diff --git a/.cargo/config.toml b/.cargo/config.toml new file mode 100644 index 000000000..9741f113e --- /dev/null +++ b/.cargo/config.toml @@ -0,0 +1,2 @@ +[alias] +xtask = "run --quiet --package xtask --" diff --git a/.gitattributes b/.gitattributes index 02be72507..e06f16ef0 100644 --- a/.gitattributes +++ b/.gitattributes @@ -1,6 +1,4 @@ +# The repository is text-only by policy (see docs/asset-policy.md). * text=auto eol=lf -*.ps1 text eol=crlf *.cmd text eol=crlf -*.sln text eol=crlf - -*.bat text eol=crlf +*.ps1 text eol=crlf diff --git a/.githooks/pre-commit b/.githooks/pre-commit new file mode 100644 index 000000000..1b89c975a --- /dev/null +++ b/.githooks/pre-commit @@ -0,0 +1,3 @@ +#!/bin/sh +# Enforces the asset policy on every commit. Install with: cargo xtask install-hooks +exec cargo xtask policy --staged diff --git a/.github/ISSUE_TEMPLATE/bug_report.yml b/.github/ISSUE_TEMPLATE/bug_report.yml deleted file mode 100644 index 7a0292677..000000000 --- a/.github/ISSUE_TEMPLATE/bug_report.yml +++ /dev/null @@ -1,63 +0,0 @@ -name: Bug report -description: The build stops, a tool fails, or a shader or asset comes out wrong. -labels: [bug] -body: - - type: markdown - attributes: - value: | - Search open and closed issues for the error text first, and comment there if it is already reported. - **Never attach game files**, extracted assets or generated shaders (DXBC, FSSM, disassembly, SPIR-V), and - don't paste more than a few lines of them. Only version 1.0.2.1 of your own Xbox Series package is - supported; issues about obtaining the game are closed. - - type: input - id: summary - attributes: - label: What happens - description: One sentence, with the exact error text if there is one. - validations: - required: true - - type: input - id: commit - attributes: - label: Commit - description: The commit you built from (`git rev-parse --short HEAD`), or the date you downloaded it. - validations: - required: true - - type: input - id: system - attributes: - label: System - description: OS, CPU, GPU and driver version, and the Python, LLVM and Vulkan SDK versions if the build failed. - placeholder: Windows 11 24H2, Ryzen 5 7600, RX 7800 XT (Adrenalin 25.10.1), Python 3.12.7, LLVM 21.1.8, Vulkan SDK 1.4.328 - validations: - required: true - - type: dropdown - id: stage - attributes: - label: Where - options: - - Finding the game (--find) - - check - - shaders - - assets - - runtime - - pipelines - - Running gta6rt - - A tool run by hand (tools/, scripts/) - validations: - required: true - - type: textarea - id: command - attributes: - label: Command and steps - description: How you started it (`Build.bat` or the exact `make_game.py` command) and whether it happens every time. - validations: - required: true - - type: textarea - id: output - attributes: - label: Output - description: The last lines the console printed, from the stage that failed down to the error. - render: text - validations: - required: true diff --git a/.github/ISSUE_TEMPLATE/config.yml b/.github/ISSUE_TEMPLATE/config.yml deleted file mode 100644 index 941dd79c8..000000000 --- a/.github/ISSUE_TEMPLATE/config.yml +++ /dev/null @@ -1,5 +0,0 @@ -blank_issues_enabled: true -contact_links: - - name: How to build - url: https://github.com/ubiquitarianism/leonida#how-to-build - about: Prerequisites, Build.bat and the make_game.py options diff --git a/.github/dependabot.yml b/.github/dependabot.yml deleted file mode 100644 index 41fd7264f..000000000 --- a/.github/dependabot.yml +++ /dev/null @@ -1,22 +0,0 @@ -# Weekly update PRs, one at a time, grouped so a week's bumps come as a single PR that CI checks. -version: 2 -updates: - - package-ecosystem: github-actions - directory: / - schedule: - interval: weekly - groups: - actions: - patterns: ["*"] - commit-message: - prefix: ci - open-pull-requests-limit: 1 - - # third_party/rpf9-explorer: CI builds rpf9dump against the new commit before it is merged. - - package-ecosystem: gitsubmodule - directory: / - schedule: - interval: weekly - commit-message: - prefix: deps - open-pull-requests-limit: 1 diff --git a/.github/pull_request_template.md b/.github/pull_request_template.md deleted file mode 100644 index 8eca32651..000000000 --- a/.github/pull_request_template.md +++ /dev/null @@ -1,27 +0,0 @@ -Claimed in the coordination issue as: - -Depends on: - -Fixes: - -### What and why - - - -### Tested - - - -GPUs tested: - -AI-assisted: - -### Checklist - -- [ ] Based on current `main` and merges cleanly (a conflicting pull request is labeled `needs rebase`). -- [ ] One topic; follow-up work goes in a new pull request. -- [ ] No game data, keys or decryption (CONTRIBUTING.md), including in logs or reports quoted here. -- [ ] A new translator rule is in the contract table of `docs/design.md`, with how it was confirmed. diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 273be0170..80e6a359e 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -1,329 +1,33 @@ name: CI + on: - workflow_call: - workflow_dispatch: + pull_request: + push: + branches: [main] permissions: contents: read concurrency: - # Coalesce superseded pending pushes per branch without canceling an active main build. - group: ci-${{ github.event_name }}-${{ github.event.pull_request.number || (github.event_name == 'push' && github.ref) || github.run_id }} - cancel-in-progress: ${{ github.event_name == 'pull_request' }} + group: ci-${{ github.ref }} + cancel-in-progress: true env: - PYTEST_FILE_MARKERS: '^import pytest|^ *HAVE_NUMPY =' + CARGO_TERM_COLOR: always jobs: - change-scope: - if: github.event_name == 'pull_request' - runs-on: ubuntu-latest - timeout-minutes: 5 - outputs: - docs-only: ${{ steps.paths.outputs.docs-only }} - steps: - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - with: - fetch-depth: 2 - persist-credentials: false - - name: Check whether only documentation changed - id: paths - shell: pwsh - run: | - # A pull_request checkout is the test merge; its first parent is the PR base. - # Treat missing history, an empty diff, and renames out of code conservatively. - $PSNativeCommandUseErrorActionPreference = $false - $docsOnly = $false - git diff --quiet "$env:GITHUB_SHA^1" "$env:GITHUB_SHA" -- - if ($LASTEXITCODE -eq 1) { - git diff --quiet --no-renames "$env:GITHUB_SHA^1" "$env:GITHUB_SHA" -- . ` - ':(exclude,top)README.md' ':(exclude,top)CONTRIBUTING.md' ` - ':(exclude,top)AGENTS.md' ':(exclude,top,glob)docs/**/*.md' - $docsOnly = $LASTEXITCODE -eq 0 - } - "docs-only=$($docsOnly.ToString().ToLowerInvariant())" >> $env:GITHUB_OUTPUT - exit 0 # GitHub's pwsh wrapper would otherwise forward git diff's status. - # A docs-only diff still needs the tests that read those documents, because `check` is skipped for it: every - # tests/test_docs_*.py (links, the design.md contract rows, list items, the repository paths a document - # names) and the i18n index, which checks docs/i18n/README.md. All are standard library only and read only - # tracked files. tests/test_ci_registration.py fails when a tests/test_docs_*.py is not run here. - - name: Check documentation when only documentation changed - if: steps.paths.outputs.docs-only == 'true' - run: | - for t in tests/test_docs_*.py tests/test_i18n_index.py; do - echo "== $t" - python3 -I "$t" || exit 1 - done - check: - needs: change-scope - if: >- - ${{ !cancelled() && (needs.change-scope.result == 'skipped' - || needs.change-scope.outputs.docs-only != 'true') }} runs-on: windows-latest - # The standard-library loop alone took 840 to 868 s in four runs on 24 November 2026, before the builds below. - timeout-minutes: 30 - steps: - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - with: - submodules: recursive - - uses: actions/setup-python@6d4fd22b20465ccc0f7354476588e8df7c9ca0e0 # v7.1.0 - with: - python-version: "3.12" - - uses: actions/setup-dotnet@0f4a354dd5547a28c70b7853dbd95d5b67886e73 # v6.1.0 - with: - dotnet-version: "8.0.x" - cache: true - cache-dependency-path: "**/packages.lock.json" - - name: Python tools compile - run: python -m compileall -q make_game.py tools tests - - name: make_game.py help - run: python -I make_game.py --help - - name: Tests (standard library only, no game data) - shell: bash - run: | - # Run every file, then fail: stopping at the first failure would hide the files after it. - failed=() - while IFS= read -r t; do - if grep -Eq "$PYTEST_FILE_MARKERS" "$t" || ! grep -q '__main__' "$t"; then - continue - fi - echo "== $t" - python -I "$t" || failed+=("$t") - done < <(find tests -path 'tests/semantic' -prune -o -type f -name 'test_*.py' -print | LC_ALL=C sort) # pytest-based files run in the translator-tests job - if (( ${#failed[@]} )); then - for t in "${failed[@]}"; do echo "::error file=$t::$t failed"; done - exit 1 - fi - - name: Build rpf9dump - run: dotnet build tools/rpf9dump/rpf9dump.csproj -c Release - - name: Test TTPF export retry - env: - RPF9DUMP_DLL: tools/rpf9dump/bin/Release/net8.0/rpf9dump.dll - run: python -I tests/test_ttpf_export_resume.py - # The standard-library loop above runs this file before rpf9dump is built, where it skips for lack of the DLL. - - name: Test rpf9dump exit codes - env: - RPF9DUMP_DLL: tools/rpf9dump/bin/Release/net8.0/rpf9dump.dll - run: python -I tests/test_rpf9dump_exit_codes.py - - name: Build the calibrated BCPack reader and test the texture pipeline - env: - RPF9DUMP_DLL: tools/rpf9dump/bin/Release/net8.0/rpf9dump.dll - shell: bash - run: | - python -m pip install -c tests/requirements.txt numpy - CARGO_HOME="$(mktemp -d)" cargo build --release --locked --offline --manifest-path tools/bcpack_calibration/Cargo.toml - python -I -c "import sys; sys.path.insert(0, 'tools'); import calibrated_texture; calibrated_texture.native()" - python -I tests/test_calibrated_texture.py - python -I tests/test_ttpf_assets.py - - name: Test rpf9dump diagnostics - run: dotnet run --project tests/Rpf9DumpDiagnostics/Rpf9DumpDiagnostics.csproj -c Release - translator-tests: - needs: change-scope - if: >- - ${{ !cancelled() && (needs.change-scope.result == 'skipped' - || needs.change-scope.outputs.docs-only != 'true') }} - runs-on: ubuntu-24.04 - timeout-minutes: 15 - steps: - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - - uses: actions/setup-python@6d4fd22b20465ccc0f7354476588e8df7c9ca0e0 # v7.1.0 - with: - python-version: "3.12" - cache: "pip" - cache-dependency-path: tests/requirements.txt - - name: Install llvm-mc (LLVM 21) and spirv-tools - shell: bash - run: | - # The signing key is checked against apt.llvm.org's published fingerprint before apt trusts it. - key=$(mktemp) - curl -fsSL -o "$key" https://apt.llvm.org/llvm-snapshot.gpg.key - python3 -I scripts/check_apt_key.py "$key" 6084F3CF814B57C1CF12EFD515CF4D18AF4F7421 - sudo gpg --dearmor -o /usr/share/keyrings/llvm-snapshot.gpg "$key" - echo "deb [signed-by=/usr/share/keyrings/llvm-snapshot.gpg] https://apt.llvm.org/noble/ llvm-toolchain-noble-21 main" | sudo tee /etc/apt/sources.list.d/llvm-21.list > /dev/null - sudo apt-get update - sudo apt-get install -y --no-install-recommends llvm-21 spirv-tools - pip install -r tests/requirements.txt - LLVM_MC=/usr/lib/llvm-21/bin/llvm-mc - echo "LLVM_MC=$LLVM_MC" >> "$GITHUB_ENV" - version_out=$("$LLVM_MC" --version) - printf '%s\n' "$version_out" - grep -q 'LLVM version 21\.' <<< "$version_out" - grep -q 'amdgcn' <<< "$version_out" - - name: Translator tests - shell: bash - run: | - pytest_files=() - while IFS= read -r t; do - if grep -Eq "$PYTEST_FILE_MARKERS" "$t" || ! grep -q '__main__' "$t"; then - pytest_files+=("$t") - elif [[ "$t" == tests/test_tex_headers.py ]]; then - pytest_files+=("$t::TestTextureDescriptorParsing::test_stdlib_qword_scanner_edge_cases_and_parity") - fi - done < <(find tests -path 'tests/semantic' -prune -o -type f -name 'test_*.py' -print | LC_ALL=C sort) - python -m pytest "${pytest_files[@]}" -q - semantic-tests: - needs: change-scope - if: >- - ${{ !cancelled() && (needs.change-scope.result == 'skipped' - || needs.change-scope.outputs.docs-only != 'true') }} - runs-on: ${{ matrix.os }} - # The Windows leg ran 513 s to its failure and was cancelled at 597 s and 599 s on 24 November 2026; the Linux - # leg takes 169 to 299 s. - timeout-minutes: 20 - strategy: - matrix: - # Pull requests run the Linux leg only: in 914 sampled pull request runs the Windows leg never failed while the - # Linux leg passed, and it took about 14% of the account's runner time. Pushes to main and workflow_dispatch - # run both legs. - os: ${{ fromJSON(github.event_name == 'pull_request' && '["ubuntu-latest"]' || '["windows-latest", "ubuntu-latest"]') }} - steps: - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - - uses: actions/setup-python@6d4fd22b20465ccc0f7354476588e8df7c9ca0e0 # v7.1.0 - with: - python-version: "3.12" - # Some semantic tests assemble and validate the translator's output with spirv-as / spirv-val and skip without - # them (test_fma_khr, test_bary_fallback, test_image_coherent...). The runner images have neither, so a skip - # here reads as a pass. The Linux leg installs SPIRV-Tools and LEONIDA_REQUIRE_SPIRV_TOOLS=1 makes - # tests/semantic/test_spirv_tools_required.py fail when they are missing, so those tests cannot go quiet again. - # The Windows leg has no SPIRV-Tools and still skips them. - - name: Install SPIRV-Tools - if: runner.os == 'Linux' - shell: bash - run: | - sudo apt-get update - sudo apt-get install -y --no-install-recommends spirv-tools - spirv-as --version - spirv-val --version - - name: Translator semantic tests - env: - LEONIDA_REQUIRE_SPIRV_TOOLS: ${{ runner.os == 'Linux' && '1' || '0' }} - run: python -I scripts/run_semantic_tests.py tests/semantic -v - - # The Python suites on an Apple Silicon Mac: the standard-library loop of the check job, the translator semantic - # tests and the pytest files of the translator-tests job, with Homebrew's llvm-mc and SPIRV-Tools. macos-26, not - # macos-15: the Homebrew bottles cover Sequoia and later, but the runtime needs Xcode 26's libc++ (runtime.yml). - macos-python: - needs: change-scope - if: >- - ${{ !cancelled() && (needs.change-scope.result == 'skipped' - || needs.change-scope.outputs.docs-only != 'true') }} - runs-on: macos-26 - # The semantic suite and the standard-library loop took 1064 s on 24 November 2026, and the job was cancelled at - # 20 minutes, 87 s into the pytest step. - timeout-minutes: 40 - env: - HOMEBREW_NO_AUTO_UPDATE: "1" - HOMEBREW_NO_INSTALL_CLEANUP: "1" - steps: - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - with: - persist-credentials: false - - uses: actions/setup-python@6d4fd22b20465ccc0f7354476588e8df7c9ca0e0 # v7.1.0 - with: - python-version: "3.12" - cache: "pip" - cache-dependency-path: tests/requirements.txt - - name: Python tools compile - run: python -m compileall -q make_game.py tools tests - - name: make_game.py help - run: python -I make_game.py --help - # Before anything is installed, as in the check job, so these files stay standard library only. The semantic - # suite runs alongside the loop, on another of the runner's three cores; together they take about 6 minutes. - - name: Translator semantic tests and tests (standard library only, no game data) - shell: bash - run: | - python -m unittest discover -s tests/semantic > "$RUNNER_TEMP/semantic.log" 2>&1 & - semantic=$! - # Run every file, then fail, as the check job does: the annotations then name each failed file. - failed=() - while IFS= read -r t; do - if grep -Eq "$PYTEST_FILE_MARKERS" "$t" || ! grep -q '__main__' "$t"; then - continue - fi - echo "== $t" - python -I "$t" || failed+=("$t") - done < <(find tests -path 'tests/semantic' -prune -o -type f -name 'test_*.py' -print | LC_ALL=C sort) - status=0 - wait "$semantic" || status=$? - echo "== tests/semantic" - cat "$RUNNER_TEMP/semantic.log" - if (( ${#failed[@]} )); then - for t in "${failed[@]}"; do echo "::error file=$t::$t failed"; done - exit 1 - fi - exit "$status" - - name: Install llvm-mc and SPIRV-Tools - run: | - brew install llvm spirv-tools - pip install -r tests/requirements.txt - LLVM_MC="$(brew --prefix llvm)/bin/llvm-mc" # keg-only: not on PATH - echo "LLVM_MC=$LLVM_MC" >> "$GITHUB_ENV" - "$LLVM_MC" --version | grep -E 'LLVM version|amdgcn' - - name: Translator tests (pytest) - shell: bash - run: | - pytest_files=() - while IFS= read -r t; do - if grep -Eq "$PYTEST_FILE_MARKERS" "$t" || ! grep -q '__main__' "$t"; then - pytest_files+=("$t") - elif [[ "$t" == tests/test_tex_headers.py ]]; then - pytest_files+=("$t::TestTextureDescriptorParsing::test_stdlib_qword_scanner_edge_cases_and_parity") - fi - done < <(find tests -path 'tests/semantic' -prune -o -type f -name 'test_*.py' -print | LC_ALL=C sort) - python -m pytest "${pytest_files[@]}" -q - - viewer-tests: - needs: change-scope - if: >- - ${{ !cancelled() && (needs.change-scope.result == 'skipped' - || needs.change-scope.outputs.docs-only != 'true') }} - runs-on: ubuntu-latest - timeout-minutes: 10 - steps: - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - - uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0 - with: - node-version: "24" - - name: Viewer chunk streaming (synthetic, no browser or game data) - run: node --test tests/test_*.cjs - - # The check job runs the standard-library loop on Windows, which has no SPIRV-Tools or numpy: the spirv-val checks - # (test_split_big_switch, test_image_load_typed...), the numpy paths and the POSIX-only tests skip there. This job - # runs the same loop on Linux with them installed, so those tests run somewhere. - stdlib-tests-linux: - needs: change-scope - if: >- - ${{ !cancelled() && (needs.change-scope.result == 'skipped' - || needs.change-scope.outputs.docs-only != 'true') }} - runs-on: ubuntu-24.04 - timeout-minutes: 15 + timeout-minutes: 60 steps: - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - - uses: actions/setup-python@6d4fd22b20465ccc0f7354476588e8df7c9ca0e0 # v7.1.0 - with: - python-version: "3.12" - cache: "pip" - cache-dependency-path: tests/requirements.txt - - name: Install SPIRV-Tools and numpy - shell: bash - run: | - sudo apt-get update - sudo apt-get install -y --no-install-recommends spirv-tools - pip install -r tests/requirements.txt - - name: Tests (standard library only, Linux) - shell: bash - run: | - # Run every file, then fail, as the check job does: the annotations then name each failed file. - failed=() - while IFS= read -r t; do - if grep -Eq "$PYTEST_FILE_MARKERS" "$t" || ! grep -q '__main__' "$t"; then - continue - fi - echo "== $t" - python -I "$t" || failed+=("$t") - done < <(find tests -path 'tests/semantic' -prune -o -type f -name 'test_*.py' -print | LC_ALL=C sort) - if (( ${#failed[@]} )); then - for t in "${failed[@]}"; do echo "::error file=$t::$t failed"; done - exit 1 - fi + - uses: actions/checkout@v5 + # The version and components pinned in rust-toolchain.toml. + - run: rustup toolchain install + - uses: Swatinem/rust-cache@v2 + - name: Clippy + run: cargo clippy --workspace --all-targets --locked -- -D warnings + - name: Clippy, diagnostics build + run: cargo clippy --workspace --all-targets --all-features --locked -- -D warnings + # Includes xtask's repository_passes_policy, the asset-policy check. + - name: Tests + run: cargo test --workspace --locked diff --git a/.github/workflows/conflict-label.yml b/.github/workflows/conflict-label.yml deleted file mode 100644 index f4d48c4f2..000000000 --- a/.github/workflows/conflict-label.yml +++ /dev/null @@ -1,41 +0,0 @@ -name: Needs rebase label - -# Labels the open pull requests that conflict with main `needs rebase` and unlabels them once they merge again -# (tools/pr_conflict_label.py). A push to main can make any open pull request conflict, so it checks all of them; a -# push to a pull request checks that one; the hourly run catches merges GitHub had not computed yet. -# -# pull_request_target gives a fork's pull request a token that can write labels. That is safe only because this job -# checks out main, never the pull request, and the tool reads nothing but the GitHub API: no pull request code runs. -on: - push: - branches: [main] - pull_request_target: - types: [opened, reopened, synchronize] - schedule: - - cron: '17 * * * *' - workflow_dispatch: - -permissions: {} - -concurrency: - group: conflict-label-${{ github.event.pull_request.number || 'all' }} - cancel-in-progress: false - -jobs: - label: - runs-on: ubuntu-24.04 - timeout-minutes: 15 - permissions: - contents: read - pull-requests: write - steps: - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - with: - ref: ${{ github.event.repository.default_branch }} - persist-credentials: false - fetch-depth: 1 - - name: Label conflicting pull requests - env: - GITHUB_TOKEN: ${{ github.token }} - PR: ${{ github.event.pull_request.number }} - run: python3 -I tools/pr_conflict_label.py --repo "$GITHUB_REPOSITORY" ${PR:+--pr "$PR"} diff --git a/.github/workflows/jactionlint.yml b/.github/workflows/jactionlint.yml deleted file mode 100644 index 0e0ed1e5c..000000000 --- a/.github/workflows/jactionlint.yml +++ /dev/null @@ -1,32 +0,0 @@ -name: jactionlint - -on: - push: - branches: [main] - paths: ['.github/**'] - pull_request: - paths: ['.github/**'] - workflow_dispatch: - -permissions: {} - -concurrency: - # Coalesce superseded pending pushes per branch without canceling an active main build. - group: jactionlint-${{ github.event_name }}-${{ github.event.pull_request.number || (github.event_name == 'push' && github.ref) || github.run_id }} - cancel-in-progress: ${{ github.event_name == 'pull_request' }} - -jobs: - jactionlint: - runs-on: ubuntu-24.04 - timeout-minutes: 10 - permissions: - contents: read - steps: - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - with: - persist-credentials: false - # `correctness` checks workflow syntax, expressions, shellcheck, and dependabot.yml; - # switch to `default` once all workflows declare timeouts and concurrency. - - uses: jdx/jactionlint@72c00452809bcca05b8bc12acdcf15dd7a9c1c5e # v2.6.0 - with: - profile: correctness diff --git a/.github/workflows/leonida-legacy-ci.yml b/.github/workflows/leonida-legacy-ci.yml deleted file mode 100644 index 33c48b1b3..000000000 --- a/.github/workflows/leonida-legacy-ci.yml +++ /dev/null @@ -1,180 +0,0 @@ -# Single entry point for ProjectLeonidaL: quick guard checks, then the full CI and Runtime reusable workflows. -# GitHub sometimes shows only the small guard workflows until every workflow file is approved under Actions; -# this workflow is the one to watch for Python tests, translator suite, and Windows/Wine/macOS runtime builds. -name: Leonida Legacy CI - -on: - push: - branches: [main] - pull_request: - workflow_dispatch: - -permissions: - contents: read - -concurrency: - group: leonida-legacy-ci-${{ github.event_name }}-${{ github.event.pull_request.number || (github.event_name == 'push' && github.ref) || github.run_id }} - cancel-in-progress: ${{ github.event_name == 'pull_request' }} - -jobs: - scope: - name: Scope - runs-on: ubuntu-24.04 - timeout-minutes: 5 - outputs: - docs-only: ${{ steps.docs.outputs.docs-only }} - run-runtime: ${{ steps.runtime.outputs.run-runtime }} - steps: - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - with: - fetch-depth: ${{ github.event_name == 'pull_request' && 2 || 1 }} - persist-credentials: false - - name: Docs-only scope (matches ci.yml change-scope) - id: docs - shell: pwsh - run: | - $docsOnly = $false - if ($env:GITHUB_EVENT_NAME -eq 'pull_request') { - git diff --quiet "$env:GITHUB_SHA^1" "$env:GITHUB_SHA" -- - if ($LASTEXITCODE -eq 1) { - git diff --quiet --no-renames "$env:GITHUB_SHA^1" "$env:GITHUB_SHA" -- . ` - ':(exclude,top)README.md' ':(exclude,top)CONTRIBUTING.md' ` - ':(exclude,top)AGENTS.md' ':(exclude,top,glob)docs/**/*.md' - $docsOnly = $LASTEXITCODE -eq 0 - } - } - "docs-only=$($docsOnly.ToString().ToLowerInvariant())" >> $env:GITHUB_OUTPUT - exit 0 - - name: Runtime-related paths (pull requests) - if: github.event_name == 'pull_request' - uses: dorny/paths-filter@de90cc6fb38fc0963ad72b210f1f284cd68cea36 # v3.0.2 - id: paths - with: - filters: | - runtime: - - runtime/** - - third_party/** - - scripts/** - - .github/workflows/runtime.yml - - .github/workflows/leonida-legacy-ci.yml - - .gitattributes - - tools/hw_oracle/** - - tools/bary_fallback_gs.py - - tools/cf_diff.py - - tools/cf_ref.py - - tools/cfg_structure.py - - tools/cpu_ref.py - - tools/f32_fuzz.py - - tools/first_light.py - - tools/fspx_unpack.py - - tools/fssm_header.py - - tools/fssm_unpack.py - - tools/gen_d3d12_stubs.py - - tools/gfx10_formats.json - - tools/lane_masks.py - - tools/mc_command.py - - tools/mesh_compute_vs.py - - tools/rdna2spirv.py - - tools/replace_retry.py - - tools/report_paths.py - - tools/shader_carve.py - - tools/shader_disasm.py - - tools/shader_ir.py - - tools/shader_meta.py - - tools/shader_stage_manifest.py - - tools/spirv_asm.py - - tools/spirv_asm_tables.py - - tools/spirv_opt.py - - tools/spirv_stubs.py - - tools/vk_subgroup_info.py - - tools/wave64_emulate_opt.py - - tools/wave64_halves.py - - tools/xdxr_bvh.py - - name: Whether to run Runtime - id: runtime - shell: bash - run: | - if [ "${{ github.event_name }}" = push ]; then - echo "run-runtime=true" >> "$GITHUB_OUTPUT" - elif [ "${{ steps.paths.outputs.runtime }}" = true ]; then - echo "run-runtime=true" >> "$GITHUB_OUTPUT" - else - echo "run-runtime=false" >> "$GITHUB_OUTPUT" - fi - - guard: - name: Quick guard - needs: scope - runs-on: ubuntu-24.04 - timeout-minutes: 10 - steps: - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - with: - persist-credentials: false - fetch-depth: 1 - - uses: actions/setup-python@6d4fd22b20465ccc0f7354476588e8df7c9ca0e0 # v7.1.0 - with: - python-version: "3.12" - - name: Python tools compile - run: python -m compileall -q make_game.py tools tests - - name: make_game.py help - run: python -I make_game.py --help - - name: Docs and i18n - run: | - for t in tests/test_docs_*.py tests/test_i18n_index.py; do - echo "== $t" - python -I "$t" || exit 1 - done - - name: No game data tracked - shell: bash - run: | - bad=$(git ls-files -z | grep -ziE '\.(rpf|ttpf|xvd|msixvc|dxbc|fssm|spv|spvasm|dds|bk2|awc|r9modeldata|obj|glb|ogg|wav|exe|dll)$' | tr '\0' '\n' || true) - if [ -n "$bad" ]; then - echo "Game or binary files tracked:" - echo "$bad" - exit 1 - fi - - name: No game data under another name - run: python -I scripts/check_no_game_data.py - - docs-only-checks: - name: Docs-only CI - needs: scope - if: github.event_name == 'pull_request' && needs.scope.outputs.docs-only == 'true' - runs-on: ubuntu-24.04 - timeout-minutes: 10 - steps: - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - with: - persist-credentials: false - - uses: actions/setup-python@6d4fd22b20465ccc0f7354476588e8df7c9ca0e0 # v7.1.0 - with: - python-version: "3.12" - - name: Check documentation when only documentation changed - run: | - for t in tests/test_docs_*.py tests/test_i18n_index.py; do - echo "== $t" - python3 -I "$t" || exit 1 - done - - ci: - name: Python / translator CI - needs: [scope, guard] - if: >- - !cancelled() && needs.guard.result == 'success' && - (github.event_name != 'pull_request' || needs.scope.outputs.docs-only != 'true') - uses: ./.github/workflows/ci.yml - permissions: - contents: read - - # tests/test_runtime_paths.py reads the pull_request path list from the scope job's paths-filter (runtime: block). - runtime: - name: Runtime and GPU - needs: [scope, guard] - if: >- - !cancelled() && needs.guard.result == 'success' && - needs.scope.outputs.run-runtime == 'true' && - (github.event_name != 'pull_request' || needs.scope.outputs.docs-only != 'true') - uses: ./.github/workflows/runtime.yml - permissions: - contents: read \ No newline at end of file diff --git a/.github/workflows/no-game-data.yml b/.github/workflows/no-game-data.yml deleted file mode 100644 index 89cf28d95..000000000 --- a/.github/workflows/no-game-data.yml +++ /dev/null @@ -1,35 +0,0 @@ -name: No Game Data -on: - push: - branches: [main] - pull_request: - workflow_dispatch: - -concurrency: - # Coalesce superseded pending pushes per branch without canceling an active main build. - group: no-game-data-${{ github.event_name }}-${{ github.event.pull_request.number || (github.event_name == 'push' && github.ref) || github.run_id }} - cancel-in-progress: ${{ github.event_name == 'pull_request' }} - -permissions: {} - -jobs: - no-game-data: - runs-on: ubuntu-24.04 - timeout-minutes: 5 - permissions: - contents: read - steps: - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - with: - persist-credentials: false - fetch-depth: 1 - - name: No game data tracked - run: | - bad=$(git ls-files -z | grep -ziE '\.(rpf|ttpf|xvd|msixvc|dxbc|fssm|spv|spvasm|dds|bk2|awc|r9modeldata|obj|glb|ogg|wav|exe|dll)$' | tr '\0' '\n' || true) - if [ -n "$bad" ]; then - echo "Game or binary files tracked:" - echo "$bad" - exit 1 - fi - - name: No game data under another name - run: python3 -I scripts/check_no_game_data.py diff --git a/.github/workflows/runtime.yml b/.github/workflows/runtime.yml deleted file mode 100644 index 7d32ef22b..000000000 --- a/.github/workflows/runtime.yml +++ /dev/null @@ -1,539 +0,0 @@ -# Builds the loader (runtime/) with MSVC and Vulkan headers (plus GPU tools and llvmpipe tests on Linux, and MoltenVK -# tests on a Mac) on runtime or translator changes, so a change that breaks the C++ build or tests shows up in CI. -name: Runtime - -on: - # What can break this build: the runtime and its vendored queue, the scripts the jobs run, this workflow, the - # line endings every checkout gets (.gitattributes), and everything the tools those scripts read depend on - - # their sibling imports, the data files they load by name (gfx10_formats.json is one a .py-only scan misses) and - # the hw_oracle directory. Any other file under tools/ used to start a full Windows and Wine build it cannot break - # (BUILD-856); paths-ignore cannot say "everything under tools/ except these", so the event lists what triggers - # it. tests/test_runtime_paths.py recomputes the tools/ part and fails when an entry is missing; keep the two - # lists identical. - # Push to main and pull requests are routed through leonida-legacy-ci.yml (unfiltered main, path filter on PR). - # tests/test_runtime_paths.py reads the pull_request path list from that workflow's paths-filter block. - workflow_call: - workflow_dispatch: - -permissions: - contents: read - -concurrency: - # Coalesce superseded pending pushes per branch without canceling an active main build. - group: runtime-${{ github.event_name }}-${{ github.event.pull_request.number || (github.event_name == 'push' && github.ref) || github.run_id }} - cancel-in-progress: ${{ github.event_name == 'pull_request' }} - -jobs: - windows: - runs-on: windows-latest - # With a warm sccache the whole job took 291 s (run 45442389069). With a cold one (0 hits, 385 misses) the build - # alone was still running after 19 minutes in run 45452312472 (24 November 2026): the 20-minute limit cancelled - # the job, and both wine jobs were skipped with it. - timeout-minutes: 45 - outputs: - wine-artifact: ${{ steps.upload-wine-artifact.outcome }} - env: - SCCACHE_GHA_ENABLED: "true" - steps: - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - - uses: actions/setup-python@6d4fd22b20465ccc0f7354476588e8df7c9ca0e0 # v7.1.0 - with: - python-version: "3.12" - - name: Set up MSVC x64 developer environment - shell: pwsh - run: | - $installer = Join-Path ${env:ProgramFiles(x86)} 'Microsoft Visual Studio\Installer' - $vswhere = Join-Path $installer 'vswhere.exe' - if (!(Test-Path -LiteralPath $vswhere -PathType Leaf)) { - throw "vswhere.exe not found at $vswhere" - } - $vs = & $vswhere -latest -products * -requires Microsoft.VisualStudio.Component.VC.Tools.x86.x64 -property installationPath | Select-Object -First 1 - if ([string]::IsNullOrWhiteSpace($vs)) { - $vs = & $vswhere -latest -prerelease -products * -requires Microsoft.VisualStudio.Component.VC.Tools.x86.x64 -property installationPath | Select-Object -First 1 - } - if ([string]::IsNullOrWhiteSpace($vs)) { - throw 'Visual Studio with Microsoft.VisualStudio.Component.VC.Tools.x86.x64 was not found' - } - $vcvars = Join-Path $vs.Trim() 'VC\Auxiliary\Build\vcvars64.bat' - if (!(Test-Path -LiteralPath $vcvars -PathType Leaf)) { - throw "vcvars64.bat not found at $vcvars" - } - - $before = @{} - foreach ($e in Get-ChildItem Env:) { - $before[$e.Name.ToUpperInvariant()] = $e.Value - } - - $dump = Join-Path $env:RUNNER_TEMP 'vcvars-env.json' - $cmd = Join-Path $env:RUNNER_TEMP 'run-vcvars.cmd' - $origPath = $env:PATH - $hadInstaller = @(($origPath -split ';') | Where-Object { $_.TrimEnd('\') -ieq $installer.TrimEnd('\') }).Count -gt 0 - $env:PATH = "$origPath;$installer" - $env:LEONIDA_VCVARS_DUMP = $dump - try { - $batch = @( - '@echo off' - 'chcp 65001 >nul' - "call `"$vcvars`" || exit /b 1" - 'where cl.exe || exit /b 1' - 'pwsh -NoProfile -Command "[Environment]::GetEnvironmentVariables() | ConvertTo-Json -Compress | Set-Content -LiteralPath $env:LEONIDA_VCVARS_DUMP -Encoding utf8" || exit /b 1' - ) -join "`r`n" - [System.IO.File]::WriteAllText($cmd, "$batch`r`n", [System.Text.UTF8Encoding]::new($false)) - & cmd.exe /d /c $cmd - if ($LASTEXITCODE -ne 0) { - throw "vcvars64.bat setup failed with exit code $LASTEXITCODE" - } - } finally { - $env:PATH = $origPath - Remove-Item Env:LEONIDA_VCVARS_DUMP -ErrorAction SilentlyContinue - Remove-Item -LiteralPath $cmd -ErrorAction SilentlyContinue - } - - $after = Get-Content -LiteralPath $dump -Raw -Encoding utf8 | ConvertFrom-Json -AsHashtable - Remove-Item -LiteralPath $dump -ErrorAction SilentlyContinue - if ($after['VSCMD_ARG_TGT_ARCH'] -ine 'x64' -or [string]::IsNullOrWhiteSpace($after['INCLUDE']) -or [string]::IsNullOrWhiteSpace($after['LIB'])) { - throw "vcvars64.bat did not initialize an x64 MSVC environment (VSCMD_ARG_TGT_ARCH='$($after['VSCMD_ARG_TGT_ARCH'])')" - } - - $pathLike = @('PATH', 'INCLUDE', 'LIB', 'LIBPATH') - $envLines = [System.Collections.Generic.List[string]]::new() - foreach ($name in ($after.Keys | Sort-Object)) { - if (!$name -or $name.StartsWith('=')) { continue } - $upper = $name.ToUpperInvariant() - if ($upper -eq 'LEONIDA_VCVARS_DUMP') { continue } - $value = [string]$after[$name] - if ($upper -in $pathLike) { - $seen = [System.Collections.Generic.HashSet[string]]::new([System.StringComparer]::OrdinalIgnoreCase) - $deduped = [System.Collections.Generic.List[string]]::new() - foreach ($entry in ($value -split ';')) { - if (!$entry) { continue } - if ($upper -eq 'PATH' -and !$hadInstaller -and ($entry.TrimEnd('\') -ieq $installer.TrimEnd('\'))) { - continue - } - if ($seen.Add($entry.TrimEnd('\'))) { - $deduped.Add($entry) - } - } - $value = $deduped -join ';' - } - if ($before.ContainsKey($upper) -and $before[$upper] -ceq $value) { continue } - if ($value -match '[\r\n]') { - $delim = "EOF_$([guid]::NewGuid().ToString('N'))" - $envLines.Add("$name<<$delim") - $envLines.Add($value) - $envLines.Add($delim) - } else { - $envLines.Add("$name=$value") - } - } - if ($envLines.Count -gt 0) { - Add-Content -LiteralPath $env:GITHUB_ENV -Value $envLines -Encoding utf8 - } - - uses: mozilla-actions/sccache-action@fc920bf0ec8de6ee65d409111f7ec508035751ba # v0.0.11 - - name: Cache Vulkan headers - id: vulkan-headers-cache - uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 - with: - path: .vulkan-headers/include - key: vulkan-headers-6802bb4733b63ed5efd3adb308a6c885ef180ea1 - - name: Checkout Vulkan headers (vulkan-sdk-1.4.363.0) - if: steps.vulkan-headers-cache.outputs.cache-hit != 'true' - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - with: - repository: KhronosGroup/Vulkan-Headers - ref: 6802bb4733b63ed5efd3adb308a6c885ef180ea1 # vulkan-sdk-1.4.363.0 - path: .vulkan-headers - sparse-checkout: include - persist-credentials: false - - name: Install glslang for D3D12 test shaders - shell: pwsh - run: | - $version = '16.6.0' - $release = "glslang-$version-windows-x86_64-release.zip" - $archive = Join-Path $env:RUNNER_TEMP $release - $destination = Join-Path $env:RUNNER_TEMP "glslang-$version" - Invoke-WebRequest -Uri "https://github.com/KhronosGroup/glslang/releases/download/$version/$release" -OutFile $archive - $expectedHash = '82bf434e69b9bb4829de7e2b4bc2c5e7a7861e53d66cf75e5cc70f5f694a8d9b' - if ((Get-FileHash -Algorithm SHA256 -LiteralPath $archive).Hash -ne $expectedHash) { - throw "Unexpected SHA-256 for $release" - } - Expand-Archive -LiteralPath $archive -DestinationPath $destination - $bin = Join-Path $destination 'bin' - # FindVulkan and the runtime fallback look for the legacy executable name. - Copy-Item -LiteralPath (Join-Path $bin 'glslang.exe') -Destination (Join-Path $bin 'glslangValidator.exe') - Add-Content -LiteralPath $env:GITHUB_PATH -Value $bin -Encoding utf8 - - name: Configure - env: - VULKAN_SDK: ${{ github.workspace }}/.vulkan-headers - run: >- - cmake -S runtime -B runtime/build -G Ninja - -DCMAKE_BUILD_TYPE=RelWithDebInfo - -DLEONIDA_D3D12_SHIM_TESTS=ON - -DLEONIDA_REQUIRE_VULKAN=ON - -DCMAKE_CXX_COMPILER_LAUNCHER=sccache - -DCMAKE_POLICY_DEFAULT_CMP0141=NEW - -DCMAKE_MSVC_DEBUG_INFORMATION_FORMAT=Embedded - - name: Build - run: cmake --build runtime/build - - name: Verify the descriptor test shaders - shell: pwsh - run: | - $shaders = @( - 'LEONIDA_TEST_CS_SAMPLE_SPV', 'LEONIDA_TEST_MS_FLOAT_SPV', - 'LEONIDA_TEST_MS_UINT_SPV', 'LEONIDA_TEST_MS_SINT_SPV', - 'LEONIDA_TEST_MSAA_VERT_SPV', 'LEONIDA_TEST_MSAA_FRAG_SPV' - ) - foreach ($shader in $shaders) { - $path = "runtime/build/generated/$shader.spv" - if (!(Test-Path -LiteralPath $path -PathType Leaf)) { - throw "The Windows runtime build did not compile $path" - } - } - # For the wine job: the test list, the checkout it was made in, and the built executables, DLLs and synthetic - # test shaders: the occlusion ones the tests are given as arguments, and generated/*.spv (compiled from - # runtime/test/glsl), which tests open through the absolute paths compiled into them. There is no game data - # on the runner. - - name: List tests for Wine - shell: bash - run: | - ctest --test-dir runtime/build --show-only=json-v1 > runtime/build/ctest.json - cygpath -m "$GITHUB_WORKSPACE" > runtime/build/windows-root.txt - - name: Upload the Windows build for Wine - id: upload-wine-artifact - uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 - with: - name: runtime-windows - path: | - runtime/build/**/*.exe - runtime/build/**/*.dll - runtime/build/binary_occlusion.vert.spv - runtime/build/binary_occlusion.frag.spv - runtime/build/overlapping_occlusion.vert.spv - runtime/build/overlapping_occlusion.frag.spv - runtime/build/generated/*.spv - runtime/build/ctest.json - runtime/build/windows-root.txt - retention-days: 7 - if-no-files-found: error - - name: CPU runtime tests - id: windows-cpu-tests - run: ctest --test-dir runtime/build --output-on-failure - # The job log needs a login to read; annotations do not. CTest lists the failed tests as ":". - - name: Name the failed CPU runtime tests - if: ${{ failure() && steps.windows-cpu-tests.outcome == 'failure' }} - shell: bash - run: | - tr -d '\r' < runtime/build/Testing/Temporary/LastTestsFailed.log | - sed -nE 's/^[0-9]+:(.+)$/::error::\1 failed/p' - - # Runs the Windows build's tests under Wine, so a change that breaks the loader on Linux (through Wine or Proton) - # shows up. The required ones are the loader and the stand-in game run end to end; the table in the job summary - # shows the rest. - # Two Wines: Ubuntu's own (9.0) and WineHQ's current stable, which is closer to what Proton users run. - # Not on pull requests: in 188 sampled pull request runs these two jobs never failed when the Windows job had passed, - # yet they took about a quarter of the account's 20 concurrent runner slots. They run on every push to main that - # touches these paths, and on demand from the Actions tab (workflow_dispatch). Pull requests still build and test the - # Windows runtime natively and upload runtime-windows for testers. - wine: - needs: windows - # The uploaded build can still be tested under Wine if the later native tests fail. - if: ${{ github.event_name != 'pull_request' && !cancelled() && needs.windows.outputs.wine-artifact == 'success' }} - runs-on: ubuntu-24.04 - # Ubuntu's Wine 9.0 is the slow one: in run 45410688081 (24 November 2026) its 295 tests took 616 s, the slowest - # 21 to 24 s each, against 70 s under WineHQ stable (11.0). Before the tests copied with CopyFileW and the runner - # turned winedbg off (docs/testing.md, known problems), each crashed test sat out its 120 s limit and the job - # was cancelled at 30 minutes. - timeout-minutes: 30 - strategy: - fail-fast: false - matrix: - wine: [ubuntu, winehq-stable] - name: wine (${{ matrix.wine }}) - steps: - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - - uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2 - with: - name: runtime-windows - path: runtime/build - - name: Install Wine, Xvfb and llvmpipe - env: - WINE_FLAVOUR: ${{ matrix.wine }} - run: | - pkgs=(xvfb xauth mesa-vulkan-drivers libvulkan1) - if [ "$WINE_FLAVOUR" = winehq-stable ]; then - # WineHQ's packages need the i386 architecture. https://gitlab.winehq.org/wine/wine/-/wikis/Debian-Ubuntu - sudo dpkg --add-architecture i386 - sudo mkdir -pm755 /etc/apt/keyrings - # The signing key is checked against WineHQ's published fingerprint before apt trusts it. - key=$(mktemp) - wget -q -O "$key" https://dl.winehq.org/wine-builds/winehq.key - python3 -I scripts/check_apt_key.py "$key" D43F640145369C51D786DDEA76F1A20FF987672F - sudo install -m 644 "$key" /etc/apt/keyrings/winehq-archive.key - sudo wget -q -NP /etc/apt/sources.list.d/ \ - "https://dl.winehq.org/wine-builds/ubuntu/dists/$(. /etc/os-release && echo "$VERSION_CODENAME")/winehq-$(. /etc/os-release && echo "$VERSION_CODENAME").sources" - pkgs+=(winehq-stable) - else - pkgs+=(wine wine64) - fi - sudo apt-get update - sudo apt-get install -y --no-install-recommends "${pkgs[@]}" - wine --version - - name: Windows tests under Wine - env: - WINEPREFIX: ${{ runner.temp }}/wineprefix - WINEDLLOVERRIDES: "mscoree,mshtml=" - WINEDEBUG: "-all" - run: >- - xvfb-run -a bash scripts/run_wine_session.sh - python3 -I scripts/run_wine_tests.py - --tests runtime/build/ctest.json - --windows-root "$(cat runtime/build/windows-root.txt)" - --summary "$GITHUB_STEP_SUMMARY" --label "$(wine --version)" - --require loader --require pe_loader --require loader_tls --require unimplemented_policy - --require run_tiny_game --require run_tiny_game_exit_code - # The general Wine runner skips tests driven by the Windows runner's cmake. - - name: Loaded async callbacks under Wine - env: - WINEPREFIX: ${{ runner.temp }}/wineprefix - WINEDLLOVERRIDES: "mscoree,mshtml=" - WINEDEBUG: "-all" - run: >- - xvfb-run -a cmake -DRUNNER=wine - -DLOADER="$GITHUB_WORKSPACE/runtime/build/gta6rt.exe" - -DGUEST="$GITHUB_WORKSPACE/runtime/build/fixtures/game/RelWithDebInfo/tiny_async.exe" - -P runtime/test/check_loaded_async.cmake - - # Also runs the hand-written GPU tests (runtime/test/shaders) on Mesa's llvmpipe, a software Vulkan driver, so a - # translator or harness change that breaks a test result shows up on every pull request, without a GPU. - linux-gpu-tools: - runs-on: ubuntu-24.04 - timeout-minutes: 15 - env: - SCCACHE_GHA_ENABLED: "true" - steps: - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - - uses: mozilla-actions/sccache-action@fc920bf0ec8de6ee65d409111f7ec508035751ba # v0.0.11 - - name: Cache Vulkan headers - id: vulkan-headers-cache - uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 - with: - path: .vulkan-headers/include - key: vulkan-headers-6802bb4733b63ed5efd3adb308a6c885ef180ea1 - - name: Checkout Vulkan headers (vulkan-sdk-1.4.363.0) - if: steps.vulkan-headers-cache.outputs.cache-hit != 'true' - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - with: - repository: KhronosGroup/Vulkan-Headers - ref: 6802bb4733b63ed5efd3adb308a6c885ef180ea1 # vulkan-sdk-1.4.363.0 - path: .vulkan-headers - sparse-checkout: include - persist-credentials: false - - name: Install llvmpipe, llvm-mc and SPIRV-Tools - run: | - pkgs=(libvulkan-dev mesa-vulkan-drivers vulkan-tools spirv-tools) - command -v cmake >/dev/null || pkgs+=(cmake) - command -v ninja >/dev/null || pkgs+=(ninja-build) - command -v g++ >/dev/null || pkgs+=(g++) - [ -x /usr/lib/llvm-19/bin/llvm-mc ] || pkgs+=(llvm-19) - sudo apt-get update - sudo apt-get install -y --no-install-recommends "${pkgs[@]}" - - name: Sanity check llvm-mc amdgcn target - run: /usr/lib/llvm-19/bin/llvm-mc --version | grep -q 'amdgcn' - - name: Configure - env: - VULKAN_SDK: ${{ github.workspace }}/.vulkan-headers - run: >- - cmake -S runtime -B runtime/build -G Ninja - -DCMAKE_BUILD_TYPE=RelWithDebInfo - -DCMAKE_CXX_COMPILER_LAUNCHER=sccache - -DLEONIDA_REQUIRE_VULKAN=ON - - name: Build - run: cmake --build runtime/build --parallel - - name: Check GPU tools exist - run: | - for tool in vk_harness vk_pipeline_check vk_command_replay_test vk_queue_test vk_predicate_capture_test vk_predicated_copy_test vk_compute_test vk_texture_test vk_store_test vk_bindless_test depth24_convert_test clear_color_test predicated_copy_test d3d12_state_map_test command_list_test descriptor_table_test gfx10_descriptors_test; do - if [ ! -f "runtime/build/$tool" ] && [ ! -f "runtime/build/$tool.exe" ]; then - echo "Missing: $tool" - exit 1 - fi - done - echo "All GPU tools built" - - name: CPU runtime tests (Linux) - run: ctest --test-dir runtime/build --output-on-failure - - name: Predicate and byte-copy shader validation and lifetimes - run: | - python3 -c 'import re,struct; from pathlib import Path; s=Path("runtime/src/predicate_reduce_spv.h").read_text(); w=[int(x,16) for x in re.findall(r"0x([0-9a-f]{8})u",s)]; Path("runtime/build/predicate_reduce.spv").write_bytes(struct.pack("<%dI"%len(w),*w))' - spirv-val --target-env vulkan1.1 runtime/build/predicate_reduce.spv - runtime/build/vk_predicate_capture_test - python3 -c 'import re,struct; from pathlib import Path; s=Path("runtime/src/predicated_copy_spv.h").read_text(); w=[int(x,16) for x in re.findall(r"0x([0-9a-f]{8})u",s)]; Path("runtime/build/predicated_copy.spv").write_bytes(struct.pack("<%dI"%len(w),*w))' - spirv-val --target-env vulkan1.2 runtime/build/predicated_copy.spv - runtime/build/vk_predicated_copy_test - - name: GPU tests on llvmpipe - shell: bash - env: - # Empty: add names here when an llvmpipe run still fails them; ci_expected_failures.py notices when they pass. - EXPECTED_FAILURES: - run: | - vulkaninfo --summary | grep -E 'deviceName.*llvmpipe' # fails the step if llvmpipe isn't there - set +e - python3 -I scripts/run_gpu_tests.py --build runtime/build --llvm-mc /usr/lib/llvm-19/bin/llvm-mc --work "$RUNNER_TEMP/gpu-native" 2>&1 | - tee "$RUNNER_TEMP/gpu-native.log" - status=${PIPESTATUS[0]} - set -e - sed -n '/=== GPU TEST RESULTS ===/,$p' "$RUNNER_TEMP/gpu-native.log" | awk '$1 == "FAIL" { print $2 }' > "$RUNNER_TEMP/failed.txt" - tail -n 1 "$RUNNER_TEMP/gpu-native.log" >> "$GITHUB_STEP_SUMMARY" - python3 -I scripts/ci_expected_failures.py "$RUNNER_TEMP/failed.txt" "$status" "$EXPECTED_FAILURES" - - name: Pipeline checker exit status on llvmpipe - shell: bash - run: | - dir=$(mktemp -d "$RUNNER_TEMP/pipeline-check.XXXXXX") - echo '{"ready":{"stage":"vs"},"missing":{"stage":"ps","outputs":[0]}}' > "$dir/index.json" - python3 -I tools/spirv_stubs.py "$dir" - cp "$dir/stubs/vs_empty.spv" "$dir/ready.spv" - check() { - runtime/build/vk_pipeline_check "$dir" "$dir/cache.bin" "$@" | tee "$dir/check.log" - } - - status=0 - check || status=$? - test "$status" -eq 1 - grep -Fx 'MODULE FAIL missing' "$dir/check.log" - grep -Fx 'vs pipelines: 1 ok, 0 failed, 0 skipped' "$dir/check.log" - test -s "$dir/cache.bin" - - cp "$dir/stubs/ps_empty.spv" "$dir/missing.spv" - check - grep -Fx 'ps pipelines: 1 ok, 0 failed, 0 skipped' "$dir/check.log" - grep -Fx 'vs pipelines: 1 ok, 0 failed, 0 skipped' "$dir/check.log" - if grep -F 'cache feedback' "$dir/check.log"; then exit 1; fi # opt-in: nothing without the flag - - check --max-bytes 1 - grep -F 'big modules skipped: 2' "$dir/check.log" - - # --cache-feedback: hits + no hit reported + unavailable == ok per stage; no particular bit is required - check --cache-feedback - for st in ps vs; do - awk -v st="$st" '$1 == st && $2 == "pipelines:" { ok = $3 } - $1 == st && $2 == "cache" && $3 == "feedback:" { sum = $4 + $6 + $10; seen = 1 } - END { exit !(seen && ok == 1 && sum == ok) }' "$dir/check.log" - done - - name: GPU tests on llvmpipe, compute with wave64 emulation - # llvmpipe has 8-wide subgroups, so the wave64 compute tests only run emulated. The emulated mesh tests are - # left out: llvmpipe's LLVM backend aborts compiling them ("Cannot emit physreg copy instruction"). - shell: bash - env: - LEONIDA_W64_EMULATE: "1" - # Empty: add names here when an emulated run still fails them; ci_expected_failures.py notices when they pass. - EXPECTED_FAILURES: - run: | - set +e - python3 -I scripts/run_gpu_tests.py --build runtime/build --llvm-mc /usr/lib/llvm-19/bin/llvm-mc --work "$RUNNER_TEMP/gpu-w64" --filter cs_ 2>&1 | - tee "$RUNNER_TEMP/gpu-w64.log" - status=${PIPESTATUS[0]} - set -e - sed -n '/=== GPU TEST RESULTS ===/,$p' "$RUNNER_TEMP/gpu-w64.log" | awk '$1 == "FAIL" { print $2 }' > "$RUNNER_TEMP/failed-w64.txt" - python3 -I scripts/ci_expected_failures.py "$RUNNER_TEMP/failed-w64.txt" "$status" "$EXPECTED_FAILURES" - - name: GPU tests on llvmpipe with the barycentric fallback - # llvmpipe has no VK_KHR_fragment_shader_barycentric, so the native run skips the pixel shaders that read raw - # barycentrics. Under --bary-fallback they read them from an input a pass-through geometry shader feeds - # (tools/bary_fallback_gs.py), the path for GPUs without the extension (NVIDIA Pascal). Every shader that - # got such a geometry shader has to pass here, not skip. - shell: bash - env: - LEONIDA_BARY_FALLBACK: "1" - # Empty: add names here when a fallback run still fails them; ci_expected_failures.py notices when they pass. - EXPECTED_FAILURES: - run: | - log="$RUNNER_TEMP/gpu-bary.log" - set +e - python3 -I scripts/run_gpu_tests.py --build runtime/build --llvm-mc /usr/lib/llvm-19/bin/llvm-mc --work "$RUNNER_TEMP/gpu-bary" 2>&1 | - tee "$log" - status=${PIPESTATUS[0]} - set -e - sed -n '/=== GPU TEST RESULTS ===/,$p' "$log" | awk '$1 == "FAIL" { print $2 }' > "$RUNNER_TEMP/failed-bary.txt" - python3 -I scripts/ci_expected_failures.py "$RUNNER_TEMP/failed-bary.txt" "$status" "$EXPECTED_FAILURES" - names=$(sed -n 's/^bary fallback GS: \(.*\)\.bary_gs\.spv$/\1/p' "$log") - if [ -z "$names" ]; then - echo "::error::no barycentric fallback geometry shader was built" - exit 1 - fi - while read -r name; do - if ! grep -Eq "^ PASS ${name}( |\$)" "$log"; then - echo "::error::$name did not pass under the barycentric fallback" - exit 1 - fi - done <<< "$names" - - # Builds the runtime on an Apple Silicon Mac and runs its tests and the hand-written GPU tests on MoltenVK. The - # hosted runner is a VM whose Metal device is "Apple Paravirtual device" (MTLGPUFamilyMac2, not Apple7), so - # Mesa's KosmicKrisp finds no device there; MoltenVK runs, with 32-wide subgroups. macos-26, not macos-15: Xcode - # 16's libc++ has no floating-point std::from_chars (vk_pipeline_check.cpp). - macos: - runs-on: macos-26 - timeout-minutes: 20 - env: - SCCACHE_GHA_ENABLED: "true" - HOMEBREW_NO_AUTO_UPDATE: "1" - HOMEBREW_NO_INSTALL_CLEANUP: "1" - steps: - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - with: - persist-credentials: false - - uses: actions/setup-python@6d4fd22b20465ccc0f7354476588e8df7c9ca0e0 # v7.1.0 - with: - python-version: "3.12" - - uses: mozilla-actions/sccache-action@fc920bf0ec8de6ee65d409111f7ec508035751ba # v0.0.11 - - name: Install MoltenVK, the Vulkan headers and loader, llvm-mc, SPIRV-Tools and glslang - run: | - brew install llvm molten-vk vulkan-headers vulkan-loader vulkan-tools spirv-tools glslang ninja - LLVM_MC="$(brew --prefix llvm)/bin/llvm-mc" # keg-only: not on PATH - echo "LLVM_MC=$LLVM_MC" >> "$GITHUB_ENV" - "$LLVM_MC" --version | grep 'LLVM version' - - name: MoltenVK sees a Metal device - run: | - VK_DRIVER_FILES="$(brew --prefix)/etc/vulkan/icd.d/MoltenVK_icd.json" vulkaninfo --summary > "$RUNNER_TEMP/vulkaninfo.txt" - grep -E 'deviceName|driverInfo|apiVersion' "$RUNNER_TEMP/vulkaninfo.txt" - grep -q 'driverID *= DRIVER_ID_MOLTENVK' "$RUNNER_TEMP/vulkaninfo.txt" - - name: Configure - run: >- - cmake -S runtime -B runtime/build -G Ninja - -DCMAKE_BUILD_TYPE=RelWithDebInfo - -DVulkan_INCLUDE_DIR="$(brew --prefix)/include" - -DCMAKE_CXX_COMPILER_LAUNCHER=sccache - -DLEONIDA_REQUIRE_VULKAN=ON - - name: Build - id: macos-build - run: cmake --build runtime/build --parallel - # Required: every test passes or skips, except the ones listed here, each with the pull request that fixes it - # on MoltenVK. They still run and show in the log; one that passes gets a notice, so the list shrinks. - - name: Runtime tests on MoltenVK - shell: bash - env: - # Empty: drop names here when a MoltenVK run still fails them; ci_expected_failures.py notices when they pass. - EXPECTED_FAILURES: - run: | - set +e - ctest --test-dir runtime/build --output-on-failure -j "$(sysctl -n hw.ncpu)" 2>&1 | tee "$RUNNER_TEMP/ctest.log" - status=${PIPESTATUS[0]} - set -e - sed -n '/The following tests FAILED:/,$p' "$RUNNER_TEMP/ctest.log" | - sed -nE 's/^[[:space:]]+[0-9]+ - ([^ ]+) .*/\1/p' > "$RUNNER_TEMP/failed.txt" - python3 -I scripts/ci_expected_failures.py "$RUNNER_TEMP/failed.txt" "$status" "$EXPECTED_FAILURES" - - name: GPU tests on MoltenVK - if: ${{ !cancelled() && steps.macos-build.outcome == 'success' }} # also after a runtime test failure - shell: bash - env: - # ps_ssharp: #1845 (the S#'s LOD bias, which a Metal sampler can't take). cs_fma_fused is newer than the job - # and wrong on MoltenVK: https://github.com/ItsNotRexed/Leonida/issues/3796#issuecomment-7086691314 - EXPECTED_FAILURES: >- - ps_ssharp - cs_fma_fused - run: | - set +e - python3 -I scripts/run_gpu_tests.py --build runtime/build --llvm-mc "$LLVM_MC" --work "$RUNNER_TEMP/gpu" 2>&1 | - tee "$RUNNER_TEMP/gpu.log" - status=${PIPESTATUS[0]} - set -e - sed -n '/=== GPU TEST RESULTS ===/,$p' "$RUNNER_TEMP/gpu.log" | awk '$1 == "FAIL" { print $2 }' > "$RUNNER_TEMP/failed.txt" - tail -n 1 "$RUNNER_TEMP/gpu.log" >> "$GITHUB_STEP_SUMMARY" - python3 -I scripts/ci_expected_failures.py "$RUNNER_TEMP/failed.txt" "$status" "$EXPECTED_FAILURES" diff --git a/.github/workflows/xma2-decoder.yml b/.github/workflows/xma2-decoder.yml deleted file mode 100644 index ff4559c6a..000000000 --- a/.github/workflows/xma2-decoder.yml +++ /dev/null @@ -1,45 +0,0 @@ -name: XMA2 decoder - -on: - push: - branches: [main] - paths: - - "runtime/xma_decoder/**" - - "third_party/xma/**" - - ".github/workflows/xma2-decoder.yml" - pull_request: - paths: - - "runtime/xma_decoder/**" - - "third_party/xma/**" - - ".github/workflows/xma2-decoder.yml" - -permissions: - contents: read - -jobs: - windows-ffi: - runs-on: windows-latest - timeout-minutes: 15 - steps: - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - - uses: ilammy/msvc-dev-cmd@0b201ec74fa43914dc39ae48a89fd1d8cb592756 # v1.13.0 - - name: Run synthetic Rust FFI tests - shell: pwsh - run: | - $env:CARGO_TARGET_DIR = Join-Path $env:RUNNER_TEMP "leonida-xma2-target" - cargo fmt --manifest-path runtime/xma_decoder/Cargo.toml -- --check - if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } - cargo test --manifest-path runtime/xma_decoder/Cargo.toml --locked - if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } - - name: Link and run the synthetic C++ ABI smoke test - shell: pwsh - run: | - $env:CARGO_TARGET_DIR = Join-Path $env:RUNNER_TEMP "leonida-xma2-target" - cargo build --manifest-path runtime/xma_decoder/Cargo.toml --locked - if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } - $library = Join-Path $env:CARGO_TARGET_DIR "debug\leonida_xma2_decoder.lib" - $smoke = Join-Path $env:RUNNER_TEMP "leonida-xma2-ffi-smoke.exe" - cl /nologo /std:c++20 /EHsc /W4 /DNDEBUG /I runtime/xma_decoder runtime/xma_decoder/tests/ffi_cpp_smoke.cpp $library "/Fe:$smoke" ws2_32.lib userenv.lib ntdll.lib synchronization.lib - if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } - & $smoke - if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } diff --git a/.gitignore b/.gitignore index faef90df2..ba6dd0e69 100644 --- a/.gitignore +++ b/.gitignore @@ -1,44 +1,78 @@ -# ---- never commit the game or anything made from it ---- -# (archives, executables, carved files, shaders, textures, models, audio, reports that quote game data) -reports/ -work/ -/assets/* -!/assets/logo.png -!/assets/logo.svg -carve/ -*.rpf -*.ttpf -*.xvd -*.msixvc -*.dxbc -*.fssm -*.spv -*.spvasm -*.dds -*.bk2 -*.awc -*.r9modeldata -*.obj -*.glb -*.ogg -*.wav +# --------------------------------------------------------------------------- +# RULE #1: nothing from the game (or any other proprietary source) is ever +# committed. +# Everything is built from files the user supplies at runtime. +# This file is the first line of defence; `cargo xtask policy` (also run by +# the pre-commit hook in .githooks/) is the second and is authoritative. +# See docs/asset-policy.md. +# --------------------------------------------------------------------------- + +# Build output +/target/ +/tests/fixtures/*/target/ -# ---- optional local Vulkan headers (manual only) ---- -deps/Vulkan-Headers/ +# Local configuration (contains paths to YOUR files) +/leonida.toml -# ---- build output and caches ---- -build/ -build-*/ -bin/ -obj/ -__pycache__/ -.pytest_cache/ -*.pyc +# Places people tend to drop data into. Keep data outside the repo instead. +/game/ +/games/ +/assets/ +/data/ +/dump/ +/dumps/ +/extracted/ +/cache/ +/out/ + +# Executables, libraries, symbols *.exe *.dll *.pdb -*.ilk *.lib +*.sys +*.obj *.exp -*.log +*.ilk + +# Console packages and containers +*.xvd +*.xvc +*.msixvc +*.xsp +*.cab +*.msi + +# Typical game data (non-exhaustive on purpose; the policy check is an allowlist) +*.bin +# The one exception (docs/asset-policy.md): the BCPack format's constant tables. +!/crates/leonida-formats/src/bcpack-tables.bin +*.dat +*.pak +*.rpf +*.dds +*.ktx +*.ktx2 +*.dxbc +*.dxil +*.cso +*.spv +*.wav +*.xma +*.ogg +*.opus +*.mp3 +*.mp4 +*.bik +*.bk2 +*.awc +*.zip +*.7z +*.rar + +# Editor / OS noise .vs/ +.idea/ +*.swp +Thumbs.db +.DS_Store diff --git a/.gitmodules b/.gitmodules deleted file mode 100644 index a60defcd2..000000000 --- a/.gitmodules +++ /dev/null @@ -1,3 +0,0 @@ -[submodule "third_party/rpf9-explorer"] - path = third_party/rpf9-explorer - url = https://github.com/breadbbbb/rpf9-explorer diff --git a/.leonida-root b/.leonida-root new file mode 100644 index 000000000..fcbc7ced6 --- /dev/null +++ b/.leonida-root @@ -0,0 +1,5 @@ +This marker file identifies the root of the Leonida Legacy source tree. + +Tools refuse to write game-derived output (caches, converted assets, prepared +images, logs containing game data) anywhere below a directory that contains +this file. See docs/asset-policy.md. diff --git a/AGENTS.md b/AGENTS.md deleted file mode 100644 index 11f868540..000000000 --- a/AGENTS.md +++ /dev/null @@ -1,123 +0,0 @@ -# Guide for coding agents - -Read this before changing anything here. [CONTRIBUTING.md](CONTRIBUTING.md) has the rules for every contributor and -[docs/design.md](docs/design.md) the formats and the translator's runtime contract; this file adds what an agent -tends to get wrong. - -## What this is - -A port template for the Xbox Series build of GTA VI, built on the player's PC from their own copy: -`make_game.py` carves and translates the shaders (RDNA2 → SPIR-V), exports the assets and builds `runtime/`, a PE -loader that maps the game's executable and resolves its imports to shims. Nothing of the game is in the repository. - -## Where things are - -- The notes under `docs/` record measured formats, indexed by [docs/README.md](docs/README.md); `docs/design.md` is the one quoted most. -- `scripts/` holds the GPU/Wine test runners (`run_gpu_tests.py`, `run_wine_tests.py`), the translator suite runner - `run_semantic_tests.py`, `check_no_game_data.py` (see the first hard rule below) and PowerShell build helpers. -- `viewer/` is the map viewer: `index.html` plus `serve.py`, a local-only server for the exported world. -- `third_party/` holds the `rpf9-explorer` submodule (`tools/rpf9dump` needs `git submodule update --init`), the vendored `xtaskqueue` the `xgameruntime` shim links and the vendored `bcpack-rs` rANS decoder of the BCPack calibration tools. -- `game/xbox-1.0.2.1.json` is the per-file size and SHA-256 manifest of the Xbox package — hashes only, no game content. -- `tests/semantic/` is the translator regression suite; a new translator rule comes with a small hand-written `.asm` fixture there. - -## Hard rules - -- **No game data, ever**: no archives, executables, carved files, shaders in any form (DXBC, FSSM, disassembly, - SPIR-V), textures, audio, or logs and reports that quote them, in commits, issues, pull requests or test - fixtures. A test that needs a shader builds its input by hand or reads it from the user's work folder. - `python -I scripts/check_no_game_data.py ...` reads the first bytes of the files you name, so it catches a - renamed file the extension check in CI misses. -- **No keys, decryption or protection workarounds.** If a format turns out to be encrypted, write that down in - `docs/design.md` and stop there. -- **Nothing online**: no Xbox Live or Rockstar services or domains. -- **Fix, don't disable**: a shader the translator rejects gets a rule, not a skip list. A new rule goes into the - contract table in `docs/design.md` with how it was confirmed (a GPU test, a Mesa/LLVM reference, or a count over - the corpus). - -## Claim before you start - -- Work is claimed in the coordination issue before a pull request is opened: the open issue titled "Coordinating - who works on what". It moves to a new issue when the thread gets long, so look it up instead of using an old - number: - - ```sh - gh issue list -R ubiquitarianism/leonida --state open --search "Coordinating who works on what in:title" - ``` - - With no `gh` auth, the search link in [CONTRIBUTING.md](CONTRIBUTING.md) works in a browser; say so when you cannot - read the claims at all rather than guessing that a thing is unclaimed. - - Check its tables and the open pull requests first. If someone has claimed the item or has a pull request for it, - stop and tell the user instead of writing it a second time. -- Put the item ID from that issue in the pull request, and `Depends on: #N` for every pull request yours builds on. -- Found work you won't do yourself (a bug, a missing method, a stale doc, a follow-up of your own pull request)? - Post it in the coordination issue as `finding: `, followed by where it is (file and line), why it matters, - and whether it needs game files or particular hardware. The coordinator checks it and lists it for others. -- For the D3D12 → Vulkan layer (`runtime/shims/d3d12_*`, `runtime/src/vulkan_*`), also read - [docs/d3d12_vulkan.md](docs/d3d12_vulkan.md) and the open pull requests: most of that work builds on a few of - them. The page that tracked it, #313, was in the original repository and is gone. -- The original repository (`ItsNotRexed/Leonida`) went private on 23 November 2026. A `#N` written before that is - an old number and links nowhere: do not cite one as if it could be read, and do not run `gh` against that - repository. The old open issues are indexed by title in - [#18](https://github.com/ubiquitarianism/leonida/issues/18) and the old open pull requests are kept as - `old-pr/` branches ([#17](https://github.com/ubiquitarianism/leonida/issues/17)). - -## Before you guess, look - -- The format or behaviour may already be measured in `docs/design.md`. Quote the file and offset a claim comes from, - or call it a hypothesis. -- Count over the whole corpus, not a sample: a rule that holds for 400 shaders can fail on the other 26 000. - -## Test without the game first - -None of these need game files. Most run in seconds - the translator suite takes a few minutes (433 files and 5 821 -tests in 224 s on 16 cores) and the two builds longer - so run one translator test file while you iterate and the -whole suite once before the pull request: - -```powershell -python -m compileall -q make_game.py tools tests -python -I make_game.py --help -python -I scripts/run_semantic_tests.py tests/semantic # translator suite, one file per core; no LLVM, SPIR-V tools or GPU needed -python -m unittest discover -s tests/semantic -p test_.py # one translator test file -python -I tests/test_.py # standalone standard-library unit test -node --test tests/test_viewer_streaming.cjs # viewer streaming; needs Node 22+ -dotnet build tools/rpf9dump/rpf9dump.csproj -c Release -cmake -S runtime -B runtime/build; cmake --build runtime/build --config RelWithDebInfo -ctest --test-dir runtime/build -C RelWithDebInfo --output-on-failure -``` - -`gta6rt` and the shims are Windows-only, so Linux and macOS configure the portable subset of the runtime tests. The -runtime tests that need the retail package read `LEONIDA_GAME_DIR` (and `LEONIDA_MOVIE`) and print `SKIP` when -unset; `loader_test` writes small PE images to `%TEMP%\leonida_loader_test`, which antivirus can block. - -For pytest-based tests (the test files with `import pytest`, or no `__main__` block: they fail to import under -`python -I`), use a virtual environment and install the pinned dependencies in -[`tests/requirements.txt`](tests/requirements.txt). From the repository root, run `python -m pytest` with the -test file you want to check. - -```powershell -python -m pip install -r tests/requirements.txt -python -m pytest tests/test_user_sgpr_census.py -``` - -With a work folder already built, a translator change is checked on a slice before the full run, and the result is -compared with the run before it: - -```powershell -python -I tools/rdna2spirv.py /shaders/dxbc/disasm --out --limit 200 -python -I tools/rdna2spirv.py /shaders/dxbc/disasm --out --shard 0/8 # one of 8 parallel slices -``` - -Shard runs write `index.part*.json`; merge them into `index.json` with `--merge`. Report translated and -`spirv-val`-valid counts before and after; a change that lowers either is a regression. - -## Conventions - -- Python tools run with `python -I` and use only the standard library unless a file says otherwise; the exceptions - are the texture and model tools that import numpy or Pillow: `bc_feature.py`, `amd_swizzle.py`, `tile_probe.py`, - `swizzle_search.py`, `tex_export.py`, `tex_mode_probe.py`, `calibrated_texture.py`, `world_grid_atlas.py`, - `tex_headers.py` and `skinned_glb.py` (which fall back to the standard library when numpy is absent). -- A text file a tool writes names its line ending - `open(path, "w", encoding="utf-8", newline="\n")` - so the same - input gives the same bytes on every platform; `tests/test_text_write_line_endings.py` catches a writer that forgets. -- Keep `make_game.py` working on Windows first: paths through `os.path`, no bash in the build. -- In the pull request, say that it was AI-assisted, what you tested and on which GPU and driver. diff --git a/Build.bat b/Build.bat deleted file mode 100644 index 85aabb7c5..000000000 --- a/Build.bat +++ /dev/null @@ -1,105 +0,0 @@ -@echo off -title Leonida Legacy - Game Builder -rem Double-click to build. Finds your copy of the game, checks what's installed, and builds into -rem Documents\Leonida. Extra options pass through, e.g. Build.bat --out D:\Games\Leonida -setlocal -cd /d "%~dp0" -echo. -echo ========================================== -echo L E O N I D A L E G A C Y - Game Builder -echo ========================================== -echo. -set "PY=" -for %%V in (3.14 3.13 3.12 3) do ( - if not defined PY ( - py -%%V -c "import sys; sys.exit(0 if sys.version_info >= (3, 12) else 1)" >nul 2>nul && set "PY=py -%%V" - ) -) -if not defined PY ( - where python >nul 2>nul && ( - python -c "import sys; sys.exit(0 if sys.version_info >= (3, 12) else 1)" >nul 2>nul && set "PY=python" - ) -) -rem No Python on PATH: look for a per-user install (python.org or winget, "Add to PATH" unticked), else offer to install one. -if not defined PY call :find_user_python -if not defined PY call :offer_python -if not defined PY ( - echo Python 3.12 or newer is needed: https://www.python.org/downloads/ - echo Tick "Add python.exe to PATH" during setup, then run Build.bat again. - pause - exit /b 1 -) -if not defined LEONIDA_SKIP_PREREQ_INSTALL ( - powershell -NoProfile -ExecutionPolicy Bypass -File "%~dp0scripts\install_prerequisites.ps1" -Auto -Quiet -) -%PY% -I "%~dp0make_game.py" %* -set "RC=%ERRORLEVEL%" -echo. -if "%RC%"=="0" (echo Done.) else (echo The build stopped. Read the message above.) -pause -exit /b %RC% - -rem ---- Helpers (only reached by "call"; the script exits above) ---- - -rem Each per-user install under %LOCALAPPDATA%\Programs\Python, highest folder name first; each one is -rem version-checked, so the name order does not matter. Needs no PATH refresh. -:find_user_python -for /f "delims=" %%D in ('dir /b /ad /o-n "%LOCALAPPDATA%\Programs\Python\Python3*" 2^>nul') do call :try_python "%LOCALAPPDATA%\Programs\Python\%%D\python.exe" -exit /b 0 - -:try_python -if defined PY exit /b 0 -if not exist %1 exit /b 0 -%1 -c "import sys; sys.exit(0 if sys.version_info >= (3, 12) else 1)" >nul 2>nul && set PY="%~1" -exit /b 0 - -rem Ask first, then install Python 3.12 for this user only (no admin): winget if present, else the pinned -rem python.org installer checked against its SHA-256 (also used if winget runs but installs nothing). LEONIDA_PY_INSTALL_DRYRUN=1 prints the command and skips it. -rem On "No" or any failure PY stays unset and the caller prints the manual instructions. -:offer_python -echo Python 3.12 or newer was not found, and the build needs it. -choice /c YN /n /t 60 /d N /m "Download and install Python 3.12 for your user account now? (No admin needed) [Y/N] " -if errorlevel 2 exit /b 0 -if not errorlevel 1 exit /b 0 -where winget >nul 2>nul && goto :py_winget -:py_download -set "PYURL=https://www.python.org/ftp/python/3.12.10/python-3.12.10-amd64.exe" -set "PYSHA=67B5635E80EA51072B87941312D00EC8927C4DB9BA18938F7AD2D27B328B95FB" -set "PYEXE=%TEMP%\leonida-python-3.12.10-amd64.exe" -if defined LEONIDA_PY_INSTALL_DRYRUN goto :py_dry_download -echo Downloading Python 3.12.10 from python.org ... -powershell -NoProfile -Command "$ErrorActionPreference='Stop'; $ProgressPreference='SilentlyContinue'; [Net.ServicePointManager]::SecurityProtocol=[Net.SecurityProtocolType]::Tls12; Invoke-WebRequest -UseBasicParsing -Uri $env:PYURL -OutFile $env:PYEXE; if ((Get-FileHash -Algorithm SHA256 -LiteralPath $env:PYEXE).Hash -ine $env:PYSHA) { Remove-Item -LiteralPath $env:PYEXE -Force; exit 3 }" -if errorlevel 1 goto :py_download_failed -echo Installing Python 3.12.10 ... -start "" /wait "%PYEXE%" /quiet InstallAllUsers=0 PrependPath=1 Include_launcher=1 -del /q "%PYEXE%" >nul 2>nul -goto :py_installed - -:py_download_failed -echo The download failed or did not match its checksum, so it was not run. -del /q "%PYEXE%" >nul 2>nul -exit /b 0 - -:py_dry_download -echo [dry run] would download %PYURL% -echo [dry run] would check SHA-256 %PYSHA% -echo [dry run] would run "%PYEXE%" /quiet InstallAllUsers=0 PrependPath=1 Include_launcher=1 -exit /b 0 - -:py_winget -set "PYWG=winget install --id Python.Python.3.12 -e --scope user --silent --accept-package-agreements --accept-source-agreements" -if defined LEONIDA_PY_INSTALL_DRYRUN goto :py_dry_winget -echo Installing Python 3.12 with winget ... -call %PYWG% -call :find_user_python -if defined PY exit /b 0 -echo winget did not install Python; trying the python.org installer instead. -goto :py_download - -:py_dry_winget -echo [dry run] would run %PYWG% -goto :py_download - -:py_installed -call :find_user_python -exit /b 0 diff --git a/Build.sh b/Build.sh deleted file mode 100755 index 567f3661e..000000000 --- a/Build.sh +++ /dev/null @@ -1,16 +0,0 @@ -#!/bin/sh -# Linux and macOS counterpart of Build.bat: finds Python 3.12 or newer and runs make_game.py, which finds your copy of -# the game, checks what's installed and builds into ~/Documents/Leonida. Extra options pass through, e.g. -# ./Build.sh --out /mnt/games/Leonida --work /mnt/scratch/leonida-work -# Nothing is installed or downloaded here; make_game.py lists anything missing (README.md, "How to build"). -here=$(CDPATH='' cd -- "$(dirname -- "$0")" && pwd) || exit 1 -# python3.N first: a distribution's python3 can be older than 3.12 while a newer one is installed beside it. -for py in python3.14 python3.13 python3.12 python3 python; do - command -v "$py" >/dev/null 2>&1 || continue - if "$py" -c 'import sys; sys.exit(0 if sys.version_info >= (3, 12) else 1)' >/dev/null 2>&1; then - exec "$py" -I "$here/make_game.py" "$@" - fi -done -echo "Python 3.12 or newer is needed. Install it with your package manager (Debian and Ubuntu:" >&2 -echo "sudo apt install python3; macOS: brew install python), then run ./Build.sh again." >&2 -exit 1 diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md deleted file mode 100644 index ac38ab0aa..000000000 --- a/CONTRIBUTING.md +++ /dev/null @@ -1,85 +0,0 @@ -# Contributing - -Thanks for helping. A few rules keep the project safe to host: - -- **No game data, ever.** That covers archives, the executable, carved files, shaders (DXBC, FSSM, disassembly, - SPIR-V), textures, models, audio, videos, and reports or logs that quote them. `.gitignore` blocks the common - types; check `git status` before you commit anyway. -- **No keys, decryption or protection workarounds**, and no links to where to get them. The tools only read files - that are already plain on disk. -- Short excerpts needed to explain a format (a few header bytes, one instruction sequence) are fine in docs and - comments. - -## Before you start - -Claim the work in [the coordination issue][claims] first: the open issue titled "Coordinating who works on what" (it -moves to a new issue when the thread gets long, so the link searches for it). Check its tables and the open pull -requests, post `claiming: ` there (or a one-line description for something not listed yet), and put the ID in -your pull request. When the pull request is open, post `done: -> #` there. Found something that needs doing -but won't do it yourself? Post `finding: ` there, with where it is and why it matters, and it goes on the -list for others. When two pull requests overlap anyway, the one that lands first is merged and the other is asked to -rebase or close. Pull requests target `main`. - -The original repository (`ItsNotRexed/Leonida`) went private on 23 November 2026, and its issues and pull requests -went with it. A `#N` in the docs, in a code comment or in a commit message from before that date is an **old** -number and links nowhere now, including the two this page used to send you to: #166 (GPU test results) and #313 -(the D3D12 → Vulkan page). - -- The titles of the issues that were open there are indexed in - [#18](https://github.com/ubiquitarianism/leonida/issues/18). To carry one on, open it again here and link the - index. -- The pull requests that were open there are kept as `old-pr/` branches, listed in - [#17](https://github.com/ubiquitarianism/leonida/issues/17). To carry one on, rebase it on `main`, keep its - author's commits and open a pull request here. -- A GPU test result is a pull request that adds a file to [`gpu-test-results/`](gpu-test-results) in the format of - the files there; [docs/testing.md](docs/testing.md) has how to run the tests. -- The plan and status of the D3D12 → Vulkan layer are in [docs/d3d12_vulkan.md](docs/d3d12_vulkan.md). - -[claims]: https://github.com/ubiquitarianism/leonida/issues?q=is%3Aissue%20is%3Aopen%20in%3Atitle%20%22Coordinating%20who%20works%20on%20what%22 - -## Working on the code - -- Python tools run with `python -I` and use only the standard library unless a file says otherwise. -- A text file a tool writes (JSON, CSV, a manifest, an assembly listing) names its line ending: `open(path, "w", - encoding="utf-8", newline="\n")` (the same for `Path.open`, `Path.write_text` and a text-mode - `tempfile.NamedTemporaryFile`), so the output is LF on Windows too and the same input gives the same bytes on every - platform. `tests/test_text_write_line_endings.py` fails for a writer that forgets it. -- A report writer refuses an output that names one of its inputs or another output, and asks - `tools/report_paths.same_report_path(a, b)` rather than deriving the answer again: it resolves both paths, - applies the volume's case rules and falls back to `os.path.samefile`, so a new tool reuses one answer - instead of a private copy. `tests/test_report_paths.py` covers it. -- `tools/rpf9dump` needs the submodule: `git submodule update --init`. -- A new shader-translator rule goes into the contract table in `docs/design.md`, with how it was confirmed: a GPU - test, a Mesa/LLVM reference, or a count over the corpus. -- `python -I tests/test_.py` runs one of the unit tests (standard library only; CI runs them all). The test - files with no `__main__` block or an `import pytest` (they need the packages in `tests/requirements.txt`) run with - `python -m pytest tests/test_.py` instead, as [AGENTS.md](AGENTS.md) describes; under `python -I` they fail - to import or run nothing. -- Runtime tests: `cmake -S runtime -B runtime/build`, `cmake --build runtime/build --config RelWithDebInfo`, then - `ctest --test-dir runtime/build -C RelWithDebInfo --output-on-failure`. The CPU tests that need no game data are configured - on Windows; Linux and macOS configure the portable subset (`gta6rt` and the shims are Windows-only). Tests that need the retail package read `LEONIDA_GAME_DIR` (and `LEONIDA_MOVIE` for the Bink - decode test) in place and print `SKIP` when the variable is unset; never copy or commit those files. -- Viewer streaming tests: `node --test tests/test_viewer_streaming.cjs` (Node.js 22+, CI tests 24 LTS; no packages, - browser, network or game data). These execute the viewer streaming code with a synthetic loader and clock. -- `loader_test` writes small PE images to a `leonida_loader_test` folder in `%TEMP%`. Antivirus that blocks newly - written executables makes it stop with that reason; exclude the folder or set `LEONIDA_TEST_DIR` to one it skips. -- Tool checks: `python -m compileall -q make_game.py tools tests`. The optional - `vk_pipeline_check [cache.bin] [--jobs N]` creates a module (and, for compute shaders, a - pipeline) for every translated shader and reports failures plus the saved cache path. -- GPU tests are small hand-written RDNA2 programs in `runtime/test/shaders`. `build.py` turns them into SPIR-V - using `llvm-mc` with the AMDGPU target (LLVM 21+). `check.py` runs them on your GPU and compares the results. - A new test gets its expected values in the comment at its top and a check in `check.py`. - [docs/testing.md](docs/testing.md) covers setup per OS, including native Windows options, and known problems. -- Say what you tested and on which GPU in the pull request. -- Run the translator tests with `python -I scripts/run_semantic_tests.py tests/semantic` (see `tests/semantic/README.md`). A new - translator rule should come with a small hand-written `.asm` fixture and its expected output words. - -## Pull requests - -- One topic per pull request, based on current `main`. Follow-up work goes in a new pull request, not into an open - one. -- Fill in the [template](.github/pull_request_template.md): the claim, `Depends on:`, `Fixes: #N` for an issue it - closes, what you tested, `GPUs tested:` (vendor, model, driver and OS) and whether it was AI-assisted. -- A pull request that conflicts with `main` is labeled `needs rebase` (`tools/pr_conflict_label.py`, run on every - push to `main` and to the pull request, and hourly). Rebase it on `main` yourself; the label goes once it merges - cleanly. Reviews start with the pull requests that do. diff --git a/Cargo.lock b/Cargo.lock new file mode 100644 index 000000000..6fcafa5a9 --- /dev/null +++ b/Cargo.lock @@ -0,0 +1,905 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "aho-corasick" +version = "1.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c982642fa9e8606056828ee9a8505737230110bb1099153c79efe865c59d12ba" +dependencies = [ + "memchr", +] + +[[package]] +name = "anstream" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "824a212faf96e9acacdbd09febd34438f8f711fb84e09a8916013cd7815ca28d" +dependencies = [ + "anstyle", + "anstyle-parse", + "anstyle-query", + "anstyle-wincon", + "colorchoice", + "is_terminal_polyfill", + "utf8parse", +] + +[[package]] +name = "anstyle" +version = "1.0.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "940b3a0ca603d1eade50a4846a2afffd5ef57a9feac2c0e2ec2e14f9ead76000" + +[[package]] +name = "anstyle-parse" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "52ce7f38b242319f7cabaa6813055467063ecdc9d355bbb4ce0c68908cd8130e" +dependencies = [ + "utf8parse", +] + +[[package]] +name = "anstyle-query" +version = "1.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "40c48f72fd53cd289104fc64099abca73db4166ad86ea0b4341abe65af83dadc" +dependencies = [ + "windows-sys", +] + +[[package]] +name = "anstyle-wincon" +version = "3.0.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "291e6a250ff86cd4a820112fb8898808a366d8f9f58ce16d1f538353ad55747d" +dependencies = [ + "anstyle", + "once_cell_polyfill", + "windows-sys", +] + +[[package]] +name = "anyhow" +version = "1.0.104" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470" + +[[package]] +name = "arrayvec" +version = "0.7.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3fb67a6e08acf24fdeccbac2cb6ac4305825bd1f117462e0e6f2f193345ad56" + +[[package]] +name = "bitflags" +version = "2.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06" + +[[package]] +name = "blake3" +version = "1.8.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6d9e454fc11f76977dc803893aff6304ed33d6a26efae8696573bea74baa27ae" +dependencies = [ + "arrayvec", + "cc", + "cfg-if", + "constant_time_eq", + "cpufeatures", +] + +[[package]] +name = "cc" +version = "1.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "02f0e023adb368345ce0ca6cdfc0f24a06554468d0e8503e14a0841de79bfa69" +dependencies = [ + "find-msvc-tools", + "shlex", +] + +[[package]] +name = "cfg-if" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600" + +[[package]] +name = "clap" +version = "4.6.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "844c5c0b65be192cb68d570cca1b21a6444431d24e39c084dc0336177015337c" +dependencies = [ + "clap_builder", + "clap_derive", +] + +[[package]] +name = "clap_builder" +version = "4.6.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec0797fb7aeb1406c84efac526901f7ec3ead2124f946b494e72879d4b54704d" +dependencies = [ + "anstream", + "anstyle", + "clap_lex", + "strsim", +] + +[[package]] +name = "clap_derive" +version = "4.6.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b4c174f11f949b9ca8c60580925e282b9cbd5454750e506f08648b2038080cd7" +dependencies = [ + "heck", + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "clap_lex" +version = "1.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e0921b3876b3a1df8a1c9f912e7f94342458022c2e84288015893d83c4d62a79" + +[[package]] +name = "colorchoice" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1d07550c9036bf2ae0c684c4297d503f838287c83c53686d05370d0e139ae570" + +[[package]] +name = "constant_time_eq" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3d52eff69cd5e647efe296129160853a42795992097e8af39800e1060caeea9b" + +[[package]] +name = "cpufeatures" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5ca28b0ae3115b884660db4118d803791fd6756b6e88f39c0f3f7859060d7566" +dependencies = [ + "libc", +] + +[[package]] +name = "equivalent" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "00d174d5400e5e8fd687ad1049e2f578285fa914201b1af7e8b112a4546bd826" + +[[package]] +name = "errno" +version = "0.3.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e35d6e78f4cebb90e51d543db8fe41528851d6deeef6ef21ebd4bfdc1e784776" +dependencies = [ + "libc", + "windows-sys", +] + +[[package]] +name = "fastrand" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223" + +[[package]] +name = "find-msvc-tools" +version = "0.1.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1c66915cc5391097de7a2b0b972e8505aa33c0df401fd3a6811dbdb32881ba48" + +[[package]] +name = "getrandom" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099" +dependencies = [ + "cfg-if", + "libc", + "r-efi", +] + +[[package]] +name = "hashbrown" +version = "0.17.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "735eaa21a6a5ffb2e84362faaeb90c05ba8e19797ca30428478cb6ea3a4921bc" + +[[package]] +name = "heck" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" + +[[package]] +name = "indexmap" +version = "2.14.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855" +dependencies = [ + "equivalent", + "hashbrown", +] + +[[package]] +name = "is_terminal_polyfill" +version = "1.70.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a6cb138bb79a146c1bd460005623e142ef0181e3d0219cb493e02f7d08a35695" + +[[package]] +name = "lazy_static" +version = "1.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "20870f649af7073d53e38067b2a84312175d56ea15217e1b15bc83506ec50afb" + +[[package]] +name = "leonida" +version = "0.1.0" +dependencies = [ + "anyhow", + "blake3", + "clap", + "leonida-core", + "leonida-game", + "leonida-hle", + "leonida-loader", + "leonida-pe", + "leonida-shader", + "memchr", + "walkdir", +] + +[[package]] +name = "leonida-core" +version = "0.1.0" +dependencies = [ + "anyhow", + "serde", + "tempfile", + "thiserror", + "toml", + "tracing-subscriber", +] + +[[package]] +name = "leonida-formats" +version = "0.1.0" + +[[package]] +name = "leonida-game" +version = "0.1.0" +dependencies = [ + "memchr", + "zlib-rs", +] + +[[package]] +name = "leonida-gpu" +version = "0.1.0" +dependencies = [ + "anyhow", + "blake3", + "leonida-formats", + "leonida-pipeline", + "leonida-shader", + "tempfile", + "tracing", + "windows", + "windows-sys", + "zlib-rs", +] + +[[package]] +name = "leonida-hle" +version = "0.1.0" +dependencies = [ + "leonida-formats", + "leonida-gpu", + "leonida-loader", + "leonida-pe", + "opus-pure", + "tempfile", + "tracing", + "windows", + "windows-core", + "windows-sys", + "zlib-rs", +] + +[[package]] +name = "leonida-loader" +version = "0.1.0" +dependencies = [ + "anyhow", + "blake3", + "leonida-core", + "leonida-pe", + "tempfile", + "thiserror", + "tracing", + "windows-sys", +] + +[[package]] +name = "leonida-pe" +version = "0.1.0" +dependencies = [ + "object", + "thiserror", +] + +[[package]] +name = "leonida-pipeline" +version = "0.1.0" +dependencies = [ + "anyhow", + "blake3", + "leonida-core", + "tempfile", + "tracing", +] + +[[package]] +name = "leonida-shader" +version = "0.1.0" +dependencies = [ + "thiserror", + "windows", + "windows-sys", + "zlib-rs", +] + +[[package]] +name = "libc" +version = "0.2.191" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a" + +[[package]] +name = "linux-raw-sys" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53" + +[[package]] +name = "log" +version = "0.4.35" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5d15f86d12da44cd8d4ec3c73984537eb7f4cadcb9776a575a0a8a05ca11005c" + +[[package]] +name = "matchers" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d1525a2a28c7f4fa0fc98bb91ae755d1e2d1505079e05539e35bc876b5d65ae9" +dependencies = [ + "regex-automata", +] + +[[package]] +name = "memchr" +version = "2.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" + +[[package]] +name = "nu-ansi-term" +version = "0.50.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7957b9740744892f114936ab4a57b3f487491bbeafaf8083688b16841a4240e5" +dependencies = [ + "windows-sys", +] + +[[package]] +name = "object" +version = "0.41.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "11dbdb66876026054e4ffc8d757d862bdf5df5aebd5c0b95a41f17832a94f7d2" +dependencies = [ + "memchr", +] + +[[package]] +name = "once_cell" +version = "1.21.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" + +[[package]] +name = "once_cell_polyfill" +version = "1.70.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "384b8ab6d37215f3c5301a95a4accb5d64aa607f1fcb26a11b5303878451b4fe" + +[[package]] +name = "opus-pure" +version = "0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ccd077a3f06e5fc42b04bb59f70d5fe0cdb2c119eef0e240af7e287180ee23ba" + +[[package]] +name = "pin-project-lite" +version = "0.2.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c938015719552d665fd0553b90d96cd7ff58e83e4c061ca99e6bb78865a72752" + +[[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 = "r-efi" +version = "6.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf" + +[[package]] +name = "regex-automata" +version = "0.4.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "41d60ef07df457506a0a1a2073112eb4aae5733dbd2813c3da77d1b0fd441158" +dependencies = [ + "aho-corasick", + "memchr", + "regex-syntax", +] + +[[package]] +name = "regex-syntax" +version = "0.8.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d902046e6a28a1e4c3cab97258a0ce11e994903f01c2d97a9447a0b3df85f4f6" + +[[package]] +name = "rustix" +version = "1.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e5e76742e5294153d4dde1207dbec5bdd81eef6fabdc0d2118babadabfd858aa" +dependencies = [ + "bitflags", + "errno", + "libc", + "linux-raw-sys", + "windows-sys", +] + +[[package]] +name = "same-file" +version = "1.0.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "93fc1dc3aaa9bfed95e02e6eadabb4baf7e3078b0bd1b4d7b6b0b68378900502" +dependencies = [ + "winapi-util", +] + +[[package]] +name = "serde" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba" +dependencies = [ + "serde_core", + "serde_derive", +] + +[[package]] +name = "serde_core" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48" +dependencies = [ + "serde_derive", +] + +[[package]] +name = "serde_derive" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "serde_spanned" +version = "1.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9c187e0a369471c550af028cba56d4f4fa2a489ad28151ae95a4d340a2a8b782" +dependencies = [ + "serde_core", +] + +[[package]] +name = "sharded-slab" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f40ca3c46823713e0d4209592e8d6e826aa57e928f09752619fc696c499637f6" +dependencies = [ + "lazy_static", +] + +[[package]] +name = "shlex" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba" + +[[package]] +name = "smallvec" +version = "1.16.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3244542535d5de959d90ec55d1b5ff0fd2bb7b1310223907d5f11932847f7b59" + +[[package]] +name = "strsim" +version = "0.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f" + +[[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 = "tempfile" +version = "3.27.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd" +dependencies = [ + "fastrand", + "getrandom", + "once_cell", + "rustix", + "windows-sys", +] + +[[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 = "thread_local" +version = "1.1.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1ad99c4c6d32803332c548b1af0540b357b3f5fc0be8f6c6bfe8b2e6ae784070" +dependencies = [ + "cfg-if", +] + +[[package]] +name = "toml" +version = "1.2.2+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5426cb1b964690d913f6c5c1a1ae0b42f428ec506bb4d452876d7a209c9bca3b" +dependencies = [ + "indexmap", + "serde_core", + "serde_spanned", + "toml_datetime", + "toml_parser", + "toml_writer", + "winnow", +] + +[[package]] +name = "toml_datetime" +version = "1.1.3+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "173f25c883cd2176a2d8212155638c0a60d484a9d84546d270866f40f56b6e49" +dependencies = [ + "serde_core", +] + +[[package]] +name = "toml_parser" +version = "1.1.6+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e6769c452d71ba30696c6b37770c439a9cc9110f47f7d5cdbeda79840ef5ea31" +dependencies = [ + "winnow", +] + +[[package]] +name = "toml_writer" +version = "1.2.0+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "009dbb7700f11c55ef83aebbe4c0e9cf1f1ac0844bd8d6f00dc38f302026e13a" + +[[package]] +name = "tracing" +version = "0.1.44" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "63e71662fa4b2a2c3a26f570f037eb95bb1f85397f3cd8076caed2f026a6d100" +dependencies = [ + "pin-project-lite", + "tracing-attributes", + "tracing-core", +] + +[[package]] +name = "tracing-attributes" +version = "0.1.31" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7490cfa5ec963746568740651ac6781f701c9c5ea257c58e057f3ba8cf69e8da" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "tracing-core" +version = "0.1.36" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "db97caf9d906fbde555dd62fa95ddba9eecfd14cb388e4f491a66d74cd5fb79a" +dependencies = [ + "once_cell", + "valuable", +] + +[[package]] +name = "tracing-log" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ee855f1f400bd0e5c02d150ae5de3840039a3f54b025156404e34c23c03f47c3" +dependencies = [ + "log", + "once_cell", + "tracing-core", +] + +[[package]] +name = "tracing-subscriber" +version = "0.3.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb7f578e5945fb242538965c2d0b04418d38ec25c79d160cd279bf0731c8d319" +dependencies = [ + "matchers", + "nu-ansi-term", + "once_cell", + "regex-automata", + "sharded-slab", + "smallvec", + "thread_local", + "tracing", + "tracing-core", + "tracing-log", +] + +[[package]] +name = "unicode-ident" +version = "1.0.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563" + +[[package]] +name = "utf8parse" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821" + +[[package]] +name = "valuable" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ba73ea9cf16a25df0c8caa16c51acb937d5712a8429db78a3ee29d5dcacd3a65" + +[[package]] +name = "walkdir" +version = "2.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b42e295b7452c4604982280d8586001fcad9b8b201cac67bca9771e7a7475403" +dependencies = [ + "same-file", + "winapi-util", +] + +[[package]] +name = "winapi-util" +version = "0.1.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22" +dependencies = [ + "windows-sys", +] + +[[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]] +name = "winnow" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8c3b93199df0ab874cdf0c6a94f0a0dc3423fe41f1cafb62b8bd7b1deb277aef" + +[[package]] +name = "xtask" +version = "0.1.0" +dependencies = [ + "anyhow", + "clap", + "walkdir", +] + +[[package]] +name = "zlib-rs" +version = "0.6.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b268e58e7c693d7c271f93ffc4ba3b380412554231c85bf61ca7af91042a4112" diff --git a/Cargo.toml b/Cargo.toml new file mode 100644 index 000000000..f9e51e05c --- /dev/null +++ b/Cargo.toml @@ -0,0 +1,79 @@ +[workspace] +resolver = "3" +members = ["crates/*", "apps/*", "xtask"] +# Fixtures are standalone crates built on demand by integration tests. +exclude = ["tests/fixtures"] + +[workspace.package] +version = "0.1.0" +edition = "2024" +rust-version = "1.88" +license = "GPL-3.0-or-later" +publish = false + +[workspace.dependencies] +# Internal crates +leonida-core = { path = "crates/leonida-core" } +leonida-pe = { path = "crates/leonida-pe" } +leonida-loader = { path = "crates/leonida-loader" } +leonida-hle = { path = "crates/leonida-hle" } +leonida-gpu = { path = "crates/leonida-gpu" } +leonida-shader = { path = "crates/leonida-shader" } +leonida-formats = { path = "crates/leonida-formats" } +leonida-pipeline = { path = "crates/leonida-pipeline" } +leonida-game = { path = "crates/leonida-game" } + +# External crates +anyhow = "1.0.104" +thiserror = "2.0.21" +clap = { version = "4.6.9", features = ["derive"] } +tracing = "0.1.44" +tracing-subscriber = { version = "0.3.23", features = ["env-filter"] } +serde = { version = "1.0.229", features = ["derive"] } +toml = "1.2.2" +object = { version = "0.41.0", default-features = false, features = ["read_core", "pe", "coff", "archive", "std"] } +windows-sys = "0.61.2" +windows = "0.62.2" +windows-core = "0.62.2" +blake3 = "1.8.7" +memchr = "2.8.3" +# SIMD-accelerated pure-Rust zlib/deflate (Zlib license, runtime AVX2/SSE4.2 dispatch). +zlib-rs = { version = "0.6.8", default-features = false, features = ["std"] } +walkdir = "2.5.1" +tempfile = "3.27.0" +# Opus decoding for the console's audio decoder (BSD-3-Clause, pure Rust). +opus-pure = "0.2.4" + +[workspace.lints.rust] +unsafe_op_in_unsafe_fn = "deny" +unused_must_use = "deny" + +[workspace.lints.clippy] +all = { level = "warn", priority = -1 } +# This fork: two style lints are let through until the newer code is tidied +# (tuple-heavy signatures and indexed loops in the translator and GPU side). +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" +# Upstream warns on unsafe blocks without a SAFETY comment; eleven blocks in +# this fork's newer GPU code still lack one. +undocumented_unsafe_blocks = "allow" + +[profile.dev.package."*"] +# Dependencies (hashing, parsing) are hot paths when chewing through +# gigabytes of game data; keep them fast even in debug builds. +opt-level = 2 + +[profile.release] +debug = "line-tables-only" + +# The development build: release code generation plus the `diagnostics` +# feature (`cargo build --profile diag -p leonida --features diagnostics`), +# kept in its own folder so it does not evict the plain release build. +[profile.diag] +inherits = "release" diff --git a/Check-PC.bat b/Check-PC.bat deleted file mode 100644 index c0fa038f6..000000000 --- a/Check-PC.bat +++ /dev/null @@ -1,32 +0,0 @@ -@echo off -title Leonida Legacy - PC Check -rem Double-click to see whether this PC is ready to build (tools, disk, optional game package, GPU). -setlocal -cd /d "%~dp0" -echo. -echo ========================================== -echo L E O N I D A L E G A C Y - PC Check -echo ========================================== -echo. -set "PY=" -for %%V in (3.14 3.13 3.12 3) do ( - if not defined PY ( - py -%%V -c "import sys; sys.exit(0 if sys.version_info >= (3, 12) else 1)" >nul 2>nul && set "PY=py -%%V" - ) -) -if not defined PY ( - where python >nul 2>nul && ( - python -c "import sys; sys.exit(0 if sys.version_info >= (3, 12) else 1)" >nul 2>nul && set "PY=python" - ) -) -if not defined PY ( - echo Python 3.12 or newer is needed: https://www.python.org/downloads/ - pause - exit /b 1 -) -%PY% -I "%~dp0scripts\pc_readiness.py" %* -set "RC=%ERRORLEVEL%" -echo. -if "%RC%"=="0" (echo Done.) else (echo Something is still missing. See above.) -pause -exit /b %RC% \ No newline at end of file diff --git a/Install-Prerequisites.bat b/Install-Prerequisites.bat deleted file mode 100644 index 698a1fd09..000000000 --- a/Install-Prerequisites.bat +++ /dev/null @@ -1,14 +0,0 @@ -@echo off -title Leonida Legacy - Install prerequisites -setlocal -cd /d "%~dp0" -echo. -echo Leonida Legacy - installs missing build tools (Python, .NET, Vulkan SDK, VS C++, llvm-mc). -echo Does not download the game. -echo. -powershell -NoProfile -ExecutionPolicy Bypass -File "%~dp0scripts\install_prerequisites.ps1" %* -set "RC=%ERRORLEVEL%" -echo. -if "%RC%"=="0" (echo All set.) else (echo Something is still missing - read the messages above.) -pause -exit /b %RC% \ No newline at end of file diff --git a/Mods.bat b/Mods.bat deleted file mode 100644 index 5b7da57f0..000000000 --- a/Mods.bat +++ /dev/null @@ -1,26 +0,0 @@ -@echo off -title Leonida - Mod Manager -rem Double-click to open the mod manager window. It manages \mods and never touches the game package. -setlocal -cd /d "%~dp0" -set "PY=" -for %%V in (3.14 3.13 3.12 3) do ( - if not defined PY ( - py -%%V -c "import sys; sys.exit(0 if sys.version_info >= (3, 12) else 1)" >nul 2>nul && set "PY=py -%%V" - ) -) -if not defined PY ( - where python >nul 2>nul && ( - python -c "import sys; sys.exit(0 if sys.version_info >= (3, 12) else 1)" >nul 2>nul && set "PY=python" - ) -) -if not defined PY ( - echo Python 3.12 or newer is needed: https://www.python.org/downloads/ - echo Tick "Add python.exe to PATH" during setup. - pause - exit /b 1 -) -%PY% -I "%~dp0tools\leonida_mods.py" gui %* -set "RC=%ERRORLEVEL%" -if not "%RC%"=="0" pause -exit /b %RC% diff --git a/Mods.sh b/Mods.sh deleted file mode 100755 index 7bb6985b4..000000000 --- a/Mods.sh +++ /dev/null @@ -1,13 +0,0 @@ -#!/bin/sh -# Linux and macOS counterpart of Mods.bat: opens the mod manager window (tools/leonida_mods.py gui). It manages -# /mods and never touches the game package. The window needs Tkinter (Debian and Ubuntu: python3-tk). -here=$(CDPATH='' cd -- "$(dirname -- "$0")" && pwd) || exit 1 -for py in python3.14 python3.13 python3.12 python3 python; do - command -v "$py" >/dev/null 2>&1 || continue - if "$py" -c 'import sys; sys.exit(0 if sys.version_info >= (3, 12) else 1)' >/dev/null 2>&1; then - exec "$py" -I "$here/tools/leonida_mods.py" gui "$@" - fi -done -echo "Python 3.12 or newer is needed. Install it with your package manager (Debian and Ubuntu:" >&2 -echo "sudo apt install python3 python3-tk; macOS: brew install python), then run ./Mods.sh again." >&2 -exit 1 diff --git a/README.md b/README.md index c901cb7b2..430e0c886 100644 --- a/README.md +++ b/README.md @@ -1,11 +1,11 @@ -

+

Telegram — Leonida Legacy


- Leonida Legacy + Leonida Legacy
@@ -13,7 +13,7 @@

-

Grand Theft Auto VI (Xbox Series) running natively on Windows, built on your PC from your own copy. +

Grand Theft Auto VI (Xbox Series) running natively on Windows, from your own copy.

Continued by orkan1k.

@@ -21,125 +21,82 @@ > *ItsNotRexed just wanted to play on the PC.*

- Status | - How to build | - How it works | - Want to help? | + Status | + Getting started | + Fork notes | Contact | Credits | License

-Leonida Legacy is a static recompilation project. The Xbox Series CPU is x86-64 like a PC, so the game's code is loaded -and run natively, and the console's system software is reimplemented. The console's precompiled RDNA2 GPU programs -are translated to SPIR-V for Vulkan. The game's models, textures and audio are read from your package. All of this -happens **on your PC, from your own copy of the game**. +Leonida Legacy is a compatibility layer. The game's x86-64 code runs unchanged inside our process, and Leonida +Legacy supplies the console platform underneath it: the loader, the runtime services, a Direct3D 12 back end and a +shader recompiler that turns the console's GPU code into DXIL on first use. See +[docs/architecture.md](docs/architecture.md). + +It is a fork of [victory-gta6](https://github.com/fxceless/victory-gta6), itself a fork of +[VIctory](https://github.com/Marvisak/VIctory). > [!IMPORTANT] -> This repository **does not contain the game, keys or an executable**, and it does not explain how to get them. You -> need your own copy, with its files already readable on disk. Nothing here decrypts or works around any protection. -> Everything the build creates (the generated shaders, extracted assets, the runtime folder and your saves) comes -> from your game and stays on your PC. Never share those files. - -## Project status - -**Early. The game does not boot yet.** Everything that can be done without the game's executable is in place, so -work on booting can start as soon as one is available to a developer. - -| What | Status | -|---|---| -| Finding and checking your copy (Xbox Series 1.0.2.1) | ✅ Works | -| Shaders: carve, unpack native RDNA2 code, disassemble | ✅ All 26,503 | -| Shaders: RDNA2 → SPIR-V translation | ✅ All **26,503** programs translate and pass `spirv-val` (2,236 VS, 12,101 PS, 2,689 CS, 9,282 mesh, 195 geometry); see [docs/design.md](docs/design.md) | -| Shader translator checked on a real GPU | ⚠️ Manual GPU checks (fetch, textures, exports, ALU). Full build runs `tools/verify_build.py` (`vk_harness`) after the shaders stage | -| Models (OBJ with real names, UVs, material references) | ✅ Exported. Not all layouts are decoded yet | -| Texture dictionaries and world texture pools (DDS) | ✅ Exported. Some pool entries (BCPack) are skipped | -| Audio banks (AWC: Opus, XMA2) | ✅ Exported whole. Decoding to WAV is not done yet | -| PE loader and import shims | ⚠️ Maps/relocates/binds imports; `gta6rt --self-test` via `tools/verify_build.py`. Real game exe still needed for full coverage | -| Xbox D3D12 → Vulkan | ⚠️ **In progress:** Vulkan-backed `ID3D12Device` (queues, allocators, command lists, fences, descriptor heaps, draws, dispatches, present) behind the Xbox-ABI proxy — GPU milestones M0–M2 (`d3d12_present_test`, `d3d12_draw_test`, `d3d12_m2_textured_test`). Default is PC D3D12; use `LEONIDA_D3D12=vulkan` for Vulkan. Still open for the full title: traced COM coverage, tessellation/stream-output PSOs, mesh PSOs, present path. See [docs/d3d12_vulkan.md](docs/d3d12_vulkan.md) | -| Booting, story mode, anything playable | ❌ No (needs the game executable and the D3D12→Vulkan layer) | - -## How to build - -The port isn't downloaded ready-made. It's built on your PC from your own copy. - -**The easy way:** - -1. Install the prerequisites below (or double-click **`Install-Prerequisites.bat`** / let **`Build.bat`** install missing tools automatically). -2. Download this project **with its submodule**: `git clone --recursive https://github.com/ProjectLeonidaL/leonida`. A - "Download ZIP" from GitHub leaves out `third_party/rpf9-explorer`. The build fetches it if `git` is installed, - and otherwise tells you what to do. -3. Optional: double-click **`Check-PC.bat`** (or `python -I scripts/pc_readiness.py`; `--lang de` or `ru` from - `scripts/i18n/pc_readiness/`) to see whether this PC has the tools, disk space, game package and GPU for the build - — without starting a build. -4. Double-click **`Build.bat`**. - -It finds your copy of the game by itself: it looks in Downloads, Desktop, Documents, Games, your home folder and -the top of every drive, two folders deep. It recognises the version from a few file sizes, without reading -anything large. If you have more than one copy it asks which one, and if it finds none it asks you to paste the -folder. Before starting it checks that everything below is installed and that there is enough free space, and it -lists anything missing in one go. The result goes to `Documents\Leonida Legacy`. A stopped build continues where it left -off. - -Your game folder is the one that holds `MicrosoftGame.Config` and the `.rpf` archives, as plain files. - -**Prerequisites:** - -- **Your own copy** of the Xbox Series package, version 1.0.2.1. -- **Windows 10/11 x64**, with about **350 GB** free for work files. They can go on another drive with `--work`. -- [Python 3.11+](https://www.python.org/downloads/) (tick "Add python.exe to PATH"). -- [.NET 8 SDK](https://dotnet.microsoft.com/download/dotnet/8.0). -- [Vulkan SDK](https://vulkan.lunarg.com/), for `spirv-as` / `spirv-val`. -- [LLVM 21+](https://github.com/llvm/llvm-project/releases) with `llvm-mc` on PATH, or set `LLVM_MC` to its path. -- Visual Studio 2022 with **Desktop development with C++**, for the runtime stage. - -On Windows, **`Install-Prerequisites.bat`** (or **`Build.bat`**, which runs the same installer quietly) uses **winget** where possible and can build **llvm-mc** with `scripts\build_llvm_mc.ps1`. It never downloads the game. Set **`LEONIDA_SKIP_PREREQ_INSTALL=1`** to skip auto-install. After installs, open a **new terminal** so `PATH` and `VULKAN_SDK` refresh. - -**From a terminal**, with the same behaviour and more control: +> This repository **does not contain the game, keys or an executable**. You need your own copy of the game. +> Everything the tools make from your files (translated shaders, caches, saves, logs) stays outside the repository +> and on your PC. Never share those files. -```powershell -python -I make_game.py --find # list the copies found on this PC -python -I make_game.py --check # check your copy, build nothing -python -I make_game.py --game "D:\path\to\your\package" --out "D:\Games\Leonida Legacy" --work "E:\leonida-legacy-work" -python -I make_game.py --stages shaders,assets # only some stages -``` +## Status -Stages run in order: `check`, `shaders`, `assets`, `runtime`. The shader translation is the longest step: several -hours on one core for now. +**Not playable yet: 2 to 4 frames per second by default, and shadowed areas are black.** Tested on Windows 11 Pro, +AMD Ryzen 7 7800X3D, NVIDIA RTX 3080 12 GB, 32 GB RAM, Series X profile. The world frame rates below were measured +by victory-gta6 on an RTX 4070 and have not been measured again on this machine yet. -**Runtime / GPU checks:** a full build (`Build.bat` or all default stages) ends with `tools/verify_build.py`: -PE self-map, Vulkan device (GPU driver or Lavapipe from your installed Vulkan SDK), and—after the shaders stage—a `vk_harness` draw using SPIR-V in `\shaders\spirv`. Nothing is downloaded during verify. +| Stage | State | +|-------|-------| +| Boot, menus, start screen | works, 30 fps | +| Opening cutscene | plays from start to finish, lit | +| Saves | the game autosaves a checkpoint and loads it again | +| First gameplay scene | renders characters, textures, sky and the sunlit exterior; HUD, pause menu and pad input work | +| Light in shadow | missing: ray-traced bounce light and shadows don't run yet, so anything out of direct sun is black | +| Frame rate in the world | 2-4 fps by default; about 10 fps in the first rooms with the newer switches, all off by default | -```powershell -python -I tools/verify_build.py --work "\work" # after runtime build -python -I tools/verify_build.py --work "\work" --require-gpu # after shaders + runtime -python -I tools/vulkan_probe.py # optional SDK / ICD check -``` +Known problems: -## How it works +- The first gameplay room is sometimes not drawn after the cutscene hands over to gameplay. +- Around 24 GB of memory is in use during play. +- Many changes are specific to this game and this GPU; some are marked `shortcut:` in the code. -| Piece | What it does | Where | -|---|---|---| -| Version check | Every package file's name, size and SHA-256 for each supported version | `game/`, `make_game.py` | -| Shader pipeline | Carves DXBC containers from `shaders.rpf` without its encrypted table of contents. Unpacks the `XBCH` → `FSSM` native RDNA2 program, disassembles it with LLVM (`gfx1013`) and translates it to SPIR-V | `tools/shader_carve.py`, `fssm_unpack.py`, `shader_disasm.py`, `rdna2spirv.py` | -| Asset export | Finds validated resources inside RPF9 archives and the loose `.ttpf` texture pools | `tools/rpf9dump` (on rpf9-explorer's Core) | -| Runtime | Maps the PE image, resolves imports to shims (GDK, XMem, `d3d12_xs`) | `runtime/` | -| Research tools | PE/RTTI inspection, raw carving, texture tiling probes, GPU test harnesses | `tools/`, `runtime/test/` | -| Post-build verify | PE self-map, Vulkan device, optional GPU draw | `tools/verify_build.py`, `tools/vulkan_env.py` | +The full measurement log, what each switch does and the debugging options are in +[docs/fork-notes.md](docs/fork-notes.md). -The translator's runtime contract (user SGPRs, push constants, memory model, bindless images, vertex fetch, -system values) and all the format notes are in [docs/design.md](docs/design.md). +## Getting started + +Requirements: Windows 10/11 x64, a CPU with AVX2, a Direct3D 12 GPU with shader model 6.6 and mesh shaders, Rust +(pinned in `rust-toolchain.toml`), and several GiB of free Windows commit at startup (if `crashes.log` reports +Windows error 1455, close other applications or make the paging file bigger). + +```powershell +cargo xtask install-hooks # asset-policy check on every commit +cargo test --workspace # needs no game data + +cargo build --release -p leonida +target\release\leonida.exe run --execute # asks for your game folder the first time +``` -## Want to help? +The first run asks for the folder of your copy of the game (the one with `MicrosoftGame.config` in it) and saves it to +`leonida.toml`, which git ignores. `leonida config` shows what is set, and `leonida.example.toml` lists the other +settings. -The biggest open pieces: +Saves, settings and `crashes.log` are kept in `%LOCALAPPDATA%\leonida\data`, derived data in +`%LOCALAPPDATA%\leonida\cache`. -- **Xbox D3D12 → Vulkan**: trace the game's real `d3d12_xs` calls, root-signature→user-SGPR mapping, remaining PSO/present paths (see [docs/d3d12_vulkan.md](docs/d3d12_vulkan.md)). -- **Audio decoding**: Opus/XMA2 streams in AWC banks to PCM. -- **Model layouts** the decoder rejects today. +Input: XInput pads. With none connected, the keyboard acts as a pad while the game's window has focus: -See [CONTRIBUTING.md](CONTRIBUTING.md). Never attach game files, extracted assets or generated shaders to issues or -pull requests. +| Keys | Pad | +|------|-----| +| W A S D / I J K L | left / right stick | +| arrows | D-pad | +| Enter, Backspace, X, Y | A, B, X, Y | +| Q / E, Z / C | shoulders, triggers | +| F / H | stick clicks | +| Esc, Tab | Menu, View | ## Contact @@ -149,17 +106,22 @@ pull requests. ## Credits -- [rpf9-explorer](https://github.com/breadbbbb/rpf9-explorer) by breadbbbb: the RPF9 model, texture-pool and AWC - decoders used by `tools/rpf9dump` (git submodule). -- [Mesa](https://gitlab.freedesktop.org/mesa/mesa) (MIT): GFX10 resource-descriptor layout (`tools/gfx10_formats.json`), - and the ACO/RADV rules used as reference for 16-bit results and shader system registers. -- [LLVM](https://llvm.org/): AMDGPU disassembler. +- **[victory-gta6](https://github.com/fxceless/victory-gta6)** by fxceless is the fork this repository continues + under the name Leonida Legacy, with its history kept. +- **[VIctory](https://github.com/Marvisak/VIctory)** by Marvisak and its contributors is the base of everything + here: the loader, the runtime services, the Direct3D 12 back end and the shader recompiler. +- **[XCL](https://github.com/ivall/xcl)** by ivall and its contributors (GPL-2.0-only) was used as a reference for + how the same game behaves under another layer. Fixes inspired by it were written anew in VIctory's code. +- The guard over every view of a memory page is code by **myokex** + ([victory-amd](https://github.com/myokex/victory-amd), commit `c6dc4d8`), which adapts pull request #115 by + Spexivus, its correction by joroyt and a part of VIctory #1122 by tightfall. The read-beside fix for kernel reads + into title memory is by **Joshua Odom** (commit `10ea38e` of the same fork family). - Logo: ["Grand Theft Auto VI" icon by SlyDevil](https://www.steamgriddb.com/icon/122618) on SteamGridDB. -- [SPIRV-Tools](https://github.com/KhronosGroup/SPIRV-Tools): assembly and validation. +- The victory-gta6 changes were developed with [Claude Code](https://claude.com/claude-code). Grand Theft Auto and all related names are trademarks of their owners. This project is not affiliated with or endorsed by them. ## License -GPLv3 (or any later version). See [LICENSE](LICENSE). Third-party code keeps its own license. +GPL-3.0-or-later, like victory-gta6 and VIctory. See [LICENSE](LICENSE). diff --git a/apps/leonida/Cargo.toml b/apps/leonida/Cargo.toml new file mode 100644 index 000000000..1df33b728 --- /dev/null +++ b/apps/leonida/Cargo.toml @@ -0,0 +1,34 @@ +[package] +name = "leonida" +description = "Command-line front end: inspect, census, convert, run." +version.workspace = true +edition.workspace = true +rust-version.workspace = true +license.workspace = true +publish.workspace = true + +[dependencies] +leonida-core.workspace = true +leonida-pe.workspace = true +leonida-loader.workspace = true +leonida-hle.workspace = true +leonida-shader = { workspace = true, features = ["host"] } +leonida-game.workspace = true +anyhow.workspace = true +blake3.workspace = true +memchr.workspace = true +clap.workspace = true +walkdir.workspace = true + +[features] +# Debug-level logs and the debugging switches (frame capture, stack dumps, +# the host debug layer, scripted keys). Off in a plain release build. +diagnostics = [ + "leonida-core/diagnostics", + "leonida-hle/diagnostics", + "leonida-loader/diagnostics", + "leonida-shader/diagnostics", +] + +[lints] +workspace = true diff --git a/apps/leonida/src/census.rs b/apps/leonida/src/census.rs new file mode 100644 index 000000000..bf0c33ed2 --- /dev/null +++ b/apps/leonida/src/census.rs @@ -0,0 +1,124 @@ +//! Which imports do titles need, and which do we cover? + +use std::collections::{BTreeMap, BTreeSet}; +use std::io::Read; +use std::path::{Path, PathBuf}; + +use anyhow::Result; +use leonida_hle::{HleResolver, HostPolicy}; +use leonida_loader::Provenance; +use leonida_pe::{ImageInfo, ImportSymbol}; + +#[derive(Default)] +struct DllStats { + functions: BTreeSet, + hle: usize, + host: usize, + missing: usize, + images: BTreeSet, +} + +pub fn run(paths: Vec, strict: bool, list_missing: bool) -> Result<()> { + let paths = crate::default_paths(paths)?; + let resolver = HleResolver::new(if strict { + HostPolicy::none() + } else { + HostPolicy::default() + }); + + let mut images = 0usize; + let mut failed = Vec::new(); + let mut dlls: BTreeMap = BTreeMap::new(); + let mut missing: BTreeMap<(String, String), BTreeSet> = BTreeMap::new(); + + for root in &paths { + for entry in walkdir::WalkDir::new(root) + .into_iter() + .filter_map(Result::ok) + { + let path = entry.path(); + if !entry.file_type().is_file() || !looks_like_pe(path) { + continue; + } + let info = match std::fs::read(path) + .map_err(anyhow::Error::from) + .and_then(|d| ImageInfo::parse(&d).map_err(anyhow::Error::from)) + { + Ok(info) => info, + Err(e) => { + failed.push((path.to_path_buf(), e.to_string())); + continue; + } + }; + images += 1; + for module in info.imports.iter().chain(&info.delay_imports) { + let key = module.dll.to_ascii_lowercase(); + let stats = dlls.entry(key.clone()).or_default(); + stats.images.insert(path.to_path_buf()); + for e in &module.entries { + let class = resolver.classify(&module.dll, &e.symbol); + if class.is_none() { + missing + .entry((key.clone(), e.symbol.to_string())) + .or_default() + .insert(path.to_path_buf()); + } + // Count each dll!function once across all images. + if stats.functions.insert(e.symbol.clone()) { + match class { + Some(Provenance::Hle) => stats.hle += 1, + Some(Provenance::Host) => stats.host += 1, + Some(Provenance::Title) => unreachable!("census maps no title DLLs"), + None => stats.missing += 1, + } + } + } + } + } + } + + println!("{images} images scanned, {} unreadable", failed.len()); + for (p, e) in &failed { + println!(" skipped {}: {e}", p.display()); + } + println!( + "\n{:<56} {:>6} {:>6} {:>6} {:>8} {:>7}", + "dll", "funcs", "hle", "host", "missing", "images" + ); + let (mut f, mut h, mut o, mut m) = (0, 0, 0, 0); + for (dll, s) in &dlls { + println!( + "{dll:<56} {:>6} {:>6} {:>6} {:>8} {:>7}", + s.functions.len(), + s.hle, + s.host, + s.missing, + s.images.len() + ); + f += s.functions.len(); + h += s.hle; + o += s.host; + m += s.missing; + } + println!("{:<56} {f:>6} {h:>6} {o:>6} {m:>8}", "TOTAL"); + + if list_missing { + let mut rows: Vec<_> = missing.into_iter().collect(); + rows.sort_by(|a, b| b.1.len().cmp(&a.1.len()).then_with(|| a.0.cmp(&b.0))); + println!("\nmissing (by number of images using it)"); + for ((dll, sym), users) in rows { + println!(" {:>4} {dll}!{sym}", users.len()); + } + } + Ok(()) +} + +/// Cheap pre-filter: an `MZ` header, regardless of extension (console +/// packages do not always use .exe/.dll). +fn looks_like_pe(path: &Path) -> bool { + let mut magic = [0u8; 2]; + std::fs::File::open(path) + .and_then(|mut f| f.read_exact(&mut magic)) + .is_ok() + && &magic == b"MZ" +} diff --git a/apps/leonida/src/inspect.rs b/apps/leonida/src/inspect.rs new file mode 100644 index 000000000..5875a3bf0 --- /dev/null +++ b/apps/leonida/src/inspect.rs @@ -0,0 +1,153 @@ +use std::collections::BTreeMap; +use std::path::Path; + +use anyhow::{Context, Result}; +use leonida_pe::implib::ImportLibrary; +use leonida_pe::{ImageInfo, layout}; + +pub fn run(file: &Path, list_imports: bool, list_exports: bool) -> Result<()> { + let data = std::fs::read(file).with_context(|| format!("reading {}", file.display()))?; + let info = ImageInfo::parse(&data).with_context(|| format!("parsing {}", file.display()))?; + + println!("file {}", file.display()); + println!("blake3 {}", blake3::hash(&data).to_hex()); + if let Some(cv) = &info.codeview { + println!("pdb {} (key {})", cv.pdb_path, cv.symbol_key()); + } + println!( + "kind {}", + if info.is_dll() { "dll" } else { "exe" } + ); + println!( + "subsystem {} ({})", + info.subsystem, + info.subsystem_name() + ); + println!( + "image base {:#x} size {:#x}", + info.image_base, info.size_of_image + ); + println!("entry rva {:#x}", info.entry_rva); + println!( + "stack reserve {:#x} commit {:#x}", + info.stack_reserve, info.stack_commit + ); + println!( + "dll flags {:#06x}{}", + info.dll_characteristics, + dll_flags(info.dll_characteristics) + ); + println!( + "relocations {} exception table {} load config {}", + yes(info.has_relocations), + yes(info.has_exception_table), + yes(info.has_load_config) + ); + if let Some(tls) = &info.tls { + println!("tls {} callback(s)", tls.callback_rvas.len()); + } + + println!("\nsections"); + for s in &info.sections { + println!( + " {:<8} rva {:#010x} vsize {:#010x} raw {:#010x} flags {:#010x}", + s.name.trim_end_matches('\0'), + s.rva, + s.virtual_size, + s.file_size, + s.characteristics + ); + } + + println!( + "\nimports {} functions from {} DLLs", + info.import_count(), + info.imports.len() + ); + for m in &info.imports { + println!(" {:<48} {:>5}", m.dll, m.entries.len()); + if list_imports { + for e in &m.entries { + println!(" {}", e.symbol); + } + } + } + if !info.delay_imports.is_empty() { + println!("\ndelay-load imports"); + for m in &info.delay_imports { + println!(" {:<48} {:>5}", m.dll, m.entries.len()); + if list_imports { + for e in &m.entries { + println!(" {}", e.symbol); + } + } + } + } + + println!("\nexports {}", info.exports.len()); + if list_exports { + for e in &info.exports { + let name = e.name.as_deref().unwrap_or("(by ordinal)"); + match (&e.rva, &e.forward) { + (_, Some(fwd)) => println!(" {:>5} {name} -> {fwd}", e.ordinal), + (Some(rva), _) => println!(" {:>5} {name} {rva:#x}", e.ordinal), + _ => println!(" {:>5} {name}", e.ordinal), + } + } + } + Ok(()) +} + +pub fn lib_exports(lib: &Path, list: bool) -> Result<()> { + let data = std::fs::read(lib).with_context(|| format!("reading {}", lib.display()))?; + let parsed = + ImportLibrary::parse(&data).with_context(|| format!("parsing {}", lib.display()))?; + let mut by_dll: BTreeMap> = BTreeMap::new(); + for i in &parsed.imports { + by_dll + .entry(i.dll.to_ascii_lowercase()) + .or_default() + .push(i.export.to_string()); + } + println!( + "{} exports from {} DLLs ({} other members)", + parsed.imports.len(), + by_dll.len(), + parsed.other_members + ); + for (dll, names) in &by_dll { + println!("{dll:<60} {:>5}", names.len()); + if list { + for n in names { + println!(" {n}"); + } + } + } + Ok(()) +} + +fn yes(b: bool) -> &'static str { + if b { "yes" } else { "no" } +} + +fn dll_flags(v: u16) -> String { + use layout::dll_flags::*; + let names = [ + (HIGH_ENTROPY_VA, "high-entropy-va"), + (DYNAMIC_BASE, "dynamic-base"), + (FORCE_INTEGRITY, "force-integrity"), + (NX_COMPAT, "nx"), + (APPCONTAINER, "appcontainer"), + (GUARD_CF, "cfg"), + ]; + let set: Vec<_> = names + .iter() + .filter(|(f, _)| v & f != 0) + .map(|(_, n)| *n) + .collect(); + if set.is_empty() { + String::new() + } else { + format!(" ({})", set.join(", ")) + } +} diff --git a/apps/leonida/src/main.rs b/apps/leonida/src/main.rs new file mode 100644 index 000000000..e561b60be --- /dev/null +++ b/apps/leonida/src/main.rs @@ -0,0 +1,330 @@ +//! `leonida`: the command-line front end. +//! +//! Every command reads the user's own files and writes only to stdout or to +//! the user's cache directory (outside the repository). + +mod census; +mod inspect; +mod run; +mod shader; +mod translate; + +use std::path::PathBuf; + +use anyhow::{Context, Result}; +use clap::{Parser, Subcommand, ValueEnum}; + +#[derive(Parser)] +#[command( + name = "leonida", + version, + about = "Run an Xbox Series title natively on Windows" +)] +struct Cli { + #[command(subcommand)] + command: Command, +} + +#[derive(Subcommand)] +enum Command { + /// Summarise one PE image: headers, sections, imports, TLS, build id. + Inspect { + file: PathBuf, + /// List every imported function. + #[arg(long)] + imports: bool, + /// List every exported function. + #[arg(long)] + exports: bool, + }, + /// Aggregate the imports of every PE image under the given paths and + /// show which ones our runtime covers. Defaults to the configured + /// game and test-title directories. + Census { + paths: Vec, + /// Do not count host pass-through as covered. + #[arg(long)] + strict: bool, + /// List every missing `dll!function`, most used first. + #[arg(long)] + missing: bool, + }, + /// List the `dll!export` pairs an import library describes. + LibExports { + lib: PathBuf, + /// List every export, not just per-DLL counts. + #[arg(long)] + list: bool, + }, + /// Find shader containers in files or directories (also inside engine + /// archives, if uncompressed) and report their layout. + ShaderInfo { + paths: Vec, + /// Print one line per container found. + #[arg(long)] + verbose: bool, + /// Also list the decoded native instructions (implies --verbose). + #[arg(long)] + disasm: bool, + }, + /// Run every shader found (containers, SGD5 files) through the + /// translator and report what it cannot handle yet. + Translate { + paths: Vec, + /// Check emitted DXIL with dxil.dll's validator (`LEONIDA_DXIL`, + /// else the newest Windows SDK's). + #[arg(long)] + validate: bool, + /// Also create a host D3D12 pipeline for each emitted shader. + #[arg(long)] + pipelines: bool, + /// Print one line per program and outcome. + #[arg(long)] + list: bool, + /// Worker threads (default: every logical core). + #[arg(long)] + jobs: Option, + /// Warm the run's shader cache: a file of shader hashes (the 16 + /// hex digits a run's log names a shader by, anywhere in a line); + /// the containers with those hashes are translated into the + /// cache and nothing else is done. Set `LEONIDA_HOST_WAVE` and + /// `LEONIDA_VIEW_LIMIT` to what the run's log says of the host. + #[arg(long)] + warm: Option, + }, + /// Prepare, map and bind a title executable; with --execute, run it. + Run { + /// The title's executable. Default: the one the game folder's + /// MicrosoftGame.config names (the folder is asked for once and + /// saved to leonida.toml). + exe: Option, + /// What unimplemented imports do when called. + #[arg(long, value_enum, default_value_t = Unimplemented::Trap)] + unimplemented: Unimplemented, + /// Disable host pass-through (everything must be implemented by us). + #[arg(long)] + strict: bool, + /// Actually start the title. Without it, stop after binding. + #[arg(long)] + execute: bool, + /// The console model the title sees (device type, memory). + #[arg(long, value_enum, default_value_t = Console::SeriesX)] + console: Console, + /// Arguments for the title, after `--` (it reads the whole command + /// line; a title that relaunches itself passes some). + #[arg(last = true)] + title_args: Vec, + }, + /// Show the resolved configuration and check it. + Config, +} + +#[derive(Clone, Copy, ValueEnum)] +enum Unimplemented { + Trap, + Zero, +} + +#[derive(Clone, Copy, ValueEnum)] +enum Console { + SeriesX, + SeriesS, +} + +fn main() -> Result<()> { + leonida_core::logging::init("info"); + // The audio recorder `run` starts for `LEONIDA_AUDIO_CAPTURE`. + #[cfg(all(windows, feature = "diagnostics"))] + if leonida_hle::modules::audio::capture::child() { + return Ok(()); + } + let cli = Cli::parse(); + match cli.command { + Command::Inspect { + file, + imports, + exports, + } => inspect::run(&file, imports, exports), + Command::Census { + paths, + strict, + missing, + } => census::run(paths, strict, missing), + Command::LibExports { lib, list } => inspect::lib_exports(&lib, list), + Command::ShaderInfo { + paths, + verbose, + disasm, + } => shader::run(paths, verbose || disasm, disasm), + Command::Translate { + paths, + validate, + pipelines, + list, + jobs, + warm, + } => { + // `LEONIDA_VIEW_LIMIT=`: translate as on a host whose view heap is capped + if let Some(n) = std::env::var("LEONIDA_VIEW_LIMIT").ok().and_then(|v| v.parse().ok()) { + leonida_shader::emit::set_view_heap_limit(n); + } + // `LEONIDA_HOST_WAVE=32`: translate as for a GPU whose waves are at most 32 lanes + if let Some(n) = std::env::var("LEONIDA_HOST_WAVE").ok().and_then(|v| v.parse().ok()) { + leonida_shader::emit::set_host_max_wave(n); + } + if let Some(file) = warm { + return translate::warm(paths, &file, jobs); + } + translate::run(paths, validate, pipelines, list, jobs) + } + Command::Run { + exe, + unimplemented, + strict, + execute, + console, + title_args: _, + } => { + let exe = match exe { + Some(exe) => exe, + None => default_exe()?, + }; + run::run(&exe, unimplemented, strict, execute, console) + } + Command::Config => show_config(), + } +} + +/// The executable the game folder's MicrosoftGame.config names. With no +/// folder configured and a terminal to ask in, the folder is asked for and +/// saved to the config file. +fn default_exe() -> Result { + use std::io::IsTerminal; + let cfg = leonida_core::Config::load()?; + let dir = if let Some(dir) = cfg.game_dir.clone() { + dir + } else if std::io::stdin().is_terminal() { + ask_game_dir()? + } else { + cfg.require_game_dir()?.to_owned() + }; + let manifest = dir.join("MicrosoftGame.config"); + let text = std::fs::read_to_string(&manifest) + .with_context(|| format!("reading {}", manifest.display()))?; + let name = manifest_exe(&text) + .with_context(|| format!("{} names no executable", manifest.display()))?; + Ok(dir.join(name)) +} + +/// Asks for the game folder until one with a MicrosoftGame.config is given, +/// then saves it. +fn ask_game_dir() -> Result { + use std::io::{BufRead, Write}; + println!("No game folder is set. Enter the folder of your copy of the game"); + println!("(the one with MicrosoftGame.config in it):"); + loop { + print!("> "); + std::io::stdout().flush()?; + let mut line = String::new(); + if std::io::stdin().lock().read_line(&mut line)? == 0 { + anyhow::bail!("no game folder given"); + } + let dir = PathBuf::from(line.trim().trim_matches('"')); + if dir.as_os_str().is_empty() { + continue; + } + if !dir.join("MicrosoftGame.config").is_file() { + println!("no MicrosoftGame.config in {}, try again:", dir.display()); + continue; + } + if let Err(e) = leonida_core::ensure_outside_repo(&dir) { + println!("{e}"); + continue; + } + let saved = leonida_core::Config::save_game_dir(&dir)?; + println!("game folder saved to {}", saved.display()); + return Ok(dir); + } +} + +/// The `Name` of the manifest's first `` element (not +/// ``, which holds them). +fn manifest_exe(manifest: &str) -> Option<&str> { + let mut rest = manifest; + while let Some(start) = rest.find("')?]; + let (at, _) = tag + .match_indices("Name=\"") + .find(|(i, _)| tag[..*i].ends_with(char::is_whitespace))?; + let value = &tag[at + "Name=\"".len()..]; + let name = &value[..value.find('"')?]; + return (!name.is_empty()).then_some(name); + } + None +} + +fn show_config() -> Result<()> { + let cfg = leonida_core::Config::load()?; + let status = |p: &Option| match p { + Some(p) if p.exists() => format!("{}", p.display()), + Some(p) => format!("{} (does not exist)", p.display()), + None => "(not set)".to_owned(), + }; + println!( + "config file : {}", + cfg.source + .as_ref() + .map_or("(none)".into(), |p| p.display().to_string()) + ); + println!("game_dir : {}", status(&cfg.game_dir)); + println!("cache_dir : {}", cfg.cache_dir.display()); + println!("data_dir : {}", cfg.data_dir.display()); + for t in &cfg.test_titles { + println!("test_title : {}", status(&Some(t.clone()))); + } + for p in cfg + .game_dir + .iter() + .chain(&cfg.test_titles) + .chain([&cfg.cache_dir, &cfg.data_dir]) + { + if let Err(e) = leonida_core::ensure_outside_repo(p) { + println!("POLICY VIOLATION: {e}"); + } + } + Ok(()) +} + +/// Paths given on the command line, or the configured game + test titles. +pub(crate) fn default_paths(paths: Vec) -> Result> { + if !paths.is_empty() { + return Ok(paths); + } + let cfg = leonida_core::Config::load()?; + let all: Vec = cfg.game_dir.into_iter().chain(cfg.test_titles).collect(); + anyhow::ensure!( + !all.is_empty(), + "no paths given and none configured (see leonida.example.toml)" + ); + Ok(all) +} + +#[cfg(test)] +mod tests { + use super::manifest_exe; + + #[test] + fn manifest_exe_is_the_first_executable() { + let text = r#""#; + assert_eq!(manifest_exe(text), Some("title.exe")); + assert_eq!(manifest_exe(""), None); + assert_eq!(manifest_exe(r#""#), None); + assert_eq!(manifest_exe(""), Some("a.exe")); + } +} diff --git a/apps/leonida/src/run.rs b/apps/leonida/src/run.rs new file mode 100644 index 000000000..c58cd2aa8 --- /dev/null +++ b/apps/leonida/src/run.rs @@ -0,0 +1,344 @@ +use std::path::Path; + +use anyhow::{Context, Result}; + +use crate::{Console, Unimplemented}; + +#[cfg(windows)] +pub fn run( + exe: &Path, + unimplemented: Unimplemented, + strict: bool, + execute: bool, + console: Console, +) -> Result<()> { + use std::sync::Arc; + use leonida_hle::{HleResolver, HostPolicy}; + use leonida_loader::{BindReport, UnimplementedPolicy, WithTitleDlls}; + + // A title that relaunched itself: the old process must be gone first. + leonida_hle::modules::lifecycle::wait_for_previous(); + let cfg = leonida_core::Config::load()?; + let original = std::fs::read(exe).with_context(|| format!("reading {}", exe.display()))?; + let prepared = leonida_loader::prepare(&original)?; + let hash = prepared.original_hash.to_hex(); + match leonida_game::identify(&hash) { + Some(build) => println!("build {} ({hash})", build.label), + None => println!("build unknown ({hash})"), + } + + let images = cfg.cache_subdir("images")?; + leonida_hle::modules::d3d12x::use_shader_cache(cfg.cache_subdir("shaders")?); + let image = leonida_loader::load(&prepared, &images)?; + // The program is mapped from the copy `load` wrote: the file's bytes + // and their patched copy are not read again, and were held for the + // whole run (two blocks of 114.7 MB each for the title, in + // physical memory: run 65's memory map). + drop(prepared); + drop(original); + leonida_hle::runtime::set_main_image(image.base()); + leonida_hle::runtime::set_image_path(image.base(), exe); + println!( + "mapped at {:#x} (preferred {:#x})", + image.base(), + image.info().image_base + ); + let resolver = HleResolver::new(if strict { + HostPolicy::none() + } else { + HostPolicy::default() + }); + let wanted = |dll: &str| title_dll(&resolver.host, dll); + let title_dir = exe.parent().unwrap_or(Path::new(".")); + // A missing manifest leaves id 0 and no storage quota. + let manifest = + std::fs::read_to_string(title_dir.join("MicrosoftGame.config")).unwrap_or_default(); + let title = leonida_hle::runtime::Title::from_manifest(&manifest); + let storage = cfg.data_subdir(&format!("{:08X}/storage", title.id))?; + println!( + "title {:08X}, storage {} ({} MB)", + title.id, + storage.display(), + title.storage_bytes >> 20 + ); + // The console's fixed drives: the package as `G:`, temporary files `T:`. + leonida_hle::modules::files::mount_at('G', title_dir); + let temp = cfg.data_subdir(&format!("{:08X}/temp", title.id))?; + leonida_hle::modules::files::mount_at('T', &temp); + leonida_hle::runtime::set_title(leonida_hle::runtime::Title { storage, ..title }); + leonida_hle::console::set(match console { + Console::SeriesX => leonida_hle::console::Console::SeriesX, + Console::SeriesS => leonida_hle::console::Console::SeriesS, + }); + println!("console {}", leonida_hle::console::current().name()); + let dlls = leonida_loader::load_title_dlls(image.info(), title_dir, &images, &wanted)?; + for (name, dll) in &dlls { + println!("title dll {name} at {:#x}", dll.base()); + leonida_hle::runtime::set_image_path(dll.base(), &title_dir.join(name)); + } + + let policy = match unimplemented { + Unimplemented::Trap => UnimplementedPolicy::Trap, + Unimplemented::Zero => UnimplementedPolicy::ReturnZero, + }; + let with_dlls = WithTitleDlls { + inner: &resolver, + dlls: &dlls, + }; + let show = |name: &str, report: BindReport| { + println!( + "bound {name}: {} hle, {} host, {} title, {} missing", + report.hle, + report.host, + report.title, + report.missing.len() + ); + for m in &report.missing { + println!(" missing {}!{}", m.dll, m.symbol); + } + }; + for (name, dll) in &dlls { + show(name, dll.bind_imports(&with_dlls, policy)?); + } + let exe_name = exe.file_name().unwrap_or_default().to_string_lossy(); + show(&exe_name, image.bind_imports(&with_dlls, policy)?); + if !execute { + println!("not executing (pass --execute to start the title)"); + return Ok(()); + } + leonida_loader::report_crashes(); + leonida_loader::log_crashes_to(temp.with_file_name("crashes.log")); + leonida_hle::runtime::use_console_timers(); + #[cfg(feature = "diagnostics")] + diagnostics(&image, &cfg); + let late = LateDlls { + host: resolver.host.clone(), + title_dir: title_dir.to_owned(), + cache_dir: images, + policy, + mapped: std::sync::Mutex::new(dlls.clone()), + lock: LoaderLock::default(), + }; + leonida_hle::runtime::set_title_dll_loader(Box::new(move |file| { + late.load(file, show).map_err(|e| format!("{e:#}")) + })); + // SAFETY: imports are bound; from here on we run title code. + let main = unsafe { Arc::new(image).spawn_main(dlls)? }; + let code = main + .join() + .map_err(|_| anyhow::anyhow!("title main thread panicked"))??; + println!("title exited with {code}"); + Ok(()) +} + +/// The debugging aids (README): scheduled stack dumps, watched values and +/// memory saved on a crash. +#[cfg(all(windows, feature = "diagnostics"))] +fn diagnostics(image: &leonida_loader::LoadedImage, cfg: &leonida_core::Config) { + leonida_loader::dump_stacks_on_schedule(); + leonida_hle::modules::audio::capture::start(); + watch(image.base(), image.info().size_of_image as usize); + // Debugging aid: `LEONIDA_CRASH_SAVE=:,...` (hex) writes those + // title ranges to `crash-.bin` in the cache dir on a crash. + let size = image.info().size_of_image as usize; + let ranges = std::env::var("LEONIDA_CRASH_SAVE").unwrap_or_default(); + let hex = |s: &str| usize::from_str_radix(s.trim().trim_start_matches("0x"), 16).ok(); + leonida_loader::save_on_crash( + ranges + .split(',') + .filter_map(|r| r.split_once(':')) + .filter_map(|(rva, len)| Some((hex(rva)?, hex(len)?))) + .filter(|&(rva, len)| rva.checked_add(len).is_some_and(|end| end <= size)) + .map(|(rva, len)| { + let file = cfg.cache_dir.join(format!("crash-{rva:x}.bin")); + (image.base() + rva, len, file) + }) + .collect(), + ); +} + +/// Debugging aid: `LEONIDA_WATCH=,...` (hex) logs the u32 at each +/// title+rva whenever it changes, polled every 5 ms (an engine's state, say). +#[cfg(all(windows, feature = "diagnostics"))] +fn watch(base: usize, size: usize) { + let Ok(list) = std::env::var("LEONIDA_WATCH") else { + return; + }; + let rvas: Vec = list + .split(',') + .filter_map(|r| usize::from_str_radix(r.trim().trim_start_matches("0x"), 16).ok()) + .filter(|&rva| rva + 4 <= size) + .collect(); + std::thread::spawn(move || { + let mut seen = vec![None; rvas.len()]; + loop { + for (&rva, seen) in rvas.iter().zip(&mut seen) { + // SAFETY: four bytes inside the mapped image, checked above. + let value = unsafe { ((base + rva) as *const u32).read_volatile() }; + if *seen != Some(value) { + eprintln!("Leonida Legacy: title+{rva:#x} = {value:#x}"); + *seen = Some(value); + } + } + std::thread::sleep(std::time::Duration::from_millis(5)); + } + }); +} + +/// DLLs the host or our runtime provide are never taken from the title. +#[cfg(windows)] +fn title_dll(host: &leonida_hle::HostPolicy, dll: &str) -> bool { + !host.allows(dll) && !leonida_hle::registry().iter().any(|m| m.serves(dll)) +} + +/// Title DLLs the title loads itself (`LoadLibrary`) that nothing imports, +/// e.g. The title's upscaler behind its FidelityFX loader. +#[cfg(windows)] +struct LateDlls { + host: leonida_hle::HostPolicy, + title_dir: std::path::PathBuf, + cache_dir: std::path::PathBuf, + policy: leonida_loader::UnimplementedPolicy, + /// Every title DLL mapped so far, to bind new ones against. + mapped: std::sync::Mutex>, + lock: LoaderLock, +} + +#[cfg(windows)] +impl LateDlls { + /// Every `LoadLibrary` of the title comes here first. Returns a title + /// image called `file`, mapping it and the title DLLs it needs first, + /// binding them and running their `DllMain` on the calling thread, as + /// the Windows loader would; `None` if `file` is no title image. + fn load( + &self, + file: &str, + show: impl Fn(&str, leonida_loader::BindReport), + ) -> Result> { + use leonida_hle::runtime::{forget_image, image_named, set_image_path}; + // Waits while another thread initialises a DLL; a `DllMain` that + // loads another DLL re-enters. + self.lock.hold(|| { + if let Some(base) = image_named(file) { + return Ok(Some(base)); + } + let new = { + let mut mapped = self.mapped.lock().unwrap_or_else(|e| e.into_inner()); + let wanted = |dll: &str| title_dll(&self.host, dll) && image_named(dll).is_none(); + let new = leonida_loader::load_title_dll( + file, + &self.title_dir, + &self.cache_dir, + &wanted, + )?; + let hle = leonida_hle::HleResolver::new(self.host.clone()); + let old = leonida_loader::WithTitleDlls { + inner: &hle, + dlls: &mapped, + }; + let resolver = leonida_loader::WithTitleDlls { + inner: &old, + dlls: &new, + }; + for (name, dll) in &new { + println!( + "title dll {name} at {:#x} (loaded by the title)", + dll.base() + ); + show(name, dll.bind_imports(&resolver, self.policy)?); + set_image_path(dll.base(), &self.title_dir.join(name)); + } + // Visible before their `DllMain`s run, which may load more. + mapped.extend(new.iter().cloned()); + new + }; + let failed = new.iter().enumerate().find_map(|(i, (name, dll))| { + // SAFETY: bound above, dependencies attached first. + let attached = unsafe { dll.attach() }; + attached + .err() + .map(|e| (i, e.context(format!("attaching {name}")))) + }); + let Some((i, error)) = failed else { + return Ok(new.last().map(|(_, dll)| dll.base())); + }; + // As `LoadLibrary` does when a `DllMain` fails: detach what this + // load attached (the failed one too) and unmap all of it. + let bases: Vec<_> = new.iter().map(|(_, d)| d.base()).collect(); + self.mapped + .lock() + .unwrap_or_else(|e| e.into_inner()) + .retain(|(_, d)| !bases.contains(&d.base())); + for (_, done) in new[..=i].iter().rev() { + // SAFETY: attached (or failing to) on this thread just now. + unsafe { done.detach() }; + } + for (_, dll) in new { + forget_image(dll.base()); + // SAFETY: detached, and no title code holds it yet. + unsafe { dll.unload() }; + } + Err(error) + }) + } +} + +/// The Windows loader lock's shape: one thread at a time, re-entered by +/// the thread that holds it. +#[cfg(windows)] +#[derive(Default)] +struct LoaderLock { + owner: std::sync::Mutex<(Option, usize)>, + free: std::sync::Condvar, +} + +#[cfg(windows)] +impl LoaderLock { + fn hold(&self, f: impl FnOnce() -> T) -> T { + let me = std::thread::current().id(); + let lock = || self.owner.lock().unwrap_or_else(|e| e.into_inner()); + { + let mut owner = lock(); + while owner.0.is_some_and(|o| o != me) { + owner = self.free.wait(owner).unwrap_or_else(|e| e.into_inner()); + } + *owner = (Some(me), owner.1 + 1); + } + let result = f(); + let mut owner = lock(); + owner.1 -= 1; + if owner.1 == 0 { + owner.0 = None; + self.free.notify_one(); + } + result + } +} + +#[cfg(all(test, windows))] +mod tests { + use std::sync::{Arc, Mutex}; + + #[test] + fn loader_lock_is_reentrant_and_exclusive() { + let lock = Arc::new(super::LoaderLock::default()); + assert_eq!(lock.hold(|| lock.hold(|| 7)), 7); + let order = Arc::new(Mutex::new(Vec::new())); + let other = lock.hold(|| { + let (theirs, their_order) = (lock.clone(), order.clone()); + let other = std::thread::spawn(move || { + theirs.hold(|| their_order.lock().unwrap().push(2)); + }); + std::thread::sleep(std::time::Duration::from_millis(50)); + order.lock().unwrap().push(1); + other + }); + other.join().unwrap(); + assert_eq!(*order.lock().unwrap(), [1, 2]); + } +} + +#[cfg(not(windows))] +pub fn run(_: &Path, _: Unimplemented, _: bool, _: bool, _: Console) -> Result<()> { + anyhow::bail!("running titles requires Windows") +} diff --git a/apps/leonida/src/shader.rs b/apps/leonida/src/shader.rs new file mode 100644 index 000000000..7f8f38d6f --- /dev/null +++ b/apps/leonida/src/shader.rs @@ -0,0 +1,227 @@ +//! Survey shader containers: bitcode, console additions and native code. + +use std::borrow::Cow; +use std::collections::BTreeMap; +use std::path::PathBuf; + +use anyhow::Result; +use leonida_game::sgd5; +use leonida_shader::gfx10::{self, Instruction}; +use leonida_shader::{Container, DxilProgram, FourCC, HwStage, ShaderError, native_programs}; + +/// Files above this size are skipped (read whole into memory for now). +pub(crate) const MAX_FILE: u64 = 2 << 30; + +/// A shader container in a file: as is, or packed in an SGD5 record. +pub(crate) enum Source<'a> { + Raw { offset: usize, data: &'a [u8] }, + Packed(sgd5::Record<'a>), +} + +impl Source<'_> { + /// The container bytes; `None` if a packed record is corrupt. + pub(crate) fn bytes(&self) -> Option> { + match self { + Source::Raw { data, .. } => Some(Cow::Borrowed(data)), + Source::Packed(r) => r.unpack().map(Cow::Owned), + } + } + + pub(crate) fn label(&self) -> String { + match self { + Source::Raw { offset, .. } => format!("@{offset:#x}"), + Source::Packed(r) => format!("@{:#x} {}", r.offset, r.name.unwrap_or("?")), + } + } +} + +/// The packed records of SGD5 data, and every container stored as is (the +/// executable keeps some records uncompressed), found by its magic. +pub(crate) fn sources(data: &[u8]) -> Vec> { + let mut out: Vec> = Vec::new(); + if sgd5::is_sgd5(data) { + out.extend(sgd5::records(data).map(Source::Packed)); + } + let raw = memchr::memmem::find_iter(data, b"DXBC") + .filter(|&offset| Container::parse(&data[offset..]).is_ok()) + .map(|offset| Source::Raw { + offset, + data: &data[offset..], + }); + out.extend(raw); + out +} + +#[derive(Default)] +struct Totals { + containers: usize, + with_dxil_part: usize, + with_bitcode: usize, + standard_layout: usize, + xdat: usize, + xbop: usize, + kinds: BTreeMap, + with_native: usize, + native_stages: BTreeMap, + native_errors: BTreeMap, + decoded: usize, + instructions: usize, + unnamed: BTreeMap, + decode_errors: BTreeMap<&'static str, usize>, + files_with_shaders: usize, +} + +pub fn run(paths: Vec, verbose: bool, disasm: bool) -> Result<()> { + let paths = crate::default_paths(paths)?; + let mut t = Totals::default(); + for root in &paths { + for entry in walkdir::WalkDir::new(root) + .into_iter() + .filter_map(Result::ok) + { + if !entry.file_type().is_file() { + continue; + } + let path = entry.path(); + if entry.metadata().map(|m| m.len()).unwrap_or(0) > MAX_FILE { + eprintln!("skipping large file {}", path.display()); + continue; + } + let Ok(data) = std::fs::read(path) else { + continue; + }; + let mut found_here = 0; + for source in sources(&data) { + let Some(bytes) = source.bytes() else { + eprintln!("corrupt record {}{}", path.display(), source.label()); + continue; + }; + let Ok(container) = Container::parse(&bytes) else { + continue; + }; + found_here += 1; + t.containers += 1; + let dxil = container.part(FourCC::DXIL); + t.with_dxil_part += usize::from(dxil.is_some()); + let program = dxil.and_then(|p| DxilProgram::parse(p.data).ok()); + let mut listing = Vec::new(); + // Independent of the bitcode: titles may strip it. + let native = match dxil.map(|p| native_programs(p.data)) { + Some(Ok(programs)) if !programs.is_empty() => { + t.with_native += 1; + let mut list = Vec::new(); + for n in &programs { + *t.native_stages.entry(n.stage).or_default() += 1; + list.push(format!("{:?} {} B", n.stage, n.code.len())); + match gfx10::decode(&n.code) { + Ok(insts) => { + t.decoded += 1; + t.instructions += insts.len(); + for i in insts.iter().filter(|i| i.name().is_none()) { + let key = format!("{:?} {:#x}", i.encoding, i.opcode); + *t.unnamed.entry(key).or_default() += 1; + } + if disasm { + listing + .extend(n.layout.iter().map(|p| format!(" {p:?}"))); + listing.extend(n.used.iter().map(|u| format!(" {u:?}"))); + listing.extend( + insts.iter().map(|i| format_instruction(i, n.wave64)), + ); + } + } + Err(e) => { + let reason = match e { + ShaderError::Isa { reason, .. } => reason, + _ => "other", + }; + *t.decode_errors.entry(reason).or_default() += 1; + list.push(format!("({e})")); + } + } + } + format!(", native {}", list.join(" ")) + } + Some(Err(e)) => { + *t.native_errors.entry(e.to_string()).or_default() += 1; + format!(", native: {e}") + } + _ => String::new(), + }; + let line = match &program { + Some(p) => { + t.with_bitcode += 1; + let x = p.xbox_extras(); + t.standard_layout += usize::from(p.is_standard_layout()); + t.xdat += usize::from(x.xdat); + t.xbop += usize::from(x.xbop); + *t.kinds.entry(format!("{:?}", p.kind)).or_default() += 1; + format!( + "{:?} sm{}.{} bitcode {} B, xdat {}, xbop {}", + p.kind, + p.shader_model.0, + p.shader_model.1, + p.bitcode.len(), + x.xdat, + x.xbop + ) + } + None => "no parsable DXIL program".to_owned(), + } + &native; + if verbose { + println!("{}{}: {line}", path.display(), source.label()); + for l in &listing { + println!("{l}"); + } + } + } + t.files_with_shaders += usize::from(found_here > 0); + } + } + println!( + "containers found {} (in {} files)", + t.containers, t.files_with_shaders + ); + println!(" with DXIL part {}", t.with_dxil_part); + println!(" with LLVM bitcode {}", t.with_bitcode); + println!(" PC-standard layout {}", t.standard_layout); + println!(" XDAT prefix {}", t.xdat); + println!(" xbop trailer {}", t.xbop); + for (k, n) in &t.kinds { + println!(" {k:<20} {n}"); + } + println!(" with native code {}", t.with_native); + for (stage, n) in &t.native_stages { + println!(" {:<18} {n}", format!("{stage:?}")); + } + for (e, n) in &t.native_errors { + println!(" native unreadable {n}: {e}"); + } + if t.with_native > 0 { + println!( + " decoded programs {} ({} instructions)", + t.decoded, t.instructions + ); + for (e, n) in &t.decode_errors { + println!(" decode failed {n}: {e}"); + } + let mut unnamed: Vec<_> = t.unnamed.iter().collect(); + unnamed.sort_by_key(|&(_, n)| std::cmp::Reverse(*n)); + for (op, n) in unnamed.iter().take(10) { + println!(" opcode not in table {op} x{n}"); + } + } + if t.containers == 0 { + println!("(none found: shaders may sit in compressed or encrypted archives)"); + } + Ok(()) +} + +fn format_instruction(i: &Instruction, wave64: bool) -> String { + let words: Vec<_> = i.words.iter().map(|w| format!("{w:08X}")).collect(); + let text = match i.name() { + Some(_) => i.text(wave64), + None => format!("<{:?} {:#x}>", i.encoding, i.opcode), + }; + format!(" {:06x}: {:<44} {text}", i.offset, words.join(" ")) +} diff --git a/apps/leonida/src/translate.rs b/apps/leonida/src/translate.rs new file mode 100644 index 000000000..a71772571 --- /dev/null +++ b/apps/leonida/src/translate.rs @@ -0,0 +1,866 @@ +//! The offline batch: every shader found goes through the translator, and +//! what it cannot handle yet is tallied (decision 0003). + +use std::collections::{BTreeMap, HashSet}; +use std::path::{Path, PathBuf}; +use std::sync::Mutex; +use std::sync::atomic::{AtomicUsize, Ordering}; + +use anyhow::Result; +use leonida_shader::emit::host::{self, Host}; +use leonida_shader::emit::{self, validator::Validator}; +use leonida_shader::structure::{self, Atom, LaneExit}; +use leonida_shader::{ + Container, FourCC, HwStage, NativeProgram, RootType, ShaderError, ir, native_programs, +}; +use leonida_shader::{io, resource}; + +use crate::shader::{MAX_FILE, Source, sources}; + +#[derive(Default)] +struct Tally { + containers: usize, + duplicates: usize, + programs: usize, + translated: usize, + instructions: usize, + structured: usize, + vector: usize, + guarded: usize, + /// Guards that read a mask the pass cannot see into. + opaque: usize, + lane_branches: usize, + uniform_branches: usize, + tracked: usize, + loaded: usize, + built: usize, + constant: usize, + /// Descriptors and scalar accesses with a computed address term. + dynamic: usize, + scalar: usize, + used: usize, + /// Used-resource entries whose root parameter no descriptor traces + /// to, by resource and root type. + untraced_used: BTreeMap, + /// Root parameters descriptors trace to that no used entry names. + unlisted: usize, + /// Vertex and pixel programs, and those whose I/O was raised. + io_programs: usize, + io_raised: usize, + interpolated: usize, + vertex_values: usize, + /// Exports by target kind. + exports: BTreeMap<&'static str, usize>, + /// Exports still packed as f16 pairs after the export patch. + compressed: usize, + /// Vertex and pixel programs every earlier stage handled, and how far + /// emission got with them. + emit_programs: usize, + emitted: usize, + validated: usize, + pipelines: usize, + /// The same for compute programs. + cs_programs: usize, + cs_emitted: usize, + cs_validated: usize, + cs_pipelines: usize, + /// The same for mesh programs. + ms_programs: usize, + ms_emitted: usize, + ms_validated: usize, + ms_pipelines: usize, + /// Reason → programs stopped by it, and the first one. + failed: BTreeMap, + /// With `--list`: one line per program and outcome. + list: bool, + lines: Vec, +} + +impl Tally { + fn fail(&mut self, reason: String, example: impl FnOnce() -> String) { + if self.list { + let e = example(); + self.lines.push(format!("{e} {reason}")); + self.failed.entry(reason).or_insert((0, e)).0 += 1; + return; + } + self.failed + .entry(reason) + .or_insert_with(|| (0, example())) + .0 += 1; + } + + fn merge(&mut self, other: Tally) { + self.containers += other.containers; + self.duplicates += other.duplicates; + self.programs += other.programs; + self.translated += other.translated; + self.instructions += other.instructions; + self.structured += other.structured; + self.vector += other.vector; + self.guarded += other.guarded; + self.opaque += other.opaque; + self.lane_branches += other.lane_branches; + self.uniform_branches += other.uniform_branches; + self.tracked += other.tracked; + self.loaded += other.loaded; + self.built += other.built; + self.constant += other.constant; + self.dynamic += other.dynamic; + self.scalar += other.scalar; + self.used += other.used; + for (k, n) in other.untraced_used { + *self.untraced_used.entry(k).or_default() += n; + } + self.unlisted += other.unlisted; + self.io_programs += other.io_programs; + self.io_raised += other.io_raised; + self.interpolated += other.interpolated; + self.vertex_values += other.vertex_values; + self.compressed += other.compressed; + self.emit_programs += other.emit_programs; + self.emitted += other.emitted; + self.validated += other.validated; + self.pipelines += other.pipelines; + self.cs_programs += other.cs_programs; + self.cs_emitted += other.cs_emitted; + self.cs_validated += other.cs_validated; + self.cs_pipelines += other.cs_pipelines; + self.ms_programs += other.ms_programs; + self.ms_emitted += other.ms_emitted; + self.ms_validated += other.ms_validated; + self.ms_pipelines += other.ms_pipelines; + for (k, n) in other.exports { + *self.exports.entry(k).or_default() += n; + } + self.lines.extend(other.lines); + for (reason, (n, example)) in other.failed { + self.failed.entry(reason).or_insert((0, example)).0 += n; + } + } +} + +/// Emitted shaders by label, shared between threads. +type Kept = std::sync::Arc>>; + +/// The optional checks after emission, one set per thread. +struct Checks { + /// Shaders named in `LEONIDA_PAIRS` (`vs+ps,...`, label substrings), + /// kept to build those pipelines after the walk. + keep: Option, + validator: Option, + host: Option<(Host, emit::HostShader)>, +} + +/// `translate --warm `: the containers whose hash the file names are +/// translated into the run's shader cache, on `jobs` threads; nothing is +/// made on the GPU. A run of the title then finds them there instead of +/// translating each at its first use. +pub fn warm(paths: Vec, file: &Path, jobs: Option) -> Result<()> { + // `--warm all`: every container found, whatever its hash. + let all = file.as_os_str() == "all"; + let mut wanted: HashSet = HashSet::new(); + if !all { + let text = std::fs::read_to_string(file)?; + for line in text.lines() { + for word in line.split(|c: char| !c.is_ascii_hexdigit()) { + if word.len() == 16 { + wanted.insert(word.to_ascii_lowercase()); + } + } + } + anyhow::ensure!(!wanted.is_empty(), "no 16-digit shader hash in {}", file.display()); + } + // `LEONIDA_WARM_SECONDS=`: stop taking new shaders after n seconds + // (what is done stays in the cache; the next warm-up goes on from there). + let limit = std::env::var("LEONIDA_WARM_SECONDS").ok().and_then(|v| v.trim().parse::().ok()); + let cfg = leonida_core::Config::load()?; + leonida_hle::modules::d3d12x::use_shader_cache(cfg.cache_subdir("shaders")?); + let paths = crate::default_paths(paths)?; + let threads = jobs.unwrap_or(4).max(1); + let began = std::time::Instant::now(); + let done = Mutex::new(HashSet::new()); + let counts = [const { AtomicUsize::new(0) }; 5]; + for root in &paths { + for entry in walkdir::WalkDir::new(root).into_iter().filter_map(Result::ok) { + if !entry.file_type().is_file() || entry.metadata().map_or(0, |m| m.len()) > MAX_FILE { + continue; + } + let Ok(data) = std::fs::read(entry.path()) else { + continue; + }; + let jobs = sources(&data); + let next = AtomicUsize::new(0); + std::thread::scope(|s| { + for _ in 0..threads.min(jobs.len()) { + s.spawn(|| { + while let Some(job) = jobs.get(next.fetch_add(1, Ordering::Relaxed)) { + let Some(bytes) = job.bytes() else { + continue; + }; + let hash = blake3::hash(&bytes).to_hex()[..16].to_owned(); + if limit.is_some_and(|n| began.elapsed().as_secs() >= n) { + counts[3].fetch_add(1, Ordering::Relaxed); + break; + } + if (!all && !wanted.contains(&hash)) || !lock(&done).insert(hash) { + continue; + } + let n = counts[4].fetch_add(1, Ordering::Relaxed) + 1; + if n.is_multiple_of(1000) { + println!("warm-up {n} shaders so far, {:.0} s", began.elapsed().as_secs_f64()); + } + let which = match leonida_hle::modules::d3d12x::warm_shader(&bytes) { + Ok(true) => 0, + Ok(false) => 1, + Err(_) => 2, + }; + counts[which].fetch_add(1, Ordering::Relaxed); + } + }); + } + }); + } + } + let [translated, there, failed] = [0, 1, 2].map(|i| counts[i].load(Ordering::Relaxed)); + let asked = if all { "all".to_owned() } else { wanted.len().to_string() }; + let stopped = if counts[3].load(Ordering::Relaxed) > 0 { " (stopped at the time limit)" } else { "" }; + println!( + "warm-up {asked} hashes asked, {} found: {translated} translated now, {there} in the cache already, {failed} do not translate; {:.1} s on {threads} threads{stopped}", + translated + there + failed, + began.elapsed().as_secs_f64() + ); + Ok(()) +} + +pub fn run( + paths: Vec, + validate: bool, + pipelines: bool, + list: bool, + jobs: Option, +) -> Result<()> { + let paths = crate::default_paths(paths)?; + // `LEONIDA_HOST_MAX_WAVE=32`: translate as for a host whose waves have + // at most 32 lanes (as the runtime does on such a card). + if let Some(n) = std::env::var("LEONIDA_HOST_MAX_WAVE").ok().and_then(|v| v.parse().ok()) { + leonida_shader::emit::set_host_max_wave(n); + } + let dll = validate.then(Validator::default_path).flatten(); + if validate { + Validator::load(dll.as_deref()).map_err(anyhow::Error::msg)?; + println!( + "validator {}", + dll.as_ref() + .map_or("dxil.dll".into(), |p| p.display().to_string()) + ); + } + if pipelines { + Host::new(false).map_err(anyhow::Error::msg)?; + } + let pairs: Vec<(String, String)> = std::env::var("LEONIDA_PAIRS") + .unwrap_or_default() + .split(',') + .filter_map(|p| p.split_once('+')) + .map(|(v, p)| (v.trim().to_owned(), p.trim().to_owned())) + .collect(); + let kept = std::sync::Arc::new(Mutex::new(Vec::new())); + let threads = + jobs.unwrap_or_else(|| std::thread::available_parallelism().map_or(4, |n| n.get())); + let seen = Mutex::new(HashSet::new()); + let total = Mutex::new(Tally::default()); + for root in &paths { + for entry in walkdir::WalkDir::new(root) + .into_iter() + .filter_map(Result::ok) + { + if !entry.file_type().is_file() || entry.metadata().map_or(0, |m| m.len()) > MAX_FILE { + continue; + } + let Ok(data) = std::fs::read(entry.path()) else { + continue; + }; + let jobs = sources(&data); + let next = AtomicUsize::new(0); + std::thread::scope(|s| { + for _ in 0..threads.min(jobs.len()) { + s.spawn(|| { + let mut t = Tally { + list, + ..Tally::default() + }; + let mut checks = Checks { + keep: (!pairs.is_empty()).then(|| kept.clone()), + validator: validate + .then(|| Validator::load(dll.as_deref()).ok()) + .flatten(), + host: pipelines + .then(|| Host::new(false).ok().map(|h| (h, host::stub_ps()))) + .flatten(), + }; + while let Some(job) = jobs.get(next.fetch_add(1, Ordering::Relaxed)) { + translate(job, entry.path(), &seen, &mut t, &mut checks); + } + lock(&total).merge(t); + }); + } + }); + } + } + let t = total.into_inner().unwrap_or_else(|e| e.into_inner()); + println!( + "containers {} ({} duplicates skipped)", + t.containers, t.duplicates + ); + println!( + "programs {} translated of {} ({} IR instructions)", + t.translated, t.programs, t.instructions + ); + println!( + "structured {} of {} ({} vector instructions, {} guarded, {} on opaque masks; \ + branches {} per lane, {} uniform)", + t.structured, + t.translated, + t.vector, + t.guarded, + t.opaque, + t.lane_branches, + t.uniform_branches + ); + println!( + "resources {} of {} tracked (descriptors {} loaded, {} built, {} constant; \ + {} scalar accesses; {} with a computed term)", + t.tracked, t.translated, t.loaded, t.built, t.constant, t.scalar, t.dynamic + ); + println!( + " used-resource entries {}: {} not traced {:?}; {} traced parameters not listed", + t.used, + t.untraced_used.values().sum::(), + t.untraced_used, + t.unlisted + ); + println!( + "I/O {} of {} vertex and pixel programs raised ({} interpolations, \ + {} vertex values; exports {:?}, {} still f16 pairs)", + t.io_raised, t.io_programs, t.interpolated, t.vertex_values, t.exports, t.compressed + ); + println!( + "DXIL {} emitted of {} vertex and pixel programs; {} validated, {} pipelines", + t.emitted, t.emit_programs, t.validated, t.pipelines + ); + println!( + " {} emitted of {} compute programs; {} validated, {} pipelines", + t.cs_emitted, t.cs_programs, t.cs_validated, t.cs_pipelines + ); + println!( + " {} emitted of {} mesh programs; {} validated, {} pipelines", + t.ms_emitted, t.ms_programs, t.ms_validated, t.ms_pipelines + ); + if !pairs.is_empty() { + let host = Host::new(false).map_err(anyhow::Error::msg)?; + let kept = lock(&kept); + let find = |name: &str| kept.iter().find(|(l, _)| l.contains(name)); + for (v, p) in &pairs { + let made = match (find(v), find(p)) { + (Some((_, vs)), Some((_, ps))) => if vs.stage == HwStage::Ms { + host.mesh_pipeline(vs, ps) + } else { + host.pipeline(vs, ps) + } + .map(|_| "pipeline created".to_owned()) + .unwrap_or_else(|e| e), + _ => "not emitted".to_owned(), + }; + println!("pair {v} + {p}: {made}"); + } + } + let mut lines = t.lines; + lines.sort(); + for l in lines { + println!("{l}"); + } + let mut failed: Vec<_> = t.failed.into_iter().collect(); + failed.sort_by_key(|(_, (n, _))| std::cmp::Reverse(*n)); + for (reason, (n, example)) in failed { + println!(" {n:>7} {reason} (e.g. {example})"); + } + Ok(()) +} + +fn translate( + source: &Source, + path: &Path, + seen: &Mutex>, + t: &mut Tally, + checks: &mut Checks, +) { + let example = || format!("{}{}", path.display(), source.label()); + let Some(bytes) = source.bytes() else { + return t.fail("corrupt record".into(), example); + }; + // The hash a run's log names the shader by (`hash=` in "first bind", + // "shader does not translate", "host pipeline refused"). + let hash = blake3::hash(&bytes).to_hex()[..16].to_owned(); + // Diagnostics: `LEONIDA_TRANSLATE_ONLY=,...` translates + // those containers alone. + static ONLY: std::sync::OnceLock> = std::sync::OnceLock::new(); + let only = ONLY.get_or_init(|| { + std::env::var("LEONIDA_TRANSLATE_ONLY") + .unwrap_or_default() + .split(',') + .map(|h| h.trim().to_lowercase()) + .filter(|h| !h.is_empty()) + .collect() + }); + if !only.is_empty() && !only.iter().any(|o| hash.starts_with(o.as_str())) { + return; + } + let example = || format!("{}{} #{hash}", path.display(), source.label()); + t.containers += 1; + let Ok(container) = Container::parse(&bytes) else { + return t.fail("no DXIL part (SM5 or older)".into(), example); + }; + let Some(dxil) = container.part(FourCC::DXIL).map(|p| p.data) else { + return t.fail("no DXIL part (SM5 or older)".into(), example); + }; + // `~`: the hash of the code alone; containers that differ only around + // it are translated once, the others listed as duplicates of it. + let code = blake3::hash(dxil); + let code8 = code.to_hex()[..8].to_owned(); + let example = || format!("{} ~{code8}", example()); + // `LEONIDA_DUMP_MATCH=;|...`: the containers whose + // line holds one of the texts (a name, `#hash`), as the title has them. + if let Ok(spec) = std::env::var("LEONIDA_DUMP_MATCH") + && let Some((dir, texts)) = spec.split_once(';') + { + let line = example(); + if texts.split('|').any(|text| !text.is_empty() && line.contains(text)) { + let name: String = source + .label() + .chars() + .skip_while(|c| *c != ' ') + .filter(|c| c.is_ascii_alphanumeric() || *c == '_') + .take(70) + .collect(); + let _ = std::fs::create_dir_all(dir); + let _ = std::fs::write(std::path::Path::new(dir).join(format!("{name}.{hash}.cdxil")), &bytes[..]); + } + } + if !lock(seen).insert(code) { + t.duplicates += 1; + if t.list { + t.lines.push(format!("{} duplicate", example())); + } + return; + } + let programs = match native_programs(dxil) { + Ok(p) => p, + Err(e) => return t.fail(e.to_string(), example), + }; + // `LEONIDA_FAIL_DUMP=`: the first 3 containers of each failure reason, as the title + // has them (`.cdxil`), to work on a translator gap offline + let dump = std::env::var_os("LEONIDA_FAIL_DUMP"); + let before: Option> = dump.as_ref().map(|_| t.failed.iter().map(|(k, v)| (k.clone(), v.0)).collect()); + translate_programs(&container, programs, &example, t, checks); + if let (Some(dir), Some(before)) = (dump, before) { + for (reason, (n, _)) in &t.failed { + let was = before.get(reason).copied().unwrap_or(0); + if *n > was && was < 3 { + let stem: String = reason.chars().map(|c| if c.is_ascii_alphanumeric() { c } else { '_' }).take(60).collect(); + let _ = std::fs::create_dir_all(&dir); + let _ = std::fs::write(std::path::Path::new(&dir).join(format!("{stem}_{was}.cdxil")), &bytes[..]); + } + } + } +} + +fn translate_programs(container: &Container, programs: Vec, example: &dyn Fn() -> String, t: &mut Tally, checks: &mut Checks) { + for p in programs { + t.programs += 1; + match leonida_shader::spill::build(&p) { + Ok(program) => { + t.translated += 1; + t.instructions += program.blocks.iter().map(|b| b.insts.len()).sum::(); + // Per-lane descriptors are traced on the per-lane form; its + // failure is listed after the resources' and I/O's. + let structured = structure::structure(&program); + let lanes = structured.as_ref().ok(); + let res = match resource::track(&program, &p.layout, p.stage, lanes) { + Ok(r) => { + tally_resources(&p, &r, t); + Some(r) + } + Err(ShaderError::Unsupported { offset, what }) => { + t.fail(format!("resources: {what}"), || { + format!("{} {:?} at {offset:#x}", example(), p.stage) + }); + None + } + Err(e) => { + t.fail(e.to_string(), || format!("{} {:?}", example(), p.stage)); + None + } + }; + let graphics = matches!(p.stage, HwStage::Vs | HwStage::Ps); + let compute = p.stage == HwStage::Cs; + let mut raised = None; + if graphics || compute || p.stage == HwStage::Ms { + t.io_programs += usize::from(graphics); + match io::raise(&program, &p) { + Ok(r) => { + if graphics { + tally_io(&r, t); + } + raised = Some(r); + } + Err(ShaderError::Unsupported { offset, what }) => t + .fail(format!("I/O: {what}"), || { + format!("{} {:?} at {offset:#x}", example(), p.stage) + }), + Err(e) => t.fail(e.to_string(), || format!("{} {:?}", example(), p.stage)), + } + } + let structured = match structured { + Ok(s) => { + tally_structured(&program, &s, t); + Some(s) + } + Err(e) => { + let reason = match e { + ShaderError::Unsupported { what, .. } => format!("structure: {what}"), + ShaderError::Isa { reason, .. } => format!("structure: {reason}"), + e => e.to_string(), + }; + t.fail(reason, || format!("{} {:?}", example(), p.stage)); + None + } + }; + if let (Some(r), Some(i), Some(s)) = (res, raised, structured) { + let label = || format!("{} {:?}", example(), p.stage); + *counter(t, p.stage, 0) += 1; + match emit::emit(container, &p, &program, &s, &i, &r) { + Ok(shader) => { + census_line(&label(), &p, &program, &shader); + *counter(t, p.stage, 1) += 1; + check(shader, t, checks, label); + } + Err(ShaderError::Unsupported { offset, what }) => t + .fail(format!("emit: {what}"), || { + format!("{} at {offset:#x}", label()) + }), + Err(e) => t.fail(format!("emit: {e}"), label), + } + } + } + Err(e) => { + let reason = match e { + ShaderError::Unsupported { what, .. } => format!("unsupported: {what}"), + e => e.to_string(), + }; + t.fail(reason, || format!("{} {:?}", example(), p.stage)); + } + } + } +} + +/// `LEONIDA_SHADER_CENSUS=`: one line per emitted program, appended: +/// its label, the console program's instructions by encoding class (a +/// static count of the whole program, not of one thread's path), and the +/// host module's instructions by kind (`emit::census::KINDS`). +fn census_line(label: &str, native: &NativeProgram, p: &ir::Program, shader: &emit::HostShader) { + use std::io::Write; + use leonida_shader::gfx10::Fields; + static OUT: std::sync::OnceLock>> = std::sync::OnceLock::new(); + let Some(out) = OUT.get_or_init(|| { + let path = std::env::var_os("LEONIDA_SHADER_CENSUS")?; + let file = std::fs::OpenOptions::new().create(true).append(true).open(path).ok()?; + Some(Mutex::new(file)) + }) else { + return; + }; + let Some(census) = emit::census::take(&shader.dxil) else { + return; + }; + // total, vector, scalar, descriptor loads, buffer and memory, image, LDS, control, other + let mut console = [0u32; 9]; + for inst in p.blocks.iter().flat_map(|b| &b.insts) { + console[0] += 1; + let k = match &inst.fields { + Fields::Valu(_) => 1, + Fields::Sop { .. } => 2, + Fields::Smem { .. } => 3, + Fields::Buffer { .. } | Fields::Flat { .. } => 4, + Fields::Image { .. } => 5, + Fields::Ds { .. } => 6, + Fields::Sopp { .. } => 7, + _ => 8, + }; + console[k] += 1; + } + let mut line = format!("{label}\twave64={}", u8::from(native.wave64)); + for (name, n) in ["c_total", "c_valu", "c_sop", "c_smem", "c_buffer", "c_image", "c_ds", "c_sopp", "c_other"].iter().zip(console) { + line.push_str(&format!("\t{name}={n}")); + } + for (name, n) in emit::census::KINDS.iter().zip(census.counts) { + line.push_str(&format!("\t{name}={n}")); + } + line.push('\n'); + let _ = lock(out).write_all(line.as_bytes()); +} + +/// Validates an emitted shader if asked to. +fn check( + mut shader: emit::HostShader, + t: &mut Tally, + checks: &mut Checks, + label: impl Fn() -> String, +) { + if let Some(keep) = &checks.keep { + lock(keep).push((label(), shader.clone())); + } + // `LEONIDA_EMIT_DUMP` with `--list`: every emitted shader as a file. + if t.list + && let Ok(dir) = std::env::var("LEONIDA_EMIT_DUMP") + { + let name: String = label() + .chars() + .map(|c| if c.is_ascii_alphanumeric() { c } else { '_' }) + .collect(); + let _ = std::fs::write( + format!("{dir}/{}.dxil", &name[name.len().saturating_sub(100)..]), + &shader.dxil, + ); + } + if let Some((h, stub_ps)) = &checks.host { + let made = match shader.stage { + HwStage::Vs => h.pipeline(&shader, stub_ps).map(drop), + HwStage::Cs => h.compute_pipeline(&shader).map(drop), + HwStage::Ms => h.mesh_pipeline(&shader, stub_ps).map(drop), + _ => host::stub_vs(&shader).and_then(|vs| h.pipeline(&vs, &shader).map(drop)), + }; + match made { + Ok(()) => { + *counter(t, shader.stage, 3) += 1; + if t.list { + t.lines.push(format!("{} pipeline created", label())); + } + } + Err(e) => t.fail(format!("pipeline: {e}"), &label), + } + } + let Some(v) = checks.validator.as_mut() else { + return; + }; + match v.validate(&mut shader.dxil) { + Ok(()) => { + *counter(t, shader.stage, 2) += 1; + if t.list { + t.lines.push(format!("{} validated", label())); + } + } + Err(text) => { + let first = text + .lines() + .find(|l| l.contains("error")) + .unwrap_or(text.lines().next().unwrap_or("")) + .to_owned(); + if let Ok(dir) = std::env::var("LEONIDA_EMIT_DUMP") { + let n = t + .failed + .get(&format!("validator: {first}")) + .map_or(0, |f| f.0); + if n < 3 { + let name = format!( + "{dir}/{}_{n}", + first + .chars() + .filter(char::is_ascii_alphanumeric) + .take(40) + .collect::() + ); + let _ = std::fs::write(format!("{name}.dxil"), &shader.dxil); + let _ = std::fs::write(format!("{name}.txt"), format!("{}\n{text}", label())); + } + } + t.fail(format!("validator: {first}"), label); + } + } +} + +/// Emission counts of `stage`'s kind: 0 programs, 1 emitted, 2 validated, +/// 3 pipelines. +fn counter(t: &mut Tally, stage: HwStage, k: usize) -> &mut usize { + let [a, b, c, d] = match stage { + HwStage::Cs => [ + &mut t.cs_programs, + &mut t.cs_emitted, + &mut t.cs_validated, + &mut t.cs_pipelines, + ], + HwStage::Ms => [ + &mut t.ms_programs, + &mut t.ms_emitted, + &mut t.ms_validated, + &mut t.ms_pipelines, + ], + _ => [ + &mut t.emit_programs, + &mut t.emitted, + &mut t.validated, + &mut t.pipelines, + ], + }; + [a, b, c, d].into_iter().nth(k).expect("0 to 3") +} + +fn tally_io(r: &io::Io, t: &mut Tally) { + t.io_raised += 1; + for (_, i) in &r.interps { + match i { + io::Interp::Interpolated { .. } => t.interpolated += 1, + io::Interp::Vertex { .. } => t.vertex_values += 1, + io::Interp::Weighted { .. } => t.interpolated += 1, + } + } + for e in &r.exports { + let kind = match e.target { + io::Target::Color(_) => "color", + io::Target::Depth => "depth", + io::Target::Null => "null", + io::Target::Position(_) => "position", + io::Target::Param { .. } => "param", + io::Target::Unread => "unread param", + io::Target::Primitive => "primitive", + io::Target::PrimitiveParam { .. } => "primitive param", + }; + *t.exports.entry(kind).or_default() += 1; + t.compressed += usize::from(e.compressed); + } +} + +fn tally_resources(p: &NativeProgram, r: &resource::Resources, t: &mut Tally) { + t.tracked += 1; + t.scalar += r.scalar.len(); + t.dynamic += r.scalar.iter().filter(|s| s.1.dynamic.is_some()).count(); + let address = |load| r.scalar.iter().find(|s| s.0 == load).map(|s| s.1); + let mut traced = HashSet::new(); + for leaf in r.descriptors.iter().flat_map(|d| d.source.leaves()) { + let a = match *leaf { + resource::Source::Loaded { load, .. } | resource::Source::Fetched { load, .. } => { + t.loaded += 1; + address(load) + } + resource::Source::Built { address, .. } => { + t.built += 1; + t.dynamic += usize::from(address.dynamic.is_some()); + Some(address) + } + resource::Source::Constant(_) => { + t.constant += 1; + None + } + resource::Source::Phi { .. } + | resource::Source::Select { .. } + | resource::Source::Lanes { .. } + | resource::Source::LanePhi { .. } => { + unreachable!("leaves are no phis, selects or per-lane choices") + } + }; + // Heaps hold dynamic resources, which no used entry lists; code + // tables are no root parameter. + if let Some(a) = a + && a.param != resource::CODE + && !matches!( + p.layout[a.param].root, + RootType::ResourceHeap | RootType::SamplerHeap + ) + { + traced.insert(p.layout[a.param].user_data); + } + } + // Root constants are listed as a CBV, read straight from the SGPRs. + traced.extend( + r.params + .iter() + .map(|&(_, param, _)| &p.layout[param]) + .filter(|l| l.root == RootType::Constants) + .map(|l| l.user_data), + ); + let listed: HashSet = p.used.iter().map(|u| u.user_data).collect(); + t.used += p.used.len(); + // Immediate samplers are literals in the code: the distinct sampler + // values (decoded) are matched against the listed entries, which do not + // say which value is whose. + let mut values: Vec = Vec::new(); + for d in r + .descriptors + .iter() + .filter(|d| d.role == resource::Role::Sampler) + { + for leaf in d.source.leaves() { + if let resource::Source::Constant(words) = leaf + && let Ok(w) = <[u32; 4]>::try_from(&words[..words.len().min(4)]) + { + let s = emit::StaticSampler::from_words(w); + if !values.contains(&s) { + values.push(s); + } + } + } + } + // Engines often declare equal samplers at several registers, so equal + // values may stand for several entries, but never more values than + // entries. + let immediate = p + .used + .iter() + .filter(|u| u.root == RootType::ImmediateSampler) + .count(); + let samplers_match = !values.is_empty() && values.len() <= immediate; + let matched = |u: &&leonida_shader::UsedResource| { + if u.root == RootType::ImmediateSampler { + samplers_match + } else { + traced.contains(&u.user_data) + } + }; + for u in p.used.iter().filter(|u| !matched(u)) { + *t.untraced_used + .entry(format!("{:?} via {:?}", u.kind, u.root)) + .or_default() += 1; + } + t.unlisted += traced.difference(&listed).count(); +} + +fn tally_structured(program: &ir::Program, s: &structure::Structured, t: &mut Tally) { + t.structured += 1; + for (block, guards) in program.blocks.iter().zip(&s.guards) { + t.vector += block + .insts + .iter() + .filter(|i| i.read(ir::Reg::S(ir::EXEC)).is_some()) + .count(); + for &g in guards.iter().flatten() { + t.guarded += 1; + let support = s.bools.support(g); + t.opaque += usize::from(support.iter().any(|a| matches!(a, Atom::Opaque(_)))); + } + } + for exit in &s.exits { + if let LaneExit::Branch { when, .. } = *exit { + if s.bools + .support(when) + .iter() + .all(|a| matches!(a, Atom::Uniform(_))) + { + t.uniform_branches += 1; + } else { + t.lane_branches += 1; + } + } + } +} + +fn lock(m: &Mutex) -> std::sync::MutexGuard<'_, T> { + m.lock().unwrap_or_else(|e| e.into_inner()) +} diff --git a/assets/logo.png b/assets/logo.png deleted file mode 100644 index 359ff6c35..000000000 Binary files a/assets/logo.png and /dev/null differ diff --git a/assets/logo.svg b/assets/logo.svg deleted file mode 100644 index 8fc789e1a..000000000 --- a/assets/logo.svg +++ /dev/null @@ -1 +0,0 @@ - \ No newline at end of file diff --git a/crates/leonida-core/Cargo.toml b/crates/leonida-core/Cargo.toml new file mode 100644 index 000000000..bdbad06e0 --- /dev/null +++ b/crates/leonida-core/Cargo.toml @@ -0,0 +1,25 @@ +[package] +name = "leonida-core" +description = "Shared plumbing: configuration, paths, the asset-policy guard, logging." +version.workspace = true +edition.workspace = true +rust-version.workspace = true +license.workspace = true +publish.workspace = true + +[dependencies] +anyhow.workspace = true +thiserror.workspace = true +serde.workspace = true +toml.workspace = true +tracing-subscriber.workspace = true + +[dev-dependencies] +tempfile.workspace = true + +[features] +# Lets `LEONIDA_LOG` enable debug and trace output. +diagnostics = [] + +[lints] +workspace = true diff --git a/crates/leonida-core/src/config.rs b/crates/leonida-core/src/config.rs new file mode 100644 index 000000000..4396e5b2a --- /dev/null +++ b/crates/leonida-core/src/config.rs @@ -0,0 +1,323 @@ +//! Where the user's files live. +//! +//! Resolution order for each value: environment variable, then the config +//! file (`LEONIDA_CONFIG`, else `./leonida.toml`), then the default. +//! See `leonida.example.toml` at the repository root. + +use std::path::{Path, PathBuf}; + +use anyhow::{Context, Result}; +use serde::Deserialize; + +use crate::policy::ensure_outside_repo; + +#[derive(Debug, Default, Clone)] +pub struct Config { + /// The user's dump of the title. + pub game_dir: Option, + /// Root for all derived data. Always outside the repository. + pub cache_dir: PathBuf, + /// What titles write and must keep (persistent local storage). Never + /// inside the cache, which may be deleted at any time. + pub data_dir: PathBuf, + /// Other titles used to exercise platform-level code. + pub test_titles: Vec, + /// The config file that was read, if any. + pub source: Option, +} + +#[derive(Debug, Default, Deserialize)] +#[serde(deny_unknown_fields)] +struct FileConfig { + #[serde(default)] + paths: FilePaths, +} + +#[derive(Debug, Default, Deserialize)] +#[serde(deny_unknown_fields)] +struct FilePaths { + game_dir: Option, + cache_dir: Option, + data_dir: Option, + #[serde(default)] + test_titles: Vec, +} + +impl Config { + /// Loads configuration from the environment and the config file. + pub fn load() -> Result { + let explicit = std::env::var_os("LEONIDA_CONFIG").map(PathBuf::from); + let path = file_path(); + let file = if path.is_file() { + let text = std::fs::read_to_string(&path) + .with_context(|| format!("reading {}", path.display()))?; + Some((path, text)) + } else if let Some(p) = explicit { + anyhow::bail!( + "LEONIDA_CONFIG points at {}, which does not exist", + p.display() + ); + } else { + None + }; + let (source, parsed) = match file { + Some((path, text)) => { + let parsed: FileConfig = + toml::from_str(&text).with_context(|| format!("parsing {}", path.display()))?; + (Some(path), parsed) + } + None => (None, FileConfig::default()), + }; + Self::resolve(parsed.paths, source, |k| std::env::var_os(k)) + } + + fn resolve( + file: FilePaths, + source: Option, + env: impl Fn(&str) -> Option, + ) -> Result { + let env_path = |k: &str| env(k).filter(|v| !v.is_empty()).map(PathBuf::from); + let test_titles = match env("LEONIDA_TEST_TITLES") { + Some(v) if !v.is_empty() => std::env::split_paths(&v) + .filter(|p| !p.as_os_str().is_empty()) + .collect(), + _ => file.test_titles, + }; + let cache_dir = env_path("LEONIDA_CACHE_DIR") + .or(file.cache_dir) + .map_or_else(|| default_dir("cache"), Ok)?; + let data_dir = env_path("LEONIDA_DATA_DIR") + .or(file.data_dir) + .map_or_else(|| default_dir("data"), Ok)?; + Ok(Config { + game_dir: env_path("LEONIDA_GAME_DIR").or(file.game_dir), + cache_dir, + data_dir, + test_titles, + source, + }) + } + + /// The game directory, or a helpful error if it is not configured. + pub fn require_game_dir(&self) -> Result<&Path> { + self.game_dir.as_deref().context( + "no game directory configured: run `leonida run` in a terminal to be asked for it, \ + or set LEONIDA_GAME_DIR or [paths].game_dir in leonida.toml", + ) + } + + /// Writes `game_dir` into `[paths]` of the config file, creating the file + /// if there is none; its other lines and comments are kept. Returns the + /// file's path. + pub fn save_game_dir(game_dir: &Path) -> Result { + let path = file_path(); + let text = match std::fs::read_to_string(&path) { + Ok(text) => text, + Err(e) if e.kind() == std::io::ErrorKind::NotFound => String::new(), + Err(e) => return Err(e).with_context(|| format!("reading {}", path.display())), + }; + let new = with_game_dir(&text, game_dir)?; + let parsed: FileConfig = + toml::from_str(&new).with_context(|| format!("updating {}", path.display()))?; + anyhow::ensure!( + parsed.paths.game_dir.as_deref() == Some(game_dir), + "updating {}: the game folder did not read back", + path.display() + ); + std::fs::write(&path, new).with_context(|| format!("writing {}", path.display()))?; + Ok(path) + } + + /// Returns `/`, creating it, after checking the asset policy. + pub fn cache_subdir(&self, sub: &str) -> Result { + subdir(&self.cache_dir, sub) + } + + /// Returns `/`, creating it, after checking the asset policy. + pub fn data_subdir(&self, sub: &str) -> Result { + subdir(&self.data_dir, sub) + } +} + +fn subdir(root: &Path, sub: &str) -> Result { + let dir = root.join(sub); + ensure_outside_repo(&dir)?; + std::fs::create_dir_all(&dir).with_context(|| format!("creating {}", dir.display()))?; + Ok(dir) +} + +/// `%LOCALAPPDATA%/leonida/` (elsewhere the XDG or home cache). +fn default_dir(name: &str) -> Result { + let base = std::env::var_os("LOCALAPPDATA") + .or_else(|| std::env::var_os("XDG_CACHE_HOME")) + .map(PathBuf::from) + .or_else(|| std::env::var_os("HOME").map(|h| PathBuf::from(h).join(".cache"))) + .context("cannot determine a user directory; set LEONIDA_CACHE_DIR and LEONIDA_DATA_DIR")?; + Ok(base.join("leonida").join(name)) +} + +/// The config file: `LEONIDA_CONFIG`, else `./leonida.toml`. +fn file_path() -> PathBuf { + std::env::var_os("LEONIDA_CONFIG").map_or_else(|| PathBuf::from("leonida.toml"), PathBuf::from) +} + +/// `text` with `game_dir` set in its `[paths]` table: a `game_dir` line +/// there is replaced, else a commented-out one, else the key goes under the +/// table's header, which is added if missing. +fn with_game_dir(text: &str, game_dir: &Path) -> Result { + let value = game_dir + .to_str() + .with_context(|| format!("{} is not valid UTF-8", game_dir.display()))?; + let line = format!("game_dir = {}", toml::Value::String(value.to_owned())); + let newline = if text.contains("\r\n") { "\r\n" } else { "\n" }; + let mut lines: Vec = text.lines().map(str::to_owned).collect(); + let key = |l: &str| { + l.strip_prefix("game_dir") + .is_some_and(|rest| rest.trim_start().starts_with('=')) + }; + match lines.iter().position(|l| l.trim() == "[paths]") { + Some(header) => { + let start = header + 1; + let end = lines[start..] + .iter() + .position(|l| l.trim_start().starts_with('[')) + .map_or(lines.len(), |i| start + i); + let section = &lines[start..end]; + let at = section.iter().position(|l| key(l.trim_start())).or_else(|| { + section.iter().position(|l| { + l.trim_start() + .strip_prefix('#') + .is_some_and(|c| key(c.trim_start())) + }) + }); + match at { + Some(i) => lines[start + i] = line, + None => lines.insert(start, line), + } + } + None => { + if lines.last().is_some_and(|l| !l.trim().is_empty()) { + lines.push(String::new()); + } + lines.push("[paths]".to_owned()); + lines.push(line); + } + } + let mut out = lines.join(newline); + out.push_str(newline); + Ok(out) +} + +#[cfg(test)] +mod tests { + use super::*; + use std::ffi::OsString; + + #[test] + fn environment_overrides_file() { + let file = FilePaths { + game_dir: Some("from-file".into()), + cache_dir: Some("cache-from-file".into()), + ..Default::default() + }; + let env = |k: &str| (k == "LEONIDA_GAME_DIR").then(|| OsString::from("from-env")); + let cfg = Config::resolve(file, None, env).unwrap(); + assert_eq!(cfg.game_dir.unwrap(), PathBuf::from("from-env")); + assert_eq!(cfg.cache_dir, PathBuf::from("cache-from-file")); + } + + #[test] + fn empty_env_values_are_ignored() { + let file = FilePaths { + game_dir: Some("from-file".into()), + ..Default::default() + }; + let env = |k: &str| (k == "LEONIDA_GAME_DIR").then(OsString::new); + let cfg = Config::resolve(file, None, env).unwrap(); + assert_eq!(cfg.game_dir.unwrap(), PathBuf::from("from-file")); + } + + #[test] + fn empty_test_titles_env_is_ignored() { + let file = FilePaths { + test_titles: vec!["from-file".into()], + ..Default::default() + }; + let env = |k: &str| (k == "LEONIDA_TEST_TITLES").then(OsString::new); + let cfg = Config::resolve(file, None, env).unwrap(); + assert_eq!(cfg.test_titles, vec![PathBuf::from("from-file")]); + } + + #[test] + fn test_titles_env_splits_paths() { + let value = std::env::join_paths(["first", "second"]).unwrap(); + let file = FilePaths::default(); + let env = |k: &str| (k == "LEONIDA_TEST_TITLES").then(|| value.clone()); + let cfg = Config::resolve(file, None, env).unwrap(); + assert_eq!( + cfg.test_titles, + vec![PathBuf::from("first"), PathBuf::from("second")] + ); + } + + #[test] + fn example_config_parses() { + let text = include_str!("../../../leonida.example.toml"); + let parsed: FileConfig = toml::from_str(text).unwrap(); + assert!(parsed.paths.game_dir.is_none()); + } + + fn game_dir_of(text: &str) -> Option { + toml::from_str::(text).unwrap().paths.game_dir + } + + #[test] + fn game_dir_fills_the_example() { + let text = include_str!("../../../leonida.example.toml"); + let dir = Path::new(r"C:\Games\The Title"); + let new = with_game_dir(text, dir).unwrap(); + assert_eq!(game_dir_of(&new).as_deref(), Some(dir)); + assert_eq!(new.lines().count(), text.lines().count()); + assert!(new.contains("# Derived data.")); + } + + #[test] + fn game_dir_replaces_a_set_one() { + let text = "[paths]\ngame_dir = 'old'\ntest_titles = []\n"; + let new = with_game_dir(text, Path::new("new")).unwrap(); + assert_eq!(new, "[paths]\ngame_dir = \"new\"\ntest_titles = []\n"); + } + + #[test] + fn game_dir_starts_an_empty_file() { + let new = with_game_dir("", Path::new("D:/game")).unwrap(); + assert_eq!(game_dir_of(&new).unwrap(), PathBuf::from("D:/game")); + } + + #[test] + fn game_dir_keeps_crlf() { + let text = "[paths]\r\n# game_dir = 'x'\r\n"; + let new = with_game_dir(text, Path::new("y")).unwrap(); + assert_eq!(new, "[paths]\r\ngame_dir = \"y\"\r\n"); + } + + #[test] + fn cache_inside_repo_is_refused() { + let inside = Path::new(env!("CARGO_MANIFEST_DIR")).join("cache"); + let cfg = Config { + cache_dir: inside, + ..Default::default() + }; + assert!(cfg.cache_subdir("x").is_err()); + } + + #[test] + fn data_inside_repo_is_refused() { + let inside = Path::new(env!("CARGO_MANIFEST_DIR")).join("data"); + let cfg = Config { + data_dir: inside, + ..Default::default() + }; + assert!(cfg.data_subdir("x").is_err()); + } +} diff --git a/crates/leonida-core/src/lib.rs b/crates/leonida-core/src/lib.rs new file mode 100644 index 000000000..5cecf8319 --- /dev/null +++ b/crates/leonida-core/src/lib.rs @@ -0,0 +1,13 @@ +//! Shared plumbing for every Leonida Legacy crate and tool. +//! +//! * [`config`]: where the user's files live (never inside the repository). +//! * [`policy`]: the runtime half of rule #1, refusing to write +//! game-derived data into the source tree. +//! * [`logging`]: one tracing setup for all binaries. + +pub mod config; +pub mod logging; +pub mod policy; + +pub use config::Config; +pub use policy::{PolicyError, ensure_outside_repo}; diff --git a/crates/leonida-core/src/logging.rs b/crates/leonida-core/src/logging.rs new file mode 100644 index 000000000..8a97d309d --- /dev/null +++ b/crates/leonida-core/src/logging.rs @@ -0,0 +1,35 @@ +//! One tracing setup for every binary. +//! +//! Filter with `LEONIDA_LOG` (falls back to `RUST_LOG`), e.g. +//! `LEONIDA_LOG=leonida_loader=trace,info`. Debug and trace output exist +//! only in builds with the `diagnostics` feature; a plain release build +//! logs info and above whatever the filter asks for. + +use tracing_subscriber::EnvFilter; +use tracing_subscriber::filter::LevelFilter; +use tracing_subscriber::layer::SubscriberExt; +use tracing_subscriber::util::SubscriberInitExt; + +/// The most verbose level this build can log. +const CAP: LevelFilter = if cfg!(feature = "diagnostics") { + LevelFilter::TRACE +} else { + LevelFilter::INFO +}; + +pub fn init(default_level: &str) { + let filter = std::env::var("LEONIDA_LOG") + .or_else(|_| std::env::var("RUST_LOG")) + .ok() + .and_then(|v| EnvFilter::try_new(v).ok()) + .unwrap_or_else(|| EnvFilter::new(default_level)); + let _ = tracing_subscriber::registry() + .with(CAP) + .with(filter) + .with( + tracing_subscriber::fmt::layer() + .with_target(true) + .with_writer(std::io::stderr), + ) + .try_init(); +} diff --git a/crates/leonida-core/src/policy.rs b/crates/leonida-core/src/policy.rs new file mode 100644 index 000000000..a61ca3810 --- /dev/null +++ b/crates/leonida-core/src/policy.rs @@ -0,0 +1,159 @@ +//! Rule #1, enforced at runtime: game-derived data never lands in the repo. +//! +//! Everything Leonida Legacy produces from the user's files (converted assets, +//! prepared images, shader caches, crash dumps) is as much "from the game" +//! as the files themselves. Every tool that writes such output must call +//! [`ensure_outside_repo`] on the destination first. The static half of the +//! rule is `cargo xtask policy`, which checks what git tracks. + +use std::path::{Component, Path, PathBuf}; + +/// Marker file at the root of the source tree. +pub const ROOT_MARKER: &str = ".leonida-root"; + +/// The source tree this binary was compiled from. +fn compiled_workspace_root() -> PathBuf { + // crates/leonida-core -> workspace root + Path::new(env!("CARGO_MANIFEST_DIR")).join("..").join("..") +} + +#[derive(Debug, thiserror::Error)] +pub enum PolicyError { + #[error( + "refusing to use {path} for game-derived data: it is inside the Leonida Legacy source tree \ + ({root}). Keep game files, caches and outputs outside the repository \ + (see docs/asset-policy.md)" + )] + InsideRepo { path: PathBuf, root: PathBuf }, + #[error("cannot resolve {path}: {source}")] + Io { + path: PathBuf, + source: std::io::Error, + }, +} + +/// Returns `Ok` only if `path` is outside every Leonida Legacy source tree. +/// +/// `path` does not have to exist yet. Two checks are made: +/// 1. it is not below the source tree this binary was built from; +/// 2. none of its ancestors contains the [`ROOT_MARKER`] file (catches +/// other clones/copies of the repository). +pub fn ensure_outside_repo(path: &Path) -> Result<(), PolicyError> { + let resolved = resolve(path)?; + + if let Ok(root) = std::fs::canonicalize(compiled_workspace_root()) + && root.join(ROOT_MARKER).is_file() + && resolved.starts_with(&root) + { + return Err(PolicyError::InsideRepo { + path: path.to_path_buf(), + root, + }); + } + + for ancestor in resolved.ancestors() { + if ancestor.join(ROOT_MARKER).is_file() { + return Err(PolicyError::InsideRepo { + path: path.to_path_buf(), + root: ancestor.to_path_buf(), + }); + } + } + Ok(()) +} + +/// Canonicalizes the longest existing prefix of `path` and re-appends the +/// rest, so that paths which do not exist yet can still be compared. +fn resolve(path: &Path) -> Result { + let absolute = if path.is_absolute() { + path.to_path_buf() + } else { + std::env::current_dir() + .map_err(|source| PolicyError::Io { + path: path.to_path_buf(), + source, + })? + .join(path) + }; + + let mut existing = absolute.as_path(); + let mut rest = Vec::new(); + loop { + match std::fs::canonicalize(existing) { + Ok(canon) => { + let mut out = canon; + for component in rest.iter().rev() { + out.push(component); + } + return Ok(normalize(&out)); + } + Err(source) => match (existing.parent(), existing.file_name()) { + (Some(parent), Some(name)) => { + rest.push(name.to_os_string()); + existing = parent; + } + _ => { + return Err(PolicyError::Io { + path: path.to_path_buf(), + source, + }); + } + }, + } + } +} + +/// Removes `.` and resolves `..` lexically (only used on the non-existing tail). +fn normalize(path: &Path) -> PathBuf { + let mut out = PathBuf::new(); + for component in path.components() { + match component { + Component::CurDir => {} + Component::ParentDir => { + out.pop(); + } + c => out.push(c), + } + } + out +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn rejects_paths_inside_this_repo() { + let inside = compiled_workspace_root().join("cache").join("textures"); + assert!(matches!( + ensure_outside_repo(&inside), + Err(PolicyError::InsideRepo { .. }) + )); + let sneaky = std::env::temp_dir().join("..").join("x"); // sanity: no panic + let _ = ensure_outside_repo(&sneaky); + } + + #[test] + fn rejects_dotdot_escapes_back_into_repo() { + let root = compiled_workspace_root(); + let path = root + .join("crates") + .join("..") + .join("not-yet-created") + .join("out"); + assert!(ensure_outside_repo(&path).is_err()); + } + + #[test] + fn rejects_other_clones_via_marker() { + let tmp = tempfile::tempdir().unwrap(); + std::fs::write(tmp.path().join(ROOT_MARKER), "").unwrap(); + assert!(ensure_outside_repo(&tmp.path().join("cache")).is_err()); + } + + #[test] + fn accepts_unrelated_directories() { + let tmp = tempfile::tempdir().unwrap(); + ensure_outside_repo(&tmp.path().join("does").join("not").join("exist")).unwrap(); + } +} diff --git a/crates/leonida-formats/Cargo.toml b/crates/leonida-formats/Cargo.toml new file mode 100644 index 000000000..6962c7df4 --- /dev/null +++ b/crates/leonida-formats/Cargo.toml @@ -0,0 +1,11 @@ +[package] +name = "leonida-formats" +description = "Platform-level data formats: texture layouts, compressed textures, audio codecs." +version.workspace = true +edition.workspace = true +rust-version.workspace = true +license.workspace = true +publish.workspace = true + +[lints] +workspace = true diff --git a/crates/leonida-formats/src/bcpack-tables.bin b/crates/leonida-formats/src/bcpack-tables.bin new file mode 100644 index 000000000..1e5485017 Binary files /dev/null and b/crates/leonida-formats/src/bcpack-tables.bin differ diff --git a/crates/leonida-formats/src/bcpack.rs b/crates/leonida-formats/src/bcpack.rs new file mode 100644 index 000000000..49c398833 --- /dev/null +++ b/crates/leonida-formats/src/bcpack.rs @@ -0,0 +1,1608 @@ +//! BCPack: lossless packing of BC1-BC7 block streams, as the console's +//! DirectStorage hardware unpacks them. Decode only; BC2 is left out (no +//! title data uses it). +//! +//! A packed stream has no header. It is 12 or 16 interleaved rANS *lanes*; +//! each lane is a run of fragments (header byte, length, payload) coded with +//! one of 128 static models, and a fixed schedule decides which lane takes +//! the next input byte. The lanes' symbols form one record per block: two +//! back references (to one of the last 256 blocks, or to a per-format +//! dictionary that stands in for blocks -1 to -255) and the residuals of the +//! endpoints and indices against them. The models, the index rank tables, +//! the BC7 control codes and the dictionaries are constants of the format, +//! kept in `bcpack-tables.bin` beside this file ([`Tables::builtin`]). + +use std::fmt; + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct Error(pub &'static str); + +impl fmt::Display for Error { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "BCPack: {}", self.0) + } +} + +impl std::error::Error for Error {} + +const MODELS: usize = 128; +const BUCKETS: usize = 9; +const HISTORY: usize = 256; +const DICTIONARY: usize = 255; +/// rANS: decode while the state is above this, read while below. +const LOW: u32 = 1 << 24; +/// Input bytes per schedule round. +const ROUND_BYTES: usize = 8; + +/// Bytes of the table file (see [`Tables::parse`]). +pub const TABLES_SIZE: usize = MODELS * BUCKETS * 2 + + 256 + + 64 + + 256 + + 64 + + 64 + + 512 * 2 + + DICTIONARY * (6 + 16 + 8 + 32 + 2 + 16 + 4 + 32 + 25 + 33 + 50 + 66); + +/// Endpoints and indices of BC1, BC3, BC4 and BC5: small unsigned values, +/// summed per element modulo the element's width. +#[derive(Clone, Copy, Default)] +struct Plain { + ep: [u8; 8], + ix: [u8; 32], +} + +#[derive(Clone, Copy, Default)] +struct Bc6Ep { + /// Endpoint 0 R G B, then endpoints 1-3, left-aligned and biased. + e: [[u16; 3]; 4], +} + +#[derive(Clone, Copy, Default)] +struct Bc6Ix { + mode: u8, + ix: [i16; 16], +} + +#[derive(Clone, Copy, Default)] +struct Bc7Ep { + ctrl: u16, + /// Per subset: R0 R1 G0 G1 B0 B1 A0 A1, left-aligned. + rows: [[u16; 8]; 3], +} + +#[derive(Clone, Copy, Default)] +struct Bc7Ix { + bits: [u8; 2], + ix: [[i16; 16]; 2], +} + +/// The format's constant tables. +pub struct Tables { + freq: [[u32; BUCKETS]; MODELS], + /// Each bucket's first slot; 65536 past the model's last, and one more + /// 65536 at the end so a bucket always has a next start. + start: [[u32; BUCKETS + 1]; MODELS], + /// Per model, the bucket of the first slot of each 256-slot window: the + /// search for a slot's bucket starts there and seldom moves on. + bucket: Box<[[u8; 256]; MODELS]>, + /// ceil(2^32 / freq): exact division for the offsets inside a bucket. + recip: [[u64; BUCKETS]; MODELS], + rank1: [u8; 256], + rank3a: [u8; 64], + rank3c: [u8; 256], + rank4: [u8; 64], + rank5: [u8; 64], + ctrl7: [u16; 512], + bc1: Vec, + bc3: Vec, + bc4: Vec, + bc5: Vec, + bc6: Vec<(Bc6Ep, Bc6Ix)>, + bc7: Vec<(Bc7Ep, Bc7Ix)>, +} + +struct Reader<'a>(&'a [u8]); + +impl Reader<'_> { + fn bytes(&mut self) -> [u8; N] { + let (head, rest) = self.0.split_at(N); + self.0 = rest; + head.try_into().unwrap_or([0; N]) + } + fn u8(&mut self) -> u8 { + self.bytes::<1>()[0] + } + fn u16(&mut self) -> u16 { + u16::from_le_bytes(self.bytes()) + } +} + +impl Tables { + /// The tables Leonida Legacy ships with. + pub fn builtin() -> Result { + Tables::parse(include_bytes!("bcpack-tables.bin")) + } + + /// Reads the table file: 128 x 9 u16 model frequencies (per bucket, the + /// frequency of each of its symbols), the rank tables (BC1 256 B, BC3 + /// alpha 64 B and colour 256 B, BC4 64 B, BC5 64 B), 512 u16 BC7 control + /// words, then 255 dictionary entries per format in format order: BC1 + /// 6 + 16 B, BC3 8 + 32 B, BC4 2 + 16 B, BC5 4 + 32 B, BC6H (u8 mode, + /// 12 u16, u8 mode, 16 i16), BC7 (u16 control, 24 u16, 2 u8, 2 B, + /// 16 + 15 i16). Little-endian, no padding. Every model must tile 65536. + pub fn parse(bytes: &[u8]) -> Result { + if bytes.len() != TABLES_SIZE { + return Err(Error("table file has the wrong size")); + } + let mut r = Reader(bytes); + let mut freq = [[0u32; BUCKETS]; MODELS]; + let mut start = [[0u32; BUCKETS + 1]; MODELS]; + let mut bucket = Box::new([[0u8; 256]; MODELS]); + let mut recip = [[0u64; BUCKETS]; MODELS]; + for m in 0..MODELS { + for f in &mut freq[m] { + *f = u32::from(r.u16()); + } + // Model 16 g + shape has g + 2 buckets; bucket b > 0 holds 2^(b-1) symbols. + let used = m / 16 + 2; + let mut at = 0u32; + for b in 0..used { + if freq[m][b] == 0 { + return Err(Error("a model has an empty bucket")); + } + start[m][b] = at; + recip[m][b] = (1u64 << 32).div_ceil(u64::from(freq[m][b])); + at += freq[m][b] << b.saturating_sub(1); + } + if at != 1 << 16 { + return Err(Error("a model does not tile 65536")); + } + start[m][used..].fill(1 << 16); + for (window, b) in bucket[m].iter_mut().enumerate() { + let first = (window as u32) << 8; + *b = start[m][1..].iter().filter(|&&s| s <= first).count() as u8; + } + } + let rank1 = r.bytes(); + let rank3a = r.bytes(); + let rank3c = r.bytes(); + let rank4 = r.bytes(); + let rank5 = r.bytes(); + let mut ctrl7 = [0u16; 512]; + for c in &mut ctrl7 { + *c = r.u16(); + } + let mut plain = |ep: usize, ix: usize| { + (0..DICTIONARY) + .map(|_| { + let mut p = Plain::default(); + for v in &mut p.ep[..ep] { + *v = r.u8(); + } + for v in &mut p.ix[..ix] { + *v = r.u8(); + } + p + }) + .collect::>() + }; + let bc1 = plain(6, 16); + let bc3 = plain(8, 32); + let bc4 = plain(2, 16); + let bc5 = plain(4, 32); + let bc6 = (0..DICTIONARY) + .map(|_| { + // The endpoint entry's mode byte plays no part in decoding. + r.u8(); + let mut ep = Bc6Ep::default(); + for v in ep.e.as_flattened_mut() { + *v = r.u16(); + } + let mut ix = Bc6Ix { + mode: r.u8(), + ..Default::default() + }; + for v in &mut ix.ix { + *v = r.u16() as i16; + } + (ep, ix) + }) + .collect(); + let bc7 = (0..DICTIONARY) + .map(|_| { + let mut ep = Bc7Ep { + ctrl: r.u16(), + ..Default::default() + }; + for v in ep.rows.as_flattened_mut() { + *v = r.u16(); + } + let mut ix = Bc7Ix { + bits: [r.u8(), r.u8()], + ..Default::default() + }; + // Unused: the widths again in all entries but the first. + r.u16(); + // Only 15 slots for set 1, which no entry uses (0 bits). + for v in &mut ix.ix.as_flattened_mut()[..31] { + *v = r.u16() as i16; + } + (ep, ix) + }) + .collect(); + Ok(Tables { + freq, + start, + bucket, + recip, + rank1, + rank3a, + rank3c, + rank4, + rank5, + ctrl7, + bc1, + bc3, + bc4, + bc5, + bc6, + bc7, + }) + } +} + +/// Unpacks `src` (BC number `bc`, 1 and 3-7) into `dst`, whose length gives +/// the block count. The stream carries no size: bytes after the last one the +/// lanes need are ignored, a stream that runs out is an error. +pub fn decode(bc: u8, src: &[u8], dst: &mut [u8], tables: &Tables) -> Result<(), Error> { + let block = match bc { + 1 | 4 => 8, + 3 | 5 | 6 | 7 => 16, + _ => return Err(Error("unsupported BC format")), + }; + if dst.is_empty() || !dst.len().is_multiple_of(block) { + return Err(Error("destination is not a whole number of blocks")); + } + let blocks = dst.len() / block; + let (widths, per): (&[u8], usize) = match bc { + 1 => (&[7, 7, 4, 5, 4, 4, 5, 4, 7, 7, 7, 7], 1), + 3 => (&[3, 3, 7, 5, 5, 5, 5, 4, 5, 4, 7, 7], 2), + 4 => (&[7, 7, 7, 7, 5, 5, 5, 5, 5, 5, 5, 5], 1), + 5 => (&[3, 3, 7, 7, 5, 5, 5, 5, 5, 5, 5, 5], 2), + 6 => (&[3, 3, 7, 7, 7, 4, 4, 4, 5, 5, 5, 7, 7, 7, 7, 4], 2), + _ => (&[3, 3, 7, 7, 7, 7, 7, 6, 6, 4, 5, 7, 7, 7, 7, 4], 2), + }; + let stride = widths.len() * per; + let mut records = vec![0u8; blocks * stride]; + let mut next = src.iter().copied(); + lanes(tables, widths, per, blocks, |_| next.next(), &mut records)?; + let records = records.chunks_exact(stride); + let out = dst.chunks_exact_mut(block); + let t = tables; + match bc { + 1 => plain(records, out, &t.bc1, &BC1, |s| bc1_residual(t, s), bc1_pack), + 3 => plain(records, out, &t.bc3, &BC3, |s| bc3_residual(t, s), bc3_pack), + 4 => plain(records, out, &t.bc4, &BC4, |s| bc4_residual(t, s), bc4_pack), + 5 => plain(records, out, &t.bc5, &BC5, |s| bc5_residual(t, s), bc5_pack), + 6 => bc6(records, out, &t.bc6), + _ => bc7(records, out, t), + } +} + +// Lanes. + +#[derive(Clone, Copy, Default)] +struct Lane { + /// Symbol bits - 1 at the full alphabet. + width: u8, + /// 0 header, 1 length (low byte), 2 length high byte, 3 payload. + phase: u8, + long: bool, + reset: bool, + model: u8, + need: bool, + latch: Option, + out: Option, + stalled: bool, + x: u32, + left: u32, +} + +impl Lane { + /// One step: take the latched byte (header, length or payload) and + /// decode at most one symbol. + fn step(&mut self, t: &Tables) -> Result<(), Error> { + if self.phase != 3 { + let Some(b) = self.latch.take() else { + return Ok(()); + }; + self.need = true; + match self.phase { + 0 => { + // The top two bits shrink the alphabet; width >= 3. + let group = self.width - (b >> 6); + self.model = group * 16 + (b & 15); + self.reset = b & 0x10 != 0; + self.long = b & 0x20 != 0; + self.left = 0; + self.phase = 1; + } + 1 if self.long => { + self.left = b.into(); + self.phase = 2; + } + 1 => { + self.left = u32::from(b) + 1; + self.phase = 3; + } + _ => { + self.left = (u32::from(b) << 8 | self.left) + 257; + self.phase = 3; + } + } + return Ok(()); + } + let mut x = self.x; + if x < LOW + && let Some(b) = self.latch.take() + { + self.left = self.left.wrapping_sub(1); + x = x << 8 | u32::from(b); + } + self.need = self.left != 0 && self.latch.is_none(); + if x > LOW { + let freq = &t.freq[usize::from(self.model)]; + let start = &t.start[usize::from(self.model)]; + let slot = x & 0xffff; + // The bucket: starts are ascending, and 65536 past the model's last. + let b = bucket_of(t, self.model, slot); + // Bucket 0 holds symbol 0, which owns slots 1 .. f[0] - 1 (slot 0 + // is never used). Bucket b > 0 holds 2^(b-1) symbols of frequency + // f[b] from start[b] on; offset and frequency are below 2^16, where + // the reciprocal divides exactly. + let (sym, f, rem) = if b == 0 { + (0, freq[0] - 1, slot.wrapping_sub(1)) + } else { + let offset = slot - start[b]; + let q = ((u64::from(offset) * t.recip[usize::from(self.model)][b]) >> 32) as u32; + ((1u32 << (b - 1)) + q, freq[b], offset - q * freq[b]) + }; + self.x = (x >> 16).wrapping_mul(f).wrapping_add(rem); + self.out = Some(sym as u8); + } else if self.left != 0 { + // At exactly 2^24 the lane neither reads nor decodes again; only a + // lane that has delivered its symbols may end up there. + self.x = x; + } else { + // The fragment ends; a byte read in this step does not reach the carried state. + self.phase = 0; + self.need = self.latch.is_none(); + if self.reset { + self.x = 0; + } + } + Ok(()) + } +} + +/// The bucket holding `slot` (below 65536): the last whose start is at or +/// below it. The window table gives the bucket of the window's first slot; +/// later buckets that start inside the window are stepped over. +#[inline] +fn bucket_of(t: &Tables, model: u8, slot: u32) -> usize { + let start = &t.start[usize::from(model)]; + let mut b = usize::from(t.bucket[usize::from(model)][(slot >> 8) as usize]); + while start[b + 1] <= slot { + b += 1; + } + b +} + +/// Decodes `per` symbols per block on every lane into `records` (one record +/// of `widths.len() * per` symbols per block), taking input from `fetch` +/// (given the lane that takes the byte) in the order of the schedule: each +/// round the lanes step in order and take at most 8 bytes between them. +// shortcut: one lane step at a time (BC1 roughly 30-60 MB/s, BC7 15-20 MB/s +// on one core); if texture streaming needs more, run the schedule only to +// split the input per lane and decode the lanes apart. +fn lanes( + t: &Tables, + widths: &[u8], + per: usize, + blocks: usize, + mut fetch: impl FnMut(usize) -> Option, + records: &mut [u8], +) -> Result<(), Error> { + let mut lanes = [Lane::default(); 16]; + let lanes = &mut lanes[..widths.len()]; + for (lane, &width) in lanes.iter_mut().zip(widths) { + lane.width = width; + lane.need = true; + } + let stride = widths.len() * per; + let full = (1u32 << widths.len()) - 1; + let (mut pos, mut done, mut idle) = (0, 0u32, 0); + // Where symbol `pos` of lane 0 goes; lane j's is `per * j` further on. + let mut at = 0; + while pos < blocks * per { + let (mut taken, mut moved) = (0, false); + for (j, lane) in lanes.iter_mut().enumerate() { + let bit = 1 << j; + let before = taken; + if !lane.stalled { + lane.step(t)?; + } + let waiting = lane.out.is_some() && done & bit != 0; + if lane.need && !waiting && taken < ROUND_BYTES { + // Past the end nothing arrives; in a valid stream only finished lanes ask there. + if let Some(b) = fetch(j) { + lane.latch = Some(b); + taken += 1; + } + } + lane.stalled = (lane.need && before >= ROUND_BYTES) || waiting; + if !lane.stalled + && let Some(sym) = lane.out.take() + { + records[at + j * per] = sym; + done |= bit; + moved = true; + } + } + if done == full { + pos += 1; + at += if pos.is_multiple_of(per) { + stride - per + 1 + } else { + 1 + }; + done = 0; + moved = true; + } + // Nothing read and nothing delivered for a few rounds: no lane can go on. + idle = if taken > 0 || moved { 0 } else { idle + 1 }; + if idle > 3 { + return Err(Error("the stream ends early or is corrupt")); + } + } + Ok(()) +} + +// Blocks. + +/// The record's endpoint and index references. +fn references(s: &[u8], paired: bool) -> (usize, usize) { + let (d, ix) = if paired { + (interleave(s[0], s[1]), interleave(s[2], s[3])) + } else { + (s[0], s[1]) + }; + let delta = (d >> 1) ^ (d & 1).wrapping_neg(); + (usize::from(ix.wrapping_add(delta)), usize::from(ix)) +} + +/// Two 4-bit symbols, the first on the even bits. +fn interleave(a: u8, b: u8) -> u8 { + let spread = |v: u8| (0..4).fold(0, |acc, k| acc | (v >> k & 1) << (2 * k)); + spread(a) | spread(b) << 1 +} + +/// Block `i`'s reference `r`: 0 none, else `r` blocks back, before the first +/// block into the dictionary. +fn pick<'a, T>(i: usize, r: usize, history: &'a [T], dictionary: &'a [T], zero: &'a T) -> &'a T { + match r { + 0 => zero, + r if r <= i => &history[(i - r) % HISTORY], + r => &dictionary[r - i - 1], + } +} + +/// Zigzag residual (0, -1, 1, -2, ...) modulo 2^bits. +fn zz(v: u8, bits: u32) -> u8 { + let mask = ((1u32 << bits) - 1) as u8; + ((v >> 1) ^ if v & 1 != 0 { mask } else { 0 }) & mask +} + +/// Element widths of the plain formats' endpoints and indices. +struct Widths { + ep: [u8; 8], + ix: [u8; 32], + paired: bool, +} + +const fn widths(ep: [u8; 8], ix3: usize, ix2: usize, paired: bool) -> Widths { + let mut ix = [0; 32]; + let mut k = 0; + while k < ix3 + ix2 { + ix[k] = if k < ix3 { 3 } else { 2 }; + k += 1; + } + Widths { ep, ix, paired } +} + +const BC1: Widths = widths([5, 6, 5, 5, 6, 5, 0, 0], 0, 16, false); +const BC3: Widths = widths([5, 6, 5, 5, 6, 5, 8, 8], 16, 16, true); +const BC4: Widths = widths([8, 8, 0, 0, 0, 0, 0, 0], 16, 0, false); +const BC5: Widths = widths([8, 8, 8, 8, 0, 0, 0, 0], 32, 0, true); + +fn plain<'a>( + records: impl Iterator, + out: impl Iterator, + dictionary: &[Plain], + w: &Widths, + residual: impl Fn(&[u8]) -> Plain, + pack: fn(&Plain, &mut [u8]), +) -> Result<(), Error> { + let mut history = vec![Plain::default(); HISTORY]; + let zero = Plain::default(); + for (i, (s, block)) in records.zip(out).enumerate() { + let (ep_ref, ix_ref) = references(s, w.paired); + let ep_ref = &pick(i, ep_ref, &history, dictionary, &zero).ep; + let ix_ref = &pick(i, ix_ref, &history, dictionary, &zero).ix; + let mut v = residual(s); + for ((v, r), bits) in v.ep.iter_mut().zip(ep_ref).zip(w.ep) { + *v = v.wrapping_add(*r) & ((1u16 << bits) - 1) as u8; + } + for ((v, r), bits) in v.ix.iter_mut().zip(ix_ref).zip(w.ix) { + *v = v.wrapping_add(*r) & ((1u8 << bits) - 1); + } + history[i % HISTORY] = v; + pack(&v, block); + } + Ok(()) +} + +/// 2-bit index residuals: one symbol per 2x2 quad. +fn quads(rank: &[u8; 256], s: &[u8], ix: &mut [u8]) { + for (q, &sym) in s.iter().enumerate() { + let v = rank[usize::from(sym)]; + let base = (q >> 1) * 8 + (q & 1) * 2; + for (k, p) in [0, 1, 4, 5].into_iter().enumerate() { + ix[base + p] = v >> (2 * k) & 3; + } + } +} + +/// 3-bit index residuals: one symbol per two pixels in raster order. +fn pairs(rank: &[u8; 64], s: &[u8], ix: &mut [u8]) { + for (k, &sym) in s.iter().enumerate() { + let v = rank[usize::from(sym & 63)]; + ix[2 * k] = v & 7; + ix[2 * k + 1] = v >> 4 & 7; + } +} + +fn bc1_residual(t: &Tables, s: &[u8]) -> Plain { + let mut v = Plain::default(); + for (k, bits) in [5, 6, 5, 5, 6, 5].into_iter().enumerate() { + v.ep[k] = zz(s[2 + k], bits); + } + quads(&t.rank1, &s[8..12], &mut v.ix); + v +} + +fn bc3_residual(t: &Tables, s: &[u8]) -> Plain { + // Colour lanes carry each channel's two endpoints together. + let mut v = Plain { + ep: [ + zz(s[14], 5), + zz(s[16], 6), + zz(s[18], 5), + zz(s[15], 5), + zz(s[17], 6), + zz(s[19], 5), + zz(s[4], 8), + zz(s[5], 8), + ], + ..Default::default() + }; + pairs(&t.rank3a, &s[6..14], &mut v.ix[..16]); + quads(&t.rank3c, &s[20..24], &mut v.ix[16..]); + v +} + +fn bc4_residual(t: &Tables, s: &[u8]) -> Plain { + let mut v = Plain::default(); + v.ep[..2].copy_from_slice(&[zz(s[2], 8), zz(s[3], 8)]); + pairs(&t.rank4, &s[4..12], &mut v.ix[..16]); + v +} + +fn bc5_residual(t: &Tables, s: &[u8]) -> Plain { + let mut v = Plain::default(); + for k in 0..4 { + v.ep[k] = zz(s[4 + k], 8); + } + pairs(&t.rank5, &s[8..24], &mut v.ix); + v +} + +/// Indices along the endpoint line -> BC1 and BC4 codes. +const BC1_CODE: [u32; 4] = [0, 2, 3, 1]; +const BC4_CODE: [u64; 8] = [0, 2, 3, 4, 5, 6, 7, 1]; + +fn bc1_color(ep: &[u8], ix: &[u8], out: &mut [u8]) { + let c0 = u16::from(ep[0]) << 11 | u16::from(ep[1]) << 5 | u16::from(ep[2]); + let c1 = u16::from(ep[3]) << 11 | u16::from(ep[4]) << 5 | u16::from(ep[5]); + let bits = (0..16).fold(0, |acc, p| { + acc | BC1_CODE[usize::from(ix[p] & 3)] << (2 * p) + }); + out[..2].copy_from_slice(&c0.to_le_bytes()); + out[2..4].copy_from_slice(&c1.to_le_bytes()); + out[4..8].copy_from_slice(&bits.to_le_bytes()); +} + +/// BC4 half: endpoints are kept 128 below their stored value. +fn bc4_alpha(e0: u8, e1: u8, ix: &[u8], out: &mut [u8]) { + let bits = (0..16).fold(0u64, |acc, p| { + acc | BC4_CODE[usize::from(ix[p] & 7)] << (16 + 3 * p) + }); + let v = u64::from(e0 ^ 0x80) | u64::from(e1 ^ 0x80) << 8 | bits; + out[..8].copy_from_slice(&v.to_le_bytes()); +} + +fn bc1_pack(v: &Plain, out: &mut [u8]) { + bc1_color(&v.ep, &v.ix, out); +} + +fn bc3_pack(v: &Plain, out: &mut [u8]) { + bc4_alpha(v.ep[6], v.ep[7], &v.ix[..16], &mut out[..8]); + bc1_color(&v.ep, &v.ix[16..], &mut out[8..]); +} + +fn bc4_pack(v: &Plain, out: &mut [u8]) { + bc4_alpha(v.ep[0], v.ep[1], &v.ix, out); +} + +fn bc5_pack(v: &Plain, out: &mut [u8]) { + bc4_alpha(v.ep[0], v.ep[1], &v.ix[..16], &mut out[..8]); + bc4_alpha(v.ep[2], v.ep[3], &v.ix[16..], &mut out[8..]); +} + +/// A byte's even and odd bits as two zigzag-coded 4-bit residuals. +fn nibbles(b: u8, odd_first: bool) -> [i16; 2] { + let half = |v: u8| (0..4).fold(0u8, |acc, k| acc | (v >> (2 * k) & 1) << k); + let z = |u: u8| i16::from(u >> 1) ^ -i16::from(u & 1); + let (even, odd) = (z(half(b)), z(half(b >> 1))); + if odd_first { [odd, even] } else { [even, odd] } +} + +/// Index residual plus reference, both left-aligned to 16 bits at their own +/// widths, back to `bits` bits (signed). +fn add_index(cur: i16, bits: u8, refv: i16, ref_bits: u8) -> i16 { + let up = |v: i16, b: u8| { + if b == 0 || b > 16 { + 0 + } else { + (v as u16) << (16 - b) + } + }; + let sum = up(cur, bits).wrapping_add(up(refv, ref_bits)) as i16; + if bits == 0 { 0 } else { sum >> (16 - bits) } +} + +/// Little-endian bit writer for one 128-bit block. +#[derive(Default)] +struct Bits { + v: u128, + at: u32, +} + +impl Bits { + fn put(&mut self, value: u64, n: u32) { + if n > 0 && self.at < 128 { + self.v |= (u128::from(value) & ((1u128 << n) - 1)) << self.at; + } + self.at += n; + } +} + +// BC7. + +/// Public BC7 anchor indices: second subset of two; second and third of three. +const ANCHOR2: [u8; 64] = [ + 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 2, 8, 2, 2, 8, 8, 15, 2, 8, + 2, 2, 8, 8, 2, 2, 15, 15, 6, 8, 2, 8, 15, 15, 2, 8, 2, 2, 2, 15, 15, 6, 6, 2, 6, 8, 15, 15, 2, + 2, 15, 15, 15, 15, 15, 2, 2, 15, +]; +const ANCHOR3A: [u8; 64] = [ + 3, 3, 15, 15, 8, 3, 15, 15, 8, 8, 6, 6, 6, 5, 3, 3, 3, 3, 8, 15, 3, 3, 6, 10, 5, 8, 8, 6, 8, 5, + 15, 15, 8, 15, 3, 5, 6, 10, 8, 15, 15, 3, 15, 5, 15, 15, 15, 15, 3, 15, 5, 5, 5, 8, 5, 10, 5, + 10, 8, 13, 15, 12, 3, 3, +]; +const ANCHOR3B: [u8; 64] = [ + 15, 8, 8, 3, 15, 15, 3, 8, 15, 15, 15, 15, 15, 15, 15, 8, 15, 8, 15, 3, 15, 8, 15, 8, 3, 15, 6, + 10, 15, 15, 10, 8, 15, 3, 15, 10, 10, 8, 9, 10, 6, 15, 8, 15, 3, 6, 6, 8, 15, 3, 15, 15, 15, + 15, 15, 15, 15, 15, 15, 15, 3, 15, 15, 8, +]; + +/// Endpoint bits of R G B A per mode (public), before p-bits and rotation. +const BC7_BITS: [[u8; 4]; 8] = [ + [4, 4, 4, 0], + [6, 6, 6, 0], + [5, 5, 5, 0], + [7, 7, 7, 0], + [5, 5, 5, 6], + [7, 7, 7, 8], + [7, 7, 7, 7], + [5, 5, 5, 5], +]; +/// Index bits of the primary and secondary sets per mode. +const BC7_INDEX: [[u8; 2]; 8] = [ + [3, 0], + [3, 0], + [2, 0], + [2, 0], + [3, 2], + [2, 2], + [4, 0], + [2, 0], +]; + +fn pbits(mode: u16) -> bool { + matches!(mode, 0 | 1 | 3 | 6 | 7) +} + +/// Channel precisions: the p-bit is red's lowest bit; rotation swaps alpha +/// with the rotated channel. +fn bc7_precision(ctrl: u16) -> [u8; 4] { + let (mode, rot) = (ctrl & 7, usize::from(ctrl >> 3 & 3)); + let mut p = BC7_BITS[usize::from(mode)]; + if rot != 0 { + p.swap(3, rot - 1); + } else if pbits(mode) { + p[0] += 1; + } + p +} + +fn bc7<'a>( + records: impl Iterator, + out: impl Iterator, + t: &Tables, +) -> Result<(), Error> { + let mut history = vec![(Bc7Ep::default(), Bc7Ix::default()); HISTORY]; + let zero = (Bc7Ep::default(), Bc7Ix::default()); + for (i, (s, block)) in records.zip(out).enumerate() { + let (ep_ref, ix_ref) = references(s, true); + let ctrl = t.ctrl7[usize::from(s[31] & 15) << 5 | usize::from(s[30] & 31)]; + if ctrl == 0 { + return Err(Error("unused BC7 control code")); + } + let mode = usize::from(ctrl & 7); + let subsets = usize::from((ctrl & 0xff) >> 6); + let prec = bc7_precision(ctrl); + let three = subsets == 3; + let or0 = |v: u8| if three { 0 } else { v }; + let if3 = |v: u8| if three { v } else { 0 }; + let stored = [ + [s[4], s[5], s[6], s[7], s[8], s[9], or0(s[10]), or0(s[11])], + [ + s[12], + s[13], + s[14], + s[15], + s[16], + s[17], + or0(s[18]), + or0(s[19]), + ], + [ + s[20], + s[21], + if3(s[10]), + if3(s[11]), + if3(s[18]), + if3(s[19]), + 0, + 0, + ], + ]; + let r = &pick(i, ep_ref, &history, &t.bc7, &zero).0; + let mut ep = Bc7Ep { + ctrl, + ..Default::default() + }; + // Rows the reference lacks build on its first row. + let common = subsets.min(usize::from((r.ctrl & 0xff) >> 6)); + let columns = if prec[3] > 0 { 8 } else { 6 }; + for c in 0..columns { + let p = prec[c / 2]; + if p == 0 { + continue; + } + let mask = 0xffffu16 << (16 - p); + for (row, st) in stored.iter().enumerate().take(subsets) { + let v = st[c]; + let residual = + (u16::from(v >> 1) ^ (v & 1).wrapping_neg() as i8 as u16) << (16 - p); + let base = r.rows[if row < common { row } else { 0 }][c] & mask; + ep.rows[row][c] = base.wrapping_add(residual); + } + } + let bits = BC7_INDEX[mode]; + let rx = &pick(i, ix_ref, &history, &t.bc7, &zero).1; + let mut ix = Bc7Ix { + bits, + ..Default::default() + }; + for (set, offsets) in [[22, 24, 26, 28], [12, 14, 16, 20]].into_iter().enumerate() { + if bits[set] == 0 { + continue; + } + for (k, o) in offsets.into_iter().enumerate() { + for (b, &byte) in s[o..o + 2].iter().enumerate() { + let pair = nibbles(byte, k < 3); + for (h, &v) in pair.iter().enumerate() { + let p = 4 * k + 2 * b + h; + ix.ix[set][p] = add_index(v, bits[set], rx.ix[set][p], rx.bits[set]); + } + } + } + } + history[i % HISTORY] = (ep, ix); + bc7_pack(&ep, &ix, prec, block); + } + Ok(()) +} + +fn bc7_pack(ep: &Bc7Ep, ix: &Bc7Ix, prec: [u8; 4], out: &mut [u8]) { + let ctrl = ep.ctrl; + let mode = ctrl & 7; + let subsets = usize::from((ctrl & 0xff) >> 6); + let part = usize::from(ctrl >> 8 & 63); + let rot = usize::from(ctrl >> 3 & 3); + let mut w = Bits::default(); + w.put(1 << mode, u32::from(mode) + 1); + match mode { + 0 => w.put(part as u64, 4), + 1 | 2 | 3 | 7 => w.put(part as u64, 6), + 4 => { + w.put(rot as u64, 2); + w.put(u64::from(ctrl >> 5 & 1), 1); + } + 5 => w.put(rot as u64, 2), + _ => {} + } + let ends = 2 * subsets; + let field = |row: usize, col: usize, p: u8| u64::from(ep.rows[row][col] >> (16 - p)); + let mut order = [0, 1, 2, 3]; + if rot != 0 { + order.swap(3, rot - 1); + } + for ch in order { + let p = prec[ch]; + if p == 0 { + continue; + } + let drop = u32::from(ch == 0 && pbits(mode)); + for e in 0..ends { + w.put(field(e / 2, 2 * ch + e % 2, p) >> drop, u32::from(p) - drop); + } + } + match mode { + 1 => (0..subsets).for_each(|row| w.put(field(row, 0, prec[0]) & 1, 1)), + m if pbits(m) => (0..ends).for_each(|e| w.put(field(e / 2, e % 2, prec[0]) & 1, 1)), + _ => {} + } + let anchors: &[u8] = match subsets { + 2 => &[0, ANCHOR2[part]], + 3 => &[0, ANCHOR3A[part], ANCHOR3B[part]], + _ => &[0], + }; + let mut indices = |set: usize| { + let bits = ix.bits[set]; + for (p, &v) in ix.ix[set].iter().enumerate() { + let n = u32::from(bits) - u32::from(anchors.contains(&(p as u8))); + w.put(u64::from(v as u16), n); + } + }; + match mode { + 4 => { + indices(1); + indices(0); + } + 5 => { + indices(0); + indices(1); + } + _ => indices(0), + } + out.copy_from_slice(&w.v.to_le_bytes()); +} + +// BC6H. + +/// Bits of endpoint 0, then of the other endpoints' R, G, B, per mode 1-14. +const BC6_BITS: [[u8; 4]; 15] = [ + [0; 4], + [10, 5, 5, 5], + [7, 6, 6, 6], + [11, 5, 4, 4], + [11, 4, 5, 4], + [11, 4, 4, 5], + [9, 5, 5, 5], + [8, 6, 5, 5], + [8, 5, 6, 5], + [8, 5, 5, 6], + [6, 6, 6, 6], + [10, 10, 10, 10], + [11, 9, 9, 9], + [12, 8, 8, 8], + [16, 4, 4, 4], +]; +/// Mode code and its width, modes 1-14. +const BC6_CODE: [(u64, u32); 15] = [ + (0, 0), + (0, 2), + (1, 2), + (2, 5), + (6, 5), + (10, 5), + (14, 5), + (18, 5), + (22, 5), + (26, 5), + (30, 5), + (3, 5), + (7, 5), + (11, 5), + (15, 5), +]; + +/// A run of the public BC6H layout: `len` bits of channel `ch` (0-2; 3 is +/// the partition) of endpoint `ep`, from bit `first` up. +#[derive(Clone, Copy)] +struct Run { + ch: u8, + ep: u8, + first: u8, + len: u8, +} + +const fn r(ch: u8, ep: u8, first: u8, len: u8) -> Run { + Run { ch, ep, first, len } +} + +const R: u8 = 0; +const G: u8 = 1; +const B: u8 = 2; +const D: Run = r(3, 0, 0, 5); + +/// The header after the mode bits, per mode 1-14. Modes 13 and 14 write the +/// high base bits in ascending order (what the console's packer does). +#[rustfmt::skip] +const BC6_LAYOUT: [&[Run]; 15] = [ + &[], + &[ + r(G, 2, 4, 1), r(B, 2, 4, 1), r(B, 3, 4, 1), r(R, 0, 0, 10), r(G, 0, 0, 10), r(B, 0, 0, 10), + r(R, 1, 0, 5), r(G, 3, 4, 1), r(G, 2, 0, 4), r(G, 1, 0, 5), r(B, 3, 0, 1), r(G, 3, 0, 4), + r(B, 1, 0, 5), r(B, 3, 1, 1), r(B, 2, 0, 4), r(R, 2, 0, 5), r(B, 3, 2, 1), r(R, 3, 0, 5), + r(B, 3, 3, 1), D, + ], + &[ + r(G, 2, 5, 1), r(G, 3, 4, 1), r(G, 3, 5, 1), r(R, 0, 0, 7), r(B, 3, 0, 1), r(B, 3, 1, 1), + r(B, 2, 4, 1), r(G, 0, 0, 7), r(B, 2, 5, 1), r(B, 3, 2, 1), r(G, 2, 4, 1), r(B, 0, 0, 7), + r(B, 3, 3, 1), r(B, 3, 5, 1), r(B, 3, 4, 1), r(R, 1, 0, 6), r(G, 2, 0, 4), r(G, 1, 0, 6), + r(G, 3, 0, 4), r(B, 1, 0, 6), r(B, 2, 0, 4), r(R, 2, 0, 6), r(R, 3, 0, 6), D, + ], + &[ + r(R, 0, 0, 10), r(G, 0, 0, 10), r(B, 0, 0, 10), r(R, 1, 0, 5), r(R, 0, 10, 1), r(G, 2, 0, 4), + r(G, 1, 0, 4), r(G, 0, 10, 1), r(B, 3, 0, 1), r(G, 3, 0, 4), r(B, 1, 0, 4), r(B, 0, 10, 1), + r(B, 3, 1, 1), r(B, 2, 0, 4), r(R, 2, 0, 5), r(B, 3, 2, 1), r(R, 3, 0, 5), r(B, 3, 3, 1), D, + ], + &[ + r(R, 0, 0, 10), r(G, 0, 0, 10), r(B, 0, 0, 10), r(R, 1, 0, 4), r(R, 0, 10, 1), r(G, 3, 4, 1), + r(G, 2, 0, 4), r(G, 1, 0, 5), r(G, 0, 10, 1), r(G, 3, 0, 4), r(B, 1, 0, 4), r(B, 0, 10, 1), + r(B, 3, 1, 1), r(B, 2, 0, 4), r(R, 2, 0, 4), r(B, 3, 0, 1), r(B, 3, 2, 1), r(R, 3, 0, 4), + r(G, 2, 4, 1), r(B, 3, 3, 1), D, + ], + &[ + r(R, 0, 0, 10), r(G, 0, 0, 10), r(B, 0, 0, 10), r(R, 1, 0, 4), r(R, 0, 10, 1), r(B, 2, 4, 1), + r(G, 2, 0, 4), r(G, 1, 0, 4), r(G, 0, 10, 1), r(B, 3, 0, 1), r(G, 3, 0, 4), r(B, 1, 0, 5), + r(B, 0, 10, 1), r(B, 2, 0, 4), r(R, 2, 0, 4), r(B, 3, 1, 1), r(B, 3, 2, 1), r(R, 3, 0, 4), + r(B, 3, 4, 1), r(B, 3, 3, 1), D, + ], + &[ + r(R, 0, 0, 9), r(B, 2, 4, 1), r(G, 0, 0, 9), r(G, 2, 4, 1), r(B, 0, 0, 9), r(B, 3, 4, 1), + r(R, 1, 0, 5), r(G, 3, 4, 1), r(G, 2, 0, 4), r(G, 1, 0, 5), r(B, 3, 0, 1), r(G, 3, 0, 4), + r(B, 1, 0, 5), r(B, 3, 1, 1), r(B, 2, 0, 4), r(R, 2, 0, 5), r(B, 3, 2, 1), r(R, 3, 0, 5), + r(B, 3, 3, 1), D, + ], + &[ + r(R, 0, 0, 8), r(G, 3, 4, 1), r(B, 2, 4, 1), r(G, 0, 0, 8), r(B, 3, 2, 1), r(G, 2, 4, 1), + r(B, 0, 0, 8), r(B, 3, 3, 1), r(B, 3, 4, 1), r(R, 1, 0, 6), r(G, 2, 0, 4), r(G, 1, 0, 5), + r(B, 3, 0, 1), r(G, 3, 0, 4), r(B, 1, 0, 5), r(B, 3, 1, 1), r(B, 2, 0, 4), r(R, 2, 0, 6), + r(R, 3, 0, 6), D, + ], + &[ + r(R, 0, 0, 8), r(B, 3, 0, 1), r(B, 2, 4, 1), r(G, 0, 0, 8), r(G, 2, 5, 1), r(G, 2, 4, 1), + r(B, 0, 0, 8), r(G, 3, 5, 1), r(B, 3, 4, 1), r(R, 1, 0, 5), r(G, 3, 4, 1), r(G, 2, 0, 4), + r(G, 1, 0, 6), r(G, 3, 0, 4), r(B, 1, 0, 5), r(B, 3, 1, 1), r(B, 2, 0, 4), r(R, 2, 0, 5), + r(B, 3, 2, 1), r(R, 3, 0, 5), r(B, 3, 3, 1), D, + ], + &[ + r(R, 0, 0, 8), r(B, 3, 1, 1), r(B, 2, 4, 1), r(G, 0, 0, 8), r(B, 2, 5, 1), r(G, 2, 4, 1), + r(B, 0, 0, 8), r(B, 3, 5, 1), r(B, 3, 4, 1), r(R, 1, 0, 5), r(G, 3, 4, 1), r(G, 2, 0, 4), + r(G, 1, 0, 5), r(B, 3, 0, 1), r(G, 3, 0, 4), r(B, 1, 0, 6), r(B, 2, 0, 4), r(R, 2, 0, 5), + r(B, 3, 2, 1), r(R, 3, 0, 5), r(B, 3, 3, 1), D, + ], + &[ + r(R, 0, 0, 6), r(G, 3, 4, 1), r(B, 3, 0, 1), r(B, 3, 1, 1), r(B, 2, 4, 1), r(G, 0, 0, 6), + r(G, 2, 5, 1), r(B, 2, 5, 1), r(B, 3, 2, 1), r(G, 2, 4, 1), r(B, 0, 0, 6), r(G, 3, 5, 1), + r(B, 3, 3, 1), r(B, 3, 5, 1), r(B, 3, 4, 1), r(R, 1, 0, 6), r(G, 2, 0, 4), r(G, 1, 0, 6), + r(G, 3, 0, 4), r(B, 1, 0, 6), r(B, 2, 0, 4), r(R, 2, 0, 6), r(R, 3, 0, 6), D, + ], + &[r(R, 0, 0, 10), r(G, 0, 0, 10), r(B, 0, 0, 10), r(R, 1, 0, 10), r(G, 1, 0, 10), r(B, 1, 0, 10)], + &[ + r(R, 0, 0, 10), r(G, 0, 0, 10), r(B, 0, 0, 10), r(R, 1, 0, 9), r(R, 0, 10, 1), r(G, 1, 0, 9), + r(G, 0, 10, 1), r(B, 1, 0, 9), r(B, 0, 10, 1), + ], + &[ + r(R, 0, 0, 10), r(G, 0, 0, 10), r(B, 0, 0, 10), r(R, 1, 0, 8), r(R, 0, 10, 2), r(G, 1, 0, 8), + r(G, 0, 10, 2), r(B, 1, 0, 8), r(B, 0, 10, 2), + ], + &[ + r(R, 0, 0, 10), r(G, 0, 0, 10), r(B, 0, 0, 10), r(R, 1, 0, 4), r(R, 0, 10, 6), r(G, 1, 0, 4), + r(G, 0, 10, 6), r(B, 1, 0, 4), r(B, 0, 10, 6), + ], +]; + +fn bc6_index_bits(mode: u8) -> u8 { + match mode { + 1..=10 => 3, + 11..=14 => 4, + _ => 0, + } +} + +fn bc6<'a>( + records: impl Iterator, + out: impl Iterator, + dictionary: &[(Bc6Ep, Bc6Ix)], +) -> Result<(), Error> { + let mut history = vec![(Bc6Ep::default(), Bc6Ix::default()); HISTORY]; + let zero = ( + Bc6Ep::default(), + Bc6Ix { + mode: 11, + ..Default::default() + }, + ); + let z = |v: u16| (v >> 1) ^ (v & 1).wrapping_neg(); + let wide = |a: u8, b: u8| { + (0..8).fold(0u16, |acc, k| { + acc | u16::from(a >> k & 1) << (2 * k) | u16::from(b >> k & 1) << (2 * k + 1) + }) + }; + for (i, (s, block)) in records.zip(out).enumerate() { + let (ep_ref, ix_ref) = references(s, true); + let mode = s[30].wrapping_add(1); + if !(1..=14).contains(&mode) { + return Err(Error("BC6H mode out of range")); + } + let two = mode < 11; + let shift = BC6_BITS[usize::from(mode)].map(|b| 16 - u32::from(b)); + let e0 = [wide(s[4], s[5]), wide(s[6], s[7]), wide(s[8], s[9])].map(z); + let e1 = [wide(s[10], s[11]), wide(s[12], s[13]), wide(s[14], s[15])].map(z); + let (e2, e3) = if two { + ( + [s[16], s[18], s[20]].map(|v| z(v.into())), + [s[17], s[19], s[21]].map(|v| z(v.into())), + ) + } else { + (e0, e1) + }; + let r = &pick(i, ep_ref, &history, dictionary, &zero).0; + let mut ep = Bc6Ep::default(); + // Endpoint 0 at the base precision, the others per channel; the + // reference is cut by the mask after the sum. + let mask = |sh: u32| 0xffffu16 << sh; + for ((e, &r), res) in ep.e[0].iter_mut().zip(&r.e[0]).zip(e0) { + *e = r.wrapping_add(res << shift[0]) & mask(shift[0]); + } + for (k, res) in [e1, e2, e3] + .iter() + .enumerate() + .take(if two { 3 } else { 1 }) + { + for c in 0..3 { + ep.e[k + 1][c] = + r.e[k + 1][c].wrapping_add(res[c] << shift[1 + c]) & mask(shift[1 + c]); + } + } + if !two { + for c in 0..3 { + ep.e[2][c] = (ep.e[0][c] >> shift[0]) << shift[1]; + } + ep.e[3] = ep.e[1]; + } + let rx = &pick(i, ix_ref, &history, dictionary, &zero).1; + let bits = bc6_index_bits(mode); + let mut ix = Bc6Ix { + mode, + ..Default::default() + }; + for k in 0..8 { + for (h, v) in nibbles(s[22 + k], k < 6).into_iter().enumerate() { + let p = 2 * k + h; + ix.ix[p] = add_index(v, bits, rx.ix[p], bc6_index_bits(rx.mode)); + } + } + history[i % HISTORY] = (ep, ix); + // Fields: the working value has its top bit flipped. + let field = |k: usize, c: usize| { + let sh = if k == 0 { shift[0] } else { shift[1 + c] }; + u64::from((ep.e[k][c] ^ 0x8000) >> sh) + }; + let mut w = Bits::default(); + let (code, n) = BC6_CODE[usize::from(mode)]; + w.put(code, n); + let part = s[31] & 31; + for run in BC6_LAYOUT[usize::from(mode)] { + if run.ch == 3 { + w.put(part.into(), 5); + } else { + w.put( + field(run.ep.into(), run.ch.into()) >> run.first, + run.len.into(), + ); + } + } + let anchor = if two { ANCHOR2[usize::from(part)] } else { 0 }; + for (p, &v) in ix.ix.iter().enumerate() { + let short = p == 0 || p == usize::from(anchor); + let v = (v as u16).wrapping_add(1 << (bits - 1)); + w.put(v.into(), u32::from(bits) - u32::from(short)); + } + block.copy_from_slice(&w.v.to_le_bytes()); + } + Ok(()) +} + +#[cfg(test)] +mod tests { + #[test] + fn the_shipped_tables_parse() { + assert!(super::Tables::builtin().is_ok()); + } + + use super::*; + + /// Tables we made: uniform models, identity ranks, a BC7 code per mode, + /// empty dictionaries. + fn tables() -> Vec { + let mut t = Vec::new(); + for m in 0..MODELS { + let g = m / 16; + for b in 0..BUCKETS { + let f: u16 = if b < g + 2 { 1 << (15 - g) } else { 0 }; + t.extend_from_slice(&f.to_le_bytes()); + } + } + t.extend((0..=255u8).map(|v| v & 0x77)); // rank1 (unused by the tests beyond 2-bit fields) + t.extend(0..64u8); // rank3a + t.extend(0..=255u8); // rank3c + t.extend((0..64u8).map(|v| (v & 7) | (v >> 3) << 4)); // rank4: low 3 bits, next 3 bits + t.extend(0..64u8); // rank5 + for code in 0..512u16 { + // Code c: mode 6 (one subset), the only one the tests use. + let ctrl: u16 = if code == 0 { 0x46 } else { 0 }; + t.extend_from_slice(&ctrl.to_le_bytes()); + } + t.resize(TABLES_SIZE, 0); + t + } + + /// A lane's symbols as one fragment: uniform model, rANS from 2^24, no + /// reset, so the lane keeps 2^24 when it ends. + fn fragment(width: u8, symbols: &[u8]) -> Vec { + let f = 1u32 << (15 - width); + let mut x = LOW; + let mut bytes = Vec::new(); + for &s in symbols.iter().rev() { + let (freq, start) = if s == 0 { + (f - 1, 1) + } else { + (f, u32::from(s) * f) + }; + while x >= (freq << 16) { + bytes.push(x as u8); + x >>= 8; + } + x = ((x / freq) << 16) + x % freq + start; + } + bytes.extend_from_slice(&x.to_le_bytes()); + bytes.reverse(); + let mut out = vec![0]; + if bytes.len() > 256 { + out[0] |= 0x20; + let n = bytes.len() - 257; + out.extend_from_slice(&[n as u8, (n >> 8) as u8]); + } else { + out.push((bytes.len() - 1) as u8); + } + out.extend(bytes); + out + } + + /// Interleaves per-lane fragments the way the decoder takes bytes. A lane + /// that has finished still asks: a filler fragment (two payload bytes) + /// brings its state to 2^24 with a byte latched, which parks it for good. + fn stream(t: &Tables, widths: &[u8], per: usize, records: &[Vec]) -> Vec { + let stride = widths.len() * per; + let mut queues: Vec> = (0..widths.len()) + .map(|j| { + let syms: Vec = records + .iter() + .flat_map(|r| r[j * per..j * per + per].to_vec()) + .collect(); + let mut bytes = fragment(widths[j], &syms); + bytes.extend([0, 1, 0, 0]); + bytes.into() + }) + .collect(); + let mut out = Vec::new(); + let mut check = vec![0; records.len() * stride]; + let fetch = |j: usize| { + let b = queues[j] + .pop_front() + .expect("a parked lane asked for input"); + out.push(b); + Some(b) + }; + lanes(t, widths, per, records.len(), fetch, &mut check).unwrap(); + assert_eq!(check, records.concat()); + out + } + + const BC4_LANES: [u8; 12] = [7, 7, 7, 7, 5, 5, 5, 5, 5, 5, 5, 5]; + + fn zigzag(v: i32) -> u8 { + if v >= 0 { + (2 * v) as u8 + } else { + (-2 * v - 1) as u8 + } + } + + #[test] + fn bc4_blocks_with_and_without_references() { + let t = Tables::parse(&tables()).unwrap(); + // Block 0: endpoints 10, -3 (+128 stored), indices p -> p & 7. + let mut b0 = vec![0, 0, zigzag(10), zigzag(-3)]; + b0.extend((0..8).map(|k| ((2 * k) & 7) | ((2 * k + 1) & 7) << 3)); + // Block 1 refers to block 0 for both: residual endpoints +1, +1; indices +1. + let mut b1 = vec![0, 1, zigzag(1), zigzag(1)]; + b1.extend((0..8).map(|_| 1 | 1 << 3)); + let src = stream(&t, &BC4_LANES, 1, &[b0, b1]); + let mut dst = [0u8; 16]; + decode(4, &src, &mut dst, &t).unwrap(); + let block = |e0: u8, e1: u8, ix: &dyn Fn(usize) -> usize| { + let bits = (0..16).fold(0u64, |a, p| a | BC4_CODE[ix(p)] << (16 + 3 * p)); + (u64::from(e0) | u64::from(e1) << 8 | bits).to_le_bytes() + }; + assert_eq!(dst[..8], block(138, 125, &|p| p & 7)); + assert_eq!(dst[8..], block(139, 126, &|p| (p + 1) & 7)); + } + + #[test] + fn lanes_take_bytes_in_schedule_order_and_long_fragments() { + let t = Tables::parse(&tables()).unwrap(); + // Many blocks: long fragments (over 256 payload bytes) on the wide lanes. + let records: Vec> = (0..400u32) + .map(|i| { + let mut r = vec![0, 0, (i * 7) as u8, (i * 13) as u8]; + r.extend((0..8).map(|k| ((i + k) * 5 % 64) as u8)); + r + }) + .collect(); + let src = stream(&t, &BC4_LANES, 1, &records); + let mut got = vec![0u8; records.len() * 12]; + let mut next = src.iter().copied(); + lanes(&t, &BC4_LANES, 1, records.len(), |_| next.next(), &mut got).unwrap(); + assert_eq!(got, records.concat()); + } + + #[test] + fn bc7_mode6_block() { + let t = Tables::parse(&tables()).unwrap(); + // Control code 0 -> mode 6; endpoints R 8 bits (p-bit low), G B A 7 bits. + let mut s = vec![0u8; 32]; + s[4] = zigzag(0x55); // R0 = 0x55: field 0x2a, p-bit 1 + s[5] = zigzag(-1); // R1 = 0xff (8 bits) + s[6] = zigzag(3); + s[10] = zigzag(0x7f >> 1); + let src = stream( + &t, + &[3, 3, 7, 7, 7, 7, 7, 6, 6, 4, 5, 7, 7, 7, 7, 4], + 2, + &[s], + ); + let mut dst = [0u8; 16]; + decode(7, &src, &mut dst, &t).unwrap(); + let mut w = Bits::default(); + w.put(1 << 6, 7); + for (v, n) in [ + (0x2a, 7), + (0x7f, 7), + (3, 7), + (0, 7), + (0, 7), + (0, 7), + (0x3f, 7), + (0, 7), + ] { + w.put(v, n); + } + w.put(1, 1); + w.put(1, 1); + assert_eq!(dst, w.v.to_le_bytes()); + } + + #[test] + fn malformed_input_is_an_error() { + let t = Tables::parse(&tables()).unwrap(); + let records: Vec> = (0..64u8) + .map(|i| vec![0, 0, i, i, 1, 2, 3, 4, 5, 6, 7, 8]) + .collect(); + let src = stream(&t, &BC4_LANES, 1, &records); + let mut dst = vec![0u8; 64 * 8]; + decode(4, &src, &mut dst, &t).unwrap(); + // Truncated. + assert!(decode(4, &src[..src.len() / 2], &mut dst, &t).is_err()); + // Headers promising more payload than the stream holds. (Other corrupt + // headers decode to garbage: the format has no redundancy.) + let headers = [[0x30; 8], [0xff; 8]].concat(); + assert!(decode(4, &headers, &mut dst[..8], &t).is_err()); + assert!(decode(4, &[], &mut dst, &t).is_err()); + // Destination not a whole number of blocks, empty, more blocks than coded. + assert!(decode(4, &src, &mut dst[..12], &t).is_err()); + assert!(decode(4, &src, &mut [], &t).is_err()); + assert!(decode(4, &src, &mut vec![0u8; 65 * 8], &t).is_err()); + // Unsupported formats, bad tables. + assert!(decode(2, &src, &mut dst, &t).is_err()); + assert!(Tables::parse(&[0; 16]).is_err()); + let mut no_tiling = tables(); + no_tiling[0] = 1; + assert!(Tables::parse(&no_tiling).is_err()); + } + + #[test] + fn noise_never_panics() { + let t = Tables::parse(&tables()).unwrap(); + let mut seed = 0x2545_f491_4f6c_dd1du64; + for round in 0..300 { + let len = round * 7 % 900; + let src: Vec = (0..len) + .map(|_| { + seed ^= seed << 13; + seed ^= seed >> 7; + seed ^= seed << 17; + seed as u8 + }) + .collect(); + for bc in [1, 3, 4, 5, 6, 7] { + let mut dst = vec![0u8; 16 * (1 + round % 40)]; + let _ = decode(bc, &src, &mut dst, &t); + } + } + } + + /// The window table finds the bucket a scan of the starts finds, for + /// every slot of every model, in the shipped tables and in ours (whose + /// buckets are wide) and in tables whose buckets are one slot wide. + #[test] + fn bucket_lookup_matches_a_scan_of_the_starts() { + let mut narrow = tables(); + for m in 0..MODELS { + // Buckets 1.. of one slot each where they fit; bucket 0 takes the rest. + let used = m / 16 + 2; + let rest = (1u32 << 16) - (1..used).map(|b| 1u32 << (b - 1)).sum::(); + for b in 0..used { + let f = if b == 0 { rest } else { 1 }; + narrow[(m * BUCKETS + b) * 2..][..2].copy_from_slice(&(f as u16).to_le_bytes()); + } + } + for t in [ + Tables::builtin().unwrap(), + Tables::parse(&tables()).unwrap(), + Tables::parse(&narrow).unwrap(), + ] { + for model in 0..MODELS as u8 { + let start = &t.start[usize::from(model)]; + for slot in 0..1u32 << 16 { + let scan = start[1..].iter().filter(|&&s| s <= slot).count(); + assert_eq!( + bucket_of(&t, model, slot), + scan, + "model {model} slot {slot}" + ); + } + } + } + } + + /// One rANS decode as first written: scan for the bucket, divide for the + /// symbol, rebuild its frequency and start from the symbol. + fn reference_decode(t: &Tables, model: u8, x: u32) -> (u8, u32) { + let (freq, start) = (&t.freq[usize::from(model)], &t.start[usize::from(model)]); + let slot = x & 0xffff; + let b = start[1..BUCKETS].iter().filter(|&&s| s <= slot).count(); + let sym = match b { + 0 => 0, + 1 => 1, + _ => (1u32 << (b - 1)) + (slot - start[b]) / freq[b], + } as u8; + let (f, c) = if sym == 0 { + (freq[0] - 1, 1) + } else { + let k = (8 - sym.leading_zeros()) as usize; + let f = freq[k]; + ( + f, + ((u32::from(sym) - (1 << (k - 1))) * f + start[k]) & 0xffff, + ) + }; + ( + sym, + (x >> 16).wrapping_mul(f).wrapping_sub(c).wrapping_add(slot), + ) + } + + /// A payload step decodes the symbol and state the first version did, for + /// every model and slot of the shipped tables and ours, at assorted states. + #[test] + fn payload_step_matches_the_reference_decode() { + for t in [ + Tables::builtin().unwrap(), + Tables::parse(&tables()).unwrap(), + ] { + for model in 0..MODELS as u8 { + for high in [0x100u32, 0x1234, 0xffff] { + for slot in 0..1u32 << 16 { + let x = high << 16 | slot; + if x <= LOW { + continue; + } + let mut lane = Lane { + phase: 3, + model, + x, + left: 1, + ..Default::default() + }; + lane.step(&t).unwrap(); + let (sym, next) = reference_decode(&t, model, x); + assert_eq!( + (lane.out, lane.x), + (Some(sym), next), + "model {model} x {x:#x}" + ); + } + } + } + } + } + + /// Pseudo-random records that fit each lane's alphabet; BC7 keeps control + /// code 0 (mode 6), the only one the synthetic tables define. + fn random_records(widths: &[u8], per: usize, blocks: usize, bc7: bool) -> Vec> { + let mut seed = 0x9e37_79b9_7f4a_7c15u64; + (0..blocks) + .map(|_| { + let mut r: Vec = (0..widths.len() * per) + .map(|k| { + seed ^= seed << 13; + seed ^= seed >> 7; + seed ^= seed << 17; + let alphabet = 1u32 << (widths[k / per] + 1); + (seed as u32 % alphabet) as u8 + }) + .collect(); + if bc7 { + r[30] = 0; + r[31] = 0; + } + r + }) + .collect() + } + + /// The fast paths decode exactly what one lane step at a time does, on + /// every format's lane layout, with short and long fragments. + #[test] + fn every_layout_round_trips_through_the_lanes() { + let t = Tables::parse(&tables()).unwrap(); + let layouts: [(&[u8], usize); 6] = [ + (&[7, 7, 4, 5, 4, 4, 5, 4, 7, 7, 7, 7], 1), + (&[3, 3, 7, 5, 5, 5, 5, 4, 5, 4, 7, 7], 2), + (&BC4_LANES, 1), + (&[3, 3, 7, 7, 5, 5, 5, 5, 5, 5, 5, 5], 2), + (&[3, 3, 7, 7, 7, 4, 4, 4, 5, 5, 5, 7, 7, 7, 7, 4], 2), + (&[3, 3, 7, 7, 7, 7, 7, 6, 6, 4, 5, 7, 7, 7, 7, 4], 2), + ]; + for (widths, per) in layouts { + for blocks in [1, 2, 17, 300, 1000] { + let records = random_records(widths, per, blocks, false); + let src = stream(&t, widths, per, &records); + let mut got = vec![0u8; records.concat().len()]; + let mut next = src.iter().copied(); + lanes(&t, widths, per, blocks, |_| next.next(), &mut got).unwrap(); + assert_eq!(got, records.concat(), "{widths:?} x{per}, {blocks} blocks"); + } + } + } + + /// Decode throughput on synthetic streams (no game data): + /// `cargo test --release -p leonida-formats bcpack_throughput -- --ignored --nocapture`. + #[test] + #[ignore = "benchmark"] + fn bcpack_throughput() { + let t = Tables::parse(&tables()).unwrap(); + let cases: [(u8, &[u8], usize, usize); 3] = [ + (1, &[7, 7, 4, 5, 4, 4, 5, 4, 7, 7, 7, 7], 1, 8), + (4, &BC4_LANES, 1, 8), + (7, &[3, 3, 7, 7, 7, 7, 7, 6, 6, 4, 5, 7, 7, 7, 7, 4], 2, 16), + ]; + for (bc, widths, per, block) in cases { + // One fragment per lane holds at most 65792 bytes. + let blocks = 1 << 14; + let records = random_records(widths, per, blocks, bc == 7); + let src = stream(&t, widths, per, &records); + let mut dst = vec![0u8; blocks * block]; + decode(bc, &src, &mut dst, &t).unwrap(); + let runs = 40; + let started = std::time::Instant::now(); + for _ in 0..runs { + decode(bc, std::hint::black_box(&src), &mut dst, &t).unwrap(); + } + let secs = started.elapsed().as_secs_f64() / f64::from(runs); + println!( + "BC{bc}: {blocks} blocks, {:.1} MB out/s, {:.1} ns/block", + (blocks * block) as f64 / secs / 1e6, + secs * 1e9 / blocks as f64 + ); + } + } + + /// Compares with reference outputs made outside the repository: + /// `LEONIDA_BCPACK_TABLES` (the table file) and `LEONIDA_BCPACK_CASES`, a + /// directory of `.bc` packed chunks with `.out` beside them. + #[test] + #[ignore = "needs the format tables and reference chunks"] + fn reference_chunks() { + let tables = std::env::var_os("LEONIDA_BCPACK_TABLES").expect("LEONIDA_BCPACK_TABLES"); + let cases = std::env::var_os("LEONIDA_BCPACK_CASES").expect("LEONIDA_BCPACK_CASES"); + let t = Tables::parse(&std::fs::read(tables).unwrap()).unwrap(); + let mut n = 0; + for entry in std::fs::read_dir(cases).unwrap() { + let path = entry.unwrap().path(); + let Some(bc) = path + .extension() + .and_then(|e| e.to_str()?.strip_prefix("bc")?.parse().ok()) + else { + continue; + }; + let want = std::fs::read(path.with_extension("out")).unwrap(); + let mut got = vec![0u8; want.len()]; + decode(bc, &std::fs::read(&path).unwrap(), &mut got, &t).unwrap(); + assert!(got == want, "{}", path.display()); + n += 1; + } + assert!(n > 0); + } + + /// A dictionary entry stands in for a block the decoder made: a set with + /// 0 index bits holds no indices, and pixel 0 is the anchor (top bit clear). + #[test] + fn bc7_dictionary_indices_line_up() { + let t = Tables::builtin().unwrap(); + for (k, (_, ix)) in t.bc7.iter().enumerate() { + let anchor = 0..1 << (ix.bits[0] - 1); + let ok = (ix.bits[1] != 0 || ix.ix[1] == [0; 16]) && anchor.contains(&ix.ix[0][0]); + assert!(ok, "entry {k}: {:?}", ix.ix); + } + } +} diff --git a/crates/leonida-formats/src/lib.rs b/crates/leonida-formats/src/lib.rs new file mode 100644 index 000000000..f3641779f --- /dev/null +++ b/crates/leonida-formats/src/lib.rs @@ -0,0 +1,10 @@ +//! Platform-level data formats, shared by every Xbox Series title. +//! +//! Each module is pure (bytes in, bytes out, no I/O): [`texture`] (the +//! GPU's tiled texture layouts and copies to and from linear rows). Planned: +//! BCPack textures, audio codecs (XMA2, Opus), and the zlib streams used by +//! hardware decompression. + +pub mod bcpack; +pub mod texture; +pub mod xma; diff --git a/crates/leonida-formats/src/texture.rs b/crates/leonida-formats/src/texture.rs new file mode 100644 index 000000000..fa719c939 --- /dev/null +++ b/crates/leonida-formats/src/texture.rs @@ -0,0 +1,1179 @@ +//! Texture layouts of the console GPU (RDNA2, GFX10.3): a texture's size and +//! alignment, where each mip and array slice starts, the address of each +//! element, and copies between tiled memory and linear rows. +//! +//! Units: an element is a texel, or a 4x4 block of a block-compressed +//! format. Mips of one array slice (or one depth slab of a thick 3D texture) +//! are stored together, smallest first: the mip tail (the small mips sharing +//! one block) at offset 0, mip 0 last. +//! +//! The algorithm follows AMD's address library (addrlib), as shipped in Mesa +//! under `src/amd/addrlib`: block dimensions, mip placement and mip tails +//! from `gfx10addrlib.cpp` and `addrlib2.cpp` +//! (`ComputeSurfaceInfoMacroTiled`, `ComputeThinBlockDimension`, +//! `GetMipTailDim`, `GetMaxNumMipsInTail`, `HwlComputeSurfaceInfoLinear`, +//! `ComputeSurfaceAddrFromCoordMacroTiled`), and the 256-byte micro tile +//! patterns in `MICRO` from `gfx10SwizzlePattern.h` (the RB+ tables, as on +//! RDNA2). addrlib carries this notice: +//! +//! Copyright (C) 2007-2026 Advanced Micro Devices, Inc. All rights reserved. +//! SPDX-License-Identifier: MIT +//! +//! Permission is hereby granted, free of charge, to any person obtaining a +//! copy of this software and associated documentation files (the +//! "Software"), to deal in the Software without restriction, including +//! without limitation the rights to use, copy, modify, merge, publish, +//! distribute, sublicense, and/or sell copies of the Software, and to permit +//! persons to whom the Software is furnished to do so, subject to the +//! following conditions: the above copyright notice and this permission +//! notice shall be included in all copies or substantial portions of the +//! Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +//! EXPRESS OR IMPLIED. + +/// A swizzle mode, by its hardware number (addrlib's `ADDR_SW_*` order). +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub struct Swizzle(pub u32); + +impl Swizzle { + pub const LINEAR: Swizzle = Swizzle(0); + pub const SW_256B_S: Swizzle = Swizzle(1); + pub const SW_256B_D: Swizzle = Swizzle(2); + pub const SW_4KB_S: Swizzle = Swizzle(5); + pub const SW_4KB_D: Swizzle = Swizzle(6); + pub const SW_64KB_S: Swizzle = Swizzle(9); + pub const SW_64KB_D: Swizzle = Swizzle(10); + pub const SW_64KB_S_T: Swizzle = Swizzle(17); + pub const SW_64KB_D_T: Swizzle = Swizzle(18); + pub const SW_4KB_S_X: Swizzle = Swizzle(21); + pub const SW_4KB_D_X: Swizzle = Swizzle(22); + pub const SW_4KB_R_X: Swizzle = Swizzle(23); + pub const SW_64KB_Z_X: Swizzle = Swizzle(24); + pub const SW_64KB_S_X: Swizzle = Swizzle(25); + pub const SW_64KB_D_X: Swizzle = Swizzle(26); + pub const SW_64KB_R_X: Swizzle = Swizzle(27); + + /// log2 of the block size in bytes (0 for linear); `None` for modes + /// GFX10 does not have. + pub fn block_log2(self) -> Option { + Some(match self.0 { + 0 => 0, + 1 | 2 => 8, + 5 | 6 | 21..=23 => 12, + 9 | 10 | 17 | 18 | 24..=27 => 16, + _ => return None, + }) + } + + fn standard(self) -> bool { + matches!(self.0, 1 | 5 | 9 | 17 | 21 | 25) + } + + fn display(self) -> bool { + matches!(self.0, 2 | 6 | 10 | 18 | 22 | 26) + } + + fn z_order(self) -> bool { + self.0 == 24 + } + + /// Pipe and bank XOR modes (`_T`, `_X`): their addresses depend on the + /// GPU's pipe configuration. + pub fn xor(self) -> bool { + self.0 >= 16 + } +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Dimension { + Tex1d, + Tex2d, + Tex3d, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Error { + /// The description makes no texture (zero size, bad element size, a + /// mode this dimension cannot use, too many mips). + Invalid, + /// A valid layout whose addressing is not implemented here. + Unsupported, + /// A buffer is smaller than the layout or the rows need. + TooSmall, +} + +/// One plane of a texture. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct Desc { + pub dimension: Dimension, + /// In texels. + pub width: u32, + pub height: u32, + /// Depth of a 3D texture, else the array size. + pub depth: u32, + pub mips: u32, + /// 1, 2, 4, 8 or 16. + pub element_bytes: u32, + /// Texels per element side: 1, or 4 for block compression. + pub block: u32, + pub samples: u32, + pub swizzle: Swizzle, +} + +/// Elements along one side of mip `mip`, as data and copies see it: texels +/// halve rounding down (to at least 1), then round up to whole elements. +fn dim(texels: u32, mip: u32, block: u32) -> u32 { + (texels >> mip).max(1).div_ceil(block) +} + +/// Elements along one side of mip `mip` for placement (padding, tail, +/// offsets): addrlib halves mip 0's elements rounding up, which can be one +/// more than [`dim`] for odd sizes. +fn padded_dim(texels: u32, mip: u32, block: u32) -> u32 { + texels.max(1).div_ceil(block).div_ceil(1 << mip) +} + +/// Where one mip lives inside a slice. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct Mip { + /// Size in elements (depth 1 unless the texture is 3D). + pub width: u32, + pub height: u32, + pub depth: u32, + /// Padded size in elements: whole blocks, or the tail's share of one. + pub pitch: u32, + pub rows: u32, + pub depth_pitch: u32, + /// Byte offset of its first block in the slice (0 in the tail). + pub offset: u64, + /// In the mip tail: byte offset inside the tail block and the element + /// position the mip starts at. + pub tail: Option, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct Tail { + pub offset: u32, + pub x: u32, + pub y: u32, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Layout { + pub desc: Desc, + /// Block dimensions in elements (linear: the pitch alignment, 1, 1). + pub block: [u32; 3], + /// 3D blocks span `block[2]` depth slices (GFX10 3D `S` and `D` modes). + pub thick: bool, + /// Array slices, depth slabs of `block[2]` slices (thick), or depth + /// slices (thin and linear 3D). + pub slices: u32, + /// Bytes of one slice: its whole mip chain. + pub slice_size: u64, + pub size: u64, + pub alignment: u64, + /// The first mip in the tail; `mips.len()` without one. + pub first_tail_mip: u32, + pub mips: Vec, + /// Byte offsets inside a block of each element coordinate bit, per + /// axis; empty for linear and unsupported modes. + pattern: [Vec; 3], +} + +/// Micro tile (256 bytes) patterns by log2 of the element size: for each +/// address bit, the element coordinate bit it takes (`x0`, `y1`, `z0`...), +/// `--` for the bits inside an element. Thin `S`, thin `D`, thick `S` +/// (also the `D` 3D modes). From addrlib's `GFX10_SW_256_S_RBPLUS`, +/// `GFX10_SW_256_D_RBPLUS` and `GFX10_SW_4K_S3_RBPLUS` patterns; the larger +/// blocks add bits Y, X (thin) or Y, X, Z (thick) in turn. +const MICRO: [[&[u8; 16]; 5]; 3] = [ + [ + b"x0x1x2x3y0y1y2y3", + b"--x0x1x2y0y1y2x3", + b"----x0x1y0y1y2x2", + b"------x0y0y1x1x2", + b"--------y0y1x0x1", + ], + [ + b"x0x1x2y1y0y2x3y3", + b"--x0x1x2y0y1y2x3", + b"----x0x1y0y1x2y2", + b"------x0y0x1x2y1", + b"--------x0y0x1y1", + ], + [ + b"x0x1z0y0z1y1x2z2", + b"--x0z0y0z1y1x1z2", + b"----x0y0z0y1x1z1", + b"------x0z0y0x1z1", + b"--------z0y0x0z1", + ], +]; + +/// For each axis, the address bit each coordinate bit lands on. +fn pattern(kind: usize, element_log2: u32, block_log2: u32) -> [Vec; 3] { + let mut axes: [Vec; 3] = Default::default(); + let micro = MICRO[kind][element_log2 as usize]; + for bit in 0..8u32 { + let (axis, index) = (micro[2 * bit as usize], micro[2 * bit as usize + 1]); + let axis = match axis { + b'x' => 0, + b'y' => 1, + b'z' => 2, + _ => continue, + }; + let index = usize::from(index - b'0'); + let to = &mut axes[axis]; + if to.len() <= index { + to.resize(index + 1, 0); + } + to[index] = bit; + } + let order: &[usize] = if kind == 2 { &[1, 0, 2] } else { &[1, 0] }; + for (bit, axis) in (8..block_log2).zip(order.iter().cycle()) { + axes[*axis].push(bit); + } + axes +} + +/// Byte offsets inside a block for coordinates 0..2^bits of one axis. +fn spread(bits: &[u32]) -> Vec { + (0..1u32 << bits.len()) + .map(|c| { + bits.iter() + .enumerate() + .map(|(i, &to)| ((c >> i) & 1) << to) + .sum() + }) + .collect() +} + +const MAX_MIPS: u32 = 16; + +/// The largest width, height and depth (or array size) accepted, in texels. +/// GFX10's image descriptors hold at most 16384 texels per side, so no +/// texture the GPU can use is refused. The bound also keeps every size +/// computed below within `u64` (and its `u32` steps), which unchecked +/// values from a title would otherwise overflow. +const MAX_EXTENT: u32 = 1 << 14; + +/// 256-byte micro tile dimensions by log2 element size, 2D and 3D. +const BLOCK_256_2D: [[u32; 2]; 5] = [[16, 16], [16, 8], [8, 8], [8, 4], [4, 4]]; +const BLOCK_256_3D: [[u32; 3]; 5] = [[8, 4, 8], [4, 4, 8], [4, 4, 4], [4, 2, 4], [2, 2, 4]]; +const BLOCK_1K_3D: [[u32; 3]; 5] = [[16, 8, 8], [8, 8, 8], [8, 8, 4], [8, 4, 4], [4, 4, 4]]; + +impl Layout { + pub fn new(desc: &Desc) -> Result { + let d = *desc; + let block_log2 = d.swizzle.block_log2().ok_or(Error::Invalid)?; + let valid = (1..=MAX_EXTENT).contains(&d.width) + && (1..=MAX_EXTENT).contains(&d.height) + && (1..=MAX_EXTENT).contains(&d.depth) + && (1..=MAX_MIPS).contains(&d.mips) + && d.element_bytes.is_power_of_two() + && d.element_bytes <= 16 + && matches!(d.block, 1 | 4) + && d.samples.is_power_of_two() + && d.samples <= 8 + && (d.samples == 1 || (d.dimension == Dimension::Tex2d && d.mips == 1)) + && (d.dimension != Dimension::Tex1d || d.height == 1) + && (d.dimension != Dimension::Tex3d + || matches!(d.swizzle.0, 0 | 5 | 9 | 17 | 21 | 24..=27)); + if !valid { + return Err(Error::Invalid); + } + if block_log2 == 0 { + Ok(Layout::linear(d)) + } else { + Ok(Layout::tiled(d, block_log2)) + } + } + + /// `HwlComputeSurfaceInfoLinear`: rows aligned to 256 bytes, mips packed + /// smallest first, a 3D texture's depth slices each hold the chain. + fn linear(d: Desc) -> Layout { + let bpe = u64::from(d.element_bytes); + let align = 256 / d.element_bytes; + let three_d = d.dimension == Dimension::Tex3d; + let mut mips = vec![]; + let mut offset = 0; + for i in (0..d.mips).rev() { + let h = padded_dim(d.height, i, d.block); + let pitch = padded_dim(d.width, i, d.block).next_multiple_of(align); + mips.push(Mip { + width: dim(d.width, i, d.block), + height: dim(d.height, i, d.block), + depth: if three_d { dim(d.depth, i, 1) } else { 1 }, + pitch, + rows: h, + depth_pitch: if three_d { d.depth } else { 1 }, + offset, + tail: None, + }); + offset += u64::from(pitch) * u64::from(h) * bpe; + } + mips.reverse(); + Layout { + desc: d, + block: [align, 1, 1], + thick: false, + slices: d.depth, + slice_size: offset, + size: offset * u64::from(d.depth), + alignment: 256, + first_tail_mip: d.mips, + mips, + pattern: Default::default(), + } + } + + fn tiled(d: Desc, block_log2: u32) -> Layout { + let element_log2 = d.element_bytes.trailing_zeros(); + let bpe = u64::from(d.element_bytes); + let block_bytes = 1u64 << block_log2; + let thick = d.dimension == Dimension::Tex3d && (d.swizzle.standard() || d.swizzle.display()); + let block = if thick { + // ComputeThickBlockDimension + let amp = (block_log2 - 10) / 3; + let rest = (block_log2 - 10) % 3; + let b = BLOCK_1K_3D[element_log2 as usize]; + [b[0] << amp, b[1] << (amp + rest / 2), b[2] << (amp + u32::from(rest != 0))] + } else { + // ComputeThinBlockDimension + let samples_log2 = d.samples.trailing_zeros(); + let elements_log2 = block_log2 - element_log2 - samples_log2; + let wide = samples_log2 & 1 == 0 || block_log2 & 1 != 0; + let w = (elements_log2 + u32::from(wide)) / 2; + [1 << w, 1 << (elements_log2 - w), 1] + }; + let slices = d.depth.next_multiple_of(block[2]); + let three_d = d.dimension == Dimension::Tex3d; + // Mip depths placed by a thick layout (thin ones store depth as + // slices). + let mip_depth = |i: u32| if thick { padded_dim(d.depth, i, 1) } else { 1 }; + let depth_of = |i: u32| if three_d { dim(d.depth, i, 1) } else { 1 }; + let (width, height) = (|i| dim(d.width, i, d.block), |i| dim(d.height, i, d.block)); + let padded = |i| (padded_dim(d.width, i, d.block), padded_dim(d.height, i, d.block)); + let mut mips = Vec::with_capacity(d.mips as usize); + let mut first_tail_mip = d.mips; + let mut slice_size = 0u64; + if d.mips == 1 { + mips.push(Mip { + width: width(0), + height: height(0), + depth: depth_of(0), + pitch: width(0).next_multiple_of(block[0]), + rows: height(0).next_multiple_of(block[1]), + depth_pitch: if three_d { slices } else { 1 }, + offset: 0, + tail: None, + }); + slice_size = u64::from(mips[0].pitch) + * u64::from(mips[0].rows) + * bpe + * u64::from(d.samples); + } else { + // GetMipTailDim: the largest mip the tail takes. + let mut tail_max = block; + if thick { + match block_log2 % 3 { + 0 => tail_max[1] >>= 1, + 1 => tail_max[0] >>= 1, + _ => tail_max[2] >>= 1, + } + } else { + tail_max[0] >>= 1; + } + // GetMaxNumMipsInTail; 256-byte blocks have no tail + // (`ComputeSurfaceInfoMicroTiled`). + let effective = if thick { + block_log2 - (block_log2 - 8) / 3 + } else { + block_log2 + }; + let max_in_tail = match effective { + 8 => 0, + 9..=11 => 1 + (1 << (effective - 9)), + _ => effective - 4, + }; + // dsMipmapHtileFix: 8- and 16-bit depth enter the tail as 32-bit. + let mut fixed = tail_max; + if d.swizzle.z_order() && element_log2 <= 1 { + let b = BLOCK_256_2D[element_log2 as usize]; + fixed[0] /= b[0] / BLOCK_256_2D[2][0]; + fixed[1] /= b[1] / BLOCK_256_2D[2][1]; + } + let mut sizes = vec![]; + for i in 0..d.mips { + let (w, h) = padded(i); + if w <= fixed[0] && h <= fixed[1] && d.mips - i <= max_in_tail { + first_tail_mip = i; + slice_size += block_bytes / u64::from(block[2]); + break; + } + let pitch = w.next_multiple_of(block[0]); + let rows = h.next_multiple_of(block[1]); + let depth = mip_depth(i).next_multiple_of(block[2]); + let one = u64::from(pitch) * u64::from(rows) * bpe; + slice_size += one; + sizes.push(one * u64::from(block[2])); + mips.push(Mip { + width: width(i), + height: height(i), + depth: depth_of(i), + pitch, + rows, + depth_pitch: if three_d { depth } else { 1 }, + offset: 0, + tail: None, + }); + } + // Standard mips from the smallest up, after the tail block. + let mut offset = if first_tail_mip < d.mips { + block_bytes + } else { + 0 + }; + for i in (0..first_tail_mip as usize).rev() { + mips[i].offset = offset; + offset += sizes[i]; + } + let micro = if thick { + let b = BLOCK_256_3D[element_log2 as usize]; + [b[0], b[1]] + } else { + BLOCK_256_2D[element_log2 as usize] + }; + let (mut pitch, mut rows) = (tail_max[0], tail_max[1]); + for i in first_tail_mip..d.mips { + let m = max_in_tail - 1 - (i - first_tail_mip); + let offset = if m > 6 { 16 << m } else { m << 8 }; + // Address bits 8.. of the offset, odd ones x, even ones y. + let bits = |from: u32| (0..6).map(|b| ((offset >> (from + 2 * b)) & 1) << b).sum(); + let (mut x, mut y): (u32, u32) = (bits(9), bits(8)); + if block_log2 & 1 != 0 { + std::mem::swap(&mut x, &mut y); + if element_log2 & 1 != 0 { + y = (y << 1) | (x & 1); + x >>= 1; + } + } + mips.push(Mip { + width: width(i), + height: height(i), + depth: depth_of(i), + pitch, + rows, + depth_pitch: if thick { + mip_depth(i).next_multiple_of(BLOCK_256_3D[element_log2 as usize][2]) + } else { + 1 + }, + offset: 0, + tail: Some(Tail { + offset, + x: x * micro[0], + y: y * micro[1], + }), + }); + pitch = (pitch >> 1).max(micro[0]); + rows = (rows >> 1).max(micro[1]); + } + } + // Thick layouts store each depth slab's chain together. + let slab = if thick { u64::from(block[2]) } else { 1 }; + let slice_size = slice_size * slab; + let slices = slices / block[2]; + let addressable = !d.swizzle.xor() && d.samples == 1; + let pattern = if addressable { + let kind = if thick { + 2 + } else { + usize::from(d.swizzle.display()) + }; + pattern(kind, element_log2, block_log2).map(|bits| spread(&bits)) + } else { + Default::default() + }; + Layout { + desc: d, + block, + thick, + slices, + slice_size, + size: slice_size * u64::from(slices), + alignment: block_bytes, + first_tail_mip, + mips, + pattern, + } + } + + /// Whether [`Layout::offset`] and the copies work for this layout: + /// linear and the modes without pipe or bank XOR, single-sampled. + /// + /// shortcut: no addressing for the XOR modes (`_X`, `_T`) and MSAA; + /// they need the GPU's pipe and bank configuration (Series X and S + /// differ). Titles use them for render targets and depth, which the + /// host renders; add them when a title copies into or out of one. + pub fn addressable(&self) -> bool { + self.desc.swizzle == Swizzle::LINEAR || !self.pattern[0].is_empty() + } + + /// The slice and the depth inside it for `z` (an array slice or a 3D + /// depth slice). + fn split(&self, z: u32) -> (u32, u32) { + if self.thick { + (z / self.block[2], z % self.block[2]) + } else { + (z, 0) + } + } + + /// Byte offset of element (`x`, `y`) of mip `mip` in array slice or + /// depth slice `z`. Coordinates must lie inside the mip. + pub fn offset(&self, mip: u32, x: u32, y: u32, z: u32) -> Result { + let m = self.mips.get(mip as usize).ok_or(Error::Invalid)?; + let depth = if self.desc.dimension == Dimension::Tex3d { + m.depth + } else { + self.slices + }; + let inside = x < m.width && y < m.height && z < depth; + if !inside || !self.addressable() { + return Err(if inside { + Error::Unsupported + } else { + Error::Invalid + }); + } + let (slice, z) = self.split(z); + let base = u64::from(slice) * self.slice_size + m.offset; + if self.desc.swizzle == Swizzle::LINEAR { + let row = u64::from(y) * u64::from(m.pitch) + u64::from(x); + return Ok(base + row * u64::from(self.desc.element_bytes)); + } + Ok(base + self.row(m, y, z) + self.column(m, x)) + } + + /// The part of an address that depends on the row (and depth in a + /// thick block). + fn row(&self, m: &Mip, y: u32, z: u32) -> u64 { + let [bw, bh, _] = self.block; + let log2 = self.alignment.trailing_zeros(); + // In the tail the pattern of the shifted position gives the mip's + // offset inside the tail block. + let y = y + m.tail.map_or(0, |t| t.y); + let blocks = u64::from(y / bh) * u64::from(m.pitch / bw); + (blocks << log2) + u64::from(self.pattern[1][(y % bh) as usize] | self.pattern[2][z as usize]) + } + + /// The part of an address that depends on the column. + fn column(&self, m: &Mip, x: u32) -> u64 { + let bw = self.block[0]; + let x = x + m.tail.map_or(0, |t| t.x); + (u64::from(x / bw) << self.alignment.trailing_zeros()) + + u64::from(self.pattern[0][(x % bw) as usize]) + } + + /// Depth slices a subresource of mip `mip` covers: the mip's depth for + /// 3D textures, else 1 (one array slice). + pub fn subresource_depth(&self, mip: u32) -> u32 { + self.mips.get(mip as usize).map_or(0, |m| m.depth) + } + + /// Copies one subresource out of tiled memory (the whole texture, + /// [`Layout::size`] bytes) into linear rows: mip `mip` of array slice + /// `slice` (3D: every depth slice of the mip, `slice` 0). Rows are + /// `row_pitch` bytes apart, depth slices `depth_pitch`. + pub fn detile( + &self, + tiled: &[u8], + mip: u32, + slice: u32, + linear: &mut [u8], + row_pitch: usize, + depth_pitch: usize, + ) -> Result<(), Error> { + self.walk::(tiled, linear, mip, slice, row_pitch, depth_pitch) + } + + /// The reverse of [`Layout::detile`]: linear rows into tiled memory. + pub fn tile( + &self, + tiled: &mut [u8], + mip: u32, + slice: u32, + linear: &[u8], + row_pitch: usize, + depth_pitch: usize, + ) -> Result<(), Error> { + self.walk::(linear, tiled, mip, slice, row_pitch, depth_pitch) + } + + /// Copies contiguous runs in one direction between the two layouts. + #[allow(clippy::too_many_arguments)] + fn walk( + &self, + src: &[u8], + dst: &mut [u8], + mip: u32, + slice: u32, + row_pitch: usize, + depth_pitch: usize, + ) -> Result<(), Error> { + let m = self.mips.get(mip as usize).ok_or(Error::Invalid)?; + let depth = m.depth; + let first = if self.desc.dimension == Dimension::Tex3d { + if slice != 0 { + return Err(Error::Invalid); + } + 0 + } else { + slice + }; + if first >= self.slices { + return Err(Error::Invalid); + } + if !self.addressable() { + return Err(Error::Unsupported); + } + let n = self.desc.element_bytes as usize; + let bytes = m.width as usize * n; + let need = (depth as usize - 1) + .checked_mul(depth_pitch) + .zip((m.height as usize - 1).checked_mul(row_pitch)) + .and_then(|(depth_offset, row_offset)| depth_offset.checked_add(row_offset)) + .and_then(|offset| offset.checked_add(bytes)) + .ok_or(Error::TooSmall)?; + let (tiled_len, linear_len) = if DETILE { + (src.len(), dst.len()) + } else { + (dst.len(), src.len()) + }; + if tiled_len < self.size as usize || linear_len < need || row_pitch < bytes { + return Err(Error::TooSmall); + } + let linear = self.desc.swizzle == Swizzle::LINEAR; + // The row and depth contribute one common base to every column, so + // the same contiguous runs repeat on every row, including mip tails. + let mut runs = Vec::new(); + if !linear { + let mut first_linear = 0; + let mut first_tiled = self.column(m, 0) as usize; + for x in 1..m.width { + let offset = self.column(m, x) as usize; + let at = x as usize * n; + if offset != first_tiled + (at - first_linear) { + runs.push((first_tiled, first_linear, at - first_linear)); + first_tiled = offset; + first_linear = at; + } + } + runs.push((first_tiled, first_linear, bytes - first_linear)); + } + // A mip can end partway through the last run. Check the other runs + // once so each row can copy them as fixed-size chunks. + let (body, last) = runs.split_at(runs.len().saturating_sub(1)); + let chunk_size = body.first().map(|run| run.2).filter(|&size| { + body.iter() + .all(|&(offset, _, len)| len == size && offset.is_multiple_of(size)) + }); + for z in 0..depth { + let (s, inner) = self.split(first + z); + let base = u64::from(s) * self.slice_size + m.offset; + for y in 0..m.height { + let linear_row = z as usize * depth_pitch + y as usize * row_pitch; + if linear { + let tiled_row = base + u64::from(y) * u64::from(m.pitch) * n as u64; + copy_run::(src, dst, tiled_row as usize, linear_row, bytes); + } else { + let tiled_row = (base + self.row(m, y, inner)) as usize; + match chunk_size { + Some(8) if tiled_row.is_multiple_of(8) => { + copy_runs::<8, DETILE>(src, dst, body, tiled_row, linear_row) + } + Some(16) if tiled_row.is_multiple_of(16) => { + copy_runs::<16, DETILE>(src, dst, body, tiled_row, linear_row) + } + Some(32) if tiled_row.is_multiple_of(32) => { + copy_runs::<32, DETILE>(src, dst, body, tiled_row, linear_row) + } + _ => copy_runs::<0, DETILE>(src, dst, body, tiled_row, linear_row), + } + copy_runs::<0, DETILE>(src, dst, last, tiled_row, linear_row); + } + } + } + Ok(()) + } +} + +fn copy_run( + src: &[u8], + dst: &mut [u8], + tiled: usize, + linear: usize, + len: usize, +) { + let (from, to) = if DETILE { + (tiled, linear) + } else { + (linear, tiled) + }; + dst[to..][..len].copy_from_slice(&src[from..][..len]); +} + +/// A row of equal runs is contiguous in linear memory. Treat it as a +/// slice of arrays so only the tiled chunk needs a bounds check per copy. +/// Use the byte ranges for irregular runs and the last run of each row. +fn copy_runs( + src: &[u8], + dst: &mut [u8], + runs: &[(usize, usize, usize)], + tiled_row: usize, + linear_row: usize, +) { + if N == 0 { + for &(tiled, linear, len) in runs { + copy_run::(src, dst, tiled_row + tiled, linear_row + linear, len); + } + } else if DETILE { + let tiled = src.as_chunks::().0; + let linear = dst[linear_row..][..runs.len() * N].as_chunks_mut::().0; + for (out, &(offset, ..)) in linear.iter_mut().zip(runs) { + *out = tiled[(tiled_row + offset) / N]; + } + } else { + let tiled = dst.as_chunks_mut::().0; + let linear = src[linear_row..][..runs.len() * N].as_chunks::().0; + for (input, &(offset, ..)) in linear.iter().zip(runs) { + tiled[(tiled_row + offset) / N] = *input; + } + } +} + +/// What a DXGI format stores per element: bytes, texels per element side +/// (4 for block compression), and whether its stencil is a second plane +/// (the GPU keeps depth and stencil apart). +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct Format { + pub bytes: u32, + pub block: u32, + pub stencil: bool, +} + +/// By DXGI format number. `None` for 96-bit, 1-bit, packed 4:2:2 and video +/// formats. +/// +/// shortcut: those formats have no layout here; add them when a title uses +/// one. +pub fn format(dxgi: u32) -> Option { + let (bytes, block, stencil) = match dxgi { + 1..=4 => (16, 1, false), + 9..=18 => (8, 1, false), + 19..=22 | 44..=47 => (4, 1, true), + 23..=43 | 67 | 87..=93 | 116 | 117 => (4, 1, false), + 48..=59 | 85 | 86 | 115 => (2, 1, false), + 118..=120 => (2, 1, true), + 60..=65 => (1, 1, false), + 70..=72 | 79..=81 => (8, 4, false), + 73..=78 | 82..=84 | 94..=99 => (16, 4, false), + _ => return None, + }; + Some(Format { + bytes, + block, + stencil, + }) +} + +/// A texture as the console allocates it: a D3D12-style description with +/// a swizzle mode. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct TextureDesc { + pub dimension: Dimension, + /// In texels. + pub width: u32, + pub height: u32, + /// Depth of a 3D texture, else the array size. + pub depth_or_array: u32, + /// 0: the full chain. + pub mips: u32, + /// DXGI format number. + pub format: u32, + pub samples: u32, + pub swizzle: Swizzle, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Plane { + /// From the start of the texture. + pub offset: u64, + pub stencil: bool, + pub layout: Layout, +} + +/// Every data plane of a texture (depth, then stencil), placed one after +/// the other. +/// +/// shortcut: no compression metadata planes (HTILE, CMASK, FMASK, DCC); +/// the console adds them to render targets and depth buffers unless the +/// description denies them, so those are smaller here than on the console. +/// The host GPU renders them, so nothing reads that memory; add the planes +/// if a title sizes a pool from console sizes and runs out. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Texture { + pub planes: Vec, + pub size: u64, + pub alignment: u64, +} + +impl Texture { + pub fn new(desc: &TextureDesc) -> Result { + let f = format(desc.format).ok_or(Error::Invalid)?; + let depth3d = if desc.dimension == Dimension::Tex3d { + desc.depth_or_array + } else { + 1 + }; + let mips = match desc.mips { + 0 => 32 - desc.width.max(desc.height).max(depth3d).max(1).leading_zeros(), + n => n, + }; + let plane = |bytes| Desc { + dimension: desc.dimension, + width: desc.width, + height: desc.height, + depth: desc.depth_or_array, + mips, + element_bytes: bytes, + block: f.block, + samples: desc.samples.max(1), + swizzle: desc.swizzle, + }; + let mut planes = vec![Plane { + offset: 0, + stencil: false, + layout: Layout::new(&plane(f.bytes))?, + }]; + if f.stencil { + let layout = Layout::new(&plane(1))?; + let offset = planes[0].layout.size.next_multiple_of(layout.alignment); + planes.push(Plane { + offset, + stencil: true, + layout, + }); + } + let last = &planes[planes.len() - 1]; + let size = last.offset + last.layout.size; + let alignment = planes.iter().map(|p| p.layout.alignment).max().unwrap_or(1); + Ok(Texture { + planes, + size, + alignment, + }) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn desc(w: u32, h: u32, mips: u32, bpe: u32, swizzle: Swizzle) -> Desc { + Desc { + dimension: Dimension::Tex2d, + width: w, + height: h, + depth: 1, + mips, + element_bytes: bpe, + block: 1, + samples: 1, + swizzle, + } + } + + /// Sizes past the hardware's 16384 texels per side are refused instead + /// of overflowing the size arithmetic (found by random-input testing). + #[test] + fn extents_past_the_hardware_limit_are_invalid() { + for swizzle in [Swizzle::LINEAR, Swizzle::SW_64KB_D_X] { + let largest = Layout::new(&desc(MAX_EXTENT, MAX_EXTENT, 15, 16, swizzle)).unwrap(); + assert!(largest.size >= u64::from(MAX_EXTENT) * u64::from(MAX_EXTENT) * 16); + for (w, h) in [ + (MAX_EXTENT + 1, 1), + (1, MAX_EXTENT + 1), + (u32::MAX, u32::MAX), + ] { + let result = Layout::new(&desc(w, h, 1, 16, swizzle)); + assert_eq!(result, Err(Error::Invalid), "{w}x{h}"); + } + let mut deep = desc(1, 1, 1, 16, swizzle); + deep.depth = u32::MAX; + assert_eq!(Layout::new(&deep), Err(Error::Invalid)); + } + } + + #[test] + fn blocks_hold_their_size_in_elements() { + for log2 in [8u32, 12, 16] { + let swizzle = match log2 { + 8 => Swizzle::SW_256B_S, + 12 => Swizzle::SW_4KB_S, + _ => Swizzle::SW_64KB_D, + }; + for e in 0..5 { + let l = Layout::new(&desc(1, 1, 1, 1 << e, swizzle)).unwrap(); + let [w, h, d] = l.block; + assert_eq!(u64::from(w * h * d) << e, 1 << log2, "{log2} {e}"); + // The pattern covers exactly the block's coordinates. + assert_eq!(l.pattern[0].len() as u32, w); + assert_eq!(l.pattern[1].len() as u32, h); + } + } + // 64 KiB, 16-byte elements: 64x64 (a 256x256 BC7 texture). + let l = Layout::new(&desc(64, 64, 1, 16, Swizzle::SW_64KB_D)).unwrap(); + assert_eq!(l.block, [64, 64, 1]); + assert_eq!((l.size, l.alignment), (65536, 65536)); + } + + /// Every element of every mip and slice lands on its own address, inside + /// the texture, and tiling then detiling gives the rows back. + #[test] + fn addresses_are_a_bijection_and_copies_round_trip() { + let cases = [ + desc(64, 64, 7, 16, Swizzle::SW_64KB_D), + desc(100, 60, 7, 4, Swizzle::SW_64KB_D), + desc(250, 175, 8, 8, Swizzle::SW_4KB_S), + desc(33, 17, 6, 1, Swizzle::SW_4KB_D), + desc(40, 9, 3, 2, Swizzle::SW_64KB_S), + desc(30, 20, 5, 4, Swizzle::LINEAR), + desc(83, 31, 6, 1, Swizzle::SW_256B_S), + Desc { + block: 4, + ..desc(109, 71, 6, 16, Swizzle::SW_256B_D) + }, + Desc { + depth: 3, + ..desc(70, 70, 4, 16, Swizzle::SW_4KB_S) + }, + Desc { + dimension: Dimension::Tex3d, + depth: 16, + ..desc(64, 32, 7, 4, Swizzle::SW_4KB_S) + }, + ]; + for d in cases { + let l = Layout::new(&d).unwrap(); + let mut seen = vec![false; l.size as usize]; + let mut tiled = vec![0u8; l.size as usize]; + let n = d.element_bytes as usize; + let slices = if d.dimension == Dimension::Tex3d { 1 } else { d.depth }; + for slice in 0..slices { + for mip in 0..d.mips { + let m = l.mips[mip as usize]; + let active = m.width as usize * n; + let row = active + 13; + let plane = row * m.height as usize + 11; + let linear: Vec = (0..plane * m.depth as usize) + .map(|i| (i * 7 + mip as usize * 13 + slice as usize) as u8) + .collect(); + l.tile(&mut tiled, mip, slice, &linear, row, plane).unwrap(); + let mut back = vec![0xcc; linear.len()]; + l.detile(&tiled, mip, slice, &mut back, row, plane).unwrap(); + for z in 0..m.depth { + let base = z as usize * plane; + for y in 0..m.height { + let start = base + y as usize * row; + assert_eq!(back[start..start + active], linear[start..start + active]); + assert!(back[start + active..start + row].iter().all(|&b| b == 0xcc)); + for x in 0..m.width { + let at = l.offset(mip, x, y, slice + z).unwrap() as usize; + let source = start + x as usize * n; + assert_eq!(tiled[at..at + n], linear[source..source + n]); + assert!(at + n <= seen.len(), "{d:?} mip {mip} outside"); + assert!(at.is_multiple_of(n)); + assert!(!seen[at], "{d:?} mip {mip} ({x},{y},{z}) twice"); + seen[at] = true; + } + } + assert!(back[base + plane - 11..base + plane].iter().all(|&b| b == 0xcc)); + } + } + } + } + } + + #[test] + fn tiled_chunks_match_element_offsets_with_odd_row_pitches() { + for swizzle in [ + Swizzle::SW_256B_S, + Swizzle::SW_256B_D, + Swizzle::SW_4KB_S, + Swizzle::SW_4KB_D, + Swizzle::SW_64KB_S, + Swizzle::SW_64KB_D, + ] { + for n in [1, 2, 4, 8, 16] { + let l = Layout::new(&Desc { + depth: 2, + ..desc(73, 39, 7, n, swizzle) + }) + .unwrap(); + let n = n as usize; + let tiled: Vec<_> = (0..l.size) + .map(|i| (i.wrapping_mul(0x9e37_79b9) >> 24) as u8) + .collect(); + let mut retiled = vec![0xbb; tiled.len()]; + let mut expected_tiled = retiled.clone(); + for slice in 0..l.slices { + for (mip, m) in l.mips.iter().enumerate() { + let mip = mip as u32; + let bytes = m.width as usize * n; + let pitch = bytes + 3; + // Keep padding between rows, with exactly the active + // bytes in the last row. + let len = (m.height as usize - 1) * pitch + bytes; + let mut linear = vec![0xcc; len]; + let mut expected = linear.clone(); + for y in 0..m.height { + for x in 0..m.width { + let src = l.offset(mip, x, y, slice).unwrap() as usize; + let dst = y as usize * pitch + x as usize * n; + expected[dst..][..n].copy_from_slice(&tiled[src..][..n]); + expected_tiled[src..][..n].copy_from_slice(&tiled[src..][..n]); + } + } + l.detile(&tiled, mip, slice, &mut linear, pitch, len) + .unwrap(); + assert_eq!(linear, expected, "{swizzle:?} {n} mip {mip} slice {slice}"); + l.tile(&mut retiled, mip, slice, &expected, pitch, len) + .unwrap(); + } + } + assert_eq!(retiled, expected_tiled, "{swizzle:?} {n}"); + } + } + } + + /// Hand-checked: in a 64 KiB `D` block of 4-byte elements, x bits go to + /// address bits 2, 3, 6, 9, 11, 13, 15 and y bits to 4, 5, 7, 8, 10, 12, + /// 14; a 4 KiB `S` block of 16-byte elements is 16x16 with y first. + #[test] + fn hand_checked_addresses() { + let l = Layout::new(&desc(128, 128, 1, 4, Swizzle::SW_64KB_D)).unwrap(); + assert_eq!(l.offset(0, 1, 0, 0), Ok(1 << 2)); + assert_eq!(l.offset(0, 4, 0, 0), Ok(1 << 6)); + assert_eq!(l.offset(0, 0, 4, 0), Ok(1 << 7)); + assert_eq!(l.offset(0, 0, 8, 0), Ok(1 << 8)); + assert_eq!(l.offset(0, 64, 64, 0), Ok((1 << 15) | (1 << 14))); + let l = Layout::new(&desc(32, 32, 1, 16, Swizzle::SW_4KB_S)).unwrap(); + assert_eq!(l.block, [16, 16, 1]); + assert_eq!(l.offset(0, 0, 1, 0), Ok(1 << 4)); + assert_eq!(l.offset(0, 1, 0, 0), Ok(1 << 6)); + // Blocks row by row: (16, 0) is the second block, (0, 16) the third. + assert_eq!(l.offset(0, 16, 0, 0), Ok(4096)); + assert_eq!(l.offset(0, 0, 16, 0), Ok(8192)); + } + + /// A 256x256 BC7 chain in 64 KiB `D`: one tail block holding mips 1-8, + /// then mip 0; mip 1 sits at x = 32 elements, 32 KiB into the tail. + #[test] + fn mip_tail_comes_first() { + let l = Layout::new(&desc(64, 64, 9, 16, Swizzle::SW_64KB_D)).unwrap(); + assert_eq!(l.first_tail_mip, 1); + assert_eq!(l.size, 2 * 65536); + assert_eq!(l.mips[0].offset, 65536); + assert_eq!( + l.mips[1].tail, + Some(Tail { + offset: 32768, + x: 32, + y: 0 + }) + ); + assert_eq!(l.offset(1, 0, 0, 0), Ok(32768)); + // 4 KiB blocks hold fewer tail mips: 16x16 BC7 mips stay outside. + let l = Layout::new(&desc(64, 64, 9, 16, Swizzle::SW_4KB_S)).unwrap(); + assert_eq!(l.first_tail_mip, 3); + assert_eq!(l.mips[2].offset, 4096); + assert_eq!(l.mips[1].offset, 8192); + assert_eq!(l.mips[0].offset, 8192 + 16384); + } + + #[test] + fn depth_stencil_is_two_planes() { + let t = Texture::new(&TextureDesc { + dimension: Dimension::Tex2d, + width: 1920, + height: 1080, + depth_or_array: 1, + mips: 1, + format: 20, + samples: 1, + swizzle: Swizzle::SW_64KB_Z_X, + }) + .unwrap(); + assert_eq!(t.planes.len(), 2); + // 4-byte depth in 128x128 blocks, 1-byte stencil in 256x256 blocks. + assert_eq!(t.planes[0].layout.size, 1920 * 1152 * 4); + assert_eq!(t.planes[1].offset, t.planes[0].layout.size); + assert_eq!(t.planes[1].layout.size, 2048 * 1280); + assert!(!t.planes[0].layout.addressable()); + } + + #[test] + fn texture_copies_reject_overflowing_pitches() { + let layout = Layout::new(&desc(4, 2, 1, 4, Swizzle::LINEAR)).unwrap(); + let mut tiled = vec![0; layout.size as usize]; + let mut linear = [0; 32]; + assert_eq!( + layout.detile(&tiled, 0, 0, &mut linear, usize::MAX, 0), + Err(Error::TooSmall) + ); + assert_eq!( + layout.tile(&mut tiled, 0, 0, &linear, usize::MAX, 0), + Err(Error::TooSmall) + ); + } + + #[test] + fn volume_copy_rejects_overflowing_depth_pitch() { + let layout = Layout::new(&Desc { + dimension: Dimension::Tex3d, + depth: 3, + ..desc(4, 2, 1, 4, Swizzle::LINEAR) + }) + .unwrap(); + let tiled = vec![0; layout.size as usize]; + let mut linear = [0; 96]; + assert_eq!( + layout.detile(&tiled, 0, 0, &mut linear, 16, usize::MAX), + Err(Error::TooSmall) + ); + } + + #[test] + fn bad_descriptions_and_buffers_are_refused() { + assert_eq!( + Layout::new(&desc(0, 4, 1, 4, Swizzle::SW_4KB_S)), + Err(Error::Invalid) + ); + assert_eq!( + Layout::new(&desc(4, 4, 1, 12, Swizzle::SW_4KB_S)), + Err(Error::Invalid) + ); + assert_eq!( + Layout::new(&desc(4, 4, 1, 4, Swizzle(3))), + Err(Error::Invalid) + ); + let l = Layout::new(&desc(64, 64, 1, 4, Swizzle::SW_4KB_S)).unwrap(); + let mut out = vec![0; 64 * 64 * 4]; + assert_eq!( + l.detile(&[0; 100], 0, 0, &mut out, 256, 0), + Err(Error::TooSmall) + ); + assert_eq!(l.offset(0, 64, 0, 0), Err(Error::Invalid)); + } +} diff --git a/crates/leonida-formats/src/xma.rs b/crates/leonida-formats/src/xma.rs new file mode 100644 index 000000000..33a5c5c85 --- /dev/null +++ b/crates/leonida-formats/src/xma.rs @@ -0,0 +1,1247 @@ +//! XMA2, the console's hardware audio codec: mono or stereo WMA Pro frames of +//! 512 samples per channel, packed into 2048-byte packets. +//! +//! A packet starts with a 32-bit header (MSB first): the number of frames +//! that begin in it (6 bits), the number of bits that finish the previous +//! frame before the first new one (15), metadata (3) and how many packets of +//! other streams follow before this stream's next packet (8). Every frame +//! starts with its length in bits (15) and ends with a "more frames" bit. +//! +//! The frame decoder follows FFmpeg's `wmaprodec.c` (LGPL-2.1-or-later, used +//! under GPL-3.0-or-later) restricted to what XMA needs: at most two +//! channels, four subframe sizes (512 down to 128), no LFE channel. + +mod tables; + +use std::sync::OnceLock; + +use tables::*; + +pub const PACKET_BYTES: usize = 2048; +const PACKET_BITS: usize = PACKET_BYTES * 8; +const HEADER_BITS: usize = 32; +/// Samples per channel in one frame. +pub const FRAME_SAMPLES: usize = 512; +/// Samples per channel in one subframe, the unit of skips and loop ends. +pub const SUBFRAME_SAMPLES: usize = 128; +const LENGTH_BITS: u32 = 15; +/// 512 >> 2: the smallest subframe. +const MIN_SUBFRAME: usize = SUBFRAME_SAMPLES; +const BLOCK_SIZES: usize = 3; +const MAX_BANDS: usize = 29; +const MAX_SUBFRAMES: usize = 32; + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct Error(pub &'static str); + +impl std::fmt::Display for Error { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!(f, "XMA: {}", self.0) + } +} + +impl std::error::Error for Error {} + +// Packets. + +/// A packet's header fields. +#[derive(Debug, Clone, Copy)] +pub struct Packet { + pub frames: u32, + pub first_frame_bit: u32, + pub skip: u32, +} + +pub fn packet(data: &[u8], index: usize) -> Option { + let start = index.checked_mul(PACKET_BYTES)?; + let b = data.get(start..)?.get(..4)?; + let h = u32::from_be_bytes([b[0], b[1], b[2], b[3]]); + Some(Packet { + frames: h >> 26, + first_frame_bit: (h >> 11) & 0x7fff, + skip: h & 0xff, + }) +} + +/// One frame's bits gathered out of its packets. +#[derive(Debug, Clone)] +pub struct Frame { + /// The frame from its length field on, MSB first. + pub data: Vec, + pub bits: usize, + /// Bit offset in the buffer where it starts, and where the next frame + /// starts (`None` when the buffer has no further frame). + pub start: usize, + pub next: Option, +} + +/// Bit positions in a buffer of packets, skipping each packet's header and +/// the packets of other streams. +struct Cursor<'a> { + data: &'a [u8], + pos: usize, +} + +impl Cursor<'_> { + fn bit(&mut self) -> Option { + if self.pos.is_multiple_of(PACKET_BITS) { + // Leaving a packet: jump over the other streams' packets. + let previous = self.pos / PACKET_BITS; + if previous > 0 { + let skip = packet(self.data, previous - 1)?.skip as usize; + self.pos = (previous + skip) * PACKET_BITS; + } + self.pos += HEADER_BITS; + } + let byte = *self.data.get(self.pos / 8)?; + let bit = (byte >> (7 - self.pos % 8)) & 1; + self.pos += 1; + Some(bit as u32) + } + + fn bits(&mut self, n: u32) -> Option { + (0..n).try_fold(0, |v, _| Some(v << 1 | self.bit()?)) + } +} + +/// Reads the frame starting at bit `start` (a frame start inside a packet's +/// payload) of `data`, a buffer of whole packets of one stream. +pub fn read_frame(data: &[u8], start: usize) -> Option { + let mut cursor = Cursor { data, pos: start }; + let bits = cursor.bits(LENGTH_BITS)? as usize; + if bits <= LENGTH_BITS as usize || bits == 0x7fff { + return None; + } + let mut out = vec![0u8; bits.div_ceil(8)]; + let mut cursor = Cursor { data, pos: start }; + for i in 0..bits { + out[i / 8] |= (cursor.bit()? as u8) << (7 - i % 8); + } + let end = cursor.pos; + let next = next_frame(data, start, end); + Some(Frame { + data: out, + bits, + start, + next, + }) +} + +/// Where the frame after the one at `start`..`end` begins: right after it, +/// unless it was the last frame to begin in its packet and the rest of that +/// packet is padding. +fn next_frame(data: &[u8], start: usize, end: usize) -> Option { + let index = start / PACKET_BITS; + let header = packet(data, index)?; + let mut at = index * PACKET_BITS + HEADER_BITS + header.first_frame_bit as usize; + let mut number = 0; + while at < start { + let mut cursor = Cursor { data, pos: at }; + let bits = cursor.bits(LENGTH_BITS)? as usize; + // The same rule as `read_frame`: a length that does not cover its own + // field is not a frame. A zero length would never move `at`, so a + // damaged packet would loop here for good. + if bits <= LENGTH_BITS as usize { + return None; + } + at += bits; + number += 1; + } + let last = number + 1 >= header.frames; + let mut end = end; + if end.is_multiple_of(PACKET_BITS) || (last && end / PACKET_BITS == index) { + // The next frame begins in the next packet of this stream. + let next = (end - 1) / PACKET_BITS + 1 + packet(data, (end - 1) / PACKET_BITS)?.skip as usize; + let header = packet(data, next)?; + end = next * PACKET_BITS + HEADER_BITS + header.first_frame_bit as usize; + } + (end / 8 < data.len()).then_some(end) +} + +// Bitstream reading inside a frame. + +struct Bits<'a> { + data: &'a [u8], + pos: usize, + end: usize, +} + +impl Bits<'_> { + fn peek32(&self) -> u32 { + let mut v = 0u64; + let byte = self.pos / 8; + for i in 0..5 { + v = v << 8 | *self.data.get(byte + i).unwrap_or(&0) as u64; + } + (v << (24 + self.pos % 8) >> 32) as u32 + } + + fn read(&mut self, n: u32) -> u32 { + if n == 0 { + return 0; + } + let v = self.peek32() >> (32 - n); + self.pos += n as usize; + v + } + + fn bit(&mut self) -> bool { + self.read(1) != 0 + } + + fn signed(&mut self, n: u32) -> i32 { + ((self.read(n) << (32 - n)) as i32) >> (32 - n) + } + + fn consumed(&self) -> usize { + self.pos + } + + fn overread(&self) -> bool { + self.pos > self.end + } +} + +/// A prefix code built like FFmpeg's `ff_vlc_init_from_lengths`: codes are +/// handed out in table order, each the next free one of its length. +struct Vlc { + /// Left-aligned code, length, symbol; sorted by code. + codes: Vec<(u32, u8, i32)>, +} + +impl Vlc { + fn new(entries: impl Iterator) -> Vlc { + let mut code = 0u64; + let mut codes = Vec::new(); + for (symbol, len) in entries { + codes.push((code as u32, len, symbol)); + code += 1 << (32 - len); + } + Vlc { codes } + } + + fn read(&self, bits: &mut Bits) -> i32 { + let v = bits.peek32(); + let i = self.codes.partition_point(|c| c.0 <= v) - 1; + let (_, len, symbol) = self.codes[i]; + bits.pos += len as usize; + symbol + } +} + +struct Codes { + scale: Vlc, + scale_rl: Vlc, + coef: [Vlc; 2], + vec4: Vlc, + vec2: Vlc, + vec1: Vlc, +} + +fn codes() -> &'static Codes { + static CODES: OnceLock = OnceLock::new(); + CODES.get_or_init(|| { + let pairs = |t: &'static [(u16, u8)], offset: i32| { + Vlc::new(t.iter().map(move |&(s, l)| (s as i32 + offset, l))) + }; + Codes { + scale: pairs(&SCALE, -60), + scale_rl: pairs(&SCALE_RL, 0), + coef: [ + Vlc::new(COEF0_SYMS.iter().zip(COEF0_LENS).map(|(&s, l)| (s as i32, l))), + pairs(&COEF1, 0), + ], + vec4: Vlc::new(VEC4_SYMS.iter().zip(VEC4_LENS).map(|(&s, l)| (s as i32 - 1, l))), + vec2: pairs(&VEC2, -1), + vec1: pairs(&VEC1, 0), + } + }) +} + +/// `ff_wma_get_large_val`. +fn large_value(bits: &mut Bits) -> u32 { + let mut n = 8; + if bits.bit() { + n += 8; + if bits.bit() { + n += 8; + if bits.bit() { + n += 7; + } + } + } + bits.read(n) +} + +fn log2(v: usize) -> u32 { + usize::BITS - 1 - v.max(1).leading_zeros() +} + +// The inverse transform. + +/// Half-length inverse MDCT as FFmpeg defines it (`av_tx` MDCT, inverse): +/// `n` coefficients to the middle `n` samples of the 2n-sample window, +/// negated and scaled by `scale`. Computed as a DCT-IV through an +/// n/2-point complex FFT. +fn imdct_half(input: &[f32], out: &mut [f32], scale: f32) { + let n = input.len(); + let m = n / 2; + let mut re = vec![0f64; m]; + let mut im = vec![0f64; m]; + for k in 0..m { + let (a, b) = (input[2 * k] as f64, input[n - 1 - 2 * k] as f64); + let (s, c) = (-std::f64::consts::PI * k as f64 / n as f64).sin_cos(); + (re[k], im[k]) = (a * c - b * s, a * s + b * c); + } + fft(&mut re, &mut im); + for k in 0..m { + let (s, c) = (-std::f64::consts::PI * (4 * k + 1) as f64 / (4 * n) as f64).sin_cos(); + let (wr, wi) = (re[k] * c - im[k] * s, re[k] * s + im[k] * c); + // DCT-IV: c[2k] = Re, c[n-1-2k] = -Im; output j is c[n-1-j]. + out[n - 1 - 2 * k] = (wr as f32) * scale; + out[2 * k] = -(wi as f32) * scale; + } +} + +/// In-place radix-2 forward DFT (`exp(-2πi nk/N)`). +fn fft(re: &mut [f64], im: &mut [f64]) { + let n = re.len(); + let mut j = 0; + for i in 1..n { + let mut bit = n >> 1; + while j & bit != 0 { + j ^= bit; + bit >>= 1; + } + j |= bit; + if i < j { + re.swap(i, j); + im.swap(i, j); + } + } + let mut len = 2; + while len <= n { + let (ws, wc) = (-2.0 * std::f64::consts::PI / len as f64).sin_cos(); + for start in (0..n).step_by(len) { + let (mut cr, mut ci) = (1.0, 0.0); + for k in 0..len / 2 { + let (a, b) = (start + k, start + k + len / 2); + let (tr, ti) = (re[b] * cr - im[b] * ci, re[b] * ci + im[b] * cr); + (re[b], im[b]) = (re[a] - tr, im[a] - ti); + (re[a], im[a]) = (re[a] + tr, im[a] + ti); + (cr, ci) = (cr * wc - ci * ws, cr * ws + ci * wc); + } + } + len <<= 1; + } +} + +/// `ff_sine_windows`: the rising half of a sine window of length `n`. +fn sine_window(n: usize) -> Vec { + (0..n) + .map(|i| ((i as f64 + 0.5) * std::f64::consts::PI / (2.0 * n as f64)).sin() as f32) + .collect() +} + +// The frame decoder. + +#[derive(Clone)] +struct Channel { + prev_block_len: usize, + transmit_coefs: bool, + num_subframes: usize, + subframe_len: [usize; MAX_SUBFRAMES], + cur_subframe: usize, + decoded_samples: usize, + quant_step: i32, + reuse_sf: bool, + scale_factor_step: i32, + max_scale_factor: i32, + saved_scale_factors: [[i32; MAX_BANDS]; 2], + scale_factor_idx: usize, + /// Which of the two saved sets is in use for this subframe. + scale_factors: usize, + table_idx: usize, + num_vec_coeffs: usize, + coeffs: [f32; FRAME_SAMPLES], + /// The frame's output, then half a frame of overlap for the next one. + out: [f32; FRAME_SAMPLES + FRAME_SAMPLES / 2], +} + +impl Channel { + fn new() -> Self { + Channel { + prev_block_len: FRAME_SAMPLES, + transmit_coefs: false, + num_subframes: 0, + subframe_len: [0; MAX_SUBFRAMES], + cur_subframe: 0, + decoded_samples: 0, + quant_step: 0, + reuse_sf: false, + scale_factor_step: 1, + max_scale_factor: 0, + saved_scale_factors: [[0; MAX_BANDS]; 2], + scale_factor_idx: 0, + scale_factors: 0, + table_idx: 0, + num_vec_coeffs: 0, + coeffs: [0.0; FRAME_SAMPLES], + out: [0.0; FRAME_SAMPLES + FRAME_SAMPLES / 2], + } + } +} + +/// Decodes the frames of one mono or stereo stream. +#[derive(Clone)] +pub struct Decoder { + channels: usize, + num_sfb: [usize; BLOCK_SIZES], + sfb_offsets: [[usize; MAX_BANDS + 1]; BLOCK_SIZES], + sf_offsets: [[[usize; MAX_BANDS]; BLOCK_SIZES]; BLOCK_SIZES], + ch: [Channel; 2], + // Per subframe. + subframe_len: usize, + channels_for_cur_subframe: usize, + channel_indexes: [usize; 2], + num_bands: usize, + table_idx: usize, + esc_len: u32, + transmit_num_vec_coeffs: bool, + transform: bool, + transform_band: [bool; MAX_BANDS], + parsed_all_subframes: bool, +} + +/// What the decoder needs from the stream format: the channel count and +/// the sample rate, which sets the scale factor band layout. +impl Decoder { + pub fn new(channels: usize, sample_rate: u32) -> Decoder { + let channels = channels.clamp(1, 2); + let rate = match sample_rate { + r if r > 44_100 => 48_000, + r if r > 32_000 => 44_100, + r if r > 24_000 => 32_000, + _ => 24_000, + }; + let mut sfb_offsets = [[0usize; MAX_BANDS + 1]; BLOCK_SIZES]; + let mut num_sfb = [0usize; BLOCK_SIZES]; + for i in 0..BLOCK_SIZES { + let subframe_len = FRAME_SAMPLES >> i; + let offsets = &mut sfb_offsets[i]; + let mut band = 1; + for &freq in CRITICAL_FREQ.iter().take(MAX_BANDS - 1) { + if offsets[band - 1] >= subframe_len { + break; + } + let offset = ((subframe_len * 2 * freq as usize) / rate + 2) & !3; + if offset > offsets[band - 1] { + offsets[band] = offset; + band += 1; + } + if offset >= subframe_len { + break; + } + } + offsets[band - 1] = subframe_len; + num_sfb[i] = band - 1; + } + let mut sf_offsets = [[[0usize; MAX_BANDS]; BLOCK_SIZES]; BLOCK_SIZES]; + for i in 0..BLOCK_SIZES { + for b in 0..num_sfb[i] { + let offset = ((sfb_offsets[i][b] + sfb_offsets[i][b + 1] - 1) << i) >> 1; + for x in 0..BLOCK_SIZES { + let mut v = 0; + while v + 1 < MAX_BANDS && (sfb_offsets[x][v + 1] << x) < offset { + v += 1; + } + sf_offsets[i][x][b] = v; + } + } + } + Decoder { + channels, + num_sfb, + sfb_offsets, + sf_offsets, + ch: [Channel::new(), Channel::new()], + subframe_len: FRAME_SAMPLES, + channels_for_cur_subframe: 0, + channel_indexes: [0, 1], + num_bands: 0, + table_idx: 0, + esc_len: 0, + transmit_num_vec_coeffs: false, + transform: false, + transform_band: [false; MAX_BANDS], + parsed_all_subframes: false, + } + } + + pub fn channels(&self) -> usize { + self.channels + } + + /// Forgets the overlap with earlier frames (a new stream or a seek). + pub fn reset(&mut self) { + self.ch = [Channel::new(), Channel::new()]; + } + + /// Decodes one frame (`frame.data`, `frame.bits`) and appends + /// `FRAME_SAMPLES` interleaved samples per channel to `out`. + pub fn decode(&mut self, data: &[u8], bits: usize, out: &mut Vec) -> Result<(), Error> { + let mut b = Bits { + data, + pos: 0, + end: bits, + }; + let len = b.read(LENGTH_BITS) as usize; + let result = self.frame(&mut b, len); + if result.is_err() { + // Whatever the frame held is lost; keep the stream's timing. + for c in 0..self.channels { + self.ch[c].out = [0.0; FRAME_SAMPLES + FRAME_SAMPLES / 2]; + } + } + for i in 0..FRAME_SAMPLES { + for c in 0..self.channels { + out.push(to_i16(self.ch[c].out[i])); + } + } + for c in 0..self.channels { + self.ch[c].out.copy_within(FRAME_SAMPLES.., 0); + } + result + } + + /// The overlap left after the last frame, then silence: half a frame of + /// samples per channel. + pub fn flush(&mut self, out: &mut Vec) { + for i in 0..FRAME_SAMPLES / 2 { + for c in 0..self.channels { + out.push(to_i16(self.ch[c].out[i])); + } + } + self.reset(); + } + + fn frame(&mut self, b: &mut Bits, len: usize) -> Result<(), Error> { + self.tile_header(b)?; + // Post-processing transform. + if self.channels > 1 && b.bit() && b.bit() { + b.read((self.channels * self.channels * 4) as u32); + } + // Dynamic range compression gain, unused. + b.read(8); + if b.bit() { + // Trim at start and end, which only WMA Pro files apply. + if b.bit() { + b.read(log2(FRAME_SAMPLES * 2)); + } + if b.bit() { + b.read(log2(FRAME_SAMPLES * 2)); + } + } + self.parsed_all_subframes = false; + for c in 0..self.channels { + let ch = &mut self.ch[c]; + ch.decoded_samples = 0; + ch.cur_subframe = 0; + ch.reuse_sf = false; + } + while !self.parsed_all_subframes { + self.subframe(b)?; + } + // FFmpeg flags `len != consumed + 2` but keeps the samples; so do we. + if b.overread() || b.consumed() > len { + return Err(Error("frame overread")); + } + Ok(()) + } + + fn subframe_length(&self, b: &mut Bits, offset: usize) -> Result { + if offset == FRAME_SAMPLES - MIN_SUBFRAME { + return Ok(MIN_SUBFRAME); + } + // Four subframe sizes: a 1-bit "not maximal", then 1 bit of shift. + let shift = if b.bit() { 1 + b.read(1) } else { 0 }; + let len = FRAME_SAMPLES >> shift; + if len < MIN_SUBFRAME { + return Err(Error("subframe length")); + } + Ok(len) + } + + fn tile_header(&mut self, b: &mut Bits) -> Result<(), Error> { + let mut num_samples = [0usize; 2]; + let mut contains = [false; 2]; + let mut channels_for_cur_subframe = self.channels; + let mut min_channel_len = 0; + for c in 0..self.channels { + self.ch[c].num_subframes = 0; + } + let fixed = b.bit(); + loop { + for c in 0..self.channels { + contains[c] = num_samples[c] == min_channel_len + && (fixed + || channels_for_cur_subframe == 1 + || min_channel_len == FRAME_SAMPLES - MIN_SUBFRAME + || b.bit()); + } + let subframe_len = self.subframe_length(b, min_channel_len)?; + min_channel_len += subframe_len; + for c in 0..self.channels { + let ch = &mut self.ch[c]; + if contains[c] { + if ch.num_subframes >= MAX_SUBFRAMES { + return Err(Error("too many subframes")); + } + ch.subframe_len[ch.num_subframes] = subframe_len; + num_samples[c] += subframe_len; + ch.num_subframes += 1; + if num_samples[c] > FRAME_SAMPLES { + return Err(Error("channel longer than a frame")); + } + } else if num_samples[c] <= min_channel_len { + if num_samples[c] < min_channel_len { + channels_for_cur_subframe = 0; + min_channel_len = num_samples[c]; + } + channels_for_cur_subframe += 1; + } + } + if min_channel_len >= FRAME_SAMPLES || b.overread() { + break; + } + } + if b.overread() { + return Err(Error("tile header")); + } + Ok(()) + } + + fn channel_transform(&mut self, b: &mut Bits) -> Result<(), Error> { + self.transform = false; + if self.channels == 1 { + return Ok(()); + } + if b.bit() { + return Err(Error("channel transform bit")); + } + // One group holding every channel of the subframe. + if self.channels_for_cur_subframe == 2 { + if b.bit() { + if b.bit() { + return Err(Error("channel transform type")); + } + } else { + self.transform = true; + } + } + if self.transform { + if !b.bit() { + for i in 0..self.num_bands { + self.transform_band[i] = b.bit(); + } + } else { + self.transform_band = [true; MAX_BANDS]; + } + } + Ok(()) + } + + fn coefficients(&mut self, b: &mut Bits, c: usize) -> Result<(), Error> { + let codes = codes(); + let table = b.bit() as usize; + let (run, level): (&[u16], &[f32]) = if table == 1 { + (&COEF1_RUN, &COEF1_LEVEL) + } else { + (&COEF0_RUN, &COEF0_LEVEL) + }; + let subframe_len = self.subframe_len; + let ch = &mut self.ch[c]; + let mut rl_mode = false; + let mut cur = 0; + let mut num_zeros = 0; + while (self.transmit_num_vec_coeffs || !rl_mode) && cur + 3 < ch.num_vec_coeffs { + let mut vals = [0u32; 4]; + let idx = codes.vec4.read(b); + if idx < 0 { + for i in (0..4).step_by(2) { + let idx = codes.vec2.read(b); + if idx < 0 { + for v in &mut vals[i..i + 2] { + let mut x = codes.vec1.read(b) as u32; + if x as usize == VEC1.len() - 1 { + x += large_value(b); + } + *v = x; + } + } else { + vals[i] = (idx >> 4) as u32; + vals[i + 1] = (idx & 0xf) as u32; + } + } + } else { + vals = [ + (idx >> 12) as u32, + ((idx >> 8) & 0xf) as u32, + ((idx >> 4) & 0xf) as u32, + (idx & 0xf) as u32, + ]; + } + for v in vals { + if v != 0 { + let negative = !b.bit(); + ch.coeffs[cur] = if negative { -(v as f32) } else { v as f32 }; + num_zeros = 0; + } else { + ch.coeffs[cur] = 0.0; + num_zeros += 1; + rl_mode |= num_zeros > subframe_len >> 8; + } + cur += 1; + } + if b.overread() { + return Err(Error("vector coefficients")); + } + } + if cur < subframe_len { + ch.coeffs[cur..subframe_len].fill(0.0); + // `ff_wma_run_level_decode`, version 1. + let mask = subframe_len - 1; + let mut offset = cur; + while offset < subframe_len { + let code = codes.coef[table].read(b); + if code > 1 { + offset += run[code as usize] as usize; + let negative = !b.bit(); + let v = level[code as usize]; + ch.coeffs[offset & mask] = if negative { -v } else { v }; + } else if code == 1 { + break; + } else { + let value = large_value(b) as i32; + if b.bit() { + if b.bit() { + if b.bit() { + // A broken escape ends the channel's + // coefficients, as in FFmpeg. + break; + } + offset += b.read(self.esc_len) as usize + 4; + } else { + offset += b.read(2) as usize + 1; + } + } + let negative = !b.bit(); + ch.coeffs[offset & mask] = if negative { -value } else { value } as f32; + } + if b.overread() { + return Err(Error("run level coefficients")); + } + offset += 1; + } + } + Ok(()) + } + + fn scale_factors(&mut self, b: &mut Bits) -> Result<(), Error> { + let codes = codes(); + for i in 0..self.channels_for_cur_subframe { + let c = self.channel_indexes[i]; + let sf_offsets = self.sf_offsets[self.table_idx][self.ch[c].table_idx]; + let ch = &mut self.ch[c]; + let target = 1 - ch.scale_factor_idx; + ch.scale_factors = target; + if ch.reuse_sf { + let from = ch.saved_scale_factors[ch.scale_factor_idx]; + for (sf, &offset) in ch.saved_scale_factors[target].iter_mut().zip(&sf_offsets).take(self.num_bands) { + *sf = from[offset]; + } + } + if ch.cur_subframe == 0 || b.bit() { + if !ch.reuse_sf { + ch.scale_factor_step = b.read(2) as i32 + 1; + let mut val = 45 / ch.scale_factor_step; + for band in 0..self.num_bands { + val += codes.scale.read(b); + ch.saved_scale_factors[target][band] = val; + } + } else { + let mut band = 0; + while band < self.num_bands { + let idx = codes.scale_rl.read(b); + let (skip, val, negative) = match idx { + 0 => { + let code = b.read(14); + ((code & 0x3f) >> 1, (code >> 6) as i32, code & 1 == 0) + } + 1 => break, + _ => ( + SCALE_RL_RUN[idx as usize] as u32, + SCALE_RL_LEVEL[idx as usize] as i32, + !b.bit(), + ), + }; + band += skip as usize; + if band >= self.num_bands { + return Err(Error("scale factor run")); + } + ch.saved_scale_factors[target][band] += if negative { -val } else { val }; + band += 1; + } + } + ch.scale_factor_idx = target; + ch.table_idx = self.table_idx; + ch.reuse_sf = true; + } + let sf = &ch.saved_scale_factors[ch.scale_factors][..self.num_bands]; + ch.max_scale_factor = sf.iter().copied().max().unwrap_or(0); + } + Ok(()) + } + + fn subframe(&mut self, b: &mut Bits) -> Result<(), Error> { + let mut offset = FRAME_SAMPLES; + let mut subframe_len = FRAME_SAMPLES; + let mut total_samples = FRAME_SAMPLES * self.channels; + for c in 0..self.channels { + let ch = &self.ch[c]; + if offset > ch.decoded_samples { + offset = ch.decoded_samples; + subframe_len = ch.subframe_len[ch.cur_subframe.min(MAX_SUBFRAMES - 1)]; + } + } + self.channels_for_cur_subframe = 0; + for c in 0..self.channels { + let ch = &mut self.ch[c]; + total_samples -= ch.decoded_samples; + if offset == ch.decoded_samples + && ch.cur_subframe < ch.num_subframes + && subframe_len == ch.subframe_len[ch.cur_subframe] + { + total_samples -= subframe_len; + ch.decoded_samples += subframe_len; + self.channel_indexes[self.channels_for_cur_subframe] = c; + self.channels_for_cur_subframe += 1; + } + } + if self.channels_for_cur_subframe == 0 { + return Err(Error("no channel in subframe")); + } + if total_samples == 0 { + self.parsed_all_subframes = true; + } + self.table_idx = log2(FRAME_SAMPLES / subframe_len) as usize; + self.num_bands = self.num_sfb[self.table_idx]; + self.subframe_len = subframe_len; + self.esc_len = log2(subframe_len - 1) + 1; + + // Extended header: fill bits. + if b.bit() { + let mut fill = b.read(2) as usize; + if fill == 0 { + let len = b.read(4); + fill = b.read(len) as usize + 1; + } + b.pos += fill; + } + if b.bit() { + return Err(Error("reserved bit")); + } + self.channel_transform(b)?; + + let mut transmit_coeffs = false; + for i in 0..self.channels_for_cur_subframe { + let c = self.channel_indexes[i]; + self.ch[c].transmit_coefs = b.bit(); + transmit_coeffs |= self.ch[c].transmit_coefs; + } + if transmit_coeffs { + self.transmit_num_vec_coeffs = b.bit(); + if self.transmit_num_vec_coeffs { + let num_bits = log2(subframe_len.div_ceil(4)) + 1; + for i in 0..self.channels_for_cur_subframe { + let c = self.channel_indexes[i]; + let n = (b.read(num_bits) << 2) as usize; + if n > subframe_len { + return Err(Error("vector coefficient count")); + } + self.ch[c].num_vec_coeffs = n; + } + } else { + for i in 0..self.channels_for_cur_subframe { + self.ch[self.channel_indexes[i]].num_vec_coeffs = subframe_len; + } + } + // Quantisation step (16-bit samples: 90 * 16 >> 4). + let mut quant_step = 90; + let mut step = b.signed(6); + quant_step += step; + if step == -32 || step == 31 { + let negative = step == -32; + let mut quant = 0; + while b.pos + 5 < b.end { + step = b.read(5) as i32; + if step != 31 { + break; + } + quant += 31; + } + quant_step += if negative { -(quant + step) } else { quant + step }; + } + if self.channels_for_cur_subframe == 1 { + self.ch[self.channel_indexes[0]].quant_step = quant_step; + } else { + let modifier_len = b.read(3); + for i in 0..self.channels_for_cur_subframe { + let c = self.channel_indexes[i]; + self.ch[c].quant_step = quant_step; + if b.bit() { + self.ch[c].quant_step += if modifier_len > 0 { + b.read(modifier_len) as i32 + 1 + } else { + 1 + }; + } + } + } + self.scale_factors(b)?; + } + + for i in 0..self.channels_for_cur_subframe { + let c = self.channel_indexes[i]; + if self.ch[c].transmit_coefs && b.pos < b.end { + self.coefficients(b, c)?; + } else { + self.ch[c].coeffs[..subframe_len].fill(0.0); + } + } + + // Where this subframe's samples go in the channel output. + let at = offset + FRAME_SAMPLES / 2; + if transmit_coeffs { + self.inverse_channel_transform(); + // Output in [-1, 1] for 16-bit streams. + let scale = 2.0 / subframe_len as f32 / 32768.0; + let sfb = self.sfb_offsets[self.table_idx]; + let mut tmp = [0f32; FRAME_SAMPLES]; + for i in 0..self.channels_for_cur_subframe { + let ch = &mut self.ch[self.channel_indexes[i]]; + let sf = ch.saved_scale_factors[ch.scale_factors]; + for band in 0..self.num_bands { + let end = sfb[band + 1].min(subframe_len); + let exp = ch.quant_step - (ch.max_scale_factor - sf[band]) * ch.scale_factor_step; + let quant = 10f32.powf(exp as f32 / 20.0); + for (t, &c) in tmp[sfb[band]..end].iter_mut().zip(&ch.coeffs[sfb[band]..end]) { + *t = c * quant; + } + } + imdct_half(&tmp[..subframe_len], &mut ch.out[at..at + subframe_len], scale); + } + } else { + for i in 0..self.channels_for_cur_subframe { + self.ch[self.channel_indexes[i]].out[at..at + subframe_len].fill(0.0); + } + } + + // Window and overlap-add with the previous block. + for i in 0..self.channels_for_cur_subframe { + let ch = &mut self.ch[self.channel_indexes[i]]; + let mut winlen = ch.prev_block_len; + let mut start = at - winlen / 2; + if subframe_len < winlen { + start += (winlen - subframe_len) / 2; + winlen = subframe_len; + } + window_overlap(&mut ch.out[start..start + winlen], &windows()[log2(winlen) as usize - 7]); + ch.prev_block_len = subframe_len; + } + + for i in 0..self.channels_for_cur_subframe { + let ch = &mut self.ch[self.channel_indexes[i]]; + if ch.cur_subframe >= ch.num_subframes { + return Err(Error("subframe overrun")); + } + ch.cur_subframe += 1; + } + if b.overread() { + return Err(Error("subframe overread")); + } + Ok(()) + } + + fn inverse_channel_transform(&mut self) { + if !self.transform || self.channels_for_cur_subframe != 2 { + return; + } + let sfb = self.sfb_offsets[self.table_idx]; + let [a, b] = &mut self.ch; + for band in 0..self.num_bands { + let range = sfb[band]..sfb[band + 1].min(self.subframe_len); + if self.transform_band[band] { + for y in range { + let (l, r) = (a.coeffs[y], b.coeffs[y]); + (a.coeffs[y], b.coeffs[y]) = (l - r, l + r); + } + } else { + for y in range { + a.coeffs[y] *= 181.0 / 128.0; + b.coeffs[y] *= 181.0 / 128.0; + } + } + } + } +} + +/// Sine windows for blocks of 128, 256 and 512 samples. +fn windows() -> &'static [Vec; 3] { + static WINDOWS: OnceLock<[Vec; 3]> = OnceLock::new(); + WINDOWS.get_or_init(|| [sine_window(128), sine_window(256), sine_window(512)]) +} + +/// FFmpeg's `vector_fmul_window` in place: the first half of `block` holds +/// the previous block's tail, the second half the current block's head. +fn window_overlap(block: &mut [f32], window: &[f32]) { + let len = block.len() / 2; + for k in 0..len { + let (i, j) = (k, 2 * len - 1 - k); + let (s0, s1) = (block[i], block[2 * len - 1 - k]); + let (wi, wj) = (window[i], window[j]); + block[i] = s0 * wj - s1 * wi; + block[j] = s0 * wi + s1 * wj; + } +} + +fn to_i16(v: f32) -> i16 { + (v * 32768.0).round().clamp(-32768.0, 32767.0) as i16 +} + +#[cfg(test)] +mod tests { + use super::*; + + /// Writes `value` as `n` bits, MSB first, at bit `pos`. + fn put_bits(data: &mut [u8], pos: usize, n: u32, value: u32) { + for i in 0..n as usize { + if value >> (n as usize - 1 - i) & 1 == 1 { + data[(pos + i) / 8] |= 1 << (7 - (pos + i) % 8); + } + } + } + + /// A damaged packet whose first frame says it is 0 bits long: finding + /// the frame after a later one must give up, not walk in place forever + /// (found by random-input testing). + #[test] + fn a_zero_length_frame_before_the_start_ends_the_search() { + let mut data = vec![0u8; PACKET_BYTES]; + // Two frames, the first at payload bit 0; its 15-bit length stays 0. + put_bits(&mut data, 0, 32, 2 << 26); + let start = HEADER_BITS + 100; + put_bits(&mut data, start, LENGTH_BITS, 200); + let frame = read_frame(&data, start).expect("the frame at `start` is well formed"); + assert_eq!(frame.bits, 200); + assert_eq!(frame.next, None); + } + + /// The direct sum `imdct_half` stands for (FFmpeg's naive inverse MDCT: + /// the standard formula, negated). + fn imdct_reference(input: &[f32]) -> Vec { + let n = input.len(); + (0..n) + .map(|j| { + let t = (j + n / 2) as f64 + 0.5 + n as f64 / 2.0; + -(input + .iter() + .enumerate() + .map(|(k, &x)| x as f64 * (std::f64::consts::PI / n as f64 * t * (k as f64 + 0.5)).cos()) + .sum::() as f32) + }) + .collect() + } + + #[test] + fn fast_imdct_matches_the_direct_sum() { + for n in [128usize, 256, 512] { + let input: Vec = (0..n).map(|i| ((i * 7919) % 97) as f32 - 48.0).collect(); + let mut fast = vec![0f32; n]; + imdct_half(&input, &mut fast, 1.0); + let reference = imdct_reference(&input); + for (a, b) in fast.iter().zip(&reference) { + assert!((a - b).abs() < 1e-2 * (1.0 + b.abs()), "n {n}: {a} vs {b}"); + } + } + } + + /// Windowed MDCT blocks of a signal, put back together the way the + /// decoder does (half IMDCT, then window and overlap), give the signal. + #[test] + fn imdct_and_window_reconstruct_a_signal() { + let n = 256; + let signal: Vec = (0..n * 6).map(|i| (i as f32 * 0.05).sin() * 0.3).collect(); + // The 2n-sample sine window; its rising half is `sine_window(n)`. + let window = |i: usize| ((i as f64 + 0.5) * std::f64::consts::PI / (2.0 * n as f64)).sin(); + let mut out = vec![0f32; n * 7]; + for block in 0..5 { + let base = block * n; + let coeffs: Vec = (0..n) + .map(|k| { + (0..2 * n) + .map(|i| { + let t = i as f64 + 0.5 + n as f64 / 2.0; + // FFmpeg's forward MDCT pairs with its inverse + // by sign. + -signal[base + i] as f64 + * window(i) + * (std::f64::consts::PI / n as f64 * t * (k as f64 + 0.5)).cos() + }) + .sum::() as f32 + }) + .collect(); + // The half output is the middle of the 2n window. + let at = base + n / 2; + imdct_half(&coeffs, &mut out[at..at + n], 2.0 / n as f32); + if block > 0 { + window_overlap(&mut out[at - n / 2..at + n / 2], &sine_window(n)); + } + } + for i in n..5 * n { + assert!((out[i] - signal[i]).abs() < 1e-3, "{i}: {} vs {}", out[i], signal[i]); + } + } + + #[test] + fn packet_rejects_out_of_range_indices_and_partial_headers() { + assert!(packet(&[0; 4], usize::MAX / PACKET_BYTES + 1).is_none()); + assert!(packet(&[0; 3], 0).is_none()); + } + + #[test] + fn packet_headers_and_frame_walk() { + // Two packets: frame A (100 bits) and B (16300 bits, crossing into + // packet 1 by 48 bits), then C (60 bits) in packet 1; the rest is + // padding. + let mut data = vec![0xffu8; 2 * PACKET_BYTES]; + let header = |frames: u32, first: u32| (frames << 26) | (first << 11); + let bits = [(0, header(2, 0), 32), (PACKET_BITS, header(1, 48), 32)]; + let put = |data: &mut Vec, at: usize, value: u32, width: u32| { + for i in 0..width as usize { + let bit = (value >> (width as usize - 1 - i)) & 1; + let p = at + i; + data[p / 8] = (data[p / 8] & !(1 << (7 - p % 8))) | ((bit as u8) << (7 - p % 8)); + } + }; + for &(at, v, w) in &bits { + put(&mut data, at, v, w); + } + put(&mut data, 32, 100, 15); + put(&mut data, 132, 16300, 15); + let c_start = PACKET_BITS + 32 + 48; + put(&mut data, c_start, 60, 15); + let a = read_frame(&data, 32).unwrap(); + assert_eq!((a.bits, a.next), (100, Some(132))); + let b = read_frame(&data, 132).unwrap(); + assert_eq!((b.bits, b.next), (16300, Some(c_start))); + // Its last bits come from after packet 1's header. + assert_eq!(b.data.len(), 16300usize.div_ceil(8)); + let c = read_frame(&data, c_start).unwrap(); + assert_eq!(c.bits, 60); + // C was packet 1's only frame: the next would be in packet 2. + assert_eq!(c.next, None); + } + + /// Walks and decodes saved input buffers (`LEONIDA_XMA_STREAMS=` of + /// `*.xma` files with their `*.ctx` context words, made outside the + /// repository): the frames walked from the first packet must be the + /// frames the packet headers count, and every frame must decode. + #[test] + #[ignore = "needs streams outside the repository"] + fn walks_saved_streams() { + let dir = std::env::var("LEONIDA_XMA_STREAMS").unwrap(); + let mut bad = 0; + let mut streams = 0; + for entry in std::fs::read_dir(dir).unwrap() { + let path = entry.unwrap().path(); + if path.extension().is_none_or(|e| e != "xma") { + continue; + } + streams += 1; + let data = std::fs::read(&path).unwrap(); + let counted: u32 = (0..data.len() / PACKET_BYTES) + .map(|i| packet(&data, i).unwrap().frames) + .sum(); + // Context word 1: sample rate in bits 27-28, stereo in bit 29. + let ctx = std::fs::read(path.with_extension("ctx")).unwrap(); + let word = u32::from_le_bytes(ctx[4..8].try_into().unwrap()); + let rate = [24_000, 32_000, 44_100, 48_000][(word >> 27 & 3) as usize]; + let mut decoder = Decoder::new(1 + (word >> 29 & 1) as usize, rate); + let (mut walked, mut errors, mut peak, mut pcm) = (0, 0, 0i16, Vec::new()); + let mut at = Some(HEADER_BITS + packet(&data, 0).unwrap().first_frame_bit as usize); + while let Some(frame) = at.and_then(|bit| read_frame(&data, bit)) { + pcm.clear(); + errors += decoder.decode(&frame.data, frame.bits, &mut pcm).is_err() as u32; + peak = pcm.iter().fold(peak, |p, s| p.max(s.saturating_abs())); + walked += 1; + at = frame.next; + } + println!( + "{}: {} packets, {counted} frames counted, {walked} walked, {errors} bad, peak {peak}", + path.display(), + data.len() / PACKET_BYTES + ); + bad += u32::from(walked != counted || errors > 0); + } + assert!(streams > 0, "LEONIDA_XMA_STREAMS contains no .xma files"); + assert_eq!(bad, 0); + } + + /// Decodes a stream's packets and compares with a reference decode of + /// the same file (16-bit PCM): `LEONIDA_XMA_REFERENCE=` holding + /// `mono.xmadata`/`mono.ref` and `stereo.xmadata`/`stereo.ref` (made + /// outside the repository). + #[test] + #[ignore = "needs reference files outside the repository"] + fn matches_a_reference_decoder() { + let dir = std::path::PathBuf::from(std::env::var("LEONIDA_XMA_REFERENCE").unwrap()); + for (name, channels) in [("mono", 1), ("stereo", 2)] { + let data = std::fs::read(dir.join(format!("{name}.xmadata"))).unwrap(); + let reference: Vec = std::fs::read(dir.join(format!("{name}.ref"))) + .unwrap() + .as_chunks::<2>() + .0 + .iter() + .map(|&b| i16::from_le_bytes(b)) + .collect(); + let mut decoder = Decoder::new(channels, 48_000); + let mut pcm = Vec::new(); + let mut at = Some(HEADER_BITS + packet(&data, 0).unwrap().first_frame_bit as usize); + let mut errors = 0; + while let Some(frame) = at.and_then(|bit| read_frame(&data, bit)) { + errors += decoder.decode(&frame.data, frame.bits, &mut pcm).is_err() as usize; + at = frame.next; + } + // Find the decoder delay, then measure the error. + let best = (0..2048 / channels) + .map(|d| { + let n = reference.len().min(pcm.len() - d * channels); + let e: f64 = (0..n) + .map(|i| (pcm[d * channels + i] as f64 - reference[i] as f64).powi(2)) + .sum(); + (e, d, n) + }) + .min_by(|a, b| a.0.total_cmp(&b.0)) + .unwrap(); + let signal: f64 = reference.iter().map(|&s| (s as f64).powi(2)).sum(); + let snr = 10.0 * (signal / best.0.max(1.0)).log10(); + println!( + "{name}: {} samples, {errors} bad frames, delay {} samples, SNR {snr:.1} dB", + pcm.len() / channels, + best.1 + ); + assert!(errors == 0 && snr > 40.0); + } + } +} diff --git a/crates/leonida-formats/src/xma/tables.rs b/crates/leonida-formats/src/xma/tables.rs new file mode 100644 index 000000000..bf8fc43f4 --- /dev/null +++ b/crates/leonida-formats/src/xma/tables.rs @@ -0,0 +1,410 @@ +//! Huffman and level tables of the WMA Pro bitstream that XMA2 frames use, +//! converted from FFmpeg's `libavcodec/wmaprodata.h` (LGPL-2.1-or-later, +//! used here under GPL-3.0-or-later as that licence allows). Pairs are +//! (symbol, code length) in canonical code order. + +pub(super) const CRITICAL_FREQ: [u16; 28] = [ + 100, 200, 300, 400, 510, 630, 770, 920, + 1080, 1270, 1480, 1720, 2000, 2320, 2700, 3150, + 3700, 4400, 5300, 6400, 7700, 9500, 12000, 15500, + 20675, 28575, 41375, 63875, +]; + +pub(super) const SCALE: [(u16, u8); 121] = [ + (58, 5), (64, 6), (66, 7), (65, 7), (62, 5), (63, 6), (68, 9), (69, 10), + (54, 15), (19, 19), (20, 19), (21, 19), (22, 19), (23, 19), (24, 19), (25, 19), + (26, 19), (27, 19), (28, 19), (29, 19), (30, 19), (31, 19), (32, 19), (33, 19), + (34, 19), (17, 19), (36, 19), (37, 19), (38, 19), (39, 19), (40, 19), (41, 19), + (42, 19), (43, 19), (44, 19), (45, 19), (46, 19), (47, 19), (48, 19), (49, 19), + (50, 19), (51, 19), (52, 19), (15, 19), (16, 19), (14, 19), (13, 19), (12, 19), + (11, 19), (10, 19), (0, 19), (9, 19), (8, 19), (7, 19), (6, 19), (5, 19), + (4, 19), (55, 13), (70, 13), (3, 19), (2, 19), (1, 19), (35, 19), (71, 19), + (72, 19), (73, 19), (74, 19), (75, 19), (76, 19), (77, 19), (78, 19), (79, 19), + (80, 19), (81, 19), (82, 19), (83, 19), (84, 19), (85, 19), (86, 19), (87, 19), + (88, 19), (89, 19), (90, 19), (91, 19), (92, 19), (93, 19), (94, 19), (95, 19), + (96, 19), (97, 19), (98, 19), (99, 19), (100, 19), (101, 19), (102, 19), (103, 19), + (104, 19), (105, 19), (106, 19), (107, 19), (108, 19), (109, 19), (110, 19), (111, 19), + (112, 19), (113, 19), (114, 19), (115, 19), (116, 19), (117, 19), (118, 19), (119, 19), + (120, 19), (18, 18), (53, 16), (56, 11), (57, 8), (67, 7), (61, 3), (59, 2), + (60, 1), +]; + +pub(super) const SCALE_RL: [(u16, u8); 120] = [ + (103, 7), (80, 11), (60, 11), (18, 10), (56, 10), (21, 12), (90, 12), (58, 11), + (27, 11), (69, 12), (84, 15), (48, 15), (86, 14), (47, 13), (19, 10), (32, 9), + (78, 6), (5, 5), (28, 4), (53, 5), (9, 7), (31, 8), (38, 8), (10, 7), + (88, 11), (25, 12), (105, 12), (118, 11), (23, 12), (82, 14), (98, 16), (110, 16), + (108, 15), (93, 13), (68, 10), (72, 12), (97, 12), (81, 12), (42, 12), (64, 8), + (4, 4), (1, 2), (7, 6), (14, 7), (0, 9), (55, 9), (61, 9), (117, 10), + (24, 12), (44, 12), (67, 12), (70, 16), (99, 18), (96, 21), (95, 21), (2, 21), + (77, 21), (52, 21), (111, 21), (102, 20), (101, 17), (46, 15), (73, 15), (109, 15), + (51, 14), (92, 14), (30, 7), (11, 7), (66, 7), (15, 8), (16, 8), (116, 9), + (65, 9), (57, 10), (59, 10), (115, 9), (12, 7), (35, 9), (17, 9), (41, 9), + (20, 11), (91, 11), (26, 12), (75, 15), (45, 15), (107, 14), (83, 14), (100, 15), + (89, 15), (43, 11), (62, 9), (37, 9), (104, 8), (6, 5), (39, 8), (40, 9), + (34, 9), (79, 7), (8, 6), (63, 6), (87, 12), (94, 14), (49, 14), (50, 13), + (22, 11), (119, 10), (33, 9), (36, 9), (113, 11), (106, 12), (112, 13), (71, 15), + (85, 15), (74, 14), (76, 10), (114, 7), (29, 5), (54, 6), (13, 6), (3, 2), +]; + +pub(super) const SCALE_RL_RUN: [u8; 120] = [ + 0, 0, 0, 0, 1, 2, 3, 4, + 5, 6, 7, 8, 9, 10, 11, 12, + 13, 14, 15, 16, 17, 18, 19, 20, + 21, 22, 23, 24, 0, 1, 2, 3, + 4, 5, 6, 7, 8, 9, 10, 11, + 12, 13, 14, 15, 16, 17, 18, 19, + 20, 21, 22, 23, 24, 0, 1, 2, + 3, 4, 5, 6, 7, 8, 9, 10, + 11, 12, 13, 14, 15, 16, 17, 18, + 19, 20, 21, 22, 23, 24, 0, 1, + 2, 3, 4, 5, 6, 7, 8, 9, + 10, 11, 12, 13, 14, 15, 16, 17, + 18, 19, 20, 21, 22, 23, 24, 0, + 1, 2, 3, 4, 5, 6, 7, 8, + 9, 10, 0, 1, 0, 1, 0, 1, +]; + +pub(super) const SCALE_RL_LEVEL: [u8; 120] = [ + 0, 0, 1, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 3, 3, 3, 3, + 3, 3, 3, 3, 3, 3, 3, 3, + 3, 3, 3, 3, 3, 3, 3, 3, + 3, 3, 3, 3, 3, 4, 4, 4, + 4, 4, 4, 4, 4, 4, 4, 4, + 4, 4, 4, 4, 4, 4, 4, 4, + 4, 4, 4, 4, 4, 4, 5, 5, + 5, 5, 5, 5, 5, 5, 5, 5, + 5, 5, 5, 5, 5, 5, 5, 5, + 5, 5, 5, 5, 5, 5, 5, 6, + 6, 6, 6, 6, 6, 6, 6, 6, + 6, 6, 7, 7, 8, 8, 9, 9, +]; + +pub(super) const COEF0_LENS: [u8; 272] = [ + 2, 9, 14, 14, 13, 12, 13, 14, + 15, 15, 12, 10, 10, 10, 13, 14, + 15, 15, 12, 11, 13, 14, 14, 13, + 15, 15, 14, 12, 12, 8, 10, 10, + 15, 15, 14, 13, 14, 14, 13, 15, + 20, 20, 19, 21, 21, 20, 19, 17, + 17, 18, 18, 15, 15, 13, 12, 14, + 15, 15, 14, 15, 15, 12, 11, 6, + 7, 8, 9, 13, 13, 13, 14, 14, + 11, 10, 7, 8, 14, 14, 14, 14, + 12, 13, 13, 12, 12, 12, 11, 9, + 13, 14, 14, 12, 11, 11, 11, 9, + 8, 7, 14, 15, 15, 14, 14, 12, + 13, 15, 16, 17, 17, 14, 12, 12, + 12, 15, 15, 14, 14, 14, 13, 13, + 9, 9, 11, 11, 10, 7, 6, 13, + 15, 15, 14, 14, 14, 13, 14, 15, + 15, 13, 14, 14, 14, 14, 10, 9, + 10, 10, 11, 11, 10, 8, 9, 13, + 14, 14, 12, 11, 14, 15, 15, 13, + 12, 14, 14, 14, 14, 13, 14, 14, + 3, 5, 8, 10, 10, 15, 15, 14, + 14, 16, 16, 15, 12, 11, 11, 11, + 7, 8, 8, 9, 12, 13, 13, 12, + 14, 15, 15, 13, 10, 11, 11, 13, + 14, 14, 13, 14, 14, 11, 10, 13, + 15, 15, 14, 12, 11, 4, 6, 6, + 8, 12, 12, 12, 13, 13, 12, 13, + 13, 14, 14, 13, 13, 13, 9, 7, + 9, 11, 14, 14, 13, 14, 14, 13, + 10, 8, 7, 5, 9, 12, 13, 14, + 15, 15, 12, 12, 10, 14, 14, 13, + 12, 13, 14, 14, 12, 13, 13, 12, + 12, 12, 9, 7, 6, 3, 4, 4, +]; + +pub(super) const COEF0_SYMS: [u16; 272] = [ + 2, 25, 111, 94, 69, 58, 87, 93, + 136, 135, 59, 37, 34, 36, 82, 182, + 120, 138, 195, 45, 168, 216, 178, 86, + 140, 219, 186, 162, 239, 18, 156, 35, + 127, 236, 109, 85, 180, 253, 88, 147, + 268, 264, 256, 266, 270, 262, 260, 248, + 246, 252, 258, 137, 189, 230, 64, 179, + 146, 208, 101, 118, 238, 163, 46, 9, + 153, 0, 26, 247, 169, 76, 202, 131, + 194, 38, 13, 19, 132, 106, 191, 97, + 65, 198, 77, 62, 66, 164, 48, 27, + 81, 183, 102, 60, 47, 49, 159, 227, + 20, 14, 112, 263, 144, 217, 104, 63, + 79, 209, 269, 250, 254, 203, 241, 196, + 61, 220, 148, 124, 185, 100, 80, 78, + 193, 28, 50, 235, 41, 1, 10, 171, + 226, 150, 103, 114, 115, 170, 105, 211, + 149, 249, 108, 188, 107, 255, 231, 155, + 42, 40, 55, 160, 39, 21, 29, 215, + 234, 184, 228, 51, 116, 142, 145, 172, + 165, 181, 130, 113, 117, 89, 128, 204, + 3, 7, 154, 157, 43, 141, 265, 133, + 225, 271, 244, 221, 74, 54, 56, 52, + 15, 222, 22, 30, 83, 199, 173, 73, + 123, 210, 143, 175, 44, 53, 237, 174, + 139, 134, 110, 218, 129, 161, 213, 177, + 267, 151, 125, 67, 223, 5, 11, 192, + 23, 214, 243, 166, 200, 176, 68, 224, + 187, 257, 261, 232, 96, 251, 31, 16, + 32, 57, 207, 121, 91, 126, 119, 99, + 158, 24, 212, 8, 33, 70, 92, 205, + 240, 242, 75, 197, 233, 259, 190, 98, + 71, 201, 122, 206, 72, 90, 95, 84, + 167, 245, 229, 17, 12, 4, 152, 6, +]; + +pub(super) const COEF1: [(u16, u8); 244] = [ + (2, 2), (3, 3), (102, 3), (4, 4), (148, 6), (134, 9), (171, 10), (18, 10), + (11, 8), (159, 8), (14, 9), (156, 14), (235, 15), (61, 15), (38, 13), (153, 13), + (48, 14), (49, 14), (23, 11), (203, 13), (208, 19), (204, 19), (129, 18), (94, 17), + (87, 16), (62, 15), (174, 15), (147, 15), (29, 12), (191, 12), (64, 15), (65, 15), + (146, 14), (164, 13), (142, 5), (132, 4), (103, 5), (154, 7), (165, 9), (181, 11), + (109, 12), (30, 12), (86, 16), (92, 16), (239, 15), (138, 14), (39, 13), (50, 14), + (115, 15), (238, 21), (228, 21), (236, 21), (222, 21), (216, 20), (226, 20), (196, 18), + (192, 17), (120, 16), (221, 14), (51, 14), (24, 11), (143, 8), (7, 6), (9, 7), + (152, 10), (136, 12), (160, 12), (241, 15), (66, 15), (168, 14), (219, 14), (113, 14), + (193, 12), (19, 10), (173, 10), (105, 8), (149, 9), (15, 9), (205, 13), (207, 13), + (125, 17), (190, 17), (182, 16), (68, 15), (70, 15), (67, 15), (137, 13), (31, 12), + (223, 14), (116, 15), (210, 19), (220, 19), (198, 18), (126, 17), (88, 16), (41, 13), + (25, 11), (40, 13), (73, 15), (243, 15), (53, 14), (195, 12), (183, 11), (225, 14), + (52, 14), (71, 15), (121, 16), (89, 16), (170, 14), (55, 14), (69, 15), (83, 15), + (209, 13), (108, 11), (32, 12), (54, 14), (122, 16), (184, 16), (176, 15), (42, 13), + (12, 8), (161, 8), (6, 5), (167, 9), (106, 9), (20, 10), (145, 12), (111, 13), + (43, 13), (26, 11), (175, 10), (107, 10), (34, 12), (33, 12), (197, 12), (74, 15), + (128, 17), (232, 20), (212, 20), (224, 19), (202, 18), (90, 16), (57, 14), (227, 14), + (97, 16), (93, 16), (140, 15), (185, 11), (27, 11), (16, 9), (158, 11), (211, 13), + (56, 14), (117, 15), (72, 15), (166, 13), (91, 16), (95, 16), (80, 15), (101, 16), + (194, 17), (127, 17), (82, 15), (21, 10), (144, 10), (177, 10), (151, 6), (10, 7), + (157, 7), (8, 6), (5, 4), (13, 8), (0, 9), (213, 13), (46, 13), (199, 12), + (35, 12), (162, 12), (135, 10), (169, 9), (45, 13), (59, 14), (114, 14), (44, 13), + (188, 16), (186, 16), (75, 15), (79, 15), (118, 15), (187, 11), (112, 13), (139, 14), + (178, 15), (81, 15), (110, 12), (28, 11), (163, 8), (133, 6), (104, 6), (17, 9), + (22, 10), (229, 14), (172, 14), (217, 13), (201, 12), (36, 12), (218, 20), (242, 22), + (240, 22), (234, 21), (230, 19), (206, 18), (200, 18), (214, 18), (130, 17), (131, 17), + (141, 15), (84, 15), (76, 15), (215, 13), (58, 14), (231, 14), (233, 14), (180, 15), + (77, 15), (37, 12), (189, 11), (179, 10), (155, 10), (47, 13), (96, 16), (99, 16), + (119, 15), (63, 14), (237, 14), (78, 15), (85, 15), (60, 14), (98, 16), (100, 16), + (124, 16), (123, 16), (150, 11), (1, 7), +]; + +pub(super) const COEF0_RUN: [u16; 272] = [ + 0, 0, 0, 1, 2, 3, 4, 5, + 6, 7, 8, 9, 10, 11, 12, 13, + 14, 15, 16, 17, 18, 19, 20, 21, + 22, 23, 24, 25, 26, 27, 28, 29, + 30, 31, 32, 33, 34, 35, 36, 37, + 38, 39, 40, 41, 42, 43, 44, 45, + 46, 47, 48, 49, 50, 51, 52, 53, + 54, 55, 56, 57, 58, 59, 60, 61, + 62, 63, 64, 65, 66, 67, 68, 69, + 70, 71, 72, 73, 74, 75, 76, 77, + 78, 79, 80, 81, 82, 83, 84, 85, + 86, 87, 88, 89, 90, 91, 92, 93, + 94, 95, 96, 97, 98, 99, 100, 101, + 102, 103, 104, 105, 106, 107, 108, 109, + 110, 111, 112, 113, 114, 115, 116, 117, + 118, 119, 120, 121, 122, 123, 124, 125, + 126, 127, 128, 129, 130, 131, 132, 133, + 134, 135, 136, 137, 138, 139, 140, 141, + 142, 143, 144, 145, 146, 147, 148, 149, + 0, 1, 2, 3, 4, 5, 6, 7, + 8, 9, 10, 11, 12, 13, 14, 15, + 16, 17, 18, 19, 20, 21, 22, 23, + 24, 25, 26, 27, 28, 29, 30, 31, + 32, 33, 34, 35, 36, 37, 38, 39, + 0, 1, 2, 3, 4, 5, 6, 7, + 8, 9, 10, 11, 12, 13, 14, 15, + 16, 17, 18, 19, 0, 1, 2, 3, + 4, 5, 6, 7, 8, 9, 0, 1, + 2, 3, 4, 0, 1, 0, 1, 0, + 1, 0, 1, 0, 1, 0, 1, 0, + 1, 0, 1, 0, 1, 0, 1, 0, + 1, 0, 1, 0, 1, 0, 1, 0, + 1, 0, 1, 0, 1, 0, 1, 0, + 1, 0, 1, 0, 1, 0, 1, 0, +]; + +pub(super) const COEF0_LEVEL: [f32; 272] = [ + 0.0, 0.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, + 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, + 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, + 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, + 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, + 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, + 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, + 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, + 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, + 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, + 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, + 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, + 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, + 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, + 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, + 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, + 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, + 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, + 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, + 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, + 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, + 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, + 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, + 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, + 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, + 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, + 3.0, 3.0, 3.0, 3.0, 4.0, 4.0, 4.0, 4.0, + 4.0, 4.0, 4.0, 4.0, 4.0, 4.0, 5.0, 5.0, + 5.0, 5.0, 5.0, 6.0, 6.0, 7.0, 7.0, 8.0, + 8.0, 9.0, 9.0, 10.0, 10.0, 11.0, 11.0, 12.0, + 12.0, 13.0, 13.0, 14.0, 14.0, 15.0, 15.0, 16.0, + 16.0, 17.0, 17.0, 18.0, 18.0, 19.0, 19.0, 20.0, + 20.0, 21.0, 21.0, 22.0, 22.0, 23.0, 23.0, 24.0, + 24.0, 25.0, 25.0, 26.0, 26.0, 27.0, 27.0, 28.0, +]; + +pub(super) const COEF1_RUN: [u16; 244] = [ + 0, 0, 0, 1, 2, 3, 4, 5, + 6, 7, 8, 9, 10, 11, 12, 13, + 14, 15, 16, 17, 18, 19, 20, 21, + 22, 23, 24, 25, 26, 27, 28, 29, + 30, 31, 32, 33, 34, 35, 36, 37, + 38, 39, 40, 41, 42, 43, 44, 45, + 46, 47, 48, 49, 50, 51, 52, 53, + 54, 55, 56, 57, 58, 59, 60, 61, + 62, 63, 64, 65, 66, 67, 68, 69, + 70, 71, 72, 73, 74, 75, 76, 77, + 78, 79, 80, 81, 82, 83, 84, 85, + 86, 87, 88, 89, 90, 91, 92, 93, + 94, 95, 96, 97, 98, 99, 0, 1, + 2, 3, 4, 5, 6, 7, 8, 9, + 10, 11, 12, 13, 14, 15, 16, 17, + 18, 19, 20, 21, 22, 23, 24, 25, + 26, 27, 28, 29, 0, 1, 2, 3, + 4, 5, 6, 7, 8, 9, 0, 1, + 2, 3, 4, 5, 0, 1, 2, 0, + 1, 2, 0, 1, 2, 0, 1, 0, + 1, 0, 1, 0, 1, 0, 1, 0, + 1, 0, 1, 0, 1, 0, 1, 0, + 1, 0, 1, 0, 1, 0, 1, 0, + 1, 0, 1, 0, 1, 0, 1, 0, + 1, 0, 1, 0, 1, 0, 1, 0, + 1, 0, 1, 0, 1, 0, 1, 0, + 1, 0, 1, 0, 1, 0, 1, 0, + 1, 0, 1, 0, 1, 0, 1, 0, + 1, 0, 1, 0, 1, 0, 1, 0, + 1, 0, 1, 0, 1, 0, 1, 0, + 1, 0, 0, 0, +]; + +pub(super) const COEF1_LEVEL: [f32; 244] = [ + 0.0, 0.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, + 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, + 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, + 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, + 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, + 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, + 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, + 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, + 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, + 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, + 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, + 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, + 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 2.0, 2.0, + 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, + 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, + 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, + 2.0, 2.0, 2.0, 2.0, 3.0, 3.0, 3.0, 3.0, + 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 4.0, 4.0, + 4.0, 4.0, 4.0, 4.0, 5.0, 5.0, 5.0, 6.0, + 6.0, 6.0, 7.0, 7.0, 7.0, 8.0, 8.0, 9.0, + 9.0, 10.0, 10.0, 11.0, 11.0, 12.0, 12.0, 13.0, + 13.0, 14.0, 14.0, 15.0, 15.0, 16.0, 16.0, 17.0, + 17.0, 18.0, 18.0, 19.0, 19.0, 20.0, 20.0, 21.0, + 21.0, 22.0, 22.0, 23.0, 23.0, 24.0, 24.0, 25.0, + 25.0, 26.0, 26.0, 27.0, 27.0, 28.0, 28.0, 29.0, + 29.0, 30.0, 30.0, 31.0, 31.0, 32.0, 32.0, 33.0, + 33.0, 34.0, 34.0, 35.0, 35.0, 36.0, 36.0, 37.0, + 37.0, 38.0, 38.0, 39.0, 39.0, 40.0, 40.0, 41.0, + 41.0, 42.0, 42.0, 43.0, 43.0, 44.0, 44.0, 45.0, + 45.0, 46.0, 46.0, 47.0, 47.0, 48.0, 48.0, 49.0, + 49.0, 50.0, 51.0, 52.0, +]; + +pub(super) const VEC4_LENS: [u8; 127] = [ + 1, 6, 8, 10, 10, 10, 10, 8, + 8, 10, 10, 9, 8, 8, 9, 12, + 12, 11, 12, 12, 11, 9, 9, 8, + 8, 9, 9, 8, 8, 9, 9, 12, + 12, 12, 14, 14, 13, 11, 11, 9, + 8, 9, 9, 11, 11, 10, 9, 8, + 6, 6, 6, 6, 6, 6, 11, 11, + 10, 11, 11, 10, 10, 11, 11, 9, + 7, 6, 7, 7, 6, 6, 6, 5, + 7, 11, 11, 10, 9, 8, 6, 9, + 9, 10, 10, 9, 8, 8, 6, 6, + 6, 8, 8, 9, 12, 12, 11, 10, + 8, 8, 8, 10, 10, 10, 10, 9, + 9, 8, 10, 11, 11, 9, 8, 8, + 8, 9, 9, 10, 11, 12, 12, 9, + 9, 9, 8, 8, 7, 7, 7, +]; + +pub(super) const VEC4_SYMS: [u16; 127] = [ + 0, 4370, 275, 8195, 4146, 12545, 8225, 290, + 4625, 515, 20, 8706, 8210, 4355, 4131, 16385, + 5121, 8961, 321, 1041, 51, 4641, 546, 4610, + 530, 513, 8451, 4385, 4130, 33, 8211, 5, + 66, 4161, 1281, 81, 6, 801, 8196, 8481, + 8449, 4611, 531, 561, 769, 12290, 8226, 19, + 4097, 2, 4369, 274, 4354, 4114, 12291, 16641, + 12305, 49, 12321, 260, 4100, 516, 21, 12546, + 8466, 4353, 4371, 4626, 257, 18, 17, 1, + 4386, 8241, 771, 4865, 8705, 8194, 4098, 12561, + 276, 50, 785, 4116, 8209, 4099, 273, 4113, + 258, 259, 4609, 35, 1026, 1025, 16401, 305, + 34, 529, 289, 770, 12289, 4, 4145, 4356, + 12306, 8193, 12801, 261, 16386, 4881, 3, 514, + 4129, 545, 306, 36, 4101, 65, 20481, 786, + 4401, 4866, 8721, 291, 8450, 8465, 4115, +]; + +pub(super) const VEC2: [(u16, u8); 137] = [ + (19, 5), (165, 10), (211, 11), (46, 11), (75, 10), (177, 11), (12, 11), (86, 8), + (83, 7), (38, 7), (133, 9), (178, 10), (28, 10), (104, 9), (73, 9), (35, 5), + (52, 6), (113, 9), (8, 9), (101, 8), (69, 7), (0, 3), (71, 8), (119, 9), + (91, 10), (179, 10), (114, 8), (166, 10), (10, 10), (44, 10), (145, 10), (66, 6), + (21, 6), (24, 8), (146, 9), (26, 9), (65, 7), (5, 7), (226, 11), (225, 12), + (15, 12), (180, 10), (147, 9), (115, 8), (40, 8), (89, 9), (134, 9), (84, 7), + (54, 7), (42, 9), (60, 10), (31, 11), (193, 11), (181, 10), (76, 10), (148, 9), + (37, 6), (67, 6), (33, 6), (3, 6), (17, 6), (2, 6), (102, 8), (87, 8), + (116, 8), (56, 8), (50, 5), (20, 5), (120, 9), (58, 9), (29, 10), (194, 10), + (135, 9), (97, 8), (7, 8), (105, 9), (13, 11), (241, 12), (16, 12), (45, 10), + (149, 9), (74, 9), (98, 7), (23, 7), (85, 7), (70, 7), (195, 10), (161, 10), + (129, 9), (72, 8), (51, 5), (36, 5), (117, 8), (61, 10), (11, 10), (162, 9), + (1, 7), (4, 6), (49, 6), (68, 6), (9, 9), (27, 9), (130, 8), (39, 7), + (53, 6), (99, 7), (25, 8), (150, 9), (90, 9), (103, 8), (163, 9), (196, 10), + (210, 10), (136, 9), (121, 9), (41, 8), (131, 8), (43, 9), (164, 9), (118, 8), + (88, 8), (81, 7), (6, 7), (55, 7), (59, 9), (30, 10), (209, 11), (14, 11), + (151, 9), (106, 9), (82, 6), (22, 6), (100, 7), (132, 8), (57, 8), (18, 4), + (34, 4), +]; + +pub(super) const VEC1: [(u16, u8); 101] = [ + (7, 5), (32, 8), (59, 10), (60, 10), (83, 11), (82, 11), (62, 10), (33, 8), + (45, 9), (61, 10), (84, 11), (85, 11), (1, 6), (13, 5), (19, 6), (25, 7), + (34, 8), (46, 9), (47, 9), (14, 5), (6, 5), (64, 10), (87, 11), (86, 11), + (63, 10), (88, 11), (90, 11), (35, 8), (26, 7), (0, 7), (48, 9), (65, 10), + (66, 10), (36, 8), (15, 5), (20, 6), (91, 11), (89, 11), (67, 10), (49, 9), + (50, 9), (69, 10), (92, 11), (93, 11), (27, 7), (5, 5), (37, 8), (68, 10), + (71, 10), (51, 9), (52, 9), (70, 10), (94, 11), (96, 11), (38, 8), (21, 6), + (16, 5), (4, 5), (28, 7), (53, 9), (95, 11), (97, 11), (73, 10), (39, 8), + (29, 7), (72, 10), (98, 11), (99, 11), (54, 9), (40, 8), (22, 6), (30, 7), + (55, 9), (74, 10), (76, 10), (56, 9), (75, 10), (77, 10), (17, 5), (3, 5), + (23, 6), (41, 8), (57, 9), (78, 10), (79, 10), (31, 7), (10, 4), (9, 4), + (100, 5), (2, 5), (11, 4), (8, 4), (18, 5), (42, 8), (58, 9), (80, 10), + (81, 10), (43, 8), (44, 8), (24, 6), (12, 4), +]; + diff --git a/crates/leonida-game/Cargo.toml b/crates/leonida-game/Cargo.toml new file mode 100644 index 000000000..71a99756b --- /dev/null +++ b/crates/leonida-game/Cargo.toml @@ -0,0 +1,15 @@ +[package] +name = "leonida-game" +description = "Everything specific to the title: its containers, build identities, patches." +version.workspace = true +edition.workspace = true +rust-version.workspace = true +license.workspace = true +publish.workspace = true + +[dependencies] +memchr.workspace = true +zlib-rs.workspace = true + +[lints] +workspace = true diff --git a/crates/leonida-game/src/lib.rs b/crates/leonida-game/src/lib.rs new file mode 100644 index 000000000..affa682b4 --- /dev/null +++ b/crates/leonida-game/src/lib.rs @@ -0,0 +1,25 @@ +//! Everything specific to the title: its container formats, build +//! identities, and the hooks we place in its code (located by per-build +//! offsets or byte-pattern signatures). What may and may not be stored here +//! is defined in docs/asset-policy.md. + +pub mod sgd5; + +/// A specific build of the title executable we know how to run. +#[derive(Debug, Clone, Copy)] +pub struct KnownBuild { + /// Our own label, e.g. "1.0.0 retail". + pub label: &'static str, + /// BLAKE3 of the original executable, hex. + pub blake3: &'static str, +} + +/// Builds we support. Empty until the executable is available. +pub const KNOWN_BUILDS: &[KnownBuild] = &[]; + +/// Looks up a build by the BLAKE3 hash of its executable. +pub fn identify(blake3_hex: &str) -> Option<&'static KnownBuild> { + KNOWN_BUILDS + .iter() + .find(|b| b.blake3.eq_ignore_ascii_case(blake3_hex)) +} diff --git a/crates/leonida-game/src/sgd5.rs b/crates/leonida-game/src/sgd5.rs new file mode 100644 index 000000000..5605b5162 --- /dev/null +++ b/crates/leonida-game/src/sgd5.rs @@ -0,0 +1,218 @@ +//! `SGD5`: the engine's shader file. Each record holds one shader container, +//! deflate-packed. The header tables are not decoded yet, so records are +//! found by their marker and cross-checked by their sizes: +//! +//! ```text +//! u8 name length (with NUL), name, NUL, u8 kind, +//! u32 n, u32 0x000DDCE7, u32 n, u32 unpacked size, raw deflate (n - 12 bytes) +//! ``` + +pub const MAGIC: &[u8; 4] = b"SGD5"; +const MARKER: [u8; 4] = 0x000D_DCE7_u32.to_le_bytes(); +/// Containers are at most a few MiB; refuse to allocate for absurd sizes. +const MAX_UNPACKED: usize = 64 << 20; + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct Record<'a> { + /// Offset of the marker in the file. + pub offset: usize, + /// Like `PS___Wrapped`; `None` if the bytes before the + /// record do not read as one. + pub name: Option<&'a str>, + /// Record type, meaning unknown (0x32 most shaders, 0x41 mesh shaders + /// and some material families, 0x3c compute, 0x40, 0x42). + pub kind: u8, + packed: &'a [u8], + unpacked_size: usize, +} + +impl Record<'_> { + /// The container, or `None` if the stream is corrupt. + pub fn unpack(&self) -> Option> { + let mut state = zlib_rs::Inflate::new(false, 15); + let mut out = Vec::new(); + let (mut in_pos, mut out_pos) = (0usize, 0usize); + loop { + if out_pos == self.unpacked_size { + let mut extra = [0u8; 1]; + let status = state + .decompress( + &self.packed[in_pos..], + &mut extra, + zlib_rs::InflateFlush::NoFlush, + ) + .ok()?; + return (status == zlib_rs::Status::StreamEnd + && state.total_out() as usize == self.unpacked_size) + .then_some(out); + } + if out_pos == out.len() { + let next_len = if out.is_empty() { + self.unpacked_size + .min(self.packed.len().saturating_mul(4).max(4096)) + } else { + out.len().saturating_mul(2).min(self.unpacked_size) + }; + out.resize(next_len, 0); + } + let status = state + .decompress( + &self.packed[in_pos..], + &mut out[out_pos..], + zlib_rs::InflateFlush::NoFlush, + ) + .ok()?; + let next_in = state.total_in() as usize; + let next_out = state.total_out() as usize; + match status { + zlib_rs::Status::StreamEnd => { + out.truncate(next_out); + return (next_out == self.unpacked_size).then_some(out); + } + zlib_rs::Status::Ok if next_in != in_pos || next_out != out_pos => { + in_pos = next_in; + out_pos = next_out; + } + zlib_rs::Status::Ok | zlib_rs::Status::BufError => return None, + } + } + } +} + +/// An SGD5 file, or a file holding one (an archive: records are found by +/// their marker, so no index is needed). +pub fn is_sgd5(file: &[u8]) -> bool { + memchr::memmem::find(file, MAGIC).is_some() +} + +/// Every record in an SGD5 file, in file order. +pub fn records(file: &[u8]) -> impl Iterator> { + memchr::memmem::find_iter(file, &MARKER).filter_map(|at| record(file, at)) +} + +fn record(file: &[u8], at: usize) -> Option> { + let u32_at = |o: usize| { + file.get(o..o + 4) + .map(|b| u32::from_le_bytes(b.try_into().expect("4 bytes")) as usize) + }; + let n = u32_at(at.checked_sub(4)?)?; + let unpacked_size = u32_at(at + 8)?; + if u32_at(at + 4)? != n || n < 12 || unpacked_size > MAX_UNPACKED { + return None; + } + let nul = at.checked_sub(6)?; + Some(Record { + offset: at, + name: (file[nul] == 0).then(|| name_before(file, nul)).flatten(), + kind: file[at - 5], + packed: file.get(at + 12..at + n)?, + unpacked_size, + }) +} + +/// The printable name that ends at `nul` and follows its length byte. +fn name_before(file: &[u8], nul: usize) -> Option<&str> { + let run = file[..nul] + .iter() + .rposition(|b| !b.is_ascii_graphic()) + .map_or(0, |p| p + 1); + // From 32 characters on, the length byte is printable too. + (run.saturating_sub(1)..nul) + .find(|&l| usize::from(file[l]) == nul - l) + .and_then(|l| std::str::from_utf8(&file[l + 1..nul]).ok()) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn record_bytes(name: &str, kind: u8, payload: &[u8]) -> Vec { + let mut buf = vec![0u8; zlib_rs::compress_bound(payload.len())]; + let config = zlib_rs::DeflateConfig { + window_bits: -15, + ..zlib_rs::DeflateConfig::new(6) + }; + let (packed, rc) = zlib_rs::compress_slice(&mut buf, payload, config); + assert_eq!(rc, zlib_rs::ReturnCode::Ok); + let n = (packed.len() + 12) as u32; + let mut out = vec![0xF4, 0x01, 0, 0, name.len() as u8 + 1]; + out.extend_from_slice(name.as_bytes()); + out.extend_from_slice(&[0, kind]); + for v in [n, 0x000D_DCE7, n, payload.len() as u32] { + out.extend_from_slice(&v.to_le_bytes()); + } + out.extend_from_slice(packed); + out + } + + #[test] + fn reads_records() { + let long = format!("PS_{}_Wrapped", "x".repeat(40)); + let mut file = MAGIC.to_vec(); + file.extend_from_slice(&[1, 2, 3, 4]); + file.extend(record_bytes( + "VS_Blit_0011aabb_Wrapped", + 0x32, + b"first container", + )); + // A marker whose sizes disagree is not a record. + file.extend_from_slice(&[9, 0, 0, 0, 0xE7, 0xDC, 0x0D, 0, 8, 0, 0, 0]); + file.extend(record_bytes(&long, 0x41, &[7; 300])); + + assert!(is_sgd5(&file)); + let found: Vec<_> = records(&file).collect(); + assert_eq!(found.len(), 2); + assert_eq!(found[0].name, Some("VS_Blit_0011aabb_Wrapped")); + assert_eq!(found[0].kind, 0x32); + assert_eq!(found[0].unpack().as_deref(), Some(&b"first container"[..])); + assert_eq!(found[1].name, Some(long.as_str())); + assert_eq!(found[1].unpack(), Some(vec![7; 300])); + + // The same file inside an archive. + let mut archive = vec![0x5A; 0x1000]; + archive.extend_from_slice(&file); + assert!(is_sgd5(&archive)); + assert_eq!(records(&archive).count(), 2); + assert!(!is_sgd5(&archive[..0x1000])); + } + + #[test] + fn corrupt_stream_does_not_unpack() { + let mut file = record_bytes("CS_x", 0x3c, &[1; 64]); + file[27] = 0xFF; // first packed byte: reserved block type + let r = records(&file).next().unwrap(); + assert_eq!(r.unpack(), None); + } + + #[test] + fn handles_empty_and_rejects_mismatched_or_truncated_streams() { + let empty = record_bytes("CS_empty", 0x3c, &[]); + assert_eq!(records(&empty).next().unwrap().unpack(), Some(Vec::new())); + + let payload: Vec = (0..16_384u32) + .map(|i| (i.wrapping_mul(31) ^ (i >> 5)) as u8) + .collect(); + let good = record_bytes("PS_big", 0x32, &payload); + let r = records(&good).next().unwrap(); + assert_eq!(r.unpack(), Some(payload.clone())); + + // Oversized stream (declared unpacked_size smaller than actual output). + let mut smaller = good.clone(); + smaller[r.offset + 8..r.offset + 12] + .copy_from_slice(&((payload.len() - 1) as u32).to_le_bytes()); + assert_eq!(records(&smaller).next().unwrap().unpack(), None); + + // Under-filled stream (declared unpacked_size larger than actual output). + let mut larger = good.clone(); + larger[r.offset + 8..r.offset + 12] + .copy_from_slice(&((payload.len() + 1) as u32).to_le_bytes()); + assert_eq!(records(&larger).next().unwrap().unpack(), None); + + // Truncated raw deflate stream. + let mut truncated = good[..good.len() - 1].to_vec(); + let new_n = (truncated.len() - r.offset) as u32; + truncated[r.offset - 4..r.offset].copy_from_slice(&new_n.to_le_bytes()); + truncated[r.offset + 4..r.offset + 8].copy_from_slice(&new_n.to_le_bytes()); + assert_eq!(records(&truncated).next().unwrap().unpack(), None); + } +} diff --git a/crates/leonida-gpu/Cargo.toml b/crates/leonida-gpu/Cargo.toml new file mode 100644 index 000000000..5daa817c2 --- /dev/null +++ b/crates/leonida-gpu/Cargo.toml @@ -0,0 +1,42 @@ +[package] +name = "leonida-gpu" +description = "D3D12.X command streams and GPU memory, translated onto host D3D12." +version.workspace = true +edition.workspace = true +rust-version.workspace = true +license.workspace = true +publish.workspace = true + +[dependencies] +blake3.workspace = true +zlib-rs.workspace = true +tracing.workspace = true +anyhow.workspace = true +leonida-formats.workspace = true +leonida-pipeline.workspace = true +leonida-shader.workspace = true + +[dev-dependencies] +tempfile.workspace = true + +[features] +# Debugging switches (frame capture, the host debug layer, per-draw data). +diagnostics = [] + +[lints] +workspace = true + +[target.'cfg(windows)'.dependencies] +windows-sys = { workspace = true, features = ["Win32_Foundation", "Win32_Security", "Win32_System_Diagnostics_Debug", "Win32_System_Diagnostics_ToolHelp", "Win32_System_EventLog", "Win32_System_Kernel", "Win32_System_LibraryLoader", "Win32_System_Memory", "Win32_System_Performance", "Win32_System_ProcessStatus", "Win32_System_SystemInformation", "Win32_System_Threading"] } +windows = { workspace = true, features = [ + "Win32_Graphics_Direct3D", + "Win32_Graphics_Direct3D_Fxc", + "Win32_Graphics_Direct3D12", + "Win32_Graphics_Dxgi", + "Win32_Graphics_Dxgi_Common", + "Win32_Graphics_Gdi", + "Win32_Security", + "Win32_System_LibraryLoader", + "Win32_System_Threading", + "Win32_UI_WindowsAndMessaging", +] } diff --git a/crates/leonida-gpu/src/capture.rs b/crates/leonida-gpu/src/capture.rs new file mode 100644 index 000000000..cf5dc2472 --- /dev/null +++ b/crates/leonida-gpu/src/capture.rs @@ -0,0 +1,863 @@ +//! Presented frames written to PNG files, to see what reaches the screen: +//! with `LEONIDA_CAPTURE=`, every frame whose number is a power of +//! two (the frames the log reports) is saved as `frame-.png`, at half +//! size. Only in builds with diagnostics. + +use std::path::PathBuf; + +use windows::Win32::Graphics::Direct3D12::*; +use windows::Win32::Graphics::Dxgi::Common::*; + +/// The folder frames go to, if capturing. +pub(crate) fn folder() -> Option<&'static PathBuf> { + static FOLDER: std::sync::OnceLock> = std::sync::OnceLock::new(); + FOLDER + .get_or_init(|| std::env::var_os("LEONIDA_CAPTURE").map(PathBuf::from)) + .as_ref() +} + +/// Frames listed in `LEONIDA_CAPTURE_FRAMES` (comma-separated): saved +/// too, and their draws traced at debug level. +pub(crate) fn listed(n: u64) -> bool { + static LIST: std::sync::OnceLock> = std::sync::OnceLock::new(); + let named = LIST + .get_or_init(|| { + let list = std::env::var("LEONIDA_CAPTURE_FRAMES").unwrap_or_default(); + list.split(',') + .filter_map(|f| f.trim().parse().ok()) + .collect() + }) + .contains(&n); + // `LEONIDA_CAPTURE_WORLD`: also the 2nd and the 6th frame after the first + // one that ran 500 draws or more (a title's first 3D frames: their + // numbers depend on how long the menus were shown), and the 30th and + // the 80th (the title opens with a cutscene made in the + // engine: later shots of it, in case the first is dark by design). + // + // `LEONIDA_CAPTURE_WORLD_ALSO` (comma-separated): more frames counted + // from that first one (the title's blue patches show from + // about the 118th frame on, when the window's model has arrived and + // the reflections hold values: none of the four above has them). + static ALSO: std::sync::OnceLock> = std::sync::OnceLock::new(); + let also = ALSO.get_or_init(|| { + let list = std::env::var("LEONIDA_CAPTURE_WORLD_ALSO").unwrap_or_default(); + list.split(',') + .filter_map(|f| f.trim().parse().ok()) + .collect() + }); + let first = WORLD.load(std::sync::atomic::Ordering::Relaxed); + let after = n.wrapping_sub(first); + named || first != u64::MAX && ([2, 6, 30, 80].contains(&after) || also.contains(&after)) +} + +/// With a capture folder, for the frames [`listed`]: `what` is added to +/// the frame's `frame--ops.txt`, one line per draw, dispatch, copy or +/// drop in the order recorded (the title records on several threads, so +/// lines of different lists interleave; each names its list). The file +/// says which pass writes which target, to find the pass whose output +/// stays empty. +#[cfg(feature = "diagnostics")] +pub(crate) fn op(list: usize, what: impl FnOnce() -> String) { + use std::io::Write; + let frame = crate::queue::presented() + 1; + if !listed(frame) { + // Before the world: the last lines are kept, and written out when + // it starts (`before-world-ops.txt`): what the title drew just + // before (the title shows a title card there, whose text + // did not show). + if world_on() && WORLD.load(std::sync::atomic::Ordering::Relaxed) == u64::MAX { + // At most 300 lines of a frame: the world's first frame alone + // (thousands of operations, recorded before it is known to be + // the world's) pushed everything before it out. + static IN_FRAME: std::sync::Mutex<(u64, u32)> = std::sync::Mutex::new((0, 0)); + { + let mut in_frame = IN_FRAME.lock().unwrap_or_else(|e| e.into_inner()); + if in_frame.0 != frame { + *in_frame = (frame, 0); + } + in_frame.1 += 1; + if in_frame.1 > 300 { + return; + } + } + let what = what(); + let mut ring = RING.lock().unwrap_or_else(|e| e.into_inner()); + if ring.len() >= RING_LINES { + ring.pop_front(); + } + ring.push_back(format!("frame {frame} list {list:#x} {what}")); + } + return; + } + let Some(folder) = folder() else { + return; + }; + static FILE: std::sync::Mutex> = std::sync::Mutex::new(None); + let what = what(); + let mut file = FILE.lock().unwrap_or_else(|e| e.into_inner()); + if file.as_ref().is_none_or(|f| f.0 != frame) { + let Ok(made) = std::fs::File::create(folder.join(format!("frame-{frame}-ops.txt"))) else { + return; + }; + *file = Some((frame, 0, made)); + } + if let Some((_, n, f)) = file.as_mut() { + *n += 1; + let _ = writeln!(f, "{n} list {list:#x} {what}"); + } +} + +/// The last lines of [`op`] before the world. +#[cfg(feature = "diagnostics")] +static RING: std::sync::Mutex> = + std::sync::Mutex::new(std::collections::VecDeque::new()); +#[cfg(feature = "diagnostics")] +const RING_LINES: usize = 6000; + +/// Whether `LEONIDA_CAPTURE_WORLD` is set. +fn world_on() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("LEONIDA_CAPTURE_WORLD").is_some()) +} + +/// Every how many world frames a picture is saved with +/// `LEONIDA_CAPTURE_WORLD` (`LEONIDA_CAPTURE_WORLD_EVERY`, 8 unless said). +/// +/// A saved frame is read back at once and written as a PNG inside the +/// present: run 225's frame log has every saved frame of the cell at 371 ms +/// against a usual 136 (the present's own copy and show 137 ms instead of +/// 2, and 123 ms more waiting for the card). At every 8th frame that was +/// the regular dip of every test run, and a fifth of its time. A run that +/// measures speed asks for 64 or more. +fn world_every() -> u64 { + static EVERY: std::sync::OnceLock = std::sync::OnceLock::new(); + *EVERY.get_or_init(|| { + std::env::var("LEONIDA_CAPTURE_WORLD_EVERY").ok().and_then(|v| v.trim().parse().ok()).filter(|&n| n > 0).unwrap_or(8) + }) +} + +/// The first frame that ran 500 draws or more (`LEONIDA_CAPTURE_WORLD`). +static WORLD: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(u64::MAX); + +/// At the present of `frame`: the draws run on the host so far. +pub(crate) fn frame_drew(frame: u64, drawn: u64) { + use std::sync::atomic::Ordering::Relaxed; + static LAST: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + let before = LAST.swap(drawn, Relaxed); + if world_on() + && drawn.saturating_sub(before) >= 500 + && WORLD.compare_exchange(u64::MAX, frame, Relaxed, Relaxed).is_ok() + { + tracing::info!(frame, "the first frame of 500 draws or more: frames {} and {} are captured", frame + 2, frame + 6); + #[cfg(feature = "diagnostics")] + if let Some(folder) = folder() { + let lines: Vec = std::mem::take(&mut *RING.lock().unwrap_or_else(|e| e.into_inner())).into(); + let _ = std::fs::write(folder.join("before-world-ops.txt"), lines.join(" +")); + } + } +} + +/// Whether frame `n` is saved. +pub(crate) fn wanted(n: u64) -> bool { + // Before the world, with `LEONIDA_CAPTURE_WORLD`: every 16th frame too + // (small pictures of menus, loading screens and title cards). + let before_world = world_on() && n.is_multiple_of(16) && WORLD.load(std::sync::atomic::Ordering::Relaxed) == u64::MAX; + // In the world: every 8th frame's picture, a timeline of the opening + // cutscene (its shots do not fall on the same frame numbers from run to + // run, so single frames cannot be compared between runs). + let first = WORLD.load(std::sync::atomic::Ordering::Relaxed); + let in_world = world_on() && first != u64::MAX && n > first && (n - first).is_multiple_of(world_every()); + folder().is_some() && (n.is_power_of_two() || listed(n) || before_world || in_world) +} + +/// Saves 8-bit RGBA or BGRA rows (`pitch` bytes apart) as frame `n`. +pub(crate) fn save(n: u64, width: u32, height: u32, pitch: usize, bgra: bool, rows: &[u8]) { + save_as(&format!("frame-{n}"), width, height, pitch, bgra, rows); +} + +/// Saves 8-bit RGBA or BGRA rows as `.png`, at half size. +fn save_as(name: &str, width: u32, height: u32, pitch: usize, bgra: bool, rows: &[u8]) { + let Some(folder) = folder() else { return }; + let (w, h) = ((width / 2).max(1), (height / 2).max(1)); + // Filter byte 0 per row, then RGB of every other pixel of every other row. + let mut raw = Vec::with_capacity((w as usize * 3 + 1) * h as usize); + for y in 0..h as usize { + raw.push(0); + let row = &rows[(2 * y).min(height as usize - 1) * pitch..]; + for x in 0..w as usize { + let p = &row[(2 * x).min(width as usize - 1) * 4..][..3]; + if bgra { + raw.extend([p[2], p[1], p[0]]); + } else { + raw.extend_from_slice(p); + } + } + } + let mut png = b"\x89PNG\r\n\x1a\n".to_vec(); + let mut header = Vec::new(); + header.extend(w.to_be_bytes()); + header.extend(h.to_be_bytes()); + header.extend([8, 2, 0, 0, 0]); // 8-bit RGB + chunk(&mut png, b"IHDR", &header); + let mut compressed = vec![0u8; zlib_rs::compress_bound(raw.len())]; + let (idat, rc) = zlib_rs::compress_slice(&mut compressed, &raw, zlib_rs::DeflateConfig::new(3)); + debug_assert_eq!(rc, zlib_rs::ReturnCode::Ok); + chunk(&mut png, b"IDAT", idat); + chunk(&mut png, b"IEND", &[]); + let path = folder.join(format!("{name}.png")); + match std::fs::write(&path, png) { + Ok(()) => tracing::info!(path = %path.display(), "frame saved"), + Err(e) => tracing::warn!(error = %e, path = %path.display(), "frame not saved"), + } +} + +fn chunk(png: &mut Vec, kind: &[u8; 4], data: &[u8]) { + png.extend((data.len() as u32).to_be_bytes()); + let start = png.len(); + png.extend(kind); + png.extend(data); + let crc = crc32(&png[start..]); + png.extend(crc.to_be_bytes()); +} + +fn crc32(bytes: &[u8]) -> u32 { + let mut crc = !0u32; + for &b in bytes { + crc ^= u32::from(b); + for _ in 0..8 { + crc = (crc >> 1) ^ (0xedb8_8320 & (crc & 1).wrapping_neg()); + } + } + !crc +} + +/// Records a copy of `texture` (in the copy-source state) into a +/// readback buffer. +pub(crate) fn read_back( + device: &ID3D12Device, + list: &ID3D12GraphicsCommandList, + texture: &ID3D12Resource, +) -> Option<(ID3D12Resource, D3D12_PLACED_SUBRESOURCE_FOOTPRINT)> { + read_back_of(device, list, texture, 0) +} + +/// As [`read_back`], of subresource `sub` (the stencil plane of a +/// one-level, one-slice depth-stencil texture is subresource 1). +fn read_back_of( + device: &ID3D12Device, + list: &ID3D12GraphicsCommandList, + texture: &ID3D12Resource, + sub: u32, +) -> Option<(ID3D12Resource, D3D12_PLACED_SUBRESOURCE_FOOTPRINT)> { + let mut footprint = D3D12_PLACED_SUBRESOURCE_FOOTPRINT::default(); + let mut total = 0; + // SAFETY: a live texture; outputs for one subresource. + unsafe { + let desc = texture.GetDesc(); + device.GetCopyableFootprints( + &desc, + sub, + 1, + 0, + Some(&mut footprint), + None, + None, + Some(&mut total), + ); + } + let heap = D3D12_HEAP_PROPERTIES { + Type: D3D12_HEAP_TYPE_READBACK, + ..Default::default() + }; + let desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, + Width: total, + Height: 1, + DepthOrArraySize: 1, + MipLevels: 1, + SampleDesc: DXGI_SAMPLE_DESC { + Count: 1, + Quality: 0, + }, + Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, + ..Default::default() + }; + let mut buffer: Option = None; + // SAFETY: plain creation; an open list; locations naming live resources. + unsafe { + device + .CreateCommittedResource( + &heap, + D3D12_HEAP_FLAG_NONE, + &desc, + D3D12_RESOURCE_STATE_COPY_DEST, + None, + &mut buffer, + ) + .ok()?; + let buffer = buffer?; + let to = D3D12_TEXTURE_COPY_LOCATION { + pResource: std::mem::transmute_copy(&buffer), + Type: D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT, + Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { + PlacedFootprint: footprint, + }, + }; + let from = D3D12_TEXTURE_COPY_LOCATION { + pResource: std::mem::transmute_copy(texture), + Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, + Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { + SubresourceIndex: sub, + }, + }; + list.CopyTextureRegion(&to, 0, 0, 0, &from, None); + Some((buffer, footprint)) + } +} + +/// Saves a frame read back by [`read_back`] (8-bit color only). +pub(crate) fn save_read_back( + frame: u64, + buffer: &ID3D12Resource, + footprint: &D3D12_PLACED_SUBRESOURCE_FOOTPRINT, +) { + let f = footprint.Footprint; + let bgra = match f.Format { + DXGI_FORMAT_R8G8B8A8_UNORM | DXGI_FORMAT_R8G8B8A8_UNORM_SRGB => false, + DXGI_FORMAT_B8G8R8A8_UNORM | DXGI_FORMAT_B8G8R8A8_UNORM_SRGB => true, + other => { + tracing::warn!(format = other.0, "frame not saved: not 8-bit color"); + return; + } + }; + let mut data = std::ptr::null_mut(); + // SAFETY: the copy finished (every submission is waited for); the + // mapping spans the footprint's rows. + unsafe { + if buffer.Map(0, None, Some(&mut data)).is_err() { + return; + } + let len = f.RowPitch as usize * f.Height as usize; + let rows = std::slice::from_raw_parts(data.cast::(), len); + save(frame, f.Width, f.Height, f.RowPitch as usize, bgra, rows); + buffer.Unmap(0, None); + } +} + +/// With `LEONIDA_DUMP_TARGETS` set: title textures the frames listed in +/// `LEONIDA_CAPTURE_FRAMES` render to or write, in first-use order, saved +/// at that frame's present as `frame----x-f.png` +/// (what each holds at the end of the frame; formats normalized to show +/// structure: floats scaled by their largest value, depth by its range). +/// The host copies are held: the title may release a target before the +/// frame is presented. +static TARGETS: std::sync::Mutex)>> = + std::sync::Mutex::new(Vec::new()); + +fn dump_on() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| folder().is_some() && std::env::var_os("LEONIDA_DUMP_TARGETS").is_some()) +} + +/// Notes a title texture the frame being built renders to or writes. +pub(crate) fn note_target(resource: crate::object::This) { + if resource.is_null() || !dump_on() || !listed(crate::queue::presented() + 1) { + return; + } + let mut targets = TARGETS.lock().unwrap_or_else(|e| e.into_inner()); + if !targets.iter().any(|&(r, _)| r == resource as usize) + && let Some(copy) = crate::resource::host_copy(resource) + { + targets.push((resource as usize, copy)); + } +} + +/// At the present of frame `frame`: saves the noted targets. +pub(crate) fn dump_targets(frame: u64) { + use std::sync::atomic::Ordering::Relaxed; + let targets = std::mem::take(&mut *TARGETS.lock().unwrap_or_else(|e| e.into_inner())); + let Some(host) = crate::host::host() else { return }; + for (i, (resource, copy)) in targets.iter().enumerate() { + let texture = ©.texture; + // SAFETY: a live resource. + let d = unsafe { texture.GetDesc() }; + if d.SampleDesc.Count > 1 || d.Dimension != D3D12_RESOURCE_DIMENSION_TEXTURE2D { + continue; + } + // Every submission has run; the dump's list moves it there and back. + let state = copy.state.load(Relaxed); + dump_one(host, texture, state, frame, i, *resource as crate::object::This, &d); + } +} + +fn dump_one( + host: &crate::host::Host, + texture: &ID3D12Resource, + state: u32, + frame: u64, + i: usize, + resource: crate::object::This, + d: &D3D12_RESOURCE_DESC, +) { + let Ok(list) = host.new_list() else { return }; + let state = D3D12_RESOURCE_STATES(crate::host::legal_state(texture, state) as i32); + let copy = D3D12_RESOURCE_STATE_COPY_SOURCE; + // SAFETY: an open list of ours and a live texture. + let read = unsafe { + if state != copy { + list.list + .ResourceBarrier(&[crate::host::transition(texture, state, copy)]); + } + let read = read_back(&host.device, &list.list, texture); + // The stencil plane of a depth-stencil target, which the title's + // lighting reads (material class in the low bits; 0x08 "inside a + // room", which the lamps of a room are multiplied by): the plane + // after the depth plane of a one-level, one-slice texture. + let stencil = (matches!(d.Format.0, 19..=22 | 44..=47) + && d.MipLevels == 1 + && d.DepthOrArraySize == 1) + .then(|| read_back_of(&host.device, &list.list, texture, 1)) + .flatten(); + if state != copy { + list.list + .ResourceBarrier(&[crate::host::transition(texture, copy, state)]); + } + (read, stencil) + }; + let (read, stencil) = read; + list.close(); + host.execute(&[&list]); + if let Some((buffer, footprint)) = stencil { + stencil_values(&buffer, &footprint, frame, resource); + } + let Some((buffer, footprint)) = read else { return }; + let f = footprint.Footprint; + let mut data = std::ptr::null_mut(); + // SAFETY: the copy finished; the mapping spans the footprint's rows. + unsafe { + if buffer.Map(0, None, Some(&mut data)).is_err() { + return; + } + let pitch = f.RowPitch as usize; + let rows = std::slice::from_raw_parts(data.cast::(), pitch * f.Height as usize); + // A 24-bit depth plane comes back as 32-bit words: which depth values + // (low 24 bits) and which top bytes it holds, the most common first. + if matches!(d.Format.0, 44..=47) { + let mut depths = std::collections::HashMap::::new(); + let mut tops = std::collections::HashMap::::new(); + for y in 0..f.Height as usize { + for x in 0..f.Width as usize { + let at = y * pitch + x * 4; + let w = u32::from_le_bytes(rows[at..at + 4].try_into().unwrap_or([0; 4])); + *depths.entry(w & 0xff_ffff).or_default() += 1; + *tops.entry(w >> 24).or_default() += 1; + } + } + let most = |m: std::collections::HashMap| { + let mut v: Vec<(u32, u32)> = m.into_iter().collect(); + v.sort_by_key(|e| std::cmp::Reverse(e.1)); + (v.len(), v.into_iter().take(12).collect::>()) + }; + tracing::info!(?resource, depths = ?most(depths), top_bytes = ?most(tops), "24-bit depth plane values (value, texels)"); + } + if let Some(rgba) = to_rgba(f.Format.0 as u32, f.Width as usize, f.Height as usize, pitch, rows) { + let name = format!( + "frame-{frame}-{i:02}-{resource:?}-{}x{}-f{}", + d.Width, d.Height, d.Format.0 + ); + save_as(&name, f.Width, f.Height, f.Width as usize * 4, false, &rgba); + } else { + tracing::info!(format = f.Format.0, ?resource, "target not dumped: format"); + } + buffer.Unmap(0, None); + } +} + +/// Logs which values a stencil plane read back by [`read_back_of`] holds +/// (the most common first), how many texels have each of its bits, and the +/// box of the texels with bit 3 (0x08). +fn stencil_values( + buffer: &ID3D12Resource, + footprint: &D3D12_PLACED_SUBRESOURCE_FOOTPRINT, + frame: u64, + resource: crate::object::This, +) { + let f = footprint.Footprint; + let (w, h, pitch) = (f.Width as usize, f.Height as usize, f.RowPitch as usize); + let mut data = std::ptr::null_mut(); + // SAFETY: the copy finished; the mapping spans the footprint's rows of + // one byte a texel, the last row without its padding. + unsafe { + if h == 0 || w == 0 || buffer.Map(0, None, Some(&mut data)).is_err() { + return; + } + let rows = std::slice::from_raw_parts(data.cast::(), pitch * (h - 1) + w); + let mut values = [0u32; 256]; + let mut bits = [0u32; 8]; + // Left, top, right, bottom of the texels with bit 3. + let mut inside = [u32::MAX, u32::MAX, 0, 0]; + for y in 0..h { + for (x, &v) in rows[y * pitch..y * pitch + w].iter().enumerate() { + values[usize::from(v)] += 1; + for (bit, count) in bits.iter_mut().enumerate() { + *count += u32::from(v >> bit & 1); + } + if v & 8 != 0 { + inside = [ + inside[0].min(x as u32), + inside[1].min(y as u32), + inside[2].max(x as u32), + inside[3].max(y as u32), + ]; + } + } + } + let mut most: Vec<(usize, u32)> = values + .iter() + .copied() + .enumerate() + .filter(|v| v.1 != 0) + .collect(); + most.sort_by_key(|v| std::cmp::Reverse(v.1)); + most.truncate(16); + tracing::info!( + frame, + ?resource, + width = w, + height = h, + values = ?most, + texels_with_bit = ?bits, + bit3_box = ?inside, + "stencil plane values (value, texels)" + ); + buffer.Unmap(0, None); + } +} + +fn half(h: u16) -> f32 { + let (sign, exp, man) = ((h >> 15) as u32, ((h >> 10) & 0x1f) as i32, (h & 0x3ff) as f32); + let v = match exp { + 0 => man * 2f32.powi(-24), + 31 => f32::INFINITY, + e => (1.0 + man / 1024.0) * 2f32.powi(e - 15), + }; + if sign == 1 { -v } else { v } +} + +/// A float packed in `bits` with a 5-bit exponent and `man` mantissa bits +/// (the 11- and 10-bit floats of R11G11B10). +fn small_float(bits: u32, man: u32) -> f32 { + let (exp, m) = ((bits >> man) & 0x1f, (bits & ((1 << man) - 1)) as f32); + match exp { + 0 => m / (1 << man) as f32 * 2f32.powi(-14), + 31 => f32::INFINITY, + e => (1.0 + m / (1 << man) as f32) * 2f32.powi(e as i32 - 15), + } +} + +/// Rows of a host format as 8-bit RGBA: 8-bit color as is, everything else +/// as channel values scaled so the largest finite one is white (single +/// channels: lowest black, highest white, as grey). `None` for formats not +/// handled. +fn to_rgba(format: u32, w: usize, h: usize, pitch: usize, rows: &[u8]) -> Option> { + let mut out = Vec::with_capacity(w * h * 4); + let px = |x: usize, y: usize, n: usize| &rows[y * pitch + x * n..][..n]; + let u16_at = |b: &[u8], i: usize| u16::from_le_bytes([b[2 * i], b[2 * i + 1]]); + let u32_at = |b: &[u8], i: usize| u32::from_le_bytes(b[4 * i..4 * i + 4].try_into().unwrap_or([0; 4])); + // Channel values as floats, then scaled. + type Decode = Box [f32; 3]>; + let (n, decode): (usize, Decode) = match format { + 27..=32 => { + for y in 0..h { + for x in 0..w { + let p = px(x, y, 4); + out.extend([p[0], p[1], p[2], 255]); + } + } + return Some(out); + } + // B8G8R8A8 and B8G8R8X8 (89 is R10G10B10_XR_BIAS_A2, below). + 87 | 88 | 90..=93 => { + for y in 0..h { + for x in 0..w { + let p = px(x, y, 4); + out.extend([p[2], p[1], p[0], 255]); + } + } + return Some(out); + } + 23..=25 | 89 => (4, Box::new(move |b| { + let v = u32_at(b, 0); + [(v & 0x3ff) as f32, (v >> 10 & 0x3ff) as f32, (v >> 20 & 0x3ff) as f32] + })), + 26 => (4, Box::new(move |b| { + let v = u32_at(b, 0); + [small_float(v & 0x7ff, 6), small_float(v >> 11 & 0x7ff, 6), small_float(v >> 22, 5)] + })), + 9..=10 => (8, Box::new(move |b| [half(u16_at(b, 0)), half(u16_at(b, 1)), half(u16_at(b, 2))])), + 11..=14 => (8, Box::new(move |b| [0, 1, 2].map(|i| f32::from(u16_at(b, i))))), + 33..=34 => (4, Box::new(move |b| [half(u16_at(b, 0)), half(u16_at(b, 1)), 0.0])), + 1..=2 => (16, Box::new(move |b| { + [0, 1, 2].map(|i| f32::from_bits(u32_at(b, i))) + })), + 15..=16 => (8, Box::new(move |b| [f32::from_bits(u32_at(b, 0)), f32::from_bits(u32_at(b, 1)), 0.0])), + 35..=38 => (4, Box::new(move |b| [f32::from(u16_at(b, 0)), f32::from(u16_at(b, 1)), 0.0])), + 48..=52 => (2, Box::new(move |b| [f32::from(b[0]), f32::from(b[1]), 0.0])), + // Single channels (and depth planes): shown as grey. + 39..=43 => (4, Box::new(move |b| [f32::from_bits(u32_at(b, 0)); 3])), + 19..=22 => (8, Box::new(move |b| [f32::from_bits(u32_at(b, 0)); 3])), + 44..=47 => (4, Box::new(move |b| [(u32_at(b, 0) & 0xff_ffff) as f32; 3])), + 53..=54 => (2, Box::new(move |b| [half(u16_at(b, 0)); 3])), + 55..=59 => (2, Box::new(move |b| [f32::from(u16_at(b, 0)); 3])), + 60..=65 => (1, Box::new(move |b| [f32::from(b[0]); 3])), + _ => return None, + }; + let values: Vec<[f32; 3]> = (0..h) + .flat_map(|y| (0..w).map(move |x| (x, y))) + .map(|(x, y)| decode(px(x, y, n))) + .collect(); + let grey = matches!(format, 19..=22 | 39..=47 | 53..=65); + let finite = values.iter().flatten().copied().filter(|v| v.is_finite()); + let (low, high) = if grey { + finite.fold((f32::MAX, f32::MIN), |(l, h), v| (l.min(v), h.max(v))) + } else { + (0.0, finite.fold(0.0f32, f32::max)) + }; + let range = (high - low).max(1e-20); + // How much of the target holds anything: a lit scene and one bright + // lamp on black have the same highest value. + let above = values.iter().filter(|v| v.iter().any(|c| c.is_finite() && *c > low)).count(); + let nonzero_percent = above as f32 * 100.0 / values.len().max(1) as f32; + tracing::info!(format, low, high, nonzero_percent, "target values"); + // Small float colour targets (the 1x1 luminance and exposure targets): + // every texel's four channels as numbers. The picture has no alpha and + // eight bits a channel. + if matches!(format, 1..=2 | 9..=10) && w * h <= 16 { + for y in 0..h { + for x in 0..w { + let b = px(x, y, n); + let texel: [f32; 4] = if n == 16 { + [0, 1, 2, 3].map(|i| f32::from_bits(u32_at(b, i))) + } else { + [0, 1, 2, 3].map(|i| half(u16_at(b, i))) + }; + tracing::info!(format, x, y, ?texel, "target texel"); + } + } + } + // R32_UINT targets hold packed light (the title reads them back as + // R9G9B9E5): as floats their low, high and share above the lowest say + // nothing. How many texels hold any bit, and the highest channel value + // of the packed reading. + if format == 42 { + let (mut set, mut packed_high) = (0usize, 0f32); + for y in 0..h { + for x in 0..w { + let v = u32_at(px(x, y, 4), 0); + set += usize::from(v != 0); + let scale = 2f32.powi((v >> 27) as i32 - 24); + for k in 0..3 { + packed_high = packed_high.max((v >> (9 * k) & 0x1ff) as f32 * scale); + } + } + } + let nonzero_bits_percent = set as f32 * 100.0 / (w * h).max(1) as f32; + tracing::info!(format, nonzero_bits_percent, packed_high, "target values as packed light"); + // The same words as plain numbers, by class. Tables of indices and + // masks say nothing as floats or as packed light: in the title's + // shadow-mask table 0 is a block in full shadow, a word up to 255 + // one value for the block, above that a block of the atlas, and all + // ones a texel never written. + let mut classes = [0usize; 6]; + let mut highest_below_ones = 0u32; + for y in 0..h { + for x in 0..w { + let v = u32_at(px(x, y, 4), 0); + classes[match v { + 0 => 0, + 1..=15 => 1, + 16..=255 => 2, + 256..=0x00ff_ffff => 3, + u32::MAX => 5, + _ => 4, + }] += 1; + if v != u32::MAX { + highest_below_ones = highest_below_ones.max(v); + } + } + } + tracing::info!( + format, + width = w, + height = h, + zero = classes[0], + one_to_15 = classes[1], + to_255 = classes[2], + to_24_bits = classes[3], + larger = classes[4], + all_ones = classes[5], + highest_below_ones, + "target values as words" + ); + } + // Float colours (scene light) go through a cube root: scaled linearly, + // a night scene under one lamp of 50 units came out all black. + let curved = matches!(format, 1..=2 | 9..=10 | 26); + for v in values { + let c = v.map(|c| { + let t = ((c - low) / range).clamp(0.0, 1.0); + ((if curved { t.cbrt() } else { t }) * 255.0) as u8 + }); + out.extend([c[0], c[1], c[2], 255]); + } + Some(out) +} + +/// Pixels per side of the grid [`probe`] reads. +const GRID: u32 = 4; +/// Bytes between the grid's pixels in the readback buffer (placement +/// alignment). +const SLOT: u64 = 512; + +/// Records copies of a grid of pixels of `texture` (8-bit color, in the +/// copy-source state) into a readback buffer, to tell black frames. +pub(crate) fn probe( + device: &ID3D12Device, + list: &ID3D12GraphicsCommandList, + texture: &ID3D12Resource, +) -> Option { + // SAFETY: a live resource. + let d = unsafe { texture.GetDesc() }; + if !matches!(d.Format.0, 27..=29 | 87 | 90 | 91) { + return None; + } + let desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, + Width: SLOT * u64::from(GRID * GRID), + Height: 1, + DepthOrArraySize: 1, + MipLevels: 1, + SampleDesc: DXGI_SAMPLE_DESC { + Count: 1, + Quality: 0, + }, + Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, + ..Default::default() + }; + let heap = D3D12_HEAP_PROPERTIES { + Type: D3D12_HEAP_TYPE_READBACK, + ..Default::default() + }; + let mut buffer: Option = None; + // SAFETY: plain creation; an open list; locations naming live resources. + unsafe { + device + .CreateCommittedResource( + &heap, + D3D12_HEAP_FLAG_NONE, + &desc, + D3D12_RESOURCE_STATE_COPY_DEST, + None, + &mut buffer, + ) + .ok()?; + let buffer = buffer?; + for i in 0..GRID * GRID { + let (x, y) = ( + (2 * (i % GRID) + 1) * d.Width as u32 / (2 * GRID), + (2 * (i / GRID) + 1) * d.Height / (2 * GRID), + ); + let to = D3D12_TEXTURE_COPY_LOCATION { + pResource: std::mem::transmute_copy(&buffer), + Type: D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT, + Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { + PlacedFootprint: D3D12_PLACED_SUBRESOURCE_FOOTPRINT { + Offset: SLOT * u64::from(i), + Footprint: D3D12_SUBRESOURCE_FOOTPRINT { + Format: d.Format, + Width: 1, + Height: 1, + Depth: 1, + RowPitch: 256, + }, + }, + }, + }; + let from = D3D12_TEXTURE_COPY_LOCATION { + pResource: std::mem::transmute_copy(texture), + Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, + Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { + SubresourceIndex: 0, + }, + }; + let pixel = D3D12_BOX { + left: x, + top: y, + front: 0, + right: x + 1, + bottom: y + 1, + back: 1, + }; + list.CopyTextureRegion(&to, 0, 0, 0, &from, Some(&pixel)); + } + Some(buffer) + } +} + +/// Whether every pixel [`probe`] read is (near) black. +pub(crate) fn black(buffer: &ID3D12Resource) -> bool { + let mut data = std::ptr::null_mut(); + // SAFETY: the copies finished (every submission is waited for). + unsafe { + if buffer.Map(0, None, Some(&mut data)).is_err() { + return false; + } + let bytes = + std::slice::from_raw_parts(data.cast::(), (SLOT * u64::from(GRID * GRID)) as usize); + let level = bytes + .chunks(SLOT as usize) + .flat_map(|pixel| pixel[..3].iter().copied()) + .max() + .unwrap_or(0); + buffer.Unmap(0, None); + let mut levels = LEVELS.lock().unwrap_or_else(|e| e.into_inner()); + if levels.len() == 12 { + levels.pop_front(); + } + levels.push_back(level); + level < 8 + } +} + +/// The brightest probed channel of the last frames, oldest first: a fade +/// darkens over several, a glitch drops at once. +static LEVELS: std::sync::Mutex> = + std::sync::Mutex::new(std::collections::VecDeque::new()); + +pub(crate) fn recent_levels() -> Vec { + let levels = LEVELS.lock().unwrap_or_else(|e| e.into_inner()); + levels.iter().copied().collect() +} + +#[cfg(test)] +mod tests { + #[test] + fn crc_matches_the_png_check_value() { + assert_eq!(super::crc32(b"IEND"), 0xae42_6082); + } + + /// R16G16B16A16_UNORM is integers, not half floats; 89 is 10:10:10:2, + /// not B8G8R8A8. + #[test] + fn unorm16_and_xr_bias_targets_decode_as_their_formats() { + // Red 0x8000 (a half-float -0), green 0x4000, blue 0. + let unorm16 = [0x00, 0x80, 0x00, 0x40, 0, 0, 0xff, 0xff]; + assert_eq!(super::to_rgba(11, 1, 1, 8, &unorm16), Some(vec![255, 127, 0, 255])); + // Red 0x3ff, green 0x1ff, blue 0, alpha 3. + let xr = (0x3ffu32 | 0x1ff << 10 | 3 << 30).to_le_bytes(); + assert_eq!(super::to_rgba(89, 1, 1, 4, &xr), Some(vec![255, 127, 0, 255])); + // B8G8R8A8 still swaps to RGBA. + assert_eq!(super::to_rgba(87, 1, 1, 4, &[1, 2, 3, 4]), Some(vec![3, 2, 1, 255])); + } +} diff --git a/crates/leonida-gpu/src/cardmeter.rs b/crates/leonida-gpu/src/cardmeter.rs new file mode 100644 index 000000000..1b6aa6f95 --- /dev/null +++ b/crates/leonida-gpu/src/cardmeter.rs @@ -0,0 +1,383 @@ +//! What the card's time goes to, by kind of list, in every run. +//! +//! The card's clock (`crate::host`) says how long the card had work of +//! ours, not which work. The timing run (`LEONIDA_GPU_TIMING`) names every +//! title command but sends each list on its own, which changes the frame, +//! and it never timed the lists the layer adds for itself: the one that +//! brings copies in the card's memory up to date and hashes their pieces +//! again, and the one that compares pieces after a submission's lists. +//! Run 187's table left 64 ms a frame of card time unexplained beside +//! them (40 ms by the count outside timing runs); with draw windows off +//! the card is the frame's limit (run 225: 85 to 98 % busy), so that sum +//! decides what is worth changing. +//! +//! Here a list gets one timestamp where it begins and one where it ends, +//! both resolved into one read-back buffer by the list itself. The card +//! writes them when it gets there; a pair is read a second and a half +//! after it was recorded, when every flight of that time has long landed, +//! and its length goes to the frame log's totals by kind. So the frame +//! log's card columns are of the frames of a moment ago: right for the +//! usual frame, not for placing one long frame. +//! +//! On by default in diagnostics builds; `LEONIDA_CARD_METER=0` or `1` says +//! otherwise. Two queries and a resolve a list. + +use std::sync::Mutex; + +use windows::Win32::Graphics::Direct3D12::*; +use windows::Win32::Graphics::Dxgi::Common::DXGI_SAMPLE_DESC; + +/// What a timed list is. +#[derive(Clone, Copy)] +pub(crate) enum Kind { + /// Ours: changed bytes go up to copies in the card's memory and their + /// pieces are hashed again (`Host::card_before`). + Sync, + /// Ours: the compare of the pieces a submission's shaders may have + /// written, and the fetch of the flagged ones inside the flight. + Check, + /// Every other host list: the title's own, our present copies. + Lists, + /// Inside one of those: from where a pipeline is bound to where the + /// next one is, or the list ends ([`begin_named`]). + Pipeline, +} + +/// Pairs of timestamps in the ring. +const PAIRS: u32 = 32768; +/// A pair is read this long after it was recorded. +const AFTER: std::time::Duration = std::time::Duration::from_millis(1000); + +/// A pair being recorded: its place in the ring, or none. +#[derive(Clone, Copy)] +pub(crate) struct Span(u32); + +impl Span { + pub(crate) const NONE: Span = Span(u32::MAX); + /// For keeping in an atomic. + pub(crate) fn raw(self) -> u32 { + self.0 + } + pub(crate) fn from_raw(raw: u32) -> Span { + Span(raw) + } +} + +struct Meter { + heap: ID3D12QueryHeap, + back: ID3D12Resource, + /// The read-back buffer's bytes, mapped for good. + mapped: usize, + /// Ticks a second of the queue's clock. + frequency: u64, + next: u32, + /// Pairs recorded and not read yet: place, kind, when recorded. + pending: std::collections::VecDeque<(u32, Kind, std::time::Instant)>, + /// What the list of a pair mostly is ([`end_named`]), by place, until + /// the pair is read. + names: std::collections::HashMap, + /// Since the last table: by name, the lists and their microseconds. + by_name: std::collections::HashMap, + /// The same by pipeline ([`begin_named`]): the times it was bound and + /// the microseconds until the next one was. + by_pipeline: std::collections::HashMap, + /// Frames since the last table. + frames: u64, + /// What each place held when it was last read: a place the card has + /// not written since (its list never ran) still holds that, and is + /// not counted again. + seen: Vec<(u64, u64)>, +} + +// SAFETY: host objects (free-threaded) and a mapping only read, behind a lock. +unsafe impl Send for Meter {} + +static METER: Mutex>> = Mutex::new(None); + +/// Whether lists are timed. +pub(crate) fn on() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| match std::env::var_os("LEONIDA_CARD_METER") { + Some(v) => v != "0", + None => cfg!(feature = "diagnostics"), + }) +} + +fn make() -> Option { + let host = crate::host::host()?; + let device = host.device(); + let mut heap: Option = None; + let mut back: Option = None; + let readback = D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_READBACK, ..Default::default() }; + let desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, + Width: u64::from(PAIRS) * 16, + Height: 1, + DepthOrArraySize: 1, + MipLevels: 1, + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, + ..Default::default() + }; + // SAFETY: plain object creation; the buffer is mapped once and stays so. + unsafe { + device + .CreateQueryHeap( + &D3D12_QUERY_HEAP_DESC { Type: D3D12_QUERY_HEAP_TYPE_TIMESTAMP, Count: PAIRS * 2, NodeMask: 0 }, + &mut heap, + ) + .ok()?; + device + .CreateCommittedResource(&readback, D3D12_HEAP_FLAG_NONE, &desc, D3D12_RESOURCE_STATE_COPY_DEST, None, &mut back) + .ok()?; + let (heap, back) = (heap?, back?); + let mut mapped = std::ptr::null_mut(); + back.Map(0, None, Some(&mut mapped)).ok()?; + let frequency = host.timestamp_frequency(); + if mapped.is_null() || frequency == 0 { + return None; + } + tracing::info!( + "the card's time is measured by kind of list, a timestamp where each list begins and ends (LEONIDA_CARD_METER=0: not)" + ); + Some(Meter { + heap, + back, + mapped: mapped as usize, + frequency, + next: 0, + pending: Default::default(), + names: Default::default(), + by_name: Default::default(), + by_pipeline: Default::default(), + frames: 0, + seen: vec![(0, 0); PAIRS as usize], + }) + } +} + +/// A list of `kind` begins here: the first timestamp of a pair. +pub(crate) fn begin(list: &ID3D12GraphicsCommandList, kind: Kind) -> Span { + if !on() { + return Span::NONE; + } + let mut meter = METER.lock().unwrap_or_else(|e| e.into_inner()); + let Some(m) = meter.get_or_insert_with(make) else { + return Span::NONE; + }; + // The ring must not come round to pairs that were not read yet. + if m.pending.len() as u32 >= PAIRS - 64 { + return Span::NONE; + } + let pair = m.next; + m.next = (m.next + 1) % PAIRS; + m.pending.push_back((pair, kind, std::time::Instant::now())); + // SAFETY: an open list and our query heap. + unsafe { list.EndQuery(&m.heap, D3D12_QUERY_TYPE_TIMESTAMP, pair * 2) }; + Span(pair) +} + +/// The list ends here: the pair's second timestamp, and both go to the +/// read-back buffer when the card has run the list. +pub(crate) fn end(list: &ID3D12GraphicsCommandList, span: Span) { + if span.0 == u32::MAX { + return; + } + let meter = METER.lock().unwrap_or_else(|e| e.into_inner()); + let Some(Some(m)) = meter.as_ref() else { + return; + }; + // SAFETY: an open list, our heap and our read-back buffer, the pair's + // own sixteen bytes of it. + unsafe { + list.EndQuery(&m.heap, D3D12_QUERY_TYPE_TIMESTAMP, span.0 * 2 + 1); + list.ResolveQueryData(&m.heap, D3D12_QUERY_TYPE_TIMESTAMP, span.0 * 2, 2, &m.back, u64::from(span.0) * 16); + } +} + +/// Whether the card's time is also measured pipeline by pipeline inside the +/// title's lists (`LEONIDA_CARD_METER_PIPELINES=1`; off by default: two +/// more queries and a resolve at every change of pipeline). +pub(crate) fn pipelines() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| on() && std::env::var_os("LEONIDA_CARD_METER_PIPELINES").is_some_and(|v| v == "1")) +} + +/// The pipeline `name` is bound on `list` here: the first timestamp of a +/// pair that [`end`] closes where the next pipeline is bound or the list +/// ends. What the card does between the two (the draws or dispatches of +/// that pipeline, and what the layer records around them) is that +/// pipeline's time in the table. +pub(crate) fn begin_named(list: &ID3D12GraphicsCommandList, name: &str) -> Span { + let span = begin(list, Kind::Pipeline); + if span.0 != u32::MAX { + let mut meter = METER.lock().unwrap_or_else(|e| e.into_inner()); + if let Some(Some(m)) = meter.as_mut() { + m.names.insert(span.0, name.to_owned()); + } + } + span +} + +/// [`end`] for one of the title's lists, with what it mostly is: the +/// pipelines it binds (`names`, in order, as the list keeps them). Every +/// 256 frames the card's time is logged by that name: which of the title's +/// passes the card's time goes to, in a run like any other (the timing run +/// that names every command sends each list alone and needs the +/// device-removed notes). +pub(crate) fn end_named(list: &ID3D12GraphicsCommandList, span: Span, names: &std::collections::BTreeSet) { + if span.0 == u32::MAX { + return; + } + end(list, span); + let name = name_of(names); + let mut meter = METER.lock().unwrap_or_else(|e| e.into_inner()); + if let Some(Some(m)) = meter.as_mut() { + m.names.insert(span.0, name); + } +} + +/// A list's name in the table: how many pipelines it binds and the first +/// two of them (the set is in the order of the names, so a pass has the +/// same name every frame). +fn name_of(names: &std::collections::BTreeSet) -> String { + let short = |n: &String| n.chars().take(60).collect::(); + let mut first = names.iter(); + match (first.next(), first.next()) { + (None, _) => "no pipeline (copies, clears, barriers)".to_string(), + (Some(a), None) => format!("1 pipeline: {}", short(a)), + (Some(a), Some(b)) => format!("{} pipelines: {} / {}", names.len(), short(a), short(b)), + } +} + +/// Microseconds between two timestamps of a clock of `frequency` ticks a +/// second; 0 if the second is not after the first (a pair the card has not +/// written, or a list that never ran). +fn micros(begin: u64, end: u64, frequency: u64) -> u64 { + if end <= begin || frequency == 0 { + return 0; + } + ((end - begin) as u128 * 1_000_000 / frequency as u128).min(10_000_000) as u64 +} + +/// The pairs recorded long enough ago are read and added to the frame +/// log's totals. Called once a frame. +pub(crate) fn collect() { + if !on() { + return; + } + let mut meter = METER.lock().unwrap_or_else(|e| e.into_inner()); + let Some(Some(m)) = meter.as_mut() else { + return; + }; + let now = std::time::Instant::now(); + while let Some(&(pair, kind, at)) = m.pending.front() { + if now.duration_since(at) < AFTER { + break; + } + m.pending.pop_front(); + // SAFETY: the pair's sixteen bytes of the mapped read-back buffer; + // the card wrote them long ago or never. + let (begin, end) = unsafe { + let p = (m.mapped as *const u64).add(pair as usize * 2); + (p.read_volatile(), p.add(1).read_volatile()) + }; + if std::mem::replace(&mut m.seen[pair as usize], (begin, end)) == (begin, end) { + continue; + } + let us = micros(begin, end, m.frequency); + use crate::framelog::{T, add}; + match kind { + Kind::Sync => { + add(T::CardSyncUs, us); + add(T::CardSyncLists, 1); + } + Kind::Check => { + add(T::CardCheckUs, us); + add(T::CardCheckLists, 1); + } + Kind::Lists => { + add(T::CardListsUs, us); + add(T::CardLists, 1); + if let Some(name) = m.names.remove(&pair) { + let e = m.by_name.entry(name).or_insert((0, 0)); + e.0 += 1; + e.1 += us; + } + } + Kind::Pipeline => { + if let Some(name) = m.names.remove(&pair) { + let e = m.by_pipeline.entry(name).or_insert((0, 0)); + e.0 += 1; + e.1 += us; + } + } + } + } + m.frames += 1; + if m.frames >= 256 { + let frames = m.frames as f64; + let mut table: Vec<(String, (u64, u64))> = m.by_name.drain().collect(); + table.sort_by_key(|&(_, (_, us))| std::cmp::Reverse(us)); + let all: u64 = table.iter().map(|&(_, (_, us))| us).sum(); + tracing::info!( + "card time of the title's lists by what they bind, per frame over {} frames: {:.1} ms in {:.0} lists of {} kinds; the largest follow", + m.frames, + all as f64 / 1e3 / frames, + table.iter().map(|&(_, (n, _))| n).sum::() as f64 / frames, + table.len() + ); + for (name, (n, us)) in table.into_iter().take(24) { + tracing::info!(" card {:6.2} ms a frame in {:5.1} lists: {name}", us as f64 / 1e3 / frames, n as f64 / frames); + } + if !m.by_pipeline.is_empty() { + let mut table: Vec<(String, (u64, u64))> = m.by_pipeline.drain().collect(); + table.sort_by_key(|&(_, (_, us))| std::cmp::Reverse(us)); + let all: u64 = table.iter().map(|&(_, (_, us))| us).sum(); + tracing::info!( + "card time by pipeline (from where it is bound to where the next is), per frame over {} frames: {:.1} ms in {:.0} bindings of {} pipelines; the largest follow", + m.frames, + all as f64 / 1e3 / frames, + table.iter().map(|&(_, (n, _))| n).sum::() as f64 / frames, + table.len() + ); + for (name, (n, us)) in table.into_iter().take(48) { + tracing::info!( + " pipeline {:6.2} ms a frame in {:6.1} bindings ({:7.1} us each): {name}", + us as f64 / 1e3 / frames, + n as f64 / frames, + us as f64 / n.max(1) as f64 + ); + } + } + m.frames = 0; + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_list_is_named_by_the_pipelines_it_binds() { + let mut names = std::collections::BTreeSet::new(); + assert_eq!(name_of(&names), "no pipeline (copies, clears, barriers)"); + names.insert("compute CS_Blur".to_string()); + assert_eq!(name_of(&names), "1 pipeline: compute CS_Blur"); + names.insert("mesh VS_A, pixel PS_B".to_string()); + names.insert("a".repeat(100)); + assert_eq!(name_of(&names), format!("3 pipelines: {} / compute CS_Blur", "a".repeat(60))); + } + + #[test] + fn a_pairs_length_is_in_microseconds_of_the_queues_clock() { + assert_eq!(micros(1_000, 11_000, 10_000_000), 1_000); + assert_eq!(micros(0, 25_000_000, 25_000_000), 1_000_000); + // Not written, or the wrong way round: nothing. + assert_eq!(micros(5, 5, 1_000), 0); + assert_eq!(micros(9, 5, 1_000), 0); + assert_eq!(micros(1, 2, 0), 0); + // A stale second stamp from the ring's last round cannot add hours. + assert_eq!(micros(1, u64::MAX, 1), 10_000_000); + } +} diff --git a/crates/leonida-gpu/src/console.rs b/crates/leonida-gpu/src/console.rs new file mode 100644 index 000000000..ab7252c57 --- /dev/null +++ b/crates/leonida-gpu/src/console.rs @@ -0,0 +1,50 @@ +//! Which console the title runs on. Titles pick settings (resolution, +//! memory budgets) by it, so the user chooses; Series X unless told. + +use std::sync::atomic::{AtomicBool, Ordering}; + +const GIB: usize = 1 << 30; + +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +pub enum Console { + #[default] + SeriesX, + SeriesS, +} + +impl Console { + /// Title memory in bytes: (GPU-optimal, standard). Series X in the + /// advanced configuration; Series S has one range, counted as standard + /// (7,776 MiB, the published console-mode figure). + // shortcut: later system updates gave Series S titles more (amount not + // published here); the title sizes nothing from this figure + // (it goes by the device type), so update it if a title does. + pub const fn title_memory(self) -> (usize, usize) { + match self { + Console::SeriesX => (10 * GIB, 7 * GIB / 2), + Console::SeriesS => (0, 7_776 << 20), + } + } + + pub const fn name(self) -> &'static str { + match self { + Console::SeriesX => "Xbox Series X", + Console::SeriesS => "Xbox Series S", + } + } +} + +static SERIES_S: AtomicBool = AtomicBool::new(false); + +/// Set before the title starts. +pub fn set(console: Console) { + SERIES_S.store(console == Console::SeriesS, Ordering::Relaxed); +} + +pub fn current() -> Console { + if SERIES_S.load(Ordering::Relaxed) { + Console::SeriesS + } else { + Console::SeriesX + } +} diff --git a/crates/leonida-gpu/src/copystat.rs b/crates/leonida-gpu/src/copystat.rs new file mode 100644 index 000000000..81bad122b --- /dev/null +++ b/crates/leonida-gpu/src/copystat.rs @@ -0,0 +1,1358 @@ +//! Diagnostics: where the submission copies of title memory go (which +//! ranges, how often, of what memory) and what limits their rate, logged +//! with the frame-rate line. `LEONIDA_COPY_MODE=plain` copies without the +//! mapped-page guard, `none` skips the copies (both for timing only). + +use std::collections::HashMap; +use std::sync::Mutex; +use std::sync::atomic::{AtomicU64, Ordering::Relaxed}; + +/// Counters since the last line. +pub(crate) enum C { + Submissions, + Copies, + CopyBytes, + Refreshes, + RefreshBytes, + Skipped, + SkippedBytes, + Runs, + RunUs, + Queries, + QueryUs, + MoveUs, + Unmapped, + /// Write-watch askings and their time. + Watches, + WatchUs, + /// Bytes of watched ranges checked, and of those found unchanged. + Checked, + Unchanged, + /// Copies that met an unmapped page. + Fallbacks, + /// Writes taken by the guard on view memory. + GuardFaults, + /// Texture bytes detiled after a watched write; hashed; detiled after a + /// hash change. + TexWatched, + TexHashed, + TexChanged, + /// Frames presented since the last line (what the line divides by). + Frames, + /// Calls of list methods that record into a host list, and the + /// nanoseconds they took, summed over the title's recording threads. + RecordCalls, + RecordNs, + /// Waiting for host pipelines being made (`pipeline::make`). + PipelineWaitUs, + /// Dynamic descriptor slots: tables asked for, refused (no free run), + /// and the nanoseconds of the searches. + DynamicAsked, + DynamicRefused, + DynamicNs, + /// Marker texts for device-removed data (`HostList::note`). + NoteNs, + /// Ranges given to shaders (steps), their snapshots, and the bytes + /// compared after the submission. + GpuWrites, + SnapshotUs, + BackCompared, + /// Reading around unmapped pages after a failed bulk read. + SparseUs, + /// Guarding view memory (part of the write-watch askings' time). + GuardUs, + /// Bytes copied whole because their memory is neither write-watched + /// nor a view (`Shadow::update_free`). + WholeBytes, + /// Submissions with ranges shaders write (they need the GPU's results + /// before they return). + BackSubmissions, + /// The title's frame waits (`frame::wait`) and the time slept in them, + /// over all its threads. + PaceWaits, + PaceUs, + /// After a present: until the title's first list call and until its + /// first submission; and from its last submission to its next present. + UntilRecordUs, + UntilSubmitUs, + TailUs, + /// Resetting host lists (`HostList::reset`). + ResetNs, + /// What shaders wrote: finding the 64 KiB pieces that differ, how many + /// do, and putting them into title memory. + BackScanUs, + BackDiffer, + BackSyncUs, + /// Texture uploads recorded, and left out as unchanged. + TexUploads, + TexSkipped, + /// Held submissions a present ran although their waits were not met. + Forced, + /// Ranges named through unordered access views by shaders that cannot + /// store to buffers, not given to shaders as written, and their bytes. + GpuWritesLeftOut, + GpuWritesLeftOutBytes, + /// Waits for memory values looked at (`list::ValueWait::met`) and the + /// nanoseconds the looks took, on every thread. + WaitChecks, + WaitCheckNs, + /// Host lists made (`Host::new_list`: for the lists a queue holds and + /// for the parts of lists cut at waits) and the nanoseconds that took. + HostLists, + HostListNs, + /// Parts of held submissions that ran while the part behind them could + /// have run with them (its waits were met already). + PartsTogether, + /// Microseconds of the copies counted in `WholeBytes`. + WholeUs, + /// Submissions by how long the card was waited for (under 2 ms, 2-8, + /// 8-32, longer), and the microseconds waited in each class. + CardUnder2, + Card2To8, + Card8To32, + CardOver32, + CardUnder2Us, + Card2To8Us, + Card8To32Us, + CardOver32Us, + /// Submissions that hand nothing back to the title (no range shaders + /// write, no value written when done), and the microseconds the card + /// was waited for them. + NothingBack, + NothingBackUs, + /// Waits for every earlier shader write recorded into host lists: for + /// the title's barrier groups, for its barriers on buffers, and the + /// indirect commands bounded (each a dispatch of ours between two such + /// waits). + WaitsForGroups, + WaitsForBuffers, + IndirectBounded, + /// `watch::writes` kernel askings that failed (the range is not + /// write-watched: view memory or not watchable). + WatchFailed, + /// `watch::writes` askings not made because the range's first block is + /// already known to be guarded view memory (no kernel call). + WatchKnownView, +} +const COUNTERS: usize = 80; +static COUNT: [AtomicU64; COUNTERS] = [const { AtomicU64::new(0) }; COUNTERS]; + +pub(crate) fn add(c: C, n: u64) { + COUNT[c as usize].fetch_add(n, Relaxed); +} + +/// How copies run: 0 guarded (as always), 1 plain, 2 not at all. +pub(crate) fn mode() -> u8 { + static MODE: std::sync::OnceLock = std::sync::OnceLock::new(); + *MODE.get_or_init(|| match std::env::var("LEONIDA_COPY_MODE").as_deref() { + Ok("plain") => 1, + Ok("none") => 2, + _ => 0, + }) +} + +/// Per source range (start, length): copies, bytes, microseconds, memory type. +type Ranges = HashMap<(usize, usize), (u64, u64, u64, u32)>; +static RANGES: Mutex> = Mutex::new(None); + +/// Per range copied whole because its memory is not watched (start, +/// length): copies and microseconds. +static WHOLE: Mutex>> = Mutex::new(None); + +/// `len` bytes at `src`, memory that is not watched, were copied whole in +/// `us`. +pub(crate) fn whole(src: usize, len: usize, us: u64) { + add(C::WholeUs, us); + let mut map = WHOLE.lock().unwrap_or_else(|e| e.into_inner()); + let e = map.get_or_insert_with(HashMap::new).entry((src, len)).or_insert((0, 0)); + e.0 += 1; + e.1 += us; +} + +/// The longest wait for the card since the last line: microseconds, and +/// what ran (lists and pipelines). +static LONGEST: Mutex<(u64, String)> = Mutex::new((0, String::new())); + +/// The waits for the card since the last line by what ran (lists and +/// pipelines): how many, and their microseconds. +static WAITS_BY_WORK: Mutex>> = Mutex::new(None); + +/// With `LEONIDA_GPU_TIMING`: the commands' time on the card since the last +/// line by what they ran (a pipeline, or the kind of command): how many, +/// their microseconds, and the longest one's. +static COMMANDS_BY_WORK: Mutex>> = Mutex::new(None); + +/// A command took `ms` on the card (timing run). `op` is its note: the +/// kind and size first, then the pipeline in brackets, then what it binds. +pub(crate) fn command_took(op: &str, ms: f64) { + let us = (ms * 1e3) as u64; + let mut by = COMMANDS_BY_WORK.lock().unwrap_or_else(|e| e.into_inner()); + let e = by.get_or_insert_with(HashMap::new).entry(command_key(op)).or_insert((0, 0, 0)); + e.0 += 1; + e.1 += us; + e.2 = e.2.max(us); +} + +/// What a command's note is summed under: its pipeline (`[compute ...]`, +/// `[mesh ..., pixel ...]`) with the command's first word, or without a +/// pipeline its first two words. +fn command_key(op: &str) -> String { + let head = op.split(" | ").next().unwrap_or(op); + let word = head.split(' ').next().unwrap_or(""); + match (head.find('['), head.find(']')) { + (Some(a), Some(b)) if a < b => format!("{word} {}", &head[a..=b]), + _ => head.split(' ').take(2).collect::>().join(" "), + } +} + +/// The card was waited for `us` for a submission; `what` names it if it is +/// the longest since the last line. +pub(crate) fn card_waited(us: u64, what: impl FnOnce() -> String) { + let (n, t) = match us { + 0..2_000 => (C::CardUnder2, C::CardUnder2Us), + 2_000..8_000 => (C::Card2To8, C::Card2To8Us), + 8_000..32_000 => (C::Card8To32, C::Card8To32Us), + _ => (C::CardOver32, C::CardOver32Us), + }; + add(n, 1); + add(t, us); + // Every submission is named (some forty a frame): the same lists run + // every frame, and the eight longest waits of a line were one list + // eight times. + let text = what(); + { + let mut by = WAITS_BY_WORK.lock().unwrap_or_else(|e| e.into_inner()); + let e = by.get_or_insert_with(HashMap::new).entry(text.clone()).or_insert((0, 0)); + e.0 += 1; + e.1 += us; + } + let mut longest = LONGEST.lock().unwrap_or_else(|e| e.into_inner()); + if us > longest.0 { + *longest = (us, text); + } +} + +/// Whether an experiment on barriers is on (`LEONIDA_BARRIER_TEST`): bit 0 +/// for `groups` (the title's barrier groups record no wait for earlier +/// shader writes), bit 1 for `indirect` (the pass that bounds an indirect +/// command runs without its two such waits; its state changes stay), both +/// bits for `both`. For timing only: without the waits a shader may read +/// what another has not finished writing. +pub(crate) fn barrier_test() -> u8 { + static TEST: std::sync::OnceLock = std::sync::OnceLock::new(); + *TEST.get_or_init(|| match std::env::var("LEONIDA_BARRIER_TEST").as_deref() { + Ok("groups") => 1, + Ok("indirect") => 2, + Ok("both") => 3, + _ => 0, + }) +} + +/// Per range compared after a submission (start, length): times, and the +/// bytes of it written back to the title. +static COMPARED: Mutex>> = Mutex::new(None); + +/// `len` bytes at `src` were compared after a submission and `written` of +/// them put back into title memory. +pub(crate) fn compared(src: usize, len: usize, written: usize) { + let mut map = COMPARED.lock().unwrap_or_else(|e| e.into_inner()); + let e = map.get_or_insert_with(HashMap::new).entry((src, len)).or_insert((0, 0)); + e.0 += 1; + e.1 += written as u64; +} + +/// A copy of `len` bytes from `src` (memory type `kind`) took `us`. +pub(crate) fn range(src: usize, len: usize, us: u64, kind: u32) { + let mut map = RANGES.lock().unwrap_or_else(|e| e.into_inner()); + let e = map + .get_or_insert_with(HashMap::new) + .entry((src, len)) + .or_insert((0, 0, 0, kind)); + e.0 += 1; + e.1 += len as u64; + e.2 += us; +} + +/// Our own allocations alive now, by size of block (under 4 KiB, to 64 KiB, +/// to 1 MiB, larger): bytes, then blocks. "Our own" is the Rust code of +/// every crate in the process: in diagnostics builds [`Counting`] stands in +/// front of the system's heap. The memory map's "process heap segments" +/// hold the blocks under about half a megabyte of ours, of the graphics +/// runtime and of the driver alike (3.5 GB in run 60's gameplay, growing by +/// some 2 MB a frame, and nothing said whose): this says which part is +/// ours. Bigger blocks are allocations of their own in the map. +static OWN: [AtomicU64; 8] = [const { AtomicU64::new(0) }; 8]; + +/// The class of [`OWN`] a block of `size` bytes counts in. +fn block_class(size: usize) -> usize { + match size { + 0..0x1000 => 0, + 0x1000..0x1_0000 => 1, + 0x1_0000..0x10_0000 => 2, + _ => 3, + } +} + +fn own(size: usize, made: bool) { + let class = block_class(size); + if made { + OWN[class].fetch_add(size as u64, Relaxed); + OWN[4 + class].fetch_add(1, Relaxed); + } else { + OWN[class].fetch_sub(size as u64, Relaxed); + OWN[4 + class].fetch_sub(1, Relaxed); + } +} + +/// Our own blocks of [`BIG`] bytes and more alive now: where each is (0: +/// none) and its bytes. The memory map lists the process's big allocations +/// by size without saying whose they are (run 65: one of 544 MB, one of +/// 401 MB, two of 174 MB, two of 115 MB); the sizes here say which of them +/// are ours. +static BIG_AT: [std::sync::atomic::AtomicUsize; 64] = [const { std::sync::atomic::AtomicUsize::new(0) }; 64]; +static BIG_BYTES: [AtomicU64; 64] = [const { AtomicU64::new(0) }; 64]; +const BIG: usize = 32 << 20; + +/// A block of [`BIG`] bytes or more was made at `at`, or released there. +fn big(at: *mut u8, size: usize, made: bool) { + if size < BIG { + return; + } + for (place, bytes) in BIG_AT.iter().zip(&BIG_BYTES) { + if made { + if place.compare_exchange(0, at as usize, Relaxed, Relaxed).is_ok() { + bytes.store(size as u64, Relaxed); + return; + } + } else if place.load(Relaxed) == at as usize { + bytes.store(0, Relaxed); + place.store(0, Relaxed); + return; + } + } +} + +/// The sizes of our own big blocks alive, largest first, in MB. +fn big_blocks() -> String { + let mut sizes: Vec = BIG_BYTES.iter().map(|b| b.load(Relaxed)).filter(|&b| b != 0).collect(); + sizes.sort_unstable_by(|a, b| b.cmp(a)); + let text: Vec = sizes.iter().map(|b| format!("{:.2}", *b as f64 / (1 << 20) as f64)).collect(); + if text.is_empty() { "none".into() } else { text.join(", ") } +} + +/// The system's allocator with every block counted in [`OWN`] (two atomic +/// additions per allocation and per release: diagnostics builds only). +struct Counting; + +// SAFETY: every call goes to the system's allocator unchanged; only +// counters are kept beside it. +unsafe impl std::alloc::GlobalAlloc for Counting { + unsafe fn alloc(&self, layout: std::alloc::Layout) -> *mut u8 { + // SAFETY: the caller's contract, passed on. + let at = unsafe { std::alloc::System.alloc(layout) }; + if !at.is_null() { + own(layout.size(), true); + big(at, layout.size(), true); + } + at + } + + unsafe fn alloc_zeroed(&self, layout: std::alloc::Layout) -> *mut u8 { + // SAFETY: the caller's contract, passed on. + let at = unsafe { std::alloc::System.alloc_zeroed(layout) }; + if !at.is_null() { + own(layout.size(), true); + big(at, layout.size(), true); + } + at + } + + unsafe fn dealloc(&self, at: *mut u8, layout: std::alloc::Layout) { + own(layout.size(), false); + big(at, layout.size(), false); + // SAFETY: the caller's contract, passed on. + unsafe { std::alloc::System.dealloc(at, layout) }; + } + + unsafe fn realloc(&self, at: *mut u8, layout: std::alloc::Layout, size: usize) -> *mut u8 { + // SAFETY: the caller's contract, passed on. + let moved = unsafe { std::alloc::System.realloc(at, layout, size) }; + if !moved.is_null() { + own(layout.size(), false); + own(size, true); + big(at, layout.size(), false); + big(moved, size, true); + } + moved + } +} + +#[global_allocator] +static HEAP: Counting = Counting; + +#[cfg(test)] +mod command_tests { + /// Commands are summed by pipeline and first word; those without a + /// pipeline by their first two words. + #[test] + fn commands_are_named_by_their_pipeline() { + use super::command_key; + assert_eq!( + command_key("dispatch 182x1x1 [compute 24f989b98dcb03f0] | 24f989b98dcb03f0: u4=0xa6b080 [heap 341380: x]"), + "dispatch [compute 24f989b98dcb03f0]" + ); + assert_eq!( + command_key("indirect kind 10 max 1 at 0xd9358fce0 [mesh 0750cb2d975c7563, pixel 085d374c5a795549] | t"), + "indirect [mesh 0750cb2d975c7563, pixel 085d374c5a795549]" + ); + assert_eq!(command_key("texture upload 0x271b61c28b0 (2048x2048x1 f99 mips 10) sub 0"), "texture upload"); + assert_eq!(command_key("alias copy of 0x26f66aca780 into 0x26fbdc93890"), "alias copy"); + } +} + +#[cfg(test)] +mod own_tests { + use super::{OWN, block_class}; + use std::sync::atomic::Ordering::Relaxed; + + #[test] + fn blocks_count_in_their_size_class() { + assert_eq!(block_class(0), 0); + assert_eq!(block_class(4095), 0); + assert_eq!(block_class(4096), 1); + assert_eq!(block_class(65535), 1); + assert_eq!(block_class(65536), 2); + assert_eq!(block_class((1 << 20) - 1), 2); + assert_eq!(block_class(1 << 20), 3); + } + + /// A block of 32 MiB or more is listed by its size while it lives. + #[test] + fn big_blocks_are_listed_while_they_live() { + let size = (48usize << 20) + 4096; + let listed = |at: usize| { + super::BIG_AT + .iter() + .zip(&super::BIG_BYTES) + .any(|(place, bytes)| place.load(Relaxed) == at && bytes.load(Relaxed) == size as u64) + }; + let block = vec![0u8; size]; + let at = block.as_ptr() as usize; + assert!(listed(at)); + assert!(super::big_blocks().contains("48.00")); + drop(block); + assert!(!listed(at)); + } + + /// A big block shows in the counters while it lives (other tests + /// allocate small blocks meanwhile: only the big class is looked at, + /// and only for at least this block). + #[test] + fn a_block_is_counted_while_it_lives() { + let block = vec![1u8; 8 << 20]; + assert!(OWN[3].load(Relaxed) >= 8 << 20); + assert!(OWN[7].load(Relaxed) >= 1); + drop(block); + assert!(OWN[7].load(Relaxed) < u64::MAX / 2, "no count below zero"); + } +} + +/// The process's memory in bytes: in physical memory, and committed +/// (private bytes). +fn process_memory() -> (u64, u64) { + use windows_sys::Win32::System::ProcessStatus::{ + K32GetProcessMemoryInfo, PROCESS_MEMORY_COUNTERS, + }; + use windows_sys::Win32::System::Threading::GetCurrentProcess; + let mut c = PROCESS_MEMORY_COUNTERS { + cb: size_of::() as u32, + ..Default::default() + }; + // SAFETY: our own process and a sized structure. + unsafe { K32GetProcessMemoryInfo(GetCurrentProcess(), &mut c, c.cb) }; + (c.WorkingSetSize as u64, c.PagefileUsage as u64) +} + +/// The PC's memory in bytes: physical memory free, and what is left to +/// commit. +fn system_memory() -> (u64, u64) { + use windows_sys::Win32::System::SystemInformation::{GlobalMemoryStatusEx, MEMORYSTATUSEX}; + // SAFETY: plain data the call fills in. + let mut m: MEMORYSTATUSEX = unsafe { std::mem::zeroed() }; + m.dwLength = size_of::() as u32; + // SAFETY: a sized structure. + unsafe { GlobalMemoryStatusEx(&mut m) }; + (m.ullAvailPhys, m.ullAvailPageFile) +} + +/// Whether the address space is walked for the memory map line +/// ([`log_memory_map`]). On by default (this module is in diagnostics +/// builds only); `LEONIDA_MEMORY_MAP=0` leaves the walk out. +fn memory_map() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("LEONIDA_MEMORY_MAP").is_none_or(|v| v != "0")) +} + +/// Asks which of the pages in `asked` (address, answer) are in physical +/// memory and adds the bytes each stands for (kind, bytes) to its kind. +fn in_memory(asked: &mut Vec<[usize; 2]>, stands: &mut Vec<(usize, u64)>, present: &mut [u64; 10]) { + use windows_sys::Win32::System::ProcessStatus::K32QueryWorkingSetEx; + use windows_sys::Win32::System::Threading::GetCurrentProcess; + // SAFETY: our own process; `asked` holds that many entries of two + // words each, as the call fills them in. + let ok = unsafe { + K32QueryWorkingSetEx(GetCurrentProcess(), asked.as_mut_ptr().cast(), (asked.len() * 16) as u32) + } != 0; + if ok { + for (a, &(kind, bytes)) in asked.iter().zip(stands.iter()) { + // Bit 0 of the answer: the page is in the process's memory. + if a[1] & 1 != 0 { + present[kind] += bytes; + } + } + } + asked.clear(); + stands.clear(); +} + +/// Logs what the process has committed by kind, from a walk of its address +/// space, and how much of each kind is in physical memory (one page in +/// sixteen is asked about). The kinds tell the title's own memory from +/// ours: the title's heaps and page views lie at console addresses (below +/// 1 TiB), everything the host allocates lies far above. Run 30, seen +/// from outside at 18.0 GB private: 4.6 GB the title's heaps, 2.6 GB in +/// 162 segments of the process heap, 2.7 GB in 707 allocations of 4 MiB +/// (windows of title memory), 0.46 GB the pipeline library's file; mapped +/// and so not private: 6.2 GB the title's page pool, 2.0 GB the driver's +/// shader cache file. +/// shortcut: the walk takes about 0.6 s on a thread of its own, and a +/// query of a region of gigabytes holds up other threads' memory calls +/// for its length (89 ms for the 6.2 GB pool), so it runs with every +/// sixth memory line only. +fn log_memory_map() { + use windows_sys::Win32::System::Memory::{ + MEM_COMMIT, MEM_FREE, MEM_IMAGE, MEM_MAPPED, MEMORY_BASIC_INFORMATION, PAGE_WRITECOMBINE, + VirtualQuery, + }; + const KINDS: [&str; 10] = [ + "the title's heaps (private, console addresses)", + "views of the title's pages (mapped, console addresses)", + "the title's page pool (mapped, 1 GB and more)", + "process heap segments (private, 15.8 MB each)", + "windows of title memory and other 4 MiB allocations", + "write-combined (buffers shared with the card)", + "other private allocations of 1 MB and more", + "other private allocations under 1 MB", + "files and other mappings at host addresses", + "programs and libraries", + ]; + /// Console addresses lie below this. + const HOST: usize = 1 << 40; + /// One page asked about stands for this much. + const STEP: usize = 64 << 10; + let started = std::time::Instant::now(); + // Allocation, start, bytes, committed, type, protection. + type Region = (usize, usize, usize, bool, u32, u32); + let mut regions: Vec = Vec::new(); + let mut at = 0usize; + loop { + // SAFETY: plain data filled in by the query. + let mut m: MEMORY_BASIC_INFORMATION = unsafe { std::mem::zeroed() }; + // SAFETY: a valid out pointer of the right size. + if unsafe { VirtualQuery(at as *const _, &mut m, size_of_val(&m)) } == 0 { + break; + } + if m.State != MEM_FREE { + regions.push(( + m.AllocationBase as usize, + m.BaseAddress as usize, + m.RegionSize, + m.State == MEM_COMMIT, + m.Type, + m.Protect, + )); + } + let next = (m.BaseAddress as usize).saturating_add(m.RegionSize); + if next <= at { + break; + } + at = next; + } + // Each allocation's whole size, reserved parts included. + let mut whole: HashMap = HashMap::new(); + for r in ®ions { + *whole.entry(r.0).or_default() += r.2; + } + let kind = |r: &Region| -> usize { + let size = whole.get(&r.0).copied().unwrap_or(0); + let console = r.0 < HOST; + if r.4 == MEM_IMAGE { + 9 + } else if r.4 == MEM_MAPPED { + match (console, size >= 1 << 30) { + (false, _) => 8, + (true, true) => 2, + (true, false) => 1, + } + } else if console { + 0 + } else if size == 0xfd_0000 { + 3 + } else if size == 4 << 20 { + 4 + } else if r.5 & PAGE_WRITECOMBINE != 0 { + 5 + } else if size >= 1 << 20 { + 6 + } else { + 7 + } + }; + let mut committed = [0u64; 10]; + let mut present = [0u64; 10]; + let mut asked: Vec<[usize; 2]> = Vec::with_capacity(4096); + let mut stands: Vec<(usize, u64)> = Vec::with_capacity(4096); + for r in regions.iter().filter(|r| r.3) { + let k = kind(r); + committed[k] += r.2 as u64; + let mut offset = 0; + while offset < r.2 { + asked.push([r.1 + offset, 0]); + stands.push((k, STEP.min(r.2 - offset) as u64)); + if asked.len() == 4096 { + in_memory(&mut asked, &mut stands, &mut present); + } + offset += STEP; + } + } + if !asked.is_empty() { + in_memory(&mut asked, &mut stands, &mut present); + } + let text: Vec = (0..KINDS.len()) + .filter(|&k| committed[k] > 0) + .map(|k| format!("{} {} MB ({} MB in memory)", KINDS[k], committed[k] >> 20, present[k] >> 20)) + .collect(); + tracing::info!( + "memory map ({} regions, {} ms): {}", + regions.len(), + started.elapsed().as_millis(), + text.join("; ") + ); + // The private allocations the kinds above leave as "other" (and the + // write-combined ones), grouped by their size: the sizes name their + // owners (the pipeline library's file to the byte, a snapshot buffer + // of a title heap's size, the driver's blocks). Committed bytes by + // allocation first, then allocations by (kind, whole size). + let mut by_allocation: HashMap = HashMap::new(); + for r in regions.iter().filter(|r| r.3) { + let k = kind(r); + if k == 5 || k == 6 { + by_allocation.entry(r.0).or_insert((k, 0)).1 += r.2 as u64; + } + } + let mut groups: HashMap<(usize, usize), (u64, u64)> = HashMap::new(); + for (base, &(k, bytes)) in &by_allocation { + let group = groups.entry((k, whole.get(base).copied().unwrap_or(0))).or_default(); + group.0 += 1; + group.1 += bytes; + } + let mut groups: Vec<((usize, usize), (u64, u64))> = groups.into_iter().collect(); + groups.sort_by_key(|g| std::cmp::Reverse(g.1.1)); + let biggest: Vec = groups + .iter() + .take(20) + .map(|&((k, size), (n, bytes))| { + format!( + "{n} of {:.2} MB{}: {} MB", + size as f64 / (1 << 20) as f64, + if k == 5 { " write-combined" } else { "" }, + bytes >> 20 + ) + }) + .collect(); + tracing::info!( + "memory map, other private allocations by size, the {} biggest groups of {} (committed): {}", + biggest.len(), + groups.len(), + biggest.join("; ") + ); +} + +/// Logs where the memory is: the process and the PC, then what this crate +/// holds by kind (alive now), then the host buffers made since the start. +fn log_memory() { + use std::sync::atomic::Ordering::Relaxed; + let mb = |v: u64| v as f64 / (1 << 20) as f64; + let (working, private) = process_memory(); + let (free, left) = system_memory(); + let copies = crate::shadow::memory(); + let staged = crate::texture::memory(); + let textures = [0, 1].map(|i| crate::resource::HOST_TEXTURES[i].load(Relaxed)); + let made: Vec = crate::host::MADE.iter().map(|m| m.load(Relaxed)).collect(); + let windows = crate::shadow::windows(); + let stagings = crate::texture::let_go(); + let census = crate::resource::census(); + let kinds: Vec = crate::resource::KINDS.iter().map(|k| k.load(Relaxed)).collect(); + let card = crate::host::host() + .and_then(|h| h.video_memory()) + .unwrap_or_default(); + // Everything the system says of the two memory groups, beside the + // budget and use the lines below print. + if let Some(h) = crate::host::host() { + h.log_video_memory("with the memory line"); + } + // What else holds memory: the map, on a thread of its own, with every + // sixth line; and what the shader table and the pipeline library keep. + static LINES: AtomicU64 = AtomicU64::new(0); + static WALKING: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); + if memory_map() && LINES.fetch_add(1, Relaxed) % 6 == 5 && !WALKING.swap(true, Relaxed) { + let walk = std::thread::Builder::new().name("leonida-memory-map".into()).spawn(|| { + log_memory_map(); + WALKING.store(false, Relaxed); + }); + if walk.is_err() { + WALKING.store(false, Relaxed); + } + } + let kept = crate::pipeline::kept(); + tracing::info!( + "memory kept beside the lines below: {} shader containers {:.0} MB, {} translations \ + {:.0} MB; the pipeline library's file {:.0} MB (its last save wrote {:.0} MB)", + kept[0], + mb(kept[1]), + kept[2], + mb(kept[3]), + mb(kept[4]), + mb(kept[5]), + ); + tracing::info!( + "memory of textures: {} title textures have no host copy yet ({:.0} MB of title memory); \ + host copies the host renders to or writes: {} alive {:.0} MB; host copies the title \ + fills: {} alive {:.0} MB ({} of them placed), {} let go {:.0} MB and {} made again \ + {:.0} MB since the start; {} host copies made in all; passes that made none for lack of \ + room: {}; the card: {:.0} MB in use of a budget of {:.0} MB, {:.0} MB of the PC's memory \ + shared with it in use", + census[2], + mb(census[3]), + census[0], + mb(census[1]), + census[4], + mb(census[5]), + census[6], + kinds[2], + mb(kinds[3]), + kinds[4], + mb(kinds[5]), + kinds[6], + crate::draw::HEAP_TEXTURES_FULL.load(Relaxed), + mb(card[1]), + mb(card[0]), + mb(card[3]), + ); + let targets = crate::resource::targets_census(); + tracing::info!( + "host copies the sweep never lets go: {} the host renders to or writes {:.0} MB ({} of them placed {:.0} MB); of them {} have title memory that is not mapped now {:.0} MB, {} were not used for 30 s and are held by no list and no slot {:.0} MB, {} are both {:.0} MB; and {} copies of textures the title fills that the host copied into {:.0} MB", + targets[0], + mb(targets[1]), + targets[10], + mb(targets[11]), + targets[2], + mb(targets[3]), + targets[4], + mb(targets[5]), + targets[6], + mb(targets[7]), + targets[8], + mb(targets[9]), + ); + tracing::info!( + "memory let go since the start: {} windows outside buffers {:.0} MB, {} staging buffers \ + {:.0} MB; of the windows alive, {:.0} MB lie between the lowest and highest address \ + asked for in each", + windows[0], + mb(windows[1]), + stagings[0], + mb(stagings[1]), + mb(windows[2]), + ); + tracing::info!( + "memory: {:.0} MB private ({:.0} MB of it in memory; the PC has {:.0} MB free and {:.0} MB \ + left to commit); host copies of title memory: {} alive {:.0} MB, of them {} windows \ + outside buffers {:.0} MB; snapshot buffers kept: {} reserving {:.0} MB; staging of \ + textures: {} alive {:.0} MB, {} kept by their texture; host textures: {} alive {:.0} MB, \ + {} placed in title memory; made so far: {} upload buffers {:.0} MB, {} shared buffers \ + {:.0} MB, {} card buffers {:.0} MB", + mb(private), + mb(working), + mb(free), + mb(left), + copies[0], + mb(copies[1]), + copies[2], + mb(copies[3]), + copies[4], + mb(copies[5]), + staged[0], + mb(staged[1]), + staged[2], + textures[0], + mb(textures[1]), + crate::resource::placed_textures(), + made[0], + mb(made[1]), + made[2], + mb(made[3]), + made[4], + mb(made[5]), + ); + tracing::info!( + "memory, placed textures: {} of them were asked for again with other filler words in their description (one resource and host copy each since the filler left the key; LEONIDA_PLACED_FILLER=1 keeps it)", + crate::resource::placed_filler_twins() + ); + // What the line above leaves open: what is alive of the buffers "made + // so far", what the windows hold and what holds them, and what our own + // code has allocated. + let alive: Vec = crate::host::ALIVE.iter().map(|a| a.load(Relaxed)).collect(); + let window = crate::shadow::window_use(); + let views = crate::descriptor::views_kept(); + let own: Vec = OWN.iter().map(|o| o.load(Relaxed)).collect(); + tracing::info!( + "memory, what holds it: {} host lists alive; their scratch memory: {} chunks {:.0} MB, of them {} chunks {:.0} MB spare ({} taken from the spare ones so far); their other upload buffers: {} alive {:.0} MB; windows outside buffers (grid {} KiB): {:.0} MB of their pages ever copied, {} shown by descriptor slots {:.0} MB, {} held by lists or the pass over the heap {:.0} MB, {} asked for without a length {:.0} MB; buffer views of the heap whose slot showed another copy than the one brought up to date: {}; distinct views kept: {} ({} free) {:.0} MB; our own allocations: {:.0} MB in {} blocks (under 4 KiB {:.0} MB in {}, to 64 KiB {:.0} MB in {}, to 1 MiB {:.0} MB in {}, larger {:.0} MB in {})", + alive[0], + alive[1], + mb(alive[2]), + alive[3], + mb(alive[4]), + alive[5], + alive[6], + mb(alive[7]), + window[7] >> 10, + mb(window[0]), + window[1], + mb(window[2]), + window[3], + mb(window[4]), + window[5], + mb(window[6]), + crate::draw::HEAP_VIEWS_ELSEWHERE.load(Relaxed), + views[0], + views[1], + mb(views[2]), + mb(own[..4].iter().sum()), + own[4..].iter().sum::(), + mb(own[0]), + own[4], + mb(own[1]), + own[5], + mb(own[2]), + own[6], + mb(own[3]), + own[7], + ); + // Round 2: what the view table still holds and what goes around it, + // what host lists cost, the card's share that is the layer's own or + // the title's no more, and which big blocks are ours. + let lists: Vec = crate::host::LISTS.iter().map(|l| l.load(Relaxed)).collect(); + tracing::info!( + "memory, more: views named whole in their records since the start: {} constant buffer \ + views, {} views of placed memory; of the view table's entries {} are constant buffer \ + views and {} views of placed memory; shapes of placed views kept: {}; host lists: {} \ + made by the host, {} preludes made for them, private bytes grew {:.0} MB while \ + lists were made; twins of depth textures: {:.0} MB; host copies of \ + placed textures whose title memory is not mapped any more (estimate): {:.0} MB, of \ + them still shown by a descriptor slot {:.0} MB; the pipeline library's mapped file \ + let go from memory so far: {:.0} MB; our own blocks of 32 MB and more, in MB: {}", + views[6], + views[7], + views[3], + views[4], + views[5], + lists[0], + lists[1], + lists[2] as i64 as f64 / (1 << 20) as f64, + mb(census[7]), + mb(census[8]), + mb(census[9]), + mb(kept[6]), + big_blocks(), + ); + // Round 3: whether windows hold the same memory more than once (they + // can, once they are cut finer than 4 MiB), and how many host lists + // the title made and never used. + tracing::info!( + "memory, windows: the {:.0} MB of windows lie over {:.0} MB of title memory (the rest is \ + memory that is in more than one window, and is copied once for each); host lists never \ + reset since they were made: {}", + mb(copies[3]), + mb(crate::shadow::window_cover()), + lists[3], + ); +} + +/// Microseconds since the first call. +fn now_us() -> u64 { + static EPOCH: std::sync::OnceLock = std::sync::OnceLock::new(); + EPOCH.get_or_init(std::time::Instant::now).elapsed().as_micros() as u64 +} + +/// When the last frame was presented and when the last submission returned +/// ([`now_us`]), and whether a list call and a submission followed that +/// present yet. +static PRESENTED_AT: AtomicU64 = AtomicU64::new(0); +static SUBMITTED_AT: AtomicU64 = AtomicU64::new(0); +static RECORDED_SINCE: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(true); +static SUBMITTED_SINCE: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(true); + +/// What a thread that submits did between its submissions and in them +/// (microseconds; list calls in nanoseconds). +#[derive(Default, Clone, Copy)] +struct Submitter { + submissions: u64, + /// From a submission's return to the next one's call: wall time, of it + /// the thread running (user, kernel), and inside our list calls. + between: u64, + between_user: u64, + between_kernel: u64, + between_ours: u64, + /// Waiting for the submission lock; running inside submissions. + lock: u64, + inside_user: u64, + inside_kernel: u64, +} + +/// By thread: the submitting threads, and list-call time (nanoseconds, +/// calls) of every recording thread. +static SUBMITTERS: Mutex> = Mutex::new(Vec::new()); +static RECORDERS: Mutex> = Mutex::new(Vec::new()); + +thread_local! { + /// This thread's last submission: when it returned ([`now_us`]) and the + /// thread's processor time then (user, kernel). + static LEFT: std::cell::Cell> = const { std::cell::Cell::new(None) }; + /// The thread's processor time when its running submission was called. + static ENTERED: std::cell::Cell<(u64, u64)> = const { std::cell::Cell::new((0, 0)) }; + /// List-call nanoseconds of this thread since its last submission. + static OURS: std::cell::Cell = const { std::cell::Cell::new(0) }; + /// List-call time not yet added to `RECORDERS` (nanoseconds, calls). + static UNSENT: std::cell::Cell<(u64, u64)> = const { std::cell::Cell::new((0, 0)) }; +} + +fn thread_id() -> u32 { + // SAFETY: a plain query. + unsafe { windows_sys::Win32::System::Threading::GetCurrentThreadId() } +} + +fn micros(t: windows_sys::Win32::Foundation::FILETIME) -> u64 { + (u64::from(t.dwHighDateTime) << 32 | u64::from(t.dwLowDateTime)) / 10 +} + +/// This thread's processor time so far (user, kernel), in microseconds. +fn thread_times() -> (u64, u64) { + use windows_sys::Win32::Foundation::FILETIME; + use windows_sys::Win32::System::Threading::{GetCurrentThread, GetThreadTimes}; + let zero = FILETIME { dwLowDateTime: 0, dwHighDateTime: 0 }; + let (mut created, mut exited, mut kernel, mut user) = (zero, zero, zero, zero); + // SAFETY: our own thread and four valid out pointers. + unsafe { GetThreadTimes(GetCurrentThread(), &mut created, &mut exited, &mut kernel, &mut user) }; + (micros(user), micros(kernel)) +} + +/// The process's processor time so far (user, kernel), in microseconds. +fn process_times() -> (u64, u64) { + use windows_sys::Win32::Foundation::FILETIME; + use windows_sys::Win32::System::Threading::{GetCurrentProcess, GetProcessTimes}; + let zero = FILETIME { dwLowDateTime: 0, dwHighDateTime: 0 }; + let (mut created, mut exited, mut kernel, mut user) = (zero, zero, zero, zero); + // SAFETY: our own process and four valid out pointers. + unsafe { GetProcessTimes(GetCurrentProcess(), &mut created, &mut exited, &mut kernel, &mut user) }; + (micros(user), micros(kernel)) +} + +fn submitter(all: &mut Vec<(u32, Submitter)>, id: u32) -> &mut Submitter { + let at = match all.iter().position(|s| s.0 == id) { + Some(at) => at, + None => { + all.push((id, Submitter::default())); + all.len() - 1 + } + }; + &mut all[at].1 +} + +/// A list call on this thread that began at `started` has returned. +pub(crate) fn recorded(started: std::time::Instant) { + let ns = started.elapsed().as_nanos() as u64; + add(C::RecordCalls, 1); + add(C::RecordNs, ns); + crate::framelog::add(crate::framelog::T::RecordCalls, 1); + crate::framelog::add(crate::framelog::T::RecordNs, ns); + crate::framelog::here(crate::framelog::H::RecordNs, ns); + if !RECORDED_SINCE.load(Relaxed) && !RECORDED_SINCE.swap(true, Relaxed) { + let began = now_us().saturating_sub(ns / 1000); + add(C::UntilRecordUs, began.saturating_sub(PRESENTED_AT.load(Relaxed))); + } + OURS.with(|o| o.set(o.get() + ns)); + let (unsent, calls) = UNSENT.with(|u| u.get()); + let (unsent, calls) = (unsent + ns, calls + 1); + // By thread, a couple of milliseconds at a time. + if unsent < 2_000_000 { + UNSENT.with(|u| u.set((unsent, calls))); + return; + } + UNSENT.with(|u| u.set((0, 0))); + if crate::framelog::on() { + crate::framelog::add(crate::framelog::T::RecordLooks, 1); + if crate::framelog::on_slow_core() { + crate::framelog::add(crate::framelog::T::RecordSlow, 1); + } + } + let id = thread_id(); + let mut all = RECORDERS.lock().unwrap_or_else(|e| e.into_inner()); + match all.iter_mut().find(|r| r.0 == id) { + Some(r) => (r.1, r.2) = (r.1 + unsent, r.2 + calls), + None => all.push((id, unsent, calls)), + } +} + +/// A submission is called on this thread (before it waits for the +/// submission lock). +pub(crate) fn submission_begins() { + let now = now_us(); + if !SUBMITTED_SINCE.load(Relaxed) && !SUBMITTED_SINCE.swap(true, Relaxed) { + add(C::UntilSubmitUs, now.saturating_sub(PRESENTED_AT.load(Relaxed))); + } + let (user, kernel) = thread_times(); + ENTERED.with(|e| e.set((user, kernel))); + let ours = OURS.with(|o| o.replace(0)); + if let Some((left, u, k)) = LEFT.with(|l| l.get()) { + let mut all = SUBMITTERS.lock().unwrap_or_else(|e| e.into_inner()); + let s = submitter(&mut all, thread_id()); + s.between += now.saturating_sub(left); + s.between_user += user.saturating_sub(u); + s.between_kernel += kernel.saturating_sub(k); + s.between_ours += ours; + } +} + +/// The submission returns; it waited `lock` microseconds for the +/// submission lock. +pub(crate) fn submission_ends(lock: u64) { + let now = now_us(); + SUBMITTED_AT.store(now, Relaxed); + let (user, kernel) = thread_times(); + let (u, k) = ENTERED.with(|e| e.get()); + LEFT.with(|l| l.set(Some((now, user, kernel)))); + OURS.with(|o| o.set(0)); + let mut all = SUBMITTERS.lock().unwrap_or_else(|e| e.into_inner()); + let s = submitter(&mut all, thread_id()); + s.submissions += 1; + s.lock += lock; + s.inside_user += user.saturating_sub(u); + s.inside_kernel += kernel.saturating_sub(k); +} + +/// The title calls its present (before our own copy to the window runs). +pub(crate) fn present_begins() { + add(C::TailUs, now_us().saturating_sub(SUBMITTED_AT.load(Relaxed))); +} + +/// A frame was presented. +pub(crate) fn presented() { + add(C::Frames, 1); + PRESENTED_AT.store(now_us(), Relaxed); + RECORDED_SINCE.store(false, Relaxed); + SUBMITTED_SINCE.store(false, Relaxed); +} + +fn page_faults() -> u64 { + use windows_sys::Win32::System::ProcessStatus::{ + K32GetProcessMemoryInfo, PROCESS_MEMORY_COUNTERS, + }; + use windows_sys::Win32::System::Threading::GetCurrentProcess; + let mut c = PROCESS_MEMORY_COUNTERS { + cb: size_of::() as u32, + ..Default::default() + }; + // SAFETY: our own process and a sized structure. + unsafe { K32GetProcessMemoryInfo(GetCurrentProcess(), &mut c, c.cb) }; + u64::from(c.PageFaultCount) +} + +/// Logs the counters per frame, and the ranges that took most bytes. The +/// counters run from line to line, so they are divided by the frames +/// presented since the last line, not by `frames` (the frames of the last +/// second or more: a 4 s frame after an unlogged 4 s frame showed two +/// frames' counts as one's). +pub(crate) fn log(frames: f64) { + let counted = COUNT[C::Frames as usize].swap(0, Relaxed); + let frames = if counted > 0 { counted as f64 } else { frames }; + static FAULTS: AtomicU64 = AtomicU64::new(0); + let faults = page_faults(); + let faults = faults - FAULTS.swap(faults, Relaxed).min(faults); + let c: Vec = COUNT + .iter() + .map(|a| a.swap(0, Relaxed) as f64 / frames) + .collect(); + let mb = |v: f64| v / 1e6; + let ms = |v: f64| v / 1e3; + tracing::info!( + "copies per frame: {:.1} submissions; {:.0} title copies {:.1} MB; {:.0} refreshes {:.1} MB, \ + {:.0} skipped {:.1} MB; {:.0} runs {:.1} ms; {:.0} queries {:.2} ms, moves {:.2} ms, \ + {:.2} MB unmapped; {:.0} page faults; {:.0} watches {:.2} ms, {:.1} MB checked, {:.1} MB \ + unchanged; {:.1} fallbacks; {:.0} guard faults; textures {:.1} MB watched and \ + changed, {:.1} MB hashed, {:.1} MB of them changed", + c[C::Submissions as usize], + c[C::Copies as usize], + mb(c[C::CopyBytes as usize]), + c[C::Refreshes as usize], + mb(c[C::RefreshBytes as usize]), + c[C::Skipped as usize], + mb(c[C::SkippedBytes as usize]), + c[C::Runs as usize], + ms(c[C::RunUs as usize]), + c[C::Queries as usize], + ms(c[C::QueryUs as usize]), + ms(c[C::MoveUs as usize]), + mb(c[C::Unmapped as usize]), + faults as f64 / frames, + c[C::Watches as usize], + ms(c[C::WatchUs as usize]), + mb(c[C::Checked as usize]), + mb(c[C::Unchanged as usize]), + c[C::Fallbacks as usize], + c[C::GuardFaults as usize], + mb(c[C::TexWatched as usize]), + mb(c[C::TexHashed as usize]), + mb(c[C::TexChanged as usize]), + ); + tracing::info!( + "recording per frame ({frames:.0} frames): {:.0} list calls {:.1} ms (all recording \ + threads); {:.1} ms waiting for pipelines; dynamic slots: {:.0} tables asked, {:.0} \ + refused, {:.1} ms searching; notes {:.1} ms; shader-written ranges: {:.0} steps in \ + {:.1} submissions, snapshots {:.1} ms, {:.1} MB compared back; sparse reads {:.1} ms; \ + guards {:.1} ms; {:.1} MB copied whole (memory not watched); {:.1} frame waits \ + sleeping {:.1} ms (all threads); ranges of shaders that cannot store to buffers: \ + {:.0} steps {:.1} MB left out", + c[C::RecordCalls as usize], + c[C::RecordNs as usize] / 1e6, + ms(c[C::PipelineWaitUs as usize]), + c[C::DynamicAsked as usize], + c[C::DynamicRefused as usize], + c[C::DynamicNs as usize] / 1e6, + c[C::NoteNs as usize] / 1e6, + c[C::GpuWrites as usize], + c[C::BackSubmissions as usize], + ms(c[C::SnapshotUs as usize]), + mb(c[C::BackCompared as usize]), + ms(c[C::SparseUs as usize]), + ms(c[C::GuardUs as usize]), + mb(c[C::WholeBytes as usize]), + c[C::PaceWaits as usize], + ms(c[C::PaceUs as usize]), + c[C::GpuWritesLeftOut as usize], + mb(c[C::GpuWritesLeftOutBytes as usize]), + ); + let [together, written, mapped] = + [0, 1, 2].map(|n| crate::watch::ALIASES[n].load(std::sync::atomic::Ordering::Relaxed)); + tracing::info!( + "guards over several views of a page, since the start: {together} blocks guarded with their other views, \ + {written} views opened by a write through another, {mapped} ranges opened because a view of them was mapped" + ); + // Where the wall clock of a frame goes: the phases of a frame, the + // processor time of the whole process, and what each submitting and + // recording thread did. + static CPU: Mutex<(u64, u64)> = Mutex::new((0, 0)); + let (user, kernel) = process_times(); + let (user, kernel) = { + let mut last = CPU.lock().unwrap_or_else(|e| e.into_inner()); + let spent = (user.saturating_sub(last.0), kernel.saturating_sub(last.1)); + *last = (user, kernel); + (spent.0 as f64 / 1e3 / frames, spent.1 as f64 / 1e3 / frames) + }; + tracing::info!( + "frame account per frame: after a present {:.1} ms until the first list call and {:.1} ms \ + until the first submission; {:.1} ms from the last submission to the present call; \ + lists reset in {:.1} ms; the process ran {user:.0} ms user + {kernel:.0} ms kernel on \ + all threads; what shaders wrote: {:.1} ms finding {:.0} pieces that differ, {:.1} ms \ + putting them back; texture uploads: {:.0} recorded, {:.0} left out; {:.1} held \ + submissions run at the present with their waits not met; waits for memory values: \ + {:.0} looks {:.1} ms; {:.0} host lists made {:.1} ms; {:.0} parts of held submissions \ + ran alone that the next part could have run with", + ms(c[C::UntilRecordUs as usize]), + ms(c[C::UntilSubmitUs as usize]), + ms(c[C::TailUs as usize]), + c[C::ResetNs as usize] / 1e6, + ms(c[C::BackScanUs as usize]), + c[C::BackDiffer as usize], + ms(c[C::BackSyncUs as usize]), + c[C::TexUploads as usize], + c[C::TexSkipped as usize], + c[C::Forced as usize], + c[C::WaitChecks as usize], + c[C::WaitCheckNs as usize] / 1e6, + c[C::HostLists as usize], + c[C::HostListNs as usize] / 1e6, + c[C::PartsTogether as usize], + ); + // What is copied whole, largest first: memory nobody tells us about. + let whole = WHOLE.lock().unwrap_or_else(|e| e.into_inner()).take(); + let mut whole: Vec<_> = whole.into_iter().flatten().collect(); + whole.sort_by_key(|&((_, len), (n, _))| std::cmp::Reverse(len as u64 * n)); + tracing::info!( + " copied whole (memory not watched): {:.1} ms per frame in {} ranges; the largest follow", + ms(c[C::WholeUs as usize]), + whole.len() + ); + for ((src, len), (n, us)) in whole.into_iter().take(6) { + tracing::info!( + " copied whole from {src:#x}+{len:#x}: {:.1}x/frame, {:.2} MB/frame, {:.2} ms/frame", + n as f64 / frames, + (len as u64 * n) as f64 / 1e6 / frames, + us as f64 / 1e3 / frames + ); + } + // The waiting for the card: many short waits or a few long ones, how + // much of it is for submissions the title gets nothing back from, and + // the longest one. + let longest = std::mem::take(&mut *LONGEST.lock().unwrap_or_else(|e| e.into_inner())); + tracing::info!( + " waiting for the card per frame: {:.1} submissions under 2 ms ({:.1} ms), {:.1} of 2-8 ms \ + ({:.1} ms), {:.1} of 8-32 ms ({:.1} ms), {:.1} longer ({:.1} ms); {:.1} submissions hand \ + nothing back to the title ({:.1} ms of the waiting); the longest since the last line: \ + {:.1} ms, {}", + c[C::CardUnder2 as usize], + ms(c[C::CardUnder2Us as usize]), + c[C::Card2To8 as usize], + ms(c[C::Card2To8Us as usize]), + c[C::Card8To32 as usize], + ms(c[C::Card8To32Us as usize]), + c[C::CardOver32 as usize], + ms(c[C::CardOver32Us as usize]), + c[C::NothingBack as usize], + ms(c[C::NothingBackUs as usize]), + longest.0 as f64 / 1e3, + longest.1 + ); + let by = WAITS_BY_WORK.lock().unwrap_or_else(|e| e.into_inner()).take(); + let mut by: Vec<_> = by.into_iter().flatten().collect(); + by.sort_by_key(|&(_, (_, us))| std::cmp::Reverse(us)); + for (what, (n, us)) in by.into_iter().take(12) { + tracing::info!( + " the card's time by what ran: {:.1} ms a frame in {:.1} submissions a frame: {}", + us as f64 / 1e3 / frames, + n as f64 / frames, + what.chars().take(700).collect::() + ); + } + let by = COMMANDS_BY_WORK.lock().unwrap_or_else(|e| e.into_inner()).take(); + let mut by: Vec<_> = by.into_iter().flatten().collect(); + by.sort_by_key(|&(_, (_, us, _))| std::cmp::Reverse(us)); + // All of them together, and by their first word: the forty lines below + // are the heaviest only (100 of 226 ms waited in run 102), and what the + // commands do not account for is the layer's own lists (the card + // copies' passes, preludes) and the waits themselves. + if !by.is_empty() { + let mut kinds: Vec<(String, u64, u64)> = Vec::new(); + for (what, (n, us, _)) in &by { + let word = what.split(' ').next().unwrap_or("").to_owned(); + match kinds.iter_mut().find(|k| k.0 == word) { + Some(k) => (k.1, k.2) = (k.1 + n, k.2 + us), + None => kinds.push((word, *n, *us)), + } + } + kinds.sort_by_key(|k| std::cmp::Reverse(k.2)); + let all: u64 = kinds.iter().map(|k| k.2).sum(); + let text: Vec = + kinds.iter().map(|(word, n, us)| format!("{word} {:.1} ms in {:.0}", *us as f64 / 1e3 / frames, *n as f64 / frames)).collect(); + tracing::info!( + " the card's time by command (timing run), all {} kinds together: {:.1} ms a frame; by first word: {}", + by.len(), + all as f64 / 1e3 / frames, + text.join(", ") + ); + } + for (what, (n, us, longest)) in by.into_iter().take(40) { + tracing::info!( + " the card's time by command (timing run): {:.2} ms a frame in {:.1} commands a frame, the longest {:.2} ms: {what}", + us as f64 / 1e3 / frames, + n as f64 / frames, + longest as f64 / 1e3 + ); + } + tracing::info!( + " write-watch askings per frame that failed in the kernel: {:.0}; not made because the range \ + is known guarded view memory: {:.0} (LEONIDA_VIEW_ASK=1 asks the kernel anyway); such ranges left \ + out of the submissions' askings ahead: {:.0}", + c[C::WatchFailed as usize], + c[C::WatchKnownView as usize], + crate::watch::AHEAD_VIEWS.swap(0, Relaxed) as f64 / frames, + ); + crate::draw::window_line(frames); + tracing::info!( + " waits for every earlier shader write, per frame: {:.0} for the title's barrier groups, {:.0} \ + for its barriers on buffers; {:.0} indirect commands bounded (a dispatch of ours between two \ + such waits each); barrier experiment {}", + c[C::WaitsForGroups as usize], + c[C::WaitsForBuffers as usize], + c[C::IndirectBounded as usize], + barrier_test() + ); + // What is compared after submissions, largest first, and how much of + // it shaders had written. + let compared = COMPARED.lock().unwrap_or_else(|e| e.into_inner()).take(); + let mut compared: Vec<_> = compared.into_iter().flatten().collect(); + compared.sort_by_key(|&((_, len), (n, _))| std::cmp::Reverse(len as u64 * n)); + tracing::info!(" compared after submissions: {} ranges; the largest follow", compared.len()); + for ((src, len), (n, written)) in compared.into_iter().take(8) { + tracing::info!( + " compared {src:#x}+{len:#x}: {:.1}x/frame, {:.2} MB/frame, {:.3} MB/frame of it written back", + n as f64 / frames, + (len as u64 * n) as f64 / 1e6 / frames, + written as f64 / 1e6 / frames + ); + } + let mut submitters = std::mem::take(&mut *SUBMITTERS.lock().unwrap_or_else(|e| e.into_inner())); + submitters.sort_by_key(|s| std::cmp::Reverse(s.1.submissions)); + for (id, s) in submitters.into_iter().take(4) { + let per = |v: u64| v as f64 / 1e3 / frames; + tracing::info!( + " thread {id} submitted {:.1}x/frame: between its submissions {:.1} ms (running \ + {:.1} ms user + {:.1} ms kernel; {:.1} ms in list calls), in them running {:.1} ms \ + user + {:.1} ms kernel, {:.1} ms waiting for the submission lock", + s.submissions as f64 / frames, + per(s.between), + per(s.between_user), + per(s.between_kernel), + s.between_ours as f64 / 1e6 / frames, + per(s.inside_user), + per(s.inside_kernel), + per(s.lock), + ); + } + let mut recorders = std::mem::take(&mut *RECORDERS.lock().unwrap_or_else(|e| e.into_inner())); + recorders.sort_by_key(|r| std::cmp::Reverse(r.1)); + let busiest: Vec = recorders + .iter() + .take(6) + .map(|r| format!("thread {} {:.0} ms in {:.0} calls", r.0, r.1 as f64 / 1e6 / frames, r.2 as f64 / frames)) + .collect(); + tracing::info!(" list calls by thread: {} threads; {}", recorders.len(), busiest.join(", ")); + log_memory(); + let ranges = RANGES.lock().unwrap_or_else(|e| e.into_inner()).take(); + let mut ranges: Vec<_> = ranges.into_iter().flatten().collect(); + ranges.sort_by_key(|&(_, (_, bytes, _, _))| std::cmp::Reverse(bytes)); + for ((src, len), (n, bytes, us, _)) in ranges.into_iter().take(10) { + use windows_sys::Win32::System::Memory::{MEMORY_BASIC_INFORMATION, VirtualQuery}; + // SAFETY: plain data filled in by the query. + let mut info: MEMORY_BASIC_INFORMATION = unsafe { std::mem::zeroed() }; + // SAFETY: a valid out pointer of the right size. + unsafe { VirtualQuery(src as *const _, &mut info, size_of_val(&info)) }; + let kind = info.Type; + tracing::info!( + " copied from {src:#x}+{len:#x} (memory {kind:#x}): {:.1}x/frame, {:.2} MB/frame, {:.2} ms/frame", + n as f64 / frames, + bytes as f64 / 1e6 / frames, + us as f64 / 1e3 / frames + ); + } +} diff --git a/crates/leonida-gpu/src/descriptor.rs b/crates/leonida-gpu/src/descriptor.rs new file mode 100644 index 000000000..35ec273b9 --- /dev/null +++ b/crates/leonida-gpu/src/descriptor.rs @@ -0,0 +1,1449 @@ +//! Descriptor heaps: zeroed memory, with handles that are plain addresses +//! (CPU and GPU alike, as on the console). +//! +//! Descriptor sizes: views 32 bytes and samplers 16, the size of RDNA 2's +//! image and sampler descriptors, so a title that copies descriptors itself +//! moves whole ones. Render target and depth views are ours alone; 128 bytes +//! leaves room for whatever stride a title assumes. +#![allow(clippy::not_unsafe_ptr_arg_deref)] + +use crate::object::{self, DESCRIPTOR_HEAP, E_INVALIDARG, HRESULT, Iid, Object, Table, This, guid}; +use crate::resource::{Memory, PAGEABLE_IIDS}; + +#[cfg(windows)] +pub(crate) mod host; + +const HEAP_IIDS: [Iid; 4] = [ + guid( + 0x8efb471d, + 0x616c, + 0x4f49, + [0x90, 0xf7, 0x12, 0x7b, 0xb7, 0x63, 0xfa, 0x51], + ), + PAGEABLE_IIDS[0], + PAGEABLE_IIDS[1], + PAGEABLE_IIDS[2], +]; + +#[repr(C)] +#[derive(Debug, Clone, Copy)] +pub(crate) struct HeapDesc { + kind: u32, + count: u32, + flags: u32, + nodes: u32, +} + +/// Newer titles (the title) pass the description followed by +/// memory of their own for the descriptors: an address and its size in +/// bytes, or a null address to have the heap allocate (inferred from the +/// title's call sites; older titles pass the plain description). +#[repr(C)] +#[derive(Debug, Clone, Copy)] +struct Placement { + address: u64, + size: u64, +} + +#[repr(C)] +pub(crate) struct Heap { + object: Object, + desc: HeapDesc, + /// The first descriptor: in `memory`, or in the title's own memory. + pub(crate) start: u64, + memory: Option, + /// Shader-visible view and sampler heaps get a host heap with the same + /// descriptor order when a draw first uses them (decision 0007, step + /// 3); slots written before wait in `pending`. + #[cfg(windows)] + host: std::sync::OnceLock>, + #[cfg(windows)] + pending: std::sync::Mutex>, + /// Changed pages of a placed shader-visible heap. Some titles copy + /// descriptor records into it as bytes, without a descriptor API call. + #[cfg(windows)] + written: Option, +} + +pub(crate) fn heap<'a>(this: This) -> &'a Heap { + // SAFETY: called from descriptor heap methods only. + unsafe { &*this.cast::() } +} + +impl Heap { + /// Whether this is a sampler heap. + pub(crate) fn samplers(&self) -> bool { + self.desc.kind == SAMPLERS + } + + /// The host heap, made on first use from what the title wrote so far. + /// Made late because a host view heap the size of the title's + /// costs over 100 MB of commit, which its boot needs for its page pool. + #[cfg(windows)] + pub(crate) fn host(&self) -> Option<&host::HostHeap> { + if let Some(h) = self.host.get() { + return h.as_ref(); + } + if self.desc.flags & SHADER_VISIBLE == 0 || !matches!(self.desc.kind, VIEWS_KIND | SAMPLERS) + { + return None; + } + let mut pending = self.pending.lock().unwrap_or_else(|e| e.into_inner()); + // A recorder can take the fast path as soon as the OnceLock is + // initialized. Publish only after replaying the queued writes. + self.host + .get_or_init(|| { + let step = u64::from(increment(self.desc.kind)?); + let h = host::HostHeap::new(self.samplers(), self.desc.count)?; + for i in pending.drain(..) { + h.mirror(i, self.start + u64::from(i) * step, false); + } + Some(h) + }) + .as_ref() + } + + /// The handle of descriptor `index` of this heap. + #[cfg(windows)] + pub(crate) fn handle(&self, index: u32) -> Option { + let step = u64::from(increment(self.desc.kind)?); + (index < self.desc.count).then(|| self.start + u64::from(index) * step) + } + + /// The descriptor index of `handle` in this heap, if it lies in it. + pub(crate) fn index(&self, handle: u64) -> Option { + let step = u64::from(increment(self.desc.kind)?); + let at = handle.checked_sub(self.start)?; + let index = at / step; + (index < u64::from(self.desc.count)).then_some(index as u32) + } +} + +const VIEWS_KIND: u32 = 0; +const SAMPLERS: u32 = 1; +const SHADER_VISIBLE: u32 = 1; + +/// Shader-visible heaps by address range, for mirroring descriptor writes: +/// start, end, heap. +/// +/// Read by every lookup and by [`sync_heaps`], written only when a heap is +/// made or dropped. It was a mutex, and [`sync_heaps`] holds it for its +/// whole pass (15 ms a frame on the submitting thread): the profile of run +/// 225 has the title's six recording threads waiting 48.5 ms a frame in +/// [`shader_slot`] for it, each lookup itself a few nanoseconds. Readers no +/// longer wait for each other. Nothing a holder calls takes it again. +#[cfg(windows)] +static SHADER_HEAPS: std::sync::RwLock> = std::sync::RwLock::new(Vec::new()); + +/// One [`sync_heaps`] at a time, as when the list above was a mutex. +#[cfg(windows)] +static SYNCING: std::sync::Mutex<()> = std::sync::Mutex::new(()); + +/// The shader-visible heap holding `handle`, and the descriptor's index. +#[cfg(windows)] +fn shader_slot<'a>(handle: u64) -> Option<(&'a Heap, u32)> { + let heaps = SHADER_HEAPS.read().unwrap_or_else(|e| e.into_inner()); + let &(_, _, at) = heaps + .iter() + .find(|&&(start, end, _)| (start..end).contains(&handle))?; + // SAFETY: registered heaps are live (removed when dropped). + let heap = unsafe { &*(at as *const Heap) }; + Some((heap, heap.index(handle)?)) +} + +/// Makes the host descriptor for what the title wrote at `handle`, if it +/// is in a shader-visible heap. +#[cfg(windows)] +fn mirror(handle: u64) { + let Some((heap, index)) = shader_slot(handle) else { + return; + }; + let mut pending = heap.pending.lock().unwrap_or_else(|e| e.into_inner()); + match heap.host.get() { + None => pending.push(index), + Some(host) => { + drop(pending); + if let Some(host) = host { + host.mirror(index, handle, false); + } + } + } +} + +/// Mirrors records copied directly into placed shader-visible heaps. Calls +/// to `Create*View` are already mirrored by [`mirror`]; raw CPU copies leave +/// only write-watch pages to reveal which slots changed. +/// +/// Upstream VIctory 86a5ed6 does the same and counts 1,300 to 14,400 such +/// slots a frame in the world of the title this fork works on, against a +/// few hundred views made by calls; without it those host slots stayed +/// null, or went on showing what they showed before. +/// `LEONIDA_HEAP_SYNC=0`: not done, as before. [`SYNCED`] counts. +#[cfg(windows)] +pub(crate) fn sync_heaps() { + use std::sync::atomic::Ordering::Relaxed; + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + if !*ON.get_or_init(|| std::env::var_os("LEONIDA_HEAP_SYNC").is_none_or(|v| v != "0")) { + return; + } + let started = std::time::Instant::now(); + let (mut pages, mut looked, mut mirrored) = (0u64, 0u64, 0u64); + let mut page_bytes: Vec = Vec::new(); + let _one = SYNCING.lock().unwrap_or_else(|e| e.into_inner()); + let heaps = SHADER_HEAPS.read().unwrap_or_else(|e| e.into_inner()); + for &(start, end, at) in heaps.iter() { + // SAFETY: registered heaps are live (removed when dropped). + let heap = unsafe { &*(at as *const Heap) }; + let (Some(Some(host)), Some(written), Some(step)) = + (heap.host.get(), &heap.written, increment(heap.desc.kind)) + else { + continue; + }; + let step = u64::from(step); + // Capped host heaps have no counterparts for the title slots reserved + // for per-draw tables; raw writes there must not be mirrored. + let mirrored_count = heap.desc.count.min(host.count()); + for (range_from, range_end) in written.take(start as usize, end as usize) { + let mut page = range_from & !(crate::watch::PAGE - 1); + while page < range_end { + let from = page.max(range_from); + let to = (page + crate::watch::PAGE).min(range_end); + // The page's records are read through the kernel, into a + // copy: a page the title unmaps meanwhile fails the read + // where 2,048 reads in place would fault. + page_bytes.resize(to - from, 0); + if crate::host::read_into(from as *const u8, &mut page_bytes) { + pages += 1; + let slots = changed_slots(from, to, start as usize, step, mirrored_count); + // The page's records in one go, under one lock + // (`HostHeap::mirror_copied_page`); one by one below + // with `LEONIDA_HEAP_SYNC_PAGE=0`. + let slots = if page_at_once() { + let (seen, made) = host.mirror_copied_page(slots, (start, step), from, &page_bytes); + looked += seen; + mirrored += made; + 0..0 + } else { + slots + }; + for index in slots { + let handle = start + index * step; + // A record that straddles the range's ends is left + // to the range that holds its first byte. + let Some(at) = (handle as usize).checked_sub(from) else { + continue; + }; + let Some(record) = page_bytes.get(at..at + step as usize) else { + continue; + }; + looked += 1; + // Only a record that is not the one last seen there + // (`HostHeap::mirror_copied`). + if host.mirror_copied(index as u32, handle, record) { + mirrored += 1; + } + } + } + page += crate::watch::PAGE; + } + } + } + drop(heaps); + for (count, n) in SYNCED.iter().zip([pages, looked, mirrored, started.elapsed().as_micros() as u64]) { + count.fetch_add(n, Relaxed); + } +} + +/// Since the last frame line, of [`sync_heaps`]: changed pages of placed +/// shader-visible heaps looked at, slots on them, slots whose record was +/// not the one last seen (mirrored), and the microseconds it took. +#[cfg(windows)] +pub(crate) static SYNCED: [std::sync::atomic::AtomicU64; 4] = [const { std::sync::atomic::AtomicU64::new(0) }; 4]; + +/// With the frame line: what [`sync_heaps`] did per frame over `frames`. +/// Nothing while no heap page changed. +#[cfg(windows)] +pub(crate) fn sync_line(frames: f64) { + let [pages, looked, mirrored, micros] = [0, 1, 2, 3].map(|i| SYNCED[i].swap(0, std::sync::atomic::Ordering::Relaxed)); + if pages == 0 { + return; + } + tracing::info!( + "descriptor records the title copied into its heap as bytes (LEONIDA_HEAP_SYNC=0: not looked for): per frame \ + {:.1} changed heap pages, {:.0} slots looked at, {:.1} whose record was new and was mirrored, {:.0} left to the \n draws that read them through tables (LEONIDA_HEAP_SYNC_TABLES=1 mirrors those too), {:.2} ms", + pages as f64 / frames, + looked as f64 / frames, + mirrored as f64 / frames, + host::COPIED_TABLED.swap(0, std::sync::atomic::Ordering::Relaxed) as f64 / frames, + micros as f64 / 1000.0 / frames + ); +} + +/// Whether [`sync_heaps`] hands a changed page's records to the host heap +/// in one go (`host::HostHeap::mirror_copied_page`). On by default: the +/// same records are mirrored either way. `LEONIDA_HEAP_SYNC_PAGE=0`: one +/// by one, as before. +#[cfg(windows)] +fn page_at_once() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("LEONIDA_HEAP_SYNC_PAGE").is_none_or(|v| v != "0")) +} + +/// Title descriptor slots in a changed byte range that have host counterparts. +/// `range_end` is exclusive. +#[cfg(windows)] +fn changed_slots( + range_from: usize, + range_end: usize, + heap_start: usize, + step: u64, + mirrored_count: u32, +) -> std::ops::Range { + let from = (range_from - heap_start) as u64; + let to = (range_end - heap_start) as u64; + let first = from / step; + let last = to.div_ceil(step).min(u64::from(mirrored_count)); + first.min(last)..last +} + +/// Gives back dynamic slots of the host heap behind the title heap at +/// `heap`, if that heap still exists. +#[cfg(windows)] +pub(crate) fn release_dynamic(heap: usize, first: u32, n: u32) { + let heaps = SHADER_HEAPS.read().unwrap_or_else(|e| e.into_inner()); + if heaps.iter().any(|&(_, _, h)| h == heap) + // SAFETY: registered heaps are live (removed when dropped). + && let Some(Some(host)) = unsafe { &*(heap as *const Heap) }.host.get() + { + host.release(first, n); + } +} + +#[cfg(windows)] +impl Drop for Heap { + fn drop(&mut self) { + let at = std::ptr::from_ref::(self) as usize; + let mut heaps = SHADER_HEAPS.write().unwrap_or_else(|e| e.into_inner()); + heaps.retain(|&(_, _, h)| h != at); + } +} + +/// Bytes per descriptor, by heap type (views, samplers, render targets, +/// depth). +fn increment(kind: u32) -> Option { + [32, 16, 128, 128].get(kind as usize).copied() +} + +/// Device method. +pub(crate) extern "system" fn increment_size(_: This, kind: u32) -> u32 { + increment(kind).unwrap_or(0) +} + +/// What our render target views hold: the resource and the view +/// description, turned into a host view when a command uses them. +#[repr(C)] +#[derive(Clone, Copy)] +pub(crate) struct RtvRecord { + tag: u32, + described: u32, + pub(crate) resource: This, + desc: [u32; 6], +} +const RTV_TAG: u32 = u32::from_le_bytes(*b"vRTV"); +const _: () = assert!(size_of::() <= 112); + +impl RtvRecord { + /// The view description in the host's type (the same layout). + #[cfg(windows)] + pub(crate) fn desc( + &self, + ) -> Option { + const TEXTURE_2D: u32 = 4; + self.host_desc(TEXTURE_2D) + } + + /// The depth view description in the host's type (the same layout). + #[cfg(windows)] + pub(crate) fn depth_desc( + &self, + ) -> Option { + const TEXTURE_2D: u32 = 3; + self.host_desc(TEXTURE_2D) + } + + /// The description words as a host type, the format as the host has it. + /// Without one, a typeless host copy gets a 2D view (`dimension`) in + /// the title's format, which the host needs spelled out. + #[cfg(windows)] + fn host_desc(&self, dimension: u32) -> Option { + assert!(size_of::() <= size_of::<[u32; 6]>()); + let mut words = if self.described != 0 { + self.desc + } else { + [ + crate::resource::view_format(self.resource)?, + dimension, + 0, + 0, + 0, + 0, + ] + }; + // A target or depth view: of a target, in its stand-in format. + words[0] = crate::resource::target_format(crate::resource::pc_format(words[0])); + // SAFETY: both host view descriptions are 24 bytes in this layout. + Some(unsafe { (&raw const words).cast::().read_unaligned() }) + } +} + +/// Device method: records the view at `handle` (descriptor memory). +pub(crate) extern "system" fn create_rtv( + _: This, + resource: This, + desc: *const [u32; 6], + handle: u64, +) { + if handle == 0 { + return; + } + // SAFETY: the title passes a description or null. + let described = unsafe { desc.as_ref() }; + let record = RtvRecord { + tag: RTV_TAG, + described: u32::from(described.is_some()), + resource, + desc: described.copied().unwrap_or_default(), + }; + // SAFETY: the handle is a descriptor slot, at least 112 bytes. + unsafe { (handle as *mut RtvRecord).write_unaligned(record) }; +} + +/// Device method: a depth view, recorded as render target views are. +pub(crate) extern "system" fn create_dsv( + this: This, + resource: This, + desc: *const [u32; 6], + handle: u64, +) { + create_rtv(this, resource, desc, handle); + if handle != 0 { + // SAFETY: just written by `create_rtv`. + unsafe { (handle as *mut u32).write_unaligned(DSV_TAG) }; + } +} +const DSV_TAG: u32 = u32::from_le_bytes(*b"vDSV"); + +/// A shader view or sampler as the title described it (descriptions in the +/// host's layout, kept as words), for the host to build its own from. +#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)] +pub(crate) enum View { + /// Constant buffer: GPU address and size. + Constant(u64, u32), + /// Shader resource: resource, description (none: the resource's own). + Shader(usize, Option<[u32; 10]>), + /// Unordered access: resource, counter resource, description. + Unordered(usize, usize, Option<[u32; 10]>), + Sampler([u32; 13]), + /// The console's own sampler description: flags, filters per axis, + /// addressing, LOD and anisotropy settings, border color, then + /// console-only tuning words. + ConsoleSampler([u32; 27]), + /// A view of memory without a resource object: whether it is unordered + /// access, the resource description, then the view's (the plain one + /// followed by the memory address and console fields). + Placed(bool, [u32; 14], [u32; 16]), +} + +impl View { + /// Whether the view reads buffer memory (constant buffers, buffer views + /// of resources or of memory) or memory the title placed a texture in: + /// such views get host slots only for draws. + #[cfg(windows)] + fn is_buffer(&self) -> bool { + match self { + View::Constant(..) | View::Placed(..) => true, + View::Shader(r, _) | View::Unordered(r, _, _) => { + crate::resource::buffer_bytes(*r as This).is_some() + } + View::Sampler(_) | View::ConsoleSampler(_) => false, + } + } +} + +/// Every distinct view in use; a descriptor holds a tag, an index into it +/// and the entry's generation, which survive titles copying descriptors as +/// bytes. A view of a resource lives as long as the resource: when the +/// title releases it, its entries are freed for reuse under a new +/// generation, so descriptors (and host slots made from them) naming the +/// old one go stale instead of naming whatever is made at the same address +/// next. +/// +/// Views without a resource object have nothing that releases them, and a +/// title copies descriptors as bytes, so nothing says when the last +/// descriptor naming an entry is gone: such entries were kept for the run. +/// The title writes some 14,000 constant buffer views a frame, +/// each at the address its constants have that frame: 2,450,139 entries +/// after four minutes of play, 1,047 MB with the index, and 11,000 more +/// every second (run 65). So the two kinds that carry an address are not +/// entries any more: their records name them whole ([`constant_words`], +/// [`placed_words`]), and the table holds only what is bounded: views of +/// resource objects (freed with the resource), samplers (as many as there +/// are sampler states), and the shapes of placed views (their descriptions +/// without the address: as many as the title has kinds of textures and +/// buffers, however often it moves them). +/// `LEONIDA_VIEW_INLINE=0`: every view is an entry, as before. +struct Views { + /// Each entry's view and generation. + list: Vec<(View, u32)>, + index: std::collections::BTreeMap, + /// Entries naming each resource. + by_resource: std::collections::BTreeMap>, + free: Vec, + /// The shapes of views of placed memory, and where each is. + shapes: Vec, + shape_index: std::collections::BTreeMap, +} + +/// Read far more often than written: every slot a draw reads through a +/// table is looked up here, on several recording threads at once in the +/// world. Readers share it; only a view not seen before (a new table entry +/// or shape) and a released resource take it alone. +static VIEWS: std::sync::RwLock = std::sync::RwLock::new(Views { + list: Vec::new(), + index: std::collections::BTreeMap::new(), + by_resource: std::collections::BTreeMap::new(), + free: Vec::new(), + shapes: Vec::new(), + shape_index: std::collections::BTreeMap::new(), +}); +const VIEW_TAG: u32 = u32::from_le_bytes(*b"vVIE"); + +/// A record is the tag and two words, `i` and `generation` (the host keeps +/// them as one 64-bit key per slot). The top two bits of `generation` say +/// what the other 62 bits are: 0, entry `i` of the table at that +/// generation; [`CONSTANT`], a constant buffer view, whole; [`PLACED`], a +/// view of placed memory: its address and the number of its shape. +const KIND_SHIFT: u32 = 30; +/// Table generations stay below the kind bits (and above 0). +const GENERATIONS: u32 = (1 << KIND_SHIFT) - 1; +const CONSTANT: u32 = 1; +const PLACED: u32 = 2; +/// Bits of a constant buffer view's address in its record: any address a +/// program can have. The 15 bits above them are its size. +const CONSTANT_ADDRESS_BITS: u32 = 47; +/// Bits of a placed view's address in its record: placed memory is title +/// memory, which lies below 1 TiB. The 22 bits above them number its shape. +const PLACED_ADDRESS_BITS: u32 = 40; +const SHAPES: usize = 1 << (62 - PLACED_ADDRESS_BITS); + +/// A view of placed memory without its address: whether it is unordered +/// access, the resource description, and the view's words but the two that +/// hold the address (10 and 11). +type Shape = (bool, [u32; 14], [u32; 14]); + +/// Whether constant buffer views and views of placed memory are named whole +/// in their records ([`Views`]). On by default; `LEONIDA_VIEW_INLINE=0` +/// makes every view a table entry, as before. +fn inline() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("LEONIDA_VIEW_INLINE").is_none_or(|v| v != "0")) +} + +/// Views named whole in their records since the start: constant buffer +/// views, views of placed memory (for the memory line). +static NAMED_WHOLE: [std::sync::atomic::AtomicU64; 2] = [const { std::sync::atomic::AtomicU64::new(0) }; 2]; + +/// The two record words of the 62 bits `payload` of kind `kind`. +fn kind_words(kind: u32, payload: u64) -> [u32; 2] { + [payload as u32, kind << KIND_SHIFT | (payload >> 32) as u32] +} + +/// The 62 bits two record words carry beside their kind. +fn payload(i: u32, generation: u32) -> u64 { + u64::from(generation & GENERATIONS) << 32 | u64::from(i) +} + +/// The record words that name the constant buffer view of `size` bytes at +/// `address` whole; `None` if they cannot: an address past 47 bits, or a +/// size of 16 KiB or more that is no multiple of 256 or reaches 4 MiB (the +/// size has 15 bits: bytes below 16 KiB, else units of 256 bytes). Such a +/// view is a table entry. +fn constant_words(address: u64, size: u32) -> Option<[u32; 2]> { + if address >> CONSTANT_ADDRESS_BITS != 0 { + return None; + } + let code = if size < 1 << 14 { + u64::from(size) + } else if size.is_multiple_of(256) && size >> 8 < 1 << 14 { + 1 << 14 | u64::from(size >> 8) + } else { + return None; + }; + Some(kind_words(CONSTANT, code << CONSTANT_ADDRESS_BITS | address)) +} + +/// The constant buffer view [`constant_words`] named. +fn constant_of(i: u32, generation: u32) -> View { + let payload = payload(i, generation); + let code = (payload >> CONSTANT_ADDRESS_BITS) as u32; + let size = if code >> 14 == 0 { code } else { (code & 0x3fff) << 8 }; + View::Constant(payload & ((1 << CONSTANT_ADDRESS_BITS) - 1), size) +} + +/// A placed view's shape and its address. +fn shape_of(unordered: bool, resource: &[u32; 14], desc: &[u32; 16]) -> (Shape, u64) { + let mut rest = [0u32; 14]; + rest[..10].copy_from_slice(&desc[..10]); + rest[10..].copy_from_slice(&desc[12..]); + ( + (unordered, *resource, rest), + u64::from(desc[10]) | u64::from(desc[11]) << 32, + ) +} + +/// The record words that name the view of placed memory at `address` with +/// shape number `shape`. +fn placed_words(shape: u32, address: u64) -> [u32; 2] { + kind_words(PLACED, u64::from(shape) << PLACED_ADDRESS_BITS | address) +} + +impl Views { + /// The number of `shape`, a new one if it is not there yet; `None` when + /// the shapes are full (the view is then a table entry). + fn shape(&mut self, shape: Shape) -> Option { + if let Some(&at) = self.shape_index.get(&shape) { + return Some(at); + } + if self.shapes.len() >= SHAPES { + return None; + } + let at = self.shapes.len() as u32; + self.shapes.push(shape); + self.shape_index.insert(shape, at); + Some(at) + } + + /// The view of placed memory [`placed_words`] named. + fn placed_of(&self, i: u32, generation: u32) -> Option { + let payload = payload(i, generation); + let address = payload & ((1 << PLACED_ADDRESS_BITS) - 1); + let &(unordered, resource, rest) = self.shapes.get((payload >> PLACED_ADDRESS_BITS) as usize)?; + let mut desc = [0u32; 16]; + desc[..10].copy_from_slice(&rest[..10]); + (desc[10], desc[11]) = (address as u32, (address >> 32) as u32); + desc[12..].copy_from_slice(&rest[10..]); + Some(View::Placed(unordered, resource, desc)) + } + + /// The record words of `view` as a table entry, if it has one. + fn entry_of(&self, view: &View) -> Option<[u32; 2]> { + let &i = self.index.get(view)?; + Some([i, self.list[i as usize].1]) + } + + /// The record words of `view` as a table entry: its entry (a new or a + /// freed one if the view is not there yet) and that entry's generation. + fn entry(&mut self, view: View) -> [u32; 2] { + let i = match self.index.get(&view) { + Some(&i) => i, + None => { + let i = match self.free.pop() { + Some(i) => { + self.list[i as usize].0 = view.clone(); + i + } + None => { + self.list.push((view.clone(), 1)); + self.list.len() as u32 - 1 + } + }; + for r in view.resources().into_iter().filter(|&r| r != 0) { + self.by_resource.entry(r).or_default().push(i); + } + self.index.insert(view, i); + i + } + }; + [i, self.list[i as usize].1] + } +} + +/// The two words that name `view` in a record: the view itself where its +/// kind allows ([`Views`]), else its table entry. +fn words_for(view: View) -> [u32; 2] { + use std::sync::atomic::Ordering::Relaxed; + if inline() { + match &view { + View::Constant(address, size) => { + if let Some(words) = constant_words(*address, *size) { + NAMED_WHOLE[0].fetch_add(1, Relaxed); + return words; + } + } + View::Placed(unordered, resource, desc) => { + let (shape, address) = shape_of(*unordered, resource, desc); + if address >> PLACED_ADDRESS_BITS == 0 { + // Nearly every placed view has a shape seen before. + let known = views_read().shape_index.get(&shape).copied(); + let shape = known.or_else(|| views_write().shape(shape)); + if let Some(shape) = shape { + NAMED_WHOLE[1].fetch_add(1, Relaxed); + return placed_words(shape, address); + } + } + } + _ => {} + } + } + // A view written before keeps its entry and generation. + if let Some(words) = views_read().entry_of(&view) { + return words; + } + views_write().entry(view) +} + +fn views_read() -> std::sync::RwLockReadGuard<'static, Views> { + VIEWS.read().unwrap_or_else(|e| e.into_inner()) +} + +fn views_write() -> std::sync::RwLockWriteGuard<'static, Views> { + VIEWS.write().unwrap_or_else(|e| e.into_inner()) +} + +/// For the memory line: the distinct views kept ([`Views`]), those of them +/// free for reuse, and the bytes the table and its index hold for them (an +/// estimate: an entry of the table, and one of the index with its share of +/// a tree node; the shapes likewise); then the entries that are constant +/// buffer views and views of placed memory (those that did not fit a +/// record, or all of them with `LEONIDA_VIEW_INLINE=0`), the shapes of +/// placed views kept, and the views named whole in their records since the +/// start: constant buffer views, views of placed memory. +#[cfg(all(windows, feature = "diagnostics"))] +pub(crate) fn views_kept() -> [u64; 8] { + use std::sync::atomic::Ordering::Relaxed; + let views = views_read(); + let each = size_of::<(View, u32)>() as u64; + let shape = size_of::() as u64; + let (mut constants, mut placed) = (0, 0); + for (view, _) in &views.list { + match view { + View::Constant(..) => constants += 1, + View::Placed(..) => placed += 1, + _ => {} + } + } + [ + views.list.len() as u64, + views.free.len() as u64, + views.list.capacity() as u64 * each + + views.index.len() as u64 * each * 3 / 2 + + views.shapes.capacity() as u64 * shape + + views.shape_index.len() as u64 * shape * 3 / 2, + constants, + placed, + views.shapes.len() as u64, + NAMED_WHOLE[0].load(Relaxed), + NAMED_WHOLE[1].load(Relaxed), + ] +} + +impl View { + /// The resource objects the view names. + fn resources(&self) -> [usize; 2] { + match *self { + View::Shader(r, _) => [r, 0], + View::Unordered(r, counter, _) => [r, counter], + _ => [0, 0], + } + } + + /// The texture object the view is of, if that texture has no host copy + /// yet (`crate::resource::host_waits`): a slot written with such a + /// view is left null until the texture is first used. + #[cfg(windows)] + fn waiting_texture(&self) -> Option { + match *self { + View::Shader(r, _) | View::Unordered(r, _, _) + if crate::resource::host_waits(r as This) => + { + Some(r) + } + _ => None, + } + } +} + +/// Title slots (their handles) written with a view of a texture object +/// that had no host copy then, by texture. A title texture gets its host +/// copy on first use (`resource.rs` `Hosted`), and the title +/// writes each texture's views into its view heap when it creates the +/// texture: making those host slots would make every host copy at once. +/// They are made when the texture is: translated shaders index the heap +/// directly, so a slot is not always made again by the draw that reads it. +#[cfg(windows)] +static WAITING: std::sync::Mutex>> = + std::sync::Mutex::new(std::collections::BTreeMap::new()); + +/// Textures given their host copy since [`make_waiting`] last ran. +#[cfg(windows)] +static MADE_LATE: std::sync::Mutex> = std::sync::Mutex::new(Vec::new()); + +/// Title texture `resource` was given its host copy (called under that +/// texture's own lock: nothing else is locked here). +#[cfg(windows)] +pub(crate) fn texture_made(resource: usize) { + MADE_LATE + .lock() + .unwrap_or_else(|e| e.into_inner()) + .push(resource); +} + +/// The slot at `handle` was written with a view of texture `resource`, +/// which has no host copy: it waits for one. +#[cfg(windows)] +fn wait_for(resource: usize, handle: u64) { + /// A texture with more slots waiting than this is in use for all we + /// know (its views are being copied about): its host copy is made. + const MOST: usize = 64; + let many = { + let mut waiting = WAITING.lock().unwrap_or_else(|e| e.into_inner()); + let slots = waiting.entry(resource).or_default(); + if !slots.contains(&handle) { + slots.push(handle); + } + slots.len() > MOST + }; + if many { + // Makes it, and notes it made. + let _ = crate::resource::host_copy(resource as This); + } else if !crate::resource::host_waits(resource as This) { + // Made by another thread since the slot was looked at: that making + // may have been taken by `make_waiting` before this slot was noted. + texture_made(resource); + } +} + +/// Makes the host slots that waited for a texture's host copy, for the +/// textures made since the last call. Called before a submission runs, by +/// the thread that submits: a slot is read when a list runs. +#[cfg(windows)] +pub(crate) fn make_waiting() { + let made = std::mem::take(&mut *MADE_LATE.lock().unwrap_or_else(|e| e.into_inner())); + for resource in made { + let handles = WAITING + .lock() + .unwrap_or_else(|e| e.into_inner()) + .remove(&resource); + for handle in handles.into_iter().flatten() { + // Only if the slot still holds a view of that texture: the + // title may have written it since (and a view of another + // texture without a host copy must go on waiting). + // (Looked up first: the handle is read only while its heap is + // there.) + let Some((heap, index)) = shader_slot(handle) else { + continue; + }; + let same = match view(handle) { + Some(View::Shader(r, _) | View::Unordered(r, _, _)) => r == resource, + _ => false, + }; + if same && let Some(Some(host)) = heap.host.get() { + host.mirror(index, handle, true); + } + } + } +} + +fn record(handle: u64, view: View) { + if handle == 0 { + return; + } + let [i, generation] = words_for(view); + // SAFETY: the handle is a descriptor slot, at least 16 bytes. + unsafe { (handle as *mut [u32; 3]).write_unaligned([VIEW_TAG, i, generation]) }; + #[cfg(windows)] + mirror(handle); +} + +/// The title released `resource`: the views naming it go stale. +pub(crate) fn forget(resource: usize) { + #[cfg(windows)] + WAITING + .lock() + .unwrap_or_else(|e| e.into_inner()) + .remove(&resource); + let mut views = views_write(); + let Some(entries) = views.by_resource.remove(&resource) else { + return; + }; + for i in entries { + let (view, generation) = views.list[i as usize].clone(); + // Entries freed through a view's other resource may hold another + // view by now. + if views.index.get(&view) != Some(&i) || !view.resources().contains(&resource) { + continue; + } + views.index.remove(&view); + // (Below the bits that say a record is no table entry.) + views.list[i as usize].1 = ((generation + 1) & GENERATIONS).max(1); + // The view's other resource (a counter) keeps a stale entry, which + // `forget` of that resource skips. + views.free.push(i); + } +} + +/// The view the record words `i` and `generation` name: the one they hold +/// whole, or the view of entry `i` if `generation` is still its own. +fn view_at(i: u32, generation: u32) -> Option { + match generation >> KIND_SHIFT { + 0 => { + let views = views_read(); + let (view, current) = views.list.get(i as usize)?; + (*current == generation).then(|| view.clone()) + } + CONSTANT => Some(constant_of(i, generation)), + PLACED => views_read().placed_of(i, generation), + _ => None, + } +} + +/// The view recorded at `handle`, if one is (and its resource is alive). +pub(crate) fn view(handle: u64) -> Option { + if handle == 0 { + return None; + } + // SAFETY: the handle is a descriptor slot the title passes back. + let [tag, i, generation] = unsafe { (handle as *const [u32; 3]).read_unaligned() }; + if tag != VIEW_TAG { + return None; + } + view_at(i, generation) +} + +/// A description of `N` words, if the title passes one. +fn words(desc: *const [u32; N]) -> Option<[u32; N]> { + // SAFETY: the title passes a description or null. + (!desc.is_null()).then(|| unsafe { desc.read_unaligned() }) +} + +/// Device method. +pub(crate) extern "system" fn create_cbv(_: This, desc: *const [u32; 4], handle: u64) { + if let Some([lo, hi, size, _]) = words(desc) { + let address = u64::from(lo) | u64::from(hi) << 32; + record(handle, View::Constant(address, size)); + } +} + +/// Device method. +pub(crate) extern "system" fn create_srv( + _: This, + resource: This, + desc: *const [u32; 10], + handle: u64, +) { + record(handle, View::Shader(resource as usize, words(desc))); +} + +/// Device method. +pub(crate) extern "system" fn create_uav( + _: This, + resource: This, + counter: This, + desc: *const [u32; 10], + handle: u64, +) { + let view = View::Unordered(resource as usize, counter as usize, words(desc)); + record(handle, view); +} + +/// Device methods 0x230 and 0x238: shader resource and unordered access +/// views of memory the title placed itself, `(resource desc, view desc, +/// handle)`. +pub(crate) extern "system" fn create_placed_srv( + _: This, + resource: *const [u32; 14], + desc: *const [u32; 16], + handle: u64, +) { + if let (Some(resource), Some(desc)) = (words(resource), words(desc)) { + record(handle, View::Placed(false, resource, desc)); + } +} + +pub(crate) extern "system" fn create_placed_uav( + _: This, + resource: *const [u32; 14], + desc: *const [u32; 16], + handle: u64, +) { + if let (Some(resource), Some(desc)) = (words(resource), words(desc)) { + record(handle, View::Placed(true, resource, desc)); + } +} + +/// Device method. +pub(crate) extern "system" fn create_sampler(_: This, desc: *const [u32; 13], handle: u64) { + if let Some(desc) = words(desc) { + record(handle, View::Sampler(desc)); + } +} + +/// Device method 0x1e8. +pub(crate) extern "system" fn create_sampler_x(_: This, desc: *const [u32; 27], handle: u64) { + if let Some(desc) = words(desc) { + record(handle, View::ConsoleSampler(desc)); + } +} + +/// Device method: `count` descriptors of `kind` from `src` to `dst`. +pub(crate) extern "system" fn copy_simple(_: This, count: u32, dst: u64, src: u64, kind: u32) { + let step = u64::from(increment(kind).unwrap_or(0)); + let len = u64::from(count) * step; + if dst != 0 && src != 0 { + // SAFETY: both ranges are descriptor slots the title owns. + unsafe { std::ptr::copy(src as *const u8, dst as *mut u8, len as usize) }; + #[cfg(windows)] + for i in 0..u64::from(count) { + mirror(dst + i * step); + } + } +} + +/// Device method: ranges of descriptors (start and count each) gathered +/// from the sources and scattered to the destinations, in order. +#[allow(clippy::too_many_arguments)] // the method's own arguments +pub(crate) extern "system" fn copy( + _: This, + dst_ranges: u32, + dst_starts: *const u64, + dst_sizes: *const u32, + src_ranges: u32, + src_starts: *const u64, + src_sizes: *const u32, + kind: u32, +) { + let Some(step) = increment(kind) else { + return; + }; + // Each range as (start, count); a null size array means one descriptor + // per range. + let ranges = |n: u32, starts: *const u64, sizes: *const u32| -> Vec<(u64, u32)> { + (0..n as usize) + .map(|i| { + // SAFETY: the title passes `n` starts and sizes (or null sizes). + unsafe { + ( + *starts.add(i), + if sizes.is_null() { 1 } else { *sizes.add(i) }, + ) + } + }) + .collect() + }; + if dst_starts.is_null() || src_starts.is_null() { + return; + } + let src = ranges(src_ranges, src_starts, src_sizes); + let mut dst = ranges(dst_ranges, dst_starts, dst_sizes).into_iter(); + let (mut to, mut room) = dst.next().unwrap_or((0, 0)); + for (mut from, mut left) in src { + while left > 0 { + while room == 0 { + let Some(next) = dst.next() else { return }; + (to, room) = next; + } + let n = left.min(room); + copy_simple(std::ptr::null(), n, to, from, kind); + let bytes = u64::from(n) * u64::from(step); + (to, from, room, left) = (to + bytes, from + bytes, room - n, left - n); + } + } +} + +/// The view recorded at `handle`, if one is. +pub(crate) fn rtv_record(handle: u64) -> Option { + tagged_record(handle, RTV_TAG) +} + +/// The depth view recorded at `handle`, if one is. +pub(crate) fn dsv_record(handle: u64) -> Option { + tagged_record(handle, DSV_TAG) +} + +fn tagged_record(handle: u64, tag: u32) -> Option { + if handle == 0 { + return None; + } + // SAFETY: the handle is a descriptor slot the title passes back. + let record = unsafe { (handle as *const RtvRecord).read_unaligned() }; + (record.tag == tag).then_some(record) +} + +/// Device method. +pub(crate) extern "system" fn create_heap( + _: This, + desc_ptr: *const HeapDesc, + iid: *const Iid, + out: *mut This, +) -> HRESULT { + // SAFETY: the title passes a description (null is tolerated). + let Some(&desc) = (unsafe { desc_ptr.as_ref() }) else { + return E_INVALIDARG; + }; + let Some(size) = increment(desc.kind).map(|i| u64::from(i) * u64::from(desc.count.max(1))) + else { + return E_INVALIDARG; + }; + // SAFETY: read only as a hint: a title that passes the plain + // description has its own stack or data after it. + let placement = unsafe { desc_ptr.add(1).cast::().read_unaligned() }; + // shortcut: a placement is recognised by its size matching the count, + // since the plain and extended descriptions share the slot and the + // interface version; find the flag that tells them apart if a title + // trips over this. + let placed = placement.address != 0 && placement.size == size; + tracing::debug!(?desc, placed, "descriptor heap"); + let (start, memory) = if placed { + (placement.address, None) + } else { + match Memory::zeroed(size, 64) { + Ok(memory) => (memory.address(), Some(memory)), + Err(hr) => return hr, + } + }; + let visible = desc.flags & SHADER_VISIBLE != 0 && matches!(desc.kind, VIEWS_KIND | SAMPLERS); + let heap = Box::new(Heap { + object: Object::new(&FUNCTIONS), + desc, + start, + memory, + #[cfg(windows)] + host: std::sync::OnceLock::new(), + #[cfg(windows)] + pending: Default::default(), + #[cfg(windows)] + written: (placed && visible) + .then(|| crate::watch::track(start as usize, size as usize, true)) + .flatten(), + }); + #[cfg(windows)] + if visible { + let at = std::ptr::from_ref::(&heap) as usize; + let mut heaps = SHADER_HEAPS.write().unwrap_or_else(|e| e.into_inner()); + heaps.push((start, start + size, at)); + } + #[cfg(not(windows))] + let _ = visible; + object::hand_out(DESCRIPTOR_HEAP, heap, iid, &HEAP_IIDS, out) +} + +extern "system" fn query(this: This, iid: *const Iid, out: *mut This) -> HRESULT { + let found = object::is(iid, &HEAP_IIDS).then_some(this); + object::answer(DESCRIPTOR_HEAP, iid, found, out) +} +extern "system" fn release(this: This) -> u32 { + object::release_boxed::(this) +} +extern "system" fn desc(this: This, out: *mut HeapDesc) { + if !out.is_null() { + // SAFETY: checked non-null; the title passes room for a description. + unsafe { out.write(heap(this).desc) }; + } +} +/// The same address for the CPU and the GPU start. +extern "system" fn start(this: This) -> u64 { + heap(this).start +} + +/// IUnknown 3, object 4, device child 1, heap 3. +static FUNCTIONS: Table<24> = { + let mut f = object::d3d12_object(object::missing_table::()); + f[0] = query as *const (); + f[2] = release as *const (); + f[7] = object::parent_device as *const (); // 0x38 + f[8] = desc as *const (); // 0x40 + f[9] = start as *const (); // 0x48 CPU + f[10] = start as *const (); // 0x50 GPU + Table(f) +}; + +#[cfg(test)] +mod tests { + use super::*; + use crate::object::{S_OK, slot}; + + /// What newer titles pass; tests use it throughout, so that reading the + /// placement stays inside the value. + #[repr(C)] + struct Extended(HeapDesc, Placement); + + fn create(desc: HeapDesc, placement: Placement, out: &mut This) -> HRESULT { + let extended = Extended(desc, placement); + create_heap(std::ptr::null(), &extended.0, &HEAP_IIDS[0], out) + } + + #[cfg(windows)] + #[test] + fn raw_heap_sync_stops_before_dynamic_host_slots() { + let start = 0x1000usize; + let step = 32; + let capped = 5; + assert_eq!( + changed_slots( + start + 3 * step + 4, + start + 4 * step + 8, + start, + step as u64, + capped + ), + 3..5 + ); + assert_eq!( + changed_slots( + start + 6 * step, + start + 9 * step, + start, + step as u64, + capped + ), + 5..5 + ); + } + + #[test] + fn heaps_hold_count_descriptors_from_their_start() { + let null = std::ptr::null(); + let desc = HeapDesc { + kind: 0, + count: 1000, + flags: 1, + nodes: 0, + }; + let none = Placement { + address: 0, + size: 0, + }; + let mut h = null; + assert_eq!(create(desc, none, &mut h), S_OK); + let cpu = slot:: u64>(h, 0x48)(h); + assert_eq!(cpu % 64, 0); + assert_eq!(slot:: u64>(h, 0x50)(h), cpu); + assert_eq!(increment_size(null, 0), 32); + // SAFETY: the heap holds 1000 descriptors of 32 bytes. + unsafe { (cpu as *mut u8).add(999 * 32 + 31).write(1) }; + assert_eq!(increment_size(null, 9), 0); + let bad = HeapDesc { kind: 9, ..desc }; + assert_eq!(create(bad, none, &mut h), E_INVALIDARG); + } + + /// A descriptor copied into a placed heap as bytes is mirrored before + /// the next submission, even though no descriptor method saw the copy. + #[cfg(windows)] + #[test] + fn records_copied_as_bytes_are_made_at_the_next_sync() { + use windows_sys::Win32::System::Memory::{ + MEM_COMMIT, MEM_RELEASE, MEM_RESERVE, PAGE_READWRITE, VirtualAlloc, VirtualFree, + }; + const MEM_WRITE_WATCH: u32 = 0x20_0000; + let memory = unsafe { + VirtualAlloc( + std::ptr::null(), + crate::watch::PAGE, + MEM_RESERVE | MEM_COMMIT | MEM_WRITE_WATCH, + PAGE_READWRITE, + ) + }; + assert!(!memory.is_null()); + let desc = HeapDesc { + kind: SAMPLERS, + count: 64, + flags: SHADER_VISIBLE, + nodes: 1, + }; + let placement = Placement { + address: memory as u64, + size: 64 * 16, + }; + let mut h: This = std::ptr::null(); + assert_eq!(create(desc, placement, &mut h), S_OK); + if let Some(host) = heap(h).host() { + let mut elsewhere = [0u64; 2]; + let source = elsewhere.as_mut_ptr() as u64; + let sampler = [21, 3, 3, 3, 0, 1, 0, 0, 0, 0, 0, 0x7f7f_ffff, 0]; + create_sampler(std::ptr::null(), &sampler, source); + // SAFETY: the heap slot and source both hold 16 descriptor bytes. + unsafe { + std::ptr::copy_nonoverlapping( + source as *const u8, + memory.cast::().add(5 * 16), + 16, + ) + }; + assert!(!host.made(5)); + sync_heaps(); + assert!(host.made(5)); + } + slot:: u32>(h, 0x10)(h); + // SAFETY: this allocation belongs to the test. + unsafe { VirtualFree(memory, 0, MEM_RELEASE) }; + } + + #[test] + fn views_survive_copies() { + let null = std::ptr::null(); + let mut heap = vec![0u64; 4 * 8]; // four 32-byte slots + let at = |i: usize| heap.as_ptr() as u64 + 32 * i as u64; + let (s0, s1, s2, s3) = (at(0), at(1), at(2), at(3)); + create_cbv(null, &[0x1000, 1, 256, 0], s0); + assert_eq!(view(s0), Some(View::Constant(0x1_0000_1000, 256))); + create_srv(null, null, std::ptr::null(), s1); + assert_eq!(view(s1), Some(View::Shader(0, None))); + // The same view twice is one entry. + create_srv(null, null, std::ptr::null(), s2); + // SAFETY: both slots are in `heap`. + assert_eq!(unsafe { *(s1 as *const [u32; 3]) }, unsafe { + *(s2 as *const [u32; 3]) + }); + // Two ranges of one into one range of two. + let (dst, dst_n, src, src_n) = ([s2], [2u32], [s0, s1], [1u32, 1]); + copy( + null, + 1, + dst.as_ptr(), + dst_n.as_ptr(), + 2, + src.as_ptr(), + src_n.as_ptr(), + 0, + ); + assert_eq!(view(s2), view(s0)); + assert_eq!(view(s3), view(s1)); + assert_eq!(view(at(0) + 8), None); + heap[0] = 0; + } + + /// Constant buffer views are named whole in their records: any address + /// a program can have, any size below 16 KiB, multiples of 256 bytes + /// up to 4 MiB; what does not fit says so. + #[test] + fn constant_views_fit_their_records() { + let top = (1u64 << CONSTANT_ADDRESS_BITS) - 1; + for address in [0u64, 0x100, 0x2602_0000, 0xd_6b60_0000, 0x7ffd_a34f_0000, top] { + for size in [0u32, 1, 255, 256, 4000, (1 << 14) - 1, 1 << 14, 65536, (1 << 22) - 256] { + let [i, generation] = constant_words(address, size).expect("fits"); + assert_eq!(generation >> KIND_SHIFT, CONSTANT); + assert_eq!(view_at(i, generation), Some(View::Constant(address, size)), "{address:#x} {size}"); + } + } + assert_eq!(constant_words(top + 1, 256), None, "an address past 47 bits"); + assert_eq!(constant_words(0x1000, (1 << 14) + 1), None, "16 KiB or more, no multiple of 256"); + assert_eq!(constant_words(0x1000, 1 << 22), None, "4 MiB"); + // Different views never share their words. + assert_ne!(constant_words(0x1000, 256), constant_words(0x1000, 512)); + assert_ne!(constant_words(0x1000, 256), constant_words(0x1100, 256)); + assert_ne!(constant_words(0x1000, 1 << 14), constant_words(0x1000, 64)); + } + + /// The leak of run 65: a title that writes constant buffer views and + /// views of placed memory at ever new addresses adds nothing to the + /// table; one shape stands for all the placed views alike. + #[test] + fn views_at_new_addresses_add_no_entries() { + if !inline() { + return; + } + let null = std::ptr::null(); + let slots = [0u64; 4]; + let at = slots.as_ptr() as u64; + // A resource description and a view no other test uses. + let resource: [u32; 14] = std::array::from_fn(|k| 0x5ee0_0000 + k as u32); + let mut desc: [u32; 16] = std::array::from_fn(|k| 0x7a70_0000 + k as u32); + let mine = |v: &View| match v { + View::Constant(address, _) => (0x6_0000_0000..0x6_1000_0000).contains(address), + View::Placed(_, r, _) => *r == resource, + _ => false, + }; + let entries = || VIEWS.read().unwrap().list.iter().filter(|(v, _)| mine(v)).count(); + let shapes = || VIEWS.read().unwrap().shapes.iter().filter(|s| s.1 == resource).count(); + for n in 0..20_000u64 { + let address = 0x6_0000_0000 + n * 0x100; + create_cbv(null, &[address as u32, (address >> 32) as u32, 512, 0], at); + assert_eq!(view(at), Some(View::Constant(address, 512))); + let placed = 0xd_4940_0000 + n * 0x1_0000; + (desc[10], desc[11]) = (placed as u32, (placed >> 32) as u32); + create_placed_srv(null, &resource, &desc, at); + assert_eq!(view(at), Some(View::Placed(false, resource, desc))); + } + assert_eq!(entries(), 0, "no table entries"); + assert_eq!(shapes(), 1, "one shape for 20,000 placed views"); + // The same shape, unordered: another shape. + create_placed_uav(null, &resource, &desc, at); + assert_eq!(view(at), Some(View::Placed(true, resource, desc))); + assert_eq!(shapes(), 2); + // Placed memory past 1 TiB (not title memory) is a table entry. + (desc[10], desc[11]) = (0, 0x100); + create_placed_srv(null, &resource, &desc, at); + assert_eq!(view(at), Some(View::Placed(false, resource, desc))); + assert_eq!(entries(), 1); + // A record's words are the same for the same view (the host knows + // a slot's view by them), and differ with the address. + // SAFETY: both handles are slots of 32 bytes above. + let words = |handle: u64| unsafe { *(handle as *const [u32; 3]) }; + let other = [0u64; 4]; + create_cbv(null, &[0x40, 6, 512, 0], at); + create_cbv(null, &[0x40, 6, 512, 0], other.as_ptr() as u64); + assert_eq!(words(at), words(other.as_ptr() as u64)); + create_cbv(null, &[0x140, 6, 512, 0], other.as_ptr() as u64); + assert_ne!(words(at), words(other.as_ptr() as u64)); + } + + /// A released resource's views go stale; the same view of a new + /// resource at the same address is a new record. + #[test] + fn views_die_with_their_resource() { + let null = std::ptr::null(); + let slots = [0u64; 2 * 4]; + let (a, b) = (slots.as_ptr() as u64, slots.as_ptr() as u64 + 32); + let resource = 0x7777_0000usize as This; + create_srv(null, resource, std::ptr::null(), a); + assert_eq!(view(a), Some(View::Shader(0x7777_0000, None))); + forget(0x7777_0000); + assert_eq!(view(a), None, "stale after release"); + create_srv(null, resource, std::ptr::null(), b); + assert_eq!(view(b), Some(View::Shader(0x7777_0000, None))); + // SAFETY: both slots are in `slots`. + let (old, new) = unsafe { (*(a as *const [u32; 3]), *(b as *const [u32; 3])) }; + assert_ne!(old, new, "a new generation"); + } + + /// The title places its shader-visible heap in its own memory + /// and checks that the heap starts there. + #[test] + fn placed_heaps_start_at_the_title_memory() { + let mut memory = vec![0u8; 64 * 32]; + let address = memory.as_mut_ptr() as u64; + let desc = HeapDesc { + kind: 0, + count: 64, + flags: 1, + nodes: 1, + }; + let mut h = std::ptr::null(); + assert_eq!( + create( + desc, + Placement { + address, + size: 64 * 32 + }, + &mut h + ), + S_OK + ); + assert_eq!(slot:: u64>(h, 0x48)(h), address); + assert_eq!(slot:: u64>(h, 0x50)(h), address); + // A size that does not match the count is not a placement. + assert_eq!(create(desc, Placement { address, size: 7 }, &mut h), S_OK); + assert_ne!(slot:: u64>(h, 0x48)(h), address); + } +} diff --git a/crates/leonida-gpu/src/descriptor/host.rs b/crates/leonida-gpu/src/descriptor/host.rs new file mode 100644 index 000000000..92d4e9441 --- /dev/null +++ b/crates/leonida-gpu/src/descriptor/host.rs @@ -0,0 +1,3644 @@ +//! Host descriptor heaps behind the title's shader-visible heaps (decision +//! 0007, step 3). Translated shaders index the heaps directly at the +//! title's descriptor positions, so each host heap keeps the title heap's +//! order: slot `i` is made from what the title wrote at slot `i`, when it +//! writes it (view creation and descriptor copies) and again when a draw +//! reads it through a table and finds the slot changed. + +use std::sync::Mutex; + +use windows::Win32::Graphics::Direct3D12::*; +use windows::Win32::Graphics::Dxgi::Common::*; + +use super::{VIEW_TAG, View, view_at}; +use crate::host::host; + +pub(crate) struct HostHeap { + pub(crate) heap: ID3D12DescriptorHeap, + cpu: usize, + step: u32, + /// Slots mirroring the title's; view heaps have `dynamic` more. + count: u32, + /// Dynamic slots past `count`: [`DYNAMIC`] in view heaps, none in + /// sampler heaps. (Upstream falls back to 2^16 on a capped host heap; + /// ours keeps 2^18 there: 2^16 and 2^17 both ran out in this title.) + dynamic: u32, + sampler: bool, + /// The record (view index and generation) each slot was last made from. + made: Mutex>, + /// A fingerprint of the record each slot held when the pass over + /// records copied in as bytes last looked at it + /// ([`HostHeap::mirror_copied`]; 0: never looked at). Made on first use. + copied: Mutex>, + /// The host resource each slot views, held while the slot does: shaders + /// index heaps directly, so a slot the title has not rewritten since it + /// released the resource may still be read, and a freed host resource + /// read there is a GPU page fault (the console reads stale memory). + kept: Mutex>>, + /// Where the search for free dynamic slots starts, and which are taken + /// (by lists not yet reset). + next: Mutex<(u32, Vec)>, + /// How many dynamic slots are free (changed under `next`'s lock): with + /// fewer than a table needs, the search is not made. Once the world + /// had taken them all, every later table of the frame searched every + /// slot before it was refused. + free: std::sync::atomic::AtomicU32, + /// The shortest table that found no run of free slots since slots were + /// last given back (changed under `next`'s lock; `u32::MAX`: none). + /// Until something is given back the free runs only shrink, so a table + /// of that length or longer is refused without the search. Enough + /// slots were free, but in pieces, and every such table walked the + /// whole ring before it was refused: 0.33 ms each with 131,072 slots, + /// 1.0 s of the recording threads in a frame that refused 3,143 (run + /// 45), under the lock all of them need. (A free run that lies across + /// the place the search starts from is seen by neither.) + too_long: std::sync::atomic::AtomicU32, + /// View heaps: the bytes per element of the buffer view at each title + /// slot, for shaders that pick a buffer by an index they compute + /// (`leonida_shader::emit::SLOT_STRIDES`): an upload buffer of + /// `SLOT_STRIDES_COUNT` dwords, its GPU address and its mapping. + strides: Option<(ID3D12Resource, u64, usize)>, + /// Title slots holding buffer views. Such a view gets its host slot + /// (and its memory a host copy) only when something reads it: a draw + /// through a table, or [`HostHeap::buffer_slots`] for shaders that pick + /// buffers from the whole heap. + buffers: Mutex>, + /// Of those and of the slots that left the set: the ones written since + /// [`HostHeap::buffer_changes`] last took them. + changed: Mutex>, + /// Title slots holding a view of a texture the title may fill itself (a + /// placed texture, a texture object), with the frame from which they + /// are due: such a texture is uploaded when a draw reads it through a + /// table; one a shader picks by a computed index is brought up to date + /// from here ([`HostHeap::texture_slots_due`]). + textures: Mutex, + /// Per title slot, the frame (plus one; 0: never) in which a draw last + /// read it through a table, or made a table it lies in (with + /// [`TABLED_READ`] set if the draw read it). The draw that + /// reads such a slot brings its texture up to date itself and the slot + /// then leaves `textures`; a write of a slot that was a table's within + /// the last [`TABLED_FRAMES`] frames is due only [`TABLED_GRACE`] + /// frames later, by when its draw has read it. A title that builds a + /// table per draw writes thousands of texture views a frame into slots + /// only tables read (the title: some 2,500 a frame in its + /// opening cutscene, a few hundred textures over and over), and every + /// one of them stood in the queue of textures picked by index, ahead + /// of or behind the ones shaders do pick by index. + tabled: Vec, + /// The title memory each placed texture view of this heap describes, + /// by slot and by address ([`Spans`]): which slots a newer view of + /// other memory there makes stale, and which to look at again when the + /// runtime maps, unmaps or writes memory ([`remapped`]). + placed: std::sync::Arc>, +} + +/// The spans of every view heap made ([`HostHeap::placed`]), for the +/// texture code, which has no heap at hand ([`next_start`], +/// [`first_viewed`]). +static PLACED_SPANS: Mutex>>> = Mutex::new(Vec::new()); + +/// Where the next texture placed inside `[start, end)` starts, past the +/// first bytes of the one at `start` ([`HEAD`]): what is there of the +/// texture at `start` ends there, whatever its full size. `None`: no view +/// in a slot shaders pick by index describes memory in that range. +pub(crate) fn next_start(start: u64, end: u64) -> Option { + let heaps = PLACED_SPANS.lock().unwrap_or_else(|e| e.into_inner()); + heaps + .iter() + .filter_map(std::sync::Weak::upgrade) + .filter_map(|spans| spans.lock().unwrap_or_else(|e| e.into_inner()).next_start(start, end)) + .min() +} + +/// The lowest level that a view of the placed texture at `start` shows, +/// over the slots shaders pick by index that hold one now. The title +/// views a texture from the first level it holds. `None`: no such slot. +pub(crate) fn first_viewed(start: u64) -> Option { + let heaps = PLACED_SPANS.lock().unwrap_or_else(|e| e.into_inner()); + heaps + .iter() + .filter_map(std::sync::Weak::upgrade) + .filter_map(|spans| spans.lock().unwrap_or_else(|e| e.into_inner()).first_viewed(start)) + .min() +} + +/// Levels on demand (`crate::tiles`): where the placed textures start +/// whose first level with memory changed since a texture pass last took +/// them ([`HostHeap::texture_views_remade`]). +static RESHOWN: Mutex> = Mutex::new(Vec::new()); + +/// The first level with memory of the placed texture at `start` changed: +/// its slots are made again at the next texture pass. +pub(crate) fn levels_changed(start: u64) { + RESHOWN.lock().unwrap_or_else(|e| e.into_inner()).push(start); +} + +/// Levels on demand (`crate::tiles`): where the placed textures start +/// whose last upload left a held level without tiles (the card had no +/// room, or no heap could be had), and when (`crate::host::moment`). A +/// texture pass makes their slots due again once the card has room +/// ([`HostHeap::texture_slots_waiting`]). +static WAITING: Mutex> = Mutex::new(std::collections::BTreeMap::new()); + +/// The last upload of the placed texture at `start` left a held level +/// without tiles. A texture picked by index is uploaded once and then +/// only when its memory is found changed, and its staging buffer goes +/// with the upload: without this the level stayed empty (the texture +/// blurred, or black if no level had tiles) for as long as the title left +/// its memory alone, where a texture refused for want of room is tried +/// again. +pub(crate) fn levels_waiting(start: u64) { + WAITING.lock().unwrap_or_else(|e| e.into_inner()).insert(start, crate::host::moment()); +} + +/// Title memory by the placed texture views that describe it: per span of +/// memory (its start, its end at full size) the title slots holding a +/// view of a texture that takes exactly that span. A console title need +/// not clear a descriptor when it streams a texture out, so a newer view +/// that cannot be there together with an older one is all that says the +/// older one is stale ([`Rule`] says when that is). Views of one span with +/// different descriptions (the formats of one family, say) are one +/// texture's. +/// +/// Spans may overlap: a texture's smallest levels lie at the start of its +/// memory, and a title that holds only those puts the next texture where +/// the larger ones would be (the title: three 512x256 textures +/// of 0x2c000 bytes each whose starts are 0x2000 and 0x4000 apart, all +/// three read by the same frame's draws, run 188). What is there of a +/// texture ends where the next one starts. +/// No host heap is needed, so it is tested without one. +#[derive(Default)] +pub(crate) struct Spans { + /// When a newer view makes an older one stale. + rule: Rule, + by_start: std::collections::BTreeMap)>, + by_slot: std::collections::HashMap, + /// The level each slot's view starts at ([`Spans::shows`]). + first: std::collections::HashMap, + /// The bytes a placed texture takes, by resource description: worked + /// out once for each (a title writes the views of a few thousand + /// descriptions, thousands of times a frame). + sizes: std::collections::HashMap<[u32; 14], Option>, +} + +/// When a view the title writes makes an older view of other memory stale. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub(crate) enum Rule { + /// When it starts where the older one starts: at the same address + /// with another length, or within the older one's first [`HEAD`] + /// bytes (or the older within its own). No two textures share the + /// block of their smallest levels. A view that only reaches into the + /// address range of an older texture's larger levels says nothing. + #[default] + Start, + /// Whenever their spans at full size overlap (the rule until run + /// 188, where it made null the slots of textures packed as above: + /// each view written took its neighbours out of the queue and off the + /// card, for good). `LEONIDA_STALE_TEXTURES=overlap`. + Overlap, + /// Never; a view that would be stale under [`Rule::Overlap`] is left + /// out of the spans instead. `LEONIDA_STALE_TEXTURES=0`, as before. + Never, +} + +/// The first bytes of a placed texture that are its own under +/// [`Rule::Start`]: the 4 KiB block its smallest levels share. (Of 129 +/// pairs of overlapping neighbours in the listings of runs 188 and 189, +/// none starts closer than 0x2000 to the one before it.) +const HEAD: u64 = 4096; + +impl Spans { + /// The bytes of title memory a placed texture with the resource + /// description `desc` takes (`crate::resource::placed_bytes`). + fn bytes(&mut self, desc: &[u32; 14]) -> Option { + if let Some(&known) = self.sizes.get(desc) { + return known; + } + let bytes = crate::resource::placed_bytes(desc); + self.sizes.insert(*desc, bytes); + bytes + } + + /// The starts of the spans that overlap `[start, end)`, each taken to + /// end where the next one starts: the last span that starts before + /// `start`, if it reaches past it at full size, and every span that + /// starts inside. + fn overlapping(&self, start: u64, end: u64) -> Vec { + let before = self + .by_start + .range(..start) + .next_back() + .filter(|(_, span)| span.0 > start) + .map(|(at, _)| *at); + before.into_iter().chain(self.by_start.range(start..end).map(|(at, _)| *at)).collect() + } + + /// Slot `index` holds a view of a texture in `[start, end)`. `newer`: + /// the title wrote it now, so the slots whose views cannot be there + /// with it ([`Rule`]) are stale: they are returned, and forgotten. + /// Otherwise (a draw made the slot from what it held), and under + /// [`Rule::Never`], a view that clashes with other spans is left out. + fn note(&mut self, index: u32, start: u64, end: u64, newer: bool) -> Vec { + let same = |span: Option<&(u64, std::collections::BTreeSet)>| span.is_some_and(|s| s.0 == end); + if self.by_slot.get(&index) == Some(&start) && same(self.by_start.get(&start)) { + return Vec::new(); + } + self.forget(index); + if end <= start { + return Vec::new(); + } + let rule = self.rule; + // The spans the view cannot be there with. + let clashing: Vec = match rule { + Rule::Start => self + .by_start + .range(start.saturating_sub(HEAD - 1)..start.saturating_add(HEAD)) + .map(|(at, _)| *at) + .collect(), + Rule::Overlap | Rule::Never => self.overlapping(start, end), + }; + let mut stale = Vec::new(); + for at in clashing { + if at == start && same(self.by_start.get(&at)) { + continue; + } + if !newer || rule == Rule::Never { + return stale; + } + if let Some((old_end, slots)) = self.by_start.remove(&at) { + // The first of them are said with both spans, to tell a + // replacement from a neighbour in one launch's log. + static SAID: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); + if SAID.fetch_add(1, std::sync::atomic::Ordering::Relaxed) < 48 { + tracing::info!( + slot = index, + start = format_args!("{start:#x}"), + end = format_args!("{end:#x}"), + stale_start = format_args!("{at:#x}"), + stale_end = format_args!("{old_end:#x}"), + stale_slots = slots.len(), + rule = ?rule, + "a placed texture view makes older views of other memory stale" + ); + } + for slot in slots { + self.by_slot.remove(&slot); + stale.push(slot); + } + } + } + self.by_start.entry(start).or_insert_with(|| (end, Default::default())).1.insert(index); + self.by_slot.insert(index, start); + stale + } + + /// The view in slot `index` starts at level `first` of its texture. + fn shows(&mut self, index: u32, first: u32) { + self.first.insert(index, first); + } + + /// The lowest level a view of the texture at `start` starts at. + fn first_viewed(&self, start: u64) -> Option { + self.by_start.get(&start)?.1.iter().filter_map(|slot| self.first.get(slot)).min().copied() + } + + /// The first span that starts inside `[start, end)` past the first + /// [`HEAD`] bytes of it. + fn next_start(&self, start: u64, end: u64) -> Option { + self.by_start.range(start.saturating_add(HEAD)..end).next().map(|(at, _)| *at) + } + + /// The slots that hold a view of the texture at `start`. + fn slots_at(&self, start: u64) -> Vec { + self.by_start.get(&start).map(|span| span.1.iter().copied().collect()).unwrap_or_default() + } + + /// Slot `index` holds no placed texture view any more. + fn forget(&mut self, index: u32) { + self.first.remove(&index); + let Some(start) = self.by_slot.remove(&index) else { + return; + }; + if let Some(span) = self.by_start.get_mut(&start) { + span.1.remove(&index); + if span.1.is_empty() { + self.by_start.remove(&start); + } + } + } + + /// The slots whose texture's memory overlaps `[start, end)`. + fn slots_in(&self, start: u64, end: u64) -> Vec { + self.overlapping(start, end) + .iter() + .filter_map(|at| self.by_start.get(at)) + .flat_map(|span| span.1.iter().copied()) + .collect() + } + + /// The slots of the textures that hold bytes of `[start, end)`, for a + /// write there: as [`Spans::slots_in`], but when a texture starts at + /// `start` itself the one before it is left out (it ends where that + /// one starts, and a request that fills a texture begins at its first + /// byte: `slots_in` would name its neighbour with every such write). + fn slots_holding(&self, start: u64, end: u64) -> Vec { + if end <= start { + return Vec::new(); + } + let before = if self.by_start.contains_key(&start) { + None + } else { + self.by_start.range(..start).next_back().filter(|(_, span)| span.0 > start).map(|(_, span)| span) + }; + before + .into_iter() + .chain(self.by_start.range(start..end).map(|(_, span)| span)) + .flat_map(|span| span.1.iter().copied()) + .collect() + } +} + +/// Title memory written behind the guards' back whose bytes are there +/// (DirectStorage's reads into physical pages, at the addresses the title +/// has them mapped; `crate::watch::title_memory_written`), since a texture +/// pass last took the ranges ([`page_written`]). Kept apart from +/// [`REMAPPED`] so that what such writes do is counted by itself. +static PAGE_WRITTEN: Mutex> = Mutex::new(Vec::new()); + +/// Since the start: such ranges kept for a pass; ranges dropped because no +/// pass took them; slots of placed textures that held bytes of them when a +/// pass took them; of those, the slots whose texture had been uploaded +/// before the write (out of the queue, or in it after an upload): they are +/// the ones that kept the bytes from before, and the ones made due when +/// `LEONIDA_PAGE_WRITES` asks for it. +pub(crate) static PAGE_WRITES: [std::sync::atomic::AtomicU64; 4] = + [const { std::sync::atomic::AtomicU64::new(0) }; 4]; + +/// Frames from the pass that takes a written range to the look at its +/// slots: the levels of one texture arrive in a few requests, and a look +/// two frames on takes those of the next frame with it. +const PAGE_WRITE_AFTER: u64 = 2; + +/// The bytes of a write the guards do not see are in title memory `[at, +/// at + len)`: the placed textures there changed with no descriptor +/// written and nothing mapped. Kept for the next texture pass +/// ([`HostHeap::texture_slots_page_written`]), as [`remapped`] keeps its +/// ranges; locks one mutex and calls nothing. +pub(crate) fn page_written(at: usize, len: usize) { + use std::sync::atomic::Ordering::Relaxed; + /// Ranges kept until a pass takes them. + const MOST: usize = 1 << 15; + let (start, end) = (at as u64, at.saturating_add(len) as u64); + if end <= SPANNED[0].load(Relaxed) || start >= SPANNED[1].load(Relaxed) { + return; + } + let mut ranges = PAGE_WRITTEN.lock().unwrap_or_else(|e| e.into_inner()); + PAGE_WRITES[0].fetch_add(1, Relaxed); + if let Some(last) = ranges.last_mut() + && last.1 == start + { + last.1 = end; + return; + } + if ranges.len() >= MOST { + PAGE_WRITES[1].fetch_add(ranges.len() as u64, Relaxed); + ranges.clear(); + } + ranges.push((start, end)); +} + +/// Title memory the runtime mapped, unmapped or is about to write since a +/// texture pass last took the ranges ([`remapped`]). +static REMAPPED: Mutex> = Mutex::new(Vec::new()); + +/// The lowest start and the highest end of any span of [`Spans`] so far +/// (the start is `u64::MAX` until there is one): what the runtime does to +/// memory outside is none of the texture pass's business. +static SPANNED: [std::sync::atomic::AtomicU64; 2] = [ + std::sync::atomic::AtomicU64::new(u64::MAX), + std::sync::atomic::AtomicU64::new(0), +]; + +/// Since the start: slots whose view a newer view of other memory there +/// made stale; ranges of memory noted as mapped, unmapped or written; +/// ranges dropped because no pass took them; slots made due by such +/// ranges; and made slots whose memory was found unmapped (made null). +pub(crate) static STALE: [std::sync::atomic::AtomicU64; 5] = + [const { std::sync::atomic::AtomicU64::new(0) }; 5]; + +/// When a view the title writes makes older views of other memory stale +/// ([`Rule`]): where it starts in the block of their smallest levels, by +/// default; `LEONIDA_STALE_TEXTURES=0`: never, as before; +/// `LEONIDA_STALE_TEXTURES=overlap`: wherever their spans overlap, the rule +/// until run 188. +fn stale_rule() -> Rule { + static RULE: std::sync::OnceLock = std::sync::OnceLock::new(); + *RULE.get_or_init(|| match std::env::var("LEONIDA_STALE_TEXTURES").as_deref() { + Ok("0") => Rule::Never, + Ok("overlap") => Rule::Overlap, + _ => Rule::Start, + }) +} + +/// The runtime mapped or unmapped title memory `[at, at + len)`, or is +/// about to write it through the kernel (`crate::watch`): the placed +/// textures there may have arrived, gone, or changed with no descriptor +/// written. The range is kept for the next texture pass +/// ([`HostHeap::texture_slots_remapped`]). Called with the runtime's own +/// locks held: this locks one mutex of its own and calls nothing. +pub(crate) fn remapped(at: usize, len: usize) { + use std::sync::atomic::Ordering::Relaxed; + /// Ranges kept until a pass takes them. + const MOST: usize = 1 << 15; + let (start, end) = (at as u64, at.saturating_add(len) as u64); + if end <= SPANNED[0].load(Relaxed) || start >= SPANNED[1].load(Relaxed) { + return; + } + let mut ranges = REMAPPED.lock().unwrap_or_else(|e| e.into_inner()); + STALE[1].fetch_add(1, Relaxed); + // Pages are mapped one after the other. + if let Some(last) = ranges.last_mut() + && last.1 == start + { + last.1 = end; + return; + } + if ranges.len() >= MOST { + // No pass runs (no shader that picks textures by index is bound): + // the slots there are looked at when they are due, as before. + STALE[2].fetch_add(ranges.len() as u64, Relaxed); + ranges.clear(); + } + ranges.push((start, end)); +} + +/// Frames for which a slot a draw read through a table counts as a table's +/// slot ([`HostHeap::tabled`]). +const TABLED_FRAMES: u64 = 240; + +/// Frames a write of a table's slot waits in the queue for the draw that +/// reads it, before the slot is taken for one shaders pick by index. +/// Frames as `crate::frame::current` counts them: in its opening cutscene +/// The title begins two or three of them per frame it presents +/// (435 begun in the 353 s of run 52's, for some 140 presented). +const TABLED_GRACE: u64 = 8; + +/// In [`HostHeap::tabled`]: a draw read the slot in that frame. +const TABLED_READ: u32 = 1 << 31; + +/// Since the start: writes of texture views into slots that count as a +/// table's (due later), and slots that left the queue because a draw read +/// them through a table. +pub(crate) static TABLED_WRITES: [std::sync::atomic::AtomicU64; 2] = + [const { std::sync::atomic::AtomicU64::new(0) }; 2]; + +/// Whether slots draws read through tables leave the queue of textures +/// picked by index; `LEONIDA_TABLED_TEXTURES=1` keeps them in it as +/// before. +fn tabled_out() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("LEONIDA_TABLED_TEXTURES").is_none_or(|v| v != "1")) +} + +/// What the queue of textures picked by index knows of a title slot. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +struct Waiting { + /// The frame from which the slot is due. + due: u64, + /// The frame it was written in. + written: u64, + /// Which write of the queue put it here: the pass hands it back with + /// what it did, so a slot written again meanwhile stays as written. + write: u64, + /// Looks in a row that found nothing to upload (its memory not mapped, + /// or no more of it than at the last upload). + looks: u8, + /// Bytes of its memory that were mapped when it was last uploaded + /// without all of it there; 0: not uploaded yet. + mapped: u64, + /// For a slot uploaded whole and looked at again + /// ([`TextureQueue::recheck`]): where its memory is (address, bytes), + /// the fingerprint it had at the upload, how many looks found it + /// unchanged, and the frame of the upload. A fingerprint of 0: none. + checked: (u64, u64, u64, u8, u64), +} + +/// The queue of title slots whose texture view waits to be brought up to +/// date for shaders that pick textures by index: which are due, and in +/// which order (no host heap needed, so it is tested without one). +#[derive(Default)] +pub(crate) struct TextureQueue { + slots: std::collections::BTreeMap, + writes: u64, + /// Slots held back because the card had no room for the host copy + /// they need ([`TextureQueue::hold`]), each with the write it was + /// held as. + held: std::collections::BTreeMap, +} + +impl TextureQueue { + /// A texture view was written into slot `index` in `frame`, due from + /// frame `due`. `seen`: it was not written, a draw or the pass made + /// the host slot from a view the queue may hold already, which then + /// stays as it is. + fn written(&mut self, index: u32, frame: u64, due: u64, seen: bool) { + if seen && self.slots.contains_key(&index) { + return; + } + self.writes += 1; + let write = self.writes; + self.slots.insert(index, Waiting { due, written: frame, write, looks: 0, mapped: 0, checked: (0, 0, 0, 0, 0) }); + } + + fn remove(&mut self, index: u32) { + self.slots.remove(&index); + } + + /// Up to `max` slots due at `frame`, each with its write number, in + /// the order to serve them: + /// - first the ones looked at before (their memory was not mapped, or + /// only part of it): the look is a query, and memory that has + /// arrived since is what the title streamed in last; + /// - then the others, the newest write first and the oldest next, in + /// turns: slot order served the low slots of a backlog of + /// 25,000-40,000 while the textures of the shot on screen waited + /// (run 52: 98% of the drawn pixels had no colour texture in the + /// first 3D frames). + fn due(&self, frame: u64, max: usize) -> Vec<(u32, u64)> { + let mut again: Vec<(u64, u32, u64)> = Vec::new(); + let mut fresh: Vec<(u64, u32, u64)> = Vec::new(); + for (&index, w) in self.slots.iter().filter(|(_, w)| w.due <= frame) { + let class = if w.looks > 0 || w.mapped > 0 { &mut again } else { &mut fresh }; + class.push((w.written, index, w.write)); + } + // By the number of the write, counted over the run. + let newest_first = |a: &(u64, u32, u64), b: &(u64, u32, u64)| b.2.cmp(&a.2); + again.sort_unstable_by(newest_first); + fresh.sort_unstable_by(newest_first); + let mut order: Vec<(u32, u64)> = again.iter().map(|&(_, index, write)| (index, write)).collect(); + let (mut new, mut old) = (0, fresh.len()); + while new < old && order.len() < max { + order.push((fresh[new].1, fresh[new].2)); + new += 1; + if new < old && order.len() < max { + old -= 1; + order.push((fresh[old].1, fresh[old].2)); + } + } + order.truncate(max); + order + } + + /// The entry of `index` if it is still the write the pass was handed. + fn same(&mut self, index: u32, write: u64) -> Option<&mut Waiting> { + self.slots.get_mut(&index).filter(|w| w.write == write) + } + + /// Slot `index` is up to date: out of the queue until written again. + fn done(&mut self, index: u32, write: u64) { + if self.same(index, write).is_some() { + self.slots.remove(&index); + } + } + + /// Nothing to upload at slot `index` now: looked at again after 1, 2, + /// 4, ... frames, at most `most`. + fn later(&mut self, index: u32, write: u64, frame: u64, most: u64) { + if let Some(w) = self.same(index, write) { + w.due = frame + (1u64 << w.looks.min(16)).min(most.max(1)); + w.looks = w.looks.saturating_add(1); + } + } + + /// The card has no room for the host copy slot `index` needs: it is + /// not handed out again before frame `due`, or before the card has + /// room again ([`TextureQueue::room`]). Nothing else of it changes: it + /// is not a slot "waiting for its memory", and when it is due it has + /// its old place among the slots never looked at. (It stayed due, so + /// every pass on a full card looked at the same few hundred slots + /// again and stopped there, and the slots behind them were never + /// reached: the ones whose host copy exists and only wants bringing up + /// to date, and the ones whose memory went, which is what lets host + /// copies go and makes room.) + fn hold(&mut self, index: u32, write: u64, due: u64) { + if let Some(w) = self.same(index, write) { + w.due = w.due.max(due); + self.held.insert(index, write); + } + } + + /// The card has room again at `frame`: the slots held back for lack of + /// it are due now, as if they had never been held. Returns how many. + fn room(&mut self, frame: u64) -> usize { + let held = std::mem::take(&mut self.held); + let mut back = 0; + for (index, write) in held { + if let Some(w) = self.same(index, write) { + w.due = w.due.min(frame); + back += 1; + } + } + back + } + + /// Slot `index` was uploaded with `mapped` bytes of its memory there, + /// not all of it: looked at again from frame `due`. + fn partly(&mut self, index: u32, write: u64, due: u64, mapped: u64) { + if let Some(w) = self.same(index, write) { + (w.due, w.looks, w.mapped) = (due, 0, mapped.max(1)); + } + } + + /// Slot `index` was uploaded whole from memory `at` (address, bytes) + /// with fingerprint `print`: looked at again from frame `due`, for a + /// title that fills a texture's memory after it wrote the view (the + /// `looks`-th such look; `uploaded` is the upload's frame). + #[allow(clippy::too_many_arguments)] + fn recheck(&mut self, index: u32, write: u64, due: u64, at: (u64, u64), print: u64, looks: u8, uploaded: u64) { + if let Some(w) = self.same(index, write) { + (w.due, w.looks, w.mapped) = (due, 1, 0); + w.checked = (at.0, at.1, print, looks, uploaded); + } + } + + /// What [`TextureQueue::recheck`] noted of slot `index`, if it is + /// waiting for such a look. + fn checked(&self, index: u32) -> Option<(u64, u64, u64, u8, u64)> { + self.slots.get(&index).map(|w| w.checked).filter(|c| c.2 != 0) + } + + /// The memory slot `index`'s texture lies in was mapped, unmapped or + /// written in `frame`: the slot is looked at from frame `due` as one + /// written now, whatever was known of it (a pass at work on it does + /// not take it out). + fn changed(&mut self, index: u32, frame: u64, due: u64) { + self.writes += 1; + let write = self.writes; + let due = self.slots.get(&index).map_or(due, |w| w.due.min(due)); + self.slots.insert(index, Waiting { due, written: frame, write, looks: 0, mapped: 0, checked: (0, 0, 0, 0, 0) }); + } + + /// Bytes of slot `index`'s memory that were mapped at its last upload + /// (0: not uploaded, or all of it was). + fn mapped(&self, index: u32) -> u64 { + self.slots.get(&index).map_or(0, |w| w.mapped) + } + + /// For the frame line: slots in the queue; of them due at `frame`; + /// waiting for their memory (looked at, never uploaded); uploaded in + /// part; and the frames the oldest due one has waited since its write. + fn census(&self, frame: u64) -> [u64; 5] { + let mut c = [self.slots.len() as u64, 0, 0, 0, 0]; + for w in self.slots.values() { + if w.mapped > 0 { + c[3] += 1; + } else if w.looks > 0 { + c[2] += 1; + } + if w.due <= frame { + c[1] += 1; + c[4] = c[4].max(frame.saturating_sub(w.written)); + } + } + c + } +} + +/// Whether `view` is of a texture the title may fill itself: a texture it +/// placed in memory, or a texture object. +pub(crate) fn is_texture_view(view: &View) -> bool { + match view { + View::Placed(false, resource, _) => resource[0] != 1, + View::Shader(r, _) => crate::resource::buffer_bytes(*r as crate::object::This).is_none(), + _ => false, + } +} + +/// Buffer views left null because the host would refuse them +/// ([`buffer_view_ok`]), since the start. +pub(crate) static REFUSED_VIEWS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + +/// Whether the host device is gone, and why (the first time it is asked +/// after that): for passes that make many views, to name the one that did +/// it. +pub(crate) fn device_removed() -> Option { + let host = host()?; + // SAFETY: a plain query. + let reason = unsafe { host.device.GetDeviceRemovedReason() }; + reason.err().map(|e| e.to_string()) +} + +/// Writes of title view-heap slots with a placed texture view and with a +/// view of a texture object, since the start (diagnostic counts). +pub(crate) static PLACED_TEXTURE_SLOTS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); +pub(crate) static OBJECT_TEXTURE_SLOTS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + +/// Bytes per element of a buffer view, as the console's descriptor holds +/// them for indexed reads (structured: the stride; raw: 1, the index is the +/// byte; typed: the format's); `None` if `view` is not a buffer view. +fn view_stride(view: &View) -> Option { + const BUFFER: u32 = 1; + let (words, unordered): (&[u32; 10], bool) = match view { + View::Shader(_, Some(d)) if d[1] == BUFFER => (d, false), + View::Unordered(_, _, Some(d)) if d[1] == BUFFER => (d, true), + View::Placed(unordered, resource, d) if resource[0] == BUFFER => { + (d[..10].try_into().ok()?, *unordered) + } + _ => return None, + }; + // SAFETY: buffer views' union members. + let (stride, raw, format) = unsafe { + if unordered { + let d = uav_desc(words); + let b = d.Anonymous.Buffer; + (b.StructureByteStride, b.Flags.0 & D3D12_BUFFER_UAV_FLAG_RAW.0 != 0, d.Format) + } else { + let d = srv_desc(words); + let b = d.Anonymous.Buffer; + (b.StructureByteStride, b.Flags.0 & D3D12_BUFFER_SRV_FLAG_RAW.0 != 0, d.Format) + } + }; + Some(if stride > 0 { + stride + } else if raw { + 1 + } else { + crate::resource::element(format.0 as u32).map_or(0, |(bytes, _)| bytes as u32) + }) +} + +/// Host heaps' GPU ranges (start, bytes, bytes per slot, sampler), for +/// device-removed reports: a shader indexing a heap past its end faults. +static GPU_RANGES: Mutex> = Mutex::new(Vec::new()); + +/// For device-removed reports: where host GPU address `va` lies against +/// the host descriptor heaps. +pub(crate) fn near_heaps(va: u64) -> String { + let ranges = GPU_RANGES.lock().unwrap_or_else(|e| e.into_inner()); + let mut text = String::new(); + for &(start, bytes, step, sampler) in ranges.iter() { + let kind = if sampler { "sampler" } else { "view" }; + let place = if va < start { + format!("{:#x} below", start - va) + } else if va < start + bytes { + format!("inside, slot {}", (va - start) / step) + } else { + format!("{:#x} past its end (slot {})", va - start - bytes, (va - start) / step) + }; + text.push_str(&format!("; {kind} heap {start:#x}+{bytes:#x}: {place}")); + } + text +} + +/// The host's limit for shader-visible view heaps on resource binding +/// tiers 1 and 2; tier 3 hardware may take more. +const PORTABLE_VIEWS: u32 = 1_000_000; + +/// The size of every host view heap on a host that takes more than +/// [`PORTABLE_VIEWS`] (AMD): the title's heap (a little over 1,000,000 +/// views in the retail game) plus [`DYNAMIC`] fits with room to spare, and +/// the last slot is the null slot every view index at or past it reads. +const UNCAPPED_VIEWS: u32 = 1 << 21; + +/// Picks, once, the null slot at the end of every host view heap and tells +/// the translator now (`set_view_heap_limit`) instead of when the title's +/// heap is made: a shader keeps the limit it was translated with, and the +/// title makes 25 pipelines (their shaders translated at once) before it +/// makes its view heap. Called before a shader is translated and before a +/// view heap is made. +/// +/// Every host clamps. A host that caps view heaps at [`PORTABLE_VIEWS`] +/// (NVIDIA) hung on a view index past the heap; one that does not (AMD +/// RDNA3, RX 7900 XT) took a page fault and removed the device on entering +/// the world: a compute program read view slot 16,777,088 (0xffff80) of a +/// heap of 1,507,328, past its end. Unclamped, that index is undefined on +/// any host. +pub(crate) fn probe_view_limit() { + static ONCE: std::sync::Once = std::sync::Once::new(); + ONCE.call_once(|| { + let Some(host) = host() else { return }; + let fits = |count: u32| { + // SAFETY: plain heap creation; the heap is released at once. + let made: windows::core::Result = unsafe { + host.device + .CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC { + Type: D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, + NumDescriptors: count, + Flags: D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE, + NodeMask: 0, + }) + }; + made.is_ok() + }; + let views = if fits(UNCAPPED_VIEWS) { + UNCAPPED_VIEWS + } else { + PORTABLE_VIEWS + }; + tracing::info!( + views, + "host view heaps hold {views} views; view indices are clamped to the null slot at the end from the first shader on" + ); + leonida_shader::emit::set_view_heap_limit(views - 1); + }); +} + +/// Slots past the title's in a view heap, for tables a draw needs made +/// afresh (constant buffers copied per draw). A list holds the slots it +/// took until it is reset (its submissions have run) or released. +/// 2^16 ran out in the world ("no free dynamic descriptor slots", run 11; +/// upstream PR #336 takes 2^18). On a host heap capped at 1,000,000 views +/// (NVIDIA) these come out of the title's slots, whose highest seen is +/// about 720,000: 2^17 left 868,000 of them, and ran out in the opening +/// cutscene (a frame asks for up to 16,000 tables while the frame before +/// still holds its own; a draw refused its table read slots never made +/// for it, and the card stopped within frames). 2^18 leaves 737,000; a +/// table past them is made afresh in these slots like any other. +pub(crate) const DYNAMIC: u32 = 1 << 18; + +impl HostHeap { + pub(crate) fn new(sampler: bool, count: u32) -> Option { + let host = host()?; + let kind = if sampler { + D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER + } else { + D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV + }; + let make = |count: u32| -> windows::core::Result { + // SAFETY: plain heap creation. + unsafe { + host.device + .CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC { + Type: kind, + NumDescriptors: count, + Flags: D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE, + NodeMask: 0, + }) + } + }; + let extra = if sampler { 0 } else { DYNAMIC }; + // A view heap ends at the null slot shaders clamp view indices to + // (`probe_view_limit`), whatever the title's own count: the title's + // slots, then the dynamic ones, then null up to and with that slot. + if !sampler { + probe_view_limit(); + } + let null = if sampler { + 0 + } else { + leonida_shader::emit::view_heap_limit() + }; + let (heap, count, size) = if null == 0 { + match make(count + extra) { + Ok(heap) => (heap, count, count + extra), + Err(e) => { + tracing::warn!(error = %e, count, sampler, "no host descriptor heap"); + return None; + } + } + } else { + let size = null + 1; + let fitted = if count + extra <= null { + count + } else { + // shortcut: descriptors past the host's limit are left out; a title that reaches + // them needs remapping. They read the null slot instead. + tracing::warn!(count, "host view heap capped at {size}; views past it read a null slot"); + null - extra + }; + match make(size) { + Ok(heap) => (heap, fitted, size), + Err(e) => { + tracing::warn!(error = %e, count, size, "no host view heap"); + return None; + } + } + }; + // SAFETY: a live heap. + let (cpu, step) = unsafe { + ( + heap.GetCPUDescriptorHandleForHeapStart().ptr, + host.device.GetDescriptorHandleIncrementSize(kind), + ) + }; + tracing::debug!(count, sampler, "host descriptor heap"); + // SAFETY: a live shader-visible heap. + let gpu = unsafe { heap.GetGPUDescriptorHandleForHeapStart().ptr }; + GPU_RANGES.lock().unwrap_or_else(|e| e.into_inner()).push(( + gpu, + u64::from(size) * u64::from(step), + u64::from(step), + sampler, + )); + let strides = (!sampler) + .then(|| { + let bytes = u64::from(leonida_shader::emit::SLOT_STRIDES_COUNT) * 4; + let (buffer, data) = host.upload_buffer(bytes)?; + // SAFETY: the buffer's whole mapping; a live buffer. + let gpu = unsafe { + std::ptr::write_bytes(data, 0, bytes as usize); + buffer.GetGPUVirtualAddress() + }; + crate::host::name(&buffer, || "element strides by view heap slot".to_owned()); + Some((buffer, gpu, data as usize)) + }) + .flatten(); + let h = HostHeap { + heap, + cpu, + step, + count, + dynamic: extra, + sampler, + made: Mutex::new(vec![0; count as usize]), + copied: Mutex::new(Vec::new()), + kept: Mutex::new(vec![None; (count + extra) as usize]), + next: Mutex::new((0, vec![false; DYNAMIC as usize])), + free: std::sync::atomic::AtomicU32::new(DYNAMIC), + too_long: std::sync::atomic::AtomicU32::new(u32::MAX), + strides, + buffers: Mutex::default(), + changed: Mutex::default(), + textures: Mutex::default(), + tabled: (0..if sampler { 0 } else { count }) + .map(|_| std::sync::atomic::AtomicU32::new(0)) + .collect(), + placed: { + let spans = std::sync::Arc::>::default(); + if !sampler { + PLACED_SPANS + .lock() + .unwrap_or_else(|e| e.into_inner()) + .push(std::sync::Arc::downgrade(&spans)); + } + spans + }, + }; + // A slot never written is undefined: shaders reading one (a slot + // the title wrote in a way we do not know, or a table entry no + // used-resource entry names) read a wild address. Every slot starts + // null instead. + let started = std::time::Instant::now(); + if let Err(e) = h.fill_null(kind, size) { + tracing::warn!(error = %e, "host descriptor heap not made null"); + } + tracing::debug!(ms = started.elapsed().as_millis(), "host descriptor heap made null"); + Some(h) + } + + /// Makes the first `total` slots null: one null slot in a CPU-side heap, + /// doubled by copies to a block, the block copied over the heap. + fn fill_null(&self, kind: D3D12_DESCRIPTOR_HEAP_TYPE, total: u32) -> windows::core::Result<()> { + const BLOCK: u32 = 1 << 16; + let Some(host) = host() else { return Ok(()) }; + // SAFETY: plain heap creation and copies inside live heaps. + unsafe { + let block: ID3D12DescriptorHeap = + host.device.CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC { + Type: kind, + NumDescriptors: BLOCK, + ..Default::default() + })?; + let start = block.GetCPUDescriptorHandleForHeapStart(); + let at = |i: u32| D3D12_CPU_DESCRIPTOR_HANDLE { + ptr: start.ptr + (i * self.step) as usize, + }; + if self.sampler { + null_sampler(start); + } else { + null_view(start); + } + let mut filled = 1; + while filled < BLOCK { + let n = filled.min(BLOCK - filled); + host.device.CopyDescriptorsSimple(n, at(filled), start, kind); + filled += n; + } + let mut done = 0; + while done < total { + let n = BLOCK.min(total - done); + host.device.CopyDescriptorsSimple(n, self.cpu(done), start, kind); + done += n; + } + } + Ok(()) + } + + /// A plain point sampler at slot `index`, for sampler slots without a + /// view. + fn null_sampler(&self, index: u32) { + null_sampler(self.cpu(index)); + } +} + +/// A plain point sampler at `at`. +fn null_sampler(at: D3D12_CPU_DESCRIPTOR_HANDLE) { + let Some(host) = host() else { return }; + let desc = 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, + ComparisonFunc: D3D12_COMPARISON_FUNC_NEVER, + ..Default::default() + }; + // SAFETY: a slot of a sampler heap of ours. + unsafe { host.device.CreateSampler(&desc, at) }; +} + +impl HostHeap { + /// `n` consecutive free dynamic slots (view heaps only), taken until + /// [`HostHeap::release`]: the first's index. + pub(crate) fn dynamic(&self, n: u32) -> Option { + if self.sampler || n == 0 || n > self.dynamic { + return None; + } + #[cfg(feature = "diagnostics")] + let started = std::time::Instant::now(); + #[cfg(feature = "diagnostics")] + crate::copystat::add(crate::copystat::C::DynamicAsked, 1); + let mut guard = self.next.lock().unwrap_or_else(|e| e.into_inner()); + let (next, taken) = &mut *guard; + let enough = self.free.load(std::sync::atomic::Ordering::Relaxed) >= n + && n < self.too_long.load(std::sync::atomic::Ordering::Relaxed); + let n = n as usize; + // Search from `next` on, then from the start. + let starts = (*next as usize..self.dynamic as usize).chain(0..*next as usize); + let mut run = 0; + let mut found = None; + let mut last = usize::MAX; + for at in starts.take(if enough { DYNAMIC as usize } else { 0 }) { + // A run cannot wrap past the end. + if at != last.wrapping_add(1) { + run = 0; + } + last = at; + run = if taken[at] { 0 } else { run + 1 }; + if run == n { + found = Some(at + 1 - n); + break; + } + } + let Some(first) = found else { + if enough { + self.too_long.fetch_min(n as u32, std::sync::atomic::Ordering::Relaxed); + } + static ONCE: std::sync::Once = std::sync::Once::new(); + ONCE.call_once(|| tracing::warn!(n, "no free dynamic descriptor slots: a table is not made")); + #[cfg(feature = "diagnostics")] + { + use crate::copystat::{C, add}; + add(C::DynamicRefused, 1); + add(C::DynamicNs, started.elapsed().as_nanos() as u64); + } + return None; + }; + #[cfg(feature = "diagnostics")] + crate::copystat::add(crate::copystat::C::DynamicNs, started.elapsed().as_nanos() as u64); + taken[first..first + n].fill(true); + self.free.fetch_sub(n as u32, std::sync::atomic::Ordering::Relaxed); + *next = ((first + n) % DYNAMIC as usize) as u32; + Some(self.count + first as u32) + } + + /// The title slots this heap has host slots for; fewer than the title's + /// when the host caps its size. + pub(crate) fn count(&self) -> u32 { + self.count + } + + /// The GPU address of the table of element strides by title slot (view + /// heaps). + pub(crate) fn strides_gpu(&self) -> Option { + self.strides.as_ref().map(|s| s.1) + } + + /// The table's buffer, for a list to hold. + pub(crate) fn strides_buffer(&self) -> Option<&ID3D12Resource> { + self.strides.as_ref().map(|s| &s.0) + } + + /// Up to `max` title slots whose texture view is due at `frame`, each + /// with its write number, in the order to serve them + /// ([`TextureQueue::due`]), and the queue's counts + /// ([`TextureQueue::census`]). + pub(crate) fn texture_slots_due(&self, frame: u64, max: usize) -> (Vec<(u32, u64)>, [u64; 5]) { + let textures = self.textures.lock().unwrap_or_else(|e| e.into_inner()); + (if max == 0 { Vec::new() } else { textures.due(frame, max) }, textures.census(frame)) + } + + /// Every title slot of the queue that is due at `frame`, and whether + /// it was uploaded before (in part, or whole and waiting for another + /// look): for the card accounting line + /// (`crate::resource::card_accounting`). + pub(crate) fn texture_slots_all_due(&self, frame: u64) -> Vec<(u32, bool)> { + let textures = self.textures.lock().unwrap_or_else(|e| e.into_inner()); + textures + .slots + .iter() + .filter(|(_, w)| w.due <= frame) + .map(|(&index, w)| (index, w.mapped > 0 || w.checked.2 != 0)) + .collect() + } + + /// The texture view of title slot `index` (as handed out with `write`) + /// was brought up to date: due again from frame `again` (uploaded with + /// that many bytes of its memory there, not all), or not until the + /// slot is written again. + pub(crate) fn texture_slot_done(&self, index: u32, write: u64, again: Option<(u64, u64)>) { + let mut textures = self.textures.lock().unwrap_or_else(|e| e.into_inner()); + match again { + Some((frame, mapped)) => textures.partly(index, write, frame, mapped), + None => textures.done(index, write), + } + } + + /// Title slot `index` was uploaded whole: see [`TextureQueue::recheck`]. + #[allow(clippy::too_many_arguments)] + pub(crate) fn texture_slot_recheck( + &self, + index: u32, + write: u64, + due: u64, + at: (u64, u64), + print: u64, + looks: u8, + uploaded: u64, + ) { + let mut textures = self.textures.lock().unwrap_or_else(|e| e.into_inner()); + textures.recheck(index, write, due, at, print, looks, uploaded); + } + + /// See [`TextureQueue::checked`]. + pub(crate) fn texture_slot_checked(&self, index: u32) -> Option<(u64, u64, u64, u8, u64)> { + self.textures.lock().unwrap_or_else(|e| e.into_inner()).checked(index) + } + + /// Nothing to upload at title slot `index` now (its memory is not + /// mapped, or no more of it than before): looked at again after 1, 2, + /// 4, ... frames, at most `most`. + pub(crate) fn texture_slot_later(&self, index: u32, write: u64, frame: u64, most: u64) { + let mut textures = self.textures.lock().unwrap_or_else(|e| e.into_inner()); + textures.later(index, write, frame, most); + } + + /// See [`TextureQueue::hold`]. + pub(crate) fn texture_slot_held(&self, index: u32, write: u64, due: u64) { + self.textures.lock().unwrap_or_else(|e| e.into_inner()).hold(index, write, due); + } + + /// See [`TextureQueue::room`]. + pub(crate) fn texture_slots_room(&self, frame: u64) -> usize { + self.textures.lock().unwrap_or_else(|e| e.into_inner()).room(frame) + } + + /// Bytes of title slot `index`'s memory that were mapped when it was + /// last uploaded in part (0: not uploaded, or whole). + pub(crate) fn texture_slot_mapped(&self, index: u32) -> u64 { + self.textures.lock().unwrap_or_else(|e| e.into_inner()).mapped(index) + } + + /// Takes the ranges of title memory the runtime mapped, unmapped or + /// wrote since the last call ([`remapped`]) and makes the slots whose + /// placed texture lies there due from the next frame (by when a write + /// under way has landed): memory that arrived is uploaded, memory that + /// went makes the slot null ([`HostHeap::texture_slot_gone`]), and a + /// texture streamed into the place of another of the same description + /// is uploaded although no descriptor says so. Slots tables read are + /// left to their draws. Returns how many slots it made due. + /// shortcut: the ranges are kept in one place for all heaps; the heap + /// whose pass runs first takes them (a title has one view heap). + pub(crate) fn texture_slots_remapped(&self, frame: u64) -> usize { + use std::sync::atomic::Ordering::Relaxed; + self.texture_slots_page_written(frame); + let ranges = std::mem::take(&mut *REMAPPED.lock().unwrap_or_else(|e| e.into_inner())); + if ranges.is_empty() { + return 0; + } + let mut slots: Vec = { + let placed = self.placed.lock().unwrap_or_else(|e| e.into_inner()); + ranges.iter().flat_map(|&(start, end)| placed.slots_in(start, end)).collect() + }; + slots.sort_unstable(); + slots.dedup(); + slots.retain(|&slot| !self.tabled_lately(slot, frame)); + let mut textures = self.textures.lock().unwrap_or_else(|e| e.into_inner()); + for &slot in &slots { + textures.changed(slot, frame, frame + 1); + } + STALE[3].fetch_add(slots.len() as u64, Relaxed); + slots.len() + } + + /// Takes the ranges of title memory written behind the guards' back + /// since the last call ([`page_written`]) and finds the slots whose + /// placed texture holds bytes of them ([`Spans::slots_holding`]). A + /// slot whose texture was uploaded before the write shows the bytes + /// from before: with `LEONIDA_PAGE_WRITES` (`crate::watch::page_writes`, + /// bit 2) it is due again [`PAGE_WRITE_AFTER`] frames on, as memory + /// mapped under it would make it ([`HostHeap::texture_slots_remapped`]); + /// its host copy exists, so the upload needs no room on the card. A + /// slot still waiting for its first upload is left as it is: that + /// upload takes the bytes that are there by then. Slots tables read + /// are left to their draws. Counted either way; returns how many slots + /// it made due. + fn texture_slots_page_written(&self, frame: u64) -> usize { + let ranges = std::mem::take(&mut *PAGE_WRITTEN.lock().unwrap_or_else(|e| e.into_inner())); + if ranges.is_empty() { + return 0; + } + self.slots_written_under(&ranges, frame, crate::watch::page_writes() & 2 != 0)[2] + } + + /// [`HostHeap::texture_slots_page_written`] for `ranges` (start, end): + /// the slots that held bytes of them, those of them uploaded before, + /// and those made due (the latter, if `due`). + fn slots_written_under(&self, ranges: &[(u64, u64)], frame: u64, due: bool) -> [usize; 3] { + use std::sync::atomic::Ordering::Relaxed; + let mut slots: Vec = { + let placed = self.placed.lock().unwrap_or_else(|e| e.into_inner()); + ranges.iter().flat_map(|&(start, end)| placed.slots_holding(start, end)).collect() + }; + slots.sort_unstable(); + slots.dedup(); + slots.retain(|&slot| !self.tabled_lately(slot, frame)); + let held = slots.len(); + let mut textures = self.textures.lock().unwrap_or_else(|e| e.into_inner()); + // Uploaded before: out of the queue, or in it after an upload (in + // part, or whole and being looked at again). + slots.retain(|slot| textures.slots.get(slot).is_none_or(|w| w.mapped > 0 || w.checked.2 != 0)); + PAGE_WRITES[2].fetch_add(held as u64, Relaxed); + PAGE_WRITES[3].fetch_add(slots.len() as u64, Relaxed); + if !due { + return [held, slots.len(), 0]; + } + for &slot in &slots { + textures.changed(slot, frame, frame + PAGE_WRITE_AFTER); + } + [held, slots.len(), slots.len()] + } + + /// Whether host slot `index` is made from the very record the title + /// has at `handle` now. Its host texture then exists (a slot keeps what + /// it views), so bringing that texture up to date takes no memory of + /// the card. + pub(crate) fn texture_slot_made_from(&self, index: u32, handle: u64) -> bool { + if index >= self.count { + return false; + } + // SAFETY: the handle is a descriptor slot in title memory. + let [tag, i, generation] = unsafe { (handle as *const [u32; 3]).read_unaligned() }; + let key = u64::from(generation) << 32 | u64::from(i); + if tag != VIEW_TAG { + return false; + } + // And the slot holds a host resource: a slot is also noted as made + // from a view the host could not make (`make` gave nothing, the + // slot is null and keeps nothing). The host copy of such a + // texture is held by no slot, may have been let go, and would be + // made anew here, with the card full. `made` first, then `kept`, + // as `mirror` takes them. + let made = self.made.lock().unwrap_or_else(|e| e.into_inner()); + made.get(index as usize).is_some_and(|&made| made != 0 && made == key) + && self + .kept + .lock() + .unwrap_or_else(|e| e.into_inner()) + .get(index as usize) + .is_some_and(Option::is_some) + } + + /// Levels on demand (`crate::tiles`): makes again the host slots of the + /// placed textures whose first level with memory changed since the + /// last call ([`levels_changed`]), each from the view it was made + /// from, so that it shows the texture from that level ([`make`]). Only + /// slots that are made; a slot draws read through a table is made by + /// its draw. Returns how many it made. + /// shortcut: the starts are kept in one place for all heaps; the heap + /// whose pass runs first takes them (a title has one view heap). + /// Levels on demand (`crate::tiles`): the card has room, so the slots + /// of up to [`Self::WAITING_A_PASS`] placed textures whose upload left + /// a held level without tiles at least a second ago + /// ([`levels_waiting`]) are due again from the next frame, as memory + /// mapped under them would make them + /// ([`HostHeap::texture_slots_remapped`]): the upload then gives the + /// level its tiles. To be called only while the card has room: without + /// it the upload would give nothing again. Slots tables read are left + /// to their draws (`texture.rs` `upload` asks again for those). Returns + /// how many slots it made due. + /// shortcut: kept in one place for all heaps, as the starts below. + pub(crate) fn texture_slots_waiting(&self, frame: u64) -> usize { + if self.sampler { + return 0; + } + let starts: Vec = { + let mut waiting = WAITING.lock().unwrap_or_else(|e| e.into_inner()); + if waiting.is_empty() { + return 0; + } + let starts: Vec = waiting + .iter() + .filter(|&(_, &since)| crate::host::long_ago(since, 1000, 2)) + .map(|(&start, _)| start) + .take(Self::WAITING_A_PASS) + .collect(); + for start in &starts { + waiting.remove(start); + } + starts + }; + if starts.is_empty() { + return 0; + } + let mut slots: Vec = { + let placed = self.placed.lock().unwrap_or_else(|e| e.into_inner()); + starts.iter().flat_map(|&start| placed.slots_at(start)).collect() + }; + slots.sort_unstable(); + slots.dedup(); + slots.retain(|&slot| !self.tabled_lately(slot, frame)); + let mut textures = self.textures.lock().unwrap_or_else(|e| e.into_inner()); + for &slot in &slots { + textures.changed(slot, frame, frame + 1); + } + crate::tiles::STATS[10].fetch_add(slots.len() as u64, std::sync::atomic::Ordering::Relaxed); + slots.len() + } + + /// Textures a pass asks again for their levels + /// ([`HostHeap::texture_slots_waiting`]): the first ones given tiles + /// may take the room the others were asked for, and an upload that + /// gives nothing is a whole texture staged and copied for nothing. + const WAITING_A_PASS: usize = 128; + + pub(crate) fn texture_views_remade(&self) -> usize { + if self.sampler { + return 0; + } + let starts = std::mem::take(&mut *RESHOWN.lock().unwrap_or_else(|e| e.into_inner())); + if starts.is_empty() { + return 0; + } + let slots: Vec = { + let placed = self.placed.lock().unwrap_or_else(|e| e.into_inner()); + starts.iter().flat_map(|&start| placed.slots_at(start)).collect() + }; + let made = self.made.lock().unwrap_or_else(|e| e.into_inner()); + let mut remade = 0; + for slot in slots { + let Some(&key) = made.get(slot as usize) else { + continue; + }; + if key == 0 { + continue; + } + let Some(view) = view_at(key as u32, (key >> 32) as u32) else { + continue; + }; + if let Some(kept) = make(&view, self.cpu(slot)) { + self.keep(slot, kept); + remade += 1; + } + } + remade + } + + /// The memory of the texture title slot `index` views is not mapped + /// (any more): a host slot made from it becomes null again, so that + /// the host copy can be let go (`crate::resource::let_go_idle`; a slot + /// keeps what it views). True if the slot was made. + pub(crate) fn texture_slot_gone(&self, index: u32) -> bool { + let mut made = self.made.lock().unwrap_or_else(|e| e.into_inner()); + if made.get(index as usize).is_none_or(|&key| key == 0) { + return false; + } + self.unmake(&mut made, index); + STALE[4].fetch_add(1, std::sync::atomic::Ordering::Relaxed); + true + } + + /// Makes host slot `index` null again, as it is before its view is + /// made: a null view of the kind it held. + fn unmake(&self, made: &mut [u64], index: u32) { + let Some(key) = made.get_mut(index as usize).map(std::mem::take) else { + return; + }; + if key == 0 { + return; + } + match view_at(key as u32, (key >> 32) as u32) { + Some(view) => null_for(&view, self.cpu(index)), + None => null_view(self.cpu(index)), + } + self.keep(index, None); + } + + /// Title slot `index` is a table's ([`HostHeap::tabled`]). `read`: a + /// draw read it through the table and brought what it views up to + /// date, so the slot leaves the queue of textures picked by index; the + /// caller makes the host slot in place ([`HostHeap::mirror`]), as the + /// pass would have, for a shader that picks it by index all the same. + pub(crate) fn texture_slot_tabled(&self, index: u32, read: bool) { + self.tabled_in(index, read, crate::frame::current()); + } + + /// [`HostHeap::texture_slot_tabled`] in frame `frame`. + fn tabled_in(&self, index: u32, read: bool, frame: u64) { + use std::sync::atomic::Ordering::Relaxed; + let Some(stamp) = self.tabled.get(index as usize) else { + return; + }; + let now = (frame as u32).wrapping_add(1) & !TABLED_READ; + let old = stamp.load(Relaxed); + if !read { + if old & !TABLED_READ != now { + stamp.store(now, Relaxed); + } + return; + } + // Once per slot and frame: tables are read by every draw. + if old != now | TABLED_READ { + stamp.store(now | TABLED_READ, Relaxed); + if tabled_out() { + let mut textures = self.textures.lock().unwrap_or_else(|e| e.into_inner()); + if textures.slots.remove(&index).is_some() { + TABLED_WRITES[1].fetch_add(1, Relaxed); + } + } + } + } + + /// Whether title slot `index` was a table's within the last + /// [`TABLED_FRAMES`] frames before `frame` (never, if such slots are + /// to be queued as any other). + fn tabled_lately(&self, index: u32, frame: u64) -> bool { + let stamp = self.tabled_stamp(index) & !TABLED_READ; + let now = (frame as u32).wrapping_add(1) & !TABLED_READ; + tabled_out() && stamp != 0 && u64::from(now.wrapping_sub(stamp)) <= TABLED_FRAMES + } + + /// What `tabled` holds for title slot `index`; 0: never a table's. + fn tabled_stamp(&self, index: u32) -> u32 { + self.tabled + .get(index as usize) + .map_or(0, |s| s.load(std::sync::atomic::Ordering::Relaxed)) + } + + /// The queue's part of a write of title slot `index` in `frame`: + /// `texture`, whether it now holds a view of a texture the title may + /// fill; `seen` as for [`HostHeap::note_buffer`]. + fn queue_texture(&self, index: u32, texture: bool, seen: bool, frame: u64) { + let stamp = if tabled_out() { self.tabled_stamp(index) } else { 0 }; + let now = (frame as u32).wrapping_add(1) & !TABLED_READ; + // A table's slot lately: the draw that reads it uploads its + // texture, so its write waits for that draw. + let lately = stamp != 0 && u64::from(now.wrapping_sub(stamp & !TABLED_READ)) <= TABLED_FRAMES; + // Made now by a draw of this frame that read it through a table: + // up to date. + let read_now = seen && stamp == now | TABLED_READ; + let mut textures = self.textures.lock().unwrap_or_else(|e| e.into_inner()); + if texture && !read_now { + let due = if lately && !seen { + TABLED_WRITES[0].fetch_add(1, std::sync::atomic::Ordering::Relaxed); + frame + TABLED_GRACE + } else { + 0 + }; + textures.written(index, frame, due, seen); + } else { + textures.remove(index); + } + } + + /// The title slots that hold buffer views. + pub(crate) fn buffer_slots(&self) -> Vec { + let buffers = self.buffers.lock().unwrap_or_else(|e| e.into_inner()); + buffers.iter().copied().collect() + } + + /// The title slots whose buffer view was written, or went, since the + /// last call. + pub(crate) fn buffer_changes(&self) -> Vec { + let mut changed = self.changed.lock().unwrap_or_else(|e| e.into_inner()); + std::mem::take(&mut *changed).into_iter().collect() + } + + /// Records what title slot `index` now holds for shaders that pick + /// buffers from the heap: its element stride in the table, and whether + /// it is a buffer view at all. + /// `seen`: the slot was not written now, a draw or a pass made its + /// host slot from what it held. + /// Returns the title slots whose placed texture view the write made + /// stale ([`Spans`]): out of the queue of textures already, their host + /// slots are the caller's to make null (it holds `made`). + fn note_buffer(&self, index: u32, view: Option<&View>, seen: bool) -> Vec { + if self.sampler { + return Vec::new(); + } + // Measured for the texture side of the same gap (textures a shader + // picks by a computed index are neither made, if placed, nor + // uploaded): slots written with a placed texture view, and with a + // view of a texture object. + let texture = match view { + Some(View::Placed(false, resource, _)) if resource[0] != 1 => { + PLACED_TEXTURE_SLOTS.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + true + } + Some(View::Shader(r, _)) if crate::resource::buffer_bytes(*r as crate::object::This).is_none() => { + OBJECT_TEXTURE_SLOTS.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + true + } + _ => false, + }; + self.queue_texture(index, texture, seen, crate::frame::current()); + // The memory a placed texture view describes. Not for a slot + // tables read (thousands of writes a frame, each read by its + // draw): no pass looks at it, and the same texture's view in a + // slot shaders pick by index says what it says. + let placed_view = match view { + Some(View::Placed(false, resource, desc)) + if resource[0] != 1 && !self.tabled_lately(index, crate::frame::current()) => + { + // (And the level the view starts at: word 4 of a texture + // view's description, after format, dimension, mapping + // and a pad.) + Some((resource, u64::from(desc[10]) | u64::from(desc[11]) << 32, desc[4])) + } + _ => None, + }; + let stale = { + use std::sync::atomic::Ordering::Relaxed; + let mut placed = self.placed.lock().unwrap_or_else(|e| e.into_inner()); + let span = placed_view.and_then(|(resource, start, first)| { + Some((start, start.saturating_add(placed.bytes(resource)?), first)) + }); + match span { + Some((start, end, first)) => { + SPANNED[0].fetch_min(start, Relaxed); + SPANNED[1].fetch_max(end, Relaxed); + placed.rule = stale_rule(); + let stale = placed.note(index, start, end, !seen); + placed.shows(index, first); + stale + } + None => { + placed.forget(index); + Vec::new() + } + } + }; + if !stale.is_empty() { + STALE[0].fetch_add(stale.len() as u64, std::sync::atomic::Ordering::Relaxed); + let mut textures = self.textures.lock().unwrap_or_else(|e| e.into_inner()); + for &slot in &stale { + textures.remove(slot); + } + } + let stride = view.and_then(view_stride); + if let Some((_, _, data)) = &self.strides + && index < leonida_shader::emit::SLOT_STRIDES_COUNT + { + // SAFETY: inside the mapping; shaders read it while we write (a + // dword, either value is one the slot had). + unsafe { (*data as *mut u32).add(index as usize).write_volatile(stride.unwrap_or(0)) }; + } + let mut buffers = self.buffers.lock().unwrap_or_else(|e| e.into_inner()); + let was = if stride.is_some() { + buffers.insert(index); + true + } else { + buffers.remove(&index) + }; + if was { + self.changed + .lock() + .unwrap_or_else(|e| e.into_inner()) + .insert(index); + } + stale + } + + /// Gives back `n` dynamic slots from `first` (an index [`dynamic`] + /// returned). + /// + /// [`dynamic`]: HostHeap::dynamic + pub(crate) fn release(&self, first: u32, n: u32) { + let Some(at) = first.checked_sub(self.count) else { + return; + }; + let mut guard = self.next.lock().unwrap_or_else(|e| e.into_inner()); + let end = (at + n).min(self.dynamic) as usize; + if let Some(slots) = guard.1.get_mut(at as usize..end) { + let given = slots.iter().filter(|taken| **taken).count() as u32; + self.free.fetch_add(given, std::sync::atomic::Ordering::Relaxed); + self.too_long.store(u32::MAX, std::sync::atomic::Ordering::Relaxed); + slots.fill(false); + } + } + + /// Makes slot `index` (a dynamic one) from `view`; a null view if the + /// host cannot. + pub(crate) fn make_at(&self, index: u32, view: &View) { + let kept = make(view, self.cpu(index)); + if kept.is_none() { + null_for(view, self.cpu(index)); + } + self.keep(index, kept.flatten()); + } + + /// Makes slot `index` read nothing: a null view, or a plain sampler. + pub(crate) fn make_null(&self, index: u32) { + if self.sampler { + self.null_sampler(index); + } else { + null_view(self.cpu(index)); + } + self.keep(index, None); + } + + /// Slot `index` now views `resource` (or nothing of the host's). + fn keep(&self, index: u32, resource: Option) { + let mut kept = self.kept.lock().unwrap_or_else(|e| e.into_inner()); + if let Some(slot) = kept.get_mut(index as usize) { + // A running submission may still read the old resource through + // this slot. + if let Some(old) = std::mem::replace(slot, resource) { + crate::host::retire(old); + } + } + } + + /// Makes slot `index` (a dynamic one) a raw buffer view of `len` bytes + /// of `buffer` from byte `offset` (a multiple of 16): a root SRV with a + /// size, whose reads past it return zeros instead of reaching whatever + /// the host placed after the buffer. + pub(crate) fn raw_at(&self, index: u32, buffer: &ID3D12Resource, offset: u64, len: u64) { + let Some(host) = host() else { return }; + let elements = (len / 4).clamp(1, u64::from(u32::MAX)) as u32; + let desc = D3D12_SHADER_RESOURCE_VIEW_DESC { + Format: DXGI_FORMAT_R32_TYPELESS, + ViewDimension: D3D12_SRV_DIMENSION_BUFFER, + Shader4ComponentMapping: D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING, + Anonymous: D3D12_SHADER_RESOURCE_VIEW_DESC_0 { + Buffer: D3D12_BUFFER_SRV { + FirstElement: offset / 4, + NumElements: elements, + StructureByteStride: 0, + Flags: D3D12_BUFFER_SRV_FLAG_RAW, + }, + }, + }; + // SAFETY: a slot of our heap and a live buffer covering the range. + unsafe { + host.device + .CreateShaderResourceView(buffer, Some(&desc), self.cpu(index)) + }; + self.keep(index, Some(buffer.clone())); + } + + /// Makes slot `index` (a dynamic one) a raw buffer view that reads + /// zeros. + pub(crate) fn null_raw_at(&self, index: u32) { + null_buffer_view(self.cpu(index)); + self.keep(index, None); + } + + /// Makes slot `index` (a dynamic one) a raw unordered access view of + /// `len` bytes of `buffer` from byte `offset` (a multiple of 16): a + /// root UAV with a size, whose accesses past it do nothing instead of + /// reaching whatever the host placed after the buffer. + pub(crate) fn raw_uav_at(&self, index: u32, buffer: &ID3D12Resource, offset: u64, len: u64) { + let Some(host) = host() else { return }; + let elements = (len / 4).clamp(1, u64::from(u32::MAX)) as u32; + let desc = D3D12_UNORDERED_ACCESS_VIEW_DESC { + Format: DXGI_FORMAT_R32_TYPELESS, + ViewDimension: D3D12_UAV_DIMENSION_BUFFER, + Anonymous: D3D12_UNORDERED_ACCESS_VIEW_DESC_0 { + Buffer: D3D12_BUFFER_UAV { + FirstElement: offset / 4, + NumElements: elements, + StructureByteStride: 0, + CounterOffsetInBytes: 0, + Flags: D3D12_BUFFER_UAV_FLAG_RAW, + }, + }, + }; + // SAFETY: a slot of our heap and a live buffer covering the range. + unsafe { + host.device.CreateUnorderedAccessView( + buffer, + None::<&ID3D12Resource>, + Some(&desc), + self.cpu(index), + ) + }; + self.keep(index, Some(buffer.clone())); + } + + /// Makes slot `index` (a dynamic one) a raw unordered access view of + /// nothing: reads give zeros, writes are dropped. + pub(crate) fn null_raw_uav_at(&self, index: u32) { + self.keep(index, None); + let Some(host) = host() else { return }; + let desc = D3D12_UNORDERED_ACCESS_VIEW_DESC { + Format: DXGI_FORMAT_R32_TYPELESS, + ViewDimension: D3D12_UAV_DIMENSION_BUFFER, + Anonymous: D3D12_UNORDERED_ACCESS_VIEW_DESC_0 { + Buffer: D3D12_BUFFER_UAV { + NumElements: 1, + Flags: D3D12_BUFFER_UAV_FLAG_RAW, + ..Default::default() + }, + }, + }; + // SAFETY: a slot of our heap; a null resource is allowed with a desc. + unsafe { + host.device.CreateUnorderedAccessView( + None::<&ID3D12Resource>, + None::<&ID3D12Resource>, + Some(&desc), + self.cpu(index), + ) + }; + } + + /// The shader-visible handle of slot `index`. + pub(crate) fn gpu_handle(&self, index: u32) -> D3D12_GPU_DESCRIPTOR_HANDLE { + // SAFETY: a live shader-visible heap. + let start = unsafe { self.heap.GetGPUDescriptorHandleForHeapStart().ptr }; + D3D12_GPU_DESCRIPTOR_HANDLE { + ptr: start + u64::from(index) * u64::from(self.step), + } + } + + /// Makes slot `index` (a dynamic one) a constant buffer view of host + /// memory (the list's own, which it holds). + pub(crate) fn constant_at(&self, index: u32, gpu: u64, size: u32) { + self.keep(index, None); + let Some(host) = host() else { return }; + let desc = D3D12_CONSTANT_BUFFER_VIEW_DESC { + BufferLocation: gpu, + SizeInBytes: size.next_multiple_of(256), + }; + // SAFETY: a slot of our heap; the memory is the caller's. + unsafe { + host.device + .CreateConstantBufferView(Some(&desc), self.cpu(index)) + }; + } + + fn cpu(&self, index: u32) -> D3D12_CPU_DESCRIPTOR_HANDLE { + D3D12_CPU_DESCRIPTOR_HANDLE { + ptr: self.cpu + index as usize * self.step as usize, + } + } + + /// For a slot on a page of the title's heap that changed with no call + /// (`super::sync_heaps`: the title copies records into its heap as + /// bytes): [`HostHeap::mirror`], if the `bytes` bytes of the record at + /// `handle` are not the ones this last saw there. True if it did. + /// + /// The page says only that something on it was written, and `mirror` + /// by itself would take every buffer or placed-texture record on it for + /// newly written each time (it leaves such a slot unmade until a draw + /// or a pass uses it): the texture queue's entry for the slot would + /// start again, and the buffer pass would look at 2,048 slots for one + /// that changed. + /// `record`: the record's bytes as the caller read them (through the + /// kernel, which fails on a page the title unmapped meanwhile where a + /// read in place would fault: the title unmaps heap pages too). + pub(crate) fn mirror_copied(&self, index: u32, handle: u64, record: &[u8]) -> bool { + if index >= self.count { + return false; + } + // A slot draws read through a table lately is left to its draws, + // as the passes over slots picked by index leave it + // (`texture_slots_remapped`, `slots_written_under`): the title + // writes its per-draw tables into the same heap every frame, and + // each draw makes what its table shows in a slot of its own. Those + // were most of the 26,000 to 43,000 records a frame this pass + // mirrored in run 200 and in the play session after it, each then + // made and brought up to date once more by the pass over buffer + // views (some 50 ms a frame). `LEONIDA_HEAP_SYNC_TABLES=1`: they + // are mirrored too, as in run 200. + if !sync_tables() && self.tabled_lately(index, crate::frame::current()) { + COPIED_TABLED.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + return false; + } + let n = record.len(); + // Never 0, which is "never looked at". (A multiply-and-fold over + // the record's words: BLAKE3 here was most of the 35 to 42 ms a + // frame this pass took over some 250,000 to 300,000 records, run + // 200.) + let print = record_print(record) | 1; + { + let mut copied = self.copied.lock().unwrap_or_else(|e| e.into_inner()); + if copied.is_empty() { + copied.resize(self.count as usize, 0); + } + let Some(last) = copied.get_mut(index as usize) else { + return false; + }; + // A slot never looked at that holds nothing: as it was. + if *last == print || (*last == 0 && record[..n].iter().all(|&b| b == 0)) { + return false; + } + *last = print; + } + self.mirror(index, handle, false); + true + } + + /// [`HostHeap::mirror_copied`] for every record of one changed page of + /// the title's heap (`super::sync_heaps`): title slots `slots`, the + /// record of slot `i` at title address `start + i * step`, and `page` + /// the bytes read from title address `from` on. Returns the records + /// looked at and those mirrored. + /// + /// The same records are mirrored as one by one. What differs is the + /// work for the others, which are nearly all of them (some 330,000 + /// looked at a frame for 14,000 mirrored, 16 ms, run 225): the lock of + /// the fingerprints is taken once for the page and not once for each + /// record, and a record whose fingerprint is the one last seen is done + /// with before the question whether its slot was a table's lately. So + /// the count of slots "left to the draws" is now of records that + /// changed, not of every record on the page. The slots to mirror are + /// made after the page's walk, in slot order as before. + pub(crate) fn mirror_copied_page( + &self, + slots: std::ops::Range, + (start, step): (u64, u64), + from: usize, + page: &[u8], + ) -> (u64, u64) { + let (frame, tables) = (crate::frame::current(), sync_tables()); + let mut looked = 0u64; + let mut due: Vec<(u32, u64)> = Vec::new(); + { + let mut copied = self.copied.lock().unwrap_or_else(|e| e.into_inner()); + if copied.is_empty() { + copied.resize(self.count as usize, 0); + } + for index in slots { + let handle = start + index * step; + // A record that straddles the range's ends is left to the + // range that holds its first byte. + let Some(at) = (handle as usize).checked_sub(from) else { + continue; + }; + let Some(record) = page.get(at..at + step as usize) else { + continue; + }; + looked += 1; + // None past the host heap's slots, as `mirror_copied`. + let Some(last) = copied.get_mut(index as usize) else { + continue; + }; + // Never 0, which is "never looked at". + let print = record_print(record) | 1; + // The record last seen, or a slot never looked at that + // holds nothing: as it was. + if *last == print || (*last == 0 && record.iter().all(|&b| b == 0)) { + continue; + } + // A table's slot lately: left to its draws, and looked at + // again next time. + if !tables && self.tabled_lately(index as u32, frame) { + COPIED_TABLED.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + continue; + } + *last = print; + due.push((index as u32, handle)); + } + } + for &(index, handle) in &due { + self.mirror(index, handle, false); + } + (looked, due.len() as u64) + } + + /// Makes host slot `index` from the record the title has at `handle` + /// if it changed since, and returns the view recorded there. Buffer + /// views are made only for draws (`for_draw`), which also copy their + /// data: a host copy of a buffer is made on first use. + pub(crate) fn mirror(&self, index: u32, handle: u64, for_draw: bool) -> Option { + if index >= self.count { + // Diagnostic (NVIDIA heap cap): the highest title slot past the + // host heap seen so far. + static HIGHEST: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); + if HIGHEST.fetch_max(index, std::sync::atomic::Ordering::Relaxed) < index { + tracing::warn!( + index, + count = self.count, + for_draw, + "title slot past the host heap" + ); + } + return None; + } + // SAFETY: the handle is a descriptor slot in title memory. + let [tag, i, generation] = unsafe { (handle as *const [u32; 3]).read_unaligned() }; + // Generations start at 1, so a made slot's key is never 0. + let key = u64::from(generation) << 32 | u64::from(i); + let mut made = self.made.lock().unwrap_or_else(|e| e.into_inner()); + let view = (tag == VIEW_TAG).then(|| view_at(i, generation)).flatten(); + let Some(view) = view else { + // Not a view of ours (never written, or of a resource the + // title released): nothing to read. + if made[index as usize] != 0 { + made[index as usize] = 0; + self.make_null(index); + let _ = self.note_buffer(index, None, false); + } else if for_draw { + // Left for later and stale since: out of the sets and the stride table. + let _ = self.note_buffer(index, None, false); + } + return None; + }; + if made[index as usize] != key { + // Views of other textures in the memory this one describes + // are stale: their host slots read nothing from here on, and + // let go of the host copies they held. + for stale in self.note_buffer(index, Some(&view), for_draw) { + if stale != index { + self.unmake(&mut made, stale); + } + } + // A view of a texture object that has no host copy yet waits + // for it, as buffer views wait for a draw: the slot is made + // when the texture is first used (`super::make_waiting`), or + // here when a draw reads the slot through a table. + let waiting = if for_draw { None } else { view.waiting_texture() }; + if let Some(texture) = waiting { + super::wait_for(texture, handle); + } + let later = !for_draw && (view.is_buffer() || waiting.is_some()); + // Another view of the placed texture the slot shows already (a + // title that streams a texture in writes its view again with + // more mips each time some arrive): the slot goes on showing + // the old view until a draw or the texture pass makes the new + // one and uploads what it shows. Made null here, the texture + // read as nothing for as long as it waited in the queue, every + // time it got sharper. + if later + && keep_views() + && view_at(made[index as usize] as u32, (made[index as usize] >> 32) as u32) + .is_some_and(|old| same_placed_texture(&old, &view)) + { + KEPT_VIEWS.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + return Some(view); + } + made[index as usize] = if later { 0 } else { key }; + let kept = if later { + None + } else { + make(&view, self.cpu(index)) + }; + if kept.is_none() && !self.sampler { + null_for(&view, self.cpu(index)); + } + self.keep(index, kept.flatten()); + } + Some(view) + } + + /// Whether slot `index` is backed by a made host descriptor (tests). + #[cfg(test)] + pub(crate) fn made(&self, index: u32) -> bool { + self.made + .lock() + .unwrap_or_else(|e| e.into_inner()) + .get(index as usize) + .is_some_and(|&key| key != 0) + } + + /// Whether host slot `index` shows `buffer`; `None` if it shows no + /// resource (diagnostics: a buffer view's slot must show the host copy + /// that is brought up to date for it). + #[cfg(feature = "diagnostics")] + pub(crate) fn shows(&self, index: u32, buffer: &ID3D12Resource) -> Option { + let kept = self.kept.lock().unwrap_or_else(|e| e.into_inner()); + let shown = kept.get(index as usize)?.as_ref()?; + Some(windows::core::Interface::as_raw(shown) == windows::core::Interface::as_raw(buffer)) + } + + /// What the queue of textures picked by index knows of title slot + /// `index` at `frame`, in a few words (diagnostics). + #[cfg(feature = "diagnostics")] + pub(crate) fn texture_slot_state(&self, index: u32, frame: u64) -> String { + let textures = self.textures.lock().unwrap_or_else(|e| e.into_inner()); + match textures.slots.get(&index) { + None => "not queued".into(), + Some(w) => format!( + "queued due={} written@{} looks={} part_mapped={} recheck={}", + if w.due <= frame { "now".to_string() } else { format!("@{}", w.due) }, + w.written, + w.looks, + w.mapped, + w.checked.2 != 0 + ), + } + } + + /// The view host slot `index` was made from, in a few words, with the + /// title and host addresses of a buffer view (diagnostics). "null" for + /// a slot never made or left null. + #[cfg(feature = "diagnostics")] + pub(crate) fn describe_slot(&self, index: u32) -> Option { + let key = *self.made.lock().unwrap_or_else(|e| e.into_inner()).get(index as usize)?; + if key == 0 { + return Some("null".into()); + } + let view = view_at(key as u32, (key >> 32) as u32)?; + let mut text: String = format!("{view:?}").chars().take(120).collect(); + if let Some((address, len)) = buffer_range(&view) { + let host = crate::shadow::find(address, len.max(1)).map(|s| s.gpu(address)); + text.push_str(&format!(" title {address:#x}+{len:#x} host {host:#x?}")); + } + Some(text) + } +} + +/// Logs `what` the first time it happens. +macro_rules! once { + ($($arg:tt)*) => {{ + static ONCE: std::sync::Once = std::sync::Once::new(); + ONCE.call_once(|| tracing::warn!($($arg)*)); + }}; +} + +/// A view description from its words, with the format as the host has it. +fn srv_desc(words: &[u32; 10]) -> D3D12_SHADER_RESOURCE_VIEW_DESC { + let mut words = *words; + words[0] = crate::resource::pc_format(words[0]); + // SAFETY: 40 bytes in the host's layout. + unsafe { + std::ptr::from_ref(&words) + .cast::() + .read_unaligned() + } +} + +fn uav_desc(words: &[u32; 10]) -> D3D12_UNORDERED_ACCESS_VIEW_DESC { + let mut words = *words; + words[0] = crate::resource::pc_format(words[0]); + // SAFETY: 40 bytes in the host's layout. + unsafe { + std::ptr::from_ref(&words) + .cast::() + .read_unaligned() + } +} + +/// A buffer view of title memory at `address` on its host copy: the first +/// element moves by the copy's offset. +/// Bytes per element of a buffer view. +fn element_size(desc: &D3D12_SHADER_RESOURCE_VIEW_DESC) -> u64 { + // SAFETY: a buffer view's union member. + let buffer = unsafe { desc.Anonymous.Buffer }; + if buffer.StructureByteStride > 0 { + u64::from(buffer.StructureByteStride) + } else if buffer.Flags.0 & D3D12_BUFFER_SRV_FLAG_RAW.0 != 0 { + 4 + } else { + crate::resource::element(desc.Format.0 as u32).map_or(0, |(bytes, _)| bytes) + } +} + +/// The title memory a buffer shader or unordered access view reads: its +/// address and length. +pub(crate) fn buffer_range(view: &View) -> Option<(u64, u64)> { + let (base, words): (u64, &[u32; 10]) = match view { + View::Shader(r, Some(desc)) => ( + crate::resource::buffer_bytes(*r as crate::object::This)?.0 as u64, + desc, + ), + View::Placed(false, resource, desc) if resource[0] == 1 => ( + u64::from(desc[10]) | u64::from(desc[11]) << 32, + desc[..10].try_into().ok()?, + ), + View::Unordered(r, _, Some(desc)) => { + let base = crate::resource::buffer_bytes(*r as crate::object::This)?.0 as u64; + return unordered_range(base, desc); + } + View::Placed(true, resource, desc) if resource[0] == 1 => { + let base = u64::from(desc[10]) | u64::from(desc[11]) << 32; + return unordered_range(base, desc[..10].try_into().ok()?); + } + _ => return None, + }; + let desc = srv_desc(words); + let element = element_size(&desc); + // SAFETY: a buffer view's union member. + let buffer = unsafe { desc.Anonymous.Buffer }; + Some(( + base + buffer.FirstElement * element, + u64::from(buffer.NumElements) * element, + )) +} + +/// The title memory the host slot of buffer view `view` is made on +/// (address, bytes): the whole buffer the view is of, which is what +/// [`make`] finds the host copy by. [`buffer_range`] is the part of it the +/// view reads. +pub(crate) fn buffer_extent(view: &View) -> Option<(u64, u64)> { + match view { + View::Shader(r, Some(_)) | View::Unordered(r, _, Some(_)) => { + let (data, len) = crate::resource::buffer_bytes(*r as crate::object::This)?; + Some((data as u64, len)) + } + View::Placed(_, resource, desc) if resource[0] == 1 => Some(( + u64::from(desc[10]) | u64::from(desc[11]) << 32, + u64::from(resource[4]) | u64::from(resource[5]) << 32, + )), + _ => None, + } +} + +/// Whether a buffer view is brought up to date in the host copy its slot +/// shows ([`buffer_copy`]). On by default; `LEONIDA_VIEW_EXTENT=0` looks the +/// copy up by the view's range alone, as before. +fn view_extent() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("LEONIDA_VIEW_EXTENT").is_none_or(|v| v != "0")) +} + +/// The host copy buffer view `view` reads, and the title range (address, +/// bytes) it reads there; `None` for other views and empty ranges. +/// +/// The copy is the one the view's slot shows: [`make`] finds it by the +/// whole buffer the view is of ([`buffer_extent`]). Looked up by the range +/// the view reads, as it was, the copy is another one wherever the two +/// lookups differ: for memory outside buffer objects, a view of a part of a +/// buffer that crosses a window line (the buffer's window is two cells, the +/// part's one), and for buffer objects, a part that also lies in a smaller +/// buffer object. The slot then showed a copy nothing brought up to date, +/// and what shaders wrote through it was looked for in the other copy. +pub(crate) fn buffer_copy(view: &View) -> Option<(std::sync::Arc, u64, u64)> { + let (address, len) = buffer_range(view)?; + if len == 0 { + return None; + } + // A view off its buffer's elements is made on a copy of its own bytes + // (`own_bytes`): the same question `buffer_srv` and `buffer_uav` ask, + // of the copy they find, so that the copy brought up to date is the + // one the slot shows. + if let Some((base, width)) = buffer_extent(view) + && let Some((first, count, element, stride, unknown)) = buffer_fields(view) + && let Some(whole) = crate::shadow::find(base, width) + && let Some((start, bytes)) = own_bytes(whole.offset(base), base, first, count, element, stride, unknown) + && let Some(own) = crate::shadow::exact(start, bytes) + { + return Some((own, start, bytes)); + } + if view_extent() + && let Some((base, width)) = buffer_extent(view) + // (The console is lax: a view may begin past its buffer's end.) + && address >= base + && address - base < width.max(1) + && let Some(shadow) = crate::shadow::find(base, width) + { + return Some((shadow, address, len)); + } + crate::shadow::find(address, len).map(|shadow| (shadow, address, len)) +} + +/// [`buffer_range`] of an unordered access view of memory at `base`. +fn unordered_range(base: u64, words: &[u32; 10]) -> Option<(u64, u64)> { + let desc = uav_desc(words); + // SAFETY: a buffer view's union member. + let buffer = unsafe { desc.Anonymous.Buffer }; + let element = if buffer.StructureByteStride > 0 { + u64::from(buffer.StructureByteStride) + } else if buffer.Flags.0 & D3D12_BUFFER_UAV_FLAG_RAW.0 != 0 { + 4 + } else { + crate::resource::element(desc.Format.0 as u32)?.0 + }; + Some(( + base + buffer.FirstElement * element, + u64::from(buffer.NumElements) * element, + )) +} + +/// The host resource a slot made by [`make`] views, if any. +type Kept = Option; + +/// Whether the pass over records copied in as bytes also mirrors slots +/// that draws read through tables lately (`LEONIDA_HEAP_SYNC_TABLES=1`; +/// off by default: [`HostHeap::mirror_copied`]). +fn sync_tables() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("LEONIDA_HEAP_SYNC_TABLES").is_some_and(|v| v == "1")) +} + +/// Since the last frame line: slots on changed heap pages that +/// [`HostHeap::mirror_copied`] left to their draws (tables' slots). +pub(crate) static COPIED_TABLED: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + +/// A 64-bit fingerprint of a descriptor record's bytes (16 or 32 of them): +/// equal records give equal prints, and two different records the same +/// print about once in 2^64. Not a hash anyone can attack: the records +/// are our own. +fn record_print(record: &[u8]) -> u64 { + const K: u64 = 0x9e37_79b9_7f4a_7c15; + let mut h = K ^ record.len() as u64; + let mut words = record.chunks_exact(8); + for word in &mut words { + let w = u64::from_le_bytes(word.try_into().unwrap_or([0; 8])); + h = (h ^ w).wrapping_mul(K); + h ^= h >> 29; + } + for &b in words.remainder() { + h = (h ^ u64::from(b)).wrapping_mul(K); + } + h ^ (h >> 32) +} + +/// Whether a buffer view off its buffer's elements gets a copy of its own +/// bytes (`LEONIDA_VIEW_OWN_COPY=0`: it is refused and reads zeros, as +/// before). +fn own_copy_on() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("LEONIDA_VIEW_OWN_COPY").is_none_or(|v| v != "0")) +} + +/// The title memory (start, bytes) of a buffer view that cannot be made on +/// the host copy of its buffer: `count` elements of `element` bytes from +/// element `first` of the buffer at `base`, which lies `offset` bytes into +/// that copy, where `offset` is not a whole number of elements and the view +/// cannot be a raw view of the same bytes either ([`raw_window`]: +/// `unknown`, the view has no format, and `stride` is its structure's). +/// The host counts a view's first element from its buffer's start, so such +/// a view has no host view there; it is made on a copy of its own bytes +/// (`crate::shadow::exact`), where it starts at element 0. `None`: the +/// view is made on its buffer's copy, as every other. +fn own_bytes(offset: u64, base: u64, first: u64, count: u32, element: u64, stride: u32, unknown: bool) -> Option<(u64, u64)> { + own_bytes_if(own_copy_on(), offset, base, first, count, element, stride, unknown) +} + +#[allow(clippy::too_many_arguments)] +fn own_bytes_if( + on: bool, + offset: u64, + base: u64, + first: u64, + count: u32, + element: u64, + stride: u32, + unknown: bool, +) -> Option<(u64, u64)> { + if !on || element == 0 || count == 0 || offset.is_multiple_of(element) { + return None; + } + if unknown && raw_window(offset, first, count, stride).is_some() { + return None; + } + let start = base.checked_add(first.checked_mul(element)?)?; + Some((start, u64::from(count) * element)) +} + +/// Of a buffer view: its first element, its elements, the bytes of one (a +/// raw view's: 4), its structure's stride, and whether it has no format. +/// As [`buffer_srv`] and [`buffer_uav`] read them from the same words. +fn buffer_fields(view: &View) -> Option<(u64, u32, u64, u32, bool)> { + const BUFFER: u32 = 1; + let (words, unordered): (&[u32; 10], bool) = match view { + View::Shader(_, Some(d)) if d[1] == BUFFER => (d, false), + View::Unordered(_, _, Some(d)) if d[1] == BUFFER => (d, true), + View::Placed(unordered, resource, d) if resource[0] == BUFFER => (d[..10].try_into().ok()?, *unordered), + _ => return None, + }; + if unordered { + let d = uav_desc(words); + // SAFETY: a buffer view's union member. + let b = unsafe { d.Anonymous.Buffer }; + let element = if b.StructureByteStride > 0 { + u64::from(b.StructureByteStride) + } else if b.Flags.0 & D3D12_BUFFER_UAV_FLAG_RAW.0 != 0 { + 4 + } else { + crate::resource::element(d.Format.0 as u32).map_or(0, |(bytes, _)| bytes) + }; + Some((b.FirstElement, b.NumElements, element, b.StructureByteStride, d.Format == DXGI_FORMAT_UNKNOWN)) + } else { + let d = srv_desc(words); + // SAFETY: a buffer view's union member. + let b = unsafe { d.Anonymous.Buffer }; + Some((b.FirstElement, b.NumElements, element_size(&d), b.StructureByteStride, d.Format == DXGI_FORMAT_UNKNOWN)) + } +} + +/// A structured buffer view (`first`, `count` elements of `stride` bytes, +/// `offset` bytes into its host copy) as a raw view of the same bytes: +/// its first dword and its dwords. Translated shaders read untyped buffers +/// as raw bytes at `element * stride + offset` (the stride from the +/// used-resource entry, or from the table by heap slot for a buffer picked +/// by index), and a raw read through a structured view gives zeros on +/// NVIDIA (reported upstream with PR #193; structured reads through raw +/// views were right there). So the host's view is raw whenever it can be: +/// the bytes must start on 16 (the host's raw view alignment) and be whole +/// dwords. A view that cannot stays structured. +fn raw_window(offset: u64, first: u64, count: u32, stride: u32) -> Option<(u64, u32)> { + if stride == 0 { + return None; + } + let start = first.checked_mul(u64::from(stride))?.checked_add(offset)?; + let bytes = u64::from(count) * u64::from(stride); + (start % 16 == 0 && bytes % 4 == 0) + .then(|| u32::try_from(bytes / 4).ok().map(|dwords| (start / 4, dwords))) + .flatten() +} + +/// Whether the host accepts a buffer view with these fields of a buffer of +/// `width` bytes. It removes the device for one it does not (view creation +/// returns nothing), and the console is laxer: the title's heap holds +/// views past their memory's end, of no elements, of typeless formats +/// without the raw flag, with strides the host has no structured buffers +/// for. Since every buffer view of the heap is made for shaders that pick +/// them by index, one such view ended the run (2026-11-24, run 10). +fn buffer_view_ok(format: DXGI_FORMAT, first: u64, count: u32, stride: u32, raw: bool, width: u64) -> bool { + use crate::resource::family; + let f = format.0 as u32; + let element = if raw { + // raw: R32 typeless, counted in dwords, starting on 16 bytes + if format != DXGI_FORMAT_R32_TYPELESS || stride != 0 || !first.is_multiple_of(4) { + return false; + } + 4 + } else if stride > 0 { + // structured: no format, a stride the host takes + if format != DXGI_FORMAT_UNKNOWN || stride > 2048 || !stride.is_multiple_of(4) { + return false; + } + u64::from(stride) + } else { + // typed: a format with a size that is not typeless + let typeless = family(f) == f && family(f + 1) == f; + match crate::resource::element(f) { + Some((bytes, 1)) if f != 0 && !typeless && bytes > 0 => bytes, + _ => return false, + } + }; + count > 0 + && first + .checked_add(u64::from(count)) + .and_then(|end| end.checked_mul(element)) + .is_some_and(|end| end <= width) +} + +fn buffer_srv( + address: u64, + len: u64, + mut desc: D3D12_SHADER_RESOURCE_VIEW_DESC, + at: D3D12_CPU_DESCRIPTOR_HANDLE, +) -> Option { + let shadow = crate::shadow::find(address, len)?; + let offset = shadow.offset(address); + // Off the elements of that copy: on a copy of its own bytes, from its + // element 0 (`own_bytes`). + let (shadow, offset) = { + // SAFETY: a buffer view's union member. + let b = unsafe { desc.Anonymous.Buffer }; + let unknown = desc.Format == DXGI_FORMAT_UNKNOWN; + match own_bytes(offset, address, b.FirstElement, b.NumElements, element_size(&desc), b.StructureByteStride, unknown) + .and_then(|(start, bytes)| crate::shadow::exact(start, bytes)) + { + Some(own) => { + desc.Anonymous.Buffer.FirstElement = 0; + (own, 0) + } + None => (shadow, offset), + } + }; + // A structured view as a raw view of the same bytes (see `raw_window`). + // SAFETY: a buffer view's union member. + let structured = unsafe { desc.Anonymous.Buffer }; + let window = (desc.Format == DXGI_FORMAT_UNKNOWN) + .then(|| raw_window(offset, structured.FirstElement, structured.NumElements, structured.StructureByteStride)) + .flatten(); + if let Some((first, count)) = window { + desc.Format = DXGI_FORMAT_R32_TYPELESS; + desc.Anonymous.Buffer = D3D12_BUFFER_SRV { + FirstElement: first, + NumElements: count, + StructureByteStride: 0, + Flags: D3D12_BUFFER_SRV_FLAG_RAW, + }; + } + let element = element_size(&desc); + // SAFETY: a buffer view's union member. + let buffer = unsafe { &mut desc.Anonymous.Buffer }; + if window.is_none() { + if element == 0 || offset % element != 0 { + once!( + offset, + element, + "buffer view not on an element of its host copy" + ); + return None; + } + buffer.FirstElement += offset / element; + } + let (first, count, stride) = (buffer.FirstElement, buffer.NumElements, buffer.StructureByteStride); + let raw = buffer.Flags.0 & D3D12_BUFFER_SRV_FLAG_RAW.0 != 0; + // SAFETY: a live buffer. + let width = unsafe { shadow.buffer.GetDesc() }.Width; + if !buffer_view_ok(desc.Format, first, count, stride, raw, width) { + REFUSED_VIEWS.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + once!( + format = desc.Format.0, + first, + count, + stride, + raw, + width, + "buffer view the host would refuse left null" + ); + return None; + } + // The console has no component mapping; one the host does not know is the default's. + if desc.Shader4ComponentMapping != D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING { + desc.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; + } + let host = host()?; + // SAFETY: a live buffer and a slot of our heap. + unsafe { + host.device + .CreateShaderResourceView(&shadow.buffer, Some(&desc), at) + }; + Some(Some(shadow.buffer.clone())) +} + +/// An unordered access view of title buffer memory at `address` (`len` +/// bytes) on its host copy, as [`buffer_srv`]; false if the copy cannot be +/// written by shaders (upload memory). +/// shortcut: what shaders write stays in the host copy; title memory (and +/// so the CPU, and copies run on the CPU) does not see it. +fn buffer_uav( + address: u64, + len: u64, + mut desc: D3D12_UNORDERED_ACCESS_VIEW_DESC, + at: D3D12_CPU_DESCRIPTOR_HANDLE, +) -> Option { + let shadow = crate::shadow::find(address, len)?; + // Off the elements of that copy: on a copy of its own bytes, from its + // element 0 (`own_bytes`). + let (shadow, own) = { + // SAFETY: a buffer view's union member. + let b = unsafe { desc.Anonymous.Buffer }; + let element = if b.StructureByteStride > 0 { + u64::from(b.StructureByteStride) + } else if b.Flags.0 & D3D12_BUFFER_UAV_FLAG_RAW.0 != 0 { + 4 + } else { + crate::resource::element(desc.Format.0 as u32).map_or(0, |(bytes, _)| bytes) + }; + let unknown = desc.Format == DXGI_FORMAT_UNKNOWN; + match own_bytes(shadow.offset(address), address, b.FirstElement, b.NumElements, element, b.StructureByteStride, unknown) + .and_then(|(start, bytes)| crate::shadow::exact(start, bytes)) + { + Some(own) => { + desc.Anonymous.Buffer.FirstElement = 0; + (own, true) + } + None => (shadow, false), + } + }; + // SAFETY: a live buffer. + let flags = unsafe { shadow.buffer.GetDesc() }.Flags; + if flags.0 & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS.0 == 0 { + once!("unordered access to a buffer whose host copy shaders cannot write"); + return None; + } + // SAFETY: a buffer view's union member. + let buffer = unsafe { &mut desc.Anonymous.Buffer }; + let element = if buffer.StructureByteStride > 0 { + u64::from(buffer.StructureByteStride) + } else if buffer.Flags.0 & D3D12_BUFFER_UAV_FLAG_RAW.0 != 0 { + 4 + } else { + crate::resource::element(desc.Format.0 as u32).map_or(0, |(bytes, _)| bytes) + }; + let offset = if own { 0 } else { shadow.offset(address) }; + // A structured view as a raw view of the same bytes (see `raw_window`). + let window = (desc.Format == DXGI_FORMAT_UNKNOWN) + .then(|| raw_window(offset, buffer.FirstElement, buffer.NumElements, buffer.StructureByteStride)) + .flatten(); + if let Some((first, count)) = window { + buffer.FirstElement = first; + buffer.NumElements = count; + buffer.StructureByteStride = 0; + buffer.Flags = D3D12_BUFFER_UAV_FLAG_RAW; + } else { + if element == 0 || offset % element != 0 { + once!(offset, element, "unordered buffer view not on an element of its host copy"); + return None; + } + buffer.FirstElement += offset / element; + } + buffer.CounterOffsetInBytes = 0; + let (first, count, stride) = (buffer.FirstElement, buffer.NumElements, buffer.StructureByteStride); + let raw = buffer.Flags.0 & D3D12_BUFFER_UAV_FLAG_RAW.0 != 0; + if window.is_some() { + // (Left out at first: every structured unordered access view was then + // refused by `buffer_view_ok` and left null, runs 15 and 16.) + desc.Format = DXGI_FORMAT_R32_TYPELESS; + } + // SAFETY: a live buffer. + let width = unsafe { shadow.buffer.GetDesc() }.Width; + if !buffer_view_ok(desc.Format, first, count, stride, raw, width) { + REFUSED_VIEWS.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + once!( + format = desc.Format.0, + first, + count, + stride, + raw, + width, + "unordered buffer view the host would refuse left null" + ); + return None; + } + let host = host()?; + // SAFETY: a live buffer and a slot of our heap. + unsafe { + host.device + .CreateUnorderedAccessView(&shadow.buffer, None::<&ID3D12Resource>, Some(&desc), at) + }; + Some(Some(shadow.buffer.clone())) +} + +/// Whether the host can make a shader (or unordered access) view of +/// `texture` in `format` (none: the texture's own). The console allows any +/// view; the host refuses (and removes the device for) views without the +/// resource's permission, of typed depth, and in another format than a +/// typed resource's. A view of a typed texture in another format of its +/// family takes the texture's format. +/// shortcut: such a view (sRGB of UNORM, say) reads without its +/// conversion; cast with castable formats if colors come out wrong. +fn fits(texture: &ID3D12Resource, mut format: Option<&mut DXGI_FORMAT>, unordered: bool) -> bool { + use crate::resource::{DEPTH_FORMATS, family}; + // SAFETY: a live resource. + let d = unsafe { texture.GetDesc() }; + let allowed = if unordered { + d.Flags.0 & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS.0 != 0 + } else { + d.Flags.0 & D3D12_RESOURCE_FLAG_DENY_SHADER_RESOURCE.0 == 0 + }; + let own = d.Format.0 as u32; + if !allowed || DEPTH_FORMATS.iter().any(|&(typed, _)| typed == own) { + if unordered { + crate::resource::DEPTH_UNORDERED[3].fetch_add(1, std::sync::atomic::Ordering::Relaxed); + } + once!( + unordered, + format = own, + flags = d.Flags.0, + "view the host does not allow" + ); + return false; + } + // Every family has more than one format, its typeless one first. + let typeless = family(own) == own && family(own + 1) == own; + if let Some(format) = format.as_deref_mut() + && unordered + && let Some(&(_, linear)) = crate::resource::SRGB + .iter() + .find(|&&(s, _)| s == format.0 as u32) + { + format.0 = linear as i32; + } + let view = format.as_ref().map_or(0, |f| f.0 as u32); + if view == 0 { + return !typeless; + } + // A view of a target whose format the host refuses, in the title's + // format: in the stand-in the host copy has. + if view != own && crate::resource::target_format(view) == own { + if let Some(format) = format { + *format = d.Format; + } + return true; + } + if family(view) != family(own) { + once!(view, own, "view format of another family"); + return false; + } + if let Some(format) = format + && !typeless + { + *format = d.Format; + } + true +} + +/// The title's unordered access view of a depth texture, as a view of the +/// texture's colour twin `twin` ([`crate::resource::Twin`]): the same mip +/// and slices, in the colour format of the twin's family for a depth or +/// typeless format (R16_UNORM for 16-bit depth, R32_FLOAT for 32-bit; the +/// bits are the same). Without a description: mip 0 of every slice. +/// The twin of a stencil plane (R8) stands for the views of that plane +/// only, which become R8_UINT views of its one plane; `None` for a view of +/// the depth plane, which the twin does not stand for. The depth plane has +/// a twin of its own, viewed as a depth texture's without stencil: a view +/// in the format of the depth plane of a depth-stencil format (21, 46) +/// takes the twin's colour format too. +fn twin_uav( + twin: &ID3D12Resource, + desc: Option<&D3D12_UNORDERED_ACCESS_VIEW_DESC>, +) -> Option { + // SAFETY: a live resource. + let d = unsafe { twin.GetDesc() }; + let mut desc = desc.cloned().unwrap_or_else(|| { + let mut all = D3D12_UNORDERED_ACCESS_VIEW_DESC { + ViewDimension: D3D12_UAV_DIMENSION_TEXTURE2D, + ..Default::default() + }; + if d.DepthOrArraySize > 1 { + all.ViewDimension = D3D12_UAV_DIMENSION_TEXTURE2DARRAY; + all.Anonymous.Texture2DArray = D3D12_TEX2D_ARRAY_UAV { + ArraySize: u32::from(d.DepthOrArraySize), + ..Default::default() + }; + } + all + }); + // A stencil plane's twin (R8 typeless, 60): the title's view is of the + // stencil plane if it names plane 1 or a stencil view format (22, 47). + if d.Format.0 == 60 { + let mut plane = 0; + match desc.ViewDimension { + D3D12_UAV_DIMENSION_TEXTURE2D => { + // SAFETY: the member the dimension names. + let mut view = unsafe { desc.Anonymous.Texture2D }; + plane = std::mem::take(&mut view.PlaneSlice); + desc.Anonymous.Texture2D = view; + } + D3D12_UAV_DIMENSION_TEXTURE2DARRAY => { + // SAFETY: the member the dimension names. + let mut view = unsafe { desc.Anonymous.Texture2DArray }; + plane = std::mem::take(&mut view.PlaneSlice); + desc.Anonymous.Texture2DArray = view; + } + _ => {} + } + if plane != 1 && !matches!(desc.Format.0, 22 | 47) { + return None; + } + desc.Format.0 = 62; + return Some(desc); + } + // None, typeless and depth formats (R16: 0, 53, 55; R32: 0, 39, 40), + // and those of a depth-stencil format's depth plane (19 to 21, 44 to + // 46), for the twin of such a plane. + desc.Format.0 = match (desc.Format.0, d.Format.0) { + (0 | 53 | 55 | 19..=21 | 44..=46, 53) => 56, + (0 | 39 | 40 | 19..=21 | 44..=46, 39) => 41, + (other, _) => other, + }; + Some(desc) +} + +/// Makes the host descriptor for `view` at `at`: the host resource it +/// views, or `None` if it cannot. +fn make(view: &View, at: D3D12_CPU_DESCRIPTOR_HANDLE) -> Option { + let host = host()?; + let device = &host.device; + match view { + &View::Constant(address, size) => { + let shadow = crate::shadow::find(address, u64::from(size))?; + let gpu = shadow.gpu(address); + if gpu % 256 != 0 { + once!( + address = format_args!("{address:#x}"), + "constant buffer not 256-byte aligned on the host" + ); + return None; + } + let desc = D3D12_CONSTANT_BUFFER_VIEW_DESC { + BufferLocation: gpu, + SizeInBytes: size.next_multiple_of(256), + }; + // SAFETY: a slot of our heap; the range lies in the host copy. + unsafe { device.CreateConstantBufferView(Some(&desc), at) }; + Some(Some(shadow.buffer.clone())) + } + View::Shader(resource, desc) => { + let resource = *resource as crate::object::This; + if let Some(texture) = crate::resource::host_resource(resource) { + // The title's views of textures with a stencil plane, as it + // describes them (format, dimension, component mapping, a + // pad, then first level, levels, plane): each distinct one + // once. They say how its shaders read the stencil plane + // (the lighting takes each pixel's material class and its + // "inside a room" bit from it). + #[cfg(feature = "diagnostics")] + { + // SAFETY: a live resource. + let own = unsafe { texture.GetDesc() }.Format.0; + if matches!(own, 19..=22 | 44..=47) { + static SEEN: Mutex)>> = Mutex::new(Vec::new()); + let mut seen = SEEN.lock().unwrap_or_else(|e| e.into_inner()); + if seen.len() < 64 && !seen.contains(&(own, *desc)) { + seen.push((own, *desc)); + tracing::info!( + ?resource, + texture_format = own, + view = ?desc, + "shader view of a depth-stencil texture" + ); + } + } + } + let mut desc = desc.as_ref().map(srv_desc); + if !fits(texture, desc.as_mut().map(|d| &mut d.Format), false) { + return None; + } + // Levels on demand (`crate::tiles`): a texture made level by + // level is shown from the first level that is the title's + // and has memory, if the title's view starts before it (a + // level without memory reads zeros: a black texture). The + // title's own view mostly starts there already. + if let Some(first) = crate::resource::first_shown(resource) + && first > 0 + { + // SAFETY: a live resource. + let own = unsafe { texture.GetDesc() }; + // The texture's own view (the title gave none): all of it. + let whole = D3D12_SHADER_RESOURCE_VIEW_DESC { + Format: own.Format, + ViewDimension: D3D12_SRV_DIMENSION_TEXTURE2D, + Shader4ComponentMapping: 5768, + Anonymous: D3D12_SHADER_RESOURCE_VIEW_DESC_0 { + Texture2D: D3D12_TEX2D_SRV { + MostDetailedMip: 0, + MipLevels: u32::MAX, + PlaneSlice: 0, + ResourceMinLODClamp: 0.0, + }, + }, + }; + crate::tiles::show_from(desc.get_or_insert(whole), first, u32::from(own.MipLevels)); + } + // SAFETY: a live texture and a slot of our heap. + unsafe { + device.CreateShaderResourceView( + texture, + desc.as_ref().map(std::ptr::from_ref), + at, + ) + }; + Some(Some(texture.clone())) + } else if let (Some((data, len)), Some(desc)) = + (crate::resource::buffer_bytes(resource), desc) + { + buffer_srv(data as u64, len, srv_desc(desc), at) + } else { + None + } + } + View::Unordered(resource, _counter, desc) => { + let resource = *resource as crate::object::This; + let Some(texture) = crate::resource::host_resource(resource) else { + return match (crate::resource::buffer_bytes(resource), desc) { + (Some((data, len)), Some(desc)) => { + buffer_uav(data as u64, len, uav_desc(desc), at) + } + _ => None, + }; + }; + // The first such views of depth textures are logged as the + // title describes them (format, dimension, then mip, slices and + // plane): they say which planes shaders write, and as what. + if crate::resource::depth_and_unordered(resource) { + static LOGGED: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); + if LOGGED.fetch_add(1, std::sync::atomic::Ordering::Relaxed) < 512 { + tracing::info!( + ?resource, + view = ?desc, + "unordered access view of a depth texture" + ); + } + } + let mut desc = desc.as_ref().map(uav_desc); + // A depth texture's unordered access is its colour twin's: the + // host gives a depth texture none. + let twin = crate::resource::twin_resource(resource) + .and_then(|twin| Some((twin, twin_uav(twin, desc.as_ref())?))) + // A view of the depth plane of a texture with a stencil + // plane: of that plane's own twin. + .or_else(|| { + let twin = crate::resource::twin_plane_resource(resource)?; + Some((twin, twin_uav(twin, desc.as_ref())?)) + }); + let texture = match twin { + Some((twin, view)) => { + desc = Some(view); + twin + } + None => texture, + }; + if !fits(texture, desc.as_mut().map(|d| &mut d.Format), true) { + return None; + } + // SAFETY: a live texture and a slot of our heap. + unsafe { + device.CreateUnorderedAccessView( + texture, + None::<&ID3D12Resource>, + desc.as_ref().map(std::ptr::from_ref), + at, + ) + }; + Some(Some(texture.clone())) + } + View::Sampler(words) => { + // SAFETY: 13 words in the host's layout. + let desc = unsafe { + std::ptr::from_ref(words) + .cast::() + .read_unaligned() + }; + // SAFETY: a slot of our sampler heap. + unsafe { device.CreateSampler(&desc, at) }; + Some(None) + } + View::ConsoleSampler(words) => { + let desc = crate::sampler::console(words); + // SAFETY: a slot of our sampler heap. + unsafe { device.CreateSampler(&desc, at) }; + Some(None) + } + View::Placed(unordered, resource, desc) => { + if let Some(view) = placed_texture(view) { + return make(&view, at); + } + const BUFFER: u32 = 1; + if resource[0] != BUFFER { + // shortcut: unordered access to a texture the title placed + // itself is not mirrored; give it a resource as shader + // views of such textures get when a dispatch writes one. + once!(dimension = resource[0], "placed unordered texture view not mirrored"); + return None; + } + // The resource description's width, after the alignment. + let len = u64::from(resource[4]) | u64::from(resource[5]) << 32; + let address = u64::from(desc[10]) | u64::from(desc[11]) << 32; + let words: &[u32; 10] = desc[..10].try_into().unwrap_or(&[0; 10]); + // An empty title buffer: nothing to view, and no host copy to + // look for (#70: such views were in flight at device removals). + if len == 0 { + return None; + } + if *unordered { + buffer_uav(address, len, uav_desc(words), at) + } else { + buffer_srv(address, len, srv_desc(words), at) + } + } + } +} + +/// Writes of a slot with another view of the placed texture it showed, +/// since the start: the slot kept showing the old view. +pub(crate) static KEPT_VIEWS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + +/// Whether a slot written with another view of the placed texture it +/// shows keeps showing the old one until the new is made; +/// `LEONIDA_KEEP_VIEWS=0` makes it null at once, as before. +fn keep_views() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("LEONIDA_KEEP_VIEWS").is_none_or(|v| v != "0")) +} + +/// Whether both are shader views of one texture the title placed in +/// memory: the same address and the same resource description, whatever +/// part of it each shows. +fn same_placed_texture(a: &View, b: &View) -> bool { + match (a, b) { + (View::Placed(false, resource, desc), View::Placed(false, other, other_desc)) => { + resource[0] != 1 && resource == other && desc[10..12] == other_desc[10..12] + } + _ => false, + } +} + +/// A shader view of a texture the title placed in memory itself, as a view +/// of the resource made for that memory (on first use). +pub(crate) fn placed_texture(view: &View) -> Option { + const BUFFER: u32 = 1; + let View::Placed(false, resource, desc) = view else { + return None; + }; + if resource[0] == BUFFER { + return None; + } + let address = u64::from(desc[10]) | u64::from(desc[11]) << 32; + let texture = crate::resource::texture_at(address, resource)?; + Some(View::Shader(texture as usize, desc[..10].try_into().ok())) +} + +/// A null view of the kind `view` is, for a slot whose view the host +/// cannot make: unordered access (to a buffer or a 2D texture) or a shader +/// view. Writes to it are dropped, reads give zeros. +fn null_for(view: &View, at: D3D12_CPU_DESCRIPTOR_HANDLE) { + let Some(host) = host() else { return }; + let is_buffer = |r: &usize| crate::resource::buffer_bytes(*r as crate::object::This).is_some(); + // Unordered views: whether a buffer, and the title's view dimension. + let (buffer, dimension) = match view { + View::Unordered(r, _, desc) => ( + is_buffer(r) || desc.is_some_and(|d| d[1] == 1), + desc.map(|d| d[1]), + ), + View::Placed(true, resource, desc) => (resource[0] == 1, Some(desc[1])), + // Shader views of buffers read nothing through a null buffer view: + // a null 2D view where the shader expects a buffer is a mismatch + // the hardware does not survive in general (GPU-based validation + // reports it). + View::Shader(r, desc) if is_buffer(r) || desc.is_some_and(|d| d[1] == 1) => { + return null_buffer_view(at); + } + View::Placed(false, resource, _) if resource[0] == 1 => return null_buffer_view(at), + // Textures: a null view of the title's dimension (1D, arrays, 3D, + // cubes), not always 2D. + View::Shader(_, Some(desc)) => return null_like(desc, at), + View::Placed(false, _, desc) => { + return null_like(desc[..10].try_into().unwrap_or(&[0; 10]), at); + } + View::Constant(..) => { + let desc = D3D12_CONSTANT_BUFFER_VIEW_DESC::default(); + // SAFETY: a slot of our heap; a zero location makes a null view. + return unsafe { host.device.CreateConstantBufferView(Some(&desc), at) }; + } + _ => return null_view(at), + }; + let desc = if buffer { + D3D12_UNORDERED_ACCESS_VIEW_DESC { + Format: DXGI_FORMAT_R32_UINT, + ViewDimension: D3D12_UAV_DIMENSION_BUFFER, + ..Default::default() + } + } else { + null_uav_desc(dimension) + }; + // SAFETY: a slot of our heap; a null resource is allowed with a desc. + unsafe { + host.device.CreateUnorderedAccessView( + None::<&ID3D12Resource>, + None::<&ID3D12Resource>, + Some(&desc), + at, + ) + }; +} + +/// A null texture UAV of the title's view dimension (1D, 1D or 2D arrays, +/// 3D), 2D if it names none: a 2D null view where the shader writes a 3D +/// texture is a mismatch GPU-based validation reports (the world's wind +/// field, CS_CopyWindFieldBeforeUpdateWithSmooth, 2026-11-24). +fn null_uav_desc(dimension: Option) -> D3D12_UNORDERED_ACCESS_VIEW_DESC { + let mut desc = D3D12_UNORDERED_ACCESS_VIEW_DESC { + Format: DXGI_FORMAT_R32_UINT, + ViewDimension: D3D12_UAV_DIMENSION_TEXTURE2D, + ..Default::default() + }; + match dimension.map(|d| D3D12_UAV_DIMENSION(d as i32)) { + Some(D3D12_UAV_DIMENSION_TEXTURE1D) => { + desc.ViewDimension = D3D12_UAV_DIMENSION_TEXTURE1D; + } + Some(D3D12_UAV_DIMENSION_TEXTURE1DARRAY) => { + desc.ViewDimension = D3D12_UAV_DIMENSION_TEXTURE1DARRAY; + desc.Anonymous.Texture1DArray = D3D12_TEX1D_ARRAY_UAV { + ArraySize: 1, + ..Default::default() + }; + } + Some(D3D12_UAV_DIMENSION_TEXTURE2DARRAY) => { + desc.ViewDimension = D3D12_UAV_DIMENSION_TEXTURE2DARRAY; + desc.Anonymous.Texture2DArray = D3D12_TEX2D_ARRAY_UAV { + ArraySize: 1, + ..Default::default() + }; + } + Some(D3D12_UAV_DIMENSION_TEXTURE3D) => { + desc.ViewDimension = D3D12_UAV_DIMENSION_TEXTURE3D; + desc.Anonymous.Texture3D = D3D12_TEX3D_UAV { + WSize: u32::MAX, + ..Default::default() + }; + } + _ => {} + } + desc +} + +/// A buffer view that reads zeros (raw, as translated shaders mostly read +/// buffers). +fn null_buffer_view(at: D3D12_CPU_DESCRIPTOR_HANDLE) { + let Some(host) = host() else { return }; + let desc = D3D12_SHADER_RESOURCE_VIEW_DESC { + Format: DXGI_FORMAT_R32_TYPELESS, + ViewDimension: D3D12_SRV_DIMENSION_BUFFER, + Shader4ComponentMapping: D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING, + Anonymous: D3D12_SHADER_RESOURCE_VIEW_DESC_0 { + Buffer: D3D12_BUFFER_SRV { + NumElements: 1, + Flags: D3D12_BUFFER_SRV_FLAG_RAW, + ..Default::default() + }, + }, + }; + // SAFETY: a slot of our heap; a null resource is allowed with a desc. + unsafe { + host.device + .CreateShaderResourceView(None::<&ID3D12Resource>, Some(&desc), at) + }; +} + +/// A texture view that reads zeros with the dimension (and mip and array +/// counts) of the title's description `words`; 2D if it names none. +fn null_like(words: &[u32; 10], at: D3D12_CPU_DESCRIPTOR_HANDLE) { + const TEXTURES: std::ops::RangeInclusive = 2..=10; + if !TEXTURES.contains(&words[1]) { + return null_view(at); + } + let Some(host) = host() else { return }; + // One mip, one slice or cube, plane 0: fields a null view still checks. + let mut w = [0u32; 10]; + w[1] = words[1]; + match words[1] { + 6 => {} + 7 => w[5] = 1, + 3 | 5 | 10 => (w[5], w[7]) = (1, 1), + _ => w[5] = 1, + } + let mut desc = srv_desc(&w); + desc.Format = DXGI_FORMAT_R8G8B8A8_UNORM; + desc.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; + // SAFETY: a slot of our heap; a null resource is allowed with a desc. + unsafe { + host.device + .CreateShaderResourceView(None::<&ID3D12Resource>, Some(&desc), at) + }; +} + +/// A view that reads zeros, for slots whose view the host cannot make. +/// shortcut: slots with no view at all (kind unknown) get this null 2D +/// view; null buffer views there did not stop the world's low-address +/// page faults (2026-11-24, run w10), so they are not the cause. +fn null_view(at: D3D12_CPU_DESCRIPTOR_HANDLE) { + let Some(host) = host() else { return }; + let desc = D3D12_SHADER_RESOURCE_VIEW_DESC { + Format: DXGI_FORMAT_R8G8B8A8_UNORM, + ViewDimension: D3D12_SRV_DIMENSION_TEXTURE2D, + Shader4ComponentMapping: D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING, + Anonymous: D3D12_SHADER_RESOURCE_VIEW_DESC_0 { + Texture2D: D3D12_TEX2D_SRV { + MipLevels: 1, + ..Default::default() + }, + }, + }; + // SAFETY: a slot of our heap; a null resource is allowed with a desc. + unsafe { + host.device + .CreateShaderResourceView(None::<&ID3D12Resource>, Some(&desc), at) + }; +} + +#[cfg(test)] +mod tests { + use super::*; + + /// A null texture UAV keeps the title's dimension (3D for the world's + /// wind field), and is 2D when the title names none. + #[test] + fn null_uavs_keep_the_titles_dimension() { + let d = null_uav_desc(Some(8)); + assert_eq!(d.ViewDimension, D3D12_UAV_DIMENSION_TEXTURE3D); + // SAFETY: the member the dimension names. + assert_eq!(unsafe { d.Anonymous.Texture3D.WSize }, u32::MAX); + let d = null_uav_desc(Some(5)); + assert_eq!(d.ViewDimension, D3D12_UAV_DIMENSION_TEXTURE2DARRAY); + // SAFETY: the member the dimension names. + assert_eq!(unsafe { d.Anonymous.Texture2DArray.ArraySize }, 1); + let dimension = |d| null_uav_desc(d).ViewDimension; + assert_eq!(dimension(Some(2)), D3D12_UAV_DIMENSION_TEXTURE1D); + assert_eq!(dimension(Some(4)), D3D12_UAV_DIMENSION_TEXTURE2D); + assert_eq!(dimension(None), D3D12_UAV_DIMENSION_TEXTURE2D); + // Multisampled UAVs need a cap; they stay 2D. + assert_eq!(dimension(Some(6)), D3D12_UAV_DIMENSION_TEXTURE2D); + } + + /// What the texture code asks of the spans (levels on demand): where + /// the next texture starts inside a span, the lowest level a view of a + /// texture shows, and a texture's slots. + #[test] + fn spans_say_the_next_start_and_the_lowest_level_viewed() { + let mut spans = Spans::default(); + // A 512x512 texture of 0x56000 bytes viewed from levels 3 and 1, + // and the next one 0x6000 after it (run 188). + spans.note(1, 0x1_0000, 0x1_0000 + 0x5_6000, true); + spans.shows(1, 3); + spans.note(2, 0x1_0000, 0x1_0000 + 0x5_6000, true); + spans.shows(2, 1); + spans.note(3, 0x1_6000, 0x1_6000 + 0x5_6000, true); + assert_eq!(spans.next_start(0x1_0000, 0x1_0000 + 0x5_6000), Some(0x1_6000)); + assert_eq!(spans.next_start(0x1_6000, 0x1_6000 + 0x5_6000), None); + assert_eq!(spans.first_viewed(0x1_0000), Some(1)); + assert_eq!(spans.first_viewed(0x1_6000), None); + assert_eq!(spans.slots_at(0x1_0000), vec![1, 2]); + // The view from level 1 goes: the texture is viewed from level 3. + spans.forget(2); + assert_eq!(spans.first_viewed(0x1_0000), Some(3)); + } + + /// Views of one placed texture are told from views of others by the + /// address and the resource description, not by what they show. + #[test] + fn views_of_one_placed_texture_are_told_by_address_and_description() { + let texture = [3, 0, 0, 0, 512, 0, 512, 0x8_0001, 98, 1, 0, 0x105, 0, 0]; + let view = |resource: [u32; 14], first_mip: u32, address: u32| { + let mut desc = [0u32; 16]; + (desc[0], desc[1], desc[4], desc[5], desc[10], desc[11]) = (98, 4, first_mip, 8 - first_mip, address, 0xb); + View::Placed(false, resource, desc) + }; + let low = view(texture, 3, 0x1000_0000); + // more mips of the same texture + assert!(same_placed_texture(&low, &view(texture, 0, 0x1000_0000))); + // another address, another description, a buffer, an unordered view + assert!(!same_placed_texture(&low, &view(texture, 3, 0x2000_0000))); + let mut wider = texture; + wider[4] = 1024; + assert!(!same_placed_texture(&low, &view(wider, 3, 0x1000_0000))); + let mut buffer = texture; + buffer[0] = 1; + assert!(!same_placed_texture(&view(buffer, 3, 0x1000_0000), &view(buffer, 3, 0x1000_0000))); + let View::Placed(_, resource, desc) = low.clone() else { unreachable!() }; + assert!(!same_placed_texture(&low, &View::Placed(true, resource, desc))); + assert!(!same_placed_texture(&low, &View::Shader(0, None))); + } + + /// A null 3D UAV made on the real device leaves it alive. + #[test] + fn null_3d_uav_is_accepted_by_the_device() { + let Some(host) = host() else { + return; // no host GPU + }; + let Some(heap) = HostHeap::new(false, 4) else { + return; + }; + let view = View::Unordered(0, 0, Some([28, 8, 0, 0, 0, 0, 0, 0, 0, 0])); + null_for(&view, heap.cpu(0)); + // SAFETY: a plain device query. + assert!(unsafe { host.device.GetDeviceRemovedReason() }.is_ok()); + } + + /// Dynamic slots stay taken until given back, and runs do not wrap. + #[test] + fn a_structured_view_made_raw_passes_the_host_check() { + // 100 elements of 20 bytes from element 8, in a copy that starts 32 + // bytes before the view's memory: bytes 192..2192. + let (first, count) = raw_window(32, 8, 100, 20).unwrap(); + assert_eq!((first, count), (48, 500)); + assert!(buffer_view_ok(DXGI_FORMAT_R32_TYPELESS, first, count, 0, true, 4096)); + // the format a raw view must name; the structured one's is refused + assert!(!buffer_view_ok(DXGI_FORMAT_UNKNOWN, first, count, 0, true, 4096)); + // past the buffer, not on 16 bytes, no elements + assert!(!buffer_view_ok(DXGI_FORMAT_R32_TYPELESS, first, count, 0, true, 2000)); + assert!(raw_window(4, 0, 100, 20).is_none()); + assert!(!buffer_view_ok(DXGI_FORMAT_R32_TYPELESS, 0, 0, 0, true, 4096)); + // a structured view the host takes as it is + assert!(buffer_view_ok(DXGI_FORMAT_UNKNOWN, 1, 10, 12, false, 4096)); + } + + /// The queue of textures picked by index serves the slots looked at + /// before first, then the newest write and the oldest in turns; a + /// slot whose memory is not there is looked at again after + /// 1, 2, 4 frames up to the limit; and what the pass reports about a + /// slot written again meanwhile is dropped. + #[test] + fn the_texture_queue_serves_the_newest_writes_first() { + let mut q = TextureQueue::default(); + // Slots 10..18 written in frames 1..9, slot 5 last. + for i in 0..8u32 { + q.written(10 + i, u64::from(i) + 1, 0, false); + } + q.written(5, 9, 0, false); + let order: Vec = q.due(9, 100).into_iter().map(|d| d.0).collect(); + // newest, oldest, newest, oldest, and so on + assert_eq!(order, [5, 10, 17, 11, 16, 12, 15, 13, 14]); + assert_eq!(q.due(9, 2).len(), 2); + assert_eq!(q.census(9), [9, 9, 0, 0, 8]); + // Slot 17's memory is not mapped: again next frame, then in 2, 4, 4. + let write = |q: &TextureQueue, index: u32| q.due(u64::MAX, 100).iter().find(|d| d.0 == index).unwrap().1; + let w17 = write(&q, 17); + let mut frame = 9; + for wait in [1, 2, 4, 4] { + q.later(17, w17, frame, 4); + assert!(!q.due(frame + wait - 1, 100).iter().any(|d| d.0 == 17)); + frame += wait; + // Due again, and ahead of every slot never looked at. + assert_eq!(q.due(frame, 100)[0].0, 17); + } + assert_eq!(q.census(9)[2], 1); + q.done(17, w17); + assert!(!q.due(u64::MAX, 100).iter().any(|d| d.0 == 17)); + // Uploaded with part of its memory there: kept, with what was there. + let w16 = write(&q, 16); + q.partly(16, w16, 12, 4096); + assert_eq!(q.mapped(16), 4096); + assert_eq!(q.due(12, 100)[0].0, 16); + // The title writes slot 16 again while the pass works on it: what + // the pass then says about the old write changes nothing. + q.written(16, 13, 0, false); + q.done(16, w16); + q.later(16, w16, 13, 4); + assert_eq!(q.mapped(16), 0); + assert_eq!(q.due(13, 100)[0].0, 16); + // A draw that makes the host slot (`seen`) keeps what the queue knows, + let w15 = write(&q, 15); + q.partly(15, w15, 20, 8192); + q.written(15, 14, 0, true); + assert_eq!(q.mapped(15), 8192); + // and queues a slot the queue did not hold. + q.written(99, 14, 0, true); + assert!(q.due(14, 100).iter().any(|d| d.0 == 99)); + // A write due later (a table's slot) is not handed out before. + q.written(98, 14, 16, false); + assert!(!q.due(15, 100).iter().any(|d| d.0 == 98)); + assert!(q.due(16, 100).iter().any(|d| d.0 == 98)); + } + + /// Slots held back for lack of room on the card are not handed out + /// until their frame, keep their place, are not counted as waiting + /// for their memory, and all come back at once when the card has room; + /// a slot written again meanwhile is the title's new write. + #[test] + fn slots_held_for_lack_of_room_come_back_when_there_is_room() { + let mut q = TextureQueue::default(); + for i in 0..4u32 { + q.written(20 + i, 1, 0, false); + } + let due = q.due(1, 100); + assert_eq!(due.len(), 4); + // The card is full: slots 20 and 21 are held back until frame 101. + for &(index, write) in due.iter().filter(|d| d.0 < 22) { + q.hold(index, write, 101); + } + let now: Vec = q.due(2, 100).into_iter().map(|d| d.0).collect(); + assert!(!now.contains(&20) && !now.contains(&21)); + assert!(now.contains(&22) && now.contains(&23)); + assert_eq!(q.census(2)[2], 0, "held slots do not wait for their memory"); + // Due again at their frame, in the order they had. + assert_eq!(q.due(101, 100), due); + // Slot 21 is written again while held: due as written. + q.written(21, 3, 0, false); + assert!(q.due(3, 100).iter().any(|d| d.0 == 21)); + // Room again at frame 5: slot 20 is due at once, and only it was + // still held as it was. + assert_eq!(q.room(5), 1); + assert!(q.due(5, 100).iter().any(|d| d.0 == 20)); + assert_eq!(q.room(6), 0); + } + + /// Textures of which only the smallest levels are held, packed into + /// one another's address range (the three of run 188: 0x2c000 bytes + /// each at full size, their starts 0x2000 and 0x4000 apart): writing + /// any of them, in any order and again, leaves the others. + #[test] + fn packed_neighbours_stay() { + let mut spans = Spans::default(); + assert_eq!(spans.rule, Rule::Start); + let at = 0xb_86bf_8000u64; + let (a, b, c) = (at, at + 0x2000, at + 0x6000); + assert!(spans.note(105_998, a, a + 0x2c000, true).is_empty()); + assert!(spans.note(106_004, b, b + 0x2c000, true).is_empty()); + assert!(spans.note(108_521, c, c + 0x2c000, true).is_empty()); + // The first written again (as a title does when levels arrive), + // from another slot too: its span reaches over the other two. + assert!(spans.note(7, a, a + 0x2c000, true).is_empty()); + assert!(spans.note(106_004, b, b + 0x2c000, true).is_empty()); + let mut all = spans.slots_in(0, u64::MAX); + all.sort_unstable(); + assert_eq!(all, [7, 105_998, 106_004, 108_521]); + // A draw makes a slot of the second texture: it is one of them. + assert!(spans.note(9, b, b + 0x2c000, false).is_empty()); + assert_eq!(spans.by_slot.get(&9), Some(&b)); + } + + /// A texture written where another starts replaces it: at the same + /// address with another length, or inside the block of its smallest + /// levels. The packed neighbours of the one replaced stay. + #[test] + fn a_texture_written_at_the_start_of_another_replaces_it() { + let mut spans = Spans::default(); + let at = 0x7_0000_0000u64; + assert!(spans.note(1, at, at + 0x2c000, true).is_empty()); + assert!(spans.note(2, at + 0x2000, at + 0x2e000, true).is_empty()); + // Another length from the same start: slot 1 is stale, slot 2 not. + assert_eq!(spans.note(3, at, at + 0xb000, true), [1]); + // A start inside the first 4 KiB of slot 3's texture: stale too. + assert_eq!(spans.note(4, at + 0x800, at + 0x1800, true), [3]); + // And the other way: a texture that starts just before one. + assert_eq!(spans.note(5, at + 0x1800, at + 0x4800, true), [2]); + let mut left = spans.slots_in(0, u64::MAX); + left.sort_unstable(); + assert_eq!(left, [4, 5]); + // Exactly 4 KiB apart: both there. + assert!(spans.note(6, at + 0x2800, at + 0x3800, true).is_empty()); + // A draw's view that clashes is left out, and nothing is stale. + assert!(spans.note(8, at + 0x900, at + 0x2900, false).is_empty()); + assert_eq!(spans.by_slot.get(&8), None); + assert_eq!(spans.by_slot.len(), 3); + } + + /// A slot written with another texture leaves its old span; the same + /// view written again changes nothing. + #[test] + fn a_slot_rewritten_moves_to_its_new_span() { + let mut spans = Spans::default(); + assert!(spans.note(1, 0x10000, 0x3c000, true).is_empty()); + assert!(spans.note(2, 0x12000, 0x3e000, true).is_empty()); + assert!(spans.note(1, 0x10000, 0x3c000, true).is_empty()); + assert_eq!(spans.slots_in(0x10000, 0x10001), [1]); + // Slot 1 now views a texture far away. + assert!(spans.note(1, 0x90000, 0x91000, true).is_empty()); + assert_eq!(spans.slots_in(0x10000, 0x10001), [] as [u32; 0]); + assert_eq!(spans.slots_in(0x12000, 0x12001), [2]); + assert_eq!(spans.slots_in(0x90000, 0x90001), [1]); + spans.forget(1); + spans.forget(2); + assert!(spans.by_start.is_empty() && spans.by_slot.is_empty()); + } + + /// Memory the runtime maps, unmaps or writes names the textures that + /// are there: among packed neighbours the one whose held levels the + /// range lies in (it ends where the next one starts), and the ones + /// that start inside the range. + #[test] + fn memory_changed_under_packed_neighbours_names_the_ones_there() { + let mut spans = Spans::default(); + let at = 0x7_0000_0000u64; + assert!(spans.note(1, at, at + 0x2c000, true).is_empty()); + assert!(spans.note(2, at + 0x2000, at + 0x2e000, true).is_empty()); + assert!(spans.note(3, at + 0x6000, at + 0x32000, true).is_empty()); + // Inside the first one's held levels. + assert_eq!(spans.slots_in(at + 0x1000, at + 0x2000), [1]); + // Inside the second's: not the first, which ends where it starts. + assert_eq!(spans.slots_in(at + 0x3000, at + 0x4000), [2]); + // Past the last start: the last one. + assert_eq!(spans.slots_in(at + 0x20000, at + 0x21000), [3]); + // A range over all of them. + assert_eq!(spans.slots_in(at, at + 0x8000), [1, 2, 3]); + // Past the end of all: none. + assert_eq!(spans.slots_in(at + 0x32000, at + 0x33000), [] as [u32; 0]); + } + + /// A write names the textures that hold its bytes: the one that + /// starts where the write starts, not the neighbour before it, whose + /// held levels end there. + #[test] + fn a_write_at_the_start_of_a_packed_texture_names_it_alone() { + let mut spans = Spans::default(); + let at = 0x7_0000_0000u64; + assert!(spans.note(1, at, at + 0x2c000, true).is_empty()); + assert!(spans.note(2, at + 0x2000, at + 0x2e000, true).is_empty()); + assert!(spans.note(3, at + 0x6000, at + 0x32000, true).is_empty()); + // A request that fills the second texture's held levels. + assert_eq!(spans.slots_in(at + 0x2000, at + 0x6000), [1, 2]); + assert_eq!(spans.slots_holding(at + 0x2000, at + 0x6000), [2]); + // From inside the first one's held levels on: both. + assert_eq!(spans.slots_holding(at + 0x1000, at + 0x3000), [1, 2]); + // A whole 64 KiB page: every texture that starts in it. + assert_eq!(spans.slots_holding(at, at + 0x10000), [1, 2, 3]); + // Past the last start, the last one; past all, or no bytes, none. + assert_eq!(spans.slots_holding(at + 0x20000, at + 0x21000), [3]); + assert_eq!(spans.slots_holding(at + 0x32000, at + 0x33000), [] as [u32; 0]); + assert_eq!(spans.slots_holding(at + 0x2000, at + 0x2000), [] as [u32; 0]); + } + + /// A write behind the guards' back under a placed texture: a slot + /// waiting for its first upload is left alone, one uploaded before is + /// counted, and made due two frames on when that is asked for. (The + /// ranges are handed over here, not through the list all heaps share.) + #[test] + fn a_page_write_makes_an_uploaded_texture_slot_due_when_asked() { + let Some(heap) = HostHeap::new(false, 8) else { + return; // no host GPU + }; + let slots = |at: u64| -> Vec { heap.texture_slots_due(at, 8).0.into_iter().map(|d| d.0).collect() }; + // 64x64 BC7, one mip, at an address no test and no title uses. + let at = 0x7fed_0000_0000u64; + let mut desc = [0u32; 16]; + (desc[10], desc[11]) = (at as u32, (at >> 32) as u32); + let view = View::Placed(false, [3, 0, 0, 0, 64, 0, 64, 0x1_0001, 98, 1, 0, 0x105, 0, 0], desc); + assert!(heap.note_buffer(1, Some(&view), false).is_empty()); + let written = [(at, at + 0x1000)]; + // Waiting for its first upload: held, not uploaded, nothing done. + assert_eq!(heap.slots_written_under(&written, 50, true), [1, 0, 0]); + let (queued, write) = heap.texture_slots_due(u64::MAX, 8).0[0]; + assert_eq!(queued, 1); + heap.texture_slot_done(1, write, None); + assert_eq!(slots(u64::MAX), []); + // Uploaded and out of the queue. Memory elsewhere: nothing. + assert_eq!(heap.slots_written_under(&[(at + 0x10_0000, at + 0x10_1000)], 60, true), [0, 0, 0]); + // Under it, counted only: it stays out of the queue. + assert_eq!(heap.slots_written_under(&written, 60, false), [1, 1, 0]); + assert_eq!(slots(u64::MAX), []); + // Under it, asked for: due two frames on, not before. + assert_eq!(heap.slots_written_under(&written, 60, true), [1, 1, 1]); + assert_eq!(slots(61), []); + assert_eq!(slots(62), [1]); + } + + /// `LEONIDA_STALE_TEXTURES=0`: nothing is ever stale, and a view that + /// overlaps others is left out of the spans, as before. + #[test] + fn never_stale_leaves_overlapping_views_out() { + let mut spans = Spans { rule: Rule::Never, ..Default::default() }; + assert!(spans.note(1, 0x1000, 0x3000, true).is_empty()); + assert!(spans.note(2, 0x2000, 0x4000, true).is_empty()); + assert!(spans.note(3, 0x1000, 0x2000, true).is_empty()); + assert_eq!(spans.slots_in(0, u64::MAX), [1]); + } + + /// The rule until run 188 (`LEONIDA_STALE_TEXTURES=overlap`): a view + /// written over memory that older views describe otherwise makes + /// those stale; views of the same span are one texture's. + #[test] + fn a_newer_view_of_other_memory_makes_the_older_stale() { + let mut spans = Spans { rule: Rule::Overlap, ..Default::default() }; + // Three textures side by side, the first in two slots. + assert!(spans.note(1, 0x1000, 0x3000, true).is_empty()); + assert!(spans.note(2, 0x1000, 0x3000, true).is_empty()); + assert!(spans.note(3, 0x3000, 0x4000, true).is_empty()); + assert!(spans.note(4, 0x8000, 0x9000, true).is_empty()); + // The same slot written with the same span again: nothing changes. + assert!(spans.note(2, 0x1000, 0x3000, true).is_empty()); + assert_eq!(spans.slots_in(0x2000, 0x3800), [1, 2, 3]); + assert_eq!(spans.slots_in(0x4000, 0x8000), [] as [u32; 0]); + // A draw makes a slot whose view overlaps them: left out, nothing stale. + assert!(spans.note(9, 0x2000, 0x3800, false).is_empty()); + assert_eq!(spans.slots_in(0x2000, 0x3800), [1, 2, 3]); + // The title writes a texture over the end of the first and all of + // the second: their three slots are stale. + let mut stale = spans.note(5, 0x2000, 0x4000, true); + stale.sort_unstable(); + assert_eq!(stale, [1, 2, 3]); + assert_eq!(spans.slots_in(0, u64::MAX), [5, 4]); + // Another start in the same memory: stale in turn. Another length + // from the same start too. + assert_eq!(spans.note(6, 0x2800, 0x3000, true), [5]); + assert_eq!(spans.note(7, 0x2800, 0x2c00, true), [6]); + // A slot that moves to another texture leaves its span behind. + assert!(spans.note(7, 0x8000, 0x9000, true).is_empty()); + assert_eq!(spans.slots_in(0x2800, 0x2c00), [] as [u32; 0]); + assert_eq!(spans.slots_in(0x8000, 0x8001), [4, 7]); + spans.forget(4); + spans.forget(7); + assert!(spans.by_start.is_empty() && spans.by_slot.is_empty()); + } + + /// Memory the runtime maps under a slot's texture makes the slot due + /// again from the next frame; a stale slot leaves the queue. + #[test] + fn remapped_memory_makes_its_texture_slots_due() { + let Some(heap) = HostHeap::new(false, 8) else { + return; // no host GPU + }; + let slots = |at: u64| -> Vec { heap.texture_slots_due(at, 8).0.into_iter().map(|d| d.0).collect() }; + // 64x64 BC7, one mip, at an address no test and no title uses. + let at = 0x7fee_0000_0000u64; + let view = |address: u64, width: u32| { + let mut desc = [0u32; 16]; + (desc[10], desc[11]) = (address as u32, (address >> 32) as u32); + View::Placed(false, [3, 0, 0, 0, width, 0, 64, 0x1_0001, 98, 1, 0, 0x105, 0, 0], desc) + }; + let len = crate::resource::placed_bytes(&[3, 0, 0, 0, 64, 0, 64, 0x1_0001, 98, 1, 0, 0x105, 0, 0]).unwrap(); + assert!(heap.note_buffer(1, Some(&view(at, 64)), false).is_empty()); + let (queued, write) = heap.texture_slots_due(u64::MAX, 8).0[0]; + assert_eq!(queued, 1); + heap.texture_slot_done(1, write, None); + assert_eq!(slots(u64::MAX), []); + // Memory elsewhere: nothing. Under the texture: due from the next frame. + remapped((at + 2 * len) as usize, 0x1000); + remapped(at as usize, 0x1000); + assert_eq!(heap.texture_slots_remapped(50), 1); + assert_eq!(slots(50), []); + assert_eq!(slots(51), [1]); + // A wider texture written at the same address: slot 1 is stale. + assert_eq!(heap.note_buffer(2, Some(&view(at, 128)), false), [1]); + assert_eq!(slots(u64::MAX), [2]); + } + + /// A slot a draw read through a table leaves the queue; the title's + /// next write of it waits for its draw, and is due after the grace + /// frames if none reads it. + #[test] + fn slots_read_through_tables_leave_the_texture_queue() { + let Some(heap) = HostHeap::new(false, 8) else { + return; // no host GPU + }; + let frame = 100; + let slots = |at: u64| -> Vec { heap.texture_slots_due(at, 8).0.into_iter().map(|d| d.0).collect() }; + let texture = View::Placed(false, [3, 0, 0, 0, 4, 0, 4, 0x1_0001, 28, 1, 0, 0x105, 0, 0], [0; 16]); + assert!(is_texture_view(&texture)); + heap.queue_texture(2, true, false, frame); + heap.queue_texture(3, true, false, frame); + assert_eq!(slots(frame), [3, 2]); + heap.tabled_in(3, true, frame); + assert_eq!(slots(frame), [2]); + // Made in place by the draw that read it: still out. + heap.queue_texture(3, true, true, frame); + assert_eq!(slots(frame), [2]); + // Written again in the next frame: due once the grace frames have + // passed without a draw that reads it. + heap.queue_texture(3, true, false, frame + 1); + assert_eq!(slots(frame + TABLED_GRACE), [2]); + assert_eq!(slots(frame + 1 + TABLED_GRACE), [3, 2]); + // The draw comes after all: out again. + heap.tabled_in(3, true, frame + 1); + assert_eq!(slots(u64::MAX), [2]); + // A slot of a table no draw read stays queued; its next write waits. + heap.tabled_in(2, false, frame + 1); + assert_eq!(slots(frame + 1), [2]); + heap.queue_texture(2, true, false, frame + 2); + assert_eq!(slots(frame + 2), []); + // Long after the last table, a write is due at once. + heap.queue_texture(2, true, false, frame + 3 + TABLED_FRAMES); + assert_eq!(slots(frame + 3 + TABLED_FRAMES), [2]); + } + + #[test] + fn dynamic_slots_are_held_until_released() { + let Some(heap) = HostHeap::new(false, 4) else { + return; // no host GPU + }; + let a = heap.dynamic(heap.dynamic - 100).unwrap(); + let b = heap.dynamic(60).unwrap(); + assert_eq!((a, b), (4, 4 + heap.dynamic - 100)); + // 40 left at the end: 50 do not fit until something is given back. + assert_eq!(heap.dynamic(50), None); + heap.release(a, 50); + assert_eq!(heap.dynamic(50), Some(4)); + assert_eq!(heap.dynamic(40), Some(4 + heap.dynamic - 40)); + } +} + +#[cfg(test)] +mod record_print_tests { + use super::record_print; + + /// Equal records print alike; a record that differs in any one byte, + /// or in its length, prints otherwise. + #[test] + fn a_record_that_changed_prints_otherwise() { + let record: Vec = (0..32u8).map(|i| i.wrapping_mul(37).wrapping_add(5)).collect(); + let print = record_print(&record); + assert_eq!(print, record_print(&record.clone())); + for at in 0..32 { + for bit in 0..8 { + let mut other = record.clone(); + other[at] ^= 1 << bit; + assert_ne!(record_print(&other), print, "byte {at} bit {bit}"); + } + } + assert_ne!(record_print(&record[..16]), print); + assert_ne!(record_print(&[0u8; 32]), record_print(&[0u8; 16])); + // A record of zeros is told from "never looked at" by the caller's `| 1`. + assert_ne!(record_print(&[0u8; 32]) | 1, 0); + } +} + +#[cfg(test)] +mod own_copy_tests { + use super::own_bytes_if; + + /// A buffer view gets a copy of its own bytes only when it has no host + /// view on its buffer's copy: off that copy's elements, and not a + /// structured view that can be a raw view of the same bytes. + #[test] + fn a_view_off_its_copys_elements_gets_its_own_bytes() { + let base = 0xd_9000_0000u64; + // On an element: the buffer's copy (the two cases of every run's + // log are the ones below). + assert_eq!(own_bytes_if(true, 24, base, 3, 10, 12, 0, false), None); + assert_eq!(own_bytes_if(true, 0, base, 0, 10, 12, 0, false), None); + // A typed view of 12-byte elements, 5,222,240 bytes into its copy + // (8 past an element): its own bytes, from its first element. + assert_eq!(own_bytes_if(true, 5_222_240, base, 3, 10, 12, 0, false), Some((base + 36, 120))); + // A structured view of 32-byte elements 8 bytes in: not on 16, so + // no raw view of the copy either. + assert_eq!(own_bytes_if(true, 8, base, 2, 4, 32, 32, true), Some((base + 64, 128))); + // The same 16 bytes in: off its elements, but a raw view of the + // copy's bytes does (as before). + assert_eq!(own_bytes_if(true, 16, base, 2, 4, 32, 32, true), None); + // No elements, no size, or the switch off: as before. + assert_eq!(own_bytes_if(true, 8, base, 2, 0, 32, 32, true), None); + assert_eq!(own_bytes_if(true, 8, base, 2, 4, 0, 0, false), None); + assert_eq!(own_bytes_if(false, 8, base, 2, 4, 32, 32, true), None); + } +} diff --git a/crates/leonida-gpu/src/device.rs b/crates/leonida-gpu/src/device.rs new file mode 100644 index 000000000..dfbf2b225 --- /dev/null +++ b/crates/leonida-gpu/src/device.rs @@ -0,0 +1,587 @@ +//! The device titles get from device creation, laid out as their inlined +//! code expects: the object header, then device fields. Its table starts +//! like the PC device interface (IUnknown, the object methods, then the +//! device methods in PC order); console additions follow. Methods we have +//! not written log their table offset and fail, so a run shows what to +//! write next. +#![allow(clippy::not_unsafe_ptr_arg_deref)] + +use std::ffi::c_void; + +use crate::object::{ + self, E_INVALIDARG, E_NOINTERFACE, E_NOTIMPL, HRESULT, Iid, Object, S_FALSE, S_OK, Table, This, + guid, guid_text, +}; +use crate::{ + descriptor, dxgi, fence, frame, list, pipeline, query, queue, resource, root, signature, +}; + +/// What D3D returns when none of the requested feature levels is supported. +const UNSUPPORTED: HRESULT = 0x887A_0004_u32 as i32; + +/// The device interface id (the same as on PC). Titles also import it as +/// data. +pub static IID: Iid = guid( + 0x189819f1, + 0x1db6, + 0x4b57, + [0xbe, 0x54, 0x18, 0x21, 0x33, 0x9b, 0x85, 0xf7], +); + +/// The levels the device answers to, as on PC: `ID3D12Device1` to +/// `ID3D12Device8`, and `ID3D12Device11`, which the title creates +/// its device as. Each level's table is the one before plus its methods. +const LEVEL_IIDS: [Iid; 9] = [ + guid( + 0x77acce80, + 0x638e, + 0x4e65, + [0x88, 0x95, 0xc1, 0xf2, 0x33, 0x86, 0x86, 0x3e], + ), + guid( + 0x30baa41e, + 0xb15b, + 0x475c, + [0xa0, 0xbb, 0x1a, 0xf5, 0xc5, 0xb6, 0x43, 0x28], + ), + guid( + 0x81dadc15, + 0x2bad, + 0x4392, + [0x93, 0xc5, 0x10, 0x13, 0x45, 0xc4, 0xaa, 0x98], + ), + guid( + 0xe865df17, + 0xa9ee, + 0x46f9, + [0xa4, 0x63, 0x30, 0x98, 0x31, 0x5a, 0xa2, 0xe5], + ), + guid( + 0x8b4f173b, + 0x2fea, + 0x4b80, + [0x8f, 0x58, 0x43, 0x07, 0x19, 0x1a, 0xb9, 0x5d], + ), + guid( + 0xc70b221b, + 0x40e4, + 0x4a17, + [0x89, 0xaf, 0x02, 0x5a, 0x07, 0x27, 0xa6, 0xdc], + ), + guid( + 0x5c014b53, + 0x68a1, + 0x4b9b, + [0x8b, 0xd1, 0xdd, 0x60, 0x46, 0xb9, 0x35, 0x8b], + ), + guid( + 0x728f1fa2, + 0xea11, + 0x4a9f, + [0x9b, 0x52, 0x9b, 0x42, 0xa4, 0x84, 0xd5, 0xc9], + ), + guid( + 0x5405c344, + 0xd457, + 0x444e, + [0xb4, 0xdd, 0x23, 0x66, 0xe4, 0x5a, 0xee, 0x39], + ), +]; + +/// Whether `iid` names the device: its first interface or a newer level. +pub(crate) fn is_device(iid: *const Iid) -> bool { + object::is(iid, &[IID]) || object::is(iid, &LEVEL_IIDS) +} + +/// The interface version these layouts were checked against (2.4). Both +/// Minecraft (March 2022) and the title (April 2026) pass it. +pub const CHECKED_VERSION: u32 = 0x0002_0004; + +/// Feature level 12_2, what the console hardware supports. +const HIGHEST_FEATURE_LEVEL: u32 = 0xc200; + +#[repr(C)] +pub struct Device { + object: Object, + /// GPU address of a null constant buffer; none yet. + null_constant_buffer: u64, + /// Byte 0 non-zero: calls the title would otherwise inline come to the + /// table. The rest is reserved. + out_of_line: [u32; 16], +} +const _: () = assert!(size_of::() == 0x58); + +/// One device per process, as on the console. +pub(crate) static DEVICE: Device = Device { + object: Object::new(&FUNCTIONS), + null_constant_buffer: 0, + out_of_line: [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], +}; + +pub(crate) fn device() -> This { + (&raw const DEVICE).cast() +} + +/// Device creation: `(adapter, parameters, iid, out)`. The parameters start +/// with the interface version; the rest (ring and scratch sizes, features +/// to leave out) does not matter to us yet. +pub extern "system" fn create( + _adapter: *const c_void, + parameters: *const u32, + iid: *const Iid, + out: *mut This, +) -> HRESULT { + if parameters.is_null() || iid.is_null() { + return E_INVALIDARG; + } + // SAFETY: checked non-null; the title passes its parameters and an id. + let (version, iid) = unsafe { (parameters.read(), &*iid) }; + tracing::info!(version = format_args!("{version:#x}"), "D3D12.X device"); + if version != CHECKED_VERSION { + tracing::warn!( + version = format_args!("{version:#x}"), + "device layouts were checked against {CHECKED_VERSION:#x} only" + ); + } + if !is_device(iid) { + tracing::warn!(iid = %guid_text(iid), "device created as an unknown interface"); + return E_NOINTERFACE; + } + if out.is_null() { + return S_FALSE; + } + if *iid == LEVEL_IIDS[8] { + NEWER.store(true, std::sync::atomic::Ordering::Relaxed); + } + object::answer(object::DEVICE, iid, Some(device()), out) +} + +/// Set when the title creates the device as `ID3D12Device11`. Its lists and +/// queues then have the newer layouts (two more methods each; see +/// `list` and `queue`), although the interface version stays 2.4. +/// shortcut: the creation interface is the only sign of the newer layouts +/// we have (the title, April 2026, versus Minecraft, March 2022); +/// look for a better one if a title breaks the rule. +static NEWER: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); + +pub(crate) fn newer() -> bool { + NEWER.load(std::sync::atomic::Ordering::Relaxed) +} + +/// The device, or its DXGI side. +extern "system" fn query_interface(this: This, iid: *const Iid, out: *mut This) -> HRESULT { + let found = if is_device(iid) { + Some(this) + } else if object::is(iid, &dxgi::DEVICE_IIDS) { + Some(dxgi::device()) + } else { + None + }; + object::answer(object::DEVICE, iid, found, out) +} + +/// What `D3D12ConfigureVirtualMemoryX` takes and fills in. +#[repr(C)] +pub struct VirtualMemory { + flags: u32, + /// GPU page table size in 4 MiB pages. + page_table_pages: u32, + /// Memory kept across title processes for the frame buffer. + preserved_bytes: u32, + /// Out: the range graphics addresses fall in. + lowest: u64, + highest: u64, +} +const _: () = assert!(size_of::() == 0x20); + +/// `d3d12_xs!D3D12ConfigureVirtualMemoryX`, called before any graphics +/// allocation. The inputs size console structures we do not have; the +/// range out is all of user space, since GPU addresses are CPU addresses. +pub extern "system" fn configure_virtual_memory(config: *mut VirtualMemory) -> HRESULT { + // SAFETY: the title passes its configuration (null is tolerated). + let Some(config) = (unsafe { config.as_mut() }) else { + return E_INVALIDARG; + }; + tracing::info!( + flags = config.flags, + page_table_pages = config.page_table_pages, + preserved_bytes = config.preserved_bytes, + "graphics virtual memory" + ); + (config.lowest, config.highest) = user_space(); + S_OK +} + +fn user_space() -> (u64, u64) { + #[cfg(windows)] + { + use windows_sys::Win32::System::SystemInformation::{GetSystemInfo, SYSTEM_INFO}; + // SAFETY: plain data, filled in by the call. + let mut info: SYSTEM_INFO = unsafe { std::mem::zeroed() }; + // SAFETY: a valid out pointer. + unsafe { GetSystemInfo(&mut info) }; + ( + info.lpMinimumApplicationAddress as u64, + info.lpMaximumApplicationAddress as u64, + ) + } + #[cfg(not(windows))] + (0x1_0000, 0x7fff_fffe_ffff) +} + +extern "system" fn node_count(_: This) -> u32 { + 1 +} + +/// Feature query 2: the highest of the requested feature levels we support. +#[repr(C)] +struct FeatureLevels { + count: u32, + requested: *const u32, + highest: u32, +} + +/// Feature query 0, what an RDNA 2 GPU reports. The console's layout has +/// one field more than PC's (index 11). +const OPTIONS: [u32; 16] = [ + 1, // double-precision shader operations + 1, // output-merger logic operations + 2, // minimum precision: 16-bit + 3, // tiled resources tier + 3, // resource binding tier + 1, // stencil reference from pixel shaders + 1, // typed UAV loads of more formats + 1, // rasterizer-ordered views + 3, // conservative rasterization tier + 40, // GPU address bits per resource + 0, // 64 KiB standard swizzle + 0, // console-only field + 0, // cross-node sharing tier + 0, // cross-adapter row-major textures + 1, // viewport and render target index from any stage + 2, // resource heap tier +]; + +extern "system" fn check_feature_support( + _: This, + feature: u32, + data: *mut c_void, + size: u32, +) -> HRESULT { + const OPTIONS_QUERY: u32 = 0; + const ARCHITECTURE: u32 = 1; + const FEATURE_LEVELS: u32 = 2; + const FORMAT_SUPPORT: u32 = 3; + const MULTISAMPLE: u32 = 4; + let expected = match feature { + OPTIONS_QUERY => size_of_val(&OPTIONS), + ARCHITECTURE => 16, + FEATURE_LEVELS => size_of::(), + FORMAT_SUPPORT => 12, + MULTISAMPLE => 16, + _ => { + tracing::warn!(feature, size, "device feature query not implemented"); + return E_NOTIMPL; + } + }; + if data.is_null() || size as usize != expected { + return E_INVALIDARG; + } + match feature { + OPTIONS_QUERY => { + // SAFETY: checked size and non-null. + unsafe { data.cast::<[u32; 16]>().write_unaligned(OPTIONS) }; + S_OK + } + ARCHITECTURE => { + // SAFETY: checked size and non-null. + let a = unsafe { &mut *data.cast::<[u32; 4]>() }; + if a[0] != 0 { + return E_INVALIDARG; // one node only + } + // Not tile-based; unified, cache-coherent memory. + a[1..].copy_from_slice(&[0, 1, 1]); + S_OK + } + FORMAT_SUPPORT => { + // SAFETY: checked size and non-null. + let q = unsafe { &mut *data.cast::<[u32; 3]>() }; + // shortcut: every use of every format; answer from the host + // device once there is one. + q[1] = 0x7fff_ffff; + q[2] = 0xffff; + S_OK + } + MULTISAMPLE => { + // SAFETY: checked size and non-null. + let q = unsafe { &mut *data.cast::<[u32; 4]>() }; + // Format, sample count, flags in; one quality level out for the + // counts the hardware has. + q[3] = u32::from(matches!(q[1], 1 | 2 | 4 | 8)); + S_OK + } + _ => feature_levels(data), + } +} + +fn feature_levels(data: *mut c_void) -> HRESULT { + // SAFETY: the caller checked size and non-null. + let query = unsafe { &mut *data.cast::() }; + if query.requested.is_null() { + return E_INVALIDARG; + } + // SAFETY: the title passes `count` levels. + let requested = unsafe { std::slice::from_raw_parts(query.requested, query.count as usize) }; + match requested + .iter() + .copied() + .filter(|&l| l <= HIGHEST_FEATURE_LEVEL) + .max() + { + Some(level) => { + query.highest = level; + S_OK + } + None => UNSUPPORTED, + } +} + +/// Device methods 0x1c8 and 0x218 (`SLOT`). The title calls both +/// (title+0x2477578 and title+0x24800d5) as `(this, description, interface +/// id, out)`, asks for `ID3D12PipelineState`, and on success keeps the +/// object `out` names and draws with it; on failure it goes without that +/// pipeline, silently. What the descriptions hold is not known: the calls +/// fail as they always did, with `out` null, and the first ones log the +/// description's words and what its first word points at, so that the two +/// methods can be written. +/// shortcut: not implemented. Answering `S_OK` here without making the +/// pipeline would hand the title whatever its stack held as an object. +extern "system" fn unknown_pipeline( + _: This, + desc: *const u8, + _iid: *const Iid, + out: *mut This, +) -> HRESULT { + use std::sync::atomic::{AtomicU32, Ordering}; + static CALLS: [AtomicU32; 2] = [const { AtomicU32::new(0) }; 2]; + let calls = CALLS[usize::from(SLOT == 0x218)].fetch_add(1, Ordering::Relaxed) + 1; + if !out.is_null() { + // SAFETY: the title's out pointer (a local of its own). + unsafe { *out = std::ptr::null() }; + } + if calls <= 4 || calls.is_power_of_two() { + // Sixteen 64-bit words at `at`, read through the kernel: neither + // pointer is known to be mapped. + #[cfg(windows)] + let words = |at: usize| -> Option> { + let mut bytes = [0u8; 128]; + (at != 0 && crate::host::read_into(at as *const u8, &mut bytes)).then(|| { + bytes + .as_chunks::<8>().0.iter() + .map(|c| c.iter().rev().fold(0u64, |v, &b| v << 8 | u64::from(b))) + .collect() + }) + }; + #[cfg(not(windows))] + let words = |_: usize| None::>; + let description = words(desc as usize); + let first = description + .as_ref() + .and_then(|w| words(w[0] as usize)); + tracing::warn!( + slot = format_args!("{:#x}", SLOT), + calls, + description = format_args!("{description:x?}"), + first_points_at = format_args!("{first:x?}"), + "a pipeline creation method that is not implemented: the title goes without this pipeline" + ); + } + E_NOTIMPL +} + +/// IUnknown 3, object methods 4, device methods 76 (0x18-0x290), then the +/// methods `ID3D12Device1` to `ID3D12Device8` add, in order: 3, 1, 3, 6, 9, +/// 1, 2, 9 (0x298-0x3a0, the console's own among them), then those of +/// `ID3D12Device9` to `ID3D12Device11`, whose console layout is unknown. +/// Every slot exists so that a call to one we have not written logs it. +static FUNCTIONS: Table<160> = { + let mut f = object::d3d12_object(object::missing_table::<{ object::DEVICE }, 160>()); + f[0] = query_interface as *const (); // 0x00 + f[7] = node_count as *const (); // 0x38 + f[8] = queue::create as *const (); // 0x40 + f[9] = list::create_allocator as *const (); // 0x48 + f[12] = list::create_list as *const (); // 0x60 + f[10] = pipeline::create_graphics as *const (); // 0x50 + f[11] = pipeline::create_compute as *const (); // 0x58 + f[13] = check_feature_support as *const (); // 0x68 + f[14] = descriptor::create_heap as *const (); // 0x70 + f[15] = descriptor::increment_size as *const (); // 0x78 + f[16] = root::create as *const (); // 0x80 + f[17] = descriptor::create_cbv as *const (); // 0x88 + f[18] = descriptor::create_srv as *const (); // 0x90 + f[19] = descriptor::create_uav as *const (); // 0x98 + f[20] = descriptor::create_rtv as *const (); // 0xa0 + f[21] = descriptor::create_dsv as *const (); // 0xa8 + f[22] = descriptor::create_sampler as *const (); // 0xb0 + f[23] = descriptor::copy as *const (); // 0xb8 + f[24] = descriptor::copy_simple as *const (); // 0xc0 + f[25] = resource::allocation_info as *const (); // 0xc8 + f[26] = resource::custom_heap_properties as *const (); // 0xd0 + f[27] = resource::create_committed as *const (); // 0xd8 + f[28] = resource::create_heap as *const (); // 0xe0 + f[29] = resource::create_placed as *const (); // 0xe8 + f[36] = fence::create as *const (); // 0x120 + f[38] = resource::copyable_footprints as *const (); // 0x130 + f[39] = query::create as *const (); // 0x138 + f[41] = signature::create as *const (); // 0x148 + f[48] = queue::create_x as *const (); // 0x180 + f[57] = unknown_pipeline::<0x1c8> as *const (); // 0x1c8 + f[61] = descriptor::create_sampler_x as *const (); // 0x1e8 + f[62] = pipeline::create_compute_x as *const (); // 0x1f0 + f[67] = unknown_pipeline::<0x218> as *const (); // 0x218 + f[69] = object::ignore as *const (); // 0x228 debug error filter + f[70] = descriptor::create_placed_srv as *const (); // 0x230 + f[71] = descriptor::create_placed_uav as *const (); // 0x238 + f[73] = list::create_list_x as *const (); // 0x248 + f[74] = resource::register_page_pool as *const (); // 0x250 + f[75] = resource::unregister_page_pool as *const (); // 0x258 + // CreateCommittedResourceX: its description is PC's plus DCC options, + // which we have no use for (the AMD upscaler's, on Series S). + f[76] = resource::create_committed as *const (); // 0x260 + f[78] = frame::set_interval as *const (); // 0x270 + f[79] = frame::schedule as *const (); // 0x278 + f[80] = frame::wait as *const (); // 0x280 + f[81] = frame::statistics as *const (); // 0x288 + f[86] = pipeline::create_stream as *const (); // 0x2b0 + f[108] = resource::allocation_info2 as *const (); // 0x360 + f[127] = resource::create_committed3 as *const (); // 0x3f8 + f[133] = resource::create_at_address as *const (); // 0x428 + Table(f) +}; + +#[cfg(test)] +mod tests { + use super::*; + use crate::object::slot; + + fn create_as(iid: &Iid) -> (HRESULT, This) { + let version = CHECKED_VERSION; + let mut device = std::ptr::null(); + let hr = create(std::ptr::null(), &version, iid, &mut device); + (hr, device) + } + + #[test] + fn creation_hands_out_the_device() { + let (hr, device) = create_as(&IID); + assert_eq!(hr, S_OK); + assert_eq!(device, super::device()); + // The title tests byte 0x18 before inlining a device call. + // SAFETY: the device is 0x58 bytes. + assert_ne!(unsafe { device.cast::().add(0x18).read() }, 0); + assert_eq!(create_as(&[0; 16]).0, E_NOINTERFACE); + assert_eq!( + slot:: u32>(device, 0x38)(device), + 1 + ); + let missing = slot:: HRESULT>(device, 0xf0); + assert_eq!(missing(), E_NOTIMPL); + } + + #[test] + fn newer_device_levels_are_the_same_device() { + // ID3D12Device11, as the title asks for it. + let (hr, device) = create_as(&LEVEL_IIDS[8]); + assert_eq!((hr, device), (S_OK, super::device())); + let mut same = std::ptr::null(); + assert_eq!(query_interface(device, &LEVEL_IIDS[4], &mut same), S_OK); + assert_eq!(same, device); + // A Device8 method we have not written fails without crashing. + let missing = slot:: HRESULT>(device, 0x3a0); + assert_eq!(missing(), E_NOTIMPL); + } + + /// A device child, and the DXGI device, hand out the device as any + /// interface the device itself answers to. + #[test] + fn the_device_is_found_at_every_level_through_others() { + type Get = extern "system" fn(This, *const Iid, *mut This) -> HRESULT; + let fence_iid = &crate::fence::FENCE_IIDS[0]; + let mut fence = std::ptr::null(); + assert_eq!( + crate::fence::create(std::ptr::null(), 0, 0, fence_iid, &mut fence), + S_OK + ); + let get_device = slot::(fence, 0x38); + let dxgi = dxgi::device(); + let query = slot::(dxgi, 0); + for iid in std::iter::once(&IID).chain(&LEVEL_IIDS) { + let mut found = std::ptr::null(); + assert_eq!(get_device(fence, iid, &mut found), S_OK, "{iid:02x?}"); + assert_eq!(found, device()); + let mut found = std::ptr::null(); + assert_eq!(query(dxgi, iid, &mut found), S_OK, "{iid:02x?}"); + assert_eq!(found, device()); + } + // What the device is not, it is not through them either. + let mut found = device(); + assert_eq!(get_device(fence, fence_iid, &mut found), E_NOINTERFACE); + assert!(found.is_null()); + slot:: u32>(fence, 0x10)(fence); + } + + /// The host's: a fence's `GetDevice` for `ID3D12Device5`. + #[cfg(windows)] + #[test] + fn the_hosts_children_hand_out_newer_device_levels() { + use windows::Win32::Graphics::Direct3D12::{ + D3D12_FENCE_FLAG_NONE, ID3D12Device5, ID3D12Fence, + }; + let Some(host) = crate::host::host() else { + return; // no host GPU here + }; + // SAFETY: plain calls on the host device and its fence. + unsafe { + let fence: ID3D12Fence = host.device.CreateFence(0, D3D12_FENCE_FLAG_NONE).unwrap(); + let mut device: Option = None; + assert!(fence.GetDevice(&mut device).is_ok()); + assert!(device.is_some()); + } + } + + #[test] + fn virtual_memory_configuration_reports_user_space() { + let mut config = VirtualMemory { + flags: 0, + page_table_pages: 7, + preserved_bytes: 0, + lowest: 0, + highest: 0, + }; + assert_eq!(configure_virtual_memory(&mut config), S_OK); + assert!(0 < config.lowest && config.lowest < config.highest); + let heap = Box::new(0u8); + assert!((config.lowest..=config.highest).contains(&(&raw const *heap as u64))); + assert_eq!(configure_virtual_memory(std::ptr::null_mut()), E_INVALIDARG); + } + + #[test] + fn feature_levels_pick_the_highest_supported() { + type Check = extern "system" fn(This, u32, *mut c_void, u32) -> HRESULT; + let device = device(); + let check = slot::(device, 0x68); + let query = |levels: &[u32], size| { + let mut query = FeatureLevels { + count: levels.len() as u32, + requested: levels.as_ptr(), + highest: 0, + }; + let hr = check(device, 2, (&raw mut query).cast(), size); + (hr, query.highest) + }; + let levels = [0xb000, 0xb100, 0xc000, 0xc100, 0xd000]; + assert_eq!(query(&levels, 0x18), (S_OK, 0xc100)); + assert_eq!(query(&levels, 0x10).0, E_INVALIDARG); + assert_eq!(query(&levels[4..], 0x18).0, UNSUPPORTED); + } +} diff --git a/crates/leonida-gpu/src/draw.rs b/crates/leonida-gpu/src/draw.rs new file mode 100644 index 000000000..e58c977bb --- /dev/null +++ b/crates/leonida-gpu/src/draw.rs @@ -0,0 +1,3761 @@ +//! Draws on the host GPU (decision 0007, step 3). A list keeps the state +//! the title sets for its draws (pipeline, descriptor heaps, root +//! arguments, vertex and index buffers, targets); each draw then brings the +//! host list up to date: the host pipeline and our root signature, the +//! user data the translated shaders read, the host copies of the buffers +//! and descriptors they read, and the states of the textures involved. +//! State the host keeps across draws (viewports, scissors, blend factor, +//! stencil reference, topology, targets) is set on the host list as the +//! title sets it. + +use std::sync::atomic::{AtomicU64, Ordering}; + +use leonida_shader::resource::RootIndexedView; +use leonida_shader::{ResourceType, RootType, UsedResource}; + +use crate::descriptor::View; +use windows::Win32::Foundation::RECT; +use windows::Win32::Graphics::Direct3D::D3D_PRIMITIVE_TOPOLOGY; +use windows::Win32::Graphics::Direct3D12::*; +use windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT; +use windows::core::Interface; + +use crate::host::HostList; +use crate::object::This; +use crate::pipeline::host::HostPipeline; + +/// A root argument as the title set it. +#[derive(Debug, Clone, Default)] +enum Root { + #[default] + None, + /// A descriptor table's first descriptor (an address in a heap). + Table(u64), + Constants(Vec), + /// A root view's GPU address. + View(u64), +} + +#[repr(C)] +#[derive(Debug, Clone, Copy, Default)] +pub(crate) struct VertexView { + address: u64, + size: u32, + stride: u32, +} + +#[repr(C)] +#[derive(Debug, Clone, Copy, Default)] +pub(crate) struct IndexView { + address: u64, + size: u32, + format: u32, +} + +/// Host states of a depth target, and of a texture shaders read. +const DEPTH_WRITE: u32 = 0x10; +const DEPTH_READ: u32 = 0x20; +const SHADER_RESOURCE: u32 = 0x40 | 0x80; + +thread_local! { + /// While a draw is prepared (`State::bind`, then its targets' states): + /// the depth target the draw only tests (0: none, or one it writes), + /// and whether a view its shaders read is of that same texture. + static TESTED_DEPTH: std::cell::Cell<(usize, bool)> = + const { std::cell::Cell::new((0, false)) }; + /// While a stage's tables are walked (`State::tables`): whether that + /// stage's shader can store to buffers (`Translated::stores`). + static STORES: std::cell::Cell = const { std::cell::Cell::new(true) }; + /// While `State::early_textures` runs the texture pass: the + /// milliseconds and the bytes that run may take, in place of the + /// pass's own per frame. + static PASS_BUDGET: std::cell::Cell> = const { std::cell::Cell::new(None) }; +} + +/// The milliseconds of every frame the pass that uploads textures picked +/// by index takes before a shader that picks by index has asked for it +/// (`LEONIDA_EARLY_TEXTURES_MS`, 12; 0: never, as before), and the +/// milliseconds it may take just before a draw of the title's decoration +/// bake (`LEONIDA_BAKE_TEXTURES_MS`, 1500; 0: nothing special). +/// +/// The pass ran only from the first world frame on, where it met some +/// 24,000 slots at once and needed 60-80 frames for them. The title bakes +/// its characters' skin and decorations into textures of its own while it +/// loads, 159-1,165 frames before that (runs 156-174), with a pixel shader +/// that picks its sources by index: whatever was not on the card then was +/// baked as nothing, once, for the run. On the console a texture is there +/// when its bytes are. +fn early_budgets() -> (u64, u64) { + static MS: std::sync::OnceLock<(u64, u64)> = std::sync::OnceLock::new(); + *MS.get_or_init(|| { + let ms = |name: &str, default: u64| { + std::env::var(name).ok().and_then(|v| v.trim().parse::().ok()).unwrap_or(default) + }; + (ms("LEONIDA_EARLY_TEXTURES_MS", 12), ms("LEONIDA_BAKE_TEXTURES_MS", 1500)) + }) +} + +/// The pixel shaders of the title's decoration bake (the title: +/// `PS_BakeDecorations_*`), by the first 16 hex digits of their hash as the +/// frame listings print it. They draw into a 256x256 corner of 2048x2048 +/// targets and name no texture in a table. +const BAKE_PIXEL_SHADERS: [&str; 4] = + ["c0a7fe77b1862e10", "0d1575a396dfe513", "b7cfd8dda91ebb6b", "280967ad158cee0b"]; + +/// Since the start: early runs of the texture pass, and those of them +/// made for a bake draw. +pub(crate) static EARLY_TEXTURE_PASSES: [AtomicU64; 2] = [AtomicU64::new(0), AtomicU64::new(0)]; + +/// Whether a buffer range a shader names through an unordered access view +/// is given to shaders as written (snapshot before the submission, compare +/// and write back after) only if that shader's code can store to buffers. +/// The title binds buffers its shaders only read through such views, and +/// every range declared costs a snapshot and a compare of its bytes: 3.97 +/// GB a frame in 31 submissions, 0.49 s of snapshots and 0.28 s of +/// comparing (run 28). On by default; `LEONIDA_WRITE_SKIP=0` declares +/// every such range, as before. +fn write_skip() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("LEONIDA_WRITE_SKIP").is_none_or(|v| v != "0")) +} + +/// A run of indirect records clamped in one pass ([`windows`]): the host +/// copy they came from (its number), their kind and stride, the offset of +/// the first in that copy, how many, and the list's scratch buffer that +/// holds them clamped, record `i` at `i * step`. +#[derive(Clone)] +struct Window { + copy: u64, + kind: u32, + stride: u32, + /// How far apart the records are in the copy, and in the scratch + /// buffer: what the title walks them by ([`windows`]). + step: u32, + base: u64, + records: u32, + scratch: ID3D12Resource, +} + +/// The most records clamped in one pass ([`windows`]). +const WINDOW_MOST: u64 = 64; + +/// Whether indirect draws that read record after record of one argument +/// buffer are clamped a window at a time (`LEONIDA_INDIRECT_WINDOW=1`; off +/// by default). +/// +/// The title issues its mesh draws one record per call, each from the next +/// slot of the same argument buffer: 3,460 a frame in gameplay, and before +/// each our clamp ran as a compute dispatch of its own between two waits, +/// so the card went from drawing to compute and back for every record. In +/// the timing run of the lit scene (run 79) a shadow draw of next to +/// nothing cost 14-16 microseconds, 4,126 records a frame. +/// +/// With the switch, when a draw asks for a record a short step after the +/// one drawn before, the clamp takes that record and the ones that step +/// apart after it (16, then twice as many each time, [`WINDOW_MOST`] at +/// most, never past the buffer) into +/// the list's scratch buffer in one pass, and the draws that follow read +/// their record there with no pass of ours and no barrier (the scratch +/// buffer stays readable as arguments until the next clamp), until one of +/// these: a compute +/// dispatch, a direct draw, an indirect call with a count buffer or more +/// than one record, a draw whose shaders can store to buffers, a record +/// outside the window, another host list. +/// +/// The step is the one the title is seen to take, not the stride its +/// command signature names: it draws one record a call, for which the +/// stride means nothing, and the title names 12 bytes (the three +/// words of a mesh dispatch) for records it keeps 32 bytes apart (2,173 of +/// a frame's 3,349 mesh records in run 87's listed frame; 283 are 16 +/// apart, which ends a window). Walked by the named stride the window +/// never opened: run 87, with the switch, still clamped 5,068 records a +/// frame one at a time. +/// +/// What it costs the guard against garbage records: nothing against a +/// hang (every record is bounded as before and charged to the list's +/// budget as before), but the budget is charged when a window is clamped, +/// so also for records of the window's tail that are never drawn. Those +/// hold garbage in this title (slots of all ones: run 93 spent lists' +/// budgets on them and emptied the draws after), so in a window a record +/// that asks for more than can run is left empty and charges nothing +/// (`crate::indirect::bound_ahead`); a tail record that looks real is +/// charged what it asks, a few thousand of 2^27. And arguments the title's CPU side changes are seen as +/// before, at the next submission. +/// +/// Off for the rest of the run from the first error the card's driver +/// reports to the system (`crate::drvwatch`): every loss of the card in a +/// run with windows was announced that way seconds ahead. +fn windows() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("LEONIDA_INDIRECT_WINDOW").is_some_and(|v| v == "1")) && !crate::drvwatch::tripped() +} + +/// Whether a record that is not on the window's walk opens a window of its +/// own at once, with the step the title was last seen to walk that +/// argument buffer by (`LEONIDA_WINDOW_JUMP=1`; `alt`: twenty seconds +/// with, twenty without, in turn, each change said in the log). Off by +/// default. Needs [`windows`]. +/// +/// Run 243 counted, per frame, 2,370 indirect commands read from a window +/// and 2,370 clamped by a pass of ours; 960 of those passes were for +/// records "off the window's walk": the title draws a few records one +/// after the other and then jumps to another place in the same argument +/// buffer, some 480 times a frame. The record after a jump was clamped +/// alone (its step is not known from one record), and the one after it +/// opened a window of sixteen: two passes a jump, each one a trip of the +/// card from drawing to compute and back (9 microseconds in the game). +/// +/// With the switch the step of the last window that draws did read from +/// is remembered with its argument buffer, kind and stride, and a record +/// that would be clamped alone on that buffer opens sixteen records at +/// that step instead: what the next record would have opened anyway, one +/// record earlier, so no more of the list's budget is spent than before. +/// If no draw reads from a window opened that way before the next pass, +/// the step is forgotten until a walk shows it again: a title that draws +/// lone records all over a buffer gets what it had. +fn jump_windows() -> bool { + /// 0 off, 1 on, 2 in turn. + static MODE: std::sync::OnceLock = std::sync::OnceLock::new(); + match *MODE.get_or_init(|| match std::env::var("LEONIDA_WINDOW_JUMP").as_deref() { + Ok("1") => 1, + Ok("alt") => 2, + _ => 0, + }) { + 0 => false, + 1 => true, + _ => { + static EPOCH: std::sync::OnceLock = std::sync::OnceLock::new(); + let on = (EPOCH.get_or_init(std::time::Instant::now).elapsed().as_secs() / 20) % 2 == 1; + static LAST: std::sync::atomic::AtomicU8 = std::sync::atomic::AtomicU8::new(2); + if LAST.swap(u8::from(on), std::sync::atomic::Ordering::Relaxed) != u8::from(on) { + tracing::info!( + "a record off the window's walk opens a window at the remembered step from now (LEONIDA_WINDOW_JUMP=alt): {}", + if on { "ON" } else { "off, as usual" } + ); + } + on + } + } +} + +/// Whether a single record that misses its window is gathered: given a +/// slot that the list's prelude fills in one pass with the list's other +/// such records, in place of a pass of ours in front of its draw +/// (`crate::indirect::gather`; `LEONIDA_INDIRECT_GATHER=1`; `alt`: twenty +/// seconds with, twenty without, in turn, each change said in the log). +/// Off by default. Needs [`windows`]. +fn gathers() -> bool { + /// 0 off, 1 on, 2 in turn. + static MODE: std::sync::OnceLock = std::sync::OnceLock::new(); + match *MODE.get_or_init(|| match std::env::var("LEONIDA_INDIRECT_GATHER").as_deref() { + Ok("1") => 1, + Ok("alt") => 2, + _ => 0, + }) { + 0 => false, + 1 => true, + _ => { + static EPOCH: std::sync::OnceLock = std::sync::OnceLock::new(); + let on = (EPOCH.get_or_init(std::time::Instant::now).elapsed().as_secs() / 20) % 2 == 1; + static LAST: std::sync::atomic::AtomicU8 = std::sync::atomic::AtomicU8::new(2); + if LAST.swap(u8::from(on), std::sync::atomic::Ordering::Relaxed) != u8::from(on) { + tracing::info!( + "single indirect records are gathered for their list's prelude from now (LEONIDA_INDIRECT_GATHER=alt): {}", + if on { "ON" } else { "off, as usual" } + ); + } + on + } + } +} + +/// The records of a window opened at a remembered step ([`jump_windows`]): +/// what the record after a lone one opens. +const WINDOW_JUMP: u32 = 16; + +/// What a record that would be clamped alone opens instead, if the step +/// its argument buffer is walked by is remembered: that step and how many +/// records (never past the buffer, of which `left` bytes are left from +/// the record on). None if nothing is remembered for this buffer, kind +/// and stride, or no second record fits. +fn jump_window(remembered: Option<(u64, u32, u32, u32)>, (copy, kind, stride): (u64, u32, u32), left: u64) -> Option<(u32, u32)> { + let (c, k, s, step) = remembered?; + if (c, k, s) != (copy, kind, stride) || step == 0 { + return None; + } + let fit = (left / u64::from(step)).min(u64::from(WINDOW_JUMP)) as u32; + (fit > 1).then_some((step, fit)) +} + +/// Diagnostics of [`windows`]: indirect commands since the last line, by +/// what became of their clamp. In order: read from a window (no pass of +/// ours); then clamped by a pass of ours because: it is a dispatch; it +/// asks for more than one record; it has a count buffer; its shaders can +/// store to buffers; it is the list's first; there was no window on its +/// argument buffer (another buffer, kind or stride, or the window was +/// ended); its record does not continue the window's walk; it is past the +/// window's end (the next window: as meant). And the records those passes +/// clamped in all; the passes that opened a window at a remembered step +/// ([`jump_windows`]), and those of them no draw read from; the commands +/// that read a gathered record ([`gathers`]: no pass of ours either), and +/// those that asked for one and got none (the list no longer gathers, or +/// its set is full). +#[cfg(feature = "diagnostics")] +pub(crate) static WINDOW_WHY: [std::sync::atomic::AtomicU64; 14] = [const { std::sync::atomic::AtomicU64::new(0) }; 14]; + +/// The line of [`WINDOW_WHY`], per frame over `frames` frames. +#[cfg(feature = "diagnostics")] +pub(crate) fn window_line(frames: f64) { + let n: Vec = WINDOW_WHY.iter().map(|n| n.swap(0, std::sync::atomic::Ordering::Relaxed) as f64 / frames.max(1.0)).collect(); + let g: Vec = crate::indirect::GATHER_NONE.iter().map(|n| n.swap(0, std::sync::atomic::Ordering::Relaxed) as f64 / frames.max(1.0)).collect(); + tracing::info!( + "indirect commands per frame by their clamp: {:.0} read from a window (no pass of ours); a pass of ours for {:.0}: {:.0} dispatches, {:.0} of more than one record, {:.0} with a count \ + buffer, {:.0} whose shaders can store to buffers, {:.0} first on their list, {:.0} with no window on their argument buffer, {:.0} off the window's walk, {:.0} past the window's end; \ + {:.0} records clamped by those passes; {:.0} of the passes opened a window at a remembered step (LEONIDA_WINDOW_JUMP=1), {:.0} of those windows were read by no draw; \ + {:.0} read a record gathered for their list's prelude (LEONIDA_INDIRECT_GATHER=1), {:.0} asked for one and got none (no fit for the clamp {:.0}, the list had stopped gathering {:.0}, too many buffers {:.0}, the set full {:.0}, no buffer {:.0})", + n[0], + n[1..9].iter().sum::(), + n[1], + n[2], + n[3], + n[4], + n[5], + n[6], + n[7], + n[8], + n[9], + n[10], + n[11], + n[12], + n[13], + g[0], + g[1], + g[2], + g[3], + g[4], + ); +} + +/// What one title list has set, and what its host list was last given. +#[derive(Default)] +pub(crate) struct State { + pipeline: usize, + /// View heap, sampler heap. + heaps: [usize; 2], + graphics: Vec, + compute: Vec, + vertex: [VertexView; 32], + index: IndexView, + /// Bound render target and depth resources, for their host states. + targets: Vec, + depth: usize, + /// The host state the bound depth view needs ([`depth_state`]). + depth_state: u32, + /// The title's primitive topology (the host's may differ). + topology: u32, + /// What the title set that goes straight onto the host list, kept for + /// the host list that continues this one after a cut ([`State::replay`]): + /// whether a topology was set, the render target and depth handles, the + /// viewports, the scissors, the blend factor and the stencil reference. + topology_set: bool, + target_handles: Vec, + depth_handle: u64, + targets_set: bool, + viewports: Vec, + scissors: Vec, + blend: Option<[f32; 4]>, + stencil: Option, + depth_bounds: Option<[f32; 2]>, + /// The indirect records clamped last, if later draws may still read + /// them ([`windows`]). + window: Option, + /// With [`jump_windows`]: the argument buffer (its copy's number), kind + /// and stride of the last window of several records that a draw read + /// from, and that window's step. + walk_step: Option<(u64, u32, u32, u32)>, + /// Whether [`State::window`] was opened at the remembered step, and + /// whether a draw has read from it since. + window_jumped: bool, + window_read: bool, + /// Diagnostics: the argument buffer and the offset of the indirect + /// command before this one on the list. + #[cfg(feature = "diagnostics")] + last_indirect: (u64, u64), + /// What the host list has: pipeline, root signature, heaps. + host_pipeline: usize, + /// Graphics, compute. + host_roots: [usize; 2], + host_heaps: [usize; 2], + /// Tables made afresh in this list: (table, slot count, contents) → first + /// dynamic slot. + fresh_tables: std::collections::HashMap<(u64, u32, u64), u32>, + /// The dynamic slots the list holds: title heap, first, count; given + /// back when the list has run, is reset or released. + dynamic: Vec<(usize, u32, u32)>, + /// Root SRVs bound as one-view tables in this list: (title heap, title + /// address; 0 for none) → dynamic slot, and the host copy the slot + /// shows: later draws of the list bring that one up to date, whatever + /// copy the address would find by then (`shadow.rs` `tails`). + root_srv_slots: std::collections::HashMap<(usize, u64), RootSlot>, + /// Root UAVs bound as one-view tables in this list, likewise. + root_uav_slots: std::collections::HashMap<(usize, u64), RootSlot>, + /// The list ran and its dynamic slots were given back. + tables_gone: bool, +} + +impl Drop for State { + fn drop(&mut self) { + for &(heap, first, n) in &self.dynamic { + crate::descriptor::release_dynamic(heap, first, n); + } + } +} + +impl State { + /// The list's submission has run (submissions are waited for): the + /// dynamic slots its tables were made in are given back, not kept + /// until the title resets the list. A frame of the opening cutscene + /// asks for 12,500 tables; held until the resets they ran the 131,072 + /// slots out, and up to 4,900 draws a frame went without their tables. + /// shortcut: a list the title runs a second time without a reset then + /// reads slots others may have taken (logged once). + pub(crate) fn tables_done(&mut self) { + if self.tables_gone && self.dynamic.is_empty() { + return; + } + if self.tables_gone { + static ONCE: std::sync::Once = std::sync::Once::new(); + ONCE.call_once(|| tracing::warn!("a list ran again after its descriptor tables were given back")); + } + for (heap, first, n) in self.dynamic.drain(..) { + crate::descriptor::release_dynamic(heap, first, n); + } + self.fresh_tables.clear(); + self.root_srv_slots.clear(); + self.root_uav_slots.clear(); + self.tables_gone = true; + } +} + +/// An experiment on the title's scissor rectangles (`LEONIDA_SCISSOR_TEST=full`): +/// they are all widened to the whole target. The title's room at +/// the start of the prologue lost its walls in five runs of seven, and in +/// those runs the player's body and the world outside were cut by one +/// rectangle around the window (run 85, frame 2046): one run with this on +/// says whether the walls are drawn and cut away by such a rectangle, or +/// not drawn at all. Off by default: a rectangle the title sets is part of +/// its picture. +fn scissor_test() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var("LEONIDA_SCISSOR_TEST").as_deref() == Ok("full")) +} + +/// An experiment on mesh draws (`LEONIDA_MESH_TEST`): 1 for `skip` (none +/// is issued), 2 for `scissor` (each runs its shaders but rasterises one +/// pixel), 0 otherwise. It tells a card hung by a mesh shader from one hung +/// by what the shader's triangles cover. +fn mesh_test() -> u8 { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| match std::env::var("LEONIDA_MESH_TEST").as_deref() { + Ok("skip") => 1, + Ok("scissor") => 2, + _ => 0, + }) +} + +/// `LEONIDA_MESH_TEST=keep:[:]`: only the mesh +/// draws whose mesh shader's hash ends in one of the first digits (and +/// whose digit before it is one of the second, if given) are issued: a +/// search for the shaders that stop the card. +fn mesh_kept(pipeline: usize) -> bool { + static KEEP: std::sync::OnceLock> = std::sync::OnceLock::new(); + let Some((last, before)) = KEEP.get_or_init(|| { + let value = std::env::var("LEONIDA_MESH_TEST").ok()?; + let mut parts = value.strip_prefix("keep:")?.split(':'); + Some((parts.next()?.to_owned(), parts.next().unwrap_or("").to_owned())) + }) else { + return true; + }; + let Some(p) = crate::pipeline::host_pipeline(pipeline as This) else { + return true; + }; + let Some(at) = p.name.find("mesh ") else { + return true; + }; + let hash = p.name[at + 5..].as_bytes(); + if hash.len() < 16 { + return true; + } + last.as_bytes().contains(&hash[15]) && (before.is_empty() || before.as_bytes().contains(&hash[14])) +} + +/// Draws recorded on the host GPU since the last frame line. +static DRAWN: AtomicU64 = AtomicU64::new(0); + +/// Draws run on the host so far. +pub(crate) fn drawn() -> u64 { + DRAWN.load(Ordering::Relaxed) +} + +/// The draws traced since the last present (diagnostics builds, with +/// debug logging for this module): logged when the frame comes out black. +#[cfg(feature = "diagnostics")] +static FRAME: std::sync::Mutex> = std::sync::Mutex::new(Vec::new()); + +/// The draws traced since the last call. +#[cfg(feature = "diagnostics")] +pub(crate) fn take_frame() -> Vec { + std::mem::take(&mut *FRAME.lock().unwrap_or_else(|e| e.into_inner())) +} + +/// Draws, mesh dispatches and dispatches recorded but not run on the host +/// (no host pipeline) since the last call. +pub(crate) fn take_dropped() -> u64 { + DROPPED.swap(0, Ordering::Relaxed) +} +/// A root SRV's dynamic slot in a list, and the host copy it shows. +type RootSlot = (u32, Option>); + +/// Buffer views of the heap whose slot showed another host buffer than +/// the copy the pass brought up to date for them, since the start +/// (diagnostics; for the memory line). It stays 0 while the pass and the +/// slots agree; with `LEONIDA_VIEW_EXTENT=0` it counts the views that were +/// read stale. +#[cfg(feature = "diagnostics")] +pub(crate) static HEAP_VIEWS_ELSEWHERE: AtomicU64 = AtomicU64::new(0); +/// Passes over the view heap's buffer views for shaders that pick them by +/// index ([`State::heap_buffers`]), and the microseconds they took. +pub(crate) static HEAP_BUFFER_PASSES: AtomicU64 = AtomicU64::new(0); +pub(crate) static HEAP_BUFFER_MICROS: AtomicU64 = AtomicU64::new(0); +/// Of [`HEAP_BUFFER_MICROS`], the microseconds of the pass over textures +/// picked by index that runs inside it (`heap_textures`), and the buffer +/// slots the pass over buffer views looked at; since the last frame line. +pub(crate) static HEAP_PASS_PARTS: [AtomicU64; 2] = [const { AtomicU64::new(0) }; 2]; +/// Textures brought up to date for shaders that pick them by index +/// ([`State::heap_textures`]), the bytes of their memory, and the slots +/// still waiting. +pub(crate) static HEAP_TEXTURES: AtomicU64 = AtomicU64::new(0); +pub(crate) static HEAP_TEXTURE_BYTES: AtomicU64 = AtomicU64::new(0); +pub(crate) static HEAP_TEXTURES_WAITING: AtomicU64 = AtomicU64::new(0); +/// Passes that made no texture because the card had no room +/// (`crate::resource::room`), for the memory line. +pub(crate) static HEAP_TEXTURES_FULL: AtomicU64 = AtomicU64::new(0); + +/// Frames after a whole upload of a texture picked by index at which its +/// memory is looked at again, each counted from the look before. +const RECHECK_FRAMES: [u64; 5] = [4, 12, 40, 120, 400]; + +/// Looks at uploaded textures picked by index that found the memory as it +/// was, and that found it changed (uploaded again), since the start. +pub(crate) static HEAP_TEXTURES_RECHECKED: [AtomicU64; 2] = [AtomicU64::new(0), AtomicU64::new(0)]; + +/// Uploads of textures already on the card made while it had no room for +/// new ones, since the start. +pub(crate) static HEAP_TEXTURES_REUPLOADED_FULL: AtomicU64 = AtomicU64::new(0); + +/// Whether a pass over the textures picked by index on a full card holds +/// back the slots that need a new host copy (`LEONIDA_FULL_CARD_PASS=0`: +/// no, as before: they stay due, each pass looks at the same ones again +/// and stops at the 257th). Held back, such a slot is looked at again +/// after about four seconds or as soon as the card has room, and the pass +/// goes on to the slots behind it: the ones whose host copy exists and +/// only wants bringing up to date, and the ones whose memory went (letting +/// their host copies go is what makes room). What is uploaded while the +/// card has room is the same either way. +fn full_card_pass() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("LEONIDA_FULL_CARD_PASS").is_none_or(|v| v != "0")) +} + +/// Whether a texture that has its host copy is still brought up to date +/// while the card has no room for new ones (`LEONIDA_REUPLOAD_WHEN_FULL=0`: +/// no). +fn reupload_when_full() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("LEONIDA_REUPLOAD_WHEN_FULL").is_none_or(|v| v != "0")) +} + +/// Whether textures picked by index are looked at again after their upload +/// (`LEONIDA_HEAP_RECHECK=0`: no). +fn heap_recheck() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("LEONIDA_HEAP_RECHECK").is_none_or(|v| v != "0")) +} +/// Times a placed texture's slot was passed over because its memory is not +/// mapped. +pub(crate) static HEAP_TEXTURES_AWAY: AtomicU64 = AtomicU64::new(0); +/// Slots the pass found up to date already: their texture is uploaded by +/// the draws that read it through a table (it has a staging buffer). +pub(crate) static HEAP_TEXTURES_TABLED: AtomicU64 = AtomicU64::new(0); +/// The queue of textures picked by index at the last pass +/// (`TextureQueue::census`): slots in it, due, waiting for their memory, +/// uploaded in part, and the frames the oldest due one has waited. +pub(crate) static HEAP_TEXTURES_QUEUE: [AtomicU64; 5] = [const { AtomicU64::new(0) }; 5]; +/// Since the start: looks at a slot uploaded in part that found no more of +/// its memory mapped; uploads of textures not all mapped; and of those, +/// the ones whose first page was not there (asked by the first page alone, +/// as before, they counted as not there at all). +pub(crate) static HEAP_TEXTURES_PARTLY: [AtomicU64; 3] = [const { AtomicU64::new(0) }; 3]; +static DROPPED: AtomicU64 = AtomicU64::new(0); + +/// Marks the last traced draw as not run on the host. +#[cfg(feature = "diagnostics")] +fn dropped(pipeline: usize) { + crate::pipeline::note_drop(pipeline as This); + if let Some(last) = FRAME.lock().unwrap_or_else(|e| e.into_inner()).last_mut() { + last.push_str(" DROPPED"); + } +} + +/// Dispatches run on the host so far. +static DISPATCHED: AtomicU64 = AtomicU64::new(0); + +pub(crate) fn dispatched() -> u64 { + DISPATCHED.load(Ordering::Relaxed) +} + +/// The host address of a root view: its buffer's host copy, or for a +/// constant buffer not 256-byte aligned there (the console needs 16) a +/// copy in upload memory. +/// shortcut: a root view has no size; constant buffers are taken as 64 KiB +/// (cut at their buffer's end), other views as all that is left of their +/// buffer. (They were taken as 1 MiB: 1,452 of the 2,021 mesh vertex +/// streams of a cutscene frame reach further, and what lay past the first +/// megabyte was never brought up to date - meshes without bodies, exploded +/// triangles. `LEONIDA_ROOT_VIEW_MB` sets a limit again.) +fn root_view(list: &HostList, address: u64, srv: bool) -> Option { + static LIMIT: std::sync::OnceLock = std::sync::OnceLock::new(); + let limit = *LIMIT.get_or_init(|| { + std::env::var("LEONIDA_ROOT_VIEW_MB") + .ok() + .and_then(|v| v.parse::().ok()) + .map_or(u64::MAX, |mb| mb << 20) + }); + let shadow = crate::shadow::find(address, 1)?; + let len = shadow + .left(address) + .min(if srv { limit } else { 1 << 16 }); + let gpu = shadow.gpu(address); + if srv || gpu % 256 == 0 { + shadow.refresh(list, address, len); + return Some(gpu); + } + let (gpu, to) = list.scratch(len)?; + list.defer_fill(to, address as *const u8, len as usize); + Some(gpu) +} + +macro_rules! once { + ($($arg:tt)*) => {{ + static ONCE: std::sync::Once = std::sync::Once::new(); + ONCE.call_once(|| tracing::warn!($($arg)*)); + }}; +} + +fn set(roots: &mut Vec, slot: u32, root: Root) { + let slot = slot as usize; + if roots.len() <= slot { + roots.resize(slot + 1, Root::None); + } + roots[slot] = root; +} + +impl State { + pub(crate) fn reset(&mut self, pipeline: This) { + *self = State::default(); + self.pipeline = pipeline as usize; + } + + /// The title's topology; console-only ones become host lists (see + /// [`crate::primitive`]). + pub(crate) fn set_topology(&mut self, list: &HostList, topology: u32) { + self.topology = topology; + self.topology_set = true; + let host = match topology { + RECTANGLES => 4, + TRIANGLE_FAN | LINE_LOOP | QUADS | QUAD_STRIP => { + once!(topology, "console topology drawn as a triangle list"); + 4 + } + t => t, + }; + // SAFETY: an open list. + unsafe { + list.list + .IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY(host as i32)) + }; + } + + pub(crate) fn set_pipeline(&mut self, pipeline: This) { + self.pipeline = pipeline as usize; + } + + pub(crate) fn set_heaps(&mut self, heaps: &[This]) { + self.heaps = [0; 2]; + for &h in heaps { + if !h.is_null() { + let samplers = crate::descriptor::heap(h).samplers(); + self.heaps[usize::from(samplers)] = h as usize; + } + } + } + + fn roots(&mut self, compute: bool) -> &mut Vec { + if compute { + &mut self.compute + } else { + &mut self.graphics + } + } + + pub(crate) fn set_table(&mut self, compute: bool, slot: u32, handle: u64) { + set(self.roots(compute), slot, Root::Table(handle)); + } + + pub(crate) fn set_view(&mut self, compute: bool, slot: u32, address: u64) { + set(self.roots(compute), slot, Root::View(address)); + } + + pub(crate) fn set_constants(&mut self, compute: bool, slot: u32, values: &[u32], offset: u32) { + let roots = self.roots(compute); + let s = slot as usize; + if !matches!(roots.get(s), Some(Root::Constants(_))) { + set(roots, slot, Root::Constants(Vec::new())); + } + if let Root::Constants(c) = &mut roots[s] { + let end = offset as usize + values.len(); + if c.len() < end { + c.resize(end, 0); + } + c[offset as usize..end].copy_from_slice(values); + } + } + + pub(crate) fn set_vertex_buffers(&mut self, start: u32, views: &[VertexView]) { + for (i, v) in views.iter().enumerate() { + if let Some(slot) = self.vertex.get_mut(start as usize + i) { + *slot = *v; + } + } + } + + pub(crate) fn clear_vertex_buffers(&mut self, start: u32, count: u32) { + for slot in self.vertex.iter_mut().skip(start as usize).take(count as usize) { + *slot = VertexView::default(); + } + } + + pub(crate) fn set_index_buffer(&mut self, view: Option<&IndexView>) { + self.index = view.copied().unwrap_or_default(); + } + + /// Render targets and depth, set on the host list at once. + pub(crate) fn set_targets(&mut self, list: &HostList, handles: &[u64], depth: u64) { + let Some(host) = crate::host::host() else { + return; + }; + self.target_handles.clear(); + self.target_handles.extend_from_slice(handles); + self.depth_handle = depth; + self.targets_set = true; + self.targets.clear(); + let mut rtvs = Vec::new(); + for &h in handles { + let Some(record) = crate::descriptor::rtv_record(h) else { + once!( + handle = format_args!("{h:#x}"), + "render target without a recorded view" + ); + continue; + }; + let Some(texture) = crate::resource::host_resource(record.resource) else { + // A typed null view (or a target without a host copy) still + // takes its slot: left out, the next live target would move + // into it and the pixel shader's outputs reach the wrong + // targets. + // shortcut: a view without a description or a format has no + // null view to stand for it and is left out, as before. + let null = record + .desc() + .filter(|d| d.Format.0 != 0 && d.ViewDimension.0 != 0); + if let Some(desc) = null { + rtvs.push(host.rtv(None, Some(&desc))); + } + continue; + }; + self.targets.push(record.resource as usize); + #[cfg(feature = "diagnostics")] + crate::capture::note_target(record.resource); + rtvs.push(host.rtv(Some(texture), record.desc().as_ref())); + } + self.depth = 0; + self.depth_state = DEPTH_WRITE; + let dsv = crate::descriptor::dsv_record(depth).and_then(|record| { + let texture = crate::resource::host_resource(record.resource)?; + self.depth = record.resource as usize; + self.depth_state = depth_state(texture, record.depth_desc().as_ref()); + if crate::resource::depth_and_unordered(record.resource) { + crate::resource::DEPTH_UNORDERED[1].fetch_add(1, Ordering::Relaxed); + } + #[cfg(feature = "diagnostics")] + crate::capture::note_target(record.resource); + Some(host.dsv(texture, record.depth_desc().as_ref())) + }); + // SAFETY: an open list; the views were just made. + unsafe { + list.list.OMSetRenderTargets( + rtvs.len() as u32, + (!rtvs.is_empty()).then_some(rtvs.as_ptr()), + false, + dsv.as_ref().map(std::ptr::from_ref), + ) + }; + } + + /// Viewports, scissors, the blend factor and the stencil reference: set + /// on the host list at once, and kept for [`State::replay`]. + pub(crate) fn set_viewports(&mut self, list: &HostList, viewports: &[D3D12_VIEWPORT]) { + self.viewports.clear(); + self.viewports.extend_from_slice(viewports); + crate::draw::viewports(list, viewports); + } + + pub(crate) fn set_scissors(&mut self, list: &HostList, rects: &[RECT]) { + self.scissors.clear(); + self.scissors.extend_from_slice(rects); + if scissor_test() { + // The experiment: every rectangle the title sets is widened to + // the largest target there is, so nothing is cut by one. What + // the listing shows (`op_text`) stays the title's own. + let full = RECT { + left: 0, + top: 0, + right: 16384, + bottom: 16384, + }; + crate::draw::scissors(list, &vec![full; rects.len()]); + return; + } + crate::draw::scissors(list, rects); + } + + pub(crate) fn set_blend_factor(&mut self, list: &HostList, factor: Option<&[f32; 4]>) { + self.blend = factor.copied(); + crate::draw::blend_factor(list, factor); + } + + pub(crate) fn set_stencil_ref(&mut self, list: &HostList, reference: u32) { + self.stencil = Some(reference); + crate::draw::stencil_ref(list, reference); + } + + pub(crate) fn set_depth_bounds(&mut self, list: &HostList, min: f32, max: f32) { + self.depth_bounds = Some([min, max]); + crate::draw::depth_bounds(list, min, max); + } + + /// `list` is a new host list that continues the title's list (it was + /// cut at a wait for a memory value, `crate::list::cut`): a new host + /// list has nothing set, so what the title set so far is set again. + /// The pipeline, the root signatures and the heaps are set by the next + /// draw or dispatch (`bind`, which is told here that the host list has + /// none); root arguments, vertex and index buffers are set by every + /// draw anyway. The dynamic descriptor slots and the tables made in + /// them stay: the parts before the cut have not run yet, and they are + /// given back when the title's list is reset. + /// shortcut: the render target views are made again from the handles' + /// descriptors as they are now, not as they were when the title set + /// the targets (a descriptor rewritten in between names another view). + pub(crate) fn replay(&mut self, list: &HostList) { + self.host_pipeline = 0; + self.host_roots = [0; 2]; + self.host_heaps = [0; 2]; + if self.topology_set { + self.set_topology(list, self.topology); + } + if self.targets_set { + let handles = std::mem::take(&mut self.target_handles); + self.set_targets(list, &handles, self.depth_handle); + } + if !self.viewports.is_empty() { + crate::draw::viewports(list, &self.viewports); + } + if !self.scissors.is_empty() { + let rects = std::mem::take(&mut self.scissors); + self.set_scissors(list, &rects); + } + if let Some(factor) = self.blend { + crate::draw::blend_factor(list, Some(&factor)); + } + if let Some(reference) = self.stencil { + crate::draw::stencil_ref(list, reference); + } + if let Some([min, max]) = self.depth_bounds { + crate::draw::depth_bounds(list, min, max); + } + } + + /// The user-data value of a root argument, as translated shaders read + /// it: a table's byte offset in its heap, a constant's value. + fn user_value(&self, compute: bool, slot: u8, root: RootType, dword: u32) -> u32 { + match (self.roots_ref(compute).get(usize::from(slot)), root) { + (Some(Root::Table(handle)), RootType::Table) => match self.heap_of(*handle) { + Some(heap) => (handle - heap.start) as u32, + None => { + once!( + handle = format_args!("{handle:#x}"), + "descriptor table outside the bound heaps" + ); + 0 + } + }, + (Some(Root::Constants(c)), RootType::Constants) => { + c.get(dword as usize).copied().unwrap_or(0) + } + // The host's own ([`Self::host_word`]): no root argument. + (_, RootType::Other(_)) => 0, + _ => { + once!( + slot, + ?root, + "a shader reads a root argument the title did not set" + ); + 0 + } + } + } + + /// A user-data dword the host computes for a translated shader + /// (`leonida_shader::emit::USER_MEMORY_BASE`, `USER_VIEW_ADDRESS`). + fn host_word( + &self, + compute: bool, + kind: u32, + slot: u8, + dword: u32, + memory: Option<&crate::memory::Ready>, + ) -> u32 { + use leonida_shader::emit::{USER_MEMORY_BASE, USER_VIEW_ADDRESS, USER_VIEW_BIAS}; + if kind == USER_MEMORY_BASE { + return memory.map_or(0, |m| m.base); + } + if kind == USER_VIEW_BIAS { + // The view begins on 16 bytes of the copy the address finds + // (`root_uav`, `root_srv_table`). + // shortcut: found again here, not taken from the list's slot. + return match self.roots_ref(compute).get(usize::from(slot)) { + Some(&Root::View(address)) => crate::shadow::find(address, 1).map_or(0, |s| { + // SAFETY: a live buffer. + let base = unsafe { s.buffer.GetGPUVirtualAddress() }; + ((s.gpu(address) - base) & 15) as u32 + }), + _ => 0, + }; + } + if kind != USER_VIEW_ADDRESS && kind != USER_VIEW_ADDRESS + 1 { + once!(kind, "a shader reads a host value this build does not know"); + return 0; + } + // The title address of the buffer view at that dword of the table. + let address = match self.roots_ref(compute).get(usize::from(slot)) { + Some(&Root::Table(table)) => crate::descriptor::view(table + u64::from(dword) * 4) + .and_then(|view| crate::descriptor::host::buffer_range(&view)) + .map_or(0, |range| range.0), + _ => 0, + }; + if address == 0 { + once!(slot, dword, "a shader takes the address of a buffer view that is not there: it reads 0"); + } + if kind == USER_VIEW_ADDRESS { + address as u32 + } else { + (address >> 32) as u32 + } + } + + /// For a shader that reads title memory by address + /// ([`crate::memory`]): its directory, fault notes and view slots, + /// with the pages of the root views the list has set made ready. + fn memory_ready(&self, list: &HostList, compute: bool, writes: bool) -> Option { + let heap = match self.heaps[0] { + 0 => None, + h => crate::descriptor::heap(h as This).host(), + }?; + let (mut addresses, mut constants) = (Vec::new(), Vec::new()); + for root in self.roots_ref(compute) { + match root { + Root::View(address) => addresses.push(*address), + Root::Constants(values) => constants.extend_from_slice(values), + _ => {} + } + } + crate::memory::ready(list, heap, &addresses, &constants, writes) + } + + /// The bound heap holding `handle`. + fn heap_of(&self, handle: u64) -> Option<&'static crate::descriptor::Heap> { + self.heaps + .iter() + .filter(|&&h| h != 0) + .map(|&h| crate::descriptor::heap(h as This)) + .find(|h| h.index(handle).is_some()) + } + + /// Brings the host list up to date for a draw; false if the draw cannot + /// run on the host. + fn prepare(&mut self, list: &HostList, indexed: bool) -> bool { + self.prepare_for(list, indexed, false) + } + + /// As [`State::prepare`], for draws (`mesh` false) or mesh dispatches. + fn prepare_for(&mut self, list: &HostList, indexed: bool, mesh: bool) -> bool { + #[cfg(feature = "diagnostics")] + if crate::pipeline::is_skipped(self.pipeline as This) { + return false; + } + let Some(p) = crate::pipeline::host_pipeline(self.pipeline as This) else { + return false; + }; + if p.compute || p.mesh != mesh { + once!(mesh, "a draw or mesh dispatch with another kind of pipeline"); + return false; + } + if p.rects && self.topology != RECTANGLES { + // Its geometry stage would turn each triangle into a rectangle. + once!("a rectangle pipeline drawn with another topology"); + } + if !self.bind(list, p, false) { + return false; + } + let l = &list.list; + // Vertex buffers the input layout reads. + let mut views = [D3D12_VERTEX_BUFFER_VIEW::default(); 32]; + let mut count = 0; + for (slot, (view, &v)) in views.iter_mut().zip(&self.vertex).enumerate() { + if p.slots & 1 << slot == 0 { + continue; + } + count = slot + 1; + if v.address == 0 || v.size == 0 { + continue; + } + let Some(shadow) = crate::shadow::find_any(v.address, u64::from(v.size)) else { + continue; + }; + shadow.refresh(list, v.address, u64::from(v.size)); + *view = D3D12_VERTEX_BUFFER_VIEW { + BufferLocation: shadow.gpu(v.address), + SizeInBytes: v.size, + StrideInBytes: v.stride, + }; + } + // SAFETY: an open list; the views name live host buffers. + unsafe { + if count > 0 { + l.IASetVertexBuffers(0, Some(&views[..count])); + } + } + if indexed { + let v = self.index; + let Some(shadow) = crate::shadow::find_any(v.address, u64::from(v.size)) else { + return false; + }; + shadow.refresh(list, v.address, u64::from(v.size)); + let view = D3D12_INDEX_BUFFER_VIEW { + BufferLocation: shadow.gpu(v.address), + SizeInBytes: v.size, + Format: DXGI_FORMAT(v.format as i32), + }; + // SAFETY: an open list; the view names a live host buffer. + unsafe { l.IASetIndexBuffer(Some(&view)) }; + } + const RENDER_TARGET: u32 = 0x4; + for &t in &self.targets { + crate::list::ensure_state(list, t as This, RENDER_TARGET); + } + if self.depth != 0 { + // A depth texture shaders also write: what they wrote, first. + list.twin_use(self.depth as This, false, true); + // A view that writes neither plane keeps the texture readable: + // the depth read state, together with the shader read states + // if this draw's shaders read the same texture (the write state + // put it out of the state those views need, and a move to it + // and back for every such draw). + let state = if self.depth_state == DEPTH_READ { + let (tested, read) = TESTED_DEPTH.get(); + if read && tested == self.depth { + DEPTH_READ | SHADER_RESOURCE + } else { + DEPTH_READ + } + } else { + DEPTH_WRITE + }; + crate::list::ensure_state(list, self.depth as This, state); + } + true + } + + /// A descriptor a shader reads through a table: its host slot made if + /// it changed, constant data copied, textures made readable. + /// What draws and dispatches share: heaps, our root signature, the + /// pipeline, and per stage the user data, root views and the + /// descriptors its tables hold. + /// False if the draw or dispatch must not run: a root SRV it reads + /// could not be given a view. + pub(crate) fn bind(&mut self, list: &HostList, p: &HostPipeline, compute: bool) -> bool { + let l = &list.list; + // Textures picked by index, before anything asks for them. + self.early_textures(list, p, compute); + if crate::host::walls_trace() { + self.walls_census(p, compute); + } + // Heaps first: a root signature with directly indexed heaps must be + // set after them. + if self.host_heaps != self.heaps { + let heaps: Vec> = self + .heaps + .iter() + .filter(|&&h| h != 0) + .filter_map(|&h| crate::descriptor::heap(h as This).host()) + .map(|h| Some(h.heap.clone())) + .collect(); + heaps.iter().flatten().for_each(|h| list.keep(h)); + // SAFETY: an open list and shader-visible heaps. + unsafe { l.SetDescriptorHeaps(&heaps) }; + self.host_heaps = self.heaps; + self.host_roots = [0; 2]; + } + // The depth target a draw only tests, for the views of it that the + // draw's shaders read (`readable`). + let tested = if !compute && self.depth_state == DEPTH_READ { + self.depth + } else { + 0 + }; + TESTED_DEPTH.set((tested, false)); + let root = p.root.as_raw() as usize; + if self.host_roots[usize::from(compute)] != root { + // SAFETY: an open list and a live root signature. + unsafe { + if compute { + l.SetComputeRootSignature(&p.root); + } else { + l.SetGraphicsRootSignature(&p.root); + } + } + self.host_roots[usize::from(compute)] = root; + } + // By host object: a title pipeline released and another made at its + // address is another host pipeline (the list keeps the old one). + if self.host_pipeline != p.pso.as_raw() as usize { + // SAFETY: an open list and a live pipeline. + unsafe { l.SetPipelineState(&p.pso) }; + self.host_pipeline = p.pso.as_raw() as usize; + list.used_pipeline(&p.name); + // The title may release the pipeline before it submits the list. + list.keep(&p.pso); + list.keep(&p.root); + } + for stage in &p.stages { + let t = stage.translated(); + STORES.set(t.stores); + let made = self.tables(list, &t.used, &t.host.root_indexed_views, compute); + STORES.set(true); + if made.iter().any(|m| m.1 == u32::MAX) { + once!("a draw whose descriptor table found no free slots is dropped"); + return false; + } + // What the shader stores through root views and raw addresses is + // copied back into title memory afterwards. + let writes = (t.stores || !write_skip()) + && !crate::pipeline::builder_quarantined(self.pipeline as This); + // Title memory by address: what the shader finds it by. + let memory = if t.host.root_srvs.contains(&leonida_shader::emit::SLOT_MEMORY) { + let Some(ready) = self.memory_ready(list, compute, writes) else { + once!("a shader that reads title memory by address without a view heap to hold its views: the draw is dropped"); + return false; + }; + Some(ready) + } else { + None + }; + if let Some((param, dwords)) = stage.user_data { + let mut values = vec![0u32; dwords as usize]; + for u in &t.host.user_data { + if let RootType::Other(kind) = u.root { + values[u.index as usize] = + self.host_word(compute, kind, u.slot, u.dword, memory.as_ref()); + continue; + } + let fresh = made + .iter() + .find(|m| m.0 == u.slot && u.root == RootType::Table); + values[u.index as usize] = match fresh { + Some(&(_, offset)) => offset, + None => self.user_value(compute, u.slot, u.root, u.dword), + }; + } + // SAFETY: an open list; `values` covers the parameter. + unsafe { + if compute { + l.SetComputeRoot32BitConstants(param, dwords, values.as_ptr().cast(), 0); + } else { + l.SetGraphicsRoot32BitConstants(param, dwords, values.as_ptr().cast(), 0); + } + } + } + for (views, srv) in [(&stage.root_cbvs, false), (&stage.root_srvs, true)] { + for &(slot, param) in views { + if srv && slot == leonida_shader::emit::SLOT_MEMORY { + // Ours: the directory of title memory by address. + if let Some(m) = &memory { + // SAFETY: an open list; the directory lives as + // long as the process and the list holds it. + unsafe { + if compute { + l.SetComputeRootShaderResourceView(param, m.directory); + } else { + l.SetGraphicsRootShaderResourceView(param, m.directory); + } + } + } + continue; + } + if srv && slot == leonida_shader::emit::SLOT_STRIDES { + // Ours, not the title's: the shader picks buffers + // from the view heap by an index it computes. + match self.heap_buffers(list) { + // SAFETY: an open list; the table lives as long + // as the heap the list holds. + Some(gpu) => unsafe { + if compute { + l.SetComputeRootShaderResourceView(param, gpu); + } else { + l.SetGraphicsRootShaderResourceView(param, gpu); + } + }, + None => once!("a shader picks buffers from a view heap that is not set"), + } + continue; + } + let tabled = srv && crate::pipeline::host::bounded_root_srvs(); + let Some(&Root::View(address)) = self.roots_ref(compute).get(usize::from(slot)) + else { + once!(slot, "a shader reads a root view the title did not set"); + // A table left unset is undefined: a null view. + if tabled && !self.root_srv_table(list, None, param, compute, false) { + return false; + } + continue; + }; + // The shader adds the bytes a raw view begins early by. + let biased = srv + && t.host.user_data.iter().any(|u| { + u.slot == slot + && u.root == RootType::Other(leonida_shader::emit::USER_VIEW_BIAS) + }); + if tabled { + if !self.root_srv_table(list, Some(address), param, compute, biased) { + return false; + } + continue; + } + let Some(mut gpu) = root_view(list, address, srv) else { + continue; + }; + if biased { + gpu -= u64::from(self.host_word( + compute, + leonida_shader::emit::USER_VIEW_BIAS, + slot, + 0, + None, + )); + } + // SAFETY: an open list; the address is in live memory. + unsafe { + match (compute, srv) { + (false, false) => l.SetGraphicsRootConstantBufferView(param, gpu), + (false, true) => l.SetGraphicsRootShaderResourceView(param, gpu), + (true, false) => l.SetComputeRootConstantBufferView(param, gpu), + (true, true) => l.SetComputeRootShaderResourceView(param, gpu), + } + } + } + } + for &(slot, param) in &stage.root_uavs { + if slot == leonida_shader::emit::SLOT_FAULTS { + // Ours: where shaders note the pages they found empty. + if let Some(m) = &memory { + // SAFETY: an open list; the buffer lives as long as + // the process and the list holds it. + unsafe { + if compute { + l.SetComputeRootUnorderedAccessView(param, m.faults); + } else { + l.SetGraphicsRootUnorderedAccessView(param, m.faults); + } + } + } + continue; + } + let address = match self.roots_ref(compute).get(usize::from(slot)) { + Some(&Root::View(address)) => Some(address), + _ => { + once!(slot, "a shader writes through a root view the title did not set"); + None + } + }; + if !self.root_uav(list, address, param, compute, writes) { + return false; + } + } + } + // Depth textures it writes through unordered access: their colour + // twins hold what they lack from here on. + list.twins_written(); + true + } + + /// Binds a root UAV: a raw unordered access view of the title buffer's + /// host copy from `address` on, as a one-view table (a null view + /// without an address, without a host copy shaders can write, or at an + /// address not on 16 bytes), or as a root descriptor with + /// `LEONIDA_ROOT_SRV_DIRECT=1` (the dispatch is dropped then if there + /// is nothing to bind). With `writes`, what the shader stored is copied + /// back into title memory when the list has run. False if the draw + /// must be dropped. + /// shortcut: a root view has no size: the view, the refresh and the + /// copy back cover all that is left of the title's buffer + /// (`LEONIDA_ROOT_UAV_MB` sets a limit for all three). + fn root_uav( + &mut self, + list: &HostList, + address: Option, + param: u32, + compute: bool, + writes: bool, + ) -> bool { + const UNORDERED: i32 = D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS.0; + static LIMIT: std::sync::OnceLock = std::sync::OnceLock::new(); + let limit = *LIMIT.get_or_init(|| { + std::env::var("LEONIDA_ROOT_UAV_MB") + .ok() + .and_then(|v| v.parse::().ok()) + .map_or(u64::MAX, |mb| mb << 20) + }); + let find = |a: u64| { + let s = crate::shadow::find(a, 1)?; + // SAFETY: a live buffer. + let flags = unsafe { s.buffer.GetDesc() }.Flags; + if flags.0 & UNORDERED == 0 { + once!("a root UAV of a buffer whose host copy shaders cannot write"); + return None; + } + Some(s) + }; + let ready = |a: u64, s: &std::sync::Arc| { + let len = s.left(a).min(limit); + s.refresh(list, a, len); + if writes { + s.gpu_writes(list, a, len); + } + }; + if !crate::pipeline::host::bounded_root_srvs() { + let Some((a, s)) = address.and_then(|a| Some((a, find(a)?))) else { + once!("a root UAV with nothing to bind: the draw is dropped"); + return false; + }; + ready(a, &s); + // From the 16 bytes below: the shader adds the rest. + // SAFETY: a live buffer. + let base = unsafe { s.buffer.GetGPUVirtualAddress() }; + let gpu = base + ((s.gpu(a) - base) & !15); + // SAFETY: an open list; the address is in a live buffer. + unsafe { + if compute { + list.list.SetComputeRootUnorderedAccessView(param, gpu); + } else { + list.list.SetGraphicsRootUnorderedAccessView(param, gpu); + } + } + return true; + } + let heap = match self.heaps[0] { + 0 => None, + h => Some(crate::descriptor::heap(h as This)), + }; + let Some((heap, host)) = heap.and_then(|h| Some((h, h.host()?))) else { + once!("a root UAV without a bound view heap: the draw is dropped"); + return false; + }; + let key = (std::ptr::from_ref(heap) as usize, address.unwrap_or(0)); + let (index, shadow) = match self.root_uav_slots.get(&key) { + Some((index, shadow)) => (*index, address.zip(shadow.clone())), + None => { + let shadow = address.and_then(|a| find(a).map(|s| (a, s))); + let Some(index) = host.dynamic(1) else { + return false; + }; + self.dynamic.push((key.0, index, 1)); + if let Some((a, s)) = &shadow { + // SAFETY: a live buffer. + let base = unsafe { s.buffer.GetGPUVirtualAddress() }; + let offset = s.gpu(*a) - base; + // Raw views start on 16 bytes: from the 16 bytes + // below, and the shader adds the rest to its offsets + // (`leonida_shader::emit::USER_VIEW_BIAS`). (An address + // not on 16 bytes got a null view at first: the + // builder's counters are at such addresses.) + let bias = offset & 15; + host.raw_uav_at(index, &s.buffer, offset - bias, s.left(*a).min(limit) + bias); + } + if shadow.is_none() { + host.null_raw_uav_at(index); + } + self.root_uav_slots + .insert(key, (index, shadow.as_ref().map(|(_, s)| s.clone()))); + (index, shadow) + } + }; + if let Some((a, s)) = &shadow { + ready(*a, s); + } + let handle = host.gpu_handle(index); + // SAFETY: an open list; the slot is in the bound view heap. + unsafe { + if compute { + list.list.SetComputeRootDescriptorTable(param, handle); + } else { + list.list.SetGraphicsRootDescriptorTable(param, handle); + } + } + true + } + + /// Binds a root SRV as a one-view table + /// ([`crate::pipeline::host::bounded_root_srvs`]): a raw view of the + /// title buffer's host copy from `address` to the copy's end, or a null + /// view (no address, no host copy, or an address not on 16 bytes). One + /// dynamic slot per address per list, given back with the list's + /// others. False if no slot could be had or no view heap is bound. + fn root_srv_table( + &mut self, + list: &HostList, + address: Option, + param: u32, + compute: bool, + biased: bool, + ) -> bool { + let heap = match self.heaps[0] { + 0 => None, + h => Some(crate::descriptor::heap(h as This)), + }; + let Some((heap, host)) = heap.and_then(|h| Some((h, h.host()?))) else { + once!("a root SRV without a bound view heap: the draw is dropped"); + return false; + }; + // A view that begins early is another view than one that does not + // (title addresses stay below bit 63). + let key = ( + std::ptr::from_ref(heap) as usize, + address.unwrap_or(0) | u64::from(biased) << 63, + ); + let (index, shadow) = match self.root_srv_slots.get(&key) { + Some((index, shadow)) => (*index, address.zip(shadow.clone())), + None => { + let shadow = address.and_then(|a| crate::shadow::find(a, 1).map(|s| (a, s))); + let Some(index) = host.dynamic(1) else { + return false; + }; + self.dynamic.push((key.0, index, 1)); + self.root_srv_slots + .insert(key, (index, shadow.as_ref().map(|(_, s)| s.clone()))); + match &shadow { + Some((a, s)) => { + // SAFETY: a live buffer. + let base = unsafe { s.buffer.GetGPUVirtualAddress() }; + let offset = s.gpu(*a) - base; + if biased { + // From the 16 bytes below; the shader adds the + // rest (`leonida_shader::emit::USER_VIEW_BIAS`). + let bias = offset & 15; + host.raw_at(index, &s.buffer, offset - bias, s.left(*a) + bias); + } else if offset.is_multiple_of(16) { + host.raw_at(index, &s.buffer, offset, s.left(*a)); + } else { + // Raw views start on 16 bytes; one from the + // aligned start would shift every read. + once!( + address = format_args!("{a:#x}"), + "a root SRV not on 16 bytes reads zeros" + ); + host.null_raw_at(index); + } + } + None => host.null_raw_at(index), + } + (index, shadow) + } + }; + // As for root descriptors (`root_view`): all that is left of the + // buffer is brought up to date. The first 1 MiB only left what lay + // past it stale (most mesh vertex streams reach further). + if let Some((a, s)) = &shadow { + s.refresh(list, *a, s.left(*a)); + } + let handle = host.gpu_handle(index); + // SAFETY: an open list; the slot is in the bound view heap. + unsafe { + if compute { + list.list.SetComputeRootDescriptorTable(param, handle); + } else { + list.list.SetGraphicsRootDescriptorTable(param, handle); + } + } + true + } + + /// For a shader that picks buffers from the view heap by an index it + /// computes (SM 6.6 dynamic resources): the GPU address of the heap's + /// table of element strides, with every buffer view of the heap given + /// its host slot and its memory brought up to date when `list` is + /// submitted. Tables tell us which views a draw reads; nothing tells + /// us which of the heap's a computed index names, so all of them are + /// made ready, once per list. + /// shortcut: the buffers are read, not written: what such a shader + /// writes through a picked unordered access view stays in the host + /// copy. A list refreshes them where it first runs such a shader; + /// title writes recorded later in the same list are not seen. + fn heap_buffers(&self, list: &HostList) -> Option { + let heap = self + .heaps + .iter() + .filter(|&&h| h != 0) + .map(|&h| crate::descriptor::heap(h as This)) + .find(|h| !h.samplers())?; + let host = heap.host()?; + let gpu = host.strides_gpu()?; + // One key per list, as textures have: no title resource is there. + const ONCE: usize = usize::MAX - 0x5e; + if !list.first_use(ONCE) { + return Some(gpu); + } + // The list may outlive the title's heap object, which owns the table. + if let Some(buffer) = host.strides_buffer() { + list.keep(buffer); + } + // The pass itself once per frame: per list it ran up to 51 times a + // frame over 81,000 views and 4,100 host copies, 18 s of every + // frame (2026-11-24, run 11). + // shortcut: what the title writes into such buffers between lists + // of one frame is seen a frame late. + static FRAME: AtomicU64 = AtomicU64::new(u64::MAX); + let frame = crate::frame::current(); + if FRAME.swap(frame, Ordering::Relaxed) == frame { + return Some(gpu); + } + let started = std::time::Instant::now(); + // Per host heap: the host copy and range each slot's buffer view + // reads, kept from pass to pass. Only the slots written since the + // last pass are looked at again (83,000 slots a pass otherwise, 0.1 s + // at best); all of them every 16 passes, because a view of a + // released resource goes stale without a write, and a slot written + // before its memory had a host copy is only made then. + type Ranges = std::collections::HashMap, u64, u64)>; + static RANGES: std::sync::Mutex>> = + std::sync::Mutex::new(None); + let mut kept = RANGES.lock().unwrap_or_else(|e| e.into_inner()); + let (passes, ranges) = kept + .get_or_insert_with(Default::default) + .entry(std::ptr::from_ref(host) as usize) + .or_insert_with(|| (0, Ranges::new())); + let changed = host.buffer_changes(); + let slots = if *passes % 16 == 0 { + ranges.clear(); + host.buffer_slots() + } else { + changed + }; + *passes += 1; + // Whether the device was there before the pass: a view that removes + // it is named below. + static GONE: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); + let mut alive = !GONE.load(Ordering::Relaxed) && crate::descriptor::host::device_removed().is_none(); + HEAP_PASS_PARTS[1].fetch_add(slots.len() as u64, Ordering::Relaxed); + for (n, &index) in slots.iter().enumerate() { + ranges.remove(&index); + let Some(handle) = heap.handle(index) else { + continue; + }; + let Some(view) = host.mirror(index, handle, true) else { + continue; + }; + // Every 64 views while the device lives (a cheap query). + if alive + && n % 64 == 63 + && let Some(why) = crate::descriptor::host::device_removed() + { + alive = false; + GONE.store(true, Ordering::Relaxed); + let last: Vec = slots[n - 63..=n] + .iter() + .filter_map(|&i| crate::descriptor::view(heap.handle(i)?).map(|v| format!("{i}: {v:?}"))) + .map(|s| s.chars().take(200).collect()) + .collect(); + tracing::error!(why, slot = index, "the host device went while buffer views of the heap were made; one of: {last:#?}"); + crate::host::log_removal_context(); + } + // The copy the slot shows (`buffer_copy`), not the one the + // view's range alone would find. + let Some((shadow, address, len)) = crate::descriptor::host::buffer_copy(&view) else { + continue; + }; + #[cfg(feature = "diagnostics")] + if host.shows(index, &shadow.buffer) == Some(false) { + HEAP_VIEWS_ELSEWHERE.fetch_add(1, Ordering::Relaxed); + } + ranges.insert(index, (shadow, address, address + len)); + } + let views = ranges.len() as u32; + // Per host copy, the span its picked views cover. + let mut spans: std::collections::HashMap, u64, u64)> = + std::collections::HashMap::new(); + for (shadow, from, to) in ranges.values() { + let key = std::sync::Arc::as_ptr(shadow) as usize; + let span = spans.entry(key).or_insert_with(|| (shadow.clone(), *from, *to)); + span.1 = span.1.min(*from); + span.2 = span.2.max(*to); + } + drop(kept); + let bytes: u64 = spans.values().map(|s| s.2 - s.1).sum(); + // Memory that is not write-watched is copied whole by every refresh. + // It was once refreshed only every 120 frames (unmapped pages read + // one by one cost 14 GB a frame in run 11, before they were + // remembered): streamed geometry then drew from stale buffers, and + // the garbage ended runs (the card stopped answering 14-90 frames + // into the opening cutscene; with every frame it ran on). The pass + // costs some 30 ms a frame this way. + static WHOLE: std::sync::Mutex>> = std::sync::Mutex::new(None); + let mut whole = WHOLE.lock().unwrap_or_else(|e| e.into_inner()); + let whole = whole.get_or_insert_with(Default::default); + for (shadow, from, to) in spans.values() { + if shadow.unwatched() { + // By the copy's number: a copy made where one let go was + // (`shadow::let_go_idle`) has never been refreshed. + let key = shadow.id() as usize; + // `LEONIDA_UNWATCHED_FRAMES` sets the interval (1: every frame). + static EVERY: std::sync::OnceLock = std::sync::OnceLock::new(); + let every = *EVERY.get_or_init(|| { + std::env::var("LEONIDA_UNWATCHED_FRAMES") + .ok() + .and_then(|v| v.parse().ok()) + .unwrap_or(1) + }); + match whole.get(&key) { + Some(&last) if frame < last + every => continue, + _ => { + whole.insert(key, frame); + } + } + } + shadow.refresh(list, *from, to - from); + } + let textures_began = std::time::Instant::now(); + self.heap_textures(list, heap, host); + HEAP_PASS_PARTS[0].fetch_add(textures_began.elapsed().as_micros() as u64, Ordering::Relaxed); + HEAP_BUFFER_PASSES.fetch_add(1, Ordering::Relaxed); + HEAP_BUFFER_MICROS.fetch_add(started.elapsed().as_micros() as u64, Ordering::Relaxed); + static LOGGED: AtomicU64 = AtomicU64::new(0); + // The first pass and every growth of the set by half. + let seen = LOGGED.load(Ordering::Relaxed); + if u64::from(views) > seen + seen / 2 { + LOGGED.store(u64::from(views), Ordering::Relaxed); + tracing::info!( + slots = slots.len(), + views, + copies = spans.len(), + mb = bytes >> 20, + ms = started.elapsed().as_millis(), + "buffer views of the heap made ready for shaders that pick them by index" + ); + } + Some(gpu) + } + + /// Runs the pass that uploads textures picked by index + /// ([`State::heap_textures`]) where nothing has asked for it yet + /// ([`early_budgets`]): once a frame for a few milliseconds, at the + /// frame's first draw with a view heap set, and with a larger budget + /// of its own before every draw whose pixel shader is one of the + /// title's bake programs. The uploads are recorded into `list` ahead + /// of the draw being bound, as the world's pass records them. + fn early_textures(&self, list: &HostList, p: &HostPipeline, compute: bool) { + let (early_ms, bake_ms) = early_budgets(); + if compute || (early_ms == 0 && bake_ms == 0) { + return; + } + let bake = bake_ms > 0 + && p.stages.iter().any(|s| BAKE_PIXEL_SHADERS.contains(&s.shader.hash.as_str())); + static FRAME: AtomicU64 = AtomicU64::new(u64::MAX); + // The milliseconds this frame's bake draws have taken so far: a + // frame has several, and together they get `bake_ms`. + static BAKED_MS: AtomicU64 = AtomicU64::new(0); + let frame = crate::frame::current(); + let first = FRAME.swap(frame, Ordering::Relaxed) != frame; + if first { + BAKED_MS.store(0, Ordering::Relaxed); + } + let left = bake_ms.saturating_sub(BAKED_MS.load(Ordering::Relaxed)); + let budget = if bake && left > 0 { + // What a bake may read must be there now: up to 2 GiB. + (left, 2 << 30) + } else if first && early_ms > 0 { + (early_ms, 64 << 20) + } else { + return; + }; + let Some(heap) = self + .heaps + .iter() + .filter(|&&h| h != 0) + .map(|&h| crate::descriptor::heap(h as This)) + .find(|h| !h.samplers()) + else { + return; + }; + let Some(host) = heap.host() else { + return; + }; + let bake = bake && left > 0; + let n = EARLY_TEXTURE_PASSES[usize::from(bake)].fetch_add(1, Ordering::Relaxed) + 1; + if bake && n.is_power_of_two() { + let [slots, due, ..] = HEAP_TEXTURES_QUEUE.each_ref().map(|c| c.load(Ordering::Relaxed)); + tracing::info!( + frame, + bakes = n, + queued_at_the_last_pass = slots, + due_at_the_last_pass = due, + uploaded_so_far = HEAP_TEXTURES.load(Ordering::Relaxed), + "a draw of the title's decoration bake: textures picked by index are uploaded first (LEONIDA_BAKE_TEXTURES_MS=0: not)" + ); + } + let began = std::time::Instant::now(); + PASS_BUDGET.set(Some(budget)); + self.heap_textures(list, heap, host); + PASS_BUDGET.set(None); + if bake { + BAKED_MS.fetch_add(began.elapsed().as_millis() as u64, Ordering::Relaxed); + } + } + + /// The queue's side of the card accounting line + /// (`crate::resource::card_accounting`, which says what the line + /// holds): the slots that are due, by what their texture has on the + /// card. Off unless `LEONIDA_CARD_ACCOUNTING=1`; then at the first pass + /// that finds the card without room, and every five seconds after it. + /// Nothing is made, uploaded or counted as used here. For 18,000 due + /// slots: 18,000 looks at a title slot and at the texture it views, a + /// lock each, some milliseconds of the thread that records the frame. + fn card_accounting( + heap: &crate::descriptor::Heap, + host: &crate::descriptor::host::HostHeap, + frame: u64, + room: bool, + ) { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + if !*ON.get_or_init(|| std::env::var_os("LEONIDA_CARD_ACCOUNTING").is_some_and(|v| v == "1")) { + return; + } + // When the next line is due (0: none yet, the card has had room). + static NEXT: AtomicU64 = AtomicU64::new(0); + let now = crate::host::now_ms().max(1); + let next = NEXT.load(Ordering::Relaxed); + // (With levels on demand the card may never be without room: the + // lines then start with the first texture made that way.) + let by_level = crate::tiles::STATS[4].load(Ordering::Relaxed) > 0; + let due_now = if next == 0 { !room || by_level } else { now >= next }; + if !due_now || NEXT.compare_exchange(next, now + 5000, Ordering::Relaxed, Ordering::Relaxed).is_err() { + return; + } + // Due slots; of them uploaded before; of them viewing nothing the + // title fills; and the textures (each once) whose host copy is + // alive, with their bytes on the card. + let mut due = [0u64; 5]; + // Textures (each once) that never had a host copy, and ones whose + // host copy was let go: where their memory is, and its bytes. + let (mut never, mut gone) = (Vec::new(), Vec::new()); + let mut seen = std::collections::BTreeSet::new(); + for (index, uploaded) in host.texture_slots_all_due(frame) { + due[0] += 1; + due[1] += u64::from(uploaded); + let state = match heap.handle(index).and_then(crate::descriptor::view) { + Some(View::Placed(false, resource, desc)) if resource[0] != 1 => { + let address = u64::from(desc[10]) | u64::from(desc[11]) << 32; + match crate::resource::placed_known(address, &resource) { + Some(texture) => crate::resource::copy_state(texture), + // No title texture was made for it: the pass never + // got as far as making one. + None => Some((0, crate::resource::placed_bytes(&resource).unwrap_or(0), address)), + } + } + Some(View::Shader(object, _)) if crate::resource::title_fills(object as This) => { + crate::resource::copy_state(object as This) + } + _ => None, + }; + let Some((state, bytes, memory)) = state else { + due[2] += 1; + continue; + }; + if !seen.insert(memory) { + continue; + } + match state { + 2 => { + due[3] += 1; + due[4] += bytes; + } + 1 => gone.push((memory, bytes)), + _ => never.push((memory, bytes)), + } + } + crate::resource::card_accounting(room, due, never, gone); + } + + /// The texture side of [`State::heap_buffers`]: textures the title fills + /// itself (streamed pages, layout-library copies) whose views sit in the + /// view heap are created (placed textures have no host texture until + /// something reads them) and uploaded, as a table read would do, for + /// shaders that pick them by a computed index. Within a budget of bytes + /// per frame and in all; the rest waits for later lists and frames. + /// The most recently written slots first (`TextureQueue::due`); slots + /// draws read through tables are not in the queue. + /// shortcut: uploaded once, and again only when the title rewrites the + /// slot. A placed texture not all mapped yet is uploaded with what is + /// there and looked at again (1, 2, 4, ... frames later, at most about + /// a second): uploaded again when more of it is mapped. Pages mapped + /// in place of others, and contents changed with no descriptor write, + /// are missed (hook the page-mapping events for those). + /// `LEONIDA_HEAP_TEXTURES=0` turns it off. + fn heap_textures( + &self, + list: &HostList, + heap: &crate::descriptor::Heap, + host: &crate::descriptor::host::HostHeap, + ) { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + if !*ON.get_or_init(|| std::env::var_os("LEONIDA_HEAP_TEXTURES").is_none_or(|v| v != "0")) { + return; + } + /// Bytes of texture memory staged per frame. + // `LEONIDA_TEXTURE_STAGE_MB` raises it: a backlog of tens of thousands of + // textures (a scene's first minutes) then drains in fewer frames. + static PER_FRAME_MB: std::sync::OnceLock = std::sync::OnceLock::new(); + let per_frame: u64 = *PER_FRAME_MB.get_or_init(|| { + std::env::var("LEONIDA_TEXTURE_STAGE_MB").ok().and_then(|v| v.trim().parse().ok()).unwrap_or(192) + }) << 20; + static FRAME: AtomicU64 = AtomicU64::new(u64::MAX); + static SPENT: AtomicU64 = AtomicU64::new(0); + let frame = crate::frame::current(); + if FRAME.swap(frame, Ordering::Relaxed) != frame { + SPENT.store(0, Ordering::Relaxed); + } + // No more of them are made while the card has no room + // (`resource::room`): by what is alive now, not by what was ever + // staged (4 GB in all, after which later textures stayed empty for + // the run). The ones nothing names any more are let go, which + // makes room again: so the slots are still looked at (the pass + // returned here, and a slot whose texture had been streamed out + // kept its host copy for as long as the card was full). + let mut room = crate::resource::room(); + // Bytes uploaded by this pass since the card was last asked + // whether it has room: asked again every 32 MiB (a pass may upload + // 192 MB and more, and one asking a pass let the queue run some + // 400 MB past its line while the world loaded: run 193). + let mut since_asked = 0u64; + if !room { + HEAP_TEXTURES_FULL.fetch_add(1, Ordering::Relaxed); + once!("textures picked by index: the card has no room for more; they wait"); + } + let mut refused = 0; + // Room again: the slots held back while the card was full are due + // now (`full_card_pass`). + if room { + host.texture_slots_room(frame); + } + // Slots whose texture's memory the runtime mapped, unmapped or + // wrote since the last pass are due again. + host.texture_slots_remapped(frame); + // Levels on demand: the slots of textures whose first level with + // memory changed since the last pass are made again from it. + host.texture_views_remade(); + // And with room, the textures whose upload left a held level + // without the card's memory are uploaded again. + if room { + host.texture_slots_waiting(frame); + } + let (due, census) = host.texture_slots_due(frame, 4096); + HEAP_TEXTURES_WAITING.store(census[0], Ordering::Relaxed); + for (count, now) in HEAP_TEXTURES_QUEUE.iter().zip(census) { + count.store(now, Ordering::Relaxed); + } + // Where the card's memory is, and what the due slots would need + // (`LEONIDA_CARD_ACCOUNTING=1`; a line when the card first has no + // room, and every five seconds after it). + Self::card_accounting(heap, host, frame, room); + // The frames in about four seconds, between 16 and 256: how long a + // slot with nothing to upload waits at most for its next look. In + // frames alone it was 120: four minutes at the opening cutscene's + // half a frame per second, while the title streams by the clock. + // (About a second before the runtime told of the memory it maps: + // the looks are now only for what that does not tell.) + static PASSED: AtomicU64 = AtomicU64::new(0); + let now = crate::host::now_ms(); + let took = now.saturating_sub(PASSED.swap(now, Ordering::Relaxed)).max(1); + let most = (4000 / took).clamp(16, 256); + // What a table entry of a texture a shader samples says. + let sampled = UsedResource { + kind: ResourceType::Srv, + root: RootType::Table, + table_offset_dwords: 0, + lower_bound: 0, + stride: 0, + dwords: 8, + user_data: 0, + slot: 0, + }; + // Also within a time per pass: the pass runs on a thread that + // records the frame, and making and staging 192 MB of textures took + // 1.6-2.2 s of each of the world's first twenty frames (run 20). + // The rest waits for the next frames, as it does past the bytes. + static SPAN_MS: std::sync::OnceLock = std::sync::OnceLock::new(); + let span = std::time::Duration::from_millis(*SPAN_MS.get_or_init(|| { + std::env::var("LEONIDA_TEXTURE_STAGE_MS").ok().and_then(|v| v.trim().parse().ok()).unwrap_or(250) + })); + // A backlog (a scene's first minutes: 22,000 slots due, 2-3 minutes of black + // surfaces at 192 MB a frame) gets three times the bytes and the time until it + // drains; `LEONIDA_TEXTURE_CATCHUP=0` keeps the plain budget. + static CATCHUP: std::sync::OnceLock = std::sync::OnceLock::new(); + let catchup = *CATCHUP.get_or_init(|| std::env::var_os("LEONIDA_TEXTURE_CATCHUP").is_none_or(|v| v != "0")); + let (per_frame, span) = if catchup && due.len() >= 1024 { (per_frame * 3, span * 3) } else { (per_frame, span) }; + // A run made early (`State::early_textures`) has a budget of its + // own: its bytes on top of what the frame has spent so far. + // (Not `most`: that is the longest wait between looks, used below.) + let (span, bytes_at_most) = match PASS_BUDGET.get() { + Some((ms, bytes)) => { + (std::time::Duration::from_millis(ms), SPENT.load(Ordering::Relaxed).saturating_add(bytes)) + } + None => (span, per_frame), + }; + let began = std::time::Instant::now(); + for (index, write) in due { + if SPENT.load(Ordering::Relaxed) >= bytes_at_most || began.elapsed() > span { + break; + } + // A placed texture whose memory is not mapped (not streamed in + // yet, or streamed out again: the heap keeps tens of thousands + // of such views) gets no host texture; looked at again soon (a + // title writes a texture's view before its pages are mapped, + // and the pass runs early in a frame). One of which some is + // mapped (a texture streaming in: its smaller mips lie at the + // start of its memory and arrive first) is uploaded with what + // is there, and again when more is. (It was uploaded again + // every 120 frames, changed or not; and asked by its first + // page alone, one whose first page is the one missing counted + // as not there.) + // A slot uploaded whole is looked at again a few times + // (`RECHECK_FRAMES`): the title writes a texture's view, and + // may fill the texture's memory itself only afterwards, with + // no descriptor write and nothing from the runtime to tell of + // it. The host copy then kept what the memory held at the + // first look for the rest of the run. The look reads 48 KiB; + // only a changed texture is uploaded again. + // `LEONIDA_HEAP_RECHECK=0`: uploaded once, as before. + if let Some((at, len, print, looks, uploaded)) = host.texture_slot_checked(index) { + if crate::texture::fingerprint(at, len) == print { + HEAP_TEXTURES_RECHECKED[0].fetch_add(1, Ordering::Relaxed); + match RECHECK_FRAMES.get(usize::from(looks) + 1) { + Some(wait) => { + host.texture_slot_recheck(index, write, frame + wait, (at, len), print, looks + 1, uploaded) + } + None => host.texture_slot_done(index, write, None), + } + continue; + } + let n = HEAP_TEXTURES_RECHECKED[1].fetch_add(1, Ordering::Relaxed); + if n < 200 || n.is_multiple_of(1000) { + tracing::warn!( + slot = index, + address = format_args!("{at:#x}"), + bytes = len, + frames_after_upload = frame.saturating_sub(uploaded), + looks, + changed = n + 1, + "a texture picked by index changed after its upload with nothing to tell of it: uploaded again" + ); + } + } + let mut partly = None; + if let Some(View::Placed(false, resource, desc)) = heap.handle(index).and_then(crate::descriptor::view) { + let address = u64::from(desc[10]) | u64::from(desc[11]) << 32; + let len = crate::resource::placed_bytes(&resource).unwrap_or(1); + let mapped = crate::texture::mapped_bytes(address as *const u8, len as usize); + if mapped == 0 { + HEAP_TEXTURES_AWAY.fetch_add(1, Ordering::Relaxed); + // Streamed out: what the slot showed is let go. + host.texture_slot_gone(index); + host.texture_slot_later(index, write, frame, most); + continue; + } + if mapped < len { + if mapped <= host.texture_slot_mapped(index) { + HEAP_TEXTURES_PARTLY[0].fetch_add(1, Ordering::Relaxed); + host.texture_slot_later(index, write, frame, most); + continue; + } + if !crate::texture::committed(address as *const u8, 1) { + HEAP_TEXTURES_PARTLY[2].fetch_add(1, Ordering::Relaxed); + } + partly = Some(mapped); + } + } + // A texture object the host renders to or writes holds the + // host's own contents: nothing to bring up to date, and this + // pass is no use of it (its host copy is made when something + // uses it, and its slots then: `descriptor::make_waiting`). + if let Some(View::Shader(object, _)) = heap.handle(index).and_then(crate::descriptor::view) + && crate::resource::buffer_bytes(object as This).is_none() + && !crate::resource::title_fills(object as This) + { + host.texture_slot_done(index, write, None); + continue; + } + // From here on a host texture is made: not without room. The + // slot stays due. + // Not so a slot already made from this very view: its host + // texture exists, and uploading it again takes none of the + // card's memory. It was refused all the same, so a texture the + // title filled after its first upload kept its empty host copy + // from the moment the card reached the line, which is the first + // world frame in eight launches of nine: the same slots were + // found changed again at every pass and never uploaded (run + // 179: 33,000 such findings), and the main character's face + // had its colour only in the launches that entered the world + // under the line. `LEONIDA_REUPLOAD_WHEN_FULL=0`: refused, as + // before. + if !room { + let has_its_texture = reupload_when_full() + && heap.handle(index).is_some_and(|handle| host.texture_slot_made_from(index, handle)); + if !has_its_texture { + refused += 1; + if full_card_pass() { + // Held back for the frames of about four seconds + // (`most`), or until the card has room; the pass + // goes on, within a count that bounds one pass. + host.texture_slot_held(index, write, frame + most); + if refused > 1024 { + break; + } + } else if refused > 256 { + break; + } + continue; + } + let n = HEAP_TEXTURES_REUPLOADED_FULL.fetch_add(1, Ordering::Relaxed) + 1; + if n == 1 || n.is_multiple_of(500) { + tracing::info!( + so_far = n, + slot = index, + "a texture already on the card is brought up to date although the card has no room for new ones" + ); + } + } + let view = heap.handle(index).and_then(|handle| host.mirror(index, handle, true)); + let placed = view.as_ref().and_then(crate::descriptor::host::placed_texture); + let resource = match placed.as_ref().or(view.as_ref()) { + Some(&View::Shader(resource, _)) => resource as This, + _ => { + host.texture_slot_done(index, write, None); + continue; + } + }; + let title_fills = crate::resource::host_resource(resource).is_some_and(crate::texture::title_written); + if !title_fills { + // a render target, a depth or unordered access texture: the host's own + host.texture_slot_done(index, write, None); + continue; + } + // A texture that has a staging buffer now is one draws read + // through a table: they upload it, and check it at every + // submission that samples it. + let tabled = crate::texture::is_staged(resource); + if let Some(view) = &view { + readable(list, sampled.kind, view); + } + // A texture view the host refuses removes the device: name it. + static GONE: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); + if !GONE.load(Ordering::Relaxed) + && let Some(why) = crate::descriptor::host::device_removed() + { + GONE.store(true, Ordering::Relaxed); + let text: String = format!("{view:?}").chars().take(300).collect(); + tracing::error!(why, slot = index, "the host device went while textures picked by index were made ready; last: {text}"); + crate::host::log_removal_context(); + return; + } + let (bytes, whole) = crate::texture::staged(resource).unwrap_or((0, true)); + // Not all of it there: looked at again next frame, and from + // then on as a slot with nothing new (a placed texture: until + // more of it is mapped; a texture object at an address the + // title mapped: again in 120 frames, as before). + let again = match partly { + Some(mapped) => Some((frame + 1, mapped)), + None => (!whole).then_some((frame + 120, 0)), + }; + if again.is_some() { + HEAP_TEXTURES_PARTLY[1].fetch_add(1, Ordering::Relaxed); + } + if tabled { + // Nothing was staged here, so nothing is counted or spent, + // and the staging buffer stays: taking it away made the + // next draw that reads the texture through a table stage, + // detile and upload all of it once more. + HEAP_TEXTURES_TABLED.fetch_add(1, Ordering::Relaxed); + host.texture_slot_done(index, write, again); + continue; + } + // Uploaded: the list holds the staging buffer until it has run; + // a table read, or the next look at a texture not all mapped + // yet, makes it anew. (Kept for those until now: every partly + // streamed texture of the heap held a staging buffer of its full + // size for good.) + let memory = if again.is_none() && heap_recheck() { + crate::texture::staged_memory(resource) + } else { + None + }; + crate::texture::unstage(resource); + SPENT.fetch_add(bytes, Ordering::Relaxed); + since_asked += bytes; + if room && since_asked >= 32 << 20 { + since_asked = 0; + room = crate::resource::room(); + } + HEAP_TEXTURE_BYTES.fetch_add(bytes, Ordering::Relaxed); + HEAP_TEXTURES.fetch_add(1, Ordering::Relaxed); + match memory { + // Whole and uploaded: looked at again (see above). + Some((at, len)) => { + let print = crate::texture::fingerprint(at, len); + host.texture_slot_recheck(index, write, frame + RECHECK_FRAMES[0], (at, len), print, 0, frame); + } + None => host.texture_slot_done(index, write, again), + } + } + } + + /// For the frame listing, after a dropped dispatch's line: its group + /// counts and the compute root arguments it was recorded with (root + /// constants as hex dwords, root views with the title buffer they + /// point into). A program that does not translate has no bindings to + /// list; these say which memory it would have read and written (the + /// ray-tracing structure builder passes its buffers this way). + #[cfg(feature = "diagnostics")] + fn list_dropped_roots(&self, groups: [u32; 3]) { + crate::capture::op(0, || { + use std::fmt::Write; + let [x, y, z] = groups; + let mut text = format!(" its roots ({x}x{y}x{z}):"); + for (slot, root) in self.compute.iter().enumerate() { + match root { + Root::None => {} + Root::Table(a) => { + let _ = write!(text, " {slot}=table {a:#x}"); + } + Root::Constants(v) => { + let _ = write!(text, " {slot}=constants {:x?}", &v[..v.len().min(48)]); + } + Root::View(a) => { + let _ = write!(text, " {slot}=view {a:#x}"); + match crate::shadow::extent(*a) { + Some((start, len)) => { + let _ = write!(text, " in buffer {start:#x}+{len:#x}"); + } + None => text.push_str(" in no buffer"), + } + } + } + } + text + }); + } + + /// Whether the shaders of the pipeline bound now can store to buffers + /// (or the pipeline is not known): a draw with them may write the + /// arguments of draws after it, which ends a list's gathering + /// (`crate::indirect::gather`). The same test keeps such a draw out of + /// a window ([`windows`]). + fn may_store(&self) -> bool { + crate::pipeline::host_pipeline(self.pipeline as This).is_none_or(|p| p.stages.iter().any(|stage| stage.translated().stores)) + } + + /// Runs a dispatch on the host. + pub(crate) fn dispatch(&mut self, list: &HostList, x: u32, y: u32, z: u32) { + // It may write the arguments a window holds clamped. + self.window = None; + list.gather_close(); + #[cfg(feature = "diagnostics")] + if crate::pipeline::is_skipped(self.pipeline as This) { + DROPPED.fetch_add(1, Ordering::Relaxed); + crate::pipeline::note_drop(self.pipeline as This); + return; + } + // A program that walks ray-tracing structures nothing has built. + if crate::pipeline::walk_held(self.pipeline as This) { + #[cfg(feature = "diagnostics")] + crate::pipeline::note_why("a walk of ray-tracing structures that are not built (LEONIDA_BVH_HOLD=1)".to_owned()); + return; + } + // The ray-tracing structure builder's stages run all or none. + if crate::pipeline::is_builder(self.pipeline as This) && !crate::pipeline::builder_runs() { + DROPPED.fetch_add(1, Ordering::Relaxed); + #[cfg(feature = "diagnostics")] + { + crate::pipeline::note_why("a stage of the ray-tracing structure builder, which is off".to_owned()); + self.list_dropped_roots([x, y, z]); + } + return; + } + let Some(p) = crate::pipeline::host_pipeline(self.pipeline as This) else { + once!( + pipeline = format_args!("{:#x}", self.pipeline), + "a dispatch without a host pipeline dropped" + ); + DROPPED.fetch_add(1, Ordering::Relaxed); + #[cfg(feature = "diagnostics")] + { + crate::pipeline::note_drop(self.pipeline as This); + self.list_dropped_roots([x, y, z]); + } + return; + }; + if !p.compute { + once!("a dispatch with a graphics pipeline"); + return; + } + if !self.bind(list, p, true) { + DROPPED.fetch_add(1, Ordering::Relaxed); + // A stage of the structure builder that cannot be bound is a + // dropped stage: the others stop too. + if crate::pipeline::is_builder(self.pipeline as This) { + crate::pipeline::builder_off("one of its dispatches could not be bound"); + } + return; + } + #[cfg(feature = "diagnostics")] + list.note_op(|| self.op_text(format!("dispatch {x}x{y}x{z}"), true)); + // SAFETY: an open list with everything set. + unsafe { list.list.Dispatch(x, y, z) }; + DISPATCHED.fetch_add(1, Ordering::Relaxed); + } + + /// What a draw or dispatch runs, for the device-removed report + /// (diagnostics): the pipeline, then per stage the user data it gets + /// (with the view at that heap index, if one is), the host addresses + /// of its root views and the views its tables name. + #[cfg(feature = "diagnostics")] + fn op_text(&self, kind: String, compute: bool) -> String { + use std::fmt::Write; + let Some(p) = crate::pipeline::host_pipeline(self.pipeline as This) else { + return kind; + }; + let mut text = format!("{kind} {}", p.name); + // What it draws into (a dispatch writes through its views below). + if !compute { + let described = |t: usize| { + crate::resource::host_made(t as This).map(|r| { + // SAFETY: a live resource. + let d = unsafe { r.GetDesc() }; + format!("{t:#x} {}x{} f{}", d.Width, d.Height, d.Format.0) + }) + }; + let targets: Vec = self.targets.iter().filter_map(|&t| described(t)).collect(); + let _ = write!(text, " targets {targets:?} depth {:?} state [{}]", described(self.depth), p.state); + // The title's scissor and viewport at this draw (the first of + // each): the title draws what it sees through a + // portal (a window, from inside a room) under the portal's + // rectangle, and the listing did not say which draws those are. + if let Some(r) = self.scissors.first() { + let _ = write!(text, " scissor [{} {} {} {}]", r.left, r.top, r.right, r.bottom); + } + if let Some(v) = self.viewports.first() { + let _ = write!( + text, + " viewport [{} {} {} {} depth {}..{}]", + v.TopLeftX, v.TopLeftY, v.Width, v.Height, v.MinDepth, v.MaxDepth + ); + } + } + let views = (self.heaps[0] != 0) + .then(|| crate::descriptor::heap(self.heaps[0] as This).host()) + .flatten(); + for stage in &p.stages { + let t = stage.translated(); + let _ = write!(text, " | {}:", stage.shader.hash); + for u in &t.host.user_data { + let v = match u.root { + RootType::Other(kind) => self.host_word(compute, kind, u.slot, u.dword, None), + _ => self.user_value(compute, u.slot, u.root, u.dword), + }; + let _ = write!(text, " u{}={v:#x}", u.index); + let index = if u.root == RootType::Table { v / 32 } else { v }; + if let Some(slot) = views.and_then(|h| h.describe_slot(index)) { + let _ = write!(text, " [heap {index}: {slot}]"); + } + } + for &(slot, _) in stage.root_cbvs.iter().chain(&stage.root_srvs).chain(&stage.root_uavs) { + if let Some(Root::View(address)) = self.roots_ref(compute).get(usize::from(slot)) { + let host = crate::shadow::find(*address, 1) + .map(|s| (s.gpu(*address), s.left(*address))); + let _ = write!(text, " root{slot}={address:#x} host {host:#x?}"); + } + } + } + let _ = write!(text, " tables {:?}", self.reads(compute)); + if !compute && !list_slots().is_empty() { + text.push_str(&self.slots_text()); + } + text + } + + /// For the frame listing, after a draw whose shader `LEONIDA_LIST_SLOTS` + /// names: the heap slots it will pick textures from by index, and what + /// the title and the host hold there (one `~slot` line each), with the + /// words they were read from (`~raw` lines, to decode offline what is + /// not decoded here). + /// + /// Where the slots are, for the title's character shaders + /// (`PS_DeferredPedTexturedNC`, from their native code): in the small + /// buffers and constants of the draw's own table (every word of those + /// that names a texture view gets a line); in the material record, at + /// the byte offset the draw's constants (table 1, dword 56) hold at + /// 0x1c, of the buffer at table 0, dword 160; and in the record at the + /// byte offset the second root constant holds of the buffer at table 0, + /// dword 688. A word that is a small number by chance and names a + /// texture gets a line too. + #[cfg(feature = "diagnostics")] + fn slots_text(&self) -> String { + use std::fmt::Write; + const MATERIALS: u32 = 160; + const GLOBAL: u32 = 688; + const DRAW_CONSTANTS: u32 = 56; + let wanted = list_slots(); + let Some(p) = crate::pipeline::host_pipeline(self.pipeline as This) else { + return String::new(); + }; + let Some(stage) = p.stages.iter().find(|s| wanted.iter().any(|w| s.shader.hash.starts_with(w.as_str()))) + else { + return String::new(); + }; + let Some(heap) = self + .heaps + .iter() + .filter(|&&h| h != 0) + .map(|&h| crate::descriptor::heap(h as This)) + .find(|h| !h.samplers()) + else { + return String::new(); + }; + let t = stage.translated(); + let mut text = String::new(); + let entry = |slot: u8, dwords: u32| -> Option { + let Some(Root::Table(table)) = self.roots_ref(false).get(usize::from(slot)) else { + return None; + }; + crate::descriptor::view(table + u64::from(dwords) * 4) + }; + let mut material = None; + for u in t.used.iter().filter(|u| u.root == RootType::Table && u.kind != ResourceType::Sampler) { + let label = format!("s{}+{}", u.slot, u.table_offset_dwords); + let Some(view) = entry(u.slot, u.table_offset_dwords) else { + let _ = write!(text, "\n ~table {label} no view"); + continue; + }; + let range = match &view { + View::Constant(address, size) => Some((*address, u64::from(*size))), + other => crate::descriptor::host::buffer_range(other), + }; + match range { + // A small buffer or constants: its words. + Some((address, len)) if len <= 2048 => { + Self::slot_words(&mut text, heap, &label, address, len as usize); + if u.slot == 1 && u.table_offset_dwords == DRAW_CONSTANTS && len >= 0x20 { + let mut word = [0u8; 4]; + if crate::host::read_into((address + 0x1c) as *const u8, &mut word) { + material = Some(u32::from_le_bytes(word)); + } + } + } + Some(_) => {} + // A texture read through the table: the title slot it sits in. + None => { + let Some(Root::Table(table)) = self.roots_ref(false).get(usize::from(u.slot)) else { + continue; + }; + match heap.index(table + u64::from(u.table_offset_dwords) * 4) { + Some(index) => text.push_str(&Self::slot_line(heap, &format!("table:{label}"), 0, index)), + None => { + let _ = write!(text, "\n ~table {label} title=[{}]", view_state(Some(&view))); + } + } + } + } + } + let uses = |slot: u8, dwords: u32| { + t.used.iter().any(|u| u.root == RootType::Table && u.slot == slot && u.table_offset_dwords == dwords) + }; + if let Some(at) = material + && uses(0, MATERIALS) + && let Some((base, len)) = entry(0, MATERIALS).as_ref().and_then(crate::descriptor::host::buffer_range) + { + let at = u64::from(at); + let _ = write!(text, "\n ~material record at {at:#x} of the buffer at {base:#x} bytes {len}"); + if at + 64 <= len { + Self::slot_words(&mut text, heap, "M", base + at, 64); + } + if at + 1936 + 512 <= len { + Self::slot_words(&mut text, heap, "M+1936", base + at + 1936, 512); + } + } + if uses(0, GLOBAL) + && let Some(slot) = t.used.iter().find(|u| u.root == RootType::Constants).map(|u| u.slot) + && let Some(Root::Constants(words)) = self.roots_ref(false).get(usize::from(slot)) + && let Some(&at) = words.get(1) + && let Some((base, len)) = entry(0, GLOBAL).as_ref().and_then(crate::descriptor::host::buffer_range) + { + let at = u64::from(at); + let _ = write!(text, "\n ~root constants {words:08x?}: record at {at:#x} of the buffer at {base:#x} bytes {len}"); + if at + 64 <= len { + Self::slot_words(&mut text, heap, "G", base + at, 64); + } + } + text + } + + /// Up to 512 bytes of title memory at `address` as hex words (a `~raw` + /// line), and a `~slot` line for every word of them that names a + /// texture view in `heap`. + #[cfg(feature = "diagnostics")] + fn slot_words(text: &mut String, heap: &crate::descriptor::Heap, label: &str, address: u64, len: usize) { + use std::fmt::Write; + let mut bytes = vec![0u8; len.min(512) & !3]; + if bytes.is_empty() || !crate::host::read_into(address as *const u8, &mut bytes) { + let _ = write!(text, "\n ~raw {label} at {address:#x} bytes {len}: unreadable"); + return; + } + let words: Vec = + bytes.chunks_exact(4).map(|w| u32::from_le_bytes([w[0], w[1], w[2], w[3]])).collect(); + let _ = write!(text, "\n ~raw {label} at {address:#x} bytes {len}:"); + for w in &words { + let _ = write!(text, " {w:08x}"); + } + for (i, &index) in words.iter().enumerate() { + let names = index != 0 + && heap + .handle(index) + .and_then(crate::descriptor::view) + .as_ref() + .is_some_and(crate::descriptor::host::is_texture_view); + if names { + text.push_str(&Self::slot_line(heap, label, i * 4, index)); + } + } + } + + /// One `~slot` line: where the slot number was read (`from`, byte + /// `at`), what the title's heap holds in slot `index` with the state + /// of that texture ([`view_state`]), what the host slot was made from, + /// and what the queue of textures picked by index knows of it. + #[cfg(feature = "diagnostics")] + fn slot_line(heap: &crate::descriptor::Heap, from: &str, at: usize, index: u32) -> String { + let title = heap.handle(index).and_then(crate::descriptor::view); + let host: String = heap + .host() + .and_then(|h| h.describe_slot(index)) + .unwrap_or_else(|| "none".into()) + .chars() + .take(90) + .collect(); + let queue = match heap.host() { + Some(h) => h.texture_slot_state(index, crate::frame::current()), + None => "no host heap".into(), + }; + format!( + "\n ~slot from={from}+{at:#x} slot={index} title=[{}] host=[{host}] queue=[{queue}]", + view_state(title.as_ref()) + ) + } + + /// A mesh draw under `LEONIDA_MESH_TEST=scissor` rasterises one pixel: + /// the scissors before it (`on`), the title's after it. + fn mesh_scissor(&self, list: &HostList, on: bool) { + if mesh_test() != 2 { + return; + } + if on { + let one = RECT { left: 0, top: 0, right: 1, bottom: 1 }; + crate::draw::scissors(list, &vec![one; self.scissors.len().max(1)]); + } else if !self.scissors.is_empty() { + crate::draw::scissors(list, &self.scissors); + } + } + + /// Runs a mesh dispatch of `x` groups on the host (the title's mesh + /// programs are one-dimensional). + pub(crate) fn dispatch_mesh(&mut self, list: &HostList, x: u32) { + self.window = None; + if self.may_store() { + list.gather_close(); + } + #[cfg(feature = "diagnostics")] + self.trace("mesh", x, 0); + let ran = mesh_test() != 1 + && mesh_kept(self.pipeline) + && self.prepare_for(list, false, true) + && match list.list.cast::() { + Ok(l6) => { + #[cfg(feature = "diagnostics")] + list.note_op(|| self.op_text(format!("mesh {x}"), false)); + self.mesh_scissor(list, true); + // SAFETY: an open list with everything set. + unsafe { l6.DispatchMesh(x, 1, 1) }; + self.mesh_scissor(list, false); + DRAWN.fetch_add(1, Ordering::Relaxed); + true + } + Err(_) => false, + }; + if !ran { + DROPPED.fetch_add(1, Ordering::Relaxed); + #[cfg(feature = "diagnostics")] + dropped(self.pipeline); + } + } + + /// The walls trace (`crate::host::walls_trace`): one log line per + /// frame with the draws of its main pass (four or more colour targets) + /// by scissor rectangle, and how often each of the title's culling + /// programs was dispatched. The title clips what it draws + /// through a window or door to that opening's rectangle while it holds + /// the camera to be in a room (run 182, frame 1529: 1,386 draws under + /// `531 0 1789 1337`); in a launch without the room's walls the same + /// shot has no such rectangle (run 187, frame 1414). The line shows + /// the frame in which that changes. + fn walls_census(&self, p: &HostPipeline, compute: bool) { + const CULL: [(&str, &str); 9] = [ + ("55679a0547649d0b", "tree"), + ("89d08e561897d4e5", "tree_imposter"), + ("9209777e8face9dd", "grass"), + ("17af15c4015cb4b6", "prop"), + ("fdd56d97a806bcca", "prop_nocull"), + ("42f717f1b4d18e94", "simple"), + ("1c4b3c0547e3e6fa", "slod"), + ("9146291b38ea9ce1", "meshlet_args"), + ("42683eebec081520", "depth_pyramid_cpu_occlusion"), + ]; + type Census = (u64, std::collections::BTreeMap<[i32; 4], u32>, [u32; 9]); + static CENSUS: std::sync::Mutex = + std::sync::Mutex::new((u64::MAX, std::collections::BTreeMap::new(), [0; 9])); + let frame = crate::frame::current(); + let mut census = CENSUS.lock().unwrap_or_else(|e| e.into_inner()); + if census.0 != frame { + let draws: u32 = census.1.values().sum(); + if draws > 0 { + let mut rects: Vec<([i32; 4], u32)> = census.1.iter().map(|(r, n)| (*r, *n)).collect(); + rects.sort_unstable_by(|a, b| b.1.cmp(&a.1)); + let scissors: Vec = rects + .iter() + .take(5) + .map(|(r, n)| format!("{} {} {} {} x{n}", r[0], r[1], r[2], r[3])) + .collect(); + let counts = census.2; + let culling: Vec = CULL + .iter() + .zip(counts) + .filter(|(_, n)| *n > 0) + .map(|(c, n)| format!("{}={n}", c.1)) + .collect(); + tracing::info!( + frame = census.0, + main_pass_draws = draws, + rectangles = rects.len(), + scissors = ?scissors, + culling = ?culling, + "walls trace: the frame's main pass by scissor rectangle, and its culling dispatches" + ); + } + census.0 = frame; + census.1.clear(); + census.2 = [0; 9]; + } + if compute { + for (i, c) in CULL.iter().enumerate() { + if p.stages.iter().any(|s| s.shader.hash.as_str() == c.0) { + census.2[i] += 1; + } + } + } else if self.targets.iter().filter(|&&t| t != 0).count() >= 4 { + let r = self.scissors.first().map_or([0; 4], |r| [r.left, r.top, r.right, r.bottom]); + *census.1.entry(r).or_insert(0) += 1; + } + } + + fn roots_ref(&self, compute: bool) -> &Vec { + if compute { + &self.compute + } else { + &self.graphics + } + } + + fn table_entry(&self, list: &HostList, u: &UsedResource, compute: bool) { + let Some(Root::Table(table)) = self.roots_ref(compute).get(usize::from(u.slot)) else { + return; + }; + let handle = table + u64::from(u.table_offset_dwords) * 4; + let Some(heap) = self.heap_of(handle) else { + return; + }; + let (Some(host), Some(index)) = (heap.host(), heap.index(handle)) else { + return; + }; + if let Some(view) = host.mirror(index, handle, true) { + readable(list, u.kind, &view); + // Up to date by this draw: not the texture pass's to make. + if crate::descriptor::host::is_texture_view(&view) { + host.texture_slot_tabled(index, true); + } + } + } + + /// The descriptors a shader reads through tables. Tables holding a + /// constant buffer are made afresh for the draw in dynamic slots, with + /// the constant data copied to upload memory when the list is + /// submitted: the host wants constant buffers 256-byte aligned, the + /// console only 16. Returns those tables' new byte offsets by root + /// parameter; the other tables' slots are made from the title's. + /// + /// Within a list, the same table holding the same descriptors is made + /// once: its constant data is copied at submission either way, and the + /// big tables the world binds would otherwise take hundreds of slots per + /// draw, wrapping the dynamic slots onto lists not yet submitted. + pub(crate) fn tables( + &mut self, + list: &HostList, + used: &[UsedResource], + indexed: &[RootIndexedView], + compute: bool, + ) -> Vec<(u8, u32)> { + let tables = |u: &&UsedResource| u.root == RootType::Table; + let mut fresh: Vec = used + .iter() + .filter(tables) + .filter(|u| u.kind == ResourceType::Cbv) + .map(|u| u.slot) + .collect(); + // Tables reaching past a host heap smaller than the title's (the + // host's limit, 1,000,000 views on NVIDIA) are made afresh too: the + // title's slots there have no host slot of their own. + for u in used.iter().filter(tables) { + if fresh.contains(&u.slot) { + continue; + } + let Some(&Root::Table(table)) = self.roots_ref(compute).get(usize::from(u.slot)) else { + continue; + }; + let end = table + u64::from(u.table_offset_dwords) * 4; + let Some(heap) = self.heap_of(table) else { + continue; + }; + let (Some(host), Some(index)) = (heap.host(), heap.index(end)) else { + continue; + }; + if index >= host.count() { + fresh.push(u.slot); + } + } + fresh.sort_unstable(); + fresh.dedup(); + for u in used.iter().filter(tables) { + if !fresh.contains(&u.slot) { + self.table_entry(list, u, compute); + } + } + let mut made = Vec::new(); + for slot in fresh { + let Some(&Root::Table(table)) = self.roots_ref(compute).get(usize::from(slot)) else { + continue; + }; + let entries: Vec<&UsedResource> = used + .iter() + .filter(tables) + .filter(|u| u.slot == slot) + .collect(); + let Some(heap) = self.heap_of(table) else { + continue; + }; + if heap.samplers() || (table - heap.start) % 32 != 0 { + continue; + } + let Some(host) = heap.host() else { + continue; + }; + let mut selected: Vec = indexed + .iter() + .filter(|index| index.table_slot == slot) + .map(|index| { + let constant = self.user_value( + compute, + index.constant_slot, + RootType::Constants, + index.constant_dword, + ); + // The shader adds i32 byte offsets and shifts by 5. + index.byte_offset.wrapping_add(constant << index.shift) / 32 + }) + .collect(); + selected.sort_unstable(); + selected.dedup(); + let n = entries + .iter() + .map(|u| u.table_offset_dwords / 8) + .chain(selected.last().copied()) + .max() + .unwrap_or(0) + + 1; + let last = table.checked_add(u64::from(n - 1) * 32); + if n > crate::descriptor::host::DYNAMIC + || last.and_then(|handle| heap.index(handle)).is_none() + { + once!(slot, n, "fresh descriptor table exceeds the available span"); + continue; + } + // The table and what its entries hold (record words). + let key = { + use std::hash::{Hash, Hasher}; + let mut h = std::collections::hash_map::DefaultHasher::new(); + for k in 0..n { + let at = table + u64::from(k) * 32; + // SAFETY: a descriptor slot in title memory. + unsafe { (at as *const [u32; 3]).read_unaligned() }.hash(&mut h); + } + (table, n, h.finish()) + }; + if let Some(&first) = self.fresh_tables.get(&key) { + for u in entries.iter().filter(|u| u.kind != ResourceType::Cbv) { + let handle = table + u64::from(u.table_offset_dwords) * 4; + if let Some(view) = crate::descriptor::view(handle) { + readable(list, u.kind, &view); + } + } + for k in selected { + if entries.iter().any(|u| u.table_offset_dwords / 8 == k) { + continue; + } + let handle = table + u64::from(k) * 32; + if let Some(view) = crate::descriptor::view(handle) + && let Some(kind) = view_kind(&view) + { + readable(list, kind, &view); + } + } + made.push((slot, first * 32)); + continue; + } + let Some(first) = host.dynamic(n) else { + // No room: the draw must not run with the title's own + // offsets (slots never made for it); `bind` drops it. + made.push((slot, u32::MAX)); + continue; + }; + self.fresh_tables.insert(key, first); + self.dynamic + .push((std::ptr::from_ref(heap) as usize, first, n)); + // The title's own slots of this table: what the draw reads of + // them it brings up to date here, in the dynamic slots. + let title_first = heap.index(table).filter(|first| first + n <= host.count()); + // The whole range: a shader may index past the entries its + // used-resource list names (descriptor arrays). + for k in 0..n { + let index = first + k; + let used = entries.iter().find(|u| u.table_offset_dwords / 8 == k); + match crate::descriptor::view(table + u64::from(k) * 32) { + Some(View::Constant(address, size)) => { + let Some((gpu, to)) = list.scratch(u64::from(size)) else { + host.make_null(index); + continue; + }; + list.defer_fill(to, address as *const u8, size as usize); + host.constant_at(index, gpu, size); + } + Some(view) => { + host.make_at(index, &view); + let kind = used.map(|u| u.kind).or_else(|| { + selected.binary_search(&k).ok().and_then(|_| view_kind(&view)) + }); + if let Some(kind) = kind { + readable(list, kind, &view); + } + // The title's slot is a table's: out of the queue + // of textures picked by index if the draw read it + // (its texture is up to date now), and made in + // place as the texture pass would have made it, + // for a shader that picks it by index all the same. + if let Some(title) = title_first + && crate::descriptor::host::is_texture_view(&view) + { + host.texture_slot_tabled(title + k, kind.is_some()); + if kind.is_some() { + host.mirror(title + k, table + u64::from(k) * 32, true); + } + } + } + None => { + host.make_null(index); + if used.is_some() { + once!(slot, "a table entry without a view"); + } + } + } + } + made.push((slot, first * 32)); + } + made + } + + /// The first draws, at debug level: what they bind and read + /// (diagnostics builds). + #[cfg(feature = "diagnostics")] + fn trace(&self, kind: &str, count: u32, first: u32) { + static TRACED: AtomicU64 = AtomicU64::new(0); + if !tracing::enabled!(tracing::Level::DEBUG) { + return; + } + let listed = crate::capture::listed(crate::queue::presented() + 1); + let logged = listed || TRACED.fetch_add(1, Ordering::Relaxed) < 64; + let targets: Vec = self + .targets + .iter() + .filter_map(|&t| crate::resource::host_made(t as This)) + .map(|t| { + // SAFETY: a live resource. + let d = unsafe { t.GetDesc() }; + format!("{}x{} f{}", d.Width, d.Height, d.Format.0) + }) + .collect(); + let v = self.vertex[0]; + let line = format!( + "{kind} {count} from {first} topology {} pipeline {:#x} targets {targets:?} vb {:#x}+{} stride {} reads {:?}", + self.topology, + self.pipeline, + v.address, + v.size, + v.stride, + self.reads(false) + ); + if logged { + tracing::debug!("draw {line}"); + } + let mut frame = FRAME.lock().unwrap_or_else(|e| e.into_inner()); + if frame.len() < 256 { + frame.push(line); + } + } + + /// What a draw's shaders read, one line per used resource (diagnostics + /// builds). + #[cfg(feature = "diagnostics")] + fn reads(&self, compute: bool) -> Vec { + let Some(p) = crate::pipeline::host_pipeline(self.pipeline as This) else { + return vec!["no host pipeline".into()]; + }; + let mut out = Vec::new(); + for stage in &p.stages { + let t = stage.translated(); + for u in &t.used { + let what = match (u.root, self.roots_ref(compute).get(usize::from(u.slot))) { + (RootType::Table, Some(Root::Table(table))) => { + let handle = table + u64::from(u.table_offset_dwords) * 4; + describe(crate::descriptor::view(handle).as_ref()) + } + (root, _) => format!("{root:?}"), + }; + out.push(format!( + "{} {:?} s{}+{}: {what}", + stage.shader.hash, u.kind, u.slot, u.table_offset_dwords + )); + } + } + out + } + + pub(crate) fn draw( + &mut self, + list: &HostList, + vertices: u32, + instances: u32, + first: u32, + first_instance: u32, + ) { + self.window = None; + if self.may_store() { + list.gather_close(); + } + #[cfg(feature = "diagnostics")] + self.trace("draw", vertices, first); + let ready = self.prepare(list, false); + // A pipeline with the rectangle geometry stage draws the title's + // vertices as they are; any other gets its rectangles expanded. + let rects = self.topology == RECTANGLES && !self.completes_rects(); + let ran = ready && (!rects || self.rectangles(list, vertices, first)); + if ran { + // Rectangles were expanded into their own vertex buffers. + let (count, from) = if rects { + (vertices / 3 * 6, 0) + } else { + (vertices, first) + }; + #[cfg(feature = "diagnostics")] + list.note_op(|| self.op_text(format!("draw {count}x{instances}"), false)); + // SAFETY: an open list with everything set. + unsafe { + list.list + .DrawInstanced(count, instances, from, first_instance) + }; + DRAWN.fetch_add(1, Ordering::Relaxed); + } + if !ran { + DROPPED.fetch_add(1, Ordering::Relaxed); + #[cfg(feature = "diagnostics")] + dropped(self.pipeline); + } + } + + /// Whether the bound pipeline completes rectangles itself, in the + /// geometry stage rectangle pipelines get (`HostPipeline::rects`). + fn completes_rects(&self) -> bool { + crate::pipeline::host_pipeline(self.pipeline as This).is_some_and(|p| p.rects) + } + + /// Binds vertex buffers holding the rectangles of vertices `first..first + /// + count` as triangles, made when the list is submitted. + fn rectangles(&self, list: &HostList, count: u32, first: u32) -> bool { + let Some(p) = crate::pipeline::host_pipeline(self.pipeline as This) else { + return false; + }; + let rects = u64::from(count / 3); + for slot in 0..32 { + let elements: Vec<(u32, u32)> = p + .inputs + .iter() + .filter(|e| e.slot == slot && !e.per_instance) + .map(|e| (e.offset, e.format)) + .collect(); + if elements.is_empty() { + continue; + } + let v = self.vertex[slot as usize]; + let stride = u64::from(v.stride); + let from = v.address + u64::from(first) * stride; + if v.address == 0 + || stride == 0 + || u64::from(first + count) * stride > u64::from(v.size) + || crate::shadow::find(from, rects * 3 * stride).is_none() + { + once!(slot, "rectangle vertices outside their buffer"); + return false; + } + let Some((gpu, to)) = list.scratch(rects * 6 * stride) else { + return false; + }; + let (from, to, stride) = (from as usize, to as usize, stride as usize); + let n = rects as usize; + list.defer_host(move || { + // The vertices are read in place, at submission: no change + // of mapping under the read (see + // `crate::watch::title_memory_reading`). + let _mapped = crate::watch::title_memory_reading(); + // SAFETY: the vertices lie in a title buffer (checked when + // recorded) and the scratch memory is the list's. + let (src, dst) = unsafe { + ( + std::slice::from_raw_parts(from as *const u8, n * 3 * stride), + std::slice::from_raw_parts_mut(to as *mut u8, n * 6 * stride), + ) + }; + crate::primitive::expand_rects(src, dst, stride, &elements); + }); + let view = D3D12_VERTEX_BUFFER_VIEW { + BufferLocation: gpu, + SizeInBytes: (rects * 6 * stride as u64) as u32, + StrideInBytes: v.stride, + }; + // SAFETY: an open list; the view names live scratch memory. + unsafe { list.list.IASetVertexBuffers(slot, Some(&[view])) }; + } + true + } + + pub(crate) fn draw_indexed( + &mut self, + list: &HostList, + indices: u32, + instances: u32, + first: u32, + base: i32, + first_instance: u32, + ) { + self.window = None; + if self.may_store() { + list.gather_close(); + } + #[cfg(feature = "diagnostics")] + self.trace("indexed", indices, first); + // Indexed rectangles are drawn by the rectangle geometry stage + // alone (nothing expands them on the CPU). + let lost = self.topology == RECTANGLES && !self.completes_rects(); + if lost { + once!("indexed rectangles not drawn"); + } + let ran = !lost && self.prepare(list, true); + if ran { + #[cfg(feature = "diagnostics")] + list.note_op(|| self.op_text(format!("indexed {indices}x{instances}"), false)); + // SAFETY: an open list with everything set. + unsafe { + list.list + .DrawIndexedInstanced(indices, instances, first, base, first_instance) + }; + DRAWN.fetch_add(1, Ordering::Relaxed); + } + if !ran { + DROPPED.fetch_add(1, Ordering::Relaxed); + #[cfg(feature = "diagnostics")] + dropped(self.pipeline); + } + } +} + +impl State { + /// Indirect execution of a one-argument signature of `kind` (PC + /// numbering: 0 draw, 1 indexed draw, 2 dispatch, 10 mesh dispatch) with + /// records `stride` bytes apart at title address `arguments`, and the + /// record count at `count` if the title gives one: the GPU reads them + /// from the buffer's host copy, where earlier dispatches may have + /// written them. False if it cannot run on the host. + pub(crate) fn execute_indirect( + &mut self, + list: &HostList, + (kind, stride, max): (u32, u32, u32), + arguments: u64, + count: Option, + ) -> bool { + // Skip before the argument clamp can mutate the indirect buffer. + #[cfg(feature = "diagnostics")] + if crate::pipeline::is_skipped(self.pipeline as This) { + crate::pipeline::note_drop(self.pipeline as This); + return false; + } + if crate::pipeline::is_builder(self.pipeline as This) && !crate::pipeline::builder_runs() { + return false; + } + // A program that walks ray-tracing structures nothing has built: + // dropped before the argument clamp, like a skipped one. + if crate::pipeline::walk_held(self.pipeline as This) { + #[cfg(feature = "diagnostics")] + crate::pipeline::note_why("a walk of ray-tracing structures that are not built (LEONIDA_BVH_HOLD=1)".to_owned()); + return false; + } + const DRAW: u32 = 0; + const INDEXED: u32 = 1; + const DISPATCH: u32 = 2; + const MESH: u32 = 10; + #[cfg(feature = "diagnostics")] + let why = |what: &str| crate::pipeline::note_why(format!("indirect kind {kind}: {what}")); + #[cfg(not(feature = "diagnostics"))] + let why = |_: &str| {}; + let Some(p) = crate::pipeline::host_pipeline(self.pipeline as This) else { + #[cfg(feature = "diagnostics")] + crate::pipeline::note_drop(self.pipeline as This); + return false; + }; + // Indirect rectangles (the title's tiled lighting, 256 + // indirect draws a frame, makes their corners from the vertex + // number) are completed by the pipeline's geometry stage: the + // arguments stay the title's, three vertices a rectangle. They + // cannot be expanded on the CPU, which does not know their count. + // shortcut: in a pipeline without that stage, a rectangle with no + // per-vertex inputs is drawn as its first triangle (three vertices, + // half of it), and one with vertex buffers is not drawn. + let made_rects = !p.rects + && kind == DRAW + && self.topology == RECTANGLES + && !p.inputs.iter().any(|e| !e.per_instance); + if made_rects { + once!("indirect rectangles without vertex inputs drawn as their first triangle"); + } + let matches_kind = match kind { + DRAW | INDEXED => { + (self.topology != RECTANGLES || made_rects || p.rects) && !p.compute && !p.mesh + } + MESH => !p.compute && p.mesh, + DISPATCH => p.compute, + _ => false, + }; + if !matches_kind { + why(&format!( + "pipeline mismatch (compute {}, mesh {}, topology {})", + p.compute, p.mesh, self.topology + )); + return false; + } + let len = u64::from(stride) * u64::from(max.max(1)); + let Some(args) = crate::shadow::find_any(arguments, len) else { + why("arguments outside title buffers"); + return false; + }; + let counter = match count { + Some(at) => match crate::shadow::find_any(at, 4) { + Some(s) => Some((s, at)), + None => { + why("count outside title buffers"); + return false; + } + }, + None => None, + }; + let Some(signature) = matches!(kind, DRAW | INDEXED | DISPATCH | MESH) + .then(|| host_signature(kind, stride)) + .flatten() + else { + why("no host signature"); + return false; + }; + if kind == MESH && (mesh_test() == 1 || !mesh_kept(self.pipeline)) { + why("mesh draws are switched off (LEONIDA_MESH_TEST=skip)"); + return false; + } + // A window of records clamped in one pass (`windows`): for single + // records without a count buffer, drawn by shaders that store to no + // buffer. Anything else ends the window: it uses the scratch buffer + // or may write the arguments. + const WINDOW_USE: usize = usize::MAX - 0x77; + let offset = args.offset(arguments); + let windowed = windows() + && kind != DISPATCH + && max == 1 + && count.is_none() + && !p.stages.iter().any(|stage| stage.translated().stores); + // Another host list (a new one after a cut, or this one after its + // reset) has another scratch buffer, or this one's with old bytes. + let first_on_list = list.first_use(WINDOW_USE); + if !windowed || first_on_list { + self.window = None; + } + if !windowed { + // A dispatch, or shaders that store to buffers: arguments may + // be written from here on. + list.gather_close(); + } + // Diagnostics: why this command gets a pass of ours, if it does. + #[cfg(feature = "diagnostics")] + let why_not = if !windows() { + usize::MAX + } else if kind == DISPATCH { + 1 + } else if max != 1 { + 2 + } else if count.is_some() { + 3 + } else if !windowed { + 4 + } else if first_on_list { + 5 + } else { + match &self.window { + None => 6, + Some(w) if !(w.copy == args.id() && w.kind == kind && w.stride == stride) => 6, + Some(w) if offset >= w.base && (offset - w.base) % u64::from(w.step) == 0 => 8, + Some(_) => 7, + } + }; + let same = |w: &Window| w.copy == args.id() && w.kind == kind && w.stride == stride; + let hit = self + .window + .as_ref() + .filter(|w| same(w) && offset >= w.base) + .filter(|w| (offset - w.base) % u64::from(w.step) == 0 && (offset - w.base) / u64::from(w.step) < u64::from(w.records)) + .map(|w| (w.scratch.clone(), offset - w.base, w.step)); + // A record that misses its window: a slot the list's prelude fills, + // if the list still gathers ([`gathers`]). + let gathered = if hit.is_none() && windowed && gathers() { + let slot = crate::indirect::gather(list, (&args.buffer, args.id()), offset, (kind, stride)); + #[cfg(feature = "diagnostics")] + WINDOW_WHY[if slot.is_some() { 12 } else { 13 }].fetch_add(1, std::sync::atomic::Ordering::Relaxed); + slot + } else { + None + }; + let (bounded, at) = match (hit, gathered) { + (Some((scratch, at, step)), _) => { + // Diagnostics of windows: the record clamped again and + // compared (`crate::indirect::window_check`). + if crate::indirect::window_check() + && crate::indirect::check_hit( + list, + (&args.buffer, offset), + (kind, step), + &scratch, + at, + ) + { + self.host_pipeline = 0; + self.host_roots[1] = 0; + } + #[cfg(feature = "diagnostics")] + WINDOW_WHY[0].fetch_add(1, std::sync::atomic::Ordering::Relaxed); + if !self.window_read { + self.window_read = true; + if let Some(w) = self.window.as_ref().filter(|w| w.records > 1) { + self.walk_step = Some((w.copy, w.kind, w.stride, w.step)); + } + } + (scratch, at) + } + (None, Some((scratch, at))) => { + // The record's bytes are up to date when the list is + // submitted, as for a record clamped in the list. + args.refresh(list, arguments, len); + // Diagnostics of windows, for gathered records too: the + // record clamped again here and compared. + if crate::indirect::window_check() && crate::indirect::check_hit(list, (&args.buffer, offset), (kind, stride), &scratch, at) { + self.host_pipeline = 0; + self.host_roots[1] = 0; + } + (scratch, at) + } + (None, None) => { + // A window opened at the remembered step that no draw read + // from: the title does not walk here by that step. + if self.window_jumped && !self.window_read { + self.walk_step = None; + #[cfg(feature = "diagnostics")] + WINDOW_WHY[11].fetch_add(1, std::sync::atomic::Ordering::Relaxed); + } + self.window_jumped = false; + // A record a short step after the last window's last one + // (the same step as that window's, if it had one): the + // title walks the buffer, so the ones that step apart + // after it are clamped with it. + let (step, records) = match &self.window { + Some(w) if windowed && same(w) => { + let last = w.base + u64::from(w.records - 1) * u64::from(w.step); + let step = offset.saturating_sub(last); + let walks = step >= u64::from(stride) + && step <= 256 + && step % 4 == 0 + && (w.records == 1 || step == u64::from(w.step)); + if walks { + let fit = (args.left(arguments) / step).min(WINDOW_MOST) as u32; + (step as u32, (if w.records == 1 { 16 } else { w.records * 2 }).min(fit).max(1)) + } else { + (stride, max) + } + } + _ => (stride, max), + }; + // A record that would be clamped alone, on a buffer whose + // step is remembered: the window the next record would + // open, opened here ([`jump_windows`]). + let (step, records) = match (windowed && records == 1 && jump_windows()) + .then(|| jump_window(self.walk_step, (args.id(), kind, stride), args.left(arguments))) + .flatten() + { + Some(jumped) => { + self.window_jumped = true; + #[cfg(feature = "diagnostics")] + WINDOW_WHY[10].fetch_add(1, std::sync::atomic::Ordering::Relaxed); + jumped + } + None => (step, records), + }; + self.window_read = false; + args.refresh(list, arguments, len.max(u64::from(step) * u64::from(records))); + if let Some((s, at)) = &counter { + s.refresh(list, *at, 4); + } + // Bounded first: the clamp binds a compute pipeline of its + // own and copies clamped active records into a scratch + // buffer at offset 0. + let count_arg = counter.as_ref().map(|(s, at)| (&s.buffer, s.offset(*at))); + // More than the record asked for: a window clamped ahead, + // whose unfilled slots must not spend the list's budget. + let bounded = if windowed && records > 1 { + crate::indirect::bound_ahead(list, (&args.buffer, offset), (kind, step, records)) + } else { + crate::indirect::bound(list, (&args.buffer, offset), count_arg, (kind, step, records)) + }; + let Some(bounded) = bounded else { + self.window = None; + why("not bounded (no clamp, or arguments not 4-byte aligned)"); + return false; + }; + #[cfg(feature = "diagnostics")] + if why_not < WINDOW_WHY.len() { + WINDOW_WHY[why_not].fetch_add(1, std::sync::atomic::Ordering::Relaxed); + WINDOW_WHY[9].fetch_add(u64::from(records), std::sync::atomic::Ordering::Relaxed); + // One in 256 of the draws that miss their window, said: + // where the record lies against the window and against + // the record drawn before it. + if (6..=8).contains(&why_not) { + static N: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + if N.fetch_add(1, std::sync::atomic::Ordering::Relaxed) % 256 == 0 { + let (last_copy, last_offset) = self.last_indirect; + tracing::info!( + "a window miss (one in 256): cause {why_not}, kind {kind}, stride {stride}, buffer {} offset {offset:#x} ({} left); the command before it on the list: buffer {last_copy} offset \ + {last_offset:#x} (this one is {} bytes on); the window it missed: {}; clamped now: {records} records at step {step}", + args.id(), + args.left(arguments), + offset as i64 - last_offset as i64, + match &self.window { + Some(w) => format!("buffer {} kind {} stride {} base {:#x} step {} records {} (this record is {} bytes from its base)", w.copy, w.kind, w.stride, w.base, w.step, w.records, offset as i64 - w.base as i64), + None => "none".to_string(), + } + ); + } + } + } + self.host_pipeline = 0; + self.host_roots[1] = 0; + self.window = windowed.then(|| Window { + copy: args.id(), + kind, + stride, + step, + base: offset, + records, + scratch: bounded.clone(), + }); + (bounded, 0) + } + }; + #[cfg(feature = "diagnostics")] + { + self.last_indirect = (args.id(), offset); + } + let ran = match kind { + DRAW | INDEXED => self.prepare(list, kind == INDEXED), + MESH => self.prepare_for(list, false, true), + DISPATCH => self.bind(list, p, true), + _ => false, + }; + if !ran { + why("prepare failed"); + return false; + } + #[cfg(feature = "diagnostics")] + list.note_op(|| { + self.op_text(format!("indirect kind {kind} max {max} at {arguments:#x}"), kind == DISPATCH) + }); + if kind == MESH { + self.mesh_scissor(list, true); + } + // SAFETY: an open list with everything set; the scratch buffer and + // host copies are kept alive by the list, and the signature is cached. + unsafe { + list.list.ExecuteIndirect( + &signature, + max, + &bounded, + at, + counter.as_ref().map(|(s, _)| &s.buffer), + counter.as_ref().map_or(0, |(s, at)| s.offset(*at)), + ) + }; + if kind == MESH { + self.mesh_scissor(list, false); + } + // The scratch buffer stays readable as arguments: the next draw of + // the window reads it with no barrier, and the next clamp moves it + // back (`crate::indirect`). + if kind == DISPATCH { + DISPATCHED.fetch_add(1, Ordering::Relaxed); + } else { + DRAWN.fetch_add(1, Ordering::Relaxed); + } + true + } +} + +/// The host command signature for one argument of `kind` with records +/// `stride` bytes apart (no root arguments, so no root signature), made +/// once. +fn host_signature(kind: u32, stride: u32) -> Option { + static MADE: std::sync::Mutex> = + std::sync::Mutex::new(Vec::new()); + let mut made = MADE.lock().unwrap_or_else(|e| e.into_inner()); + if let Some((_, s)) = made.iter().find(|(k, _)| *k == (kind, stride)) { + return Some(s.clone()); + } + let argument = D3D12_INDIRECT_ARGUMENT_DESC { + Type: D3D12_INDIRECT_ARGUMENT_TYPE(kind as i32), + ..Default::default() + }; + let desc = D3D12_COMMAND_SIGNATURE_DESC { + ByteStride: stride, + NumArgumentDescs: 1, + pArgumentDescs: &argument, + NodeMask: 0, + }; + let mut signature: Option = None; + // SAFETY: a description of one argument; no root arguments. + let result = unsafe { + crate::host::host()?.device.CreateCommandSignature( + &desc, + None::<&ID3D12RootSignature>, + &mut signature, + ) + }; + if let Err(e) = result { + once!(error = %e, kind, stride, "host command signature refused"); + return None; + } + let signature = signature?; + made.push(((kind, stride), signature.clone())); + Some(signature) +} + +/// Gets what a shader reads or writes through a view ready: buffer data +/// copied, textures moved to the state they need. +fn view_kind(view: &View) -> Option { + match view { + View::Shader(..) | View::Placed(false, ..) => Some(ResourceType::Srv), + View::Unordered(..) | View::Placed(true, ..) => Some(ResourceType::Uav), + _ => None, + } +} + +/// The host state a depth view needs of its texture: the read state if the +/// view writes no plane the format has (the title's read-only flags), else +/// the write state. +/// shortcut: whole textures have one state, so a view that writes one of +/// two planes counts as writing. +fn depth_state(texture: &ID3D12Resource, desc: Option<&D3D12_DEPTH_STENCIL_VIEW_DESC>) -> u32 { + // D16_UNORM and D32_FLOAT: depth formats without a stencil plane. + const ONE_PLANE: [i32; 2] = [55, 40]; + let Some(desc) = desc else { + return DEPTH_WRITE; + }; + let format = if desc.Format.0 == 0 { + // SAFETY: a live texture; a view without a format has its own. + unsafe { texture.GetDesc() }.Format.0 + } else { + desc.Format.0 + }; + let mut needed = D3D12_DSV_FLAG_READ_ONLY_DEPTH.0; + if !ONE_PLANE.contains(&format) { + needed |= D3D12_DSV_FLAG_READ_ONLY_STENCIL.0; + } + if desc.Flags.0 & needed == needed { + DEPTH_READ + } else { + DEPTH_WRITE + } +} + +fn readable(list: &HostList, kind: ResourceType, view: &View) { + const UNORDERED_ACCESS: u32 = 0x8; + let placed = crate::descriptor::host::placed_texture(view); + let view = placed.as_ref().unwrap_or(view); + // Buffer views read title memory: their range is copied at submission; + // what shaders write through unordered access goes back to it after. + if let Some((shadow, address, len)) = crate::descriptor::host::buffer_copy(view) { + shadow.refresh(list, address, len); + if kind == ResourceType::Uav { + // A shader that cannot store to buffers leaves the range as + // the title has it: nothing to find afterwards. + if STORES.get() || !write_skip() { + shadow.gpu_writes(list, address, len); + } else { + #[cfg(feature = "diagnostics")] + { + crate::copystat::add(crate::copystat::C::GpuWritesLeftOut, 1); + crate::copystat::add(crate::copystat::C::GpuWritesLeftOutBytes, len); + } + } + } + } + match (view, kind) { + (View::Shader(resource, _), ResourceType::Srv) => { + // A view the title placed, in another format, in the memory of + // a texture the host writes: that texture's texels, copied on + // the host (title memory does not have them). + let aliased = crate::resource::alias_of(*resource as This) + .is_some_and(|source| crate::texture::alias(list, *resource as This, source)); + if !aliased + && let Some(t) = crate::resource::host_resource(*resource as This) + && crate::texture::title_written(t) + { + crate::texture::upload(list, *resource as This, t); + } + // A depth texture shaders also write: what they wrote, first. + list.twin_use(*resource as This, false, false); + // The depth target the draw only tests is read in both ways at + // once: both read states, which its preparation asks for too. + let (tested, _) = TESTED_DEPTH.get(); + let state = if tested != 0 && tested == *resource { + TESTED_DEPTH.set((tested, true)); + DEPTH_READ | SHADER_RESOURCE + } else { + SHADER_RESOURCE + }; + crate::list::ensure_state(list, *resource as This, state); + #[cfg(feature = "diagnostics")] + if let Some(t) = crate::resource::host_resource(*resource as This) { + // SAFETY: a live resource. + let d = unsafe { t.GetDesc() }; + if d.Flags.0 & 7 == 0 { + tracing::debug!( + resource = format_args!("{resource:#x}"), + ?d, + "a shader reads a texture the title fills" + ); + } + } + } + (View::Unordered(resource, _, _), ResourceType::Uav) => { + #[cfg(feature = "diagnostics")] + crate::capture::note_target(*resource as This); + // Unordered access to a depth texture is its colour twin's. + if !list.twin_use(*resource as This, true, true) { + crate::list::ensure_state(list, *resource as This, UNORDERED_ACCESS); + } + } + _ => {} + } +} + +/// The pixel shaders whose draws get their slots listed +/// ([`State::slots_text`]): `LEONIDA_LIST_SLOTS`, hash prefixes separated +/// by commas. None by default. +#[cfg(feature = "diagnostics")] +fn list_slots() -> &'static [String] { + static LIST: std::sync::OnceLock> = std::sync::OnceLock::new(); + LIST.get_or_init(|| { + std::env::var("LEONIDA_LIST_SLOTS") + .unwrap_or_default() + .split(',') + .map(|s| s.trim().to_ascii_lowercase()) + .filter(|s| !s.is_empty()) + .collect() + }) +} + +/// A fingerprint of the 4 KiB of title memory at `at` (FNV-1a, 64 bits; of +/// 4 KiB of zeros it is always the same value, which `slots.py` knows), or +/// "unreadable". +#[cfg(feature = "diagnostics")] +fn print_4k(at: u64) -> String { + let mut bytes = [0u8; 4096]; + if at == 0 || !crate::host::read_into(at as *const u8, &mut bytes) { + return "unreadable".into(); + } + let mut hash = 0xcbf2_9ce4_8422_2325_u64; + for b in bytes { + hash = (hash ^ u64::from(b)).wrapping_mul(0x0000_0100_0000_01b3); + } + format!("{hash:016x}") +} + +/// The `bytes` of title memory at `at`: how many are mapped, and the +/// fingerprints of the first and the last 4 KiB (a texture's smallest +/// levels lie first, its largest last). +#[cfg(feature = "diagnostics")] +fn memory_state(at: u64, bytes: u64) -> String { + let mapped = crate::texture::mapped_bytes(at as *const u8, bytes as usize); + let last = at + bytes.saturating_sub(4096); + format!("memory={at:#x} mapped={mapped}/{bytes} first4k={} last4k={}", print_4k(at), print_4k(last)) +} + +/// Title texture `this` for the frame listing: its size, whether it has a +/// host copy (not made here), its staging buffer's state, whether the host +/// copied into it, and its memory ([`memory_state`]). +#[cfg(feature = "diagnostics")] +fn texture_state(this: This) -> String { + let Some((at, desc)) = crate::resource::texture_memory(this) else { + return "not a texture".into(); + }; + // SAFETY: 56 bytes in the description's layout. + let words = unsafe { std::ptr::from_ref(&desc).cast::<[u32; 14]>().read_unaligned() }; + let bytes = crate::resource::placed_bytes(&words).unwrap_or(0); + let staged = match crate::texture::staged_state(this) { + Some((uploaded, dirty)) => format!("staged=yes uploaded={uploaded} dirty={dirty}"), + None => "staged=no".into(), + }; + format!( + "{}x{} f{} levels={} host_copy={} {staged} host_written={} title_fills={} {}", + u64::from(words[4]) | u64::from(words[5]) << 32, + words[6], + words[8], + words[7] >> 16, + crate::resource::host_made(this).is_some(), + crate::texture::host_wrote(this as usize), + crate::resource::title_fills(this), + memory_state(at as u64, bytes) + ) +} + +/// A view of the title's heap for the frame listing: a texture with its +/// state ([`texture_state`]; a placed one that has no resource yet with +/// its memory alone), anything else in a few words. +#[cfg(feature = "diagnostics")] +fn view_state(view: Option<&View>) -> String { + match view { + None => "no view".into(), + Some(View::Placed(false, r, d)) if r[0] != 1 => { + let address = u64::from(d[10]) | u64::from(d[11]) << 32; + let state = match crate::resource::texture_at_made(address, r) { + Some(this) => texture_state(this), + None => format!( + "{}x{} f{} levels={} resource=none {}", + u64::from(r[4]) | u64::from(r[5]) << 32, + r[6], + r[8], + r[7] >> 16, + memory_state(address, crate::resource::placed_bytes(r).unwrap_or(0)) + ), + }; + // (Last, so that readers of the older lines still find + // theirs: the level the view starts at, and how many it shows.) + format!("placed texture view_format={} {state} view_levels={}+{}", d[0], d[4], d[5] as i32) + } + Some(View::Shader(r, d)) if crate::resource::texture_memory(*r as This).is_some() => { + format!( + "texture object {r:#x} view_format={} {} view_levels={}", + d.as_ref().map_or(0, |d| d[0]), + texture_state(*r as This), + d.as_ref().map_or("all".to_owned(), |d| format!("{}+{}", d[4], d[5] as i32)) + ) + } + Some(v) => format!("{v:?}").chars().take(80).collect(), + } +} + +/// A view in a few words (diagnostics builds). +#[cfg(feature = "diagnostics")] +fn describe(view: Option<&View>) -> String { + let texture = |r: This| { + crate::resource::host_made(r).map(|t| { + // SAFETY: a live resource. + let d = unsafe { t.GetDesc() }; + format!("{}x{} f{} flags {:#x} of {r:?}", d.Width, d.Height, d.Format.0, d.Flags.0) + }) + }; + match view { + None => "no view".into(), + Some(v @ View::Shader(r, _)) => texture(*r as This) + .unwrap_or_else(|| format!("buffer {:?}", crate::descriptor::host::buffer_range(v))), + Some(v @ View::Unordered(r, ..)) => match texture(*r as This) { + Some(t) => format!("uav texture {t}"), + None => format!( + "uav resource {r:#x} buffer {:?}", + crate::descriptor::host::buffer_range(v) + ), + }, + Some(View::Placed(u, r, d)) => format!( + "placed uav={u} dim {} {}x{} f{} layout {:#x} at {:#x}", + r[0], + u64::from(r[4]) | u64::from(r[5]) << 32, + r[6], + r[8], + r[11], + u64::from(d[10]) | u64::from(d[11]) << 32 + ), + // The first four values, as a colour rectangle's constants are. + Some(View::Constant(address, size)) + if *size >= 16 && crate::texture::committed(*address as *const u8, 16) => + { + // SAFETY: 16 committed bytes of title memory. + let v = unsafe { (*address as *const [f32; 4]).read_unaligned() }; + format!("Constant({address:#x}, {size}) {v:?}") + } + Some(v) => format!("{v:?}").chars().take(60).collect(), + } +} + +/// The console's own primitive topologies. +const TRIANGLE_FAN: u32 = 6; +const RECTANGLES: u32 = 17; +const LINE_LOOP: u32 = 18; +const QUADS: u32 = 19; +const QUAD_STRIP: u32 = 20; + +/// Fixed-function state, straight onto the host list. +pub(crate) fn viewports(list: &HostList, viewports: &[D3D12_VIEWPORT]) { + // SAFETY: an open list. + unsafe { list.list.RSSetViewports(viewports) }; +} + +pub(crate) fn scissors(list: &HostList, rects: &[RECT]) { + // SAFETY: an open list. + unsafe { list.list.RSSetScissorRects(rects) }; +} + +pub(crate) fn blend_factor(list: &HostList, factor: Option<&[f32; 4]>) { + // SAFETY: an open list. + unsafe { list.list.OMSetBlendFactor(factor) }; +} + +pub(crate) fn stencil_ref(list: &HostList, reference: u32) { + #[cfg(feature = "diagnostics")] + crate::capture::op(std::ptr::from_ref(list) as usize, || format!("STENCIL REF {reference:#x}")); + // SAFETY: an open list. + unsafe { list.list.OMSetStencilRef(reference) }; +} + +pub(crate) fn depth_bounds(list: &HostList, min: f32, max: f32) { + #[cfg(feature = "diagnostics")] + crate::capture::op(std::ptr::from_ref(list) as usize, || { + format!("DEPTH BOUNDS {min}..{max}") + }); + if crate::host::host().is_some_and(|h| h.depth_bounds()) + && let Ok(l1) = list.list.cast::() + { + // SAFETY: an open list on a device that supports depth bounds. + unsafe { l1.OMSetDepthBounds(min, max) }; + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_lone_record_opens_a_window_at_the_remembered_step() { + // (a mesh dispatch is kind 10, a draw kind 0) + let remembered = Some((7u64, 10u32, 12u32, 32u32)); + // the same buffer, kind and stride: sixteen records at the title's step + assert_eq!(jump_window(remembered, (7, 10, 12), 1 << 20), Some((32, 16))); + // never past the buffer: 100 bytes left hold three records 32 apart + assert_eq!(jump_window(remembered, (7, 10, 12), 100), Some((32, 3))); + // one record fits: nothing to open + assert_eq!(jump_window(remembered, (7, 10, 12), 40), None); + // another buffer, kind or stride, or nothing remembered: alone, as before + assert_eq!(jump_window(remembered, (8, 10, 12), 1 << 20), None); + assert_eq!(jump_window(remembered, (7, 0, 12), 1 << 20), None); + assert_eq!(jump_window(remembered, (7, 10, 16), 1 << 20), None); + assert_eq!(jump_window(None, (7, 10, 12), 1 << 20), None); + } +} diff --git a/crates/leonida-gpu/src/drvwatch.rs b/crates/leonida-gpu/src/drvwatch.rs new file mode 100644 index 000000000..346cdbbc8 --- /dev/null +++ b/crates/leonida-gpu/src/drvwatch.rs @@ -0,0 +1,188 @@ +//! The graphics driver's errors, seen as the system records them. +//! +//! A card is not lost out of nothing. Every loss of runs 201, 204, 208 and +//! 224 has entries of the card's driver in the system's event log (NVIDIA: +//! provider `nvlddmkm`, event 153, "Error occurred on GPUID") from 2.7 to +//! 6.3 seconds BEFORE the device was removed, several of them; run 210 has +//! three and kept its device; the runs with no such entry lost nothing. +//! Nothing in the layer saw them: the first it knew was the device gone. +//! +//! Here the layer subscribes to that log. Each entry of a display driver +//! is written to our log when the system records it, with our own clock, +//! so it can be laid beside what the layer did in that moment; it is +//! counted; and the first one trips a switch ([`tripped`]) that the paths +//! under suspicion ask before they run (the draw windows of `crate::draw` +//! turn themselves off for the rest of the run). So a driver error costs a +//! slower frame from then on, and not the card. +//! +//! On by default; `LEONIDA_DRIVER_WATCH=0` subscribes to nothing. + +use std::sync::atomic::{AtomicBool, AtomicU64, Ordering::Relaxed}; + +use windows_sys::Win32::System::EventLog::{ + EVT_HANDLE, EVT_SUBSCRIBE_NOTIFY_ACTION, EvtSubscribe, EvtSubscribeActionDeliver, EvtSubscribeToFutureEvents, +}; + +/// Entries of a display driver seen since the start. +static ERRORS: AtomicU64 = AtomicU64::new(0); +/// Whether one was seen ([`tripped`]). +static TRIPPED: AtomicBool = AtomicBool::new(false); + +/// Whether the card's driver has reported an error in this run: what could +/// have caused it stops for the rest of the run. +pub(crate) fn tripped() -> bool { + TRIPPED.load(Relaxed) +} + +/// Driver errors seen since the start. +pub(crate) fn errors() -> u64 { + ERRORS.load(Relaxed) +} + +/// An entry of a display driver was recorded. +fn seen() { + let n = ERRORS.fetch_add(1, Relaxed) + 1; + let first = !TRIPPED.swap(true, Relaxed); + tracing::error!( + n, + "the graphics driver reported an error to the system's event log{}", + if first { + ": from now on the paths under suspicion are off for this run (draw windows clamp each record again)" + } else { + "" + } + ); +} + +unsafe extern "system" fn on_event(action: EVT_SUBSCRIBE_NOTIFY_ACTION, _context: *const core::ffi::c_void, _event: EVT_HANDLE) -> u32 { + if action == EvtSubscribeActionDeliver { + seen(); + } + 0 +} + +/// Subscribes to the display drivers' entries in the system's event log, +/// once. Entries from before the call are not delivered. +pub(crate) fn start() { + static ONCE: std::sync::Once = std::sync::Once::new(); + ONCE.call_once(|| { + if std::env::var_os("LEONIDA_DRIVER_WATCH").is_some_and(|v| v == "0") { + return; + } + let wide = |s: &str| -> Vec { s.encode_utf16().chain(std::iter::once(0)).collect() }; + let channel = wide("System"); + // The kernel drivers of the three vendors, and the system's own + // "display driver stopped responding" source. + let query = wide( + "*[System[Provider[@Name='nvlddmkm' or @Name='amdkmdag' or @Name='amdwddmg' or @Name='igfx' or @Name='igfxn' \ + or @Name='Display']]]", + ); + // SAFETY: valid strings for the call's length; the callback is a + // plain function that touches only statics; the subscription is + // kept for the life of the process. + let subscription = unsafe { + EvtSubscribe( + 0, + std::ptr::null_mut(), + channel.as_ptr(), + query.as_ptr(), + 0, + std::ptr::null(), + Some(on_event), + EvtSubscribeToFutureEvents, + ) + }; + if subscription == 0 { + tracing::warn!( + error = %std::io::Error::last_os_error(), + "no subscription to the system's event log: the graphics driver's errors are not seen as they happen" + ); + } else { + tracing::info!( + "the graphics driver's errors in the system's event log are watched: each is logged here as it is recorded, and \ + the first turns the paths under suspicion off (LEONIDA_DRIVER_WATCH=0: not watched)" + ); + } + }); +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn the_first_error_trips_the_switch_and_every_one_is_counted() { + // (Other tests do not touch these statics.) + assert!(!tripped()); + assert_eq!(errors(), 0); + seen(); + assert!(tripped()); + seen(); + assert_eq!(errors(), 2); + assert!(tripped()); + } + + /// End to end, by hand (`--ignored`): an entry written to the + /// Application log under a name of our own reaches a subscription made + /// the same way as [`start`]'s, within a second. It leaves one + /// information entry in that log. + #[test] + #[ignore = "writes one entry to the Application event log: run it by name with --ignored"] + fn an_entry_written_reaches_a_subscription() { + use windows_sys::Win32::System::EventLog::{ + DeregisterEventSource, EVENTLOG_INFORMATION_TYPE, EvtClose, RegisterEventSourceW, ReportEventW, + }; + static GOT: AtomicU64 = AtomicU64::new(0); + unsafe extern "system" fn got(action: EVT_SUBSCRIBE_NOTIFY_ACTION, _: *const core::ffi::c_void, _: EVT_HANDLE) -> u32 { + if action == EvtSubscribeActionDeliver { + GOT.fetch_add(1, Relaxed); + } + 0 + } + let wide = |s: &str| -> Vec { s.encode_utf16().chain(std::iter::once(0)).collect() }; + let (channel, query) = (wide("Application"), wide("*[System[Provider[@Name='leonida-drvwatch-test']]]")); + // SAFETY: as in `start`. + let subscription = unsafe { + EvtSubscribe(0, std::ptr::null_mut(), channel.as_ptr(), query.as_ptr(), 0, std::ptr::null(), Some(got), EvtSubscribeToFutureEvents) + }; + assert_ne!(subscription, 0, "{}", std::io::Error::last_os_error()); + let (name, text) = (wide("leonida-drvwatch-test"), wide("a test entry of the Leonida Legacy layer's driver watch")); + // SAFETY: a source of our own name, one string, no data. + unsafe { + let source = RegisterEventSourceW(std::ptr::null(), name.as_ptr()); + assert!(!source.is_null(), "{}", std::io::Error::last_os_error()); + let strings = [text.as_ptr()]; + assert_ne!( + ReportEventW(source, EVENTLOG_INFORMATION_TYPE, 0, 1, std::ptr::null_mut(), 1, 0, strings.as_ptr(), std::ptr::null()), + 0, + "{}", + std::io::Error::last_os_error() + ); + DeregisterEventSource(source); + } + let started = std::time::Instant::now(); + while GOT.load(Relaxed) == 0 && started.elapsed() < std::time::Duration::from_secs(5) { + std::thread::sleep(std::time::Duration::from_millis(10)); + } + let after = started.elapsed(); + // SAFETY: our own subscription. + unsafe { EvtClose(subscription) }; + assert_eq!(GOT.load(Relaxed), 1, "the entry was not delivered in 5 s"); + eprintln!("delivered after {} ms", after.as_millis()); + } + + /// The subscription itself: the system accepts the channel and the + /// query (a query it cannot read is refused at once). + #[test] + fn the_system_takes_the_subscription() { + let wide = |s: &str| -> Vec { s.encode_utf16().chain(std::iter::once(0)).collect() }; + let (channel, query) = (wide("System"), wide("*[System[Provider[@Name='nvlddmkm' or @Name='Display']]]")); + // SAFETY: as in `start`. + let subscription = unsafe { + EvtSubscribe(0, std::ptr::null_mut(), channel.as_ptr(), query.as_ptr(), 0, std::ptr::null(), Some(on_event), EvtSubscribeToFutureEvents) + }; + assert_ne!(subscription, 0, "{}", std::io::Error::last_os_error()); + // SAFETY: our own subscription. + unsafe { windows_sys::Win32::System::EventLog::EvtClose(subscription) }; + } +} diff --git a/crates/leonida-gpu/src/dxgi.rs b/crates/leonida-gpu/src/dxgi.rs new file mode 100644 index 000000000..2561b39f5 --- /dev/null +++ b/crates/leonida-gpu/src/dxgi.rs @@ -0,0 +1,341 @@ +//! The DXGI side of the device: one adapter with one output, reached from +//! the device by interface query. Tables follow the PC interfaces' order +//! (IUnknown, the object methods, then each interface's methods). +#![allow(clippy::not_unsafe_ptr_arg_deref)] + +use crate::object::{ + self, ADAPTER, DXGI_DEVICE, E_INVALIDARG, FACTORY, HRESULT, Iid, MORE_DATA, NOT_FOUND, OUTPUT, + Object, S_OK, Table, This, guid, +}; + +/// The DXGI device interfaces, base first (as on PC). +pub(crate) const DEVICE_IIDS: [Iid; 3] = [ + guid( + 0x54ec77fa, + 0x1377, + 0x44e6, + [0x8c, 0x32, 0x88, 0xfd, 0x5f, 0x44, 0xc8, 0x4c], + ), + guid( + 0x77db970f, + 0x6276, + 0x48ba, + [0xba, 0x28, 0x07, 0x01, 0x43, 0xb4, 0x39, 0x2c], + ), + guid( + 0x05008617, + 0xfbfd, + 0x4051, + [0xa7, 0x90, 0x14, 0x48, 0x84, 0xb4, 0xf6, 0xa9], + ), +]; +const ADAPTER_IIDS: [Iid; 3] = [ + guid( + 0x2411e7e1, + 0x12ac, + 0x4ccf, + [0xbd, 0x14, 0x97, 0x98, 0xe8, 0x53, 0x4d, 0xc0], + ), + guid( + 0x29038f61, + 0x3839, + 0x4626, + [0x91, 0xfd, 0x08, 0x68, 0x79, 0x01, 0x1a, 0x05], + ), + guid( + 0x0aa1ae0a, + 0xfa0e, + 0x4b84, + [0x86, 0x44, 0xe0, 0x5f, 0xf8, 0xe5, 0xac, 0xb5], + ), +]; +const FACTORY_IIDS: [Iid; 3] = [ + guid( + 0x7b7166ec, + 0x21c7, + 0x44ae, + [0xb2, 0x1a, 0xc9, 0xae, 0x32, 0x1a, 0xe3, 0x69], + ), + guid( + 0x770aae78, + 0xf26f, + 0x4dba, + [0xa8, 0x29, 0x25, 0x3c, 0x83, 0xd1, 0xb3, 0x87], + ), + guid( + 0x50c83a1c, + 0xe072, + 0x4c48, + [0x87, 0xb0, 0x36, 0x30, 0xfa, 0x36, 0xa6, 0xd0], + ), +]; +const OUTPUT_IIDS: [Iid; 1] = [guid( + 0xae02eedb, + 0xc735, + 0x4690, + [0x8d, 0x52, 0x5a, 0x8d, 0xc2, 0x02, 0x13, 0xaa], +)]; + +static DEVICE: Object = Object::new(&DEVICE_FUNCTIONS); +static ADAPTER_OBJECT: Object = Object::new(&ADAPTER_FUNCTIONS); +static FACTORY_OBJECT: Object = Object::new(&FACTORY_FUNCTIONS); +static OUTPUT_OBJECT: Object = Object::new(&OUTPUT_FUNCTIONS); + +pub(crate) fn device() -> This { + &DEVICE +} + +/// `found` if `iid` is one of `known`. +fn query(kind: usize, iid: *const Iid, known: &[Iid], found: This, out: *mut This) -> HRESULT { + object::answer(kind, iid, object::is(iid, known).then_some(found), out) +} + +/// The DXGI device also answers for the D3D12 device. +extern "system" fn device_query(this: This, iid: *const Iid, out: *mut This) -> HRESULT { + if crate::device::is_device(iid) { + return object::answer(DXGI_DEVICE, iid, Some(crate::device::device()), out); + } + query(DXGI_DEVICE, iid, &DEVICE_IIDS, this, out) +} +extern "system" fn device_parent(_: This, iid: *const Iid, out: *mut This) -> HRESULT { + query(DXGI_DEVICE, iid, &ADAPTER_IIDS, &ADAPTER_OBJECT, out) +} +extern "system" fn device_adapter(_: This, out: *mut This) -> HRESULT { + object::answer(DXGI_DEVICE, &ADAPTER_IIDS[0], Some(&ADAPTER_OBJECT), out) +} + +extern "system" fn adapter_query(this: This, iid: *const Iid, out: *mut This) -> HRESULT { + query(ADAPTER, iid, &ADAPTER_IIDS, this, out) +} +extern "system" fn adapter_parent(_: This, iid: *const Iid, out: *mut This) -> HRESULT { + query(ADAPTER, iid, &FACTORY_IIDS, &FACTORY_OBJECT, out) +} +extern "system" fn adapter_outputs(_: This, index: u32, out: *mut This) -> HRESULT { + if index != 0 { + return NOT_FOUND; + } + object::answer(ADAPTER, &OUTPUT_IIDS[0], Some(&OUTPUT_OBJECT), out) +} + +#[repr(C)] +struct AdapterDescription { + name: [u16; 128], + vendor: u32, + device: u32, + subsystem: u32, + revision: u32, + dedicated_video_memory: usize, + dedicated_system_memory: usize, + shared_system_memory: usize, + luid: [u32; 2], +} +const _: () = assert!(size_of::() == 0x130); + +const AMD: u32 = 0x1002; + +extern "system" fn adapter_description(_: This, out: *mut AdapterDescription) -> HRESULT { + if out.is_null() { + return E_INVALIDARG; + } + let mut name = [0; 128]; + for (slot, unit) in name.iter_mut().zip("Leonida Legacy console GPU".encode_utf16()) { + *slot = unit; + } + // shortcut: memory sizes are the title's split (GPU-optimal, standard), + // not measured; revisit once memory is emulated. + let (gpu_optimal, standard) = crate::console::current().title_memory(); + let description = AdapterDescription { + name, + vendor: AMD, + device: 0, + subsystem: 0, + revision: 0, + dedicated_video_memory: gpu_optimal, + dedicated_system_memory: 0, + shared_system_memory: standard, + luid: [1, 0], + }; + // SAFETY: checked non-null; the title passes room for the description. + unsafe { out.write(description) }; + S_OK +} + +extern "system" fn factory_query(this: This, iid: *const Iid, out: *mut This) -> HRESULT { + query(FACTORY, iid, &FACTORY_IIDS, this, out) +} +extern "system" fn factory_adapters(_: This, index: u32, out: *mut This) -> HRESULT { + if index != 0 { + return NOT_FOUND; + } + object::answer(FACTORY, &ADAPTER_IIDS[0], Some(&ADAPTER_OBJECT), out) +} + +extern "system" fn output_query(this: This, iid: *const Iid, out: *mut This) -> HRESULT { + query(OUTPUT, iid, &OUTPUT_IIDS, this, out) +} +extern "system" fn output_parent(_: This, iid: *const Iid, out: *mut This) -> HRESULT { + query(OUTPUT, iid, &ADAPTER_IIDS, &ADAPTER_OBJECT, out) +} + +/// IUnknown 3, object 4, device 5 + 2 + 3. +static DEVICE_FUNCTIONS: Table<32> = { + let mut f = object::missing_table::(); + f[0] = device_query as *const (); + f[6] = device_parent as *const (); // 0x30 + f[7] = device_adapter as *const (); // 0x38 + Table(f) +}; + +/// IUnknown 3, object 4, adapter 3 + 1 + 1. +static ADAPTER_FUNCTIONS: Table<24> = { + let mut f = object::missing_table::(); + f[0] = adapter_query as *const (); + f[6] = adapter_parent as *const (); // 0x30 + f[7] = adapter_outputs as *const (); // 0x38 + f[8] = adapter_description as *const (); // 0x40 + Table(f) +}; + +/// IUnknown 3, object 4, factory 5 + 2 + 11. +static FACTORY_FUNCTIONS: Table<32> = { + let mut f = object::missing_table::(); + f[0] = factory_query as *const (); + f[7] = factory_adapters as *const (); // 0x38 + f[12] = factory_adapters as *const (); // 0x60, the same for version 1 + Table(f) +}; + +/// A display mode as the console lists it: size, refresh rate (numerator, +/// denominator), format, scanline order, scaling, flags. +#[repr(C)] +struct Mode { + width: u32, + height: u32, + refresh: [u32; 2], + format: u32, + scanlines: u32, + scaling: u32, + flags: u32, +} +const _: () = assert!(size_of::() == 32); + +/// The size of the display the console reports: `LEONIDA_DISPLAY_MODE=WxH` +/// if set (as a console reports the television it is plugged into: a +/// Series X on a 1080p set lists a 1080p mode), else 3840x2160. +/// shortcut: not yet the host display's own size by default; make it so +/// once a title is seen to render for the mode it is given. +fn display_size() -> (u32, u32) { + static SIZE: std::sync::OnceLock<(u32, u32)> = std::sync::OnceLock::new(); + *SIZE.get_or_init(|| { + let asked = std::env::var("LEONIDA_DISPLAY_MODE").ok().and_then(|v| { + let (w, h) = v.trim().split_once(['x', 'X'])?; + Some((w.trim().parse::().ok()?, h.trim().parse::().ok()?)) + }); + let size = match asked { + Some((w, h)) if (640..=7680).contains(&w) && (360..=4320).contains(&h) => (w, h), + _ => (3840, 2160), + }; + tracing::info!(width = size.0, height = size.1, "display mode reported to the title"); + size + }) +} + +/// The console's mode list: one 4K mode at 60 Hz (the title looks +/// for a 120 Hz one to allow 120 Hz frame intervals). +/// shortcut: fixed mode, not the host display's; report the host's rates if +/// a title paces by them. +extern "system" fn modes( + _: This, + _format: u32, + _flags: u32, + count: *mut u32, + out: *mut Mode, +) -> HRESULT { + // SAFETY: the title passes its count (null is tolerated). + let Some(count) = (unsafe { count.as_mut() }) else { + return E_INVALIDARG; + }; + if out.is_null() { + *count = 1; + return S_OK; + } + if *count < 1 { + return MORE_DATA; + } + *count = 1; + let (width, height) = display_size(); + let mode = Mode { + width, + height, + refresh: [60, 1], + format: 0, + scanlines: 1, // progressive + scaling: 0, + flags: 0, + }; + // SAFETY: checked non-null; room for `count` >= 1 modes. + unsafe { out.write(mode) }; + S_OK +} + +/// IUnknown 3, object 4, output 15 (12 as on PC, then 3 console ones). +static OUTPUT_FUNCTIONS: Table<32> = { + let mut f = object::missing_table::(); + f[0] = output_query as *const (); + f[6] = output_parent as *const (); // 0x30 + f[21] = modes as *const (); // 0xa8 + Table(f) +}; + +#[cfg(test)] +mod tests { + use super::*; + use crate::object::{E_NOINTERFACE, slot}; + + type Query = extern "system" fn(This, *const Iid, *mut This) -> HRESULT; + type Get = extern "system" fn(This, *mut This) -> HRESULT; + type Indexed = extern "system" fn(This, u32, *mut This) -> HRESULT; + type Describe = extern "system" fn(This, *mut AdapterDescription) -> HRESULT; + + /// Minecraft's startup: device → DXGI device (newest first) → adapter → + /// description, factory, first output. + #[test] + fn startup_walks_from_device_to_output() { + let d3d = crate::device::device(); + let newest_pc = guid( + 0x6007896c, + 0x3244, + 0x4afd, + [0xbf, 0x18, 0xa6, 0xd3, 0xbe, 0xda, 0x50, 0x23], + ); + let mut dxgi = std::ptr::null(); + let qi = slot::(d3d, 0); + assert_eq!(qi(d3d, &newest_pc, &mut dxgi), E_NOINTERFACE); + assert!(dxgi.is_null()); + assert_eq!(qi(d3d, &DEVICE_IIDS[2], &mut dxgi), S_OK); + assert_eq!(dxgi, device()); + + let mut adapter = std::ptr::null(); + assert_eq!(slot::(dxgi, 0x38)(dxgi, &mut adapter), S_OK); + let mut description = std::mem::MaybeUninit::::uninit(); + assert_eq!( + slot::(adapter, 0x40)(adapter, description.as_mut_ptr()), + S_OK + ); + // SAFETY: written above. + assert_eq!(unsafe { description.assume_init() }.vendor, AMD); + + let mut factory = std::ptr::null(); + let parent = slot::(adapter, 0x30); + assert_eq!(parent(adapter, &FACTORY_IIDS[2], &mut factory), S_OK); + let mut again = std::ptr::null(); + assert_eq!(slot::(factory, 0x38)(factory, 0, &mut again), S_OK); + assert_eq!(again, adapter); + + let mut output = std::ptr::null(); + let outputs = slot::(adapter, 0x38); + assert_eq!(outputs(adapter, 0, &mut output), S_OK); + assert!(!output.is_null()); + assert_eq!(outputs(adapter, 1, &mut output), NOT_FOUND); + } +} diff --git a/crates/leonida-gpu/src/fence.rs b/crates/leonida-gpu/src/fence.rs new file mode 100644 index 000000000..b82033550 --- /dev/null +++ b/crates/leonida-gpu/src/fence.rs @@ -0,0 +1,358 @@ +//! Fences: a 64-bit value and the events waiting for it. Nothing runs on a +//! GPU yet, so only signals (the title's, later our queues') move one. +#![allow(clippy::not_unsafe_ptr_arg_deref)] + +use std::ffi::c_void; +use std::sync::Mutex; +use std::sync::atomic::{AtomicU64, Ordering}; + +use crate::object::{self, E_NOTIMPL, FENCE, HRESULT, Iid, Object, S_OK, Table, This, guid}; +use crate::resource::PAGEABLE_IIDS; + +pub(crate) const FENCE_IIDS: [Iid; 4] = [ + guid( + 0x0a753dcf, + 0xc4d8, + 0x4b91, + [0xad, 0xf6, 0xbe, 0x5a, 0x60, 0xd9, 0x5a, 0x76], + ), + PAGEABLE_IIDS[0], + PAGEABLE_IIDS[1], + PAGEABLE_IIDS[2], +]; + +#[repr(C)] +struct Fence { + object: Object, + /// Titles also read it straight from memory, at the fence's GPU + /// address. + value: AtomicU64, + flags: u32, + /// Events to set once the value reaches theirs (handles as integers). + waiters: Mutex>, + /// For [`pace`]: when each wait above was asked for. + #[cfg(all(windows, feature = "diagnostics"))] + asked: Mutex>, +} + +fn fence<'a>(this: This) -> &'a Fence { + // SAFETY: called from fence methods only. + unsafe { &*this.cast::() } +} + +pub(crate) extern "system" fn create( + _: This, + initial: u64, + flags: u32, + iid: *const Iid, + out: *mut This, +) -> HRESULT { + tracing::debug!(initial, flags, "fence"); + let fence = Box::new(Fence { + object: Object::new(&FUNCTIONS), + value: AtomicU64::new(initial), + flags, + waiters: Mutex::new(Vec::new()), + #[cfg(all(windows, feature = "diagnostics"))] + asked: Mutex::new(Vec::new()), + }); + object::hand_out(FENCE, fence, iid, &FENCE_IIDS, out) +} + +fn set_event(event: usize) { + #[cfg(windows)] + // SAFETY: the title passed an event handle. + unsafe { + windows_sys::Win32::System::Threading::SetEvent(event as *mut c_void) + }; + #[cfg(not(windows))] + let _ = event; +} + +extern "system" fn query(this: This, iid: *const Iid, out: *mut This) -> HRESULT { + object::answer( + FENCE, + iid, + object::is(iid, &FENCE_IIDS).then_some(this), + out, + ) +} +extern "system" fn release(this: This) -> u32 { + object::release_boxed::(this) +} +pub(crate) extern "system" fn completed(this: This) -> u64 { + fence(this).value.load(Ordering::Acquire) +} +extern "system" fn set_event_on_completion(this: This, value: u64, event: *mut c_void) -> HRESULT { + let fence = fence(this); + let mut waiters = fence.waiters.lock().unwrap_or_else(|e| e.into_inner()); + if fence.value.load(Ordering::Acquire) >= value { + if !event.is_null() { + set_event(event as usize); + } + #[cfg(all(windows, feature = "diagnostics"))] + pace::ready(); + return S_OK; + } + #[cfg(all(windows, feature = "diagnostics"))] + pace::waits(this, &fence.asked, value, fence.value.load(Ordering::Acquire)); + if event.is_null() { + // With submissions sent to the card and not waited for + // (`crate::host::late`) the signal may be behind them: they are + // settled, which sets it. + #[cfg(windows)] + if crate::host::late() { + drop(waiters); + crate::host::settle_for_fence(); + if fence.value.load(Ordering::Acquire) >= value { + return S_OK; + } + tracing::warn!(value, "blocking fence wait not implemented"); + return E_NOTIMPL; + } + // shortcut: a null event means "block until reached"; nothing can + // reach it while no GPU work runs, so fail instead of hanging. + tracing::warn!(value, "blocking fence wait not implemented"); + return E_NOTIMPL; + } + waiters.push((value, event as usize)); + S_OK +} +/// Moves the fence to `value` and sets the events that waited for it. +pub(crate) fn set(this: This, value: u64) { + let fence = fence(this); + let mut waiters = fence.waiters.lock().unwrap_or_else(|e| e.into_inner()); + fence.value.store(value, Ordering::Release); + #[cfg(all(windows, feature = "diagnostics"))] + pace::reached(this, &fence.asked, value); + waiters.retain(|&(wanted, event)| { + let reached = wanted <= value; + if reached { + set_event(event); + } + !reached + }); +} +pub(crate) extern "system" fn signal(this: This, value: u64) -> HRESULT { + set(this, value); + // A queue may have waited for it: what it held runs now. + #[cfg(windows)] + crate::queue::release_held(false); + S_OK +} + +extern "system" fn creation_flags(this: This) -> u32 { + fence(this).flags +} +/// Where the value lives (GPU addresses are CPU addresses). +extern "system" fn gpu_address(this: This) -> u64 { + (&raw const fence(this).value) as u64 +} + +/// How the title paces itself on its fences, measured (diagnostics +/// builds): which value it waits for, how long until our line gets the +/// fence there, and how many frames lie between the title's `Signal` on +/// its queue and the fence being set. Run 233 put presents behind the +/// line and the frame did not get shorter: the title waited somewhere +/// else, and this says for what. +#[cfg(all(windows, feature = "diagnostics"))] +pub(crate) mod pace { + use std::sync::Mutex; + use std::sync::atomic::{AtomicU32, AtomicU64, Ordering}; + use std::time::Instant; + + use crate::object::This; + + pub(crate) struct Asked { + value: u64, + at: Instant, + frame: u64, + thread: u32, + } + + /// The title's `Signal` calls on a queue not yet at the fence: + /// fence, value, when, frame. + static QUEUED: Mutex> = Mutex::new(Vec::new()); + /// The thread that presents. + static RENDER: AtomicU32 = AtomicU32::new(0); + /// Since the last line: waits already met; waits not met; of those, + /// the render thread's; reached waits, their microseconds, their + /// frames between; the render thread's reached waits and microseconds; + /// signals set, their microseconds since the title's call, their + /// frames between. + static N: [AtomicU64; 11] = [const { AtomicU64::new(0) }; 11]; + static SAID: AtomicU64 = AtomicU64::new(0); + static LINE_AT: AtomicU64 = AtomicU64::new(0); + + /// Whether events are said one by one now: four seconds of every two + /// minutes of the wall clock, the same seconds in which the loader says + /// the title's `mwaitx` waits (`console_insn`), to lay the two side by side. + fn detail_now() -> bool { + std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).is_ok_and(|d| d.as_secs() % 120 < 4) + } + + fn thread() -> u32 { + // SAFETY: a plain query. + unsafe { windows_sys::Win32::System::Threading::GetCurrentThreadId() } + } + + pub(super) fn ready() { + N[0].fetch_add(1, Ordering::Relaxed); + } + + pub(super) fn waits(fence: This, asked: &Mutex>, value: u64, now: u64) { + let thread = thread(); + let render = thread == RENDER.load(Ordering::Relaxed); + N[1].fetch_add(1, Ordering::Relaxed); + if render { + N[2].fetch_add(1, Ordering::Relaxed); + } + let frame = crate::queue::presented(); + if detail_now() || SAID.fetch_add(1, Ordering::Relaxed) < 48 { + tracing::info!( + "pace: the title waits for fence {fence:?} value {value} (it is at {now}) in frame {frame}, on {}", + if render { "the render thread".to_string() } else { format!("thread {thread}") } + ); + } + let mut asked = asked.lock().unwrap_or_else(|e| e.into_inner()); + if asked.len() < 4096 { + asked.push(Asked { value, at: Instant::now(), frame, thread }); + } + } + + /// The title called `Signal` for `fence` on a queue. + pub(crate) fn signal_called(fence: usize, value: u64) { + let mut queued = QUEUED.lock().unwrap_or_else(|e| e.into_inner()); + if queued.len() < 4096 { + queued.push((fence, value, Instant::now(), crate::queue::presented())); + } + } + + pub(super) fn reached(fence: This, asked: &Mutex>, value: u64) { + let frame = crate::queue::presented(); + let render = RENDER.load(Ordering::Relaxed); + { + let mut queued = QUEUED.lock().unwrap_or_else(|e| e.into_inner()); + queued.retain(|&(f, v, at, called)| { + let done = f == fence as usize && v <= value; + if done { + N[8].fetch_add(1, Ordering::Relaxed); + N[9].fetch_add(at.elapsed().as_micros() as u64, Ordering::Relaxed); + N[10].fetch_add(frame.saturating_sub(called), Ordering::Relaxed); + if detail_now() || SAID.fetch_add(1, Ordering::Relaxed) < 48 { + tracing::info!( + "pace: fence {fence:?} is set to {v}, {:.1} ms after the title's Signal for it (called in frame {called}, set in frame {frame})", + at.elapsed().as_micros() as f64 / 1e3 + ); + } + } + !done + }); + } + let mut asked = asked.lock().unwrap_or_else(|e| e.into_inner()); + asked.retain(|a| { + let done = a.value <= value; + if done { + let us = a.at.elapsed().as_micros() as u64; + N[3].fetch_add(1, Ordering::Relaxed); + N[4].fetch_add(us, Ordering::Relaxed); + N[5].fetch_add(frame.saturating_sub(a.frame), Ordering::Relaxed); + if a.thread == render { + N[6].fetch_add(1, Ordering::Relaxed); + N[7].fetch_add(us, Ordering::Relaxed); + } + if detail_now() || SAID.fetch_add(1, Ordering::Relaxed) < 48 { + tracing::info!( + "pace: fence {fence:?} reached {} {:.1} ms after the wait for it (asked in frame {}, reached in frame {frame})", + a.value, + us as f64 / 1e3, + a.frame + ); + } + } + !done + }); + } + + /// Once a frame, on the thread that presents: a line every 256 frames. + pub(crate) fn frame() { + RENDER.store(thread(), Ordering::Relaxed); + let frame = crate::queue::presented(); + let last = LINE_AT.load(Ordering::Relaxed); + if frame < last + 256 { + return; + } + LINE_AT.store(frame, Ordering::Relaxed); + let n: Vec = N.iter().map(|n| n.swap(0, Ordering::Relaxed) as f64).collect(); + let frames = (frame - last).max(1) as f64; + let per = |a: f64, b: f64| if b > 0.0 { a / b } else { 0.0 }; + tracing::info!( + "pace, per frame: fence waits already met {:.2}, not met {:.2} (the render thread's {:.2}); a wait is met {:.1} ms and {:.2} frames after it was asked \ + (the render thread's: {:.1} ms, {:.1} ms a frame); the title's queue signals: {:.2} a frame, a fence is set {:.1} ms and {:.2} frames after the title's Signal call", + n[0] / frames, + n[1] / frames, + n[2] / frames, + per(n[4], n[3]) / 1e3, + per(n[5], n[3]), + per(n[7], n[6]) / 1e3, + n[7] / frames / 1e3, + n[8] / frames, + per(n[9], n[8]) / 1e3, + per(n[10], n[8]), + ); + } +} + +/// IUnknown 3, object 4, device child 1, fence 3, fence 1 (2, a console +/// one among them). +static FUNCTIONS: Table<24> = { + let mut f = object::d3d12_object(object::missing_table::()); + f[0] = query as *const (); + f[2] = release as *const (); + f[7] = object::parent_device as *const (); // 0x38 + f[8] = completed as *const (); // 0x40 + f[9] = set_event_on_completion as *const (); // 0x48 + f[10] = signal as *const (); // 0x50 + f[11] = creation_flags as *const (); // 0x58 + f[12] = gpu_address as *const (); // 0x60 + Table(f) +}; + +#[cfg(test)] +mod tests { + use super::*; + use crate::object::slot; + + #[cfg(windows)] + #[test] + fn signals_set_waiting_events() { + use windows_sys::Win32::Foundation::{CloseHandle, WAIT_OBJECT_0}; + use windows_sys::Win32::System::Threading::{CreateEventW, WaitForSingleObject}; + + let mut f = std::ptr::null(); + assert_eq!(create(std::ptr::null(), 1, 0, &FENCE_IIDS[0], &mut f), S_OK); + assert_eq!(slot:: u64>(f, 0x40)(f), 1); + // SAFETY: plain auto-reset event. + let event = unsafe { CreateEventW(std::ptr::null(), 0, 0, std::ptr::null()) }; + assert!(!event.is_null()); + let wait = slot:: HRESULT>(f, 0x48); + let signal = slot:: HRESULT>(f, 0x50); + assert_eq!(wait(f, 5, event), S_OK); + // SAFETY: a valid event. + assert_ne!(unsafe { WaitForSingleObject(event, 0) }, WAIT_OBJECT_0); + assert_eq!(signal(f, 5), S_OK); + // SAFETY: as above. + assert_eq!(unsafe { WaitForSingleObject(event, 0) }, WAIT_OBJECT_0); + assert_eq!(wait(f, 5, event), S_OK, "already reached"); + // SAFETY: as above. + assert_eq!(unsafe { WaitForSingleObject(event, 0) }, WAIT_OBJECT_0); + assert_eq!(wait(f, 9, std::ptr::null_mut()), E_NOTIMPL); + // The title reads the value at the fence's address. + let at = slot:: u64>(f, 0x60)(f); + // SAFETY: the fence's value. + assert_eq!(unsafe { *(at as *const u64) }, 5); + // SAFETY: ours. + unsafe { CloseHandle(event) }; + assert_eq!(slot:: u32>(f, 0x10)(f), 0); + } +} diff --git a/crates/leonida-gpu/src/fpsbox.rs b/crates/leonida-gpu/src/fpsbox.rs new file mode 100644 index 000000000..cc2e00b47 --- /dev/null +++ b/crates/leonida-gpu/src/fpsbox.rs @@ -0,0 +1,270 @@ +//! The frame rate, drawn into the top left corner of every frame shown. +//! +//! The window's caption has the frame rate, but a capture of the window's +//! picture (a stream) does not carry the caption. Here the number is part +//! of the picture: a small box of text copied onto the swap chain's back +//! buffer right after the title's frame, before it is presented. The +//! title's own frame is not touched, so saved frames and everything read +//! back from it are as before. +//! +//! The text is drawn on the CPU with a font of its own (5 by 7 dots a +//! glyph) into a buffer the card copies from; a buffer is made once for a +//! text and never written again, so a present still in the air reads what +//! it was recorded with. On by default; `LEONIDA_FPS_COUNTER=0` leaves the +//! frame as the title drew it. + +use std::collections::HashMap; +use std::sync::Mutex; +use std::sync::atomic::{AtomicU32, Ordering}; + +use windows::Win32::Graphics::Direct3D12::*; +use windows::Win32::Graphics::Dxgi::Common::*; + +/// The frame rate in tenths of a frame a second, as last measured (once a +/// second, by the presenter's meter); `u32::MAX` before the first. +static TENTHS: AtomicU32 = AtomicU32::new(u32::MAX); + +/// Whether the counter is drawn. +fn on() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("LEONIDA_FPS_COUNTER").is_none_or(|v| v != "0")) +} + +/// The frame rate just measured. +pub(crate) fn set(fps: f64) { + if fps.is_finite() && fps >= 0.0 { + TENTHS.store((fps * 10.0).round().min(99_999.0) as u32, Ordering::Relaxed); + } +} + +/// A glyph's seven rows, five dots each (bit 4 is the left one). +fn glyph(c: char) -> [u8; 7] { + match c { + '0' => [0b01110, 0b10001, 0b10011, 0b10101, 0b11001, 0b10001, 0b01110], + '1' => [0b00100, 0b01100, 0b00100, 0b00100, 0b00100, 0b00100, 0b01110], + '2' => [0b01110, 0b10001, 0b00001, 0b00010, 0b00100, 0b01000, 0b11111], + '3' => [0b11110, 0b00001, 0b00001, 0b01110, 0b00001, 0b00001, 0b11110], + '4' => [0b00010, 0b00110, 0b01010, 0b10010, 0b11111, 0b00010, 0b00010], + '5' => [0b11111, 0b10000, 0b11110, 0b00001, 0b00001, 0b10001, 0b01110], + '6' => [0b00110, 0b01000, 0b10000, 0b11110, 0b10001, 0b10001, 0b01110], + '7' => [0b11111, 0b00001, 0b00010, 0b00100, 0b01000, 0b01000, 0b01000], + '8' => [0b01110, 0b10001, 0b10001, 0b01110, 0b10001, 0b10001, 0b01110], + '9' => [0b01110, 0b10001, 0b10001, 0b01111, 0b00001, 0b00010, 0b01100], + '.' => [0, 0, 0, 0, 0, 0b01100, 0b01100], + 'F' => [0b11111, 0b10000, 0b10000, 0b11110, 0b10000, 0b10000, 0b10000], + 'P' => [0b11110, 0b10001, 0b10001, 0b11110, 0b10000, 0b10000, 0b10000], + 'S' => [0b01111, 0b10000, 0b10000, 0b01110, 0b00001, 0b00001, 0b11110], + _ => [0; 7], + } +} + +/// The text for a frame rate in tenths. +fn text(tenths: u32) -> String { + format!("{}.{} FPS", tenths / 10, tenths % 10) +} + +/// Bytes a pixel of a swap chain format this layer presents in, or none. +fn pixel_bytes(format: DXGI_FORMAT) -> Option { + match format { + DXGI_FORMAT_R8G8B8A8_UNORM | DXGI_FORMAT_B8G8R8A8_UNORM | DXGI_FORMAT_R10G10B10A2_UNORM => Some(4), + DXGI_FORMAT_R16G16B16A16_FLOAT => Some(8), + _ => None, + } +} + +/// One pixel of `format`: of the text (`lit`) or of the box behind it. +fn pixel(format: DXGI_FORMAT, lit: bool, out: &mut [u8]) { + // The text: a bright yellow. The box: nearly black. + let (r, g, b): (f32, f32, f32) = if lit { (1.0, 0.92, 0.16) } else { (0.03, 0.03, 0.03) }; + let byte = |v: f32| (v * 255.0).round() as u8; + match format { + DXGI_FORMAT_R8G8B8A8_UNORM => out.copy_from_slice(&[byte(r), byte(g), byte(b), 255]), + DXGI_FORMAT_B8G8R8A8_UNORM => out.copy_from_slice(&[byte(b), byte(g), byte(r), 255]), + DXGI_FORMAT_R10G10B10A2_UNORM => { + let ten = |v: f32| (v * 1023.0).round() as u32; + out.copy_from_slice(&(ten(r) | ten(g) << 10 | ten(b) << 20 | 3 << 30).to_le_bytes()); + } + _ => { + for (i, v) in [r, g, b, 1.0].into_iter().enumerate() { + out[i * 2..i * 2 + 2].copy_from_slice(&half(v).to_le_bytes()); + } + } + } +} + +/// A value from 0 to 1 as a 16-bit float. +fn half(v: f32) -> u16 { + let bits = v.clamp(0.0, 1.0).to_bits(); + if v <= 0.0 { + return 0; + } + // Sign 0; the exponent moves from a bias of 127 to one of 15; the top + // ten bits of the fraction stay. Values under 2^-14 (none of ours) are 0. + let exponent = ((bits >> 23) & 0xFF) as i32 - 127 + 15; + if exponent <= 0 { + return 0; + } + ((exponent as u32) << 10 | (bits >> 13) & 0x3FF) as u16 +} + +/// The box for `text` at `scale` dots a pixel: its width and height in +/// pixels and, row by row from the top, whether each pixel is text. +fn bitmap(text: &str, scale: u32) -> (u32, u32, Vec) { + let chars: Vec = text.chars().collect(); + let pad = 2 * scale; + let width = 2 * pad + chars.len() as u32 * 6 * scale - scale; + let height = 2 * pad + 7 * scale; + let mut lit = vec![false; (width * height) as usize]; + for (i, &c) in chars.iter().enumerate() { + let rows = glyph(c); + for (row, bits) in rows.into_iter().enumerate() { + for column in 0..5u32 { + if bits >> (4 - column) & 1 == 0 { + continue; + } + let (x0, y0) = (pad + (i as u32 * 6 + column) * scale, pad + row as u32 * scale); + for y in y0..y0 + scale { + for x in x0..x0 + scale { + lit[(y * width + x) as usize] = true; + } + } + } + } + } + (width, height, lit) +} + +/// A buffer the card copies a text's box from, with its footprint. +struct Made { + buffer: ID3D12Resource, + width: u32, + height: u32, + pitch: u32, +} + +// SAFETY: a free-threaded D3D12 object and plain numbers. +unsafe impl Send for Made {} + +/// The boxes made so far, by text, format and scale. +static MADE: Mutex>> = Mutex::new(None); + +/// Copies the frame rate's box onto `back`, a back buffer of `width` by +/// `height` pixels of `format` that `list` holds as a copy's destination. +/// Nothing if the counter is off, no rate was measured yet, the format is +/// not one of ours or the frame is too small for the box. +pub(crate) fn draw(host: &crate::host::Host, list: &ID3D12GraphicsCommandList, back: &ID3D12Resource, (width, height, format): (u32, u32, DXGI_FORMAT)) { + if !on() { + return; + } + let tenths = TENTHS.load(Ordering::Relaxed); + let Some(bytes) = pixel_bytes(format).filter(|_| tenths != u32::MAX) else { + return; + }; + // About a fortieth of the frame's height a glyph: 6 dots a pixel at + // 2160 lines, 3 at 1080. + let scale = (height / 360).clamp(2, 12); + let mut made = MADE.lock().unwrap_or_else(|e| e.into_inner()); + let made = made.get_or_insert_with(HashMap::new); + if made.len() > 2048 { + // (Every text is a buffer of a few hundred KiB; a rate that wanders + // over thousands of values is not expected.) + made.clear(); + } + let key = (tenths, format.0, scale); + if !made.contains_key(&key) { + let (w, h, lit) = bitmap(&text(tenths), scale); + let pitch = (w as usize * bytes).next_multiple_of(D3D12_TEXTURE_DATA_PITCH_ALIGNMENT as usize); + let Some((buffer, data)) = host.shared_buffer((pitch * h as usize) as u64) else { + return; + }; + // SAFETY: the buffer's own mapped bytes, `pitch * h` of them. + let out = unsafe { std::slice::from_raw_parts_mut(data, pitch * h as usize) }; + for y in 0..h as usize { + for x in 0..w as usize { + let at = y * pitch + x * bytes; + pixel(format, lit[y * w as usize + x], &mut out[at..at + bytes]); + } + } + made.insert(key, Made { buffer, width: w, height: h, pitch: pitch as u32 }); + } + let Some(m) = made.get(&key) else { + return; + }; + let margin = 4 * scale; + if m.width + 2 * margin > width || m.height + 2 * margin > height { + return; + } + // SAFETY: an open list; the back buffer is a copy's destination in it + // and the box lies inside it; our buffer holds `pitch * height` bytes + // and is kept for as long as the process runs. + unsafe { + let from = D3D12_TEXTURE_COPY_LOCATION { + pResource: std::mem::transmute_copy(&m.buffer), + Type: D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT, + Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { + PlacedFootprint: D3D12_PLACED_SUBRESOURCE_FOOTPRINT { + Offset: 0, + Footprint: D3D12_SUBRESOURCE_FOOTPRINT { Format: format, Width: m.width, Height: m.height, Depth: 1, RowPitch: m.pitch }, + }, + }, + }; + let to = D3D12_TEXTURE_COPY_LOCATION { + pResource: std::mem::transmute_copy(back), + Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, + Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { SubresourceIndex: 0 }, + }; + list.CopyTextureRegion(&to, margin, margin, 0, &from, None); + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn the_text_is_the_rate_to_a_tenth() { + assert_eq!(text(103), "10.3 FPS"); + assert_eq!(text(7), "0.7 FPS"); + assert_eq!(text(300), "30.0 FPS"); + } + + #[test] + fn the_box_holds_every_glyph_with_a_margin() { + let (w, h, lit) = bitmap("10.3 FPS", 3); + // Eight glyphs of five dots and seven gaps of one, a pad of two dots all round. + assert_eq!((w, h), ((8 * 5 + 7 + 4) * 3, (7 + 4) * 3)); + assert_eq!(lit.len(), (w * h) as usize); + // The pad is box, not text; the "1" has its stem lit. + assert!(lit[..(w * 6) as usize].iter().all(|&l| !l), "the top pad"); + assert!((0..h).all(|y| !lit[(y * w) as usize] && !lit[(y * w + w - 1) as usize]), "the side pads"); + let at = |x: u32, y: u32| lit[(y * w + x) as usize]; + // Glyph 0 ("1"): dot column 2 of row 0 is lit, column 0 is not. + assert!(at(6 + 2 * 3, 6) && !at(6, 6)); + // A space lights nothing: glyph 4. + assert!((0..7 * 3).all(|y| (0..5 * 3).all(|x| !at(6 + 4 * 18 + x, 6 + y)))); + // Every glyph used has at least one dot, but the space. + for c in "0123456789.FPS".chars() { + assert!(glyph(c).iter().any(|&r| r != 0), "{c}"); + } + } + + #[test] + fn pixels_are_in_the_formats_the_layer_presents_in() { + let mut four = [0u8; 4]; + pixel(DXGI_FORMAT_R8G8B8A8_UNORM, true, &mut four); + assert_eq!(four, [255, 235, 41, 255]); + pixel(DXGI_FORMAT_B8G8R8A8_UNORM, true, &mut four); + assert_eq!(four, [41, 235, 255, 255]); + pixel(DXGI_FORMAT_R10G10B10A2_UNORM, true, &mut four); + let v = u32::from_le_bytes(four); + assert_eq!((v & 1023, v >> 10 & 1023, v >> 20 & 1023, v >> 30), (1023, 941, 164, 3)); + let mut eight = [0u8; 8]; + pixel(DXGI_FORMAT_R16G16B16A16_FLOAT, true, &mut eight); + assert_eq!(u16::from_le_bytes([eight[0], eight[1]]), 0x3C00, "1.0 as a half"); + assert_eq!(u16::from_le_bytes([eight[6], eight[7]]), 0x3C00); + assert_eq!(half(0.5), 0x3800); + assert_eq!(half(0.0), 0); + assert_eq!(pixel_bytes(DXGI_FORMAT_R16G16B16A16_FLOAT), Some(8)); + assert_eq!(pixel_bytes(DXGI_FORMAT_D32_FLOAT), None); + } +} diff --git a/crates/leonida-gpu/src/frame.rs b/crates/leonida-gpu/src/frame.rs new file mode 100644 index 000000000..aed2359ab --- /dev/null +++ b/crates/leonida-gpu/src/frame.rs @@ -0,0 +1,252 @@ +//! Frame pacing: the title sets a frame interval and waits for each frame +//! to begin. Ours is a clock started by the first interval set, ticking +//! once per interval; the token is the frame number. Each event kind +//! (origin, vblank, flip) happens once per tick, so two waits for the same +//! kind never end on the same tick: the title polls the origin +//! with "token on time-out" (starting its next frame at once) and is paced +//! by a blocking wait for the flip before each present. +//! +//! shortcut: event offsets are ignored (every event is at the tick); tie +//! the clock to presentation if a title paces by them. +#![allow(clippy::not_unsafe_ptr_arg_deref)] + +use std::sync::Mutex; +use std::sync::atomic::{AtomicU64, Ordering}; +use std::time::{Duration, Instant}; + +use crate::object::{HRESULT, S_FALSE, S_OK, This}; + +/// What a wait returns when its time is up first. +const TIMEOUT: HRESULT = S_FALSE; +/// The frame-origin event: the one that starts frames and makes tokens. +const ORIGIN: u32 = 0; +/// Make the frame's token even if the wait times out (the title starts the +/// frame early). +const TOKEN_ON_TIMEOUT: u32 = 2; +const SIXTIETH: Duration = Duration::from_micros(16_667); + +struct Clock { + start: Instant, + interval: Duration, + /// The tick number at `start` (ticks go on across interval changes). + first: u64, +} + +static CLOCK: Mutex> = Mutex::new(None); +static FRAME: AtomicU64 = AtomicU64::new(0); + +fn clock() -> std::sync::MutexGuard<'static, Option> { + CLOCK.lock().unwrap_or_else(|e| e.into_inner()) +} + +/// Device method: a frame every `length` microseconds. The period is how +/// many intervals a frame may take to reach the display (pipeline depth), +/// not part of the rate. +pub(crate) extern "system" fn set_interval( + _: This, + _output: This, + length: u32, + _period: u32, + _flags: u32, +) -> HRESULT { + let interval = match length { + 0 => SIXTIETH, + us => Duration::from_micros(u64::from(us)), + }; + tracing::info!(?interval, "frame interval"); + // A new interval starts from now, after the last tick handed out. + let first = LAST + .iter() + .map(|t| t.load(Ordering::Relaxed)) + .max() + .unwrap_or(0); + *clock() = Some(Clock { + start: Instant::now(), + interval, + first, + }); + S_OK +} + +/// Device method: events are scheduled at every tick. +pub(crate) extern "system" fn schedule( + _: This, + _kind: u32, + _offset: u32, + _list: *const u8, + _flags: u32, +) -> HRESULT { + S_OK +} + +/// Frames begun so far (frame waits that ended). +pub(crate) fn current() -> u64 { + FRAME.load(Ordering::Relaxed) +} + +/// Per event kind (origin, vblank, flip and later kinds): the last tick a +/// wait for it ended on. +static LAST: [AtomicU64; 3] = [const { AtomicU64::new(0) }; 3]; + +fn last(kind: u32) -> &'static AtomicU64 { + &LAST[(kind as usize).min(LAST.len() - 1)] +} + +/// The next tick after now and after the last one a wait for `kind` ended +/// on (an event happens once per tick: a wait woken a little early must not +/// let the next one end on the same tick), and how long until it. +fn next_tick(kind: u32) -> (u64, Duration) { + let mut clock = clock(); + let c = clock.get_or_insert_with(|| Clock { + start: Instant::now(), + interval: SIXTIETH, + first: 0, + }); + let elapsed = c.start.elapsed().as_nanos(); + let interval = c.interval.as_nanos().max(1); + let tick = + (c.first + (elapsed / interval + 1) as u64).max(last(kind).load(Ordering::Relaxed) + 1); + let at = u128::from(tick - c.first) * interval; + ( + tick, + Duration::from_nanos(at.saturating_sub(elapsed) as u64), + ) +} + +/// Device method: blocks until the next tick (or the time-out); an origin +/// wait then hands out the new frame's token. Other events keep the token +/// the title passes. Ticks are absolute (start plus whole intervals), so +/// lateness never accumulates. +pub(crate) extern "system" fn wait( + _: This, + kind: u32, + timeout_ms: u32, + _list: *const u8, + flags: u32, + token: *mut u64, +) -> HRESULT { + let origin = kind == ORIGIN; + let (mut tick, mut wait) = next_tick(kind); + let limit = Duration::from_millis(u64::from(timeout_ms)); + // A blocking wait for an event that has happened since the last wait + // for it ended (a frame took longer than a tick) ends at once, on the + // tick that passed: sleeping on to the next one cost 17 ms of every + // 730 ms frame (run 58: "2.0 frame waits sleeping 16.8 ms"). Polls (a + // time-out shorter than a tick) answer as before. + // `LEONIDA_LATE_WAITS=1` sleeps to the next tick, as before. + static SLEEP: std::sync::OnceLock = std::sync::OnceLock::new(); + if !*SLEEP.get_or_init(|| std::env::var_os("LEONIDA_LATE_WAITS").is_some_and(|v| v == "1")) + && limit >= wait + && tick > last(kind).load(Ordering::Relaxed) + 1 + { + tick -= 1; + wait = Duration::ZERO; + } + let hr = if wait > limit { + std::thread::sleep(limit); + TIMEOUT + } else { + std::thread::sleep(wait); + last(kind).fetch_max(tick, Ordering::Relaxed); + S_OK + }; + #[cfg(windows)] + { + let us = wait.min(limit).as_micros() as u64; + crate::framelog::add(crate::framelog::T::PaceUs, us); + crate::framelog::here(crate::framelog::H::PaceUs, us); + } + #[cfg(all(windows, feature = "diagnostics"))] + { + use crate::copystat::{C, add}; + add(C::PaceWaits, 1); + add(C::PaceUs, wait.min(limit).as_micros() as u64); + } + // A frame begun on a time-out takes no tick: its flip still does. + if origin && (hr == S_OK || flags & TOKEN_ON_TIMEOUT != 0) { + // Tokens count frames (consecutive), not ticks. + let frame = FRAME.fetch_add(1, Ordering::Relaxed) + 1; + if !token.is_null() { + // SAFETY: checked non-null; the title passes its token. + unsafe { token.write(frame) }; + } + } + #[cfg(feature = "diagnostics")] + tracing::debug!( + kind, + timeout_ms, + flags, + hr, + tick, + wait_us = wait.as_micros() as u64, + frame = current(), + "frame wait" + ); + hr +} + +/// Device method: no statistics are kept, so none are returned. +pub(crate) extern "system" fn statistics( + _: This, + _token: u64, + _kinds: u32, + count: *mut u32, + _out: *mut u8, +) -> HRESULT { + if !count.is_null() { + // SAFETY: checked non-null. + unsafe { count.write(0) }; + } + S_OK +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn waits_end_on_ticks_and_count_frames() { + let null = std::ptr::null(); + assert_eq!(set_interval(null, null, 2_000, 1, 0), S_OK); + let mut first = 0; + assert_eq!(wait(null, 0, 1_000, std::ptr::null(), 0, &mut first), S_OK); + let before = Instant::now(); + let mut second = 0; + assert_eq!(wait(null, 0, 1_000, std::ptr::null(), 0, &mut second), S_OK); + assert!(second > first); + assert!(before.elapsed() <= Duration::from_millis(50)); + assert_eq!(wait(null, 0, 0, std::ptr::null(), 0, &mut second), TIMEOUT); + // Tokens count frames, a frame started early on a time-out too. + let mut early = 0; + let flags = TOKEN_ON_TIMEOUT; + assert_eq!( + wait(null, 0, 0, std::ptr::null(), flags, &mut early), + TIMEOUT + ); + let mut next = 0; + assert_eq!(wait(null, 0, 1_000, std::ptr::null(), 0, &mut next), S_OK); + assert!(early == second + 1 && next == early + 1); + assert!(LAST[0].load(Ordering::Relaxed) >= 2); + + // The title's loop (the clock is global, so in the same test): an + // origin poll that times out (and starts the frame), then a + // blocking flip wait. Each flip takes its own tick. + const FLIP: u32 = 2; + assert_eq!(set_interval(null, null, 5_000, 3, 0), S_OK); + let mut token = 0; + let flips: Vec = (0..4) + .map(|_| { + let _ = wait(null, 0, 0, std::ptr::null(), TOKEN_ON_TIMEOUT, &mut token); + assert_eq!( + wait(null, FLIP, u32::MAX, std::ptr::null(), 0, &mut token), + S_OK + ); + LAST[2].load(Ordering::Relaxed) + }) + .collect(); + assert!(flips.windows(2).all(|w| w[1] == w[0] + 1), "{flips:?}"); + // Even when a flip wait begins on the tick another just ended on. + let (tick, _) = next_tick(FLIP); + assert!(tick > flips[3]); + } +} diff --git a/crates/leonida-gpu/src/framelog.rs b/crates/leonida-gpu/src/framelog.rs new file mode 100644 index 000000000..22ccb164c --- /dev/null +++ b/crates/leonida-gpu/src/framelog.rs @@ -0,0 +1,655 @@ +//! Every frame's length, and what the long ones were made of. +//! +//! The frame-rate line averages over a second or more, and its counters +//! are reset at each line: a single long frame is lost in it, and so is +//! what that frame was made of. Run 222's dips (150 ms frames with some of +//! 250 to 500 ms among them) could not be placed from those lines. +//! +//! Here every counter runs from the start and is never reset. At the end +//! of each present call the totals are read, and their differences since +//! the present before are that frame's. Every five seconds one line gives +//! the frame times (each one, the shortest, the median, the longest), one +//! gives the usual frame's make-up (the mean of the frames that were not +//! long), and each long frame gets a line of its own in the same form, so +//! a long frame is read against a usual one column by column. +//! +//! On by default in diagnostics builds, off in others; +//! `LEONIDA_FRAME_LOG=1` or `0` says otherwise. The counters themselves +//! are plain atomic adds in every build. + +use std::sync::Mutex; +use std::sync::atomic::{AtomicU64, Ordering::Relaxed}; + +/// Totals since the start (microseconds unless said otherwise). +#[derive(Clone, Copy)] +#[repr(usize)] +pub enum T { + /// The title's present call, all of it; of it, running the queues' + /// lines and settling submissions before our copy; and our copy to the + /// window with the host's present. + PresentUs, + PresentLineUs, + PresentShowUs, + /// The title's submit calls (`queue::execute`), on every thread. + ExecuteUs, + /// The submit thread of ours (`LEONIDA_ASYNC_SUBMIT=1`) at work: wall + /// time running the queues' lines, and its processor time doing so. + WorkerUs, + WorkerUserUs, + WorkerKernelUs, + /// Submissions sent; preparing them and waiting for the card, on + /// whichever thread (the frame-rate line's "preparing" and "on the + /// GPU"). + Submissions, + PrepareUs, + CardWaitUs, + /// The card with nothing of ours queued, and how much of that while + /// the submitting thread was working. + CardIdleUs, + CardIdleBehindUs, + /// Copies of title memory for submissions (time, bytes), and what + /// shaders wrote copied back (time, bytes). + CopyUs, + CopyBytes, + CopyBackUs, + CopyBackBytes, + /// List calls that record into host lists, on every thread + /// (nanoseconds, calls). Diagnostics builds only. + RecordNs, + RecordCalls, + /// The runtime changing what title memory shows: calls, the time from + /// asking for the lock to letting it go, and of that the wait for + /// readers. + Remaps, + RemapUs, + RemapWaitUs, + /// Texture refreshes on every thread, and of them the wait for title + /// memory to hold still; uploads recorded. + RefreshUs, + RefreshStillUs, + Uploads, + /// Waiting for host pipelines being made. + PipelineWaitUs, + /// Writes taken by the guards on view memory. + GuardFaults, + /// The title's frame waits: time slept, on every thread. + PaceUs, + /// DirectStorage requests finished, their destination bytes, and the + /// workers' time in them. + DiskReads, + DiskBytes, + DiskUs, + /// The card's time by kind of list (`crate::cardmeter`), as read a + /// second and a half after the lists were recorded: our lists that + /// bring copies in the card's memory up to date and hash their pieces, + /// our compare lists, and every other list; and how many of each. + CardSyncUs, + CardSyncLists, + CardCheckUs, + CardCheckLists, + CardListsUs, + CardLists, + /// Looks at which processor a thread is on ([`on_slow_core`]), and how + /// many found a slow one (an efficiency core of a hybrid processor): + /// the thread that presents (one look a present), our submit thread + /// (one a turn), and the recording threads (one every couple of + /// milliseconds of list calls). + RenderLooks, + RenderSlow, + WorkerLooks, + WorkerSlow, + RecordLooks, + RecordSlow, + Count, +} + +const N: usize = T::Count as usize; +static TOTAL: [AtomicU64; N] = [const { AtomicU64::new(0) }; N]; + +/// Adds to a total. +pub fn add(t: T, n: u64) { + TOTAL[t as usize].fetch_add(n, Relaxed); +} + +/// Takes from a total (a time that was summed over threads is corrected +/// to the time it took). +pub fn sub(t: T, n: u64) { + TOTAL[t as usize].fetch_sub(n, Relaxed); +} + +/// What a thread did inside our calls since its last present: for the +/// thread that presents (the title's render thread). +#[derive(Clone, Copy)] +#[repr(usize)] +pub enum H { + /// List calls, nanoseconds. + RecordNs, + /// Submit calls, microseconds. + ExecuteUs, + /// Frame waits, microseconds slept. + PaceUs, + Count, +} + +const HN: usize = H::Count as usize; + +thread_local! { + static HERE: std::cell::Cell<[u64; HN]> = const { std::cell::Cell::new([0; HN]) }; +} + +/// Adds to this thread's own count. +pub fn here(h: H, n: u64) { + HERE.with(|c| { + let mut v = c.get(); + v[h as usize] += n; + c.set(v); + }); +} + +/// Whether the processor this thread runs on right now is a slow one: on a +/// processor with two kinds of cores (the console has eight alike; an Intel +/// hybrid has fast cores and efficiency cores at about half their speed), +/// one of a lower efficiency class than the best. Always false where all +/// cores are alike. +pub fn on_slow_core() -> bool { + use windows_sys::Win32::System::Threading::GetCurrentProcessorNumber; + /// By logical processor (of group 0): whether it is slow. + static SLOW: std::sync::OnceLock> = std::sync::OnceLock::new(); + let slow = SLOW.get_or_init(|| { + let sets = cpu_sets(); + let best = sets.iter().map(|c| c.2).max().unwrap_or(0); + let mut slow = vec![false; sets.iter().map(|c| c.1 as usize + 1).max().unwrap_or(0)]; + for (_, processor, class) in &sets { + slow[*processor as usize] = *class < best; + } + tracing::info!( + "processors: {} logical, {} of them slow ones (a lower efficiency class than the best); the frame log counts how \ + often the render, submit and recording threads are found on a slow one", + slow.len(), + slow.iter().filter(|&&s| s).count() + ); + slow + }); + // SAFETY: a plain query. + let processor = unsafe { GetCurrentProcessorNumber() } as usize; + slow.get(processor).copied().unwrap_or(false) +} + +/// The system's processor sets of group 0: each one's id, its logical +/// processor and its efficiency class (higher is faster). +fn cpu_sets() -> Vec<(u32, u8, u8)> { + use windows_sys::Win32::System::SystemInformation::{GetSystemCpuSetInformation, SYSTEM_CPU_SET_INFORMATION}; + use windows_sys::Win32::System::Threading::GetCurrentProcess; + let mut bytes = 0u32; + // SAFETY: a size query, then the call into a buffer of that size. + unsafe { GetSystemCpuSetInformation(std::ptr::null_mut(), 0, &mut bytes, GetCurrentProcess(), 0) }; + let mut buffer = vec![0u64; (bytes as usize).div_ceil(8).max(1)]; + // SAFETY: as above; the buffer holds `bytes` bytes, aligned for the records. + let ok = unsafe { GetSystemCpuSetInformation(buffer.as_mut_ptr().cast(), bytes, &mut bytes, GetCurrentProcess(), 0) }; + let mut sets = Vec::new(); + let mut at = 0usize; + while ok != 0 && at + size_of::() <= bytes as usize { + // SAFETY: a record inside the buffer; each says its own size. + let info = unsafe { &*(buffer.as_ptr().cast::().add(at).cast::()) }; + if info.Size == 0 { + break; + } + // SAFETY: the record's type is CpuSet (the only one there is). + let set = unsafe { &info.Anonymous.CpuSet }; + if set.Group == 0 { + sets.push((set.Id, set.LogicalProcessorIndex, set.EfficiencyClass)); + } + at += info.Size as usize; + } + sets +} + +/// The slow logical processors of group 0 as a mask (a lower efficiency +/// class than the best): 0 where all cores are alike. +pub fn slow_processors() -> usize { + let sets = cpu_sets(); + let best = sets.iter().map(|c| c.2).max().unwrap_or(0); + sets.iter().filter(|c| c.2 < best && c.1 < usize::BITS as u8).fold(0, |mask, c| mask | 1usize << c.1) +} + +/// Asks the system to run the calling thread on the fast cores only, where +/// the processor has two kinds (`LEONIDA_FAST_CORES=0`: not asked). +/// +/// The title keeps its own threads on fast cores (run 229: its render +/// thread in 3,484 looks of 3,484, its recording threads in 104,254 of +/// 104,254), as on the console, whose eight cores are alike. The layer's +/// submit thread was found on a slow one in 1,529 looks of 24,021, and the +/// frame waits for that thread. A set of processors selected for a thread +/// is a preference the scheduler keeps unless nothing of it is free. +pub fn keep_on_fast_cores(what: &str) { + use windows_sys::Win32::System::Threading::{GetCurrentThread, SetThreadSelectedCpuSets}; + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + if !*ON.get_or_init(|| std::env::var_os("LEONIDA_FAST_CORES").is_none_or(|v| v != "0")) { + return; + } + let sets = cpu_sets(); + let best = sets.iter().map(|c| c.2).max().unwrap_or(0); + let fast: Vec = sets.iter().filter(|c| c.2 == best).map(|c| c.0).collect(); + // All alike (or nothing known): nothing to ask for. + if fast.is_empty() || fast.len() == sets.len() { + return; + } + // SAFETY: our own thread and a list of the system's own set ids. + let ok = unsafe { SetThreadSelectedCpuSets(GetCurrentThread(), fast.as_ptr(), fast.len() as u32) }; + if ok == 0 { + tracing::warn!(what, error = %std::io::Error::last_os_error(), "the thread could not be kept on the fast cores"); + } else { + tracing::info!(what, fast = fast.len(), of = sets.len(), "the thread is kept on the fast cores (LEONIDA_FAST_CORES=0: not)"); + } +} + +/// Asks the system to run the calling thread on the slow cores only, where +/// the processor has two kinds and at least eight slow logical processors +/// (a helper that must not take a fast core from the title's threads). +/// True if it was asked. +/// +/// The title pins its threads as on the console, where disk decompression +/// is the hardware's: measured on a 14700KF, 31 of its threads are tied to +/// logical processors 0-13, the fast cores. The layer decompresses on as +/// many worker threads as there are logical processors (28), free to run +/// anywhere: in the opening cutscene's streaming stretch about ten of them +/// were busy while the title's recording calls took three times as long. +pub fn keep_on_slow_cores(what: &str) -> bool { + use windows_sys::Win32::System::Threading::{GetCurrentThread, SetThreadSelectedCpuSets}; + let sets = cpu_sets(); + let best = sets.iter().map(|c| c.2).max().unwrap_or(0); + let slow: Vec = sets.iter().filter(|c| c.2 < best).map(|c| c.0).collect(); + if slow.len() < 8 { + return false; + } + // SAFETY: our own thread and a list of the system's own set ids. + let ok = unsafe { SetThreadSelectedCpuSets(GetCurrentThread(), slow.as_ptr(), slow.len() as u32) } != 0; + static ONCE: std::sync::Once = std::sync::Once::new(); + ONCE.call_once(|| { + tracing::info!(what, slow = slow.len(), of = sets.len(), ok, "helper threads are kept on the slow cores: the first one"); + }); + ok +} + +/// Whether frames are logged. +pub fn on() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| match std::env::var_os("LEONIDA_FRAME_LOG") { + Some(v) => v != "0", + None => cfg!(feature = "diagnostics"), + }) +} + +fn micros(t: windows_sys::Win32::Foundation::FILETIME) -> u64 { + (u64::from(t.dwHighDateTime) << 32 | u64::from(t.dwLowDateTime)) / 10 +} + +/// This thread's processor time so far (user, kernel), in microseconds. +pub fn thread_times() -> (u64, u64) { + use windows_sys::Win32::Foundation::FILETIME; + use windows_sys::Win32::System::Threading::{GetCurrentThread, GetThreadTimes}; + let zero = FILETIME { dwLowDateTime: 0, dwHighDateTime: 0 }; + let (mut created, mut exited, mut kernel, mut user) = (zero, zero, zero, zero); + // SAFETY: our own thread and four valid out pointers. + unsafe { GetThreadTimes(GetCurrentThread(), &mut created, &mut exited, &mut kernel, &mut user) }; + (micros(user), micros(kernel)) +} + +/// The process's processor time so far (user, kernel), in microseconds. +fn process_times() -> (u64, u64) { + use windows_sys::Win32::Foundation::FILETIME; + use windows_sys::Win32::System::Threading::{GetCurrentProcess, GetProcessTimes}; + let zero = FILETIME { dwLowDateTime: 0, dwHighDateTime: 0 }; + let (mut created, mut exited, mut kernel, mut user) = (zero, zero, zero, zero); + // SAFETY: our own process and four valid out pointers. + unsafe { GetProcessTimes(GetCurrentProcess(), &mut created, &mut exited, &mut kernel, &mut user) }; + (micros(user), micros(kernel)) +} + +/// The process's page faults so far (soft and hard). +fn page_faults() -> u64 { + use windows_sys::Win32::System::ProcessStatus::{K32GetProcessMemoryInfo, PROCESS_MEMORY_COUNTERS}; + use windows_sys::Win32::System::Threading::GetCurrentProcess; + // SAFETY: plain data the call fills in. + let mut c: PROCESS_MEMORY_COUNTERS = unsafe { std::mem::zeroed() }; + c.cb = size_of::() as u32; + // SAFETY: our own process and a sized structure. + unsafe { K32GetProcessMemoryInfo(GetCurrentProcess(), &mut c, c.cb) }; + u64::from(c.PageFaultCount) +} + +/// The PC's free physical memory, in MiB. +fn free_mb() -> u64 { + use windows_sys::Win32::System::SystemInformation::{GlobalMemoryStatusEx, MEMORYSTATUSEX}; + // SAFETY: plain data the call fills in. + let mut m: MEMORYSTATUSEX = unsafe { std::mem::zeroed() }; + m.dwLength = size_of::() as u32; + // SAFETY: a sized structure. + unsafe { GlobalMemoryStatusEx(&mut m) }; + m.ullAvailPhys >> 20 +} + +/// Values read when a frame ends, all running totals but the last. +const S: usize = 11; +const S_THREAD_USER: usize = 0; +const S_THREAD_KERNEL: usize = 1; +const S_PROCESS_USER: usize = 2; +const S_PROCESS_KERNEL: usize = 3; +const S_PAGE_FAULTS: usize = 4; +const S_DRAWS: usize = 5; +const S_PIPELINES_MADE: usize = 6; +const S_PIPELINES_LOADED: usize = 7; +const S_STAGING_REUSED: usize = 8; +const S_STAGING_MADE: usize = 9; +/// Not a total: the free memory then. +const S_FREE_MB: usize = 10; + +fn sample() -> [u64; S] { + let (tu, tk) = thread_times(); + let (pu, pk) = process_times(); + [ + tu, + tk, + pu, + pk, + page_faults(), + crate::draw::drawn(), + crate::pipeline::frame_log_counts().0, + crate::pipeline::frame_log_counts().1, + crate::texture::SPARE_STATS[0].load(Relaxed), + crate::texture::SPARE_STATS[1].load(Relaxed), + free_mb(), + ] +} + +/// One frame: its number, when it ended (seconds since the first), its +/// length in microseconds, and the differences of the totals, the sampled +/// values and the presenting thread's own counts over it. +#[derive(Clone)] +struct Frame { + number: u64, + at: f64, + us: f64, + t: [f64; N], + s: [f64; S], + h: [f64; HN], +} + +struct State { + first: std::time::Instant, + /// The last frame's end: when, the totals and samples then, and the + /// thread that presented. + last: Option<(std::time::Instant, [u64; N], [u64; S], u32)>, + number: u64, + frames: Vec, + since: std::time::Instant, + /// The lengths of the last frames (microseconds), for the usual one. + recent: std::collections::VecDeque, +} + +static STATE: Mutex> = Mutex::new(None); + +fn median(values: impl Iterator) -> f64 { + let mut v: Vec = values.collect(); + if v.is_empty() { + return 0.0; + } + v.sort_by(f64::total_cmp); + v[v.len() / 2] +} + +/// A frame's make-up as text (`f` may be a mean of frames). +fn text(f: &Frame) -> String { + let t = |x: T| f.t[x as usize]; + let ms = |x: T| f.t[x as usize] / 1e3; + let s = |i: usize| f.s[i]; + let h = |x: H| f.h[x as usize]; + format!( + "{:.0} ms | render thread: ran {:.0} ms (user {:.0}, kernel {:.0}); in the present call {:.1} (lines and settling \ + {:.1}, copy and show {:.1}), in submit calls {:.1}, in list calls {:.1}, paced {:.1} | submit thread: at work \ + {:.1} ms (user {:.1}, kernel {:.1}); {:.0} submissions, preparing {:.1}, waiting for the card {:.1}; copies {:.1} \ + ms {:.1} MB; copy-back {:.1} ms {:.2} MB | card: idle {:.1} ms ({:.1} behind us); by its own clock, of the lists of a moment ago: our \ + send-and-hash lists {:.1} ms in {:.0}, our compare lists {:.1} ms in {:.0}, all other lists {:.1} ms in {:.0} | \ + recording, all threads: {:.1} ms in {:.0} calls; all submit calls {:.1} ms | textures: refresh {:.1} ms ({:.1} waiting for memory to hold \ + still), {:.0} uploads, staging {:.0} made {:.0} reused | remapping: {:.0} calls {:.1} ms ({:.1} waiting for \ + readers) | pipelines: {:.0} made, {:.0} loaded, {:.1} ms waited | disk: {:.0} reads {:.1} MB {:.1} worker ms | \ + faults: {:.0} page, {:.0} guard | process: {:.0} user {:.0} kernel ms | pacing, all threads {:.1} ms | {:.0} \ + draws | {:.0} MB free | found on a slow core: the render thread {:.0} of {:.0} looks, the submit thread {:.0} of {:.0}, recording threads {:.0} of {:.0}", + f.us / 1e3, + (s(S_THREAD_USER) + s(S_THREAD_KERNEL)) / 1e3, + s(S_THREAD_USER) / 1e3, + s(S_THREAD_KERNEL) / 1e3, + ms(T::PresentUs), + ms(T::PresentLineUs), + ms(T::PresentShowUs), + h(H::ExecuteUs) / 1e3, + h(H::RecordNs) / 1e6, + h(H::PaceUs) / 1e3, + ms(T::WorkerUs), + ms(T::WorkerUserUs), + ms(T::WorkerKernelUs), + t(T::Submissions), + ms(T::PrepareUs), + ms(T::CardWaitUs), + ms(T::CopyUs), + t(T::CopyBytes) / 1e6, + ms(T::CopyBackUs), + t(T::CopyBackBytes) / 1e6, + ms(T::CardIdleUs), + ms(T::CardIdleBehindUs), + ms(T::CardSyncUs), + t(T::CardSyncLists), + ms(T::CardCheckUs), + t(T::CardCheckLists), + ms(T::CardListsUs), + t(T::CardLists), + t(T::RecordNs) / 1e6, + t(T::RecordCalls), + ms(T::ExecuteUs), + ms(T::RefreshUs), + ms(T::RefreshStillUs), + t(T::Uploads), + s(S_STAGING_MADE), + s(S_STAGING_REUSED), + t(T::Remaps), + ms(T::RemapUs), + ms(T::RemapWaitUs), + s(S_PIPELINES_MADE), + s(S_PIPELINES_LOADED), + ms(T::PipelineWaitUs), + t(T::DiskReads), + t(T::DiskBytes) / 1e6, + ms(T::DiskUs), + s(S_PAGE_FAULTS), + t(T::GuardFaults), + s(S_PROCESS_USER) / 1e3, + s(S_PROCESS_KERNEL) / 1e3, + ms(T::PaceUs), + s(S_DRAWS), + s(S_FREE_MB), + t(T::RenderSlow), + t(T::RenderLooks), + t(T::WorkerSlow), + t(T::WorkerLooks), + t(T::RecordSlow), + t(T::RecordLooks), + ) +} + +/// The mean of `frames` (not empty). +fn mean(frames: &[&Frame]) -> Frame { + let n = frames.len() as f64; + let mut out = Frame { number: 0, at: 0.0, us: 0.0, t: [0.0; N], s: [0.0; S], h: [0.0; HN] }; + for f in frames { + out.us += f.us / n; + for i in 0..N { + out.t[i] += f.t[i] / n; + } + for i in 0..S { + out.s[i] += f.s[i] / n; + } + for i in 0..HN { + out.h[i] += f.h[i] / n; + } + } + out +} + +/// Over how many microseconds a frame is long, the usual one being +/// `usual`: half as long again, and at least 40 ms more. +fn long_over(usual: f64) -> f64 { + (usual * 1.5).max(usual + 40_000.0) +} + +/// The lines of a reading: the frame times, the usual frame, the long ones. +fn lines(frames: &[Frame], usual: f64, seconds: f64) -> Vec { + let over = long_over(usual); + let (long, plain): (Vec<&Frame>, Vec<&Frame>) = frames.iter().partition(|f| f.us > over); + let each: Vec = frames.iter().map(|f| format!("{:.0}", f.us / 1e3)).collect(); + let shortest = frames.iter().map(|f| f.us).fold(f64::INFINITY, f64::min); + let longest = frames.iter().map(|f| f.us).fold(0.0, f64::max); + let mut out = vec![format!( + "frame times: {} frames in {seconds:.1} s: shortest {:.0} ms, median {:.0}, longest {:.0}; {} long (over {:.0} ms, \ + the usual frame of the last {RECENT} being {:.0}); each: {}", + frames.len(), + shortest / 1e3, + median(frames.iter().map(|f| f.us)) / 1e3, + longest / 1e3, + long.len(), + over / 1e3, + usual / 1e3, + each.join(" ") + )]; + if !plain.is_empty() { + out.push(format!("usual frame (the mean of {} not long): {}", plain.len(), text(&mean(&plain)))); + } + for f in long.iter().take(LONG_MOST) { + out.push(format!("long frame {} at {:.1} s: {}", f.number, f.at, text(f))); + } + if long.len() > LONG_MOST { + out.push(format!("long frames: {} more in this reading are not listed", long.len() - LONG_MOST)); + } + out +} + +/// Frames whose lengths give the usual one, and the long frames listed in +/// a reading at most. +const RECENT: usize = 64; +const LONG_MOST: usize = 8; + +/// A frame ends: called at the end of the title's present call, on the +/// thread that made it. +pub fn frame() { + if !on() { + return; + } + crate::cardmeter::collect(); + add(T::RenderLooks, 1); + if on_slow_core() { + add(T::RenderSlow, 1); + } + let now = std::time::Instant::now(); + let totals: [u64; N] = std::array::from_fn(|i| TOTAL[i].load(Relaxed)); + let sampled = sample(); + let here = HERE.with(|c| c.replace([0; HN])); + // SAFETY: a plain query. + let thread = unsafe { windows_sys::Win32::System::Threading::GetCurrentThreadId() }; + let mut state = STATE.lock().unwrap_or_else(|e| e.into_inner()); + let state = state.get_or_insert_with(|| State { + first: now, + last: None, + number: 0, + frames: Vec::new(), + since: now, + recent: std::collections::VecDeque::new(), + }); + state.number += 1; + if let Some((then, t0, s0, thread0)) = state.last.replace((now, totals, sampled, thread)) { + let mut f = Frame { + number: state.number, + at: (now - state.first).as_secs_f64(), + us: (now - then).as_micros() as f64, + t: std::array::from_fn(|i| totals[i].wrapping_sub(t0[i]) as i64 as f64), + s: std::array::from_fn(|i| sampled[i].wrapping_sub(s0[i]) as i64 as f64), + h: here.map(|v| v as f64), + }; + f.s[S_FREE_MB] = sampled[S_FREE_MB] as f64; + if thread != thread0 { + // Another thread presented: its processor time is not this frame's. + (f.s[S_THREAD_USER], f.s[S_THREAD_KERNEL]) = (0.0, 0.0); + } + state.frames.push(f); + } + let elapsed = state.since.elapsed(); + if elapsed < std::time::Duration::from_secs(5) || state.frames.is_empty() { + return; + } + let frames = std::mem::take(&mut state.frames); + state.since = now; + // The usual frame: the median of the last frames, this reading's with + // those before it. + for f in &frames { + if state.recent.len() == RECENT { + state.recent.pop_front(); + } + state.recent.push_back(f.us); + } + let usual = median(state.recent.iter().copied()); + for line in lines(&frames, usual, elapsed.as_secs_f64()) { + tracing::info!("{line}"); + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn frame(number: u64, ms: f64) -> Frame { + let mut f = Frame { number, at: number as f64, us: ms * 1e3, t: [0.0; N], s: [0.0; S], h: [0.0; HN] }; + f.t[T::PresentUs as usize] = ms * 100.0; + f.t[T::Uploads as usize] = ms; + f + } + + #[test] + fn a_long_frame_is_listed_beside_the_usual_one() { + let frames: Vec = [150.0, 160.0, 140.0, 400.0, 150.0].iter().enumerate().map(|(i, &ms)| frame(i as u64, ms)).collect(); + let out = lines(&frames, 150_000.0, 1.0); + assert_eq!(out.len(), 3, "{out:#?}"); + assert!(out[0].starts_with("frame times: 5 frames in 1.0 s: shortest 140 ms, median 150, longest 400; 1 long (over 225 ms"), "{}", out[0]); + assert!(out[0].ends_with("each: 150 160 140 400 150"), "{}", out[0]); + // The usual frame is the mean of the four that are not long. + assert!(out[1].starts_with("usual frame (the mean of 4 not long): 150 ms |"), "{}", out[1]); + assert!(out[1].contains("in the present call 15.0 "), "{}", out[1]); + assert!(out[1].contains(" 150 uploads"), "{}", out[1]); + assert!(out[2].starts_with("long frame 3 at 3.0 s: 400 ms |"), "{}", out[2]); + assert!(out[2].contains("in the present call 40.0 "), "{}", out[2]); + assert!(out[2].contains(" 400 uploads"), "{}", out[2]); + } + + #[test] + fn long_is_half_as_long_again_and_at_least_40_ms_more() { + assert_eq!(long_over(150_000.0), 225_000.0); + assert_eq!(long_over(30_000.0), 70_000.0); + } + + #[test] + fn more_long_frames_than_are_listed_are_counted() { + let mut frames: Vec = (0..12).map(|i| frame(i, 500.0)).collect(); + frames.push(frame(12, 100.0)); + let out = lines(&frames, 100_000.0, 5.0); + assert_eq!(out.iter().filter(|l| l.starts_with("long frame ")).count(), LONG_MOST); + assert!(out.last().unwrap().starts_with("long frames: 4 more"), "{out:#?}"); + } + + #[test] + fn totals_and_a_threads_own_counts_add_up() { + let before = TOTAL[T::DiskReads as usize].load(Relaxed); + add(T::DiskReads, 3); + sub(T::DiskReads, 1); + assert_eq!(TOTAL[T::DiskReads as usize].load(Relaxed) - before, 2); + here(H::PaceUs, 5); + here(H::PaceUs, 6); + assert_eq!(HERE.with(|c| c.get())[H::PaceUs as usize], 11); + } +} diff --git a/crates/leonida-gpu/src/host.rs b/crates/leonida-gpu/src/host.rs new file mode 100644 index 000000000..a328f57fe --- /dev/null +++ b/crates/leonida-gpu/src/host.rs @@ -0,0 +1,8963 @@ +//! The host GPU: one D3D12 device and direct queue (decision 0007), and a +//! window to present on. +//! +//! shortcut: every submission is waited for, so CPU and GPU never overlap +//! (unless `LEONIDA_LATE_WAIT=1`, see [`late`]); +//! overlap them with per-submission fences once more than clears run. + +use std::sync::atomic::{AtomicU32, Ordering}; +use std::sync::{Mutex, OnceLock}; + +use windows::Win32::Foundation::{HANDLE, HWND, LPARAM, LRESULT, RECT, WPARAM}; +use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_12_0; +use windows::Win32::Graphics::Direct3D12::*; +use windows::Win32::Graphics::Dxgi::Common::*; +use windows::Win32::Graphics::Dxgi::*; +use windows::Win32::System::LibraryLoader::GetModuleHandleW; +use windows::Win32::System::Threading::{CreateEventW, INFINITE, WaitForSingleObject}; +use windows::Win32::UI::WindowsAndMessaging::*; +use windows::core::{Interface, PCWSTR, w}; + +/// Resource states without the console's own bits (compression hints from +/// bit 25 up), which the host rejects. +pub(crate) fn pc_state(state: u32) -> u32 { + state & 0x01ff_ffff +} + +/// A console state as a host texture state: PC bits only, and none of the +/// buffer-only ones the console allows on textures (vertex, constant and +/// index buffer, stream out, indirect arguments, as in "generic read"). +pub(crate) fn texture_state(state: u32) -> u32 { + const BUFFER_ONLY: u32 = 0x1 | 0x2 | 0x100 | 0x200; + pc_state(state) & !BUFFER_ONLY +} + +/// Render target views live only until their command is recorded, so a +/// ring of host descriptors is enough. +const RTV_RING: u32 = 1024; + +pub(crate) struct Host { + pub(crate) device: ID3D12Device, + queue: ID3D12CommandQueue, + fence: ID3D12Fence, + /// The last value signalled on `fence`, behind the submission lock. + submitted: Mutex, + event: HANDLE, + rtvs: ID3D12DescriptorHeap, + rtv_size: u32, + /// A ring of depth views, used as `rtvs`. + dsvs: ID3D12DescriptorHeap, + dsv_size: u32, + next_dsv: AtomicU32, + /// With `LEONIDA_D3D12_DEBUG` set (diagnostics builds): the debug + /// layer's messages. + messages: Option, + next_rtv: AtomicU32, + presenter: Mutex>, + /// The adapter the device is on, for its memory budget + /// ([`Host::video_memory`]); `None` if the system does not name it. + adapter: Option, +} + +// SAFETY: D3D12 devices, queues, fences and descriptor heaps are +// free-threaded; the event handle is only waited on under `submitted`. +unsafe impl Send for Host {} +// SAFETY: as above. +unsafe impl Sync for Host {} + +/// Host objects the title let go of while a submission may still use them +/// (a texture its descriptors name, a descriptor slot's old resource), by +/// the submission count they wait for. The title's descriptor writes and +/// releases reach the host at once, from its own threads, while the host +/// runs a submission: freeing there is a GPU page fault on the freed +/// texture (a device hang). +static RETIRED: Mutex> = Mutex::new(Vec::new()); +/// Submissions started and finished (waited for). +static STARTED: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); +static FINISHED: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + +/// A retired object, dropped on whatever thread finishes the submission. +struct Retired(#[allow(dead_code)] Box); +// SAFETY: what is retired is D3D12 objects (free-threaded) and the +// reference-counted wrappers holding them, dropped once. +unsafe impl Send for Retired {} + +/// Milliseconds since the first call. +pub(crate) fn now_ms() -> u64 { + static EPOCH: OnceLock = OnceLock::new(); + EPOCH.get_or_init(std::time::Instant::now).elapsed().as_millis() as u64 +} + +/// This moment, for telling later how long ago it was ([`long_ago`]): the +/// frames begun so far (high half, `crate::frame::current`) and tenths of a +/// second since the start. Host copies of title memory, staging buffers and +/// host textures note when they were last used with it. +pub(crate) fn moment() -> u64 { + (crate::frame::current() << 32) | ((now_ms() / 100) & 0xffff_ffff) +} + +/// Whether `moment` lies at least `ms` milliseconds and `frames` frames +/// back. Both: at seconds per frame, what every frame uses is not touched +/// for seconds, and at many frames per second not for many frames. (A title +/// that never waits for frames has no frame count: nothing is then idle.) +pub(crate) fn long_ago(moment: u64, ms: u64, frames: u64) -> bool { + let now = self::moment(); + let tenths = (now & 0xffff_ffff).saturating_sub(moment & 0xffff_ffff); + (now >> 32).saturating_sub(moment >> 32) >= frames && tenths * 100 >= ms +} + +/// Available physical RAM on the host in bytes, from `GlobalMemoryStatusEx`. +pub(crate) fn available_physical_ram() -> Option { + use windows_sys::Win32::System::SystemInformation::{GlobalMemoryStatusEx, MEMORYSTATUSEX}; + // SAFETY: plain data the call fills in. + let mut m: MEMORYSTATUSEX = unsafe { std::mem::zeroed() }; + m.dwLength = std::mem::size_of::() as u32; + // SAFETY: a sized structure. + let ok = unsafe { GlobalMemoryStatusEx(&mut m) } != 0; + ok.then_some(m.ullAvailPhys) +} + +/// Effective idle timeout (in milliseconds) for VRAM-backed host textures, +/// scaled down under VRAM pressure. Never returns less than 1,000 ms so +/// handles not yet recorded into a list or slot remain protected. +pub(crate) fn vram_idle_ms(video_memory: Option<[u64; 4]>) -> u64 { + const NORMAL_MS: u64 = 5_000; + const MODERATE_MS: u64 = 2_500; + const HIGH_MS: u64 = 1_000; + let Some([budget, used, ..]) = video_memory else { + return NORMAL_MS; + }; + if budget == 0 { + return NORMAL_MS; + } + let used_pct = (u128::from(used) * 100) / u128::from(budget); + if used_pct >= 85 { + HIGH_MS + } else if used_pct >= 75 { + MODERATE_MS + } else { + NORMAL_MS + } +} + +/// Effective idle timeout (in milliseconds) for system-RAM caches (staging +/// buffers, loose shadows, and the mapped pipeline library), scaled down +/// when free physical RAM is low. Never returns less than 2,000 ms. +pub(crate) fn ram_idle_ms(avail_phys: Option) -> u64 { + const GIB: u64 = 1024 * 1024 * 1024; + const NORMAL_MS: u64 = 10_000; + const MODERATE_MS: u64 = 5_000; + const HIGH_MS: u64 = 2_000; + let Some(avail) = avail_phys else { + return NORMAL_MS; + }; + if avail < 2 * GIB { + HIGH_MS + } else if avail < 4 * GIB { + MODERATE_MS + } else { + NORMAL_MS + } +} + +/// How many references are held on a host object (its COM count): ours +/// all, since the host's views and commands hold none. A buffer or texture +/// with one is held by its owner alone: no descriptor slot keeps it +/// (`HostHeap::kept`) and no list (`HostList::keep`). +pub(crate) fn references(object: &impl Interface) -> u32 { + type Method = unsafe extern "system" fn(*mut std::ffi::c_void) -> u32; + let raw = object.as_raw(); + // SAFETY: a live COM object, whose first three methods are those of + // `IUnknown` (query, add a reference, release one); the pair leaves the + // count as it was, and the release returns it. The first is not called. + unsafe { + let methods = *raw.cast::<*const [Method; 3]>(); + ((*methods)[1])(raw); + ((*methods)[2])(raw) + } +} + +/// Once a second, before a submission starts: lets go of what nothing +/// names any more (copies of windows of title memory, staging buffers, +/// host copies of textures the title fills). +/// `LEONIDA_SWEEP=0` keeps everything, as before. +fn sweep() { + // The in-place probe and census, if asked for (`LEONIDA_INPLACE_PROBE`). + crate::inplace::tick(); + static ON: OnceLock = OnceLock::new(); + if !*ON.get_or_init(|| std::env::var_os("LEONIDA_SWEEP").is_none_or(|v| v != "0")) { + return; + } + static LAST: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + let now = now_ms(); + let last = LAST.load(Ordering::Relaxed); + if now < last + 1000 + || LAST + .compare_exchange(last, now, Ordering::Relaxed, Ordering::Relaxed) + .is_err() + { + return; + } + crate::pipeline::trim_library(); + crate::shadow::let_go_idle(); + crate::texture::let_go_idle(); + crate::resource::let_go_idle(); +} + +/// Drops `object` once every submission running now has finished: at once +/// if none is. +pub(crate) fn retire(object: T) { + let started = STARTED.load(Ordering::Acquire); + if started <= FINISHED.load(Ordering::Acquire) { + RETIREMENTS[0].fetch_add(1, Ordering::Relaxed); + drop(object); + return; + } + RETIREMENTS[1].fetch_add(1, Ordering::Relaxed); + RETIRED + .lock() + .unwrap_or_else(|e| e.into_inner()) + .push((started, Retired(Box::new(object)))); +} + +/// Drops what waited for submissions up to `finished`. +fn bury(finished: u64) { + let done: Vec<(u64, Retired)> = { + let mut retired = RETIRED.lock().unwrap_or_else(|e| e.into_inner()); + if retired.is_empty() { + return; + } + let (done, keep) = std::mem::take(&mut *retired) + .into_iter() + .partition(|(at, _)| *at <= finished); + *retired = keep; + done + }; + drop(done); +} + +/// Objects [`retire`] dropped at once (no submission was running) and +/// kept until a running submission finished, since the start. +static RETIREMENTS: [std::sync::atomic::AtomicU64; 2] = [const { std::sync::atomic::AtomicU64::new(0) }; 2]; + +/// What the layer did to the host's objects lately, newest last (sweeps +/// that let host copies go, pipeline library calls, saves and trims): said +/// once when the host device is removed ([`log_removal_context`]), with +/// what the submitting thread and the pipeline workers were doing at that +/// moment. A device the driver removes "internally" names no command, and +/// the pass that happens to notice first names only the view it was at: +/// the three such losses of runs 72, 73 and 82 each came within 5 ms of a +/// pipeline library call that no line of the log tied to them. +/// `LEONIDA_TRAIL=0`: nothing is kept and nothing is said. +static TRAIL: Mutex> = Mutex::new(std::collections::VecDeque::new()); +/// The entries kept. +const TRAIL_MOST: usize = 96; + +fn trail_on() -> bool { + static ON: OnceLock = OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("LEONIDA_TRAIL").is_none_or(|v| v != "0")) +} + +/// Microseconds since the first call. +pub(crate) fn now_us() -> u64 { + static EPOCH: OnceLock = OnceLock::new(); + EPOCH.get_or_init(std::time::Instant::now).elapsed().as_micros() as u64 +} + +/// The calling thread, as the log's other lines name threads. +pub(crate) fn thread_id() -> u32 { + // SAFETY: a plain query. + unsafe { windows::Win32::System::Threading::GetCurrentThreadId() } +} + +/// Notes something done to the host's objects ([`TRAIL`]); `what` is only +/// run when the trail is kept. +pub(crate) fn trail(what: impl FnOnce() -> String) { + if !trail_on() { + return; + } + let entry = (now_us(), thread_id(), what()); + // Sweeps also go to the log as they happen: the trail is only said at + // a loss, and the driver's errors in the system's event log (run 224's + // first fell inside a sweep of 4,711 host textures) need the sweeps of + // clean runs beside them. + if entry.2.starts_with("sweep:") { + tracing::info!("{}", entry.2); + } + let mut trail = TRAIL.lock().unwrap_or_else(|e| e.into_inner()); + if trail.len() >= TRAIL_MOST { + trail.pop_front(); + } + trail.push_back(entry); +} + +/// What the submitting thread is doing (0 nothing: between submissions, +/// 1 preparing one, 2 waiting for the card to run it, 3 copying back what +/// it wrote), the lists of that submission, and since when ([`now_us`]). +static SUBMITTING: [std::sync::atomic::AtomicU64; 3] = [const { std::sync::atomic::AtomicU64::new(0) }; 3]; + +fn submitting(phase: u64, lists: usize) { + SUBMITTING[1].store(lists as u64, Ordering::Relaxed); + SUBMITTING[2].store(now_us(), Ordering::Relaxed); + SUBMITTING[0].store(phase, Ordering::Relaxed); +} + +/// What was going on when the host device went: whether a submission was +/// on the card, the pipeline library's state and the calls running in it, +/// and the trail. +pub(crate) fn removal_context() -> String { + use std::fmt::Write; + let now = now_us(); + let ms = |at: u64| now.saturating_sub(at) as f64 / 1000.0; + let phase = match SUBMITTING[0].load(Ordering::Relaxed) { + 0 => "between submissions (nothing of ours was running on the card)", + 1 => "preparing a submission (nothing of ours was running on the card)", + 2 => "waiting for the card to run a submission", + _ => "copying back what a submission wrote (nothing of ours was running on the card)", + }; + let mut text = format!( + "the submitting thread was {phase}, of {} lists, for {:.1} ms; {}; objects let go at once {} and after a running submission {}; submissions started {} finished {}", + SUBMITTING[1].load(Ordering::Relaxed), + ms(SUBMITTING[2].load(Ordering::Relaxed)), + crate::pipeline::library_removal_note(), + RETIREMENTS[0].load(Ordering::Relaxed), + RETIREMENTS[1].load(Ordering::Relaxed), + STARTED.load(Ordering::Relaxed), + FINISHED.load(Ordering::Relaxed), + ); + let trail = TRAIL.lock().unwrap_or_else(|e| e.into_inner()); + let _ = write!(text, "; the last {} things done, newest last:", trail.len()); + for (at, thread, what) in trail.iter() { + let _ = write!(text, "\n {:.1} ms before, thread {thread}: {what}", ms(*at)); + } + text +} + +/// Says [`removal_context`] in the log, once: called by whoever finds the +/// host device removed. +pub(crate) fn log_removal_context() { + static SAID: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); + if !trail_on() || SAID.swap(true, Ordering::Relaxed) { + return; + } + tracing::error!("when the host device went: {}", removal_context()); +} + +/// Time spent in submissions since the last frame-rate line, in +/// microseconds: preparing them on the CPU (title memory copies, texture +/// detiling), then waiting for the GPU. +static SUBMISSION_US: [std::sync::atomic::AtomicU64; 2] = + [std::sync::atomic::AtomicU64::new(0), std::sync::atomic::AtomicU64::new(0)]; + +/// Adds to [`SUBMISSION_US`] and to the frame log's totals. +fn submission_us(i: usize, us: u64) { + SUBMISSION_US[i].fetch_add(us, Ordering::Relaxed); + crate::framelog::add([crate::framelog::T::PrepareUs, crate::framelog::T::CardWaitUs][i], us); + if i == 0 { + crate::framelog::add(crate::framelog::T::Submissions, 1); + } +} + +/// Adds to [`PREPARING`]'s copies (time, bytes) and to the frame log's totals. +fn preparing(i: usize, n: u64) { + PREPARING[i].fetch_add(n, Ordering::Relaxed); + crate::framelog::add([crate::framelog::T::CopyUs, crate::framelog::T::CopyBytes][i], n); +} + +/// Adds to [`COPY_BACK`] and to the frame log's totals. +fn copy_back(i: usize, n: u64) { + COPY_BACK[i].fetch_add(n, Ordering::Relaxed); + crate::framelog::add([crate::framelog::T::CopyBackUs, crate::framelog::T::CopyBackBytes][i], n); +} + +/// Adds to [`CARD_CLOCK_US`] and, for the card's idle times, to the frame +/// log's totals. +fn card_clock_us(i: usize, us: u64) { + CARD_CLOCK_US[i].fetch_add(us, Ordering::Relaxed); + match i { + 0 => crate::framelog::add(crate::framelog::T::CardIdleUs, us), + 1 => crate::framelog::add(crate::framelog::T::CardIdleBehindUs, us), + _ => {} + } +} + +/// After submissions: shader-written ranges compared and copied back into +/// title memory (microseconds, bytes that differed), since the last +/// frame-rate line. +static COPY_BACK: [std::sync::atomic::AtomicU64; 2] = + [std::sync::atomic::AtomicU64::new(0), std::sync::atomic::AtomicU64::new(0)]; + +/// The card's clock, for the frame line of every run, in microseconds since +/// the last one: how long the card had nothing of ours queued; how much of +/// that while the thread that holds the submission lock was working (the +/// card idle behind us: preparing and copying back are done with the card +/// standing); and how long that thread stood waiting for the card. +/// +/// Every send of lists to the queue is followed by a signal on a fence of +/// the clock's own ([`Host::card_sent`]). A thread of the clock waits for +/// the newest signal and notes the moment the card reached it with nothing +/// newer sent; the next send ends that idle stretch. +static CARD_CLOCK_US: [std::sync::atomic::AtomicU64; 3] = [const { std::sync::atomic::AtomicU64::new(0) }; 3]; + +/// Of the thread that holds the submission lock: the microseconds it has +/// worked so far (preparing, copying back; not its waits for the card), and +/// since when it works now ([`now_us`] plus one; 0: it does not). +static WORKING: [std::sync::atomic::AtomicU64; 2] = [const { std::sync::atomic::AtomicU64::new(0) }; 2]; + +/// The thread that holds the submission lock starts (`on`) or stops +/// working; whether it worked until now. +fn working(on: bool) -> bool { + let now = now_us() + 1; + let since = WORKING[1].swap(if on { now } else { 0 }, Ordering::Relaxed); + if since != 0 { + WORKING[0].fetch_add(now.saturating_sub(since), Ordering::Relaxed); + } + since != 0 +} + +/// [`WORKING`] as of now: microseconds worked so far. +fn worked() -> u64 { + let since = WORKING[1].load(Ordering::Relaxed); + let now = if since != 0 { (now_us() + 1).saturating_sub(since) } else { 0 }; + WORKING[0].load(Ordering::Relaxed) + now +} + +/// The thread that holds the submission lock stood waiting for the card +/// from `since` until now ([`CARD_CLOCK_US`]). +fn stood(since: std::time::Instant) { + card_clock_us(2, since.elapsed().as_micros() as u64); +} + +/// What [`CARD_CLOCK_US`] is measured with. +struct CardClock { + fence: ID3D12Fence, + /// Signals sent so far; and, while the card has reached the last of + /// them, since when and what [`worked`] said then. + state: Mutex<(u64, Option<(std::time::Instant, u64)>)>, + sent: std::sync::Condvar, +} + +// SAFETY: a fence (free-threaded) behind a lock. +unsafe impl Send for CardClock {} +// SAFETY: as above. +unsafe impl Sync for CardClock {} + +/// The clock's thread: waits for the newest signal sent and notes when the +/// card got there with nothing newer behind it. +fn card_clock_watch(clock: &'static CardClock) { + // SAFETY: a plain event of our own. + let Ok(event) = (unsafe { CreateEventW(None, false, false, None) }) else { + return; + }; + let mut seen = 0; + loop { + let target = { + let mut state = clock.state.lock().unwrap_or_else(|e| e.into_inner()); + while state.0 == seen { + state = clock.sent.wait(state).unwrap_or_else(|e| e.into_inner()); + } + state.0 + }; + // SAFETY: the clock's fence and this thread's event. + unsafe { + if clock.fence.SetEventOnCompletion(target, event).is_ok() { + WaitForSingleObject(event, INFINITE); + } + } + seen = target; + let mut state = clock.state.lock().unwrap_or_else(|e| e.into_inner()); + if state.0 == target && state.1.is_none() { + state.1 = Some((std::time::Instant::now(), worked())); + } + } +} + +/// For the frame-rate line: [`CARD_CLOCK_US`] per frame, `ms` being the +/// frame's time. +fn card_clock_line(frames: f64, ms: f64) { + let [idle, behind, stood] = [0, 1, 2].map(|i| CARD_CLOCK_US[i].swap(0, Ordering::Relaxed) as f64 / 1000.0 / frames); + tracing::info!( + "the card's clock per frame: nothing of ours queued {idle:.1} ms (the card about {:.0}% busy by this count), \ + {behind:.1} ms of that while the submitting thread was working (the card idle behind us), the rest while the title \ + had not submitted; the submitting thread stood waiting for the card {stood:.1} ms", + if ms > 0.0 { (100.0 * (1.0 - idle / ms)).clamp(0.0, 100.0) } else { 0.0 } + ); +} + +/// Of the preparing: title memory copies (microseconds, bytes) and texture +/// refreshes (microseconds, bytes hashed), since the last frame-rate line. +pub(crate) static PREPARING: [std::sync::atomic::AtomicU64; 4] = [ + std::sync::atomic::AtomicU64::new(0), + std::sync::atomic::AtomicU64::new(0), + std::sync::atomic::AtomicU64::new(0), + std::sync::atomic::AtomicU64::new(0), +]; + +/// Host buffers made since the start, as (count, bytes): in the upload heap +/// (staging, list scratch), shared with the processor (host copies of title +/// memory) and the graphics card's own (indirect arguments, twins' copies). +/// For the memory line: against what is alive, they show what was let go. +pub(crate) static MADE: [std::sync::atomic::AtomicU64; 6] = [const { std::sync::atomic::AtomicU64::new(0) }; 6]; + +/// What of that is alive now, for the memory line (`MADE` counts what was +/// ever made: 42,607 upload buffers, 77.9 GB, in five minutes of run 60, +/// and nothing said how many were alive): host lists; the lists' scratch +/// chunks and their bytes; of those, the chunks no list holds (kept for the +/// next list, [`Spare`]) and their bytes; chunks taken from those kept +/// instead of made, since the start; and the lists' other upload buffers +/// (texture data copied from buffers, scratch too big for a chunk) and +/// their bytes. +pub(crate) static ALIVE: [std::sync::atomic::AtomicU64; 8] = [const { std::sync::atomic::AtomicU64::new(0) }; 8]; + +/// About host lists, for the memory line: lists made by the host since the +/// start; preludes made (a list's second allocator and list, made when it +/// first needs one, [`lazy_prelude`]); and, in diagnostics builds, the +/// bytes the process's private memory grew by while lists were being made +/// (what a list costs: host objects with the driver's command memory; 631 +/// lists were alive in run 65, each with a prelude it may never use). +/// Then the lists alive that were never reset since they were made: the +/// host sides of title lists the title made and has not used (a host list +/// cost 0.68 MB of private memory in run 69: 431 MB for the 632 the title +/// makes at its start). +pub(crate) static LISTS: [std::sync::atomic::AtomicU64; 4] = [const { std::sync::atomic::AtomicU64::new(0) }; 4]; + +/// The process's private bytes (diagnostics: around the making of lists). +#[cfg(feature = "diagnostics")] +fn private_bytes() -> u64 { + use windows_sys::Win32::System::ProcessStatus::{K32GetProcessMemoryInfo, PROCESS_MEMORY_COUNTERS}; + use windows_sys::Win32::System::Threading::GetCurrentProcess; + let mut c = PROCESS_MEMORY_COUNTERS { + cb: size_of::() as u32, + ..Default::default() + }; + // SAFETY: our own process and a sized structure. + unsafe { K32GetProcessMemoryInfo(GetCurrentProcess(), &mut c, c.cb) }; + c.PagefileUsage as u64 +} + +/// What the runtime does when the host GPU fails for good: report it like a +/// crash and end the run. The console has no such state, and carrying on +/// draws nothing at seconds per frame. +static ON_FAILURE: OnceLock !> = OnceLock::new(); + +/// Sets what a host GPU failure does (the runtime's crash report). +pub fn on_failure(report: fn(&str) -> !) { + let _ = ON_FAILURE.set(report); +} + +/// Ends the run on a host GPU failure: what failed, the removal reason and +/// the debug layer's first error, if any (`LEONIDA_D3D12_DEBUG=1` in a +/// diagnostics build names the command). +pub(crate) fn fail(what: std::fmt::Arguments) -> ! { + let mut text = what.to_string(); + if let Some(host) = host() { + // SAFETY: a plain query. + if let Err(e) = unsafe { host.device.GetDeviceRemovedReason() } { + text.push_str(&format!("; device removed: {e}")); + log_removal_context(); + } + match host.log_messages() { + Some(first) => text.push_str(&format!("; debug layer: {first}")), + None if host.messages.is_none() => text.push_str( + "; a diagnostics build with LEONIDA_D3D12_DEBUG=1 names the command", + ), + None => {} + } + } + tracing::error!("{text}"); + // Tests have no log: the reason goes to their output. + #[cfg(test)] + eprintln!("host GPU failure: {text}"); + match ON_FAILURE.get() { + Some(report) => report(&text), + None => std::process::abort(), + } +} + +/// The host GPU, created on first use; `None` without one (a run then +/// behaves as before: nothing executes). +pub(crate) fn host() -> Option<&'static Host> { + static HOST: OnceLock> = OnceLock::new(); + HOST.get_or_init(|| match create() { + Ok(host) => Some(host), + Err(e) => { + tracing::warn!(error = %e, "no host D3D12 device; command lists will not run"); + None + } + }) + .as_ref() +} + +fn create() -> windows::core::Result { + crate::drvwatch::start(); + crate::spread::start(); + // SAFETY: plain D3D12 object creation with valid descriptions. + unsafe { + // The debug layer only in builds with diagnostics. + let debug = + cfg!(feature = "diagnostics") && std::env::var_os("LEONIDA_D3D12_DEBUG").is_some(); + if debug { + let mut layer: Option = None; + match D3D12GetDebugInterface(&mut layer) { + Ok(()) => layer.iter().for_each(|l| l.EnableDebugLayer()), + Err(e) => tracing::warn!(error = %e, "no D3D12 debug layer"), + } + // GPU-based validation (`LEONIDA_D3D12_GBV`): out-of-range + // descriptor heap indices and the like become messages naming + // the command instead of page faults. Without state tracking + // (directly indexed textures are not transitioned). + if std::env::var_os("LEONIDA_D3D12_GBV").is_some() + && let Some(l) = &layer + { + if let Ok(d1) = l.cast::() { + d1.SetEnableGPUBasedValidation(true); + } + if let Ok(d2) = l.cast::() { + d2.SetGPUBasedValidationFlags( + D3D12_GPU_BASED_VALIDATION_FLAGS_DISABLE_STATE_TRACKING, + ); + } + tracing::info!("GPU-based validation on"); + } + } + // Diagnostics: device-removed data (the command that faulted, the + // faulting address), read when the device is removed. + if dred_on() { + let mut dred: Option = None; + if D3D12GetDebugInterface(&mut dred).is_ok() + && let Some(dred) = dred + { + dred.SetAutoBreadcrumbsEnablement(D3D12_DRED_ENABLEMENT_FORCED_ON); + dred.SetPageFaultEnablement(D3D12_DRED_ENABLEMENT_FORCED_ON); + } + } + let mut device: Option = None; + // Diagnostics: the software adapter, on which a shader's wild access + // is an access violation in this process (a crash report with the + // address and instruction) instead of a GPU fault and driver reset. + if cfg!(feature = "diagnostics") && std::env::var_os("LEONIDA_D3D12_WARP").is_some() { + let adapter = warp_adapter()?; + D3D12CreateDevice(&adapter, D3D_FEATURE_LEVEL_12_0, &mut device)?; + tracing::info!("host device on the software adapter (WARP)"); + } else { + D3D12CreateDevice(None, D3D_FEATURE_LEVEL_12_0, &mut device)?; + } + let device = device.ok_or_else(windows::core::Error::empty)?; + // `LEONIDA_D3D12_BACKGROUND=0`: the runtime's background work (the + // driver compiling shaders again on the "D3D Background Thread"s, + // for minutes after pipelines were made or loaded) is switched off. + // An experiment: while those threads ran, the same shot took + // 1,000-1,200 ms a frame, and 830-950 ms from the moment they + // stopped (run 54, 08:32:01 to 08:32:06). Left as it is by default: + // whether the card is slower with the shaders it then keeps is not + // known. + if std::env::var_os("LEONIDA_D3D12_BACKGROUND").is_some_and(|v| v == "0") + && let Ok(device6) = device.cast::() + { + let set = device6.SetBackgroundProcessingMode( + D3D12_BACKGROUND_PROCESSING_MODE_DISABLE_BACKGROUND_WORK, + D3D12_MEASUREMENTS_ACTION_KEEP_ALL, + None, + None, + ); + tracing::info!(ok = set.is_ok(), "the host's background shader work is switched off (LEONIDA_D3D12_BACKGROUND=0)"); + } + // the widest wave the GPU runs: 32 (NVIDIA) gets console wave64 compute programs whose + // cross-lane code stays in 32-lane halves translated for waves of 32 + let mut o1 = D3D12_FEATURE_DATA_D3D12_OPTIONS1::default(); + if device + .CheckFeatureSupport(D3D12_FEATURE_D3D12_OPTIONS1, (&raw mut o1).cast(), size_of_val(&o1) as u32) + .is_ok() + { + tracing::info!(min = o1.WaveLaneCountMin, max = o1.WaveLaneCountMax, "host wave lanes"); + leonida_shader::emit::set_host_max_wave(o1.WaveLaneCountMax); + } + let messages = debug + .then(|| device.cast::().ok()) + .flatten(); + let queue: ID3D12CommandQueue = device.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC { + Type: D3D12_COMMAND_LIST_TYPE_DIRECT, + ..Default::default() + })?; + let fence: ID3D12Fence = device.CreateFence(0, D3D12_FENCE_FLAG_NONE)?; + let event = CreateEventW(None, false, false, None)?; + let rtvs: ID3D12DescriptorHeap = + device.CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC { + Type: D3D12_DESCRIPTOR_HEAP_TYPE_RTV, + NumDescriptors: RTV_RING, + ..Default::default() + })?; + let rtv_size = device.GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_RTV); + let dsvs: ID3D12DescriptorHeap = + device.CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC { + Type: D3D12_DESCRIPTOR_HEAP_TYPE_DSV, + NumDescriptors: RTV_RING, + ..Default::default() + })?; + let dsv_size = device.GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_DSV); + let adapter = CreateDXGIFactory2::(DXGI_CREATE_FACTORY_FLAGS(0)) + .and_then(|factory| factory.EnumAdapterByLuid::(device.GetAdapterLuid())) + .ok(); + tracing::info!("host D3D12 device ready"); + Ok(Host { + device, + queue, + fence, + submitted: Mutex::new(0), + event, + rtvs, + rtv_size, + dsvs, + dsv_size, + next_dsv: AtomicU32::new(0), + messages, + next_rtv: AtomicU32::new(0), + presenter: Mutex::new(None), + adapter, + }) + } +} + +/// DXGI may return hardware for `EnumWarpAdapter` (notably under Proton). +/// Reject it before creating a device in diagnostics' software-only mode. +pub(crate) fn warp_adapter() -> windows::core::Result { + // SAFETY: plain DXGI adapter queries. + unsafe { + let factory: IDXGIFactory4 = CreateDXGIFactory2(DXGI_CREATE_FACTORY_FLAGS(0))?; + let adapter: IDXGIAdapter = factory.EnumWarpAdapter()?; + let desc = adapter.cast::()?.GetDesc1()?; + if desc.Flags & DXGI_ADAPTER_FLAG_SOFTWARE.0 as u32 == 0 { + tracing::warn!( + vendor = format_args!("{:#x}", desc.VendorId), + flags = format_args!("{:#x}", desc.Flags), + "DXGI did not identify the WARP adapter as software; refusing device" + ); + return Err(windows::core::Error::from_hresult( + windows::Win32::Foundation::E_FAIL, + )); + } + Ok(adapter) + } +} + +#[cfg(test)] +mod tests { + #[test] + fn sparse_copies_preserve_islands_and_observe_remaps() { + use windows_sys::Win32::System::Memory::*; + const N: usize = 5 << 16; + // SAFETY: we reserve a private region, commit selected pages inside it, + // and only directly access the pages while they are writable. + unsafe { + let base = VirtualAlloc(std::ptr::null(), N, MEM_RESERVE, PAGE_NOACCESS).cast::(); + assert!(!base.is_null()); + let mut expected = vec![0; N]; + for (offset, value) in [(0, 9), (2 << 16, 37), (N - 4096, 85)] { + let at = base.add(offset); + assert_eq!(VirtualAlloc(at.cast(), 4096, MEM_COMMIT, PAGE_READWRITE), at.cast()); + at.write_bytes(value, 4096); + expected[offset..offset + 4096].fill(value); + } + for remap in [false, true] { + if remap { + let mut old = 0; + assert_ne!(VirtualProtect(base.cast(), 4096, PAGE_NOACCESS, &mut old), 0); + expected[..4096].fill(0); + let at = base.add(1 << 16); + assert_eq!(VirtualAlloc(at.cast(), 4096, MEM_COMMIT, PAGE_READWRITE), at.cast()); + at.write_bytes(0xc7, 4096); + expected[1 << 16..(1 << 16) + 4096].fill(0xc7); + } + let mut out = vec![0xee; N]; + super::copy_mapped(out.as_mut_ptr().add(27), base.add(27), N - 54, false); + assert_eq!(out[27..N - 27], expected[27..N - 27]); + assert!(out[..27].iter().chain(&out[N - 27..]).all(|&v| v == 0xee)); + } + assert_ne!(VirtualFree(base.cast(), 0, MEM_RELEASE), 0); + } + } + + use super::*; + + #[test] + fn warp_adapter_accepts_only_software() { + // This probes DXGI without creating a D3D12 device or running a title. + // SAFETY: plain DXGI adapter queries. + let raw = unsafe { + let Ok(factory) = CreateDXGIFactory2::(DXGI_CREATE_FACTORY_FLAGS(0)) + else { + return; + }; + factory.EnumWarpAdapter::() + }; + let Ok(raw) = raw else { return }; + // SAFETY: EnumWarpAdapter returns a DXGI adapter, which implements + // IDXGIAdapter1; `raw` owns that interface. + let desc = unsafe { raw.cast::().unwrap().GetDesc1().unwrap() }; + eprintln!( + "EnumWarpAdapter: vendor={:#x}, flags={:#x}", + desc.VendorId, desc.Flags + ); + assert_eq!( + warp_adapter().is_ok(), + desc.Flags & DXGI_ADAPTER_FLAG_SOFTWARE.0 as u32 != 0, + ); + } +} + +/// A host command list and its allocator, always used together. +pub(crate) struct HostList { + allocator: ID3D12CommandAllocator, + pub(crate) list: ID3D12GraphicsCommandList, + /// Work for submission time, in recorded order. + deferred: Mutex, + /// Upload memory for data the list's draws make (expanded vertices), + /// reused after a reset. + scratch: Mutex, + /// Host texture states the list assumes, by host copy: at its start and + /// at its end. Lists are recorded on many threads and run in submission + /// order, so the transitions from a texture's real state are made at + /// submission, in `prelude`. Holding the copies keeps every texture the + /// list names alive until it is reset, even if the title releases the + /// resource first. + states: Mutex, + /// What the list does with depth textures that have a colour twin, by + /// twin ([`TwinUse`]). + twins: Mutex>, + /// The list that runs those transitions just before this one, made + /// when the list first has such transitions ([`lazy_prelude`]). + prelude: OnceLock>, + /// The pipelines the list binds, for reports of slow submissions. + pipelines: Mutex>, + /// The work its indirect executions may still do (`indirect`): a + /// shader-writable word, zeroed when the list is submitted, and after + /// it what the clamp notes about mesh records. In memory the CPU maps. + budget: OnceLock>, + /// The same words in the card's own memory ([`card_budget`]), which the + /// clamp uses instead when there is one: zeroed in the list before its + /// first clamp, its notes copied to `budget` when the list closes. + card_budget: OnceLock>, + /// Device-local scratch buffer for clamped indirect arguments (`indirect`), + /// grown to the largest indirect execution recorded on the list. + indirect_args: Mutex>, + /// The buffers of `crate::indirect::window_check`, made at its first use. + window_check: OnceLock>, + /// Counts the list in [`ALIVE`] while it lives. + _alive: Counted, + /// The pair of timestamps its run is timed with since its last reset + /// (`crate::cardmeter`), or none. + meter: AtomicU32, + /// With `crate::cardmeter::pipelines`: the pair of the pipeline bound + /// last, open until the next one is bound or the list closes. + pipeline_meter: AtomicU32, + /// The records its draws read from slots that its prelude fills + /// (`crate::indirect::gather`). + gather: Mutex, + /// The texts of the markers `note_op` set, in order (for device-removed + /// data without marker texts), with the host GPU range a copy reads. + #[cfg(feature = "diagnostics")] + notes: Mutex>, + /// With `LEONIDA_GPU_TIMING`: a GPU timestamp before each noted command + /// and at the end, and where they are read back. + #[cfg(feature = "diagnostics")] + stamps: OnceLock>, +} + +/// A list's prelude: an allocator and a closed list. +type Prelude = (ID3D12CommandAllocator, ID3D12GraphicsCommandList); + +/// What a list gathers for its prelude to clamp (`crate::indirect::gather`). +#[derive(Default)] +struct Gather { + /// Something recorded in the list may write arguments: no record is + /// gathered from here on (the ones gathered before are read before + /// the list runs, which is before that). + closed: bool, + /// One set per argument buffer, kind and stride. + sets: Vec, + /// The budget words the gathered records are charged to. + budget: Option, + /// Scratch buffers of earlier recordings, kept for the next sets. + spare: Vec, +} + +/// The most argument buffers a list gathers from. +const GATHER_SETS: usize = 8; + +/// Whether a host list's prelude is made when the list first needs one. A +/// prelude runs the texture transitions and twin copies a list needs before +/// it; lists that name no texture never have one, and every host list was +/// made with one all the same: twice the host objects per list, for the +/// title's 630 lists and for every list made anew. +/// `LEONIDA_LAZY_PRELUDE=0`: made with the list, as before. +fn lazy_prelude() -> bool { + static ON: OnceLock = OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("LEONIDA_LAZY_PRELUDE").is_none_or(|v| v != "0")) +} + +/// Timestamps per list (diagnostics); commands past them are not timed. +#[cfg(feature = "diagnostics")] +const STAMPS: u32 = 4096; + +/// A marker's text and the host range its command reads (diagnostics). +#[cfg(feature = "diagnostics")] +type Note = (String, Option<(u64, u64)>); + +type States = std::collections::HashMap< + usize, + (u32, u32, std::sync::Arc), +>; + +/// What a list does with a depth texture that has a colour twin +/// ([`crate::resource::Twin`]). Lists are recorded on many threads and run +/// in submission order, so a list cannot know which side an earlier list +/// leaves behind: it notes which sides it uses as it finds them, and its +/// prelude copies one side into the other at submission if that side is +/// behind then. From its first use of a side on, the list knows. +struct TwinUse { + /// The depth texture (the title resource's host copy) and its twin. + depth: std::sync::Arc, + twin: std::sync::Arc, + /// The sides (depth texture, twin) the list uses as it finds them. + needs: [bool; 2], + /// Whether each side lacks what the other was written last, where the + /// list is now; `None`: as the list found it. + behind: [Option; 2], + /// The draw or dispatch being prepared writes the twin. + writing: bool, + /// The depth plane's twin holds what the plane lacks although the list + /// copied the twins since: the plane's pass waits for the list's close. + late: bool, +} + +/// The pass that draws the twin of a depth plane into the plane: one +/// triangle over each mip of each slice, its pixel shader writing the +/// twin's texel as the depth, with the depth test "always" and no stencil +/// (the stencil plane is copied through a buffer and not touched here). +/// +/// A 16-bit twin holds whole steps of 1/65535, and the depth written is +/// the step times the float nearest 1/65535 (0x37800080). That is how +/// The title's tiled lighting computes the depth of the +/// rectangles it then draws with the test "equal", one class of materials +/// a draw (all six of its vertex shaders multiply the class number by that +/// constant), so the pass and the draw give the host the same float, and +/// the host turns the same float into the same 24 bits. The step divided +/// by 65535 is another float for 512 of the 65,536 steps (none under 257), +/// and lands in another 24-bit step for 127 of them (none under 385). +const PLANE_CORNERS: &str = r#" +float4 corner(uint i : SV_VertexID) : SV_Position { + return float4(float(i & 1) * 4.0 - 1.0, float(i >> 1) * 4.0 - 1.0, 0.0, 1.0); +} +"#; +const PLANE_STEPS: &str = r#" +#define RS "DescriptorTable(SRV(t0), visibility = SHADER_VISIBILITY_PIXEL)" +Texture2DArray twin : register(t0); +[RootSignature(RS)] +float plane(float4 p : SV_Position) : SV_Depth { + return float(twin.Load(int4(int2(p.xy), 0, 0))) * asfloat(0x37800080); +} +"#; +const PLANE_FLOATS: &str = r#" +#define RS "DescriptorTable(SRV(t0), visibility = SHADER_VISIBILITY_PIXEL)" +Texture2DArray twin : register(t0); +[RootSignature(RS)] +float plane(float4 p : SV_Position) : SV_Depth { + return twin.Load(int4(int2(p.xy), 0, 0)); +} +"#; + +/// Views of twins the pass reads, in a heap of ours used as a ring. +/// shortcut: a view must last until its list has run; with one or two +/// passes a frame the ring is far from coming round. +const PLANE_VIEWS: u32 = 256; + +/// What the pass draws with: the heap of its views of twins, and per kind +/// of twin (16-bit steps or floats) and depth format the root signature +/// and pipeline, made when first needed (`None`: the host refused). +struct PlanePass { + views: ID3D12DescriptorHeap, + cpu: usize, + gpu: u64, + step: u32, + next: AtomicU32, + made: Mutex)>>, +} + +/// The pass's root signature and pipeline for one kind of twin and one +/// depth format. +type PlanePipeline = (ID3D12RootSignature, ID3D12PipelineState); + +// SAFETY: D3D12 objects are free-threaded. +unsafe impl Send for PlanePass {} +// SAFETY: as above. +unsafe impl Sync for PlanePass {} + +fn plane_pass() -> Option<&'static PlanePass> { + static PASS: OnceLock> = OnceLock::new(); + PASS.get_or_init(|| { + let host = host()?; + let kind = D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV; + // SAFETY: plain heap creation and queries. + unsafe { + let views: ID3D12DescriptorHeap = host + .device + .CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC { + Type: kind, + NumDescriptors: PLANE_VIEWS, + Flags: D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE, + NodeMask: 0, + }) + .ok()?; + Some(PlanePass { + cpu: views.GetCPUDescriptorHandleForHeapStart().ptr, + gpu: views.GetGPUDescriptorHandleForHeapStart().ptr, + step: host.device.GetDescriptorHandleIncrementSize(kind), + views, + next: AtomicU32::new(0), + made: Mutex::default(), + }) + } + }) + .as_ref() +} + +/// Compiles function `entry` of `source` for `target` with the system's +/// compiler, as the indirect-argument clamp is (`crate::indirect`). +pub(crate) fn compile( + source: &str, + entry: windows::core::PCSTR, + target: windows::core::PCSTR, +) -> windows::core::Result> { + use windows::Win32::Graphics::Direct3D::Fxc::D3DCompile; + use windows::Win32::Graphics::Direct3D::ID3DBlob; + let mut code: Option = None; + let mut errors: Option = None; + // SAFETY: the source and names live through the call; out pointers ours. + let compiled = unsafe { + D3DCompile( + source.as_ptr().cast(), + source.len(), + windows::core::s!("leonida"), + None, + None, + entry, + target, + 0, + 0, + &mut code, + Some(&mut errors), + ) + }; + if let Err(e) = compiled { + if let Some(errors) = errors { + // SAFETY: the blob's own bytes. + let text = unsafe { + std::slice::from_raw_parts( + errors.GetBufferPointer().cast::(), + errors.GetBufferSize(), + ) + }; + tracing::warn!("a shader of ours: {}", String::from_utf8_lossy(text)); + } + return Err(e); + } + let code = code.ok_or_else(windows::core::Error::empty)?; + // SAFETY: the blob's own bytes. + let bytes = unsafe { + std::slice::from_raw_parts(code.GetBufferPointer().cast::(), code.GetBufferSize()) + }; + Ok(bytes.to_vec()) +} + +impl PlanePass { + /// The root signature and pipeline for a twin of 16-bit steps (`steps`) + /// or of floats and the depth format `format`. + fn pipeline(&self, steps: bool, format: DXGI_FORMAT) -> Option { + let mut made = self.made.lock().unwrap_or_else(|e| e.into_inner()); + if let Some((_, _, pipeline)) = made.iter().find(|m| (m.0, m.1) == (steps, format.0)) { + return pipeline.clone(); + } + let pipeline = match Self::make(steps, format) { + Ok(pipeline) => Some(pipeline), + Err(e) => { + tracing::warn!( + error = %e, + steps, + format = format.0, + "no pipeline to draw a depth plane from its twin: such planes stay as they are" + ); + None + } + }; + made.push((steps, format.0, pipeline.clone())); + pipeline + } + + fn make(steps: bool, format: DXGI_FORMAT) -> windows::core::Result { + use windows::core::s; + let device = &host().ok_or_else(windows::core::Error::empty)?.device; + let vs = compile(PLANE_CORNERS, s!("corner"), s!("vs_5_1"))?; + let source = if steps { PLANE_STEPS } else { PLANE_FLOATS }; + let ps = compile(source, s!("plane"), s!("ps_5_1"))?; + let code = |bytes: &[u8]| D3D12_SHADER_BYTECODE { + pShaderBytecode: bytes.as_ptr().cast(), + BytecodeLength: bytes.len(), + }; + // SAFETY: the root signature is inside the pixel shader; the + // description points at live data and never releases its pointer. + unsafe { + let root: ID3D12RootSignature = device.CreateRootSignature(0, &ps[..])?; + let desc = D3D12_GRAPHICS_PIPELINE_STATE_DESC { + pRootSignature: std::mem::transmute_copy(&root), + VS: code(&vs[..]), + PS: code(&ps[..]), + SampleMask: u32::MAX, + RasterizerState: D3D12_RASTERIZER_DESC { + FillMode: D3D12_FILL_MODE_SOLID, + CullMode: D3D12_CULL_MODE_NONE, + DepthClipEnable: true.into(), + ..Default::default() + }, + // Every texel is written; stencil stays off. + DepthStencilState: D3D12_DEPTH_STENCIL_DESC { + DepthEnable: true.into(), + DepthWriteMask: D3D12_DEPTH_WRITE_MASK_ALL, + DepthFunc: D3D12_COMPARISON_FUNC_ALWAYS, + ..Default::default() + }, + PrimitiveTopologyType: D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE, + DSVFormat: format, + SampleDesc: DXGI_SAMPLE_DESC { + Count: 1, + Quality: 0, + }, + ..Default::default() + }; + let pipeline: ID3D12PipelineState = device.CreateGraphicsPipelineState(&desc)?; + Ok((root, pipeline)) + } + } +} + +/// Records into `list` the pass that draws `plane`, the twin of the depth +/// plane of `depth`, into that plane: `depth` in the depth-write state, +/// `plane` readable by pixel shaders. The pass sets the list's descriptor +/// heap, graphics root signature, pipeline, depth target, viewport, +/// scissor and topology and puts none of them back: it is for a list that +/// records nothing of the title's after it. +fn record_plane_pass( + list: &ID3D12GraphicsCommandList, + depth: &ID3D12Resource, + plane: &ID3D12Resource, +) { + let (Some(host), Some(pass)) = (host(), plane_pass()) else { + return; + }; + // SAFETY: live resources. + let (of, twin) = unsafe { (depth.GetDesc(), plane.GetDesc()) }; + // An R16 typeless twin (53) holds steps, read as R16_UINT (57); an R32 + // typeless one floats, read as R32_FLOAT (41). The depth view names + // the depth-stencil format of the texture's family (44: 45, 19: 20). + let steps = twin.Format.0 == 53; + let format = DXGI_FORMAT(match of.Format.0 { + 44 => 45, + 19 => 20, + typed => typed, + }); + let Some((root, pipeline)) = pass.pipeline(steps, format) else { + return; + }; + for slice in 0..u32::from(of.DepthOrArraySize) { + for mip in 0..u32::from(of.MipLevels) { + let slot = pass.next.fetch_add(1, Ordering::Relaxed) % PLANE_VIEWS; + let view = D3D12_SHADER_RESOURCE_VIEW_DESC { + Format: DXGI_FORMAT(if steps { 57 } else { 41 }), + ViewDimension: D3D12_SRV_DIMENSION_TEXTURE2DARRAY, + Shader4ComponentMapping: D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING, + Anonymous: D3D12_SHADER_RESOURCE_VIEW_DESC_0 { + Texture2DArray: D3D12_TEX2D_ARRAY_SRV { + MostDetailedMip: mip, + MipLevels: 1, + FirstArraySlice: slice, + ArraySize: 1, + ..Default::default() + }, + }, + }; + let target = D3D12_DEPTH_STENCIL_VIEW_DESC { + Format: format, + ViewDimension: D3D12_DSV_DIMENSION_TEXTURE2DARRAY, + Anonymous: D3D12_DEPTH_STENCIL_VIEW_DESC_0 { + Texture2DArray: D3D12_TEX2D_ARRAY_DSV { + MipSlice: mip, + FirstArraySlice: slice, + ArraySize: 1, + }, + }, + ..Default::default() + }; + let target = host.dsv(depth, Some(&target)); + let (width, height) = ((of.Width >> mip).max(1) as u32, (of.Height >> mip).max(1)); + let cpu = D3D12_CPU_DESCRIPTOR_HANDLE { + ptr: pass.cpu + (slot * pass.step) as usize, + }; + let gpu = D3D12_GPU_DESCRIPTOR_HANDLE { + ptr: pass.gpu + u64::from(slot * pass.step), + }; + // SAFETY: an open list; a slot of our heap; live resources and + // objects (the pass's own live as long as the process). + unsafe { + host.device + .CreateShaderResourceView(plane, Some(&view), cpu); + list.SetDescriptorHeaps(&[Some(pass.views.clone())]); + list.SetGraphicsRootSignature(&root); + list.SetPipelineState(&pipeline); + list.SetGraphicsRootDescriptorTable(0, gpu); + list.OMSetRenderTargets(0, None, false, Some(&target)); + list.RSSetViewports(&[D3D12_VIEWPORT { + TopLeftX: 0.0, + TopLeftY: 0.0, + Width: width as f32, + Height: height as f32, + MinDepth: 0.0, + MaxDepth: 1.0, + }]); + list.RSSetScissorRects(&[RECT { + left: 0, + top: 0, + right: width as i32, + bottom: height as i32, + }]); + list.IASetPrimitiveTopology( + windows::Win32::Graphics::Direct3D::D3D_PRIMITIVE_TOPOLOGY(4), + ); + list.DrawInstanced(3, 1, 0, 0); + } + crate::resource::PLANES[0].fetch_add(1, Ordering::Relaxed); + } + } +} + +/// Records into `list` the copy of a depth texture into its colour twin +/// (`colour`) or of the twin into the depth texture, both already in their +/// copy states: whole textures of one size in one format family, which the +/// host copies as they are; or, for the twin of a stencil plane, that plane +/// alone, through the twin's buffer. +fn record_twin_copy( + list: &ID3D12GraphicsCommandList, + depth: &ID3D12Resource, + twin: &crate::resource::Twin, + colour: bool, +) { + let (from, to) = if colour { + (depth, &twin.colour.texture) + } else { + (&twin.colour.texture, depth) + }; + crate::resource::TWINS[2 + usize::from(colour)].fetch_add(1, Ordering::Relaxed); + // shortcut: the depth plane's twin is not given the plane (that is a + // pass the other way: the plane read by a shader, the twin as its + // target). The twin then lacks what draws and clears wrote to the + // plane since shaders last wrote the twin. In the title + // nothing writes that plane but the twin's pass (its 192 draws against + // it only test, run 29), so the twin lacks nothing. Counted. + if colour && twin.plane.is_some() { + crate::resource::PLANES[1].fetch_add(1, Ordering::Relaxed); + } + let Some(through) = &twin.through else { + // SAFETY: an open list and two live textures. + unsafe { list.CopyResource(to, from) }; + return; + }; + // A stencil plane and its twin: each mip and slice of the plane goes + // into the buffer, laid out as the host lays the plane out for copies, + // and from the buffer into the other texture, whole subresources both + // times. In the depth texture the stencil plane's subresources follow + // the depth plane's; the twin has the one plane. + let Some(host) = host() else { return }; + // SAFETY: a live texture. + let of = unsafe { depth.GetDesc() }; + let planes = u32::from(of.MipLevels) * u32::from(of.DepthOrArraySize); + let mut rows = vec![D3D12_PLACED_SUBRESOURCE_FOOTPRINT::default(); planes as usize]; + // SAFETY: a plain query writing `planes` footprints. + unsafe { + host.device.GetCopyableFootprints( + &of, + planes, + planes, + 0, + Some(rows.as_mut_ptr()), + None, + None, + None, + ); + } + let (first_from, first_to) = if colour { (planes, 0) } else { (0, planes) }; + let subresource = |texture: &ID3D12Resource, index: u32| D3D12_TEXTURE_COPY_LOCATION { + // SAFETY: a borrowed pointer the location never releases. + pResource: unsafe { std::mem::transmute_copy(texture) }, + Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, + Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { + SubresourceIndex: index, + }, + }; + let placed = |row: &D3D12_PLACED_SUBRESOURCE_FOOTPRINT| D3D12_TEXTURE_COPY_LOCATION { + // SAFETY: as above. + pResource: unsafe { std::mem::transmute_copy(through) }, + Type: D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT, + Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { + PlacedFootprint: *row, + }, + }; + let (common, source, dest) = ( + D3D12_RESOURCE_STATE_COMMON, + D3D12_RESOURCE_STATE_COPY_SOURCE, + D3D12_RESOURCE_STATE_COPY_DEST, + ); + // SAFETY: an open list and live resources; the buffer was made as big + // as these footprints, and rests in the common state between copies. + unsafe { + list.ResourceBarrier(&[transition(through, common, dest)]); + for (i, row) in rows.iter().enumerate() { + let index = first_from + i as u32; + list.CopyTextureRegion(&placed(row), 0, 0, 0, &subresource(from, index), None); + } + list.ResourceBarrier(&[transition(through, dest, source)]); + for (i, row) in rows.iter().enumerate() { + let index = first_to + i as u32; + list.CopyTextureRegion(&subresource(to, index), 0, 0, 0, &placed(row), None); + } + list.ResourceBarrier(&[transition(through, source, common)]); + } +} + +/// Whether device-removed data is on (`LEONIDA_D3D12_DRED`, diagnostics +/// builds). +pub(crate) fn dred_on() -> bool { + static ON: OnceLock = OnceLock::new(); + *ON.get_or_init(|| { + cfg!(feature = "diagnostics") && std::env::var_os("LEONIDA_D3D12_DRED").is_some() + }) +} + +/// Indirect mesh dispatches since the last frame line: the largest group +/// count a record asked for, and the groups asked in all (from the lists' +/// budget buffers, a run late). +static MESH_GROUPS: [std::sync::atomic::AtomicU64; 2] = [const { std::sync::atomic::AtomicU64::new(0) }; 2]; + +/// Whether a list's indirect-work budget lives in the card's own memory +/// (`LEONIDA_INDIRECT_CARD_BUDGET=0` keeps it in memory the CPU maps, as +/// before). The clamp charges it with atomics, at least two in a row for +/// every clamp; in mapped memory on a card of its own each of them +/// crosses the bus. +fn card_budget() -> bool { + static ON: OnceLock = OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("LEONIDA_INDIRECT_CARD_BUDGET").is_none_or(|v| v != "0")) +} + +/// Whether each list of a submission runs and is timed on its own, slow +/// ones logged with their commands (`LEONIDA_GPU_TIMING`, diagnostics +/// builds; the commands are noted with `LEONIDA_D3D12_DRED` on). +#[cfg(feature = "diagnostics")] +fn timing() -> bool { + static ON: OnceLock = OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("LEONIDA_GPU_TIMING").is_some()) +} + +/// Names a host object for the device-removed report, which names the +/// allocations a page fault hit (only with device-removed data on). +pub(crate) fn name(object: &impl Interface, text: impl FnOnce() -> String) { + if dred_on() + && let Ok(object) = object.cast::() + { + // SAFETY: a plain call on a live object. + let _ = unsafe { object.SetName(&windows::core::HSTRING::from(text())) }; + } +} + +/// One in [`ALIVE`]`[0]` while it lives (a host list), and one in +/// [`LISTS`]`[3]` until it is first reset. +struct Counted { + /// Not reset since it was made. + fresh: std::sync::atomic::AtomicBool, +} + +impl Counted { + fn new() -> Counted { + ALIVE[0].fetch_add(1, Ordering::Relaxed); + LISTS[3].fetch_add(1, Ordering::Relaxed); + Counted { + fresh: std::sync::atomic::AtomicBool::new(true), + } + } + + /// The list is reset: it is in use. + fn used(&self) { + if self.fresh.swap(false, Ordering::Relaxed) { + LISTS[3].fetch_sub(1, Ordering::Relaxed); + } + } +} + +impl Drop for Counted { + fn drop(&mut self) { + ALIVE[0].fetch_sub(1, Ordering::Relaxed); + self.used(); + } +} + +/// A chunk of upload memory for lists' scratch data: the buffer, its +/// mapping and its host GPU address. +struct Chunk { + _buffer: ID3D12Resource, + data: usize, + gpu: u64, +} + +// SAFETY: a D3D12 resource (free-threaded) and its persistent mapping, +// written only by the list that holds the chunk. +unsafe impl Send for Chunk {} + +/// Upload chunks handed out front to back: the chunks (each with its +/// bytes), the one in use and the bytes used in it. +#[derive(Default)] +struct Scratch { + chunks: Vec<(Chunk, u64)>, + current: usize, + used: u64, +} + +// SAFETY: the chunk pointers are persistent mappings of upload buffers. +unsafe impl Send for Scratch {} + +impl Drop for Scratch { + fn drop(&mut self) { + give_chunks(std::mem::take(&mut self.chunks)); + } +} + +const SCRATCH_CHUNK: u64 = 4 << 20; +/// A list's first chunk when the chunks are shared ([`scratch_pool`]): most +/// lists put a few constants or a rectangle's corners there, and every +/// list that did took 4 MiB of the PC's memory for it. +const SCRATCH_FIRST: u64 = 256 << 10; +/// The most bytes of chunks kept while no list holds them. +const SPARE_MOST: u64 = 128 << 20; + +/// Whether lists share their scratch chunks: a list takes a chunk when it +/// first needs one, a small one first, and gives all of them back when it +/// is reset or dropped, for the next list. Before, a list kept every chunk +/// it ever took (4 MiB each) for as long as it lived, used or not, and the +/// host lists of held submissions, which live for one submission, each +/// made theirs anew: some 57 upload buffers of 4 MiB made, zeroed and +/// freed per frame of gameplay (run 60). +/// `LEONIDA_SCRATCH_POOL=0`: chunks of 4 MiB kept by their list, as before. +fn scratch_pool() -> bool { + static ON: OnceLock = OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("LEONIDA_SCRATCH_POOL").is_none_or(|v| v != "0")) +} + +/// Things of some sizes that nothing holds now, kept for whoever next asks +/// for one of the same size. +struct Spare { + kept: Vec<(T, u64)>, + bytes: u64, +} + +impl Spare { + const fn new() -> Self { + Spare { kept: Vec::new(), bytes: 0 } + } + + /// A kept thing of `size` bytes, the one given last. + fn take(&mut self, size: u64) -> Option { + let at = self.kept.iter().rposition(|(_, s)| *s == size)?; + self.bytes -= size; + Some(self.kept.remove(at).0) + } + + /// Keeps `thing` (`size` bytes) unless that takes the kept bytes past + /// `most`: then it comes back. + fn give(&mut self, thing: T, size: u64, most: u64) -> Option { + if self.bytes + size > most { + return Some(thing); + } + self.bytes += size; + self.kept.push((thing, size)); + None + } +} + +/// Scratch chunks no list holds. +static SPARE: Mutex> = Mutex::new(Spare::new()); + +/// A scratch chunk of `size` bytes: one kept ([`SPARE`]) or a new one. +fn take_chunk(host: &Host, size: u64) -> Option { + if scratch_pool() + && let Some(chunk) = SPARE.lock().unwrap_or_else(|e| e.into_inner()).take(size) + { + ALIVE[3].fetch_sub(1, Ordering::Relaxed); + ALIVE[4].fetch_sub(size, Ordering::Relaxed); + ALIVE[5].fetch_add(1, Ordering::Relaxed); + return Some(chunk); + } + let (buffer, data) = host.upload_buffer(size)?; + name(&buffer, || "list scratch".into()); + // SAFETY: a live buffer. + let gpu = unsafe { buffer.GetGPUVirtualAddress() }; + ALIVE[1].fetch_add(1, Ordering::Relaxed); + ALIVE[2].fetch_add(size, Ordering::Relaxed); + Some(Chunk { + _buffer: buffer, + data: data as usize, + gpu, + }) +} + +/// A list is done with `chunks` (it was reset after its submissions ran, +/// or dropped): kept for the next list, or freed past [`SPARE_MOST`] and +/// without the pool. +fn give_chunks(chunks: Vec<(Chunk, u64)>) { + if chunks.is_empty() { + return; + } + let mut freed = Vec::new(); + { + let mut spare = SPARE.lock().unwrap_or_else(|e| e.into_inner()); + for (chunk, size) in chunks { + let back = if scratch_pool() { + spare.give(chunk, size, SPARE_MOST) + } else { + Some(chunk) + }; + match back { + None => { + ALIVE[3].fetch_add(1, Ordering::Relaxed); + ALIVE[4].fetch_add(size, Ordering::Relaxed); + } + Some(chunk) => { + ALIVE[1].fetch_sub(1, Ordering::Relaxed); + ALIVE[2].fetch_sub(size, Ordering::Relaxed); + freed.push(chunk); + } + } + } + } + // Freed outside the lock. + drop(freed); +} + +/// What the host keeps for copies in the card's own memory +/// ([`crate::shadow::cards`]): three lists of ours and the compare. +struct CardWork { + /// Before a submission's lists: what changed on the copies' CPU side + /// goes to their card side. Those not in use: a plan takes one and + /// gives it back when its submission has run (`Host::card_done`), so + /// that submissions sent ahead ([`late`]) each have their own. + sync: Vec, + /// After them, in the same submission: the compare of the declared + /// ranges with their bytes from before. As `sync`. + check: Vec, + /// After it ran: the pieces that differ come down. + fetch: Prelude, + root: ID3D12RootSignature, + pso: ID3D12PipelineState, + /// One dword per piece compared, set where the piece differs: PC + /// memory, mapped (buffer, mapping, bytes). + differs: (ID3D12Resource, usize, u64), + /// Where the pieces that differ are fetched to: PC memory, mapped. + fetched: Option<(ID3D12Resource, usize, u64)>, + /// The dwords of `differs` taken by plans whose results were not read + /// yet. + taken: u32, + /// Plans made and not done with (`Host::card_done`). + out: u32, + /// The fetch inside flights ([`inflight_fetch`]), if it is on and was + /// made. + inflight: Option, +} + +/// What the fetch inside flights needs ([`inflight_fetch`], [`CARD_FETCH`]). +struct CardInflight { + root: ID3D12RootSignature, + pso: ID3D12PipelineState, + /// PC memory, mapped (buffer, mapping, bytes): dword 0 the counter of + /// tickets, then one dword per dword of `CardWork::differs`, the entry + /// of that piece. + table: (ID3D12Resource, usize, u64), + /// PC memory, mapped (buffer, mapping, slots of [`INFLIGHT_SLOT`] + /// bytes): where the pieces come down. + fetched: (ID3D12Resource, usize, u32), + /// Every ticket below it belongs to a landed flight: its slot may be + /// written over. Raised by the thread that lands flights; read when a + /// compare's list is recorded (an older value only gives fewer slots). + landed: u32, + /// What fetches the old way brought (copy, offsets, and the highest + /// send whose lists were surely on the queue ahead of the fetch: its + /// order of the queue less one). A flight sent at or before that ran + /// ahead of the fetch, so the CPU's side holds those bytes as the card + /// had them after the flight, or newer: the flight's own slot is older + /// there and is not merged there. Dropped once every flight sent up to + /// it has landed. + brought: Vec<(std::sync::Arc, usize, usize, u64)>, +} + +// SAFETY: D3D12 objects (free-threaded) and persistent mappings, used only +// under the submission lock. +unsafe impl Send for CardWork {} + +static CARD_WORK: Mutex> = Mutex::new(None); + +/// The compare of a declared range of a copy in the card's memory with +/// its bytes from before, one thread per 64 KiB piece (cut at multiples of +/// 64 KiB of title memory, as `Shadow::card_piece` cuts them): `differs` +/// gets a dword per piece, 1 where a byte differs. The offsets are widened +/// to 16 bytes; buffers are multiples of 64 KiB, and a piece flagged for a +/// byte just outside the range costs a fetch that finds nothing. +pub(crate) const CARD_COMPARE: &str = r#" +#define RS "RootConstants(num32BitConstants=6, b0), SRV(t0), UAV(u0), UAV(u1)" +cbuffer Span : register(b0) { + uint first; // the first piece + uint skew; // where the copy starts in its piece 0 + uint size; // the copy's buffer, in bytes (a multiple of 64 KiB) + uint pieces; + uint out_at; // the first piece's dword in `differs`, in bytes + uint compare; // 0: the hashes are stored; else compared with those stored (2: and then stored) +}; +ByteAddressBuffer now : register(t0); +// 16 bytes per piece of the copy: the hash of its bytes when they were +// last sent up (or hashed whole, the first time). +RWByteAddressBuffer hashes : register(u0); +RWByteAddressBuffer differs : register(u1); +[RootSignature(RS)] +[numthreads(64, 1, 1)] +void main(uint3 id : SV_DispatchThreadID) { + if (id.x >= pieces) return; + uint piece = first + id.x; + uint lo = piece * 65536u; + lo = lo > skew ? lo - skew : 0u; + uint hi = min((piece + 1u) * 65536u - skew, size); + lo = lo & ~15u; + hi = (hi + 15u) & ~15u; + uint4 h = uint4(0x9E3779B9u, 0x85EBCA6Bu, 0xC2B2AE35u, 0x27D4EB2Fu); + [loop] + for (uint at = lo; at < hi; at += 16u) { + h = (h ^ now.Load4(at)) * uint4(0x01000193u, 0x9E3779B1u, 0x85EBCA77u, 0xC2B2AE3Du); + h = h.yzwx ^ (h >> 15); + } + if (compare != 0u) { + differs.Store(out_at + id.x * 4u, any(h != hashes.Load4(piece * 16u)) ? 1u : 0u); + // With the copy-back on its own thread: the next compare of the + // piece finds what is written from here on. + if (compare == 2u) hashes.Store4(piece * 16u, h); + } else { + hashes.Store4(piece * 16u, h); + } +} +"#; + +/// Whether the pieces a flight's compare flags come down to the PC inside +/// the flight itself (`LEONIDA_CARD_FETCH_INFLIGHT=1`; off by default, and +/// only with [`relay`]). +/// +/// With the relay the thread that lands flights fetched the flagged pieces +/// with a list of its own on the host's queue, the one the submitting +/// thread keeps filling: the fetch ran behind every flight sent meanwhile. +/// Measured on an RTX 3070 Laptop: 140.9 ms a frame of that thread waiting +/// for fetches, for 63 pieces (3.2 MB) in about five fetches, some 28 ms a +/// fetch spent queued behind newer flights; and the submitting thread +/// waited 81.7 ms a frame in "title memory read" settles for that thread. +/// +/// With the switch the compare's list does the fetch: right behind the +/// compare, [`CARD_FETCH`] copies each piece it flagged into a slot of a +/// buffer in the PC's memory ([`CardInflight`]), so when the flight's fence +/// is reached its bytes are there, and the landing merges them +/// (`Shadow::card_merge_relay`) with no list, signal or wait of its own. +/// The merge's "fetched after" is the flight's own send number +/// (`CardPlan::sent_as`): see [`Host::relay_card_back`] for why that is +/// exact and when a landing falls back to the old fetch. +fn inflight_fetch() -> bool { + static ON: OnceLock = OnceLock::new(); + *ON.get_or_init(|| relay() && std::env::var_os("LEONIDA_CARD_FETCH_INFLIGHT").is_some_and(|v| v == "1")) +} + +/// The bytes of the PC's memory pieces fetched inside flights go to +/// ([`inflight_fetch`]; `LEONIDA_CARD_FETCH_INFLIGHT_MB`, 64): 1,024 slots +/// ([`inflight_slots`]). A flight whose flagged pieces find no free slot +/// lands the old way. +fn inflight_fetch_bytes() -> u64 { + static MOST: OnceLock = OnceLock::new(); + *MOST.get_or_init(|| { + std::env::var("LEONIDA_CARD_FETCH_INFLIGHT_MB").ok().and_then(|v| v.trim().parse::().ok()).unwrap_or(64).max(1) << 20 + }) +} + +/// A slot of [`CARD_FETCH`]: a 64 KiB piece as the compare cuts it, widened +/// to 16 bytes at both ends (one more 16-byte step where the copy does not +/// start at a multiple of 16 in its piece). +pub(crate) const INFLIGHT_SLOT: u64 = (64 << 10) + 16; + +/// The slots for `bytes` asked of [`inflight_fetch_bytes`]: one per 64 KiB, +/// rounded down to a power of two (at least 1, at most 2^15: the shader's +/// byte offsets into the slots are 32-bit), so that +/// `ticket % slots` runs on without a jump when the 32-bit ticket wraps +/// (2^32 is a multiple of it; with 1,023 slots it would jump by 4 and two +/// tickets in the air could share a slot). The buffer is `slots` times +/// [`INFLIGHT_SLOT`], a little over `bytes`. +pub(crate) fn inflight_slots(bytes: u64) -> u32 { + let wanted = (bytes >> 16).clamp(1, 1 << 15); + 1u32 << (63 - wanted.leading_zeros()) +} + +/// [`CARD_FETCH`]'s table entry for a piece the compare did not flag. +pub(crate) const INFLIGHT_NONE: u32 = 0xffff_ffff; + +/// Where piece `i` of `span` starts in its [`CARD_FETCH`] slot, as an +/// offset of the copy: the compare's lower bound of the piece, widened down +/// to 16 bytes (`CARD_COMPARE`, before clamping to the declared range). +/// What `Shadow::card_piece` gives for the piece lies at or above it, and +/// within [`INFLIGHT_SLOT`] of it. +pub(crate) fn inflight_piece_from(span: &crate::shadow::CardSpan, i: u32) -> usize { + let lo = (span.first + i) as usize * 65536; + let lo = lo.saturating_sub(span.skew as usize); + lo & !15 +} + +/// Whether the ticket `k` of [`CARD_FETCH`]'s counter gets a slot, with +/// every ticket below `floor` landed and `slots` slots: the slot is +/// `k % slots`. The tickets of flights still in the air are at or above +/// `floor` (they are taken in the queue's order and flights land in that +/// order), so two that get a slot are fewer than `slots` apart and never +/// share one. The arithmetic of the shader, for the tests. +pub(crate) fn inflight_gets_slot(k: u32, floor: u32, slots: u32) -> bool { + k.wrapping_sub(floor) < slots +} + +/// The fetch inside a flight ([`inflight_fetch`]), run in the compare's list +/// right behind the compare of a declared range (a UAV barrier between): +/// one group per piece (looping where a range has more than 65,535); where +/// `differs` flags the piece, its first thread takes a ticket of the +/// counter (`table`'s dword 0) and, if [`inflight_gets_slot`], the group +/// copies the piece, cut and widened as the compare hashes it, into slot +/// `ticket % slots` of `fetched`. Every piece's entry in `table` (dword 1 + +/// its dword in `differs`) is written: the ticket, also one that got no +/// slot (the landing repeats the test with the plan's `landed`), or +/// [`INFLIGHT_NONE`]. +pub(crate) const CARD_FETCH: &str = r#" +#define RS "RootConstants(num32BitConstants=8, b0), SRV(t0), UAV(u0), UAV(u1), UAV(u2)" +#define SLOT 65552u +#define NONE 0xffffffffu +cbuffer Span : register(b0) { + uint first; // the first piece + uint skew; // where the copy starts in its piece 0 + uint size; // the copy's buffer, in bytes (a multiple of 64 KiB) + uint pieces; + uint out_at; // the first piece's dword in `differs`, in bytes + uint landed; // every ticket below it is landed + uint slots; // slots of `fetched` + uint groups; // groups dispatched +}; +ByteAddressBuffer now : register(t0); +RWByteAddressBuffer differs : register(u0); +RWByteAddressBuffer table : register(u1); +RWByteAddressBuffer fetched : register(u2); +groupshared uint ticket; +[RootSignature(RS)] +[numthreads(64, 1, 1)] +void main(uint3 group : SV_GroupID, uint t : SV_GroupIndex) { + [loop] + for (uint i = group.x; i < pieces; i += groups) { + if (t == 0u) { + uint entry = NONE; + if (differs.Load(out_at + i * 4u) != 0u) { + uint k; + table.InterlockedAdd(0, 1u, k); + entry = k; + } + table.Store(4u + out_at + i * 4u, entry); + ticket = entry; + } + GroupMemoryBarrierWithGroupSync(); + uint k = ticket; + GroupMemoryBarrierWithGroupSync(); + if (k != NONE && (k - landed) < slots) { + uint piece = first + i; + uint lo = piece * 65536u; + lo = lo > skew ? lo - skew : 0u; + uint hi = min((piece + 1u) * 65536u - skew, size); + lo = lo & ~15u; + hi = (hi + 15u) & ~15u; + uint into = (k % slots) * SLOT; + [loop] + for (uint at = lo + t * 16u; at < hi; at += 1024u) { + fetched.Store4(into + (at - lo), now.Load4(at)); + } + } + } +} +"#; + +/// Whether the pieces hashed again after ranges were sent up to a copy in +/// the card's memory are hashed in runs of pieces that touch, each piece +/// once (`LEONIDA_CARD_REHASH_RUNS=1`; off by default), and not in a pass +/// per range sent up. +/// +/// These passes are ours, they run on the card before every submission's +/// lists, and no timing so far names them: each walks its 64 KiB pieces +/// 16 bytes at a time, 4,096 steps one after the other, so a pass takes +/// the time of one piece however few its pieces are. Run 102 sent up 514 +/// ranges a frame: 514 such passes. The same pieces are hashed either way; +/// a piece hashed when it need not be, or not hashed when it should, costs +/// a fetch that finds nothing and loses no shader write. +/// +/// `LEONIDA_CARD_REHASH_RUNS=alt`: twenty seconds with, twenty without, in +/// turn, each change said in the log: one run then measures both on the +/// same scene (the card meter's "send-and-hash lists" in the frame log). +/// Runs 105-110 found no change in the frame, but the card was not the +/// frame's limit then. +fn rehash_runs() -> bool { + /// 0 off, 1 on, 2 in turn. + static MODE: OnceLock = OnceLock::new(); + match *MODE.get_or_init(|| match std::env::var("LEONIDA_CARD_REHASH_RUNS").as_deref() { + Ok("1") => 1, + Ok("alt") => 2, + _ => 0, + }) { + 0 => false, + 1 => true, + _ => { + let joined = (now_us() / 20_000_000) % 2 == 1; + static LAST: std::sync::atomic::AtomicU8 = std::sync::atomic::AtomicU8::new(2); + if LAST.swap(u8::from(joined), Ordering::Relaxed) != u8::from(joined) { + tracing::info!( + "card rehash passes from now (LEONIDA_CARD_REHASH_RUNS=alt): {}", + if joined { "JOINED, one pass a run of touching pieces" } else { "one pass a range sent up, as usual" } + ); + } + joined + } + } +} + +/// Since the last frame-rate line, of our own passes over copies in the +/// card's memory: hash passes after ranges were sent up, the pieces they +/// hashed, and compare passes after the lists. +static CARD_PASSES: [std::sync::atomic::AtomicU64; 3] = [const { std::sync::atomic::AtomicU64::new(0) }; 3]; + +/// Whether what shaders wrote to copies in the card's memory is merged +/// into title memory on several threads (`LEONIDA_WIDE_MERGE=1`; off by +/// default). The pieces the card's compare found differing come down in +/// one fetch and were then merged one after the other on the thread that +/// settles: about 630 pieces and 40 MB a frame (run 104), each compared +/// with the copy's CPU side byte by byte and put into title memory through +/// the kernel. A piece is its own bytes of its copy and of title memory, +/// so eight threads take an eighth of them each. +fn wide_merge() -> bool { + static ON: OnceLock = OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("LEONIDA_WIDE_MERGE").is_some_and(|v| v == "1")) +} + +/// One declared range of a copy in the card's memory, in a submission. +struct CardRange { + shadow: std::sync::Arc, + /// As declared (title addresses), for the statistics. + declared: (usize, usize), + span: crate::shadow::CardSpan, + /// Its first piece's dword in the compare's results. + at: u32, + /// Whether the card compares it; else every piece is fetched. + compared: bool, +} + +/// What a submission does for copies in the card's memory. +struct CardPlan { + ranges: Vec, + /// The compare, run after the submission's lists. + check: Option, + /// The copies whose card side was brought up to date, alive until the + /// submission has run. + _synced: Vec>, + /// The lists of ours the plan recorded (whether the compare, the + /// list), given back by `Host::card_done`. + lists: Vec<(bool, Prelude)>, + /// With [`relay`], the number of this plan's send of changed ranges + /// (`QUEUE_ORDER`); else 0. + sent_as: u64, + /// Whether the compare's list fetches the flagged pieces itself + /// ([`inflight_fetch`]): every compared range has its [`CARD_FETCH`]. + inflight: bool, + /// The `CardInflight::landed` its [`CARD_FETCH`] was told: which of its + /// tickets got a slot ([`inflight_gets_slot`]). + inflight_landed: u32, +} + +/// One piece of submission-time work, in recorded order. +enum Step { + /// A copy into title memory (destination, source, bytes): the title's + /// buffer copies, which later refreshes must see. + Copy(usize, usize, usize), + /// A copy of title memory into the list's own upload memory. + Fill(usize, usize, usize), + /// Brings a range (address, bytes) of a buffer's host copy up to date: + /// once per submission, whichever lists ask, until a `Copy` or `Run` + /// intervenes. + Refresh(std::sync::Arc, usize, usize), + /// Work that may write title memory. + Run(Box), + /// Work that writes host memory only. + Host(Box), + /// Shaders write a range (address, bytes) of a buffer's host copy. + GpuWrite(std::sync::Arc, usize, usize), + /// Brings a texture's staging buffer up to date: once per submission, + /// whichever lists sample it, until a `Copy` or `Run` intervenes. + Texture(std::sync::Arc), +} + +/// What a list does on the CPU when it is submitted: copies between host +/// memory regions (title buffers, upload buffers and buffer copies), and +/// the upload buffers its GPU commands read, kept until the list is reset. +#[derive(Default)] +struct Deferred { + /// Destination, source, bytes. + copies: Vec, + uploads: Vec, + /// The bytes of `uploads` (counted in [`ALIVE`] while they are held). + upload_bytes: u64, + /// Host objects the list's commands name (pipelines, root signatures, + /// descriptor heaps): the title may release its objects before it + /// submits the list. + kept: Vec, + /// Buffer ranges refreshed since the last title copy (host copy, + /// address, bytes): refreshing them again would find the same bytes. + refreshed: std::collections::HashSet<(usize, usize, usize)>, + /// Textures whose contents the list brings up to date. + textures: std::collections::HashSet, + /// Bottom-of-pipe writes, done once the list has run: address, what, + /// bytes. + writes: Vec<(usize, crate::queue::Written, usize)>, + /// Textures read back (texture to buffer copies), done once the list + /// has run: the host buffer the list copies the texels into, the title + /// memory they go to, the bytes of a row, the rows, the title's row + /// pitch. + backs: Vec<(ID3D12Resource, usize, [usize; 3])>, + /// Whether the indirect-work budget is zeroed for this recording (a + /// step on the CPU, or in the list for the card's copy). + budget_zeroed: bool, + /// The indirect scratch buffer (`HostList::indirect_args`, by its + /// interface pointer) that a clamp in this recording left readable as + /// indirect arguments; 0 if none. It stays readable until the next + /// clamp into it ([`HostList::indirect_state`]). + indirect_readable: usize, +} + +impl Deferred { + /// Holds `buffer` (`size` bytes of upload memory) until the list is + /// reset. + fn hold_upload(&mut self, buffer: ID3D12Resource, size: u64) { + ALIVE[6].fetch_add(1, Ordering::Relaxed); + ALIVE[7].fetch_add(size, Ordering::Relaxed); + self.upload_bytes += size; + self.uploads.push(buffer); + } +} + +impl Drop for Deferred { + fn drop(&mut self) { + ALIVE[6].fetch_sub(self.uploads.len() as u64, Ordering::Relaxed); + ALIVE[7].fetch_sub(self.upload_bytes, Ordering::Relaxed); + } +} + +/// Whether a queue's submissions go to the card without a wait for each +/// (`LEONIDA_LATE_WAIT=1`; off by default, and off in the timing run, which +/// waits for every list on its own). +/// +/// Every submission was prepared, sent, waited for and copied back before +/// the next one was looked at, so the card stood idle while we prepared +/// and we stood idle while it ran: in run 86 a frame of 446 ms is 134 ms of +/// preparing, 194 ms of waiting and 78 ms of copying back, one after the +/// other, on the one thread that submits. +/// +/// With the switch a queue's submission is sent and joins a line of +/// "flights" ([`Flight`]); the thread goes on to the next one while the +/// card runs. The flights are settled together ([`Host::settle`]: one wait +/// for the card, what their shaders wrote copied back once per byte, then +/// their bottom-of-pipe writes and the fence signals behind them, in +/// order) at the next point where the title, or our own preparing, can +/// observe what they do. Those points, exactly: +/// +/// 1. a synchronous submission of ours ([`Host::execute`]): a present, a +/// read-back or map of a texture, a clear or upload run at once; +/// 2. the next submission reads title memory that a flight's shaders may +/// write: a title buffer copy, a fill of upload memory, a texture's +/// memory, any step that runs code of ours on title memory +/// ([`late_blocked`]); +/// 3. the next submission refreshes a range of a host copy that a flight's +/// shaders may write, and the title wrote a page of it since it was last +/// copied ([`stale_under_flights`]): the refresh leaves such a range +/// alone until the flight's writes are back, as it always did within a +/// submission; +/// 4. a queue stands at a wait for a memory value that no flight's +/// bottom-of-pipe write is known to satisfy, at an address a flight may +/// write ([`late_met`]); +/// 5. the title blocks on a fence without an event; +/// 6. the card has run every flight (a thread of ours waits for that: +/// [`late_helper`]), or the flights hold [`late_most`] host lists. +/// +/// What the title is told (bottom-of-pipe writes, fence values) is told +/// when the card has really run the work, later than before and never +/// earlier; a fence signalled on a queue while flights are in the air is +/// set behind them. A wait for a memory value that a flight's +/// bottom-of-pipe write satisfies counts as met: the waiting part goes to +/// the card behind that flight, which is the order the wait asks for. +/// +/// What it assumes beyond today: memory the title rewrites between two of +/// its submissions, without waiting for the first, may be seen by the +/// first's shaders (as on the console, where the card reads title memory +/// when it runs, not when the list is submitted). +pub(crate) fn late() -> bool { + late_stage() > 0 +} + +/// `LEONIDA_LATE_WAIT`: 0 (off), 1, or 2 ([`late_exact`]). +fn late_stage() -> u8 { + static STAGE: OnceLock = OnceLock::new(); + *STAGE.get_or_init(|| { + if std::env::var_os("LEONIDA_GPU_TIMING").is_some() { + return 0; + } + match std::env::var("LEONIDA_LATE_WAIT").as_deref() { + Ok("1") => 1, + Ok("2") => 2, + Ok("3") => 3, + // The relay alone: on top of stage 3. + Err(_) if crate::shadow::relay() => 3, + _ => 0, + } + }) +} + +/// Stage 2 of [`late`] (`LEONIDA_LATE_WAIT=2`): point 3 of its list is no +/// longer a point. Where the title wrote a page that lies in a range a +/// flight's shaders may write, the bytes the title changed are found (the +/// page as it is now against what the copy held when the flight was +/// prepared) and put into the copy, and only those: what the flight's +/// shaders write beside them stays (`Shadow::merge_under_writes`). The +/// flights are settled for it only where that cannot be done: memory that +/// is not write-watched, or a copy in the card's memory with more changed +/// runs than a submission should send up one by one. +/// +/// In run 92 (stage 1) this point settled the flights five times a frame +/// of twelve, each time with the card's work still to wait for: 172 ms a +/// frame of waiting were left of 200. +/// +/// What differs from settling first: a byte both the title and a flight's +/// shader wrote is the title's if the shader wrote it first, the shader's +/// if it wrote it afterwards; settled first it was always the shader's. +/// The title writing a byte a shader of its own is writing is a race on +/// the console too. +fn late_exact() -> bool { + late_stage() > 1 +} + +/// Stage 3 of [`late`] (`LEONIDA_LATE_WAIT=3`: stage 2, and the present is +/// no longer a point where flights are settled). The copy to the back +/// buffer is sent as a flight of its own (`Host::execute_own`, a list of +/// its own for each present in the air) and the swap chain is told to +/// present behind it; the queue's call returns, and the card finishes the +/// frame while the title records the next one. What the title is told +/// about the frame (bottom-of-pipe writes, fences) is told when the card +/// has run it, by the settling thread. +/// +/// What is left out with it: the look whether the presented frame is black +/// (diagnostics; it reads the frame back at once). A frame that is saved +/// or listed is presented the old way. Once every second and a half a +/// submission settles the flights all the same, for the sweep that lets +/// idle host objects go (it needs nothing in the air). +pub(crate) fn late_free_present() -> bool { + late_stage() > 2 +} + +/// The relay's first stage (`LEONIDA_RELAY=1`; off by default; it turns +/// [`late`] on at stage 3 unless `LEONIDA_LATE_WAIT` says another stage, +/// and is off with it, in the timing run and with kept snapshots). +/// +/// With [`late`] alone every settle does three things on the thread that +/// holds the submission lock: it waits for everything in the air, copies +/// back with the card standing, and only then goes on preparing. The frame +/// stays a relay: the card works about 242 ms of it and one thread +/// prepares, waits and copies back for about 220. +/// +/// With the switch a thread of its own ([`relay_worker`]) lands flights as +/// soon as the card has run them, in the order they were sent and without +/// the submission lock: it fetches and merges what their shaders wrote to +/// copies in the card's memory, compares and merges the other copies, +/// frees the flights' ranges, and then does their read-backs, their +/// bottom-of-pipe writes and the fence signals behind them, in the line's +/// order. The submitting thread meanwhile prepares and sends the next +/// submissions. [`Host::settle`] no longer settles anything: it waits until +/// that thread has landed everything in the air, at the same points as +/// before (the list in [`late`]), so whoever can observe title memory, a +/// fence or a present still does so only after the flights before it are +/// merged. +/// +/// What makes that safe is in `crate::shadow::relay` (ranges counted per +/// flight; a merge that never stores into memory the card may be writing; +/// sends to card copies numbered) and here: flights land in the order of +/// [`LINE`] by one thread, so a later flight's results never reach title +/// memory before an earlier flight's; the compare on the card stores the +/// hash it made, so each flight's compare flags exactly what changed since +/// the compare before it, however late the pieces are fetched; the fetch +/// goes to the queue under [`QUEUE_ORDER`], which says which sends of +/// title bytes the card had received when it ran. +pub(crate) fn relay() -> bool { + static ON: OnceLock = OnceLock::new(); + *ON.get_or_init(|| late_stage() > 0 && crate::shadow::relay()) +} + +/// The relay's second stage (`LEONIDA_RELAY=2`): a submission that reads +/// title memory a flight's shaders may write (a title buffer copy, a fill +/// of upload memory, a texture) waits only until the flights that declared +/// that memory have landed, not for everything in the air; and at +/// [`late_most`] lists in the air it waits until there are fewer. At `1` +/// both wait for everything. +fn relay_exact() -> bool { + static ON: OnceLock = OnceLock::new(); + // Stage 2 unless `LEONIDA_RELAY=1` asks for the first one (the default + // since the walls of the first room were found drawn in every run with + // this set and in fewer than half without it). + *ON.get_or_init(|| relay() && std::env::var_os("LEONIDA_RELAY").is_none_or(|v| v == "2")) +} + +/// Told when something joins [`LINE`], for the thread that lands flights +/// ([`relay`]); [`LINE_MOVED`] stays the word for the thread that looks at +/// what queues hold. +static RELAY_MOVED: std::sync::Condvar = std::sync::Condvar::new(); + +/// Told when flights have landed ([`relay`]): who waits for that looks +/// again. +static LINE_LANDED: std::sync::Condvar = std::sync::Condvar::new(); + +/// With [`relay`], the order of what we put on the queue: the number of +/// sends of changed ranges to copies in the card's memory so far +/// (`Host::card_before`). Held from the taking of the ranges until their +/// list is on the queue, and while a fetch of pieces goes to the queue: a +/// fetch sent with the count at N ran behind sends 1..N and ahead of every +/// later one. +static QUEUE_ORDER: Mutex = Mutex::new(0); + +/// Since the last frame-rate line, of the thread that lands flights +/// ([`relay`]): landings, flights landed, microseconds it waited for the +/// card with nothing to land, microseconds it waited for fetches of card +/// copies' pieces, microseconds of landing in all. +static RELAY_STATS: [std::sync::atomic::AtomicU64; 5] = [const { std::sync::atomic::AtomicU64::new(0) }; 5]; + +/// Since the last frame-rate line, with [`inflight_fetch`]: pieces merged +/// from the slots their flights fetched them to, their bytes, landings that +/// went the old way because a plan's pieces overflowed the slots, and +/// landings that fetched the old way (for any reason, overflow too). +static INFLIGHT_STATS: [std::sync::atomic::AtomicU64; 4] = [const { std::sync::atomic::AtomicU64::new(0) }; 4]; + +/// After a fetch the old way taken with the queue's count at `after`, for +/// plans whose highest send is `landed`: up to which send the notes of +/// sends to card copies may go (`crate::shadow::relay_fetched`). +/// +/// Without [`inflight_fetch`] every later merge is of a later fetch, whose +/// count is `after` or more: notes up to `after` are of no use, as before. +/// With it, a flight still in the air, sent before the fetch, merges its +/// own slot with "fetched after" its own send, which may be below `after`: +/// it needs the notes of the sends between, or it takes the title's bytes +/// that went up in them for its shaders' writes and puts its older card +/// bytes over them. (Flights 5, 6, 7 in the air; 5 lands the old way with +/// the count at 7; a title byte went up in send 7 into a piece 6's shaders +/// write; 6 lands from its slot, which holds that byte from before send 7.) +/// So the mark goes only to the landed plans' highest send: every flight +/// still to land was sent after it, and every later fetch the old way +/// takes a count at least that high. (`CardInflight::brought` is another +/// matter: the card's bytes the fetch put in the CPU's side, not the +/// title's.) +pub(crate) fn fallback_fetched_mark(inflight: bool, after: u64, landed: Option) -> u64 { + match (inflight, landed) { + (false, _) => after, + (true, Some(landed)) => landed.min(after), + (true, None) => 0, + } +} + +/// The landed mark of [`CARD_FETCH`]'s tickets after ticket `k` landed: one +/// past `k` if that is ahead of `landed`, in wrapping order (tickets in the +/// air are always within 2^31 of the mark), else `landed`. +pub(crate) fn inflight_raise(landed: u32, k: u32) -> u32 { + let next = k.wrapping_add(1); + if (next.wrapping_sub(landed) as i32) > 0 { next } else { landed } +} + +/// With [`inflight_fetch`], after a landing merged (either way): the tickets +/// these plans' fetches took are landed, and their slots may be written +/// over. Plans land in the line's order and tickets are taken in the +/// queue's (a UAV barrier opens every compare's list), so every ticket of a +/// plan in the air is ahead of these. +/// +/// The counter is never reset and wraps after 2^32 tickets: the mark is +/// raised in wrapping order ([`inflight_raise`]), and the slots are a power +/// of two, so `k % slots` runs on across the wrap. shortcut: ticket +/// 0xffff_ffff reads as [`INFLIGHT_NONE`]; a flagged piece that draws it +/// copies nothing and its landing goes the old way, once every 2^32. +fn inflight_tickets_landed(plans: &[&CardPlan]) { + let mut work = CARD_WORK.lock().unwrap_or_else(|e| e.into_inner()); + let Some(work) = work.as_mut() else { + return; + }; + let dwords = (work.differs.2 / 4) as usize; + let Some(inflight) = work.inflight.as_mut() else { + return; + }; + // SAFETY: the mapping of the tickets; these plans' fetches have run. + let table = unsafe { std::slice::from_raw_parts((inflight.table.1 as *const u32).add(1), dwords) }; + for plan in plans.iter().filter(|p| p.inflight) { + for r in plan.ranges.iter().filter(|r| r.compared) { + for p in 0..r.span.pieces { + if let Some(&k) = table.get((r.at + p) as usize) + && k != INFLIGHT_NONE + { + inflight.landed = inflight_raise(inflight.landed, k); + } + } + } + } + // Every flight still to land was sent after these: what fetches the old + // way brought up to them concerns none of them. + if let Some(last) = plans.iter().map(|p| p.sent_as).max() { + inflight.brought.retain(|b| b.3 > last); + } +} + +/// Of the line's things in order (a flight: the value signalled on the +/// host's fence behind it; a write or a signal behind a flight: `None`): +/// how many, from the front, can be landed when the card has reached +/// `completed`: everything ahead of the first flight it has not run. A +/// later flight never lands before an earlier one, and what follows a +/// flight (its bottom-of-pipe writes, signals) never before the flight. +fn landable(line: &[Option], completed: u64) -> usize { + line.iter().position(|f| f.is_some_and(|f| f > completed)).unwrap_or(line.len()) +} + +/// For one plan of copies in the card's memory, with [`relay`]: `flags` +/// holds, for every piece of every range of the plan, the copy, the +/// piece's number in the copy and whether the compare flagged it there (or +/// did not run). The pieces to fetch, under whichever range: all of them +/// flagged under any. Two ranges of a plan may hold parts of the same +/// 64 KiB piece; the compare hashes the whole piece for each and stores +/// the hash, so the second of them may find it stored already and not +/// flag it. +fn flagged_pieces(flags: &[(usize, u32, bool)]) -> std::collections::HashSet<(usize, u32)> { + flags.iter().filter(|f| f.2).map(|f| (f.0, f.1)).collect() +} + +/// Whether pieces fetched on a copy queue beside later flights are fetched +/// again when those flights land (`LEONIDA_QUEUE2_REFETCH=0`: not, as +/// before; on by default with `LEONIDA_QUEUE2` bit 1). +fn refetch() -> bool { + static ON: OnceLock = OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("LEONIDA_QUEUE2_REFETCH").is_none_or(|v| v != "0")) +} + +/// With fetches on a copy queue (`crate::queue2`, bit 1): the pieces (copy, +/// piece number) a fetch brought down while later submissions may have been +/// running, each with the number of the last submission started when the +/// fetch had run ([`STARTED`]). +/// +/// Such a fetch stands behind the flights being landed and nothing else, +/// so it runs beside whatever was sent after them. A later flight that +/// writes the piece (a buffer cleared and filled again) may be half way +/// through it: the bytes that come down are neither the earlier flight's +/// nor the later one's, and they go into title memory. If the later flight +/// leaves the piece as the earlier one left it (a still scene does, every +/// frame), its own compare finds the stored hash unchanged and flags +/// nothing: title memory kept the half-written bytes until the piece next +/// changed. On the direct queue a fetch only ever sees whole flights. +/// +/// So a flight that declared such a piece and had started before the fetch +/// had run fetches it at its own landing whatever its compare says +/// ([`fetched_beside`]); that fetch stands behind the flight, and is noted +/// here in turn if still later flights were in the air. Between the two +/// landings title memory may hold the half-written bytes, as it does on +/// the console, where the title reads the memory the card is writing: what +/// the title is promised is the piece as the flight left it once that +/// flight's fence is signalled, and the landing comes before the signal. +static BESIDE: Mutex>> = Mutex::new(None); + +/// Since the last frame-rate line: pieces fetched because an earlier fetch +/// of them ran beside their flight ([`BESIDE`]), and pieces noted there. +static BESIDE_STATS: [std::sync::atomic::AtomicU64; 2] = [const { std::sync::atomic::AtomicU64::new(0) }; 2]; + +/// [`BESIDE`]: whether the flight numbered `number` (among the submissions +/// started) must fetch a piece that an earlier landing's fetch brought +/// down when submissions up to `started` had been started: it had started +/// by then, so it may have been writing the piece under that fetch. +fn fetched_beside(started: Option, number: u64) -> bool { + started.is_some_and(|started| started >= number) +} + +/// [`BESIDE`], after a landing of flights up to number `landed` whose +/// fetch brought `fetched` down while submissions up to `started` had +/// been started: what is noted of the pieces afterwards, and how many were +/// noted now. A note is done with once every submission it names has +/// landed (each fetched the piece again if it declared it); the pieces +/// just fetched are noted if anything later than the flights landed had +/// started. +fn note_beside(noted: &mut std::collections::HashMap<(usize, u32), u64>, fetched: &[(usize, u32)], landed: u64, started: u64) -> u64 { + noted.retain(|_, upto| *upto > landed); + if started <= landed { + return 0; + } + for piece in fetched { + noted.insert(*piece, started); + } + fetched.len() as u64 +} + +#[cfg(test)] +mod relay_tests { + use super::{fetched_beside, flagged_pieces, landable, note_beside}; + + /// A piece fetched on the copy queue while a later flight was in the + /// air is fetched again by that flight, and by no flight sent after + /// the fetch had run; the note goes when its flights have landed. + #[test] + fn a_piece_fetched_beside_a_later_flight_is_fetched_again_by_it() { + let mut noted = std::collections::HashMap::new(); + let (a, p) = (0x1000usize, 7u32); + // Flight 5 lands; its fetch ran while 6 and 7 had started. + assert_eq!(note_beside(&mut noted, &[(a, p)], 5, 7), 1); + assert!(fetched_beside(noted.get(&(a, p)).copied(), 6)); + assert!(fetched_beside(noted.get(&(a, p)).copied(), 7)); + // Flight 8 was sent after the fetch had run: its compare decides. + assert!(!fetched_beside(noted.get(&(a, p)).copied(), 8)); + // Another piece was never noted. + assert!(!fetched_beside(noted.get(&(a, p + 1)).copied(), 6)); + // Flight 6 lands and fetches it again, with 7 still in the air and + // nothing newer: the note stays for 7. + assert_eq!(note_beside(&mut noted, &[(a, p)], 6, 7), 1); + assert!(fetched_beside(noted.get(&(a, p)).copied(), 7)); + // Flight 7 lands with nothing behind it: nothing is noted any more. + assert_eq!(note_beside(&mut noted, &[(a, p)], 7, 7), 0); + assert!(noted.is_empty()); + // A fetch with nothing later in the air notes nothing. + assert_eq!(note_beside(&mut noted, &[(a, p)], 9, 9), 0); + assert!(noted.is_empty()); + } + + /// Two flights and what follows each: nothing of the second lands + /// before the card has run it, and nothing behind a flight lands + /// before the flight. + #[test] + fn flights_land_in_the_order_they_were_sent() { + // Flight (fence 5), its write, a signal, flight (fence 6), its write. + let line = [Some(5), None, None, Some(6), None]; + assert_eq!(landable(&line, 4), 0); + assert_eq!(landable(&line, 5), 3); + assert_eq!(landable(&line, 6), 5); + assert_eq!(landable(&line, u64::MAX), 5); + // Signals with no flight ahead land at once; behind one they wait. + assert_eq!(landable(&[None, None], 0), 2); + assert_eq!(landable(&[None, Some(9), None], 8), 1); + assert_eq!(landable(&[], 3), 0); + // After the first three landed, the rest when its turn comes. + assert_eq!(landable(&line[3..], 5), 0); + assert_eq!(landable(&line[3..], 6), 2); + } + + /// A piece flagged under one range of a plan is fetched under every + /// range that holds a part of it; pieces of other copies are not. + #[test] + fn a_piece_flagged_under_one_range_is_fetched_under_all() { + let (a, b) = (0x1000usize, 0x2000usize); + // Copy a: piece 3 under two ranges, flagged under the first only; + // piece 4 not flagged; copy b: piece 3 not flagged, piece 9 flagged. + let flags = [(a, 3, true), (a, 4, false), (a, 3, false), (b, 3, false), (b, 9, true)]; + let fetch = flagged_pieces(&flags); + assert!(fetch.contains(&(a, 3))); + assert!(!fetch.contains(&(a, 4))); + assert!(!fetch.contains(&(b, 3))); + assert!(fetch.contains(&(b, 9))); + assert_eq!(fetch.len(), 2); + } +} + +/// The most host lists in the air before the flights are settled +/// (`LEONIDA_LATE_WAIT_LISTS`, 256; `=128` is the value before: with the +/// relay it stopped the submitting thread twice a frame for 92-103 ms in +/// all while the card stood idle 64-113 ms a frame, runs 158, 159 and 162; +/// 32 settled the flights three times a +/// frame in run 92 and 64 still 1.3-1.7 times in run 99, with 12,919 tables +/// asked and none refused; watch "tables asked, N refused"): their dynamic +/// descriptor slots, upload +/// memory and scratch chunks are held until then, and a frame's lists held +/// all at once ran the slots out before (run 45). +fn late_most() -> usize { + static MOST: OnceLock = OnceLock::new(); + *MOST.get_or_init(|| { + std::env::var("LEONIDA_LATE_WAIT_LISTS").ok().and_then(|v| v.trim().parse().ok()).unwrap_or(256).max(1) + }) +} + +/// Whether a submission with bottom-of-pipe writes may fly +/// (`LEONIDA_LATE_WAIT_WRITES=0`: it is settled as soon as it is sent, so +/// the title is told at once, as before; for telling a title that polls +/// such a value from one that does not). +fn late_writes() -> bool { + static ON: OnceLock = OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("LEONIDA_LATE_WAIT_WRITES").is_none_or(|v| v != "0")) +} + +/// Per host copy, the ranges a submission's shaders may write, as declared +/// (address, end). +type Declared = (std::sync::Arc, Vec<(usize, usize)>); + +/// What [`Host::submit`] hands back for a submission it sent and did not +/// wait for. +struct Sent { + /// Its number among the submissions started. + number: u64, + card: Option, + back: Vec, + /// Its bottom-of-pipe writes. + writes: Vec<(usize, crate::queue::Written, usize)>, +} + +/// A submission on the card that has not been waited for ([`late`]): its +/// host lists, taken from the title's (which it may reset meanwhile), and +/// what is to be done once it has run. +struct Flight { + number: u64, + /// The value signalled on the host's fence behind it. + fence: u64, + lists: Vec, + order: Vec, + card: Option, + back: Vec, +} + +/// One thing in the line of what waits for the card, in order. +enum Late { + Run(Flight), + /// A bottom-of-pipe write of the flight before it: address, what, bytes. + Write(usize, crate::queue::Written, usize), + /// A fence (its address) signalled behind the flights before it. + Signal(usize, u64), +} + +struct Line { + line: Vec, + /// The title memory the flights' shaders may write (address, end), in + /// order and joined. + written: Vec<(usize, usize)>, + /// Host lists in the flights. + lists: usize, + /// The value signalled on the host's fence behind the last flight. + target: u64, + /// A settle has taken the line and is not done: a signal still goes + /// behind it. + settling: bool, + /// Something was settled away from a queue's own calls: the helper + /// thread looks at what queues hold. + poke: bool, + /// Host lists of settled flights, reset and given back outside the + /// submission lock ([`land`]: a settle may run under a caller's own + /// locks). + landed: Vec<(Vec, Vec)>, + /// With [`relay`]: the bottom-of-pipe writes of the flights being + /// landed (taken out of `line`, not done yet), for [`late_met`]. + in_hand: Vec<(usize, crate::queue::Written, usize)>, +} + +// SAFETY: D3D12 objects (free-threaded) and host lists nothing records +// into; touched under the lock. +unsafe impl Send for Line {} + +static LINE: Mutex = Mutex::new(Line { + line: Vec::new(), + written: Vec::new(), + lists: 0, + target: 0, + settling: false, + poke: false, + landed: Vec::new(), + in_hand: Vec::new(), +}); +/// Told when a flight joins [`LINE`] or it is poked. +static LINE_MOVED: std::sync::Condvar = std::sync::Condvar::new(); + +fn line() -> std::sync::MutexGuard<'static, Line> { + LINE.lock().unwrap_or_else(|e| e.into_inner()) +} + +/// Why flights were settled ([`LATE_STATS`]' places from 2 on). +const WHY_SYNC: usize = 2; +const WHY_CARD_DONE: usize = 3; +const WHY_VALUE: usize = 4; +const WHY_STALE: usize = 5; +const WHY_READ: usize = 6; +const WHY_RUN: usize = 7; +const WHY_MOST: usize = 8; +const WHY_WRITES: usize = 9; +const WHY_FENCE: usize = 10; + +/// Since the last frame-rate line: submissions sent without a wait; +/// settles; settles by reason ([`WHY_SYNC`]..); flights settled; +/// microseconds settles waited for the card; value waits met by a flight's +/// bottom-of-pipe write; fence signals set behind flights. +/// Then: the settles for title memory read, by what read it (a buffer +/// copy, a fill of upload memory, a texture). +static LATE_STATS: [std::sync::atomic::AtomicU64; 18] = [const { std::sync::atomic::AtomicU64::new(0) }; 18]; + +/// Since the last frame-rate line: the microseconds settles waited for the +/// card, by why they settled (the `WHY_` places). +static LATE_WAITED: [std::sync::atomic::AtomicU64; 11] = [const { std::sync::atomic::AtomicU64::new(0) }; 11]; + +/// Whether `[from, to)` touches one of `ranges` (in order, joined). +fn touches(ranges: &[(usize, usize)], from: usize, to: usize) -> bool { + if from >= to { + return false; + } + let at = ranges.partition_point(|r| r.1 <= from); + ranges.get(at).is_some_and(|r| r.0 < to) +} + +/// `ranges` with `more`, in order, joined where they overlap or touch. +fn join_ranges(ranges: &mut Vec<(usize, usize)>, more: impl IntoIterator) { + ranges.extend(more.into_iter().filter(|r| r.0 < r.1)); + ranges.sort_unstable(); + let mut out: Vec<(usize, usize)> = Vec::with_capacity(ranges.len()); + for &(from, to) in ranges.iter() { + match out.last_mut() { + Some(last) if from <= last.1 => last.1 = last.1.max(to), + _ => out.push((from, to)), + } + } + *ranges = out; +} + +/// Whether anything is in the air. +fn flying() -> bool { + if !late() { + return false; + } + let line = line(); + // (With the relay: also while flights are being landed.) + line.settling || line.line.iter().any(|l| matches!(l, Late::Run(_))) +} + +/// With flights in the air ([`late`]): why `runs` cannot be prepared +/// before they are settled, if so. Preparing reads title memory on the +/// CPU (the title's buffer copies, fills of upload memory, textures) and +/// runs steps of ours that may read or write it anywhere; what the +/// flights' shaders write is not there yet. +fn late_blocked(runs: &[&HostList]) -> Option { + let written = { + let line = line(); + if line.written.is_empty() { + return None; + } + line.written.clone() + }; + blocked_by(&written, runs, true) +} + +/// [`late_blocked`] against `written`, the title memory flights' shaders +/// may write (in order, joined); `count` whether the kind of read is +/// counted for the frame line. +fn blocked_by(written: &[(usize, usize)], runs: &[&HostList], count: bool) -> Option { + if written.is_empty() { + return None; + } + for list in runs { + for step in &list.deferred().copies { + match step { + &Step::Copy(dst, src, len) => { + if touches(written, src, src + len) || touches(written, dst, dst + len) { + // A copy that only READS where flights may write is + // not waited for either, and checked like a fill + // (`fill_ahead`): run 210 looked at 197 such waits + // (20,480 bytes out of the 174 MB buffer into a small + // buffer of its own, four a frame, 43 to 60 ms a + // frame) and neither side had other bytes after + // one. A copy INTO such a range still waits. + if !touches(written, dst, dst + len) && fill_ahead::on() { + if count { + fill_ahead::read(src, len); + } + continue; + } + if count { + LATE_STATS[15].fetch_add(1, Ordering::Relaxed); + #[cfg(feature = "diagnostics")] + fill_check::blocked_copy(written, dst, src, len); + } + return Some(WHY_READ); + } + } + &Step::Fill(_, src, len) => { + if touches(written, src, src + len) { + // Not waited for, and checked when the flights land + // (`fill_ahead`). + if fill_ahead::on() { + if count { + fill_ahead::read(src, len); + } + continue; + } + if count { + LATE_STATS[16].fetch_add(1, Ordering::Relaxed); + #[cfg(feature = "diagnostics")] + fill_check::blocked(written, src, len); + } + return Some(WHY_READ); + } + } + Step::Texture(staging) => { + let (at, len) = staging.memory(); + if touches(written, at, at + len) { + if count { + LATE_STATS[17].fetch_add(1, Ordering::Relaxed); + } + return Some(WHY_READ); + } + } + Step::Run(_) => return Some(WHY_RUN), + Step::Refresh(..) | Step::GpuWrite(..) | Step::Host(_) => {} + } + } + } + None +} + +/// Fills of upload memory (a constant buffer a table names, copied into +/// the list's own memory when the list is submitted) that read title memory +/// flights "may write" are no longer waited for; what the flights then +/// write is checked against them, and the first fill that read bytes a +/// flight changed afterwards turns the waiting back on for good. +/// +/// Why: a flight declares every range its shaders can store to, and the +/// title has an unordered view over the whole of its 174 MB buffer, whose +/// copy is in the card's memory. Its per-draw constants lie in the same +/// buffer, at new addresses every frame. So the first such fill of a frame +/// waited until those flights had landed: one wait a frame, 56 to 95 ms of +/// the submitting thread standing still (runs 202 and 206; 145 ms while +/// the world loaded in 208), the largest single wait of the frame. Run 208 +/// looked at every one of them: 44 fills of 480 bytes, and after the wait +/// the bytes were the same 44 times. +/// +/// What it risks, and how it is bounded: a fill that reads bytes a flight +/// in the air is about to change takes the old bytes, and the lists of +/// that one submission draw with them. `wrote` sees it when the flight +/// lands (the bytes going into title memory are compared with the ones +/// there, over every fill that read ahead of them) and from then on fills +/// wait as before. `LEONIDA_FILL_WAIT=1`: they wait from the start. +mod fill_ahead { + use std::collections::HashMap; + use std::sync::atomic::{AtomicBool, AtomicU64, Ordering::Relaxed}; + use std::sync::{Mutex, OnceLock}; + + /// Fills are looked up by the 64 KiB of title memory they read. + const PIECE: usize = 1 << 16; + /// A fill is checked against flights that land this many frames after + /// it at most (flights are settled at 256 lists in the air, and by + /// every present that waits). + const KEEP: u64 = 16; + + /// A flight changed bytes a fill had read ahead of it: fills wait. + static WAIT: AtomicBool = AtomicBool::new(false); + /// Since the last frame line: fills that read ahead; landings' writes + /// that touched one's piece. Since the start: fills that read bytes a + /// flight then changed. + static COUNT: [AtomicU64; 3] = [const { AtomicU64::new(0) }; 3]; + + #[derive(Default)] + struct Piece { + /// The frame its old fills were last dropped in. + pruned: u64, + /// From, to, frame, and the number of the last submission started + /// when it read: the flights in the air then have that number or + /// a lower one, and only their writes can be ones it missed. + fills: Vec<(usize, usize, u64, u64)>, + } + + /// The lowest submission number among the flights the landing thread + /// is landing now; 0: not known (a landing by another way), and then + /// every write counts. (Run 211: a read of frame 1381 was taken for + /// missed because shaders wrote the same 80 bytes in frame 1397, in a + /// flight sent sixteen frames after it.) + static LANDING: AtomicU64 = AtomicU64::new(0); + + pub(super) fn landing(first: u64) { + LANDING.store(first, Relaxed); + } + + static READ: Mutex>> = Mutex::new(None); + + pub(super) fn on() -> bool { + static ON: OnceLock = OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("LEONIDA_FILL_WAIT").is_none_or(|v| v != "1")) && !WAIT.load(Relaxed) + } + + /// A fill reads `len` bytes at `src` ahead of flights that may write + /// them. + pub(super) fn read(src: usize, len: usize) { + if len == 0 { + return; + } + COUNT[0].fetch_add(1, Relaxed); + let frame = crate::frame::current(); + let mut read = READ.lock().unwrap_or_else(|e| e.into_inner()); + let map = read.get_or_insert_with(HashMap::new); + for piece in src / PIECE..=(src + len - 1) / PIECE { + let p = map.entry(piece).or_default(); + if p.pruned != frame { + p.pruned = frame; + p.fills.retain(|f| f.2 + KEEP >= frame); + } + p.fills.push((src, src + len, frame, super::STARTED.load(Relaxed))); + } + } + + /// A landing is about to put `new` into title memory at `at`: bytes + /// shaders wrote, merged into the title's. + pub(crate) fn wrote(at: usize, new: &[u8]) { + if new.is_empty() || WAIT.load(Relaxed) { + return; + } + let frame = crate::frame::current(); + let landing = LANDING.load(Relaxed); + let hits: Vec<(usize, usize, u64)> = { + let read = READ.lock().unwrap_or_else(|e| e.into_inner()); + let Some(map) = read.as_ref() else { return }; + let end = at + new.len(); + (at / PIECE..=(end - 1) / PIECE) + .filter_map(|piece| map.get(&piece)) + .flat_map(|p| p.fills.iter().copied()) + .filter(|f| f.0 < end && f.1 > at && f.2 + KEEP >= frame && (landing == 0 || landing <= f.3)) + .map(|f| (f.0, f.1, f.2)) + .collect() + }; + if hits.is_empty() { + return; + } + COUNT[1].fetch_add(1, Relaxed); + let mut now = Vec::new(); + for (from, to, read_in) in hits { + let (a, b) = (from.max(at), to.min(at + new.len())); + now.clear(); + now.resize(b - a, 0); + // Title memory as it is, which is what the fill read unless the + // title wrote it since; not there: nothing to say. + if !super::read_into(a as *const u8, &mut now) || now[..] == new[a - at..b - at] { + continue; + } + let n = COUNT[2].fetch_add(1, Relaxed) + 1; + let first = now.iter().zip(&new[a - at..b - at]).position(|(x, y)| x != y).unwrap_or(0); + if !WAIT.swap(true, Relaxed) { + tracing::warn!( + "a fill of upload memory read {} bytes at {from:#x} in frame {read_in} ahead of a flight whose shaders changed \ + them (first at {:#x}, landed in frame {frame}): the lists of that submission drew with the bytes from before. \ + Fills wait for flights again from here on, as with LEONIDA_FILL_WAIT=1 ({n} such fills)", + to - from, + a + first + ); + } + return; + } + } + + /// With the frame line. + pub(super) fn line(frames: f64) { + let [ahead, looked] = [0, 1].map(|i| COUNT[i].swap(0, Relaxed)); + if ahead == 0 && looked == 0 { + return; + } + let kept = { + let frame = crate::frame::current(); + let mut read = READ.lock().unwrap_or_else(|e| e.into_inner()); + read.as_mut().map_or(0, |map| { + map.retain(|_, p| { + p.fills.retain(|f| f.2 + KEEP >= frame); + !p.fills.is_empty() + }); + map.values().map(|p| p.fills.len()).sum::() + }) + }; + tracing::info!( + "fills of upload memory that read title memory flights may write, not waited for (LEONIDA_FILL_WAIT=1 waits): {:.1} per \ + frame; {:.1} landings' writes per frame fell in the same 64 KiB as one and were compared with it; fills that read \ + bytes a flight then changed, since the start: {}{}; {kept} fills kept to check", + ahead as f64 / frames, + looked as f64 / frames, + COUNT[2].load(Relaxed), + if WAIT.load(Relaxed) { " (fills wait again)" } else { "" } + ); + } +} + +pub(crate) use fill_ahead::wrote as shaders_write; + +/// Diagnostics: the fills of upload memory that made a submission wait for +/// flights (`blocked_by`), which one they are, and whether the wait was +/// needed: the bytes the fill reads are kept when it blocks and compared +/// with what it reads once the flights have landed. +/// +/// Runs 202 and 206: one such wait a frame, 56 to 95 ms of the submitting +/// thread standing still, the largest single wait of the frame. The ranges +/// flights "may write" are whole views shaders can store to; if the bytes +/// a fill reads never change under the wait, the wait is for nothing. +#[cfg(feature = "diagnostics")] +mod fill_check { + use std::sync::Mutex; + use std::sync::atomic::{AtomicU64, Ordering::Relaxed}; + + /// The fill waited for now: source, length, its bytes when it blocked. + static PENDING: Mutex)>> = Mutex::new(None); + /// Fills that blocked by (source page, length): how often. + static SEEN: Mutex> = Mutex::new(Vec::new()); + /// Fills checked after their wait; those whose bytes had changed; the + /// bytes that had. + static CHECKED: [AtomicU64; 3] = [const { AtomicU64::new(0) }; 3]; + + /// A fill of `len` bytes at `src` blocks on `written`. + pub(super) fn blocked(written: &[(usize, usize)], src: usize, len: usize) { + let at = written.partition_point(|r| r.1 <= src); + let touched = written.get(at).copied().unwrap_or((0, 0)); + let key = (src & !0xfff, len); + let mut seen = SEEN.lock().unwrap_or_else(|e| e.into_inner()); + let known = seen.iter().position(|s| (s.0, s.1) == key); + match known { + Some(k) => seen[k].2 += 1, + None if seen.len() < 256 => { + seen.push((key.0, key.1, 1)); + if seen.len() <= 12 { + tracing::info!( + "a fill of upload memory waits for flights: {len} bytes at {src:#x}; the range shaders may write that it touches: {:#x}+{:#x} ({} ranges in the air); frame {}", + touched.0, + touched.1 - touched.0, + written.len(), + crate::frame::current() + ); + } + } + None => {} + } + drop(seen); + let mut bytes = vec![0u8; len.min(1 << 20)]; + if super::read_into(src as *const u8, &mut bytes) { + *PENDING.lock().unwrap_or_else(|e| e.into_inner()) = Some((src, len, bytes)); + } + } + + /// The fill of `len` bytes at `src` runs now. + pub(super) fn runs(src: usize, len: usize) { + let mut pending = PENDING.lock().unwrap_or_else(|e| e.into_inner()); + if !pending.as_ref().is_some_and(|p| (p.0, p.1) == (src, len)) { + return; + } + let Some((_, _, before)) = pending.take() else { return }; + drop(pending); + let mut now = vec![0u8; before.len()]; + if !super::read_into(src as *const u8, &mut now) { + return; + } + let differ = before.iter().zip(&now).filter(|(a, b)| a != b).count() as u64; + let n = CHECKED[0].fetch_add(1, Relaxed) + 1; + if differ > 0 { + let bad = CHECKED[1].fetch_add(1, Relaxed) + 1; + CHECKED[2].fetch_add(differ, Relaxed); + if bad <= 12 { + let first = before.iter().zip(&now).position(|(a, b)| a != b).unwrap_or(0); + tracing::info!( + "a fill of upload memory that waited for flights read other bytes after the wait: {differ} of {len} bytes at {src:#x} changed, the first at +{first:#x} (check {n}, frame {})", + crate::frame::current() + ); + } + } + } + + /// The title buffer copy waited for now: destination, source, length, + /// the bytes of both when it blocked. + static PENDING_COPY: Mutex, Vec)>> = Mutex::new(None); + /// Copies checked after their wait; those whose source had changed; + /// those whose destination had. + static COPIES: [AtomicU64; 3] = [const { AtomicU64::new(0) }; 3]; + /// Copies that blocked by (source page, destination page, length). + static SEEN_COPIES: Mutex> = Mutex::new(Vec::new()); + + /// A title buffer copy of `len` bytes from `src` to `dst` blocks on + /// `written`. + pub(super) fn blocked_copy(written: &[(usize, usize)], dst: usize, src: usize, len: usize) { + let by_src = super::touches(written, src, src + len); + let by_dst = super::touches(written, dst, dst + len); + let key = (src & !0xfff, dst & !0xfff, len); + let mut seen = SEEN_COPIES.lock().unwrap_or_else(|e| e.into_inner()); + let known = seen.iter().position(|s| (s.0, s.1, s.2) == key); + match known { + Some(k) => seen[k].3 += 1, + None if seen.len() < 256 => { + seen.push((key.0, key.1, key.2, 1)); + if seen.len() <= 16 { + let range = |at: usize| { + let k = written.partition_point(|r| r.1 <= at); + written.get(k).copied().unwrap_or((0, 0)) + }; + let (s, d) = (range(src), range(dst)); + tracing::info!( + "a title buffer copy waits for flights: {len} bytes from {src:#x} to {dst:#x}; source in a range shaders may write: {by_src} ({:#x}+{:#x}); destination: {by_dst} ({:#x}+{:#x}); {} ranges in the air; frame {}", + s.0, + s.1 - s.0, + d.0, + d.1 - d.0, + written.len(), + crate::frame::current() + ); + } + } + None => {} + } + drop(seen); + let n = len.min(1 << 20); + let (mut a, mut b) = (vec![0u8; n], vec![0u8; n]); + if super::read_into(src as *const u8, &mut a) && super::read_into(dst as *const u8, &mut b) { + *PENDING_COPY.lock().unwrap_or_else(|e| e.into_inner()) = Some((dst, src, len, a, b)); + } + } + + /// The title buffer copy runs now. + pub(super) fn copy_runs(dst: usize, src: usize, len: usize) { + let mut pending = PENDING_COPY.lock().unwrap_or_else(|e| e.into_inner()); + if !pending.as_ref().is_some_and(|p| (p.0, p.1, p.2) == (dst, src, len)) { + return; + } + let Some((_, _, _, src_before, dst_before)) = pending.take() else { return }; + drop(pending); + let (mut a, mut b) = (vec![0u8; src_before.len()], vec![0u8; dst_before.len()]); + if !super::read_into(src as *const u8, &mut a) || !super::read_into(dst as *const u8, &mut b) { + return; + } + let n = COPIES[0].fetch_add(1, Relaxed) + 1; + let (src_changed, dst_changed) = (a != src_before, b != dst_before); + if src_changed { + COPIES[1].fetch_add(1, Relaxed); + } + if dst_changed { + COPIES[2].fetch_add(1, Relaxed); + } + if (src_changed || dst_changed) && COPIES[1].load(Relaxed) + COPIES[2].load(Relaxed) <= 16 { + let differ = |x: &[u8], y: &[u8]| x.iter().zip(y).filter(|(p, q)| p != q).count(); + tracing::info!( + "a title buffer copy that waited for flights found other bytes after the wait: {len} bytes from {src:#x} to {dst:#x}; {} source bytes changed, {} destination bytes changed (check {n}, frame {})", + differ(&a, &src_before), + differ(&b, &dst_before), + crate::frame::current() + ); + } + } + + /// With the frame line. + pub(super) fn line() { + let copies = COPIES[0].load(Relaxed); + if copies > 0 { + let seen = SEEN_COPIES.lock().unwrap_or_else(|e| e.into_inner()); + let mut most: Vec<_> = seen.clone(); + most.sort_unstable_by_key(|s| std::cmp::Reverse(s.3)); + let most: Vec = + most.iter().take(6).map(|s| format!("{:#x}->{:#x}+{:#x} {}x", s.0, s.1, s.2, s.3)).collect(); + tracing::info!( + "title buffer copies that waited for flights, since the start: {copies} checked after their wait; the source had other bytes after it {} times, the destination {} times; {} distinct copies, the most frequent: {}", + COPIES[1].load(Relaxed), + COPIES[2].load(Relaxed), + seen.len(), + most.join(", ") + ); + } + let n = CHECKED[0].load(Relaxed); + if n == 0 { + return; + } + let seen = SEEN.lock().unwrap_or_else(|e| e.into_inner()); + let mut most: Vec<_> = seen.clone(); + most.sort_unstable_by_key(|s| std::cmp::Reverse(s.2)); + let most: Vec = most.iter().take(6).map(|s| format!("{:#x}+{:#x} {}x", s.0, s.1, s.2)).collect(); + tracing::info!( + "fills of upload memory that waited for flights, since the start: {n} checked after their wait, {} of them read other bytes than before it ({} bytes in all); {} distinct fills (page, length), the most frequent: {}", + CHECKED[1].load(Relaxed), + CHECKED[2].load(Relaxed), + seen.len(), + most.join(", ") + ); + } +} + +/// With flights in the air, after the submission's write-watch asking: +/// whether `runs` refresh a range of a host copy that a flight's shaders +/// may write and that the title wrote since it was last copied. The +/// refresh leaves ranges shaders are writing alone (`Shadow::update`), so +/// the title's bytes there would reach the card a submission late. +fn stale_under_flights(runs: &[&HostList]) -> bool { + use std::sync::Arc; + // Per copy, the span of what is refreshed (a flush brings that much + // up to date at most). + let mut spans: Vec<(Arc, usize, usize)> = Vec::new(); + for list in runs { + for step in &list.deferred().copies { + if let Step::Refresh(shadow, address, len) = step + && shadow.writes_pending() + { + match spans.iter_mut().find(|s| Arc::ptr_eq(&s.0, shadow)) { + Some(s) => (s.1, s.2) = (s.1.min(*address), s.2.max(*address + *len)), + None => spans.push((shadow.clone(), *address, *address + *len)), + } + } + } + } + if late_exact() { + // The title's bytes are put in beside the flights' writes; a + // settle is still due where that could not be done. At most this + // many changed runs go up to copies in the card's memory, each a + // copy of its own there. + // (`LEONIDA_MERGE_RUNS`: the cap. Run 218 had 500 to 5,400 changed + // runs a frame of a few bytes each, and the cap of 512 settled the + // flights twice a frame, 50 ms of the submitting thread.) + static RUNS: OnceLock = OnceLock::new(); + let mut runs_left = *RUNS.get_or_init(|| { + std::env::var("LEONIDA_MERGE_RUNS").ok().and_then(|v| v.trim().parse::().ok()).map_or(512, |n| n.clamp(1, 1 << 16)) + }); + return spans.iter().any(|(shadow, from, to)| shadow.merge_under_writes(*from, *to - *from, &mut runs_left)); + } + spans.iter().any(|(shadow, from, to)| shadow.stale_under_writes(*from, *to - *from)) +} + +/// A fence signal on a queue ([`late`]): goes behind the flights in the +/// air, if there are any, and is set when they are settled. Whether it +/// did; if not the caller sets the fence now. +pub(crate) fn late_signal(fence: usize, value: u64) -> bool { + if !late() { + return false; + } + let mut line = line(); + if line.line.is_empty() && !line.settling { + return false; + } + line.line.push(Late::Signal(fence, value)); + LATE_STATS[14].fetch_add(1, Ordering::Relaxed); + drop(line); + // A signal alone (behind a settle under way) has no flight to wake + // the helper thread for it. + LINE_MOVED.notify_one(); + RELAY_MOVED.notify_one(); + true +} + +/// A queue stands at `wait`, which memory does not meet now ([`late`]): +/// whether it is met once the flights in the air have run. A flight's +/// bottom-of-pipe write of a value that meets it says yes without a wait +/// for the card: the part behind the wait goes to the card behind that +/// flight, which is the order the wait asks for. If the flights may write +/// the value in a way not known here (shaders, a timestamp, another +/// width), they are settled and memory is asked again. +pub(crate) fn late_met(wait: &crate::list::ValueWait) -> bool { + let (address, bytes) = wait.place(); + { + let line = line(); + if line.line.is_empty() && line.in_hand.is_empty() { + return false; + } + let mut unsure = touches(&line.written, address, address + bytes); + // (With the relay: first the writes of flights being landed.) + let writes = line.in_hand.iter().map(|(at, what, n)| (at, what, n)).chain(line.line.iter().filter_map(|item| match item { + Late::Write(at, what, n) => Some((at, what, n)), + _ => None, + })); + for (at, what, n) in writes { + if *at >= address + bytes || address >= *at + *n { + continue; + } + match what { + crate::queue::Written::Value(v) if *at == address && *n >= bytes => { + if wait.holds_for(*v) { + LATE_STATS[13].fetch_add(1, Ordering::Relaxed); + return true; + } + } + _ => unsure = true, + } + } + if !unsure { + return false; + } + } + settle_now(WHY_VALUE); + wait.met() +} + +/// [`late_met`] without its settle: whether a bottom-of-pipe write of a +/// flight in the air, or of one being landed, is known to meet `wait`. +/// False says nothing about what else the flights may write there. +pub(crate) fn late_met_known(wait: &crate::list::ValueWait) -> bool { + let (address, bytes) = wait.place(); + let line = line(); + let writes = line.in_hand.iter().map(|(at, what, n)| (at, what, n)).chain(line.line.iter().filter_map(|item| match item { + Late::Write(at, what, n) => Some((at, what, n)), + _ => None, + })); + for (at, what, n) in writes { + if let crate::queue::Written::Value(v) = what + && *at == address + && *n >= bytes + && wait.holds_for(*v) + { + LATE_STATS[13].fetch_add(1, Ordering::Relaxed); + return true; + } + } + false +} + +/// Settles the flights in the air, if any ([`Host::settle`]), for reason +/// `why` (one of the `WHY_` places). Not from inside a submission. +pub(crate) fn settle_now(why: usize) { + if !late() { + return; + } + let Some(host) = host() else { + return; + }; + let mut submitted = host.submitted.lock().unwrap_or_else(|e| e.into_inner()); + host.settle(&mut submitted, why); +} + +/// [`settle_now`] at a present, and for a fence the title blocks on. +pub(crate) fn settle_for_present() { + settle_now(WHY_SYNC); +} +pub(crate) fn settle_for_fence() { + settle_now(WHY_FENCE); +} + +/// Resets the host lists of settled flights and keeps them for reuse, as +/// a queue does for the lists it ran (`crate::list::recycle`). +fn land() { + let landed = std::mem::take(&mut line().landed); + for (lists, order) in landed { + crate::list::recycle(lists, &order); + } +} + +/// The thread that settles the flights once the card has run them all +/// ([`late`]): without it a bottom-of-pipe write would reach the title only +/// at the next call that settles, and a title thread that polls such a +/// value while the submitting thread waits for that thread would never +/// see it. +fn late_helper() { + let Some(host) = host() else { + return; + }; + crate::framelog::keep_on_fast_cores("leonida-late-wait"); + // SAFETY: a plain event of our own. + let Ok(event) = (unsafe { CreateEventW(None, false, false, None) }) else { + tracing::warn!("no event for the thread that settles submissions sent ahead"); + return; + }; + loop { + let target = { + let mut line = line(); + loop { + if line.poke { + line.poke = false; + break None; + } + // (With the relay the flights are another thread's.) + if !relay() && !line.line.is_empty() && !line.settling { + break Some(line.target); + } + line = LINE_MOVED.wait(line).unwrap_or_else(|e| e.into_inner()); + } + }; + let Some(target) = target else { + land(); + crate::queue::release_held(false); + continue; + }; + // The card first, without the submission lock: the submitting + // thread prepares and sends meanwhile. + // SAFETY: our fence and event. + unsafe { + if host.fence.SetEventOnCompletion(target, event).is_ok() { + WaitForSingleObject(event, INFINITE); + } + } + { + let mut submitted = host.submitted.lock().unwrap_or_else(|e| e.into_inner()); + // Something newer went up meanwhile: the card is waited for + // again, the submitting thread is not held up for it. + if line().target != target { + continue; + } + host.settle(&mut submitted, WHY_CARD_DONE); + } + land(); + crate::queue::release_held(false); + } +} + +/// Starts the threads of [`late`], once: the one that settles flights when +/// the card has run them and looks at what queues hold, and with [`relay`] +/// the one that lands flights. +fn late_threads() { + static HELPER: std::sync::Once = std::sync::Once::new(); + HELPER.call_once(|| { + if let Err(e) = std::thread::Builder::new().name("leonida-late-wait".into()).spawn(late_helper) { + tracing::warn!(error = %e, "no thread to settle submissions sent ahead: they are settled by the calls that follow"); + } + tracing::info!( + most = late_most(), + writes = late_writes(), + "submissions are sent to the card without a wait for each (LEONIDA_LATE_WAIT=1)" + ); + if relay() { + // Without it nothing would ever land. + if let Err(e) = std::thread::Builder::new().name("leonida-relay".into()).spawn(relay_worker) { + fail(format_args!("no thread to land submissions sent ahead (LEONIDA_RELAY=1): {e}")); + } + tracing::info!( + exact = relay_exact(), + "what shaders wrote is copied back by a thread of its own, beside the submitting thread (LEONIDA_RELAY=1)" + ); + } + }); +} + +/// With [`relay`]: waits until `done` says so of the line, looked at each +/// time flights have landed. Counted as a settle for `why`, and its time +/// as waiting for the card. The caller may hold the submission lock: the +/// thread that lands flights never takes it. +fn relay_wait(why: usize, done: impl Fn(&Line) -> bool) { + let mut line = line(); + if done(&line) { + return; + } + LATE_STATS[1].fetch_add(1, Ordering::Relaxed); + LATE_STATS[why].fetch_add(1, Ordering::Relaxed); + let was_working = working(false); + let waiting = std::time::Instant::now(); + while !done(&line) { + line = LINE_LANDED.wait(line).unwrap_or_else(|e| e.into_inner()); + } + drop(line); + stood(waiting); + working(was_working); + let us = waiting.elapsed().as_micros() as u64; + LATE_STATS[12].fetch_add(us, Ordering::Relaxed); + LATE_WAITED[why.min(10)].fetch_add(us, Ordering::Relaxed); + submission_us(1, us); +} + +/// What the thread that lands flights fetches card copies' pieces with +/// ([`relay`]): a list, a fence and an event of its own (the host's are +/// behind the submission lock), and the memory the pieces come down to. +struct RelayFetch { + list: Prelude, + fence: ID3D12Fence, + event: HANDLE, + /// The last value signalled on `fence`. + sent: u64, + /// Buffer, mapping, bytes. + buffer: Option<(ID3D12Resource, usize, u64)>, +} + +/// The thread that lands flights ([`relay`]): as soon as the card has run +/// the first flights of the line it takes them, with what follows them, +/// and does what they left to do ([`Host::relay_land`]); else it waits for +/// the card, or for a flight. It takes neither the submission lock nor +/// anything a caller of [`Host::settle`] may hold: resetting the landed +/// lists and looking at what queues hold are left to [`late_helper`]. +fn relay_worker() { + let Some(host) = host() else { + return; + }; + crate::framelog::keep_on_fast_cores("leonida-relay"); + // SAFETY: a plain event of our own. + let Ok(event) = (unsafe { CreateEventW(None, false, false, None) }) else { + fail(format_args!("no event for the thread that lands submissions sent ahead (LEONIDA_RELAY=1)")); + }; + let mut fetch: Option = None; + loop { + let next = { + let mut line = line(); + loop { + if line.line.is_empty() { + line = RELAY_MOVED.wait(line).unwrap_or_else(|e| e.into_inner()); + continue; + } + let fences: Vec> = line + .line + .iter() + .map(|l| match l { + Late::Run(flight) => Some(flight.fence), + _ => None, + }) + .collect(); + // SAFETY: a plain query. + let completed = unsafe { host.fence.GetCompletedValue() }; + let n = landable(&fences, completed); + if n == 0 { + // The first thing is a flight the card has not run. + break Err(fences[0].unwrap_or(0)); + } + line.settling = true; + let items: Vec = line.line.drain(..n).collect(); + line.in_hand = items + .iter() + .filter_map(|l| match l { + Late::Write(at, what, bytes) => Some((*at, *what, *bytes)), + _ => None, + }) + .collect(); + break Ok(items); + } + }; + match next { + Ok(items) => host.relay_land(items, &mut fetch), + Err(target) => { + let waiting = std::time::Instant::now(); + // SAFETY: the host's fence and this thread's event. + let waited = unsafe { + host.fence.SetEventOnCompletion(target, event).map(|()| { + WaitForSingleObject(event, INFINITE); + }) + }; + if waited.is_err() { + std::thread::sleep(std::time::Duration::from_millis(1)); + } + RELAY_STATS[2].fetch_add(waiting.elapsed().as_micros() as u64, Ordering::Relaxed); + } + } + } +} + +/// [`relay`]: what shaders wrote to the declared ranges `back` of copies +/// in the PC's memory goes into title memory. As [`hand_back`], each byte +/// once, the pieces that differ found on several threads; but the merge is +/// `Shadow::relay_merge`, which does not write the copy, and the ranges +/// are not done with here (each flight's are, afterwards). +fn relay_hand_back(back: &[Declared]) { + let mut work: Vec<(std::sync::Arc, usize, usize)> = Vec::new(); + for (shadow, declared) in back { + if shadow.carded() { + continue; + } + let mut spans: Vec<(usize, usize)> = Vec::new(); + join_ranges(&mut spans, declared.iter().copied()); + for &(from, to) in &spans { + shadow.relay_compared(from, to - from); + } + work.extend(spans.into_iter().map(|(from, to)| (shadow.clone(), from, to))); + } + if work.is_empty() { + return; + } + #[cfg(feature = "diagnostics")] + let scanning = std::time::Instant::now(); + // Looked through without a lock: a piece that changes meanwhile (a + // later flight writing, the title's bytes going in) is found now or by + // that flight's landing, and the merge looks again under the lock. + let found = crate::shadow::find_all(&work); + #[cfg(feature = "diagnostics")] + crate::copystat::add(crate::copystat::C::BackScanUs, scanning.elapsed().as_micros() as u64); + let (mut now, mut title) = (Vec::new(), Vec::new()); + for ((shadow, from, to), found) in work.iter().zip(found) { + let mut written = 0; + for (at, n) in found { + written += shadow.relay_merge(at, n, &mut now, &mut title); + } + copy_back(1, written as u64); + #[cfg(feature = "diagnostics")] + crate::copystat::compared(*from, to - from, written); + let _ = (from, to); + } +} + +/// For the frame-rate line, with [`late`]: what the line of flights did +/// per frame since the last one. +fn late_line(frames: f64) { + if !late() { + return; + } + #[cfg(feature = "diagnostics")] + fill_check::line(); + fill_ahead::line(frames); + let s: Vec = LATE_STATS.iter().map(|s| s.swap(0, Ordering::Relaxed) as f64 / frames).collect(); + tracing::info!( + "submissions sent ahead per frame: {:.1} in {:.1} settles ({:.1} flights each time), {:.1} ms waiting for the card in them; \ + settled for: a synchronous submission or present {:.1}, the card had run them {:.1}, a wait for a memory value {:.1}, \ + title memory changed under shader writes {:.1}, title memory read {:.1} (by a buffer copy {:.1}, a fill of upload memory {:.1}, \ + a texture {:.1}), a step of ours {:.1}, {} lists in the air {:.1}, \ + bottom-of-pipe writes (LEONIDA_LATE_WAIT_WRITES=0) {:.1}, a blocking fence wait {:.1}; \ + {:.1} waits for memory values met by a flight's bottom-of-pipe write, {:.1} fence signals set behind flights", + s[0], + s[1], + if s[1] > 0.0 { s[11] / s[1] } else { 0.0 }, + s[12] / 1000.0, + s[WHY_SYNC], + s[WHY_CARD_DONE], + s[WHY_VALUE], + s[WHY_STALE], + s[WHY_READ], + s[15], + s[16], + s[17], + s[WHY_RUN], + late_most(), + s[WHY_MOST], + s[WHY_WRITES], + s[WHY_FENCE], + s[13], + s[14], + ); + { + let w: Vec = LATE_WAITED.iter().map(|w| w.swap(0, Ordering::Relaxed) as f64 / 1000.0 / frames).collect(); + tracing::info!( + "of the waiting for the card in settles, per frame, by what settled: a synchronous submission or present {:.1} ms, \ + the card had run them {:.1}, a wait for a memory value {:.1}, title memory changed under shader writes {:.1}, \ + title memory read {:.1}, a step of ours {:.1}, lists in the air {:.1}, bottom-of-pipe writes {:.1}, a blocking fence wait {:.1}", + w[WHY_SYNC], + w[WHY_CARD_DONE], + w[WHY_VALUE], + w[WHY_STALE], + w[WHY_READ], + w[WHY_RUN], + w[WHY_MOST], + w[WHY_WRITES], + w[WHY_FENCE], + ); + } + if relay() { + let r: Vec = RELAY_STATS.iter().map(|r| r.swap(0, Ordering::Relaxed) as f64 / frames).collect(); + let [again, noted] = [0, 1].map(|i| BESIDE_STATS[i].swap(0, Ordering::Relaxed) as f64 / frames); + tracing::info!( + "the relay per frame (LEONIDA_RELAY={}): {:.1} flights landed in {:.1} landings by the thread that copies back, \ + beside the submitting thread; that thread waited {:.1} ms for the card with nothing to land and {:.1} ms for \ + fetches of card copies' pieces, and was {:.1} ms landing in all (the frame line's \"copying back\" is its time; \ + \"settles\" above are waits of other threads for it); pieces fetched on the copy queue beside later \ + submissions: {noted:.1}, pieces those fetched again at their own landing whatever the compare said: {again:.1} \ + (LEONIDA_QUEUE2_REFETCH)", + if relay_exact() { 2 } else { 1 }, + r[1], + r[0], + r[2] / 1000.0, + r[3] / 1000.0, + r[4] / 1000.0, + ); + if inflight_fetch() { + let i: Vec = INFLIGHT_STATS.iter().map(|i| i.swap(0, Ordering::Relaxed) as f64 / frames).collect(); + tracing::info!( + "card copies' pieces fetched inside their flights per frame (LEONIDA_CARD_FETCH_INFLIGHT=1): {:.1} pieces \ + ({:.2} MB) merged with no fetch of their own; {:.1} landings fetched the old way (the wait above), {:.1} of \ + them because a flight's pieces overflowed the slots", + i[0], + i[1] / (1 << 20) as f64, + i[3], + i[2], + ); + } + } + if late_exact() { + let [pages, runs, bytes] = crate::shadow::merged_stats().map(|n| n as f64 / frames); + tracing::info!( + "title bytes put in under flights' shader writes per frame (LEONIDA_LATE_WAIT=2): {pages:.0} pages looked at, \ + {runs:.0} changed runs, {:.2} MB", + bytes / (1 << 20) as f64 + ); + } +} + +#[cfg(test)] +mod late_tests { + use super::{continues, join_ranges, touches}; + + /// Copies join only when both ends continue and the whole does not + /// overlap itself. + #[test] + fn copies_join_only_end_to_end_and_apart() { + // (destination, source, bytes) + assert!(continues((1000, 5000, 16), (1016, 5016, 32))); + assert!(continues((5000, 1000, 16), (5016, 1016, 32))); + // A gap, or only one side continues. + assert!(!continues((1000, 5000, 16), (1020, 5016, 32))); + assert!(!continues((1000, 5000, 16), (1016, 5020, 32))); + assert!(!continues((1000, 5000, 16), (1000, 5000, 16))); + // Together they would overlap: the second reads what the first wrote. + assert!(!continues((1000, 1016, 16), (1016, 1032, 16))); + assert!(!continues((1016, 1000, 16), (1032, 1016, 16))); + // They touch without overlapping. + assert!(continues((1000, 1032, 16), (1016, 1048, 16))); + assert!(!continues((usize::MAX - 8, 0, 8), (0, 8, 8))); + } + + /// Ranges are found by what they hold, not by where they start, and a + /// range that only touches another's end does not touch it. + #[test] + fn ranges_touch_where_they_overlap() { + let mut ranges = Vec::new(); + join_ranges(&mut ranges, [(40, 50), (10, 20), (20, 25), (45, 60), (7, 7)]); + assert_eq!(ranges, [(10, 25), (40, 60)]); + join_ranges(&mut ranges, [(25, 40)]); + assert_eq!(ranges, [(10, 60)]); + let ranges = [(10usize, 25usize), (40, 60), (100, 101)]; + for (from, to, hit) in [ + (0, 10, false), + (0, 11, true), + (24, 25, true), + (25, 40, false), + (25, 41, true), + (59, 200, true), + (60, 100, false), + (100, 101, true), + (101, 500, false), + (30, 30, false), + (50, 50, false), + ] { + assert_eq!(touches(&ranges, from, to), hit, "{from}..{to}"); + } + assert!(!touches(&[], 0, usize::MAX)); + } +} + +/// Whether a title buffer copy that continues the one recorded before it +/// in its list becomes one step with it (`LEONIDA_JOIN_COPIES=1`; off by +/// default). +/// +/// Each copy is done at submission through the kernel, which reports a +/// page that is not there instead of faulting (`copy_mapped`), tells the +/// write watch and the guards, and ends the refreshes gathered so far: a +/// call into the kernel for some 480 bytes, 14,042 times a frame in run 86 +/// (6.8 MB; "moves 19 ms" with the refreshes' own reads). How many of them +/// continue the one before is counted either way and said on its own line +/// with the frame rate; the switch is worth that many kernel calls. +/// +/// Joined, the same bytes move: [`continues`] joins only copies whose +/// ranges, taken together, do not overlap, and nothing is recorded between +/// two steps that follow each other. What differs: a page that is not +/// mapped now fails the joined copy as a whole (it then goes page by page, +/// zeros for what cannot be read, as a single copy does), where before +/// only the copy that held it did. +fn join_copies() -> bool { + static ON: OnceLock = OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("LEONIDA_JOIN_COPIES").is_some_and(|v| v == "1")) +} + +/// Since the last frame-rate line: title buffer copies recorded, and those +/// that continue the one before ([`join_copies`]). +static COPIES_JOINED: [std::sync::atomic::AtomicU64; 2] = [const { std::sync::atomic::AtomicU64::new(0) }; 2]; + +/// Whether the copy `next` (destination, source, bytes) goes on exactly +/// where `last` ended, source and destination both, and the two as one do +/// not overlap (source over destination): then one copy of both moves the +/// bytes the two would move in turn. +fn continues(last: (usize, usize, usize), next: (usize, usize, usize)) -> bool { + let ((d, s, n), (dst, src, len)) = (last, next); + let Some(all) = n.checked_add(len) else { + return false; + }; + d.checked_add(n) == Some(dst) + && s.checked_add(n) == Some(src) + && (d.checked_add(all).is_some_and(|end| end <= s) || s.checked_add(all).is_some_and(|end| end <= d)) +} + +/// The ranges the shaders of `runs` may write, per host copy, as declared. +/// One list's lock at a time: a submission may name a list twice. +fn declared_writes(runs: &[&HostList]) -> Vec { + let mut back: Vec = Vec::new(); + for list in runs { + for step in &list.deferred().copies { + if let Step::GpuWrite(shadow, address, len) = step { + let range = (*address, *address + *len); + match back.iter_mut().find(|(s, _)| std::sync::Arc::ptr_eq(s, shadow)) { + Some((_, ranges)) => { + if !ranges.contains(&range) { + ranges.push(range); + } + } + None => back.push((shadow.clone(), vec![range])), + } + } + } + } + back +} + +/// The walls trace (`LEONIDA_WALLS_TRACE=1` or `2`; off by default): log +/// lines that say what the title's CPU was given while it decided whether +/// the camera is in a room. The values of the small read-backs +/// ([`read_backs`]), the frame's main pass by scissor rectangle with its +/// culling dispatches (`draw.rs`, `walls_census`), the shader-written +/// buffers merged into title memory (`shadow.rs`, `walls_merged`), host +/// copies found stale after their refresh (`shadow.rs`; only with +/// `LEONIDA_REFRESH_CHECK=1` as well: it costs about 100 ms a frame), and, in the +/// runtime, the read requests that fail (with 2: every request). +pub(crate) fn walls_trace() -> bool { + static ON: OnceLock = OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("LEONIDA_WALLS_TRACE").is_some_and(|v| v == "1" || v == "2")) +} + +/// After `list` has run: the texels its read-backs copied into host +/// buffers of ours go to the title's memory (`HostList::defer_read_back`). +/// +/// A submission that is waited for did this itself. One sent ahead +/// ([`late`]) did not, at any stage: the flights' lists were settled +/// without it, so the title read a buffer nobody wrote, as before read-backs +/// were made (the exposure metering's two small float targets, every frame). +fn read_backs(list: &HostList) { + for (buffer, at, [row, rows, pitch]) in &list.deferred().backs { + let mut data = std::ptr::null_mut(); + // SAFETY: a read-back buffer of ours, written by the list that has + // run; the title's destination holds every row (checked when the + // copy was recorded). + unsafe { + if buffer.Map(0, None, Some(&mut data)).is_ok() && !data.is_null() { + let from = data.cast::().cast_const(); + for line in 0..*rows { + std::ptr::copy_nonoverlapping(from.add(line * row.next_multiple_of(256)), (*at as *mut u8).add(line * pitch), *row); + } + // The walls trace: what the title is handed (one row of at + // most 24 values: its 5x1 and 1x1 float targets). + if walls_trace() && *rows == 1 && *row <= 96 { + let mut values = [0f32; 24]; + std::ptr::copy_nonoverlapping(from, values.as_mut_ptr().cast::(), *row & !3); + tracing::info!( + frame = crate::frame::current(), + to = format_args!("{:#x}", *at), + bytes = *row, + values = ?&values[..*row / 4], + "walls trace: a read-back lands in title memory" + ); + } + buffer.Unmap(0, None); + } + } + } +} + +/// After the card ran what declared `back`: what shaders wrote there goes +/// into title memory, and the ranges are done with. +fn hand_back(back: &[Declared]) { + if crate::shadow::wide_back() { + // Every range first (the pieces that differ, found on several + // threads), then the merges, in order, as below. + let mut work: Vec<(std::sync::Arc, usize, usize)> = Vec::new(); + for (shadow, declared) in back { + if shadow.carded() { + continue; + } + let mut sorted = declared.clone(); + sorted.sort_unstable(); + let mut spans: Vec<(usize, usize)> = Vec::new(); + for (from, to) in sorted { + match spans.last_mut() { + Some(last) if from <= last.1 => last.1 = last.1.max(to), + _ => spans.push((from, to)), + } + } + work.extend(spans.into_iter().map(|(from, to)| (shadow.clone(), from, to))); + } + #[cfg(feature = "diagnostics")] + let scanning = std::time::Instant::now(); + let found = crate::shadow::find_all(&work); + #[cfg(feature = "diagnostics")] + crate::copystat::add(crate::copystat::C::BackScanUs, scanning.elapsed().as_micros() as u64); + for ((shadow, from, to), found) in work.iter().zip(found) { + let written = shadow.copy_back_with(*from, to - from, Some(found)); + copy_back(1, written as u64); + #[cfg(feature = "diagnostics")] + crate::copystat::compared(*from, to - from, written); + } + for (shadow, declared) in back { + shadow.copy_back_done(declared); + } + return; + } + for (shadow, declared) in back { + if shadow.carded() { + // Done before (`Host::card_back`). + shadow.copy_back_done(declared); + continue; + } + // Each byte compared once: the world declares dozens of views + // of its 174 MB heap that overlap almost entirely, and comparing + // every one whole was gigabytes a frame (0.3-0.5 s) for the few + // MB shaders wrote. Only ranges that overlap or touch are + // joined: what lies between two was not given to shaders (the + // snapshot does not hold it). + let mut sorted = declared.clone(); + sorted.sort_unstable(); + let mut spans: Vec<(usize, usize)> = Vec::new(); + for (from, to) in sorted { + match spans.last_mut() { + Some(last) if from <= last.1 => last.1 = last.1.max(to), + _ => spans.push((from, to)), + } + } + for (from, to) in spans { + let written = shadow.copy_back(from, to - from); + copy_back(1, written as u64); + #[cfg(feature = "diagnostics")] + crate::copystat::compared(from, to - from, written); + } + shadow.copy_back_done(declared); + } +} + +impl Host { + /// Whether the host runs mesh shaders at shader model 6.6 (translated + /// mesh shaders need both); logged once. + pub(crate) fn mesh_shaders(&self) -> bool { + static MESH: OnceLock = OnceLock::new(); + *MESH.get_or_init(|| { + let mut options = D3D12_FEATURE_DATA_D3D12_OPTIONS7::default(); + let mut model = D3D12_FEATURE_DATA_SHADER_MODEL { + HighestShaderModel: D3D_SHADER_MODEL_6_6, + }; + // SAFETY: each query writes its own structure of the given size. + let ok = unsafe { + self.device + .CheckFeatureSupport( + D3D12_FEATURE_D3D12_OPTIONS7, + (&raw mut options).cast(), + size_of_val(&options) as u32, + ) + .is_ok() + && self + .device + .CheckFeatureSupport( + D3D12_FEATURE_SHADER_MODEL, + (&raw mut model).cast(), + size_of_val(&model) as u32, + ) + .is_ok() + }; + let mesh = ok + && options.MeshShaderTier != D3D12_MESH_SHADER_TIER_NOT_SUPPORTED + && model.HighestShaderModel.0 >= D3D_SHADER_MODEL_6_6.0; + tracing::info!(mesh, "host mesh shader support"); + mesh + }) + } + + /// Whether the host GPU supports the depth bounds test; logged once. + pub(crate) fn depth_bounds(&self) -> bool { + static BOUNDS: OnceLock = OnceLock::new(); + *BOUNDS.get_or_init(|| { + let mut options = D3D12_FEATURE_DATA_D3D12_OPTIONS2::default(); + // SAFETY: writes `options` of the given size. + let ok = unsafe { + self.device + .CheckFeatureSupport( + D3D12_FEATURE_D3D12_OPTIONS2, + (&raw mut options).cast(), + size_of_val(&options) as u32, + ) + .is_ok() + }; + let supported = ok && options.DepthBoundsTestSupported.as_bool(); + tracing::info!(supported, "host depth bounds support"); + supported + }) + } + + /// A new list, open for recording. + pub(crate) fn new_list(&self) -> windows::core::Result { + #[cfg(feature = "diagnostics")] + let started = std::time::Instant::now(); + #[cfg(feature = "diagnostics")] + let before = private_bytes(); + let list = self.make_list(); + LISTS[0].fetch_add(1, Ordering::Relaxed); + // (May shrink while a list is made, on another thread's account: + // added as it is, the sum is what counts.) + #[cfg(feature = "diagnostics")] + LISTS[2].fetch_add(private_bytes().wrapping_sub(before), Ordering::Relaxed); + #[cfg(feature = "diagnostics")] + { + use crate::copystat::{C, add}; + add(C::HostLists, 1); + add(C::HostListNs, started.elapsed().as_nanos() as u64); + } + list + } + + /// An allocator and a closed list for a prelude. + fn make_prelude(&self) -> Option { + // SAFETY: plain object creation. + let made: windows::core::Result = unsafe { + (|| { + let allocator: ID3D12CommandAllocator = + self.device.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT)?; + let list: ID3D12GraphicsCommandList = + self.device + .CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &allocator, None)?; + list.Close()?; + Ok((allocator, list)) + })() + }; + LISTS[1].fetch_add(1, Ordering::Relaxed); + match made { + Ok(prelude) => Some(prelude), + Err(e) => { + tracing::warn!(error = %e, "no host list for a prelude"); + None + } + } + } + + fn make_list(&self) -> windows::core::Result { + // SAFETY: plain object creation. + unsafe { + let allocator: ID3D12CommandAllocator = self + .device + .CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT)?; + let list: ID3D12GraphicsCommandList = self.device.CreateCommandList( + 0, + D3D12_COMMAND_LIST_TYPE_DIRECT, + &allocator, + None, + )?; + let prelude = OnceLock::new(); + if !lazy_prelude() { + let _ = prelude.set(self.make_prelude()); + } + Ok(HostList { + allocator, + list, + deferred: Mutex::default(), + scratch: Mutex::default(), + states: Mutex::default(), + twins: Mutex::default(), + prelude, + pipelines: Mutex::default(), + budget: OnceLock::new(), + card_budget: OnceLock::new(), + indirect_args: Mutex::default(), + window_check: OnceLock::new(), + _alive: Counted::new(), + meter: AtomicU32::new(u32::MAX), + pipeline_meter: AtomicU32::new(u32::MAX), + gather: Mutex::default(), + #[cfg(feature = "diagnostics")] + notes: Mutex::default(), + #[cfg(feature = "diagnostics")] + stamps: OnceLock::new(), + }) + } + } + + /// The card's clock ([`CARD_CLOCK_US`]), made at the first send. + fn card_clock(&self) -> Option<&'static CardClock> { + static CLOCK: OnceLock> = OnceLock::new(); + static WATCH: std::sync::Once = std::sync::Once::new(); + let clock = CLOCK + .get_or_init(|| { + // SAFETY: a plain fence on our device. + let fence = unsafe { self.device.CreateFence::(0, D3D12_FENCE_FLAG_NONE) }.ok()?; + Some(CardClock { + fence, + state: Mutex::new((0, None)), + sent: std::sync::Condvar::new(), + }) + }) + .as_ref()?; + WATCH.call_once(|| { + if let Err(e) = std::thread::Builder::new().name("leonida-card-clock".into()).spawn(move || card_clock_watch(clock)) { + tracing::warn!(error = %e, "no thread for the card's clock: the frame line's idle times stay 0"); + } + }); + Some(clock) + } + + /// Lists of ours just went to the queue: the clock's signal goes + /// behind them, and an idle stretch of the card, if one was under way, + /// ends here ([`CARD_CLOCK_US`]). + fn card_sent(&self) { + let Some(clock) = self.card_clock() else { + return; + }; + let mut state = clock.state.lock().unwrap_or_else(|e| e.into_inner()); + state.0 += 1; + // SAFETY: our queue and the clock's fence. + let _ = unsafe { self.queue.Signal(&clock.fence, state.0) }; + if let Some((since, worked_then)) = state.1.take() { + card_clock_us(0, since.elapsed().as_micros() as u64); + card_clock_us(1, worked().saturating_sub(worked_then)); + } + drop(state); + clock.sent.notify_one(); + } + + /// Whether the host has what copies in the card's memory need (three + /// lists and the compare); made at the first ask. A copy goes to the + /// card's memory only if it has. + pub(crate) fn card_ready(&self) -> bool { + static READY: OnceLock = OnceLock::new(); + *READY.get_or_init(|| match self.make_card_work() { + Ok(work) => { + *CARD_WORK.lock().unwrap_or_else(|e| e.into_inner()) = Some(work); + true + } + Err(e) => { + tracing::warn!(error = %e, "no host copies in the card's memory: the compare could not be made"); + false + } + }) + } + + fn make_card_work(&self) -> windows::core::Result { + use windows::Win32::Graphics::Direct3D::Fxc::D3DCompile; + use windows::Win32::Graphics::Direct3D::ID3DBlob; + let mut code: Option = None; + // SAFETY: the source and names live through the call; the out + // pointer is ours. + unsafe { + D3DCompile( + CARD_COMPARE.as_ptr().cast(), + CARD_COMPARE.len(), + windows::core::s!("card compare"), + None, + None, + windows::core::s!("main"), + windows::core::s!("cs_5_1"), + 0, + 0, + &mut code, + None, + )?; + } + let code = code.ok_or_else(windows::core::Error::empty)?; + let list = || self.make_prelude().ok_or_else(windows::core::Error::empty); + // A megabyte of results: 262,144 pieces, 16 GB of declared ranges + // in one submission. + const RESULTS: u64 = 1 << 20; + let (differs, data) = self.shared_buffer(RESULTS).ok_or_else(windows::core::Error::empty)?; + name(&differs, || "card compare results".into()); + // SAFETY: the blob's own bytes; the root signature is inside the + // shader. + unsafe { + let bytes = std::slice::from_raw_parts(code.GetBufferPointer().cast::(), code.GetBufferSize()); + let root: ID3D12RootSignature = self.device.CreateRootSignature(0, bytes)?; + let pso: ID3D12PipelineState = self.device.CreateComputePipelineState(&D3D12_COMPUTE_PIPELINE_STATE_DESC { + pRootSignature: std::mem::transmute_copy(&root), + CS: D3D12_SHADER_BYTECODE { + pShaderBytecode: bytes.as_ptr().cast(), + BytecodeLength: bytes.len(), + }, + ..Default::default() + })?; + Ok(CardWork { + sync: vec![list()?], + check: vec![list()?], + fetch: list()?, + root, + pso, + differs: (differs, data as usize, RESULTS), + fetched: None, + taken: 0, + out: 0, + inflight: if inflight_fetch() { self.make_card_inflight(RESULTS) } else { None }, + }) + } + } + + /// [`CardInflight`] for `results` bytes of the compare's results; `None` + /// (and the old fetch) if the shader or the memory cannot be had. + fn make_card_inflight(&self, results: u64) -> Option { + use windows::Win32::Graphics::Direct3D::Fxc::D3DCompile; + use windows::Win32::Graphics::Direct3D::ID3DBlob; + let made = (|| -> windows::core::Result { + let mut code: Option = None; + // SAFETY: the source and names live through the call; the out + // pointer is ours. + unsafe { + D3DCompile( + CARD_FETCH.as_ptr().cast(), + CARD_FETCH.len(), + windows::core::s!("card fetch in flight"), + None, + None, + windows::core::s!("main"), + windows::core::s!("cs_5_1"), + 0, + 0, + &mut code, + None, + )?; + } + let code = code.ok_or_else(windows::core::Error::empty)?; + let slots = inflight_slots(inflight_fetch_bytes()); + let (table, table_data) = self.shared_buffer(4 + results).ok_or_else(windows::core::Error::empty)?; + name(&table, || "card fetch in flight: tickets".into()); + let fetched_bytes = u64::from(slots) * INFLIGHT_SLOT; + let (fetched, fetched_data) = self.shared_buffer(fetched_bytes).ok_or_else(windows::core::Error::empty)?; + name(&fetched, || "card fetch in flight: pieces".into()); + // SAFETY: the mapping holds the counter; nothing of ours ran + // on the card with it yet. + unsafe { table_data.cast::().write_volatile(0) }; + // SAFETY: the blob's own bytes; the root signature is inside + // the shader. + unsafe { + let bytes = std::slice::from_raw_parts(code.GetBufferPointer().cast::(), code.GetBufferSize()); + let root: ID3D12RootSignature = self.device.CreateRootSignature(0, bytes)?; + let pso: ID3D12PipelineState = self.device.CreateComputePipelineState(&D3D12_COMPUTE_PIPELINE_STATE_DESC { + pRootSignature: std::mem::transmute_copy(&root), + CS: D3D12_SHADER_BYTECODE { + pShaderBytecode: bytes.as_ptr().cast(), + BytecodeLength: bytes.len(), + }, + ..Default::default() + })?; + Ok(CardInflight { + root, + pso, + table: (table, table_data as usize, 4 + results), + fetched: (fetched, fetched_data as usize, slots), + landed: 0, + brought: Vec::new(), + }) + } + })(); + match made { + Ok(inflight) => { + tracing::info!( + slots = inflight.fetched.2, + "card copies' flagged pieces come down inside their flights (LEONIDA_CARD_FETCH_INFLIGHT=1)" + ); + Some(inflight) + } + Err(e) => { + tracing::warn!(error = %e, "no fetch inside flights (LEONIDA_CARD_FETCH_INFLIGHT=1): pieces are fetched the old way"); + None + } + } + } + + /// Before a submission's lists run, for copies in the card's memory + /// ([`crate::shadow::cards`]): what changed on their CPU side since + /// the last submission goes to their card side (a list of ours, run + /// now; the submission's lists follow it on the queue), and the ranges + /// this submission's shaders may write get a compare to run after its + /// lists. `None` if there is nothing to do. + /// + /// `flown`: the submission is sent ahead with [`relay`]. Its compare + /// then stores the hashes it makes (see [`flagged_pieces`] and + /// `relay`). + /// + /// `sent`: the last value signalled on the host's fence; the caller + /// signals the next one behind this submission's lists. + /// + /// With `LEONIDA_QUEUE2` bit 2 (`crate::queue2`; off by default) the + /// changed bytes cross from the PC's memory to the card's on a copy + /// queue, on the card's copy engine, while the direct queue still runs + /// what was sent before: they go into a landing buffer in the card's + /// memory that nothing else uses. The direct queue is told to wait for + /// that copy and then moves the bytes from the landing buffer into the + /// copies, inside the card's memory, in the same place of its order as + /// before. So the copies change exactly when they did on one queue; what + /// leaves the direct queue is the crossing from the PC's memory. + fn card_before(&self, runs: &[&HostList], flown: bool, sent: u64) -> Option { + use std::sync::Arc; + if !crate::shadow::cards() { + return None; + } + // The ranges this submission's shaders may write, per copy. + let mut declared: Vec<(Arc, Vec<(usize, usize)>)> = Vec::new(); + for list in runs { + for step in &list.deferred().copies { + if let Step::GpuWrite(shadow, address, len) = step + && shadow.carded() + { + let range = (*address, *address + *len); + match declared.iter_mut().find(|(s, _)| Arc::ptr_eq(s, shadow)) { + Some((_, ranges)) => { + if !ranges.contains(&range) { + ranges.push(range); + } + } + None => declared.push((shadow.clone(), vec![range])), + } + } + } + } + // With the relay: the order of the queue is held from here until + // what is taken is on the queue, and the taking is numbered. + let mut order = relay().then(|| QUEUE_ORDER.lock().unwrap_or_else(|e| e.into_inner())); + let sent_as = match order.as_mut() { + Some(order) => { + **order += 1; + **order + } + None => 0, + }; + let mut dirty = crate::shadow::card_dirty(sent_as); + // With fetches on a copy queue (`crate::queue2`, bit 1 of + // `LEONIDA_QUEUE2`): the send's number is signalled on the direct + // queue behind the send, so that a fetch knows which sends the card + // has finished (`Second::order_done`). + let numbered = || { + if sent_as != 0 + && let Some(second) = crate::queue2::second().filter(|s| s.fetches()) + { + second.sent_up(&self.queue, sent_as); + } + }; + if declared.is_empty() && dirty.is_empty() { + numbered(); + return None; + } + let mut work = CARD_WORK.lock().unwrap_or_else(|e| e.into_inner()); + let work = work.as_mut()?; + // A copy whose shader writes are declared for the first time gets + // its bytes from before, whole. + let mut whole: Vec> = Vec::new(); + for (shadow, _) in &declared { + if shadow.card_make_before(|size| { + let before = self.uav_buffer(crate::shadow::card_hash_bytes(size))?; + name(&before, || "title buffer on the card, hashes of its pieces".into()); + Some(before) + }) { + whole.push(shadow.clone()); + if !dirty.iter().any(|(s, _)| Arc::ptr_eq(s, shadow)) { + dirty.push((shadow.clone(), Vec::new())); + } + } + } + let mut used: Vec<(bool, Prelude)> = Vec::new(); + // The changed bytes through the copy queue (`LEONIDA_QUEUE2` bit + // 2): the landing buffer they are in, in the order of `dirty`'s + // ranges, once the direct queue has waited. `None`: straight from + // the PC's memory on the direct queue, as before. + let mut landed: Option = None; + if let Some(second) = crate::queue2::second().filter(|s| s.uploads()) { + let bytes: u64 = dirty + .iter() + .filter(|(shadow, _)| shadow.carded()) + .flat_map(|(_, ranges)| ranges.iter().map(|&(a, b)| (b - a) as u64)) + .sum(); + // SAFETY: a plain query. + let completed = unsafe { self.fence.GetCompletedValue() }; + // Held until the card has passed this submission's signal: the + // direct queue's copy out of it runs ahead of that. + if bytes > 0 + && let Some(landing) = second.landing(bytes, completed, sent + 1) + { + // SAFETY: an open copy list of the lane's; live buffers, + // and the ranges lie in them; the host's queue. + let sent_up = unsafe { + (|| -> windows::core::Result<()> { + let copy = second.up.list()?; + let mut at = 0u64; + for (shadow, ranges) in &dirty { + let Some((staging, _, _)) = shadow.card_sides() else { + continue; + }; + for &(a, b) in ranges { + copy.1.CopyBufferRegion(&landing, at, staging, a as u64, (b - a) as u64); + at += (b - a) as u64; + } + } + let job = second.up.send(copy, &[], bytes)?; + // Nothing sent to the direct queue from here on + // runs before the bytes have landed. + second.hold(&self.queue, job) + })() + }; + if let Err(e) = sent_up { + fail(format_args!( + "host copies in the card's memory could not be brought up to date through the copy queue ({e}, LEONIDA_QUEUE2)" + )); + } + landed = Some(landing); + } + } + if !dirty.is_empty() { + let Some(sync) = work.sync.pop().or_else(|| self.make_prelude()) else { + fail(format_args!("no host list to bring host copies in the card's memory up to date")); + }; + let (allocator, list) = &sync; + // SAFETY: the list's last run finished (it ran ahead of a + // submission that was waited for, and came back after that); + // live buffers, and the ranges lie in them. + let recorded = unsafe { + (|| -> windows::core::Result<()> { + allocator.Reset()?; + list.Reset(allocator, None)?; + let timed = crate::cardmeter::begin(list, crate::cardmeter::Kind::Sync); + // Where the next range lies in the landing buffer. + let mut at = 0u64; + for (shadow, ranges) in &dirty { + let Some((staging, before, size)) = shadow.card_sides() else { + continue; + }; + for &(a, b) in ranges { + match &landed { + Some(landing) => list.CopyBufferRegion(&shadow.buffer, a as u64, landing, at, (b - a) as u64), + None => list.CopyBufferRegion(&shadow.buffer, a as u64, staging, a as u64, (b - a) as u64), + } + at += (b - a) as u64; + crate::shadow::CARD_STATS[0].fetch_add((b - a) as u64, Ordering::Relaxed); + } + crate::shadow::CARD_STATS[1].fetch_add(ranges.len() as u64, Ordering::Relaxed); + let Some(before) = before else { + continue; + }; + // No twin (it cost the card the copy's size again, + // 399 MB in run 75): `before` holds a 128-bit hash + // of each 64 KiB piece. The pieces just sent up are + // hashed again, all of them the first time; the + // compare after the lists hashes the declared + // pieces and flags those whose hash is another. + if !ranges.is_empty() { + list.ResourceBarrier(&[transition( + &shadow.buffer, + D3D12_RESOURCE_STATE_COPY_DEST, + D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE, + )]); + } + list.SetComputeRootSignature(&work.root); + list.SetPipelineState(&work.pso); + list.SetComputeRootShaderResourceView(1, shadow.buffer.GetGPUVirtualAddress()); + list.SetComputeRootUnorderedAccessView(2, before.GetGPUVirtualAddress()); + list.SetComputeRootUnorderedAccessView(3, work.differs.0.GetGPUVirtualAddress()); + let runs: Vec = if whole.iter().any(|s| Arc::ptr_eq(s, shadow)) { + vec![shadow.card_run(0, usize::MAX)] + } else { + ranges.iter().map(|&(a, b)| shadow.card_run(a, b)).collect() + }; + // The same pieces in fewer passes (`rehash_runs`). + let runs = if rehash_runs() { crate::shadow::joined_piece_runs(runs) } else { runs }; + CARD_PASSES[0].fetch_add(runs.len() as u64, Ordering::Relaxed); + CARD_PASSES[1].fetch_add(runs.iter().map(|r| u64::from(r.pieces)).sum::(), Ordering::Relaxed); + for run in runs { + let constants = [run.first, run.skew, size as u32, run.pieces, 0, 0]; + list.SetComputeRoot32BitConstants(0, 6, constants.as_ptr().cast(), 0); + list.Dispatch(run.pieces.div_ceil(64), 1, 1); + } + } + crate::cardmeter::end(list, timed); + list.Close()?; + self.queue.ExecuteCommandLists(&[Some(list.cast()?)]); + Ok(()) + })() + }; + if let Err(e) = recorded { + fail(format_args!("host copies in the card's memory could not be brought up to date ({e})")); + } + used.push((false, sync)); + } + numbered(); + drop(order); + let mut plan = CardPlan { + ranges: Vec::new(), + check: None, + _synced: dirty.into_iter().map(|(shadow, _)| shadow).collect(), + lists: used, + sent_as, + inflight: false, + inflight_landed: 0, + }; + // Each byte once, as the copy-back joins the declared ranges. The + // results go behind those of plans still in the air. + let mut at = work.taken; + for (shadow, ranges) in &declared { + let mut sorted = ranges.clone(); + sorted.sort_unstable(); + let mut spans: Vec<(usize, usize)> = Vec::new(); + for (from, to) in sorted { + match spans.last_mut() { + Some(last) if from <= last.1 => last.1 = last.1.max(to), + _ => spans.push((from, to)), + } + } + let twin = shadow.card_sides().is_some_and(|(_, before, _)| before.is_some()); + for (from, to) in spans { + let Some(span) = shadow.card_span(from, to) else { + continue; + }; + let compared = twin && u64::from(at + span.pieces) * 4 <= work.differs.2; + plan.ranges.push(CardRange { + shadow: shadow.clone(), + declared: (from, to), + span, + at, + compared, + }); + if compared { + at += span.pieces; + } + } + } + work.taken = at; + if plan.ranges.iter().any(|r| r.compared) { + let Some(check) = work.check.pop().or_else(|| self.make_prelude()) else { + fail(format_args!("no host list for the compare of host copies in the card's memory")); + }; + let (allocator, list) = ✓ + // SAFETY: the list's last run finished (its submission was + // waited for, and it came back after that); live buffers; the + // compare's own root signature. + let recorded = unsafe { + (|| -> windows::core::Result { + allocator.Reset()?; + list.Reset(allocator, None)?; + let timed = crate::cardmeter::begin(list, crate::cardmeter::Kind::Check); + // What the submission's shaders wrote, first. + list.ResourceBarrier(&[D3D12_RESOURCE_BARRIER { + Type: D3D12_RESOURCE_BARRIER_TYPE_UAV, + Flags: D3D12_RESOURCE_BARRIER_FLAG_NONE, + Anonymous: D3D12_RESOURCE_BARRIER_0 { + UAV: std::mem::ManuallyDrop::new(D3D12_RESOURCE_UAV_BARRIER { + pResource: std::mem::ManuallyDrop::new(None), + }), + }, + }]); + list.SetComputeRootSignature(&work.root); + list.SetPipelineState(&work.pso); + list.SetComputeRootUnorderedAccessView(3, work.differs.0.GetGPUVirtualAddress()); + for r in plan.ranges.iter().filter(|r| r.compared) { + let Some((_, Some(before), size)) = r.shadow.card_sides() else { + continue; + }; + let constants = [r.span.first, r.span.skew, size as u32, r.span.pieces, r.at * 4, if flown { 2 } else { 1 }]; + list.SetComputeRoot32BitConstants(0, 6, constants.as_ptr().cast(), 0); + list.SetComputeRootShaderResourceView(1, r.shadow.buffer.GetGPUVirtualAddress()); + list.SetComputeRootUnorderedAccessView(2, before.GetGPUVirtualAddress()); + list.Dispatch(r.span.pieces.div_ceil(64), 1, 1); + CARD_PASSES[2].fetch_add(1, Ordering::Relaxed); + } + // The fetch inside the flight (`inflight_fetch`): behind + // every compare of the list, the pieces they flagged go + // to slots in the PC's memory. + if flown && let Some(inflight) = &work.inflight { + list.ResourceBarrier(&[D3D12_RESOURCE_BARRIER { + Type: D3D12_RESOURCE_BARRIER_TYPE_UAV, + Flags: D3D12_RESOURCE_BARRIER_FLAG_NONE, + Anonymous: D3D12_RESOURCE_BARRIER_0 { + UAV: std::mem::ManuallyDrop::new(D3D12_RESOURCE_UAV_BARRIER { + pResource: std::mem::ManuallyDrop::new(None), + }), + }, + }]); + list.SetComputeRootSignature(&inflight.root); + list.SetPipelineState(&inflight.pso); + list.SetComputeRootUnorderedAccessView(2, work.differs.0.GetGPUVirtualAddress()); + list.SetComputeRootUnorderedAccessView(3, inflight.table.0.GetGPUVirtualAddress()); + list.SetComputeRootUnorderedAccessView(4, inflight.fetched.0.GetGPUVirtualAddress()); + let mut every = true; + for r in plan.ranges.iter().filter(|r| r.compared) { + let Some((_, Some(_), size)) = r.shadow.card_sides() else { + every = false; + continue; + }; + let groups = r.span.pieces.clamp(1, 65535); + let constants = + [r.span.first, r.span.skew, size as u32, r.span.pieces, r.at * 4, inflight.landed, inflight.fetched.2, groups]; + list.SetComputeRoot32BitConstants(0, 8, constants.as_ptr().cast(), 0); + list.SetComputeRootShaderResourceView(1, r.shadow.buffer.GetGPUVirtualAddress()); + list.Dispatch(groups, 1, 1); + } + plan.inflight = every; + plan.inflight_landed = inflight.landed; + } + crate::cardmeter::end(list, timed); + list.Close()?; + list.cast() + })() + }; + match recorded { + Ok(list) => plan.check = Some(list), + Err(e) => fail(format_args!("the compare of host copies in the card's memory could not be recorded ({e})")), + } + plan.lists.push((true, check)); + } + work.out += 1; + Some(plan) + } + + /// With [`relay`]: whether the compare's result area is half taken by + /// plans in the air. It starts from the beginning only when no plan is + /// out, so the caller lets the flights land first. + fn card_results_low(&self) -> bool { + CARD_WORK + .lock() + .unwrap_or_else(|e| e.into_inner()) + .as_ref() + .is_some_and(|work| u64::from(work.taken) * 8 > work.differs.2) + } + + /// The plan's submission has run and its results were read + /// ([`Host::card_back`]): its lists are free for the next plan. Called + /// when nothing of ours is on the card, so the compare's results start + /// from the beginning again. + fn card_done(&self, plan: CardPlan) { + let mut work = CARD_WORK.lock().unwrap_or_else(|e| e.into_inner()); + let Some(work) = work.as_mut() else { + return; + }; + for (check, list) in plan.lists { + if check { work.check.push(list) } else { work.sync.push(list) } + } + work.out = work.out.saturating_sub(1); + // With the relay other plans may be on the card, their results + // not read yet: the area starts again only when none is out. + if !relay() || work.out == 0 { + work.taken = 0; + } + } + + /// The relay's own list, fence, event for [`Host::relay_card_back`]. + fn make_relay_fetch(&self) -> Option { + let list = self.make_prelude()?; + // SAFETY: plain objects of our own. + unsafe { + let fence: ID3D12Fence = self.device.CreateFence(0, D3D12_FENCE_FLAG_NONE).ok()?; + let event = CreateEventW(None, false, false, None).ok()?; + Some(RelayFetch { + list, + fence, + event, + sent: 0, + buffer: None, + }) + } + } + + /// [`relay`], on the thread that lands flights: for the plans of the + /// flights being landed (the card has run them), the pieces their + /// compares flagged are fetched, once each, with a list and a wait of + /// this thread's own, and what shaders wrote in them goes into title + /// memory (`Shadow::card_merge_relay`). As [`Host::card_back`], but: + /// no submission lock; a piece flagged under one range of a plan is + /// fetched under all ([`flagged_pieces`]); the fetch runs behind + /// whatever was sent meanwhile, so it may bring a later flight's + /// bytes, which that flight's landing then finds merged already; and + /// nothing is sent back up. + /// + /// With [`inflight_fetch`] the pieces are first looked for where the + /// flights' own compare lists put them ([`Host::relay_card_inflight`]); + /// only a landing that cannot take them from there fetches, as here. + /// `behind`: the value signalled on the host's fence behind the last of + /// the flights. With `LEONIDA_QUEUE2` bit 1 (`crate::queue2`) the fetch + /// goes to a copy queue, behind that value and nothing else: it does + /// not stand behind what the submitting thread sent meanwhile (run + /// 118: 114-157 ms a frame of this thread's time). It then reads the + /// card's side while later flights may be writing it: a byte is the + /// old one or the new one, and the flight that writes it has a compare + /// and a landing of its own behind it. + /// + /// `plans` come with their flights' numbers and `landed` is the number + /// of the last flight being landed: a piece an earlier fetch on the + /// copy queue brought down beside one of these flights is fetched + /// whatever the compare says ([`BESIDE`]). + fn relay_card_back(&self, plans: &[(u64, &CardPlan)], fetch: &mut Option, behind: u64, landed: u64) { + if inflight_fetch() { + let only: Vec<&CardPlan> = plans.iter().map(|p| p.1).collect(); + let taken = self.relay_card_inflight(&only); + inflight_tickets_landed(&only); + if taken { + return; + } + } + let lane = crate::queue2::second().filter(|s| s.fetches()); + // The pieces fetched beside flights that had started, as noted by + // earlier landings: looked at for these plans, renewed below. + let beside = lane.is_some() && refetch(); + let noted: std::collections::HashMap<(usize, u32), u64> = if beside { + BESIDE.lock().unwrap_or_else(|e| e.into_inner()).clone().unwrap_or_default() + } else { + Default::default() + }; + let mut again = 0u64; + // Every piece fetched now: (copy, piece number). + let mut numbers: Vec<(usize, u32)> = Vec::new(); + let differs = { + let work = CARD_WORK.lock().unwrap_or_else(|e| e.into_inner()); + work.as_ref().map(|work| (work.differs.1, (work.differs.2 / 4) as usize)) + }; + let mut pieces: Vec<(std::sync::Arc, usize, usize, u64)> = Vec::new(); + let mut total = 0u64; + if let Some((differs, dwords)) = differs { + // SAFETY: the mapping of the results. The compares of these + // plans have run, and their dwords are given to no other plan + // before these are done with (`card_done`). + let differs = unsafe { std::slice::from_raw_parts(differs as *const u32, dwords) }; + let mut seen = std::collections::HashSet::new(); + for &(number, plan) in plans { + let mut flags: Vec<(usize, u32, bool)> = plan + .ranges + .iter() + .flat_map(|r| { + (0..r.span.pieces).map(move |p| { + let flagged = !r.compared || differs.get((r.at + p) as usize).is_none_or(|&d| d != 0); + (std::sync::Arc::as_ptr(&r.shadow) as usize, r.span.first + p, flagged) + }) + }) + .collect(); + // A piece an earlier fetch brought down while this flight + // may have been writing it: fetched, flagged or not. + for flag in flags.iter_mut().filter(|f| !f.2) { + if fetched_beside(noted.get(&(flag.0, flag.1)).copied(), number) { + flag.2 = true; + again += 1; + } + } + let fetched = flagged_pieces(&flags); + numbers.extend(fetched.iter().copied()); + for r in &plan.ranges { + let copy = std::sync::Arc::as_ptr(&r.shadow) as usize; + for p in 0..r.span.pieces { + if !fetched.contains(&(copy, r.span.first + p)) { + continue; + } + let (lo, hi) = r.shadow.card_piece(&r.span, p); + if lo < hi && seen.insert((copy, lo, hi)) { + pieces.push((r.shadow.clone(), lo, hi, total)); + total += (hi - lo) as u64; + } + } + crate::shadow::CARD_STATS[2].fetch_add(u64::from(r.span.pieces), Ordering::Relaxed); + } + } + } + BESIDE_STATS[0].fetch_add(again, Ordering::Relaxed); + if pieces.is_empty() { + if inflight_fetch() { + // The next merge may be of a flight in the air now, with + // bytes from when it ran: only sends up to these plans' are + // older than it. + if let Some(last) = plans.iter().map(|p| p.1.sent_as).max() { + crate::shadow::relay_fetched(last); + } + return; + } + if beside { + // Notes whose flights have all landed are done with. + let mut all = BESIDE.lock().unwrap_or_else(|e| e.into_inner()); + note_beside(all.get_or_insert_with(Default::default), &[], landed, landed); + } + // Nothing to fetch: every send so far is older than the next + // fetch (on a copy queue: every send the card has finished). + crate::shadow::relay_fetched(match lane { + Some(second) => second.order_done(), + None => *QUEUE_ORDER.lock().unwrap_or_else(|e| e.into_inner()), + }); + return; + } + if inflight_fetch() { + INFLIGHT_STATS[3].fetch_add(1, Ordering::Relaxed); + } + if fetch.is_none() { + *fetch = self.make_relay_fetch(); + } + let Some(f) = fetch.as_mut() else { + fail(format_args!("no list, fence or event to fetch what shaders wrote to the card's memory (LEONIDA_RELAY=1)")); + }; + if f.buffer.as_ref().is_none_or(|b| b.2 < total) { + let size = total.next_multiple_of(16 << 20); + f.buffer = self.shared_buffer(size).map(|(buffer, data)| (buffer, data as usize, size)); + } + let Some((buffer, data, _)) = f.buffer.clone() else { + fail(format_args!("no memory to fetch what shaders wrote to the card's memory ({total} bytes, LEONIDA_RELAY=1)")); + }; + f.sent += 1; + let ((allocator, list), fence, event, sent) = (f.list.clone(), f.fence.clone(), f.event, f.sent); + let waiting = std::time::Instant::now(); + // SAFETY: the list's last run was waited for by this thread; live + // buffers (the copies are held by the plans); the fence and the + // event are this thread's. + let ran = unsafe { + (|| -> windows::core::Result { + if let Some(second) = lane { + // The sends of title bytes the card has finished are in + // what comes down. A later one may be too, if the card + // runs it before this fetch: the merge leaves its bytes + // out as a send that came after, and they are the + // title's either way. + let after = second.order_done(); + let copy = second.down.list()?; + for (shadow, lo, hi, at) in &pieces { + copy.1.CopyBufferRegion(&buffer, *at, &shadow.buffer, *lo as u64, (*hi - *lo) as u64); + } + let job = second.down.send(copy, &[(&self.fence, behind)], total)?; + second.down.wait(job, event)?; + if beside { + // Whatever had started by now may have been + // writing these pieces while they came down + // (counted before a submission's lists go to the + // queue, `Host::submit`: nothing later ran yet). + let started = STARTED.load(Ordering::Acquire); + let mut all = BESIDE.lock().unwrap_or_else(|e| e.into_inner()); + let noted = note_beside(all.get_or_insert_with(Default::default), &numbers, landed, started); + BESIDE_STATS[1].fetch_add(noted, Ordering::Relaxed); + } + second.down.stats.waited_us.fetch_add(waiting.elapsed().as_micros() as u64, Ordering::Relaxed); + return Ok(after); + } + allocator.Reset()?; + list.Reset(&allocator, None)?; + for (shadow, lo, hi, at) in &pieces { + list.CopyBufferRegion(&buffer, *at, &shadow.buffer, *lo as u64, (*hi - *lo) as u64); + } + list.Close()?; + let lists = [Some(list.cast::()?)]; + // In the order of the queue: the sends of title bytes so + // far are ahead of this fetch, every later one behind it. + let order = QUEUE_ORDER.lock().unwrap_or_else(|e| e.into_inner()); + self.queue.ExecuteCommandLists(&lists); + let after = *order; + drop(order); + self.card_sent(); + self.queue.Signal(&fence, sent)?; + fence.SetEventOnCompletion(sent, event)?; + WaitForSingleObject(event, INFINITE); + Ok(after) + })() + }; + let after = match ran { + Ok(after) => after, + Err(e) => fail(format_args!("what shaders wrote to the card's memory could not be fetched ({e}, LEONIDA_RELAY=1)")), + }; + // This fetch may bring bytes of flights in the air now: their own + // slots are older than what it puts in the CPU's side there + // (`relay_card_inflight`). Sends up to `after` are numbered, and the + // submission numbered `after` may not have its lists on the queue + // yet; every one before it has (the submission lock). + if inflight_fetch() + && after > 1 + && let Some(inflight) = CARD_WORK.lock().unwrap_or_else(|e| e.into_inner()).as_mut().and_then(|w| w.inflight.as_mut()) + { + inflight.brought.extend(pieces.iter().map(|(shadow, lo, hi, _)| (shadow.clone(), *lo, *hi, after - 1))); + } + let us = waiting.elapsed().as_micros() as u64; + RELAY_STATS[3].fetch_add(us, Ordering::Relaxed); + { + use crate::shadow::CARD_STATS; + CARD_STATS[3].fetch_add(pieces.len() as u64, Ordering::Relaxed); + CARD_STATS[4].fetch_add(total, Ordering::Relaxed); + CARD_STATS[5].fetch_add(1, Ordering::Relaxed); + CARD_STATS[6].fetch_add(us, Ordering::Relaxed); + } + let mut title = Vec::new(); + let mut written = 0; + for (shadow, lo, hi, at) in &pieces { + // SAFETY: the mapping of the fetched bytes, `total` of them; + // the copy into it has run. + let gpu = unsafe { std::slice::from_raw_parts((data + *at as usize) as *const u8, hi - lo) }; + let merged = shadow.card_merge_relay(*lo, gpu, after, &mut title); + shadow.walls_merged(gpu.len(), merged); + written += merged; + } + copy_back(1, written as u64); + // Sends up to `after` are of no use to any later merge; with the + // fetch inside flights only those up to these plans' are + // (`fallback_fetched_mark`). + let landed = plans.iter().map(|p| p.1.sent_as).max(); + crate::shadow::relay_fetched(fallback_fetched_mark(inflight_fetch(), after, landed)); + } + + /// [`Host::relay_card_back`] with [`inflight_fetch`]: the pieces these + /// plans' compares flagged are taken from the slots their own compare + /// lists copied them to ([`CARD_FETCH`]) and merged, plan by plan in the + /// line's order, with no list or wait of ours. `false` (nothing merged) + /// if any plan cannot land so; the caller then lands them all the old + /// way, as without the switch. + /// + /// The merge's "fetched after" (`Shadow::card_merge_relay`) is the + /// plan's own `sent_as`. `QUEUE_ORDER` is raised only in + /// `Host::card_before`, under the submission lock, and that lock is held + /// until the submission's lists and its compare's list are on the queue + /// behind its sync list: so when the compare's list ran, the card had + /// received exactly the sends 1..=`sent_as` of title bytes and no later + /// one, which is what the merge's skip of later sends asks. (The old + /// fetch, by contrast, ran whenever it reached the queue, and took the + /// count at its own ExecuteCommandLists.) + /// + /// When a landing goes the old way instead, all of it does: a fetch the + /// old way brings the card's bytes as they are now, newer than the slots + /// of plans in the air then, and merging an older slot after it would + /// put a flight's bytes back over a later flight's. For the same reason + /// the bytes such a fetch brought (`CardInflight::brought`) are left + /// out of the slots of flights whose lists were on the queue ahead of + /// it: the CPU's side holds what the card held after them there. The + /// rest of their slots is merged, newer than anything merged there + /// before. (Left out whole, a flight sent before such a fetch would have + /// had to land the old way, its fetch taking a later count still: one + /// overflow kept every landing on the old way while flights were in + /// the air.) Plans land in the line's order, each plan's slot as it was + /// right behind its own lists, so every merge here is of bytes at least + /// as new as the CPU's side holds. + /// + /// shortcut: all or nothing per landing, and a plan whose pieces overflow + /// the slots lands the old way for all its pieces, not only the ones + /// left out. + fn relay_card_inflight(&self, plans: &[&CardPlan]) -> bool { + use std::sync::Arc; + type Piece = (Arc, usize, usize, usize, u64); + let mut pieces: Vec = Vec::new(); + { + let work = CARD_WORK.lock().unwrap_or_else(|e| e.into_inner()); + let Some(work) = work.as_ref() else { + return false; + }; + let Some(inflight) = &work.inflight else { + return false; + }; + let dwords = (work.differs.2 / 4) as usize; + // SAFETY: the mappings of the results and the tickets. The + // compares and fetches of these plans have run, and their dwords + // are given to no other plan before these are done with + // (`card_done`). + let (differs, table) = unsafe { + ( + std::slice::from_raw_parts(work.differs.1 as *const u32, dwords), + std::slice::from_raw_parts((inflight.table.1 as *const u32).add(1), dwords), + ) + }; + let slots = inflight.fetched.2; + for plan in plans { + if plan.ranges.is_empty() { + continue; + } + if !plan.inflight || plan.ranges.iter().any(|r| !r.compared) { + return false; + } + // Pieces (copy, number) the compare flagged, with their ticket. + let mut tickets: std::collections::HashMap<(usize, u32), u32> = std::collections::HashMap::new(); + let mut flags: Vec<(usize, u32, bool)> = Vec::new(); + for r in &plan.ranges { + let copy = Arc::as_ptr(&r.shadow) as usize; + for p in 0..r.span.pieces { + let at = (r.at + p) as usize; + let (Some(&flag), Some(&entry)) = (differs.get(at), table.get(at)) else { + return false; + }; + if flag != 0 { + if entry == INFLIGHT_NONE { + return false; + } + if !inflight_gets_slot(entry, plan.inflight_landed, slots) { + INFLIGHT_STATS[2].fetch_add(1, Ordering::Relaxed); + return false; + } + tickets.insert((copy, r.span.first + p), entry); + } + flags.push((copy, r.span.first + p, flag != 0)); + } + } + let fetched = flagged_pieces(&flags); + let mut seen = std::collections::HashSet::new(); + for r in &plan.ranges { + let copy = Arc::as_ptr(&r.shadow) as usize; + for p in 0..r.span.pieces { + let piece = r.span.first + p; + if !fetched.contains(&(copy, piece)) { + continue; + } + let (lo, hi) = r.shadow.card_piece(&r.span, p); + if lo >= hi || !seen.insert((copy, lo, hi)) { + continue; + } + let from = inflight_piece_from(&r.span, p); + let Some(&k) = tickets.get(&(copy, piece)) else { + return false; + }; + if lo < from || (hi - from) as u64 > INFLIGHT_SLOT { + return false; + } + let slot = inflight.fetched.1 + (k % slots) as usize * INFLIGHT_SLOT as usize; + // Bytes a fetch the old way brought after this flight ran. + let newer: Vec<(usize, usize)> = inflight + .brought + .iter() + .filter(|b| b.3 >= plan.sent_as && Arc::ptr_eq(&b.0, &r.shadow) && b.1 < hi && b.2 > lo) + .map(|b| (b.1, b.2)) + .collect(); + for (a, b) in crate::shadow::outside(lo, hi, newer) { + pieces.push((r.shadow.clone(), a, b, slot + (a - from), plan.sent_as)); + } + } + } + } + } + // Outside the lock: no slot of these plans is written over before + // their tickets are landed (`inflight_tickets_landed`, after this). + let mut title = Vec::new(); + let (mut written, mut bytes) = (0, 0u64); + for (shadow, lo, hi, at, after) in &pieces { + // SAFETY: inside the mapping of the slots (checked above); the + // copy into it ran in the plan's flight, which the card has run. + let gpu = unsafe { std::slice::from_raw_parts(*at as *const u8, hi - lo) }; + written += shadow.card_merge_relay(*lo, gpu, *after, &mut title); + bytes += (hi - lo) as u64; + } + for plan in plans { + for r in &plan.ranges { + crate::shadow::CARD_STATS[2].fetch_add(u64::from(r.span.pieces), Ordering::Relaxed); + } + } + copy_back(1, written as u64); + INFLIGHT_STATS[0].fetch_add(pieces.len() as u64, Ordering::Relaxed); + INFLIGHT_STATS[1].fetch_add(bytes, Ordering::Relaxed); + // The next merge is of a later plan, or a fetch the old way sent now. + if let Some(last) = plans.iter().map(|p| p.sent_as).max() { + crate::shadow::relay_fetched(last); + } + true + } + + /// [`relay`], on the thread that lands flights: `items` are the first + /// things of the line, flights the card has run and what follows them. + /// What their shaders wrote goes into title memory (copies in the + /// card's memory first, then the others, each byte once whichever + /// flights declared it); then every flight's ranges are done with; + /// then, in the line's order, each flight's read-backs, its + /// bottom-of-pipe writes and the fence signals behind it. Title memory + /// is complete before the title is told anything. + fn relay_land(&self, items: Vec, fetch: &mut Option) { + let landing = std::time::Instant::now(); + { + let flights: Vec<&Flight> = items + .iter() + .filter_map(|l| match l { + Late::Run(flight) => Some(flight), + _ => None, + }) + .collect(); + if !flights.is_empty() { + // SAFETY: a plain query. + if unsafe { self.device.GetDeviceRemovedReason() }.is_err() { + let runs: Vec<&HostList> = flights.iter().flat_map(|f| f.order.iter().map(|&i| f.lists[i].host())).collect(); + fail(format_args!( + "host GPU device removed after {} submissions sent ahead (LEONIDA_RELAY=1) of {} lists{}{}", + flights.len(), + runs.len(), + self.removal_data(&runs), + last_notes(&runs) + )); + } + fill_ahead::landing(flights.iter().map(|f| f.number).min().unwrap_or(0)); + let plans: Vec<(u64, &CardPlan)> = flights.iter().filter_map(|f| f.card.as_ref().map(|card| (f.number, card))).collect(); + let behind = flights.iter().map(|f| f.fence).max().unwrap_or(0); + let landed = flights.iter().map(|f| f.number).max().unwrap_or(0); + self.relay_card_back(&plans, fetch, behind, landed); + let mut back: Vec = Vec::new(); + for flight in &flights { + for (shadow, ranges) in &flight.back { + match back.iter_mut().find(|(s, _)| std::sync::Arc::ptr_eq(s, shadow)) { + Some((_, all)) => { + for range in ranges { + if !all.contains(range) { + all.push(*range); + } + } + } + None => back.push((shadow.clone(), ranges.clone())), + } + } + } + relay_hand_back(&back); + // Only now, and flight by flight: a range another flight + // in the air declared too stays closed to refreshes. + for flight in &flights { + for (shadow, ranges) in &flight.back { + shadow.copy_back_done(ranges); + } + } + copy_back(0, landing.elapsed().as_micros() as u64); + RELAY_STATS[0].fetch_add(1, Ordering::Relaxed); + RELAY_STATS[1].fetch_add(flights.len() as u64, Ordering::Relaxed); + } + } + // In the order given: what tells the title the card is done. + let mut last = 0; + let mut landed = Vec::new(); + for item in items { + match item { + Late::Run(flight) => { + last = flight.number; + for &i in &flight.order { + read_backs(flight.lists[i].host()); + } + if let Some(card) = flight.card { + self.card_done(card); + } + landed.push((flight.lists, flight.order)); + } + Late::Write(at, what, bytes) => what.write(at as *mut u8, bytes), + Late::Signal(fence, value) => crate::fence::set(fence as crate::object::This, value), + } + } + if last > 0 { + FINISHED.store(last, Ordering::Release); + bury(last); + } + self.log_messages(); + fill_ahead::landing(0); + RELAY_STATS[4].fetch_add(landing.elapsed().as_micros() as u64, Ordering::Relaxed); + { + let mut line = line(); + let Line { + line: items, + written, + lists, + settling, + poke, + landed: kept, + in_hand, + .. + } = &mut *line; + kept.extend(landed); + in_hand.clear(); + // What is still in the air, from the flights that are. + written.clear(); + *lists = 0; + let mut ranges = Vec::new(); + for item in items.iter() { + if let Late::Run(flight) = item { + *lists += flight.order.len().max(1); + ranges.extend(flight.back.iter().flat_map(|(_, r)| r.iter().copied())); + } + } + join_ranges(written, ranges); + *settling = false; + // The landed lists are reset, and what queues hold looked at, + // by the helper thread (they take locks a waiter may hold). + *poke = true; + } + LINE_MOVED.notify_all(); + LINE_LANDED.notify_all(); + } + + /// After a submission ran, for copies in the card's memory: the pieces + /// of the declared ranges that the compare found differing (all of a + /// range it did not compare) are fetched, with one more wait for the + /// card, and what shaders wrote in them goes into title memory. + /// `submitted` is the last value signalled on the fence. `seen` holds + /// the pieces fetched already since the card was last waited for + /// (several submissions settled together name the same ones). + fn card_back( + &self, + plan: &CardPlan, + submitted: &mut u64, + seen: &mut std::collections::HashSet<(usize, usize, usize)>, + ) { + if plan.ranges.is_empty() { + return; + } + let mut work = CARD_WORK.lock().unwrap_or_else(|e| e.into_inner()); + let Some(work) = work.as_mut() else { + return; + }; + // SAFETY: the mapping of the results, which the compare (it has + // run) wrote. + let differs = unsafe { std::slice::from_raw_parts(work.differs.1 as *const u32, (work.differs.2 / 4) as usize) }; + // The pieces to fetch: the range, the offsets in its copy, and + // where the bytes come down. + let mut pieces: Vec<(usize, usize, usize, u64)> = Vec::new(); + let mut total = 0u64; + for (i, r) in plan.ranges.iter().enumerate() { + for p in 0..r.span.pieces { + if r.compared && differs[(r.at + p) as usize] == 0 { + continue; + } + let (lo, hi) = r.shadow.card_piece(&r.span, p); + if lo < hi && seen.insert((std::sync::Arc::as_ptr(&r.shadow) as usize, lo, hi)) { + pieces.push((i, lo, hi, total)); + total += (hi - lo) as u64; + } + } + crate::shadow::CARD_STATS[2].fetch_add(u64::from(r.span.pieces), Ordering::Relaxed); + } + let mut written = vec![0usize; plan.ranges.len()]; + if !pieces.is_empty() { + if work.fetched.as_ref().is_none_or(|f| f.2 < total) { + let size = total.next_multiple_of(16 << 20); + work.fetched = self.shared_buffer(size).map(|(buffer, data)| (buffer, data as usize, size)); + } + let Some((fetched, data, _)) = &work.fetched else { + fail(format_args!("no memory to fetch what shaders wrote to the card's memory ({total} bytes)")); + }; + let waiting = std::time::Instant::now(); + let (allocator, list) = &work.fetch; + // SAFETY: the list's last run was waited for; live buffers; the + // fence and event are ours, under the submission lock. + let ran = unsafe { + (|| -> windows::core::Result<()> { + // With `LEONIDA_QUEUE2` bit 1 the fetch goes to the copy + // queue here too, behind everything sent to the direct + // queue. Nothing is gained (the card has run it all + // when this is reached); the path is the same one the + // relay uses, in the plainest run there is. + if let Some(second) = crate::queue2::second().filter(|s| s.fetches()) { + let copy = second.down.list()?; + for &(i, lo, hi, at) in &pieces { + copy.1.CopyBufferRegion(fetched, at, &plan.ranges[i].shadow.buffer, lo as u64, (hi - lo) as u64); + } + let job = second.down.send(copy, &[(&self.fence, *submitted)], total)?; + let was_working = working(false); + second.down.wait(job, self.event)?; + stood(waiting); + working(was_working); + second.down.stats.waited_us.fetch_add(waiting.elapsed().as_micros() as u64, Ordering::Relaxed); + return Ok(()); + } + allocator.Reset()?; + list.Reset(allocator, None)?; + for &(i, lo, hi, at) in &pieces { + list.CopyBufferRegion(fetched, at, &plan.ranges[i].shadow.buffer, lo as u64, (hi - lo) as u64); + } + list.Close()?; + self.queue.ExecuteCommandLists(&[Some(list.cast()?)]); + self.card_sent(); + *submitted += 1; + self.queue.Signal(&self.fence, *submitted)?; + self.fence.SetEventOnCompletion(*submitted, self.event)?; + let was_working = working(false); + WaitForSingleObject(self.event, INFINITE); + stood(waiting); + working(was_working); + Ok(()) + })() + }; + if let Err(e) = ran { + fail(format_args!("what shaders wrote to the card's memory could not be fetched ({e})")); + } + { + use crate::shadow::CARD_STATS; + CARD_STATS[3].fetch_add(pieces.len() as u64, Ordering::Relaxed); + CARD_STATS[4].fetch_add(total, Ordering::Relaxed); + CARD_STATS[5].fetch_add(1, Ordering::Relaxed); + CARD_STATS[6].fetch_add(waiting.elapsed().as_micros() as u64, Ordering::Relaxed); + } + if wide_merge() && pieces.len() >= 8 { + // The pieces are apart from one another (each its own bytes + // of its copy and of title memory): several at a time. + let fetched = *data; + let counts: std::sync::Arc> = + std::sync::Arc::new((0..plan.ranges.len()).map(|_| std::sync::atomic::AtomicUsize::new(0)).collect()); + let each = pieces.len().div_ceil(8); + let jobs: Vec> = pieces + .chunks(each) + .map(|chunk| { + let chunk: Vec<(std::sync::Arc, usize, usize, usize, u64)> = + chunk.iter().map(|&(i, lo, hi, at)| (plan.ranges[i].shadow.clone(), i, lo, hi, at)).collect(); + let counts = counts.clone(); + Box::new(move || { + let mut title = Vec::new(); + for (shadow, i, lo, hi, at) in chunk { + // SAFETY: the mapping of the fetched bytes; + // the copy into it has run, and the caller + // waits for this job. + let gpu = unsafe { std::slice::from_raw_parts((fetched + at as usize) as *const u8, hi - lo) }; + let merged = shadow.card_merge(lo, gpu, &mut title); + shadow.walls_merged(gpu.len(), merged); + counts[i].fetch_add(merged, Ordering::Relaxed); + } + }) as Box + }) + .collect(); + crate::shadow::wide_run(jobs); + for (written, count) in written.iter_mut().zip(counts.iter()) { + *written += count.load(Ordering::Relaxed); + } + } else { + let mut title = Vec::new(); + for &(i, lo, hi, at) in &pieces { + // SAFETY: the mapping of the fetched bytes, `total` of + // them; the copy into it has run. + let gpu = unsafe { std::slice::from_raw_parts((*data + at as usize) as *const u8, hi - lo) }; + let merged = plan.ranges[i].shadow.card_merge(lo, gpu, &mut title); + plan.ranges[i].shadow.walls_merged(gpu.len(), merged); + written[i] += merged; + } + } + } + for (r, written) in plan.ranges.iter().zip(written) { + copy_back(1, written as u64); + let (from, to) = r.declared; + #[cfg(feature = "diagnostics")] + crate::copystat::compared(from, to - from, written); + let _ = (from, to); + } + } + + /// Runs closed lists and waits for them, and with [`late`] for + /// everything sent to the card before them, which is settled first. + pub(crate) fn execute(&self, runs: &[&HostList]) { + // Behind what the queues were given before it and have not run + // yet (`crate::queue::behind`). + crate::queue::before_sync(); + let _ = self.submit(runs, false); + } + + /// A queue's submission with [`late`]: the host lists `lists`, taken + /// from the title's, go to the card in `order` and are not waited for. + /// They join the line of flights and are settled, with the others in + /// the air, at the next point where what they do can be observed + /// ([`late`] lists those points); their host lists are reset and kept + /// for reuse then, as a queue does for the lists it ran. + pub(crate) fn execute_late(&self, lists: Vec, order: Vec) { + if order.is_empty() { + crate::list::recycle(lists, &order); + return; + } + late_threads(); + let sent = { + let runs: Vec<&HostList> = order.iter().map(|&i| lists[i].host()).collect(); + self.submit(&runs, true) + }; + let Some((mut submitted, sent)) = sent else { + // (Not reached: a submission sent ahead always comes back.) + crate::list::recycle(lists, &order); + return; + }; + let told = !sent.writes.is_empty(); + let most = { + let mut line = line(); + let Line { line: items, written, lists: flying, target, .. } = &mut *line; + join_ranges(written, sent.back.iter().flat_map(|(_, ranges)| ranges.iter().copied())); + *flying += order.len(); + *target = *submitted; + items.push(Late::Run(Flight { + number: sent.number, + fence: *target, + lists, + order, + card: sent.card, + back: sent.back, + })); + items.extend(sent.writes.into_iter().map(|(at, what, bytes)| Late::Write(at, what, bytes))); + *flying >= late_most() + }; + LATE_STATS[0].fetch_add(1, Ordering::Relaxed); + RELAY_MOVED.notify_one(); + if told && !late_writes() { + self.settle(&mut submitted, WHY_WRITES); + } else if most && relay_exact() { + // Until there are fewer, not until there are none. + relay_wait(WHY_MOST, |line| line.lists < late_most()); + } else if most { + self.settle(&mut submitted, WHY_MOST); + } else { + LINE_MOVED.notify_one(); + } + drop(submitted); + land(); + } + + /// Sends `list`, a closed list of ours (the present's copy), as a + /// flight ([`late_free_present`]): not waited for, settled with the + /// others. The caller keeps the list and does not reset it before the + /// submission whose number comes back has finished ([`FINISHED`]); 0 if + /// it ran and was waited for after all. + fn execute_own(&self, list: &HostList) -> u64 { + late_threads(); + let Some((submitted, sent)) = self.submit(&[list], true) else { + return 0; + }; + let number = sent.number; + { + let mut line = line(); + let Line { line: items, written, lists: flying, target, .. } = &mut *line; + join_ranges(written, sent.back.iter().flat_map(|(_, ranges)| ranges.iter().copied())); + *flying += 1; + *target = *submitted; + items.push(Late::Run(Flight { + number, + fence: *target, + lists: Vec::new(), + order: Vec::new(), + card: sent.card, + back: sent.back, + })); + items.extend(sent.writes.into_iter().map(|(at, what, bytes)| Late::Write(at, what, bytes))); + } + LATE_STATS[0].fetch_add(1, Ordering::Relaxed); + LINE_MOVED.notify_one(); + RELAY_MOVED.notify_one(); + drop(submitted); + number + } + + /// Waits for the card to run every flight in the air ([`late`]) and + /// does what they left to do, as [`Host::execute`] does for one + /// submission after its wait: the pieces their shaders wrote in copies + /// in the card's memory are fetched and merged (each once), the ranges + /// they declared in the other copies are compared and copied back + /// (each byte once, whichever flights declared it), and then, in the + /// order they were given: their bottom-of-pipe writes and the fence + /// signals behind them. `submitted` is the submission lock's value; + /// `why` one of the `WHY_` places. Nothing happens if nothing flies. + /// + /// Everything in the air is settled, never the first flights alone: + /// the merge writes the copies' CPU side, which a flight still on the + /// card may be writing too. + fn settle(&self, submitted: &mut u64, why: usize) { + if !late() { + return; + } + if relay() { + // Nothing is settled here: the thread that lands flights does + // it, in order, and this waits until nothing is in the air and + // nothing is being landed. Every point that settled before + // comes here, so each still sees title memory, fences and + // bottom-of-pipe values as after a settle. + relay_wait(why, |line| line.line.is_empty() && !line.settling); + return; + } + let was_working = working(true); + let mut counted = false; + loop { + let items = { + let mut line = line(); + if line.line.is_empty() { + line.settling = false; + break; + } + line.settling = true; + line.written.clear(); + line.lists = 0; + std::mem::take(&mut line.line) + }; + let flights = items.iter().filter(|i| matches!(i, Late::Run(_))).count(); + if !counted { + counted = true; + LATE_STATS[1].fetch_add(1, Ordering::Relaxed); + LATE_STATS[why].fetch_add(1, Ordering::Relaxed); + } + LATE_STATS[11].fetch_add(flights as u64, Ordering::Relaxed); + if flights > 0 { + submitting(2, flights); + let waiting = std::time::Instant::now(); + // SAFETY: the fence and event are ours, under the + // submission lock; `submitted` is the last value signalled. + unsafe { + match self.fence.SetEventOnCompletion(*submitted, self.event) { + Ok(()) => { + working(false); + WaitForSingleObject(self.event, INFINITE); + stood(waiting); + working(true); + } + Err(e) => tracing::warn!(error = %e, "submissions sent ahead not waited for"), + } + } + let gpu = waiting.elapsed(); + LATE_STATS[12].fetch_add(gpu.as_micros() as u64, Ordering::Relaxed); + LATE_WAITED[why.min(10)].fetch_add(gpu.as_micros() as u64, Ordering::Relaxed); + submission_us(1, gpu.as_micros() as u64); + #[cfg(feature = "diagnostics")] + crate::copystat::card_waited(gpu.as_micros() as u64, || { + format!("{flights} submissions sent ahead, settled together") + }); + // SAFETY: a plain query. + if unsafe { self.device.GetDeviceRemovedReason() }.is_err() { + let runs: Vec<&HostList> = items + .iter() + .filter_map(|i| match i { + Late::Run(f) => Some(f), + _ => None, + }) + .flat_map(|f| f.order.iter().map(|&i| f.lists[i].host())) + .collect(); + fail(format_args!( + "host GPU device removed after {flights} submissions sent ahead (LEONIDA_LATE_WAIT=1) of {} lists{}{}", + runs.len(), + self.removal_data(&runs), + last_notes(&runs) + )); + } + submitting(3, flights); + let copying = std::time::Instant::now(); + let mut seen = std::collections::HashSet::new(); + let mut back: Vec = Vec::new(); + for item in &items { + let Late::Run(flight) = item else { + continue; + }; + if let Some(card) = &flight.card { + self.card_back(card, submitted, &mut seen); + } + for (shadow, ranges) in &flight.back { + match back.iter_mut().find(|(s, _)| std::sync::Arc::ptr_eq(s, shadow)) { + Some((_, all)) => { + for range in ranges { + if !all.contains(range) { + all.push(*range); + } + } + } + None => back.push((shadow.clone(), ranges.clone())), + } + } + } + hand_back(&back); + copy_back(0, copying.elapsed().as_micros() as u64); + } + // In the order given: what tells the title the card is done. + let mut last = 0; + let mut landed = Vec::new(); + for item in items { + match item { + Late::Run(flight) => { + last = flight.number; + for &i in &flight.order { + read_backs(flight.lists[i].host()); + } + if let Some(card) = flight.card { + self.card_done(card); + } + landed.push((flight.lists, flight.order)); + } + Late::Write(at, what, bytes) => what.write(at as *mut u8, bytes), + Late::Signal(fence, value) => crate::fence::set(fence as crate::object::This, value), + } + } + if last > 0 { + FINISHED.store(last, Ordering::Release); + bury(last); + } + line().landed.extend(landed); + } + if counted { + self.log_messages(); + submitting(0, 0); + // What was settled may be what a queue stands at, and the + // caller may not be one that looks (a read-back, a present). + if why != WHY_CARD_DONE { + line().poke = true; + LINE_MOVED.notify_one(); + } + } + working(was_working); + } + + /// [`Host::execute`], or with `late` the first half of + /// [`Host::execute_late`]: the lists are prepared and sent, and what is + /// to be done once they have run comes back with the submission lock + /// still held. + fn submit<'a>(&'a self, runs: &[&HostList], late: bool) -> Option<(std::sync::MutexGuard<'a, u64>, Sent)> { + #[cfg(feature = "diagnostics")] + let called = std::time::Instant::now(); + #[cfg(feature = "diagnostics")] + crate::copystat::submission_begins(); + #[cfg(feature = "diagnostics")] + crate::profile::seen(crate::profile::Seen::Submit); + // One submission at a time from preparation to copy-back: snapshots + // and the ranges shaders write are per host copy, not per submission. + let mut submitted = self.submitted.lock().unwrap_or_else(|e| e.into_inner()); + let was_working = working(true); + submitting(1, runs.len()); + // Flights in the air ([`late`]): a submission that is waited for + // settles them first, one sent ahead only if preparing it reads + // what they write. + if !late { + self.settle(&mut submitted, WHY_SYNC); + } else if let Some(why) = late_blocked(runs) { + if relay_exact() && why == WHY_READ { + // Only until the flights that may write what is read have + // landed: their copy-back's end, not the card's other work. + relay_wait(why, |line| blocked_by(&line.written, runs, false).is_none()); + } else { + self.settle(&mut submitted, why); + } + } + // Descriptors the title copied into placed heaps directly, before + // command lists that index those slots are submitted. + crate::descriptor::sync_heaps(); + let behind = late && flying(); + // Before this submission counts as started: what the sweep lets go + // of is named by no list, and nothing runs now (behind flights the + // sweep waits for a submission that finds none in the air: there is + // one at every present). + static SWEPT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + if !behind { + sweep(); + SWEPT.store(now_ms(), Ordering::Relaxed); + } else if late_free_present() && now_ms() > SWEPT.load(Ordering::Relaxed) + 1500 { + // With the present sent ahead nothing else brings a moment + // with nothing in the air: one is made for the sweep. + self.settle(&mut submitted, WHY_SYNC); + sweep(); + SWEPT.store(now_ms(), Ordering::Relaxed); + } + let behind = late && flying(); + // The slots that waited for a texture's host copy, before the + // lists that may read them run. + crate::descriptor::make_waiting(); + let this_submission = STARTED.fetch_add(1, Ordering::AcqRel) + 1; + // The ranges shaders write are counted for it (with the relay). + crate::shadow::preparing(this_submission); + let started = std::time::Instant::now(); + #[cfg(feature = "diagnostics")] + let lock = (started - called).as_micros() as u64; + #[cfg(feature = "diagnostics")] + crate::copystat::add(crate::copystat::C::Submissions, 1); + let mut lists: Vec> = Vec::with_capacity(2 * runs.len()); + // Where each run's lists start in `lists`. + let mut firsts = Vec::with_capacity(runs.len()); + let mut batch = Batch::default(); + // The time a settle of flights takes inside this preparing: the + // wait for the card and the copy-back have their own places on the + // frame line (run 92 showed them twice, "preparing" 250 ms for 135). + let mut settled = std::time::Duration::ZERO; + // One write-watch asking for everything the submission refreshes + // (`LEONIDA_ASK_ONCE`): per copy, the span of its refreshed ranges. + if crate::watch::once() { + let mut spans: std::collections::HashMap = std::collections::HashMap::new(); + for list in runs { + for step in &list.deferred().copies { + if let Step::Refresh(shadow, address, len) = step + && !shadow.unwatched() + { + let span = spans + .entry(std::sync::Arc::as_ptr(shadow) as usize) + .or_insert((*address, *address + *len)); + *span = (span.0.min(*address), span.1.max(*address + *len)); + } + } + } + let ranges: Vec<(usize, usize)> = spans.into_values().collect(); + crate::watch::ask_once(&ranges); + // Behind flights: the title wrote memory that a flight's shaders + // may write too, and this submission refreshes it. The flights + // are settled, and the asking made again: the copy-back wrote + // title memory, which other copies of it must see. + if behind && stale_under_flights(runs) { + let settling = std::time::Instant::now(); + self.settle(&mut submitted, WHY_STALE); + settled += settling.elapsed(); + crate::watch::ask_once(&ranges); + } + } else if behind && stale_under_flights(runs) { + let settling = std::time::Instant::now(); + self.settle(&mut submitted, WHY_STALE); + settled += settling.elapsed(); + } + for list in runs { + list.run_deferred(&mut batch); + firsts.push(lists.len()); + if let Some(prelude) = list.prelude() { + lists.push(Some(prelude)); + } + lists.push(list.list.cast().ok()); + } + batch.flush(); + crate::watch::ask_once_end(); + // The snapshots of the ranges shaders may write, if they were left + // for now (`crate::shadow::wide_back`): the refreshes are done, the + // lists have not gone to the card. + { + #[cfg(feature = "diagnostics")] + let snapshots = std::time::Instant::now(); + crate::shadow::take_snapshots(); + #[cfg(feature = "diagnostics")] + crate::copystat::add(crate::copystat::C::SnapshotUs, snapshots.elapsed().as_micros() as u64); + } + // Copies in the card's memory: what changed on their CPU side goes + // up ahead of the lists, and a compare of what the shaders may + // write follows them in the same submission. + let flown = late && relay(); + if flown && self.card_results_low() { + let settling = std::time::Instant::now(); + self.settle(&mut submitted, WHY_MOST); + settled += settling.elapsed(); + } + let card = self.card_before(runs, flown, *submitted); + if let Some(check) = card.as_ref().and_then(|c| c.check.clone()) { + lists.push(Some(check)); + } + let prepared = std::time::Instant::now(); + if late { + *submitted += 1; + // SAFETY: closed lists; the fence is ours. + let signalled = unsafe { + self.queue.ExecuteCommandLists(&lists); + self.queue.Signal(&self.fence, *submitted) + }; + self.card_sent(); + if let Err(e) = signalled { + fail(format_args!("a submission sent ahead could not be followed by a signal ({e})")); + } + let back = declared_writes(runs); + let writes = runs.iter().flat_map(|l| l.deferred().writes.clone()).collect(); + submission_us(0, (prepared - started).saturating_sub(settled).as_micros() as u64); + submitting(0, 0); + #[cfg(feature = "diagnostics")] + crate::copystat::submission_ends(lock); + let sent = Sent { + number: this_submission, + card, + back, + writes, + }; + working(was_working); + return Some((submitted, sent)); + } + // Diagnostics: each list on its own, timed (`LEONIDA_GPU_TIMING`). + #[cfg(feature = "diagnostics")] + let groups: Vec<&[Option]> = if timing() { + firsts + .iter() + .zip(firsts.iter().skip(1).chain([&lists.len()])) + .map(|(&a, &b)| &lists[a..b]) + .collect() + } else { + vec![&lists[..]] + }; + #[cfg(not(feature = "diagnostics"))] + let groups = [&lists[..]]; + submitting(2, runs.len()); + for (i, group) in groups.iter().enumerate() { + *submitted += 1; + let started = std::time::Instant::now(); + // SAFETY: closed lists; the fence and event are ours. + unsafe { + self.queue.ExecuteCommandLists(group); + self.card_sent(); + let waited = self + .queue + .Signal(&self.fence, *submitted) + .and_then(|()| self.fence.SetEventOnCompletion(*submitted, self.event)); + match waited { + Ok(()) => { + working(false); + WaitForSingleObject(self.event, INFINITE); + stood(started); + working(true); + } + Err(e) => tracing::warn!(error = %e, "host submission not waited for"), + } + } + // With timing on each group is one of `runs` (and the compare + // of copies in the card's memory, with the last): every + // command's time on the card goes to the sums by pipeline. + #[cfg(feature = "diagnostics")] + if timing() { + // SAFETY: a plain query. + let frequency = unsafe { self.queue.GetTimestampFrequency() }.unwrap_or(1); + for (ms, op) in runs[i].slowest(frequency, usize::MAX) { + crate::copystat::command_took(&op, ms); + } + } + // A submission of one list was never named here (`groups.len() + // > 1` was the test): the two 50 ms lists of the gameplay + // frame, each a submission of its own, printed nothing. + #[cfg(feature = "diagnostics")] + if timing() && started.elapsed() > std::time::Duration::from_millis(50) { + // SAFETY: a plain query. + let frequency = unsafe { self.queue.GetTimestampFrequency() }.unwrap_or(1); + let commands = runs[i].notes.lock().unwrap_or_else(|e| e.into_inner()).len(); + tracing::warn!(ms = started.elapsed().as_millis(), commands, "slow host list"); + for (ms, op) in runs[i].slowest(frequency, 6) { + tracing::warn!("slow list command, {ms:.1} ms: {op}"); + } + } + let _ = (i, started); + } + let _ = &firsts; + FINISHED.store(this_submission, Ordering::Release); + bury(this_submission); + let gpu = prepared.elapsed(); + submission_us(0, (prepared - started).as_micros() as u64); + submission_us(1, gpu.as_micros() as u64); + #[cfg(feature = "diagnostics")] + crate::copystat::card_waited(gpu.as_micros() as u64, || { + let pipelines: std::collections::BTreeSet = runs + .iter() + .flat_map(|l| l.pipelines.lock().unwrap_or_else(|e| e.into_inner()).clone()) + .collect(); + let text = format!("{} lists, pipelines {pipelines:?}", runs.len()); + text.chars().take(1200).collect() + }); + // The host resets a device whose submission runs for about 2 s. + if gpu > std::time::Duration::from_millis(250) { + let pipelines: std::collections::BTreeSet = runs + .iter() + .flat_map(|l| l.pipelines.lock().unwrap_or_else(|e| e.into_inner()).clone()) + .collect(); + tracing::warn!(ms = gpu.as_millis(), lists = runs.len(), ?pipelines, "slow host submission"); + } + // SAFETY: a plain query. + if unsafe { self.device.GetDeviceRemovedReason() }.is_err() { + fail(format_args!( + "host GPU device removed after a submission of {} lists{}{}", + runs.len(), + self.removal_data(runs), + last_notes(runs) + )); + } + submitting(3, runs.len()); + // What shaders wrote goes back before the bottom-of-pipe writes, + // which tell the title the GPU is done; each range once per + // submission, however many dispatches declared it (the world's + // passes declare the same big ranges dozens of times). + let copying = std::time::Instant::now(); + // For copies in the card's memory the compare has run there: the + // pieces that differ are fetched and merged. + if let Some(card) = &card { + self.card_back(card, &mut submitted, &mut std::collections::HashSet::new()); + } + let back = declared_writes(runs); + hand_back(&back); + if let Some(card) = card { + self.card_done(card); + } + #[cfg(feature = "diagnostics")] + if !back.is_empty() { + crate::copystat::add(crate::copystat::C::BackSubmissions, 1); + } + // Nothing of this submission goes back to the title: no range of + // shader writes, no value written when it is done. The wait for + // such a one is only for order and for what the card still holds. + #[cfg(feature = "diagnostics")] + if back.is_empty() && runs.iter().all(|l| l.deferred().writes.is_empty()) { + use crate::copystat::{C, add}; + add(C::NothingBack, 1); + add(C::NothingBackUs, gpu.as_micros() as u64); + } + copy_back(0, copying.elapsed().as_micros() as u64); + for list in runs { + // Read backs first: a value written at the bottom of the pipe + // may be what tells the title that they are there. + read_backs(list); + for &(at, what, bytes) in &list.deferred().writes { + what.write(at as *mut u8, bytes); + } + } + self.log_messages(); + submitting(0, 0); + #[cfg(feature = "diagnostics")] + crate::copystat::submission_ends(lock); + // With the relay: nothing is in the air now, so no fetch still to + // be merged is older than the sends to card copies so far, and + // their notes can go. + if relay() { + crate::shadow::relay_fetched(*QUEUE_ORDER.lock().unwrap_or_else(|e| e.into_inner())); + } + working(was_working); + None + } + + /// With `LEONIDA_D3D12_DRED`: the faulting address and the allocations + /// it lies in (by the names we give them) or the title memory copy just + /// below it; for each list that did not finish, the command it stopped + /// at and what the draws and dispatches in flight there run (or, in + /// lists that never started, the pipelines they bind). + fn removal_data(&self, runs: &[&HostList]) -> String { + let Ok(dred) = self.device.cast::() else { + return String::new(); + }; + let mut text = String::new(); + let mut fault_va = None; + // SAFETY: the outputs are the runtime's, valid while the device + // lives; nodes are walked as linked, histories have their counts. + unsafe { + if let Ok(fault) = dred.GetPageFaultAllocationOutput1() + && fault.PageFaultVA != 0 + { + let va = fault.PageFaultVA; + fault_va = Some(va); + text.push_str(&format!("; page fault at {va:#x}")); + for (what, head) in [ + ("inside", fault.pHeadExistingAllocationNode), + ("inside freed", fault.pHeadRecentFreedAllocationNode), + ] { + let mut names = Vec::new(); + let mut node = head; + while let Some(n) = node.as_ref() + && names.len() < 8 + { + let name = if n.ObjectNameW.is_null() { + "unnamed".to_owned() + } else { + n.ObjectNameW.to_string().unwrap_or_default() + }; + names.push(format!("{name} (type {})", n.AllocationType.0)); + node = n.pNext; + } + if !names.is_empty() { + text.push_str(&format!("; {what} {names:?}")); + } + } + text.push_str(&crate::shadow::near(va)); + text.push_str(&crate::descriptor::host::near_heaps(va)); + } + // The plain output: the extended one (with marker texts) came + // back without stopped lists on this host. + let crumbs = match dred.GetAutoBreadcrumbsOutput() { + Ok(crumbs) => crumbs, + Err(e) => { + text.push_str(&format!("; no breadcrumbs ({e})")); + return text; + } + }; + // Every list's progress (done/count), in the runtime's order. + let mut progress = Vec::new(); + let mut node = crumbs.pHeadAutoBreadcrumbNode; + while let Some(p) = node.as_ref() { + let done = p.pLastBreadcrumbValue.as_ref().copied().unwrap_or(0); + let ours = p.pCommandList.as_ref().map(|l| l.as_raw()); + let index = runs.iter().position(|r| Some(r.list.as_raw()) == ours); + progress.push(format!("{done}/{} {index:?}", p.BreadcrumbCount)); + node = p.pNext; + } + text.push_str(&format!("; breadcrumbs (done/count, list) {progress:?}")); + let mut plain = crumbs.pHeadAutoBreadcrumbNode; + while let Some(p) = plain.as_ref() { + let done = p.pLastBreadcrumbValue.as_ref().copied().unwrap_or(0); + if done < p.BreadcrumbCount && !p.pCommandHistory.is_null() { + let history = + std::slice::from_raw_parts(p.pCommandHistory, p.BreadcrumbCount as usize); + text.push_str(&format!( + "; a list stopped at command {done} of {} (op {})", + p.BreadcrumbCount, history[done as usize].0 + )); + let list = p.pCommandList.as_ref().map(|l| l.as_raw()); + let run = runs.iter().find(|r| Some(r.list.as_raw()) == list); + // The k-th marker command is the k-th note. + #[cfg(feature = "diagnostics")] + let markers: Vec<(u32, String)> = run.map_or_else(Vec::new, |r| { + let notes = r.notes.lock().unwrap_or_else(|e| e.into_inner()); + history + .iter() + .enumerate() + .filter(|(_, op)| **op == D3D12_AUTO_BREADCRUMB_OP_SETMARKER) + .zip(notes.iter()) + .map(|((at, _), (note, range))| { + let place = fault_va.zip(*range).map(|(va, r)| fault_in(va, r)); + (at as u32, format!("{note}{}", place.unwrap_or_default())) + }) + .collect() + }); + #[cfg(not(feature = "diagnostics"))] + let markers: Vec<(u32, String)> = Vec::new(); + #[cfg(not(feature = "diagnostics"))] + let _ = fault_va; + if done > 0 { + text.push_str(&in_flight(history, &markers, done as usize)); + } else if let Some(r) = run { + let pipelines = r.pipelines.lock().unwrap_or_else(|e| e.into_inner()); + text.push_str(&format!(", its pipelines {pipelines:?}")); + } + } + plain = p.pNext; + } + } + text + } + + /// With the frame line (`LEONIDA_D3D12_DEBUG=1`, diagnostics builds): + /// the debug layer's messages since the last call go to our log, the + /// first five of each kind in full, the rest counted, with one line of + /// the counts by kind. + /// + /// They were only read when the device was lost ([`fail`]): a run that + /// survived (run 205) said nothing of what the layer had found, and + /// what it finds is what a driver's fault would have to be traced back + /// to (an object let go while the card uses it, a resource in the + /// wrong state, a view of something gone). + pub(crate) fn drain_messages(&self) { + let Some(queue) = &self.messages else { + return; + }; + static SEEN: Mutex> = Mutex::new(std::collections::BTreeMap::new()); + let mut seen = SEEN.lock().unwrap_or_else(|e| e.into_inner()); + // SAFETY: each message is read into a buffer of the size the queue + // reports, then the queue is emptied. + let stored = unsafe { + let stored = queue.GetNumStoredMessages(); + for i in 0..stored { + let mut size = 0; + if queue.GetMessage(i, None, &mut size).is_err() || size == 0 { + continue; + } + let mut buffer = vec![0u64; size.div_ceil(8)]; + let message = buffer.as_mut_ptr().cast::(); + if queue.GetMessage(i, Some(message), &mut size).is_ok() { + let m = &*message; + let kind = seen.entry(m.ID.0).or_insert((0, m.Severity.0)); + kind.0 += 1; + if kind.0 <= 5 { + let text = std::slice::from_raw_parts(m.pDescription, m.DescriptionByteLength); + let text = String::from_utf8_lossy(text); + let text = text.trim_end_matches('\0'); + tracing::warn!(id = m.ID.0, severity = m.Severity.0, nth = kind.0, "D3D12 debug layer: {text}"); + } + } + } + queue.ClearStoredMessages(); + stored + }; + if stored > 0 { + let counts: Vec = seen.iter().map(|(id, (n, severity))| format!("id {id} (severity {severity}) x{n}")).collect(); + tracing::info!( + "D3D12 debug layer messages so far by kind (severity 0 corruption, 1 error, 2 warning, 3 info, 4 message): {}", + counts.join(", ") + ); + } + } + + /// The host device (`crate::cardmeter`). + pub(crate) fn device(&self) -> &ID3D12Device { + &self.device + } + + /// Ticks a second of the queue's timestamps; 0 if it has none. + pub(crate) fn timestamp_frequency(&self) -> u64 { + // SAFETY: a plain query. + unsafe { self.queue.GetTimestampFrequency() }.unwrap_or(0) + } + + /// Moves the debug layer's messages into our log; returns the first + /// error among them. + pub(crate) fn log_messages(&self) -> Option { + let Some(queue) = &self.messages else { + return None; + }; + let mut first_error = None; + // SAFETY: each message is read into a buffer of the size the queue + // reports, then the queue is emptied. + unsafe { + for i in 0..queue.GetNumStoredMessages() { + let mut size = 0; + if queue.GetMessage(i, None, &mut size).is_err() || size == 0 { + continue; + } + let mut buffer = vec![0u64; size.div_ceil(8)]; + let message = buffer.as_mut_ptr().cast::(); + if queue.GetMessage(i, Some(message), &mut size).is_ok() { + let m = &*message; + let text = std::slice::from_raw_parts(m.pDescription, m.DescriptionByteLength); + let text = String::from_utf8_lossy(text); + let text = text.trim_end_matches('\0'); + tracing::warn!(id = m.ID.0, severity = m.Severity.0, "D3D12: {text}"); + if m.Severity.0 <= D3D12_MESSAGE_SEVERITY_ERROR.0 && first_error.is_none() { + first_error = Some(text.to_owned()); + } + } + } + queue.ClearStoredMessages(); + } + first_error + } + + /// A host render target view of `resource`, valid until it is recorded. + pub(crate) fn rtv( + &self, + resource: Option<&ID3D12Resource>, + desc: Option<&D3D12_RENDER_TARGET_VIEW_DESC>, + ) -> D3D12_CPU_DESCRIPTOR_HANDLE { + let slot = self.next_rtv.fetch_add(1, Ordering::Relaxed) % RTV_RING; + // SAFETY: a slot of our heap and a live resource, or none with a + // description (a typed null view). + unsafe { + let mut handle = self.rtvs.GetCPUDescriptorHandleForHeapStart(); + handle.ptr += (slot * self.rtv_size) as usize; + self.device + .CreateRenderTargetView(resource, desc.map(|d| d as *const _), handle); + handle + } + } + + /// A host depth view of `resource`, valid until it is recorded. + pub(crate) fn dsv( + &self, + resource: &ID3D12Resource, + desc: Option<&D3D12_DEPTH_STENCIL_VIEW_DESC>, + ) -> D3D12_CPU_DESCRIPTOR_HANDLE { + let slot = self.next_dsv.fetch_add(1, Ordering::Relaxed) % RTV_RING; + // SAFETY: a slot of our heap and a live resource. + unsafe { + let mut handle = self.dsvs.GetCPUDescriptorHandleForHeapStart(); + handle.ptr += (slot * self.dsv_size) as usize; + self.device + .CreateDepthStencilView(resource, desc.map(|d| d as *const _), handle); + handle + } + } +} + +impl HostList { + /// The timestamp heap and its read-back buffer (diagnostics, timing on). + #[cfg(feature = "diagnostics")] + fn stamps(&self) -> Option<&(ID3D12QueryHeap, ID3D12Resource)> { + if !timing() { + return None; + } + self.stamps + .get_or_init(|| { + let device = &host()?.device; + let mut heap: Option = None; + let mut back: Option = None; + let readback = D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_READBACK, ..Default::default() }; + let desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, + Width: u64::from(STAMPS) * 8, + Height: 1, + DepthOrArraySize: 1, + MipLevels: 1, + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, + ..Default::default() + }; + // SAFETY: plain object creation. + unsafe { + device + .CreateQueryHeap( + &D3D12_QUERY_HEAP_DESC { Type: D3D12_QUERY_HEAP_TYPE_TIMESTAMP, Count: STAMPS, NodeMask: 0 }, + &mut heap, + ) + .ok()?; + device + .CreateCommittedResource( + &readback, + D3D12_HEAP_FLAG_NONE, + &desc, + D3D12_RESOURCE_STATE_COPY_DEST, + None, + &mut back, + ) + .ok()?; + } + Some((heap?, back?)) + }) + .as_ref() + } + + /// The noted commands that took longest on the GPU, longest first, as + /// (milliseconds, text) (diagnostics, timing on, after the list ran). + #[cfg(feature = "diagnostics")] + fn slowest(&self, frequency: u64, n: usize) -> Vec<(f64, String)> { + let notes = self.notes.lock().unwrap_or_else(|e| e.into_inner()); + let (Some((_, back)), count) = (self.stamps(), notes.len().min(STAMPS as usize - 1)) else { + return Vec::new(); + }; + let mut data = std::ptr::null_mut(); + let range = D3D12_RANGE { Begin: 0, End: (count + 1) * 8 }; + // SAFETY: a read-back buffer the finished list resolved into. + let stamps: Vec = unsafe { + if back.Map(0, Some(&range), Some(&mut data)).is_err() { + return Vec::new(); + } + let s = std::slice::from_raw_parts(data.cast::(), count + 1).to_vec(); + back.Unmap(0, None); + s + }; + let mut times: Vec<(f64, String)> = (0..count) + .map(|i| { + let ticks = stamps[i + 1].saturating_sub(stamps[i]); + (ticks as f64 * 1e3 / frequency.max(1) as f64, notes[i].0.chars().take(300).collect()) + }) + .collect(); + times.sort_by(|a, b| b.0.total_cmp(&a.0)); + times.truncate(n); + times + } + + pub(crate) fn close(&self) { + self.twins_to_depth(); + let scratch = self.indirect_args.lock().unwrap_or_else(|e| e.into_inner()).clone(); + if let Some((scratch, _)) = scratch { + self.indirect_common(&scratch); + } + self.card_budget_out(); + // The scratch buffers its prelude fills and leaves readable as + // arguments: common again behind the list, as every scratch buffer. + for set in self.gather.lock().unwrap_or_else(|e| e.into_inner()).sets.iter().filter(|s| s.records() > 0) { + // SAFETY: an open list and a live buffer. + unsafe { + self.list.ResourceBarrier(&[transition( + &set.scratch, + D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT, + D3D12_RESOURCE_STATE_COMMON, + )]); + } + } + crate::cardmeter::end(&self.list, crate::cardmeter::Span::from_raw(self.pipeline_meter.swap(u32::MAX, Ordering::Relaxed))); + crate::cardmeter::end_named( + &self.list, + crate::cardmeter::Span::from_raw(self.meter.swap(u32::MAX, Ordering::Relaxed)), + &self.pipelines.lock().unwrap_or_else(|e| e.into_inner()), + ); + #[cfg(feature = "diagnostics")] + if let Some((heap, back)) = self.stamps() { + let count = (self.notes.lock().unwrap_or_else(|e| e.into_inner()).len() as u32).min(STAMPS - 1); + // SAFETY: an open list, our heap and read-back buffer. + unsafe { + self.list.EndQuery(heap, D3D12_QUERY_TYPE_TIMESTAMP, count); + self.list.ResolveQueryData(heap, D3D12_QUERY_TYPE_TIMESTAMP, 0, count + 1, back, 0); + } + } + // SAFETY: our list. + if let Err(e) = unsafe { self.list.Close() } { + fail(format_args!( + "a host command list did not close ({e}): a command recorded into it was invalid" + )); + } + } + + /// Only after the list's last submission finished (every one is waited + /// for). + pub(crate) fn reset(&self) { + #[cfg(feature = "diagnostics")] + let started = std::time::Instant::now(); + self._alive.used(); + *self.deferred() = Deferred::default(); + self.states.lock().unwrap_or_else(|e| e.into_inner()).clear(); + self.twins.lock().unwrap_or_else(|e| e.into_inner()).clear(); + self.pipelines.lock().unwrap_or_else(|e| e.into_inner()).clear(); + { + let mut gather = self.gather.lock().unwrap_or_else(|e| e.into_inner()); + let Gather { closed, sets, spare, .. } = &mut *gather; + *closed = false; + for set in sets.drain(..) { + if spare.len() < GATHER_SETS { + spare.push(set.into_scratch()); + } + } + } + #[cfg(feature = "diagnostics")] + self.notes.lock().unwrap_or_else(|e| e.into_inner()).clear(); + { + let mut scratch = self.scratch.lock().unwrap_or_else(|e| e.into_inner()); + (scratch.current, scratch.used) = (0, 0); + // Every submission of the list has run: nothing reads its + // scratch memory any more, and the next list to ask takes it. + if scratch_pool() { + give_chunks(std::mem::take(&mut scratch.chunks)); + } + } + // SAFETY: the list is not executing. + let reset = unsafe { + self.allocator + .Reset() + .and_then(|()| self.list.Reset(&self.allocator, None)) + }; + if let Err(e) = reset { + fail(format_args!("a host command list did not reset ({e})")); + } + self.meter + .store(crate::cardmeter::begin(&self.list, crate::cardmeter::Kind::Lists).raw(), Ordering::Relaxed); + #[cfg(feature = "diagnostics")] + crate::copystat::add(crate::copystat::C::ResetNs, started.elapsed().as_nanos() as u64); + } + + /// Moves a title texture's host copy to `wanted` (a host state) in this + /// list: the host texture and the state it leaves, if that is a change. + /// The list's first use of a texture records nothing: its prelude brings + /// the texture there at submission. + pub(crate) fn transition( + &self, + resource: crate::object::This, + wanted: u32, + ) -> Option<(&'static ID3D12Resource, u32)> { + let texture = crate::resource::host_resource(resource)?; + let copy = crate::resource::host_copy(resource)?; + let wanted = legal_state(texture, wanted); + let mut states = self.states.lock().unwrap_or_else(|e| e.into_inner()); + match states.entry(std::sync::Arc::as_ptr(©) as usize) { + std::collections::hash_map::Entry::Vacant(v) => { + v.insert((wanted, wanted, copy)); + None + } + std::collections::hash_map::Entry::Occupied(mut o) => { + let before = std::mem::replace(&mut o.get_mut().1, wanted); + (before != wanted).then_some((texture, before)) + } + } + } + + /// Moves host texture `copy` to `wanted` (a host state) in this list, + /// as [`HostList::transition`] does a title resource's host copy, and + /// records the barrier: for textures that are not a title resource's + /// host copy (colour twins) and for the copies between the two. + fn settle(&self, copy: &std::sync::Arc, wanted: u32) { + let wanted = legal_state(©.texture, wanted); + let mut states = self.states.lock().unwrap_or_else(|e| e.into_inner()); + let before = match states.entry(std::sync::Arc::as_ptr(copy) as usize) { + std::collections::hash_map::Entry::Vacant(v) => { + v.insert((wanted, wanted, copy.clone())); + None + } + std::collections::hash_map::Entry::Occupied(mut o) => { + let before = std::mem::replace(&mut o.get_mut().1, wanted); + (before != wanted).then_some(before) + } + }; + drop(states); + if let Some(before) = before { + let barrier = transition( + ©.texture, + D3D12_RESOURCE_STATES(before as i32), + D3D12_RESOURCE_STATES(wanted as i32), + ); + // SAFETY: an open list and a live texture. + unsafe { self.list.ResourceBarrier(&[barrier]) }; + } + } + + /// A use of title texture `resource` about to be recorded, if it is a + /// depth texture with a colour twin (false if it is not): of the twin + /// (`colour`: unordered access) or of the depth texture (depth target, + /// clear, shader read, copy, resolve), writing it or only reading. The + /// side used is first brought up to date: by a copy recorded here if + /// this list wrote the other side since, by the list's prelude if the + /// list uses the side as it finds it. The twin is left in the + /// unordered access state; the caller moves the depth texture to the + /// state its use needs, as for any texture. A twin still ahead when the + /// list closes is copied then (`twins_to_depth`). + /// shortcut: every depth target bound for a draw counts as written + /// (also when the draw only tests), and every unordered access view a + /// shader names as written; views a shader picks from the heap by a + /// computed index are not seen here at all. + pub(crate) fn twin_use( + &self, + resource: crate::object::This, + colour: bool, + write: bool, + ) -> bool { + const UNORDERED_ACCESS: u32 = 0x8; + // Asked for every texture a draw reads: most have no twin. + let Some(twin) = crate::resource::twin(resource) else { + return false; + }; + let Some(depth) = crate::resource::host_copy(resource) else { + return false; + }; + let side = usize::from(colour); + let mut twins = self.twins.lock().unwrap_or_else(|e| e.into_inner()); + let u = twins + .entry(std::sync::Arc::as_ptr(&twin) as usize) + .or_insert_with(|| TwinUse { + depth: depth.clone(), + twin: twin.clone(), + needs: [false; 2], + behind: [None; 2], + writing: false, + late: false, + }); + let copy = match u.behind[side] { + Some(behind) => behind, + None => { + u.needs[side] = true; + false + } + }; + u.behind[side] = Some(false); + match (write, colour) { + // Shaders write the twin when the draw or dispatch runs: what + // the same one reads of the depth texture is prepared before + // (`twins_written`). + (true, true) => u.writing = true, + (true, false) => u.behind[1] = Some(true), + (false, _) => {} + } + // shortcut: the depth plane's twin is not drawn into the plane + // here: the pass sets a pipeline and a target of ours, which a list + // still recording the title's commands cannot take. This use sees + // the plane as it was; the pass runs when the list closes + // (`twins_to_depth`). Counted. + if copy && !colour && twin.plane.is_some() { + u.late = true; + crate::resource::PLANES[2].fetch_add(1, Ordering::Relaxed); + } + drop(twins); + if copy { + self.twin_copy(&depth, &twin, colour); + } else if colour { + self.settle(&twin.colour, UNORDERED_ACCESS); + } + // The depth plane's twin is written through unordered access too. + if colour && let Some(plane) = &twin.plane { + self.settle(plane, UNORDERED_ACCESS); + } + true + } + + /// Records the pass that draws the twin of the depth plane of `depth` + /// into the plane, if `twin` has one, with the moves to the states the + /// pass needs; the twin is left in the unordered access state. Only + /// for a list that records nothing of the title's afterwards + /// (`record_plane_pass`). + fn pass_plane( + &self, + depth: &std::sync::Arc, + twin: &crate::resource::Twin, + ) { + const UNORDERED_ACCESS: u32 = 0x8; + const DEPTH_WRITE: u32 = 0x10; + const PIXEL_SHADER_RESOURCE: u32 = 0x80; + let Some(plane) = &twin.plane else { return }; + self.settle(depth, DEPTH_WRITE); + self.settle(plane, PIXEL_SHADER_RESOURCE); + record_plane_pass(&self.list, &depth.texture, &plane.texture); + self.settle(plane, UNORDERED_ACCESS); + } + + /// Records the copy of a depth texture into its colour twin (`colour`) + /// or of the twin into the depth texture, with the moves to the copy + /// states. The twin is left in the unordered access state. + fn twin_copy( + &self, + depth: &std::sync::Arc, + twin: &crate::resource::Twin, + colour: bool, + ) { + const UNORDERED_ACCESS: u32 = 0x8; + const COPY_DEST: u32 = 0x400; + const COPY_SOURCE: u32 = 0x800; + let (from, to) = if colour { + (depth, &twin.colour) + } else { + (&twin.colour, depth) + }; + self.settle(from, COPY_SOURCE); + self.settle(to, COPY_DEST); + record_twin_copy(&self.list, &depth.texture, twin, colour); + self.settle(&twin.colour, UNORDERED_ACCESS); + } + + /// Before the list closes: the depth textures whose twins it wrote last + /// are given what was written, and left readable by shaders. Shaders + /// that pick a view from the heap by a computed index are not seen by + /// `twin_use` and read the depth texture in lists that never name it + /// (in a captured frame of the title no table names a shadow + /// map for reading but the pass that fills the next one). + fn twins_to_depth(&self) { + const SHADER_RESOURCE: u32 = 0x40 | 0x80; + let mut twins = self.twins.lock().unwrap_or_else(|e| e.into_inner()); + let written: Vec<_> = twins + .values_mut() + .filter(|u| u.behind[0] == Some(true) || u.late) + .map(|u| { + // Not copied again if the list copied since the last write + // and only the depth plane's pass is left. + let copy = u.behind[0] == Some(true); + u.behind[0] = Some(false); + u.late = false; + (u.depth.clone(), u.twin.clone(), copy) + }) + .collect(); + drop(twins); + for (depth, twin, copy) in &written { + if *copy { + self.twin_copy(depth, twin, false); + } + // Nothing of the title's is recorded after this: the pass may + // leave its own pipeline and target set. + self.pass_plane(depth, twin); + self.settle(depth, SHADER_RESOURCE); + } + } + + /// The draw or dispatch just prepared is recorded: the twins it writes + /// now hold what their depth textures lack. + pub(crate) fn twins_written(&self) { + let mut twins = self.twins.lock().unwrap_or_else(|e| e.into_inner()); + for u in twins.values_mut().filter(|u| u.writing) { + u.writing = false; + u.behind[0] = Some(true); + } + } + + /// At submission: the list that moves each texture this list uses from + /// its real state to the one the list starts with; the textures' real + /// states become those the list ends with. For depth textures with a + /// colour twin it first copies the side the list uses as it finds it + /// from the other, if a list submitted earlier left it behind. + fn prelude(&self) -> Option { + const COPY_DEST: u32 = 0x400; + const COPY_SOURCE: u32 = 0x800; + let host_state = |state: u32| D3D12_RESOURCE_STATES(state as i32); + let states = self.states.lock().unwrap_or_else(|e| e.into_inner()); + // The copies (depth texture, twin, whether into the twin); the + // sides are then as this list leaves them. + let mut syncs = Vec::new(); + let twins = self.twins.lock().unwrap_or_else(|e| e.into_inner()); + for u in twins.values() { + let real = u.twin.behind.load(Ordering::Relaxed); + let mut behind = [real & 1 != 0, real & 2 != 0]; + for side in [0, 1] { + if u.needs[side] && behind[side] { + syncs.push((u.depth.clone(), u.twin.clone(), side == 1)); + behind = [false; 2]; + } + } + let left = [0, 1].map(|side| u.behind[side].unwrap_or(behind[side])); + let left = u32::from(left[0]) | (u32::from(left[1]) << 1); + u.twin.behind.store(left, Ordering::Relaxed); + } + drop(twins); + // A copy runs with its textures in the copy states: each moves + // there from its real state, and from there to the state the list + // starts with (back to its real state if the list does not use it). + let mut to_copy = Vec::new(); + let mut barriers = Vec::new(); + let mut copying = std::collections::HashMap::new(); + for (depth, twin, colour) in &syncs { + let (from, to) = if *colour { + (depth, &twin.colour) + } else { + (&twin.colour, depth) + }; + for (texture, state) in [(from, COPY_SOURCE), (to, COPY_DEST)] { + let key = std::sync::Arc::as_ptr(texture) as usize; + let real = texture.state.load(Ordering::Relaxed); + copying.insert(key, state); + if real != state { + to_copy.push(transition( + &texture.texture, + host_state(real), + host_state(state), + )); + if !states.contains_key(&key) { + barriers.push(transition( + &texture.texture, + host_state(state), + host_state(real), + )); + } + } + } + } + barriers.extend(states.iter().filter_map(|(key, (first, last, copy))| { + let real = copy.state.swap(*last, Ordering::Relaxed); + let real = copying.get(key).copied().unwrap_or(real); + (real != *first) + .then(|| transition(©.texture, host_state(real), host_state(*first))) + })); + // The records the list's draws read from slots (`crate::indirect::gather`). + let gather = self.gather.lock().unwrap_or_else(|e| e.into_inner()); + let gathered = gather.sets.iter().any(|s| s.records() > 0); + if barriers.is_empty() && syncs.is_empty() && !gathered { + return None; + } + let Some((allocator, list)) = self + .prelude + .get_or_init(|| host().and_then(|h| h.make_prelude())) + .as_ref() + else { + fail(format_args!("no host list for a state prelude")); + }; + // SAFETY: the prelude is not executing (every submission is waited + // for); the textures are live. + let recorded = unsafe { + allocator.Reset().and_then(|()| { + list.Reset(allocator, None)?; + if !to_copy.is_empty() { + list.ResourceBarrier(&to_copy); + } + for (depth, twin, colour) in &syncs { + record_twin_copy(list, &depth.texture, twin, *colour); + } + if !barriers.is_empty() { + list.ResourceBarrier(&barriers); + } + if gathered { + // The slots must hold clamped records before a draw + // reads them: a prelude that cannot record the passes + // is no prelude. + let filled = match &gather.budget { + Some(budget) => crate::indirect::record_gathers(list, &gather.sets, budget), + None => false, + }; + if !filled { + fail(format_args!("a list's gathered indirect records could not be clamped in its prelude")); + } + } + list.Close() + }) + }; + if let Err(e) = recorded { + fail(format_args!("a host state prelude did not record ({e})")); + } + list.cast().ok() + } + + /// From here on the list gathers no records (`crate::indirect::gather`): + /// what is about to be recorded may write arguments. + pub(crate) fn gather_close(&self) { + self.gather.lock().unwrap_or_else(|e| e.into_inner()).closed = true; + } + + /// A slot for the record at `offset` of the host copy `src` in the + /// scratch buffer the list's prelude fills (`crate::indirect::gather`, + /// which checked the record): the buffer and the slot's place in it. + pub(crate) fn gather_slot(&self, src: &ID3D12Resource, src_id: u64, offset: u32, (kind, stride): (u32, u32)) -> Option<(ID3D12Resource, u64)> { + let none = |why: usize| { + crate::indirect::GATHER_NONE[why].fetch_add(1, Ordering::Relaxed); + None + }; + let mut gather = self.gather.lock().unwrap_or_else(|e| e.into_inner()); + if gather.closed { + return none(1); + } + let found = gather + .sets + .iter() + .position(|s| s.src_id == src_id && s.kind == kind && s.stride == stride && s.src.as_raw() == src.as_raw()); + let at = match found { + Some(at) => at, + None => { + if gather.sets.len() >= GATHER_SETS { + return none(2); + } + // The prelude zeroes the budget as the list zeroes its own. + if self.list.cast::().is_err() { + return none(4); + } + let Some(host) = host() else { + return none(4); + }; + if gather.budget.is_none() { + let Some(budget) = host.uav_buffer(256) else { + return none(4); + }; + name(&budget, || "indirect budget of gathered records".to_owned()); + gather.budget = Some(budget); + } + let scratch = match gather.spare.pop() { + Some(scratch) => scratch, + None => { + let Some(scratch) = host.uav_buffer(u64::from(crate::indirect::GATHER_MOST) * u64::from(crate::indirect::GATHER_STRIDE)) else { + return none(4); + }; + name(&scratch, || "indirect arguments, gathered".to_owned()); + scratch + } + }; + let Some(table) = self.scratch(u64::from(crate::indirect::GATHER_MOST) * 4) else { + gather.spare.push(scratch); + return none(4); + }; + gather.sets.push(crate::indirect::GatherSet::new(src.clone(), src_id, (kind, stride), scratch, table)); + gather.sets.len() - 1 + } + }; + let set = &mut gather.sets[at]; + let Some(slot) = set.slot(offset) else { + return none(3); + }; + Some((set.scratch.clone(), u64::from(slot) * u64::from(stride))) + } + + /// Notes what the command about to be recorded does, as a marker + /// command whose text the list keeps (diagnostics, with device-removed + /// data on): the report pairs the breadcrumbs' marker commands with the + /// texts in order and names the commands a fault stopped among. + #[cfg(feature = "diagnostics")] + pub(crate) fn note_op(&self, what: impl FnOnce() -> String) { + self.note(what, None); + } + + /// As [`HostList::note_op`], for a copy that reads the host GPU range + /// `(address, bytes)`: the report places the faulting address in it. + #[cfg(feature = "diagnostics")] + pub(crate) fn note_read(&self, what: impl FnOnce() -> String, range: (u64, u64)) { + self.note(what, Some(range)); + } + + #[cfg(feature = "diagnostics")] + fn note(&self, what: impl FnOnce() -> String, range: Option<(u64, u64)>) { + if !dred_on() { + crate::capture::op(std::ptr::from_ref(self) as usize, what); + return; + } + { + let started = std::time::Instant::now(); + let at = self.notes.lock().unwrap_or_else(|e| e.into_inner()).len() as u32; + if let Some((heap, _)) = self.stamps() && at < STAMPS - 1 { + // SAFETY: an open list and our query heap. + unsafe { self.list.EndQuery(heap, D3D12_QUERY_TYPE_TIMESTAMP, at) }; + } + let what = what(); + crate::capture::op(std::ptr::from_ref(self) as usize, || what.clone()); + let text: Vec = what.encode_utf16().chain([0]).collect(); + const UNICODE: u32 = 0; + // SAFETY: an open list; the marker is copied when recorded. + unsafe { + self.list.SetMarker(UNICODE, Some(text.as_ptr().cast()), 2 * text.len() as u32) + }; + self.notes + .lock() + .unwrap_or_else(|e| e.into_inner()) + .push((what, range)); + crate::copystat::add(crate::copystat::C::NoteNs, started.elapsed().as_nanos() as u64); + } + } + + /// Whether nothing recorded since the list was opened does any work: + /// no draw or dispatch (the first keeps its pipeline), no copy, clear, + /// upload or resolve (they defer a step or move a texture's state), no + /// bottom-of-pipe write. State set on the list does not count. + pub(crate) fn untouched(&self) -> bool { + { + let deferred = self.deferred(); + if !(deferred.copies.is_empty() + && deferred.uploads.is_empty() + && deferred.kept.is_empty() + && deferred.textures.is_empty() + && deferred.writes.is_empty() + && deferred.backs.is_empty()) + { + return false; + } + } + self.states.lock().unwrap_or_else(|e| e.into_inner()).is_empty() + && self.twins.lock().unwrap_or_else(|e| e.into_inner()).is_empty() + } + + /// Notes a pipeline the list binds; called where it is bound. + pub(crate) fn used_pipeline(&self, name: &str) { + { + let mut pipelines = self.pipelines.lock().unwrap_or_else(|e| e.into_inner()); + if !pipelines.contains(name) { + pipelines.insert(name.to_owned()); + } + } + if crate::cardmeter::pipelines() { + // The pipeline before it ends here on the card's clock. + crate::cardmeter::end(&self.list, crate::cardmeter::Span::from_raw(self.pipeline_meter.swap(u32::MAX, Ordering::Relaxed))); + self.pipeline_meter.store(crate::cardmeter::begin_named(&self.list, name).raw(), Ordering::Relaxed); + } + } + + fn deferred(&self) -> std::sync::MutexGuard<'_, Deferred> { + self.deferred.lock().unwrap_or_else(|e| e.into_inner()) + } + + /// Copies `len` bytes from `src` to `dst` when the list is submitted. + pub(crate) fn defer_copy(&self, dst: *mut u8, src: *const u8, len: usize) { + let mut deferred = self.deferred(); + COPIES_JOINED[0].fetch_add(1, Ordering::Relaxed); + // A copy that goes on where the one recorded just before it ended, + // source and destination both: with `join_copies` the two are one + // step. + if let Some(Step::Copy(d, s, n)) = deferred.copies.last_mut() + && continues((*d, *s, *n), (dst as usize, src as usize, len)) + { + COPIES_JOINED[1].fetch_add(1, Ordering::Relaxed); + if join_copies() { + *n += len; + return; + } + } + deferred + .copies + .push(Step::Copy(dst as usize, src as usize, len)); + deferred.refreshed.clear(); + } + + /// Copies `len` bytes of title memory at `src` into the list's upload + /// memory at `dst` when the list is submitted. + pub(crate) fn defer_fill(&self, dst: *mut u8, src: *const u8, len: usize) { + self.deferred() + .copies + .push(Step::Fill(dst as usize, src as usize, len)); + } + + /// Brings `[address, address + len)` of a buffer's host copy up to date + /// when the list is submitted (once per range until a title copy + /// intervenes), keeping the copy alive until the list is reset. + pub(crate) fn defer_refresh( + &self, + shadow: &std::sync::Arc, + address: usize, + len: usize, + ) { + let mut deferred = self.deferred(); + let key = (std::sync::Arc::as_ptr(shadow) as usize, address, len); + if deferred.refreshed.insert(key) { + deferred + .copies + .push(Step::Refresh(shadow.clone(), address, len)); + } + } + + /// Shaders of the list write `[address, address + len)` of a buffer's + /// host copy: copied back into title memory once the list has run. + pub(crate) fn defer_gpu_write( + &self, + shadow: &std::sync::Arc, + address: usize, + len: usize, + ) { + self.deferred() + .copies + .push(Step::GpuWrite(shadow.clone(), address, len)); + } + + /// A read back: once the list has run, `rows` rows of `row` bytes go + /// from `buffer` (rows 256-byte pitched, see `PlacedFootprint::host_rows`) + /// to title memory at `dst`, pitched `pitch`. The buffer lives until + /// the list is reset. + pub(crate) fn defer_read_back(&self, buffer: ID3D12Resource, dst: *mut u8, [row, rows, pitch]: [usize; 3]) { + self.deferred().backs.push((buffer, dst as usize, [row, rows, pitch])); + } + + /// Stores `what` (`bytes` of it) at `dst` once the list has run. + pub(crate) fn defer_write(&self, dst: *mut u8, what: crate::queue::Written, bytes: usize) { + self.deferred().writes.push((dst as usize, what, bytes)); + } + + /// Whether the list, once it has run, stores at `address` a value of + /// `bytes` bytes or more for which `holds` says yes (one of its + /// bottom-of-pipe writes, as [`late_met`] reads them of a flight). + pub(crate) fn will_write(&self, address: usize, bytes: usize, holds: impl Fn(u64) -> bool) -> bool { + self.deferred() + .writes + .iter() + .any(|(at, what, n)| *at == address && *n >= bytes && matches!(what, crate::queue::Written::Value(v) if holds(*v))) + } + + /// A mapped upload buffer of `size` bytes, alive until the list is + /// reset. + /// + /// shortcut: one buffer per copy; pool them once uploads are frequent. + pub(crate) fn upload(&self, host: &Host, size: u64) -> Option<(ID3D12Resource, *mut u8)> { + let (buffer, data) = host.upload_buffer(size)?; + name(&buffer, || format!("list upload {size:#x}")); + self.deferred().hold_upload(buffer.clone(), size); + Some((buffer, data)) + } + + /// `len` bytes of upload memory (256-byte aligned) until the list is + /// reset: the host GPU address and the CPU pointer. + pub(crate) fn scratch(&self, len: u64) -> Option<(u64, *mut u8)> { + let host = host()?; + let mut s = self.scratch.lock().unwrap_or_else(|e| e.into_inner()); + let len = len.max(1).next_multiple_of(256); + if len > SCRATCH_CHUNK { + let (buffer, data) = host.upload_buffer(len)?; + name(&buffer, || format!("list scratch {len:#x}")); + // SAFETY: a live buffer. + let gpu = unsafe { buffer.GetGPUVirtualAddress() }; + self.deferred().hold_upload(buffer, len); + return Some((gpu, data)); + } + // The chunk in use while `len` fits in what is left of it, else the + // next one (a list's first chunk may be a small one). + while s.current < s.chunks.len() && s.used + len > s.chunks[s.current].1 { + (s.current, s.used) = (s.current + 1, 0); + } + if s.current == s.chunks.len() { + let size = if scratch_pool() && s.chunks.is_empty() && len <= SCRATCH_FIRST { + SCRATCH_FIRST + } else { + SCRATCH_CHUNK + }; + let chunk = take_chunk(host, size)?; + s.chunks.push((chunk, size)); + s.used = 0; + } + let (data, gpu) = (s.chunks[s.current].0.data, s.chunks[s.current].0.gpu); + let at = s.used; + s.used += len; + Some((gpu + at, (data + at as usize) as *mut u8)) + } + + /// The bytes of scratch chunks the list holds now (after a reset: + /// none while lists share their chunks). + pub(crate) fn scratch_kept(&self) -> u64 { + let scratch = self.scratch.lock().unwrap_or_else(|e| e.into_inner()); + scratch.chunks.iter().map(|c| c.1).sum() + } + + /// The host address of the list's indirect-work budget, zeroed at each + /// submission of the list from the first use after a reset on. + pub(crate) fn budget(&self) -> Option { + let (buffer, data) = self + .budget + .get_or_init(|| { + let (b, d) = host()?.shared_buffer(256)?; + Some((b, d as usize)) + }) + .as_ref()?; + let card = self.card_budget.get_or_init(|| self.make_card_budget()).as_ref(); + let mut deferred = self.deferred(); + if !deferred.budget_zeroed { + deferred.budget_zeroed = true; + let at = *data; + // SAFETY: the list's own mapped words, written before it runs. + // The words after the budget hold what the clamp noted about the + // list's last run (mesh dispatches: the largest group count + // asked for, the groups asked in all; with the card's copy, as + // the list's end copied them here): taken, then zeroed. + deferred.copies.push(Step::Host(Box::new(move || unsafe { + let words = at as *mut u32; + let (largest, all) = (words.add(1).read_volatile(), words.add(2).read_volatile()); + MESH_GROUPS[0].fetch_max(u64::from(largest), Ordering::Relaxed); + MESH_GROUPS[1].fetch_add(u64::from(all), Ordering::Relaxed); + for k in 0..3 { + words.add(k).write_volatile(0); + } + }))); + drop(deferred); + if let Some(card) = card { + self.zero_card_budget(card); + } + } + // SAFETY: a live buffer. + Some(unsafe { card.unwrap_or(buffer).GetGPUVirtualAddress() }) + } + + /// The budget's words in the card's own memory ([`card_budget`]), if + /// the list can zero them itself (`WriteBufferImmediate`). + fn make_card_budget(&self) -> Option { + if !card_budget() { + return None; + } + self.list.cast::().ok()?; + let buffer = host()?.uav_buffer(256)?; + name(&buffer, || "indirect budget".to_owned()); + Some(buffer) + } + + /// Records, before the list's first clamp, the zeroing of the card's + /// copy of the budget: common, written as a copy, then left for + /// unordered access until the list closes ([`HostList::card_budget_out`]). + fn zero_card_budget(&self, card: &ID3D12Resource) { + let Ok(list2) = self.list.cast::() else { + return; + }; + // SAFETY: a live buffer. + let at = unsafe { card.GetGPUVirtualAddress() }; + let zeros = [0u64, 4, 8].map(|offset| D3D12_WRITEBUFFERIMMEDIATE_PARAMETER { + Dest: at + offset, + Value: 0, + }); + // SAFETY: an open list; the buffer is the list's own and in the + // common state at the start of every recording. + unsafe { + self.list.ResourceBarrier(&[transition( + card, + D3D12_RESOURCE_STATE_COMMON, + D3D12_RESOURCE_STATE_COPY_DEST, + )]); + list2.WriteBufferImmediate(zeros.len() as u32, zeros.as_ptr(), None); + self.list.ResourceBarrier(&[transition( + card, + D3D12_RESOURCE_STATE_COPY_DEST, + D3D12_RESOURCE_STATE_UNORDERED_ACCESS, + )]); + } + } + + /// Before the list closes, if this recording charged the card's copy + /// of the budget: its notes on mesh records go to the mapped words + /// (read at the next submission), and it goes back to common. + fn card_budget_out(&self) { + if !self.deferred().budget_zeroed { + return; + } + let (Some(Some(card)), Some(Some((mapped, _)))) = + (self.card_budget.get(), self.budget.get()) + else { + return; + }; + // SAFETY: an open list; both buffers are the list's own. The + // mapped one is promoted from common to the copy destination. + unsafe { + self.list.ResourceBarrier(&[transition( + card, + D3D12_RESOURCE_STATE_UNORDERED_ACCESS, + D3D12_RESOURCE_STATE_COPY_SOURCE, + )]); + self.list.CopyBufferRegion(mapped, 4, card, 4, 8); + self.list.ResourceBarrier(&[transition( + card, + D3D12_RESOURCE_STATE_COPY_SOURCE, + D3D12_RESOURCE_STATE_COMMON, + )]); + } + } + + /// A device-local unordered-access buffer of at least `size` bytes for + /// clamped indirect arguments, reused across executions and resets of the + /// list. Smaller buffers replaced mid-list stay alive until + /// [`HostList::reset`]. + pub(crate) fn indirect_scratch(&self, size: u64) -> Option { + let needed = size.max(64 << 10); + let mut slot = self.indirect_args.lock().unwrap_or_else(|e| e.into_inner()); + if let Some((buffer, cap)) = &*slot + && *cap >= needed + { + return Some(buffer.clone()); + } + let prev = slot.as_ref().map_or(0, |(_, cap)| *cap); + let alloc = prev + .saturating_mul(2) + .max(needed) + .next_multiple_of(64 << 10); + let buffer = host()?.uav_buffer(alloc)?; + name(&buffer, || format!("indirect arguments {alloc:#x}")); + let old = slot.replace((buffer.clone(), alloc)); + drop(slot); + if let Some((old_buf, _)) = old { + // It ends the list common, as every scratch buffer does. + self.indirect_common(&old_buf); + self.keep(&old_buf); + } + Some(buffer) + } + + /// Moves `scratch` back to the common state if a clamp left it readable + /// as indirect arguments ([`HostList::indirect_readable`]): where the + /// list's first clamp expects it. Done before the list closes and before + /// a bigger scratch buffer replaces it: one barrier per list (where + /// there was one per indirect execution), and the list ends as it + /// begins however it is submitted. + fn indirect_common(&self, scratch: &ID3D12Resource) { + { + let mut deferred = self.deferred(); + if deferred.indirect_readable != scratch.as_raw() as usize { + return; + } + deferred.indirect_readable = 0; + } + let barrier = transition( + scratch, + D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT, + D3D12_RESOURCE_STATE_COMMON, + ); + // SAFETY: an open list and a live buffer this recording left in + // `INDIRECT_ARGUMENT`. + unsafe { self.list.ResourceBarrier(&[barrier]) }; + } + + /// The state the list's indirect scratch buffer `scratch` is in at this + /// point of the recording: indirect arguments if a clamp in this + /// recording left it so ([`HostList::indirect_readable`]), otherwise + /// common: the state a buffer is made in, and the one a recording + /// leaves it in when it closes or replaces it ([`HostList::indirect_common`]). + pub(crate) fn indirect_state(&self, scratch: &ID3D12Resource) -> D3D12_RESOURCE_STATES { + if self.deferred().indirect_readable == scratch.as_raw() as usize { + D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT + } else { + D3D12_RESOURCE_STATE_COMMON + } + } + + /// A clamp recorded in this list left `scratch` readable as indirect + /// arguments. It stays so for every execution that reads it, until the + /// next clamp moves it back to unordered access. + pub(crate) fn indirect_readable(&self, scratch: &ID3D12Resource) { + self.deferred().indirect_readable = scratch.as_raw() as usize; + } + + /// The list's buffers for `crate::indirect::window_check`. + pub(crate) fn window_check(&self) -> Option<&crate::indirect::WindowCheck> { + self.window_check.get_or_init(crate::indirect::WindowCheck::new).as_ref() + } + + /// Keeps `object` alive until the list is reset. + pub(crate) fn keep(&self, object: &impl Interface) { + if let Ok(object) = object.cast::() { + self.deferred().kept.push(object); + } + } + + /// Whether this is the first time since the reset that the list asks + /// about `key` (a texture to bring up to date). + pub(crate) fn first_use(&self, key: usize) -> bool { + self.deferred().textures.insert(key) + } + + /// Runs `work` when the list is submitted, in order with its copies. + /// `work` may write title memory (refreshes after it copy again). + pub(crate) fn defer(&self, work: impl Fn() + Send + 'static) { + self.deferred().copies.push(Step::Run(Box::new(work))); + self.deferred().refreshed.clear(); + } + + /// As [`HostList::defer`], for work that writes only host memory. + pub(crate) fn defer_host(&self, work: impl Fn() + Send + 'static) { + self.deferred().copies.push(Step::Host(Box::new(work))); + } + + /// Brings a texture's staging buffer up to date when the list is + /// submitted, keeping it alive until the list is reset. + pub(crate) fn defer_texture(&self, staging: std::sync::Arc) { + self.deferred().copies.push(Step::Texture(staging)); + } + + /// Runs the list's submission-time steps; refreshes go into `batch` + /// (the title's big buffers, a 174 MB one among them, are read by most + /// lists of a submission, through many ranges). + fn run_deferred(&self, batch: &mut Batch) { + #[cfg(feature = "diagnostics")] + use crate::copystat::{C, add}; + for step in &self.deferred().copies { + let started = std::time::Instant::now(); + let copied = match step { + &Step::Copy(dst, src, len) => { + #[cfg(feature = "diagnostics")] + { + add(C::Copies, 1); + add(C::CopyBytes, len as u64); + } + batch.title_wrote(dst, len); + #[cfg(feature = "diagnostics")] + fill_check::copy_runs(dst, src, len); + copy_mapped(dst as *mut u8, src as *const u8, len, true); + // With the submission's one asking: the journal learns it. + crate::watch::wrote(dst, len); + len + } + &Step::Fill(dst, src, len) => { + #[cfg(feature = "diagnostics")] + { + add(C::Copies, 1); + add(C::CopyBytes, len as u64); + fill_check::runs(src, len); + } + copy_mapped(dst as *mut u8, src as *const u8, len, false); + len + } + Step::Refresh(shadow, address, len) => { + #[cfg(feature = "diagnostics")] + { + add(C::Refreshes, 1); + add(C::RefreshBytes, *len as u64); + } + batch.add(shadow, *address, *len); + continue; + } + Step::Run(work) | Step::Host(work) => { + if matches!(step, Step::Run(_)) { + batch.title_written(); + } + work(); + // It wrote title memory, where is not known here: the + // submission's one asking ends, later refreshes ask anew. + if matches!(step, Step::Run(_)) { + crate::watch::ask_once_end(); + } + #[cfg(feature = "diagnostics")] + { + add(C::Runs, 1); + add(C::RunUs, started.elapsed().as_micros() as u64); + } + continue; + } + Step::GpuWrite(shadow, address, len) => { + // The shaders start from the title's data: this copy's + // pending refresh first. The other copies' wait for + // the next flush of all (flushing all of them at every + // range a dispatch writes made thousands of write-watch + // askings a frame). + batch.flush_one(shadow); + #[cfg(feature = "diagnostics")] + let snapshot = std::time::Instant::now(); + shadow.writing(*address, *len); + #[cfg(feature = "diagnostics")] + { + add(C::GpuWrites, 1); + add(C::SnapshotUs, snapshot.elapsed().as_micros() as u64); + } + continue; + } + Step::Texture(staging) => { + if batch.texture_due(staging) { + staging.refresh(); + } + continue; + } + }; + preparing(0, started.elapsed().as_micros() as u64); + preparing(1, copied as u64); + } + } +} + +/// Whether a submission's refreshes of host copies run on several threads, +/// a copy to a thread (`LEONIDA_WIDE_REFRESH=1`; off by default). +/// +/// A submission brings some sixty copies up to date, one after the other +/// on the submitting thread: for each, the pages the title wrote are asked +/// for and read through the kernel into the copy. That is the frame line's +/// "copies", 45-50 ms a frame, and the copies have nothing to do with one +/// another: each refresh writes its own copy and its own notes, and reads +/// title memory. With the switch the copies of a flush (four or more) are +/// spread over the threads kept for the snapshots (`crate::shadow::wide`). +/// The write-watch journal and the guards are behind their own locks, as +/// they are for the title's threads. +fn wide_refresh() -> bool { + static ON: OnceLock = OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("LEONIDA_WIDE_REFRESH").is_some_and(|v| v == "1")) +} + +/// Whether a range of a host copy brought up to date in a submission is +/// left alone for the rest of that submission, until a step of ours writes +/// title memory there (`LEONIDA_REFRESH_ONCE=1`; off by default). After +/// upstream VIctory 6d021fe ("a copy's range brought up to date is not +/// copied again in the submission until a step writes title memory"). +/// +/// A list of dispatches records "refresh this range, shaders write it" for +/// every dispatch, and each of those refreshes was done on its own +/// (`Batch::flush_one`): a walk of the guards or a failed kernel asking +/// for a copy of view memory, some 1,800 to 2,700 a frame and 23 to 29 ms +/// (runs 222 and 225, "watches"), nearly all finding nothing new. +/// +/// What changes: what the title's other threads write into a range while +/// its submission is being prepared is taken by the next submission, not +/// by a later step of this one, as `crate::watch::once` already has it for +/// write-watched memory. What this submission's lists read was written +/// before they were submitted. A title buffer copy of ours takes its +/// bytes out of what counts as up to date ([`Batch::title_wrote`]); any +/// other step that writes title memory takes everything out. +/// +/// `LEONIDA_REFRESH_ONCE=alt`: twenty seconds with, twenty without, in +/// turn, each change said in the log, so that one run measures both in +/// the same scene (two runs do not stand in the same scene at the same +/// second: runs 228 and 229). +fn refresh_once() -> bool { + /// 0 off, 1 on, 2 in turn. + static MODE: OnceLock = OnceLock::new(); + match *MODE.get_or_init(|| match std::env::var("LEONIDA_REFRESH_ONCE").as_deref() { + Ok("1") => 1, + Ok("alt") => 2, + _ => 0, + }) { + 0 => false, + 1 => true, + _ => { + let on = (now_us() / 20_000_000) % 2 == 1; + static LAST: std::sync::atomic::AtomicU8 = std::sync::atomic::AtomicU8::new(2); + if LAST.swap(u8::from(on), Ordering::Relaxed) != u8::from(on) { + tracing::info!( + "refreshes once a submission from now (LEONIDA_REFRESH_ONCE=alt): {}", + if on { "ON" } else { "off, as usual" } + ); + } + on + } + } +} + +/// A submission's refreshes not done yet, merged per buffer copy into the +/// range that covers them: done before a step that writes title memory or +/// gives a range to shaders, and before the lists run. +/// +/// Also the textures brought up to date in the submission so far: most +/// lists of a world submission sample the same textures, and a texture in +/// physical-page memory is hashed whole each time it is checked. Checked +/// once, it is checked again only after a step that writes title memory. +#[derive(Default)] +struct Batch { + refreshes: Vec<(std::sync::Arc, usize, usize)>, + /// Where each copy (by address) is in `refreshes`: the list that makes + /// the heap's buffers ready adds some 4,100 copies, and searching them + /// for every refresh of a submission was tens of millions of + /// comparisons a frame. + index: std::collections::HashMap, + /// With [`refresh_once`], by copy (its address; the copy is held, so + /// that the address names no other): the range of title addresses + /// brought up to date in this submission that no step of ours has + /// written since. + current: std::collections::HashMap, usize, usize)>, + /// Staging buffers (by address) refreshed since the last title write. + textures: std::collections::HashSet, +} + +impl Batch { + fn add(&mut self, shadow: &std::sync::Arc, address: usize, len: usize) { + let end = address + len; + let key = std::sync::Arc::as_ptr(shadow) as usize; + // Brought up to date in this submission already ([`refresh_once`]; + // nothing is in `current` without the switch). + if let Some(&(_, from, to)) = self.current.get(&key) + && from <= address + && end <= to + { + #[cfg(feature = "diagnostics")] + { + crate::copystat::add(crate::copystat::C::Skipped, 1); + crate::copystat::add(crate::copystat::C::SkippedBytes, len as u64); + } + return; + } + match self.index.get(&key) { + Some(&at) => { + let r = &mut self.refreshes[at]; + (r.1, r.2) = (r.1.min(address), r.2.max(end)); + } + None => { + self.index.insert(key, self.refreshes.len()); + self.refreshes.push((shadow.clone(), address, end)); + } + } + } + + /// Before shaders are given a range of `shadow`'s copy: its pending + /// refresh is done, the others stay pending. + fn flush_one(&mut self, shadow: &std::sync::Arc) { + let Some(at) = self.index.remove(&(std::sync::Arc::as_ptr(shadow) as usize)) else { + return; + }; + let (shadow, from, to) = self.refreshes.swap_remove(at); + // The last entry took its place. + if let Some(moved) = self.refreshes.get(at) { + self.index.insert(std::sync::Arc::as_ptr(&moved.0) as usize, at); + } + Self::update(&shadow, from, to); + Self::brought(&mut self.current, &shadow, from, to); + } + + /// With [`refresh_once`]: `[from, to)` of `shadow`'s copy was brought + /// up to date. Kept: its union with what was up to date if they touch, + /// else the larger of the two. + fn brought( + current: &mut std::collections::HashMap, usize, usize)>, + shadow: &std::sync::Arc, + from: usize, + to: usize, + ) { + if !refresh_once() || from >= to { + return; + } + let entry = current + .entry(std::sync::Arc::as_ptr(shadow) as usize) + .or_insert_with(|| (shadow.clone(), from, to)); + if from <= entry.2 && entry.1 <= to { + (entry.1, entry.2) = (entry.1.min(from), entry.2.max(to)); + } else if to - from > entry.2 - entry.1 { + (entry.1, entry.2) = (from, to); + } + } + + /// Brings `[from, to)` of a copy up to date, timed. + fn update(shadow: &crate::shadow::Shadow, from: usize, to: usize) { + let started = std::time::Instant::now(); + let copied = shadow.update(from, to - from); + let us = started.elapsed().as_micros() as u64; + #[cfg(feature = "diagnostics")] + crate::copystat::range(from, to - from, us, 0); + preparing(0, us); + preparing(1, copied as u64); + } + + /// Whether `staging` is still to be refreshed in this submission (and + /// notes it refreshed). + fn texture_due(&mut self, staging: &std::sync::Arc) -> bool { + self.textures.insert(std::sync::Arc::as_ptr(staging) as *const () as usize) + } + + /// Before a step that writes title memory: pending refreshes are done + /// first, and textures are checked again after it. + fn title_written(&mut self) { + self.flush(); + self.textures.clear(); + // Where it writes is not known: no copy counts as up to date. + self.current.clear(); + } + + /// [`Batch::title_written`] for a write of ours whose place is known + /// (a title buffer copy into `[at, at + len)`): of a copy up to date + /// in this submission that holds some of those bytes, the larger part + /// beside them stays so. + fn title_wrote(&mut self, at: usize, len: usize) { + self.flush(); + self.textures.clear(); + let end = at + len; + self.current.retain(|_, entry| { + let (from, to) = (entry.1, entry.2); + if end <= from || to <= at { + return true; + } + let (left, right) = (at.saturating_sub(from), to.saturating_sub(end)); + if left >= right { + entry.2 = from + left; + } else { + entry.1 = end; + } + entry.1 < entry.2 + }); + } + + fn flush(&mut self) { + self.index.clear(); + // One write-watch asking for the copies that lie close together, + // not one per copy. + let ahead = self.refreshes.len() > 1; + if ahead { + let started = std::time::Instant::now(); + let ranges: Vec<(usize, usize)> = self + .refreshes + .iter() + .filter(|r| !r.0.unwatched()) + .map(|r| (r.1, r.2)) + .collect(); + crate::watch::ask_ahead(&ranges); + preparing(0, started.elapsed().as_micros() as u64); + } + if wide_refresh() && self.refreshes.len() >= 4 { + // Each copy on its own, several at a time: a copy's refresh + // writes that copy and reads title memory, nothing of another's. + // The time counted is the time it took, not the threads' sum. + let started = std::time::Instant::now(); + let before = PREPARING[0].load(Ordering::Relaxed); + // Noted now: nothing reads the notes before the jobs are done. + for (shadow, from, to) in &self.refreshes { + Self::brought(&mut self.current, shadow, *from, *to); + } + let jobs: Vec> = self + .refreshes + .drain(..) + .map(|(shadow, from, to)| Box::new(move || Self::update(&shadow, from, to)) as Box) + .collect(); + crate::shadow::wide_run(jobs); + let summed = PREPARING[0].load(Ordering::Relaxed).saturating_sub(before); + let over = summed.saturating_sub(started.elapsed().as_micros() as u64); + PREPARING[0].fetch_sub(over, Ordering::Relaxed); + crate::framelog::sub(crate::framelog::T::CopyUs, over); + } else { + for (shadow, from, to) in self.refreshes.drain(..) { + Self::update(&shadow, from, to); + Self::brought(&mut self.current, &shadow, from, to); + } + } + if ahead { + crate::watch::ask_ahead_done(); + } + } +} + +/// Copies title memory at submission. The ranges were checked against their +/// resources when recorded, but the title may since have unmapped pages of +/// them (tiled memory, page mappings), which read as zeros here; a title +/// destination (`title_dst`) that is not all mapped is left alone. +/// +/// The source is read through the kernel (`ReadProcessMemory`), which +/// reports an unmapped page instead of faulting. Asking `VirtualQuery` first +/// cost about 2 ms per copy in the title's big pools (it walks the page +/// tables to the region's end), which made copies run at 100-200 MB/s. +pub(crate) fn copy_mapped(dst: *mut u8, src: *const u8, len: usize, title_dst: bool) { + #[cfg(feature = "diagnostics")] + match crate::copystat::mode() { + 1 => { + // SAFETY: timing only: the caller vouches for the source. + unsafe { std::ptr::copy(src, dst, len) }; + return; + } + 2 => return, + _ => {} + } + if len == 0 { + return; + } + // A title destination that is not all mapped is left alone. Asking + // Windows first (`VirtualQuery`) walks the page tables to the end of + // the destination's region: in the title's big blocks that is + // milliseconds a copy, and it was a seventh of the submitting thread's + // time in gameplay (run 60: 71 of 500 looks). The kernel's copy below + // says the same when it fails, so the question is only asked then. + // `LEONIDA_COPY_ASK=1` asks first, as before. + static ASK: OnceLock = OnceLock::new(); + let ask_first = title_dst + && *ASK.get_or_init(|| std::env::var_os("LEONIDA_COPY_ASK").is_some_and(|v| v == "1")); + if ask_first && !crate::texture::committed(dst, len) { + return; + } + if title_dst { + // The kernel writes the destination: it must not be guarded. + crate::watch::writing(dst as usize, len); + } + #[cfg(feature = "diagnostics")] + let moved = std::time::Instant::now(); + // Into host memory: in place first, if asked for (`crate::plaincopy`); + // through the kernel if that is off or met a page that was not there. + let whole = (!title_dst && crate::plaincopy::copy(dst, src, len)) || read(src, dst, len); + #[cfg(feature = "diagnostics")] + crate::copystat::add(crate::copystat::C::MoveUs, moved.elapsed().as_micros() as u64); + if whole { + return; + } + // The copy failed: a source page is not there, or the destination is + // not all mapped. Then the destination stays as it is (the kernel may + // have written its first pages). + if title_dst && !ask_first && !crate::texture::committed(dst, len) { + return; + } + #[cfg(feature = "diagnostics")] + crate::copystat::add(crate::copystat::C::Fallbacks, 1); + #[cfg(feature = "diagnostics")] + let sparse = std::time::Instant::now(); + if !title_dst && len >= 64 << 10 { + read_sparse(src, dst, len); + } else { + read_pieces(src, dst, len); + } + #[cfg(feature = "diagnostics")] + crate::copystat::add(crate::copystat::C::SparseUs, sparse.elapsed().as_micros() as u64); +} + +/// After a failed bulk read into host memory, skip contiguous holes. Never +/// cache the query across copies: the title may remap the same address. +fn read_sparse(src: *const u8, dst: *mut u8, len: usize) { + use windows_sys::Win32::System::Memory::{ + MEM_COMMIT, MEMORY_BASIC_INFORMATION, PAGE_NOACCESS, VirtualQuery, + }; + let mut offset = 0; + while offset < len { + let at = src.wrapping_add(offset); + let to = dst.wrapping_add(offset); + let remaining = len - offset; + // SAFETY: the query inspects an address and fills a local structure. + let mut info: MEMORY_BASIC_INFORMATION = unsafe { std::mem::zeroed() }; + let size = unsafe { VirtualQuery(at.cast(), &mut info, size_of_val(&info)) }; + let n = (info.BaseAddress as usize).saturating_add(info.RegionSize) + .saturating_sub(at as usize).min(remaining); + if size != size_of_val(&info) || n == 0 { + read_pieces(at, to, remaining); + break; + } + if info.State != MEM_COMMIT || info.Protect == PAGE_NOACCESS { + #[cfg(feature = "diagnostics")] + crate::copystat::add(crate::copystat::C::Unmapped, n as u64); + // SAFETY: this path is only used with a writable host destination. + unsafe { to.write_bytes(0, n) }; + } else if !read(at, to, n) { + // A mapping may change between query and read. + read_pieces(at, to, n); + } + offset += n; + } +} + +fn read_pieces(src: *const u8, dst: *mut u8, len: usize) { + // Something is unmapped: page by page (64 KiB, then 4 KiB in a piece + // that fails), zeros for what cannot be read. + for_pieces(src as usize, len, 64 << 10, |at, n| { + let to = dst.wrapping_add(at - src as usize); + if !read(at as *const u8, to, n) { + for_pieces(at, n, 4 << 10, |at, n| { + let to = dst.wrapping_add(at - src as usize); + if !read(at as *const u8, to, n) { + #[cfg(feature = "diagnostics")] + crate::copystat::add(crate::copystat::C::Unmapped, n as u64); + // SAFETY: inside the destination, which is mapped. + unsafe { to.write_bytes(0, n) }; + } + }); + } + }); +} + +/// Reads title memory at `src` into `dst`; false if a page of it is not +/// readable. +pub(crate) fn read_into(src: *const u8, dst: &mut [u8]) -> bool { + // In place first, if asked for (`crate::plaincopy`): the destination is + // memory of ours, as in `copy_mapped`. + crate::plaincopy::copy(dst.as_mut_ptr(), src, dst.len()) || read(src, dst.as_mut_ptr(), dst.len()) +} + +/// Copies `len` bytes from `src` to `dst` unless a source page is not +/// readable. +fn read(src: *const u8, dst: *mut u8, len: usize) -> bool { + use windows_sys::Win32::System::Diagnostics::Debug::ReadProcessMemory; + use windows_sys::Win32::System::Threading::GetCurrentProcess; + let mut done = 0; + // SAFETY: the destination is mapped writable memory of `len` bytes; the + // kernel checks the source. + unsafe { ReadProcessMemory(GetCurrentProcess(), src.cast(), dst.cast(), len, &mut done) != 0 } +} + +#[link(name = "ntdll", kind = "raw-dylib")] +unsafe extern "system" { + /// The kernel's write into a process's memory, `(process, address, + /// bytes, length, written out)`: an NTSTATUS, negative when a page of + /// the range is not there or not writable. It changes no protection. + fn NtWriteVirtualMemory( + process: *mut std::ffi::c_void, + base: *mut std::ffi::c_void, + buffer: *const std::ffi::c_void, + size: usize, + written: *mut usize, + ) -> i32; +} + +/// Whether title memory is written with the kernel's own call +/// (`NtWriteVirtualMemory`) and not `WriteProcessMemory`, which first asks +/// what the pages are (as `VirtualQuery` does: about 2 ms a call in the +/// title's big pools, see [`copy_mapped`]): putting back what shaders wrote +/// cost 1.2-1.9 s a frame for 430-800 pieces, 2 ms each whatever their size +/// (run 24). On by default; `LEONIDA_DIRECT_WRITES=0` writes as before. +fn direct_writes() -> bool { + static ON: OnceLock = OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("LEONIDA_DIRECT_WRITES").is_none_or(|v| v != "0")) +} + +/// Copies host memory into title memory after a submission (what shaders +/// wrote), leaving pages that are not mapped alone. +pub(crate) fn write_mapped(dst: *mut u8, src: *const u8, len: usize) { + use windows_sys::Win32::System::Diagnostics::Debug::WriteProcessMemory; + use windows_sys::Win32::System::Threading::GetCurrentProcess; + let direct = direct_writes(); + let write = |at: usize, n: usize| { + let from = src.wrapping_add(at - dst as usize); + let mut done = 0; + if direct { + // SAFETY: as below; the kernel checks the destination and + // writes nothing it cannot (the caller opened its guards: + // `crate::watch::writing`). + return unsafe { + NtWriteVirtualMemory(GetCurrentProcess(), at as _, from.cast(), n, &mut done) >= 0 + }; + } + // SAFETY: the source is our mapped host copy; the kernel checks the + // destination. + unsafe { WriteProcessMemory(GetCurrentProcess(), at as _, from.cast(), n, &mut done) != 0 } + }; + if len == 0 || write(dst as usize, len) { + return; + } + for_pieces(dst as usize, len, 64 << 10, |at, n| { + if !write(at, n) { + for_pieces(at, n, 4 << 10, |at, n| { + write(at, n); + }); + } + }); +} + +/// Calls `f` with the pieces of `[start, start + len)` cut at multiples of +/// `step`. +fn for_pieces(start: usize, len: usize, step: usize, mut f: impl FnMut(usize, usize)) { + let end = start + len; + let mut at = start; + while at < end { + let next = ((at / step + 1) * step).min(end); + f(at, next - at); + at = next; + } +} + +impl Host { + /// The queue everything of ours runs on, for a call that must go to it + /// in order with the lists (`crate::tiles`: a texture's levels are + /// given memory ahead of the list that uploads them). + pub(crate) fn queue(&self) -> &ID3D12CommandQueue { + &self.queue + } + + /// A buffer in the upload heap, mapped for writing. + /// A buffer of `size` bytes the card writes and we read (a read back), + /// in the state copies into it need. + pub(crate) fn read_back_buffer(&self, size: u64) -> Option { + let heap = D3D12_HEAP_PROPERTIES { + Type: D3D12_HEAP_TYPE_READBACK, + ..Default::default() + }; + let desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, + Width: size.max(1), + Height: 1, + DepthOrArraySize: 1, + MipLevels: 1, + SampleDesc: DXGI_SAMPLE_DESC { + Count: 1, + Quality: 0, + }, + Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, + ..Default::default() + }; + let mut buffer: Option = None; + // SAFETY: plain creation of a read-back buffer. + let made = unsafe { + self.device.CreateCommittedResource( + &heap, + D3D12_HEAP_FLAG_NONE, + &desc, + D3D12_RESOURCE_STATE_COPY_DEST, + None, + &mut buffer, + ) + }; + match made { + Ok(()) => buffer, + Err(e) => { + tracing::warn!(error = %e, size, "no read-back buffer"); + None + } + } + } + + pub(crate) fn upload_buffer(&self, size: u64) -> Option<(ID3D12Resource, *mut u8)> { + MADE[0].fetch_add(1, Ordering::Relaxed); + MADE[1].fetch_add(size, Ordering::Relaxed); + let heap = D3D12_HEAP_PROPERTIES { + Type: D3D12_HEAP_TYPE_UPLOAD, + ..Default::default() + }; + let desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, + Width: size.max(1), + Height: 1, + DepthOrArraySize: 1, + MipLevels: 1, + SampleDesc: DXGI_SAMPLE_DESC { + Count: 1, + Quality: 0, + }, + Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, + ..Default::default() + }; + let mut buffer: Option = None; + let mut data = std::ptr::null_mut(); + // SAFETY: plain creation and mapping of an upload buffer. + let made = unsafe { + self.device + .CreateCommittedResource( + &heap, + D3D12_HEAP_FLAG_NONE, + &desc, + D3D12_RESOURCE_STATE_GENERIC_READ, + None, + &mut buffer, + ) + .and_then(|()| { + let b = buffer.as_ref().ok_or_else(windows::core::Error::empty)?; + b.Map(0, None, Some(&mut data)) + }) + }; + match made { + Ok(()) => Some((buffer?, data.cast())), + Err(e) => { + tracing::warn!(error = %e, size, "no upload buffer"); + None + } + } + } +} + +/// The swap chain formats a presented texture can be copied into: its own +/// family's. +fn swap_format(format: DXGI_FORMAT) -> Option { + Some(match format.0 { + 27..=32 => DXGI_FORMAT_R8G8B8A8_UNORM, + 87 | 90 | 91 => DXGI_FORMAT_B8G8R8A8_UNORM, + 23..=25 => DXGI_FORMAT_R10G10B10A2_UNORM, + 9..=14 => DXGI_FORMAT_R16G16B16A16_FLOAT, + _ => return None, + }) +} + +const BUFFERS: u32 = 2; + +struct Presenter { + swap_chain: IDXGISwapChain3, + width: u32, + height: u32, + format: DXGI_FORMAT, + copy: HostList, + /// With presents sent ahead ([`late_free_present`]): a list for each + /// present in the air, and the submission it last flew as (it is used + /// again once that one has finished). + ahead: Vec<(HostList, u64)>, + hwnd: HWND, + meter: Meter, +} + +/// The frame rate, shown in the window's caption every second and logged +/// every few seconds. +struct Meter { + since: std::time::Instant, + frames: u32, + #[cfg(feature = "diagnostics")] + copy_stats_frames: u64, + drawn: u64, + logged: std::time::Instant, + /// The caption the window had, once read. + caption: Option>, +} + +impl Meter { + fn new() -> Self { + let now = std::time::Instant::now(); + Meter { + since: now, + frames: 0, + #[cfg(feature = "diagnostics")] + copy_stats_frames: 0, + drawn: crate::draw::drawn(), + logged: now, + caption: None, + } + } + + /// Counts a presented frame. + fn frame(&mut self, hwnd: HWND) { + #[cfg(feature = "diagnostics")] + tracing::debug!(target: "leonida_gpu::frame", token = crate::frame::current(), "present"); + #[cfg(feature = "diagnostics")] + crate::copystat::presented(); + self.frames += 1; + #[cfg(feature = "diagnostics")] + { + self.copy_stats_frames += 1; + } + let elapsed = self.since.elapsed(); + if elapsed < std::time::Duration::from_secs(1) { + return; + } + let drawn = crate::draw::drawn(); + let frames = f64::from(self.frames); + let fps = frames / elapsed.as_secs_f64(); + crate::fpsbox::set(fps); + let ms = elapsed.as_secs_f64() * 1000.0 / frames; + let draws = (drawn - self.drawn) as f64 / frames; + (self.since, self.frames, self.drawn) = (std::time::Instant::now(), 0, drawn); + // Of a frame, ms preparing submissions and ms waiting for the GPU. + let [cpu, gpu] = [0, 1].map(|i| { + SUBMISSION_US[i].swap(0, Ordering::Relaxed) as f64 / 1000.0 / frames + }); + let [copy_ms, copy_mb, texture_ms, texture_mb] = [0, 1, 2, 3].map(|i| { + let scale = if i % 2 == 0 { 1e3 } else { 1e6 }; + PREPARING[i].swap(0, Ordering::Relaxed) as f64 / scale / frames + }); + let [back_ms, back_mb] = [0, 1].map(|i| { + COPY_BACK[i].swap(0, Ordering::Relaxed) as f64 / [1e3, 1e6][i] / frames + }); + let dropped = crate::draw::take_dropped() as f64 / frames; + let indirect = crate::list::take_indirect() as f64 / frames; + let mesh_largest = MESH_GROUPS[0].swap(0, Ordering::Relaxed); + let mesh_groups = MESH_GROUPS[1].swap(0, Ordering::Relaxed) as f64 / frames; + tracing::info!( + "indirect mesh dispatches: the largest group count asked for {mesh_largest} (run: at most 65535), {mesh_groups:.0} groups asked per frame" + ); + // (Run 200 counted indirect compute records asking for 77,000 to + // 98,000 groups in x, 0.2 to 0.8 a frame, cut to the 65,535 one + // dispatch runs; the counter went when the clamp's budget moved to + // the card's memory.) + { + let [texture_us, slots] = [0, 1].map(|i| crate::draw::HEAP_PASS_PARTS[i].swap(0, Ordering::Relaxed)); + tracing::info!( + "the pass over the heap per frame (the frame line's \"heap buffers ... ms\" is both parts): {:.1} ms in its pass over textures picked by index; {:.0} buffer slots looked at by its pass over buffer views", + texture_us as f64 / 1e3 / frames, + slots as f64 / frames + ); + } + crate::shadow::exact_line(frames); + crate::descriptor::sync_line(frames); + late_line(frames); + card_clock_line(frames, ms); + crate::queue2::line(frames); + crate::plaincopy::line(frames); + if let Some(host) = host() { + host.drain_messages(); + } + { + let held = crate::pipeline::WALKS_HELD.swap(0, Ordering::Relaxed); + if held > 0 { + tracing::info!( + "dispatches of programs that walk ray-tracing structures held back per frame (LEONIDA_BVH_HOLD=1; the builder has not built them): {:.1}", + held as f64 / frames + ); + } + } + crate::shadow::back_line(frames); + { + let [passes, pieces, compares] = [0, 1, 2].map(|i| CARD_PASSES[i].swap(0, Ordering::Relaxed) as f64 / frames); + if passes + compares > 0.0 { + tracing::info!( + "our passes over copies in the card's memory per frame: {passes:.0} hash passes over {pieces:.0} pieces after \ + ranges were sent up (LEONIDA_CARD_REHASH_RUNS=1 joins them: now {}), {compares:.0} compare passes", + if rehash_runs() { "on" } else { "off" } + ); + } + } + { + let [own, asking, still, all] = + [0, 1, 2, 3].map(|i| crate::texture::REFRESH_WAITS[i].swap(0, Ordering::Relaxed) as f64 / 1000.0 / frames); + if all >= 1.0 { + tracing::info!( + "texture refreshes per frame, all threads: {all:.1} ms, of them {own:.1} ms waiting for a texture another thread \ + is refreshing, {asking:.1} ms asking the write watch and the guards, {still:.1} ms waiting for title memory to \ + hold still (the runtime remapping it); the rest is reading, hashing and detiling" + ); + } + let [through, left] = [0, 1].map(|i| crate::texture::UNLOCKED[i].swap(0, Ordering::Relaxed) as f64 / frames); + if through + left > 0.0 { + tracing::info!( + "texture refreshes that did not wait for title memory to hold still, per frame (LEONIDA_TEXTURE_NO_WAIT=1): \ + {through:.1} read through the kernel, {left:.1} left for the next refresh (a page was not there)" + ); + } + } + { + let [copies, joined] = [0, 1].map(|i| COPIES_JOINED[i].swap(0, Ordering::Relaxed) as f64 / frames); + if copies > 0.0 { + tracing::info!( + "title buffer copies recorded per frame: {copies:.0}, of them {joined:.0} continue the one before \ + (LEONIDA_JOIN_COPIES=1 makes those one copy with it: now {})", + if join_copies() { "on" } else { "off" } + ); + } + } + // Passes over the heap's buffer views for shaders that pick them by index. + let picked = crate::draw::HEAP_BUFFER_PASSES.swap(0, Ordering::Relaxed) as f64 / frames; + let picked_ms = + crate::draw::HEAP_BUFFER_MICROS.swap(0, Ordering::Relaxed) as f64 / 1e3 / frames; + // Copies between depth textures and their colour twins, each way. + let [twin_to_depth, twin_to_colour] = + [2, 3].map(|i| crate::resource::TWINS[i].swap(0, Ordering::Relaxed) as f64 / frames); + // Depth planes drawn from their twins. + let planes = crate::resource::PLANES[0].swap(0, Ordering::Relaxed) as f64 / frames; + // Copies in the card's memory (`crate::shadow::cards`). + let card = crate::shadow::card_stats(); + #[cfg(feature = "diagnostics")] + let slow = crate::watch::slow_asks(); + // Over the same frames as the counts above. + #[cfg(feature = "diagnostics")] + let drops = crate::pipeline::take_drops(); + if self.logged.elapsed() >= std::time::Duration::from_secs(5) { + self.logged = std::time::Instant::now(); + tracing::info!( + "placed texture views: {} writes of another view of the texture a slot showed (it kept the old view until the new was made)", + crate::descriptor::host::KEPT_VIEWS.load(Ordering::Relaxed) + ); + tracing::info!( + "copies left out since the start because both sides were one host texture: {}", + crate::list::SELF_COPIES.load(Ordering::Relaxed) + ); + if crate::drvwatch::errors() > 0 { + tracing::warn!( + "errors the graphics driver reported to the system since the start: {} (the paths under suspicion are off)", + crate::drvwatch::errors() + ); + } + crate::tiles::status(); + { + let [queued, due, away, partly, oldest] = + [0, 1, 2, 3, 4].map(|i| crate::draw::HEAP_TEXTURES_QUEUE[i].load(Ordering::Relaxed)); + let [same, parts, tails] = + [0, 1, 2].map(|i| crate::draw::HEAP_TEXTURES_PARTLY[i].load(Ordering::Relaxed)); + tracing::info!( + "textures picked by index, the queue: {queued} slots, {due} of them due (the oldest written {oldest} frames ago), \ + {away} waiting for their memory, {partly} uploaded in part; since the start: {} slots found uploaded already by \ + the draws that read them through tables, {} writes of tables' slots (due some frames later), {} slots taken out \ + as read through a table, {parts} uploads of textures not all mapped ({tails} of them without their first page), \ + {same} looks that found no more mapped; {} slots made stale by a newer view of other memory there, \ + {} ranges of memory mapped, unmapped or written under texture views ({} dropped), {} slots made due by them, \ + {} made slots found unmapped and made null", + crate::draw::HEAP_TEXTURES_TABLED.load(Ordering::Relaxed), + crate::descriptor::host::TABLED_WRITES[0].load(Ordering::Relaxed), + crate::descriptor::host::TABLED_WRITES[1].load(Ordering::Relaxed), + crate::descriptor::host::STALE[0].load(Ordering::Relaxed), + crate::descriptor::host::STALE[1].load(Ordering::Relaxed), + crate::descriptor::host::STALE[2].load(Ordering::Relaxed), + crate::descriptor::host::STALE[3].load(Ordering::Relaxed), + crate::descriptor::host::STALE[4].load(Ordering::Relaxed) + ); + } + { + let mode = crate::watch::page_writes(); + let [writes, bytes, guarded, plain] = [0, 1, 2, 3].map(|i| crate::watch::WRITTEN[i].load(Ordering::Relaxed)); + let [kept, dropped, slots, uploaded] = + [0, 1, 2, 3].map(|i| crate::descriptor::host::PAGE_WRITES[i].load(Ordering::Relaxed)); + tracing::info!( + "writes behind the guards, since the start: {writes} DirectStorage writes into physical pages at addresses the title had mapped ({} MB); {guarded} guarded 64 KiB blocks of host copies lay under them ({}); {plain} reads to plain addresses finished ({}); {kept} ranges under texture views kept for the texture pass ({dropped} dropped); {slots} slots of placed textures held their bytes, {uploaded} of them uploaded before the write ({}) (LEONIDA_PAGE_WRITES: unset or guards opens the guarded blocks, 0 counts only, 1, slots, all)", + bytes >> 20, + if mode & 1 != 0 { "opened, taken again" } else { "left as they were" }, + if mode & 4 != 0 { "told as well" } else { "counted only" }, + if mode & 2 != 0 { "made due again" } else { "left as they were" } + ); + } + #[cfg(feature = "diagnostics")] + tracing::info!( + "write-watch askings of a millisecond or more: {:.1} a frame, {:.1} ms a frame; the longest asking {:.1} ms", + slow[0] as f64 / frames, + slow[1] as f64 / 1e3 / frames, + slow[2] as f64 / 1e3 + ); + if crate::shadow::cards() { + let per_frame = |i: usize| card[i] as f64 / frames; + tracing::info!( + "host copies in the card's memory: {} copies {} MB, their bytes from before {} MB; per frame: \ + {:.1} MB sent up in {:.0} ranges, {:.0} pieces compared on the card, {:.0} of them fetched \ + ({:.1} MB) with {:.1} more waits for the card ({:.1} ms)", + card[7], + card[8] >> 20, + card[9] >> 20, + per_frame(0) / 1e6, + per_frame(1), + per_frame(2), + per_frame(3), + per_frame(4) / 1e6, + per_frame(5), + per_frame(6) / 1e3 + ); + } + tracing::info!( + "{fps:.1} fps, {ms:.1} ms/frame ({cpu:.1} preparing: copies {copy_ms:.1} ms \ + {copy_mb:.1} MB, textures {texture_ms:.1} ms {texture_mb:.1} MB; {gpu:.1} on the \ + GPU; {back_ms:.1} copying back {back_mb:.1} MB), {draws:.0} draws/frame, \ + dropped {dropped:.0} without a host pipeline ({making} being made) and \ + {indirect:.0} indirect; heap buffers {picked:.1} passes {picked_ms:.1} ms; texture slots written so far: {placed} placed, {objects} of objects; \ + textures picked by index: {picked_textures} uploaded so far ({picked_mb} MB), \ + {picked_waiting} waiting, {picked_away} passed over unmapped; depth textures with unordered access: {du0} made, bound as depth {du1}x, cleared as depth {du2}x, unordered views refused {du3}x; buffer views left null as the host would refuse them: {refused}", + picked_textures = crate::draw::HEAP_TEXTURES.load(Ordering::Relaxed), + picked_mb = crate::draw::HEAP_TEXTURE_BYTES.load(Ordering::Relaxed) >> 20, + picked_waiting = crate::draw::HEAP_TEXTURES_WAITING.load(Ordering::Relaxed), + picked_away = crate::draw::HEAP_TEXTURES_AWAY.load(Ordering::Relaxed), + du0 = crate::resource::DEPTH_UNORDERED[0].load(Ordering::Relaxed), + du1 = crate::resource::DEPTH_UNORDERED[1].load(Ordering::Relaxed), + du2 = crate::resource::DEPTH_UNORDERED[2].load(Ordering::Relaxed), + du3 = crate::resource::DEPTH_UNORDERED[3].load(Ordering::Relaxed), + refused = format!( + "{}; depth twins: {} alive, {} depth textures left without one; twin copies per frame: {twin_to_depth:.1} into depth textures, {twin_to_colour:.1} into twins; depth planes: {planes:.1} drawn from their twins per frame, {} times not given back to a twin, {} times used before the pass", + crate::descriptor::host::REFUSED_VIEWS.load(Ordering::Relaxed), + crate::resource::TWINS[0].load(Ordering::Relaxed), + crate::resource::TWINS[1].load(Ordering::Relaxed), + crate::resource::PLANES[1].load(Ordering::Relaxed), + crate::resource::PLANES[2].load(Ordering::Relaxed) + ), + making = crate::pipeline::making(), + placed = crate::descriptor::host::PLACED_TEXTURE_SLOTS.load(Ordering::Relaxed), + objects = crate::descriptor::host::OBJECT_TEXTURE_SLOTS.load(Ordering::Relaxed) + ); + #[cfg(feature = "diagnostics")] + { + crate::copystat::log(std::mem::take(&mut self.copy_stats_frames) as f64); + for (why, n) in drops.iter().take(40) { + tracing::info!( + "dropped {:.1}/frame without a host pipeline: {why}", + *n as f64 / frames + ); + } + } + } + if self.caption.is_none() { + // The window's own text, read without a message. + let mut buffer = vec![0u16; 512]; + // SAFETY: a window handle and a buffer of that length. + let n = unsafe { InternalGetWindowText(hwnd, &mut buffer) }; + buffer.truncate(n.max(0) as usize); + self.caption = Some(buffer); + } + let Some(caption) = &self.caption else { return }; + let text = format!(" | Leonida Legacy {fps:.0} fps {ms:.1} ms/frame {draws:.0} draws/frame"); + let mut text: Vec = caption.iter().copied().chain(text.encode_utf16()).collect(); + text.push(0); + // Setting the text waits for the window's thread (a title thread, + // which may not pump for a while), so a thread of ours does it and + // presenting never waits; it takes the newest text when free. + static PENDING: Mutex)>> = Mutex::new(None); + static SETTER: std::sync::Once = std::sync::Once::new(); + *PENDING.lock().unwrap_or_else(|e| e.into_inner()) = Some((hwnd.0 as usize, text)); + SETTER.call_once(|| { + let _ = std::thread::Builder::new() + .name("leonida-caption".into()) + .spawn(|| { + loop { + let next = PENDING.lock().unwrap_or_else(|e| e.into_inner()).take(); + match next { + // SAFETY: a window handle and a NUL-terminated text. + Some((hwnd, text)) => unsafe { + let _ = SetWindowTextW(HWND(hwnd as *mut _), PCWSTR(text.as_ptr())); + }, + None => std::thread::sleep(std::time::Duration::from_millis(100)), + } + } + }); + }); + } +} + +impl Host { + /// Shows `texture`, which is in `state` (a host state) and stays in it, + /// as frame `frame` (saved if captures are on). `None` if nothing was + /// shown; else, in diagnostics builds, whether the frame was black. + pub(crate) fn present(&self, texture: &ID3D12Resource, state: u32, frame: u64) -> Option { + let showing = std::time::Instant::now(); + let shown = self.present_now(texture, state, frame); + crate::framelog::add(crate::framelog::T::PresentShowUs, showing.elapsed().as_micros() as u64); + shown + } + + fn present_now(&self, texture: &ID3D12Resource, state: u32, frame: u64) -> Option { + // SAFETY: a live resource. + let desc = unsafe { texture.GetDesc() }; + let Some(format) = swap_format(desc.Format) else { + tracing::warn!(format = desc.Format.0, "cannot present this format"); + return None; + }; + let (width, height) = (desc.Width as u32, desc.Height); + let mut presenter = self.presenter.lock().unwrap_or_else(|e| e.into_inner()); + if presenter.is_none() { + *presenter = match self.presenter(width, height, format) { + Ok(p) => Some(p), + Err(e) => { + tracing::warn!(error = %e, "no swap chain"); + return None; + } + }; + } + let p = presenter.as_mut()?; + if (p.width, p.height, p.format) != (width, height, format) { + // Presents sent ahead hold back buffers until they have run. + settle_now(WHY_SYNC); + // SAFETY: no back buffer is held; every submission was waited for. + let resized = unsafe { + p.swap_chain + .ResizeBuffers(BUFFERS, width, height, format, DXGI_SWAP_CHAIN_FLAG(0)) + }; + match resized { + Ok(()) => { + (p.width, p.height, p.format) = (width, height, format); + tracing::info!( + width, + height, + format = format.0, + frame, + "the swap chain's buffers were made again for another size or format" + ); + self.log_video_memory("right after the swap chain's buffers were made again"); + } + Err(e) => { + tracing::warn!(error = %e, width, height, "swap chain not resized"); + return None; + } + } + } + let state = D3D12_RESOURCE_STATES(state as i32); + // SAFETY: our swap chain, list and a live source texture. + unsafe { + let index = p.swap_chain.GetCurrentBackBufferIndex(); + let Ok(back) = p.swap_chain.GetBuffer::(index) else { + return None; + }; + // Sent ahead ([`late_free_present`]) unless the frame is to be + // read back at once (a saved or listed frame): then a list of + // its own, one whose last flight has finished or a new one. + #[cfg(feature = "diagnostics")] + let read_now = crate::capture::wanted(frame) || crate::capture::listed(frame); + #[cfg(not(feature = "diagnostics"))] + let read_now = false; + let slot = if late_free_present() && !read_now { + let finished = FINISHED.load(Ordering::Acquire); + p.ahead.iter().position(|(_, flown)| *flown <= finished).or_else(|| { + let list = self.new_list().ok()?; + list.close(); + p.ahead.push((list, 0)); + Some(p.ahead.len() - 1) + }) + } else { + None + }; + let copy = match slot { + Some(i) => &p.ahead[i].0, + None => &p.copy, + }; + copy.reset(); + let list = ©.list; + list.ResourceBarrier(&[ + transition(texture, state, D3D12_RESOURCE_STATE_COPY_SOURCE), + transition( + &back, + D3D12_RESOURCE_STATE_PRESENT, + D3D12_RESOURCE_STATE_COPY_DEST, + ), + ]); + list.CopyResource(&back, texture); + // The frame rate, into the corner of what is shown (not of the + // title's own frame, which the lines below read back). + crate::fpsbox::draw(self, list, &back, (width, height, format)); + #[cfg(feature = "diagnostics")] + let capture = crate::capture::wanted(frame) + .then(|| crate::capture::read_back(&self.device, list, texture)) + .flatten(); + #[cfg(feature = "diagnostics")] + let probe = if slot.is_some() { None } else { crate::capture::probe(&self.device, list, texture) }; + #[cfg(not(feature = "diagnostics"))] + let _ = frame; + list.ResourceBarrier(&[ + transition(texture, D3D12_RESOURCE_STATE_COPY_SOURCE, state), + transition( + &back, + D3D12_RESOURCE_STATE_COPY_DEST, + D3D12_RESOURCE_STATE_PRESENT, + ), + ]); + copy.close(); + match slot { + Some(i) => { + let flown = self.execute_own(copy); + p.ahead[i].1 = flown; + } + None => self.execute(&[copy]), + } + #[cfg(feature = "diagnostics")] + if let Some((buffer, footprint)) = capture { + crate::capture::save_read_back(frame, &buffer, &footprint); + } + let _ = p.swap_chain.Present(0, DXGI_PRESENT(0)); + p.meter.frame(p.hwnd); + #[cfg(feature = "diagnostics")] + return Some(probe.is_some_and(|b| crate::capture::black(&b))); + #[cfg(not(feature = "diagnostics"))] + Some(false) + } + } + + fn presenter( + &self, + width: u32, + height: u32, + format: DXGI_FORMAT, + ) -> windows::core::Result { + let hwnd = match title_window() { + Some(hwnd) => hwnd, + None => window(width, height)?, + }; + self.log_video_memory("right before the swap chain is made"); + // SAFETY: plain object creation for our window. + unsafe { + let factory: IDXGIFactory2 = CreateDXGIFactory2(DXGI_CREATE_FACTORY_FLAGS(0))?; + let desc = DXGI_SWAP_CHAIN_DESC1 { + Width: width, + Height: height, + Format: format, + SampleDesc: DXGI_SAMPLE_DESC { + Count: 1, + Quality: 0, + }, + BufferUsage: DXGI_USAGE_RENDER_TARGET_OUTPUT, + BufferCount: BUFFERS, + SwapEffect: DXGI_SWAP_EFFECT_FLIP_DISCARD, + ..Default::default() + }; + let swap_chain = factory + .CreateSwapChainForHwnd(&self.queue, hwnd, &desc, None, None)? + .cast::()?; + let copy = self.new_list()?; + copy.close(); + tracing::info!(width, height, format = format.0, "presenting to a window"); + self.log_video_memory("right after the swap chain is made"); + Ok(Presenter { + swap_chain, + width, + height, + format, + copy, + ahead: Vec::new(), + hwnd, + meter: Meter::new(), + }) + } + } +} + +/// A visible top-level window of this process: the one the title made, if +/// it made one. +fn title_window() -> Option { + extern "system" fn visit(hwnd: HWND, found: LPARAM) -> windows::core::BOOL { + let mut process = 0; + // SAFETY: a window handle from the enumeration; `found` is ours. + unsafe { + GetWindowThreadProcessId(hwnd, Some(&mut process)); + if process == windows::Win32::System::Threading::GetCurrentProcessId() + && IsWindowVisible(hwnd).as_bool() + { + *(found.0 as *mut Option) = Some(hwnd); + return false.into(); + } + } + true.into() + } + let mut found: Option = None; + // SAFETY: the callback only writes `found`, which outlives the call. + let _ = unsafe { EnumWindows(Some(visit), LPARAM(&raw mut found as isize)) }; + found +} + +/// `state` without the bits the host texture's flags forbid: the console +/// lets the title name states its own resources allow (unordered access on +/// a depth target, whose host copy cannot have both). +pub(crate) fn legal_state(texture: &ID3D12Resource, state: u32) -> u32 { + // SAFETY: a plain query. + legal_for(unsafe { texture.GetDesc() }.Flags.0 as u32, state) +} + +/// [`legal_state`] for a texture with resource flags `flags`. +pub(crate) fn legal_for(flags: u32, state: u32) -> u32 { + // (flag, set or clear forbids, state bits): render target, unordered + // access, depth, denied shader resource. + const FORBIDDEN: [(u32, bool, u32); 4] = [ + (0x1, false, 0x4), + (0x4, false, 0x8), + (0x2, false, 0x10 | 0x20), + (0x8, true, 0x40 | 0x80), + ]; + FORBIDDEN + .iter() + .filter(|&&(flag, deny, _)| (flags & flag != 0) == deny) + .fold(state, |s, &(_, _, bits)| s & !bits) +} + +impl Host { + /// The card's memory as the system accounts it to this process, in + /// bytes: the budget and the use of the card's own memory, then of the + /// PC's memory shared with the card (where the system moves what does + /// not fit on the card). + pub(crate) fn video_memory(&self) -> Option<[u64; 4]> { + let adapter = self.adapter.as_ref()?; + let mut own = DXGI_QUERY_VIDEO_MEMORY_INFO::default(); + let mut shared = DXGI_QUERY_VIDEO_MEMORY_INFO::default(); + // SAFETY: plain queries that fill our structures. + unsafe { + adapter + .QueryVideoMemoryInfo(0, DXGI_MEMORY_SEGMENT_GROUP_LOCAL, &mut own) + .ok()?; + adapter + .QueryVideoMemoryInfo(0, DXGI_MEMORY_SEGMENT_GROUP_NON_LOCAL, &mut shared) + .ok()?; + } + // The card's budget moved by 256 MB or more since the last look: + // said at once, with what was in use at the last look, so the log + // has the moment. (It fell from 11,242 MB to some 10,300 MB with + // the first world frame in runs 179 to 185, and the memory line, + // seconds later, was the first to show it. We reserve nothing + // and make the swap chain once, at the start.) + static LAST: [std::sync::atomic::AtomicU64; 3] = [const { std::sync::atomic::AtomicU64::new(0) }; 3]; + let now = [own.Budget, own.CurrentUsage, shared.CurrentUsage]; + let last = [0, 1, 2].map(|i| LAST[i].swap(now[i], Ordering::Relaxed)); + if last[0] != 0 && last[0].abs_diff(own.Budget) >= (256u64 << 20) { + tracing::info!( + "the system changed the budget of the card's memory from {} MB to {} MB (frame {}); at the last look {} MB of the card's and {} MB of the PC's shared memory were in use", + last[0] >> 20, + own.Budget >> 20, + crate::frame::current(), + last[1] >> 20, + last[2] >> 20 + ); + self.log_video_memory("right after that change"); + } + Some([own.Budget, own.CurrentUsage, shared.Budget, shared.CurrentUsage]) + } + + /// Both of the system's memory groups for this process, in bytes: for + /// the card's own memory and then for the PC's memory shared with the + /// card, the budget, the use, what could still be reserved and what + /// is reserved (the layer reserves none). + pub(crate) fn video_memory_groups(&self) -> Option<[[u64; 4]; 2]> { + let adapter = self.adapter.as_ref()?; + let mut own = DXGI_QUERY_VIDEO_MEMORY_INFO::default(); + let mut shared = DXGI_QUERY_VIDEO_MEMORY_INFO::default(); + // SAFETY: plain queries that fill our structures. + unsafe { + adapter + .QueryVideoMemoryInfo(0, DXGI_MEMORY_SEGMENT_GROUP_LOCAL, &mut own) + .ok()?; + adapter + .QueryVideoMemoryInfo(0, DXGI_MEMORY_SEGMENT_GROUP_NON_LOCAL, &mut shared) + .ok()?; + } + let all = |m: &DXGI_QUERY_VIDEO_MEMORY_INFO| { + [m.Budget, m.CurrentUsage, m.AvailableForReservation, m.CurrentReservation] + }; + Some([all(&own), all(&shared)]) + } + + /// Logs [`Self::video_memory_groups`], with `when` it is said. + pub(crate) fn log_video_memory(&self, when: &str) { + let Some([own, shared]) = self.video_memory_groups() else { + return; + }; + tracing::info!( + "video memory as the system counts it, {}: the card's own: budget {} MB, in use {} MB, {} MB could still be reserved, {} MB reserved; the PC's shared with the card: budget {} MB, in use {} MB, {} MB could still be reserved, {} MB reserved (the layer reserves none)", + when, + own[0] >> 20, + own[1] >> 20, + own[2] >> 20, + own[3] >> 20, + shared[0] >> 20, + shared[1] >> 20, + shared[2] >> 20, + shared[3] >> 20 + ); + } + + /// A buffer in system memory that the CPU maps (write-back, so reading + /// it is fast too) and shaders read and write: for host copies of title + /// memory that shaders write, which upload memory cannot be. Starts in + /// the common state (buffers move out of it implicitly). + pub(crate) fn shared_buffer(&self, size: u64) -> Option<(ID3D12Resource, *mut u8)> { + MADE[2].fetch_add(1, Ordering::Relaxed); + MADE[3].fetch_add(size, Ordering::Relaxed); + let heap = D3D12_HEAP_PROPERTIES { + Type: D3D12_HEAP_TYPE_CUSTOM, + CPUPageProperty: D3D12_CPU_PAGE_PROPERTY_WRITE_BACK, + MemoryPoolPreference: D3D12_MEMORY_POOL_L0, + ..Default::default() + }; + let desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, + Width: size.max(1), + Height: 1, + DepthOrArraySize: 1, + MipLevels: 1, + SampleDesc: DXGI_SAMPLE_DESC { + Count: 1, + Quality: 0, + }, + Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, + Flags: D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS, + ..Default::default() + }; + let mut buffer: Option = None; + let mut data = std::ptr::null_mut(); + // SAFETY: plain creation and mapping of a CPU-visible buffer. + let made = unsafe { + self.device + .CreateCommittedResource( + &heap, + D3D12_HEAP_FLAG_NONE, + &desc, + D3D12_RESOURCE_STATE_COMMON, + None, + &mut buffer, + ) + .and_then(|()| { + let b = buffer.as_ref().ok_or_else(windows::core::Error::empty)?; + b.Map(0, None, Some(&mut data)) + }) + }; + match made { + Ok(()) => Some((buffer?, data.cast())), + Err(e) => { + tracing::warn!(error = %e, size, "no shared buffer"); + None + } + } + } + + /// A device-local buffer shaders may write (unordered access) and indirect + /// execution may read, starting in the common state. + pub(crate) fn uav_buffer(&self, size: u64) -> Option { + MADE[4].fetch_add(1, Ordering::Relaxed); + MADE[5].fetch_add(size, Ordering::Relaxed); + let heap = D3D12_HEAP_PROPERTIES { + Type: D3D12_HEAP_TYPE_DEFAULT, + ..Default::default() + }; + let desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, + Width: size.max(1), + Height: 1, + DepthOrArraySize: 1, + MipLevels: 1, + SampleDesc: DXGI_SAMPLE_DESC { + Count: 1, + Quality: 0, + }, + Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, + Flags: D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS, + ..Default::default() + }; + let mut buffer: Option = None; + // SAFETY: plain creation of a device-local buffer. + let made = unsafe { + self.device.CreateCommittedResource( + &heap, + D3D12_HEAP_FLAG_NONE, + &desc, + D3D12_RESOURCE_STATE_COMMON, + None, + &mut buffer, + ) + }; + match made { + Ok(()) => buffer, + Err(e) => { + tracing::warn!(error = %e, size, "no unordered-access buffer"); + None + } + } + } +} + +/// For adapters without device-removed data (the software one): the last +/// commands each list of the failed submission noted (diagnostics, with +/// `LEONIDA_D3D12_DRED`). +fn last_notes(runs: &[&HostList]) -> String { + #[cfg(feature = "diagnostics")] + { + let mut text = String::new(); + for (i, r) in runs.iter().enumerate() { + let notes = r.notes.lock().unwrap_or_else(|e| e.into_inner()); + for (n, _) in notes.iter().rev().take(6).rev() { + text.push_str(&format!("; list {i} of {}, of its {}: {n}", runs.len(), notes.len())); + } + } + text + } + #[cfg(not(feature = "diagnostics"))] + { + let _ = runs; + String::new() + } +} + +/// Where the faulting address `va` lies against a range `(start, bytes)` a +/// command reads (diagnostics). +#[cfg(feature = "diagnostics")] +fn fault_in(va: u64, (start, bytes): (u64, u64)) -> String { + let end = start + bytes; + if va < start { + format!(" (fault {:#x} below its source)", start - va) + } else if va < end { + format!(" (fault at source +{:#x})", va - start) + } else { + format!(" (fault {:#x} past its source's end)", va - end) + } +} + +/// The commands that may have been running where a list stopped at +/// command `done`: those between the barriers around it (work between +/// barriers overlaps on the GPU), by kind, and what the markers just +/// before them say (`HostList::note_op`: diagnostics builds with +/// device-removed data on). +fn in_flight(history: &[D3D12_AUTO_BREADCRUMB_OP], markers: &[(u32, String)], done: usize) -> String { + let barrier = |op: &D3D12_AUTO_BREADCRUMB_OP| *op == D3D12_AUTO_BREADCRUMB_OP_RESOURCEBARRIER; + let from = history[..done].iter().rposition(barrier).map_or(0, |b| b + 1); + let to = history[done..] + .iter() + .position(barrier) + .map_or(history.len(), |b| (done + b).max(done + 1)); + let mut text = format!(", commands {from}..{to} between its barriers:"); + let mut shown = 0; + // From just before the command the GPU had not finished: the first + // twelve after the barrier named draws long done when a list of 79 + // mesh draws stopped at its 45th (run 41). + for i in from.max(done.saturating_sub(4))..to { + let op = history[i]; + if op == D3D12_AUTO_BREADCRUMB_OP_SETMARKER || shown == 12 { + continue; + } + shown += 1; + let marker = i + .checked_sub(1) + .filter(|&m| history[m] == D3D12_AUTO_BREADCRUMB_OP_SETMARKER) + .and_then(|m| markers.iter().find(|(at, _)| *at as usize == m)) + .map_or("no marker", |(_, s)| s.as_str()); + text.push_str(&format!("; command {i} (op {}): {marker}", op.0)); + } + text +} + +pub(crate) fn transition( + resource: &ID3D12Resource, + before: D3D12_RESOURCE_STATES, + after: D3D12_RESOURCE_STATES, +) -> D3D12_RESOURCE_BARRIER { + D3D12_RESOURCE_BARRIER { + Type: D3D12_RESOURCE_BARRIER_TYPE_TRANSITION, + Flags: D3D12_RESOURCE_BARRIER_FLAG_NONE, + Anonymous: D3D12_RESOURCE_BARRIER_0 { + Transition: std::mem::ManuallyDrop::new(D3D12_RESOURCE_TRANSITION_BARRIER { + // SAFETY: a borrowed pointer; the barrier never releases it. + pResource: unsafe { std::mem::transmute_copy(resource) }, + Subresource: D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES, + StateBefore: before, + StateAfter: after, + }), + }, + } +} + +/// A window of the given client size, owned by its own message thread. +fn window(width: u32, height: u32) -> windows::core::Result { + let (sender, receiver) = std::sync::mpsc::channel(); + std::thread::Builder::new() + .name("leonida-window".into()) + .spawn(move || { + let made = make_window(width, height); + let ok = made.is_ok(); + let _ = sender.send(made.map(|h| h.0 as usize)); + if ok { + pump(); + } + }) + .map_err(|_| windows::core::Error::empty())?; + let hwnd = receiver + .recv() + .map_err(|_| windows::core::Error::empty())??; + Ok(HWND(hwnd as *mut _)) +} + +extern "system" fn window_proc( + hwnd: HWND, + message: u32, + wparam: WPARAM, + lparam: LPARAM, +) -> LRESULT { + // SAFETY: the default handling for our window. + unsafe { DefWindowProcW(hwnd, message, wparam, lparam) } +} + +fn make_window(width: u32, height: u32) -> windows::core::Result { + const CLASS: PCWSTR = w!("Leonida Legacy"); + // SAFETY: registers our class once and creates a window of it. + unsafe { + let instance = GetModuleHandleW(None)?; + let class = WNDCLASSEXW { + cbSize: size_of::() as u32, + lpfnWndProc: Some(window_proc), + hInstance: instance.into(), + lpszClassName: CLASS, + hCursor: LoadCursorW(None, IDC_ARROW)?, + ..Default::default() + }; + RegisterClassExW(&class); + let mut rect = RECT { + left: 0, + top: 0, + right: width as i32, + bottom: height as i32, + }; + AdjustWindowRect(&mut rect, WS_OVERLAPPEDWINDOW, false)?; + CreateWindowExW( + WINDOW_EX_STYLE(0), + CLASS, + w!("Leonida Legacy"), + WS_OVERLAPPEDWINDOW | WS_VISIBLE, + CW_USEDEFAULT, + CW_USEDEFAULT, + rect.right - rect.left, + rect.bottom - rect.top, + None, + None, + Some(instance.into()), + None, + ) + } +} + +fn pump() { + let mut message = MSG::default(); + // SAFETY: the standard message loop of this thread's window. + unsafe { + while GetMessageW(&mut message, None, 0, 0).as_bool() { + let _ = TranslateMessage(&message); + DispatchMessageW(&message); + } + } +} + +#[cfg(test)] +mod trail { + /// The trail keeps the newest things, and the report made when the + /// host device is removed says them and the pipeline library's state + /// (no card is asked for any of it). + #[test] + fn the_removal_report_says_the_newest_things_done() { + for n in 0..super::TRAIL_MOST + 5 { + super::trail(|| format!("thing {n} done")); + } + let text = super::removal_context(); + assert!(text.contains("the submitting thread was")); + assert!(text.contains("pipeline library: no call running")); + assert!(text.contains(&format!("thing {} done", super::TRAIL_MOST + 4))); + assert!(!text.contains("thing 4 done"), "the oldest entries are dropped"); + } +} + +#[cfg(test)] +mod spare { + use super::Spare; + + /// Kept things come back by size, the last given first, and nothing is + /// kept past the limit. + #[test] + fn kept_things_come_back_by_size_within_the_limit() { + let mut spare: Spare = Spare::new(); + assert_eq!(spare.take(4), None); + assert_eq!(spare.give(1, 4, 10), None); + assert_eq!(spare.give(2, 1, 10), None); + assert_eq!(spare.give(3, 4, 10), None); + assert_eq!(spare.bytes, 9); + // Past the limit: handed back, nothing changes. + assert_eq!(spare.give(4, 4, 10), Some(4)); + assert_eq!(spare.bytes, 9); + assert_eq!(spare.take(2), None, "no thing of that size"); + assert_eq!(spare.take(4), Some(3)); + assert_eq!(spare.take(4), Some(1)); + assert_eq!(spare.take(4), None); + assert_eq!(spare.take(1), Some(2)); + assert_eq!(spare.bytes, 0); + assert!(spare.kept.is_empty()); + } +} + +#[cfg(test)] +mod batch { // Batch::texture_due lives here; `mod tests` is already taken at the top of this file + use super::Batch; + use std::sync::Arc; + + #[test] + fn a_texture_is_checked_once_per_submission() { + let mut batch = Batch::default(); + let (a, b) = (Arc::new([0u8; 16]), Arc::new([0u8; 16])); + // The first list sampling each texture checks it ... + assert!(batch.texture_due(&a)); + assert!(batch.texture_due(&b)); + // ... later lists of the same submission do not. + assert!(!batch.texture_due(&a)); + assert!(!batch.texture_due(&a.clone())); + assert!(!batch.texture_due(&b)); + } + + #[test] + fn title_writes_make_textures_due_again() { + let mut batch = Batch::default(); + let a = Arc::new(1u32); + assert!(batch.texture_due(&a)); + assert!(!batch.texture_due(&a)); + // A copy into title memory or work that may write it may have + // changed the texture's memory. + batch.title_written(); + assert!(batch.texture_due(&a)); + assert!(!batch.texture_due(&a)); + // A fresh submission starts over. + let mut next = Batch::default(); + assert!(next.texture_due(&a)); + } + + /// The hashing a submission does for textures in physical-page memory, + /// with every list checking the textures it samples (before) and with + /// each checked once (after). Run with + /// `cargo test --release -p leonida-gpu -- --ignored --nocapture texture_checks`. + #[test] + #[ignore = "benchmark"] + fn texture_checks_per_submission() { + const TEXTURES: usize = 48; + const SIZE: usize = 4 << 20; + const LISTS: usize = 12; + let textures: Vec>> = (0..TEXTURES) + .map(|t| Arc::new((0..SIZE).map(|i| (i * 31 + t) as u8).collect())) + .collect(); + let submit = |dedupe: bool| { + let mut batch = Batch::default(); + let mut hashed = 0usize; + let started = std::time::Instant::now(); + for _ in 0..LISTS { + for t in &textures { + if !dedupe || batch.texture_due(t) { + std::hint::black_box(blake3::hash(t)); + hashed += 1; + } + } + } + (started.elapsed(), hashed) + }; + submit(false); // warm up + let (before, n_before) = submit(false); + let (after, n_after) = submit(true); + assert_eq!((n_before, n_after), (TEXTURES * LISTS, TEXTURES)); + println!( + "{LISTS} lists sampling {TEXTURES} textures of {} MiB: \ + before {n_before} hashes in {before:?}, after {n_after} in {after:?} ({:.1}x)", + SIZE >> 20, + before.as_secs_f64() / after.as_secs_f64() + ); + } + + #[test] + fn vram_idle_ms_scales_with_pressure() { + use super::vram_idle_ms; + let gib = 1024 * 1024 * 1024; + // Normal (< 75%) + assert_eq!(vram_idle_ms(Some([10 * gib, 0, 0, 0])), 5_000); + assert_eq!(vram_idle_ms(Some([10 * gib, 7 * gib, 0, 0])), 5_000); + assert_eq!(vram_idle_ms(Some([100, 74, 0, 0])), 5_000); + // Moderate (75%..85%) + assert_eq!(vram_idle_ms(Some([100, 75, 0, 0])), 2_500); + assert_eq!(vram_idle_ms(Some([100, 84, 0, 0])), 2_500); + // High (>= 85%, including over-budget) + assert_eq!(vram_idle_ms(Some([100, 85, 0, 0])), 1_000); + assert_eq!(vram_idle_ms(Some([10 * gib, 12 * gib, 0, 0])), 1_000); + // Missing or zero budget falls back to normal + assert_eq!(vram_idle_ms(None), 5_000); + assert_eq!(vram_idle_ms(Some([0, 100, 0, 0])), 5_000); + } + + #[test] + fn ram_idle_ms_scales_with_pressure() { + use super::ram_idle_ms; + let gib = 1024 * 1024 * 1024; + // Normal (>= 4 GiB) + assert_eq!(ram_idle_ms(Some(8 * gib)), 10_000); + assert_eq!(ram_idle_ms(Some(4 * gib)), 10_000); + // Moderate (2 GiB..4 GiB) + assert_eq!(ram_idle_ms(Some(4 * gib - 1)), 5_000); + assert_eq!(ram_idle_ms(Some(2 * gib)), 5_000); + // High (< 2 GiB) + assert_eq!(ram_idle_ms(Some(2 * gib - 1)), 2_000); + assert_eq!(ram_idle_ms(Some(0)), 2_000); + // Missing falls back to normal + assert_eq!(ram_idle_ms(None), 10_000); + } +} + +/// The host's own paths for a copy in the card's memory, end to end, on +/// the software adapter only: the title's bytes go up, a shader reads them +/// and writes, and what it wrote comes back into title memory. Run it with +/// the switches under test in the environment (they are read once per +/// process); it does nothing unless the host device is the software +/// adapter (`LEONIDA_D3D12_WARP=1` in a diagnostics build) and the copy is +/// in the card's memory (`LEONIDA_CARD_BUFFERS_MIN_MB=1`): +/// +/// `LEONIDA_D3D12_WARP=1 LEONIDA_CARD_BUFFERS_MIN_MB=1 [LEONIDA_QUEUE2=n] +/// [LEONIDA_RELAY=2 | LEONIDA_LATE_WAIT=3] cargo test -p leonida-gpu +/// --features diagnostics queue2_tests` +/// +/// The same title memory must come out whatever the switches: through the +/// direct queue alone, and through the copy queues. +#[cfg(test)] +mod queue2_tests { + use super::*; + + /// `memory[to] = memory[from] + add`, after `spin` steps. + const ADD: &str = r#" +#define RS "RootConstants(num32BitConstants=4, b0), UAV(u0)" +cbuffer What : register(b0) { uint to; uint from; uint add; uint spin; }; +RWByteAddressBuffer memory : register(u0); +[RootSignature(RS)] +[numthreads(1, 1, 1)] +void main() { + uint h = 0u; + [loop] + for (uint i = 0u; i < spin; i++) { + h = (h ^ memory.Load(from)) * 0x01000193u; + } + memory.Store(to, memory.Load(from) + add + (h & 0u)); +} +"#; + + #[test] + fn warp_title_bytes_go_up_and_shader_writes_come_back_whatever_the_queues() { + use windows_sys::Win32::System::Memory::{MEM_COMMIT, MEM_RESERVE, PAGE_READWRITE, VirtualAlloc}; + const MEM_WRITE_WATCH: u32 = 0x0020_0000; + let Some(host) = host() else { + return; + }; + // Never on a real card. + // SAFETY: a plain query. + let software = host + .adapter + .as_ref() + .and_then(|a| unsafe { a.GetDesc1() }.ok()) + .is_some_and(|d| d.Flags & DXGI_ADAPTER_FLAG_SOFTWARE.0 as u32 != 0); + if !software { + eprintln!("queue2_tests: skipped, the host device is not the software adapter (LEONIDA_D3D12_WARP=1, diagnostics)"); + return; + } + const PIECE: usize = 64 << 10; + const LEN: usize = 4 << 20; + const ROUNDS: usize = 12; + // "Title memory": write-watched, as the title's is. + // SAFETY: a plain allocation of our own. + let title = unsafe { VirtualAlloc(std::ptr::null(), LEN, MEM_RESERVE | MEM_COMMIT | MEM_WRITE_WATCH, PAGE_READWRITE) } as *mut u8; + assert!(!title.is_null()); + let dword = |at: usize| unsafe { title.add(at).cast::() }; + for i in 0..LEN / 4 { + // SAFETY: inside the allocation. + unsafe { dword(i * 4).write_volatile(0x5A00_0000 | i as u32) }; + } + crate::shadow::register(0x51_5151, title as u64, LEN as u64); + let shadow = crate::shadow::find(title as u64, LEN as u64).expect("a host copy"); + if !shadow.carded() { + eprintln!("queue2_tests: skipped, the copy is not in the card's memory (LEONIDA_CARD_BUFFERS_MIN_MB=1)"); + return; + } + let code = compile(ADD, windows::core::s!("main"), windows::core::s!("cs_5_1")).expect("the test's shader"); + // SAFETY: the shader's own root signature; plain creation. + let (root, pso): (ID3D12RootSignature, ID3D12PipelineState) = unsafe { + let root: ID3D12RootSignature = host.device.CreateRootSignature(0, &code).expect("a root signature"); + let pso = host + .device + .CreateComputePipelineState(&D3D12_COMPUTE_PIPELINE_STATE_DESC { + pRootSignature: std::mem::transmute_copy(&root), + CS: D3D12_SHADER_BYTECODE { + pShaderBytecode: code.as_ptr().cast(), + BytecodeLength: code.len(), + }, + ..Default::default() + }) + .expect("a pipeline"); + (root, pso) + }; + // Round k: the title writes a dword in piece 1+k; a submission's + // shader adds k to it and stores the sum in piece 30+k, a range + // declared as shader-written. Nothing is waited for between the + // rounds where submissions are sent ahead. + let from = |k: usize| (1 + k) * PIECE + 4 * k + 64; + let to = |k: usize| (30 + k) * PIECE + 8 * k + 128; + let titles = |k: usize| 0x0100_0000 + 0x1000 * k as u32 + 7; + let mut lists = Vec::new(); + for k in 0..ROUNDS { + // SAFETY: inside the allocation. + unsafe { dword(from(k)).write_volatile(titles(k)) }; + let list = host.new_list().expect("a host list"); + shadow.refresh(&list, title as u64, LEN as u64); + shadow.gpu_writes(&list, (title as usize + (30 + k) * PIECE) as u64, PIECE as u64); + // SAFETY: an open list; the copy's buffer, with unordered + // access; the shader's own root signature. + unsafe { + list.list.SetComputeRootSignature(&root); + list.list.SetPipelineState(&pso); + let constants = [to(k) as u32, from(k) as u32, k as u32, 30_000]; + list.list.SetComputeRoot32BitConstants(0, 4, constants.as_ptr().cast(), 0); + list.list.SetComputeRootUnorderedAccessView(1, shadow.buffer.GetGPUVirtualAddress()); + list.list.Dispatch(1, 1, 1); + } + list.close(); + if late() { + host.execute_own(&list); + } else { + host.execute(&[&list]); + } + lists.push(list); + } + settle_now(WHY_SYNC); + for k in 0..ROUNDS { + // SAFETY: inside the allocation. + let (sum, kept) = unsafe { (dword(to(k)).read_volatile(), dword(from(k)).read_volatile()) }; + assert_eq!(kept, titles(k), "round {k}: the title's own dword changed"); + assert_eq!( + sum, + titles(k) + k as u32, + "round {k}: the shader read {:#x} where the title had written {:#x}, or its write did not come back", + sum.wrapping_sub(k as u32), + titles(k) + ); + } + // Nothing else moved. + let touched: std::collections::HashSet = (0..ROUNDS).flat_map(|k| [from(k), to(k)]).collect(); + for i in (0..LEN / 4).filter(|i| !touched.contains(&(i * 4))) { + // SAFETY: inside the allocation. + let got = unsafe { dword(i * 4).read_volatile() }; + assert_eq!(got, 0x5A00_0000 | i as u32, "dword {i} of title memory changed"); + } + // The queues the switches name did the work. + if let Some(second) = crate::queue2::second() { + let (down, up) = (second.down.stats.jobs.load(Ordering::Relaxed), second.up.stats.jobs.load(Ordering::Relaxed)); + // (Sends that found no landing buffer went the old way.) + let no_room = second.landing[1].load(Ordering::Relaxed); + eprintln!( + "queue2_tests: LEONIDA_QUEUE2={} late {} relay {}: {down} fetches and {up} sends through the copy queues ({no_room} more found no landing buffer), the direct queue told to wait {} times", + crate::queue2::bits(), + late(), + relay(), + second.held[0].load(Ordering::Relaxed) + ); + assert_eq!(down > 0, second.fetches(), "fetches through the copy queue"); + assert_eq!(up + no_room > 0, second.uploads(), "sends through the copy queue"); + assert_eq!(up, second.held[0].load(Ordering::Relaxed), "the direct queue waits for every send"); + } else { + eprintln!("queue2_tests: the direct queue alone (late {}, relay {})", late(), relay()); + } + drop(lists); + } + + /// `memory[to] = first` at once; then `spin` steps, each a store to + /// `memory[to + 4]`; then `memory[to + 4] = 0` and `memory[to] = last`. + /// Whatever `spin` is, the bytes it leaves are the same. + const TWICE: &str = r#" +#define RS "RootConstants(num32BitConstants=4, b0), UAV(u0)" +cbuffer What : register(b0) { uint to; uint first; uint last; uint spin; }; +RWByteAddressBuffer memory : register(u0); +[RootSignature(RS)] +[numthreads(1, 1, 1)] +void main() { + memory.Store(to, first); + [loop] + for (uint i = 0u; i < spin; i++) { + memory.Store(to + 4u, i); + } + memory.Store(to + 4u, 0u); + memory.Store(to, last); +} +"#; + + /// The hole a fetch on the copy queue had (`LEONIDA_QUEUE2` bit 1 with + /// the relay): flight A writes a piece; flight B, sent behind it, + /// writes the same piece through a half-way value and leaves it as A + /// left it. A is landed while B is half way: the fetch, beside B on + /// the copy queue, brings B's half-way bytes into title memory. B's + /// compare finds the piece as A's compare left it and flags nothing, + /// so B's landing fetched nothing and title memory kept the half-way + /// bytes. With the fix B's landing fetches the piece all the same + /// (`BESIDE`). + /// + /// `LEONIDA_D3D12_WARP=1 LEONIDA_CARD_BUFFERS_MIN_MB=1 LEONIDA_QUEUE2=1 + /// LEONIDA_RELAY=1 cargo test -p leonida-gpu --features diagnostics + /// fetched_again -- --nocapture` (alone: it lands its two flights + /// itself; `LEONIDA_QUEUE2_REFETCH=0` shows the fault). + #[test] + fn warp_a_piece_fetched_while_a_later_flight_writes_it_is_fetched_again() { + use windows_sys::Win32::System::Memory::{MEM_COMMIT, MEM_RESERVE, PAGE_READWRITE, VirtualAlloc}; + const MEM_WRITE_WATCH: u32 = 0x0020_0000; + let Some(host) = host() else { + return; + }; + // Never on a real card. + // SAFETY: a plain query. + let software = host + .adapter + .as_ref() + .and_then(|a| unsafe { a.GetDesc1() }.ok()) + .is_some_and(|d| d.Flags & DXGI_ADAPTER_FLAG_SOFTWARE.0 as u32 != 0); + if !software { + eprintln!("queue2_tests: skipped, the host device is not the software adapter (LEONIDA_D3D12_WARP=1, diagnostics)"); + return; + } + if !relay() || !crate::queue2::second().is_some_and(|s| s.fetches()) { + eprintln!("queue2_tests: skipped, fetches do not go to a copy queue beside the relay (LEONIDA_RELAY=1 LEONIDA_QUEUE2=1)"); + return; + } + const PIECE: usize = 64 << 10; + const LEN: usize = 4 << 20; + // SAFETY: a plain allocation of our own. + let title = unsafe { VirtualAlloc(std::ptr::null(), LEN, MEM_RESERVE | MEM_COMMIT | MEM_WRITE_WATCH, PAGE_READWRITE) } as *mut u8; + assert!(!title.is_null()); + let dword = |at: usize| unsafe { title.add(at).cast::() }; + for i in 0..LEN / 4 { + // SAFETY: inside the allocation. + unsafe { dword(i * 4).write_volatile(0x5A00_0000 | i as u32) }; + } + crate::shadow::register(0x52_5252, title as u64, LEN as u64); + let shadow = crate::shadow::find(title as u64, LEN as u64).expect("a host copy"); + if !shadow.carded() { + eprintln!("queue2_tests: skipped, the copy is not in the card's memory (LEONIDA_CARD_BUFFERS_MIN_MB=1)"); + return; + } + let code = compile(TWICE, windows::core::s!("main"), windows::core::s!("cs_5_1")).expect("the test's shader"); + // SAFETY: the shader's own root signature; plain creation. + let (root, pso): (ID3D12RootSignature, ID3D12PipelineState) = unsafe { + let root: ID3D12RootSignature = host.device.CreateRootSignature(0, &code).expect("a root signature"); + let pso = host + .device + .CreateComputePipelineState(&D3D12_COMPUTE_PIPELINE_STATE_DESC { + pRootSignature: std::mem::transmute_copy(&root), + CS: D3D12_SHADER_BYTECODE { + pShaderBytecode: code.as_ptr().cast(), + BytecodeLength: code.len(), + }, + ..Default::default() + }) + .expect("a pipeline"); + (root, pso) + }; + // A list whose shader writes the dword at 256 of `piece`, declared. + let record = |piece: usize, first: u32, last: u32, spin: u32| { + let list = host.new_list().expect("a host list"); + shadow.refresh(&list, title as u64, LEN as u64); + shadow.gpu_writes(&list, (title as usize + piece * PIECE) as u64, PIECE as u64); + // SAFETY: an open list; the copy's buffer, with unordered + // access; the shader's own root signature. + unsafe { + list.list.SetComputeRootSignature(&root); + list.list.SetPipelineState(&pso); + let constants = [(piece * PIECE + 256) as u32, first, last, spin]; + list.list.SetComputeRoot32BitConstants(0, 4, constants.as_ptr().cast(), 0); + list.list.SetComputeRootUnorderedAccessView(1, shadow.buffer.GetGPUVirtualAddress()); + list.list.Dispatch(1, 1, 1); + } + list.close(); + list + }; + // SAFETY: a plain query. + let completed = || unsafe { host.fence.GetCompletedValue() }; + let wait_for = |value: u64| { + while completed() < value { + std::thread::sleep(std::time::Duration::from_millis(1)); + } + }; + // How many steps keep the card busy for some seconds: timed on + // another piece, waited for. + const TRIAL: u32 = 1 << 20; + let trial = record(40, 1, 2, TRIAL); + let timing = std::time::Instant::now(); + host.execute(&[&trial]); + let took = timing.elapsed().as_secs_f64().max(1e-4); + let spin = (f64::from(TRIAL) * 3.0 / took).clamp(f64::from(TRIAL), 2.0e9) as u32; + // SAFETY: inside the allocation. + assert_eq!(unsafe { dword(40 * PIECE + 256).read_volatile() }, 2, "the trial's write did not come back"); + const AT: usize = 20 * PIECE + 256; + const HALF_WAY: u32 = 0xDEAD_0001; + const LEFT: u32 = 0x600D_0002; + // Flight A, and the card has run it. + let a = record(20, HALF_WAY, LEFT, 16); + let (submitted, mut sent_a) = host.submit(&[&a], true).expect("flight A sent ahead"); + let fence_a = *submitted; + drop(submitted); + wait_for(fence_a); + // Flight B: the same piece, through the half-way value, for seconds. + let b = record(20, HALF_WAY, LEFT, spin); + let (submitted, mut sent_b) = host.submit(&[&b], true).expect("flight B sent ahead"); + let fence_b = *submitted; + drop(submitted); + std::thread::sleep(std::time::Duration::from_millis(300)); + assert!( + completed() < fence_b, + "flight B had run after 0.3 s ({spin} steps; the trial's {TRIAL} took {took:.3} s): nothing to show" + ); + // A lands, as `Host::relay_land` lands it, while B is half way. + let mut fetch = None; + { + let plan = sent_a.card.as_ref().expect("flight A has a plan for the card's copies"); + host.relay_card_back(&[(sent_a.number, plan)], &mut fetch, fence_a, sent_a.number); + } + for (copy, ranges) in &sent_a.back { + copy.copy_back_done(ranges); + } + // SAFETY: inside the allocation. + let seen = unsafe { dword(AT).read_volatile() }; + let b_ran = completed() >= fence_b; + eprintln!( + "queue2_tests: after A's landing title memory holds {seen:#x} (half way {HALF_WAY:#x}, left {LEFT:#x}); B had run: {b_ran}; {spin} steps" + ); + assert_eq!( + seen, HALF_WAY, + "the fetch for A did not come down beside B (it waited for B, or B had not begun): this machine cannot show the fault" + ); + // B has run; it left the piece as A left it, so its compare flags + // nothing. Its landing must bring the piece down all the same. + wait_for(fence_b); + { + let plan = sent_b.card.as_ref().expect("flight B has a plan for the card's copies"); + host.relay_card_back(&[(sent_b.number, plan)], &mut fetch, fence_b, sent_b.number); + } + for (copy, ranges) in &sent_b.back { + copy.copy_back_done(ranges); + } + // SAFETY: inside the allocation. + let (left, beside) = unsafe { (dword(AT).read_volatile(), dword(AT + 4).read_volatile()) }; + assert_eq!( + left, LEFT, + "title memory kept flight B's half-way bytes: B's compare found the piece as A left it and B's landing fetched nothing" + ); + assert_eq!(beside, 0, "the dword beside it holds a half-way count"); + for sent in [&mut sent_a, &mut sent_b] { + if let Some(plan) = sent.card.take() { + host.card_done(plan); + } + } + drop((a, b, trial)); + } +} diff --git a/crates/leonida-gpu/src/indirect.rs b/crates/leonida-gpu/src/indirect.rs new file mode 100644 index 000000000..a3235334a --- /dev/null +++ b/crates/leonida-gpu/src/indirect.rs @@ -0,0 +1,2948 @@ +//! Indirect execution's arguments, bounded before the GPU reads them. The +//! title's own compute passes write most of them; a pass we drop or +//! translate wrongly leaves whatever the memory held, and a draw of four +//! billion vertices or a dispatch past the host's limits runs until the +//! host resets the display driver. So active records are copied and clamped +//! on the GPU into a device-local scratch buffer, just before execution, by a +//! compute shader of ours (HLSL compiled by the system's compiler; a 5.1 +//! shader with its root signature inside), leaving the title's argument and +//! count buffers untouched. +//! +//! The scratch buffer is left readable as indirect arguments after a clamp +//! and stays so until the next clamp into it, which moves it straight back +//! to unordered access; it goes back to the common state once, when the +//! list closes. The executions that read it record no barrier of their +//! own, so draws that read records clamped together (`crate::draw`'s +//! windows) follow each other with nothing between them. Before, each +//! execution was followed by a move of the scratch buffer back to the +//! common state, which drivers may treat as a full wait. +//! +//! When a count buffer is given, threads at or past `min(max, count)` return +//! immediately without charging the list's budget or reading uninitialized +//! tail slots. Each list has a budget (2^27 vertex instances or threads, +//! groups counted as 64 threads, mesh groups as 128): active records past it +//! run empty, saturating without 32-bit wraparound so a list of thousands of +//! garbage records cannot run for seconds either. +//! +//! shortcut: the bounds (2^24 vertices, 2^26 vertex instances, 65,535 +//! groups per dimension and 2^20 per dispatch, one-dimensional mesh +//! dispatches, the budget) cut legitimate work beyond them; raise them if +//! the title needs more. + +use windows::Win32::Graphics::Direct3D::Fxc::D3DCompile; +use windows::Win32::Graphics::Direct3D::ID3DBlob; +use windows::Win32::Graphics::Direct3D12::*; +use windows::core::s; + +use crate::host::{HostList, host, transition}; + +const SOURCE: &str = r#" +#define RS "RootConstants(num32BitConstants=6, b0), SRV(t0), SRV(t1), UAV(u0), UAV(u1)" +cbuffer Record : register(b0) { + uint kind; + uint stride; + uint records; + uint args_offset; + // Bit 0: a count buffer bounds the records. Bit 1: the records are a + // window clamped ahead of their draws: one that asks for more than can + // run is left empty and costs nothing. Bit 2: the records are gathered + // (`gather`): record i lies in the source where word i of the table + // behind `count_buf` says (from `count_offset` on), and goes to slot i. + uint has_count; + uint count_offset; +}; +ByteAddressBuffer src_args : register(t0); +ByteAddressBuffer count_buf : register(t1); +RWByteAddressBuffer dst_args : register(u0); +// The list's work so far (vertex instances, threads): past the budget, +// records run empty. +RWByteAddressBuffer budget : register(u1); +static const uint BUDGET = 1u << 27; +// The vertices or indices an instance from which a draw record runs empty. +static const uint MOST_DRAW = 1u << 23; +// Groups of one dispatch; more run empty. +static const uint GROUPS = 1u << 20; +// Each group charges the budget once: the costs of its records go here, +// one thread charges their sum, saturating as each record would in lane +// order, and every thread then reads whether its own record fitted. A +// compare and swap per record, 64 threads racing for one word, cost a +// round for each record of a window, and in memory the CPU maps (where the +// budget was, and is with LEONIDA_INDIRECT_CARD_BUDGET=0) every atomic +// crosses the bus on a card of its own. +groupshared uint costs[64]; +groupshared uint fits[64]; +groupshared uint largest_asked; +groupshared uint all_asked; +[RootSignature(RS)] +[numthreads(64, 1, 1)] +void main(uint3 id : SV_DispatchThreadID, uint gi : SV_GroupIndex) { + uint eff_count = records; + bool ahead = (has_count & 2u) != 0; + if ((has_count & 1u) != 0) { + eff_count = min(eff_count, count_buf.Load(count_offset)); + } + // Threads past the records take part in the group's charge (cost 0) + // and store nothing. + bool active = id.x < eff_count; + uint src_at = args_offset + id.x * stride; + // (A branch, not a select: without the bit the view behind `count_buf` + // is a count of four bytes, or the source itself, and is not read here.) + [branch] + if ((has_count & 4u) != 0) { + src_at = count_buf.Load(count_offset + id.x * 4u); + } + uint dst_at = id.x * stride; + uint cost = 0; + uint asked = 0; + uint2 draw_counts = uint2(0, 0); + uint3 groups = uint3(0, 0, 0); + if (gi == 0) { + largest_asked = 0; + all_asked = 0; + } + if (active && kind <= 1) { + // Draws: vertex or index count, then instances. + uint2 want = src_args.Load2(src_at); + if (ahead && (want.x > (1u << 24) || want.y > (1u << 24))) { + want = uint2(0, 0); + } + uint count = min(want.x, 1u << 24); + uint instances = min(want.y, (1u << 26) / max(count, 1u)); + cost = count * instances; + // A record that asks for MOST_DRAW vertices or indices an instance + // or more is no draw of the title's (no mesh of a console title has + // 2.8 million triangles): it runs empty and charges nothing. Run + // 206's window check found one list with 90 draws of 2^24 vertices + // and one instance each. Clamped one draw at a time, the list's + // budget lets eight of them run (2^27 in all) and empties the other + // 82; served from a window, whose records are charged once however + // often they are drawn, all 90 ran: 1.5 thousand million vertices + // in one list, with windows on in the runs that lost the device + // (201, 204). + if (count >= MOST_DRAW) { + count = 0; + instances = 0; + cost = 0; + } + draw_counts = uint2(count, instances); + } else if (active && kind == 2) { + uint3 g = min(src_args.Load3(src_at), uint3(65535u, 65535u, 65535u)); + // x * y fits 32 bits; the whole count may not. + if (g.z != 0 && g.x * g.y > GROUPS / g.z) { + g = uint3(0, 0, 0); + } + cost = g.x * g.y * g.z * 64u; + groups = g; + } else if (active) { + // Mesh dispatches: the console's are one-dimensional. + uint3 g = src_args.Load3(src_at); + // Ahead of its draw, a record over the most a dispatch runs is a + // slot the title has not filled (the title leaves all + // ones there): empty, and not counted below either. + if (ahead && g.x > 65535u) { + g = uint3(0, 0, 0); + } + asked = g.x; + g = uint3(min(g.x, 65535u), min(g.y, 1u), min(g.z, 1u)); + cost = g.x * g.y * g.z * 128u; + groups = g; + } + costs[gi] = cost; + GroupMemoryBarrierWithGroupSync(); + if (active && kind > 2) { + // Diagnostics, in the budget buffer's next words (below): the + // largest group count a mesh record asked for, and the groups + // asked in all. + uint was; + InterlockedMax(largest_asked, asked, was); + InterlockedAdd(all_asked, min(asked, 1u << 24), was); + } + // The group's own records: none for a group past a count buffer's + // count (an execution may ask for thousands and count a few), which + // touches the budget not at all, as its threads did not before. + uint first = id.x - gi; + uint n = eff_count > first ? min(64u, eff_count - first) : 0u; + if (gi == 0 && n > 0) { + // What the records charge, from `before` on, in lane order: a + // record that does not fit whole runs empty and takes the rest. + // Only the group's own records are walked (one, clamped alone). + uint before; + budget.InterlockedOr(0, 0, before); + [allow_uav_condition] + while (before < BUDGET) { + uint next = before; + for (uint j = 0; j < n; j++) { + uint c = costs[j]; + if (c > 0 && next < BUDGET) { + next = (BUDGET - next <= c) ? BUDGET : (next + c); + } + } + if (next == before) break; + uint prev; + budget.InterlockedCompareExchange(0, before, next, prev); + if (prev == before) break; + before = prev; + } + uint at = before; + for (uint k = 0; k < n; k++) { + uint c = costs[k]; + uint fit = 1; + if (c > 0) { + fit = (at < BUDGET && BUDGET - at >= c) ? 1u : 0u; + at = (at >= BUDGET || BUDGET - at <= c) ? BUDGET : (at + c); + } + fits[k] = fit; + } + } + GroupMemoryBarrierWithGroupSync(); + if (gi == 0 && kind > 2 && n > 0) { + uint was; + budget.InterlockedMax(4, largest_asked, was); + budget.InterlockedAdd(8, all_asked, was); + } + if (!active) { + return; + } + bool over = fits[gi] == 0; + if (kind <= 1) { + if (over) { + draw_counts = uint2(0, 0); + } + dst_args.Store2(dst_at, draw_counts); + for (uint off = 8; off < stride; off += 4) { + dst_args.Store(dst_at + off, src_args.Load(src_at + off)); + } + } else { + if (over) { + groups = uint3(0, 0, 0); + } + dst_args.Store3(dst_at, groups); + for (uint off = 12; off < stride; off += 4) { + dst_args.Store(dst_at + off, src_args.Load(src_at + off)); + } + } +} +"#; + +struct Clamp { + root: ID3D12RootSignature, + pso: ID3D12PipelineState, +} + +// SAFETY: D3D12 objects are free-threaded. +unsafe impl Send for Clamp {} +// SAFETY: as above. +unsafe impl Sync for Clamp {} + +fn clamp() -> Option<&'static Clamp> { + static CLAMP: std::sync::OnceLock> = std::sync::OnceLock::new(); + CLAMP + .get_or_init(|| match make() { + Ok(c) => Some(c), + Err(e) => { + tracing::warn!(error = %e, "no argument clamp: indirect execution dropped"); + None + } + }) + .as_ref() +} + +fn make() -> windows::core::Result { + let device = &host().ok_or_else(windows::core::Error::empty)?.device; + make_for(device) +} + +fn make_for(device: &ID3D12Device) -> windows::core::Result { + make_from(device, SOURCE) +} + +/// The clamp compiled from `source` (ours, or in the benchmark the one it +/// replaced). +fn make_from(device: &ID3D12Device, source: &str) -> windows::core::Result { + let mut code: Option = None; + let mut errors: Option = None; + // SAFETY: the source and names live through the call; out pointers ours. + let compiled = unsafe { + D3DCompile( + source.as_ptr().cast(), + source.len(), + s!("clamp"), + None, + None, + s!("main"), + s!("cs_5_1"), + 0, + 0, + &mut code, + Some(&mut errors), + ) + }; + if let Err(e) = compiled { + if let Some(errors) = errors { + // SAFETY: the blob's own bytes. + let text = unsafe { + std::slice::from_raw_parts( + errors.GetBufferPointer().cast::(), + errors.GetBufferSize(), + ) + }; + tracing::warn!("argument clamp: {}", String::from_utf8_lossy(text)); + } + return Err(e); + } + let code = code.ok_or_else(windows::core::Error::empty)?; + // SAFETY: the blob's own bytes; the root signature is inside the shader. + unsafe { + let bytes = + std::slice::from_raw_parts(code.GetBufferPointer().cast::(), code.GetBufferSize()); + let root: ID3D12RootSignature = device.CreateRootSignature(0, bytes)?; + let pso = device.CreateComputePipelineState(&D3D12_COMPUTE_PIPELINE_STATE_DESC { + pRootSignature: std::mem::transmute_copy(&root), + CS: D3D12_SHADER_BYTECODE { + pShaderBytecode: bytes.as_ptr().cast(), + BytecodeLength: bytes.len(), + }, + ..Default::default() + })?; + Ok(Clamp { root, pso }) + } +} + +/// Minimum record byte stride for a supported PC indirect argument `kind`. +fn min_stride(kind: u32) -> Option { + match kind { + 0 => Some(16), + 1 => Some(20), + 2 | 10 => Some(12), + _ => None, + } +} + +/// Validates record alignment and returns the scratch byte size `stride * records`. +fn validate_layout( + (kind, stride, records): (u32, u32, u32), + src_offset: u64, + count_offset: Option, +) -> Option { + let min = min_stride(kind)?; + if stride < min || !stride.is_multiple_of(4) || !src_offset.is_multiple_of(4) { + return None; + } + if count_offset.is_some_and(|off| !off.is_multiple_of(4)) { + return None; + } + let bytes = u64::from(stride).checked_mul(u64::from(records))?; + (bytes <= u64::from(u32::MAX)).then_some(bytes) +} + +/// Records, in `list`, the non-destructive clamp of up to `records` records of +/// `kind` (PC argument numbering) `stride` bytes apart from `src` (and bounded +/// by the 32-bit count in `count` when given) into a device-local scratch +/// buffer, at offset `0`. The scratch buffer is left in `INDIRECT_ARGUMENT` +/// until the next clamp into it: executions read it with no barrier of +/// their own. Replaces the list's compute root signature and pipeline +/// (callers bind theirs after). `None` if the clamp or alignment is not +/// available. +pub(crate) fn bound( + list: &HostList, + src: (&ID3D12Resource, u64), + count: Option<(&ID3D12Resource, u64)>, + spec: (u32, u32, u32), +) -> Option { + let bytes = validate_layout(spec, src.1, count.map(|(_, off)| off))?; + let (c, budget, dst) = (clamp()?, list.budget()?, list.indirect_scratch(bytes)?); + clamp_into(list, c, &dst, budget, src, count, spec, false).then_some(dst) +} + +/// [`bound`] for a window of records clamped ahead of the draws that will +/// read them (`crate::draw`'s windows; no count buffer). The records past +/// the ones the title filled are whatever the buffer holds, and each +/// record clamped charges the list's budget when it is clamped: a slot of +/// all ones, clamped to the most a mesh dispatch runs (65,535 groups), +/// charged a sixteenth of the budget, so sixteen of them emptied every +/// draw of the list after them (run 93: "the largest group count asked for +/// 4294967295", 43 to 153 such records a frame). Here a record that asks +/// for more than can run is left empty and charges nothing; a record +/// clamped alone is clamped and charged as before. +pub(crate) fn bound_ahead( + list: &HostList, + src: (&ID3D12Resource, u64), + spec: (u32, u32, u32), +) -> Option { + let bytes = validate_layout(spec, src.1, None)?; + let (c, budget, dst) = (clamp()?, list.budget()?, list.indirect_scratch(bytes)?); + clamp_into(list, c, &dst, budget, src, None, spec, true).then_some(dst) +} + +/// [`record_clamp_as`] into `list`'s scratch buffer `dst`, from the state +/// the list left it in; afterwards the list knows it is readable as +/// indirect arguments. +#[allow(clippy::too_many_arguments)] +fn clamp_into( + list: &HostList, + c: &Clamp, + dst: &ID3D12Resource, + budget: u64, + src: (&ID3D12Resource, u64), + count: Option<(&ID3D12Resource, u64)>, + spec: (u32, u32, u32), + ahead: bool, +) -> bool { + let before = list.indirect_state(dst); + let recorded = record_clamp_as(c, &list.list, (dst, before), budget, src, count, spec, ahead); + if recorded { + list.indirect_readable(dst); + } + recorded +} + +/// Records the clamp into `dst`, which is in state `before` (common, or +/// indirect arguments after an earlier clamp into it), and leaves `dst` in +/// `INDIRECT_ARGUMENT`. `ahead`: the records are a window clamped ahead of +/// their draws ([`bound_ahead`]). False, with nothing recorded, if the +/// layout or the addresses do not fit the clamp. +#[allow(clippy::too_many_arguments)] +fn record_clamp_as( + c: &Clamp, + l: &ID3D12GraphicsCommandList, + (dst, before): (&ID3D12Resource, D3D12_RESOURCE_STATES), + budget: u64, + (src, src_offset): (&ID3D12Resource, u64), + count: Option<(&ID3D12Resource, u64)>, + (kind, stride, records): (u32, u32, u32), + ahead: bool, +) -> bool { + let Some(bytes) = validate_layout( + (kind, stride, records), + src_offset, + count.map(|(_, off)| off), + ) else { + return false; + }; + // SAFETY: live D3D12 buffer resources. + let (src_base, dst_gpu) = unsafe { (src.GetGPUVirtualAddress(), dst.GetGPUVirtualAddress()) }; + if !src_base.is_multiple_of(4) || !dst_gpu.is_multiple_of(4) || !budget.is_multiple_of(4) { + return false; + } + let (src_gpu, args_offset) = match src_offset + .checked_add(bytes) + .filter(|&end| end <= u64::from(u32::MAX)) + { + Some(_) => (src_base, src_offset as u32), + None => { + let Some(rebased) = src_base.checked_add(src_offset) else { + return false; + }; + (rebased, 0) + } + }; + let (count_gpu, has_count, count_offset) = match count { + Some((buf, off)) => { + // SAFETY: a live D3D12 buffer resource. + let base = unsafe { buf.GetGPUVirtualAddress() }; + if !base.is_multiple_of(4) { + return false; + } + match off.checked_add(4).filter(|&end| end <= u64::from(u32::MAX)) { + Some(_) => (base, 1u32, off as u32), + None => { + let Some(rebased) = base.checked_add(off) else { + return false; + }; + (rebased, 1u32, 0u32) + } + } + } + None => (src_gpu, 0u32, 0u32), + }; + let constants = [kind, stride, records, args_offset, has_count | (u32::from(ahead) << 1), count_offset]; + // SAFETY: an open list; our root signature and pipeline; live source, + // count, scratch destination, and budget buffers. `src` and `count` stay + // in `COMMON` / `GENERIC_READ` via implicit buffer promotion while `dst` + // transitions `before -> UNORDERED_ACCESS -> INDIRECT_ARGUMENT`. Moving + // it out of `INDIRECT_ARGUMENT` orders this clamp's writes after every + // earlier execution's reads of the scratch buffer; nothing else writes it. + // Diagnostics: counted; `LEONIDA_BARRIER_TEST=indirect` leaves the two + // waits for every earlier shader write out (the state changes stay). + #[cfg(feature = "diagnostics")] + crate::copystat::add(crate::copystat::C::IndirectBounded, 1); + #[cfg(feature = "diagnostics")] + let waits = crate::copystat::barrier_test() & 2 == 0; + #[cfg(not(feature = "diagnostics"))] + let waits = true; + let first = [ + uav_barrier(), + transition(dst, before, D3D12_RESOURCE_STATE_UNORDERED_ACCESS), + ]; + let second = [ + uav_barrier(), + transition( + dst, + D3D12_RESOURCE_STATE_UNORDERED_ACCESS, + D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT, + ), + ]; + let skip = usize::from(!waits); + unsafe { + // Earlier shader writes (the title's argument and count passes) first. + l.ResourceBarrier(&first[skip..]); + if records > 0 { + l.SetComputeRootSignature(&c.root); + l.SetPipelineState(&c.pso); + l.SetComputeRoot32BitConstants(0, 6, constants.as_ptr().cast(), 0); + l.SetComputeRootShaderResourceView(1, src_gpu); + l.SetComputeRootShaderResourceView(2, count_gpu); + l.SetComputeRootUnorderedAccessView(3, dst_gpu); + l.SetComputeRootUnorderedAccessView(4, budget); + l.Dispatch(records.div_ceil(64), 1, 1); + } + l.ResourceBarrier(&second[skip..]); + } + true +} + +/// The most records of one argument buffer gathered for a list +/// ([`gather`]): a multiple of the clamp's 64 threads a group, so that the +/// threads past the last record read inside the table. +pub(crate) const GATHER_MOST: u32 = 4096; +/// The widest record gathered: its slot in the scratch buffer. +pub(crate) const GATHER_STRIDE: u32 = 32; + +/// The records of one argument buffer that a list's draws read, to be +/// clamped in one pass before the list runs ([`gather`]): the buffer (a +/// host copy, and its number), the records' kind and stride, the scratch +/// buffer whose slot `i` holds record `i` clamped, and the table of the +/// records' offsets in the buffer (upload memory of the list). +pub(crate) struct GatherSet { + pub(crate) src: ID3D12Resource, + pub(crate) src_id: u64, + pub(crate) kind: u32, + pub(crate) stride: u32, + pub(crate) scratch: ID3D12Resource, + table_gpu: u64, + table: usize, + /// A record's offset in the buffer, and its slot. + slots: std::collections::HashMap, +} + +// SAFETY: D3D12 objects are free-threaded; the table is the list's own +// upload memory, written under the list's lock before the list is submitted. +unsafe impl Send for GatherSet {} + +impl GatherSet { + pub(crate) fn new(src: ID3D12Resource, src_id: u64, (kind, stride): (u32, u32), scratch: ID3D12Resource, (table_gpu, table): (u64, *mut u8)) -> Self { + Self { src, src_id, kind, stride, scratch, table_gpu, table: table as usize, slots: Default::default() } + } + + /// The records gathered so far. + pub(crate) fn records(&self) -> u32 { + self.slots.len() as u32 + } + + /// The slot of the record at `offset`: the one it has, or the next + /// free one. None when the set is full. + pub(crate) fn slot(&mut self, offset: u32) -> Option { + if let Some(&slot) = self.slots.get(&offset) { + return Some(slot); + } + let slot = self.slots.len() as u32; + if slot >= GATHER_MOST { + return None; + } + // SAFETY: the table holds `GATHER_MOST` words. + unsafe { (self.table as *mut u32).add(slot as usize).write_volatile(offset) }; + self.slots.insert(offset, slot); + Some(slot) + } + + /// The scratch buffer `src`'s set uses, to keep for the list's next recording. + pub(crate) fn into_scratch(self) -> ID3D12Resource { + self.scratch + } +} + +/// Whether [`gather`] can take a record of `kind` and `stride` at `offset` +/// of a buffer at `src_gpu`: what [`record_gather_as`] asks of its +/// arguments, checked when the record is taken, because a record once +/// given a slot is drawn from the slot. +pub(crate) fn gatherable(src_gpu: u64, offset: u64, (kind, stride): (u32, u32)) -> Option { + let min = min_stride(kind)?; + if stride < min || stride > GATHER_STRIDE || !stride.is_multiple_of(4) || !offset.is_multiple_of(4) || !src_gpu.is_multiple_of(4) { + return None; + } + u32::try_from(offset).ok().filter(|o| o.checked_add(stride).is_some()) +} + +/// For a single record of `kind` and `stride` at `offset` of the host copy +/// `src` (its number `src_id`) that a draw of `list` is about to read: a +/// slot in the list's scratch buffer for that argument buffer, which the +/// list's prelude fills with the record clamped, in one pass with all the +/// other records the list's draws read (`HostList::prelude`, +/// [`record_gathers`]). Nothing is recorded in the list. The scratch +/// buffer and the record's place in it; None if the list no longer +/// gathers (something in it may write arguments), the set is full, or the +/// record does not fit the clamp: the caller clamps it as before. +/// +/// Why: the title keeps its mesh records scattered through one argument +/// buffer of about 100 MB (from one draw to the next 16 to 33,056 bytes +/// on, or back), so a window of records at one step cannot serve them, and +/// about 1,450 draws a frame each had a compute pass of ours in front of +/// them: the card left drawing for compute and came back, about nine +/// microseconds each (run 243, and the windows' own measurement). +pub(crate) fn gather(list: &HostList, (src, src_id): (&ID3D12Resource, u64), offset: u64, spec: (u32, u32)) -> Option<(ID3D12Resource, u64)> { + clamp()?; + // SAFETY: a live D3D12 buffer resource. + let Some(offset) = gatherable(unsafe { src.GetGPUVirtualAddress() }, offset, spec) else { + GATHER_NONE[0].fetch_add(1, std::sync::atomic::Ordering::Relaxed); + return None; + }; + list.gather_slot(src, src_id, offset, spec) +} + +/// Since the last line: records that got no slot because they do not fit +/// the clamp, because their list had stopped gathering, because the list +/// gathers from too many buffers, because their set was full, because a +/// buffer could not be made. +pub(crate) static GATHER_NONE: [std::sync::atomic::AtomicU64; 5] = [const { std::sync::atomic::AtomicU64::new(0) }; 5]; + +/// Records the clamp of `records` gathered records into `dst`, which is in +/// state `before`, and leaves `dst` in `INDIRECT_ARGUMENT`: record `i` is +/// read at the offset word `i` of the table at `table_gpu` names, in the +/// buffer `src`, and stored clamped at `i * stride`. Charged to the budget +/// word at `budget` as records clamped one by one are. False, with nothing +/// recorded, if the layout or the addresses do not fit the clamp. +fn record_gather_as( + c: &Clamp, + l: &ID3D12GraphicsCommandList, + (dst, before): (&ID3D12Resource, D3D12_RESOURCE_STATES), + budget: u64, + src: &ID3D12Resource, + table_gpu: u64, + (kind, stride, records): (u32, u32, u32), +) -> bool { + // SAFETY: live D3D12 buffer resources. + let (src_gpu, dst_gpu) = unsafe { (src.GetGPUVirtualAddress(), dst.GetGPUVirtualAddress()) }; + if gatherable(src_gpu, 0, (kind, stride)).is_none() + || records == 0 + || records > GATHER_MOST + || !dst_gpu.is_multiple_of(4) + || !budget.is_multiple_of(4) + || !table_gpu.is_multiple_of(4) + { + return false; + } + let constants = [kind, stride, records, 0u32, 4u32, 0u32]; + let first = [uav_barrier(), transition(dst, before, D3D12_RESOURCE_STATE_UNORDERED_ACCESS)]; + let second = [ + uav_barrier(), + transition(dst, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT), + ]; + // SAFETY: an open list; our root signature and pipeline; live source, + // table, scratch destination and budget buffers. The first wait puts + // the pass behind every earlier shader write (the title's argument + // passes of the lists before); the second puts the list's draws behind + // the pass. + unsafe { + l.ResourceBarrier(&first); + l.SetComputeRootSignature(&c.root); + l.SetPipelineState(&c.pso); + l.SetComputeRoot32BitConstants(0, 6, constants.as_ptr().cast(), 0); + l.SetComputeRootShaderResourceView(1, src_gpu); + l.SetComputeRootShaderResourceView(2, table_gpu); + l.SetComputeRootUnorderedAccessView(3, dst_gpu); + l.SetComputeRootUnorderedAccessView(4, budget); + l.Dispatch(records.div_ceil(64), 1, 1); + l.ResourceBarrier(&second); + } + true +} + +/// Records, into a list's prelude `l`, the passes that fill the scratch +/// buffers of `sets` ([`gather`]), charged to the words of `budget`, which +/// is zeroed first (the gathered records have a budget of their own: the +/// list's own clamps zero and charge theirs inside the list, after this). +/// False if anything could not be recorded: the slots then hold no clamped +/// records and the list must not run. +pub(crate) fn record_gathers(l: &ID3D12GraphicsCommandList, sets: &[GatherSet], budget: &ID3D12Resource) -> bool { + use windows::core::Interface; + let (Some(c), Ok(l2)) = (clamp(), l.cast::()) else { + return false; + }; + // SAFETY: a live buffer. + let at = unsafe { budget.GetGPUVirtualAddress() }; + let zeros = [0u64, 4, 8].map(|offset| D3D12_WRITEBUFFERIMMEDIATE_PARAMETER { Dest: at + offset, Value: 0 }); + // SAFETY: an open list; the budget buffer is the list's own and common + // between its runs. + unsafe { + l.ResourceBarrier(&[transition(budget, D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_COPY_DEST)]); + l2.WriteBufferImmediate(zeros.len() as u32, zeros.as_ptr(), None); + l.ResourceBarrier(&[transition(budget, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_UNORDERED_ACCESS)]); + } + let mut all = true; + for set in sets.iter().filter(|s| s.records() > 0) { + all &= record_gather_as(c, l, (&set.scratch, D3D12_RESOURCE_STATE_COMMON), at, &set.src, set.table_gpu, (set.kind, set.stride, set.records())); + } + // SAFETY: as above. + unsafe { + l.ResourceBarrier(&[transition(budget, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_COMMON)]); + } + all +} + +/// Whether every draw served from a window is checked against a fresh +/// clamp of its record (`LEONIDA_INDIRECT_WINDOW_CHECK=1`, with +/// `LEONIDA_INDIRECT_WINDOW=1`; off by default). A window clamps its +/// records once, ahead of their draws; if anything wrote a record between +/// the window's clamp and its draw, the draw reads the old one. The check +/// clamps the record again just before the draw (into a buffer of its own, +/// charging a budget of its own) and compares the two on the card: the +/// counts are logged ("window check"), and the first record that differs in +/// each run of a list is named. For telling whether windows can be trusted +/// in a scene before they are on by default; it costs a clamp and a compare +/// per window draw. +pub(crate) fn window_check() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| { + std::env::var_os("LEONIDA_INDIRECT_WINDOW_CHECK").is_some_and(|v| v == "1") + }) +} + +/// The compare of [`window_check`]: `words` dwords of the record a window +/// clamped (`t0`) against the same record clamped just now (`t1`). Counts +/// the checks and the records that differ in `u0`, keeps the first record +/// that differs there (eight dwords of each), and zeroes the fresh clamp's +/// own budget (`u1`) for the next check. +const CHECK_SOURCE: &str = r#" +#define RS "RootConstants(num32BitConstants=1, b0), SRV(t0), SRV(t1), UAV(u0), UAV(u1)" +cbuffer Check : register(b0) { + uint words; +}; +ByteAddressBuffer window_record : register(t0); +ByteAddressBuffer fresh_record : register(t1); +RWByteAddressBuffer results : register(u0); +RWByteAddressBuffer fresh_budget : register(u1); +[RootSignature(RS)] +[numthreads(1, 1, 1)] +void main() { + bool same = true; + for (uint i = 0; i < words; i++) { + if (window_record.Load(4 * i) != fresh_record.Load(4 * i)) { + same = false; + } + } + uint was; + results.InterlockedAdd(4, 1, was); + if (!same) { + uint before; + results.InterlockedAdd(0, 1, before); + if (before == 0) { + for (uint k = 0; k < min(words, 8u); k++) { + results.Store(8 + 4 * k, window_record.Load(4 * k)); + results.Store(40 + 4 * k, fresh_record.Load(4 * k)); + } + } + } + fresh_budget.Store3(0, uint3(0, 0, 0)); +} +"#; + +fn compare() -> Option<&'static Clamp> { + static COMPARE: std::sync::OnceLock> = std::sync::OnceLock::new(); + COMPARE + .get_or_init(|| { + let device = &host()?.device; + match make_from(device, CHECK_SOURCE) { + Ok(c) => Some(c), + Err(e) => { + tracing::warn!(error = %e, "no window check"); + None + } + } + }) + .as_ref() +} + +/// A list's buffers for [`window_check`]: the fresh clamps' records and +/// budget (the card's memory), and the results (memory the CPU maps: +/// records that differed, checks, then the first differing record as the +/// window had it and as the fresh clamp made it, eight dwords each). +pub(crate) struct WindowCheck { + args: ID3D12Resource, + budget: ID3D12Resource, + results: ID3D12Resource, + data: usize, +} + +// SAFETY: D3D12 objects are free-threaded; the mapping is read only at +// submission, when the list's last run has finished. +unsafe impl Send for WindowCheck {} +// SAFETY: as above. +unsafe impl Sync for WindowCheck {} + +impl WindowCheck { + pub(crate) fn new() -> Option { + let host = host()?; + let (results, data) = host.shared_buffer(256)?; + // SAFETY: the mapping holds 256 bytes; nothing runs yet. + unsafe { std::ptr::write_bytes(data, 0, 256) }; + Some(WindowCheck { + args: host.uav_buffer(64 << 10)?, + budget: host.uav_buffer(256)?, + results, + data: data as usize, + }) + } + + /// What the list's last run found, zeroed for the next: checks, records + /// that differed, and the first that did (as the window had it, as the + /// fresh clamp made it). Only between runs of the list. + pub(crate) fn take(&self) -> (u32, u32, [u32; 8], [u32; 8]) { + let words = self.data as *mut u32; + // SAFETY: the list's own mapped words; its last run has finished. + unsafe { + let at = |k: usize| words.add(k).read_volatile(); + let window = std::array::from_fn(|k| at(2 + k)); + let fresh = std::array::from_fn(|k| at(10 + k)); + let found = (at(1), at(0), window, fresh); + std::ptr::write_bytes(words, 0, 18); + found + } + } +} + +/// Checks and differing records seen by [`window_check`] so far. +static CHECKED: [std::sync::atomic::AtomicU64; 2] = + [const { std::sync::atomic::AtomicU64::new(0) }; 2]; + +/// [`window_check`] for a draw served from a window: the record of `kind` +/// at `src`, `step` bytes long, which the window clamped into `scratch` at +/// `at`, is clamped again into the list's check buffer and compared. Runs +/// compute work of ours, so the caller binds its pipeline again after it. +/// False if nothing was recorded. +pub(crate) fn check_hit( + list: &HostList, + src: (&ID3D12Resource, u64), + (kind, step): (u32, u32), + scratch: &ID3D12Resource, + at: u64, +) -> bool { + const CHECK_USE: usize = usize::MAX - 0x78; + let (Some(c), Some(cmp), Some(check)) = (clamp(), compare(), list.window_check()) else { + return false; + }; + if list.first_use(CHECK_USE) { + // At this recording's submission: what the list's last run found. + let data = check.data; + let words = WindowCheck { + args: check.args.clone(), + budget: check.budget.clone(), + results: check.results.clone(), + data, + }; + list.defer_host(move || { + let (checked, differed, window, fresh) = words.take(); + if checked == 0 { + return; + } + use std::sync::atomic::Ordering::Relaxed; + let total = CHECKED[0].fetch_add(u64::from(checked), Relaxed) + u64::from(checked); + let bad = CHECKED[1].fetch_add(u64::from(differed), Relaxed) + u64::from(differed); + if differed > 0 { + tracing::warn!( + differed, + checked, + ?window, + ?fresh, + "window check: a draw served from a window read a record that \ + differs from a fresh clamp of it" + ); + } + if total / 10_000 != (total - u64::from(checked)) / 10_000 { + tracing::info!(checked = total, differed = bad, "window check"); + } + }); + } + // SAFETY: live buffers. + let (budget, results, fresh, window) = unsafe { + ( + check.budget.GetGPUVirtualAddress(), + check.results.GetGPUVirtualAddress(), + check.args.GetGPUVirtualAddress(), + scratch.GetGPUVirtualAddress() + at, + ) + }; + // The record again, by the window's rules, into the check's buffer + // (common before and after every check). + let common = D3D12_RESOURCE_STATE_COMMON; + let spec = (kind, step, 1); + if !record_clamp_as(c, &list.list, (&check.args, common), budget, src, None, spec, true) { + return false; + } + let args = D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT; + let read = D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE; + let words = step / 4; + // SAFETY: an open list; the compare's own root signature and pipeline; + // the scratch buffer is readable as arguments (and stays so), the + // check's buffer was left so by the clamp above. + unsafe { + list.list.ResourceBarrier(&[ + transition(scratch, args, D3D12_RESOURCE_STATES(args.0 | read.0)), + transition(&check.args, args, read), + ]); + list.list.SetComputeRootSignature(&cmp.root); + list.list.SetPipelineState(&cmp.pso); + list.list.SetComputeRoot32BitConstants(0, 1, (&raw const words).cast(), 0); + list.list.SetComputeRootShaderResourceView(1, window); + list.list.SetComputeRootShaderResourceView(2, fresh); + list.list.SetComputeRootUnorderedAccessView(3, results); + list.list.SetComputeRootUnorderedAccessView(4, budget); + list.list.Dispatch(1, 1, 1); + list.list.ResourceBarrier(&[ + transition(scratch, D3D12_RESOURCE_STATES(args.0 | read.0), args), + transition(&check.args, read, common), + ]); + } + true +} + +fn uav_barrier() -> D3D12_RESOURCE_BARRIER { + D3D12_RESOURCE_BARRIER { + Type: D3D12_RESOURCE_BARRIER_TYPE_UAV, + Flags: D3D12_RESOURCE_BARRIER_FLAG_NONE, + Anonymous: D3D12_RESOURCE_BARRIER_0 { + UAV: std::mem::ManuallyDrop::new(D3D12_RESOURCE_UAV_BARRIER { + pResource: std::mem::ManuallyDrop::new(None), + }), + }, + } +} + +#[cfg(test)] +mod tests { + use super::*; + use windows::Win32::Foundation::HANDLE; + use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_12_0; + use windows::Win32::Graphics::Dxgi::Common::DXGI_SAMPLE_DESC; + use windows::Win32::Graphics::Dxgi::*; + use windows::Win32::System::Threading::{CreateEventW, INFINITE, WaitForSingleObject}; + use windows::core::Interface; + + const WORKER_CS: &str = r#" +#define RS "UAV(u0)" +RWByteAddressBuffer hits : register(u0); +[RootSignature(RS)] +[numthreads(1, 1, 1)] +void main() { + uint prev; + hits.InterlockedAdd(0, 1, prev); +} +"#; + + struct WarpHarness { + device: ID3D12Device, + queue: ID3D12CommandQueue, + allocator: ID3D12CommandAllocator, + list: ID3D12GraphicsCommandList, + fence: ID3D12Fence, + submitted: u64, + event: HANDLE, + clamp: Clamp, + worker: Clamp, + } + + impl WarpHarness { + fn new() -> Option { + // SAFETY: plain DXGI WARP query and D3D12 test harness setup. + unsafe { + let factory: IDXGIFactory4 = + CreateDXGIFactory2(DXGI_CREATE_FACTORY_FLAGS(0)).ok()?; + let adapter: IDXGIAdapter = factory.EnumWarpAdapter().ok()?; + let desc = adapter.cast::().ok()?.GetDesc1().ok()?; + if desc.Flags & DXGI_ADAPTER_FLAG_SOFTWARE.0 as u32 == 0 { + return None; + } + let mut device: Option = None; + D3D12CreateDevice(&adapter, D3D_FEATURE_LEVEL_12_0, &mut device).ok()?; + let device = device?; + let queue: ID3D12CommandQueue = device + .CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC { + Type: D3D12_COMMAND_LIST_TYPE_DIRECT, + ..Default::default() + }) + .ok()?; + let allocator: ID3D12CommandAllocator = device + .CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT) + .ok()?; + let list: ID3D12GraphicsCommandList = device + .CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &allocator, None) + .ok()?; + let fence: ID3D12Fence = device.CreateFence(0, D3D12_FENCE_FLAG_NONE).ok()?; + let event = CreateEventW(None, false, false, None).ok()?; + let clamp = make_for(&device).expect("clamp shader must compile on WARP"); + let worker = compile_cs(&device, WORKER_CS).expect("worker shader must compile"); + Some(Self { + device, + queue, + allocator, + list, + fence, + submitted: 0, + event, + clamp, + worker, + }) + } + } + + /// CPU-mapped L0 write-back buffer matching `Shadow`'s heap type. + fn shared_buffer(&self, size: u64) -> (ID3D12Resource, *mut u8, u64) { + let heap = D3D12_HEAP_PROPERTIES { + Type: D3D12_HEAP_TYPE_CUSTOM, + CPUPageProperty: D3D12_CPU_PAGE_PROPERTY_WRITE_BACK, + MemoryPoolPreference: D3D12_MEMORY_POOL_L0, + ..Default::default() + }; + let desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, + Width: size.max(4), + Height: 1, + DepthOrArraySize: 1, + MipLevels: 1, + SampleDesc: DXGI_SAMPLE_DESC { + Count: 1, + Quality: 0, + }, + Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, + Flags: D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS, + ..Default::default() + }; + let mut buffer: Option = None; + let mut data = std::ptr::null_mut(); + // SAFETY: plain buffer creation and persistent CPU mapping. + unsafe { + self.device + .CreateCommittedResource( + &heap, + D3D12_HEAP_FLAG_NONE, + &desc, + D3D12_RESOURCE_STATE_COMMON, + None, + &mut buffer, + ) + .unwrap(); + let buffer = buffer.unwrap(); + buffer.Map(0, None, Some(&mut data)).unwrap(); + let gpu = buffer.GetGPUVirtualAddress(); + (buffer, data.cast(), gpu) + } + } + + /// Device-local `DEFAULT`-heap UAV scratch buffer. + fn default_uav(&self, size: u64) -> ID3D12Resource { + let heap = D3D12_HEAP_PROPERTIES { + Type: D3D12_HEAP_TYPE_DEFAULT, + ..Default::default() + }; + let desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, + Width: size.max(64 << 10), + Height: 1, + DepthOrArraySize: 1, + MipLevels: 1, + SampleDesc: DXGI_SAMPLE_DESC { + Count: 1, + Quality: 0, + }, + Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, + Flags: D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS, + ..Default::default() + }; + let mut buffer: Option = None; + // SAFETY: plain device-local buffer creation. + unsafe { + self.device + .CreateCommittedResource( + &heap, + D3D12_HEAP_FLAG_NONE, + &desc, + D3D12_RESOURCE_STATE_COMMON, + None, + &mut buffer, + ) + .unwrap(); + } + buffer.unwrap() + } + + fn signature(&self, kind: u32, stride: u32) -> ID3D12CommandSignature { + let arg = D3D12_INDIRECT_ARGUMENT_DESC { + Type: D3D12_INDIRECT_ARGUMENT_TYPE(kind as i32), + ..Default::default() + }; + let desc = D3D12_COMMAND_SIGNATURE_DESC { + ByteStride: stride, + NumArgumentDescs: 1, + pArgumentDescs: &arg, + NodeMask: 0, + }; + let mut sig: Option = None; + // SAFETY: valid single-argument command signature description. + unsafe { + self.device + .CreateCommandSignature(&desc, None::<&ID3D12RootSignature>, &mut sig) + .unwrap(); + } + sig.unwrap() + } + + fn submit_and_wait(&mut self) { + self.submitted += 1; + // SAFETY: closing, executing, waiting on fence, and resetting our list. + unsafe { + self.list.Close().unwrap(); + let cmd: ID3D12CommandList = self.list.cast().unwrap(); + self.queue.ExecuteCommandLists(&[Some(cmd)]); + self.queue.Signal(&self.fence, self.submitted).unwrap(); + self.fence + .SetEventOnCompletion(self.submitted, self.event) + .unwrap(); + WaitForSingleObject(self.event, INFINITE); + self.allocator.Reset().unwrap(); + self.list.Reset(&self.allocator, None).unwrap(); + } + } + } + + fn compile_cs(device: &ID3D12Device, source: &str) -> windows::core::Result { + let mut code: Option = None; + // SAFETY: source and entry names outlive `D3DCompile`. + unsafe { + D3DCompile( + source.as_ptr().cast(), + source.len(), + s!("worker"), + None, + None, + s!("main"), + s!("cs_5_1"), + 0, + 0, + &mut code, + None, + )?; + let code = code.unwrap(); + let bytes = std::slice::from_raw_parts( + code.GetBufferPointer().cast::(), + code.GetBufferSize(), + ); + let root: ID3D12RootSignature = device.CreateRootSignature(0, bytes)?; + let pso = device.CreateComputePipelineState(&D3D12_COMPUTE_PIPELINE_STATE_DESC { + pRootSignature: std::mem::transmute_copy(&root), + CS: D3D12_SHADER_BYTECODE { + pShaderBytecode: bytes.as_ptr().cast(), + BytecodeLength: bytes.len(), + }, + ..Default::default() + })?; + Ok(Clamp { root, pso }) + } + } + + /// The compare of copies in the card's memory (`crate::host`), on the + /// software adapter. Told 1 it flags the pieces whose bytes are not + /// what was hashed last and leaves the hashes: a piece a shader changed + /// and a later one changed back then looks untouched, which is right + /// only if the piece was fetched after both. Told 2 (submissions sent + /// ahead with the relay, whose pieces are fetched flight by flight) it + /// stores the hash it made: each compare flags what changed since the + /// compare before it, also a change back. + #[test] + fn warp_card_compare_stores_the_hash_it_made_when_told() { + let Some(mut warp) = WarpHarness::new() else { + return; + }; + let compare = compile_cs(&warp.device, crate::host::CARD_COMPARE).expect("the card compare must compile on WARP"); + const PIECE: usize = 64 << 10; + const PIECES: u32 = 3; + let size = PIECE * PIECES as usize; + let (_now, now_ptr, now_gpu) = warp.shared_buffer(size as u64); + let (_hashes, _, hashes_gpu) = warp.shared_buffer(16 * u64::from(PIECES)); + let (_differs, differs_ptr, differs_gpu) = warp.shared_buffer(64); + let content: Vec = (0..size).map(|i| (i * 31 + i / 251) as u8).collect(); + // SAFETY: the mapping holds `size` bytes. + unsafe { std::ptr::copy_nonoverlapping(content.as_ptr(), now_ptr, size) }; + // One pass over the three pieces; what it left in `differs` (7s + // where it stored nothing). + let run = |warp: &mut WarpHarness, mode: u32| -> [u32; 3] { + // SAFETY: our open list, live buffers, the compare's own root + // signature; the mappings hold what is read and written. + unsafe { + for piece in 0..PIECES as usize { + differs_ptr.cast::().add(piece).write_volatile(7); + } + warp.list.SetComputeRootSignature(&compare.root); + warp.list.SetPipelineState(&compare.pso); + let constants = [0u32, 0, size as u32, PIECES, 0, mode]; + warp.list.SetComputeRoot32BitConstants(0, 6, constants.as_ptr().cast(), 0); + warp.list.SetComputeRootShaderResourceView(1, now_gpu); + warp.list.SetComputeRootUnorderedAccessView(2, hashes_gpu); + warp.list.SetComputeRootUnorderedAccessView(3, differs_gpu); + warp.list.Dispatch(PIECES.div_ceil(64), 1, 1); + } + warp.submit_and_wait(); + // SAFETY: as above. + [0, 1, 2].map(|piece| unsafe { differs_ptr.cast::().add(piece).read_volatile() }) + }; + let at = PIECE + 1234; + // SAFETY (each): inside the mapping. + let set = |value: u8| unsafe { now_ptr.add(at).write_volatile(value) }; + // 0: the hashes are stored, nothing is flagged. + assert_eq!(run(&mut warp, 0), [7, 7, 7]); + assert_eq!(run(&mut warp, 1), [0, 0, 0]); + // A change in the second piece: flagged, and with 1 flagged again + // (the hash stays the old one). + set(content[at] ^ 0x40); + assert_eq!(run(&mut warp, 1), [0, 1, 0]); + assert_eq!(run(&mut warp, 1), [0, 1, 0]); + // Changed back: with 1 the piece looks untouched. + set(content[at]); + assert_eq!(run(&mut warp, 1), [0, 0, 0]); + // With 2 the change is flagged once, and the hash is the new one. + set(content[at] ^ 0x40); + assert_eq!(run(&mut warp, 2), [0, 1, 0]); + assert_eq!(run(&mut warp, 2), [0, 0, 0]); + // Changed back: flagged, where 1 saw nothing. + set(content[at]); + assert_eq!(run(&mut warp, 2), [0, 1, 0]); + assert_eq!(run(&mut warp, 2), [0, 0, 0]); + } + + /// The fetch inside flights (`crate::host::CARD_FETCH`), on the software + /// adapter, in one list behind the compare as `Host::card_before` + /// records it: each flagged piece takes a ticket and, while it is + /// within the slots of the lowest ticket in the air, its bytes go to + /// its slot; an unflagged piece's entry says so; a ticket past the + /// slots is written but copies nothing. + #[test] + fn warp_card_fetch_copies_flagged_pieces_to_their_slots() { + use crate::host::{CARD_COMPARE, CARD_FETCH, INFLIGHT_NONE, INFLIGHT_SLOT}; + let Some(mut warp) = WarpHarness::new() else { + return; + }; + let compare = compile_cs(&warp.device, CARD_COMPARE).expect("the card compare must compile on WARP"); + let fetch = compile_cs(&warp.device, CARD_FETCH).expect("the card fetch must compile on WARP"); + const PIECE: usize = 64 << 10; + const PIECES: u32 = 3; + // The copy starts 40 bytes into its piece 0: piece 0 is short, the + // others straddle title pieces and start off a multiple of 16. + const SKEW: u32 = 40; + let size = PIECE * PIECES as usize; + let (_now, now_ptr, now_gpu) = warp.shared_buffer(size as u64); + let (_hashes, _, hashes_gpu) = warp.shared_buffer(16 * u64::from(PIECES + 1)); + let (_differs, _, differs_gpu) = warp.shared_buffer(64); + let (_table, table_ptr, table_gpu) = warp.shared_buffer(4 + 64); + let slots = 1u32; + let (_fetched, fetched_ptr, fetched_gpu) = warp.shared_buffer(INFLIGHT_SLOT * u64::from(slots)); + let content: Vec = (0..size).map(|i| (i * 31 + i / 251) as u8).collect(); + // SAFETY: the mappings hold what is written. + unsafe { + std::ptr::copy_nonoverlapping(content.as_ptr(), now_ptr, size); + table_ptr.cast::().write_volatile(0); + } + let pieces = PIECES + 1; + let run = |warp: &mut WarpHarness, mode: u32, landed: u32| -> Vec { + // SAFETY: our open list, live buffers, the shaders' own root + // signatures; the mappings hold what is read and written. + unsafe { + warp.list.SetComputeRootSignature(&compare.root); + warp.list.SetPipelineState(&compare.pso); + let constants = [0u32, SKEW, size as u32, pieces, 0, mode]; + warp.list.SetComputeRoot32BitConstants(0, 6, constants.as_ptr().cast(), 0); + warp.list.SetComputeRootShaderResourceView(1, now_gpu); + warp.list.SetComputeRootUnorderedAccessView(2, hashes_gpu); + warp.list.SetComputeRootUnorderedAccessView(3, differs_gpu); + warp.list.Dispatch(1, 1, 1); + if mode == 2 { + warp.list.ResourceBarrier(&[uav_barrier()]); + warp.list.SetComputeRootSignature(&fetch.root); + warp.list.SetPipelineState(&fetch.pso); + // Two groups for four pieces: the loop over pieces. + let constants = [0u32, SKEW, size as u32, pieces, 0, landed, slots, 2]; + warp.list.SetComputeRoot32BitConstants(0, 8, constants.as_ptr().cast(), 0); + warp.list.SetComputeRootShaderResourceView(1, now_gpu); + warp.list.SetComputeRootUnorderedAccessView(2, differs_gpu); + warp.list.SetComputeRootUnorderedAccessView(3, table_gpu); + warp.list.SetComputeRootUnorderedAccessView(4, fetched_gpu); + warp.list.Dispatch(2, 1, 1); + } + } + warp.submit_and_wait(); + // SAFETY: as above. + (0..=pieces as usize).map(|i| unsafe { table_ptr.cast::().add(i).read_volatile() }).collect() + }; + // SAFETY (each): inside the mapping of the copy. + let set = |at: usize, value: u8| unsafe { now_ptr.add(at).write_volatile(value) }; + // SAFETY (each): the slot's mapping holds `INFLIGHT_SLOT` bytes. + let slot = |len: usize| unsafe { std::slice::from_raw_parts(fetched_ptr, len).to_vec() }; + run(&mut warp, 0, 0); + // Piece 2 of the copy (title piece 2: bytes 2 * 64 KiB - 40 on), its + // slot from the multiple of 16 below to the one above its end. + let from = 2 * PIECE - SKEW as usize; + let widened = from & !15; + assert_ne!(widened, from); + set(from + 100, content[from + 100] ^ 0x40); + let table = run(&mut warp, 2, 0); + assert_eq!(table, [1, INFLIGHT_NONE, INFLIGHT_NONE, 0, INFLIGHT_NONE]); + let mut wanted = content[widened..widened + INFLIGHT_SLOT as usize].to_vec(); + wanted[from + 100 - widened] ^= 0x40; + assert_eq!(slot(INFLIGHT_SLOT as usize), wanted, "piece 2 in slot 0"); + // Two pieces flagged with one slot, ticket 0 not landed: tickets 1 + // and 2 get none and the slot keeps what it held. + set(5, content[5] ^ 1); + set(PIECE + 7, content[PIECE + 7] ^ 1); + let table = run(&mut warp, 2, 0); + assert_eq!(table[0], 3); + let mut tickets = [table[1], table[2]]; + tickets.sort_unstable(); + assert_eq!(tickets, [1, 2]); + assert_eq!(&table[3..], [INFLIGHT_NONE, INFLIGHT_NONE]); + assert_eq!(slot(INFLIGHT_SLOT as usize), wanted); + // Every ticket up to 2 landed: the next one, 3, gets slot 0. Piece + // 0 starts at the copy's start. + set(9, content[9] ^ 2); + let table = run(&mut warp, 2, 3); + assert_eq!(table, [4, 3, INFLIGHT_NONE, INFLIGHT_NONE, INFLIGHT_NONE]); + let mut piece0 = content[..PIECE - SKEW as usize].to_vec(); + piece0[5] ^= 1; + piece0[9] ^= 2; + assert_eq!(slot(PIECE - SKEW as usize), piece0); + } + + /// The clamp compiles with the system's compiler and the host takes it. + #[test] + fn argument_clamp_builds() { + if super::host().is_none() { + return; // no host GPU here + } + assert!(super::clamp().is_some()); + } + + #[test] + fn rejects_unaligned_or_undersized_layouts() { + assert_eq!(validate_layout((0, 16, 4), 0, None), Some(64)); + assert_eq!(validate_layout((1, 20, 4), 64, Some(128)), Some(80)); + assert_eq!(validate_layout((2, 12, 0), 0, Some(0)), Some(0)); + assert_eq!(validate_layout((10, 16, 2), 8, None), Some(32)); + // Undersized strides for each kind. + assert_eq!(validate_layout((0, 12, 1), 0, None), None); + assert_eq!(validate_layout((1, 16, 1), 0, None), None); + assert_eq!(validate_layout((2, 8, 1), 0, None), None); + assert_eq!(validate_layout((10, 8, 1), 0, None), None); + // Unknown kind. + assert_eq!(validate_layout((3, 16, 1), 0, None), None); + // Unaligned stride, source offset, or count offset. + assert_eq!(validate_layout((0, 18, 1), 0, None), None); + assert_eq!(validate_layout((0, 16, 1), 2, None), None); + assert_eq!(validate_layout((0, 16, 1), 0, Some(6)), None); + // Total byte size exceeding 32-bit ByteAddressBuffer indexing. + assert_eq!(validate_layout((1, 20, u32::MAX), 0, None), None); + } + + /// WARP D3D12 execution test proving: + /// (a) `countBuffer` with a small count (`3`) and `4,093` garbage tail slots + /// (`max = 4096`) does NOT blow `BUDGET` or zero valid dispatches in + /// this or subsequent `ExecuteIndirect` calls in the same list, + /// (b) `src_args` (and `count_buf`) are NOT mutated in-place, and + /// (c) full `stride` bytes (`stride = 24` > `12`) are copied for active + /// records into `dst_args` at offset `0`. + #[test] + fn warp_count_buffer_ignores_garbage_tail_and_preserves_source() { + let Some(mut warp) = WarpHarness::new() else { + return; + }; + const KIND_DISPATCH: u32 = 2; + const STRIDE: u32 = 24; // 6 dwords: 3 dispatch group counts + 3 extra payload dwords + const MAX: u32 = 4096; + const ARGS_OFFSET: usize = 64; // non-zero offset with sentinel prefix + const COUNT_OFFSET_1: usize = 128; + const COUNT_OFFSET_2: usize = 192; + + let src_bytes = ARGS_OFFSET + (STRIDE as usize) * (MAX as usize) + 64; + let (src_buf, src_ptr, _) = warp.shared_buffer(src_bytes as u64); + let (count_buf, count_ptr, _) = warp.shared_buffer(512); + let (_budget_buf, budget_ptr, budget_gpu) = warp.shared_buffer(256); + let (_hits_buf, hits_ptr, hits_gpu) = warp.shared_buffer(256); + let (readback_buf, readback_ptr, _) = warp.shared_buffer((STRIDE * 8) as u64); + let dst_buf = warp.default_uav(u64::from(STRIDE) * u64::from(MAX)); + let sig = warp.signature(KIND_DISPATCH, STRIDE); + + // Fill the entire source buffer with non-zero sentinel bytes, then + // populate 3 valid records at `ARGS_OFFSET` and 4,093 huge garbage + // records in `3..MAX` that would exhaust `BUDGET` ~2,000x over if read. + let mut initial_src = vec![0xA5u8; src_bytes]; + let write_record = |buf: &mut [u8], idx: usize, words: [u32; 6]| { + let base = ARGS_OFFSET + idx * (STRIDE as usize); + for (w, val) in words.into_iter().enumerate() { + buf[base + w * 4..base + (w + 1) * 4].copy_from_slice(&val.to_le_bytes()); + } + }; + write_record( + &mut initial_src, + 0, + [3, 2, 1, 0x1111_2222, 0x3333_4444, 0x5555_6666], + ); + write_record( + &mut initial_src, + 1, + [5, 1, 1, 0x7777_8888, 0x9999_AAAA, 0xBBBB_CCCC], + ); + // Record 2 exceeds 65,535 in X -> clamped to (65535, 1, 1). + write_record( + &mut initial_src, + 2, + [100_000, 1, 1, 0xDDDD_EEEE, 0xFFFF_0001, 0x0123_4567], + ); + for slot in 3..MAX as usize { + // Each garbage slot would clamp to 65535 * 16 * 1 = 1,048,560 groups + // (`cost = 67,107,840 ~= BUDGET / 2`), exhausting `BUDGET` immediately! + write_record( + &mut initial_src, + slot, + [0xFFFF_FFFF, 16, 1, 0xDEAD_BEEF, 0xBAD0_C0DE, slot as u32], + ); + } + + // Second indirect call's source records (at offset 0 of a second buffer, + // or later in `count_buf`): put 2 active records + garbage tail in a + // second range to run back-to-back in the SAME command list. + let mut initial_count = vec![0x5Au8; 512]; + initial_count[COUNT_OFFSET_1..COUNT_OFFSET_1 + 4].copy_from_slice(&3u32.to_le_bytes()); + initial_count[COUNT_OFFSET_2..COUNT_OFFSET_2 + 4].copy_from_slice(&2u32.to_le_bytes()); + + // SAFETY: buffers are mapped with exact capacities above. + unsafe { + std::ptr::copy_nonoverlapping(initial_src.as_ptr(), src_ptr, src_bytes); + std::ptr::copy_nonoverlapping(initial_count.as_ptr(), count_ptr, 512); + (budget_ptr as *mut u32).write_volatile(0); + (hits_ptr as *mut u32).write_volatile(0); + std::ptr::write_bytes(readback_ptr, 0, (STRIDE * 8) as usize); + } + + // Record Call #1 (`eff_count = 3` out of `MAX = 4096`), copy the first + // 5 records of `dst_buf` out for inspection, then record Call #2 + // (`eff_count = 2` out of `MAX = 4096`) reusing `dst_buf` in the same list! + assert!(record_clamp_as( + &warp.clamp, + &warp.list, + (&dst_buf, D3D12_RESOURCE_STATE_COMMON), + budget_gpu, + (&src_buf, ARGS_OFFSET as u64), + Some((&count_buf, COUNT_OFFSET_1 as u64)), + (KIND_DISPATCH, STRIDE, MAX), + false, + )); + // SAFETY: open command list, valid worker PSO/root and buffers. + unsafe { + warp.list.SetComputeRootSignature(&warp.worker.root); + warp.list.SetPipelineState(&warp.worker.pso); + warp.list.SetComputeRootUnorderedAccessView(0, hits_gpu); + warp.list.ExecuteIndirect( + &sig, + MAX, + &dst_buf, + 0, + Some(&count_buf), + COUNT_OFFSET_1 as u64, + ); + } + + // Snapshot `dst_buf` after Call #1 (copy 5 * STRIDE bytes, then leave + // `dst_buf` readable as arguments again, as the clamp left it). + // SAFETY: open command list; the clamp left `dst_buf` in `INDIRECT_ARGUMENT`. + unsafe { + warp.list.ResourceBarrier(&[transition( + &dst_buf, + D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT, + D3D12_RESOURCE_STATE_COPY_SOURCE, + )]); + warp.list + .CopyBufferRegion(&readback_buf, 0, &dst_buf, 0, u64::from(STRIDE * 5)); + warp.list.ResourceBarrier(&[transition( + &dst_buf, + D3D12_RESOURCE_STATE_COPY_SOURCE, + D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT, + )]); + } + + // Call #2 in the SAME command list (`eff_count = 2` -> records 0 and 1: + // 6 + 5 = 11 groups). Would run empty if Call #1's tail blew `BUDGET`! + // The scratch buffer goes straight from arguments back to unordered + // access. + assert!(record_clamp_as( + &warp.clamp, + &warp.list, + (&dst_buf, D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT), + budget_gpu, + (&src_buf, ARGS_OFFSET as u64), + Some((&count_buf, COUNT_OFFSET_2 as u64)), + (KIND_DISPATCH, STRIDE, MAX), + false, + )); + // SAFETY: open command list, valid worker PSO/root and buffers. + unsafe { + warp.list.SetComputeRootSignature(&warp.worker.root); + warp.list.SetPipelineState(&warp.worker.pso); + warp.list.SetComputeRootUnorderedAccessView(0, hits_gpu); + warp.list.ExecuteIndirect( + &sig, + MAX, + &dst_buf, + 0, + Some(&count_buf), + COUNT_OFFSET_2 as u64, + ); + } + + warp.submit_and_wait(); + + // SAFETY: GPU execution finished; read mapped host results. + let (hits, spent, after_src, after_count, clamped_words) = unsafe { + let hits = (hits_ptr as *const u32).read_volatile(); + let spent = (budget_ptr as *const u32).read_volatile(); + let after_src = std::slice::from_raw_parts(src_ptr.cast_const(), src_bytes).to_vec(); + let after_count = std::slice::from_raw_parts(count_ptr.cast_const(), 512).to_vec(); + let words = std::slice::from_raw_parts( + readback_ptr.cast::().cast_const(), + (STRIDE as usize / 4) * 5, + ) + .to_vec(); + (hits, spent, after_src, after_count, words) + }; + + // Call #1: (3*2*1) + (5*1*1) + (65535*1*1) = 65,546 groups. + // Call #2: (3*2*1) + (5*1*1) = 11 groups. + let expected_groups = (6 + 5 + 65_535) + (6 + 5); + assert_eq!( + hits, expected_groups, + "valid indirect dispatches must all execute" + ); + assert_eq!( + spent, + expected_groups * 64, + "budget must reflect only active records below countBuffer" + ); + assert_eq!( + after_src, initial_src, + "src_args must never be mutated in-place" + ); + assert_eq!( + after_count, initial_count, + "count_buf must never be mutated" + ); + + // Check `dst_args` records 0..3: clamped group counts + preserved extra stride words. + assert_eq!( + &clamped_words[0..6], + &[3, 2, 1, 0x1111_2222, 0x3333_4444, 0x5555_6666] + ); + assert_eq!( + &clamped_words[6..12], + &[5, 1, 1, 0x7777_8888, 0x9999_AAAA, 0xBBBB_CCCC] + ); + assert_eq!( + &clamped_words[12..18], + &[65_535, 1, 1, 0xDDDD_EEEE, 0xFFFF_0001, 0x0123_4567] + ); + // Inactive slot 3 was never copied from `src_args`. + assert_ne!(clamped_words[21], 0xDEAD_BEEF); + } + + /// WARP D3D12 test proving `BUDGET` saturates without 32-bit unsigned + /// wraparound across >64 huge indexed-draw records (`count = None`), while + /// preserving `StartIndexLocation`, `BaseVertexLocation`, + /// `StartInstanceLocation`, and custom stride padding, and leaving + /// `src_args` untouched. + /// A window of mesh records clamped ahead: the filled ones come out as + /// they are and are charged, the slots of all ones come out empty and + /// charge nothing; clamped as single records the same slots are clamped + /// to the most and spend the budget. + #[test] + fn gathered_records_must_fit_the_clamp() { + // a mesh record 12 bytes wide at a 4-byte offset of a buffer on a 4-byte address + assert_eq!(gatherable(0x1000, 0x6d71550, (10, 12)), Some(0x6d71550)); + assert_eq!(gatherable(0x1000, 0, (1, 20)), Some(0)); + // not on four bytes, too narrow, too wide, an unknown kind, past 4 GiB + assert_eq!(gatherable(0x1000, 0x6d71552, (10, 12)), None); + assert_eq!(gatherable(0x1002, 0x40, (10, 12)), None); + assert_eq!(gatherable(0x1000, 0x40, (10, 8)), None); + assert_eq!(gatherable(0x1000, 0x40, (10, GATHER_STRIDE + 4)), None); + assert_eq!(gatherable(0x1000, 0x40, (7, 12)), None); + assert_eq!(gatherable(0x1000, 1 << 32, (10, 12)), None); + assert_eq!(gatherable(0x1000, u64::from(u32::MAX) - 3, (10, 12)), None); + } + + #[test] + fn warp_gathered_records_come_out_as_if_clamped_one_by_one() { + let Some(mut warp) = WarpHarness::new() else { + return; + }; + const KIND_MESH: u32 = 10; + const STRIDE: u32 = 12; + // Records scattered through a buffer as the title keeps them: 16 to + // thousands of bytes apart, not in order, one of them twice over + // the budget's most (65,535 groups), one of all ones (garbage). + let records: [(u32, [u32; 3]); 7] = [ + (0x3350, [5, 1, 1]), + (0x0040, [519, 1, 1]), + (0x0050, [0, 1, 1]), + (0x7ff0, [70000, 1, 1]), + (0x1230, [u32::MAX, u32::MAX, u32::MAX]), + (0x0010, [9, 7, 3]), + (0x2000, [1, 0, 0]), + ]; + let total = 0x8000usize; + let mut src = vec![0x5Au8; total]; + for (at, words) in records { + for (w, word) in words.into_iter().enumerate() { + let i = at as usize + w * 4; + src[i..i + 4].copy_from_slice(&word.to_le_bytes()); + } + } + let slots = (GATHER_MOST * STRIDE) as u64; + let (src_buf, src_ptr, _) = warp.shared_buffer(total as u64); + let (_table_buf, table_ptr, table_gpu) = warp.shared_buffer(u64::from(GATHER_MOST) * 4); + let (_budget_buf, budget_ptr, budget_gpu) = warp.shared_buffer(256); + let (readback_buf, readback_ptr, _) = warp.shared_buffer(slots); + let dst_buf = warp.default_uav(slots); + // SAFETY: mapped buffers of these sizes. + unsafe { + std::ptr::copy_nonoverlapping(src.as_ptr(), src_ptr, total); + std::ptr::write_bytes(table_ptr, 0, GATHER_MOST as usize * 4); + for (i, (at, _)) in records.into_iter().enumerate() { + (table_ptr as *mut u32).add(i).write_volatile(at); + } + std::ptr::write_bytes(budget_ptr, 0, 256); + std::ptr::write_bytes(readback_ptr, 0xEE, slots as usize); + } + assert!(record_gather_as( + &warp.clamp, + &warp.list, + (&dst_buf, D3D12_RESOURCE_STATE_COMMON), + budget_gpu, + &src_buf, + table_gpu, + (KIND_MESH, STRIDE, records.len() as u32), + )); + // SAFETY: an open list; the scratch buffer, which the pass left + // readable as arguments, is copied for the check. + unsafe { + warp.list.ResourceBarrier(&[transition( + &dst_buf, + D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT, + D3D12_RESOURCE_STATE_COPY_SOURCE, + )]); + warp.list.CopyBufferRegion(&readback_buf, 0, &dst_buf, 0, slots); + } + warp.submit_and_wait(); + // SAFETY: the work is done; mapped buffers. + let (spent, out) = unsafe { + ( + (budget_ptr as *const u32).read_volatile(), + std::slice::from_raw_parts(readback_ptr.cast::().cast_const(), records.len() * 3).to_vec(), + ) + }; + // Slot i holds record i as the clamp leaves a mesh record clamped + // alone: the groups bounded to 65,535 and the other two to one. + let want: Vec<[u32; 3]> = records.iter().map(|(_, w)| [w[0].min(65535), w[1].min(1), w[2].min(1)]).collect(); + for (i, want) in want.iter().enumerate() { + assert_eq!(&out[i * 3..i * 3 + 3], want, "slot {i} (the record at {:#x})", records[i].0); + } + let charged: u32 = want.iter().map(|w| w[0] * w[1] * w[2] * 128).sum(); + assert_eq!(spent, charged, "each record charged once, as clamped alone"); + // The source is read only. + // SAFETY: a mapped buffer. + assert_eq!(unsafe { std::slice::from_raw_parts(src_ptr.cast_const(), total) }, &src[..]); + } + + #[test] + fn warp_window_leaves_unfilled_slots_empty_and_uncharged() { + let Some(mut warp) = WarpHarness::new() else { + return; + }; + const KIND_MESH: u32 = 10; + const STRIDE: u32 = 32; + const RECORDS: u32 = 16; + let filled = [5u32, 0, 519]; + let total = (STRIDE * RECORDS) as usize; + let mut src = vec![0xffu8; total]; + for (i, groups) in filled.into_iter().enumerate() { + let words = [groups, 1, 1, 0xAB00 + i as u32]; + for (w, word) in words.into_iter().enumerate() { + let at = i * STRIDE as usize + w * 4; + src[at..at + 4].copy_from_slice(&word.to_le_bytes()); + } + } + for ahead in [true, false] { + let (src_buf, src_ptr, _) = warp.shared_buffer(total as u64); + let (_budget_buf, budget_ptr, budget_gpu) = warp.shared_buffer(256); + let (readback_buf, readback_ptr, _) = warp.shared_buffer(total as u64); + let dst_buf = warp.default_uav(total as u64); + // SAFETY: mapped buffers of these sizes. + unsafe { + std::ptr::copy_nonoverlapping(src.as_ptr(), src_ptr, total); + std::ptr::write_bytes(budget_ptr, 0, 256); + std::ptr::write_bytes(readback_ptr, 0, total); + } + assert!(record_clamp_as( + &warp.clamp, + &warp.list, + (&dst_buf, D3D12_RESOURCE_STATE_COMMON), + budget_gpu, + (&src_buf, 0), + None, + (KIND_MESH, STRIDE, RECORDS), + ahead, + )); + // SAFETY: an open list; the scratch buffer, which the clamp left + // readable as arguments, is copied for the check. + unsafe { + warp.list.ResourceBarrier(&[transition( + &dst_buf, + D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT, + D3D12_RESOURCE_STATE_COPY_SOURCE, + )]); + warp.list.CopyBufferRegion(&readback_buf, 0, &dst_buf, 0, total as u64); + } + warp.submit_and_wait(); + // SAFETY: the work is done; mapped buffers. + let (spent, largest, out) = unsafe { + ( + (budget_ptr as *const u32).read_volatile(), + (budget_ptr as *const u32).add(1).read_volatile(), + std::slice::from_raw_parts(readback_ptr.cast::().cast_const(), total / 4).to_vec(), + ) + }; + for (i, groups) in filled.into_iter().enumerate() { + let rec = &out[i * 8..i * 8 + 4]; + assert_eq!(rec, [groups, u32::from(groups > 0).max(1).min(1), 1, 0xAB00 + i as u32], "filled record {i}, ahead {ahead}"); + } + let charged_filled = (5 + 519) * 128; + if ahead { + for i in filled.len()..RECORDS as usize { + assert_eq!(out[i * 8..i * 8 + 3], [0, 0, 0], "unfilled slot {i} must come out empty"); + assert_eq!(out[i * 8 + 3], u32::MAX, "the words after the record are copied as they are"); + } + assert_eq!(spent, charged_filled, "unfilled slots charge nothing"); + assert_eq!(largest, 519, "and are not counted as asked for"); + } else { + // Thirteen slots at 65,535 groups: sixteen would be all of it. + assert_eq!(spent, charged_filled + 13 * 65535 * 128, "clamped one by one, each slot is charged the most"); + assert_eq!(largest, u32::MAX); + } + } + } + + #[test] + fn warp_budget_saturates_without_wraparound_and_preserves_draw_fields() { + let Some(mut warp) = WarpHarness::new() else { + return; + }; + const KIND_INDEXED: u32 = 1; + const STRIDE: u32 = 24; // 5 indexed-draw words + 1 trailing custom word + const RECORDS: u32 = 128; // 2 waves of 64: old InterlockedAdd wrapped 2^32 at 64! + const BUDGET_CAP: u32 = 1 << 27; + + let total_bytes = (STRIDE * RECORDS) as usize; + let (src_buf, src_ptr, _) = warp.shared_buffer(total_bytes as u64); + let (_budget_buf, budget_ptr, budget_gpu) = warp.shared_buffer(256); + let (readback_buf, readback_ptr, _) = warp.shared_buffer(total_bytes as u64); + let dst_buf = warp.default_uav(total_bytes as u64); + + let mut initial_src = vec![0u8; total_bytes]; + for i in 0..RECORDS as usize { + // The first record is no draw (2^24 indices): it runs empty + // and charges nothing. + let words: [u32; 6] = [ + if i == 0 { 1 << 24 } else { 1 << 22 }, // IndexCount + if i == 0 { 1 } else { u32::MAX }, // InstanceCount -> clamps to 16 (cost = 1 << 26) + 1000 + i as u32, // StartIndexLocation + (-200i32 + i as i32) as u32, // BaseVertexLocation + 5000 + i as u32, // StartInstanceLocation + 0xCAFE_0000 | (i as u32), // Extra stride word + ]; + let base = i * (STRIDE as usize); + for (w, val) in words.into_iter().enumerate() { + initial_src[base + w * 4..base + (w + 1) * 4].copy_from_slice(&val.to_le_bytes()); + } + } + + // SAFETY: mapped buffers have sufficient capacity. + unsafe { + std::ptr::copy_nonoverlapping(initial_src.as_ptr(), src_ptr, total_bytes); + (budget_ptr as *mut u32).write_volatile(0); + std::ptr::write_bytes(readback_ptr, 0, total_bytes); + } + + assert!(record_clamp_as( + &warp.clamp, + &warp.list, + (&dst_buf, D3D12_RESOURCE_STATE_COMMON), + budget_gpu, + (&src_buf, 0), + None, + (KIND_INDEXED, STRIDE, RECORDS), + false, + )); + + // SAFETY: open command list; copy clamped scratch buffer (left + // readable as arguments) for verification. + unsafe { + warp.list.ResourceBarrier(&[transition( + &dst_buf, + D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT, + D3D12_RESOURCE_STATE_COPY_SOURCE, + )]); + warp.list + .CopyBufferRegion(&readback_buf, 0, &dst_buf, 0, total_bytes as u64); + } + warp.submit_and_wait(); + + // SAFETY: GPU work completed. + let (spent, after_src, out_words) = unsafe { + let spent = (budget_ptr as *const u32).read_volatile(); + let after_src = std::slice::from_raw_parts(src_ptr.cast_const(), total_bytes).to_vec(); + let out_words = std::slice::from_raw_parts( + readback_ptr.cast::().cast_const(), + total_bytes / 4, + ) + .to_vec(); + (spent, after_src, out_words) + }; + + assert_eq!( + spent, BUDGET_CAP, + "budget must saturate at BUDGET without wrapping" + ); + assert_eq!(after_src, initial_src, "src_args must remain untouched"); + + let mut kept = 0usize; + let mut zeroed = 0usize; + for i in 0..RECORDS as usize { + let rec = &out_words[i * 6..(i + 1) * 6]; + if rec[0] == (1 << 22) && rec[1] == 16 { + assert!(i == 1 || i == 2, "the first two real draws fit the budget"); + kept += 1; + } else { + assert_eq!((rec[0], rec[1]), (0, 0), "excess draw must be zeroed"); + zeroed += 1; + } + assert_eq!(rec[2], 1000 + i as u32); + assert_eq!(rec[3], (-200i32 + i as i32) as u32); + assert_eq!(rec[4], 5000 + i as u32); + assert_eq!(rec[5], 0xCAFE_0000 | (i as u32)); + } + assert_eq!((kept, zeroed), (2, (RECORDS as usize) - 2)); + } + + /// Exercises `HostList::indirect_scratch`, `bound`, the scratch buffer's + /// tracked state, `Host::execute`, and `HostList::reset` end-to-end on + /// the host device. + #[test] + fn host_list_reuses_and_grows_scratch_across_submissions() { + let Some(host) = super::host() else { + return; + }; + // What earlier tests left in the debug layer's queue, if it is on. + let _ = host.log_messages(); + let Ok(list) = host.new_list() else { + return; + }; + let Some((src_buf, src_ptr)) = host.shared_buffer(256 << 10) else { + return; + }; + let Some((count_buf, count_ptr)) = host.shared_buffer(256) else { + return; + }; + // SAFETY: mapped host buffers. + unsafe { + std::ptr::write_bytes(src_ptr, 0x7F, 256 << 10); + (count_ptr as *mut u32).write_volatile(2); + } + + let args = D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT; + // First two calls fit inside the initial 64 KiB scratch buffer and + // must reuse the exact same `ID3D12Resource`, which stays readable + // as arguments between them. + let b1 = bound(&list, (&src_buf, 0), Some((&count_buf, 0)), (0, 16, 64)).unwrap(); + assert_eq!( + list.indirect_state(&b1), + args, + "a clamp leaves the scratch readable as arguments" + ); + let b2 = bound(&list, (&src_buf, 64), Some((&count_buf, 0)), (1, 20, 128)).unwrap(); + assert_eq!( + b1.as_raw(), + b2.as_raw(), + "scratch buffer within capacity must be reused" + ); + assert_eq!(list.indirect_state(&b2), args); + + // A call needing >64 KiB grows the scratch buffer mid-list while keeping + // `b1` alive until reset. The new buffer starts out common. + let grown = list.indirect_scratch(5000 * 20).unwrap(); + assert_eq!( + list.indirect_state(&grown), + D3D12_RESOURCE_STATE_COMMON, + "a new scratch buffer is common" + ); + let b3 = bound(&list, (&src_buf, 0), Some((&count_buf, 0)), (1, 20, 5000)).unwrap(); + assert_eq!(b3.as_raw(), grown.as_raw()); + assert_ne!( + b3.as_raw(), + b1.as_raw(), + "larger request must grow scratch buffer" + ); + assert_eq!(list.indirect_state(&b3), args); + assert_eq!( + list.indirect_state(&b1), + D3D12_RESOURCE_STATE_COMMON, + "the replaced buffer went back to common" + ); + + list.close(); + // With the debug layer on (`LEONIDA_D3D12_DEBUG=1`, diagnostics): + // every barrier recorded named the state the buffer was in. Read + // before the submission, which moves the messages to the log. + assert_eq!(host.log_messages(), None, "the debug layer found an error"); + host.execute(&[&list]); + list.reset(); + + // After reset, requests up to the grown high-water mark reuse `b3` with + // zero new allocations; the buffer decayed to common when the + // submission ran. + assert_eq!( + list.indirect_state(&b3), + D3D12_RESOURCE_STATE_COMMON, + "a reset list starts with a common scratch buffer" + ); + let b4 = bound(&list, (&src_buf, 0), Some((&count_buf, 0)), (1, 20, 4096)).unwrap(); + assert_eq!( + b4.as_raw(), + b3.as_raw(), + "grown scratch buffer must persist across reset" + ); + assert_eq!(list.indirect_state(&b4), args); + list.close(); + assert_eq!(host.log_messages(), None, "the debug layer found an error"); + host.execute(&[&list]); + list.reset(); + } + + /// A group charges its records in lane order: with 300 left of the + /// budget, the first draw (100) fits, the second (250) does not and + /// takes the rest, and the ones after it run empty. (Racing for the + /// word record by record, which of them fitted was up to the GPU.) + #[test] + fn warp_a_group_charges_its_records_in_lane_order() { + let Some(mut warp) = WarpHarness::new() else { + return; + }; + const KIND_DRAW: u32 = 0; + const STRIDE: u32 = 16; + const BUDGET_CAP: u32 = 1 << 27; + let counts = [100u32, 250, 50, 100]; + let total = counts.len() * STRIDE as usize; + let (src_buf, src_ptr, _) = warp.shared_buffer(total as u64); + let (_budget_buf, budget_ptr, budget_gpu) = warp.shared_buffer(256); + let (readback_buf, readback_ptr, _) = warp.shared_buffer(total as u64); + let dst_buf = warp.default_uav(total as u64); + // SAFETY: mapped buffers of these sizes. + unsafe { + for (i, &count) in counts.iter().enumerate() { + let words = [count, 1, 7, 9]; + std::ptr::copy_nonoverlapping( + words.as_ptr().cast::(), + src_ptr.add(i * STRIDE as usize), + 16, + ); + } + std::ptr::write_bytes(budget_ptr, 0, 256); + (budget_ptr as *mut u32).write_volatile(BUDGET_CAP - 300); + } + assert!(record_clamp_as( + &warp.clamp, + &warp.list, + (&dst_buf, D3D12_RESOURCE_STATE_COMMON), + budget_gpu, + (&src_buf, 0), + None, + (KIND_DRAW, STRIDE, counts.len() as u32), + false, + )); + // SAFETY: an open list; the clamped records are copied for the check. + unsafe { + warp.list.ResourceBarrier(&[transition( + &dst_buf, + D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT, + D3D12_RESOURCE_STATE_COPY_SOURCE, + )]); + warp.list.CopyBufferRegion(&readback_buf, 0, &dst_buf, 0, total as u64); + } + warp.submit_and_wait(); + // SAFETY: the work is done; mapped buffers. + let (spent, out) = unsafe { + ( + (budget_ptr as *const u32).read_volatile(), + std::slice::from_raw_parts(readback_ptr.cast::().cast_const(), total / 4) + .to_vec(), + ) + }; + assert_eq!(out[0..4], [100, 1, 7, 9], "the first record fits"); + for i in 1..counts.len() { + assert_eq!(out[i * 4..i * 4 + 4], [0, 0, 7, 9], "record {i} runs empty"); + } + assert_eq!(spent, BUDGET_CAP, "the record that did not fit took the rest"); + } + + /// The list's budget starts empty at each submission, wherever it + /// lives (the card's copy is zeroed in the list): a recording whose + /// clamps spend all of it is followed, after the reset, by one whose + /// small record still runs. + #[test] + fn host_list_budget_starts_empty_at_each_submission() { + let Some(host) = super::host() else { + return; + }; + let Ok(list) = host.new_list() else { + return; + }; + let _ = host.log_messages(); + let worker = compile_cs(&host.device, WORKER_CS).expect("worker shader must compile"); + const KIND_DISPATCH: u32 = 2; + const STRIDE: u32 = 12; + let signature = { + let arg = D3D12_INDIRECT_ARGUMENT_DESC { + Type: D3D12_INDIRECT_ARGUMENT_TYPE(KIND_DISPATCH as i32), + ..Default::default() + }; + let desc = D3D12_COMMAND_SIGNATURE_DESC { + ByteStride: STRIDE, + NumArgumentDescs: 1, + pArgumentDescs: &arg, + NodeMask: 0, + }; + let mut sig: Option = None; + // SAFETY: a valid single-argument command signature description. + unsafe { + host.device + .CreateCommandSignature(&desc, None::<&ID3D12RootSignature>, &mut sig) + .unwrap(); + } + sig.unwrap() + }; + // Three records of 65,535 x 16 groups: about half the budget each. + let Some((big, big_ptr)) = host.shared_buffer(3 * u64::from(STRIDE)) else { + return; + }; + let Some((small, small_ptr)) = host.shared_buffer(u64::from(STRIDE)) else { + return; + }; + let Some((hits_buf, hits_ptr)) = host.shared_buffer(256) else { + return; + }; + // SAFETY: mapped buffers of these sizes; nothing runs yet. + unsafe { + for i in 0..3 { + let words = [65535u32, 16, 1]; + std::ptr::copy_nonoverlapping( + words.as_ptr().cast::(), + big_ptr.add(i * STRIDE as usize), + 12, + ); + } + std::ptr::copy_nonoverlapping([1u32, 1, 1].as_ptr().cast::(), small_ptr, 12); + std::ptr::write_bytes(hits_ptr, 0, 256); + } + // SAFETY: a live buffer. + let hits_gpu = unsafe { hits_buf.GetGPUVirtualAddress() }; + for round in 0..2 { + // Spends the budget (clamped, not executed), then one group. + bound(&list, (&big, 0), None, (KIND_DISPATCH, STRIDE, 3)).unwrap(); + let scratch = bound(&list, (&small, 0), None, (KIND_DISPATCH, STRIDE, 1)).unwrap(); + // SAFETY: an open list; the worker's root signature and + // pipeline; buffers the test holds until the list has run. + unsafe { + list.list.SetComputeRootSignature(&worker.root); + list.list.SetPipelineState(&worker.pso); + list.list.SetComputeRootUnorderedAccessView(0, hits_gpu); + list.list.ExecuteIndirect(&signature, 1, &scratch, 0, None, 0); + } + list.close(); + assert_eq!(host.log_messages(), None, "the debug layer found an error"); + host.execute(&[&list]); + list.reset(); + // SAFETY: the list has run; a mapped buffer. + let hits = unsafe { (hits_ptr as *const u32).read_volatile() }; + // The small record comes after the big ones spent the budget: + // it runs empty, in every round alike (none carries over). + assert_eq!(hits, 0, "round {round}: the spent budget empties the record after it"); + } + // A recording with only the small record: the budget is empty + // again, so it runs. + let scratch = bound(&list, (&small, 0), None, (KIND_DISPATCH, STRIDE, 1)).unwrap(); + // SAFETY: as above. + unsafe { + list.list.SetComputeRootSignature(&worker.root); + list.list.SetPipelineState(&worker.pso); + list.list.SetComputeRootUnorderedAccessView(0, hits_gpu); + list.list.ExecuteIndirect(&signature, 1, &scratch, 0, None, 0); + } + list.close(); + assert_eq!(host.log_messages(), None, "the debug layer found an error"); + host.execute(&[&list]); + list.reset(); + // SAFETY: the list has run; a mapped buffer. + let hits = unsafe { (hits_ptr as *const u32).read_volatile() }; + assert_eq!(hits, 1, "the budget starts empty at the next submission"); + } + + /// The window check: a record nothing wrote since its window clamped + /// it compares equal; one written on the card after the window's clamp + /// (an untracked writer) is found, and named as the window had it and + /// as it is now. + #[test] + fn host_list_window_check_finds_a_record_written_under_its_window() { + let Some(host) = super::host() else { + return; + }; + let Ok(list) = host.new_list() else { + return; + }; + let _ = host.log_messages(); + const KIND_DISPATCH: u32 = 2; + const STEP: u32 = 32; + let records = [[3u32, 1, 1], [5, 1, 1], [7, 1, 1], [9, 1, 1]]; + let total = records.len() * STEP as usize; + let (Some((src, src_ptr)), Some((patch, patch_ptr))) = + (host.shared_buffer(total as u64), host.shared_buffer(64)) + else { + return; + }; + // SAFETY: mapped buffers of these sizes; nothing runs yet. + unsafe { + std::ptr::write_bytes(src_ptr, 0, total); + for (i, words) in records.iter().enumerate() { + std::ptr::copy_nonoverlapping( + words.as_ptr().cast::(), + src_ptr.add(i * STEP as usize), + 12, + ); + } + std::ptr::copy_nonoverlapping([11u32, 2, 1].as_ptr().cast::(), patch_ptr, 12); + } + let spec = (KIND_DISPATCH, STEP, records.len() as u32); + let scratch = bound_ahead(&list, (&src, 0), spec).unwrap(); + // Record 0: nothing wrote it. + assert!(check_hit(&list, (&src, 0), (KIND_DISPATCH, STEP), &scratch, 0)); + // Record 1 is written on the card after the window's clamp. + let read = D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE; + // SAFETY: an open list; `src` was read by the clamp (promoted to a + // shader read), `patch` is common; both live until the list has run. + unsafe { + list.list.ResourceBarrier(&[transition(&src, read, D3D12_RESOURCE_STATE_COPY_DEST)]); + list.list.CopyBufferRegion(&src, u64::from(STEP), &patch, 0, 12); + list.list.ResourceBarrier(&[transition(&src, D3D12_RESOURCE_STATE_COPY_DEST, read)]); + } + let at = u64::from(STEP); + assert!(check_hit(&list, (&src, at), (KIND_DISPATCH, STEP), &scratch, at)); + list.close(); + assert_eq!(host.log_messages(), None, "the debug layer found an error"); + host.execute(&[&list]); + let (checked, differed, window, fresh) = list.window_check().unwrap().take(); + list.reset(); + assert_eq!((checked, differed), (2, 1), "two checks, the written record differs"); + assert_eq!(window[..3], [5, 1, 1], "as the window clamped it"); + assert_eq!(fresh[..3], [11, 2, 1], "as it is now"); + } + + /// Records the dispatch records `groups` (three words each, `step` + /// bytes apart, the rest of each record ones) into a fresh mapped + /// buffer of `warp`'s device. + fn dispatch_records(warp: &WarpHarness, groups: &[u32], step: u32) -> ID3D12Resource { + let total = groups.len() * step as usize; + let (buffer, ptr, _) = warp.shared_buffer(total as u64); + let mut bytes = vec![0xffu8; total]; + for (i, &g) in groups.iter().enumerate() { + for (w, word) in [g, 1, 1].into_iter().enumerate() { + let at = i * step as usize + w * 4; + bytes[at..at + 4].copy_from_slice(&word.to_le_bytes()); + } + } + // SAFETY: the mapping holds `total` bytes. + unsafe { std::ptr::copy_nonoverlapping(bytes.as_ptr(), ptr, total) }; + buffer + } + + /// Two windows in one list, as `crate::draw` records them: each clamps + /// its records ahead, then one execution per record reads the scratch + /// buffer with no barrier between them; the second clamp moves the + /// scratch buffer straight from arguments back to unordered access. + /// Every record runs once, with the group count it asked for. + #[test] + fn warp_window_executions_read_their_records_with_no_barrier_between() { + let Some(mut warp) = WarpHarness::new() else { + return; + }; + const KIND_DISPATCH: u32 = 2; + // The title names 12 bytes and keeps its records 32 apart. + const STRIDE: u32 = 12; + const STEP: u32 = 32; + let windows: [&[u32]; 2] = [&[1, 2, 3, 4], &[10, 11, 12, 13]]; + let sources: Vec = + windows.iter().map(|g| dispatch_records(&warp, g, STEP)).collect(); + let (_budget_buf, budget_ptr, budget_gpu) = warp.shared_buffer(256); + let (_hits_buf, hits_ptr, hits_gpu) = warp.shared_buffer(256); + let dst_buf = warp.default_uav(u64::from(STEP) * 4); + let sig = warp.signature(KIND_DISPATCH, STRIDE); + // SAFETY: mapped buffers of these sizes. + unsafe { + std::ptr::write_bytes(budget_ptr, 0, 256); + std::ptr::write_bytes(hits_ptr, 0, 256); + } + let mut state = D3D12_RESOURCE_STATE_COMMON; + for (groups, src) in windows.iter().zip(&sources) { + assert!(record_clamp_as( + &warp.clamp, + &warp.list, + (&dst_buf, state), + budget_gpu, + (src, 0), + None, + (KIND_DISPATCH, STEP, groups.len() as u32), + true, + )); + state = D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT; + // SAFETY: an open list; the worker's root signature and + // pipeline; the scratch buffer is readable as arguments. + unsafe { + warp.list.SetComputeRootSignature(&warp.worker.root); + warp.list.SetPipelineState(&warp.worker.pso); + warp.list.SetComputeRootUnorderedAccessView(0, hits_gpu); + for i in 0..groups.len() as u64 { + warp.list.ExecuteIndirect(&sig, 1, &dst_buf, i * u64::from(STEP), None, 0); + } + } + } + warp.submit_and_wait(); + // SAFETY: the work is done; mapped buffers. + let (hits, spent) = unsafe { + ( + (hits_ptr as *const u32).read_volatile(), + (budget_ptr as *const u32).read_volatile(), + ) + }; + let expected: u32 = windows.iter().flat_map(|g| g.iter()).sum(); + assert_eq!(hits, expected, "every record of both windows runs once"); + assert_eq!(spent, expected * 64, "and is charged what it asked for"); + } + + /// The windows of `warp_window_executions_read_their_records_with_no_barrier_between` + /// through a host list (`bound_ahead`, the list's tracked scratch state, + /// `Host::execute`), twice: on the first recording the scratch buffer + /// starts common, on the second (after the reset) it starts common + /// again. With the debug layer on (`LEONIDA_D3D12_DEBUG=1` in a + /// diagnostics build) no barrier names a state the buffer is not in. + #[test] + fn host_list_window_executions_need_no_barrier_of_their_own() { + let Some(host) = super::host() else { + return; + }; + // What earlier tests left in the debug layer's queue, if it is on. + let _ = host.log_messages(); + let Ok(list) = host.new_list() else { + return; + }; + let worker = compile_cs(&host.device, WORKER_CS).expect("worker shader must compile"); + const KIND_DISPATCH: u32 = 2; + const STRIDE: u32 = 12; + const STEP: u32 = 32; + let signature = { + let arg = D3D12_INDIRECT_ARGUMENT_DESC { + Type: D3D12_INDIRECT_ARGUMENT_TYPE(KIND_DISPATCH as i32), + ..Default::default() + }; + let desc = D3D12_COMMAND_SIGNATURE_DESC { + ByteStride: STRIDE, + NumArgumentDescs: 1, + pArgumentDescs: &arg, + NodeMask: 0, + }; + let mut sig: Option = None; + // SAFETY: a valid single-argument command signature description. + unsafe { + host.device + .CreateCommandSignature(&desc, None::<&ID3D12RootSignature>, &mut sig) + .unwrap(); + } + sig.unwrap() + }; + let windows: [&[u32]; 2] = [&[1, 2, 3, 4], &[10, 11, 12, 13]]; + let mut sources = Vec::new(); + for groups in windows { + let total = groups.len() * STEP as usize; + let Some((buffer, ptr)) = host.shared_buffer(total as u64) else { + return; + }; + let mut bytes = vec![0xffu8; total]; + for (i, &g) in groups.iter().enumerate() { + for (w, word) in [g, 1, 1].into_iter().enumerate() { + let at = i * STEP as usize + w * 4; + bytes[at..at + 4].copy_from_slice(&word.to_le_bytes()); + } + } + // SAFETY: the mapping holds `total` bytes. + unsafe { std::ptr::copy_nonoverlapping(bytes.as_ptr(), ptr, total) }; + sources.push(buffer); + } + let Some((hits_buf, hits_ptr)) = host.shared_buffer(256) else { + return; + }; + let expected: u32 = windows.iter().flat_map(|g| g.iter()).sum(); + // SAFETY: a live buffer. + let hits_gpu = unsafe { hits_buf.GetGPUVirtualAddress() }; + for _ in 0..2 { + // SAFETY: the mapping holds 256 bytes; nothing runs. + unsafe { std::ptr::write_bytes(hits_ptr, 0, 256) }; + for (groups, src) in windows.iter().zip(&sources) { + let spec = (KIND_DISPATCH, STEP, groups.len() as u32); + let scratch = bound_ahead(&list, (src, 0), spec).unwrap(); + assert_eq!(list.indirect_state(&scratch), D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT); + // SAFETY: an open list; the worker's root signature and + // pipeline; buffers the test holds until the list has run. + unsafe { + list.list.SetComputeRootSignature(&worker.root); + list.list.SetPipelineState(&worker.pso); + list.list.SetComputeRootUnorderedAccessView(0, hits_gpu); + for i in 0..groups.len() as u64 { + let at = i * u64::from(STEP); + list.list.ExecuteIndirect(&signature, 1, &scratch, at, None, 0); + } + } + } + list.close(); + // With the debug layer on: nothing it objects to was recorded. + // Read before the submission, which moves the messages to the log. + assert_eq!(host.log_messages(), None, "the debug layer found an error"); + host.execute(&[&list]); + list.reset(); + // SAFETY: the list has run; a mapped buffer. + let hits = unsafe { (hits_ptr as *const u32).read_volatile() }; + assert_eq!(hits, expected, "every record of both windows runs once"); + } + } +} + +/// The benchmark of the clamp and its barriers (ignored by default). +#[cfg(test)] +mod bench; + +/// What one small draw costs this card, bare and with one thing changed +/// between every two draws: a measurement, not a check (it asserts only +/// that the card answered). The timing run of the lit scene (run 187) has +/// some 11,000 small commands a frame at 5 to 16 microseconds each, and no +/// log says whether that is what we put around a command or what the card +/// takes for one. Each variant here is 10,000 one-triangle draws into a +/// 2560x1440 target, timed on the card by one pair of timestamps around +/// the whole batch (not one per command, which would time the stamps). +/// +/// Run by name, no game needed: +/// `cargo test -p leonida-gpu --release -- --ignored bare_command_cost --nocapture` +#[cfg(test)] +mod bare_cost { + use windows::Win32::Foundation::{HANDLE, RECT}; + use windows::Win32::Graphics::Direct3D::{D3D_FEATURE_LEVEL_12_0, D3D_PRIMITIVE_TOPOLOGY}; + use windows::Win32::Graphics::Direct3D12::*; + use windows::Win32::Graphics::Dxgi::Common::*; + use windows::Win32::Graphics::Dxgi::*; + use windows::Win32::System::Threading::{CreateEventW, INFINITE, WaitForSingleObject}; + use windows::core::{Interface, s}; + + use crate::host::{compile, transition}; + + /// Draws in a batch. + const DRAWS: u32 = 10_000; + const WIDTH: u32 = 2560; + const HEIGHT: u32 = 1440; + + /// One small triangle in the middle of the target (about 180 pixels), + /// and two pixel programs that read one texel of a texture through a + /// table, so that the view heap set is in use. + const DRAW: &str = r#" +#define RS "DescriptorTable(SRV(t0))" +Texture2D image : register(t0); +[RootSignature(RS)] +float4 corner(uint i : SV_VertexID) : SV_Position { + float2 p = float2((i << 1) & 2, i & 2); + return float4(p * 0.02 - 0.01, 0.5, 1.0); +} +[RootSignature(RS)] +float4 first(float4 at : SV_Position) : SV_Target { + return image.Load(int3(0, 0, 0)); +} +[RootSignature(RS)] +float4 second(float4 at : SV_Position) : SV_Target { + return 1.0 - image.Load(int3(0, 0, 0)); +} +"#; + + /// A compute pass of next to nothing, as our clamp of an indirect + /// record is: one group of one thread that writes one word. + const WORK: &str = r#" +#define RS "UAV(u0)" +RWByteAddressBuffer words : register(u0); +[RootSignature(RS)] +[numthreads(1, 1, 1)] +void work() { + words.Store(0, words.Load(0) + 1); +} +"#; + + /// What changes between every two draws of a batch. + #[derive(Clone, Copy, PartialEq)] + enum Between { + /// Nothing. + Nothing, + /// The pipeline: two alternate. + Pipeline, + /// A second texture goes from target to shader read and back. + BarrierPair, + /// The depth texture bound for testing goes from write to read or + /// back. + DepthMove, + /// The pair of descriptor heaps: two pairs alternate. + Heaps, + /// The colour target: two alternate. + Targets, + /// A compute pass of ours of one group, and the pipeline back. + Compute, + /// The same between two waits for every earlier shader write, as + /// the clamp records them. + ComputeWithWaits, + } + + struct Rig { + queue: ID3D12CommandQueue, + allocator: ID3D12CommandAllocator, + list: ID3D12GraphicsCommandList, + fence: ID3D12Fence, + submitted: u64, + event: HANDLE, + root: ID3D12RootSignature, + pipelines: [ID3D12PipelineState; 2], + work_root: ID3D12RootSignature, + work: ID3D12PipelineState, + words: ID3D12Resource, + other: ID3D12Resource, + depth: ID3D12Resource, + /// Kept alive: the views below name them. + _kept: Vec, + _target_heaps: [ID3D12DescriptorHeap; 2], + heap_pairs: [[Option; 2]; 2], + tables: [D3D12_GPU_DESCRIPTOR_HANDLE; 2], + targets: [D3D12_CPU_DESCRIPTOR_HANDLE; 2], + depth_written: D3D12_CPU_DESCRIPTOR_HANDLE, + depth_tested: D3D12_CPU_DESCRIPTOR_HANDLE, + stamps: ID3D12QueryHeap, + back: ID3D12Resource, + card: String, + } + + fn texture( + device: &ID3D12Device, + (width, height): (u32, u32), + format: DXGI_FORMAT, + flags: D3D12_RESOURCE_FLAGS, + state: D3D12_RESOURCE_STATES, + ) -> ID3D12Resource { + let heap = D3D12_HEAP_PROPERTIES { + Type: D3D12_HEAP_TYPE_DEFAULT, + ..Default::default() + }; + let desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D, + Width: u64::from(width), + Height: height, + DepthOrArraySize: 1, + MipLevels: 1, + Format: format, + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Flags: flags, + ..Default::default() + }; + let mut out: Option = None; + // SAFETY: plain texture creation. + unsafe { + device + .CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &desc, state, None, &mut out) + .unwrap(); + } + out.unwrap() + } + + fn buffer( + device: &ID3D12Device, + size: u64, + kind: D3D12_HEAP_TYPE, + flags: D3D12_RESOURCE_FLAGS, + state: D3D12_RESOURCE_STATES, + ) -> ID3D12Resource { + let heap = D3D12_HEAP_PROPERTIES { + Type: kind, + ..Default::default() + }; + let desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, + Width: size, + Height: 1, + DepthOrArraySize: 1, + MipLevels: 1, + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, + Flags: flags, + ..Default::default() + }; + let mut out: Option = None; + // SAFETY: plain buffer creation. + unsafe { + device + .CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &desc, state, None, &mut out) + .unwrap(); + } + out.unwrap() + } + + fn heap(device: &ID3D12Device, kind: D3D12_DESCRIPTOR_HEAP_TYPE, count: u32, visible: bool) -> ID3D12DescriptorHeap { + let flags = if visible { + D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE + } else { + D3D12_DESCRIPTOR_HEAP_FLAG_NONE + }; + // SAFETY: plain heap creation. + unsafe { + device + .CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC { + Type: kind, + NumDescriptors: count, + Flags: flags, + NodeMask: 0, + }) + .unwrap() + } + } + + fn pipeline(device: &ID3D12Device, root: &ID3D12RootSignature, vs: &[u8], ps: &[u8]) -> ID3D12PipelineState { + let code = |bytes: &[u8]| D3D12_SHADER_BYTECODE { + pShaderBytecode: bytes.as_ptr().cast(), + BytecodeLength: bytes.len(), + }; + let mut blend = D3D12_BLEND_DESC::default(); + blend.RenderTarget[0].RenderTargetWriteMask = 0xf; + let mut formats = [DXGI_FORMAT(0); 8]; + formats[0] = DXGI_FORMAT_R8G8B8A8_UNORM; + // SAFETY: the description points at live data and never releases + // its pointer to the root signature. + unsafe { + let desc = D3D12_GRAPHICS_PIPELINE_STATE_DESC { + pRootSignature: std::mem::transmute_copy(root), + VS: code(vs), + PS: code(ps), + BlendState: blend, + SampleMask: u32::MAX, + RasterizerState: D3D12_RASTERIZER_DESC { + FillMode: D3D12_FILL_MODE_SOLID, + CullMode: D3D12_CULL_MODE_NONE, + DepthClipEnable: true.into(), + ..Default::default() + }, + // Depth is tested and never written, so the texture may be + // in the write state or in the read state under one view. + DepthStencilState: D3D12_DEPTH_STENCIL_DESC { + DepthEnable: true.into(), + DepthWriteMask: D3D12_DEPTH_WRITE_MASK_ZERO, + DepthFunc: D3D12_COMPARISON_FUNC_LESS_EQUAL, + ..Default::default() + }, + PrimitiveTopologyType: D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE, + NumRenderTargets: 1, + RTVFormats: formats, + DSVFormat: DXGI_FORMAT_D32_FLOAT, + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + ..Default::default() + }; + device.CreateGraphicsPipelineState(&desc).unwrap() + } + } + + impl Rig { + /// The default adapter, as the layer takes it; `None` without one + /// or on a software adapter. + fn new() -> Option { + let vs = compile(DRAW, s!("corner"), s!("vs_5_1")).ok()?; + let ps = [ + compile(DRAW, s!("first"), s!("ps_5_1")).ok()?, + compile(DRAW, s!("second"), s!("ps_5_1")).ok()?, + ]; + let cs = compile(WORK, s!("work"), s!("cs_5_1")).ok()?; + // SAFETY: plain object creation on a device of our own; the + // views are made in heaps that live as long as the rig. + unsafe { + let mut device: Option = None; + D3D12CreateDevice(None, D3D_FEATURE_LEVEL_12_0, &mut device).ok()?; + let device = device?; + let desc = CreateDXGIFactory2::(DXGI_CREATE_FACTORY_FLAGS(0)) + .and_then(|factory| factory.EnumAdapterByLuid::(device.GetAdapterLuid())) + .ok()? + .cast::() + .ok()? + .GetDesc1() + .ok()?; + if desc.Flags & DXGI_ADAPTER_FLAG_SOFTWARE.0 as u32 != 0 { + return None; + } + let card = String::from_utf16_lossy(&desc.Description) + .trim_end_matches('\0') + .to_owned(); + let queue: ID3D12CommandQueue = device + .CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC { + Type: D3D12_COMMAND_LIST_TYPE_DIRECT, + ..Default::default() + }) + .ok()?; + let allocator: ID3D12CommandAllocator = + device.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT).ok()?; + let list: ID3D12GraphicsCommandList = device + .CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &allocator, None) + .ok()?; + let fence: ID3D12Fence = device.CreateFence(0, D3D12_FENCE_FLAG_NONE).ok()?; + let event = CreateEventW(None, false, false, None).ok()?; + + let root: ID3D12RootSignature = device.CreateRootSignature(0, &vs[..]).ok()?; + let pipelines = [ + pipeline(&device, &root, &vs, &ps[0]), + pipeline(&device, &root, &vs, &ps[1]), + ]; + let work_root: ID3D12RootSignature = device.CreateRootSignature(0, &cs[..]).ok()?; + let work: ID3D12PipelineState = device + .CreateComputePipelineState(&D3D12_COMPUTE_PIPELINE_STATE_DESC { + pRootSignature: std::mem::transmute_copy(&work_root), + CS: D3D12_SHADER_BYTECODE { + pShaderBytecode: cs.as_ptr().cast(), + BytecodeLength: cs.len(), + }, + ..Default::default() + }) + .ok()?; + + let size = (WIDTH, HEIGHT); + let colour = |state| texture(&device, size, DXGI_FORMAT_R8G8B8A8_UNORM, D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET, state); + let target = [ + colour(D3D12_RESOURCE_STATE_RENDER_TARGET), + colour(D3D12_RESOURCE_STATE_RENDER_TARGET), + ]; + let other = colour(D3D12_RESOURCE_STATE_RENDER_TARGET); + let depth = texture( + &device, + size, + DXGI_FORMAT_D32_FLOAT, + D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL, + D3D12_RESOURCE_STATE_DEPTH_WRITE, + ); + let image = texture( + &device, + (4, 4), + DXGI_FORMAT_R8G8B8A8_UNORM, + D3D12_RESOURCE_FLAG_NONE, + D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE, + ); + let words = buffer( + &device, + 64 << 10, + D3D12_HEAP_TYPE_DEFAULT, + D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS, + D3D12_RESOURCE_STATE_UNORDERED_ACCESS, + ); + let back = buffer( + &device, + 16, + D3D12_HEAP_TYPE_READBACK, + D3D12_RESOURCE_FLAG_NONE, + D3D12_RESOURCE_STATE_COPY_DEST, + ); + let mut stamps: Option = None; + device + .CreateQueryHeap( + &D3D12_QUERY_HEAP_DESC { + Type: D3D12_QUERY_HEAP_TYPE_TIMESTAMP, + Count: 2, + NodeMask: 0, + }, + &mut stamps, + ) + .ok()?; + let stamps = stamps?; + + // Target and depth views. + let rtvs = heap(&device, D3D12_DESCRIPTOR_HEAP_TYPE_RTV, 2, false); + let rtv_step = device.GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_RTV) as usize; + let mut targets = [rtvs.GetCPUDescriptorHandleForHeapStart(); 2]; + targets[1].ptr += rtv_step; + device.CreateRenderTargetView(&target[0], None, targets[0]); + device.CreateRenderTargetView(&target[1], None, targets[1]); + let dsvs = heap(&device, D3D12_DESCRIPTOR_HEAP_TYPE_DSV, 2, false); + let dsv_step = device.GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_DSV) as usize; + let depth_written = dsvs.GetCPUDescriptorHandleForHeapStart(); + let mut depth_tested = depth_written; + depth_tested.ptr += dsv_step; + device.CreateDepthStencilView(&depth, None, depth_written); + let tested = D3D12_DEPTH_STENCIL_VIEW_DESC { + Format: DXGI_FORMAT_D32_FLOAT, + ViewDimension: D3D12_DSV_DIMENSION_TEXTURE2D, + Flags: D3D12_DSV_FLAG_READ_ONLY_DEPTH, + ..Default::default() + }; + device.CreateDepthStencilView(&depth, Some(&tested), depth_tested); + + // Two pairs of shader-visible heaps: views (one view of the + // small texture each) and samplers (none used). + let view_heaps = [ + heap(&device, D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, 1, true), + heap(&device, D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, 1, true), + ]; + let sampler_heaps = [ + heap(&device, D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER, 1, true), + heap(&device, D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER, 1, true), + ]; + for views in &view_heaps { + device.CreateShaderResourceView(&image, None, views.GetCPUDescriptorHandleForHeapStart()); + } + let tables = [ + view_heaps[0].GetGPUDescriptorHandleForHeapStart(), + view_heaps[1].GetGPUDescriptorHandleForHeapStart(), + ]; + let heap_pairs = [ + [Some(view_heaps[0].clone()), Some(sampler_heaps[0].clone())], + [Some(view_heaps[1].clone()), Some(sampler_heaps[1].clone())], + ]; + + // The first list: both targets and the depth texture cleared. + list.ClearRenderTargetView(targets[0], &[0.0; 4], None); + list.ClearRenderTargetView(targets[1], &[0.0; 4], None); + list.ClearDepthStencilView(depth_written, D3D12_CLEAR_FLAG_DEPTH, 1.0, 0, None); + let [first_target, second_target] = target; + let mut rig = Rig { + queue, + allocator, + list, + fence, + submitted: 0, + event, + root, + pipelines, + work_root, + work, + words, + other, + depth, + _kept: vec![first_target, second_target, image], + _target_heaps: [rtvs, dsvs], + heap_pairs, + tables, + targets, + depth_written, + depth_tested, + stamps, + back, + card, + }; + rig.finish(); + Some(rig) + } + } + + /// Closes the open list, runs it, waits for the card and opens the + /// list again. + fn finish(&mut self) { + self.submitted += 1; + // SAFETY: our list, queue and fence; the allocator is reset + // only after the card finished everything recorded from it. + unsafe { + self.list.Close().unwrap(); + let run: ID3D12CommandList = self.list.cast().unwrap(); + self.queue.ExecuteCommandLists(&[Some(run)]); + self.queue.Signal(&self.fence, self.submitted).unwrap(); + self.fence.SetEventOnCompletion(self.submitted, self.event).unwrap(); + WaitForSingleObject(self.event, INFINITE); + self.allocator.Reset().unwrap(); + self.list.Reset(&self.allocator, None).unwrap(); + } + } + + /// What every list starts with: a new list has nothing set. + fn begin(&self) { + let l = &self.list; + // SAFETY: an open list and live objects and views. + unsafe { + l.SetDescriptorHeaps(&self.heap_pairs[0]); + l.SetGraphicsRootSignature(&self.root); + l.SetPipelineState(&self.pipelines[0]); + l.SetGraphicsRootDescriptorTable(0, self.tables[0]); + l.OMSetRenderTargets(1, Some(&self.targets[0]), false, Some(&self.depth_tested)); + l.RSSetViewports(&[D3D12_VIEWPORT { + TopLeftX: 0.0, + TopLeftY: 0.0, + Width: WIDTH as f32, + Height: HEIGHT as f32, + MinDepth: 0.0, + MaxDepth: 1.0, + }]); + l.RSSetScissorRects(&[RECT { + left: 0, + top: 0, + right: WIDTH as i32, + bottom: HEIGHT as i32, + }]); + // A triangle list. + l.IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY(4)); + } + } + + /// One batch of [`DRAWS`] draws in `lists` lists run one by one, + /// with `between` recorded before every draw: the microseconds a + /// draw took on the card, and the milliseconds recording took. + fn batch(&mut self, between: Between, lists: u32) -> (f64, f64) { + let (target, read, written, tested) = ( + D3D12_RESOURCE_STATE_RENDER_TARGET, + D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE, + D3D12_RESOURCE_STATE_DEPTH_WRITE, + D3D12_RESOURCE_STATE_DEPTH_READ, + ); + let started = std::time::Instant::now(); + let mut drawn = 0u32; + for part in 0..lists { + let l = &self.list; + // SAFETY: an open list; our query heap; live objects. + unsafe { + if part == 0 { + l.EndQuery(&self.stamps, D3D12_QUERY_TYPE_TIMESTAMP, 0); + } + } + self.begin(); + // SAFETY: an open list with everything set; live objects. + // Every state moved is moved back within the batch (the + // draws of a list are an even number). + unsafe { + for _ in 0..DRAWS / lists { + let odd = (drawn % 2) as usize; + match between { + Between::Nothing => {} + Between::Pipeline => l.SetPipelineState(&self.pipelines[odd]), + Between::BarrierPair => { + l.ResourceBarrier(&[transition(&self.other, target, read)]); + l.ResourceBarrier(&[transition(&self.other, read, target)]); + } + Between::DepthMove => { + let (from, to) = if odd == 0 { (written, tested) } else { (tested, written) }; + l.ResourceBarrier(&[transition(&self.depth, from, to)]); + } + Between::Heaps => { + l.SetDescriptorHeaps(&self.heap_pairs[odd]); + l.SetGraphicsRootDescriptorTable(0, self.tables[odd]); + } + Between::Targets => { + l.OMSetRenderTargets(1, Some(&self.targets[odd]), false, Some(&self.depth_tested)); + } + Between::Compute | Between::ComputeWithWaits => { + let waits = between == Between::ComputeWithWaits; + if waits { + l.ResourceBarrier(&[super::uav_barrier()]); + } + l.SetComputeRootSignature(&self.work_root); + l.SetPipelineState(&self.work); + l.SetComputeRootUnorderedAccessView(0, self.words.GetGPUVirtualAddress()); + l.Dispatch(1, 1, 1); + if waits { + l.ResourceBarrier(&[super::uav_barrier()]); + } + l.SetPipelineState(&self.pipelines[0]); + } + } + l.DrawInstanced(3, 1, 0, 0); + drawn += 1; + } + if part + 1 < lists { + // The next list of the batch: this one is sent on + // its own and the list is opened again at once + // (the allocator is not reset before the card is + // done with all of them). + l.Close().unwrap(); + let run: ID3D12CommandList = l.cast().unwrap(); + self.queue.ExecuteCommandLists(&[Some(run)]); + l.Reset(&self.allocator, None).unwrap(); + } else { + l.EndQuery(&self.stamps, D3D12_QUERY_TYPE_TIMESTAMP, 1); + l.ResolveQueryData(&self.stamps, D3D12_QUERY_TYPE_TIMESTAMP, 0, 2, &self.back, 0); + } + } + } + let recording = started.elapsed().as_secs_f64() * 1e3; + self.finish(); + let mut data = std::ptr::null_mut(); + let range = D3D12_RANGE { Begin: 0, End: 16 }; + // SAFETY: a read-back buffer the finished list resolved two + // timestamps into. + let ticks = unsafe { + self.back.Map(0, Some(&range), Some(&mut data)).unwrap(); + let stamps = std::slice::from_raw_parts(data.cast::(), 2).to_vec(); + self.back.Unmap(0, None); + stamps[1].saturating_sub(stamps[0]) + }; + // SAFETY: a plain query of our queue. + let frequency = unsafe { self.queue.GetTimestampFrequency() }.unwrap_or(1).max(1); + (ticks as f64 * 1e6 / frequency as f64 / f64::from(drawn.max(1)), recording) + } + } + + #[test] + #[ignore = "a measurement on the card: run it by name with --ignored --nocapture"] + fn bare_command_cost() { + let Some(mut rig) = Rig::new() else { + eprintln!("no hardware adapter, or our shaders did not compile; skipped"); + return; + }; + eprintln!("bare command cost on {}: {DRAWS} one-triangle draws into {WIDTH}x{HEIGHT}, three batches each", rig.card); + // The first batch pays for whatever the driver does at first use. + rig.batch(Between::Nothing, 1); + let variants = [ + ("(a) nothing changes between draws", Between::Nothing, 1), + ("(b) another pipeline every draw", Between::Pipeline, 1), + ("(c) a barrier pair on a second texture every draw", Between::BarrierPair, 1), + ("(d) the tested depth texture moved between write and read every draw", Between::DepthMove, 1), + ("(e) another pair of descriptor heaps every draw", Between::Heaps, 1), + ("(f) another colour target every draw", Between::Targets, 1), + ("(g) nothing changes, in 100 lists run one by one", Between::Nothing, 100), + ("(h) a compute pass of ours of one group before every draw", Between::Compute, 1), + ("(i) the same pass between two waits for earlier shader writes", Between::ComputeWithWaits, 1), + ]; + let mut least = Vec::new(); + for (name, between, lists) in variants { + let mut runs: Vec<(f64, f64)> = (0..3).map(|_| rig.batch(between, lists)).collect(); + runs.sort_by(|a, b| a.0.total_cmp(&b.0)); + eprintln!( + "{name}: {:.2} microseconds a draw on the card (the three: {:.2}, {:.2}, {:.2}); recording took {:.1} ms", + runs[0].0, runs[0].0, runs[1].0, runs[2].0, runs[0].1 + ); + least.push(runs[0].0); + } + assert!(least.iter().all(|us| us.is_finite() && *us > 0.0), "the card gave no time for a batch"); + } +} diff --git a/crates/leonida-gpu/src/indirect/bench.rs b/crates/leonida-gpu/src/indirect/bench.rs new file mode 100644 index 000000000..654129b62 --- /dev/null +++ b/crates/leonida-gpu/src/indirect/bench.rs @@ -0,0 +1,502 @@ +//! A frame's worth of one-record indirect draws on the host GPU, clamped one +//! at a time and in windows, recorded as `main` does (the scratch buffer +//! back to the common state after every execution, the clamp charging the +//! budget record by record) and as this tree does (readable until the next +//! clamp, one charge per group). Ignored by default; run it with +//! `cargo test -p leonida-gpu --release --lib indirect::bench -- --ignored --nocapture`. +//! It needs no title files: the draws are tiny triangles of ours. + +use super::*; +use windows::Win32::Foundation::RECT; +use windows::Win32::Graphics::Dxgi::Common::{DXGI_FORMAT_R8G8B8A8_UNORM, DXGI_SAMPLE_DESC}; +use windows::Win32::Graphics::Dxgi::{ + CreateDXGIFactory2, DXGI_CREATE_FACTORY_FLAGS, IDXGIFactory4, +}; +use windows::Win32::System::Threading::{CreateEventW, INFINITE, WaitForSingleObject}; +use windows::core::{Interface, PCSTR}; + +/// Draws a frame (the title's gameplay frames hold about 3,200 indirect +/// executions, #107), records a window holds, and how far apart the +/// records are (the title keeps them 32 bytes apart). +const DRAWS: u32 = 3200; +const WINDOW: u32 = 32; +const STEP: u32 = 32; +const RUNS: usize = 9; + +const SHADERS: &str = r#" +#define RS "RootFlags(0)" +[RootSignature(RS)] +float4 vs(uint v : SV_VertexID, uint i : SV_InstanceID) : SV_Position { +float2 p = float2((v & 1) ? 0.05 : 0.0, (v & 2) ? 0.05 : 0.0) - 0.5; +return float4(p, 0.5, 1); +} +float4 ps() : SV_Target { return float4(1, 0.5, 0.25, 1); } +"#; + +fn compile(entry: &str, target: &str) -> Vec { + let entry = std::ffi::CString::new(entry).unwrap(); + let target = std::ffi::CString::new(target).unwrap(); + let mut code: Option = None; + // SAFETY: the source and names outlive the call. + unsafe { + D3DCompile( + SHADERS.as_ptr().cast(), + SHADERS.len(), + s!("bench"), + None, + None, + PCSTR(entry.as_ptr().cast()), + PCSTR(target.as_ptr().cast()), + 0, + 0, + &mut code, + None, + ) + .unwrap(); + let code = code.unwrap(); + std::slice::from_raw_parts(code.GetBufferPointer().cast::(), code.GetBufferSize()) + .to_vec() + } +} + +/// The clamp as it was before it charged the budget once per group +/// (record by record, every thread racing for the budget word), kept +/// here to measure against. +const OLD_SOURCE: &str = r#" +#define RS "RootConstants(num32BitConstants=6, b0), SRV(t0), SRV(t1), UAV(u0), UAV(u1)" +cbuffer Record : register(b0) { +uint kind; +uint stride; +uint records; +uint args_offset; +// Bit 0: a count buffer bounds the records. Bit 1: the records are a +// window clamped ahead of their draws: one that asks for more than can +// run is left empty and costs nothing. +uint has_count; +uint count_offset; +}; +ByteAddressBuffer src_args : register(t0); +ByteAddressBuffer count_buf : register(t1); +RWByteAddressBuffer dst_args : register(u0); +// The list's work so far (vertex instances, threads): past the budget, +// records run empty. +RWByteAddressBuffer budget : register(u1); +static const uint BUDGET = 1u << 27; +// Groups of one dispatch; more run empty. +static const uint GROUPS = 1u << 20; +[RootSignature(RS)] +[numthreads(64, 1, 1)] +void main(uint3 id : SV_DispatchThreadID) { +uint eff_count = records; +bool ahead = (has_count & 2u) != 0; +if ((has_count & 1u) != 0) { + eff_count = min(eff_count, count_buf.Load(count_offset)); +} +if (id.x >= eff_count) return; +uint src_at = args_offset + id.x * stride; +uint dst_at = id.x * stride; +uint cost; +uint2 draw_counts = uint2(0, 0); +uint3 groups = uint3(0, 0, 0); +if (kind <= 1) { + // Draws: vertex or index count, then instances. + uint2 asked = src_args.Load2(src_at); + if (ahead && (asked.x > (1u << 24) || asked.y > (1u << 24))) { + asked = uint2(0, 0); + } + uint count = min(asked.x, 1u << 24); + uint instances = min(asked.y, (1u << 26) / max(count, 1u)); + cost = count * instances; + draw_counts = uint2(count, instances); +} else if (kind == 2) { + uint3 g = min(src_args.Load3(src_at), uint3(65535u, 65535u, 65535u)); + // x * y fits 32 bits; the whole count may not. + if (g.z != 0 && g.x * g.y > GROUPS / g.z) { + g = uint3(0, 0, 0); + } + cost = g.x * g.y * g.z * 64u; + groups = g; +} else { + // Mesh dispatches: the console's are one-dimensional. + uint3 g = src_args.Load3(src_at); + // Ahead of its draw, a record over the most a dispatch runs is a + // slot the title has not filled (the title leaves all + // ones there): empty, and not counted below either. + if (ahead && g.x > 65535u) { + g = uint3(0, 0, 0); + } + // Diagnostics, in the budget buffer's next words: the largest + // group count a mesh record asked for, and the groups asked in all. + uint was; + budget.InterlockedMax(4, g.x, was); + budget.InterlockedAdd(8, min(g.x, 1u << 24), was); + g = uint3(min(g.x, 65535u), min(g.y, 1u), min(g.z, 1u)); + cost = g.x * g.y * g.z * 128u; + groups = g; +} +bool over = false; +if (cost > 0) { + uint before; + budget.InterlockedOr(0, 0, before); + [allow_uav_condition] + while (before < BUDGET) { + uint next = (BUDGET - before <= cost) ? BUDGET : (before + cost); + uint prev; + budget.InterlockedCompareExchange(0, before, next, prev); + if (prev == before) break; + before = prev; + } + over = before >= BUDGET || BUDGET - before < cost; +} +if (kind <= 1) { + if (over) { + draw_counts = uint2(0, 0); + } + dst_args.Store2(dst_at, draw_counts); + for (uint off = 8; off < stride; off += 4) { + dst_args.Store(dst_at + off, src_args.Load(src_at + off)); + } +} else { + if (over) { + groups = uint3(0, 0, 0); + } + dst_args.Store3(dst_at, groups); + for (uint off = 12; off < stride; off += 4) { + dst_args.Store(dst_at + off, src_args.Load(src_at + off)); + } +} +} +"#; + +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +enum Barriers { + /// Back to the common state after every execution (as before). + Old, + /// Readable as arguments until the next clamp, common at the end. + New, +} + +#[test] +#[ignore = "benchmark; see the module notes"] +fn bench_indirect_draw_barriers() { + let Some(host) = super::host() else { + eprintln!("no host GPU"); + return; + }; + let device = &host.device; + let clamps = [ + make_from(device, OLD_SOURCE).expect("the old clamp"), + make_for(device).expect("the clamp"), + ]; + // SAFETY: plain D3D12 object creation with valid descriptions; the + // objects outlive every list recorded and run below. + unsafe { + let adapter = { + let luid = device.GetAdapterLuid(); + CreateDXGIFactory2::(DXGI_CREATE_FACTORY_FLAGS(0)) + .and_then(|f| { + f.EnumAdapterByLuid::(luid) + }) + .and_then(|a| a.GetDesc1()) + .map(|d| { + String::from_utf16_lossy(&d.Description) + .trim_end_matches('\0') + .to_owned() + }) + .unwrap_or_else(|_| "an unnamed adapter".to_owned()) + }; + let queue: ID3D12CommandQueue = device + .CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC { + Type: D3D12_COMMAND_LIST_TYPE_DIRECT, + ..Default::default() + }) + .unwrap(); + let allocator: ID3D12CommandAllocator = device + .CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT) + .unwrap(); + let list: ID3D12GraphicsCommandList = device + .CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &allocator, None) + .unwrap(); + list.Close().unwrap(); + let fence: ID3D12Fence = device.CreateFence(0, D3D12_FENCE_FLAG_NONE).unwrap(); + let event = CreateEventW(None, false, false, None).unwrap(); + let frequency = queue.GetTimestampFrequency().unwrap() as f64; + + // The pipeline: tiny triangles into a small target. + let (vs, ps) = (compile("vs", "vs_5_1"), compile("ps", "ps_5_1")); + let root: ID3D12RootSignature = device.CreateRootSignature(0, &vs).unwrap(); + let mut desc = D3D12_GRAPHICS_PIPELINE_STATE_DESC { + pRootSignature: std::mem::transmute_copy(&root), + VS: D3D12_SHADER_BYTECODE { + pShaderBytecode: vs.as_ptr().cast(), + BytecodeLength: vs.len(), + }, + PS: D3D12_SHADER_BYTECODE { + pShaderBytecode: ps.as_ptr().cast(), + BytecodeLength: ps.len(), + }, + SampleMask: u32::MAX, + RasterizerState: D3D12_RASTERIZER_DESC { + FillMode: D3D12_FILL_MODE_SOLID, + CullMode: D3D12_CULL_MODE_NONE, + DepthClipEnable: true.into(), + ..Default::default() + }, + PrimitiveTopologyType: D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE, + NumRenderTargets: 1, + SampleDesc: DXGI_SAMPLE_DESC { + Count: 1, + Quality: 0, + }, + ..Default::default() + }; + desc.BlendState.RenderTarget[0].RenderTargetWriteMask = + D3D12_COLOR_WRITE_ENABLE_ALL.0 as u8; + desc.RTVFormats[0] = DXGI_FORMAT_R8G8B8A8_UNORM; + let pso: ID3D12PipelineState = device.CreateGraphicsPipelineState(&desc).unwrap(); + let target_desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D, + Width: 256, + Height: 256, + DepthOrArraySize: 1, + MipLevels: 1, + Format: DXGI_FORMAT_R8G8B8A8_UNORM, + SampleDesc: DXGI_SAMPLE_DESC { + Count: 1, + Quality: 0, + }, + Flags: D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET, + ..Default::default() + }; + let mut target: Option = None; + device + .CreateCommittedResource( + &D3D12_HEAP_PROPERTIES { + Type: D3D12_HEAP_TYPE_DEFAULT, + ..Default::default() + }, + D3D12_HEAP_FLAG_NONE, + &target_desc, + D3D12_RESOURCE_STATE_RENDER_TARGET, + None, + &mut target, + ) + .unwrap(); + let target = target.unwrap(); + let rtvs: ID3D12DescriptorHeap = device + .CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC { + Type: D3D12_DESCRIPTOR_HEAP_TYPE_RTV, + NumDescriptors: 1, + ..Default::default() + }) + .unwrap(); + let rtv = rtvs.GetCPUDescriptorHandleForHeapStart(); + device.CreateRenderTargetView(&target, None, rtv); + + // The title's records: three vertices, one instance, 32 bytes apart. + let (src, src_ptr) = host.shared_buffer(u64::from(DRAWS * STEP)).unwrap(); + for i in 0..DRAWS as usize { + let words = [3u32, 1, 0, 0]; + std::ptr::copy_nonoverlapping( + words.as_ptr().cast::(), + src_ptr.add(i * STEP as usize), + 16, + ); + } + let (budget, budget_ptr) = host.shared_buffer(256).unwrap(); + let budget_gpu = budget.GetGPUVirtualAddress(); + // The same words in the card's own memory (zeroed when made; the + // runs below charge far less than the budget). + let card_budget = host.uav_buffer(256).unwrap(); + let card_budget_gpu = card_budget.GetGPUVirtualAddress(); + let scratch = host + .uav_buffer(u64::from(WINDOW * STEP).max(64 << 10)) + .unwrap(); + let signature = { + let arg = D3D12_INDIRECT_ARGUMENT_DESC { + Type: D3D12_INDIRECT_ARGUMENT_TYPE_DRAW, + ..Default::default() + }; + let desc = D3D12_COMMAND_SIGNATURE_DESC { + ByteStride: 16, + NumArgumentDescs: 1, + pArgumentDescs: &arg, + NodeMask: 0, + }; + let mut sig: Option = None; + device + .CreateCommandSignature(&desc, None::<&ID3D12RootSignature>, &mut sig) + .unwrap(); + sig.unwrap() + }; + let stamps: ID3D12QueryHeap = { + let mut heap: Option = None; + device + .CreateQueryHeap( + &D3D12_QUERY_HEAP_DESC { + Type: D3D12_QUERY_HEAP_TYPE_TIMESTAMP, + Count: 2, + NodeMask: 0, + }, + &mut heap, + ) + .unwrap(); + heap.unwrap() + }; + let mut back: Option = None; + device + .CreateCommittedResource( + &D3D12_HEAP_PROPERTIES { + Type: D3D12_HEAP_TYPE_READBACK, + ..Default::default() + }, + D3D12_HEAP_FLAG_NONE, + &D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, + Width: 16, + Height: 1, + DepthOrArraySize: 1, + MipLevels: 1, + SampleDesc: DXGI_SAMPLE_DESC { + Count: 1, + Quality: 0, + }, + Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, + ..Default::default() + }, + D3D12_RESOURCE_STATE_COPY_DEST, + None, + &mut back, + ) + .unwrap(); + let back = back.unwrap(); + let mut submitted = 0u64; + + // One frame's lists: GPU ms (timestamps around the list), CPU ms + // recording it, ms from submission to the end of its run. + let mut frame = |barriers: Barriers, clamp: &Clamp, window: u32, card: bool| -> [f64; 3] { + allocator.Reset().unwrap(); + list.Reset(&allocator, None).unwrap(); + let recording = std::time::Instant::now(); + list.EndQuery(&stamps, D3D12_QUERY_TYPE_TIMESTAMP, 0); + list.OMSetRenderTargets(1, Some(&rtv), false, None); + list.RSSetViewports(&[D3D12_VIEWPORT { + Width: 256.0, + Height: 256.0, + MaxDepth: 1.0, + ..Default::default() + }]); + list.RSSetScissorRects(&[RECT { + left: 0, + top: 0, + right: 256, + bottom: 256, + }]); + list.IASetPrimitiveTopology( + windows::Win32::Graphics::Direct3D::D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST, + ); + list.SetGraphicsRootSignature(&root); + let mut state = D3D12_RESOURCE_STATE_COMMON; + for first in (0..DRAWS).step_by(window as usize) { + let records = window.min(DRAWS - first); + assert!(record_clamp_as( + clamp, + &list, + (&scratch, state), + if card { card_budget_gpu } else { budget_gpu }, + (&src, u64::from(first * STEP)), + None, + (0, STEP, records), + window > 1, + )); + state = D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT; + list.SetPipelineState(&pso); + for k in 0..records { + list.ExecuteIndirect(&signature, 1, &scratch, u64::from(k * STEP), None, 0); + if barriers == Barriers::Old { + list.ResourceBarrier(&[transition( + &scratch, + D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT, + D3D12_RESOURCE_STATE_COMMON, + )]); + state = D3D12_RESOURCE_STATE_COMMON; + } + } + } + if state != D3D12_RESOURCE_STATE_COMMON { + list.ResourceBarrier(&[transition(&scratch, state, D3D12_RESOURCE_STATE_COMMON)]); + } + list.EndQuery(&stamps, D3D12_QUERY_TYPE_TIMESTAMP, 1); + list.ResolveQueryData(&stamps, D3D12_QUERY_TYPE_TIMESTAMP, 0, 2, &back, 0); + list.Close().unwrap(); + let recorded = recording.elapsed().as_secs_f64() * 1e3; + let running = std::time::Instant::now(); + queue.ExecuteCommandLists(&[Some(list.cast::().unwrap())]); + submitted += 1; + queue.Signal(&fence, submitted).unwrap(); + fence.SetEventOnCompletion(submitted, event).unwrap(); + WaitForSingleObject(event, INFINITE); + let ran = running.elapsed().as_secs_f64() * 1e3; + let mut data = std::ptr::null_mut(); + back.Map(0, None, Some(&mut data)).unwrap(); + let t = std::slice::from_raw_parts(data.cast::(), 2); + let gpu = t[1].saturating_sub(t[0]) as f64 / frequency * 1e3; + back.Unmap(0, None); + (budget_ptr as *mut u32).write_volatile(0); + [gpu, recorded, ran] + }; + + // What `main` records, then this branch; the windows a step at a + // time (barriers, then the clamp's one charge per group). + let (old, new) = (&clamps[0], &clamps[1]); + // The last two keep the budget in the card's memory instead of + // memory the CPU maps (where the list's budget is now). + let cases: [(&str, Barriers, &Clamp, u32, bool); 7] = [ + ("one at a time, main", Barriers::Old, old, 1, false), + ("one at a time, this", Barriers::New, new, 1, false), + ("windows of 32, main", Barriers::Old, old, WINDOW, false), + ("windows, new barriers", Barriers::New, old, WINDOW, false), + ("windows of 32, this", Barriers::New, new, WINDOW, false), + ("one at a time, card", Barriers::New, new, 1, true), + ("windows of 32, card", Barriers::New, new, WINDOW, true), + ]; + // Warm up, then the cases in turn, so drift falls on all alike. + for &(_, barriers, clamp, window, card) in &cases { + frame(barriers, clamp, window, card); + } + let mut times: Vec> = vec![Vec::new(); cases.len()]; + for _ in 0..RUNS { + for (i, &(_, barriers, clamp, window, card)) in cases.iter().enumerate() { + times[i].push(frame(barriers, clamp, window, card)); + } + } + let median = |v: &[[f64; 3]], k: usize| { + let mut x: Vec = v.iter().map(|t| t[k]).collect(); + x.sort_by(f64::total_cmp); + x[x.len() / 2] + }; + eprintln!( + "indirect draw barriers on {adapter}: {DRAWS} one-record draws a frame, \ + medians of {RUNS} frames" + ); + for (i, (name, ..)) in cases.iter().enumerate() { + let gpu = median(×[i], 0); + eprintln!( + " {name:<22} GPU {gpu:7.2} ms ({:5.2} us a draw), recording {:6.2} ms, \ + submit to done {:7.2} ms", + gpu * 1e3 / f64::from(DRAWS), + median(×[i], 1), + median(×[i], 2), + ); + } + for (from, to) in [(0, 1), (2, 3), (3, 4), (2, 4), (1, 5), (4, 6)] { + let (a, b) = (median(×[from], 0), median(×[to], 0)); + eprintln!( + " {} -> {}: GPU time {:+.1} %", + cases[from].0, + cases[to].0, + (b / a - 1.0) * 100.0 + ); + } + } +} diff --git a/crates/leonida-gpu/src/inplace.rs b/crates/leonida-gpu/src/inplace.rs new file mode 100644 index 000000000..3440bc555 --- /dev/null +++ b/crates/leonida-gpu/src/inplace.rs @@ -0,0 +1,1412 @@ +//! Title memory as the card's own memory: a host heap opened on memory +//! the title already has, and a buffer placed in it, so that shaders read +//! and write the title's bytes themselves and no host copy stands between +//! (the console's one memory). This file holds the two openings Direct3D +//! has, a probe that says what this PC's driver makes of them +//! (`LEONIDA_INPLACE_PROBE`), and a census of which title memory could be +//! opened. +//! +//! What the Direct3D runtime and the kernel answer, measured on this PC +//! with the software adapter (the rules are theirs, not the adapter's; +//! what the card's driver adds is what the probe is for): +//! +//! - `OpenExistingHeapFromAddress` takes the base address of a whole +//! `VirtualAlloc` allocation and nothing inside it; every page must be +//! committed and have one protection. Opening locks every page into the +//! PC's memory at once (256 MiB never touched: 70 ms and 256 MB of +//! working set). +//! - `OpenExistingHeapFromAddress1` (`ID3D12Device13`) takes any committed +//! part of an allocation, with the same rule for its pages; parts may +//! overlap, and the whole may be opened beside them. It also takes a +//! committed view of a section. +//! - `OpenExistingHeapFromFileMapping` takes a section made with +//! `SEC_COMMIT` and refuses one made with `SEC_RESERVE` (how `xmem` +//! makes the title's page pool today). The heap is the section, not a +//! view of it: views may be unmapped, mapped elsewhere or made +//! read-only, and the section's handle closed, with the heap alive. +//! Opening it locks nothing (256 MiB: 0.2 ms, no working set). +//! - The heap is a custom heap in the PC's memory (write-back pages, pool +//! L0), shared and cross-adapter shared, 64 KiB aligned. A buffer in it +//! must have `ALLOW_CROSS_ADAPTER`; unordered access beside it is taken. +//! A texture must be row-major with one level. Tile mappings into such +//! a heap are refused and REMOVE THE DEVICE: never call them. +//! - While a heap opened from an address stands, the title cannot +//! decommit, release or protect the pages in it (`VirtualFree` and +//! `VirtualProtect` fail with error 87), nor unmap a view in it. Pages +//! outside the opened part are free to change. + +use std::collections::BTreeMap; +use std::ffi::c_void; +use std::sync::Mutex; +use std::sync::atomic::{AtomicU64, Ordering}; + +use windows::Win32::Foundation::HANDLE; +use windows::Win32::Graphics::Direct3D::Fxc::D3DCompile; +use windows::Win32::Graphics::Direct3D::ID3DBlob; +use windows::Win32::Graphics::Direct3D12::*; +use windows::Win32::Graphics::Dxgi::Common::DXGI_SAMPLE_DESC; +use windows::Win32::System::Threading::{CreateEventW, WaitForSingleObject}; +use windows::core::{Interface, s}; +use windows_sys::Win32::System::Memory as mem; + +/// The unit heaps and placed buffers are cut on, and the console's page. +const K64: usize = 64 << 10; +/// The host's write watching (not in windows-sys' memory module). +const MEM_WRITE_WATCH: u32 = 0x20_0000; + +/// `LEONIDA_INPLACE_PROBE`: 0 (unset) nothing; 1 the probe on memory of +/// its own at the first sweep, and the census 30 and 150 seconds later; +/// 2 also opens one part of the title's own memory for a moment at the +/// first census. +pub(crate) fn probe_level() -> u8 { + static LEVEL: std::sync::OnceLock = std::sync::OnceLock::new(); + *LEVEL.get_or_init(|| std::env::var("LEONIDA_INPLACE_PROBE").ok().and_then(|v| v.trim().parse().ok()).unwrap_or(0)) +} + +/// `LEONIDA_INPLACE`: 0 (unset) off. 1: a window of title memory outside +/// buffers that lies in private memory committed whole is not copied: a +/// part of the title's allocation is opened as a host heap and the window +/// is a buffer placed over it ([`place_for`]). 2: title buffers too, +/// except the big ones in the card's memory. +/// +/// What stage 1 covers is private memory (`XMemVirtualAlloc`'s). View +/// memory (the page pool) is turned down here: its section is made +/// reserved, which the host refuses, and what a view shows changes when +/// the title maps pages. +/// +/// What it assumes, for 2: nothing reads title memory that a submission +/// not yet run writes through such a buffer. With every submission waited +/// for (the default) that holds; with `LEONIDA_LATE_WAIT` it does not, +/// since the flights' rules know shader writes only by the ranges copies +/// declare. Do not combine 2 with late wait. +/// +/// shortcut: while a window is in place the title cannot decommit, free +/// or protect its pages (the call fails with error 87; the probe shows +/// it). The title's heaps are allocated once and kept, and nothing of the +/// kind was seen; [`title_memory_freeing`] is there for the runtime to +/// call before such a call once it takes them over. +pub(crate) fn level() -> u8 { + static LEVEL: std::sync::OnceLock = std::sync::OnceLock::new(); + *LEVEL.get_or_init(|| std::env::var("LEONIDA_INPLACE").ok().and_then(|v| v.trim().parse().ok()).unwrap_or(0)) +} + +/// The most title memory in place at once, in bytes +/// (`LEONIDA_INPLACE_MB`, 4096): opening locks the pages into the PC's +/// memory, also those the title never touched. +fn most() -> u64 { + static MOST: std::sync::OnceLock = std::sync::OnceLock::new(); + *MOST.get_or_init(|| std::env::var("LEONIDA_INPLACE_MB").ok().and_then(|v| v.trim().parse::().ok()).unwrap_or(4096) << 20) +} + +/// In place now: windows and their bytes, title buffers and their bytes; +/// then, since the start: asks turned down because the memory is a view +/// or not private memory committed whole, because the host refused, +/// because of [`most`]; and what was let go because its memory changed. +static STATS: [AtomicU64; 8] = [const { AtomicU64::new(0) }; 8]; + +/// A buffer placed over title memory, and its heap. +pub(crate) struct Placed { + pub(crate) buffer: ID3D12Resource, + pub(crate) heap: ID3D12Heap, + /// The host GPU address of the title memory's first byte. + pub(crate) gpu: u64, + /// Bytes from the buffer's first byte to the title memory's first. + pub(crate) bias: u64, +} + +/// Opens the 64 KiB pages that hold title memory `[start, start + len)` +/// as a heap of their own and places one buffer over all of them. `Err` +/// with nothing if the memory is not private memory committed whole +/// (nothing was asked of the host), with the host's error if it refused. +pub(crate) fn place_part(device: &ID3D12Device, start: u64, len: u64) -> Result> { + let at = start & !(K64 as u64 - 1); + let bytes = (start + len.max(1)).next_multiple_of(K64 as u64) - at; + if !private_whole(at as usize, bytes as usize) { + return Err(None); + } + let heap = open(device, From::Part(at as usize, bytes as usize)).map_err(Some)?; + let buffer = place(device, &heap, 0, bytes).map_err(Some)?; + // SAFETY: a live buffer. + let gpu = unsafe { buffer.GetGPUVirtualAddress() } + (start - at); + Ok(Placed { buffer, heap, gpu, bias: start - at }) +} + +/// Title memory `[start, start + len)` in place, for a window outside +/// buffers or a title buffer, if [`level`] asks for it and the memory can +/// be opened; `None` leaves the caller to make a copy, as before. +pub(crate) fn place_for(start: u64, len: u64, window: bool) -> Option { + if level() < if window { 1 } else { 2 } { + return None; + } + // View memory: known from the runtime without asking Windows. + if cover(start as usize, len as usize) != Cover::None { + STATS[4].fetch_add(1, Ordering::Relaxed); + return None; + } + if STATS[1].load(Ordering::Relaxed) + STATS[3].load(Ordering::Relaxed) + len > most() { + STATS[6].fetch_add(1, Ordering::Relaxed); + return None; + } + let host = crate::host::host()?; + match place_part(&host.device, start, len) { + Ok(placed) => { + let at = if window { 0 } else { 2 }; + STATS[at].fetch_add(1, Ordering::Relaxed); + STATS[at + 1].fetch_add(len, Ordering::Relaxed); + Some(placed) + } + Err(None) => { + STATS[4].fetch_add(1, Ordering::Relaxed); + None + } + Err(Some(e)) => { + if STATS[5].fetch_add(1, Ordering::Relaxed) < 8 { + tracing::warn!(start = format_args!("{start:#x}"), len, error = %e, "title memory not opened in place: a copy instead"); + } + None + } + } +} + +/// What [`place_for`] gave is gone. +pub(crate) fn gone(window: bool, bytes: u64) { + let at = if window { 0 } else { 2 }; + STATS[at].fetch_sub(1, Ordering::Relaxed); + STATS[at + 1].fetch_sub(bytes, Ordering::Relaxed); +} + +/// Title memory `[at, at + len)` is about to show something else, or the +/// title is about to decommit, free or protect it: what is in place there +/// is let go (the tables forget it; its heap goes when the last list and +/// slot that hold it do). Called for memory the runtime maps anew; for +/// the runtime to call before the title's own `VirtualFree` once it takes +/// that call over. +pub fn title_memory_freeing(at: usize, len: usize) { + if STATS[0].load(Ordering::Relaxed) + STATS[2].load(Ordering::Relaxed) == 0 { + return; + } + let gone = crate::shadow::in_place_let_go(at as u64, len as u64); + STATS[7].fetch_add(gone, Ordering::Relaxed); +} + +/// The line of what is in place, every ten seconds while [`level`] is on. +fn say() { + static LAST: AtomicU64 = AtomicU64::new(0); + let now = crate::host::now_ms(); + let last = LAST.load(Ordering::Relaxed); + if now < last + 10_000 || LAST.compare_exchange(last, now, Ordering::Relaxed, Ordering::Relaxed).is_err() { + return; + } + let s: Vec = STATS.iter().map(|s| s.load(Ordering::Relaxed)).collect(); + tracing::info!( + "title memory in place: {} windows {} MB, {} title buffers {} MB (no copy, no refresh, no copy-back); turned down: {} view memory or not private memory committed whole, \ + {} refused by the host, {} over LEONIDA_INPLACE_MB; {} let go because their memory changed", + s[0], + s[1] >> 20, + s[2], + s[3] >> 20, + s[4], + s[5], + s[6], + s[7] + ); +} + +/// What a heap is opened on. +pub(crate) enum From { + /// A whole `VirtualAlloc` allocation, by its base address. + Region(usize), + /// A committed part of one: address and bytes. + Part(usize, usize), + /// A section made with `SEC_COMMIT`, by its handle. + Section(usize), +} + +/// Opens a heap on memory the process has. +pub(crate) fn open(device: &ID3D12Device, from: From) -> windows::core::Result { + // SAFETY: the calls take an address or a handle and check both + // themselves; a refusal is an error code. + unsafe { + match from { + From::Region(at) => device.cast::()?.OpenExistingHeapFromAddress(at as *const c_void), + From::Part(at, bytes) => device.cast::()?.OpenExistingHeapFromAddress1(at as *const c_void, bytes), + From::Section(handle) => device.cast::()?.OpenExistingHeapFromFileMapping(HANDLE(handle as *mut c_void)), + } + } +} + +fn buffer_desc(size: u64, flags: D3D12_RESOURCE_FLAGS) -> D3D12_RESOURCE_DESC { + D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, + Width: size.max(1), + Height: 1, + DepthOrArraySize: 1, + MipLevels: 1, + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, + Flags: flags, + ..Default::default() + } +} + +/// A buffer of `size` bytes at `offset` (a multiple of 64 KiB) of an +/// opened heap, which shaders may read and write, in the common state. +pub(crate) fn place(device: &ID3D12Device, heap: &ID3D12Heap, offset: u64, size: u64) -> windows::core::Result { + let mut placed: Option = None; + // The heap is cross-adapter shared, so the buffer must say so too. + let flags = D3D12_RESOURCE_FLAG_ALLOW_CROSS_ADAPTER | D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS; + // SAFETY: plain creation in a live heap. + unsafe { device.CreatePlacedResource(heap, offset, &buffer_desc(size, flags), D3D12_RESOURCE_STATE_COMMON, None, &mut placed)? }; + placed.ok_or_else(windows::core::Error::empty) +} + +// The title's views of its physical pages, as the runtime maps them: the +// census needs them to say which view memory is one run of a section (one +// placed buffer could show it) and which is scattered pages. + +struct Views { + /// By address: bytes, the section's handle, the offset in it. + views: BTreeMap, + /// By section and byte offset of a 64 KiB page: the address of that + /// page in every view that shows it. A write through one view of a + /// page is a write of the bytes every other view shows + /// (`crate::watch` guards them all). + pages: BTreeMap<(usize, u64), Vec>, + /// Sections by handle: bytes, and whether made committed. + sections: Vec<(usize, u64, bool)>, +} + +static VIEWS: Mutex = + Mutex::new(Views { views: BTreeMap::new(), pages: BTreeMap::new(), sections: Vec::new() }); + +fn views() -> std::sync::MutexGuard<'static, Views> { + VIEWS.lock().unwrap_or_else(|e| e.into_inner()) +} + +/// The runtime made a section of `bytes` for physical pages; `committed` +/// if with `SEC_COMMIT` (only such a section can be opened as a heap). +pub fn title_memory_section(section: usize, bytes: u64, committed: bool) { + { + let mut v = views(); + v.sections.retain(|s| s.0 != section); + v.sections.push((section, bytes, committed)); + } + // A view of our own made on an earlier section that had this handle's + // number shows that section's pages, not this one's: it is forgotten + // (left mapped: nothing reads it any more) and the next store through + // a view of ours maps this section. + let gone = OWN.lock().unwrap_or_else(|e| e.into_inner()).as_mut().and_then(|own| own.remove(§ion)).flatten(); + if gone.is_some() { + tracing::info!(section, "a section handle's number came round again: our own view of the earlier section is forgotten"); + } +} + +/// The runtime mapped `[at, at + len)` as a view of `section` from +/// `offset` on. Call after [`crate::title_memory_remapped`] of the range. +pub fn title_memory_view(at: usize, len: usize, section: usize, offset: u64) { + { + let mut v = views(); + v.views.insert(at, (len, section, offset)); + for k in 0..len.div_ceil(K64) { + v.pages.entry((section, offset + (k * K64) as u64)).or_default().push(at + k * K64); + } + } + // This view is writable from now on: a guard over the same bytes at + // another view must look at them again, and the pages are noted written + // there (`crate::watch`). + crate::watch::views_mapped(section, offset, len); +} + +/// What `[at, at + len)` showed is gone ([`crate::title_memory_remapped`]): +/// the views that touch it are forgotten (the runtime tells again those it +/// maps anew). +pub(crate) fn views_gone(at: usize, len: usize) { + let mut v = views(); + if v.views.is_empty() { + return; + } + let end = at.saturating_add(len); + let first = v.views.range(..=at).next_back().filter(|(base, view)| *base + view.0 > at).map(|(base, _)| *base); + let gone: Vec = first.into_iter().chain(v.views.range(at.saturating_add(1)..end).map(|(base, _)| *base)).collect(); + for base in gone { + let Some((bytes, section, offset)) = v.views.remove(&base) else { + continue; + }; + for k in 0..bytes.div_ceil(K64) { + let key = (section, offset + (k * K64) as u64); + if let Some(pages) = v.pages.get_mut(&key) { + let page = base + k * K64; + pages.retain(|&shown| shown != page); + if pages.is_empty() { + v.pages.remove(&key); + } + } + } + } +} + +/// The title views that overlap `[start, end)`, as `(address, bytes)`. +pub(crate) fn views_between(start: usize, end: usize) -> Vec<(usize, usize)> { + if start >= end { + return Vec::new(); + } + let v = views(); + let mut out = Vec::new(); + if let Some((&base, &(bytes, _, _))) = v.views.range(..=start).next_back() + && base + bytes > start + { + out.push((base, bytes)); + } + for (&base, &(bytes, _, _)) in v.views.range(start.saturating_add(1)..end) { + out.push((base, bytes)); + } + out +} + +/// The address of the 64 KiB page shown at `page` in every title view that +/// shows it, `page`'s own address included; empty if `page` is not a view. +pub(crate) fn pages_of(page: usize) -> Vec { + let v = views(); + let Some((&base, &(bytes, section, offset))) = v.views.range(..=page).next_back() else { + return Vec::new(); + }; + let within = page.wrapping_sub(base); + if within >= bytes || !within.is_multiple_of(K64) { + return Vec::new(); + } + v.pages.get(&(section, offset + within as u64)).cloned().unwrap_or_default() +} + +/// The title views that show any of the physical bytes `[offset, offset + +/// len)` of `section`, as `(address, bytes)` ranges in address order; not +/// those of a page shown in very many views (`MANY_VIEWS`). +pub(crate) fn views_of_section(section: usize, offset: u64, len: usize) -> Vec<(usize, usize)> { + if len == 0 { + return Vec::new(); + } + let v = views(); + let end = offset.saturating_add(len as u64); + let mut pages: Vec = Vec::new(); + let mut at = offset - offset % K64 as u64; + while at < end { + if let Some(shown) = v.pages.get(&(section, at)) + && shown.len() <= crate::watch::MANY_VIEWS + { + pages.extend(shown.iter().copied()); + } + match at.checked_add(K64 as u64) { + Some(next) => at = next, + None => break, + } + } + pages.sort_unstable(); + pages.dedup(); + let mut runs: Vec<(usize, usize)> = Vec::with_capacity(pages.len()); + for page in pages { + match runs.last_mut() { + Some((first, bytes)) if *first + *bytes == page => *bytes += K64, + _ => runs.push((page, K64)), + } + } + runs +} + +/// Whether what shaders wrote goes back into title view memory through a +/// view of our own (`LEONIDA_BACK_OWN_VIEW=1`; off by default). +/// +/// The copy-back writes title memory at the title's address, so it opens +/// the guard on the 64 KiB block first (and on every other view of the +/// page), and the block then counts as written by the title: the host +/// copy that just put the bytes there copies all 64 KiB of it back in at +/// its next refresh, and sends them up to the card again if it lives +/// there. In runs 218-222 the bytes copied in went with the bytes copied +/// back, 0.83 MB for each MB (78 readings), some 50 MB of 142 MB a frame. +/// +/// With the switch the bytes are stored through a view of our own on the +/// same section, which no guard covers: the title's views stay read-only +/// (a title write still faults and is seen), the write-watch journal is +/// told the page was written (`crate::watch::wrote_own`) so that every +/// other copy of it takes it again, and the copy that wrote it notes the +/// page current (`put_back_own` in `crate::shadow`). +/// +/// `LEONIDA_BACK_OWN_VIEW=alt`: twenty seconds with, twenty without, in +/// turn, each change said in the log, for measuring it in one scene. +pub(crate) fn back_own() -> bool { + /// 0 off, 1 on, 2 in turn. + static MODE: std::sync::OnceLock = std::sync::OnceLock::new(); + match *MODE.get_or_init(|| match std::env::var("LEONIDA_BACK_OWN_VIEW").as_deref() { + Ok("1") => 1, + Ok("alt") => 2, + _ => 0, + }) { + 0 => false, + 1 => true, + _ => { + static EPOCH: std::sync::OnceLock = std::sync::OnceLock::new(); + let on = (EPOCH.get_or_init(std::time::Instant::now).elapsed().as_secs() / 20) % 2 == 1; + static LAST: std::sync::atomic::AtomicU8 = std::sync::atomic::AtomicU8::new(2); + if LAST.swap(u8::from(on), std::sync::atomic::Ordering::Relaxed) != u8::from(on) { + tracing::info!( + "copy-back through views of our own from now (LEONIDA_BACK_OWN_VIEW=alt): {}", + if on { "ON" } else { "off, as usual" } + ); + } + on + } + } +} + +/// A view of our own on a whole section of the title's physical pages: +/// where it is, its bytes, and which of its 64 KiB blocks we have asked +/// to be committed through it (a bit each). +struct Own { + base: usize, + bytes: u64, + committed: Vec, +} + +/// Our own views by section handle; `None` in a section's place if the +/// host refused the view (not asked again). +static OWN: Mutex>>> = Mutex::new(None); + +/// Stores `bytes` at title address `at` through a view of our own +/// ([`back_own`]), if `[at, at + bytes.len())` lies in one 64 KiB page of +/// a title view of a section. Gives the addresses of that page in every +/// title view that shows it (the page of `at` among them), or `None` with +/// nothing written: not view memory, a page of very many views, the +/// runtime changing mappings at this moment, or the host refusing. +pub(crate) fn write_own(at: usize, bytes: &[u8]) -> Option> { + if bytes.is_empty() || at / K64 != (at + bytes.len() - 1) / K64 { + return None; + } + // No mapping changes until the bytes are in: the view found below + // shows these pages for as long as this is held. + let _still = crate::watch::title_memory_reading_now()?; + let (section, offset, shown, section_bytes) = { + let v = views(); + let (&base, &(len, section, offset)) = v.views.range(..=at).next_back()?; + if at + bytes.len() > base + len { + return None; + } + let offset = offset + (at - base) as u64; + let shown = v.pages.get(&(section, offset - offset % K64 as u64))?.clone(); + if shown.len() > crate::watch::MANY_VIEWS { + return None; + } + let section_bytes = v.sections.iter().find(|s| s.0 == section)?.1; + (section, offset, shown, section_bytes) + }; + if offset + bytes.len() as u64 > section_bytes { + return None; + } + let mut own = OWN.lock().unwrap_or_else(|e| e.into_inner()); + let view = own + .get_or_insert_with(Default::default) + .entry(section) + .or_insert_with(|| { + // SAFETY: a section handle the runtime gave us, alive as long + // as the title's views of it are; the view is ours and stays. + let at = unsafe { mem::MapViewOfFile(section as *mut c_void, mem::FILE_MAP_WRITE, 0, 0, 0) }; + if at.Value.is_null() { + tracing::warn!( + section, + error = %std::io::Error::last_os_error(), + "no view of our own on a section of title pages: what shaders wrote goes back the old way there" + ); + return None; + } + tracing::info!( + section, + mb = section_bytes >> 20, + "a view of our own on a section of title pages, for what shaders wrote (LEONIDA_BACK_OWN_VIEW=1)" + ); + Some(Own { + base: at.Value as usize, + bytes: section_bytes, + committed: vec![0; (section_bytes as usize).div_ceil(K64).div_ceil(64)], + }) + }) + .as_mut()?; + if offset + bytes.len() as u64 > view.bytes { + return None; + } + let block = offset as usize / K64; + if (view.committed[block / 64] & (1u64 << (block % 64))) == 0 { + // The title's view committed these pages of the section; asked + // once more through ours, which changes nothing if they are. + // SAFETY: a block inside our own view. + let there = unsafe { + mem::VirtualAlloc((view.base + block * K64) as *const c_void, K64, mem::MEM_COMMIT, mem::PAGE_READWRITE) + }; + if there.is_null() { + return None; + } + view.committed[block / 64] |= 1u64 << (block % 64); + } + // SAFETY: committed bytes inside our own view; the source is the + // caller's slice. + unsafe { std::ptr::copy_nonoverlapping(bytes.as_ptr(), (view.base + offset as usize) as *mut u8, bytes.len()) }; + Some(shown) +} + +/// How the views cover `[at, at + len)`. +#[derive(Debug, PartialEq, Eq, Clone, Copy)] +pub(crate) enum Cover { + /// No view holds its first byte. + None, + /// Views hold a part of it only. + Holes, + /// Views hold all of it, from more than one place. + Scattered, + /// All of it is one run of one section: the section and the offset of + /// `at` in it. + Run(usize, u64), +} + +fn cover_in(views: &BTreeMap, at: usize, len: usize) -> Cover { + let end = at + len.max(1); + let Some((&base, &(bytes, section, offset))) = views.range(..=at).next_back().filter(|(base, view)| *base + view.0 > at) else { + return Cover::None; + }; + let first = (section, offset + (at - base) as u64); + let (mut reached, mut one) = (base + bytes, true); + while reached < end { + let Some(&(bytes, s, o)) = views.get(&reached) else { + return Cover::Holes; + }; + one &= s == first.0 && o == first.1 + (reached - at) as u64; + reached += bytes; + } + if one { Cover::Run(first.0, first.1) } else { Cover::Scattered } +} + +/// [`Cover`] of `[at, at + len)` by the title's views as they are now. +pub(crate) fn cover(at: usize, len: usize) -> Cover { + cover_in(&views().views, at, len) +} + +/// Whether `[at, at + len)` is private memory, all committed and +/// read-write: what [`From::Part`] takes. One question to Windows (it +/// walks the page tables to the end of the pages that share the first +/// one's state: a millisecond in the title's big blocks, so ask when a +/// copy is made, not when it is used). +pub(crate) fn private_whole(at: usize, len: usize) -> bool { + // SAFETY: plain data filled in by the query. + let mut info: mem::MEMORY_BASIC_INFORMATION = unsafe { std::mem::zeroed() }; + // SAFETY: a valid out pointer of the right size. + let n = unsafe { mem::VirtualQuery(at as *const c_void, &mut info, size_of_val(&info)) }; + n != 0 + && info.State == mem::MEM_COMMIT + && info.Type == mem::MEM_PRIVATE + && info.Protect == mem::PAGE_READWRITE + && (info.BaseAddress as usize).saturating_add(info.RegionSize) >= at.saturating_add(len) +} + +fn hr(result: &windows::core::Result) -> String { + match result { + Ok(_) => "ok".to_owned(), + Err(e) => format!("REFUSED {:#010x} ({})", e.code().0, e.message().trim()), + } +} + +/// A queue, a list and a fence of the probe's own on `device`: nothing of +/// the host's submissions is touched. +struct Rig { + device: ID3D12Device, + queue: ID3D12CommandQueue, + allocator: ID3D12CommandAllocator, + list: ID3D12GraphicsCommandList, + fence: ID3D12Fence, + done: u64, + event: HANDLE, +} + +impl Drop for Rig { + fn drop(&mut self) { + // SAFETY: our event. + unsafe { + let _ = windows::Win32::Foundation::CloseHandle(self.event); + } + } +} + +impl Rig { + fn new(device: &ID3D12Device) -> windows::core::Result { + // SAFETY: plain creation of objects of our own. + unsafe { + let queue: ID3D12CommandQueue = + device.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC { Type: D3D12_COMMAND_LIST_TYPE_DIRECT, ..Default::default() })?; + let allocator: ID3D12CommandAllocator = device.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT)?; + let list: ID3D12GraphicsCommandList = device.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &allocator, None)?; + list.Close()?; + let fence: ID3D12Fence = device.CreateFence(0, D3D12_FENCE_FLAG_NONE)?; + let event = CreateEventW(None, false, false, None)?; + Ok(Rig { device: device.clone(), queue, allocator, list, fence, done: 0, event }) + } + } + + /// Records with `record`, runs it and waits (ten seconds at most). + fn run(&mut self, record: impl FnOnce(&ID3D12GraphicsCommandList)) -> windows::core::Result<()> { + // SAFETY: our own list and queue, one run at a time. + unsafe { + self.allocator.Reset()?; + self.list.Reset(&self.allocator, None)?; + record(&self.list); + self.list.Close()?; + self.queue.ExecuteCommandLists(&[Some(self.list.cast()?)]); + self.done += 1; + self.queue.Signal(&self.fence, self.done)?; + self.fence.SetEventOnCompletion(self.done, self.event)?; + if WaitForSingleObject(self.event, 10_000).0 != 0 { + return Err(windows::core::Error::from_hresult(windows::Win32::Foundation::E_FAIL)); + } + self.device.GetDeviceRemovedReason() + } + } + + fn committed(&self, kind: D3D12_HEAP_TYPE, size: u64, state: D3D12_RESOURCE_STATES) -> windows::core::Result { + let heap = D3D12_HEAP_PROPERTIES { Type: kind, ..Default::default() }; + let mut buffer: Option = None; + // SAFETY: plain creation. + unsafe { + self.device + .CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &buffer_desc(size, D3D12_RESOURCE_FLAG_NONE), state, None, &mut buffer)? + }; + buffer.ok_or_else(windows::core::Error::empty) + } + + /// What the GPU reads of `size` bytes of `resource` from `offset`. + fn fetch(&mut self, resource: &ID3D12Resource, offset: u64, size: usize) -> windows::core::Result> { + let back = self.committed(D3D12_HEAP_TYPE_READBACK, size as u64, D3D12_RESOURCE_STATE_COPY_DEST)?; + // SAFETY: two live buffers, the range inside both. + self.run(|list| unsafe { list.CopyBufferRegion(&back, 0, resource, offset, size as u64) })?; + let mut data = std::ptr::null_mut(); + // SAFETY: the mapping holds `size` bytes until unmapped. + unsafe { + back.Map(0, None, Some(&mut data))?; + let bytes = std::slice::from_raw_parts(data.cast::(), size).to_vec(); + back.Unmap(0, None); + Ok(bytes) + } + } + + /// The GPU writes `bytes` at `offset` of `resource` (a copy). + fn store(&mut self, resource: &ID3D12Resource, offset: u64, bytes: &[u8]) -> windows::core::Result<()> { + let up = self.committed(D3D12_HEAP_TYPE_UPLOAD, bytes.len() as u64, D3D12_RESOURCE_STATE_GENERIC_READ)?; + let mut data = std::ptr::null_mut(); + // SAFETY: the mapping holds the buffer's bytes until unmapped. + unsafe { + up.Map(0, None, Some(&mut data))?; + std::ptr::copy_nonoverlapping(bytes.as_ptr(), data.cast::(), bytes.len()); + up.Unmap(0, None); + } + // SAFETY: two live buffers, the range inside both. + self.run(|list| unsafe { list.CopyBufferRegion(resource, offset, &up, 0, bytes.len() as u64) }) + } + + /// A compute shader stores, through a root unordered-access view at + /// `gpu`, the sum of the buffer's first two words in its third. + fn shade(&mut self, gpu: u64) -> windows::core::Result<()> { + const SOURCE: &str = "#define RS \"UAV(u0)\"\nRWByteAddressBuffer b : register(u0);\n[RootSignature(RS)]\n[numthreads(1, 1, 1)]\nvoid main() { b.Store(8, b.Load(0) + b.Load(4)); }\n"; + let mut code: Option = None; + // SAFETY: the source and names live through the call; then the + // blob's own bytes, which hold the root signature too. + let (root, pso): (ID3D12RootSignature, ID3D12PipelineState) = unsafe { + D3DCompile(SOURCE.as_ptr().cast(), SOURCE.len(), s!("inplace"), None, None, s!("main"), s!("cs_5_1"), 0, 0, &mut code, None)?; + let code = code.ok_or_else(windows::core::Error::empty)?; + let bytes = std::slice::from_raw_parts(code.GetBufferPointer().cast::(), code.GetBufferSize()); + let root: ID3D12RootSignature = self.device.CreateRootSignature(0, bytes)?; + let pso = self.device.CreateComputePipelineState(&D3D12_COMPUTE_PIPELINE_STATE_DESC { + pRootSignature: std::mem::transmute_copy(&root), + CS: D3D12_SHADER_BYTECODE { pShaderBytecode: bytes.as_ptr().cast(), BytecodeLength: bytes.len() }, + ..Default::default() + })?; + (root, pso) + }; + // SAFETY: an open list of ours; the view names a live buffer. + self.run(|list| unsafe { + list.SetComputeRootSignature(&root); + list.SetPipelineState(&pso); + list.SetComputeRootUnorderedAccessView(0, gpu); + list.Dispatch(1, 1, 1); + }) + } + + /// Milliseconds the card takes to copy `bytes` of `from` into its own + /// memory, the best of three. + fn copy_ms(&mut self, from: &ID3D12Resource, bytes: u64) -> windows::core::Result { + let heap = D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() }; + let mut to: Option = None; + // SAFETY: plain creation. + unsafe { + self.device.CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &buffer_desc(bytes, D3D12_RESOURCE_FLAG_NONE), D3D12_RESOURCE_STATE_COMMON, None, &mut to)? + }; + let to = to.ok_or_else(windows::core::Error::empty)?; + let mut best = f64::MAX; + for _ in 0..3 { + let started = std::time::Instant::now(); + // SAFETY: two live buffers of `bytes` bytes or more. + self.run(|list| unsafe { list.CopyBufferRegion(&to, 0, from, 0, bytes) })?; + best = best.min(started.elapsed().as_secs_f64() * 1000.0); + } + Ok(best) + } +} + +fn fill(at: *mut u8, len: usize, seed: u8) { + for i in 0..len { + // SAFETY: the caller's own committed memory of `len` bytes. + unsafe { at.add(i).write((i as u8).wrapping_mul(31).wrapping_add(seed)) }; + } +} + +fn same(at: *const u8, bytes: &[u8]) -> bool { + // SAFETY: the caller's own committed memory of that length. + unsafe { std::slice::from_raw_parts(at, bytes.len()) == bytes } +} + +/// The process's working set in MB. +fn working_set_mb() -> u64 { + use windows_sys::Win32::System::ProcessStatus::{K32GetProcessMemoryInfo, PROCESS_MEMORY_COUNTERS}; + let mut counters = PROCESS_MEMORY_COUNTERS { cb: size_of::() as u32, ..Default::default() }; + // SAFETY: our own process and a sized structure. + unsafe { K32GetProcessMemoryInfo(windows_sys::Win32::System::Threading::GetCurrentProcess(), &mut counters, counters.cb) }; + counters.WorkingSetSize as u64 >> 20 +} + +/// What the probe found. The lines are the whole account; the flags are +/// what the stages build on. +#[derive(Default)] +pub(crate) struct Probe { + pub(crate) lines: Vec, + /// A part of private, write-watched memory opens, a buffer in it shows + /// the memory's bytes to the GPU, also those the CPU wrote afterwards. + pub(crate) part_reads: bool, + /// What the GPU writes there (a copy, and a shader through unordered + /// access) the CPU reads at the memory's address. + pub(crate) part_writes: bool, + /// The same two for a committed section, through a view of it. + pub(crate) section_reads: bool, + pub(crate) section_writes: bool, + /// The section's heap outlives the view: the GPU's write with no view + /// mapped shows in a view mapped afterwards. + pub(crate) section_outlives_views: bool, + /// A section made with `SEC_RESERVE` (as `xmem` makes the page pool) + /// was refused. + pub(crate) reserved_section_refused: bool, +} + +/// Tries the openings on memory of the probe's own, made the way `xmem` +/// makes title memory, with a queue of its own on `device`; `memory` +/// gives the card's memory account (`Host::video_memory`) where there is +/// one. Nothing of the title's is touched. `mb` is the size of the cost +/// measurement (0 leaves it out). +pub(crate) fn probe(device: &ID3D12Device, memory: &dyn Fn() -> Option<[u64; 4]>, mb: usize) -> Probe { + let mut p = Probe::default(); + let mut rig = match Rig::new(device) { + Ok(rig) => rig, + Err(e) => { + p.lines.push(format!("no queue of its own: {e}")); + return p; + } + }; + let mut options = D3D12_FEATURE_DATA_D3D12_OPTIONS::default(); + // SAFETY: a plain query that fills our structure. + let _ = unsafe { device.CheckFeatureSupport(D3D12_FEATURE_D3D12_OPTIONS, (&raw mut options).cast(), size_of_val(&options) as u32) }; + p.lines.push(format!( + "the device: ID3D12Device3 {}, ID3D12Device13 {} (parts of an allocation); cross-adapter row-major textures {}; heap tier {}", + device.cast::().is_ok(), + device.cast::().is_ok(), + options.CrossAdapterRowMajorTextureSupported.as_bool(), + options.ResourceHeapTier.0 + )); + // SAFETY: memory of the probe's own, made and released here; every + // address used lies inside it. + unsafe { + private(&mut p, &mut rig); + section(&mut p, &mut rig); + if mb > 0 { + cost(&mut p, &mut rig, memory, mb); + } + } + p.lines.push(format!( + "VERDICT: private memory in place: reads {}, writes {}; the page pool's section in place: reads {}, writes {}, whatever the views do {}; \ + a reserved section is refused {} (the pool must be made committed to be opened)", + p.part_reads, p.part_writes, p.section_reads, p.section_writes, p.section_outlives_views, p.reserved_section_refused + )); + p +} + +fn describe(heap: &ID3D12Heap) -> String { + // SAFETY: a plain query. + let d = unsafe { heap.GetDesc() }; + format!( + "heap of {} KiB: type {} (4 = custom), CPU pages {} (3 = write-back), pool {} (1 = the PC's memory), alignment {}, flags {:#x} (0x1 shared, 0x20 cross-adapter, 0x200 write watch, 0x400 shader atomics)", + d.SizeInBytes >> 10, + d.Properties.Type.0, + d.Properties.CPUPageProperty.0, + d.Properties.MemoryPoolPreference.0, + d.Alignment, + d.Flags.0 + ) +} + +/// Private memory, reserved as `xmem` reserves the title's heaps +/// (committed, read-write, write-watched): a part of it opened. +unsafe fn private(p: &mut Probe, rig: &mut Rig) { + const SIZE: usize = 64 * K64; + // SAFETY (the whole function): the allocation below, `SIZE` bytes. + unsafe { + let base = mem::VirtualAlloc(std::ptr::null(), SIZE, mem::MEM_RESERVE | mem::MEM_COMMIT | MEM_WRITE_WATCH, mem::PAGE_READWRITE).cast::(); + if base.is_null() { + p.lines.push("private memory: none to try with".to_owned()); + return; + } + // The part: 16 pages from the 16th on. + let (at, bytes) = (base.add(16 * K64), 16 * K64); + let whole = open(&rig.device, From::Region(base as usize)); + p.lines.push(format!("private memory, the whole allocation (OpenExistingHeapFromAddress): {}", hr(&whole))); + drop(whole); + let opened = open(&rig.device, From::Part(at as usize, bytes)); + p.lines.push(format!("private memory, a part of it (OpenExistingHeapFromAddress1): {}", hr(&opened))); + if let Ok(heap) = &opened { + p.lines.push(format!(" {}", describe(heap))); + let placed = place(&rig.device, heap, K64 as u64, 4 * K64 as u64); + p.lines.push(format!(" a buffer placed in it (cross-adapter, unordered access): {}", hr(&placed))); + if let Ok(buffer) = &placed { + let memory = at.add(K64); + fill(memory, 4 * K64, 1); + let first = rig.fetch(buffer, 0, 4 * K64).is_ok_and(|got| same(memory, &got)); + fill(memory, 4 * K64, 77); + let second = rig.fetch(buffer, 0, 4 * K64).is_ok_and(|got| same(memory, &got)); + p.part_reads = first && second; + p.lines.push(format!(" the GPU reads the memory's bytes: {first}; and those the CPU wrote afterwards, with no call in between: {second}")); + mem::ResetWriteWatch(base.cast(), SIZE); + let new: Vec = (0..K64).map(|i| (i as u8) ^ 0x5a).collect(); + let copied = rig.store(buffer, 4096, &new).is_ok() && same(memory.add(4096), &new); + let (mut found, mut count, mut granularity) = ([0usize; 64], 64usize, 0u32); + let watched = mem::GetWriteWatch(0, base.cast(), SIZE, found.as_mut_ptr().cast(), &mut count, &mut granularity) == 0; + memory.cast::<[u32; 3]>().write([40, 2, 0]); + let shaded = rig.shade(buffer.GetGPUVirtualAddress()); + let shader = shaded.is_ok() && memory.cast::<[u32; 3]>().read()[2] == 42; + p.part_writes = copied && shader; + p.lines.push(format!( + " the CPU reads at the memory's address what the GPU wrote: by a copy {copied}; by a shader through unordered access {shader} ({}); \ + write watching saw {} of the copy's 16 pages{}", + hr(&shaded), + if watched { count } else { 0 }, + if watched { "" } else { " (the asking failed)" } + )); + } + // What the title can still do with the pages while the heap stands. + let mut old = 0; + let protect_in = mem::VirtualProtect(at.add(8 * K64).cast(), K64, mem::PAGE_READONLY, &mut old) != 0; + if protect_in { + mem::VirtualProtect(at.add(8 * K64).cast(), K64, mem::PAGE_READWRITE, &mut old); + } + let decommit_in = mem::VirtualFree(at.add(9 * K64).cast(), K64, mem::MEM_DECOMMIT) != 0; + let decommit_out = mem::VirtualFree(base.add(40 * K64).cast(), K64, mem::MEM_DECOMMIT) != 0; + p.lines.push(format!( + " with the heap standing, the title's own calls: read-only inside the part {protect_in}, decommit inside {decommit_in}, decommit outside {decommit_out} \ + (false inside means the heap must go before the title frees or guards those pages)" + )); + drop(placed); + } + drop(opened); + let freed = mem::VirtualFree(base.cast(), 0, mem::MEM_RELEASE) != 0; + p.lines.push(format!(" released after the heap went: {freed}")); + } +} + +/// A section and a view of it in a placeholder, as `xmem` maps physical +/// pages: reserved (as it is made today) and committed. +unsafe fn section(p: &mut Probe, rig: &mut Rig) { + const SIZE: usize = 32 * K64; + // SAFETY (the whole function): the sections, placeholder and views + // made below. + unsafe { + let process = windows_sys::Win32::System::Threading::GetCurrentProcess(); + let invalid = windows_sys::Win32::Foundation::INVALID_HANDLE_VALUE; + let reserved = mem::CreateFileMappingW(invalid, std::ptr::null(), mem::PAGE_READWRITE | mem::SEC_RESERVE, 0, SIZE as u32, std::ptr::null()); + if !reserved.is_null() { + let opened = open(&rig.device, From::Section(reserved as usize)); + p.reserved_section_refused = opened.is_err(); + p.lines.push(format!("a section made reserved, as the page pool is today (OpenExistingHeapFromFileMapping): {}", hr(&opened))); + drop(opened); + windows_sys::Win32::Foundation::CloseHandle(reserved); + } + let handle = mem::CreateFileMappingW(invalid, std::ptr::null(), mem::PAGE_READWRITE | mem::SEC_COMMIT, 0, SIZE as u32, std::ptr::null()); + let hole = mem::VirtualAlloc2(process, std::ptr::null(), SIZE, mem::MEM_RESERVE | mem::MEM_RESERVE_PLACEHOLDER, mem::PAGE_NOACCESS, std::ptr::null_mut(), 0).cast::(); + if handle.is_null() || hole.is_null() { + p.lines.push("a committed section: none to try with".to_owned()); + return; + } + // Pages 4..12 of the section at the placeholder's start. + mem::VirtualFree(hole.cast(), 8 * K64, mem::MEM_RELEASE | mem::MEM_PRESERVE_PLACEHOLDER); + let view = mem::MapViewOfFile3(handle, process, hole.cast(), (4 * K64) as u64, 8 * K64, mem::MEM_REPLACE_PLACEHOLDER, mem::PAGE_READWRITE, std::ptr::null_mut(), 0); + let opened = open(&rig.device, From::Section(handle as usize)); + p.lines.push(format!("a section made committed (OpenExistingHeapFromFileMapping): {}", hr(&opened))); + let mut unmapped = false; + if let (Ok(heap), false) = (&opened, view.Value.is_null()) { + p.lines.push(format!(" {}", describe(heap))); + // The section's page 5 is the view's second page. + let placed = place(&rig.device, heap, 5 * K64 as u64, 2 * K64 as u64); + p.lines.push(format!(" a buffer placed at the section's offset of a view's pages: {}", hr(&placed))); + if let Ok(buffer) = &placed { + let memory = hole.add(K64); + fill(memory, 2 * K64, 3); + p.section_reads = rig.fetch(buffer, 0, 2 * K64).is_ok_and(|got| same(memory, &got)); + let new: Vec = (0..K64).map(|i| (i as u8) ^ 0x33).collect(); + p.section_writes = rig.store(buffer, 0, &new).is_ok() && same(memory, &new); + // The guard of `watch.rs`: the view read-only. + let mut old = 0; + let guarded = mem::VirtualProtect(memory.cast(), K64, mem::PAGE_READONLY, &mut old) != 0; + let new: Vec = (0..K64).map(|i| (i as u8) ^ 0x44).collect(); + let through = rig.store(buffer, 0, &new).is_ok() && same(memory, &new); + // The view goes; the GPU writes; another view shows it. + unmapped = mem::UnmapViewOfFile2(process, view, mem::MEM_PRESERVE_PLACEHOLDER) != 0; + let new: Vec = (0..K64).map(|i| (i as u8) ^ 0x55).collect(); + let stored = rig.store(buffer, 0, &new).is_ok(); + let other = mem::MapViewOfFile(handle, mem::FILE_MAP_WRITE, 0, (5 * K64) as u32, K64); + p.section_outlives_views = unmapped && stored && !other.Value.is_null() && same(other.Value.cast(), &new); + p.lines.push(format!( + " the GPU reads the view's bytes {}; the CPU reads through the view what the GPU wrote {}; the view made read-only under the heap {guarded}, \ + and the GPU writes it all the same {through}; the view unmapped under the heap {unmapped}, the GPU's write then shows in a view mapped afterwards {}", + p.section_reads, p.section_writes, p.section_outlives_views + )); + if !other.Value.is_null() { + mem::UnmapViewOfFile(other); + } + } + } + drop(opened); + if !unmapped && !view.Value.is_null() { + mem::UnmapViewOfFile2(process, view, mem::MEM_PRESERVE_PLACEHOLDER); + } + windows_sys::Win32::Foundation::CloseHandle(handle); + // The placeholder was split in two: each half is released. + mem::VirtualFree(hole.cast(), 0, mem::MEM_RELEASE); + mem::VirtualFree(hole.add(8 * K64).cast(), 0, mem::MEM_RELEASE); + } +} + +/// What opening costs, on `mb` MB each of private memory never touched +/// and of a committed section never touched: the time, the working set, +/// the card's account of the PC's memory shared with it; and how fast the +/// card copies out of such a heap against a shared buffer of today's kind. +unsafe fn cost(p: &mut Probe, rig: &mut Rig, memory: &dyn Fn() -> Option<[u64; 4]>, mb: usize) { + let bytes = mb << 20; + let shared = || memory().map_or(0, |m| m[3] >> 20); + let ms = |speed: Option| speed.map_or("?".to_owned(), |ms| format!("{ms:.1}")); + // SAFETY (the whole function): the allocation and the section below. + unsafe { + let base = mem::VirtualAlloc(std::ptr::null(), bytes, mem::MEM_RESERVE | mem::MEM_COMMIT | MEM_WRITE_WATCH, mem::PAGE_READWRITE).cast::(); + if !base.is_null() { + let (set, account, started) = (working_set_mb(), shared(), std::time::Instant::now()); + let opened = open(&rig.device, From::Part(base as usize, bytes)); + let took = started.elapsed().as_secs_f64() * 1000.0; + let placed = opened.as_ref().ok().and_then(|heap| place(&rig.device, heap, 0, bytes as u64).ok()); + let speed = placed.as_ref().and_then(|buffer| rig.copy_ms(buffer, bytes as u64).ok()); + p.lines.push(format!( + "cost, {mb} MB of private memory never touched: {}; opened in {took:.1} ms; working set {set} -> {} MB; shared with the card {account} -> {} MB; \ + the card copies it out in {} ms", + hr(&opened), + working_set_mb(), + shared(), + ms(speed) + )); + drop((placed, opened)); + mem::VirtualFree(base.cast(), 0, mem::MEM_RELEASE); + } + let invalid = windows_sys::Win32::Foundation::INVALID_HANDLE_VALUE; + let handle = mem::CreateFileMappingW(invalid, std::ptr::null(), mem::PAGE_READWRITE | mem::SEC_COMMIT, (bytes as u64 >> 32) as u32, bytes as u32, std::ptr::null()); + if !handle.is_null() { + let (set, account, started) = (working_set_mb(), shared(), std::time::Instant::now()); + let opened = open(&rig.device, From::Section(handle as usize)); + let took = started.elapsed().as_secs_f64() * 1000.0; + let (set_opened, account_opened) = (working_set_mb(), shared()); + let placed = opened.as_ref().ok().and_then(|heap| place(&rig.device, heap, 0, bytes as u64).ok()); + let speed = placed.as_ref().and_then(|buffer| rig.copy_ms(buffer, bytes as u64).ok()); + p.lines.push(format!( + "cost, {mb} MB of a committed section never touched: {}; opened in {took:.1} ms; working set {set} -> {set_opened} -> after the card read all of it {} MB; \ + shared with the card {account} -> {account_opened} -> {} MB; the card copies it out in {} ms", + hr(&opened), + working_set_mb(), + shared(), + ms(speed) + )); + drop((placed, opened)); + windows_sys::Win32::Foundation::CloseHandle(handle); + } + // Today's kind of host copy, for the comparison. + let heap = D3D12_HEAP_PROPERTIES { + Type: D3D12_HEAP_TYPE_CUSTOM, + CPUPageProperty: D3D12_CPU_PAGE_PROPERTY_WRITE_BACK, + MemoryPoolPreference: D3D12_MEMORY_POOL_L0, + ..Default::default() + }; + let mut buffer: Option = None; + let made = rig.device.CreateCommittedResource( + &heap, + D3D12_HEAP_FLAG_NONE, + &buffer_desc(bytes as u64, D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS), + D3D12_RESOURCE_STATE_COMMON, + None, + &mut buffer, + ); + if let (Ok(()), Some(buffer)) = (made, buffer) { + let speed = rig.copy_ms(&buffer, bytes as u64).ok(); + p.lines.push(format!("cost, for comparison: the card copies {mb} MB out of a shared buffer of today's kind in {} ms", ms(speed))); + } + } +} + +// The census: which of the title memory that has host copies today could +// be opened, and by which opening. + +/// Counts and bytes by kind, in the order of [`KINDS`]. +#[derive(Default, Clone, Copy)] +struct Tally([(u64, u64); 6]); + +const KINDS: [&str; 6] = [ + "private, committed whole (a part can be opened)", + "view memory, one run of a section (one placed buffer)", + "view memory, scattered pages", + "view memory with unmapped pages", + "private but not committed whole, or guarded", + "other", +]; + +fn kind_of(at: usize, len: usize, known: &mut Vec<(usize, usize)>) -> usize { + match cover(at, len) { + Cover::Run(..) => return 1, + Cover::Scattered => return 2, + Cover::Holes => return 3, + Cover::None => {} + } + let end = at + len; + if known.iter().any(|&(from, to)| from <= at && end <= to) { + return 0; + } + // SAFETY: plain data filled in by the query. + let mut info: mem::MEMORY_BASIC_INFORMATION = unsafe { std::mem::zeroed() }; + // SAFETY: a valid out pointer of the right size. + let n = unsafe { mem::VirtualQuery(at as *const c_void, &mut info, size_of_val(&info)) }; + if n == 0 { + return 5; + } + let reach = (info.BaseAddress as usize).saturating_add(info.RegionSize); + if info.Type == mem::MEM_PRIVATE && info.State == mem::MEM_COMMIT && info.Protect == mem::PAGE_READWRITE { + known.push((info.BaseAddress as usize, reach)); + return if reach >= end { 0 } else { 4 }; + } + match info.Type { + mem::MEM_PRIVATE => 4, + mem::MEM_MAPPED => 3, + _ => 5, + } +} + +/// The census lines for `spans` (start, bytes, whether a window outside +/// buffers). +fn census_of(spans: &[(u64, u64, bool)]) -> Vec { + let mut known = Vec::new(); + let (mut buffers, mut windows) = (Tally::default(), Tally::default()); + for &(start, len, window) in spans { + let kind = kind_of(start as usize, len as usize, &mut known); + let tally = if window { &mut windows } else { &mut buffers }; + tally.0[kind].0 += 1; + tally.0[kind].1 += len; + } + let mut lines = Vec::new(); + for (name, tally) in [("title buffers", buffers), ("windows outside buffers", windows)] { + let all = tally.0.iter().fold((0, 0), |a, b| (a.0 + b.0, a.1 + b.1)); + lines.push(format!("census, {name}: {} of {} MB", all.0, all.1 >> 20)); + for (kind, &(n, bytes)) in KINDS.iter().zip(&tally.0) { + if n > 0 { + lines.push(format!("census, {kind}: {n} of {} MB", bytes >> 20)); + } + } + } + let v = views(); + let (count, bytes) = (v.views.len(), v.views.values().map(|view| view.0 as u64).sum::()); + let pages = v.views.values().filter(|view| view.0 == K64).count(); + let big = v.views.values().map(|view| view.0).max().unwrap_or(0); + lines.push(format!( + "census, the title's views of physical pages: {count} of {} MB; {pages} of them one 64 KiB page; the longest {} MB", + bytes >> 20, + big >> 20 + )); + for &(_, bytes, committed) in &v.sections { + lines.push(format!( + "census, a section of {} MB, {}", + bytes >> 20, + if committed { "committed: it can be opened as one heap" } else { "reserved: refused as a heap until it is made with SEC_COMMIT" } + )); + } + lines +} + +/// With [`probe_level`] 2: one part of the title's own private memory +/// (the start of the biggest such title buffer, 4 MiB at most) is opened +/// for a moment, a buffer placed, 64 KiB read by the GPU and compared +/// with what the CPU reads there (the title may be writing it meanwhile: +/// the count of equal bytes is given), and all of it released. While the +/// heap stands (milliseconds) a `VirtualFree` of the title's on those +/// pages would fail. +fn real_part(spans: &[(u64, u64, bool)]) -> Vec { + let Some(host) = crate::host::host() else { + return Vec::new(); + }; + let mut known = Vec::new(); + let found = spans + .iter() + .filter(|s| !s.2 && s.1 >= 2 * K64 as u64) + .filter(|s| kind_of(s.0 as usize, s.1 as usize, &mut known) == 0) + .max_by_key(|s| s.1); + let Some(&(start, len, _)) = found else { + return vec!["the title's memory: no title buffer in private, committed memory to try".to_owned()]; + }; + let at = (start as usize).next_multiple_of(K64); + let bytes = ((start + len) as usize).saturating_sub(at).min(4 << 20) & !(K64 - 1); + if bytes == 0 || !private_whole(at, bytes) { + return vec!["the title's memory: the buffer found holds no whole 64 KiB page that is still committed".to_owned()]; + } + let mut lines = Vec::new(); + let (set, started) = (working_set_mb(), std::time::Instant::now()); + let opened = open(&host.device, From::Part(at, bytes)); + lines.push(format!( + "the title's memory, {} KiB at {at:#x} (of the title buffer {start:#x}+{len:#x}): {}; in {:.1} ms; working set {set} -> {} MB", + bytes >> 10, + hr(&opened), + started.elapsed().as_secs_f64() * 1000.0, + working_set_mb() + )); + if let Ok(heap) = &opened { + let placed = place(&host.device, heap, 0, bytes as u64); + lines.push(format!(" a buffer placed over it: {}", hr(&placed))); + if let (Ok(buffer), Ok(mut rig)) = (&placed, Rig::new(&host.device)) { + let mut before = vec![0u8; K64]; + crate::host::copy_mapped(before.as_mut_ptr(), at as *const u8, K64, false); + let got = rig.fetch(buffer, 0, K64); + let mut after = vec![0u8; K64]; + crate::host::copy_mapped(after.as_mut_ptr(), at as *const u8, K64, false); + match got { + Ok(got) => { + let equal = (0..K64).filter(|&i| got[i] == before[i] || got[i] == after[i]).count(); + let zeros = got.iter().filter(|&&b| b == 0).count(); + lines.push(format!( + " the GPU read 64 KiB of the title's own bytes: {equal} of {K64} equal to what the CPU read just before or just after ({zeros} of them zero)" + )); + } + Err(e) => lines.push(format!(" the GPU's read failed: {e}")), + } + } + } + lines +} + +/// Called once a second by the thread that submits, before a submission +/// (`host::sweep`): with [`probe_level`], the probe at the first call, the +/// census (on a thread of its own: it asks Windows about every copy) 30 +/// and 150 seconds later. +pub(crate) fn tick() { + if level() > 0 { + say(); + } + if probe_level() == 0 { + return; + } + static STARTED: AtomicU64 = AtomicU64::new(0); + static DONE: AtomicU64 = AtomicU64::new(0); + let now = crate::host::now_ms().max(1); + let started = match STARTED.compare_exchange(0, now, Ordering::Relaxed, Ordering::Relaxed) { + Ok(_) => { + let Some(host) = crate::host::host() else { + return; + }; + let mb = std::env::var("LEONIDA_INPLACE_PROBE_MB").ok().and_then(|v| v.trim().parse().ok()).unwrap_or(64usize); + let took = std::time::Instant::now(); + let probe = probe(&host.device, &|| host.video_memory(), mb.min(1024)); + for line in &probe.lines { + tracing::info!("in place probe: {line}"); + } + tracing::info!("in place probe: took {:.0} ms", took.elapsed().as_secs_f64() * 1000.0); + now + } + Err(started) => started, + }; + let due = match DONE.load(Ordering::Relaxed) { + 0 => now >= started + 30_000, + 1 => now >= started + 150_000, + _ => false, + }; + if due { + let which = DONE.fetch_add(1, Ordering::Relaxed); + std::thread::spawn(move || { + let spans = crate::shadow::spans(); + for line in census_of(&spans) { + tracing::info!("in place {line}"); + } + if which == 0 && probe_level() >= 2 { + for line in real_part(&spans) { + tracing::info!("in place probe: {line}"); + } + } + }); + } +} + +#[cfg(test)] +mod tests { + use super::*; + + /// Views as the runtime tells them: a range inside one view, or over + /// views that continue each other in one section, is one run; over + /// views from elsewhere it is scattered; over a gap it has holes. + #[test] + fn views_say_what_one_placed_buffer_could_show() { + let mut views = BTreeMap::new(); + let at = 0x7_0000_0000usize; + views.insert(at, (4 * K64, 9, 16 * K64 as u64)); + // Continues the first in the section. + views.insert(at + 4 * K64, (2 * K64, 9, 20 * K64 as u64)); + // Follows in address, from elsewhere in the section. + views.insert(at + 6 * K64, (K64, 9, 3 * K64 as u64)); + // After a gap of one page. + views.insert(at + 8 * K64, (K64, 9, 4 * K64 as u64)); + assert_eq!(cover_in(&views, at + K64, 2 * K64), Cover::Run(9, 17 * K64 as u64)); + assert_eq!(cover_in(&views, at + K64, 5 * K64), Cover::Run(9, 17 * K64 as u64)); + assert_eq!(cover_in(&views, at, 7 * K64), Cover::Scattered); + assert_eq!(cover_in(&views, at + 6 * K64, 3 * K64), Cover::Holes); + assert_eq!(cover_in(&views, at + 7 * K64, K64), Cover::None); + assert_eq!(cover_in(&views, at - K64, 2 * K64), Cover::None); + } + + /// What the runtime forgets when memory is mapped anew. + #[test] + fn remapped_memory_forgets_its_views() { + let at = 0x7_4000_0000usize; + title_memory_view(at, 4 * K64, 77, 0); + title_memory_view(at + 4 * K64, K64, 77, 4 * K64 as u64); + assert_eq!(cover(at, 5 * K64), Cover::Run(77, 0)); + // One page inside the first view goes: the whole view is forgotten + // (the runtime maps and tells again what stays of it). + views_gone(at + K64, K64); + assert_eq!(cover(at, K64), Cover::None); + assert_eq!(cover(at + 4 * K64, K64), Cover::Run(77, 4 * K64 as u64)); + views_gone(at + 4 * K64, K64); + assert_eq!(cover(at + 4 * K64, K64), Cover::None); + } + + /// Only private memory committed whole, read-write, is taken for a part. + #[test] + fn only_private_memory_committed_whole_is_a_part() { + // SAFETY: an allocation of the test's own. + unsafe { + let base = mem::VirtualAlloc(std::ptr::null(), 8 * K64, mem::MEM_RESERVE, mem::PAGE_NOACCESS).cast::(); + assert!(!base.is_null()); + assert!(!private_whole(base as usize, K64), "reserved only"); + mem::VirtualAlloc(base.cast(), 4 * K64, mem::MEM_COMMIT, mem::PAGE_READWRITE); + assert!(private_whole(base as usize, 4 * K64)); + assert!(private_whole(base as usize + K64, 2 * K64)); + assert!(!private_whole(base as usize, 5 * K64), "reaches into the reserved half"); + let mut old = 0; + mem::VirtualProtect(base.cast(), K64, mem::PAGE_READONLY, &mut old); + assert!(!private_whole(base as usize, 2 * K64), "a guarded page"); + mem::VirtualFree(base.cast(), 0, mem::MEM_RELEASE); + } + } + + pub(crate) fn warp() -> Option { + use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_12_0; + use windows::Win32::Graphics::Dxgi::*; + // SAFETY: plain DXGI queries and device creation on the software + // adapter; a card is never opened. + unsafe { + let factory: IDXGIFactory4 = CreateDXGIFactory2(DXGI_CREATE_FACTORY_FLAGS(0)).ok()?; + let adapter: IDXGIAdapter = factory.EnumWarpAdapter().ok()?; + let desc = adapter.cast::().ok()?.GetDesc1().ok()?; + if desc.Flags & DXGI_ADAPTER_FLAG_SOFTWARE.0 as u32 == 0 { + return None; + } + let mut device: Option = None; + D3D12CreateDevice(&adapter, D3D_FEATURE_LEVEL_12_0, &mut device).ok()?; + device + } + } + + /// The probe, whole, on the software adapter: the same calls the card + /// gets. The runtime's and the kernel's rules hold there; the card's + /// driver is what a run with `LEONIDA_INPLACE_PROBE=1` adds. + #[test] + fn warp_probe_opens_title_like_memory_and_the_gpu_sees_its_bytes() { + let Some(device) = warp() else { return }; + if device.cast::().is_err() { + eprintln!("no ID3D12Device13 here: parts of an allocation cannot be opened"); + return; + } + let probe = probe(&device, &|| None, 4); + for line in &probe.lines { + eprintln!("in place probe: {line}"); + } + assert!(probe.part_reads, "the GPU reads private memory in place"); + assert!(probe.part_writes, "GPU writes land in private memory"); + assert!(probe.section_reads && probe.section_writes, "a committed section in place"); + assert!(probe.section_outlives_views, "the section's heap does not depend on views"); + assert!(probe.reserved_section_refused, "a reserved section is refused"); + } + + /// Stage 1's own call on the software adapter: a title buffer that + /// begins and ends off the 64 KiB lines is placed over its pages, the + /// GPU reads the buffer's bytes at the offset the views use, and its + /// write lands at the title's address. Memory that is not committed + /// whole is turned down without asking the host. + #[test] + fn warp_a_title_buffer_in_place_shows_its_bytes_at_its_offset() { + let Some(device) = warp() else { return }; + if device.cast::().is_err() { + return; + } + // SAFETY: an allocation of the test's own. + unsafe { + let base = mem::VirtualAlloc(std::ptr::null(), 8 * K64, mem::MEM_RESERVE | mem::MEM_COMMIT | MEM_WRITE_WATCH, mem::PAGE_READWRITE).cast::(); + let (start, len) = (base as u64 + K64 as u64 + 0x1230, 2 * K64 as u64 + 5); + let placed = place_part(&device, start, len).unwrap_or_else(|e| panic!("not placed: {e:?}")); + assert_eq!(placed.bias, 0x1230); + assert_eq!(placed.gpu, placed.buffer.GetGPUVirtualAddress() + 0x1230); + assert_eq!(placed.buffer.GetDesc().Width, 3 * K64 as u64, "the pages that hold the buffer"); + let mut rig = Rig::new(&device).unwrap(); + fill(start as *mut u8, len as usize, 7); + let got = rig.fetch(&placed.buffer, placed.bias, len as usize).unwrap(); + assert!(same(start as *const u8, &got), "the GPU reads the title buffer's bytes"); + rig.store(&placed.buffer, placed.bias + 16, &[0xa5; 64]).unwrap(); + assert!(same((start + 16) as *const u8, &[0xa5; 64]), "the GPU's write is at the title's address"); + drop(placed); + // Half of it decommitted: turned down, the host not asked. + assert_ne!(mem::VirtualFree(base.add(2 * K64).cast(), K64, mem::MEM_DECOMMIT), 0); + assert!(matches!(place_part(&device, start, len), Err(None))); + mem::VirtualFree(base.cast(), 0, mem::MEM_RELEASE); + } + } + + /// The census names each kind of memory. + #[test] + fn census_tells_private_memory_from_views() { + // SAFETY: an allocation of the test's own. + unsafe { + let base = mem::VirtualAlloc(std::ptr::null(), 8 * K64, mem::MEM_RESERVE | mem::MEM_COMMIT, mem::PAGE_READWRITE) as u64; + let view = 0x7_8000_0000u64; + title_memory_view(view as usize, 2 * K64, 5, 0); + title_memory_view(view as usize + 2 * K64, K64, 5, 9 * K64 as u64); + let lines = census_of(&[(base, 2 * K64 as u64, false), (base + 4 * K64 as u64, K64 as u64, true), (view, K64 as u64, true), (view, 3 * K64 as u64, false)]); + let text = lines.join("\n"); + assert!(text.contains("census, title buffers: 2 of"), "{text}"); + assert!(text.contains("census, private, committed whole (a part can be opened): 1 of"), "{text}"); + assert!(text.contains("census, view memory, scattered pages: 1 of"), "{text}"); + assert!(text.contains("census, view memory, one run of a section (one placed buffer): 1 of"), "{text}"); + views_gone(view as usize, 3 * K64); + mem::VirtualFree(base as *mut c_void, 0, mem::MEM_RELEASE); + } + } +} diff --git a/crates/leonida-gpu/src/lib.rs b/crates/leonida-gpu/src/lib.rs new file mode 100644 index 000000000..4ec7d6f64 --- /dev/null +++ b/crates/leonida-gpu/src/lib.rs @@ -0,0 +1,85 @@ +//! D3D12.X on host D3D12. +//! +//! D3D12.X records commands from code inlined into the title, which writes +//! packets into the command list while its put pointer is below a limit and +//! calls the list's method otherwise. Our lists keep the limits at zero, so +//! every command arrives here as a call, to be run on host D3D12. The +//! title's GPU addresses are CPU addresses (console memory is unified). +//! +//! [`device`] is the device object titles create, [`dxgi`] its adapter side, +//! [`resource`] heaps and resources, [`fence`] fences, [`queue`] command +//! queues, [`list`] command allocators and lists, [`descriptor`] +//! descriptor heaps, [`root`] root signatures, [`query`] query heaps, +//! [`signature`] command signatures, [`pipeline`] pipeline states, +//! [`frame`] frame pacing, [`object`] what all console graphics objects +//! share, [`console`] which console model the title sees. Planned: +//! `present` (swap chain). + +#[cfg(all(windows, feature = "diagnostics"))] +mod capture; +#[cfg(windows)] +mod cardmeter; +pub mod console; +#[cfg(all(windows, feature = "diagnostics"))] +mod copystat; +pub mod descriptor; +pub mod device; +#[cfg(windows)] +mod drvwatch; +#[cfg(windows)] +mod fpsbox; +#[cfg(windows)] +mod spread; +#[cfg(windows)] +mod draw; +pub mod dxgi; +pub mod fence; +pub mod frame; +#[cfg(windows)] +pub mod framelog; +#[cfg(windows)] +mod host; +#[cfg(windows)] +mod indirect; +#[cfg(windows)] +mod inplace; +pub mod list; +pub mod object; +pub mod pipeline; +#[cfg(windows)] +mod plaincopy; +#[cfg(windows)] +mod primitive; +#[cfg(all(windows, feature = "diagnostics"))] +mod profile; +pub mod query; +pub mod queue; +#[cfg(windows)] +mod queue2; +pub mod resource; +pub mod root; +#[cfg(windows)] +mod sampler; +#[cfg(windows)] +pub mod shader_cache; +#[cfg(windows)] +mod memory; +#[cfg(windows)] +mod shadow; +#[cfg(windows)] +mod tiles; +pub mod signature; +#[cfg(windows)] +mod texture; +#[cfg(windows)] +mod watch; + +#[cfg(windows)] +pub use host::on_failure; +#[cfg(windows)] +pub use inplace::{title_memory_freeing, title_memory_section, title_memory_view}; +#[cfg(windows)] +pub use watch::{ + title_memory_reading, title_memory_remapped, title_memory_remapping, title_memory_written, + writing as kernel_will_write, +}; diff --git a/crates/leonida-gpu/src/list.rs b/crates/leonida-gpu/src/list.rs new file mode 100644 index 000000000..b96818835 --- /dev/null +++ b/crates/leonida-gpu/src/list.rs @@ -0,0 +1,2273 @@ +//! Command allocators and command lists. +//! +//! The title's inlined code writes packets into a list only while its put +//! pointer is below a limit, and calls the list's method otherwise. Our +//! lists keep the pointer and every limit at zero, so every command reaches +//! the table as a call. +//! +//! Each list records onto a host command list as its methods are called +//! (decision 0007); draw state lives in `crate::draw`. Methods not +//! written yet log once with their caller, so a run lists what to do next. +#![allow(clippy::not_unsafe_ptr_arg_deref)] + +use std::mem::offset_of; + +use crate::object::{ + self, ALLOCATOR, E_INVALIDARG, HRESULT, Iid, LIST, Object, S_OK, Table, This, guid, +}; +use crate::queue::Written; +use crate::resource::PAGEABLE_IIDS; + +const ALLOCATOR_IIDS: [Iid; 4] = [ + guid( + 0x6102dee4, + 0xaf59, + 0x4b09, + [0xb9, 0x99, 0xb4, 0x4d, 0x73, 0xf0, 0x9b, 0x24], + ), + PAGEABLE_IIDS[0], + PAGEABLE_IIDS[1], + PAGEABLE_IIDS[2], +]; + +/// The list interfaces up to `ID3D12GraphicsCommandList6` (the table has +/// all their slots): those whose ids are the same as on PC, the console's +/// own List5 and List6 (the title asks for List6), then the +/// device child's. +const LIST_IIDS: [Iid; 10] = [ + guid( + 0x7116d91c, + 0xe7e4, + 0x47ce, + [0xb8, 0xc6, 0xec, 0x81, 0x68, 0xf4, 0x37, 0xe5], + ), + guid( + 0x5b160d0f, + 0xac1b, + 0x4185, + [0x8b, 0xa8, 0xb3, 0xae, 0x42, 0xa5, 0xa4, 0x55], + ), + guid( + 0x553103fb, + 0x1fe7, + 0x4557, + [0xbb, 0x38, 0x94, 0x6d, 0x7d, 0x0e, 0x7c, 0xa7], + ), + guid( + 0x38c3e585, + 0xff17, + 0x412c, + [0x91, 0x50, 0x4f, 0xc6, 0xf9, 0xd7, 0x2a, 0x28], + ), + guid( + 0x6fda83a7, + 0xb84c, + 0x4e38, + [0x9a, 0xc8, 0xc7, 0xbd, 0x22, 0x01, 0x6b, 0x3d], + ), + guid( + 0x8754318e, + 0xd3a9, + 0x4541, + [0x98, 0xcf, 0x64, 0x5b, 0x50, 0xdc, 0x48, 0x74], + ), + guid( + 0x55050859, + 0x4024, + 0x474c, + [0x98, 0xcf, 0x64, 0x5b, 0x51, 0xdc, 0x48, 0x74], + ), + guid( + 0xc3827890, + 0x4024, + 0x474c, + [0x98, 0xcf, 0x64, 0x5b, 0x51, 0xdc, 0x48, 0x74], + ), + PAGEABLE_IIDS[1], + PAGEABLE_IIDS[2], +]; + +#[repr(C)] +struct Allocator { + object: Object, + kind: u32, +} + +/// The layout the title's inlined code reads. +#[repr(C)] +struct List { + object: Object, + kind: u32, + /// The put pointer, then the plain, draw, API and unbiased API limits: + /// all zero, so every inline check fails. + put: [u64; 5], + reserved: [u32; 64], + /// State the inline code keeps for building packets; unused by us. + graphics_root_headers: [u32; 128], + compute_root_headers: [u32; 128], + pipeline_shadow: [u32; 8], + /// Newer titles' lists are larger: the title's state flush + /// (title+0x32786) copies a pipeline's 32 bytes to +0x544..+0x564 and + /// tests +0x548, so its layout runs past 0x560. Its size is unknown; + /// this keeps our fields clear of whatever the title writes there. + newer: [u32; 256], + /// Ours, after the console layout: memory handed out by + /// [`allocate_upload`], kept until the list is reset; the host list the + /// calls record into (decision 0007), and the draw state the title set. + uploads: std::sync::Mutex>>, + #[cfg(windows)] + host: Option, + #[cfg(windows)] + state: std::sync::Mutex, + /// The parts of the recording before `host`, in order, each closed: the + /// list is cut at its waits for memory values ([`cut`]). + #[cfg(windows)] + earlier: Vec, + /// The waits recorded before the first work of `host`: the queue stands + /// at them before it runs `host`. + #[cfg(windows)] + gate: Vec, +} + +/// One part of a title list cut at its waits: the waits the queue stands +/// at, then the host list that runs once they are met. +#[cfg(windows)] +struct Part { + waits: Vec, + host: crate::host::HostList, +} +const _: () = assert!(offset_of!(List, put) == 0x18); +const _: () = assert!(offset_of!(List, pipeline_shadow) + 32 == 0x560); + +/// Runs `f` with the host list and draw state of a title list, if there +/// is a host GPU. +#[cfg(windows)] +fn with_state(this: This, f: impl FnOnce(&crate::host::HostList, &mut crate::draw::State)) { + let Some(list) = host_list(this) else { return }; + #[cfg(feature = "diagnostics")] + let started = std::time::Instant::now(); + // SAFETY: the title passes one of our lists. + let state = unsafe { &(*this.cast::()).state }; + f(list, &mut state.lock().unwrap_or_else(|e| e.into_inner())); + #[cfg(feature = "diagnostics")] + crate::copystat::recorded(started); + #[cfg(feature = "diagnostics")] + crate::profile::seen(crate::profile::Seen::Record); +} + +/// The submission of `lists` has run: each gives its descriptor tables' +/// slots back ([`crate::draw::State::tables_done`]). A list cut at waits +/// keeps them: its state goes with its last part. +#[cfg(windows)] +pub(crate) fn tables_done(lists: &[This]) { + for &this in lists { + if this.is_null() { + continue; + } + // SAFETY: the title passes our lists. + let list = unsafe { &*this.cast::() }; + if list.earlier.is_empty() { + list.state.lock().unwrap_or_else(|e| e.into_inner()).tables_done(); + } + } +} + +/// The host list behind a title list, if there is a host GPU. +#[cfg(windows)] +pub(crate) fn host_list<'a>(this: This) -> Option<&'a crate::host::HostList> { + if this.is_null() { + return None; + } + // SAFETY: the title passes one of our lists. + unsafe { (*this.cast::()).host.as_ref() } +} + +/// The host side of a submitted list, taken from it: a queue that waits +/// for a fence runs it later, and the title may reset the list meanwhile. +/// With it go the upload memory and the dynamic descriptor slots its +/// commands name, kept until it has run. +#[cfg(windows)] +pub(crate) struct Detached { + host: crate::host::HostList, + _uploads: Vec>, + _state: crate::draw::State, +} + +#[cfg(windows)] +impl Detached { + pub(crate) fn host(&self) -> &crate::host::HostList { + &self.host + } +} + +/// A host list that has run and waits to be used again, and the bytes of +/// upload memory it keeps. +#[cfg(windows)] +struct Idle(crate::host::HostList, u64); + +// SAFETY: D3D12 objects are free-threaded, and an idle list is touched by +// nobody until it is taken out again. +#[cfg(windows)] +unsafe impl Send for Idle {} + +/// Host lists that have run, reset and ready to record: the host side of +/// a list a queue held, or of a part of a list cut at a wait, is taken +/// from the title's list at its submission, and the title's list needs +/// another. Each was made new and thrown away after its run: a hundred a +/// frame in gameplay, each two command allocators and two lists, and for +/// four in ten a budget and an argument buffer (run 61: "104 host lists +/// made 21.2 ms" a frame, and the graphics kernel's time to free them). +#[cfg(windows)] +static IDLE: std::sync::Mutex<(Vec, u64)> = std::sync::Mutex::new((Vec::new(), 0)); + +/// The most host lists kept idle, and the most upload memory they may keep +/// between them (a list keeps scratch chunks over a reset only while lists +/// do not share them, `LEONIDA_SCRATCH_POOL=0`). +#[cfg(windows)] +// (512 since run 221: with submissions prepared by a thread of ours the +// title has its lists back at once and resets them while the flights of +// the frame before are still in the air, so more than 128 are out at a +// time: 80 host lists were made and as many thrown away every frame, +// 8 ms to make and more to free, on the thread that submits.) +const IDLE_MOST: (usize, u64) = (512, 256 << 20); + +/// Whether host lists that have run are used again (on by default; +/// `LEONIDA_LIST_POOL=0`: each is made new and thrown away, as before). +#[cfg(windows)] +fn pools() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("LEONIDA_LIST_POOL").is_none_or(|v| v != "0")) +} + +/// A host list open for recording: one that has run, as a title's list is +/// after its reset, or a new one. +#[cfg(windows)] +fn fresh_list() -> Option { + let idle = { + let mut idle = IDLE.lock().unwrap_or_else(|e| e.into_inner()); + let taken = idle.0.pop(); + if let Some(Idle(_, bytes)) = &taken { + idle.1 -= bytes; + } + taken + }; + match idle { + Some(Idle(list, _)) => Some(list), + None => crate::host::host().and_then(|h| h.new_list().ok()), + } +} + +/// The host sides of lists whose submission has run (submissions are +/// waited for; `ran` names the ones it ran, by their place in `lists`): +/// what they held is let go, as before, and the host lists are reset and +/// kept for [`fresh_list`]. +#[cfg(windows)] +pub(crate) fn recycle(lists: Vec, ran: &[usize]) { + if !pools() { + return; + } + for (i, Detached { host, _uploads, _state }) in lists.into_iter().enumerate() { + // The descriptor slots and the upload memory its commands named. + drop(_state); + drop(_uploads); + if !ran.contains(&i) || IDLE.lock().unwrap_or_else(|e| e.into_inner()).0.len() >= IDLE_MOST.0 { + continue; + } + // As the title's reset does: what the list kept for its commands + // goes, its allocators stay. + host.reset(); + let bytes = host.scratch_kept(); + let mut idle = IDLE.lock().unwrap_or_else(|e| e.into_inner()); + if idle.0.len() < IDLE_MOST.0 && idle.1 + bytes <= IDLE_MOST.1 { + idle.0.push(Idle(host, bytes)); + idle.1 += bytes; + } + } +} + +/// A wait for a memory value recorded into list `this`, with waits cut +/// into lists (`crate::queue::cuts`). On the console the queue runs the +/// list up to the wait, stands there until the value is in memory, and +/// runs on; the list's bottom-of-pipe writes before the wait are done by +/// then, and other queues may be waiting for exactly those. So the +/// recording is cut here: the host list so far is closed and kept as a +/// part of its own ([`Part`]), the title's calls record into a new host +/// list from here on, and the wait stands before that one. A submission +/// then gives the queue the parts in order ([`detach_parts`]). +/// +/// A wait before any work (the first call after a reset, or a wait right +/// after another) cuts nothing: it joins the waits before the current +/// host list. +/// shortcut: a bottom-of-pipe write is done when its part has run, not at +/// its place in the part: a queue waiting for it starts later than on the +/// console, never earlier, and nothing can wait for itself that way (a +/// part has no wait after its first work). +#[cfg(windows)] +fn cut(this: This, wait: ValueWait) { + if this.is_null() { + return; + } + // SAFETY: the title passes one of our lists; a list is recorded by one + // thread at a time and is not submitted while it records. + let list = unsafe { &mut *this.cast_mut().cast::() }; + let Some(current) = list.host.as_ref() else { + return; + }; + if current.untouched() { + list.gate.push(wait); + return; + } + let Some(fresh) = fresh_list() else { + // shortcut: without a new host list the wait stands before the part + // it was recorded in. + static ONCE: std::sync::Once = std::sync::Once::new(); + ONCE.call_once(|| tracing::warn!("no host list for the part after a wait: the wait moves to the part's start")); + list.gate.push(wait); + return; + }; + current.close(); + static CUTS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + if CUTS.fetch_add(1, std::sync::atomic::Ordering::Relaxed) < 4 { + tracing::info!(parts = list.earlier.len() + 2, "a list is cut at a wait for a memory value"); + } + if let Some(done) = list.host.replace(fresh) { + let waits = std::mem::replace(&mut list.gate, vec![wait]); + list.earlier.push(Part { waits, host: done }); + } + // What the title set so far, on the new host list. + if let Some(host) = list.host.as_ref() { + list.state + .lock() + .unwrap_or_else(|e| e.into_inner()) + .replay(host); + } +} + +/// Whether list `this` recorded a wait for a memory value (with waits cut +/// into lists). +#[cfg(windows)] +pub(crate) fn cut_list(this: This) -> bool { + if this.is_null() { + return false; + } + // SAFETY: one of our lists, closed and submitted: nothing records + // into it. + let list = unsafe { &*this.cast::() }; + !list.earlier.is_empty() || !list.gate.is_empty() +} + +/// What a queue is given for submitted lists that were cut at their waits: +/// the waits it stands at, the host lists it runs once they are met, and +/// the order those run in. +#[cfg(windows)] +pub(crate) type Parts = Vec<(Vec, Vec, Vec)>; + +/// Takes the host sides of the submitted `lists`, part by part ([`cut`]), +/// and leaves each list a new, closed host list for its next reset, as +/// [`detach`] does. What comes back is in the order the queue runs it: a +/// new entry starts at every part that has waits; host lists without +/// waits join the entry before them. The list's upload memory and draw +/// state (its dynamic descriptor slots) go with its last part, which runs +/// last. +/// shortcut: a list the submission names a second time runs again only if +/// it has one part and that part is in the entry being filled; otherwise +/// the second naming is dropped (logged once). +#[cfg(windows)] +pub(crate) fn detach_parts(lists: &[This]) -> Parts { + let mut parts: Parts = vec![(Vec::new(), Vec::new(), Vec::new())]; + // The lists taken: where its one host list is (entry, place), or none + // for a list of several parts. + let mut seen: Vec<(This, Option<(usize, usize)>)> = Vec::new(); + for &this in lists { + if this.is_null() { + continue; + } + if let Some(&(_, at)) = seen.iter().find(|(t, _)| *t == this) { + match at { + Some((entry, place)) if entry + 1 == parts.len() => parts[entry].2.push(place), + _ => { + static ONCE: std::sync::Once = std::sync::Once::new(); + ONCE.call_once(|| { + tracing::warn!("a list named twice by a submission that waits for memory values runs once") + }); + } + } + continue; + } + let Some(fresh) = fresh_list() else { + continue; + }; + // A new host list is open; the title's next call on its list is a + // reset, which wants it closed. + fresh.close(); + // SAFETY: one of our lists, closed and submitted: nothing records + // into it until the title resets it. + let list = unsafe { &mut *this.cast_mut().cast::() }; + let Some(host) = list.host.replace(fresh) else { + continue; + }; + let earlier = std::mem::take(&mut list.earlier); + let gate = std::mem::take(&mut list.gate); + let uploads = std::mem::take(&mut *list.uploads.lock().unwrap_or_else(|e| e.into_inner())); + let state = std::mem::take(&mut *list.state.lock().unwrap_or_else(|e| e.into_inner())); + let single = earlier.is_empty() && gate.is_empty(); + let mut pieces: Vec<(Vec, Detached)> = earlier + .into_iter() + .map(|part| { + ( + part.waits, + Detached { + host: part.host, + _uploads: Vec::new(), + _state: Default::default(), + }, + ) + }) + .collect(); + pieces.push(( + gate, + Detached { + host, + _uploads: uploads, + _state: state, + }, + )); + let mut last = None; + for (waits, detached) in pieces { + if !waits.is_empty() { + parts.push((waits, Vec::new(), Vec::new())); + } + let entry = parts.len() - 1; + let (_, taken, order) = &mut parts[entry]; + let place = taken.len(); + order.push(place); + taken.push(detached); + last = Some((entry, place)); + } + seen.push((this, if single { last } else { None })); + } + // (The first entry is empty if the first list begins with a wait.) + parts.retain(|(_, taken, _)| !taken.is_empty()); + parts +} + +/// Takes the host sides of submitted lists (each once, however often the +/// submission names it) and leaves each list a new, closed host list for +/// its next reset: what was taken, and which of them run in what order. +#[cfg(windows)] +pub(crate) fn detach(lists: &[This]) -> (Vec, Vec) { + let mut taken: Vec<(This, Detached)> = Vec::new(); + let mut order = Vec::new(); + for &this in lists { + if this.is_null() { + continue; + } + if let Some(i) = taken.iter().position(|(t, _)| *t == this) { + order.push(i); + continue; + } + let Some(fresh) = fresh_list() else { + continue; + }; + // A new host list is open; the title's next call on its list is a + // reset, which wants it closed. + fresh.close(); + let list = this.cast_mut().cast::(); + // SAFETY: one of our lists, closed and submitted: nothing records + // into it until the title resets it. + let (host, uploads, state) = unsafe { + let Some(host) = (*list).host.replace(fresh) else { + continue; + }; + let uploads = + std::mem::take(&mut *(*list).uploads.lock().unwrap_or_else(|e| e.into_inner())); + let state = + std::mem::take(&mut *(*list).state.lock().unwrap_or_else(|e| e.into_inner())); + (host, uploads, state) + }; + order.push(taken.len()); + taken.push(( + this, + Detached { + host, + _uploads: uploads, + _state: state, + }, + )); + } + (taken.into_iter().map(|(_, d)| d).collect(), order) +} + +pub(crate) extern "system" fn create_allocator( + _: This, + kind: u32, + iid: *const Iid, + out: *mut This, +) -> HRESULT { + let allocator = Box::new(Allocator { + object: Object::new(&ALLOCATOR_FUNCTIONS), + kind, + }); + object::hand_out(ALLOCATOR, allocator, iid, &ALLOCATOR_IIDS, out) +} + +/// Lists start open, as in D3D12. +pub(crate) extern "system" fn create_list( + _: This, + _nodes: u32, + kind: u32, + allocator: This, + pipeline: This, + iid: *const Iid, + out: *mut This, +) -> HRESULT { + new_list(kind, allocator, pipeline, iid, out) +} + +/// The console's list creation: type, flags, node mask and barrier batch +/// size in a description. +#[repr(C)] +#[derive(Debug)] +pub(crate) struct ListDesc { + kind: u32, + flags: u32, + nodes: u32, + barrier_batch: u32, +} + +pub(crate) extern "system" fn create_list_x( + _: This, + desc: *const ListDesc, + allocator: This, + pipeline: This, + iid: *const Iid, + out: *mut This, +) -> HRESULT { + // SAFETY: the title passes a description (null is tolerated). + let Some(desc) = (unsafe { desc.as_ref() }) else { + return E_INVALIDARG; + }; + tracing::debug!(?desc, "console command list"); + new_list(desc.kind, allocator, pipeline, iid, out) +} + +/// `pipeline` is the list's initial pipeline (null: none), bound until the +/// title sets another, as after a reset. +fn new_list( + kind: u32, + allocator: This, + pipeline: This, + iid: *const Iid, + out: *mut This, +) -> HRESULT { + if allocator.is_null() { + return E_INVALIDARG; + } + tracing::debug!(kind, "command list"); + let list = Box::new(List { + object: if crate::device::newer() { + Object::new(&NEWER_LIST_FUNCTIONS) + } else { + Object::new(&LIST_FUNCTIONS) + }, + kind, + put: [0; 5], + reserved: [0; 64], + graphics_root_headers: [0; 128], + compute_root_headers: [0; 128], + pipeline_shadow: [0; 8], + newer: [0; 256], + uploads: Default::default(), + #[cfg(windows)] + host: crate::host::host().and_then(|h| match h.new_list() { + Ok(list) => Some(list), + Err(e) => { + tracing::warn!(error = %e, "no host command list"); + None + } + }), + #[cfg(windows)] + state: { + let mut state = crate::draw::State::default(); + state.set_pipeline(pipeline); + std::sync::Mutex::new(state) + }, + #[cfg(windows)] + earlier: Vec::new(), + #[cfg(windows)] + gate: Vec::new(), + }); + #[cfg(not(windows))] + let _ = pipeline; + object::hand_out(LIST, list, iid, &LIST_IIDS, out) +} + +extern "system" fn allocator_query(this: This, iid: *const Iid, out: *mut This) -> HRESULT { + let found = object::is(iid, &ALLOCATOR_IIDS).then_some(this); + object::answer(ALLOCATOR, iid, found, out) +} +extern "system" fn allocator_release(this: This) -> u32 { + object::release_boxed::(this) +} +/// Nothing is recorded, so there is nothing to free. +extern "system" fn allocator_reset(_: This) -> HRESULT { + S_OK +} + +extern "system" fn list_query(this: This, iid: *const Iid, out: *mut This) -> HRESULT { + object::answer(LIST, iid, object::is(iid, &LIST_IIDS).then_some(this), out) +} +extern "system" fn list_release(this: This) -> u32 { + object::release_boxed::(this) +} +extern "system" fn list_type(this: This) -> u32 { + // SAFETY: `this` is one of our lists. + unsafe { (*this.cast::()).kind } +} +extern "system" fn close(this: This) -> HRESULT { + #[cfg(windows)] + if let Some(host) = host_list(this) { + host.close(); + } + S_OK +} +extern "system" fn reset(this: This, allocator: This, pipeline: This) -> HRESULT { + if allocator.is_null() { + return E_INVALIDARG; + } + // A wait recorded and never submitted goes with the recording. + VALUE_WAITS + .lock() + .unwrap_or_else(|e| e.into_inner()) + .retain(|&(list, _)| list != this as usize); + // Every submission of the list has run (submissions are waited for). + // SAFETY: the title passes one of our lists. + let uploads = unsafe { &(*this.cast::()).uploads }; + uploads.lock().unwrap_or_else(|e| e.into_inner()).clear(); + // The parts of a recording that was cut and never submitted go with it + // (a submission takes the parts it runs). + #[cfg(windows)] + { + // SAFETY: the title passes one of our lists, and neither records + // into it nor submits it during its reset. + let list = unsafe { &mut *this.cast_mut().cast::() }; + list.earlier.clear(); + list.gate.clear(); + } + #[cfg(windows)] + with_state(this, |host, state| { + host.reset(); + state.reset(pipeline); + }); + #[cfg(not(windows))] + let _ = (this, pipeline); + S_OK +} + +/// A resource barrier as titles pass it: type, flags, then a resource and +/// either a subresource and two states (transition) or a second resource +/// (aliasing). The same layout as the host's. +#[repr(C)] +#[derive(Clone, Copy)] +pub(crate) struct Barrier { + kind: u32, + flags: u32, + first: This, + second: u64, + last: u64, +} + +/// The barrier on host resources, or `None` if it names a resource the host +/// GPU does not have (buffers so far). +#[cfg(windows)] +fn host_barrier(list: &crate::host::HostList, b: &Barrier) -> Option { + use windows::core::Interface; + let host = |r: This| crate::resource::host_resource(r).map(|h| h.as_raw().cast_const().cast()); + match b.kind { + 0 => { + // A split barrier's first half: its second half transitions. + const BEGIN_ONLY: u32 = 1; + if b.flags & BEGIN_ONLY != 0 { + return None; + } + // shortcut: whole resources, from the state the list tracked + // (`HostList::transition`); subresources are not told apart. + let wanted = crate::host::texture_state(b.last as u32); + let (texture, before) = list.transition(b.first, wanted)?; + Some(Barrier { + kind: 0, + flags: 0, + first: texture.as_raw().cast_const().cast(), + second: 0xffff_ffff | (u64::from(before) << 32), + last: u64::from(crate::host::legal_state(texture, wanted)), + }) + } + 1 => Some(Barrier { + first: if b.first.is_null() { + b.first + } else { + host(b.first)? + }, + second: if b.second == 0 { + 0 + } else { + host(b.second as This)? as u64 + }, + ..*b + }), + 2 => Some(Barrier { + first: if b.first.is_null() { + b.first + } else { + // A depth texture's unordered access is its colour twin's + // (the host gives the depth texture none): the barrier is + // on the texture shaders write. + match crate::resource::twin_resource(b.first) { + Some(twin) => twin.as_raw().cast_const().cast(), + None => host(b.first)?, + } + }, + ..*b + }), + _ => None, + } +} + +/// An unordered access barrier on every resource: earlier shader writes +/// finish before later work reads or writes. +const UAV_BARRIER: Barrier = Barrier { + kind: 2, + flags: 0, + first: std::ptr::null(), + second: 0, + last: 0, +}; + +/// Returns the console's barrier "actions" (none). +extern "system" fn barrier(this: This, count: u32, barriers: *const Barrier) -> u32 { + #[cfg(windows)] + if let Some(list) = host_list(this) + && !barriers.is_null() + { + // SAFETY: the title passes `count` barriers. + let barriers = unsafe { std::slice::from_raw_parts(barriers, count as usize) }; + let mut host: Vec = barriers + .iter() + .filter_map(|b| host_barrier(list, b)) + .collect(); + // Buffers have host copies, not resources the barrier can name: + // a barrier on one waits for every shader write before it. + if barriers.iter().any(|b| { + b.kind != 1 && !b.first.is_null() && crate::resource::buffer_bytes(b.first).is_some() + }) { + host.push(UAV_BARRIER); + #[cfg(feature = "diagnostics")] + crate::copystat::add(crate::copystat::C::WaitsForBuffers, 1); + } + if !host.is_empty() { + use windows::Win32::Graphics::Direct3D12::D3D12_RESOURCE_BARRIER; + const _: () = assert!(size_of::() == size_of::()); + // SAFETY: the same layout; borrowed resource pointers, never + // released through this slice. + let host = unsafe { + std::slice::from_raw_parts( + host.as_ptr().cast::(), + host.len(), + ) + }; + // SAFETY: an open list and live resources. + unsafe { list.list.ResourceBarrier(host) }; + } + } + 0 +} + +/// Moves a title texture's host copy to `state` in the list, if needed. +#[cfg(windows)] +pub(crate) fn ensure_state(list: &crate::host::HostList, resource: This, state: u32) { + use windows::Win32::Graphics::Direct3D12::D3D12_RESOURCE_STATES as State; + if let Some((texture, before)) = list.transition(resource, state) { + let state = crate::host::legal_state(texture, state); + let barrier = crate::host::transition(texture, State(before as i32), State(state as i32)); + // SAFETY: an open list and a live texture. + unsafe { list.list.ResourceBarrier(&[barrier]) }; + } +} + +#[cfg(windows)] +const COPY_DEST: u32 = 0x400; +#[cfg(windows)] +const COPY_SOURCE: u32 = 0x800; + +/// `len` bytes at `offset` of a title buffer, if they are inside it. +#[cfg(windows)] +fn buffer_range(buffer: This, offset: u64, len: u64) -> Option<*mut u8> { + let (data, size) = crate::resource::buffer_bytes(buffer)?; + let end = offset.checked_add(len)?; + if end > size { + tracing::warn!(offset, len, size, "copy outside its buffer"); + return None; + } + // SAFETY: inside the buffer, checked above. + Some(unsafe { data.add(offset as usize) }) +} + +/// Buffer to buffer: both are host memory, copied at submission. +extern "system" fn copy_buffer_region( + this: This, + dst: This, + dst_offset: u64, + src: This, + src_offset: u64, + len: u64, +) { + #[cfg(windows)] + if let Some(list) = host_list(this) + && let Some(to) = buffer_range(dst, dst_offset, len) + && let Some(from) = buffer_range(src, src_offset, len) + { + list.defer_copy(to, from, len as usize); + } + #[cfg(not(windows))] + let _ = (this, dst, dst_offset, src, src_offset, len); +} + +/// Whether one of two resources is a target in a stand-in format and the +/// other is not ([`crate::resource::target_format`]): their texels differ +/// in size, so the host cannot copy between them (logged once). +#[cfg(windows)] +fn unlike(dst: This, src: This) -> bool { + let unlike = crate::resource::stands_in(dst) != crate::resource::stands_in(src); + if unlike { + static ONCE: std::sync::Once = std::sync::Once::new(); + ONCE.call_once(|| { + tracing::warn!(?dst, ?src, "copy between a stand-in target and title-format texels skipped") + }); + } + unlike +} + +/// Copies left out because both sides were one host texture +/// ([`copy_resource`], [`copy_texture_region`]), since the start. +#[cfg(windows)] +pub(crate) static SELF_COPIES: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + +extern "system" fn copy_resource(this: This, dst: This, src: This) { + #[cfg(windows)] + { + let Some(list) = host_list(this) else { + return; + }; + if let (Some(to), Some(from)) = ( + crate::resource::host_resource(dst), + crate::resource::host_resource(src), + ) { + if unlike(dst, src) { + return; + } + // Two title textures over the same memory have one host + // texture between them: the copy would be of that texture onto + // itself, which the host does not allow, and it would change + // nothing. It was recorded all the same, with the texture left + // in the source state as the copy's destination (run 205's + // debug layer: "CopyResource with its destination in the + // COPY_SOURCE state", 37 times, a 2560x1440 depth texture). + // Only the two state changes and the copy are left out: what + // is noted of the textures stays as it was. After + // triippywhale 6e502b3b. + let same = windows::core::Interface::as_raw(to) == windows::core::Interface::as_raw(from); + // A source the title fills itself is uploaded first (upstream + // PR #671): a copy read whatever the host texture held. + if crate::texture::title_written(from) { + crate::texture::upload(list, src, from); + } + // Depth textures shaders also write: what they wrote, first. + list.twin_use(dst, false, true); + list.twin_use(src, false, false); + // A destination made level by level gets its levels' memory + // ahead of this list (`crate::tiles`). + crate::texture::card_writes(list, dst, to, None); + crate::texture::host_written(dst); + if same { + SELF_COPIES.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + static ONCE: std::sync::Once = std::sync::Once::new(); + ONCE.call_once(|| { + tracing::info!( + ?dst, + ?src, + "a copy between two title textures that share one host texture is left out: the first one" + ); + }); + return; + } + ensure_state(list, dst, COPY_DEST); + ensure_state(list, src, COPY_SOURCE); + #[cfg(feature = "diagnostics")] + list.note_op(|| format!("copy resource {src:?} to {dst:?}")); + // SAFETY: an open list and live textures. + unsafe { list.list.CopyResource(to, from) }; + } else if let (Some((to, a)), Some((from, b))) = ( + crate::resource::buffer_bytes(dst), + crate::resource::buffer_bytes(src), + ) { + list.defer_copy(to, from, a.min(b) as usize); + } + } + #[cfg(not(windows))] + let _ = (this, dst, src); +} + +extern "system" fn copy_resource_x(this: This, dst: This, src: This, _flags: u32) { + copy_resource(this, dst, src); +} + +/// A copy location as titles pass it, laid out as the host's: a resource, +/// then a subresource index (type 0) or a placed footprint (type 1). +#[repr(C)] +#[derive(Clone, Copy)] +pub(crate) struct CopyLocation { + resource: This, + kind: u32, + footprint: crate::resource::PlacedFootprint, +} + +/// Texture to texture on the GPU; buffer to texture through an upload +/// buffer filled at submission. Texture to buffer (read back) is not done +/// yet. +extern "system" fn copy_texture_region( + this: This, + dst: *const CopyLocation, + x: u32, + y: u32, + z: u32, + src: *const CopyLocation, + source_box: *const [u32; 6], +) { + #[cfg(windows)] + { + use windows::Win32::Graphics::Direct3D12::{D3D12_BOX, D3D12_TEXTURE_COPY_LOCATION}; + use windows::core::Interface; + const FOOTPRINT: u32 = 1; + // SAFETY: the title passes both locations (null is tolerated). + let (Some(list), Some(&dst), Some(&src)) = + (host_list(this), unsafe { dst.as_ref() }, unsafe { + src.as_ref() + }) + else { + return; + }; + let Some(to) = crate::resource::host_resource(dst.resource) else { + // Texture to buffer: a read back. The list copies the texels + // into a host buffer of ours; once it has run they go to the + // title's buffer (`HostList::defer_read_back`). + // The title reads two tiny float targets back every frame (5x1 + // and 1x1 RGBA32F, 80 and 16 bytes: run 90), and read a buffer + // nobody wrote. `LEONIDA_READ_BACK=0` leaves them unmade, as + // before. + static COUNT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + let n = COUNT.fetch_add(1, std::sync::atomic::Ordering::Relaxed) + 1; + let made = read_back(list, dst, x, y, z, src, source_box); + if n <= 16 || n.is_multiple_of(4096) || made.is_err() { + static REFUSED: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + if made.is_err() && REFUSED.fetch_add(1, std::sync::atomic::Ordering::Relaxed) >= 16 { + return; + } + let source = crate::resource::host_resource(src.resource).map(|r| { + // SAFETY: a live resource. + let d = unsafe { r.GetDesc() }; + format!("{}x{} f{} mips {}", d.Width, d.Height, d.Format.0, d.MipLevels) + }); + tracing::info!( + copies = n, + made = ?made, + source = ?source, + source_kind = src.kind, + destination_kind = dst.kind, + destination_offset = dst.footprint.offset, + destination_bytes = ?dst.footprint.bytes(), + "a texture to buffer copy (a read back)" + ); + } + return; + }; + if unlike(dst.resource, src.resource) { + return; + } + let mut from = src; + // Both sides are the same subresource of one host texture (set below). + let mut same = false; + let _upload; // keeps the source alive while this call records it + #[cfg(feature = "diagnostics")] + let mut read = None; + if src.kind == FOOTPRINT { + let (Some(host), Some(bytes)) = (crate::host::host(), src.footprint.bytes()) else { + return; + }; + let Some(data) = buffer_range(src.resource, src.footprint.offset, bytes) else { + return; + }; + let Some((buffer, staging)) = list.upload(host, bytes) else { + return; + }; + // The list owns this mapped D3D12 upload buffer. Wine can report + // its address as MEM_FREE, so use the host-upload path. + list.defer_fill(staging, data, bytes as usize); + from.resource = buffer.as_raw().cast_const().cast(); + from.footprint.offset = 0; + #[cfg(feature = "diagnostics")] + { + // SAFETY: a live buffer. + read = Some((unsafe { buffer.GetGPUVirtualAddress() }, bytes)); + } + _upload = buffer; + } else { + let Some(texture) = crate::resource::host_resource(src.resource) else { + return; + }; + // The same subresource of one host texture on both sides (two + // title textures over one memory): not a copy the host allows. + // The states and the copy are left out below; the rest is + // noted as before. + same = texture.as_raw() == to.as_raw() + && src.kind != FOOTPRINT + && dst.kind != FOOTPRINT + && src.footprint.offset as u32 == dst.footprint.offset as u32; + list.twin_use(src.resource, false, false); + if crate::texture::title_written(texture) { + crate::texture::upload(list, src.resource, texture); + } + if !same { + ensure_state(list, src.resource, COPY_SOURCE); + } + from.resource = texture.as_raw().cast_const().cast(); + } + // A depth texture shaders also write: what they wrote, first (the + // source above too). + list.twin_use(dst.resource, false, true); + // A destination made level by level gets the level's memory ahead + // of this list (`crate::tiles`): the title's bake copies each level + // of its result into a block-compressed texture of that kind, and + // a copy into a level without memory is dropped. + crate::texture::card_writes(list, dst.resource, to, Some(dst.footprint.offset as u32)); + crate::texture::host_written(dst.resource); + if same { + SELF_COPIES.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + return; + } + ensure_state(list, dst.resource, COPY_DEST); + let mut to_location = dst; + to_location.resource = to.as_raw().cast_const().cast(); + let host_box = (!source_box.is_null()).then(|| source_box.cast::()); + #[cfg(feature = "diagnostics")] + { + let text = || { + // SAFETY: a live texture; the box is the title's or null. + let (d, b) = unsafe { (to.GetDesc(), host_box.map(|b| *b)) }; + format!( + "copy to {:?} {}x{} f{} sub/kind {} at {x},{y},{z} from {:?} kind {} footprint {:?} box {b:?}", + dst.resource, + d.Width, + d.Height, + d.Format.0, + dst.kind, + src.resource, + src.kind, + (src.kind == FOOTPRINT).then_some(src.footprint) + ) + }; + match read { + Some(range) => list.note_read(text, range), + None => list.note_op(text), + } + } + const _: () = + assert!(size_of::() == size_of::()); + // SAFETY: an open list; both locations in the host's layout, naming + // live resources; the box is the title's (same layout). + unsafe { + list.list.CopyTextureRegion( + (&raw const to_location).cast(), + x, + y, + z, + (&raw const from).cast(), + host_box, + ) + }; + } + #[cfg(not(windows))] + let _ = (this, dst, x, y, z, src, source_box); +} + +/// Records a texture to buffer copy (a read back) of [`copy_texture_region`] +/// into `list`, or says why not. +#[cfg(windows)] +#[allow(clippy::too_many_arguments)] // the method's own arguments +fn read_back( + list: &crate::host::HostList, + dst: CopyLocation, + x: u32, + y: u32, + z: u32, + src: CopyLocation, + source_box: *const [u32; 6], +) -> Result<(), &'static str> { + use windows::Win32::Graphics::Direct3D12::D3D12_BOX; + use windows::core::Interface; + const FOOTPRINT: u32 = 1; + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + if !*ON.get_or_init(|| std::env::var_os("LEONIDA_READ_BACK").is_none_or(|v| v != "0")) { + return Err("switched off"); + } + if dst.kind != FOOTPRINT || src.kind == FOOTPRINT { + return Err("not a texture subresource into a placed footprint"); + } + if (x, y, z) != (0, 0, 0) { + return Err("a destination corner other than the footprint's"); + } + let host = crate::host::host().ok_or("no host")?; + let (footprint, [size, row, rows, pitch]) = dst.footprint.host_rows().ok_or("an unknown format")?; + // The title's buffer holds every row at its own pitch. + let bytes = pitch * (rows - 1) + row; + let data = buffer_range(dst.resource, dst.footprint.offset, bytes).ok_or("a destination outside its buffer")?; + let texture = crate::resource::host_resource(src.resource).ok_or("no host texture")?; + let buffer = host.read_back_buffer(size).ok_or("no read-back buffer")?; + // As a texture source of any copy: what shaders wrote to a depth twin + // and what the title wrote itself first, then the state. + list.twin_use(src.resource, false, false); + if crate::texture::title_written(texture) { + crate::texture::upload(list, src.resource, texture); + } + ensure_state(list, src.resource, COPY_SOURCE); + let mut from = src; + from.resource = texture.as_raw().cast_const().cast(); + let mut to = dst; + to.resource = buffer.as_raw().cast_const().cast(); + to.footprint = footprint; + let host_box = (!source_box.is_null()).then(|| source_box.cast::()); + #[cfg(feature = "diagnostics")] + list.note_op(|| { + format!( + "read back of {:?} sub {} into buffer {:?}+{:#x}: {rows} rows of {row} bytes", + src.resource, src.footprint.offset as u32, dst.resource, dst.footprint.offset + ) + }); + // SAFETY: an open list; both locations in the host's layout (asserted + // in `copy_texture_region`), naming a live texture and our buffer, which + // the list keeps until it is reset; the box is the title's. + unsafe { + list.list + .CopyTextureRegion((&raw const to).cast(), 0, 0, 0, (&raw const from).cast(), host_box) + }; + list.defer_read_back(buffer, data, [row as usize, rows as usize, pitch as usize]); + Ok(()) +} + +#[allow(clippy::too_many_arguments)] // the method's own arguments +extern "system" fn copy_texture_region_x( + this: This, + dst: *const CopyLocation, + x: u32, + y: u32, + z: u32, + src: *const CopyLocation, + source_box: *const [u32; 6], + _flags: u32, +) { + copy_texture_region(this, dst, x, y, z, src, source_box); +} + +extern "system" fn resolve( + this: This, + dst: This, + dst_sub: u32, + src: This, + src_sub: u32, + format: u32, +) { + #[cfg(windows)] + if let Some(list) = host_list(this) + && let (Some(to), Some(from)) = ( + crate::resource::host_resource(dst), + crate::resource::host_resource(src), + ) + { + use windows::Win32::Foundation::RECT; + use windows::Win32::Graphics::Direct3D12::{ + D3D12_RESOLVE_MODE_AVERAGE, ID3D12GraphicsCommandList1, + }; + use windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT; + use windows::core::Interface; + const RESOLVE_DEST: u32 = 0x1000; + const RESOLVE_SOURCE: u32 = 0x2000; + if unlike(dst, src) { + return; + } + // Depth textures shaders also write: what they wrote, first. + list.twin_use(dst, false, true); + list.twin_use(src, false, false); + // As for a copy (`crate::tiles`). + crate::texture::card_writes(list, dst, to, Some(dst_sub)); + ensure_state(list, dst, RESOLVE_DEST); + ensure_state(list, src, RESOLVE_SOURCE); + crate::texture::host_written(dst); + #[cfg(feature = "diagnostics")] + list.note_op(|| format!("resolve {src:?} to {dst:?} format {format}")); + // SAFETY: an open list and live textures; the region is inside both. + unsafe { + let (a, b) = (to.GetDesc(), from.GetDesc()); + let format = if crate::resource::stands_in(dst) { a.Format } else { DXGI_FORMAT(format as i32) }; + if (a.Width, a.Height) == (b.Width, b.Height) { + list.list + .ResolveSubresource(to, dst_sub, from, src_sub, format); + } else if let Ok(list1) = list.list.cast::() { + // The console clips a larger source to the destination. + let rect = RECT { + left: 0, + top: 0, + right: a.Width.min(b.Width) as i32, + bottom: a.Height.min(b.Height) as i32, + }; + list1.ResolveSubresourceRegion( + to, + dst_sub, + 0, + 0, + from, + src_sub, + Some(&rect), + format, + D3D12_RESOLVE_MODE_AVERAGE, + ); + } + } + } + #[cfg(not(windows))] + let _ = (this, dst, dst_sub, src, src_sub, format); +} + +#[repr(C)] +pub(crate) struct Rect { + left: i32, + top: i32, + right: i32, + bottom: i32, +} + +extern "system" fn clear_rtv( + this: This, + handle: u64, + color: *const [f32; 4], + count: u32, + rects: *const Rect, +) { + #[cfg(windows)] + { + let (Some(list), Some(record)) = (host_list(this), crate::descriptor::rtv_record(handle)) + else { + return; + }; + let (Some(texture), Some(host)) = ( + crate::resource::host_resource(record.resource), + crate::host::host(), + ) else { + return; + }; + // SAFETY: the title passes four floats (null is tolerated). + let Some(color) = (unsafe { color.as_ref() }) else { + return; + }; + let rects = (count > 0 && !rects.is_null()).then(|| { + // SAFETY: the title passes `count` rectangles, laid out as the host's. + unsafe { std::slice::from_raw_parts(rects.cast(), count as usize) } + }); + const RENDER_TARGET: u32 = 0x4; + let rtv = host.rtv(Some(texture), record.desc().as_ref()); + // SAFETY: an open list, a fresh view of a live texture. + unsafe { + if let Some((_, before)) = list.transition(record.resource, RENDER_TARGET) { + use windows::Win32::Graphics::Direct3D12::D3D12_RESOURCE_STATES as State; + list.list.ResourceBarrier(&[crate::host::transition( + texture, + State(before as i32), + State(RENDER_TARGET as i32), + )]); + } + list.list.ClearRenderTargetView(rtv, color, rects); + } + } + #[cfg(not(windows))] + let _ = (this, handle, color, count, rects); +} + +/// `ClearDepthStencilView(handle, flags, depth, stencil, count, rects)`; +/// flags: 1 depth, 2 stencil. +extern "system" fn clear_dsv( + this: This, + handle: u64, + flags: u32, + depth: f32, + stencil: u8, + count: u32, + rects: *const Rect, +) { + #[cfg(windows)] + { + use windows::Win32::Graphics::Direct3D12::D3D12_CLEAR_FLAGS; + let (Some(list), Some(record)) = (host_list(this), crate::descriptor::dsv_record(handle)) + else { + return; + }; + let (Some(texture), Some(host)) = ( + crate::resource::host_resource(record.resource), + crate::host::host(), + ) else { + return; + }; + let rects = (count > 0 && !rects.is_null()).then(|| { + // SAFETY: the title passes `count` rectangles, laid out as the host's. + unsafe { std::slice::from_raw_parts(rects.cast(), count as usize) } + }); + const DEPTH_WRITE: u32 = 0x10; + // A depth texture shaders also write: what they wrote, first (the + // clear may be of one slice or of some rectangles). + list.twin_use(record.resource, false, true); + ensure_state(list, record.resource, DEPTH_WRITE); + if crate::resource::depth_and_unordered(record.resource) { + crate::resource::DEPTH_UNORDERED[2].fetch_add(1, std::sync::atomic::Ordering::Relaxed); + } + let dsv = host.dsv(texture, record.depth_desc().as_ref()); + // SAFETY: an open list, a fresh view of a live texture. + unsafe { + list.list + .ClearDepthStencilView(dsv, D3D12_CLEAR_FLAGS(flags as i32 & 3), depth, stencil, rects) + }; + } + #[cfg(not(windows))] + let _ = (this, handle, flags, depth, stencil, count, rects); +} + +/// `CopyMemoryToMemoryX(destination, source, size, flags)`: GPU addresses +/// are title memory, copied at submission like buffer copies (if mapped). +extern "system" fn copy_memory(this: This, dst: u64, src: u64, len: u64, _flags: u32) { + #[cfg(windows)] + if let Some(list) = host_list(this) + && dst != 0 + && src != 0 + { + let len = len as usize; + list.defer(move || { + if crate::texture::committed(src as *const u8, len) + && crate::texture::committed(dst as *const u8, len) + { + // SAFETY: both ranges are committed title memory. + unsafe { std::ptr::copy(src as *const u8, dst as *mut u8, len) }; + } + }); + } + #[cfg(not(windows))] + let _ = (this, dst, src, len); +} + +/// `DriverHintX(feature, value)`: no hints for the host. +extern "system" fn driver_hint(_: This, _feature: u64, _value: u64) -> u64 { + 0 +} + +/// `DispatchX(x, y, z, flags)`: a dispatch with console flags, which the +/// host has no use for (the ray-tracing builder dispatches this way). +extern "system" fn dispatch_x(this: This, x: u32, y: u32, z: u32, _flags: u32) { + #[cfg(windows)] + state::dispatch(this, x, y, z); + #[cfg(not(windows))] + { + let _ = (this, x, y, z); + count_dispatch(); + } +} + +/// `BeginQuery`/`EndQuery(heap, type, index)`: queries are answered when +/// resolved. +extern "system" fn query_mark(_: This, _heap: This, _kind: u32, _index: u32) {} + +/// `ResolveQueryData(heap, type, first, count, buffer, offset)`: writes +/// each query's result into the buffer once the list has run. Timestamps +/// (type 2) are the GPU clock then; occlusion counts (0) say a million +/// samples passed and binary occlusion (1) visible, so nothing is culled +/// by a query. +/// shortcut: no query runs on the host GPU; results are plausible values, +/// not measured ones (time spans come out as the submission's length). +extern "system" fn resolve_queries( + this: This, + _heap: This, + kind: u32, + _first: u32, + count: u32, + buffer: This, + offset: u64, +) { + const OCCLUSION: u32 = 0; + const BINARY: u32 = 1; + const TIMESTAMP: u32 = 2; + const PIPELINE_STATISTICS: u32 = 3; + let Some((data, size)) = crate::resource::buffer_bytes(buffer) else { + return; + }; + let (what, bytes) = match kind { + OCCLUSION => (Written::Value(1 << 20), 8), + BINARY => (Written::Value(1), 8), + TIMESTAMP => (Written::GpuTimestamp, 8), + PIPELINE_STATISTICS => (Written::Value(0), 88), + _ => (Written::Value(0), 16), + }; + if offset + u64::from(count) * bytes > size { + return; + } + for i in 0..u64::from(count) { + // Wider results are written as 8-byte pieces. + for piece in 0..bytes / 8 { + // SAFETY: inside the buffer, checked above. + let at = unsafe { data.add((offset + i * bytes + piece * 8) as usize) }; + let what = if piece == 0 { what } else { Written::Value(0) }; + defer_write(this, at as u64, what, 8); + } + } +} + +/// IUnknown 3, object 4, device child 1, allocator 2. +static ALLOCATOR_FUNCTIONS: Table<24> = { + let mut f = object::d3d12_object(object::missing_table::()); + f[0] = allocator_query as *const (); + f[2] = allocator_release as *const (); + f[7] = object::parent_device as *const (); // 0x38 + f[8] = allocator_reset as *const (); // 0x40 + f[9] = object::ignore as *const (); // 0x48 allocation callback + Table(f) +}; + +extern "system" fn set_pipeline(this: This, pipeline: This) { + crate::pipeline::bound(pipeline); + #[cfg(windows)] + with_state(this, |_, state| state.set_pipeline(pipeline)); + #[cfg(not(windows))] + let _ = this; +} + +/// Pipeline syncs: waits for earlier work and cache flushes, at the top or +/// bottom of the pipe `(flags, control, address, size)`. Host lists order +/// their own work and every submission is waited for, so there is nothing +/// to do. +extern "system" fn sync(_: This, _flags: u32, _control: u32, _address: u64, _size: u64) {} + +/// Reset with console flags `(allocator, pipeline, flags)`; the flags only +/// tune the console's command memory. +extern "system" fn reset_x(this: This, allocator: This, pipeline: This, _flags: u32) -> HRESULT { + reset(this, allocator, pipeline) +} + +/// Newer lists' 0x4a0 `(size, alignment) -> pointer`: memory the list +/// owns until it is reset, which the CPU writes and the GPU reads at the +/// same address; null on failure. The title's BVH builder puts +/// its instance descriptions there (and wrote through our old +/// `E_NOTIMPL` as a pointer). +extern "system" fn allocate_upload(this: This, size: u64, alignment: u64) -> *mut u8 { + let align = usize::try_from(alignment).unwrap_or(0).max(16); + let Some(len) = usize::try_from(size).ok().and_then(|s| s.checked_add(align)) else { + return std::ptr::null_mut(); + }; + if this.is_null() || !align.is_power_of_two() { + return std::ptr::null_mut(); + } + let mut block = vec![0u8; len]; + let start = block.as_mut_ptr(); + // SAFETY: the offset is below `align`, so `size` bytes fit after it. + let at = unsafe { start.add(start.align_offset(align)) }; + // SAFETY: the title passes one of our lists. + let uploads = unsafe { &(*this.cast::()).uploads }; + // Moving the vector keeps its heap block where it is. + uploads.lock().unwrap_or_else(|e| e.into_inner()).push(block); + at +} + +/// Draw state the host has no use for (root signatures: ours come with +/// the pipeline; depth order and shading rate hints): any arguments, +/// nothing returned. +extern "system" fn ignored_state(_: This) {} + +/// The title's draw state (decision 0007, step 3), kept for its draws or +/// set on the host list at once. Without a host GPU these do nothing. +#[cfg(windows)] +mod state { + use super::{This, with_state}; + use crate::draw::{IndexView, VertexView}; + use windows::Win32::Foundation::RECT; + use windows::Win32::Graphics::Direct3D12::D3D12_VIEWPORT; + + /// `count` items at `items`, or none. + fn items<'a, T>(items: *const T, count: u32) -> &'a [T] { + if items.is_null() || count == 0 { + return &[]; + } + // SAFETY: the title passes `count` items. + unsafe { std::slice::from_raw_parts(items, count as usize) } + } + + pub(super) extern "system" fn topology(this: This, topology: u32) { + with_state(this, |list, s| s.set_topology(list, topology)); + } + pub(super) extern "system" fn viewports( + this: This, + count: u32, + viewports: *const D3D12_VIEWPORT, + ) { + // (Through the draw state, which keeps them for the host list + // that continues this one after a cut: `State::replay`.) + with_state(this, |list, s| s.set_viewports(list, items(viewports, count))); + } + pub(super) extern "system" fn scissors(this: This, count: u32, rects: *const RECT) { + with_state(this, |list, s| s.set_scissors(list, items(rects, count))); + } + pub(super) extern "system" fn blend_factor(this: This, factor: *const [f32; 4]) { + with_state(this, |list, s| { + // SAFETY: the title passes four floats or null. + s.set_blend_factor(list, unsafe { factor.as_ref() }) + }); + } + pub(super) extern "system" fn stencil_ref(this: This, reference: u32) { + with_state(this, |list, s| s.set_stencil_ref(list, reference)); + } + pub(super) extern "system" fn depth_bounds(this: This, min: f32, max: f32) { + with_state(this, |list, s| s.set_depth_bounds(list, min, max)); + } + pub(super) extern "system" fn heaps(this: This, count: u32, heaps: *const This) { + with_state(this, |_, s| s.set_heaps(items(heaps, count))); + } + pub(super) extern "system" fn compute_table(this: This, slot: u32, handle: u64) { + with_state(this, |_, s| s.set_table(true, slot, handle)); + } + pub(super) extern "system" fn graphics_table(this: This, slot: u32, handle: u64) { + with_state(this, |_, s| s.set_table(false, slot, handle)); + } + pub(super) extern "system" fn compute_constant(this: This, slot: u32, value: u32, offset: u32) { + with_state(this, |_, s| s.set_constants(true, slot, &[value], offset)); + } + pub(super) extern "system" fn graphics_constant( + this: This, + slot: u32, + value: u32, + offset: u32, + ) { + with_state(this, |_, s| s.set_constants(false, slot, &[value], offset)); + } + pub(super) extern "system" fn compute_constants( + this: This, + slot: u32, + count: u32, + values: *const u32, + offset: u32, + ) { + with_state(this, |_, s| { + s.set_constants(true, slot, items(values, count), offset) + }); + } + pub(super) extern "system" fn graphics_constants( + this: This, + slot: u32, + count: u32, + values: *const u32, + offset: u32, + ) { + with_state(this, |_, s| { + s.set_constants(false, slot, items(values, count), offset) + }); + } + /// Root constant buffer, shader resource and unordered access views. + pub(super) extern "system" fn compute_view(this: This, slot: u32, address: u64) { + with_state(this, |_, s| s.set_view(true, slot, address)); + } + pub(super) extern "system" fn graphics_view(this: This, slot: u32, address: u64) { + with_state(this, |_, s| s.set_view(false, slot, address)); + } + pub(super) extern "system" fn index_buffer(this: This, view: *const IndexView) { + // SAFETY: the title passes a view or null. + with_state(this, |_, s| s.set_index_buffer(unsafe { view.as_ref() })); + } + pub(super) extern "system" fn vertex_buffers( + this: This, + start: u32, + count: u32, + views: *const VertexView, + ) { + with_state(this, |_, s| { + if views.is_null() { + s.clear_vertex_buffers(start, count); + } else { + s.set_vertex_buffers(start, items(views, count)); + } + }); + } + /// `(count, handles, one range, depth)`: with one range, the handles + /// follow the first at the render target view size (128 bytes). + pub(super) extern "system" fn targets( + this: This, + count: u32, + handles: *const u64, + one_range: i32, + depth: *const u64, + ) { + let handles: Vec = if one_range != 0 && !handles.is_null() { + // SAFETY: the title passes the first handle. + let first = unsafe { *handles }; + (0..u64::from(count)).map(|i| first + 128 * i).collect() + } else { + items(handles, count).to_vec() + }; + // SAFETY: the title passes a handle or null. + let depth = unsafe { depth.as_ref() }.copied().unwrap_or(0); + with_state(this, |list, s| s.set_targets(list, &handles, depth)); + } + pub(super) extern "system" fn draw( + this: This, + vertices: u32, + instances: u32, + first: u32, + first_instance: u32, + ) { + super::count_draw(); + with_state(this, |list, s| { + s.draw(list, vertices, instances, first, first_instance) + }); + } + pub(super) extern "system" fn dispatch(this: This, x: u32, y: u32, z: u32) { + super::count_dispatch(); + with_state(this, |list, s| s.dispatch(list, x, y, z)); + } + /// `DispatchMesh(x, y, z)` (the PC method of List6); the title's mesh + /// programs take `x` groups only. + pub(super) extern "system" fn dispatch_mesh(this: This, x: u32, y: u32, z: u32) { + super::count_draw(); + if y * z != 1 { + static ONCE: std::sync::Once = std::sync::Once::new(); + ONCE.call_once(|| tracing::warn!(x, y, z, "a mesh dispatch with y or z groups")); + } + with_state(this, |list, s| s.dispatch_mesh(list, x)); + } + /// `DispatchMeshX(x, flags, indirect arguments, payload)`. + /// shortcut: dispatches whose group count is in GPU memory (indirect) + /// are dropped; make them ExecuteIndirect when the title uses them. + pub(super) extern "system" fn dispatch_mesh_x( + this: This, + x: u32, + _flags: u64, + indirect: u64, + _payload: u64, + ) { + super::count_draw(); + if indirect != 0 { + static ONCE: std::sync::Once = std::sync::Once::new(); + ONCE.call_once(|| tracing::warn!("indirect mesh dispatches dropped")); + return; + } + with_state(this, |list, s| s.dispatch_mesh(list, x)); + } + pub(super) extern "system" fn draw_indexed( + this: This, + indices: u32, + instances: u32, + first: u32, + base: i32, + first_instance: u32, + ) { + super::count_draw(); + with_state(this, |list, s| { + s.draw_indexed(list, indices, instances, first, base, first_instance) + }); + } +} + +/// Without a host GPU every draw state call is ignored. +#[cfg(not(windows))] +mod state { + pub(super) use super::dispatch; + pub(super) use super::draw; + pub(super) use super::draw as draw_indexed; + pub(super) use super::draw as dispatch_mesh; + pub(super) use super::draw as dispatch_mesh_x; + pub(super) use super::ignored_state as blend_factor; + pub(super) use super::ignored_state as compute_constant; + pub(super) use super::ignored_state as compute_constants; + pub(super) use super::ignored_state as compute_table; + pub(super) use super::ignored_state as compute_view; + pub(super) use super::ignored_state as graphics_constant; + pub(super) use super::ignored_state as graphics_constants; + pub(super) use super::ignored_state as graphics_table; + pub(super) use super::ignored_state as graphics_view; + pub(super) use super::ignored_state as heaps; + pub(super) use super::ignored_state as index_buffer; + pub(super) use super::ignored_state as scissors; + pub(super) use super::ignored_state as stencil_ref; + pub(super) use super::ignored_state as depth_bounds; + pub(super) use super::ignored_state as targets; + pub(super) use super::ignored_state as topology; + pub(super) use super::ignored_state as vertex_buffers; + pub(super) use super::ignored_state as viewports; +} + +fn count_draw() { + DRAWS.fetch_add(1, std::sync::atomic::Ordering::Relaxed); +} + +/// Draws of the kinds the host does not run yet (indirect, mesh), and +/// dispatches, counted per frame for the log. +/// shortcut: dropped until their shaders translate (decision 0007). +#[cfg(not(windows))] +extern "system" fn draw(_: This) { + count_draw(); +} + +/// `ExecuteIndirect(signature, max count, arguments, offset, count buffer, +/// offset)`. The title's signatures (title+0x2479466, 2026-11-24) +/// hold one argument each: draw (stride 16), indexed draw (20), dispatch +/// (12), mesh dispatch (12), and the console's single-pass dispatch, type +/// 105 (stride 12: the three group counts; its flags live in the +/// signature, the title passes none), run as a plain dispatch. They run +/// through the host's indirect execution (`State::execute_indirect`). +/// shortcut: signatures that change root arguments are dropped (logged +/// once per signature). +extern "system" fn execute_indirect( + this: This, + signature: This, + max: u32, + arguments: This, + offset: u64, + count: This, + count_offset: u64, +) { + count_draw(); + let Some((stride, args)) = crate::signature::layout(signature) else { + return; + }; + let address = crate::resource::buffer_bytes(arguments).map(|(p, _)| p as u64 + offset); + let counter = crate::resource::buffer_bytes(count).map(|(p, _)| p as u64 + count_offset); + let mut ran = false; + #[cfg(windows)] + if let ([[kind, ..]], Some(address)) = (args, address) + && (count.is_null() || counter.is_some()) + { + const DISPATCH: u32 = 2; + const DISPATCH_SINGLE: u32 = 105; + let kind = if *kind == DISPATCH_SINGLE { DISPATCH } else { *kind }; + with_state(this, |list, s| { + ran = s.execute_indirect(list, (kind, stride, max), address, counter); + }); + } else { + #[cfg(all(windows, feature = "diagnostics"))] + crate::pipeline::note_why(format!( + "indirect signature {args:?}: arguments in a buffer {}, count in a buffer {}", + address.is_some(), + count.is_null() || counter.is_some() + )); + } + if ran { + return; + } + INDIRECT.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + static SEEN: std::sync::Mutex> = std::sync::Mutex::new(Vec::new()); + let mut seen = SEEN.lock().unwrap_or_else(|e| e.into_inner()); + if !seen.contains(&(signature as usize)) { + seen.push(signature as usize); + tracing::info!( + stride, + ?args, + max, + address = ?address.map(|a| format!("{a:#x}")), + counted = !count.is_null(), + "indirect execution dropped (first time for this signature)" + ); + } +} + +/// Indirect executions dropped since the last call. +pub(crate) fn take_indirect() -> u64 { + INDIRECT.swap(0, std::sync::atomic::Ordering::Relaxed) +} +static INDIRECT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); +fn count_dispatch() { + DISPATCHES.fetch_add(1, std::sync::atomic::Ordering::Relaxed); +} +#[cfg(not(windows))] +extern "system" fn dispatch(_: This) { + count_dispatch(); +} +static DRAWS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); +static DISPATCHES: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + +/// Draws (any kind, mesh and indirect included) and compute dispatches +/// recorded since the last call. +pub(crate) fn take_counts() -> (u64, u64) { + use std::sync::atomic::Ordering::Relaxed; + (DRAWS.swap(0, Relaxed), DISPATCHES.swap(0, Relaxed)) +} + +/// A GPU wait for a memory value: the list's commands after it run when +/// the 32 or 64 bits at `address` compare as asked with `reference`. +#[derive(Clone, Copy, Debug)] +pub(crate) struct ValueWait { + address: u64, + comparison: u32, + reference: u64, + wide: bool, +} + +impl ValueWait { + /// Whether the memory holds what is waited for now. + /// shortcut: the comparison codes are taken to be the comparison + /// functions' (1 never .. 8 always, value against reference); one not + /// known counts as met, and so does memory that is not mapped. + /// + /// The value is read through the kernel, which reports memory that is + /// not there instead of faulting (as the copies of title memory are + /// read, `crate::host::copy_mapped`). Asking Windows first whether the + /// memory is committed (`VirtualQuery`) walks the page tables to the + /// end of the region: the title keeps these values in a 1.1 GB + /// allocation (0xd00000000), where one question took about 8 ms, and a + /// queue asks at every submission and every signal, for each queue that + /// stands at a wait (the title has five queues). That was + /// 1.0-2.2 s of every cutscene frame on the thread that submits (runs + /// 36-49: "between its submissions ... kernel"; 47 of 110 looks at + /// that thread in run 49 found it in this question). + /// `LEONIDA_WAIT_ASK=1` asks first, as before. + pub(crate) fn met(&self) -> bool { + #[cfg(all(windows, feature = "diagnostics"))] + let started = std::time::Instant::now(); + let met = self.holds(); + #[cfg(all(windows, feature = "diagnostics"))] + { + use crate::copystat::{C, add}; + add(C::WaitChecks, 1); + add(C::WaitCheckNs, started.elapsed().as_nanos() as u64); + } + met + } + + fn holds(&self) -> bool { + let bytes = if self.wide { 8 } else { 4 }; + if self.address == 0 { + return true; + } + static ASK: std::sync::OnceLock = std::sync::OnceLock::new(); + if *ASK.get_or_init(|| std::env::var_os("LEONIDA_WAIT_ASK").is_some_and(|v| v == "1")) + && !crate::texture::committed(self.address as *const u8, bytes) + { + return true; + } + // The low `bytes` bytes; the rest stays zero. + let mut raw = [0u8; 8]; + if !crate::host::read_into(self.address as *const u8, &mut raw[..bytes]) { + return true; + } + self.holds_for(u64::from_le_bytes(raw)) + } + + /// Where the value waited for is: address and bytes. + #[cfg(windows)] + pub(crate) fn place(&self) -> (usize, usize) { + (self.address as usize, if self.wide { 8 } else { 4 }) + } + + /// Whether the wait is met with `value` at its address (its low half + /// for a 32-bit wait). + pub(crate) fn holds_for(&self, value: u64) -> bool { + let (value, reference) = if self.wide { + (value, self.reference) + } else { + (value & 0xFFFF_FFFF, self.reference & 0xFFFF_FFFF) + }; + match self.comparison { + 1 => false, + 2 => value < reference, + 3 => value == reference, + 4 => value <= reference, + 5 => value > reference, + 6 => value != reference, + 7 => value >= reference, + _ => true, + } + } +} + +/// The waits lists recorded since their last reset, by list. +static VALUE_WAITS: std::sync::Mutex> = std::sync::Mutex::new(Vec::new()); + +/// The waits of the submitted `lists` that are not met yet (taken from +/// them): what the console's GPU would stop at. The title orders work +/// between its queues this way (the title: the compute queue's +/// lighting passes wait for a value the graphics queue's depth pass writes +/// at the bottom of the pipe; run at once, they read a cleared depth +/// buffer and nothing was lit). +/// shortcut: a wait holds its whole list (and submission) back, not only +/// the commands after it. +pub(crate) fn unmet_waits(lists: &[This]) -> Vec { + let mut waits = VALUE_WAITS.lock().unwrap_or_else(|e| e.into_inner()); + let mut unmet = Vec::new(); + waits.retain(|&(list, wait)| { + if !lists.iter().any(|&l| l as usize == list) { + return true; + } + if !wait.met() { + unmet.push(wait); + } + false + }); + unmet +} + +/// The waits each of the submitted `lists` recorded (taken from them), +/// met or not, at the list's first place in the submission. +#[cfg(windows)] +pub(crate) fn waits_by_list(lists: &[This]) -> Vec> { + let mut waits = VALUE_WAITS.lock().unwrap_or_else(|e| e.into_inner()); + let mut by = vec![Vec::new(); lists.len()]; + waits.retain(|&(list, wait)| { + match lists.iter().position(|&l| l as usize == list) { + Some(i) => { + by[i].push(wait); + false + } + None => true, + } + }); + by +} + +fn wait_for(this: This, address: u64, comparison: u32, reference: u64, wide: bool) { + let wait = ValueWait { + address, + comparison, + reference, + wide, + }; + static SEEN: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + if SEEN.fetch_add(1, std::sync::atomic::Ordering::Relaxed) < 12 { + tracing::info!( + address = format_args!("{address:#x}"), + comparison, + reference, + wide, + met = wait.met(), + "a list waits for a memory value" + ); + } + #[cfg(all(windows, feature = "diagnostics"))] + if let Some(host) = host_list(this) { + crate::capture::op(std::ptr::from_ref(host) as usize, || { + format!( + "WAIT VALUE at {address:#x} comparison {comparison} reference {reference:#x} wide {wide} met {}", + wait.met() + ) + }); + } + // The list is cut here, and the wait stands before what follows. + #[cfg(windows)] + if crate::queue::cuts() { + cut(this, wait); + return; + } + VALUE_WAITS + .lock() + .unwrap_or_else(|e| e.into_inner()) + .push((this as usize, wait)); +} +extern "system" fn wait_value(this: This, address: u64, comparison: u32, reference: u64) { + wait_for(this, address, comparison, reference, false); +} +extern "system" fn wait_value64(this: This, address: u64, comparison: u32, reference: u64) { + wait_for(this, address, comparison, reference, true); +} + +/// The enhanced barriers `(group count, groups)`: buffer, texture and +/// global barriers with layouts instead of states. Every host use of a +/// title texture (clears, copies) moves its host copy to the state it needs +/// first, so only their ordering matters: one barrier on every shader +/// write (the title's buffer barriers order compute passes). +extern "system" fn barrier_groups(this: This, count: u32, _groups: *const u8) { + // Diagnostics: counted, and left out under `LEONIDA_BARRIER_TEST=groups`. + #[cfg(all(windows, feature = "diagnostics"))] + if count > 0 { + crate::copystat::add(crate::copystat::C::WaitsForGroups, 1); + if crate::copystat::barrier_test() & 1 != 0 { + return; + } + } + #[cfg(windows)] + if count > 0 + && let Some(list) = host_list(this) + { + use windows::Win32::Graphics::Direct3D12::D3D12_RESOURCE_BARRIER; + // SAFETY: the same layout; no resource named. + let barrier = unsafe { std::mem::transmute::(UAV_BARRIER) }; + // SAFETY: an open list. + unsafe { list.list.ResourceBarrier(&[barrier]) }; + } + #[cfg(not(windows))] + let _ = (this, count); +} + +/// The bottom-of-pipe value writes `(address, value, flush, flags)`, 32 and +/// 64 bits: done when the list has run, as the GPU would. Flag 1 writes the +/// GPU timestamp instead (64-bit form), flag 2 the system timestamp. +extern "system" fn write32(this: This, address: u64, value: u32, _flush: u32, _flags: u32) { + defer_write(this, address, Written::Value(u64::from(value)), 4); + value_written(this, address, u64::from(value)); +} +extern "system" fn write64(this: This, address: u64, value: u64, _flush: u32, flags: u32) { + const GPU_TIMESTAMP: u32 = 1; + const SYSTEM_TIMESTAMP: u32 = 2; + let what = match flags { + GPU_TIMESTAMP => Written::GpuTimestamp, + SYSTEM_TIMESTAMP => Written::SystemTimestamp, + _ => Written::Value(value), + }; + defer_write(this, address, what, 8); + if let Written::Value(value) = what { + value_written(this, address, value); + } +} + +/// The title wrote a value at the bottom of the pipe (not a timestamp, not +/// a query result): listed (diagnostics), and with `LEONIDA_CUT_WRITES=1` +/// the host list is cut right behind it, so that the value is stored when +/// the card has run the list up to there, as on the console, and not when +/// the whole list has run. Lists of other queues wait for these values +/// (the title: the compute list that builds the depth pyramid +/// waits for one, and the meshlet culling of the same frame reads that +/// pyramid). Off by default: every such write then ends a host list, and +/// each part is a submission of its own. +fn value_written(this: This, address: u64, value: u64) { + #[cfg(windows)] + { + if address == 0 || this.is_null() { + return; + } + #[cfg(not(feature = "diagnostics"))] + let _ = value; + #[cfg(feature = "diagnostics")] + if let Some(host) = host_list(this) { + crate::capture::op(std::ptr::from_ref(host) as usize, || { + format!("WRITE VALUE at {address:#x} value {value:#x}") + }); + } + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + if !*ON.get_or_init(|| std::env::var_os("LEONIDA_CUT_WRITES").is_some_and(|v| v == "1")) + || !crate::queue::cuts() + { + return; + } + // SAFETY: the title passes one of our lists; a list is recorded by + // one thread at a time and is not submitted while it records. + let list = unsafe { &mut *this.cast_mut().cast::() }; + let Some(current) = list.host.as_ref() else { + return; + }; + let Some(fresh) = fresh_list() else { + return; + }; + current.close(); + if let Some(done) = list.host.replace(fresh) { + // The part so far keeps its waits; nothing stands before the + // next one but this part itself. + let waits = std::mem::take(&mut list.gate); + list.earlier.push(Part { waits, host: done }); + } + if let Some(host) = list.host.as_ref() { + list.state + .lock() + .unwrap_or_else(|e| e.into_inner()) + .replay(host); + } + } + #[cfg(not(windows))] + let _ = (this, address, value); +} + +fn defer_write(this: This, address: u64, what: Written, bytes: usize) { + if address == 0 { + return; + } + #[cfg(windows)] + if let Some(list) = host_list(this) { + list.defer_write(address as *mut u8, what, bytes); + return; + } + let _ = this; + // Without a host GPU nothing runs later: write now. + what.write(address as *mut u8, bytes); +} + +/// The list methods by their slot in older titles' lists (the 2020-era +/// layout): IUnknown 3, object 4, device child 1, list 1, graphics list 96 +/// (59 as on PC, then console ones), then versions 1-6 (6 + 1 + 1 + 11 + 3 +/// + 13): 140 slots. +const METHODS: [(usize, *const ()); 52] = [ + (0, list_query as *const ()), + (2, list_release as *const ()), + (7, object::parent_device as *const ()), // 0x38 + (8, list_type as *const ()), // 0x40 + (9, close as *const ()), // 0x48 + (10, reset as *const ()), // 0x50 + (12, state::draw as *const ()), // 0x60 instanced + (13, state::draw_indexed as *const ()), // 0x68 indexed + (14, state::dispatch as *const ()), // 0x70 + (15, copy_buffer_region as *const ()), // 0x78 + (16, copy_texture_region as *const ()), // 0x80 + (17, copy_resource as *const ()), // 0x88 + (19, resolve as *const ()), // 0x98 + (20, state::topology as *const ()), // 0xa0 + (21, state::viewports as *const ()), // 0xa8 + (22, state::scissors as *const ()), // 0xb0 + (23, state::blend_factor as *const ()), // 0xb8 + (24, state::stencil_ref as *const ()), // 0xc0 + (25, set_pipeline as *const ()), // 0xc8 + (26, barrier as *const ()), // 0xd0 + (32, state::heaps as *const ()), // 0x100 + (33, ignored_state as *const ()), // 0x108 compute root signature + (34, ignored_state as *const ()), // 0x110 graphics root signature + (35, state::compute_table as *const ()), // 0x118 + (36, state::graphics_table as *const ()), // 0x120 + (37, state::compute_constant as *const ()), // 0x128 + (38, state::graphics_constant as *const ()), // 0x130 + (39, state::compute_constants as *const ()), // 0x138 + (40, state::graphics_constants as *const ()), // 0x140 + (41, state::compute_view as *const ()), // 0x148 CBV + (42, state::graphics_view as *const ()), // 0x150 CBV + (43, state::compute_view as *const ()), // 0x158 SRV + (44, state::graphics_view as *const ()), // 0x160 SRV + (45, state::compute_view as *const ()), // 0x168 UAV + (46, state::graphics_view as *const ()), // 0x170 UAV + (47, state::index_buffer as *const ()), // 0x178 + (48, state::vertex_buffers as *const ()), // 0x180 + (50, state::targets as *const ()), // 0x190 + (51, clear_dsv as *const ()), // 0x198 + (52, clear_rtv as *const ()), // 0x1a0 + (59, execute_indirect as *const ()), // 0x1d8 indirect + (60, copy_memory as *const ()), // 0x1e0 + (68, state::depth_bounds as *const ()), // 0x220 depth bounds + (69, write32 as *const ()), // 0x228 + (70, write64 as *const ()), // 0x230 + (71, wait_value as *const ()), // 0x238, 32 bits + (72, wait_value64 as *const ()), // 0x240, 64 bits + (73, ignored_state as *const ()), // 0x248 pixel shader depth order + (83, copy_texture_region_x as *const ()), // 0x298 + (84, copy_resource_x as *const ()), // 0x2a0 + (124, ignored_state as *const ()), // 0x3e0 shading rate + (127, state::dispatch_mesh as *const ()), // 0x3f8 mesh dispatch +]; +/// The rest of [`METHODS`], kept apart only to stay readable. +const MORE_METHODS: [(usize, *const ()); 9] = [ + (28, query_mark as *const ()), // 0xe0 BeginQuery + (29, query_mark as *const ()), // 0xe8 EndQuery + (30, resolve_queries as *const ()), // 0xf0 + (78, dispatch_x as *const ()), // 0x270 + (98, state::dispatch_mesh_x as *const ()), // 0x310 + (99, driver_hint as *const ()), // 0x318 + // Pipeline syncs at the top and bottom of the pipe, 0x408 and 0x410. + (129, sync as *const ()), + (130, sync as *const ()), + (137, reset_x as *const ()), // 0x448 +]; + +/// Newer titles' lists have two more methods in the console part of the +/// base list, after the clears (0x198/0x1a0 as before) and before +/// ExecuteIndirect, which moved from 0x1d8 to 0x1e8: every slot from 0x1d8 +/// on is two later (taken here as starting exactly at 0x1d8). Inferred from +/// The title's call shapes: ExecuteIndirect 0x1e8, bottom-of-pipe +/// writes 0x238/0x240, waits 0x248/0x250, depth bounds 0x230, shading rate +/// 0x3f0/0x400, syncs 0x418/0x420, ResetX 0x458 (asserts on failure). +const fn newer_slot(slot: usize) -> usize { + if slot >= 59 { slot + 2 } else { slot } +} + +/// Methods only newer titles' lists have. 0x490: the enhanced barrier +/// `(group count, groups)`, with 16-byte groups `(type, count, barriers)` +/// and 40-byte buffer barriers (title+0x95e0 builds them). 0x470 `(u64)`, +/// called from the title's state flush with its result unused. +/// shortcut: 0x470's purpose is unknown; ignored until a title shows it +/// matters. +const NEWER_METHODS: [(usize, *const ()); 3] = [ + (142, ignored_state as *const ()), + (146, barrier_groups as *const ()), + (148, allocate_upload as *const ()), +]; + +const fn list_table(newer: bool) -> [*const (); 160] { + let mut f = object::d3d12_object(object::missing_table::()); + let mut i = 0; + while i < METHODS.len() + MORE_METHODS.len() { + let (slot, method) = if i < METHODS.len() { + METHODS[i] + } else { + MORE_METHODS[i - METHODS.len()] + }; + f[if newer { newer_slot(slot) } else { slot }] = method; + i += 1; + } + let mut i = 0; + while newer && i < NEWER_METHODS.len() { + f[NEWER_METHODS[i].0] = NEWER_METHODS[i].1; + i += 1; + } + f +} + +/// Every slot up to the limit exists and logs, for the methods newer +/// titles add. +static LIST_FUNCTIONS: Table<160> = Table(list_table(false)); +static NEWER_LIST_FUNCTIONS: Table<160> = Table(list_table(true)); + +#[cfg(test)] +mod tests { + use super::*; + use crate::object::slot; + + #[test] + fn every_inline_command_falls_back_to_the_table() { + let null = std::ptr::null(); + let mut allocator = null; + assert_eq!( + create_allocator(null, 0, &ALLOCATOR_IIDS[0], &mut allocator), + S_OK + ); + let mut list = null; + let hr = create_list(null, 0, 0, allocator, null, &LIST_IIDS[1], &mut list); + assert_eq!(hr, S_OK); + // What the title's inline draw checks: put < draw limit. + // SAFETY: the list is 0x560 bytes. + let (put, draw_limit, api_limit) = unsafe { + let at = |o: usize| list.cast::().add(o).cast::().read(); + (at(0x18), at(0x28), at(0x30)) + }; + assert!(put >= draw_limit && put >= api_limit); + // The console's ID3D12GraphicsCommandList6, as the title asks. + let mut same = null; + assert_eq!(list_query(list, &LIST_IIDS[7], &mut same), S_OK); + assert_eq!(same, list); + assert_eq!(slot:: u32>(list, 0x10)(list), 1); + assert_eq!(slot:: u32>(list, 0x40)(list), 0); + assert_eq!( + slot:: HRESULT>(list, 0x48)(list), + S_OK + ); + // List-owned upload memory: aligned, writable, gone at reset. + let p = allocate_upload(list, 40, 0x100); + assert!(!p.is_null() && (p as usize).is_multiple_of(0x100)); + // SAFETY: 40 bytes were handed out. + unsafe { p.write_bytes(0xab, 40) }; + assert!(allocate_upload(list, 8, 0x30).is_null(), "not a power of two"); + assert_eq!(reset(list, allocator, null), S_OK); + // SAFETY: the list is ours. + assert!(unsafe { &(*list.cast::()).uploads }.lock().unwrap().is_empty()); + let release = |o: This| slot:: u32>(o, 0x10)(o); + assert_eq!(release(list), 0); + assert_eq!(release(allocator), 0); + } +} diff --git a/crates/leonida-gpu/src/memory.rs b/crates/leonida-gpu/src/memory.rs new file mode 100644 index 000000000..4a382f18a --- /dev/null +++ b/crates/leonida-gpu/src/memory.rs @@ -0,0 +1,319 @@ +//! Title memory by address, for translated shaders that read and write +//! through raw 40-bit addresses (`leonida_shader::emit::SLOT_MEMORY`: the +//! console's ray-tracing structure builder and the programs that walk its +//! structures; the structures themselves lie in plain title memory, in no +//! buffer object). +//! +//! The copies are the ones every other access uses ([`crate::shadow`]: a +//! title buffer's copy, or the 4 MiB window of memory outside buffers), so +//! a root view and a raw address reach the same host bytes. This module +//! keeps what a shader needs to find them: +//! +//! - the **directory**: per 64 KiB page of title address space the number +//! of the copy that holds the page (0: none) and the page's byte offset +//! in it; one buffer for all lists, entries only ever go from empty to +//! filled; +//! - per view heap a run of slots with a raw unordered access view of each +//! numbered copy (slot 0 of the run: a null view, for pages without a +//! copy); +//! - the **faults**: the page numbers shaders found empty, read back here +//! once a frame, so the copies exist from the next frame on. A pointer a +//! shader takes out of memory cannot be known before it runs; the +//! addresses a dispatch is given as root views are made ready before it. +//! +//! **A page that is not there when a shader touches it is a lost access**: +//! the read gives 0, the store is dropped, and the fault note only helps +//! the next frame. For the structure builder that is the same as a dropped +//! stage, so before a dispatch the host makes ready everything it can see +//! the dispatch name: the whole copy around each root view, around each +//! pair of root constants that is a title address and around each root +//! constant that is one in 256-byte units (the builder passes structures +//! all three ways), and the 4 MiB after each (a structure may cross a +//! window's end). +//! shortcut: what a stage reaches only through pointers it reads out of +//! memory (InitHeaders' table of structure addresses, LoadInstances' +//! instance records) is not made ready unless something else named it; +//! the fault count in the log says whether that happens. The whole answer +//! is the extent of the title's allocation around an address, which the +//! memory module of the layer knows and this one does not ask yet. +//! +//! shortcut: a copy that is numbered is kept for the rest of the run, and +//! there are at most [`COPIES`] of them (4 MiB windows mostly: 4 GiB at +//! most). Every dispatch of such a shader brings all numbered copies up to +//! date and, if it can store, declares all of them written (the bytes are +//! compared on the CPU afterwards, as for any unordered access view): a +//! dirty-page mask written by the shader would bound both. + +use std::collections::HashMap; +use std::sync::{Arc, Mutex}; + +use leonida_shader::emit::{MEMORY_FAULTS, MEMORY_PAGES}; +use windows::Win32::Graphics::Direct3D12::*; + +use crate::descriptor::host::HostHeap; +use crate::host::{HostList, host}; +use crate::shadow::Shadow; + +/// Copies that can be numbered (the run of heap slots is one longer). A +/// listed frame of the opening cutscene names about 50 windows. +const COPIES: u32 = 1023; +/// A window of memory outside buffers (`shadow.rs`). +const CELL: u64 = 4 << 20; +/// A directory page. +const PAGE: u64 = 1 << 16; + +struct Memory { + /// Buffer, its mapping, its GPU address. + directory: (ID3D12Resource, *mut u32, u64), + faults: (ID3D12Resource, *mut u32, u64), + /// Copy `n` is `copies[n - 1]`. + copies: Vec>, + /// Per host view heap (by address): the first slot of its run, and how + /// many copies have their view there. + heaps: HashMap, + /// The frame the faults were last read in. + frame: u64, + /// Pages asked for this frame that are not the title's memory. + refused: std::collections::HashSet, +} + +// SAFETY: the mappings are of buffers the struct owns; all access is under +// the mutex. +unsafe impl Send for Memory {} + +static MEMORY: Mutex> = Mutex::new(None); + +/// What a draw binds. +pub(crate) struct Ready { + pub(crate) directory: u64, + pub(crate) faults: u64, + /// The view heap slot of the null view; copy `n`'s view is `n` further. + pub(crate) base: u32, +} + +impl Memory { + fn new() -> Option { + let host = host()?; + let make = |dwords: u64, what: &str| { + let (buffer, data) = host.shared_buffer(dwords * 4)?; + crate::host::name(&buffer, || format!("title memory by address: {what}")); + // SAFETY: a fresh mapping of at least that many bytes. + unsafe { std::ptr::write_bytes(data, 0, (dwords * 4) as usize) }; + // SAFETY: a live buffer. + let gpu = unsafe { buffer.GetGPUVirtualAddress() }; + Some((buffer, data.cast::(), gpu)) + }; + tracing::info!("title memory by address: a shader reads or writes through raw addresses"); + Some(Memory { + directory: make(u64::from(MEMORY_PAGES) * 2, "directory")?, + faults: make(u64::from(MEMORY_FAULTS), "faults")?, + copies: Vec::new(), + heaps: HashMap::new(), + frame: u64::MAX, + refused: Default::default(), + }) + } + + /// Gives the page of `address` its copy, if it has none and the memory + /// is the title's. + fn map(&mut self, address: u64) { + let page = address / PAGE; + // The last entry stays empty: addresses past the directory read it. + if page >= u64::from(MEMORY_PAGES) - 1 { + return; + } + // SAFETY: inside the directory's mapping. + let entry = unsafe { self.directory.1.add(page as usize * 2) }; + // SAFETY: as above. + if unsafe { entry.read() } != 0 { + return; + } + let start = page * PAGE; + // A shader's pointer, or a constant taken for an address, may be + // anything: only memory the title has. + if self.refused.contains(&page) { + return; + } + if !crate::texture::committed(start as *const u8, PAGE as usize) { + self.refused.insert(page); + return; + } + // The copy a root view at that address would get; a buffer that + // ends inside the page is passed over for what holds all of it. + let whole = |s: &Arc| s.offset_in(start).is_some_and(|_| s.left(start) >= PAGE); + let Some(shadow) = crate::shadow::find(start, 1) + .filter(whole) + .or_else(|| crate::shadow::find(start, PAGE).filter(whole)) + else { + return; + }; + // SAFETY: a live buffer. + let flags = unsafe { shadow.buffer.GetDesc() }.Flags; + if flags.0 & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS.0 == 0 { + return; + } + let n = match self.copies.iter().position(|c| Arc::ptr_eq(c, &shadow)) { + Some(n) => n, + None if self.copies.len() < COPIES as usize => { + self.copies.push(shadow.clone()); + let n = self.copies.len() - 1; + // Every page the copy holds whole, not only the one asked + // for: a structure is more than 64 KiB. + // shortcut: a page of a title buffer inside this one that + // has a copy of its own is given this copy too. + let (first, len) = shadow.span(); + let mut at = first.next_multiple_of(PAGE); + while at + PAGE <= first + len && at / PAGE < u64::from(MEMORY_PAGES) - 1 { + // SAFETY: inside the directory's mapping. + let other = unsafe { self.directory.1.add((at / PAGE) as usize * 2) }; + // SAFETY: as above; the offset first, as below. + unsafe { + if other.read() == 0 { + other.add(1).write_volatile((at - first) as u32); + other.write_volatile(n as u32 + 1); + } + } + at += PAGE; + } + n + } + None => { + static ONCE: std::sync::Once = std::sync::Once::new(); + ONCE.call_once(|| { + tracing::warn!(COPIES, "title memory by address: no number left for another copy; its pages read zeros") + }); + return; + } + }; + let offset = shadow.offset_in(start).unwrap_or(0); + // The offset first: a shader that sees the number sees it too. + // SAFETY: inside the directory's mapping. + unsafe { + entry.add(1).write_volatile(offset as u32); + entry.write_volatile(n as u32 + 1); + } + } + + /// The pages shaders found empty since the last frame. + fn take_faults(&mut self) { + let mut pages = Vec::new(); + for i in 1..MEMORY_FAULTS as usize { + // SAFETY: inside the faults' mapping; the GPU may be writing, + // a number missed now is written again next frame. + let at = unsafe { self.faults.1.add(i) }; + // SAFETY: as above. + let page = unsafe { at.read_volatile() }; + if page != 0 { + pages.push(page); + // SAFETY: as above. + unsafe { at.write_volatile(0) }; + } + } + if !pages.is_empty() { + // Each is an access that read 0 or was dropped. + static SAID: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); + if SAID.fetch_add(1, std::sync::atomic::Ordering::Relaxed) < 50 { + tracing::warn!( + pages = pages.len(), + first = format_args!("{:#x}", u64::from(pages[0]) * PAGE), + "title memory by address: shaders touched pages that had no copy (those accesses read 0 or were dropped); the copies are made now" + ); + } + } + for page in pages { + self.map(u64::from(page) * PAGE); + } + } + + /// What a dispatch names: the copy around `address` and the 4 MiB + /// after it. + fn name(&mut self, address: u64) { + self.map(address); + self.map((address & !(CELL - 1)) + CELL); + } +} + +/// Before a draw whose shader reads title memory by address: what its +/// root arguments name gets its copies (`addresses`: its root views; +/// `constants`: its root constants, see the module), every numbered copy +/// has its view in `heap`'s run and is brought up to date when `list` is +/// submitted (and, with `writes`, copied back after). None if the host +/// cannot hold it; the draw is then dropped. +pub(crate) fn ready( + list: &HostList, + heap: &HostHeap, + addresses: &[u64], + constants: &[u32], + writes: bool, +) -> Option { + let mut guard = MEMORY.lock().unwrap_or_else(|e| e.into_inner()); + if guard.is_none() { + *guard = Memory::new(); + } + let m = guard.as_mut()?; + let frame = crate::frame::current(); + if m.frame != frame { + m.frame = frame; + m.refused.clear(); + m.take_faults(); + } + let numbered = m.copies.len(); + for &address in addresses { + m.name(address); + } + // A title address in two constants (low dword, then bits 32 to 39), or + // in one in 256-byte units. A constant that only looks like one names + // memory nothing reads; one that is not the title's memory is refused. + for (i, &c) in constants.iter().enumerate() { + if let Some(&high) = constants.get(i + 1) + && (1..=0xFF).contains(&high) + && c >= 0x1_0000 + { + m.name(u64::from(c) | u64::from(high) << 32); + } + if c >= 0x0100_0000 { + m.name(u64::from(c) << 8); + } + } + let key = std::ptr::from_ref(heap) as usize; + let (base, made) = match m.heaps.get(&key) { + Some(&run) => run, + None => { + // Held for the heap's life: not given back with a list's slots. + let base = heap.dynamic(COPIES + 1)?; + heap.null_raw_uav_at(base); + (base, 0) + } + }; + for (n, shadow) in m.copies.iter().enumerate().skip(made as usize) { + let (_, len) = shadow.span(); + heap.raw_uav_at(base + 1 + n as u32, &shadow.buffer, 0, len); + } + m.heaps.insert(key, (base, m.copies.len() as u32)); + // Once per list, and for copies numbered since: the builder alone + // dispatches hundreds of times a frame. + // shortcut: a copy another list numbers meanwhile is brought up to date + // by that list's submission, which may run after this one's. + const READ: usize = usize::MAX - 0x6d; + const WRITE: usize = usize::MAX - 0x6e; + let first_read = list.first_use(READ); + let first_write = writes && list.first_use(WRITE); + for (n, shadow) in m.copies.iter().enumerate() { + let (start, len) = shadow.span(); + if first_read || n >= numbered { + shadow.refresh(list, start, len); + } + if writes && (first_write || n >= numbered) { + shadow.gpu_writes(list, start, len); + } + } + if first_read { + list.keep(&m.directory.0); + list.keep(&m.faults.0); + } + Some(Ready { + directory: m.directory.2, + faults: m.faults.2, + base, + }) +} diff --git a/crates/leonida-gpu/src/object.rs b/crates/leonida-gpu/src/object.rs new file mode 100644 index 000000000..156c92ded --- /dev/null +++ b/crates/leonida-gpu/src/object.rs @@ -0,0 +1,384 @@ +//! What every console graphics object starts with: a function table +//! pointer, bookkeeping bits and a reference count. Tables begin with +//! IUnknown's three slots. Our objects are static and never destroyed. +#![allow(clippy::not_unsafe_ptr_arg_deref)] + +use std::collections::BTreeMap; +use std::sync::Mutex; +use std::sync::atomic::{AtomicBool, AtomicU32, Ordering}; + +pub type HRESULT = i32; +pub const S_OK: HRESULT = 0; +pub(crate) const S_FALSE: HRESULT = 1; +pub(crate) const E_NOTIMPL: HRESULT = 0x8000_4001_u32 as i32; +pub(crate) const E_NOINTERFACE: HRESULT = 0x8000_4002_u32 as i32; +pub(crate) const E_POINTER: HRESULT = 0x8000_4003_u32 as i32; +pub(crate) const E_INVALIDARG: HRESULT = 0x8007_0057_u32 as i32; +pub(crate) const E_OUTOFMEMORY: HRESULT = 0x8007_000E_u32 as i32; +/// What D3D and DXGI return for a missing item (adapter, output, private +/// data). +pub(crate) const NOT_FOUND: HRESULT = 0x887A_0002_u32 as i32; +pub(crate) const MORE_DATA: HRESULT = 0x887A_0003_u32 as i32; + +pub type Iid = [u8; 16]; + +/// An interface id from its text form's fields, in memory order. +pub const fn guid(a: u32, b: u16, c: u16, d: [u8; 8]) -> Iid { + let (a, b, c) = (a.to_le_bytes(), b.to_le_bytes(), c.to_le_bytes()); + [ + a[0], a[1], a[2], a[3], b[0], b[1], c[0], c[1], d[0], d[1], d[2], d[3], d[4], d[5], d[6], + d[7], + ] +} + +pub fn guid_text(g: &Iid) -> String { + let a = u32::from_le_bytes([g[0], g[1], g[2], g[3]]); + let b = u16::from_le_bytes([g[4], g[5]]); + let c = u16::from_le_bytes([g[6], g[7]]); + let d: String = g[8..].iter().map(|x| format!("{x:02x}")).collect(); + format!("{a:08x}-{b:04x}-{c:04x}-{}-{}", &d[..4], &d[4..]) +} + +#[repr(C)] +pub struct Object { + functions: *const *const (), + /// Device index (bits 0-2) and bookkeeping bits; all zero. + bits: u32, + refs: AtomicU32, +} +// SAFETY: the table is static and immutable; the count is atomic. +unsafe impl Sync for Object {} + +impl Object { + pub(crate) const fn new(table: &'static Table) -> Self { + Object { + functions: table.0.as_ptr(), + bits: 0, + refs: AtomicU32::new(0), + } + } +} + +pub(crate) type This = *const Object; + +#[repr(transparent)] +pub(crate) struct Table(pub [*const (); N]); +// SAFETY: function addresses only. +unsafe impl Sync for Table {} + +pub(crate) extern "system" fn add_ref(this: This) -> u32 { + // SAFETY: `this` is one of our objects. + unsafe { &*this }.refs.fetch_add(1, Ordering::Relaxed) + 1 +} + +pub(crate) extern "system" fn release(this: This) -> u32 { + // SAFETY: `this` is one of our objects. + let refs = &unsafe { &*this }.refs; + let _ = refs.fetch_update(Ordering::Relaxed, Ordering::Relaxed, |n| n.checked_sub(1)); + refs.load(Ordering::Relaxed) +} + +/// Answers an interface query (or any call handing out an object): a new +/// reference to `found`, or null and `E_NOINTERFACE`. +pub(crate) fn answer(kind: usize, iid: *const Iid, found: Option, out: *mut This) -> HRESULT { + if out.is_null() { + return E_POINTER; + } + let hr = match found { + Some(object) => { + add_ref(object); + // SAFETY: checked non-null; the title passes room for a pointer. + unsafe { out.write(object) }; + return S_OK; + } + None => E_NOINTERFACE, + }; + // SAFETY: the title passes an interface id (null is tolerated). + let iid = unsafe { iid.as_ref() }.map(guid_text).unwrap_or_default(); + tracing::warn!(object = KINDS[kind], %iid, "unknown interface"); + // SAFETY: checked non-null. + unsafe { out.write(std::ptr::null()) }; + hr +} + +/// Whether `iid` is one of `known`. +pub(crate) fn is(iid: *const Iid, known: &[Iid]) -> bool { + // SAFETY: the title passes an interface id (null is tolerated). + unsafe { iid.as_ref() }.is_some_and(|i| known.contains(i)) +} + +/// Hands a new object to the title as one of `known`, or drops it. `T` +/// starts with its `Object`; its table's release slot is +/// [`release_boxed::`]. +pub(crate) fn hand_out( + kind: usize, + object: Box, + iid: *const Iid, + known: &[Iid], + out: *mut This, +) -> HRESULT { + if !is(iid, known) { + return answer(kind, iid, None, out); + } + if out.is_null() { + // Asked only whether creation would succeed. + return S_FALSE; + } + answer(kind, iid, Some(Box::into_raw(object).cast()), out) +} + +/// Release for objects made by [`hand_out`]: the last reference frees it. +pub(crate) fn release_boxed(this: This) -> u32 { + // SAFETY: `this` is the header of a boxed `T`. + let refs = &unsafe { &*this }.refs; + match refs.fetch_update(Ordering::AcqRel, Ordering::Acquire, |n| n.checked_sub(1)) { + Ok(1) => { + private_data().retain(|&(object, _), _| object != this as usize); + // SAFETY: that was the last reference to a `Box`. + drop(unsafe { Box::from_raw(this.cast_mut().cast::()) }); + 0 + } + Ok(n) => n - 1, + Err(_) => 0, + } +} + +/// Private data of every object, by object address and id. +static PRIVATE: Mutex>> = Mutex::new(BTreeMap::new()); + +fn private_data() -> std::sync::MutexGuard<'static, BTreeMap<(usize, Iid), Vec>> { + PRIVATE.lock().unwrap_or_else(|e| e.into_inner()) +} + +extern "system" fn get_private_data( + this: This, + id: *const Iid, + size: *mut u32, + data: *mut u8, +) -> HRESULT { + // SAFETY: the title passes an id and its buffer size (null is tolerated). + let (Some(id), Some(size)) = (unsafe { (id.as_ref(), size.as_mut()) }) else { + return E_INVALIDARG; + }; + let map = private_data(); + let Some(value) = map.get(&(this as usize, *id)) else { + *size = 0; + return NOT_FOUND; + }; + let len = value.len() as u32; + let room = std::mem::replace(size, len); + if data.is_null() { + return S_OK; + } + if room < len { + return MORE_DATA; + } + // SAFETY: the buffer holds `room` >= `len` bytes. + unsafe { data.copy_from_nonoverlapping(value.as_ptr(), value.len()) }; + S_OK +} + +/// Null data removes the entry. +extern "system" fn set_private_data( + this: This, + id: *const Iid, + size: u32, + data: *const u8, +) -> HRESULT { + // SAFETY: the title passes an id (null is tolerated). + let Some(&id) = (unsafe { id.as_ref() }) else { + return E_INVALIDARG; + }; + let mut map = private_data(); + if data.is_null() { + map.remove(&(this as usize, id)); + } else { + // SAFETY: the title passes `size` bytes. + let value = unsafe { std::slice::from_raw_parts(data, size as usize) }; + map.insert((this as usize, id), value.to_vec()); + } + S_OK +} + +/// Fills a D3D12 table's object methods: private data and name (setting +/// an interface as private data stays unwritten). +pub(crate) const fn d3d12_object(mut f: [*const (); N]) -> [*const (); N] { + f[3] = get_private_data as *const (); // 0x18 + f[4] = set_private_data as *const (); // 0x20 + f[6] = set_name as *const (); // 0x30 + f +} + +/// The object methods' name setter: names only reach our log. +pub(crate) extern "system" fn set_name(this: This, name: *const u16) -> HRESULT { + let name = if name.is_null() { + String::new() + } else { + // SAFETY: a non-null name is NUL-terminated UTF-16. + let len = (0..).take_while(|&i| unsafe { *name.add(i) } != 0).count(); + // SAFETY: `len` units were just read. + String::from_utf16_lossy(unsafe { std::slice::from_raw_parts(name, len) }) + }; + tracing::debug!(object = ?this, %name, "named"); + S_OK +} + +/// The device-child method: the device that made the object, as any of +/// the interfaces the device itself answers to. +pub(crate) extern "system" fn parent_device(_: This, iid: *const Iid, out: *mut This) -> HRESULT { + let device = crate::device::device(); + answer( + DEVICE, + iid, + crate::device::is_device(iid).then_some(device), + out, + ) +} + +pub(crate) const DEVICE: usize = 0; +pub(crate) const DXGI_DEVICE: usize = 1; +pub(crate) const ADAPTER: usize = 2; +pub(crate) const FACTORY: usize = 3; +pub(crate) const OUTPUT: usize = 4; +pub(crate) const HEAP: usize = 5; +pub(crate) const RESOURCE: usize = 6; +pub(crate) const FENCE: usize = 7; +pub(crate) const QUEUE: usize = 8; +pub(crate) const ALLOCATOR: usize = 9; +pub(crate) const LIST: usize = 10; +pub(crate) const DESCRIPTOR_HEAP: usize = 11; +pub(crate) const ROOT_SIGNATURE: usize = 12; +pub(crate) const QUERY_HEAP: usize = 13; +pub(crate) const COMMAND_SIGNATURE: usize = 14; +pub(crate) const PIPELINE: usize = 15; +const KINDS: [&str; 16] = [ + "device", + "DXGI device", + "adapter", + "factory", + "output", + "heap", + "resource", + "fence", + "command queue", + "command allocator", + "command list", + "descriptor heap", + "root signature", + "query heap", + "command signature", + "pipeline state", +]; + +const MAX_SLOTS: usize = 160; + +/// Which unwritten slots have been reported; each is logged once. +static REPORTED: [[AtomicBool; MAX_SLOTS]; KINDS.len()] = + [const { [const { AtomicBool::new(false) }; MAX_SLOTS] }; KINDS.len()]; + +/// Logged once per slot, with the caller's offset in its module (the title +/// image for title calls). Wrong for a slot that returns a value instead of +/// an `HRESULT`. +extern "system" fn missing() -> HRESULT { + if !REPORTED[KIND][SLOT].swap(true, Ordering::Relaxed) { + tracing::warn!( + object = KINDS[KIND], + slot = format_args!("{:#x}", SLOT * 8), + caller = caller(), + "method not implemented" + ); + } + E_NOTIMPL +} + +/// The return address of whoever called our caller, as `+offset` into its +/// module. +#[inline(never)] +fn caller() -> String { + #[cfg(windows)] + { + use windows_sys::Win32::System::Diagnostics::Debug::RtlCaptureStackBackTrace; + use windows_sys::Win32::System::LibraryLoader::{ + GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS, GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT, + GetModuleHandleExW, + }; + let mut frame = std::ptr::null_mut(); + // SAFETY: room for one frame; skips this function and its caller. + if unsafe { RtlCaptureStackBackTrace(2, 1, &mut frame, std::ptr::null_mut()) } == 1 { + let mut module = std::ptr::null_mut(); + // SAFETY: looks up the module holding the address, no reference. + let found = unsafe { + GetModuleHandleExW( + GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS + | GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT, + frame as *const u16, + &mut module, + ) + }; + if found != 0 { + return format!("+{:#x}", frame as usize - module as usize); + } + return format!("{frame:?}"); + } + } + String::new() +} + +/// Accepts and ignores (debug-only settings). +pub(crate) extern "system" fn ignore() -> HRESULT { + S_OK +} + +macro_rules! missing { + ($kind:ident; $($slot:literal)*) => { [$(missing::<$kind, $slot> as *const ()),*] }; +} + +/// A table of `N` slots that log and fail; callers fill in what they have. +/// Tables are made longer than the interfaces we know, so that a method a +/// newer title adds logs instead of jumping into whatever follows the table. +pub(crate) const fn missing_table() -> [*const (); N] { + let all = missing!(KIND; + 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 + 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 + 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 + 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 + 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 + 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 + 158 159 + ); + assert!(N <= all.len()); + let mut table = [std::ptr::null(); N]; + let mut i = 0; + while i < N { + table[i] = all[i]; + i += 1; + } + table[1] = add_ref as *const (); + table[2] = release as *const (); + table +} + +#[cfg(test)] +pub(crate) fn slot(object: This, offset: usize) -> F { + // SAFETY: `object` is ours and its table has the slot. + let f = unsafe { *(*object).functions.add(offset / 8) }; + // SAFETY: the caller names the slot's signature. + unsafe { std::mem::transmute_copy(&f) } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn guids_round_trip_through_text() { + let g = guid( + 0x189819f1, + 0x1db6, + 0x4b57, + [0xbe, 0x54, 0x18, 0x21, 0x33, 0x9b, 0x85, 0xf7], + ); + assert_eq!(g[..4], [0xf1, 0x19, 0x98, 0x18]); + assert_eq!(guid_text(&g), "189819f1-1db6-4b57-be54-1821339b85f7"); + } +} diff --git a/crates/leonida-gpu/src/pipeline.rs b/crates/leonida-gpu/src/pipeline.rs new file mode 100644 index 000000000..6096f0a4e --- /dev/null +++ b/crates/leonida-gpu/src/pipeline.rs @@ -0,0 +1,938 @@ +//! Pipeline states. Both descriptions start as on PC: the root signature, +//! then the shader stages (five for graphics, one for compute); streams +//! carry the rest of the graphics state as subobjects of the standard +//! types. +//! +//! Host pipelines are made on a pipeline's first draw, not at creation: +//! The title creates some 60,000 pipelines in its first 20 +//! seconds and draws with a few dozen (decision 0007, step 3). Shader +//! containers are shared by content hash and translated once, on first +//! use (decision 0003). +//! +//! shortcut: only vertex plus pixel pipelines from streams and compute +//! pipelines get host pipelines; mesh, tessellation and geometry stages, +//! and the plain graphics description, keep their containers only. The 32-byte +//! packet after the header stays zero: titles only copy it inline, which +//! our null command-list limits keep from running. +#![allow(clippy::not_unsafe_ptr_arg_deref)] + +use std::collections::HashMap; +use std::mem::offset_of; +use std::sync::{Arc, Mutex, OnceLock}; + +use crate::object::{self, E_INVALIDARG, HRESULT, Iid, Object, PIPELINE, Table, This, guid}; +use crate::resource::PAGEABLE_IIDS; + +const PIPELINE_IIDS: [Iid; 4] = [ + guid( + 0x765a30f3, + 0xf624, + 0x4c6f, + [0xa8, 0x28, 0xac, 0xe9, 0x48, 0x62, 0x24, 0x45], + ), + PAGEABLE_IIDS[0], + PAGEABLE_IIDS[1], + PAGEABLE_IIDS[2], +]; + +#[repr(C)] +pub(crate) struct Bytecode { + code: *const u8, + size: usize, +} + +#[repr(C)] +pub(crate) struct GraphicsHead { + root: This, + /// Vertex, pixel, domain, hull, geometry. + stages: [Bytecode; 5], +} + +#[repr(C)] +pub(crate) struct ComputeHead { + root: This, + stage: Bytecode, +} + +/// A shader container a title passed, shared by every pipeline with the +/// same bytes. +pub(crate) struct Shader { + pub(crate) stage: &'static str, + /// The first 8 bytes of its BLAKE3, as logged. + pub(crate) hash: String, + container: Vec, + #[cfg(windows)] + translated: OnceLock>, + /// Whether its code walks the ray-tracing structures, once looked at + /// ([`Shader::walks`]). + #[cfg(windows)] + walks: OnceLock, +} + +impl std::fmt::Debug for Shader { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!(f, "{} {}", self.stage, self.hash) + } +} + +/// Every container seen, by full content hash. +static SHADERS: Mutex>>> = Mutex::new(None); + +/// For the memory lines: containers kept and their bytes, translations +/// kept and the bytes of their host code. None of them is ever let go. +static KEPT: [std::sync::atomic::AtomicU64; 4] = [const { std::sync::atomic::AtomicU64::new(0) }; 4]; + +/// What the shader table and the pipeline library keep in memory: +/// containers and their bytes, translations and their bytes, the bytes of +/// the library's file (kept whole while the library lives) and what its +/// last save wrote. +#[cfg(windows)] +#[cfg_attr(not(feature = "diagnostics"), allow(dead_code))] +pub(crate) fn kept() -> [u64; 7] { + use std::sync::atomic::Ordering::Relaxed; + [ + KEPT[0].load(Relaxed), + KEPT[1].load(Relaxed), + KEPT[2].load(Relaxed), + KEPT[3].load(Relaxed), + library::BLOB.load(Relaxed), + library::SAVED.load(Relaxed), + library::TRIMMED_BYTES.load(Relaxed), + ] +} + +/// The shared container for `bytes`. +fn shader(stage: &'static str, bytes: &[u8]) -> Arc { + let full = blake3::hash(bytes); + let mut shaders = SHADERS.lock().unwrap_or_else(|e| e.into_inner()); + shaders + .get_or_insert_with(HashMap::new) + .entry(*full.as_bytes()) + .or_insert_with(|| { + KEPT[0].fetch_add(1, std::sync::atomic::Ordering::Relaxed); + KEPT[1].fetch_add(bytes.len() as u64, std::sync::atomic::Ordering::Relaxed); + Arc::new(Shader { + stage, + hash: full.to_hex()[..16].to_owned(), + container: bytes.to_vec(), + #[cfg(windows)] + translated: OnceLock::new(), + #[cfg(windows)] + walks: OnceLock::new(), + }) + }) + .clone() +} + +/// A translated shader and the console resources its code reads. +#[cfg(windows)] +pub(crate) struct Translated { + pub(crate) host: leonida_shader::emit::HostShader, + pub(crate) used: Vec, + /// Whether the shader's code can store to buffer memory ([`stores`]); + /// true when its code is not known. + pub(crate) stores: bool, +} + +#[cfg(windows)] +impl Shader { + /// The translation, made on first use; a shader that does not + /// translate is logged once. + pub(crate) fn translated(&self) -> Option<&Translated> { + self.translated + .get_or_init(|| { + let done = translate(&self.container); + // `LEONIDA_SHADER_SAVE=`: each shader as the title gave it (`.cdxil`) and as + // translated (`.dxil`), by the hash crash reports name it with + if let Some(dir) = std::env::var_os("LEONIDA_SHADER_SAVE") { + let dir = std::path::PathBuf::from(dir); + let _ = std::fs::create_dir_all(&dir); + let stem = format!("{}.{}", self.hash, self.stage); + let _ = std::fs::write(dir.join(format!("{stem}.cdxil")), &self.container); + if let Ok(t) = &done { + let _ = std::fs::write(dir.join(format!("{stem}.dxil")), &t.host.dxil); + } + } + if let Ok(t) = &done { + KEPT[2].fetch_add(1, std::sync::atomic::Ordering::Relaxed); + KEPT[3].fetch_add(t.host.dxil.len() as u64, std::sync::atomic::Ordering::Relaxed); + } + match &done { + Ok(t) => tracing::info!( + stage = self.stage, + hash = %self.hash, + user_data = t.host.user_data.len(), + samplers = t.host.samplers.len(), + "shader translated" + ), + Err(e) => tracing::warn!( + stage = self.stage, + hash = %self.hash, + error = %e, + "shader does not translate; its pipelines' draws are dropped" + ), + } + done.ok() + }) + .as_ref() + } +} + +#[cfg(windows)] +fn translate(container: &[u8]) -> Result { + use leonida_shader::{Container, FourCC, HwStage}; + // The translation depends on it (a view index past a capped heap). + crate::descriptor::host::probe_view_limit(); + let c = Container::parse(container).map_err(|e| e.to_string())?; + let programs = match c.part(FourCC::DXIL) { + Some(part) => leonida_shader::native_programs(part.data).map_err(|e| e.to_string())?, + None => Vec::new(), + }; + let host = crate::shader_cache::host_shader(container)?; + let stores = programs.is_empty() || programs.iter().any(stores); + let used = programs + .into_iter() + .find(|p| { + matches!( + p.stage, + HwStage::Vs | HwStage::Ps | HwStage::Ms | HwStage::Cs + ) + }) + .map(|p| p.used) + .unwrap_or_default(); + Ok(Translated { host, used, stores }) +} + +/// The compute pipelines of the console's ray-tracing structure builder +/// (`XboxBvhBuilder.dll`; its programs are the ones with a spilled +/// user-data table) run **all or none**. Its stages feed each other +/// through memory: a stage that runs on what a dropped stage never wrote +/// computes its store offsets from garbage. The structures lie in plain +/// title memory, between the title's own objects, and a root view has no +/// size, so those stores land on the neighbours (run 98, with 14 of 35 +/// stages translated: the title died within a second of the first builder +/// submission, on pointers that had become bounding-box bit patterns). +/// +/// So a builder dispatch runs only while every builder pipeline the title +/// has created has a host pipeline; the first builder dispatch makes them +/// all on the spot instead of over the next frames (a stage "still being +/// made" would be a dropped stage). One that cannot be made turns the +/// builder off for the rest of the run. +/// +/// shortcut: and only with `LEONIDA_BVH_BUILDER=1`, until a run has shown +/// the whole builder and the host side of title memory by address +/// (`memory.rs`) working on a card; nothing reads the structures before +/// the programs that walk them translate. +#[cfg(windows)] +struct Builder { + pipelines: Vec>, + /// Every one of `pipelines` has a host pipeline. + whole: bool, + /// One could not be made. + off: bool, +} + +#[cfg(windows)] +static BUILDER: Mutex = Mutex::new(Builder { + pipelines: Vec::new(), + whole: false, + off: false, +}); + +/// Whether `shaders` are a pipeline of the structure builder. +#[cfg(windows)] +fn of_builder(shaders: &[Arc]) -> bool { + use leonida_shader::{Container, FourCC}; + let [shader] = shaders else { return false }; + if shader.stage != "compute" { + return false; + } + let Ok(c) = Container::parse(&shader.container) else { + return false; + }; + c.part(FourCC::DXIL) + .and_then(|part| leonida_shader::native_programs(part.data).ok()) + .is_some_and(|programs| programs.iter().any(leonida_shader::spill::is_spilled)) +} + +/// `LEONIDA_BVH_QUARANTINE=1`: what the structure builder's stages store +/// stays in the host's copies and is not copied back into title memory. A +/// check for a first run of the whole builder: a stage that stores where +/// it should not can then not reach the title's own objects (run 98), and +/// the programs that walk the structures read the host's copies anyway. +/// shortcut: not a way to run: the title also reads results back (sizes, +/// counters) and gets none, and a copy's pages are overwritten from title +/// memory when the title writes them. +#[cfg(windows)] +pub(crate) fn builder_quarantined(this: This) -> bool { + static ON: OnceLock = OnceLock::new(); + is_builder(this) && *ON.get_or_init(|| std::env::var_os("LEONIDA_BVH_QUARANTINE").is_some_and(|v| v == "1")) +} + +#[cfg(windows)] +impl Shader { + /// Whether the program walks the ray-tracing structures: its code has + /// an `image_bvh_intersect_ray` or `image_bvh64_intersect_ray`. Looked + /// at once, when a dispatch first asks. + fn walks(&self) -> bool { + *self.walks.get_or_init(|| container_walks(&self.container)) + } +} + +/// Whether a console container's code tests rays against the nodes of a +/// ray-tracing structure. +#[cfg(windows)] +fn container_walks(container: &[u8]) -> bool { + use leonida_shader::{Container, FourCC}; + let Ok(c) = Container::parse(container) else { + return false; + }; + c.part(FourCC::DXIL) + .and_then(|part| leonida_shader::native_programs(part.data).ok()) + .is_some_and(|programs| programs.iter().any(|p| code_walks(&p.code))) +} + +/// Whether native code has a ray-tracing node test. +#[cfg(windows)] +fn code_walks(code: &[u8]) -> bool { + leonida_shader::gfx10::decode(code).is_ok_and(|code| code.iter().any(|i| i.name().is_some_and(|n| n.starts_with("image_bvh")))) +} + +/// Dispatches held back by [`walk_held`] since the last frame line. +#[cfg(windows)] +pub(crate) static WALKS_HELD: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + +/// Whether a dispatch with the title's pipeline `this` is held back +/// because its program walks ray-tracing structures nothing has built +/// (`LEONIDA_BVH_HOLD=1`; off by default). +/// +/// The structure builder does not run (see [`Builder`]: only with +/// `LEONIDA_BVH_BUILDER=1`, and then only whole, which a host of 32-lane +/// waves does not manage yet). The title's ray-traced passes run all the +/// same: 64 programs of its shader pack test rays against structure nodes +/// (ray-traced shadows, screen probes, reflections, the irradiance cache; +/// one of them, `CS_IrradianceCache_ShadowTrace_WithFar` f607780aa8e502d0, +/// from the first world frame on in every run). Each walks, in a loop the +/// title bounds at 65,535 steps a wave, whatever bytes lie where the +/// structure would be: what it returns is not a picture of the scene, and +/// how long it runs depends on those bytes. Upstream's pull request 2311 +/// measured a card hung in exactly that dispatch on an NVIDIA card, every +/// run, and both card losses of ours since the draw windows' own fault was +/// fixed (runs 208 and 224) came within a second of the first use of the +/// programs that shade those rays' hits (`CS_RaytracingResolve`). +/// +/// With the switch such a dispatch is dropped until the builder has run +/// whole. What the passes would have written stays as the title left it +/// (their targets are not cleared by us): the picture has to be looked at. +#[cfg(windows)] +pub(crate) fn walk_held(this: This) -> bool { + static ON: OnceLock = OnceLock::new(); + if this.is_null() || !*ON.get_or_init(|| std::env::var_os("LEONIDA_BVH_HOLD").is_some_and(|v| v == "1")) { + return false; + } + let p = pipeline(this); + if !p.shaders.iter().any(|s| s.stage == "compute" && s.walks()) { + return false; + } + // (Asked only for the few programs that walk: the lock is the builder's.) + if BUILDER.lock().unwrap_or_else(|e| e.into_inner()).whole { + return false; + } + if WALKS_HELD.fetch_add(1, std::sync::atomic::Ordering::Relaxed) == 0 { + static ONCE: std::sync::Once = std::sync::Once::new(); + ONCE.call_once(|| { + tracing::info!( + shaders = ?p.shaders, + "a dispatch of a program that walks ray-tracing structures is held back: the structure builder has not built them (LEONIDA_BVH_HOLD=1); the first one" + ); + }); + } + true +} + +/// Whether the title's pipeline `this` is one of the structure builder's. +#[cfg(windows)] +pub(crate) fn is_builder(this: This) -> bool { + !this.is_null() && pipeline(this).builder +} + +/// A stage of the builder was dropped after all: none runs from here on. +#[cfg(windows)] +pub(crate) fn builder_off(why: &'static str) { + let mut b = BUILDER.lock().unwrap_or_else(|e| e.into_inner()); + if !b.off { + b.off = true; + tracing::warn!(why, "the ray-tracing structure builder is turned off for the rest of the run: its stages run all or none"); + } +} + +/// At a dispatch of a builder pipeline: whether the builder runs (see +/// [`Builder`]). +#[cfg(windows)] +pub(crate) fn builder_runs() -> bool { + static ALLOWED: OnceLock = OnceLock::new(); + if !*ALLOWED.get_or_init(|| std::env::var_os("LEONIDA_BVH_BUILDER").is_some_and(|v| v == "1")) { + return false; + } + let mut b = BUILDER.lock().unwrap_or_else(|e| e.into_inner()); + if b.off { + return false; + } + if b.whole { + return true; + } + let missing = b.pipelines.iter().filter(|p| !make::now(p)).count(); + if missing > 0 { + b.off = true; + tracing::warn!( + missing, + of = b.pipelines.len(), + "the ray-tracing structure builder stays off: not all of its programs have a host pipeline, and its stages run all or none" + ); + return false; + } + tracing::info!( + pipelines = b.pipelines.len(), + "the ray-tracing structure builder runs: all of its programs have host pipelines" + ); + b.whole = true; + true +} + +/// Whether a console program can store to buffer memory: it has a buffer, +/// typed-buffer, scalar-memory, flat or global store or atomic, or code +/// that is not all known (an instruction of those kinds outside our table, +/// an indirect jump, code that does not decode). Stores to textures +/// (image instructions) and to the program's own scratch memory do not +/// count: neither reaches a buffer's host copy. After upstream #413, +/// which leaves scalar-memory stores out and counts image stores. +#[cfg(windows)] +fn stores(program: &leonida_shader::NativeProgram) -> bool { + use leonida_shader::gfx10::{Encoding, decode}; + let Ok(code) = decode(&program.code) else { + return true; + }; + code.iter().any(|i| { + let name = i.name(); + match i.encoding { + Encoding::Mubuf + | Encoding::Mtbuf + | Encoding::Smem + | Encoding::Flat + | Encoding::Global => name.is_none_or(|n| { + (n.contains("store") || n.contains("atomic")) && !n.contains("scratch") + }), + Encoding::Sop1 => name.is_none_or(|n| matches!(n, "s_setpc_b64" | "s_swappc_b64")), + _ => false, + } + }) +} + +#[repr(C)] +struct Pipeline { + object: Object, + packet: [u32; 8], + /// Each used stage's container. + shaders: Vec>, + /// Whether a list has bound it yet (its shaders are logged then). + bound: std::sync::atomic::AtomicBool, + /// What its host pipeline is made from, and the host pipeline once made + /// (by a worker: the title may release the pipeline meanwhile). + #[cfg(windows)] + host: Arc, + /// One of the ray-tracing structure builder's ([`Builder`]). + #[cfg(windows)] + builder: bool, +} +const _: () = assert!(offset_of!(Pipeline, packet) == 0x10); + +/// Stage names, in description order. +const GRAPHICS_STAGES: [&str; 5] = ["vertex", "pixel", "domain", "hull", "geometry"]; + +fn pipeline<'a>(this: This) -> &'a Pipeline { + // SAFETY: the title passes one of our pipelines. + unsafe { &*this.cast::() } +} + +/// List method: logs each pipeline's shaders the first time a list binds +/// it, so a run lists the shaders its frames need first. +pub(crate) fn bound(this: This) { + if this.is_null() { + return; + } + let p = pipeline(this); + if p.bound.swap(true, std::sync::atomic::Ordering::Relaxed) { + return; + } + let frame = crate::frame::current(); + for shader in &p.shaders { + tracing::info!(pipeline = ?this, frame, stage = shader.stage, size = shader.container.len(), hash = %shader.hash, "first bind"); + } +} + +/// The host pipeline of a title pipeline; `None` if one of its shaders does +/// not translate, the host refuses it, or it is still being made (its first +/// use starts that, see [`make`]). +#[cfg(windows)] +pub(crate) fn host_pipeline<'a>(this: This) -> Option<&'a host::HostPipeline> { + if this.is_null() { + return None; + } + make::ready(&pipeline(this).host) +} + +/// Host pipelines queued and not made yet. +#[cfg(windows)] +pub(crate) fn making() -> u64 { + make::waiting() +} + +/// Draws and dispatches dropped since the last [`take_drops`], by reason +/// (diagnostics). +#[cfg(all(windows, feature = "diagnostics"))] +static DROPS: Mutex>> = Mutex::new(None); + +/// Shader hashes as printed in the pipeline diagnostics. +#[cfg(all(windows, feature = "diagnostics"))] +fn parse_skip_hashes(value: &str) -> Vec { + value + .split(',') + .map(str::trim) + .filter(|hash| !hash.is_empty()) + .filter_map(|hash| { + if hash.len() == 16 && hash.bytes().all(|byte| byte.is_ascii_hexdigit()) { + Some(hash.to_ascii_lowercase()) + } else { + tracing::warn!( + hash, + "LEONIDA_SKIP_PIPELINES expects 16-digit shader hashes" + ); + None + } + }) + .collect() +} + +#[cfg(all(windows, feature = "diagnostics"))] +fn skipped_shader(p: &Pipeline) -> Option<&str> { + static HASHES: OnceLock> = OnceLock::new(); + let hashes = HASHES.get_or_init(|| { + let value = std::env::var("LEONIDA_SKIP_PIPELINES").unwrap_or_default(); + parse_skip_hashes(&value) + }); + if hashes.is_empty() { + return None; + } + p.shaders + .iter() + .find(|shader| hashes.contains(&shader.hash)) + .map(|shader| shader.hash.as_str()) +} + +#[cfg(all(windows, feature = "diagnostics"))] +pub(crate) fn is_skipped(this: This) -> bool { + !this.is_null() && skipped_shader(pipeline(this)).is_some() +} + +/// Counts a draw or dispatch of `this` intentionally skipped or dropped +/// for want of a host pipeline (diagnostics). +#[cfg(all(windows, feature = "diagnostics"))] +pub(crate) fn note_drop(this: This) { + let why = if this.is_null() { + Some("no pipeline set".to_owned()) + } else { + let p = pipeline(this); + skipped_shader(p) + .map(|hash| format!("skipped shader {hash}")) + .or_else(|| make::missing(&p.host)) + }; + if let Some(why) = why { + note_why(why); + } +} + +/// Counts a draw or dispatch dropped for `why` (diagnostics). +#[cfg(all(windows, feature = "diagnostics"))] +pub(crate) fn note_why(why: String) { + crate::capture::op(0, || format!("DROPPED {why}")); + let mut drops = DROPS.lock().unwrap_or_else(|e| e.into_inner()); + *drops.get_or_insert_with(HashMap::new).entry(why).or_default() += 1; +} + +/// The drops counted since the last call, most first (diagnostics). +#[cfg(all(windows, feature = "diagnostics"))] +pub(crate) fn take_drops() -> Vec<(String, u64)> { + let drops = DROPS.lock().unwrap_or_else(|e| e.into_inner()).take(); + let mut drops: Vec<(String, u64)> = drops.into_iter().flatten().collect(); + // Frame reports only show the first 40 reasons. Keep ties ordered so + // a HashMap iteration order change cannot change which reasons appear. + drops.sort_unstable_by(|a, b| b.1.cmp(&a.1).then_with(|| a.0.cmp(&b.0))); + drops +} + +/// The stage's container, if it has one. +fn copy(stage: &'static str, code: &Bytecode) -> Option> { + if code.code.is_null() || code.size == 0 { + return None; + } + // SAFETY: the title passes `size` bytes of shader code. + Some(shader(stage, unsafe { + std::slice::from_raw_parts(code.code, code.size) + })) +} + +fn hand_out( + shaders: Vec>, + #[cfg(windows)] graphics: Option>, + iid: *const Iid, + out: *mut This, +) -> HRESULT { + tracing::trace!(?shaders, "pipeline state"); + #[cfg(windows)] + let host = Arc::new(make::Pending::new(shaders.clone(), graphics)); + #[cfg(windows)] + make::early(&host); + #[cfg(windows)] + let builder = of_builder(&shaders); + #[cfg(windows)] + if builder { + // Another stage: the group is looked at again at its next dispatch. + let mut b = BUILDER.lock().unwrap_or_else(|e| e.into_inner()); + b.pipelines.push(host.clone()); + b.whole = false; + } + let pipeline = Box::new(Pipeline { + object: Object::new(&FUNCTIONS), + packet: [0; 8], + #[cfg(windows)] + host, + #[cfg(windows)] + builder, + shaders, + bound: std::sync::atomic::AtomicBool::new(false), + }); + object::hand_out(PIPELINE, pipeline, iid, &PIPELINE_IIDS, out) +} + +/// Device method. +pub(crate) extern "system" fn create_graphics( + _: This, + desc: *const GraphicsHead, + iid: *const Iid, + out: *mut This, +) -> HRESULT { + // SAFETY: the title passes a description (null is tolerated). + let Some(desc) = (unsafe { desc.as_ref() }) else { + return E_INVALIDARG; + }; + let stages = GRAPHICS_STAGES.iter().zip(&desc.stages); + let shaders = stages.filter_map(|(s, c)| copy(s, c)).collect(); + hand_out( + shaders, + #[cfg(windows)] + None, + iid, + out, + ) +} + +/// Device method. +pub(crate) extern "system" fn create_compute( + _: This, + desc: *const ComputeHead, + iid: *const Iid, + out: *mut This, +) -> HRESULT { + // SAFETY: the title passes a description (null is tolerated). + let Some(desc) = (unsafe { desc.as_ref() }) else { + return E_INVALIDARG; + }; + hand_out( + copy("compute", &desc.stage).into_iter().collect(), + #[cfg(windows)] + None, + iid, + out, + ) +} + +/// Device method 0x1f0: the plain compute description plus console +/// extensions `(desc, extension count, extensions, iid, out)`. +/// shortcut: the extensions (console shader settings) are ignored, as is +/// the rest of the description. +pub(crate) extern "system" fn create_compute_x( + this: This, + desc: *const ComputeHead, + _extensions: u32, + _extended: *const u8, + iid: *const Iid, + out: *mut This, +) -> HRESULT { + create_compute(this, desc, iid, out) +} + +/// A pipeline described as a stream: its size and the subobjects, each a +/// type then its data, padded to 8 bytes. +#[repr(C)] +pub(crate) struct StreamDesc { + size: usize, + stream: *const u8, +} + +/// A subobject type's size (type included), and the stage it is if it is a +/// shader. The console numbers amplification and mesh shaders 23 and 24 +/// (PC: 24 and 25); its own types from 25 on are not sized yet. +fn subobject(kind: u32) -> Option<(usize, Option<&'static str>)> { + let stage = |name| Some((24, Some(name))); + match kind { + 1 => stage("vertex"), + 2 => stage("pixel"), + 3 => stage("domain"), + 4 => stage("hull"), + 5 => stage("geometry"), + 6 => stage("compute"), + 23 => stage("amplification"), + 24 => stage("mesh"), + 0 => Some((16, None)), + 12 | 19 => Some((24, None)), + 7 | 15 => Some((40, None)), + 8 => Some((336, None)), + 10 => Some((48, None)), + 11 => Some((56, None)), + 17 => Some((16, None)), + 21 => Some((64, None)), + 22 => Some((32, None)), + 9 | 13 | 14 | 16 | 18 | 20 => Some((8, None)), + _ => None, + } +} + +/// Device method: a pipeline from a stream; the shaders are kept, and the +/// graphics state for the host pipeline. +pub(crate) extern "system" fn create_stream( + _: This, + desc: *const StreamDesc, + iid: *const Iid, + out: *mut This, +) -> HRESULT { + // SAFETY: the title passes a description (null is tolerated). + let Some(desc) = (unsafe { desc.as_ref() }) else { + return E_INVALIDARG; + }; + if desc.stream.is_null() { + return E_INVALIDARG; + } + let mut shaders = Vec::new(); + #[cfg(windows)] + let mut graphics = host::GraphicsState::default(); + let mut at = 0; + while at + 8 <= desc.size { + // SAFETY: inside the stream the title passes. + let kind = unsafe { desc.stream.add(at).cast::().read_unaligned() }; + let Some((size, stage)) = subobject(kind) else { + tracing::warn!( + kind, + at, + "pipeline subobject of unknown size; the rest is ignored" + ); + break; + }; + if let Some(stage) = stage { + // SAFETY: a shader subobject has its bytecode at +8. + let code = unsafe { &*desc.stream.add(at + 8).cast::() }; + shaders.extend(copy(stage, code)); + } + #[cfg(windows)] + // SAFETY: a whole subobject of this kind lies at `at`. + unsafe { + graphics.read(kind, desc.stream.add(at)) + }; + at += size; + } + hand_out( + shaders, + #[cfg(windows)] + Some(Box::new(graphics)), + iid, + out, + ) +} + +extern "system" fn query(this: This, iid: *const Iid, out: *mut This) -> HRESULT { + let found = object::is(iid, &PIPELINE_IIDS).then_some(this); + object::answer(PIPELINE, iid, found, out) +} +extern "system" fn release(this: This) -> u32 { + object::release_boxed::(this) +} + +/// IUnknown 3, object 4, device child 1, pipeline 3. +static FUNCTIONS: Table<24> = { + let mut f = object::d3d12_object(object::missing_table::()); + f[0] = query as *const (); + f[2] = release as *const (); + f[7] = object::parent_device as *const (); // 0x38 + Table(f) +}; + +#[cfg(windows)] +pub(crate) mod host; +#[cfg(windows)] +mod library; + +/// Host pipelines created and loaded from the library since the start +/// (`crate::framelog`). +#[cfg(windows)] +pub(crate) fn frame_log_counts() -> (u64, u64) { + use std::sync::atomic::Ordering::Relaxed; + (library::MADE.load(Relaxed), library::LOADED.load(Relaxed)) +} +#[cfg(windows)] +mod make; + +/// Lets the pipeline library's mapped file go from memory when no pipeline +/// has loaded for a while (`library::trim`); called by the host's sweep. +#[cfg(windows)] +pub(crate) fn trim_library() { + library::trim(); +} + +/// The pipeline library's part of the report when the host device is +/// removed (`library::removal_note`). +#[cfg(windows)] +pub(crate) fn library_removal_note() -> String { + library::removal_note() +} + +/// Keeps compiled host pipelines, and the list of title pipelines to start +/// early, in `dir` (a folder of the cache) across runs. +#[cfg(windows)] +pub fn use_pipeline_cache(dir: std::path::PathBuf) { + library::use_pipeline_cache(dir); +} + +/// Saves the pipeline cache now if anything was added (at the end of a run). +#[cfg(windows)] +pub fn save_pipeline_cache() { + library::save(true); +} + +#[cfg(test)] +mod tests { + #[cfg(all(windows, feature = "diagnostics"))] + #[test] + fn skip_hashes_accepts_full_hashes_only() { + assert!(super::parse_skip_hashes(" , ").is_empty()); + assert_eq!( + super::parse_skip_hashes(" 0123456789ABCDEF, 0123456789abcde, xyz, 0011223344556677,"), + ["0123456789abcdef", "0011223344556677"] + ); + } + + use super::*; + use crate::object::{S_OK, slot}; + + fn shaders(p: This) -> Vec<(&'static str, Vec)> { + pipeline(p) + .shaders + .iter() + .map(|s| (s.stage, s.container.clone())) + .collect() + } + + #[test] + fn pipelines_keep_their_shaders() { + let (vs, ps) = ([1u8, 2, 3], [4u8; 5]); + let none = || Bytecode { + code: std::ptr::null(), + size: 0, + }; + let desc = GraphicsHead { + root: std::ptr::null(), + stages: [ + Bytecode { + code: vs.as_ptr(), + size: vs.len(), + }, + Bytecode { + code: ps.as_ptr(), + size: ps.len(), + }, + none(), + none(), + none(), + ], + }; + let mut p = std::ptr::null(); + assert_eq!( + create_graphics(std::ptr::null(), &desc, &PIPELINE_IIDS[0], &mut p), + S_OK + ); + assert_eq!( + shaders(p), + [("vertex", vs.to_vec()), ("pixel", ps.to_vec())] + ); + // A second pipeline with the same pixel shader shares its container. + let mut q = std::ptr::null(); + create_graphics(std::ptr::null(), &desc, &PIPELINE_IIDS[0], &mut q); + assert!(Arc::ptr_eq( + &pipeline(p).shaders[1], + &pipeline(q).shaders[1] + )); + assert_eq!(slot:: u32>(p, 0x10)(p), 0); + } + + /// The stream layout the title builds (title+0x86f090): root + /// signature, five shader slots (the first a mesh shader), blend, sample + /// mask, rasterizer, depth-stencil 1, sample description, input layout, + /// topology, render target and depth formats: 0x2b0 bytes. + #[test] + fn streams_yield_their_shaders() { + let (ms, ps) = ([9u8; 7], [4u8; 5]); + let mut stream = vec![0u8; 0x2b0]; + let mut put = |at: usize, v: u64| stream[at..at + 8].copy_from_slice(&v.to_le_bytes()); + for (at, kind) in [ + (0x10, 24), + (0x28, 2), + (0x40, 3), + (0x58, 4), + (0x70, 5), + (0x88, 8), + (0x1d8, 9), + (0x1e0, 10), + (0x210, 21), + (0x250, 17), + (0x260, 12), + (0x278, 14), + (0x280, 15), + (0x2a8, 16), + ] { + put(at, kind); + } + put(0x18, ms.as_ptr() as u64); + put(0x20, ms.len() as u64); + put(0x30, ps.as_ptr() as u64); + put(0x38, ps.len() as u64); + // Topology type 3 (triangles), one render target of format 28. + put(0x278, 14 | 3 << 32); + put(0x280, 15 | 28 << 32); + put(0x2a0, 1 << 32); + let desc = StreamDesc { + size: stream.len(), + stream: stream.as_ptr(), + }; + let mut p = std::ptr::null(); + let hr = create_stream(std::ptr::null(), &desc, &PIPELINE_IIDS[0], &mut p); + assert_eq!(hr, S_OK); + assert_eq!(shaders(p), [("mesh", ms.to_vec()), ("pixel", ps.to_vec())]); + #[cfg(windows)] + { + let g = pipeline(p).host.graphics.as_deref().unwrap(); + assert_eq!(g.topology.0, 3); + assert_eq!( + (g.targets.NumRenderTargets, g.targets.RTFormats[0].0), + (1, 28) + ); + } + } +} diff --git a/crates/leonida-gpu/src/pipeline/host.rs b/crates/leonida-gpu/src/pipeline/host.rs new file mode 100644 index 000000000..e2e8543b6 --- /dev/null +++ b/crates/leonida-gpu/src/pipeline/host.rs @@ -0,0 +1,1319 @@ +//! Host pipelines for title pipelines (decision 0007, step 3): the +//! title's graphics state with the translated shaders, under a root +//! signature of our own that the translated shaders' bindings define +//! (`leonida_shader::emit`): per stage one block of root constants for the +//! user data, root views for the title's root views, static samplers for +//! the immediate samplers, and directly indexed heaps. + +use std::ffi::{CStr, CString}; +use std::sync::Arc; + +use leonida_shader::emit::{ROOT_CBV_SPACE, SAMPLER_SPACE, USER_DATA_SPACE}; +use windows::Win32::Graphics::Direct3D::ID3DBlob; +use windows::Win32::Graphics::Direct3D12::*; +use windows::Win32::Graphics::Dxgi::Common::*; +use windows::core::PCSTR; + +use super::{Shader, Translated}; +use crate::host::host; + +/// A stream's graphics state, owned (the title's stream lives only for the +/// creation call). Subobjects the stream leaves out keep D3D12's defaults. +pub(crate) struct GraphicsState { + blend: D3D12_BLEND_DESC, + sample_mask: u32, + rasterizer: D3D12_RASTERIZER_DESC, + depth: D3D12_DEPTH_STENCIL_DESC, + depth_bounds: bool, + /// Input elements, their names pointing into `names`. + inputs: Vec, + names: Vec, + strip_cut: D3D12_INDEX_BUFFER_STRIP_CUT_VALUE, + pub(crate) topology: D3D12_PRIMITIVE_TOPOLOGY_TYPE, + pub(crate) targets: D3D12_RT_FORMAT_ARRAY, + depth_format: DXGI_FORMAT, + samples: DXGI_SAMPLE_DESC, +} + +impl Default for GraphicsState { + fn default() -> Self { + let target = D3D12_RENDER_TARGET_BLEND_DESC { + SrcBlend: D3D12_BLEND_ONE, + DestBlend: D3D12_BLEND_ZERO, + BlendOp: D3D12_BLEND_OP_ADD, + SrcBlendAlpha: D3D12_BLEND_ONE, + DestBlendAlpha: D3D12_BLEND_ZERO, + BlendOpAlpha: D3D12_BLEND_OP_ADD, + LogicOp: D3D12_LOGIC_OP_NOOP, + RenderTargetWriteMask: D3D12_COLOR_WRITE_ENABLE_ALL.0 as u8, + ..Default::default() + }; + let keep = D3D12_DEPTH_STENCILOP_DESC { + StencilFailOp: D3D12_STENCIL_OP_KEEP, + StencilDepthFailOp: D3D12_STENCIL_OP_KEEP, + StencilPassOp: D3D12_STENCIL_OP_KEEP, + StencilFunc: D3D12_COMPARISON_FUNC_ALWAYS, + }; + GraphicsState { + blend: D3D12_BLEND_DESC { + RenderTarget: [target; 8], + ..Default::default() + }, + sample_mask: u32::MAX, + rasterizer: D3D12_RASTERIZER_DESC { + FillMode: D3D12_FILL_MODE_SOLID, + CullMode: D3D12_CULL_MODE_BACK, + DepthClipEnable: true.into(), + ..Default::default() + }, + depth: D3D12_DEPTH_STENCIL_DESC { + DepthEnable: true.into(), + DepthWriteMask: D3D12_DEPTH_WRITE_MASK_ALL, + DepthFunc: D3D12_COMPARISON_FUNC_LESS, + StencilReadMask: 0xff, + StencilWriteMask: 0xff, + FrontFace: keep, + BackFace: keep, + ..Default::default() + }, + depth_bounds: false, + inputs: Vec::new(), + names: Vec::new(), + strip_cut: D3D12_INDEX_BUFFER_STRIP_CUT_VALUE_DISABLED, + topology: D3D12_PRIMITIVE_TOPOLOGY_TYPE_UNDEFINED, + targets: D3D12_RT_FORMAT_ARRAY::default(), + depth_format: DXGI_FORMAT_UNKNOWN, + samples: DXGI_SAMPLE_DESC { + Count: 1, + Quality: 0, + }, + } + } +} + +impl GraphicsState { + /// Takes in one subobject of a stream: its type, then its data at +4 + /// (+8 for those holding pointers). + /// + /// # Safety + /// `at` points at a whole subobject of type `kind`. + pub(crate) unsafe fn read(&mut self, kind: u32, at: *const u8) { + // SAFETY: the caller passes a whole subobject. + unsafe { + let data = at.add(4); + match kind { + 8 => self.blend = data.cast::().read_unaligned(), + 9 => self.sample_mask = data.cast::().read_unaligned(), + 10 => self.rasterizer = data.cast::().read_unaligned(), + 11 => { + self.depth = data.cast::().read_unaligned(); + self.depth_bounds = false; + } + 21 => { + let d = data.cast::().read_unaligned(); + self.depth_bounds = d.DepthBoundsTestEnable.as_bool(); + self.depth = D3D12_DEPTH_STENCIL_DESC { + DepthEnable: d.DepthEnable, + DepthWriteMask: d.DepthWriteMask, + DepthFunc: d.DepthFunc, + StencilEnable: d.StencilEnable, + StencilReadMask: d.StencilReadMask, + StencilWriteMask: d.StencilWriteMask, + FrontFace: d.FrontFace, + BackFace: d.BackFace, + }; + } + 12 => { + let layout = at.add(8).cast::().read_unaligned(); + if layout.pInputElementDescs.is_null() { + return; + } + let elements = std::slice::from_raw_parts( + layout.pInputElementDescs, + layout.NumElements as usize, + ); + self.names = elements + .iter() + .map(|e| CStr::from_ptr(e.SemanticName.0.cast()).to_owned()) + .collect(); + self.inputs = elements + .iter() + .zip(&self.names) + .map(|(e, name)| D3D12_INPUT_ELEMENT_DESC { + SemanticName: PCSTR(name.as_ptr().cast()), + Format: DXGI_FORMAT( + crate::resource::pc_format(e.Format.0 as u32) as i32 + ), + ..*e + }) + .collect(); + } + 13 => { + self.strip_cut = + D3D12_INDEX_BUFFER_STRIP_CUT_VALUE(data.cast::().read_unaligned()) + } + 14 => { + self.topology = + D3D12_PRIMITIVE_TOPOLOGY_TYPE(data.cast::().read_unaligned()) + } + 15 => { + self.targets = data.cast::().read_unaligned(); + for f in &mut self.targets.RTFormats { + f.0 = crate::resource::target_format(crate::resource::pc_format( + f.0 as u32, + )) as i32; + } + } + 16 => { + let f = data.cast::().read_unaligned(); + self.depth_format = DXGI_FORMAT(crate::resource::pc_format(f) as i32); + } + 17 => self.samples = data.cast::().read_unaligned(), + _ => {} + } + } + } + + /// Everything the state holds, as text: part of a pipeline's name in + /// the library and of the key a title pipeline is started early by. + pub(crate) fn describe(&self) -> String { + let inputs: Vec = self + .inputs + .iter() + .zip(&self.names) + .map(|(e, name)| { + format!( + "{name:?} {} {} {} {} {} {}", + e.SemanticIndex, e.Format.0, e.InputSlot, e.AlignedByteOffset, e.InputSlotClass.0, e.InstanceDataStepRate + ) + }) + .collect(); + let bounds = if self.depth_bounds { + " depth-bounds" + } else { + "" + }; + format!( + "{:?} {} {:?} {:?}{bounds} {inputs:?} {} {} {:?} {} {:?}", + self.blend, + self.sample_mask, + self.rasterizer, + self.depth, + self.strip_cut.0, + self.topology.0, + self.targets, + self.depth_format.0, + self.samples + ) + } + + fn depth1(&self) -> D3D12_DEPTH_STENCIL_DESC1 { + let d = &self.depth; + D3D12_DEPTH_STENCIL_DESC1 { + DepthEnable: d.DepthEnable, + DepthWriteMask: d.DepthWriteMask, + DepthFunc: d.DepthFunc, + StencilEnable: d.StencilEnable, + StencilReadMask: d.StencilReadMask, + StencilWriteMask: d.StencilWriteMask, + FrontFace: d.FrontFace, + BackFace: d.BackFace, + DepthBoundsTestEnable: self.depth_bounds.into(), + } + } + + /// The vertex buffer slots the input layout reads. + fn slots(&self) -> u32 { + self.inputs + .iter() + .fold(0, |m, e| m | 1 << e.InputSlot.min(31)) + } + + /// The input elements with their byte offsets worked out. + fn elements(&self) -> Vec { + let mut next = [0u32; 32]; + self.inputs + .iter() + .map(|e| { + let slot = e.InputSlot.min(31) as usize; + let format = e.Format.0 as u32; + let offset = if e.AlignedByteOffset == D3D12_APPEND_ALIGNED_ELEMENT { + next[slot] + } else { + e.AlignedByteOffset + }; + let bytes = crate::resource::element(format).map_or(0, |(b, _)| b as u32); + next[slot] = offset + bytes; + Input { + slot: slot as u32, + offset, + format, + per_instance: e.InputSlotClass == D3D12_INPUT_CLASSIFICATION_PER_INSTANCE_DATA, + } + }) + .collect() + } +} + +/// One input element: vertex buffer slot, byte offset, format. +#[derive(Debug, Clone, Copy)] +pub(crate) struct Input { + pub(crate) slot: u32, + pub(crate) offset: u32, + pub(crate) format: u32, + pub(crate) per_instance: bool, +} + +/// The console's own primitive topology types. +const RECTANGLES: i32 = 19; +const QUADS: i32 = 32; + +/// Whether the title's root SRVs are bound as one-view tables of the +/// buffer's host copy, whose reads past its end return zeros, rather than +/// as root descriptors, which have no size: a mesh shader's vertex fetch +/// has no record limit, and a read past the copy reaches whatever the host +/// placed after it (memory it has freed: the device is removed, upstream +/// PR #493). `LEONIDA_ROOT_SRV_DIRECT=1` goes back to root descriptors. +pub(crate) fn bounded_root_srvs() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("LEONIDA_ROOT_SRV_DIRECT").is_none()) +} + +/// One stage of a host pipeline and where its bindings go. +pub(crate) struct Stage { + pub(crate) shader: Arc, + /// The root parameter of its user data, and its size in dwords. + pub(crate) user_data: Option<(u32, u32)>, + /// Root parameters of its root views: (title root parameter, ours). + pub(crate) root_cbvs: Vec<(u8, u32)>, + pub(crate) root_srvs: Vec<(u8, u32)>, + /// Root UAVs: one-view tables like the SRVs (or root descriptors with + /// `LEONIDA_ROOT_SRV_DIRECT=1`). + pub(crate) root_uavs: Vec<(u8, u32)>, +} + +impl Stage { + pub(crate) fn translated(&self) -> &Translated { + self.shader + .translated() + .expect("host pipelines are made from translated shaders") + } +} + +pub(crate) struct HostPipeline { + /// A compute pipeline (else graphics). + pub(crate) compute: bool, + /// A mesh pipeline (graphics without vertex input). + pub(crate) mesh: bool, + pub(crate) pso: ID3D12PipelineState, + pub(crate) root: ID3D12RootSignature, + /// Vertex, then pixel stage, or the compute stage. + pub(crate) stages: Vec, + /// The vertex buffer slots it reads (bit per slot). + pub(crate) slots: u32, + pub(crate) inputs: Vec, + /// Has the geometry stage that completes the console's rectangles + /// (`leonida_shader::emit::rect_list_gs`): its rectangle draws go out + /// as the title gives them, three vertices a rectangle. + pub(crate) rects: bool, + /// Its shaders, for reports of slow submissions. + pub(crate) name: String, + /// Its depth, stencil, cull and blend state in short, for the frame + /// listing (empty for compute). + #[cfg_attr(not(feature = "diagnostics"), allow(dead_code))] + pub(crate) state: String, +} + +/// Logs a pipeline that gets no host pipeline, once per reason. +fn refuse(reason: &'static str, shaders: &[Arc]) -> Option { + static SEEN: std::sync::Mutex> = std::sync::Mutex::new(Vec::new()); + let mut seen = SEEN.lock().unwrap_or_else(|e| e.into_inner()); + if !seen.contains(&reason) { + seen.push(reason); + tracing::warn!(?shaders, "no host pipeline: {reason} (logged once)"); + } + None +} + +impl HostPipeline { + /// A host pipeline for vertex and pixel shaders with the graphics + /// state `g`, or for one compute shader. + pub(crate) fn new(shaders: &[Arc], g: Option<&GraphicsState>) -> Option { + // For the report when the host device is removed: what this thread + // has in the library from here on. + super::library::label(format!("{shaders:?}")); + let find = |stage| shaders.iter().find(|s| s.stage == stage); + let compute = match shaders { + [cs] if cs.stage == "compute" => Some(cs), + _ => None, + }; + if compute.is_none() + && shaders + .iter() + .any(|s| !matches!(s.stage, "vertex" | "pixel" | "mesh")) + { + return refuse( + "only vertex, mesh, pixel and compute stages are translated", + shaders, + ); + } + let mesh = find("mesh"); + let stages = if let Some(cs) = compute { + vec![(cs, D3D12_SHADER_VISIBILITY_ALL)] + } else { + let first = match (mesh, find("vertex")) { + (Some(ms), _) => (ms, D3D12_SHADER_VISIBILITY_MESH), + (None, Some(vs)) => (vs, D3D12_SHADER_VISIBILITY_VERTEX), + (None, None) => return refuse("no vertex or mesh shader", shaders), + }; + let mut stages = vec![first]; + stages.extend(find("pixel").map(|ps| (ps, D3D12_SHADER_VISIBILITY_PIXEL))); + stages + }; + if mesh.is_some() && !host()?.mesh_shaders() { + return refuse("the host GPU has no mesh shaders (or no shader model 6.6)", shaders); + } + for (s, _) in &stages { + s.translated()?; + } + let host = host()?; + + // The root signature the translated shaders' bindings define. + let mut params: Vec = Vec::new(); + // The ranges table parameters point at, alive until the root + // signature is made. + let mut ranges: Vec> = Vec::new(); + let mut samplers = Vec::new(); + let mut bound = Vec::new(); + for &(shader, visibility) in &stages { + let t = &shader.translated()?.host; + let mut stage = Stage { + shader: shader.clone(), + user_data: None, + root_cbvs: Vec::new(), + root_srvs: Vec::new(), + root_uavs: Vec::new(), + }; + let dwords = t.user_data_dwords(); + if dwords > 0 { + stage.user_data = Some((params.len() as u32, dwords)); + params.push(D3D12_ROOT_PARAMETER1 { + ParameterType: D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS, + Anonymous: D3D12_ROOT_PARAMETER1_0 { + Constants: D3D12_ROOT_CONSTANTS { + ShaderRegister: 0, + RegisterSpace: USER_DATA_SPACE, + Num32BitValues: dwords, + }, + }, + ShaderVisibility: visibility, + }); + } + for (slots, kind, out) in [ + ( + &t.root_cbvs, + D3D12_ROOT_PARAMETER_TYPE_CBV, + &mut stage.root_cbvs, + ), + ( + &t.root_srvs, + D3D12_ROOT_PARAMETER_TYPE_SRV, + &mut stage.root_srvs, + ), + ( + &t.root_uavs, + D3D12_ROOT_PARAMETER_TYPE_UAV, + &mut stage.root_uavs, + ), + ] { + for &slot in slots { + let uav = kind == D3D12_ROOT_PARAMETER_TYPE_UAV; + // Ours, not the title's, stay root descriptors: the + // table of strides, the directory of title memory by + // address and its fault notes. + let ours = if uav { + slot == leonida_shader::emit::SLOT_FAULTS + } else { + slot == leonida_shader::emit::SLOT_STRIDES + || slot == leonida_shader::emit::SLOT_MEMORY + }; + if (uav || kind == D3D12_ROOT_PARAMETER_TYPE_SRV) && !ours && bounded_root_srvs() { + // A one-view table: the view's size bounds the + // reads (and a root UAV's writes), which a root + // descriptor leaves unbounded. + // (Our own table of strides stays a descriptor.) + ranges.push(Box::new(D3D12_DESCRIPTOR_RANGE1 { + RangeType: if uav { + D3D12_DESCRIPTOR_RANGE_TYPE_UAV + } else { + D3D12_DESCRIPTOR_RANGE_TYPE_SRV + }, + NumDescriptors: 1, + BaseShaderRegister: u32::from(slot), + RegisterSpace: ROOT_CBV_SPACE, + Flags: D3D12_DESCRIPTOR_RANGE_FLAG_DESCRIPTORS_VOLATILE + | D3D12_DESCRIPTOR_RANGE_FLAG_DATA_VOLATILE, + OffsetInDescriptorsFromTableStart: 0, + })); + let range: *const D3D12_DESCRIPTOR_RANGE1 = &**ranges.last()?; + out.push((slot, params.len() as u32)); + params.push(D3D12_ROOT_PARAMETER1 { + ParameterType: D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE, + Anonymous: D3D12_ROOT_PARAMETER1_0 { + DescriptorTable: D3D12_ROOT_DESCRIPTOR_TABLE1 { + NumDescriptorRanges: 1, + pDescriptorRanges: range, + }, + }, + ShaderVisibility: visibility, + }); + continue; + } + out.push((slot, params.len() as u32)); + params.push(D3D12_ROOT_PARAMETER1 { + ParameterType: kind, + Anonymous: D3D12_ROOT_PARAMETER1_0 { + Descriptor: D3D12_ROOT_DESCRIPTOR1 { + ShaderRegister: u32::from(slot), + RegisterSpace: ROOT_CBV_SPACE, + Flags: D3D12_ROOT_DESCRIPTOR_FLAG_DATA_VOLATILE, + }, + }, + ShaderVisibility: visibility, + }); + } + } + for (n, s) in t.static_samplers.iter().enumerate() { + samplers.push(D3D12_STATIC_SAMPLER_DESC { + Filter: D3D12_FILTER(s.filter as i32), + AddressU: D3D12_TEXTURE_ADDRESS_MODE(s.address[0] as i32), + AddressV: D3D12_TEXTURE_ADDRESS_MODE(s.address[1] as i32), + AddressW: D3D12_TEXTURE_ADDRESS_MODE(s.address[2] as i32), + MipLODBias: s.mip_lod_bias, + MaxAnisotropy: s.max_anisotropy, + ComparisonFunc: D3D12_COMPARISON_FUNC(s.comparison as i32), + BorderColor: D3D12_STATIC_BORDER_COLOR(s.border as i32), + MinLOD: s.min_lod, + MaxLOD: s.max_lod, + ShaderRegister: n as u32, + RegisterSpace: SAMPLER_SPACE, + ShaderVisibility: visibility, + }); + } + bound.push(stage); + } + let (root, root_blob) = match root_signature(&host.device, ¶ms, &samplers, compute.is_some()) { + Ok(root) => root, + Err(e) => { + tracing::warn!(error = %e, ?shaders, "host root signature refused"); + return None; + } + }; + let code = |i: usize| { + stages.get(i).and_then(|(s, _)| s.translated()).map_or( + D3D12_SHADER_BYTECODE::default(), + |t| D3D12_SHADER_BYTECODE { + pShaderBytecode: t.host.dxil.as_ptr().cast(), + BytecodeLength: t.host.dxil.len(), + }, + ) + }; + if compute.is_some() { + let desc = D3D12_COMPUTE_PIPELINE_STATE_DESC { + // SAFETY: a borrowed pointer the description never releases. + pRootSignature: unsafe { std::mem::transmute_copy(&root) }, + CS: code(0), + ..Default::default() + }; + let name = super::library::name("compute", &root_blob, &[&code_bytes(&code(0))], ""); + let made = super::library::pipeline( + &name, + // SAFETY: the description points at live data. + |library, name| unsafe { library.LoadComputePipeline(name, &desc) }, + // SAFETY: as above. + || unsafe { host.device.CreateComputePipelineState(&desc) }, + ); + let pso = match made { + Ok(pso) => pso, + Err(e) => { + tracing::warn!(error = %e, ?shaders, "host pipeline refused"); + host.log_messages(); + return None; + } + }; + tracing::info!(?shaders, "host pipeline"); + crate::host::name(&pso, || format!("{shaders:?}")); + return Some(HostPipeline { + compute: true, + mesh: false, + pso, + root, + stages: bound, + name: format!("{shaders:?}"), + slots: 0, + inputs: Vec::new(), + rects: false, + state: String::new(), + }); + } + let Some(g) = g else { + return refuse("graphics state not kept (plain description)", shaders); + }; + let depth_bounds = if g.depth_bounds { + if host.depth_bounds() { + true + } else { + static SEEN: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + if SEEN.fetch_add(1, std::sync::atomic::Ordering::Relaxed) < 4 { + tracing::warn!( + "a pipeline enables the depth bounds test, which the host GPU does not support: its draws pass at every depth" + ); + } + false + } + } else { + false + }; + let state = g.describe(); + if mesh.is_some() { + // "triangles": the stream names its topology since it did not + // load from the library without one (see `mesh_pipeline`); a + // new name keeps such entries, stored before, from being + // looked up again. + let name = super::library::name( + "mesh triangles", + &root_blob, + &[&code_bytes(&code(0)), &code_bytes(&code(1))], + &state, + ); + let pso = match mesh_pipeline(&host.device, &root, code(0), code(1), g, depth_bounds, &name) { + Ok(pso) => pso, + Err(e) => { + tracing::warn!(error = %e, ?shaders, "host mesh pipeline refused"); + host.log_messages(); + return None; + } + }; + tracing::info!(?shaders, "host mesh pipeline"); + crate::host::name(&pso, || format!("{shaders:?}")); + return Some(HostPipeline { + compute: false, + mesh: true, + pso, + root, + stages: bound, + name: format!("{shaders:?}"), + slots: 0, + inputs: Vec::new(), + rects: false, + state: String::new(), + }); + } + + // A pipeline the title makes for rectangles gets a geometry stage + // that completes each one from the three vertices the vertex + // shader made. Without it (refused here or by the host) the draws + // fall back on what `draw` does for rectangles. + let mut rect_gs = None; + if g.topology.0 == RECTANGLES { + let ps = stages.get(1).and_then(|(s, _)| s.translated()); + let vs = &stages[0].0.translated()?.host.dxil; + match leonida_shader::emit::rect_list_gs(vs, ps.map(|t| &t.host.dxil[..])) { + Ok(gs) => rect_gs = Some(gs), + Err(e) => tracing::warn!(error = %e, ?shaders, "no rectangle geometry stage"), + } + } + let mut desc = D3D12_GRAPHICS_PIPELINE_STATE_DESC { + // SAFETY: a borrowed pointer the description never releases. + pRootSignature: unsafe { std::mem::transmute_copy(&root) }, + VS: code(0), + PS: code(1), + GS: rect_gs.as_ref().map_or(D3D12_SHADER_BYTECODE::default(), |gs| { + D3D12_SHADER_BYTECODE { + pShaderBytecode: gs.as_ptr().cast(), + BytecodeLength: gs.len(), + } + }), + BlendState: g.blend, + SampleMask: g.sample_mask, + RasterizerState: g.rasterizer, + DepthStencilState: g.depth, + InputLayout: D3D12_INPUT_LAYOUT_DESC { + pInputElementDescs: g.inputs.as_ptr(), + NumElements: g.inputs.len() as u32, + }, + IBStripCutValue: g.strip_cut, + // The console's rectangle and quad types draw as triangles on + // the host (see `draw`). + PrimitiveTopologyType: match g.topology.0 { + RECTANGLES | QUADS => D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE, + _ => g.topology, + }, + NumRenderTargets: g.targets.NumRenderTargets, + RTVFormats: g.targets.RTFormats, + DSVFormat: g.depth_format, + SampleDesc: g.samples, + ..Default::default() + }; + // A pipeline with the geometry stage has a name of its own in the + // library; the others keep theirs. + let name = |gs: Option<&Vec>| match gs { + Some(gs) => super::library::name( + "graphics rectangles", + &root_blob, + &[&code_bytes(&code(0)), &code_bytes(&code(1)), &gs[..]], + &state, + ), + None => super::library::name( + "graphics", + &root_blob, + &[&code_bytes(&code(0)), &code_bytes(&code(1))], + &state, + ), + }; + let make = |desc: &D3D12_GRAPHICS_PIPELINE_STATE_DESC, name: &str| { + if depth_bounds { + return graphics_depth_bounds_pipeline(&host.device, &root, desc, g.depth1(), name); + } + super::library::pipeline( + name, + // SAFETY: the description points at live data. + |library, name| unsafe { library.LoadGraphicsPipeline(name, desc) }, + // SAFETY: as above. + || unsafe { host.device.CreateGraphicsPipelineState(desc) }, + ) + }; + let mut made = make(&desc, &name(rect_gs.as_ref())); + if made.is_err() && rect_gs.is_some() { + // The host refused the geometry stage: once more without it. + tracing::warn!(?shaders, "host pipeline refused with the rectangle geometry stage"); + host.log_messages(); + desc.GS = D3D12_SHADER_BYTECODE::default(); + rect_gs = None; + made = make(&desc, &name(None)); + } + let pso = match made { + Ok(pso) => pso, + Err(e) => { + tracing::warn!(error = %e, ?shaders, "host pipeline refused"); + host.log_messages(); + return None; + } + }; + tracing::info!(?shaders, "host pipeline"); + crate::host::name(&pso, || format!("{shaders:?}")); + tracing::debug!( + ?shaders, + depth = ?g.depth, + depth_bounds, + dsv = g.depth_format.0, + targets = ?&g.targets.RTFormats[..g.targets.NumRenderTargets.min(8) as usize], + blend = ?g.blend.RenderTarget[0], + cull = g.rasterizer.CullMode.0, + "host graphics state" + ); + Some(HostPipeline { + compute: false, + mesh: false, + pso, + root, + stages: bound, + name: format!("{shaders:?}"), + slots: g.slots(), + inputs: g.elements(), + rects: rect_gs.is_some(), + state: { + let (d, r, b) = (&g.depth, &g.rasterizer, &g.blend.RenderTarget[0]); + let face = |f: &D3D12_DEPTH_STENCILOP_DESC| { + format!( + "fail {} depth-fail {} pass {} func {}", + f.StencilFailOp.0, f.StencilDepthFailOp.0, f.StencilPassOp.0, f.StencilFunc.0 + ) + }; + let bounds = if depth_bounds { " bounds true" } else { "" }; + format!( + "depth {} write {} func {}{bounds}; stencil {} read {:#x} write {:#x} front [{}] back [{}]; cull {} front-ccw {}; blend {} src {} dst {} op {} mask {:#x}", + d.DepthEnable.as_bool(), + d.DepthWriteMask.0, + d.DepthFunc.0, + d.StencilEnable.as_bool(), + d.StencilReadMask, + d.StencilWriteMask, + face(&d.FrontFace), + face(&d.BackFace), + r.CullMode.0, + r.FrontCounterClockwise.as_bool(), + b.BlendEnable.as_bool(), + b.SrcBlend.0, + b.DestBlend.0, + b.BlendOp.0, + b.RenderTargetWriteMask + ) + }, + }) + } +} + +/// A stream subobject: its type, then its description, pointer-aligned. +#[repr(C, align(8))] +struct Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE, T); + +fn stream_pipeline( + device: &ID3D12Device, + stream: &mut S, + name: &str, +) -> windows::core::Result { + use windows::core::Interface; + let desc = D3D12_PIPELINE_STATE_STREAM_DESC { + SizeInBytes: size_of::(), + pPipelineStateSubobjectStream: std::ptr::from_mut(stream).cast(), + }; + let device = device.cast::()?; + super::library::pipeline( + name, + // SAFETY: the stream holds whole subobjects pointing at live data. + |library, name| unsafe { library.LoadPipeline(name, &desc) }, + // SAFETY: as above. + || unsafe { device.CreatePipelineState(&desc) }, + ) +} + +/// A graphics pipeline enabling the depth bounds test: `D3D12_GRAPHICS_PIPELINE_STATE_DESC` +/// has no field for `DepthBoundsTestEnable`, so it is created and loaded as a +/// pipeline-state stream with `DEPTH_STENCIL1`. +fn graphics_depth_bounds_pipeline( + device: &ID3D12Device, + root: &ID3D12RootSignature, + d: &D3D12_GRAPHICS_PIPELINE_STATE_DESC, + depth: D3D12_DEPTH_STENCIL_DESC1, + name: &str, +) -> windows::core::Result { + use windows::core::Interface; + #[repr(C)] + struct Stream { + root: Sub<*mut std::ffi::c_void>, + vs: Sub, + ps: Sub, + blend: Sub, + mask: Sub, + raster: Sub, + depth: Sub, + input: Sub, + strip_cut: Sub, + topology: Sub, + targets: Sub, + dsv: Sub, + samples: Sub, + } + #[repr(C)] + struct StreamGs { + base: Stream, + gs: Sub, + } + let targets = D3D12_RT_FORMAT_ARRAY { + RTFormats: d.RTVFormats, + NumRenderTargets: d.NumRenderTargets, + }; + let base = Stream { + root: Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_ROOT_SIGNATURE, root.as_raw()), + vs: Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_VS, d.VS), + ps: Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_PS, d.PS), + blend: Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_BLEND, d.BlendState), + mask: Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_SAMPLE_MASK, d.SampleMask), + raster: Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_RASTERIZER, d.RasterizerState), + depth: Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DEPTH_STENCIL1, depth), + input: Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_INPUT_LAYOUT, d.InputLayout), + strip_cut: Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_IB_STRIP_CUT_VALUE, d.IBStripCutValue), + topology: Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_PRIMITIVE_TOPOLOGY, d.PrimitiveTopologyType), + targets: Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_RENDER_TARGET_FORMATS, targets), + dsv: Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DEPTH_STENCIL_FORMAT, d.DSVFormat), + samples: Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_SAMPLE_DESC, d.SampleDesc), + }; + if d.GS.pShaderBytecode.is_null() { + let mut stream = base; + stream_pipeline(device, &mut stream, name) + } else { + let mut stream = StreamGs { + base, + gs: Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_GS, d.GS), + }; + stream_pipeline(device, &mut stream, name) + } +} + +/// A mesh pipeline from the title's graphics state: the pipeline-state +/// stream form (no input layout). +/// +/// The stream names a triangle topology, which D3D12 does not need for a +/// mesh shader: without it the pipeline library refuses to load a stored +/// pipeline with the very stream it was made from (`E_INVALIDARG`; debug +/// layer message 972, "does not match the one used to create the PSO"), so +/// every mesh pipeline was compiled again, and its store then refused (970, +/// "already exists"). The translation makes triangle mesh shaders only +/// (`mesh_prologue` refuses others), and the debug layer wants the two to +/// agree (1323). +fn mesh_pipeline( + device: &ID3D12Device, + root: &ID3D12RootSignature, + ms: D3D12_SHADER_BYTECODE, + ps: D3D12_SHADER_BYTECODE, + g: &GraphicsState, + depth_bounds: bool, + name: &str, +) -> windows::core::Result { + use windows::core::Interface; + #[repr(C)] + struct Stream { + root: Sub<*mut std::ffi::c_void>, + ms: Sub, + ps: Sub, + blend: Sub, + mask: Sub, + raster: Sub, + depth: Sub, + targets: Sub, + dsv: Sub, + samples: Sub, + topology: Sub, + } + let build = |depth: Sub<_>| { + let mut stream = Stream { + root: Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_ROOT_SIGNATURE, root.as_raw()), + ms: Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_MS, ms), + ps: Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_PS, ps), + blend: Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_BLEND, g.blend), + mask: Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_SAMPLE_MASK, g.sample_mask), + raster: Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_RASTERIZER, g.rasterizer), + depth, + targets: Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_RENDER_TARGET_FORMATS, g.targets), + dsv: Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DEPTH_STENCIL_FORMAT, g.depth_format), + samples: Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_SAMPLE_DESC, g.samples), + topology: Sub( + D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_PRIMITIVE_TOPOLOGY, + D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE, + ), + }; + stream_pipeline(device, &mut stream, name) + }; + if depth_bounds { + let mut stream = Stream { + root: Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_ROOT_SIGNATURE, root.as_raw()), + ms: Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_MS, ms), + ps: Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_PS, ps), + blend: Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_BLEND, g.blend), + mask: Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_SAMPLE_MASK, g.sample_mask), + raster: Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_RASTERIZER, g.rasterizer), + depth: Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DEPTH_STENCIL1, g.depth1()), + targets: Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_RENDER_TARGET_FORMATS, g.targets), + dsv: Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DEPTH_STENCIL_FORMAT, g.depth_format), + samples: Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_SAMPLE_DESC, g.samples), + topology: Sub( + D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_PRIMITIVE_TOPOLOGY, + D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE, + ), + }; + stream_pipeline(device, &mut stream, name) + } else { + build(Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DEPTH_STENCIL, g.depth)) + } +} + +/// The bytes of shader code (none for an absent stage). +fn code_bytes(code: &D3D12_SHADER_BYTECODE) -> Vec { + if code.pShaderBytecode.is_null() { + return Vec::new(); + } + // SAFETY: a translation's own bytes, alive while its shader is. + unsafe { std::slice::from_raw_parts(code.pShaderBytecode.cast::(), code.BytecodeLength) }.to_vec() +} + +fn root_signature( + device: &ID3D12Device, + params: &[D3D12_ROOT_PARAMETER1], + samplers: &[D3D12_STATIC_SAMPLER_DESC], + compute: bool, +) -> windows::core::Result<(ID3D12RootSignature, Vec)> { + let input = if compute { + D3D12_ROOT_SIGNATURE_FLAG_NONE + } else { + D3D12_ROOT_SIGNATURE_FLAG_ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT + }; + let desc = D3D12_VERSIONED_ROOT_SIGNATURE_DESC { + Version: windows::Win32::Graphics::Direct3D12::D3D_ROOT_SIGNATURE_VERSION_1_1, + Anonymous: D3D12_VERSIONED_ROOT_SIGNATURE_DESC_0 { + Desc_1_1: D3D12_ROOT_SIGNATURE_DESC1 { + NumParameters: params.len() as u32, + pParameters: params.as_ptr(), + NumStaticSamplers: samplers.len() as u32, + pStaticSamplers: samplers.as_ptr(), + Flags: input + | D3D12_ROOT_SIGNATURE_FLAG_CBV_SRV_UAV_HEAP_DIRECTLY_INDEXED + | D3D12_ROOT_SIGNATURE_FLAG_SAMPLER_HEAP_DIRECTLY_INDEXED, + }, + }, + }; + // SAFETY: the description points at live arrays; the blob is read in + // full before it is released. + unsafe { + let mut blob: Option = None; + let mut error: Option = None; + if let Err(e) = D3D12SerializeVersionedRootSignature(&desc, &mut blob, Some(&mut error)) { + if let Some(error) = error { + let text = std::slice::from_raw_parts( + error.GetBufferPointer().cast::(), + error.GetBufferSize(), + ); + tracing::warn!("root signature: {}", String::from_utf8_lossy(text)); + } + return Err(e); + } + let blob = blob.ok_or_else(windows::core::Error::empty)?; + let bytes = + std::slice::from_raw_parts(blob.GetBufferPointer().cast::(), blob.GetBufferSize()); + Ok((device.CreateRootSignature(0, bytes)?, bytes.to_vec())) + } +} + +#[cfg(test)] +mod tests { + use std::path::{Path, PathBuf}; + use std::sync::atomic::Ordering; + + use super::*; + + /// A triangle mesh shader of our own and a pixel shader for it. + const MS: &str = "struct V { float4 p : SV_Position; }; + [outputtopology(\"triangle\")] [numthreads(1, 1, 1)] + void main(out vertices V v[3], out indices uint3 t[1]) { + SetMeshOutputCounts(3, 1); + v[0].p = float4(0, 0, 0, 1); + v[1].p = float4(1, 0, 0, 1); + v[2].p = float4(0, 1, 0, 1); + t[0] = uint3(0, 1, 2); + }"; + const PS: &str = "float4 main() : SV_Target { return 1; }"; + + /// The PC `dxc.exe` (`LEONIDA_PC_DXC`, else the newest Windows SDK's). + fn dxc() -> Option { + let dxc = match std::env::var_os("LEONIDA_PC_DXC") { + Some(p) => PathBuf::from(p), + None => leonida_shader::emit::validator::Validator::default_path()? + .with_file_name("dxc.exe"), + }; + dxc.exists().then_some(dxc) + } + + fn compile(dxc: &Path, dir: &Path, src: &str, profile: &str) -> Vec { + let (hlsl, out) = ( + dir.join(format!("{profile}.hlsl")), + dir.join(format!("{profile}.dxil")), + ); + std::fs::write(&hlsl, src).unwrap(); + let status = std::process::Command::new(dxc) + .args(["-nologo", "-T", profile, "-E", "main", "-Fo"]) + .arg(&out) + .arg(&hlsl) + .status() + .unwrap(); + assert!(status.success(), "dxc failed for {profile}"); + std::fs::read(out).unwrap() + } + + fn code(bytes: &[u8]) -> D3D12_SHADER_BYTECODE { + D3D12_SHADER_BYTECODE { + pShaderBytecode: bytes.as_ptr().cast(), + BytecodeLength: bytes.len(), + } + } + + /// A mesh pipeline made once is loaded from the library the next time, + /// not compiled again (a stream without a topology never loads). + #[test] + fn a_mesh_pipeline_loads_from_the_library() { + let Some(host) = host() else { + return; // no host GPU here + }; + if !host.mesh_shaders() { + eprintln!("no host mesh shader support; skipped"); + return; + } + let Some(dxc) = dxc() else { + eprintln!("no PC dxc.exe; skipped"); + return; + }; + let dir = tempfile::tempdir().unwrap(); + let ms = compile(&dxc, dir.path(), MS, "ms_6_5"); + let ps = compile(&dxc, dir.path(), PS, "ps_6_5"); + let (root, root_blob) = root_signature(&host.device, &[], &[], false).unwrap(); + let mut g = GraphicsState::default(); + // This pipeline has only a color target, with no depth buffer. + g.depth.DepthEnable = false.into(); + g.targets.NumRenderTargets = 1; + g.targets.RTFormats[0] = DXGI_FORMAT_R8G8B8A8_UNORM; + let name = super::super::library::name("mesh test", &root_blob, &[&ms, &ps], &g.describe()); + mesh_pipeline(&host.device, &root, code(&ms), code(&ps), &g, false, &name).expect("made"); + let loaded = super::super::library::LOADED.load(Ordering::Relaxed); + mesh_pipeline(&host.device, &root, code(&ms), code(&ps), &g, false, &name).expect("made again"); + assert!( + super::super::library::LOADED.load(Ordering::Relaxed) > loaded, + "the mesh pipeline was compiled again instead of loaded from the library" + ); + } + + const VS: &str = "float4 main(uint i : SV_VertexID) : SV_Position { + float2 p = float2((i << 1) & 2, i & 2); + return float4(p * 2.0 - 1.0, 0.5, 1.0); + }"; + + /// A graphics pipeline with `DepthBoundsTestEnable` loads back from the + /// pipeline library and culls or passes fragments according to + /// `OMSetDepthBounds` (including across a command-list cut). + #[test] + fn depth_bounds_pipeline_loads_and_filters_draws() { + let Some(host) = host() else { + return; + }; + if !host.depth_bounds() { + eprintln!("no host depth bounds support; skipped"); + return; + } + let Some(dxc) = dxc() else { + eprintln!("no PC dxc.exe; skipped"); + return; + }; + let dir = tempfile::tempdir().unwrap(); + let vs = compile(&dxc, dir.path(), VS, "vs_6_5"); + let ps = compile(&dxc, dir.path(), PS, "ps_6_5"); + let (root, root_blob) = root_signature(&host.device, &[], &[], false).unwrap(); + + let mut g = GraphicsState::default(); + // Subobject 21 (`DEPTH_STENCIL1`) with `DepthBoundsTestEnable = true`, + // depth test itself off so only depth bounds gates the draw. + #[repr(C, align(8))] + struct Sub21(u32, D3D12_DEPTH_STENCIL_DESC1); + let sub = Sub21( + 21, + D3D12_DEPTH_STENCIL_DESC1 { + DepthEnable: false.into(), + DepthWriteMask: D3D12_DEPTH_WRITE_MASK_ZERO, + DepthFunc: D3D12_COMPARISON_FUNC_ALWAYS, + DepthBoundsTestEnable: true.into(), + ..Default::default() + }, + ); + // SAFETY: `sub` is a complete subobject 21. + unsafe { g.read(21, (&raw const sub).cast()) }; + assert!(g.depth_bounds); + assert!(g.describe().contains("depth-bounds")); + g.rasterizer.CullMode = D3D12_CULL_MODE_NONE; + g.targets.NumRenderTargets = 1; + g.targets.RTFormats[0] = DXGI_FORMAT_R8G8B8A8_UNORM; + g.depth_format = DXGI_FORMAT_D32_FLOAT; + + let desc = D3D12_GRAPHICS_PIPELINE_STATE_DESC { + // SAFETY: borrowed pointer, never released by the descriptor. + pRootSignature: unsafe { std::mem::transmute_copy(&root) }, + VS: code(&vs), + PS: code(&ps), + BlendState: g.blend, + SampleMask: g.sample_mask, + RasterizerState: g.rasterizer, + DepthStencilState: g.depth, + IBStripCutValue: g.strip_cut, + PrimitiveTopologyType: D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE, + NumRenderTargets: 1, + RTVFormats: g.targets.RTFormats, + DSVFormat: g.depth_format, + SampleDesc: g.samples, + ..Default::default() + }; + let name = super::super::library::name( + "graphics depth-bounds test", + &root_blob, + &[&vs, &ps], + &g.describe(), + ); + let pso = graphics_depth_bounds_pipeline(&host.device, &root, &desc, g.depth1(), &name) + .expect("depth-bounds PSO made"); + let loaded = super::super::library::LOADED.load(Ordering::Relaxed); + graphics_depth_bounds_pipeline(&host.device, &root, &desc, g.depth1(), &name) + .expect("depth-bounds PSO made again"); + assert!( + super::super::library::LOADED.load(Ordering::Relaxed) > loaded, + "the depth-bounds pipeline was compiled again instead of loaded from the library" + ); + + // Execute two draws against a depth buffer cleared to 0.5: + // 1) bounds [0.6, 1.0] -> rejected (target stays 0) + // 2) bounds [0.4, 0.6] replayed onto a fresh HostList -> passes (target becomes 255) + let make_tex = |format, flags, state, clear: D3D12_CLEAR_VALUE| { + let heap = D3D12_HEAP_PROPERTIES { + Type: D3D12_HEAP_TYPE_DEFAULT, + ..Default::default() + }; + let rd = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D, + Width: 4, + Height: 4, + DepthOrArraySize: 1, + MipLevels: 1, + Format: format, + SampleDesc: DXGI_SAMPLE_DESC { + Count: 1, + Quality: 0, + }, + Flags: flags, + ..Default::default() + }; + let mut out: Option = None; + // SAFETY: valid heap and resource descriptions. + unsafe { + host.device + .CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &rd, state, Some(&clear), &mut out) + .unwrap(); + } + out.unwrap() + }; + let color = make_tex( + DXGI_FORMAT_R8G8B8A8_UNORM, + D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET, + D3D12_RESOURCE_STATE_RENDER_TARGET, + D3D12_CLEAR_VALUE { + Format: DXGI_FORMAT_R8G8B8A8_UNORM, + Anonymous: D3D12_CLEAR_VALUE_0 { Color: [0.0; 4] }, + }, + ); + let depth = make_tex( + DXGI_FORMAT_D32_FLOAT, + D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL, + D3D12_RESOURCE_STATE_DEPTH_WRITE, + D3D12_CLEAR_VALUE { + Format: DXGI_FORMAT_D32_FLOAT, + Anonymous: D3D12_CLEAR_VALUE_0 { + DepthStencil: D3D12_DEPTH_STENCIL_VALUE { + Depth: 0.5, + Stencil: 0, + }, + }, + }, + ); + let readback = { + let heap = D3D12_HEAP_PROPERTIES { + Type: D3D12_HEAP_TYPE_READBACK, + ..Default::default() + }; + let rd = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, + Width: 1024, + Height: 1, + DepthOrArraySize: 1, + MipLevels: 1, + SampleDesc: DXGI_SAMPLE_DESC { + Count: 1, + Quality: 0, + }, + Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, + ..Default::default() + }; + let mut out: Option = None; + // SAFETY: valid readback buffer description. + unsafe { + host.device + .CreateCommittedResource( + &heap, + D3D12_HEAP_FLAG_NONE, + &rd, + D3D12_RESOURCE_STATE_COPY_DEST, + None, + &mut out, + ) + .unwrap(); + } + out.unwrap() + }; + + let run_draw = |min: f32, max: f32| -> u8 { + let mut state = crate::draw::State::default(); + let first_list = host.new_list().unwrap(); + state.set_depth_bounds(&first_list, min, max); + first_list.close(); + // Replay onto a second host list, exercising `State::replay`. + let list = host.new_list().unwrap(); + state.replay(&list); + let rtv = host.rtv(Some(&color), None); + let dsv = host.dsv(&depth, None); + let vp = D3D12_VIEWPORT { + TopLeftX: 0.0, + TopLeftY: 0.0, + Width: 4.0, + Height: 4.0, + MinDepth: 0.0, + MaxDepth: 1.0, + }; + let rect = windows::Win32::Foundation::RECT { + left: 0, + top: 0, + right: 4, + bottom: 4, + }; + // SAFETY: open command list, live resources and views. + unsafe { + list.list.ClearRenderTargetView(rtv, &[0.0; 4], None); + list.list.ClearDepthStencilView(dsv, D3D12_CLEAR_FLAG_DEPTH, 0.5, 0, None); + list.list.OMSetRenderTargets(1, Some(&rtv), false, Some(&dsv)); + list.list.RSSetViewports(&[vp]); + list.list.RSSetScissorRects(&[rect]); + list.list.SetGraphicsRootSignature(&root); + list.list.SetPipelineState(&pso); + list.list + .IASetPrimitiveTopology(windows::Win32::Graphics::Direct3D::D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST); + list.list.DrawInstanced(3, 1, 0, 0); + list.list.ResourceBarrier(&[crate::host::transition( + &color, + D3D12_RESOURCE_STATE_RENDER_TARGET, + D3D12_RESOURCE_STATE_COPY_SOURCE, + )]); + let dst = D3D12_TEXTURE_COPY_LOCATION { + pResource: std::mem::transmute_copy(&readback), + Type: D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT, + Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { + PlacedFootprint: D3D12_PLACED_SUBRESOURCE_FOOTPRINT { + Offset: 0, + Footprint: D3D12_SUBRESOURCE_FOOTPRINT { + Format: DXGI_FORMAT_R8G8B8A8_UNORM, + Width: 4, + Height: 4, + Depth: 1, + RowPitch: 256, + }, + }, + }, + }; + let src = D3D12_TEXTURE_COPY_LOCATION { + pResource: std::mem::transmute_copy(&color), + Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, + Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { SubresourceIndex: 0 }, + }; + list.list.CopyTextureRegion(&dst, 0, 0, 0, &src, None); + list.list.ResourceBarrier(&[crate::host::transition( + &color, + D3D12_RESOURCE_STATE_COPY_SOURCE, + D3D12_RESOURCE_STATE_RENDER_TARGET, + )]); + } + list.close(); + host.execute(&[&list]); + let mut ptr = std::ptr::null_mut(); + // SAFETY: `execute` waited for the GPU; readback holds 1024 bytes. + unsafe { + readback.Map(0, None, Some(&mut ptr)).unwrap(); + let pixel = *ptr.cast::(); + readback.Unmap(0, None); + pixel + } + }; + + assert_eq!(run_draw(0.6, 1.0), 0, "depth 0.5 outside [0.6, 1.0] must be rejected"); + assert_eq!(run_draw(0.4, 0.6), 255, "depth 0.5 inside [0.4, 0.6] must pass"); + } +} diff --git a/crates/leonida-gpu/src/pipeline/library.rs b/crates/leonida-gpu/src/pipeline/library.rs new file mode 100644 index 000000000..ad7f361fd --- /dev/null +++ b/crates/leonida-gpu/src/pipeline/library.rs @@ -0,0 +1,841 @@ +//! Compiled host pipelines kept on disk, and the title pipelines worth +//! starting early (decision 0007, "Pipeline cache"). +//! +//! 1. Every host pipeline goes into the host's pipeline library, named by +//! a hash of all that its host description holds (the translated +//! shaders' code, which changes when a translation does, our root +//! signature, the graphics state). The library is saved under the cache +//! folder; the host refuses a library of another adapter or driver, and +//! an entry whose description differs, so neither is ever used. +//! 2. The title pipelines a run drew or dispatched with are listed by a key +//! known when the title creates them (their shader containers and +//! graphics state); the next run hands those to the workers at +//! creation, during loading. +//! +//! Library calls overlap: the host documents the library as safe to use +//! from several threads ("The pipeline library is thread-safe to use, and +//! will internally synchronize as necessary", `CreatePipelineLibrary`, +//! Thread Safety), with one exception kept here: two loads of the same +//! pipeline are made one after the other ([`same_name`]). Under one lock of +//! ours for every call, the eight workers made pipelines one at a time: +//! 87 to 96 of 110 looks at each worker found it waiting for that lock +//! (run 49), and an earlier run's 2,300 pipelines, all in the library, were +//! still being loaded 46 s into the opening cutscene. +//! `LEONIDA_LIBRARY_LOCK=1`: one call at a time, as before. +//! +//! The library's file is mapped, not read into memory ([`Blob`]): the host +//! keeps pointing into the bytes it was made from for as long as it lives, +//! and read into a buffer they were 1,352 MB of the process's own memory +//! for the whole run (run 60), all of it in physical memory. Mapped, the +//! pages are the file's: only those the host reads are in memory, and the +//! system can drop them without writing them anywhere. A save writes the +//! new library through a mapping of the new file in the same way (a buffer +//! of the library's size was made, filled and written out at each save). +//! `LEONIDA_LIBRARY_MAP=0`: read and written through buffers, as before. +//! +//! The mapped file's handle stays open for as long as the mapping lives +//! ([`holds`]). A save renames the new library over the file this run has +//! mapped, and with the handle closed Windows then gives up the old file's +//! contents: every page of the mapping that is not in memory at that +//! moment, or leaves memory later (the trim below, or Windows taking pages +//! back), reads as zeros from then on. The host's library reads such pages +//! as stored pipelines; the driver, handed a pipeline of zeros, removes the +//! device with DXGI_ERROR_DRIVER_INTERNAL_ERROR (runs 72, 73 and 82, each +//! within 5 ms of the first library call after a save and a trim; and the +//! library run 77 saved from such pages was refused by run 78). Measured +//! with a 64 MB file written past the system's cache, mapped and replaced: +//! 16,352 of 16,384 pages read zeros with the handle closed, none with it +//! open (the test below). `LEONIDA_LIBRARY_HANDLE=0`: closed, as before. + +use std::collections::HashSet; +use std::path::PathBuf; +use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; +use std::sync::{Mutex, MutexGuard, OnceLock, RwLock}; + +use windows::Win32::Graphics::Direct3D12::*; +use windows::core::{HSTRING, Interface, PCWSTR}; + +static DIR: OnceLock = OnceLock::new(); + +/// Keeps the pipeline library and the early list in `dir` from now on. +pub fn use_pipeline_cache(dir: PathBuf) { + let _ = DIR.set(dir); +} + +/// Host pipelines created, loaded from the library, and title pipelines +/// started at creation, since the start. +pub(crate) static MADE: AtomicU64 = AtomicU64::new(0); +pub(crate) static LOADED: AtomicU64 = AtomicU64::new(0); +pub(crate) static EARLY: AtomicU64 = AtomicU64::new(0); +/// For the memory lines: the bytes of the library's file, kept in memory +/// while the library lives, and the bytes the last save wrote (a buffer of +/// that size is made, filled and written every time pipelines were added, +/// at most every 20 s). +pub(crate) static BLOB: AtomicU64 = AtomicU64::new(0); +pub(crate) static SAVED: AtomicU64 = AtomicU64::new(0); + +/// Whether the library's file is mapped ([`Blob`]) and saved through a +/// mapping. On by default; `LEONIDA_LIBRARY_MAP=0` uses buffers, as before. +fn mapped() -> bool { + static ON: OnceLock = OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("LEONIDA_LIBRARY_MAP").is_none_or(|v| v != "0")) +} + +/// Whether the mapped library file's handle is kept open while it is +/// mapped (see the module's notes: without it a save in the same run turns +/// the mapping's pages into zeros as they leave memory). On by default; +/// `LEONIDA_LIBRARY_HANDLE=0` closes it after mapping, as before. +fn holds() -> bool { + static ON: OnceLock = OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("LEONIDA_LIBRARY_HANDLE").is_none_or(|v| v != "0")) +} + +/// A whole file mapped into memory: read-only (the library's file) or +/// writable (the file a save fills). Unmapped when dropped. +struct Mapped { + at: windows_sys::Win32::System::Memory::MEMORY_MAPPED_VIEW_ADDRESS, + len: usize, + /// The file, for a mapping made by [`Mapped::open`] ([`holds`]): open + /// until after the view is unmapped, so that the file a rename took + /// the name from keeps its contents for the view. + _file: Option, +} + +impl Mapped { + /// Maps `file` (`len` bytes, not zero) for reading, or for reading and + /// writing. + fn map(file: &std::fs::File, len: usize, write: bool) -> Option { + use std::os::windows::io::AsRawHandle; + use windows_sys::Win32::Foundation::CloseHandle; + use windows_sys::Win32::System::Memory::{ + CreateFileMappingW, FILE_MAP_READ, FILE_MAP_WRITE, MapViewOfFile, PAGE_READONLY, PAGE_READWRITE, + }; + if len == 0 { + return None; + } + // SAFETY: a file we hold open; the view keeps the file's pages + // after the mapping object and the file are closed. + let at = unsafe { + let mapping = CreateFileMappingW( + file.as_raw_handle(), + std::ptr::null(), + if write { PAGE_READWRITE } else { PAGE_READONLY }, + 0, + 0, + std::ptr::null(), + ); + if mapping.is_null() { + return None; + } + let at = MapViewOfFile(mapping, if write { FILE_MAP_WRITE } else { FILE_MAP_READ }, 0, 0, 0); + CloseHandle(mapping); + at + }; + (!at.Value.is_null()).then_some(Mapped { at, len, _file: None }) + } + + /// The file at `path`, mapped for reading; `None` if it is not there, + /// is empty or cannot be mapped. + fn open(path: &std::path::Path) -> Option { + Mapped::open_holding(path, holds()) + } + + /// As [`Mapped::open`]; `hold` says whether the file stays open with + /// the mapping. + fn open_holding(path: &std::path::Path, hold: bool) -> Option { + // Opened as the standard library opens a file to read: others may + // read, write, rename and delete it meanwhile, so a save still + // renames the new library over this one. + let file = std::fs::File::open(path).ok()?; + let len = usize::try_from(file.metadata().ok()?.len()).ok()?; + let mut mapped = Mapped::map(&file, len, false)?; + if hold { + mapped._file = Some(file); + } + Some(mapped) + } + + /// A new file of `len` bytes at `path` (replacing what is there), + /// mapped for writing. + fn create(path: &std::path::Path, len: usize) -> Option { + let file = std::fs::OpenOptions::new() + .read(true) + .write(true) + .create(true) + .truncate(true) + .open(path) + .ok()?; + file.set_len(len as u64).ok()?; + Mapped::map(&file, len, true) + } + + fn bytes(&self) -> &[u8] { + // SAFETY: the view holds `len` readable bytes until dropped. + unsafe { std::slice::from_raw_parts(self.at.Value.cast(), self.len) } + } + + /// Only for a view made by [`Mapped::create`]. + fn bytes_mut(&mut self) -> &mut [u8] { + // SAFETY: a writable view of `len` bytes, ours alone. + unsafe { std::slice::from_raw_parts_mut(self.at.Value.cast(), self.len) } + } +} + +impl Drop for Mapped { + fn drop(&mut self) { + // SAFETY: our view. + unsafe { windows_sys::Win32::System::Memory::UnmapViewOfFile(self.at) }; + } +} + +/// The bytes a library is made from: the host reads them for as long as +/// the library lives, so they are kept beside it. +enum Blob { + /// No file (an empty library). + None, + /// The file read into memory (`LEONIDA_LIBRARY_MAP=0`, tests, or a file + /// that could not be mapped). + Held(Vec), + /// The file itself, mapped. + Mapped(Mapped), +} + +impl Blob { + /// The library file in `dir`: a library a save left beside it + /// ([`NEXT_FILE`]) takes its place first. + fn of(dir: &std::path::Path) -> Blob { + let path = dir.join(LIBRARY_FILE); + let next = dir.join(NEXT_FILE); + if next.exists() && std::fs::rename(&next, &path).is_err() { + tracing::warn!("the host pipeline library saved last could not take the old one's place"); + } + if mapped() + && let Some(file) = Mapped::open(&path) + { + return Blob::Mapped(file); + } + match std::fs::read(&path) { + Ok(bytes) if !bytes.is_empty() => Blob::Held(bytes), + _ => Blob::None, + } + } + + fn bytes(&self) -> &[u8] { + match self { + Blob::None => &[], + Blob::Held(bytes) => bytes, + Blob::Mapped(file) => file.bytes(), + } + } +} + +/// The mapped library file's view (address, bytes; 0: not mapped), when a +/// pipeline was last loaded from the library (`crate::host::now_ms`), and +/// whether the view's pages were let go since ([`trim`]). +static VIEW: [std::sync::atomic::AtomicUsize; 2] = [const { std::sync::atomic::AtomicUsize::new(0) }; 2]; +static LOADED_AT: AtomicU64 = AtomicU64::new(0); +static TRIMMED: AtomicBool = AtomicBool::new(false); +/// The bytes of the view let go so far, for the memory line. +pub(crate) static TRIMMED_BYTES: AtomicU64 = AtomicU64::new(0); +/// When the view's pages were last let go (`crate::host::now_ms`), and how +/// often and when a save of this run last renamed a new library over the +/// mapped file: for [`removal_note`]. +static TRIMMED_AT: AtomicU64 = AtomicU64::new(0); +static REPLACED: [AtomicU64; 2] = [const { AtomicU64::new(0) }; 2]; + +/// The library calls running now: thread, what (load, make, store, +/// serialise), the pipeline, and since when (`crate::host::now_us`). +static CALLS: Mutex> = Mutex::new(Vec::new()); + +thread_local! { + /// The pipeline this thread is making (its shaders), for [`CALLS`]. + static LABEL: std::cell::RefCell = const { std::cell::RefCell::new(String::new()) }; +} + +/// Names the pipeline this thread makes next. +pub(crate) fn label(text: String) { + LABEL.with(|l| *l.borrow_mut() = text); +} + +/// A library call of this thread, listed in [`CALLS`] until dropped. +struct Call(u32, u64); + +fn call(what: &'static str, name: &str) -> Call { + let (thread, since) = (crate::host::thread_id(), crate::host::now_us()); + let label = LABEL.with(|l| l.borrow().clone()); + CALLS + .lock() + .unwrap_or_else(|e| e.into_inner()) + .push((thread, what, format!("{name} {label}"), since)); + Call(thread, since) +} + +impl Drop for Call { + fn drop(&mut self) { + CALLS + .lock() + .unwrap_or_else(|e| e.into_inner()) + .retain(|c| (c.0, c.3) != (self.0, self.1)); + } +} + +/// For the report when the host device is removed: the library calls +/// running at that moment, whether this run replaced the mapped file and +/// let its pages go, and how many pages of the mapping read as zeros now. +/// A library holds no page of zeros (the 259 MB one of run 83 has no run of +/// 2,048 zero bytes): each such page is one whose contents were lost (see +/// the module's notes), and a pipeline stored there is what the driver was +/// handed. +pub(crate) fn removal_note() -> String { + use std::fmt::Write; + let now = crate::host::now_us(); + let mut text = String::from("pipeline library: "); + { + let calls = CALLS.lock().unwrap_or_else(|e| e.into_inner()); + if calls.is_empty() { + text.push_str("no call running"); + } + for (i, (thread, what, name, since)) in calls.iter().enumerate() { + let _ = write!( + text, + "{}{what} of {name} running for {:.1} ms on thread {thread}", + if i == 0 { "" } else { ", " }, + now.saturating_sub(*since) as f64 / 1000.0 + ); + } + } + let (at, len) = (VIEW[0].load(Ordering::Relaxed), VIEW[1].load(Ordering::Relaxed)); + if at == 0 { + text.push_str("; its file is not mapped"); + return text; + } + let ago = |ms: u64| crate::host::now_ms().saturating_sub(ms) as f64 / 1000.0; + let _ = write!( + text, + "; its file is mapped ({len} bytes), the handle {}", + if holds() { "kept open" } else { "closed (LEONIDA_LIBRARY_HANDLE=0)" } + ); + match REPLACED[0].load(Ordering::Relaxed) { + 0 => text.push_str("; this run has not replaced the file"), + n => { + let _ = write!( + text, + "; this run replaced the file under the mapping {n} times, last {:.1} s ago", + ago(REPLACED[1].load(Ordering::Relaxed)) + ); + } + } + if TRIMMED_BYTES.load(Ordering::Relaxed) > 0 { + let _ = write!(text, "; its pages were last let go {:.1} s ago", ago(TRIMMED_AT.load(Ordering::Relaxed))); + } + // Within two seconds: pages not in memory come from the disk. + let started = std::time::Instant::now(); + // SAFETY: the view lives as long as the library, which is never dropped. + let bytes = unsafe { std::slice::from_raw_parts(at as *const u8, len) }; + let (mut zero, mut looked, mut first) = (0u64, 0u64, None); + for (n, page) in bytes.chunks(4096).enumerate() { + if n % 4096 == 0 && started.elapsed() > std::time::Duration::from_secs(2) { + break; + } + looked += 1; + if page.iter().all(|&b| b == 0) { + zero += 1; + if first.is_none() { + first = Some(n); + } + } + } + let _ = write!(text, "; {zero} of the {looked} pages looked at read as zeros now"); + if let Some(first) = first { + let _ = write!(text, " (the first is page {first}): the library's contents were lost there"); + } + text +} + +/// Lets the mapped library file's pages go from the process's memory once +/// no pipeline has been loaded for ten seconds. The host reads nearly the +/// whole file while the early pipelines load (run 65: all 1,490 MB of it +/// were in the process's memory a minute in, and 1,300 MB still at the +/// end, on a PC with 2 GB free); after that it reads the file again only +/// when a new pipeline loads. Pages let go stay in Windows' file cache +/// while nothing else wants the memory, and come back on the next read. +/// Called once a second by the sweep; does its work on a thread of its own +/// (hundreds of thousands of pages), once after each burst of loads. +/// `LEONIDA_LIBRARY_TRIM=0`: the pages stay until Windows takes them. +pub(crate) fn trim() { + static ON: OnceLock = OnceLock::new(); + let (at, len) = (VIEW[0].load(Ordering::Relaxed), VIEW[1].load(Ordering::Relaxed)); + if at == 0 + || TRIMMED.load(Ordering::Relaxed) + || !*ON.get_or_init(|| std::env::var_os("LEONIDA_LIBRARY_TRIM").is_none_or(|v| v != "0")) + { + return; + } + let quiet_ms = crate::host::ram_idle_ms(crate::host::available_physical_ram()); + if crate::host::now_ms() < LOADED_AT.load(Ordering::Relaxed) + quiet_ms + || TRIMMED.swap(true, Ordering::Relaxed) + { + return; + } + let work = move || { + // SAFETY: the view lives as long as the library, which is never + // dropped. Unlocking pages that are not locked fails, as expected, + // and takes them out of the working set: the documented way to let + // pages of a mapped file go. + unsafe { windows_sys::Win32::System::Memory::VirtualUnlock(at as *const _, len) }; + TRIMMED_BYTES.fetch_add(len as u64, Ordering::Relaxed); + TRIMMED_AT.store(crate::host::now_ms(), Ordering::Relaxed); + crate::host::trail(|| format!("pipeline library: the mapped file's pages let go from memory ({len} bytes)")); + }; + if std::thread::Builder::new().name("leonida-library-trim".into()).spawn(work).is_err() { + TRIMMED.store(false, Ordering::Relaxed); + } +} + +struct Library { + library: ID3D12PipelineLibrary1, + /// The blob the library was made from: it must outlive the library. + _blob: Blob, + /// Pipelines stored since the last save. + added: AtomicU64, + /// Stores share it and a save takes it alone: the size the library + /// asks for must still be its size when it is written out. + saving: RwLock<()>, +} + +// SAFETY: D3D12 objects are free-threaded, and the library synchronises +// its own calls (see the module's notes); what it does not, two loads of +// one name, is serialised by `same_name`. +unsafe impl Send for Library {} +// SAFETY: as above; the other fields are an atomic and a lock. +unsafe impl Sync for Library {} + +/// Held by a load of the pipeline named `name`: loads of the same name +/// wait for each other (the host's one exception to the library's thread +/// safety: such a load may change that pipeline's entry). Names share 64 +/// locks, so two different names seldom wait. +fn same_name(name: &str) -> MutexGuard<'static, ()> { + static LOADING: [Mutex<()>; 64] = [const { Mutex::new(()) }; 64]; + let at = name.bytes().fold(0usize, |h, b| h.wrapping_mul(31).wrapping_add(usize::from(b))); + LOADING[at % LOADING.len()].lock().unwrap_or_else(|e| e.into_inner()) +} + +/// With `LEONIDA_LIBRARY_LOCK=1`: held by every library call, as before. +fn one_call() -> Option> { + static ON: OnceLock = OnceLock::new(); + static CALLING: Mutex<()> = Mutex::new(()); + ON.get_or_init(|| std::env::var_os("LEONIDA_LIBRARY_LOCK").is_some_and(|v| v == "1")) + .then(|| CALLING.lock().unwrap_or_else(|e| e.into_inner())) +} + +const LIBRARY_FILE: &str = "host-pipelines.bin"; +/// A saved library that could not replace [`LIBRARY_FILE`] while this run +/// had it mapped (a system that refuses to replace a mapped file): the next +/// start renames it over the library first ([`Blob::of`]). +const NEXT_FILE: &str = "host-pipelines.next"; +const EARLY_FILE: &str = "early-pipelines.txt"; +/// Title pipelines listed for an early start, at most. +const EARLY_MAX: usize = 8192; + +fn library() -> Option<&'static Library> { + static LIBRARY: OnceLock> = OnceLock::new(); + LIBRARY + .get_or_init(|| { + let device = crate::host::host()?.device.cast::().ok()?; + let blob = DIR.get().map_or(Blob::None, |d| Blob::of(d)); + let library = open(&device, blob); + if library.is_none() { + tracing::warn!("no host pipeline library: pipelines are not kept"); + } + library + }) + .as_ref() +} + +/// The library in `blob`, or an empty one if the host rejects the blob (an +/// adapter or driver change, damage). +fn open(device: &ID3D12Device1, blob: Blob) -> Option { + let make = |bytes: &[u8]| -> windows::core::Result { + // SAFETY: the bytes outlive the library (kept beside it). + unsafe { + device.CreatePipelineLibrary::(bytes)?.cast() + } + }; + if !blob.bytes().is_empty() { + match make(blob.bytes()) { + Ok(library) => { + let bytes = blob.bytes().len(); + BLOB.store(bytes as u64, Ordering::Relaxed); + tracing::info!(bytes, mapped = matches!(blob, Blob::Mapped(_)), "host pipeline library loaded"); + if let Blob::Mapped(file) = &blob { + VIEW[1].store(file.len, Ordering::Relaxed); + VIEW[0].store(file.at.Value as usize, Ordering::Relaxed); + LOADED_AT.store(crate::host::now_ms(), Ordering::Relaxed); + } + return Some(Library { + library, + _blob: blob, + added: AtomicU64::new(0), + saving: RwLock::new(()), + }); + } + Err(e) => tracing::info!(error = %e, "host pipeline library rejected; starting an empty one"), + } + } else { + tracing::info!("no host pipeline library yet; starting an empty one"); + } + // The rejected bytes are let go (a mapped file is unmapped) before the + // empty library is made: nothing reads them any more. + drop(blob); + let library = make(&[]).ok()?; + Some(Library { + library, + _blob: Blob::None, + added: AtomicU64::new(0), + saving: RwLock::new(()), + }) +} + +/// A pipeline's name in the library: the hash of what its host +/// description holds. +pub(crate) fn name(kind: &str, root: &[u8], code: &[&[u8]], state: &str) -> String { + let mut h = blake3::Hasher::new(); + for part in [kind.as_bytes(), root].into_iter().chain(code.iter().copied()).chain([state.as_bytes()]) { + h.update(&(part.len() as u64).to_le_bytes()); + h.update(part); + } + h.finalize().to_hex()[..32].to_owned() +} + +/// The pipeline named `name`: loaded from the library by `load` if it is +/// there with the same description, else made by `create` and stored. +pub(crate) fn pipeline( + name: &str, + load: impl FnOnce(&ID3D12PipelineLibrary1, PCWSTR) -> windows::core::Result, + create: impl FnOnce() -> windows::core::Result, +) -> windows::core::Result { + let wide = HSTRING::from(name); + let Some(library) = library() else { + MADE.fetch_add(1, Ordering::Relaxed); + return create(); + }; + let began = std::time::Instant::now(); + let loaded = { + let _all = one_call(); + let _one = same_name(name); + let _call = call("load", name); + load(&library.library, PCWSTR(wide.as_ptr())) + }; + // The load read the library's file (see `trim`). + LOADED_AT.store(crate::host::now_ms(), Ordering::Relaxed); + TRIMMED.store(false, Ordering::Relaxed); + let refused = match loaded { + Ok(pso) => { + LOADED.fetch_add(1, Ordering::Relaxed); + crate::host::trail(|| { + let label = LABEL.with(|l| l.borrow().clone()); + format!("pipeline library: loaded {label} in {:.1} ms", began.elapsed().as_secs_f64() * 1e3) + }); + return Ok(pso); + } + Err(e) => e, + }; + // Compiled outside any lock: compiles take up to seconds. + let pso = { + let _call = call("make", name); + create()? + }; + MADE.fetch_add(1, Ordering::Relaxed); + crate::host::trail(|| { + let label = LABEL.with(|l| l.borrow().clone()); + format!( + "pipeline library: made {label} in {:.1} ms (the library did not load it: {refused})", + began.elapsed().as_secs_f64() * 1e3 + ) + }); + let _all = one_call(); + let _stores = library.saving.read().unwrap_or_else(|e| e.into_inner()); + let _call = call("store", name); + // SAFETY: a live pipeline; a name already stored (a description that + // differs) is refused, which leaves the library as it was. + if unsafe { library.library.StorePipeline(PCWSTR(wide.as_ptr()), &pso) }.is_ok() { + library.added.fetch_add(1, Ordering::Relaxed); + } + Ok(pso) +} + +/// Writes the library and the early list if pipelines were added since the +/// last save and `SAVE_EVERY` has passed (or `now`). +pub(crate) fn save(now: bool) { + static LAST: Mutex> = Mutex::new(None); + const SAVE_EVERY: std::time::Duration = std::time::Duration::from_secs(20); + let (Some(dir), Some(library)) = (DIR.get(), library()) else { return }; + { + let mut last = LAST.lock().unwrap_or_else(|e| e.into_inner()); + if !now && last.is_some_and(|t| t.elapsed() < SAVE_EVERY) { + return; + } + *last = Some(std::time::Instant::now()); + } + if let Err(e) = std::fs::create_dir_all(dir) { + tracing::warn!(error = %e, "host pipeline library not saved"); + return; + } + let tmp = dir.join(LIBRARY_FILE).with_extension("tmp"); + // The bytes of the library written to `tmp`; 0 when no pipeline was + // added: the library on disk is then what it was, and only the early + // list is written (a title pipeline first drawn with wrote all 1,352 MB + // of the library again: run 60's second save). + let bytes = { + let _all = one_call(); + // No store between asking the size and writing; loads go on. + let _alone = library.saving.write().unwrap_or_else(|e| e.into_inner()); + let added = library.added.load(Ordering::Relaxed); + if !USED_CHANGED.swap(false, Ordering::Relaxed) && added == 0 { + return; + } + if added == 0 { + 0 + } else { + // SAFETY: a plain query. + let size = unsafe { library.library.GetSerializedSize() }; + let _call = call("serialise", "the whole library"); + if let Err(e) = serialise(&library.library, &tmp, size) { + tracing::warn!(error = %e, "host pipeline library not serialised"); + let _ = std::fs::remove_file(&tmp); + return; + } + library.added.store(0, Ordering::Relaxed); + SAVED.store(size as u64, Ordering::Relaxed); + size + } + }; + let used: Vec = USED.lock().unwrap_or_else(|e| e.into_inner()).iter().flatten().cloned().collect(); + let library_written = if bytes > 0 { replace_library(dir, &tmp) } else { Ok(()) }; + if bytes > 0 && library_written.is_ok() { + // In place unless the system refused and the new one waits beside it. + let in_place = !dir.join(NEXT_FILE).exists(); + if in_place && VIEW[0].load(Ordering::Relaxed) != 0 { + REPLACED[1].store(crate::host::now_ms(), Ordering::Relaxed); + REPLACED[0].fetch_add(1, Ordering::Relaxed); + } + crate::host::trail(|| { + format!( + "pipeline library: saved {bytes} bytes, {}", + if in_place { "renamed over the library's file" } else { "left beside the library's file for the next start" } + ) + }); + } + let written = library_written + .and_then(|()| write_atomically(&dir.join(EARLY_FILE), used.join("\n").as_bytes())); + match written { + Ok(()) => tracing::info!( + bytes, + early = used.len(), + made = MADE.load(Ordering::Relaxed), + loaded = LOADED.load(Ordering::Relaxed), + started_early = EARLY.load(Ordering::Relaxed), + "host pipeline library saved" + ), + Err(e) => tracing::warn!(error = %e, "host pipeline library not saved"), + } +} + +/// Writes the library's `size` serialised bytes to the file `tmp`: through +/// a mapping of that file, so that the bytes are the file's pages and not +/// 1.3 GB more of the process's own memory for the seconds a save takes; +/// through a buffer where the file cannot be mapped (and with +/// `LEONIDA_LIBRARY_MAP=0`). +fn serialise(library: &ID3D12PipelineLibrary1, tmp: &std::path::Path, size: usize) -> std::io::Result<()> { + let failed = |e: windows::core::Error| std::io::Error::other(e.to_string()); + if mapped() + && let Some(mut file) = Mapped::create(tmp, size) + { + // SAFETY: a buffer of the size the library asks for. + return unsafe { library.Serialize(file.bytes_mut()) }.map_err(failed); + } + let mut bytes = vec![0u8; size]; + // SAFETY: a buffer of the size the library asks for. + unsafe { library.Serialize(&mut bytes) }.map_err(failed)?; + std::fs::write(tmp, &bytes) +} + +/// Renames the written library `tmp` over the library's file in `dir`. This +/// run may have that file mapped: Windows 11 replaces a mapped file, and +/// the mapping goes on reading the old one for as long as a handle on it +/// is open ([`holds`]; with none, only the pages in memory at that moment +/// stay: the rest read as zeros). Where a system refuses, the new library +/// is left beside it as [`NEXT_FILE`] for the next start. +fn replace_library(dir: &std::path::Path, tmp: &std::path::Path) -> std::io::Result<()> { + std::fs::rename(tmp, dir.join(LIBRARY_FILE)).or_else(|_| std::fs::rename(tmp, dir.join(NEXT_FILE))) +} + +/// Writes `bytes` to a temporary file beside `path`, then renames it over +/// `path`: a reader never sees a part. +fn write_atomically(path: &std::path::Path, bytes: &[u8]) -> std::io::Result<()> { + let tmp = path.with_extension("tmp"); + std::fs::write(&tmp, bytes)?; + std::fs::rename(&tmp, path) +} + +/// Title pipeline keys requested by draws or dispatches (this run and the last). +static USED: Mutex>> = Mutex::new(None); +static USED_CHANGED: AtomicBool = AtomicBool::new(false); + +fn used() -> std::sync::MutexGuard<'static, Option>> { + let mut used = USED.lock().unwrap_or_else(|e| e.into_inner()); + if used.is_none() { + let listed = DIR + .get() + .and_then(|d| std::fs::read_to_string(d.join(EARLY_FILE)).ok()) + .unwrap_or_default(); + let set: HashSet = listed.lines().filter(|l| !l.is_empty()).map(str::to_owned).collect(); + tracing::info!(pipelines = set.len(), "title pipelines to start early"); + *used = Some(set); + } + used +} + +/// Whether the title pipeline with `key` was requested in this or an earlier run. +pub(crate) fn wanted_early(key: &str) -> bool { + used().as_ref().is_some_and(|s| s.contains(key)) +} + +/// A draw or dispatch requested the title pipeline with `key`. +pub(crate) fn note_used(key: &str) { + let mut used = used(); + let set = used.get_or_insert_with(HashSet::new); + if set.len() < EARLY_MAX && set.insert(key.to_owned()) { + USED_CHANGED.store(true, Ordering::Relaxed); + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn names_change_with_what_goes_into_the_pipeline() { + let a = name("graphics", b"root", &[b"vs", b"ps"], "state"); + assert_eq!(a, name("graphics", b"root", &[b"vs", b"ps"], "state")); + assert_ne!(a, name("graphics", b"root", &[b"vs", b"ps2"], "state")); + assert_ne!(a, name("graphics", b"root", &[b"vs", b"ps"], "state2")); + assert_ne!(a, name("graphics", b"root2", &[b"vs", b"ps"], "state")); + assert_ne!(a, name("mesh", b"root", &[b"vs", b"ps"], "state")); + // Parts do not run into each other. + assert_ne!(a, name("graphics", b"root", &[b"vsp", b"s"], "state")); + } + + #[test] + fn a_rejected_blob_gives_an_empty_library() { + let Some(device) = crate::host::host().and_then(|h| h.device.cast::().ok()) else { + return; // no host GPU here + }; + let library = open(&device, Blob::Held(b"not a pipeline library".repeat(16))).expect("an empty library"); + // SAFETY: a plain query on a live library. + assert!(unsafe { library.library.GetSerializedSize() } > 0); + assert!(matches!(library._blob, Blob::None)); + } + + /// A mapped file reads as the file's bytes, a file written through a + /// mapping holds what was written, and the library's file can be + /// replaced while it is mapped (or the new one waits as the next). + #[test] + fn the_library_file_is_mapped_and_replaced() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join(LIBRARY_FILE); + assert!(matches!(Blob::of(dir.path()), Blob::None), "no file yet"); + std::fs::write(&path, b"").unwrap(); + assert!(matches!(Blob::of(dir.path()), Blob::None), "an empty file"); + let old: Vec = (0..200_000u32).map(|i| i as u8).collect(); + std::fs::write(&path, &old).unwrap(); + let blob = Blob::of(dir.path()); + assert!(matches!(blob, Blob::Mapped(_)) || !mapped()); + assert_eq!(blob.bytes(), &old[..]); + // A save while the old file is mapped. + let tmp = path.with_extension("tmp"); + let new: Vec = (0..300_000u32).map(|i| (i * 7) as u8).collect(); + { + let mut file = Mapped::create(&tmp, new.len()).expect("a new file, mapped"); + file.bytes_mut().copy_from_slice(&new); + } + assert_eq!(std::fs::read(&tmp).unwrap(), new); + replace_library(dir.path(), &tmp).unwrap(); + assert!(!tmp.exists()); + // The mapping still reads the old library. + assert_eq!(blob.bytes(), &old[..]); + drop(blob); + // The next start reads the new one, wherever the save left it. + assert_eq!(Blob::of(dir.path()).bytes(), &new[..]); + assert!(!dir.path().join(NEXT_FILE).exists()); + } + + /// The bytes at `at` of the pattern the test below writes. + fn pattern(at: usize, out: &mut [u8]) { + for (i, word) in out.chunks_exact_mut(4).enumerate() { + let v = ((at / 4 + i) as u32).wrapping_mul(2_654_435_761).wrapping_add(1); + word.copy_from_slice(&v.to_le_bytes()); + } + } + + /// A file of `len` bytes (whole MiB) of [`pattern`], written past the + /// system's cache: none of its pages is in memory afterwards. False + /// where the folder's file system does not take such writes. + fn write_uncached(path: &std::path::Path, len: usize) -> bool { + use std::io::Write; + use std::os::windows::fs::OpenOptionsExt; + // FILE_FLAG_NO_BUFFERING | FILE_FLAG_WRITE_THROUGH + const UNCACHED: u32 = 0x2000_0000 | 0x8000_0000; + const CHUNK: usize = 1 << 20; + let Ok(mut file) = std::fs::OpenOptions::new() + .write(true) + .create(true) + .truncate(true) + .custom_flags(UNCACHED) + .open(path) + else { + return false; + }; + // Such writes want a buffer on a sector boundary. + let mut store = vec![0u8; CHUNK + 4096]; + let start = store.as_ptr().align_offset(4096); + for at in (0..len).step_by(CHUNK) { + let chunk = &mut store[start..start + CHUNK]; + pattern(at, chunk); + if file.write_all(chunk).is_err() { + return false; + } + } + true + } + + /// The device loss of runs 72, 73 and 82: the library's file is + /// replaced while it is mapped, and pages of the mapping that were not + /// in memory then are read afterwards (in the runs: pages the trim let + /// go and Windows gave to something else). With the file's handle kept + /// open they still read as the old file. (With it closed, as before, + /// all but the first few read as zeros on the PC this was found on.) + #[test] + fn a_replaced_library_file_still_reads_from_the_disk() { + const LEN: usize = 8 << 20; + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join(LIBRARY_FILE); + if !write_uncached(&path, LEN) { + return; // no uncached writes here: nothing to show + } + let mapped = Mapped::open_holding(&path, true).expect("the file, mapped"); + // A save: the new library, renamed over the mapped one. + let tmp = path.with_extension("tmp"); + { + let mut file = Mapped::create(&tmp, LEN).expect("a new file, mapped"); + file.bytes_mut().fill(0xEE); + } + replace_library(dir.path(), &tmp).unwrap(); + // Every page of the old mapping, read for the first time now. + let mut expected = vec![0u8; 4096]; + for (page, bytes) in mapped.bytes().chunks(4096).enumerate() { + pattern(page * 4096, &mut expected); + assert!(bytes == &expected[..], "page {page} of the replaced library no longer reads as the old file"); + } + } +} diff --git a/crates/leonida-gpu/src/pipeline/make.rs b/crates/leonida-gpu/src/pipeline/make.rs new file mode 100644 index 000000000..ad5b9ef51 --- /dev/null +++ b/crates/leonida-gpu/src/pipeline/make.rs @@ -0,0 +1,400 @@ +//! Host pipelines are made by workers, not by the title thread that first +//! records a draw with them. Translating a shader and the host driver's +//! compile take from milliseconds to seconds each (structurisation of the +//! biggest compute programs ~0.4 s, some driver compiles 3.4 s), and +//! the title's first world frame wants over 1,200 new pipelines: made +//! on its recording threads, that frame took more than 30 s and the +//! title's GPU watchdog ended the run (decision 0007, "Pipelines made off +//! the title's threads"). +//! +//! A first use queues the pipeline and waits for it within a budget per +//! frame, so the cheap ones (menus, one-off passes such as a colour-grading +//! bake) are there at once as before; past the budget a draw or dispatch +//! whose pipeline is not ready is dropped, as an untranslated one is. +//! +//! The default budget is half a second per title frame. A pass the title +//! runs only once and whose pipeline takes longer is lost. + +use std::collections::VecDeque; +use std::sync::atomic::{AtomicBool, AtomicU8, AtomicU64, Ordering}; +use std::sync::{Arc, Condvar, Mutex, OnceLock}; +use std::time::{Duration, Instant}; + +use super::Shader; +use super::host::{GraphicsState, HostPipeline}; + +/// What a host pipeline is made from, and the host pipeline once made. +pub(crate) struct Pending { + shaders: Vec>, + pub(crate) graphics: Option>, + queue_state: AtomicU8, + made: OnceLock>, + /// What identifies it across runs (shader containers and state), and + /// whether a draw or dispatch has requested it yet. + key: String, + used: AtomicBool, +} + +// SAFETY: D3D12 objects are free-threaded; the graphics state (whose input +// elements point into its own names) is only read after creation. +unsafe impl Send for Pending {} +// SAFETY: as above. +unsafe impl Sync for Pending {} + +impl Pending { + pub(crate) fn new(shaders: Vec>, graphics: Option>) -> Pending { + let mut key = blake3::Hasher::new(); + for s in &shaders { + key.update(s.stage.as_bytes()); + key.update(s.hash.as_bytes()); + } + key.update(graphics.as_ref().map(|g| g.describe()).unwrap_or_default().as_bytes()); + Pending { + shaders, + graphics, + queue_state: AtomicU8::new(NOT_QUEUED), + made: OnceLock::new(), + key: key.finalize().to_hex()[..32].to_owned(), + used: AtomicBool::new(false), + } + } + + fn make(&self) { + self.made + .get_or_init(|| HostPipeline::new(&self.shaders, self.graphics.as_deref())); + let (lock, done) = &DONE; + let _held = lock.lock().unwrap_or_else(|e| e.into_inner()); + done.notify_all(); + } +} + +/// Why a pipeline has no host pipeline (diagnostics): its shaders that do +/// not translate, else "refused" or "being made"; `None` if it has one. +#[cfg(feature = "diagnostics")] +pub(crate) fn missing(p: &Pending) -> Option { + match p.made.get() { + Some(Some(_)) => None, + None => Some("being made".into()), + Some(None) => { + let failed: Vec = p + .shaders + .iter() + .filter(|s| matches!(s.translated.get(), Some(None))) + .map(|s| format!("{} {}", s.stage, s.hash)) + .collect(); + Some(if failed.is_empty() { + format!("refused {:?}", p.shaders) + } else { + failed.join(" + ") + }) + } + } +} + +/// Signalled whenever a worker has made a pipeline. +static DONE: (Mutex<()>, Condvar) = (Mutex::new(()), Condvar::new()); + +/// Waiting allowed per title frame, over all threads. +fn wait_budget() -> Duration { + static BUDGET: OnceLock = OnceLock::new(); + *BUDGET.get_or_init(|| { + let millis = std::env::var("LEONIDA_PIPELINE_WAIT_MS") + .ok() + .and_then(|value| value.trim().parse::().ok()) + .unwrap_or(500); + tracing::info!(millis, "host pipeline wait budget per frame"); + Duration::from_millis(millis) + }) +} + +/// Pipelines queued and not made yet. +static WAITING: AtomicU64 = AtomicU64::new(0); + +/// Pipelines queued and not made yet (for the frame line). +pub(crate) fn waiting() -> u64 { + WAITING.load(Ordering::Relaxed) +} + +/// The host pipeline if it is made (or is made within the frame's budget); +/// queues it on first use. +pub(crate) fn ready(p: &Arc) -> Option<&HostPipeline> { + // A still-pending pipeline was requested by the title too. Prewarm it + // on the next launch, even if this run never got to use it. + if !p.used.load(Ordering::Relaxed) && !p.used.swap(true, Ordering::Relaxed) { + super::library::note_used(&p.key); + } + if p.made.get().is_none() { + start(p, REQUESTED); + wait(p, crate::frame::current()); + } + p.made.get()?.as_ref() +} + +/// Makes `p` on this thread if it is not made yet (waiting for a worker +/// that is making it); whether it has a host pipeline. +pub(crate) fn now(p: &Arc) -> bool { + p.make(); + p.made.get().is_some_and(|made| made.is_some()) +} + +/// At the title's creation of a pipeline: starts it at once if an earlier +/// run drew with it (during loading, so the world's first frames find it). +pub(crate) fn early(p: &Arc) { + if !p.shaders.is_empty() && super::library::wanted_early(&p.key) { + super::library::EARLY.fetch_add(1, Ordering::Relaxed); + start(p, EARLY); + } +} + +/// Whether the frame's budget is one for all threads together: a thread +/// that waits takes what is left of it and gives back what it did not +/// use. Counted only when a wait had ended, the budget was one per thread: +/// each of the title's five recording threads began its first wait of a +/// frame with nothing counted yet and waited the whole half second, 2.5 s +/// of waiting in every frame in which pipelines were being made (runs +/// 34-49: "2504 ms waiting for pipelines" in each such frame). +/// On by default; `LEONIDA_PIPELINE_WAIT_SHARED=0` counts as before. +fn shared_budget() -> bool { + static ON: OnceLock = OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("LEONIDA_PIPELINE_WAIT_SHARED").is_none_or(|v| v != "0")) +} + +/// Waits for `p` while frame `frame` has budget left. +fn wait(p: &Pending, frame: u64) { + let budget = wait_budget(); + if budget.is_zero() { + return; + } + // The frame the budget belongs to, and what was waited of it (or is + // taken by a thread waiting now). + static SPENT: Mutex<(u64, Duration)> = Mutex::new((u64::MAX, Duration::ZERO)); + let shared = shared_budget(); + let left = { + let mut spent = SPENT.lock().unwrap_or_else(|e| e.into_inner()); + if spent.0 != frame { + *spent = (frame, Duration::ZERO); + } + let left = budget.saturating_sub(spent.1); + if shared { + spent.1 += left; + } + left + }; + if left.is_zero() { + return; + } + let started = Instant::now(); + let (lock, done) = &DONE; + let mut held = lock.lock().unwrap_or_else(|e| e.into_inner()); + while p.made.get().is_none() { + let rest = left.saturating_sub(started.elapsed()); + if rest.is_zero() { + break; + } + held = done.wait_timeout(held, rest).unwrap_or_else(|e| e.into_inner()).0; + } + drop(held); + let waited = started.elapsed().min(left); + { + let mut spent = SPENT.lock().unwrap_or_else(|e| e.into_inner()); + // A frame that began meanwhile has its own budget. + if spent.0 == frame { + if shared { + spent.1 = spent.1.saturating_sub(left - waited); + } else { + spent.1 += waited; + } + } + } + crate::framelog::add(crate::framelog::T::PipelineWaitUs, started.elapsed().as_micros() as u64); + #[cfg(feature = "diagnostics")] + crate::copystat::add( + crate::copystat::C::PipelineWaitUs, + started.elapsed().as_micros() as u64, + ); +} + +const NOT_QUEUED: u8 = 0; +const EARLY: u8 = 1; +const REQUESTED: u8 = 2; +const MAKING: u8 = 3; + +struct Queue { + early: VecDeque>, + requested: VecDeque>, +} + +impl Queue { + const fn new() -> Self { + Self { + early: VecDeque::new(), + requested: VecDeque::new(), + } + } + + /// Queues an unrequested pipeline or promotes one queued at creation. + /// Returns whether it is new to the queue, or `None` if nothing changed. + fn push(&mut self, p: &Arc, priority: u8) -> Option { + let prev = p.queue_state.load(Ordering::Relaxed); + if prev >= priority { + return None; + } + p.queue_state.store(priority, Ordering::Relaxed); + if priority == REQUESTED { + self.requested.push_back(p.clone()); + } else { + self.early.push_back(p.clone()); + } + Some(prev == NOT_QUEUED) + } + + fn pop(&mut self) -> Option> { + let p = self.requested.pop_front().or_else(|| { + // An early entry can have been promoted and claimed already. + std::iter::from_fn(|| self.early.pop_front()) + .find(|p| p.queue_state.load(Ordering::Relaxed) == EARLY) + })?; + p.queue_state.store(MAKING, Ordering::Relaxed); + Some(p) + } +} + +static QUEUE: Mutex = Mutex::new(Queue::new()); +static AVAILABLE: Condvar = Condvar::new(); + +/// Start or promote work for a draw without waiting behind the entire early +/// list. Queue changes and worker claims happen under the same lock. +fn start(p: &Arc, priority: u8) { + if p.queue_state.load(Ordering::Relaxed) >= priority { + return; + } + if !workers() { + if p.queue_state.swap(MAKING, Ordering::Relaxed) == NOT_QUEUED { + p.make(); + } + return; + } + let mut queue = QUEUE.lock().unwrap_or_else(|e| e.into_inner()); + if let Some(new) = queue.push(p, priority) { + if new { + PEAK.fetch_max(WAITING.fetch_add(1, Ordering::Relaxed) + 1, Ordering::Relaxed); + } + AVAILABLE.notify_one(); + } +} + +fn next() -> Arc { + let mut queue = QUEUE.lock().unwrap_or_else(|e| e.into_inner()); + loop { + if let Some(p) = queue.pop() { + return p; + } + queue = AVAILABLE.wait(queue).unwrap_or_else(|e| e.into_inner()); + } +} + +/// Starts the workers (half the logical processors, 2 to 8) on first use. +fn workers() -> bool { + static RUNNING: OnceLock = OnceLock::new(); + *RUNNING.get_or_init(|| { + let mut running = false; + let workers = std::thread::available_parallelism().map_or(2, |n| (n.get() / 2).clamp(2, 8)); + for i in 0..workers { + let spawned = std::thread::Builder::new() + .name(format!("leonida-pipelines-{i}")) + .spawn(|| { + // Below the title's own threads (loading, recording). + // SAFETY: a plain call on our own thread. + unsafe { + use windows::Win32::System::Threading::*; + let _ = SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_BELOW_NORMAL); + } + loop { + next().make(); + if WAITING.fetch_sub(1, Ordering::Relaxed) == 1 { + drained(); + } else { + super::library::save(false); + } + } + }); + if let Err(e) = spawned { + tracing::warn!(error = %e, "no pipeline worker"); + } else { + running = true; + } + } + running + }) +} + +/// The most pipelines waiting at once since the workers last ran out. +static PEAK: AtomicU64 = AtomicU64::new(0); + +/// The workers ran out of work: logged after a batch of 10 or more, and +/// the cache saved (at most every 20 s). +fn drained() { + use super::library::{EARLY, LOADED, MADE}; + if PEAK.swap(0, Ordering::Relaxed) >= 10 { + tracing::info!( + made = MADE.load(Ordering::Relaxed), + loaded = LOADED.load(Ordering::Relaxed), + started_early = EARLY.load(Ordering::Relaxed), + "host pipelines all made" + ); + } + super::library::save(false); +} + +#[cfg(test)] +mod tests { + use super::*; + + /// A first use queues the pipeline and, within the budget, gets the + /// worker's answer (here: no host pipeline for no shaders). + #[test] + fn first_use_is_made_by_a_worker() { + let p = Arc::new(Pending::new(Vec::new(), None)); + assert!(ready(&p).is_none()); + assert_ne!(p.queue_state.load(Ordering::Relaxed), NOT_QUEUED); + let started = Instant::now(); + while p.made.get().is_none() && started.elapsed() < Duration::from_secs(10) { + std::thread::yield_now(); + } + assert!(matches!(p.made.get(), Some(None))); + } + + #[test] + fn pending_pipeline_is_recorded_for_the_next_launch() { + let mut p = Pending::new(Vec::new(), None); + p.key = "pending-pipeline-test".to_owned(); + // Simulate a worker that has taken the job but cannot finish it yet. + p.queue_state.store(MAKING, Ordering::Relaxed); + let p = Arc::new(p); + + assert!(!super::super::library::wanted_early(&p.key)); + assert!(ready(&p).is_none()); + assert!(p.made.get().is_none()); + assert!(super::super::library::wanted_early(&p.key)); + } + + #[test] + fn draws_promote_early_pipelines_without_claiming_them_twice() { + let earlier = Arc::new(Pending::new(Vec::new(), None)); + let promoted = Arc::new(Pending::new(Vec::new(), None)); + let requested = Arc::new(Pending::new(Vec::new(), None)); + let mut queue = Queue::new(); + + assert_eq!(queue.push(&earlier, EARLY), Some(true)); + assert_eq!(queue.push(&promoted, EARLY), Some(true)); + assert_eq!(queue.push(&requested, REQUESTED), Some(true)); + assert_eq!(queue.push(&promoted, REQUESTED), Some(false)); + assert_eq!(queue.push(&promoted, REQUESTED), None); + + assert!(Arc::ptr_eq(&queue.pop().unwrap(), &requested)); + assert!(Arc::ptr_eq(&queue.pop().unwrap(), &promoted)); + assert_eq!(queue.push(&promoted, REQUESTED), None); + assert!(Arc::ptr_eq(&queue.pop().unwrap(), &earlier)); + assert!(queue.pop().is_none()); + } +} diff --git a/crates/leonida-gpu/src/plaincopy.rs b/crates/leonida-gpu/src/plaincopy.rs new file mode 100644 index 000000000..59d0f70d3 --- /dev/null +++ b/crates/leonida-gpu/src/plaincopy.rs @@ -0,0 +1,318 @@ +//! Copies of title memory made in place, by this process, with a way back +//! when a page is not there (`LEONIDA_COPY_PLAIN=1`; off by default). +//! +//! Every copy of title memory into a host buffer goes through the kernel +//! (`ReadProcessMemory` on our own process, `crate::host::copy_mapped`): +//! the title unmaps and remaps its memory while we read it, a read in +//! place of a page that is gone is an access violation, and the kernel's +//! copy fails instead. It costs what a system call that locks and probes +//! every page costs: run 225's profile has the submitting thread 35 ms a +//! frame inside `ZwReadVirtualMemory` for about 100 MB (3 GB a second), +//! where the processor's own copy moves that much in a third of the time. +//! +//! Here the copy is one `rep movsb` in a function of ours that uses no +//! stack. An exception handler, first in the line, looks at every access +//! violation: one that is a READ and happened at exactly that instruction +//! continues at the function's other exit, which returns 0, and the +//! caller falls back to the kernel's copy as before (it says which page +//! is gone and fills in zeros). A write that faults is not ours to take: +//! the destination is host memory, which is always there; such a fault +//! goes on to the handlers after this one. + +use std::sync::atomic::{AtomicU64, Ordering::Relaxed}; + +#[cfg(target_arch = "x86_64")] +core::arch::global_asm!( + ".globl leonida_copy_guarded", + ".globl leonida_copy_guarded_at", + ".globl leonida_copy_guarded_fault", + "leonida_copy_guarded:", + // rcx: to, rdx: from, r8: bytes. rsi and rdi are the caller's: kept in + // r9 and r10, which are ours to use, so nothing is on the stack. + " mov r9, rsi", + " mov r10, rdi", + " mov rdi, rcx", + " mov rsi, rdx", + " mov rcx, r8", + "leonida_copy_guarded_at:", + " rep movsb", + " mov rsi, r9", + " mov rdi, r10", + " mov eax, 1", + " ret", + "leonida_copy_guarded_fault:", + " mov rsi, r9", + " mov rdi, r10", + " xor eax, eax", + " ret", +); + +#[cfg(target_arch = "x86_64")] +unsafe extern "C" { + fn leonida_copy_guarded(to: *mut u8, from: *const u8, len: usize) -> u32; + static leonida_copy_guarded_at: u8; + static leonida_copy_guarded_fault: u8; +} + +/// Whether copies of title memory into host memory are made in place +/// (`LEONIDA_COPY_PLAIN=1`). +pub(crate) fn on() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| { + let on = cfg!(target_arch = "x86_64") && std::env::var_os("LEONIDA_COPY_PLAIN").is_some_and(|v| v == "1"); + if on { + install(); + tracing::info!( + "copies of title memory into host buffers are made in place, with the kernel's copy behind them for a \ + page that is not there (LEONIDA_COPY_PLAIN=1)" + ); + } + on + }) +} + +/// Copies made in place, their bytes, the copies that met a page that was +/// not there (and went to the kernel's copy), and the copies not tried in +/// place because their source faulted lately ([`RECENT`]) or they were +/// under [`LEAST`] bytes, since the last line. +static COUNT: [AtomicU64; 5] = [const { AtomicU64::new(0) }; 5]; + +/// The fewest bytes copied in place. A read of a byte or a word is how the +/// layer ASKS whether a page is there (a texture's first page, a record): +/// it is expected to fail, and a failed kernel read costs a microsecond +/// where a fault and its handler cost tens (run 230: 1,000 to 1,300 faults +/// a frame, nearly all of them such askings, took back most of what the +/// copies in place had won). +const LEAST: usize = 256; + +/// The 64 KiB blocks of title memory a copy in place faulted in lately: +/// their copies go straight to the kernel's, which reads round the hole. +/// By the block's number, in the place its low bits name (a later block +/// with the same low bits takes the place). Forgotten every two seconds: +/// the title maps the memory in the end. +static RECENT: [std::sync::atomic::AtomicUsize; 1024] = [const { std::sync::atomic::AtomicUsize::new(0) }; 1024]; +/// When [`RECENT`] was last emptied (milliseconds of [`now_ms`]). +static EMPTIED: AtomicU64 = AtomicU64::new(0); + +fn now_ms() -> u64 { + static START: std::sync::OnceLock = std::sync::OnceLock::new(); + START.get_or_init(std::time::Instant::now).elapsed().as_millis() as u64 +} + +/// The numbers of the first and last 64 KiB block of `[from, from + len)`, +/// never 0 (0 is an empty place). +fn blocks(from: usize, len: usize) -> (usize, usize) { + ((from >> 16) | 1 << 63, ((from + len.max(1) - 1) >> 16) | 1 << 63) +} + +/// Whether a copy from there faulted lately. +fn faulted_lately(from: usize, len: usize) -> bool { + let now = now_ms(); + let emptied = EMPTIED.load(Relaxed); + if now.saturating_sub(emptied) >= 2_000 && EMPTIED.compare_exchange(emptied, now, Relaxed, Relaxed).is_ok() { + for place in &RECENT { + place.store(0, Relaxed); + } + return false; + } + let (first, last) = blocks(from, len); + RECENT[first & 1023].load(Relaxed) == first || RECENT[last & 1023].load(Relaxed) == last +} + +/// A copy from there faulted. +fn note_fault(from: usize, len: usize) { + let (first, last) = blocks(from, len); + RECENT[first & 1023].store(first, Relaxed); + RECENT[last & 1023].store(last, Relaxed); +} + +/// The handler that turns a read fault inside [`guarded`] into its return +/// of false; put first in the line, once. +#[cfg(target_arch = "x86_64")] +fn install() { + use windows_sys::Win32::Foundation::{ + EXCEPTION_ACCESS_VIOLATION, EXCEPTION_GUARD_PAGE, EXCEPTION_IN_PAGE_ERROR, + }; + use windows_sys::Win32::System::Diagnostics::Debug::{ + AddVectoredExceptionHandler, EXCEPTION_CONTINUE_EXECUTION, EXCEPTION_CONTINUE_SEARCH, EXCEPTION_POINTERS, + }; + unsafe extern "system" fn on_fault(info: *mut EXCEPTION_POINTERS) -> i32 { + // SAFETY: the system passes the exception being dispatched and the + // context it will continue with. + let (r, context) = unsafe { (&*(*info).ExceptionRecord, &mut *(*info).ContextRecord) }; + // Only at the copy's own instruction. + if context.Rip != (&raw const leonida_copy_guarded_at) as u64 { + return EXCEPTION_CONTINUE_SEARCH; + } + const READ: usize = 0; + let read = r.NumberParameters >= 1 && r.ExceptionInformation[0] == READ; + let gone = (r.ExceptionCode == EXCEPTION_ACCESS_VIOLATION || r.ExceptionCode == EXCEPTION_IN_PAGE_ERROR) && read; + if gone || r.ExceptionCode == EXCEPTION_GUARD_PAGE { + context.Rip = (&raw const leonida_copy_guarded_fault) as u64; + return EXCEPTION_CONTINUE_EXECUTION; + } + EXCEPTION_CONTINUE_SEARCH + } + static ONCE: std::sync::Once = std::sync::Once::new(); + // SAFETY: a handler that reads the record it is given and nothing else. + ONCE.call_once(|| unsafe { + AddVectoredExceptionHandler(1, Some(on_fault)); + }); +} + +#[cfg(not(target_arch = "x86_64"))] +fn install() {} + +/// Copies `len` bytes from `from` to `to` in place; false if a page of the +/// source was not there (then some of `to` may have been written). +/// +/// `to` must be writable memory of `len` bytes that is ours (host memory); +/// `from` may be anything. +#[cfg(target_arch = "x86_64")] +fn guarded(to: *mut u8, from: *const u8, len: usize) -> bool { + install(); + // SAFETY: the destination is the caller's to write; a source page that + // is not there ends the copy with 0 instead of a fault ([`install`]). + unsafe { leonida_copy_guarded(to, from, len) != 0 } +} + +#[cfg(not(target_arch = "x86_64"))] +fn guarded(_: *mut u8, _: *const u8, _: usize) -> bool { + false +} + +/// With [`on`]: copies title memory at `from` into host memory at `to`; +/// false if it is off or a source page was not there (the caller then +/// copies through the kernel, as before). +pub(crate) fn copy(to: *mut u8, from: *const u8, len: usize) -> bool { + if !on() { + return false; + } + if len < LEAST { + COUNT[4].fetch_add(1, Relaxed); + return false; + } + if faulted_lately(from as usize, len) { + COUNT[3].fetch_add(1, Relaxed); + return false; + } + let whole = guarded(to, from, len); + if whole { + COUNT[0].fetch_add(1, Relaxed); + COUNT[1].fetch_add(len as u64, Relaxed); + } else { + COUNT[2].fetch_add(1, Relaxed); + note_fault(from as usize, len); + } + whole +} + +/// With the frame line: what [`copy`] did per frame over `frames`. +pub(crate) fn line(frames: f64) { + if !on() { + return; + } + let [copies, bytes, gone, lately, small] = [0, 1, 2, 3, 4].map(|i| COUNT[i].swap(0, Relaxed) as f64 / frames); + tracing::info!( + "copies of title memory made in place per frame (LEONIDA_COPY_PLAIN=1): {copies:.0}, {:.1} MB; {gone:.1} met a page \ + that was not there and went through the kernel's copy; left to the kernel's copy untried: {lately:.0} whose source \ + faulted in the last two seconds, {small:.0} of under {LEAST} bytes", + bytes / 1e6 + ); +} + +#[cfg(all(test, target_arch = "x86_64"))] +mod tests { + use super::*; + use windows_sys::Win32::System::Memory::{ + MEM_COMMIT, MEM_RELEASE, MEM_RESERVE, PAGE_NOACCESS, PAGE_READWRITE, VirtualAlloc, VirtualFree, + }; + + const PAGE: usize = 4096; + + #[test] + fn memory_that_is_there_is_copied() { + let from: Vec = (0..100_000u32).map(|i| (i * 7 + 3) as u8).collect(); + let mut to = vec![0u8; from.len()]; + assert!(guarded(to.as_mut_ptr(), from.as_ptr(), from.len())); + assert_eq!(to, from); + // Nothing to copy is a copy. + assert!(guarded(to.as_mut_ptr(), from.as_ptr(), 0)); + } + + /// Three pages reserved, the first committed: a copy that stays in the + /// first page is whole; one that runs into the second ends with false, + /// the bytes before the hole copied, and the thread goes on. + #[test] + fn a_page_that_is_not_there_ends_the_copy_without_a_fault() { + // SAFETY: memory of the test's own. + let base = unsafe { VirtualAlloc(std::ptr::null(), 3 * PAGE, MEM_RESERVE, PAGE_NOACCESS) } as *mut u8; + assert!(!base.is_null()); + // SAFETY: the first page of that reservation. + assert!(!unsafe { VirtualAlloc(base.cast(), PAGE, MEM_COMMIT, PAGE_READWRITE) }.is_null()); + // SAFETY: committed and writable. + unsafe { std::slice::from_raw_parts_mut(base, PAGE) }.fill(0xAB); + let mut to = vec![0u8; 2 * PAGE]; + assert!(guarded(to.as_mut_ptr(), base, PAGE)); + assert!(to[..PAGE].iter().all(|&b| b == 0xAB)); + to.fill(0); + assert!(!guarded(to.as_mut_ptr(), base.wrapping_add(PAGE / 2), PAGE)); + assert!(to[..PAGE / 2].iter().all(|&b| b == 0xAB), "the bytes before the hole"); + assert!(to[PAGE / 2..].iter().all(|&b| b == 0), "nothing after it"); + // A source that is not there at all. + assert!(!guarded(to.as_mut_ptr(), base.wrapping_add(PAGE), PAGE)); + // Committed but closed to reads. + // SAFETY: the third page of the reservation. + assert!(!unsafe { VirtualAlloc(base.wrapping_add(2 * PAGE).cast(), PAGE, MEM_COMMIT, PAGE_NOACCESS) }.is_null()); + assert!(!guarded(to.as_mut_ptr(), base.wrapping_add(2 * PAGE), 16)); + // And the registers the caller owns came back: this still works. + assert!(guarded(to.as_mut_ptr(), base, PAGE)); + assert!(to[..PAGE].iter().all(|&b| b == 0xAB)); + // SAFETY: the test's reservation. + unsafe { VirtualFree(base.cast(), 0, MEM_RELEASE) }; + } + + /// A source that faulted is remembered by its 64 KiB blocks, and only + /// those. + #[test] + fn a_source_that_faulted_is_remembered_by_its_blocks() { + // (Addresses no other test uses; the table is shared.) + let at = 0x7654_3210_0000usize; + assert!(!faulted_lately(at, 4096)); + note_fault(at + 100, 4096); + assert!(faulted_lately(at, 16)); + assert!(faulted_lately(at + 0xffff, 1)); + // A copy that ends in the block, and one that begins in it. + assert!(faulted_lately(at - 4096, 8192)); + // The blocks beside it are not remembered. + assert!(!faulted_lately(at + 0x10000, 4096)); + assert!(!faulted_lately(at - 0x10000, 4096)); + assert_eq!(blocks(0, 0), (1 << 63, 1 << 63)); + } + + /// Many threads at once, half of them faulting: each gets its own answer. + #[test] + fn threads_fault_and_copy_side_by_side() { + // SAFETY: memory of the test's own. + let base = unsafe { VirtualAlloc(std::ptr::null(), 2 * PAGE, MEM_RESERVE, PAGE_NOACCESS) } as usize; + assert_ne!(base, 0); + // SAFETY: the first page of that reservation. + assert!(!unsafe { VirtualAlloc(base as *const _, PAGE, MEM_COMMIT, PAGE_READWRITE) }.is_null()); + let threads: Vec<_> = (0..8) + .map(|t| { + std::thread::spawn(move || { + let mut to = vec![0u8; PAGE]; + for _ in 0..2_000 { + let from = (base + if t % 2 == 0 { 0 } else { PAGE }) as *const u8; + assert_eq!(guarded(to.as_mut_ptr(), from, PAGE), t % 2 == 0); + } + }) + }) + .collect(); + for t in threads { + t.join().unwrap(); + } + // SAFETY: the test's reservation. + unsafe { VirtualFree(base as *mut _, 0, MEM_RELEASE) }; + } +} diff --git a/crates/leonida-gpu/src/primitive.rs b/crates/leonida-gpu/src/primitive.rs new file mode 100644 index 000000000..3c5a76bdc --- /dev/null +++ b/crates/leonida-gpu/src/primitive.rs @@ -0,0 +1,237 @@ +//! Console primitive types the host lacks. A rectangle list gives three +//! corners per rectangle, the second the one between the other two, and +//! the hardware adds the fourth at `v0 + v2 - v1` (the title's +//! full-screen rectangles come as top left, bottom left, bottom right); on +//! the host each rectangle becomes two triangles, with the fourth vertex +//! made from the other three on the CPU. +//! +//! shortcut: the fourth vertex is computed from vertex inputs, not from +//! vertex shader outputs as the hardware does; that is the same for vertex +//! shaders linear in their inputs (blits, 2D quads). Inputs in formats +//! [`components`] does not know keep the first vertex's value, and so do +//! components past the end of the vertex (an element that reaches into the +//! next one, which the layout allows). +//! +//! A pipeline the title makes for rectangles completes them on the GPU +//! instead, in a geometry stage (`leonida_shader::emit::rect_list_gs`): +//! from the vertex shader's outputs, whichever vertex the corner is, for +//! direct, indexed and indirect draws alike. This expansion is what is +//! left for a pipeline that could not get that stage. + +/// Expands `rects` rectangles of `stride`-byte vertices from `src` into six +/// vertices each in `dst`: `(v0, v1, v2)` and `(v0, v2, v3)`, so both +/// triangles turn the same way. `elements` are (byte offset, format). +pub(crate) fn expand_rects(src: &[u8], dst: &mut [u8], stride: usize, elements: &[(u32, u32)]) { + for (rect, out) in src + .chunks_exact(3 * stride) + .zip(dst.chunks_exact_mut(6 * stride)) + { + let v = |i: usize| &rect[i * stride..(i + 1) * stride]; + for (slot, i) in [0, 1, 2, 0, 2].into_iter().enumerate() { + out[slot * stride..(slot + 1) * stride].copy_from_slice(v(i)); + } + let fourth = &mut out[5 * stride..]; + fourth.copy_from_slice(v(0)); + for &(offset, format) in elements { + let at = offset as usize; + let Some((n, kind)) = components(format) else { + continue; + }; + // Only the components inside the vertex: the rest belong to the + // next one. + let inside = stride.saturating_sub(at) / kind.bytes(); + for c in 0..n.min(inside) { + let get = |i: usize| kind.read(&v(i)[at..], c); + let value = get(0) + get(2) - get(1); + kind.write(&mut fourth[at..], c, value); + } + } + } +} + +#[derive(Clone, Copy)] +enum Kind { + F32, + F16, + Unorm8, + Unorm16, +} + +/// Component count and kind of the vertex formats rectangles use. +fn components(format: u32) -> Option<(usize, Kind)> { + Some(match format { + 2 => (4, Kind::F32), + 6 => (3, Kind::F32), + 16 => (2, Kind::F32), + 41 => (1, Kind::F32), + 10 => (4, Kind::F16), + 34 => (2, Kind::F16), + 54 => (1, Kind::F16), + 11 => (4, Kind::Unorm16), + 35 => (2, Kind::Unorm16), + 28 | 29 | 87 | 91 => (4, Kind::Unorm8), + _ => return None, + }) +} + +impl Kind { + fn bytes(self) -> usize { + match self { + Kind::F32 => 4, + Kind::F16 | Kind::Unorm16 => 2, + Kind::Unorm8 => 1, + } + } + + fn read(self, at: &[u8], c: usize) -> f32 { + let b = &at[c * self.bytes()..]; + match self { + Kind::F32 => f32::from_le_bytes([b[0], b[1], b[2], b[3]]), + Kind::F16 => half_to_f32(u16::from_le_bytes([b[0], b[1]])), + Kind::Unorm16 => f32::from(u16::from_le_bytes([b[0], b[1]])) / 65535.0, + Kind::Unorm8 => f32::from(b[0]) / 255.0, + } + } + + fn write(self, at: &mut [u8], c: usize, v: f32) { + let n = self.bytes(); + let b = &mut at[c * n..(c + 1) * n]; + match self { + Kind::F32 => b.copy_from_slice(&v.to_le_bytes()), + Kind::F16 => b.copy_from_slice(&f32_to_half(v).to_le_bytes()), + Kind::Unorm16 => { + b.copy_from_slice(&((v.clamp(0.0, 1.0) * 65535.0).round() as u16).to_le_bytes()) + } + Kind::Unorm8 => b[0] = (v.clamp(0.0, 1.0) * 255.0).round() as u8, + } + } +} + +fn half_to_f32(h: u16) -> f32 { + let sign = u32::from(h >> 15) << 31; + let exp = u32::from((h >> 10) & 0x1f); + let man = u32::from(h & 0x3ff); + let bits = match (exp, man) { + (0, 0) => sign, + // Subnormal: scale the mantissa. + (0, m) => { + let v = m as f32 * 2f32.powi(-24); + return if sign != 0 { -v } else { v }; + } + (31, m) => sign | 0x7f80_0000 | m << 13, + (e, m) => sign | (e + 112) << 23 | m << 13, + }; + f32::from_bits(bits) +} + +fn f32_to_half(v: f32) -> u16 { + let bits = v.to_bits(); + let sign = ((bits >> 16) & 0x8000) as u16; + let exp = ((bits >> 23) & 0xff) as i32 - 127 + 15; + let man = bits & 0x7f_ffff; + if exp >= 31 { + return sign | 0x7c00; // too large: infinity + } + if exp <= 0 { + if exp < -10 { + return sign; // below half the smallest subnormal: zero + } + // Half subnormals are `m * 2^-24`. An f32 in this range is still + // normal (exponent field >= 1), so its significand has the implicit + // leading 1; shift it into the half mantissa, rounding to even. + let sig = (1u32 << 23) | man; + let shift = (14 - exp) as u32; + let halfway = 1u32 << (shift - 1); + let q = sig >> shift; + let r = sig & ((1u32 << shift) - 1); + let m = q + u32::from(r > halfway || (r == halfway && (q & 1) != 0)); + return sign | m as u16; + } + // Rounded to nearest: a carry out of the mantissa is added into the + // exponent (`2 - 2^-12` is 2.0); at most it reaches infinity, 0x7c00. + let half = (exp as u32) << 10; + sign | (half + ((man + 0x1000) >> 13)) as u16 +} + +#[cfg(test)] +mod tests { + use super::*; + + /// A rectangle of float2 positions and RGBA8 colors, given as top + /// left, bottom left, bottom right: the fourth corner completes the + /// parallelogram at the top right. + #[test] + fn rectangles_get_their_fourth_corner() { + let vertex = |x: f32, y: f32, r: u8| { + let mut v = Vec::new(); + v.extend(x.to_le_bytes()); + v.extend(y.to_le_bytes()); + v.extend([r, 0, 0, 255]); + v + }; + let src: Vec = [ + vertex(-1.0, 1.0, 0), + vertex(-1.0, -1.0, 100), + vertex(1.0, -1.0, 150), + ] + .concat(); + let mut dst = vec![0u8; 6 * 12]; + expand_rects(&src, &mut dst, 12, &[(0, 16), (8, 28)]); + assert_eq!(dst[..36], src[..]); + assert_eq!(dst[36..48], src[..12]); + assert_eq!(dst[48..60], src[24..36]); + assert_eq!(dst[60..], vertex(1.0, 1.0, 50)[..]); + assert_eq!(f32_to_half(1.5), 0x3e00); + assert_eq!(half_to_f32(0x3e00), 1.5); + assert_eq!(half_to_f32(0xc000), -2.0); + } + + /// A rounding that carries out of the mantissa raises the exponent + /// (the carry used to be or-ed into an odd exponent, halving the value). + #[test] + fn halves_round_up_into_the_next_power_of_two() { + assert_eq!(f32_to_half(2.0 - 2f32.powi(-12)), 0x4000); + assert_eq!(f32_to_half(0.5 - 2f32.powi(-13)), 0x3800); + assert_eq!(f32_to_half(65520.0), 0x7c00, "past the largest half"); + // An R16_FLOAT element at 1.0, 2^-12 and 1.0: the fourth corner is + // 2 - 2^-12, which rounds to 2.0. + let src: Vec = [0x3c00_u16, 0x0c00, 0x3c00] + .iter() + .flat_map(|h| h.to_le_bytes()) + .collect(); + let mut dst = vec![0u8; 6 * 2]; + expand_rects(&src, &mut dst, 2, &[(0, 54)]); + assert_eq!(dst[10..], 0x4000_u16.to_le_bytes()); + } + + /// An element that reaches past the stride (float4 at 4 in 8-byte + /// vertices, RGBA8 at the stride itself): the components inside get + /// the fourth corner, the rest keep the first vertex's bytes. The old + /// code indexed past the vertex and panicked. + #[test] + fn elements_past_the_stride_are_left_alone() { + let vertex = |x: f32, y: f32| [x.to_le_bytes(), y.to_le_bytes()].concat(); + let src = [vertex(0.0, 2.0), vertex(1.0, 3.0), vertex(5.0, 7.0)].concat(); + let mut dst = vec![0u8; 6 * 8]; + expand_rects(&src, &mut dst, 8, &[(0, 16), (4, 2), (8, 28)]); + assert_eq!(dst[..40], [&src[..], &src[..8], &src[16..]].concat()[..]); + assert_eq!(dst[40..], vertex(4.0, 6.0)[..]); + } + + /// `half_to_f32` reads subnormals, so an f16 rectangle output must be + /// able to write them back instead of flushing every one to zero. + #[test] + fn half_subnormals_convert_in_both_directions() { + assert_eq!(f32_to_half(2f32.powi(-24)), 0x0001); + assert_eq!(f32_to_half(-2f32.powi(-24)), 0x8001); + assert_eq!(f32_to_half(2f32.powi(-23)), 0x0002); + assert_eq!(f32_to_half(1023.0 * 2f32.powi(-24)), 0x03ff); + // Ties go to an even mantissa: 0/1 and 1/2. + assert_eq!(f32_to_half(2f32.powi(-25)), 0x0000); + assert_eq!(f32_to_half(3.0 * 2f32.powi(-25)), 0x0002); + // Below half the smallest subnormal, and normal values, are unchanged. + assert_eq!(f32_to_half(2f32.powi(-26)), 0x0000); + assert_eq!(f32_to_half(1.5), 0x3e00); + assert_eq!(half_to_f32(0x0001), 2f32.powi(-24)); + } +} diff --git a/crates/leonida-gpu/src/profile.rs b/crates/leonida-gpu/src/profile.rs new file mode 100644 index 000000000..58847c86b --- /dev/null +++ b/crates/leonida-gpu/src/profile.rs @@ -0,0 +1,2961 @@ +//! Where the layer's threads spend their time: a sampling profiler +//! (`LEONIDA_PROFILE=1`, diagnostics builds; off otherwise). +//! +//! The log's own counters say how long the phases of a frame take, not +//! what a thread does inside them: in the graphics driver, in a kernel +//! call, waiting for a lock. A thread of ours ([`run`]) looks, a thousand +//! times a second (`LEONIDA_PROFILE_HZ`), at the threads that matter: +//! +//! * the submitting thread and the recording threads, which name +//! themselves by what they call ([`seen`]: [`crate::host::Host`]'s +//! submissions, the list calls); +//! * our workers, by the names we start them with (`leonida-pipelines-N`, +//! `leonida-wide-N`, `leonida-late-wait`) and the title's main thread; +//! * the busiest of the other threads (the title's own). +//! +//! A look ([`Sampler::capture`]) suspends the thread, reads its registers +//! and copies the used part of its stack with the kernel's own read, and +//! lets it go: between the two nothing of ours takes a lock, allocates or +//! reads memory that may be gone. The stack is walked afterwards, in the +//! copy ([`Sampler::walk`]), by each image's unwind data (the Windows +//! loader registered it for title images too), every read checked to stay +//! inside the copy. A thread that has used no processor cycles since the +//! last look is where it was: it is not suspended again. +//! +//! Names are found when the report is written, not when a sample is +//! taken ([`Symbols`]): our executable through its PDB (inlined calls +//! too), system and driver code by export or `module+offset`, title code +//! as `title+offset` of the function's start. +//! +//! The report is written every `LEONIDA_PROFILE_EVERY` seconds (30) and at +//! exit to `LEONIDA_PROFILE_OUT` (`%TEMP%\leonida_profile_.txt`), the +//! stacks for a flame graph beside it (`.folded`). Per kind of thread: +//! time by module, by function (own and with what it calls), where it +//! waited and for which of our functions, the hottest lines of ours. Times +//! are milliseconds per presented frame ([`frame`]). + +use std::cell::Cell; +use std::collections::HashMap; +use std::ffi::c_void; +use std::fmt::Write as _; +use std::hash::{BuildHasherDefault, Hasher}; +use std::path::PathBuf; +use std::ptr::{null, null_mut}; +use std::sync::atomic::{AtomicBool, AtomicU8, AtomicU32, AtomicU64, Ordering::Relaxed}; +use std::time::{Duration, Instant}; + +use windows_sys::Win32::Foundation::{ + CloseHandle, DUPLICATE_SAME_ACCESS, DuplicateHandle, HANDLE, HMODULE, LocalFree, +}; +use windows_sys::Win32::System::Diagnostics::Debug::{ + CONTEXT, CONTEXT_CONTROL_AMD64, CONTEXT_INTEGER_AMD64, GetThreadContext, IMAGEHLP_LINEW64, + IMAGEHLP_MODULEW64, ReadProcessMemory, RtlLookupFunctionEntry, RtlVirtualUnwind, SYMBOL_INFOW, + UNW_FLAG_NHANDLER, +}; +use windows_sys::Win32::System::LibraryLoader::{ + GetModuleFileNameW, GetModuleHandleW, GetProcAddress, LOAD_LIBRARY_SEARCH_SYSTEM32, + LoadLibraryExA, +}; +use windows_sys::Win32::System::Memory::{MEM_COMMIT, MEM_RESERVE, PAGE_READWRITE, VirtualAlloc}; +use windows_sys::Win32::System::ProcessStatus::{ + K32EnumProcessModules, K32GetModuleInformation, MODULEINFO, +}; +use windows_sys::Win32::System::Threading::{ + GetCurrentProcess, GetCurrentThread, GetCurrentThreadId, GetThreadDescription, GetThreadId, + GetThreadTimes, OpenThread, ResumeThread, SetThreadPriority, SuspendThread, THREAD_GET_CONTEXT, + THREAD_PRIORITY_TIME_CRITICAL, THREAD_QUERY_INFORMATION, THREAD_QUERY_LIMITED_INFORMATION, + THREAD_SUSPEND_RESUME, WaitForSingleObject, +}; + +#[link(name = "kernel32", kind = "raw-dylib")] +unsafe extern "system" { + /// The processor cycles a thread has used so far. + fn QueryThreadCycleTime(thread: HANDLE, cycles: *mut u64) -> i32; +} + +#[link(name = "ntdll", kind = "raw-dylib")] +unsafe extern "system" { + /// The thread of `process` after `thread` (null: the first), opened + /// with `access`; an NTSTATUS, not zero after the last. + fn NtGetNextThread( + process: HANDLE, + thread: HANDLE, + access: u32, + attributes: u32, + flags: u32, + next: *mut HANDLE, + ) -> i32; + /// `(thread, class, out, size, written)`: an NTSTATUS. + fn NtQueryInformationThread( + thread: HANDLE, + class: i32, + information: *mut c_void, + size: u32, + written: *mut u32, + ) -> i32; +} + +// --------------------------------------------------------------------- +// What the layer's threads tell the profiler. +// --------------------------------------------------------------------- + +/// 0: not asked yet, [`OFF`], [`ON`]. +static STATE: AtomicU8 = AtomicU8::new(0); +const OFF: u8 = 1; +const ON: u8 = 2; + +/// Frames presented since the profiler started. +static FRAMES: AtomicU64 = AtomicU64::new(0); + +/// What a thread was seen doing. +#[derive(Clone, Copy)] +pub(crate) enum Seen { + /// It called a submission ([`crate::host::Host`]). + Submit = 0, + /// It made a list call. + Record = 1, +} + +/// A thread that called [`seen`], and how often for each [`Seen`]. A line +/// of the cache each: the recording threads count here at every list call. +#[repr(align(64))] +struct Known { + thread: AtomicU32, + seen: [AtomicU64; 2], +} + +const KNOWN: usize = 64; +static KNOWN_THREADS: [Known; KNOWN] = [const { + Known { + thread: AtomicU32::new(0), + seen: [const { AtomicU64::new(0) }; 2], + } +}; KNOWN]; + +/// Submissions after which a thread is a submitting thread, and list calls +/// after which it is a recording thread: a thread that reads a texture +/// back once while the world loads is neither. +const SUBMITS: u64 = 8; +const LIST_CALLS: u64 = 64; + +thread_local! { + /// This thread's place in [`KNOWN_THREADS`], plus one; 0 before it has + /// one, 255 if there was none left. + static MINE: Cell = const { Cell::new(0) }; +} + +/// Whether the profiler runs; the first call reads `LEONIDA_PROFILE` and +/// starts it. +#[inline] +fn on() -> bool { + match STATE.load(Relaxed) { + ON => true, + OFF => false, + _ => decide(), + } +} + +#[cold] +fn decide() -> bool { + static ONCE: std::sync::Once = std::sync::Once::new(); + ONCE.call_once(|| { + let started = Config::from_env().is_some_and(start); + let state = if started { ON } else { OFF }; + STATE.store(state, Relaxed); + }); + STATE.load(Relaxed) == ON +} + +/// The calling thread was seen doing `what`: it is followed once it has +/// done so often enough. Costs a load when the profiler is off. +#[inline] +pub(crate) fn seen(what: Seen) { + if !on() { + return; + } + let mine = MINE.with(Cell::get); + let known = match mine { + 0 => match claim() { + Some(known) => known, + None => return, + }, + 255 => return, + at => &KNOWN_THREADS[usize::from(at) - 1], + }; + known.seen[what as usize].fetch_add(1, Relaxed); +} + +/// A place in [`KNOWN_THREADS`] for the calling thread. +#[cold] +fn claim() -> Option<&'static Known> { + // SAFETY: a plain query. + let id = unsafe { GetCurrentThreadId() }; + for (at, known) in KNOWN_THREADS.iter().enumerate() { + if known + .thread + .compare_exchange(0, id, Relaxed, Relaxed) + .is_ok() + { + known.seen[0].store(0, Relaxed); + known.seen[1].store(0, Relaxed); + MINE.with(|m| m.set(at as u8 + 1)); + return Some(known); + } + } + MINE.with(|m| m.set(255)); + None +} + +/// A frame was presented. +#[inline] +pub(crate) fn frame() { + if on() { + FRAMES.fetch_add(1, Relaxed); + } +} + +// --------------------------------------------------------------------- +// The switches. +// --------------------------------------------------------------------- + +/// The kinds of thread followed. +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +pub(crate) enum Role { + Submit, + Record, + Late, + Wide, + Pipelines, + TitleMain, + Busy, +} + +impl Role { + const ALL: [Role; 7] = [ + Role::Submit, + Role::Record, + Role::Late, + Role::Wide, + Role::Pipelines, + Role::TitleMain, + Role::Busy, + ]; + + /// As `LEONIDA_PROFILE_THREADS` and the stacks file name it. + fn name(self) -> &'static str { + match self { + Role::Submit => "submit", + Role::Record => "record", + Role::Late => "late-wait", + Role::Wide => "wide", + Role::Pipelines => "pipelines", + Role::TitleMain => "title-main", + Role::Busy => "busy", + } + } + + fn says(self) -> &'static str { + match self { + Role::Submit => "SUBMITTING (threads that send lists to the card: Host::submit)", + Role::Record => "RECORDING (threads that make list calls and do not submit)", + Role::Late => "LATE WAIT (leonida-late-wait: settles submissions sent ahead)", + Role::Wide => "WIDE WORKERS (leonida-wide-N: copies and compares of title memory)", + Role::Pipelines => "PIPELINE WORKERS (leonida-pipelines-N)", + Role::TitleMain => "TITLE MAIN (title-main)", + Role::Busy => "OTHER BUSY THREADS (the busiest threads with none of the roles above)", + } + } + + /// The role of a thread we named. + fn of_name(name: &str) -> Option { + if name.starts_with("leonida-pipelines-") { + Some(Role::Pipelines) + } else if name.starts_with("leonida-wide-") { + Some(Role::Wide) + } else if name == "leonida-late-wait" { + Some(Role::Late) + } else if name == "title-main" { + Some(Role::TitleMain) + } else { + None + } + } +} + +/// Frames kept of a stack at most (`LEONIDA_PROFILE_DEPTH` asks for fewer). +const MAX_DEPTH: usize = 96; + +#[derive(Clone)] +struct Config { + /// Looks per second. + hz: u32, + /// The report. + out: PathBuf, + /// Seconds between reports. + every: f64, + /// Seconds before the first look, and after how many more the last. + after: f64, + length: Option, + /// Frames kept of a stack, from the innermost. + depth: usize, + /// Bytes copied of a stack at most. + stack: usize, + /// Threads followed at most, and of those the busy ones with no role. + most: usize, + busy: usize, + /// The roles followed, by `Role as usize`. + roles: [bool; 7], + /// Whether calls the compiler inlined are shown as frames of their own. + inline: bool, + /// Whether a thread that used no cycles since the last look is taken + /// to be where it was. + reuse: bool, + /// The share of a thread's time it may stand still for our looks + /// (0: no limit): a thread whose looks cost more is looked at less + /// often. + budget: f64, + /// Microseconds a tick is put off by at most, a different time each + /// tick ([`Pace::wait`]). + jitter: u64, +} + +fn env_number(name: &str) -> Option { + std::env::var(name).ok()?.trim().parse().ok() +} + +impl Config { + fn new(hz: u32, out: PathBuf) -> Config { + Config { + hz, + out, + every: 30.0, + after: 0.0, + length: None, + depth: 48, + stack: 128 << 10, + most: 24, + busy: 6, + roles: [true; 7], + inline: true, + reuse: true, + budget: 0.03, + jitter: 250, + } + } + + /// `LEONIDA_PROFILE=1` and the switches beside it; `None` without it. + fn from_env() -> Option { + if !std::env::var_os("LEONIDA_PROFILE").is_some_and(|v| v == "1") { + return None; + } + let out = std::env::var_os("LEONIDA_PROFILE_OUT").map_or_else( + || std::env::temp_dir().join(format!("leonida_profile_{}.txt", std::process::id())), + PathBuf::from, + ); + let hz = env_number("LEONIDA_PROFILE_HZ").map_or(1000.0, |v| v.clamp(1.0, 4000.0)); + let mut config = Config::new(hz as u32, out); + let seconds = |name: &str, least: f64| env_number(name).map(|v| v.max(least)); + config.every = seconds("LEONIDA_PROFILE_EVERY", 1.0).unwrap_or(config.every); + config.after = seconds("LEONIDA_PROFILE_AFTER", 0.0).unwrap_or(0.0); + config.length = seconds("LEONIDA_PROFILE_FOR", 1.0); + let count = |name: &str, usual: usize, most: usize| { + env_number(name).map_or(usual, |v| (v.max(0.0) as usize).min(most)) + }; + config.depth = count("LEONIDA_PROFILE_DEPTH", config.depth, MAX_DEPTH).max(4); + config.stack = count("LEONIDA_PROFILE_STACK_KB", 128, 1024).max(4) << 10; + config.most = count("LEONIDA_PROFILE_MAX_THREADS", config.most, 64).max(1); + config.busy = count("LEONIDA_PROFILE_BUSY", config.busy, 32); + config.inline = std::env::var_os("LEONIDA_PROFILE_INLINE").is_none_or(|v| v != "0"); + config.reuse = std::env::var_os("LEONIDA_PROFILE_REUSE").is_none_or(|v| v != "0"); + config.budget = env_number("LEONIDA_PROFILE_BUDGET") + .map_or(config.budget, |v| v.clamp(0.0, 100.0) / 100.0); + config.jitter = count("LEONIDA_PROFILE_JITTER_US", 250, 2000) as u64; + if let Ok(list) = std::env::var("LEONIDA_PROFILE_THREADS") { + let named: Vec<&str> = list.split(',').map(str::trim).collect(); + for role in Role::ALL { + config.roles[role as usize] = named.contains(&role.name()); + } + } + Some(config) + } +} + +// --------------------------------------------------------------------- +// Samples: a tree of calls per thread. +// --------------------------------------------------------------------- + +/// A hash for small keys of ours (addresses and indices), not for +/// anything a stranger chooses. +#[derive(Default, Clone, Copy)] +struct Fast(u64); + +impl Hasher for Fast { + fn write(&mut self, bytes: &[u8]) { + for &b in bytes { + self.write_u64(u64::from(b)); + } + } + fn write_u8(&mut self, v: u8) { + self.write_u64(u64::from(v)); + } + fn write_u32(&mut self, v: u32) { + self.write_u64(u64::from(v)); + } + fn write_u64(&mut self, v: u64) { + self.0 = (self.0.rotate_left(5) ^ v).wrapping_mul(0x517c_c1b7_2722_0a95); + } + fn write_usize(&mut self, v: usize) { + self.write_u64(v as u64); + } + fn finish(&self) -> u64 { + self.0 + } +} + +type FastMap = HashMap>; + +/// A frame as called from its parent's: `address` is the instruction the +/// thread was at (an innermost frame) or a byte inside the call that has +/// not returned (the others), so both lie in the function they belong to. +struct Node { + parent: u32, + address: u64, + /// Of the samples that ended here: microseconds of wall clock they + /// stand for, microseconds of those the thread was on a processor (by + /// its cycle counter), and how many they were. + wall: u64, + cpu: u64, + hits: u32, +} + +/// The address of the node that stands for the frames not kept, between +/// the thread's first frame and the outermost one kept. +const CUT: u64 = 1; +/// The address of the node samples go to once the trees are full. +const FULL: u64 = 2; + +/// The calls of one thread, each sample at the node of its innermost frame. +struct Tree { + nodes: Vec, + children: FastMap<(u32, u64), u32>, +} + +impl Tree { + fn new() -> Tree { + Tree { + nodes: vec![Node { + parent: 0, + address: 0, + wall: 0, + cpu: 0, + hits: 0, + }], + children: FastMap::default(), + } + } + + fn child(&mut self, parent: u32, address: u64) -> u32 { + *self.children.entry((parent, address)).or_insert_with(|| { + self.nodes.push(Node { + parent, + address, + wall: 0, + cpu: 0, + hits: 0, + }); + self.nodes.len() as u32 - 1 + }) + } + + /// The node of a stack, `frames` from the innermost; `whole` if they + /// reach the thread's first frame. With `room` false no node is made: + /// what is new goes to the [`FULL`] node. + fn place(&mut self, frames: &[u64], whole: bool, room: bool) -> u32 { + let mut at = 0; + if !whole { + at = self.child(0, CUT); + } + for &address in frames.iter().rev() { + at = match self.children.get(&(at, address)) { + Some(&next) => next, + None if room => self.child(at, address), + None => return self.child(0, FULL), + }; + } + at + } +} + +/// The trees' nodes together, at most (56 bytes each with their index). +const MOST_NODES: usize = 1_500_000; + +// --------------------------------------------------------------------- +// Looking at a thread. +// --------------------------------------------------------------------- + +/// `GetThreadContext` and `RtlVirtualUnwind` want the context 16-byte +/// aligned, and windows-sys declares it without that alignment. +#[repr(C, align(16))] +struct Aligned(CONTEXT); + +/// Zeroed bytes kept after the room for a stack's copy: what a frame's +/// unwinding reads past the copied part (a frame cut by the limit, a +/// return address that was none) is read from here. +const SLACK: usize = 2 << 20; +/// Copied of a stack that is not the thread's own (a fiber's) at most. +const FOREIGN: usize = 32 << 10; +/// What a thread needs open for [`Sampler::capture`], and to be asked +/// whether it has ended (`SYNCHRONIZE`). +const ACCESS: u32 = + THREAD_SUSPEND_RESUME | THREAD_GET_CONTEXT | THREAD_QUERY_INFORMATION | 0x0010_0000; +/// Microseconds of processor time a waiting thread is taken to use at +/// most for being suspended and resumed (the kernel wakes it for both): +/// about 6 were measured. A thread that used no more since a look that +/// suspended it has not left its wait. +const SETTLING_US: f64 = 30.0; +/// The share of a suspension, as we time it (from asking for it to having +/// let go), that the thread really stands still: the rest is the kernel +/// reaching the thread and returning to us. Measured with threads whose +/// work is counted, eight of them always running: about 20 us of work +/// lost a look (1.8 to 2.1 % at 960 looks a second) for 25 to 28 us held. +const STOOD: f64 = 0.8; +/// A suspension counted as no longer than this in a thread's running +/// average (nanoseconds): the long ones are a thread that was not on a +/// processor when we asked, which costs it nothing. +const COST_MOST: f64 = 250_000.0; + +struct Thread { + id: u32, + handle: HANDLE, + name: String, + /// Where it started: what a thread without a name is told by. + start: u64, + role: Role, + /// Its stack's reservation: a stack pointer inside is the thread's own. + low: usize, + high: usize, + /// Its cycle counter at the last look, the node of that look, and + /// whether the thread was suspended for it. + cycles: u64, + last: Option, + stood: bool, + /// It is looked at every `every` ticks ([`Config::budget`]), next in + /// `turn` ticks; `owed` is the time since its last look + /// (microseconds), `cost` what a suspension of it takes (nanoseconds, + /// a running average). + every: u32, + turn: u32, + owed: u64, + cost: f64, + /// Bytes of its stack copied at a look; 0: all of it. Less once a + /// walk has shown how many the kept frames take. + want: usize, + tree: Tree, + /// Still running, as of the last [`Sampler::rescan`]. + alive: bool, + round: u64, + /// Looks: all, those answered without suspending it, those that + /// failed, and those whose stack did not reach its first frame. + looks: u64, + reused: u64, + missed: u64, + cut: u64, +} + +/// A thread with no role, watched for how busy it is. +struct Other { + handle: HANDLE, + cycles: u64, + name: String, + round: u64, +} + +struct Sampler { + config: Config, + me: u32, + threads: Vec, + others: FastMap, + round: u64, + scanned: Instant, + context: Box, + /// The copy of a stack: `config.stack + 16` bytes, then [`SLACK`]. + copy: *mut u8, + room: usize, + /// How far the copy has bytes that are not zero. + dirty: usize, + frames: [u64; MAX_DEPTH], + /// Cycles of the processor's counter per microsecond. + cycles_per_us: f64, + /// The cycles a waiting thread uses at most to be suspended and let + /// go again ([`SETTLING_US`]). + settling: u64, + clock: Instant, + /// The count of frames presented ([`FRAMES`]; a test's own). + presents: &'static AtomicU64, + /// The last tick, on `clock`, and the frame count then. + last: Duration, + frames_then: u64, + /// Since the start: ticks, late ones, microseconds they stand for, + /// frames presented meanwhile. + ticks: u64, + late: u64, + wall: u64, + presented: u64, + /// Suspensions: how many, their time together and the longest + /// (nanoseconds), and how many by length ([`held_class`]). + held: u64, + held_ns: u64, + held_longest: u64, + held_by: [u64; 256], + nodes: usize, + symbols: Option, +} + +impl Sampler { + fn new(config: Config) -> Sampler { + let room = config.stack + 16 + SLACK; + // SAFETY: fresh zeroed memory of ours, kept for the process's life. + let copy = unsafe { VirtualAlloc(null(), room, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE) }; + assert!(!copy.is_null(), "no memory for the profiler's stack copy"); + let clock = Instant::now(); + let cycles_per_us = cycles_per_us(); + // SAFETY: a zeroed CONTEXT is valid. + let context = Box::new(Aligned(unsafe { std::mem::zeroed() })); + Sampler { + config, + // SAFETY: a plain query. + me: unsafe { GetCurrentThreadId() }, + threads: Vec::new(), + others: FastMap::default(), + round: 0, + scanned: clock, + context, + copy: copy.cast(), + room, + dirty: 0, + frames: [0; MAX_DEPTH], + cycles_per_us, + settling: (SETTLING_US * cycles_per_us) as u64, + clock, + presents: &FRAMES, + last: clock.elapsed(), + frames_then: FRAMES.load(Relaxed), + ticks: 0, + late: 0, + wall: 0, + presented: 0, + held: 0, + held_ns: 0, + held_longest: 0, + held_by: [0; 256], + nodes: 0, + symbols: None, + } + } + + /// The time under which `share` of the suspensions stayed, in + /// microseconds (to a quarter of a power of two). + fn held_within(&self, share: f64) -> f64 { + let mut left = (self.held as f64 * share) as u64; + for (class, &count) in self.held_by.iter().enumerate() { + if count > left { + // The class's upper end: its lower end as [`held_class`] + // gives it, plus its width. + let (bits, quarter) = (class / 4, class as u64 % 4); + let under = if bits < 2 { + class as u64 + 1 + } else { + (5 + quarter) << (bits - 2) + }; + return under as f64 / 1000.0; + } + left -= count; + } + self.held_longest as f64 / 1000.0 + } + + /// Time that passed while the sampler did something else (a report) is + /// nobody's: the next tick counts from now. + fn resync(&mut self) { + self.last = self.clock.elapsed(); + self.frames_then = self.presents.load(Relaxed); + } + + /// One look at every followed thread. + fn tick(&mut self) { + let now = self.clock.elapsed(); + let passed = now.saturating_sub(self.last).as_micros() as u64; + self.last = now; + let period = 1_000_000 / u64::from(self.config.hz.max(1)); + // A stall of ours is not the threads' time. + let weight = passed.min(20 * period); + self.late += u64::from(passed > 2 * period); + let frames = self.presents.load(Relaxed); + self.presented += frames.saturating_sub(self.frames_then); + self.frames_then = frames; + self.wall += weight; + self.ticks += 1; + for at in 0..self.threads.len() { + let thread = &mut self.threads[at]; + if !thread.alive { + continue; + } + // A thread looked at every few ticks: its look stands for all + // the time since its last one. + thread.owed += weight; + thread.turn = thread.turn.saturating_sub(1); + if thread.turn == 0 { + thread.turn = thread.every; + let weight = std::mem::take(&mut thread.owed); + self.look(at, weight); + } + } + } + + fn look(&mut self, at: usize, weight: u64) { + let reuse = self.config.reuse; + let thread = &mut self.threads[at]; + thread.looks += 1; + let mut cycles = 0; + // SAFETY: a thread handle of ours and a valid out pointer. + if unsafe { QueryThreadCycleTime(thread.handle, &mut cycles) } == 0 { + thread.missed += 1; + return; + } + let ran = cycles.saturating_sub(thread.cycles); + thread.cycles = cycles; + // It has not run since the last look: it is where it was. A + // thread that was suspended for that look ran to be suspended and + // let go, which is not running its own code. + let still = ran == 0 || thread.stood && ran <= self.settling; + let last = thread.last; + let node = match last { + Some(node) if still && reuse => { + thread.reused += 1; + thread.stood = false; + node + } + _ => { + let Some((got, held)) = self.capture(at) else { + self.threads[at].missed += 1; + self.threads[at].last = None; + return; + }; + let (frames, whole, used) = self.walk(at, got); + let room = self.nodes < MOST_NODES; + let (hz, budget) = (f64::from(self.config.hz), self.config.budget); + let deep = frames >= self.config.depth.min(MAX_DEPTH); + let thread = &mut self.threads[at]; + thread.stood = true; + // The kept frames took `used` bytes: that and a quarter more + // next time. A walk that ran out of copy first: all again. + thread.want = if deep { used + used / 4 + 1024 } else { 0 }; + // What a look costs the thread: about [`STOOD`] of the time we + // hold it (the rest is the kernel reaching it). Over the + // budget, it is looked at less often. + let held = (held as f64).min(COST_MOST); + thread.cost = if thread.cost == 0.0 { + held + } else { + thread.cost + (held - thread.cost) / 16.0 + }; + thread.every = if budget > 0.0 { + (STOOD * thread.cost * hz / 1e9 / budget) + .ceil() + .clamp(1.0, 32.0) as u32 + } else { + 1 + }; + let before = thread.tree.nodes.len(); + let node = thread.tree.place(&self.frames[..frames], whole, room); + self.nodes += thread.tree.nodes.len() - before; + thread.cut += u64::from(!whole); + node + } + }; + let cpu = ((ran as f64 / self.cycles_per_us) as u64).min(weight); + let thread = &mut self.threads[at]; + thread.last = Some(node); + let node = &mut thread.tree.nodes[node as usize]; + node.wall += weight; + node.cpu += cpu; + node.hits += 1; + } + + /// Suspends the thread, reads its registers into `self.context` and + /// copies its stack from the stack pointer up into `self.copy`, and + /// resumes it; the bytes copied, or `None` if it could not be looked + /// at (it ended). + /// + /// While the thread stands still it may hold any lock of the process + /// (the heap's, the loader's, the unwinder's tables'): nothing here + /// between the suspension and the resumption takes one or allocates. + /// The stack is read by the kernel (`ReadProcessMemory`), which fails + /// where a plain read would fault (a thread that is ending). + fn capture(&mut self, at: usize) -> Option<(usize, u64)> { + let thread = &self.threads[at]; + let (handle, low, high) = (thread.handle, thread.low, thread.high); + let context = &mut self.context.0; + context.ContextFlags = CONTEXT_CONTROL_AMD64 | CONTEXT_INTEGER_AMD64; + let limit = match thread.want { + 0 => self.config.stack, + want => want.min(self.config.stack), + }; + let began = Instant::now(); + // SAFETY: a thread of this process that is not this one; the + // context is aligned and ours; the copy has `limit + 16` bytes. + let (read, offset, got) = unsafe { + if SuspendThread(handle) == u32::MAX { + return None; + } + let read = GetThreadContext(handle, context) != 0; + let (mut offset, mut got) = (0, 0); + if read { + let rsp = context.Rsp as usize; + let want = if rsp >= low && rsp < high { + (high - rsp).min(limit) + } else { + limit.min(FOREIGN) + }; + // The copy keeps the stack's alignment: unwinding loads + // saved vector registers with aligned moves. + offset = rsp & 15; + ReadProcessMemory( + GetCurrentProcess(), + rsp as *const c_void, + self.copy.add(offset).cast(), + want, + &mut got, + ); + got = got.min(want); + } + ResumeThread(handle); + (read, offset, got) + }; + let held = began.elapsed().as_nanos() as u64; + self.held += 1; + self.held_ns += held; + self.held_longest = self.held_longest.max(held); + self.held_by[held_class(held).0] += 1; + if !read { + return None; + } + // What an earlier, longer copy left behind it. + let end = offset + got; + if end < self.dirty { + // SAFETY: inside the copy. + unsafe { self.copy.add(end).write_bytes(0, self.dirty - end) }; + } + self.dirty = end; + Some((got, held)) + } + + /// Walks the stack copied by [`Sampler::capture`] (`got` bytes from + /// the stack pointer in `self.context`) into `self.frames`, from the + /// innermost: the count, whether the thread's first frame was + /// reached, and the bytes of the copy the frames took. + /// + /// The thread runs again, so the walk reads the copy: the stack + /// pointer and every saved register that points into the copied part + /// of the stack are moved into the copy before each step (frame + /// pointers are such registers), and a step is taken only if all it + /// can read lies in the copy or the zeroes after it ([`frame_fits`]). + fn walk(&mut self, at: usize, got: usize) -> (usize, bool, usize) { + let (low, high) = (self.threads[at].low, self.threads[at].high); + let depth = self.config.depth.min(MAX_DEPTH); + let context = &mut self.context.0; + let lo = context.Rsp as usize; + let start = self.copy as usize + (lo & 15); + let end = start + got; + let limit = self.copy as usize + self.room; + let top = if lo >= low && lo < high { + high + } else { + lo + got + }; + let mut clipped = false; + self.frames[0] = context.Rip; + let mut frames = 1; + let (mut blind, mut last) = (0, 0); + while frames < depth { + // Into the copy: what points into the stack as it was. + for register in [ + &mut context.Rsp, + &mut context.Rbx, + &mut context.Rbp, + &mut context.Rsi, + &mut context.Rdi, + &mut context.R12, + &mut context.R13, + &mut context.R14, + &mut context.R15, + ] { + let value = *register as usize; + if value >= lo && value < top { + if value - lo < got { + *register = (start + (value - lo)) as u64; + } else { + // Above what was copied: reads there find zeroes. + *register = end as u64; + clipped = true; + } + } + } + let rsp = context.Rsp as usize; + // Out of the copy, or not upwards: the walk ends. + if rsp < start || rsp + 8 > end || rsp <= last { + break; + } + last = rsp; + let mut image = 0; + // SAFETY: looks up the unwind data covering `Rip`, if any. + let entry = unsafe { RtlLookupFunctionEntry(context.Rip, &mut image, null_mut()) }; + if entry.is_null() { + // Code without unwind data is a leaf function (the + // system's call stubs are): its return address is at + // `rsp`. Twice in a row it is no stack of calls. + blind += 1; + if blind > 2 { + break; + } + // SAFETY: `rsp..rsp + 8` is inside the copy. + context.Rip = unsafe { (rsp as *const u64).read_unaligned() }; + context.Rsp += 8; + } else { + blind = 0; + // SAFETY: `entry` is `image`'s, as just looked up. + if !unsafe { frame_fits(image, entry.cast(), context, start, end, limit) } { + break; + } + let (mut data, mut frame) = (null_mut(), 0); + // SAFETY: `entry` belongs to `image`; the context is our + // aligned copy, and what the step reads is in our copy of + // the stack (checked above). + unsafe { + RtlVirtualUnwind( + UNW_FLAG_NHANDLER, + image, + context.Rip, + entry, + context, + &mut data, + &mut frame, + null_mut(), + ) + }; + } + if context.Rip == 0 { + // The first frame's caller: none. (Zeroes read above a + // clipped copy look the same.) + return (frames, !clipped, last + 8 - start); + } + self.frames[frames] = context.Rip - 1; + frames += 1; + } + (frames, false, (last + 8).saturating_sub(start)) + } + + /// Follows the thread `id` as `role`; `handle`, if not null, is open + /// with [`ACCESS`] and becomes ours. + fn follow(&mut self, id: u32, role: Role, handle: HANDLE, name: Option) { + if let Some(thread) = self.threads.iter_mut().find(|t| t.alive && t.id == id) { + // Seen doing more than it was followed for. + if (role as usize) < thread.role as usize { + thread.role = role; + } + thread.round = self.round; + if !handle.is_null() { + // SAFETY: ours, as the caller says. + unsafe { CloseHandle(handle) }; + } + return; + } + let handle = if handle.is_null() { + // SAFETY: opens a thread of this process by its id. + unsafe { OpenThread(ACCESS, 0, id) } + } else { + handle + }; + if handle.is_null() { + return; + } + if self.threads.iter().filter(|t| t.alive).count() >= self.config.most { + // SAFETY: opened above or given to us. + unsafe { CloseHandle(handle) }; + return; + } + let (low, high) = stack_of(handle); + let mut cycles = 0; + // SAFETY: a thread handle of ours and a valid out pointer. + unsafe { QueryThreadCycleTime(handle, &mut cycles) }; + self.threads.push(Thread { + id, + handle, + name: name.unwrap_or_else(|| thread_name(handle)), + start: start_of(handle), + role, + low, + high, + cycles, + last: None, + stood: false, + every: 1, + turn: 1, + owed: 0, + cost: 0.0, + want: 0, + tree: Tree::new(), + alive: true, + round: self.round, + looks: 0, + reused: 0, + missed: 0, + cut: 0, + }); + } + + /// Finds the threads to follow: those the hooks have seen, those with + /// a name of ours, and the busiest of the rest; and notes the ones + /// that ended. + fn rescan(&mut self) { + let passed = self.scanned.elapsed(); + self.scanned = Instant::now(); + self.round += 1; + let wanted = self.config.roles; + for known in &KNOWN_THREADS { + let id = known.thread.load(Relaxed); + if id == 0 || id == self.me { + continue; + } + let role = if known.seen[Seen::Submit as usize].load(Relaxed) >= SUBMITS { + Role::Submit + } else if known.seen[Seen::Record as usize].load(Relaxed) >= LIST_CALLS { + Role::Record + } else { + continue; + }; + if wanted[role as usize] { + self.follow(id, role, null_mut(), None); + } + } + // Every thread of the process: (cycles since the last scan, id) of + // those with no role. + let mut busy: Vec<(u64, u32)> = Vec::new(); + let mut previous: HANDLE = null_mut(); + loop { + let mut next = null_mut(); + // SAFETY: our own process; `previous` is null or a thread + // handle the last pass gave us, closed once passed on. + let status = unsafe { + let status = NtGetNextThread( + GetCurrentProcess(), + previous, + THREAD_QUERY_LIMITED_INFORMATION, + 0, + 0, + &mut next, + ); + if !previous.is_null() { + CloseHandle(previous); + } + status + }; + if status != 0 || next.is_null() { + break; + } + previous = next; + // SAFETY: a thread handle just opened. + let id = unsafe { GetThreadId(next) }; + if id == 0 || id == self.me { + continue; + } + if let Some(thread) = self.threads.iter_mut().find(|t| t.alive && t.id == id) { + thread.round = self.round; + continue; + } + let round = self.round; + let other = match self.others.entry(id) { + std::collections::hash_map::Entry::Occupied(o) => o.into_mut(), + std::collections::hash_map::Entry::Vacant(v) => { + // SAFETY: opens a thread of this process by its id. + let handle = unsafe { OpenThread(ACCESS, 0, id) }; + if handle.is_null() { + continue; + } + let mut cycles = 0; + // SAFETY: a thread handle of ours, a valid out pointer. + unsafe { QueryThreadCycleTime(handle, &mut cycles) }; + v.insert(Other { + handle, + cycles, + name: String::new(), + round, + }) + } + }; + other.round = round; + if other.name.is_empty() { + other.name = thread_name(other.handle); + } + if other.name == "leonida-profile" { + continue; + } + // SAFETY: a thread handle of ours, opened with `SYNCHRONIZE`. + if unsafe { WaitForSingleObject(other.handle, 0) } == 0 { + continue; + } + if let Some(role) = Role::of_name(&other.name) { + if wanted[role as usize] + && let Some(other) = self.others.remove(&id) + { + self.follow(id, role, other.handle, Some(other.name)); + } + continue; + } + let mut cycles = 0; + // SAFETY: a thread handle of ours and a valid out pointer. + unsafe { QueryThreadCycleTime(other.handle, &mut cycles) }; + busy.push((cycles.saturating_sub(other.cycles), id)); + other.cycles = cycles; + } + // Threads that ended: no longer looked at; what was sampled stays. + // (A thread we hold a handle to is still listed after its end.) + let round = self.round; + // SAFETY: a thread handle of ours, opened with `SYNCHRONIZE`. + let ended = |handle: HANDLE| unsafe { WaitForSingleObject(handle, 0) } == 0; + for thread in self + .threads + .iter_mut() + .filter(|t| t.alive && (t.round != round || ended(t.handle))) + { + thread.alive = false; + // SAFETY: ours. + unsafe { CloseHandle(thread.handle) }; + thread.handle = null_mut(); + for known in &KNOWN_THREADS { + let _ = known + .thread + .compare_exchange(thread.id, 0, Relaxed, Relaxed); + } + } + self.others.retain(|_, other| { + let gone = other.round != round || ended(other.handle); + if gone { + // SAFETY: ours. + unsafe { CloseHandle(other.handle) }; + } + !gone + }); + // The busiest of the rest: a quarter of a processor or more. + if wanted[Role::Busy as usize] { + let least = (0.25 * passed.as_micros() as f64 * self.cycles_per_us) as u64; + busy.sort_unstable_by(|a, b| b.cmp(a)); + for (ran, id) in busy { + let followed = self + .threads + .iter() + .filter(|t| t.alive && t.role == Role::Busy) + .count(); + if ran < least.max(1) || followed >= self.config.busy { + break; + } + if let Some(other) = self.others.remove(&id) { + self.follow(id, Role::Busy, other.handle, Some(other.name)); + } + } + } + } +} + +/// Whether unwinding one frame of the function `entry` of the image at +/// `image` from `context` reads only our copy of a stack (`start..end`) +/// and the zeroes after it (to `limit`): the stack pointer, and the frame +/// pointer if the function has set one up, must lie in the copy, and what +/// the function's unwind codes take off the stack must fit in the zeroes. +/// +/// `RtlVirtualUnwind` trusts the registers it is given. Ours come from a +/// thread stopped anywhere, and a return address may be none (code +/// without unwind data in the middle of a stack): a frame pointer that +/// points nowhere would be read through. +/// +/// # Safety +/// `entry` is the function table entry of `image` for `context.Rip`. +unsafe fn frame_fits( + image: u64, + entry: *const [u32; 3], + context: &CONTEXT, + start: usize, + end: usize, + limit: usize, +) -> bool { + // SAFETY: the caller's entry, and the unwind data it names in its + // loaded image: a header of four bytes, `count` two-byte codes, and + // after them (made even) the entry of the function this one is a + // part of, if the header says so. + unsafe { + let [begin, finish, mut data] = entry.read_unaligned(); + let at = context + .Rip + .wrapping_sub(image) + .wrapping_sub(u64::from(begin)); + // The frame register the function itself names (its first part). + let mut pointer = 0; + // Bytes above the frame's base that unwinding may read: the + // return address, a machine frame's tail. + let mut reach = 64usize; + // Bases other than the stack pointer: frame pointers set up. + let mut bases = [0usize; 4]; + let mut based = 0; + for part in 0..8 { + if data & 1 != 0 { + return false; + } + let info = (image + u64::from(data)) as *const u8; + let [version, _prolog, count, frame] = info.cast::<[u8; 4]>().read(); + if !matches!(version & 7, 1 | 2) { + return false; + } + let chained = version >> 3 & 4 != 0; + if part == 0 { + pointer = frame & 15; + } + let codes = info.add(4); + let count = usize::from(count); + let slot = |i: usize| codes.add(2 * i).cast::().read_unaligned(); + let mut i = 0; + let (mut found, mut set) = (false, false); + while i < count { + let [offset, op] = codes.add(2 * i).cast::<[u8; 2]>().read(); + let (op, op_info) = (op & 15, usize::from(op >> 4)); + i += match op { + // A register pushed. + 0 => { + reach += 8; + 1 + } + // A large allocation: its size in the next one or two slots. + 1 if op_info == 0 => { + reach += usize::from(slot(i + 1)) * 8; + 2 + } + 1 => { + reach += usize::from(slot(i + 1)) | usize::from(slot(i + 2)) << 16; + 3 + } + // A small allocation. + 2 => { + reach += op_info * 8 + 8; + 1 + } + // The frame pointer set: done already if the thread is + // past that instruction, or in a later part of the function. + 3 => { + found = true; + set = part > 0 || chained || at >= u64::from(offset); + 1 + } + // Registers saved in the frame (near, far), an epilogue + // note and a spare code, vector registers saved. + 4 | 8 => 2, + 5 | 9 => 3, + 6 => 1, + 7 => 2, + // A machine frame. + 10 => { + reach += 48; + 1 + } + _ => return false, + }; + } + if frame & 15 != 0 && (set || !found || part > 0 || chained) { + let register = gpr(context, frame & 15) as usize; + let back = usize::from(frame >> 4) * 16; + if register < start + back || register > end || based == bases.len() { + return false; + } + bases[based] = register - back; + based += 1; + } + if !chained { + let rsp = context.Rsp as usize; + let code = image + u64::from(finish) - context.Rip; + return rsp >= start + && rsp < end + && reach <= SLACK + && rsp + reach <= limit + && bases[..based].iter().all(|base| base + reach <= limit) + && epilogue_fits(context, code as usize, pointer, start, end); + } + let parent = codes + .add(2 * ((count + 1) & !1)) + .cast::<[u32; 3]>() + .read_unaligned(); + data = parent[2]; + } + false + } +} + +/// Whether the instructions at `context.Rip` (`code` bytes of them are the +/// function's), if the unwinder takes them for the end of a function, +/// leave the stack pointer inside our copy of a stack (`start..end`). +/// `pointer` is the function's frame register (0: none). +/// +/// Where a thread stands at a function's last instructions, the +/// unwinder does not use the unwind codes: it runs those instructions +/// itself, an `add rsp, n` or a `lea rsp, [frame register + n]`, then the +/// `pop`s, then the return. An address that is no instruction's start can +/// read as a `pop rsp`, or as an `add` of any number: this reads the +/// bytes as the unwinder does and refuses what would take the stack +/// pointer out of the copy. It takes a little more for a function's end +/// than the unwinder does (any jump after the `pop`s, wherever it goes). +/// +/// # Safety +/// `code` bytes at `context.Rip` are readable. +unsafe fn epilogue_fits( + context: &CONTEXT, + code: usize, + pointer: u8, + start: usize, + end: usize, +) -> bool { + let rip = context.Rip as *const u8; + // Past the function's end reads as a breakpoint: nothing of an epilogue. + let byte = |i: usize| { + if i < code { + // SAFETY: inside the `code` bytes the caller says are readable. + unsafe { rip.add(i).read() } + } else { + 0xcc + } + }; + let number = |i: usize| i32::from_le_bytes([byte(i), byte(i + 1), byte(i + 2), byte(i + 3)]); + let moved = |from: u64, by: i32| (from as usize).wrapping_add(by as isize as usize); + let mut rsp = context.Rsp as usize; + let mut at = 0; + if byte(0) == 0x48 && byte(1) == 0x83 && byte(2) == 0xc4 { + // add rsp, n (a byte). + rsp = moved(context.Rsp, i32::from(byte(3) as i8)); + at = 4; + } else if byte(0) == 0x48 && byte(1) == 0x81 && byte(2) == 0xc4 { + // add rsp, n. + rsp = moved(context.Rsp, number(3)); + at = 7; + } else if byte(0) & 0xfe == 0x48 && byte(1) == 0x8d { + // lea rsp, [register + n]: taken only from the frame register. + let register = (byte(0) & 1) << 3 | byte(2) & 7; + let (near, far) = (byte(2) & 0xf8 == 0x60, byte(2) & 0xf8 == 0xa0); + if register != 0 && register == pointer && (near || far) { + let by = if near { + i32::from(byte(3) as i8) + } else { + number(3) + }; + rsp = moved(gpr(context, register), by); + at = if near { 4 } else { 7 }; + } + } + // The `pop`s. + let (mut pops, mut pops_rsp) = (0, false); + loop { + let (op, rex) = (byte(at), byte(at) & 0xf0 == 0x40); + let register = if rex { byte(at + 1) } else { op }; + if register & 0xf8 != 0x58 || pops == 64 { + break; + } + pops_rsp |= register & 7 == 4 && !(rex && op & 1 != 0); + at += if rex { 2 } else { 1 }; + pops += 1; + } + // A return or a jump: only then are the instructions before it run. + let leaves = matches!(byte(at), 0xc3 | 0xc2 | 0xeb | 0xe9) + || byte(at) == 0xf3 && byte(at + 1) == 0xc3 + || byte(at) == 0xff && byte(at + 1) == 0x25 + || byte(at) & 0xf0 == 0x40 && byte(at + 1) == 0xff && byte(at + 2) & 0x38 == 0x20; + !leaves || (!pops_rsp && pops < 64 && rsp >= start && rsp + 8 * (pops + 1) <= end) +} + +/// The class of a time in nanoseconds: four to a power of two (the +/// index), and the class's lower end. +fn held_class(ns: u64) -> (usize, u64) { + if ns < 4 { + return (ns as usize, ns); + } + let bits = 63 - ns.leading_zeros() as usize; + let quarter = ns >> (bits - 2) & 3; + (bits * 4 + quarter as usize, (4 + quarter) << (bits - 2)) +} + +/// The general register numbered `n` as unwind data numbers them. +fn gpr(context: &CONTEXT, n: u8) -> u64 { + match n & 15 { + 0 => context.Rax, + 1 => context.Rcx, + 2 => context.Rdx, + 3 => context.Rbx, + 4 => context.Rsp, + 5 => context.Rbp, + 6 => context.Rsi, + 7 => context.Rdi, + 8 => context.R8, + 9 => context.R9, + 10 => context.R10, + 11 => context.R11, + 12 => context.R12, + 13 => context.R13, + 14 => context.R14, + _ => context.R15, + } +} + +/// The processor counter's cycles per microsecond, measured. +fn cycles_per_us() -> f64 { + let began = Instant::now(); + // SAFETY: reads the processor's time stamp counter. + let from = unsafe { std::arch::x86_64::_rdtsc() }; + std::thread::sleep(Duration::from_millis(20)); + // SAFETY: as above. + let cycles = unsafe { std::arch::x86_64::_rdtsc() }.wrapping_sub(from); + (cycles as f64 / began.elapsed().as_micros().max(1) as f64).max(1.0) +} + +/// The reservation of a thread's stack, lowest address and end; (0, 0) if +/// it cannot be asked (the thread ended). +fn stack_of(thread: HANDLE) -> (usize, usize) { + /// `THREAD_BASIC_INFORMATION` (ntddk). + #[repr(C)] + struct Basic { + exit_status: i32, + teb: usize, + client_id: [usize; 2], + affinity: usize, + priority: i32, + base_priority: i32, + } + let mut basic = Basic { + exit_status: 0, + teb: 0, + client_id: [0; 2], + affinity: 0, + priority: 0, + base_priority: 0, + }; + // SAFETY: writes `basic`, whose layout and size are the system's. + let status = unsafe { + NtQueryInformationThread( + thread, + 0, + (&raw mut basic).cast(), + size_of::() as u32, + null_mut(), + ) + }; + if status != 0 || basic.teb == 0 { + return (0, 0); + } + // The thread's block: the stack's end at +8, the start of its + // reservation at +0x1478. Read by the kernel: the thread may end. + let word = |at: usize| { + let (mut value, mut got) = (0usize, 0); + // SAFETY: reads eight bytes into `value`; fails if they are gone. + let read = unsafe { + ReadProcessMemory( + GetCurrentProcess(), + at as *const c_void, + (&raw mut value).cast(), + 8, + &mut got, + ) + }; + if read != 0 && got == 8 { value } else { 0 } + }; + let (high, low) = (word(basic.teb + 8), word(basic.teb + 0x1478)); + if low != 0 && low < high { + (low, high) + } else { + (0, 0) + } +} + +/// The address a thread started at; 0 if it cannot be asked. +fn start_of(thread: HANDLE) -> u64 { + let mut start = 0u64; + // SAFETY: writes one pointer-sized start address + // (`ThreadQuerySetWin32StartAddress` is 9). + unsafe { + NtQueryInformationThread(thread, 9, (&raw mut start).cast(), 8, null_mut()); + } + start +} + +fn thread_name(thread: HANDLE) -> String { + let mut text: *mut u16 = null_mut(); + // SAFETY: the system allocates the string; we free it with LocalFree. + unsafe { + if GetThreadDescription(thread, &mut text) < 0 || text.is_null() { + return String::new(); + } + let len = (0..).take_while(|&i| *text.add(i) != 0).count(); + let name = String::from_utf16_lossy(std::slice::from_raw_parts(text, len)); + LocalFree(text.cast()); + name + } +} + +// --------------------------------------------------------------------- +// Names, found when a report is written. +// --------------------------------------------------------------------- + +/// Whose code a frame is. +#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)] +enum Kind { + Ours = 0, + Driver = 1, + Direct3d = 2, + System = 3, + Title = 4, + Other = 5, +} + +const KINDS: [&str; 6] = [ + "ours", + "graphics driver", + "d3d12 / dxgi", + "ntdll + kernel", + "title", + "other", +]; + +/// The kind of a module by its file name (lower case). +fn kind_of(file: &str, ours: bool) -> Kind { + let starts = |list: &[&str]| list.iter().any(|p| file.starts_with(p)); + if ours { + Kind::Ours + } else if file.starts_with("leonida-image-") { + Kind::Title + } else if starts(&["nv", "amd", "ati", "igd", "igc", "ig1", "ig9", "ig7", "ig8"]) { + Kind::Driver + } else if starts(&["d3d", "dxgi", "dxcore", "dxil", "dcomp", "dwmapi"]) { + Kind::Direct3d + } else if matches!( + file, + "ntdll.dll" | "kernelbase.dll" | "kernel32.dll" | "win32u.dll" + ) { + Kind::System + } else { + Kind::Other + } +} + +struct Module { + base: u64, + end: u64, + /// What its frames are named by: `title`, or its file name. + label: String, + kind: Kind, +} + +/// A function as the report names it. +struct Func { + name: String, + /// Of ours, but the language's runtime (`std::`, `core::`, `alloc::`). + runtime: bool, + /// A call that waits ([`waits`]). + wait: bool, +} + +/// What an address is. +struct Resolved { + /// The functions it is in, outermost first: more than one where the + /// compiler inlined calls (ours only). + funcs: Box<[u32]>, + kind: Option, + /// Its source line (ours), an index into `Symbols::lines`. + line: Option, +} + +type SymFromAddr = unsafe extern "system" fn(HANDLE, u64, *mut u64, *mut SYMBOL_INFOW) -> i32; +type SymFromInline = + unsafe extern "system" fn(HANDLE, u64, u32, *mut u64, *mut SYMBOL_INFOW) -> i32; +type SymInlineQuery = + unsafe extern "system" fn(HANDLE, u64, u32, u64, u64, *mut u32, *mut u32) -> i32; +type SymLine = unsafe extern "system" fn(HANDLE, u64, *mut u32, *mut IMAGEHLP_LINEW64) -> i32; +type SymLineInline = + unsafe extern "system" fn(HANDLE, u64, u32, u64, *mut u32, *mut IMAGEHLP_LINEW64) -> i32; + +/// The system's symbol library (`dbghelp.dll`), loaded when the first +/// report is written: a build that does not profile does not load it. +struct DbgHelp { + process: HANDLE, + refresh: unsafe extern "system" fn(HANDLE) -> i32, + from_addr: SymFromAddr, + line: Option, + module: Option i32>, + /// Inlined calls: how many at an address, their first context, a name + /// and a line by context. + inline: Option<( + unsafe extern "system" fn(HANDLE, u64) -> u32, + SymInlineQuery, + SymFromInline, + Option, + )>, +} + +/// A symbol with room for its name. +#[repr(C)] +struct Symbol { + info: SYMBOL_INFOW, + name: [u16; 1024], +} + +impl DbgHelp { + fn open() -> Option { + // SAFETY: loads the system's own dbghelp.dll and looks its + // functions up by name; each is called with the signature the + // system documents for it. The library's "process" is a second + // handle to ours, so its tables are not the ones Rust's own + // backtraces set up for the plain handle. + unsafe { + let library = LoadLibraryExA( + c"dbghelp.dll".as_ptr().cast(), + null_mut(), + LOAD_LIBRARY_SEARCH_SYSTEM32, + ); + if library.is_null() { + return None; + } + macro_rules! find { + ($name:literal) => { + GetProcAddress(library, $name.as_ptr().cast()).map(|f| std::mem::transmute(f)) + }; + } + let get_options: unsafe extern "system" fn() -> u32 = find!(c"SymGetOptions")?; + let set_options: unsafe extern "system" fn(u32) -> u32 = find!(c"SymSetOptions")?; + let initialize: unsafe extern "system" fn(HANDLE, *const u16, i32) -> i32 = + find!(c"SymInitializeW")?; + let refresh = find!(c"SymRefreshModuleList")?; + let from_addr = find!(c"SymFromAddrW")?; + let inline = match ( + find!(c"SymAddrIncludeInlineTrace"), + find!(c"SymQueryInlineTrace"), + find!(c"SymFromInlineContextW"), + ) { + (Some(count), Some(query), Some(name)) => { + Some((count, query, name, find!(c"SymGetLineFromInlineContextW"))) + } + _ => None, + }; + let mut process = null_mut(); + let me = GetCurrentProcess(); + if DuplicateHandle(me, me, me, &mut process, 0, 0, DUPLICATE_SAME_ACCESS) == 0 { + return None; + } + // Names undecorated, lines loaded, a module's symbols read + // when first asked for, no dialogs. Symbols are looked for + // where the image says and beside our executable only: no + // symbol server is asked (`_NT_SYMBOL_PATH` is not used when + // a path is given). + const UNDNAME: u32 = 0x2; + const DEFERRED_LOADS: u32 = 0x4; + const LOAD_LINES: u32 = 0x10; + const FAIL_CRITICAL_ERRORS: u32 = 0x200; + const NO_PROMPTS: u32 = 0x80000; + set_options( + get_options() + | UNDNAME + | DEFERRED_LOADS + | LOAD_LINES + | FAIL_CRITICAL_ERRORS + | NO_PROMPTS, + ); + let folder = std::env::current_exe() + .ok() + .and_then(|exe| exe.parent().map(|p| p.to_path_buf())) + .unwrap_or_default(); + let path: Vec = folder + .to_string_lossy() + .encode_utf16() + .chain(std::iter::once(0)) + .collect(); + if initialize(process, path.as_ptr(), 1) == 0 { + CloseHandle(process); + return None; + } + Some(DbgHelp { + process, + refresh, + from_addr, + line: find!(c"SymGetLineFromAddrW64"), + module: find!(c"SymGetModuleInfoW64"), + inline, + }) + } + } + + /// A symbol's name and address from a lookup that fills `symbol`. + fn named(lookup: impl FnOnce(*mut SYMBOL_INFOW) -> i32) -> Option<(String, u64)> { + // SAFETY: a zeroed symbol is valid; its header says how much room + // follows for the name, and the name read is inside that room. + unsafe { + let mut symbol: Box = Box::new(std::mem::zeroed()); + symbol.info.SizeOfStruct = size_of::() as u32; + symbol.info.MaxNameLen = symbol.name.len() as u32; + // The whole of it: the name runs on past the header. + let whole = (&raw mut *symbol).cast::(); + if lookup(whole) == 0 { + return None; + } + let len = ((*whole).NameLen as usize).min(symbol.name.len()); + let name = whole + .cast::() + .add(std::mem::offset_of!(SYMBOL_INFOW, Name)) + .cast::(); + let text = std::slice::from_raw_parts(name, len); + let end = text.iter().position(|&c| c == 0).unwrap_or(len); + Some((String::from_utf16_lossy(&text[..end]), (*whole).Address)) + } + } + + /// The symbol at or before `address`: its name and its own address. + fn symbol(&self, address: u64) -> Option<(String, u64)> { + let mut displacement = 0; + // SAFETY: the library's own call with a symbol of ours to fill. + Self::named(|symbol| unsafe { + (self.from_addr)(self.process, address, &mut displacement, symbol) + }) + } + + /// The functions `address` is in, outermost first (the calls the + /// compiler inlined there, if `inlined`), and the context of the + /// innermost for [`DbgHelp::line`]. + fn functions(&self, address: u64, inlined: bool) -> (Vec, Option) { + if inlined && let Some((count, query, name, _)) = self.inline { + // SAFETY: the library's own calls, as documented: the count + // of inlined calls at an address, the context of the first, + // then a name per context; the last context is the function + // itself. + unsafe { + let inlines = count(self.process, address); + let (mut first, mut index) = (0, 0); + if inlines > 0 + && query( + self.process, + address, + 0, + address, + address, + &mut first, + &mut index, + ) != 0 + { + let mut names: Vec = (first..=first + inlines) + .filter_map(|context| { + let mut displacement = 0; + Self::named(|symbol| { + name(self.process, address, context, &mut displacement, symbol) + }) + }) + .map(|(name, _)| name) + .collect(); + if !names.is_empty() { + names.reverse(); + return (names, Some(first)); + } + } + } + } + ( + self.symbol(address) + .into_iter() + .map(|(name, _)| name) + .collect(), + None, + ) + } + + /// The source file and line of `address` (of the inlined call with + /// `context`, if any). + fn line(&self, address: u64, context: Option) -> Option<(String, u32)> { + // SAFETY: the library's own calls with a line of ours to fill; + // the file name it points to is a string of its own. + unsafe { + let mut line: IMAGEHLP_LINEW64 = std::mem::zeroed(); + line.SizeOfStruct = size_of::() as u32; + let mut displacement = 0; + let found = match (context, self.inline.and_then(|i| i.3)) { + (Some(context), Some(by_context)) => { + by_context( + self.process, + address, + context, + 0, + &mut displacement, + &mut line, + ) != 0 + } + _ => false, + } || self.line.is_some_and(|by_address| { + by_address(self.process, address, &mut displacement, &mut line) != 0 + }); + if !found || line.FileName.is_null() { + return None; + } + let len = (0..1024) + .take_while(|&i| *line.FileName.add(i) != 0) + .count(); + let file = String::from_utf16_lossy(std::slice::from_raw_parts(line.FileName, len)); + Some((file, line.LineNumber)) + } + } + + /// Whether the module at `base` has its symbols from a PDB, and what + /// the library says it loaded. + fn has_pdb(&self, base: u64) -> (bool, String) { + let Some(module) = self.module else { + return (false, String::new()); + }; + // SAFETY: the library's own call with a sized structure to fill. + unsafe { + let mut info: Box = Box::new(std::mem::zeroed()); + info.SizeOfStruct = size_of::() as u32; + if module(self.process, base, &mut *info) == 0 { + return (false, String::new()); + } + let text = |chars: &[u16]| { + let end = chars.iter().position(|&c| c == 0).unwrap_or(chars.len()); + String::from_utf16_lossy(&chars[..end]) + }; + // SymPdb is 3 and SymDia 7. + (matches!(info.SymType, 3 | 7), text(&info.LoadedPdbName)) + } + } +} + +/// The start of the function `address` is in, by its image's unwind data +/// (the first part's, for a function in several); `None` for code that +/// has none. +fn function_start(address: u64) -> Option { + let mut image = 0; + // SAFETY: looks up the unwind data covering `address`, if any, and + // reads it in its loaded image: a part of a function names the entry + // of the function it belongs to after its codes. + unsafe { + let entry = RtlLookupFunctionEntry(address, &mut image, null_mut()); + if entry.is_null() { + return None; + } + let mut entry = entry.cast::<[u32; 3]>().read_unaligned(); + for _ in 0..8 { + if entry[2] & 1 != 0 { + break; + } + let info = (image + u64::from(entry[2])) as *const u8; + let [version, _, count, _] = info.cast::<[u8; 4]>().read(); + if version >> 3 & 4 == 0 { + break; + } + let after = info.add(4 + 2 * ((usize::from(count) + 1) & !1)); + entry = after.cast::<[u32; 3]>().read_unaligned(); + } + Some(image + u64::from(entry[0])) + } +} + +/// Whether a thread whose innermost frame is `name` waits there: the +/// kernel's waits, by their names in ntdll and win32u (`Nt` or `Zw`). +fn waits(name: &str) -> bool { + let function = name.rsplit('!').next().unwrap_or(name); + let Some(call) = function + .strip_prefix("Nt") + .or_else(|| function.strip_prefix("Zw")) + else { + return false; + }; + [ + "WaitFor", + "DelayExecution", + "RemoveIoCompletion", + "SignalAndWait", + "UserMsgWaitForMultipleObjects", + "UserGetMessage", + "UserWaitMessage", + "GdiDdDDIWaitFor", + ] + .iter() + .any(|wait| call.starts_with(wait)) +} + +/// What kind of wait the frames between a waiting call and the function +/// of ours that waited make it. +fn wait_kind(path: &[&str]) -> &'static str { + let has = |what: &str| path.iter().any(|name| name.contains(what)); + if has("SleepConditionVariable") || has("Condvar") { + "condition variable" + } else if has("SRWLock") { + "lock (SRW)" + } else if has("CriticalSection") { + "lock (critical section)" + } else if has("Mutex") || has("RwLock") || has("Once") { + "lock (ours)" + } else if has("park") { + "parked" + } else if has("Sleep") || has("sleep") || has("DelayExecution") { + "sleep" + } else if has("GdiDdDDIWaitFor") { + "graphics kernel" + } else if has("WaitOnAddress") || has("WaitForAlertByThreadId") { + "wait on address" + } else if has("IoCompletion") || has("GetQueuedCompletionStatus") { + "I/O completion" + } else if has("MsgWait") || has("GetMessage") || has("WaitMessage") { + "window messages" + } else if has("WaitForMultipleObjects") || has("WaitForSingleObject") { + "event or handle" + } else { + "other wait" + } +} + +struct Symbols { + dbghelp: Option, + inline: bool, + /// Loaded modules by base, as of the report being written. + modules: Vec, + /// Whether our executable's names come from its PDB, and which. + pdb: (bool, String), + funcs: Vec, + by_name: HashMap, + lines: Vec, + by_line: HashMap, + resolved: Vec, + by_address: FastMap, +} + +impl Symbols { + fn new(inline: bool) -> Symbols { + Symbols { + dbghelp: DbgHelp::open(), + inline, + modules: Vec::new(), + pdb: (false, String::new()), + funcs: Vec::new(), + by_name: HashMap::new(), + lines: Vec::new(), + by_line: HashMap::new(), + resolved: Vec::new(), + by_address: FastMap::default(), + } + } + + /// Lists the loaded modules anew (a report's first step). + fn refresh(&mut self) { + // SAFETY: plain queries of our own process with sized buffers. + unsafe { + if let Some(dbghelp) = &self.dbghelp { + (dbghelp.refresh)(dbghelp.process); + } + let me = GetCurrentProcess(); + let mut handles: Vec = vec![null_mut(); 2048]; + let mut bytes = 0; + let size = (handles.len() * size_of::()) as u32; + if K32EnumProcessModules(me, handles.as_mut_ptr(), size, &mut bytes) == 0 { + return; + } + handles.truncate(bytes as usize / size_of::()); + let exe = GetModuleHandleW(null()); + let mut modules = Vec::with_capacity(handles.len()); + for handle in handles { + let mut info = MODULEINFO { + lpBaseOfDll: null_mut(), + SizeOfImage: 0, + EntryPoint: null_mut(), + }; + if K32GetModuleInformation(me, handle, &mut info, size_of::() as u32) + == 0 + { + continue; + } + let mut path = [0u16; 520]; + let len = GetModuleFileNameW(handle, path.as_mut_ptr(), path.len() as u32); + let path = String::from_utf16_lossy(&path[..len as usize]); + let file = path.rsplit(['\\', '/']).next().unwrap_or(&path).to_owned(); + let kind = kind_of(&file.to_ascii_lowercase(), handle == exe); + let base = handle as u64; + modules.push(Module { + base, + end: base + u64::from(info.SizeOfImage), + label: file, + kind, + }); + } + modules.sort_by_key(|m| m.base); + // The title's images are named by their content: the largest + // is the title itself, the others its libraries. + let largest = modules + .iter() + .filter(|m| m.kind == Kind::Title) + .map(|m| m.end - m.base) + .max(); + for module in modules.iter_mut().filter(|m| m.kind == Kind::Title) { + module.label = if Some(module.end - module.base) == largest { + "title".to_owned() + } else { + let hash = module.label.trim_start_matches("leonida-image-"); + format!("title-{}", &hash[..hash.len().min(6)]) + }; + } + self.modules = modules; + if let Some(dbghelp) = &self.dbghelp + && !self.pdb.0 + { + // The executable's symbols are read when first asked for. + dbghelp.symbol(function_start as *const () as u64); + self.pdb = dbghelp.has_pdb(exe as u64); + } + } + } + + fn func(&mut self, name: String, kind: Option) -> u32 { + if let Some(&at) = self.by_name.get(&name) { + return at; + } + // (By the name before its type arguments: a closure of ours is one.) + let own_name = name.split('<').next().unwrap_or(&name); + let runtime = kind == Some(Kind::Ours) + && [ + "std::", "core::", "alloc::", "__rust", "__chkstk", "mem", "str", + ] + .iter() + .any(|p| own_name.starts_with(p)); + self.funcs.push(Func { + wait: waits(&name), + name: name.clone(), + runtime, + }); + self.by_name.insert(name, self.funcs.len() as u32 - 1); + self.funcs.len() as u32 - 1 + } + + /// What `address` is, as an index into `self.resolved`. + fn resolve(&mut self, address: u64) -> u32 { + if let Some(&at) = self.by_address.get(&address) { + return at; + } + let resolved = self.look_up(address); + self.resolved.push(resolved); + let at = self.resolved.len() as u32 - 1; + self.by_address.insert(address, at); + at + } + + fn look_up(&mut self, address: u64) -> Resolved { + let marker = match address { + CUT => Some("[frames not kept]"), + FULL => Some("[samples after the trees were full]"), + _ => None, + }; + if let Some(name) = marker { + let func = self.func(name.to_owned(), None); + return Resolved { + funcs: Box::new([func]), + kind: None, + line: None, + }; + } + let at = self.modules.partition_point(|m| m.base <= address); + let module = at + .checked_sub(1) + .map(|at| &self.modules[at]) + .filter(|m| address < m.end); + let Some(module) = module else { + let func = self.func("[code in no loaded module]".to_owned(), Some(Kind::Other)); + return Resolved { + funcs: Box::new([func]), + kind: Some(Kind::Other), + line: None, + }; + }; + let (base, kind, label) = (module.base, module.kind, module.label.clone()); + let start = function_start(address); + // By the function's start in its module: what code with no names + // (the title, the driver) is told apart by. + let plain = || match start { + Some(start) => format!("{label}+{:#x}", start - base), + None => format!("{label}+{:#x}", (address - base) & !15), + }; + let mut line = None; + let names = match (&self.dbghelp, kind) { + (_, Kind::Title) | (None, _) => vec![plain()], + (Some(dbghelp), Kind::Ours) if self.pdb.0 => { + let (names, context) = dbghelp.functions(address, self.inline); + line = dbghelp.line(address, context); + if names.is_empty() { + vec![plain()] + } else { + names + } + } + (Some(dbghelp), _) => { + // An export names the function only if it starts it: the + // nearest export below is some other function's. + let export = dbghelp.symbol(address).filter(|&(_, at)| match start { + Some(start) => at >= start && at <= address, + None => at <= address && address - at < 0x100, + }); + match export { + Some((name, _)) => { + let module = label.rsplit_once('.').map_or(&*label, |(stem, _)| stem); + vec![format!("{module}!{name}")] + } + None => vec![plain()], + } + } + }; + let funcs = names + .into_iter() + .map(|name| self.func(name, Some(kind))) + .collect(); + let line = line.map(|(file, line)| { + // The last three parts of the path: the crate, `src`, the file. + let mut parts: Vec<&str> = file.rsplit(['\\', '/']).take(3).collect(); + parts.reverse(); + let text = format!("{}:{line}", parts.join("\\")); + *self.by_line.entry(text.clone()).or_insert_with(|| { + self.lines.push(text); + self.lines.len() as u32 - 1 + }) + }); + Resolved { + funcs, + kind: Some(kind), + line, + } + } +} + +// --------------------------------------------------------------------- +// The report. +// --------------------------------------------------------------------- + +/// A function's time in a role, microseconds. +#[derive(Default, Clone, Copy)] +struct Row { + /// In the function itself, and of that on a processor. + own: u64, + cpu: u64, + /// In it and in what it called. + all: u64, +} + +/// What a role's threads did. +#[derive(Default)] +struct RoleReport { + threads: Vec, + wall: u64, + cpu: u64, + waiting: u64, + funcs: FastMap, + /// By [`Kind`]: innermost frame's, the nearest frame's that is not the + /// system's, and with what it called. + modules: [[u64; 3]; 6], + /// (kind of wait, the function that waited, through whose code) to + /// microseconds. + waits: HashMap<(&'static str, u32, Option), u64>, + lines: FastMap<(u32, u32), u64>, + /// Stacks as function indices, outermost first. + stacks: HashMap, u64>, +} + +/// A written report, and its numbers for the tests. +struct Report { + text: String, + folded: String, + #[cfg_attr(not(test), allow(dead_code))] + roles: Vec, +} + +/// A role's numbers as the tests ask for them (microseconds). +#[cfg_attr(not(test), allow(dead_code))] +struct RoleSummary { + role: Role, + wall: u64, + waiting: u64, + /// (name, own, with what it called), every function. + functions: Vec<(String, u64, u64)>, + /// (kind, the function that waited, time). + waits: Vec<(String, String, u64)>, +} + +/// The stacks written to the stacks file: those with this share of their +/// role's time or more; the rest go to one line per role. +const FOLD_LEAST: f64 = 0.00005; + +impl Sampler { + fn report(&mut self) -> Report { + let began = Instant::now(); + let inline = self.config.inline; + let stood = (self.held_within(0.5), self.held_within(0.99)); + let symbols = self.symbols.get_or_insert_with(|| Symbols::new(inline)); + symbols.refresh(); + // Every node's address, named. + let named: Vec> = self + .threads + .iter() + .map(|t| { + t.tree + .nodes + .iter() + .map(|n| symbols.resolve(n.address)) + .collect() + }) + .collect(); + let starts: Vec = self + .threads + .iter() + .map(|t| symbols.resolve(t.start)) + .collect(); + let symbols = &*symbols; + let mut roles: Vec = Role::ALL.iter().map(|_| RoleReport::default()).collect(); + // Per thread: wall, on a processor, waiting (microseconds). + let mut per_thread = vec![[0u64; 3]; self.threads.len()]; + // Per thread: own time by function, for the one it is mostly in. + let mut mostly: Vec> = vec![FastMap::default(); self.threads.len()]; + let mut stamp = 0u32; + let mut seen = vec![0u32; symbols.funcs.len()]; + let mut path: Vec<(u32, Option)> = Vec::new(); + for (t, thread) in self.threads.iter().enumerate() { + let role = &mut roles[thread.role as usize]; + role.threads.push(t); + let nodes = &thread.tree.nodes; + for (i, node) in nodes.iter().enumerate().skip(1) { + if node.wall == 0 { + continue; + } + // The stack, innermost first, inlined calls as frames. + path.clear(); + let mut at = i; + while at != 0 { + let resolved = &symbols.resolved[named[t][at] as usize]; + path.extend(resolved.funcs.iter().rev().map(|&f| (f, resolved.kind))); + at = nodes[at].parent as usize; + } + let (wall, cpu) = (node.wall, node.cpu); + role.wall += wall; + role.cpu += cpu; + per_thread[t][0] += wall; + per_thread[t][1] += cpu; + *mostly[t].entry(path[0].0).or_default() += wall; + let (leaf, leaf_kind) = path[0]; + let row = role.funcs.entry(leaf).or_default(); + row.own += wall; + row.cpu += cpu; + stamp += 1; + let mut kinds = [false; 6]; + // Every thread starts in the system's code: those outermost + // frames are not the system "with what it calls". + let start = path + .iter() + .rposition(|p| p.1.is_some_and(|k| k != Kind::System)); + for (at, &(func, kind)) in path.iter().enumerate() { + if seen[func as usize] != stamp { + seen[func as usize] = stamp; + role.funcs.entry(func).or_default().all += wall; + } + if let Some(kind) = kind + && start.is_some_and(|start| at <= start) + { + kinds[kind as usize] = true; + } + } + for (kind, &on) in kinds.iter().enumerate() { + role.modules[kind][2] += if on { wall } else { 0 }; + } + if let Some(kind) = leaf_kind { + role.modules[kind as usize][0] += wall; + } + // Whose time it is: the innermost frame that is not the + // system's (a kernel call is its caller's). + let owner = path + .iter() + .filter_map(|&(_, kind)| kind) + .find(|&kind| !matches!(kind, Kind::System | Kind::Other)) + .or(leaf_kind); + if let Some(kind) = owner { + role.modules[kind as usize][1] += wall; + } + let ours = |&(func, kind): &(u32, Option)| { + kind == Some(Kind::Ours) && !symbols.funcs[func as usize].runtime + }; + if symbols.funcs[leaf as usize].wait { + role.waiting += wall; + per_thread[t][2] += wall; + // The function of ours that waited (the title's, on a + // thread with none of ours), and what lies between. + let caller = path + .iter() + .position(ours) + .or_else(|| path.iter().position(|p| p.1 == Some(Kind::Title))); + let between = &path[..caller.unwrap_or(path.len())]; + let names: Vec<&str> = between + .iter() + .map(|&(f, _)| &*symbols.funcs[f as usize].name) + .collect(); + let through = between.iter().filter_map(|&(_, kind)| kind).find(|kind| { + matches!( + kind, + Kind::Driver | Kind::Direct3d | Kind::Title | Kind::Other + ) + }); + let caller = caller.map_or(u32::MAX, |at| path[at].0); + *role + .waits + .entry((wait_kind(&names), caller, through)) + .or_default() += wall; + } + let resolved = &symbols.resolved[named[t][i] as usize]; + if let Some(line) = resolved.line { + *role.lines.entry((line, leaf)).or_default() += wall; + } + let stack: Vec = path.iter().rev().map(|&(f, _)| f).collect(); + *role.stacks.entry(stack).or_default() += wall; + } + } + + // Written out. + let frames = self.presented; + let seconds = self.wall as f64 / 1e6; + // Microseconds to the unit of the tables. + let (unit, per) = if frames > 0 { + ("ms a frame", 1000.0 * frames as f64) + } else { + ("ms a second", 1000.0 * seconds.max(1e-9)) + }; + let ms = |us: u64| us as f64 / per; + let share = |us: u64, of: u64| 100.0 * us as f64 / of.max(1) as f64; + let name = |func: u32| match symbols.funcs.get(func as usize) { + Some(func) => &*func.name, + None => "[no function of ours or the title's]", + }; + // For the tables: a long name's start and end (the stacks file has it whole). + let short = |func: u32, most: usize| { + let name = name(func); + let chars = name.chars().count(); + if chars <= most { + return name.to_owned(); + } + let head: String = name.chars().take(most * 2 / 3).collect(); + let tail: String = name.chars().skip(chars - most / 3).collect(); + format!("{head}...{tail}") + }; + let mut text = String::new(); + let mut folded = String::new(); + let mut summaries = Vec::new(); + let w = &mut text; + let _ = writeln!(w, "Leonida Legacy profile, process {}", std::process::id()); + let _ = writeln!( + w, + "sampled {seconds:.1} s in {} looks ({} asked a second, {:.2} ms between looks, {} late); \ + {frames} frames presented meanwhile{}", + self.ticks, + self.config.hz, + self.wall as f64 / 1000.0 / self.ticks.max(1) as f64, + self.late, + if frames > 0 { + format!( + " ({:.1} ms a frame)", + self.wall as f64 / 1000.0 / frames as f64 + ) + } else { + " (none: the tables are per second of sampling)".to_owned() + }, + ); + let alive = self.threads.iter().filter(|t| t.alive).count(); + let _ = writeln!( + w, + "{} threads followed ({alive} still running); a thread looked at stood still under {:.0} us \ + half the times, under {:.0} us 99 in 100, {:.0} us at longest, {:.1} us on average, {} \ + times; {} call sites kept{}", + self.threads.len(), + stood.0, + stood.1, + self.held_longest as f64 / 1000.0, + self.held_ns as f64 / 1000.0 / self.held.max(1) as f64, + self.held, + self.nodes, + if self.nodes >= MOST_NODES { + " (FULL: later new stacks are one line)" + } else { + "" + }, + ); + if self.config.budget > 0.0 { + let _ = writeln!( + w, + "a thread may stand still for looks {:.1} % of its time (LEONIDA_PROFILE_BUDGET): one \ + whose looks cost more is looked at every 2nd, 3rd... tick while it runs (\"every\" \ + below); its samples stand for more time each, so the times stay right", + 100.0 * self.config.budget + ); + } + let (mine, since) = (own_cpu(), self.clock.elapsed()); + let _ = writeln!( + w, + "the sampler's thread used {:.1} % of one processor", + 100.0 * mine.as_secs_f64() / since.as_secs_f64().max(1e-9), + ); + let _ = writeln!( + w, + "names of ours: {}", + match (&symbols.dbghelp, &symbols.pdb) { + (None, _) => + "dbghelp.dll could not be used: every frame is module+offset".to_owned(), + (Some(_), (true, pdb)) => format!("from {pdb}"), + (Some(_), (false, _)) => + "NO PDB FOUND for the executable: its frames are module+offset of each \ + function's start (keep leonida.pdb beside leonida.exe)" + .to_owned(), + } + ); + let _ = writeln!(w); + let _ = writeln!( + w, + "How to read. Every number is {unit} unless it is a %. A role's time is its threads' \ + together: five recording threads can make more than a frame." + ); + let _ = writeln!( + w, + " own time with the function as the innermost frame; a call into the kernel \ + (ntdll!Nt..., win32u!Nt...) is the kernel working or waiting for that caller" + ); + let _ = writeln!(w, " with own time plus everything the function called"); + let _ = writeln!( + w, + " on cpu share of the own time the thread was on a processor (its cycle counter): \ + low means it stood there blocked" + ); + let _ = writeln!( + w, + " waiting samples whose innermost frame is one of the kernel's waits; under WAITS \ + they are given to the function of ours that waited" + ); + let _ = writeln!( + w, + " looks times a thread was sampled; not susp: of those, the ones answered without \ + suspending it (it had not run since the look before); cut: stacks that did not reach \ + the thread's first frame; look us: what a suspension of it takes" + ); + let _ = writeln!( + w, + " title+0x1234 is the title's function starting at that offset; \ + nvwgf2umx.dll+0x1234 a driver function with no name; [frames not kept] marks stacks \ + deeper than {} frames or {} KB", + self.config.depth, + self.config.stack >> 10, + ); + let _ = writeln!(w); + let _ = writeln!(w, "THREADS"); + let _ = writeln!( + w, + " {:<10} {:>7} {:<30} {:>9} {:>8} {:>9} {:>9} {:>8} {:>7} {:>7} {:>5} {:>8} mostly in (own time)", + "role", + "thread", + "name, or where it started", + unit, + "on cpu %", + "waiting %", + "looks", + "not susp", + "failed", + "cut", + "every", + "look us" + ); + for role in Role::ALL { + for &t in &roles[role as usize].threads { + let thread = &self.threads[t]; + let [wall, cpu, waiting] = per_thread[t]; + let said = if thread.name.is_empty() { + let start = &symbols.resolved[starts[t] as usize]; + format!("at {}", short(start.funcs[0], 27)) + } else { + thread.name.chars().take(30).collect::() + }; + let top = mostly[t].iter().max_by_key(|&(&func, &us)| (us, func)); + let top = top.map_or(String::new(), |(&func, &us)| { + format!(" {} ({:.0} %)", short(func, 70), share(us, wall)) + }); + let _ = writeln!( + w, + " {:<10} {:>7} {:<30} {:>9.1} {:>8.1} {:>9.1} {:>9} {:>8} {:>7} {:>7} {:>5} {:>8.1}{}{top}", + role.name(), + thread.id, + said, + ms(wall), + share(cpu, wall), + share(waiting, wall), + thread.looks, + thread.reused, + thread.missed, + thread.cut, + thread.every, + thread.cost / 1000.0, + if thread.alive { "" } else { " (ended)" }, + ); + } + } + for role in Role::ALL { + let r = &roles[role as usize]; + if r.wall == 0 { + continue; + } + let _ = writeln!(w); + let _ = writeln!( + w, + "=== {} === {} thread{}: {:.1} {unit}, on a processor {:.1} ({:.0} %), waiting {:.1} ({:.0} %)", + role.says(), + r.threads.len(), + if r.threads.len() == 1 { "" } else { "s" }, + ms(r.wall), + ms(r.cpu), + share(r.cpu, r.wall), + ms(r.waiting), + share(r.waiting, r.wall), + ); + let _ = writeln!( + w, + " BY MODULE (own: the innermost frame's; for: system time given to the nearest \ + caller that is ours, the driver's, Direct3D's or the title's; with: anywhere on \ + the stack above the thread's start)" + ); + let _ = writeln!( + w, + " {:<18} {:>9} {:>6} {:>9} {:>6} {:>9} {:>6}", + "", "own", "%", "for", "%", "with", "%" + ); + for (kind, label) in KINDS.iter().enumerate() { + let [own, owner, all] = r.modules[kind]; + let _ = writeln!( + w, + " {:<18} {:>9.2} {:>6.1} {:>9.2} {:>6.1} {:>9.2} {:>6.1}", + label, + ms(own), + share(own, r.wall), + ms(owner), + share(owner, r.wall), + ms(all), + share(all, r.wall), + ); + } + let mut rows: Vec<(u32, Row)> = r.funcs.iter().map(|(&f, &row)| (f, row)).collect(); + let table = |w: &mut String, title: &str, rows: &[(u32, Row)]| { + let _ = writeln!(w, " {title}"); + let _ = writeln!( + w, + " {:>9} {:>6} {:>9} {:>6} {:>7} function", + "own", "%", "with", "%", "on cpu%" + ); + for &(func, row) in rows.iter().take(40) { + let _ = writeln!( + w, + " {:>9.2} {:>6.1} {:>9.2} {:>6.1} {:>7} {}", + ms(row.own), + share(row.own, r.wall), + ms(row.all), + share(row.all, r.wall), + if row.own > 0 { + format!("{:.0}", share(row.cpu, row.own)) + } else { + "-".into() + }, + short(func, 150), + ); + } + }; + rows.sort_by(|a, b| b.1.own.cmp(&a.1.own).then(a.0.cmp(&b.0))); + let own = rows.iter().take_while(|row| row.1.own > 0).count(); + table(&mut *w, "FUNCTIONS BY OWN TIME (top 40)", &rows[..own]); + // Every stack of a thread has its start-up frames: they say nothing. + rows.retain(|&(func, _)| { + let func = &symbols.funcs[func as usize]; + let start = ["!RtlUserThreadStart", "!BaseThreadInitThunk"]; + !func.runtime && !start.iter().any(|s| func.name.ends_with(s)) + }); + rows.sort_by(|a, b| b.1.all.cmp(&a.1.all).then(a.0.cmp(&b.0))); + table( + &mut *w, + "FUNCTIONS WITH WHAT THEY CALL (top 40; without the thread's start and the language's runtime)", + &rows, + ); + let mut waits: Vec<_> = r.waits.iter().map(|(&key, &us)| (us, key)).collect(); + waits.sort_by(|a, b| b.0.cmp(&a.0).then(a.1.1.cmp(&b.1.1))); + if !waits.is_empty() { + let _ = writeln!( + w, + " WAITS ({:.1} {unit}, {:.0} % of the role), by the function that waited", + ms(r.waiting), + share(r.waiting, r.wall) + ); + let _ = writeln!( + w, + " {:>9} {:>6} {:<24} {:<16} waited in", + "", "%", "kind", "inside" + ); + for &(us, (kind, caller, through)) in waits.iter().take(30) { + let _ = writeln!( + w, + " {:>9.2} {:>6.1} {:<24} {:<16} {}", + ms(us), + share(us, r.wall), + kind, + through.map_or("-", |kind| KINDS[kind as usize]), + short(caller, 150), + ); + } + } + let mut lines: Vec<_> = r.lines.iter().map(|(&key, &us)| (us, key)).collect(); + lines.sort_by(|a, b| b.0.cmp(&a.0).then(a.1.cmp(&b.1))); + if !lines.is_empty() { + let _ = writeln!(w, " HOTTEST LINES OF OURS (own time)"); + for &(us, (line, func)) in lines.iter().take(25) { + let _ = writeln!( + w, + " {:>9.2} {:>6.1} {} ({})", + ms(us), + share(us, r.wall), + symbols.lines[line as usize], + short(func, 100), + ); + } + } + let mut stacks: Vec<(&Vec, u64)> = + r.stacks.iter().map(|(s, &us)| (s, us)).collect(); + stacks.sort_by(|a, b| b.1.cmp(&a.1).then(a.0.cmp(b.0))); + let fold = |stack: &[u32]| { + let mut line = String::from(role.name()); + for &func in stack { + line.push(';'); + line.extend(name(func).chars().map(|c| match c { + ';' => ':', + ' ' => '_', + c => c, + })); + } + line + }; + let _ = writeln!( + w, + " STACKS (the 12 heaviest of {}, their innermost 10 frames, {unit}; all of them \ + whole, in microseconds, in the .folded file)", + stacks.len() + ); + for &(stack, us) in stacks.iter().take(12) { + let from = stack.len().saturating_sub(10); + let _ = writeln!( + w, + " {:>9.2} {:>6.1} {}{}", + ms(us), + share(us, r.wall), + if from > 0 { "... " } else { "" }, + stack[from..] + .iter() + .map(|&f| short(f, 60)) + .collect::>() + .join(" > "), + ); + } + let least = (FOLD_LEAST * r.wall as f64) as u64; + let mut rest = 0; + for &(stack, us) in &stacks { + if us >= least { + let _ = writeln!(folded, "{} {us}", fold(stack)); + } else { + rest += us; + } + } + if rest > 0 { + let _ = writeln!( + folded, + "{};[stacks_under_{:.3}_%_each] {rest}", + role.name(), + 100.0 * FOLD_LEAST + ); + } + summaries.push(RoleSummary { + role, + wall: r.wall, + waiting: r.waiting, + functions: r + .funcs + .iter() + .map(|(&f, row)| (name(f).to_owned(), row.own, row.all)) + .collect(), + waits: waits + .iter() + .map(|&(us, (kind, caller, _))| (kind.to_owned(), name(caller).to_owned(), us)) + .collect(), + }); + } + let _ = writeln!(w); + let _ = writeln!( + w, + "(this report took {:.0} ms to write; sampling stood still meanwhile)", + began.elapsed().as_secs_f64() * 1000.0 + ); + Report { + text, + folded, + roles: summaries, + } + } + + /// Writes the report and the stacks file, each whole or not at all (a + /// process ended in the middle leaves the last ones). + fn write(&mut self) { + let report = self.report(); + let out = self.config.out.clone(); + let put = |file: PathBuf, text: &str| { + let mut partial = file.clone().into_os_string(); + partial.push(".part"); + std::fs::write(&partial, text).and_then(|()| std::fs::rename(&partial, &file)) + }; + let mut stacks = out.clone().into_os_string(); + stacks.push(".folded"); + let written = + put(out.clone(), &report.text).and_then(|()| put(stacks.into(), &report.folded)); + static SAID: AtomicBool = AtomicBool::new(false); + match written { + Ok(()) if !SAID.swap(true, Relaxed) => { + tracing::info!(file = %out.display(), "profile written (and again as the run goes on; the stacks for a flame graph are beside it, .folded)"); + } + Ok(()) => {} + Err(e) => tracing::warn!(error = %e, file = %out.display(), "profile not written"), + } + self.resync(); + } +} + +/// The processor time the calling thread has used. +fn own_cpu() -> Duration { + use windows_sys::Win32::Foundation::FILETIME; + let zero = FILETIME { + dwLowDateTime: 0, + dwHighDateTime: 0, + }; + let (mut created, mut exited, mut kernel, mut user) = (zero, zero, zero, zero); + // SAFETY: our own thread and four valid out pointers. + unsafe { + GetThreadTimes( + GetCurrentThread(), + &mut created, + &mut exited, + &mut kernel, + &mut user, + ) + }; + let ticks = |t: FILETIME| u64::from(t.dwHighDateTime) << 32 | u64::from(t.dwLowDateTime); + Duration::from_nanos((ticks(kernel) + ticks(user)) * 100) +} + +// --------------------------------------------------------------------- +// The sampler's thread. +// --------------------------------------------------------------------- + +/// Asks the sampler to write its last report and end; set when it has. +static STOP: AtomicBool = AtomicBool::new(false); +static DONE: AtomicBool = AtomicBool::new(false); +/// The sampler's thread, as a handle: to see at exit whether it still runs. +static SAMPLER: std::sync::atomic::AtomicPtr = + std::sync::atomic::AtomicPtr::new(null_mut()); + +unsafe extern "C" { + fn atexit(f: extern "C" fn()) -> i32; +} + +/// At process exit (registered after the loader's own exit function, so +/// run before it ends the other threads): the last report is written. +extern "C" fn at_exit() { + STOP.store(true, Relaxed); + let thread = SAMPLER.load(Relaxed); + let waiting = Instant::now(); + while !DONE.load(Relaxed) && waiting.elapsed() < Duration::from_secs(10) { + // SAFETY: the sampler's thread handle, never closed; signalled + // when the thread is gone, however it went. + if thread.is_null() || unsafe { WaitForSingleObject(thread, 5) } == 0 { + break; + } + } +} + +/// The sampler's clock: a timer of the system's finer kind, which fires +/// every period by itself where the period is whole milliseconds (a +/// sleep of a millisecond takes one and a half). +struct Pace { + timer: HANDLE, + period: Duration, + /// The timer fires by itself; otherwise it is set before each wait, + /// for `next`. + repeats: bool, + next: Instant, + /// Microseconds a tick is put off by at most, and the state of the + /// numbers that say by how much. + jitter: u64, + random: u64, +} + +impl Pace { + fn new(hz: u32, jitter: u64) -> Pace { + use windows_sys::Win32::System::Threading::{ + CREATE_WAITABLE_TIMER_HIGH_RESOLUTION, CreateWaitableTimerExW, SetWaitableTimer, + }; + let hz = hz.max(1); + let period = Duration::from_secs_f64(1.0 / f64::from(hz)); + // SAFETY: makes a timer of ours (all access), unnamed. + let timer = unsafe { + CreateWaitableTimerExW( + null(), + null(), + CREATE_WAITABLE_TIMER_HIGH_RESOLUTION, + 0x1f_0003, + ) + }; + let mut repeats = false; + if !timer.is_null() && hz <= 1000 && 1000 % hz == 0 { + // First in a period from now (100 ns units, negative: from + // now), then every period (milliseconds). + let first = -(period.as_nanos() as i64 / 100); + // SAFETY: our timer; no completion routine. + repeats = unsafe { + SetWaitableTimer(timer, &first, (1000 / hz) as i32, None, null(), 0) != 0 + }; + } + Pace { + timer, + period, + repeats, + next: Instant::now() + period, + // Less than the period, so ticks stay in order. + jitter: jitter.min(period.as_micros() as u64 / 2), + random: 0x9e37_79b9_7f4a_7c15, + } + } + + /// Waits for the next tick. + /// + /// The timer wakes us on the system's clock, and so are woken the + /// threads that sleep: looked at then, a thread that sleeps a + /// millisecond at a time is always just waking (a test's sleeping + /// thread was seen out of its wait 12 % of the time; it is 0.5 %). So + /// the look is put off by a time that differs from tick to tick, + /// spent spinning: no timer is that fine. + fn wait(&mut self) { + self.wait_for_timer(); + if self.jitter > 0 { + self.random ^= self.random << 13; + self.random ^= self.random >> 7; + self.random ^= self.random << 17; + let until = Instant::now() + Duration::from_micros(self.random % (self.jitter + 1)); + while Instant::now() < until { + std::hint::spin_loop(); + } + } + } + + fn wait_for_timer(&mut self) { + use windows_sys::Win32::System::Threading::{INFINITE, SetWaitableTimer}; + if self.repeats { + // SAFETY: our timer. + unsafe { WaitForSingleObject(self.timer, INFINITE) }; + return; + } + let now = Instant::now(); + if self.next > now { + let due = -((self.next - now).as_nanos() as i64 / 100).max(1); + // SAFETY: our timer, set to fire once and waited for. + let set = !self.timer.is_null() + && unsafe { SetWaitableTimer(self.timer, &due, 0, None, null(), 0) } != 0; + if set { + // SAFETY: our timer. + unsafe { WaitForSingleObject(self.timer, INFINITE) }; + } else { + std::thread::sleep(self.next - now); + } + } + // A tick that came late is not made up for: the next is a period on. + self.next = (self.next + self.period).max(Instant::now()); + } +} + +/// Starts the sampler; false if its thread could not be made. +fn start(config: Config) -> bool { + use std::os::windows::io::IntoRawHandle; + let says = format!( + "profiling (LEONIDA_PROFILE=1): {} looks a second at the submitting, recording and worker \ + threads, the report in {} every {:.0} s and at exit", + config.hz, + config.out.display(), + config.every + ); + match std::thread::Builder::new() + .name("leonida-profile".into()) + .spawn(move || run(config)) + { + Ok(thread) => { + SAMPLER.store(thread.into_raw_handle().cast(), Relaxed); + // SAFETY: registers a function with the host CRT's exit table. + unsafe { atexit(at_exit) }; + tracing::info!("{says}"); + true + } + Err(e) => { + tracing::warn!(error = %e, "no thread for the profiler"); + false + } + } +} + +fn run(config: Config) { + // Above the threads it looks at: a late look stretches a sample, and + // a sampler taken off its processor between suspending a thread and + // letting it go leaves that thread standing. It sleeps most of the time. + // SAFETY: a plain call on our own thread. + unsafe { SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_TIME_CRITICAL) }; + let wait = |seconds: f64| { + let until = Instant::now() + Duration::from_secs_f64(seconds); + while Instant::now() < until && !STOP.load(Relaxed) { + std::thread::sleep(Duration::from_millis(20)); + } + }; + wait(config.after); + let mut pace = Pace::new(config.hz, config.jitter); + let (every, length) = ( + Duration::from_secs_f64(config.every), + config.length.map(Duration::from_secs_f64), + ); + let mut sampler = Sampler::new(config); + sampler.rescan(); + sampler.resync(); + let began = Instant::now(); + let (mut scan, mut report) = (began + SCAN, began + every); + while !STOP.load(Relaxed) && length.is_none_or(|length| began.elapsed() < length) { + pace.wait(); + sampler.tick(); + let now = Instant::now(); + if now >= scan { + sampler.rescan(); + scan = now + SCAN; + } + if now >= report { + sampler.write(); + report = Instant::now() + every; + } + } + sampler.write(); + DONE.store(true, Relaxed); +} + +/// Between two searches for threads to follow. +const SCAN: Duration = Duration::from_secs(1); + +#[cfg(test)] +mod tests; diff --git a/crates/leonida-gpu/src/profile/tests.rs b/crates/leonida-gpu/src/profile/tests.rs new file mode 100644 index 000000000..07d3104b4 --- /dev/null +++ b/crates/leonida-gpu/src/profile/tests.rs @@ -0,0 +1,1005 @@ +//! The profiler on threads whose work is known. No graphics card is used. + +use super::*; +use std::sync::atomic::AtomicBool; +use std::sync::{Arc, Mutex, mpsc}; + +fn config(hz: u32) -> Config { + Config::new(hz, std::env::temp_dir().join("leonida_profile_test.txt")) +} + +/// Starts a thread running `work` and returns its id once it runs. +fn thread(work: impl FnOnce() + Send + 'static) -> (u32, std::thread::JoinHandle<()>) { + let (said, hears) = mpsc::channel(); + let running = std::thread::spawn(move || { + // SAFETY: a plain query. + said.send(unsafe { GetCurrentThreadId() }).unwrap(); + work(); + }); + (hears.recv().unwrap(), running) +} + +/// Looks at the followed threads for `time`, a look every `period`, with +/// `frames` presents spread over it. +fn sample(sampler: &mut Sampler, time: Duration, period: Duration, frames: &AtomicU64, each: u64) { + sampler.resync(); + let began = Instant::now(); + let mut looks = 0u64; + while began.elapsed() < time { + std::thread::sleep(period); + sampler.tick(); + looks += 1; + if each > 0 && looks.is_multiple_of(each) { + frames.fetch_add(1, Relaxed); + } + } +} + +#[inline(never)] +fn profile_test_spin_inner(stop: &AtomicBool) -> u64 { + let mut sum = 0u64; + while !stop.load(Relaxed) { + for i in 0..2000u64 { + sum = std::hint::black_box(sum.wrapping_mul(31).wrapping_add(i)); + } + } + sum +} + +#[inline(never)] +fn profile_test_spins(stop: &AtomicBool) -> u64 { + std::hint::black_box(profile_test_spin_inner(stop)).wrapping_add(1) +} + +#[inline(never)] +fn profile_test_sleeps(stop: &AtomicBool) -> u64 { + let mut naps = 0; + while !stop.load(Relaxed) { + std::thread::sleep(Duration::from_millis(5)); + naps = std::hint::black_box(naps + 1); + } + naps +} + +#[inline(never)] +fn profile_test_locks(lock: &Mutex) -> u64 { + let mut held = lock.lock().unwrap(); + *held += 1; + std::hint::black_box(*held) +} + +#[inline(never)] +fn profile_test_deep(left: u32, stop: &AtomicBool) -> u64 { + // A frame of a kilobyte, so a hundred of them pass any small limit. + let mut room = [0u64; 128]; + room[left as usize % 128] = u64::from(left); + let room = std::hint::black_box(room); + let below = if left == 0 { + profile_test_sleeps(stop) + } else { + profile_test_deep(left - 1, stop) + }; + std::hint::black_box(below.wrapping_add(room[3])) +} + +/// Whether `address` is committed code. +fn executable(address: u64) -> bool { + use windows_sys::Win32::System::Memory::{MEM_COMMIT, MEMORY_BASIC_INFORMATION, VirtualQuery}; + // SAFETY: a zeroed MEMORY_BASIC_INFORMATION is valid; the query reads + // the address space's bookkeeping, not `address`. + unsafe { + let mut info: MEMORY_BASIC_INFORMATION = std::mem::zeroed(); + VirtualQuery(address as *const _, &mut info, size_of_val(&info)) != 0 + && info.State == MEM_COMMIT + && info.Protect & 0xf0 != 0 + && info.Protect & 0x100 == 0 + } +} + +fn own(role: &RoleSummary, what: &str) -> u64 { + role.functions + .iter() + .filter(|f| f.0.contains(what)) + .map(|f| f.1) + .sum() +} + +fn with(role: &RoleSummary, what: &str) -> u64 { + role.functions + .iter() + .filter(|f| f.0.contains(what)) + .map(|f| f.2) + .max() + .unwrap_or(0) +} + +fn role(report: &Report, role: Role) -> &RoleSummary { + report + .roles + .iter() + .find(|r| r.role == role) + .unwrap_or_else(|| panic!("no {role:?} in\n{}", report.text)) +} + +/// A busy loop in one function, a sleep in another, a wait for a lock in +/// a third: the report gives each thread's time to the right one, as +/// running or as waiting, and per frame. +#[test] +fn time_goes_to_the_function_that_spent_it() { + static PRESENTS: AtomicU64 = AtomicU64::new(0); + let stop = Arc::new(AtomicBool::new(false)); + let lock = Arc::new(Mutex::new(0u64)); + let held = lock.lock().unwrap(); + let (spinning, a) = thread({ + let stop = stop.clone(); + move || { + std::hint::black_box(profile_test_spins(&stop)); + } + }); + let (sleeping, b) = thread({ + let stop = stop.clone(); + move || { + std::hint::black_box(profile_test_sleeps(&stop)); + } + }); + let (locked, c) = thread({ + let lock = lock.clone(); + move || { + std::hint::black_box(profile_test_locks(&lock)); + } + }); + std::thread::sleep(Duration::from_millis(50)); + + let mut sampler = Sampler::new(config(1000)); + sampler.presents = &PRESENTS; + sampler.follow(spinning, Role::Submit, null_mut(), Some("spins".into())); + sampler.follow(sleeping, Role::Record, null_mut(), Some("sleeps".into())); + sampler.follow(locked, Role::Wide, null_mut(), Some("locks".into())); + assert_eq!(sampler.threads.len(), 3); + assert!( + sampler.threads.iter().all(|t| t.low != 0 && t.low < t.high), + "stack bounds" + ); + sample( + &mut sampler, + Duration::from_millis(1500), + Duration::from_millis(1), + &PRESENTS, + 20, + ); + let report = sampler.report(); + stop.store(true, Relaxed); + drop(held); + for running in [a, b, c] { + running.join().unwrap(); + } + println!("{}", report.text); + assert!(sampler.presented >= 20, "{} frames", sampler.presented); + assert!( + sampler.symbols.as_ref().is_some_and(|s| s.pdb.0), + "the test's PDB was not found" + ); + + // The busy loop: all of it in the inner function, called from the outer. + let spins = role(&report, Role::Submit); + assert!(spins.wall >= 1_200_000, "{} us sampled", spins.wall); + // (An unoptimised build calls the loop's own pieces; an optimised one + // has them inside it.) + let inner = with(spins, "profile_test_spin_inner"); + assert!( + inner * 100 >= spins.wall * 95, + "inner {inner} of {}", + spins.wall + ); + assert!(with(spins, "profile_test_spins") * 100 >= spins.wall * 95); + assert!(own(spins, "profile_test_spins") * 100 <= spins.wall * 5); + assert!( + spins.waiting * 100 <= spins.wall * 5, + "waiting {}", + spins.waiting + ); + // Every sample is some function's own time, once. + assert_eq!(spins.functions.iter().map(|f| f.1).sum::(), spins.wall); + + // The sleep: waiting, for the function that slept. + let sleeps = role(&report, Role::Record); + assert!( + sleeps.waiting * 100 >= sleeps.wall * 85, + "{} of {}", + sleeps.waiting, + sleeps.wall + ); + let (kind, caller, time) = &sleeps.waits[0]; + assert!( + kind == "sleep" && caller.contains("profile_test_sleeps"), + "{kind}, {caller}" + ); + assert!(time * 100 >= sleeps.waiting * 95); + + // The lock: waiting, for the function that wanted it. + let locks = role(&report, Role::Wide); + assert!( + locks.waiting * 100 >= locks.wall * 95, + "{} of {}", + locks.waiting, + locks.wall + ); + let (kind, caller, _) = &locks.waits[0]; + assert!( + kind == "lock (ours)" && caller.contains("profile_test_locks"), + "{kind}, {caller}" + ); + + // Per frame, and the stacks for a flame graph: outer before inner. + assert!(report.text.contains("ms a frame")); + let stack = report + .folded + .lines() + .find(|l| l.starts_with("submit;") && l.contains("profile_test_spin_inner")) + .unwrap_or_else(|| panic!("{}", report.folded)); + let (outer, inner) = ( + stack.find("profile_test_spins").unwrap(), + stack.find("profile_test_spin_inner").unwrap(), + ); + assert!(outer < inner, "{stack}"); + // The thread that waited the whole time was suspended once at most a + // few times: it had not run since the look before. + let waiting = sampler.threads.iter().find(|t| t.id == locked).unwrap(); + assert!( + waiting.reused * 10 >= waiting.looks * 9, + "{} of {}", + waiting.reused, + waiting.looks + ); +} + +/// A stack deeper than is kept, and one longer than is copied: the +/// innermost frames are still named, and the stack is marked as cut. +#[test] +fn deep_stacks_are_cut_not_lost() { + let stop = Arc::new(AtomicBool::new(false)); + let (deep, running) = thread({ + let stop = stop.clone(); + move || { + std::hint::black_box(profile_test_deep(150, &stop)); + } + }); + std::thread::sleep(Duration::from_millis(50)); + for (depth, stack) in [(24, 128 << 10), (MAX_DEPTH, 8 << 10)] { + static PRESENTS: AtomicU64 = AtomicU64::new(0); + let mut settings = config(500); + (settings.depth, settings.stack, settings.reuse) = (depth, stack, false); + let mut sampler = Sampler::new(settings); + sampler.presents = &PRESENTS; + sampler.follow(deep, Role::Busy, null_mut(), None); + sample( + &mut sampler, + Duration::from_millis(300), + Duration::from_millis(2), + &PRESENTS, + 0, + ); + let report = sampler.report(); + let thread = &sampler.threads[0]; + assert!( + thread.looks > 20 && thread.missed == 0, + "{} looks", + thread.looks + ); + assert_eq!( + thread.cut, thread.looks, + "depth {depth}, {stack} bytes copied" + ); + let busy = role(&report, Role::Busy); + assert!( + with(busy, "[frames not kept]") * 100 >= busy.wall * 99, + "{}", + report.text + ); + assert!( + with(busy, "profile_test_sleeps") * 100 >= busy.wall * 90, + "{}", + report.text + ); + assert!(report.text.contains("ms a second")); + } + stop.store(true, Relaxed); + running.join().unwrap(); +} + +/// Registers and stack bytes that mean nothing, at addresses inside real +/// code: the walk stops, and reads nothing outside its copy (a read +/// elsewhere would end the test with an access violation). +#[test] +fn stacks_that_mean_nothing_are_walked_without_a_fault() { + let mut symbols = Symbols::new(false); + symbols.refresh(); + let modules: Vec<(u64, u64)> = symbols.modules.iter().map(|m| (m.base, m.end)).collect(); + assert!(modules.len() > 3); + let mut sampler = Sampler::new(config(1000)); + // SAFETY: a plain query. + let me = unsafe { GetCurrentThreadId() }; + // A thread entry is all the walk needs; this one is never suspended. + sampler.follow(me, Role::Busy, null_mut(), None); + let mut state = 0x9e37_79b9_7f4a_7c15u64; + let mut next = move || { + state ^= state << 13; + state ^= state >> 7; + state ^= state << 17; + state + }; + // Return instructions (bytes that read as one) in the modules' code. + let mut returns = Vec::new(); + while returns.len() < 20_000 { + let r = next(); + let (base, end) = modules[(r >> 32) as usize % modules.len()]; + let at = base + 0x1000 + r % (end - base - 0x1000).max(1); + if !executable(at) { + continue; + } + // SAFETY: committed code of a loaded module, as just asked, to + // the end of its page. + let bytes = + unsafe { std::slice::from_raw_parts(at as *const u8, 0x1000 - (at as usize & 0xfff)) }; + if let Some(ret) = bytes.iter().skip(16).position(|&b| b == 0xc3) { + returns.push(at + 16 + ret as u64); + } + } + let limit = sampler.config.stack; + let (mut walked, mut frames) = (0u64, 0u64); + let rounds = env_number("LEONIDA_PROFILE_TEST_WALKS").map_or(60_000, |n| n as u64); + for round in 0..rounds { + let got = (next() as usize % limit) & !7; + // A pretended stack somewhere, or the thread's own range. + let rsp = if round.is_multiple_of(2) { + (0x7000_0000_0000u64 + (next() & 0xffff_fff0)) as usize + } else { + sampler.threads[0].low + 0x1000 + (next() as usize & 0xff8) + }; + let code = |r: u64| { + if r.is_multiple_of(3) { + // A few bytes before a return: where functions end. + return returns[(r >> 32) as usize % returns.len()] - (r >> 8 & 15); + } + let (base, end) = modules[(r >> 32) as usize % modules.len()]; + base + 0x1000 + r % (end - base - 0x1000).max(1) + }; + // The copy: words that are nothing, stack addresses, code addresses. + for at in (0..got).step_by(8) { + let r = next(); + let word = match r % 4 { + 0 => r, + 1 => (rsp + (next() as usize % (got + 4096))) as u64, + 2 => code(next()), + _ => r & 0xffff, + }; + // SAFETY: inside the copy. + unsafe { + sampler + .copy + .add((rsp & 15) + at) + .cast::() + .write_unaligned(word) + }; + } + let end = (rsp & 15) + got; + if end < sampler.dirty { + // SAFETY: inside the copy. + unsafe { sampler.copy.add(end).write_bytes(0, sampler.dirty - end) }; + } + sampler.dirty = end; + let context = &mut sampler.context.0; + for register in [ + &mut context.Rax, + &mut context.Rbx, + &mut context.Rcx, + &mut context.Rdx, + &mut context.Rbp, + &mut context.Rsi, + &mut context.Rdi, + &mut context.R8, + &mut context.R9, + &mut context.R10, + &mut context.R11, + &mut context.R12, + &mut context.R13, + &mut context.R14, + &mut context.R15, + ] { + let r = next(); + *register = match r % 3 { + 0 => r, + 1 => (rsp + (next() as usize % (got + 4096))) as u64, + _ => r & 0xfff, + }; + } + context.Rsp = rsp as u64; + context.Rip = code(next()); + let (count, _, used) = sampler.walk(0, got); + assert!(used <= got + 8, "{used} of {got}"); + walked += 1; + frames += count as u64; + } + println!("{walked} walks of stacks that mean nothing, {frames} frames"); + assert!(frames > walked); +} + +/// The walk of another thread's copied stack names the same callers as +/// the system's own walk of that thread by itself. +#[test] +fn the_walk_in_the_copy_is_the_systems_walk() { + use windows_sys::Win32::System::Diagnostics::Debug::RtlCaptureStackBackTrace; + let (said, hears) = mpsc::channel(); + let (go, wait) = mpsc::channel::<()>(); + #[inline(never)] + fn profile_test_parked(said: &mpsc::Sender>, wait: &mpsc::Receiver<()>) -> u64 { + let mut own = [null_mut(); 32]; + // SAFETY: writes at most 32 return addresses into `own`. + let n = unsafe { RtlCaptureStackBackTrace(0, 32, own.as_mut_ptr(), null_mut()) }; + said.send(own[..usize::from(n)].iter().map(|&a| a as u64).collect()) + .unwrap(); + wait.recv().ok(); + std::hint::black_box(u64::from(n)) + } + let (parked, running) = thread(move || { + std::hint::black_box(profile_test_parked(&said, &wait)); + }); + let own = hears.recv().unwrap(); + std::thread::sleep(Duration::from_millis(50)); + let mut sampler = Sampler::new(config(1000)); + sampler.follow(parked, Role::Busy, null_mut(), None); + let (got, _) = sampler.capture(0).expect("the thread is looked at"); + let (frames, whole, used) = sampler.walk(0, got); + assert!(used > 64 && used <= got, "{used} of {got} bytes"); + let walked: Vec = sampler.frames[..frames].to_vec(); + go.send(()).unwrap(); + running.join().unwrap(); + assert!(whole, "{frames} frames"); + // The system's walk starts in the function that asked; ours deeper, in + // the wait. From that function's caller on they are the same calls + // (ours keeps the byte before each return address). + let callers: Vec = own[1..].iter().map(|a| a - 1).collect(); + assert!(callers.len() >= 3, "{own:x?}"); + let at = walked + .iter() + .position(|&a| a == callers[0]) + .unwrap_or_else(|| panic!("{walked:x?} {callers:x?}")); + assert_eq!( + &walked[at..], + &callers[..], + "ours {walked:x?}, the system's {own:x?}" + ); +} + +#[test] +fn names_say_what_waits_and_whose_code_it_is() { + assert!(waits("ntdll!NtWaitForSingleObject")); + assert!(waits("ntdll!ZwWaitForAlertByThreadId")); + assert!(waits("ntdll!NtDelayExecution")); + assert!(waits( + "win32u!NtGdiDdDDIWaitForSynchronizationObjectFromCpu" + )); + assert!(!waits("ntdll!NtQueryVirtualMemory")); + assert!(!waits("ntdll!NtYieldExecution")); + assert!(!waits("leonida_gpu::host::Host::submit")); + assert_eq!( + wait_kind(&[ + "ntdll!NtWaitForAlertByThreadId", + "ntdll!RtlAcquireSRWLockExclusive" + ]), + "lock (SRW)" + ); + assert_eq!( + wait_kind(&[ + "ntdll!NtWaitForAlertByThreadId", + "ntdll.dll+0x1230", + "std::sys::sync::mutex::futex::Mutex::lock_contended" + ]), + "lock (ours)" + ); + assert_eq!( + wait_kind(&[ + "ntdll!NtWaitForAlertByThreadId", + "std::sys::sync::condvar::futex::Condvar::wait" + ]), + "condition variable" + ); + assert_eq!( + wait_kind(&[ + "ntdll!NtWaitForSingleObject", + "KERNELBASE!WaitForSingleObjectEx" + ]), + "event or handle" + ); + assert_eq!( + wait_kind(&["ntdll!NtDelayExecution", "KERNELBASE!SleepEx"]), + "sleep" + ); + assert_eq!(kind_of("nvwgf2umx.dll", false), Kind::Driver); + assert_eq!(kind_of("ntdll.dll", false), Kind::System); + assert_eq!(kind_of("d3d12core.dll", false), Kind::Direct3d); + assert_eq!( + kind_of("leonida-image-0123456789abcdef.dll", false), + Kind::Title + ); + assert_eq!(kind_of("vcruntime140.dll", false), Kind::Other); + assert_eq!(kind_of("leonida.exe", true), Kind::Ours); + assert_eq!(Role::of_name("leonida-pipelines-3"), Some(Role::Pipelines)); + assert_eq!(Role::of_name("leonida-wide-0"), Some(Role::Wide)); + assert_eq!(Role::of_name("leonida-window"), None); +} + +#[test] +fn times_are_classed_four_to_a_power_of_two() { + assert_eq!(held_class(0), (0, 0)); + assert_eq!(held_class(3), (3, 3)); + assert_eq!(held_class(4), (8, 4)); + assert_eq!(held_class(7), (11, 7)); + assert_eq!(held_class(8), (12, 8)); + assert_eq!(held_class(9), (12, 8)); + assert_eq!(held_class(10), (13, 10)); + assert_eq!(held_class(20_000), (56, 16_384)); + let mut sampler = Sampler::new(config(1000)); + for ns in [1000, 20_000, 20_000, 20_000, 500_000] { + sampler.held += 1; + sampler.held_by[held_class(ns).0] += 1; + sampler.held_longest = sampler.held_longest.max(ns); + } + // The middle one of five is a 20 us one: its class ends at 20.48. + assert_eq!(sampler.held_within(0.5), 20.48); + assert_eq!(sampler.held_within(0.99), 524.288); +} + +#[test] +fn a_tree_keeps_each_call_site_once() { + let mut tree = Tree::new(); + // Innermost first: 3 called by 2 called by 1. + let a = tree.place(&[3, 2, 1], true, true); + let b = tree.place(&[3, 2, 1], true, true); + let c = tree.place(&[4, 2, 1], true, true); + assert_eq!(a, b); + assert_ne!(a, c); + assert_eq!(tree.nodes.len(), 5); + assert_eq!(tree.nodes[a as usize].parent, tree.nodes[c as usize].parent); + // A cut stack hangs under the marker, not under the first frame. + let cut = tree.place(&[3, 2, 1], false, true); + assert_ne!(cut, a); + assert_eq!(tree.nodes[1 + 4].address, CUT); + // With no room, what is new goes to the one node for it. + let nodes = tree.nodes.len(); + let full = tree.place(&[9, 8, 1], true, false); + assert_eq!(tree.nodes[full as usize].address, FULL); + assert_eq!(tree.nodes.len(), nodes + 1); + assert_eq!(tree.place(&[3, 2, 1], true, false), a); +} + +/// The hooks' own cost and the roles they give: a thread that submits is +/// followed as submitting once it has done so often enough. +#[test] +fn threads_are_followed_by_what_they_were_seen_doing() { + STATE.store(ON, Relaxed); + let stop = Arc::new(AtomicBool::new(false)); + let (submits, a) = thread({ + let stop = stop.clone(); + move || { + for _ in 0..SUBMITS { + seen(Seen::Submit); + } + for _ in 0..LIST_CALLS { + seen(Seen::Record); + } + profile_test_sleeps(&stop); + } + }); + let (records, b) = thread({ + let stop = stop.clone(); + move || { + seen(Seen::Submit); + for _ in 0..LIST_CALLS { + seen(Seen::Record); + } + profile_test_sleeps(&stop); + } + }); + let (named, c) = { + let stop = stop.clone(); + let (said, hears) = mpsc::channel(); + let running = std::thread::Builder::new() + .name("leonida-wide-7".into()) + .spawn(move || { + // SAFETY: a plain query. + said.send(unsafe { GetCurrentThreadId() }).unwrap(); + profile_test_sleeps(&stop); + }) + .unwrap(); + (hears.recv().unwrap(), running) + }; + std::thread::sleep(Duration::from_millis(50)); + let mut settings = config(1000); + settings.busy = 0; + let mut sampler = Sampler::new(settings); + sampler.rescan(); + let role_of = |id: u32| sampler.threads.iter().find(|t| t.id == id).map(|t| t.role); + assert_eq!(role_of(submits), Some(Role::Submit)); + assert_eq!(role_of(records), Some(Role::Record)); + assert_eq!(role_of(named), Some(Role::Wide)); + assert!(sampler.threads.iter().all(|t| t.id != sampler.me)); + // A thread that ends is no longer looked at, and its place is free. + stop.store(true, Relaxed); + for running in [a, b, c] { + running.join().unwrap(); + } + sampler.rescan(); + sampler.rescan(); + assert!( + sampler + .threads + .iter() + .filter(|t| [submits, records, named].contains(&t.id)) + .all(|t| !t.alive) + ); + assert!( + KNOWN_THREADS + .iter() + .all(|k| ![submits, records].contains(&k.thread.load(Relaxed))) + ); + sampler.tick(); +} + +/// The sampler's own thread, as the game runs it: it finds a worker by +/// its name and a busy thread by its work, and writes the report and the +/// stacks file when its time is up. +#[test] +fn the_sampler_finds_threads_and_writes_its_files() { + let stop = Arc::new(AtomicBool::new(false)); + let named = { + let stop = stop.clone(); + std::thread::Builder::new() + .name("leonida-pipelines-9".into()) + .spawn(move || { + profile_test_sleeps(&stop); + }) + .unwrap() + }; + let (_, busy) = thread({ + let stop = stop.clone(); + move || { + std::hint::black_box(profile_test_spins(&stop)); + } + }); + let folder = std::env::temp_dir().join(format!("leonida_profile_test_{}", std::process::id())); + std::fs::create_dir_all(&folder).unwrap(); + let mut settings = config(500); + settings.out = folder.join("profile.txt"); + (settings.every, settings.length, settings.busy) = (1.2, Some(3.0), 2); + let out = settings.out.clone(); + std::thread::spawn(move || run(settings)).join().unwrap(); + stop.store(true, Relaxed); + named.join().unwrap(); + busy.join().unwrap(); + let text = std::fs::read_to_string(&out).unwrap(); + let mut stacks = out.clone().into_os_string(); + stacks.push(".folded"); + let folded = std::fs::read_to_string(&stacks).unwrap(); + let _ = std::fs::remove_dir_all(&folder); + println!("{text}"); + assert!(text.contains("=== PIPELINE WORKERS"), "{text}"); + assert!(text.contains("leonida-pipelines-9")); + assert!(text.contains("=== OTHER BUSY THREADS"), "{text}"); + // The sleeping thread is seen sleeping: its wake-ups are on the same + // clock as the sampler's ticks, and are not what is sampled. + let pipelines = text.split("=== PIPELINE WORKERS").nth(1).unwrap(); + let waiting: f64 = pipelines + .split("waiting ") + .nth(1) + .and_then(|rest| rest.split('(').nth(1)) + .and_then(|rest| rest.split(' ').next()) + .and_then(|share| share.parse().ok()) + .unwrap_or_else(|| panic!("{pipelines}")); + assert!( + waiting >= 93.0, + "the sleeping thread waits {waiting} % of its time" + ); + assert!( + folded + .lines() + .any(|l| l.starts_with("busy;") && l.contains("profile_test_spin_inner")), + "{folded}" + ); + assert!( + folded + .lines() + .any(|l| l.starts_with("pipelines;") && l.contains("profile_test_sleeps")), + "{folded}" + ); + // Each stack line ends in its microseconds. + assert!(folded.lines().all(|l| { + l.rsplit(' ') + .next() + .is_some_and(|n| n.parse::().is_ok()) + })); + assert!(DONE.load(Relaxed)); +} + +/// Measures what the profiler costs the threads it looks at. Not a test +/// of anything: run it by name, in a release build: +/// `cargo test --profile diag -p leonida-gpu --features diagnostics +/// profile::tests::what_looking_costs -- --ignored --nocapture`. +/// +/// Eight threads do work that is counted, one to a core and above the +/// priority other programs run at, so that a busy machine does not +/// decide the result; rounds with and without the profiler alternate. +#[test] +#[ignore = "a measurement, not a test"] +fn what_looking_costs() { + use windows_sys::Win32::System::Threading::{SetThreadAffinityMask, THREAD_PRIORITY_HIGHEST}; + #[repr(align(128))] + struct Count(AtomicU64); + const THREADS: usize = 8; + static COUNTS: [Count; THREADS] = [const { Count(AtomicU64::new(0)) }; THREADS]; + static STOP: AtomicBool = AtomicBool::new(false); + static WAITS: AtomicBool = AtomicBool::new(false); + + #[inline(never)] + fn profile_cost_work(depth: u32, count: &AtomicU64, seed: u64) -> u64 { + if depth > 0 { + return std::hint::black_box(profile_cost_work( + depth - 1, + count, + seed ^ u64::from(depth), + )) + 1; + } + let mut x = seed | 1; + while !STOP.load(Relaxed) { + for _ in 0..4096 { + x ^= x << 13; + x ^= x >> 7; + x ^= x << 17; + } + count.fetch_add(1, Relaxed); + if WAITS.load(Relaxed) && x.is_multiple_of(64) { + // Now and then a wait, as a thread that waits for the card has. + std::thread::sleep(Duration::from_micros(500)); + } + } + x + } + + let pinned = std::thread::available_parallelism().map_or(1, |n| n.get()) >= 2 * THREADS; + let mut running = Vec::new(); + let mut ids = Vec::new(); + for (i, count) in COUNTS.iter().enumerate() { + let (id, thread) = thread(move || { + // SAFETY: plain calls on our own thread. + unsafe { + if pinned { + SetThreadAffinityMask(GetCurrentThread(), 1 << (2 * i)); + } + SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_HIGHEST); + } + std::hint::black_box(profile_cost_work(30, &count.0, i as u64 + 1)); + }); + ids.push(id); + running.push(thread); + } + std::thread::sleep(Duration::from_millis(200)); + // The parts of a look at a running thread, each timed on its own. + { + // SAFETY: a thread of this test, suspended and resumed in turn; the + // context is aligned; the copy is ours. + unsafe { + SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_TIME_CRITICAL); + let thread = OpenThread(ACCESS, 0, ids[0]); + let mut context = Box::new(Aligned(std::mem::zeroed())); + let mut copy = vec![0u8; 256 << 10]; + let mut parts: [Vec; 5] = Default::default(); + for _ in 0..3000 { + std::thread::sleep(Duration::from_micros(300)); + context.0.ContextFlags = CONTEXT_CONTROL_AMD64 | CONTEXT_INTEGER_AMD64; + let mut got = 0; + let t0 = Instant::now(); + SuspendThread(thread); + let t1 = Instant::now(); + GetThreadContext(thread, &mut context.0); + let t2 = Instant::now(); + ReadProcessMemory( + GetCurrentProcess(), + context.0.Rsp as *const c_void, + copy.as_mut_ptr().cast(), + 4096, + &mut got, + ); + let t3 = Instant::now(); + ResumeThread(thread); + let t4 = Instant::now(); + for (part, time) in + parts + .iter_mut() + .zip([t1 - t0, t2 - t1, t3 - t2, t4 - t3, t4 - t0]) + { + part.push(time.as_nanos() as u64); + } + } + CloseHandle(thread); + SetThreadPriority(GetCurrentThread(), 0); + let median = |part: &mut Vec| { + part.sort_unstable(); + ( + part[part.len() / 2] as f64 / 1000.0, + part[part.len() * 9 / 10] as f64 / 1000.0, + ) + }; + let [a, b, c, d, e] = parts.each_mut().map(median); + println!( + "a look at a running thread, 3000 of them, median (and 9 in 10 under), microseconds: \ + suspend {:.1} ({:.1}), read its registers {:.1} ({:.1}), copy 4 KB of stack {:.1} ({:.1}), \ + resume {:.1} ({:.1}), all {:.1} ({:.1})", + a.0, a.1, b.0, b.1, c.0, c.1, d.0, d.1, e.0, e.1 + ); + // The kernel's copy against a plain one, by size. + let source = vec![7u8; 256 << 10]; + for size in [4usize << 10, 16 << 10, 64 << 10, 128 << 10, 256 << 10] { + let (mut kernel, mut plain) = (Vec::new(), Vec::new()); + for _ in 0..400 { + let mut got = 0; + let t0 = Instant::now(); + ReadProcessMemory( + GetCurrentProcess(), + source.as_ptr().cast(), + copy.as_mut_ptr().cast(), + size, + &mut got, + ); + let t1 = Instant::now(); + std::ptr::copy_nonoverlapping( + source.as_ptr(), + std::hint::black_box(copy.as_mut_ptr()), + size, + ); + let t2 = Instant::now(); + kernel.push((t1 - t0).as_nanos() as u64); + plain.push((t2 - t1).as_nanos() as u64); + } + println!( + "a copy of {} KB: the kernel's {:.1} us, a plain one {:.1} us (medians of 400)", + size >> 10, + median(&mut kernel).0, + median(&mut plain).0 + ); + } + } + } + let total = || COUNTS.iter().map(|c| c.0.load(Relaxed)).sum::(); + let round = Duration::from_millis(1000); + let rounds = 9; + // The timer the sampler ticks by. + { + let mut pace = Pace::new(1000, 0); + let (began, mut longest, mut last) = (Instant::now(), Duration::ZERO, Instant::now()); + for _ in 0..2000 { + pace.wait(); + longest = longest.max(last.elapsed()); + last = Instant::now(); + } + println!( + "the timer: 2000 ticks of a millisecond took {:.1} ms, the longest {:.2} ms (repeating: {})", + began.elapsed().as_secs_f64() * 1000.0, + longest.as_secs_f64() * 1000.0, + pace.repeats + ); + } + for (what, waits, reuse, budget) in [ + ( + "8 threads always running, no limit on what looks may cost (LEONIDA_PROFILE_BUDGET=0)", + false, + true, + 0.0, + ), + ( + "8 threads always running, the usual limit of 3 %", + false, + true, + 0.03, + ), + ( + "8 threads that run and wait, the usual limit", + true, + true, + 0.03, + ), + ( + "8 threads that run and wait, every look a suspension (LEONIDA_PROFILE_REUSE=0), no limit", + true, + false, + 0.0, + ), + ] { + WAITS.store(waits, Relaxed); + std::thread::sleep(Duration::from_millis(300)); + for hz in [1000u32, 4000] { + let (mut without, mut with) = (Vec::new(), Vec::new()); + let (mut half, mut most, mut longest, mut looks, mut reused, mut late, mut used) = + (0.0f64, 0.0f64, 0.0f64, 0, 0, 0, 0.0); + let (mut ticks, mut every) = (0, 1); + for _ in 0..rounds { + // Without the profiler. + let (from, began) = (total(), Instant::now()); + std::thread::sleep(round); + without.push((total() - from) as f64 / began.elapsed().as_secs_f64()); + // With it, on a thread of its own as in the game. + let ids = ids.clone(); + let measured = std::thread::spawn(move || { + // SAFETY: a plain call on our own thread. + unsafe { SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_TIME_CRITICAL) }; + let mut settings = config(hz); + settings.reuse = reuse; + settings.budget = budget; + let mut sampler = Sampler::new(settings); + for &id in &ids { + sampler.follow(id, Role::Record, null_mut(), None); + } + sampler.resync(); + let mut pace = Pace::new(hz, 250); + let (cpu, from, began) = (own_cpu(), total(), Instant::now()); + while began.elapsed() < round { + pace.wait(); + sampler.tick(); + } + let rate = (total() - from) as f64 / began.elapsed().as_secs_f64(); + let used = (own_cpu() - cpu).as_secs_f64() / began.elapsed().as_secs_f64(); + let threads = &sampler.threads; + ( + rate, + used, + sampler.held_within(0.5), + sampler.held_within(0.99), + sampler.held_longest as f64 / 1000.0, + threads.iter().map(|t| t.looks).sum::(), + threads.iter().map(|t| t.reused).sum::(), + sampler.late, + threads.iter().map(|t| t.missed).sum::(), + sampler.ticks, + threads.iter().map(|t| t.every).max().unwrap_or(1), + ) + }) + .join() + .unwrap(); + with.push(measured.0); + used += measured.1 / rounds as f64; + half = half.max(measured.2); + most = most.max(measured.3); + longest = longest.max(measured.4); + looks += measured.5; + reused += measured.6; + late += measured.7; + assert_eq!(measured.8, 0, "looks that failed"); + ticks += measured.9; + every = every.max(measured.10); + } + let median = |values: &mut Vec| { + values.sort_by(f64::total_cmp); + values[values.len() / 2] + }; + let spread = |values: &[f64]| { + 100.0 * (values[values.len() - 1] - values[0]) / values[values.len() / 2] + }; + let (off, on) = (median(&mut without), median(&mut with)); + println!( + "{what}, {hz} looks a second: work done {:.2} % less with the profiler (medians of {rounds} \ + rounds of 1 s: {off:.0} against {on:.0} a second; the rounds without it differ by {:.1} %, \ + with it by {:.1} %); a suspension under {half:.0} us half the times, under {most:.0} us 99 \ + in 100, {longest:.0} us at longest; {ticks} ticks ({late} late), {looks} looks, {reused} \ + without a suspension, a thread looked at every {every} ticks at most; the sampler's \ + thread used {:.1} % of a processor", + 100.0 * (off - on) / off, + spread(&without), + spread(&with), + 100.0 * used, + ); + } + } + STOP.store(true, Relaxed); + for thread in running { + thread.join().unwrap(); + } +} diff --git a/crates/leonida-gpu/src/query.rs b/crates/leonida-gpu/src/query.rs new file mode 100644 index 000000000..f3eb6b040 --- /dev/null +++ b/crates/leonida-gpu/src/query.rs @@ -0,0 +1,72 @@ +//! Query heaps. Nothing runs on a GPU yet, so no query ever produces a +//! result; the heap only remembers its description. +#![allow(clippy::not_unsafe_ptr_arg_deref)] + +use crate::object::{self, E_INVALIDARG, HRESULT, Iid, Object, QUERY_HEAP, Table, This, guid}; +use crate::resource::PAGEABLE_IIDS; + +const HEAP_IIDS: [Iid; 4] = [ + guid( + 0x0d9658ae, + 0xed45, + 0x469e, + [0xa6, 0x1d, 0x97, 0x0e, 0xc5, 0x83, 0xca, 0xb4], + ), + PAGEABLE_IIDS[0], + PAGEABLE_IIDS[1], + PAGEABLE_IIDS[2], +]; + +#[repr(C)] +#[derive(Debug, Clone, Copy)] +pub(crate) struct Desc { + kind: u32, + count: u32, + nodes: u32, +} + +#[repr(C)] +struct Heap { + object: Object, + desc: Desc, +} + +/// Device method. +pub(crate) extern "system" fn create( + _: This, + desc: *const Desc, + iid: *const Iid, + out: *mut This, +) -> HRESULT { + // SAFETY: the title passes a description (null is tolerated). + let Some(&desc) = (unsafe { desc.as_ref() }) else { + return E_INVALIDARG; + }; + tracing::debug!(?desc, "query heap"); + let heap = Box::new(Heap { + object: Object::new(&FUNCTIONS), + desc, + }); + object::hand_out(QUERY_HEAP, heap, iid, &HEAP_IIDS, out) +} + +extern "system" fn query(this: This, iid: *const Iid, out: *mut This) -> HRESULT { + object::answer( + QUERY_HEAP, + iid, + object::is(iid, &HEAP_IIDS).then_some(this), + out, + ) +} +extern "system" fn release(this: This) -> u32 { + object::release_boxed::(this) +} + +/// IUnknown 3, object 4, device child 1. +static FUNCTIONS: Table<24> = { + let mut f = object::d3d12_object(object::missing_table::()); + f[0] = query as *const (); + f[2] = release as *const (); + f[7] = object::parent_device as *const (); // 0x38 + Table(f) +}; diff --git a/crates/leonida-gpu/src/queue.rs b/crates/leonida-gpu/src/queue.rs new file mode 100644 index 000000000..2fedd5348 --- /dev/null +++ b/crates/leonida-gpu/src/queue.rs @@ -0,0 +1,1657 @@ +//! Command queues. Submitted lists run on the host GPU and are waited for, +//! so fence signals complete at once. +#![allow(clippy::not_unsafe_ptr_arg_deref)] + +use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; + +use crate::object::{self, E_INVALIDARG, HRESULT, Iid, Object, QUEUE, S_OK, Table, This, guid}; +use crate::resource::PAGEABLE_IIDS; + +const QUEUE_IIDS: [Iid; 4] = [ + guid( + 0x0ec870a6, + 0x5d7e, + 0x4c22, + [0x8c, 0xfc, 0x5b, 0xaa, 0xe0, 0x76, 0x16, 0xed], + ), + PAGEABLE_IIDS[0], + PAGEABLE_IIDS[1], + PAGEABLE_IIDS[2], +]; + +#[repr(C)] +#[derive(Debug, Clone, Copy)] +pub(crate) struct QueueDesc { + kind: u32, + priority: i32, + flags: u32, + nodes: u32, +} + +/// The title reads the list type right after the header. +#[repr(C)] +struct Queue { + object: Object, + kind: u32, + desc: QueueDesc, + /// What the queue was given after a wait for a fence that had not been + /// reached, in order; it runs when the fence gets there. + #[cfg(windows)] + held: std::sync::Mutex>, +} +const _: () = assert!(std::mem::offset_of!(Queue, kind) == 0x10); + +/// One thing a waiting queue holds back. +#[cfg(windows)] +enum Held { + /// The queue waits for the fence (its address) to reach the value. + Wait(usize, u64), + /// A list of the next submission waits for a memory value. + Value(crate::list::ValueWait), + /// A submission: the lists' host sides, taken from the title's lists + /// (which it may reset meanwhile), and the order they run in. + Run(Vec, Vec), + /// A signal of the queue's, due after what it holds before it. + Signal(usize, u64), + /// With [`behind`]: the submission at the head of the line is being + /// prepared and sent by our thread, with the line unlocked, so the + /// title can add to its end meanwhile; whatever is added stays behind + /// this (the line is not empty), signals too. + Running, + /// With [`present_behind`]: the title's present of a frame, due after + /// what the queue holds before it: the host texture shown, the state + /// the title's lists leave it in, and the frame's number. + Present(windows::Win32::Graphics::Direct3D12::ID3D12Resource, u32, u64), +} + +/// Presents that are in a queue's line and have not run ([`Held::Present`]). +#[cfg(windows)] +static PRESENTS_HELD: AtomicU64 = AtomicU64::new(0); + +/// Whether a present goes behind the queue's line and returns at once +/// (`LEONIDA_ASYNC_PRESENT=1`; needs [`behind`] and presents that do not +/// settle the flights, `crate::host::late_free_present`). +/// +/// Why: with [`behind`] our thread prepares and sends the submissions, but +/// the title's present still ran the line itself first, that is: it stood +/// until our thread had prepared every submission of the frame. Run 225's +/// frame log (the cell, 136 ms a frame): the title's render thread is 77 ms +/// of every frame inside the present waiting for that, using 3 ms of +/// processor itself, and only then begins to record the next frame (about +/// 57 ms), during which our thread has nothing to prepare. The two phases +/// ran one after the other. +/// +/// With the switch the present is one more thing in the line +/// ([`Held::Present`]): our thread shows the frame when it gets there, in +/// order, and the title records the next frame meanwhile. +/// +/// The title is one frame ahead at most: a present that finds the one +/// before it still in a line runs the old way (the lines first, then +/// itself), and so does a frame that is saved or listed, and a present +/// that finds its queue's line empty. A wait nothing ever meets is +/// therefore still forced, by the present after it. +/// +/// What it assumes, beyond what [`behind`] does: title memory a submission +/// reads stays as it was until the submission's fence is signalled, also +/// across the title's present. On the console the card reads that memory +/// when it runs the list, after the present call has returned. +/// +/// `LEONIDA_ASYNC_PRESENT=alt`: twenty seconds with, twenty without, in +/// turn, each change said in the log, for measuring it in one scene. +#[cfg(windows)] +fn present_behind() -> bool { + /// 0 off, 1 on, 2 in turn. + static MODE: std::sync::OnceLock = std::sync::OnceLock::new(); + let mode = *MODE.get_or_init(|| { + let asked = match std::env::var("LEONIDA_ASYNC_PRESENT").as_deref() { + Ok("1") => 1, + Ok("alt") => 2, + _ => 0, + }; + let mode = if asked != 0 && behind() && crate::host::late_free_present() { asked } else { 0 }; + if mode != 0 { + tracing::info!("presents go behind the queue's line and return at once (LEONIDA_ASYNC_PRESENT=1; alt: in turn)"); + } + mode + }); + match mode { + 0 => false, + 1 => true, + _ => { + static EPOCH: std::sync::OnceLock = std::sync::OnceLock::new(); + let on = (EPOCH.get_or_init(std::time::Instant::now).elapsed().as_secs() / 20) % 2 == 1; + static LAST: std::sync::atomic::AtomicU8 = std::sync::atomic::AtomicU8::new(2); + if LAST.swap(u8::from(on), Ordering::Relaxed) != u8::from(on) { + tracing::info!( + "presents behind the line from now (LEONIDA_ASYNC_PRESENT=alt): {}", + if on { "ON" } else { "off, as usual" } + ); + } + on + } + } +} + +/// With [`present_behind`]: puts the present of the next frame behind what +/// the queue `this` holds. False if it has to run the old way. +#[cfg(windows)] +fn send_behind(this: This, planes: u32, plane_parameters: *const Plane) -> bool { + if this.is_null() || planes == 0 || PRESENTS_HELD.load(Ordering::Relaxed) != 0 { + return false; + } + let frame = FRAMES.load(Ordering::Relaxed) + 1; + // A frame that is saved or listed is read back at once. + #[cfg(feature = "diagnostics")] + if crate::capture::wanted(frame) || crate::capture::listed(frame) { + return false; + } + // SAFETY: the title passes `planes` plane descriptions. + let Some(plane) = (unsafe { plane_parameters.as_ref() }) else { + return false; + }; + if plane.count == 0 || plane.resources.is_null() { + return false; + } + // SAFETY: the plane lists `count` resources. + let resource = unsafe { *plane.resources }; + let Some(texture) = crate::resource::host_resource(resource) else { + return false; + }; + // The state the lists recorded so far leave the texture in: what our + // copy finds it in when it runs behind them (looked at, not changed). + const COPY_SOURCE: u32 = 0x800; + let state = crate::resource::host_transition(resource, COPY_SOURCE).map_or(COPY_SOURCE, |(_, before)| before); + crate::resource::host_transition(resource, state); + let texture = texture.clone(); + let sent = hold(this, || { + PRESENTS_HELD.fetch_add(1, Ordering::Relaxed); + Held::Present(texture, state, frame) + }); + if sent { + PRESENTS_BEHIND.fetch_add(1, Ordering::Relaxed); + wake(); + } + sent +} + +/// Presents sent behind their queue's line since the start +/// ([`send_behind`]), for the line every 512 of them. +#[cfg(windows)] +static PRESENTS_BEHIND: AtomicU64 = AtomicU64::new(0); + +/// The queues that hold something (their addresses). +#[cfg(windows)] +static WAITING: std::sync::Mutex> = std::sync::Mutex::new(Vec::new()); + +#[cfg(windows)] +fn lock(mutex: &std::sync::Mutex) -> std::sync::MutexGuard<'_, T> { + mutex.lock().unwrap_or_else(|e| e.into_inner()) +} + +/// Whether queues wait for fences. `LEONIDA_QUEUE_WAIT=0`: they do not, +/// and every submission runs when it is made (as before). +#[cfg(windows)] +fn waits() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("LEONIDA_QUEUE_WAIT").is_none_or(|v| v != "0")) +} + +/// Whether a submission is held list by list: the lists before the first +/// one whose wait for a memory value is not met run at once, and each list +/// that waits is held with the lists after it, behind its own waits. +/// Holding a submission whole made the title's queues wait for each other: +/// a graphics submission was held for a value a compute list writes, and +/// that compute list for a value an earlier list of the same graphics +/// submission writes. Nothing moved until the present forced it, and the +/// title reached its present only after waiting about 2.5 s, every frame +/// (runs 27-30: 2.4-2.9 s from the last submission to the present call, +/// 13-32 ms before waits were honoured; the frame's main graphics +/// submissions, 88 lists, ran forced, the compute lists before them). +/// On by default; `LEONIDA_SPLIT_WAITS=0` holds whole submissions, as +/// before. +#[cfg(windows)] +fn split() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("LEONIDA_SPLIT_WAITS").is_none_or(|v| v != "0")) +} + +/// Whether a list is cut into host lists at its waits for memory values +/// (`crate::list::cut`), and a queue runs a submission part by part: it +/// stands at each wait until the value is in memory, with everything +/// recorded before the wait run and its bottom-of-pipe writes done, as on +/// the console. Held list by list ([`split`]) a wait still held its whole +/// list: the title's lists are chains of jobs, each behind a wait for a +/// value another queue's list writes in the middle of its own chain +/// (frame 858 of run 33: a compute list of 433 commands with 13 waits; +/// graphics lists of the form "341 dispatches, wait, draws"), so two lists +/// each waited for a write behind the other's wait and only the present +/// moved them, in the wrong order. +/// On by default where waits are honoured list by list; +/// `LEONIDA_CUT_WAITS=0` holds whole lists, as before. +#[cfg(windows)] +pub(crate) fn cuts() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + waits() && split() && *ON.get_or_init(|| std::env::var_os("LEONIDA_CUT_WAITS").is_none_or(|v| v != "0")) +} + +/// Whether a present runs what queues still hold (on by default: a wait +/// is not kept across frames). `LEONIDA_WAIT_FORCE=0` keeps it held: for +/// finding out whether the title's waits reach across its presents; a +/// wait nothing ever meets then stops the title for good. +#[cfg(windows)] +fn forces() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("LEONIDA_WAIT_FORCE").is_none_or(|v| v != "0")) +} + +/// A submission to a queue whose lists are cut at their waits ([`cuts`]). +/// The lists before the first one that waits run at once if the queue +/// holds nothing; the rest goes behind what the queue holds, part by part +/// (`crate::list::detach_parts`): the waits of a part, then its host +/// lists. [`release_held`] runs the queue's line as far as the values are +/// there, now and whenever a submission has run. +#[cfg(windows)] +fn submit_cut(this: This, lists: &[This]) { + let Some(host) = crate::host::host() else { + return; + }; + let first = if !behind() && lock(&queue(this).held).is_empty() { + lists + .iter() + .position(|&l| crate::list::cut_list(l)) + .unwrap_or(lists.len()) + } else { + 0 + }; + #[cfg(feature = "diagnostics")] + crate::capture::op(this as usize, || { + let named: Vec = lists + .iter() + .map(|&l| match crate::list::host_list(l) { + Some(h) => format!("{:#x}", std::ptr::from_ref(h) as usize), + None => format!("title {l:?}"), + }) + .collect(); + format!( + "SUBMIT queue kind {:?} held {} lists {named:?} (the first {first} run at once, the rest part by part)", + Some(queue(this).kind), + first < lists.len() + ) + }); + if first > 0 && crate::host::late() { + // Sent to the card and not waited for: their host sides are taken + // from the title's lists (which it may reset before they have run) + // and come back, with their tables' slots, when they are settled. + let (taken, order) = crate::list::detach(&lists[..first]); + host.execute_late(taken, order); + } else if first > 0 { + let now: Vec<_> = lists[..first] + .iter() + .filter_map(|&l| crate::list::host_list(l)) + .collect(); + host.execute(&now); + // They have run: their descriptor tables' slots are free again, as + // on the path without cuts ([`execute`]). This path replaced that + // one without the call, so the lists that run at once kept their + // slots until the title's reset and the ring ran out as before + // (run 45: 3,143 of 15,942 tables refused in one frame). + crate::list::tables_done(&lists[..first]); + } + if first < lists.len() { + let parts = crate::list::detach_parts(&lists[first..]); + static SEEN: AtomicU64 = AtomicU64::new(0); + if SEEN.fetch_add(1, Ordering::Relaxed) < 8 { + tracing::info!( + kind = queue(this).kind, + lists = lists.len(), + run_at_once = first, + parts = parts.len(), + waits = parts.iter().map(|p| p.0.len()).sum::(), + "a submission is given to its queue part by part (its lists wait for memory values)" + ); + } + { + let mut held = lock(&queue(this).held); + for (waits, taken, order) in parts { + held.extend(waits.into_iter().map(Held::Value)); + held.push(Held::Run(taken, order)); + } + } + let mut waiting = lock(&WAITING); + if !waiting.contains(&(this as usize)) { + waiting.push(this as usize); + } + } + // What ran may be what another queue waits for, and what was just + // given to the queue may be free to run already. + release_held(false); +} + +/// A submission to a queue that honours waits, list by list ([`split`]). +/// shortcut: a wait still holds its whole list, not only the commands +/// after it; and lists named twice among those held stay in one piece. +#[cfg(windows)] +fn submit_split(this: This, lists: &[This]) { + let Some(host) = crate::host::host() else { + return; + }; + let by = crate::list::waits_by_list(lists); + // Behind what the queue already holds, nothing runs now. + let cut = if lock(&queue(this).held).is_empty() { + (0..lists.len()) + .find(|&i| by[i].iter().any(|w| !w.met())) + .unwrap_or(lists.len()) + } else { + 0 + }; + #[cfg(feature = "diagnostics")] + crate::capture::op(this as usize, || { + let named: Vec = lists + .iter() + .map(|&l| match crate::list::host_list(l) { + Some(h) => format!("{:#x}", std::ptr::from_ref(h) as usize), + None => format!("title {l:?}"), + }) + .collect(); + format!( + "SUBMIT queue kind {:?} held {} lists {named:?} (the first {cut} run at once)", + Some(queue(this).kind), + cut < lists.len() + ) + }); + if cut > 0 { + let now: Vec<_> = lists[..cut] + .iter() + .filter_map(|&l| crate::list::host_list(l)) + .collect(); + host.execute(&now); + } + if cut < lists.len() { + static SEEN: AtomicU64 = AtomicU64::new(0); + if SEEN.fetch_add(1, Ordering::Relaxed) < 8 { + tracing::info!( + kind = queue(this).kind, + lists = lists.len(), + run_at_once = cut, + waits = ?by[cut], + "lists of a submission are held for a memory value" + ); + } + let rest = &lists[cut..]; + // A list's host side can be taken once. + let twice = rest.iter().enumerate().any(|(i, l)| rest[..i].contains(l)); + let mut pieces: Vec = Vec::new(); + let mut from = cut; + while from < lists.len() { + // Up to the next list that waits for anything (met or not: it + // is looked at again when its turn comes). + let to = if twice { + lists.len() + } else { + (from + 1..lists.len()) + .find(|&i| !by[i].is_empty()) + .unwrap_or(lists.len()) + }; + let waits: Vec = by[from..to].concat(); + pieces.extend(waits.into_iter().map(Held::Value)); + let (taken, order) = crate::list::detach(&lists[from..to]); + pieces.push(Held::Run(taken, order)); + from = to; + } + lock(&queue(this).held).extend(pieces); + let mut waiting = lock(&WAITING); + if !waiting.contains(&(this as usize)) { + waiting.push(this as usize); + } + } + // What ran may be what another queue waits for, and what was just held + // may be free to run already. + release_held(false); +} + +/// Adds `what()` to what the queue holds, if it holds anything (it waits +/// for a fence): whether it was added. +#[cfg(windows)] +fn hold(this: This, what: impl FnOnce() -> Held) -> bool { + if this.is_null() { + return false; + } + let mut held = lock(&queue(this).held); + if held.is_empty() { + return false; + } + held.push(what()); + true +} + +/// Runs what waiting queues hold as far as their fences have been reached +/// (`all`: all of it), each queue's in the order it was given. Called +/// where a fence may have moved: after a signal and after a submission (a +/// list's bottom-of-pipe write may be into a fence), never from inside +/// one. +#[cfg(windows)] +pub(crate) fn release_held(all: bool) { + if !all && behind() { + // A thread of ours runs what is free to run ([`behind`]). + wake(); + return; + } + release_held_now(all); +} + +/// Whether a submission is only put in its queue's line by the thread +/// that submits it, and prepared and sent by a thread of ours +/// (`LEONIDA_ASYNC_SUBMIT=1`; needs flights and lists cut at their waits, +/// both defaults). +/// +/// Why: the profile of run 213 (292 ms a frame) has the title's render +/// thread inside `queue::execute` for 202 ms of every frame: 155 ms in +/// `Host::submit` (preparing: the copies of title memory, the write +/// watch, descriptors, textures; and waiting for flights), while its five +/// recording threads stand idle 78 % of the time and the card 43 %. The +/// title's thread does nothing with the result of that work: it only has +/// to be done before the lists run, in order. +/// +/// With the switch a submission's lists are taken from the title's lists +/// (as they already are when the queue holds anything) and put behind +/// the queue's line; one thread of ours ([`worker`]) runs the line in +/// order. A signal of the queue goes behind them, as it does behind +/// anything held. Everything that must see earlier submissions done runs +/// the line itself first: a present, and every submission of ours that +/// is waited for ([`before_sync`]). +/// +/// What it assumes: title memory a submission reads is not rewritten by +/// the title between its submit call and the moment our thread prepares +/// it, some milliseconds later. On the console the card reads that +/// memory when it runs the list, later still, so a title that rewrote it +/// earlier would be wrong there too. +#[cfg(windows)] +pub(crate) fn behind() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| { + let on = std::env::var_os("LEONIDA_ASYNC_SUBMIT").is_some_and(|v| v == "1") && crate::host::late() && cuts(); + if on { + tracing::info!("submissions are prepared and sent by a thread of ours, not by the thread that submits (LEONIDA_ASYNC_SUBMIT=1)"); + let _ = std::thread::Builder::new().name("leonida-submit".into()).spawn(worker); + } + on + }) +} + +/// Whether there is something for [`worker`] to look at. +#[cfg(windows)] +static WORK: (std::sync::Mutex, std::sync::Condvar) = (std::sync::Mutex::new(false), std::sync::Condvar::new()); + +#[cfg(windows)] +fn wake() { + *lock(&WORK.0) = true; + WORK.1.notify_one(); +} + +/// The thread of [`behind`]: runs what queues hold as far as it is free +/// to run, each time something was added or a fence moved. +#[cfg(windows)] +fn worker() { + crate::framelog::keep_on_fast_cores("leonida-submit"); + loop { + { + let mut work = lock(&WORK.0); + while !*work { + work = WORK.1.wait(work).unwrap_or_else(|e| e.into_inner()); + } + *work = false; + } + let started = std::time::Instant::now(); + let (user, kernel) = crate::framelog::thread_times(); + if crate::framelog::on() { + crate::framelog::add(crate::framelog::T::WorkerLooks, 1); + if crate::framelog::on_slow_core() { + crate::framelog::add(crate::framelog::T::WorkerSlow, 1); + } + } + release_held_now(false); + let (user_now, kernel_now) = crate::framelog::thread_times(); + crate::framelog::add(crate::framelog::T::WorkerUs, started.elapsed().as_micros() as u64); + crate::framelog::add(crate::framelog::T::WorkerUserUs, user_now.saturating_sub(user)); + crate::framelog::add(crate::framelog::T::WorkerKernelUs, kernel_now.saturating_sub(kernel)); + } +} + +#[cfg(windows)] +thread_local! { + /// This thread is inside [`release_held_now`]. + static RELEASING_HERE: std::cell::Cell = const { std::cell::Cell::new(false) }; +} + +/// Whether parts that follow one another in the queues' lines go to the +/// host as one submission (`LEONIDA_JOIN_PARTS=1`; `alt`: twenty seconds +/// with, twenty without, in turn, each change said in the log). Off by +/// default. Needs [`behind`]. +/// +/// Why: the title's lists wait for memory values (19 to 20 waits a frame +/// in the first rooms, each met by the bottom-of-pipe write of the part +/// before it), and every wait cuts a submission into parts: 29 host +/// submissions a frame from about 15 of the title's (run 238). Each part +/// is prepared on its own: 82 askings of the write watch, 666 refresh +/// steps, a heap sync, a merge under the flights in the air, and on the +/// card one list of ours that sends changed bytes and one that compares. +/// The title hands a frame over in one burst at the end of its recording, +/// then stands still until the line has finished it (its fence wait of +/// the next frame: run 238), so the parts are all in the lines when our +/// thread gets to them. +/// +/// With the switch the thread that runs the lines takes parts off them +/// in the order they would have run and gives them to the host together: +/// the same host lists in the same order, prepared once. Between two +/// parts a wait passes if memory meets it, if a write of a flight in the +/// air is known to meet it, or if a bottom-of-pipe write of a part taken +/// before it meets it (that part is ahead of it in the joined +/// submission, which is the order the wait asks for). A signal met +/// behind parts not sent yet is delivered right behind the joined +/// submission: never before the part it followed has run. Anything else +/// (a wait not known to be met, a present, the end of what is free to +/// run) sends what was taken first. At most [`join_most`] parts or +/// [`join_lists`] lists are joined, so that the card has work while the +/// next ones are prepared. Each queue with a part taken keeps the mark +/// [`Held::Running`] at the head of its line until the part is sent: +/// what the title gives the queue meanwhile, signals too, stays behind. +#[cfg(windows)] +fn join_parts() -> bool { + /// 0 off, 1 on, 2 in turn. + static MODE: std::sync::OnceLock = std::sync::OnceLock::new(); + let mode = *MODE.get_or_init(|| { + let mode = match std::env::var("LEONIDA_JOIN_PARTS").as_deref() { + Ok("1") => 1, + Ok("alt") => 2, + _ => 0, + }; + if mode != 0 { + tracing::info!( + "parts that follow one another in the queues' lines go to the host as one submission, at most {} parts or {} lists (LEONIDA_JOIN_PARTS=1; alt: in turn)", + join_most(), + join_lists() + ); + } + mode + }); + match mode { + 0 => false, + 1 => true, + _ => { + static EPOCH: std::sync::OnceLock = std::sync::OnceLock::new(); + let on = (EPOCH.get_or_init(std::time::Instant::now).elapsed().as_secs() / 20) % 2 == 1; + static LAST: std::sync::atomic::AtomicU8 = std::sync::atomic::AtomicU8::new(2); + if LAST.swap(u8::from(on), Ordering::Relaxed) != u8::from(on) { + tracing::info!("parts joined into one host submission from now (LEONIDA_JOIN_PARTS=alt): {}", if on { "ON" } else { "off, as usual" }); + } + on + } + } +} + +/// The most parts joined into one host submission (`LEONIDA_JOIN_MOST`, 4). +#[cfg(windows)] +fn join_most() -> usize { + static N: std::sync::OnceLock = std::sync::OnceLock::new(); + *N.get_or_init(|| std::env::var("LEONIDA_JOIN_MOST").ok().and_then(|v| v.parse().ok()).filter(|&n| n >= 1).unwrap_or(4)) +} + +/// The most host lists joined into one host submission (`LEONIDA_JOIN_LISTS`, 48). +#[cfg(windows)] +fn join_lists() -> usize { + static N: std::sync::OnceLock = std::sync::OnceLock::new(); + *N.get_or_init(|| std::env::var("LEONIDA_JOIN_LISTS").ok().and_then(|v| v.parse().ok()).filter(|&n| n >= 1).unwrap_or(48)) +} + +/// With [`join_parts`]: parts taken off the queues' lines and not yet +/// given to the host, in the order they run. +#[cfg(windows)] +#[derive(Default)] +struct Joined { + lists: Vec, + order: Vec, + parts: usize, + /// Signals met behind those parts: delivered when the parts are sent. + signals: Vec<(usize, u64)>, + /// The queues with a part here: each has [`Held::Running`] at the + /// head of its line. + marked: Vec, +} + +#[cfg(windows)] +impl Joined { + fn is_empty(&self) -> bool { + self.parts == 0 + } + + /// One more part behind those taken: its lists keep their order. + fn add(&mut self, lists: Vec, order: Vec) { + let (lists, order) = join(std::mem::take(&mut self.lists), std::mem::take(&mut self.order), lists, order); + self.lists = lists; + self.order = order; + self.parts += 1; + } + + fn full(&self) -> bool { + self.parts >= join_most() || self.order.len() >= join_lists() + } + + /// Whether a bottom-of-pipe write of a part taken meets `wait`. + fn meets(&self, wait: &crate::list::ValueWait) -> bool { + let (address, bytes) = wait.place(); + self.order.iter().any(|&i| self.lists[i].host().will_write(address, bytes, |v| wait.holds_for(v))) + } +} + +#[cfg(windows)] +/// The things of one part behind those of another: `order` names places in +/// `lists`, so the second part's places move up by the first's count. +fn join(mut lists: Vec, mut order: Vec, more: Vec, more_order: Vec) -> (Vec, Vec) { + let base = lists.len(); + lists.extend(more); + order.extend(more_order.into_iter().map(|i| i + base)); + (lists, order) +} + +/// Parts joined, host submissions they went in, their lists, signals +/// delivered behind them, and waits passed for a write of a part taken. +#[cfg(windows)] +static JOINED: [AtomicU64; 5] = [const { AtomicU64::new(0) }; 5]; + +/// Gives the host what [`Joined`] holds, as one submission, delivers the +/// signals met behind it, and takes the marks off the lines. Called with +/// no line locked. +#[cfg(windows)] +fn send_joined(joined: &mut Joined) { + if joined.parts > 0 { + let (lists, order) = (std::mem::take(&mut joined.lists), std::mem::take(&mut joined.order)); + JOINED[0].fetch_add(joined.parts as u64, Ordering::Relaxed); + let sent = JOINED[1].fetch_add(1, Ordering::Relaxed) + 1; + JOINED[2].fetch_add(order.len() as u64, Ordering::Relaxed); + JOINED[3].fetch_add(joined.signals.len() as u64, Ordering::Relaxed); + if sent % 2048 == 0 { + let n: Vec = JOINED.iter().map(|n| n.swap(0, Ordering::Relaxed)).collect(); + tracing::info!( + "parts joined (LEONIDA_JOIN_PARTS=1): {} parts went to the host in {} submissions ({:.1} parts, {:.1} lists each), {} signals delivered behind them, {} waits passed for a write of a part not sent yet", + n[0], + n[1], + n[0] as f64 / n[1].max(1) as f64, + n[2] as f64 / n[1].max(1) as f64, + n[3], + n[4] + ); + } + match crate::host::host() { + Some(host) => host.execute_late(lists, order), + // (Not reached: parts are only taken with a host.) + None => crate::list::recycle(lists, &order), + } + joined.parts = 0; + } + // Behind what was just sent, in the order they were met. + for (fence, value) in joined.signals.drain(..) { + if !crate::host::late_signal(fence, value) { + crate::fence::set(fence as This, value); + } + } + for q in joined.marked.drain(..) { + // SAFETY: a live queue, as in the loop that marked it. + let line = unsafe { &(*(q as *const Queue)).held }; + let mut held = lock(line); + if matches!(held.first(), Some(Held::Running)) { + held.remove(0); + } + if held.is_empty() { + lock(&WAITING).retain(|&w| w != q); + } + } +} + +/// Before a submission of ours that is waited for, with [`behind`]: what +/// the queues hold and is free to run runs first, on this thread, so the +/// submission keeps its place behind them. +#[cfg(windows)] +pub(crate) fn before_sync() { + if behind() && !RELEASING_HERE.get() { + release_held_now(false); + } +} + +#[cfg(windows)] +fn release_held_now(all: bool) { + // One caller at a time, so a queue's submissions keep their order. + static RELEASING: std::sync::Mutex<()> = std::sync::Mutex::new(()); + if lock(&WAITING).is_empty() { + return; + } + let _one = lock(&RELEASING); + let was_here = RELEASING_HERE.replace(true); + struct Leave(bool); + impl Drop for Leave { + fn drop(&mut self) { + RELEASING_HERE.set(self.0); + } + } + let _leave = Leave(was_here); + // Parts taken and not sent yet ([`join_parts`]): none when the lines + // are forced, and none is left when this returns. + let joining = !all && behind() && crate::host::late() && crate::host::host().is_some() && join_parts(); + let mut joined = Joined::default(); + loop { + let queues = lock(&WAITING).clone(); + let mut moved = false; + for q in queues { + // SAFETY: a live queue: one released is taken off the list. + let line = unsafe { &(*(q as *const Queue)).held }; + let mut held = lock(line); + loop { + // A queue with a part in `joined` has our mark at the head + // of its line: what is looked at is behind the mark. + let base = usize::from(joined.marked.contains(&q)); + match held.get(base) { + None | Some(Held::Running) => break, + Some(&Held::Wait(fence, value)) + if !all && crate::fence::completed(fence as This) < value => + { + break; + } + // With parts taken and not sent: only what is known + // without a wait for the card. A wait that stays is + // looked at again when the parts have been sent. + Some(Held::Value(wait)) if !all && !joined.is_empty() => { + if !wait.met() && !crate::host::late_met_known(wait) { + if !joined.meets(wait) { + break; + } + JOINED[4].fetch_add(1, Ordering::Relaxed); + } + } + Some(Held::Value(wait)) if !all && !value_met(wait) => break, + // The frame is shown behind the parts taken: they are + // sent first. + Some(Held::Present(..)) if !joined.is_empty() => break, + Some(_) => {} + } + match held.remove(base) { + Held::Wait(..) | Held::Running => {} + Held::Value(wait) => { + // Passed at a present without being met: what the + // queue stood at. + if all && !value_met(&wait) { + static SEEN: AtomicU64 = AtomicU64::new(0); + if SEEN.fetch_add(1, Ordering::Relaxed) < 16 { + tracing::warn!( + queue = format_args!("{q:#x}"), + ?wait, + "a wait for a memory value was not met at a present: the queue runs on" + ); + } + } + } + Held::Run(lists, order) => { + #[cfg(feature = "diagnostics")] + crate::capture::op(q, || { + format!( + "RUN held submission of {} lists (forced {all})", + order.len() + ) + }); + // Diagnostics: the part behind this one stands at + // waits that are met already, so the two could have + // been one host submission (one wait for the card, + // each range shaders write compared once). + #[cfg(feature = "diagnostics")] + { + let waits = held.iter().take_while(|h| matches!(h, Held::Value(_))).count(); + if waits > 0 + && matches!(held.get(waits), Some(Held::Run(..))) + && held[..waits].iter().all(|h| matches!(h, Held::Value(w) if w.met())) + { + crate::copystat::add(crate::copystat::C::PartsTogether, 1); + } + } + if joining { + // Taken, to go with the parts that follow it. + // The line stays open behind our mark. + if !joined.marked.contains(&q) { + held.insert(0, Held::Running); + joined.marked.push(q); + } + joined.add(lists, order); + if joined.full() { + drop(held); + send_joined(&mut joined); + held = lock(line); + } + moved = true; + continue; + } + if crate::host::late() + && let Some(host) = crate::host::host() + { + // Not waited for: the host keeps the lists + // until they are settled. + if behind() && !all { + // The line is open while this part is + // prepared and sent: only this thread takes + // from its head (one releaser at a time). + held.insert(0, Held::Running); + drop(held); + host.execute_late(lists, order); + held = lock(line); + if matches!(held.first(), Some(Held::Running)) { + held.remove(0); + } + } else { + host.execute_late(lists, order); + } + } else { + let ran = { + let runs: Vec<&crate::host::HostList> = + order.iter().map(|&i| lists[i].host()).collect(); + match crate::host::host() { + Some(host) => { + host.execute(&runs); + true + } + None => false, + } + }; + // They have run: their host lists are used again. + if ran { + crate::list::recycle(lists, &order); + } + } + if all { + #[cfg(feature = "diagnostics")] + crate::copystat::add(crate::copystat::C::Forced, 1); + static ONCE: AtomicBool = AtomicBool::new(false); + if !ONCE.swap(true, Ordering::Relaxed) { + tracing::warn!( + "a queue still held a submission at a present: its fence was not reached" + ); + } + } + } + Held::Present(texture, state, frame) => { + let show = || { + if let Some(host) = crate::host::host() { + let _ = host.present(&texture, state, frame); + } + }; + if all { + show(); + } else { + // The line is open while the frame is shown, + // as it is while a submission is prepared. + held.insert(0, Held::Running); + drop(held); + show(); + held = lock(line); + if matches!(held.first(), Some(Held::Running)) { + held.remove(0); + } + } + PRESENTS_HELD.fetch_sub(1, Ordering::Relaxed); + } + // Behind what was sent to the card and not waited + // for, if anything was. + Held::Signal(fence, value) => { + if !joined.is_empty() { + // Behind parts not sent yet: with them. + joined.signals.push((fence, value)); + } else if !crate::host::late_signal(fence, value) { + crate::fence::set(fence as This, value); + } + } + } + moved = true; + } + if held.is_empty() { + lock(&WAITING).retain(|&w| w != q); + } + } + if !moved { + if joined.is_empty() { + break; + } + // Nothing more is free to run behind the parts taken: they go + // to the host, and what stood at a wait is looked at again. + send_joined(&mut joined); + } + } +} + +/// Whether a queue may pass `wait`: memory holds the value, or, with +/// submissions sent to the card without a wait (`crate::host::late`), it +/// will once those in the air have run. +#[cfg(windows)] +fn value_met(wait: &crate::list::ValueWait) -> bool { + wait.met() || (crate::host::late() && crate::host::late_met(wait)) +} + +fn queue<'a>(this: This) -> &'a Queue { + // SAFETY: called from queue methods only. + unsafe { &*this.cast::() } +} + +pub(crate) extern "system" fn create( + _: This, + desc: *const QueueDesc, + iid: *const Iid, + out: *mut This, +) -> HRESULT { + // SAFETY: the title passes a description (null is tolerated). + let Some(&desc) = (unsafe { desc.as_ref() }) else { + return E_INVALIDARG; + }; + tracing::debug!(?desc, "command queue"); + let queue = Box::new(Queue { + object: if crate::device::newer() { + Object::new(&NEWER_FUNCTIONS) + } else { + Object::new(&FUNCTIONS) + }, + kind: desc.kind, + desc, + #[cfg(windows)] + held: Default::default(), + }); + object::hand_out(QUEUE, queue, iid, &QUEUE_IIDS, out) +} + +/// The console's queue description: an engine or pipe and a queue on it +/// in place of PC's priority and node mask. +#[repr(C)] +#[derive(Debug, Clone, Copy)] +pub(crate) struct QueueDescX { + kind: u32, + flags: u32, + engine_or_pipe: u32, + queue: u32, +} + +/// Device method `CreateCommandQueueX`. The host picks engines itself, so +/// the queue is created as on PC. +pub(crate) extern "system" fn create_x( + this: This, + desc: *const QueueDescX, + iid: *const Iid, + out: *mut This, +) -> HRESULT { + // SAFETY: the title passes a description (null is tolerated). + let Some(&x) = (unsafe { desc.as_ref() }) else { + return E_INVALIDARG; + }; + tracing::debug!(desc = ?x, "console command queue"); + let desc = QueueDesc { + kind: x.kind, + priority: 0, + flags: x.flags, + nodes: 1, + }; + create(this, &desc, iid, out) +} + +extern "system" fn query(this: This, iid: *const Iid, out: *mut This) -> HRESULT { + object::answer( + QUEUE, + iid, + object::is(iid, &QUEUE_IIDS).then_some(this), + out, + ) +} +extern "system" fn release(this: This) -> u32 { + let left = object::release_boxed::(this); + #[cfg(windows)] + if left == 0 { + lock(&WAITING).retain(|&q| q != this as usize); + } + left +} + +/// Runs the lists' host lists and waits for them (decision 0007). A queue +/// that waits for a fence keeps them until the fence is reached. +extern "system" fn execute(this: This, count: u32, lists: *const This) { + #[cfg(windows)] + let started = std::time::Instant::now(); + execute_now(this, count, lists); + #[cfg(windows)] + { + let us = started.elapsed().as_micros() as u64; + crate::framelog::add(crate::framelog::T::ExecuteUs, us); + crate::framelog::here(crate::framelog::H::ExecuteUs, us); + } +} + +fn execute_now(this: This, count: u32, lists: *const This) { + if lists.is_null() { + return; + } + #[cfg(windows)] + if let Some(host) = crate::host::host() { + // SAFETY: the title passes `count` lists. + let lists = unsafe { std::slice::from_raw_parts(lists, count as usize) }; + if cuts() && !this.is_null() { + submit_cut(this, lists); + return; + } + if waits() && split() && !this.is_null() { + submit_split(this, lists); + return; + } + // A list that waits for a memory value not there yet: the queue + // holds the submission, as it does behind a fence. + if waits() && !this.is_null() { + let unmet = crate::list::unmet_waits(lists); + if !unmet.is_empty() { + static SEEN: AtomicU64 = AtomicU64::new(0); + if SEEN.fetch_add(1, Ordering::Relaxed) < 8 { + tracing::info!(kind = queue(this).kind, ?unmet, "a submission is held for a memory value"); + } + lock(&queue(this).held).extend(unmet.into_iter().map(Held::Value)); + let mut waiting = lock(&WAITING); + if !waiting.contains(&(this as usize)) { + waiting.push(this as usize); + } + } + } + let kept = hold(this, || { + let (taken, order) = crate::list::detach(lists); + Held::Run(taken, order) + }); + // Diagnostics: the order submissions are made in, next to the + // commands of the frame's `ops` file (which are in recording order). + #[cfg(feature = "diagnostics")] + crate::capture::op(this as usize, || { + let kind = (!this.is_null()).then(|| queue(this).kind); + // The lists as the frame's other lines name them (their host sides). + let named: Vec = lists + .iter() + .map(|&l| match crate::list::host_list(l) { + Some(h) => format!("{:#x}", std::ptr::from_ref(h) as usize), + None => format!("title {l:?}"), + }) + .collect(); + format!("SUBMIT queue kind {kind:?} held {kept} lists {named:?}") + }); + if kept { + return; + } + let host_lists: Vec<_> = lists + .iter() + .filter_map(|&l| crate::list::host_list(l)) + .collect(); + host.execute(&host_lists); + crate::list::tables_done(lists); + // What the lists wrote at the bottom of the pipe may be a fence + // another queue waits for. + release_held(false); + return; + } + let _ = this; + static ONCE: AtomicBool = AtomicBool::new(false); + if !ONCE.swap(true, Ordering::Relaxed) { + tracing::warn!(count, "command lists submitted; no host GPU runs them"); + } +} + +/// The start of a present plane: frame token, then the plane's resources. +#[repr(C)] +pub(crate) struct Plane { + token: u64, + count: u32, + resources: *const This, +} +/// Submission tagged with the frame it belongs to `(count, lists, frame +/// token, flags)`; frames are paced elsewhere, so it runs as a plain one. +extern "system" fn execute_x(this: This, count: u32, lists: *const This, _token: u64, _flags: u32) { + execute(this, count, lists); +} +/// Signal with sync settings for the top and bottom of the pipe; our +/// submissions are complete when they return, so it signals at once. +extern "system" fn signal2_x( + this: This, + fence: This, + value: u64, + _bottom: *const u8, + _top: *const u8, +) -> HRESULT { + signal(this, fence, value) +} +/// Markers and events only matter to profilers. +extern "system" fn marker(_: This) {} +extern "system" fn signal(this: This, fence: This, value: u64) -> HRESULT { + if fence.is_null() { + return E_INVALIDARG; + } + #[cfg(all(windows, feature = "diagnostics"))] + crate::fence::pace::signal_called(fence as usize, value); + // A queue that waits signals after what it holds. + #[cfg(windows)] + if hold(this, || Held::Signal(fence as usize, value)) { + return S_OK; + } + // Behind the submissions sent to the card and not waited for: the + // fence is set when they are settled. + #[cfg(windows)] + if crate::host::late_signal(fence as usize, value) { + return S_OK; + } + let _ = this; + crate::fence::signal(fence, value) +} +/// From here on the queue runs nothing it is given until `fence` reaches +/// `value`: how the console orders work between queues (the title's +/// compute queue waits for the depth the graphics queue draws). Our +/// submissions run when they are made, so a wait for a value already +/// reached is nothing; otherwise what the queue is given next is held +/// ([`Held`]) until a signal or a list's bottom-of-pipe write gets the +/// fence there. +extern "system" fn wait(this: This, fence: This, value: u64) -> HRESULT { + if fence.is_null() { + return E_INVALIDARG; + } + #[cfg(windows)] + if !this.is_null() { + let now = crate::fence::completed(fence); + // Whether the title uses this at all (the first calls). + { + static CALLS: AtomicU64 = AtomicU64::new(0); + if CALLS.fetch_add(1, Ordering::Relaxed) < 8 { + tracing::info!(kind = queue(this).kind, now, value, "a queue is told to wait for a fence"); + } + } + #[cfg(feature = "diagnostics")] + crate::capture::op(this as usize, || format!("WAIT queue kind {} for fence {fence:?} value {value} (now {now})", queue(this).kind)); + let behind = { + let mut held = lock(&queue(this).held); + let behind = !held.is_empty() || now < value; + if behind && waits() { + held.push(Held::Wait(fence as usize, value)); + } + behind + }; + if behind { + static SEEN: AtomicU64 = AtomicU64::new(0); + if SEEN.fetch_add(1, Ordering::Relaxed) < 8 { + tracing::info!( + kind = queue(this).kind, + now, + value, + held = waits(), + "a queue waits for a fence not reached yet" + ); + } + } + if behind && waits() { + { + let mut waiting = lock(&WAITING); + if !waiting.contains(&(this as usize)) { + waiting.push(this as usize); + } + } + // The fence may have got there meanwhile. + release_held(false); + } + } + let _ = (this, value); + S_OK +} +/// Ticks per second of GPU timestamps (see [`Written::GpuTimestamp`]). +extern "system" fn timestamp_frequency(_: This, out: *mut u64) -> HRESULT { + if out.is_null() { + return E_INVALIDARG; + } + // SAFETY: checked non-null. + unsafe { out.write(TIMESTAMP_FREQUENCY) }; + S_OK +} +const TIMESTAMP_FREQUENCY: u64 = 100_000_000; + +/// What a list's bottom-of-pipe write stores when the list has run. +#[derive(Debug, Clone, Copy)] +pub(crate) enum Written { + Value(u64), + /// The GPU clock: [`TIMESTAMP_FREQUENCY`] ticks per second since the + /// process started (our GPU work is done on the CPU's timeline). + GpuTimestamp, + /// The CPU's performance counter. + SystemTimestamp, +} + +impl Written { + /// Stores the low `bytes` (4 or 8) of the value at `at`. + pub(crate) fn write(self, at: *mut u8, bytes: usize) { + let value = match self { + Written::Value(v) => v, + Written::GpuTimestamp => { + static START: std::sync::OnceLock = std::sync::OnceLock::new(); + let elapsed = START.get_or_init(std::time::Instant::now).elapsed(); + (elapsed.as_nanos() / (1_000_000_000 / u128::from(TIMESTAMP_FREQUENCY))) as u64 + } + Written::SystemTimestamp => system_timestamp(), + }; + // SAFETY: the title names writable GPU memory (unified with ours). + unsafe { + if bytes == 4 { + at.cast::().write_unaligned(value as u32); + } else { + at.cast::().write_unaligned(value); + } + } + } +} + +fn system_timestamp() -> u64 { + #[cfg(windows)] + { + let mut count = 0; + // SAFETY: a valid out pointer. + unsafe { windows_sys::Win32::System::Performance::QueryPerformanceCounter(&mut count) }; + count as u64 + } + #[cfg(not(windows))] + 0 +} + +/// Frames presented so far. +static FRAMES: AtomicU64 = AtomicU64::new(0); + +#[cfg(feature = "diagnostics")] +pub(crate) fn presented() -> u64 { + FRAMES.load(Ordering::Relaxed) +} + +/// Shows the first plane's first resource in our window. +/// +/// shortcut: one plane, no scaling or placement, the source expected in +/// the common state. +extern "system" fn present( + this: This, + planes: u32, + plane_parameters: *const Plane, + _parameters: *const u8, +) -> HRESULT { + #[cfg(windows)] + let presenting = std::time::Instant::now(); + let hr = present_now(this, planes, plane_parameters); + #[cfg(windows)] + { + crate::framelog::add(crate::framelog::T::PresentUs, presenting.elapsed().as_micros() as u64); + crate::framelog::frame(); + #[cfg(feature = "diagnostics")] + crate::fence::pace::frame(); + } + hr +} + +fn present_now(this: This, planes: u32, plane_parameters: *const Plane) -> HRESULT { + #[cfg(windows)] + let presenting = std::time::Instant::now(); + #[cfg(all(windows, feature = "diagnostics"))] + crate::copystat::present_begins(); + #[cfg(all(windows, feature = "diagnostics"))] + crate::profile::frame(); + // With `present_behind`: the frame is shown by our thread, behind what + // the queue holds, and nothing is run or waited for here. + #[cfg(windows)] + let sent_behind = present_behind() && send_behind(this, planes, plane_parameters); + #[cfg(not(windows))] + let _ = this; + // Submissions sent to the card and not waited for are settled first, + // and what that frees runs in its own order, before anything is forced. + #[cfg(windows)] + if sent_behind { + } else if crate::host::late() && !crate::host::late_free_present() { + // (With `behind`: what the queues hold runs here first, and what + // it sent is settled with the rest.) + if behind() { + release_held_now(false); + } + crate::host::settle_for_present(); + release_held_now(false); + crate::host::settle_for_present(); + } else if crate::host::late() { + // The present is sent ahead too: what waits for a value a flight + // will write runs behind that flight, and nothing is settled here. + release_held_now(false); + } + // shortcut: what a queue still holds at a present runs now, whatever + // its fence: a wait is not kept across frames. + #[cfg(windows)] + if !sent_behind { + release_held(forces()); + } + #[cfg(windows)] + crate::framelog::add(crate::framelog::T::PresentLineUs, presenting.elapsed().as_micros() as u64); + let frame = FRAMES.fetch_add(1, Ordering::Relaxed) + 1; + #[cfg(windows)] + if sent_behind && PRESENTS_BEHIND.load(Ordering::Relaxed).is_multiple_of(512) { + tracing::info!( + frame, + behind = PRESENTS_BEHIND.load(Ordering::Relaxed), + "presents sent behind their queue's line so far (LEONIDA_ASYNC_PRESENT=1); the others ran the old way" + ); + } + if frame.is_power_of_two() { + let (draws, dispatches) = crate::list::take_counts(); + #[cfg(windows)] + let (drawn, dispatched) = { + static DRAWN: AtomicU64 = AtomicU64::new(0); + static DISPATCHED: AtomicU64 = AtomicU64::new(0); + let since = |last: &AtomicU64, now: u64| now - last.swap(now, Ordering::Relaxed); + ( + since(&DRAWN, crate::draw::drawn()), + since(&DISPATCHED, crate::draw::dispatched()), + ) + }; + #[cfg(not(windows))] + let (drawn, dispatched) = (0, 0); + tracing::info!( + frame, + draws, + drawn, + dispatches, + dispatched, + "frame presented (since the last line: draws and dispatches, and those run on the host)" + ); + #[cfg(windows)] + if frame >= 256 { + let (hits, misses) = crate::shader_cache::counts(); + tracing::info!(hits, misses, "shaders from the cache and translated so far"); + } + } + #[cfg(all(windows, feature = "diagnostics"))] + { + crate::capture::frame_drew(frame, crate::draw::drawn()); + if crate::capture::listed(frame) { + crate::capture::dump_targets(frame); + } + } + #[cfg(windows)] + if !sent_behind + && planes > 0 + // SAFETY: the title passes `planes` plane descriptions. + && let Some(plane) = unsafe { plane_parameters.as_ref() } + && plane.count > 0 + && !plane.resources.is_null() + // SAFETY: the plane lists `count` resources. + && let resource = unsafe { *plane.resources } + && let Some(texture) = crate::resource::host_resource(resource) + && let Some(host) = crate::host::host() + { + const COPY_SOURCE: u32 = 0x800; + let state = crate::resource::host_transition(resource, COPY_SOURCE) + .map_or(COPY_SOURCE, |(_, before)| before); + let shown = host.present(texture, state, frame); + crate::resource::host_transition(resource, state); + #[cfg(feature = "diagnostics")] + blinks(frame, resource, state, shown); + #[cfg(not(feature = "diagnostics"))] + let _ = shown; + } + #[cfg(not(windows))] + let _ = (planes, plane_parameters); + S_OK +} +/// Diagnostics: logs a presented frame that is black after one that was +/// not, with what was presented and how many draws ran since. +#[cfg(all(windows, feature = "diagnostics"))] +fn blinks(frame: u64, resource: This, state: u32, shown: Option) { + static LAST: std::sync::Mutex<(bool, u64, u64)> = std::sync::Mutex::new((false, 0, 0)); + let mut last = LAST.lock().unwrap_or_else(|e| e.into_inner()); + let drawn = crate::draw::drawn(); + let black = shown.unwrap_or(false); + let draws = crate::draw::take_frame(); + if black && !last.0 { + last.2 += 1; + tracing::warn!( + frame, + resource = ?resource, + state = format_args!("{state:#x}"), + draws = drawn - last.1, + copied = shown.is_some(), + black_frames = last.2, + levels = ?crate::capture::recent_levels(), + "a black frame after a frame that was not" + ); + for d in draws { + tracing::warn!("black frame {frame}: {d}"); + } + AFTER.store(frame + 6, Ordering::Relaxed); + } + // Six frames on: the levels around it (a fade or a single drop). + static AFTER: AtomicU64 = AtomicU64::new(0); + if AFTER.load(Ordering::Relaxed) == frame { + tracing::warn!(frame, levels = ?crate::capture::recent_levels(), "levels after the black frame"); + } + *last = (black, drawn, last.2); +} + +/// A run of destination pages: how they are mapped (0 pool pages from +/// `start` on, 1 pool page `start` each, 2 unmapped, 3 left as they are) +/// and how many. +#[repr(C)] +pub(crate) struct PageRange { + kind: u32, + start: u32, + count: u32, +} + +/// The ranges mapped from a destination address on. +#[repr(C)] +pub(crate) struct PageBatch { + destination: u64, + count: u32, + ranges: *const PageRange, +} + +/// Bytes per mapped page. +const PAGE: u64 = 64 << 10; + +/// `CopyPageMappingsBatchX(count, batches, pool, pool pages, flags)`: maps +/// pages of a pool (memory the title mapped physical pages into) at the +/// batches' addresses. The title streams textures into pool pages +/// and maps them into its tiled heap this way (title+0xf2c470, ranges of +/// one constant page or of unmapped pages). Done at once: every earlier +/// submission has run. +extern "system" fn copy_page_mappings( + _: This, + count: u32, + batches: *const PageBatch, + pool: u64, + pool_pages: u32, + _flags: u32, +) -> HRESULT { + let Some(map) = crate::resource::page_mapper() else { + return E_INVALIDARG; + }; + if batches.is_null() && count > 0 { + return E_INVALIDARG; + } + let batches = (count > 0).then(|| { + // SAFETY: the title passes `count` batches. + unsafe { std::slice::from_raw_parts(batches, count as usize) } + }); + let mut ok = true; + for b in batches.into_iter().flatten() { + if b.ranges.is_null() { + continue; + } + // SAFETY: each batch holds `count` ranges. + let ranges = unsafe { std::slice::from_raw_parts(b.ranges, b.count as usize) }; + let mut at = b.destination; + for r in ranges { + let len = u64::from(r.count) * PAGE; + let inside = |pages: u32| r.start.checked_add(pages).is_some_and(|e| e <= pool_pages); + let source = pool + u64::from(r.start) * PAGE; + ok &= match r.kind { + 0 if inside(r.count) => map(at, source, len), + 1 if inside(1) => (0..u64::from(r.count)).all(|k| map(at + k * PAGE, source, PAGE)), + 2 => map(at, 0, len), + 3 => true, + _ => false, + }; + at += len; + } + } + if !ok { + static ONCE: std::sync::Once = std::sync::Once::new(); + ONCE.call_once(|| tracing::warn!(pool = format_args!("{pool:#x}"), "a page mapping failed")); + } + S_OK +} + +extern "system" fn desc(this: This, out: *mut QueueDesc) { + if !out.is_null() { + // SAFETY: checked non-null; the title passes room for a description. + unsafe { out.write(queue(this).desc) }; + } +} + +/// The queue methods by their slot in older titles' queues (the 2020-era +/// layout): IUnknown 3, object 4, device child 1, queue 26 (12 as on PC, +/// then console ones). +const METHODS: [(usize, *const ()); 15] = [ + (0, query as *const ()), + (2, release as *const ()), + (7, object::parent_device as *const ()), // 0x38 + (10, execute as *const ()), // 0x50 + (11, marker as *const ()), // 0x58 set marker + (12, marker as *const ()), // 0x60 begin event + (13, marker as *const ()), // 0x68 end event + (14, signal as *const ()), // 0x70 + (15, wait as *const ()), // 0x78 + (16, timestamp_frequency as *const ()), // 0x80 + (26, desc as *const ()), // 0xd0 + (29, copy_page_mappings as *const ()), // 0xe8 page mapping batch + (30, present as *const ()), // 0xf0 + (33, execute_x as *const ()), // 0x108 + (32, signal2_x as *const ()), // 0x100 +]; + +/// Newer titles' queues have two more methods before Signal, which moved +/// from 0x70 to 0x80: every slot from 0x70 on is two later (taken here as +/// starting exactly at 0x70, the methods before it kept in place). +/// Inferred from the title's calls: Signal 0x80 `(fence, +/// value)`, timestamp frequency 0x90 (title+0x24841a6), suspend and resume +/// 0xb8/0xc0, PresentX 0x100, the frame-token submission 0x118 `(count, +/// lists, token, flags)` (title+0x24821dd). +const fn newer_slot(slot: usize) -> usize { + if slot >= 14 { slot + 2 } else { slot } +} + +const fn queue_table(newer: bool) -> [*const (); 36] { + let mut f = object::d3d12_object(object::missing_table::()); + let mut i = 0; + while i < METHODS.len() { + let (slot, method) = METHODS[i]; + f[if newer { newer_slot(slot) } else { slot }] = method; + i += 1; + } + f +} + +static FUNCTIONS: Table<36> = Table(queue_table(false)); +static NEWER_FUNCTIONS: Table<36> = Table(queue_table(true)); + +#[cfg(test)] +mod tests { + use super::*; + + #[cfg(windows)] + #[test] + fn joined_parts_keep_their_lists_and_their_order() { + // a part of three lists run as 2, 0, 1; then one of two run as 1, 0; then one of one + let (lists, order) = join(vec!["a0", "a1", "a2"], vec![2, 0, 1], vec!["b0", "b1"], vec![1, 0]); + let (lists, order) = join(lists, order, vec!["c0"], vec![0]); + assert_eq!(lists, ["a0", "a1", "a2", "b0", "b1", "c0"]); + let run: Vec<&str> = order.iter().map(|&i| lists[i]).collect(); + assert_eq!(run, ["a2", "a0", "a1", "b1", "b0", "c0"], "each part's lists in its own order, the parts one after the other"); + // a part with a list named twice, and an empty one + let (lists, order) = join(vec!["a0"], vec![0, 0], Vec::new(), Vec::new()); + let (lists, order) = join(lists, order, vec!["b0"], vec![0, 0]); + assert_eq!(order.iter().map(|&i| lists[i]).collect::>(), ["a0", "a0", "b0", "b0"]); + } + use crate::object::slot; + + /// Where a queue's signal is: newer layouts have it two slots later. + /// Another test may switch layouts while this one runs, so the queue's + /// own table decides. + fn signal_slot(q: This) -> usize { + // SAFETY: one of our queues; its first field is the table. + let table = unsafe { *q.cast::<*const *const ()>() }; + if table == NEWER_FUNCTIONS.0.as_ptr() { + 0x80 + } else { + 0x70 + } + } + + #[test] + fn queue_signals_complete_at_once() { + let null = std::ptr::null(); + let desc = QueueDesc { + kind: 0, + priority: 0, + flags: 0, + nodes: 0, + }; + let mut q = null; + assert_eq!(create(null, &desc, &QUEUE_IIDS[0], &mut q), S_OK); + // SAFETY: the title reads the type at +0x10. + assert_eq!(unsafe { q.cast::().add(0x10).cast::().read() }, 0); + let mut fence = null; + let fence_iid = &crate::fence::FENCE_IIDS[0]; + assert_eq!( + crate::fence::create(null, 0, 0, fence_iid, &mut fence), + S_OK + ); + let signal = slot:: HRESULT>(q, signal_slot(q)); + assert_eq!(signal(q, fence, 7), S_OK); + assert_eq!( + slot:: u64>(fence, 0x40)(fence), + 7 + ); + assert_eq!(slot:: u32>(q, 0x10)(q), 0); + } + + /// The title's compute queue: `{COMPUTE, 0, pipe 1, queue 0}`. + #[test] + fn console_queues_are_created_as_on_pc() { + let null = std::ptr::null(); + let desc = QueueDescX { + kind: 2, + flags: 0, + engine_or_pipe: 1, + queue: 0, + }; + let mut q = null; + assert_eq!(create_x(null, &desc, &QUEUE_IIDS[0], &mut q), S_OK); + assert_eq!(queue(q).desc.kind, 2); + let none = std::ptr::null(); + assert_eq!(create_x(null, none, &QUEUE_IIDS[0], &mut q), E_INVALIDARG); + } + + #[test] + fn newer_queues_have_their_methods_two_slots_later() { + let (old, new) = (queue_table(false), queue_table(true)); + assert_eq!(old[10], new[10]); // submission stays at 0x50 + assert_eq!(old[14], new[16]); // signal 0x70 → 0x80 + assert_eq!(old[30], new[32]); // present 0xf0 → 0x100 + assert_eq!(new[35], execute_x as *const ()); // 0x118 + } + + #[test] + fn timestamps_and_values_are_written() { + let mut at = [0u64; 2]; + Written::Value(0x1_0000_0002).write(at.as_mut_ptr().cast(), 4); + assert_eq!(at[0], 2); + Written::GpuTimestamp.write(at[1..].as_mut_ptr().cast(), 8); + let first = at[1]; + std::thread::sleep(std::time::Duration::from_millis(2)); + Written::GpuTimestamp.write(at[1..].as_mut_ptr().cast(), 8); + assert!(at[1] > first); + } +} diff --git a/crates/leonida-gpu/src/queue2.rs b/crates/leonida-gpu/src/queue2.rs new file mode 100644 index 000000000..cca297f1a --- /dev/null +++ b/crates/leonida-gpu/src/queue2.rs @@ -0,0 +1,1047 @@ +//! More queues on the card, for copies only (`LEONIDA_QUEUE2`; off by +//! default): work of ours that does not depend on the order of the title's +//! draws goes to a copy queue of its own and no longer stands in the one +//! direct queue behind them. A copy queue runs on the card's copy engine, +//! beside the engine that draws. +//! +//! Two lanes, each a copy queue with a fence of its own, so that one never +//! stands behind the other: +//! +//! - **down** (bit 1): the fetch of the pieces shaders wrote in copies in +//! the card's memory (`Host::relay_card_back`, `Host::card_back`). With +//! the relay that fetch stood behind every flight sent since: 114-157 ms +//! a frame of the landing thread's 176-229 (run 118). +//! - **up** (bit 2): the title bytes that changed on the CPU's side of such +//! copies cross to the card's memory (`Host::card_before`), into a +//! landing buffer of ours there; the direct queue waits for them and +//! moves them on into the copies, inside the card's memory. +//! +//! What is synchronised, and with what: +//! +//! - A job of a lane may wait for fences of the direct queue +//! ([`Lane::send`]'s `after`: `ID3D12CommandQueue::Wait` on the lane's +//! queue). A fetch names the fence value behind the last flight it lands, +//! so it runs after that flight's lists and its compare. +//! - The direct queue waits for a job of the up lane ([`Second::hold`]: +//! `Wait` on the direct queue for the lane's fence), so nothing sent to +//! the direct queue afterwards runs before the bytes have landed. +//! - No wait can stand for ever: a job only ever waits for a value already +//! signalled on the direct queue, and the direct queue only for a job +//! already sent, so each wait's partner lies ahead of it in its queue. +//! - Only buffers go through the lanes. A buffer needs no state change for +//! a copy queue (it is promoted from the common state and falls back to +//! it), and it may be READ on one queue while another queue's work on it +//! is in the air; a texture may not, which is why no texture goes this +//! way. +//! - No lane WRITES a buffer that the direct queue's work in the air +//! names: the host's debug layer calls that an error ("not safe to start +//! write GPU operations now on this Command Queue", seen on the software +//! adapter with a first draft that copied title bytes straight into the +//! copies). Hence the landing buffers ([`Second::landing`]): each is +//! written by one job of the up lane and read by the direct queue behind +//! its wait for that job, and is given out again only when the card has +//! passed that read. The copies themselves change only on the direct +//! queue, in its order, as before. +//! - With the relay the sends of title bytes are numbered +//! (`crate::host::QUEUE_ORDER`). The direct queue signals each number +//! behind its send ([`Second::sent_up`]), and a fetch on the down lane +//! takes for "the sends ahead of me" those the card has finished +//! ([`Second::order_done`]). A later send that the card happens to run +//! before the fetch is left out by the merge as one that came after +//! (`Shadow::card_merge_relay`): the title's bytes stand, as they would. + +use std::sync::atomic::{AtomicU64, Ordering}; +use std::sync::mpsc::{Receiver, Sender, channel}; +use std::sync::{Mutex, OnceLock}; +use std::time::Instant; + +use windows::Win32::Foundation::HANDLE; +use windows::Win32::Graphics::Direct3D12::*; +use windows::Win32::System::Threading::{CreateEventW, INFINITE, WaitForSingleObject}; +use windows::core::Interface; + +/// `LEONIDA_QUEUE2`, a sum of bits; unset or 0: off, everything goes +/// through the one direct queue as before. +/// +/// - 1: fetches of what shaders wrote to copies in the card's memory go to +/// a copy queue (the gain is with `LEONIDA_RELAY=1`/`2`; without the +/// relay nothing else is queued when they run, so it only shows that +/// the path works); +/// - 2: the title bytes sent up to copies in the card's memory cross from +/// the PC's memory on a copy queue, into landing buffers in the card's +/// memory ([`landing_most`] says how much of it), and the direct queue +/// moves them on from there. +/// +/// Read once, when the first submission asks. +pub(crate) fn bits() -> u32 { + static BITS: OnceLock = OnceLock::new(); + *BITS.get_or_init(|| std::env::var("LEONIDA_QUEUE2").ok().and_then(|v| v.trim().parse::().ok()).unwrap_or(0) & 3) +} + +/// The most bytes of landing buffers in the card's memory, for title +/// bytes on their way to copies there (`LEONIDA_QUEUE2_LANDING_MB`, 96; +/// a frame sent up 45-76 MB in runs 116-120, and a buffer is free again as +/// soon as the card has run the submission it was for). A send that finds +/// no room goes straight from the PC's memory on the direct queue, as +/// without the switch; the frame line counts those. +fn landing_most() -> u64 { + static MOST: OnceLock = OnceLock::new(); + *MOST.get_or_init(|| { + std::env::var("LEONIDA_QUEUE2_LANDING_MB").ok().and_then(|v| v.trim().parse::().ok()).unwrap_or(96) << 20 + }) +} + +/// A buffer in the card's memory that title bytes land in. +struct Landing { + buffer: ID3D12Resource, + size: u64, + /// The value of the host's fence that the card passes after the direct + /// queue's last read of the buffer: free once it is reached. + until: u64, +} + +/// Which landing buffer (its size, and the fence value it is held until) +/// takes `bytes` when the host's fence has reached `completed`: the +/// smallest free one that holds them. +fn pick_landing(landings: &[(u64, u64)], bytes: u64, completed: u64) -> Option { + landings + .iter() + .enumerate() + .filter(|&(_, &(size, until))| until <= completed && size >= bytes) + .min_by_key(|&(_, &(size, _))| size) + .map(|(at, _)| at) +} + +/// An allocator and a list of the copy type. +pub(crate) type CopyList = (ID3D12CommandAllocator, ID3D12GraphicsCommandList); + +/// Since the last frame-rate line, of one lane: jobs, their bytes, +/// microseconds the lane had a job (sent and not finished: its time on the +/// card and its waits for the direct queue's fences), microseconds a thread +/// of ours stood waiting for its jobs. +#[derive(Default)] +pub(crate) struct LaneStats { + pub(crate) jobs: AtomicU64, + pub(crate) bytes: AtomicU64, + pub(crate) busy_us: AtomicU64, + pub(crate) waited_us: AtomicU64, +} + +struct LaneState { + /// Jobs sent: the last value signalled on the lane's fence. + sent: u64, + /// Lists not in use, each with the job it last ran in: free for the + /// next job once the card has run that one. + spare: Vec<(u64, CopyList)>, + /// To the lane's clock: a job and when it was sent. + clock: Option>, +} + +/// A copy queue with a fence of its own; its jobs run in the order sent. +pub(crate) struct Lane { + device: ID3D12Device, + queue: ID3D12CommandQueue, + /// Signalled on `queue` behind each job with the job's number. + fence: ID3D12Fence, + state: Mutex, + pub(crate) stats: LaneStats, +} + +// SAFETY: D3D12 devices, queues, fences, allocators and lists are +// free-threaded objects; the lists are recorded by the thread that took +// them and otherwise touched under `state`. +unsafe impl Send for Lane {} +// SAFETY: as above. +unsafe impl Sync for Lane {} + +fn lock(mutex: &Mutex) -> std::sync::MutexGuard<'_, T> { + mutex.lock().unwrap_or_else(|e| e.into_inner()) +} + +/// A lane's busy time grows by the stretch from `sent` (or from when the +/// job before it finished, `before`, if that was later: the lane was busy +/// with that one until then) to `done`. Returns the microseconds. +fn busy_stretch(before: Option, sent: Instant, done: Instant) -> u64 { + let from = before.map_or(sent, |b| b.max(sent)); + done.saturating_duration_since(from).as_micros() as u64 +} + +impl Lane { + fn new(device: &ID3D12Device, name: &str) -> windows::core::Result { + // SAFETY: plain object creation with valid descriptions. + unsafe { + let queue: ID3D12CommandQueue = device.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC { + Type: D3D12_COMMAND_LIST_TYPE_COPY, + ..Default::default() + })?; + let fence: ID3D12Fence = device.CreateFence(0, D3D12_FENCE_FLAG_NONE)?; + let wide: Vec = format!("leonida copy queue ({name})").encode_utf16().chain([0]).collect(); + let _ = queue.SetName(windows::core::PCWSTR(wide.as_ptr())); + Ok(Lane { + device: device.clone(), + queue, + fence, + state: Mutex::new(LaneState { + sent: 0, + spare: Vec::new(), + clock: None, + }), + stats: LaneStats::default(), + }) + } + } + + /// Starts the lane's clock: a thread that waits for each job in turn + /// and adds up how long the lane had one ([`LaneStats::busy_us`]). + fn clocked(&'static self, name: &str) { + let (tx, rx) = channel(); + let started = std::thread::Builder::new().name(format!("leonida-queue2-{name}")).spawn(move || self.watch(&rx)); + match started { + Ok(_) => lock(&self.state).clock = Some(tx), + Err(e) => tracing::warn!(error = %e, "no thread for a copy queue's clock: its milliseconds stay 0"), + } + } + + fn watch(&self, jobs: &Receiver<(u64, Instant)>) { + // SAFETY: a plain event of our own. + let Ok(event) = (unsafe { CreateEventW(None, false, false, None) }) else { + return; + }; + let mut before = None; + while let Ok((job, sent)) = jobs.recv() { + if self.wait(job, event).is_err() { + return; + } + let done = Instant::now(); + self.stats.busy_us.fetch_add(busy_stretch(before, sent, done), Ordering::Relaxed); + before = Some(done); + } + } + + /// An open list of the copy type: one whose last job the card has run, + /// or a new one. + pub(crate) fn list(&self) -> windows::core::Result { + // SAFETY: a plain query; a list is reset only when the job it ran + // in is done; plain object creation otherwise. + unsafe { + let done = self.fence.GetCompletedValue(); + let free = { + let mut state = lock(&self.state); + state.spare.iter().position(|(job, _)| *job <= done).map(|at| state.spare.swap_remove(at).1) + }; + if let Some((allocator, list)) = free { + allocator.Reset()?; + list.Reset(&allocator, None)?; + return Ok((allocator, list)); + } + let allocator: ID3D12CommandAllocator = self.device.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_COPY)?; + let list: ID3D12GraphicsCommandList = + self.device.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_COPY, &allocator, None)?; + Ok((allocator, list)) + } + } + + /// Closes `list` (from [`Lane::list`], with copies recorded) and sends + /// it as the lane's next job, of `bytes` bytes. The job runs behind + /// the lane's earlier jobs and not before each fence of `after` (fences + /// of other queues) has reached its value: every value must have been + /// signalled on its queue already. Returns the job's number, for + /// [`Lane::wait`], [`Lane::done`] and [`Second::hold`]. + pub(crate) fn send(&self, list: CopyList, after: &[(&ID3D12Fence, u64)], bytes: u64) -> windows::core::Result { + // SAFETY: an open list of ours; the lane's queue and fence; live + // fences of the same device. + unsafe { + list.1.Close()?; + let lists = [Some(list.1.cast::()?)]; + // One job at a time from its waits to its signal: the jobs' + // numbers are the order they run in. + let mut state = lock(&self.state); + for &(fence, value) in after { + // (A fence is at 0 before anything is signalled on it: + // nothing to wait for.) + if value != 0 { + self.queue.Wait(fence, value)?; + } + } + self.queue.ExecuteCommandLists(&lists); + state.sent += 1; + let job = state.sent; + self.queue.Signal(&self.fence, job)?; + state.spare.push((job, list)); + if let Some(clock) = &state.clock { + let _ = clock.send((job, Instant::now())); + } + self.stats.jobs.fetch_add(1, Ordering::Relaxed); + self.stats.bytes.fetch_add(bytes, Ordering::Relaxed); + Ok(job) + } + } + + /// Whether the card has run `job`. + pub(crate) fn done(&self, job: u64) -> bool { + // SAFETY: a plain query. + unsafe { self.fence.GetCompletedValue() >= job } + } + + /// Waits on this thread, with its `event`, until the card has run + /// `job`. + pub(crate) fn wait(&self, job: u64, event: HANDLE) -> windows::core::Result<()> { + // SAFETY: the lane's fence and the caller's event. + unsafe { + if self.fence.GetCompletedValue() < job { + self.fence.SetEventOnCompletion(job, event)?; + WaitForSingleObject(event, INFINITE); + } + } + Ok(()) + } +} + +/// The copy queues and what ties them to the direct queue. +pub(crate) struct Second { + bits: u32, + device: ID3D12Device, + /// The landing buffers made so far ([`Second::landing`]). + landings: Mutex>, + /// The landing buffers' bytes alive; since the last frame-rate line, + /// the sends that found no room in them. + pub(crate) landing: [AtomicU64; 2], + /// Fetches (bit 1). + pub(crate) down: Lane, + /// Sends of title bytes to copies in the card's memory (bit 2). + pub(crate) up: Lane, + /// Signalled on the DIRECT queue behind each numbered send of title + /// bytes, with its number ([`Second::sent_up`]). + order: ID3D12Fence, + /// Signalled on the DIRECT queue just ahead of each wait for the up + /// lane ([`Second::hold`]), for the clock: when the direct queue got + /// there. Behind the lock: the holds made so far, and the way to the + /// thread that times them. + reached: ID3D12Fence, + holds: Mutex<(u64, Option>)>, + /// Since the last frame-rate line: waits of the direct queue for the up + /// lane, those of them at which it stood, and for how many + /// microseconds. + pub(crate) held: [AtomicU64; 3], +} + +// SAFETY: fences (free-threaded) and lanes. +unsafe impl Send for Second {} +// SAFETY: as above. +unsafe impl Sync for Second {} + +impl Second { + /// The lanes on `device`. `bits` as [`bits`]. + pub(crate) fn new(device: &ID3D12Device, bits: u32) -> windows::core::Result { + // SAFETY: plain fences on the device. + unsafe { + Ok(Second { + bits, + device: device.clone(), + landings: Mutex::new(Vec::new()), + landing: [const { AtomicU64::new(0) }; 2], + down: Lane::new(device, "down")?, + up: Lane::new(device, "up")?, + order: device.CreateFence(0, D3D12_FENCE_FLAG_NONE)?, + reached: device.CreateFence(0, D3D12_FENCE_FLAG_NONE)?, + holds: Mutex::new((0, None)), + held: [const { AtomicU64::new(0) }; 3], + }) + } + } + + /// Starts the clocks: the lanes' and the one that times the direct + /// queue's waits ([`Second::held`]). + pub(crate) fn clocked(&'static self) { + self.down.clocked("down"); + self.up.clocked("up"); + let (tx, rx) = channel(); + match std::thread::Builder::new().name("leonida-queue2-holds".into()).spawn(move || self.watch_holds(&rx)) { + Ok(_) => lock(&self.holds).1 = Some(tx), + Err(e) => tracing::warn!(error = %e, "no thread to time the direct queue's waits for the copy queue: they stay 0"), + } + } + + /// Whether fetches go to the down lane. + pub(crate) fn fetches(&self) -> bool { + self.bits & 1 != 0 + } + + /// Whether title bytes go up through the up lane. + pub(crate) fn uploads(&self) -> bool { + self.bits & 2 != 0 + } + + /// A buffer in the card's memory for `bytes` title bytes on their way + /// up, for a job of the up lane to write and the direct queue to read + /// behind its wait for that job ([`Second::hold`]). `completed`: the + /// value the host's fence has reached; `until`: the value it reaches + /// when the card has run that read (the next one signalled behind + /// it). The buffer is not given out again before then, so no job + /// writes it while anything in the air names it. `None`: no room under + /// [`landing_most`], or no memory; the caller sends the bytes the old + /// way. + pub(crate) fn landing(&self, bytes: u64, completed: u64, until: u64) -> Option { + let mut landings = lock(&self.landings); + let sizes: Vec<(u64, u64)> = landings.iter().map(|l| (l.size, l.until)).collect(); + if let Some(at) = pick_landing(&sizes, bytes, completed) { + landings[at].until = until; + return Some(landings[at].buffer.clone()); + } + // A new one; free ones that are too small make room for it (the + // card has passed their last use: nothing names them). + let size = bytes.next_multiple_of(1 << 20); + let alive = |landings: &[Landing]| landings.iter().map(|l| l.size).sum::(); + if alive(&landings) + size > landing_most() { + landings.retain(|l| l.until > completed); + } + let made = if alive(&landings) + size > landing_most() { + None + } else { + let heap = D3D12_HEAP_PROPERTIES { + Type: D3D12_HEAP_TYPE_DEFAULT, + ..Default::default() + }; + let desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, + Width: size, + Height: 1, + DepthOrArraySize: 1, + MipLevels: 1, + SampleDesc: windows::Win32::Graphics::Dxgi::Common::DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, + ..Default::default() + }; + let mut buffer: Option = None; + // SAFETY: plain creation of a buffer in the card's memory. + let made = unsafe { + self.device.CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &desc, D3D12_RESOURCE_STATE_COMMON, None, &mut buffer) + }; + match (made, buffer) { + (Ok(()), Some(buffer)) => { + let wide: Vec = "leonida landing buffer (title bytes on their way up)".encode_utf16().chain([0]).collect(); + // SAFETY: a live buffer and a terminated string. + let _ = unsafe { buffer.SetName(windows::core::PCWSTR(wide.as_ptr())) }; + landings.push(Landing { + buffer: buffer.clone(), + size, + until, + }); + Some(buffer) + } + _ => None, + } + }; + self.landing[0].store(alive(&landings), Ordering::Relaxed); + if made.is_none() { + self.landing[1].fetch_add(1, Ordering::Relaxed); + } + made + } + + /// The numbered send `number` of title bytes has just gone to `direct` + /// (or there was nothing to send under that number): the number is + /// signalled behind it. + pub(crate) fn sent_up(&self, direct: &ID3D12CommandQueue, number: u64) { + // SAFETY: a live queue and our fence. + let _ = unsafe { direct.Signal(&self.order, number) }; + } + + /// The last numbered send of title bytes the card has finished: every + /// send up to it is in what a fetch sent from now on brings down. + pub(crate) fn order_done(&self) -> u64 { + // SAFETY: a plain query. + unsafe { self.order.GetCompletedValue() } + } + + /// Makes `direct` wait for `job` of the up lane: nothing sent to it + /// from now on runs before the card has run the job. The job must have + /// been sent ([`Lane::send`]). + pub(crate) fn hold(&self, direct: &ID3D12CommandQueue, job: u64) -> windows::core::Result<()> { + let mut holds = lock(&self.holds); + holds.0 += 1; + // SAFETY: a live queue and our fences. + unsafe { + // For the clock only: the moment the queue gets to the wait. + let _ = direct.Signal(&self.reached, holds.0); + direct.Wait(&self.up.fence, job)?; + } + self.held[0].fetch_add(1, Ordering::Relaxed); + if let Some(clock) = &holds.1 { + let _ = clock.send((holds.0, job)); + } + Ok(()) + } + + /// Times the holds, in the order they were made: from the moment the + /// direct queue got to one until the job it waits for is done. (While + /// it stands at one it gets to no later one, so one thread sees each + /// in time.) + fn watch_holds(&self, holds: &Receiver<(u64, u64)>) { + // SAFETY: a plain event of our own. + let Ok(event) = (unsafe { CreateEventW(None, false, false, None) }) else { + return; + }; + while let Ok((hold, job)) = holds.recv() { + // SAFETY: our fence and this thread's event. + unsafe { + if self.reached.GetCompletedValue() < hold { + if self.reached.SetEventOnCompletion(hold, event).is_err() { + return; + } + WaitForSingleObject(event, INFINITE); + } + } + if self.up.done(job) { + continue; + } + let standing = Instant::now(); + if self.up.wait(job, event).is_err() { + return; + } + self.held[1].fetch_add(1, Ordering::Relaxed); + self.held[2].fetch_add(standing.elapsed().as_micros() as u64, Ordering::Relaxed); + } + } +} + +/// The copy queues, made at the first ask if [`bits`] says so; `None` when +/// the switch is off or they could not be made (everything then goes +/// through the direct queue, as before). +pub(crate) fn second() -> Option<&'static Second> { + static SECOND: OnceLock> = OnceLock::new(); + static CLOCKS: std::sync::Once = std::sync::Once::new(); + if bits() == 0 { + return None; + } + let second = SECOND + .get_or_init(|| { + let host = crate::host::host()?; + match Second::new(&host.device, bits()) { + Ok(second) => { + tracing::info!( + fetches = second.fetches(), + uploads = second.uploads(), + landing_mb = landing_most() >> 20, + "copy queues on the card beside the direct queue (LEONIDA_QUEUE2={})", + bits() + ); + Some(second) + } + Err(e) => { + tracing::warn!(error = %e, "no copy queues (LEONIDA_QUEUE2): everything goes through the direct queue"); + None + } + } + }) + .as_ref()?; + CLOCKS.call_once(|| second.clocked()); + Some(second) +} + +/// For the frame-rate line: what the copy queues did per frame since the +/// last one. "On their queue" is from a job's send to its end with each +/// moment counted once: its time on the card and any wait of its queue +/// for the direct queue's fences. The direct queue "stood" at a wait if +/// the job was not done when it got there. +pub(crate) fn line(frames: f64) { + let Some(second) = second() else { + return; + }; + let take = |a: &AtomicU64| a.swap(0, Ordering::Relaxed) as f64 / frames; + let ms = |a: &AtomicU64| take(a) / 1000.0; + let mb = |a: &AtomicU64| take(a) / (1 << 20) as f64; + let (down, up) = (&second.down.stats, &second.up.stats); + let (down_jobs, down_mb, down_busy, down_waited) = (take(&down.jobs), mb(&down.bytes), ms(&down.busy_us), ms(&down.waited_us)); + let (up_jobs, up_mb, up_busy) = (take(&up.jobs), mb(&up.bytes), ms(&up.busy_us)); + let [holds, stood, stood_us] = [0, 1, 2].map(|i| take(&second.held[i])); + let (landing_mb, no_room) = (second.landing[0].load(Ordering::Relaxed) >> 20, take(&second.landing[1])); + tracing::info!( + "the copy queues per frame (LEONIDA_QUEUE2={}): fetches of what shaders wrote: {down_jobs:.1} jobs, {down_mb:.1} MB, \ + {down_busy:.1} ms on their queue, our threads stood {down_waited:.1} ms waiting for them; title bytes sent up: \ + {up_jobs:.1} jobs, {up_mb:.1} MB, {up_busy:.1} ms on their queue; the direct queue was told to wait for them \ + {holds:.1} times and stood at {stood:.1} of those for {:.1} ms in all; landing buffers on the card: {landing_mb} MB, \ + {no_room:.1} sends found no room in them and went through the direct queue (LEONIDA_QUEUE2_LANDING_MB)", + second.bits, + stood_us / 1000.0 + ); +} + +#[cfg(test)] +mod tests { + use super::*; + use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_12_0; + use windows::Win32::Graphics::Direct3D::Fxc::D3DCompile; + use windows::Win32::Graphics::Direct3D::ID3DBlob; + use windows::Win32::Graphics::Dxgi::Common::DXGI_SAMPLE_DESC; + use windows::Win32::Graphics::Dxgi::*; + use windows::core::s; + + /// A lane's busy time counts each moment once: a job sent while the + /// one before it still ran adds only what came after that one. + #[test] + fn a_lanes_busy_time_counts_each_moment_once() { + let t = Instant::now(); + let at = |ms: u64| t + std::time::Duration::from_millis(ms); + // Alone: from the send to the end. + assert_eq!(busy_stretch(None, at(10), at(14)), 4_000); + // Sent at 10 while the job before ran until 12: 12 to 14. + assert_eq!(busy_stretch(Some(at(12)), at(10), at(14)), 2_000); + // Sent after the one before had finished: from the send. + assert_eq!(busy_stretch(Some(at(5)), at(10), at(14)), 4_000); + // (The clock's own lateness never makes a stretch negative.) + assert_eq!(busy_stretch(Some(at(20)), at(10), at(14)), 0); + } + + /// A landing buffer is given out again only when the card has passed + /// its last use, and the smallest one that holds the bytes is taken. + #[test] + fn a_landing_buffer_is_free_when_the_card_has_passed_its_use() { + // (size, held until this value of the host's fence) + let landings = [(4 << 20, 10), (1 << 20, 12), (2 << 20, 7), (8 << 20, 7)]; + // The card is at 9: the third and fourth are free. + assert_eq!(pick_landing(&landings, 1 << 20, 9), Some(2)); + assert_eq!(pick_landing(&landings, 3 << 20, 9), Some(3)); + assert_eq!(pick_landing(&landings, 9 << 20, 9), None); + // At 10 the first is free too, and is the smallest for 3 MiB. + assert_eq!(pick_landing(&landings, 3 << 20, 10), Some(0)); + // At 6 none is: a use that the card has not passed holds its buffer. + assert_eq!(pick_landing(&landings, 1, 6), None); + // The value itself frees it (the signal is behind the read). + assert_eq!(pick_landing(&landings, 1, 7), Some(2)); + assert_eq!(pick_landing(&[], 1, u64::MAX), None); + } + + /// A shader of the direct queue that takes a while and then stores a + /// dword: `at` (bytes) gets `value`. + const SLOW_STORE: &str = r#" +#define RS "RootConstants(num32BitConstants=3, b0), UAV(u0)" +cbuffer What : register(b0) { uint at; uint value; uint spin; }; +RWByteAddressBuffer memory : register(u0); +[RootSignature(RS)] +[numthreads(1, 1, 1)] +void main() { + uint h = value; + [loop] + for (uint i = 0; i < spin; i++) { + h = (h ^ memory.Load((i & 63u) * 4u)) * 0x01000193u; + } + memory.Store(at, value + (h & 0u)); +} +"#; + + /// The software adapter with a direct queue and the copy queues. + struct Warp { + device: ID3D12Device, + direct: ID3D12CommandQueue, + /// The direct queue's fence and the last value signalled on it. + fence: ID3D12Fence, + submitted: u64, + event: HANDLE, + second: &'static Second, + root: ID3D12RootSignature, + pso: ID3D12PipelineState, + /// Direct lists sent and not waited for yet. + flown: Vec, + } + + impl Warp { + fn new(bits: u32) -> Option { + // SAFETY: plain DXGI and D3D12 set-up on the software adapter. + unsafe { + let factory: IDXGIFactory4 = CreateDXGIFactory2(DXGI_CREATE_FACTORY_FLAGS(0)).ok()?; + let adapter: IDXGIAdapter = factory.EnumWarpAdapter().ok()?; + let desc = adapter.cast::().ok()?.GetDesc1().ok()?; + if desc.Flags & DXGI_ADAPTER_FLAG_SOFTWARE.0 as u32 == 0 { + return None; + } + let mut device: Option = None; + D3D12CreateDevice(&adapter, D3D_FEATURE_LEVEL_12_0, &mut device).ok()?; + let device = device?; + let direct: ID3D12CommandQueue = device + .CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC { + Type: D3D12_COMMAND_LIST_TYPE_DIRECT, + ..Default::default() + }) + .ok()?; + let fence: ID3D12Fence = device.CreateFence(0, D3D12_FENCE_FLAG_NONE).ok()?; + let event = CreateEventW(None, false, false, None).ok()?; + // The clocks' threads live as long as the process: the + // queues of a test are kept for them. + let second: &'static Second = Box::leak(Box::new(Second::new(&device, bits).expect("copy queues on WARP"))); + second.clocked(); + let mut code: Option = None; + D3DCompile( + SLOW_STORE.as_ptr().cast(), + SLOW_STORE.len(), + s!("slow store"), + None, + None, + s!("main"), + s!("cs_5_1"), + 0, + 0, + &mut code, + None, + ) + .expect("the test's shader compiles"); + let code = code?; + let bytes = std::slice::from_raw_parts(code.GetBufferPointer().cast::(), code.GetBufferSize()); + let root: ID3D12RootSignature = device.CreateRootSignature(0, bytes).ok()?; + let pso: ID3D12PipelineState = device + .CreateComputePipelineState(&D3D12_COMPUTE_PIPELINE_STATE_DESC { + pRootSignature: std::mem::transmute_copy(&root), + CS: D3D12_SHADER_BYTECODE { + pShaderBytecode: bytes.as_ptr().cast(), + BytecodeLength: bytes.len(), + }, + ..Default::default() + }) + .ok()?; + Some(Warp { + device, + direct, + fence, + submitted: 0, + event, + second, + root, + pso, + flown: Vec::new(), + }) + } + } + + /// A buffer as the host makes them: in the card's own memory + /// (`Host::uav_buffer`), or in the PC's memory and mapped + /// (`Host::shared_buffer`). + fn buffer(&self, size: u64, mapped: bool) -> (ID3D12Resource, *mut u8) { + let heap = if mapped { + D3D12_HEAP_PROPERTIES { + Type: D3D12_HEAP_TYPE_CUSTOM, + CPUPageProperty: D3D12_CPU_PAGE_PROPERTY_WRITE_BACK, + MemoryPoolPreference: D3D12_MEMORY_POOL_L0, + ..Default::default() + } + } else { + D3D12_HEAP_PROPERTIES { + Type: D3D12_HEAP_TYPE_DEFAULT, + ..Default::default() + } + }; + let desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, + Width: size, + Height: 1, + DepthOrArraySize: 1, + MipLevels: 1, + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, + Flags: D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS, + ..Default::default() + }; + let mut buffer: Option = None; + let mut data = std::ptr::null_mut(); + // SAFETY: plain creation, and a mapping of CPU-visible memory. + unsafe { + self.device + .CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &desc, D3D12_RESOURCE_STATE_COMMON, None, &mut buffer) + .expect("a test buffer"); + let buffer = buffer.expect("a test buffer"); + if mapped { + buffer.Map(0, None, Some(&mut data)).expect("a mapping"); + } + (buffer, data.cast()) + } + } + + /// Sends a list of the direct queue made by `record`, with a + /// signal behind it, and does not wait: the value signalled. + fn fly(&mut self, record: impl FnOnce(&ID3D12GraphicsCommandList)) -> u64 { + // SAFETY: plain creation; an open list of ours; our queue and + // fence. + unsafe { + let allocator: ID3D12CommandAllocator = + self.device.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT).expect("an allocator"); + let list: ID3D12GraphicsCommandList = + self.device.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &allocator, None).expect("a list"); + record(&list); + list.Close().expect("the list closes"); + self.direct.ExecuteCommandLists(&[Some(list.cast().expect("a command list"))]); + self.submitted += 1; + self.direct.Signal(&self.fence, self.submitted).expect("a signal"); + self.flown.push((allocator, list)); + } + self.submitted + } + + /// A direct list that stores `value` at byte `at` of `memory` + /// after `spin` steps. + fn store(&mut self, memory: &ID3D12Resource, at: u32, value: u32, spin: u32) -> u64 { + let (root, pso) = (self.root.clone(), self.pso.clone()); + // SAFETY: a live buffer with unordered access; the shader's + // own root signature. + self.fly(|list| unsafe { + list.SetComputeRootSignature(&root); + list.SetPipelineState(&pso); + let constants = [at, value, spin]; + list.SetComputeRoot32BitConstants(0, 3, constants.as_ptr().cast(), 0); + list.SetComputeRootUnorderedAccessView(1, memory.GetGPUVirtualAddress()); + list.Dispatch(1, 1, 1); + }) + } + + /// Waits for everything sent to the direct queue and the lanes. + fn land(&mut self) { + // SAFETY: our fence and event. + unsafe { + self.fence.SetEventOnCompletion(self.submitted, self.event).expect("a wait"); + WaitForSingleObject(self.event, INFINITE); + } + for lane in [&self.second.down, &self.second.up] { + let last = lock(&lane.state).sent; + lane.wait(last, self.event).expect("a wait"); + } + assert!( + // SAFETY: a plain query. + unsafe { self.device.GetDeviceRemovedReason() }.is_ok(), + "the software adapter lost the device" + ); + self.flown.clear(); + } + } + + /// The dwords of a mapped buffer. + fn dwords(data: *mut u8, at: usize, n: usize) -> Vec { + // SAFETY: the caller's mapping holds them. + (0..n).map(|i| unsafe { data.cast::().add(at + i).read_volatile() }).collect() + } + + /// What shaders wrote, read back through the down lane, is what the + /// direct queue reads back: the same bytes of a buffer in the card's + /// memory come down both ways, and the lane's copy is behind the fence + /// of the submission that wrote them without any wait of ours between. + #[test] + fn warp_a_fetch_through_the_copy_queue_brings_what_the_direct_queue_brings() { + let Some(mut warp) = Warp::new(1) else { + return; + }; + const DWORDS: usize = 4096; + let bytes = (DWORDS * 4) as u64; + let (card, _) = warp.buffer(bytes, false); + let (down_direct, direct_data) = warp.buffer(bytes, true); + let (down_lane, lane_data) = warp.buffer(bytes, true); + for round in 1..=3u32 { + // "Shader writes": a few dwords, each by a dispatch. + let mut behind = 0; + for i in 0..24u32 { + behind = warp.store(&card, (i * 163 % DWORDS as u32) * 4, round * 1000 + i, 20_000); + } + // Through the lane, behind the writes' fence; no wait of ours. + let second = warp.second; + let list = second.down.list().expect("a copy list"); + // SAFETY: an open copy list; live buffers. + unsafe { list.1.CopyBufferRegion(&down_lane, 0, &card, 0, bytes) }; + let job = second.down.send(list, &[(&warp.fence, behind)], bytes).expect("the fetch is sent"); + // And through the direct queue, as before. + // SAFETY: an open list; live buffers. + warp.fly(|list| unsafe { list.CopyBufferRegion(&down_direct, 0, &card, 0, bytes) }); + second.down.wait(job, warp.event).expect("the fetch is waited for"); + assert!(second.down.done(job)); + warp.land(); + let (direct, lane) = (dwords(direct_data, 0, DWORDS), dwords(lane_data, 0, DWORDS)); + assert_eq!(direct, lane, "round {round}: the two ways brought different bytes"); + for i in 0..24u32 { + assert_eq!(lane[(i * 163 % DWORDS as u32) as usize], round * 1000 + i, "round {round}, write {i}"); + } + } + assert_eq!(warp.second.down.stats.jobs.load(Ordering::Relaxed), 3); + } + + /// Ordering under the fences, nothing waited for on the CPU: write k + /// goes to the direct queue with a signal behind it, and fetch k, sent + /// at once to the lane behind that signal, must hold writes 1..=k + /// (later writes may or may not be in it: they are newer, never + /// older). Sixteen of each are in the air together. + #[test] + fn warp_a_fetch_behind_a_fence_holds_everything_sent_before_that_fence() { + let Some(mut warp) = Warp::new(1) else { + return; + }; + const N: usize = 16; + let bytes = (N * 4) as u64; + let (card, _) = warp.buffer(64 << 10, false); + let (down, data) = warp.buffer(bytes * N as u64, true); + let second = warp.second; + for k in 0..N { + let behind = warp.store(&card, (k * 4) as u32, 0xA000 + k as u32, 60_000); + let list = second.down.list().expect("a copy list"); + // SAFETY: an open copy list; live buffers; the slot is inside. + unsafe { list.1.CopyBufferRegion(&down, k as u64 * bytes, &card, 0, bytes) }; + second.down.send(list, &[(&warp.fence, behind)], bytes).expect("the fetch is sent"); + } + warp.land(); + for k in 0..N { + let slot = dwords(data, k * N, N); + for (i, &got) in slot.iter().enumerate().take(k + 1) { + assert_eq!(got, 0xA000 + i as u32, "fetch {k} ran before write {i}, which was sent before its fence"); + } + for (i, &got) in slot.iter().enumerate().skip(k + 1) { + assert!(got == 0 || got == 0xA000 + i as u32, "fetch {k} holds {got:#x} for write {i}"); + } + } + } + + /// Title bytes sent up through the up lane are there when the direct + /// queue goes on: each of sixteen sends is followed, with no wait of + /// ours, by a direct list that reads the buffer back, and each read + /// holds its own send and all before it. Each send is made late on + /// purpose (it stands behind a slow list of the direct queue), so the + /// read would come first if the direct queue did not wait. The + /// numbered sends are signalled in order, and the clock saw the holds. + #[test] + fn warp_the_direct_queue_goes_on_only_when_what_was_sent_up_is_there() { + let Some(mut warp) = Warp::new(3) else { + return; + }; + const N: usize = 16; + const PART: u64 = 64 << 10; + let (staging, staged) = warp.buffer(PART * N as u64, true); + // A buffer in the card's memory per send: the lane writes one that + // nothing in the air names yet (as it writes landing buffers). + let cards: Vec = (0..N).map(|_| warp.buffer(PART, false).0).collect(); + let (other, _) = warp.buffer(64 << 10, false); + // What each read brings: the first dword of every part. + let (down, data) = warp.buffer((N * N * 4) as u64, true); + let second = warp.second; + for k in 0..N { + // The title's bytes of part k (the CPU's side of the copy). + for i in 0..(PART as usize / 4) { + // SAFETY: inside the mapping; nothing on the card reads + // part k before the send below. + unsafe { staged.cast::().add(k * (PART as usize / 4) + i).write_volatile(0xB000 + k as u32) }; + } + let slow = warp.store(&other, 0, k as u32, 80_000); + let list = second.up.list().expect("a copy list"); + // SAFETY: an open copy list; live buffers. + unsafe { list.1.CopyBufferRegion(&cards[k], 0, &staging, k as u64 * PART, PART) }; + let job = second.up.send(list, &[(&warp.fence, slow)], PART).expect("the bytes are sent up"); + second.hold(&warp.direct, job).expect("the direct queue waits"); + second.sent_up(&warp.direct, k as u64 + 1); + // SAFETY: an open list; live buffers; the slots are inside. + warp.fly(|list| unsafe { + for (part, card) in cards.iter().enumerate().take(k + 1) { + list.CopyBufferRegion(&down, ((k * N + part) * 4) as u64, card, 0, 4); + } + }); + } + warp.land(); + assert_eq!(second.order_done(), N as u64); + for k in 0..N { + let read = dwords(data, k * N, N); + for (part, &got) in read.iter().enumerate().take(k + 1) { + assert_eq!(got, 0xB000 + part as u32, "the direct queue's read {k} ran before send {part} was on the card"); + } + } + assert_eq!(second.held[0].load(Ordering::Relaxed), N as u64); + assert_eq!(second.up.stats.bytes.load(Ordering::Relaxed), PART * N as u64); + } + + /// The way title bytes go up with bit 2, as `Host::card_before` does + /// it: a job of the up lane brings them into a landing buffer while a + /// slow list of the direct queue is still running, the direct queue + /// waits for the job and then copies from the landing buffer into the + /// copy. A shader's store to the same bytes, sent before, must lose to + /// them (the copy changes in the direct queue's order, as on one + /// queue), and what a fetch through the down lane brings is what the + /// direct queue reads. Twelve rounds in the air together, each with a + /// landing buffer of its own until the card has passed its use. + #[test] + fn warp_title_bytes_reach_the_copy_through_a_landing_buffer_in_the_direct_queues_order() { + let Some(mut warp) = Warp::new(3) else { + return; + }; + const N: usize = 12; + let (staging, staged) = warp.buffer(64 << 10, true); + let (card, _) = warp.buffer(64 << 10, false); + let (down, data) = warp.buffer((N * 4) as u64, true); + let (down_lane, lane_data) = warp.buffer((N * 4) as u64, true); + let second = warp.second; + let mut landings = Vec::new(); + for k in 0..N { + let at = (k * 256) as u64; + // SAFETY: inside the mapping; read by the card only through + // the job below. + unsafe { staged.add(at as usize).cast::().write_volatile(0xC000 + k as u32) }; + // A shader's (slow) store to the same dword, sent first. + warp.store(&card, at as u32, 0xDEAD_0000 + k as u32, 80_000); + // SAFETY: a plain query. + let completed = unsafe { warp.fence.GetCompletedValue() }; + let landing = second.landing(4, completed, warp.submitted + 1).expect("a landing buffer"); + let list = second.up.list().expect("a copy list"); + // SAFETY: an open copy list; live buffers. + unsafe { list.1.CopyBufferRegion(&landing, 0, &staging, at, 4) }; + let job = second.up.send(list, &[], 4).expect("the bytes are sent up"); + second.hold(&warp.direct, job).expect("the direct queue waits"); + // SAFETY: an open list; live buffers. + let read = warp.fly(|list| unsafe { + list.CopyBufferRegion(&card, at, &landing, 0, 4); + list.CopyBufferRegion(&down, (k * 4) as u64, &card, at, 4); + }); + let list = second.down.list().expect("a copy list"); + // SAFETY: an open copy list; live buffers. + unsafe { list.1.CopyBufferRegion(&down_lane, (k * 4) as u64, &card, at, 4) }; + second.down.send(list, &[(&warp.fence, read)], 4).expect("the fetch is sent"); + landings.push(landing.as_raw() as usize); + } + warp.land(); + let want: Vec = (0..N).map(|k| 0xC000 + k as u32).collect(); + assert_eq!(dwords(data, 0, N), want, "the title's bytes did not reach the copy behind the shader's store"); + assert_eq!(dwords(lane_data, 0, N), want, "the copy queue's fetch differs from the direct queue's"); + // No buffer was given out while its last use was in the air: one + // given to two rounds was free in between. + landings.sort_unstable(); + landings.dedup(); + assert!(!landings.is_empty() && landings.len() <= N); + // Everything has run: the next ask takes one of them, makes none. + let alive = second.landing[0].load(Ordering::Relaxed); + // SAFETY: a plain query. + let completed = unsafe { warp.fence.GetCompletedValue() }; + let again = second.landing(4, completed, warp.submitted + 1).expect("a landing buffer"); + assert!(landings.contains(&(again.as_raw() as usize))); + assert_eq!(second.landing[0].load(Ordering::Relaxed), alive); + } + + /// Lists of a lane come back for the next job once the card has run + /// the job they were in, and not before. + #[test] + fn warp_a_lanes_lists_are_used_again_only_after_their_job() { + let Some(mut warp) = Warp::new(1) else { + return; + }; + let (card, _) = warp.buffer(64 << 10, false); + let (down, _) = warp.buffer(64 << 10, true); + let second = warp.second; + // A job that cannot run yet: it waits for a fence value the direct + // queue reaches only after a slow store. + let behind = warp.store(&card, 0, 1, 400_000); + let first = second.down.list().expect("a copy list"); + let first_list = first.1.as_raw(); + // SAFETY: an open copy list; live buffers. + unsafe { first.1.CopyBufferRegion(&down, 0, &card, 0, 64) }; + let job = second.down.send(first, &[(&warp.fence, behind)], 64).expect("sent"); + if !second.down.done(job) { + // Still in the air: the next list is another one. + let next = second.down.list().expect("a copy list"); + assert_ne!(next.1.as_raw(), first_list, "a list was reset while its job had not run"); + second.down.send(next, &[], 0).expect("sent"); + } + warp.land(); + // Everything has run: a list of before comes back. + let again = second.down.list().expect("a copy list"); + let spare_left = lock(&second.down.state).spare.len(); + assert!(spare_left <= 1, "lists that have run are taken before new ones are made"); + second.down.send(again, &[], 0).expect("sent"); + warp.land(); + } +} diff --git a/crates/leonida-gpu/src/resource.rs b/crates/leonida-gpu/src/resource.rs new file mode 100644 index 000000000..b0e2f01ef --- /dev/null +++ b/crates/leonida-gpu/src/resource.rs @@ -0,0 +1,3990 @@ +//! Heaps, committed and placed resources, and resource sizes. +//! +//! Heaps and resources are host memory and a resource's GPU address is its +//! CPU address, as on the console; textures also get a host copy, and +//! buffers a host copy when a draw reads them (`shadow`). +#![allow(clippy::not_unsafe_ptr_arg_deref)] + +use std::alloc::{Layout, alloc_zeroed, dealloc}; +use std::ffi::c_void; +use std::ptr::NonNull; + +use leonida_formats::texture; + +use crate::object::{ + self, E_INVALIDARG, E_OUTOFMEMORY, HEAP, HRESULT, Iid, Object, RESOURCE, S_OK, Table, This, + guid, +}; + +/// The interfaces every device child also answers for. +pub(crate) const PAGEABLE_IIDS: [Iid; 3] = [ + guid( + 0x63ee58fb, + 0x1268, + 0x4835, + [0x86, 0xda, 0xf0, 0x08, 0xce, 0x62, 0xf0, 0xd6], + ), + guid( + 0x905db94b, + 0xa00c, + 0x4140, + [0x9d, 0xf5, 0x2b, 0x64, 0xca, 0x9e, 0xa3, 0x57], + ), + guid( + 0xc4fec28f, + 0x7966, + 0x4e95, + [0x9f, 0x94, 0xf4, 0x31, 0xcb, 0x56, 0xc3, 0xb8], + ), +]; +const HEAP_IIDS: [Iid; 4] = [ + guid( + 0x6b3b2502, + 0x6e51, + 0x45b3, + [0x90, 0xee, 0x98, 0x84, 0x26, 0x5e, 0x8d, 0xf3], + ), + PAGEABLE_IIDS[0], + PAGEABLE_IIDS[1], + PAGEABLE_IIDS[2], +]; +const RESOURCE_IIDS: [Iid; 4] = [ + guid( + 0x696442be, + 0xa72e, + 0x4059, + [0xbc, 0x79, 0x5b, 0x5c, 0x98, 0x04, 0x0f, 0xad], + ), + PAGEABLE_IIDS[0], + PAGEABLE_IIDS[1], + PAGEABLE_IIDS[2], +]; + +const KIB_64: u64 = 64 << 10; +const MIB_4: u64 = 4 << 20; + +#[repr(C)] +#[derive(Debug, Clone, Copy)] +pub(crate) struct HeapProperties { + kind: u32, + cpu_pages: u32, + pool: u32, + creation_nodes: u32, + visible_nodes: u32, +} + +#[repr(C)] +#[derive(Debug, Clone, Copy)] +pub(crate) struct HeapDesc { + size: u64, + properties: HeapProperties, + alignment: u64, + flags: u32, +} + +#[repr(C)] +#[derive(Debug, Clone, Copy)] +pub(crate) struct ResourceDesc { + dimension: u32, + alignment: u64, + width: u64, + height: u32, + depth_or_array_size: u16, + mip_levels: u16, + format: u32, + sample_count: u32, + sample_quality: u32, + layout: u32, + flags: u32, +} + +#[repr(C)] +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) struct AllocationInfo { + size: u64, + alignment: u64, +} + +const _: () = assert!(size_of::() == 20); +const _: () = assert!(size_of::() == 48); +const _: () = assert!(size_of::() == 56); + +const BUFFER: u32 = 1; +const TEXTURE_3D: u32 = 4; + +/// Bytes per element and the element's width in texels (4 for block +/// compression), by DXGI format number. `None` for 1-bit and video +/// formats. The console adds 116/117 (10-bit float color), 118-120 (16-bit +/// depth with 8-bit stencil, two planes: 3 bytes per texel), 189 (signed +/// 10-bit color), 190 (two 4-bit channels) and 191 (24/8 color). +pub(crate) fn element(format: u32) -> Option<(u64, u64)> { + Some(match format { + 1..=4 => (16, 1), + 5..=8 => (12, 1), + 9..=22 => (8, 1), + 23..=47 | 67 | 87..=93 | 116 | 117 | 189 | 191 => (4, 1), + 118..=120 => (3, 1), + 48..=59 | 68 | 69 | 85 | 86 | 115 => (2, 1), + 60..=65 | 190 => (1, 1), + 70..=72 | 79..=81 => (8, 4), + 73..=78 | 82..=84 | 94..=99 => (16, 4), + _ => return None, + }) +} + +/// A texture's layout in console memory, as the console's layout library +/// gives it (`leonida-hle`'s `xg` serves the same): the description's +/// layout field is `0x100 | swizzle mode`, 1 linear, 0 the library's pick. +pub(crate) fn texture_layout(desc: &ResourceDesc) -> Option { + use texture::{Dimension, Swizzle, TextureDesc}; + const TEXTURE_1D: u32 = 2; + const TEXTURE_2D: u32 = 3; + const RENDER_TARGET: u32 = 1; + const DEPTH: u32 = 2; + let dimension = match desc.dimension { + TEXTURE_1D => Dimension::Tex1d, + TEXTURE_2D => Dimension::Tex2d, + TEXTURE_3D => Dimension::Tex3d, + _ => return None, + }; + let swizzle = match desc.layout { + 0 if dimension == Dimension::Tex1d => Swizzle::LINEAR, + 0 if desc.flags & DEPTH != 0 => Swizzle::SW_64KB_Z_X, + 0 if desc.flags & RENDER_TARGET != 0 => Swizzle::SW_64KB_R_X, + 0 => Swizzle::SW_4KB_S, + 1 => Swizzle::LINEAR, + l if l & !0xff == 0x100 => Swizzle(l & 0xff), + _ => return None, + }; + texture::Texture::new(&TextureDesc { + dimension, + width: u32::try_from(desc.width).ok()?, + height: desc.height, + depth_or_array: u32::from(desc.depth_or_array_size), + mips: u32::from(desc.mip_levels), + format: desc.format, + samples: desc.sample_count.max(1), + swizzle, + }) + .ok() +} + +/// Bytes and alignment a resource takes: buffers their width (64 KiB +/// aligned), textures their console layout (formats it does not know: +/// every mip of every array slice and sample, packed, 64 KiB aligned), +/// rounded up to the alignment. +fn footprint(desc: &ResourceDesc) -> Option { + if desc.dimension != BUFFER + && let Some(t) = texture_layout(desc) + { + // As the console: the layout's own alignment unless more is asked + // (4 KiB for 4 KiB modes, where PC says 64 KiB). + // The title keeps these sizes in its texture tables, and its streaming + // asserts when they disagree with the streamed layout. + let alignment = desc.alignment.max(t.alignment); + if !alignment.is_power_of_two() { + return None; + } + return Some(AllocationInfo { + size: t.size.checked_next_multiple_of(alignment)?, + alignment, + }); + } + let bytes = if desc.dimension == BUFFER { + desc.width + } else { + let (element, block) = element(desc.format)?; + let (depth, slices) = if desc.dimension == TEXTURE_3D { + (u64::from(desc.depth_or_array_size), 1) + } else { + (1, u64::from(desc.depth_or_array_size)) + }; + let height = u64::from(desc.height); + let mips = mip_count(desc); + let mut chain = 0u64; + for mip in 0..mips.min(64) { + let w = (desc.width >> mip).max(1).div_ceil(block); + let h = (height >> mip).max(1).div_ceil(block); + let d = (depth >> mip).max(1); + chain = chain.checked_add(w.checked_mul(h)?.checked_mul(d)?.checked_mul(element)?)?; + } + chain + .checked_mul(slices)? + .checked_mul(u64::from(desc.sample_count.max(1)))? + }; + if bytes == 0 { + return None; + } + let minimum = if desc.sample_count > 1 { MIB_4 } else { KIB_64 }; + let alignment = desc.alignment.max(minimum); + if !alignment.is_power_of_two() { + return None; + } + Some(AllocationInfo { + size: bytes.checked_next_multiple_of(KIB_64)?, + alignment, + }) +} + +/// A format as the host has it. The console's 16-bit depth with stencil +/// (and its typeless views) has no PC format: the 24-bit ones stand in. +pub(crate) fn pc_format(format: u32) -> u32 { + match format { + 118 => 45, + 119 => 46, + 120 => 47, + other => other, + } +} + +/// The format of a texture the host GPU renders to or writes as unordered +/// access, for the title's `format`. The console's GPU does both with the +/// 16-bit colour formats B5G5R5A1 (86) and B4G4R4A4 (115), and +/// the title has full-screen targets in both; a host that refuses either use +/// (NVIDIA) refused the whole texture, so every pass that wrote it drew +/// nothing. There 8-bit RGBA stands in: the same channels in the same +/// order, every 4-bit level exact and every 5-bit level within 1/510. +/// The title also renders to R9G9B9E5 (67), which no PC GPU does: 16-bit +/// float RGBA stands in, with at least R9G9B9E5's precision and range. +/// The title's pipelines and views of such targets name the stand-in too +/// ([`view_format`], the host view checks). +/// shortcut: copies between such a target and a texture the title fills +/// itself in the 16-bit format are skipped ([`stands_in`]); convert them +/// if a pass turns out to need one. +pub(crate) fn target_format(format: u32) -> u32 { + const STAND_INS: [(u32, u32); 3] = [(86, 28), (115, 28), (67, 10)]; + let Some(i) = STAND_INS.iter().position(|&(f, _)| f == format) else { + return format; + }; + #[cfg(windows)] + { + use windows::Win32::Graphics::Direct3D12::*; + static REFUSED: std::sync::OnceLock<[bool; 3]> = std::sync::OnceLock::new(); + let refused = REFUSED.get_or_init(|| { + STAND_INS.map(|(f, to)| { + let Some(host) = crate::host::host() else { + return false; + }; + let mut support = D3D12_FEATURE_DATA_FORMAT_SUPPORT { + Format: windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT(f as i32), + ..Default::default() + }; + // SAFETY: a plain query into our own structure. + let asked = unsafe { + host.device.CheckFeatureSupport( + D3D12_FEATURE_FORMAT_SUPPORT, + (&raw mut support).cast(), + size_of_val(&support) as u32, + ) + }; + let both = D3D12_FORMAT_SUPPORT1_RENDER_TARGET.0 + | D3D12_FORMAT_SUPPORT1_TYPED_UNORDERED_ACCESS_VIEW.0; + let refused = asked.is_err() || support.Support1.0 & both != both; + if refused { + tracing::info!(format = f, stand_in = to, "the host does not render to this format: a stand-in is used"); + } + refused + }) + }); + if refused[i] { + return STAND_INS[i].1; + } + } + format +} + +/// Whether the host copy of the title texture `this` is in a stand-in +/// format ([`target_format`]): its texels are not laid out as the title's. +#[cfg(windows)] +pub(crate) fn stands_in(this: This) -> bool { + if this.is_null() { + return false; + } + let own = pc_format(resource(this).desc.format); + target_format(own) != own + && host_resource(this) + // SAFETY: a live resource. + .is_some_and(|host| unsafe { host.GetDesc() }.Format.0 as u32 == target_format(own)) +} + +/// Depth textures the title also asks unordered access for (the console +/// allows both; the host copy loses the unordered access): how many were +/// made, and how often such a texture was bound as the depth target, +/// cleared as depth, and asked for an unordered access view the host could +/// not give. Measured to decide what such textures need (a colour twin, or +/// to be colour textures altogether). +pub(crate) static DEPTH_UNORDERED: [std::sync::atomic::AtomicU64; 4] = + [const { std::sync::atomic::AtomicU64::new(0) }; 4]; + +/// Whether the title asked for both depth and unordered access for `this`. +#[cfg(windows)] +pub(crate) fn depth_and_unordered(this: This) -> bool { + !this.is_null() && resource(this).desc.flags & 6 == 6 +} + +/// The colour twin of a depth texture the title also writes as unordered +/// access. The console allows both on one texture; the host gives a depth +/// texture no unordered access, so shaders write a colour texture of the +/// same size and format family instead, and one is copied into the other +/// when a side is used after the other was written +/// (`HostList::twin_use`). +/// shortcut: whole textures are copied, not the mips and slices written. +/// A depth texture with a stencil plane gets a twin for each plane ( +/// the title's tiled lighting writes each pixel's material class into +/// the depth plane and masks into the stencil plane, then draws each class +/// with the depth test "equal"): the stencil plane's is copied through a +/// buffer, the depth plane's is drawn into the plane by a pass of ours +/// (`HostList::pass_plane`). Unordered access views of a multisampled +/// texture stay null. +#[cfg(windows)] +pub(crate) struct Twin { + /// The colour texture and the state it is in, as a host copy's. + pub(crate) colour: std::sync::Arc, + /// Which side lacks what the other was written last, after the lists + /// submitted so far: bit 0 the depth texture, bit 1 the twin. + pub(crate) behind: std::sync::atomic::AtomicU32, + /// For a depth texture with a stencil plane, `colour` is the twin of + /// that plane (8 bits a texel) and this the buffer the two are copied + /// through: no colour format shares a family with a depth-stencil + /// format, but the host copies between a buffer and one plane. + pub(crate) through: Option, + /// For a depth texture with a stencil plane: the twin of its depth + /// plane, 16 bits a texel for the console's 16-bit depth-stencil + /// formats and a 32-bit float otherwise. No host colour format holds + /// the bits of a 24-bit depth plane, so the two are not copied: a pass + /// draws the twin into the plane. + pub(crate) plane: Option>, +} + +#[cfg(windows)] +impl Drop for Twin { + fn drop(&mut self) { + TWINS[0].fetch_sub(1, std::sync::atomic::Ordering::Relaxed); + } +} + +/// Colour twins alive, depth textures with unordered access left without +/// one, and the copies recorded into depth textures and into twins since +/// the last frame-rate line. +#[cfg(windows)] +pub(crate) static TWINS: [std::sync::atomic::AtomicU64; 4] = + [const { std::sync::atomic::AtomicU64::new(0) }; 4]; + +/// Depth planes drawn from their twins by the pass since the last +/// frame-rate line; and since the start, how often a depth plane's twin +/// lacked what was written to the plane (not given to it), and how often a +/// depth plane was used in the list that had written its twin, before the +/// pass (which runs when the list closes). +#[cfg(windows)] +pub(crate) static PLANES: [std::sync::atomic::AtomicU64; 3] = + [const { std::sync::atomic::AtomicU64::new(0) }; 3]; + +/// The colour twin of title texture `this`, if it has one. +#[cfg(windows)] +pub(crate) fn twin(this: This) -> Option> { + if this.is_null() { + return None; + } + hosted(this, true).and_then(|made| made.1) +} + +/// The twin's texture, for the unordered access views of `this`. +#[cfg(windows)] +pub(crate) fn twin_resource<'a>( + this: This, +) -> Option<&'a windows::Win32::Graphics::Direct3D12::ID3D12Resource> { + if this.is_null() { + return None; + } + let (_, twin) = hosted(this, true)?; + // SAFETY: as in `host_resource`: the twin lives as long as the host + // copy, which a depth texture keeps until the title releases it. + twin.map(|t| unsafe { &*std::ptr::from_ref(&t.colour.texture) }) +} + +/// The texture of the twin of the depth plane of `this`, a depth texture +/// with a stencil plane, for the unordered access views of that plane. +#[cfg(windows)] +pub(crate) fn twin_plane_resource<'a>( + this: This, +) -> Option<&'a windows::Win32::Graphics::Direct3D12::ID3D12Resource> { + if this.is_null() { + return None; + } + let (_, twin) = hosted(this, true)?; + let twin = twin?; + // SAFETY: as in `twin_resource`. + twin.plane + .as_ref() + .map(|p| unsafe { &*std::ptr::from_ref(&p.texture) }) +} + +/// The colour twin for a texture described by `desc` whose host copy is +/// `depth`, if the title asks for depth and unordered access both and the +/// host can copy between the two: the same size, mips and slices in the +/// depth format's typeless family (R16 for 16-bit depth, R32 for 32-bit), +/// or R8 for the stencil plane of a format that has one, with unordered +/// access only. A format with a stencil plane gets a twin for its depth +/// plane too, R16 for the console's 16-bit depth-stencil formats and R32 +/// otherwise. `LEONIDA_DEPTH_TWINS=0` makes none (such views stay null), +/// `LEONIDA_DEPTH_TWINS=stencil` only those of formats with a stencil +/// plane, `LEONIDA_DEPTH_TWINS=nodepth` none for the depth planes of such +/// formats. +#[cfg(windows)] +fn twin_texture( + desc: &ResourceDesc, + depth: &windows::Win32::Graphics::Direct3D12::ID3D12Resource, +) -> Option> { + use std::sync::atomic::Ordering::Relaxed; + use windows::Win32::Graphics::Direct3D12::*; + const DEPTH_AND_UNORDERED: u32 = 6; + const UNORDERED: u32 = 4; + const UNORDERED_ACCESS: u32 = 0x8; + // R32 and R16 typeless: the families of the depth formats of one plane. + const ONE_PLANE: [u32; 2] = [39, 53]; + if desc.dimension == BUFFER || desc.flags & DEPTH_AND_UNORDERED != DEPTH_AND_UNORDERED { + return None; + } + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + if !*ON.get_or_init(|| std::env::var_os("LEONIDA_DEPTH_TWINS").is_none_or(|v| v != "0")) { + return None; + } + // R32G8X24 and R24G8 typeless: depth with a stencil plane, whose twin + // is R8 typeless. + const WITH_STENCIL: [u32; 2] = [19, 44]; + const R8_TYPELESS: u32 = 60; + let typeless = family(pc_format(desc.format)); + let stencil = WITH_STENCIL.contains(&typeless); + static STENCIL_ONLY: std::sync::OnceLock = std::sync::OnceLock::new(); + let stencil_only = *STENCIL_ONLY + .get_or_init(|| std::env::var_os("LEONIDA_DEPTH_TWINS").is_some_and(|v| v == "stencil")); + if !stencil && stencil_only { + return None; + } + if !(stencil || ONE_PLANE.contains(&typeless)) || desc.sample_count > 1 { + TWINS[1].fetch_add(1, Relaxed); + return None; + } + let host = crate::host::host()?; + let mut d = *desc; + d.layout = 0; + d.alignment = 0; + d.flags = UNORDERED; + d.format = if stencil { R8_TYPELESS } else { typeless }; + let heap = D3D12_HEAP_PROPERTIES { + Type: D3D12_HEAP_TYPE_DEFAULT, + ..Default::default() + }; + let mut texture: Option = None; + // SAFETY: the description has the host layout, as in `host_texture`; + // the out pointer is ours. + let made = unsafe { + host.device.CreateCommittedResource( + &heap, + D3D12_HEAP_FLAG_NONE, + (&raw const d).cast(), + D3D12_RESOURCE_STATES(UNORDERED_ACCESS as i32), + None, + &mut texture, + ) + }; + if let Err(e) = made { + tracing::warn!(error = %e, desc = ?d, "no colour twin for a depth texture"); + } + let Some(texture) = texture else { + TWINS[1].fetch_add(1, Relaxed); + return None; + }; + crate::host::name(&texture, || { + format!("depth twin {}x{} f{}", d.width, d.height, d.format) + }); + // The buffer a stencil plane and its twin are copied through: as big + // as the plane's mips and slices laid out for a copy (they follow the + // depth plane's in the texture's subresources). + let through = if stencil { + // SAFETY: a live texture. + let of = unsafe { depth.GetDesc() }; + let planes = u32::from(of.MipLevels) * u32::from(of.DepthOrArraySize); + let mut bytes = 0; + // SAFETY: a plain query; the out pointer is ours. + unsafe { + host.device.GetCopyableFootprints( + &of, + planes, + planes, + 0, + None, + None, + None, + Some(&mut bytes), + ); + } + let Some(buffer) = host.uav_buffer(bytes) else { + TWINS[1].fetch_add(1, Relaxed); + return None; + }; + Some(buffer) + } else { + None + }; + // The twin of the depth plane of a format with a stencil plane: R16 + // typeless (53) for the console's 16-bit depth-stencil formats (118 to + // 120), whose shaders write 16-bit steps, R32 typeless (39) otherwise. + static NO_PLANE: std::sync::OnceLock = std::sync::OnceLock::new(); + let no_plane = *NO_PLANE + .get_or_init(|| std::env::var_os("LEONIDA_DEPTH_TWINS").is_some_and(|v| v == "nodepth")); + let plane = if stencil && !no_plane { + d.format = if (118..=120).contains(&desc.format) { + 53 + } else { + 39 + }; + let mut texture: Option = None; + // SAFETY: as for the first twin. + let made = unsafe { + host.device.CreateCommittedResource( + &heap, + D3D12_HEAP_FLAG_NONE, + (&raw const d).cast(), + D3D12_RESOURCE_STATES(UNORDERED_ACCESS as i32), + None, + &mut texture, + ) + }; + if let Err(e) = made { + tracing::warn!(error = %e, desc = ?d, "no twin for a depth plane"); + } + texture.map(|texture| { + crate::host::name(&texture, || { + format!("depth plane twin {}x{} f{}", d.width, d.height, d.format) + }); + std::sync::Arc::new(HostTexture::new(texture, UNORDERED_ACCESS)) + }) + } else { + None + }; + TWINS[0].fetch_add(1, Relaxed); + Some(std::sync::Arc::new(Twin { + colour: std::sync::Arc::new(HostTexture::new(texture, UNORDERED_ACCESS)), + behind: std::sync::atomic::AtomicU32::new(0), + through, + plane, + })) +} + +/// The typeless format of a format's family (itself if it has none). +pub(crate) fn family(format: u32) -> u32 { + const FAMILIES: [(u32, u32); 22] = [ + (1, 4), + (5, 8), + (9, 14), + (15, 18), + (19, 22), + (23, 25), + (27, 32), + (33, 38), + (39, 43), + (44, 47), + (48, 52), + (53, 59), + (60, 65), + (70, 72), + (73, 75), + (76, 78), + (79, 81), + (82, 84), + (90, 91), + (92, 93), + (94, 96), + (97, 99), + ]; + match format { + 87 => 90, + 88 => 92, + f => FAMILIES + .iter() + .find(|&&(first, last)| (first..=last).contains(&f)) + .map_or(f, |&(first, _)| first), + } +} + +/// sRGB formats and their linear twins. +pub(crate) const SRGB: [(u32, u32); 3] = [(29, 28), (91, 87), (93, 88)]; + +/// The format a view of a title texture must name when its host copy is +/// typeless (see [`DEPTH_FORMATS`], [`SRGB`]): the title's own; `None` if +/// the host copy is typed. +pub(crate) fn view_format(this: This) -> Option { + // First: a view of no resource (a typed null view) has none. + let host = host_resource(this)?; + let own = pc_format(resource(this).desc.format); + // SAFETY: a live resource. + let format = unsafe { host.GetDesc() }.Format.0 as u32; + // A stand-in target is typed. + (format != own && format != target_format(own)).then_some(own) +} + +/// Depth formats with their typeless family: depth textures that shaders +/// read are made typeless on the host, which only allows views of +/// typeless depth resources. +pub(crate) const DEPTH_FORMATS: [(u32, u32); 4] = [(20, 19), (40, 39), (45, 44), (55, 53)]; + +/// Mip levels, the full chain for 0. +fn mip_count(desc: &ResourceDesc) -> u32 { + let depth = if desc.dimension == TEXTURE_3D { + u64::from(desc.depth_or_array_size) + } else { + 1 + }; + match desc.mip_levels { + 0 => { + 64 - desc + .width + .max(u64::from(desc.height)) + .max(depth) + .max(1) + .leading_zeros() + } + n => u32::from(n), + } +} + +#[repr(C)] +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) struct PlacedFootprint { + pub(crate) offset: u64, + format: u32, + width: u32, + height: u32, + depth: u32, + row_pitch: u32, +} + +impl PlacedFootprint { + /// The bytes it spans in a buffer: every row pitched but the last. + pub(crate) fn bytes(&self) -> Option { + let (element, block) = element(self.format)?; + let lines = u64::from(self.height).div_ceil(block) * u64::from(self.depth); + let last = u64::from(self.width).div_ceil(block) * element; + Some(u64::from(self.row_pitch) * lines.saturating_sub(1) + last) + } + + /// For a read back through a host buffer: this footprint at offset 0 + /// with its rows pitched as the host wants them (multiples of 256 + /// bytes), then the bytes that buffer needs, the bytes of a row, the + /// rows, and the title's own pitch. + pub(crate) fn host_rows(&self) -> Option<(PlacedFootprint, [u64; 4])> { + let (element, block) = element(self.format)?; + let lines = (u64::from(self.height).div_ceil(block) * u64::from(self.depth)).max(1); + let row = u64::from(self.width).div_ceil(block) * element; + let pitch = row.max(1).next_multiple_of(256); + let host = PlacedFootprint { + offset: 0, + row_pitch: u32::try_from(pitch).ok()?, + ..*self + }; + Some((host, [pitch * lines, row, lines, u64::from(self.row_pitch)])) + } +} +const _: () = assert!(size_of::() == 32); + +const NO_FOOTPRINT: PlacedFootprint = PlacedFootprint { + offset: u64::MAX, + format: 0, + width: 0, + height: 0, + depth: 0, + row_pitch: 0, +}; + +/// One subresource's size in an upload buffer: footprint (offset 0), rows +/// and bytes per row. Planes of depth-stencil formats are not told apart. +fn subresource(desc: &ResourceDesc, index: u32) -> Option<(PlacedFootprint, u32, u64)> { + const PITCH: u64 = 256; + if desc.dimension == BUFFER { + let footprint = PlacedFootprint { + offset: 0, + format: 0, + width: u32::try_from(desc.width).ok()?, + height: 1, + depth: 1, + row_pitch: u32::try_from(desc.width.next_multiple_of(PITCH)).ok()?, + }; + return (index == 0).then_some((footprint, 1, desc.width)); + } + let mips = mip_count(desc); + let slices = if desc.dimension == TEXTURE_3D { + 1 + } else { + u32::from(desc.depth_or_array_size).max(1) + }; + let (mip, slice) = (index % mips, index / mips); + if slice >= slices { + return None; + } + let (element, block) = element(desc.format)?; + let width = (desc.width >> mip).max(1).next_multiple_of(block); + let height = (u64::from(desc.height) >> mip) + .max(1) + .next_multiple_of(block); + let depth = if desc.dimension == TEXTURE_3D { + (u32::from(desc.depth_or_array_size) >> mip).max(1) + } else { + 1 + }; + let row_size = width / block * element; + let footprint = PlacedFootprint { + offset: 0, + format: desc.format, + width: u32::try_from(width).ok()?, + height: u32::try_from(height).ok()?, + depth, + row_pitch: u32::try_from(row_size.next_multiple_of(PITCH)).ok()?, + }; + Some((footprint, u32::try_from(height / block).ok()?, row_size)) +} + +/// Device method: where each subresource goes in an upload buffer, rows +/// 256-byte and subresources 512-byte aligned, as on PC. Unknown sizes give +/// the documented all-ones values. +pub(crate) extern "system" fn copyable_footprints( + _: This, + desc: *const ResourceDesc, + first: u32, + count: u32, + base: u64, + layouts: *mut PlacedFootprint, + rows: *mut u32, + row_sizes: *mut u64, + total: *mut u64, +) { + const PLACEMENT: u64 = 512; + // SAFETY: the title passes a description (null is tolerated). + let desc = unsafe { desc.as_ref() }; + let mut end = base; + let mut known = desc.is_some(); + for i in 0..count { + let one = desc.and_then(|d| subresource(d, first + i)); + let (layout, row_count, row_size) = match one { + Some((mut footprint, row_count, row_size)) => { + footprint.offset = end.next_multiple_of(PLACEMENT); + let pitch = u64::from(footprint.row_pitch); + let lines = u64::from(row_count) * u64::from(footprint.depth); + end = footprint.offset + pitch * lines.saturating_sub(1) + row_size; + (footprint, row_count, row_size) + } + None => { + known = false; + (NO_FOOTPRINT, u32::MAX, u64::MAX) + } + }; + let i = i as usize; + // SAFETY: each output is null or holds `count` entries. + unsafe { + if !layouts.is_null() { + layouts.add(i).write(layout); + } + if !rows.is_null() { + rows.add(i).write(row_count); + } + if !row_sizes.is_null() { + row_sizes.add(i).write(row_size); + } + } + } + if !known { + tracing::warn!(?desc, "no footprint for this resource"); + } + if !total.is_null() { + // SAFETY: checked non-null. + unsafe { total.write(if known { end - base } else { u64::MAX }) }; + } +} + +/// Device method: the footprint of resources placed one after another. +/// Returns a 16-byte value, through a hidden first argument. Invalid input +/// gives the documented size `u64::MAX`. +pub(crate) extern "system" fn allocation_info( + out: *mut AllocationInfo, + _: This, + _visible: u32, + count: u32, + descs: *const ResourceDesc, +) -> *mut AllocationInfo { + let descs = if descs.is_null() { + &[][..] + } else { + // SAFETY: the title passes `count` descriptions. + unsafe { std::slice::from_raw_parts(descs, count as usize) } + }; + // SAFETY: the caller passes room for the value. + unsafe { out.write(place(descs.iter(), |_, _| ())) }; + out +} + +/// The newer description: the plain one, then a sampler feedback mip +/// region (width, height, depth). +#[repr(C)] +pub(crate) struct ResourceDesc1 { + desc: ResourceDesc, + mip_region: [u32; 3], +} +const _: () = assert!(size_of::() == 72); + +/// Where one resource goes in [`allocation_info2`]'s placement. +#[repr(C)] +pub(crate) struct AllocationInfo1 { + offset: u64, + alignment: u64, + size: u64, +} + +/// Device method 0x360 (`ID3D12Device8`): [`allocation_info`] for newer +/// descriptions, also telling where each resource goes. +pub(crate) extern "system" fn allocation_info2( + out: *mut AllocationInfo, + _: This, + _visible: u32, + count: u32, + descs: *const ResourceDesc1, + each: *mut AllocationInfo1, +) -> *mut AllocationInfo { + let descs = if descs.is_null() { + &[][..] + } else { + // SAFETY: the title passes `count` descriptions. + unsafe { std::slice::from_raw_parts(descs, count as usize) } + }; + let total = place(descs.iter().map(|d| &d.desc), |i, info| { + if !each.is_null() { + // SAFETY: the title passes room for `count` entries. + unsafe { each.add(i).write(info) }; + } + }); + // SAFETY: the caller passes room for the value. + unsafe { out.write(total) }; + out +} + +/// Resources placed one after another: the whole footprint, telling `each` +/// where every resource goes. Unknown sizes give the documented `u64::MAX`. +fn place<'a>( + descs: impl Iterator, + mut each: impl FnMut(usize, AllocationInfo1), +) -> AllocationInfo { + let mut total = AllocationInfo { + size: 0, + alignment: KIB_64, + }; + for (i, desc) in descs.enumerate() { + let Some(one) = footprint(desc) else { + tracing::warn!(?desc, "no size for this resource"); + each( + i, + AllocationInfo1 { + offset: u64::MAX, + alignment: 0, + size: u64::MAX, + }, + ); + return AllocationInfo { + size: u64::MAX, + alignment: 0, + }; + }; + tracing::debug!(?desc, ?one, "allocation info"); + let offset = total.size.next_multiple_of(one.alignment); + each( + i, + AllocationInfo1 { + offset, + alignment: one.alignment, + size: one.size, + }, + ); + total.size = offset + one.size; + total.alignment = total.alignment.max(one.alignment); + } + total +} + +/// Zeroed host memory standing in for GPU memory. +pub(crate) struct Memory { + ptr: NonNull, + layout: Layout, + /// Set when the memory came from the title's allocator, with these + /// allocation attributes (it goes back there). + attributes: Option, +} + +pub type AllocRoutine = extern "system" fn(usize, u64) -> *mut c_void; +pub type FreeRoutine = extern "system" fn(*mut c_void, u64); +static ALLOCATOR: std::sync::OnceLock<(AllocRoutine, FreeRoutine)> = std::sync::OnceLock::new(); + +/// Committed resources get their memory from the title's general +/// allocator, as on the console, where titles hook it to place graphics +/// memory themselves (the title places its back buffers in a +/// block of its own and checks they fill it). The runtime names it before +/// the device exists. +pub fn use_allocator(alloc: AllocRoutine, free: FreeRoutine) { + let _ = ALLOCATOR.set((alloc, free)); +} + +/// Maps the physical pages behind one range of title memory at another, +/// `(to, from, len)` (`from` 0 unmaps); false on failure. +pub type PageMapper = fn(u64, u64, u64) -> bool; +static PAGE_MAPPER: std::sync::OnceLock = std::sync::OnceLock::new(); + +/// The runtime's page mapper, for the queues' page-mapping copies (memory +/// is the runtime's, as on the console). +pub fn use_page_mapper(mapper: PageMapper) { + let _ = PAGE_MAPPER.set(mapper); +} + +pub(crate) fn page_mapper() -> Option { + PAGE_MAPPER.get().copied() +} + +/// Allocation attributes for resource memory: allocator id, page size +/// (bits 14-15: 2 MiB pages from 2 MiB up, else 64 KiB), alignment as log2 +/// (bits 24-28) and memory type (bits 29-32: write-combined for GPU-only +/// heaps, cacheable for the CPU-visible ones). +/// shortcut: the console runtime's own choice of page size and memory type +/// is not known; this is the plausible one. +fn resource_attributes(info: AllocationInfo, heap_kind: u32) -> u64 { + const GRAPHICS_ALLOCATOR: u64 = 128 << 16; + const DEFAULT_HEAP: u32 = 1; + let pages: u64 = if info.size >= 2 << 20 { 2 } else { 1 }; + let memory: u64 = if heap_kind == DEFAULT_HEAP { 1 } else { 3 }; + let alignment = u64::from(info.alignment.max(1).trailing_zeros()); + GRAPHICS_ALLOCATOR | pages << 14 | alignment << 24 | memory << 29 +} + +impl Memory { + /// A committed resource's memory: from the title's allocator if the + /// runtime named one, else our own; zeroed either way. + fn for_resource(info: AllocationInfo, heap_kind: u32) -> Result { + let Some(&(alloc, _)) = ALLOCATOR.get() else { + return Memory::new(info); + }; + let layout = Layout::from_size_align(info.size as usize, info.alignment as usize) + .map_err(|_| E_INVALIDARG)?; + let attributes = resource_attributes(info, heap_kind); + let ptr = + NonNull::new(alloc(layout.size(), attributes).cast::()).ok_or(E_OUTOFMEMORY)?; + // SAFETY: the allocator handed out `size` bytes. + unsafe { ptr.as_ptr().write_bytes(0, layout.size()) }; + Ok(Memory { + ptr, + layout, + attributes: Some(attributes), + }) + } + + /// `size` zeroed bytes aligned to `alignment` (a power of two). + pub(crate) fn zeroed(size: u64, alignment: u64) -> Result { + Memory::new(AllocationInfo { size, alignment }) + } + + pub(crate) fn address(&self) -> u64 { + self.ptr.as_ptr() as u64 + } + + fn new(info: AllocationInfo) -> Result { + let layout = usize::try_from(info.size) + .ok() + .zip(usize::try_from(info.alignment).ok()) + .filter(|&(size, _)| size > 0) + .and_then(|(size, align)| Layout::from_size_align(size, align).ok()) + .ok_or(E_INVALIDARG)?; + // SAFETY: the size is non-zero. + let ptr = NonNull::new(unsafe { alloc_zeroed(layout) }).ok_or(E_OUTOFMEMORY)?; + // The big ones are named in the log: the memory line counts our own + // allocations by size, and these are the title's memory given out + // of ours (a heap it made through the device, a descriptor heap). + if info.size >= 32 << 20 { + tracing::info!(mb = info.size >> 20, at = ?ptr, "memory for the title from our allocator (a heap or a descriptor heap)"); + } + Ok(Memory { + ptr, + layout, + attributes: None, + }) + } +} + +impl Drop for Memory { + fn drop(&mut self) { + match (self.attributes, ALLOCATOR.get()) { + (Some(attributes), Some(&(_, free))) => free(self.ptr.as_ptr().cast(), attributes), + // SAFETY: allocated in `new` with this layout. + _ => unsafe { dealloc(self.ptr.as_ptr(), self.layout) }, + } + } +} + +#[repr(C)] +struct Heap { + object: Object, + desc: HeapDesc, + memory: Memory, +} + +pub(crate) extern "system" fn create_heap( + _: This, + desc: *const HeapDesc, + iid: *const Iid, + out: *mut This, +) -> HRESULT { + // SAFETY: the title passes a description (null is tolerated). + let Some(&desc) = (unsafe { desc.as_ref() }) else { + return E_INVALIDARG; + }; + tracing::debug!( + size = desc.size, + kind = desc.properties.kind, + flags = format_args!("{:#x}", desc.flags), + "heap" + ); + if desc.alignment != 0 && !desc.alignment.is_power_of_two() { + return E_INVALIDARG; + } + let info = AllocationInfo { + size: desc.size, + alignment: desc.alignment.max(KIB_64), + }; + let memory = match Memory::new(info) { + Ok(memory) => memory, + Err(hr) => return hr, + }; + let heap = Box::new(Heap { + object: Object::new(&HEAP_FUNCTIONS), + desc, + memory, + }); + object::hand_out(HEAP, heap, iid, &HEAP_IIDS, out) +} + +extern "system" fn heap_query(this: This, iid: *const Iid, out: *mut This) -> HRESULT { + object::answer(HEAP, iid, object::is(iid, &HEAP_IIDS).then_some(this), out) +} +extern "system" fn heap_release(this: This) -> u32 { + object::release_boxed::(this) +} +extern "system" fn heap_desc(this: This, out: *mut HeapDesc) { + if !out.is_null() { + // SAFETY: `this` is a heap; the title passes room for a description. + unsafe { out.write((*this.cast::()).desc) }; + } +} + +/// A resource's memory: its own, or a range of a heap it holds a reference +/// to. +enum Backing { + Committed(Memory), + Placed { + heap: This, + offset: u64, + }, + /// Memory the title mapped itself, at this address. + Address(*mut u8), +} + +impl Drop for Backing { + fn drop(&mut self) { + if let Backing::Placed { heap, .. } = *self { + heap_release(heap); + } + } +} + +#[repr(C)] +struct Resource { + object: Object, + desc: ResourceDesc, + heap: HeapProperties, + heap_flags: u32, + backing: Backing, + /// Textures also live on the host GPU (decision 0007); buffers do not + /// yet. With, for a depth texture the title also writes as unordered + /// access, the colour texture shaders write instead ([`Twin`]). + #[cfg(windows)] + host: Hosted, +} + +/// A title texture's host copy and the state it is in. The title's barriers +/// name console states (looser than the host's), so we transition from this +/// one. Lists that use the texture hold it until they are reset: the title +/// may release a resource whose commands it recorded but not yet submitted +/// (console memory outlives the object; a host texture must outlive the +/// lists that name it). +#[cfg(windows)] +pub(crate) struct HostTexture { + pub(crate) texture: windows::Win32::Graphics::Direct3D12::ID3D12Resource, + pub(crate) state: std::sync::atomic::AtomicU32, + /// The bytes the host gives it. + bytes: u64, + /// Whether its contents come from title memory ([`fills`]): counted in + /// [`KINDS`] while it lives. + filled: bool, + /// Made without memory of its own (`crate::tiles`): the tiles its + /// levels have been given. Its `bytes` are 0: what it holds of the card + /// is counted there. + pub(crate) tiled: Option, +} + +/// What a title texture has on the host: its host copy and, for a depth +/// texture shaders also write, the colour twin. +#[cfg(windows)] +type Made = (std::sync::Arc, Option>); + +/// A title texture's host side. The host copy is made when something first +/// uses the texture, not when the title creates it: the title +/// had created 3,871 textures (9.2 GB on the host) before its world's first +/// frame, of which a frame's lists name some hundreds (run 23), on a card +/// with 12 GB. A title texture is memory the title has either way; its host +/// copy is the card's. +#[cfg(windows)] +struct Hosted { + /// The host copy (and twin) once made. Taken out again only by + /// [`let_go_idle`] and when the title releases the resource. + made: std::sync::Mutex>, + /// The state and clear value the title created the texture with. + state: u32, + clear: Option<[u32; 5]>, + /// When the host copy was last asked for (`crate::host::moment`), + /// written under `made`'s lock. + used: std::sync::atomic::AtomicU64, + /// The host refused to make it: not tried again. + refused: std::sync::atomic::AtomicBool, + /// Its host copy was let go as idle once. + gone: std::sync::atomic::AtomicBool, + /// A texture of [`PLACED_TEXTURES`]. + placed: std::sync::atomic::AtomicBool, +} + +/// Counts for the memory line: host copies of textures the title fills +/// alive and their bytes; such copies let go as idle since the start and +/// their bytes; made again after that and their bytes; and host copies made +/// since the start. +#[cfg(windows)] +pub(crate) static KINDS: [std::sync::atomic::AtomicU64; 7] = + [const { std::sync::atomic::AtomicU64::new(0) }; 7]; + +/// Every title texture alive (not buffers), by address: for the sweep and +/// the memory line. A texture leaves the table before it is freed. +#[cfg(windows)] +static TEXTURES: std::sync::Mutex> = + std::sync::Mutex::new(std::collections::BTreeSet::new()); + +#[cfg(windows)] +fn textures() -> std::sync::MutexGuard<'static, std::collections::BTreeSet> { + TEXTURES.lock().unwrap_or_else(|e| e.into_inner()) +} + +/// The title textures the host renders to or writes (targets, depth, +/// unordered access), by the address of their memory: what a view the +/// title places in that memory in another format shows ([`alias_of`]). A +/// texture leaves the table before it is freed. +#[cfg(windows)] +static TARGETS_AT: std::sync::Mutex> = + std::sync::Mutex::new(std::collections::BTreeMap::new()); + +/// For `this`, a texture made for a view the title placed in memory +/// ([`texture_at`]): the title texture the host writes that lies in the +/// same memory, if there is one of the same size, levels and layers with +/// texels of the same width. The console reads such a texture through the +/// view as it is +/// (the title packs light as R9G9B9E5 into R32_UINT textures +/// with compute shaders, which cannot write R9G9B9E5, and samples them +/// through R9G9B9E5 views placed at the textures' addresses: the sky, the +/// sky and light probes, the bounced light the lighting pass adds). On the +/// host the two are two textures and what the shaders wrote exists in one +/// of them only: the other was filled from title memory, which nothing +/// writes, so everything read through such a view was black. +/// Textures of several levels or layers count too (the screen probes' +/// light atlas has four levels, the camera's sky light cache six layers, +/// the cloud and sky tables are volumes): only textures of one level and +/// one layer were found at first, and the programs behind the others read +/// the title's unwritten memory - the sky light cache's second stage wrote +/// all zeros from a first stage that held light (run 88). +/// `LEONIDA_ALIAS_COPY=0`: none is found, as before; `=1`: only textures +/// of one level and one layer, as at first. +#[cfg(windows)] +pub(crate) fn alias_of(this: This) -> Option { + use std::sync::atomic::Ordering::Relaxed; + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + if this.is_null() + || !*ON.get_or_init(|| std::env::var_os("LEONIDA_ALIAS_COPY").is_none_or(|v| v != "0")) + { + return None; + } + static WHOLE: std::sync::OnceLock = std::sync::OnceLock::new(); + let whole = + *WHOLE.get_or_init(|| std::env::var_os("LEONIDA_ALIAS_COPY").is_none_or(|v| v != "1")); + let r = resource(this); + // A level count of 0 asks for a full chain: not counted here. + let one = |d: &ResourceDesc| { + d.dimension != BUFFER + && d.mip_levels >= 1 + && d.depth_or_array_size >= 1 + && (whole || (d.mip_levels == 1 && d.depth_or_array_size == 1)) + && d.sample_count <= 1 + }; + if !r.host.placed.load(Relaxed) || !fills(&r.desc) || !one(&r.desc) { + return None; + } + // Under the table's lock: a texture leaves it before it is freed. + let targets = TARGETS_AT.lock().unwrap_or_else(|e| e.into_inner()); + let other = *targets.get(&(r.data() as u64))? as This; + let o = resource(other); + const DEPTH: u32 = 0x2; + let same = one(&o.desc) + && o.desc.dimension == r.desc.dimension + && o.desc.width == r.desc.width + && o.desc.height == r.desc.height + && o.desc.mip_levels == r.desc.mip_levels + && o.desc.depth_or_array_size == r.desc.depth_or_array_size + && o.desc.flags & DEPTH == 0 + && target_format(o.desc.format) == o.desc.format + && element(o.desc.format).is_some_and(|e| e.1 == 1 && Some(e) == element(r.desc.format)); + same.then_some(other) +} + +/// Whether host copies are made on first use. On by default; +/// `LEONIDA_LAZY_TEXTURES=0` makes each when the title creates its texture, +/// as before. +#[cfg(windows)] +fn lazy() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("LEONIDA_LAZY_TEXTURES").is_none_or(|v| v != "0")) +} + +/// Whether a texture described by `desc` takes its contents from title +/// memory: one the host neither renders to nor writes (no target, depth or +/// unordered access flag). Its host copy can be made again from that +/// memory; any other texture's contents exist on the host alone. +#[cfg(windows)] +fn fills(desc: &ResourceDesc) -> bool { + const TARGET_DEPTH_UNORDERED: u32 = 0x7; + desc.dimension != BUFFER && desc.flags & TARGET_DEPTH_UNORDERED == 0 +} + +/// Whether the title fills texture `this` itself ([`fills`]). +#[cfg(windows)] +pub(crate) fn title_fills(this: This) -> bool { + !this.is_null() && fills(&resource(this).desc) +} + +/// Whether `this` is a texture whose host copy is not made yet (and may +/// still be): a descriptor slot written with a view of it waits +/// (`crate::descriptor::make_waiting`). +#[cfg(windows)] +pub(crate) fn host_waits(this: This) -> bool { + if this.is_null() || !lazy() { + return false; + } + let r = resource(this); + r.desc.dimension != BUFFER + && !r.host.refused.load(std::sync::atomic::Ordering::Relaxed) + && r.host.made.lock().unwrap_or_else(|e| e.into_inner()).is_none() +} + +/// The host side of title texture `this`: made now if it is not there and +/// `make` says so. `None` for buffers and for textures the host refuses. +#[cfg(windows)] +fn hosted(this: This, make: bool) -> Option { + use std::sync::atomic::Ordering::Relaxed; + let r = resource(this); + if r.desc.dimension == BUFFER { + return None; + } + let mut made = r.host.made.lock().unwrap_or_else(|e| e.into_inner()); + if made.is_none() { + if !make || r.host.refused.load(Relaxed) { + return None; + } + let clear = r + .host + .clear + .as_ref() + .map_or(std::ptr::null(), |c| std::ptr::from_ref(c).cast::()); + // Levels on demand (`crate::tiles`): a texture the title places in + // memory and fills, of a megabyte or more, that does not hold all + // its levels now, is made without memory and given it level by + // level. It does not hold them all if its memory is not all + // mapped, if the next texture starts inside its span, or if a + // view of it starts below level 0. Every other texture, and this + // one if the card will not have it so, is made as before. + const TEXTURE_2D: u32 = 3; + let mut tiled = None; + let mut texture = None; + let shape_fits = fills(&r.desc) + && r.desc.dimension == TEXTURE_2D + && r.desc.depth_or_array_size == 1 + && r.desc.mip_levels > 1 + && r.desc.sample_count <= 1; + if shape_fits && r.host.placed.load(Relaxed) && crate::tiles::wanted() { + let bytes = footprint(&r.desc).map_or(0, |f| f.size); + let start = r.data() as u64; + // What the upload can read: a console layout, no XOR mode + // (`crate::texture` `staging`). + let readable = texture_layout(&r.desc).is_some_and(|t| !t.planes[0].layout.desc.swizzle.xor()); + let partly = readable + && bytes >= crate::tiles::floor() + && (!crate::texture::committed(r.data().cast_const(), bytes as usize) + || crate::descriptor::host::next_start(start, start.saturating_add(bytes)).is_some() + || crate::descriptor::host::first_viewed(start).is_some_and(|first| first > 0)); + let reserved = if partly { host_texture_as(&r.desc, r.host.state, clear, true) } else { None }; + let cut = reserved + .as_ref() + .zip(crate::host::host()) + .and_then(|(t, host)| crate::tiles::Tiled::make(&host.device, t, u32::from(r.desc.mip_levels))); + // (Both or neither: a reserved texture the card will not cut + // into tiles is dropped here, and the old kind is made below.) + if cut.is_some() { + tiled = cut; + texture = reserved; + } + } + let texture = match texture { + Some(texture) => Some(texture), + None => host_texture(&r.desc, r.host.state, clear), + }; + let Some(texture) = texture else { + r.host.refused.store(true, Relaxed); + return None; + }; + let twin = twin_texture(&r.desc, &texture); + // One line per depth texture with unordered access: its address is + // the one target dumps and the captured frame's list of commands + // name. + if r.desc.flags & 6 == 6 { + tracing::info!( + resource = ?this, + desc = ?r.desc, + twin = twin.is_some(), + "depth texture with unordered access" + ); + } + let state = crate::host::legal_state(&texture, crate::host::texture_state(r.host.state)); + let mut host = match tiled { + Some(tiled) => HostTexture::new_tiled(texture, state, tiled), + None => HostTexture::new(texture, state), + }; + host.filled = fills(&r.desc); + if host.filled { + KINDS[0].fetch_add(1, Relaxed); + KINDS[1].fetch_add(host.bytes, Relaxed); + } + if r.host.gone.load(Relaxed) { + KINDS[4].fetch_add(1, Relaxed); + KINDS[5].fetch_add(host.bytes, Relaxed); + } + KINDS[6].fetch_add(1, Relaxed); + *made = Some((std::sync::Arc::new(host), twin)); + // Slots the title wrote with views of it while it had no host copy + // are made before the next submission runs. + crate::descriptor::texture_made(this as usize); + } + r.host.used.store(crate::host::moment(), Relaxed); + made.clone() +} + +/// The host copy of title texture `this` if it is made, without making it +/// (for diagnostics, which must not count as a use). +#[cfg(all(windows, feature = "diagnostics"))] +pub(crate) fn host_made<'a>( + this: This, +) -> Option<&'a windows::Win32::Graphics::Direct3D12::ID3D12Resource> { + if this.is_null() { + return None; + } + let (host, _) = hosted(this, false)?; + // SAFETY: as in `host_resource`. + Some(unsafe { &*std::ptr::from_ref(&host.texture) }) +} + +/// Whether more host copies of textures the title fills may be made for +/// shaders that pick textures by index (`draw.rs` `heap_textures`): always +/// up to `FLOOR` bytes of them, beyond that while the card's memory in use +/// by this process is under nine tenths of the budget the system gives it +/// ([`room_percent`] says another share; `LEONIDA_TEXTURE_BUDGET_MB` sets a +/// limit on those copies' bytes instead). Past the budget the system moves +/// the card's memory into the PC's, which ended runs 20 and 24. +#[cfg(windows)] +pub(crate) fn room() -> bool { + use std::sync::atomic::Ordering::Relaxed; + const FLOOR: u64 = 2 << 30; + const WITHOUT_BUDGET: u64 = 4 << 30; + static LIMIT: std::sync::OnceLock> = std::sync::OnceLock::new(); + let limit = *LIMIT.get_or_init(|| { + let mb = std::env::var("LEONIDA_TEXTURE_BUDGET_MB").ok()?; + mb.trim().parse::().ok().map(|mb| mb << 20) + }); + // (With the tiles of the copies made level by level, whose own bytes + // count as none: `crate::tiles`.) + let filled = KINDS[1].load(Relaxed) + crate::tiles::given_total(); + if let Some(limit) = limit { + return filled < limit; + } + if filled < FLOOR { + return true; + } + match crate::host::host().and_then(|h| h.video_memory()) { + // What is kept for card copies of title buffers not made yet + // (`crate::shadow::card_room_kept`) and for the render targets a + // world makes in its first frame ([`targets_room_kept`]) counts as + // used. + Some([budget, used, ..]) => { + used + crate::shadow::card_room_kept() + targets_room_kept() < budget / 100 * room_percent() + } + None => filled < WITHOUT_BUDGET, + } +} + +/// The bytes of the card's memory the texture queue leaves free for +/// render targets and other host copies the host itself writes that are +/// not made yet: `LEONIDA_CARD_ROOM_FOR_TARGETS_MB` (3,072; 0: none, as +/// before) less what such copies hold now. +/// +/// Measured (runs 193, 197, 198): 652 MB of them before the world, 2,255 +/// to 2,352 MB right after its first frame, 2,800 to 3,100 MB two minutes +/// on, none of them idle (run 198's census). They are made with no room +/// test, in the same frame as the card copies of title buffers (762 MB), +/// after the texture queue has filled the card to its line with textures +/// written while the world loaded (7.3 GB of them at the first world frame +/// of run 193, of which 2.3 GB were let go again within 13 seconds). The +/// card then stood at 99 to 100.5 % of its budget, buffer copies were +/// turned down for good (31 of 95 made: the frame 355 ms where 95 give +/// 238), and the queue was refused from the first world frame on. With +/// their room kept, the queue stops that much earlier while the world +/// loads and gets it back as the targets are made. +#[cfg(windows)] +pub(crate) fn targets_room_kept() -> u64 { + use std::sync::atomic::Ordering::Relaxed; + static MOST: std::sync::OnceLock = std::sync::OnceLock::new(); + let most = *MOST.get_or_init(|| { + std::env::var("LEONIDA_CARD_ROOM_FOR_TARGETS_MB") + .ok() + .and_then(|v| v.trim().parse::().ok()) + .map_or(3072 << 20, |mb| mb.min(8192) << 20) + }); + // Every host texture's bytes less those of the copies the title fills. + let targets = HOST_TEXTURES[1].load(Relaxed).saturating_sub(KINDS[1].load(Relaxed)); + most.saturating_sub(targets) +} + +/// [`room`] as it was at most a tenth of a second ago, for a question +/// asked of many textures a frame ([`room`] asks the system each time). +#[cfg(windows)] +pub(crate) fn room_lately() -> bool { + use std::sync::atomic::Ordering::Relaxed; + // The tenth of a second of the last asking, counted from 1, and its + // answer in the lowest bit. + static LAST: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + let tenth = crate::host::now_ms() / 100 + 1; + let last = LAST.load(Relaxed); + if last >> 1 == tenth { + return last & 1 != 0; + } + let room = room(); + LAST.store((tenth << 1) | u64::from(room), Relaxed); + room +} + +/// The share of the card's budget, in percent, up to which host copies of +/// textures picked by index are made ([`room`]): 90 unless +/// `LEONIDA_TEXTURE_ROOM_PERCENT` says another (50 to 97). At 90 about a +/// tenth of the budget, 1,020 MB of 10,200, stays unused while thousands of +/// textures wait (runs 170-174); the card copies of title buffers from +/// 1 MiB up take 449 MB more of the card than before (941 against 492), +/// and 94 gives the textures about that much back. +#[cfg(windows)] +fn room_percent() -> u64 { + static PERCENT: std::sync::OnceLock = std::sync::OnceLock::new(); + *PERCENT.get_or_init(|| { + std::env::var("LEONIDA_TEXTURE_ROOM_PERCENT") + .ok() + .and_then(|v| v.trim().parse::().ok()) + .map_or(90, |percent| percent.clamp(50, 97)) + }) +} + +/// For the card accounting line ([`card_accounting`]): the title texture +/// made for a view of memory at `address` with the resource description +/// `desc`, if there is one ([`texture_at`] makes it; this does not). +#[cfg(windows)] +pub(crate) fn placed_known(address: u64, desc: &[u32; 14]) -> Option { + // Without the filler words and with them: whichever `texture_at` keeps. + let mut key = *desc; + key[1] = 0; + key[13] = 0; + let map = PLACED_TEXTURES.lock().unwrap_or_else(|e| e.into_inner()); + map.get(&(address, key)).or_else(|| map.get(&(address, *desc))).map(|&r| r as This) +} + +/// For the card accounting line: whether title texture `this` has a host +/// copy now (2), had one that was let go and not made again (1), or never +/// had one (0); the bytes (its host copy's on the card, or without one +/// what its console layout takes in title memory); and where its title +/// memory is. `None` for buffers. Not a use of the texture. +#[cfg(windows)] +pub(crate) fn copy_state(this: This) -> Option<(u8, u64, u64)> { + use std::sync::atomic::Ordering::Relaxed; + if this.is_null() { + return None; + } + let r = resource(this); + if r.desc.dimension == BUFFER { + return None; + } + let memory = r.data() as u64; + let made = r.host.made.lock().unwrap_or_else(|e| e.into_inner()); + Some(match made.as_ref() { + Some((host, _)) => (2, host.bytes, memory), + None => (u8::from(r.host.gone.load(Relaxed)), footprint(&r.desc).map_or(0, |f| f.size), memory), + }) +} + +/// One line of where the card's memory is and what the queue of textures +/// picked by index would need (`LEONIDA_CARD_ACCOUNTING=1`; `draw.rs` +/// `card_accounting` says when, and hands over the queue's side: `room` +/// as the pass found it, `due` its counts, `never` and `gone` the memory +/// of the due textures without a host copy). The line holds +/// - the host copies of textures the title fills that are alive: how +/// many, their bytes, and the bytes of the levels whose title memory is +/// not mapped (a host copy is made with every level of the description; +/// a texture streaming in has its small levels only). A copy's bytes +/// are shared out to its levels by their texels, so that part is an +/// estimate; +/// - the due slots: how many, and their textures by what they have on +/// the card (a host copy alive: no card memory needed; never one; one +/// that was let go), with the bytes the last two would need and how +/// much of their memory is mapped now; +/// - the host copies let go, made again and made since the line before. +/// +/// The textures are noted under the table's lock (their memory, their +/// description, their copy's bytes: about a millisecond for 18,000) and +/// the kernel is asked about their memory on a thread of its own, after +/// the lock is given back: one question for a texture that is all there +/// (up to 256 pages each; 18,000 textures of 5.5 GB are 1.4 million +/// pages, some 20,000 questions), one per level and array slice more for +/// one that is not. Not measured: a tenth to half a second is expected, +/// and the line says what it took. No line is begun while one is walking. +#[cfg(windows)] +pub(crate) fn card_accounting(room: bool, due: [u64; 5], never: Vec<(u64, u64)>, gone: Vec<(u64, u64)>) { + use std::sync::atomic::Ordering::Relaxed; + static WALKING: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); + // Host copies let go and their bytes, made again and their bytes, and + // made in all, at the line before. + static BEFORE: [std::sync::atomic::AtomicU64; 5] = [const { std::sync::atomic::AtomicU64::new(0) }; 5]; + if WALKING.swap(true, Relaxed) { + return; + } + let began = std::time::Instant::now(); + // (The last: made level by level, its bytes are those of its tiles.) + let mut copies: Vec<(usize, ResourceDesc, u64, bool)> = Vec::new(); + // Textures the title fills without a host copy: never one, one let go. + let mut without = [0u64; 2]; + { + let all = textures(); + for &at in all.iter() { + // SAFETY: as in `let_go_idle`. + let r = unsafe { &*(at as *const Resource) }; + if !fills(&r.desc) { + continue; + } + let made = r.host.made.lock().unwrap_or_else(|e| e.into_inner()); + match made.as_ref() { + Some((host, _)) => copies.push(match &host.tiled { + Some(tiled) => (r.data() as usize, r.desc, tiled.given_bytes(), true), + None => (r.data() as usize, r.desc, host.bytes, false), + }), + None => without[usize::from(r.host.gone.load(Relaxed))] += 1, + } + } + } + let kinds = KINDS.each_ref().map(|k| k.load(Relaxed)); + let mut since = [0u64; 5]; + for ((slot, now), before) in since.iter_mut().zip([kinds[2], kinds[3], kinds[4], kinds[5], kinds[6]]).zip(&BEFORE) { + *slot = now.saturating_sub(before.swap(now, Relaxed)); + } + let video = crate::host::host().and_then(|h| h.video_memory()); + let noted_us = began.elapsed().as_micros() as u64; + let walk = move || { + fn texels(m: &texture::Mip) -> u64 { + u64::from(m.width) * u64::from(m.height) * u64::from(m.depth) + } + let began = std::time::Instant::now(); + // Copies; their bytes; the bytes of levels not mapped; copies with + // a level not mapped; with the largest level not mapped; with no + // level mapped; copies without a console layout (not asked). + let mut c = [0u64; 7]; + // Of the copies: made level by level, and the bytes of their tiles. + let mut on_demand = [0u64; 2]; + for &(memory, desc, bytes, by_level) in &copies { + c[0] += 1; + c[1] += bytes; + if by_level { + on_demand[0] += 1; + on_demand[1] += bytes; + continue; + } + let Some(layout) = texture_layout(&desc).map(|t| t.planes[0].layout.clone()) else { + c[6] += 1; + continue; + }; + if layout.size == 0 || crate::texture::committed(memory as *const u8, layout.size as usize) { + continue; + } + c[3] += 1; + // Every slice holds the whole chain: the levels of the tail in + // its first block, the others after it from the smallest up + // (`leonida_formats::texture::Layout`). + let mips = &layout.mips; + let tail = (layout.first_tail_mip as usize).min(mips.len()); + let there = |from: u64, to: u64| { + (0..u64::from(layout.slices)).all(|slice| { + let at = memory as u64 + slice * layout.slice_size + from; + crate::texture::committed(at as *const u8, (to - from) as usize) + }) + }; + let all: u64 = mips.iter().map(texels).sum::().max(1); + let (mut missing, mut any) = (0u64, false); + for (level, m) in mips.iter().enumerate().take(tail) { + let end = if level == 0 { layout.slice_size } else { mips[level - 1].offset }; + if end <= m.offset { + continue; + } + if there(m.offset, end) { + any = true; + } else { + missing += texels(m); + c[4] += u64::from(level == 0); + } + } + if tail < mips.len() { + if there(0, layout.alignment.min(layout.slice_size).max(1)) { + any = true; + } else { + missing += mips[tail..].iter().map(texels).sum::(); + } + } + c[2] += (u128::from(bytes) * u128::from(missing) / u128::from(all)) as u64; + c[5] += u64::from(!any); + } + // Of the due textures without a host copy: how many; the bytes of + // their memory; with all of it mapped, and those bytes; with part + // of it mapped, and the bytes that are; with none of it mapped. + let mapped = |list: &[(u64, u64)]| { + let mut n = [0u64; 7]; + for &(at, len) in list { + n[0] += 1; + n[1] += len; + let there = crate::texture::mapped_bytes(at as *const u8, len as usize); + if len > 0 && there >= len { + n[2] += 1; + n[3] += len; + } else if there > 0 { + n[4] += 1; + n[5] += there; + } else { + n[6] += 1; + } + } + n + }; + let (never, gone) = (mapped(&never), mapped(&gone)); + let [budget_mb, used_mb] = video.map_or([0, 0], |v| [v[0] >> 20, v[1] >> 20]); + let [copies_n, copies_mb, unmapped_mb, partly, largest, nothing, unknown] = + [c[0], c[1] >> 20, c[2] >> 20, c[3], c[4], c[5], c[6]]; + let [without_never, without_gone] = without; + let [due_slots, due_uploaded, due_other, alive_n, alive_mb] = [due[0], due[1], due[2], due[3], due[4] >> 20]; + let [never_n, never_mb, never_whole, never_whole_mb, never_part, never_part_mb, never_none] = + [never[0], never[1] >> 20, never[2], never[3] >> 20, never[4], never[5] >> 20, never[6]]; + let [gone_n, gone_mb, gone_whole, gone_whole_mb, gone_part, gone_part_mb, gone_none] = + [gone[0], gone[1] >> 20, gone[2], gone[3] >> 20, gone[4], gone[5] >> 20, gone[6]]; + let [let_go, let_go_mb, again, again_mb, made] = [since[0], since[1] >> 20, since[2], since[3] >> 20, since[4]]; + let walk_ms = began.elapsed().as_millis() as u64; + let [by_level_n, by_level_mb] = [on_demand[0], on_demand[1] >> 20]; + tracing::info!( + "card accounting: room {room}, the card {used_mb} MB in use of a budget of {budget_mb} MB; host copies of textures the title \ + fills: {copies_n} alive {copies_mb} MB, of which {unmapped_mb} MB are levels whose title memory is not mapped ({partly} copies \ + with such a level, {largest} of them the largest level, {nothing} with no level mapped; {unknown} without a console layout, not \ + asked); title textures without a host copy: {without_never} never had one, {without_gone} had one let go; due slots: \ + {due_slots} ({due_uploaded} uploaded before, {due_other} of nothing the title fills), their textures: {alive_n} with a host \ + copy alive ({alive_mb} MB, no card memory needed); {never_n} that never had one ({never_mb} MB of title memory: {never_whole} \ + all mapped {never_whole_mb} MB, {never_part} in part {never_part_mb} MB mapped, {never_none} not mapped); {gone_n} whose host \ + copy was let go ({gone_mb} MB: {gone_whole} all mapped {gone_whole_mb} MB, {gone_part} in part {gone_part_mb} MB mapped, \ + {gone_none} not mapped); since the line before: {let_go} host copies let go {let_go_mb} MB, {again} made again {again_mb} MB, \ + {made} made in all; noting took {noted_us} us on the frame's thread, the walk {walk_ms} ms on its own; of the host \ + copies {by_level_n} are made level by level and hold {by_level_mb} MB of tiles (in the MB alive, not in the levels not mapped)" + ); + WALKING.store(false, Relaxed); + }; + if std::thread::Builder::new().name("card accounting".into()).spawn(walk).is_err() { + WALKING.store(false, Relaxed); + } +} + +/// Lets go of the host copies of textures the title fills that nothing +/// names any more: placed textures were never released (one host texture +/// per address and description ever viewed: 18,639 of them, 2.5 GB, after +/// nine minutes of run 24), nor those of texture objects before the title +/// released them. A host copy goes when +/// - the title fills the texture ([`fills`]) and the host never copied +/// into it: its contents are in title memory; +/// - only the resource holds it: no list not yet reset names it (a list +/// holds the copies of the textures it uses, `HostList::transition`); +/// - only the host copy holds the host texture: no descriptor slot views +/// it (a slot keeps what it views, `HostHeap::kept`), so no shader can +/// read it through a slot made earlier, by a table or by an index; +/// - nothing asked for it for `IDLE_MS` and `IDLE_FRAMES` frames. +/// +/// The next use makes the host copy anew and uploads the title's memory +/// again (its staging state goes with it). The title resource stays: its +/// address is what views and lists name. +/// shortcut: [`host_resource`] hands out the host texture without holding +/// it; a thread that asked for it and has not yet recorded its use (which +/// makes the list or the slot hold it) is protected by that idle time alone. +/// Every caller uses it at once, within the title's call. +/// Called before a submission starts, by the thread that submits. +/// `LEONIDA_TEXTURE_SWEEP=0` lets nothing go. +#[cfg(windows)] +pub(crate) fn let_go_idle() { + use std::sync::atomic::Ordering::Relaxed; + const IDLE_FRAMES: u64 = 4; + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + if !*ON.get_or_init(|| std::env::var_os("LEONIDA_TEXTURE_SWEEP").is_none_or(|v| v != "0")) { + return; + } + let idle_ms = crate::host::vram_idle_ms(crate::host::host().and_then(|h| h.video_memory())); + // For the trail (`crate::host::trail`): how many went, their bytes, + // and the first one. + let (mut went, mut bytes, mut first) = (0u64, 0u64, None); + let all = textures(); + for &at in all.iter() { + // SAFETY: a texture leaves the table before it is freed, under the + // lock held here (`Drop for Resource`). + let r = unsafe { &*(at as *const Resource) }; + if !fills(&r.desc) || crate::texture::host_wrote(at) { + continue; + } + let gone = { + let mut made = r.host.made.lock().unwrap_or_else(|e| e.into_inner()); + let idle = made.as_ref().is_some_and(|(host, _)| { + crate::host::long_ago(r.host.used.load(Relaxed), idle_ms, IDLE_FRAMES) + && std::sync::Arc::strong_count(host) == 1 + && crate::host::references(&host.texture) == 1 + }); + if idle { + // Under the lock: the next use must not find the staging + // state of the texture let go (it says "uploaded"). + crate::texture::unstage(at as This); + made.take() + } else { + None + } + }; + if let Some((host, _)) = gone { + r.host.gone.store(true, Relaxed); + KINDS[2].fetch_add(1, Relaxed); + KINDS[3].fetch_add(host.bytes, Relaxed); + went += 1; + bytes += host.bytes; + if first.is_none() { + first = Some(at); + } + crate::host::retire(host); + } + } + if went > 0 { + crate::host::trail(|| { + format!( + "sweep: {went} host copies of textures the title fills let go ({} KiB), each held by its title texture alone (no list, no slot); the first: title texture {:#x}", + bytes >> 10, + first.unwrap_or(0) + ) + }); + } +} + +/// For the memory line: the host copies the sweep never lets go +/// ([`let_go_idle`] takes only copies of textures the title fills that the +/// host never copied into), by what would say they are dead weight. A +/// count and the bytes (twins included) of: the copies the host renders to +/// or writes; of them, those whose title memory is not mapped now (its +/// first page); those nothing has used for 30 seconds and 60 frames and +/// that no list and no slot holds; those that are both; the copies of +/// textures the title fills that the host copied into; and, of the first, +/// the placed ones. Render-target copies grew from 2,319 MB at the world's +/// first frame to 3,075 MB 150 s later in run 197 and never shrank, while +/// 26,517 copies of filled textures were let go to stay under the card's +/// line. +#[cfg(all(windows, feature = "diagnostics"))] +pub(crate) fn targets_census() -> [u64; 12] { + use std::sync::atomic::Ordering::Relaxed; + let mut c = [0u64; 12]; + let all = textures(); + for &at in all.iter() { + // SAFETY: as in `let_go_idle`. + let r = unsafe { &*(at as *const Resource) }; + let made = r.host.made.lock().unwrap_or_else(|e| e.into_inner()); + let Some((host, twin)) = made.as_ref() else { + continue; + }; + let copied_into = host.filled && crate::texture::host_wrote(at); + if host.filled && !copied_into { + continue; + } + let bytes = host.bytes + twin.as_ref().map_or(0, |t| t.colour.bytes); + let mut add = |i: usize| { + c[i] += 1; + c[i + 1] += bytes; + }; + if copied_into { + add(8); + continue; + } + add(0); + let placed = r.host.placed.load(Relaxed); + // Its first page: what is there of a texture starts there. + let unmapped = placed && !crate::texture::committed(r.data().cast_const(), 1); + let idle = crate::host::long_ago(r.host.used.load(Relaxed), 30_000, 60) + && std::sync::Arc::strong_count(host) == 1 + && crate::host::references(&host.texture) == 1; + if unmapped { + add(2); + } + if idle { + add(4); + } + if unmapped && idle { + add(6); + } + if placed { + add(10); + } + } + c +} + +/// For the memory line: title textures with a host copy the host renders +/// to or writes and those copies' bytes (twins included); title textures +/// without a host copy and the bytes of title memory they are; host copies +/// of textures the title fills and their bytes; of all title textures, +/// the placed ones with a host copy; the bytes of the twins alone (the +/// layer's own: the console has no second texture for a depth texture +/// shaders write); and, of the host copies of placed textures the title +/// fills, the bytes of those whose title memory is not mapped any more and +/// of those a descriptor slot still shows (the card holds a texture the +/// title has given up for as long as a slot shows it). The last two are +/// estimates from every 16th such texture: asking Windows about the memory +/// of all 16,000 takes too long. +#[cfg(all(windows, feature = "diagnostics"))] +pub(crate) fn census() -> [u64; 10] { + const EVERY: u64 = 16; + let mut count = [0u64; 10]; + let mut placed_filled = 0u64; + let all = textures(); + for &at in all.iter() { + // SAFETY: as in `let_go_idle`. + let r = unsafe { &*(at as *const Resource) }; + let made = r.host.made.lock().unwrap_or_else(|e| e.into_inner()); + match made.as_ref() { + Some((host, twin)) => { + let kind = if host.filled { 4 } else { 0 }; + count[kind] += 1; + count[kind + 1] += host.bytes + twin.as_ref().map_or(0, |t| t.colour.bytes); + count[7] += twin.as_ref().map_or(0, |t| t.colour.bytes); + let placed = r.host.placed.load(std::sync::atomic::Ordering::Relaxed); + if placed { + count[6] += 1; + } + if placed && host.filled { + placed_filled += 1; + // Its first page: a texture's smallest mips lie there, + // and are mapped first and unmapped last. + if placed_filled.is_multiple_of(EVERY) && !crate::texture::committed(r.data().cast_const(), 1) { + count[8] += host.bytes * EVERY; + if crate::host::references(&host.texture) > 1 { + count[9] += host.bytes * EVERY; + } + } + } + } + None => { + count[2] += 1; + count[3] += footprint(&r.desc).map_or(0, |f| f.size); + } + } + } + count +} + +/// Host textures alive (the title's and the twins) and the bytes the host +/// gives them, for the memory line. +#[cfg(windows)] +pub(crate) static HOST_TEXTURES: [std::sync::atomic::AtomicU64; 2] = + [const { std::sync::atomic::AtomicU64::new(0) }; 2]; + +/// The bytes the host allocates for `texture`. +#[cfg(windows)] +fn host_bytes(texture: &windows::Win32::Graphics::Direct3D12::ID3D12Resource) -> u64 { + let Some(host) = crate::host::host() else { + return 0; + }; + // SAFETY: plain queries on a live resource and device. + unsafe { + let desc = texture.GetDesc(); + host.device.GetResourceAllocationInfo(0, &[desc]).SizeInBytes + } +} + +#[cfg(windows)] +impl HostTexture { + fn new(texture: windows::Win32::Graphics::Direct3D12::ID3D12Resource, state: u32) -> HostTexture { + use std::sync::atomic::Ordering::Relaxed; + let bytes = host_bytes(&texture); + HOST_TEXTURES[0].fetch_add(1, Relaxed); + HOST_TEXTURES[1].fetch_add(bytes, Relaxed); + HostTexture { + texture, + state: std::sync::atomic::AtomicU32::new(state), + bytes, + filled: false, + tiled: None, + } + } + + /// A texture made without memory of its own (`crate::tiles`): counted + /// as a host texture of no bytes. + fn new_tiled( + texture: windows::Win32::Graphics::Direct3D12::ID3D12Resource, + state: u32, + tiled: crate::tiles::Tiled, + ) -> HostTexture { + HOST_TEXTURES[0].fetch_add(1, std::sync::atomic::Ordering::Relaxed); + HostTexture { + texture, + state: std::sync::atomic::AtomicU32::new(state), + bytes: 0, + filled: false, + tiled: Some(tiled), + } + } +} + +#[cfg(windows)] +impl Drop for HostTexture { + fn drop(&mut self) { + use std::sync::atomic::Ordering::Relaxed; + HOST_TEXTURES[0].fetch_sub(1, Relaxed); + HOST_TEXTURES[1].fetch_sub(self.bytes, Relaxed); + if self.filled { + KINDS[0].fetch_sub(1, Relaxed); + KINDS[1].fetch_sub(self.bytes, Relaxed); + } + } +} + +/// How many textures placed in title memory have a resource of ours +/// (never released), for the memory line. +#[cfg(all(windows, feature = "diagnostics"))] +pub(crate) fn placed_textures() -> u64 { + PLACED_TEXTURES.lock().unwrap_or_else(|e| e.into_inner()).len() as u64 +} + +/// Moves the host texture to `wanted` (a host texture state); the host +/// resource and the state it leaves, if that is a change. +#[cfg(windows)] +pub(crate) fn host_transition(this: This, wanted: u32) -> Option<(*mut c_void, u32)> { + use windows::core::Interface; + let (host, _) = hosted(this, true)?; + let before = host + .state + .swap(wanted, std::sync::atomic::Ordering::Relaxed); + (before != wanted).then(|| (host.texture.as_raw(), before)) +} + +/// The host GPU's copy of a title resource, if it has one: made now if +/// this is the texture's first use ([`Hosted`]). Asking is a use; what must +/// not count as one asks `host_made`. +#[cfg(windows)] +pub(crate) fn host_resource<'a>( + this: This, +) -> Option<&'a windows::Win32::Graphics::Direct3D12::ID3D12Resource> { + if this.is_null() { + return None; + } + let (host, _) = hosted(this, true)?; + // SAFETY: the resource holds the host copy until the title releases it + // (lists and slots that name the texture hold it past that), or until + // `let_go_idle` takes it: only from a texture the title fills, that no + // list and no slot holds and that nothing asked for in seconds (the + // asking just made is noted under the same lock). + Some(unsafe { &*std::ptr::from_ref(&host.texture) }) +} + +/// A title texture's host copy, shared, for a list to hold. +#[cfg(windows)] +pub(crate) fn host_copy(this: This) -> Option> { + if this.is_null() { + return None; + } + hosted(this, true).map(|made| made.0) +} + +/// A host texture like the title's: same description, in GPU memory, +/// without the console's layout and flags. +#[cfg(windows)] +fn host_texture( + desc: &ResourceDesc, + state: u32, + clear: *const c_void, +) -> Option { + host_texture_as(desc, state, clear, false) +} + +/// [`host_texture`]; `reserved`: without memory of its own, to be given +/// tiles level by level (`crate::tiles`). +#[cfg(windows)] +fn host_texture_as( + desc: &ResourceDesc, + state: u32, + clear: *const c_void, + reserved: bool, +) -> Option { + use windows::Win32::Graphics::Direct3D12::*; + const PC_FLAGS: u32 = 0xf; // render target, depth, UAV, no shader access + if desc.dimension == BUFFER { + return None; + } + let host = crate::host::host()?; + let mut d = *desc; + d.layout = 0; + d.alignment = 0; + d.flags &= PC_FLAGS; + // PC refuses depth targets that are also unordered-access (the console + // allows both; the title's shadow maps ask for it). + // The host copy loses the unordered access: shaders write a colour + // twin instead ([`Twin`]). + const DEPTH: u32 = 2; + const UNORDERED: u32 = 4; + if d.flags & DEPTH != 0 { + if d.flags & UNORDERED != 0 { + DEPTH_UNORDERED[0].fetch_add(1, std::sync::atomic::Ordering::Relaxed); + } + d.flags &= !UNORDERED; + } + d.format = pc_format(d.format); + const TARGET: u32 = 1; + if d.flags & (TARGET | UNORDERED) != 0 { + d.format = target_format(d.format); + } + const DENY_SHADER_RESOURCE: u32 = 8; + if d.flags & DENY_SHADER_RESOURCE == 0 + && let Some(&(_, typeless)) = DEPTH_FORMATS.iter().find(|&&(f, _)| f == d.format) + { + d.format = typeless; + } + // The host has no sRGB unordered access: such textures are typeless, + // their unordered access views plain UNORM. + if d.flags & UNORDERED != 0 && SRGB.iter().any(|&(srgb, _)| srgb == d.format) { + d.format = family(d.format); + } + // The clear value names the format too: format, then color or depth + // and stencil (5 words). + let clear_value = (!clear.is_null()).then(|| { + // SAFETY: the title passes a whole clear value. + let mut value = unsafe { clear.cast::<[u32; 5]>().read_unaligned() }; + value[0] = pc_format(value[0]); + if d.flags & (TARGET | UNORDERED) != 0 { + value[0] = target_format(value[0]); + } + value + }); + let heap = D3D12_HEAP_PROPERTIES { + Type: D3D12_HEAP_TYPE_DEFAULT, + ..Default::default() + }; + let mut texture: Option = None; + let made = if reserved { + // The card's own layout of 64 KiB tiles, which a reserved texture + // must have. + d.layout = D3D12_TEXTURE_LAYOUT_64KB_UNDEFINED_SWIZZLE.0 as u32; + // SAFETY: as below; a texture the title fills has no clear value. + unsafe { + host.device.CreateReservedResource( + (&raw const d).cast(), + D3D12_RESOURCE_STATES( + crate::host::legal_for(d.flags, crate::host::texture_state(state)) as i32, + ), + None, + &mut texture, + ) + } + } else { + // SAFETY: the description has the host layout (checked size, same + // fields); the out pointer is ours. + unsafe { + host.device.CreateCommittedResource( + &heap, + D3D12_HEAP_FLAG_NONE, + (&raw const d).cast(), + D3D12_RESOURCE_STATES( + crate::host::legal_for(d.flags, crate::host::texture_state(state)) as i32, + ), + // The same layout: format, then color or depth and stencil. + clear_value.as_ref().map(|v| std::ptr::from_ref(v).cast()), + &mut texture, + ) + } + }; + if let Err(e) = made { + tracing::warn!(error = %e, desc = ?d, reserved, "no host texture"); + } + if let Some(t) = &texture { + crate::host::name(t, || { + format!("texture {}x{} f{} flags {:#x}", d.width, d.height, d.format, d.flags) + }); + } + texture +} + +/// The host copy of title texture `this` if it is made and was made +/// without memory of its own (`crate::tiles`); it is not made here. +#[cfg(windows)] +pub(crate) fn host_tiled(this: This) -> Option { + if this.is_null() || !crate::tiles::wanted() { + return None; + } + hosted(this, false).map(|(host, _)| host).filter(|host| host.tiled.is_some()).map(OnDemand) +} + +/// The first level a view of title texture `this` may show, if its host +/// copy is made level by level and some level is held and has memory +/// (`crate::tiles::Tiled::first_shown`). +#[cfg(windows)] +pub(crate) fn first_shown(this: This) -> Option { + host_tiled(this)?.tiled()?.first_shown() +} + +/// A host copy made without memory of its own (`crate::tiles`), as a +/// submission-time step of a list holds it. +#[cfg(windows)] +pub(crate) struct OnDemand(std::sync::Arc); + +// SAFETY: the host texture is named only in queue calls, which any thread +// may make; what it has been given is behind a lock of its own. +#[cfg(windows)] +unsafe impl Send for OnDemand {} +// SAFETY: as above. +#[cfg(windows)] +unsafe impl Sync for OnDemand {} + +#[cfg(windows)] +impl OnDemand { + pub(crate) fn tiled(&self) -> Option<&crate::tiles::Tiled> { + self.0.tiled.as_ref() + } + + /// [`crate::tiles::Tiled::uploaded`]; `memory`: where the texture's + /// title memory starts (its slots are made again if the first level + /// they may show changed). + /// Held levels get tiles only while the card has room ([`room`]). + /// Returns whether a level is still without its tiles: the caller + /// records the upload again later. + pub(crate) fn uploaded(&self, held: u32, memory: u64) -> bool { + let Some(tiled) = &self.0.tiled else { + return false; + }; + let (changed, waiting) = tiled.uploaded(&self.0.texture, held, room()); + if changed { + crate::descriptor::host::levels_changed(memory); + } + if waiting { + crate::tiles::STATS[9].fetch_add(1, std::sync::atomic::Ordering::Relaxed); + } + waiting + } + + /// [`crate::tiles::Tiled::card_wrote`]; `memory` as above. + pub(crate) fn card_wrote(&self, levels: u32, memory: u64) { + if let Some(tiled) = &self.0.tiled + && tiled.card_wrote(&self.0.texture, levels) + { + crate::descriptor::host::levels_changed(memory); + } + } +} + +/// A texture's console memory and description; `None` for buffers. +pub(crate) fn texture_memory(this: This) -> Option<(*const u8, ResourceDesc)> { + if this.is_null() { + return None; + } + let r = resource(this); + (r.desc.dimension != BUFFER).then(|| (r.data().cast_const(), r.desc)) +} + +/// A buffer's host memory and size; `None` for textures. +pub(crate) fn buffer_bytes(this: This) -> Option<(*mut u8, u64)> { + if this.is_null() { + return None; + } + let r = resource(this); + (r.desc.dimension == BUFFER).then(|| (r.data(), r.desc.width)) +} + +impl Resource { + fn data(&self) -> *mut u8 { + match self.backing { + Backing::Committed(ref memory) => memory.ptr.as_ptr(), + // SAFETY: placement checked the range lies inside the heap. + Backing::Placed { heap, offset } => unsafe { + (*heap.cast::()) + .memory + .ptr + .as_ptr() + .add(offset as usize) + }, + Backing::Address(at) => at, + } + } +} + +fn resource<'a>(this: This) -> &'a Resource { + // SAFETY: called from resource methods only. + unsafe { &*this.cast::() } +} + +// The creation methods' own arguments, passed on. +#[allow(clippy::too_many_arguments)] +fn hand_out_resource( + desc: ResourceDesc, + heap: HeapProperties, + heap_flags: u32, + backing: Backing, + state: u32, + clear: *const c_void, + iid: *const Iid, + out: *mut This, +) -> HRESULT { + #[cfg(not(windows))] + let _ = (state, clear); + let resource = Box::new(Resource { + object: Object::new(&RESOURCE_FUNCTIONS), + desc, + heap, + heap_flags, + backing, + #[cfg(windows)] + host: Hosted { + made: std::sync::Mutex::new(None), + state, + // SAFETY: the title passes a whole clear value (the format, + // then color or depth and stencil: 5 words) or null. + clear: (!clear.is_null()).then(|| unsafe { clear.cast::<[u32; 5]>().read_unaligned() }), + used: std::sync::atomic::AtomicU64::new(0), + refused: std::sync::atomic::AtomicBool::new(false), + gone: std::sync::atomic::AtomicBool::new(false), + placed: std::sync::atomic::AtomicBool::new(false), + }, + }); + // The host copy waits for the texture's first use ([`Hosted`]). + #[cfg(windows)] + if desc.dimension != BUFFER { + let at = std::ptr::from_ref::(&resource) as usize; + textures().insert(at); + if !fills(&desc) { + TARGETS_AT + .lock() + .unwrap_or_else(|e| e.into_inner()) + .insert(resource.data() as u64, at); + } + if !lazy() { + let _ = hosted(at as This, true); + } + } + #[cfg(windows)] + if desc.dimension == BUFFER { + let at = std::ptr::from_ref::(&resource) as usize; + crate::shadow::register(at, resource.data() as u64, desc.width); + } + object::hand_out(RESOURCE, resource, iid, &RESOURCE_IIDS, out) +} + +#[cfg(windows)] +impl Drop for Resource { + fn drop(&mut self) { + // Out of the table of textures first: the sweep looks at the ones + // in it, under its lock. + if self.desc.dimension != BUFFER { + textures().remove(&(std::ptr::from_ref::(self) as usize)); + if !fills(&self.desc) { + let mut targets = TARGETS_AT.lock().unwrap_or_else(|e| e.into_inner()); + let at = self.data() as u64; + if targets.get(&at) == Some(&(std::ptr::from_ref::(self) as usize)) { + targets.remove(&at); + } + } + } + let made = self + .host + .made + .get_mut() + .unwrap_or_else(|e| e.into_inner()) + .take(); + #[cfg(feature = "diagnostics")] + if made + .as_ref() + .is_some_and(|(h, _)| std::sync::Arc::strong_count(h) > 1) + { + // Before lists held their textures, this freed a texture that + // lists not yet run still named (a GPU page fault). + static OUTLIVED: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + let n = OUTLIVED.fetch_add(1, std::sync::atomic::Ordering::Relaxed) + 1; + if n.is_power_of_two() { + tracing::info!( + n, + desc = ?self.desc, + "a title texture was released while a list not yet reset names its host copy" + ); + } + } + // A running submission may still read the host copy (and a depth + // texture's colour twin). + if let Some((host, twin)) = made { + crate::host::retire(host); + if let Some(twin) = twin { + crate::host::retire(twin); + } + } + crate::texture::forget(std::ptr::from_ref::(self) as usize); + crate::descriptor::forget(std::ptr::from_ref::(self) as usize); + if self.desc.dimension == BUFFER { + crate::shadow::unregister( + std::ptr::from_ref::(self) as usize, + self.data() as u64, + ); + } + } +} + +pub(crate) extern "system" fn create_committed( + _: This, + heap: *const HeapProperties, + heap_flags: u32, + desc: *const ResourceDesc, + state: u32, + clear: *const c_void, + iid: *const Iid, + out: *mut This, +) -> HRESULT { + // SAFETY: the title passes both descriptions (null is tolerated). + let (Some(&heap), Some(&desc)) = (unsafe { (heap.as_ref(), desc.as_ref()) }) else { + return E_INVALIDARG; + }; + let Some(info) = footprint(&desc) else { + tracing::warn!(?desc, "no size for this resource"); + return E_INVALIDARG; + }; + tracing::debug!( + dimension = desc.dimension, + size = info.size, + heap = heap.kind, + "committed resource" + ); + let memory = match Memory::for_resource(info, heap.kind) { + Ok(memory) => memory, + Err(hr) => return hr, + }; + hand_out_resource( + desc, + heap, + heap_flags, + Backing::Committed(memory), + state, + clear, + iid, + out, + ) +} + +/// Device method 0x3f8, inferred from the title's calls +/// (title+0x193e1b4: its back buffers, heap flag "allow display"): the +/// committed resource creation of the enhanced-barrier interfaces, +/// `(heap, heap flags, desc1, initial layout, clear value, protected +/// session, castable format count, castable formats, iid, out)`. The host +/// copy starts in the common state, as layouts are not tracked. +#[allow(clippy::too_many_arguments)] // the method's own arguments +pub(crate) extern "system" fn create_committed3( + this: This, + heap: *const HeapProperties, + heap_flags: u32, + desc: *const ResourceDesc, + _layout: u32, + clear: *const c_void, + _protected: This, + _castable_count: u32, + _castable: *const u32, + iid: *const Iid, + out: *mut This, +) -> HRESULT { + const COMMON: u32 = 0; + create_committed(this, heap, heap_flags, desc, COMMON, clear, iid, out) +} + +/// Registered page pools (64 KiB pages the title maps into tiled +/// resources by page index): first address and page count; a handle is an +/// index plus one, a removed pool leaves `None`. +static PAGE_POOLS: std::sync::Mutex>> = std::sync::Mutex::new(Vec::new()); + +fn page_pools() -> std::sync::MutexGuard<'static, Vec>> { + PAGE_POOLS.lock().unwrap_or_else(|e| e.into_inner()) +} + +/// Device method 0x250: `(address, page count, handle out)`. +pub(crate) extern "system" fn register_page_pool( + _: This, + address: u64, + pages: u32, + out: *mut usize, +) -> HRESULT { + if out.is_null() || pages == 0 || !address.is_multiple_of(KIB_64) { + return E_INVALIDARG; + } + tracing::debug!(address = format_args!("{address:#x}"), pages, "page pool"); + let mut pools = page_pools(); + pools.push(Some((address, pages))); + // SAFETY: checked non-null; the title passes room for a handle. + unsafe { out.write(pools.len()) }; + S_OK +} + +/// Device method 0x258. +pub(crate) extern "system" fn unregister_page_pool(_: This, handle: usize) -> HRESULT { + match page_pools().get_mut(handle.wrapping_sub(1)) { + Some(pool @ Some(_)) => { + *pool = None; + S_OK + } + _ => E_INVALIDARG, + } +} + +/// Device method 0x428, one of the `ID3D12Device9` to `ID3D12Device11` +/// additions. From the title's call: a resource at a virtual +/// address the title mapped itself, `(address, desc1, initial barrier +/// layout, clear value, iid, out)`, as `CreatePlacedResourceX` with +/// enhanced barriers. GPU addresses are CPU addresses, so the resource is +/// a view of that memory. `D3D12_RESOURCE_DESC1` starts like the plain +/// description; its sampler feedback region is not needed. +pub(crate) extern "system" fn create_at_address( + _: This, + address: u64, + desc: *const ResourceDesc, + layout: u32, + clear: *const c_void, + iid: *const Iid, + out: *mut This, +) -> HRESULT { + // SAFETY: the title passes a description (null is tolerated). + let Some(&desc) = (unsafe { desc.as_ref() }) else { + return E_INVALIDARG; + }; + if address == 0 { + return E_INVALIDARG; + } + tracing::debug!( + address = format_args!("{address:#x}"), + dimension = desc.dimension, + width = desc.width, + layout, + "resource at an address" + ); + const COMMON: u32 = 0; + const DEFAULT: HeapProperties = HeapProperties { + kind: 1, + cpu_pages: 0, + pool: 0, + creation_nodes: 1, + visible_nodes: 1, + }; + hand_out_resource( + desc, + DEFAULT, + 0, + Backing::Address(address as *mut u8), + COMMON, + clear, + iid, + out, + ) +} + +/// Textures the title placed in its own memory and views without a +/// resource object (device 0x230, the title's streamed and +/// interface textures), by address and description: a resource at that +/// address, made the first time a draw reads one. +/// The resource is kept for the run (views and lists name its address); +/// its host texture is let go when nothing names it any more +/// ([`let_go_idle`]) and made again on the next use. +#[cfg(windows)] +static PLACED_TEXTURES: std::sync::Mutex> = + std::sync::Mutex::new(std::collections::BTreeMap::new()); + +/// The placed textures asked for with filler words set, as asked +/// (address and description): for [`PLACED_TWINS`]. +#[cfg(windows)] +static PLACED_RAW: std::sync::Mutex> = + std::sync::Mutex::new(std::collections::BTreeSet::new()); + +/// Placed textures asked for a second time with other filler words in +/// their description: each was a second resource and host copy before the +/// filler was left out of the key ([`texture_at`]). +#[cfg(windows)] +static PLACED_TWINS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + +/// See [`PLACED_TWINS`]. +#[cfg(windows)] +pub(crate) fn placed_filler_twins() -> u64 { + PLACED_TWINS.load(std::sync::atomic::Ordering::Relaxed) +} + +/// The bytes of title memory a texture with the resource description +/// `desc` (as words) takes where the title placed it; `None` for a buffer +/// and for a description without a size. +#[cfg(windows)] +pub(crate) fn placed_bytes(desc: &[u32; 14]) -> Option { + // SAFETY: 56 bytes in the description's layout. + let d = unsafe { desc.as_ptr().cast::().read_unaligned() }; + if d.dimension == BUFFER { + return None; + } + footprint(&d).map(|f| f.size) +} + +/// The resource [`texture_at`] made for a texture placed at `address` with +/// the description `desc`, if it has made one: never made here (for the +/// frame listing, which must not count as a use). +#[cfg(all(windows, feature = "diagnostics"))] +pub(crate) fn texture_at_made(address: u64, desc: &[u32; 14]) -> Option { + let mut key = *desc; + key[1] = 0; + key[13] = 0; + let map = PLACED_TEXTURES.lock().unwrap_or_else(|e| e.into_inner()); + let found = map.get(&(address, key)).or_else(|| map.get(&(address, *desc)))?; + Some(*found as This) +} + +/// The resource for a texture placed at `address` with the resource +/// description `desc` (as words), made on first use. +#[cfg(windows)] +pub(crate) fn texture_at(address: u64, desc: &[u32; 14]) -> Option { + // Words 1 and 13 of the description are the filler of its layout + // (after the dimension, and at the end): the title leaves there what + // its stack held, and two views of one texture that differed only in + // them each got a resource and a host copy of their own, on a card + // that fills at world entry. They are not part of what a texture is. + // `LEONIDA_PLACED_FILLER=1`: kept in the key, as before. + static KEPT: std::sync::OnceLock = std::sync::OnceLock::new(); + let raw = *desc; + let mut key = *desc; + if !*KEPT.get_or_init(|| std::env::var_os("LEONIDA_PLACED_FILLER").is_some_and(|v| v == "1")) { + key[1] = 0; + key[13] = 0; + } + let desc = &key; + let mut map = PLACED_TEXTURES.lock().unwrap_or_else(|e| e.into_inner()); + // How many resources the filler alone would have added (a count for + // the log: `placed_filler_twins`). + if raw != key { + let mut seen = PLACED_RAW.lock().unwrap_or_else(|e| e.into_inner()); + if seen.insert((address, raw)) { + let others = seen.range((address, [0; 14])..=(address, [u32::MAX; 14])).filter(|(_, r)| { + let mut blank = *r; + blank[1] = 0; + blank[13] = 0; + blank == key + }); + if others.count() > 1 { + PLACED_TWINS.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + } + } + } + if let Some(&r) = map.get(&(address, *desc)) { + return Some(r as This); + } + // SAFETY: 56 bytes in the description's layout. + let d = unsafe { desc.as_ptr().cast::().read_unaligned() }; + if d.dimension == BUFFER { + return None; + } + let mut out = std::ptr::null(); + let made = create_at_address( + std::ptr::null(), + address, + &d, + 0, + std::ptr::null(), + &RESOURCE_IIDS[0], + &mut out, + ); + if made != S_OK { + return None; + } + map.insert((address, *desc), out as usize); + crate::texture::placed_in_host_written(address, desc); + resource(out) + .host + .placed + .store(true, std::sync::atomic::Ordering::Relaxed); + Some(out) +} + +pub(crate) extern "system" fn create_placed( + _: This, + heap: This, + offset: u64, + desc: *const ResourceDesc, + state: u32, + clear: *const c_void, + iid: *const Iid, + out: *mut This, +) -> HRESULT { + // SAFETY: the title passes a description (null is tolerated). + let Some(&desc) = (unsafe { desc.as_ref() }) else { + return E_INVALIDARG; + }; + if heap.is_null() { + return E_INVALIDARG; + } + // SAFETY: the title passes one of our heaps. + let h = unsafe { &*heap.cast::() }; + let fits = footprint(&desc).is_some_and(|info| { + offset.is_multiple_of(info.alignment) + && offset + .checked_add(info.size) + .is_some_and(|end| end <= h.desc.size) + }); + if !fits { + tracing::warn!( + ?desc, + offset, + heap = h.desc.size, + "placed resource does not fit" + ); + return E_INVALIDARG; + } + object::add_ref(heap); + let backing = Backing::Placed { heap, offset }; + hand_out_resource( + desc, + h.desc.properties, + h.desc.flags, + backing, + state, + clear, + iid, + out, + ) +} + +extern "system" fn resource_query(this: This, iid: *const Iid, out: *mut This) -> HRESULT { + object::answer( + RESOURCE, + iid, + object::is(iid, &RESOURCE_IIDS).then_some(this), + out, + ) +} +extern "system" fn resource_release(this: This) -> u32 { + object::release_boxed::(this) +} +/// Memory is always mapped (subresources are not told apart yet); a null +/// `out` only asks for residency. +extern "system" fn map(this: This, _sub: u32, _read: *const c_void, out: *mut *mut u8) -> HRESULT { + if !out.is_null() { + // SAFETY: checked non-null; the title passes room for a pointer. + unsafe { out.write(resource(this).data()) }; + } + S_OK +} +extern "system" fn unmap(_: This, _sub: u32, _written: *const c_void) {} +extern "system" fn resource_desc(this: This, out: *mut ResourceDesc) { + if !out.is_null() { + // SAFETY: checked non-null; the title passes room for a description. + unsafe { out.write(resource(this).desc) }; + } +} +/// Device method `GetCustomHeapProperties`, returning its struct through a +/// hidden first argument: what a standard heap type is as a custom heap. +/// Memory is unified and cache-coherent (as the architecture query says), +/// so every type is in pool L0, default heaps are not CPU-visible and the +/// others are write-back. +pub(crate) extern "system" fn custom_heap_properties( + out: *mut HeapProperties, + _: This, + nodes: u32, + kind: u32, +) -> *mut HeapProperties { + const CUSTOM: u32 = 4; + const NOT_AVAILABLE: u32 = 1; + const WRITE_BACK: u32 = 3; + const L0: u32 = 1; + let nodes = nodes.max(1); + let cpu_pages = match kind { + 1 => NOT_AVAILABLE, + 2 | 3 => WRITE_BACK, + _ => 0, + }; + let properties = HeapProperties { + kind: CUSTOM, + cpu_pages, + pool: if cpu_pages == 0 { 0 } else { L0 }, + creation_nodes: nodes, + visible_nodes: nodes, + }; + // SAFETY: the title passes room for the result (null is tolerated). + if let Some(out) = unsafe { out.as_mut() } { + *out = properties; + } + out +} + +extern "system" fn gpu_address(this: This) -> u64 { + let r = resource(this); + let at = r.data() as u64; + // The console's GPU addresses fit in 40 bits; its ray-tracing builder + // refuses others (diagnostics: which memory breaks that). + #[cfg(feature = "diagnostics")] + if at >> 40 != 0 { + static ONCE: [std::sync::Once; 2] = [std::sync::Once::new(), std::sync::Once::new()]; + let backing = match r.backing { + Backing::Committed(ref m) => format!("committed, attributes {:?}", m.attributes), + Backing::Placed { offset, .. } => format!("placed in a heap at {offset:#x}"), + Backing::Address(_) => "at a title address".into(), + }; + ONCE[usize::from(r.desc.dimension == BUFFER)].call_once(|| { + tracing::warn!(address = format_args!("{at:#x}"), backing, desc = ?r.desc, "a GPU address above 40 bits") + }); + } + at +} +extern "system" fn heap_properties( + this: This, + properties: *mut HeapProperties, + flags: *mut u32, +) -> HRESULT { + let r = resource(this); + // SAFETY: either pointer may be null; otherwise the title passes room. + unsafe { + if let Some(p) = properties.as_mut() { + *p = r.heap; + } + if let Some(f) = flags.as_mut() { + *f = r.heap_flags; + } + } + S_OK +} + +/// IUnknown 3, object 4, device child 1, heap 1. +static HEAP_FUNCTIONS: Table<24> = { + let mut f = object::d3d12_object(object::missing_table::()); + f[0] = heap_query as *const (); + f[2] = heap_release as *const (); + f[7] = object::parent_device as *const (); // 0x38 + f[8] = heap_desc as *const (); // 0x40 + Table(f) +}; + +/// IUnknown 3, object 4, device child 1, resource 10 (7 as on PC, then 3 +/// console ones). +static RESOURCE_FUNCTIONS: Table<32> = { + let mut f = object::d3d12_object(object::missing_table::()); + f[0] = resource_query as *const (); + f[2] = resource_release as *const (); + f[7] = object::parent_device as *const (); // 0x38 + f[8] = map as *const (); // 0x40 + f[9] = unmap as *const (); // 0x48 + f[10] = resource_desc as *const (); // 0x50 + f[11] = gpu_address as *const (); // 0x58 + f[14] = heap_properties as *const (); // 0x70 + Table(f) +}; + +#[cfg(test)] +mod tests { + use super::*; + use crate::object::slot; + + type Release = extern "system" fn(This) -> u32; + type Map = extern "system" fn(This, u32, *const c_void, *mut *mut u8) -> HRESULT; + type Address = extern "system" fn(This) -> u64; + + const PROPERTIES: HeapProperties = HeapProperties { + kind: 1, + cpu_pages: 0, + pool: 0, + creation_nodes: 0, + visible_nodes: 0, + }; + + fn buffer(width: u64) -> ResourceDesc { + ResourceDesc { + dimension: BUFFER, + alignment: 0, + width, + height: 1, + depth_or_array_size: 1, + mip_levels: 1, + format: 0, + sample_count: 1, + sample_quality: 0, + layout: 1, + flags: 0, + } + } + + fn texture(width: u64, height: u32, format: u32, mips: u16) -> ResourceDesc { + ResourceDesc { + dimension: 3, + width, + height, + format, + mip_levels: mips, + layout: 0, + ..buffer(0) + } + } + + fn heap(size: u64) -> This { + let desc = HeapDesc { + size, + properties: PROPERTIES, + alignment: 0, + flags: 0, + }; + let mut heap = std::ptr::null(); + assert_eq!( + create_heap(std::ptr::null(), &desc, &HEAP_IIDS[0], &mut heap), + S_OK + ); + heap + } + + #[test] + fn heaps_are_zeroed_aligned_memory() { + let heap = heap(1 << 20); + // SAFETY: a heap we just made. + let memory = unsafe { &(*heap.cast::()).memory }; + assert_eq!(memory.ptr.as_ptr() as u64 % KIB_64, 0); + let mut back = std::mem::MaybeUninit::::uninit(); + slot::(heap, 0x40)(heap, back.as_mut_ptr()); + // SAFETY: written above. + assert_eq!(unsafe { back.assume_init() }.size, 1 << 20); + assert_eq!(slot::(heap, 0x10)(heap), 0); + + let bad = HeapDesc { + size: 1 << 20, + properties: PROPERTIES, + alignment: 3, + flags: 0, + }; + let mut out = std::ptr::null(); + assert_eq!( + create_heap(std::ptr::null(), &bad, &HEAP_IIDS[0], &mut out), + E_INVALIDARG + ); + } + + #[test] + fn device_setup_heap_properties_and_resources_at_addresses() { + let device = crate::device::device(); + // GetCustomHeapProperties (0xd0): the struct comes back through the + // hidden first argument, which is also returned. + type Custom = + extern "system" fn(*mut HeapProperties, This, u32, u32) -> *mut HeapProperties; + let mut p = PROPERTIES; + let back = slot::(device, 0xd0)(&mut p, device, 1, 2); + assert_eq!(back, &raw mut p); + assert_eq!( + ( + p.kind, + p.cpu_pages, + p.pool, + p.creation_nodes, + p.visible_nodes + ), + (4, 3, 1, 1, 1), + "upload: custom, write-back, L0" + ); + slot::(device, 0xd0)(&mut p, device, 1, 1); + assert_eq!(p.cpu_pages, 1, "default: not CPU-visible"); + + // 0x428: a buffer over memory the title owns, as the title asks. + type At = extern "system" fn( + This, + u64, + *const ResourceDesc, + u32, + *const c_void, + *const Iid, + *mut This, + ) -> HRESULT; + let memory = vec![0u8; 0x1_0000]; + let address = memory.as_ptr() as u64; + let mut r = std::ptr::null(); + let create = slot::(device, 0x428); + let desc = buffer(0x1_0000); + let null = std::ptr::null(); + assert_eq!( + create( + device, + address, + &desc, + u32::MAX, + null, + &RESOURCE_IIDS[0], + &mut r + ), + 0 + ); + assert_eq!(slot::
(r, 0x58)(r), address); + assert_eq!(slot::(r, 0x10)(r), 0); + // The title's memory is still there after the release. + assert_eq!(memory[0xffff], 0); + assert_ne!( + create(device, 0, &desc, u32::MAX, null, &RESOURCE_IIDS[0], &mut r), + 0 + ); + } + + #[test] + fn sizes_cover_every_mip() { + let size = |d: &ResourceDesc| footprint(d).map(|i| i.size); + assert_eq!(size(&buffer(256)), Some(KIB_64)); + // Textures take their console layout and its alignment (4 KiB + // standard swizzle when the description leaves it to the library): + // 512x512 BC7 with 10 mips is 0x56000 bytes, 4 KiB aligned, as on + // the console. + let layout = |d: &ResourceDesc| texture_layout(d).unwrap().size; + let rgba = texture(256, 256, 28, 0); + assert_eq!(size(&rgba), Some(layout(&rgba).next_multiple_of(4096))); + let bc7 = footprint(&texture(512, 512, 98, 10)); + let console = AllocationInfo { + size: 0x56000, + alignment: 0x1000, + }; + assert_eq!(bc7, Some(console)); + assert!(layout(&rgba) >= 4 * (256 * 256 * 4) / 3, "every mip"); + // BC1 is 8 bytes per 4x4 block: 1024x1024, one mip = 512 KiB. + assert_eq!(size(&texture(1024, 1024, 71, 1)), Some(512 << 10)); + assert_eq!(size(&texture(16, 16, 66, 1)), None, "1-bit format"); + // Linear layout (1) and an explicit mode (64 KiB display, 0x10a). + let linear = ResourceDesc { + layout: 1, + ..texture(100, 60, 28, 1) + }; + assert_eq!( + texture_layout(&linear).unwrap().planes[0] + .layout + .desc + .swizzle + .0, + 0 + ); + let display = ResourceDesc { + layout: 0x10a, + ..texture(100, 60, 28, 1) + }; + assert_eq!( + texture_layout(&display).unwrap().planes[0] + .layout + .desc + .swizzle + .0, + 10 + ); + + let mut info = AllocationInfo { + size: 0, + alignment: 0, + }; + let descs = [buffer(100), texture(256, 256, 28, 0)]; + allocation_info(&mut info, std::ptr::null(), 0, 2, descs.as_ptr()); + assert_eq!( + info, + AllocationInfo { + size: KIB_64 + size(&descs[1]).unwrap(), + alignment: KIB_64 + } + ); + allocation_info(&mut info, std::ptr::null(), 0, 1, &texture(1, 1, 999, 1)); + assert_eq!(info.size, u64::MAX); + } + + #[test] + fn upload_footprints_follow_the_pc_rules() { + let null = std::ptr::null(); + let mut layouts = [NO_FOOTPRINT; 2]; + let (mut rows, mut sizes, mut total) = ([0; 2], [0; 2], 0); + let mut footprints = |desc: &ResourceDesc, first, count| { + let (l, r, s) = (layouts.as_mut_ptr(), rows.as_mut_ptr(), sizes.as_mut_ptr()); + copyable_footprints(null, desc, first, count, 0, l, r, s, &mut total); + (layouts, rows, sizes, total) + }; + // 100x60 RGBA8, 2 mips: 400-byte rows pitched to 512. + let (l, r, s, t) = footprints(&texture(100, 60, 28, 2), 0, 2); + assert_eq!((l[0].row_pitch, r[0], s[0]), (512, 60, 400)); + // Mip 1 (50x30, 200-byte rows) starts after 59 pitched rows and one + // packed row, rounded up to 512. + assert_eq!(l[1].offset, (512 * 59 + 400u64).next_multiple_of(512)); + assert_eq!((l[1].width, l[1].height, r[1]), (50, 30, 30)); + assert_eq!(t, l[1].offset + 256 * 29 + 200); + // BC1: rows of 4x4 blocks, 8 bytes each. + let (_, r, s, _) = footprints(&texture(64, 64, 71, 1), 0, 1); + assert_eq!((r[0], s[0]), (16, 128)); + let (_, _, _, t) = footprints(&texture(64, 64, 71, 1), 1, 1); + assert_eq!(t, u64::MAX, "no second subresource"); + } + + /// A 4x4 texture filled from a title buffer through our list and queue, + /// then read back from the host GPU. + #[cfg(windows)] + #[test] + fn buffer_data_reaches_the_host_texture() { + use windows::Win32::Graphics::Direct3D12::*; + let Some(host) = crate::host::host() else { + return; // no host GPU here + }; + let null = std::ptr::null(); + let iid = &RESOURCE_IIDS[0]; + const COPY_DEST: u32 = 0x400; + let (mut image, mut source) = (null, null); + let rgba = texture(4, 4, 28, 1); + assert_eq!( + create_committed( + null, + &PROPERTIES, + 0, + &rgba, + COPY_DEST, + null.cast(), + iid, + &mut image + ), + S_OK + ); + assert_eq!( + create_committed( + null, + &PROPERTIES, + 0, + &buffer(1024), + 0, + null.cast(), + iid, + &mut source + ), + S_OK + ); + let (data, _) = buffer_bytes(source).unwrap(); + // SAFETY: the buffer holds 1024 bytes. + let bytes = unsafe { std::slice::from_raw_parts_mut(data, 1024) }; + for (i, b) in bytes.iter_mut().enumerate() { + *b = (i % 251) as u8; + } + + let queue_iid = guid( + 0x0ec870a6, + 0x5d7e, + 0x4c22, + [0x8c, 0xfc, 0x5b, 0xaa, 0xe0, 0x76, 0x16, 0xed], + ); + let allocator_iid = guid( + 0x6102dee4, + 0xaf59, + 0x4b09, + [0xb9, 0x99, 0xb4, 0x4d, 0x73, 0xf0, 0x9b, 0x24], + ); + let list_iid = guid( + 0x5b160d0f, + 0xac1b, + 0x4185, + [0x8b, 0xa8, 0xb3, 0xae, 0x42, 0xa5, 0xa4, 0x55], + ); + let (mut queue, mut allocator, mut list) = (null, null, null); + let queue_desc = [0u32; 4]; + assert_eq!( + crate::queue::create(null, queue_desc.as_ptr().cast(), &queue_iid, &mut queue), + S_OK + ); + assert_eq!( + crate::list::create_allocator(null, 0, &allocator_iid, &mut allocator), + S_OK + ); + assert_eq!( + crate::list::create_list(null, 0, 0, allocator, null, &list_iid, &mut list), + S_OK + ); + + #[repr(C)] + struct Location { + resource: This, + kind: u32, + footprint: PlacedFootprint, + } + let rows = PlacedFootprint { + offset: 0, + format: 28, + width: 4, + height: 4, + depth: 1, + row_pitch: 256, + }; + let to = Location { + resource: image, + kind: 0, + footprint: PlacedFootprint { offset: 0, ..rows }, + }; + let from = Location { + resource: source, + kind: 1, + footprint: rows, + }; + type Copy = + extern "system" fn(This, *const Location, u32, u32, u32, *const Location, *const u8); + slot::(list, 0x80)(list, &to, 0, 0, 0, &from, null.cast()); + slot:: HRESULT>(list, 0x48)(list); + slot::(queue, 0x50)(queue, 1, &list); + + // Read the host texture back into a readback buffer. + let readback_heap = D3D12_HEAP_PROPERTIES { + Type: D3D12_HEAP_TYPE_READBACK, + ..Default::default() + }; + let readback_desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, + Width: 1024, + Height: 1, + DepthOrArraySize: 1, + MipLevels: 1, + SampleDesc: windows::Win32::Graphics::Dxgi::Common::DXGI_SAMPLE_DESC { + Count: 1, + Quality: 0, + }, + Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, + ..Default::default() + }; + let mut readback: Option = None; + // SAFETY: plain creation of a readback buffer. + unsafe { + host.device + .CreateCommittedResource( + &readback_heap, + D3D12_HEAP_FLAG_NONE, + &readback_desc, + D3D12_RESOURCE_STATE_COPY_DEST, + None, + &mut readback, + ) + .unwrap(); + } + let readback = readback.unwrap(); + let host_image = host_resource(image).unwrap(); + let back = host.new_list().unwrap(); + let (_, before) = host_transition(image, 0x800).unwrap(); + // The upload list holds the texture until it is reset. + assert!(std::sync::Arc::strong_count(&host_copy(image).unwrap()) > 2); + use windows::core::Interface; + let out_to = Location { + resource: readback.as_raw().cast_const().cast(), + kind: 1, + footprint: rows, + }; + let out_from = Location { + resource: host_image.as_raw().cast_const().cast(), + kind: 0, + footprint: to.footprint, + }; + // SAFETY: an open list, live resources, locations in the host layout. + unsafe { + back.list.ResourceBarrier(&[crate::host::transition( + host_image, + D3D12_RESOURCE_STATES(before as i32), + D3D12_RESOURCE_STATE_COPY_SOURCE, + )]); + back.list.CopyTextureRegion( + (&raw const out_to).cast(), + 0, + 0, + 0, + (&raw const out_from).cast(), + None, + ); + } + back.close(); + host.execute(&[&back]); + let mut mapped = std::ptr::null_mut(); + // SAFETY: the copy finished (execute waits); the buffer is 1024 bytes. + let read = unsafe { + readback + .Map( + 0, + Some(&D3D12_RANGE { + Begin: 0, + End: 1024, + }), + Some(&mut mapped), + ) + .unwrap(); + std::slice::from_raw_parts(mapped.cast::(), 1024) + }; + for row in 0..4 { + let at = row * 256; + assert_eq!(read[at..at + 16], bytes[at..at + 16], "row {row}"); + } + } + + /// A 16-bit depth texture the title also asks unordered access for gets + /// a colour twin, and the host copies one into the other, both ways: a + /// pattern put into the twin is copied to the depth texture, the twin + /// is overwritten with zeros, and the pattern comes back from the depth + /// texture. A copy the host does not allow ends the test (with the + /// debug layer's message under `LEONIDA_D3D12_DEBUG=1` in a diagnostics + /// build). + #[cfg(windows)] + #[test] + fn a_depth_texture_and_its_twin_copy_into_each_other() { + use windows::Win32::Graphics::Direct3D12::*; + use windows::Win32::Graphics::Dxgi::Common::{DXGI_FORMAT, DXGI_SAMPLE_DESC}; + let Some(host) = crate::host::host() else { + return; // no host GPU here + }; + let null = std::ptr::null(); + const DEPTH_WRITE: u32 = 0x10; + let desc = ResourceDesc { + flags: 6, + ..texture(4, 4, 55, 1) + }; + let mut depth = null; + assert_eq!( + create_committed( + null, + &PROPERTIES, + 0, + &desc, + DEPTH_WRITE, + null.cast(), + &RESOURCE_IIDS[0], + &mut depth + ), + S_OK + ); + let host_depth = host_resource(depth).unwrap(); + let Some(twin) = twin_resource(depth) else { + return; // twins are turned off + }; + // SAFETY: live resources. + let (d, t) = unsafe { (host_depth.GetDesc(), twin.GetDesc()) }; + // Both R16 typeless: one a depth texture, one with unordered access. + assert_eq!((d.Format.0, d.Flags.0), (53, 2)); + assert_eq!((t.Format.0, t.Flags.0), (53, 4)); + + // Four rows of four 16-bit texels, 256 bytes apart as copies place + // them: the pattern, then as many zeros. + let mut pattern = vec![0u8; 1024]; + for row in 0..4 { + for b in 0..8 { + pattern[row * 256 + b] = (1 + row * 8 + b) as u8; + } + } + let (upload, data) = host.upload_buffer(2048).unwrap(); + // SAFETY: the buffer's mapping, 2048 bytes. + unsafe { + std::ptr::copy_nonoverlapping(pattern.as_ptr(), data, 1024); + std::ptr::write_bytes(data.add(1024), 0, 1024); + } + let readback_heap = D3D12_HEAP_PROPERTIES { + Type: D3D12_HEAP_TYPE_READBACK, + ..Default::default() + }; + let readback_desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, + Width: 1024, + Height: 1, + DepthOrArraySize: 1, + MipLevels: 1, + SampleDesc: DXGI_SAMPLE_DESC { + Count: 1, + Quality: 0, + }, + Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, + ..Default::default() + }; + let mut readback: Option = None; + // SAFETY: plain creation of a readback buffer. + unsafe { + host.device + .CreateCommittedResource( + &readback_heap, + D3D12_HEAP_FLAG_NONE, + &readback_desc, + D3D12_RESOURCE_STATE_COPY_DEST, + None, + &mut readback, + ) + .unwrap(); + } + let readback = readback.unwrap(); + + // A texture's one subresource; the four rows of a buffer at `offset`. + let whole = |texture: &ID3D12Resource| D3D12_TEXTURE_COPY_LOCATION { + // SAFETY: a borrowed pointer the location never releases. + pResource: unsafe { std::mem::transmute_copy(texture) }, + Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, + Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { + SubresourceIndex: 0, + }, + }; + let rows = |buffer: &ID3D12Resource, offset: u64| D3D12_TEXTURE_COPY_LOCATION { + // SAFETY: as above. + pResource: unsafe { std::mem::transmute_copy(buffer) }, + Type: D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT, + Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { + PlacedFootprint: D3D12_PLACED_SUBRESOURCE_FOOTPRINT { + Offset: offset, + Footprint: D3D12_SUBRESOURCE_FOOTPRINT { + Format: DXGI_FORMAT(53), + Width: 4, + Height: 4, + Depth: 1, + RowPitch: 256, + }, + }, + }, + }; + let (written, tested, source, dest) = ( + D3D12_RESOURCE_STATE_UNORDERED_ACCESS, + D3D12_RESOURCE_STATE_DEPTH_WRITE, + D3D12_RESOURCE_STATE_COPY_SOURCE, + D3D12_RESOURCE_STATE_COPY_DEST, + ); + let moved = crate::host::transition; + let list = host.new_list().unwrap(); + // SAFETY: an open list and live resources; the two textures are one + // size in one format family. + unsafe { + let l = &list.list; + // The pattern into the twin, the twin into the depth texture. + l.ResourceBarrier(&[moved(twin, written, dest), moved(host_depth, tested, dest)]); + l.CopyTextureRegion(&whole(twin), 0, 0, 0, &rows(&upload, 0), None); + l.ResourceBarrier(&[moved(twin, dest, source)]); + l.CopyResource(host_depth, twin); + // Zeros over the twin, then the depth texture back into it. + l.ResourceBarrier(&[moved(twin, source, dest)]); + l.CopyTextureRegion(&whole(twin), 0, 0, 0, &rows(&upload, 1024), None); + l.ResourceBarrier(&[moved(host_depth, dest, source)]); + l.CopyResource(twin, host_depth); + // The twin read back; both textures to the states they had. + l.ResourceBarrier(&[moved(twin, dest, source)]); + l.CopyTextureRegion(&rows(&readback, 0), 0, 0, 0, &whole(twin), None); + l.ResourceBarrier(&[ + moved(twin, source, written), + moved(host_depth, source, tested), + ]); + } + list.close(); + host.execute(&[&list]); + let mut mapped = std::ptr::null_mut(); + // SAFETY: the copies finished (execute waits); the buffer is 1024 bytes. + let read = unsafe { + readback + .Map( + 0, + Some(&D3D12_RANGE { + Begin: 0, + End: 1024, + }), + Some(&mut mapped), + ) + .unwrap(); + std::slice::from_raw_parts(mapped.cast::(), 1024) + }; + for row in 0..4 { + let at = row * 256; + assert_eq!(read[at..at + 8], pattern[at..at + 8], "row {row}"); + } + } + + /// A depth texture with a stencil plane that the title also asks + /// unordered access for gets a twin of the stencil plane, and what + /// shaders write there is in the stencil plane once the list is closed: + /// a pattern put into the twin is read back from the plane. + #[cfg(windows)] + #[test] + fn a_stencil_planes_twin_reaches_the_plane() { + use std::sync::atomic::Ordering::Relaxed; + use windows::Win32::Graphics::Direct3D12::*; + use windows::Win32::Graphics::Dxgi::Common::{DXGI_FORMAT, DXGI_SAMPLE_DESC}; + let Some(host) = crate::host::host() else { + return; // no host GPU here + }; + let null = std::ptr::null(); + const DEPTH_WRITE: u32 = 0x10; + let desc = ResourceDesc { + flags: 6, + ..texture(4, 4, 45, 1) + }; + let mut depth = null; + assert_eq!( + create_committed( + null, + &PROPERTIES, + 0, + &desc, + DEPTH_WRITE, + null.cast(), + &RESOURCE_IIDS[0], + &mut depth + ), + S_OK + ); + let host_depth = host_resource(depth).unwrap(); + let Some(twin) = twin_resource(depth) else { + return; // twins are turned off + }; + // SAFETY: live resources. + let (d, t) = unsafe { (host_depth.GetDesc(), twin.GetDesc()) }; + // R24G8 typeless with depth, R8 typeless with unordered access. + assert_eq!((d.Format.0, d.Flags.0), (44, 2)); + assert_eq!((t.Format.0, t.Flags.0), (60, 4)); + + // Four rows of four texels, 256 bytes apart as copies place them. + let mut pattern = vec![0u8; 1024]; + for row in 0..4 { + for b in 0..4 { + pattern[row * 256 + b] = (1 + row * 4 + b) as u8; + } + } + let (upload, data) = host.upload_buffer(1024).unwrap(); + // SAFETY: the buffer's mapping, 1024 bytes. + unsafe { std::ptr::copy_nonoverlapping(pattern.as_ptr(), data, 1024) }; + let readback_heap = D3D12_HEAP_PROPERTIES { + Type: D3D12_HEAP_TYPE_READBACK, + ..Default::default() + }; + let readback_desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, + // Room for the rows as the host places them (512 bytes apart + // for the stencil plane on NVIDIA, not 256). + Width: 4096, + Height: 1, + DepthOrArraySize: 1, + MipLevels: 1, + SampleDesc: DXGI_SAMPLE_DESC { + Count: 1, + Quality: 0, + }, + Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, + ..Default::default() + }; + let mut readback: Option = None; + // SAFETY: plain creation of a readback buffer. + unsafe { + host.device + .CreateCommittedResource( + &readback_heap, + D3D12_HEAP_FLAG_NONE, + &readback_desc, + D3D12_RESOURCE_STATE_COPY_DEST, + None, + &mut readback, + ) + .unwrap(); + } + let readback = readback.unwrap(); + // How the host lays the stencil plane (subresource 1) out in a buffer. + let mut plane = D3D12_PLACED_SUBRESOURCE_FOOTPRINT::default(); + // SAFETY: a plain query writing one footprint. + unsafe { + host.device + .GetCopyableFootprints(&d, 1, 1, 0, Some(&mut plane), None, None, None); + } + let pattern_rows = D3D12_PLACED_SUBRESOURCE_FOOTPRINT { + Offset: 0, + Footprint: D3D12_SUBRESOURCE_FOOTPRINT { + Format: DXGI_FORMAT(60), + Width: 4, + Height: 4, + Depth: 1, + RowPitch: 256, + }, + }; + + // A subresource of a texture; rows of a buffer. + let whole = |texture: &ID3D12Resource, index: u32| D3D12_TEXTURE_COPY_LOCATION { + // SAFETY: a borrowed pointer the location never releases. + pResource: unsafe { std::mem::transmute_copy(texture) }, + Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, + Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { + SubresourceIndex: index, + }, + }; + let rows = |buffer: &ID3D12Resource, placed: D3D12_PLACED_SUBRESOURCE_FOOTPRINT| { + D3D12_TEXTURE_COPY_LOCATION { + // SAFETY: as above. + pResource: unsafe { std::mem::transmute_copy(buffer) }, + Type: D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT, + Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { + PlacedFootprint: placed, + }, + } + }; + let (written, source, dest) = ( + D3D12_RESOURCE_STATE_UNORDERED_ACCESS, + D3D12_RESOURCE_STATE_COPY_SOURCE, + D3D12_RESOURCE_STATE_COPY_DEST, + ); + let moved = crate::host::transition; + + // The pattern into the twin, where a shader would write it. + let fill = host.new_list().unwrap(); + // SAFETY: an open list and live resources. + unsafe { + let l = &fill.list; + l.ResourceBarrier(&[moved(twin, written, dest)]); + l.CopyTextureRegion(&whole(twin, 0), 0, 0, 0, &rows(&upload, pattern_rows), None); + l.ResourceBarrier(&[moved(twin, dest, written)]); + } + fill.close(); + host.execute(&[&fill]); + + // A list in which a shader writes the twin: closing it copies the + // twin into the stencil plane. + let list = host.new_list().unwrap(); + assert!(list.twin_use(depth, true, true)); + list.twins_written(); + list.close(); + host.execute(&[&list]); + + // The stencil plane read back from the state the list left it in. + let state = host_copy(depth).unwrap().state.load(Relaxed); + let state = D3D12_RESOURCE_STATES(state as i32); + let back = host.new_list().unwrap(); + // SAFETY: an open list and live resources; a whole subresource. + unsafe { + let l = &back.list; + l.ResourceBarrier(&[moved(host_depth, state, source)]); + let (to, from) = (rows(&readback, plane), whole(host_depth, 1)); + l.CopyTextureRegion(&to, 0, 0, 0, &from, None); + l.ResourceBarrier(&[moved(host_depth, source, state)]); + } + back.close(); + host.execute(&[&back]); + let mut mapped = std::ptr::null_mut(); + // SAFETY: the copies finished (execute waits); the buffer is 4096 bytes. + let read = unsafe { + readback + .Map( + 0, + Some(&D3D12_RANGE { + Begin: 0, + End: 4096, + }), + Some(&mut mapped), + ) + .unwrap(); + std::slice::from_raw_parts(mapped.cast::(), 4096) + }; + let pitch = plane.Footprint.RowPitch as usize; + for row in 0..4 { + let (at, from) = (row * pitch, row * 256); + assert_eq!(read[at..at + 4], pattern[from..from + 4], "row {row}"); + } + } + + /// The depth plane of a depth-stencil texture is drawn from the plane's + /// twin when the list that wrote the twin closes: class numbers are put + /// into the twin of a texture in the console's 16-bit depth-stencil + /// format, and draws with the depth test "equal" at the depth the + /// title's lighting computes for a class (the number times the float + /// nearest 1/65535) then cover the texels of that class and no other. + #[cfg(windows)] + #[test] + fn a_depth_planes_twin_is_drawn_into_the_plane() { + use std::sync::atomic::Ordering::Relaxed; + use windows::Win32::Foundation::RECT; + use windows::Win32::Graphics::Direct3D::D3D_PRIMITIVE_TOPOLOGY; + use windows::Win32::Graphics::Direct3D12::*; + use windows::Win32::Graphics::Dxgi::Common::{DXGI_FORMAT, DXGI_SAMPLE_DESC}; + use windows::core::s; + let Some(host) = crate::host::host() else { + return; // no host GPU here + }; + let null = std::ptr::null(); + const DEPTH_WRITE: u32 = 0x10; + let desc = ResourceDesc { + flags: 6, + ..texture(4, 4, 118, 1) + }; + let mut depth = null; + assert_eq!( + create_committed( + null, + &PROPERTIES, + 0, + &desc, + DEPTH_WRITE, + null.cast(), + &RESOURCE_IIDS[0], + &mut depth + ), + S_OK + ); + let host_depth = host_resource(depth).unwrap(); + let Some(plane) = twin_plane_resource(depth) else { + return; // these twins are turned off + }; + // SAFETY: live resources. + let (d, t) = unsafe { (host_depth.GetDesc(), plane.GetDesc()) }; + // R24G8 typeless with depth, R16 typeless with unordered access. + assert_eq!((d.Format.0, d.Flags.0), (44, 2)); + assert_eq!((t.Format.0, t.Flags.0), (53, 4)); + + // Four rows of four class numbers (16 bits each), 256 bytes apart + // as copies place them. 128 and 129 are the classes whose 24-bit + // depth lies nearest a half step. + const CLASSES: [u16; 16] = [ + 8, 65, 128, 129, 65, 8, 129, 128, 0, 255, 65, 64, 129, 130, 8, 65, + ]; + let mut pattern = vec![0u8; 1024]; + for (i, class) in CLASSES.into_iter().enumerate() { + let at = i / 4 * 256 + i % 4 * 2; + pattern[at..at + 2].copy_from_slice(&class.to_le_bytes()); + } + let (upload, data) = host.upload_buffer(1024).unwrap(); + // SAFETY: the buffer's mapping, 1024 bytes. + unsafe { std::ptr::copy_nonoverlapping(pattern.as_ptr(), data, 1024) }; + let buffer = |kind: D3D12_HEAP_TYPE, state: D3D12_RESOURCE_STATES| { + let heap = D3D12_HEAP_PROPERTIES { + Type: kind, + ..Default::default() + }; + let desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, + Width: 1024, + Height: 1, + DepthOrArraySize: 1, + MipLevels: 1, + SampleDesc: DXGI_SAMPLE_DESC { + Count: 1, + Quality: 0, + }, + Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, + ..Default::default() + }; + let mut made: Option = None; + // SAFETY: plain creation of a buffer. + unsafe { + host.device + .CreateCommittedResource( + &heap, + D3D12_HEAP_FLAG_NONE, + &desc, + state, + None, + &mut made, + ) + .unwrap(); + } + made.unwrap() + }; + let readback = buffer(D3D12_HEAP_TYPE_READBACK, D3D12_RESOURCE_STATE_COPY_DEST); + // The colour target the draws cover: 4x4, 8 bits a texel. + let target = { + let heap = D3D12_HEAP_PROPERTIES { + Type: D3D12_HEAP_TYPE_DEFAULT, + ..Default::default() + }; + let desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D, + Width: 4, + Height: 4, + DepthOrArraySize: 1, + MipLevels: 1, + Format: DXGI_FORMAT(61), + SampleDesc: DXGI_SAMPLE_DESC { + Count: 1, + Quality: 0, + }, + Flags: D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET, + ..Default::default() + }; + let mut made: Option = None; + // SAFETY: plain creation of a texture. + unsafe { + host.device + .CreateCommittedResource( + &heap, + D3D12_HEAP_FLAG_NONE, + &desc, + D3D12_RESOURCE_STATE_RENDER_TARGET, + None, + &mut made, + ) + .unwrap(); + } + made.unwrap() + }; + let rows_of = |format: i32| D3D12_PLACED_SUBRESOURCE_FOOTPRINT { + Offset: 0, + Footprint: D3D12_SUBRESOURCE_FOOTPRINT { + Format: DXGI_FORMAT(format), + Width: 4, + Height: 4, + Depth: 1, + RowPitch: 256, + }, + }; + // A texture's one subresource; rows of a buffer. + let whole = |texture: &ID3D12Resource| D3D12_TEXTURE_COPY_LOCATION { + // SAFETY: a borrowed pointer the location never releases. + pResource: unsafe { std::mem::transmute_copy(texture) }, + Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, + Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { + SubresourceIndex: 0, + }, + }; + let rows = |buffer: &ID3D12Resource, placed: D3D12_PLACED_SUBRESOURCE_FOOTPRINT| { + D3D12_TEXTURE_COPY_LOCATION { + // SAFETY: as above. + pResource: unsafe { std::mem::transmute_copy(buffer) }, + Type: D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT, + Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { + PlacedFootprint: placed, + }, + } + }; + let (written, source, dest, tested, drawn) = ( + D3D12_RESOURCE_STATE_UNORDERED_ACCESS, + D3D12_RESOURCE_STATE_COPY_SOURCE, + D3D12_RESOURCE_STATE_COPY_DEST, + D3D12_RESOURCE_STATE_DEPTH_WRITE, + D3D12_RESOURCE_STATE_RENDER_TARGET, + ); + let moved = crate::host::transition; + + // The class numbers into the twin, where a shader would write them. + let fill = host.new_list().unwrap(); + // SAFETY: an open list and live resources. + unsafe { + let l = &fill.list; + l.ResourceBarrier(&[moved(plane, written, dest)]); + l.CopyTextureRegion(&whole(plane), 0, 0, 0, &rows(&upload, rows_of(53)), None); + l.ResourceBarrier(&[moved(plane, dest, written)]); + } + fill.close(); + host.execute(&[&fill]); + + // A list in which a shader writes the twins: closing it draws the + // depth plane's twin into the plane. + let list = host.new_list().unwrap(); + assert!(list.twin_use(depth, true, true)); + list.twins_written(); + list.close(); + host.execute(&[&list]); + + // The draws: a triangle over the target at the depth of a class, + // as the title's lighting places its rectangles. + const SOURCE: &str = r#" +#define RS "RootConstants(num32BitConstants = 1, b0)" +cbuffer Drawn : register(b0) { uint number; }; +[RootSignature(RS)] +float4 corner(uint i : SV_VertexID) : SV_Position { + float z = float(number) * asfloat(0x37800080); + return float4(float(i & 1) * 4.0 - 1.0, float(i >> 1) * 4.0 - 1.0, z, 1.0); +} +float4 lit() : SV_Target { return 1.0; } +"#; + let vs = crate::host::compile(SOURCE, s!("corner"), s!("vs_5_1")).unwrap(); + let ps = crate::host::compile(SOURCE, s!("lit"), s!("ps_5_1")).unwrap(); + let code = |bytes: &[u8]| D3D12_SHADER_BYTECODE { + pShaderBytecode: bytes.as_ptr().cast(), + BytecodeLength: bytes.len(), + }; + let mut blend = D3D12_BLEND_DESC::default(); + blend.RenderTarget[0].RenderTargetWriteMask = 0xf; + let mut formats = [DXGI_FORMAT(0); 8]; + formats[0] = DXGI_FORMAT(61); + // SAFETY: plain creation; the description points at live data. + let (signature, pipeline) = unsafe { + let signature: ID3D12RootSignature = + host.device.CreateRootSignature(0, &vs[..]).unwrap(); + let desc = D3D12_GRAPHICS_PIPELINE_STATE_DESC { + pRootSignature: std::mem::transmute_copy(&signature), + VS: code(&vs[..]), + PS: code(&ps[..]), + BlendState: blend, + SampleMask: u32::MAX, + RasterizerState: D3D12_RASTERIZER_DESC { + FillMode: D3D12_FILL_MODE_SOLID, + CullMode: D3D12_CULL_MODE_NONE, + DepthClipEnable: true.into(), + ..Default::default() + }, + // As the title's lighting: test "equal", nothing written. + DepthStencilState: D3D12_DEPTH_STENCIL_DESC { + DepthEnable: true.into(), + DepthWriteMask: D3D12_DEPTH_WRITE_MASK_ZERO, + DepthFunc: D3D12_COMPARISON_FUNC_EQUAL, + ..Default::default() + }, + PrimitiveTopologyType: D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE, + NumRenderTargets: 1, + RTVFormats: formats, + DSVFormat: DXGI_FORMAT(45), + SampleDesc: DXGI_SAMPLE_DESC { + Count: 1, + Quality: 0, + }, + ..Default::default() + }; + let pipeline: ID3D12PipelineState = + host.device.CreateGraphicsPipelineState(&desc).unwrap(); + (signature, pipeline) + }; + let state = host_copy(depth).unwrap().state.load(Relaxed); + let state = D3D12_RESOURCE_STATES(state as i32); + let colour = host.rtv(Some(&target), None); + let depth_view = host.dsv( + host_depth, + Some(&D3D12_DEPTH_STENCIL_VIEW_DESC { + Format: DXGI_FORMAT(45), + ViewDimension: D3D12_DSV_DIMENSION_TEXTURE2D, + ..Default::default() + }), + ); + let back = host.new_list().unwrap(); + // SAFETY: an open list and live resources and views. + unsafe { + let l = &back.list; + if state != tested { + l.ResourceBarrier(&[moved(host_depth, state, tested)]); + } + l.ClearRenderTargetView(colour, &[0.0; 4], None); + l.SetGraphicsRootSignature(&signature); + l.SetPipelineState(&pipeline); + l.OMSetRenderTargets(1, Some(&colour), false, Some(&depth_view)); + l.RSSetViewports(&[D3D12_VIEWPORT { + TopLeftX: 0.0, + TopLeftY: 0.0, + Width: 4.0, + Height: 4.0, + MinDepth: 0.0, + MaxDepth: 1.0, + }]); + l.RSSetScissorRects(&[RECT { + left: 0, + top: 0, + right: 4, + bottom: 4, + }]); + l.IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY(4)); + // Classes 65 and 129 are drawn; the others are not. + for class in [65u32, 129] { + l.SetGraphicsRoot32BitConstant(0, class, 0); + l.DrawInstanced(3, 1, 0, 0); + } + l.ResourceBarrier(&[moved(&target, drawn, source)]); + let (to, from) = (rows(&readback, rows_of(61)), whole(&target)); + l.CopyTextureRegion(&to, 0, 0, 0, &from, None); + } + back.close(); + host.execute(&[&back]); + let mut mapped = std::ptr::null_mut(); + // SAFETY: the copy finished (execute waits); the buffer is 1024 bytes. + let read = unsafe { + readback + .Map( + 0, + Some(&D3D12_RANGE { + Begin: 0, + End: 1024, + }), + Some(&mut mapped), + ) + .unwrap(); + std::slice::from_raw_parts(mapped.cast::(), 1024) + }; + for (i, class) in CLASSES.into_iter().enumerate() { + let covered = read[i / 4 * 256 + i % 4] != 0; + let drawn = matches!(class, 65 | 129); + assert_eq!(covered, drawn, "texel {i}, class {class}"); + } + } + + #[test] + fn committed_and_placed_resources_map_at_their_gpu_address() { + let null = std::ptr::null(); + let mut committed = null; + let hr = create_committed( + null, + &PROPERTIES, + 0, + &buffer(256), + 0, + null.cast(), + &RESOURCE_IIDS[0], + &mut committed, + ); + assert_eq!(hr, S_OK); + let mut data = std::ptr::null_mut(); + assert_eq!( + slot::(committed, 0x40)(committed, 0, null.cast(), &mut data), + S_OK + ); + assert_eq!(slot::
(committed, 0x58)(committed), data as u64); + // SAFETY: the buffer is at least 256 zeroed bytes. + assert_eq!(unsafe { *data.add(255) }, 0); + assert_eq!(slot::(committed, 0x10)(committed), 0); + + let heap = heap(4 * KIB_64); + let place = |offset, desc: &ResourceDesc, out: &mut This| { + create_placed( + null, + heap, + offset, + desc, + 0, + null.cast(), + &RESOURCE_IIDS[0], + out, + ) + }; + let mut placed = null; + assert_eq!(place(KIB_64, &buffer(KIB_64), &mut placed), S_OK); + // SAFETY: a heap we made. + let base = unsafe { (*heap.cast::()).memory.ptr.as_ptr() } as u64; + assert_eq!(slot::
(placed, 0x58)(placed), base + KIB_64); + let mut other = null; + assert_eq!( + place(4 * KIB_64, &buffer(1), &mut other), + E_INVALIDARG, + "past the end" + ); + assert_eq!( + place(100, &buffer(1), &mut other), + E_INVALIDARG, + "misaligned" + ); + // The resource keeps the heap alive. + assert_eq!(slot::(heap, 0x10)(heap), 1); + assert_eq!(slot::(placed, 0x10)(placed), 0); + } +} diff --git a/crates/leonida-gpu/src/root.rs b/crates/leonida-gpu/src/root.rs new file mode 100644 index 000000000..5bded71dc --- /dev/null +++ b/crates/leonida-gpu/src/root.rs @@ -0,0 +1,324 @@ +//! Root signatures. +//! +//! Serializing goes to the host's `D3D12SerializeRootSignature` (or its +//! versioned form): the description is laid out as on PC, and the blob it +//! returns works as the console's, whose two methods sit in the same slots. +//! The console's own flags (bit 24 and up) are dropped first. +#![allow(clippy::not_unsafe_ptr_arg_deref)] + +use std::ffi::{CStr, c_void}; +use std::sync::OnceLock; + +use crate::object::{ + self, E_INVALIDARG, E_NOTIMPL, HRESULT, Iid, Object, ROOT_SIGNATURE, Table, This, guid, +}; +use crate::resource::PAGEABLE_IIDS; + +const ROOT_SIGNATURE_IIDS: [Iid; 3] = [ + guid( + 0xc54a6b66, + 0x72df, + 0x4ee8, + [0x8b, 0xe5, 0xa9, 0x46, 0xa1, 0x42, 0x92, 0x14], + ), + PAGEABLE_IIDS[1], + PAGEABLE_IIDS[2], +]; + +const CONSOLE_FLAGS: u32 = 0xff00_0000; + +#[repr(C)] +#[derive(Clone, Copy)] +pub struct Desc { + parameter_count: u32, + parameters: *const c_void, + sampler_count: u32, + samplers: *const c_void, + flags: u32, +} + +/// Every version's description starts with the fields of [`Desc`]. +#[repr(C)] +#[derive(Clone, Copy)] +pub struct VersionedDesc { + version: u32, + desc: Desc, +} + +type Serialize = + unsafe extern "system" fn(*const Desc, u32, *mut *mut c_void, *mut *mut c_void) -> HRESULT; +type SerializeVersioned = + unsafe extern "system" fn(*const VersionedDesc, *mut *mut c_void, *mut *mut c_void) -> HRESULT; + +/// An export of the host's `d3d12.dll` in System32, looked up once. +fn host_export(cache: &OnceLock>, name: &CStr) -> Option { + *cache.get_or_init(|| { + #[cfg(windows)] + { + use windows_sys::Win32::System::LibraryLoader::{ + GetProcAddress, LOAD_LIBRARY_SEARCH_SYSTEM32, LoadLibraryExW, + }; + let dll: Vec = "d3d12.dll".encode_utf16().chain([0]).collect(); + // SAFETY: a NUL-terminated name; System32 only. + let module = unsafe { + LoadLibraryExW( + dll.as_ptr(), + std::ptr::null_mut(), + LOAD_LIBRARY_SEARCH_SYSTEM32, + ) + }; + if module.is_null() { + return None; + } + // SAFETY: a loaded module and a NUL-terminated name. + unsafe { GetProcAddress(module, name.as_ptr().cast()) }.map(|f| f as usize) + } + #[cfg(not(windows))] + None + }) +} + +fn without_console_flags(desc: Desc) -> Desc { + if desc.flags & CONSOLE_FLAGS != 0 { + tracing::debug!( + flags = format_args!("{:#x}", desc.flags), + "console root signature flags dropped" + ); + } + Desc { + flags: desc.flags & !CONSOLE_FLAGS, + ..desc + } +} + +/// `d3d12_xs!D3D12SerializeRootSignature`. +pub extern "system" fn serialize( + desc: *const Desc, + version: u32, + blob: *mut *mut c_void, + error: *mut *mut c_void, +) -> HRESULT { + // SAFETY: the title passes a description (null is tolerated). + let Some(&desc) = (unsafe { desc.as_ref() }) else { + return E_INVALIDARG; + }; + static FUNCTION: OnceLock> = OnceLock::new(); + let Some(address) = host_export(&FUNCTION, c"D3D12SerializeRootSignature") else { + tracing::warn!("no host d3d12.dll to serialize root signatures"); + return E_NOTIMPL; + }; + // SAFETY: the export has this signature; it takes what the title passed. + unsafe { + std::mem::transmute::(address)( + &without_console_flags(desc), + version, + blob, + error, + ) + } +} + +/// `d3d12_xs!D3D12SerializeVersionedRootSignature`. +pub extern "system" fn serialize_versioned( + desc: *const VersionedDesc, + blob: *mut *mut c_void, + error: *mut *mut c_void, +) -> HRESULT { + // SAFETY: the title passes a description (null is tolerated). + let Some(&desc) = (unsafe { desc.as_ref() }) else { + return E_INVALIDARG; + }; + static FUNCTION: OnceLock> = OnceLock::new(); + let Some(address) = host_export(&FUNCTION, c"D3D12SerializeVersionedRootSignature") else { + tracing::warn!("no host d3d12.dll to serialize root signatures"); + return E_NOTIMPL; + }; + let desc = VersionedDesc { + desc: without_console_flags(desc.desc), + ..desc + }; + // SAFETY: the export has this signature; it takes what the title passed. + unsafe { std::mem::transmute::(address)(&desc, blob, error) } +} + +type Deserialize = + unsafe extern "system" fn(*const u8, usize, *const Iid, *mut *mut c_void) -> HRESULT; + +/// `d3d12_xs!D3D12CreateRootSignatureDeserializer`: our blobs are the +/// host's serialization, so the host's deserializer reads them, and its +/// object (IUnknown, then the description getter) is laid out as the +/// console's. The title's upscaler asks with the PC interface id. +pub extern "system" fn create_deserializer( + blob: *const u8, + size: usize, + iid: *const Iid, + out: *mut *mut c_void, +) -> HRESULT { + if blob.is_null() || out.is_null() { + return E_INVALIDARG; + } + static FUNCTION: OnceLock> = OnceLock::new(); + let Some(address) = host_export(&FUNCTION, c"D3D12CreateRootSignatureDeserializer") else { + tracing::warn!("no host d3d12.dll to deserialize root signatures"); + return E_NOTIMPL; + }; + // SAFETY: the export has this signature; it takes what the title passed. + unsafe { std::mem::transmute::(address)(blob, size, iid, out) } +} + +#[repr(C)] +struct RootSignature { + object: Object, + /// The serialized form, kept for translating pipelines later. + blob: Vec, +} + +/// Device method. +pub(crate) extern "system" fn create( + _: This, + _nodes: u32, + blob: *const u8, + size: usize, + iid: *const Iid, + out: *mut This, +) -> HRESULT { + if blob.is_null() || size == 0 { + return E_INVALIDARG; + } + // SAFETY: the title passes `size` bytes. + let blob = unsafe { std::slice::from_raw_parts(blob, size) }.to_vec(); + tracing::debug!(size, "root signature"); + let root = Box::new(RootSignature { + object: Object::new(&FUNCTIONS), + blob, + }); + object::hand_out(ROOT_SIGNATURE, root, iid, &ROOT_SIGNATURE_IIDS, out) +} + +extern "system" fn query(this: This, iid: *const Iid, out: *mut This) -> HRESULT { + let found = object::is(iid, &ROOT_SIGNATURE_IIDS).then_some(this); + object::answer(ROOT_SIGNATURE, iid, found, out) +} +extern "system" fn release(this: This) -> u32 { + object::release_boxed::(this) +} + +/// IUnknown 3, object 4, device child 1. +static FUNCTIONS: Table<24> = { + let mut f = object::d3d12_object(object::missing_table::()); + f[0] = query as *const (); + f[2] = release as *const (); + f[7] = object::parent_device as *const (); // 0x38 + Table(f) +}; + +#[cfg(test)] +mod tests { + use super::*; + use crate::object::{S_OK, slot}; + + /// One 32-bit constant at b0, serialized by the host, then created. + #[cfg(windows)] + #[test] + fn host_serialized_blobs_create_root_signatures() { + use windows::Win32::Graphics::Direct3D12::{ + D3D12_ROOT_CONSTANTS, D3D12_ROOT_PARAMETER, D3D12_ROOT_PARAMETER_0, + D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS, D3D12_SHADER_VISIBILITY_ALL, + }; + let parameter = D3D12_ROOT_PARAMETER { + ParameterType: D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS, + Anonymous: D3D12_ROOT_PARAMETER_0 { + Constants: D3D12_ROOT_CONSTANTS { + ShaderRegister: 0, + RegisterSpace: 0, + Num32BitValues: 1, + }, + }, + ShaderVisibility: D3D12_SHADER_VISIBILITY_ALL, + }; + let desc = Desc { + parameter_count: 1, + parameters: (&raw const parameter).cast(), + sampler_count: 0, + samplers: std::ptr::null(), + flags: 0x0100_0001, + }; + let (mut blob, mut error) = (std::ptr::null_mut(), std::ptr::null_mut()); + assert_eq!(serialize(&desc, 1, &mut blob, &mut error), S_OK); + let blob = blob.cast_const().cast::(); + let data = slot:: *const u8>(blob, 0x18)(blob); + let size = slot:: usize>(blob, 0x20)(blob); + assert!(size > 0); + let null = std::ptr::null(); + let mut root = null; + assert_eq!( + create(null, 0, data, size, &ROOT_SIGNATURE_IIDS[0], &mut root), + S_OK + ); + assert_eq!(slot:: u32>(root, 0x10)(root), 0); + slot:: u32>(blob, 0x10)(blob); + } + + /// The host's deserializer reads our blobs back (the upscaler's call). + #[cfg(windows)] + #[test] + fn our_blobs_deserialize_on_the_host() { + use windows::Win32::Graphics::Direct3D12::ID3D12RootSignatureDeserializer; + use windows::core::Interface; + let desc = VersionedDesc { + version: 1, + desc: Desc { + parameter_count: 0, + parameters: std::ptr::null(), + sampler_count: 0, + samplers: std::ptr::null(), + flags: 1, + }, + }; + let (mut blob, mut error) = (std::ptr::null_mut(), std::ptr::null_mut()); + assert_eq!(serialize_versioned(&desc, &mut blob, &mut error), S_OK); + let blob = blob.cast_const().cast::(); + let data = slot:: *const u8>(blob, 0x18)(blob); + let size = slot:: usize>(blob, 0x20)(blob); + let iid: Iid = ID3D12RootSignatureDeserializer::IID.to_u128().to_be_bytes(); + let iid = guid( + u32::from_be_bytes(iid[0..4].try_into().unwrap()), + u16::from_be_bytes(iid[4..6].try_into().unwrap()), + u16::from_be_bytes(iid[6..8].try_into().unwrap()), + iid[8..16].try_into().unwrap(), + ); + let mut out = std::ptr::null_mut(); + assert_eq!(create_deserializer(data, size, &iid, &mut out), S_OK); + // SAFETY: the host handed out this interface. + let deserializer = unsafe { ID3D12RootSignatureDeserializer::from_raw(out) }; + // SAFETY: valid while the deserializer lives. + let read = unsafe { &*deserializer.GetRootSignatureDesc() }; + assert_eq!((read.NumParameters, read.Flags.0), (0, 1)); + slot:: u32>(blob, 0x10)(blob); + } + + /// Version 1.0 through the versioned entry point, with a console flag. + #[cfg(windows)] + #[test] + fn versioned_descriptions_serialize_on_the_host() { + let desc = VersionedDesc { + version: 1, + desc: Desc { + parameter_count: 0, + parameters: std::ptr::null(), + sampler_count: 0, + samplers: std::ptr::null(), + flags: 0x0200_0001, + }, + }; + let (mut blob, mut error) = (std::ptr::null_mut(), std::ptr::null_mut()); + assert_eq!(serialize_versioned(&desc, &mut blob, &mut error), S_OK); + let blob = blob.cast_const().cast::(); + assert!(slot:: usize>(blob, 0x20)(blob) > 0); + slot:: u32>(blob, 0x10)(blob); + assert_eq!( + serialize_versioned(std::ptr::null(), &mut blob.cast_mut().cast(), &mut error), + E_INVALIDARG + ); + } +} diff --git a/crates/leonida-gpu/src/sampler.rs b/crates/leonida-gpu/src/sampler.rs new file mode 100644 index 000000000..ee95da3fd --- /dev/null +++ b/crates/leonida-gpu/src/sampler.rs @@ -0,0 +1,119 @@ +//! Samplers as the host describes them, from the console's sampler +//! description (`CreateSamplerX`), which names the hardware's sampler +//! fields. (Immediate samplers in shader code come decoded with the +//! translation.) + +use windows::Win32::Graphics::Direct3D12::*; + +/// The fields both forms share. +#[derive(Debug, Clone, Copy, PartialEq)] +struct Fields { + /// Point 0, bilinear 1, anisotropic point 2, anisotropic bilinear 3. + mag: u32, + min: u32, + /// None 0, point 1, linear 2. + mip: u32, + /// Plain 0, minimum 1, maximum 2. + mode: u32, + /// Host address modes. + address: [u32; 3], + anisotropy: u32, + /// Host comparison function. + compare: u32, + min_lod: f32, + max_lod: f32, + bias: f32, + border: [f32; 4], +} + +impl Fields { + fn host(&self) -> D3D12_SAMPLER_DESC { + let linear = |f: u32| u32::from(f == 1 || f == 3); + let aniso = self.mag >= 2 || self.min >= 2; + // The console compares when the instruction says so, with the + // sampler's function; the host needs a comparison sampler for that. + // A sampler given a real test (less ... greater-or-equal) is one; + // never, always and none are plain samplers. + const LESS: u32 = 2; + const GREATER_EQUAL: u32 = 7; + let compares = (LESS..=GREATER_EQUAL).contains(&self.compare); + let reduction = match self.mode { + 1 => 2, + 2 => 3, + _ => u32::from(compares), + }; + let filter = if aniso { + 0x55 + } else { + linear(self.min) << 4 | linear(self.mag) << 2 | u32::from(self.mip == 2) + }; + D3D12_SAMPLER_DESC { + Filter: D3D12_FILTER((reduction << 7 | filter) as i32), + AddressU: D3D12_TEXTURE_ADDRESS_MODE(self.address[0] as i32), + AddressV: D3D12_TEXTURE_ADDRESS_MODE(self.address[1] as i32), + AddressW: D3D12_TEXTURE_ADDRESS_MODE(self.address[2] as i32), + MipLODBias: self.bias, + MaxAnisotropy: if aniso { + self.anisotropy.clamp(1, 16) + } else { + 1 + }, + ComparisonFunc: D3D12_COMPARISON_FUNC(self.compare.max(1) as i32), + BorderColor: self.border, + MinLOD: self.min_lod, + // Without a mip filter the console samples mip 0 only. + MaxLOD: if self.mip == 0 { + self.min_lod + } else { + self.max_lod + }, + } + } +} + +/// The console's sampler description (27 words): flags, magnification, +/// minification, mip and depth filters, filter mode, three address modes, +/// minimum and maximum LOD, LOD bias, secondary bias, anisotropy, its bias +/// and threshold, comparison, border color, then tuning words. +pub(crate) fn console(words: &[u32; 27]) -> D3D12_SAMPLER_DESC { + let f = |i: usize| f32::from_bits(words[i]); + Fields { + mag: words[1], + min: words[2], + mip: words[3], + mode: words[5], + address: [words[6], words[7], words[8]], + min_lod: f(9), + max_lod: f(10), + bias: f(11), + anisotropy: words[13], + compare: words[16], + border: [f(17), f(18), f(19), f(20)], + } + .host() +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn console_descriptions_decode() { + let mut w = [0u32; 27]; + w[1] = 1; // bilinear magnification + w[2] = 0; // point minification + w[3] = 2; // linear mips + w[6..9].copy_from_slice(&[3, 3, 3]); + w[10] = 1000.0f32.to_bits(); + let d = console(&w); + assert_eq!(d.Filter.0, 0x5, "min point, mag and mip linear"); + assert_eq!(d.AddressW, D3D12_TEXTURE_ADDRESS_MODE_CLAMP); + assert_eq!(d.MaxLOD, 1000.0); + // A less-or-equal test makes a comparison sampler; never does not. + w[16] = 4; + assert_eq!(console(&w).Filter.0, 0x85); + assert_eq!(console(&w).ComparisonFunc, D3D12_COMPARISON_FUNC_LESS_EQUAL); + w[16] = 1; + assert_eq!(console(&w).Filter.0, 0x5); + } +} diff --git a/crates/leonida-gpu/src/shader_cache.rs b/crates/leonida-gpu/src/shader_cache.rs new file mode 100644 index 000000000..75bf51e01 --- /dev/null +++ b/crates/leonida-gpu/src/shader_cache.rs @@ -0,0 +1,417 @@ +//! Translated shaders kept on disk (decision 0003): under the configured +//! cache folder, keyed by the container's content and by the translator +//! that translated it (its source fingerprint and settings, see `build`), so +//! a changed translator never serves an old translation. Entries go through +//! `leonida-pipeline`'s content-addressed cache, which writes them +//! atomically; an entry that does not read back is translated again. +//! +//! The entry is our own encoding of [`HostShader`]: a field added to it +//! must be added to `encode` and `decode` too (entries of older builds +//! are ignored anyway). + +use std::path::PathBuf; +use std::sync::OnceLock; +use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; + +use leonida_pipeline::{Cache, Converter}; +use leonida_shader::emit::{HostShader, StaticSampler, UserData}; +use leonida_shader::resource::RootIndexedView; +use leonida_shader::{HwStage, RootType}; + +static CACHE: OnceLock = OnceLock::new(); +static HITS: AtomicU64 = AtomicU64::new(0); +static MISSES: AtomicU64 = AtomicU64::new(0); + +/// Keeps translated shaders in `dir` from now on. +pub fn use_shader_cache(dir: PathBuf) { + match Cache::open(dir) { + Ok(cache) => { + let _ = CACHE.set(cache); + } + Err(e) => tracing::warn!(error = %e, "no shader cache"), + } +} + +/// Shaders found in the cache and translated since the start. +pub(crate) fn counts() -> (u64, u64) { + (HITS.load(Ordering::Relaxed), MISSES.load(Ordering::Relaxed)) +} + +/// What identifies the translation, besides the container: the shader +/// crate's fingerprint (its source, every switch it reads, the host facts the +/// device gave it, the loop limit, barrier waits and clean-up passes) and +/// this file's encoding of the result. Not the whole executable any more: a +/// rebuild that leaves the translator alone keeps its translations (each new +/// build used to translate the title's thousands of shaders again, which kept +/// the first minutes of every test run short of pipelines). +/// `LEONIDA_SHADER_CACHE_KEY=exe` restores the old key (the executable's hash). +/// Worked out per lookup, so a translation made before the device said its +/// wave size is never filed under the later key. +fn build() -> [u8; 32] { + static WARNED: std::sync::Once = std::sync::Once::new(); + let limit = leonida_shader::emit::loop_limit(); + if limit != leonida_shader::emit::DEFAULT_LOOP_LIMIT { + WARNED.call_once(|| tracing::warn!(limit, "LEONIDA_SHADER_LOOP_LIMIT: translated loops stop sooner")); + } + static EXE: OnceLock> = OnceLock::new(); + let exe = EXE.get_or_init(|| { + if std::env::var_os("LEONIDA_SHADER_CACHE_KEY").is_some_and(|v| v == "exe") { + match std::env::current_exe().and_then(std::fs::read) { + Ok(bytes) => Some(*blake3::hash(&bytes).as_bytes()), + Err(e) => { + tracing::warn!(error = %e, "cannot read our executable; keying on the translator"); + None + } + } + } else { + None + } + }); + let mut h = blake3::Hasher::new(); + h.update(b"leonida shader cache key 2\0"); + if let Some(exe) = exe { + h.update(exe); + } + h.update(&leonida_shader::emit::translation_fingerprint()); + h.update(include_bytes!("shader_cache.rs")); + *h.finalize().as_bytes() +} + +/// The offline warm-up (`leonida translate --warm`): `container` is +/// translated into the cache unless it is there already. `Ok(true)`: it +/// was translated now. Needs [`use_shader_cache`] and the same host facts +/// the run will have (`leonida_shader::emit::translation_fingerprint`). +pub fn warm(container: &[u8]) -> Result { + let cache = CACHE.get().ok_or("no shader cache")?; + let ran = AtomicBool::new(false); + let translate = |c: &[u8]| { + ran.store(true, Ordering::Relaxed); + leonida_shader::emit::translate(c).map_err(|e| e.to_string()) + }; + cached(cache, &build(), container, translate).map(|_| ran.load(Ordering::Relaxed)) +} + +/// The translation of a console shader container, from the cache when +/// there is one. +pub(crate) fn host_shader(container: &[u8]) -> Result { + let translate = |c: &[u8]| leonida_shader::emit::translate(c).map_err(|e| e.to_string()); + match CACHE.get() { + Some(cache) => cached(cache, &build(), container, translate), + None => translate(container), + } +} + +/// The cache entry's converter: the build and the container in, the +/// encoded translation out. `ran` tells a miss from a hit. +struct Translate { + translate: F, + ran: AtomicBool, +} + +impl Result + Send + Sync> Converter for Translate { + fn id(&self) -> &'static str { + "shader.dxil" + } + fn version(&self) -> u32 { + // The build fingerprint in the input does the versioning. + 1 + } + fn convert(&self, input: &[u8]) -> anyhow::Result> { + self.ran.store(true, Ordering::Relaxed); + let shader = (self.translate)(&input[32..]).map_err(anyhow::Error::msg)?; + Ok(encode(&shader)) + } +} + +fn cached( + cache: &Cache, + build: &[u8; 32], + container: &[u8], + translate: impl Fn(&[u8]) -> Result + Send + Sync, +) -> Result { + let input = [&build[..], container].concat(); + let converter = Translate { + translate, + ran: AtomicBool::new(false), + }; + for _ in 0..2 { + let path = cache + .get_or_convert(&converter, &input) + .map_err(|e| format!("{e:#}"))?; + if let Some(shader) = std::fs::read(&path).ok().and_then(|b| decode(&b)) { + let (counter, what) = if converter.ran.load(Ordering::Relaxed) { + (&MISSES, "translated and cached") + } else { + (&HITS, "from the cache") + }; + counter.fetch_add(1, Ordering::Relaxed); + tracing::debug!(path = %path.display(), "shader {what}"); + return Ok(shader); + } + tracing::debug!(path = %path.display(), "unreadable shader cache entry; translating again"); + let _ = std::fs::remove_file(&path); + } + MISSES.fetch_add(1, Ordering::Relaxed); + (converter.translate)(container) +} + +const MAGIC: &[u8; 4] = b"VSH1"; +const STAGES: [HwStage; 8] = [ + HwStage::Ls, + HwStage::Hs, + HwStage::Es, + HwStage::Gs, + HwStage::Vs, + HwStage::Ps, + HwStage::Ms, + HwStage::Cs, +]; + +fn root_code(r: RootType) -> u32 { + match r { + RootType::Constants => 0, + RootType::Descriptor => 1, + RootType::Table => 2, + RootType::ImmediateSampler => 3, + RootType::ResourceHeap => 4, + RootType::SamplerHeap => 5, + RootType::Other(x) => 6 + x, + } +} + +fn root_type(code: u32) -> RootType { + match code { + 0 => RootType::Constants, + 1 => RootType::Descriptor, + 2 => RootType::Table, + 3 => RootType::ImmediateSampler, + 4 => RootType::ResourceHeap, + 5 => RootType::SamplerHeap, + x => RootType::Other(x - 6), + } +} + +/// Little-endian words and length-prefixed lists. +fn encode(s: &HostShader) -> Vec { + let mut out = MAGIC.to_vec(); + let word = |out: &mut Vec, v: u32| out.extend(v.to_le_bytes()); + let stage = STAGES.iter().position(|&x| x == s.stage).unwrap_or(0) as u32; + word(&mut out, stage); + word(&mut out, s.dxil.len() as u32); + out.extend(&s.dxil); + word(&mut out, s.user_data.len() as u32); + for u in &s.user_data { + for v in [u.index, u32::from(u.slot), root_code(u.root), u.dword] { + word(&mut out, v); + } + } + word(&mut out, s.samplers.len() as u32); + for sampler in &s.samplers { + for &v in sampler { + word(&mut out, v); + } + } + word(&mut out, s.static_samplers.len() as u32); + for t in &s.static_samplers { + let [u, v, w] = t.address; + let words = [ + t.filter, + u, + v, + w, + t.mip_lod_bias.to_bits(), + t.max_anisotropy, + t.comparison, + t.border, + t.min_lod.to_bits(), + t.max_lod.to_bits(), + ]; + for v in words { + word(&mut out, v); + } + } + for slots in [&s.root_cbvs, &s.root_srvs, &s.root_uavs] { + word(&mut out, slots.len() as u32); + out.extend(slots); + } + word(&mut out, s.root_indexed_views.len() as u32); + for view in &s.root_indexed_views { + for value in [ + u32::from(view.table_slot), + u32::from(view.constant_slot), + view.constant_dword, + view.byte_offset, + u32::from(view.shift), + ] { + word(&mut out, value); + } + } + out +} + +fn decode(bytes: &[u8]) -> Option { + struct Reader<'a>(&'a [u8]); + impl<'a> Reader<'a> { + fn take(&mut self, n: usize) -> Option<&'a [u8]> { + let (head, rest) = self.0.split_at_checked(n)?; + self.0 = rest; + Some(head) + } + fn word(&mut self) -> Option { + Some(u32::from_le_bytes(self.take(4)?.try_into().ok()?)) + } + fn list(&mut self) -> Option> { + let n = self.word()? as usize; + Some(self.take(n)?.to_vec()) + } + } + let mut r = Reader(bytes); + if r.take(4)? != MAGIC { + return None; + } + let stage = *STAGES.get(r.word()? as usize)?; + let dxil = r.list()?; + let n = r.word()? as usize; + let mut user_data = Vec::with_capacity(n.min(256)); + for _ in 0..n { + user_data.push(UserData { + index: r.word()?, + slot: u8::try_from(r.word()?).ok()?, + root: root_type(r.word()?), + dword: r.word()?, + }); + } + let n = r.word()? as usize; + let mut samplers = Vec::with_capacity(n.min(256)); + for _ in 0..n { + samplers.push([r.word()?, r.word()?, r.word()?, r.word()?]); + } + let n = r.word()? as usize; + let mut static_samplers = Vec::with_capacity(n.min(256)); + for _ in 0..n { + static_samplers.push(StaticSampler { + filter: r.word()?, + address: [r.word()?, r.word()?, r.word()?], + mip_lod_bias: f32::from_bits(r.word()?), + max_anisotropy: r.word()?, + comparison: r.word()?, + border: r.word()?, + min_lod: f32::from_bits(r.word()?), + max_lod: f32::from_bits(r.word()?), + }); + } + let root_cbvs = r.list()?; + let root_srvs = r.list()?; + let root_uavs = r.list()?; + let n = r.word()? as usize; + let mut root_indexed_views = Vec::with_capacity(n.min(256)); + for _ in 0..n { + root_indexed_views.push(RootIndexedView { + table_slot: u8::try_from(r.word()?).ok()?, + constant_slot: u8::try_from(r.word()?).ok()?, + constant_dword: r.word()?, + byte_offset: r.word()?, + shift: u8::try_from(r.word()?).ok().filter(|&s| s < 32)?, + }); + } + r.0.is_empty().then_some(HostShader { + stage, + dxil, + user_data, + samplers, + static_samplers, + root_cbvs, + root_srvs, + root_uavs, + root_indexed_views, + }) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn shader() -> HostShader { + HostShader { + stage: HwStage::Ps, + dxil: b"DXBC and the rest".to_vec(), + user_data: vec![UserData { + index: 8, + slot: 1, + root: RootType::Table, + dword: 0, + }], + samplers: vec![[0x400, 0xc0_0000, 0x18f0_0000, 0]], + static_samplers: vec![StaticSampler::from_words([ + 0x400, + 0xc0_0000, + 0x18f0_0000, + 0, + ])], + root_cbvs: vec![2], + root_srvs: vec![0, 3], + root_uavs: vec![1], + root_indexed_views: vec![RootIndexedView { + table_slot: 1, + constant_slot: 2, + constant_dword: 3, + byte_offset: 32, + shift: 5, + }], + } + } + + #[test] + fn translations_come_back_from_the_cache() { + let dir = tempfile::tempdir().unwrap(); + let cache = Cache::open(dir.path()).unwrap(); + let build = [7u8; 32]; + let container = b"a console container".as_slice(); + let runs = AtomicU64::new(0); + let translate = |_: &[u8]| { + runs.fetch_add(1, Ordering::Relaxed); + Ok(shader()) + }; + assert_eq!(cached(&cache, &build, container, translate), Ok(shader())); + assert_eq!(cached(&cache, &build, container, translate), Ok(shader())); + assert_eq!(runs.load(Ordering::Relaxed), 1, "the second came from disk"); + + // Another build translates again. + assert_eq!(cached(&cache, &[8; 32], container, translate), Ok(shader())); + assert_eq!(runs.load(Ordering::Relaxed), 2); + + // A damaged entry is a miss, translated and stored again. + for e in walk(dir.path()) { + std::fs::write(e, b"VSH1 broken").unwrap(); + } + assert_eq!(cached(&cache, &build, container, translate), Ok(shader())); + assert_eq!(runs.load(Ordering::Relaxed), 3); + assert_eq!(cached(&cache, &build, container, translate), Ok(shader())); + assert_eq!(runs.load(Ordering::Relaxed), 3); + + // Failures are not stored. + let fail = |_: &[u8]| Err::("unsupported".to_owned()); + assert!(cached(&cache, &build, b"other", fail).is_err()); + } + + fn walk(dir: &std::path::Path) -> Vec { + let mut files = Vec::new(); + for e in std::fs::read_dir(dir).unwrap().flatten() { + if e.path().is_dir() { + files.extend(walk(&e.path())); + } else { + files.push(e.path()); + } + } + files + } + + #[test] + fn entries_round_trip_and_reject_damage() { + let bytes = encode(&shader()); + assert_eq!(decode(&bytes), Some(shader())); + assert_eq!(decode(&bytes[..bytes.len() - 1]), None); + assert_eq!(decode(&[bytes.as_slice(), &[0]].concat()), None); + assert_eq!(decode(b"VSH0"), None); + } +} diff --git a/crates/leonida-gpu/src/shadow.rs b/crates/leonida-gpu/src/shadow.rs new file mode 100644 index 000000000..d578afac1 --- /dev/null +++ b/crates/leonida-gpu/src/shadow.rs @@ -0,0 +1,4282 @@ +//! Host copies of title buffers (decision 0007, step 3 and "Copies of title +//! memory"). Title buffers are title memory, which the host GPU cannot +//! read, so a buffer a draw uses gets a persistent host buffer of its size +//! on first use (system memory shaders may also write), and the ranges each +//! submission reads (vertex, index and constant data, buffer views) are +//! brought up to date from title memory before it runs: the 64 KiB pages +//! the title wrote since they were last copied ([`crate::watch`]: write +//! watching, or read-only guards on physical-page views), all of it where +//! neither works. A title GPU address inside the buffer is the same offset +//! in its copy. Ranges shaders write go back to title memory after the +//! submission ([`Shadow::gpu_writes`]). +//! +//! shortcut: only the ranges draws are known to read are brought up to +//! date (vertex and index buffer views, constant buffers in tables, root +//! descriptors, buffer views in tables); buffers read through directly +//! indexed heaps keep what their first use copied. + +use std::collections::BTreeMap; +use std::sync::atomic::{AtomicU8, AtomicU64, Ordering}; +use std::sync::{Arc, Mutex}; + +use windows::Win32::Graphics::Direct3D12::ID3D12Resource; + +use crate::host::{HostList, host}; +use crate::watch::PAGE; + +/// A title buffer's host copy. +pub(crate) struct Shadow { + pub(crate) buffer: ID3D12Resource, + data: *mut u8, + gpu: u64, + /// Where the title buffer starts and how long it is. + start: u64, + len: u64, + /// Per page of title memory from `start`'s on: the write-watch asking + /// after which it was last copied (0: never). + copied: Mutex>, + /// Whether the memory is write-watched: unknown, yes, no. + watched: AtomicU8, + /// Ranges shaders of a submission not yet copied back may be writing: + /// title memory there is older than the copy. + pending: Mutex>, + /// With [`relay`]: how many submissions not yet copied back declared + /// each range of `pending` ([`Flights`]). Locked inside `pending`'s + /// lock. + flights: Mutex, + /// The copy's bytes before the submission ran, for the ranges its + /// shaders write (`pending`), each at its offset in the copy: what the + /// GPU wrote differs. Room for the whole copy; only those ranges' bytes + /// are set (and read). + before: Mutex>>, + /// With snapshots kept ([`keeps`]): which 64 KiB pieces of the snapshot + /// hold the copy's bytes as they are now, and whether the snapshot is + /// counted in [`KEPT_BYTES`]. + kept: Mutex<(Vec, bool)>, + /// When the copy was last asked for (`crate::host::moment`): a window + /// outside buffers nothing asked for in a while, and nothing holds, is + /// let go ([`let_go_idle`]). + used: AtomicU64, + /// The lowest and highest title address asked for in the copy (a + /// window is 4 MiB whatever was asked: measured for the memory line). + asked: [AtomicU64; 2], + /// Asks for the copy that gave no length (root views: they read from + /// their address to the copy's end, whatever lies there). + unsized_asks: AtomicU64, + /// A number no other copy has had. Its address is no name for a copy: + /// one let go and another made may share it. + id: u64, + /// With [`cards`], for a big title buffer: `buffer` is in the card's + /// own memory, and this is the rest of the copy. + card: Option, + /// A window of title memory outside buffers, not a title buffer's copy. + window: bool, + /// With `crate::inplace`: not a copy at all. `buffer` is placed in a + /// heap opened on the title memory itself, so shaders read and write + /// the title's own bytes and nothing is copied either way. The heap, + /// and the bytes from the buffer's first byte to `start` (the heap + /// begins on a 64 KiB line; a title buffer need not). + place: Option<(windows::Win32::Graphics::Direct3D12::ID3D12Heap, u64)>, +} + +/// What a copy in the card's memory ([`cards`]) has beside the buffer +/// shaders see. +struct Card { + /// The CPU's side, in the PC's memory: what `data` maps. Title memory + /// is copied into it as into any copy, and what changed in it goes to + /// the card's side before the next submission. + staging: ID3D12Resource, + /// The card side's bytes as they were when the submission's shaders + /// started, in the card's memory too: made when shader writes are + /// first declared for the copy, and compared with the card's side, on + /// the card, after each submission that declares some. + before: Mutex>, + /// Offsets of the copy whose bytes changed on the CPU's side and have + /// not gone to the card's side yet. + dirty: Mutex>, + /// With [`relay`]: the offsets that went from `dirty` to the card's + /// side, each with the number of the send that took it + /// ([`card_dirty`]), kept until a fetch sent after it has been merged. + /// Locked inside `dirty`'s lock. + sent: Mutex>, + /// The buffers' bytes (the title buffer's, rounded up to 64 KiB). + size: u64, +} + +/// Whether the host copies of big title buffers are in the card's own +/// memory (on by default since run 75 showed it holds: the BVH skinning +/// list went from 50.5 to 4.5 ms on the card; `LEONIDA_CARD_BUFFERS=0` +/// keeps every copy in the PC's memory, as before. Read when a copy is +/// made, so it takes a fresh start). +/// +/// Every host copy was a buffer in the PC's memory that the card reads +/// and writes over the bus, so that our code can fill it and compare it. +/// The title's shaders read almost all their buffer data from a few big +/// title buffers (in the gameplay frame of run 69, 190-330 MB of distinct +/// ranges of the 174 MB heap per list against 0-13 MB elsewhere), and a +/// skinning dispatch of ONE group of 32 threads took 1.8 ms on the card +/// (run 70): the time of some 170 loads one after the other, not of the +/// arithmetic. +/// +/// With the switch, a title buffer of [`card_limits`]' size or more has two +/// sides. Shaders see `Shadow::buffer`, in the card's memory. The CPU's +/// side (`Card::staging`, what `Shadow::data` maps) takes title memory as +/// before, and the ranges that changed in it are copied to the card's side +/// before each submission (`Host::card_before`). What shaders wrote is +/// found on the card: after the submission's lists a compute pass of ours +/// compares each declared range, by 64 KiB piece, with the card side's +/// bytes from before (`Card::before`), and only the pieces that differ are +/// fetched and merged into title memory, byte by byte as +/// [`Shadow::copy_back`] does (`Host::card_back`, [`Shadow::card_merge`]). +/// No snapshot is taken and nothing is compared on the CPU for such a copy. +/// +/// What it assumes is what [`keeps`] assumes: shaders write a copy only in +/// ranges declared as written. A write outside them is seen by later +/// shaders, as before, and goes back to the title the next time a declared +/// range holds its piece (before: never). +pub(crate) fn cards() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("LEONIDA_CARD_BUFFERS").is_none_or(|v| v != "0")) +} + +/// The smallest title buffer whose copy goes to the card's memory, and the +/// most bytes of such copies (their "before" twins not counted: a copy +/// shaders write takes its size twice), both in bytes: +/// `LEONIDA_CARD_BUFFERS_MIN_MB` (16) and `LEONIDA_CARD_BUFFERS_MB` (512). +/// Run 69's gameplay has ten title buffers of 16 MiB or more, 494 MB, and +/// 1,650 MB of the card's budget free. +fn card_limits() -> (u64, u64) { + static LIMITS: std::sync::OnceLock<(u64, u64)> = std::sync::OnceLock::new(); + *LIMITS.get_or_init(|| { + let mb = |name: &str, default: u64| { + std::env::var(name).ok().and_then(|v| v.trim().parse::().ok()).unwrap_or(default) << 20 + }; + // From 1 MiB up and 1,024 MB in all by default (it was 16 and 512): + // the shader writes of the smaller buffers are then found by the + // card's hashes too, and with that the first room's walls were + // drawn in every run. + (mb("LEONIDA_CARD_BUFFERS_MIN_MB", 1).max(1 << 20), mb("LEONIDA_CARD_BUFFERS_MB", 1024)) + }) +} + +/// Bytes alive of copies' card sides, and of their "before" twins. +static CARD_BYTES: [AtomicU64; 2] = [const { AtomicU64::new(0) }; 2]; + +/// Whether the texture queue leaves room on the card for the card copies +/// of title buffers that are not made yet +/// (`LEONIDA_CARD_ROOM_FOR_BUFFERS=1`; off by default). +/// +/// The copies are made in one burst when the world loads (run 189: 94 of +/// its 95 within two seconds, right before the first world frame), and +/// [`card_for`] makes one only while the card is under eight tenths of its +/// budget. That held as long as the textures picked by index filled the +/// card after the burst. Since the texture queue keeps packed neighbours +/// (52b8060) it fills the card while the world loads: 85% and more at the +/// burst in runs 190 to 192, so one copy of 95 was made, the CPU looked +/// for shader writes in 600 to 720 MB a frame where it had been 30, and +/// the frame went from about 240 to 370-470 ms. +/// +/// With the switch, the texture queue's rule (`resource::room`) counts the +/// part of [`card_limits`]' second number that no copy has taken yet as +/// used, and a copy may be made up to nine tenths of the budget: the room +/// it takes was kept for it. After the burst what is kept is what the +/// burst left of the limit (87 MB of 1,024 in run 189). +/// +/// On by default from the build after run 199 +/// (`LEONIDA_CARD_ROOM_FOR_BUFFERS=0`: off, as before). Run 193 had it on and still made 31 copies of 95: the copies +/// and the world's render targets (+1,603 MB) arrive in the same first +/// world frame and raced for the 448 MB left under the line, and a copy +/// turned down is not asked for again (`lookup` asks once), while its room +/// went on being kept (616 MB to the end of the run). So now: the texture +/// queue also keeps room for the targets (`resource::targets_room_kept`), +/// a copy is made up to 97 hundredths of the budget (its room was kept), +/// and the room of a copy turned down is given up ([`CARD_REFUSED`]). +fn card_room_kept_on() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("LEONIDA_CARD_ROOM_FOR_BUFFERS").is_none_or(|v| v != "0")) +} + +/// Title buffers big enough for a copy in the card's memory that were +/// turned down for want of room, since the start, and their bytes: their +/// copies stay in the PC's memory for as long as the title keeps the +/// buffers, so no room is kept for them any more. +static CARD_REFUSED: [AtomicU64; 2] = [const { AtomicU64::new(0) }; 2]; + +/// The bytes of the card's memory the texture queue leaves free for card +/// copies of title buffers not made yet ([`card_room_kept_on`]): 0 with +/// the switch off or without card copies. +pub(crate) fn card_room_kept() -> u64 { + if !card_room_kept_on() || !cards() { + return 0; + } + card_limits().1.saturating_sub(CARD_BYTES[0].load(Ordering::Relaxed) + CARD_REFUSED[1].load(Ordering::Relaxed)) +} + +/// The copies in the card's memory. +static CARDED: Mutex>> = Mutex::new(Vec::new()); + +/// Since the last frame line: bytes copied to card sides and the ranges +/// they were; pieces compared on the card, pieces fetched and their +/// bytes; the waits for the card the fetches added and their microseconds. +pub(crate) static CARD_STATS: [AtomicU64; 7] = [const { AtomicU64::new(0) }; 7]; + +/// [`CARD_STATS`], taken; then the copies in the card's memory, their +/// bytes and their "before" twins' bytes. +pub(crate) fn card_stats() -> [u64; 10] { + let mut out = [0u64; 10]; + for (i, stat) in CARD_STATS.iter().enumerate() { + out[i] = stat.swap(0, Ordering::Relaxed); + } + out[7] = CARDED.lock().unwrap_or_else(|e| e.into_inner()).iter().filter(|w| w.strong_count() > 0).count() as u64; + out[8] = CARD_BYTES[0].load(Ordering::Relaxed) + WINDOW_CARD_BYTES.load(Ordering::Relaxed); + out[9] = CARD_BYTES[1].load(Ordering::Relaxed); + out +} + +/// The bytes of the hashes kept on the card for a copy of `size` bytes: 16 +/// for each 64 KiB piece (a copy that does not start on a piece boundary +/// has one piece more). +pub(crate) fn card_hash_bytes(size: u64) -> u64 { + (size / PIECE as u64 + 2) * 16 +} + +/// A buffer of `size` bytes in the card's memory for a title buffer's +/// copy, if the copy is to be there: [`cards`] is on, the size is within +/// [`card_limits`] and below 1 GiB (the compare counts in 32 bits), and the +/// host has what it takes (`Host::card_ready`). +fn card_for(size: u64) -> Option { + if !cards() { + return None; + } + let (least, most) = card_limits(); + if size < least || size >= 1 << 30 { + return None; + } + let host = host()?; + if !host.card_ready() { + return None; + } + // Only while the card has room: with this copy on it, a fifth of the + // budget the system gives us must still be free. Copies are made when + // the world loads, before the textures fill the card; the texture + // queue's own rule (`resource::room`: nine tenths of the budget) counts + // them, so the card's use stays where it was and the textures' share + // shrinks by the copies' bytes, at most `card_limits`' second number. + // (With `card_room_kept_on` the texture queue kept this copy's room + // free, and the copy may go up to the queue's own line.) + let hundredths = if card_room_kept_on() { 97 } else { 80 }; + if let Some([budget, used, ..]) = host.video_memory() + && used + size > budget / 100 * hundredths + { + // Said, with the numbers it was decided by: run 193 made 31 copies + // of 95 and no line named the others. The first 64, then every + // 32nd. + let n = CARD_REFUSED[0].fetch_add(1, Ordering::Relaxed) + 1; + let bytes = CARD_REFUSED[1].fetch_add(size, Ordering::Relaxed) + size; + if n <= 64 || n.is_multiple_of(32) { + tracing::info!( + "no card copy for a title buffer of {} KiB: the card has {} MB in use of a budget of {} MB and a copy is made up to \ + {} MB; the copies made hold {} MB of at most {} MB; {} buffers turned down so far ({} MB), frame {}", + size >> 10, + used >> 20, + budget >> 20, + (budget / 100 * hundredths) >> 20, + CARD_BYTES[0].load(Ordering::Relaxed) >> 20, + most >> 20, + n, + bytes >> 20, + crate::frame::current() + ); + } + return None; + } + if CARD_BYTES[0].fetch_add(size, Ordering::Relaxed) + size > most { + CARD_BYTES[0].fetch_sub(size, Ordering::Relaxed); + return None; + } + let buffer = host.uav_buffer(size); + if buffer.is_none() { + CARD_BYTES[0].fetch_sub(size, Ordering::Relaxed); + } + buffer +} + +/// The most bytes of windows outside buffers whose copies go to the card's +/// memory (`LEONIDA_CARD_WINDOWS_MB`; 0, the default, none). +/// +/// Windows are two thirds of the PC memory the card shares (run 104: 861 +/// windows, 3,552 MB of 5,400), and every draw that takes vertices, indices +/// or constants from the title's own allocator reads them over the bus. +/// Shaders write none of them (run 91: "0.0 MB compared in 0 ranges of +/// windows"), so a window on the card needs only what a card copy has +/// already: the CPU's side takes title memory as before, and what changed +/// in it goes up before each submission. No hashes, no compare, no fetch, +/// unless a shader does declare a write to it one day. +/// +/// A window goes to the card while there is room under this number and +/// while a fifth of the card's budget is free, as title buffers do +/// (`card_for`): textures keep their room, and once they have filled the +/// card later windows stay where they are. The CPU's side stays in the PC's +/// memory, so the memory shared with the card does not shrink by this +/// alone; what moves is what shaders read. +fn window_card_most() -> u64 { + static MOST: std::sync::OnceLock = std::sync::OnceLock::new(); + *MOST.get_or_init(|| { + std::env::var("LEONIDA_CARD_WINDOWS_MB").ok().and_then(|v| v.trim().parse::().ok()).unwrap_or(0) << 20 + }) +} + +/// Bytes alive of windows' card sides ([`window_card_most`]). +static WINDOW_CARD_BYTES: AtomicU64 = AtomicU64::new(0); + +/// A buffer in the card's memory for a window of `size` bytes, if it is to +/// be there ([`window_card_most`]). +fn window_card_for(size: u64) -> Option { + let most = window_card_most(); + if most == 0 || !cards() { + return None; + } + let host = host()?; + if !host.card_ready() { + return None; + } + if let Some([budget, used, ..]) = host.video_memory() + && used + size > budget / 10 * 8 + { + return None; + } + if WINDOW_CARD_BYTES.fetch_add(size, Ordering::Relaxed) + size > most { + WINDOW_CARD_BYTES.fetch_sub(size, Ordering::Relaxed); + return None; + } + let buffer = host.uav_buffer(size); + if buffer.is_none() { + WINDOW_CARD_BYTES.fetch_sub(size, Ordering::Relaxed); + } + buffer +} + +/// The copies in the card's memory whose CPU side changed since they were +/// last asked: each with the changed offsets, in order and joined where +/// they touch. The ranges are taken: the caller copies them to the card's +/// side (`Host::card_before`). +/// +/// With [`relay`], `sent_as` is the number of the send that takes them +/// (`crate::host`'s order of the queue): each range is noted with it, in +/// the same lock that took it, so that a merge of pieces fetched before +/// that send knows the card did not hold these bytes yet +/// ([`Shadow::card_merge_relay`]). Notes of sends that every fetch still to +/// be merged came after are dropped. +pub(crate) fn card_dirty(sent_as: u64) -> Vec<(Arc, Vec<(usize, usize)>)> { + let mut out = Vec::new(); + let mut carded = CARDED.lock().unwrap_or_else(|e| e.into_inner()); + let fetched = RELAY_FETCHED.load(Ordering::Acquire); + carded.retain(|weak| { + let Some(shadow) = weak.upgrade() else { + return false; + }; + let ranges = shadow + .card + .as_ref() + .map(|c| { + let mut dirty = c.dirty.lock().unwrap_or_else(|e| e.into_inner()); + let ranges = std::mem::take(&mut *dirty); + if relay() { + let mut sent = c.sent.lock().unwrap_or_else(|e| e.into_inner()); + sent.retain(|s| s.2 > fetched); + sent.extend(ranges.iter().map(|&(a, b)| (a, b, sent_as))); + } + ranges + }) + .unwrap_or_default(); + if !ranges.is_empty() { + out.push((shadow, joined(ranges))); + } + true + }); + out +} + +/// Ranges in order, those that overlap or touch as one. +fn joined(mut ranges: Vec<(usize, usize)>) -> Vec<(usize, usize)> { + ranges.sort_unstable(); + let mut out: Vec<(usize, usize)> = Vec::with_capacity(ranges.len()); + for (from, to) in ranges { + match out.last_mut() { + Some(last) if from <= last.1 => last.1 = last.1.max(to), + _ => out.push((from, to)), + } + } + out +} + +/// Runs of pieces to hash again (`Host::card_before`), those that overlap +/// or touch as one, in order: every piece of `runs` is in the result once +/// and no other piece is. Ranges sent up lie close together (514 a frame +/// for 87 MB in run 102), and each had a pass of its own over its pieces, +/// so a piece that held several ranges was hashed once for each. +pub(crate) fn joined_piece_runs(mut runs: Vec) -> Vec { + runs.sort_unstable_by_key(|r| r.first); + let mut out: Vec = Vec::with_capacity(runs.len()); + for run in runs { + match out.last_mut() { + Some(last) if run.first <= last.first + last.pieces => { + last.pieces = last.pieces.max(run.first + run.pieces - last.first); + last.to = last.to.max(run.to); + } + _ => out.push(run), + } + } + out +} + +/// A declared range of a copy in the card's memory, as the compare on the +/// card takes it: its offsets in the copy, its first 64 KiB piece (pieces +/// are cut at multiples of 64 KiB of title memory; piece 0 holds offset +/// 0), how many pieces hold it, and where the copy starts in piece 0. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) struct CardSpan { + pub(crate) from: u32, + pub(crate) to: u32, + pub(crate) first: u32, + pub(crate) pieces: u32, + pub(crate) skew: u32, +} + +/// [`CardSpan`] for offsets `[from, to)` (`from < to`) of a copy of title +/// memory from `start` on. +fn card_span_of(start: usize, from: usize, to: usize) -> CardSpan { + let pieces = pieces_of(start, from, to); + CardSpan { + from: from as u32, + to: to as u32, + first: pieces.start as u32, + pieces: pieces.len() as u32, + skew: (start % PIECE) as u32, + } +} + +/// The offsets of piece `i` of `span` that lie in the span, for a copy of +/// `len` bytes of title memory from `start` on: what is fetched and merged +/// of a piece the compare found differing. +fn card_piece_of(start: usize, len: usize, span: &CardSpan, i: u32) -> (usize, usize) { + let (lo, hi) = piece_at(start, len, (span.first + i) as usize); + (lo.max(span.from as usize), hi.min(span.to as usize)) +} + +#[cfg(test)] +mod card_tests { + use super::{CardSpan, PIECE, card_piece_of, card_span_of, joined, joined_piece_runs}; + + /// Joined runs hold every piece of the runs given, once, and no other. + #[test] + fn piece_runs_join_without_losing_or_adding_pieces() { + let run = |first: u32, pieces: u32| CardSpan { + from: first * 65536, + to: (first + pieces) * 65536, + first, + pieces, + skew: 7, + }; + let runs = vec![run(40, 1), run(3, 2), run(4, 1), run(5, 3), run(40, 1), run(9, 1), run(41, 2), run(100, 1)]; + let mut wanted: Vec = runs.iter().flat_map(|r| r.first..r.first + r.pieces).collect(); + wanted.sort_unstable(); + wanted.dedup(); + let joined = joined_piece_runs(runs); + let got: Vec = joined.iter().flat_map(|r| r.first..r.first + r.pieces).collect(); + assert_eq!(got, wanted); + assert_eq!(joined.iter().map(|r| (r.first, r.pieces)).collect::>(), [(3, 5), (9, 1), (40, 3), (100, 1)]); + assert!(joined.iter().all(|r| r.skew == 7)); + assert!(joined_piece_runs(Vec::new()).is_empty()); + } + + /// The offsets the compare's shader takes for a piece (`CARD_COMPARE` + /// in host.rs), before it widens them to 16 bytes. + fn shader_piece(span: &CardSpan, i: u32) -> (u32, u32) { + let piece = span.first + i; + let lo = piece * 65536; + let lo = if lo > span.skew { lo - span.skew } else { 0 }; + let hi = (piece + 1) * 65536 - span.skew; + (lo.max(span.from), hi.min(span.to)) + } + + /// The pieces of a span cover it without gaps, and the shader's + /// arithmetic names the same bytes as ours. + #[test] + fn the_shader_and_the_merge_cut_the_same_pieces() { + for start in [0usize, 4096, PIECE - 16, PIECE, 3 * PIECE + 0x1f00, 0xd_b790_df00] { + let len = 5 * PIECE + 4096; + for (from, to) in [(0, len), (0, 1), (16, PIECE), (PIECE - 4, PIECE + 4), (2 * PIECE, len), (12345, 4 * PIECE + 7)] { + let span = card_span_of(start, from, to); + let mut at = from; + for i in 0..span.pieces { + let (lo, hi) = card_piece_of(start, len, &span, i); + assert_eq!(lo, at, "{start:#x} {from} {to} piece {i}"); + assert!(hi > lo && hi - lo <= PIECE); + assert_eq!(shader_piece(&span, i), (lo as u32, hi as u32), "{start:#x} {from} {to} piece {i}"); + at = hi; + } + assert_eq!(at, to, "{start:#x} {from} {to}"); + } + } + } + + /// The fetch inside flights (`CARD_FETCH` in host.rs) copies each piece + /// from `inflight_piece_from` on: what the merge takes of the piece lies + /// in that slot. + #[test] + fn a_piece_fetched_in_flight_fits_its_slot() { + let slot = crate::host::INFLIGHT_SLOT as usize; + for start in [0usize, 4096, 7, PIECE - 16, PIECE - 3, 3 * PIECE + 0x1f09, 0xd_b790_df00] { + let len = 5 * PIECE + 4096; + for (from, to) in [(0, len), (0, 1), (16, PIECE), (PIECE - 4, PIECE + 4), (2 * PIECE, len), (12345, 4 * PIECE + 7)] { + let span = card_span_of(start, from, to); + for i in 0..span.pieces { + let (lo, hi) = card_piece_of(start, len, &span, i); + let at = crate::host::inflight_piece_from(&span, i); + assert_eq!(at % 16, 0); + assert!(lo >= at && hi - at <= slot, "{start:#x} {from} {to} piece {i}: {lo}..{hi} from {at}"); + } + } + } + } + + /// The slots are a power of two, one per 64 KiB asked, within the + /// shader's 32-bit offsets. + #[test] + fn inflight_slots_are_a_power_of_two() { + use crate::host::{INFLIGHT_SLOT, inflight_slots}; + assert_eq!(inflight_slots(64 << 20), 1024); + assert_eq!(inflight_slots(100 << 20), 1024); + assert_eq!(inflight_slots(1), 1); + assert_eq!(inflight_slots(1 << 20), 16); + let most = inflight_slots(u64::MAX); + assert!(most.is_power_of_two() && u64::from(most) * INFLIGHT_SLOT <= 1 << 32); + } + + /// Tickets drawn and landed in order, the mark raised as the landing + /// raises it (every ticket a landed flight drew), through the counter's + /// wrap with the slots the default gives: no two tickets in the air + /// that got a slot share one, slots are still given after the wrap, and + /// the mark follows the counter. + #[test] + fn inflight_tickets_never_share_a_slot_across_the_wrap() { + use crate::host::{inflight_gets_slot, inflight_raise, inflight_slots}; + let slots = inflight_slots(64 << 20); + let mut landed = u32::MAX - 3000; + let mut next = landed; + // Flights of 1 to 700 flagged pieces, up to three in the air: + // (tickets drawn, those that got a slot). + let mut air: std::collections::VecDeque<(Vec, Vec)> = Default::default(); + let mut after_wrap = 0; + for flight in 0..40u32 { + let drawn: Vec = (0..1 + flight * 37 % 700).map(|i| next.wrapping_add(i)).collect(); + next = next.wrapping_add(drawn.len() as u32); + let slotted: Vec = drawn.iter().copied().filter(|&k| inflight_gets_slot(k, landed, slots)).collect(); + after_wrap += slotted.iter().filter(|&&k| k < 1 << 20).count(); + air.push_back((drawn, slotted)); + let mut used: Vec = air.iter().flat_map(|a| a.1.iter()).map(|k| k % slots).collect(); + let n = used.len(); + used.sort_unstable(); + used.dedup(); + assert_eq!(used.len(), n, "flight {flight}: two tickets in the air share a slot"); + if air.len() == 3 + && let Some((drawn, _)) = air.pop_front() + { + for k in drawn { + landed = inflight_raise(landed, k); + } + } + } + while let Some((drawn, _)) = air.pop_front() { + for k in drawn { + landed = inflight_raise(landed, k); + } + } + assert!(next < 1 << 20, "the counter wrapped"); + assert!(after_wrap > 0, "slots after the wrap"); + assert_eq!(landed, next); + // Raised in wrapping order, never back. + assert_eq!(inflight_raise(u32::MAX - 1, u32::MAX), 0); + assert_eq!(inflight_raise(5, 2), 5); + assert_eq!(inflight_raise(u32::MAX - 1, 3), 4); + assert!(!inflight_gets_slot(3, 4, 8)); + } + + /// Flights 5, 6, 7 in the air with the fetch inside flights: 5 lands + /// the old way with the queue's count at 7. The title's byte that went + /// up in send 7 must still be told apart when 6 lands from its slot + /// (its merge leaves out sends after 6), so send 7's note must outlive + /// the mark (`card_dirty` keeps notes above it, `card_merge_relay` + /// leaves out those above its "fetched after"). + #[test] + fn a_fetch_the_old_way_keeps_the_notes_flights_in_the_air_need() { + use crate::host::fallback_fetched_mark; + let notes = [5u64, 6, 7]; + let mark = fallback_fetched_mark(true, 7, Some(5)); + let kept: Vec = notes.iter().copied().filter(|&s| s > mark).collect(); + assert!(kept.iter().any(|&s| s > 6), "send 7's note was dropped before flight 6 merged"); + assert_eq!(mark, 5); + // Without the switch every later merge fetches after 7: as before. + assert_eq!(fallback_fetched_mark(false, 7, Some(5)), 7); + assert_eq!(fallback_fetched_mark(true, 7, None), 0); + } + + /// Changed ranges are joined where they overlap or touch, and only there. + #[test] + fn ranges_join_where_they_touch() { + assert_eq!(joined(vec![(8, 12), (0, 4), (4, 6), (10, 20), (30, 31)]), [(0, 6), (8, 20), (30, 31)]); + assert!(joined(Vec::new()).is_empty()); + } +} + +/// Whether the copy-back of what shaders wrote runs on a thread of its own, +/// beside the submitting thread and outside the submission lock +/// (`LEONIDA_RELAY=1` or `2`; off by default; not with kept snapshots, +/// [`keeps`]). `crate::host::relay` says what it does; here it changes +/// what a copy keeps: +/// +/// - the ranges shaders may be writing are counted per submission +/// ([`Flights`]): a range two flights declared stays closed to refreshes +/// until both have been copied back; +/// - the merge of what the card wrote never stores into memory the card +/// may be writing ([`merge_piece`]): what it learns goes into title +/// memory and into the copy's reference (the snapshot, or the CPU's side +/// of a copy in the card's memory), under that reference's lock; +/// - what goes up to a copy in the card's memory is numbered +/// ([`card_dirty`]), so that a merge can tell the title's bytes the card +/// had not received from bytes the card wrote. +pub(crate) fn relay() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + // On by default (stage 2, `crate::host::relay_exact`); `LEONIDA_RELAY=0` + // turns it off, `=1` asks for the first stage. + // The crate's own tests run without it unless they ask: several of + // them look at title memory right after a submission, which the + // relay's landing thread may still be writing. + *ON.get_or_init(|| std::env::var("LEONIDA_RELAY").map_or(!cfg!(test), |v| v == "1" || v == "2") && !keeps()) +} + +/// The submission being prepared (its number among those started): what +/// [`Shadow::writing`] counts a declared range for ([`Flights`]). +static PREPARED: AtomicU64 = AtomicU64::new(0); + +/// A submission's preparing begins (`crate::host`, under the submission +/// lock). +pub(crate) fn preparing(number: u64) { + PREPARED.store(number, Ordering::Relaxed); +} + +/// With [`relay`]: the number of the last send of changed ranges to the +/// card (`crate::host`'s order of the queue) that every fetch still to be +/// merged came after. Notes of sends up to it are of no use any more. +static RELAY_FETCHED: AtomicU64 = AtomicU64::new(0); + +/// A fetch sent after send `number` is the oldest one that may still be +/// merged ([`RELAY_FETCHED`]). +pub(crate) fn relay_fetched(number: u64) { + RELAY_FETCHED.fetch_max(number, Ordering::AcqRel); +} + +/// With [`relay`]: how many submissions that are not copied back yet +/// declared each range shaders may be writing (range, count, the last +/// submission that declared it). +/// +/// Without it a range declared by two flights was one entry, and the end +/// of the first flight's copy-back removed it while the second was still +/// writing: the next refresh would have put title bytes over what the +/// second flight's shaders were writing. +#[derive(Default)] +struct Flights(Vec<((usize, usize), u32, u64)>); + +impl Flights { + /// Submission `number` declares `range`: counted once for it, however + /// often it declares it. + fn declare(&mut self, range: (usize, usize), number: u64) { + match self.0.iter_mut().find(|f| f.0 == range) { + Some(f) => { + if f.2 != number { + f.1 += 1; + f.2 = number; + } + } + None => self.0.push((range, 1, number)), + } + } + + /// One submission that declared `ranges` (each once) is copied back: + /// the ranges no other submission still holds. + fn done(&mut self, ranges: &[(usize, usize)]) -> Vec<(usize, usize)> { + let mut free = Vec::new(); + for range in ranges { + match self.0.iter().position(|f| f.0 == *range) { + Some(at) => { + self.0[at].1 = self.0[at].1.saturating_sub(1); + if self.0[at].1 == 0 { + self.0.swap_remove(at); + free.push(*range); + } + } + // Not counted (declared before anything counted): free. + None => free.push(*range), + } + } + free + } +} + +/// The relay's merge of a stretch of a copy ([`relay`]). `now` is what the +/// card's memory holds, read once; `held` is the copy's reference for the +/// stretch (its snapshot, or the CPU's side of a copy in the card's +/// memory): what the card's memory held when it was last looked at; +/// `title` is title memory as just read. Every byte the card changed +/// (`now` differs from `held`) goes into `title` and into `held`; every +/// other byte of both stays as it is, so a byte the title wrote and the +/// card did not keeps the title's value. Whether `title` changed. +/// +/// Nothing is stored into `now`'s source: the card may be writing it for a +/// later flight at this moment, and a store there, even of the value just +/// read, could undo that write. (The merge of a waited-for submission +/// stores every byte of a differing stretch back into the copy.) +fn merge_piece(now: &[u8], held: &mut [u8], title: &mut [u8]) -> bool { + let mut differs = 0u8; + for ((n, h), t) in now.iter().zip(held.iter_mut()).zip(title.iter_mut()) { + let wrote = if *n != *h { 0xffu8 } else { 0 }; + let merged = (*t & !wrote) | (*n & wrote); + differs |= merged ^ *t; + *t = merged; + *h = (*h & !wrote) | (*n & wrote); + } + differs != 0 +} + +/// `[from, to)` without the ranges of `skip`, in order. +pub(crate) fn outside(from: usize, to: usize, mut skip: Vec<(usize, usize)>) -> Vec<(usize, usize)> { + skip.sort_unstable(); + let mut out = Vec::new(); + let mut at = from; + for (a, b) in skip { + if b <= at { + continue; + } + if a >= to { + break; + } + if a > at { + out.push((at, a)); + } + at = at.max(b); + } + if at < to { + out.push((at, to)); + } + out +} + +/// The runs of 4-byte words of title memory (cut on its addresses; +/// `read` and `merged` are of the memory at `address`) that hold a byte in +/// which `merged` differs from `read`, as (offset, bytes) in order to +/// `put`. A shader stores words, so these are what the card wrote; every +/// other byte of `merged` is the title's as it was read. +fn word_runs(address: usize, read: &[u8], merged: &[u8], mut put: impl FnMut(usize, usize)) { + let n = read.len().min(merged.len()); + let mut i = 0; + while i < n { + // Equal bytes are passed over, 32 at a time while they last. + match first_difference(&read[i..n], &merged[i..n]) { + Some(d) => i += d, + None => break, + } + // From the word that holds this byte (or the stretch's first + // byte) to the end of the last word in a row that holds one. + let first = i - ((address + i) & 3).min(i); + let mut end = first; + while end < n { + let word = (((address + end) | 3) + 1 - address).min(n); + if read[end..word] == merged[end..word] { + break; + } + end = word; + } + put(first, end - first); + i = end; + } +} + +/// Whether the merges that write a stretch of title memory back +/// ([`Shadow::relay_merge`], [`Shadow::card_merge`], +/// [`Shadow::card_merge_relay`]) look, right before that write, for title +/// bytes it is about to put back to older values (`LEONIDA_MERGE_RACE=1`; +/// off by default). Logging only: [`merge_race`]. +fn merge_race_on() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("LEONIDA_MERGE_RACE").is_some_and(|v| v == "1")) +} + +/// [`merge_race`]'s sums. Of frame `frame`, and in `total` since the +/// start: stretches written back, their bytes, title bytes put back to +/// older values, bytes the title and the card both changed, stretches with +/// either, the runs a write of the card's words alone makes +/// ([`word_runs`]) and their bytes. `said`: the frame's first stretches +/// with either. `quiet`: frames since the last line. +struct MergeRace { + frame: u64, + now: [u64; 7], + said: Vec, + total: [u64; 7], + quiet: u64, +} + +static MERGE_RACE: Mutex = + Mutex::new(MergeRace { frame: 0, now: [0; 7], said: Vec::new(), total: [0; 7], quiet: 0 }); + +/// With [`merge_race_on`], right before a merge writes `merged` over title +/// memory at `address` (a stretch of the copy of the title buffer `copy`: +/// start and bytes): title memory is read once more and compared with +/// `read`, what the merge read of it before. A byte that changed in +/// between and that the write-back stores with its value as first read +/// (the card did not change it) is a title byte put back to an older +/// value; one the write-back stores with the card's byte is one both +/// changed. Only bytes the write-back stores are looked at. Summed per +/// frame; a line for every frame that has any, and one every 100 frames +/// whatever it holds, so that "none" is said, not assumed. +/// +/// A lower bound: a title write that lands after this read (while the +/// write-back itself runs) is not seen, nor one that wrote a byte and then +/// its old value again. Costs one more read and two compares of every +/// stretch written back, on the thread that merges. +fn merge_race(read: Option<&[u8]>, copy: (u64, u64), address: usize, merged: &[u8], which: &'static str) { + if !merge_race_on() { + return; + } + let Some(read) = read else { + return; + }; + let n = read.len().min(merged.len()); + let (read, merged) = (&read[..n], &merged[..n]); + let mut runs: Vec<(usize, usize)> = Vec::new(); + word_runs(address, read, merged, |off, len| runs.push((off, len))); + let whole = [(0, n)]; + let looked: &[(usize, usize)] = &whole; + let mut again = vec![0u8; n]; + let (mut put_back, mut both, mut first) = (0u64, 0u64, None); + if crate::host::read_into(address as *const u8, &mut again) { + for &(off, len) in looked { + for i in off..off + len { + if again[i] == read[i] || again[i] == merged[i] { + continue; + } + if merged[i] == read[i] { + put_back += 1; + first.get_or_insert(i); + } else { + both += 1; + } + } + } + } + let frame = crate::frame::current(); + let mut race = MERGE_RACE.lock().unwrap_or_else(|e| e.into_inner()); + if race.frame != frame { + race.quiet += 1; + if race.now[4] > 0 || race.quiet >= 100 { + tracing::info!( + frame = race.frame, + stretches = race.now[0], + stretch_bytes = race.now[1], + put_back = race.now[2], + both_changed = race.now[3], + stretches_hit = race.now[4], + word_runs = race.now[5], + word_run_bytes = race.now[6], + stretches_since_start = race.total[0], + stretch_bytes_since_start = race.total[1], + put_back_since_start = race.total[2], + both_changed_since_start = race.total[3], + stretches_hit_since_start = race.total[4], + word_runs_since_start = race.total[5], + word_run_bytes_since_start = race.total[6], + first = ?race.said, + "merge race: title bytes that changed between a merge's read of title memory and its write-back of what shaders wrote, in this frame (LEONIDA_MERGE_RACE=1)" + ); + race.quiet = 0; + } + race.frame = frame; + race.now = [0; 7]; + race.said.clear(); + } + let hit = u64::from(put_back + both > 0); + let run_bytes: u64 = runs.iter().map(|r| r.1 as u64).sum(); + let add = [1, n as u64, put_back, both, hit, runs.len() as u64, run_bytes]; + for (i, v) in add.iter().enumerate() { + race.now[i] += v; + race.total[i] += v; + } + if hit > 0 && race.said.len() < 8 { + race.said.push(format!( + "{which}: copy {:#x}+{:#x} stretch {address:#x}+{n:#x}: {put_back} put back (first at {:#x}), {both} both changed", + copy.0, + copy.1, + address + first.unwrap_or(0) + )); + } +} + +#[cfg(test)] +mod relay_tests { + use super::{Flights, changed_runs, merge_piece, outside}; + + /// A range two flights declared is free only when both are done, in + /// either order; a submission that declares it many times counts once. + #[test] + fn a_range_stays_closed_until_every_flight_that_declared_it_is_done() { + let (a, b) = ((0x1000, 0x2000), (0x1800, 0x3000)); + let mut flights = Flights::default(); + for _ in 0..3 { + flights.declare(a, 7); + } + flights.declare(b, 7); + flights.declare(a, 8); + // Flight 7 lands: `a` is still flight 8's, `b` was only flight 7's. + assert_eq!(flights.done(&[a, b]), vec![b]); + // Declared again meanwhile by a third. + flights.declare(a, 9); + assert_eq!(flights.done(&[a]), vec![]); + assert_eq!(flights.done(&[a]), vec![a]); + assert!(flights.0.is_empty()); + // The later flight first: the same. + flights.declare(a, 1); + flights.declare(a, 2); + assert_eq!(flights.done(&[a]), vec![]); + assert_eq!(flights.done(&[a]), vec![a]); + // A range never counted is free at once. + assert_eq!(flights.done(&[b]), vec![b]); + } + + /// The merge moves exactly the bytes the card changed, into title + /// memory and into the reference, and stores nothing else. + #[test] + fn the_merge_stores_only_what_the_card_changed() { + let held0: Vec = (0..200u32).map(|i| (i * 5 + 1) as u8).collect(); + let mut now = held0.clone(); + for at in [0usize, 3, 4, 5, 64, 199] { + now[at] ^= 0x33; + } + // The title wrote other bytes meanwhile, and one the card wrote too. + let mut title = held0.clone(); + for at in [1usize, 5, 100] { + title[at] = 0xee; + } + let title0 = title.clone(); + let mut held = held0.clone(); + assert!(merge_piece(&now, &mut held, &mut title)); + for at in 0..200 { + if now[at] != held0[at] { + assert_eq!((title[at], held[at]), (now[at], now[at]), "the card's byte at {at}"); + } else { + assert_eq!((title[at], held[at]), (title0[at], held0[at]), "untouched at {at}"); + } + } + // Again with nothing new: nothing changes and nothing is reported. + let (title1, held1) = (title.clone(), held.clone()); + assert!(!merge_piece(&now, &mut held, &mut title)); + assert_eq!((title, held), (title1, held1)); + } + + #[test] + fn ranges_are_cut_out() { + assert_eq!(outside(10, 50, vec![]), vec![(10, 50)]); + assert_eq!(outside(10, 50, vec![(0, 10), (50, 60)]), vec![(10, 50)]); + assert_eq!(outside(10, 50, vec![(30, 35), (0, 12), (34, 40), (48, 99)]), vec![(12, 30), (40, 48)]); + assert_eq!(outside(10, 50, vec![(0, 99)]), vec![]); + } + + /// A model of a copy in the PC's memory under the relay: the card + /// writes `copy` directly; `snap` is the snapshot; `title` is title + /// memory. Flight A and flight B declare overlapping ranges and both + /// are in the air; the title's CPU writes in between and its bytes are + /// put in beside the flights' (`merge_under_writes`: into the copy and + /// the snapshot); A lands while B is still writing; then B lands. + #[test] + fn two_flights_overlapping_ranges_and_a_cpu_write_in_between() { + const N: usize = 64; + let base: Vec = (0..N as u32).map(|i| i as u8).collect(); + let (mut copy, mut title) = (base.clone(), base.clone()); + // A declares [0, 40), B declares [24, 64): each byte's snapshot is + // taken when the first range that holds it is declared. + let (a, b) = ((0usize, 40usize), (24usize, 64usize)); + let mut snap = base.clone(); + // The card runs A: writes 4..12 and 30..34. + for at in (4..12).chain(30..34) { + copy[at] = 0xa0; + } + // The title's CPU writes 8..10 (over A's bytes), 20 and 50, after + // A's refresh: the next submission's preparing finds them against + // the snapshot and puts them in, into the copy and the snapshot. + for at in [8usize, 9, 20, 50] { + title[at] = 0x77; + } + for (at, n) in changed_runs(&title, &snap) { + copy[at..at + n].copy_from_slice(&title[at..at + n]); + snap[at..at + n].copy_from_slice(&title[at..at + n]); + } + // The card starts B: it has written 32..36 so far, over A's 32..34. + for at in 32..36 { + copy[at] = 0xb0; + } + // A lands (B still on the card): its range is merged. The copy is + // read once and not written. + let seen = copy.clone(); + { + let mut t = title[a.0..a.1].to_vec(); + assert!(merge_piece(&seen[a.0..a.1], &mut snap[a.0..a.1], &mut t)); + title[a.0..a.1].copy_from_slice(&t); + } + assert_eq!(copy, seen, "the merge stores nothing into the copy"); + // A's bytes are in title memory, except where the title wrote + // after A's shaders did (8, 9: the title's); B's first bytes came + // along; nothing of B's range beyond A's was touched. + for at in (4..8).chain(10..12).chain(30..32) { + assert_eq!(title[at], 0xa0, "A's byte at {at}"); + } + assert_eq!((title[8], title[9], title[20], title[50]), (0x77, 0x77, 0x77, 0x77)); + for at in 32..36 { + assert_eq!(title[at], 0xb0, "B's byte so far at {at}"); + } + // The card finishes B: 36..44. + for at in 36..44 { + copy[at] = 0xb1; + } + // The title's CPU writes 40 after B's shader did: found against + // the snapshot at the next preparing, which is before B lands. + title[40] = 0x55; + for (at, n) in changed_runs(&title[b.0..b.1], &snap[b.0..b.1]) { + let at = at + b.0; + copy[at..at + n].copy_from_slice(&title[at..at + n]); + snap[at..at + n].copy_from_slice(&title[at..at + n]); + } + // B lands. + let seen = copy.clone(); + { + let mut t = title[b.0..b.1].to_vec(); + assert!(merge_piece(&seen[b.0..b.1], &mut snap[b.0..b.1], &mut t)); + title[b.0..b.1].copy_from_slice(&t); + } + // B's results are there, never replaced by A's older ones. + for at in 32..36 { + assert_eq!(title[at], 0xb0); + } + for at in (36..40).chain(41..44) { + assert_eq!(title[at], 0xb1, "B's byte at {at}"); + } + assert_eq!(title[40], 0x55, "the title wrote it last"); + // In the declared ranges the copy, the snapshot and title memory + // now agree byte for byte: nothing is left to hand back, and + // nothing was lost. + assert_eq!(copy[a.0..b.1], title[a.0..b.1]); + assert_eq!(snap[a.0..b.1], title[a.0..b.1]); + // A third merge finds nothing. + let mut t = title.clone(); + assert!(!merge_piece(©, &mut snap, &mut t)); + } + + /// A model of a copy in the card's memory under the relay: `card` is + /// the card's side, `cpu` the CPU's side, `title` title memory. The + /// title's changed bytes go into the CPU's side at once and up to the + /// card with a later send; pieces fetched before that send must not + /// take the card's older bytes there for something the card wrote. + #[test] + fn title_bytes_not_yet_on_the_card_are_not_taken_for_shader_writes() { + const N: usize = 48; + let base: Vec = (0..N as u32).map(|i| (i + 100) as u8).collect(); + let (mut card, mut cpu, mut title) = (base.clone(), base.clone(), base.clone()); + // Flight A's shaders write 10..14 on the card. + for at in 10..14 { + card[at] = 0xa0; + } + // The title's CPU writes 12 (over A's) and 30; the preparing of + // the next submission puts both into the CPU's side and notes them + // to go up (send 5). They are not on the card yet. + title[12] = 0x77; + title[30] = 0x78; + let mut noted = Vec::new(); + for (at, n) in changed_runs(&title, &cpu) { + cpu[at..at + n].copy_from_slice(&title[at..at + n]); + noted.push((at, at + n, 5u64)); + } + // A's pieces are fetched after send 4, before send 5: the fetch + // holds A's bytes and the card's old bytes at 12 and 30. + let fetched = card.clone(); + let fetched_after = 4u64; + // Send 5 goes up behind it. + for &(a, b, _) in ¬ed { + card[a..b].copy_from_slice(&cpu[a..b]); + } + // The merge leaves out what went up after the fetch. + let skip: Vec<(usize, usize)> = noted.iter().filter(|s| s.2 > fetched_after).map(|s| (s.0, s.1)).collect(); + let mut changed = false; + for (a, b) in outside(0, N, skip) { + let mut t = title[a..b].to_vec(); + changed |= merge_piece(&fetched[a..b], &mut cpu[a..b], &mut t); + title[a..b].copy_from_slice(&t); + } + assert!(changed); + // A's bytes arrived; the title's two writes stand, in title memory + // and on both sides of the copy. + for at in [10usize, 11, 13] { + assert_eq!((title[at], cpu[at]), (0xa0, 0xa0)); + } + assert_eq!((title[12], cpu[12], card[12]), (0x77, 0x77, 0x77)); + assert_eq!((title[30], cpu[30], card[30]), (0x78, 0x78, 0x78)); + assert_eq!(card, cpu); + assert_eq!(card, title); + // Without the leaving out, the card's old byte at 30 would have + // been taken for a shader write and put over the title's. + let mut wrong_title = title.clone(); + let mut wrong_cpu = cpu.clone(); + merge_piece(&fetched, &mut wrong_cpu, &mut wrong_title); + assert_eq!(wrong_title[30], base[30]); + } +} + +/// Snapshot memory kept for reuse (already touched, so no page faults). +static POOL: Mutex>> = Mutex::new(Vec::new()); + +/// An empty buffer with room for `n` bytes, from the pool if it has one +/// of about that size: a small copy's snapshot took the 174 MB buffer kept +/// for the big heap's, which then got another, until eight of them were +/// reserved (1.4 GB in run 24). +fn pooled(n: usize) -> Vec { + let mut pool = POOL.lock().unwrap_or_else(|e| e.into_inner()); + let most = n.saturating_mul(4).max(1 << 20); + let fit = pool + .iter() + .enumerate() + .filter(|(_, v)| v.capacity() >= n && v.capacity() <= most) + .min_by_key(|(_, v)| v.capacity()) + .map(|(i, _)| i); + let mut v = match fit { + Some(i) => pool.swap_remove(i), + None => Vec::with_capacity(n), + }; + v.clear(); + v +} + +/// Returns a snapshot buffer to the pool: at most 8 kept, the largest, and +/// of those the largest one and the next ones up to `KEPT` bytes in all. +fn give_back(v: Vec) { + const KEPT: usize = 512 << 20; + let mut pool = POOL.lock().unwrap_or_else(|e| e.into_inner()); + pool.push(v); + pool.sort_by_key(|v| std::cmp::Reverse(v.capacity())); + pool.truncate(8); + let (mut seen, mut total) = (0, 0usize); + pool.retain(|v| { + seen += 1; + total = total.saturating_add(v.capacity()); + seen == 1 || total <= KEPT + }); +} + +const NOT_WATCHED: u8 = 2; + +// Fixed-size equality compiles to two SIMD comparisons on Windows x64. +// Only the first or last unequal chunk needs a byte-wise search. +const DIFF_CHUNK: usize = 32; + +/// Where `a` and `b` first differ within their common length. +fn first_difference(a: &[u8], b: &[u8]) -> Option { + let len = a.len().min(b.len()); + let (a_chunks, a_tail) = a[..len].as_chunks::(); + let (b_chunks, b_tail) = b[..len].as_chunks::(); + let (offset, a, b) = match a_chunks.iter().zip(b_chunks).position(|(x, y)| x != y) { + Some(i) => (i * DIFF_CHUNK, &a_chunks[i][..], &b_chunks[i][..]), + None => (len - a_tail.len(), a_tail, b_tail), + }; + a.iter().zip(b).position(|(x, y)| x != y).map(|i| offset + i) +} + +/// Where `a` and `b` last differ within their common length. +fn last_difference(a: &[u8], b: &[u8]) -> Option { + let len = a.len().min(b.len()); + let (a_chunks, a_tail) = a[..len].as_chunks::(); + let (b_chunks, b_tail) = b[..len].as_chunks::(); + if let Some(i) = a_tail.iter().zip(b_tail).rposition(|(x, y)| x != y) { + return Some(len - a_tail.len() + i); + } + let chunk = a_chunks.iter().zip(b_chunks).rposition(|(x, y)| x != y)?; + a_chunks[chunk] + .iter() + .zip(&b_chunks[chunk]) + .rposition(|(x, y)| x != y) + .map(|i| chunk * DIFF_CHUNK + i) +} + +#[cfg(test)] +mod difference_tests { + use super::{first_difference, last_difference}; + + /// The chunk searches agree with a byte-wise scan across chunk boundaries. + #[test] + fn differences_are_found_as_byte_by_byte() { + let base: Vec = (0..98u32).map(|i| (i * 7 + 3) as u8).collect(); + for len in [0, 1, 31, 32, 33, 63, 64, 65, 97] { + let a = &base[1..1 + len]; + let same = a.to_vec(); + assert_eq!(first_difference(&same, a), None); + assert_eq!(last_difference(&same, a), None); + for at in 0..len { + for other in at..len { + let mut b = a.to_vec(); + b[at] ^= 0x80; + b[other] ^= 0x01; + let first = a.iter().zip(&b).position(|(x, y)| x != y); + let last = a.iter().zip(&b).rposition(|(x, y)| x != y); + assert_eq!(first_difference(a, &b), first, "{len} {at} {other}"); + assert_eq!(last_difference(a, &b), last, "{len} {at} {other}"); + } + } + } + } + + #[test] + fn differences_ignore_bytes_past_the_shorter_slice() { + let a = [0; 65]; + let mut b = [0; 67]; + b[65] = 1; + assert_eq!(first_difference(&a, &b), None); + assert_eq!(last_difference(&b, &a), None); + b[32] = 1; + b[64] = 1; + assert_eq!(first_difference(&b, &a), Some(32)); + assert_eq!(last_difference(&a, &b), Some(64)); + } +} + +/// The unit shader writes are looked for and put back in. +const PIECE: usize = 64 << 10; + +/// Copies `len` bytes, on several threads if they are many: a snapshot of +/// the world's big heap is 100-170 MB per submission, 2-4 GB a frame, and +/// one thread copies some 8 GB/s. +/// +/// # Safety +/// Both ranges are valid for `len` bytes and do not overlap. +unsafe fn copy_wide(src: *const u8, dst: *mut u8, len: usize) { + const PER_THREAD: usize = 16 << 20; + let threads = (len / PER_THREAD).clamp(1, 6); + if threads == 1 { + // SAFETY: the caller's. + unsafe { std::ptr::copy_nonoverlapping(src, dst, len) }; + return; + } + let (src, dst, each) = (src as usize, dst as usize, len.div_ceil(threads)); + std::thread::scope(|s| { + for i in 0..threads { + let at = (i * each).min(len); + let n = each.min(len - at); + s.spawn(move || { + // SAFETY: a part of the caller's ranges. + unsafe { std::ptr::copy_nonoverlapping((src + at) as *const u8, (dst + at) as *mut u8, n) }; + }); + } + }); +} + +/// Whether the snapshots of a submission's shader-written ranges, and the +/// compare that finds what the shaders wrote, run on several threads +/// across ranges (`LEONIDA_WIDE_BACK=1`; off by default). +/// +/// Both ran range by range on the submitting thread, a range on several +/// threads only if it was 16 MiB or more. The ranges left on the CPU's side +/// since the big buffers went to the card are small and many: in run 86, +/// 7,024 declared ranges a frame, 375 MB of them compared after the card +/// ran in 563 pieces of work, none of 16 MiB: 51 ms a frame of snapshots +/// and 35 ms of comparing, one thread, bound by one core's memory speed. +/// +/// With the switch a submission's snapshots are noted as it is prepared +/// and taken together when its refreshes are done, just before it goes to +/// the card ([`take_snapshots`]), and the compares of everything declared +/// run together after the card ([`find_all`]), both cut into pieces of +/// work of about 1 MiB for a few threads that are kept ([`wide`]). The +/// bytes taken and the bytes compared are the same ones: a range's bytes +/// cannot change between the moment it is declared and the end of the +/// preparing (a declared range is left alone by every refresh, the title's +/// own copies write title memory and not the copy, and the card runs the +/// lists only afterwards). +pub(crate) fn wide_back() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + // On by default; `LEONIDA_WIDE_BACK=0` turns it off. + *ON.get_or_init(|| std::env::var_os("LEONIDA_WIDE_BACK").is_none_or(|v| v != "0")) +} + +type Job = Box; + +/// Threads kept for [`wide`]: what they are to do, and the word that there +/// is something. +struct Workers { + jobs: Mutex>, + more: std::sync::Condvar, +} + +fn workers() -> &'static Workers { + static WORKERS: std::sync::OnceLock = std::sync::OnceLock::new(); + static STARTED: std::sync::Once = std::sync::Once::new(); + let workers = WORKERS.get_or_init(|| Workers { + jobs: Mutex::new(std::collections::VecDeque::new()), + more: std::sync::Condvar::new(), + }); + STARTED.call_once(|| { + let n = std::thread::available_parallelism().map_or(4, |n| n.get() / 4).clamp(2, 6); + for i in 0..n { + let _ = std::thread::Builder::new().name(format!("leonida-wide-{i}")).spawn(move || { + let workers = WORKERS.get().expect("made above"); + loop { + let job = { + let mut jobs = workers.jobs.lock().unwrap_or_else(|e| e.into_inner()); + loop { + if let Some(job) = jobs.pop_front() { + break job; + } + jobs = workers.more.wait(jobs).unwrap_or_else(|e| e.into_inner()); + } + }; + job(); + } + }); + } + }); + workers +} + +/// Runs `jobs` on the kept threads and on this one, and returns when all +/// of them are done. The jobs copy and compare memory; they do not panic. +fn wide(jobs: Vec) { + if jobs.len() < 2 { + for job in jobs { + job(); + } + return; + } + let workers = workers(); + let left = Arc::new((Mutex::new(jobs.len()), std::sync::Condvar::new())); + { + let mut queue = workers.jobs.lock().unwrap_or_else(|e| e.into_inner()); + for job in jobs { + let left = left.clone(); + queue.push_back(Box::new(move || { + job(); + let mut n = left.0.lock().unwrap_or_else(|e| e.into_inner()); + *n -= 1; + if *n == 0 { + left.1.notify_all(); + } + })); + } + } + workers.more.notify_all(); + loop { + let job = workers.jobs.lock().unwrap_or_else(|e| e.into_inner()).pop_front(); + match job { + Some(job) => job(), + None => break, + } + } + let mut n = left.0.lock().unwrap_or_else(|e| e.into_inner()); + while *n > 0 { + n = left.1.wait(n).unwrap_or_else(|e| e.into_inner()); + } +} + +/// [`wide`], for the host's own work on host copies (a submission's +/// refreshes, the merge of what shaders wrote to card copies). +pub(crate) fn wide_run(jobs: Vec>) { + wide(jobs); +} + +/// About this many bytes to a piece of work for [`wide`]. +const WIDE_JOB: usize = 1 << 20; + +/// With [`wide_back`]: the snapshots noted while a submission is prepared +/// (from, to, bytes), taken by [`take_snapshots`]. +static SNAPS: Mutex> = Mutex::new(Vec::new()); + +/// With [`wide_back`], when a submission's refreshes are done and before +/// its lists go to the card: takes the snapshots [`Shadow::writing`] noted. +/// Nothing to do without the switch. +pub(crate) fn take_snapshots() { + let snaps = std::mem::take(&mut *SNAPS.lock().unwrap_or_else(|e| e.into_inner())); + if snaps.is_empty() { + return; + } + wide(copy_jobs(snaps)); +} + +/// `copies` (from, to, bytes) as pieces of work of about [`WIDE_JOB`] +/// bytes each: long ones cut, short ones together. +fn copy_jobs(copies: Vec<(usize, usize, usize)>) -> Vec { + let mut jobs: Vec = Vec::new(); + let mut group: Vec<(usize, usize, usize)> = Vec::new(); + let mut bytes = 0; + let flush = |group: &mut Vec<(usize, usize, usize)>, jobs: &mut Vec| { + let group = std::mem::take(group); + if !group.is_empty() { + jobs.push(Box::new(move || { + for (src, dst, len) in group { + // SAFETY: the caller's ranges: a host copy's mapping and + // its snapshot, which do not overlap. + unsafe { std::ptr::copy_nonoverlapping(src as *const u8, dst as *mut u8, len) }; + } + })); + } + }; + for (src, dst, len) in copies { + let mut at = 0; + while at < len { + let n = (WIDE_JOB - bytes).min(len - at); + group.push((src + at, dst + at, n)); + at += n; + bytes += n; + if bytes >= WIDE_JOB { + flush(&mut group, &mut jobs); + bytes = 0; + } + } + } + flush(&mut group, &mut jobs); + jobs +} + +/// With [`wide_back`]: for each of `work` (a copy not in the card's memory +/// and a range `[address, end)` its shaders may have written, declared and +/// not yet done), the 64 KiB pieces that differ from the snapshot, as +/// [`Shadow::copy_back_with`] takes them; found on several threads. +pub(crate) fn find_all(work: &[(Arc, usize, usize)]) -> Vec> { + let scans = work + .iter() + .map(|(shadow, address, end)| { + let (from, to) = shadow.inside(*address, end.saturating_sub(*address)); + // The snapshot's memory stays until the range is done with + // (`copy_back_done`), which comes after this. + match shadow.before.lock().unwrap_or_else(|e| e.into_inner()).as_ref() { + Some(before) => (shadow.data as usize, before.as_ptr() as usize, shadow.start as usize, from, to), + None => (0, 0, 0, 0, 0), + } + }) + .collect(); + find_pieces(scans) +} + +/// For each of `scans` (where a copy's bytes are, where its snapshot's +/// are, the title address the copy starts at, offsets from and to): the +/// 64 KiB pieces (cut at multiples of 64 KiB of title memory, as +/// [`Shadow::differing`] cuts them) of `[from, to)` whose bytes differ, as +/// (offset, bytes) in order. On several threads ([`wide`]), in pieces of +/// work of about [`WIDE_JOB`] bytes that hold whole pieces. +fn find_pieces(scans: Vec<(usize, usize, usize, usize, usize)>) -> Vec> { + // What a job finds: (which scan, its place among that scan's jobs, the + // pieces). + type Found = Vec<(usize, usize, Vec<(usize, usize)>)>; + // A job's part of a scan: the scan, then which and place. + type Part = (usize, usize, usize, usize, usize, usize, usize); + let found: Arc> = Arc::default(); + let mut jobs: Vec = Vec::new(); + let mut group: Vec = Vec::new(); + let mut bytes = 0; + let flush = |group: &mut Vec, jobs: &mut Vec| { + let group = std::mem::take(group); + if group.is_empty() { + return; + } + let found = found.clone(); + jobs.push(Box::new(move || { + let mut mine: Found = Vec::with_capacity(group.len()); + for (data, before, start, from, to, which, place) in group { + let mut pieces = Vec::new(); + let mut at = from; + while at < to { + let n = (PIECE - (start + at) % PIECE).min(to - at); + // SAFETY: inside the copy's mapping and its snapshot + // (which holds the copy's bytes at the copy's offsets); + // nothing writes either while a submission's results + // are compared. + let (now, old) = unsafe { + ( + std::slice::from_raw_parts((data + at) as *const u8, n), + std::slice::from_raw_parts((before + at) as *const u8, n), + ) + }; + if now != old { + pieces.push((at, n)); + } + at += n; + } + mine.push((which, place, pieces)); + } + found.lock().unwrap_or_else(|e| e.into_inner()).extend(mine); + })); + }; + let count = scans.len(); + for (which, (data, before, start, from, to)) in scans.into_iter().enumerate() { + let (mut at, mut place) = (from, 0); + while at < to { + // Cut where pieces end, so that every job sees whole pieces. + let room = (WIDE_JOB - bytes).max(PIECE); + let mut next = (at + room).min(to); + if next < to { + next -= (start + next) % PIECE; + if next <= at { + next = (at + PIECE - (start + at) % PIECE).min(to); + } + } + group.push((data, before, start, at, next, which, place)); + bytes += next - at; + place += 1; + at = next; + if bytes >= WIDE_JOB { + flush(&mut group, &mut jobs); + bytes = 0; + } + } + } + flush(&mut group, &mut jobs); + wide(jobs); + let mut found = std::mem::take(&mut *found.lock().unwrap_or_else(|e| e.into_inner())); + found.sort_unstable_by_key(|f| (f.0, f.1)); + let mut out = vec![Vec::new(); count]; + for (which, _, pieces) in found { + out[which].extend(pieces); + } + out +} + +/// Since the last frame-rate line, of the shader-written ranges looked for +/// on the CPU (copies not in the card's memory): bytes snapshotted in +/// windows outside buffers and in title buffers' copies; bytes compared in +/// windows, in buffers' copies, and of those in copies of 1 MiB or more; +/// ranges compared in windows and in buffers' copies. +static BACK_CLASS: [AtomicU64; 7] = [const { AtomicU64::new(0) }; 7]; + +/// For the frame-rate line: where the CPU's search for shader writes goes +/// (per frame). A copy of a title buffer can go to the card's memory, +/// where the card does the search (`LEONIDA_CARD_BUFFERS_MIN_MB`); a +/// window outside buffers cannot as the code stands. +pub(crate) fn back_line(frames: f64) { + let c: Vec = BACK_CLASS.iter().map(|c| c.swap(0, Ordering::Relaxed) as f64 / frames).collect(); + if c.iter().all(|&v| v == 0.0) { + return; + } + let mb = |v: f64| v / (1 << 20) as f64; + tracing::info!( + "shader writes looked for on the CPU per frame: {:.1} MB compared in {:.0} ranges of windows outside buffers ({:.1} MB \ + snapshotted), {:.1} MB in {:.0} ranges of title buffers' copies ({:.1} MB snapshotted), of them {:.1} MB in copies \ + of 1 MiB or more (LEONIDA_CARD_BUFFERS_MIN_MB=1 would have the card look there)", + mb(c[2]), + c[5], + mb(c[0]), + mb(c[3]), + c[6], + mb(c[1]), + mb(c[4]), + ); +} + +#[cfg(test)] +mod wide_tests { + use super::{Job, PIECE, WIDE_JOB, copy_jobs, find_pieces, wide}; + use std::sync::Arc; + use std::sync::atomic::{AtomicUsize, Ordering}; + + /// Every job runs once, however many there are, and `wide` returns + /// only when all have. + #[test] + fn all_jobs_run_before_wide_returns() { + for n in [0usize, 1, 2, 7, 300] { + let ran = Arc::new(AtomicUsize::new(0)); + let jobs: Vec = (0..n) + .map(|i| { + let ran = ran.clone(); + Box::new(move || { + ran.fetch_add(i + 1, Ordering::Relaxed); + }) as Job + }) + .collect(); + wide(jobs); + assert_eq!(ran.load(Ordering::Relaxed), n * (n + 1) / 2, "{n} jobs"); + } + } + + /// Copies cut into jobs copy every byte once: long ones, short ones + /// and empty ones. + #[test] + fn copies_cut_into_jobs_copy_the_same_bytes() { + let len = 3 * WIDE_JOB + 12345; + let src: Vec = (0..len).map(|i| (i * 31 + i / 977) as u8).collect(); + let mut dst = vec![0u8; len]; + let (s, d) = (src.as_ptr() as usize, dst.as_mut_ptr() as usize); + // Ranges of the buffer, each to the same offsets of the other. + let cuts = [0, 1, 1, 4096, 70_000, WIDE_JOB + 3, 2 * WIDE_JOB + 3, 2 * WIDE_JOB + 9, len]; + let copies: Vec<(usize, usize, usize)> = cuts.windows(2).map(|w| (s + w[0], d + w[0], w[1] - w[0])).collect(); + let jobs = copy_jobs(copies); + assert!(jobs.len() >= 3); + wide(jobs); + assert!(src == dst); + } + + /// The pieces found on several threads are the ones a walk piece by + /// piece finds, for copies that start anywhere in a 64 KiB piece of + /// title memory and ranges that start and end anywhere. + #[test] + fn pieces_found_wide_are_those_found_one_by_one() { + let len = 5 * WIDE_JOB / 2 + 777; + let old: Vec = (0..len).map(|i| (i * 7 + i / 513) as u8).collect(); + let mut now = old.clone(); + // Changes: single bytes at piece edges, a run across two pieces, + // the last byte, and nothing in between. + for at in [0usize, 1, PIECE - 1, PIECE, 3 * PIECE + 5, WIDE_JOB - 1, WIDE_JOB, WIDE_JOB + PIECE / 2, 2 * WIDE_JOB + 9, len - 1] { + now[at] ^= 0x5a; + } + for byte in &mut now[9 * PIECE - 40..9 * PIECE + 40] { + *byte ^= 0x01; + } + let (data, before) = (now.as_ptr() as usize, old.as_ptr() as usize); + let mut scans = Vec::new(); + let mut wanted = Vec::new(); + for start in [0usize, 4096, PIECE - 16, 0xd_b790_df00] { + for (from, to) in [(0, len), (0, 1), (1, 2), (PIECE - 1, PIECE + 1), (3 * PIECE, 3 * PIECE), (12345, len - 1), (WIDE_JOB - 3, 2 * WIDE_JOB + 10)] { + scans.push((data, before, start, from, to)); + let mut pieces = Vec::new(); + let mut at = from; + while at < to { + let n = (PIECE - (start + at) % PIECE).min(to - at); + if now[at..at + n] != old[at..at + n] { + pieces.push((at, n)); + } + at += n; + } + wanted.push(pieces); + } + } + // A scan of nothing (a range whose snapshot is gone). + scans.push((0, 0, 0, 0, 0)); + wanted.push(Vec::new()); + assert_eq!(find_pieces(scans), wanted); + } +} + +/// What [`Shadow::copy_back`] does with a piece that differs from the +/// snapshot: `host` is the copy's bytes there, `old` the snapshot's. From +/// the first byte that differs to the last, title memory is read into +/// `title` (scratch, sized to that stretch) by `read` (the stretch's offset +/// in the piece, where to), the GPU's bytes are put in and `host` takes the +/// result. The stretch's offset in the piece and its length if that changed +/// title memory; none if nothing differs or title memory is not there. +/// `runs` takes the runs of the stretch (offsets into `title`, lengths) +/// whose bytes are the GPU's and differ from the title's as read: only +/// those are to be written, so a title write that lands between the read +/// and the write elsewhere in the stretch stays (upstream VIctory #2009). +/// `mask` is scratch. +fn back_piece( + host: &mut [u8], + old: &[u8], + title: &mut Vec, + mask: &mut Vec, + runs: &mut Vec<(usize, usize)>, + read: impl FnOnce(usize, &mut [u8]) -> bool, +) -> Option<(usize, usize)> { + runs.clear(); + // From the first byte that differs to the last: title memory is read + // and written there only (a shader that sets a few words of a piece + // cost a read, a walk and a write of all 64 KiB of it). + let first = first_difference(host, old)?; + let last = last_difference(host, old).unwrap_or(first); + let n = last + 1 - first; + let (host, old) = (&mut host[first..=last], &old[first..=last]); + title.clear(); + title.resize(n, 0); + if !read(first, title) { + return None; + } + // Title memory with the GPU's bytes put in; the copy takes the title's + // bytes in turn. + // Without a branch, so the loop runs many bytes at a time: the GPU's + // byte where the copy's byte is not what it was before the submission + // and the title left its byte as it was, else the title's. (With the + // two searches above this was 44 ms a frame for 970 pieces.) + // Where the shader and the title both changed a byte while the GPU ran, + // the title's stays: the shader computed its byte from the copy's older + // data (one cleared a bit of a record the title had already replaced, + // and copying it back broke the title's object: an access violation + // through 0xffffffff00000000; PalmVIDev e0b70476, VIctory f39c6c2). + mask.clear(); + mask.resize(n, 0); + let mut differs = 0u8; + for (((t, h), o), m) in title.iter_mut().zip(host.iter_mut()).zip(old).zip(mask.iter_mut()) { + let gpu = if (*h != *o) & (*t == *o) { 0xffu8 } else { 0 }; + let merged = (*t & !gpu) | (*h & gpu); + *m = merged ^ *t; + differs |= *m; + *t = merged; + *h = merged; + } + if differs == 0 { + return None; + } + let mut i = 0; + while i < n { + while i < n && mask[i] == 0 { + i += 1; + } + let start = i; + while i < n && mask[i] != 0 { + i += 1; + } + if i > start { + runs.push((start, i - start)); + } + } + Some((first, n)) +} + +/// Since the last frame-rate line, of [`Shadow::merge_under_writes`]: pages +/// compared, changed runs put in, and their bytes. +static MERGED: [AtomicU64; 3] = [const { AtomicU64::new(0) }; 3]; + +/// [`MERGED`], taken. +pub(crate) fn merged_stats() -> [u64; 3] { + [0, 1, 2].map(|i| MERGED[i].swap(0, Ordering::Relaxed)) +} + +/// `runs` (in order) with those a gap of `gap` bytes or fewer apart made +/// one run, the gap's bytes included. +fn joined_over(runs: Vec<(usize, usize)>, gap: usize) -> Vec<(usize, usize)> { + if gap == 0 || runs.len() < 2 { + return runs; + } + let mut out: Vec<(usize, usize)> = Vec::with_capacity(runs.len()); + for (at, n) in runs { + match out.last_mut() { + Some(last) if at - (last.0 + last.1) <= gap => last.1 = at + n - last.0, + _ => out.push((at, n)), + } + } + out +} + +/// The gap, in bytes, over which the title bytes put into a copy in the +/// card's memory under flights' shader writes are joined into one run +/// (`LEONIDA_MERGE_GAP`, 0 to 64; 0 by default: only the bytes the title +/// changed go up, as before). +/// +/// Run 219: the title rewrites some hundred pages of its big buffer a +/// frame while flights that may write that buffer are in the air, and +/// byte by byte the new content differs from the old in 38,000 runs a +/// frame (equal bytes in between, mostly zeros), far over the 512 runs a +/// submission may send, so the flights were settled twice a frame, 50 ms +/// of the submitting thread. Joined over small gaps the same pages are a +/// few runs. +/// +/// What it gives up: a gap byte is equal in title memory and on the CPU +/// side of the copy, and goes up with its run. If a flight in the air +/// wrote exactly that byte on the card (a shader store within `gap` bytes +/// between two bytes the title changed in the same frame), the store is +/// overwritten with the old value, and no compare finds it. Exact (0) is +/// the default for that reason. +fn merge_gap() -> usize { + static GAP: std::sync::OnceLock = std::sync::OnceLock::new(); + *GAP.get_or_init(|| std::env::var("LEONIDA_MERGE_GAP").ok().and_then(|v| v.trim().parse::().ok()).map_or(0, |n| n.min(64))) +} + +/// Whether a refresh of a copy in the card's memory stores and sends on +/// only the bytes that differ from the copy's CPU side +/// (`LEONIDA_COPY_CHANGED=1`; `alt`: twenty seconds with, twenty without, +/// in turn, each change said in the log). Off by default. +/// +/// Why: the write watch and the guards say which pages the title wrote +/// to, 4 KiB or 64 KiB at a time, not which bytes changed. A refresh +/// copied every such page into the copy's CPU side and noted all of it +/// for the card: about 78 MB a frame crossed to the card and their 64 KiB +/// pieces were hashed again there (the layer's "sync" lists, 13 to 20 ms +/// of the card a frame), for pages of which the title had changed a few +/// bytes, or had written the same bytes again. The CPU side holds what +/// the card's side holds outside the ranges shaders are writing (which a +/// refresh leaves alone), so bytes that are equal there need not go. +fn copy_changed() -> bool { + /// 0 off, 1 on, 2 in turn. + static MODE: std::sync::OnceLock = std::sync::OnceLock::new(); + match *MODE.get_or_init(|| match std::env::var("LEONIDA_COPY_CHANGED").as_deref() { + Ok("1") => 1, + Ok("alt") => 2, + _ => 0, + }) { + 0 => false, + 1 => true, + _ => { + static EPOCH: std::sync::OnceLock = std::sync::OnceLock::new(); + let on = (EPOCH.get_or_init(std::time::Instant::now).elapsed().as_secs() / 20) % 2 == 1; + static LAST: std::sync::atomic::AtomicU8 = std::sync::atomic::AtomicU8::new(2); + if LAST.swap(u8::from(on), Ordering::Relaxed) != u8::from(on) { + tracing::info!( + "copies in the card's memory are refreshed by what differs from now (LEONIDA_COPY_CHANGED=alt): {}", + if on { "ON" } else { "off, as usual" } + ); + } + on + } + } +} + +/// Since the start, with [`copy_changed`]: bytes of title memory read, +/// bytes that went on, their stretches, and the refreshes. +static COPY_CHANGED: [AtomicU64; 4] = [const { AtomicU64::new(0) }; 4]; + +/// The chunk a refresh by what differs compares at a time +/// ([`changed_chunks`]): whole chunks go on, so that the compare is the +/// machine's compare of two blocks and a refresh makes a few stretches, +/// not forty (run 254: found byte by byte, the stretches cost the +/// submitting thread more than the card gained). A chunk holds at most +/// this many equal bytes beside a changed one: four times the gap the +/// merges under flights join by, which is why this form is not used for +/// ranges a flight's shaders are writing (they never come here: a refresh +/// leaves them alone, and `Shadow::copy_stale` is given whole pages). +const COPY_CHANGED_CHUNK: usize = 256; + +/// The stretches of `now` that differ from `was` (of one length), in +/// whole chunks of `chunk` bytes (the last one shorter), as (offset, +/// bytes) in order, chunks side by side made one stretch. +fn changed_chunks(now: &[u8], was: &[u8], chunk: usize) -> Vec<(usize, usize)> { + let n = now.len().min(was.len()); + let mut out: Vec<(usize, usize)> = Vec::new(); + let mut at = 0; + while at < n { + let len = chunk.min(n - at); + if now[at..at + len] != was[at..at + len] { + match out.last_mut() { + Some(last) if last.0 + last.1 == at => last.1 += len, + _ => out.push((at, len)), + } + } + at += len; + } + out +} + +/// The runs of bytes where `now` differs from `was` (of one length), as +/// (offset, bytes) in order: every differing byte is in a run and no equal +/// byte is. +fn changed_runs(now: &[u8], was: &[u8]) -> Vec<(usize, usize)> { + let n = now.len().min(was.len()); + let mut runs = Vec::new(); + let mut i = 0; + while i < n { + // Equal bytes, eight at a time while they last. + while i + 8 <= n && now[i..i + 8] == was[i..i + 8] { + i += 8; + } + while i < n && now[i] == was[i] { + i += 1; + } + if i >= n { + break; + } + let first = i; + while i < n && now[i] != was[i] { + i += 1; + } + runs.push((first, i - first)); + } + runs +} + +#[cfg(test)] +mod merge_tests { + use super::{PIECE, back_piece, changed_chunks, changed_runs}; + + #[test] + fn changed_chunks_hold_every_changed_byte() { + let was: Vec = (0..2000u32).map(|i| (i * 31 + 7) as u8).collect(); + for changes in [vec![], vec![0usize], vec![1999], vec![255, 256], vec![5, 300, 301, 1024, 1990]] { + let mut now = was.clone(); + for &at in &changes { + now[at] ^= 0x5A; + } + for chunk in [1usize, 64, 256, 4096] { + let stretches = changed_chunks(&now, &was, chunk); + let mut put = was.clone(); + for &(at, n) in &stretches { + assert!(at % chunk == 0 && n > 0 && at + n <= now.len()); + put[at..at + n].copy_from_slice(&now[at..at + n]); + } + assert_eq!(put, now, "{changes:?} chunk {chunk}"); + // No stretch without a changed byte in each of its chunks, and none touching the next. + assert!(stretches.windows(2).all(|w| w[0].0 + w[0].1 < w[1].0)); + let chunks: usize = stretches.iter().map(|s| s.1.div_ceil(chunk)).sum(); + let mut changed: Vec = changes.iter().map(|c| c / chunk).collect(); + changed.dedup(); + assert_eq!(chunks, changed.len(), "{changes:?} chunk {chunk}"); + } + } + assert_eq!(changed_chunks(&[1, 2, 3], &[1, 2, 4], 256), [(0, 3)], "a last chunk shorter than the others"); + } + + #[test] + fn a_piece_put_back_reads_only_its_stretch() { + let old: Vec = (0..PIECE).map(|i| (i * 7 + i / 251) as u8).collect(); + // The title wrote 7 and 40,000 since the snapshot; the GPU wrote 5, + // 9 and 40,000 (the GPU's byte wins where both wrote). + let mut title_memory = old.clone(); + title_memory[7] ^= 0x11; + title_memory[40_000] ^= 0x22; + let mut host = old.clone(); + for at in [5, 9] { + host[at] ^= 0x33; + } + let gpu = host.clone(); + let mut scratch = Vec::new(); + let (mut mask, mut runs) = (Vec::new(), Vec::new()); + let mut asked = None; + let read = |first: usize, into: &mut [u8]| { + asked = Some((first, into.len())); + into.copy_from_slice(&title_memory[first..first + into.len()]); + true + }; + assert_eq!(back_piece(&mut host, &old, &mut scratch, &mut mask, &mut runs, read), Some((5, 5))); + assert_eq!(asked, Some((5, 5))); + let mut wanted = title_memory[5..10].to_vec(); + wanted[0] = gpu[5]; + wanted[4] = gpu[9]; + assert_eq!(scratch, wanted); + assert_eq!(host[5..10], wanted); + // Only the GPU's two bytes are written back (upstream #2009). + assert_eq!(runs, [(0, 1), (4, 1)]); + // The copy outside the stretch is left as it was. + assert!(host[..5] == gpu[..5] && host[10..] == gpu[10..]); + assert!(scratch.capacity() < PIECE / 2, "scratch of {} bytes for a stretch of 5", scratch.capacity()); + + // Nothing differs: title memory is not read. + let mut same = old.clone(); + assert_eq!(back_piece(&mut same, &old, &mut scratch, &mut mask, &mut runs, |_, _| unreachable!()), None); + // Title memory not there: nothing to write, the copy unchanged. + let mut host = gpu.clone(); + assert_eq!(back_piece(&mut host, &old, &mut scratch, &mut mask, &mut runs, |_, _| false), None); + assert!(host == gpu); + // The GPU wrote what the title holds already: nothing to write. + let mut title_memory = old.clone(); + title_memory[5] = gpu[5]; + title_memory[9] = gpu[9]; + let mut host = gpu.clone(); + let read = |first: usize, into: &mut [u8]| { + into.copy_from_slice(&title_memory[first..first + into.len()]); + true + }; + assert_eq!(back_piece(&mut host, &old, &mut scratch, &mut mask, &mut runs, read), None); + // A whole piece changed: the scratch grows to it. + let mut host: Vec = old.iter().map(|b| !b).collect(); + assert_eq!(back_piece(&mut host, &old, &mut scratch, &mut mask, &mut runs, |_, into| into.len() == PIECE), Some((0, PIECE))); + assert_eq!(scratch.len(), PIECE); + } + + /// A byte the shader and the title both changed while the GPU ran keeps + /// the title's (the shader computed it from the copy's older data); a + /// byte only the shader changed goes back, and only such bytes are in + /// the runs to write (PalmVIDev e0b70476, upstream #2009). + #[test] + fn a_byte_both_changed_keeps_the_titles_and_only_gpu_bytes_are_written() { + let old = vec![1u8, 2, 3, 4, 5, 6]; + let mut host = old.clone(); + host[1] = 20; // the GPU alone + host[3] = 40; // both + host[4] = 50; // the GPU alone + let mut title_memory = old.clone(); + title_memory[3] = 44; + title_memory[5] = 66; // the title alone + let (mut scratch, mut mask, mut runs) = (Vec::new(), Vec::new(), Vec::new()); + let read = |first: usize, into: &mut [u8]| { + into.copy_from_slice(&title_memory[first..first + into.len()]); + true + }; + assert_eq!(back_piece(&mut host, &old, &mut scratch, &mut mask, &mut runs, read), Some((1, 4))); + assert_eq!(scratch, [20, 3, 44, 50], "the title's byte where both changed"); + assert_eq!(host[1..5], [20, 3, 44, 50], "the copy takes the result"); + assert_eq!(runs, [(0, 1), (3, 1)], "the GPU's bytes only"); + } + + /// The runs hold exactly the bytes that differ: putting them into the + /// old bytes gives the new ones, and no run holds an equal byte. + #[test] + fn changed_runs_are_exactly_the_bytes_that_differ() { + let was: Vec = (0..300u32).map(|i| (i * 13 + 5) as u8).collect(); + for changes in [vec![], vec![0], vec![299], vec![7, 8, 9], vec![7, 9], vec![15, 16, 17, 23, 24, 64, 65, 66, 67, 68, 69, 70, 71, 72, 298, 299]] { + let mut now = was.clone(); + for &at in &changes { + now[at] ^= 0x41; + } + let runs = changed_runs(&now, &was); + let mut put = was.clone(); + let mut held = Vec::new(); + for &(at, n) in &runs { + assert!(n > 0); + put[at..at + n].copy_from_slice(&now[at..at + n]); + held.extend(at..at + n); + } + assert_eq!(put, now, "{changes:?}"); + assert_eq!(held, changes, "{changes:?}"); + // Runs do not touch: two that did would be one. + assert!(runs.windows(2).all(|w| w[0].0 + w[0].1 < w[1].0), "{changes:?}"); + } + assert!(changed_runs(&[], &[]).is_empty()); + } +} + +/// Host copies alive (also those only a list, a descriptor pass or a +/// snapshot still holds) and the bytes of title memory they copy. +static LIVE: [std::sync::atomic::AtomicU64; 2] = [const { std::sync::atomic::AtomicU64::new(0) }; 2]; + +impl Drop for Shadow { + fn drop(&mut self) { + if self.place.is_some() { + // Never counted with the copies (`Shadow::placed`). + crate::inplace::gone(self.window, self.len); + return; + } + LIVE[0].fetch_sub(1, Ordering::Relaxed); + LIVE[1].fetch_sub(self.len, Ordering::Relaxed); + if self.kept.get_mut().unwrap_or_else(|e| e.into_inner()).1 { + KEPT_BYTES.fetch_sub(self.len, Ordering::Relaxed); + } + let window = self.window; + if let Some(card) = &mut self.card { + if window { + WINDOW_CARD_BYTES.fetch_sub(card.size, Ordering::Relaxed); + } else { + CARD_BYTES[0].fetch_sub(card.size, Ordering::Relaxed); + } + if card.before.get_mut().unwrap_or_else(|e| e.into_inner()).is_some() { + CARD_BYTES[1].fetch_sub(card_hash_bytes(card.size), Ordering::Relaxed); + } + } + } +} + +/// Whether a copy's snapshot is kept from one submission to the next and +/// only the pieces that changed in between are taken again +/// (`LEONIDA_KEEP_SNAPSHOTS=1`; off by default). +/// +/// A snapshot is the copy's bytes before a submission, to find what its +/// shaders wrote. Taken anew for every submission it is 1,050 MB of copying +/// a frame (72-86 ms in gameplay, runs 61 and 62) for buffers of which +/// 100 MB changed. Kept, a piece of it is taken again only after something +/// changed the copy there: a refresh from title memory ([`Shadow::copy`]), +/// shader writes found after a submission, or the bytes put back then +/// ([`Shadow::copy_back`]). +/// +/// What it assumes, and why it is not on by default: that nothing else +/// writes a copy. A shader that writes a buffer through a view we did not +/// declare as written (we declare the unordered-access views of shaders +/// that can store) changes the copy unseen; with a fresh snapshot that +/// write is simply never put back, with a kept one it would be taken for a +/// write of a later submission and put back then, over whatever the title +/// wrote there since. +fn keeps() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("LEONIDA_KEEP_SNAPSHOTS").is_some_and(|v| v == "1")) +} + +/// Bytes of the snapshots kept, and the most that may be. +static KEPT_BYTES: AtomicU64 = AtomicU64::new(0); +/// `LEONIDA_KEEP_SNAPSHOTS_MB`, 256 unless set (it was 768: run 80, with +/// kept snapshots beside copies in the card's memory, ran the PC out of +/// memory in 27 s; kept snapshots are the PC's memory, all of it resident). +fn kept_most() -> u64 { + static MOST: std::sync::OnceLock = std::sync::OnceLock::new(); + *MOST.get_or_init(|| { + std::env::var("LEONIDA_KEEP_SNAPSHOTS_MB").ok().and_then(|v| v.trim().parse::().ok()).unwrap_or(256) << 20 + }) +} + +/// The 64 KiB pieces, cut at multiples of 64 KiB of title memory, that +/// hold offsets `[from, to)` of a copy of memory from `start` on +/// (`from < to`); piece 0 holds offset 0. +fn pieces_of(start: usize, from: usize, to: usize) -> std::ops::Range { + let first = start / PIECE; + (start + from) / PIECE - first..(start + to - 1) / PIECE - first + 1 +} + +/// The offsets that piece `piece` holds of a copy of `len` bytes of memory +/// from `start` on. +fn piece_at(start: usize, len: usize, piece: usize) -> (usize, usize) { + let first = start / PIECE; + let lo = ((first + piece) * PIECE).saturating_sub(start); + let hi = ((first + piece + 1) * PIECE - start).min(len); + (lo, hi) +} + +#[cfg(test)] +mod piece_tests { + use super::{PIECE, piece_at, pieces_of}; + + /// The pieces cover a copy without gaps, each cut where the compare + /// cuts (at multiples of 64 KiB of title memory). + #[test] + fn pieces_cover_the_copy_as_the_compare_cuts_it() { + for start in [0usize, 1, 4096, PIECE - 1, PIECE, PIECE + 77, 5 * PIECE + 12345] { + for len in [1usize, 100, PIECE - 1, PIECE, PIECE + 1, 3 * PIECE + 500] { + let count = pieces_of(start, 0, len).end; + let mut at = 0; + for piece in 0..count { + let (lo, hi) = piece_at(start, len, piece); + assert_eq!(lo, at, "{start} {len} {piece}"); + // As `Shadow::differing` cuts: to the next multiple. + let n = (PIECE - (start + at) % PIECE).min(len - at); + assert_eq!(hi, at + n, "{start} {len} {piece}"); + assert_eq!(pieces_of(start, lo, hi), piece..piece + 1); + assert_eq!(pieces_of(start, hi - 1, hi), piece..piece + 1); + at = hi; + } + assert_eq!(at, len, "{start} {len}"); + assert_eq!(pieces_of(start, 0, len), 0..count); + } + } + } +} + +/// The pages of `[a, e)` (title addresses, `a < e`) that a copy whose +/// first page is `base` must take from title memory before it holds the +/// title's bytes: those it never took (`copied` 0), whether or not the +/// title wrote them since tracking began, and those `written` (as +/// `crate::watch::writes` gives it, by page in order) shows written after +/// the copy took them. As [`Shadow::copy_stale`] decides it. +/// +/// [`Shadow::stale_under_writes`] and [`Shadow::merge_under_writes`] looked +/// at `written` alone, so a page of a range shaders may be writing that the +/// copy never took, and the title had not written lately, was neither +/// merged nor a reason to settle; the refresh leaves such ranges alone, and +/// shaders read zeros there (fxceless/leonida-fork#206: missing geometry +/// with `LEONIDA_LATE_WAIT`/`LEONIDA_RELAY`). +fn stale_pages_in(base: usize, copied: &[u64], a: usize, e: usize, written: &[(usize, u64)]) -> Vec { + (a / PAGE..e.div_ceil(PAGE)) + .filter(|&page| page >= base) + .filter(|&page| match copied.get(page - base) { + None => false, + Some(0) => true, + Some(&at) => written + .binary_search_by_key(&page, |&(p, _)| p) + .is_ok_and(|i| written[i].1 > at), + }) + .collect() +} + +#[cfg(test)] +mod stale_tests { + use super::*; + + #[test] + fn pages_never_taken_are_stale_written_or_not() { + let base = 0x100; + let copied = [5, 0, 5, 5]; + let at = |page: usize| page * PAGE; + // Page 0x101 was never taken; page 0x102 was written after it was + // taken, page 0x103 before. + let written = [(0x102, 6), (0x103, 4)]; + assert_eq!(stale_pages_in(base, &copied, at(0x100), at(0x104), &written), [0x101, 0x102]); + // Part of a page counts as the page; pages outside the copy do not. + assert_eq!(stale_pages_in(base, &copied, at(0x101) + 8, at(0x101) + 16, &[]), [0x101]); + assert!(stale_pages_in(base, &copied, at(0x104), at(0x106), &[(0x104, 9)]).is_empty()); + } +} + +/// Copies of windows outside buffers let go since the start, and their +/// bytes. +static LET_GO: [AtomicU64; 2] = [const { AtomicU64::new(0) }; 2]; + +/// For the memory line: the windows let go since the start and their +/// bytes, and of the bytes of the windows alive, how many lie between the +/// lowest and the highest address ever asked for in each. +#[cfg(feature = "diagnostics")] +pub(crate) fn windows() -> [u64; 3] { + let asked: u64 = { + let loose = LOOSE.lock().unwrap_or_else(|e| e.into_inner()); + loose + .values() + .map(|s| { + let low = s.asked[0].load(Ordering::Relaxed); + let high = s.asked[1].load(Ordering::Relaxed); + high.saturating_sub(low) + }) + .sum() + }; + [LET_GO[0].load(Ordering::Relaxed), LET_GO[1].load(Ordering::Relaxed), asked] +} + +/// For the memory line, of the windows alive: the bytes of their pages +/// ever copied from title memory (the rest of each window is memory the +/// host zeroed and nothing read: what a window made no bigger than what is +/// read would not hold); the windows a descriptor slot shows and their +/// bytes (they stay until the title writes the slot again); the windows a +/// list or a pass over the heap holds and their bytes; the windows asked +/// for without a length (root views, which keep the 4 MiB grid) and their +/// bytes; and the window grid in bytes ([`window`]). +#[cfg(feature = "diagnostics")] +pub(crate) fn window_use() -> [u64; 8] { + let mut out = [0u64; 8]; + let loose = LOOSE.lock().unwrap_or_else(|e| e.into_inner()); + for s in loose.values() { + let copied = s.copied.lock().unwrap_or_else(|e| e.into_inner()); + let pages = copied.iter().filter(|&&at| at != 0).count() as u64; + out[0] += (pages * PAGE as u64).min(s.len); + if crate::host::references(&s.buffer) > 1 { + out[1] += 1; + out[2] += s.len; + } + if Arc::strong_count(s) > 1 { + out[3] += 1; + out[4] += s.len; + } + if s.unsized_asks.load(Ordering::Relaxed) > 0 { + out[5] += 1; + out[6] += s.len; + } + } + out[7] = window(); + out +} + +/// Lets go of the copies of windows outside buffers that nothing names any +/// more. They were never freed, and the world's streaming keeps asking for +/// new ones: 648 windows (2.8 GB) when the cutscene began, 974 (4.3 GB) +/// eight minutes later (run 24). A window goes when +/// - only the table of windows holds its copy: no list not yet reset reads +/// or writes it, no pass over the heap keeps its range, no submission is +/// comparing it; +/// - only the copy holds its host buffer: no descriptor slot views it (a +/// slot keeps the buffer it views, `HostHeap::kept`), so no draw can read +/// it through a slot made earlier; +/// - nothing asked for it for `IDLE_MS` and `IDLE_FRAMES` frames. +/// +/// The next read of that memory makes a new copy and copies the window +/// again. Called before a submission starts, by the thread that submits. +pub(crate) fn let_go_idle() { + const IDLE_FRAMES: u64 = 4; + let gone: Vec> = { + // Held from the look to the removal: `loose` hands a copy out + // under the same lock, so none is handed out in between. + let mut map = LOOSE.lock().unwrap_or_else(|e| e.into_inner()); + if map.is_empty() { + return; + } + let idle_ms = crate::host::ram_idle_ms(crate::host::available_physical_ram()); + let idle: Vec<(u64, u64)> = map + .iter() + .filter(|(_, s)| { + Arc::strong_count(s) == 1 + && crate::host::long_ago(s.used.load(Ordering::Relaxed), idle_ms, IDLE_FRAMES) + && crate::host::references(&s.buffer) == 1 + }) + .map(|(key, _)| *key) + .collect(); + idle.into_iter().filter_map(|key| map.remove(&key)).collect() + }; + if !gone.is_empty() { + let (went, bytes) = (gone.len(), gone.iter().map(|s| s.len).sum::()); + crate::host::trail(|| { + format!("sweep: {went} host copies of windows of title memory let go ({} KiB), held by no list and no slot", bytes >> 10) + }); + } + for shadow in gone { + LET_GO[0].fetch_add(1, Ordering::Relaxed); + LET_GO[1].fetch_add(shadow.len, Ordering::Relaxed); + // Nothing runs now and nothing names it: freed at once unless a + // submission is running after all. + crate::host::retire(shadow); + } +} + +/// For the memory line: host copies alive and their bytes, of them the +/// windows of memory outside buffers and their bytes, and the snapshot +/// buffers kept for reuse and the bytes they reserve. +#[cfg(feature = "diagnostics")] +pub(crate) fn memory() -> [u64; 6] { + let (windows, window_bytes) = { + let loose = LOOSE.lock().unwrap_or_else(|e| e.into_inner()); + // Each copy once: a window may stand under several keys. + let mut seen = std::collections::HashSet::new(); + let bytes: u64 = loose + .values() + .filter(|s| seen.insert(Arc::as_ptr(s) as usize)) + .map(|s| s.len) + .sum(); + (seen.len() as u64, bytes) + }; + let (kept, kept_bytes) = { + let pool = POOL.lock().unwrap_or_else(|e| e.into_inner()); + (pool.len() as u64, pool.iter().map(|v| v.capacity() as u64).sum::()) + }; + [ + LIVE[0].load(Ordering::Relaxed), + LIVE[1].load(Ordering::Relaxed), + windows, + window_bytes, + kept, + kept_bytes, + ] +} + +// SAFETY: D3D12 resources are free-threaded; `data` is a persistent mapping +// written only on the submitting thread. +unsafe impl Send for Shadow {} +// SAFETY: as above. +unsafe impl Sync for Shadow {} + +impl Shadow { + /// The host GPU address of a title address inside the buffer. + pub(crate) fn gpu(&self, address: u64) -> u64 { + self.gpu + (address - self.start) + } + + /// The title memory the copy is of: its start and length. + pub(crate) fn span(&self) -> (u64, u64) { + (self.start, self.len) + } + + /// The offset of a title address in the copy, if it lies in it. + pub(crate) fn offset_in(&self, address: u64) -> Option { + address.checked_sub(self.start).filter(|&at| at < self.len) + } + + /// Bytes from a title address to the buffer's end. + pub(crate) fn left(&self, address: u64) -> u64 { + (self.start + self.len).saturating_sub(address) + } + + /// Whether the memory behind the copy turned out not to be write-watched: + /// every refresh then copies its whole range. + pub(crate) fn unwatched(&self) -> bool { + self.watched.load(Ordering::Relaxed) == NOT_WATCHED + } + + /// The copy's own number (see the field). + pub(crate) fn id(&self) -> u64 { + self.id + } + + /// Offset of a title address from the buffer's start. + pub(crate) fn offset(&self, address: u64) -> u64 { + address - self.start + self.place.as_ref().map_or(0, |place| place.1) + } + + /// Title memory `[start, start + len)` in place: `placed` is a buffer + /// over it in a heap opened on it. Shaped as a copy so that everything + /// that binds, views or keeps a copy works on it unchanged; what + /// copies does nothing ([`Shadow::update`], [`Shadow::gpu_writes`]). + fn placed(placed: crate::inplace::Placed, start: u64, len: u64, window: bool) -> Shadow { + crate::host::name(&placed.buffer, || format!("title memory {start:#x}+{len:#x} in place")); + let mut shadow = Shadow::new(placed.buffer, start as *mut u8, placed.gpu, start, len); + // Not a copy: not counted with them, and nothing asks what the + // title wrote there. + LIVE[0].fetch_sub(1, Ordering::Relaxed); + LIVE[1].fetch_sub(len, Ordering::Relaxed); + *shadow.watched.get_mut() = NOT_WATCHED; + shadow.window = window; + shadow.place = Some((placed.heap, placed.bias)); + shadow + } + + /// Brings `len` bytes at `address` up to date when `list` is submitted, + /// and keeps the copy alive until the list is reset. + pub(crate) fn refresh(self: &Arc, list: &HostList, address: u64, len: u64) { + let len = len.min(self.start + self.len - address); + list.defer_refresh(self, address as usize, len as usize); + } + + fn new(buffer: ID3D12Resource, data: *mut u8, gpu: u64, start: u64, len: u64) -> Shadow { + let pages = (start + len).div_ceil(PAGE as u64) - start / PAGE as u64; + LIVE[0].fetch_add(1, Ordering::Relaxed); + LIVE[1].fetch_add(len, Ordering::Relaxed); + Shadow { + buffer, + data, + gpu, + start, + len, + copied: Mutex::new(vec![0; pages as usize]), + watched: AtomicU8::new(0), + pending: Mutex::default(), + flights: Mutex::default(), + before: Mutex::default(), + kept: Mutex::default(), + used: AtomicU64::new(crate::host::moment()), + asked: [AtomicU64::new(u64::MAX), AtomicU64::new(0)], + unsized_asks: AtomicU64::new(0), + id: { + static NEXT: AtomicU64 = AtomicU64::new(1); + NEXT.fetch_add(1, Ordering::Relaxed) + }, + card: None, + window: false, + place: None, + } + } + + /// `[address, address + len)` cut to the buffer, as offsets in the copy. + fn inside(&self, address: usize, len: usize) -> (usize, usize) { + let (start, end) = (self.start as usize, (self.start + self.len) as usize); + let from = address.clamp(start, end); + (from - start, (address + len).clamp(from, end) - start) + } + + /// Shaders of `list` may write `[address, address + len)` of the copy + /// (unordered access): after the list's submission has run, the range + /// is copied back into title memory, where the title reads it; until + /// then no refresh copies title memory over it. Call after the + /// [`Shadow::refresh`] that gives the shaders the title's data. + /// + /// shortcut: what shaders wrote is found by keeping the range's bytes + /// before the submission (a copy per declared range and submission); + /// a GPU-side dirty mask would save that if big ranges make it slow. + pub(crate) fn gpu_writes(self: &Arc, list: &HostList, address: u64, len: u64) { + // In place the shaders write title memory itself: no snapshot, no + // compare, nothing to copy back, and no wait on its account. + // shortcut: another host copy of the same bytes (a title buffer + // inside this one with a copy of its own, a texture in it) is not + // told: the card's writes are not seen by write watching. + if self.place.is_some() { + return; + } + let len = len.min(self.left(address)); + list.defer_gpu_write(self, address as usize, len as usize); + } + + /// At submission, after the range's refresh: a submitted list's shaders + /// write this range. Its bytes are kept to tell later what the GPU wrote: + /// one snapshot per copy and submission, each byte taken once, when the + /// first range holding it is declared (the world declares overlapping + /// views of its 174 MB heap dozens of times, from different offsets: a + /// snapshot grown to cover each was copied whole every time), in reused + /// memory (fresh snapshots cost ~2.3 million page faults per world + /// frame). + pub(crate) fn writing(&self, address: usize, len: usize) { + if self.place.is_some() { + return; + } + let range = (address, address + len); + let mut pending = self.pending.lock().unwrap_or_else(|e| e.into_inner()); + // With the copy-back on its own thread: counted for this submission + // (once), whether or not an earlier one still holds the range. + if relay() { + self.flights.lock().unwrap_or_else(|e| e.into_inner()).declare(range, PREPARED.load(Ordering::Relaxed)); + } + // Dispatches declare the same ranges thousands of times. + if pending.contains(&range) { + return; + } + // In the card's memory: no snapshot. What shaders wrote is found on + // the card (`Host::card_before` reads the declared ranges from the + // lists). + if self.card.is_some() { + pending.push(range); + return; + } + // The parts no declared range holds yet: their bytes are taken now, + // just after the range's refresh (a part declared earlier has not + // been refreshed since, and keeps the bytes taken then). + let mut parts = vec![self.inside(address, len)]; + for &(a, e) in pending.iter() { + let (a, e) = self.inside(a, e - a); + let mut rest = Vec::with_capacity(parts.len() + 1); + for (from, to) in parts { + if e <= from || a >= to { + rest.push((from, to)); + continue; + } + if from < a { + rest.push((from, a)); + } + if e < to { + rest.push((e, to)); + } + } + parts = rest; + } + pending.push(range); + let taken: usize = parts.iter().map(|&(from, to)| to.saturating_sub(from)).sum(); + BACK_CLASS[usize::from(!self.window)].fetch_add(taken as u64, Ordering::Relaxed); + let total = self.len as usize; + let mut before = self.before.lock().unwrap_or_else(|e| e.into_inner()); + let snapshot = before.get_or_insert_with(|| pooled(total)); + if keeps() { + // Piece by piece, and only the pieces not known current. A + // piece the part holds whole is current from now on; of a + // piece it holds partly only the part's bytes are taken, as + // without the switch, and it is taken again next time (the + // rest of it may belong to a range declared earlier, whose + // bytes stay as they were taken). + let mut kept = self.kept.lock().unwrap_or_else(|e| e.into_inner()); + if kept.0.is_empty() { + kept.0 = vec![false; self.pieces(0, total.max(1)).end]; + } + for (from, to) in parts { + if from >= to { + continue; + } + for piece in self.pieces(from, to) { + if kept.0[piece] { + continue; + } + let (lo, hi) = self.piece(piece); + let whole = from <= lo && hi <= to; + let (lo, hi) = (lo.max(from), hi.min(to)); + // SAFETY: as below; `hi <= total`. + unsafe { + std::ptr::copy_nonoverlapping(self.data.add(lo), snapshot.as_mut_ptr().add(lo), hi - lo); + } + kept.0[piece] = whole; + } + } + return; + } + if wide_back() { + // Noted, and taken with the submission's other snapshots when + // its refreshes are done (`take_snapshots`): the range is + // declared from here on, so nothing changes its bytes before + // then. The snapshot's memory stays where it is until the + // range is done with (`copy_back_done`). + let mut snaps = SNAPS.lock().unwrap_or_else(|e| e.into_inner()); + let (data, snapshot) = (self.data as usize, snapshot.as_mut_ptr() as usize); + snaps.extend(parts.into_iter().filter(|&(from, to)| from < to).map(|(from, to)| (data + from, snapshot + from, to - from))); + return; + } + for (from, to) in parts { + if from < to { + // SAFETY: the copy's mapping and the snapshot's allocation + // (`pooled`) both hold `total` bytes, and `to <= total`. + unsafe { + copy_wide(self.data.add(from), snapshot.as_mut_ptr().add(from), to - from); + } + } + } + } + + /// After the submission ran: copies the bytes its shaders wrote back + /// into title memory (unmapped pages left alone), and only those: the + /// title's threads write the same buffers while the GPU runs (its + /// command memory shares the big GPU heap with what shaders write), and + /// putting back the copy's older bytes there broke the title's own + /// records (a fence list read as -1, title+0x4e9b54a). Returns the bytes + /// written. The range must lie in ranges declared with + /// [`Shadow::writing`] and not yet done: `Host::execute` passes the + /// union of a submission's ranges, each byte once, then calls + /// [`Shadow::copy_back_done`]. + pub(crate) fn copy_back(&self, address: usize, len: usize) -> usize { + self.copy_back_with(address, len, None) + } + + /// [`Shadow::copy_back`]; `found`, if given, is the pieces of the range + /// that differ from the snapshot, found beforehand ([`find_all`]). + pub(crate) fn copy_back_with(&self, address: usize, len: usize, found: Option>) -> usize { + if self.place.is_some() { + return 0; + } + let snapshot = self.before.lock().unwrap_or_else(|e| e.into_inner()); + let mut written = 0; + let (from, to) = self.inside(address, len); + let start = self.start as usize; + self.compared(from, to); + if let Some(before) = &*snapshot + && from < to + { + // SAFETY: `writing` set the snapshot's bytes of every declared + // range, at the copy's offsets. + let before = unsafe { std::slice::from_raw_parts(before.as_ptr().add(from), to - from) }; + // By 64 KiB piece: the copy compared with its bytes before the + // submission (on several threads: gigabytes a frame, bound by + // memory speed), title memory read only where the GPU wrote. + #[cfg(feature = "diagnostics")] + let scanning = std::time::Instant::now(); + let differing = match found { + Some(found) => found, + None => self.differing(from, to, before), + }; + #[cfg(feature = "diagnostics")] + let syncing = { + use crate::copystat::{C, add}; + add(C::BackScanUs, scanning.elapsed().as_micros() as u64); + add(C::BackDiffer, differing.len() as u64); + std::time::Instant::now() + }; + // Where the copy changes (the GPU wrote, and below the title's + // bytes come in), a kept snapshot is no longer current. + for &(at, n) in &differing { + self.changed(at, at + n); + } + // Sized to each stretch read (`back_piece`): a zeroed 64 KiB per + // range, most of whose ranges differ nowhere, was most of the + // work for small ranges. + let (mut title, mut mask, mut runs) = (Vec::new(), Vec::new(), Vec::new()); + for (at, n) in differing { + // SAFETY: inside the mapping; only the submitting thread + // writes it. + let host = unsafe { std::slice::from_raw_parts_mut(self.data.add(at), n) }; + let old = &before[at - from..at - from + n]; + let read = |first: usize, title: &mut [u8]| crate::host::read_into((start + at + first) as *const u8, title); + let Some((first, n)) = back_piece(host, old, &mut title, &mut mask, &mut runs, read) else { + continue; + }; + let at = at + first; + crate::host::shaders_write(start + at, &title[..n.min(title.len())]); + crate::watch::writing(start + at, n); + // Only the GPU's bytes (upstream #2009): the rest of the + // stretch is the title's as read, and a title write landing + // there since stays. + for &(off, len) in &runs { + crate::host::write_mapped((start + at + off) as *mut u8, title[off..].as_ptr(), len); + written += len; + } + } + // Our write shows as a title write at the copy's next refresh, + // which copies those pages once more (some dozens of MB a + // frame). Asking about the whole range here, to note them + // current, cost more: 19-31 askings a frame over 110-174 MB of + // view memory, each a walk of its guards. + #[cfg(feature = "diagnostics")] + crate::copystat::add(crate::copystat::C::BackSyncUs, syncing.elapsed().as_micros() as u64); + } + written + } + + /// Offsets `[from, to)` of the copy are compared with the snapshot: for + /// the frame line's counts. + fn compared(&self, from: usize, to: usize) { + #[cfg(feature = "diagnostics")] + crate::copystat::add(crate::copystat::C::BackCompared, (to - from) as u64); + let (bytes, ranges) = if self.window { (2, 5) } else { (3, 6) }; + BACK_CLASS[bytes].fetch_add((to - from) as u64, Ordering::Relaxed); + BACK_CLASS[ranges].fetch_add(1, Ordering::Relaxed); + if !self.window && self.len >= 1 << 20 { + BACK_CLASS[4].fetch_add((to - from) as u64, Ordering::Relaxed); + } + } + + /// [`relay`]: the declared range `[address, address + len)` of a copy + /// in the PC's memory is about to be looked through + /// (`crate::shadow::find_all`) by the thread that settles: counted as + /// [`Shadow::copy_back_with`] counts it. + pub(crate) fn relay_compared(&self, address: usize, len: usize) { + let (from, to) = self.inside(address, len); + self.compared(from, to); + } + + /// [`relay`], for a copy in the PC's memory: offsets `[at, at + n)` + /// are a 64 KiB piece of a declared range that differed from the + /// snapshot when it was looked through. What the card wrote there + /// since the snapshot was last brought up goes into title memory, from + /// the first to the last such byte, and into the snapshot, so that the + /// next flight's merge finds only what the card writes from now on. + /// The copy is read once and never written: a later flight's shaders + /// may be writing it at this moment. Under the snapshot's lock, which + /// [`Shadow::merge_under_writes`] holds while it reads title memory + /// and puts the title's bytes into the copy and the snapshot: the two + /// never see each other half done. `now` and `title` are scratch + /// memory. Returns the bytes written to title memory. + pub(crate) fn relay_merge(&self, at: usize, n: usize, now: &mut Vec, title: &mut Vec) -> usize { + let start = self.start as usize; + if self.card.is_some() || n == 0 || at + n > self.len as usize { + return 0; + } + let mut snapshot = self.before.lock().unwrap_or_else(|e| e.into_inner()); + let Some(before) = snapshot.as_mut() else { + return 0; + }; + now.clear(); + now.reserve(n); + // SAFETY: inside the copy's mapping (checked above), read into + // room just reserved; the card may write the mapping meanwhile, and + // each byte read is one it held at some moment. + unsafe { + std::ptr::copy_nonoverlapping(self.data.add(at), now.as_mut_ptr(), n); + now.set_len(n); + } + // SAFETY: the snapshot's allocation holds the copy's length + // (`writing`), and these offsets are in a range declared and not + // done with, whose bytes it holds; nothing else touches them + // without the lock held here. + let held = unsafe { std::slice::from_raw_parts_mut(before.as_mut_ptr().add(at), n) }; + let Some(first) = first_difference(now, held) else { + return 0; + }; + let last = last_difference(now, held).unwrap_or(first); + let (at, n) = (at + first, last + 1 - first); + let (now, held) = (&now[first..=last], &mut held[first..=last]); + title.clear(); + title.resize(n, 0); + // Title memory not there: looked at again when the next flight + // that declared the range lands (the snapshot stays as it is). + if !crate::host::read_into((start + at) as *const u8, title) { + return 0; + } + // The stretch as read: what the card did not change is the + // title's, and may have been written again since. + let as_read = merge_race_on().then(|| title.clone()); + if !merge_piece(now, held, title) { + return 0; + } + crate::host::shaders_write(start + at, &title[..]); + if self.put_back_own(start + at, &title[..]) { + return n; + } + crate::watch::writing(start + at, n); + merge_race(as_read.as_deref(), (self.start, self.len), start + at, &title[..], "pc relay"); + crate::host::write_mapped((start + at) as *mut u8, title.as_ptr(), n); + n + } + + /// With `crate::inplace::back_own` (`LEONIDA_BACK_OWN_VIEW=1`): stores + /// what a merge made of title memory `[at, at + bytes.len())` (inside + /// one 64 KiB page, as every merged stretch is) through a view of our + /// own, tells the journal, and notes the page current for this copy if + /// it was current before: the copy holds the same bytes (the merge put + /// them into both), so the next refresh need not take the page again. + /// The guards are not touched: a title write to the page still faults + /// and is reported at a later asking, which every copy then takes, + /// this one too. False with nothing done if the switch is off or the + /// memory cannot be written that way (the caller writes as before). + fn put_back_own(&self, at: usize, bytes: &[u8]) -> bool { + /// Since the start: stretches and bytes stored this way, pages + /// noted current for their copy, stretches written the old way; + /// and with `LEONIDA_BACK_OWN_CHECK=1`: stores the title's own + /// address did not show afterwards, pages noted current whose + /// CPU side in the copy differs from title memory, and those of + /// them whose guard was clean (a hole in the rule: a title write + /// on its way leaves the guard open). + static OWN_WRITES: [AtomicU64; 7] = [const { AtomicU64::new(0) }; 7]; + static CHECK: std::sync::OnceLock = std::sync::OnceLock::new(); + let check = *CHECK.get_or_init(|| std::env::var_os("LEONIDA_BACK_OWN_CHECK").is_some_and(|v| v == "1")); + if !crate::inplace::back_own() { + return false; + } + let Some(shown) = crate::inplace::write_own(at, bytes) else { + OWN_WRITES[3].fetch_add(1, Ordering::Relaxed); + return false; + }; + if check { + // The title's own address must show what went in through ours. + let mut back = vec![0u8; bytes.len()]; + if crate::host::read_into(at as *const u8, &mut back) && back != bytes { + OWN_WRITES[4].fetch_add(1, Ordering::Relaxed); + } + } + let page = at / PAGE; + let others: Vec = shown.iter().map(|&a| a / PAGE).filter(|&p| p != page).collect(); + let (before, now) = crate::watch::wrote_own(page, &others); + // A placed texture there changed with no descriptor written (what + // `crate::watch::writing` tells the texture table on the old way). + crate::descriptor::host::remapped(at, bytes.len()); + let base = self.start as usize / PAGE; + { + let mut copied = self.copied.lock().unwrap_or_else(|e| e.into_inner()); + if let Some(taken) = page.checked_sub(base).and_then(|i| copied.get_mut(i)) + && *taken != 0 + && *taken >= before + { + *taken = (*taken).max(now); + OWN_WRITES[2].fetch_add(1, Ordering::Relaxed); + // A copy in the card's memory only: its CPU side is never + // written by the card, so it must equal title memory now. + if check && self.card.is_some() { + let (start, end) = (self.start as usize, (self.start + self.len) as usize); + let (lo, hi) = ((page * PAGE).max(start), ((page + 1) * PAGE).min(end)); + if lo < hi { + let mut title = vec![0u8; hi - lo]; + // SAFETY: inside the copy's mapping; read only. + let held = unsafe { std::slice::from_raw_parts(self.data.add(lo - start).cast_const(), hi - lo) }; + if crate::host::read_into(lo as *const u8, &mut title) && title != held { + OWN_WRITES[5].fetch_add(1, Ordering::Relaxed); + if crate::watch::clean(page) { + OWN_WRITES[6].fetch_add(1, Ordering::Relaxed); + } + } + } + } + } + } + OWN_WRITES[1].fetch_add(bytes.len() as u64, Ordering::Relaxed); + let n = OWN_WRITES[0].fetch_add(1, Ordering::Relaxed) + 1; + if n % 16384 == 0 { + tracing::info!( + "what shaders wrote, stored through views of our own (LEONIDA_BACK_OWN_VIEW=1), since the start: {n} stretches {} MB, {} pages noted current for the copy that wrote them (not copied in again), {} stretches written the old way; with LEONIDA_BACK_OWN_CHECK=1: {} stores the title's address did not show, {} pages noted current whose CPU side differs from title memory, {} of those with the guard clean", + OWN_WRITES[1].load(Ordering::Relaxed) >> 20, + OWN_WRITES[2].load(Ordering::Relaxed), + OWN_WRITES[3].load(Ordering::Relaxed), + OWN_WRITES[4].load(Ordering::Relaxed), + OWN_WRITES[5].load(Ordering::Relaxed), + OWN_WRITES[6].load(Ordering::Relaxed) + ); + } + true + } + + /// The 64 KiB pieces (cut at multiples of 64 KiB of title memory) of + /// `[from, to)` of the copy that differ from `before` (the bytes from + /// `from` on), as (offset, bytes) in order; compared on several threads + /// when the range is big. + fn differing(&self, from: usize, to: usize, before: &[u8]) -> Vec<(usize, usize)> { + let (start, data) = (self.start as usize, self.data as usize); + let scan = |a: usize, b: usize| -> Vec<(usize, usize)> { + let mut found = Vec::new(); + let mut at = a; + while at < b { + let n = (PIECE - (start + at) % PIECE).min(b - at); + // SAFETY: inside the mapping, which nothing writes while a + // submission's results are compared. + let host = unsafe { std::slice::from_raw_parts((data + at) as *const u8, n) }; + if host != &before[at - from..at - from + n] { + found.push((at, n)); + } + at += n; + } + found + }; + const PER_THREAD: usize = 16 << 20; + let threads = ((to - from) / PER_THREAD).clamp(1, 8); + if threads == 1 { + return scan(from, to); + } + // Cut on piece boundaries, so that every thread sees whole pieces. + let cut = |i: usize| { + if i == threads { + return to; + } + let at = from + (to - from) / threads * i; + (at - (start + at) % PIECE).max(from) + }; + let scan = &scan; + std::thread::scope(|s| { + let parts: Vec<_> = (0..threads) + .map(|i| { + let (a, b) = (cut(i), cut(i + 1)); + s.spawn(move || scan(a, b)) + }) + .collect(); + parts + .into_iter() + .flat_map(|part| match part.join() { + Ok(found) => found, + Err(panic) => std::panic::resume_unwind(panic), + }) + .collect() + }) + } + + /// After [`Shadow::copy_back`] of a submission's ranges: every submitted + /// step that declared one of `ranges` (`(address, end)`, as declared) is + /// done with it (one submission runs at a time), and the snapshot with + /// the last range. + /// + /// With [`relay`] several submissions may hold a range: `ranges` are + /// those of one of them (each once), and a range is done with when the + /// last submission that declared it is ([`Flights`]). + pub(crate) fn copy_back_done(&self, ranges: &[(usize, usize)]) { + if self.place.is_some() { + return; + } + let mut pending = self.pending.lock().unwrap_or_else(|e| e.into_inner()); + if relay() { + let free = self.flights.lock().unwrap_or_else(|e| e.into_inner()).done(ranges); + pending.retain(|r| !free.contains(r)); + } else { + pending.retain(|r| !ranges.contains(r)); + } + if !pending.is_empty() || self.card.is_some() { + return; + } + if keeps() { + // Kept for the next submission, if it is worth it (a megabyte + // or more) and there is room. + let mut kept = self.kept.lock().unwrap_or_else(|e| e.into_inner()); + if !kept.1 && self.len >= 1 << 20 { + if KEPT_BYTES.fetch_add(self.len, Ordering::Relaxed) + self.len <= kept_most() { + kept.1 = true; + } else { + KEPT_BYTES.fetch_sub(self.len, Ordering::Relaxed); + } + } + if kept.1 { + return; + } + // Given back: nothing of it is current next time. (The lock + // on the pieces ends here: `copy_back` takes it while it holds + // the snapshot's.) + kept.0.clear(); + } + if let Some(bytes) = self.before.lock().unwrap_or_else(|e| e.into_inner()).take() { + give_back(bytes); + } + } + + /// The 64 KiB pieces (cut at multiples of 64 KiB of title memory, as + /// [`Shadow::differing`] cuts them) that hold offsets `[from, to)` of + /// the copy; `from < to`. + fn pieces(&self, from: usize, to: usize) -> std::ops::Range { + pieces_of(self.start as usize, from, to) + } + + /// The offsets in the copy that piece `piece` holds. + fn piece(&self, piece: usize) -> (usize, usize) { + piece_at(self.start as usize, self.len as usize, piece) + } + + /// The copy's bytes at offsets `[from, to)` change: a kept snapshot is + /// not current there any more. + fn changed(&self, from: usize, to: usize) { + if !keeps() || from >= to { + return; + } + let mut kept = self.kept.lock().unwrap_or_else(|e| e.into_inner()); + if kept.0.is_empty() { + return; + } + for piece in self.pieces(from, to) { + kept.0[piece] = false; + } + } + + /// Whether shaders of a submission not yet copied back may be writing + /// the copy. + pub(crate) fn writes_pending(&self) -> bool { + !self.pending.lock().unwrap_or_else(|e| e.into_inner()).is_empty() + } + + /// Whether [`Shadow::update`] of `[address, address + len)` would leave + /// title bytes behind: a range shaders may be writing holds a page the + /// title wrote since the copy last took it. The answer comes from the + /// write-watch journal alone, as the submission's one asking left it + /// (`crate::watch::asked`); where the journal cannot say (memory not + /// write-watched, a range not asked about) it is yes. A page the copy + /// never took whole counts as written if the title ever wrote it. + /// + /// For submissions sent to the card without a wait + /// (`crate::host::late`): the ranges are those of flights in the air, + /// which are then settled before this refresh. + pub(crate) fn stale_under_writes(&self, address: usize, len: usize) -> bool { + let (start, end) = (self.start as usize, (self.start + self.len) as usize); + let (from, to) = (address.max(start), (address + len).min(end)); + if from >= to { + return false; + } + let busy: Vec<(usize, usize)> = self + .pending + .lock() + .unwrap_or_else(|e| e.into_inner()) + .iter() + .filter(|&&(a, e)| a < to && e > from) + .map(|&(a, e)| (a.max(from), e.min(to))) + .collect(); + if busy.is_empty() { + return false; + } + if self.watched.load(Ordering::Relaxed) == NOT_WATCHED { + return true; + } + let base = start / PAGE; + let copied = self.copied.lock().unwrap_or_else(|e| e.into_inner()); + busy.into_iter().any(|(a, e)| match crate::watch::asked(a, e) { + Some((_, written)) => !stale_pages_in(base, &copied, a, e, &written).is_empty(), + None => true, + }) + } + + /// Where [`Shadow::stale_under_writes`] says yes: puts the bytes the + /// title changed into the copy, in the ranges shaders may be writing, + /// and only those bytes, so that what the shaders write beside them + /// stays (`crate::host::late_exact`). For each page of such a range + /// that the title wrote since the copy last took it, title memory as + /// it is now is compared with what the copy held when the range was + /// given to the shaders: the copy's CPU side for a copy in the card's + /// memory (the changed runs go up before the next submission, each a + /// copy of its own bytes, `runs_left` of them at most), the snapshot + /// for the others (the changed bytes go into the copy and into the + /// snapshot, so the compare after the card ran takes them for the + /// title's and not the shaders'). + /// + /// Whether the caller must still settle the flights: the journal + /// cannot say what was written, a snapshot is missing, or `runs_left` + /// ran out. Pages done before that stay done. + pub(crate) fn merge_under_writes(&self, address: usize, len: usize, runs_left: &mut usize) -> bool { + let (start, end) = (self.start as usize, (self.start + self.len) as usize); + let (from, to) = (address.max(start), (address + len).min(end)); + if from >= to { + return false; + } + let busy: Vec<(usize, usize)> = self + .pending + .lock() + .unwrap_or_else(|e| e.into_inner()) + .iter() + .filter(|&&(a, e)| a < to && e > from) + .map(|&(a, e)| (a.max(from), e.min(to))) + .collect(); + if busy.is_empty() { + return false; + } + if self.watched.load(Ordering::Relaxed) == NOT_WATCHED { + return true; + } + let base = start / PAGE; + let mut title = vec![0u8; PAGE]; + for (a, e) in busy { + // As the refresh itself asks (`update_free`): the journal if + // the submission's asking covered the range, else the kernel, + // else the guards. The journal alone said nothing for copies + // of view memory, which is guarded and not write-watched, and + // those were all of run 99's cases: the flights were settled + // 4-5 times a frame for "0 pages looked at". + let Some((now, written)) = crate::watch::writes(a, e, true) else { + return true; + }; + let stale: Vec = { + let copied = self.copied.lock().unwrap_or_else(|e| e.into_inner()); + stale_pages_in(base, &copied, a, e, &written) + }; + for page in stale { + let (lo, hi) = ((page * PAGE).max(a), ((page + 1) * PAGE).min(e)); + if lo >= hi { + continue; + } + let n = hi - lo; + let title = &mut title[..n]; + // The lock of the copy's reference (the snapshot, or the + // CPU's side of a copy in the card's memory), from before + // title memory is read until the title's bytes are in: with + // the copy-back on its own thread ([`relay`]) that thread + // puts what the card wrote into title memory and into the + // reference under the same lock, and a page read before + // such a merge and compared after it would take the card's + // bytes for the title's. + let mut before = self.before.lock().unwrap_or_else(|e| e.into_inner()); + // A page that is not there is left as it is, and looked at + // again next time. + if !crate::host::read_into(lo as *const u8, title) { + continue; + } + MERGED[0].fetch_add(1, Ordering::Relaxed); + let at = lo - start; + if self.card.is_some() { + // SAFETY: inside the mapping of the copy's CPU side, + // which only the submitting thread writes. + let held = unsafe { std::slice::from_raw_parts_mut(self.data.add(at), n) }; + let runs = joined_over(changed_runs(title, held), merge_gap()); + if runs.len() > *runs_left { + return true; + } + *runs_left -= runs.len(); + for (r, m) in runs { + held[r..r + m].copy_from_slice(&title[r..r + m]); + self.card_changed(at + r, at + r + m); + MERGED[1].fetch_add(1, Ordering::Relaxed); + MERGED[2].fetch_add(m as u64, Ordering::Relaxed); + } + } else { + let Some(snapshot) = before.as_mut() else { + return true; + }; + // SAFETY: the snapshot's allocation holds the copy's + // bytes at the copy's offsets (`writing`), and these + // are in a declared range. + let held = unsafe { std::slice::from_raw_parts_mut(snapshot.as_mut_ptr().add(at), n) }; + for (r, m) in changed_runs(title, held) { + // SAFETY: inside the copy's mapping. The card may be + // writing the copy beside these bytes; they are + // written here and nothing around them. + unsafe { std::ptr::copy_nonoverlapping(title.as_ptr().add(r), self.data.add(at + r), m) }; + held[r..r + m].copy_from_slice(&title[r..r + m]); + MERGED[1].fetch_add(1, Ordering::Relaxed); + MERGED[2].fetch_add(m as u64, Ordering::Relaxed); + } + } + drop(before); + // Taken, if the range holds all of the page that is in the + // copy; else the rest of it is the refresh's, which notes + // only whole pages, and the page is looked at again. + if (page * PAGE).max(start) >= a && ((page + 1) * PAGE).min(end) <= e { + let mut copied = self.copied.lock().unwrap_or_else(|e| e.into_inner()); + if let Some(at) = copied.get_mut(page - base) { + *at = now; + } + } + } + } + false + } + + /// At submission: copies what changed of `[address, address + len)` + /// since it was last copied (all of it if the memory is not + /// write-watched). Returns the bytes copied. + pub(crate) fn update(&self, address: usize, len: usize) -> usize { + // In place: the card reads title memory itself. + if self.place.is_some() { + return 0; + } + let (start, end) = (self.start as usize, (self.start + self.len) as usize); + let (from, to) = (address.max(start), (address + len).min(end)); + if from >= to { + return 0; + } + let mut busy: Vec<(usize, usize)> = self + .pending + .lock() + .unwrap_or_else(|e| e.into_inner()) + .iter() + .copied() + .filter(|&(a, e)| a < to && e > from) + .collect(); + if !busy.is_empty() { + // Around ranges shaders are writing: the gaps, each as below + // (in the world most submissions have such ranges; copying the + // gaps whole cost ~1 s per frame). + busy.sort_unstable(); + let (mut at, mut bytes) = (from, 0); + for (a, e) in busy { + if a > at { + bytes += self.update_free(at, a); + } + at = at.max(e); + } + if at < to { + bytes += self.update_free(at, to); + } + return bytes; + } + self.update_free(from, to) + } + + /// [`Shadow::update`] of `[from, to)` (inside the buffer) where no + /// shader writes. + fn update_free(&self, from: usize, to: usize) -> usize { + if self.watched.load(Ordering::Relaxed) != NOT_WATCHED { + if let Some((now, written)) = crate::watch::writes(from, to, true) { + self.watched.store(1, Ordering::Relaxed); + let copied = self.copy_stale(from, to, now, &written); + self.refresh_check(from, to); + #[cfg(feature = "diagnostics")] + { + use crate::copystat::{C, add}; + add(C::Checked, (to - from) as u64); + add(C::Unchanged, (to - from).saturating_sub(copied) as u64); + } + return copied; + } + self.watched.store(NOT_WATCHED, Ordering::Relaxed); + } + #[cfg(feature = "diagnostics")] + crate::copystat::add(crate::copystat::C::WholeBytes, (to - from) as u64); + #[cfg(feature = "diagnostics")] + let started = std::time::Instant::now(); + self.copy(from, to); + #[cfg(feature = "diagnostics")] + crate::copystat::whole(from, to - from, started.elapsed().as_micros() as u64); + to - from + } + + /// Diagnostic (`LEONIDA_REFRESH_CHECK=1`; off by default): after a + /// refresh of `[from, to)` that trusted the write watch or the guards, + /// the first 256 bytes of every 64 KiB block of it are read from title + /// memory and compared with the copy. A block that differs on three + /// refreshes in a row was changed with nothing to tell of it (a write + /// through another view of its pages, as DirectStorage's page + /// destinations make) and the card reads old bytes there: said with + /// the copy and the address. One that differs once is a write of the + /// title's that arrived between the refresh and the look. + fn refresh_check(&self, from: usize, to: usize) { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + if !*ON.get_or_init(|| std::env::var_os("LEONIDA_REFRESH_CHECK").is_some_and(|v| v == "1")) { + return; + } + const SAMPLE: usize = 256; + // Blocks found differing: how many refreshes in a row. + static DIFFERING: Mutex>> = Mutex::new(None); + static SAID: AtomicU64 = AtomicU64::new(0); + let start = self.start as usize; + let mut title = [0u8; SAMPLE]; + let mut at = from; + while at < to { + let n = SAMPLE.min(to - at); + if crate::host::read_into(at as *const u8, &mut title[..n]) { + // SAFETY: `[from, to)` lies inside the buffer (`update`), + // so these bytes are inside the copy's mapping. + let copy = unsafe { std::slice::from_raw_parts(self.data.add(at - start).cast_const(), n) }; + let mut map = DIFFERING.lock().unwrap_or_else(|e| e.into_inner()); + let map = map.get_or_insert_with(Default::default); + if copy == &title[..n] { + map.remove(&at); + } else { + let times = map.entry(at).or_insert(0); + *times += 1; + if *times == 3 { + let said = SAID.fetch_add(1, Ordering::Relaxed) + 1; + if said <= 64 || said.is_power_of_two() { + tracing::warn!( + said, + copy = self.id, + copy_start = format_args!("{start:#x}"), + copy_bytes = self.len, + address = format_args!("{at:#x}"), + refreshed = format_args!("{from:#x}..{to:#x}"), + on_the_card = self.card.is_some(), + window = self.window, + "a host copy of title memory is stale after its refresh, three times in a row: the memory changed with nothing to tell of it (LEONIDA_REFRESH_CHECK=1)" + ); + } + } + } + } + // The first bytes of the next 64 KiB block. + at = (at / PAGE + 1) * PAGE; + } + } + + /// Copies the pages of `[from, to)` written after their last copy + /// (`written`: last writes by page, in page order; `now`: this + /// asking), whole pages within the buffer. + fn copy_stale(&self, from: usize, to: usize, now: u64, written: &[(usize, u64)]) -> usize { + let base = self.start as usize / PAGE; + let mut copied = self.copied.lock().unwrap_or_else(|e| e.into_inner()); + let mut writes = written.iter().peekable(); + let (mut bytes, mut run) = (0, None); + let last = (to - 1) / PAGE; + for page in from / PAGE..=last { + let write = match writes.peek() { + Some(&&(p, w)) if p == page => { + writes.next(); + w + } + _ => 0, + }; + let at = &mut copied[page - base]; + if *at == 0 || write > *at { + // A page only partly in the range is copied in part: it + // stays stale for the rest. + let (start, end) = (self.start as usize, (self.start + self.len) as usize); + if (page * PAGE).max(start) >= from && ((page + 1) * PAGE).min(end) <= to { + *at = now; + } + run.get_or_insert(page); + } else if let Some(first) = run.take() { + bytes += self.copy((first * PAGE).max(from), (page * PAGE).min(to)); + } + } + // Cut to the range: next to it shaders may be writing the copy. + if let Some(first) = run { + bytes += self.copy((first * PAGE).max(from), ((last + 1) * PAGE).min(to)); + } + bytes + } + + /// Copies title memory `[from, to)`, cut to the buffer, into the copy. + fn copy(&self, from: usize, to: usize) -> usize { + let (start, end) = (self.start as usize, (self.start + self.len) as usize); + let (from, to) = (from.max(start), to.min(end)); + if self.card.is_some() && from < to && copy_changed() && self.copy_changed(from, to) { + return to - from; + } + // SAFETY: inside the mapping (`from` and `to` are within the buffer). + let at = unsafe { self.data.add(from - start) }; + crate::host::copy_mapped(at, from as *const u8, to - from, false); + // After the bytes are in: a snapshot taken meanwhile is not current. + self.changed(from - start, to - start); + self.card_changed(from - start, to - start); + to - from + } + + /// [`Shadow::copy`] for a copy in the card's memory, with + /// [`copy_changed`]: title memory `[from, to)` (inside the buffer) is + /// read beside the copy's CPU side and only the stretches that differ + /// are stored there and noted for the card. False with nothing done if + /// title memory could not be read whole (the caller copies as before). + fn copy_changed(&self, from: usize, to: usize) -> bool { + thread_local! { + static NOW: std::cell::RefCell> = const { std::cell::RefCell::new(Vec::new()) }; + } + let (start, n) = (self.start as usize, to - from); + NOW.with(|now| { + let mut now = now.borrow_mut(); + if now.len() < n { + now.resize(n, 0); + } + if !crate::host::read_into(from as *const u8, &mut now[..n]) { + return false; + } + // SAFETY: inside the copy's mapping (`from` and `to` are within + // the buffer); nothing else writes the CPU side of these bytes + // while a refresh has them (a refresh is one thread's). + let held = unsafe { std::slice::from_raw_parts(self.data.add(from - start).cast_const(), n) }; + let stretches = changed_chunks(&now[..n], held, COPY_CHANGED_CHUNK); + let mut sent = 0; + for &(at, len) in &stretches { + // SAFETY: as above; the stretch lies inside both. + unsafe { std::ptr::copy_nonoverlapping(now.as_ptr().add(at), self.data.add(from - start + at), len) }; + // After the bytes are in: a snapshot taken meanwhile is not current. + self.changed(from - start + at, from - start + at + len); + self.card_changed(from - start + at, from - start + at + len); + sent += len; + } + COPY_CHANGED[0].fetch_add(n as u64, Ordering::Relaxed); + COPY_CHANGED[1].fetch_add(sent as u64, Ordering::Relaxed); + COPY_CHANGED[2].fetch_add(stretches.len() as u64, Ordering::Relaxed); + let calls = COPY_CHANGED[3].fetch_add(1, Ordering::Relaxed) + 1; + if calls % 65536 == 0 { + tracing::info!( + "copies in the card's memory, refreshed by what differs (LEONIDA_COPY_CHANGED=1), since the start: {calls} refreshes read {} MB of title memory the title had written to; {} MB of it differed from the copy and went on to the card, in {} stretches", + COPY_CHANGED[0].load(Ordering::Relaxed) >> 20, + COPY_CHANGED[1].load(Ordering::Relaxed) >> 20, + COPY_CHANGED[2].load(Ordering::Relaxed) + ); + } + true + }) + } + + /// Whether shaders read and write this copy in the card's own memory + /// ([`cards`]). + pub(crate) fn carded(&self) -> bool { + self.card.is_some() + } + + /// The CPU side's bytes at offsets `[from, to)` changed: they go to the + /// card's side before the next submission. + fn card_changed(&self, from: usize, to: usize) { + let Some(card) = &self.card else { + return; + }; + if from >= to { + return; + } + let mut dirty = card.dirty.lock().unwrap_or_else(|e| e.into_inner()); + match dirty.last_mut() { + Some(last) if from <= last.1 && to >= last.0 => *last = (last.0.min(from), last.1.max(to)), + _ => dirty.push((from, to)), + } + } + + /// Of a copy in the card's memory: the CPU's side (PC memory), the + /// card side's bytes from before if made yet, and their size. + pub(crate) fn card_sides(&self) -> Option<(&ID3D12Resource, Option, u64)> { + let card = self.card.as_ref()?; + let before = card.before.lock().unwrap_or_else(|e| e.into_inner()).clone(); + Some((&card.staging, before, card.size)) + } + + /// Shader writes are declared for a copy in the card's memory: makes + /// its "before" twin with `make` (bytes to buffer) if it has none. + /// Whether one was made now: the caller fills it, whole, from the + /// card's side before the submission's lists run. Without one (no + /// memory) every piece of a declared range is fetched. + pub(crate) fn card_make_before(&self, make: impl FnOnce(u64) -> Option) -> bool { + let Some(card) = &self.card else { + return false; + }; + let mut before = card.before.lock().unwrap_or_else(|e| e.into_inner()); + if before.is_some() { + return false; + } + *before = make(card.size); + if before.is_some() { + CARD_BYTES[1].fetch_add(card_hash_bytes(card.size), Ordering::Relaxed); + } + before.is_some() + } + + /// The declared range `[address, end)` as the compare on the card + /// takes it; `None` if none of it lies in the copy. + pub(crate) fn card_span(&self, address: usize, end: usize) -> Option { + let (from, to) = self.inside(address, end.saturating_sub(address)); + (from < to).then(|| card_span_of(self.start as usize, from, to)) + } + + /// The pieces that hold offsets `[from, to)` of the copy (cut to it), + /// as the card's hashing takes them. + pub(crate) fn card_run(&self, from: usize, to: usize) -> CardSpan { + let to = to.min(self.len as usize); + card_span_of(self.start as usize, from.min(to.saturating_sub(1)), to) + } + + /// The offsets of piece `i` of `span` that lie in the span. + pub(crate) fn card_piece(&self, span: &CardSpan, i: u32) -> (usize, usize) { + card_piece_of(self.start as usize, self.len as usize, span, i) + } + + /// The walls trace (`crate::host::walls_trace`): a piece of `fetched` + /// bytes of this copy came back from the card and `written` of them + /// went into title memory. Summed per buffer and logged once a frame: + /// which shader-written buffers the title's CPU could see fresh in + /// that frame, and how much of each changed. + pub(crate) fn walls_merged(&self, fetched: usize, written: usize) { + if !crate::host::walls_trace() { + return; + } + static SEEN: Mutex<(u64, BTreeMap)> = Mutex::new((0, BTreeMap::new())); + let frame = crate::frame::current(); + let mut seen = SEEN.lock().unwrap_or_else(|e| e.into_inner()); + if seen.0 != frame { + let buffers: Vec = seen + .1 + .iter() + .map(|(at, v)| format!("{at:#x}+{:#x}: {} pieces, {} fetched, {} written", v.0, v.1, v.2, v.3)) + .take(32) + .collect(); + if !buffers.is_empty() { + tracing::info!( + frame = seen.0, + count = seen.1.len(), + buffers = ?buffers, + "walls trace: shader-written card buffers merged into title memory in this frame" + ); + } + seen.1.clear(); + seen.0 = frame; + } + let entry = seen.1.entry(self.start).or_insert((self.len, 0, 0, 0)); + entry.1 += 1; + entry.2 += fetched as u64; + entry.3 += written as u64; + } + + /// After a submission, for a copy in the card's memory: `gpu` is what + /// the card's side holds at offset `at` on, in a piece the compare + /// found differing. The bytes shaders wrote (those that differ from the + /// CPU's side, which is what the card's side held when they started) + /// go into title memory, from the first to the last of them, as + /// [`Shadow::copy_back`] puts them; the CPU's side takes the result and + /// sends it up before the next submission. `title` is scratch memory. + /// Returns the bytes written to title memory. + pub(crate) fn card_merge(&self, at: usize, gpu: &[u8], title: &mut Vec) -> usize { + let start = self.start as usize; + if self.card.is_none() || at + gpu.len() > self.len as usize { + return 0; + } + // SAFETY: inside the mapping (checked above); only the submitting + // thread writes it. + let old = unsafe { std::slice::from_raw_parts_mut(self.data.add(at), gpu.len()) }; + let Some(first) = first_difference(gpu, old) else { + return 0; + }; + let last = last_difference(gpu, old).unwrap_or(first); + let (at, n) = (at + first, last + 1 - first); + let (gpu, old) = (&gpu[first..=last], &mut old[first..=last]); + title.clear(); + title.resize(n, 0); + let mut written = 0; + if crate::host::read_into((start + at) as *const u8, title) { + // The stretch as read: what the card did not change is the + // title's, and may have been written again since. + let as_read = merge_race_on().then(|| title.clone()); + // As in `copy_back`: the card's byte where it is not what it + // was before the submission, else the title's. + let mut differs = 0u8; + for ((t, g), o) in title.iter_mut().zip(gpu).zip(old.iter_mut()) { + let wrote = if *g != *o { 0xffu8 } else { 0 }; + let merged = (*t & !wrote) | (*g & wrote); + differs |= merged ^ *t; + *t = merged; + *o = merged; + } + if differs != 0 { + crate::host::shaders_write(start + at, &title[..]); + crate::watch::writing(start + at, n); + merge_race(as_read.as_deref(), (self.start, self.len), start + at, &title[..], "card"); + crate::host::write_mapped((start + at) as *mut u8, title.as_ptr(), n); + written = n; + } + } else { + // Title memory is not mapped there: the copy keeps what the + // card wrote, as before. + old.copy_from_slice(gpu); + } + // The card's side and its "before" take the result. + self.card_changed(at, at + n); + written + } + + /// [`relay`], for a copy in the card's memory: `gpu` is what the + /// card's side held at offset `at` on when a fetch sent after send + /// `fetched_after` (`crate::host`'s order of the queue) ran, in a piece + /// the compare found differing. The bytes that differ from the CPU's + /// side are what shaders wrote; they go into title memory, from the + /// first to the last of them, and into the CPU's side. Nothing is sent + /// up afterwards (the card holds these bytes or newer ones: sending + /// them up could undo a later flight's write), and the title's other + /// bytes are left to the refresh. + /// + /// Left out: bytes of the CPU's side that hold title bytes the card + /// had not received when the fetch ran, those still to go up and those + /// that went up with a later send. There the card's side is the older + /// one, and taking it for a shader's write would put it over what the + /// title wrote. Under the CPU side's lock (the snapshot's, which such + /// a copy has no other use for), as [`Shadow::merge_under_writes`]. + /// `title` is scratch memory. Returns the bytes written to title + /// memory. + pub(crate) fn card_merge_relay(&self, at: usize, gpu: &[u8], fetched_after: u64, title: &mut Vec) -> usize { + let start = self.start as usize; + let Some(card) = &self.card else { + return 0; + }; + if at + gpu.len() > self.len as usize { + return 0; + } + let _side = self.before.lock().unwrap_or_else(|e| e.into_inner()); + // SAFETY: inside the mapping (checked above). The offsets are in a + // range declared and not done with, which no refresh writes; what + // does write it (the title's bytes put in under shader writes) + // holds the lock held here. + let held = unsafe { std::slice::from_raw_parts_mut(self.data.add(at), gpu.len()) }; + let Some(first) = first_difference(gpu, held) else { + return 0; + }; + let last = last_difference(gpu, held).unwrap_or(first); + let (at, n) = (at + first, last + 1 - first); + let (gpu, held) = (&gpu[first..=last], &mut held[first..=last]); + let skip: Vec<(usize, usize)> = { + let dirty = card.dirty.lock().unwrap_or_else(|e| e.into_inner()); + let sent = card.sent.lock().unwrap_or_else(|e| e.into_inner()); + dirty + .iter() + .copied() + .chain(sent.iter().filter(|s| s.2 > fetched_after).map(|s| (s.0, s.1))) + .filter(|&(a, b)| a < at + n && b > at) + .collect() + }; + title.clear(); + title.resize(n, 0); + let mapped = crate::host::read_into((start + at) as *const u8, title); + // The stretch as read: what the card did not change is the + // title's, and may have been written again since. + let as_read = (mapped && merge_race_on()).then(|| title.clone()); + let mut changed = false; + for (a, b) in outside(at, at + n, skip) { + let (a, b) = (a - at, b - at); + // Title memory that is not mapped: the CPU's side keeps what + // the card wrote, as before; `title` is scratch then. + changed |= merge_piece(&gpu[a..b], &mut held[a..b], &mut title[a..b]); + } + if !mapped || !changed { + return 0; + } + crate::host::shaders_write(start + at, &title[..]); + if self.put_back_own(start + at, &title[..]) { + return n; + } + crate::watch::writing(start + at, n); + merge_race(as_read.as_deref(), (self.start, self.len), start + at, &title[..], "card relay"); + crate::host::write_mapped((start + at) as *mut u8, title.as_ptr(), n); + n + } +} + +struct Entry { + end: u64, + shadow: Option>, +} + +/// Title buffers by (start address, resource), with their copy once made. +static BUFFERS: Mutex> = Mutex::new(BTreeMap::new()); + +fn buffers() -> std::sync::MutexGuard<'static, BTreeMap<(u64, usize), Entry>> { + BUFFERS.lock().unwrap_or_else(|e| e.into_inner()) +} + +/// A title buffer exists at `start` (`len` bytes). +pub(crate) fn register(resource: usize, start: u64, len: u64) { + buffers().insert( + (start, resource), + Entry { + end: start + len, + shadow: None, + }, + ); +} + +/// The title released it; lists that still hold its copy keep it alive. +pub(crate) fn unregister(resource: usize, start: u64) { + buffers().remove(&(start, resource)); +} + +/// The title buffer holding `address`, as (start, length), without making +/// its copy (diagnostics: which buffer a dropped program's root view names). +#[cfg(feature = "diagnostics")] +pub(crate) fn extent(address: u64) -> Option<(u64, u64)> { + buffers() + .range(..=(address, usize::MAX)) + .rev() + .take(64) + .find(|(_, e)| e.end > address) + .map(|(k, e)| (k.0, e.end - k.0)) +} + +/// Title memory `[at, at + len)` is about to show something else or be +/// given up: what is in place there (`crate::inplace`) is taken out of the +/// tables, so that the next ask makes a copy or opens the memory anew, and +/// goes when no list and no slot holds it any more. Returns how many. +pub(crate) fn in_place_let_go(at: u64, len: u64) -> u64 { + let end = at.saturating_add(len); + let mut gone: Vec> = Vec::new(); + { + let mut map = LOOSE.lock().unwrap_or_else(|e| e.into_inner()); + let keys: Vec<(u64, u64)> = map + .range((at.saturating_sub(WINDOW), 0)..(end, 0)) + .filter(|(key, shadow)| shadow.place.is_some() && key.0 + key.1 > at) + .map(|(key, _)| *key) + .collect(); + gone.extend(keys.into_iter().filter_map(|key| map.remove(&key))); + } + { + // As `lookup` finds a buffer: among the 256 that start below. + let mut map = buffers(); + for (_, entry) in map.range_mut(..(end, 0)).rev().take(256) { + if entry.end > at && entry.shadow.as_ref().is_some_and(|s| s.place.is_some()) { + gone.extend(entry.shadow.take()); + } + } + } + let n = gone.len() as u64; + for shadow in gone { + crate::host::retire(shadow); + } + n +} + +/// For the in-place census (`crate::inplace`): the title buffers (start, +/// bytes, false) and the windows outside buffers that have a copy (start, +/// bytes, true). +pub(crate) fn spans() -> Vec<(u64, u64, bool)> { + let mut spans: Vec<(u64, u64, bool)> = buffers().iter().map(|(key, entry)| (key.0, entry.end - key.0, false)).collect(); + let loose = LOOSE.lock().unwrap_or_else(|e| e.into_inner()); + spans.extend(loose.keys().map(|&(start, len)| (start, len, true))); + spans +} + +/// The copy of the innermost title buffer holding `[address, address + +/// len)`, made on first use. A `len` of 0 or 1 is an ask without a length +/// (a root view: the caller reads on to the copy's end). +pub(crate) fn find(address: u64, len: u64) -> Option> { + lookup(address, len, false) +} + +/// As [`find`], for an ask that is done with the copy when its list has +/// run (a draw's vertex and index buffers, indirect arguments): outside +/// buffer objects it takes a window that is there already and holds the +/// range ([`holder`]), and makes one of its own only if none does. +/// +/// [`find`] names a window by the ask alone, which a descriptor slot needs +/// (the slot shows the window its view found when it was made, and the +/// pass that brings it up to date must find the same one). A draw needs no +/// such thing: it binds the copy it found and brings that copy up to date. +/// Named by the ask alone, every draw's range was a window of its own +/// wherever the windows are cut finer than 4 MiB: draws that bind +/// different ranges of the same memory then each copied their range, and +/// windows nothing asked for again for ten seconds were let go and made +/// (and copied) anew. Run 71, on a 256 KiB grid: 350 MB copied per frame +/// against 120 MB, 7,087 write-watch askings against 2,600, and 5,263 +/// windows (4.5 GB) let go in two minutes against 393 in a whole run. +pub(crate) fn find_any(address: u64, len: u64) -> Option> { + // With whole windows (the default) there is one window to a cell and + // nothing to choose: exactly `find`. + if !fine() { + return find(address, len); + } + lookup(address, len, true) +} + +fn lookup(address: u64, len: u64, any: bool) -> Option> { + let end = address.checked_add(len.max(1))?; + let mut map = buffers(); + let key = map + .range(..=(address, usize::MAX)) + .rev() + .take(64) + .find(|(_, e)| e.end >= end) + .map(|(k, _)| *k); + let Some(key) = key else { + drop(map); + return loose(address, end, len <= 1, any); + }; + let entry = map.get_mut(&key)?; + if entry.shadow.is_none() { + let len = entry.end - key.0; + // Rounded up so that views ending in the buffer's last 256 bytes fit. + // Shaders write some buffers (unordered access), so not upload memory. + let size = len.next_multiple_of(1 << 16); + // In place, if asked for and the memory can be opened + // (`crate::inplace::place_for`): the buffer is the title's own + // memory. Not the big ones `cards` puts in the card's memory: those + // are read too often to stay in the PC's. + let big = cards() && size >= card_limits().0; + if !big && let Some(placed) = crate::inplace::place_for(key.0, len, false) { + entry.shadow = Some(Arc::new(Shadow::placed(placed, key.0, len, false))); + return entry.shadow.clone(); + } + let (buffer, data) = host()?.shared_buffer(size)?; + crate::host::name(&buffer, || format!("title buffer {:#x}+{len:#x}", key.0)); + // A big one, with `cards`: shaders get a buffer in the card's own + // memory, and the one just made is the CPU's side. + let (buffer, card) = match card_for(size) { + Some(on_card) => { + crate::host::name(&on_card, || format!("title buffer {:#x}+{len:#x} on the card", key.0)); + tracing::info!( + start = format_args!("{:#x}", key.0), + len, + "a buffer's host copy is in the card's memory" + ); + let card = Card { + staging: buffer, + before: Mutex::default(), + dirty: Mutex::default(), + sent: Mutex::default(), + size, + }; + (on_card, Some(card)) + } + None => (buffer, None), + }; + // SAFETY: a live buffer. + let gpu = unsafe { buffer.GetGPUVirtualAddress() }; + if len >= 16 << 20 { + tracing::info!( + start = format_args!("{:#x}", key.0), + len, + "large buffer copied to the host" + ); + } else { + tracing::debug!( + start = format_args!("{:#x}", key.0), + len, + "buffer copied to the host" + ); + } + let mut shadow = Shadow::new(buffer, data, gpu, key.0, len); + shadow.card = card; + let shadow = Arc::new(shadow); + if shadow.card.is_some() { + CARDED.lock().unwrap_or_else(|e| e.into_inner()).push(Arc::downgrade(&shadow)); + } + entry.shadow = Some(shadow); + } + entry.shadow.clone() +} + +/// Titles also use memory outside any buffer object as GPU memory ( +/// the title's interface vertices, from its own allocator). Such memory +/// gets copies of the aligned windows it touches. +/// A window nothing names any more is let go ([`let_go_idle`]). +/// shortcut: a window is 4 MiB however little of it is read (the memory +/// line says how much was ever asked for, and how much was ever copied); +/// [`window`] cuts the windows of asks that give a length on a finer grid. +const WINDOW: u64 = 4 << 20; + +/// The grid the windows of asks with a length are cut on, in bytes: 4 MiB +/// unless `LEONIDA_WINDOW_KB` names a smaller power of two (64 at least). +/// A window is the PC's memory, all of it, however little of it is read: +/// 803 windows held 3.3 GB in run 60's gameplay, and all that was ever +/// asked for in them lay within 1.6 GB. On a grid of 1 MiB or 256 KiB a +/// window ends nearer to what is read. An ask without a length keeps the +/// 4 MiB grid whatever is set: a root view reads from its address to its +/// window's end, and mesh streams bound that way reach megabytes. +/// shortcut: the default stays 4 MiB until a run with the memory line's +/// window counts has shown what the finer grids give; the same memory +/// asked for with different ranges then lies in more than one window. +fn window() -> u64 { + static GRID: std::sync::OnceLock = std::sync::OnceLock::new(); + *GRID.get_or_init(|| { + let kb = std::env::var("LEONIDA_WINDOW_KB").ok().and_then(|v| v.trim().parse::().ok()); + grid(kb) + }) +} + +/// The window grid in bytes for a setting in KiB: a power of two from +/// 64 KiB to 4 MiB, 4 MiB for anything else. +fn grid(kb: Option) -> u64 { + match kb { + Some(kb) if kb.is_power_of_two() && (64..=4096).contains(&kb) => kb << 10, + _ => WINDOW, + } +} + +/// The window (start, bytes) of title memory for an ask of `[address, +/// end)` on a grid of `grid` bytes. +fn window_of(address: u64, end: u64, grid: u64) -> (u64, u64) { + let start = address & !(grid - 1); + (start, end.next_multiple_of(grid) - start) +} + +/// Whether the window of an ask without a length begins at the ask instead +/// of at the 4 MiB line below it. Such an ask (a root view) reads from its +/// address to the end of its 4 MiB cell; what lies below the lowest +/// address ever asked for in the cell is memory the host zeroed and nothing +/// reads (513 of run 65's 782 windows were asked for that way, 2,052 MB; +/// of all windows' 3,236 MB, 1,988 MB were ever copied). With this on, the +/// window is the cell's tail from the ask's step on ([`TAIL_STEP`]); an ask +/// lower in the cell later makes a longer tail, which every ask from then +/// on takes, and the shorter one goes when nothing holds it any more. +/// shortcut: off unless `LEONIDA_WINDOW_TAILS=1`. A longer tail is another +/// host buffer than the shorter one: what was bound to the shorter stays +/// right only because every list brings up to date the copy it bound +/// (`draw.rs` keeps a root view's copy with its slot). It pays only +/// together with `LEONIDA_WINDOW_KB` below 4096: on the 4 MiB grid an ask +/// with a length in the same cell makes the whole cell's window, and the +/// tail is that. +fn tails() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("LEONIDA_WINDOW_TAILS").is_some_and(|v| v == "1")) +} + +/// Tails begin on multiples of this. A longer tail is a new host buffer, +/// filled from title memory from its first byte to its last: begun on the +/// 64 KiB page of each ask, a cell whose asks came from the top down made +/// up to 63 of them, one after the other (part of run 71's copies). On +/// this step it is 15 at most, and a tail holds up to 192 KiB it did not +/// need. +const TAIL_STEP: u64 = 256 << 10; + +/// The window (start, bytes) a tail ask at `address` makes: from the ask's +/// step ([`TAIL_STEP`]) to the end of its 4 MiB cell. +fn tail_of(address: u64, end: u64) -> (u64, u64) { + let (cell, len) = window_of(address, end, WINDOW); + let start = address & !(TAIL_STEP - 1); + (start, cell + len - start) +} + +/// Of `windows` (start, bytes), the one an ask of `[address, end)` that +/// may take any window takes ([`find_any`]): the longest that holds the +/// whole range. +fn holder(windows: impl Iterator, address: u64, end: u64) -> Option<(u64, u64)> { + windows + .filter(|&(start, bytes)| start <= address && start + bytes >= end) + .max_by_key(|&(start, bytes)| (bytes, std::cmp::Reverse(start))) +} + +/// Whether windows may be smaller than their 4 MiB cell (a finer grid, or +/// tails): only then is there more than one window to choose from. +fn fine() -> bool { + tails() || window() < WINDOW +} + +/// For the memory line: the bytes of title memory the windows alive lie +/// over (each byte once), beside the windows' own bytes in +/// [`memory`]: the difference is memory that is in more than one window, +/// which is copied once for each. +#[cfg(feature = "diagnostics")] +pub(crate) fn window_cover() -> u64 { + let loose = LOOSE.lock().unwrap_or_else(|e| e.into_inner()); + cover(loose.keys().copied()) +} + +/// The bytes `windows` (start, bytes; in order of start) lie over, each +/// byte once. +#[cfg_attr(not(any(test, feature = "diagnostics")), allow(dead_code))] +fn cover(windows: impl Iterator) -> u64 { + let (mut covered, mut reached) = (0, 0); + for (start, bytes) in windows { + let end = start + bytes; + if end > reached { + covered += end - start.max(reached); + reached = end; + } + } + covered +} + +/// Of `windows` (start, bytes; in order), the longest tail a tail ask at +/// `address` can take: the first that begins in the ask's cell at or below +/// the ask's page and ends where the cell ends. +fn longest_tail(windows: impl Iterator, address: u64, end: u64) -> Option<(u64, u64)> { + let (cell, len) = window_of(address, end, WINDOW); + let step = address & !(TAIL_STEP - 1); + windows + .filter(|&(start, bytes)| start >= cell && start <= step && start + bytes == cell + len) + .min() +} + +/// Copies of title memory outside buffers, by (start, length). +static LOOSE: Mutex>> = Mutex::new(BTreeMap::new()); + +fn loose(address: u64, end: u64, unsized_ask: bool, any: bool) -> Option> { + let mut map = LOOSE.lock().unwrap_or_else(|e| e.into_inner()); + let (cell, _) = window_of(address, end, WINDOW); + let named = window_of(address, end, if unsized_ask { WINDOW } else { window() }); + let (start, len) = if unsized_ask && tails() { + let there = map.range((cell, 0)..=(address, u64::MAX)).map(|(key, _)| *key); + longest_tail(there, address, end).unwrap_or_else(|| tail_of(address, end)) + } else if any && fine() && !unsized_ask { + // The windows that begin in the ask's cell at or below the ask (one + // that begins in a cell below and reaches this far is passed over: + // the ask then makes its own). + let there = map.range((cell, 0)..=(address, u64::MAX)).map(|(key, _)| *key); + holder(there, address, end).unwrap_or(named) + } else { + named + }; + // Under the lock, with the handing out: see `let_go_idle`. + let note = |shadow: &Shadow| { + shadow.used.store(crate::host::moment(), Ordering::Relaxed); + shadow.asked[0].fetch_min(address, Ordering::Relaxed); + shadow.asked[1].fetch_max(end, Ordering::Relaxed); + if unsized_ask { + shadow.unsized_asks.fetch_add(1, Ordering::Relaxed); + } + }; + if let Some(shadow) = map.get(&(start, len)) { + note(shadow); + return Some(shadow.clone()); + } + // In place, if asked for and the window's memory can be opened: the + // window is the title's own memory, with nothing to copy. + if let Some(placed) = crate::inplace::place_for(start, len, true) { + let shadow = Arc::new(Shadow::placed(placed, start, len, true)); + note(&shadow); + map.insert((start, len), shadow.clone()); + return Some(shadow); + } + let (buffer, data) = host()?.shared_buffer(len)?; + crate::host::name(&buffer, || format!("title memory {start:#x}+{len:#x}")); + // With room for windows on the card (`window_card_most`): shaders get a + // buffer there, and the one just made is the CPU's side. + let (buffer, card) = match window_card_for(len) { + Some(on_card) => { + crate::host::name(&on_card, || format!("title memory {start:#x}+{len:#x} on the card")); + let card = Card { + staging: buffer, + before: Mutex::default(), + dirty: Mutex::default(), + sent: Mutex::default(), + size: len, + }; + (on_card, Some(card)) + } + None => (buffer, None), + }; + // SAFETY: a live buffer. + let gpu = unsafe { buffer.GetGPUVirtualAddress() }; + tracing::debug!( + start = format_args!("{start:#x}"), + len, + "loose memory copied to the host" + ); + let mut shadow = Shadow::new(buffer, data, gpu, start, len); + shadow.window = true; + shadow.card = card; + let shadow = Arc::new(shadow); + if shadow.card.is_some() { + CARDED.lock().unwrap_or_else(|e| e.into_inner()).push(Arc::downgrade(&shadow)); + } + note(&shadow); + map.insert((start, len), shadow.clone()); + Some(shadow) +} + +/// Copies of single buffer views' own bytes ([`exact`]), by (start, +/// bytes), each with the asking that last took it; and the askings so far. +#[allow(clippy::type_complexity)] +static EXACT: Mutex<(u64, BTreeMap<(u64, u64), (Arc, u64)>)> = Mutex::new((0, BTreeMap::new())); + +/// Since the last frame line: askings for such copies, and copies made. +static EXACT_STATS: [AtomicU64; 2] = [const { AtomicU64::new(0) }; 2]; + +/// A copy of the title memory `[address, address + len)` that starts at +/// `address` itself: for a buffer view whose bytes do not start on an +/// element of the copy its buffer has (`descriptor/host.rs` `own_bytes`). +/// A host view counts its first element from its buffer's start; a console +/// view starts at any address, and the title places views at ring +/// positions inside its big GPU heap. Such a view was refused and its slot +/// read zeros ("buffer view not on an element of its host copy", in every +/// run; upstream VIctory 86a5ed6 found its meshlet culling constants and +/// colour-bake parameter blocks among them and gives each a copy of its +/// own bytes, as here). +/// +/// The copy is brought up to date and written back like any other (a list +/// refreshes the copy its view's slot shows, `buffer_copy`). Kept by +/// (start, bytes) for as long as a list or a slot holds it; of the others, +/// those not asked for lately go once there are many (ring positions +/// change every frame). +pub(crate) fn exact(address: u64, len: u64) -> Option> { + /// Copies kept before the idle ones are looked for, and the askings an + /// idle one stays for. + const MANY: usize = 256; + const LATELY: u64 = 512; + if len == 0 { + return None; + } + EXACT_STATS[0].fetch_add(1, Ordering::Relaxed); + let mut guard = EXACT.lock().unwrap_or_else(|e| e.into_inner()); + let (tick, map) = &mut *guard; + *tick += 1; + let now = *tick; + if let Some((shadow, used)) = map.get_mut(&(address, len)) { + *used = now; + shadow.used.store(crate::host::moment(), Ordering::Relaxed); + return Some(shadow.clone()); + } + if map.len() >= MANY { + // Held by the map alone (no list), its buffer by the copy alone (no + // slot shows it), and not asked for lately. + map.retain(|_, (shadow, used)| { + Arc::strong_count(shadow) > 1 || crate::host::references(&shadow.buffer) > 1 || *used + LATELY > now + }); + } + let (buffer, data) = host()?.shared_buffer(len.next_multiple_of(256))?; + crate::host::name(&buffer, || format!("title view {address:#x}+{len:#x}")); + // SAFETY: a live buffer. + let gpu = unsafe { buffer.GetGPUVirtualAddress() }; + let shadow = Arc::new(Shadow::new(buffer, data, gpu, address, len)); + map.insert((address, len), (shadow.clone(), now)); + EXACT_STATS[1].fetch_add(1, Ordering::Relaxed); + Some(shadow) +} + +/// With the frame line: the buffer views that got a copy of their own +/// bytes ([`exact`]), per frame over `frames`, and the copies kept now. +/// Nothing while there are none. +pub(crate) fn exact_line(frames: f64) { + let [asked, made] = [0, 1].map(|i| EXACT_STATS[i].swap(0, Ordering::Relaxed)); + if asked == 0 { + return; + } + let kept = EXACT.lock().unwrap_or_else(|e| e.into_inner()).1.len(); + tracing::info!( + "buffer views off their copy's elements (they were refused and read zeros; LEONIDA_VIEW_OWN_COPY=0 refuses them again): \ + {:.1} asked for per frame, {:.1} copies of their own bytes made per frame, {kept} kept", + asked as f64 / frames, + made as f64 / frames + ); +} + +#[cfg(test)] +mod window_tests { + use super::{WINDOW, cover, grid, holder, longest_tail, tail_of, window_of}; + + /// An ask that may take any window takes the longest that holds all of + /// it, and none that holds only a part. + #[test] + fn an_ask_takes_the_longest_window_that_holds_it() { + let cell = 0xd_1200_0000u64; + let (ask, end) = (cell + 0x9_0000, cell + 0xb_0000); + assert_eq!(holder([].into_iter(), ask, end), None); + let there = [ + (cell, 0x4_0000), // ends below the ask + (cell + 0x8_0000, 0x2_0000), // holds its first half only + (cell + 0x8_0000, 0x4_0000), // holds it + (cell + 0x4_0000, 0x10_0000), // holds it, longer + (cell + 0xa_0000, 0x40_0000), // begins above it + ]; + assert_eq!(holder(there.into_iter(), ask, end), Some((cell + 0x4_0000, 0x10_0000))); + // Of two as long, the one that begins lower. + let two = [(cell + 0x8_0000, 0x8_0000), (cell + 0x4_0000, 0x8_0000)]; + assert_eq!(holder(two.into_iter(), ask, end), Some((cell + 0x4_0000, 0x8_0000))); + } + + /// What windows lie over counts each byte once. + #[test] + fn overlapping_windows_cover_their_memory_once() { + assert_eq!(cover([].into_iter()), 0); + let apart = [(0x10_0000u64, 0x4_0000u64), (0x20_0000, 0x4_0000)]; + assert_eq!(cover(apart.into_iter()), 0x8_0000); + // One inside another, one overlapping its end, one touching. + let over = [ + (0x10_0000u64, 0x10_0000u64), + (0x14_0000, 0x4_0000), + (0x1c_0000, 0x8_0000), + (0x24_0000, 0x4_0000), + ]; + assert_eq!(cover(over.into_iter()), 0x18_0000); + } + + /// A tail runs from the ask's page to the end of its 4 MiB cell, and an + /// ask takes the longest tail there is that holds it. + #[test] + fn tails_run_to_the_cells_end_and_the_longest_is_taken() { + let cell = 0xd_1200_0000u64; + let ask = cell + 0x12_3456; + assert_eq!(tail_of(ask, ask + 1), (cell + 0x10_0000, WINDOW - 0x10_0000)); + // The cell's first page: the whole cell, the window there always was. + assert_eq!(tail_of(cell + 0xffff, cell + 0x1_0000), (cell, WINDOW)); + let end = cell + WINDOW; + let tail = |from: u64| (cell + from, WINDOW - from); + // Nothing there, or only tails that begin above the ask. + assert_eq!(longest_tail([].into_iter(), ask, ask + 1), None); + assert_eq!(longest_tail([tail(0x20_0000)].into_iter(), ask, ask + 1), None); + // The longest of those that hold the ask; windows that do not reach + // the cell's end (cut on a finer grid for asks with a length) and + // windows of other cells are not tails. + let there = [ + (cell - WINDOW, WINDOW), + (cell, 0x4_0000), + tail(0x8_0000), + tail(0x10_0000), + (cell + 0x10_0000, 0x4_0000), + tail(0x20_0000), + ]; + assert_eq!(longest_tail(there.into_iter(), ask, ask + 1), Some(tail(0x8_0000))); + let (start, bytes) = tail(0x8_0000); + assert!(start <= ask && start + bytes == end); + // The whole cell's window is the longest tail of all. + let with_whole = [(cell, WINDOW), tail(0x8_0000)]; + assert_eq!(longest_tail(with_whole.into_iter(), ask, ask + 1), Some((cell, WINDOW))); + } + + /// The setting takes powers of two from 64 KiB to 4 MiB; anything else + /// leaves the grid as it was. + #[test] + fn the_grid_is_a_power_of_two_or_the_default() { + assert_eq!(grid(None), WINDOW); + assert_eq!(grid(Some(4096)), WINDOW); + assert_eq!(grid(Some(1024)), 1 << 20); + assert_eq!(grid(Some(256)), 256 << 10); + assert_eq!(grid(Some(64)), 64 << 10); + for bad in [0, 32, 100, 1000, 8192] { + assert_eq!(grid(Some(bad)), WINDOW, "{bad}"); + } + } + + /// A window holds its ask and is cut on the grid; on the default grid + /// it is the window there always was. + #[test] + fn windows_hold_their_ask_on_the_grid() { + let (address, end) = (0xd_1234_5678u64, 0xd_1234_5678u64 + 0x9000); + assert_eq!(window_of(address, end, WINDOW), (0xd_1200_0000, 4 << 20)); + assert_eq!(window_of(address, end, 1 << 20), (0xd_1230_0000, 1 << 20)); + assert_eq!(window_of(address, end, 256 << 10), (0xd_1234_0000, 256 << 10)); + // An ask across a grid line takes both cells. + let end = address + 0x4_0000; + assert_eq!(window_of(address, end, 256 << 10), (0xd_1234_0000, 512 << 10)); + for g in [64u64 << 10, 256 << 10, 1 << 20, WINDOW] { + let (start, len) = window_of(address, end, g); + assert!(start <= address && start + len >= end); + assert!(start % g == 0 && len % g == 0); + } + } +} + +#[cfg(test)] +mod card_merge_tests { + use super::{Card, Shadow}; + use std::sync::Mutex; + use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_11_0; + use windows::Win32::Graphics::Direct3D12::*; + use windows::Win32::Graphics::Dxgi::Common::DXGI_SAMPLE_DESC; + use windows::Win32::Graphics::Dxgi::*; + + /// A plain buffer on the software adapter: what a copy's `buffer` and + /// its card's `staging` are; the merge never touches them. + fn warp_buffer() -> Option { + // SAFETY: plain DXGI and D3D12 creation calls on the software adapter. + unsafe { + let factory: IDXGIFactory4 = CreateDXGIFactory2(DXGI_CREATE_FACTORY_FLAGS(0)).ok()?; + let adapter: IDXGIAdapter = factory.EnumWarpAdapter().ok()?; + let mut device: Option = None; + D3D12CreateDevice(&adapter, D3D_FEATURE_LEVEL_11_0, &mut device).ok()?; + let device = device?; + let heap = D3D12_HEAP_PROPERTIES { + Type: D3D12_HEAP_TYPE_DEFAULT, + ..Default::default() + }; + let desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, + Width: 64 << 10, + Height: 1, + DepthOrArraySize: 1, + MipLevels: 1, + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, + ..Default::default() + }; + let mut buffer: Option = None; + device + .CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &desc, D3D12_RESOURCE_STATE_COMMON, None, &mut buffer) + .ok()?; + buffer + } + } + + /// The mixed landing the fetch inside flights must survive, on a real + /// copy in the card's memory and its merge (`Shadow::card_merge_relay`): + /// flights 5, 6, 7 in the air; 5 lands the old way with the queue's + /// count at 7; the title wrote a byte that went up in send 7 into a + /// piece flight 6's shaders write; 6 then lands from its own slot, which + /// holds that byte as it was before send 7. The notes of sends are + /// dropped as `card_dirty` drops them, below the mark the old-way fetch + /// sets (`crate::host::fallback_fetched_mark`): with the mark at the + /// landed plans' send the title's byte survives and the shader's write + /// lands; with the mark at the fetch's count (as before the fix) the + /// title's byte is put back to the card's older one. + #[test] + fn a_title_byte_sent_after_a_flight_survives_its_slot() { + let (Some(buffer), Some(staging)) = (warp_buffer(), warp_buffer()) else { + return; + }; + const LEN: usize = 64 << 10; + let (title_byte, shader_byte) = (100usize, 200usize); + let content: Vec = (0..LEN).map(|i| (i * 7 + 3) as u8).collect(); + let land = |mark: u64| -> Vec { + let mut title = content.clone(); + let mut side = content.clone(); + // The title's byte, refreshed into the CPU's side and sent up in send 7. + title[title_byte] ^= 0x5a; + side[title_byte] = title[title_byte]; + let mut shadow = Shadow::new(buffer.clone(), side.as_mut_ptr(), 0, title.as_ptr() as u64, LEN as u64); + shadow.card = Some(Card { + staging: staging.clone(), + before: Mutex::new(None), + dirty: Mutex::default(), + sent: Mutex::new(vec![(title_byte, title_byte + 1, 7)]), + // 0: no card bytes counted (`Drop` takes them off again). + size: 0, + }); + // As `card_dirty` with the mark set by the old-way fetch. + if let Some(card) = &shadow.card { + card.sent.lock().unwrap().retain(|s| s.2 > mark); + } + // Flight 6's slot: the card's bytes behind its lists, before send 7. + let mut slot = content.clone(); + slot[shader_byte] ^= 0xc3; + let written = shadow.card_merge_relay(0, &slot, 6, &mut Vec::new()); + assert!(written > 0); + drop(shadow); + title + }; + let fixed = land(crate::host::fallback_fetched_mark(true, 7, Some(5))); + assert_eq!(fixed[title_byte], content[title_byte] ^ 0x5a, "the title's byte was lost"); + assert_eq!(fixed[shader_byte], content[shader_byte] ^ 0xc3, "the shader's write did not land"); + // The mark at the fetch's count: the note of send 7 is gone and the + // older card byte is taken for a shader's write. + let before = land(7); + assert_eq!(before[title_byte], content[title_byte]); + } +} + +/// For device-removed reports: the copy of title memory whose host range +/// starts closest below host GPU address `va`, and where `va` is in it. +pub(crate) fn near(va: u64) -> String { + let mut all: Vec<(u64, u64, u64)> = buffers() + .values() + .filter_map(|e| e.shadow.as_deref().map(|s| (s.gpu, s.start, s.len))) + .collect(); + all.extend( + LOOSE + .lock() + .unwrap_or_else(|e| e.into_inner()) + .values() + .map(|s| (s.gpu, s.start, s.len)), + ); + let below = all.iter().filter(|c| c.0 <= va).max(); + let above = all.iter().filter(|c| c.0 > va).min(); + let mut text = match below { + Some(&(gpu, start, len)) => format!( + "; the nearest title memory copy below it: {start:#x}+{len:#x} at host {gpu:#x}, offset {:#x}", + va - gpu + ), + None => "; no title memory copy below it".into(), + }; + if let Some(&(gpu, start, len)) = above { + text.push_str(&format!( + "; the nearest above: {start:#x}+{len:#x} at host {gpu:#x} ({} copies in all)", + all.len() + )); + } + text +} diff --git a/crates/leonida-gpu/src/signature.rs b/crates/leonida-gpu/src/signature.rs new file mode 100644 index 000000000..3c7b5d53d --- /dev/null +++ b/crates/leonida-gpu/src/signature.rs @@ -0,0 +1,94 @@ +//! Command signatures: the record layout of indirect execution. Kept for +//! translating it later. +#![allow(clippy::not_unsafe_ptr_arg_deref)] + +use crate::object::{ + self, COMMAND_SIGNATURE, E_INVALIDARG, HRESULT, Iid, Object, Table, This, guid, +}; +use crate::resource::PAGEABLE_IIDS; + +const SIGNATURE_IIDS: [Iid; 4] = [ + guid( + 0xc36a797c, + 0xec80, + 0x4f0a, + [0x89, 0x85, 0xa7, 0xb2, 0x47, 0x50, 0x82, 0xd1], + ), + PAGEABLE_IIDS[0], + PAGEABLE_IIDS[1], + PAGEABLE_IIDS[2], +]; + +#[repr(C)] +pub(crate) struct Desc { + stride: u32, + count: u32, + /// Each a type and up to three 32-bit fields. + arguments: *const [u32; 4], + nodes: u32, +} + +#[repr(C)] +struct Signature { + object: Object, + stride: u32, + arguments: Vec<[u32; 4]>, +} + +/// Device method. +pub(crate) extern "system" fn create( + _: This, + desc: *const Desc, + _root: This, + iid: *const Iid, + out: *mut This, +) -> HRESULT { + // SAFETY: the title passes a description (null is tolerated). + let Some(desc) = (unsafe { desc.as_ref() }) else { + return E_INVALIDARG; + }; + if desc.arguments.is_null() && desc.count > 0 { + return E_INVALIDARG; + } + let arguments = if desc.count == 0 { + Vec::new() + } else { + // SAFETY: the title passes `count` argument descriptions. + unsafe { std::slice::from_raw_parts(desc.arguments, desc.count as usize) }.to_vec() + }; + tracing::debug!(stride = desc.stride, ?arguments, "command signature"); + let signature = Box::new(Signature { + object: Object::new(&FUNCTIONS), + stride: desc.stride, + arguments, + }); + object::hand_out(COMMAND_SIGNATURE, signature, iid, &SIGNATURE_IIDS, out) +} + +/// A signature's record stride and arguments (type, then up to three +/// fields each). +pub(crate) fn layout<'a>(this: This) -> Option<(u32, &'a [[u32; 4]])> { + if this.is_null() { + return None; + } + // SAFETY: the title passes one of our signatures. + let s = unsafe { &*this.cast::() }; + Some((s.stride, &s.arguments)) +} + +extern "system" fn query(this: This, iid: *const Iid, out: *mut This) -> HRESULT { + let found = object::is(iid, &SIGNATURE_IIDS).then_some(this); + object::answer(COMMAND_SIGNATURE, iid, found, out) +} +extern "system" fn release(this: This) -> u32 { + object::release_boxed::(this) +} + +/// IUnknown 3, object 4, device child 1. +static FUNCTIONS: Table<24> = { + let mut f = object::d3d12_object(object::missing_table::()); + f[0] = query as *const (); + f[2] = release as *const (); + f[7] = object::parent_device as *const (); // 0x38 + Table(f) +}; diff --git a/crates/leonida-gpu/src/spread.rs b/crates/leonida-gpu/src/spread.rs new file mode 100644 index 000000000..3bb0bbdf6 --- /dev/null +++ b/crates/leonida-gpu/src/spread.rs @@ -0,0 +1,260 @@ +//! The title's crowded thread groups get more processors to run on. +//! +//! The title pins its threads as on the console: sixteen logical +//! processors of eight like cores. Measured on a 14700KF (eight fast cores +//! as logical processors 0-15, twelve efficiency cores as 16-27): eleven +//! of its threads, the ones that record lists and run its jobs, share +//! logical processors 8-12, which are two and a half fast cores; a +//! two-second sample found those five 70 to 107 % busy while fast core 7 +//! and the efficiency cores carried no pinned thread at all. The profile +//! of run 236 shows what that costs: code of the recording threads that +//! cannot wait for anything (a load of an atomic, a step in a tree) was +//! on a processor in only 58 to 72 of 100 looks, where the same kind of +//! code on the layer's unpinned submit thread was in 90 to 97. The frame +//! waits about 50 ms for those threads before the submit thread's 80. +//! +//! With `LEONIDA_SPREAD=1` a group with more threads than processors may +//! also run on the processors no pinned thread of the title uses: the +//! slow cores by default (`LEONIDA_SPREAD_SPARE=`: those +//! instead). The title cannot tell which processor a thread is on (it +//! imports neither `GetCurrentProcessorNumber` nor uses `rdpid`), and a +//! wider set is a place to run, not an order: the scheduler still prefers +//! the fast cores. `LEONIDA_SPREAD=alt`: twenty seconds with, twenty +//! without, in turn, each change said in the log, to measure it in one +//! scene. Off by default. + +use std::collections::HashMap; + +use windows_sys::Win32::Foundation::{CloseHandle, HANDLE, INVALID_HANDLE_VALUE}; +use windows_sys::Win32::System::Diagnostics::ToolHelp::{CreateToolhelp32Snapshot, TH32CS_SNAPTHREAD, THREADENTRY32, Thread32First, Thread32Next}; +use windows_sys::Win32::System::SystemInformation::GROUP_AFFINITY; +use windows_sys::Win32::System::Threading::{ + GetCurrentProcess, GetCurrentProcessId, GetProcessAffinityMask, GetThreadGroupAffinity, OpenThread, SetThreadGroupAffinity, THREAD_QUERY_INFORMATION, + THREAD_SET_INFORMATION, +}; + +/// 0 off, 1 on, 2 in turn. +fn mode() -> u8 { + static MODE: std::sync::OnceLock = std::sync::OnceLock::new(); + *MODE.get_or_init(|| match std::env::var("LEONIDA_SPREAD").as_deref() { + Ok("1") => 1, + Ok("alt") => 2, + _ => 0, + }) +} + +/// A pinned thread of the title: the mask the title gave it and the one it +/// has from us. +struct Pinned { + original: usize, + wide: usize, +} + +/// The mask for a group of `threads` threads the title pinned to `mask`: +/// with `spare` added if they are more than its processors. +fn widened(mask: usize, threads: usize, spare: usize) -> usize { + if threads > mask.count_ones() as usize { mask | spare } else { mask } +} + +/// Whether `mask` is a pinning of the title's: some of the console's +/// sixteen logical processors, not all the processors there are. +fn console_pinning(mask: usize, all: usize) -> bool { + mask != 0 && mask != all && mask & !0xFFFF == 0 +} + +/// The ids of this process's threads. +fn threads() -> Vec { + let mut ids = Vec::new(); + // SAFETY: a snapshot handle, closed below; the entry says its own size. + unsafe { + let snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, 0); + if snapshot == INVALID_HANDLE_VALUE { + return ids; + } + let process = GetCurrentProcessId(); + let mut entry: THREADENTRY32 = std::mem::zeroed(); + entry.dwSize = size_of::() as u32; + let mut more = Thread32First(snapshot, &mut entry) != 0; + while more { + if entry.th32OwnerProcessID == process { + ids.push(entry.th32ThreadID); + } + more = Thread32Next(snapshot, &mut entry) != 0; + } + CloseHandle(snapshot); + } + ids +} + +/// A thread's mask in processor group 0, if it can be asked. +fn mask_of(thread: HANDLE) -> Option { + // SAFETY: plain data filled in by the query. + let mut affinity: GROUP_AFFINITY = unsafe { std::mem::zeroed() }; + // SAFETY: an open thread handle and a valid out pointer. + (unsafe { GetThreadGroupAffinity(thread, &mut affinity) } != 0 && affinity.Group == 0).then_some(affinity.Mask) +} + +/// One look at all threads: the title's pinned ones are noted, and each +/// gets its wide mask (`wide`) or the title's own back. +fn pass(pinned: &mut HashMap, all: usize, spare: usize, wide: bool, said: &mut String) { + let ids = threads(); + pinned.retain(|id, _| ids.contains(id)); + let mut open: Vec<(u32, HANDLE, usize)> = Vec::new(); + for id in ids { + // SAFETY: a thread id of this process; the handle is closed below. + let handle = unsafe { OpenThread(THREAD_QUERY_INFORMATION | THREAD_SET_INFORMATION, 0, id) }; + if handle.is_null() { + continue; + } + match mask_of(handle) { + Some(mask) => { + let ours = pinned.get(&id).is_some_and(|p| mask == p.wide || mask == p.original); + if !ours { + if console_pinning(mask, all) { + // New, or the title pinned it again. + pinned.insert(id, Pinned { original: mask, wide: mask }); + } else { + // Not pinned (an id used again by another thread). + pinned.remove(&id); + } + } + open.push((id, handle, mask)); + } + // SAFETY: the handle opened above. + None => unsafe { + CloseHandle(handle); + }, + } + } + let mut groups: HashMap = HashMap::new(); + for p in pinned.values() { + *groups.entry(p.original).or_default() += 1; + } + for p in pinned.values_mut() { + p.wide = widened(p.original, groups[&p.original], spare); + } + for (id, handle, mask) in open { + if let Some(p) = pinned.get(&id) { + let want = if wide { p.wide } else { p.original }; + if mask != want { + let affinity = GROUP_AFFINITY { Mask: want, Group: 0, Reserved: [0; 3] }; + // SAFETY: an open thread handle and a mask of this system's processors. + if unsafe { SetThreadGroupAffinity(handle, &affinity, std::ptr::null_mut()) } == 0 { + tracing::debug!(id, want, error = %std::io::Error::last_os_error(), "a thread's processors could not be set"); + } + } + } + // SAFETY: the handle opened above. + unsafe { CloseHandle(handle) }; + } + let mut table: Vec<(usize, usize)> = groups.into_iter().collect(); + table.sort(); + let text = table + .iter() + .map(|&(mask, threads)| { + let to = widened(mask, threads, spare); + if to == mask { + format!("{threads} on {mask:#x} ({} processors)", mask.count_ones()) + } else { + format!("{threads} on {mask:#x} ({} processors) -> {to:#x} ({})", mask.count_ones(), to.count_ones()) + } + }) + .collect::>() + .join("; "); + if text != *said { + tracing::info!("spread: the title's pinned threads by its mask: {text}"); + *said = text; + } +} + +/// Starts the thread that widens the title's crowded groups, if asked for. +pub(crate) fn start() { + static ONCE: std::sync::Once = std::sync::Once::new(); + if mode() == 0 { + return; + } + ONCE.call_once(|| { + let made = std::thread::Builder::new().name("leonida-spread".into()).spawn(|| { + let (mut all, mut system) = (0usize, 0usize); + // SAFETY: our own process and valid out pointers. + if unsafe { GetProcessAffinityMask(GetCurrentProcess(), &mut all, &mut system) } == 0 || all == 0 { + tracing::warn!("spread: the process's processors could not be asked; nothing is widened"); + return; + } + let spare = match std::env::var("LEONIDA_SPREAD_SPARE").ok().and_then(|v| usize::from_str_radix(v.trim_start_matches("0x"), 16).ok()) { + Some(mask) => mask & all, + None => crate::framelog::slow_processors() & all, + }; + if spare == 0 { + tracing::info!("spread: no spare processors (all cores are alike and LEONIDA_SPREAD_SPARE names none); nothing is widened"); + return; + } + tracing::info!( + "spread: the title's thread groups with more threads than processors may also run on processors {spare:#x} (LEONIDA_SPREAD=1; alt: in turn)" + ); + let epoch = std::time::Instant::now(); + let mut pinned = HashMap::new(); + let mut said = String::new(); + let mut last = None; + loop { + let wide = mode() == 1 || (epoch.elapsed().as_secs() / 20) % 2 == 1; + if mode() == 2 && last != Some(wide) { + tracing::info!( + "the title's crowded thread groups run on more processors from now (LEONIDA_SPREAD=alt): {}", + if wide { "ON" } else { "off, as usual" } + ); + } + last = Some(wide); + pass(&mut pinned, all, spare, wide, &mut said); + // Often enough to catch threads the title starts and to turn with the + // twenty-second phases; a pass is a snapshot and a query a thread. + std::thread::sleep(std::time::Duration::from_millis(500)); + } + }); + if let Err(error) = made { + tracing::warn!(%error, "the spread thread could not be started"); + } + }); +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn only_crowded_groups_are_widened() { + let spare = 0x0FFF_0000; + // eleven threads on five processors: crowded + assert_eq!(widened(0x1F00, 11, spare), 0x0FFF_1F00); + // eight on eight, three on six, one on one: left alone + assert_eq!(widened(0xFF, 8, spare), 0xFF); + assert_eq!(widened(0x3F00, 3, spare), 0x3F00); + assert_eq!(widened(0x2000, 1, spare), 0x2000); + assert_eq!(widened(0x3FFF, 11, spare), 0x3FFF); + assert_eq!(widened(0x3FFF, 15, spare), 0x0FFF_3FFF); + } + + #[test] + fn a_pinning_of_the_title_is_within_the_console_s_sixteen() { + let all = 0x0FFF_FFFF; + assert!(console_pinning(0x1F00, all)); + assert!(console_pinning(0xFFFF, all)); + assert!(!console_pinning(all, all), "not pinned"); + assert!(!console_pinning(0x0FFF_1F00, all), "already wide: not the title's"); + assert!(!console_pinning(0, all)); + // a PC with sixteen processors: all of them is not a pinning + assert!(!console_pinning(0xFFFF, 0xFFFF)); + } + + #[test] + fn this_process_has_threads_and_they_have_masks() { + let ids = threads(); + assert!(!ids.is_empty()); + // SAFETY: a thread id of this process. + let handle = unsafe { OpenThread(THREAD_QUERY_INFORMATION | THREAD_SET_INFORMATION, 0, ids[0]) }; + assert!(!handle.is_null()); + assert!(mask_of(handle).is_some_and(|m| m != 0)); + // SAFETY: the handle opened above. + unsafe { CloseHandle(handle) }; + } +} diff --git a/crates/leonida-gpu/src/texture.rs b/crates/leonida-gpu/src/texture.rs new file mode 100644 index 000000000..2aca7afe6 --- /dev/null +++ b/crates/leonida-gpu/src/texture.rs @@ -0,0 +1,1614 @@ +//! Texture contents the title writes itself (decision 0007, "Texture +//! memory"): streamed pages, layout-library copies, movie frames, glyph +//! atlases. Such a texture lives in console memory in its tiled layout; +//! before a submission samples its host copy, the memory is detiled into a +//! staging buffer when its content changed, and the staging buffer is +//! copied into the host texture. +//! +//! "Changed" means a page of the memory was written since the last detiling +//! ([`crate::watch`]), in write-watched memory; in physical-page views, +//! which cannot be watched, a content hash of the whole memory at every +//! submission that samples it. +//! +//! shortcut: a change detiles the whole texture, not the pages written. +//! Only textures read through descriptor tables are brought up to date +//! (directly indexed views are not known per draw); plane 0 is uploaded +//! (every mip and array slice), depth and stencil planes are not. + +use std::collections::HashMap; +use std::sync::{Arc, Mutex}; + +use windows::Win32::Graphics::Direct3D12::*; + +use crate::host::{HostList, host}; +use crate::object::This; + +macro_rules! once { + ($($arg:tt)*) => {{ + static ONCE: std::sync::Once = std::sync::Once::new(); + ONCE.call_once(|| tracing::warn!($($arg)*)); + }}; +} + +/// A texture's upload state: the staging buffer laid out as the host +/// texture's subresources, and what was last detiled. +pub(crate) struct Staging { + buffer: ID3D12Resource, + /// Its bytes. + #[cfg(feature = "diagnostics")] + size: u64, + data: *mut u8, + footprints: Vec, + rows: Vec, + layout: leonida_formats::texture::Layout, + /// Mips per array slice. + mips: u32, + /// The staging buffer's bytes (counted in `STAGED` while it lives). + bytes: u64, + memory: *const u8, + last: Mutex, + /// Whether the staging buffer was detiled since a submitted list last + /// uploaded it, and whether one has uploaded it at all: a list records + /// the upload only then. (Every list that sampled a title texture + /// uploaded all of it again, changed or not: 5,411 subresource copies + /// of 1,120 textures in one frame of run 18.) + dirty: std::sync::atomic::AtomicBool, + uploaded: std::sync::atomic::AtomicBool, + /// When a list last recorded a use of it (`crate::host::moment`). + used: std::sync::atomic::AtomicU64, + /// Levels on demand (`crate::tiles`): the texture's host copy was made + /// without memory of its own when the staging buffer was made. + on_demand: bool, + /// For such a texture: the levels that were the title's at the last + /// detiling (a bit a level; the staging buffer holds zeros for the + /// others), and what that was judged by ([`Staging::judgement`]). + detiled: std::sync::atomic::AtomicU32, + judged: [std::sync::atomic::AtomicU64; 2], + /// For such a texture: when an upload last left a held level without + /// tiles (`crate::host::moment`, never 0; 0: none did). The upload is + /// recorded again about a second later if the card has room by then + /// ([`upload`]). + waiting: std::sync::atomic::AtomicU64, + /// The size of the buffer if it came from the pool of spare staging + /// buffers and goes back to it ([`staging_buffer`]); 0: a buffer of its + /// own, released when this is dropped. + pooled: u64, +} + +/// A staging buffer nothing holds: the buffer and where it is mapped. +struct Spare(ID3D12Resource, usize); + +// SAFETY: a D3D12 buffer and its mapping, touched by nobody while it is +// spare. +unsafe impl Send for Spare {} + +/// Spare staging buffers by size (a power of two), and their bytes in all. +static SPARE: Mutex<(std::collections::BTreeMap>, u64)> = + Mutex::new((std::collections::BTreeMap::new(), 0)); +/// The most bytes kept spare, and the largest buffer that is pooled. +const SPARE_MOST: (u64, u64) = (256 << 20, 8 << 20); +/// Staging buffers taken from the spare ones, and made, since the start. +pub(crate) static SPARE_STATS: [std::sync::atomic::AtomicU64; 2] = [const { std::sync::atomic::AtomicU64::new(0) }; 2]; + +/// A mapped upload buffer of `total` bytes for a texture's staging, all +/// zeros, and its pool size (0: not pooled). +/// +/// Every texture the title streams in got a buffer of its own from the +/// host and gave it back when its staging went: about a quarter of a +/// millisecond to make (run 213's profile: 25 ms a frame on the recording +/// threads for some 100 uploads, most of it the graphics kernel waiting) +/// and more to free on the thread that submits. A streaming burst is 200 +/// to 500 uploads in a frame (run 222), and those are the frames that +/// dip. Buffers of up to 8 MiB are now kept by size and used again, +/// zeroed as a new one is (levels not there yet must read as zeros). +/// `LEONIDA_STAGING_POOL=0`: made and freed each time, as before. +fn staging_buffer(host: &crate::host::Host, total: u64) -> Option<(ID3D12Resource, *mut u8, u64)> { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + let size = total.max(64 << 10).next_power_of_two(); + if size > SPARE_MOST.1 || !*ON.get_or_init(|| std::env::var_os("LEONIDA_STAGING_POOL").is_none_or(|v| v != "0")) { + return host.upload_buffer(total).map(|(buffer, data)| (buffer, data, 0)); + } + let spare = { + let mut all = SPARE.lock().unwrap_or_else(|e| e.into_inner()); + let taken = all.0.get_mut(&size).and_then(Vec::pop); + if taken.is_some() { + all.1 -= size; + } + taken + }; + if let Some(Spare(buffer, data)) = spare { + SPARE_STATS[0].fetch_add(1, std::sync::atomic::Ordering::Relaxed); + // SAFETY: the buffer's own mapping, `size` bytes, which nothing + // else holds. + unsafe { std::ptr::write_bytes(data as *mut u8, 0, total as usize) }; + return Some((buffer, data as *mut u8, size)); + } + SPARE_STATS[1].fetch_add(1, std::sync::atomic::Ordering::Relaxed); + host.upload_buffer(size).map(|(buffer, data)| (buffer, data, size)) +} + +/// What a texture's staging buffer holds: the hash of the memory detiled +/// (memory not watched), or the write-watch asking it was detiled after. +#[derive(Default)] +struct Last { + hash: Option, + asked: u64, + /// The frame a partly mapped texture was last read in. + partial: Option, +} + +// SAFETY: the staging mapping is written only at submission, under +// `last`'s lock; the title memory is only read. +unsafe impl Send for Staging {} +// SAFETY: as above. +unsafe impl Sync for Staging {} + +static STAGING: Mutex>>> = Mutex::new(None); + +/// The buffer a texture the host writes is copied through into the texture +/// of a view the title placed in its memory in another format +/// ([`alias`]): every level of every layer as each of the two formats lays +/// it out for a copy (the same bytes: the texels are as wide), the written +/// texture's layout first. +struct Through { + buffer: ID3D12Resource, + parts: Vec<( + D3D12_PLACED_SUBRESOURCE_FOOTPRINT, + D3D12_PLACED_SUBRESOURCE_FOOTPRINT, + )>, +} + +/// The most levels times layers [`alias`] copies (a cube of nine levels). +const ALIAS_PARTS: u32 = 54; + +// SAFETY: a device-local buffer only lists record copies with. +unsafe impl Send for Through {} +// SAFETY: as above. +unsafe impl Sync for Through {} + +/// The copy buffers of [`alias`], by the placed view's texture. +static THROUGH: Mutex>>> = Mutex::new(None); + +/// Brings `placed`, the texture of a view the title placed in the memory +/// of `source` in another format (`crate::resource::alias_of`), up to date +/// with what the host wrote to `source`: the texels of every level and +/// layer are copied as they are, through a buffer (the host copies between +/// two formats of one texel width in no other way). Recorded the first time +/// the list reads the view +/// and again whenever the list used `source` in another way since (wrote +/// it, or read it itself). Leaves `placed` in the copy destination state, +/// as [`upload`] does. False if the copy cannot be made: the caller fills +/// the texture from title memory, as before. +pub(crate) fn alias(list: &HostList, placed: This, source: This) -> bool { + const TARGET_OR_UNORDERED: u32 = 0x4 | 0x8; + const COPY_DEST: u32 = 0x400; + const COPY_SOURCE: u32 = 0x800; + let (Some(to), Some(from)) = ( + crate::resource::host_resource(placed), + crate::resource::host_resource(source), + ) else { + return false; + }; + let Some(host) = host() else { return false }; + let through = { + let mut map = THROUGH.lock().unwrap_or_else(|e| e.into_inner()); + let map = map.get_or_insert_with(HashMap::new); + match map.get(&(placed as usize)) { + Some(through) => through.clone(), + None => { + // SAFETY: live textures. + let (of_from, of_to) = unsafe { (from.GetDesc(), to.GetDesc()) }; + // Levels times layers (a volume's slices are one part). + let count = |d: &D3D12_RESOURCE_DESC| { + let layers = if d.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE3D { + 1 + } else { + u32::from(d.DepthOrArraySize) + }; + u32::from(d.MipLevels) * layers + }; + let parts = count(&of_from); + if parts == 0 || parts > ALIAS_PARTS || parts != count(&of_to) { + return false; + } + let mut rows = [(); 2] + .map(|()| vec![D3D12_PLACED_SUBRESOURCE_FOOTPRINT::default(); parts as usize]); + let mut bytes = [0u64; 2]; + // SAFETY: plain queries; the out pointers are ours and + // hold `parts` layouts each. + unsafe { + host.device.GetCopyableFootprints( + &of_from, + 0, + parts, + 0, + Some(rows[0].as_mut_ptr()), + None, + None, + Some(&mut bytes[0]), + ); + host.device.GetCopyableFootprints( + &of_to, + 0, + parts, + 0, + Some(rows[1].as_mut_ptr()), + None, + None, + Some(&mut bytes[1]), + ); + } + let alike = rows[0].iter().zip(&rows[1]).all(|(a, b)| { + let (fa, fb) = (a.Footprint, b.Footprint); + a.Offset == b.Offset + && (fa.Width, fa.Height, fa.Depth, fa.RowPitch) + == (fb.Width, fb.Height, fb.Depth, fb.RowPitch) + }); + if bytes[0] == 0 || bytes[0] != bytes[1] || !alike { + return false; + } + let Some(buffer) = host.uav_buffer(bytes[0]) else { + return false; + }; + crate::host::name(&buffer, || { + format!( + "alias copy {}x{} f{} to f{}", + of_from.Width, of_from.Height, of_from.Format.0, of_to.Format.0 + ) + }); + tracing::info!( + view = ?placed, + texture = ?source, + width = of_from.Width, + height = of_from.Height, + parts, + written_as = of_from.Format.0, + read_as = of_to.Format.0, + "a view placed in the memory of a texture the host writes, in another format: read from that texture by a copy on the host" + ); + let [of_written, of_read] = rows; + let through = Arc::new(Through { + buffer, + parts: of_written.into_iter().zip(of_read).collect(), + }); + map.insert(placed as usize, through.clone()); + through + } + } + }; + let first = list.first_use(placed as usize); + // The source's first use in the list records nothing (its prelude + // brings it to the state); a use in another way since the last copy + // shows as a change of state. + let before = list.transition(source, COPY_SOURCE).map(|(texture, before)| { + let state = crate::host::legal_state(texture, COPY_SOURCE); + let barrier = crate::host::transition( + texture, + D3D12_RESOURCE_STATES(before as i32), + D3D12_RESOURCE_STATES(state as i32), + ); + // SAFETY: an open list and a live texture. + unsafe { list.list.ResourceBarrier(&[barrier]) }; + before + }); + if !first && before.is_none() { + return true; + } + card_writes(list, placed, to, None); + crate::list::ensure_state(list, placed, COPY_DEST); + let part = |texture: &ID3D12Resource, index: usize| D3D12_TEXTURE_COPY_LOCATION { + // SAFETY: a borrowed pointer the location never releases. + pResource: unsafe { std::mem::transmute_copy(texture) }, + Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, + Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { + SubresourceIndex: index as u32, + }, + }; + let rows = |row: &D3D12_PLACED_SUBRESOURCE_FOOTPRINT| D3D12_TEXTURE_COPY_LOCATION { + // SAFETY: as above. + pResource: unsafe { std::mem::transmute_copy(&through.buffer) }, + Type: D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT, + Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { + PlacedFootprint: *row, + }, + }; + let (common, read, written) = ( + D3D12_RESOURCE_STATE_COMMON, + D3D12_RESOURCE_STATE_COPY_SOURCE, + D3D12_RESOURCE_STATE_COPY_DEST, + ); + #[cfg(feature = "diagnostics")] + list.note_op(|| format!("alias copy of {source:?} into {placed:?}")); + // SAFETY: an open list and live resources; the buffer is as big as + // the footprints and rests in the common state between copies. + unsafe { + list.list + .ResourceBarrier(&[crate::host::transition(&through.buffer, common, written)]); + for (index, (of_written, _)) in through.parts.iter().enumerate() { + list.list + .CopyTextureRegion(&rows(of_written), 0, 0, 0, &part(from, index), None); + } + list.list + .ResourceBarrier(&[crate::host::transition(&through.buffer, written, read)]); + for (index, (_, of_read)) in through.parts.iter().enumerate() { + list.list + .CopyTextureRegion(&part(to, index), 0, 0, 0, &rows(of_read), None); + } + list.list + .ResourceBarrier(&[crate::host::transition(&through.buffer, read, common)]); + } + list.keep(&through.buffer); + // A draw that also writes the source (a view of it handled before + // this one) needs it in that state again; the next read of the alias + // then copies once more, as it must after a write. + if let Some(before) = before + && before & TARGET_OR_UNORDERED != 0 + { + crate::list::ensure_state(list, source, before); + } + true +} + +/// Whether a texture refresh that finds the runtime remapping title memory +/// goes on without waiting for it (`LEONIDA_TEXTURE_NO_WAIT=1`; off by +/// default). +/// +/// A texture whose memory is all mapped is read in place, under a lock +/// the runtime takes alone while it changes a mapping +/// (`crate::watch::title_memory_reading`), so that no page goes away under +/// the read. While the world streams in the runtime remaps all the time, +/// and each of the frame's 150-360 refreshes waited for it: runs 99-101 +/// have 4, 15 and 16 frame lines with over 300 ms of "textures", up to +/// 3,708 ms, and on every one of them the wait for this lock is the whole +/// of it (1,345 of 1,381 ms; 3,630 of 3,708; the write-watch askings 3-12 +/// ms, the texture's own lock 0). +/// +/// With the switch the refresh asks for the lock without waiting. If the +/// runtime has it, the texture is read through the kernel instead, which +/// needs no lock: it fails if a page is not there, and then the texture is +/// left as it is and read at its next refresh, a frame later. A read +/// through the kernel costs about 0.6 ms a megabyte against 0.3 in place. +/// +/// What changes for the picture: a texture that arrives while the runtime +/// is remapping may show a frame later. It never shows partly read. +fn no_wait() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("LEONIDA_TEXTURE_NO_WAIT").is_some_and(|v| v == "1")) +} + +/// Since the last frame-rate line, with [`no_wait`]: refreshes that read +/// through the kernel because title memory was being remapped, and those +/// left for the next refresh because a page was not there. +pub(crate) static UNLOCKED: [std::sync::atomic::AtomicU64; 2] = [const { std::sync::atomic::AtomicU64::new(0) }; 2]; + +/// Since the last frame-rate line, of texture refreshes on every thread, in +/// microseconds: waiting for the texture's own lock (another thread is +/// refreshing the same texture), asking the write watch and the guards, +/// waiting for title memory to hold still (the lock the runtime takes +/// alone while it remaps, `crate::watch::title_memory_reading`), and the +/// refreshes in all. +/// +/// While the world streams in, the frame line's "textures" is seconds a +/// frame in some runs and tenths in others for the same megabytes (2,566 +/// ms for 110 MB in run 93, 314 ms for 132 MB in run 91; before these +/// counters, runs 81, 83, 85 and 94 each had lines of 1.5-2.9 s), and the +/// submitting thread is not running while it lasts (run 93: 240-310 ms of +/// its own time a frame beside 1,100-1,800 ms of "textures"): it waits. +/// These say for what. +pub(crate) static REFRESH_WAITS: [std::sync::atomic::AtomicU64; 4] = [const { std::sync::atomic::AtomicU64::new(0) }; 4]; + +/// `f`'s result, its time added to [`REFRESH_WAITS`]' place `slot`. +fn waited(slot: usize, f: impl FnOnce() -> T) -> T { + let started = std::time::Instant::now(); + let out = f(); + let us = started.elapsed().as_micros() as u64; + REFRESH_WAITS[slot].fetch_add(us, std::sync::atomic::Ordering::Relaxed); + if slot == 2 { + crate::framelog::add(crate::framelog::T::RefreshStillUs, us); + } + out +} + +thread_local! { + /// Room to read a texture's memory into: one buffer per submitting + /// thread. Each texture kept its own, a second copy in memory of every + /// write-watched or partly mapped texture ever sampled, for the run. + static READ: std::cell::RefCell> = const { std::cell::RefCell::new(Vec::new()) }; +} + +/// Calls `f` with `size` bytes of this thread's read buffer (their +/// contents are whatever the last texture left). +fn with_read(size: usize, f: impl FnOnce(&mut [u8]) -> R) -> R { + READ.with(|read| { + let mut read = read.borrow_mut(); + if read.len() < size { + read.resize(size, 0); + } + f(&mut read[..size]) + }) +} + +/// Whether a texture all of whose memory is mapped is read through the +/// kernel's copy instead of in place (`LEONIDA_TEXTURE_COPY=1`; off by +/// default). Round 3 of the memory work read every such texture that way +/// to be safe from pages taken away under the read; it cost 0.6 ms per MB +/// against 0.3 in place (90-105 ms a frame while the world streams in, runs +/// 72 and 73, against 20-40), and both runs with it lost the graphics +/// device, for a reason not found. The read in place is safe now for +/// another reason (`crate::watch::title_memory_reading`); this switch is +/// left to tell whether the copy was what lost the device. +fn through_copy() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("LEONIDA_TEXTURE_COPY").is_some_and(|v| v == "1")) +} + +/// Calls `f` with the `size` bytes of title memory at `memory`, read +/// through the kernel into this thread's read buffer; pages that are not +/// there read as zeros. The bytes are those a read in place would see. +fn with_title(memory: *const u8, size: usize, f: impl FnOnce(&[u8]) -> R) -> R { + with_read(size, |read| { + crate::host::copy_mapped(read.as_mut_ptr(), memory, size, false); + f(read) + }) +} + +/// Staging buffers alive (also those only a list still holds) and their +/// bytes. +static STAGED: [std::sync::atomic::AtomicU64; 2] = [const { std::sync::atomic::AtomicU64::new(0) }; 2]; + +impl Drop for Staging { + fn drop(&mut self) { + use std::sync::atomic::Ordering::Relaxed; + STAGED[0].fetch_sub(1, Relaxed); + STAGED[1].fetch_sub(self.bytes, Relaxed); + // Nothing holds the staging any more (lists keep it until they are + // reset, after their submission has run): its buffer is spare. + if self.pooled != 0 { + let mut all = SPARE.lock().unwrap_or_else(|e| e.into_inner()); + if all.1 + self.pooled <= SPARE_MOST.0 { + all.1 += self.pooled; + all.0.entry(self.pooled).or_default().push(Spare(self.buffer.clone(), self.data as usize)); + } + } + } +} + +/// For the memory line: staging buffers alive, their bytes, and how many +/// of them their texture still has (the others wait for a list's reset). +#[cfg(feature = "diagnostics")] +pub(crate) fn memory() -> [u64; 3] { + use std::sync::atomic::Ordering::Relaxed; + let kept = STAGING + .lock() + .unwrap_or_else(|e| e.into_inner()) + .as_ref() + .map_or(0, |map| map.len() as u64); + [STAGED[0].load(Relaxed), STAGED[1].load(Relaxed), kept] +} + +/// Staging buffers let go as idle since the start, and their bytes. +static LET_GO: [std::sync::atomic::AtomicU64; 2] = [const { std::sync::atomic::AtomicU64::new(0) }; 2]; + +/// For the memory line: staging buffers let go as idle, and their bytes. +#[cfg(feature = "diagnostics")] +pub(crate) fn let_go() -> [u64; 2] { + use std::sync::atomic::Ordering::Relaxed; + [LET_GO[0].load(Relaxed), LET_GO[1].load(Relaxed)] +} + +/// Lets go of the staging buffers no list recorded a use of for `IDLE_MS` +/// and `IDLE_FRAMES` frames and no list holds: a staging buffer is system memory the size of its +/// texture, kept so that an unchanged texture is not uploaded again, and +/// those of textures no longer sampled were kept for the run (2,246 of +/// them, 2.1 GB, at the end of run 24). The next list that samples such a +/// texture makes a staging buffer anew, detiles and uploads once more. +/// Called before a submission starts, by the thread that submits. +pub(crate) fn let_go_idle() { + use std::sync::atomic::Ordering::Relaxed; + const IDLE_FRAMES: u64 = 4; + let mut map = STAGING.lock().unwrap_or_else(|e| e.into_inner()); + let Some(map) = map.as_mut() else { + return; + }; + if map.is_empty() { + return; + } + let idle_ms = crate::host::ram_idle_ms(crate::host::available_physical_ram()); + // A list that recorded an upload or a check holds the staging until it + // is reset: one only the table holds is named by no list, recorded or + // running. + let (mut went, mut bytes) = (0u64, 0u64); + map.retain(|_, s| { + let keep = Arc::strong_count(s) > 1 + || !crate::host::long_ago(s.used.load(Relaxed), idle_ms, IDLE_FRAMES); + if !keep { + LET_GO[0].fetch_add(1, Relaxed); + LET_GO[1].fetch_add(s.bytes, Relaxed); + went += 1; + bytes += s.bytes; + } + keep + }); + if went > 0 { + crate::host::trail(|| format!("sweep: {went} staging buffers of textures let go ({} KiB), held by no list", bytes >> 10)); + } +} + +/// Textures the host GPU wrote by a copy or resolve: their contents are on +/// the host, not in title memory, which stays as it was. +static HOST_WRITTEN: Mutex>> = Mutex::new(None); + +/// A host copy or resolve writes `resource`. +pub(crate) fn host_written(resource: This) { + let new = { + let mut set = HOST_WRITTEN.lock().unwrap_or_else(|e| e.into_inner()); + set.get_or_insert_with(Default::default).insert(resource as usize) + }; + // Diagnostics (run 177): where its title memory is, for placed views + // the title reads that memory through ([`placed_in_host_written`]). + if new && let Some((at, desc)) = crate::resource::texture_memory(resource) { + // SAFETY: 56 bytes in the description's layout. + let words = unsafe { std::ptr::from_ref(&desc).cast::<[u32; 14]>().read_unaligned() }; + let bytes = crate::resource::placed_bytes(&words).unwrap_or(0); + if !at.is_null() && bytes > 0 { + HOST_WRITTEN_AT + .lock() + .unwrap_or_else(|e| e.into_inner()) + .insert(at as u64, (bytes, words[4], words[6], words[7], words[8], resource as usize)); + } + } +} + +/// The title memory of textures the host copied into, by address: bytes +/// and description words 4, 6, 7 and 8 (width, height, layers and levels, +/// format). +static HOST_WRITTEN_AT: Mutex> = + Mutex::new(std::collections::BTreeMap::new()); + +/// A texture the title placed at `address` (description words `desc`) was +/// made: says so once if it lies in the memory of a texture the host +/// copied into ([`host_written`]). Its own host copy is filled from title +/// memory, which the copy never reached: the copied texels are on the +/// card in the other texture, where no shader that reads this view finds +/// them. +pub(crate) fn placed_in_host_written(address: u64, desc: &[u32; 14]) { + let hit = { + let map = HOST_WRITTEN_AT.lock().unwrap_or_else(|e| e.into_inner()); + map.range(..=address) + .next_back() + .filter(|(at, d)| address < **at + d.0) + .map(|(at, d)| (*at, *d)) + }; + if let Some((at, (bytes, width, height, layers_levels, format, _))) = hit { + static SAID: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + if SAID.fetch_add(1, std::sync::atomic::Ordering::Relaxed) < 200 { + tracing::warn!( + view_address = format_args!("{address:#x}"), + view_offset = address - at, + view_width = desc[4], + view_height = desc[6], + view_layers_levels = format_args!("{:#x}", desc[7]), + view_format = desc[8], + copied_address = format_args!("{at:#x}"), + copied_bytes = bytes, + copied_width = width, + copied_height = height, + copied_layers_levels = format_args!("{layers_levels:#x}"), + copied_format = format, + "HERO LEAD: a placed texture view lies in the memory of a texture the host copied into: it is filled from title memory, which the copy never reached" + ); + } + } +} + +/// Whether the host GPU wrote `resource` by a copy or resolve +/// ([`host_written`]): its host copy cannot be made again from title +/// memory. +pub(crate) fn host_wrote(resource: usize) -> bool { + HOST_WRITTEN + .lock() + .unwrap_or_else(|e| e.into_inner()) + .as_ref() + .is_some_and(|set| set.contains(&resource)) +} + +/// The title released a resource. +pub(crate) fn forget(resource: usize) { + let mut map = STAGING.lock().unwrap_or_else(|e| e.into_inner()); + if let Some(map) = map.as_mut() { + map.remove(&resource); + } + let mut set = HOST_WRITTEN.lock().unwrap_or_else(|e| e.into_inner()); + if let Some(set) = set.as_mut() { + set.remove(&resource); + } + // Its memory may be given to other textures now (run 177: most of the + // "HERO LEAD" lines were views in memory a released texture had held). + HOST_WRITTEN_AT.lock().unwrap_or_else(|e| e.into_inner()).retain(|_, d| d.5 != resource); + let mut through = THROUGH.lock().unwrap_or_else(|e| e.into_inner()); + if let Some(through) = through.as_mut() { + through.remove(&resource); + } +} + +/// Whether `resource`'s host copy takes its contents from title memory: +/// a texture the host GPU does not render to or write. +pub(crate) fn title_written(texture: &ID3D12Resource) -> bool { + const TARGET_DEPTH_UNORDERED: i32 = 0x7; + // SAFETY: a live resource. + unsafe { texture.GetDesc() }.Flags.0 & TARGET_DEPTH_UNORDERED == 0 +} + +/// Records, once per list, the copy of `resource`'s staging buffer into +/// its host copy, and the detiling that refreshes the staging buffer at +/// submission if the memory changed. Leaves the texture in the copy +/// destination state. +pub(crate) fn upload(list: &HostList, resource: This, texture: &ID3D12Resource) { + let host_written = HOST_WRITTEN + .lock() + .unwrap_or_else(|e| e.into_inner()) + .as_ref() + .is_some_and(|set| set.contains(&(resource as usize))); + // shortcut: a texture the host copied into keeps the host's contents + // even if the title later writes its memory too. + if host_written || !list.first_use(resource as usize) { + return; + } + let Some(staging) = staging(resource, texture) else { + return; + }; + use std::sync::atomic::Ordering::Relaxed; + staging.used.store(crate::host::moment(), Relaxed); + // Levels on demand: a view of the texture now starts at another + // level, or another texture now starts inside its span, with no byte + // of its memory changed. The levels are judged anew: detiled again at + // this list's submission, and uploaded by this list. + if staging.on_demand && staging.judgement() != staging.judged() { + staging.forget(); + staging.dirty.store(true, Relaxed); + } + // Levels on demand: the last upload left a held level without tiles + // (the card had no room, or no heap could be had), and nothing else + // would record an upload again until the title writes the texture: the + // level stayed empty, the texture blurred or black. Asked again about + // once a second, and only when the card has room; the staging buffer + // still holds the level's bytes. + if staging.on_demand { + let since = staging.waiting.load(Relaxed); + if since != 0 && crate::host::long_ago(since, 1000, 2) { + if crate::resource::room_lately() { + staging.waiting.store(0, Relaxed); + staging.dirty.store(true, Relaxed); + crate::tiles::STATS[10].fetch_add(1, Relaxed); + } else { + staging.waiting.store(crate::host::moment().max(1), Relaxed); + } + } + } + // The host texture has the staging buffer's contents: only the check + // at submission is left, and what it finds changed the next list that + // samples the texture uploads (a frame late where every list of the + // frame was recorded before that check). + if staging.uploaded.load(Relaxed) && !staging.dirty.load(Relaxed) { + #[cfg(feature = "diagnostics")] + crate::copystat::add(crate::copystat::C::TexSkipped, 1); + list.defer_texture(staging); + return; + } + #[cfg(feature = "diagnostics")] + crate::copystat::add(crate::copystat::C::TexUploads, 1); + crate::framelog::add(crate::framelog::T::Uploads, 1); + const COPY_DEST: u32 = 0x400; + crate::list::ensure_state(list, resource, COPY_DEST); + // The staging buffer lives as long as `staging`, which the deferred + // refresh below holds until the list is reset. + for (i, footprint) in staging.footprints.iter().enumerate() { + #[cfg(feature = "diagnostics")] + { + let f = footprint.Footprint; + // SAFETY: live resources. + let (gpu, d) = unsafe { (staging.buffer.GetGPUVirtualAddress(), texture.GetDesc()) }; + let len = u64::from(f.RowPitch) * u64::from(staging.rows[i]) * u64::from(f.Depth); + list.note_read( + || { + format!( + "texture upload {resource:?} ({}x{}x{} f{} mips {}) sub {i} of {} from staging {gpu:#x}+{:#x}: offset {:#x} {}x{}x{} pitch {}", + d.Width, + d.Height, + d.DepthOrArraySize, + d.Format.0, + d.MipLevels, + staging.footprints.len(), + staging.size, + footprint.Offset, + f.Width, + f.Height, + f.Depth, + f.RowPitch + ) + }, + (gpu + footprint.Offset, len), + ); + } + let to = D3D12_TEXTURE_COPY_LOCATION { + // SAFETY: a borrowed pointer the location never releases. + pResource: unsafe { std::mem::transmute_copy(texture) }, + Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, + Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { + SubresourceIndex: i as u32, + }, + }; + let from = D3D12_TEXTURE_COPY_LOCATION { + // SAFETY: as above. + pResource: unsafe { std::mem::transmute_copy(&staging.buffer) }, + Type: D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT, + Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { + PlacedFootprint: *footprint, + }, + }; + // SAFETY: an open list; both locations name live resources. + unsafe { list.list.CopyTextureRegion(&to, 0, 0, 0, &from, None) }; + } + // When the list is submitted, its copy takes what the staging buffer + // holds by then: noted before the check below, which sets `dirty` + // again if it detiles (the next list then uploads once more). + { + let staging = staging.clone(); + list.defer_host(move || { + staging.uploaded.store(true, Relaxed); + staging.dirty.store(false, Relaxed); + }); + } + // Levels on demand (`crate::tiles`): after the check below, in the + // order of this list's steps, and before the list is executed, the + // levels the staging buffer holds as the title's are given the card's + // memory if they have none. The list copies every level, so each one + // given here is written whole by it (the rest are copies into no + // memory, which the card drops). + let on_demand = if staging.on_demand { crate::resource::host_tiled(resource) } else { None }; + let Some(on_demand) = on_demand else { + // Once per submission however many of its lists sample the texture. + list.defer_texture(staging); + return; + }; + list.defer_texture(staging.clone()); + list.defer_host(move || { + let waiting = on_demand.uploaded(staging.detiled.load(Relaxed), staging.memory as u64); + staging.waiting.store(if waiting { crate::host::moment().max(1) } else { 0 }, Relaxed); + // A texture picked by index has no staging buffer after this + // upload: its slots are made due again by the texture pass. + if waiting { + crate::descriptor::host::levels_waiting(staging.memory as u64); + } + }); +} + +/// Levels on demand: the levels a list claimed for its zeros +/// (`crate::tiles::Tiled::claim`), held by the list's submission-time +/// step. A list that is reset without having been submitted gives the +/// claim up, or the next list that writes those levels would send no zeros +/// and what its write does not cover would be what the tiles' last owner +/// left. +struct Claimed { + on_demand: crate::resource::OnDemand, + fresh: u32, + ran: std::sync::atomic::AtomicBool, +} + +impl Drop for Claimed { + fn drop(&mut self) { + if self.fresh != 0 + && !*self.ran.get_mut() + && let Some(tiled) = self.on_demand.tiled() + { + tiled.unclaim(self.fresh); + } + } +} + +/// Levels on demand (`crate::tiles`): the card itself is about to write +/// title texture `resource` in `list` (a copy or a resolve into level +/// `level`, or into every level). If its host copy `texture` was made +/// without memory, the levels written get theirs when the list is +/// submitted, ahead of it on the queue; the ones that have none yet are +/// first written with zeros, here in the same list, so that what the +/// card's write does not cover is not what the tiles' last owner left. +/// To be called before the list is brought to the state of that write. +/// shortcut: two lists that write the same new level, submitted in the +/// other order than recorded, lose the first one's write under the zeros +/// of the other; so does an upload recorded and not yet submitted. +pub(crate) fn card_writes(list: &HostList, resource: This, texture: &ID3D12Resource, level: Option) { + let Some(on_demand) = crate::resource::host_tiled(resource) else { + return; + }; + let Some(tiled) = on_demand.tiled() else { + return; + }; + let levels = match level { + Some(level) => tiled.with_level(level), + None => tiled.every_level(), + }; + if levels == 0 { + return; + } + let fresh = tiled.claim(levels); + // Of them, the ones whose zeros could not be recorded. + let mut unzeroed = if host().is_none() { fresh } else { 0 }; + if fresh != 0 + && let Some(host) = host() + { + const COPY_DEST: u32 = 0x400; + crate::list::ensure_state(list, resource, COPY_DEST); + // SAFETY: a live resource. + let d = unsafe { texture.GetDesc() }; + for level in (0..u32::from(d.MipLevels).min(32)).filter(|&level| fresh & (1u32 << level) != 0) { + let mut footprint = D3D12_PLACED_SUBRESOURCE_FOOTPRINT::default(); + let mut bytes = 0u64; + // SAFETY: outputs for one subresource. + unsafe { + host.device + .GetCopyableFootprints(&d, level, 1, 0, Some(&mut footprint), None, None, Some(&mut bytes)); + } + let Some((buffer, data)) = list.upload(host, bytes) else { + // (With the levels that share its tiles, if it is one of + // the small ones.) + unzeroed |= tiled.with_level(level); + continue; + }; + // SAFETY: a mapped buffer of `bytes` bytes, just made. + unsafe { std::ptr::write_bytes(data, 0, bytes as usize) }; + let to = D3D12_TEXTURE_COPY_LOCATION { + // SAFETY: a borrowed pointer the location never releases. + pResource: unsafe { std::mem::transmute_copy(texture) }, + Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, + Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { SubresourceIndex: level }, + }; + let from = D3D12_TEXTURE_COPY_LOCATION { + // SAFETY: as above; the list holds the buffer until it is reset. + pResource: unsafe { std::mem::transmute_copy(&buffer) }, + Type: D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT, + Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { PlacedFootprint: footprint }, + }; + // SAFETY: an open list; both locations name live resources. + unsafe { list.list.CopyTextureRegion(&to, 0, 0, 0, &from, None) }; + } + } + // A new level without its zeros gets no tiles from this list: the + // card's write into it is lost (the level reads zeros, as before the + // write), which is less wrong than a part write over what the tiles' + // last owner left. The next list that writes it claims it again. + unzeroed &= fresh; + if unzeroed != 0 { + tiled.unclaim(unzeroed); + } + let levels = levels & !unzeroed; + if levels == 0 { + return; + } + let memory = crate::resource::texture_memory(resource).map_or(0, |(memory, _)| memory as u64); + let step = Claimed { + on_demand, + fresh: fresh & !unzeroed, + ran: std::sync::atomic::AtomicBool::new(false), + }; + list.defer_host(move || { + step.ran.store(true, std::sync::atomic::Ordering::Relaxed); + step.on_demand.card_wrote(levels, memory); + }); +} + +impl Staging { + /// Levels on demand: what says, beside the mapping, which levels of + /// the texture are the title's now. First the lowest level a live view + /// of the texture shows (0 without a view that says): the title's own + /// word, a texture it holds from level 3 on is viewed from level 3. + /// Then where the next texture placed in this one's span starts, in + /// bytes from this one's start (`u64::MAX`: none does): for a texture + /// viewed from level 0 although a neighbour sits where its large + /// levels would be. + fn judgement(&self) -> [u64; 2] { + let start = self.memory as u64; + let first = crate::descriptor::host::first_viewed(start).map_or(0, u64::from); + let limit = crate::descriptor::host::next_start(start, start.saturating_add(self.layout.size)) + .map_or(u64::MAX, |at| at - start); + [first, limit] + } + + /// What [`Staging::judgement`] said at the last detiling. + fn judged(&self) -> [u64; 2] { + use std::sync::atomic::Ordering::Relaxed; + [self.judged[0].load(Relaxed), self.judged[1].load(Relaxed)] + } + + /// Levels on demand: the levels that are the title's now, a bit a + /// level. A level is held if no view starts above it, its bytes end + /// before the next texture starts, and all of them are mapped. The + /// smallest levels share the texture's first block and are held + /// together. (The console layout: that block first, then the other + /// levels from the smallest up, level 0 last: + /// `leonida_formats::texture::Layout`.) A texture this cannot tell + /// the levels of holds them all. + fn held_levels(&self, [first, limit]: [u64; 2]) -> u32 { + let mips = &self.layout.mips; + if self.layout.slices != 1 || mips.is_empty() || mips.len() > 32 { + return u32::MAX; + } + let tail = (self.layout.first_tail_mip as usize).min(mips.len()); + let there = |from: u64, to: u64| { + to > from && to <= limit && committed(self.memory.wrapping_add(from as usize), (to - from) as usize) + }; + let mut held = 0u32; + for (level, m) in mips.iter().enumerate().take(tail) { + let end = if level == 0 { self.layout.slice_size } else { mips[level - 1].offset }; + if level as u64 >= first && there(m.offset, end) { + held |= 1 << level; + } + } + if tail < mips.len() && there(0, self.layout.alignment.min(self.layout.slice_size)) { + for level in tail..mips.len() { + if level as u64 >= first { + held |= 1 << level; + } + } + } + held + } + + /// Forgets what the staging buffer was last filled from: the next + /// refresh detiles anew, whether the memory changed or not. + fn forget(&self) { + *self.last.lock().unwrap_or_else(|e| e.into_inner()) = Last::default(); + } + + /// The title memory the texture is read from: address and bytes. + pub(crate) fn memory(&self) -> (usize, usize) { + (self.memory as usize, self.layout.size as usize) + } + + /// Detiles the texture memory into the staging buffer if it changed + /// since the last time (and is mapped at all). + pub(crate) fn refresh(&self) { + use std::sync::atomic::Ordering::Relaxed; + let started = std::time::Instant::now(); + let read = self.refresh_now(); + let preparing = &crate::host::PREPARING; + preparing[2].fetch_add(started.elapsed().as_micros() as u64, Relaxed); + preparing[3].fetch_add(read as u64, Relaxed); + } + + /// Returns the bytes of title memory read. + fn refresh_now(&self) -> usize { + let whole = std::time::Instant::now(); + let read = self.refresh_timed(); + let us = whole.elapsed().as_micros() as u64; + REFRESH_WAITS[3].fetch_add(us, std::sync::atomic::Ordering::Relaxed); + crate::framelog::add(crate::framelog::T::RefreshUs, us); + read + } + + fn refresh_timed(&self) -> usize { + let size = self.layout.size as usize; + let start = self.memory as usize; + let mut last = waited(0, || self.last.lock().unwrap_or_else(|e| e.into_inner())); + let last = &mut *last; + if let Some((now, written)) = waited(1, || crate::watch::writes(start, start + size, false)) { + if last.asked != 0 && written.iter().all(|&(_, w)| w <= last.asked) { + return 0; + } + last.asked = now; + // Read through the copy, which stands unmapped pages: memory of + // big pools is too slow to ask page by page. + with_read(size, |read| { + crate::host::copy_mapped(read.as_mut_ptr(), self.memory, size, false); + self.detile(read); + }); + #[cfg(feature = "diagnostics")] + crate::copystat::add(crate::copystat::C::TexWatched, size as u64); + return size; + } + // View memory has no write-watch, and a texture there was hashed + // whole at every check: 229 MB and 51 ms a frame in a gameplay view + // where two textures change (run 58). It is guarded now, as buffers + // in view memory are: a write of the title's to it faults once and + // is noted, a mapping is announced by the runtime. While neither + // happened the texture is as it was. What the guard cannot see (a + // write to the same pages through another view) is still found by + // the hash, which is taken every eighth frame only, by the + // texture's address, so the textures take turns. + // `LEONIDA_TEXTURE_GUARD=0` hashes at every check, as before. + static GUARD: std::sync::OnceLock = std::sync::OnceLock::new(); + if *GUARD.get_or_init(|| std::env::var_os("LEONIDA_TEXTURE_GUARD").is_none_or(|v| v != "0")) + && let Some((now, written)) = waited(1, || crate::watch::writes(start, start + size, true)) + { + const HASH_EVERY: u64 = 8; + let unwritten = last.asked != 0 && written.iter().all(|&(_, w)| w <= last.asked); + last.asked = now; + let turn = crate::frame::current().wrapping_add((start >> 16) as u64).is_multiple_of(HASH_EVERY); + if unwritten && !turn { + return 0; + } + } + // From here on the texture's memory may be read in place. Held until + // that read is done: the runtime changes what title memory shows + // only with this taken alone, so what `committed` finds mapped + // stays mapped (see `crate::watch::title_memory_reading`; without + // it a page went between the asking and the read in runs 71 and + // 74). + let _mapped = if no_wait() { + // Not waited for: while the runtime remaps title memory the + // texture is read through the kernel instead, whole or not at + // all (`no_wait`). + let Some(mapped) = crate::watch::title_memory_reading_now() else { + return self.refresh_unlocked(last, size); + }; + mapped + } else { + waited(2, crate::watch::title_memory_reading) + }; + if !committed(self.memory, size) { + // Partly mapped: a streamed texture with only some mips' pages + // there, the usual state while it streams in. Read through the + // copy, which stands unmapped pages (zeros), and upload what + // is there; nothing at all mapped changes nothing. + // shortcut: read again at most every 30 frames (reading around + // unmapped pages is slow, and nothing tells us when pages + // arrive): a mip that streams in shows up to 30 frames late. + let frame = crate::frame::current(); + if last.partial.is_some_and(|at| frame < at + 30) { + return 0; + } + last.partial = Some(frame); + #[cfg(feature = "diagnostics")] + crate::copystat::add(crate::copystat::C::TexHashed, size as u64); + let changed = with_read(size, |read| { + crate::host::copy_mapped(read.as_mut_ptr(), self.memory, size, false); + let hash = blake3::hash(read); + if last.hash == Some(hash) { + return false; + } + last.hash = Some(hash); + if read.iter().all(|&b| b == 0) { + return false; + } + self.detile(read); + true + }); + #[cfg(feature = "diagnostics")] + if changed { + crate::copystat::add(crate::copystat::C::TexChanged, size as u64); + } + let _ = changed; + return size; + } + if through_copy() { + return with_title(self.memory, size, |tiled| { + let hash = blake3::hash(tiled); + #[cfg(feature = "diagnostics")] + crate::copystat::add(crate::copystat::C::TexHashed, size as u64); + if last.hash == Some(hash) { + return size; + } + last.hash = Some(hash); + self.detile(tiled); + #[cfg(feature = "diagnostics")] + crate::copystat::add(crate::copystat::C::TexChanged, size as u64); + size + }); + } + // SAFETY: committed memory of the texture's layout size, and it + // stays committed while `_mapped` is held. + let tiled = unsafe { std::slice::from_raw_parts(self.memory, size) }; + let hash = blake3::hash(tiled); + #[cfg(feature = "diagnostics")] + crate::copystat::add(crate::copystat::C::TexHashed, size as u64); + if last.hash == Some(hash) { + return size; + } + last.hash = Some(hash); + self.detile(tiled); + #[cfg(feature = "diagnostics")] + crate::copystat::add(crate::copystat::C::TexChanged, size as u64); + size + } + + /// A refresh while the runtime is remapping title memory ([`no_wait`]): + /// the texture is read through the kernel, which fails if a page of it + /// is not there at this moment. Then nothing is taken and the texture + /// is looked at again at its next refresh (what was learnt about writes + /// to it is forgotten, so that it is not passed over as unwritten). + /// Returns the bytes read. + fn refresh_unlocked(&self, last: &mut Last, size: usize) -> usize { + use std::sync::atomic::Ordering::Relaxed; + let read = with_read(size, |read| { + if !crate::host::read_into(self.memory, read) { + return false; + } + let hash = blake3::hash(read); + if last.hash != Some(hash) { + last.hash = Some(hash); + self.detile(read); + } + true + }); + if read { + UNLOCKED[0].fetch_add(1, Relaxed); + size + } else { + UNLOCKED[1].fetch_add(1, Relaxed); + last.asked = 0; + 0 + } + } + + /// Detiles `tiled` (the texture's memory) into the staging buffer. + fn detile(&self, tiled: &[u8]) { + self.dirty.store(true, std::sync::atomic::Ordering::Relaxed); + // Levels on demand: which levels are the title's is judged here, + // once, for what the staging buffer holds from now on. The step + // that gives levels their memory goes by this answer. + let held = if self.on_demand { + use std::sync::atomic::Ordering::Relaxed; + let judged = self.judgement(); + self.judged[0].store(judged[0], Relaxed); + self.judged[1].store(judged[1], Relaxed); + let held = self.held_levels(judged); + self.detiled.store(held, Relaxed); + held + } else { + u32::MAX + }; + #[cfg(feature = "diagnostics")] + if tiled.iter().all(|&b| b == 0) { + tracing::debug!( + memory = ?self.memory, + desc = ?self.layout.desc, + "a sampled texture's memory is all zero (not streamed yet, or a failed BCPack read)" + ); + } + for (i, (footprint, &rows)) in self.footprints.iter().zip(&self.rows).enumerate() { + let (mip, slice) = (i as u32 % self.mips, i as u32 / self.mips); + let f = footprint.Footprint; + let pitch = f.RowPitch as usize; + let len = pitch * rows as usize * f.Depth as usize; + // SAFETY: the subresource's part of the mapped staging buffer. + let linear = unsafe { + std::slice::from_raw_parts_mut(self.data.add(footprint.Offset as usize), len) + }; + if mip < 32 && held & (1 << mip) == 0 { + // Not the title's: zeros, not what lies in that memory. + linear.fill(0); + continue; + } + if let Err(e) = + self.layout + .detile(tiled, mip, slice, linear, pitch, pitch * rows as usize) + { + tracing::warn!(?e, mip, slice, "texture not detiled"); + return; + } + } + } +} + +/// Lets go of a title texture's staging buffer (lists that recorded an +/// upload from it hold it until they have run); the next upload makes one +/// anew. +pub(crate) fn unstage(resource: This) { + let mut map = STAGING.lock().unwrap_or_else(|e| e.into_inner()); + if let Some(map) = map.as_mut() { + map.remove(&(resource as usize)); + } +} + +/// Where a staged title texture's memory is: address and bytes. +pub(crate) fn staged_memory(resource: This) -> Option<(u64, u64)> { + let map = STAGING.lock().unwrap_or_else(|e| e.into_inner()); + let (at, len) = map.as_ref()?.get(&(resource as usize))?.memory(); + Some((at as u64, len as u64)) +} + +/// A fingerprint of the title memory `[at, at + len)`, never 0: of all of +/// it up to 48 KiB, else of 16 KiB at its start, its middle and its end +/// (a texture streams in whole mips; the small ones lie first). Read +/// through the kernel, so pages not there count as zeros. +pub(crate) fn fingerprint(at: u64, len: u64) -> u64 { + const WINDOW: usize = 16 << 10; + thread_local! { + static READ: std::cell::RefCell> = const { std::cell::RefCell::new(Vec::new()) }; + } + let len = len as usize; + let mut hasher = blake3::Hasher::new(); + READ.with(|read| { + let mut read = read.borrow_mut(); + read.resize(3 * WINDOW, 0); + let mut take = |from: usize, bytes: usize| { + read[..bytes].fill(0); + crate::host::copy_mapped(read.as_mut_ptr(), (at as usize + from) as *const u8, bytes, false); + hasher.update(&read[..bytes]); + }; + if len <= 3 * WINDOW { + take(0, len); + } else { + take(0, WINDOW); + take((len / 2) & !0xfff, WINDOW); + take(len - WINDOW, WINDOW); + } + }); + let hash = hasher.finalize(); + let mut first = [0u8; 8]; + first.copy_from_slice(&hash.as_bytes()[..8]); + u64::from_le_bytes(first) | 1 +} + +/// Whether a title texture has a staging buffer: a list recorded its +/// upload, and the lists that sample it check it at submission. +/// For the frame listing: whether a list has uploaded `resource`'s staging +/// buffer, and whether it was detiled since. None: it has none. +#[cfg(feature = "diagnostics")] +pub(crate) fn staged_state(resource: This) -> Option<(bool, bool)> { + use std::sync::atomic::Ordering::Relaxed; + let map = STAGING.lock().unwrap_or_else(|e| e.into_inner()); + let staging = map.as_ref()?.get(&(resource as usize))?; + Some((staging.uploaded.load(Relaxed), staging.dirty.load(Relaxed))) +} + +pub(crate) fn is_staged(resource: This) -> bool { + let map = STAGING.lock().unwrap_or_else(|e| e.into_inner()); + map.as_ref().is_some_and(|map| map.contains_key(&(resource as usize))) +} + +/// The bytes of a title texture's memory, and whether all of it is mapped, +/// if the texture has been staged for upload. +pub(crate) fn staged(resource: This) -> Option<(u64, bool)> { + let s = { + let map = STAGING.lock().unwrap_or_else(|e| e.into_inner()); + map.as_ref()?.get(&(resource as usize))?.clone() + }; + let size = s.layout.size as usize; + Some((size as u64, committed(s.memory, size))) +} + +/// Whether `[at, at + len)` is committed memory (streamed textures may be +/// unmapped until their pages arrive). +pub(crate) fn committed(at: *const u8, len: usize) -> bool { + if by_query() { + return committed_by_query(at, len); + } + if len == 0 { + return true; + } + let (there, of) = readable(at as usize, len, true); + there == of +} + +/// Whether the two questions above and below are put to `VirtualQuery`, as +/// they were (`LEONIDA_COMMITTED_QUERY=1`). `VirtualQuery` answers with the +/// length of the run of pages in the same state, which it finds by walking +/// the page tables to the run's end: 8.8 ms for one question in the title's +/// 1.1 GB block (round 6). The pass over the heap's views asks three or +/// more of them for every texture slot that is due, 3,000 slots a frame +/// when the card has no room (run 75): that pass then ran 208-264 ms, and +/// while it ran the submitting thread's write-watch askings waited behind +/// the walks (run 76: 8-22 askings a frame of 6-21 ms each, 46-172 ms). +fn by_query() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("LEONIDA_COMMITTED_QUERY").is_some_and(|v| v == "1")) +} + +/// Of the kernel's pages that hold `[at, at + len)` (`len > 0`): how many +/// can be read, and how many there are; with `all`, it stops at the first +/// that cannot. One question to the kernel for up to 256 pages at once +/// (`QueryWorkingSetEx`: the state of each page asked about, no walk); a +/// page not in the working set may still be there (never touched, or +/// trimmed), and a one-byte read through the kernel says. +/// A page that is committed and may not be read counts as not there, which +/// is what the callers ask for: they read or write the memory next. +fn readable(at: usize, len: usize, all: bool) -> (usize, usize) { + use windows_sys::Win32::System::ProcessStatus::{K32QueryWorkingSetEx, PSAPI_WORKING_SET_EX_INFORMATION}; + use windows_sys::Win32::System::Threading::GetCurrentProcess; + const KERNEL_PAGE: usize = 4096; + let (first, last) = (at / KERNEL_PAGE, at.saturating_add(len - 1) / KERNEL_PAGE); + let of = last - first + 1; + let mut there = 0; + // SAFETY: plain data. + let mut info: [PSAPI_WORKING_SET_EX_INFORMATION; 256] = unsafe { std::mem::zeroed() }; + let mut page = first; + while page <= last { + let n = (last - page + 1).min(info.len()); + for (i, entry) in info[..n].iter_mut().enumerate() { + entry.VirtualAddress = ((page + i) * KERNEL_PAGE) as *mut _; + } + // SAFETY: `n` entries of the size given; our own process. + let asked = unsafe { + K32QueryWorkingSetEx( + GetCurrentProcess(), + info.as_mut_ptr().cast(), + (n * size_of::()) as u32, + ) + } != 0; + for (i, entry) in info[..n].iter().enumerate() { + // Bit 0 of the answer: the page is in the working set. + // SAFETY: plain data the query filled in. + let valid = asked && unsafe { entry.VirtualAttributes.Flags } & 1 != 0; + let mut byte = [0u8]; + if valid || crate::host::read_into(((page + i) * KERNEL_PAGE) as *const u8, &mut byte) { + there += 1; + } else if all { + return (there, of); + } + } + page += n; + } + (there, of) +} + +fn committed_by_query(at: *const u8, len: usize) -> bool { + use windows_sys::Win32::System::Memory::{MEM_COMMIT, MEMORY_BASIC_INFORMATION, VirtualQuery}; + let mut p = at as usize; + let end = p + len; + while p < end { + // SAFETY: plain data filled in by the query. + let mut info: MEMORY_BASIC_INFORMATION = unsafe { std::mem::zeroed() }; + // SAFETY: a valid out pointer of the right size. + let n = unsafe { VirtualQuery(p as *const _, &mut info, size_of_val(&info)) }; + if n == 0 || info.State != MEM_COMMIT { + return false; + } + p = info.BaseAddress as usize + info.RegionSize; + } + true +} + +/// How many bytes of `[at, at + len)` are committed memory: all of a +/// texture that is there, some of one streaming in (its smaller mips lie +/// at the start of its memory, and their pages are mapped first), none of +/// one not there. With neither the first nor the last page committed the +/// answer is none without a look at the pages between (two queries for the +/// slots whose texture is away, which are asked again and again). +pub(crate) fn mapped_bytes(at: *const u8, len: usize) -> u64 { + use windows_sys::Win32::System::Memory::{MEM_COMMIT, MEMORY_BASIC_INFORMATION, VirtualQuery}; + if len == 0 { + return 0; + } + let start = at as usize; + let end = start.saturating_add(len); + if !committed(at, 1) && !committed((end - 1) as *const u8, 1) { + return 0; + } + if !by_query() { + static BY_PAGE: std::sync::OnceLock = std::sync::OnceLock::new(); + if *BY_PAGE.get_or_init(|| std::env::var_os("LEONIDA_MAPPED_BY_PAGE").is_some_and(|v| v == "1")) { + // By page, without the walk: whole pages, cut to the range. + let (there, _) = readable(start, len, false); + return (there as u64 * 4096).min(len as u64); + } + // By 64 KiB block, one page asked of each: the title's memory is + // mapped in blocks of that size (the console's page), and the + // answer is a measure of how much of a texture has arrived, not a + // promise that every byte can be read (the upload reads through the + // kernel). By page, a texture half there cost a failed kernel read + // for each of its missing pages, every frame it stayed due: 1,663 + // textures "uploaded in part" kept the pass over the heap's views at + // 90-160 ms a frame (run 81). `LEONIDA_MAPPED_BY_PAGE=1`: by page. + const BLOCK: usize = 64 << 10; + let mut there = 0u64; + let mut block = start & !(BLOCK - 1); + while block < end { + let (lo, hi) = (block.max(start), block.saturating_add(BLOCK).min(end)); + if readable(lo, 1, true).0 == 1 { + there += (hi - lo) as u64; + } + block = block.saturating_add(BLOCK); + } + return there; + } + let (mut p, mut there) = (start, 0u64); + while p < end { + // SAFETY: plain data filled in by the query. + let mut info: MEMORY_BASIC_INFORMATION = unsafe { std::mem::zeroed() }; + // SAFETY: a valid out pointer of the right size. + let n = unsafe { VirtualQuery(p as *const _, &mut info, size_of_val(&info)) }; + let next = (info.BaseAddress as usize).saturating_add(info.RegionSize).min(end); + if n == 0 || next <= p { + break; + } + if info.State == MEM_COMMIT { + there += (next - p) as u64; + } + p = next; + } + there +} + +/// The staging state of a title texture, made on first use. +fn staging(resource: This, texture: &ID3D12Resource) -> Option> { + // Asked before the table is locked: the sweep lets go of a staging + // buffer with its texture's host side locked, in that order. + let on_demand = crate::resource::host_tiled(resource).is_some(); + let mut map = STAGING.lock().unwrap_or_else(|e| e.into_inner()); + let map = map.get_or_insert_with(HashMap::new); + if let Some(s) = map.get(&(resource as usize)) { + return Some(s.clone()); + } + let (memory, desc) = crate::resource::texture_memory(resource)?; + let Some(layout) = crate::resource::texture_layout(&desc).map(|t| t.planes[0].layout.clone()) + else { + once!( + ?desc, + "texture contents without a console layout not uploaded" + ); + return None; + }; + if layout.desc.swizzle.xor() { + once!(?desc, "texture contents in an XOR mode not uploaded"); + return None; + } + let host = host()?; + // SAFETY: a live resource. + let d = unsafe { texture.GetDesc() }; + let count = if d.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE3D { + u32::from(d.MipLevels) + } else { + u32::from(d.MipLevels) * u32::from(d.DepthOrArraySize) + }; + let mut footprints = vec![D3D12_PLACED_SUBRESOURCE_FOOTPRINT::default(); count as usize]; + let mut rows = vec![0u32; count as usize]; + let mut total = 0; + // SAFETY: outputs for `count` subresources. + unsafe { + host.device.GetCopyableFootprints( + &d, + 0, + count, + 0, + Some(footprints.as_mut_ptr()), + Some(rows.as_mut_ptr()), + None, + Some(&mut total), + ); + } + let (buffer, data, pooled) = staging_buffer(host, total)?; + crate::host::name(&buffer, || { + format!( + "staging of {resource:?} {}x{}x{} f{}", + d.Width, d.Height, d.DepthOrArraySize, d.Format.0 + ) + }); + tracing::debug!(?desc, total, "texture contents uploaded from title memory"); + STAGED[0].fetch_add(1, std::sync::atomic::Ordering::Relaxed); + STAGED[1].fetch_add(total, std::sync::atomic::Ordering::Relaxed); + let s = Arc::new(Staging { + buffer, + #[cfg(feature = "diagnostics")] + size: total, + data, + footprints, + rows, + layout, + mips: u32::from(d.MipLevels), + bytes: total, + memory, + last: Mutex::default(), + dirty: std::sync::atomic::AtomicBool::new(true), + uploaded: std::sync::atomic::AtomicBool::new(false), + used: std::sync::atomic::AtomicU64::new(crate::host::moment()), + on_demand, + detiled: std::sync::atomic::AtomicU32::new(0), + judged: [const { std::sync::atomic::AtomicU64::new(0) }; 2], + waiting: std::sync::atomic::AtomicU64::new(0), + pooled, + }); + map.insert(resource as usize, s.clone()); + Some(s) +} + +#[cfg(test)] +mod title_memory_tests { + use super::with_title; + + /// Title memory whose tail is reserved and not committed reads through + /// the copy as its bytes and then zeros, without a fault; so does + /// memory a page of which is taken away between two reads, and the + /// zeros are zeros whatever the read buffer held before. + #[test] + fn an_uncommitted_tail_reads_as_zeros() { + use windows_sys::Win32::System::Memory::*; + const HEAD: usize = 0xb_0000; + const SIZE: usize = 0x20_0000; + // SAFETY: a private reservation of our own; only committed pages + // are written in place, and nothing else reads them in place. + unsafe { + // The read buffer holds something else first. + let other = vec![0x77u8; SIZE]; + with_title(other.as_ptr(), SIZE, |bytes| assert!(bytes.iter().all(|&b| b == 0x77))); + let base = VirtualAlloc(std::ptr::null(), SIZE, MEM_RESERVE, PAGE_NOACCESS).cast::(); + assert!(!base.is_null()); + assert_eq!(VirtualAlloc(base.cast(), HEAD, MEM_COMMIT, PAGE_READWRITE), base.cast()); + base.write_bytes(0x5a, HEAD); + with_title(base, SIZE, |bytes| { + assert!(bytes[..HEAD].iter().all(|&b| b == 0x5a), "what is mapped"); + assert!(bytes[HEAD..].iter().all(|&b| b == 0), "what is not: zeros"); + }); + // The title takes a page in the middle away: zeros from then + // on, the rest as before. + assert_ne!(VirtualFree(base.add(0x4_0000).cast(), 0x1_0000, MEM_DECOMMIT), 0); + with_title(base, SIZE, |bytes| { + assert!(bytes[..0x4_0000].iter().all(|&b| b == 0x5a)); + assert!(bytes[0x4_0000..0x5_0000].iter().all(|&b| b == 0)); + assert!(bytes[0x5_0000..HEAD].iter().all(|&b| b == 0x5a)); + assert!(bytes[HEAD..].iter().all(|&b| b == 0)); + }); + assert_ne!(VirtualFree(base.cast(), 0, MEM_RELEASE), 0); + } + } + + /// The texture both device-loss runs named last (16 texels wide, 4 or 8 + /// high, format 10, layout 0x100, console flags 0x300000; its memory + /// began 0x300 into a page in run 73 and 0x700 in run 72, and here also + /// 0xf00, so that a page line runs through it): what the detiling is + /// given and what it writes are the same read in place and read through + /// the copy, and the rows it writes end where the staging buffer the + /// host sizes for it ends (896 bytes for 4 rows of 128 bytes 256 apart, + /// 1,920 for 8). + #[test] + fn the_small_texture_of_runs_72_and_73_detiles_the_same_both_ways() { + use windows_sys::Win32::System::Memory::*; + for (height, within) in [(4u32, 0x300usize), (8, 0x700), (4, 0xf00), (8, 0xf00)] { + // The description as the log printed it, word for word. + let words: [u32; 14] = [3, 0, 0, 0, 16, 0, height, 65537, 10, 1, 0, 256, 3_145_728, 0]; + // SAFETY: fourteen words are a resource description (56 bytes, + // plain numbers). + let desc: crate::resource::ResourceDesc = unsafe { std::mem::transmute(words) }; + let layout = crate::resource::texture_layout(&desc) + .expect("a console layout") + .planes[0] + .layout + .clone(); + let size = layout.size as usize; + let (row, pitch) = (16 * 8, 256usize); + assert!(size >= row * height as usize, "the layout holds every texel"); + // Committed pages and a reserved one after them; the texture + // begins `within` bytes into the first, as the title placed it. + // SAFETY: our own reservation; the committed part is written + // and read in place, by this thread alone. + unsafe { + let pages = size.div_ceil(4096) + 1; + let base = VirtualAlloc(std::ptr::null(), (pages + 1) * 4096, MEM_RESERVE, PAGE_NOACCESS).cast::(); + assert!(!base.is_null()); + assert_eq!(VirtualAlloc(base.cast(), pages * 4096, MEM_COMMIT, PAGE_READWRITE), base.cast()); + for i in 0..pages * 4096 { + base.add(i).write((i * 7 + i / 251) as u8); + } + let memory = base.add(within); + let in_place = std::slice::from_raw_parts(memory, size); + // The bytes: the same in place and through the copy. + with_title(memory, size, |copied| assert_eq!(copied, in_place)); + // What the detiling writes: the same, and inside the bytes + // the host's staging buffer for this texture has. + let staged = (height as usize - 1) * pitch + row; + assert_eq!(staged, if height == 4 { 896 } else { 1920 }); + let detile = |tiled: &[u8]| { + // The slice `Staging::detile` hands over: whole rows. + let mut linear = vec![0xeeu8; pitch * height as usize]; + layout + .detile(tiled, 0, 0, &mut linear, pitch, pitch * height as usize) + .expect("detiled"); + linear + }; + let direct = detile(in_place); + let through = with_title(memory, size, |copied| detile(copied)); + assert_eq!(direct, through); + for y in 0..height as usize { + assert!(direct[y * pitch..][..row].iter().any(|&b| b != 0xee), "row {y} written"); + assert!(direct[y * pitch + row..(y + 1) * pitch].iter().all(|&b| b == 0xee), "nothing past row {y}"); + } + // A buffer of exactly the staged bytes is enough. + let mut exact = vec![0u8; staged]; + layout + .detile(in_place, 0, 0, &mut exact, pitch, pitch * height as usize) + .expect("the staging buffer's bytes are enough"); + assert_ne!(VirtualFree(base.cast(), 0, MEM_RELEASE), 0); + } + } + } +} diff --git a/crates/leonida-gpu/src/tiles.rs b/crates/leonida-gpu/src/tiles.rs new file mode 100644 index 000000000..39220452d --- /dev/null +++ b/crates/leonida-gpu/src/tiles.rs @@ -0,0 +1,1587 @@ +//! Levels on demand: host copies of title textures that take the card's +//! memory level by level, as the title holds the levels. +//! +//! The title places a texture's whole chain of levels in its address space +//! and holds only some of them: the smallest first, at the start of the +//! texture's memory. The memory of the larger ones is either not mapped, +//! or belongs to the next texture, which the title packs where they would +//! be (run 188). A host copy was a committed texture: every level of it +//! took the card's memory from the first upload on. Run 189's accounting +//! line counted 2.2 to 3.0 GB of 4.3 to 5.5 GB of host copies in levels +//! whose title memory was not mapped, on some 1,600 copies; with about +//! 2.2 to 3.1 GB of render targets that filled the card, and textures +//! that needed a new host copy waited for room (the main character's face +//! among them, runs 188 and 189). +//! +//! Here such a texture is a reserved one (`CreateReservedResource`): it has +//! every level, so level numbers and sizes are what they were, but no +//! memory. The rules: +//! - A level is given tiles of a heap of ours (`UpdateTileMappings`, on the +//! queue) only in a submission-time step of a list that also writes all +//! of that level: the upload of the texture (`texture.rs` `upload`, which +//! copies every level from the staging buffer every time), or, before +//! the card itself writes the texture (a copy, a resolve), an upload of +//! every level with every level given (`texture.rs` `make_whole`). The +//! step runs when the list is submitted, before the list is executed, so +//! the mapping is ahead of the copy on the queue. Tiles hold what their +//! last owner left; no level is shown before it is written whole. +//! - Which levels are held is said by one function, at the moment the +//! staging buffer is filled (`Staging::held_levels`): the levels whose +//! title memory is mapped and lies before the start of the next texture +//! placed in this one's span. The staging buffer holds zeros for the +//! others, and the step gives tiles by that same answer. +//! - The small levels the card packs into shared tiles are given together +//! when any of them is held; the upload writes all of them (zeros for +//! the ones not held). +//! - A shader must not reach a level without memory (it reads zeros: a +//! black texture). The host view of a slot is made from the first level +//! that is held and has tiles ([`show_from`], `descriptor/host.rs` +//! `make`), and the slots of a texture are made again when that level +//! changes (`HostHeap::texture_views_remade`). +//! - shortcut: tiles are not taken back while the host copy lives. A level +//! the title lets go of, or that turns out to be the next texture's, +//! keeps its tiles; it is hidden by the views and written with zeros at +//! the next upload. Its tiles go back when the host copy does. +//! +//! Only for a texture the title places in memory and fills, two-dimensional, +//! one layer, more than one level, of [`floor`] bytes or more, whose memory +//! is not all its own when the host copy is made (`resource.rs` `hosted`); +//! every other texture is made as before. Off unless +//! `LEONIDA_LEVELS_ON_DEMAND=1`. + +use std::sync::Mutex; +use std::sync::atomic::{AtomicU32, AtomicU64, Ordering}; + +use windows::Win32::Graphics::Direct3D12::*; + +use crate::host::host; + +/// The card's tile: 64 KiB. +const TILE: u64 = 64 << 10; + +/// Tiles in one heap of the pool (64 MiB). The largest level given is a +/// 4096x4096 one of one byte a texel: 256 tiles. +const HEAP_TILES: u32 = 1024; + +/// Since the start, or now: such textures alive; the bytes all their +/// levels would take; the bytes of the tiles given to them; the bytes of +/// the pool's heaps; such textures made in all; levels given; calls of +/// `UpdateTileMappings`; their microseconds; heaps given back to the card; +/// uploads that left a held level without tiles (the card had no room, or +/// no heap could be had); uploads recorded again for such a level. +pub(crate) static STATS: [AtomicU64; 11] = [const { AtomicU64::new(0) }; 11]; + +/// Whether textures are made this way: the switch +/// (`LEONIDA_LEVELS_ON_DEMAND=1`; off by default), and a card that reads +/// zeros from, and drops writes to, levels without memory (tiled resources +/// tier 2). +pub(crate) fn wanted() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| { + if !std::env::var_os("LEONIDA_LEVELS_ON_DEMAND").is_some_and(|v| v == "1") { + return false; + } + let Some(host) = host() else { + return false; + }; + let mut options = D3D12_FEATURE_DATA_D3D12_OPTIONS::default(); + // SAFETY: a plain query into a struct of its own size. + let asked = unsafe { + host.device.CheckFeatureSupport( + D3D12_FEATURE_D3D12_OPTIONS, + (&raw mut options).cast(), + size_of_val(&options) as u32, + ) + }; + let tier = options.TiledResourcesTier.0; + let on = asked.is_ok() && tier >= 2; + tracing::info!( + tier, + on, + floor_kb = floor() >> 10, + "host copies of title textures take the card's memory level by level (LEONIDA_LEVELS_ON_DEMAND=1)" + ); + on + }) +} + +fn parse_floor(value: Option<&str>) -> u64 { + value + .and_then(|v| v.trim().parse::().ok()) + .map_or(1 << 20, |kb| kb.max(64).saturating_mul(1024)) +} + +/// The bytes from which a texture is made this way: a megabyte, or +/// `LEONIDA_LEVELS_MIN_KB`. (The accounting of run 189: the levels not +/// held are 1.9 MB a copy on some 1,600 copies; a 512x512 texture has six +/// tiles at most, and most of the calls for nothing.) +pub(crate) fn floor() -> u64 { + static BYTES: std::sync::OnceLock = std::sync::OnceLock::new(); + *BYTES.get_or_init(|| parse_floor(std::env::var("LEONIDA_LEVELS_MIN_KB").ok().as_deref())) +} + +/// The bytes of the tiles given to textures now: the card's memory they +/// hold (`resource.rs` `room` counts it with the other host copies). +pub(crate) fn given_total() -> u64 { + STATS[2].load(Ordering::Relaxed) +} + +/// One heap of the pool and its free runs of tiles (first tile, tiles), in +/// order, no two touching. +struct Heap { + heap: ID3D12Heap, + free: Vec<(u32, u32)>, +} + +// SAFETY: a heap of the device, named only in queue and device calls, which +// any thread may make; its free runs are plain numbers behind `POOL`'s lock. +unsafe impl Send for Heap {} + +impl Heap { + fn free_tiles(&self) -> u32 { + self.free.iter().map(|run| run.1).sum() + } +} + +/// The pool's heaps by place; a place is empty after its heap went back to +/// the card (a texture names its heaps by place). +static POOL: Mutex>> = Mutex::new(Vec::new()); + +/// `count` tiles of one heap, in as many runs as it takes, the lowest free +/// tiles first (single free tiles are used up before a long run is cut): +/// the heap, its place in the pool and the runs (first tile, tiles). A new +/// heap is made when no heap has that many free. +fn take(device: &ID3D12Device, count: u32) -> Option<(ID3D12Heap, usize, Vec<(u32, u32)>)> { + if count == 0 || count > HEAP_TILES { + return None; + } + let mut pool = POOL.lock().unwrap_or_else(|e| e.into_inner()); + let found = pool.iter().position(|h| h.as_ref().is_some_and(|h| h.free_tiles() >= count)); + let index = match found { + Some(index) => index, + None => { + let desc = D3D12_HEAP_DESC { + SizeInBytes: u64::from(HEAP_TILES) * TILE, + Properties: D3D12_HEAP_PROPERTIES { + Type: D3D12_HEAP_TYPE_DEFAULT, + ..Default::default() + }, + Alignment: 0, + Flags: D3D12_HEAP_FLAG_ALLOW_ONLY_NON_RT_DS_TEXTURES, + }; + let mut made: Option = None; + // SAFETY: plain creation; the out pointer is ours. + if let Err(e) = unsafe { device.CreateHeap::(&raw const desc, &raw mut made) } { + tracing::warn!(error = %e, "no heap for texture levels given on demand: those levels stay empty"); + return None; + } + let fresh = Heap { + heap: made?, + free: vec![(0, HEAP_TILES)], + }; + STATS[3].fetch_add(u64::from(HEAP_TILES) * TILE, Ordering::Relaxed); + match pool.iter().position(Option::is_none) { + Some(index) => { + pool[index] = Some(fresh); + index + } + None => { + pool.push(Some(fresh)); + pool.len() - 1 + } + } + } + }; + let h = pool[index].as_mut()?; + let mut runs = Vec::new(); + let mut left = count; + while left > 0 { + let &(start, tiles) = h.free.first()?; + let part = tiles.min(left); + runs.push((start, part)); + if part == tiles { + h.free.remove(0); + } else { + h.free[0] = (start + part, tiles - part); + } + left -= part; + } + Some((h.heap.clone(), index, runs)) +} + +/// Gives the runs `runs` of the pool's heap at `index` back; runs that +/// touch become one. A heap with every tile free goes back to the card, +/// unless it is the pool's only one. (Called when the texture that held +/// the tiles is dropped: nothing on the card reads through its mappings +/// any more, as for any host texture that is dropped.) +fn give_back(index: usize, runs: &[(u32, u32)]) { + let mut pool = POOL.lock().unwrap_or_else(|e| e.into_inner()); + let Some(Some(h)) = pool.get_mut(index) else { + return; + }; + h.free.extend_from_slice(runs); + h.free.sort_unstable(); + let mut joined: Vec<(u32, u32)> = Vec::with_capacity(h.free.len()); + for &(from, tiles) in &h.free { + match joined.last_mut() { + Some(last) if last.0 + last.1 == from => last.1 += tiles, + _ => joined.push((from, tiles)), + } + } + h.free = joined; + let all_free = h.free_tiles() == HEAP_TILES; + if all_free && pool.iter().flatten().count() > 1 { + pool[index] = None; + STATS[3].fetch_sub(u64::from(HEAP_TILES) * TILE, Ordering::Relaxed); + STATS[8].fetch_add(1, Ordering::Relaxed); + } +} + +/// What is given so far to one texture. +struct Given { + /// Per level with tiles of its own: whether it has them. + levels: Vec, + /// Whether the small levels the card packs together have theirs. + packed: bool, + /// The runs taken: the heap's place, first tile, tiles. + runs: Vec<(usize, u32, u32)>, +} + +/// A host texture made without memory, and the tiles its levels have been +/// given. +pub(crate) struct Tiled { + /// Tiles of each level that has tiles of its own (level 0 first). + standard: Vec, + /// The tiles of the levels the card packs together (0: there are none); + /// they are the levels from `standard.len()` on. + packed: u32, + /// Levels in all. + levels: u32, + /// The bytes all its tiles would take. + pub(crate) full: u64, + given: Mutex, + /// The first level a view of the texture may show: the first one that + /// is held or was written by the card and has tiles (`u32::MAX`: none + /// yet). + shown: AtomicU32, + /// The levels held at the last upload (a bit a level). + held: AtomicU32, + /// The levels the card itself wrote, in lists submitted so far. + card: AtomicU32, + /// The levels a recorded list of the card's own writes has already + /// written with zeros first ([`Tiled::claim`]). + claimed: AtomicU32, +} + +impl Tiled { + /// For `texture`, just made reserved with `levels` levels and one + /// layer: how the card cuts it into tiles. `None` if the card will not + /// say, or cuts it in a way this does not handle; the caller then makes + /// the texture the old way. + pub(crate) fn make(device: &ID3D12Device, texture: &ID3D12Resource, levels: u32) -> Option { + if levels == 0 || levels > 16 { + return None; + } + let mut total = 0u32; + let mut packed = D3D12_PACKED_MIP_INFO::default(); + let mut shape = D3D12_TILE_SHAPE::default(); + let mut count = levels; + let mut tilings = vec![D3D12_SUBRESOURCE_TILING::default(); levels as usize]; + // SAFETY: outputs of our own, `count` tilings of them. + unsafe { + device.GetResourceTiling( + texture, + Some(&raw mut total), + Some(&raw mut packed), + Some(&raw mut shape), + Some(&raw mut count), + 0, + tilings.as_mut_ptr(), + ); + } + let standard_levels = u32::from(packed.NumStandardMips); + if total == 0 || standard_levels + u32::from(packed.NumPackedMips) != levels || standard_levels > count { + return None; + } + let mut standard = Vec::with_capacity(standard_levels as usize); + for tiling in &tilings[..standard_levels as usize] { + let tiles = tiling + .WidthInTiles + .checked_mul(u32::from(tiling.HeightInTiles)) + .and_then(|n| n.checked_mul(u32::from(tiling.DepthInTiles))) + .unwrap_or(0); + if tiles == 0 || tiles > HEAP_TILES || tiling.StartTileIndexInOverallResource == D3D12_PACKED_TILE { + return None; + } + standard.push(tiles); + } + let packed_tiles = if packed.NumPackedMips > 0 { packed.NumTilesForPackedMips } else { 0 }; + if (packed.NumPackedMips > 0 && packed_tiles == 0) || packed_tiles > HEAP_TILES { + return None; + } + let full = u64::from(total) * TILE; + STATS[0].fetch_add(1, Ordering::Relaxed); + STATS[1].fetch_add(full, Ordering::Relaxed); + STATS[4].fetch_add(1, Ordering::Relaxed); + Some(Tiled { + given: Mutex::new(Given { + levels: vec![false; standard.len()], + packed: false, + runs: Vec::new(), + }), + standard, + packed: packed_tiles, + levels, + full, + shown: AtomicU32::new(u32::MAX), + held: AtomicU32::new(0), + card: AtomicU32::new(0), + claimed: AtomicU32::new(0), + }) + } + + /// At the submission of a list that uploads every level of `texture` + /// from its staging buffer, of which `held` are the title's now (the + /// others are zeros there): tiles for the held ones that have none. + /// `room`: whether the card has room for more host copies + /// (`resource.rs` `room`). Without room no held level gets tiles: the + /// list still brings the levels that have theirs up to date (which + /// takes none of the card's memory), and its copies into the others go + /// nowhere. (An upload of a host copy that exists passes the full + /// card's gate in `draw.rs` on the ground that it takes no memory; + /// with tiles given here regardless, the line would not bound these + /// textures.) + /// Returns whether the first level a view may show changed, and + /// whether a level named is still without tiles (no room, or no heap + /// could be had): the caller has the upload recorded again later, or + /// the level would stay empty until the title writes the texture. + pub(crate) fn uploaded(&self, texture: &ID3D12Resource, held: u32, room: bool) -> (bool, bool) { + match host() { + Some(host) => self.uploaded_on(host.queue(), &host.device, texture, held, room), + None => (false, false), + } + } + + /// [`Tiled::uploaded`] on a queue and a device. + pub(crate) fn uploaded_on( + &self, + queue: &ID3D12CommandQueue, + device: &ID3D12Device, + texture: &ID3D12Resource, + held: u32, + room: bool, + ) -> (bool, bool) { + let held = held & self.every_level(); + let mut given = self.given.lock().unwrap_or_else(|e| e.into_inner()); + self.held.store(held, Ordering::Relaxed); + let card = self.card.load(Ordering::Relaxed); + let named = held | card; + // The levels the card itself writes are few and are not kept + // waiting: a write of the card's into no memory is lost. + let changed = self.give_locked(&mut given, queue, device, texture, named, if room { named } else { card }); + let missing = self.without_locked(&given, named) != 0; + (changed, missing) + } + + /// At the submission of a list in which the card itself writes the + /// levels `levels` of `texture` (after zeros, if they were new: + /// [`Tiled::claim`]): tiles for those that have none. Returns whether + /// the first level a view may show changed. + /// Only the levels this list writes get tiles here: a held level that + /// is waiting for room is written by no copy of this list, and tiles + /// hold what their last owner left. + pub(crate) fn card_wrote(&self, texture: &ID3D12Resource, levels: u32) -> bool { + match host() { + Some(host) => self.card_wrote_on(host.queue(), &host.device, texture, levels), + None => false, + } + } + + /// [`Tiled::card_wrote`] on a queue and a device. + pub(crate) fn card_wrote_on( + &self, + queue: &ID3D12CommandQueue, + device: &ID3D12Device, + texture: &ID3D12Resource, + levels: u32, + ) -> bool { + let levels = levels & self.every_level(); + let mut given = self.given.lock().unwrap_or_else(|e| e.into_inner()); + let prev = self.card.load(Ordering::Relaxed); + let changed = self.give_locked( + &mut given, + queue, + device, + texture, + prev | levels | self.held.load(Ordering::Relaxed), + levels, + ); + // Only levels that actually received tiles (or already had them) saw + // the card's write; a level that got no tiles saw its zeros and write + // dropped, so neither `card` nor `claimed` should keep it. + let without = self.without_locked(&given, levels); + let backed = levels & !without; + if backed != 0 { + self.card.fetch_or(backed, Ordering::Relaxed); + } + if without != 0 { + self.unclaim(without); + } + changed + } + + /// The bits of the levels that get their tiles with level `level`: + /// itself, or every level the card packs together if it is one of them. + pub(crate) fn with_level(&self, level: u32) -> u32 { + let first_packed = self.standard.len() as u32; + if level < first_packed { + 1 << level + } else if level < self.levels { + self.every_level() & !((1u32 << first_packed) - 1) + } else { + 0 + } + } + + /// Of `levels`, the ones that have no tiles now and that no list + /// recorded before has claimed: the caller's list writes them with + /// zeros before the card's own write, so that what the write does not + /// cover is not what the tiles' last owner left. + pub(crate) fn claim(&self, levels: u32) -> u32 { + let fresh = self.without(levels); + fresh & !self.claimed.fetch_or(fresh, Ordering::Relaxed) + } + + /// Gives up the claim on `levels` ([`Tiled::claim`]): the zeros of the + /// list that claimed them never reached tiles of theirs (the list was + /// reset without being submitted, the zeros could not be recorded, or + /// no tiles could be had), so the next list that writes them sends its + /// own. + /// shortcut: a second list recorded between the claim and this sends + /// no zeros; if it is the first whose write gets tiles, what that + /// write does not cover is what the tiles' last owner left. + pub(crate) fn unclaim(&self, levels: u32) { + self.claimed.fetch_and(!levels, Ordering::Relaxed); + } + + /// Of `levels` (a bit a level), the ones that have no tiles now. + pub(crate) fn without(&self, levels: u32) -> u32 { + let given = self.given.lock().unwrap_or_else(|e| e.into_inner()); + self.without_locked(&given, levels) + } + + fn without_locked(&self, given: &Given, levels: u32) -> u32 { + let first_packed = self.standard.len() as u32; + let mut without = 0; + for level in 0..self.levels.min(32) { + let has = if level < first_packed { given.levels[level as usize] } else { given.packed }; + if !has { + without |= 1 << level; + } + } + levels & without + } + + /// Gives tiles to the levels of `texture` that both `named` and `may` + /// name (a bit a level, level 0 the lowest) and that have none yet; + /// the levels the card packs together get theirs when any of them is + /// so named. `named`: the levels that are the title's or the card's + /// own, by which the first level a view may show is told; `may`: the + /// ones of them that may get tiles in this call. To be called only + /// from a submission-time step of a list that writes every level of + /// `may`, whole: the call is ahead of that list on `queue`, and tiles + /// hold what their last owner left. + /// Returns whether the first level a view may show changed + /// ([`Tiled::first_shown`]): the caller has the texture's slots made + /// again. + #[cfg(test)] + pub(crate) fn give_on( + &self, + queue: &ID3D12CommandQueue, + device: &ID3D12Device, + texture: &ID3D12Resource, + named: u32, + may: u32, + ) -> bool { + let mut given = self.given.lock().unwrap_or_else(|e| e.into_inner()); + self.give_locked(&mut given, queue, device, texture, named, may) + } + + fn give_locked( + &self, + given: &mut Given, + queue: &ID3D12CommandQueue, + device: &ID3D12Device, + texture: &ID3D12Resource, + named: u32, + may: u32, + ) -> bool { + let has = |level: u32| level < 32 && named & (1 << level) != 0; + let now = |level: u32| level < 32 && named & may & (1 << level) != 0; + let first_packed = self.standard.len() as u32; + // (subresource, tiles, the level if it has tiles of its own) to map now. + let mut wanted: Vec<(u32, u32, Option)> = Vec::new(); + for level in 0..first_packed { + if !given.levels[level as usize] && now(level) { + wanted.push((level, self.standard[level as usize], Some(level as usize))); + } + } + if self.packed > 0 && !given.packed && (first_packed..self.levels).any(now) { + wanted.push((first_packed, self.packed, None)); + } + for (subresource, tiles, level) in wanted { + let Some((heap, index, runs)) = take(device, tiles) else { + continue; + }; + let at = D3D12_TILED_RESOURCE_COORDINATE { + X: 0, + Y: 0, + Z: 0, + Subresource: subresource, + }; + let size = D3D12_TILE_REGION_SIZE { + NumTiles: tiles, + ..Default::default() + }; + // One region, the subresource's tiles in order, on as many + // ranges of the heap as the runs taken. + let flags = vec![D3D12_TILE_RANGE_FLAG_NONE; runs.len()]; + let starts: Vec = runs.iter().map(|run| run.0).collect(); + let counts: Vec = runs.iter().map(|run| run.1).collect(); + let began = std::time::Instant::now(); + // SAFETY: a live reserved texture and a live heap of ours; one + // region of `tiles` tiles from the subresource's first tile; + // `runs.len()` ranges whose counts add up to `tiles`, in three + // arrays of that length that live through the call. + unsafe { + queue.UpdateTileMappings( + texture, + 1, + Some(&raw const at), + Some(&raw const size), + &heap, + runs.len() as u32, + Some(flags.as_ptr()), + Some(starts.as_ptr()), + Some(counts.as_ptr()), + D3D12_TILE_MAPPING_FLAG_NONE, + ); + } + STATS[6].fetch_add(1, Ordering::Relaxed); + STATS[7].fetch_add(began.elapsed().as_micros() as u64, Ordering::Relaxed); + match level { + Some(level) => given.levels[level] = true, + None => given.packed = true, + } + for &(start, count) in &runs { + given.runs.push((index, start, count)); + } + STATS[2].fetch_add(u64::from(tiles) * TILE, Ordering::Relaxed); + STATS[5].fetch_add(1, Ordering::Relaxed); + } + let with_tiles = |level: u32| { + if level < first_packed { + given.levels[level as usize] + } else { + given.packed + } + }; + let shown = (0..self.levels).find(|&level| has(level) && with_tiles(level)).unwrap_or(u32::MAX); + self.shown.swap(shown, Ordering::Relaxed) != shown + } + + /// The first level a view of the texture may show; `None` while no + /// level is both held and given (the views are then as the title made + /// them, and read zeros). + pub(crate) fn first_shown(&self) -> Option { + let shown = self.shown.load(Ordering::Relaxed); + (shown != u32::MAX).then_some(shown) + } + + /// Whether level `level` has tiles. + #[cfg(test)] + fn has_tiles(&self, level: u32) -> bool { + let given = self.given.lock().unwrap_or_else(|e| e.into_inner()); + match given.levels.get(level as usize) { + Some(&has) => has, + None => level < self.levels && given.packed, + } + } + + /// Whether every level has tiles. + #[cfg(test)] + fn whole(&self) -> bool { + let given = self.given.lock().unwrap_or_else(|e| e.into_inner()); + given.levels.iter().all(|&has| has) && (self.packed == 0 || given.packed) + } + + /// A bit for every level of the texture. + pub(crate) fn every_level(&self) -> u32 { + if self.levels >= 32 { u32::MAX } else { (1 << self.levels) - 1 } + } + + /// The bytes of the tiles it has now. + pub(crate) fn given_bytes(&self) -> u64 { + let given = self.given.lock().unwrap_or_else(|e| e.into_inner()); + given.runs.iter().map(|run| u64::from(run.2) * TILE).sum() + } +} + +impl Drop for Tiled { + fn drop(&mut self) { + let given = self.given.get_mut().unwrap_or_else(|e| e.into_inner()); + let mut bytes = 0; + let mut by_heap: std::collections::BTreeMap> = std::collections::BTreeMap::new(); + for &(index, start, tiles) in &given.runs { + by_heap.entry(index).or_default().push((start, tiles)); + bytes += u64::from(tiles) * TILE; + } + for (index, runs) in by_heap { + give_back(index, &runs); + } + STATS[0].fetch_sub(1, Ordering::Relaxed); + STATS[1].fetch_sub(self.full, Ordering::Relaxed); + STATS[2].fetch_sub(bytes, Ordering::Relaxed); + } +} + +/// Keeps a two-dimensional shader view (2D or 2D array) from the levels +/// before `first` of a texture of `levels` levels: it starts at `first` if +/// it started before it, shows as many levels fewer (clamped to the +/// remaining levels), and reduces `ResourceMinLODClamp` by the same shift so +/// the effective minimum LOD stays at the same resource level. +pub(crate) fn show_from(desc: &mut D3D12_SHADER_RESOURCE_VIEW_DESC, first: u32, levels: u32) { + if first >= levels { + return; + } + let clamp = |most: &mut u32, mips: &mut u32, min_lod: &mut f32| { + if first <= *most { + return; + } + let fewer = first - *most; + *most = first; + if *mips != u32::MAX { + *mips = mips.saturating_sub(fewer).clamp(1, levels - first); + } + if *min_lod > 0.0 { + *min_lod = (*min_lod - fewer as f32).max(0.0); + } + }; + match desc.ViewDimension { + D3D12_SRV_DIMENSION_TEXTURE2D => { + // SAFETY: `ViewDimension` selects `Texture2D`. + let view = unsafe { &mut desc.Anonymous.Texture2D }; + clamp(&mut view.MostDetailedMip, &mut view.MipLevels, &mut view.ResourceMinLODClamp); + } + D3D12_SRV_DIMENSION_TEXTURE2DARRAY => { + // SAFETY: `ViewDimension` selects `Texture2DArray`. + let view = unsafe { &mut desc.Anonymous.Texture2DArray }; + clamp(&mut view.MostDetailedMip, &mut view.MipLevels, &mut view.ResourceMinLODClamp); + } + _ => {} + } +} + +/// For the log, with the texture queue's line: what this saves, and what +/// the mapping calls cost since the line before. +pub(crate) fn status() { + static BEFORE: [AtomicU64; 2] = [const { AtomicU64::new(0) }; 2]; + let s: Vec = STATS.iter().map(|s| s.load(Ordering::Relaxed)).collect(); + if s[4] == 0 { + return; + } + let calls = s[6] - BEFORE[0].swap(s[6], Ordering::Relaxed); + let micros = s[7] - BEFORE[1].swap(s[7], Ordering::Relaxed); + tracing::info!( + "textures with levels on demand: {} alive ({} made so far), {} MB of the card given to {} levels in all, \ + {} MB of the card not allocated for levels the title does not hold ({} MB if every level had memory); \ + the pool's heaps {} MB ({} given back to the card so far); since the line before: {} calls of \ + UpdateTileMappings in {} microseconds; in all {} calls, {} microseconds; {} uploads left a held \ + level without memory (no room on the card, or no heap), {} uploads were recorded again for one", + s[0], + s[4], + s[2] >> 20, + s[5], + s[1].saturating_sub(s[2]) >> 20, + s[1] >> 20, + s[3] >> 20, + s[8], + calls, + micros, + s[6], + s[7], + s[9], + s[10], + ); +} + +/// On the card, without the title: what levels on demand relies on, with +/// the pool and the mapping call of this module on a device of the test's +/// own. One test, one device: the pool is one for the process, and its +/// heaps belong to the device that made them. +/// +/// Run by name, alone, no game needed: +/// `cargo test -p leonida-gpu --release -- --ignored levels_on_demand --nocapture` +/// +/// It runs on the SOFTWARE adapter unless `LEONIDA_TILES_TEST_CARD=1`: on +/// that adapter nothing reaches the card or its driver, so nothing it does +/// can reset the driver or touch the screen. Wherever it runs, the debug +/// layer is switched on if Windows has it (the optional feature "Graphics +/// Tools"), its messages are printed after every step, and the test stops +/// at the first error or lost device with the step's name, before +/// anything else is sent. On the card it does not run without the layer, +/// and no wait is longer than 1.5 s. +#[cfg(test)] +mod tests { + use windows::Win32::Foundation::{HANDLE, WAIT_OBJECT_0}; + use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_12_0; + use windows::Win32::Graphics::Dxgi::Common::*; + use windows::Win32::System::Threading::{CreateEventW, WaitForSingleObject}; + use windows::core::{Interface, s}; + + use super::*; + use crate::host::{compile, transition, warp_adapter}; + + const SIDE: u32 = 1024; + const LEVELS: u16 = 11; + + /// Two views of one texture read at the same place and level: the + /// first as the layer makes it for a texture whose level 0 has no + /// memory, the second as the title asked. + const LOOK: &str = r#" +#define RS "DescriptorTable(SRV(t0, numDescriptors = 2)), UAV(u0), StaticSampler(s0, filter = FILTER_MIN_MAG_MIP_POINT)" +Texture2D clamped : register(t0); +Texture2D whole : register(t1); +SamplerState nearest : register(s0); +RWByteAddressBuffer words : register(u0); +[RootSignature(RS)] +[numthreads(1, 1, 1)] +void look() { + float4 a = clamped.SampleLevel(nearest, float2(0.3, 0.3), 0); + float4 b = whole.SampleLevel(nearest, float2(0.3, 0.3), 0); + words.Store(0, (uint)(a.x * 255.0 + 0.5)); + words.Store(4, (uint)(b.x * 255.0 + 0.5)); +} +"#; + + /// Where each level of a texture lies in a buffer of all of them: its + /// place, its rows, the bytes of a row that are the level's own, and + /// the buffer's bytes. + struct Laid { + footprints: Vec, + rows: Vec, + wide: Vec, + total: u64, + } + + struct Rig { + device: ID3D12Device, + queue: ID3D12CommandQueue, + allocator: ID3D12CommandAllocator, + list: ID3D12GraphicsCommandList, + fence: ID3D12Fence, + event: HANDLE, + submitted: u64, + /// The debug layer's messages, if Windows has the layer. + messages: Option, + /// What the test is doing, for the message when it stops. + step: &'static str, + /// On the card, not on the software adapter. + card: bool, + } + + impl Rig { + /// The software adapter, or the default one with + /// `LEONIDA_TILES_TEST_CARD=1`; `None` without one, without tiled + /// resources of tier 2, or on the card without the debug layer. + fn new() -> Option { + // SAFETY: plain object creation on a device of our own. + unsafe { + let card = std::env::var_os("LEONIDA_TILES_TEST_CARD").is_some_and(|v| v == "1"); + // The debug layer, before the device is made: a call that + // is not well formed is then refused and named by the + // runtime, not handed to the driver. + let mut layer: Option = None; + let layered = D3D12GetDebugInterface(&mut layer).is_ok() && layer.is_some(); + layer.iter().for_each(|l| l.EnableDebugLayer()); + if card && !layered { + eprintln!("no D3D12 debug layer (Windows optional feature \"Graphics Tools\"): not run on the card without it"); + return None; + } + let mut device: Option = None; + if card { + D3D12CreateDevice(None, D3D_FEATURE_LEVEL_12_0, &mut device).ok()?; + } else { + let adapter = warp_adapter().ok()?; + D3D12CreateDevice(&adapter, D3D_FEATURE_LEVEL_12_0, &mut device).ok()?; + } + let device = device?; + let messages = device.cast::().ok(); + let mut options = D3D12_FEATURE_DATA_D3D12_OPTIONS::default(); + device + .CheckFeatureSupport( + D3D12_FEATURE_D3D12_OPTIONS, + (&raw mut options).cast(), + size_of_val(&options) as u32, + ) + .ok()?; + eprintln!( + "levels on demand, {}: tiled resources tier {}, debug layer {}", + if card { "ON THE CARD" } else { "on the software adapter" }, + options.TiledResourcesTier.0, + if messages.is_some() { "on" } else { "not installed" } + ); + if options.TiledResourcesTier.0 < 2 { + return None; + } + let queue: ID3D12CommandQueue = device + .CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC { + Type: D3D12_COMMAND_LIST_TYPE_DIRECT, + ..Default::default() + }) + .ok()?; + let allocator: ID3D12CommandAllocator = + device.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT).ok()?; + let list: ID3D12GraphicsCommandList = device + .CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &allocator, None) + .ok()?; + let fence: ID3D12Fence = device.CreateFence(0, D3D12_FENCE_FLAG_NONE).ok()?; + let event = CreateEventW(None, false, false, None).ok()?; + Some(Rig { + device, + queue, + allocator, + list, + fence, + event, + submitted: 0, + messages, + step: "making the device", + card, + }) + } + } + + /// Prints what the debug layer said since the last call; the first + /// error among it (as `host.rs` `log_messages` reads them). + fn said(&self) -> Option { + let queue = self.messages.as_ref()?; + let mut first_error = None; + // SAFETY: each message is read into a buffer of the size the + // queue reports, then the queue is emptied. + unsafe { + for i in 0..queue.GetNumStoredMessages() { + let mut size = 0; + if queue.GetMessage(i, None, &mut size).is_err() || size == 0 { + continue; + } + let mut buffer = vec![0u64; size.div_ceil(8)]; + let message = buffer.as_mut_ptr().cast::(); + if queue.GetMessage(i, Some(message), &mut size).is_ok() { + let m = &*message; + let text = std::slice::from_raw_parts(m.pDescription, m.DescriptionByteLength); + let text = String::from_utf8_lossy(text); + let text = text.trim_end_matches('\0'); + eprintln!("D3D12 says (severity {}, id {}): {text}", m.Severity.0, m.ID.0); + if m.Severity.0 <= D3D12_MESSAGE_SEVERITY_ERROR.0 && first_error.is_none() { + first_error = Some(text.to_owned()); + } + } + } + queue.ClearStoredMessages(); + } + first_error + } + + /// Stops the test, naming the step, if the device is lost or the + /// debug layer reported an error: nothing more is sent after it. + fn check(&self, what: &str) { + let error = self.said(); + // SAFETY: a plain query. + let removed = unsafe { self.device.GetDeviceRemovedReason() }; + assert!(removed.is_ok(), "{}, {what}: the device is lost: {removed:?}", self.step); + assert!(error.is_none(), "{}, {what}: the debug layer reports an error: {}", self.step, error.unwrap_or_default()); + } + + /// Gives tiles as a submission would, and stops if the mapping + /// call was refused. + fn give(&self, tiled: &Tiled, texture: &ID3D12Resource, levels: u32) { + tiled.give_on(&self.queue, &self.device, texture, levels, levels); + self.check("tiles given"); + } + + /// Records with `record`, runs the list behind what is already on + /// the queue (tile mappings among it), waits for the card and + /// opens the list again. + fn run(&mut self, record: impl FnOnce(&ID3D12GraphicsCommandList)) { + record(&self.list); + self.submitted += 1; + // SAFETY: our list, queue and fence; the allocator is reset + // only after the card finished everything recorded from it. + unsafe { + self.list.Close().unwrap(); + let run: ID3D12CommandList = self.list.cast().unwrap(); + self.queue.ExecuteCommandLists(&[Some(run)]); + self.queue.Signal(&self.fence, self.submitted).unwrap(); + self.fence.SetEventOnCompletion(self.submitted, self.event).unwrap(); + // Never without end: a step is a few copies of a few + // megabytes. On the card the limit stays under Windows' own + // two seconds; the software adapter, which compiles its + // shader on first use and resets nothing, gets longer. + let limit = if self.card { 1500 } else { 20_000 }; + let waited = WaitForSingleObject(self.event, limit); + self.check("a submission"); + assert!( + waited == WAIT_OBJECT_0, + "{}: a submission did not finish within {limit} ms; stopped before another is sent", + self.step + ); + self.allocator.Reset().unwrap(); + self.list.Reset(&self.allocator, None).unwrap(); + } + } + + fn buffer(&self, kind: D3D12_HEAP_TYPE, flags: D3D12_RESOURCE_FLAGS, state: D3D12_RESOURCE_STATES, bytes: u64) -> ID3D12Resource { + let heap = D3D12_HEAP_PROPERTIES { + Type: kind, + ..Default::default() + }; + let desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, + Width: bytes, + Height: 1, + DepthOrArraySize: 1, + MipLevels: 1, + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, + Flags: flags, + ..Default::default() + }; + let mut out: Option = None; + // SAFETY: plain buffer creation. + unsafe { + self.device + .CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &desc, state, None, &mut out) + .unwrap(); + } + out.unwrap() + } + + /// A square texture description of `side` texels and `levels` + /// levels; `reserved`: in the layout a texture without memory of + /// its own must have. + fn desc(format: DXGI_FORMAT, side: u32, levels: u16, reserved: bool) -> D3D12_RESOURCE_DESC { + D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D, + Width: u64::from(side), + Height: side, + DepthOrArraySize: 1, + MipLevels: levels, + Format: format, + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Layout: if reserved { D3D12_TEXTURE_LAYOUT_64KB_UNDEFINED_SWIZZLE } else { D3D12_TEXTURE_LAYOUT_UNKNOWN }, + ..Default::default() + } + } + + /// A texture without memory, in the state copies into it need, and + /// how the card cuts it. + fn reserved(&self, desc: &D3D12_RESOURCE_DESC) -> (ID3D12Resource, Tiled) { + let mut made: Option = None; + // SAFETY: plain creation; a texture that is no target has no clear value. + let asked = unsafe { + self.device + .CreateReservedResource(desc, D3D12_RESOURCE_STATE_COPY_DEST, None, &mut made) + }; + // The layer's reason first, if it refused. + self.check("a texture without memory made"); + asked.expect("a reserved texture"); + let texture = made.expect("a reserved texture"); + let tiled = Tiled::make(&self.device, &texture, u32::from(desc.MipLevels)).expect("the card says how it cuts the texture"); + (texture, tiled) + } + + fn footprints(&self, desc: &D3D12_RESOURCE_DESC) -> Laid { + let levels = usize::from(desc.MipLevels); + let mut footprints = vec![D3D12_PLACED_SUBRESOURCE_FOOTPRINT::default(); levels]; + let mut rows = vec![0u32; levels]; + let mut wide = vec![0u64; levels]; + let mut total = 0u64; + // SAFETY: outputs for `levels` subresources. + unsafe { + self.device.GetCopyableFootprints( + desc, + 0, + levels as u32, + 0, + Some(footprints.as_mut_ptr()), + Some(rows.as_mut_ptr()), + Some(wide.as_mut_ptr()), + Some(&mut total), + ); + } + Laid { + footprints, + rows, + wide, + total, + } + } + + /// An upload buffer of `total` bytes in which the bytes of each + /// level are `byte(level)`. + fn filled(&self, layout: &Laid, byte: impl Fn(usize) -> u8) -> ID3D12Resource { + let (footprints, rows) = (&layout.footprints, &layout.rows); + let upload = self.buffer(D3D12_HEAP_TYPE_UPLOAD, D3D12_RESOURCE_FLAG_NONE, D3D12_RESOURCE_STATE_GENERIC_READ, layout.total); + // SAFETY: the buffer is `total` bytes; each level's rows lie inside it. + unsafe { + let mut data = std::ptr::null_mut(); + upload.Map(0, None, Some(&mut data)).unwrap(); + for (level, f) in footprints.iter().enumerate() { + let len = rows[level] as usize * f.Footprint.RowPitch as usize; + std::slice::from_raw_parts_mut(data.cast::().add(f.Offset as usize), len).fill(byte(level)); + } + upload.Unmap(0, None); + } + upload + } + + /// Copies every level of `texture` from `upload`, then every level + /// back, and gives for each level the first sixteen bytes read of + /// its first row and of the row and column half way (another tile + /// of a level of several). + fn round_trip( + &mut self, + texture: &ID3D12Resource, + layout: &Laid, + upload: Option<&ID3D12Resource>, + ) -> Vec<[Vec; 2]> { + let (footprints, rows) = (&layout.footprints, &layout.rows); + let back = self.buffer(D3D12_HEAP_TYPE_READBACK, D3D12_RESOURCE_FLAG_NONE, D3D12_RESOURCE_STATE_COPY_DEST, layout.total); + self.run(|list| { + // SAFETY: an open list; the texture and buffers outlive the run. + unsafe { + if let Some(upload) = upload { + for (level, f) in footprints.iter().enumerate() { + list.CopyTextureRegion(&sub(texture, level as u32), 0, 0, 0, &placed(upload, *f), None); + } + } + list.ResourceBarrier(&[transition(texture, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_COPY_SOURCE)]); + for (level, f) in footprints.iter().enumerate() { + list.CopyTextureRegion(&placed(&back, *f), 0, 0, 0, &sub(texture, level as u32), None); + } + list.ResourceBarrier(&[transition(texture, D3D12_RESOURCE_STATE_COPY_SOURCE, D3D12_RESOURCE_STATE_COPY_DEST)]); + } + }); + let mut read = Vec::new(); + // SAFETY: a read-back buffer of `total` bytes the finished list copied into. + unsafe { + let mut data = std::ptr::null_mut(); + back.Map(0, None, Some(&mut data)).unwrap(); + for (level, f) in footprints.iter().enumerate() { + let pitch = f.Footprint.RowPitch as usize; + let len = rows[level] as usize * pitch; + let bytes = std::slice::from_raw_parts(data.cast::().cast_const().add(f.Offset as usize), len); + // The bytes of a row that are the level's own (its + // blocks or texels; the rest of the pitch is padding). + let own = layout.wide[level] as usize; + let wide = own.min(len).min(16); + let first = bytes[..wide].to_vec(); + let middle = (rows[level] as usize / 2) * pitch + ((own / 2) & !15); + let far = if rows[level] >= 2 && own >= 32 && middle + wide <= len { + bytes[middle..middle + wide].to_vec() + } else { + first.clone() + }; + read.push([first, far]); + } + back.Unmap(0, None); + } + read + } + } + + fn sub(texture: &ID3D12Resource, index: u32) -> D3D12_TEXTURE_COPY_LOCATION { + D3D12_TEXTURE_COPY_LOCATION { + // SAFETY: a borrowed pointer the location never releases. + pResource: unsafe { std::mem::transmute_copy(texture) }, + Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, + Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { SubresourceIndex: index }, + } + } + + fn placed(buffer: &ID3D12Resource, footprint: D3D12_PLACED_SUBRESOURCE_FOOTPRINT) -> D3D12_TEXTURE_COPY_LOCATION { + D3D12_TEXTURE_COPY_LOCATION { + // SAFETY: as above. + pResource: unsafe { std::mem::transmute_copy(buffer) }, + Type: D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT, + Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { PlacedFootprint: footprint }, + } + } + + fn all(bytes: &[Vec; 2], want: u8) -> bool { + bytes.iter().all(|part| part.iter().all(|&b| b == want)) + } + + /// The levels from `first` on, a bit a level. + fn from_level(first: u32) -> u32 { + (u32::MAX << first) & ((1 << u32::from(LEVELS)) - 1) + } + + /// (i) Levels arrive one by one: after each step every level with + /// tiles reads back its own bytes and every level without reads zeros. + fn levels_arrive(rig: &mut Rig, format: DXGI_FORMAT) { + rig.step = if format == DXGI_FORMAT_BC7_UNORM { "step 1, levels arrive (BC7)" } else { "step 1, levels arrive (BC3)" }; + let desc = Rig::desc(format, SIDE, LEVELS, true); + let (texture, tiled) = rig.reserved(&desc); + // (The card packs the levels smaller than a tile into shared + // tiles; the software adapter may give each its own.) + eprintln!( + "format {}: {} levels with tiles of their own ({:?} tiles), {} tiles for the packed ones", + format.0, + tiled.standard.len(), + tiled.standard, + tiled.packed + ); + assert!(!rig.card || tiled.packed > 0, "on the card a 1024 texture has levels smaller than a tile"); + let layout = rig.footprints(&desc); + let upload = rig.filled(&layout, |level| level as u8 + 1); + for first in [3u32, 1, 0] { + // Ahead of the list on the queue, as at a submission. + rig.give(&tiled, &texture, from_level(first)); + let read = rig.round_trip(&texture, &layout, Some(&upload)); + for (level, bytes) in read.iter().enumerate() { + let want = if tiled.has_tiles(level as u32) { level as u8 + 1 } else { 0 }; + assert!(all(bytes, want), "format {} from level {first}: level {level} reads {bytes:?}, wanted {want}", format.0); + } + } + assert!(tiled.whole()); + assert_eq!(tiled.first_shown(), Some(0)); + } + + /// (ii) A copy on the card into a level without tiles is dropped; the + /// same copy in a list that runs after the level was given lands. + fn a_card_copy_lands_after_the_give(rig: &mut Rig) { + rig.step = "step 2, a copy on the card into a level without tiles"; + let format = DXGI_FORMAT_BC7_UNORM; + let desc = Rig::desc(format, SIDE, LEVELS, true); + let (texture, tiled) = rig.reserved(&desc); + let layout = rig.footprints(&desc); + // The last level with tiles of its own, and a texture of its size + // with every byte 0x5a to copy from. + let level = tiled.standard.len() as u32 - 1; + let source_desc = Rig::desc(format, SIDE >> level, 1, false); + let source_layout = rig.footprints(&source_desc); + let source_bytes = rig.filled(&source_layout, |_| 0x5a); + let mut made: Option = None; + let heap = D3D12_HEAP_PROPERTIES { + Type: D3D12_HEAP_TYPE_DEFAULT, + ..Default::default() + }; + // SAFETY: plain texture creation. + unsafe { + rig.device + .CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &source_desc, D3D12_RESOURCE_STATE_COPY_DEST, None, &mut made) + .unwrap(); + } + let source = made.unwrap(); + rig.run(|list| { + // SAFETY: an open list and live resources. + unsafe { + list.CopyTextureRegion(&sub(&source, 0), 0, 0, 0, &placed(&source_bytes, source_layout.footprints[0]), None); + list.ResourceBarrier(&[transition(&source, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_COPY_SOURCE)]); + // No tiles yet: this copy goes nowhere. + list.CopyTextureRegion(&sub(&texture, level), 0, 0, 0, &sub(&source, 0), None); + } + }); + let before = rig.round_trip(&texture, &layout, None); + assert!(all(&before[level as usize], 0), "a copy into a level without tiles left {:?}", before[level as usize]); + // As `texture.rs` `card_writes` has it: the give at the list's + // submission, the copy in the list. + assert_ne!(tiled.claim(tiled.with_level(level)), 0, "the level is new"); + rig.give(&tiled, &texture, tiled.with_level(level)); + rig.run(|list| { + // SAFETY: as above. + unsafe { list.CopyTextureRegion(&sub(&texture, level), 0, 0, 0, &sub(&source, 0), None) }; + }); + let after = rig.round_trip(&texture, &layout, None); + assert!(all(&after[level as usize], 0x5a), "the copy after the give left {:?}", after[level as usize]); + assert_eq!(tiled.claim(tiled.with_level(level)), 0, "claimed once"); + } + + /// (iii) Tiles a texture gave back go to the next one, which reads + /// what was written into it and zeros where it has no tiles; what a + /// level given and not written reads is printed (the reason no level + /// is given outside a list that writes it). + fn a_reused_tile_reads_as_written(rig: &mut Rig) { + rig.step = "step 3, a reused tile"; + let desc = Rig::desc(DXGI_FORMAT_BC7_UNORM, SIDE, LEVELS, true); + let layout = rig.footprints(&desc); + let (first, first_tiles) = rig.reserved(&desc); + let level = first_tiles.standard.len() as u32 - 1; + rig.give(&first_tiles, &first, 1 << level); + let upload = rig.filled(&layout, |_| 0xa5); + let read = rig.round_trip(&first, &layout, Some(&upload)); + assert!(all(&read[level as usize], 0xa5)); + let runs = first_tiles.given.lock().unwrap().runs.clone(); + drop(first_tiles); + drop(first); + let (second, second_tiles) = rig.reserved(&desc); + rig.give(&second_tiles, &second, 1 << level); + let reused = second_tiles.given.lock().unwrap().runs == runs; + let unwritten = rig.round_trip(&second, &layout, None); + eprintln!( + "a level given tiles and not written reads {:?} (its tiles are the first texture's: {reused})", + &unwritten[level as usize][0][..4] + ); + let upload = rig.filled(&layout, |_| 0x3c); + let read = rig.round_trip(&second, &layout, Some(&upload)); + assert!(all(&read[level as usize], 0x3c), "the reused level reads {:?}", read[level as usize]); + assert!(all(&read[0], 0), "level 0 has no tiles and reads {:?}", read[0]); + } + + /// (iv) A level whose tiles come from several runs of the heap (single + /// free tiles between taken ones) reads as written in every tile. + fn a_level_on_several_ranges(rig: &mut Rig) { + rig.step = "step 4, a level on several ranges of the heap"; + // Three single tiles; the first and the last go back, the middle + // one stays taken. + let singles: Vec<_> = (0..3).map(|_| take(&rig.device, 1).expect("a tile")).collect(); + give_back(singles[0].1, &singles[0].2); + give_back(singles[2].1, &singles[2].2); + let desc = Rig::desc(DXGI_FORMAT_BC7_UNORM, SIDE, LEVELS, true); + let layout = rig.footprints(&desc); + let (texture, tiled) = rig.reserved(&desc); + // Level 1 of a 1024 texture: four tiles. + assert!(tiled.standard.len() > 1 && tiled.standard[1] >= 2); + rig.give(&tiled, &texture, 1 << 1); + let runs = tiled.given.lock().unwrap().runs.len(); + eprintln!("level 1 ({} tiles) was mapped on {runs} ranges", tiled.standard[1]); + assert!(runs >= 2, "the single free tiles were not used first"); + let upload = rig.filled(&layout, |_| 0x77); + let read = rig.round_trip(&texture, &layout, Some(&upload)); + assert!(all(&read[1], 0x77), "level 1 reads {:?}", read[1]); + give_back(singles[1].1, &singles[1].2); + } + + /// (v) A view made by [`show_from`] of a texture whose level 0 has no + /// tiles returns level 1's colour for a sample at level 0; the view as + /// the title asked returns zero. + fn the_view_starts_at_the_first_level_with_tiles(rig: &mut Rig) -> Option<()> { + rig.step = "step 5, the view from the first level with tiles"; + let cs = compile(LOOK, s!("look"), s!("cs_5_1")).ok()?; + let format = DXGI_FORMAT_R8G8B8A8_UNORM; + let desc = Rig::desc(format, SIDE, LEVELS, true); + let layout = rig.footprints(&desc); + let (texture, tiled) = rig.reserved(&desc); + // Every level but the largest; each level's bytes are sixteen + // times its number plus one. + rig.give(&tiled, &texture, from_level(1)); + assert_eq!(tiled.first_shown(), Some(1)); + let upload = rig.filled(&layout, |level| (level as u8 + 1) * 16); + rig.round_trip(&texture, &layout, Some(&upload)); + // SAFETY: plain object creation; the views are made in a heap + // that lives to the end of the function, of a live texture. + let (root, pipeline, views, words, back) = unsafe { + let root: ID3D12RootSignature = rig.device.CreateRootSignature(0, &cs[..]).ok()?; + let pipeline: ID3D12PipelineState = rig + .device + .CreateComputePipelineState(&D3D12_COMPUTE_PIPELINE_STATE_DESC { + pRootSignature: std::mem::transmute_copy(&root), + CS: D3D12_SHADER_BYTECODE { + pShaderBytecode: cs.as_ptr().cast(), + BytecodeLength: cs.len(), + }, + ..Default::default() + }) + .ok()?; + let views: ID3D12DescriptorHeap = rig + .device + .CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC { + Type: D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, + NumDescriptors: 2, + Flags: D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE, + NodeMask: 0, + }) + .ok()?; + let as_asked = D3D12_SHADER_RESOURCE_VIEW_DESC { + Format: format, + ViewDimension: D3D12_SRV_DIMENSION_TEXTURE2D, + Shader4ComponentMapping: 5768, + Anonymous: D3D12_SHADER_RESOURCE_VIEW_DESC_0 { + Texture2D: D3D12_TEX2D_SRV { + MostDetailedMip: 0, + MipLevels: u32::MAX, + PlaneSlice: 0, + ResourceMinLODClamp: 0.0, + }, + }, + }; + let mut shown = as_asked; + show_from(&mut shown, tiled.first_shown()?, u32::from(LEVELS)); + assert_eq!(shown.Anonymous.Texture2D.MostDetailedMip, 1); + let step = rig.device.GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV) as usize; + let mut at = views.GetCPUDescriptorHandleForHeapStart(); + rig.device.CreateShaderResourceView(&texture, Some(&raw const shown), at); + at.ptr += step; + rig.device.CreateShaderResourceView(&texture, Some(&raw const as_asked), at); + let words = rig.buffer( + D3D12_HEAP_TYPE_DEFAULT, + D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS, + D3D12_RESOURCE_STATE_UNORDERED_ACCESS, + 256, + ); + let back = rig.buffer(D3D12_HEAP_TYPE_READBACK, D3D12_RESOURCE_FLAG_NONE, D3D12_RESOURCE_STATE_COPY_DEST, 256); + (root, pipeline, views, words, back) + }; + // Before the one dispatch: the pipeline and both views are sound. + rig.check("the pipeline and the views made"); + rig.run(|list| { + // SAFETY: an open list and live objects. + unsafe { + list.ResourceBarrier(&[transition(&texture, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE)]); + list.SetDescriptorHeaps(&[Some(views.clone())]); + list.SetComputeRootSignature(&root); + list.SetPipelineState(&pipeline); + list.SetComputeRootDescriptorTable(0, views.GetGPUDescriptorHandleForHeapStart()); + list.SetComputeRootUnorderedAccessView(1, words.GetGPUVirtualAddress()); + list.Dispatch(1, 1, 1); + list.ResourceBarrier(&[transition(&words, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_COPY_SOURCE)]); + list.CopyBufferRegion(&back, 0, &words, 0, 16); + } + }); + // SAFETY: a read-back buffer the finished list copied sixteen bytes into. + let read = unsafe { + let mut data = std::ptr::null_mut(); + let range = D3D12_RANGE { Begin: 0, End: 16 }; + back.Map(0, Some(&range), Some(&mut data)).unwrap(); + let read = std::slice::from_raw_parts(data.cast::(), 2).to_vec(); + back.Unmap(0, None); + read + }; + eprintln!("a sample at level 0: {} through the view from level 1, {} through the view as asked", read[0], read[1]); + assert_eq!(read[0], 32, "the view from the first level with tiles reads level 1"); + assert_eq!(read[1], 0, "the view from level 0 reads a level without tiles"); + Some(()) + } + + fn a_full_card_keeps_new_levels_waiting(rig: &mut Rig) { + rig.step = "step 6, no room on the card: held levels wait, and get their tiles when asked again"; + let desc = Rig::desc(DXGI_FORMAT_BC7_UNORM, SIDE, LEVELS, true); + let (texture, tiled) = rig.reserved(&desc); + let layout = rig.footprints(&desc); + let upload = rig.filled(&layout, |level| level as u8 + 1); + let read_as_given = |rig: &mut Rig, what: &str| { + let read = rig.round_trip(&texture, &layout, Some(&upload)); + for (level, bytes) in read.iter().enumerate() { + let want = if tiled.has_tiles(level as u32) { level as u8 + 1 } else { 0 }; + assert!(all(bytes, want), "{what}: level {level} reads {bytes:?}, wanted {want}"); + } + }; + // No room: nothing is given, the held levels are said to wait, + // nothing is shown, every level reads zeros. + let (changed, waiting) = tiled.uploaded_on(&rig.queue, &rig.device, &texture, from_level(3), false); + rig.check("an upload without room"); + assert!(!changed && waiting, "without room: changed {changed}, waiting {waiting}"); + assert_eq!(tiled.given_bytes(), 0, "without room no tile is given"); + assert_eq!(tiled.first_shown(), None); + read_as_given(rig, "without room"); + // Asked again with room: the same levels get theirs. + let (changed, waiting) = tiled.uploaded_on(&rig.queue, &rig.device, &texture, from_level(3), true); + rig.check("the upload again, with room"); + assert!(changed && !waiting, "with room: changed {changed}, waiting {waiting}"); + assert!(tiled.has_tiles(3) && !tiled.has_tiles(2)); + assert_eq!(tiled.first_shown(), Some(3)); + read_as_given(rig, "with room"); + // More levels held and no room again: the ones that have tiles + // are brought up to date, the new ones wait, the view stays. + let before = tiled.given_bytes(); + let (changed, waiting) = tiled.uploaded_on(&rig.queue, &rig.device, &texture, from_level(1), false); + rig.check("more levels held, without room"); + assert!(!changed && waiting, "more levels without room: changed {changed}, waiting {waiting}"); + assert_eq!(tiled.given_bytes(), before); + assert_eq!(tiled.first_shown(), Some(3)); + read_as_given(rig, "more levels without room"); + // The card's own write is not kept waiting, and brings only its + // own level: level 1 still waits although it is held. + assert_eq!(tiled.claim(1 << 0), 1 << 0); + let changed = tiled.card_wrote_on(&rig.queue, &rig.device, &texture, 1 << 0); + rig.check("the card's own write, without room"); + assert!(changed && tiled.has_tiles(0) && !tiled.has_tiles(1) && !tiled.has_tiles(2)); + assert_eq!(tiled.first_shown(), Some(0)); + assert_eq!(tiled.claim(1 << 0), 0, "a level with tiles is not claimed again"); + // With room everything held gets its tiles. + let (_, waiting) = tiled.uploaded_on(&rig.queue, &rig.device, &texture, from_level(1), true); + rig.check("the last upload, with room"); + assert!(!waiting && tiled.whole()); + read_as_given(rig, "everything given"); + } + + fn a_claim_given_up_is_made_again(rig: &mut Rig) { + rig.step = "step 7, a claim whose zeros never landed is given up"; + let desc = Rig::desc(DXGI_FORMAT_BC7_UNORM, SIDE, LEVELS, true); + let (_texture, tiled) = rig.reserved(&desc); + let level = tiled.with_level(2); + assert_eq!(tiled.claim(level), level, "the level is new"); + assert_eq!(tiled.claim(level), 0, "claimed once"); + // The list that claimed it was reset without being submitted. + tiled.unclaim(level); + assert_eq!(tiled.claim(level), level, "claimed again after it was given up"); + // The small levels the card packs together are claimed together. + let small = tiled.with_level(u32::from(LEVELS) - 1); + assert!(!rig.card || small.count_ones() > 1, "on the card a 1024 texture has several levels in one tile"); + assert_eq!(tiled.claim(1 << (u32::from(LEVELS) - 1)), 1 << (u32::from(LEVELS) - 1)); + tiled.unclaim(small); + assert_eq!(tiled.claim(small), small); + } + + /// On the software adapter unless `LEONIDA_TILES_TEST_CARD=1`. + #[test] + #[ignore = "on the card: run it by name with --ignored --nocapture"] + fn levels_on_demand_on_the_card() { + let Some(mut rig) = Rig::new() else { + eprintln!("no adapter with tiled resources of tier 2, or no debug layer for a run on the card; skipped"); + return; + }; + rig.check("the device made"); + levels_arrive(&mut rig, DXGI_FORMAT_BC7_UNORM); + levels_arrive(&mut rig, DXGI_FORMAT_BC3_UNORM); + a_card_copy_lands_after_the_give(&mut rig); + a_reused_tile_reads_as_written(&mut rig); + a_level_on_several_ranges(&mut rig); + a_full_card_keeps_new_levels_waiting(&mut rig); + a_claim_given_up_is_made_again(&mut rig); + if the_view_starts_at_the_first_level_with_tiles(&mut rig).is_none() { + eprintln!("the view test's shader or objects could not be made; that part was skipped"); + } + rig.step = "the end"; + rig.check("every step done"); + eprintln!( + "all steps passed {}", + if rig.card { "ON THE CARD" } else { "on the software adapter; LEONIDA_TILES_TEST_CARD=1 is the run on the card" } + ); + let s: Vec = STATS.iter().map(|s| s.load(Ordering::Relaxed)).collect(); + eprintln!( + "{} calls of UpdateTileMappings took {} microseconds in all ({} a call); the pool's heaps {} MB, {} given back", + s[6], + s[7], + s[7] / s[6].max(1), + s[3] >> 20, + s[8] + ); + } + + #[test] + fn floor_saturates_instead_of_wrapping() { + assert_eq!(parse_floor(None), 1 << 20); + assert_eq!(parse_floor(Some("0")), 64 << 10); + assert_eq!(parse_floor(Some("2048")), 2048 << 10); + assert_eq!(parse_floor(Some(&(1u64 << 54).to_string())), u64::MAX); + assert_eq!(parse_floor(Some(&u64::MAX.to_string())), u64::MAX); + } + + #[test] + fn show_from_clamps_2d_and_2d_array_and_adjusts_min_lod() { + let mut srv2d = D3D12_SHADER_RESOURCE_VIEW_DESC { + Format: DXGI_FORMAT_R8G8B8A8_UNORM, + ViewDimension: D3D12_SRV_DIMENSION_TEXTURE2D, + Shader4ComponentMapping: 5768, + Anonymous: D3D12_SHADER_RESOURCE_VIEW_DESC_0 { + Texture2D: D3D12_TEX2D_SRV { + MostDetailedMip: 0, + MipLevels: 12, + PlaneSlice: 0, + ResourceMinLODClamp: 3.5, + }, + }, + }; + show_from(&mut srv2d, 3, 11); + // SAFETY: `ViewDimension` is `TEXTURE2D`. + let v2d = unsafe { srv2d.Anonymous.Texture2D }; + assert_eq!(v2d.MostDetailedMip, 3); + // Clamped to remaining levels (11 - 3 = 8), not 12 - 3 = 9. + assert_eq!(v2d.MipLevels, 8); + assert_eq!(v2d.ResourceMinLODClamp, 0.5); + + let mut srv_arr = D3D12_SHADER_RESOURCE_VIEW_DESC { + Format: DXGI_FORMAT_R8G8B8A8_UNORM, + ViewDimension: D3D12_SRV_DIMENSION_TEXTURE2DARRAY, + Shader4ComponentMapping: 5768, + Anonymous: D3D12_SHADER_RESOURCE_VIEW_DESC_0 { + Texture2DArray: D3D12_TEX2D_ARRAY_SRV { + MostDetailedMip: 0, + MipLevels: 6, + FirstArraySlice: 0, + ArraySize: 1, + PlaneSlice: 0, + ResourceMinLODClamp: 1.5, + }, + }, + }; + show_from(&mut srv_arr, 2, 11); + // SAFETY: `ViewDimension` is `TEXTURE2DARRAY`. + let varr = unsafe { srv_arr.Anonymous.Texture2DArray }; + assert_eq!(varr.MostDetailedMip, 2); + assert_eq!(varr.MipLevels, 4); + assert_eq!(varr.ResourceMinLODClamp, 0.0); + } + + #[test] + fn card_wrote_failure_does_not_poison_card_mask() { + let Some(host) = host() else { + return; + }; + // A dummy live resource (never mapped because `take()` rejects `HEAP_TILES + 1`). + let heap = D3D12_HEAP_PROPERTIES { + Type: D3D12_HEAP_TYPE_DEFAULT, + ..Default::default() + }; + let desc = Rig::desc(DXGI_FORMAT_R8G8B8A8_UNORM, 64, 2, false); + let mut tex: Option = None; + // SAFETY: plain texture creation on the host device. + unsafe { + host.device + .CreateCommittedResource( + &heap, + D3D12_HEAP_FLAG_NONE, + &desc, + D3D12_RESOURCE_STATE_COMMON, + None, + &mut tex, + ) + .unwrap(); + } + let tex = tex.unwrap(); + STATS[0].fetch_add(1, Ordering::Relaxed); + STATS[1].fetch_add(TILE, Ordering::Relaxed); + let mut tiled = Tiled { + // Level 0 demands > HEAP_TILES so `take()` fails deterministically. + standard: vec![HEAP_TILES + 1, 1], + packed: 0, + levels: 2, + full: TILE, + given: Mutex::new(Given { + levels: vec![false, false], + packed: false, + runs: Vec::new(), + }), + shown: AtomicU32::new(u32::MAX), + held: AtomicU32::new(0), + card: AtomicU32::new(0), + claimed: AtomicU32::new(0), + }; + assert_eq!(tiled.claim(1 << 0), 1 << 0); + let changed = tiled.card_wrote_on(host.queue(), &host.device, &tex, 1 << 0); + assert!(!changed); + assert_eq!(tiled.card.load(Ordering::Relaxed), 0, "failed tile allocation must not poison `card`"); + assert_eq!(tiled.first_shown(), None); + assert_eq!(tiled.claim(1 << 0), 1 << 0, "failed level must be unclaimed"); + // Even if level 0 later becomes allocatable, an upload with `room == false` + // that does not hold level 0 must not treat level 0 as card-owned. + tiled.standard[0] = 1; + let (changed, waiting) = tiled.uploaded_on(host.queue(), &host.device, &tex, 1 << 1, false); + assert!(!changed && waiting); + assert!(!tiled.has_tiles(0)); + assert_eq!(tiled.given_bytes(), 0); + } +} diff --git a/crates/leonida-gpu/src/watch.rs b/crates/leonida-gpu/src/watch.rs new file mode 100644 index 000000000..4746e833e --- /dev/null +++ b/crates/leonida-gpu/src/watch.rs @@ -0,0 +1,1750 @@ +//! Which title memory the title wrote since a host copy took it (decision +//! 0007, "Copies of title memory"). The runtime reserves title GPU memory +//! with write watching (`leonida-hle` xmem), so the kernel keeps a dirty bit +//! per 4 KiB page; asking for a range's written pages also clears them. Host +//! copies of the same memory can overlap (nested buffers, textures in +//! buffers), so what one asks is kept here for the others: a journal of +//! each page's last write, numbered by the asking. +//! +//! Physical-page views (xmem's sections) cannot be write-watched. There a +//! copy leaves each 64 KiB block it took read-only, and our vectored handler +//! takes the first write to it: it notes the block as written and gives the +//! write access back. The runtime tells us when it maps or unmaps views +//! ([`title_memory_remapped`]), which resets their protection. Blocks found +//! wholly uncommitted are skipped while they remain so; one query can +//! confirm a whole region, including ordinary reservations between views. +//! +//! Writes into physical pages through another view are seen too: the +//! runtime tells us the views of the pages it wrote itself ([`writing`], +//! xmem's `write_physical` and DirectStorage's page destinations), and a +//! write by the title through any view of a guarded page faults like one +//! at the guarded address (the guard makes every view of the page +//! read-only, [`open`] gives them all back; not a page of more than +//! [`MANY_VIEWS`] views). A +//! system call writing into a guarded block fails (none is known to). + +use std::collections::{BTreeMap, BTreeSet}; +use std::sync::Mutex; + +/// The unit tracked and copied: 64 KiB, the console's page (the kernel's +/// 4 KiB pages fold into it). Finer units made the checks of the world's +/// big buffers cost more than the copies they saved. +pub(crate) const PAGE: usize = 64 << 10; +/// The kernel's page, the unit of its answers. +const KERNEL_PAGE: usize = 4096; + +/// A title-memory range whose changed pages another subsystem needs to read. +pub(crate) struct Tracked { + start: usize, + end: usize, + seen: Mutex>, +} + +/// Tracks a runtime GPU-memory range, including physical-page views when +/// `views` is true. Other process memory is not tracked. +pub(crate) fn track(start: usize, len: usize, views: bool) -> Option { + let end = start.checked_add(len)?; + if len == 0 || writes(start, end, views).is_none() { + return None; + } + Some(Tracked { + start, + end, + seen: Mutex::default(), + }) +} + +struct Journal { + /// Numbers the askings; 0 is "never". + asked: u64, + /// Page number → the asking that last found it written. + written: BTreeMap, + /// Room for the kernel's answer. + found: Vec, + /// Page ranges asked ahead for a submission's refreshes ([`ask_ahead`]) + /// and the asking that did: `writes` answers for a range inside one + /// from the journal, without another kernel call. + ahead: Vec<(usize, usize)>, + ahead_asked: u64, + /// The ahead asking stands for a whole submission ([`ask_once`]): no + /// other ahead asking is made, and `ahead` stays, until + /// [`ask_once_end`]. + kept: bool, +} + +static JOURNAL: Mutex = Mutex::new(Journal { + asked: 0, + written: BTreeMap::new(), + found: Vec::new(), + ahead: Vec::new(), + ahead_asked: 0, + kept: false, +}); + +/// Ranges of one submission closer than this are asked about together: +/// walking the pages between them costs less than another kernel call (a +/// call that resets written pages costs 30-70 microseconds whatever the +/// range). +const AHEAD_GAP: usize = (8 << 20) / PAGE; +/// The most one asking covers (its answer needs 8 bytes per 4 KiB page). +const AHEAD_MAX: usize = (1 << 30) / PAGE; + +/// Asks the kernel about many ranges `(start, end)` at once, before the +/// [`writes`] of each: ranges close together are one asking, and `writes` +/// then answers from the journal until [`ask_ahead_done`]. The world's +/// submissions refresh thousands of host copies (6,664 askings a frame, +/// 456 ms, in run 14). Ranges that are not write-watched, or lie alone, are +/// left to `writes`. +pub(crate) fn ask_ahead(ranges: &[(usize, usize)]) { + let mut pieces: Vec<(usize, usize)> = ranges + .iter() + .filter(|r| r.0 < r.1) + .map(|&(start, end)| (start / PAGE, end.div_ceil(PAGE))) + .collect(); + if pieces.len() < 2 { + return; + } + pieces.sort_unstable(); + let mut j = JOURNAL.lock().unwrap_or_else(|e| e.into_inner()); + let j = &mut *j; + // The submission's one asking stands ([`ask_once`]): what it does not + // hold is left to `writes`. + if j.kept { + return; + } + // View memory the guards hold is left to `writes`, which answers it + // from the guards ([`known_view`]): the kernel's write watch can only + // fail there. Asked here with the others, a run holding such a range + // failed, was asked again by halves down to single ranges, failing + // each time, and the range then went to `writes` all the same (after + // triippywhale d0581a55). `LEONIDA_VIEW_ASK=1` asks as before. + #[cfg(feature = "diagnostics")] + let all = pieces.len(); + pieces.retain(|&(first, _)| !known_view(first * PAGE)); + #[cfg(feature = "diagnostics")] + AHEAD_VIEWS.fetch_add((all - pieces.len()) as u64, std::sync::atomic::Ordering::Relaxed); + j.asked += 1; + j.ahead_asked = j.asked; + j.ahead.clear(); + let mut i = 0; + while i < pieces.len() { + let first = pieces[i].0; + let mut last = pieces[i].1; + let mut k = i + 1; + while k < pieces.len() + && pieces[k].0 <= last + AHEAD_GAP + && last.max(pieces[k].1) - first <= AHEAD_MAX + { + last = last.max(pieces[k].1); + k += 1; + } + ask_run(j, &pieces[i..k]); + i = k; + } +} + +/// Since the last frame line: the kernel askings that took a millisecond +/// or more, their microseconds, and the longest asking's. An asking walks +/// page tables, some ten microseconds for most ranges; in run 75 the 2,644 +/// askings of a frame took 219 ms in the lines where the pass over the +/// heap's views ran long, 25-50 ms in the others. These numbers say +/// whether a few askings wait for something or all of them are slow. +#[cfg(feature = "diagnostics")] +static SLOW: [std::sync::atomic::AtomicU64; 3] = [const { std::sync::atomic::AtomicU64::new(0) }; 3]; + +#[cfg(feature = "diagnostics")] +fn slow(us: u64) { + use std::sync::atomic::Ordering::Relaxed; + if us >= 1000 { + SLOW[0].fetch_add(1, Relaxed); + SLOW[1].fetch_add(us, Relaxed); + } + SLOW[2].fetch_max(us, Relaxed); +} + +/// Since the last frame line: ranges of view memory the guards hold that a +/// submission's askings ahead ([`ask_ahead`], [`ask_once`]) left out. Each +/// was a kernel asking that failed, or several, before. +#[cfg(feature = "diagnostics")] +pub(crate) static AHEAD_VIEWS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + +/// [`SLOW`], taken. +#[cfg(feature = "diagnostics")] +pub(crate) fn slow_asks() -> [u64; 3] { + [0, 1, 2].map(|i| SLOW[i].swap(0, std::sync::atomic::Ordering::Relaxed)) +} + +/// The submission's refreshes are done: `writes` asks the kernel again. +pub(crate) fn ask_ahead_done() { + let mut j = JOURNAL.lock().unwrap_or_else(|e| e.into_inner()); + if !j.kept { + j.ahead.clear(); + } +} + +/// Whether a submission asks the kernel once, before its first refresh, +/// about every range its lists refresh (`LEONIDA_ASK_ONCE=1`; off by +/// default). +/// +/// A submission's refreshes are done in groups, between the title's own +/// buffer copies (each copy flushes the refreshes recorded before it), and +/// every group asked the kernel again: 2,644 askings a frame, 70 a +/// submission. With the switch the journal answers all of them from one +/// asking made when the submission starts. +/// +/// What changes: memory the title's other threads write while the +/// submission is being prepared is seen by the next submission's asking, +/// not by this one's later groups. What this submission's lists read was +/// written before they were submitted, so before the asking. Our own +/// writes into title memory while preparing are told to the journal +/// ([`wrote`]) or end the asking ([`ask_once_end`]). +pub(crate) fn once() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + // On by default since run 81 (with card buffers: 375-450 ms a frame + // against 573-647, the picture unchanged over four minutes); + // `LEONIDA_ASK_ONCE=0` asks per range, as before. + *ON.get_or_init(|| std::env::var_os("LEONIDA_ASK_ONCE").is_none_or(|v| v != "0")) +} + +/// With [`once`]: asks about `ranges` (everything a submission's lists +/// refresh) as [`ask_ahead`] does, and lets that asking stand until +/// [`ask_once_end`]. +pub(crate) fn ask_once(ranges: &[(usize, usize)]) { + if !once() { + return; + } + ask_once_end(); + ask_ahead(ranges); + let mut j = JOURNAL.lock().unwrap_or_else(|e| e.into_inner()); + let j = &mut *j; + if j.ahead.is_empty() { + // `ask_ahead` asked nothing (fewer than two ranges). + j.asked += 1; + j.ahead_asked = j.asked; + } + // `ask_ahead` leaves a range that lies alone to `writes`, which asks + // once per flush: with one asking for the submission that was every + // such range asked again at each of its 70 flushes (run 76: 2,300 + // askings a frame with the switch on, as without it). They are asked + // here, once; what is not write-watched stays with `writes`. + for &(start, end) in ranges { + if start >= end { + continue; + } + // View memory the guards hold is not asked about: the asking can + // only fail there, one failed kernel call for each such copy at + // every submission, and `writes` answers it from the guards + // (after triippywhale cc368c7c). + if known_view(start) { + #[cfg(feature = "diagnostics")] + AHEAD_VIEWS.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + continue; + } + let (first, last) = (start / PAGE, end.div_ceil(PAGE)); + if !j.ahead.iter().any(|&(a, b)| a <= first && last <= b) && ask_kernel(j, first, last) { + j.ahead.push((first, last)); + } + } + j.kept = !j.ahead.is_empty(); +} + +/// The submission's one asking stands no longer: its refreshes are done, +/// or title memory was written in a way the journal was not told. +pub(crate) fn ask_once_end() { + let mut j = JOURNAL.lock().unwrap_or_else(|e| e.into_inner()); + if j.kept { + j.kept = false; + j.ahead.clear(); + } +} + +/// We wrote title memory `[at, at + len)` while a submission's one asking +/// stands (the title's buffer copies, done at submission): its pages count +/// as written after that asking, so the refreshes that follow copy them. +pub(crate) fn wrote(at: usize, len: usize) { + let mut j = JOURNAL.lock().unwrap_or_else(|e| e.into_inner()); + if !j.kept || len == 0 { + return; + } + j.asked += 1; + let now = j.asked; + // The asking that stands moves with it: `asked` and `writes` give it as + // "now", and a page noted written after "now" stays stale for every + // copy that takes it (copied at `now`, written at `now + 1`): copied + // again at every refresh, and a reason to settle flights + // (fxceless/leonida-fork#410). + j.ahead_asked = now; + for page in at / PAGE..at.saturating_add(len).div_ceil(PAGE) { + j.written.insert(page, now); + } +} + +/// We wrote the 64 KiB page numbered `page` of title memory through a +/// view of our own (`crate::inplace::write_own`): no guard was opened and +/// no kernel write-watch bit set, so the journal is told here. The page, +/// and the same physical page at its other title addresses (`others`, +/// page numbers), count as written at a new asking, which every host copy +/// that holds them takes at its next refresh. Returns the asking that had +/// last found `page` written (0: never) and the new one, for the copy +/// that wrote to note itself current. +pub(crate) fn wrote_own(page: usize, others: &[usize]) -> (u64, u64) { + let mut j = JOURNAL.lock().unwrap_or_else(|e| e.into_inner()); + let j = &mut *j; + j.asked += 1; + let now = j.asked; + // As in [`wrote`]: an asking that stands for a submission, or for a + // flush, moves with it, or a copy taking the page at the standing + // asking would find it written "later" at every refresh. + if j.kept || !j.ahead.is_empty() { + j.ahead_asked = now; + } + let before = j.written.insert(page, now).unwrap_or(0); + for &other in others { + if other != page { + j.written.insert(other, now); + } + } + (before, now) +} + +/// One kernel asking for `pieces` (page ranges in order); by halves if it +/// fails, as a run across two reservations or into memory that is not +/// write-watched does. A piece alone is left to [`writes`]. +fn ask_run(j: &mut Journal, pieces: &[(usize, usize)]) { + if pieces.len() < 2 { + return; + } + let first = pieces[0].0; + let last = pieces.iter().map(|p| p.1).max().unwrap_or(first); + if ask_kernel(j, first, last) { + j.ahead.push((first, last)); + return; + } + let (a, b) = pieces.split_at(pieces.len() / 2); + ask_run(j, a); + ask_run(j, b); +} + +/// Asks the kernel for the written pages of pages `[first, last)` and notes +/// them in the journal under the ahead asking; false (and nothing changed) +/// if the range is not write-watched memory of one reservation. +fn ask_kernel(j: &mut Journal, first: usize, last: usize) -> bool { + use windows_sys::Win32::System::Memory::GetWriteWatch; + const WRITE_WATCH_FLAG_RESET: u32 = 1; + let mut count = (last - first) * PAGE / KERNEL_PAGE; + j.found.resize(count.max(j.found.len()), 0); + let mut granularity = 0; + #[cfg(feature = "diagnostics")] + let started = std::time::Instant::now(); + // SAFETY: the answer buffer holds `count` entries. + let failed = unsafe { + GetWriteWatch( + WRITE_WATCH_FLAG_RESET, + (first * PAGE) as *const _, + (last - first) * PAGE, + j.found.as_mut_ptr().cast(), + &mut count, + &mut granularity, + ) + } != 0; + if failed { + return false; + } + #[cfg(feature = "diagnostics")] + { + use crate::copystat::{C, add}; + add(C::Watches, 1); + add(C::WatchUs, started.elapsed().as_micros() as u64); + slow(started.elapsed().as_micros() as u64); + } + let now = j.ahead_asked; + for k in 0..count { + let page = j.found[k] / PAGE; + j.written.insert(page, now); + } + true +} + +/// What [`writes`] would say of `[start, end)` from the journal alone, if +/// the range lies in one asked ahead ([`ask_ahead`], [`ask_once`]): the +/// pages written since tracking began and the asking that last found each +/// written, with the number of the asking that stands (as [`writes`] gives +/// it). `None` if the kernel would have to be asked. +pub(crate) fn asked(start: usize, end: usize) -> Option<(u64, Vec<(usize, u64)>)> { + let (first, last) = (start / PAGE, end.div_ceil(PAGE)); + let j = JOURNAL.lock().unwrap_or_else(|e| e.into_inner()); + j.ahead + .iter() + .any(|&(a, b)| a <= first && last <= b) + .then(|| (j.ahead_asked, j.written.range(first..last).map(|(&p, &w)| (p, w)).collect())) +} + +/// The pages of `[start, end)` (whole pages) as last written, for pages +/// written since tracking began: `(page number, asking)` in page order, and +/// this asking's number, which is higher than any in the list but those the +/// kernel just reported. `None` if the memory is not write-watched (nor, +/// with `guarded`, view memory, which is then guarded). +pub(crate) fn writes(start: usize, end: usize, guarded: bool) -> Option<(u64, Vec<(usize, u64)>)> { + use windows_sys::Win32::System::Memory::GetWriteWatch; + const WRITE_WATCH_FLAG_RESET: u32 = 1; + let (first, last) = (start / PAGE, end.div_ceil(PAGE)); + let mut j = JOURNAL.lock().unwrap_or_else(|e| e.into_inner()); + let j = &mut *j; + // Asked ahead with the submission's other ranges: the journal has it. + if j.ahead.iter().any(|&(a, b)| a <= first && last <= b) { + return Some(( + j.ahead_asked, + j.written + .range(first..last) + .map(|(&p, &w)| (p, w)) + .collect(), + )); + } + let mut count = (last - first) * PAGE / KERNEL_PAGE; + j.found.resize(count.max(j.found.len()), 0); + let mut granularity = 0; + #[cfg(feature = "diagnostics")] + let started = std::time::Instant::now(); + // View memory the guards already hold cannot be write-watched: the + // kernel asking would only fail. Copies of it are flushed many times a + // frame, each time paying that failed call before the guards answer. + let known_view = guarded && known_view(first * PAGE); + // SAFETY: the answer buffer holds `count` entries. + let failed = known_view + || unsafe { + GetWriteWatch( + WRITE_WATCH_FLAG_RESET, + (first * PAGE) as *const _, + (last - first) * PAGE, + j.found.as_mut_ptr().cast(), + &mut count, + &mut granularity, + ) + } != 0; + #[cfg(feature = "diagnostics")] + crate::copystat::add( + if known_view { + crate::copystat::C::WatchKnownView + } else { + crate::copystat::C::WatchFailed + }, + failed as u64, + ); + #[cfg(feature = "diagnostics")] + if failed && !known_view && guarded { + failed_asking(first * PAGE, last * PAGE); + } + let guarded = if failed { + count = 0; + if !guarded { + return None; + } + #[cfg(feature = "diagnostics")] + let guarding = std::time::Instant::now(); + let written = guard(first * PAGE, last * PAGE); + #[cfg(feature = "diagnostics")] + crate::copystat::add(crate::copystat::C::GuardUs, guarding.elapsed().as_micros() as u64); + written? + } else { + Vec::new() + }; + #[cfg(feature = "diagnostics")] + { + use crate::copystat::{C, add}; + add(C::Watches, 1); + add(C::WatchUs, started.elapsed().as_micros() as u64); + slow(started.elapsed().as_micros() as u64); + } + j.asked += 1; + let now = j.asked; + let pages = j.found[..count].iter().map(|&at| at / PAGE).chain(guarded); + for page in pages.collect::>() { + j.written.insert(page, now); + } + Some(( + now, + j.written + .range(first..last) + .map(|(&p, &w)| (p, w)) + .collect(), + )) +} + +/// Diagnostics: one in 2,048 of the askings the kernel's write watch +/// refused for memory the guards did not know (some 200 a frame in the +/// first rooms, each followed by a question to Windows about the memory): +/// what the memory is and what the guards hold of its first block. +#[cfg(feature = "diagnostics")] +fn failed_asking(start: usize, end: usize) { + use windows_sys::Win32::System::Memory::{MEMORY_BASIC_INFORMATION, VirtualQuery}; + static N: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + if N.fetch_add(1, std::sync::atomic::Ordering::Relaxed) % 2048 != 0 { + return; + } + // SAFETY: plain data filled in by the query. + let mut info: MEMORY_BASIC_INFORMATION = unsafe { std::mem::zeroed() }; + // SAFETY: a valid out pointer of the right size. + let n = unsafe { VirtualQuery(start as *const _, &mut info, size_of_val(&info)) }; + let (protected, clean, absent, viewed, aliased) = { + let g = guards(); + let b = start / BLOCK; + (g.protected.contains(&b), g.clean.contains(&b), g.absent.contains(&b), g.viewed.contains(&b), g.aliased.contains(&b)) + }; + tracing::info!( + "a failed write-watch asking (one in 2048): {start:#x}+{:#x}; Windows says (answered {n}): base {:#x} region {:#x} state {:#x} type {:#x} protect {:#x} allocation protect {:#x}; \ + the guards of its first block: protected {protected} clean {clean} absent {absent} viewed {viewed} aliased {aliased}; is a view: {}", + end - start, + info.BaseAddress as usize, + info.RegionSize, + info.State, + info.Type, + info.Protect, + info.AllocationProtect, + is_view(start, end) + ); +} + +impl Tracked { + /// Takes changed pages of `[from, to)`, cut to the tracked range. A + /// partial page stays changed so a later take can read its other bytes. + pub(crate) fn take(&self, from: usize, to: usize) -> Vec<(usize, usize)> { + let (from, to) = (from.max(self.start), to.min(self.end)); + if from >= to { + return Vec::new(); + } + let Some((_, pages)) = writes(from, to, true) else { + return Vec::new(); + }; + let mut seen = self.seen.lock().unwrap_or_else(|e| e.into_inner()); + let mut ranges: Vec<(usize, usize)> = Vec::new(); + for (page, write) in pages { + if seen.get(&page).is_some_and(|&last| last >= write) { + continue; + } + let (start, end) = ((page * PAGE).max(from), ((page + 1) * PAGE).min(to)); + if start >= end { + continue; + } + // Keep partial pages dirty: the caller has not taken the rest. + if (page * PAGE).max(self.start) >= from + && ((page + 1) * PAGE).min(self.end) <= to + { + seen.insert(page, write); + } + match ranges.last_mut() { + Some((_, last)) if *last == start => *last = end, + _ => ranges.push((start, end)), + } + } + ranges + } +} + +/// Guarded blocks of view memory. +const BLOCK: usize = PAGE; + +/// Whether the block holding `start` is view memory the guards already +/// hold (read-only by our hand, or noted absent): asking the kernel's write +/// watch about it can only fail. `LEONIDA_VIEW_ASK=1` (or +/// `LEONIDA_GUARD_ASK=1`) asks the kernel anyway, as before. +fn known_view(start: usize) -> bool { + static ASK: std::sync::OnceLock = std::sync::OnceLock::new(); + let ask = *ASK.get_or_init(|| { + ["LEONIDA_VIEW_ASK", "LEONIDA_GUARD_ASK"] + .iter() + .any(|n| std::env::var_os(n).is_some_and(|v| v == "1")) + }); + if ask { + return false; + } + let g = guards(); + let first = start / BLOCK; + g.protected.contains(&first) || g.absent.contains(&first) || (view_known() && g.viewed.contains(&first)) +} + +struct Guards { + /// Blocks we made read-only. + protected: BTreeSet, + /// Of those, the ones not written since a copy took them. + clean: BTreeSet, + /// Blocks already copied as zeros. While they remain wholly uncommitted, + /// the copy can skip hundreds of MB of failing kernel reads per world frame. + absent: BTreeSet, + /// Blocks whose physical page was guarded together with its other views + /// (those views' blocks are in it too): a write to one opens them all. + /// A write range can be huge (`fread`), so only these are looked up. + aliased: BTreeSet, + /// With [`view_known`]: blocks made read-only at least once since the + /// runtime last mapped or unmapped them. They are view memory whether + /// their guard stands now or a write has opened it. + viewed: BTreeSet, +} + +/// Whether a block once guarded stays known as view memory while its +/// guard is open (`LEONIDA_VIEW_KNOWN=1`; off by default). +/// +/// A range whose first block the title wrote since the last check has +/// that block neither read-only nor noted absent, so nothing says it is a +/// view: the kernel's write watch is asked and fails, and then Windows is +/// asked what the memory is (`is_view`), a walk of the page tables to the +/// end of the pages that share the first one's state. In runs 222 and 225 +/// that was 338-450 failed askings a frame and 6.5-7.8 ms a frame of the +/// submitting thread in `VirtualQuery`. With the switch the block is +/// remembered from the time it was first made read-only until the runtime +/// maps or unmaps it ([`title_memory_remapped`]). +/// +/// `LEONIDA_VIEW_KNOWN=alt`: twenty seconds with, twenty without, in turn, +/// each change said in the log, for measuring it in one scene. (Blocks +/// noted in one phase are forgotten at a remapping in either.) +fn view_known() -> bool { + /// 0 off, 1 on, 2 in turn. + static MODE: std::sync::OnceLock = std::sync::OnceLock::new(); + match *MODE.get_or_init(|| match std::env::var("LEONIDA_VIEW_KNOWN").as_deref() { + Ok("1") => 1, + Ok("alt") => 2, + _ => 0, + }) { + 0 => false, + 1 => true, + _ => { + static EPOCH: std::sync::OnceLock = std::sync::OnceLock::new(); + let on = (EPOCH.get_or_init(std::time::Instant::now).elapsed().as_secs() / 20) % 2 == 1; + static LAST: std::sync::atomic::AtomicU8 = std::sync::atomic::AtomicU8::new(2); + if LAST.swap(u8::from(on), std::sync::atomic::Ordering::Relaxed) != u8::from(on) { + tracing::info!( + "view memory stays known while its guard is open from now (LEONIDA_VIEW_KNOWN=alt): {}", + if on { "ON" } else { "off, as usual" } + ); + } + on + } + } +} + +static GUARDS: Mutex = Mutex::new(Guards { + protected: BTreeSet::new(), + clean: BTreeSet::new(), + absent: BTreeSet::new(), + aliased: BTreeSet::new(), + viewed: BTreeSet::new(), +}); + +fn guards() -> std::sync::MutexGuard<'static, Guards> { + GUARDS.lock().unwrap_or_else(|e| e.into_inner()) +} + +/// Whether the block `page` is read-only by our hand and unwritten since a +/// copy took it (diagnostics of `LEONIDA_BACK_OWN_CHECK`). +pub(crate) fn clean(page: usize) -> bool { + guards().clean.contains(&page) +} + +/// For view memory: the pages of `[start, end)`'s blocks written since +/// they were last guarded (all of a block's pages), guarding them again +/// before the caller copies them. `None` if the memory is not a view. +fn guard(start: usize, end: usize) -> Option> { + // A range whose first block the guards hold already (read-only by our + // hand, or noted absent) is a view: no question to Windows. The + // question walks the page tables to the end of the pages that share the + // first one's state, and a guarded view is one long run of read-only + // pages: 0.6 ms for the title's 174 MB heap, 16 times a frame, and most + // of the 68 ms a frame of "guards" (run 58). + // `LEONIDA_GUARD_ASK=1` asks every time, as before. + static ASK: std::sync::OnceLock = std::sync::OnceLock::new(); + let known = !*ASK.get_or_init(|| std::env::var_os("LEONIDA_GUARD_ASK").is_some_and(|v| v == "1")) && { + let g = guards(); + let first = start / BLOCK; + g.protected.contains(&first) || g.absent.contains(&first) || (view_known() && g.viewed.contains(&first)) + }; + if !known && !is_view(start, end) { + return None; + } + install(); + let mut g = guards(); + let mut written = Vec::new(); + let mut run: Option = None; + let (first, last) = (start / BLOCK, end.div_ceil(BLOCK)); + // The range's clean blocks, in order: read off the set in one pass, + // not looked up one block at a time. A frame asks about some 10 GB of + // view memory, 150,000 blocks, nearly all clean: the lookups were most + // of the 60-90 ms a frame of "guards" (run 54). What the loop adds to + // the set meanwhile is the block it stands at or ones before it. + let clean: Vec = g.clean.range(first..last).copied().collect(); + if clean.len() == last - first { + // Nothing written, mapped or new since the range was last taken. + return Some(written); + } + let mut next_clean = 0; + let mut uncommitted_until = first; + for block in first..=last { + while next_clean < clean.len() && clean[next_clean] < block { + next_clean += 1; + } + let is_clean = next_clean < clean.len() && clean[next_clean] == block; + let mut open = block < last && !is_clean; + if open && g.absent.contains(&block) { + // Ordinary commits need no runtime mapping notification. Reuse + // this asking's query for the following blocks in the same region. + if block >= uncommitted_until { + uncommitted_until = uncommitted_end(block); + } + open = block >= uncommitted_until; + if open { + g.absent.remove(&block); + } + } + if open { + written.extend(block * BLOCK / PAGE..(block + 1) * BLOCK / PAGE); + if g.protected.contains(&block) { + // Written through the runtime, still read-only. + g.clean.insert(block); + } else { + run.get_or_insert(block); + continue; + } + } + if let Some(from) = run.take() { + protect(&mut g, from, block); + } + } + Some(written) +} + +/// Whether `[start, end)` is view memory. The title's views lie in +/// placeholders, mapped and unmapped block by block as it streams, so a +/// range can begin in a block that is not mapped right now: the first +/// pages of the range that are there decide. A range with nothing there +/// counts as a view (its blocks are noted absent, and looked at again when +/// the runtime maps them). +/// +/// Looking at the first address only took such a range for "not a view": +/// its copy was marked not watched for good and copied whole at every +/// refresh, around its unmapped pages (run 54: 300 such ranges, 570 MB +/// copied a frame for them, 255 copies a frame reading around holes). +/// `LEONIDA_GUARD_HOLES=0` looks at the first address only, as before. +fn is_view(start: usize, end: usize) -> bool { + use windows_sys::Win32::System::Memory::{ + MEM_COMMIT, MEM_MAPPED, MEMORY_BASIC_INFORMATION, VirtualQuery, + }; + static HOLES: std::sync::OnceLock = std::sync::OnceLock::new(); + let holes = *HOLES.get_or_init(|| std::env::var_os("LEONIDA_GUARD_HOLES").is_none_or(|v| v != "0")); + let mut at = start; + loop { + // SAFETY: plain data filled in by the query. + let mut info: MEMORY_BASIC_INFORMATION = unsafe { std::mem::zeroed() }; + // SAFETY: a valid out pointer of the right size. + let n = unsafe { VirtualQuery(at as *const _, &mut info, size_of_val(&info)) }; + if n == 0 { + return false; + } + if info.Type == MEM_MAPPED { + return true; + } + // Committed memory that is no view (the title's heaps, ours), or + // the answer as it was before. + if info.State == MEM_COMMIT || !holes { + return false; + } + // A hole (a placeholder, or free): on to what follows it. + let next = (info.BaseAddress as usize).saturating_add(info.RegionSize); + if next <= at || next >= end { + return true; + } + at = next; + } +} + +/// Makes blocks `[from, to)` read-only and notes them guarded and clean; +/// block by block if they span views, leaving out any that fail, and +/// noting those not committed (unmapped) absent. The same physical pages +/// at every other view of them are made read-only too: a write through +/// one of those is this memory written, and only a fault can say so. +/// `LEONIDA_VIEW_GUARD=0` leaves the other views as they are, as before. +fn protect(g: &mut Guards, from: usize, to: usize) { + protect_here(g, from, to); + if !view_guard() { + return; + } + for (base, bytes) in crate::inplace::views_between(from.saturating_mul(BLOCK), to.saturating_mul(BLOCK)) { + let first = (base / BLOCK).max(from); + let last = (base.saturating_add(bytes).div_ceil(BLOCK)).min(to); + for block in first..last { + let shown = crate::inplace::pages_of(block * BLOCK); + // One view (nothing else to guard), or the page the title shows + // wherever it has nothing (thousands of views): each view of + // that one is guarded by itself. + if shown.len() < 2 || shown.len() > MANY_VIEWS { + continue; + } + #[cfg(feature = "diagnostics")] + ALIASES[0].fetch_add(1, std::sync::atomic::Ordering::Relaxed); + for alias in shown { + let alias = alias / BLOCK; + g.aliased.insert(alias); + if alias != block { + protect_alias(g, alias); + } + } + } + } +} + +/// Views of one page past which its views are not guarded together. +pub(crate) const MANY_VIEWS: usize = 64; + +/// Whether all the views of a guarded page are guarded together +/// (`LEONIDA_VIEW_GUARD`). +fn view_guard() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("LEONIDA_VIEW_GUARD").is_none_or(|v| v != "0")) +} + +/// Diagnostics: blocks guarded together with their other views, blocks +/// opened because another view of theirs was written, and blocks opened +/// because a view of theirs was mapped; since the start. +#[cfg(feature = "diagnostics")] +pub(crate) static ALIASES: [std::sync::atomic::AtomicU64; 3] = [const { std::sync::atomic::AtomicU64::new(0) }; 3]; + +/// Makes `block` read-only: another view of pages a copy has just taken +/// through its own view, so that a write through this one faults too. It is +/// not noted clean. The copies of title memory at this view have not taken +/// the pages: noted clean, the block would not be reported written at their +/// next check and they would keep the bytes from before the write (`guard` +/// reports a block that is read-only and not clean as written, then notes it +/// clean). A block that is clean stays so: had the pages been written since +/// its copies took them, `open` would have opened it. +fn protect_alias(g: &mut Guards, block: usize) { + use windows_sys::Win32::System::Memory::{PAGE_READONLY, VirtualProtect}; + if g.protected.contains(&block) { + return; + } + let mut old = 0; + // SAFETY: title view memory; only its protection changes. + if unsafe { VirtualProtect((block * BLOCK) as *const _, BLOCK, PAGE_READONLY, &mut old) } != 0 { + g.protected.insert(block); + if view_known() { + g.viewed.insert(block); + } + } +} + +/// [`protect`] for one range, without the other views of its pages. +fn protect_here(g: &mut Guards, from: usize, to: usize) { + use windows_sys::Win32::System::Memory::{PAGE_READONLY, VirtualProtect}; + let set = |from: usize, to: usize| { + let mut old = 0; + // SAFETY: title view memory; only its protection changes. + unsafe { + VirtualProtect( + (from * BLOCK) as *const _, + (to - from) * BLOCK, + PAGE_READONLY, + &mut old, + ) != 0 + } + }; + let note = |g: &mut Guards, from: usize, to: usize| { + g.protected.extend(from..to); + g.clean.extend(from..to); + if view_known() { + g.viewed.extend(from..to); + } + }; + if set(from, to) { + note(g, from, to); + return; + } + for block in from..to { + if set(block, block + 1) { + note(g, block, block + 1); + } else { + #[cfg(feature = "diagnostics")] + let error = std::io::Error::last_os_error(); + if block < uncommitted_end(block) { + g.absent.insert(block); + } else { + // Diagnostics: a committed block that will not be made + // read-only is reported written at every asking and never + // known to the guards (one in 1,024 said). + #[cfg(feature = "diagnostics")] + { + static N: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + if N.fetch_add(1, std::sync::atomic::Ordering::Relaxed) % 1024 == 0 { + tracing::info!("a block of title memory could not be made read-only (one in 1024): {:#x}: {error}", block * BLOCK); + } + } + } + } + } +} + +/// The end (exclusive) of the whole uncommitted blocks starting at `block`. +fn uncommitted_end(block: usize) -> usize { + use windows_sys::Win32::System::Memory::{ + MEM_FREE, MEM_RESERVE, MEMORY_BASIC_INFORMATION, VirtualQuery, + }; + // SAFETY: plain data filled in by the query. + let mut info: MEMORY_BASIC_INFORMATION = unsafe { std::mem::zeroed() }; + // SAFETY: a valid out pointer of the right size. + let n = unsafe { VirtualQuery((block * BLOCK) as *const _, &mut info, size_of_val(&info)) }; + if n != 0 && matches!(info.State, MEM_RESERVE | MEM_FREE) { + (info.BaseAddress as usize).saturating_add(info.RegionSize) / BLOCK + } else { + block + } +} + +/// Gives write access back to the guarded blocks of `[start, end)` and +/// notes them written; true if any was guarded. The same physical pages at +/// every other view of them are opened too: the write that faulted (or is +/// ours, `crate::host::copy_mapped`) goes through one view, and every +/// guard over the pages must copy them again. +fn open(g: &mut Guards, start: usize, end: usize) -> bool { + let any = open_here(g, start, end); + if start >= end || g.aliased.is_empty() { + return any; + } + let aliased: Vec = g.aliased.range(start / BLOCK..end.div_ceil(BLOCK)).copied().collect(); + for block in aliased { + g.aliased.remove(&block); + for alias in crate::inplace::pages_of(block * BLOCK) { + if alias / BLOCK != block && open_here(g, alias, alias.saturating_add(BLOCK)) { + #[cfg(feature = "diagnostics")] + ALIASES[1].fetch_add(1, std::sync::atomic::Ordering::Relaxed); + } + g.aliased.remove(&(alias / BLOCK)); + } + } + any +} + +/// [`open`] for one range, without the other views of its pages. +fn open_here(g: &mut Guards, start: usize, end: usize) -> bool { + use windows_sys::Win32::System::Memory::{PAGE_READWRITE, VirtualProtect}; + let blocks: Vec = g + .protected + .range(start / BLOCK..end.div_ceil(BLOCK)) + .copied() + .collect(); + for &block in &blocks { + g.protected.remove(&block); + g.clean.remove(&block); + let mut old = 0; + // SAFETY: a block we made read-only. + unsafe { VirtualProtect((block * BLOCK) as *const _, BLOCK, PAGE_READWRITE, &mut old) }; + } + !blocks.is_empty() +} + +/// Before our own write into title memory `[at, at + len)` through the +/// kernel (which does not fault into our handler): opens its guarded blocks. +/// The runtime calls it (as `kernel_will_write`) before the title's kernel +/// reads into its own memory. +pub fn writing(at: usize, len: usize) { + // The length is the title's (`fread`'s size times count, saturated). + open(&mut guards(), at, at.saturating_add(len)); + // A placed texture there changes with no descriptor written. + crate::descriptor::host::remapped(at, len); +} + +/// What `LEONIDA_PAGE_WRITES` asks to be done with a write the guards do +/// not see once its bytes are there ([`title_memory_written`]), as bits: +/// 1, the guarded blocks under it are opened and count as written (host +/// copies of buffers and textures read through tables take them again); +/// 2, the placed textures picked by index that lie under it are due again; +/// 4, both also for reads to plain addresses when they have finished. +/// Unset or `guards`: bit 1 alone. `0`: nothing, counted only (the default +/// until run 199). `1`: bits 1 and 2. `slots`: bit 2 alone. `all`: +/// everything. +/// (Bit 1 by default: in every run 10,000 to 50,000 guarded blocks of host +/// copies lay under such writes and kept the bytes from before; runs 197 +/// and 198 opened them, 9,766 and 10,796 blocks, with nothing worse for +/// it. Bit 2 makes texture slots due and is the one that flooded the +/// queue in an earlier form: still asked for by name.) +pub(crate) fn page_writes() -> u8 { + static MODE: std::sync::OnceLock = std::sync::OnceLock::new(); + *MODE.get_or_init(|| match std::env::var("LEONIDA_PAGE_WRITES").as_deref().map(str::trim) { + Ok("0") => 0, + Ok("1") => 3, + Ok("slots") => 2, + Ok("all") => 7, + _ => 1, + }) +} + +/// Since the start: writes into physical pages through the runtime's own +/// views that landed at addresses the title has mapped (one for each run +/// of addresses); their bytes; guarded blocks that lay under them (host +/// copies that would otherwise keep the bytes from before); reads to +/// plain addresses that finished. +pub(crate) static WRITTEN: [std::sync::atomic::AtomicU64; 4] = [const { std::sync::atomic::AtomicU64::new(0) }; 4]; + +/// The bytes of a write the guards do not see are there: title memory +/// `[at, at + len)`. `pages`: DirectStorage wrote them into physical pages +/// through a view of the runtime's own, and this is an address where the +/// title has those pages mapped (no title address faulted, nothing was +/// mapped or unmapped; the shortcut this file's header names). Otherwise a +/// read to a plain address has finished, of which [`writing`] was told +/// before it began. +/// +/// Upstream's c75fdba does the same for its trackers (its `Writing` marks +/// the pages once more when dropped; page destinations are reported at +/// each address showing them). Here it is counted always and acted on as +/// [`page_writes`] says. Called without the runtime's page-table lock; +/// takes the guards' lock, then, alone, the lock of the ranges kept for +/// the texture pass. +pub fn title_memory_written(at: usize, len: usize, pages: bool) { + use std::sync::atomic::Ordering::Relaxed; + if len == 0 { + return; + } + let mode = page_writes(); + let end = at.saturating_add(len); + if pages { + WRITTEN[0].fetch_add(1, Relaxed); + WRITTEN[1].fetch_add(len as u64, Relaxed); + } else { + WRITTEN[3].fetch_add(1, Relaxed); + if mode & 4 == 0 { + return; + } + } + { + let mut g = guards(); + let guarded = g.protected.range(at / BLOCK..end.div_ceil(BLOCK)).count() as u64; + if pages { + WRITTEN[2].fetch_add(guarded, Relaxed); + } + if mode & 1 != 0 && guarded != 0 { + open(&mut g, at, end); + } + } + // A placed texture there changed with no descriptor written. + crate::descriptor::host::page_written(at, len); +} + +/// The runtime mapped a view of the physical bytes `[offset, offset + len)` +/// of `section` (`crate::inplace::title_memory_view`): the view is +/// writable, so the same bytes guarded at another view must be checked +/// again — and are, the pages noted written, which also has the next check +/// guard the new view (`protect`). +pub(crate) fn views_mapped(section: usize, offset: u64, len: usize) { + if !view_guard() { + return; + } + let ranges = crate::inplace::views_of_section(section, offset, len); + if ranges.is_empty() { + return; + } + let mut g = guards(); + for &(at, n) in &ranges { + if open_here(&mut g, at, at.saturating_add(n)) { + #[cfg(feature = "diagnostics")] + ALIASES[2].fetch_add(1, std::sync::atomic::Ordering::Relaxed); + } + } +} + +/// Held shared by a read of title memory in place, and alone by the runtime +/// while it changes what title memory shows. +/// +/// The runtime does not change a mapping in one step. To unmap one page of +/// a view it unmaps the whole view and maps what stays again +/// (`xmem.rs` `unmap`), and a view it maps is a reservation until the next +/// call commits it (`map`, then `commit`). For that moment pages the title +/// never gave up are "reserved, never committed", and a thread reading +/// them in place takes an access violation: run 71 in `Layout::detile`, +/// run 74 in the hash before it, both under `Staging::refresh_now`, which +/// had asked whether the texture was all mapped and been told yes. Asking +/// cannot help; not changing the mapping while such a read is under way +/// does. +static MAPPING: std::sync::RwLock<()> = std::sync::RwLock::new(()); + +/// What the runtime holds while it changes what title memory shows +/// ([`title_memory_remapping`]). +pub struct Remapping(#[allow(dead_code)] std::sync::RwLockWriteGuard<'static, ()>, std::time::Instant); + +impl Drop for Remapping { + fn drop(&mut self) { + // From asking for the lock until it is let go (the frame log). + crate::framelog::add(crate::framelog::T::RemapUs, self.1.elapsed().as_micros() as u64); + } +} + +/// The runtime is about to map, unmap or move physical pages of title +/// memory: until what it returns is dropped, no read of title memory in +/// place is under way and none begins ([`title_memory_reading`]). Taken +/// around the whole change, the unmapping and the mapping again. +pub fn title_memory_remapping() -> Remapping { + let asked = std::time::Instant::now(); + let held = MAPPING.write().unwrap_or_else(|e| e.into_inner()); + crate::framelog::add(crate::framelog::T::Remaps, 1); + crate::framelog::add(crate::framelog::T::RemapWaitUs, asked.elapsed().as_micros() as u64); + Remapping(held, asked) +} + +/// What a read of title memory in place holds ([`title_memory_reading`]). +pub struct Reading(#[allow(dead_code)] std::sync::RwLockReadGuard<'static, ()>); + +/// For reading title memory in place: until what it returns is dropped, +/// the runtime changes no mapping, so memory found mapped stays mapped. +/// Not to be taken twice by one thread, nor held across anything that +/// maps title memory. +pub fn title_memory_reading() -> Reading { + Reading(MAPPING.read().unwrap_or_else(|e| e.into_inner())) +} + +/// [`title_memory_reading`] if it can be had at once: `None` while the +/// runtime changes a mapping (or waits to), for a caller that has another +/// way to read and would rather not wait. +pub fn title_memory_reading_now() -> Option { + match MAPPING.try_read() { + Ok(guard) => Some(Reading(guard)), + Err(std::sync::TryLockError::Poisoned(e)) => Some(Reading(e.into_inner())), + Err(std::sync::TryLockError::WouldBlock) => None, + } +} + +/// The runtime mapped or unmapped title memory `[at, at + len)`: what it +/// shows is new and read-write, so it is no longer guarded (nor known +/// unmapped). +pub fn title_memory_remapped(at: usize, len: usize) { + // A placed texture there arrives, goes or changes with no descriptor + // written. + crate::descriptor::host::remapped(at, len); + // The views the runtime told us of there are no longer what it shows. + crate::inplace::views_gone(at, len); + // And nothing stays in place over it. + crate::inplace::title_memory_freeing(at, len); + let mut g = guards(); + let range = at / BLOCK..at.saturating_add(len).div_ceil(BLOCK); + let absent: Vec = g.absent.range(range.clone()).copied().collect(); + for block in absent { + g.absent.remove(&block); + } + let blocks: Vec = g.protected.range(range).copied().collect(); + for block in blocks { + g.protected.remove(&block); + g.clean.remove(&block); + } + let aliased: Vec = g.aliased.range(at / BLOCK..at.saturating_add(len).div_ceil(BLOCK)).copied().collect(); + for block in aliased { + g.aliased.remove(&block); + } + if view_known() { + // The runtime calls this for two things only (`xmem`: `map` and + // `unmap`): a range it has just mapped a section's pages into, + // and a view it is about to make a placeholder again. Either way + // what stands there is view memory or a hole in it, which is what + // `is_view` would answer for a range that begins there; and the + // write watch's asking can only fail there. The title remaps some + // 83 times a frame, and each time the blocks were forgotten, so + // that the next asking about each range went to the kernel twice + // (run 235: 266 to 565 failed askings a frame with the blocks + // remembered from their guards alone, no fewer than without). + g.viewed.extend(at / BLOCK..at.saturating_add(len).div_ceil(BLOCK)); + return; + } + // What the range shows is new: no longer known to be a view. + let viewed: Vec = g.viewed.range(at / BLOCK..at.saturating_add(len).div_ceil(BLOCK)).copied().collect(); + for block in viewed { + g.viewed.remove(&block); + } +} + +/// Registers the handler that takes writes to guarded blocks, once, ahead +/// of the crash reporter's. +fn install() { + use windows_sys::Win32::Foundation::{EXCEPTION_ACCESS_VIOLATION, NTSTATUS}; + use windows_sys::Win32::System::Diagnostics::Debug::{ + AddVectoredExceptionHandler, EXCEPTION_CONTINUE_EXECUTION, EXCEPTION_CONTINUE_SEARCH, + EXCEPTION_POINTERS, + }; + unsafe extern "system" fn on_write(info: *mut EXCEPTION_POINTERS) -> i32 { + // SAFETY: the system passes the exception being dispatched. + let r = unsafe { &*(*info).ExceptionRecord }; + const WRITE: usize = 1; + if r.ExceptionCode != EXCEPTION_ACCESS_VIOLATION as NTSTATUS + || r.NumberParameters < 2 + || r.ExceptionInformation[0] != WRITE + { + return EXCEPTION_CONTINUE_SEARCH; + } + let at = r.ExceptionInformation[1]; + // Held across both checks: another thread may have opened the block + // since this one faulted, and a copy may have guarded it again since + // (then it is ours again, not read-only for some other reason). + let mut g = guards(); + if open(&mut g, at, at + 1) { + #[cfg(feature = "diagnostics")] + crate::copystat::add(crate::copystat::C::GuardFaults, 1); + crate::framelog::add(crate::framelog::T::GuardFaults, 1); + return EXCEPTION_CONTINUE_EXECUTION; + } + if writable(at) { + EXCEPTION_CONTINUE_EXECUTION + } else { + EXCEPTION_CONTINUE_SEARCH + } + } + static ONCE: std::sync::Once = std::sync::Once::new(); + // SAFETY: the handler only touches our guard state and protections. + ONCE.call_once(|| unsafe { + AddVectoredExceptionHandler(1, Some(on_write)); + }); +} + +/// Whether `at` is committed read-write memory now. +fn writable(at: usize) -> bool { + use windows_sys::Win32::System::Memory::{ + MEM_COMMIT, MEMORY_BASIC_INFORMATION, PAGE_READWRITE, VirtualQuery, + }; + // SAFETY: plain data filled in by the query. + let mut info: MEMORY_BASIC_INFORMATION = unsafe { std::mem::zeroed() }; + // SAFETY: a valid out pointer of the right size. + let n = unsafe { VirtualQuery(at as *const _, &mut info, size_of_val(&info)) }; + n != 0 && info.State == MEM_COMMIT && info.Protect == PAGE_READWRITE +} + +#[cfg(test)] +mod tests { + use super::*; + use windows_sys::Win32::System::Memory::{ + MEM_COMMIT, MEM_RELEASE, MEM_RESERVE, PAGE_READWRITE, VirtualAlloc, VirtualFree, + }; + const MEM_WRITE_WATCH: u32 = 0x20_0000; + + #[test] + fn written_pages_are_reported_to_every_asker() { + // SAFETY: a fresh write-watched allocation, freed at the end. + let p = unsafe { + VirtualAlloc( + std::ptr::null(), + 4 * PAGE, + MEM_RESERVE | MEM_COMMIT | MEM_WRITE_WATCH, + PAGE_READWRITE, + ) + } as usize; + assert_ne!(p, 0); + let (start, end) = (p, p + 4 * PAGE); + let (_, before) = writes(start, end, false).expect("watched"); + assert!(before.is_empty()); + // SAFETY: committed pages of ours. + unsafe { ((p + PAGE + 8) as *mut u8).write(1) }; + let (now, after) = writes(start, end, false).expect("watched"); + assert_eq!(after, [(p / PAGE + 1, now)]); + // Another asker after the kernel's bit was cleared still sees it. + let (later, again) = writes(p + PAGE, p + 2 * PAGE, false).expect("watched"); + assert!(later > now); + assert_eq!(again, [(p / PAGE + 1, now)]); + let mut plain = vec![0u8; PAGE]; + assert!( + writes( + plain.as_mut_ptr() as usize, + plain.as_ptr() as usize + PAGE, + true + ) + .is_none() + ); + // SAFETY: our allocation. + unsafe { VirtualFree(p as *mut _, 0, MEM_RELEASE) }; + } + + /// A kernel read into a guarded view block fails; opened first, it + /// lands and the block counts as written. + #[test] + fn kernel_reads_into_guarded_blocks_after_opening() { + use std::io::{Read, Seek, Write}; + use windows_sys::Win32::System::Memory::{ + CreateFileMappingW, FILE_MAP_WRITE, MapViewOfFile, UnmapViewOfFile, + }; + // SAFETY: a pagefile section of two blocks, mapped read-write. + let view = unsafe { + let section = CreateFileMappingW( + -1isize as _, + std::ptr::null(), + PAGE_READWRITE, + 0, + (2 * BLOCK) as u32, + std::ptr::null(), + ); + assert!(!section.is_null()); + MapViewOfFile(section, FILE_MAP_WRITE, 0, 0, 2 * BLOCK).Value as usize + }; + assert_ne!(view, 0); + assert!(guard(view, view + 2 * BLOCK).is_some()); // now read-only + let mut file = tempfile::tempfile().unwrap(); + file.write_all(b"from the disk").unwrap(); + // `ReadFile` inside: the kernel writes the view. + let read = |file: &mut std::fs::File| { + file.rewind().unwrap(); + // SAFETY: 13 bytes of our view, nothing else refers to them. + let into = unsafe { std::slice::from_raw_parts_mut((view + 100) as *mut u8, 13) }; + file.read(into).is_ok_and(|n| n == 13) + }; + assert!( + !read(&mut file), + "the kernel does not fault into our handler" + ); + writing(view + 100, 13); + assert!(read(&mut file)); + // SAFETY: the bytes just read. + let landed = unsafe { std::slice::from_raw_parts((view + 100) as *const u8, 13) }; + assert_eq!(landed, b"from the disk"); + assert_eq!( + guard(view, view + 2 * BLOCK), + Some((view / PAGE..view / PAGE + 1).collect()) + ); + // SAFETY: our view. + unsafe { + UnmapViewOfFile( + windows_sys::Win32::System::Memory::MEMORY_MAPPED_VIEW_ADDRESS { + Value: view as *mut _, + }, + ) + }; + title_memory_remapped(view, 2 * BLOCK); + } + + #[test] + fn writes_in_partly_committed_view_blocks_are_reported() { + use windows_sys::Win32::Foundation::{CloseHandle, INVALID_HANDLE_VALUE}; + use windows_sys::Win32::System::Memory::{ + CreateFileMappingW, FILE_MAP_WRITE, MEMORY_MAPPED_VIEW_ADDRESS, MapViewOfFile, + SEC_RESERVE, UnmapViewOfFile, + }; + + const SIZE: usize = 3 * BLOCK; + struct View(MEMORY_MAPPED_VIEW_ADDRESS); + impl Drop for View { + fn drop(&mut self) { + title_memory_remapped(self.0.Value as usize, SIZE); + // SAFETY: our view is still mapped. + unsafe { UnmapViewOfFile(self.0) }; + } + } + // SAFETY: a new reserved pagefile section. The view holds its own + // reference after we close the handle, including on assertion failure. + let view = unsafe { + let section = CreateFileMappingW( + INVALID_HANDLE_VALUE, + std::ptr::null(), + PAGE_READWRITE | SEC_RESERVE, + 0, + SIZE as u32, + std::ptr::null(), + ); + assert!(!section.is_null()); + let view = MapViewOfFile(section, FILE_MAP_WRITE, 0, 0, SIZE); + CloseHandle(section); + assert!(!view.Value.is_null()); + View(view) + }; + let start = view.0.Value as usize; + let commit = |at: usize, len| { + // SAFETY: these pages belong to our reserved view. + let committed = unsafe { VirtualAlloc(at as _, len, MEM_COMMIT, PAGE_READWRITE) }; + assert_eq!(committed as usize, at); + }; + let early = start + BLOCK + 3 * KERNEL_PAGE; + let late = start + 2 * BLOCK + 3 * KERNEL_PAGE; + commit(start, BLOCK); + commit(early, KERNEL_PAGE); + let refresh = || guard(start, start + SIZE).unwrap(); + assert_eq!(refresh(), [start / PAGE, early / PAGE, late / PAGE]); + // The last block is still entirely reserved. + assert!(!refresh().contains(&(late / PAGE))); + + commit(late, KERNEL_PAGE); // Ordinary commit, without a runtime mapping notification. + for at in [early, late] { + assert!(writable(at)); + // SAFETY: each address is inside its committed read-write page. + unsafe { (at as *mut u8).write_volatile(1) }; + } + assert_eq!(refresh(), [early / PAGE, late / PAGE]); + } + + /// A range of view memory whose first block is not mapped is a view + /// all the same: its blocks are reported once, then the ones written + /// or mapped since. + #[test] + fn a_range_that_begins_in_an_unmapped_block_is_guarded() { + use windows_sys::Win32::System::Memory::{ + CreateFileMappingW, MEM_PRESERVE_PLACEHOLDER, MEM_REPLACE_PLACEHOLDER, + MEM_RESERVE_PLACEHOLDER, MapViewOfFile3, PAGE_NOACCESS, UnmapViewOfFile2, + VirtualAlloc2, + }; + use windows_sys::Win32::System::Threading::GetCurrentProcess; + // SAFETY: a fresh placeholder of three blocks and a pagefile + // section of three; the middle block is mapped first. + let (p, section) = unsafe { + let p = VirtualAlloc2( + GetCurrentProcess(), + std::ptr::null(), + 3 * BLOCK, + MEM_RESERVE | MEM_RESERVE_PLACEHOLDER, + PAGE_NOACCESS, + std::ptr::null_mut(), + 0, + ) as usize; + assert_ne!(p, 0); + let section = CreateFileMappingW( + -1isize as _, + std::ptr::null(), + PAGE_READWRITE, + 0, + (3 * BLOCK) as u32, + std::ptr::null(), + ); + assert!(!section.is_null()); + (p, section) + }; + let map = |block: usize| { + // SAFETY: splits the placeholder at the block and maps the + // section's block there. + let view = unsafe { + VirtualFree( + (p + block * BLOCK) as *mut _, + BLOCK, + MEM_RELEASE | MEM_PRESERVE_PLACEHOLDER, + ); + MapViewOfFile3( + section, + GetCurrentProcess(), + (p + block * BLOCK) as *const _, + (block * BLOCK) as u64, + BLOCK, + MEM_REPLACE_PLACEHOLDER, + PAGE_READWRITE, + std::ptr::null_mut(), + 0, + ) + }; + assert_eq!(view.Value as usize, p + block * BLOCK); + view + }; + let pages = |block: usize| (p + block * BLOCK) / PAGE..(p + (block + 1) * BLOCK) / PAGE; + let all: Vec = (0..3).flat_map(pages).collect(); + // Nothing mapped at all: a view with every block absent. + assert!(is_view(p, p + 3 * BLOCK)); + let middle = map(1); + title_memory_remapped(p + BLOCK, BLOCK); + // The range begins in the placeholder, its middle block is a view. + assert!(is_view(p, p + 3 * BLOCK)); + assert_eq!(guard(p, p + 3 * BLOCK), Some(all)); + assert_eq!(guard(p, p + 3 * BLOCK), Some(Vec::new()), "nothing written since"); + // SAFETY: inside the mapped middle block. + unsafe { ((p + BLOCK + 8) as *mut u8).write_volatile(1) }; + assert_eq!(guard(p, p + 3 * BLOCK), Some(pages(1).collect())); + let first = map(0); + title_memory_remapped(p, BLOCK); + assert_eq!(guard(p, p + 3 * BLOCK), Some(pages(0).collect())); + assert_eq!(guard(p, p + 3 * BLOCK), Some(Vec::new())); + // Memory of ours that is no view stays none. + let mut local = [0u8; 16]; + let at = local.as_mut_ptr() as usize; + assert!(!is_view(at, at + local.len())); + // SAFETY: our views and placeholder. + unsafe { + UnmapViewOfFile2(GetCurrentProcess(), first, MEM_PRESERVE_PLACEHOLDER); + UnmapViewOfFile2(GetCurrentProcess(), middle, MEM_PRESERVE_PLACEHOLDER); + for block in 0..3 { + VirtualFree((p + block * BLOCK) as *mut _, 0, MEM_RELEASE); + } + windows_sys::Win32::Foundation::CloseHandle(section); + } + title_memory_remapped(p, 3 * BLOCK); + } + + /// Blocks of a placeholder between views are reported once, then not + /// again (they cannot be guarded) until the runtime maps them. + #[test] + fn unmapped_blocks_are_reported_once_until_mapped() { + use windows_sys::Win32::System::Memory::{ + CreateFileMappingW, MEM_PRESERVE_PLACEHOLDER, MEM_REPLACE_PLACEHOLDER, + MEM_RESERVE_PLACEHOLDER, MapViewOfFile3, PAGE_NOACCESS, UnmapViewOfFile2, + VirtualAlloc2, + }; + use windows_sys::Win32::System::Threading::GetCurrentProcess; + // SAFETY: a fresh placeholder of three blocks and a pagefile + // section of two; block 0 shows the section's first block, as the + // runtime maps physical pages. + let (p, section) = unsafe { + let p = VirtualAlloc2( + GetCurrentProcess(), + std::ptr::null(), + 3 * BLOCK, + MEM_RESERVE | MEM_RESERVE_PLACEHOLDER, + PAGE_NOACCESS, + std::ptr::null_mut(), + 0, + ) as usize; + assert_ne!(p, 0); + let section = CreateFileMappingW( + -1isize as _, + std::ptr::null(), + PAGE_READWRITE, + 0, + (2 * BLOCK) as u32, + std::ptr::null(), + ); + assert!(!section.is_null()); + (p, section) + }; + let map = |block: usize| { + // SAFETY: splits the placeholder at the block and maps the + // section's block there. + let view = unsafe { + VirtualFree( + (p + block * BLOCK) as *mut _, + BLOCK, + MEM_RELEASE | MEM_PRESERVE_PLACEHOLDER, + ); + MapViewOfFile3( + section, + GetCurrentProcess(), + (p + block * BLOCK) as *const _, + (block * BLOCK) as u64, + BLOCK, + MEM_REPLACE_PLACEHOLDER, + PAGE_READWRITE, + std::ptr::null_mut(), + 0, + ) + }; + assert_eq!(view.Value as usize, p + block * BLOCK); + view + }; + let first = map(0); + let pages = |block: usize| (p + block * BLOCK) / PAGE..(p + (block + 1) * BLOCK) / PAGE; + let all: Vec = (0..3).flat_map(pages).collect(); + assert_eq!(guard(p, p + 3 * BLOCK), Some(all)); + assert_eq!( + guard(p, p + 3 * BLOCK), + Some(Vec::new()), + "nothing written since" + ); + let second = map(1); + title_memory_remapped(p + BLOCK, BLOCK); + assert_eq!(guard(p, p + 3 * BLOCK), Some(pages(1).collect())); + assert_eq!(guard(p, p + 3 * BLOCK), Some(Vec::new())); + // SAFETY: our views and placeholder. + unsafe { + UnmapViewOfFile2(GetCurrentProcess(), first, MEM_PRESERVE_PLACEHOLDER); + UnmapViewOfFile2(GetCurrentProcess(), second, MEM_PRESERVE_PLACEHOLDER); + for block in 0..3 { + VirtualFree((p + block * BLOCK) as *mut _, 0, MEM_RELEASE); + } + windows_sys::Win32::Foundation::CloseHandle(section); + } + title_memory_remapped(p, 3 * BLOCK); + } + + /// A pagefile section mapped twice: two views of the same physical + /// pages, the second left for the test; the section handle, the two + /// addresses. + fn two_views(bytes: usize) -> (usize, usize, usize) { + use windows_sys::Win32::Foundation::INVALID_HANDLE_VALUE; + use windows_sys::Win32::System::Memory::{ + CreateFileMappingW, FILE_MAP_WRITE, MapViewOfFile, + }; + // SAFETY: a fresh pagefile section, mapped twice; the views keep + // the section alive and the handle is closed by the caller. + unsafe { + let section = CreateFileMappingW( + INVALID_HANDLE_VALUE, + std::ptr::null(), + PAGE_READWRITE, + 0, + bytes as u32, + std::ptr::null(), + ); + assert!(!section.is_null()); + let one = MapViewOfFile(section, FILE_MAP_WRITE, 0, 0, bytes).Value as usize; + let two = MapViewOfFile(section, FILE_MAP_WRITE, 0, 0, bytes).Value as usize; + assert_ne!(one, 0); + assert_ne!(two, 0); + crate::inplace::title_memory_view(one, bytes, section as usize, 0); + crate::inplace::title_memory_view(two, bytes, section as usize, 0); + (section as usize, one, two) + } + } + + /// The section of [`two_views`] is closed and its views unmapped; the + /// guard is told they are gone first. + fn drop_views(section: usize, views: &[usize], bytes: usize) { + use windows_sys::Win32::Foundation::CloseHandle; + use windows_sys::Win32::System::Memory::{MEMORY_MAPPED_VIEW_ADDRESS, UnmapViewOfFile}; + for &view in views { + title_memory_remapped(view, bytes); + // SAFETY: a view of the section mapped by `two_views`. + unsafe { + UnmapViewOfFile(MEMORY_MAPPED_VIEW_ADDRESS { + Value: view as *mut _, + }) + }; + } + // SAFETY: the section's last reference. + unsafe { CloseHandle(section as *mut std::ffi::c_void) }; + } + + /// The title wrote the pages of a guarded texture through another view + /// of them: the fault at that view is the guard's to see, and the + /// guarded view's next check reports the pages written. + #[test] + fn a_write_through_another_view_is_reported_at_the_guarded_one() { + const SIZE: usize = 2 * BLOCK; + let (section, guarded, other) = two_views(SIZE); + let pages = |block: usize| (guarded + block * BLOCK) / PAGE; + // The first check takes it in (and every view of its pages). + assert_eq!(guard(guarded, guarded + SIZE), Some(vec![pages(0), pages(1)])); + assert_eq!(guard(guarded, guarded + SIZE), Some(Vec::new()), "nothing written yet"); + // Writing through the other view faults into the handler, which + // opens that view and the guarded one: the next check sees it. + // SAFETY: the second view, read-write once the handler has opened it. + unsafe { ((other + BLOCK + 8) as *mut u8).write(1) }; + assert_eq!(guard(guarded, guarded + SIZE), Some(vec![pages(1)])); + assert_eq!(guard(guarded, guarded + SIZE), Some(Vec::new())); + drop_views(section, &[guarded, other], SIZE); + } + + /// A view of guarded pages is mapped anew: it is writable, so the + /// guarded view checks its pages again (and guards the new view). + #[test] + fn a_view_mapped_beside_a_guarded_one_makes_it_check_again() { + const SIZE: usize = 2 * BLOCK; + let (section, guarded, other) = two_views(SIZE); + let pages = |block: usize| (guarded + block * BLOCK) / PAGE; + assert_eq!(guard(guarded, guarded + SIZE), Some(vec![pages(0), pages(1)])); + assert_eq!(guard(guarded, guarded + SIZE), Some(Vec::new()), "nothing written yet"); + title_memory_remapped(other, SIZE); + crate::inplace::title_memory_view(other, SIZE, section, 0); + assert_eq!(guard(guarded, guarded + SIZE), Some(vec![pages(0), pages(1)])); + assert_eq!(guard(guarded, guarded + SIZE), Some(Vec::new())); + drop_views(section, &[guarded, other], SIZE); + } + + /// A write of the runtime's own, told at one view of the pages + /// (`writing`): the other views' next checks report the pages written. + #[test] + fn a_write_told_at_one_view_is_reported_at_the_others() { + const SIZE: usize = 2 * BLOCK; + let (section, guarded, other) = two_views(SIZE); + let pages = |block: usize| (guarded + block * BLOCK) / PAGE; + assert_eq!(guard(guarded, guarded + SIZE), Some(vec![pages(0), pages(1)])); + assert_eq!(guard(guarded, guarded + SIZE), Some(Vec::new()), "nothing written yet"); + writing(other + BLOCK, BLOCK); + assert_eq!(guard(guarded, guarded + SIZE), Some(vec![pages(1)])); + assert_eq!(guard(guarded, guarded + SIZE), Some(Vec::new())); + // Half a page and the next: both blocks, not just the first's. + writing(other + BLOCK / 2, BLOCK); + assert_eq!(guard(guarded, guarded + SIZE), Some(vec![pages(0), pages(1)])); + drop_views(section, &[guarded, other], SIZE); + } + + /// Both views of the pages are checked, each for a copy of its own + /// (the title shows one physical page at several addresses, and each + /// address has its host copy): a write through either is reported at + /// both, whichever is checked first. Guarding the pages for the first + /// view's check must not note the second view clean, or its copy would + /// keep the bytes from before the write. + #[test] + fn a_write_is_reported_at_every_checked_view() { + const SIZE: usize = 2 * BLOCK; + let (section, one, two) = two_views(SIZE); + let pages = |view: usize, block: usize| (view + block * BLOCK) / PAGE; + assert_eq!(guard(one, one + SIZE), Some(vec![pages(one, 0), pages(one, 1)])); + assert_eq!(guard(two, two + SIZE), Some(vec![pages(two, 0), pages(two, 1)]), "the second view's first check"); + assert_eq!(guard(one, one + SIZE), Some(Vec::new()), "nothing written yet"); + assert_eq!(guard(two, two + SIZE), Some(Vec::new()), "nothing written yet"); + // SAFETY: the second view, read-write once the handler has opened it. + unsafe { ((two + BLOCK + 8) as *mut u8).write(1) }; + assert_eq!(guard(one, one + SIZE), Some(vec![pages(one, 1)])); + assert_eq!(guard(two, two + SIZE), Some(vec![pages(two, 1)]), "written through this view, checked second"); + // SAFETY: the first view, as above. + unsafe { ((one + 8) as *mut u8).write(1) }; + assert_eq!(guard(two, two + SIZE), Some(vec![pages(two, 0)])); + assert_eq!(guard(one, one + SIZE), Some(vec![pages(one, 0)]), "written through this view, checked second"); + assert_eq!(guard(one, one + SIZE), Some(Vec::new())); + assert_eq!(guard(two, two + SIZE), Some(Vec::new())); + drop_views(section, &[one, two], SIZE); + } + + /// A page shown in more than `MANY_VIEWS` views is guarded at each by + /// itself: the others stay writable, and nothing looks through them all. + #[test] + fn a_page_of_many_views_is_guarded_one_view_at_a_time() { + let (section, one, two) = two_views(BLOCK); + let filler = one + (1 << 45); + for n in 0..MANY_VIEWS { + crate::inplace::title_memory_view(filler + n * BLOCK, BLOCK, section, 0); + } + assert_eq!(guard(one, one + BLOCK), Some(vec![one / PAGE])); + assert!(writable(two), "another view of it is left alone"); + // SAFETY: the guarded view, opened by the handler. + unsafe { ((one + 8) as *mut u8).write(1) }; + assert_eq!(guard(one, one + BLOCK), Some(vec![one / PAGE])); + title_memory_remapped(filler, MANY_VIEWS * BLOCK); + drop_views(section, &[one, two], BLOCK); + } + + /// A write or mapping that runs past the end of the address space (a + /// title's `fread` with a huge count) covers up to the end; the sum used + /// to overflow. Up there no test has guarded blocks. + #[test] + fn ranges_past_the_address_space_end_do_not_overflow() { + let top = usize::MAX - 16; + writing(top, PAGE); + title_memory_remapped(top, usize::MAX); + } +} + +#[cfg(test)] +mod mapping_tests { + use super::{title_memory_reading, title_memory_remapping}; + use std::sync::atomic::{AtomicBool, Ordering}; + use std::sync::{Arc, mpsc}; + use std::time::Duration; + + /// A change of mapping waits for a read in place that is under way, and + /// a read in place waits for a change of mapping. + #[test] + fn reads_in_place_and_remappings_wait_for_each_other() { + // A reader holds; the change does not begin until it lets go. + let changed = Arc::new(AtomicBool::new(false)); + let reading = title_memory_reading(); + let (began, wait) = mpsc::channel(); + let change = { + let changed = changed.clone(); + std::thread::spawn(move || { + began.send(()).unwrap(); + let _changing = title_memory_remapping(); + changed.store(true, Ordering::SeqCst); + }) + }; + wait.recv().unwrap(); + std::thread::sleep(Duration::from_millis(100)); + assert!(!changed.load(Ordering::SeqCst), "the mapping changed under a read in place"); + drop(reading); + change.join().unwrap(); + assert!(changed.load(Ordering::SeqCst)); + // A change holds; the read does not begin until it is done. + let read = Arc::new(AtomicBool::new(false)); + let changing = title_memory_remapping(); + let (began, wait) = mpsc::channel(); + let reader = { + let read = read.clone(); + std::thread::spawn(move || { + began.send(()).unwrap(); + let _reading = title_memory_reading(); + read.store(true, Ordering::SeqCst); + }) + }; + wait.recv().unwrap(); + std::thread::sleep(Duration::from_millis(100)); + assert!(!read.load(Ordering::SeqCst), "a read in place began during a change of mapping"); + drop(changing); + reader.join().unwrap(); + assert!(read.load(Ordering::SeqCst)); + } +} diff --git a/crates/leonida-hle/Cargo.toml b/crates/leonida-hle/Cargo.toml new file mode 100644 index 000000000..2fe729ca2 --- /dev/null +++ b/crates/leonida-hle/Cargo.toml @@ -0,0 +1,55 @@ +[package] +name = "leonida-hle" +description = "Our implementation of the Xbox system API surface the title imports." +version.workspace = true +edition.workspace = true +rust-version.workspace = true +license.workspace = true +publish.workspace = true + +[dependencies] +leonida-gpu.workspace = true +leonida-loader.workspace = true +leonida-pe.workspace = true +leonida-formats.workspace = true +opus-pure.workspace = true +zlib-rs.workspace = true +tracing.workspace = true + +[target.'cfg(windows)'.dependencies] +windows-sys = { workspace = true, features = [ + "Win32_Foundation", + "Win32_Globalization", + "Win32_Media", + "Win32_Security", + "Win32_Storage_FileSystem", + "Win32_System_Diagnostics_Debug", + "Win32_System_LibraryLoader", + "Win32_System_Memory", + "Win32_System_Power", + "Win32_System_ProcessStatus", + "Win32_System_Threading", + "Win32_UI_Input_KeyboardAndMouse", + "Win32_UI_Input_XboxController", + "Win32_UI_WindowsAndMessaging", +] } +# Diagnostics only: recording our own audio (`modules::audio::capture`). +windows = { workspace = true, optional = true, features = [ + "Win32_Media_Audio", + "Win32_System_Com", + "Win32_System_Com_StructuredStorage", + "Win32_System_Threading", + "Win32_System_Variant", +] } +# `#[implement]` names it. +windows-core = { workspace = true, optional = true } + +[dev-dependencies] +tempfile.workspace = true + +[features] +# Debugging switches (scripted keys and the like). +diagnostics = ["leonida-gpu/diagnostics", "leonida-loader/diagnostics", "dep:windows", "dep:windows-core"] + +[lints] +workspace = true diff --git a/crates/leonida-hle/src/host.rs b/crates/leonida-hle/src/host.rs new file mode 100644 index 000000000..bdf7c9791 --- /dev/null +++ b/crates/leonida-hle/src/host.rs @@ -0,0 +1,148 @@ +//! Pass-through to the host's own implementation of shared APIs. + +use leonida_pe::ImportSymbol; + +/// Which DLLs may be satisfied by the host's own implementation. +/// +/// Console titles link mostly against Windows API sets that behave the same +/// on PC. Passing those through lets bring-up focus on what really differs. +/// Anything whose semantics differ on console (memory, files, threads) is +/// overridden in `modules`, which always wins over the host. +#[derive(Debug, Clone)] +pub struct HostPolicy { + /// Lower-case patterns; a trailing `*` matches a prefix. + pub allow: Vec, +} + +impl Default for HostPolicy { + fn default() -> Self { + let allow = [ + "api-ms-win-core-*", + "api-ms-win-eventing-*", + "api-ms-win-security-*", + "api-ms-win-crt-*", + "kernel32.dll", + "kernelbase.dll", + "ntdll.dll", + "ucrtbase.dll", + "vcruntime140*", + "msvcp140*", + // Off-machine traffic is refused in `modules::net`. + "ws2_32.dll", + "bcrypt.dll", + "crypt32.dll", + "ncrypt.dll", + "winhttp.dll", + "sspicli.dll", + "cabinet.dll", + "avrt.dll", + // Window, message and shell APIs: the host's desktop window + // stands in for the console's single core window. + "ext-ms-win-rtcore-ntuser-*", + "api-ms-win-shcore-*", + "msvcp_win.dll", + "ole32.dll", + "advapi32.dll", + "iphlpapi.dll", + // The title's crash handler writes minidumps with it (loaded by name). + "dbghelp.dll", + // Same APIs as the console's (XAudio2 ordinal 1 is XAudio2Create + // on both); Media Foundation reads local media files. + "xaudio2_9.dll", + "mfplat.dll", + "mfreadwrite.dll", + ]; + HostPolicy { + allow: allow.iter().map(|s| s.to_string()).collect(), + } + } +} + +impl HostPolicy { + /// No pass-through at all: shows the full surface a title needs. + pub fn none() -> Self { + HostPolicy { allow: Vec::new() } + } + + pub fn allows(&self, dll: &str) -> bool { + let dll = dll.to_ascii_lowercase(); + self.allow + .iter() + .any(|pattern| match pattern.strip_suffix('*') { + Some(prefix) => dll.starts_with(prefix), + None => dll == *pattern, + }) + } + + pub(crate) fn resolve(&self, dll: &str, symbol: &ImportSymbol) -> Option { + if !self.allows(dll) { + return None; + } + imp::resolve(dll, symbol) + } +} + +/// The host's own `name` from the System32 DLL `dll`: what a title import +/// of it is bound to when we do not override it. +pub(crate) fn function(dll: &str, name: &str) -> Option { + let name = ImportSymbol::Name { + hint: 0, + name: name.into(), + }; + imp::resolve(dll, &name) +} + +#[cfg(windows)] +mod imp { + use std::collections::HashMap; + use std::ffi::CString; + use std::sync::{LazyLock, Mutex}; + + use leonida_pe::ImportSymbol; + use windows_sys::Win32::System::LibraryLoader::{ + GetProcAddress, LOAD_LIBRARY_SEARCH_SYSTEM32, LoadLibraryExA, + }; + + /// Module handles by lower-case DLL name (stored as usize: Send + Sync). + static MODULES: LazyLock>> = LazyLock::new(Default::default); + + pub(super) fn resolve(dll: &str, symbol: &ImportSymbol) -> Option { + let module = module(dll)?; + let proc = match symbol { + ImportSymbol::Name { name, .. } => { + let name = CString::new(name.as_str()).ok()?; + // SAFETY: valid module handle, NUL-terminated name. + unsafe { GetProcAddress(module as _, name.as_ptr().cast()) } + } + // SAFETY: MAKEINTRESOURCE-style ordinal lookup on a valid module. + ImportSymbol::Ordinal(o) => unsafe { GetProcAddress(module as _, *o as usize as _) }, + }; + proc.map(|f| f as *const () as usize) + } + + fn module(dll: &str) -> Option { + let key = dll.to_ascii_lowercase(); + let mut cache = MODULES.lock().unwrap_or_else(|e| e.into_inner()); + if let Some(&m) = cache.get(&key) { + return Some(m); + } + let name = CString::new(key.as_str()).ok()?; + // System32 only: never pick up a same-named DLL from the current folder or PATH. + // SAFETY: NUL-terminated DLL name; only allow-listed system DLLs get here. + let handle = unsafe { + LoadLibraryExA( + name.as_ptr().cast(), + std::ptr::null_mut(), + LOAD_LIBRARY_SEARCH_SYSTEM32, + ) + } as usize; + (handle != 0).then(|| *cache.entry(key).or_insert(handle)) + } +} + +#[cfg(not(windows))] +mod imp { + pub(super) fn resolve(_dll: &str, _symbol: &leonida_pe::ImportSymbol) -> Option { + None + } +} diff --git a/crates/leonida-hle/src/lib.rs b/crates/leonida-hle/src/lib.rs new file mode 100644 index 000000000..20e07ba96 --- /dev/null +++ b/crates/leonida-hle/src/lib.rs @@ -0,0 +1,123 @@ +//! Our implementation of the Xbox system API surface. +//! +//! A title imports from three kinds of DLLs, and each gets its own policy: +//! +//! | kind | examples | handled by | +//! |------|----------|------------| +//! | Windows API sets the console shares with PC | `api-ms-win-core-synch-*`, `ws2_32.dll` | host pass-through, overridden here where console behaviour differs (paths, memory) | +//! | console-only system APIs | `xgameruntime.dll`, `xmem.dll`, `d3d12_xs.dll` | implemented here, in [`modules`] | +//! | anything else | | an unimplemented-import stub from the loader | +//! +//! Resolution order for every import: an implementation in [`modules`], +//! then the host if [`HostPolicy`] allows that DLL, then `Missing`. + +mod host; +pub mod modules; +mod registry; +pub mod runtime; + +pub use host::HostPolicy; +pub use registry::{HleExport, HleModule, registry}; +pub use leonida_gpu::console; + +use leonida_loader::{ImportResolver, Provenance, Resolution}; +use leonida_pe::ImportSymbol; + +/// Resolves a title's imports against our runtime and the host. +#[derive(Debug, Default)] +pub struct HleResolver { + pub host: HostPolicy, +} + +impl HleResolver { + pub fn new(host: HostPolicy) -> Self { + HleResolver { host } + } + + /// Where an import would come from, without binding anything. + pub fn classify(&self, dll: &str, symbol: &ImportSymbol) -> Option { + match self.resolve(dll, symbol) { + Resolution::Found { provenance, .. } => Some(provenance), + Resolution::Missing => None, + } + } +} + +impl ImportResolver for HleResolver { + fn resolve(&self, dll: &str, symbol: &ImportSymbol) -> Resolution { + // Ordinal imports look up `#n`. + if let Some(address) = registry::lookup(dll, &symbol.to_string()) { + return Resolution::Found { + address, + provenance: Provenance::Hle, + }; + } + match self.host.resolve(dll, symbol) { + Some(address) => Resolution::Found { + address, + provenance: Provenance::Host, + }, + None => Resolution::Missing, + } + } +} + +// The registry is code-only, so the "Missing" outcome can be checked on any +// host; host pass-through itself needs Windows. +#[cfg(test)] +mod tests { + use super::*; + + fn name(n: &str) -> ImportSymbol { + ImportSymbol::Name { + hint: 0, + name: n.into(), + } + } + + #[test] + fn console_api_resolves_to_hle() { + let r = HleResolver::new(HostPolicy::none()); + assert_eq!( + r.classify("XGameRuntime.dll", &name("XGameRuntimeInitialize")), + Some(Provenance::Hle) + ); + } + + #[test] + fn strict_policy_reports_missing() { + let r = HleResolver::new(HostPolicy::none()); + assert_eq!( + r.classify("api-ms-win-core-synch-l1-1-0.dll", &name("Sleep")), + None + ); + } + + #[cfg(windows)] + #[test] + fn shared_api_sets_pass_through_to_host() { + let r = HleResolver::default(); + assert_eq!( + r.classify("api-ms-win-core-synch-l1-2-0.dll", &name("Sleep")), + Some(Provenance::Host) + ); + // Console-only DLLs never pass through. + assert_eq!( + r.classify("xmem.dll", &name("XMemSetAllocationHooks")), + None + ); + } + + #[cfg(windows)] + #[test] + fn overrides_win_over_host() { + let r = HleResolver::default(); + assert_eq!( + r.classify( + "api-ms-win-core-libraryloader-l1-2-0.dll", + &name("GetModuleHandleW") + ), + Some(Provenance::Hle) + ); + } +} diff --git a/crates/leonida-hle/src/modules/apu.rs b/crates/leonida-hle/src/modules/apu.rs new file mode 100644 index 000000000..0668f0dea --- /dev/null +++ b/crates/leonida-hle/src/modules/apu.rs @@ -0,0 +1,524 @@ +//! The console's audio decoder (`xapu.dll`): Opus packets in, float PCM out. +//! +//! A title connects once for one kind of processing, gets a block of memory +//! for its packets and output, and then queues per-stream commands +//! (activate, process, reset, deactivate) and dequeues one result per +//! command. We decode each command when it is queued, so its result is ready +//! at once; the order of results is the order of commands. +#![allow(non_snake_case)] +#![allow(clippy::not_unsafe_ptr_arg_deref)] + +use std::alloc::Layout; +use std::collections::VecDeque; +use std::ffi::c_void; +use std::sync::Mutex; + +use opus_pure::OpusDecoder; +use windows_sys::Win32::Foundation::{CloseHandle, HANDLE}; +use windows_sys::Win32::System::Threading::{CreateEventW, SetEvent}; + +use super::xasync::E_INVALIDARG; +use super::xgameruntime::{HRESULT, S_OK}; +use crate::{HleModule, hle_export}; + +const E_NOTIMPL: HRESULT = 0x8000_4001_u32 as i32; +const E_OUTOFMEMORY: HRESULT = 0x8007_000E_u32 as i32; +const QUEUE_FULL: HRESULT = 0x8AC8_1000_u32 as i32; +/// No result yet, which titles poll for. +pub(crate) const PENDING_RESULTS: HRESULT = 0x8AC8_1001_u32 as i32; +const INVALID_COMMAND: HRESULT = 0x8AC8_1002_u32 as i32; +const INVALID_STREAM: HRESULT = 0x8AC8_1003_u32 as i32; +const ALREADY_ACTIVE: HRESULT = 0x8AC8_1005_u32 as i32; +const BAD_PACKET: HRESULT = 0x8AC8_1008_u32 as i32; + +/// Processing kinds; only plain decoding is implemented. +const DECODE_OPUS: u32 = 1; + +const ACTIVATE: u32 = 1; +const DEACTIVATE: u32 = 2; +const PROCESS: u32 = 3; +const NOTIFY: u32 = 4; +const RESET: u32 = 5; + +/// Command option: signal the connection's event when the result is ready. +const SIGNAL: u32 = 1; +/// Connect options. +const DEINTERLEAVED_OUTPUT: u32 = 4; +const RESULT_EVENT: u32 = 8; + +/// The longest Opus packet duration at 48 kHz (120 ms). +const MAX_FRAMES: usize = 5760; + +#[repr(C)] +pub struct ConnectInput { + process: u32, + streams: u32, + commands_per_stream: u32, + memory: u32, + frames_per_output: u32, + options: u32, +} + +#[repr(C)] +pub struct ConnectOutput { + memory: *mut c_void, + result_event: HANDLE, +} + +/// What every command starts with, and what its result echoes. +#[repr(C, packed)] +#[derive(Clone, Copy)] +pub struct CommandId { + kind: u32, + stream: u32, + sequence: u32, + options: u32, + context: u64, +} + +#[repr(C, packed)] +struct Activate { + id: CommandId, + channels: u32, + init_length: u32, + init: *const c_void, + start_pitch: f32, + processing_length: u32, + processing: *mut c_void, +} + +#[repr(C, packed)] +#[derive(Clone, Copy)] +struct Process { + id: CommandId, + pitch_ramp: f32, + target_pitch: f32, + first_frame: u32, + frame_count: u32, + input_length: u32, + input: *const u8, + output_length: u32, + output: *mut u8, +} + +#[repr(C, packed)] +#[derive(Clone, Copy)] +pub struct ApuResult { + id: CommandId, + state: u32, + state_data: u64, + usec: u64, + error: HRESULT, + frames: u32, + output_length: u32, + output: *mut u8, + pitch: f32, + input_length: u32, + input: *const u8, +} + +// SAFETY: the raw pointers are title addresses carried through, never +// dereferenced after the result is made. +unsafe impl Send for ApuResult {} + +pub struct Connection { + memory: *mut u8, + layout: Layout, + event: HANDLE, + options: u32, + per_stream: u32, + state: Mutex, +} + +struct State { + streams: Vec>, + /// Results not yet dequeued, per stream. + queued: Vec, + results: VecDeque, + commands: u32, + dequeued: u32, +} + +fn lock(c: &Connection) -> std::sync::MutexGuard<'_, State> { + c.state.lock().unwrap_or_else(|e| e.into_inner()) +} + +pub extern "system" fn XApuConnect( + input: *const ConnectInput, + output: *mut ConnectOutput, + handle: *mut *mut Connection, +) -> HRESULT { + if input.is_null() || output.is_null() || handle.is_null() { + return E_INVALIDARG; + } + // SAFETY: checked non-null. + let input = unsafe { &*input }; + if !(1..=500).contains(&input.streams) + || !(1..=16).contains(&input.commands_per_stream) + || input.memory == 0 + { + return E_INVALIDARG; + } + if input.process != DECODE_OPUS { + // shortcut: rate conversion (decode-convert, PCM convert) is not + // implemented; add a resampler if a title connects for it. + tracing::warn!( + process = input.process, + "audio decoder: processing kind not implemented" + ); + return E_NOTIMPL; + } + if input.frames_per_output != 0 { + return E_INVALIDARG; + } + let Ok(layout) = Layout::from_size_align(input.memory as usize, 16) else { + return E_INVALIDARG; + }; + // SAFETY: non-zero size. + let memory = unsafe { std::alloc::alloc_zeroed(layout) }; + if memory.is_null() { + return E_OUTOFMEMORY; + } + let event = if input.options & RESULT_EVENT != 0 { + // SAFETY: plain auto-reset event, no name. + unsafe { CreateEventW(std::ptr::null(), 0, 0, std::ptr::null()) } + } else { + std::ptr::null_mut() + }; + let streams = input.streams as usize; + tracing::info!( + streams, + memory = input.memory, + options = input.options, + "audio decoder connected" + ); + let connection = Box::new(Connection { + memory, + layout, + event, + options: input.options, + per_stream: input.commands_per_stream, + state: Mutex::new(State { + streams: (0..streams).map(|_| None).collect(), + queued: vec![0; streams], + results: VecDeque::new(), + commands: 0, + dequeued: 0, + }), + }); + // SAFETY: checked non-null. + unsafe { + output.write(ConnectOutput { + memory: memory.cast(), + result_event: event, + }); + handle.write(Box::into_raw(connection)); + } + S_OK +} + +pub extern "system" fn XApuDisconnect(handle: *mut Connection) -> HRESULT { + if handle.is_null() { + return E_INVALIDARG; + } + // SAFETY: made by `XApuConnect`; disconnected once. + let connection = unsafe { Box::from_raw(handle) }; + if !connection.event.is_null() { + // SAFETY: our event. + unsafe { CloseHandle(connection.event) }; + } + // SAFETY: allocated in `XApuConnect` with this layout. + unsafe { std::alloc::dealloc(connection.memory, connection.layout) }; + S_OK +} + +pub extern "system" fn XApuEnqueueCommand( + handle: *mut Connection, + command: *const CommandId, + total: *mut u32, +) -> HRESULT { + if handle.is_null() || command.is_null() { + return E_INVALIDARG; + } + // SAFETY: a connection from `XApuConnect`; every command starts with an id. + let (connection, id) = unsafe { (&*handle, command.read_unaligned()) }; + let mut state = lock(connection); + let stream = id.stream as usize; + if stream >= state.streams.len() { + return INVALID_STREAM; + } + if state.queued[stream] >= connection.per_stream { + return QUEUE_FULL; + } + let mut result = ApuResult { + id, + state: 0, + state_data: 0, + usec: 0, + error: S_OK, + frames: 0, + output_length: 0, + output: std::ptr::null_mut(), + pitch: 1.0, + input_length: 0, + input: std::ptr::null(), + }; + let decoder = &mut state.streams[stream]; + match id.kind { + ACTIVATE => { + // SAFETY: an activate command is this struct. + let channels = unsafe { command.cast::().read_unaligned() }.channels; + tracing::debug!(stream, channels, "Opus stream activated"); + result.error = if decoder.is_some() { + ALREADY_ACTIVE + } else { + match OpusDecoder::new(48_000, channels as usize) { + Ok(d) if (1..=2).contains(&channels) => { + *decoder = Some(d); + S_OK + } + _ => E_INVALIDARG, + } + }; + } + DEACTIVATE => *decoder = None, + RESET => { + if let Some(d) = decoder { + let _ = d.reset_state(); + } + } + NOTIFY => {} + PROCESS => { + // SAFETY: a process command is this struct. + let command = unsafe { command.cast::().read_unaligned() }; + match decoder { + Some(d) => process(d, connection.options, &command, &mut result), + None => result.error = INVALID_STREAM, + } + } + _ => return INVALID_COMMAND, + } + state.queued[stream] += 1; + state.commands = state.commands.wrapping_add(1); + state.results.push_back(result); + if !total.is_null() { + // SAFETY: optional out parameter. + unsafe { total.write(state.commands) }; + } + if id.options & SIGNAL != 0 && !connection.event.is_null() { + // SAFETY: our event. + unsafe { SetEvent(connection.event) }; + } + S_OK +} + +/// Decodes one packet into the command's output buffer, keeping the frames +/// from `first_frame` on, at most `frame_count` of them. +fn process(decoder: &mut OpusDecoder, options: u32, command: &Process, result: &mut ApuResult) { + let channels = decoder.channels(); + let (input, input_length) = (command.input, command.input_length); + let (output, output_length) = (command.output, command.output_length); + result.input = input; + result.input_length = input_length; + result.output = output; + if input.is_null() || output.is_null() || input_length == 0 { + result.error = E_INVALIDARG; + return; + } + // SAFETY: the title's packet in its connection memory. + let packet = unsafe { std::slice::from_raw_parts(input, input_length as usize) }; + let mut pcm = vec![0f32; MAX_FRAMES * channels]; + let decoded = match decoder.decode(packet, MAX_FRAMES, &mut pcm) { + Ok(n) => n, + Err(_) => { + result.error = BAD_PACKET; + return; + } + }; + let first = (command.first_frame as usize).min(decoded); + let frames = (decoded - first) + .min(command.frame_count as usize) + .min(output_length as usize / (4 * channels)); + let kept = &pcm[first * channels..(first + frames) * channels]; + // SAFETY: the title's output buffer holds `output_length` bytes. + let out = unsafe { std::slice::from_raw_parts_mut(output.cast::(), frames * channels) }; + if options & DEINTERLEAVED_OUTPUT != 0 && channels == 2 { + for (i, frame) in kept.as_chunks::<2>().0.iter().enumerate() { + (out[i], out[frames + i]) = (frame[0], frame[1]); + } + } else { + out.copy_from_slice(kept); + } + result.frames = frames as u32; + result.output_length = (frames * channels * 4) as u32; +} + +pub extern "system" fn XApuDequeueResult(handle: *mut Connection, out: *mut ApuResult) -> HRESULT { + if handle.is_null() || out.is_null() { + return E_INVALIDARG; + } + // SAFETY: a connection from `XApuConnect`. + let mut state = lock(unsafe { &*handle }); + let Some(result) = state.results.pop_front() else { + return PENDING_RESULTS; + }; + let stream = result.id.stream as usize; + state.queued[stream] -= 1; + state.dequeued = state.dequeued.wrapping_add(1); + // SAFETY: the title passes room for one result. + unsafe { out.write_unaligned(result) }; + S_OK +} + +pub extern "system" fn XApuGetResultCount(handle: *mut Connection, total: *mut u32) -> u32 { + if handle.is_null() { + return 0; + } + // SAFETY: a connection from `XApuConnect`. + let state = lock(unsafe { &*handle }); + if !total.is_null() { + // SAFETY: optional out parameter. + unsafe { total.write(state.dequeued) }; + } + state.results.len() as u32 +} + +pub(crate) fn module() -> HleModule { + HleModule { + name: "apu", + dlls: &["xapu.dll"], + exports: vec![ + hle_export!(XApuConnect), + hle_export!(XApuDisconnect), + hle_export!(XApuEnqueueCommand), + hle_export!(XApuDequeueResult), + hle_export!(XApuGetResultCount), + ], + } +} + +#[cfg(test)] +mod tests { + use super::*; + use opus_pure::{Application, OpusEncoder}; + + fn id(kind: u32, stream: u32) -> CommandId { + CommandId { + kind, + stream, + sequence: 7, + options: 0, + context: 0x1234, + } + } + + #[test] + fn decodes_opus_as_the_title_drives_it() { + assert_eq!(size_of::(), 0x50); + // 256 mono/stereo streams, two commands each, as the title connects. + let input = ConnectInput { + process: DECODE_OPUS, + streams: 256, + commands_per_stream: 2, + memory: 0x10_4000, + frames_per_output: 0, + options: 1, + }; + let mut output = ConnectOutput { + memory: std::ptr::null_mut(), + result_event: std::ptr::null_mut(), + }; + let mut handle = std::ptr::null_mut(); + assert_eq!(XApuConnect(&input, &mut output, &mut handle), S_OK); + let base = output.memory.cast::(); + + let activate = Activate { + id: id(ACTIVATE, 3), + channels: 2, + init_length: 0, + init: std::ptr::null(), + start_pitch: 1.0, + processing_length: 0, + processing: std::ptr::null_mut(), + }; + assert_eq!( + XApuEnqueueCommand(handle, (&raw const activate).cast(), std::ptr::null_mut()), + S_OK + ); + + // A 20 ms stereo packet of a 440 Hz tone. + let tone: Vec = (0..960 * 2) + .map(|i| ((i / 2) as f32 * 440.0 * std::f32::consts::TAU / 48_000.0).sin() * 0.5) + .collect(); + let mut encoder = OpusEncoder::new(48_000, 2, Application::Audio).unwrap(); + let mut packet = [0u8; 1500]; + let n = encoder.encode(&tone, 960, &mut packet).unwrap(); + // SAFETY: inside the connection memory. + unsafe { std::ptr::copy_nonoverlapping(packet.as_ptr(), base, n) }; + let process = Process { + id: id(PROCESS, 3), + pitch_ramp: 0.0, + target_pitch: 1.0, + first_frame: 0, + frame_count: 960, + input_length: n as u32, + input: base, + output_length: 0xf00 * 2, + output: base.wrapping_add(0x14000), + }; + let mut total = 0; + assert_eq!( + XApuEnqueueCommand(handle, (&raw const process).cast(), &mut total), + S_OK + ); + assert_eq!(total, 2); + // Two results queued for stream 3: its queue is full. + assert_eq!( + XApuEnqueueCommand(handle, (&raw const process).cast(), &mut total), + QUEUE_FULL + ); + assert_eq!(XApuGetResultCount(handle, std::ptr::null_mut()), 2); + + let mut result = std::mem::MaybeUninit::::zeroed(); + assert_eq!(XApuDequeueResult(handle, result.as_mut_ptr()), S_OK); + // SAFETY: written above. + let first = unsafe { result.assume_init() }; + let (kind, error, context) = (first.id.kind, first.error, first.id.context); + assert_eq!((kind, error, context), (ACTIVATE, S_OK, 0x1234)); + assert_eq!(XApuDequeueResult(handle, result.as_mut_ptr()), S_OK); + // SAFETY: written above. + let decoded = unsafe { result.assume_init() }; + let (kind, error, frames, length) = ( + decoded.id.kind, + decoded.error, + decoded.frames, + decoded.output_length, + ); + assert_eq!((kind, error, frames, length), (PROCESS, S_OK, 960, 960 * 8)); + // SAFETY: the decoder wrote 960 stereo frames there. + let pcm = + unsafe { std::slice::from_raw_parts(base.wrapping_add(0x14000).cast::(), 1920) }; + let energy: f32 = pcm.iter().map(|s| s * s).sum::() / 1920.0; + assert!(energy > 0.01, "decoded a tone, energy {energy}"); + assert_eq!( + XApuDequeueResult(handle, result.as_mut_ptr()), + PENDING_RESULTS + ); + let mut dequeued = 0; + assert_eq!(XApuGetResultCount(handle, &mut dequeued), 0); + assert_eq!(dequeued, 2); + + // A process on a stream that was never activated fails in its result. + let mut stray = process; + stray.id.stream = 4; + assert_eq!( + XApuEnqueueCommand(handle, (&raw const stray).cast(), &mut total), + S_OK + ); + assert_eq!(XApuDequeueResult(handle, result.as_mut_ptr()), S_OK); + // SAFETY: written above. + let error = unsafe { result.assume_init() }.error; + assert_eq!(error, INVALID_STREAM); + assert_eq!(XApuDisconnect(handle), S_OK); + } +} diff --git a/crates/leonida-hle/src/modules/audio.rs b/crates/leonida-hle/src/modules/audio.rs new file mode 100644 index 000000000..76ae7f963 --- /dev/null +++ b/crates/leonida-hle/src/modules/audio.rs @@ -0,0 +1,1172 @@ +//! The console's audio hardware (`AcpHal.dll`): +//! +//! * the APU heap: host memory with 32-bit device addresses; +//! * SHAPE context arrays allocated from it; +//! * the audio coprocessor's command and message queues, where every +//! command completes at once and is acknowledged as the hardware would; +//! * the XMA decoder: enabled XMA contexts are decoded on a thread of ours +//! into their output rings, like the hardware does. +//! +//! SHAPE's other units (rate conversion, EQ, filters, mixing through +//! flowgraphs) are not emulated, so voices that need them stay silent. +//! Mixed audio leaves through the host's WASAPI, which titles and +//! middleware reach through COM like on PC. fmod's console build sets up +//! the coprocessor inside `System_Create` and waits there for its first +//! command to be acknowledged; the title uses only XMA contexts. +#![allow(non_snake_case)] +#![allow(clippy::not_unsafe_ptr_arg_deref)] + +use std::alloc::Layout; +use std::collections::{BTreeMap, VecDeque}; +use std::ffi::c_void; +use std::sync::{Mutex, MutexGuard, OnceLock, RwLock, RwLockReadGuard}; +use std::time::Instant; + +use super::xasync::E_INVALIDARG; +use super::xgameruntime::{HRESULT, S_OK}; +use crate::{HleModule, hle_export}; + +#[cfg(all(windows, feature = "diagnostics"))] +pub mod capture; + +const E_FAIL: HRESULT = 0x8000_4005_u32 as i32; +const E_OUTOFMEMORY: HRESULT = 0x8007_000E_u32 as i32; + +fn lock(m: &Mutex) -> MutexGuard<'_, T> { + m.lock().unwrap_or_else(|e| e.into_inner()) +} + +// The APU heap. + +struct Block { + size: usize, + apu: u32, + layout: Layout, +} + +struct Heap { + /// By host address. + blocks: BTreeMap, + /// Host address by device address. + by_apu: BTreeMap, + /// Free device address ranges, start to end, merged with neighbours. + free: BTreeMap, + /// Set by `ApuCreateHeap` or the first allocation: the heap exists. + created: bool, +} + +static HEAP: Mutex = Mutex::new(Heap { + blocks: BTreeMap::new(), + by_apu: BTreeMap::new(), + free: BTreeMap::new(), + created: false, +}); + +/// Device addresses start above 0, which means "none" to titles. +const APU_BASE: u32 = 0x0001_0000; + +impl Heap { + /// First fit in the free ranges. + fn take(&mut self, size: u32, align: u32) -> Option { + if self.free.is_empty() && !self.created { + self.free.insert(APU_BASE, u32::MAX); + } + self.created = true; + let (start, end, apu) = self.free.iter().find_map(|(&start, &end)| { + let apu = start.checked_next_multiple_of(align)?; + (apu.checked_add(size)? <= end).then_some((start, end, apu)) + })?; + self.free.remove(&start); + if start < apu { + self.free.insert(start, apu); + } + if apu + size < end { + self.free.insert(apu + size, end); + } + Some(apu) + } + + fn give_back(&mut self, mut start: u32, mut end: u32) { + if let Some((&before, &before_end)) = self.free.range(..start).next_back() + && before_end == start + { + self.free.remove(&before); + start = before; + } + if let Some(after_end) = self.free.remove(&end) { + end = after_end; + } + self.free.insert(start, end); + } +} + +/// Zeroed host memory and its device address. +fn heap_alloc(size: usize, align: usize) -> Option<(*mut u8, u32)> { + let layout = Layout::from_size_align(size.max(1), align.max(16)).ok()?; + let mut heap = lock(&HEAP); + let apu = heap.take(u32::try_from(layout.size()).ok()?, align as u32)?; + // SAFETY: non-zero size. + let ptr = unsafe { std::alloc::alloc_zeroed(layout) }; + if ptr.is_null() { + heap.give_back(apu, apu + layout.size() as u32); + return None; + } + heap.blocks + .insert(ptr as usize, Block { size, apu, layout }); + heap.by_apu.insert(apu, ptr as usize); + // The big ones are named in the log: they are the title's audio memory + // given out of our allocator, which the memory line counts as ours. + if size >= 32 << 20 { + tracing::info!(mb = size >> 20, at = ?ptr, "audio memory for the title from our allocator"); + } + Some((ptr, apu)) +} + +fn heap_free(ptr: *mut u8) { + let mut heap = lock(&HEAP); + let Some(block) = heap.blocks.remove(&(ptr as usize)) else { + return; + }; + heap.by_apu.remove(&block.apu); + heap.give_back(block.apu, block.apu + block.layout.size() as u32); + drop(heap); + // SAFETY: allocated by `heap_alloc` with this layout. + unsafe { std::alloc::dealloc(ptr, block.layout) }; +} + +/// Sizes the heap once, before anything is allocated from it. The console +/// reserves both parts up front; we allocate per block, so the sizes only +/// decide whether the call is valid. +// shortcut: the cached and non-cached sizes are not enforced as limits; +// enforce them if a title relies on running out. +pub extern "system" fn ApuCreateHeap(cached: u32, _non_cached: u32) -> HRESULT { + const ALREADY_ALLOCATED: HRESULT = 0x8ACA_0001_u32 as i32; + if cached == 0 { + return E_INVALIDARG; + } + let mut heap = lock(&HEAP); + if heap.created { + return ALREADY_ALLOCATED; + } + heap.created = true; + heap.free.insert(APU_BASE, u32::MAX); + S_OK +} + +/// The host address of a device address, null outside the heap. +pub extern "system" fn ApuMapApuAddress(apu: u32) -> *mut c_void { + heap_unmap(apu).map_or(std::ptr::null_mut(), |p| p.cast()) +} + +/// The device address of any byte of a heap block, 0 elsewhere. +fn heap_map(ptr: usize) -> u32 { + let heap = lock(&HEAP); + match heap.blocks.range(..=ptr).next_back() { + Some((&start, block)) if ptr < start + block.size.max(1) => { + block.apu + (ptr - start) as u32 + } + _ => 0, + } +} + +/// The host address of a device address, if a heap block holds it. +fn heap_unmap(apu: u32) -> Option<*mut u8> { + let heap = lock(&HEAP); + let (&start, &host) = heap.by_apu.range(..=apu).next_back()?; + let block = &heap.blocks[&host]; + (apu < start.saturating_add(block.size.max(1) as u32)) + .then(|| (host + (apu - start) as usize) as *mut u8) +} + +/// `len` bytes of title memory at a device address, if one heap block holds +/// them all. +fn heap_bytes<'a>(apu: u32, len: usize) -> Option<&'a mut [u8]> { + let heap = lock(&HEAP); + let (&start, &host) = heap.by_apu.range(..=apu).next_back()?; + let offset = (apu - start) as usize; + (offset + len <= heap.blocks[&host].size) + // SAFETY: inside a live heap block, which the title and the audio + // hardware share like on the console. + .then(|| unsafe { std::slice::from_raw_parts_mut((host + offset) as *mut u8, len) }) +} + +pub extern "system" fn ApuAlloc( + out: *mut *mut c_void, + apu: *mut u32, + size: u32, + align: u32, + _flags: u32, +) -> HRESULT { + if out.is_null() || size == 0 || align < 4 || !align.is_power_of_two() { + return E_INVALIDARG; + } + let Some((ptr, address)) = heap_alloc(size as usize, align as usize) else { + return E_OUTOFMEMORY; + }; + // SAFETY: checked non-null; optional out parameter checked below. + unsafe { + out.write(ptr.cast()); + if !apu.is_null() { + apu.write(address); + } + } + S_OK +} + +pub extern "system" fn ApuFree(ptr: *mut c_void) { + heap_free(ptr.cast()); +} + +pub extern "system" fn ApuMapVirtualAddress(ptr: *const c_void) -> u32 { + heap_map(ptr as usize) +} + +pub extern "system" fn ApuIsVirtualAddressValid(ptr: *const c_void, align: u32) -> bool { + let apu = heap_map(ptr as usize); + apu != 0 && (align == 0 || apu.is_multiple_of(align)) +} + +// SHAPE context arrays. + +/// Six counts (rate conversion, EQ/compression, filter/volume, DMA, XMA, +/// PCM), then the six arrays and their device addresses. +#[repr(C, packed)] +pub struct ShapeContexts { + counts: [u32; 6], + arrays: [*mut c_void; 6], + apu: [u32; 6], +} + +/// Bytes per context: rate conversion, DMA and XMA as fmod clears them; +/// the others (not seen yet) get a generous upper bound. +const CONTEXT_BYTES: [usize; 6] = [32, 256, 256, 16, 64, 256]; + +static CONTEXTS: Mutex> = Mutex::new(None); + +pub extern "system" fn AcpHalAllocateShapeContexts(contexts: *mut ShapeContexts) -> HRESULT { + if contexts.is_null() { + return E_INVALIDARG; + } + let mut allocated = lock(&CONTEXTS); + if allocated.is_some() { + return E_FAIL; + } + // SAFETY: the title passes its request; packed fields are copied out. + let counts = unsafe { std::ptr::addr_of!((*contexts).counts).read_unaligned() }; + let mut arrays: [*mut c_void; 6] = [std::ptr::null_mut(); 6]; + let mut addresses = [0u32; 6]; + for i in 0..6 { + if counts[i] == 0 { + continue; + } + let Some((ptr, apu)) = heap_alloc(counts[i] as usize * CONTEXT_BYTES[i], 256) else { + arrays.iter().for_each(|&p| heap_free(p.cast())); + return E_OUTOFMEMORY; + }; + (arrays[i], addresses[i]) = (ptr.cast(), apu); + } + // SAFETY: as above. + unsafe { + std::ptr::addr_of_mut!((*contexts).arrays).write_unaligned(arrays); + std::ptr::addr_of_mut!((*contexts).apu).write_unaligned(addresses); + } + *allocated = Some(arrays.map(|p| p as usize)); + let mut xma = XMA.write().unwrap_or_else(|e| e.into_inner()); + xma.array = arrays[4] as usize; + xma.voices = (0..counts[4]).map(|_| Mutex::new(None)).collect(); + S_OK +} + +pub extern "system" fn AcpHalReleaseShapeContexts() -> HRESULT { + match lock(&CONTEXTS).take() { + Some(arrays) => { + *XMA.write().unwrap_or_else(|e| e.into_inner()) = Xma::EMPTY; + arrays.iter().for_each(|&p| heap_free(p as *mut u8)); + S_OK + } + None => E_FAIL, + } +} + +// The XMA decoder. +// +// An XMA context (16 words in the shared context array) names up to two +// input buffers of 2 KiB packets, a ring of 256-byte output blocks the +// hardware fills with 16-bit PCM, and the read offset the title advances +// by command. Words and bit fields, as titles write them: +// 0: input 0 size in packets (0-11), loop count (12-19, 255 forever), +// valid inputs (20-21), output size in blocks (22-26), write block +// (27-31, hardware); +// 1: input 1 size (0-11), loop end subframe (12-13), loop start subframes +// to skip (17-19), subframes to skip at the start (24-26), sample rate +// (27-28: 24, 32, 44.1, 48 kHz), stereo (29), output writable (31); +// 2: read position in bits (0-25), error status (26-30), error (31); +// 3: loop start in bits (0-25); 4: loop end in bits (0-25), current input +// (31); 5, 6: input addresses; 7: output address; 8: overlap buffer; +// 9: read block (0-4). +// Titles read back only the write block, "writable" and the read block, +// and take whatever lies between read and write. +// shortcut: each enabled context decodes from a cold state and the overlap +// buffer is ignored (titles copy it between consecutive contexts of one +// voice); keep decoder state there if a title's seams turn out audible. + +use leonida_formats::xma; + +const ENABLE_XMA: u32 = 5; +const ENABLE_XMAS: u32 = 6; +const DISABLE_XMA: u32 = 7; +const DISABLE_XMAS: u32 = 8; +const ADVANCE_XMA_READ: u32 = 18; + +const BLOCK_BYTES: usize = 256; +const SAMPLES_PER_BLOCK: usize = BLOCK_BYTES / 2; +/// Error status: the input ran out. +const INPUT_INVALID: u32 = 4; + +struct Voice { + decoder: Option, + pcm: VecDeque, + /// Samples per channel still to drop (start or loop subframe skips). + skip: usize, + ended: bool, + trace: Trace, +} + +/// What a voice did, for the debug log when it is disabled. +struct Trace { + since: Instant, + /// Samples per channel written to the ring. + produced: usize, + /// Blocks the title took (command 18), how often, and how often it + /// found the ring less than full. + taken: usize, + takes: u32, + partial_takes: u32, + frames: u32, + bad_frames: u32, + /// The loudest sample written. + peak: i16, + /// Milliseconds after enabling when the input ran out. + ended_ms: Option, +} + +struct Xma { + /// Host address of the context array. + array: usize, + /// One entry per context, `Some` while enabled. Each has its own lock, + /// so a command for one voice never waits for others to decode (the + /// title sends them from its time-critical mixer thread). + voices: Vec>>, +} + +impl Xma { + const EMPTY: Xma = Xma { + array: 0, + voices: Vec::new(), + }; +} + +/// Written only when the context arrays are allocated or released. +static XMA: RwLock = RwLock::new(Xma::EMPTY); + +fn xma() -> RwLockReadGuard<'static, Xma> { + XMA.read().unwrap_or_else(|e| e.into_inner()) +} + +/// A context's words in title memory. +#[derive(Clone, Copy)] +struct Context(*mut u32); + +impl Context { + fn get(self, word: usize) -> u32 { + // SAFETY: inside the context array; the title reads and writes it + // concurrently, like the hardware's. + unsafe { self.0.add(word).read_volatile() } + } + + fn set(self, word: usize, value: u32) { + // SAFETY: as above. + unsafe { self.0.add(word).write_volatile(value) } + } + + fn field(self, word: usize, shift: u32, bits: u32) -> u32 { + (self.get(word) >> shift) & ((1 << bits) - 1) + } + + fn set_field(self, word: usize, shift: u32, bits: u32, value: u32) { + let mask = ((1u32 << bits) - 1) << shift; + self.set(word, (self.get(word) & !mask) | ((value << shift) & mask)); + } + + fn channels(self) -> usize { + 1 + self.field(1, 29, 1) as usize + } +} + +impl Xma { + fn context(&self, index: u32) -> Option { + ((index as usize) < self.voices.len() && self.array != 0) + .then(|| Context((self.array + index as usize * 64) as *mut u32)) + } + + fn enable(&self, index: u32) { + let Some(context) = self.context(index) else { + return; + }; + let mut slot = lock(&self.voices[index as usize]); + context.set_field(2, 26, 6, 0); + tracing::debug!( + index, + words = ?(0..10).map(|w| format!("{:08x}", context.get(w))).collect::>(), + "XMA voice enabled" + ); + #[cfg(feature = "diagnostics")] + dump_input(index, context); + *slot = Some(Voice { + decoder: None, + pcm: VecDeque::new(), + skip: context.field(1, 24, 3) as usize * xma::SUBFRAME_SAMPLES, + ended: false, + trace: Trace { + since: Instant::now(), + produced: 0, + taken: 0, + takes: 0, + partial_takes: 0, + frames: 0, + bad_frames: 0, + peak: 0, + ended_ms: None, + }, + }); + drop(slot); + wake_decoder(); + } + + fn disable(&self, index: u32) { + let Some(context) = self.context(index) else { + return; + }; + let Some(voice) = lock(&self.voices[index as usize]).take() else { + return; + }; + let t = &voice.trace; + tracing::debug!( + index, + ms = t.since.elapsed().as_millis(), + produced = t.produced, + taken = t.taken * SAMPLES_PER_BLOCK / context.channels(), + takes = t.takes, + partial_takes = t.partial_takes, + frames = t.frames, + bad_frames = t.bad_frames, + peak = t.peak, + input_ended_ms = ?t.ended_ms, + read_bit = context.field(2, 0, 26), + input_bits = context.field(0, 0, 12) * xma::PACKET_BYTES as u32 * 8, + "XMA voice disabled" + ); + } + + /// Moves the title's read block on, which frees output space. + fn advance_read(&self, index: u32, blocks: u32) { + let Some(context) = self.context(index) else { + return; + }; + // The decoder writes the same words. + let mut slot = lock(&self.voices[index as usize]); + let size = context.field(0, 22, 5).max(1); + // The count is the title's: reduced first, so the sum stays small. + let read = (context.field(9, 0, 5) + blocks % size) % size; + context.set_field(9, 0, 5, read); + if blocks > 0 { + context.set_field(1, 31, 1, 1); + } + if let Some(voice) = &mut *slot { + let t = &mut voice.trace; + t.taken += blocks as usize; + t.takes += 1; + t.partial_takes += u32::from(blocks < size); + } + drop(slot); + wake_decoder(); + } + + /// Fills every enabled context's output as far as it has room. + fn pump(&self) { + let start = Instant::now(); + let mut active = 0; + for index in 0..self.voices.len() as u32 { + if let (Some(context), Some(voice)) = + (self.context(index), &mut *lock(&self.voices[index as usize])) + { + pump(context, voice); + active += 1; + } + } + let took = start.elapsed(); + if took.as_millis() >= 4 { + tracing::debug!(active, ms = took.as_millis(), "slow XMA decoding pass"); + } + } +} + +fn pump(context: Context, voice: &mut Voice) { + let size = context.field(0, 22, 5); + if size == 0 { + return; + } + while context.field(1, 31, 1) == 1 { + if voice.pcm.len() < SAMPLES_PER_BLOCK && !decode(context, voice) { + return; + } + let write = context.field(0, 27, 5); + let address = context.get(7) as usize + write as usize * BLOCK_BYTES; + let Some(out) = heap_bytes(address as u32, BLOCK_BYTES) else { + return; + }; + for pair in out.as_chunks_mut::<2>().0 { + let sample = voice.pcm.pop_front().unwrap_or(0); + voice.trace.peak = voice.trace.peak.max(sample.saturating_abs()); + pair.copy_from_slice(&sample.to_le_bytes()); + } + voice.trace.produced += SAMPLES_PER_BLOCK / context.channels(); + let write = (write + 1) % size; + context.set_field(0, 27, 5, write); + if write == context.field(9, 0, 5) { + // Full: nothing more until the title advances its read block. + context.set_field(1, 31, 1, 0); + } + } +} + +/// Decodes the next frame of the current input into `voice.pcm`; false +/// when there is nothing left to decode. +fn decode(context: Context, voice: &mut Voice) -> bool { + if voice.ended { + return false; + } + let channels = context.channels(); + let mut current = context.field(4, 31, 1); + let valid = context.field(0, 20, 2); + if valid & (1 << current) == 0 { + if valid & (1 << (1 - current)) == 0 { + // Out of input: the overlap tail, then nothing. + if let Some(decoder) = &mut voice.decoder { + let mut tail = Vec::new(); + decoder.flush(&mut tail); + voice.pcm.extend(tail); + } + voice.ended = true; + voice.trace.ended_ms = Some(voice.trace.since.elapsed().as_millis()); + context.set_field(2, 26, 5, INPUT_INVALID); + context.set_field(2, 31, 1, 1); + return !voice.pcm.is_empty(); + } + current = 1 - current; + context.set_field(4, 31, 1, current); + context.set_field(2, 0, 26, 0); + } + let (address, packets) = match current { + 0 => (context.get(5), context.field(0, 0, 12)), + _ => (context.get(6), context.field(1, 0, 12)), + }; + let Some(data) = heap_bytes(address & !0x7ff, packets as usize * xma::PACKET_BYTES) else { + context.set_field(0, 20 + current, 1, 0); + return true; + }; + let mut at = context.field(2, 0, 26) as usize; + if at < 32 { + at = 32 + xma::packet(data, 0).map_or(0, |p| p.first_frame_bit as usize); + } + let Some(frame) = xma::read_frame(data, at) else { + // This input is used up. + context.set_field(0, 20 + current, 1, 0); + return true; + }; + let decoder = voice.decoder.get_or_insert_with(|| { + const RATES: [u32; 4] = [24_000, 32_000, 44_100, 48_000]; + xma::Decoder::new(channels, RATES[context.field(1, 27, 2) as usize]) + }); + let mut pcm = Vec::with_capacity(xma::FRAME_SAMPLES * channels); + voice.trace.frames += 1; + if let Err(e) = decoder.decode(&frame.data, frame.bits, &mut pcm) { + voice.trace.bad_frames += 1; + if voice.trace.bad_frames <= 2 { + tracing::debug!( + at, + bits = frame.bits, + head = ?&frame.data[..frame.data.len().min(8)], + %e, + "XMA frame did not decode" + ); + } + } + let mut next = frame.next.unwrap_or(0); + let loops = context.field(0, 12, 8); + let loop_end = context.field(4, 0, 26) as usize; + let ends_loop = loop_end != 0 + && (frame.start == loop_end + || (frame.start < loop_end && frame.next.is_none_or(|n| loop_end < n))); + if loops > 0 && ends_loop { + let keep = (context.field(1, 12, 2) as usize + 1) * xma::SUBFRAME_SAMPLES * channels; + pcm.truncate(keep); + next = context.field(3, 0, 26) as usize; + voice.skip = context.field(1, 17, 3) as usize * xma::SUBFRAME_SAMPLES; + if loops != 255 { + context.set_field(0, 12, 8, loops - 1); + } + } + let skip = (voice.skip * channels).min(pcm.len()); + voice.skip -= skip / channels; + voice.pcm.extend(&pcm[skip..]); + if next == 0 { + context.set_field(0, 20 + current, 1, 0); + } + context.set_field(2, 0, 26, next as u32); + true +} + +/// `LEONIDA_XMA_DUMP=`: saves the context words (`-.ctx`) +/// and input buffer 0 (`.xma`) of the first 32 voices enabled, to test +/// the decoder on a title's streams outside the title. +#[cfg(feature = "diagnostics")] +fn dump_input(index: u32, context: Context) { + static COUNT: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); + let Some(dir) = std::env::var_os("LEONIDA_XMA_DUMP") else { + return; + }; + let n = COUNT.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + if n >= 32 { + return; + } + let dir = std::path::PathBuf::from(dir); + let words: Vec = (0..16).flat_map(|w| context.get(w).to_le_bytes()).collect(); + let input = heap_bytes( + context.get(5) & !0x7ff, + context.field(0, 0, 12) as usize * xma::PACKET_BYTES, + ); + let _ = std::fs::create_dir_all(&dir); + let _ = std::fs::write(dir.join(format!("{n:02}-{index}.ctx")), words); + let _ = std::fs::write(dir.join(format!("{n:02}-{index}.xma")), input.unwrap_or_default()); +} + +/// Starts the decoding thread on the first enabled voice, and has it fill +/// rings now: a voice just enabled or read from. +fn wake_decoder() { + static DECODER: OnceLock = OnceLock::new(); + DECODER + .get_or_init(|| { + std::thread::Builder::new() + .name("leonida XMA decoder".into()) + .spawn(|| { + loop { + xma().pump(); + // A 256-byte output block lasts 2.7 ms at 48 kHz mono. + std::thread::park_timeout(std::time::Duration::from_millis(2)); + } + }) + .map_or_else(|_| std::thread::current(), |h| h.thread().clone()) + }) + .unpark(); +} + +/// Runs an XMA command; false for one this does not know. +fn xma_command(command: u32, word: impl Fn(usize) -> Option) -> bool { + let xma = xma(); + match command { + ENABLE_XMA => xma.enable(word(0).unwrap_or(u32::MAX)), + DISABLE_XMA => xma.disable(word(0).unwrap_or(u32::MAX)), + ENABLE_XMAS | DISABLE_XMAS => { + for i in 0..xma.voices.len() as u32 { + if word(i as usize / 32).unwrap_or(0) & (1 << (i % 32)) != 0 { + match command { + ENABLE_XMAS => xma.enable(i), + _ => xma.disable(i), + } + } + } + } + ADVANCE_XMA_READ => xma.advance_read(word(0).unwrap_or(u32::MAX), word(1).unwrap_or(0)), + _ => return false, + } + true +} + +// The audio coprocessor. + +const LOAD_FLOWGRAPH: u32 = 1; +const REGISTER_MESSAGES: u32 = 2; +const UNREGISTER_MESSAGES: u32 = 3; + +const FLOWGRAPH_COMPLETED: u32 = 0x02; +const COMMAND_COMPLETED: u32 = 0x10; +const DISCONNECTED: u32 = 0x80; + +/// Audio frames of 128 samples at 48 kHz. +const FRAMES_PER_SECOND: u64 = 375; + +#[repr(C, packed)] +#[derive(Clone, Copy)] +struct Message { + kind: u32, + dropped: u32, + usec: u32, + data: [u8; 16], +} + +struct State { + connected: bool, + /// Message kinds the title registered for. + mask: u32, + messages: VecDeque, + /// Queue size given to `connect`. + capacity: usize, + /// Messages lost to a full queue since the last one queued. + dropped: u32, + since: Instant, +} + +impl State { + fn usec(&self) -> u64 { + self.since.elapsed().as_micros() as u64 + } + + fn frame(&self) -> u32 { + (self.usec() * FRAMES_PER_SECOND / 1_000_000) as u32 + } + + /// Queues a registered message; a full queue drops it and counts it in + /// the next one that fits. + fn post(&mut self, kind: u32, data: &[u8]) { + if self.mask & kind == 0 { + return; + } + if self.messages.len() >= self.capacity { + self.dropped = self.dropped.saturating_add(1); + tracing::debug!(kind, dropped = self.dropped, "coprocessor message dropped"); + return; + } + let mut message = Message { + kind, + dropped: std::mem::take(&mut self.dropped), + usec: self.usec() as u32, + data: [0; 16], + }; + message.data[..data.len()].copy_from_slice(data); + self.messages.push_back(message); + } +} + +/// The interface object: its method table, then our state. +#[repr(C)] +pub struct Acp { + vtable: &'static AcpMethods, + state: Mutex, +} + +#[repr(C)] +struct AcpMethods { + connect: extern "system" fn(*mut Acp, u32, u32) -> HRESULT, + disconnect: extern "system" fn(*mut Acp) -> HRESULT, + submit: extern "system" fn(*mut Acp, u32, u64, u32, *const c_void, u32) -> HRESULT, + pop_message: extern "system" fn(*mut Acp, *mut Message) -> bool, + message_count: extern "system" fn(*mut Acp) -> u32, + release: extern "system" fn(*mut Acp), +} + +static ACP_METHODS: AcpMethods = AcpMethods { + connect, + disconnect, + submit, + pop_message, + message_count, + release, +}; + +fn state(this: *mut Acp) -> MutexGuard<'static, State> { + // SAFETY: title code calls methods on the object `AcpHalCreate` made, + // which lives until `release`. + lock(unsafe { &(*this).state }) +} + +extern "system" fn connect(this: *mut Acp, commands: u32, messages: u32) -> HRESULT { + if commands == 0 { + return E_INVALIDARG; + } + let mut state = state(this); + state.connected = true; + state.capacity = messages as usize; + S_OK +} + +extern "system" fn disconnect(this: *mut Acp) -> HRESULT { + let mut state = state(this); + if !state.connected { + return E_FAIL; + } + state.post(DISCONNECTED, &[]); + state.connected = false; + S_OK +} + +/// Done at once: message registrations take effect, a flowgraph completes +/// unprocessed, a command with an id is acknowledged, and its notification +/// word is set. +extern "system" fn submit( + this: *mut Acp, + command: u32, + id: u64, + _frame: u32, + data: *const c_void, + notification: u32, +) -> HRESULT { + static SEEN: Mutex = Mutex::new(0); + if command < 64 && *lock(&SEEN) & 1 << command == 0 { + *lock(&SEEN) |= 1 << command; + tracing::info!(command, "first coprocessor command of this kind"); + } + let mut state = state(this); + let word = |at: usize| -> Option { + // SAFETY: the command's data starts with these u32 fields. + (!data.is_null()).then(|| unsafe { data.cast::().add(at).read_unaligned() }) + }; + match command { + REGISTER_MESSAGES => state.mask |= word(0).unwrap_or(0), + UNREGISTER_MESSAGES => state.mask &= !word(0).unwrap_or(0), + LOAD_FLOWGRAPH => { + let flowgraph = word(1).unwrap_or(0); + state.post(FLOWGRAPH_COMPLETED, &flowgraph.to_le_bytes()); + } + _ if xma_command(command, word) => {} + // shortcut: context updates and the other SHAPE units' commands are + // acknowledged but not carried out; add them when a title sends + // them (each kind is logged once above). + _ => {} + } + if id != 0 { + let mut done = [0u8; 16]; + done[..4].copy_from_slice(&command.to_le_bytes()); + done[4..12].copy_from_slice(&id.to_le_bytes()); + done[12..].copy_from_slice(&state.frame().to_le_bytes()); + state.post(COMMAND_COMPLETED, &done); + } + if notification != 0 + && let Some(word) = heap_unmap(notification) + { + // SAFETY: a u32 in a heap block, which the title reads as volatile. + unsafe { word.cast::().write_volatile(1) }; + } + S_OK +} + +extern "system" fn pop_message(this: *mut Acp, out: *mut Message) -> bool { + let Some(message) = state(this).messages.pop_front() else { + return false; + }; + if !out.is_null() { + // SAFETY: the title passes room for one message. + unsafe { out.write_unaligned(message) }; + } + true +} + +extern "system" fn message_count(this: *mut Acp) -> u32 { + state(this).messages.len() as u32 +} + +extern "system" fn release(this: *mut Acp) { + // SAFETY: made by `AcpHalCreate` with `Box::into_raw`; released once. + drop(unsafe { Box::from_raw(this) }); +} + +pub extern "system" fn AcpHalCreate(out: *mut *mut Acp) -> HRESULT { + if out.is_null() { + return E_INVALIDARG; + } + let acp = Box::new(Acp { + vtable: &ACP_METHODS, + state: Mutex::new(State { + connected: false, + mask: 0, + messages: VecDeque::new(), + capacity: 0, + dropped: 0, + since: Instant::now(), + }), + }); + // SAFETY: checked non-null. + unsafe { out.write(Box::into_raw(acp)) }; + S_OK +} + +pub(crate) fn module() -> HleModule { + HleModule { + name: "audio", + dlls: &["acphal.dll"], + exports: vec![ + hle_export!(AcpHalAllocateShapeContexts), + hle_export!(AcpHalReleaseShapeContexts), + hle_export!(AcpHalCreate), + hle_export!(ApuAlloc), + hle_export!(ApuCreateHeap), + hle_export!(ApuFree), + hle_export!(ApuIsVirtualAddressValid), + hle_export!(ApuMapApuAddress), + hle_export!(ApuMapVirtualAddress), + ], + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn heap_maps_every_byte_of_a_block() { + let _serial = lock(&CONTEXT_TESTS); + let (mut ptr, mut apu) = (std::ptr::null_mut(), 0); + assert_eq!(ApuAlloc(&mut ptr, &mut apu, 0x100, 128, 1), S_OK); + assert!(apu != 0 && apu.is_multiple_of(128)); + let inner = ptr.cast::().wrapping_add(0x40).cast_const().cast(); + assert_eq!(ApuMapVirtualAddress(inner), apu + 0x40); + assert!(ApuIsVirtualAddressValid(ptr, 128)); + assert_eq!(heap_unmap(apu + 4), Some(ptr.cast::().wrapping_add(4))); + ApuFree(ptr); + assert_eq!(ApuMapVirtualAddress(ptr), 0); + assert_eq!(ApuAlloc(&mut ptr, &mut apu, 0x100, 6, 1), E_INVALIDARG); + } + + /// The context arrays and the heap exist once per process: tests that + /// allocate from them run one at a time (a concurrent allocation could + /// take a freed range a test expects back). + static CONTEXT_TESTS: Mutex<()> = Mutex::new(()); + + #[test] + fn heap_reuses_freed_addresses() { + let _serial = lock(&CONTEXT_TESTS); + let (mut a, mut b, mut c) = ( + std::ptr::null_mut(), + std::ptr::null_mut(), + std::ptr::null_mut(), + ); + let (mut apu_a, mut apu_b, mut apu_c) = (0, 0, 0); + assert_eq!(ApuAlloc(&mut a, &mut apu_a, 0x1000, 0x1000, 1), S_OK); + assert_eq!(ApuAlloc(&mut b, &mut apu_b, 0x1000, 0x1000, 1), S_OK); + ApuFree(a); + assert_eq!(ApuAlloc(&mut c, &mut apu_c, 0x800, 0x800, 1), S_OK); + // The freed range is free again, whichever part `c` took. + assert!( + lock(&HEAP) + .free + .iter() + .any(|(&s, &e)| s <= apu_a + 0x800 && apu_a + 0x1000 <= e) + || apu_c == apu_a + ); + assert_eq!( + ApuMapApuAddress(apu_b + 8), + b.cast::().wrapping_add(8).cast() + ); + assert!(ApuMapApuAddress(0).is_null()); + assert_eq!( + ApuCreateHeap(64 << 20, 0), + 0x8ACA_0001_u32 as i32, + "too late" + ); + ApuFree(b); + ApuFree(c); + } + + /// Two packets of three silent mono frames each: a fixed one-subframe + /// layout, no transmitted coefficients. + fn silent_stream() -> Vec { + let mut data = vec![0xffu8; 2 * xma::PACKET_BYTES]; + let mut put = |at: usize, value: u32, width: usize| { + for i in 0..width { + let (p, bit) = (at + i, (value >> (width - 1 - i)) & 1); + data[p / 8] = (data[p / 8] & !(0x80 >> (p % 8))) | ((bit as u8) << (7 - p % 8)); + } + }; + for packet in 0..2 { + let base = packet * xma::PACKET_BYTES * 8; + put(base, 3 << 26, 32); + for frame in 0..3 { + let at = base + 32 + frame * 31; + put(at, 31, 15); // length + put(at + 15, 0b10, 2); // fixed layout, one 512-sample subframe + put(at + 17, 0, 8 + 1 + 3 + 2); // gain, no trim, empty subframe + } + } + data + } + + #[test] + fn xma_contexts_decode_into_their_output_rings() { + let _serial = lock(&CONTEXT_TESTS); + let mut request = ShapeContexts { + counts: [0, 0, 0, 0, 4, 0], + arrays: [std::ptr::null_mut(); 6], + apu: [0; 6], + }; + assert_eq!(AcpHalAllocateShapeContexts(&mut request), S_OK); + let context = Context(request.arrays[4].cast::().wrapping_add(16)); + + let (mut input, mut input_apu) = (std::ptr::null_mut(), 0); + assert_eq!(ApuAlloc(&mut input, &mut input_apu, 0x1000, 0x800, 1), S_OK); + let stream = silent_stream(); + // SAFETY: two packets were allocated. + unsafe { std::ptr::copy_nonoverlapping(stream.as_ptr(), input.cast(), stream.len()) }; + let (mut output, mut output_apu) = (std::ptr::null_mut(), 0); + assert_eq!( + ApuAlloc(&mut output, &mut output_apu, 0x400, 0x100, 2), + S_OK + ); + // SAFETY: the ring was just allocated. + unsafe { output.cast::().write_bytes(0x55, 0x400) }; + + // As the title sets one up: two packets, input 0 valid, a ring of + // four blocks, writable, 48 kHz mono, reading from the first frame. + context.set(0, 2 | 1 << 20 | 4 << 22); + context.set(1, 1 << 31 | 3 << 27); + context.set(2, 32); + context.set(5, input_apu); + context.set(7, output_apu); + + let mut acp = std::ptr::null_mut(); + assert_eq!(AcpHalCreate(&mut acp), S_OK); + // SAFETY: just created. + let m = unsafe { (*acp).vtable }; + assert_eq!((m.connect)(acp, 0x1000, 0x1000), S_OK); + let submit = |command: u32, words: &[u32]| { + assert_eq!( + (m.submit)(acp, command, 0xf1, u32::MAX, words.as_ptr().cast(), 0), + S_OK + ); + }; + submit(ENABLE_XMA, &[1]); + xma().pump(); + // Full: all four blocks written (silence), the write block wrapped + // onto the read block, and the ring no longer writable. + assert_eq!(context.field(0, 27, 5), 0); + assert_eq!(context.field(1, 31, 1), 0); + // SAFETY: the ring. + let ring = unsafe { std::slice::from_raw_parts(output.cast::(), 0x400) }; + assert!(ring.iter().all(|&b| b == 0)); + + // Read four blocks at a time until the input has run out and the + // ring keeps room (the decoding thread may fill it too). + for _ in 0..20 { + submit(ADVANCE_XMA_READ, &[1, 4]); + xma().pump(); + if context.field(2, 31, 1) == 1 && context.field(1, 31, 1) == 1 { + break; + } + } + // Six frames and the flushed tail: 3,328 samples, 26 blocks. + let produced = |x: &Xma| lock(&x.voices[1]).as_ref().map(|v| v.trace.produced); + assert_eq!(produced(&xma()), Some(26 * SAMPLES_PER_BLOCK)); + assert_eq!(context.field(0, 20, 2), 0, "input used up"); + assert_eq!(context.field(2, 26, 5), INPUT_INVALID); + + // A count near `u32::MAX` wraps the read block like any other + // (3 + 0xffff_ffff blocks on a ring of four is block 2); the sum + // used to overflow. + context.set_field(9, 0, 5, 3); + submit(ADVANCE_XMA_READ, &[1, u32::MAX]); + assert_eq!(context.field(9, 0, 5), 2); + + submit(DISABLE_XMA, &[1]); + assert_eq!(produced(&xma()), None); + (m.release)(acp); + ApuFree(input); + ApuFree(output); + assert_eq!(AcpHalReleaseShapeContexts(), S_OK); + } + + #[test] + fn full_message_queues_count_drops() { + let mut acp = std::ptr::null_mut(); + assert_eq!(AcpHalCreate(&mut acp), S_OK); + // SAFETY: just created. + let m = unsafe { (*acp).vtable }; + assert_eq!((m.connect)(acp, 16, 2), S_OK); + let mask = COMMAND_COMPLETED; + assert_eq!( + (m.submit)( + acp, + REGISTER_MESSAGES, + 0, + u32::MAX, + (&raw const mask).cast(), + 0 + ), + S_OK + ); + for id in 1..=4 { + assert_eq!((m.submit)(acp, 12, id, u32::MAX, std::ptr::null(), 0), S_OK); + } + assert_eq!((m.message_count)(acp), 2); + let mut message = Message { + kind: 0, + dropped: 0, + usec: 0, + data: [0; 16], + }; + assert!((m.pop_message)(acp, &mut message) && (m.pop_message)(acp, &mut message)); + assert_eq!((m.submit)(acp, 12, 5, u32::MAX, std::ptr::null(), 0), S_OK); + assert!((m.pop_message)(acp, &mut message)); + let dropped = message.dropped; + assert_eq!(dropped, 2); + (m.release)(acp); + } + + #[test] + fn startup_as_fmod_does_it() { + let _serial = lock(&CONTEXT_TESTS); + // Context arrays: rate conversion, DMA and XMA. + let mut request = ShapeContexts { + counts: [0x200, 0, 0, 0x400, 0x200, 0], + arrays: [std::ptr::null_mut(); 6], + apu: [0; 6], + }; + assert_eq!(size_of::(), 0x60); + assert_eq!(AcpHalAllocateShapeContexts(&mut request), S_OK); + let arrays = request.arrays; + assert!(!arrays[0].is_null() && !arrays[3].is_null() && !arrays[4].is_null()); + assert!(arrays[1].is_null()); + // SAFETY: 0x200 rate-conversion contexts of 32 bytes were allocated. + unsafe { arrays[0].cast::().write_bytes(0, 0x200 << 5) }; + + // Connect, register every message but frame starts, then wait for + // the registration to be acknowledged. + let mut acp = std::ptr::null_mut(); + assert_eq!(AcpHalCreate(&mut acp), S_OK); + // SAFETY: just created. + let m = unsafe { (*acp).vtable }; + assert_eq!((m.connect)(acp, 0x804, 0x804), S_OK); + let mask = 0xfe_u32; + let data = (&raw const mask).cast(); + assert_eq!( + (m.submit)(acp, REGISTER_MESSAGES, 1, u32::MAX, data, 0), + S_OK + ); + let mut message = Message { + kind: 0, + dropped: 0, + usec: 0, + data: [0; 16], + }; + assert!((m.pop_message)(acp, &mut message)); + let (kind, dropped) = (message.kind, message.dropped); + assert_eq!((kind, dropped), (COMMAND_COMPLETED, 0)); + assert_eq!( + u64::from_le_bytes(message.data[4..12].try_into().unwrap()), + 1 + ); + assert!(!(m.pop_message)(acp, &mut message)); + assert_eq!((m.disconnect)(acp), S_OK); + assert_eq!((m.message_count)(acp), 1, "disconnected"); + (m.release)(acp); + assert_eq!(AcpHalReleaseShapeContexts(), S_OK); + } +} diff --git a/crates/leonida-hle/src/modules/audio/capture.rs b/crates/leonida-hle/src/modules/audio/capture.rs new file mode 100644 index 000000000..c637e5066 --- /dev/null +++ b/crates/leonida-hle/src/modules/audio/capture.rs @@ -0,0 +1,229 @@ +//! Debugging aid: `LEONIDA_AUDIO_CAPTURE=` records what the title +//! plays, 48 kHz stereo 16-bit, through process loopback: our own process +//! tree only, never the rest of the host's mix. Stretches where nothing was +//! played are written as silence, so the file keeps real time. +//! +//! The recorder runs in a child copy of this executable: an audio client +//! in the title's process raises that process's timer resolution, which +//! changes how the title's own waits behave. + +use std::fs::File; +use std::io::{Seek, SeekFrom, Write}; +use std::path::Path; +use std::time::{Duration, Instant}; + +use windows::Win32::Media::Audio::{ + AUDCLNT_BUFFERFLAGS_DATA_DISCONTINUITY, AUDCLNT_BUFFERFLAGS_SILENT, AUDCLNT_SHAREMODE_SHARED, + AUDCLNT_STREAMFLAGS_AUTOCONVERTPCM, AUDCLNT_STREAMFLAGS_LOOPBACK, + AUDIOCLIENT_ACTIVATION_PARAMS, AUDIOCLIENT_ACTIVATION_PARAMS_0, + AUDIOCLIENT_ACTIVATION_TYPE_PROCESS_LOOPBACK, AUDIOCLIENT_PROCESS_LOOPBACK_PARAMS, + ActivateAudioInterfaceAsync, IActivateAudioInterfaceAsyncOperation, + IActivateAudioInterfaceCompletionHandler, IActivateAudioInterfaceCompletionHandler_Impl, + IAudioCaptureClient, IAudioClient, PROCESS_LOOPBACK_MODE_INCLUDE_TARGET_PROCESS_TREE, + VIRTUAL_AUDIO_DEVICE_PROCESS_LOOPBACK, WAVE_FORMAT_PCM, WAVEFORMATEX, +}; +use windows::Win32::System::Com::{COINIT_MULTITHREADED, CoInitializeEx}; +use windows::Win32::Foundation::WAIT_OBJECT_0; +use windows::Win32::System::Threading::{ + OpenProcess, PROCESS_SYNCHRONIZE, Sleep, WaitForSingleObject, +}; +use windows::core::{HRESULT, IUnknown, Interface, Ref, implement}; + +const RATE: u32 = 48_000; +const FRAME_BYTES: usize = 4; + +/// Activation completes asynchronously; the recording thread polls for it. +#[implement(IActivateAudioInterfaceCompletionHandler)] +struct Activated; + +impl IActivateAudioInterfaceCompletionHandler_Impl for Activated_Impl { + fn ActivateCompleted( + &self, + _: Ref, + ) -> windows::core::Result<()> { + Ok(()) + } +} + +/// Names the process to record, in the recorder's environment. +const TARGET: &str = "LEONIDA_AUDIO_CAPTURE_OF"; + +/// Starts the recorder if `LEONIDA_AUDIO_CAPTURE` names a file. With this +/// module's debug log, also logs once a second what a `Sleep(1)` takes in +/// this process (the title's millisecond waits get the same). +pub fn start() { + if tracing::enabled!(tracing::Level::DEBUG) { + let _ = std::thread::Builder::new() + .name("leonida timing probe".into()) + .spawn(|| { + loop { + std::thread::sleep(Duration::from_secs(1)); + let at = Instant::now(); + // SAFETY: plain wait. + unsafe { Sleep(1) }; + let ms = at.elapsed().as_secs_f32() * 1000.0; + tracing::debug!(ms, "Sleep(1) took"); + } + }); + } + if std::env::var_os("LEONIDA_AUDIO_CAPTURE").is_some() + && let Err(e) = std::env::current_exe().and_then(|exe| { + std::process::Command::new(exe) + .env(TARGET, std::process::id().to_string()) + .spawn() + }) + { + tracing::warn!("audio capture not started: {e}"); + } +} + +/// In the recorder (a child started by [`start`]): records until the +/// target exits and returns true; false in any other process. +pub fn child() -> bool { + let (Some(pid), Some(path)) = ( + std::env::var(TARGET).ok().and_then(|p| p.parse().ok()), + std::env::var_os("LEONIDA_AUDIO_CAPTURE"), + ) else { + return false; + }; + if let Err(e) = record(pid, Path::new(&path)) { + tracing::warn!("audio capture stopped: {e}"); + } + true +} + +fn header(frames: u64) -> [u8; 44] { + let data = u32::try_from(frames * FRAME_BYTES as u64).unwrap_or(u32::MAX - 36); + let mut h = [0u8; 44]; + let fields: [(&[u8], usize); 11] = [ + (b"RIFF", 0), + (&(36 + data).to_le_bytes(), 4), + (b"WAVEfmt ", 8), + (&16u32.to_le_bytes(), 16), + (&1u16.to_le_bytes(), 20), + (&2u16.to_le_bytes(), 22), + (&RATE.to_le_bytes(), 24), + (&(RATE * FRAME_BYTES as u32).to_le_bytes(), 28), + (&(FRAME_BYTES as u16).to_le_bytes(), 32), + (&16u16.to_le_bytes(), 34), + (b"data", 36), + ]; + for (bytes, at) in fields { + h[at..at + bytes.len()].copy_from_slice(bytes); + } + h[40..].copy_from_slice(&data.to_le_bytes()); + h +} + +fn record(pid: u32, path: &Path) -> Result<(), Box> { + // SAFETY: COM calls with parameters built here; buffers are used only + // between `GetBuffer` and `ReleaseBuffer`. + unsafe { + CoInitializeEx(None, COINIT_MULTITHREADED).ok()?; + let target = OpenProcess(PROCESS_SYNCHRONIZE, false, pid)?; + let params = AUDIOCLIENT_ACTIVATION_PARAMS { + ActivationType: AUDIOCLIENT_ACTIVATION_TYPE_PROCESS_LOOPBACK, + Anonymous: AUDIOCLIENT_ACTIVATION_PARAMS_0 { + ProcessLoopbackParams: AUDIOCLIENT_PROCESS_LOOPBACK_PARAMS { + TargetProcessId: pid, + ProcessLoopbackMode: PROCESS_LOOPBACK_MODE_INCLUDE_TARGET_PROCESS_TREE, + }, + }, + }; + /// A `PROPVARIANT` holding a blob (`VT_BLOB`). + #[repr(C)] + struct Blob { + vt: u16, + reserved: [u16; 3], + size: u32, + data: *const AUDIOCLIENT_ACTIVATION_PARAMS, + } + let blob = Blob { + vt: 0x41, + reserved: [0; 3], + size: size_of_val(¶ms) as u32, + data: ¶ms, + }; + let handler: IActivateAudioInterfaceCompletionHandler = Activated.into(); + let operation = ActivateAudioInterfaceAsync( + VIRTUAL_AUDIO_DEVICE_PROCESS_LOOPBACK, + &IAudioClient::IID, + Some((&raw const blob).cast()), + &handler, + )?; + let client = loop { + let (mut hr, mut client) = (HRESULT(0), None::); + // Fails (`E_ILLEGAL_METHOD_CALL`) until activation completes. + if operation.GetActivateResult(&mut hr, &mut client).is_ok() { + hr.ok()?; + break client.ok_or("no audio client")?.cast::()?; + } + std::thread::sleep(Duration::from_millis(10)); + }; + let format = WAVEFORMATEX { + wFormatTag: WAVE_FORMAT_PCM as u16, + nChannels: 2, + nSamplesPerSec: RATE, + nAvgBytesPerSec: RATE * FRAME_BYTES as u32, + nBlockAlign: FRAME_BYTES as u16, + wBitsPerSample: 16, + cbSize: 0, + }; + client.Initialize( + AUDCLNT_SHAREMODE_SHARED, + AUDCLNT_STREAMFLAGS_LOOPBACK | AUDCLNT_STREAMFLAGS_AUTOCONVERTPCM, + 10_000_000, + 0, + &format, + None, + )?; + let capture: IAudioCaptureClient = client.GetService()?; + let mut file = File::create(path)?; + file.write_all(&header(0))?; + client.Start()?; + tracing::info!(path = %path.display(), "recording the title's audio"); + + let (mut written, mut first) = (0u64, None); + let mut patched = Instant::now(); + loop { + std::thread::sleep(Duration::from_millis(10)); + let ended = WaitForSingleObject(target, 0) == WAIT_OBJECT_0; + while capture.GetNextPacketSize()? > 0 { + let (mut data, mut frames, mut flags, mut qpc) = (std::ptr::null_mut(), 0, 0, 0); + capture.GetBuffer(&mut data, &mut frames, &mut flags, None, Some(&mut qpc))?; + // Where this packet belongs, from its time stamp (100 ns). + let at = (qpc - *first.get_or_insert(qpc)) * u64::from(RATE) / 10_000_000; + if at > written + u64::from(RATE / 500) { + tracing::debug!( + ms = (at - written) * 1000 / u64::from(RATE), + "audio capture: nothing played" + ); + let silence = vec![0u8; (at - written) as usize * FRAME_BYTES]; + file.write_all(&silence)?; + written = at; + } + let bytes = frames as usize * FRAME_BYTES; + if flags & AUDCLNT_BUFFERFLAGS_SILENT.0 as u32 != 0 { + file.write_all(&vec![0u8; bytes])?; + } else { + file.write_all(std::slice::from_raw_parts(data, bytes))?; + } + if flags & AUDCLNT_BUFFERFLAGS_DATA_DISCONTINUITY.0 as u32 != 0 && written > 0 { + tracing::debug!("audio capture: discontinuity"); + } + written += u64::from(frames); + capture.ReleaseBuffer(frames)?; + } + if ended || patched.elapsed() >= Duration::from_secs(1) { + // Valid sizes at any time: runs end by being killed. + file.seek(SeekFrom::Start(0))?; + file.write_all(&header(written))?; + file.seek(SeekFrom::End(0))?; + patched = Instant::now(); + } + if ended { + return Ok(()); + } + } + } +} diff --git a/crates/leonida-hle/src/modules/d3d12x.rs b/crates/leonida-hle/src/modules/d3d12x.rs new file mode 100644 index 000000000..8034912be --- /dev/null +++ b/crates/leonida-hle/src/modules/d3d12x.rs @@ -0,0 +1,121 @@ +//! `d3d12_xs.dll`: virtual memory setup, device creation, root signature +//! serialization. The device and everything it creates live in +//! `leonida-gpu`. + +use std::ffi::c_void; + +use leonida_gpu::device; +use leonida_gpu::object::{HRESULT, Iid, Object}; + +use crate::{HleExport, HleModule}; + +/// Device creation; first hands the device the title's general allocator +/// (`XMemAlloc`, which honours the title's hooks) for resource memory. +extern "system" fn create_device( + adapter: *const c_void, + parameters: *const u32, + iid: *const Iid, + out: *mut *const Object, +) -> HRESULT { + leonida_gpu::resource::use_allocator(super::xmem::XMemAlloc, super::xmem::XMemFree); + leonida_gpu::resource::use_page_mapper(super::xmem::map_alias); + #[cfg(windows)] + leonida_gpu::on_failure(host_gpu_failed); + device::create(adapter, parameters, iid, out) +} + +/// A host GPU failure ends the run like a crash: reported to the crash log, +/// then the process ends as the console ends a title. +#[cfg(windows)] +fn host_gpu_failed(what: &str) -> ! { + use windows_sys::Win32::System::Threading::{GetCurrentProcess, TerminateProcess}; + leonida_loader::log_crash(&format!("Leonida Legacy: host GPU failure: {what}")); + const DXGI_ERROR_DEVICE_REMOVED: u32 = 0x887A_0005; + // SAFETY: ends our own process. + unsafe { TerminateProcess(GetCurrentProcess(), DXGI_ERROR_DEVICE_REMOVED) }; + unreachable!("the process has ended") +} + +/// The offline warm-up: see `leonida_gpu::shader_cache::warm`. +pub fn warm_shader(container: &[u8]) -> Result { + #[cfg(windows)] + { + leonida_gpu::shader_cache::warm(container) + } + #[cfg(not(windows))] + { + let _ = container; + Err("no shader cache on this host".into()) + } +} + +/// Keeps the host's translations of the title's shaders in `dir` (a +/// folder of the cache) across runs, and its compiled pipelines beside it +/// (`pipelines`). +pub fn use_shader_cache(dir: std::path::PathBuf) { + #[cfg(windows)] + { + leonida_gpu::pipeline::use_pipeline_cache(dir.with_file_name("pipelines")); + leonida_gpu::shader_cache::use_shader_cache(dir); + } + #[cfg(not(windows))] + let _ = dir; +} + +pub(crate) fn module() -> HleModule { + HleModule { + name: "d3d12x", + dlls: &["d3d12_xs.dll"], + exports: vec![ + HleExport { + name: "D3D12ConfigureVirtualMemoryX", + address: device::configure_virtual_memory as *const () as usize, + }, + HleExport { + name: "D3D12XboxCreateDevice", + address: create_device as *const () as usize, + }, + HleExport { + name: "D3D12SerializeRootSignature", + address: leonida_gpu::root::serialize as *const () as usize, + }, + HleExport { + name: "D3D12SerializeVersionedRootSignature", + address: leonida_gpu::root::serialize_versioned as *const () as usize, + }, + // The AMD upscaler's (Series S). + HleExport { + name: "D3D12CreateRootSignatureDeserializer", + address: leonida_gpu::root::create_deserializer as *const () as usize, + }, + // A data import: the title reads the id at this address. + HleExport { + name: "IID_ID3D12Device", + address: (&raw const device::IID) as usize, + }, + ], + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::{HleResolver, HostPolicy}; + use leonida_loader::ImportResolver; + use leonida_loader::Resolution; + use leonida_pe::ImportSymbol; + + #[test] + fn the_interface_id_import_is_bound_to_data() { + let symbol = ImportSymbol::Name { + hint: 0, + name: "IID_ID3D12Device".into(), + }; + let r = HleResolver::new(HostPolicy::none()); + let Resolution::Found { address, .. } = r.resolve("d3d12_xs.dll", &symbol) else { + panic!("not bound"); + }; + // SAFETY: the address is our static id. + assert_eq!(unsafe { *(address as *const [u8; 16]) }, device::IID); + } +} diff --git a/crates/leonida-hle/src/modules/display.rs b/crates/leonida-hle/src/modules/display.rs new file mode 100644 index 000000000..99798a5c4 --- /dev/null +++ b/crates/leonida-hle/src/modules/display.rs @@ -0,0 +1,195 @@ +//! The display and what the system shell does for a title: HDR mode, screen +//! timeout deferrals, launching URIs, screenshots. +#![allow(clippy::not_unsafe_ptr_arg_deref)] + +use std::ffi::{c_char, c_void}; + +use super::xgameruntime::{ + Guid, HRESULT, Interface, Methods, NOT_SUPPORTED, Object, add_ref, missing, put, text, +}; + +/// HDR mode; asked for with this interface id since 2020. +pub const HDR_PROVIDER: Guid = Guid::new( + 0x03f0_fe74, + 0xfdd9, + 0x4e5c, + [0xb6, 0x30, 0xf9, 0x33, 0x9c, 0x47, 0xac, 0xc5], +); +pub const HDR_IID: Guid = Guid::new( + 0x35f0_7670, + 0x706e, + 0x4bfb, + [0x94, 0x76, 0x09, 0x07, 0x98, 0xc5, 0xeb, 0xf3], +); +/// Launching URIs and screen timeout deferrals; the interface id is the +/// provider's. +pub const SHELL: Guid = Guid::new( + 0x1b33_9674, + 0x328d, + 0x4283, + [0xa2, 0x00, 0x31, 0x71, 0xf1, 0x8d, 0x36, 0x39], +); +/// Screenshots and clips. +pub const CAPTURE_PROVIDER: Guid = Guid::new( + 0xa4f1_aee2, + 0x4bf1, + 0x4485, + [0xb0, 0x08, 0xa7, 0xc2, 0x6d, 0x52, 0xac, 0x27], +); +/// As the title (2026) asks for it; it calls 0x28 (take a +/// screenshot) with the public API's arguments. +pub const CAPTURE_IID_2026: Guid = Guid::new( + 0x22e6_72d7, + 0xb4e3, + 0x406c, + [0xbd, 0x50, 0x8f, 0x0d, 0x25, 0x23, 0x6f, 0x9e], +); + +pub static HDR_OBJECT: Object = Object::new("hdr", &HDR_VTABLE); +pub static SHELL_OBJECT: Object = Object::new("shell", &SHELL_VTABLE); +pub static CAPTURE_OBJECT: Object = Object::new("capture", &CAPTURE_VTABLE); + +pub const INTERFACES: &[Interface] = &[ + (HDR_PROVIDER, HDR_IID, &HDR_OBJECT), + (SHELL, SHELL, &SHELL_OBJECT), + (CAPTURE_PROVIDER, CAPTURE_IID_2026, &CAPTURE_OBJECT), +]; + +type This = *const Object; + +/// 2: disabled. We present in SDR, so the title must render SDR. +// shortcut: HDR output is not done (see the presentation items in +// `TODO.md`); report enabled, with the host display's luminance, once the +// swap chain can present HDR. +extern "system" fn try_enable_hdr(_: This, preference: u32, _info: *mut c_void) -> u32 { + tracing::info!(preference, "HDR mode: disabled (SDR presentation)"); + 2 +} + +/// Nothing launches URIs for the title: no store, browser or console app +/// exists here, and the console's are online services. +extern "system" fn launch_uri(_: This, _user: *const c_void, uri: *const c_char) -> HRESULT { + tracing::info!(uri = text(uri).unwrap_or_default(), "URI not launched"); + NOT_SUPPORTED +} + +/// A deferral keeps the host display on, as on the console, through a +/// power request; the handle is that request. +#[cfg(windows)] +extern "system" fn acquire_deferral(_: This, out: *mut *mut c_void) -> HRESULT { + use windows_sys::Win32::System::Power::{ + PowerCreateRequest, PowerRequestDisplayRequired, PowerSetRequest, + }; + use windows_sys::Win32::System::Threading::{ + POWER_REQUEST_CONTEXT_SIMPLE_STRING, REASON_CONTEXT, + }; + if out.is_null() { + return super::xasync::E_INVALIDARG; + } + let mut reason: Vec = "Title display deferral\0".encode_utf16().collect(); + let mut context = REASON_CONTEXT { + Flags: POWER_REQUEST_CONTEXT_SIMPLE_STRING, + ..Default::default() + }; + context.Reason.SimpleReasonString = reason.as_mut_ptr(); + // SAFETY: a valid context; the string is copied by the call. + let request = unsafe { PowerCreateRequest(&context) }; + if request as isize == -1 { + return last_error(); + } + // SAFETY: the request we just created. + if unsafe { PowerSetRequest(request, PowerRequestDisplayRequired) } == 0 { + let hr = last_error(); + // SAFETY: as above; not handed out. + unsafe { windows_sys::Win32::Foundation::CloseHandle(request) }; + return hr; + } + put(out, request) +} + +#[cfg(windows)] +extern "system" fn close_deferral(_: This, handle: *mut c_void) { + use windows_sys::Win32::Foundation::CloseHandle; + use windows_sys::Win32::System::Power::{PowerClearRequest, PowerRequestDisplayRequired}; + if !handle.is_null() { + // SAFETY: a request from `acquire_deferral`. + unsafe { + PowerClearRequest(handle, PowerRequestDisplayRequired); + CloseHandle(handle); + } + } +} + +#[cfg(windows)] +fn last_error() -> HRESULT { + // SAFETY: no preconditions. + let code = unsafe { windows_sys::Win32::Foundation::GetLastError() }; + (0x8007_0000 | (code & 0xffff)) as i32 +} + +// shortcut: screenshots fail as if capture were unavailable. Taking one needs +// a hook in the GPU side: the last presented frame read back as BGRA8 (size, +// row pitch, bytes) on request, e.g. `leonida_gpu::last_frame() -> +// Option`, copied from the back buffer after `PresentX`. +extern "system" fn take_screenshot(_: This, _user: *const c_void, _result: *mut c_void) -> HRESULT { + tracing::info!("screenshot not taken"); + NOT_SUPPORTED +} + +static HDR_VTABLE: Methods<5> = Methods([ + missing::<0> as *const (), + add_ref as *const (), + add_ref as *const (), + missing::<3> as *const (), + try_enable_hdr as *const (), // 0x20 +]); + +#[cfg(windows)] +static SHELL_VTABLE: Methods<6> = Methods([ + missing::<0> as *const (), + add_ref as *const (), + add_ref as *const (), + launch_uri as *const (), // 0x18 + acquire_deferral as *const (), // 0x20 + close_deferral as *const (), // 0x28 +]); +#[cfg(not(windows))] +static SHELL_VTABLE: Methods<4> = Methods([ + missing::<0> as *const (), + add_ref as *const (), + add_ref as *const (), + launch_uri as *const (), +]); + +static CAPTURE_VTABLE: Methods<6> = Methods([ + missing::<0> as *const (), + add_ref as *const (), + add_ref as *const (), + missing::<3> as *const (), // 0x18 diagnostic screenshot + missing::<4> as *const (), // 0x20 diagnostic clip + take_screenshot as *const (), // 0x28 +]); + +#[cfg(all(test, windows))] +mod tests { + use super::*; + use crate::modules::xgameruntime::{S_OK, method}; + + #[test] + fn sdr_and_display_deferrals() { + type Hdr = extern "system" fn(This, u32, *mut c_void) -> u32; + assert_eq!( + method::(&HDR_OBJECT, 0x20)(&HDR_OBJECT, 0, std::ptr::null_mut()), + 2 + ); + type Acquire = extern "system" fn(This, *mut *mut c_void) -> HRESULT; + type Close = extern "system" fn(This, *mut c_void); + let mut handle = std::ptr::null_mut(); + assert_eq!( + method::(&SHELL_OBJECT, 0x20)(&SHELL_OBJECT, &mut handle), + S_OK + ); + assert!(!handle.is_null()); + method::(&SHELL_OBJECT, 0x28)(&SHELL_OBJECT, handle); + } +} diff --git a/crates/leonida-hle/src/modules/dsp.rs b/crates/leonida-hle/src/modules/dsp.rs new file mode 100644 index 000000000..87c456aed --- /dev/null +++ b/crates/leonida-hle/src/modules/dsp.rs @@ -0,0 +1,314 @@ +//! The console's audio DSP (`chad.dll`): streams that convolve blocks of +//! float samples with an impulse response (reverb), or run other block +//! transforms, on a coprocessor. +//! +//! A title connects once with a memory block for the DSP, activates +//! streams, and submits one command per block (gains, an input and an +//! output buffer). Activation hands back a status block whose second word is +//! the ticket of the last completed command and whose fourth is its result; +//! the title checks it one block later and treats a late command as an +//! overrun. Commands complete when submitted here. +//! +//! The transforms themselves are not computed: the hardware takes impulse +//! responses already in its own partitioned frequency-domain layout, which +//! is not known. Outputs are silence, so reverb returns are dry. +// shortcut: no convolution or block transform; outputs are zeros. Needs the +// coprocessor's impulse response and spectrum layouts to do better. +#![allow(non_snake_case)] +#![allow(clippy::not_unsafe_ptr_arg_deref)] + +use std::ffi::c_void; +use std::sync::Mutex; + +use super::xasync::E_INVALIDARG; +use super::xgameruntime::{HRESULT, S_OK}; +use crate::{HleModule, hle_export}; + +const E_POINTER: HRESULT = 0x8000_4003_u32 as i32; +const E_OUTOFMEMORY: HRESULT = 0x8007_000E_u32 as i32; + +const CONVOLUTION: u32 = 1; +/// Option bits that need a stereo stream, and one convolution refuses. +const STEREO_OPTIONS: u32 = 2 | 8; +const NOT_FOR_CONVOLUTION: u32 = 4; + +pub struct Dsp { + max_streams: u32, + active: Mutex, +} + +/// What activation describes. +#[repr(C, packed)] +pub struct StreamDesc { + kind: u32, + options: u32, + frames: u32, + channels: u32, + ir_floats: u32, + ir: *const f32, +} + +/// The status block a stream's owner polls. +#[repr(C)] +pub struct Status { + submitted: u32, + completed: u32, + reserved: u32, + result: HRESULT, +} + +pub struct Stream { + dsp: *mut Dsp, + frames: u32, + channels: u32, + status: Box, +} + +/// One block of work. +#[repr(C)] +pub struct Command { + gains: [f32; 2], + input: *const f32, + output: *mut f32, + reserved: u64, +} + +pub extern "system" fn XDspConnectWithMaximumStreamLimit( + base: *mut c_void, + base_length: u32, + ir_seconds: u32, + max_streams: u32, + max_channels: u32, + out: *mut *mut Dsp, +) -> HRESULT { + if base.is_null() + || !(0x1_0000..=0x1F40_0000).contains(&base_length) + || ir_seconds > 0x80 + || max_streams > 0x100 + || max_channels > 2 + { + return E_INVALIDARG; + } + if out.is_null() { + return E_POINTER; + } + tracing::info!( + base_length, + ir_seconds, + max_streams, + max_channels, + "audio DSP connected" + ); + let dsp = Box::new(Dsp { + max_streams, + active: Mutex::new(0), + }); + // SAFETY: checked non-null. + unsafe { out.write(Box::into_raw(dsp)) }; + S_OK +} + +pub extern "system" fn XDspDisconnect(dsp: *mut Dsp) -> HRESULT { + if dsp.is_null() { + return E_INVALIDARG; + } + // SAFETY: made by `XDspConnectWithMaximumStreamLimit`; disconnected + // once, after its streams. + drop(unsafe { Box::from_raw(dsp) }); + S_OK +} + +fn valid(desc: &StreamDesc) -> bool { + let (kind, options, frames, channels) = (desc.kind, desc.options, desc.frames, desc.channels); + let shape = if kind == CONVOLUTION { + (1..=2).contains(&channels) + && matches!(frames, 0x200 | 0x400) + && options & NOT_FOR_CONVOLUTION == 0 + } else { + channels == 1 && matches!(frames, 0x200 | 0x400 | 0x800) + }; + shape && (options & STEREO_OPTIONS == 0 || channels == 2) +} + +pub extern "system" fn XDspActivate( + dsp: *mut Dsp, + desc: *const StreamDesc, + status: *mut *const Status, + stream: *mut *mut Stream, +) -> HRESULT { + if status.is_null() || stream.is_null() { + return E_POINTER; + } + if dsp.is_null() || desc.is_null() { + return E_INVALIDARG; + } + // SAFETY: checked non-null; the title passes its description. + let desc = unsafe { &*desc }; + if !valid(desc) { + return E_INVALIDARG; + } + let (kind, options, frames, channels) = (desc.kind, desc.options, desc.frames, desc.channels); + tracing::debug!( + kind, + options, + frames, + channels, + "audio DSP stream activated" + ); + { + // SAFETY: a connection from `XDspConnectWithMaximumStreamLimit`. + let dsp = unsafe { &*dsp }; + let mut active = dsp.active.lock().unwrap_or_else(|e| e.into_inner()); + if *active >= dsp.max_streams { + return E_OUTOFMEMORY; + } + *active += 1; + } + let new = Box::new(Stream { + dsp, + frames: desc.frames, + channels: desc.channels, + status: Box::new(Status { + submitted: 0, + completed: 0, + reserved: 0, + result: S_OK, + }), + }); + // SAFETY: checked non-null. + unsafe { + status.write(&*new.status); + stream.write(Box::into_raw(new)); + } + S_OK +} + +pub extern "system" fn XDspDeactivate(stream: *mut Stream) -> HRESULT { + if stream.is_null() { + return E_INVALIDARG; + } + // SAFETY: made by `XDspActivate`; deactivated once. + let stream = unsafe { Box::from_raw(stream) }; + // SAFETY: the connection outlives its streams. + let dsp = unsafe { &*stream.dsp }; + *dsp.active.lock().unwrap_or_else(|e| e.into_inner()) -= 1; + S_OK +} + +/// Completes the command at once: its output block is silence. +pub extern "system" fn XDspSubmitCommand( + stream: *mut Stream, + command: *const Command, + ticket: *mut u32, +) -> HRESULT { + if stream.is_null() || command.is_null() { + return E_INVALIDARG; + } + // SAFETY: a stream from `XDspActivate`, the title's command. + let (stream, command) = unsafe { (&mut *stream, &*command) }; + if !command.output.is_null() { + let samples = (stream.frames * stream.channels) as usize; + // SAFETY: the title's output buffer holds one block of the stream. + unsafe { std::ptr::write_bytes(command.output, 0, samples) }; + } + let status = &mut *stream.status; + let next = status.submitted.wrapping_add(1); + // SAFETY: the status block is read by title code on other threads. + unsafe { + std::ptr::write_volatile(&mut status.submitted, next); + std::ptr::write_volatile(&mut status.result, S_OK); + std::ptr::write_volatile(&mut status.completed, next); + } + if !ticket.is_null() { + // SAFETY: optional out parameter. + unsafe { ticket.write(next) }; + } + S_OK +} + +pub(crate) fn module() -> HleModule { + HleModule { + name: "dsp", + dlls: &["chad.dll"], + exports: vec![ + hle_export!(XDspConnectWithMaximumStreamLimit), + hle_export!(XDspDisconnect), + hle_export!(XDspActivate), + hle_export!(XDspDeactivate), + hle_export!(XDspSubmitCommand), + ], + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn convolution_stream_as_the_title_drives_it() { + let mut base = vec![0u8; 0x10_0000]; + let mut dsp = std::ptr::null_mut(); + assert_eq!( + XDspConnectWithMaximumStreamLimit( + base.as_mut_ptr().cast(), + 0x10_0000, + 24, + 0x80, + 1, + &mut dsp + ), + S_OK + ); + let ir = vec![0f32; 0x800]; + // Stereo convolution with option 2, as the title asks for. + let desc = StreamDesc { + kind: CONVOLUTION, + options: 2, + frames: 0x400, + channels: 2, + ir_floats: 0x800, + ir: ir.as_ptr(), + }; + let (mut status, mut stream) = (std::ptr::null(), std::ptr::null_mut()); + assert_eq!(XDspActivate(dsp, &desc, &mut status, &mut stream), S_OK); + let mut output = vec![1f32; 0x800]; + let input = vec![0.5f32; 0x800]; + let command = Command { + gains: [1.0, 1.0], + input: input.as_ptr(), + output: output.as_mut_ptr(), + reserved: 0, + }; + let mut ticket = 0; + assert_eq!(XDspSubmitCommand(stream, &command, &mut ticket), S_OK); + // SAFETY: the stream's status block. + let (completed, result) = unsafe { ((*status).completed, (*status).result) }; + assert_eq!((completed, result), (ticket, S_OK)); + assert!(output.iter().all(|&s| s == 0.0)); + assert_eq!(XDspDeactivate(stream), S_OK); + + // Mono streams refuse stereo options; transforms are mono only. + let bad = StreamDesc { + channels: 1, + ..desc + }; + assert_eq!( + XDspActivate(dsp, &bad, &mut status, &mut stream), + E_INVALIDARG + ); + let transform = StreamDesc { + kind: 2, + options: 0, + channels: 1, + ir_floats: 0, + ir: std::ptr::null(), + ..desc + }; + assert_eq!( + XDspActivate(dsp, &transform, &mut status, &mut stream), + S_OK + ); + assert_eq!(XDspDeactivate(stream), S_OK); + assert_eq!(XDspDisconnect(dsp), S_OK); + } +} diff --git a/crates/leonida-hle/src/modules/dstorage.rs b/crates/leonida-hle/src/modules/dstorage.rs new file mode 100644 index 000000000..aaf25d8b4 --- /dev/null +++ b/crates/leonida-hle/src/modules/dstorage.rs @@ -0,0 +1,1797 @@ +//! The console's DirectStorage (`XCRDAPI.dll`): a factory that opens files +//! and creates request queues and status arrays the title polls. Its +//! interfaces have grown since 2020 (new interface ids, new slots); the +//! slots here are the ones the title calls, read from its call +//! sites. Slots nobody has needed yet log their offset. +//! +//! Submitted requests of every queue run on one pool of workers, as the +//! console's hardware runs them: in parallel, started in queue order, +//! queues served by weighted round robin over their priorities (about 10x +//! per level, counted in bytes), with at most the staging buffer's worth of +//! compressed source in flight. Each request reads its source (a file or +//! memory), inflates zlib data and/or unpacks BCPack data, and writes the +//! destination (an address, or physical pages). Completion is what stays +//! in order: a status entry is written once every request enqueued before +//! it on its queue has finished, with the first failure (in queue order) +//! since the previous status entry, or success. +#![allow(non_snake_case)] +#![allow(clippy::not_unsafe_ptr_arg_deref)] + +use std::borrow::Cow; +use std::collections::{BTreeMap, BTreeSet, HashMap, VecDeque}; +use std::ffi::{CStr, c_char, c_void}; +use std::os::windows::fs::FileExt; +use std::os::windows::io::FromRawHandle; +use std::sync::atomic::{AtomicBool, AtomicI32, AtomicU32, AtomicU64, Ordering}; +use std::sync::{Condvar, Mutex, MutexGuard, OnceLock}; + +use leonida_formats::bcpack::{self, Tables}; + +use super::xasync::{E_INVALIDARG, E_NOTIMPL, E_PENDING}; +use super::xgameruntime::{Guid, HRESULT, Methods, Object, S_OK, add_ref, missing, put}; +use crate::{HleModule, hle_export}; + +/// The factory interface the title asks for. +const FACTORY: Guid = Guid::new( + 0x6295_9d11, + 0xd45f, + 0x4884, + [0xa0, 0xa3, 0xf7, 0x86, 0x2e, 0xa2, 0x43, 0xae], +); +const E_NOINTERFACE: HRESULT = 0x8000_4002_u32 as i32; +const E_OUTOFMEMORY: HRESULT = 0x8007_000E_u32 as i32; +/// `HRESULT_FROM_WIN32(ERROR_HANDLE_EOF)`: the source ends early. +const END_OF_FILE: HRESULT = 0x8007_0026_u32 as i32; +/// `HRESULT_FROM_WIN32(ERROR_INVALID_DATA)`: a bad compressed stream. +const INVALID_DATA: HRESULT = 0x8007_000D_u32 as i32; + +type Out = *mut *mut c_void; + +static FACTORY_OBJECT: Object = Object::new("dstorage factory", &FACTORY_VTABLE); + +pub extern "system" fn DStorageGetFactory(iid: *const Guid, out: Out) -> HRESULT { + // SAFETY: the title passes a GUID (null tolerated). + match unsafe { iid.as_ref() } { + Some(&iid) if iid == FACTORY => { + put(out, std::ptr::from_ref(&FACTORY_OBJECT).cast_mut().cast()) + } + iid => { + tracing::warn!(iid = ?iid.map(Guid::to_string), "DStorageGetFactory: unknown interface"); + E_NOINTERFACE + } + } +} + +/// One of our objects with state: the runtime's object header (method +/// table first), a reference count, then `T`. +#[repr(C)] +struct Instance { + base: Object, + refs: AtomicU32, + state: T, +} + +impl Instance { + fn create(base: Object, state: T) -> *mut c_void { + Box::into_raw(Box::new(Instance { + base, + refs: AtomicU32::new(1), + state, + })) + .cast() + } +} + +extern "system" fn add_ref_instance(this: *const Instance) -> u32 { + // SAFETY: an instance we created and the title still holds. + unsafe { &*this }.refs.fetch_add(1, Ordering::Relaxed) + 1 +} + +extern "system" fn release(this: *mut Instance) -> u32 { + // SAFETY: as above. + let left = unsafe { &*this }.refs.fetch_sub(1, Ordering::AcqRel) - 1; + if left == 0 { + // SAFETY: the last reference; created by `Instance::create`. + drop(unsafe { Box::from_raw(this) }); + } + left +} + +fn iid_text(iid: *const Guid) -> String { + // SAFETY: the title passes a GUID (null tolerated). + unsafe { iid.as_ref() }.map_or_else(|| "null".into(), Guid::to_string) +} + +/// `HRESULT_FROM_WIN32` of a host error. +fn from_win32(error: &std::io::Error) -> HRESULT { + error + .raw_os_error() + .map_or(E_INVALIDARG, |e| (0x8007_0000 | (e as u32 & 0xffff)) as i32) +} + +// The factory. + +type Factory = *const Object; + +/// Opens `path` for reading; the file object owns the handle. +extern "system" fn open_file(_: Factory, path: *const u16, iid: *const Guid, out: Out) -> HRESULT { + const GENERIC_READ: u32 = 0x8000_0000; + const FILE_SHARE_READ: u32 = 1; + const OPEN_EXISTING: u32 = 3; + if path.is_null() { + return E_INVALIDARG; + } + // Goes through `files`, so paths on our virtual drives work too. + let handle = super::files::CreateFileW( + path, + GENERIC_READ, + FILE_SHARE_READ, + std::ptr::null(), + OPEN_EXISTING, + 0, + std::ptr::null_mut(), + ); + // SAFETY: the title passes a NUL-terminated path. + let name = unsafe { + let len = (0..).take_while(|&i| *path.add(i) != 0).count(); + String::from_utf16_lossy(std::slice::from_raw_parts(path, len)) + }; + if handle as isize == -1 { + let error = std::io::Error::last_os_error(); + tracing::warn!(path = name, %error, "dstorage: opening a file failed"); + return from_win32(&error); + } + let kept = name.clone(); + tracing::info!(path = name, iid = iid_text(iid), "dstorage: file opened"); + // SAFETY: a handle we just opened and nobody else owns. + let file = unsafe { std::fs::File::from_raw_handle(handle) }; + let file = Instance::create(Object::new("dstorage file", &FILE_VTABLE), File { file }); + WALLS_FILES.lock().unwrap_or_else(|e| e.into_inner()).push((file as usize, kept)); + put(out, file) +} + +/// `(capacity, name, iid, out)`. +extern "system" fn create_status_array( + _: Factory, + capacity: u32, + name: *const c_char, + iid: *const Guid, + out: Out, +) -> HRESULT { + tracing::info!( + capacity, + name = text(name), + iid = iid_text(iid), + "dstorage: status array" + ); + let entries = (0..capacity).map(|_| AtomicI32::new(S_OK)).collect(); + let array = Instance::create( + Object::new("dstorage status array", &STATUS_VTABLE), + StatusArray { entries }, + ); + put(out, array) +} + +/// The queue's description: as in 2020 (source type, capacity, priority, +/// name), plus a field the title sets to 1. +#[repr(C)] +struct QueueDesc { + source_type: u64, + capacity: u16, + priority: i8, + name: *const c_char, + unknown: u64, +} + +extern "system" fn create_queue( + _: Factory, + desc: *const QueueDesc, + iid: *const Guid, + out: Out, +) -> HRESULT { + // SAFETY: the title passes its description (null tolerated). + let Some(desc) = (unsafe { desc.as_ref() }) else { + return E_INVALIDARG; + }; + let name = text(desc.name); + tracing::info!( + source = desc.source_type, + capacity = desc.capacity, + priority = desc.priority, + name, + unknown = desc.unknown, + iid = iid_text(iid), + "dstorage: queue" + ); + let Some(scheduler) = scheduler() else { + return E_OUTOFMEMORY; + }; + let mut lanes = scheduler.lock(); + let id = lanes.next_id; + lanes.next_id += 1; + let lane = Lane::new(desc.priority, desc.capacity); + lanes.lanes.insert(id, lane); + drop(lanes); + put( + out, + Instance::create(Object::new("dstorage queue", &QUEUE_VTABLE), Queue { id }), + ) +} + +/// The title asks for 32 MiB and stops if this fails. +extern "system" fn set_staging_buffer_size(_: Factory, size: u32) -> HRESULT { + tracing::info!(size, "dstorage: staging buffer size"); + if let Some(scheduler) = scheduler() { + scheduler.lock().staging = u64::from(size); + } + S_OK +} + +fn text(name: *const c_char) -> String { + if name.is_null() { + return String::new(); + } + // SAFETY: a NUL-terminated name from the title. + unsafe { CStr::from_ptr(name) } + .to_string_lossy() + .into_owned() +} + +static FACTORY_VTABLE: Methods<16> = Methods([ + missing::<0> as *const (), + add_ref as *const (), + add_ref as *const (), + missing::<3> as *const (), // 0x18 (2020: queue creation) + open_file as *const (), // 0x20 + create_status_array as *const (), // 0x28 + missing::<6> as *const (), // 0x30 (2020: CPU affinity) + missing::<7> as *const (), // 0x38 (2020: debug flags) + set_staging_buffer_size as *const (), // 0x40 + missing::<9> as *const (), + create_queue as *const (), // 0x50 + missing::<11> as *const (), + missing::<12> as *const (), + missing::<13> as *const (), + missing::<14> as *const (), + missing::<15> as *const (), +]); + +// Files. + +struct File { + file: std::fs::File, +} + +static FILE_VTABLE: Methods<8> = Methods([ + missing::<0> as *const (), + add_ref_instance:: as *const (), + release:: as *const (), + missing::<3> as *const (), + missing::<4> as *const (), + missing::<5> as *const (), + missing::<6> as *const (), + missing::<7> as *const (), +]); + +// Status arrays. + +struct StatusArray { + entries: Box<[AtomicI32]>, +} + +type Array = *mut Instance; + +/// The result of the requests before entry `index`: pending, the first +/// failure, or success. +extern "system" fn status_result(this: Array, index: u32) -> HRESULT { + // SAFETY: an array we created and the title still holds. + let entries = &unsafe { &*this }.state.entries; + entries + .get(index as usize) + .map_or(E_INVALIDARG, |e| e.load(Ordering::Acquire)) +} + +/// The title polls this (entry 0, a `Sleep(1)` loop) and never +/// reads the result itself. +extern "system" fn is_complete(this: Array, index: u32) -> bool { + status_result(this, index) != E_PENDING +} + +static STATUS_VTABLE: Methods<5> = Methods([ + missing::<0> as *const (), + add_ref_instance:: as *const (), + release:: as *const (), + is_complete as *const (), // 0x18 + status_result as *const (), // 0x20 +]); + +// Queues. + +/// A queue object: its lane in the scheduler. +struct Queue { + id: u64, +} + +impl Drop for Queue { + fn drop(&mut self) { + close_lane(self.id); + } +} + +type QueueRef = *const Instance; + +/// Every queue's requests, run by a pool of workers. +struct Scheduler { + lanes: Mutex, + /// Requests to start, or staging space freed. + work: Condvar, + /// A request finished (for full queues and `close`). + finished: Condvar, +} + +/// Priority weights per class (low, normal, high and real-time), as the +/// console's: about 10x per level, counted against request sizes. +const COST: [u64; 3] = [100, 10, 1]; +/// The console's default staging buffer. +const STAGING: u64 = 32 << 20; + +struct Lanes { + lanes: HashMap, + next_id: u64, + /// Submission order over all queues. + next_seq: u64, + /// Bytes of staging held by running requests, and the limit. + staged: u64, + staging: u64, + /// A start waited for staging space since the last finish. + starved: bool, + /// Weighted round robin: each class's virtual time (bytes × cost), and + /// the time of the last start; within a class, the lane clock of the + /// last start. + clock: [u64; 3], + now: u64, + lane_now: [u64; 3], + /// Since the last debug summary: requests, bytes written, time spent + /// running them. + done: (u64, u64, std::time::Duration), + refused: u64, + /// BCPack bytes written and time spent on them. + bcpack: (u64, std::time::Duration), + since: Option, +} + +/// A queue's requests in the scheduler. +struct Lane { + class: usize, + capacity: usize, + /// Bytes started, for round robin among the lanes of a class. + clock: u64, + /// Enqueued, not yet submitted. + unsubmitted: Vec, + /// Submitted, by sequence number: reads not started, status entries + /// not written, reads running, and failures not yet reported. + reads: VecDeque<(u64, Request)>, + statuses: VecDeque<(u64, Status)>, + running: BTreeSet, + failures: BTreeMap, + closed: bool, +} + +// SAFETY: requests point into title memory and our own objects, which stay +// valid until the title has seen them complete; status arrays count their +// references atomically. +unsafe impl Send for Lane {} + +/// A read a worker runs. +struct Job { + lane: u64, + seq: u64, + request: Request, + staging: u64, +} + +// SAFETY: as for `Lane`. +unsafe impl Send for Job {} + +/// The scheduler, with its workers started on first use; `None` if not +/// even one worker could start. +fn scheduler() -> Option<&'static Scheduler> { + static SCHEDULER: OnceLock> = OnceLock::new(); + static STARTED: std::sync::Once = std::sync::Once::new(); + let scheduler = SCHEDULER + .get_or_init(|| { + Some(Scheduler { + lanes: Mutex::new(Lanes { + lanes: HashMap::new(), + next_id: 0, + next_seq: 0, + staged: 0, + staging: STAGING, + starved: false, + clock: [0; 3], + now: 0, + lane_now: [0; 3], + done: Default::default(), + refused: 0, + bcpack: Default::default(), + since: None, + }), + work: Condvar::new(), + finished: Condvar::new(), + }) + }) + .as_ref()?; + STARTED.call_once(|| { + let workers = std::thread::available_parallelism().map_or(4, |n| n.get()); + let started = (0..workers) + .filter(|i| { + std::thread::Builder::new() + .name(format!("dstorage {i}")) + .spawn(|| work(scheduler)) + .is_ok() + }) + .count(); + tracing::info!(workers = started, "dstorage: workers"); + }); + Some(scheduler) +} + +impl Scheduler { + fn lock(&self) -> MutexGuard<'_, Lanes> { + self.lanes.lock().unwrap_or_else(|e| e.into_inner()) + } +} + +/// The walls trace (`LEONIDA_WALLS_TRACE`): 0 or unset: off; 1: a line for +/// every read request that fails, with its file; 2: for every request (the +/// list of a launch's reads, by file and offset, is what a launch with the +/// first room's walls and one without are compared by). +fn walls_trace() -> u8 { + static ON: OnceLock = OnceLock::new(); + *ON.get_or_init(|| { + std::env::var("LEONIDA_WALLS_TRACE").ok().and_then(|v| v.trim().parse::().ok()).unwrap_or(0) + }) +} + +/// The files opened, by the address of our file object, with their paths +/// (for the walls trace: a request names its file by that address). +static WALLS_FILES: Mutex> = Mutex::new(Vec::new()); + +/// The walls trace's line for a request that is done. +fn walls_request(request: &Request, result: &Result<(), HRESULT>, started: std::time::Instant) { + let level = walls_trace(); + if level == 0 || (level == 1 && result.is_ok()) { + return; + } + let file = if request.options & MEMORY_SOURCE != 0 { + "memory".to_string() + } else { + let files = WALLS_FILES.lock().unwrap_or_else(|e| e.into_inner()); + let source = request.source as usize; + files.iter().find(|f| f.0 == source).map_or_else(|| "?".to_string(), |f| f.1.clone()) + }; + let hr = match result { + Ok(()) => 0, + Err(hr) => *hr as u32, + }; + tracing::info!( + file, + offset = request.offset, + source_size = request.source_size, + destination_size = request.destination_size, + to_pages = request.options & PAGE_DESTINATION != 0, + options = format_args!("{:#x}", request.options), + ms = started.elapsed().as_millis() as u64, + ok = result.is_ok(), + hr = format_args!("{hr:#010x}"), + "walls trace: a read request is done" + ); +} + +/// A worker: runs the next read of the most deserving queue. +fn work(scheduler: &'static Scheduler) { + // `LEONIDA_DISK_CORES=slow`: the workers leave the fast cores to the + // title's threads (`leonida_gpu::framelog::keep_on_slow_cores`; off by + // default until it is measured). + #[cfg(windows)] + { + static SLOW: OnceLock = OnceLock::new(); + if *SLOW.get_or_init(|| std::env::var_os("LEONIDA_DISK_CORES").is_some_and(|v| v == "slow")) { + leonida_gpu::framelog::keep_on_slow_cores("dstorage worker"); + } + } + let mut lanes = scheduler.lock(); + loop { + let Some(job) = lanes.start() else { + lanes = scheduler.work.wait(lanes).unwrap_or_else(|e| e.into_inner()); + continue; + }; + drop(lanes); + let started = std::time::Instant::now(); + let result = execute(&job.request); + walls_request(&job.request, &result, started); + lanes = scheduler.lock(); + lanes.finish(&job, result); + lanes.count(&job, started); + if std::mem::take(&mut lanes.starved) { + scheduler.work.notify_all(); + } + scheduler.finished.notify_all(); + } +} + +impl Lanes { + /// Counts a finished request; every 5 s a debug line sums them up. + fn count(&mut self, job: &Job, started: std::time::Instant) { + let (requests, bytes, busy) = &mut self.done; + *requests += 1; + *bytes += u64::from(job.request.destination_size); + *busy += started.elapsed(); + #[cfg(windows)] + { + use leonida_gpu::framelog::{T, add}; + add(T::DiskReads, 1); + add(T::DiskBytes, u64::from(job.request.destination_size)); + add(T::DiskUs, started.elapsed().as_micros() as u64); + } + if job.request.options & BCPACK != 0 { + self.bcpack.0 += u64::from(job.request.destination_size); + self.bcpack.1 += started.elapsed(); + } + let since = *self.since.get_or_insert(started); + let elapsed = since.elapsed(); + if elapsed.as_secs() >= 5 { + let waiting: usize = self.lanes.values().map(|l| l.reads.len()).sum(); + let reading = READING.swap(0, Ordering::Relaxed) as f64 / 1e9; + tracing::debug!( + requests = *requests, + mb_per_s = format_args!("{:.1}", *bytes as f64 / elapsed.as_secs_f64() / 1e6), + busy_workers = format_args!("{:.2}", busy.as_secs_f64() / elapsed.as_secs_f64()), + reading_workers = format_args!("{:.2}", reading / elapsed.as_secs_f64()), + staging_waits = std::mem::take(&mut self.refused), + bcpack_mb = self.bcpack.0 / 1_000_000, + bcpack_workers = format_args!("{:.2}", self.bcpack.1.as_secs_f64() / elapsed.as_secs_f64()), + waiting, + "dstorage: last {:.1} s", + elapsed.as_secs_f64() + ); + self.done = Default::default(); + self.bcpack = Default::default(); + self.since = None; + } + } + + /// Starts the next read of the class with the least virtual time, from + /// its lane that has started the fewest bytes, if the staging buffer + /// has room for it (or nothing else holds any). + fn start(&mut self) -> Option { + let busy = || self.lanes.iter().filter(|(_, l)| !l.reads.is_empty()); + let (_, class) = busy().map(|(_, l)| (self.clock[l.class], l.class)).min()?; + let (_, _, id) = busy() + .filter(|(_, l)| l.class == class) + .filter_map(|(&id, l)| Some((l.clock, l.reads.front()?.0, id))) + .min()?; + let lane = self.lanes.get_mut(&id)?; + let &(seq, request) = lane.reads.front()?; + let staging = staging_bytes(&request); + if self.staged > 0 && self.staged + staging > self.staging { + self.starved = true; + self.refused += 1; + return None; + } + lane.reads.pop_front(); + lane.running.insert(seq); + self.staged += staging; + let size = u64::from(request.destination_size.max(request.source_size)).max(1); + self.now = self.clock[class]; + self.clock[class] += size * COST[class]; + self.lane_now[class] = lane.clock; + lane.clock += size; + Some(Job { + lane: id, + seq, + request, + staging, + }) + } + + fn finish(&mut self, job: &Job, result: Result<(), HRESULT>) { + self.staged -= job.staging; + if let Some(lane) = self.lanes.get_mut(&job.lane) { + lane.running.remove(&job.seq); + if let Err(hr) = result { + lane.failures.insert(job.seq, hr); + } + lane.flush(); + } + } + + /// Moves a queue's enqueued commands to the workers. + fn submit(&mut self, id: u64) { + let Some(class) = self.lanes.get(&id).map(|l| l.class) else { + return; + }; + // A class that had nothing waiting starts from now, not from the + // credit it left behind. + if !self + .lanes + .values() + .any(|l| l.class == class && !l.reads.is_empty()) + { + self.clock[class] = self.clock[class].max(self.now); + } + let Some(lane) = self.lanes.get_mut(&id) else { + return; + }; + if lane.reads.is_empty() { + lane.clock = lane.clock.max(self.lane_now[class]); + } + for command in std::mem::take(&mut lane.unsubmitted) { + let seq = self.next_seq; + self.next_seq += 1; + match command { + Command::Read(request) => lane.reads.push_back((seq, request)), + Command::Status(status) => lane.statuses.push_back((seq, status)), + } + } + lane.flush(); + } +} + +impl Lane { + fn new(priority: i8, capacity: u16) -> Lane { + Lane { + class: priority.clamp(-1, 1).wrapping_add(1) as usize, + capacity: usize::from(capacity), + clock: 0, + unsubmitted: Vec::new(), + reads: VecDeque::new(), + statuses: VecDeque::new(), + running: BTreeSet::new(), + failures: BTreeMap::new(), + closed: false, + } + } + + /// Requests and status entries held, submitted or not. + fn entries(&self) -> usize { + self.unsubmitted.len() + self.reads.len() + self.statuses.len() + self.running.len() + } + + /// Writes the status entries whose earlier reads have all finished. + fn flush(&mut self) { + while let Some(&(seq, _)) = self.statuses.front() { + let waiting = self.reads.front().map(|r| r.0); + if waiting.into_iter().chain(self.running.first().copied()).any(|s| s < seq) { + return; + } + let Some((_, status)) = self.statuses.pop_front() else { + return; + }; + let later = self.failures.split_off(&seq); + let first = std::mem::replace(&mut self.failures, later) + .into_values() + .next(); + status + .entry() + .store(first.unwrap_or(S_OK), Ordering::Release); + } + } +} + +/// Staging bytes a request holds while it runs: what it buffers between +/// the file and the destination. Raw reads go straight to their +/// destination, memory sources need none (as on the console). +fn staging_bytes(request: &Request) -> u64 { + let buffered = request.options & (ZLIB | BCPACK | PAGE_DESTINATION) != 0; + if buffered && request.options & MEMORY_SOURCE == 0 { + u64::from(request.source_size) + } else { + 0 + } +} + +/// Ends a queue: what was not started is dropped, and this waits for the +/// reads already running (they write title memory). +fn close_lane(id: u64) { + let Some(scheduler) = scheduler() else { + return; + }; + let mut lanes = scheduler.lock(); + let Some(lane) = lanes.lanes.get_mut(&id) else { + return; + }; + lane.closed = true; + lane.unsubmitted.clear(); + lane.reads.clear(); + lane.statuses.clear(); // releases their arrays + while lanes.lanes.get(&id).is_some_and(|l| !l.running.is_empty()) { + lanes = scheduler + .finished + .wait(lanes) + .unwrap_or_else(|e| e.into_inner()); + } + lanes.lanes.remove(&id); + scheduler.finished.notify_all(); +} + +/// A read request as the title builds it, 0x48 bytes. +#[repr(C)] +#[derive(Clone, Copy)] +struct Request { + options: u64, + /// An address, or with `PAGE_DESTINATION` an array of 64 KiB page + /// numbers. + destination: *mut c_void, + /// With `PAGE_DESTINATION`, the low 16 bits are where in the first page + /// the destination starts. + page_offset: u64, + destination_size: u32, + /// Our file object, or with `MEMORY_SOURCE` an address. + source: *const c_void, + offset: u64, + source_size: u32, + /// Compressed size between two decompression stages; unused here. + intermediate_size: u32, + /// Matched by cancellation; the title leaves it 0. + tag: u64, + name: *const c_char, +} + +// Request options. +/// Inflate zlib (RFC 1950) data. +const ZLIB: u64 = 1; +/// Bits 1-4: decode BCPack data of this BC format number (0: none). +const BCPACK: u64 = 0xf << 1; +const PAGE_DESTINATION: u64 = 1 << 21; +const MEMORY_SOURCE: u64 = 1 << 22; +// Bits 5-20 select a further transform, bit 23 a source in physical pages; +// The title's packages need neither, so requests with them fail. + +const PAGE: usize = 64 * 1024; + +enum Command { + Read(Request), + Status(Status), +} + + +/// A status entry to write, holding a reference on its array. +struct Status { + array: Array, + index: u32, +} + +impl Drop for Status { + fn drop(&mut self) { + release(self.array); + } +} + +impl Status { + fn entry(&self) -> &AtomicI32 { + // SAFETY: we hold a reference; the index was checked when enqueued. + &unsafe { &*self.array }.state.entries[self.index as usize] + } +} + +extern "system" fn enqueue_request(this: QueueRef, request: *const Request) { + // SAFETY: the title passes its request (null tolerated). + let Some(&request) = (unsafe { request.as_ref() }) else { + return; + }; + queue(this, Command::Read(request)); +} + +extern "system" fn enqueue_status(this: QueueRef, array: Array, index: u32) { + // SAFETY: the title passes an array we created (null tolerated). + let Some(entries) = (unsafe { array.as_ref() }).map(|a| &a.state.entries) else { + return; + }; + let Some(entry) = entries.get(index as usize) else { + tracing::warn!(index, "dstorage: status entry out of range"); + return; + }; + entry.store(E_PENDING, Ordering::Release); + add_ref_instance(array); + queue(this, Command::Status(Status { array, index })); +} + +/// Adds a command to the queue; blocks while the queue is full, and +/// submits on its own once half of it is enqueued, as the console does. +fn queue(this: QueueRef, command: Command) { + // SAFETY: a queue we created and the title still holds. + let id = unsafe { &*this }.state.id; + let Some(scheduler) = scheduler() else { + return; + }; + let mut lanes = scheduler.lock(); + loop { + let Some(lane) = lanes.lanes.get(&id).filter(|l| !l.closed) else { + return; // closed: dropped (a status releases its array) + }; + // One slot stays free, as the console's count of empty slots says. + if lane.entries() + 1 < lane.capacity.max(2) { + break; + } + lanes = scheduler + .finished + .wait(lanes) + .unwrap_or_else(|e| e.into_inner()); + } + let Some(lane) = lanes.lanes.get_mut(&id) else { + return; + }; + lane.unsubmitted.push(command); + if lane.unsubmitted.len() >= (lane.capacity / 2).max(1) { + lanes.submit(id); + scheduler.work.notify_all(); + } +} + +extern "system" fn submit(this: QueueRef) { + // SAFETY: as above. + let id = unsafe { &*this }.state.id; + let Some(scheduler) = scheduler() else { + return; + }; + let mut lanes = scheduler.lock(); + let pending = lanes.lanes.get(&id).map_or(0, |l| l.unsubmitted.len()); + tracing::debug!(commands = pending, "dstorage: submit"); + lanes.submit(id); + scheduler.work.notify_all(); +} + +/// Ends the queue whatever its reference count: what was not started never +/// completes, and this returns once the reads already running have +/// finished. The title calls this, not `Release`. +extern "system" fn close(this: QueueRef) { + // SAFETY: as above. + close_lane(unsafe { &*this }.state.id); +} + +/// Reads, inflates and/or unpacks, and writes one request. +fn execute(request: &Request) -> Result<(), HRESULT> { + let options = request.options; + let fail = |hr: HRESULT, why: &str| { + tracing::warn!( + options = format_args!("{options:#x}"), + offset = request.offset, + source_size = request.source_size, + destination_size = request.destination_size, + intermediate_size = request.intermediate_size, + tag = request.tag, + name = text(request.name), + hr = format_args!("{:#010x}", hr as u32), + "dstorage: request failed: {why}" + ); + hr + }; + if options & !(ZLIB | BCPACK | PAGE_DESTINATION | MEMORY_SOURCE) != 0 { + return Err(fail(E_NOTIMPL, "unsupported options")); + } + if request.source.is_null() || request.destination.is_null() { + return Err(fail(E_INVALIDARG, "no source or destination")); + } + let bc = ((options & BCPACK) >> 1) as u8; + let size = request.destination_size as usize; + if options & (ZLIB | BCPACK) == 0 { + if request.source_size > request.destination_size { + return Err(fail(E_INVALIDARG, "source larger than destination")); + } + let size = request.source_size as usize; + // A file read into a title address is the kernel's write, and the + // kernel does not fault into the GPU side's guard: a block guarded + // again between `kernel_will_write` and the read (the guard over all + // the views of a page protects other views from other threads) made + // the read fail with ERROR_INVALID_USER_BUFFER, and the title stops + // at the failed request (runs amd-C and amd-C2, seconds after the + // world's first frame). It is read beside and copied in: our copy + // faults into the guard like the title's own writes. + let bounce = options & (PAGE_DESTINATION | MEMORY_SOURCE) == 0; + return into_destination(request, size, |out| { + if !bounce { + return read_into(request, out).map(|()| size); + } + let mut data = vec![0; size]; + read_into(request, &mut data)?; + out.copy_from_slice(&data); + Ok(size) + }) + .map_err(|hr| fail(hr, "copying")); + } + let tables = if bc != 0 { Some(bcpack_tables()?) } else { None }; + let source = read_source(request).map_err(|hr| fail(hr, "reading the source"))?; + // The console's order: zlib first, then BCPack. + let source = if bc != 0 && options & ZLIB != 0 { + let mut packed = vec![0; request.intermediate_size as usize]; + let n = inflate(&source, &mut packed).map_err(|hr| fail(hr, "zlib"))?; + packed.truncate(n); + Cow::Owned(packed) + } else { + source + }; + into_destination(request, size, |out| match tables { + Some(tables) => bcpack::decode(bc, &source, out, tables) + .map(|()| out.len()) + .map_err(|e| fail(INVALID_DATA, &e.to_string())), + None => inflate(&source, out).map_err(|hr| fail(hr, "zlib")), + })?; + tracing::trace!( + options = format_args!("{options:#x}"), + offset = request.offset, + size, + "dstorage: request done" + ); + Ok(()) +} + +/// Inflates a zlib stream into `out`, returning the bytes written. A stream +/// that ends short of `out` passes: the title's chunks fill it exactly, and +/// nothing says that is required. +fn inflate(source: &[u8], out: &mut [u8]) -> Result { + thread_local! { + static INFLATE: std::cell::RefCell = + std::cell::RefCell::new(zlib_rs::Inflate::new(true, 15)); + } + INFLATE.with_borrow_mut(|state| { + state.reset(true); + // `Inflate::decompress` cannot distinguish a valid empty stream from + // an insufficient buffer when `avail_out == 0`, so use a 1-byte scratch + // destination and verify `written <= out_len` afterward. + let out_len = out.len(); + let mut scratch = [0u8; 1]; + let dest = if out_len == 0 { &mut scratch[..] } else { out }; + let (mut in_pos, mut out_pos) = (0usize, 0usize); + let status = loop { + match state.decompress( + &source[in_pos..], + &mut dest[out_pos..], + zlib_rs::InflateFlush::NoFlush, + ) { + Ok(zlib_rs::Status::StreamEnd) => break Ok(zlib_rs::Status::StreamEnd), + Ok(zlib_rs::Status::Ok) => { + let next_in = state.total_in() as usize; + let next_out = state.total_out() as usize; + if next_in == in_pos && next_out == out_pos { + break Ok(zlib_rs::Status::BufError); + } + in_pos = next_in; + out_pos = next_out; + } + other => break other, + } + }; + let written = state.total_out() as usize; + match status { + Ok(zlib_rs::Status::StreamEnd) if written <= out_len => Ok(written), + other => { + tracing::debug!(?other, "dstorage: zlib stream"); + Err(INVALID_DATA) + } + } + }) +} + +/// The BCPack format's constant tables, parsed once for the process. If +/// they do not parse every BCPack request fails: one warning, then debug. +fn bcpack_tables() -> Result<&'static Tables, HRESULT> { + static TABLES: OnceLock> = OnceLock::new(); + static WARNED: AtomicBool = AtomicBool::new(false); + match TABLES.get_or_init(load_bcpack_tables) { + Ok(tables) => Ok(tables), + Err(why) if !WARNED.swap(true, Ordering::Relaxed) => { + tracing::warn!("dstorage: BCPack requests fail: {why} (more at debug)"); + Err(E_NOTIMPL) + } + Err(_) => { + tracing::debug!("dstorage: BCPack request failed: no tables"); + Err(E_NOTIMPL) + } + } +} + +/// The tables Leonida Legacy ships with. +#[cfg(not(test))] +fn load_bcpack_tables() -> Result { + Tables::builtin().map_err(|e| format!("the built-in BCPack tables: {e}")) +} + +/// Tests decode streams made against tables of their own, from this folder. +#[cfg(test)] +static BCPACK_DIR: OnceLock = OnceLock::new(); + +#[cfg(test)] +fn use_bcpack_tables(dir: std::path::PathBuf) { + let _ = BCPACK_DIR.set(dir); +} + +#[cfg(test)] +fn load_bcpack_tables() -> Result { + let dir = BCPACK_DIR.get().ok_or("no folder set for the test tables")?; + let bytes = std::fs::read(dir.join("tables.bin")).map_err(|e| e.to_string())?; + Tables::parse(&bytes).map_err(|e| e.to_string()) +} + +/// A compressed request's source: borrowed from memory, or read from the +/// file. +fn read_source(request: &Request) -> Result, HRESULT> { + let size = request.source_size as usize; + if request.options & MEMORY_SOURCE != 0 { + // SAFETY: the title's source holds `size` bytes until completion. + let bytes = unsafe { std::slice::from_raw_parts(request.source.cast(), size) }; + return Ok(Cow::Borrowed(bytes)); + } + let mut bytes = vec![0; size]; + read_into(request, &mut bytes)?; + Ok(Cow::Owned(bytes)) +} + +/// Nanoseconds workers spent reading files, for the debug summary. +static READING: AtomicU64 = AtomicU64::new(0); + +/// Fills `out` (the source size) from the request's file or memory. +fn read_into(request: &Request, out: &mut [u8]) -> Result<(), HRESULT> { + if request.options & MEMORY_SOURCE != 0 { + // SAFETY: the title's source holds `out.len()` bytes until completion. + out.copy_from_slice(unsafe { std::slice::from_raw_parts(request.source.cast(), out.len()) }); + return Ok(()); + } + // SAFETY: a file object we created; the title keeps it open. + let file = &unsafe { &*request.source.cast::>() } + .state + .file; + let started = std::time::Instant::now(); + let mut done = 0; + let result = loop { + if done == out.len() { + break Ok(()); + } + match file.seek_read(&mut out[done..], request.offset + done as u64) { + Ok(0) => break Err(END_OF_FILE), + Ok(n) => done += n, + Err(error) => break Err(from_win32(&error)), + } + }; + READING.fetch_add(started.elapsed().as_nanos() as u64, Ordering::Relaxed); + result +} + +/// Runs `fill` on the destination's first `len` bytes; `fill` returns how +/// many it produced. GPU-visible destinations are host memory like the +/// rest (GPU address = CPU address), so an address is written in place; +/// physical pages are too when they are consecutive pages of one +/// allocation, and otherwise go through a buffer. +fn into_destination( + request: &Request, + len: usize, + fill: impl FnOnce(&mut [u8]) -> Result, +) -> Result<(), HRESULT> { + if request.options & PAGE_DESTINATION == 0 { + // Opens the guarded blocks and tells the GPU side a placed texture + // there changes. `fill` writes from user mode (a file read is read + // beside first, see `execute`), so a block guarded again meanwhile + // faults into the guard instead of failing the write. + leonida_gpu::kernel_will_write(request.destination as usize, len); + // SAFETY: the title's destination holds `destination_size` bytes, at + // least `len`, and nothing else writes it until completion. + let out = unsafe { std::slice::from_raw_parts_mut(request.destination.cast::(), len) }; + let filled = fill(out).map(drop); + // Said again now that the bytes are there (upstream's c75fdba holds + // the blocks open over the read and marks them once more at its + // end): a copy or a texture pass that took the memory while the + // read was under way took what was there before. Counted; acted on + // only with `LEONIDA_PAGE_WRITES=all`. + leonida_gpu::title_memory_written(request.destination as usize, len, false); + return filled; + } + let offset = (request.page_offset & 0xffff) as usize; + // SAFETY: the title passes a page number per 64 KiB of destination, + // which holds at least `len` bytes from `offset`. + let pages = unsafe { + std::slice::from_raw_parts( + request.destination.cast::(), + (offset + len).div_ceil(PAGE), + ) + }; + // Consecutive pages of one allocation (the usual case): written in + // place through one view. + if let Some(mut window) = super::xmem::page_window(pages, offset, len) { + let filled = fill(window.bytes()).map(drop); + drop(window); + // The title maps pages where the card reads them and has them + // filled afterwards: the GPU side's copies of those addresses + // learn of the bytes only from this (upstream c75fdba, fork PR + // #571). After a decode that failed part way too: what it wrote + // is there. + super::xmem::pages_written(pages, offset, len); + return filled; + } + let mut data = vec![0; len]; + let n = fill(&mut data)?; + // A page the title has just made, or a view the host refuses for a + // moment, comes right a little later: the write is tried again before + // the request fails (`LEONIDA_DSTORAGE_RETRIES`, 12 tries, about 0.9 s + // in all; 0: not tried again, as before). Runs 175-178 lost 12 to 446 + // reads a launch here, all in one second of the loading; the one build + // that tried again (run 165) lost none of 13. + static RETRIES: std::sync::OnceLock = std::sync::OnceLock::new(); + let retries = *RETRIES.get_or_init(|| { + std::env::var("LEONIDA_DSTORAGE_RETRIES").ok().and_then(|v| v.trim().parse().ok()).unwrap_or(12) + }); + // Since the start: writes that succeeded on a later try, and writes + // given up. + static RETRIED: [AtomicU64; 2] = [AtomicU64::new(0), AtomicU64::new(0)]; + let mut written = super::xmem::write_physical(pages, offset, &data[..n]); + let mut tries = 0u32; + while !written && tries < retries { + std::thread::sleep(std::time::Duration::from_millis((2u64 << tries.min(6)).min(128))); + tries += 1; + written = super::xmem::write_physical(pages, offset, &data[..n]); + } + if written { + if tries > 0 { + let on_a_retry = RETRIED[0].fetch_add(1, Ordering::Relaxed) + 1; + tracing::info!( + offset, + len, + tries, + on_a_retry, + given_up = RETRIED[1].load(Ordering::Relaxed), + "dstorage: a destination's physical pages written after a retry" + ); + } + // As above, after the write that succeeded. + super::xmem::pages_written(pages, offset, n); + Ok(()) + } else { + let given_up = RETRIED[1].fetch_add(1, Ordering::Relaxed) + 1; + tracing::warn!( + known = super::xmem::pages_known(pages, offset, len), + tries, + given_up, + on_a_retry = RETRIED[0].load(Ordering::Relaxed), + "dstorage: retries used up (LEONIDA_DSTORAGE_RETRIES)" + ); + // Said aloud: the title never reads a request's result + // (it only polls for completion), so a destination left unwritten + // is a model or texture that silently holds whatever its pages + // held before. + tracing::warn!( + offset, + len, + pages = pages.len(), + "dstorage: a destination's physical pages could not be written (unknown page or a host failure); its request fails" + ); + Err(E_INVALIDARG) + } +} + +/// Slots by the 2020 order, which the argument shapes at +/// the title's call sites match (0x18, 0x20, 0x30 and 0x40 are called). +static QUEUE_VTABLE: Methods<12> = Methods([ + missing::<0> as *const (), + add_ref_instance:: as *const (), + release:: as *const (), + enqueue_request as *const (), // 0x18 + enqueue_status as *const (), // 0x20 + missing::<5> as *const (), // 0x28 (2020: fence signal) + submit as *const (), // 0x30 + missing::<7> as *const (), // 0x38 (2020: cancel by tag) + close as *const (), // 0x40 + missing::<9> as *const (), // 0x48 (2020: error event) + missing::<10> as *const (), // 0x50 (2020: error record) + missing::<11> as *const (), // 0x58 (2020: queue info) +]); + +pub(crate) fn module() -> HleModule { + HleModule { + name: "dstorage", + dlls: &["xcrdapi.dll"], + exports: vec![hle_export!(DStorageGetFactory)], + } +} + +#[cfg(test)] +mod tests { + use std::os::windows::ffi::OsStrExt; + use std::time::{Duration, Instant}; + + use super::*; + use crate::modules::xgameruntime::method; + + fn call(object: *mut c_void, slot: usize) -> F { + // SAFETY: every object here starts with the runtime header. + method(unsafe { &*object.cast::() }, slot) + } + + fn factory() -> *mut c_void { + let mut factory = std::ptr::null_mut(); + assert_eq!(DStorageGetFactory(&FACTORY, &mut factory), S_OK); + factory + } + + fn open(path: &std::path::Path) -> *mut c_void { + let wide: Vec = path.as_os_str().encode_wide().chain([0]).collect(); + let open: extern "system" fn(*mut c_void, *const u16, *const Guid, Out) -> HRESULT = + call(factory(), 0x20); + let mut file = std::ptr::null_mut(); + assert_eq!( + open(factory(), wide.as_ptr(), std::ptr::null(), &mut file), + S_OK + ); + file + } + + fn status_array(capacity: u32) -> *mut c_void { + let create: extern "system" fn( + *mut c_void, + u32, + *const c_char, + *const Guid, + Out, + ) -> HRESULT = call(factory(), 0x28); + let mut array = std::ptr::null_mut(); + let name = c"test".as_ptr(); + assert_eq!( + create(factory(), capacity, name, std::ptr::null(), &mut array), + S_OK + ); + array + } + + fn new_queue(source_type: u64) -> *mut c_void { + let create: extern "system" fn(*mut c_void, *const QueueDesc, *const Guid, Out) -> HRESULT = + call(factory(), 0x50); + let desc = QueueDesc { + source_type, + capacity: 0x80, + priority: 0, + name: c"test".as_ptr(), + unknown: 1, + }; + let mut queue = std::ptr::null_mut(); + assert_eq!(create(factory(), &desc, std::ptr::null(), &mut queue), S_OK); + queue + } + + fn request( + options: u64, + destination: *mut c_void, + destination_size: usize, + source: *const c_void, + offset: u64, + source_size: usize, + ) -> Request { + Request { + options, + destination, + page_offset: 0, + destination_size: destination_size as u32, + source, + offset, + source_size: source_size as u32, + intermediate_size: 0, + tag: 0, + name: std::ptr::null(), + } + } + + fn enqueue(queue: *mut c_void, request: &Request) { + let f: extern "system" fn(*mut c_void, *const Request) = call(queue, 0x18); + f(queue, request); + } + + fn enqueue_status(queue: *mut c_void, array: *mut c_void, index: u32) { + let f: extern "system" fn(*mut c_void, *mut c_void, u32) = call(queue, 0x20); + f(queue, array, index); + } + + fn void(object: *mut c_void, slot: usize) { + let f: extern "system" fn(*mut c_void) = call(object, slot); + f(object); + } + + fn result(array: *mut c_void, index: u32) -> HRESULT { + let f: extern "system" fn(*mut c_void, u32) -> HRESULT = call(array, 0x20); + f(array, index) + } + + /// Polls as the title does, then returns the entry's result. + fn wait(array: *mut c_void, index: u32) -> HRESULT { + let done: extern "system" fn(*mut c_void, u32) -> bool = call(array, 0x18); + let start = Instant::now(); + while !done(array, index) { + assert!(start.elapsed() < Duration::from_secs(10), "never completed"); + std::thread::sleep(Duration::from_millis(1)); + } + result(array, index) + } + + fn file_with(bytes: &[u8]) -> (tempfile::TempDir, *mut c_void) { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("data.bin"); + std::fs::write(&path, bytes).unwrap(); + let file = open(&path); + (dir, file) + } + + fn pattern(n: usize) -> Vec { + (0..n).map(|i| (i * 7 + i / 251) as u8).collect() + } + + #[test] + fn request_layout_is_the_titles() { + assert_eq!(size_of::(), 0x48); + assert_eq!(std::mem::offset_of!(Request, destination_size), 0x18); + assert_eq!(std::mem::offset_of!(Request, source), 0x20); + assert_eq!(std::mem::offset_of!(Request, source_size), 0x30); + assert_eq!(std::mem::offset_of!(Request, name), 0x40); + assert_eq!(std::mem::offset_of!(QueueDesc, unknown), 0x18); + } + + fn compress_zlib(plain: &[u8]) -> Vec { + let mut buf = vec![0u8; zlib_rs::compress_bound(plain.len())]; + let (packed, rc) = + zlib_rs::compress_slice(&mut buf, plain, zlib_rs::DeflateConfig::new(6)); + assert_eq!(rc, zlib_rs::ReturnCode::Ok); + packed.to_vec() + } + + #[test] + fn raw_and_zlib_reads_from_a_file() { + let plain = pattern(300_000); + let packed = compress_zlib(&plain); + let mut contents = plain.clone(); + contents.extend_from_slice(&packed); + let (_dir, file) = file_with(&contents); + let (queue, array) = (new_queue(0), status_array(1)); + + let mut raw = vec![0u8; 1000]; + let mut inflated = vec![0u8; plain.len()]; + let at = |b: &mut Vec| b.as_mut_ptr().cast(); + enqueue(queue, &request(0, at(&mut raw), 1000, file, 5000, 1000)); + let offset = plain.len() as u64; + let zlib = request( + ZLIB, + at(&mut inflated), + plain.len(), + file, + offset, + packed.len(), + ); + enqueue(queue, &zlib); + enqueue_status(queue, array, 0); + assert_eq!(result(array, 0), E_PENDING, "pending until done"); + void(queue, 0x30); + assert_eq!(wait(array, 0), S_OK); + assert_eq!(raw, plain[5000..6000]); + assert_eq!(inflated, plain); + void(queue, 0x40); + } + + #[test] + fn memory_sources_inflate_too() { + let plain = pattern(70_000); + let packed = compress_zlib(&plain); + let (queue, array) = (new_queue(1), status_array(1)); + let mut out = vec![0u8; plain.len()]; + let options = ZLIB | MEMORY_SOURCE; + let r = request( + options, + out.as_mut_ptr().cast(), + out.len(), + packed.as_ptr().cast(), + 0, + packed.len(), + ); + enqueue(queue, &r); + enqueue_status(queue, array, 0); + void(queue, 0x30); + assert_eq!(wait(array, 0), S_OK); + assert_eq!(out, plain); + } + + #[test] + fn statuses_complete_in_order_with_the_first_failure() { + let contents = pattern(4096); + let (_dir, file) = file_with(&contents); + let (queue, array) = (new_queue(0), status_array(3)); + // Requests in flight together run in any order, so none of them + // shares a destination (failed ones leave theirs undefined). + let mut buffers = [[0u8; 16]; 5]; + let [failed, failed_too, out, other, bcpack] = buffers.each_mut().map(|b| b.as_mut_ptr().cast()); + + // Segment 0: a read past the end, then a bad stream; the first wins. + enqueue(queue, &request(0, failed, 16, file, 4090, 16)); + enqueue(queue, &request(ZLIB, failed_too, 16, file, 0, 16)); + enqueue_status(queue, array, 0); + // Segment 1: two reads. + enqueue(queue, &request(0, other, 16, file, 0, 16)); + enqueue(queue, &request(0, out, 16, file, 100, 16)); + enqueue_status(queue, array, 1); + void(queue, 0x30); + // Segment 2: a BCPack request (BC7) whose stream is empty fails. + with_test_tables(); + enqueue(queue, &request(7 << 1, bcpack, 16, file, 0, 0)); + enqueue_status(queue, array, 2); + void(queue, 0x30); + + assert_eq!(wait(array, 2), INVALID_DATA); + assert_eq!(result(array, 0), END_OF_FILE); + assert_eq!(result(array, 1), S_OK); + assert_eq!(buffers[2], contents[100..116]); + assert_eq!(buffers[3], contents[..16]); + } + + #[test] + fn half_a_queue_submits_itself() { + let (_dir, file) = file_with(&pattern(64)); + let create: extern "system" fn(*mut c_void, *const QueueDesc, *const Guid, Out) -> HRESULT = + call(factory(), 0x50); + let desc = QueueDesc { + source_type: 0, + capacity: 4, + priority: 1, + name: c"small".as_ptr(), + unknown: 1, + }; + let mut queue = std::ptr::null_mut(); + assert_eq!(create(factory(), &desc, std::ptr::null(), &mut queue), S_OK); + let array = status_array(1); + let mut out = [0u8; 16]; + enqueue(queue, &request(0, out.as_mut_ptr().cast(), 16, file, 8, 16)); + enqueue_status(queue, array, 0); // the second of four: no submit needed + assert_eq!(wait(array, 0), S_OK); + assert_eq!(out, pattern(64)[8..24]); + } + + /// Lanes without workers: what `start` picks, and when statuses land. + fn lanes(staging: u64) -> Lanes { + Lanes { + lanes: HashMap::new(), + next_id: 0, + next_seq: 0, + staged: 0, + staging, + starved: false, + clock: [0; 3], + now: 0, + lane_now: [0; 3], + done: Default::default(), + refused: 0, + bcpack: Default::default(), + since: None, + } + } + + fn read(lanes: &mut Lanes, id: u64, options: u64, size: u32) { + let mut r = request(options, std::ptr::null_mut(), 0, std::ptr::null(), 0, 0); + (r.destination_size, r.source_size) = (size, size); + let lane = lanes.lanes.get_mut(&id).unwrap(); + lane.unsubmitted.push(Command::Read(r)); + } + + #[test] + fn priorities_share_by_bytes_about_tenfold() { + let mut l = lanes(STAGING); + l.lanes.insert(0, Lane::new(0, 4096)); + l.lanes.insert(1, Lane::new(1, 4096)); + l.lanes.insert(2, Lane::new(2, 4096)); // real-time: as high + for _ in 0..400 { + for id in 0..3 { + read(&mut l, id, 0, 4096); + } + } + (0..3).for_each(|id| l.submit(id)); + let mut started = [0u32; 3]; + for _ in 0..330 { + let job = l.start().unwrap(); + started[job.lane as usize] += 1; + l.finish(&job, Ok(())); + } + // Normal gets about a tenth of what high and real-time get together. + assert_eq!(started[1] + started[2], 300, "{started:?}"); + assert_eq!(started[0], 30, "{started:?}"); + assert!(started[1].abs_diff(started[2]) <= 1, "{started:?}"); + } + + #[test] + fn staging_bounds_compressed_bytes_in_flight() { + let mut l = lanes(100); + l.lanes.insert(0, Lane::new(0, 64)); + read(&mut l, 0, ZLIB, 60); + read(&mut l, 0, ZLIB, 60); + read(&mut l, 0, 0, 1000); // raw: straight to its destination + l.submit(0); + let first = l.start().unwrap(); + assert!(l.start().is_none(), "60 + 60 > 100"); + l.finish(&first, Ok(())); + let second = l.start().unwrap(); + let raw = l.start().unwrap(); + assert_eq!((second.staging, raw.staging), (60, 0)); + // Alone, a request larger than the buffer still runs. + read(&mut l, 0, ZLIB, 500); + l.submit(0); + assert!(l.start().is_none()); + l.finish(&second, Ok(())); + assert!(l.start().is_some()); + } + + #[test] + fn a_status_waits_for_every_earlier_read() { + let mut l = lanes(STAGING); + l.lanes.insert(0, Lane::new(0, 64)); + let array = status_array(2).cast::>(); + let status = |index| { + add_ref_instance(array); + Command::Status(Status { array, index }) + }; + read(&mut l, 0, 0, 16); + read(&mut l, 0, 0, 16); + l.lanes.get_mut(&0).unwrap().unsubmitted.push(status(0)); + read(&mut l, 0, 0, 16); + l.lanes.get_mut(&0).unwrap().unsubmitted.push(status(1)); + // SAFETY: an array we created. + for entry in unsafe { &(*array).state.entries }.iter() { + entry.store(E_PENDING, Ordering::Release); + } + l.submit(0); + let jobs: Vec = (0..3).map(|_| l.start().unwrap()).collect(); + // The last read and the first finish; the second then fails. + l.finish(&jobs[2], Ok(())); + l.finish(&jobs[0], Ok(())); + let results = || (result(array.cast(), 0), result(array.cast(), 1)); + assert_eq!(results(), (E_PENDING, E_PENDING)); + l.finish(&jobs[1], Err(INVALID_DATA)); + assert_eq!(results(), (INVALID_DATA, S_OK)); + } + + #[test] + fn zlib_then_bcpack() { + with_test_tables(); + let packed = compress_zlib(&BC4_STREAM); + let (_dir, file) = file_with(&packed); + let (queue, array) = (new_queue(0), status_array(1)); + let mut out = [0u8; 16]; + let options = ZLIB | 4 << 1; + let mut r = request(options, out.as_mut_ptr().cast(), 16, file, 0, packed.len()); + r.intermediate_size = BC4_STREAM.len() as u32; + enqueue(queue, &r); + enqueue_status(queue, array, 0); + void(queue, 0x30); + assert_eq!(wait(array, 0), S_OK); + assert_eq!(out, bc4_blocks()); + } + + /// BCPack tables we made (uniform models; BC4 index pairs: low 3 bits, + /// next 3 bits), in a folder kept for the test process. + fn with_test_tables() { + static DIR: OnceLock<()> = OnceLock::new(); + DIR.get_or_init(|| { + let mut t = Vec::new(); + for m in 0..128 { + let g = m / 16; + for b in 0..9 { + let f: u16 = if b < g + 2 { 1 << (15 - g) } else { 0 }; + t.extend_from_slice(&f.to_le_bytes()); + } + } + t.extend([0; 256 + 64 + 256]); + t.extend((0..64u8).map(|v| (v & 7) | (v >> 3) << 4)); + t.resize(bcpack::TABLES_SIZE, 0); + let dir = tempfile::tempdir().unwrap().keep(); + std::fs::write(dir.join("tables.bin"), t).unwrap(); + use_bcpack_tables(dir); + }); + } + + /// Two BC4 blocks from the format's test encoder: endpoints 10, -3 with + /// indices p -> p & 7, then the same block plus 1 everywhere. + const BC4_STREAM: [u8; 88] = [ + 0, 0, 0, 0, 0, 0, 0, 0, 5, 5, 5, 5, 4, 4, 4, 4, 1, 1, 1, 1, 0x10, 0x10, 0x10, 0x10, 2, 1, + 0, 0, 0, 0, 0, 0, 0, 0, 0x14, 5, 0x20, 0x68, 0xb0, 0xf8, 3, 3, 2, 2, 0x24, 0x24, 0x24, + 0x24, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 4, 4, 0x10, 0x10, 0x10, 0x10, 0, 0, 0, 0, + 0x20, 0x68, 0xb0, 0xf8, 0x24, 0x24, 0x24, 0x24, 0, 0, 0, 0, 0, 0, 0, 0, + ]; + + /// What `BC4_STREAM` unpacks to. + fn bc4_blocks() -> [u8; 16] { + let code = [0u64, 2, 3, 4, 5, 6, 7, 1]; + let block = |e0: u64, e1: u64, add: usize| { + let bits = (0..16).fold(0, |a, p| a | code[(p + add) & 7] << (16 + 3 * p)); + (e0 | e1 << 8 | bits).to_le_bytes() + }; + let mut out = [0; 16]; + out[..8].copy_from_slice(&block(138, 125, 0)); + out[8..].copy_from_slice(&block(139, 126, 1)); + out + } + + #[test] + fn bcpack_requests_unpack_into_the_destination() { + with_test_tables(); + let mut contents = pattern(100); + contents.extend_from_slice(&BC4_STREAM); + let (_dir, file) = file_with(&contents); + let (queue, array) = (new_queue(0), status_array(1)); + let mut out = [0u8; 16]; + enqueue(queue, &request(4 << 1, out.as_mut_ptr().cast(), 16, file, 100, 88)); + enqueue_status(queue, array, 0); + void(queue, 0x30); + assert_eq!(wait(array, 0), S_OK); + assert_eq!(out, bc4_blocks()); + } + + #[test] + fn a_closed_queue_completes_nothing() { + let (_dir, file) = file_with(&pattern(64)); + let (queue, array) = (new_queue(0), status_array(1)); + let mut out = [0u8; 16]; + enqueue(queue, &request(0, out.as_mut_ptr().cast(), 16, file, 0, 16)); + enqueue_status(queue, array, 0); + void(queue, 0x40); + void(queue, 0x30); + std::thread::sleep(Duration::from_millis(50)); + assert_eq!(result(array, 0), E_PENDING); + assert_eq!(out, [0; 16]); + } + + #[test] + fn physical_page_destinations() { + use crate::modules::xmem; + let mut pages = [0usize; 2]; + let mut n = 2; + assert_eq!( + xmem::XMemAllocatePhysicalPages(0, &mut n, pages.as_mut_ptr()), + 1 + ); + // Where the title would see them: a reservation of 64 KiB pages. + let mapped = xmem::XMemVirtualAlloc( + std::ptr::null_mut(), + 2 * PAGE, + 0x2000 | 0x2040_0000, // reserve, 64 KiB pages + 0, + 0x04, + ); + assert!(!mapped.is_null()); + assert_eq!( + xmem::XMemMapPhysicalPages(mapped, 2, pages.as_ptr()), + mapped + ); + + let plain = pattern(100); + let (queue, array) = (new_queue(1), status_array(1)); + let mut r = request( + PAGE_DESTINATION | MEMORY_SOURCE, + pages.as_mut_ptr().cast(), + plain.len(), + plain.as_ptr().cast(), + 0, + plain.len(), + ); + r.page_offset = (PAGE - 40) as u64; // across the page boundary + enqueue(queue, &r); + enqueue_status(queue, array, 0); + void(queue, 0x30); + assert_eq!(wait(array, 0), S_OK); + // SAFETY: both pages are mapped read-write. + let seen = unsafe { std::slice::from_raw_parts(mapped.cast::().add(PAGE - 40), 100) }; + assert_eq!(seen, plain); + } + #[test] + fn zlib_into_pages_in_place_and_across_allocations() { + use crate::modules::xmem; + let allocate = |n: usize| { + let (mut pages, mut given) = (vec![0usize; n], n); + assert_eq!( + xmem::XMemAllocatePhysicalPages(0, &mut given, pages.as_mut_ptr()), + 1 + ); + pages + }; + let (a, b) = (allocate(3), allocate(1)); + let plain = pattern(2 * PAGE + 100); + let packed = compress_zlib(&plain); + // One allocation's pages in order (one window), then pages of two + // (through a buffer), both from 50 bytes into the first. + let mut destinations = [a.clone(), vec![a[0], a[1], b[0]]]; + let (queue, array) = (new_queue(1), status_array(1)); + for pages in &mut destinations { + let mut r = request( + ZLIB | PAGE_DESTINATION | MEMORY_SOURCE, + pages.as_mut_ptr().cast(), + plain.len(), + packed.as_ptr().cast(), + 0, + packed.len(), + ); + r.page_offset = 50; + enqueue(queue, &r); + } + enqueue_status(queue, array, 0); + void(queue, 0x30); + assert_eq!(wait(array, 0), S_OK); + for pages in &destinations { + let mapped = xmem::XMemVirtualAlloc( + std::ptr::null_mut(), + 3 * PAGE, + 0x2000 | 0x2040_0000, // reserve, 64 KiB pages + 0, + 0x04, + ); + assert!(!mapped.is_null()); + assert_eq!( + xmem::XMemMapPhysicalPages(mapped, 3, pages.as_ptr()), + mapped + ); + // SAFETY: all three pages are mapped read-write. + let seen = unsafe { std::slice::from_raw_parts(mapped.cast::(), 3 * PAGE) }; + assert!(seen[..50].iter().all(|&b| b == 0)); + assert_eq!(seen[50..50 + plain.len()], plain); + assert_eq!( + xmem::XMemMapPhysicalPages(mapped, 3, std::ptr::null()), + mapped + ); + } + assert_eq!(xmem::XMemFreePhysicalPages(3, a.as_ptr()), 1); + assert_eq!(xmem::XMemFreePhysicalPages(1, b.as_ptr()), 1); + } + + #[test] + fn zlib_inflate_handles_short_exact_empty_and_bad_streams() { + let plain = pattern(65_537); + let packed = compress_zlib(&plain); + + // Exact fit. + let mut exact = vec![0u8; plain.len()]; + assert_eq!(inflate(&packed, &mut exact), Ok(plain.len())); + assert_eq!(exact, plain); + + // Short stream into a larger buffer passes and returns bytes written; + // guard bytes outside the slice passed to `inflate` stay untouched. + let mut larger = vec![0xAA; plain.len() + 64]; + assert_eq!( + inflate(&packed, &mut larger[..plain.len() + 32]), + Ok(plain.len()) + ); + assert_eq!(&larger[..plain.len()], &plain[..]); + assert!(larger[plain.len() + 32..].iter().all(|&b| b == 0xAA)); + + // Empty valid stream passes for empty or non-empty destinations. + let empty = compress_zlib(&[]); + assert_eq!(inflate(&empty, &mut []), Ok(0)); + let mut scratch = [0x55u8; 4]; + assert_eq!(inflate(&empty, &mut scratch), Ok(0)); + + // Oversized stream (destination too small, including empty) fails. + let mut small = vec![0u8; plain.len() - 1]; + assert_eq!(inflate(&packed, &mut small), Err(INVALID_DATA)); + assert_eq!(inflate(&packed, &mut []), Err(INVALID_DATA)); + + // Truncated stream (missing trailer or payload bytes) fails. + let mut out = vec![0u8; plain.len()]; + assert_eq!( + inflate(&packed[..packed.len() - 1], &mut out), + Err(INVALID_DATA) + ); + assert_eq!( + inflate(&packed[..packed.len() / 2], &mut out), + Err(INVALID_DATA) + ); + assert_eq!(inflate(&[], &mut out), Err(INVALID_DATA)); + + // Corrupt Adler-32 trailer fails. + let mut bad_adler = packed.clone(); + *bad_adler.last_mut().unwrap() ^= 1; + assert_eq!(inflate(&bad_adler, &mut out), Err(INVALID_DATA)); + + // Corrupt header/payload fails, and subsequent valid inflate on the + // same thread still succeeds (verifies thread-local state reset). + let mut bad_body = packed.clone(); + bad_body[2] ^= 0xFF; + assert_eq!(inflate(&bad_body, &mut out), Err(INVALID_DATA)); + assert_eq!(inflate(&packed, &mut out), Ok(plain.len())); + assert_eq!(out, plain); + } +} diff --git a/crates/leonida-hle/src/modules/files.rs b/crates/leonida-hle/src/modules/files.rs new file mode 100644 index 000000000..28c4a2d20 --- /dev/null +++ b/crates/leonida-hle/src/modules/files.rs @@ -0,0 +1,1004 @@ +//! Virtual drives over host folders: on the console, title storage is a +//! drive of its own, and titles build paths on that assumption. +//! +//! Every title import that takes a path is bound here. A path on a virtual +//! drive (`X:\..`, `X:/..`, `X:`, `\\?\X:\..`) is rewritten to the host +//! folder behind it and handed to the host's own function; any other path +//! goes to the host unchanged. A rewritten narrow path goes to the host's +//! wide twin, so host folders outside the ANSI code page work; never to our +//! wide wrapper, which would rewrite the host path a second time when its +//! drive letter is mounted too. Letters are chosen among those the host +//! does not use, so no host drive is hidden. +#![allow(non_snake_case)] +#![allow(clippy::not_unsafe_ptr_arg_deref)] +#![allow(clippy::too_many_arguments)] + +use std::ffi::{CStr, c_char, c_void}; +use std::os::windows::ffi::OsStrExt; +use std::path::Path; +use std::sync::{Mutex, MutexGuard}; + +use windows_sys::Win32::Globalization::{CP_ACP, MultiByteToWideChar}; +use windows_sys::Win32::Storage::FileSystem::GetLogicalDrives; + +use crate::{HleExport, HleModule, hle_export}; + +/// The host's own function: what the import would have been bound to. +macro_rules! host { + ($dll:literal, $name:literal: $ty:ty) => {{ + static ADDRESS: std::sync::OnceLock = std::sync::OnceLock::new(); + let address = *ADDRESS.get_or_init(|| { + crate::host::function($dll, $name) + .unwrap_or_else(|| panic!("the host lacks {}!{}", $dll, $name)) + }); + // SAFETY: the host exports this function with this signature. + unsafe { std::mem::transmute::(address) } + }}; +} +pub(crate) use host; + +/// Mounted drives: upper-case letter and host root (UTF-16, no trailing +/// separator, no NUL). +static DRIVES: Mutex)>> = Mutex::new(Vec::new()); + +fn drives() -> MutexGuard<'static, Vec<(u16, Vec)>> { + DRIVES.lock().unwrap_or_else(|e| e.into_inner()) +} + +/// Gives the host folder `root` a drive letter (the same one if it already +/// has one): the highest letter neither the host nor another mount uses. +pub fn mount(root: &Path) -> Option { + let wide = root_wide(root); + let mut drives = drives(); + if let Some(&(letter, _)) = drives.iter().find(|(_, r)| *r == wide) { + return char::from_u32(letter.into()); + } + // SAFETY: no arguments. + let host = unsafe { GetLogicalDrives() }; + let letter = (b'D'..=b'Z').rev().find(|&l| { + host >> (l - b'A') & 1 == 0 && !drives.iter().any(|(m, _)| *m == u16::from(l)) + })?; + tracing::info!(drive = %char::from(letter), root = %root.display(), "virtual drive"); + drives.push((letter.into(), wide)); + Some(letter.into()) +} + +/// Gives the host folder `root` a drive letter the console fixes (titles +/// open their package as `G:\..` and temporary files as `T:\..`). A host +/// drive of that letter is hidden from the title. +pub fn mount_at(letter: char, root: &Path) { + let letter = letter.to_ascii_uppercase(); + let Some(index) = u32::from(letter) + .checked_sub(u32::from('A')) + .filter(|i| *i < 26) + else { + return; + }; + // SAFETY: no arguments. + let hides_host_drive = unsafe { GetLogicalDrives() } >> index & 1 != 0; + tracing::info!(drive = %letter, root = %root.display(), hides_host_drive, "virtual drive"); + let mut drives = drives(); + drives.retain(|(l, _)| u32::from(*l) != u32::from(letter)); + drives.push((letter as u16, root_wide(root))); +} + +/// `root` as UTF-16, absolute, without trailing separators (a drive root +/// keeps its own). +fn root_wide(root: &Path) -> Vec { + let root = std::path::absolute(root).unwrap_or_else(|_| root.to_owned()); + let mut wide: Vec = root.as_os_str().encode_wide().collect(); + while wide.len() > 3 && wide.last().is_some_and(|c| SEPARATORS.contains(c)) { + wide.pop(); + } + wide +} + +const SEPARATORS: [u16; 2] = [b'\\' as u16, b'/' as u16]; +const VERBATIM: [u16; 4] = [b'\\' as u16, b'\\' as u16, b'?' as u16, b'\\' as u16]; + +/// Host paths from this length on take the `\\?\` form, which lifts the +/// host's MAX_PATH limit (248 characters for a directory, 260 for a file). +const LONG: usize = 248; + +/// `root` and the title's `tail` as a `\\?\` path. That form turns off the +/// host's own clean-up, so `/` becomes `\` and `.` and `..` are resolved +/// here (`..` stops at the root). +fn verbatim(root: &[u16], tail: &[u16]) -> Vec { + let backslash = u16::from(b'\\'); + let mut out = if root.starts_with(&VERBATIM) { + root.to_vec() + } else if let Some(unc) = root.strip_prefix(&[backslash; 2][..]) { + let mut out = VERBATIM.to_vec(); + out.extend("UNC\\".encode_utf16()); + out.extend_from_slice(unc); + out + } else { + [&VERBATIM[..], root].concat() + }; + while out.last() == Some(&backslash) { + out.pop(); + } + let dot = u16::from(b'.'); + let mut parts: Vec<&[u16]> = Vec::new(); + for part in tail.split(|c| SEPARATORS.contains(c)) { + match part { + [] => {} + [d] if *d == dot => {} + [d, e] if [*d, *e] == [dot; 2] => drop(parts.pop()), + _ => parts.push(part), + } + } + for part in parts { + out.push(backslash); + out.extend_from_slice(part); + } + out +} + +/// The host path, NUL-terminated, for `path` (without its NUL) if it is on +/// a virtual drive. +pub(crate) fn translate(path: &[u16]) -> Option> { + let (prefix, rest) = match path.strip_prefix(&VERBATIM[..]) { + Some(rest) => (&VERBATIM[..], rest), + None => (&[][..], path), + }; + let &[letter, colon, ..] = rest else { + return None; + }; + if colon != u16::from(b':') { + return None; + } + let letter = u8::try_from(letter).ok().filter(u8::is_ascii_alphabetic)?; + let letter = u16::from(letter.to_ascii_uppercase()); + let drives = drives(); + let (_, root) = drives.iter().find(|(l, _)| *l == letter)?; + let tail = &rest[2..]; + if prefix.is_empty() && root.len() + tail.len() >= LONG { + let mut out = verbatim(root, tail); + out.push(0); + return Some(out); + } + let mut out = prefix.to_vec(); + out.extend_from_slice(root); + // `X:` and `X:name` are relative to the root. + if !tail.first().is_some_and(|c| SEPARATORS.contains(c)) { + out.push(b'\\'.into()); + } + let verbatim = !prefix.is_empty(); + out.extend(tail.iter().map(|&c| { + if verbatim && c == u16::from(b'/') { + b'\\'.into() + } else { + c + } + })); + out.push(0); + Some(out) +} + +/// A title's wide path: the host path when it is on a virtual drive, else +/// the title's own pointer. +struct Wide(*const u16, Option>); + +impl Wide { + fn ptr(&self) -> *const u16 { + self.1.as_ref().map_or(self.0, |p| p.as_ptr()) + } +} + +fn wide(path: *const u16) -> Wide { + if path.is_null() { + return Wide(path, None); + } + // SAFETY: the title passes a NUL-terminated path. + let path_slice = unsafe { + let len = (0..).take_while(|&i| *path.add(i) != 0).count(); + std::slice::from_raw_parts(path, len) + }; + let host = translate(path_slice); + trace(path_slice, host.as_deref()); + Wide(path, host) +} + +/// Every title path at debug level, with the host path if rewritten. +fn trace(path: &[u16], host: Option<&[u16]>) { + tracing::debug!( + path = %String::from_utf16_lossy(path), + host = host.map(|h| String::from_utf16_lossy(&h[..h.len() - 1])), + "title path" + ); +} + +/// A narrow path (ANSI code page, as the host decodes it) on a virtual +/// drive, as a wide host path. +fn narrow(path: *const c_char) -> Option> { + if path.is_null() { + return None; + } + // SAFETY: the title passes a NUL-terminated path. + let bytes = unsafe { CStr::from_ptr(path) }.to_bytes(); + // The drive part is ASCII in every code page; decode only candidates. + match bytes.strip_prefix(br"\\?\").unwrap_or(bytes) { + [letter, b':', ..] if letter.is_ascii_alphabetic() => {} + _ => { + tracing::debug!(path = %String::from_utf8_lossy(bytes), "title path"); + return None; + } + } + let len = i32::try_from(bytes.len()).ok()?; + // SAFETY: sizing call, then a call with room for `n` units. + let wide = unsafe { + let n = MultiByteToWideChar(CP_ACP, 0, bytes.as_ptr(), len, std::ptr::null_mut(), 0); + let mut wide = vec![0u16; usize::try_from(n).ok()?]; + MultiByteToWideChar(CP_ACP, 0, bytes.as_ptr(), len, wide.as_mut_ptr(), n); + wide + }; + let host = translate(&wide); + trace(&wide, host.as_deref()); + host +} + +/// An ASCII mode string (`"rb"`, `"w, ccs=UTF-8"`) for a wide CRT call. +fn widen(mode: *const c_char) -> Vec { + if mode.is_null() { + return vec![0]; + } + // SAFETY: a NUL-terminated mode string. + let bytes = unsafe { CStr::from_ptr(mode) }.to_bytes(); + bytes.iter().map(|&b| u16::from(b)).chain([0]).collect() +} + +type Handle = *mut c_void; +type File = *mut c_void; + +// kernel32 and its file API sets. + +pub extern "system" fn CreateFileW( + path: *const u16, + access: u32, + share: u32, + security: *const c_void, + disposition: u32, + flags: u32, + template: Handle, +) -> Handle { + let p = wide(path); + host!("kernel32.dll", "CreateFileW": extern "system" fn(*const u16, u32, u32, *const c_void, u32, u32, Handle) -> Handle)( + p.ptr(), + access, + share, + security, + disposition, + flags, + template, + ) +} + +pub extern "system" fn CreateFileA( + path: *const c_char, + access: u32, + share: u32, + security: *const c_void, + disposition: u32, + flags: u32, + template: Handle, +) -> Handle { + match narrow(path) { + Some(p) => { + host!("kernel32.dll", "CreateFileW": extern "system" fn(*const u16, u32, u32, *const c_void, u32, u32, Handle) -> Handle)( + p.as_ptr(), + access, + share, + security, + disposition, + flags, + template, + ) + } + None => { + host!("kernel32.dll", "CreateFileA": extern "system" fn(*const c_char, u32, u32, *const c_void, u32, u32, Handle) -> Handle)( + path, + access, + share, + security, + disposition, + flags, + template, + ) + } + } +} + +/// Used by Bink. +pub extern "system" fn CreateFile2( + path: *const u16, + access: u32, + share: u32, + disposition: u32, + params: *const c_void, +) -> Handle { + let p = wide(path); + host!("kernel32.dll", "CreateFile2": extern "system" fn(*const u16, u32, u32, u32, *const c_void) -> Handle)( + p.ptr(), + access, + share, + disposition, + params, + ) +} + +pub extern "system" fn DeleteFileA(path: *const c_char) -> i32 { + match narrow(path) { + Some(p) => { + host!("kernel32.dll", "DeleteFileW": extern "system" fn(*const u16) -> i32)(p.as_ptr()) + } + None => { + host!("kernel32.dll", "DeleteFileA": extern "system" fn(*const c_char) -> i32)(path) + } + } +} + +pub extern "system" fn DeleteFileW(path: *const u16) -> i32 { + let p = wide(path); + host!("kernel32.dll", "DeleteFileW": extern "system" fn(*const u16) -> i32)(p.ptr()) +} + +pub extern "system" fn RemoveDirectoryW(path: *const u16) -> i32 { + let p = wide(path); + host!("kernel32.dll", "RemoveDirectoryW": extern "system" fn(*const u16) -> i32)(p.ptr()) +} + +pub extern "system" fn SetFileAttributesW(path: *const u16, attributes: u32) -> i32 { + let p = wide(path); + host!("kernel32.dll", "SetFileAttributesW": extern "system" fn(*const u16, u32) -> i32)( + p.ptr(), + attributes, + ) +} + +pub extern "system" fn GetFileAttributesA(path: *const c_char) -> u32 { + match narrow(path) { + Some(p) => { + host!("kernel32.dll", "GetFileAttributesW": extern "system" fn(*const u16) -> u32)( + p.as_ptr(), + ) + } + None => { + host!("kernel32.dll", "GetFileAttributesA": extern "system" fn(*const c_char) -> u32)( + path, + ) + } + } +} + +pub extern "system" fn CreateDirectoryW(path: *const u16, security: *const c_void) -> i32 { + let p = wide(path); + host!("kernel32.dll", "CreateDirectoryW": extern "system" fn(*const u16, *const c_void) -> i32)( + p.ptr(), + security, + ) +} + +pub extern "system" fn GetFileAttributesExW( + path: *const u16, + level: i32, + info: *mut c_void, +) -> i32 { + let p = wide(path); + host!("kernel32.dll", "GetFileAttributesExW": extern "system" fn(*const u16, i32, *mut c_void) -> i32)( + p.ptr(), + level, + info, + ) +} + +pub extern "system" fn GetFileAttributesW(path: *const u16) -> u32 { + let p = wide(path); + host!("kernel32.dll", "GetFileAttributesW": extern "system" fn(*const u16) -> u32)(p.ptr()) +} + +pub extern "system" fn GetDiskFreeSpaceExW( + path: *const u16, + available: *mut u64, + total: *mut u64, + free: *mut u64, +) -> i32 { + let p = wide(path); + host!("kernel32.dll", "GetDiskFreeSpaceExW": extern "system" fn(*const u16, *mut u64, *mut u64, *mut u64) -> i32)( + p.ptr(), + available, + total, + free, + ) +} + +/// Wants a volume root: a virtual drive answers for the host volume its +/// folder is on. +pub extern "system" fn GetDiskFreeSpaceW( + root: *const u16, + sectors_per_cluster: *mut u32, + bytes_per_sector: *mut u32, + free_clusters: *mut u32, + clusters: *mut u32, +) -> i32 { + let mut p = wide(root); + if let Some(host) = &mut p.1 + && let [letter, colon, sep, ..] = host[..] + && colon == u16::from(b':') + && SEPARATORS.contains(&sep) + { + *host = vec![letter, colon, sep, 0]; + } + host!("kernel32.dll", "GetDiskFreeSpaceW": extern "system" fn(*const u16, *mut u32, *mut u32, *mut u32, *mut u32) -> i32)( + p.ptr(), + sectors_per_cluster, + bytes_per_sector, + free_clusters, + clusters, + ) +} + +pub extern "system" fn FindFirstFileW(path: *const u16, data: *mut c_void) -> Handle { + let p = wide(path); + host!("kernel32.dll", "FindFirstFileW": extern "system" fn(*const u16, *mut c_void) -> Handle)( + p.ptr(), + data, + ) +} + +pub extern "system" fn FindFirstFileExW( + path: *const u16, + level: i32, + data: *mut c_void, + search: i32, + filter: *mut c_void, + flags: u32, +) -> Handle { + let p = wide(path); + host!("kernel32.dll", "FindFirstFileExW": extern "system" fn(*const u16, i32, *mut c_void, i32, *mut c_void, u32) -> Handle)( + p.ptr(), + level, + data, + search, + filter, + flags, + ) +} + +pub extern "system" fn MoveFileExW(from: *const u16, to: *const u16, flags: u32) -> i32 { + let (from, to) = (wide(from), wide(to)); + host!("kernel32.dll", "MoveFileExW": extern "system" fn(*const u16, *const u16, u32) -> i32)( + from.ptr(), + to.ptr(), + flags, + ) +} + +pub extern "system" fn SetCurrentDirectoryA(path: *const c_char) -> i32 { + match narrow(path) { + Some(p) => { + host!("kernel32.dll", "SetCurrentDirectoryW": extern "system" fn(*const u16) -> i32)( + p.as_ptr(), + ) + } + None => { + host!("kernel32.dll", "SetCurrentDirectoryA": extern "system" fn(*const c_char) -> i32)( + path, + ) + } + } +} + +// The C runtime (ucrtbase, which the title's CRT imports bind to). + +pub extern "C" fn _wfopen(path: *const u16, mode: *const u16) -> File { + let p = wide(path); + host!("ucrtbase.dll", "_wfopen": extern "C" fn(*const u16, *const u16) -> File)(p.ptr(), mode) +} + +pub extern "C" fn _wfopen_s(out: *mut File, path: *const u16, mode: *const u16) -> i32 { + let p = wide(path); + host!("ucrtbase.dll", "_wfopen_s": extern "C" fn(*mut File, *const u16, *const u16) -> i32)( + out, + p.ptr(), + mode, + ) +} + +pub extern "C" fn _wfsopen(path: *const u16, mode: *const u16, share: i32) -> File { + let p = wide(path); + host!("ucrtbase.dll", "_wfsopen": extern "C" fn(*const u16, *const u16, i32) -> File)( + p.ptr(), + mode, + share, + ) +} + +// Kernel reads into title memory. The GPU side leaves blocks of title GPU +// buffers read-only to see the title's next write, and the kernel's writes +// fail there instead of faulting into its handler; the title's +// synchronous reads (title+0x313fc0) read straight into 4 KiB-aligned +// destinations and retry a failed `ReadFile` forever. So the destination +// is opened first. A block guarded again before the kernel writes it (the +// guard over all the views of a page protects other views from other +// threads) fails that `ReadFile`, and the title's retry opens it again; +// `fread` has no such retry and reads beside instead (see there). + +pub extern "system" fn ReadFile( + file: *mut c_void, + buffer: *mut u8, + len: u32, + read: *mut u32, + overlapped: *mut c_void, +) -> i32 { + leonida_gpu::kernel_will_write(buffer as usize, len as usize); + host!("kernel32.dll", "ReadFile": extern "system" fn(*mut c_void, *mut u8, u32, *mut u32, *mut c_void) -> i32)( + file, buffer, len, read, overlapped, + ) +} + +/// The host CRT reads large requests straight into the caller's buffer +/// through the kernel, whose write fails on a guarded block instead of +/// faulting into the guard. So the bytes are read beside, a chunk at a time +/// (a caller may ask for far more than the file holds), and copied in from +/// user mode, where a guarded block faults into the guard like the title's +/// own writes. Returns the items read, as the CRT does; the bytes of a +/// partial last item are copied too, as the CRT leaves them. +pub extern "C" fn fread(buffer: *mut u8, size: usize, count: usize, stream: File) -> usize { + let read = host!("ucrtbase.dll", "fread": extern "C" fn(*mut u8, usize, usize, File) -> usize); + let total = size.saturating_mul(count); + if buffer.is_null() || total == 0 { + // The CRT's own checks and answer (EINVAL, or nothing to read). + return read(buffer, size, count, stream); + } + const CHUNK: usize = 1 << 20; + let mut beside = vec![0u8; total.min(CHUNK)]; + let mut done = 0; + while done < total { + let want = (total - done).min(CHUNK); + let n = read(beside.as_mut_ptr(), 1, want, stream); + if n > 0 { + leonida_gpu::kernel_will_write(buffer as usize + done, n); + // SAFETY: the caller's buffer holds `size * count` bytes, and + // `done + n` is at most that. + unsafe { std::ptr::copy_nonoverlapping(beside.as_ptr(), buffer.add(done), n) }; + done += n; + } + if n < want { + break; + } + } + done / size +} + +pub extern "C" fn fopen(path: *const c_char, mode: *const c_char) -> File { + match narrow(path) { + Some(p) => host!("ucrtbase.dll", "_wfopen": extern "C" fn(*const u16, *const u16) -> File)( + p.as_ptr(), + widen(mode).as_ptr(), + ), + None => { + host!("ucrtbase.dll", "fopen": extern "C" fn(*const c_char, *const c_char) -> File)( + path, mode, + ) + } + } +} + +pub extern "C" fn fopen_s(out: *mut File, path: *const c_char, mode: *const c_char) -> i32 { + match narrow(path) { + Some(p) => { + host!("ucrtbase.dll", "_wfopen_s": extern "C" fn(*mut File, *const u16, *const u16) -> i32)( + out, + p.as_ptr(), + widen(mode).as_ptr(), + ) + } + None => { + host!("ucrtbase.dll", "fopen_s": extern "C" fn(*mut File, *const c_char, *const c_char) -> i32)( + out, path, mode, + ) + } + } +} + +/// `_open(path, flags[, mode])` is variadic; on x64 the optional integer +/// travels in the same register either way, so it is passed on as is. +pub extern "C" fn _open(path: *const c_char, flags: i32, mode: i32) -> i32 { + match narrow(path) { + Some(p) => host!("ucrtbase.dll", "_wopen": extern "C" fn(*const u16, i32, i32) -> i32)( + p.as_ptr(), + flags, + mode, + ), + None => host!("ucrtbase.dll", "_open": extern "C" fn(*const c_char, i32, i32) -> i32)( + path, flags, mode, + ), + } +} + +/// See [`_open`]; used by libHttpClient. +pub extern "C" fn _wopen(path: *const u16, flags: i32, mode: i32) -> i32 { + let p = wide(path); + host!("ucrtbase.dll", "_wopen": extern "C" fn(*const u16, i32, i32) -> i32)( + p.ptr(), + flags, + mode, + ) +} + +pub extern "C" fn _wstat64(path: *const u16, stat: *mut c_void) -> i32 { + let p = wide(path); + host!("ucrtbase.dll", "_wstat64": extern "C" fn(*const u16, *mut c_void) -> i32)(p.ptr(), stat) +} + +pub extern "C" fn _stat64i32(path: *const c_char, stat: *mut c_void) -> i32 { + match narrow(path) { + Some(p) => { + host!("ucrtbase.dll", "_wstat64i32": extern "C" fn(*const u16, *mut c_void) -> i32)( + p.as_ptr(), + stat, + ) + } + None => { + host!("ucrtbase.dll", "_stat64i32": extern "C" fn(*const c_char, *mut c_void) -> i32)( + path, stat, + ) + } + } +} + +pub extern "C" fn remove(path: *const c_char) -> i32 { + match narrow(path) { + Some(p) => host!("ucrtbase.dll", "_wremove": extern "C" fn(*const u16) -> i32)(p.as_ptr()), + None => host!("ucrtbase.dll", "remove": extern "C" fn(*const c_char) -> i32)(path), + } +} + +pub extern "C" fn _wchmod(path: *const u16, mode: i32) -> i32 { + let p = wide(path); + host!("ucrtbase.dll", "_wchmod": extern "C" fn(*const u16, i32) -> i32)(p.ptr(), mode) +} + +pub extern "C" fn _wutime64(path: *const u16, times: *mut c_void) -> i32 { + let p = wide(path); + host!("ucrtbase.dll", "_wutime64": extern "C" fn(*const u16, *mut c_void) -> i32)( + p.ptr(), + times, + ) +} + +// The C++ library: `std::basic_filebuf::open` goes through `_Fiopen`. + +const FIOPEN: &str = "?_Fiopen@std@@YAPEAU_iobuf@@PEBDHH@Z"; +const FIOPEN_WIDE: &str = "?_Fiopen@std@@YAPEAU_iobuf@@PEB_WHH@Z"; + +/// `_Fiopen(const wchar_t* path, ios_base::openmode, int protection)`. +extern "C" fn fiopen_wide(path: *const u16, mode: i32, protection: i32) -> File { + let p = wide(path); + host!("msvcp140.dll", "?_Fiopen@std@@YAPEAU_iobuf@@PEB_WHH@Z": extern "C" fn(*const u16, i32, i32) -> File)( + p.ptr(), + mode, + protection, + ) +} + +/// `_Fiopen(const char* path, ios_base::openmode, int protection)`. +extern "C" fn fiopen(path: *const c_char, mode: i32, protection: i32) -> File { + match narrow(path) { + Some(p) => { + host!("msvcp140.dll", "?_Fiopen@std@@YAPEAU_iobuf@@PEB_WHH@Z": extern "C" fn(*const u16, i32, i32) -> File)( + p.as_ptr(), + mode, + protection, + ) + } + None => { + host!("msvcp140.dll", "?_Fiopen@std@@YAPEAU_iobuf@@PEBDHH@Z": extern "C" fn(*const c_char, i32, i32) -> File)( + path, mode, protection, + ) + } + } +} + +pub(crate) fn module() -> HleModule { + HleModule { + name: "files", + dlls: &[ + "kernel32.dll", + "kernelbase.dll", + "api-ms-win-core-file-*", + "api-ms-win-core-processenvironment-*", + "ucrtbase.dll", + "api-ms-win-crt-stdio-*", + "api-ms-win-crt-filesystem-*", + "api-ms-win-crt-time-*", + "msvcp140.dll", + ], + exports: vec![ + hle_export!(ReadFile), + hle_export!(fread), + hle_export!(CreateFileW), + hle_export!(CreateFileA), + hle_export!(CreateFile2), + hle_export!(DeleteFileA), + hle_export!(DeleteFileW), + hle_export!(RemoveDirectoryW), + hle_export!(SetFileAttributesW), + hle_export!(GetFileAttributesA), + hle_export!(CreateDirectoryW), + hle_export!(GetFileAttributesW), + hle_export!(GetFileAttributesExW), + hle_export!(GetDiskFreeSpaceExW), + hle_export!(GetDiskFreeSpaceW), + hle_export!(FindFirstFileW), + hle_export!(FindFirstFileExW), + hle_export!(MoveFileExW), + hle_export!(SetCurrentDirectoryA), + hle_export!(_wfopen), + hle_export!(_wfopen_s), + hle_export!(_wfsopen), + hle_export!(fopen), + hle_export!(fopen_s), + hle_export!(_open), + hle_export!(_wopen), + hle_export!(_wstat64), + hle_export!(_stat64i32), + hle_export!(remove), + hle_export!(_wchmod), + hle_export!(_wutime64), + HleExport { + name: FIOPEN, + address: fiopen as *const () as usize, + }, + HleExport { + name: FIOPEN_WIDE, + address: fiopen_wide as *const () as usize, + }, + ], + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn w(s: &str) -> Vec { + s.encode_utf16().chain([0]).collect() + } + + #[test] + fn kernel_reads_reach_the_buffer() { + use std::os::windows::io::AsRawHandle; + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("data.bin"); + std::fs::write(&path, b"0123456789").unwrap(); + let file = std::fs::File::open(&path).unwrap(); + let (mut out, mut n) = ([0u8; 10], 0); + let handle = file.as_raw_handle().cast(); + assert_ne!(ReadFile(handle, out.as_mut_ptr(), 10, &mut n, std::ptr::null_mut()), 0); + assert_eq!((&out, n), (b"0123456789", 10)); + } + + #[test] + fn fread_reads_beside_in_chunks() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("data.bin"); + // Over two chunks, and not a whole number of 3-byte items. + let bytes: Vec = (0..(5 << 19) + 1).map(|i| (i * 7 + i / 251) as u8).collect(); + std::fs::write(&path, &bytes).unwrap(); + let fclose = host!("ucrtbase.dll", "fclose": extern "C" fn(File) -> i32); + let open = || { + let f = _wfopen(w(&path.to_string_lossy()).as_ptr(), w("rb").as_ptr()); + assert!(!f.is_null()); + f + }; + + // Asked for far more than the file holds: the whole file, in items. + let f = open(); + let mut out = vec![0xaau8; bytes.len() + 64]; + let items = fread(out.as_mut_ptr(), 3, out.len() / 3, f); + assert_eq!(items, bytes.len() / 3); + assert_eq!(&out[..bytes.len()], &bytes[..], "the partial last item's bytes too"); + assert!(out[bytes.len()..].iter().all(|&b| b == 0xaa), "nothing past what was read"); + fclose(f); + + // Exact reads continue where the last one stopped. + let f = open(); + let mut a = vec![0u8; 1000]; + let mut b = vec![0u8; (1 << 20) + 5]; + assert_eq!(fread(a.as_mut_ptr(), 1000, 1, f), 1); + assert_eq!(fread(b.as_mut_ptr(), 1, b.len(), f), b.len()); + assert_eq!(a, bytes[..1000]); + assert_eq!(b, bytes[1000..1000 + b.len()]); + fclose(f); + } + + fn text(v: &[u16]) -> String { + String::from_utf16_lossy(&v[..v.len() - 1]) + } + + #[test] + fn rewrites_only_paths_on_mounted_drives() { + let dir = tempfile::tempdir().unwrap(); + let root = dir.path().to_string_lossy().into_owned(); + let letter = mount(dir.path()).unwrap(); + assert_eq!( + mount(dir.path()), + Some(letter), + "mounting twice reuses the letter" + ); + let tr = |s: String| translate(&w(&s)[..s.encode_utf16().count()]).map(|v| text(&v)); + assert_eq!( + tr(format!("{letter}:/a/b.txt")), + Some(format!("{root}/a/b.txt")) + ); + let lower = letter.to_ascii_lowercase(); + assert_eq!(tr(format!("{lower}:\\a")), Some(format!("{root}\\a"))); + assert_eq!(tr(format!("{letter}:")), Some(format!("{root}\\"))); + assert_eq!( + tr(format!(r"\\?\{letter}:/a/b")), + Some(format!(r"\\?\{root}\a\b")) + ); + assert_eq!(tr(r"C:\Windows".into()), None); + assert_eq!(tr("relative/path".into()), None); + assert_eq!(tr(String::new()), None); + + // Fixed letters, as the console's package drive; a later mount of + // the same letter replaces the earlier one. + let package = tempfile::tempdir().unwrap(); + mount_at('g', dir.path()); + mount_at('G', package.path()); + assert_eq!( + tr(r"G:\appdata0.rpf".into()), + Some(format!(r"{}\appdata0.rpf", package.path().display())) + ); + assert_ne!(mount(dir.path()), Some('G'), "free letters skip fixed ones"); + + // Long ones take the `\\?\` form, cleaned up as the host would. + let long = "d".repeat(250); + assert_eq!( + tr(format!(r"G:/a/./b/../{long}//f")), + Some(format!(r"\\?\{}\a\{long}\f", package.path().display())) + ); + assert_eq!( + verbatim(&w(r"\\server\share\")[..15], &w("/x/../../y")[..10]), + w(r"\\?\UNC\server\share\y")[..22].to_vec() + ); + } + + #[test] + fn long_title_paths_work_on_the_host() { + let dir = tempfile::tempdir().unwrap(); + let letter = mount(dir.path()).unwrap(); + let deep = format!("{letter}:/{}/{}", "a".repeat(200), "b".repeat(100)); + let null = std::ptr::null_mut(); + let first = w(&deep[..203]); + assert_ne!(CreateDirectoryW(first.as_ptr(), null), 0); + assert_ne!(CreateDirectoryW(w(&deep).as_ptr(), null), 0); + let file = format!("{deep}/../{}/f.txt", "b".repeat(100)); + let f = _wfopen(w(&file).as_ptr(), w("wb").as_ptr()); + assert!(!f.is_null(), "{file}"); + host!("ucrtbase.dll", "fclose": extern "C" fn(File) -> i32)(f); + assert_ne!(DeleteFileW(w(&format!("{deep}/f.txt")).as_ptr()), 0); + assert_ne!(RemoveDirectoryW(w(&deep).as_ptr()), 0); + } + + #[test] + fn title_file_calls_land_in_the_host_folder() { + let dir = tempfile::tempdir().unwrap(); + let letter = mount(dir.path()).unwrap(); + const GENERIC_WRITE: u32 = 0x4000_0000; + const CREATE_ALWAYS: u32 = 2; + let close = host!("kernel32.dll", "CloseHandle": extern "system" fn(Handle) -> i32); + let fclose = host!("ucrtbase.dll", "fclose": extern "C" fn(File) -> i32); + + let path = w(&format!(r"{letter}:\created.bin")); + let null = std::ptr::null_mut(); + let h = CreateFileW( + path.as_ptr(), + GENERIC_WRITE, + 0, + null, + CREATE_ALWAYS, + 0, + null, + ); + assert_ne!(h as isize, -1); + close(h); + assert!(dir.path().join("created.bin").is_file()); + + let path = format!("{letter}:/opened.txt\0"); + let f = fopen(path.as_ptr().cast(), c"wb".as_ptr()); + assert!(!f.is_null()); + fclose(f); + assert!(dir.path().join("opened.txt").is_file()); + + let path = format!("{letter}:/stream.txt\0"); + const OUT: i32 = 2; + let f = fiopen(path.as_ptr().cast(), OUT, 0x40); + assert!(!f.is_null()); + fclose(f); + assert!(dir.path().join("stream.txt").is_file()); + + assert_eq!(remove(path.as_ptr().cast()), 0); + assert!(!dir.path().join("stream.txt").exists()); + let f = fiopen_wide(w(&format!("{letter}:/wide.txt")).as_ptr(), OUT, 0x40); + assert!(!f.is_null()); + fclose(f); + assert!(dir.path().join("wide.txt").is_file()); + + const OPEN_EXISTING: u32 = 3; + let path = w(&format!(r"{letter}:\created.bin")); + let h = CreateFile2(path.as_ptr(), GENERIC_WRITE, 0, OPEN_EXISTING, null); + assert_ne!(h as isize, -1); + close(h); + const INVALID_FILE_ATTRIBUTES: u32 = u32::MAX; + assert_ne!(GetFileAttributesW(path.as_ptr()), INVALID_FILE_ATTRIBUTES); + + const O_WRONLY: i32 = 1; + const O_CREAT: i32 = 0x100; + const S_IWRITE: i32 = 0x80; + let path = format!("{letter}:/low.bin\0"); + let fd = _open(path.as_ptr().cast(), O_WRONLY | O_CREAT, S_IWRITE); + assert!(fd >= 0); + host!("ucrtbase.dll", "_close": extern "C" fn(i32) -> i32)(fd); + assert!(dir.path().join("low.bin").is_file()); + + // Other paths pass through untouched. + let host_path = format!("{}\0", dir.path().join("plain.txt").display()); + let f = fopen(host_path.as_ptr().cast(), c"wb".as_ptr()); + assert!(!f.is_null()); + fclose(f); + assert!(dir.path().join("plain.txt").is_file()); + } + + /// A narrow path is rewritten once, as its wide twin is. The inner + /// drive's folder lies on the outer virtual drive, as the title folder + /// does when it sits on a host `G:` drive and is mounted as `G:`. The + /// outer letter is no host drive, so the host finds nothing there; a + /// narrow call that reaches the outer folder rewrote the path twice. + #[test] + fn narrow_paths_are_rewritten_once() { + let dir = tempfile::tempdir().unwrap(); + let folder = dir.path().join("inner"); + std::fs::create_dir(&folder).unwrap(); + std::fs::write(folder.join("present.txt"), b"").unwrap(); + let outer = mount(dir.path()).unwrap(); + let inner = mount(Path::new(&format!(r"{outer}:\inner"))).unwrap(); + let path = |name: &str| format!("{inner}:/{name}\0"); + + const INVALID_FILE_ATTRIBUTES: u32 = u32::MAX; + let wide = GetFileAttributesW(w(&format!("{inner}:/present.txt")).as_ptr()); + assert_eq!(wide, INVALID_FILE_ATTRIBUTES); + let narrow = GetFileAttributesA(path("present.txt").as_ptr().cast()); + assert_eq!(narrow, wide, "GetFileAttributesA agrees with its wide twin"); + + const GENERIC_WRITE: u32 = 0x4000_0000; + const CREATE_ALWAYS: u32 = 2; + let null = std::ptr::null_mut(); + let h = CreateFileA( + path("a.bin").as_ptr().cast(), + GENERIC_WRITE, + 0, + null, + CREATE_ALWAYS, + 0, + null, + ); + assert_eq!(h as isize, -1); + assert!(fopen(path("b.txt").as_ptr().cast(), c"wb".as_ptr()).is_null()); + let mut f: File = std::ptr::null_mut(); + let error = fopen_s(&mut f, path("c.txt").as_ptr().cast(), c"wb".as_ptr()); + assert_ne!(error, 0); + const OUT: i32 = 2; + assert!(fiopen(path("d.txt").as_ptr().cast(), OUT, 0x40).is_null()); + + // Nothing was made behind a path rewritten twice. + let names: Vec<_> = std::fs::read_dir(&folder) + .unwrap() + .map(|e| e.unwrap().file_name()) + .collect(); + assert_eq!(names, ["present.txt"]); + } +} diff --git a/crates/leonida-hle/src/modules/gameinput.rs b/crates/leonida-hle/src/modules/gameinput.rs new file mode 100644 index 000000000..1b47cb134 --- /dev/null +++ b/crates/leonida-hle/src/modules/gameinput.rs @@ -0,0 +1,1629 @@ +//! `gameinput.dll`: input devices from the host. Gamepads come from XInput +//! (host slots 0-3); while none is connected, the keyboard drives one +//! stand-in gamepad (`FALLBACK_BUTTONS`). The keyboard is a device of its own +//! too. A poll thread turns host state into readings (a new one per change) +//! and runs device callbacks on connect and disconnect. +#![allow(non_snake_case)] +// Title code calls these through the objects, passing pointers the real API +// would trust. +#![allow(clippy::not_unsafe_ptr_arg_deref)] + +use std::collections::VecDeque; +use std::ffi::c_void; +use std::ops::Deref; +use std::ptr::NonNull; +use std::sync::atomic::{AtomicU32, AtomicU64, Ordering}; +use std::sync::{Condvar, LazyLock, Mutex, MutexGuard, PoisonError}; +use std::thread::ThreadId; +use std::time::{Duration, Instant}; + +use super::xasync::{E_INVALIDARG, E_NOTIMPL}; +use super::xgameruntime::{HRESULT, S_OK}; +use crate::{HleExport, HleModule}; + +/// The documented errors. +pub const DEVICE_DISCONNECTED: HRESULT = 0x838A_0001_u32 as i32; +pub const DEVICE_NOT_FOUND: HRESULT = 0x838A_0002_u32 as i32; +pub const READING_NOT_FOUND: HRESULT = 0x838A_0003_u32 as i32; +pub const REFERENCE_TOO_OLD: HRESULT = 0x838A_0004_u32 as i32; +const E_NOINTERFACE: HRESULT = 0x8000_4002_u32 as i32; + +/// Input kinds (bits) our devices have. +const KEYBOARD_KIND: u32 = 0x10; +const GAMEPAD_KIND: u32 = 0x4_0000; +/// Device status of a connected device: connected, input enabled. +const STATUS_CONNECTED: u32 = 0x3; +const ASYNC_ENUMERATION: u32 = 1; + +/// Gamepad buttons; the title maps each bit to one of its pad buttons. +const MENU: u32 = 0x1; +const VIEW: u32 = 0x2; +const A: u32 = 0x4; +const B: u32 = 0x8; +const X: u32 = 0x10; +const Y: u32 = 0x20; +const UP: u32 = 0x40; +const DOWN: u32 = 0x80; +const LEFT: u32 = 0x100; +const RIGHT: u32 = 0x200; +const LEFT_SHOULDER: u32 = 0x400; +const RIGHT_SHOULDER: u32 = 0x800; +const LEFT_STICK: u32 = 0x1000; +const RIGHT_STICK: u32 = 0x2000; + +/// Devices: host pad slots, the keyboard's stand-in pad, the keyboard. +const PADS: usize = 4; +const FALLBACK: usize = PADS; +const KEYBOARD: usize = PADS + 1; +const DEVICES: usize = PADS + 2; + +/// Readings kept per device for next/previous lookups. +const HISTORY: usize = 256; +const POLL: Duration = Duration::from_millis(8); + +/// The keyboard's stand-in gamepad (virtual key, button); README lists it. +/// Sticks: W/A/S/D left, I/J/K/L right; triggers Z and C. +const FALLBACK_BUTTONS: [(u8, u32); 14] = [ + (0x1B, MENU), // Esc + (0x09, VIEW), // Tab + (0x0D, A), // Enter + (0x08, B), // Backspace + (b'X', X), + (b'Y', Y), + (0x26, UP), // arrows + (0x28, DOWN), + (0x25, LEFT), + (0x27, RIGHT), + (b'Q', LEFT_SHOULDER), + (b'E', RIGHT_SHOULDER), + (b'F', LEFT_STICK), + (b'H', RIGHT_STICK), +]; + +/// A gamepad reading: triggers 0 to 1, sticks -1 to 1 (up positive). +#[repr(C)] +#[derive(Clone, Copy, Debug, Default, PartialEq)] +struct PadState { + buttons: u32, + left_trigger: f32, + right_trigger: f32, + left_x: f32, + left_y: f32, + right_x: f32, + right_y: f32, +} + +/// One key held down: scan code (0xE0xx when extended), character, key. +#[repr(C)] +#[derive(Clone, Copy, Debug, Default, PartialEq)] +struct KeyState { + scan_code: u32, + code_point: u32, + virtual_key: u8, + dead_key: bool, +} + +const _: () = assert!(size_of::() == 12 && size_of::() == 28); + +/// Host input, or a fake in tests. +trait Source: Send { + /// The pad in host slot `slot`, `None` when the slot is empty. + fn pad(&mut self, slot: usize) -> Option; + /// Keys held down; none while the title's window lacks focus. + fn keys(&mut self) -> Vec; + /// Motor speeds: low frequency (left), high frequency (right). + fn rumble(&mut self, slot: usize, low: u16, high: u16); +} + +fn fallback(keys: &[KeyState]) -> PadState { + let on = |vk: u8| { + if keys.iter().any(|k| k.virtual_key == vk) { + 1.0 + } else { + 0.0 + } + }; + PadState { + buttons: FALLBACK_BUTTONS + .iter() + .filter(|(vk, _)| on(*vk) != 0.0) + .fold(0, |all, (_, bit)| all | bit), + left_trigger: on(b'Z'), + right_trigger: on(b'C'), + left_x: on(b'D') - on(b'A'), + left_y: on(b'W') - on(b'S'), + right_x: on(b'L') - on(b'J'), + right_y: on(b'I') - on(b'K'), + } +} + +#[repr(C)] +struct Table([*const (); N]); +// SAFETY: function addresses only. +unsafe impl Sync for Table {} + +/// The input object; one per hub. +#[repr(C)] +pub struct Object { + vtable: &'static Table<22>, + hub: *const Hub, +} + +#[repr(C)] +pub struct Device { + vtable: &'static Table<21>, + hub: *const Hub, + index: usize, + info: DeviceInfo, +} + +/// What a device says about itself. The title reads `id` (+0x20); the rest +/// follows the public layout and is zero where we have nothing to say. +#[repr(C)] +#[derive(Default)] +#[allow(dead_code)] // read by title code +struct DeviceInfo { + size: u32, + vendor: u16, + product: u16, + revision: u16, + interface: u8, + collection: u8, + usage: [u16; 2], + versions: [u16; 8], + id: [u8; 32], + root_id: [u8; 32], + family: i32, + capabilities: u32, + supported_input: u32, + rumble_motors: u32, + /// Counts and optional detail pointers. + rest: [u64; 26], +} + +const _: () = assert!(std::mem::offset_of!(DeviceInfo, id) == 0x20); + +fn kind(index: usize) -> u32 { + if index == KEYBOARD { + KEYBOARD_KIND + } else { + GAMEPAD_KIND + } +} + +impl Device { + fn new(index: usize) -> Device { + let mut id = [0; 32]; + id[..7].copy_from_slice(b"leonida"); + id[31] = index as u8 + 1; + let info = DeviceInfo { + size: size_of::() as u32, + id, + root_id: id, + supported_input: kind(index), + // Low and high frequency. + rumble_motors: if index < PADS { 0x3 } else { 0 }, + ..Default::default() + }; + Device { + vtable: &DEVICE, + hub: std::ptr::null(), + index, + info, + } + } + + fn hub(&self) -> &'static Hub { + // SAFETY: set by `Hub::new`; hubs are never freed. + unsafe { &*self.hub } + } +} + +#[derive(PartialEq)] +enum Value { + Pad(PadState), + Keys(Vec), +} + +#[repr(C)] +pub struct Reading { + vtable: &'static Table<25>, + refs: AtomicU32, + device: *const Device, + sequence: u64, + timestamp: u64, + value: Value, +} + +impl Reading { + fn kind(&self) -> u32 { + match self.value { + Value::Pad(_) => GAMEPAD_KIND, + Value::Keys(_) => KEYBOARD_KIND, + } + } +} + +/// A counted reference to a reading. +struct Ref(NonNull); + +impl Ref { + fn new(reading: Reading) -> Ref { + Ref(NonNull::from(Box::leak(Box::new(reading)))) + } + + /// Another reference, for the title. + fn share(&self) -> *const Reading { + reading_add_ref(self.0.as_ptr()); + self.0.as_ptr() + } +} + +impl Deref for Ref { + type Target = Reading; + fn deref(&self) -> &Reading { + // SAFETY: we hold a reference, so it is alive. + unsafe { self.0.as_ref() } + } +} + +impl Drop for Ref { + fn drop(&mut self) { + reading_release(self.0.as_ptr()); + } +} + +type DeviceCallback = extern "system" fn(u64, *mut c_void, *const Device, u64, u32, u32); + +#[derive(Clone, Copy)] +struct Registration { + token: u64, + /// One device's address, or 0 for any. + device: usize, + kind: u32, + status: u32, + context: usize, + callback: DeviceCallback, +} + +impl Registration { + fn matches(&self, devices: &[Device; DEVICES], index: usize) -> bool { + kind(index) & self.kind != 0 + && (self.device == 0 || self.device == &devices[index] as *const Device as usize) + } + + fn event(&self, device: usize, timestamp: u64, current: u32, previous: u32) -> Event { + Event { + registration: *self, + device, + timestamp, + current, + previous, + } + } +} + +struct Event { + registration: Registration, + device: usize, + timestamp: u64, + current: u32, + previous: u32, +} + +#[derive(Default)] +struct Slot { + connected: bool, + sequence: u64, + history: VecDeque, +} + +struct State { + slots: [Slot; DEVICES], + callbacks: Vec, + /// Asynchronous enumerations, delivered by the next poll. + pending: Vec, + /// Device callbacks running now: token and thread. + running: Vec<(u64, ThreadId)>, +} + +pub struct Hub { + object: Object, + devices: [Device; DEVICES], + /// Apart from the state: XInput can be slow, and the title reads + /// readings every frame. + source: Mutex>, + state: Mutex, + /// A device callback returned. + returned: Condvar, +} + +fn lock(mutex: &Mutex) -> MutexGuard<'_, T> { + mutex.lock().unwrap_or_else(PoisonError::into_inner) +} + +// SAFETY: the back pointers are set before the hub is shared and never +// change; what changes sits behind the mutex or is atomic. +unsafe impl Send for Hub {} +// SAFETY: as above. +unsafe impl Sync for Hub {} + +static START: LazyLock = LazyLock::new(Instant::now); + +/// Microseconds, the clock of every timestamp we hand out. +fn now() -> u64 { + START.elapsed().as_micros() as u64 +} + +impl Hub { + fn new(source: Box) -> &'static Hub { + let hub = Box::into_raw(Box::new(Hub { + object: Object { + vtable: &INPUT, + hub: std::ptr::null(), + }, + devices: std::array::from_fn(Device::new), + source: Mutex::new(source), + state: Mutex::new(State { + slots: Default::default(), + callbacks: Vec::new(), + pending: Vec::new(), + running: Vec::new(), + }), + returned: Condvar::new(), + })); + // SAFETY: just allocated and never freed; nothing else sees it yet. + unsafe { + (*hub).object.hub = hub; + for device in &mut (*hub).devices { + device.hub = hub; + } + &*hub + } + } + + /// A hub over the host's input, polled from now on. + fn start(source: Box) -> &'static Hub { + let hub = Hub::new(source); + hub.poll(); + std::thread::spawn(move || { + loop { + std::thread::sleep(POLL); + hub.poll(); + } + }); + hub + } + + fn state(&self) -> MutexGuard<'_, State> { + lock(&self.state) + } + + /// Reads the host once; device callbacks run on the calling thread. + fn poll(&self) { + let (pads, keys) = { + let mut source = lock(&self.source); + let pads: [_; PADS] = std::array::from_fn(|slot| source.pad(slot)); + (pads, source.keys()) + }; + let events = self.state().poll(&self.devices, pads, keys); + self.deliver(events); + } + + /// Runs callbacks, never under our lock: they call back into us. One + /// unregistered since the event was taken does not run, and + /// `UnregisterCallback` waits for one that runs. + fn deliver(&self, events: Vec) { + let me = std::thread::current().id(); + for e in events { + let r = e.registration; + { + let mut state = self.state(); + if !state.callbacks.iter().any(|c| c.token == r.token) { + continue; + } + state.running.push((r.token, me)); + } + (r.callback)( + r.token, + r.context as *mut c_void, + &self.devices[e.device], + e.timestamp, + e.current, + e.previous, + ); + let mut state = self.state(); + if let Some(i) = state.running.iter().position(|&x| x == (r.token, me)) { + state.running.swap_remove(i); + } + self.returned.notify_all(); + } + } + + fn index(&self, device: *const Device) -> Option { + self.devices.iter().position(|d| std::ptr::eq(d, device)) + } +} + +impl State { + fn poll( + &mut self, + devices: &[Device; DEVICES], + pads: [Option; PADS], + keys: Vec, + ) -> Vec { + let now = now(); + let mut events = std::mem::take(&mut self.pending); + let any_pad = pads.iter().any(Option::is_some); + for (slot, pad) in pads.into_iter().enumerate() { + self.update(devices, slot, pad.map(Value::Pad), now, &mut events); + } + let fallback = (!any_pad).then(|| Value::Pad(fallback(&keys))); + self.update(devices, FALLBACK, fallback, now, &mut events); + self.update(devices, KEYBOARD, Some(Value::Keys(keys)), now, &mut events); + events + } + + /// Records a device's state: a reading when it changed, callbacks when + /// the device came or went. + fn update( + &mut self, + devices: &[Device; DEVICES], + index: usize, + value: Option, + now: u64, + events: &mut Vec, + ) { + let slot = &mut self.slots[index]; + let was = slot.connected; + slot.connected = value.is_some(); + if let Some(value) = value + && (!was || slot.history.back().is_none_or(|r| r.value != value)) + { + slot.sequence += 1; + if slot.history.len() == HISTORY { + slot.history.pop_front(); + } + slot.history.push_back(Ref::new(Reading { + vtable: &READING, + refs: AtomicU32::new(1), + device: &devices[index], + sequence: slot.sequence, + timestamp: now, + value, + })); + } + if was != slot.connected { + tracing::info!(device = index, connected = !was, "input device"); + let (current, previous) = if was { + (0, STATUS_CONNECTED) + } else { + (STATUS_CONNECTED, 0) + }; + events.extend( + self.callbacks + .iter() + .filter(|r| r.matches(devices, index) && r.status & STATUS_CONNECTED != 0) + .map(|r| r.event(index, now, current, previous)), + ); + } + } +} + +#[cfg(windows)] +fn host() -> Box { + Box::new(host::Host::default()) +} + +#[cfg(not(windows))] +fn host() -> Box { + struct Nothing; + impl Source for Nothing { + fn pad(&mut self, _: usize) -> Option { + None + } + fn keys(&mut self) -> Vec { + Vec::new() + } + fn rumble(&mut self, _: usize, _: u16, _: u16) {} + } + Box::new(Nothing) +} + +static HUB: LazyLock<&'static Hub> = LazyLock::new(|| Hub::start(host())); + +type This = *const Object; +type Out = *mut *const c_void; + +/// The DLL's only export (ordinal 1): the input object, static and shared. +pub extern "system" fn GameInputCreate(out: *mut This) -> HRESULT { + tracing::info!("GameInputCreate"); + if out.is_null() { + return E_INVALIDARG; + } + // SAFETY: checked non-null; the title passes room for a pointer. + unsafe { out.write(&HUB.object) }; + S_OK +} + +fn hub(this: This) -> &'static Hub { + // SAFETY: `this` is a hub's object; hubs are never freed. + unsafe { &*(*this).hub } +} + +/// Clears a COM out pointer and returns `hr`. +fn fail(out: Out, hr: HRESULT) -> HRESULT { + if !out.is_null() { + // SAFETY: checked non-null; the title passes room for a pointer. + unsafe { out.write(std::ptr::null()) }; + } + hr +} + +/// Gives the title a reference to `reading`, or fails as with none. +fn hand(out: Out, reading: Option<&Ref>) -> HRESULT { + match reading { + _ if out.is_null() => E_INVALIDARG, + Some(reading) => { + // SAFETY: checked non-null; the title passes room for a pointer. + unsafe { out.write(reading.share().cast()) }; + S_OK + } + None => fail(out, READING_NOT_FOUND), + } +} + +extern "system" fn no_interface(_: *const c_void, _iid: *const c_void, out: Out) -> HRESULT { + tracing::warn!("input QueryInterface not implemented"); + fail(out, E_NOINTERFACE) +} +/// The input object and devices live as long as the process. +extern "system" fn add_ref(_: *const c_void) -> u32 { + 1 +} + +extern "system" fn timestamp(_: This) -> u64 { + now() +} + +extern "system" fn current_reading( + this: This, + kind: u32, + device: *const Device, + out: Out, +) -> HRESULT { + let hub = hub(this); + let state = hub.state(); + let newest = |i: usize| { + state.slots[i] + .history + .back() + .filter(|r| r.kind() & kind != 0) + }; + let found = if device.is_null() { + (0..DEVICES) + .filter(|&i| state.slots[i].connected) + .filter_map(newest) + .max_by_key(|r| r.timestamp) + } else { + match hub.index(device) { + None => return fail(out, E_INVALIDARG), + Some(i) if !state.slots[i].connected => return fail(out, DEVICE_DISCONNECTED), + Some(i) => newest(i), + } + }; + tracing::trace!( + kind = format_args!("{kind:#x}"), + device = ?hub.index(device), + sequence = found.map(|r| r.sequence), + "current reading" + ); + hand(out, found) +} + +/// The reading after (`forward`) or before `reference` on its device. +fn relative( + this: This, + reference: *const Reading, + kind: u32, + device: *const Device, + out: Out, + forward: bool, +) -> HRESULT { + if reference.is_null() { + return fail(out, E_INVALIDARG); + } + let hub = hub(this); + // SAFETY: a reading we handed out and the title still holds. + let reference = unsafe { &*reference }; + // shortcut: with no device given only the reference's device is walked, + // not every device's readings in time order; the title walks + // only keyboard readings (one device) and the current pad's previous one. + let Some(index) = hub.index(reference.device) else { + return fail(out, E_INVALIDARG); + }; + if !device.is_null() && !std::ptr::eq(device, reference.device) { + return fail(out, E_INVALIDARG); + } + let state = hub.state(); + let history = &state.slots[index].history; + if history + .front() + .is_none_or(|oldest| reference.sequence < oldest.sequence) + { + return fail(out, REFERENCE_TOO_OLD); + } + let wanted = |r: &&Ref| r.kind() & kind != 0; + let found = if forward { + history + .iter() + .filter(|r| r.sequence > reference.sequence) + .find(wanted) + } else { + history + .iter() + .rev() + .filter(|r| r.sequence < reference.sequence) + .find(wanted) + }; + hand(out, found) +} +extern "system" fn next_reading( + this: This, + reference: *const Reading, + kind: u32, + device: *const Device, + out: Out, +) -> HRESULT { + relative(this, reference, kind, device, out, true) +} +extern "system" fn previous_reading( + this: This, + reference: *const Reading, + kind: u32, + device: *const Device, + out: Out, +) -> HRESULT { + relative(this, reference, kind, device, out, false) +} +/// The device's reading at `time`, among those still kept. +extern "system" fn temporal_reading( + this: This, + time: u64, + device: *const Device, + out: Out, +) -> HRESULT { + let hub = hub(this); + let Some(index) = hub.index(device) else { + return fail(out, E_INVALIDARG); + }; + let state = hub.state(); + let history = &state.slots[index].history; + hand(out, history.iter().rev().find(|r| r.timestamp <= time)) +} + +static NEXT_TOKEN: AtomicU64 = AtomicU64::new(1); + +fn token(out: *mut u64) -> HRESULT { + if !out.is_null() { + // SAFETY: checked non-null. + unsafe { out.write(NEXT_TOKEN.fetch_add(1, Ordering::Relaxed)) }; + } + S_OK +} + +// shortcut: reading callbacks never run; the title registers none +// (it polls). +extern "system" fn register_reading( + _: This, + _device: *const c_void, + _kind: u32, + _threshold: f32, + _context: *mut c_void, + _callback: *const c_void, + out: *mut u64, +) -> HRESULT { + tracing::warn!("input reading callbacks are never called"); + token(out) +} + +/// Device callbacks run on our poll thread when a device comes or goes. +/// Enumeration reports the devices already there: blocking on the caller's +/// thread before we return (the title registers holding a lock its callback +/// takes again), asynchronous on the next poll. +extern "system" fn register_device( + this: This, + device: *const Device, + kind: u32, + status: u32, + enumeration: u32, + context: *mut c_void, + callback: Option, + out: *mut u64, +) -> HRESULT { + let Some(callback) = callback else { + return E_INVALIDARG; + }; + let hub = hub(this); + let registration = Registration { + token: NEXT_TOKEN.fetch_add(1, Ordering::Relaxed), + device: device as usize, + kind, + status, + context: context as usize, + callback, + }; + let mut found = Vec::new(); + { + let mut state = hub.state(); + if enumeration != 0 && status & STATUS_CONNECTED != 0 { + let now = now(); + found = (0..DEVICES) + .filter(|&i| state.slots[i].connected && registration.matches(&hub.devices, i)) + .map(|i| registration.event(i, now, STATUS_CONNECTED, 0)) + .collect(); + } + tracing::info!( + kind = format_args!("{kind:#x}"), + enumeration, + devices = found.len(), + "input device callback" + ); + state.callbacks.push(registration); + if enumeration == ASYNC_ENUMERATION { + state.pending.append(&mut found); + } + } + if !out.is_null() { + // SAFETY: checked non-null. + unsafe { out.write(registration.token) }; + } + hub.deliver(found); + S_OK +} +/// Guide button and keyboard layout callbacks: neither ever changes here. +extern "system" fn register_other( + _: This, + _device: *const c_void, + _context: *mut c_void, + _callback: *const c_void, + out: *mut u64, +) -> HRESULT { + token(out) +} + +fn forget(this: This, token: u64) { + let mut state = hub(this).state(); + state.callbacks.retain(|r| r.token != token); + state.pending.retain(|e| e.registration.token != token); +} +extern "system" fn stop_callback(this: This, token: u64) { + forget(this, token); +} +/// Stops the callback, then waits up to `timeout` µs for a call of it that +/// is running; false on time-out, or from inside that callback (it cannot +/// wait for itself), as documented. Either way it is never called again. +extern "system" fn unregister_callback(this: This, token: u64, timeout: u64) -> bool { + forget(this, token); + let hub = hub(this); + let me = std::thread::current().id(); + let deadline = Instant::now().checked_add(Duration::from_micros(timeout)); + let mut state = hub.state(); + loop { + let running = state.running.iter().filter(|r| r.0 == token); + if running.clone().any(|r| r.1 == me) { + return false; + } + if running.count() == 0 { + return true; + } + state = match deadline { + None => hub.returned.wait(state).unwrap_or_else(PoisonError::into_inner), + Some(deadline) => { + let Some(left) = deadline.checked_duration_since(Instant::now()) else { + return false; + }; + let waited = hub.returned.wait_timeout(state, left); + waited.unwrap_or_else(PoisonError::into_inner).0 + } + }; + } +} + +/// Dispatcher and aggregate device: no title of ours asks for them. +extern "system" fn create_dispatcher(_: This, out: Out) -> HRESULT { + tracing::warn!("input dispatcher not implemented"); + fail(out, E_NOTIMPL) +} +extern "system" fn create_aggregate(_: This, _kind: u32, out: Out) -> HRESULT { + tracing::warn!("aggregate input device not implemented"); + fail(out, E_NOTIMPL) +} +extern "system" fn find_by_id(this: This, id: *const [u8; 32], out: Out) -> HRESULT { + if id.is_null() || out.is_null() { + return fail(out, E_INVALIDARG); + } + // SAFETY: checked non-null; the title passes a device id. + let id = unsafe { &*id }; + match hub(this).devices.iter().find(|d| d.info.id == *id) { + Some(device) => { + // SAFETY: checked non-null. + unsafe { out.write((device as *const Device).cast()) }; + S_OK + } + None => fail(out, DEVICE_NOT_FOUND), + } +} +/// Lookup by object, platform handle or platform string: our devices have +/// none of these. +extern "system" fn find_device(_: This, _value: *const c_void, out: Out) -> HRESULT { + fail(out, DEVICE_NOT_FOUND) +} +extern "system" fn enable_oem_device( + _: This, + _vendor: u16, + _product: u16, + _interface: u8, + _collection: u8, +) -> HRESULT { + S_OK +} +extern "system" fn set_focus_policy(_: This, _policy: u32) {} + +static INPUT: Table<22> = Table([ + no_interface as *const (), // 0x00 + add_ref as *const (), // 0x08 AddRef + add_ref as *const (), // 0x10 Release + timestamp as *const (), // 0x18 + current_reading as *const (), // 0x20 + next_reading as *const (), // 0x28 + previous_reading as *const (), // 0x30 + temporal_reading as *const (), // 0x38 + register_reading as *const (), // 0x40 + register_device as *const (), // 0x48 + register_other as *const (), // 0x50 guide button + register_other as *const (), // 0x58 keyboard layout + stop_callback as *const (), // 0x60 + unregister_callback as *const (), // 0x68 + create_dispatcher as *const (), // 0x70 + create_aggregate as *const (), // 0x78 + find_by_id as *const (), // 0x80 + find_device as *const (), // 0x88 by object + find_device as *const (), // 0x90 by platform handle + find_device as *const (), // 0x98 by platform string + enable_oem_device as *const (), // 0xa0 + set_focus_policy as *const (), // 0xa8 +]); + +extern "system" fn device_info(this: *const Device) -> *const DeviceInfo { + // SAFETY: one of our devices. + unsafe { &(*this).info } +} +extern "system" fn device_status(this: *const Device) -> u32 { + // SAFETY: one of our devices. + let device = unsafe { &*this }; + if device.hub().state().slots[device.index].connected { + STATUS_CONNECTED + } else { + 0 + } +} +// shortcut: trigger motors are dropped (XInput has none). The host API that +// drives them without a redistributable is Windows.Gaming.Input (WinRT +// `Gamepad.Vibration`), which needs WinRT bindings this crate lacks outside +// diagnostics builds; the title sends trigger levels in slot 0x50. +extern "system" fn set_rumble(this: *const Device, params: *const [f32; 4]) { + // SAFETY: one of our devices. + let device = unsafe { &*this }; + if device.index >= PADS { + return; + } + let [low, high, ..] = if params.is_null() { + [0.0; 4] + } else { + // SAFETY: checked non-null; four motor levels. + unsafe { *params } + }; + let speed = |level: f32| (level.clamp(0.0, 1.0) * f32::from(u16::MAX)) as u16; + lock(&device.hub().source).rumble(device.index, speed(low), speed(high)); +} +extern "system" fn unsupported(_: *const c_void) -> HRESULT { + tracing::warn!( + slot = format_args!("{SLOT:#x}"), + "input device method not implemented" + ); + E_NOTIMPL +} + +static DEVICE: Table<21> = Table([ + no_interface as *const (), // 0x00 + add_ref as *const (), // 0x08 AddRef + add_ref as *const (), // 0x10 Release + device_info as *const (), // 0x18 + device_status as *const (), // 0x20 + unsupported::<0x28> as *const (), // battery + unsupported::<0x30> as *const (), // force feedback + unsupported::<0x38> as *const (), // + unsupported::<0x40> as *const (), // + unsupported::<0x48> as *const (), // haptics + set_rumble as *const (), // 0x50 + unsupported::<0x58> as *const (), // input synchronization + unsupported::<0x60> as *const (), // + unsupported::<0x68> as *const (), // power off + unsupported::<0x70> as *const (), // raw device access + unsupported::<0x78> as *const (), // + unsupported::<0x80> as *const (), // + unsupported::<0x88> as *const (), // + unsupported::<0x90> as *const (), // + unsupported::<0x98> as *const (), // + unsupported::<0xa0> as *const (), // +]); + +fn reading<'a>(this: *const Reading) -> &'a Reading { + // SAFETY: a reading we handed out and the title still holds. + unsafe { &*this } +} +extern "system" fn reading_add_ref(this: *const Reading) -> u32 { + reading(this).refs.fetch_add(1, Ordering::Relaxed) + 1 +} +extern "system" fn reading_release(this: *const Reading) -> u32 { + let left = reading(this).refs.fetch_sub(1, Ordering::AcqRel) - 1; + if left == 0 { + // SAFETY: the last reference is gone; `Ref::new` boxed it. + drop(unsafe { Box::from_raw(this.cast_mut()) }); + } + left +} +extern "system" fn input_kind(this: *const Reading) -> u32 { + reading(this).kind() +} +extern "system" fn sequence_number(this: *const Reading, kind: u32) -> u64 { + let reading = reading(this); + if reading.kind() & kind != 0 { + reading.sequence + } else { + 0 + } +} +extern "system" fn reading_timestamp(this: *const Reading) -> u64 { + reading(this).timestamp +} +extern "system" fn reading_device(this: *const Reading, out: *mut *const Device) { + if !out.is_null() { + // SAFETY: checked non-null; devices need no reference. + unsafe { out.write(reading(this).device) }; + } +} +extern "system" fn key_count(this: *const Reading) -> u32 { + match &reading(this).value { + Value::Keys(keys) => keys.len() as u32, + Value::Pad(_) => 0, + } +} +extern "system" fn key_state(this: *const Reading, count: u32, out: *mut KeyState) -> u32 { + let Value::Keys(keys) = &reading(this).value else { + return 0; + }; + if out.is_null() { + return 0; + } + let n = keys.len().min(count as usize); + // SAFETY: the title passes room for `count` keys. + unsafe { std::ptr::copy_nonoverlapping(keys.as_ptr(), out, n) }; + n as u32 +} +extern "system" fn gamepad_state(this: *const Reading, out: *mut PadState) -> bool { + match &reading(this).value { + Value::Pad(state) if !out.is_null() => { + // SAFETY: checked non-null. + unsafe { out.write(*state) }; + true + } + _ => false, + } +} +/// Kinds our devices do not have: no count, no state. +extern "system" fn nothing(_: *const c_void) -> usize { + 0 +} + +static READING: Table<25> = Table([ + no_interface as *const (), // 0x00 + reading_add_ref as *const (), // 0x08 + reading_release as *const (), // 0x10 + input_kind as *const (), // 0x18 + sequence_number as *const (), // 0x20 + reading_timestamp as *const (), // 0x28 + reading_device as *const (), // 0x30 + nothing as *const (), // 0x38 raw report + nothing as *const (), // 0x40 controller axes, buttons, switches + nothing as *const (), // 0x48 + nothing as *const (), // 0x50 + nothing as *const (), // 0x58 + nothing as *const (), // 0x60 + nothing as *const (), // 0x68 + key_count as *const (), // 0x70 + key_state as *const (), // 0x78 + nothing as *const (), // 0x80 mouse + nothing as *const (), // 0x88 touch + nothing as *const (), // 0x90 + nothing as *const (), // 0x98 motion + nothing as *const (), // 0xa0 arcade stick + nothing as *const (), // 0xa8 flight stick + gamepad_state as *const (), // 0xb0 + nothing as *const (), // 0xb8 racing wheel + nothing as *const (), // 0xc0 UI navigation +]); + +pub(crate) fn module() -> HleModule { + HleModule { + name: "gameinput", + dlls: &["gameinput.dll"], + // Titles import it by ordinal only. + exports: vec![HleExport { + name: "#1", + address: GameInputCreate as *const () as usize, + }], + } +} + +/// Host input: XInput pads, the keyboard while our process has focus. +#[cfg(windows)] +mod host { + use std::time::{Duration, Instant}; + + use windows_sys::Win32::System::Threading::GetCurrentProcessId; + use windows_sys::Win32::UI::Input::KeyboardAndMouse::{ + GetAsyncKeyState, MAPVK_VK_TO_VSC_EX, MapVirtualKeyW, + }; + use windows_sys::Win32::UI::Input::XboxController::{ + XINPUT_GAMEPAD, XINPUT_GAMEPAD_A, XINPUT_GAMEPAD_B, XINPUT_GAMEPAD_BACK, + XINPUT_GAMEPAD_DPAD_DOWN, XINPUT_GAMEPAD_DPAD_LEFT, XINPUT_GAMEPAD_DPAD_RIGHT, + XINPUT_GAMEPAD_DPAD_UP, XINPUT_GAMEPAD_LEFT_SHOULDER, XINPUT_GAMEPAD_LEFT_THUMB, + XINPUT_GAMEPAD_RIGHT_SHOULDER, XINPUT_GAMEPAD_RIGHT_THUMB, XINPUT_GAMEPAD_START, + XINPUT_GAMEPAD_X, XINPUT_GAMEPAD_Y, XINPUT_STATE, XINPUT_VIBRATION, XInputGetState, + XInputSetState, + }; + use windows_sys::Win32::UI::WindowsAndMessaging::{ + GetForegroundWindow, GetWindowThreadProcessId, + }; + + use super::*; + + /// Asking XInput about an empty slot is slow; look again this often. + const EMPTY_SLOT_RECHECK: Duration = Duration::from_secs(1); + + const BUTTONS: [(u16, u32); 14] = [ + (XINPUT_GAMEPAD_START, MENU), + (XINPUT_GAMEPAD_BACK, VIEW), + (XINPUT_GAMEPAD_A, A), + (XINPUT_GAMEPAD_B, B), + (XINPUT_GAMEPAD_X, X), + (XINPUT_GAMEPAD_Y, Y), + (XINPUT_GAMEPAD_DPAD_UP, UP), + (XINPUT_GAMEPAD_DPAD_DOWN, DOWN), + (XINPUT_GAMEPAD_DPAD_LEFT, LEFT), + (XINPUT_GAMEPAD_DPAD_RIGHT, RIGHT), + (XINPUT_GAMEPAD_LEFT_SHOULDER, LEFT_SHOULDER), + (XINPUT_GAMEPAD_RIGHT_SHOULDER, RIGHT_SHOULDER), + (XINPUT_GAMEPAD_LEFT_THUMB, LEFT_STICK), + (XINPUT_GAMEPAD_RIGHT_THUMB, RIGHT_STICK), + ]; + + /// Raw values, no dead zone: titles apply their own. + pub(super) fn convert(pad: &XINPUT_GAMEPAD) -> PadState { + let stick = |v: i16| (f32::from(v) / 32767.0).max(-1.0); + PadState { + buttons: BUTTONS + .iter() + .filter(|(host, _)| pad.wButtons & host != 0) + .fold(0, |all, (_, bit)| all | bit), + left_trigger: f32::from(pad.bLeftTrigger) / 255.0, + right_trigger: f32::from(pad.bRightTrigger) / 255.0, + left_x: stick(pad.sThumbLX), + left_y: stick(pad.sThumbLY), + right_x: stick(pad.sThumbRX), + right_y: stick(pad.sThumbRY), + } + } + + #[derive(Default)] + pub(super) struct Host { + empty_until: [Option; PADS], + } + + impl Source for Host { + fn pad(&mut self, slot: usize) -> Option { + if self.empty_until[slot].is_some_and(|until| Instant::now() < until) { + return None; + } + let mut state = XINPUT_STATE::default(); + // SAFETY: room for the state. + if unsafe { XInputGetState(slot as u32, &mut state) } != 0 { + self.empty_until[slot] = Some(Instant::now() + EMPTY_SLOT_RECHECK); + return None; + } + self.empty_until[slot] = None; + #[allow(unused_mut)] + let mut pad = convert(&state.Gamepad); + // The scripted keys (`LEONIDA_KEYS`) also press the first + // pad's buttons, by the stand-in pad's table: with a real pad + // connected the stand-in is not there, and a title that listens + // to the pad (the title's start screen) saw nothing. + #[cfg(feature = "diagnostics")] + if slot == 0 { + for vk in scripted() { + if let Some(&(_, button)) = super::FALLBACK_BUTTONS.iter().find(|(key, _)| *key == vk) { + pad.buttons |= button; + } + } + } + Some(pad) + } + + fn keys(&mut self) -> Vec { + #[cfg(feature = "diagnostics")] + let mut down = scripted(); + #[cfg(not(feature = "diagnostics"))] + let mut down = Vec::new(); + if focused() { + // Left/right modifier keys only, as devices report them; no + // mouse buttons (below 0x08). + let held: Vec = (0x08..=0xFE_u8) + .filter(|vk| !(0x10..=0x12).contains(vk) && !down.contains(vk)) + // SAFETY: plain queries. + .filter(|&vk| unsafe { GetAsyncKeyState(i32::from(vk)) } < 0) + .collect(); + down.extend(held); + } + down.into_iter() + .map(|vk| KeyState { + // SAFETY: plain query. + scan_code: unsafe { MapVirtualKeyW(u32::from(vk), MAPVK_VK_TO_VSC_EX) }, + virtual_key: vk, + // shortcut: no characters (code point 0); + // the title reads scan codes and virtual keys only. + ..Default::default() + }) + .collect() + } + + fn rumble(&mut self, slot: usize, low: u16, high: u16) { + let speeds = XINPUT_VIBRATION { + wLeftMotorSpeed: low, + wRightMotorSpeed: high, + }; + // SAFETY: a valid vibration; an empty slot just fails. + unsafe { XInputSetState(slot as u32, &speeds) }; + } + } + + /// Debugging aid: `LEONIDA_KEYS=:,...` holds each key for + /// 0.2 s that long after input starts, with or without focus. A key is a + /// letter, a digit, or `Enter`, `Esc`, `Tab`, `Back`, `Up`, `Down`, + /// `Left`, `Right` (the stand-in pad's table maps them to buttons). + #[cfg(feature = "diagnostics")] + fn scripted() -> Vec { + static SCRIPT: LazyLock<(Instant, Vec<(Duration, u8)>)> = LazyLock::new(|| { + let list = std::env::var("LEONIDA_KEYS").unwrap_or_default(); + let keys = list.split(',').filter_map(|entry| { + let (at, key) = entry.split_once(':')?; + let vk = match key.trim() { + "Enter" => 0x0D, + "Esc" => 0x1B, + "Tab" => 0x09, + "Back" => 0x08, + "Up" => 0x26, + "Down" => 0x28, + "Left" => 0x25, + "Right" => 0x27, + k if k.len() == 1 && k.as_bytes()[0].is_ascii_alphanumeric() => { + k.as_bytes()[0].to_ascii_uppercase() + } + _ => return None, + }; + Some(( + Duration::try_from_secs_f64(at.trim().parse().ok()?).ok()?, + vk, + )) + }); + (Instant::now(), keys.collect()) + }); + let (start, keys) = &*SCRIPT; + let now = start.elapsed(); + keys.iter() + .filter(|&&(at, _)| (at..at + Duration::from_millis(200)).contains(&now)) + .map(|&(_, vk)| vk) + .collect() + } + + /// The foreground window is one of ours (the title's or our fallback). + fn focused() -> bool { + let mut process = 0; + // SAFETY: plain queries; a null window gives process 0. + unsafe { + GetWindowThreadProcessId(GetForegroundWindow(), &mut process); + process == GetCurrentProcessId() + } + } + + #[test] + fn host_pads_convert_to_console_pads() { + let pad = XINPUT_GAMEPAD { + wButtons: XINPUT_GAMEPAD_A | XINPUT_GAMEPAD_START | XINPUT_GAMEPAD_DPAD_LEFT, + bLeftTrigger: 255, + sThumbLX: -32768, + sThumbLY: 32767, + ..Default::default() + }; + let state = convert(&pad); + assert_eq!(state.buttons, A | MENU | LEFT); + assert_eq!( + ( + state.left_trigger, + state.left_x, + state.left_y, + state.right_x + ), + (1.0, -1.0, 1.0, 0.0) + ); + } +} + +#[cfg(test)] +mod tests { + use std::sync::Arc; + + use super::*; + use crate::HleResolver; + use crate::HostPolicy; + use leonida_loader::Provenance; + use leonida_pe::ImportSymbol; + + #[derive(Default)] + struct FakeHost { + pads: [Option; PADS], + keys: Vec, + rumble: Vec<(usize, u16, u16)>, + } + + struct Fake(Arc>); + + impl Source for Fake { + fn pad(&mut self, slot: usize) -> Option { + self.0.lock().unwrap().pads[slot] + } + fn keys(&mut self) -> Vec { + self.0.lock().unwrap().keys.clone() + } + fn rumble(&mut self, slot: usize, low: u16, high: u16) { + self.0.lock().unwrap().rumble.push((slot, low, high)); + } + } + + fn fake() -> (&'static Hub, Arc>) { + let host = Arc::new(Mutex::new(FakeHost::default())); + let hub = Hub::new(Box::new(Fake(Arc::clone(&host)))); + hub.poll(); + (hub, host) + } + + fn key(virtual_key: u8) -> KeyState { + KeyState { + scan_code: u32::from(virtual_key) + 0x100, + virtual_key, + ..Default::default() + } + } + + fn slot(object: *const T, offset: usize) -> F { + // SAFETY: our objects start with their table, which has the slot. + let f = unsafe { *(*(object as *const *const *const ())).add(offset / 8) }; + // SAFETY: the caller names the slot's signature. + unsafe { std::mem::transmute_copy(&f) } + } + + /// Device callbacks seen: device index, current and previous status. + type Log = Mutex>; + + extern "system" fn record( + _token: u64, + context: *mut c_void, + device: *const Device, + _timestamp: u64, + current: u32, + previous: u32, + ) { + // SAFETY: the test passes its log and one of the hub's devices. + let (log, index) = unsafe { (&*(context as *const Log), (*device).index) }; + log.lock().unwrap().push((index, current, previous)); + } + + fn register(hub: &Hub, kind: u32, enumeration: u32, log: &Log) -> u64 { + type Register = extern "system" fn( + This, + *const Device, + u32, + u32, + u32, + *mut c_void, + Option, + *mut u64, + ) -> HRESULT; + let mut token = 0; + let context = log as *const Log as *mut c_void; + let register = slot::(&hub.object, 0x48); + let hr = register( + &hub.object, + std::ptr::null(), + kind, + 1, + enumeration, + context, + Some(record), + &mut token, + ); + assert_eq!(hr, S_OK); + assert_ne!(token, 0); + token + } + + fn result(hr: HRESULT, out: *const c_void) -> Result<*const Reading, HRESULT> { + if hr == S_OK { + Ok(out.cast()) + } else { + assert!(out.is_null()); + Err(hr) + } + } + + fn current(hub: &Hub, kind: u32, device: usize) -> Result<*const Reading, HRESULT> { + type Current = extern "system" fn(This, u32, *const Device, Out) -> HRESULT; + let mut out = std::ptr::null(); + let hr = slot::(&hub.object, 0x20)( + &hub.object, + kind, + &hub.devices[device], + &mut out, + ); + result(hr, out) + } + + fn walk(hub: &Hub, offset: usize, from: *const Reading) -> Result<*const Reading, HRESULT> { + type Walk = extern "system" fn(This, *const Reading, u32, *const Device, Out) -> HRESULT; + let mut out = std::ptr::null(); + let device = reading(from).device; + let hr = + slot::(&hub.object, offset)(&hub.object, from, GAMEPAD_KIND, device, &mut out); + result(hr, out) + } + + fn pad(reading: *const Reading) -> PadState { + let mut state = PadState::default(); + let get = + slot:: bool, _>(reading, 0xb0); + assert!(get(reading, &mut state)); + state + } + + fn stamp(reading: *const Reading) -> (u64, u64) { + let time = slot:: u64, _>(reading, 0x28); + let sequence = slot:: u64, _>(reading, 0x20); + (time(reading), sequence(reading, GAMEPAD_KIND)) + } + + fn release(reading: *const Reading) { + slot:: u32, _>(reading, 0x10)(reading); + } + + #[test] + fn ordinal_one_resolves_to_create() { + let r = HleResolver::new(HostPolicy::none()); + assert_eq!( + r.classify("GameInput.dll", &ImportSymbol::Ordinal(1)), + Some(Provenance::Hle) + ); + assert_eq!(r.classify("GameInput.dll", &ImportSymbol::Ordinal(2)), None); + } + + #[test] + fn pads_connect_report_and_disconnect() { + let (hub, host) = fake(); + let log = Log::default(); + register(hub, GAMEPAD_KIND, 2, &log); + // Blocking enumeration ran before registration returned: with no + // host pad the keyboard's stand-in is the only one. + assert_eq!(*log.lock().unwrap(), [(FALLBACK, STATUS_CONNECTED, 0)]); + + host.lock().unwrap().pads[1] = Some(PadState { + buttons: A, + left_x: 0.5, + ..Default::default() + }); + hub.poll(); + assert_eq!( + log.lock().unwrap()[1..], + [(1, STATUS_CONNECTED, 0), (FALLBACK, 0, STATUS_CONNECTED)] + ); + + let first = current(hub, GAMEPAD_KIND, 1).unwrap(); + assert_eq!(pad(first).buttons, A); + assert_eq!(pad(first).left_x, 0.5); + // No change, no new reading. + hub.poll(); + let again = current(hub, GAMEPAD_KIND, 1).unwrap(); + assert_eq!(again, first); + release(again); + + std::thread::sleep(Duration::from_millis(2)); + host.lock().unwrap().pads[1].as_mut().unwrap().buttons = B; + hub.poll(); + let second = current(hub, GAMEPAD_KIND, 1).unwrap(); + assert_eq!(pad(second).buttons, B); + let (t1, s1) = stamp(first); + let (t2, s2) = stamp(second); + assert!(t2 > t1 && s2 == s1 + 1); + assert!(t2 <= now()); + + // The title's edge check: previous of current, and back again. + assert_eq!(walk(hub, 0x30, second), Ok(first)); + assert_eq!(walk(hub, 0x28, first), Ok(second)); + assert_eq!(walk(hub, 0x28, second), Err(READING_NOT_FOUND)); + assert_eq!(walk(hub, 0x30, first), Err(READING_NOT_FOUND)); + for r in [first, first, second, second] { + release(r); + } + + host.lock().unwrap().pads[1] = None; + hub.poll(); + assert_eq!( + log.lock().unwrap()[3..], + [(1, 0, STATUS_CONNECTED), (FALLBACK, STATUS_CONNECTED, 0)] + ); + assert_eq!(current(hub, GAMEPAD_KIND, 1), Err(DEVICE_DISCONNECTED)); + // The stand-in is back, at rest. + let rest = current(hub, GAMEPAD_KIND, FALLBACK).unwrap(); + assert_eq!(pad(rest), PadState::default()); + release(rest); + } + + #[test] + fn keys_feed_the_keyboard_and_the_stand_in_pad() { + let (hub, host) = fake(); + let log = Log::default(); + register(hub, KEYBOARD_KIND, 2, &log); + assert_eq!(*log.lock().unwrap(), [(KEYBOARD, STATUS_CONNECTED, 0)]); + + let keys = vec![key(b'W'), key(0x0D), key(b'L'), key(b'C')]; + host.lock().unwrap().keys = keys.clone(); + hub.poll(); + let r = current(hub, KEYBOARD_KIND, KEYBOARD).unwrap(); + let count = slot:: u32, _>(r, 0x70); + let state = + slot:: u32, _>(r, 0x78); + assert_eq!(count(r), 4); + let mut got = [KeyState::default(); 8]; + assert_eq!(state(r, 8, got.as_mut_ptr()), 4); + assert_eq!(got[..4], keys[..]); + release(r); + + let r = current(hub, GAMEPAD_KIND, FALLBACK).unwrap(); + assert_eq!( + pad(r), + PadState { + buttons: A, + left_y: 1.0, + right_x: 1.0, + right_trigger: 1.0, + ..Default::default() + } + ); + release(r); + // A keyboard reading is no gamepad reading. + assert_eq!(current(hub, GAMEPAD_KIND, KEYBOARD), Err(READING_NOT_FOUND)); + } + + #[test] + fn async_enumeration_waits_for_the_poll_and_unregistering_stops_callbacks() { + let (hub, host) = fake(); + let log = Log::default(); + let token = register(hub, GAMEPAD_KIND, ASYNC_ENUMERATION, &log); + assert!(log.lock().unwrap().is_empty()); + hub.poll(); + assert_eq!(*log.lock().unwrap(), [(FALLBACK, STATUS_CONNECTED, 0)]); + + let unregister = slot:: bool, _>(&hub.object, 0x68); + assert!(unregister(&hub.object, token, 5000)); + host.lock().unwrap().pads[0] = Some(PadState::default()); + hub.poll(); + assert_eq!(log.lock().unwrap().len(), 1); + } + + #[test] + fn unregistering_waits_for_a_running_callback() { + use std::sync::atomic::AtomicBool; + static INSIDE: AtomicBool = AtomicBool::new(false); + static LEAVE: AtomicBool = AtomicBool::new(false); + static FROM_INSIDE: AtomicU32 = AtomicU32::new(0); + extern "system" fn slow( + token: u64, + context: *mut c_void, + _: *const Device, + _: u64, + _: u32, + _: u32, + ) { + // From inside its own callback, unregistering fails at once. + let unregister = slot:: bool, _>(context, 0x68); + if !unregister(context.cast(), token, 0) { + FROM_INSIDE.fetch_add(1, Ordering::SeqCst); + } + INSIDE.store(true, Ordering::SeqCst); + while !LEAVE.load(Ordering::SeqCst) { + std::thread::sleep(Duration::from_millis(1)); + } + } + let (hub, host) = fake(); + type Register = extern "system" fn( + This, + *const Device, + u32, + u32, + u32, + *mut c_void, + Option, + *mut u64, + ) -> HRESULT; + let register = slot::(&hub.object, 0x48); + let mut token = 0; + let context = (&raw const hub.object).cast_mut().cast(); + assert_eq!( + register(&hub.object, std::ptr::null(), GAMEPAD_KIND, 1, 0, context, Some(slow), &mut token), + S_OK + ); + host.lock().unwrap().pads[1] = Some(PadState::default()); + let poller = std::thread::spawn(|| hub.poll()); + while !INSIDE.load(Ordering::SeqCst) { + std::thread::sleep(Duration::from_millis(1)); + } + let unregister = slot:: bool, _>(&hub.object, 0x68); + assert!(!unregister(&hub.object, token, 5000), "times out while it runs"); + let leave = std::thread::spawn(|| { + std::thread::sleep(Duration::from_millis(50)); + LEAVE.store(true, Ordering::SeqCst); + }); + let start = Instant::now(); + assert!(unregister(&hub.object, token, u64::MAX), "waits for it"); + assert!(start.elapsed() >= Duration::from_millis(40)); + assert_eq!(FROM_INSIDE.load(Ordering::SeqCst), 1); + poller.join().unwrap(); + leave.join().unwrap(); + } + + #[test] + fn devices_are_found_by_id_and_rumble_reaches_the_host() { + let (hub, host) = fake(); + host.lock().unwrap().pads[2] = Some(PadState::default()); + hub.poll(); + let device = &hub.devices[2] as *const Device; + let info = slot:: *const u8, _>(device, 0x18); + // SAFETY: the info has the id at +0x20. + let id = unsafe { *(info(device).add(0x20) as *const [u8; 32]) }; + assert_ne!(id, [0; 32]); + + type Find = extern "system" fn(This, *const [u8; 32], Out) -> HRESULT; + let find = slot::(&hub.object, 0x80); + let mut out = std::ptr::null(); + assert_eq!(find(&hub.object, &id, &mut out), S_OK); + assert_eq!(out, device.cast()); + assert_eq!(find(&hub.object, &[1; 32], &mut out), DEVICE_NOT_FOUND); + assert!(out.is_null()); + + type Rumble = extern "system" fn(*const Device, *const [f32; 4]); + let rumble = slot::(device, 0x50); + rumble(device, &[0.5, 1.0, 1.0, 1.0]); + rumble(&hub.devices[FALLBACK], &[1.0; 4]); + rumble(device, std::ptr::null()); + assert_eq!(host.lock().unwrap().rumble, [(2, 32767, 65535), (2, 0, 0)]); + } +} diff --git a/crates/leonida-hle/src/modules/kernel.rs b/crates/leonida-hle/src/modules/kernel.rs new file mode 100644 index 000000000..b9ba6e0ad --- /dev/null +++ b/crates/leonida-hle/src/modules/kernel.rs @@ -0,0 +1,687 @@ +//! Overrides of shared Windows APIs whose console meaning differs. +//! +//! Only the differences live here; everything else passes through to the +//! host (see `HostPolicy`). +#![allow(non_snake_case)] +// Title code calls these through its import table, passing pointers the real +// API would trust. +#![allow(clippy::not_unsafe_ptr_arg_deref)] + +use std::ffi::{CStr, c_void}; + +use crate::{HleModule, HostPolicy, hle_export, registry, runtime}; + +/// `GetModuleHandleW(NULL)` must return the title's image, not our exe; +/// title images and our console modules are found by name. +pub extern "system" fn GetModuleHandleW(name: *const u16) -> *mut c_void { + if name.is_null() { + return runtime::main_image().unwrap_or(0) as *mut c_void; + } + find_module(&wide(name), false).unwrap_or_else(|| host::get_module_handle_w(name)) +} + +/// See [`GetModuleHandleW`]. +pub extern "system" fn GetModuleHandleA(name: *const u8) -> *mut c_void { + if name.is_null() { + return runtime::main_image().unwrap_or(0) as *mut c_void; + } + find_module(&narrow(name), false).unwrap_or_else(|| host::get_module_handle_a(name)) +} + +/// A NUL-terminated string from the title. +fn narrow(text: *const u8) -> String { + // SAFETY: the title passes a NUL-terminated string. + unsafe { CStr::from_ptr(text.cast()) } + .to_string_lossy() + .into_owned() +} + +/// See [`narrow`]. +fn wide(text: *const u16) -> String { + // SAFETY: the title passes a NUL-terminated string. + unsafe { + let len = (0..).take_while(|&i| *text.add(i) != 0).count(); + String::from_utf16_lossy(std::slice::from_raw_parts(text, len)) + } +} + +/// A title image's path is its original file, not our cache copy; +/// `NULL` means the title's exe. +pub extern "system" fn GetModuleFileNameW(module: *mut c_void, out: *mut u16, size: u32) -> u32 { + let Some(path) = title_path(module) else { + return host::get_module_file_name_w(module, out, size); + }; + let wide: Vec = path.encode_utf16().collect(); + // SAFETY: the title passes a buffer of `size` characters. + copy_truncated(&wide, unsafe { + std::slice::from_raw_parts_mut(out, size as usize) + }) +} + +/// See [`GetModuleFileNameW`]. +pub extern "system" fn GetModuleFileNameA(module: *mut c_void, out: *mut u8, size: u32) -> u32 { + let Some(path) = title_path(module) else { + return host::get_module_file_name_a(module, out, size); + }; + // SAFETY: the title passes a buffer of `size` bytes. + copy_truncated(path.as_bytes(), unsafe { + std::slice::from_raw_parts_mut(out, size as usize) + }) +} + +fn title_path(module: *mut c_void) -> Option { + let base = if module.is_null() { + runtime::main_image()? + } else { + module as usize + }; + Some(runtime::image_path(base)?.to_string_lossy().into_owned()) +} + +/// `GetModuleFileName`'s contract: copy with a NUL; if it does not fit, +/// truncate to the buffer, report `ERROR_INSUFFICIENT_BUFFER` and return +/// the buffer size. +fn copy_truncated(text: &[T], out: &mut [T]) -> u32 { + let Some(room) = out.len().checked_sub(1) else { + host::set_last_error(ERROR_INSUFFICIENT_BUFFER); + return 0; + }; + let n = text.len().min(room); + out[..n].copy_from_slice(&text[..n]); + out[n] = T::default(); + if n < text.len() { + host::set_last_error(ERROR_INSUFFICIENT_BUFFER); + return out.len() as u32; + } + n as u32 +} + +const ERROR_INSUFFICIENT_BUFFER: u32 = 122; + +/// Console-only DLLs we implement load as a pseudo handle (titles load +/// `xgameruntime.dll` this way), the title's DLLs as the images we map +/// (on first use if nothing imports them); anything else loads on the host. +pub extern "system" fn LoadLibraryExA( + name: *const u8, + file: *mut c_void, + flags: u32, +) -> *mut c_void { + if !name.is_null() + && let Some(handle) = find_module(&narrow(name), runs_code(flags)) + { + return handle; + } + host::load_library_ex_a(name, file, flags) +} + +/// See [`LoadLibraryExA`]. +pub extern "system" fn LoadLibraryExW( + name: *const u16, + file: *mut c_void, + flags: u32, +) -> *mut c_void { + if !name.is_null() + && let Some(handle) = find_module(&wide(name), runs_code(flags)) + { + return handle; + } + host::load_library_ex_w(name, file, flags) +} + +/// False for loads as data or resources (`DONT_RESOLVE_DLL_REFERENCES`, +/// `LOAD_LIBRARY_AS_DATAFILE(_EXCLUSIVE)`, `AS_IMAGE_RESOURCE`): those run +/// no code, so a title DLL we have not mapped can go to the host. +fn runs_code(flags: u32) -> bool { + flags & (0x1 | 0x2 | 0x20 | 0x40) == 0 +} + +pub extern "system" fn LoadLibraryA(name: *const u8) -> *mut c_void { + LoadLibraryExA(name, std::ptr::null_mut(), 0) +} + +pub extern "system" fn LoadLibraryW(name: *const u16) -> *mut c_void { + LoadLibraryExW(name, std::ptr::null_mut(), 0) +} + +/// Looks up our implementations behind a pseudo handle; real modules go to +/// the host. +pub extern "system" fn GetProcAddress(module: *mut c_void, name: *const u8) -> *mut c_void { + // `NULL` is the process's exe, which for the title is its own image. + let module = if module.is_null() { + runtime::main_image().unwrap_or(0) as *mut c_void + } else { + module + }; + let Some(m) = registry().iter().find(|m| handle(m) == module) else { + return host_override(module, name).unwrap_or_else(|| host::get_proc_address(module, name)); + }; + // Values below 0x10000 are ordinals; we export by name only. + if (name as usize) < 0x1_0000 { + tracing::warn!( + module = m.name, + ordinal = name as usize, + "GetProcAddress by ordinal" + ); + return std::ptr::null_mut(); + } + // SAFETY: not an ordinal, so the title passes a NUL-terminated name. + let name = unsafe { CStr::from_ptr(name.cast()) }.to_string_lossy(); + match m.exports.iter().find(|e| e.name == name) { + Some(e) => e.address as *mut c_void, + None => { + tracing::warn!(module = m.name, %name, "GetProcAddress: not implemented"); + std::ptr::null_mut() + } + } +} + +/// What a host module's `name` (or ordinal) is bound to at import binding +/// when we override it: a title that looks a function up by name must not +/// get past our overrides (the network guard, path rewriting). +fn host_override(module: *mut c_void, name: *const u8) -> Option<*mut c_void> { + if module.is_null() || runtime::image_path(module as usize).is_some() { + return None; + } + let symbol = if (name as usize) < 0x1_0000 { + format!("#{}", name as usize) + } else { + narrow(name) + }; + let mut path = [0u16; 260]; + let len = host::get_module_file_name_w(module, path.as_mut_ptr(), path.len() as u32) as usize; + let path = String::from_utf16_lossy(&path[..len.min(path.len())]); + let file = path.rsplit('\\').next()?; + crate::registry::lookup(file, &symbol).map(|address| address as *mut c_void) +} + +/// Our pseudo modules and the title's images stay loaded: `LoadLibrary` +/// took no reference on them, so the host's count must not drop. +pub extern "system" fn FreeLibrary(module: *mut c_void) -> i32 { + if registry().iter().any(|m| handle(m) == module) + || runtime::image_path(module as usize).is_some() + { + return 1; + } + host::free_library(module) +} + +/// Title images hear of thread starts and ends from us, not from the +/// Windows loader (`leonida_loader::disable_thread_calls`). +pub extern "system" fn DisableThreadLibraryCalls(module: *mut c_void) -> i32 { + host::disable_thread_library_calls(module) +} + +/// Title debug output goes to our log (no debugger needs to be attached). +pub extern "system" fn OutputDebugStringA(text: *const u8) { + if !text.is_null() { + let text = narrow(text); + host::note_title_output(text.trim()); + tracing::info!(target: "title", "{}", text.trim_end()); + } +} + +/// See [`OutputDebugStringA`]. +pub extern "system" fn OutputDebugStringW(text: *const u16) { + if !text.is_null() { + let text = wide(text); + host::note_title_output(text.trim()); + tracing::info!(target: "title", "{}", text.trim_end()); + } +} + +/// The CRT's `exit`, through which the title's entry point returns: logs +/// the code and the caller, then exits on the host. +pub extern "C" fn exit(code: i32) -> ! { + tracing::warn!(code, from = %host::callers(), "title exits"); + host::exit(code) +} + +/// The CRT's `abort` (also reached from `terminate`): logged like [`exit`]. +pub extern "C" fn abort() -> ! { + tracing::error!(from = %host::callers(), "title aborts"); + host::abort() +} + +/// The CRT's `terminate` and the STL's invalid-argument exit: logged, then +/// the host's `abort`. +pub extern "C" fn terminate() -> ! { + tracing::error!(from = %host::callers(), "title calls terminate"); + host::abort() +} + +/// See [`terminate`]. +pub extern "C" fn _invalid_parameter_noinfo_noreturn() -> ! { + tracing::error!(from = %host::callers(), "title passed an invalid parameter"); + host::abort() +} + +/// The title's unhandled-exception filter. Ours stands in front of it and +/// reports the crash first; the title still gets its own back. +static TITLE_FILTER: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); + +pub extern "system" fn SetUnhandledExceptionFilter(filter: usize) -> usize { + host::set_unhandled_exception_filter(report_unhandled); + TITLE_FILTER.swap(filter, std::sync::atomic::Ordering::AcqRel) +} + +extern "system" fn report_unhandled(info: *const c_void) -> i32 { + host::report_unhandled(info); + match TITLE_FILTER.load(std::sync::atomic::Ordering::Acquire) { + 0 => 0, // EXCEPTION_CONTINUE_SEARCH + filter => { + type Filter = extern "system" fn(*const c_void) -> i32; + // SAFETY: the title registered this filter. + let filter: Filter = unsafe { std::mem::transmute(filter) }; + filter(info) + } + } +} + +/// See [`exit`]; only the current process is logged. +pub extern "system" fn TerminateProcess(process: *mut c_void, code: u32) -> i32 { + if process as isize == -1 { + tracing::warn!(code, from = %host::callers(), "title terminates the process"); + } + host::terminate_process(process, code) +} + +/// The pseudo handle of one of our modules: its address, never a real image. +fn handle(m: &HleModule) -> *mut c_void { + m as *const HleModule as *mut c_void +} + +/// The title's images and our console modules by name; `None` leaves the +/// name to the host, which only DLLs `HostPolicy` passes through get (as at +/// import binding); others fail. With `load`, a title DLL not mapped yet is +/// mapped now. +fn find_module(path: &str, load: bool) -> Option<*mut c_void> { + let file = path.rsplit(['\\', '/']).next().unwrap_or(path); + // As the Windows loader does, a name without extension means a DLL. + let file = if file.contains('.') { + file.to_owned() + } else { + format!("{file}.dll") + }; + // Loads go through the title DLL loader first: it waits for a DLL that + // another thread is still initialising, as the Windows loader lock does. + if load { + match runtime::load_title_dll(&file) { + Ok(Some(base)) => return Some(base as *mut c_void), + Ok(None) => {} + // Not the host: it would load the unpatched DLL from the title's folder. + Err(error) => { + tracing::error!(dll = file, %error, "mapping a title DLL failed"); + host::set_last_error(ERROR_MOD_NOT_FOUND); + return Some(std::ptr::null_mut()); + } + } + } + if let Some(base) = runtime::image_named(&file) { + return Some(base as *mut c_void); + } + // DLLs the host has too are real host modules, whatever `--strict` says. + let host_dll = HostPolicy::default().allows(&file); + if !host_dll && let Some(m) = registry().iter().find(|m| m.serves(&file)) { + if load { + tracing::info!(dll = file, "loaded as a pseudo module"); + } + return Some(handle(m)); + } + if host_dll { + return None; + } + // Any other host DLL (wininet, urlmon, ...) is beyond what we guard, and + // the console does not have it. + refuse(&file); + host::set_last_error(ERROR_MOD_NOT_FOUND); + Some(std::ptr::null_mut()) +} + +/// Logs a DLL name the title is refused, once. +fn refuse(file: &str) { + static REFUSED: std::sync::Mutex> = std::sync::Mutex::new(Vec::new()); + let file = file.to_ascii_lowercase(); + let mut refused = REFUSED.lock().unwrap_or_else(|e| e.into_inner()); + if !refused.contains(&file) { + tracing::warn!(dll = file, "a host DLL outside the host policy: refused"); + refused.push(file); + } +} + +const ERROR_MOD_NOT_FOUND: u32 = 126; + +pub(crate) fn module() -> HleModule { + HleModule { + name: "kernel", + dlls: &[ + "kernel32.dll", + "kernelbase.dll", + "api-ms-win-core-libraryloader-*", + "api-ms-win-core-processthreads-*", + "api-ms-win-core-debug-*", + "api-ms-win-core-errorhandling-*", + "api-ms-win-crt-runtime-*", + ], + exports: vec![ + hle_export!(GetModuleHandleW), + hle_export!(GetModuleHandleA), + hle_export!(GetModuleFileNameW), + hle_export!(GetModuleFileNameA), + hle_export!(LoadLibraryExA), + hle_export!(LoadLibraryExW), + hle_export!(LoadLibraryA), + hle_export!(LoadLibraryW), + hle_export!(GetProcAddress), + hle_export!(FreeLibrary), + hle_export!(DisableThreadLibraryCalls), + hle_export!(OutputDebugStringA), + hle_export!(OutputDebugStringW), + hle_export!(exit), + hle_export!(abort), + hle_export!(terminate), + hle_export!(_invalid_parameter_noinfo_noreturn), + hle_export!(TerminateProcess), + hle_export!(SetUnhandledExceptionFilter), + ], + } +} + +/// The return addresses above the caller, as `module+rva`, for logs. +#[cfg(feature = "diagnostics")] +pub(crate) fn callers() -> String { + host::callers() +} + +#[cfg(windows)] +mod host { + use std::ffi::c_void; + + use windows_sys::Win32::Foundation::{FreeLibrary, SetLastError}; + use windows_sys::Win32::System::Diagnostics::Debug::RtlCaptureStackBackTrace; + use windows_sys::Win32::System::LibraryLoader::{ + DisableThreadLibraryCalls, GetModuleFileNameA, GetModuleFileNameW, GetModuleHandleA, + GetModuleHandleW, GetProcAddress, LoadLibraryExA, LoadLibraryExW, + }; + use windows_sys::Win32::System::Threading::TerminateProcess; + + unsafe extern "C" { + #[link_name = "exit"] + fn crt_exit(code: i32) -> !; + #[link_name = "abort"] + fn crt_abort() -> !; + } + + // SAFETY (every function): forwarding the title's own arguments to the + // host API of the same name. + + pub(super) fn get_module_handle_w(name: *const u16) -> *mut c_void { + // SAFETY: see above. + unsafe { GetModuleHandleW(name) } + } + + pub(super) fn get_module_handle_a(name: *const u8) -> *mut c_void { + // SAFETY: see above. + unsafe { GetModuleHandleA(name) } + } + + pub(super) fn get_module_file_name_w(module: *mut c_void, out: *mut u16, size: u32) -> u32 { + // SAFETY: see above. + unsafe { GetModuleFileNameW(module, out, size) } + } + + pub(super) fn get_module_file_name_a(module: *mut c_void, out: *mut u8, size: u32) -> u32 { + // SAFETY: see above. + unsafe { GetModuleFileNameA(module, out, size) } + } + + pub(super) fn set_last_error(code: u32) { + // SAFETY: see above. + unsafe { SetLastError(code) } + } + + pub(super) fn load_library_ex_a(name: *const u8, file: *mut c_void, flags: u32) -> *mut c_void { + // SAFETY: see above. + unsafe { LoadLibraryExA(name, file, flags) } + } + + pub(super) fn load_library_ex_w( + name: *const u16, + file: *mut c_void, + flags: u32, + ) -> *mut c_void { + // SAFETY: see above. + unsafe { LoadLibraryExW(name, file, flags) } + } + + pub(super) fn get_proc_address(module: *mut c_void, name: *const u8) -> *mut c_void { + // SAFETY: see above. + unsafe { GetProcAddress(module, name) }.map_or(std::ptr::null_mut(), |f| f as *mut c_void) + } + + pub(super) fn free_library(module: *mut c_void) -> i32 { + // SAFETY: see above. + unsafe { FreeLibrary(module) } + } + + pub(super) fn disable_thread_library_calls(module: *mut c_void) -> i32 { + match leonida_loader::disable_thread_calls(module as usize) { + Some(done) => i32::from(done), + // SAFETY: see above. + None => unsafe { DisableThreadLibraryCalls(module) }, + } + } + + pub(super) fn exit(code: i32) -> ! { + // SAFETY: see above. + unsafe { crt_exit(code) } + } + + pub(super) fn abort() -> ! { + // SAFETY: see above. + unsafe { crt_abort() } + } + + pub(super) fn terminate_process(process: *mut c_void, code: u32) -> i32 { + // SAFETY: see above. + unsafe { TerminateProcess(process, code) } + } + + pub(super) fn set_unhandled_exception_filter(filter: extern "system" fn(*const c_void) -> i32) { + // SAFETY: our filter takes the exception pointers as an opaque pointer. + unsafe { + windows_sys::Win32::System::Diagnostics::Debug::SetUnhandledExceptionFilter( + std::mem::transmute::< + extern "system" fn(*const c_void) -> i32, + windows_sys::Win32::System::Diagnostics::Debug::LPTOP_LEVEL_EXCEPTION_FILTER, + >(filter), + ) + }; + } + + pub(super) fn report_unhandled(info: *const c_void) { + // SAFETY: the system's exception pointers, passed to the filter. + unsafe { leonida_loader::report_unhandled(info.cast()) }; + } + + pub(super) fn note_title_output(line: &str) { + leonida_loader::note_title_output(line); + } + + /// Our caller's callers, as `module+rva`. + pub(super) fn callers() -> String { + let mut frames = [std::ptr::null_mut(); 12]; + // SAFETY: fills at most `frames.len()` return addresses. + let n = unsafe { + RtlCaptureStackBackTrace( + 2, + frames.len() as u32, + frames.as_mut_ptr(), + std::ptr::null_mut(), + ) + }; + let names: Vec<_> = frames[..usize::from(n)] + .iter() + .map(|&f| leonida_loader::locate(f as usize)) + .collect(); + names.join(" < ") + } +} + +#[cfg(not(windows))] +mod host { + use std::ffi::c_void; + + pub(super) fn get_module_handle_w(_: *const u16) -> *mut c_void { + std::ptr::null_mut() + } + + pub(super) fn get_module_handle_a(_: *const u8) -> *mut c_void { + std::ptr::null_mut() + } + + pub(super) fn load_library_ex_a(_: *const u8, _: *mut c_void, _: u32) -> *mut c_void { + std::ptr::null_mut() + } + + pub(super) fn get_module_file_name_w(_: *mut c_void, _: *mut u16, _: u32) -> u32 { + 0 + } + + pub(super) fn get_module_file_name_a(_: *mut c_void, _: *mut u8, _: u32) -> u32 { + 0 + } + + pub(super) fn set_last_error(_: u32) {} + + pub(super) fn load_library_ex_w(_: *const u16, _: *mut c_void, _: u32) -> *mut c_void { + std::ptr::null_mut() + } + + pub(super) fn get_proc_address(_: *mut c_void, _: *const u8) -> *mut c_void { + std::ptr::null_mut() + } + + pub(super) fn free_library(_: *mut c_void) -> i32 { + 0 + } + + pub(super) fn disable_thread_library_calls(_: *mut c_void) -> i32 { + 0 + } + + pub(super) fn exit(code: i32) -> ! { + std::process::exit(code) + } + + pub(super) fn abort() -> ! { + std::process::abort() + } + + pub(super) fn terminate_process(_: *mut c_void, code: u32) -> i32 { + std::process::exit(code as i32) + } + + pub(super) fn set_unhandled_exception_filter(_: extern "system" fn(*const c_void) -> i32) {} + + pub(super) fn report_unhandled(_: *const c_void) {} + + pub(super) fn note_title_output(_: &str) {} + + pub(super) fn callers() -> String { + String::new() + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn title_images_report_their_original_path() { + let base = 0x7000_0000_0000; + runtime::set_image_path(base, std::path::Path::new(r"C:\title\game.exe")); + let module = base as *mut c_void; + let mut buf = [0xFFFFu16; 32]; + let n = GetModuleFileNameW(module, buf.as_mut_ptr(), buf.len() as u32); + assert_eq!( + String::from_utf16_lossy(&buf[..n as usize]), + r"C:\title\game.exe" + ); + assert_eq!(buf[n as usize], 0); + + // Too small: truncated, NUL-terminated, the buffer size returned. + let mut small = [0u8; 4]; + assert_eq!(GetModuleFileNameA(module, small.as_mut_ptr(), 4), 4); + assert_eq!(&small, &[b'C', b':', b'\\', 0]); + } + + fn w(text: &str) -> Vec { + text.encode_utf16().chain(Some(0)).collect() + } + + #[cfg(windows)] + #[test] + fn host_lookups_by_name_get_our_overrides() { + let kernel32 = GetModuleHandleW(w("kernel32.dll").as_ptr()); + assert!(!kernel32.is_null()); + let ours = crate::registry::lookup("kernel32.dll", "CreateFileW").unwrap(); + assert_eq!( + GetProcAddress(kernel32, c"CreateFileW".as_ptr().cast()) as usize, + ours + ); + // A plain name stays the host's. + let host = host::get_proc_address(kernel32, c"GetTickCount".as_ptr().cast()); + assert!(!host.is_null()); + assert_eq!( + GetProcAddress(kernel32, c"GetTickCount".as_ptr().cast()), + host + ); + // Host DLLs outside the host policy do not exist for the title. + assert!(LoadLibraryW(w("wininet.dll").as_ptr()).is_null()); + assert!(LoadLibraryA(c"C:\\Windows\\System32\\urlmon".as_ptr().cast()).is_null()); + assert!(GetModuleHandleW(w("WININET.DLL").as_ptr()).is_null()); + assert_eq!( + // SAFETY: reads this thread's last error. + unsafe { windows_sys::Win32::Foundation::GetLastError() }, + ERROR_MOD_NOT_FOUND + ); + assert!(!LoadLibraryW(w("kernel32").as_ptr()).is_null()); + // By ordinal too (ws2_32 #4 is `connect`). + let ws2 = LoadLibraryW(w("ws2_32.dll").as_ptr()); + assert_eq!( + GetProcAddress(ws2, 4 as *const u8) as usize, + crate::registry::lookup("ws2_32.dll", "connect").unwrap() + ); + } + + #[test] + fn title_dlls_and_pseudo_modules_are_found_by_name() { + let base = 0x7100_0000_0000usize; + runtime::set_image_path(base, std::path::Path::new(r"C:\title\Mapped.dll")); + runtime::set_title_dll_loader(Box::new(|file| match file { + "late.dll" => Ok(Some(0x7200_0000_0000)), + "broken.dll" => Err("bad image".into()), + _ => Ok(None), + })); + let mapped = base as *mut c_void; + assert_eq!(GetModuleHandleW(w("MAPPED").as_ptr()), mapped); + assert_eq!(GetModuleHandleA(c"sub\\mapped.dll".as_ptr().cast()), mapped); + assert_eq!(LoadLibraryW(w("mapped.dll").as_ptr()), mapped); + assert_eq!(FreeLibrary(mapped), 1, "title images stay loaded"); + + // Not mapped yet: `LoadLibrary` maps it, `GetModuleHandle` does not. + assert!(GetModuleHandleW(w("late.dll").as_ptr()).is_null()); + assert_eq!( + LoadLibraryA(c"late".as_ptr().cast()) as usize, + 0x7200_0000_0000 + ); + assert!(LoadLibraryA(c"broken.dll".as_ptr().cast()).is_null()); + // As data it runs no code, so the host loads it (and finds nothing). + let data = LoadLibraryExW(w("late.dll").as_ptr(), std::ptr::null_mut(), 0x2); + assert_ne!(data as usize, 0x7200_0000_0000); + + let runtime = LoadLibraryA(c"xgameruntime.dll".as_ptr().cast()); + assert!(!runtime.is_null()); + assert_eq!(GetModuleHandleW(w("XGameRuntime.dll").as_ptr()), runtime); + } +} diff --git a/crates/leonida-hle/src/modules/lifecycle.rs b/crates/leonida-hle/src/modules/lifecycle.rs new file mode 100644 index 000000000..414b85efd --- /dev/null +++ b/crates/leonida-hle/src/modules/lifecycle.rs @@ -0,0 +1,438 @@ +//! The title's life cycle. A console title is never told it is closing: +//! quitting it or launching a new game first suspends it (its suspend +//! routines run, and it has a second to save) and then ends the process. +//! Closing the title's window does the same here; a new launch then starts +//! `leonida` again, which waits for this process to be gone. +#![allow(non_snake_case)] +#![allow(clippy::not_unsafe_ptr_arg_deref)] +#![allow(clippy::too_many_arguments)] + +use std::ffi::c_void; +use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; +use std::sync::{Mutex, MutexGuard}; +use std::time::Duration; + +use windows_sys::Win32::Foundation::{HINSTANCE, HWND, LPARAM, LRESULT, RECT, WPARAM}; +use windows_sys::Win32::System::Threading::{GetCurrentProcess, TerminateProcess}; +use windows_sys::Win32::UI::WindowsAndMessaging::{self as wm, HMENU}; +use windows_sys::core::{PCSTR, PCWSTR, w}; + +use crate::{HleModule, hle_export}; + +type Routine = extern "system" fn(quiesced: u8, context: *mut c_void); + +/// Registration id, routine and context of each suspend routine. +static ROUTINES: Mutex> = Mutex::new(Vec::new()); + +fn routines() -> MutexGuard<'static, Vec<(usize, Routine, usize)>> { + ROUTINES.lock().unwrap_or_else(|e| e.into_inner()) +} + +/// How long the console lets suspend routines run before it ends the title. +const SUSPEND_DEADLINE: Duration = Duration::from_secs(1); + +const ERROR_INVALID_PARAMETER: u32 = 87; + +pub extern "system" fn RegisterAppStateChangeNotification( + routine: Option, + context: *mut c_void, + registration: *mut usize, +) -> u32 { + let Some(routine) = routine else { + return ERROR_INVALID_PARAMETER; + }; + if registration.is_null() { + return ERROR_INVALID_PARAMETER; + } + static NEXT: AtomicUsize = AtomicUsize::new(1); + let id = NEXT.fetch_add(1, Ordering::Relaxed); + routines().push((id, routine, context as usize)); + // SAFETY: checked non-null; the title passes room for its registration. + unsafe { registration.write(id) }; + 0 +} + +pub extern "system" fn UnregisterAppStateChangeNotification(registration: usize) { + routines().retain(|&(id, ..)| id != registration); +} + +/// The window procedure a title window had before ours. +const TITLE_PROC: PCWSTR = w!("leonida.wndproc"); + +pub extern "system" fn CreateWindowExW( + ex_style: u32, + class: PCWSTR, + name: PCWSTR, + style: u32, + x: i32, + y: i32, + width: i32, + height: i32, + parent: HWND, + menu: HMENU, + instance: HINSTANCE, + param: *const c_void, +) -> HWND { + let (x, y, width, height) = fit(parent, x, y, width, height); + // SAFETY: the title's own arguments, forwarded (the size fitted). + let hwnd = unsafe { + wm::CreateWindowExW( + ex_style, class, name, style, x, y, width, height, parent, menu, instance, param, + ) + }; + hook(hwnd); + hwnd +} + +/// See [`CreateWindowExW`]. +pub extern "system" fn CreateWindowExA( + ex_style: u32, + class: PCSTR, + name: PCSTR, + style: u32, + x: i32, + y: i32, + width: i32, + height: i32, + parent: HWND, + menu: HMENU, + instance: HINSTANCE, + param: *const c_void, +) -> HWND { + let (x, y, width, height) = fit(parent, x, y, width, height); + // SAFETY: the title's own arguments, forwarded (the size fitted). + let hwnd = unsafe { + wm::CreateWindowExA( + ex_style, class, name, style, x, y, width, height, parent, menu, instance, param, + ) + }; + hook(hwnd); + hwnd +} + +/// A console title sizes its window to its render target ( +/// the title: 3840x2160 on a Series X), which can exceed the host's screen. +/// A top-level window larger than the work area is shrunk to fit, keeping +/// its proportions, and centred; what it shows is scaled to it (the swap +/// chain stretches). +fn fit(parent: HWND, x: i32, y: i32, width: i32, height: i32) -> (i32, i32, i32, i32) { + let mut area = RECT::default(); + // SAFETY: `area` receives the primary monitor's work area. + let known = + unsafe { wm::SystemParametersInfoW(wm::SPI_GETWORKAREA, 0, (&raw mut area).cast(), 0) }; + let fitted = fit_into(&area, width, height); + if !parent.is_null() || known == 0 || fitted == (width, height) { + return (x, y, width, height); + } + tracing::info!(width, height, to = ?fitted, "title window fitted to the screen"); + let (w, h) = fitted; + let left = area.left + (area.right - area.left - w) / 2; + let top = area.top + (area.bottom - area.top - h) / 2; + (left, top, w, h) +} + +/// `width` x `height` scaled down to fit `area`, or unchanged if it fits +/// (or is `CW_USEDEFAULT`). +fn fit_into(area: &RECT, width: i32, height: i32) -> (i32, i32) { + let (aw, ah) = (area.right - area.left, area.bottom - area.top); + if width <= 0 || height <= 0 || aw <= 0 || ah <= 0 || (width <= aw && height <= ah) { + return (width, height); + } + let scale = f64::min( + f64::from(aw) / f64::from(width), + f64::from(ah) / f64::from(height), + ); + ( + (f64::from(width) * scale) as i32, + (f64::from(height) * scale) as i32, + ) +} + +/// Puts our procedure in front of the title's. +fn hook(hwnd: HWND) { + if hwnd.is_null() { + return; + } + // SAFETY: a window this thread just created. The title's procedure is + // stored before ours can run. + unsafe { + let title = wm::GetWindowLongPtrW(hwnd, wm::GWLP_WNDPROC); + wm::SetPropW(hwnd, TITLE_PROC, title as *mut c_void); + wm::SetWindowLongPtrW(hwnd, wm::GWLP_WNDPROC, window_proc as *const () as isize); + } +} + +extern "system" fn window_proc( + hwnd: HWND, + message: u32, + wparam: WPARAM, + lparam: LPARAM, +) -> LRESULT { + // A user close (close button, Alt+F4, window or taskbar menu); a + // console title never sees one, nor a WM_CLOSE from it. + if message == wm::WM_SYSCOMMAND && wparam & 0xFFF0 == wm::SC_CLOSE as usize { + end_title("window closed", Box::new(|| {})); + return 0; + } + // Alt or F10 puts a window into menu mode: the system runs a modal menu + // loop on the thread that owns the window, which is the title's. The + // title then stops (no frames, no input) until a key ends the loop, and + // nothing shows it, since the window has no menu bar; + // the title aborts itself about half a minute later. A console has no window + // menu. The mouse still opens it from the title bar. + if message == wm::WM_SYSCOMMAND && wparam & 0xFFF0 == wm::SC_KEYMENU as usize { + return 0; + } + // SAFETY: the procedure `hook` stored, called the way the system would. + unsafe { + let title = wm::GetPropW(hwnd, TITLE_PROC); + if message == wm::WM_NCDESTROY { + wm::RemovePropW(hwnd, TITLE_PROC); + } + let title = std::mem::transmute::<*mut c_void, wm::WNDPROC>(title); + wm::CallWindowProcW(title, hwnd, message, wparam, lparam) + } +} + +/// Suspends the title as the console does when it ends it, runs `then` +/// (once), then ends the process. Returns at once; later calls do nothing. +pub(crate) fn end_title(why: &'static str, then: Box) { + static ENDING: AtomicBool = AtomicBool::new(false); + if ENDING.swap(true, Ordering::SeqCst) { + return; + } + let suspend = routines().clone(); + tracing::info!(routines = suspend.len(), "{why}: suspending the title"); + // Whoever comes first (the routines or the deadline) runs `then`; the + // other waits for it, so the process never ends halfway through. + let then = std::sync::Arc::new(Mutex::new(Some(then))); + let finish = move |how: &str| { + let mut then = then.lock().unwrap_or_else(|e| e.into_inner()); + tracing::info!("{how}; ending the title"); + if let Some(then) = then.take() { + then(); + } + end(); + }; + let late = finish.clone(); + // Not on the calling thread: titles hand the suspend to their window + // thread and wait for it inside the routine. + std::thread::spawn(move || { + for (_, routine, context) in suspend { + routine(1, context as *mut c_void); + } + finish("title suspended"); + }); + std::thread::spawn(move || { + std::thread::sleep(SUSPEND_DEADLINE); + late("title did not finish suspending in time"); + }); +} + +/// Set in the environment of a relaunched `leonida`: an inherited handle +/// of the process it replaces. +const RELAUNCHED_FROM: &str = "LEONIDA_RELAUNCHED_FROM"; + +/// Starts `leonida` again with `args` (after the title has suspended); the +/// new process waits until this one has ended. +pub(crate) fn relaunch(args: Vec) { + use windows_sys::Win32::Foundation::{DUPLICATE_SAME_ACCESS, DuplicateHandle, HANDLE}; + let mut me: HANDLE = std::ptr::null_mut(); + // SAFETY: an inheritable duplicate of our own process handle. + let duplicated = unsafe { + DuplicateHandle( + GetCurrentProcess(), + GetCurrentProcess(), + GetCurrentProcess(), + &mut me, + 0, + 1, + DUPLICATE_SAME_ACCESS, + ) + } != 0; + let spawned = std::env::current_exe().and_then(|exe| { + let mut command = std::process::Command::new(exe); + command.args(&args); + if duplicated { + command.env(RELAUNCHED_FROM, (me as usize).to_string()); + } + command.spawn() + }); + match spawned { + Ok(child) => tracing::info!(pid = child.id(), ?args, "relaunched"), + Err(e) => tracing::warn!(%e, "relaunch failed; the title just ends"), + } +} + +/// In a relaunched `leonida`: waits (30 s at most) for the process it +/// replaces to be gone, so the two never share the title's files. +pub fn wait_for_previous() { + use windows_sys::Win32::Foundation::{CloseHandle, HANDLE}; + use windows_sys::Win32::System::Threading::WaitForSingleObject; + let Some(handle) = std::env::var(RELAUNCHED_FROM) + .ok() + .and_then(|h| h.parse::().ok()) + else { + return; + }; + // SAFETY: removing our own variable before any other thread reads it. + unsafe { std::env::remove_var(RELAUNCHED_FROM) }; + let handle = handle as HANDLE; + // SAFETY: the inherited process handle the previous process gave us. + unsafe { + WaitForSingleObject(handle, 30_000); + CloseHandle(handle); + } +} + +fn end() { + // Compiled host pipelines kept for the next run. + #[cfg(windows)] + leonida_gpu::pipeline::save_pipeline_cache(); + // SAFETY: ends this process, as the console ends a suspended title. + unsafe { TerminateProcess(GetCurrentProcess(), 0) }; +} + +pub(crate) fn module() -> HleModule { + HleModule { + name: "lifecycle", + dlls: &[ + "api-ms-win-core-psm-appnotify-*", + "ext-ms-win-rtcore-ntuser-window-*", + ], + exports: vec![ + hle_export!(RegisterAppStateChangeNotification), + hle_export!(UnregisterAppStateChangeNotification), + hle_export!(CreateWindowExW), + hle_export!(CreateWindowExA), + ], + } +} + +#[cfg(test)] +mod tests { + use super::*; + + extern "system" fn noop(_: u8, _: *mut c_void) {} + + #[test] + fn registrations_come_and_go() { + let (mut a, mut b) = (0, 0); + assert_eq!( + RegisterAppStateChangeNotification(Some(noop), std::ptr::null_mut(), &mut a), + 0 + ); + assert_eq!( + RegisterAppStateChangeNotification(Some(noop), std::ptr::null_mut(), &mut b), + 0 + ); + UnregisterAppStateChangeNotification(a); + let left: Vec<_> = routines().iter().map(|r| r.0).collect(); + assert_eq!(left, [b]); + } + + #[test] + fn oversized_windows_shrink_to_the_screen() { + let area = RECT { + left: 0, + top: 0, + right: 1920, + bottom: 1040, + }; + assert_eq!(fit_into(&area, 3840, 2160), (1848, 1040)); + assert_eq!(fit_into(&area, 1280, 720), (1280, 720)); + assert_eq!( + fit_into(&area, wm::CW_USEDEFAULT, 0), + (wm::CW_USEDEFAULT, 0) + ); + } + + #[test] + fn hooked_windows_still_reach_the_title_procedure() { + let null = std::ptr::null_mut(); + let hwnd = CreateWindowExW( + 0, + w!("STATIC"), + w!("before"), + 0, + 0, + 0, + 10, + 10, + null, + null, + null, + std::ptr::null(), + ); + assert!(!hwnd.is_null()); + let mut text = [0u16; 16]; + // SAFETY: our window; the buffer holds 16 characters. + unsafe { + wm::SetWindowTextW(hwnd, w!("after")); + let n = wm::GetWindowTextW(hwnd, text.as_mut_ptr(), 16); + assert_eq!(String::from_utf16_lossy(&text[..n as usize]), "after"); + assert!(!wm::GetPropW(hwnd, TITLE_PROC).is_null()); + wm::DestroyWindow(hwnd); + } + } + + thread_local! { + /// The system commands `recording` received, low four bits cleared. + static COMMANDS: std::cell::RefCell> = const { std::cell::RefCell::new(Vec::new()) }; + } + + /// Stands in for a title's procedure: notes system commands and acts + /// on none of them (no menu loop, no minimising). + extern "system" fn recording( + hwnd: HWND, + message: u32, + wparam: WPARAM, + lparam: LPARAM, + ) -> LRESULT { + if message == wm::WM_SYSCOMMAND { + COMMANDS.with(|c| c.borrow_mut().push(wparam & 0xFFF0)); + return 0; + } + // SAFETY: the system's default procedure, called as the system would. + unsafe { wm::DefWindowProcW(hwnd, message, wparam, lparam) } + } + + #[test] + fn the_keyboard_menu_never_reaches_the_title() { + let null = std::ptr::null_mut(); + let hwnd = CreateWindowExW( + 0, + w!("STATIC"), + w!("menu"), + 0, + 0, + 0, + 10, + 10, + null, + null, + null, + std::ptr::null(), + ); + assert!(!hwnd.is_null()); + // SAFETY: our window, owned by this thread, so each message is + // handled before SendMessageW returns. `recording` stands in for the + // title's procedure and the original is put back before the window + // is destroyed. + unsafe { + let title = wm::GetPropW(hwnd, TITLE_PROC); + wm::SetPropW(hwnd, TITLE_PROC, recording as *const () as *mut c_void); + let command = |c: u32, key: u8| { + wm::SendMessageW(hwnd, wm::WM_SYSCOMMAND, c as usize, LPARAM::from(key)) + }; + command(wm::SC_KEYMENU, 0); // Alt or F10 + command(wm::SC_KEYMENU, b' '); // Alt+Space + command(wm::SC_KEYMENU | 1, 0); // the low bits are the system's + command(wm::SC_MINIMIZE, 0); + wm::SetPropW(hwnd, TITLE_PROC, title); + wm::DestroyWindow(hwnd); + } + let seen = COMMANDS.with(|c| c.borrow().clone()); + assert_eq!(seen, [wm::SC_MINIMIZE as usize]); + } +} diff --git a/crates/leonida-hle/src/modules/media.rs b/crates/leonida-hle/src/modules/media.rs new file mode 100644 index 000000000..aa6e91c5b --- /dev/null +++ b/crates/leonida-hle/src/modules/media.rs @@ -0,0 +1,531 @@ +//! Media Foundation is the host's (`mfplat.dll` passes through), except for +//! the source resolver: the host's would fetch `http`, `rtsp` and other +//! URLs over the network, past `modules::net`. Titles get a proxy that +//! opens local files only, with paths on our virtual drives rewritten to +//! their host folders, and forwards everything else to the host's resolver. +#![allow(non_snake_case)] +#![allow(clippy::not_unsafe_ptr_arg_deref)] + +use std::collections::HashSet; +use std::ffi::c_void; +use std::sync::atomic::{AtomicU32, Ordering}; +use std::sync::{Mutex, OnceLock}; + +use super::files; +use super::xgameruntime::{HRESULT, S_OK}; +use crate::{HleModule, hle_export}; + +const E_NOINTERFACE: HRESULT = 0x8000_4002_u32 as i32; +const E_POINTER: HRESULT = 0x8000_4003_u32 as i32; +/// What Media Foundation answers for a URL scheme it has no handler for. +const UNSUPPORTED_SCHEME: HRESULT = 0xC00D_36C3_u32 as i32; + +const IID_IUNKNOWN: [u8; 16] = guid(0x0000_0000, 0x0000, 0x0000, [0xC0, 0, 0, 0, 0, 0, 0, 0x46]); +const IID_RESOLVER: [u8; 16] = guid( + 0xFBE5_A32D, + 0xA497, + 0x4B61, + [0xBB, 0x85, 0x97, 0xB1, 0xA8, 0x48, 0xA6, 0xE3], +); + +const fn guid(a: u32, b: u16, c: u16, d: [u8; 8]) -> [u8; 16] { + let (a, b, c) = (a.to_le_bytes(), b.to_le_bytes(), c.to_le_bytes()); + [ + a[0], a[1], a[2], a[3], b[0], b[1], c[0], c[1], d[0], d[1], d[2], d[3], d[4], d[5], d[6], + d[7], + ] +} + +// The URL rule. + +/// Where a resolver may read `url` from: `Ok` with the NUL-terminated +/// string to hand to the host, or `Err((scheme, host))` for anything that +/// is not a local file. +fn local(url: &[u16]) -> Result, (String, String)> { + let text = String::from_utf16_lossy(url); + let drive = |s: &str| { + let b = s.as_bytes(); + b.len() >= 2 && b[0].is_ascii_alphabetic() && b[1] == b':' + }; + let host_of = |rest: &str| rest.split(['/', '\\']).next().unwrap_or("").to_string(); + let path = if let Some(rest) = text.strip_prefix(r"\\?\") { + if !drive(rest) { + return Err(("unc".into(), host_of(rest.trim_start_matches("UNC\\")))); + } + text.clone() + } else if let Some(rest) = text.strip_prefix(r"\\").or_else(|| text.strip_prefix("//")) { + return Err(("unc".into(), host_of(rest))); + } else if drive(&text) { + text.clone() + } else if let Some((scheme, rest)) = text.split_once(':').filter(|(s, _)| { + s.len() > 1 + && s.bytes() + .all(|c| c.is_ascii_alphanumeric() || b"+-.".contains(&c)) + }) { + let scheme = scheme.to_ascii_lowercase(); + let authority = rest.strip_prefix("//"); + if scheme != "file" { + return Err((scheme, authority.map(host_of).unwrap_or_default())); + } + let path = match authority { + Some(rest) => { + let host = host_of(rest); + if !host.is_empty() && !host.eq_ignore_ascii_case("localhost") { + return Err((scheme, host)); + } + &rest[host.len()..] + } + None => rest, + }; + let path = percent_decode(path.trim_start_matches(['/', '\\'])).replace('/', "\\"); + if !drive(&path) { + // A local file without a drive: the host resolves it as is. + return Ok(with_nul(url)); + } + path + } else { + // A relative path. + return Ok(with_nul(url)); + }; + let wide: Vec = path.encode_utf16().collect(); + Ok(files::translate(&wide).unwrap_or_else(|| with_nul(&wide))) +} + +fn with_nul(s: &[u16]) -> Vec { + s.iter().copied().chain([0]).collect() +} + +fn percent_decode(s: &str) -> String { + let b = s.as_bytes(); + let mut out = Vec::with_capacity(b.len()); + let mut i = 0; + while i < b.len() { + let hex = b + .get(i + 1..i + 3) + .and_then(|h| std::str::from_utf8(h).ok()); + match (b[i], hex.and_then(|h| u8::from_str_radix(h, 16).ok())) { + (b'%', Some(v)) => { + out.push(v); + i += 3; + } + (c, _) => { + out.push(c); + i += 1; + } + } + } + String::from_utf8_lossy(&out).into_owned() +} + +/// The URL to give the host, or the refusal (logged once per scheme and +/// host). +fn checked(url: *const u16) -> Result, HRESULT> { + if url.is_null() { + return Err(E_POINTER); + } + // SAFETY: a NUL-terminated wide string from the title. + let len = (0..) + .take_while(|&i| unsafe { url.add(i).read() } != 0) + .count(); + // SAFETY: as above, `len` characters before the NUL. + let wide = unsafe { std::slice::from_raw_parts(url, len) }; + local(wide).map_err(|(scheme, host)| { + static REFUSED: Mutex>> = Mutex::new(None); + let mut refused = REFUSED.lock().unwrap_or_else(|e| e.into_inner()); + if refused + .get_or_insert_with(HashSet::new) + .insert((scheme.clone(), host.clone())) + { + tracing::warn!( + scheme, + host, + "media: refused a URL that is not a local file" + ); + } + UNSUPPORTED_SCHEME + }) +} + +// The proxy resolver. + +/// The host's resolver, called through its method table. +#[repr(C)] +struct Host { + vtable: *const usize, +} + +impl Host { + /// Method `n` of the host object, typed by the caller. + unsafe fn method(this: *mut Host, n: usize) -> F { + // SAFETY: the caller names the slot's real signature; `this` is the + // host's live resolver. + unsafe { std::mem::transmute_copy(&*(*this).vtable.add(n)) } + } +} + +#[repr(C)] +pub struct Resolver { + vtable: &'static Methods, + host: *mut Host, + refs: AtomicU32, +} + +type Unknown = *mut c_void; + +#[repr(C)] +struct Methods { + query_interface: + extern "system" fn(*mut Resolver, *const [u8; 16], *mut *mut c_void) -> HRESULT, + add_ref: extern "system" fn(*mut Resolver) -> u32, + release: extern "system" fn(*mut Resolver) -> u32, + create_from_url: extern "system" fn( + *mut Resolver, + *const u16, + u32, + Unknown, + *mut u32, + *mut Unknown, + ) -> HRESULT, + create_from_stream: extern "system" fn( + *mut Resolver, + Unknown, + *const u16, + u32, + Unknown, + *mut u32, + *mut Unknown, + ) -> HRESULT, + begin_from_url: extern "system" fn( + *mut Resolver, + *const u16, + u32, + Unknown, + *mut Unknown, + Unknown, + Unknown, + ) -> HRESULT, + end_from_url: extern "system" fn(*mut Resolver, Unknown, *mut u32, *mut Unknown) -> HRESULT, + begin_from_stream: extern "system" fn( + *mut Resolver, + Unknown, + *const u16, + u32, + Unknown, + *mut Unknown, + Unknown, + Unknown, + ) -> HRESULT, + end_from_stream: extern "system" fn(*mut Resolver, Unknown, *mut u32, *mut Unknown) -> HRESULT, + cancel: extern "system" fn(*mut Resolver, Unknown) -> HRESULT, +} + +static METHODS: Methods = Methods { + query_interface, + add_ref, + release, + create_from_url, + create_from_stream, + begin_from_url, + end_from_url, + begin_from_stream, + end_from_stream, + cancel, +}; + +fn host(this: *mut Resolver) -> *mut Host { + // SAFETY: title code calls methods on a proxy we made, alive until its + // last release. + unsafe { (*this).host } +} + +/// Only the resolver's own interfaces: anything else could hand out the +/// host object unguarded. +extern "system" fn query_interface( + this: *mut Resolver, + iid: *const [u8; 16], + out: *mut *mut c_void, +) -> HRESULT { + if iid.is_null() || out.is_null() { + return E_POINTER; + } + // SAFETY: checked non-null. + let iid = unsafe { *iid }; + let found = iid == IID_IUNKNOWN || iid == IID_RESOLVER; + // SAFETY: checked non-null. + unsafe { + out.write(if found { + this.cast() + } else { + std::ptr::null_mut() + }) + }; + if !found { + return E_NOINTERFACE; + } + add_ref(this); + S_OK +} + +extern "system" fn add_ref(this: *mut Resolver) -> u32 { + // SAFETY: as in `host`. + unsafe { (*this).refs.fetch_add(1, Ordering::Relaxed) + 1 } +} + +extern "system" fn release(this: *mut Resolver) -> u32 { + // SAFETY: as in `host`. + let left = unsafe { (*this).refs.fetch_sub(1, Ordering::AcqRel) } - 1; + if left == 0 { + // SAFETY: made by `MFCreateSourceResolver`; this was the last + // reference, to the proxy and to the host object it holds. + let proxy = unsafe { Box::from_raw(this) }; + // SAFETY: slot 2 is `Release`. + let release: extern "system" fn(*mut Host) -> u32 = unsafe { Host::method(proxy.host, 2) }; + release(proxy.host); + } + left +} + +extern "system" fn create_from_url( + this: *mut Resolver, + url: *const u16, + flags: u32, + props: Unknown, + kind: *mut u32, + object: *mut Unknown, +) -> HRESULT { + let url = match checked(url) { + Ok(url) => url, + Err(error) => { + if !object.is_null() { + // SAFETY: the title's out parameter. + unsafe { object.write(std::ptr::null_mut()) }; + } + return error; + } + }; + let host = host(this); + // SAFETY: slot 3 is `CreateObjectFromURL`. + let f: extern "system" fn( + *mut Host, + *const u16, + u32, + Unknown, + *mut u32, + *mut Unknown, + ) -> HRESULT = unsafe { Host::method(host, 3) }; + f(host, url.as_ptr(), flags, props, kind, object) +} + +extern "system" fn begin_from_url( + this: *mut Resolver, + url: *const u16, + flags: u32, + props: Unknown, + cookie: *mut Unknown, + callback: Unknown, + state: Unknown, +) -> HRESULT { + let url = match checked(url) { + Ok(url) => url, + Err(error) => return error, + }; + let host = host(this); + // SAFETY: slot 5 is `BeginCreateObjectFromURL`. + let f: extern "system" fn( + *mut Host, + *const u16, + u32, + Unknown, + *mut Unknown, + Unknown, + Unknown, + ) -> HRESULT = unsafe { Host::method(host, 5) }; + f(host, url.as_ptr(), flags, props, cookie, callback, state) +} + +extern "system" fn create_from_stream( + this: *mut Resolver, + stream: Unknown, + url: *const u16, + flags: u32, + props: Unknown, + kind: *mut u32, + object: *mut Unknown, +) -> HRESULT { + let host = host(this); + // SAFETY: slot 4 is `CreateObjectFromByteStream`; the URL is only a + // hint for picking a handler. + let f: extern "system" fn( + *mut Host, + Unknown, + *const u16, + u32, + Unknown, + *mut u32, + *mut Unknown, + ) -> HRESULT = unsafe { Host::method(host, 4) }; + f(host, stream, url, flags, props, kind, object) +} + +extern "system" fn end_from_url( + this: *mut Resolver, + result: Unknown, + kind: *mut u32, + object: *mut Unknown, +) -> HRESULT { + let host = host(this); + // SAFETY: slot 6 is `EndCreateObjectFromURL`. + let f: extern "system" fn(*mut Host, Unknown, *mut u32, *mut Unknown) -> HRESULT = + unsafe { Host::method(host, 6) }; + f(host, result, kind, object) +} + +#[allow(clippy::too_many_arguments)] +extern "system" fn begin_from_stream( + this: *mut Resolver, + stream: Unknown, + url: *const u16, + flags: u32, + props: Unknown, + cookie: *mut Unknown, + callback: Unknown, + state: Unknown, +) -> HRESULT { + let host = host(this); + // SAFETY: slot 7 is `BeginCreateObjectFromByteStream`. + let f: extern "system" fn( + *mut Host, + Unknown, + *const u16, + u32, + Unknown, + *mut Unknown, + Unknown, + Unknown, + ) -> HRESULT = unsafe { Host::method(host, 7) }; + f(host, stream, url, flags, props, cookie, callback, state) +} + +extern "system" fn end_from_stream( + this: *mut Resolver, + result: Unknown, + kind: *mut u32, + object: *mut Unknown, +) -> HRESULT { + let host = host(this); + // SAFETY: slot 8 is `EndCreateObjectFromByteStream`. + let f: extern "system" fn(*mut Host, Unknown, *mut u32, *mut Unknown) -> HRESULT = + unsafe { Host::method(host, 8) }; + f(host, result, kind, object) +} + +extern "system" fn cancel(this: *mut Resolver, cookie: Unknown) -> HRESULT { + let host = host(this); + // SAFETY: slot 9 is `CancelObjectCreation`. + let f: extern "system" fn(*mut Host, Unknown) -> HRESULT = unsafe { Host::method(host, 9) }; + f(host, cookie) +} + +/// The host's resolver behind our proxy. +pub extern "system" fn MFCreateSourceResolver(out: *mut *mut Resolver) -> HRESULT { + if out.is_null() { + return E_POINTER; + } + static CREATE: OnceLock> = OnceLock::new(); + let Some(create) = + *CREATE.get_or_init(|| crate::host::function("mfplat.dll", "MFCreateSourceResolver")) + else { + return UNSUPPORTED_SCHEME; + }; + // SAFETY: the host's `MFCreateSourceResolver(IMFSourceResolver**)`. + let create: extern "system" fn(*mut *mut Host) -> HRESULT = + unsafe { std::mem::transmute(create) }; + let mut host = std::ptr::null_mut(); + let hr = create(&mut host); + if hr < 0 || host.is_null() { + return hr; + } + let proxy = Box::new(Resolver { + vtable: &METHODS, + host, + refs: AtomicU32::new(1), + }); + // SAFETY: checked non-null. + unsafe { out.write(Box::into_raw(proxy)) }; + S_OK +} + +pub(crate) fn module() -> HleModule { + HleModule { + name: "media", + dlls: &["mfplat.dll"], + exports: vec![hle_export!(MFCreateSourceResolver)], + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn wide(s: &str) -> Vec { + s.encode_utf16().collect() + } + + fn text(v: &[u16]) -> String { + String::from_utf16_lossy(v.strip_suffix(&[0]).unwrap_or(v)) + } + + #[test] + fn only_local_files_reach_the_host() { + // Network schemes and shares are refused, naming scheme and host. + let refused = |url: &str| local(&wide(url)).unwrap_err(); + assert_eq!( + refused("https://cdn.example.com/a.mp4"), + ("https".into(), "cdn.example.com".into()) + ); + assert_eq!(refused("RTSP://10.0.0.1:554/x").0, "rtsp"); + assert_eq!(refused("mms://h/x").0, "mms"); + assert_eq!( + refused(r"\\server\share\a.mp4"), + ("unc".into(), "server".into()) + ); + assert_eq!( + refused("file://server/share/a.mp4"), + ("file".into(), "server".into()) + ); + + // A path on a virtual drive goes to its host folder, also as a + // `file:` URL; other local files pass as they are. + // Checked by opening the files: `files` may spell the host root + // differently (absolute, `\\?\` for long paths) from the temp dir. + let dir = tempfile::tempdir().unwrap(); + std::fs::create_dir(dir.path().join("movies")).unwrap(); + std::fs::write(dir.path().join("movies").join("intro.mp4"), b"1").unwrap(); + std::fs::write(dir.path().join("movies").join("intro a.mp4"), b"2").unwrap(); + let letter = files::mount(dir.path()).expect("a free drive letter"); + let host = text(&local(&wide(&format!(r"{letter}:\movies\intro.mp4"))).unwrap()); + assert_eq!( + std::fs::read(&host).ok().as_deref(), + Some(&b"1"[..]), + "{host}" + ); + let from_url = + text(&local(&wide(&format!("file:///{letter}:/movies/intro%20a.mp4"))).unwrap()); + assert_eq!( + std::fs::read(&from_url).ok().as_deref(), + Some(&b"2"[..]), + "{from_url}" + ); + assert_eq!( + text(&local(&wide("file:///C:/Windows/a.wav")).unwrap()), + r"C:\Windows\a.wav" + ); + assert_eq!(text(&local(&wide("clip.mp4")).unwrap()), "clip.mp4"); + } + + #[test] + fn interface_ids_are_the_resolvers() { + assert_eq!(&IID_IUNKNOWN[8..], &[0xC0, 0, 0, 0, 0, 0, 0, 0x46]); + assert_eq!(&IID_RESOLVER[..4], &[0x2D, 0xA3, 0xE5, 0xFB]); + } +} diff --git a/crates/leonida-hle/src/modules/mod.rs b/crates/leonida-hle/src/modules/mod.rs new file mode 100644 index 000000000..b90126c90 --- /dev/null +++ b/crates/leonida-hle/src/modules/mod.rs @@ -0,0 +1,74 @@ +//! Implementations, one module per area of the console API. +//! +//! Adding an API: write an `extern "system"` function named exactly like +//! the import, then list it with `hle_export!` in the module's `module()`. +//! Run `leonida census` over your titles to see what is still missing. +//! +//! Planned areas (driven by census results, not by completeness): +//! `file` (package paths), `thread` (TLS callbacks for title threads), +//! `xaudio2`, `xstore` stubs. + +#[cfg(windows)] +pub mod apu; +pub mod audio; +pub mod d3d12x; +pub mod display; +pub mod dsp; +#[cfg(windows)] +pub mod dstorage; +#[cfg(windows)] +pub mod files; +pub mod gameinput; +pub mod kernel; +#[cfg(windows)] +pub mod lifecycle; +#[cfg(windows)] +pub mod media; +#[cfg(windows)] +pub mod net; +pub mod speech; +pub mod storage; +pub mod xasync; +pub mod xg; +pub mod xgame; +pub mod xgameruntime; +pub mod xgamesave; +pub mod xgameui; +#[cfg(windows)] +pub mod xmem; +pub mod xnetworking; +pub mod xpackage; +pub mod xstore; +pub mod xsystem; +pub mod xuser; + +use crate::HleModule; + +pub(crate) fn all() -> Vec { + let mut all = vec![ + kernel::module(), + xgameruntime::module(), + gameinput::module(), + d3d12x::module(), + audio::module(), + dsp::module(), + xg::module(), + ]; + #[cfg(windows)] + all.push(apu::module()); + #[cfg(windows)] + all.push(media::module()); + #[cfg(windows)] + all.push(dstorage::module()); + #[cfg(windows)] + all.push(files::module()); + #[cfg(windows)] + all.push(lifecycle::module()); + #[cfg(windows)] + all.push(net::module()); + #[cfg(windows)] + all.push(xmem::module()); + #[cfg(windows)] + all.push(xsystem::module()); + all +} diff --git a/crates/leonida-hle/src/modules/net.rs b/crates/leonida-hle/src/modules/net.rs new file mode 100644 index 000000000..1d75e43cd --- /dev/null +++ b/crates/leonida-hle/src/modules/net.rs @@ -0,0 +1,1069 @@ +//! A console without a network cable: the title reaches loopback only. +//! +//! Every way out of Winsock and WinHTTP a title can import or look up by +//! name is vetted here; the rest of both DLLs is the host's own. +//! +//! * Connects (also by name, by list, `ConnectEx` from `WSAIoctl`) and +//! datagram sends to anything but 127.0.0.0/8 and ::1 fail with +//! `WSAENETUNREACH`. +//! * Forward lookups other than `localhost` and IP literals fail with +//! `WSAHOST_NOT_FOUND`; reverse lookups of other addresses come back +//! numeric, or fail if a name is required, as with no network. +//! * `WinHttpConnect` to a host that is not loopback fails with +//! `ERROR_WINHTTP_CANNOT_CONNECT`, so no request (or WebSocket) handle can +//! exist for one. Proxies are off and proxy auto-detection (WPAD, PAC +//! downloads) fails with `ERROR_WINHTTP_AUTODETECTION_FAILED`. +//! * A bind to all interfaces is narrowed to loopback, so nothing on the +//! network can connect in. +#![allow(non_snake_case)] +#![allow(clippy::not_unsafe_ptr_arg_deref)] +#![allow(clippy::too_many_arguments)] + +use std::ffi::{CStr, c_char, c_void}; +use std::net::{IpAddr, SocketAddr}; +use std::sync::Mutex; + +use windows_sys::Win32::Foundation::SetLastError; + +use crate::modules::files::host; +use crate::{HleExport, HleModule, hle_export}; + +const SOCKET_ERROR: i32 = -1; +const INVALID_SOCKET: Socket = !0; +const WSAEINVAL: i32 = 10022; +const WSAEADDRNOTAVAIL: i32 = 10049; +const WSAENETUNREACH: i32 = 10051; +const WSASERVICE_NOT_FOUND: i32 = 10108; +const WSAHOST_NOT_FOUND: i32 = 11001; +const ERROR_WINHTTP_CANNOT_CONNECT: u32 = 12029; +const ERROR_WINHTTP_AUTODETECTION_FAILED: u32 = 12180; +const AF_INET: u16 = 2; +const AF_INET6: u16 = 23; +const NI_NUMERICHOST: i32 = 0x02; +const NI_NAMEREQD: i32 = 0x04; +const SIO_GET_EXTENSION_FUNCTION_POINTER: u32 = 0xC800_0006; +const SIO_GET_MULTIPLE_EXTENSION_FUNCTION_POINTER: u32 = 0xC800_0024; +const WINHTTP_ACCESS_TYPE_NO_PROXY: u32 = 1; +const WINHTTP_OPTION_PROXY: u32 = 38; + +#[repr(C)] +#[derive(Clone, Copy, PartialEq, Eq)] +struct Guid(u32, u16, u16, [u8; 8]); + +const WSAID_CONNECTEX: Guid = Guid( + 0x25a2_07b9, + 0xddf3, + 0x4660, + [0x8e, 0xe9, 0x76, 0xe5, 0x8c, 0x74, 0x06, 0x3e], +); +const WSAID_WSASENDMSG: Guid = Guid( + 0xa441_e712, + 0x754f, + 0x43ca, + [0x84, 0xa7, 0x0d, 0xee, 0x44, 0xcf, 0x60, 0x6d], +); + +type Socket = usize; +type Handle = *mut c_void; + +/// Logs `what` for `destination` the first time (no payload, ever). +fn once(what: &'static str, destination: String) { + static SEEN: Mutex> = Mutex::new(Vec::new()); + let mut seen = SEEN.lock().unwrap_or_else(|e| e.into_inner()); + if !seen.iter().any(|(w, d)| *w == what && *d == destination) { + tracing::info!(%destination, "{what}"); + seen.push((what, destination)); + } +} + +fn wsa_error(code: i32) { + host!("ws2_32.dll", "WSASetLastError": extern "system" fn(i32))(code); +} + +fn narrow(text: *const c_char) -> Option { + (!text.is_null()).then(|| { + // SAFETY: the title passes a NUL-terminated string. + unsafe { CStr::from_ptr(text) } + .to_string_lossy() + .into_owned() + }) +} + +fn wide(text: *const u16) -> Option { + // SAFETY: the title passes a NUL-terminated string or null. + (!text.is_null()).then(|| unsafe { + let len = (0..).take_while(|&i| *text.add(i) != 0).count(); + String::from_utf16_lossy(std::slice::from_raw_parts(text, len)) + }) +} + +/// An IPv4 or IPv6 `sockaddr` of `len` bytes. +fn socket_addr(addr: *const u8, len: i32) -> Option { + let len = usize::try_from(len).ok()?; + if addr.is_null() || len < 4 { + return None; + } + // SAFETY: the title passes `len` readable bytes. + let b = unsafe { std::slice::from_raw_parts(addr, len) }; + let port = u16::from_be_bytes([b[2], b[3]]); + match u16::from_le_bytes([b[0], b[1]]) { + AF_INET if len >= 16 => Some((<[u8; 4]>::try_from(&b[4..8]).ok()?, port).into()), + AF_INET6 if len >= 28 => Some((<[u8; 16]>::try_from(&b[8..24]).ok()?, port).into()), + _ => None, + } +} + +/// A raw address of family `kind` (`gethostbyaddr` style). +fn raw_ip(addr: *const c_char, len: i32, kind: i32) -> Option { + let len = usize::try_from(len).ok()?; + if addr.is_null() { + return None; + } + // SAFETY: the title passes `len` readable bytes. + let b = unsafe { std::slice::from_raw_parts(addr.cast::(), len) }; + match (u16::try_from(kind).ok()?, len) { + (AF_INET, 4..) => Some(<[u8; 4]>::try_from(&b[..4]).ok()?.into()), + (AF_INET6, 16..) => Some(<[u8; 16]>::try_from(&b[..16]).ok()?.into()), + _ => None, + } +} + +fn loopback(ip: IpAddr) -> bool { + ip.to_canonical().is_loopback() +} + +/// `localhost` or a loopback literal (bracketed IPv6 too). +fn loopback_name(name: &str) -> bool { + let bare = name.trim_start_matches('[').trim_end_matches(']'); + bare.eq_ignore_ascii_case("localhost") || bare.parse().is_ok_and(loopback) +} + +fn shown(addr: Option) -> String { + addr.map_or_else(|| "not an IP address".into(), |a| a.to_string()) +} + +/// True for a loopback `sockaddr`; otherwise logs it and sets +/// `WSAENETUNREACH`. Other address families count as off the machine. +fn reachable(what: &'static str, addr: *const u8, len: i32) -> bool { + match socket_addr(addr, len) { + Some(a) if loopback(a.ip()) => true, + a => { + once(what, shown(a)); + wsa_error(WSAENETUNREACH); + false + } + } +} + +/// Connecting by name: only to loopback. A name would need a lookup +/// (`WSAHOST_NOT_FOUND`), an address a route (`WSAENETUNREACH`). +fn reachable_name(name: Option) -> bool { + match name { + Some(name) if !loopback_name(&name) => { + let literal = name.parse::().is_ok(); + once("network connect blocked", name); + wsa_error(if literal { + WSAENETUNREACH + } else { + WSAHOST_NOT_FOUND + }); + false + } + // No name: the host rejects the call itself. + _ => true, + } +} + +/// Names answered without asking the network: none, `localhost`, IP +/// literals (connecting to one is vetted separately). +fn resolvable(name: Option) -> bool { + match name { + Some(name) + if !(name.is_empty() + || name.eq_ignore_ascii_case("localhost") + || name.parse::().is_ok()) => + { + once("network name lookup blocked", name); + wsa_error(WSAHOST_NOT_FOUND); + false + } + _ => true, + } +} + +/// Reverse lookups ask DNS unless the address is loopback. +fn reverse_resolvable(ip: Option) -> bool { + match ip { + Some(ip) if loopback(ip) => true, + ip => { + once("network reverse lookup blocked", shown(ip)); + false + } + } +} + +/// `getnameinfo` flags that keep a host name lookup on the machine: the +/// numeric form, as without a network, or `None` if a name is required. +fn name_info_flags(sa: *const u8, len: i32, host_wanted: bool, flags: i32) -> Option { + if !host_wanted + || flags & NI_NUMERICHOST != 0 + || reverse_resolvable(socket_addr(sa, len).map(|a| a.ip())) + { + Some(flags) + } else if flags & NI_NAMEREQD != 0 { + wsa_error(WSAHOST_NOT_FOUND); + None + } else { + Some(flags | NI_NUMERICHOST) + } +} + +// Connects. + +pub extern "system" fn connect(s: Socket, name: *const u8, len: i32) -> i32 { + if !reachable("network connect blocked", name, len) { + return SOCKET_ERROR; + } + host!("ws2_32.dll", "connect": extern "system" fn(Socket, *const u8, i32) -> i32)(s, name, len) +} + +pub extern "system" fn WSAConnect( + s: Socket, + name: *const u8, + len: i32, + caller_data: *const c_void, + callee_data: *mut c_void, + sqos: *const c_void, + gqos: *const c_void, +) -> i32 { + if !reachable("network connect blocked", name, len) { + return SOCKET_ERROR; + } + host!("ws2_32.dll", "WSAConnect": extern "system" fn(Socket, *const u8, i32, *const c_void, *mut c_void, *const c_void, *const c_void) -> i32)( + s, + name, + len, + caller_data, + callee_data, + sqos, + gqos, + ) +} + +pub extern "system" fn WSAConnectByNameA( + s: Socket, + node: *const c_char, + service: *const c_char, + local_len: *mut u32, + local: *mut c_void, + remote_len: *mut u32, + remote: *mut c_void, + timeout: *const c_void, + reserved: *mut c_void, +) -> i32 { + if !reachable_name(narrow(node)) { + return 0; + } + host!("ws2_32.dll", "WSAConnectByNameA": extern "system" fn(Socket, *const c_char, *const c_char, *mut u32, *mut c_void, *mut u32, *mut c_void, *const c_void, *mut c_void) -> i32)( + s, node, service, local_len, local, remote_len, remote, timeout, reserved, + ) +} + +pub extern "system" fn WSAConnectByNameW( + s: Socket, + node: *const u16, + service: *const u16, + local_len: *mut u32, + local: *mut c_void, + remote_len: *mut u32, + remote: *mut c_void, + timeout: *const c_void, + reserved: *mut c_void, +) -> i32 { + if !reachable_name(wide(node)) { + return 0; + } + host!("ws2_32.dll", "WSAConnectByNameW": extern "system" fn(Socket, *const u16, *const u16, *mut u32, *mut c_void, *mut u32, *mut c_void, *const c_void, *mut c_void) -> i32)( + s, node, service, local_len, local, remote_len, remote, timeout, reserved, + ) +} + +/// `SOCKET_ADDRESS`; a `SOCKET_ADDRESS_LIST` is an `i32` count, then these +/// (pointer aligned). +#[repr(C)] +struct SocketAddress { + addr: *const u8, + len: i32, +} + +/// Every candidate must be loopback. +pub extern "system" fn WSAConnectByList( + s: Socket, + list: *const u8, + local_len: *mut u32, + local: *mut c_void, + remote_len: *mut u32, + remote: *mut c_void, + timeout: *const c_void, + reserved: *mut c_void, +) -> i32 { + if !list.is_null() { + // SAFETY: the title passes a `SOCKET_ADDRESS_LIST`. + let entries = unsafe { + let count = usize::try_from(list.cast::().read()).unwrap_or(0); + std::slice::from_raw_parts(list.add(8).cast::(), count) + }; + if !entries + .iter() + .all(|e| reachable("network connect blocked", e.addr, e.len)) + { + return 0; + } + } + host!("ws2_32.dll", "WSAConnectByList": extern "system" fn(Socket, *const u8, *mut u32, *mut c_void, *mut u32, *mut c_void, *const c_void, *mut c_void) -> i32)( + s, list, local_len, local, remote_len, remote, timeout, reserved, + ) +} + +pub extern "system" fn WSAJoinLeaf( + s: Socket, + name: *const u8, + len: i32, + caller_data: *const c_void, + callee_data: *mut c_void, + sqos: *const c_void, + gqos: *const c_void, + flags: u32, +) -> Socket { + if !reachable("network connect blocked", name, len) { + return INVALID_SOCKET; + } + host!("ws2_32.dll", "WSAJoinLeaf": extern "system" fn(Socket, *const u8, i32, *const c_void, *mut c_void, *const c_void, *const c_void, u32) -> Socket)( + s, + name, + len, + caller_data, + callee_data, + sqos, + gqos, + flags, + ) +} + +/// `ConnectEx` as `WSAIoctl` hands it out: vetted, then the socket's own. +extern "system" fn connect_ex( + s: Socket, + name: *const u8, + len: i32, + send: *const c_void, + send_len: u32, + sent: *mut u32, + overlapped: *mut c_void, +) -> i32 { + if !reachable("network connect blocked", name, len) { + return 0; + } + let (mut real, mut size) = (0usize, 0u32); + let ioctl = host!("ws2_32.dll", "WSAIoctl": extern "system" fn(Socket, u32, *const c_void, u32, *mut c_void, u32, *mut u32, *mut c_void, *const c_void) -> i32); + let guid = WSAID_CONNECTEX; + let found = ioctl( + s, + SIO_GET_EXTENSION_FUNCTION_POINTER, + (&raw const guid).cast(), + 16, + (&raw mut real).cast(), + 8, + &mut size, + std::ptr::null_mut(), + std::ptr::null(), + ); + if found != 0 || real == 0 { + return 0; + } + // SAFETY: the provider's `ConnectEx` for this socket. + let real = unsafe { + std::mem::transmute::< + usize, + extern "system" fn( + Socket, + *const u8, + i32, + *const c_void, + u32, + *mut u32, + *mut c_void, + ) -> i32, + >(real) + }; + real(s, name, len, send, send_len, sent, overlapped) +} + +/// The `ConnectEx` and `WSASendMsg` pointers it hands out are ours; the +/// multi-pointer query (Registered I/O, whose `RIOSendEx` takes any +/// address) is refused as by an old system. Other controls pass through. +pub extern "system" fn WSAIoctl( + s: Socket, + code: u32, + input: *const c_void, + input_len: u32, + output: *mut c_void, + output_len: u32, + returned: *mut u32, + overlapped: *mut c_void, + completion: *const c_void, +) -> i32 { + if code == SIO_GET_MULTIPLE_EXTENSION_FUNCTION_POINTER { + wsa_error(WSAEINVAL); + return SOCKET_ERROR; + } + let result = host!("ws2_32.dll", "WSAIoctl": extern "system" fn(Socket, u32, *const c_void, u32, *mut c_void, u32, *mut u32, *mut c_void, *const c_void) -> i32)( + s, code, input, input_len, output, output_len, returned, overlapped, completion, + ); + if result == 0 && code == SIO_GET_EXTENSION_FUNCTION_POINTER && input_len >= 16 { + // SAFETY: the host just read a GUID from `input` and wrote a pointer to `output`. + unsafe { + let ours = match input.cast::().read_unaligned() { + WSAID_CONNECTEX => connect_ex as *const () as usize, + WSAID_WSASENDMSG => WSASendMsg as *const () as usize, + _ => return result, + }; + output.cast::().write_unaligned(ours); + } + } + result +} + +// Datagram sends. + +/// Without an address it sends to the connected peer, which `connect` vetted; +/// so does a stream socket whatever `to` says (Winsock ignores it there). +pub extern "system" fn sendto( + s: Socket, + buf: *const u8, + len: i32, + flags: i32, + to: *const u8, + to_len: i32, +) -> i32 { + if !to.is_null() && !stream(s) && !reachable("network datagram blocked", to, to_len) { + return SOCKET_ERROR; + } + host!("ws2_32.dll", "sendto": extern "system" fn(Socket, *const u8, i32, i32, *const u8, i32) -> i32)( + s, buf, len, flags, to, to_len, + ) +} + +pub extern "system" fn WSASendTo( + s: Socket, + buffers: *const c_void, + count: u32, + sent: *mut u32, + flags: u32, + to: *const u8, + to_len: i32, + overlapped: *mut c_void, + completion: *const c_void, +) -> i32 { + if !to.is_null() && !stream(s) && !reachable("network datagram blocked", to, to_len) { + return SOCKET_ERROR; + } + host!("ws2_32.dll", "WSASendTo": extern "system" fn(Socket, *const c_void, u32, *mut u32, u32, *const u8, i32, *mut c_void, *const c_void) -> i32)( + s, buffers, count, sent, flags, to, to_len, overlapped, completion, + ) +} + +/// A connection-oriented socket, whose sends go to the peer `connect` vetted. +fn stream(s: Socket) -> bool { + const SOL_SOCKET: i32 = 0xffff; + const SO_TYPE: i32 = 0x1008; + const SOCK_STREAM: i32 = 1; + let (mut kind, mut len) = (0i32, 4i32); + let getsockopt = host!("ws2_32.dll", "getsockopt": extern "system" fn(Socket, i32, i32, *mut i32, *mut i32) -> i32); + getsockopt(s, SOL_SOCKET, SO_TYPE, &mut kind, &mut len) == 0 && kind == SOCK_STREAM +} + +/// The start of a `WSAMSG`: the destination. +#[repr(C)] +struct MessageName { + name: *const u8, + len: i32, +} + +pub extern "system" fn WSASendMsg( + s: Socket, + message: *const c_void, + flags: u32, + sent: *mut u32, + overlapped: *mut c_void, + completion: *const c_void, +) -> i32 { + // SAFETY: the title passes a `WSAMSG` or null. + if let Some(m) = unsafe { message.cast::().as_ref() } + && !m.name.is_null() + && !reachable("network datagram blocked", m.name, m.len) + { + return SOCKET_ERROR; + } + host!("ws2_32.dll", "WSASendMsg": extern "system" fn(Socket, *const c_void, u32, *mut u32, *mut c_void, *const c_void) -> i32)( + s, message, flags, sent, overlapped, completion, + ) +} + +/// All interfaces become loopback, the only one an unplugged console has; +/// any other address is not ours (`WSAEADDRNOTAVAIL`). +// shortcut: `[::]` becomes `[::1]`, so a dual-stack listener no longer hears +// 127.0.0.1; bind both families if a title relies on that. +pub extern "system" fn bind(s: Socket, name: *const u8, len: i32) -> i32 { + let host_bind = host!("ws2_32.dll", "bind": extern "system" fn(Socket, *const u8, i32) -> i32); + match socket_addr(name, len) { + Some(a) if loopback(a.ip()) => host_bind(s, name, len), + Some(a) if a.ip().is_unspecified() => { + once("network bind narrowed to loopback", a.to_string()); + // SAFETY: `socket_addr` checked `len` readable bytes. + let mut local = unsafe { std::slice::from_raw_parts(name, len as usize) }.to_vec(); + match a { + SocketAddr::V4(_) => local[4..8].copy_from_slice(&[127, 0, 0, 1]), + SocketAddr::V6(_) => local[23] = 1, + } + host_bind(s, local.as_ptr(), len) + } + a => { + once("network bind blocked", shown(a)); + wsa_error(WSAEADDRNOTAVAIL); + SOCKET_ERROR + } + } +} + +// Forward lookups. + +pub extern "system" fn getaddrinfo( + node: *const c_char, + service: *const c_char, + hints: *const c_void, + result: *mut *mut c_void, +) -> i32 { + if !resolvable(narrow(node)) { + return WSAHOST_NOT_FOUND; + } + host!("ws2_32.dll", "getaddrinfo": extern "system" fn(*const c_char, *const c_char, *const c_void, *mut *mut c_void) -> i32)( + node, service, hints, result, + ) +} + +pub extern "system" fn GetAddrInfoW( + node: *const u16, + service: *const u16, + hints: *const c_void, + result: *mut *mut c_void, +) -> i32 { + if !resolvable(wide(node)) { + return WSAHOST_NOT_FOUND; + } + host!("ws2_32.dll", "GetAddrInfoW": extern "system" fn(*const u16, *const u16, *const c_void, *mut *mut c_void) -> i32)( + node, service, hints, result, + ) +} + +pub extern "system" fn GetAddrInfoExA( + name: *const c_char, + service: *const c_char, + namespace: u32, + provider: *const c_void, + hints: *const c_void, + result: *mut *mut c_void, + timeout: *const c_void, + overlapped: *mut c_void, + completion: *const c_void, + handle: *mut Handle, +) -> i32 { + if !resolvable(narrow(name)) { + return WSAHOST_NOT_FOUND; + } + host!("ws2_32.dll", "GetAddrInfoExA": extern "system" fn(*const c_char, *const c_char, u32, *const c_void, *const c_void, *mut *mut c_void, *const c_void, *mut c_void, *const c_void, *mut Handle) -> i32)( + name, service, namespace, provider, hints, result, timeout, overlapped, completion, handle, + ) +} + +pub extern "system" fn GetAddrInfoExW( + name: *const u16, + service: *const u16, + namespace: u32, + provider: *const c_void, + hints: *const c_void, + result: *mut *mut c_void, + timeout: *const c_void, + overlapped: *mut c_void, + completion: *const c_void, + handle: *mut Handle, +) -> i32 { + if !resolvable(wide(name)) { + return WSAHOST_NOT_FOUND; + } + host!("ws2_32.dll", "GetAddrInfoExW": extern "system" fn(*const u16, *const u16, u32, *const c_void, *const c_void, *mut *mut c_void, *const c_void, *mut c_void, *const c_void, *mut Handle) -> i32)( + name, service, namespace, provider, hints, result, timeout, overlapped, completion, handle, + ) +} + +pub extern "system" fn gethostbyname(name: *const c_char) -> *mut c_void { + if !resolvable(narrow(name)) { + return std::ptr::null_mut(); + } + host!("ws2_32.dll", "gethostbyname": extern "system" fn(*const c_char) -> *mut c_void)(name) +} + +pub extern "system" fn WSAAsyncGetHostByName( + window: Handle, + message: u32, + name: *const c_char, + buf: *mut c_char, + buf_len: i32, +) -> Handle { + if !resolvable(narrow(name)) { + return std::ptr::null_mut(); + } + host!("ws2_32.dll", "WSAAsyncGetHostByName": extern "system" fn(Handle, u32, *const c_char, *mut c_char, i32) -> Handle)( + window, message, name, buf, buf_len, + ) +} + +/// Name-space queries (DNS, also network lists and Bluetooth) are refused +/// as a console without a network answers them. +// shortcut: local name spaces are refused too; pass those through if a title +// needs one. +pub extern "system" fn WSALookupServiceBeginA( + _restrictions: *const c_void, + _flags: u32, + _lookup: *mut Handle, +) -> i32 { + once("network name-space query blocked", "any".into()); + wsa_error(WSASERVICE_NOT_FOUND); + SOCKET_ERROR +} + +/// See [`WSALookupServiceBeginA`]. +pub extern "system" fn WSALookupServiceBeginW( + restrictions: *const c_void, + flags: u32, + lookup: *mut Handle, +) -> i32 { + WSALookupServiceBeginA(restrictions, flags, lookup) +} + +// Reverse lookups. + +pub extern "system" fn gethostbyaddr(addr: *const c_char, len: i32, kind: i32) -> *mut c_void { + if !reverse_resolvable(raw_ip(addr, len, kind)) { + wsa_error(WSAHOST_NOT_FOUND); + return std::ptr::null_mut(); + } + host!("ws2_32.dll", "gethostbyaddr": extern "system" fn(*const c_char, i32, i32) -> *mut c_void)( + addr, len, kind, + ) +} + +pub extern "system" fn WSAAsyncGetHostByAddr( + window: Handle, + message: u32, + addr: *const c_char, + len: i32, + kind: i32, + buf: *mut c_char, + buf_len: i32, +) -> Handle { + if !reverse_resolvable(raw_ip(addr, len, kind)) { + wsa_error(WSAHOST_NOT_FOUND); + return std::ptr::null_mut(); + } + host!("ws2_32.dll", "WSAAsyncGetHostByAddr": extern "system" fn(Handle, u32, *const c_char, i32, i32, *mut c_char, i32) -> Handle)( + window, message, addr, len, kind, buf, buf_len, + ) +} + +pub extern "system" fn getnameinfo( + sa: *const u8, + sa_len: i32, + host: *mut c_char, + host_len: u32, + serv: *mut c_char, + serv_len: u32, + flags: i32, +) -> i32 { + let Some(flags) = name_info_flags(sa, sa_len, !host.is_null(), flags) else { + return WSAHOST_NOT_FOUND; + }; + host!("ws2_32.dll", "getnameinfo": extern "system" fn(*const u8, i32, *mut c_char, u32, *mut c_char, u32, i32) -> i32)( + sa, sa_len, host, host_len, serv, serv_len, flags, + ) +} + +pub extern "system" fn GetNameInfoW( + sa: *const u8, + sa_len: i32, + host: *mut u16, + host_len: u32, + serv: *mut u16, + serv_len: u32, + flags: i32, +) -> i32 { + let Some(flags) = name_info_flags(sa, sa_len, !host.is_null(), flags) else { + return WSAHOST_NOT_FOUND; + }; + host!("ws2_32.dll", "GetNameInfoW": extern "system" fn(*const u8, i32, *mut u16, u32, *mut u16, u32, i32) -> i32)( + sa, sa_len, host, host_len, serv, serv_len, flags, + ) +} + +// WinHTTP. + +/// The one door to a server: requests, uploads and WebSockets all hang off +/// the handle this returns. +pub extern "system" fn WinHttpConnect( + session: Handle, + server: *const u16, + port: u16, + reserved: u32, +) -> Handle { + if let Some(name) = wide(server) + && !loopback_name(&name) + { + once("HTTP connection blocked", format!("{name}:{port}")); + // SAFETY: no pointers. + unsafe { SetLastError(ERROR_WINHTTP_CANNOT_CONNECT) }; + return std::ptr::null_mut(); + } + host!("winhttp.dll", "WinHttpConnect": extern "system" fn(Handle, *const u16, u16, u32) -> Handle)( + session, server, port, reserved, + ) +} + +/// Sessions never use a proxy: only loopback is reachable, and a proxy +/// (named, or found by auto-detection) would carry it off the machine. +pub extern "system" fn WinHttpOpen( + agent: *const u16, + access: u32, + _proxy: *const u16, + _bypass: *const u16, + flags: u32, +) -> Handle { + if access != WINHTTP_ACCESS_TYPE_NO_PROXY { + once("HTTP proxy ignored", format!("access type {access}")); + } + host!("winhttp.dll", "WinHttpOpen": extern "system" fn(*const u16, u32, *const u16, *const u16, u32) -> Handle)( + agent, + WINHTTP_ACCESS_TYPE_NO_PROXY, + std::ptr::null(), + std::ptr::null(), + flags, + ) +} + +/// See [`WinHttpOpen`]: a proxy set later is accepted and not used. +pub extern "system" fn WinHttpSetOption( + handle: Handle, + option: u32, + buffer: *const c_void, + len: u32, +) -> i32 { + if option == WINHTTP_OPTION_PROXY { + once("HTTP proxy ignored", "WINHTTP_OPTION_PROXY".into()); + return 1; + } + host!("winhttp.dll", "WinHttpSetOption": extern "system" fn(Handle, u32, *const c_void, u32) -> i32)( + handle, option, buffer, len, + ) +} + +/// Proxy auto-detection asks the network (DHCP, DNS, a PAC download). +fn no_auto_proxy() -> u32 { + once("HTTP proxy auto-detection blocked", "WPAD/PAC".into()); + ERROR_WINHTTP_AUTODETECTION_FAILED +} + +pub extern "system" fn WinHttpDetectAutoProxyConfigUrl(_flags: u32, _url: *mut *mut u16) -> i32 { + // SAFETY: no pointers. + unsafe { SetLastError(no_auto_proxy()) }; + 0 +} + +pub extern "system" fn WinHttpGetProxyForUrl( + _session: Handle, + _url: *const u16, + _options: *const c_void, + _info: *mut c_void, +) -> i32 { + // SAFETY: no pointers. + unsafe { SetLastError(no_auto_proxy()) }; + 0 +} + +pub extern "system" fn WinHttpGetProxyForUrlEx( + _resolver: Handle, + _url: *const u16, + _options: *const c_void, + _context: usize, +) -> u32 { + no_auto_proxy() +} + +pub extern "system" fn WinHttpGetProxyForUrlEx2( + _resolver: Handle, + _url: *const u16, + _options: *const c_void, + _selection_len: u32, + _selection: *const u8, + _context: usize, +) -> u32 { + no_auto_proxy() +} + +pub extern "system" fn WinHttpGetProxySettingsEx( + _resolver: Handle, + _kind: i32, + _params: *const c_void, + _context: usize, +) -> u32 { + no_auto_proxy() +} + +/// Winsock imports by ordinal; the Winsock 1.1 numbers are fixed. +fn ordinal(name: &'static str, f: usize) -> HleExport { + HleExport { name, address: f } +} + +pub(crate) fn module() -> HleModule { + HleModule { + name: "net", + dlls: &["ws2_32.dll", "winhttp.dll"], + exports: vec![ + hle_export!(connect), + hle_export!(WSAConnect), + hle_export!(WSAConnectByNameA), + hle_export!(WSAConnectByNameW), + hle_export!(WSAConnectByList), + hle_export!(WSAJoinLeaf), + hle_export!(WSAIoctl), + hle_export!(sendto), + hle_export!(WSASendTo), + hle_export!(WSASendMsg), + hle_export!(bind), + hle_export!(getaddrinfo), + hle_export!(GetAddrInfoW), + hle_export!(GetAddrInfoExA), + hle_export!(GetAddrInfoExW), + hle_export!(gethostbyname), + hle_export!(WSAAsyncGetHostByName), + hle_export!(WSALookupServiceBeginA), + hle_export!(WSALookupServiceBeginW), + hle_export!(gethostbyaddr), + hle_export!(WSAAsyncGetHostByAddr), + hle_export!(getnameinfo), + hle_export!(GetNameInfoW), + hle_export!(WinHttpConnect), + hle_export!(WinHttpOpen), + hle_export!(WinHttpSetOption), + hle_export!(WinHttpDetectAutoProxyConfigUrl), + hle_export!(WinHttpGetProxyForUrl), + hle_export!(WinHttpGetProxyForUrlEx), + hle_export!(WinHttpGetProxyForUrlEx2), + hle_export!(WinHttpGetProxySettingsEx), + ordinal("#2", bind as *const () as usize), + ordinal("#4", connect as *const () as usize), + ordinal("#20", sendto as *const () as usize), + ordinal("#51", gethostbyaddr as *const () as usize), + ordinal("#52", gethostbyname as *const () as usize), + ordinal("#102", WSAAsyncGetHostByAddr as *const () as usize), + ordinal("#103", WSAAsyncGetHostByName as *const () as usize), + ], + } +} + +#[cfg(test)] +mod tests { + use super::*; + use leonida_pe::ImportSymbol; + + fn v4(ip: [u8; 4], port: u16) -> [u8; 16] { + let mut a = [0u8; 16]; + a[..2].copy_from_slice(&AF_INET.to_le_bytes()); + a[2..4].copy_from_slice(&port.to_be_bytes()); + a[4..8].copy_from_slice(&ip); + a + } + + // TEST-NET-1 (192.0.2.0/24): never routed, and never tried here. + const AWAY: [u8; 4] = [192, 0, 2, 1]; + const HOME: [u8; 4] = [127, 0, 0, 1]; + + #[test] + fn only_loopback_is_reachable() { + // Also starts Winsock for the raw calls below. + let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); + let port = listener.local_addr().unwrap().port(); + let socket = host!("ws2_32.dll", "socket": extern "system" fn(i32, i32, i32) -> Socket); + let close = host!("ws2_32.dll", "closesocket": extern "system" fn(Socket) -> i32); + let last_error = host!("ws2_32.dll", "WSAGetLastError": extern "system" fn() -> i32); + let null = std::ptr::null_mut::(); + + // Connects. + let s = socket(2, 1, 6); + assert_ne!(s, INVALID_SOCKET); + assert_eq!(connect(s, v4(AWAY, 80).as_ptr(), 16), SOCKET_ERROR); + assert_eq!(last_error(), WSAENETUNREACH); + let n = null.cast(); + assert_eq!( + WSAConnectByNameA( + s, + c"example.com".as_ptr(), + c"80".as_ptr(), + n, + null, + n, + null, + null, + null + ), + 0 + ); + assert_eq!(last_error(), WSAHOST_NOT_FOUND); + assert_eq!(connect(s, v4(HOME, port).as_ptr(), 16), 0); + listener.accept().unwrap(); + // A stream socket sends to its vetted peer whatever `to` says. + assert_eq!(sendto(s, b"x".as_ptr(), 1, 0, v4(AWAY, 9).as_ptr(), 16), 1); + close(s); + + // `ConnectEx` from `WSAIoctl` is the vetted one. + let s = socket(2, 1, 6); + let mut f = 0usize; + let mut size = 0u32; + let guid = WSAID_CONNECTEX; + let got = WSAIoctl( + s, + SIO_GET_EXTENSION_FUNCTION_POINTER, + (&raw const guid).cast(), + 16, + (&raw mut f).cast(), + 8, + &mut size, + null, + null, + ); + assert_eq!((got, f), (0, connect_ex as *const () as usize)); + assert_eq!( + connect_ex(s, v4(AWAY, 80).as_ptr(), 16, null, 0, n, null), + 0 + ); + assert_eq!(last_error(), WSAENETUNREACH); + close(s); + + // Datagram sends. + let u = socket(2, 2, 17); + assert_eq!( + sendto(u, b"x".as_ptr(), 1, 0, v4(AWAY, 9).as_ptr(), 16), + SOCKET_ERROR + ); + assert_eq!(last_error(), WSAENETUNREACH); + assert_eq!( + sendto(u, b"x".as_ptr(), 1, 0, v4(HOME, port).as_ptr(), 16), + 1 + ); + close(u); + + // Forward and reverse lookups. + let mut result = null; + assert_eq!( + getaddrinfo( + c"example.com".as_ptr(), + std::ptr::null(), + std::ptr::null(), + &mut result + ), + WSAHOST_NOT_FOUND + ); + let name: Vec = "example.com\0".encode_utf16().collect(); + assert_eq!( + GetAddrInfoW( + name.as_ptr(), + std::ptr::null(), + std::ptr::null(), + &mut result + ), + WSAHOST_NOT_FOUND + ); + let mut text = [0 as c_char; 64]; + let away = v4(AWAY, 80); + assert_eq!( + getnameinfo( + away.as_ptr(), + 16, + text.as_mut_ptr(), + 64, + std::ptr::null_mut(), + 0, + 0 + ), + 0 + ); + // SAFETY: NUL-terminated by `getnameinfo`. + let numeric = unsafe { CStr::from_ptr(text.as_ptr()) }; + assert_eq!(numeric.to_str(), Ok("192.0.2.1")); + assert_eq!( + getnameinfo( + away.as_ptr(), + 16, + text.as_mut_ptr(), + 64, + std::ptr::null_mut(), + 0, + NI_NAMEREQD + ), + WSAHOST_NOT_FOUND + ); + assert!(gethostbyaddr(AWAY.as_ptr().cast(), 4, 2).is_null()); + + // WinHTTP. + assert!(WinHttpConnect(null, name.as_ptr(), 443, 0).is_null()); + // SAFETY: no arguments. + let error = unsafe { windows_sys::Win32::Foundation::GetLastError() }; + assert_eq!(error, ERROR_WINHTTP_CANNOT_CONNECT); + assert_eq!( + WinHttpGetProxyForUrlEx(null, name.as_ptr(), std::ptr::null(), 0), + ERROR_WINHTTP_AUTODETECTION_FAILED + ); + + // The ordinals we override name the functions they stand for. + let m = module(); + for e in m.exports.iter().filter(|e| e.name.starts_with('#')) { + let named = m + .exports + .iter() + .find(|n| n.address == e.address && !n.name.starts_with('#')) + .unwrap(); + let by_ordinal = ImportSymbol::Ordinal(e.name[1..].parse().unwrap()); + assert_eq!( + crate::HostPolicy::default().resolve("ws2_32.dll", &by_ordinal), + crate::host::function("ws2_32.dll", named.name), + "{} is not {}", + e.name, + named.name + ); + } + // Every override names a real export of its DLL. Some exports only + // exist on newer Windows (WinHttpGetProxySettingsEx is absent from + // Windows 10's winhttp.dll); the HLE supplies those itself, so skip + // them only when the host really lacks them. + const NEWER_WINDOWS_ONLY: &[&str] = &["WinHttpGetProxySettingsEx"]; + for e in m.exports.iter().filter(|e| !e.name.starts_with('#')) { + let dll = if e.name.starts_with("WinHttp") { + "winhttp.dll" + } else { + "ws2_32.dll" + }; + let present = crate::host::function(dll, e.name).is_some(); + if !present && NEWER_WINDOWS_ONLY.contains(&e.name) { + continue; + } + assert!(present, "{dll} lacks {}", e.name); + } + } +} diff --git a/crates/leonida-hle/src/modules/speech.rs b/crates/leonida-hle/src/modules/speech.rs new file mode 100644 index 000000000..15e8eca86 --- /dev/null +++ b/crates/leonida-hle/src/modules/speech.rs @@ -0,0 +1,151 @@ +//! Accessibility: speech synthesis for the title's narration. No voice is +//! installed here, and every stream is valid WAVE audio of no length, so +//! narration is silent. +// shortcut: silent speech. The host's engine (SAPI through COM, or WinRT +// speech synthesis) needs COM bindings this crate has only in diagnostics +// builds, plus voice enumeration and SSML the title sends (slot 0xa8); the +// title then plays the empty stream and goes on. +#![allow(clippy::not_unsafe_ptr_arg_deref)] + +use std::ffi::{c_char, c_void}; + +use super::xgameruntime::{ + Guid, HRESULT, Interface, Methods, Object, S_OK, add_ref, missing, put, text, +}; + +/// Closed captions, high contrast, speech to text and synthesis. +pub const PROVIDER: Guid = Guid::new( + 0x3e24_1977, + 0x6237, + 0x41e9, + [0x85, 0x59, 0x10, 0x2c, 0x2d, 0x99, 0x83, 0xf1], +); +/// Unchanged since 2020. +pub const IID: Guid = Guid::new( + 0xd722_b373, + 0x8c4d, + 0x4692, + [0x9e, 0x51, 0xd6, 0xad, 0x9b, 0x37, 0xaa, 0x7d], +); + +pub static OBJECT: Object = Object::new("accessibility", &VTABLE); +pub const INTERFACES: &[Interface] = &[(PROVIDER, IID, &OBJECT)]; + +/// A WAVE file of 16 kHz mono 16-bit PCM with no samples: RIFF size 36, +/// a 16-byte format chunk (PCM, 1 channel, 16,000 Hz, 32,000 bytes/s, +/// block 2, 16 bits), an empty data chunk. +const SILENCE: [u8; 44] = + *b"RIFF\x24\0\0\0WAVEfmt \x10\0\0\0\x01\0\x01\0\x80\x3e\0\0\0\x7d\0\0\x02\0\x10\0data\0\0\0\0"; + +/// Synthesizers and streams hold nothing, so their handles are fixed +/// addresses and closing them is free. +static SYNTHESIZER: u8 = 0; +static STREAM: u8 = 0; + +type This = *const Object; + +/// No voice is installed, so the callback never runs. +extern "system" fn enumerate_voices( + _: This, + _context: *mut c_void, + _callback: *const c_void, +) -> HRESULT { + S_OK +} +extern "system" fn create(_: This, out: *mut *const u8) -> HRESULT { + put(out, &raw const SYNTHESIZER) +} +extern "system" fn close(_: This, _: *const u8) -> HRESULT { + S_OK +} +extern "system" fn set_default_voice(_: This, _: *const u8) -> HRESULT { + S_OK +} +extern "system" fn set_custom_voice(_: This, _: *const u8, _voice: *const c_char) -> HRESULT { + S_OK +} +extern "system" fn create_stream( + _: This, + _: *const u8, + words: *const c_char, + out: *mut *const u8, +) -> HRESULT { + tracing::debug!(text = text(words).unwrap_or_default(), "speech (silent)"); + put(out, &raw const STREAM) +} +extern "system" fn stream_size(_: This, _: *const u8, out: *mut usize) -> HRESULT { + put(out, SILENCE.len()) +} +extern "system" fn stream_data( + _: This, + _: *const u8, + size: usize, + buffer: *mut u8, + used: *mut usize, +) -> HRESULT { + if buffer.is_null() || size < SILENCE.len() { + return super::xasync::E_NOT_SUFFICIENT_BUFFER; + } + // SAFETY: the buffer holds `size` bytes, checked above. + unsafe { buffer.copy_from_nonoverlapping(SILENCE.as_ptr(), SILENCE.len()) }; + if !used.is_null() { + // SAFETY: checked non-null. + unsafe { used.write(SILENCE.len()) }; + } + S_OK +} + +static VTABLE: Methods<22> = Methods([ + missing::<0> as *const (), + add_ref as *const (), + add_ref as *const (), + missing::<3> as *const (), // 0x18 closed captions + missing::<4> as *const (), // 0x20 + missing::<5> as *const (), // 0x28 high contrast + missing::<6> as *const (), // 0x30 speech to text + missing::<7> as *const (), // 0x38 + enumerate_voices as *const (), // 0x40 + create as *const (), // 0x48 + close as *const (), // 0x50 + set_default_voice as *const (), // 0x58 + set_custom_voice as *const (), // 0x60 + create_stream as *const (), // 0x68 from text + close as *const (), // 0x70 a stream + stream_size as *const (), // 0x78 + stream_data as *const (), // 0x80 + missing::<17> as *const (), // 0x88 speech to text + missing::<18> as *const (), // 0x90 + missing::<19> as *const (), // 0x98 + missing::<20> as *const (), // 0xa0 + create_stream as *const (), // 0xa8 from SSML +]); + +#[cfg(test)] +mod tests { + use super::*; + use crate::modules::xgameruntime::method; + + #[test] + fn streams_are_empty_wave_files() { + let this: This = &OBJECT; + type Create = extern "system" fn(This, *mut *const u8) -> HRESULT; + type Stream = extern "system" fn(This, *const u8, *const c_char, *mut *const u8) -> HRESULT; + type Size = extern "system" fn(This, *const u8, *mut usize) -> HRESULT; + type Data = extern "system" fn(This, *const u8, usize, *mut u8, *mut usize) -> HRESULT; + let (mut synth, mut stream, mut size) = (std::ptr::null(), std::ptr::null(), 0); + assert_eq!(method::(&OBJECT, 0x48)(this, &mut synth), S_OK); + let say = method::(&OBJECT, 0x68); + assert_eq!(say(this, synth, c"Hello".as_ptr(), &mut stream), S_OK); + assert_eq!(method::(&OBJECT, 0x78)(this, stream, &mut size), S_OK); + let mut wav = vec![0u8; size]; + let mut used = 0; + let data = method::(&OBJECT, 0x80); + assert_eq!(data(this, stream, size, wav.as_mut_ptr(), &mut used), S_OK); + assert_eq!( + (&wav[..4], &wav[8..16], &wav[36..40]), + (&b"RIFF"[..], &b"WAVEfmt "[..], &b"data"[..]) + ); + assert_eq!(u32::from_le_bytes(wav[24..28].try_into().unwrap()), 16_000); + assert_eq!(used, 44); + } +} diff --git a/crates/leonida-hle/src/modules/storage.rs b/crates/leonida-hle/src/modules/storage.rs new file mode 100644 index 000000000..600cbad97 --- /dev/null +++ b/crates/leonida-hle/src/modules/storage.rs @@ -0,0 +1,240 @@ +//! Persistent local storage: a host folder of the title's own +//! (`runtime::Title::storage`, under the data directory, never the cache) +//! with the quota its manifest declares, seen by the title as a drive +//! (`files`). +#![allow(clippy::not_unsafe_ptr_arg_deref)] + +use std::path::Path; + +use super::xasync::{self, AsyncBlock, E_ABORT}; +use super::xgameruntime::{ + Guid, HRESULT, Interface, Methods, NOT_SUPPORTED, Object, S_OK, add_ref, missing, put, + put_string, +}; +use crate::runtime; + +pub const PROVIDER: Guid = Guid::new( + 0xf4fa_f4d4, + 0x2d04, + 0x4fce, + [0xb3, 0xe0, 0x47, 0x4a, 0x71, 0x3a, 0x3e, 0x84], +); +pub const IID: Guid = Guid::new( + 0xd294_11df, + 0x0794, + 0x4553, + [0x8b, 0x27, 0x95, 0xfc, 0x02, 0xd0, 0xf7, 0x5d], +); + +/// As the title (2026) asks for it; it calls 0x20 (path) and 0x28 +/// (space) with the same arguments. +pub const IID_2026: Guid = Guid::new( + 0x41a4_e10c, + 0x5a7e, + 0x41d9, + [0x8c, 0x37, 0x37, 0xbd, 0xe6, 0x2a, 0x07, 0xd6], +); + +pub static OBJECT: Object = Object::new("persistent local storage", &VTABLE); +pub const INTERFACES: &[Interface] = &[(PROVIDER, IID, &OBJECT), (PROVIDER, IID_2026, &OBJECT)]; + +const E_FAIL: HRESULT = 0x8000_4005_u32 as i32; + +type This = *const Object; + +/// The path titles get: the root of a virtual drive over the folder. On the +/// console storage is a drive of its own, and titles rely on it: Minecraft +/// keeps only what precedes the path's last `:\` and mounts that as a +/// drive, so a host folder such as `C:\Users\..` would make it write to the +/// root of `C:`. None (the path calls fail) before the title is set. +fn folder() -> Option { + let storage = runtime::title().storage; + if storage.as_os_str().is_empty() { + return None; + } + #[cfg(windows)] + return super::files::mount(&storage).map(|letter| format!("{letter}:\\")); + #[cfg(not(windows))] + None +} + +extern "system" fn path_size(_: This, out: *mut usize) -> HRESULT { + match folder() { + Some(path) => put(out, path.len() + 1), + None => NOT_SUPPORTED, + } +} + +/// A buffer too small for the path fails with `E_FAIL`, the documented +/// Xbox result (a PC gets `ERROR_INSUFFICIENT_BUFFER`). +extern "system" fn path(_: This, size: usize, buffer: *mut u8, used: *mut usize) -> HRESULT { + match folder() { + Some(path) if size <= path.len() => E_FAIL, + Some(path) => put_string(&path, size, buffer, used), + None => NOT_SUPPORTED, + } +} + +#[repr(C)] +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct SpaceInfo { + /// Writable now. + pub available_free: u64, + /// Left in the quota. + pub total_free: u64, + pub used: u64, + /// The quota. + pub total: u64, +} + +fn used_bytes(dir: &Path) -> u64 { + let Ok(entries) = std::fs::read_dir(dir) else { + return 0; + }; + entries + .flatten() + .map(|e| match e.metadata() { + Ok(m) if m.is_dir() => used_bytes(&e.path()), + Ok(m) => m.len(), + Err(_) => 0, + }) + .sum() +} + +/// What the host disk under `dir` has free (unlimited if unknown). +pub(crate) fn disk_free(dir: &Path) -> u64 { + #[cfg(windows)] + { + use std::os::windows::ffi::OsStrExt; + let wide: Vec = dir.as_os_str().encode_wide().chain([0]).collect(); + let mut free = 0; + let null = std::ptr::null_mut(); + // SAFETY: a NUL-terminated path and a valid output. + let ok = unsafe { + windows_sys::Win32::Storage::FileSystem::GetDiskFreeSpaceExW( + wide.as_ptr(), + &mut free, + null, + null, + ) + }; + if ok != 0 { + return free; + } + } + let _ = dir; + u64::MAX +} + +fn space() -> SpaceInfo { + let title = runtime::title(); + let used = used_bytes(&title.storage); + let free = title.storage_bytes.saturating_sub(used); + SpaceInfo { + // Writable now: the quota's rest, as far as the host disk allows. + available_free: free.min(disk_free(&title.storage)), + total_free: free, + used, + total: title.storage_bytes, + } +} + +extern "system" fn space_info(_: This, out: *mut SpaceInfo) -> HRESULT { + put(out, space()) +} + +/// Tells our prompts apart from other calls on the same block. +static PROMPT: u8 = 0; + +/// There is nobody to ask: granted when the quota has room, else declined. +extern "system" fn prompt_for_space(_: This, bytes: u64, block: *mut AsyncBlock) -> HRESULT { + let hr = if bytes <= space().total_free { + S_OK + } else { + E_ABORT + }; + xasync::finished(block, (&raw const PROMPT).cast(), hr) +} + +extern "system" fn prompt_result(_: This, block: *mut AsyncBlock) -> HRESULT { + let none = std::ptr::null_mut(); + xasync::XAsyncGetResult(block, (&raw const PROMPT).cast(), 0, none, none.cast()) +} + +static VTABLE: Methods<8> = Methods([ + missing::<0> as *const (), + add_ref as *const (), + add_ref as *const (), + path_size as *const (), // 0x18 + path as *const (), // 0x20 + space_info as *const (), // 0x28 + prompt_for_space as *const (), // 0x30 + prompt_result as *const (), // 0x38 +]); + +#[cfg(test)] +mod tests { + use super::*; + use crate::modules::xgameruntime::method; + + #[test] + fn serves_a_drive_over_the_title_folder_and_its_quota() { + type Size = extern "system" fn(This, *mut usize) -> HRESULT; + type Get = extern "system" fn(This, usize, *mut u8, *mut usize) -> HRESULT; + type Space = extern "system" fn(This, *mut SpaceInfo) -> HRESULT; + type Prompt = extern "system" fn(This, u64, *mut AsyncBlock) -> HRESULT; + type Result = extern "system" fn(This, *mut AsyncBlock) -> HRESULT; + let this: This = &OBJECT; + let dir = tempfile::tempdir().unwrap(); + std::fs::write(dir.path().join("save.dat"), [0u8; 100]).unwrap(); + runtime::set_title(runtime::Title { + id: 1, + storage: dir.path().to_owned(), + storage_bytes: 1000, + ..Default::default() + }); + + // The path is a drive root, never the host folder. + let mut size = 0; + assert_eq!(method::(&OBJECT, 0x18)(this, &mut size), S_OK); + assert_eq!(size, 4, "X:\\ and its NUL"); + let (mut buffer, mut used) = ([0u8; 4], 0); + let get = method::(&OBJECT, 0x20); + assert_eq!(get(this, 4, buffer.as_mut_ptr(), &mut used), S_OK); + assert_eq!(get(this, 3, buffer.as_mut_ptr(), &mut used), E_FAIL); + let drive = std::str::from_utf8(&buffer[..3]).unwrap(); + assert!(drive.ends_with(":\\"), "{drive}"); + // Title file calls on it reach the folder. + let path = format!("{drive}save.dat\0"); + let mut attributes = [0u8; 36]; + let get_attributes = super::super::files::GetFileAttributesExW; + let wide: Vec = path.encode_utf16().collect(); + assert_ne!( + get_attributes(wide.as_ptr(), 0, attributes.as_mut_ptr().cast()), + 0 + ); + + let mut info = SpaceInfo { + available_free: 0, + total_free: 0, + used: 0, + total: 0, + }; + assert_eq!(method::(&OBJECT, 0x28)(this, &mut info), S_OK); + assert_eq!((info.used, info.total_free, info.total), (100, 900, 1000)); + + let prompt = method::(&OBJECT, 0x30); + let result = method::(&OBJECT, 0x38); + for (bytes, expect) in [(900, S_OK), (901, E_ABORT)] { + let mut block = AsyncBlock { + queue: std::ptr::null(), + context: std::ptr::null_mut(), + callback: None, + internal: [0; 4], + }; + assert_eq!(prompt(this, bytes, &mut block), S_OK); + assert_eq!(xasync::XAsyncGetStatus(&mut block, true), expect); + assert_eq!(result(this, &mut block), expect, "{bytes} bytes"); + } + } +} diff --git a/crates/leonida-hle/src/modules/xasync.rs b/crates/leonida-hle/src/modules/xasync.rs new file mode 100644 index 000000000..068d75f2a --- /dev/null +++ b/crates/leonida-hle/src/modules/xasync.rs @@ -0,0 +1,1337 @@ +//! XTaskQueue and XAsync: the runtime's callback queues and async-call +//! blocks, served as the task-queue provider's object from `QueryApiImpl`. +//! +//! As documented for the public API: a queue has a work port and a +//! completion port, each dispatched manually (the title calls dispatch), +//! on a thread pool, serialised on one thread, or immediately on the +//! submitting thread. A null queue handle means the process queue. An +//! async block's system area holds its status and result size, so both +//! stay readable after our state for the call is gone. +#![allow(non_snake_case)] +#![allow(clippy::not_unsafe_ptr_arg_deref)] + +use std::collections::{HashMap, VecDeque}; +use std::ffi::c_void; +use std::sync::atomic::{AtomicBool, AtomicU64, AtomicUsize, Ordering}; +use std::sync::{Arc, Condvar, LazyLock, Mutex, MutexGuard}; +use std::time::Duration; + +use super::xgameruntime::{Guid, HRESULT, Interface, Methods, Object, S_OK, add_ref, missing}; + +/// The task-queue provider; it is also the interface id titles ask for. +pub const PROVIDER: Guid = Guid { + data1: 0x073b_7dcb, + data2: 0x1fcf, + data3: 0x4030, + data4: [0x94, 0xbe, 0xe3, 0xc9, 0xeb, 0x62, 0x34, 0x28], +}; + +pub const E_PENDING: HRESULT = 0x8000_000A_u32 as i32; +pub const E_ABORT: HRESULT = 0x8000_4004_u32 as i32; +pub const E_NOTIMPL: HRESULT = 0x8000_4001_u32 as i32; +pub const E_INVALIDARG: HRESULT = 0x8007_0057_u32 as i32; +pub const E_NOT_SUFFICIENT_BUFFER: HRESULT = 0x8007_007A_u32 as i32; +pub const E_ILLEGAL_METHOD_CALL: HRESULT = 0x8000_000E_u32 as i32; + +const WORK: u32 = 0; +const COMPLETION: u32 = 1; +const INFINITE: u32 = u32::MAX; + +type Callback = extern "system" fn(*mut c_void, bool); +type MonitorCallback = extern "system" fn(*mut c_void, *const Queue, u32); +type TerminatedCallback = extern "system" fn(*mut c_void); +type CompletionRoutine = extern "system" fn(*mut AsyncBlock); +type Provider = extern "system" fn(u32, *const ProviderData) -> HRESULT; + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum Mode { + Manual, + ThreadPool, + Serialized, + Immediate, +} + +impl Mode { + fn from_raw(mode: u32) -> Option { + [ + Mode::Manual, + Mode::ThreadPool, + Mode::Serialized, + Mode::Immediate, + ] + .get(mode as usize) + .copied() + } +} + +/// A title callback and its context (addresses, so tasks can cross threads). +#[derive(Clone, Copy)] +struct Task { + context: usize, + callback: usize, +} + +impl Task { + fn new(context: *mut c_void, callback: Callback) -> Task { + Task { + context: context as usize, + callback: callback as usize, + } + } + + fn run(self, canceled: bool) { + // SAFETY: built from a `Callback` in `new`. + let callback: Callback = unsafe { std::mem::transmute(self.callback) }; + callback(self.context as *mut c_void, canceled); + } +} + +struct Port { + mode: Mode, + tasks: Mutex>, + ready: Condvar, +} + +impl Port { + fn new(mode: Mode) -> Arc { + let port = Arc::new(Port { + mode, + tasks: Mutex::default(), + ready: Condvar::new(), + }); + if mode == Mode::Serialized { + // The worker ends once it holds the last reference (every queue + // using the port is closed) and nothing is left to run. + let worker = port.clone(); + std::thread::spawn(move || { + loop { + match worker.take(1000, || false) { + Some(task) => task.run(false), + None if Arc::strong_count(&worker) == 1 => break, + None => {} + } + } + }); + } + port + } + + fn submit(&self, task: Task) { + match self.mode { + Mode::Immediate => task.run(false), + Mode::ThreadPool => POOL.submit(task), + Mode::Manual | Mode::Serialized => { + lock(&self.tasks).push_back(task); + self.ready.notify_one(); + } + } + } + + /// The next queued task, waiting up to `timeout_ms`, or until `ended` + /// (checked whenever the port is woken) says no task will come. + fn take(&self, timeout_ms: u32, ended: impl Fn() -> bool) -> Option { + let waiting = |t: &mut VecDeque| t.is_empty() && !ended(); + let tasks = lock(&self.tasks); + let mut tasks = if timeout_ms == INFINITE { + self.ready + .wait_while(tasks, waiting) + .unwrap_or_else(|e| e.into_inner()) + } else { + let timeout = Duration::from_millis(timeout_ms.into()); + self.ready + .wait_timeout_while(tasks, timeout, waiting) + .unwrap_or_else(|e| e.into_inner()) + .0 + }; + tasks.pop_front() + } +} + +/// The thread pool behind thread-pool ports: idle workers are reused, and a +/// new one starts whenever more tasks wait than workers idle, so a callback +/// that blocks on another never starves it. Workers stay for reuse. +struct Pool { + /// Queued tasks and the number of idle workers. + state: Mutex<(VecDeque, usize)>, + ready: Condvar, +} + +static POOL: Pool = Pool { + state: Mutex::new((VecDeque::new(), 0)), + ready: Condvar::new(), +}; + +impl Pool { + fn submit(&'static self, task: Task) { + let mut state = lock(&self.state); + state.0.push_back(task); + if state.0.len() > state.1 { + std::thread::spawn(move || self.work()); + } else { + self.ready.notify_one(); + } + } + + fn work(&self) { + let mut state = lock(&self.state); + loop { + while state.0.is_empty() { + state.1 += 1; + state = self.ready.wait(state).unwrap_or_else(|e| e.into_inner()); + state.1 -= 1; + } + let task = state.0.pop_front(); + drop(state); + if let Some(task) = task { + task.run(false); + } + state = lock(&self.state); + } + } +} + +/// A queue handle is `Arc::into_raw` of this; duplicating and closing a +/// handle add and drop a reference. +pub struct Queue { + ports: [Arc; 2], + monitors: Mutex>, + terminated: AtomicBool, +} + +impl Queue { + fn new(ports: [Arc; 2]) -> Arc { + Arc::new(Queue { + ports, + monitors: Mutex::default(), + terminated: AtomicBool::new(false), + }) + } + + fn submit(self: &Arc, port: u32, delay_ms: u32, task: Task) -> HRESULT { + if port > COMPLETION { + return E_INVALIDARG; + } + if self.terminated.load(Ordering::Acquire) { + return E_ABORT; + } + if delay_ms == 0 { + self.deliver(port, task); + } else { + let queue = self.clone(); + std::thread::spawn(move || { + std::thread::sleep(Duration::from_millis(delay_ms.into())); + queue.deliver(port, task); + }); + } + S_OK + } + + fn deliver(self: &Arc, port: u32, task: Task) { + self.ports[port as usize].submit(task); + // Copied out: a monitor may unregister itself. + let monitors = lock(&self.monitors).clone(); + for (_, context, callback) in monitors { + // SAFETY: stored from a `MonitorCallback` in `register_monitor`. + let callback: MonitorCallback = unsafe { std::mem::transmute(callback) }; + callback(context as *mut c_void, Arc::as_ptr(self), port); + } + } +} + +fn lock(m: &Mutex) -> MutexGuard<'_, T> { + m.lock().unwrap_or_else(|e| e.into_inner()) +} + +/// The process queue: `None` until first used (then a thread-pool queue), +/// `Some(None)` once the title clears it. +static PROCESS_QUEUE: Mutex>>> = Mutex::new(None); + +fn process_queue() -> Option> { + lock(&PROCESS_QUEUE) + .get_or_insert_with(|| { + Some(Queue::new([ + Port::new(Mode::ThreadPool), + Port::new(Mode::ThreadPool), + ])) + }) + .clone() +} + +/// A new reference to the queue behind `handle` (null: the process queue). +fn queue(handle: *const Queue) -> Option> { + if handle.is_null() { + return process_queue(); + } + // SAFETY: a handle we returned, which the title has not closed. + unsafe { + Arc::increment_strong_count(handle); + Some(Arc::from_raw(handle)) + } +} + +pub fn XTaskQueueCreate(work: u32, completion: u32, out: *mut *const Queue) -> HRESULT { + let (Some(work), Some(completion)) = (Mode::from_raw(work), Mode::from_raw(completion)) else { + return E_INVALIDARG; + }; + if out.is_null() { + return E_INVALIDARG; + } + let queue = Queue::new([Port::new(work), Port::new(completion)]); + // SAFETY: checked non-null; the title passes room for a handle. + unsafe { out.write(Arc::into_raw(queue)) }; + S_OK +} + +/// A port handle points at the port, which its queue keeps alive. +pub fn XTaskQueueGetPort(handle: *const Queue, port: u32, out: *mut *const c_void) -> HRESULT { + let Some(queue) = queue(handle) else { + return E_INVALIDARG; + }; + if port > COMPLETION || out.is_null() { + return E_INVALIDARG; + } + // SAFETY: checked non-null. + unsafe { out.write(Arc::as_ptr(&queue.ports[port as usize]).cast()) }; + S_OK +} + +pub fn XTaskQueueCreateComposite( + work: *const c_void, + completion: *const c_void, + out: *mut *const Queue, +) -> HRESULT { + if work.is_null() || completion.is_null() || out.is_null() { + return E_INVALIDARG; + } + let port = |p: *const c_void| { + // SAFETY: a port handle from `XTaskQueueGetPort`, whose queue is open. + unsafe { + Arc::increment_strong_count(p.cast::()); + Arc::from_raw(p.cast::()) + } + }; + let queue = Queue::new([port(work), port(completion)]); + // SAFETY: checked non-null. + unsafe { out.write(Arc::into_raw(queue)) }; + S_OK +} + +pub fn XTaskQueueDuplicateHandle(handle: *const Queue, out: *mut *const Queue) -> HRESULT { + match queue(handle) { + Some(queue) if !out.is_null() => { + // SAFETY: checked non-null. + unsafe { out.write(Arc::into_raw(queue)) }; + S_OK + } + _ => E_INVALIDARG, + } +} + +pub fn XTaskQueueCloseHandle(handle: *const Queue) { + if !handle.is_null() { + // SAFETY: a handle we returned; this drops its reference. + unsafe { Arc::decrement_strong_count(handle) }; + } +} + +/// Runs one queued callback of a manual port; false if none came in time, +/// or none can come: the queue was terminated (which ends a wait under way, +/// as a dispatcher thread's loop expects). +pub fn XTaskQueueDispatch(handle: *const Queue, port: u32, timeout_ms: u32) -> bool { + let Some(queue) = queue(handle) else { + return false; + }; + let Some(port) = queue.ports.get(port as usize) else { + return false; + }; + if port.mode != Mode::Manual { + return false; + } + match port.take(timeout_ms, || queue.terminated.load(Ordering::Acquire)) { + Some(task) => { + task.run(false); + true + } + None => false, + } +} + +pub fn XTaskQueueSubmitDelayedCallback( + handle: *const Queue, + port: u32, + delay_ms: u32, + context: *mut c_void, + callback: Option, +) -> HRESULT { + match (queue(handle), callback) { + (Some(queue), Some(callback)) => queue.submit(port, delay_ms, Task::new(context, callback)), + _ => E_INVALIDARG, + } +} + +/// Cancels what is still queued (callbacks see `canceled`), refuses new +/// work, then calls `callback`. +pub fn XTaskQueueTerminate( + handle: *const Queue, + _wait: bool, + context: *mut c_void, + callback: Option, +) -> HRESULT { + let Some(queue) = queue(handle) else { + return E_INVALIDARG; + }; + queue.terminated.store(true, Ordering::Release); + for port in &queue.ports { + let pending: Vec = lock(&port.tasks).drain(..).collect(); + // Dispatches waiting on this queue end: nothing more will come. + // (Those of other queues on the port see theirs is open and wait + // on.) After the lock above, so none misses both flag and wake. + port.ready.notify_all(); + for task in pending { + task.run(true); + } + } + if let Some(callback) = callback { + callback(context); + } + S_OK +} + +static NEXT_TOKEN: AtomicU64 = AtomicU64::new(1); + +pub fn XTaskQueueRegisterMonitor( + handle: *const Queue, + context: *mut c_void, + callback: Option, + token: *mut u64, +) -> HRESULT { + let (Some(queue), Some(callback)) = (queue(handle), callback) else { + return E_INVALIDARG; + }; + if token.is_null() { + return E_INVALIDARG; + } + let id = NEXT_TOKEN.fetch_add(1, Ordering::Relaxed); + lock(&queue.monitors).push((id, context as usize, callback as usize)); + // SAFETY: checked non-null. + unsafe { token.write(id) }; + S_OK +} + +pub fn XTaskQueueUnregisterMonitor(handle: *const Queue, token: u64) { + if let Some(queue) = queue(handle) { + lock(&queue.monitors).retain(|m| m.0 != token); + } +} + +/// A new handle to the process queue, if there is one. +pub fn XTaskQueueGetCurrentProcessTaskQueue(out: *mut *const Queue) -> bool { + let found = process_queue(); + if !out.is_null() { + // SAFETY: checked non-null. + unsafe { out.write(found.clone().map_or(std::ptr::null(), Arc::into_raw)) }; + } + found.is_some() +} + +pub fn XTaskQueueSetCurrentProcessTaskQueue(handle: *const Queue) { + let new = if handle.is_null() { + None + } else { + queue(handle) + }; + *lock(&PROCESS_QUEUE) = Some(new); +} + +/// An async block: what the title fills in, then the system area. +#[repr(C)] +pub struct AsyncBlock { + pub queue: *const Queue, + pub context: *mut c_void, + pub callback: Option, + /// Ours: [unused, status, result size, unused]. + pub internal: [usize; 4], +} + +#[repr(C)] +pub struct ProviderData { + pub block: *mut AsyncBlock, + pub buffer_size: usize, + pub buffer: *mut c_void, + pub context: *mut c_void, +} + +const OP_BEGIN: u32 = 0; +const OP_DO_WORK: u32 = 1; +const OP_GET_RESULT: u32 = 2; +const OP_CANCEL: u32 = 3; +const OP_CLEANUP: u32 = 4; + +/// One call in flight, until its result is taken or it fails. +struct Call { + provider: Provider, + context: usize, + identity: usize, + done: Mutex, + finished: Condvar, +} + +impl Call { + fn provider( + &self, + op: u32, + block: *mut AsyncBlock, + size: usize, + buffer: *mut c_void, + ) -> HRESULT { + let data = ProviderData { + block, + buffer_size: size, + buffer, + context: self.context as *mut c_void, + }; + (self.provider)(op, &data) + } +} + +/// Calls by block address. +static CALLS: LazyLock>>> = LazyLock::new(Default::default); + +fn call(block: *mut AsyncBlock) -> Option> { + lock(&CALLS).get(&(block as usize)).cloned() +} + +/// The block's status and result-size words. +fn words(block: *mut AsyncBlock) -> (&'static AtomicUsize, &'static AtomicUsize) { + // SAFETY: the title's block outlives the call; its system area is ours. + unsafe { + let internal = std::ptr::addr_of_mut!((*block).internal).cast::(); + (&*internal.add(1), &*internal.add(2)) + } +} + +fn status(block: *mut AsyncBlock) -> HRESULT { + words(block).0.load(Ordering::Acquire) as u32 as i32 +} + +fn release(block: *mut AsyncBlock) { + // Unlocked before the provider runs: it may call back into us. + let removed = lock(&CALLS).remove(&(block as usize)); + if let Some(call) = removed { + call.provider(OP_CLEANUP, block, 0, std::ptr::null_mut()); + } +} + +pub fn XAsyncBegin( + block: *mut AsyncBlock, + context: *mut c_void, + identity: *const c_void, + _identity_name: *const u8, + provider: Option, +) -> HRESULT { + let Some(provider) = provider else { + return E_INVALIDARG; + }; + if block.is_null() || call(block).is_some() { + return E_INVALIDARG; + } + let (status, size) = words(block); + status.store(E_PENDING as u32 as usize, Ordering::Release); + size.store(0, Ordering::Release); + let call = Arc::new(Call { + provider, + context: context as usize, + identity: identity as usize, + done: Mutex::new(false), + finished: Condvar::new(), + }); + lock(&CALLS).insert(block as usize, call.clone()); + // A failed begin fails the call, so the completion routine still runs. + let hr = call.provider(OP_BEGIN, block, 0, std::ptr::null_mut()); + if hr < 0 { + XAsyncComplete(block, hr, 0); + } + S_OK +} + +/// Queues the provider's `DoWork` on the block's work port. +pub fn XAsyncSchedule(block: *mut AsyncBlock, delay_ms: u32) -> HRESULT { + extern "system" fn work(block: *mut c_void, canceled: bool) { + let block = block.cast::(); + let Some(call) = call(block) else { return }; + let hr = if canceled { + E_ABORT + } else { + call.provider(OP_DO_WORK, block, 0, std::ptr::null_mut()) + }; + if hr != E_PENDING { + XAsyncComplete(block, hr, 0); + } + } + if block.is_null() || call(block).is_none() { + return E_INVALIDARG; + } + // SAFETY: a block in flight is valid. + let handle = unsafe { (*block).queue }; + match queue(handle) { + Some(queue) => queue.submit(WORK, delay_ms, Task::new(block.cast(), work)), + None => E_INVALIDARG, + } +} + +/// Records the result (the first one wins), wakes waiters and queues the +/// completion routine on the block's completion port. +pub fn XAsyncComplete(block: *mut AsyncBlock, result: HRESULT, required_size: usize) { + extern "system" fn complete(block: *mut c_void, _canceled: bool) { + let block = block.cast::(); + // SAFETY: read before the status was published; see below. + if let Some(routine) = unsafe { (*block).callback } { + routine(block); + } + } + let Some(call) = call(block) else { return }; + if result == E_PENDING { + return; + } + let mut done = lock(&call.done); + if *done { + return; + } + // Read before publishing: once the status is set, the title may free + // the block. + // SAFETY: a block in flight is valid. + let (handle, routine) = unsafe { ((*block).queue, (*block).callback) }; + let (status, size) = words(block); + if result < 0 || required_size == 0 { + release(block); + } + size.store(required_size, Ordering::Release); + status.store(result as u32 as usize, Ordering::Release); + *done = true; + call.finished.notify_all(); + drop(done); + if routine.is_some() { + let task = Task::new(block.cast(), complete); + match queue(handle) { + Some(queue) if queue.submit(COMPLETION, 0, task) == S_OK => {} + _ => task.run(true), + } + } +} + +pub fn XAsyncGetStatus(block: *mut AsyncBlock, wait: bool) -> HRESULT { + if block.is_null() { + return E_INVALIDARG; + } + if wait && let Some(call) = call(block) { + let done = lock(&call.done); + drop(call.finished.wait_while(done, |d| !*d)); + } + status(block) +} + +pub fn XAsyncGetResultSize(block: *mut AsyncBlock, out: *mut usize) -> HRESULT { + if block.is_null() || out.is_null() { + return E_INVALIDARG; + } + let hr = status(block); + // Any nonnegative completion carries a result, not just S_OK: S_FALSE + // is a success code too and a provider may return data with it. + if hr >= 0 { + // SAFETY: checked non-null. + unsafe { out.write(words(block).1.load(Ordering::Acquire)) }; + } + hr +} + +/// Asks the provider to cancel; the call fails with `E_ABORT` unless the +/// provider completed it first. +pub fn XAsyncCancel(block: *mut AsyncBlock) { + if let Some(call) = call(block) { + call.provider(OP_CANCEL, block, 0, std::ptr::null_mut()); + XAsyncComplete(block, E_ABORT, 0); + } +} + +/// Has the provider write the result into `buffer`, then ends the call. +pub fn XAsyncGetResult( + block: *mut AsyncBlock, + identity: *const c_void, + buffer_size: usize, + buffer: *mut c_void, + used: *mut usize, +) -> HRESULT { + if block.is_null() { + return E_INVALIDARG; + } + let hr = status(block); + let size = words(block).1.load(Ordering::Acquire); + if hr < 0 || size == 0 { + if hr >= 0 && !used.is_null() { + // SAFETY: checked non-null. + unsafe { used.write(0) }; + } + return hr; + } + let Some(call) = call(block) else { + return E_ILLEGAL_METHOD_CALL; + }; + if call.identity != identity as usize { + return E_INVALIDARG; + } + if buffer_size < size || buffer.is_null() { + return E_NOT_SUFFICIENT_BUFFER; + } + let hr = call.provider(OP_GET_RESULT, block, buffer_size, buffer); + if !used.is_null() { + // SAFETY: checked non-null. + unsafe { used.write(size) }; + } + release(block); + hr +} + +/// Starts a call on `block` that is already over: it completes with `hr` +/// and no result data, through the block's completion port as usual. +pub fn finished(block: *mut AsyncBlock, identity: *const c_void, hr: HRESULT) -> HRESULT { + finished_with( + block, + identity, + if hr < 0 { Err(hr) } else { Ok(Vec::new()) }, + ) +} + +/// Like [`finished`], with the bytes `XAsyncGetResult` hands out for +/// `identity` (an error has none). +pub fn finished_with( + block: *mut AsyncBlock, + identity: *const c_void, + result: Result, HRESULT>, +) -> HRESULT { + type Data = Result, HRESULT>; + extern "system" fn provider(op: u32, data: *const ProviderData) -> HRESULT { + // SAFETY: the runtime passes valid provider data; the context is the + // boxed result until cleanup frees it. + let data = unsafe { &*data }; + let result = data.context.cast::(); + match op { + // SAFETY: boxed in `finished_with`; nothing runs after cleanup. + OP_CLEANUP => drop(unsafe { Box::from_raw(result) }), + OP_BEGIN => { + // SAFETY: as above. Copied out: completing may clean up. + let (hr, len) = match unsafe { &*result } { + Ok(bytes) => (S_OK, bytes.len()), + Err(hr) => (*hr, 0), + }; + XAsyncComplete(data.block, hr, len); + } + // SAFETY: as above; the runtime checked the buffer's size. + OP_GET_RESULT => unsafe { + if let Ok(bytes) = &*result { + data.buffer + .cast::() + .copy_from(bytes.as_ptr(), bytes.len()); + } + }, + _ => {} + } + S_OK + } + let context = Box::into_raw(Box::new(result)); + let hr = XAsyncBegin( + block, + context.cast(), + identity, + std::ptr::null(), + Some(provider), + ); + if hr < 0 { + // Refused before the call existed, so no cleanup will come. + // SAFETY: still ours. + drop(unsafe { Box::from_raw(context) }); + } + hr +} + +/// Like [`finished_with`], but the result comes from `work`, run on a +/// thread of ours; the call stays pending until it returns (a dialog, say). +pub fn pending_with( + block: *mut AsyncBlock, + identity: *const c_void, + work: impl FnOnce() -> Result, HRESULT> + Send + 'static, +) -> HRESULT { + type Data = Mutex<(Option Result, HRESULT> + Send>>, Vec)>; + extern "system" fn provider(op: u32, data: *const ProviderData) -> HRESULT { + // SAFETY: the runtime passes valid provider data; the context is the + // boxed state until cleanup frees it. + let data = unsafe { &*data }; + let state = data.context.cast::(); + match op { + // SAFETY: boxed in `pending_with`; nothing runs after cleanup. + OP_CLEANUP => drop(unsafe { Box::from_raw(state) }), + OP_BEGIN => { + // SAFETY: as above; cleanup waits for completion. + let work = unsafe { &*state }.lock().unwrap_or_else(|e| e.into_inner()).0.take(); + let (block, state) = (data.block as usize, state as usize); + std::thread::spawn(move || { + let result = work.map_or(Err(E_ABORT), |work| work()); + let (hr, len) = match &result { + Ok(bytes) => (S_OK, bytes.len()), + Err(hr) => (*hr, 0), + }; + if let Ok(bytes) = result { + // SAFETY: the call is pending, so its state lives. + let state = unsafe { &*(state as *const Data) }; + state.lock().unwrap_or_else(|e| e.into_inner()).1 = bytes; + } + XAsyncComplete(block as *mut AsyncBlock, hr, len); + }); + } + // SAFETY: as above; the runtime checked the buffer's size. + OP_GET_RESULT => unsafe { + let state = (*state).lock().unwrap_or_else(|e| e.into_inner()); + data.buffer + .cast::() + .copy_from(state.1.as_ptr(), state.1.len()); + }, + _ => {} + } + S_OK + } + let state: Box = Box::new(Mutex::new((Some(Box::new(work)), Vec::new()))); + let context = Box::into_raw(state); + let hr = XAsyncBegin(block, context.cast(), identity, std::ptr::null(), Some(provider)); + if hr < 0 { + // SAFETY: refused before the call existed; still ours. + drop(unsafe { Box::from_raw(context) }); + } + hr +} + +/// The result of a call begun with [`finished_with`] for `identity`, as a +/// `T` written through `out`. +pub fn result(block: *mut AsyncBlock, identity: *const c_void, out: *mut T) -> HRESULT { + XAsyncGetResult( + block, + identity, + size_of::(), + out.cast(), + std::ptr::null_mut(), + ) +} + +/// The bytes of a value, for [`finished_with`]. +pub fn bytes(value: T) -> Vec { + // SAFETY: a `Copy` value is plain data; padding bytes are never read. + unsafe { std::slice::from_raw_parts((&raw const value).cast::(), size_of::()) }.to_vec() +} + +type Work = extern "system" fn(*mut AsyncBlock) -> HRESULT; + +/// Runs `work` on the block's work port as an async call of its own; its +/// return value is the call's result. +pub fn XAsyncRun(block: *mut AsyncBlock, work: Option) -> HRESULT { + extern "system" fn provider(op: u32, data: *const ProviderData) -> HRESULT { + // SAFETY: the runtime passes valid provider data. + let data = unsafe { &*data }; + match op { + OP_BEGIN => XAsyncSchedule(data.block, 0), + OP_DO_WORK => { + // SAFETY: the context is the `Work` given to `XAsyncRun`. + let work = unsafe { std::mem::transmute::<*mut c_void, Work>(data.context) }; + work(data.block) + } + _ => S_OK, + } + } + let Some(work) = work else { + return E_INVALIDARG; + }; + let identity = XAsyncRun as *const c_void; + XAsyncBegin( + block, + work as *mut c_void, + identity, + std::ptr::null(), + Some(provider), + ) +} + +// The object `QueryApiImpl` returns. Each method takes the object first, +// then the API's arguments; slot offsets as titles call them. + +pub static OBJECT: Object = Object::new("task queue", &VTABLE); + +/// Its interface id is the provider's. +pub const INTERFACES: &[Interface] = &[(PROVIDER, PROVIDER, &OBJECT)]; + +type This = *const Object; +extern "system" fn m_get_status(_: This, b: *mut AsyncBlock, wait: u8) -> HRESULT { + XAsyncGetStatus(b, wait != 0) +} +extern "system" fn m_get_result_size(_: This, b: *mut AsyncBlock, out: *mut usize) -> HRESULT { + XAsyncGetResultSize(b, out) +} +extern "system" fn m_cancel(_: This, b: *mut AsyncBlock) { + XAsyncCancel(b) +} +extern "system" fn m_run(_: This, b: *mut AsyncBlock, work: Option) -> HRESULT { + XAsyncRun(b, work) +} +extern "system" fn m_begin( + _: This, + b: *mut AsyncBlock, + context: *mut c_void, + identity: *const c_void, + name: *const u8, + provider: Option, +) -> HRESULT { + XAsyncBegin(b, context, identity, name, provider) +} +extern "system" fn m_schedule(_: This, b: *mut AsyncBlock, delay: u32) -> HRESULT { + XAsyncSchedule(b, delay) +} +extern "system" fn m_complete(_: This, b: *mut AsyncBlock, hr: HRESULT, size: usize) { + XAsyncComplete(b, hr, size) +} +extern "system" fn m_get_result( + _: This, + b: *mut AsyncBlock, + identity: *const c_void, + size: usize, + buffer: *mut c_void, + used: *mut usize, +) -> HRESULT { + XAsyncGetResult(b, identity, size, buffer, used) +} +extern "system" fn m_create( + _: This, + work: u32, + completion: u32, + out: *mut *const Queue, +) -> HRESULT { + XTaskQueueCreate(work, completion, out) +} +extern "system" fn m_create_composite( + _: This, + work: *const c_void, + completion: *const c_void, + out: *mut *const Queue, +) -> HRESULT { + XTaskQueueCreateComposite(work, completion, out) +} +extern "system" fn m_get_port( + _: This, + q: *const Queue, + port: u32, + out: *mut *const c_void, +) -> HRESULT { + XTaskQueueGetPort(q, port, out) +} +extern "system" fn m_duplicate(_: This, q: *const Queue, out: *mut *const Queue) -> HRESULT { + XTaskQueueDuplicateHandle(q, out) +} +extern "system" fn m_dispatch(_: This, q: *const Queue, port: u32, timeout: u32) -> bool { + XTaskQueueDispatch(q, port, timeout) +} +extern "system" fn m_close(_: This, q: *const Queue) { + XTaskQueueCloseHandle(q) +} +extern "system" fn m_submit( + _: This, + q: *const Queue, + port: u32, + context: *mut c_void, + callback: Option, +) -> HRESULT { + XTaskQueueSubmitDelayedCallback(q, port, 0, context, callback) +} +extern "system" fn m_submit_delayed( + _: This, + q: *const Queue, + port: u32, + delay: u32, + context: *mut c_void, + callback: Option, +) -> HRESULT { + XTaskQueueSubmitDelayedCallback(q, port, delay, context, callback) +} +extern "system" fn m_terminate( + _: This, + q: *const Queue, + wait: u8, + context: *mut c_void, + callback: Option, +) -> HRESULT { + XTaskQueueTerminate(q, wait != 0, context, callback) +} +extern "system" fn m_register_monitor( + _: This, + q: *const Queue, + context: *mut c_void, + callback: Option, + token: *mut u64, +) -> HRESULT { + XTaskQueueRegisterMonitor(q, context, callback, token) +} +extern "system" fn m_unregister_monitor(_: This, q: *const Queue, token: u64) { + XTaskQueueUnregisterMonitor(q, token) +} +extern "system" fn m_get_process_queue(_: This, out: *mut *const Queue) -> bool { + XTaskQueueGetCurrentProcessTaskQueue(out) +} +extern "system" fn m_set_process_queue(_: This, q: *const Queue) { + XTaskQueueSetCurrentProcessTaskQueue(q) +} +/// The runtime's debug check that the caller is not a time-critical thread, +/// which every runtime call in a title makes first. +extern "system" fn m_check_thread(_: This) {} + +static VTABLE: Methods<31> = Methods([ + missing::<0> as *const (), // 0x00 QueryInterface + add_ref as *const (), // 0x08 AddRef + add_ref as *const (), // 0x10 Release: the object is static + m_get_status as *const (), // 0x18 + m_get_result_size as *const (), // 0x20 + m_cancel as *const (), // 0x28 + m_run as *const (), // 0x30 + m_begin as *const (), // 0x38 + missing::<8> as *const (), // 0x40 + m_schedule as *const (), // 0x48 + m_complete as *const (), // 0x50 + m_get_result as *const (), // 0x58 + m_create as *const (), // 0x60 + m_create_composite as *const (), // 0x68 + m_get_port as *const (), // 0x70 + m_duplicate as *const (), // 0x78 + m_dispatch as *const (), // 0x80 + m_close as *const (), // 0x88 + m_submit as *const (), // 0x90 + m_submit_delayed as *const (), // 0x98 + missing::<20> as *const (), // 0xa0 register a wait handle + missing::<21> as *const (), // 0xa8 unregister it + m_terminate as *const (), // 0xb0 + m_register_monitor as *const (), // 0xb8 + m_unregister_monitor as *const (), // 0xc0 + m_get_process_queue as *const (), // 0xc8 + m_set_process_queue as *const (), // 0xd0 + missing::<27> as *const (), // 0xd8 thread time-sensitivity + missing::<28> as *const (), // 0xe0 + m_check_thread as *const (), // 0xe8 + missing::<30> as *const (), // 0xf0 +]); + +#[cfg(test)] +mod tests { + use super::*; + use std::sync::atomic::AtomicU32; + + fn slot(offset: usize) -> F { + crate::modules::xgameruntime::method(&OBJECT, offset) + } + + static RAN: AtomicU32 = AtomicU32::new(0); + extern "system" fn count(context: *mut c_void, canceled: bool) { + RAN.fetch_add( + if canceled { 100 } else { context as u32 }, + Ordering::SeqCst, + ); + } + + #[test] + fn manual_ports_run_callbacks_when_dispatched() { + type Create = extern "system" fn(This, u32, u32, *mut *const Queue) -> HRESULT; + type Submit = extern "system" fn(This, *const Queue, u32, *mut c_void, Callback) -> HRESULT; + type Dispatch = extern "system" fn(This, *const Queue, u32, u32) -> bool; + type Close = extern "system" fn(This, *const Queue); + let this: This = &OBJECT; + let mut q = std::ptr::null(); + assert_eq!(slot::(0x60)(this, 0, 0, &mut q), S_OK); + assert_eq!( + slot::(0x90)(this, q, COMPLETION, 5 as *mut c_void, count), + S_OK + ); + assert_eq!(RAN.load(Ordering::SeqCst), 0, "manual: nothing runs yet"); + assert!( + !slot::(0x80)(this, q, WORK, 0), + "work port is empty" + ); + assert!(slot::(0x80)(this, q, COMPLETION, 0)); + assert_eq!(RAN.load(Ordering::SeqCst), 5); + assert!(!slot::(0x80)(this, q, COMPLETION, 0)); + slot::(0x88)(this, q); + } + + /// A provider that schedules its work and returns a u64 result. + extern "system" fn provider(op: u32, data: *const ProviderData) -> HRESULT { + // SAFETY: the runtime passes valid provider data. + let data = unsafe { &*data }; + match op { + OP_BEGIN => XAsyncSchedule(data.block, 0), + OP_DO_WORK => { + XAsyncComplete(data.block, S_OK, 8); + S_OK + } + OP_GET_RESULT => { + // SAFETY: at least 8 bytes, checked by the runtime. + unsafe { data.buffer.cast::().write(data.context as u64) }; + S_OK + } + _ => S_OK, + } + } + + static COMPLETED: AtomicU32 = AtomicU32::new(0); + extern "system" fn completed(_: *mut AsyncBlock) { + COMPLETED.fetch_add(1, Ordering::SeqCst); + } + + #[test] + fn async_calls_complete_and_return_results() { + let mut q = std::ptr::null(); + // Work on a thread pool, completion dispatched by hand. + assert_eq!(XTaskQueueCreate(1, 0, &mut q), S_OK); + let mut block = AsyncBlock { + queue: q, + context: std::ptr::null_mut(), + callback: Some(completed), + internal: [0; 4], + }; + let identity = 0x1d as *const c_void; + assert_eq!( + XAsyncBegin( + &mut block, + 42 as *mut c_void, + identity, + std::ptr::null(), + Some(provider) + ), + S_OK + ); + assert_eq!(XAsyncGetStatus(&mut block, true), S_OK); + let mut size = 0; + assert_eq!(XAsyncGetResultSize(&mut block, &mut size), S_OK); + assert_eq!(size, 8); + assert_eq!(COMPLETED.load(Ordering::SeqCst), 0, "completion is manual"); + assert!(XTaskQueueDispatch(q, COMPLETION, INFINITE)); + assert_eq!(COMPLETED.load(Ordering::SeqCst), 1); + + let mut value = 0u64; + let mut small = 0u32; + let out = (&mut small as *mut u32).cast(); + assert_eq!( + XAsyncGetResult(&mut block, identity, 4, out, std::ptr::null_mut()), + E_NOT_SUFFICIENT_BUFFER + ); + let out = (&mut value as *mut u64).cast(); + let mut used = 0; + assert_eq!( + XAsyncGetResult(&mut block, identity, 8, out, &mut used), + S_OK + ); + assert_eq!((value, used), (42, 8)); + assert!(call(&mut block).is_none(), "the call ends with its result"); + XTaskQueueCloseHandle(q); + } + + #[test] + fn a_nonnegative_completion_still_returns_its_payload() { + const S_FALSE: HRESULT = 1; + extern "system" fn provider(op: u32, data: *const ProviderData) -> HRESULT { + // SAFETY: the runtime passes valid provider data. + let data = unsafe { &*data }; + match op { + OP_BEGIN => XAsyncSchedule(data.block, 0), + OP_DO_WORK => { + XAsyncComplete(data.block, S_FALSE, 8); + S_OK + } + OP_GET_RESULT => { + // SAFETY: the caller checked eight bytes. + unsafe { data.buffer.cast::().write(0x1234) }; + S_OK + } + _ => S_OK, + } + } + let mut q = std::ptr::null(); + assert_eq!(XTaskQueueCreate(0, 0, &mut q), S_OK); + let mut block = AsyncBlock { + queue: q, + context: std::ptr::null_mut(), + callback: None, + internal: [0; 4], + }; + let identity = 0x77 as *const c_void; + assert_eq!( + XAsyncBegin(&mut block, std::ptr::null_mut(), identity, std::ptr::null(), Some(provider)), + S_OK + ); + assert!(XTaskQueueDispatch(q, WORK, 0)); + assert_eq!(XAsyncGetStatus(&mut block, false), S_FALSE); + let mut size = 0; + assert_eq!(XAsyncGetResultSize(&mut block, &mut size), S_FALSE); + assert_eq!(size, 8); + let mut value = 0u64; + let mut used = 0; + assert_eq!( + XAsyncGetResult(&mut block, identity, 8, (&mut value as *mut u64).cast(), &mut used), + S_OK + ); + assert_eq!((value, used), (0x1234, 8)); + assert!(call(&raw mut block).is_none(), "the call ends with its result"); + XTaskQueueCloseHandle(q); + } + + #[test] + fn run_returns_the_work_result() { + extern "system" fn work(_: *mut AsyncBlock) -> HRESULT { + E_ABORT + } + let mut block = AsyncBlock { + queue: std::ptr::null(), + context: std::ptr::null_mut(), + callback: None, + internal: [0; 4], + }; + assert_eq!( + slot::) -> HRESULT>(0x30)( + &OBJECT, + &mut block, + Some(work) + ), + S_OK + ); + assert_eq!(XAsyncGetStatus(&mut block, true), E_ABORT); + } + + #[test] + fn pool_callbacks_may_wait_for_each_other() { + static SECOND: AtomicBool = AtomicBool::new(false); + static FIRST: AtomicBool = AtomicBool::new(false); + extern "system" fn waits(_: *mut c_void, _: bool) { + let start = std::time::Instant::now(); + while !SECOND.load(Ordering::SeqCst) && start.elapsed().as_secs() < 5 { + std::thread::yield_now(); + } + FIRST.store(SECOND.load(Ordering::SeqCst), Ordering::SeqCst); + } + extern "system" fn releases(_: *mut c_void, _: bool) { + SECOND.store(true, Ordering::SeqCst); + } + let mut q = std::ptr::null(); + assert_eq!(XTaskQueueCreate(1, 1, &mut q), S_OK); + let none = std::ptr::null_mut(); + assert_eq!( + XTaskQueueSubmitDelayedCallback(q, WORK, 0, none, Some(waits)), + S_OK + ); + assert_eq!( + XTaskQueueSubmitDelayedCallback(q, WORK, 0, none, Some(releases)), + S_OK + ); + let start = std::time::Instant::now(); + while !FIRST.load(Ordering::SeqCst) && start.elapsed().as_secs() < 10 { + std::thread::sleep(Duration::from_millis(1)); + } + assert!(FIRST.load(Ordering::SeqCst)); + XTaskQueueCloseHandle(q); + } + + /// A dispatcher thread's loop, `while (XTaskQueueDispatch(queue, port, + /// INFINITE));`, ends when its queue is terminated: nothing can be + /// submitted to it any more, so nothing else would ever wake it. + #[test] + fn terminate_ends_a_waiting_dispatch() { + static RAN: AtomicU32 = AtomicU32::new(0); + extern "system" fn ran(_: *mut c_void, _: bool) { + RAN.fetch_add(1, Ordering::SeqCst); + } + /// Dispatches `queue`'s work until a dispatch returns false, then + /// says so. + fn dispatcher(queue: *const Queue) -> std::sync::mpsc::Receiver<()> { + let (done, ended) = std::sync::mpsc::channel(); + let queue = queue as usize; + std::thread::spawn(move || { + while XTaskQueueDispatch(queue as *const Queue, WORK, INFINITE) {} + let _ = done.send(()); + }); + ended + } + let run_one = |queue, total| { + let none = std::ptr::null_mut(); + assert_eq!( + XTaskQueueSubmitDelayedCallback(queue, WORK, 0, none, Some(ran)), + S_OK + ); + for _ in 0..500 { + if RAN.load(Ordering::SeqCst) == total { + return; + } + std::thread::sleep(Duration::from_millis(10)); + } + panic!("callback {total} did not run"); + }; + let (long, short) = (Duration::from_secs(5), Duration::from_millis(200)); + let none = std::ptr::null_mut(); + + // Two queues on the same manual ports. + let (mut a, mut b) = (std::ptr::null(), std::ptr::null()); + assert_eq!(XTaskQueueCreate(0, 0, &mut a), S_OK); + let (mut work, mut completion) = (std::ptr::null(), std::ptr::null()); + assert_eq!(XTaskQueueGetPort(a, WORK, &mut work), S_OK); + assert_eq!(XTaskQueueGetPort(a, COMPLETION, &mut completion), S_OK); + assert_eq!(XTaskQueueCreateComposite(work, completion, &mut b), S_OK); + + let ended = dispatcher(a); + run_one(a, 1); + // The other queue's end is not this one's: the wait goes on and + // still runs what comes in. + assert_eq!(XTaskQueueTerminate(b, false, none, None), S_OK); + assert!( + ended.recv_timeout(short).is_err(), + "ended with another queue" + ); + run_one(a, 2); + // Its own queue's end is. + assert_eq!(XTaskQueueTerminate(a, false, none, None), S_OK); + assert!( + ended.recv_timeout(long).is_ok(), + "still waiting on a terminated queue" + ); + // And a dispatch that starts after the end returns at once. + assert!(!XTaskQueueDispatch(a, WORK, INFINITE)); + XTaskQueueCloseHandle(a); + XTaskQueueCloseHandle(b); + } + + #[test] + fn terminate_cancels_what_is_queued() { + static TERMINATED: AtomicBool = AtomicBool::new(false); + extern "system" fn terminated(_: *mut c_void) { + TERMINATED.store(true, Ordering::SeqCst); + } + extern "system" fn note(context: *mut c_void, canceled: bool) { + // SAFETY: the test passes a pointer to its flag. + unsafe { *context.cast::() = canceled }; + } + let mut q = std::ptr::null(); + assert_eq!(XTaskQueueCreate(0, 0, &mut q), S_OK); + let mut canceled = false; + let flag = (&mut canceled as *mut bool).cast(); + assert_eq!( + XTaskQueueSubmitDelayedCallback(q, WORK, 0, flag, Some(note)), + S_OK + ); + assert_eq!( + XTaskQueueTerminate(q, true, std::ptr::null_mut(), Some(terminated)), + S_OK + ); + assert!(canceled && TERMINATED.load(Ordering::SeqCst)); + assert_eq!( + XTaskQueueSubmitDelayedCallback(q, WORK, 0, flag, Some(note)), + E_ABORT + ); + XTaskQueueCloseHandle(q); + } +} diff --git a/crates/leonida-hle/src/modules/xg.rs b/crates/leonida-hle/src/modules/xg.rs new file mode 100644 index 000000000..cee781cc2 --- /dev/null +++ b/crates/leonida-hle/src/modules/xg.rs @@ -0,0 +1,780 @@ +//! `xg_xs.dll`: the console's texture layout library. Titles ask it which +//! swizzle mode a texture should use, how large it is, where each mip and +//! slice lies, and to copy linear data into tiled memory and back. Served +//! from `leonida_formats::texture`. +//! +//! The title imports `XGCreateTextureComputer` and +//! `XGSuggestSwizzleMode` and calls these computer methods: Release (0x08), +//! the layout (0x10), copies into (0x40) and out of (0x48) a subresource, +//! and the 64 KiB tiling (0x50). The other slots log and fail. +#![allow(non_snake_case)] +// Title code passes pointers the real library would trust. +#![allow(clippy::not_unsafe_ptr_arg_deref)] + +use std::sync::atomic::{AtomicU32, Ordering}; + +use leonida_formats::texture::{Dimension, Error, Layout, Swizzle, Texture, TextureDesc}; + +use super::xasync::{E_INVALIDARG, E_NOTIMPL}; +use super::xgameruntime::{HRESULT, S_OK}; +use crate::{HleModule, hle_export}; + +const E_FAIL: HRESULT = 0x8000_4005_u32 as i32; + +/// `D3D12_RESOURCE_DESC`, whose layout field carries `0x100 | swizzle +/// mode` on the console (1 row major, 0 "pick one"). +#[repr(C)] +#[derive(Debug, Clone, Copy)] +pub struct ResourceDesc { + pub dimension: u32, + pub alignment: u64, + pub width: u64, + pub height: u32, + pub depth_or_array: u16, + pub mips: u16, + pub format: u32, + pub samples: u32, + pub quality: u32, + pub layout: u32, + pub flags: u32, +} +const _: () = assert!(size_of::() == 0x38); + +const SWIZZLED: u32 = 0x100; +const ROW_MAJOR: u32 = 1; +const ALLOW_RENDER_TARGET: u32 = 1; +const ALLOW_DEPTH_STENCIL: u32 = 2; +const TEXTURE_1D: u32 = 2; +const TEXTURE_3D: u32 = 4; + +/// The mode the console's library picks for a description: linear for 1D, +/// the XOR render and depth modes for targets, else 4 KiB standard +/// (`.ttpf` textures without a mode of their own use it). +/// +/// shortcut: the rule of the library's older optimal-mode function (any +/// size, 2D, 3D and cubes alike); `XGSuggestSwizzleMode` itself is newer +/// than every copy we could check. Revisit if streamed textures come out +/// scrambled. +fn suggested(desc: &ResourceDesc) -> Swizzle { + if desc.dimension == TEXTURE_1D { + Swizzle::LINEAR + } else if desc.flags & ALLOW_DEPTH_STENCIL != 0 { + Swizzle::SW_64KB_Z_X + } else if desc.flags & ALLOW_RENDER_TARGET != 0 { + Swizzle::SW_64KB_R_X + } else { + Swizzle::SW_4KB_S + } +} + +/// `(desc, flags, out layout)`; the title passes flags 0 and puts the +/// result in the description's layout field. +pub extern "system" fn XGSuggestSwizzleMode( + desc: *const ResourceDesc, + _flags: u32, + out: *mut u32, +) -> HRESULT { + // SAFETY: the title passes a description and room for the layout + // (either may be null). + match unsafe { (desc.as_ref(), out.as_mut()) } { + (Some(desc), Some(out)) => { + *out = SWIZZLED | suggested(desc).0; + S_OK + } + _ => E_INVALIDARG, + } +} + +#[repr(C)] +pub struct Computer { + vtable: &'static Vtable, + refs: AtomicU32, + desc: ResourceDesc, + mips: u32, + texture: Texture, +} + +type This = *mut Computer; + +fn computer<'a>(this: This) -> &'a Computer { + // SAFETY: called from computer methods only. + unsafe { &*this } +} + +pub extern "system" fn XGCreateTextureComputer( + desc: *const ResourceDesc, + out: *mut This, +) -> HRESULT { + // SAFETY: the title passes a description and room for a pointer. + let (Some(&desc), false) = (unsafe { desc.as_ref() }, out.is_null()) else { + return E_INVALIDARG; + }; + let Some(texture) = texture(&desc) else { + tracing::warn!(?desc, "no texture layout"); + return E_INVALIDARG; + }; + tracing::debug!( + width = desc.width, + height = desc.height, + format = desc.format, + layout = format_args!("{:#x}", desc.layout), + size = texture.size, + "texture computer" + ); + let mips = texture.planes[0].layout.mips.len() as u32; + let computer = Box::new(Computer { + vtable: &VTABLE, + refs: AtomicU32::new(1), + desc, + mips, + texture, + }); + // SAFETY: checked non-null. + unsafe { out.write(Box::into_raw(computer)) }; + S_OK +} + +fn texture(desc: &ResourceDesc) -> Option { + let dimension = match desc.dimension { + TEXTURE_1D => Dimension::Tex1d, + 3 => Dimension::Tex2d, + TEXTURE_3D => Dimension::Tex3d, + _ => return None, + }; + let swizzle = match desc.layout { + 0 => suggested(desc), + ROW_MAJOR => Swizzle::LINEAR, + l if l & !0xff == SWIZZLED => Swizzle(l & 0xff), + _ => return None, + }; + let texture = Texture::new(&TextureDesc { + dimension, + width: u32::try_from(desc.width).ok()?, + height: desc.height, + depth_or_array: u32::from(desc.depth_or_array), + mips: u32::from(desc.mips), + format: desc.format, + samples: desc.samples.max(1), + swizzle, + }) + .ok()?; + // The layout struct has room for 15 mips. + (texture.planes[0].layout.mips.len() <= MIPS).then_some(texture) +} + +const MIPS: usize = 15; + +/// One mip in the layout the title reads (offsets 0x00, 0x08, 0x10 and +/// 0x1c are read by the title; the rest follow the library's +/// older public shape). +#[repr(C)] +#[derive(Debug, Default, Clone, Copy)] +pub struct MipOut { + pub size: u64, + pub offset: u64, + pub slice_size: u64, + pub pitch_texels: u32, + pub pitch_bytes: u32, + pub alignment: u32, + /// Width, height in elements, depth or array size. + pub padded: [u32; 3], + pub elements: [u32; 2], + pub texels: [u32; 2], + pub depth_or_array: u32, + pub samples: u32, + pub swizzle: u32, + pub bank_rotation: [u64; 2], + pub slice_depth: u32, + pub in_tail: u32, + /// Where a tail mip starts in elements: x bits 0-10, y 11-21. + pub tail_position: u32, +} + +#[repr(C)] +#[derive(Debug, Clone, Copy)] +pub struct PlaneOut { + /// 1 data, 7 depth, 8 stencil (metadata planes are not made). + pub usage: u32, + pub size: u64, + pub slice_size: u64, + pub offset: u64, + pub alignment: u64, + pub element_bytes: u32, + pub standard_mips: u32, + pub tail_mips: u32, + pub mips: [MipOut; MIPS], +} + +#[repr(C)] +#[derive(Debug, Clone, Copy)] +pub struct LayoutOut { + pub size: u64, + pub alignment: u64, + pub mips: u32, + pub planes: u32, + pub plane: [PlaneOut; 4], + pub dimension: u32, +} +const _: () = assert!(size_of::() == 0x70); +const _: () = assert!(size_of::() == 0x6c8); +const _: () = assert!(size_of::() == 0x1b40); + +/// The mode a tail mip is reported in: the 256-byte one of its kind (3 for +/// the render kind, which GFX10 lacks), the depth mode itself. +fn tail_swizzle(swizzle: Swizzle) -> u32 { + match swizzle.0 { + 2 | 6 | 10 | 18 | 22 | 26 => Swizzle::SW_256B_D.0, + 23 | 27 => 3, + 24 => swizzle.0, + _ => Swizzle::SW_256B_S.0, + } +} + +fn mip_out(desc: &ResourceDesc, l: &Layout, i: usize) -> MipOut { + let m = &l.mips[i]; + let bpe = u64::from(l.desc.element_bytes); + let block = l.desc.block; + let three_d = desc.dimension == TEXTURE_3D; + let array = u32::from(desc.depth_or_array).max(1); + let mut out = MipOut { + pitch_texels: m.pitch * block, + pitch_bytes: m.pitch * l.desc.element_bytes, + padded: [m.pitch, m.rows, if three_d { m.depth_pitch } else { array }], + elements: [m.width, m.height], + texels: [((desc.width >> i) as u32).max(1), (desc.height >> i).max(1)], + depth_or_array: if three_d { m.depth } else { array }, + samples: l.desc.samples, + slice_depth: l.block[2], + ..MipOut::default() + }; + let slice = u64::from(m.pitch) * u64::from(m.rows) * bpe; + let depth = u64::from(if three_d { m.depth_pitch } else { 1 }); + match m.tail { + None => { + out.offset = m.offset; + out.slice_size = slice * u64::from(l.desc.samples); + out.size = out.slice_size * depth; + out.alignment = l.alignment as u32; + out.swizzle = l.desc.swizzle.0; + } + Some(t) => { + out.in_tail = 1; + out.alignment = 256; + out.swizzle = tail_swizzle(l.desc.swizzle); + if l.thick { + // A 3D tail mip is placed by position, not by offset. + out.slice_size = l.alignment / u64::from(l.block[2]); + out.tail_position = t.x | t.y << 11; + } else { + out.offset = u64::from(t.offset); + out.slice_size = slice; + } + out.size = out.slice_size * depth; + } + } + out +} + +extern "system" fn add_ref(this: This) -> u32 { + computer(this).refs.fetch_add(1, Ordering::Relaxed) + 1 +} + +extern "system" fn release(this: This) -> u32 { + let left = computer(this).refs.fetch_sub(1, Ordering::AcqRel) - 1; + if left == 0 { + // SAFETY: made by `Box::into_raw` in `XGCreateTextureComputer`; the + // last reference is gone. + drop(unsafe { Box::from_raw(this) }); + } + left +} + +extern "system" fn layout(this: This, out: *mut LayoutOut) -> HRESULT { + if out.is_null() { + return E_INVALIDARG; + } + let c = computer(this); + // SAFETY: the title passes room for the layout; every field is plain + // data, so zeroes are a valid start. + let out = unsafe { + out.write_bytes(0, 1); + &mut *out + }; + out.size = c.texture.size; + out.alignment = c.texture.alignment; + out.mips = c.mips; + out.planes = c.texture.planes.len() as u32; + out.dimension = c.desc.dimension; + // The library calls a depth plane "depth" only beside stencil or + // without mips. + let depth = + c.desc.flags & ALLOW_DEPTH_STENCIL != 0 && (c.texture.planes.len() > 1 || c.mips == 1); + for (plane, p) in out.plane.iter_mut().zip(&c.texture.planes) { + let l = &p.layout; + plane.usage = match (p.stencil, depth) { + (true, _) => 8, + (false, true) => 7, + (false, false) => 1, + }; + plane.size = l.size; + plane.slice_size = l.slice_size; + plane.offset = p.offset; + plane.alignment = l.alignment; + plane.element_bytes = l.desc.element_bytes; + plane.standard_mips = l.first_tail_mip; + plane.tail_mips = c.mips - l.first_tail_mip; + for (i, mip) in plane.mips.iter_mut().take(l.mips.len()).enumerate() { + *mip = mip_out(&c.desc, l, i); + } + } + S_OK +} + +/// The plane, its mip and array slice for a subresource index, and the +/// tiled bytes and the linear bytes the copy touches. +struct CopyArgs<'a> { + layout: &'a Layout, + mip: u32, + slice: u32, + tiled: usize, + linear: usize, +} + +fn copy_args( + c: &Computer, + plane: u32, + subresource: u32, + row: u32, + depth: u32, +) -> Option> { + let p = c.texture.planes.get(plane as usize)?; + let l = &p.layout; + let (mip, slice) = (subresource % c.mips, subresource / c.mips); + let m = l.mips.get(mip as usize)?; + let bytes = m.width as usize * l.desc.element_bytes as usize; + let depths = l.subresource_depth(mip) as usize; + let linear = (depths - 1) * depth as usize + (m.height as usize - 1) * row as usize + bytes; + Some(CopyArgs { + layout: l, + mip, + slice, + tiled: (p.offset + l.size) as usize, + linear, + }) +} + +fn result(r: Result<(), Error>) -> HRESULT { + match r { + Ok(()) => S_OK, + Err(Error::Unsupported) => E_NOTIMPL, + Err(_) => E_INVALIDARG, + } +} + +/// `(tiled base, plane, subresource, linear, row pitch, depth pitch)`. +extern "system" fn copy_into( + this: This, + tiled: *mut u8, + plane: u32, + subresource: u32, + linear: *const u8, + row: u32, + depth: u32, +) -> HRESULT { + let c = computer(this); + let Some(a) = copy_args(c, plane, subresource, row, depth) else { + return E_INVALIDARG; + }; + if tiled.is_null() || linear.is_null() { + return E_INVALIDARG; + } + let offset = c.texture.planes[plane as usize].offset as usize; + // SAFETY: the title's memory holds the whole texture and its rows. + let (tiled, linear) = unsafe { + ( + std::slice::from_raw_parts_mut(tiled.add(offset), a.tiled - offset), + std::slice::from_raw_parts(linear, a.linear), + ) + }; + let r = a + .layout + .tile(tiled, a.mip, a.slice, linear, row as usize, depth as usize); + if r.is_err() { + tracing::warn!(?r, desc = ?c.desc, subresource, "copy into a texture failed"); + } + result(r) +} + +/// `(linear, plane, subresource, sample, tiled base, row pitch, depth +/// pitch)`. +#[allow(clippy::too_many_arguments)] +extern "system" fn copy_from( + this: This, + linear: *mut u8, + plane: u32, + subresource: u32, + _sample: u32, + tiled: *const u8, + row: u32, + depth: u32, +) -> HRESULT { + let c = computer(this); + let Some(a) = copy_args(c, plane, subresource, row, depth) else { + return E_INVALIDARG; + }; + if tiled.is_null() || linear.is_null() { + return E_INVALIDARG; + } + let offset = c.texture.planes[plane as usize].offset as usize; + // SAFETY: the title's memory holds the whole texture and its rows. + let (tiled, linear) = unsafe { + ( + std::slice::from_raw_parts(tiled.add(offset), a.tiled - offset), + std::slice::from_raw_parts_mut(linear, a.linear), + ) + }; + let r = a + .layout + .detile(tiled, a.mip, a.slice, linear, row as usize, depth as usize); + if r.is_err() { + tracing::warn!(?r, desc = ?c.desc, subresource, "copy out of a texture failed"); + } + result(r) +} + +#[repr(C)] +pub struct PackedMips { + pub standard: u8, + pub packed: u8, + pub tiles: u32, + pub start: u32, +} + +#[repr(C)] +pub struct SubresourceTiling { + pub width: u32, + pub height: u16, + pub depth: u16, + pub start: u32, +} + +const TILE: u64 = 64 << 10; + +/// `(total tiles, packed mips, tile shape in texels, in: room / out: +/// count, first, subresource tilings)`, in 64 KiB tiles of plane 0, for 2D +/// 64 KiB modes only (others fail, as on the console). The mip tail is the +/// packed part, tile 0 of each slice; tilings list the standard mips of +/// every slice in turn. With a tail the console's library lists two slices +/// at most and zeroes all but the first; so do we (the title reads slice 0 +/// only). +extern "system" fn tiling( + this: This, + tiles: *mut u32, + packed: *mut PackedMips, + shape: *mut [u32; 3], + count: *mut u32, + first: u32, + out: *mut SubresourceTiling, +) -> HRESULT { + let c = computer(this); + let l = &c.texture.planes[0].layout; + if l.alignment != TILE { + return E_FAIL; + } + if l.thick { + return E_NOTIMPL; + } + let standard = l.first_tail_mip; + let tail = standard < c.mips; + let tail_tiles = match standard { + 0 => l.slice_size / TILE, + s if s < c.mips => l.mips[s as usize - 1].offset / TILE, + _ => 0, + }; + let block = l.desc.block; + // SAFETY: each output is null or room for its value; `out` has room + // for `*count` entries. + unsafe { + if let Some(t) = tiles.as_mut() { + *t = (l.size / TILE) as u32; + } + if let Some(p) = packed.as_mut() { + *p = PackedMips { + standard: standard as u8, + packed: (c.mips - standard) as u8, + tiles: tail_tiles as u32, + start: 0, + }; + } + if let Some(s) = shape.as_mut() { + *s = [l.block[0] * block, l.block[1] * block, l.block[2]]; + } + if let Some(n) = count.as_mut() { + let slices = if tail { l.slices.min(2) } else { l.slices }; + let wanted = (standard * slices).saturating_sub(first).min(*n); + for i in 0..wanted { + let (slice, mip) = ((first + i) / standard, (first + i) % standard); + let m = &l.mips[mip as usize]; + let entry = if tail && slice > 0 { + SubresourceTiling { + width: 0, + height: 0, + depth: 0, + start: 0, + } + } else { + SubresourceTiling { + width: m.pitch / l.block[0], + height: (m.rows / l.block[1]) as u16, + depth: 1, + start: ((u64::from(slice) * l.slice_size + m.offset) / TILE) as u32, + } + }; + out.add(i as usize).write(entry); + } + *n = wanted; + } + } + S_OK +} + +/// Slot 0x30 `(plane, mip, x, y, z or slice, sample, bit position)`: an +/// element's byte offset from the texture's start. The title reads +/// texels of a 128x4 `4KB_S` texture on the CPU through it (title+0x5151c90); +/// an error returned as an offset made it read wild memory. 0 if outside. +extern "system" fn element_offset( + this: This, + plane: u32, + mip: u32, + x: u64, + y: u32, + z: u32, + _sample: u32, + bit: *mut u32, +) -> u64 { + if !bit.is_null() { + // SAFETY: the caller passes room for the bit position or null. + unsafe { bit.write(0) }; + } + let Some(p) = computer(this).texture.planes.get(plane as usize) else { + return 0; + }; + let x = u32::try_from(x).unwrap_or(u32::MAX); + match p.layout.offset(mip, x, y, z) { + Ok(at) => p.offset + at, + Err(e) => { + tracing::warn!(?e, mip, x, y, z, "texel outside its texture"); + 0 + } + } +} + +/// Slots the title does not call: size, alignment, offsets, coordinates, +/// view descriptor, tiled-resource query. +extern "system" fn unused(this: This) -> HRESULT { + tracing::warn!(desc = ?computer(this).desc, "unimplemented texture computer method"); + E_NOTIMPL +} + +#[repr(C)] +struct Vtable([*const (); 13]); +// SAFETY: function addresses only. +unsafe impl Sync for Vtable {} + +static VTABLE: Vtable = Vtable([ + add_ref as *const (), // 0x00 + release as *const (), // 0x08 + layout as *const (), // 0x10 + unused as *const (), // 0x18 size + unused as *const (), // 0x20 alignment + unused as *const (), // 0x28 mip offset + element_offset as *const (), // 0x30 + unused as *const (), // 0x38 element coordinate + copy_into as *const (), // 0x40 + copy_from as *const (), // 0x48 + tiling as *const (), // 0x50 + unused as *const (), // 0x58 view descriptor + unused as *const (), // 0x60 tiled resource? +]); + +pub(crate) fn module() -> HleModule { + HleModule { + name: "xg", + dlls: &["xg_xs.dll"], + exports: vec![ + hle_export!(XGCreateTextureComputer), + hle_export!(XGSuggestSwizzleMode), + ], + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn desc(width: u64, height: u32, mips: u16, format: u32, layout: u32) -> ResourceDesc { + ResourceDesc { + dimension: 3, + alignment: 0, + width, + height, + depth_or_array: 1, + mips, + format, + samples: 1, + quality: 0, + layout, + flags: 0, + } + } + + /// Method `index` of a computer, as the title calls it. + fn slot(c: This, index: usize) -> T { + // SAFETY: the computer is live; T is the slot's function type. + unsafe { std::mem::transmute_copy(&(*c).vtable.0[index]) } + } + + fn create(d: &ResourceDesc) -> This { + let mut c = std::ptr::null_mut(); + assert_eq!(XGCreateTextureComputer(d, &mut c), S_OK); + c + } + + /// Element offsets: linear rows of 1 KiB (128 elements), 0 outside. + #[test] + fn element_offsets_follow_the_layout() { + type Offset = extern "system" fn(This, u32, u32, u64, u32, u32, u32, *mut u32) -> u64; + let c = create(&desc(128, 4, 1, 11, 0x100)); + let offset: Offset = slot(c, 6); + let mut bit = 7; + assert_eq!(offset(c, 0, 0, 3, 1, 0, 0, &mut bit), (128 + 3) * 8); + assert_eq!(bit, 0); + assert_eq!(offset(c, 0, 0, 128, 0, 0, 0, std::ptr::null_mut()), 0); + slot:: u32>(c, 1)(c); + } + + #[test] + fn suggestions_follow_the_use() { + let mut out = 0; + let mut d = desc(256, 256, 1, 98, 0); + assert_eq!(XGSuggestSwizzleMode(&d, 0, &mut out), S_OK); + assert_eq!(out, 0x105); + d.flags = ALLOW_RENDER_TARGET; + XGSuggestSwizzleMode(&d, 0, &mut out); + assert_eq!(out, 0x11b); + d.flags = ALLOW_DEPTH_STENCIL; + XGSuggestSwizzleMode(&d, 0, &mut out); + assert_eq!(out, 0x118); + } + + /// The title's calls: layout, then a copy in and out of each mip. + #[test] + fn layout_and_copies_through_the_object() { + // 256x256 BC7, full chain, 64 KiB display mode. + let c = create(&desc(256, 256, 0, 98, 0x10a)); + // SAFETY: plain data, filled by the call. + let mut l: Box = Box::new(unsafe { std::mem::zeroed() }); + let get: extern "system" fn(This, *mut LayoutOut) -> HRESULT = slot(c, 2); + assert_eq!(get(c, &mut *l), S_OK); + assert_eq!( + (l.size, l.alignment, l.mips, l.planes), + (131072, 65536, 9, 1) + ); + let p = &l.plane[0]; + assert_eq!((p.standard_mips, p.tail_mips, p.element_bytes), (1, 8, 16)); + assert_eq!((p.mips[0].offset, p.mips[0].pitch_bytes), (65536, 1024)); + assert_eq!((p.mips[1].offset, p.mips[1].in_tail), (32768, 1)); + + type Into = extern "system" fn(This, *mut u8, u32, u32, *const u8, u32, u32) -> HRESULT; + type From = + extern "system" fn(This, *mut u8, u32, u32, u32, *const u8, u32, u32) -> HRESULT; + let (into, from): (Into, From) = (slot(c, 8), slot(c, 9)); + let mut tiled = vec![0u8; l.size as usize]; + for mip in 0..9u32 { + let m = &p.mips[mip as usize]; + let row = m.elements[0] * 16; + let rows: Vec = (0..row * m.elements[1]).map(|i| (i ^ mip) as u8).collect(); + assert_eq!( + into(c, tiled.as_mut_ptr(), 0, mip, rows.as_ptr(), row, 0), + S_OK + ); + let mut back = vec![0u8; rows.len()]; + assert_eq!( + from(c, back.as_mut_ptr(), 0, mip, 0, tiled.as_ptr(), row, 0), + S_OK + ); + assert_eq!(back, rows, "mip {mip}"); + } + // 0x50: one tile for the tail, one for mip 0. + type Tiling = extern "system" fn( + This, + *mut u32, + *mut PackedMips, + *mut [u32; 3], + *mut u32, + u32, + *mut SubresourceTiling, + ) -> HRESULT; + let tiling: Tiling = slot(c, 10); + let (mut tiles, mut shape, mut n) = (0, [0; 3], 4); + let mut packed = PackedMips { + standard: 0, + packed: 0, + tiles: 0, + start: 0, + }; + let mut subs: Vec = (0..4) + .map(|_| SubresourceTiling { + width: 0, + height: 0, + depth: 0, + start: 0, + }) + .collect(); + assert_eq!( + tiling( + c, + &mut tiles, + &mut packed, + &mut shape, + &mut n, + 0, + subs.as_mut_ptr() + ), + S_OK + ); + assert_eq!( + (tiles, packed.standard, packed.packed, packed.tiles), + (2, 1, 8, 1) + ); + assert_eq!((shape, n, subs[0].start), ([256, 256, 1], 1, 1)); + assert_eq!(release(c), 0); + + // 4 KiB modes have no 64 KiB tiling. + let null = std::ptr::null_mut::(); + let c = create(&desc(256, 256, 0, 98, 0x105)); + assert_eq!( + tiling( + c, + &mut tiles, + null.cast(), + null.cast(), + null.cast(), + 0, + null.cast() + ), + E_FAIL + ); + assert_eq!(release(c), 0); + } + + #[test] + fn bad_descriptions_fail() { + let mut c = std::ptr::null_mut(); + let bad = desc(256, 256, 1, 0, 0x10a); + assert_eq!(XGCreateTextureComputer(&bad, &mut c), E_INVALIDARG); + let bad = desc(256, 256, 1, 28, 0x103); + assert_eq!(XGCreateTextureComputer(&bad, &mut c), E_INVALIDARG); + assert!(module().exports.len() == 2); + } +} diff --git a/crates/leonida-hle/src/modules/xgame.rs b/crates/leonida-hle/src/modules/xgame.rs new file mode 100644 index 000000000..3a5d3a2aa --- /dev/null +++ b/crates/leonida-hle/src/modules/xgame.rs @@ -0,0 +1,241 @@ +//! The title's own id (from its manifest), which runtime areas exist, and +//! game invites and events. Offline no invite arrives and events go +//! nowhere. +#![allow(clippy::not_unsafe_ptr_arg_deref)] + +use std::ffi::{CStr, c_char, c_void}; + +use super::xgameruntime::{ + Guid, HRESULT, Interface, Methods, Object, S_OK, add_ref, missing, put, text, token, +}; +use crate::runtime; + +/// Title id and launching another title. +pub const TITLE_PROVIDER: Guid = Guid::new( + 0x973a_344e, + 0x24bf, + 0x4d0f, + [0x84, 0x57, 0x56, 0xc5, 0x34, 0x89, 0x2b, 0x29], +); +/// As Minecraft (2022) asks for it. +pub const TITLE_IID: Guid = Guid::new( + 0x2549_f142, + 0x6419, + 0x4a06, + [0x97, 0xb5, 0x93, 0x1a, 0xab, 0x7c, 0x2f, 0x34], +); +/// Feature checks; the interface id is the provider's, as for the next two. +pub const FEATURES: Guid = Guid::new( + 0x8836_fe87, + 0xedb9, + 0x4fe3, + [0x8d, 0xad, 0x05, 0xf0, 0xd2, 0xcd, 0x5b, 0x40], +); +pub const INVITES: Guid = Guid::new( + 0x0651_aae2, + 0x4012, + 0x4077, + [0xbf, 0x84, 0x8b, 0x90, 0x97, 0x09, 0x0e, 0x2c], +); +pub const EVENTS: Guid = Guid::new( + 0xbbfb_dcc7, + 0xbfe7, + 0x409b, + [0xa5, 0xca, 0xed, 0xf0, 0x54, 0x96, 0x0b, 0x4d], +); + +pub static TITLE_OBJECT: Object = Object::new("title", &TITLE_VTABLE); +pub static FEATURES_OBJECT: Object = Object::new("features", &FEATURES_VTABLE); +pub static INVITES_OBJECT: Object = Object::new("invites", &INVITES_VTABLE); +pub static EVENTS_OBJECT: Object = Object::new("events", &EVENTS_VTABLE); + +pub const INTERFACES: &[Interface] = &[ + (TITLE_PROVIDER, TITLE_IID, &TITLE_OBJECT), + (FEATURES, FEATURES, &FEATURES_OBJECT), + (INVITES, INVITES, &INVITES_OBJECT), + (EVENTS, EVENTS, &EVENTS_OBJECT), +]; + +type This = *const Object; + +extern "system" fn title_id(_: This, out: *mut u32) -> HRESULT { + put(out, runtime::title().id) +} + +/// As documented: the title ends (suspended first, as on any end) and the +/// game starts again in a new process; this never returns. +/// The title relaunches itself (its own path from `GetModuleFileNameA`) with +/// arguments from its configuration. The new `leonida run` gets the same +/// options, the new executable, and the title's arguments after `--` +/// (the title reads the whole command line). +extern "system" fn launch_new_game( + _: This, + exe: *const c_char, + args: *const c_char, + _user: *const c_void, +) { + let (exe, args) = (text(exe).unwrap_or_default(), text(args).unwrap_or_default()); + tracing::info!(exe, args, "XLaunchNewGame"); + let current = runtime::main_image() + .and_then(runtime::image_path) + .unwrap_or_default(); + let ours: Vec<_> = std::env::args_os().skip(1).collect(); + let command = relaunch_args(ours, current.as_os_str(), &exe, &args); + super::lifecycle::end_title( + "XLaunchNewGame", + Box::new(move || super::lifecycle::relaunch(command)), + ); + loop { + std::thread::park(); + } +} + +/// Our own arguments for the relaunch: the title's executable replaced by +/// `exe`, earlier title arguments dropped, `args` after `--`. +fn relaunch_args( + ours: Vec, + current: &std::ffi::OsStr, + exe: &str, + args: &str, +) -> Vec { + let mut out: Vec<_> = ours.into_iter().take_while(|a| a != "--").collect(); + if !exe.is_empty() + && let Some(slot) = out.iter_mut().find(|a| a.as_os_str() == current) + { + *slot = exe.into(); + } + if !args.trim().is_empty() { + out.push("--".into()); + out.extend(args.split_whitespace().map(Into::into)); + } + out +} + +/// Runtime areas by number, in the public feature list's order, that we +/// serve: accessibility (0), app capture (1), async calls and providers +/// (2, 3), display (4), game (5), invites (6), game saves (7), game UI (8), +/// launcher (9), networking (10), packages (11), persistent local storage +/// (12), speech synthesis (13), store (14), system (15), task queues (16), +/// users (18), error reports (19), game events (20). Not threads (17) or +/// game streaming (21). +const AVAILABLE: [u32; 20] = [ + 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 18, 19, 20, +]; + +extern "system" fn is_feature_available(_: This, feature: u32) -> bool { + AVAILABLE.contains(&feature) +} + +/// Nothing raises these events offline, so the callback never runs. +extern "system" fn register( + _: This, + _queue: *const c_void, + _context: *mut c_void, + _callback: *const c_void, + out: *mut u64, +) -> HRESULT { + put(out, token()) +} +extern "system" fn unregister(_: This, _token: u64, _wait: bool) -> bool { + true +} + +/// Accepted and dropped; the name goes to the debug log. +extern "system" fn write_event( + _: This, + _user: *const c_void, + _service_config: *const c_char, + _session: *const c_char, + name: *const c_char, + _dimensions: *const c_char, + _measurements: *const c_char, +) -> HRESULT { + if !name.is_null() { + // SAFETY: a non-null name is a NUL-terminated string. + let name = unsafe { CStr::from_ptr(name) }.to_string_lossy(); + tracing::debug!(%name, "game event dropped"); + } + S_OK +} + +static TITLE_VTABLE: Methods<5> = Methods([ + missing::<0> as *const (), + add_ref as *const (), + add_ref as *const (), + title_id as *const (), // 0x18 + launch_new_game as *const (), // 0x20 +]); + +static FEATURES_VTABLE: Methods<4> = Methods([ + missing::<0> as *const (), + add_ref as *const (), + add_ref as *const (), + is_feature_available as *const (), // 0x18 +]); + +static INVITES_VTABLE: Methods<5> = Methods([ + missing::<0> as *const (), + add_ref as *const (), + add_ref as *const (), + register as *const (), // 0x18 + unregister as *const (), // 0x20 +]); + +static EVENTS_VTABLE: Methods<4> = Methods([ + missing::<0> as *const (), + add_ref as *const (), + add_ref as *const (), + write_event as *const (), // 0x18 +]); + +#[cfg(test)] +mod tests { + use super::*; + use crate::modules::xgameruntime::method; + + #[test] + fn a_relaunch_keeps_our_options() { + let ours: Vec = + ["run", "G:/game.exe", "--execute", "--console", "series-s", "--", "-old"] + .map(Into::into) + .into(); + let current = std::ffi::OsStr::new("G:/game.exe"); + let again = relaunch_args(ours.clone(), current, "G:/game.exe", " -config=x -y "); + let expected = ["run", "G:/game.exe", "--execute", "--console", "series-s", "--"]; + assert_eq!(again[..6], expected.map(std::ffi::OsString::from)); + assert_eq!(again[6..], ["-config=x", "-y"].map(std::ffi::OsString::from)); + let other = relaunch_args(ours, current, "G:/other.exe", ""); + assert_eq!(other.len(), 5); + assert_eq!(other[1], "G:/other.exe"); + } + + #[test] + fn served_areas_are_available_others_not() { + type Check = extern "system" fn(This, u32) -> bool; + let check = method::(&FEATURES_OBJECT, 0x18); + assert!(check(&FEATURES_OBJECT, 18), "users"); + assert!(!check(&FEATURES_OBJECT, 21), "game streaming"); + + type Register = extern "system" fn( + This, + *const c_void, + *mut c_void, + *const c_void, + *mut u64, + ) -> HRESULT; + type Unregister = extern "system" fn(This, u64, bool) -> bool; + let null = std::ptr::null(); + let mut token = 0; + let register = method::(&INVITES_OBJECT, 0x18); + assert_eq!( + register(&INVITES_OBJECT, null, null as _, null, &mut token), + S_OK + ); + assert_ne!(token, 0); + assert!(method::(&INVITES_OBJECT, 0x20)( + &INVITES_OBJECT, + token, + true + )); + } +} diff --git a/crates/leonida-hle/src/modules/xgameruntime.rs b/crates/leonida-hle/src/modules/xgameruntime.rs new file mode 100644 index 000000000..b3f5963fc --- /dev/null +++ b/crates/leonida-hle/src/modules/xgameruntime.rs @@ -0,0 +1,344 @@ +//! `xgameruntime.dll`: the console game runtime (XGame*, XUser*, XTaskQueue*...). +//! +//! Titles rarely import it. A stub linked into the title loads the DLL with +//! `LoadLibraryExA` (answered with a pseudo handle, see `kernel`), looks up +//! the `*ApiImpl` functions and `XErrorReport` with `GetProcAddress`, and +//! initialises. Each runtime API call then asks `QueryApiImpl` for a COM-style +//! object of its area (provider and interface GUIDs), calls one method and +//! releases it. Until an area is implemented its query fails, and the call +//! returns that error without touching the object. An area's interface id +//! changes when its method table does, so each object answers only the ids +//! whose slots we know. Implemented, as an offline retail console with one +//! signed-in user: task queues and async blocks (`xasync`), the user +//! (`xuser`), system information (`xsystem`), title id, feature checks, +//! invites and events (`xgame`), persistent local storage (`storage`), game +//! saves (`xgamesave`), networking (`xnetworking`), the package +//! (`xpackage`), the store (`xstore`), system dialogs (`xgameui`), speech +//! (`speech`), HDR, URIs, display deferrals and screenshots (`display`). +#![allow(non_snake_case)] +// Title code calls these through its import table, passing pointers the real +// API would trust. +#![allow(clippy::not_unsafe_ptr_arg_deref)] + +use std::ffi::{CStr, c_char, c_void}; +use std::sync::Mutex; +use std::sync::atomic::{AtomicU64, Ordering}; + +use super::{ + display, speech, storage, xasync, xgame, xgamesave, xgameui, xnetworking, xpackage, xstore, + xsystem, xuser, +}; +use crate::{HleModule, hle_export}; + +pub type HRESULT = i32; +pub const S_OK: HRESULT = 0; +/// `HRESULT_FROM_WIN32(ERROR_NOT_SUPPORTED)`. +pub const NOT_SUPPORTED: HRESULT = 0x8007_0032_u32 as i32; + +#[repr(C)] +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct Guid { + pub data1: u32, + pub data2: u16, + pub data3: u16, + pub data4: [u8; 8], +} + +impl Guid { + pub const fn new(data1: u32, data2: u16, data3: u16, data4: [u8; 8]) -> Guid { + Guid { + data1, + data2, + data3, + data4, + } + } +} + +impl std::fmt::Display for Guid { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + let d = self.data4; + write!( + f, + "{:08x}-{:04x}-{:04x}-{:02x}{:02x}-{:02x}{:02x}{:02x}{:02x}{:02x}{:02x}", + self.data1, self.data2, self.data3, d[0], d[1], d[2], d[3], d[4], d[5], d[6], d[7] + ) + } +} + +/// A runtime object as title code calls it: its first word points at the +/// method table. Ours are static, so reference counting is a no-op. +#[repr(C)] +pub struct Object { + vtable: *const *const (), + /// Named in the log when a title calls a method we lack. + area: &'static str, +} + +// SAFETY: the table is a static array of function addresses. +unsafe impl Sync for Object {} + +impl Object { + pub const fn new(area: &'static str, methods: &'static Methods) -> Object { + Object { + vtable: methods.0.as_ptr(), + area, + } + } +} + +/// An object's method table, by slot (`QueryInterface`, `AddRef`, +/// `Release`, then the area's methods from offset 0x18). +pub struct Methods(pub [*const (); N]); + +// SAFETY: function addresses only. +unsafe impl Sync for Methods {} + +/// A (provider, interface id) pair a title may ask for, and our object. +pub type Interface = (Guid, Guid, &'static Object); + +const AREAS: &[&[Interface]] = &[ + xasync::INTERFACES, + xuser::INTERFACES, + xsystem::INTERFACES, + xgame::INTERFACES, + storage::INTERFACES, + xnetworking::INTERFACES, + xpackage::INTERFACES, + display::INTERFACES, + xgamesave::INTERFACES, + xstore::INTERFACES, + xgameui::INTERFACES, + speech::INTERFACES, +]; + +/// `AddRef` and `Release`. +pub extern "system" fn add_ref(_: *const Object) -> u32 { + 1 +} + +/// A slot nobody has needed yet; logged with its area. Wrong for a slot +/// that returns `bool` or a value. +pub extern "system" fn missing(this: *const Object) -> HRESULT { + // SAFETY: title code calls methods on objects we handed out. + let area = unsafe { (*this).area }; + tracing::warn!( + area, + slot = format_args!("{:#x}", SLOT * 8), + "runtime method not implemented" + ); + xasync::E_NOTIMPL +} + +/// Writes `value` through `out` if it is non-null. +pub fn put(out: *mut T, value: T) -> HRESULT { + if out.is_null() { + return xasync::E_INVALIDARG; + } + // SAFETY: checked non-null; the title passes room for a `T`. + unsafe { out.write(value) }; + S_OK +} + +/// Copies `text` and a NUL into the title's `size`-byte buffer and reports +/// the bytes used, as the runtime's string getters do. +pub fn put_string(text: &str, size: usize, buffer: *mut u8, used: *mut usize) -> HRESULT { + let len = text.len() + 1; + if buffer.is_null() || size < len { + return xasync::E_NOT_SUFFICIENT_BUFFER; + } + // SAFETY: the buffer holds `size` bytes, checked above. + unsafe { + buffer.copy_from_nonoverlapping(text.as_ptr(), text.len()); + buffer.add(text.len()).write(0); + } + if !used.is_null() { + // SAFETY: checked non-null. + unsafe { used.write(len) }; + } + S_OK +} + +/// The title's NUL-terminated string, if any. +pub fn text(s: *const c_char) -> Option { + // SAFETY: the title passes a NUL-terminated string or null. + (!s.is_null()).then(|| unsafe { CStr::from_ptr(s) }.to_string_lossy().into_owned()) +} + +/// A new registration token for callbacks we never call (events nobody +/// raises offline). +pub fn token() -> u64 { + static NEXT: AtomicU64 = AtomicU64::new(1); + NEXT.fetch_add(1, Ordering::Relaxed) +} + +/// Calls method `slot` (byte offset) of `object` as title code would. +#[cfg(test)] +pub(crate) fn method(object: &Object, slot: usize) -> F { + // SAFETY: the caller names the slot's signature; tables cover the slots + // tests use. + unsafe { std::mem::transmute_copy(&*object.vtable.add(slot / 8)) } +} + +pub extern "system" fn XGameRuntimeInitialize() -> HRESULT { + tracing::info!("XGameRuntimeInitialize"); + S_OK +} + +pub extern "system" fn XGameRuntimeUninitialize() { + tracing::info!("XGameRuntimeUninitialize"); +} + +/// The arguments identify the title's build of the stub; not checked. +pub extern "system" fn InitializeApiImpl(version: u64, build: u64) -> HRESULT { + tracing::info!(version, build, "InitializeApiImpl"); + S_OK +} + +pub extern "system" fn InitializeApiImplEx(version: u64, build: u64, flags: u64) -> HRESULT { + tracing::info!(version, build, flags, "InitializeApiImplEx"); + S_OK +} + +/// The stub prefers this one when present. It passes the same three values +/// and a pointer to the title's initialisation options, null unless the +/// title initialises with options (the title does not). +pub extern "system" fn InitializeApiImplEx2( + version: u64, + build: u64, + flags: u64, + options: *const c_void, +) -> HRESULT { + tracing::info!(version, build, flags, ?options, "InitializeApiImplEx2"); + S_OK +} + +pub extern "system" fn UninitializeApiImpl() { + tracing::info!("UninitializeApiImpl"); +} + +/// The object for an implemented (provider, interface id); others fail, +/// each pair logged once. +pub extern "system" fn QueryApiImpl( + provider: *const Guid, + iid: *const Guid, + out: *mut *mut c_void, +) -> HRESULT { + static QUERIED: Mutex> = Mutex::new(Vec::new()); + // SAFETY: the title passes pointers to GUIDs (null is tolerated). + let (Some(&provider), Some(&iid)) = (unsafe { provider.as_ref() }, unsafe { iid.as_ref() }) + else { + return NOT_SUPPORTED; + }; + #[cfg(feature = "diagnostics")] + if tracing::enabled!(tracing::Level::DEBUG) { + // Each runtime call site once: which title code uses which area, when. + static CALLS: Mutex> = Mutex::new(Vec::new()); + let from = super::kernel::callers(); + let mut calls = CALLS.lock().unwrap_or_else(|e| e.into_inner()); + if !calls.contains(&from) { + tracing::debug!(%provider, %iid, %from, "runtime call"); + calls.push(from); + } + } + let found = AREAS + .iter() + .flat_map(|area| area.iter()) + .find(|(p, i, _)| (*p, *i) == (provider, iid)); + if let Some(&(_, _, object)) = found + && !out.is_null() + { + // SAFETY: checked non-null; the title passes room for a pointer. + unsafe { out.write((object as *const Object).cast_mut().cast()) }; + return S_OK; + } + let mut queried = QUERIED.lock().unwrap_or_else(|e| e.into_inner()); + if !queried.contains(&(provider, iid)) { + queried.push((provider, iid)); + tracing::warn!(%provider, %iid, "runtime API area not implemented"); + } + NOT_SUPPORTED +} + +pub extern "system" fn XErrorReport(hr: HRESULT, message: *const c_char) { + let message = if message.is_null() { + "".into() + } else { + // SAFETY: a non-null message is a NUL-terminated string. + unsafe { CStr::from_ptr(message) }.to_string_lossy() + }; + tracing::warn!(hr = format_args!("{:#010x}", hr as u32), %message, "XErrorReport"); +} + +pub(crate) fn module() -> HleModule { + HleModule { + name: "xgameruntime", + dlls: &["xgameruntime.dll"], + exports: vec![ + hle_export!(XGameRuntimeInitialize), + hle_export!(XGameRuntimeUninitialize), + hle_export!(InitializeApiImpl), + hle_export!(InitializeApiImplEx), + hle_export!(InitializeApiImplEx2), + hle_export!(UninitializeApiImpl), + hle_export!(QueryApiImpl), + hle_export!(XErrorReport), + ], + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::modules::kernel::{FreeLibrary, GetProcAddress, LoadLibraryExA}; + + #[test] + fn title_stub_loads_the_runtime_dynamically() { + let load = |name: &CStr| LoadLibraryExA(name.as_ptr().cast(), std::ptr::null_mut(), 0x800); + let runtime = load(c"xgameruntime.dll"); + assert!(!runtime.is_null()); + let proc = |name: &CStr| GetProcAddress(runtime, name.as_ptr().cast()); + for name in [ + c"InitializeApiImpl", + c"InitializeApiImplEx", + c"InitializeApiImplEx2", + c"QueryApiImpl", + c"UninitializeApiImpl", + c"XErrorReport", + ] { + assert!(!proc(name).is_null(), "{name:?}"); + } + assert!(proc(c"NotAnExport").is_null()); + let ordinal = std::ptr::without_provenance::(1); + assert!(GetProcAddress(runtime, ordinal).is_null()); + + type Init = extern "system" fn(u64, u64, u64) -> HRESULT; + type Query = extern "system" fn(*const Guid, *const Guid, *mut *mut c_void) -> HRESULT; + // SAFETY: the addresses are our functions with these signatures. + let (init, query) = unsafe { + ( + std::mem::transmute::<*mut c_void, Init>(proc(c"InitializeApiImplEx")), + std::mem::transmute::<*mut c_void, Query>(proc(c"QueryApiImpl")), + ) + }; + assert_eq!(init(1, 2, 2), S_OK); + let guid = Guid { + data1: 1, + data2: 2, + data3: 3, + data4: [4; 8], + }; + let untouched = 0x1234 as *mut c_void; + let mut out = untouched; + assert!(query(&guid, &guid, &mut out) < 0); + assert_eq!(out, untouched); + assert_eq!(FreeLibrary(runtime), 1); + + #[cfg(windows)] + { + let kernel32 = load(c"kernel32.dll"); + assert!(!kernel32.is_null(), "host DLLs still load from the host"); + assert!(!GetProcAddress(kernel32, c"GetTickCount".as_ptr().cast()).is_null()); + } + } +} diff --git a/crates/leonida-hle/src/modules/xgamesave.rs b/crates/leonida-hle/src/modules/xgamesave.rs new file mode 100644 index 000000000..99275a00c --- /dev/null +++ b/crates/leonida-hle/src/modules/xgamesave.rs @@ -0,0 +1,1355 @@ +//! XGameSave: the user's game saves, kept on the host under the title's +//! data directory, next to persistent local storage (`runtime::Title:: +//! saves`), never in the cache. A provider is a folder per user and +//! service configuration, a container a folder in it. +//! +//! An update is all or nothing, as documented: each one writes a complete +//! new version of the container (`v.new/`, unchanged blobs hard-linked +//! from the previous version), flushed to disk, and one directory rename +//! commits it (`v`); the highest committed version is the container. +//! A crash leaves the old version or the new one, never a mix; leftovers +//! are removed on sight. Deleting a container renames it away first. +//! +//! Names are exact: a version's `manifest` holds the container's name, its +//! display name and the blob names (blob `i` is the file `i`), so case, +//! characters the host forbids, reserved device names and length never +//! reach a file name. A container's folder is its name made safe (and +//! shortened) plus a hash of the exact name, so names differing only in +//! case get different folders. Offline there is no cloud copy, so nothing +//! ever needs a sync. +#![allow(clippy::not_unsafe_ptr_arg_deref)] + +use std::ffi::{CString, c_char, c_void}; +use std::io::Write as _; +use std::path::{Path, PathBuf}; +use std::sync::Mutex; + +use super::xasync::{self, AsyncBlock, E_INVALIDARG}; +use super::xgameruntime::{ + Guid, HRESULT, Interface, Methods, Object, S_OK, add_ref, missing, put, text, +}; +use super::{storage, xuser}; +use crate::runtime; + +pub const PROVIDER: Guid = Guid::new( + 0x704c_3f58, + 0xe629, + 0x4cc2, + [0xb1, 0x97, 0x30, 0x51, 0x1b, 0x99, 0x6f, 0xe2], +); +/// As the title (2026) asks for it; every slot it calls takes +/// the public API's arguments in the same order as under the provider's +/// own id (older titles). +pub const IID_2026: Guid = Guid::new( + 0x1bff_f3af, + 0xf14a, + 0x40a3, + [0x8e, 0x35, 0x9a, 0xda, 0x90, 0x65, 0x93, 0xf9], +); + +pub static OBJECT: Object = Object::new("game save", &VTABLE); +pub const INTERFACES: &[Interface] = + &[(PROVIDER, PROVIDER, &OBJECT), (PROVIDER, IID_2026, &OBJECT)]; + +// The public API's error codes. +pub const INVALID_CONTAINER_NAME: HRESULT = 0x8083_0001_u32 as i32; +pub const NO_ACCESS: HRESULT = 0x8083_0002_u32 as i32; +pub const OUT_OF_LOCAL_STORAGE: HRESULT = 0x8083_0003_u32 as i32; +pub const UPDATE_TOO_BIG: HRESULT = 0x8083_0005_u32 as i32; +pub const QUOTA_EXCEEDED: HRESULT = 0x8083_0006_u32 as i32; +pub const BUFFER_TOO_SMALL: HRESULT = 0x8083_0007_u32 as i32; +pub const BLOB_NOT_FOUND: HRESULT = 0x8083_0008_u32 as i32; + +/// Per user and title, as documented. +const QUOTA: u64 = 256 << 20; +/// What one update may write in all, as documented. +const MAX_UPDATE: usize = 16 << 20; +const MANIFEST: &str = "manifest"; +/// Readable part of a container's folder name, at most. +const READABLE: usize = 100; + +/// Every save operation, so none sees another's half-made version. +static SAVES: Mutex<()> = Mutex::new(()); + +fn saves_lock() -> std::sync::MutexGuard<'static, ()> { + SAVES.lock().unwrap_or_else(|e| e.into_inner()) +} + +/// `name` as a file name: letters, digits, `-` and `_` stay, every other +/// byte becomes `%XX`. The result never contains a dot. +fn file_name(name: &str) -> String { + name.bytes() + .map(|b| match b { + b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' => (b as char).to_string(), + _ => format!("%{b:02X}"), + }) + .collect() +} + +/// The name behind a file name from [`file_name`]; `None` for other files. +fn decode(file: &str) -> Option { + if file.contains('.') { + return None; + } + let mut out = Vec::new(); + let mut bytes = file.bytes(); + while let Some(b) = bytes.next() { + if b == b'%' { + let hex = [bytes.next()?, bytes.next()?]; + out.push(u8::from_str_radix(std::str::from_utf8(&hex).ok()?, 16).ok()?); + } else { + out.push(b); + } + } + String::from_utf8(out).ok() +} + +/// The container's folder: its name made safe, cut short, then `~` and a +/// hash of the exact name (64-bit FNV-1a, stable across builds). +fn container_dir(root: &Path, name: &str) -> PathBuf { + let hash = name.bytes().fold(0xcbf2_9ce4_8422_2325_u64, |h, b| { + (h ^ u64::from(b)).wrapping_mul(0x100_0000_01b3) + }); + let mut readable = file_name(name); + readable.truncate(READABLE); // ASCII only + root.join(format!("{readable}~{hash:016x}")) +} + +/// Documented: the path part (up to the last `/`) letters, digits, `_` and +/// `/`; the file part letters, digits, `_`, `.` and `-`, not empty, not +/// ending in `.`, no `..`; 256 characters at most. +fn valid_container(name: &str) -> bool { + let (path, file) = name.rsplit_once('/').unwrap_or(("", name)); + name.len() <= 256 + && path + .bytes() + .all(|b| b.is_ascii_alphanumeric() || b == b'_' || b == b'/') + && !file.is_empty() + && !file.ends_with('.') + && !file.contains("..") + && file + .bytes() + .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'_' | b'.' | b'-')) +} + +/// A committed version of a container. +struct Version { + dir: PathBuf, + number: u64, + name: String, + display: String, + /// Blob names; blob `i` is the file `i`. + blobs: Vec, +} + +impl Version { + fn blob(&self, i: usize) -> PathBuf { + self.dir.join(i.to_string()) + } + + fn sizes(&self) -> Vec<(String, u64)> { + let size = |i| std::fs::metadata(self.blob(i)).map_or(0, |m| m.len()); + let blobs = self.blobs.iter().enumerate(); + blobs.map(|(i, n)| (n.clone(), size(i))).collect() + } +} + +/// The manifest: length-prefixed strings (u32 LE): container name, display +/// name, then each blob name. +fn manifest(name: &str, display: &str, blobs: &[&str]) -> Vec { + let mut out = Vec::new(); + for s in [name, display].into_iter().chain(blobs.iter().copied()) { + out.extend_from_slice(&(s.len() as u32).to_le_bytes()); + out.extend_from_slice(s.as_bytes()); + } + out +} + +fn parse_manifest(bytes: &[u8]) -> Option> { + let mut out = Vec::new(); + let mut rest = bytes; + while !rest.is_empty() { + let (len, tail) = rest.split_first_chunk::<4>()?; + let len = u32::from_le_bytes(*len) as usize; + out.push(String::from_utf8(tail.get(..len)?.to_vec()).ok()?); + rest = &tail[len..]; + } + (out.len() >= 2).then_some(out) +} + +/// The container's newest committed version, if any. Removes what a crash +/// left: unfinished versions and older ones. +fn current(dir: &Path) -> std::io::Result> { + let mut committed = Vec::new(); + for entry in std::fs::read_dir(dir)?.flatten() { + let file = entry.file_name(); + let file = file.to_string_lossy(); + if file.ends_with(".new") { + std::fs::remove_dir_all(entry.path())?; + } else if let Some(n) = file.strip_prefix('v').and_then(|n| n.parse::().ok()) { + committed.push(n); + } + } + committed.sort_unstable(); + let Some(&number) = committed.last() else { + return Ok(None); + }; + for old in &committed[..committed.len() - 1] { + std::fs::remove_dir_all(dir.join(format!("v{old}")))?; + } + let version = dir.join(format!("v{number}")); + let bad = || std::io::Error::new(std::io::ErrorKind::InvalidData, "bad save manifest"); + let mut names = parse_manifest(&std::fs::read(version.join(MANIFEST))?).ok_or_else(bad)?; + let blobs = names.split_off(2); + let [name, display] = <[String; 2]>::try_from(names).map_err(|_| bad())?; + Ok(Some(Version { + dir: version, + number, + name, + display, + blobs, + })) +} + +/// The version of container `name` in `dir`; none for a missing container +/// or another name that hashes alike. +fn current_named(dir: &Path, name: &str) -> std::io::Result> { + match current(dir) { + Ok(v) => Ok(v.filter(|v| v.name == name)), + Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None), + Err(e) => Err(e), + } +} + +/// Where a crash test stops the process (test builds only). +fn step() { + #[cfg(test)] + tests::crash_point(); +} + +/// A blob of a new version: new data, or the previous version's file. +enum Source<'a> { + Data(&'a [u8]), + Kept(PathBuf), +} + +/// Writes version `number` of the container in `dir` and commits it. +fn commit( + dir: &Path, + number: u64, + name: &str, + display: &str, + blobs: &[(&str, Source<'_>)], +) -> std::io::Result<()> { + let staged = dir.join(format!("v{number}.new")); + if staged.exists() { + std::fs::remove_dir_all(&staged)?; + } + std::fs::create_dir_all(&staged)?; + let write = |path: PathBuf, data: &[u8]| -> std::io::Result<()> { + let mut file = std::fs::File::create(path)?; + file.write_all(data)?; + file.sync_all() + }; + for (i, (_, source)) in blobs.iter().enumerate() { + let path = staged.join(i.to_string()); + match source { + Source::Data(data) => write(path, data)?, + // Files are never changed in place, so sharing one is safe. + Source::Kept(from) => std::fs::hard_link(from, &path) + .or_else(|_| std::fs::copy(from, &path).map(drop))?, + } + step(); + } + let names: Vec<&str> = blobs.iter().map(|(n, _)| *n).collect(); + write(staged.join(MANIFEST), &manifest(name, display, &names))?; + step(); + std::fs::rename(&staged, dir.join(format!("v{number}")))?; + step(); + Ok(()) +} + +/// The containers under a provider's root, by exact name; containers in +/// the old one-file-per-blob layout are converted first. +fn containers(root: &Path) -> Vec<(String, PathBuf)> { + let mut out = Vec::new(); + for entry in std::fs::read_dir(root).into_iter().flatten().flatten() { + let path = entry.path(); + let file = entry.file_name().to_string_lossy().into_owned(); + if !path.is_dir() { + continue; + } + if file.ends_with(".gone") { + let _ = std::fs::remove_dir_all(&path); + } else if file.contains('~') { + if let Ok(Some(v)) = current(&path) { + out.push((v.name, path)); + } + } else if let Some(name) = decode(&file) + && let Some(dir) = migrate(root, &name, &path) + { + out.push((name, dir)); + } + } + out.sort(); + out +} + +/// Moves a container of the old layout (blob files named by encoded name, +/// a `.display` file) into a committed version, then removes it. +fn migrate(root: &Path, name: &str, old: &Path) -> Option { + let dir = container_dir(root, name); + let done = current_named(&dir, name).ok()?.is_some(); // a crash after the commit + if !done { + let display = std::fs::read_to_string(old.join(".display")).unwrap_or_default(); + let mut blobs: Vec<(String, Vec)> = std::fs::read_dir(old) + .ok()? + .flatten() + .filter_map(|e| { + let blob = decode(e.file_name().to_str()?)?; + Some((blob, std::fs::read(e.path()).ok()?)) + }) + .collect(); + blobs.sort(); + let sources: Vec<_> = blobs + .iter() + .map(|(n, d)| (n.as_str(), Source::Data(d))) + .collect(); + commit(&dir, 1, name, &display, &sources).ok()?; + } + std::fs::remove_dir_all(old).ok()?; + tracing::info!(container = name, "game save moved to the versioned layout"); + Some(dir) +} + +fn used_bytes(root: &Path) -> u64 { + containers(root) + .iter() + .filter_map(|(name, dir)| current_named(dir, name).ok().flatten()) + .map(|v| v.sizes().iter().map(|(_, size)| size).sum::()) + .sum() +} + +struct Provider { + root: PathBuf, +} +struct Container { + name: String, + dir: PathBuf, +} +struct Update { + name: String, + dir: PathBuf, + display: Option, + /// Blob writes (`Some`) and deletions (`None`), in order. + changes: Vec<(String, Option>)>, +} + +/// A handle we gave out. +fn get<'a, T>(handle: *const T) -> Option<&'a T> { + // SAFETY: handles are boxes we created and the title has not closed. + unsafe { handle.as_ref() } +} +fn give(value: T) -> *mut T { + Box::into_raw(Box::new(value)) +} +fn take(handle: *mut T) { + if !handle.is_null() { + // SAFETY: as in `get`; closing ends the handle. + drop(unsafe { Box::from_raw(handle) }); + } +} + +impl Provider { + /// The provider for the only user and `config` (the service + /// configuration id), under `saves`. An empty id names no + /// configuration, like none: as a folder name it would be the user's + /// folder itself, where the other configurations' folders are. + fn open(saves: &Path, config: Option<&str>) -> Result { + let config = config.filter(|c| !c.is_empty()).unwrap_or("default"); + let root = saves + .join(format!("{:016X}", xuser::XUID)) + .join(file_name(config)); + std::fs::create_dir_all(&root).map_err(|_| NO_ACCESS)?; + let _saves = saves_lock(); + containers(&root); // converts old containers now + Ok(Provider { root }) + } + + fn remaining(&self) -> u64 { + let _saves = saves_lock(); + remaining(&self.root) + } + + fn container(&self, name: &str) -> Container { + Container { + name: name.to_owned(), + dir: container_dir(&self.root, name), + } + } +} + +/// Quota left under a provider's root, or less if the host disk is fuller. +fn remaining(root: &Path) -> u64 { + QUOTA + .saturating_sub(used_bytes(root)) + .min(storage::disk_free(root)) +} + +/// Why an update writing `written` bytes, `replaced` of them over blobs it +/// replaces, does not fit: past the per-user quota (`used` bytes kept), or +/// past the host disk's `free` bytes, which is not the user's quota (the +/// new version is written before the old one goes, so nothing it replaces +/// counts there). +fn no_room(written: u64, replaced: u64, used: u64, free: u64) -> Option { + if written > QUOTA.saturating_sub(used) + replaced { + Some(QUOTA_EXCEEDED) + } else if written > free { + Some(OUT_OF_LOCAL_STORAGE) + } else { + None + } +} + +fn io_error(dir: &Path, e: &std::io::Error) -> HRESULT { + tracing::warn!(dir = %dir.display(), %e, "game save"); + if e.kind() == std::io::ErrorKind::StorageFull { + OUT_OF_LOCAL_STORAGE + } else { + NO_ACCESS + } +} + +impl Update { + /// Applies the update as one new version of the container. + fn submit(&self) -> HRESULT { + let _saves = saves_lock(); + let current = match current(&self.dir) { + Ok(v) => v, + Err(e) if e.kind() == std::io::ErrorKind::NotFound => None, + Err(e) => return io_error(&self.dir, &e), + }; + if current.as_ref().is_some_and(|v| v.name != self.name) { + // Another container's name hashes alike: never mix the two. + return NO_ACCESS; + } + // The blobs after the update: name → new data or the kept file. + let mut blobs: Vec<(&str, Source<'_>)> = current + .iter() + .flat_map(|v| { + let kept = v.blobs.iter().enumerate(); + kept.map(|(i, n)| (n.as_str(), Source::Kept(v.blob(i)))) + }) + .collect(); + for (name, data) in &self.changes { + blobs.retain(|(n, _)| n != name); + if let Some(data) = data { + blobs.push((name, Source::Data(data))); + } + } + blobs.sort_by(|a, b| a.0.cmp(b.0)); + let written: usize = blobs + .iter() + .map(|(_, s)| match s { + Source::Data(d) => d.len(), + Source::Kept(_) => 0, + }) + .sum(); + if written > MAX_UPDATE { + return UPDATE_TOO_BIG; + } + let replaced: u64 = current.as_ref().map_or(0, |v| { + let sizes = v.sizes(); + let changed = sizes.iter().filter(|(n, _)| self.changes.iter().any(|(c, _)| c == n)); + changed.map(|(_, size)| size).sum() + }); + let root = self.dir.parent().unwrap_or(&self.dir); + let free = storage::disk_free(root); + if let Some(hr) = no_room(written as u64, replaced, used_bytes(root), free) { + return hr; + } + let display = self.display.as_deref(); + let display = display.or(current.as_ref().map(|v| v.display.as_str())); + let number = current.as_ref().map_or(1, |v| v.number + 1); + if let Err(e) = commit(&self.dir, number, &self.name, display.unwrap_or(""), &blobs) { + return io_error(&self.dir, &e); + } + // The old version is garbage now; a crash here leaves it for later. + if let Some(old) = ¤t { + let _ = std::fs::remove_dir_all(&old.dir); + step(); + } + S_OK + } +} + +/// Deletes a container: renamed away (one step), then removed. +fn delete(root: &Path, name: &str) -> HRESULT { + let _saves = saves_lock(); + let dir = container_dir(root, name); + match current_named(&dir, name) { + Ok(Some(_)) => {} + Ok(None) => return S_OK, + Err(e) => return io_error(&dir, &e), + } + let gone = dir.with_extension("gone"); + let _ = std::fs::remove_dir_all(&gone); + step(); + if let Err(e) = std::fs::rename(&dir, &gone) { + return io_error(&dir, &e); + } + step(); + let _ = std::fs::remove_dir_all(&gone); + S_OK +} + +/// Reads the named blobs (all of them for `None`) of a container. +fn read(c: &Container, names: Option>) -> Result)>, HRESULT> { + let _saves = saves_lock(); + let version = current_named(&c.dir, &c.name) + .map_err(|e| io_error(&c.dir, &e))? + .ok_or(BLOB_NOT_FOUND)?; + let names = names.unwrap_or_else(|| version.blobs.clone()); + names + .into_iter() + .map(|name| { + let i = version.blobs.iter().position(|b| *b == name).ok_or(BLOB_NOT_FOUND)?; + let data = std::fs::read(version.blob(i)).map_err(|e| io_error(&c.dir, &e))?; + Ok((name, data)) + }) + .collect() +} + +/// One blob as the public API lays it out: name, size, data. +const BLOB: usize = 24; + +/// Blobs laid out as the title reads them: the blob array, then each name +/// (NUL-terminated) and its data, with pointers `base` plus offset. +fn layout(blobs: &[(String, Vec)], base: usize) -> Vec { + let mut out = vec![0u8; blobs.len() * BLOB]; + for (i, (name, data)) in blobs.iter().enumerate() { + let name_at = base + out.len(); + out.extend_from_slice(name.as_bytes()); + out.push(0); + let data_at = base + out.len(); + out.extend_from_slice(data); + let entry = &mut out[i * BLOB..(i + 1) * BLOB]; + entry[..8].copy_from_slice(&name_at.to_le_bytes()); + entry[8..12].copy_from_slice(&(data.len() as u32).to_le_bytes()); + entry[16..].copy_from_slice(&data_at.to_le_bytes()); + } + out +} + +/// The names a title passes (`count` strings, or all blobs if null). +fn names(names: *const *const c_char, count: u32) -> Option> { + if names.is_null() { + return None; + } + // SAFETY: the title passes `count` strings. + let names = unsafe { std::slice::from_raw_parts(names, count as usize) }; + Some(names.iter().map(|&n| text(n).unwrap_or_default()).collect()) +} + +type This = *const Object; +type ContainerCallback = extern "system" fn(*const ContainerInfo, *mut c_void) -> bool; +type BlobCallback = extern "system" fn(*const BlobInfo, *mut c_void) -> bool; + +#[repr(C)] +pub struct ContainerInfo { + pub name: *const c_char, + pub display_name: *const c_char, + pub blob_count: u32, + pub total_size: u64, + pub last_modified: i64, + pub needs_sync: bool, +} + +#[repr(C)] +pub struct BlobInfo { + pub name: *const c_char, + pub size: u32, +} + +/// Calls `callback` with the information of each container that passes +/// `keep` until it returns false; never under our lock (it may call us). +fn report(root: &Path, keep: impl Fn(&str) -> bool, context: *mut c_void, callback: ContainerCallback) { + let infos: Vec<(CString, CString, u32, u64, i64)> = { + let _saves = saves_lock(); + containers(root) + .into_iter() + .filter(|(name, _)| keep(name)) + .filter_map(|(name, dir)| current_named(&dir, &name).ok().flatten()) + .map(|v| { + let modified = std::fs::metadata(v.dir.join(MANIFEST)) + .and_then(|m| m.modified()) + .ok() + .and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok()) + .map_or(0, |d| d.as_secs() as i64); + let size = v.sizes().iter().map(|(_, s)| s).sum(); + let count = v.blobs.len() as u32; + (cstring(&v.name), cstring(&v.display), count, size, modified) + }) + .collect() + }; + for (name, display, blob_count, total_size, last_modified) in &infos { + let info = ContainerInfo { + name: name.as_ptr(), + display_name: display.as_ptr(), + blob_count: *blob_count, + total_size: *total_size, + last_modified: *last_modified, + needs_sync: false, + }; + if !callback(&info, context) { + break; + } + } +} + +fn cstring(s: &str) -> CString { + CString::new(s.replace('\0', "")).unwrap_or_default() +} + +static INIT: u8 = 0; +static QUOTA_CALL: u8 = 0; +static DELETE: u8 = 0; +static READ: u8 = 0; +static SUBMIT: u8 = 0; + +extern "system" fn initialize_async( + _: This, + _user: *const c_void, + config: *const c_char, + _sync_on_demand: bool, + block: *mut AsyncBlock, +) -> HRESULT { + let saves = runtime::title().saves(); + let result = if saves.parent().is_none_or(|p| p.as_os_str().is_empty()) { + Err(NO_ACCESS) + } else { + Provider::open(&saves, text(config).as_deref()).map(|p| xasync::bytes(give(p))) + }; + xasync::finished_with(block, (&raw const INIT).cast(), result) +} +extern "system" fn initialize_result( + _: This, + block: *mut AsyncBlock, + out: *mut *mut Provider, +) -> HRESULT { + xasync::result(block, (&raw const INIT).cast(), out) +} +extern "system" fn close_provider(_: This, provider: *mut Provider) { + take(provider); +} + +extern "system" fn quota_async( + _: This, + provider: *const Provider, + block: *mut AsyncBlock, +) -> HRESULT { + let result = get(provider) + .ok_or(E_INVALIDARG) + .map(|p| xasync::bytes(p.remaining() as i64)); + xasync::finished_with(block, (&raw const QUOTA_CALL).cast(), result) +} +extern "system" fn quota_result(_: This, block: *mut AsyncBlock, out: *mut i64) -> HRESULT { + xasync::result(block, (&raw const QUOTA_CALL).cast(), out) +} + +extern "system" fn delete_async( + _: This, + provider: *const Provider, + name: *const c_char, + block: *mut AsyncBlock, +) -> HRESULT { + let hr = match (get(provider), text(name)) { + (Some(p), Some(name)) if valid_container(&name) => delete(&p.root, &name), + (Some(_), Some(_)) => INVALID_CONTAINER_NAME, + _ => E_INVALIDARG, + }; + xasync::finished(block, (&raw const DELETE).cast(), hr) +} +extern "system" fn delete_result(_: This, block: *mut AsyncBlock) -> HRESULT { + let none = std::ptr::null_mut(); + xasync::XAsyncGetResult(block, (&raw const DELETE).cast(), 0, none, none.cast()) +} + +/// Reports the container if it exists; a missing one is no error, the +/// callback just does not run. +extern "system" fn container_info( + _: This, + provider: *const Provider, + name: *const c_char, + context: *mut c_void, + callback: Option, +) -> HRESULT { + let (Some(p), Some(name), Some(callback)) = (get(provider), text(name), callback) else { + return E_INVALIDARG; + }; + if !valid_container(&name) { + return INVALID_CONTAINER_NAME; + } + report(&p.root, |n| n == name, context, callback); + S_OK +} + +extern "system" fn enumerate_containers( + _: This, + provider: *const Provider, + context: *mut c_void, + callback: Option, +) -> HRESULT { + let (Some(p), Some(callback)) = (get(provider), callback) else { + return E_INVALIDARG; + }; + report(&p.root, |_| true, context, callback); + S_OK +} + +/// The container exists once an update to it is submitted. +extern "system" fn create_container( + _: This, + provider: *const Provider, + name: *const c_char, + out: *mut *mut Container, +) -> HRESULT { + let (Some(p), Some(name)) = (get(provider), text(name)) else { + return E_INVALIDARG; + }; + if !valid_container(&name) { + return INVALID_CONTAINER_NAME; + } + put(out, give(p.container(&name))) +} +extern "system" fn close_container(_: This, container: *mut Container) { + take(container); +} + +extern "system" fn enumerate_blobs( + _: This, + container: *const Container, + prefix: *const c_char, + context: *mut c_void, + callback: Option, +) -> HRESULT { + let (Some(c), Some(callback)) = (get(container), callback) else { + return E_INVALIDARG; + }; + let prefix = text(prefix).unwrap_or_default(); + let blobs = { + let _saves = saves_lock(); + let version = current_named(&c.dir, &c.name).ok().flatten(); + version.map(|v| v.sizes()).unwrap_or_default() + }; + for (name, size) in blobs.into_iter().filter(|(n, _)| n.starts_with(&prefix)) { + let name = cstring(&name); + let info = BlobInfo { + name: name.as_ptr(), + size: size as u32, + }; + if !callback(&info, context) { + break; + } + } + S_OK +} + +extern "system" fn read_blobs( + _: This, + container: *const Container, + blob_names: *const *const c_char, + count: *mut u32, + size: usize, + out: *mut u8, +) -> HRESULT { + let Some(c) = get(container) else { + return E_INVALIDARG; + }; + // SAFETY: the title passes its count. + let wanted = unsafe { count.as_ref() }.copied().unwrap_or(0); + let blobs = match read(c, names(blob_names, wanted)) { + Ok(blobs) => blobs, + Err(hr) => return hr, + }; + let bytes = layout(&blobs, out as usize); + if out.is_null() || size < bytes.len() { + return BUFFER_TOO_SMALL; + } + // SAFETY: the buffer holds `size` bytes, checked above. + unsafe { out.copy_from_nonoverlapping(bytes.as_ptr(), bytes.len()) }; + put(count, blobs.len() as u32) +} + +/// Read at once; the result holds the layout with pointers relative to the +/// title's buffer, fixed up when the title takes it. +extern "system" fn read_async( + _: This, + container: *const Container, + blob_names: *const *const c_char, + count: u32, + block: *mut AsyncBlock, +) -> HRESULT { + let result = match get(container) { + Some(c) => read(c, names(blob_names, count)).map(|blobs| layout(&blobs, 0)), + None => Err(E_INVALIDARG), + }; + xasync::finished_with(block, (&raw const READ).cast(), result) +} +extern "system" fn read_result( + _: This, + block: *mut AsyncBlock, + size: usize, + out: *mut u8, + count: *mut u32, +) -> HRESULT { + let mut used = 0; + let hr = xasync::XAsyncGetResult(block, (&raw const READ).cast(), size, out.cast(), &mut used); + // The documented error for a small buffer; the result stays for a + // retry with a larger one. + if hr == xasync::E_NOT_SUFFICIENT_BUFFER { + return BUFFER_TOO_SMALL; + } + if hr < 0 { + return hr; + } + // The first name follows the blob array, so its offset gives the count. + let blobs = if used == 0 { + 0 + } else { + // SAFETY: the result holds at least one blob entry. + unsafe { out.cast::().read_unaligned() / BLOB } + }; + for i in 0..blobs { + for field in [0, 16] { + // SAFETY: within the blob array just written. + unsafe { + let p = out.add(i * BLOB + field).cast::(); + p.write_unaligned(p.read_unaligned() + out as usize); + } + } + } + put(count, blobs as u32) +} + +extern "system" fn create_update( + _: This, + container: *const Container, + display: *const c_char, + out: *mut *mut Update, +) -> HRESULT { + let Some(c) = get(container) else { + return E_INVALIDARG; + }; + put( + out, + give(Update { + name: c.name.clone(), + dir: c.dir.clone(), + display: text(display), + changes: Vec::new(), + }), + ) +} +extern "system" fn close_update(_: This, update: *mut Update) { + take(update); +} + +extern "system" fn write_blob( + _: This, + update: *mut Update, + name: *const c_char, + data: *const u8, + size: usize, +) -> HRESULT { + // SAFETY: a handle we gave out; the title does not use it concurrently. + let (Some(update), Some(name)) = (unsafe { update.as_mut() }, text(name)) else { + return E_INVALIDARG; + }; + if name.is_empty() || (data.is_null() && size > 0) { + return E_INVALIDARG; + } + if size > MAX_UPDATE { + return UPDATE_TOO_BIG; + } + let data = if size == 0 { + Vec::new() + } else { + // SAFETY: the title passes `size` bytes. + unsafe { std::slice::from_raw_parts(data, size) }.to_vec() + }; + update.changes.push((name, Some(data))); + S_OK +} + +extern "system" fn delete_blob(_: This, update: *mut Update, name: *const c_char) -> HRESULT { + // SAFETY: as in `write_blob`. + match (unsafe { update.as_mut() }, text(name)) { + (Some(update), Some(name)) if !name.is_empty() => { + update.changes.push((name, None)); + S_OK + } + _ => E_INVALIDARG, + } +} + +extern "system" fn submit_async(_: This, update: *const Update, block: *mut AsyncBlock) -> HRESULT { + let hr = get(update).map_or(E_INVALIDARG, Update::submit); + xasync::finished(block, (&raw const SUBMIT).cast(), hr) +} +extern "system" fn submit_result(_: This, block: *mut AsyncBlock) -> HRESULT { + let none = std::ptr::null_mut(); + xasync::XAsyncGetResult(block, (&raw const SUBMIT).cast(), 0, none, none.cast()) +} + +static VTABLE: Methods<30> = Methods([ + missing::<0> as *const (), + add_ref as *const (), + add_ref as *const (), + missing::<3> as *const (), // 0x18 initialize (blocking) + initialize_async as *const (), // 0x20 + initialize_result as *const (), // 0x28 + close_provider as *const (), // 0x30 + missing::<7> as *const (), // 0x38 remaining quota (blocking) + quota_async as *const (), // 0x40 + quota_result as *const (), // 0x48 + missing::<10> as *const (), // 0x50 delete (blocking) + delete_async as *const (), // 0x58 + delete_result as *const (), // 0x60 + container_info as *const (), // 0x68 + enumerate_containers as *const (), // 0x70 + missing::<15> as *const (), // 0x78 by name prefix + create_container as *const (), // 0x80 + close_container as *const (), // 0x88 + missing::<18> as *const (), // 0x90 all blob info + enumerate_blobs as *const (), // 0x98 by name prefix + read_blobs as *const (), // 0xa0 + read_async as *const (), // 0xa8 + read_result as *const (), // 0xb0 + create_update as *const (), // 0xb8 + close_update as *const (), // 0xc0 + write_blob as *const (), // 0xc8 + delete_blob as *const (), // 0xd0 + missing::<27> as *const (), // 0xd8 submit (blocking) + submit_async as *const (), // 0xe0 + submit_result as *const (), // 0xe8 +]); + +#[cfg(test)] +mod tests { + use std::io::BufRead; + use std::sync::atomic::{AtomicU32, Ordering}; + + use super::*; + use crate::modules::xgameruntime::method; + + fn block() -> AsyncBlock { + AsyncBlock { + queue: std::ptr::null(), + context: std::ptr::null_mut(), + callback: None, + internal: [0; 4], + } + } + + static STEPS: AtomicU32 = AtomicU32::new(0); + + /// In a child process of the crash test, stops for good at the step + /// `LEONIDA_SAVE_STOP` names and says so. + pub(super) fn crash_point() { + let Ok(stop) = std::env::var("LEONIDA_SAVE_STOP") else { + return; + }; + if stop.parse() == Ok(STEPS.fetch_add(1, Ordering::SeqCst) + 1) { + println!("STOPPED"); + let _ = std::io::stdout().flush(); + loop { + std::thread::sleep(std::time::Duration::from_secs(60)); + } + } + } + + /// The per-user quota and the host disk fail with their own errors. + #[test] + fn a_full_disk_is_not_the_quota() { + let mb = 1 << 20; + assert_eq!(no_room(2 * mb, 0, 0, mb), Some(OUT_OF_LOCAL_STORAGE)); + assert_eq!(no_room(2 * mb, 0, QUOTA - mb, 100 * mb), Some(QUOTA_EXCEEDED)); + // Replacing a blob of the same size fits a full quota. + assert_eq!(no_room(mb, mb, QUOTA, 100 * mb), None); + assert_eq!(no_room(mb, 0, 0, mb), None); + } + + fn update(root: &Path, display: &str, changes: &[(&str, Option<&str>)]) -> HRESULT { + Update { + name: "Slot".into(), + dir: container_dir(root, "Slot"), + display: Some(display.into()), + changes: changes + .iter() + .map(|(n, d)| (n.to_string(), d.map(|d| d.as_bytes().to_vec()))) + .collect(), + } + .submit() + } + + /// The container `Slot`: display name and blobs. + fn state(root: &Path) -> Option<(String, Vec<(String, String)>)> { + let c = Provider { root: root.into() }.container("Slot"); + let display = current_named(&c.dir, "Slot").unwrap()?.display; + let blobs = read(&c, None).unwrap(); + let text = |(n, d): (String, Vec)| (n, String::from_utf8(d).unwrap()); + Some((display, blobs.into_iter().map(text).collect())) + } + + fn old_state() -> Option<(String, Vec<(String, String)>)> { + Some(("one".into(), vec![("a".into(), "old a".into()), ("b".into(), "old b".into())])) + } + + /// Run by the crash test in a child process; does nothing otherwise. + #[test] + fn crash_child() { + let (Ok(root), Ok(op)) = (std::env::var("LEONIDA_SAVE_CHILD"), std::env::var("LEONIDA_SAVE_OP")) else { + return; + }; + let root = PathBuf::from(root); + let hr = if op == "update" { + update(&root, "two", &[("a", Some("new a")), ("b", None), ("c", Some("new c"))]) + } else { + delete(&root, "Slot") + }; + assert_eq!(hr, S_OK); + println!("FINISHED"); + } + + /// Kills a process in the middle of an update (and of a deletion) at + /// every step: what is left is the whole old container or the whole + /// new one. + #[test] + fn a_kill_at_any_step_leaves_old_or_new() { + let new = Some(("two".into(), vec![("a".into(), "new a".into()), ("c".into(), "new c".into())])); + for (op, after) in [("update", new), ("delete", None)] { + let mut seen = (0, 0); + for stop in 1.. { + let dir = tempfile::tempdir().unwrap(); + let root = dir.path(); + assert_eq!(update(root, "one", &[("a", Some("old a")), ("b", Some("old b"))]), S_OK); + let mut child = std::process::Command::new(std::env::current_exe().unwrap()) + .args(["--exact", "modules::xgamesave::tests::crash_child", "--nocapture"]) + .args(["--test-threads=1"]) + .env("LEONIDA_SAVE_CHILD", root) + .env("LEONIDA_SAVE_OP", op) + .env("LEONIDA_SAVE_STOP", stop.to_string()) + .stdout(std::process::Stdio::piped()) + .spawn() + .unwrap(); + let out = std::io::BufReader::new(child.stdout.take().unwrap()); + let mut finished = false; + for line in out.lines() { + let line = line.unwrap(); + if line.contains("STOPPED") { + break; + } + finished |= line.contains("FINISHED"); + } + let _ = child.kill(); + child.wait().unwrap(); + let left = state(root); + if left == old_state() { + seen.0 += 1; + } else { + assert_eq!(left, after, "{op}, killed at step {stop}"); + seen.1 += 1; + } + if finished { + break; + } + } + assert!(seen.0 > 0 && seen.1 > 1, "{op}: {seen:?}"); + } + } + + #[test] + fn names_are_exact() { + for name in ["Save_1", "slot/2", "a.b c%", "\u{e9}t\u{e9}"] { + let file = file_name(name); + assert!(!file.contains(['.', '/', ' ']), "{file}"); + assert_eq!(decode(&file).as_deref(), Some(name)); + } + assert_eq!(decode("x.new"), None); + for good in ["Profile/Slot_1", "a/b/Save-2.sav", "x", &"a".repeat(256)] { + assert!(valid_container(good), "{good}"); + } + for bad in ["a b", "", "a/", "a.", "a..b", "a.b/c", "a-b/c", &"a".repeat(257)] { + assert!(!valid_container(bad), "{bad}"); + } + + // Containers and blobs differing only in case, reserved device + // names, characters the host forbids, long names: all distinct. + let dir = tempfile::tempdir().unwrap(); + let p = Provider { root: dir.path().into() }; + let long = "n".repeat(300); + let blobs = ["A", "a", "CON", "nul.txt", "x/y:z*?\"<>|", long.as_str(), "end. "]; + for container in ["Save", "save", "SAVE/CON.x"] { + let c = p.container(container); + let u = Update { + name: c.name.clone(), + dir: c.dir.clone(), + display: None, + changes: blobs + .iter() + .map(|b| (b.to_string(), Some(format!("{container}:{b}").into_bytes()))) + .collect(), + }; + assert_eq!(u.submit(), S_OK, "{container}"); + } + let _saves = saves_lock(); + let names: Vec = containers(dir.path()).into_iter().map(|c| c.0).collect(); + drop(_saves); + assert_eq!(names, ["SAVE/CON.x", "Save", "save"]); + for container in ["Save", "save", "SAVE/CON.x"] { + let read = read(&p.container(container), None).unwrap(); + let mut expected: Vec<_> = blobs + .iter() + .map(|b| (b.to_string(), format!("{container}:{b}").into_bytes())) + .collect(); + expected.sort(); + assert_eq!(read, expected, "{container}"); + } + } + + #[test] + fn the_old_layout_moves_over() { + let saves = tempfile::tempdir().unwrap(); + let root = saves.path().join(format!("{:016X}", xuser::XUID)).join("scid"); + let old = root.join("Player"); + std::fs::create_dir_all(&old).unwrap(); + std::fs::write(old.join("Save%20Game%20Data"), b"data").unwrap(); + std::fs::write(old.join("Save%20Game%20Header"), b"header").unwrap(); + std::fs::write(old.join("Save%20Game%20Data.new"), b"half").unwrap(); + std::fs::write(old.join(".display"), b"Chapter 1").unwrap(); + let p = Provider::open(saves.path(), Some("scid")).unwrap(); + assert!(!old.exists()); + let c = p.container("Player"); + let blobs = read(&c, None).unwrap(); + assert_eq!( + blobs, + [ + ("Save Game Data".into(), b"data".to_vec()), + ("Save Game Header".into(), b"header".to_vec()) + ] + ); + let v = current_named(&c.dir, "Player").unwrap().unwrap(); + assert_eq!((v.number, v.display.as_str()), (1, "Chapter 1")); + } + + /// An empty configuration id names none. As a folder name it would be + /// the folder every configuration lives in, whose folders then look + /// like containers of the old layout and are converted away. + #[test] + fn an_empty_configuration_id_is_the_default_one() { + let saves = tempfile::tempdir().unwrap(); + let scid = Provider::open(saves.path(), Some("scid")).unwrap(); + assert_eq!(update(&scid.root, "one", &[("a", Some("kept"))]), S_OK); + let kept = Some(("one".into(), vec![("a".into(), "kept".into())])); + assert_eq!(state(&scid.root), kept); + + let empty = Provider::open(saves.path(), Some("")).unwrap(); + assert!(scid.root.is_dir(), "another configuration's saves are gone"); + assert_eq!(state(&scid.root), kept); + let default = Provider::open(saves.path(), None).unwrap(); + assert_eq!(empty.root, default.root); + + // Named configurations stay apart, from it and from each other. + assert_ne!(empty.root, scid.root); + assert_eq!(state(&empty.root), None); + let other = Provider::open(saves.path(), Some("other")).unwrap(); + assert_eq!(state(&other.root), None); + assert_eq!(state(&scid.root), kept); + } + + #[test] + fn saves_persist_across_providers() { + let this: This = &OBJECT; + let saves = tempfile::tempdir().unwrap(); + let provider = give(Provider::open(saves.path(), Some("scid")).unwrap()); + + // Write two blobs through an update. + let mut container = std::ptr::null_mut(); + type Create = extern "system" fn( + This, + *const Provider, + *const c_char, + *mut *mut Container, + ) -> HRESULT; + let create = method::(&OBJECT, 0x80); + assert_eq!( + create(this, provider, c"bad name".as_ptr(), &mut container), + INVALID_CONTAINER_NAME + ); + assert_eq!( + create(this, provider, c"Slot_1".as_ptr(), &mut container), + S_OK + ); + let mut update = std::ptr::null_mut(); + type Update_ = + extern "system" fn(This, *const Container, *const c_char, *mut *mut Update) -> HRESULT; + assert_eq!( + method::(&OBJECT, 0xb8)(this, container, c"Chapter 1".as_ptr(), &mut update), + S_OK + ); + type Write = + extern "system" fn(This, *mut Update, *const c_char, *const u8, usize) -> HRESULT; + let write = method::(&OBJECT, 0xc8); + assert_eq!( + write(this, update, c"world".as_ptr(), b"hello".as_ptr(), 5), + S_OK + ); + assert_eq!( + write(this, update, c"player.dat".as_ptr(), b"xy".as_ptr(), 2), + S_OK + ); + assert_eq!( + write(this, update, c"gone".as_ptr(), b"z".as_ptr(), 1), + S_OK + ); + type Delete = extern "system" fn(This, *mut Update, *const c_char) -> HRESULT; + assert_eq!(method::(&OBJECT, 0xd0)(this, update, c"gone".as_ptr()), S_OK); + type Submit = extern "system" fn(This, *const Update, *mut AsyncBlock) -> HRESULT; + let mut b = block(); + assert_eq!(method::(&OBJECT, 0xe0)(this, update, &mut b), S_OK); + assert_eq!(xasync::XAsyncGetStatus(&mut b, true), S_OK); + close_update(this, update); + close_container(this, container); + close_provider(this, provider); + + // A new provider sees the container and reads both blobs back. + let provider = give(Provider::open(saves.path(), Some("scid")).unwrap()); + extern "system" fn seen(info: *const ContainerInfo, context: *mut c_void) -> bool { + // SAFETY: valid during the callback; the context is the test's vector. + let (info, out) = unsafe { + ( + &*info, + &mut *context.cast::>(), + ) + }; + out.push(( + text(info.name).unwrap(), + text(info.display_name).unwrap(), + info.blob_count, + info.total_size, + )); + true + } + let mut found: Vec<(String, String, u32, u64)> = Vec::new(); + let context = (&raw mut found).cast(); + assert_eq!( + enumerate_containers(this, provider, context, Some(seen)), + S_OK + ); + assert_eq!(found, [("Slot_1".into(), "Chapter 1".into(), 2, 7)]); + + let mut container = std::ptr::null_mut(); + assert_eq!( + create_container(this, provider, c"Slot_1".as_ptr(), &mut container), + S_OK + ); + let mut b = block(); + let wanted = [c"world".as_ptr(), c"player.dat".as_ptr()]; + assert_eq!( + read_async(this, container, wanted.as_ptr(), 2, &mut b), + S_OK + ); + assert_eq!(xasync::XAsyncGetStatus(&mut b, true), S_OK); + let mut size = 0; + assert_eq!(xasync::XAsyncGetResultSize(&mut b, &mut size), S_OK); + assert_eq!( + size, + 2 * BLOB + "world\0hello".len() + "player.dat\0xy".len() + ); + let mut buffer = vec![0u64; size.div_ceil(8)]; + let mut count = 0; + assert_eq!( + read_result(this, &mut b, 8, buffer.as_mut_ptr().cast(), &mut count), + BUFFER_TOO_SMALL + ); + assert_eq!( + read_result(this, &mut b, size, buffer.as_mut_ptr().cast(), &mut count), + S_OK + ); + assert_eq!(count, 2); + let blob = |i: usize| { + // SAFETY: the layout the call wrote. + unsafe { + let entry = buffer.as_ptr().cast::().add(i * BLOB); + let name = text(entry.cast::<*const c_char>().read_unaligned()).unwrap(); + let len = entry.add(8).cast::().read_unaligned() as usize; + let data = std::slice::from_raw_parts( + entry.add(16).cast::<*const u8>().read_unaligned(), + len, + ); + (name, data.to_vec()) + } + }; + assert_eq!(blob(0), ("world".into(), b"hello".to_vec())); + assert_eq!(blob(1), ("player.dat".into(), b"xy".to_vec())); + + let missing = [c"nothing".as_ptr()]; + let mut one = 1; + let mut small = [0u8; 8]; + let read_now = method::< + extern "system" fn( + This, + *const Container, + *const *const c_char, + *mut u32, + usize, + *mut u8, + ) -> HRESULT, + >(&OBJECT, 0xa0); + assert_eq!( + read_now( + this, + container, + missing.as_ptr(), + &mut one, + 8, + small.as_mut_ptr() + ), + BLOB_NOT_FOUND + ); + assert_eq!( + read_now( + this, + container, + wanted.as_ptr(), + &mut 2, + 8, + small.as_mut_ptr() + ), + BUFFER_TOO_SMALL + ); + + // Quota counts the blobs; deleting the container frees it. + let mut b = block(); + assert_eq!(quota_async(this, provider, &mut b), S_OK); + let mut left = 0i64; + assert_eq!(quota_result(this, &mut b, &mut left), S_OK); + assert!(left as u64 <= QUOTA - 7); + let mut b = block(); + assert_eq!( + delete_async(this, provider, c"Slot_1".as_ptr(), &mut b), + S_OK + ); + assert_eq!(delete_result(this, &mut b), S_OK); + found.clear(); + let context = (&raw mut found).cast(); + assert_eq!( + enumerate_containers(this, provider, context, Some(seen)), + S_OK + ); + assert!(found.is_empty()); + close_container(this, container); + close_provider(this, provider); + } +} diff --git a/crates/leonida-hle/src/modules/xgameui.rs b/crates/leonida-hle/src/modules/xgameui.rs new file mode 100644 index 000000000..9882b2eac --- /dev/null +++ b/crates/leonida-hle/src/modules/xgameui.rs @@ -0,0 +1,321 @@ +//! System dialogs a title opens (XGameUi). A profile card has nothing to +//! show and closes at once. Text entry opens a small host dialog (title, +//! description, default text, the length limit) on a thread of its own and +//! completes the call with what the user typed, or as cancelled (`E_ABORT`) +//! when the dialog is dismissed or cannot open. +#![allow(clippy::not_unsafe_ptr_arg_deref)] + +use std::ffi::{c_char, c_void}; + +use super::xasync::{self, AsyncBlock, E_ABORT}; +use super::xgameruntime::{ + Guid, HRESULT, Interface, Methods, Object, S_OK, add_ref, missing, put, text, +}; + +pub const PROVIDER: Guid = Guid::new( + 0xdfcd_4649, + 0x4ff8, + 0x4043, + [0xba, 0x07, 0x35, 0xd6, 0x07, 0xdf, 0x98, 0xb0], +); +/// As the title (2026) asks for it; the slots it calls (0x38, +/// 0x40, 0x88-0x98) take the public API's arguments in the 2020 order. +pub const IID_2026: Guid = Guid::new( + 0xeaf6_69df, + 0x5542, + 0x4590, + [0x99, 0xa3, 0x8d, 0xc0, 0x61, 0xf8, 0x37, 0xcc], +); + +pub static OBJECT: Object = Object::new("game ui", &VTABLE); +pub const INTERFACES: &[Interface] = &[(PROVIDER, IID_2026, &OBJECT)]; + +type This = *const Object; + +static PROFILE: u8 = 0; +static TEXT: u8 = 0; + +extern "system" fn profile_card_async( + _: This, + block: *mut AsyncBlock, + _user: *const c_void, + xuid: u64, +) -> HRESULT { + tracing::info!(xuid, "profile card: nothing to show"); + xasync::finished(block, (&raw const PROFILE).cast(), S_OK) +} +extern "system" fn profile_card_result(_: This, block: *mut AsyncBlock) -> HRESULT { + let none = std::ptr::null_mut(); + xasync::XAsyncGetResult(block, (&raw const PROFILE).cast(), 0, none, none.cast()) +} + +/// The title treats `E_ABORT` as cancelled and goes on; any +/// other failure as an error. +extern "system" fn text_entry_async( + _: This, + block: *mut AsyncBlock, + title: *const c_char, + description: *const c_char, + default: *const c_char, + _scope: u32, + max_length: u32, +) -> HRESULT { + let [title, description, default] = [title, description, default].map(|t| text(t).unwrap_or_default()); + tracing::info!(title, description, max_length, "text entry"); + xasync::pending_with(block, (&raw const TEXT).cast(), move || { + match ask(&title, &description, &default, max_length) { + Some(typed) => { + tracing::info!(length = typed.chars().count(), "text entry: done"); + let mut bytes = limit(&typed, max_length).into_bytes(); + bytes.push(0); + Ok(bytes) + } + None => { + tracing::info!("text entry: cancelled"); + Err(E_ABORT) + } + } + }) +} +/// Bytes of the result, its NUL included. +extern "system" fn text_entry_size(_: This, block: *mut AsyncBlock, out: *mut u32) -> HRESULT { + let mut size = 0; + let hr = xasync::XAsyncGetResultSize(block, &mut size); + if hr < 0 { + return hr; + } + put(out, size as u32) +} +extern "system" fn text_entry_result( + _: This, + block: *mut AsyncBlock, + size: u32, + buffer: *mut c_char, + used: *mut u32, +) -> HRESULT { + let mut written = 0; + let identity = (&raw const TEXT).cast(); + let hr = xasync::XAsyncGetResult(block, identity, size as usize, buffer.cast(), &mut written); + if hr < 0 || used.is_null() { + return hr; + } + put(used, written as u32) +} + +/// At most `max` characters (0: no limit). +fn limit(typed: &str, max: u32) -> String { + match max { + 0 => typed.to_owned(), + max => typed.chars().take(max as usize).collect(), + } +} + +/// Asks the user in a modal host dialog; `None` if dismissed. +#[cfg(not(test))] +fn ask(title: &str, description: &str, default: &str, max: u32) -> Option { + dialog::ask(title, description, default, max) +} + +/// Tests answer for the user: "typed" for a title starting with "Type", +/// cancelled otherwise. +#[cfg(test)] +fn ask(title: &str, _: &str, default: &str, _: u32) -> Option { + title.starts_with("Type").then(|| format!("{default}typed")) +} + +mod dialog { + use windows_sys::Win32::Foundation::{HWND, LPARAM, WPARAM}; + use windows_sys::Win32::System::LibraryLoader::GetModuleHandleW; + use windows_sys::Win32::UI::Input::KeyboardAndMouse::SetFocus; + use windows_sys::Win32::UI::WindowsAndMessaging::{self as wm, DLGTEMPLATE}; + + const EDIT: i32 = 100; + // Edit control messages (the controls headers). + const EM_SETSEL: u32 = 0xb1; + const EM_LIMITTEXT: u32 = 0xc5; + + /// The dialog's state, behind its user data while it runs. + struct Entry { + max: u32, + typed: Option, + } + + /// The description, an edit box with the default text, OK and Cancel, + /// from an in-memory template (dialog units, the system font); Enter + /// accepts, Esc cancels. + #[allow(dead_code)] // unused in test builds + pub(super) fn ask(title: &str, description: &str, default: &str, max: u32) -> Option { + let mut t: Vec = Vec::new(); + fn dword(t: &mut Vec, v: u32) { + t.extend([v as u16, (v >> 16) as u16]); + } + fn text(t: &mut Vec, s: &str) { + t.extend(s.encode_utf16().filter(|&c| c != 0)); + t.push(0); + } + let style = wm::WS_POPUP | wm::WS_CAPTION | wm::WS_SYSMENU; + let flags = (wm::DS_MODALFRAME | wm::DS_CENTER | wm::DS_SETFOREGROUND) as u32; + dword(&mut t, style | flags); + dword(&mut t, wm::WS_EX_TOPMOST); + t.extend([4, 0, 0, 240, 62, 0, 0]); // items, x, y, cx, cy, no menu, default class + text(&mut t, title); + let mut item = |style: u32, rect: [u16; 4], id: u16, class: u16, caption: &str| { + if t.len() % 2 == 1 { + t.push(0); // items start on a DWORD + } + dword(&mut t, wm::WS_CHILD | wm::WS_VISIBLE | style); + dword(&mut t, 0); + t.extend(rect); + t.extend([id, 0xffff, class]); + text(&mut t, caption); + t.push(0); // no creation data + }; + let (button, edit, label) = (0x80, 0x81, 0x82); + let tab = wm::WS_TABSTOP; + item(0, [7, 7, 226, 10], 0xffff, label, description); + let edit_style = wm::WS_BORDER | tab | wm::ES_AUTOHSCROLL as u32; + item(edit_style, [7, 20, 226, 12], EDIT as u16, edit, default); + let ok = wm::BS_DEFPUSHBUTTON as u32 | tab; + item(ok, [129, 40, 50, 14], wm::IDOK as u16, button, "OK"); + let cancel = wm::BS_PUSHBUTTON as u32 | tab; + item(cancel, [183, 40, 50, 14], wm::IDCANCEL as u16, button, "Cancel"); + // The template must start on a DWORD. + let template: Vec = t + .chunks(2) + .map(|c| u32::from(c[0]) | u32::from(c.get(1).copied().unwrap_or(0)) << 16) + .collect(); + let mut entry = Entry { max, typed: None }; + // SAFETY: a complete template and our dialog procedure; `entry` + // outlives the modal dialog. + unsafe { + wm::DialogBoxIndirectParamW( + GetModuleHandleW(std::ptr::null()), + template.as_ptr().cast::(), + std::ptr::null_mut(), + Some(procedure), + (&raw mut entry) as LPARAM, + ); + } + entry.typed + } + + extern "system" fn procedure(dialog: HWND, message: u32, wparam: WPARAM, lparam: LPARAM) -> isize { + // SAFETY: our dialog; its user data is the `Entry` from `ask`, + // stored at WM_INITDIALOG. + unsafe { + let edit = wm::GetDlgItem(dialog, EDIT); + match message { + wm::WM_INITDIALOG => { + wm::SetWindowLongPtrW(dialog, wm::GWLP_USERDATA, lparam); + let entry = &*(lparam as *const Entry); + wm::SendMessageW(edit, EM_LIMITTEXT, entry.max as WPARAM, 0); + wm::SendMessageW(edit, EM_SETSEL, 0, -1); + SetFocus(edit); + 0 // focus set here + } + wm::WM_COMMAND => { + let entry = &mut *(wm::GetWindowLongPtrW(dialog, wm::GWLP_USERDATA) as *mut Entry); + match (wparam & 0xffff) as i32 { + wm::IDOK => { + let mut buffer = vec![0u16; wm::GetWindowTextLengthW(edit) as usize + 1]; + let n = wm::GetWindowTextW(edit, buffer.as_mut_ptr(), buffer.len() as i32); + entry.typed = Some(String::from_utf16_lossy(&buffer[..n.max(0) as usize])); + wm::EndDialog(dialog, 1); + } + wm::IDCANCEL => { + wm::EndDialog(dialog, 0); + } + _ => return 0, + } + 1 + } + _ => 0, + } + } + } +} + +static VTABLE: Methods<20> = Methods([ + missing::<0> as *const (), + add_ref as *const (), + add_ref as *const (), + missing::<3> as *const (), // 0x18 message dialog + missing::<4> as *const (), // 0x20 + missing::<5> as *const (), // 0x28 send invite + missing::<6> as *const (), // 0x30 + profile_card_async as *const (), // 0x38 + profile_card_result as *const (), // 0x40 + missing::<9> as *const (), // 0x48 achievements + missing::<10> as *const (), // 0x50 + missing::<11> as *const (), // 0x58 player picker + missing::<12> as *const (), // 0x60 + missing::<13> as *const (), // 0x68 + missing::<14> as *const (), // 0x70 error dialog + missing::<15> as *const (), // 0x78 + missing::<16> as *const (), // 0x80 notification position + text_entry_async as *const (), // 0x88 + text_entry_size as *const (), // 0x90 + text_entry_result as *const (), // 0x98 +]); + +#[cfg(test)] +mod tests { + use super::*; + use crate::modules::xgameruntime::method; + + fn block() -> AsyncBlock { + AsyncBlock { + queue: std::ptr::null(), + context: std::ptr::null_mut(), + callback: None, + internal: [0; 4], + } + } + + #[test] + fn dialogs_end_with_what_was_typed() { + let this: This = &OBJECT; + let mut b = block(); + type Card = extern "system" fn(This, *mut AsyncBlock, *const c_void, u64) -> HRESULT; + type Done = extern "system" fn(This, *mut AsyncBlock) -> HRESULT; + assert_eq!( + method::(&OBJECT, 0x38)(this, &mut b, std::ptr::null(), 1), + S_OK + ); + assert_eq!(xasync::XAsyncGetStatus(&mut b, true), S_OK); + assert_eq!(method::(&OBJECT, 0x40)(this, &mut b), S_OK); + + type Entry = extern "system" fn( + This, + *mut AsyncBlock, + *const c_char, + *const c_char, + *const c_char, + u32, + u32, + ) -> HRESULT; + type Size = extern "system" fn(This, *mut AsyncBlock, *mut u32) -> HRESULT; + type Result_ = extern "system" fn(This, *mut AsyncBlock, u32, *mut c_char, *mut u32) -> HRESULT; + let null = std::ptr::null(); + let entry = method::(&OBJECT, 0x88); + // Dismissed: cancelled. + let mut b = block(); + assert_eq!(entry(this, &mut b, c"Name".as_ptr(), null, null, 0, 16), S_OK); + assert_eq!(xasync::XAsyncGetStatus(&mut b, true), E_ABORT); + let mut size = 0; + assert_eq!(method::(&OBJECT, 0x90)(this, &mut b, &mut size), E_ABORT); + // Typed: the text, cut to the limit, with its NUL. + let mut b = block(); + let default = c"abc".as_ptr(); + assert_eq!(entry(this, &mut b, c"Type".as_ptr(), null, default, 0, 6), S_OK); + assert_eq!(xasync::XAsyncGetStatus(&mut b, true), S_OK); + assert_eq!(method::(&OBJECT, 0x90)(this, &mut b, &mut size), S_OK); + assert_eq!(size, 7); + let mut out = [0 as c_char; 7]; + let mut used = 0; + let result = method::(&OBJECT, 0x98); + assert_eq!(result(this, &mut b, 7, out.as_mut_ptr(), &mut used), S_OK); + assert_eq!((text(out.as_ptr()).as_deref(), used), (Some("abctyp"), 7)); + assert_eq!(limit("\u{e9}t\u{e9}s", 3), "\u{e9}t\u{e9}"); + } +} diff --git a/crates/leonida-hle/src/modules/xmem.rs b/crates/leonida-hle/src/modules/xmem.rs new file mode 100644 index 000000000..7292a7674 --- /dev/null +++ b/crates/leonida-hle/src/modules/xmem.rs @@ -0,0 +1,1455 @@ +//! `xmem.dll`: console memory, served from host memory. The GPU side works +//! from CPU addresses (unified memory), so memory types and bandwidth +//! classes change nothing here; what constrains addresses (alignment, +//! 2 MiB pages, address-bit limits) is honoured. +#![allow(non_snake_case)] +// Title code calls these through its import table, passing pointers the real +// API would trust. +#![allow(clippy::not_unsafe_ptr_arg_deref)] + +use std::alloc::{Layout, alloc, dealloc}; +use std::collections::{BTreeMap, HashMap}; +use std::ffi::c_void; +use std::sync::atomic::{AtomicUsize, Ordering}; +use std::sync::{Arc, LazyLock, Mutex, MutexGuard}; + +use windows_sys::Win32::Foundation::{ + CloseHandle, ERROR_COMMITMENT_LIMIT, HANDLE, INVALID_HANDLE_VALUE, +}; +use windows_sys::Win32::System::Memory::{ + CreateFileMappingW, MEM_ADDRESS_REQUIREMENTS, MEM_COMMIT, MEM_EXTENDED_PARAMETER, + MEM_PRESERVE_PLACEHOLDER, MEM_RELEASE, MEM_REPLACE_PLACEHOLDER, MEM_RESERVE, + MEM_RESERVE_PLACEHOLDER, MEMORY_BASIC_INFORMATION, MEMORY_MAPPED_VIEW_ADDRESS, MapViewOfFile3, + MemExtendedParameterAddressRequirements, PAGE_NOACCESS, PAGE_READWRITE, SEC_COMMIT, + SEC_RESERVE, UnmapViewOfFile2, VirtualAlloc, VirtualAlloc2, VirtualFree, VirtualQueryEx, +}; +use windows_sys::Win32::System::ProcessStatus::{ + K32GetPerformanceInfo, K32GetProcessMemoryInfo, PERFORMANCE_INFORMATION, + PROCESS_MEMORY_COUNTERS, +}; +use windows_sys::Win32::System::Threading::GetCurrentProcess; +use windows_sys::core::BOOL; + +use crate::{HleModule, hle_export}; + +const MIB: usize = 1 << 20; + +/// Whether we run under Wine (its ntdll exports `wine_get_version`). +pub(crate) fn on_wine() -> bool { + static WINE: LazyLock = LazyLock::new(|| { + use windows_sys::Win32::System::LibraryLoader::{GetModuleHandleA, GetProcAddress}; + // SAFETY: plain lookups in ntdll, always loaded. + unsafe { + let ntdll = GetModuleHandleA(c"ntdll.dll".as_ptr().cast()); + !ntdll.is_null() && GetProcAddress(ntdll, c"wine_get_version".as_ptr().cast()).is_some() + } + }); + *WINE +} + +/// Standard memory the title has handed to the system. +static TRANSFERRED: AtomicUsize = AtomicUsize::new(0); + +// Console additions to the host's flags. +/// 2 MiB pages; the host reads this bit as large pages, which need a +/// privilege. +const PAGES_2M: u32 = 0x2000_0000; +/// With `PAGES_2M`: 64 KiB pages; the host reads it as AWE memory. +const PAGES_64K_BIT: u32 = 0x40_0000; +const PAGES_64K: u32 = PAGES_2M | PAGES_64K_BIT; +/// The host's protection constants and `PAGE_GUARD`. Above them the console +/// adds GPU access bits (0x800-0x40000). Write-combining and uncached are +/// dropped too: our GPU side reads this memory through the CPU. +const HOST_PROTECTION: u32 = 0x1ff; +/// XMem flags of memory both processors reach: all of ours. +const GRAPHICS: u64 = 3; +/// XMem flag bit of 32-bit graphics memory. +const ADDRESS_32BIT: u64 = 4; +/// The host's write watching (not in windows-sys' memory module). +const MEM_WRITE_WATCH: u32 = 0x20_0000; + +/// The addresses XMem `flags` allow, first and last: the low 4 GiB for +/// 32-bit memory; else from 4 GiB (kept for 32-bit requests, which the +/// title's big pools would otherwise crowd out) up to 46 down to 40 bits +/// from the field at bit 12, or 40 bits without one: the console keeps +/// title memory there, and its ray-tracing structures must be ( +/// the title's BVH builder refuses one above; the title asks for its GPU heap +/// with no field). Decision 0001. +fn address_range(flags: u64) -> (usize, usize) { + let bits = match (flags & ADDRESS_32BIT, flags >> 12 & 7) { + (0, 0) => 40, + (0, field) => 47 - field, + _ => return (0, u32::MAX as usize), + }; + (1 << 32, (1 << bits) - 1) +} + +pub extern "system" fn XMemVirtualAlloc( + base: *mut c_void, + size: usize, + kind: u32, + flags: u64, + protect: u32, +) -> *mut c_void { + let (lowest, highest) = address_range(flags); + let mut requirements = MEM_ADDRESS_REQUIREMENTS { + LowestStartingAddress: lowest as *mut c_void, + HighestEndingAddress: highest as *mut c_void, + Alignment: if kind & (PAGES_2M | PAGES_64K_BIT) == PAGES_2M { + 2 * MIB + } else { + 0 + }, + }; + let mut protect = match protect & HOST_PROTECTION { + 0 => PAGE_NOACCESS, + p => p, + }; + // A reservation of 64 KiB pages takes physical pages later + // (`XMemMapPhysicalPages`); on the host only a placeholder can. + // shortcut: committing part of such a reservation later would fail + // (the title's 23 calls never do); replace that part of the + // placeholder then. + let placeholder = kind & PAGES_64K == PAGES_64K && kind & MEM_COMMIT == 0; + if placeholder { + if kind & MEM_REPLACE_PLACEHOLDER != 0 { + // Part of a placeholder the title split: it stays one. + return base; + } + protect = PAGE_NOACCESS; + } + let mut kind = kind & !(PAGES_2M | PAGES_64K_BIT); + if placeholder { + kind |= MEM_RESERVE | MEM_RESERVE_PLACEHOLDER; + } + let mut parameter = MEM_EXTENDED_PARAMETER::default(); + parameter.Anonymous1._bitfield = MemExtendedParameterAddressRequirements as u64; + parameter.Anonymous2.Pointer = (&raw mut requirements).cast(); + // Address requirements apply to reservations at an address of our choice. + let constrained = base.is_null(); + if constrained { + kind |= MEM_RESERVE; + // The GPU side copies only the pages the title wrote since its last + // copy (`leonida_gpu`, decision 0007); placeholders cannot be + // watched (their physical-page views are copied whole). + if kind & MEM_RESERVE_PLACEHOLDER == 0 { + kind |= MEM_WRITE_WATCH; + } + } + // SAFETY: the title's own arguments, cleaned of console bits; the + // parameter points at `requirements`, which outlives the call. + let at = unsafe { + VirtualAlloc2( + GetCurrentProcess(), + base, + size, + kind, + protect, + if constrained { + &mut parameter + } else { + std::ptr::null_mut() + }, + constrained.into(), + ) + }; + if base.is_null() { + tracing::debug!( + size, + kind = format_args!("{kind:#x}"), + flags = format_args!("{flags:#x}"), + at = format_args!("{at:p}"), + "XMemVirtualAlloc" + ); + } + at +} + +/// `MEMORY_BASIC_INFORMATION` (the console's first 0x30 bytes are the +/// same), then the XMem flags and tag. +#[repr(C)] +pub struct BasicInformation { + host: MEMORY_BASIC_INFORMATION, + flags: u64, + tag_code: u32, + tag: [u8; 4], +} + +// shortcut: every committed page reports graphics memory and no tag, since +// all of it is GPU-reachable here (the title's BVH builder, the +// only caller, wants graphics memory); remember the flags of +// `XMemVirtualAlloc` regions if a title tells CPU-only memory apart. +pub extern "system" fn XMemVirtualQuery( + process: HANDLE, + address: *const c_void, + out: *mut BasicInformation, +) -> BOOL { + let size = size_of::(); + // SAFETY: the title passes room for the whole structure; the host + // fails on a null one. + unsafe { + if VirtualQueryEx(process, address, out.cast(), size) == 0 { + return 0; + } + let info = &mut *out; + info.flags = if info.host.State == MEM_COMMIT { + GRAPHICS + } else { + 0 + }; + info.tag_code = 0; + info.tag = [0; 4]; + } + 1 +} + +// `XMemAlloc` attributes: alignment as log2 (5 bits at 24, 4 bytes and up +// from 2), then the memory type, then bit 33: a 32-bit address. +const ALIGNMENT_SHIFT: u64 = 24; +const ALLOC_32BIT: u64 = 1 << 33; +/// Our block header: the block's size and alignment, just below the +/// pointer handed out. +const HEADER: usize = 2 * size_of::(); + +fn layout(size: usize, attributes: u64) -> Option { + // An alignment of at least 16 leaves room for the header. + let align = 1usize << (attributes >> ALIGNMENT_SHIFT & 0x1f).max(4); + Layout::from_size_align(size.checked_add(align)?, align).ok() +} + +type AllocRoutine = extern "system" fn(usize, u64) -> *mut c_void; +type FreeRoutine = extern "system" fn(*mut c_void, u64); + +/// The allocation and free routines the title's exe exports as +/// `__XMemAllocationHooks__` (the title does): `XMemAlloc` and +/// `XMemFree` call them, for the title's own calls and its middleware's; +/// the `…Default` exports do not. +fn hooks() -> [usize; 2] { + static AT: std::sync::OnceLock = std::sync::OnceLock::new(); + let at = match AT.get() { + Some(&at) => at, + // Looked up once the title is mapped, which is before it runs. + None => match crate::runtime::main_image() { + Some(base) => *AT.get_or_init(|| { + use windows_sys::Win32::System::LibraryLoader::GetProcAddress; + // SAFETY: a mapped image and a NUL-terminated name. + let at = unsafe { + GetProcAddress(base as _, c"__XMemAllocationHooks__".as_ptr().cast()) + } + .map_or(0, |f| f as usize); + tracing::info!(found = at != 0, "xmem allocation hooks"); + at + }), + None => 0, + }, + }; + if at == 0 { + return [0; 2]; + } + // SAFETY: the export is two routine pointers. + unsafe { (at as *const [usize; 2]).read() } +} + +/// The title's general allocator, for middleware too: its hook if it has +/// one, else [`XMemAllocDefault`]. +pub extern "system" fn XMemAlloc(size: usize, attributes: u64) -> *mut c_void { + match hooks()[0] { + 0 => XMemAllocDefault(size, attributes), + hook => { + // SAFETY: the title's own routine of this type. + let alloc: AllocRoutine = unsafe { std::mem::transmute(hook) }; + alloc(size, attributes) + } + } +} + +/// See [`XMemAlloc`]. +pub extern "system" fn XMemFree(address: *mut c_void, attributes: u64) { + match hooks()[1] { + 0 => XMemFreeDefault(address, attributes), + hook => { + // SAFETY: the title's own routine of this type. + let free: FreeRoutine = unsafe { std::mem::transmute(hook) }; + free(address, attributes) + } + } +} + +/// The system allocator behind [`XMemAlloc`]. +pub extern "system" fn XMemAllocDefault(size: usize, attributes: u64) -> *mut c_void { + if attributes & ALLOC_32BIT != 0 { + return XMemVirtualAlloc( + std::ptr::null_mut(), + size, + MEM_RESERVE | MEM_COMMIT, + GRAPHICS | ADDRESS_32BIT, + PAGE_READWRITE, + ); + } + let Some(layout) = layout(size, attributes) else { + return std::ptr::null_mut(); + }; + // shortcut: the host heap's addresses lie above 2^40, unlike the + // console's; nothing seen builds ray-tracing structures in this memory + // (the title uses its GPU heap). Sub-allocate from a + // reservation below 2^40 if one does. + // SAFETY: the layout has a non-zero size. + let block = unsafe { alloc(layout) }; + if block.is_null() { + return block.cast(); + } + // SAFETY: the block holds the alignment (at least the header) and then + // `size` bytes. + unsafe { + let user = block.add(layout.align()); + user.sub(HEADER) + .cast::<[usize; 2]>() + .write([layout.size(), layout.align()]); + user.cast() + } +} + +/// Frees what [`XMemAllocDefault`] returned, given the same attributes. +pub extern "system" fn XMemFreeDefault(address: *mut c_void, attributes: u64) { + if address.is_null() { + return; + } + // SAFETY: the address came from `XMemAlloc` with these attributes: a + // whole reservation, or a header-prefixed block. + unsafe { + if attributes & ALLOC_32BIT != 0 { + VirtualFree(address, 0, MEM_RELEASE); + return; + } + let user = address.cast::(); + let [size, align] = user.sub(HEADER).cast::<[usize; 2]>().read(); + dealloc( + user.sub(align), + Layout::from_size_align_unchecked(size, align), + ); + } +} + +/// A retail console has no tools memory. +pub extern "system" fn XMemIsToolsMemAvailable() -> BOOL { + 0 +} + +// Physical pages: on the console, 64 KiB frames a title maps into its own +// reservations, at more than one address if it likes. Here each allocation +// is a pagefile-backed section, its pages are 64 KiB slices of it, and a +// mapping is a view of consecutive slices in place of a host placeholder. + +const PAGE: usize = 64 << 10; + +struct Section(HANDLE); + +// SAFETY: a section handle may be used from any thread. +unsafe impl Send for Section {} +// SAFETY: as above. +unsafe impl Sync for Section {} + +impl Drop for Section { + fn drop(&mut self) { + // SAFETY: our handle; views keep the section alive on their own. + unsafe { CloseHandle(self.0) }; + } +} + +/// Where a page lives, or what a view starts with: a section and a page +/// index in it. +#[derive(Clone)] +struct Slice { + section: Arc
, + index: usize, +} + +impl Slice { + /// The key in `Physical::shown` of the page `k` pages after this one. + fn key(&self, k: usize) -> (usize, usize) { + (Arc::as_ptr(&self.section) as usize, self.index + k) + } +} + +#[derive(Default)] +struct Physical { + next_page: usize, + pages: HashMap, + /// Mapped views by address: their length and what they show. + views: BTreeMap, + /// Where each page shows: by its section and its index there, the + /// address of that page in every view that shows it now ([`shown_at`]; + /// as upstream's c75fdba keeps it). The title maps pages where the + /// card reads them and has them filled afterwards by DirectStorage, + /// which writes through views of our own. + shown: HashMap<(usize, usize), Vec>, +} + +static PHYSICAL: LazyLock> = LazyLock::new(|| { + Mutex::new(Physical { + // Page numbers are opaque to titles; 0 stays unused. + next_page: 0x10_0000, + ..Default::default() + }) +}); + +fn physical() -> MutexGuard<'static, Physical> { + PHYSICAL.lock().unwrap_or_else(|e| e.into_inner()) +} + +/// `count` is in and out (pages wanted, pages given); all or nothing here. +pub extern "system" fn XMemAllocatePhysicalPages( + flags: u64, + count: *mut usize, + pages: *mut usize, +) -> BOOL { + if count.is_null() || pages.is_null() { + return 0; + } + // SAFETY: checked non-null. + let n = unsafe { *count }; + let Some(size) = n.checked_mul(PAGE).filter(|&s| s > 0) else { + return 0; + }; + // A pagefile-backed section of `size` bytes, its pages committed when + // first mapped or written (`commit`): the title asks for 6.1 + // GiB at once, which a busy host often cannot commit (error 1450). + // SAFETY: plain section creation. + let handle = unsafe { + CreateFileMappingW( + INVALID_HANDLE_VALUE, + std::ptr::null(), + // Under Wine a committed section is a sparse file, free until + // touched, and committing a reserved one page by page costs a + // wineserver request each that scans every range committed so + // far: commit it whole there. + PAGE_READWRITE | if on_wine() { SEC_COMMIT } else { SEC_RESERVE }, + (size as u64 >> 32) as u32, + size as u32, + std::ptr::null(), + ) + }; + if handle.is_null() { + let error = std::io::Error::last_os_error(); + tracing::warn!(n, %error, "XMemAllocatePhysicalPages failed"); + // SAFETY: checked non-null. + unsafe { count.write(0) }; + return 0; + } + tracing::debug!( + n, + flags = format_args!("{flags:#x}"), + "XMemAllocatePhysicalPages" + ); + // For the GPU side's in-place census: only a committed section can be + // opened as a host heap. + leonida_gpu::title_memory_section(handle as usize, size as u64, on_wine()); + let section = Arc::new(Section(handle)); + let mut physical = physical(); + let first = physical.next_page; + physical.next_page += n * FRAMES; + for index in 0..n { + let slice = Slice { + section: section.clone(), + index, + }; + let number = first + index * FRAMES; + physical.pages.insert(number, slice); + // SAFETY: the title passes room for `n` page numbers. + unsafe { pages.add(index).write(number) }; + } + 1 +} + +/// Page numbers count 4 KiB frames, so a 64 KiB page's is a multiple of +/// 16: the title keeps them as 21-bit `number >> 4` and rebuilds +/// them with `<< 4` (128 GiB of pages at most). +const FRAMES: usize = PAGE >> 12; + +/// Pages still mapped stay readable through their views until unmapped. +pub extern "system" fn XMemFreePhysicalPages(n: usize, pages: *const usize) -> BOOL { + if pages.is_null() { + return 0; + } + let mut physical = physical(); + for i in 0..n { + // SAFETY: the title passes `n` page numbers. + physical.pages.remove(&unsafe { *pages.add(i) }); + } + 1 +} + +/// A view of our own on consecutive slices of one section, committed and +/// writable, unmapped when dropped. +struct View { + at: MEMORY_MAPPED_VIEW_ADDRESS, + len: usize, +} + +impl View { + /// Maps `n` slices from `slice` on. + fn map(slice: &Slice, n: usize) -> Option { + use windows_sys::Win32::System::Memory::{FILE_MAP_WRITE, MapViewOfFile}; + let (offset, len) = ((slice.index * PAGE) as u64, n * PAGE); + // SAFETY: slices of a section we own; the view is ours until dropped. + let at = unsafe { + MapViewOfFile( + slice.section.0, + FILE_MAP_WRITE, + (offset >> 32) as u32, + offset as u32, + len, + ) + }; + if at.Value.is_null() { + return None; + } + let view = View { at, len }; + commit(at.Value as usize, len).then_some(view) + } + + fn bytes(&mut self) -> &mut [u8] { + // SAFETY: the view holds `len` committed read-write bytes, ours + // alone while `self` lives (other views of the slices only alias + // them, as the console's do). + unsafe { std::slice::from_raw_parts_mut(self.at.Value.cast(), self.len) } + } +} + +impl Drop for View { + fn drop(&mut self) { + use windows_sys::Win32::System::Memory::UnmapViewOfFile; + // SAFETY: our view. + unsafe { UnmapViewOfFile(self.at) }; + } +} + +/// The pages behind bytes `[offset, offset + len)` of `pages` (64 KiB +/// each), as runs of consecutive slices of one section: each run's first +/// slice and its length in pages. One look at the page table, which the +/// title's own mapping calls share with every DirectStorage worker. `None` +/// if a page is unknown or `pages` ends early. +fn runs(pages: &[usize], offset: usize, len: usize) -> Option> { + let end = offset.checked_add(len)?; + let pages = pages.get(offset / PAGE..end.div_ceil(PAGE))?; + let physical = physical(); + let mut runs: Vec<(Slice, usize)> = Vec::new(); + for page in pages { + let slice = physical.pages.get(page)?; + match runs.last_mut() { + Some((first, n)) + if Arc::ptr_eq(&first.section, &slice.section) + && slice.index == first.index + *n => + { + *n += 1; + } + _ => runs.push((slice.clone(), 1)), + } + } + Some(runs) +} + +/// Whether every page under `[offset, offset + len)` is known (a write that +/// fails with them known is a host failure). +pub(crate) fn pages_known(pages: &[usize], offset: usize, len: usize) -> bool { + runs(pages, offset, len).is_some() +} + +/// Copies `data` into physical pages, from `offset` bytes into the first, +/// whether or not they are mapped anywhere (DirectStorage destinations). +/// One view per run of consecutive pages, not one per page: each view +/// costs a map, a commit and an unmap (which flushes every core's TLB). +/// False if a page is unknown or the host fails. +pub(crate) fn write_physical(pages: &[usize], offset: usize, data: &[u8]) -> bool { + let Some(runs) = runs(pages, offset, data.len()) else { + return false; + }; + let (mut within, mut done) = (offset % PAGE, 0); + for (slice, n) in &runs { + let Some(mut view) = View::map(slice, *n) else { + return false; + }; + let k = (n * PAGE - within).min(data.len() - done); + view.bytes()[within..within + k].copy_from_slice(&data[done..done + k]); + (within, done) = (0, done + k); + } + true +} + +/// Bytes `[offset, offset + len)` of physical pages, writable in place +/// until dropped: DirectStorage decodes into it instead of a buffer it +/// would then copy. +pub(crate) struct PageWindow { + view: View, + within: usize, + len: usize, +} + +impl PageWindow { + pub(crate) fn bytes(&mut self) -> &mut [u8] { + let (within, len) = (self.within, self.len); + &mut self.view.bytes()[within..within + len] + } +} + +/// A window on bytes `[offset, offset + len)` of `pages` when they are +/// consecutive pages of one allocation (how titles usually hand them out); +/// `None` otherwise (pages of several allocations, out of order, or +/// unknown, or a host failure), which `write_physical` then handles or +/// reports. +pub(crate) fn page_window(pages: &[usize], offset: usize, len: usize) -> Option { + let runs = runs(pages, offset, len)?; + let [(slice, n)] = runs.as_slice() else { + return None; + }; + Some(PageWindow { + view: View::map(slice, *n)?, + within: offset % PAGE, + len, + }) +} + +/// The title addresses that show bytes `[offset, offset + len)` of `pages` +/// now, byte for byte, as runs (address, bytes) in address order: a write +/// to the pages through a view of our own ([`page_window`], +/// [`write_physical`]) lands there too, and nothing that watches those +/// addresses sees it (the GPU side's guards fault only on a write at the +/// guarded address itself). Empty if no view shows them. Byte for byte, +/// not by whole pages: the title packs several small textures into one +/// page and fills each with a request of its own. +pub(crate) fn shown_at(pages: &[usize], offset: usize, len: usize) -> Vec<(usize, usize)> { + let Some(end) = offset.checked_add(len) else { + return Vec::new(); + }; + let first = offset / PAGE; + let Some(touched) = pages.get(first..end.div_ceil(PAGE)) else { + return Vec::new(); + }; + let mut pieces: Vec<(usize, usize)> = Vec::new(); + { + let physical = physical(); + for (i, page) in touched.iter().enumerate() { + let Some(addresses) = physical.pages.get(page).and_then(|slice| physical.shown.get(&slice.key(0))) else { + continue; + }; + // The bytes of this page that the write covers. + let lo = if i == 0 { offset % PAGE } else { 0 }; + let hi = (end - (first + i) * PAGE).min(PAGE); + pieces.extend(addresses.iter().map(|&at| (at + lo, hi - lo))); + } + } + pieces.sort_unstable(); + let mut runs: Vec<(usize, usize)> = Vec::new(); + for (at, bytes) in pieces { + match runs.last_mut() { + Some((start, n)) if *start + *n == at => *n += bytes, + _ => runs.push((at, bytes)), + } + } + runs +} + +/// Bytes `[offset, offset + len)` of `pages` have been written through a +/// view of our own: the GPU side is told at every title address that +/// shows them (`leonida_gpu::title_memory_written`; what it does with it +/// is `LEONIDA_PAGE_WRITES`' to say, and it counts either way). Call when +/// the bytes are there, and without the page table's lock ([`shown_at`] +/// takes and leaves it). +pub(crate) fn pages_written(pages: &[usize], offset: usize, len: usize) { + for (at, bytes) in shown_at(pages, offset, len) { + leonida_gpu::title_memory_written(at, bytes, true); + } +} + +/// Maps `n` pages at `address`, in place of what is mapped there; null +/// `pages` unmaps. Returns `address`, or null if a page or the host fails. +pub extern "system" fn XMemMapPhysicalPages( + address: *mut c_void, + n: usize, + pages: *const usize, +) -> *mut c_void { + let base = address as usize; + let mut physical = physical(); + // Until the pages are mapped again: `unmap` takes whole views away and + // maps what stays of them again, and a mapped view is a reservation + // until it is committed. A read of title memory in place must not fall + // into that gap (`leonida_gpu::title_memory_remapping`). + let _changing = leonida_gpu::title_memory_remapping(); + unmap(&mut physical, base, n * PAGE); + if pages.is_null() { + return address; + } + // SAFETY: the title passes `n` page numbers. + let pages = unsafe { std::slice::from_raw_parts(pages, n) }; + let mut i = 0; + while i < n { + let Some(first) = physical.pages.get(&pages[i]).cloned() else { + tracing::warn!(page = pages[i], "XMemMapPhysicalPages: unknown page"); + return std::ptr::null_mut(); + }; + // One view per run of consecutive slices of one section. + let run = 1 + pages[i + 1..] + .iter() + .zip(1..) + .take_while(|&(page, k)| { + physical.pages.get(page).is_some_and(|s| { + Arc::ptr_eq(&s.section, &first.section) && s.index == first.index + k + }) + }) + .count(); + if !map(&mut physical, base + i * PAGE, run * PAGE, first) { + return std::ptr::null_mut(); + } + i += run; + } + address +} + +/// One page at each address; null `pages`, or a page number 0, unmaps +/// (the title passes 0 for addresses to clear). +pub extern "system" fn XMemMapPhysicalPagesScatter( + addresses: *const *mut c_void, + n: usize, + pages: *const usize, +) -> BOOL { + if addresses.is_null() { + return 0; + } + for i in 0..n { + // SAFETY: the title passes `n` addresses and, unless null, `n` pages. + let (address, page) = unsafe { + ( + *addresses.add(i), + if pages.is_null() || *pages.add(i) == 0 { + std::ptr::null() + } else { + pages.add(i) + }, + ) + }; + if XMemMapPhysicalPages(address, 1, page).is_null() { + return 0; + } + } + 1 +} + +/// Maps the physical pages shown at `[from, from + len)` at `to` as well, +/// in place of what `to` shows; `from` 0 unmaps. The GPU's page-mapping +/// copies (`leonida_gpu`, queue `CopyPageMappingsBatchX`): +/// the title maps pages into a pool view, then has the GPU map them into its tiled +/// heap. Page by page; false if a source page is not mapped physical memory. +pub fn map_alias(to: u64, from: u64, len: u64) -> bool { + let (to, from, len) = (to as usize, from as usize, len as usize); + let mut physical = physical(); + // As in `XMemMapPhysicalPages`: no read in place meets the gap. + let _changing = leonida_gpu::title_memory_remapping(); + unmap(&mut physical, to, len); + for k in (0..len).step_by(PAGE) { + if from == 0 { + break; + } + let at = from + k; + let Some(slice) = physical + .views + .range(..=at) + .next_back() + .filter(|(base, (size, _))| at < *base + size) + .map(|(base, (_, s))| Slice { + index: s.index + (at - base) / PAGE, + section: s.section.clone(), + }) + else { + return false; + }; + if !map(&mut physical, to + k, PAGE, slice) { + return false; + } + } + true +} + +/// Maps `slice` and the slices after it over `[base, base + len)`, which +/// must lie in one placeholder. +fn map(physical: &mut Physical, base: usize, len: usize, slice: Slice) -> bool { + // SAFETY: splits the placeholder around the range (failing harmlessly + // when the range is the whole placeholder), then maps the section + // there; both act only on placeholders. + let view = unsafe { + VirtualFree( + base as *mut c_void, + len, + MEM_RELEASE | MEM_PRESERVE_PLACEHOLDER, + ); + MapViewOfFile3( + slice.section.0, + GetCurrentProcess(), + base as *const c_void, + (slice.index * PAGE) as u64, + len, + MEM_REPLACE_PLACEHOLDER, + PAGE_READWRITE, + std::ptr::null_mut(), + 0, + ) + }; + if view.Value as usize != base { + tracing::warn!( + address = format_args!("{base:#x}"), + len, + error = %std::io::Error::last_os_error(), + "mapping physical pages failed (not a placeholder?)" + ); + return false; + } + if !commit(base, len) { + // SAFETY: the view just mapped, back to a placeholder. + unsafe { UnmapViewOfFile2(GetCurrentProcess(), view, MEM_PRESERVE_PLACEHOLDER) }; + return false; + } + // New contents, read-write: the GPU side's copies no longer guard it. + leonida_gpu::title_memory_remapped(base, len); + // What the range shows now, for the GPU side's in-place census. + leonida_gpu::title_memory_view(base, len, slice.section.0 as usize, (slice.index * PAGE) as u64); + for k in 0..len.div_ceil(PAGE) { + physical.shown.entry(slice.key(k)).or_default().push(base + k * PAGE); + } + physical.views.insert(base, (len, slice)); + true +} + +/// Commits the section pages a view shows (once per page, whichever view). +fn commit(base: usize, len: usize) -> bool { + if on_wine() { + return true; // sections are committed whole there + } + // SAFETY: `[base, base + len)` is a view of a reserved section. + if !unsafe { VirtualAlloc(base as *const c_void, len, MEM_COMMIT, PAGE_READWRITE) }.is_null() { + return true; + } + let error = std::io::Error::last_os_error(); + if error.raw_os_error() == Some(ERROR_COMMITMENT_LIMIT as i32) { + let mut info = PERFORMANCE_INFORMATION { + cb: size_of::() as u32, + ..Default::default() + }; + // SAFETY: the buffer and size describe a writable PERFORMANCE_INFORMATION. + let queried = unsafe { K32GetPerformanceInfo(&mut info, info.cb) } != 0; + leonida_loader::log_crash(&commit_limit_message(len, &error, queried.then_some(&info))); + } else { + tracing::warn!(len, %error, "committing physical pages failed"); + } + false +} + +fn commit_limit_message( + len: usize, + error: &std::io::Error, + info: Option<&PERFORMANCE_INFORMATION>, +) -> String { + let mut message = format!( + "Leonida Legacy: Windows commit limit reached while committing {len} bytes of physical pages: {error}.\n" + ); + if let Some(info) = info { + use std::fmt::Write; + + let committed = info.CommitTotal * info.PageSize / MIB; + let limit = info.CommitLimit * info.PageSize / MIB; + let _ = writeln!( + message, + "System commit: {committed} MiB of {limit} MiB in use." + ); + } + message.push_str( + "Close other applications or increase the Windows paging file size, then retry.\n", + ); + message +} + +/// Returns `[base, base + len)` to placeholders; views reaching past it +/// are mapped again outside it. +fn unmap(physical: &mut Physical, base: usize, len: usize) { + // No bytes: no view to return. The search below would still find the + // view holding `base` and cut it in two there, and its range of views + // starting inside would run backwards (which `BTreeMap` panics on). + if len == 0 { + return; + } + let end = base + len; + // Views do not overlap: the one holding `base`, then those starting + // inside (the GPU's page mappings make one view per page). + let first = physical + .views + .range(..=base) + .next_back() + .filter(|(at, (size, _))| *at + size > base) + .map(|(at, _)| *at); + let hit: Vec = first + .into_iter() + .chain(physical.views.range(base + 1..end).map(|(at, _)| *at)) + .collect(); + for at in hit { + let Some((size, slice)) = physical.views.remove(&at) else { + continue; + }; + for k in 0..size.div_ceil(PAGE) { + let key = slice.key(k); + if let Some(addresses) = physical.shown.get_mut(&key) { + addresses.retain(|&a| a != at + k * PAGE); + if addresses.is_empty() { + physical.shown.remove(&key); + } + } + } + leonida_gpu::title_memory_remapped(at, size); + // SAFETY: a view we mapped; it becomes a placeholder again. + unsafe { + UnmapViewOfFile2( + GetCurrentProcess(), + MEMORY_MAPPED_VIEW_ADDRESS { + Value: at as *mut c_void, + }, + MEM_PRESERVE_PLACEHOLDER, + ) + }; + if at < base { + map(physical, at, base - at, slice.clone()); + } + if at + size > end { + let index = slice.index + (end - at) / PAGE; + map(physical, end, at + size - end, Slice { index, ..slice }); + } + } +} + +/// The oldest layout we know; newer titles pass other flag values (Minecraft +/// 0x20000001) and read the same leading fields. +#[repr(C)] +#[derive(Debug, Default)] +pub struct WorkingSet { + pub title_limit: usize, + pub title_used: usize, + pub tools_limit: usize, + pub tools_used: usize, + pub stack_used: u32, + pub physical_pages: u32, + pub gpu_optimal_limit: usize, + pub gpu_optimal_used: usize, + pub tools_gpu_optimal_limit: usize, + pub tools_gpu_optimal_used: usize, + pub kernel_pool_used: u32, + pub kernel_pool_limit: u32, +} + +/// The title's budget and our process's commit as what it uses. No tools +/// memory: a retail console. +// shortcut: all fields are filled whatever the flags ask for, and use is +// not split by bandwidth class (GPU-optimal use reads 0); track +// allocations per class if a title budgets from that field. +pub extern "system" fn XMemGetWorkingSetStatistics(_which: u32, out: *mut WorkingSet) -> BOOL { + if out.is_null() { + return 0; + } + let mut counters = PROCESS_MEMORY_COUNTERS { + cb: size_of::() as u32, + ..Default::default() + }; + // SAFETY: our own process and a sized structure. + unsafe { K32GetProcessMemoryInfo(GetCurrentProcess(), &mut counters, counters.cb) }; + let (gpu_optimal, standard) = leonida_gpu::console::current().title_memory(); + let stats = WorkingSet { + title_limit: gpu_optimal + standard - TRANSFERRED.load(Ordering::Relaxed), + title_used: counters.PagefileUsage, + gpu_optimal_limit: gpu_optimal, + ..Default::default() + }; + // What the title is told, logged at the first asking and at every + // 1,024th: "used" is all the process has committed, the layer's own + // memory and the card's included (27 GB in run 60's gameplay against a + // limit of 13.5 GB). A title that budgets its streaming from these two + // figures believes it is far over its limit. + // shortcut: the figure is not yet the title's own memory alone (its + // heaps and the pages it mapped); count those if this line shows the + // title asking. + static ASKED: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + let asked = ASKED.fetch_add(1, Ordering::Relaxed); + if asked.is_multiple_of(1024) { + tracing::info!( + asked = asked + 1, + which = _which, + limit_mb = stats.title_limit >> 20, + used_mb = stats.title_used >> 20, + "the title asks how much memory it uses" + ); + } + // SAFETY: checked non-null; the title passes room for the structure. + unsafe { out.write(stats) }; + 1 +} + +/// Hands title memory (standard, in 2 MiB pages) to the system. The other +/// transfers involve tools memory, which a retail console has none of. +pub extern "system" fn XMemTransferMemory(kind: u32, size: usize) -> BOOL { + const TITLE_TO_SYSTEM: u32 = 0; + tracing::info!(kind, size, "XMemTransferMemory"); + if size == 0 { + return 1; + } + let Some(size) = size.checked_next_multiple_of(2 * MIB) else { + return 0; + }; + let standard = leonida_gpu::console::current().title_memory().1; + let moved = kind == TITLE_TO_SYSTEM + && TRANSFERRED + .fetch_update(Ordering::Relaxed, Ordering::Relaxed, |t| { + t.checked_add(size).filter(|&t| t <= standard) + }) + .is_ok(); + moved.into() +} + +pub(crate) fn module() -> HleModule { + HleModule { + name: "xmem", + dlls: &["xmem.dll"], + exports: vec![ + hle_export!(XMemAlloc), + hle_export!(XMemFree), + hle_export!(XMemAllocDefault), + hle_export!(XMemFreeDefault), + hle_export!(XMemIsToolsMemAvailable), + hle_export!(XMemAllocatePhysicalPages), + hle_export!(XMemFreePhysicalPages), + hle_export!(XMemMapPhysicalPages), + hle_export!(XMemMapPhysicalPagesScatter), + hle_export!(XMemVirtualAlloc), + hle_export!(XMemVirtualQuery), + hle_export!(XMemGetWorkingSetStatistics), + hle_export!(XMemTransferMemory), + ], + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn query(address: *const c_void) -> BasicInformation { + // SAFETY: plain data; zero is a valid value. + let mut info: BasicInformation = unsafe { std::mem::zeroed() }; + // SAFETY: a pseudo handle needs no closing. + let process = unsafe { GetCurrentProcess() }; + assert_eq!(XMemVirtualQuery(process, address, &mut info), 1); + info + } + + #[test] + fn alloc_honours_alignment_and_frees() { + for (field, align) in [(0, 16), (4, 16), (0xc, 4096), (0x10, 64 * 1024)] { + let attributes = field << ALIGNMENT_SHIFT | 1 << 29; // a graphics type + let p = XMemAlloc(100, attributes); + assert!(!p.is_null()); + assert_eq!(p as usize % align, 0, "field {field:#x}"); + // SAFETY: 100 bytes were allocated. + unsafe { p.cast::().write_bytes(0xab, 100) }; + XMemFree(p, attributes); + } + let p = XMemAlloc(4096, ALLOC_32BIT); + assert!(!p.is_null() && (p as usize) < 1 << 32); + XMemFree(p, ALLOC_32BIT); + } + + #[test] + fn virtual_alloc_meets_console_constraints() { + const GPU_READ_WRITE: u32 = 0x2000; + let p = XMemVirtualAlloc( + std::ptr::null_mut(), + 4 * MIB, + PAGES_2M | MEM_RESERVE | MEM_COMMIT, + GRAPHICS | 7 << 12, // 40-bit addresses + PAGE_READWRITE | GPU_READ_WRITE, + ); + assert!(!p.is_null()); + assert_eq!(p as usize % (2 * MIB), 0); + assert!((p as usize) < 1 << 40); + let info = query(p); + assert_eq!(info.host.State, MEM_COMMIT); + assert_eq!(info.host.Protect, PAGE_READWRITE); + assert_eq!(info.flags & GRAPHICS, GRAPHICS); + // Write-watched, for the GPU side's copies. + let (mut found, mut count, mut granularity) = ([0usize; 4], 4, 0); + // SAFETY: room for `count` addresses. + let watched = unsafe { + windows_sys::Win32::System::Memory::GetWriteWatch( + 0, + p, + 4 * MIB, + found.as_mut_ptr().cast(), + &mut count, + &mut granularity, + ) + }; + assert_eq!(watched, 0); + // SAFETY: our own reservation. + assert_ne!(unsafe { VirtualFree(p, 0, MEM_RELEASE) }, 0); + assert_eq!(query(p).flags, 0); + // No address field: above the 32-bit range and below 2^40, where + // the console keeps it. + let p = XMemVirtualAlloc( + std::ptr::null_mut(), + 16 << 30, + MEM_RESERVE, + GRAPHICS, + PAGE_NOACCESS, + ); + assert!(!p.is_null() && (p as usize) >= 1 << 32, "{p:p}"); + assert!((p as usize) + (16 << 30) <= 1 << 40, "{p:p}"); + // SAFETY: our own reservation. + assert_ne!(unsafe { VirtualFree(p, 0, MEM_RELEASE) }, 0); + } + + #[test] + fn transfers_shrink_the_title_budget() { + let mut before = WorkingSet::default(); + assert_eq!(XMemGetWorkingSetStatistics(0x2000_0001, &mut before), 1); + assert!(before.title_used > 0); + assert_eq!(XMemTransferMemory(0, 128 * MIB - 1), 1); + assert_eq!(XMemTransferMemory(2, MIB), 0, "no tools memory"); + let standard = leonida_gpu::console::current().title_memory().1; + assert_eq!(XMemTransferMemory(0, standard), 0, "over budget"); + let mut after = WorkingSet::default(); + XMemGetWorkingSetStatistics(0x2000_0001, &mut after); + assert_eq!(before.title_limit - after.title_limit, 128 * MIB); + } + + #[test] + fn statistics_have_the_console_layout() { + assert_eq!(size_of::(), 0x50); + assert_eq!(size_of::(), 0x40); + assert_eq!(std::mem::offset_of!(WorkingSet, gpu_optimal_limit), 0x28); + } + + #[test] + fn commit_limit_report_includes_request_and_system_commit() { + let error = std::io::Error::from_raw_os_error(ERROR_COMMITMENT_LIMIT as i32); + let info = PERFORMANCE_INFORMATION { + CommitTotal: 512, + CommitLimit: 768, + PageSize: 4096, + ..Default::default() + }; + let report = commit_limit_message(4 * MIB, &error, Some(&info)); + assert!(report.contains("4194304 bytes")); + assert!(report.contains("2 MiB of 3 MiB in use")); + let fallback = commit_limit_message(4 * MIB, &error, None); + for report in [&report, &fallback] { + assert!(report.contains("os error 1455")); + assert!(report.contains("Windows paging file size")); + } + assert!(!fallback.contains("System commit:")); + } + + #[test] + fn physical_pages_map_alias_and_unmap() { + let mut pages = [0usize; 3]; + let mut n = 3; + assert_eq!(XMemAllocatePhysicalPages(0, &mut n, pages.as_mut_ptr()), 1); + assert_eq!(n, 3); + // Packed into 21 bits as `number >> 4`, as the title keeps them. + for p in pages { + assert_eq!((p >> 4 & 0x1f_ffff) << 4, p); + } + // Reservations of 64 KiB pages, as titles make them for mapping. + let reserve = || { + XMemVirtualAlloc( + std::ptr::null_mut(), + 3 * PAGE, + MEM_RESERVE | PAGES_64K, + 0, + PAGE_READWRITE, + ) + }; + let (a, b) = (reserve(), reserve()); + assert!(!a.is_null() && !b.is_null()); + let at = |p: *mut c_void, page: usize| p.wrapping_byte_add(page * PAGE); + assert_eq!(XMemMapPhysicalPages(a, 3, pages.as_ptr()), a); + + // The same page at a second address shows the same bytes. + assert_eq!( + XMemMapPhysicalPages(at(b, 1), 1, pages[2..].as_ptr()), + at(b, 1) + ); + // SAFETY: both pages are mapped read-write. + unsafe { + at(a, 2).cast::().write(7); + assert_eq!(at(b, 1).cast::().read(), 7); + a.cast::().write(1); + } + // Writes into pages (DirectStorage's) show through their views. + assert!(write_physical(&pages[2..], 1, &[9])); + // SAFETY: mapped read-write. + assert_eq!(unsafe { at(b, 1).cast::().add(1).read() }, 9); + + // Unmapping the middle page keeps its neighbours. + assert_eq!( + XMemMapPhysicalPages(at(a, 1), 1, std::ptr::null()), + at(a, 1) + ); + assert_eq!(query(at(a, 1)).host.State, MEM_RESERVE); + assert_eq!(query(a).host.State, MEM_COMMIT); + assert_eq!(query(at(a, 2)).host.State, MEM_COMMIT); + // SAFETY: still mapped. + assert_eq!(unsafe { at(a, 2).cast::().read() }, 7); + + // A scattered page lands in the hole. + let addresses = [at(a, 1)]; + assert_eq!( + XMemMapPhysicalPagesScatter(addresses.as_ptr(), 1, pages.as_ptr()), + 1 + ); + // SAFETY: page 0 is now mapped at both `a` and `a + PAGE`. + assert_eq!(unsafe { at(a, 1).cast::().read() }, 1); + // Page number 0 unmaps. + assert_eq!( + XMemMapPhysicalPagesScatter(addresses.as_ptr(), 1, [0usize].as_ptr()), + 1 + ); + assert_eq!(query(at(a, 1)).host.State, MEM_RESERVE); + // The GPU's page-mapping copy: what `a + 2 pages` shows, at `b`. + assert!(map_alias(b as u64, at(a, 2) as u64, PAGE as u64)); + // SAFETY: mapped read-write. + assert_eq!(unsafe { b.cast::().read() }, 7); + assert!(map_alias(b as u64, 0, PAGE as u64)); + assert_eq!(query(b).host.State, MEM_RESERVE); + assert!(!map_alias(b as u64, at(a, 1) as u64, PAGE as u64)); + assert_eq!(XMemFreePhysicalPages(3, pages.as_ptr()), 1); + assert_eq!(XMemIsToolsMemAvailable(), 0); + } + + /// A thread that reads a mapped page in place, as the GPU side reads a + /// texture, never meets the moment in which the runtime has taken the + /// page's view away to map it again: mapping the same pages at the same + /// address unmaps the view and maps a new one, and without the lock the + /// reader faults on a page "reserved, never committed" (the crashes of + /// runs 71 and 74). + #[test] + fn a_read_in_place_never_meets_the_gap_of_a_remapping() { + use std::sync::atomic::{AtomicBool, Ordering}; + let mut pages = [0usize; 3]; + let mut n = 3; + assert_eq!(XMemAllocatePhysicalPages(0, &mut n, pages.as_mut_ptr()), 1); + let a = XMemVirtualAlloc( + std::ptr::null_mut(), + 3 * PAGE, + MEM_RESERVE | PAGES_64K, + 0, + PAGE_READWRITE, + ); + assert!(!a.is_null()); + assert_eq!(XMemMapPhysicalPages(a, 3, pages.as_ptr()), a); + // SAFETY: mapped read-write. + unsafe { a.cast::().write(1) }; + let first = a as usize; + let stop = std::sync::Arc::new(AtomicBool::new(false)); + let reader = { + let stop = stop.clone(); + std::thread::spawn(move || { + let mut reads = 0u64; + while !stop.load(Ordering::Relaxed) { + let _reading = leonida_gpu::title_memory_reading(); + // SAFETY: the page is mapped whenever no change of + // mapping is under way, and none is while `_reading` + // is held. + assert_eq!(unsafe { (first as *const u8).read_volatile() }, 1); + reads += 1; + } + reads + }) + }; + for _ in 0..2000 { + // The same pages at the same address: the view goes and comes + // back, with the same bytes. + assert_eq!(XMemMapPhysicalPages(a, 3, pages.as_ptr()), a); + } + stop.store(true, Ordering::Relaxed); + assert!(reader.join().expect("the reader never faulted") > 0); + assert_eq!(XMemMapPhysicalPages(a, 3, std::ptr::null()), a); + assert_eq!(XMemFreePhysicalPages(3, pages.as_ptr()), 1); + } + + #[test] + fn mapping_no_pages_changes_nothing() { + let pages = allocate(2); + let a = XMemVirtualAlloc( + std::ptr::null_mut(), + 2 * PAGE, + MEM_RESERVE | PAGES_64K, + 0, + PAGE_READWRITE, + ); + assert!(!a.is_null()); + assert_eq!(XMemMapPhysicalPages(a, 2, pages.as_ptr()), a); + // SAFETY: both pages are mapped read-write. + unsafe { a.cast::().write(5) }; + let second = a.wrapping_byte_add(PAGE); + + // A count of 0 at the start of a view, inside it and past it: with + // pages, without (an unmap), and as the GPU's page-mapping copy. + for at in [a, second, a.wrapping_byte_add(2 * PAGE)] { + assert_eq!(XMemMapPhysicalPages(at, 0, pages.as_ptr()), at); + assert_eq!(XMemMapPhysicalPages(at, 0, std::ptr::null()), at); + assert!(map_alias(at as u64, a as u64, 0)); + assert!(map_alias(at as u64, 0, 0)); + } + + // The view is still the one view it was. + let view = physical().views.get(&(a as usize)).map(|v| v.0); + assert_eq!(view, Some(2 * PAGE)); + assert_eq!(query(a).host.State, MEM_COMMIT); + assert_eq!(query(second).host.State, MEM_COMMIT); + // SAFETY: still mapped. + assert_eq!(unsafe { a.cast::().read() }, 5); + + // A count of 1 still unmaps that page alone. + assert_eq!(XMemMapPhysicalPages(second, 1, std::ptr::null()), second); + assert_eq!(query(second).host.State, MEM_RESERVE); + assert_eq!(query(a).host.State, MEM_COMMIT); + assert_eq!(XMemMapPhysicalPages(a, 1, std::ptr::null()), a); + assert_eq!(XMemFreePhysicalPages(2, pages.as_ptr()), 1); + } + + /// `n` pages of one new allocation. + fn allocate(n: usize) -> Vec { + let (mut pages, mut given) = (vec![0; n], n); + assert_eq!( + XMemAllocatePhysicalPages(0, &mut given, pages.as_mut_ptr()), + 1 + ); + assert_eq!(given, n); + pages + } + + /// The bytes of one page, through a view of our own. + fn page_bytes(page: usize) -> Vec { + let slice = physical().pages.get(&page).cloned().expect("known page"); + View::map(&slice, 1).expect("mapped").bytes().to_vec() + } + + #[test] + fn runs_group_consecutive_pages_of_one_allocation() { + let (a, b) = (allocate(3), allocate(1)); + let lengths = |pages: &[usize], offset, len| { + runs(pages, offset, len).map(|r| r.iter().map(|&(_, n)| n).collect::>()) + }; + assert_eq!(lengths(&a, 0, 3 * PAGE), Some(vec![3])); + // Only the pages the bytes reach. + assert_eq!(lengths(&a, PAGE + 5, 10), Some(vec![1])); + assert_eq!(lengths(&a, PAGE - 1, 2), Some(vec![2])); + assert_eq!(lengths(&a, 0, 0), Some(vec![])); + // Out of order, or across allocations: one run each. + assert_eq!( + lengths(&[a[0], a[2], a[1]], 0, 3 * PAGE), + Some(vec![1, 1, 1]) + ); + assert_eq!(lengths(&[a[1], a[2], b[0]], 0, 3 * PAGE), Some(vec![2, 1])); + // A slice that follows on in another section starts a run. + assert_eq!(lengths(&[b[0], a[1]], 0, 2 * PAGE), Some(vec![1, 1])); + // Too few pages for the bytes, or an unknown one. + assert_eq!(lengths(&a, 0, 3 * PAGE + 1), None); + assert_eq!(lengths(&[a[0], 0x10], 0, 2 * PAGE), None); + assert_eq!(lengths(&a, usize::MAX, 2), None); + assert_eq!(XMemFreePhysicalPages(3, a.as_ptr()), 1); + assert_eq!(XMemFreePhysicalPages(1, b.as_ptr()), 1); + } + + #[test] + fn writes_cross_runs_and_allocations() { + let (a, b) = (allocate(2), allocate(1)); + let pages = [a[0], a[1], b[0]]; + let data: Vec = (0..2 * PAGE + 64).map(|i| (i * 7 % 251) as u8).collect(); + let offset = PAGE - 32; + // Past the third page: the second run is too short. + assert!(!write_physical(&pages, offset, &data)); + assert!(write_physical(&pages, offset, &data[..2 * PAGE])); + let seen: Vec = pages.iter().flat_map(|&p| page_bytes(p)).collect(); + assert!(seen[..offset].iter().all(|&b| b == 0), "before the offset"); + assert_eq!(seen[offset..offset + 2 * PAGE], data[..2 * PAGE]); + assert!(seen[offset + 2 * PAGE..].iter().all(|&b| b == 0), "after"); + assert!( + !write_physical(&[a[0], 0x10], 0, &data[..PAGE + 1]), + "unknown page" + ); + assert_eq!(XMemFreePhysicalPages(2, a.as_ptr()), 1); + assert_eq!(XMemFreePhysicalPages(1, b.as_ptr()), 1); + } + + /// Pages say where the title has them mapped, byte for byte (after + /// fork PR #571's test; its runs are whole pages). + #[test] + fn pages_say_where_they_are_mapped() { + let pages = allocate(3); + let reserve = |n: usize| { + let at = XMemVirtualAlloc(std::ptr::null_mut(), n * PAGE, MEM_RESERVE | PAGES_64K, 0, PAGE_READWRITE); + assert!(!at.is_null()); + at + }; + // `b` keeps a page unmapped at either end, so that no run at `b` + // ever touches one at `a`, wherever the host puts the two. + let (a, b) = (reserve(3), reserve(4)); + assert!(shown_at(&pages, 0, 3 * PAGE).is_empty(), "mapped nowhere"); + // All three at `a`; the last two at `b`, from its second page on. + assert_eq!(XMemMapPhysicalPages(a, 3, pages.as_ptr()), a); + let second = b.wrapping_byte_add(PAGE); + assert_eq!(XMemMapPhysicalPages(second, 2, pages[1..].as_ptr()), second); + let (a, second) = (a as usize, second as usize); + let sorted = |mut runs: Vec<(usize, usize)>| { + runs.sort_unstable(); + runs + }; + assert_eq!(shown_at(&pages, 0, PAGE), vec![(a, PAGE)]); + // A request for part of a page names those bytes alone. + assert_eq!(shown_at(&pages, 0x4000, 0x3000), vec![(a + 0x4000, 0x3000)]); + // Across two pages, shown at two addresses each: one run at each. + assert_eq!( + shown_at(&pages, PAGE + 1, PAGE), + sorted(vec![(a + PAGE + 1, PAGE), (second + 1, PAGE)]) + ); + // A page unmapped in the middle of a view: the rest still shows. + let middle = (a + PAGE) as *mut c_void; + assert_eq!(XMemMapPhysicalPages(middle, 1, std::ptr::null()), middle); + assert_eq!( + shown_at(&pages, 0, 3 * PAGE), + sorted(vec![(a, PAGE), (a + 2 * PAGE, PAGE), (second, 2 * PAGE)]) + ); + // Too few pages for the bytes: nothing (the write fails too). + assert!(shown_at(&pages, 0, 3 * PAGE + 1).is_empty()); + for (at, n) in [(a, 3), (second, 2)] { + let at = at as *mut c_void; + assert_eq!(XMemMapPhysicalPages(at, n, std::ptr::null()), at); + } + assert!(shown_at(&pages, 0, 3 * PAGE).is_empty()); + assert_eq!(XMemFreePhysicalPages(3, pages.as_ptr()), 1); + } + + #[test] + fn page_windows_cover_one_run_in_place() { + let (a, b) = (allocate(3), allocate(1)); + let mut window = page_window(&a, PAGE + 3, PAGE).expect("one run"); + assert_eq!(window.bytes().len(), PAGE); + window.bytes().fill(0x5a); + drop(window); + let (second, third) = (page_bytes(a[1]), page_bytes(a[2])); + assert!(second[..3].iter().all(|&b| b == 0)); + assert!(second[3..].iter().all(|&b| b == 0x5a)); + assert!(third[..3].iter().all(|&b| b == 0x5a)); + assert!(third[3..].iter().all(|&b| b == 0)); + // Several runs, or an unknown page: no window. + assert!(page_window(&[a[0], b[0]], 0, PAGE + 1).is_none()); + assert!(page_window(&[a[1], a[0]], 0, PAGE + 1).is_none()); + assert!(page_window(&[0x10], 0, 1).is_none()); + // One page of several is still one run. + assert!(page_window(&[a[0], b[0]], 0, PAGE).is_some()); + assert_eq!(XMemFreePhysicalPages(3, a.as_ptr()), 1); + assert_eq!(XMemFreePhysicalPages(1, b.as_ptr()), 1); + } +} diff --git a/crates/leonida-hle/src/modules/xnetworking.rs b/crates/leonida-hle/src/modules/xnetworking.rs new file mode 100644 index 000000000..c0b21a3f2 --- /dev/null +++ b/crates/leonida-hle/src/modules/xnetworking.rs @@ -0,0 +1,210 @@ +//! XNetworking as an offline console answers it: the network stack is up +//! (titles wait for that before anything else) but reaches nothing, the +//! connectivity hint never changes, and the title's security allow list, +//! which comes from the service, cannot be fetched. +#![allow(clippy::not_unsafe_ptr_arg_deref)] + +use std::ffi::{c_char, c_void}; + +use super::xasync::{self, AsyncBlock}; +use super::xgameruntime::{ + Guid, HRESULT, Interface, Methods, Object, add_ref, missing, put, text, token, +}; + +pub const PROVIDER: Guid = Guid::new( + 0x37e5_6907, + 0x2f10, + 0x41e8, + [0xb7, 0x2f, 0x36, 0xed, 0xb1, 0x85, 0x33, 0x1a], +); + +/// As the title (2026) asks for it; the slots it calls (0x18-0x88) +/// take the same arguments as under the provider's own id (older titles). +pub const IID_2026: Guid = Guid::new( + 0xbf23_46b2, + 0x39af, + 0x4658, + [0xb5, 0xea, 0x44, 0x71, 0x3c, 0x7e, 0x83, 0xb3], +); + +pub static OBJECT: Object = Object::new("networking", &VTABLE); +pub const INTERFACES: &[Interface] = + &[(PROVIDER, PROVIDER, &OBJECT), (PROVIDER, IID_2026, &OBJECT)]; + +/// `HRESULT_FROM_WIN32(ERROR_NETWORK_UNREACHABLE)`: what needs the service. +pub const UNREACHABLE: HRESULT = 0x8007_04CF_u32 as i32; + +/// The documented default for the preferred local UDP multiplayer port. +const UDP_PORT: u16 = 3074; + +/// The connectivity hint: level, cost, interface type, then four flags. +#[repr(C)] +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct ConnectivityHint { + pub level: u32, + pub cost: u32, + pub interface_type: u32, + pub initialized: bool, + pub approaching_data_limit: bool, + pub over_data_limit: bool, + pub roaming: bool, +} + +/// Initialized, no connectivity (level 1), cost unknown (0). +const OFFLINE: ConnectivityHint = ConnectivityHint { + level: 1, + cost: 0, + interface_type: 0, + initialized: true, + approaching_data_limit: false, + over_data_limit: false, + roaming: false, +}; + +type This = *const Object; + +extern "system" fn udp_port(_: This, out: *mut u16) -> HRESULT { + put(out, UDP_PORT) +} + +/// Tells our port queries apart from other calls on the same block. +static PORT: u8 = 0; + +extern "system" fn udp_port_async(_: This, block: *mut AsyncBlock) -> HRESULT { + xasync::finished_with(block, (&raw const PORT).cast(), Ok(xasync::bytes(UDP_PORT))) +} +extern "system" fn udp_port_result(_: This, block: *mut AsyncBlock, out: *mut u16) -> HRESULT { + xasync::result(block, (&raw const PORT).cast(), out) +} + +static SECURITY: u8 = 0; + +/// The allow list comes from the service: unreachable offline. +extern "system" fn security_info_async( + _: This, + url: *const c_char, + block: *mut AsyncBlock, +) -> HRESULT { + tracing::debug!( + url = text(url).unwrap_or_default(), + "security information: offline" + ); + xasync::finished(block, (&raw const SECURITY).cast(), UNREACHABLE) +} +extern "system" fn security_info_size(_: This, block: *mut AsyncBlock, out: *mut usize) -> HRESULT { + xasync::XAsyncGetResultSize(block, out) +} +extern "system" fn security_info_result( + _: This, + block: *mut AsyncBlock, + size: usize, + used: *mut usize, + buffer: *mut u8, + _info: *mut *const c_void, +) -> HRESULT { + xasync::XAsyncGetResult( + block, + (&raw const SECURITY).cast(), + size, + buffer.cast(), + used, + ) +} + +/// No security information can exist offline, so no certificate passes. +extern "system" fn verify_certificate( + _: This, + _request: *mut c_void, + _info: *const c_void, +) -> HRESULT { + UNREACHABLE +} + +extern "system" fn connectivity_hint(_: This, out: *mut ConnectivityHint) -> HRESULT { + put(out, OFFLINE) +} + +/// The hint never changes offline, so the callback never runs. +extern "system" fn register( + _: This, + _queue: *const c_void, + _context: *mut c_void, + _callback: *const c_void, + out: *mut u64, +) -> HRESULT { + put(out, token()) +} +extern "system" fn unregister(_: This, _token: u64, _wait: bool) -> bool { + true +} + +static VTABLE: Methods<18> = Methods([ + missing::<0> as *const (), + add_ref as *const (), + add_ref as *const (), + udp_port as *const (), // 0x18 + udp_port_async as *const (), // 0x20 + udp_port_result as *const (), // 0x28 + missing::<6> as *const (), // 0x30 port changed + missing::<7> as *const (), // 0x38 + security_info_async as *const (), // 0x40 + security_info_size as *const (), // 0x48 + security_info_result as *const (), // 0x50 + missing::<11> as *const (), // 0x58 the same for UTF-16 URLs + missing::<12> as *const (), // 0x60 + missing::<13> as *const (), // 0x68 + verify_certificate as *const (), // 0x70 + connectivity_hint as *const (), // 0x78 + register as *const (), // 0x80 hint changed (never) + unregister as *const (), // 0x88 +]); + +#[cfg(test)] +mod tests { + use super::*; + use crate::modules::xgameruntime::{S_OK, method}; + + fn block() -> AsyncBlock { + AsyncBlock { + queue: std::ptr::null(), + context: std::ptr::null_mut(), + callback: None, + internal: [0; 4], + } + } + + #[test] + fn offline_but_initialized() { + let this: This = &OBJECT; + type Hint = extern "system" fn(This, *mut ConnectivityHint) -> HRESULT; + let mut hint = OFFLINE; + hint.initialized = false; + assert_eq!(method::(&OBJECT, 0x78)(this, &mut hint), S_OK); + assert!(hint.initialized && hint.level == 1); + assert_eq!(size_of::(), 16); + + type Begin = extern "system" fn(This, *mut AsyncBlock) -> HRESULT; + type Port = extern "system" fn(This, *mut AsyncBlock, *mut u16) -> HRESULT; + let mut b = block(); + assert_eq!(method::(&OBJECT, 0x20)(this, &mut b), S_OK); + assert_eq!(xasync::XAsyncGetStatus(&mut b, true), S_OK); + let mut port = 0; + assert_eq!(method::(&OBJECT, 0x28)(this, &mut b, &mut port), S_OK); + assert_eq!(port, 3074); + + type Url = extern "system" fn(This, *const c_char, *mut AsyncBlock) -> HRESULT; + type Size = extern "system" fn(This, *mut AsyncBlock, *mut usize) -> HRESULT; + let mut b = block(); + let url = c"https://example.invalid/"; + assert_eq!( + method::(&OBJECT, 0x40)(this, url.as_ptr(), &mut b), + S_OK + ); + assert_eq!(xasync::XAsyncGetStatus(&mut b, true), UNREACHABLE); + let mut size = 0; + assert_eq!( + method::(&OBJECT, 0x48)(this, &mut b, &mut size), + UNREACHABLE + ); + } +} diff --git a/crates/leonida-hle/src/modules/xpackage.rs b/crates/leonida-hle/src/modules/xpackage.rs new file mode 100644 index 000000000..315faac50 --- /dev/null +++ b/crates/leonida-hle/src/modules/xpackage.rs @@ -0,0 +1,371 @@ +//! XPackage: the title's own installation, complete and launchable, with +//! every chunk ready; no other package (content, add-ons) is installed. +//! The package is the folder of the title's executable (`G:` to the title). +#![allow(clippy::not_unsafe_ptr_arg_deref)] + +use std::ffi::{c_char, c_void}; +use std::path::Path; +use std::sync::OnceLock; + +use super::xasync::{self, AsyncBlock}; +use super::xgameruntime::{ + Guid, HRESULT, Interface, Methods, Object, S_OK, add_ref, missing, put, put_string, text, token, +}; +use crate::runtime; + +pub const PROVIDER: Guid = Guid::new( + 0xaf40_6016, + 0xe850, + 0x4aa8, + [0xa8, 0x8d, 0x2f, 0x3d, 0xcb, 0x9d, 0xac, 0x7e], +); + +/// As the title (2026) asks for it. Its slots up to 0xd0 take the +/// arguments the public API lists in the same order; 0x110 uninstalls a +/// package, 0x128/0x130 mount one with UI, 0x138 enumerates packages. +pub const IID_2026: Guid = Guid::new( + 0x0b9d_556e, + 0xab70, + 0x43f4, + [0xba, 0xa0, 0x99, 0x99, 0xac, 0x4c, 0xb0, 0x40], +); + +pub static OBJECT: Object = Object::new("package", &VTABLE); +pub const INTERFACES: &[Interface] = &[(PROVIDER, IID_2026, &OBJECT)]; + +/// The documented "could not resolve an identifier for the package". +pub const NO_PACKAGE: HRESULT = 0x8924_5208_u32 as i32; + +/// Our installation's identifier: the title id in hex (titles keep it in 33 +/// bytes and hand it back to us). +pub fn identifier() -> String { + format!("{:08X}", runtime::title().id) +} + +fn is_ours(id: *const c_char) -> bool { + text(id).is_some_and(|id| id == identifier()) +} + +/// Bytes in the package folder, counted once. +fn package_bytes() -> u64 { + fn size(dir: &Path) -> u64 { + let Ok(entries) = std::fs::read_dir(dir) else { + return 0; + }; + entries + .flatten() + .map(|e| match e.metadata() { + Ok(m) if m.is_dir() => size(&e.path()), + Ok(m) => m.len(), + Err(_) => 0, + }) + .sum() + } + static BYTES: OnceLock = OnceLock::new(); + *BYTES.get_or_init(|| { + let exe = runtime::main_image().and_then(runtime::image_path); + exe.as_deref().and_then(Path::parent).map_or(0, size) + }) +} + +type This = *const Object; + +extern "system" fn current_identifier(_: This, size: usize, buffer: *mut u8) -> HRESULT { + put_string(&identifier(), size, buffer, std::ptr::null_mut()) +} + +extern "system" fn is_packaged(_: This) -> bool { + true +} + +/// Installation monitors all watch the same finished installation, so the +/// handle is a fixed address. +static MONITOR: u8 = 0; +fn monitor() -> *const c_void { + (&raw const MONITOR).cast() +} + +extern "system" fn create_monitor( + _: This, + id: *const c_char, + _selector_count: u32, + _selectors: *const c_void, + _interval_ms: u32, + _queue: *const c_void, + out: *mut *const c_void, +) -> HRESULT { + if !is_ours(id) { + return NO_PACKAGE; + } + put(out, monitor()) +} +extern "system" fn close_monitor(_: This, _: *const c_void) {} + +#[repr(C)] +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct Progress { + pub total_bytes: u64, + pub installed_bytes: u64, + pub launch_bytes: u64, + pub launchable: bool, + pub completed: bool, +} + +extern "system" fn progress(_: This, _: *const c_void, out: *mut Progress) { + let bytes = package_bytes(); + put( + out, + Progress { + total_bytes: bytes, + installed_bytes: bytes, + launch_bytes: bytes, + launchable: true, + completed: true, + }, + ); +} + +/// The installation is complete, so progress never changes. +extern "system" fn register_progress( + _: This, + _monitor: *const c_void, + _context: *mut c_void, + _callback: *const c_void, + out: *mut u64, +) -> HRESULT { + put(out, token()) +} + +/// 0: ready. +// shortcut: every selector counts as installed, including ones the +// package's layout does not have (the console answers those with an +// invalid-selector error); the title asks only about its own +// chunks, which a full install has. +extern "system" fn find_availability( + _: This, + id: *const c_char, + _selector_count: u32, + _selectors: *const c_void, + out: *mut u32, +) -> HRESULT { + if !is_ours(id) { + return NO_PACKAGE; + } + put(out, 0) +} + +extern "system" fn change_order( + _: This, + id: *const c_char, + _count: u32, + _selectors: *const c_void, +) -> HRESULT { + if is_ours(id) { S_OK } else { NO_PACKAGE } +} + +static INSTALL: u8 = 0; + +/// Everything is installed: done at once, the result is a monitor. +extern "system" fn install_chunks_async( + _: This, + id: *const c_char, + _count: u32, + _selectors: *const c_void, + _interval_ms: u32, + _suppress_confirmation: bool, + block: *mut AsyncBlock, +) -> HRESULT { + let result = if is_ours(id) { + Ok(xasync::bytes(monitor())) + } else { + Err(NO_PACKAGE) + }; + xasync::finished_with(block, (&raw const INSTALL).cast(), result) +} +extern "system" fn install_chunks_result( + _: This, + block: *mut AsyncBlock, + out: *mut *const c_void, +) -> HRESULT { + xasync::result(block, (&raw const INSTALL).cast(), out) +} + +/// Nothing to download. +extern "system" fn estimate_download( + _: This, + id: *const c_char, + _count: u32, + _selectors: *const c_void, + bytes: *mut u64, + confirm: *mut bool, +) -> HRESULT { + if !is_ours(id) { + return NO_PACKAGE; + } + if !confirm.is_null() { + // SAFETY: checked non-null. + unsafe { confirm.write(false) }; + } + put(bytes, 0) +} + +// shortcut: accepted but nothing is removed (the package folder is the +// user's), so the chunks stay ready; the title's one call site +// (title+0x293b4b0, its chunk manager) would then see them still installed. +extern "system" fn uninstall_chunks( + _: This, + id: *const c_char, + _count: u32, + _selectors: *const c_void, +) -> HRESULT { + if is_ours(id) { S_OK } else { NO_PACKAGE } +} + +/// Mount handles only come from mounting another package, and there is +/// none. +extern "system" fn mount_path(_: This, _: *const c_void, _: usize, _: *mut u8) -> HRESULT { + xasync::E_INVALIDARG +} +extern "system" fn close_mount(_: This, _: *const c_void) {} + +/// Only other packages are uninstalled this way, and none is installed. +extern "system" fn uninstall_package(_: This, id: *const c_char) -> bool { + tracing::info!( + id = text(id).unwrap_or_default(), + "package uninstall refused" + ); + false +} + +static MOUNT: u8 = 0; + +extern "system" fn mount_async(_: This, id: *const c_char, block: *mut AsyncBlock) -> HRESULT { + tracing::info!( + id = text(id).unwrap_or_default(), + "package mount: not installed" + ); + xasync::finished(block, (&raw const MOUNT).cast(), NO_PACKAGE) +} +extern "system" fn mount_result( + _: This, + block: *mut AsyncBlock, + out: *mut *const c_void, +) -> HRESULT { + xasync::result(block, (&raw const MOUNT).cast(), out) +} + +/// Titles enumerate content packages (kind 1); there are none. +// shortcut: the game kind (0) also lists nothing, not this installation; +// The title enumerates only content (kind 1, title+0x2937bf0). +extern "system" fn enumerate( + _: This, + kind: u32, + _scope: u32, + _context: *mut c_void, + _callback: *const c_void, +) -> HRESULT { + tracing::debug!(kind, "packages enumerated: none"); + S_OK +} + +static VTABLE: Methods<40> = Methods([ + missing::<0> as *const (), + add_ref as *const (), + add_ref as *const (), + current_identifier as *const (), // 0x18 + is_packaged as *const (), // 0x20 + create_monitor as *const (), // 0x28 + close_monitor as *const (), // 0x30 + progress as *const (), // 0x38 + missing::<8> as *const (), // 0x40 update a monitor + register_progress as *const (), // 0x48 + missing::<10> as *const (), // 0x50 unregister it + missing::<11> as *const (), // 0x58 user locale + find_availability as *const (), // 0x60 + missing::<13> as *const (), // 0x68 enumerate chunk availability + change_order as *const (), // 0x70 + missing::<15> as *const (), // 0x78 install chunks + install_chunks_async as *const (), // 0x80 + install_chunks_result as *const (), // 0x88 + estimate_download as *const (), // 0x90 + uninstall_chunks as *const (), // 0x98 + missing::<20> as *const (), // 0xa0 + missing::<21> as *const (), // 0xa8 + missing::<22> as *const (), // 0xb0 + missing::<23> as *const (), // 0xb8 mount (deprecated) + missing::<24> as *const (), // 0xc0 mount path size + mount_path as *const (), // 0xc8 + close_mount as *const (), // 0xd0 + missing::<27> as *const (), // 0xd8 + missing::<28> as *const (), // 0xe0 enumerate packages (older) + missing::<29> as *const (), // 0xe8 + missing::<30> as *const (), // 0xf0 + missing::<31> as *const (), // 0xf8 + missing::<32> as *const (), // 0x100 + missing::<33> as *const (), // 0x108 + uninstall_package as *const (), // 0x110 + missing::<35> as *const (), // 0x118 + missing::<36> as *const (), // 0x120 + mount_async as *const (), // 0x128 + mount_result as *const (), // 0x130 + enumerate as *const (), // 0x138 +]); + +#[cfg(test)] +mod tests { + use super::*; + use crate::modules::xgameruntime::method; + + #[test] + fn the_installation_is_complete_and_alone() { + let this: This = &OBJECT; + type Id = extern "system" fn(This, usize, *mut u8) -> HRESULT; + let mut id = [0u8; 33]; + assert_eq!(method::(&OBJECT, 0x18)(this, 33, id.as_mut_ptr()), S_OK); + let len = id.iter().position(|&b| b == 0).unwrap(); + assert_eq!(std::str::from_utf8(&id[..len]).unwrap(), identifier()); + assert!(method:: bool>(&OBJECT, 0x20)( + this + )); + + type Find = + extern "system" fn(This, *const c_char, u32, *const c_void, *mut u32) -> HRESULT; + let mut availability = 9; + let ours = format!("{}\0", identifier()); + let find = method::(&OBJECT, 0x60); + let none = std::ptr::null(); + assert_eq!( + find(this, ours.as_ptr().cast(), 0, none, &mut availability), + S_OK + ); + assert_eq!(availability, 0, "ready"); + assert_eq!( + find(this, c"dlc".as_ptr(), 0, none, &mut availability), + NO_PACKAGE + ); + + type Progress_ = extern "system" fn(This, *const c_void, *mut Progress); + let mut p = Progress { + total_bytes: 1, + installed_bytes: 0, + launch_bytes: 0, + launchable: false, + completed: false, + }; + method::(&OBJECT, 0x38)(this, monitor(), &mut p); + assert!(p.completed && p.launchable && p.installed_bytes == p.total_bytes); + + type Mount = extern "system" fn(This, *const c_char, *mut AsyncBlock) -> HRESULT; + let mut block = AsyncBlock { + queue: std::ptr::null(), + context: std::ptr::null_mut(), + callback: None, + internal: [0; 4], + }; + assert_eq!( + method::(&OBJECT, 0x128)(this, c"dlc".as_ptr(), &mut block), + S_OK + ); + assert_eq!(xasync::XAsyncGetStatus(&mut block, true), NO_PACKAGE); + } +} diff --git a/crates/leonida-hle/src/modules/xstore.rs b/crates/leonida-hle/src/modules/xstore.rs new file mode 100644 index 000000000..9e2b74b21 --- /dev/null +++ b/crates/leonida-hle/src/modules/xstore.rs @@ -0,0 +1,479 @@ +//! XStore as an offline console answers it: the game's own licence is +//! local and active (a full, owned game); the user owns no add-ons; what +//! needs the store service (catalog, consumables, purchase and update +//! pages, collection ids, update checks) fails with the documented store +//! network error. +#![allow(clippy::not_unsafe_ptr_arg_deref)] + +use std::ffi::{c_char, c_void}; + +use super::xasync::{self, AsyncBlock, E_ILLEGAL_METHOD_CALL}; +use super::xgameruntime::{ + Guid, HRESULT, Interface, Methods, Object, S_OK, add_ref, missing, put, put_string, text, token, +}; +use super::xpackage; +use crate::runtime; + +pub const PROVIDER: Guid = Guid::new( + 0x0dd1_12ac, + 0x7c24, + 0x448c, + [0xb9, 0x2b, 0x39, 0x60, 0xfb, 0x5b, 0xd3, 0x0c], +); +/// As the title (2026) asks for it; every slot it calls takes +/// the public API's arguments in the 2020 order. +pub const IID_2026: Guid = Guid::new( + 0xb09d_803c, + 0x2414, + 0x4a05, + [0x82, 0xc6, 0x66, 0xdf, 0xdc, 0x9e, 0x9a, 0x44], +); +/// The same table extended by durables licensing (0x238, 0x240). +pub const DURABLES_IID: Guid = Guid::new( + 0x2d42_fea5, + 0xe71d, + 0x4b76, + [0x97, 0xcd, 0xc5, 0x0a, 0xfb, 0xb3, 0xae, 0x5d], +); + +pub static OBJECT: Object = Object::new("store", &VTABLE); +pub const INTERFACES: &[Interface] = &[ + (PROVIDER, IID_2026, &OBJECT), + (PROVIDER, DURABLES_IID, &OBJECT), +]; + +/// The documented "failed to communicate with the store network". +pub const NETWORK_ERROR: HRESULT = 0x8924_5301_u32 as i32; + +type This = *const Object; +type Handle = *const c_void; + +/// Contexts and product queries hold nothing (queries are always empty), +/// so their handles are fixed addresses. A licence handle says whether it +/// is valid by which address it is. +static CONTEXT: u8 = 0; +static QUERY: u8 = 0; +static VALID: u8 = 0; +static INVALID: u8 = 0; +fn handle(of: &'static u8) -> Handle { + (of as *const u8).cast() +} + +/// Identifies our calls on a block: one per result shape. +static FAILED: u8 = 0; +static QUERY_CALL: u8 = 0; +static LICENSE_CALL: u8 = 0; +static GAME_LICENSE: u8 = 0; + +fn offline(block: *mut AsyncBlock, what: &str) -> HRESULT { + tracing::info!(what, "store call: offline"); + xasync::finished(block, (&raw const FAILED).cast(), NETWORK_ERROR) +} +/// The result functions of calls that failed: their status. +extern "system" fn status(_: This, block: *mut AsyncBlock) -> HRESULT { + xasync::XAsyncGetStatus(block, false) +} + +extern "system" fn create_context(_: This, _user: *const c_void, out: *mut Handle) -> HRESULT { + put(out, handle(&CONTEXT)) +} +extern "system" fn close(_: This, _: Handle) {} + +extern "system" fn associated_products_async( + _: This, + _: Handle, + _kinds: u32, + _per_page: u32, + block: *mut AsyncBlock, +) -> HRESULT { + offline(block, "associated products") +} + +/// The user owns no add-ons: an empty query. +extern "system" fn entitled_products_async( + _: This, + _: Handle, + _kinds: u32, + _per_page: u32, + block: *mut AsyncBlock, +) -> HRESULT { + xasync::finished_with( + block, + (&raw const QUERY_CALL).cast(), + Ok(xasync::bytes(handle(&QUERY))), + ) +} +extern "system" fn query_result(_: This, block: *mut AsyncBlock, out: *mut Handle) -> HRESULT { + xasync::result(block, (&raw const QUERY_CALL).cast(), out) +} +/// Empty, so the callback never runs. +extern "system" fn enumerate_products( + _: This, + _: Handle, + _: *mut c_void, + _: *const c_void, +) -> HRESULT { + S_OK +} +extern "system" fn has_more_pages(_: This, _: Handle) -> bool { + false +} +/// There is no next page to ask for. +extern "system" fn next_page_async(_: This, _: Handle, block: *mut AsyncBlock) -> HRESULT { + xasync::finished(block, (&raw const QUERY_CALL).cast(), E_ILLEGAL_METHOD_CALL) +} + +fn license_for(owned: bool, block: *mut AsyncBlock) -> HRESULT { + let license = handle(if owned { &VALID } else { &INVALID }); + xasync::finished_with( + block, + (&raw const LICENSE_CALL).cast(), + Ok(xasync::bytes(license)), + ) +} +/// Only the game's own package is installed, so only its licence is valid. +extern "system" fn license_for_package_async( + _: This, + _: Handle, + package: *const c_char, + block: *mut AsyncBlock, +) -> HRESULT { + let ours = text(package).is_some_and(|p| p == xpackage::identifier()); + license_for(ours, block) +} +/// The user owns no durables: their licences are not valid. +extern "system" fn license_for_durables_async( + _: This, + _: Handle, + store_id: *const c_char, + block: *mut AsyncBlock, +) -> HRESULT { + tracing::debug!( + store_id = text(store_id).unwrap_or_default(), + "durable not owned" + ); + license_for(false, block) +} +extern "system" fn license_result(_: This, block: *mut AsyncBlock, out: *mut Handle) -> HRESULT { + xasync::result(block, (&raw const LICENSE_CALL).cast(), out) +} +extern "system" fn is_license_valid(_: This, license: Handle) -> bool { + license == handle(&VALID) +} + +/// The game licence, as the public API lays it out. +#[repr(C)] +#[derive(Debug, Clone, Copy)] +pub struct GameLicense { + pub sku_store_id: [u8; 18], + pub is_active: bool, + pub is_trial_owned_by_this_user: bool, + pub is_disc_license: bool, + pub is_trial: bool, + pub trial_seconds_remaining: u32, + pub trial_unique_id: [u8; 64], + pub expiration: i64, +} + +/// A full, active licence for the game's SKU (`/0010`, the +/// store's first SKU), not a trial, without expiry. +fn game_license() -> GameLicense { + let mut sku = [0u8; 18]; + let id = format!("{}/0010", runtime::title().store_id); + let len = id.len().min(sku.len() - 1); + sku[..len].copy_from_slice(&id.as_bytes()[..len]); + GameLicense { + sku_store_id: sku, + is_active: true, + is_trial_owned_by_this_user: false, + is_disc_license: false, + is_trial: false, + trial_seconds_remaining: 0, + trial_unique_id: [0; 64], + expiration: 0, + } +} + +extern "system" fn game_license_async(_: This, _: Handle, block: *mut AsyncBlock) -> HRESULT { + let license = xasync::bytes(game_license()); + xasync::finished_with(block, (&raw const GAME_LICENSE).cast(), Ok(license)) +} +extern "system" fn game_license_result( + _: This, + block: *mut AsyncBlock, + out: *mut GameLicense, +) -> HRESULT { + xasync::result(block, (&raw const GAME_LICENSE).cast(), out) +} + +extern "system" fn consumable_balance_async( + _: This, + _: Handle, + _store_id: *const c_char, + block: *mut AsyncBlock, +) -> HRESULT { + offline(block, "consumable balance") +} +extern "system" fn report_fulfillment_async( + _: This, + _: Handle, + _store_id: *const c_char, + _quantity: u32, + _tracking_id: *const c_void, + block: *mut AsyncBlock, +) -> HRESULT { + offline(block, "consumable fulfillment") +} +/// Collections and purchase ids alike. +extern "system" fn user_id_async( + _: This, + _: Handle, + _ticket: *const c_char, + _publisher_user_id: *const c_char, + block: *mut AsyncBlock, +) -> HRESULT { + offline(block, "user store id") +} +extern "system" fn size_status(_: This, block: *mut AsyncBlock, _out: *mut usize) -> HRESULT { + xasync::XAsyncGetStatus(block, false) +} +extern "system" fn string_status( + _: This, + block: *mut AsyncBlock, + _: usize, + _: *mut c_char, +) -> HRESULT { + xasync::XAsyncGetStatus(block, false) +} +extern "system" fn count_status(_: This, block: *mut AsyncBlock, _out: *mut u32) -> HRESULT { + xasync::XAsyncGetStatus(block, false) +} +extern "system" fn array_status( + _: This, + block: *mut AsyncBlock, + _: u32, + _: *mut c_void, +) -> HRESULT { + xasync::XAsyncGetStatus(block, false) +} + +extern "system" fn purchase_ui_async( + _: This, + _: Handle, + _store_id: *const c_char, + _name: *const c_char, + _json: *const c_char, + block: *mut AsyncBlock, +) -> HRESULT { + offline(block, "purchase page") +} +extern "system" fn product_page_ui_async( + _: This, + _: Handle, + _store_id: *const c_char, + block: *mut AsyncBlock, +) -> HRESULT { + offline(block, "product page") +} +extern "system" fn redeem_ui_async( + _: This, + _: Handle, + _token: *const c_char, + _allowed: *const *const c_char, + _allowed_count: usize, + _disallow_csv: bool, + block: *mut AsyncBlock, +) -> HRESULT { + offline(block, "redeem page") +} +extern "system" fn updates_async(_: This, _: Handle, block: *mut AsyncBlock) -> HRESULT { + offline(block, "update check") +} +/// Installing updates or packages by id alike. +extern "system" fn install_async( + _: This, + _: Handle, + _ids: *const *const c_char, + _count: usize, + block: *mut AsyncBlock, +) -> HRESULT { + offline(block, "package download") +} + +/// The game's own store id maps to its installation; nothing else is +/// installed. +extern "system" fn package_identifier( + _: This, + store_id: *const c_char, + size: usize, + buffer: *mut u8, +) -> HRESULT { + let title = runtime::title(); + match text(store_id) { + Some(id) if !title.store_id.is_empty() && id == title.store_id => { + put_string(&xpackage::identifier(), size, buffer, std::ptr::null_mut()) + } + _ => xpackage::NO_PACKAGE, + } +} + +/// Licences never change offline, so these callbacks never run. +extern "system" fn register( + _: This, + _: Handle, + _queue: *const c_void, + _context: *mut c_void, + _callback: *const c_void, + out: *mut u64, +) -> HRESULT { + put(out, token()) +} +extern "system" fn unregister(_: This, _: Handle, _token: u64, _wait: bool) -> bool { + true +} + +static VTABLE: Methods<76> = Methods([ + missing::<0> as *const (), + add_ref as *const (), + add_ref as *const (), + create_context as *const (), // 0x18 + close as *const (), // 0x20 + associated_products_async as *const (), // 0x28 + query_result as *const (), // 0x30 + missing::<7> as *const (), // 0x38 products by id + missing::<8> as *const (), // 0x40 + entitled_products_async as *const (), // 0x48 + query_result as *const (), // 0x50 + missing::<11> as *const (), // 0x58 product for the game + missing::<12> as *const (), // 0x60 + missing::<13> as *const (), // 0x68 product for a package + missing::<14> as *const (), // 0x70 + enumerate_products as *const (), // 0x78 + has_more_pages as *const (), // 0x80 + next_page_async as *const (), // 0x88 + query_result as *const (), // 0x90 + close as *const (), // 0x98 a product query + license_for_package_async as *const (), // 0xa0 + license_result as *const (), // 0xa8 + is_license_valid as *const (), // 0xb0 + close as *const (), // 0xb8 a licence + missing::<24> as *const (), // 0xc0 can acquire for store id + missing::<25> as *const (), // 0xc8 + missing::<26> as *const (), // 0xd0 can acquire for package + missing::<27> as *const (), // 0xd8 + game_license_async as *const (), // 0xe0 + game_license_result as *const (), // 0xe8 + missing::<30> as *const (), // 0xf0 add-on licences + missing::<31> as *const (), // 0xf8 + missing::<32> as *const (), // 0x100 + consumable_balance_async as *const (), // 0x108 + status as *const (), // 0x110 + report_fulfillment_async as *const (), // 0x118 + missing::<36> as *const (), // 0x120 + user_id_async as *const (), // 0x128 collections id + size_status as *const (), // 0x130 + string_status as *const (), // 0x138 + user_id_async as *const (), // 0x140 purchase id + size_status as *const (), // 0x148 + string_status as *const (), // 0x150 + missing::<43> as *const (), // 0x158 licence token + missing::<44> as *const (), // 0x160 + missing::<45> as *const (), // 0x168 + missing::<46> as *const (), // 0x170 + missing::<47> as *const (), // 0x178 + missing::<48> as *const (), // 0x180 + purchase_ui_async as *const (), // 0x188 + missing::<50> as *const (), // 0x190 + missing::<51> as *const (), // 0x198 rate and review + missing::<52> as *const (), // 0x1a0 + redeem_ui_async as *const (), // 0x1a8 + missing::<54> as *const (), // 0x1b0 + updates_async as *const (), // 0x1b8 + count_status as *const (), // 0x1c0 + array_status as *const (), // 0x1c8 + missing::<58> as *const (), // 0x1d0 download updates + missing::<59> as *const (), // 0x1d8 + install_async as *const (), // 0x1e0 updates + status as *const (), // 0x1e8 + install_async as *const (), // 0x1f0 packages by store id + count_status as *const (), // 0x1f8 + array_status as *const (), // 0x200 + package_identifier as *const (), // 0x208 + register as *const (), // 0x210 game licence changed + unregister as *const (), // 0x218 + register as *const (), // 0x220 package licence lost + unregister as *const (), // 0x228 + missing::<70> as *const (), // 0x230 + license_for_durables_async as *const (), // 0x238 + license_result as *const (), // 0x240 + missing::<73> as *const (), // 0x248 associated products page + missing::<74> as *const (), // 0x250 + product_page_ui_async as *const (), // 0x258 +]); + +#[cfg(test)] +mod tests { + use super::*; + use crate::modules::xgameruntime::method; + + fn block() -> AsyncBlock { + AsyncBlock { + queue: std::ptr::null(), + context: std::ptr::null_mut(), + callback: None, + internal: [0; 4], + } + } + + #[test] + fn the_game_is_licensed_and_the_store_is_offline() { + let this: This = &OBJECT; + assert_eq!(size_of::(), 104); + type Begin = extern "system" fn(This, Handle, *mut AsyncBlock) -> HRESULT; + type Result = extern "system" fn(This, *mut AsyncBlock, *mut GameLicense) -> HRESULT; + let mut b = block(); + assert_eq!( + method::(&OBJECT, 0xe0)(this, handle(&CONTEXT), &mut b), + S_OK + ); + assert_eq!(xasync::XAsyncGetStatus(&mut b, true), S_OK); + let mut license = std::mem::MaybeUninit::::zeroed(); + assert_eq!( + method::(&OBJECT, 0xe8)(this, &mut b, license.as_mut_ptr()), + S_OK + ); + // SAFETY: written by the call. + let license = unsafe { license.assume_init() }; + assert!(license.is_active && !license.is_trial); + + let mut b = block(); + assert_eq!( + method::(&OBJECT, 0x1b8)(this, handle(&CONTEXT), &mut b), + S_OK + ); + assert_eq!(xasync::XAsyncGetStatus(&mut b, true), NETWORK_ERROR); + type Count = extern "system" fn(This, *mut AsyncBlock, *mut u32) -> HRESULT; + assert_eq!( + method::(&OBJECT, 0x1c0)(this, &mut b, &mut 0), + NETWORK_ERROR + ); + + type Durable = extern "system" fn(This, Handle, *const c_char, *mut AsyncBlock) -> HRESULT; + type License = extern "system" fn(This, *mut AsyncBlock, *mut Handle) -> HRESULT; + let mut b = block(); + let durable = method::(&OBJECT, 0x238); + assert_eq!( + durable(this, handle(&CONTEXT), c"9XYZ".as_ptr(), &mut b), + S_OK + ); + assert_eq!(xasync::XAsyncGetStatus(&mut b, true), S_OK); + let mut l = std::ptr::null(); + assert_eq!( + method::(&OBJECT, 0x240)(this, &mut b, &mut l), + S_OK + ); + assert!(!method:: bool>( + &OBJECT, 0xb0 + )(this, l)); + } +} diff --git a/crates/leonida-hle/src/modules/xsystem.rs b/crates/leonida-hle/src/modules/xsystem.rs new file mode 100644 index 000000000..9975c943f --- /dev/null +++ b/crates/leonida-hle/src/modules/xsystem.rs @@ -0,0 +1,400 @@ +//! XSystem: the console's identity and sandbox, and how analytics describe +//! the device. Fixed values: one offline retail console, the model the user +//! chose ([`leonida_gpu::console`]). +#![allow(clippy::not_unsafe_ptr_arg_deref)] + +use super::xgameruntime::{ + Guid, HRESULT, Interface, Methods, Object, add_ref, missing, put_string, +}; + +pub const PROVIDER: Guid = Guid::new( + 0xe349_bd1a, + 0xfc20, + 0x4e40, + [0xb9, 0x9c, 0x41, 0x78, 0xcc, 0x6b, 0x40, 0x9f], +); + +/// The interface as Minecraft (2022) asks for it; an older table +/// ended before the device id. +pub const IID: Guid = Guid::new( + 0x6fd7_1f09, + 0x7513, + 0x49f0, + [0x89, 0xbc, 0xbf, 0xaf, 0x5d, 0xf6, 0xf8, 0x52], +); + +/// Analytics information; its interface id is the provider's. +pub const ANALYTICS: Guid = Guid::new( + 0xb884_675d, + 0xb738, + 0x4a9c, + [0x81, 0x5d, 0x9a, 0x9a, 0x1e, 0x0c, 0x6c, 0x9b], +); + +/// 38 characters (39 bytes with the NUL). +const CONSOLE_ID: &str = "00000000000000000000000000000000000001"; +/// The retail sandbox. +const SANDBOX: &str = "RETAIL"; +/// Base64 of 32 bytes: 44 characters (45 bytes with the NUL). +const DEVICE_ID: &str = "VkljdG9yeSBvZmZsaW5lIGRldmljZSBpZGVudGl0eSE="; + +pub static OBJECT: Object = Object::new("system", &VTABLE); +pub static ANALYTICS_OBJECT: Object = Object::new("analytics", &ANALYTICS_VTABLE); + +/// The interface as the title (2026) asks for it; it calls the +/// same three slots (0x18, 0x20, 0x28) with the same arguments. +pub const IID_2026: Guid = Guid::new( + 0x1861_cf2e, + 0xe18b, + 0x4834, + [0xa9, 0xf5, 0xb4, 0xa4, 0xe6, 0xef, 0xb4, 0xcf], +); + +pub const INTERFACES: &[Interface] = &[ + (PROVIDER, IID, &OBJECT), + (PROVIDER, IID_2026, &OBJECT), + (ANALYTICS, ANALYTICS, &ANALYTICS_OBJECT), +]; + +type This = *const Object; + +extern "system" fn console_id(_: This, size: usize, buffer: *mut u8, used: *mut usize) -> HRESULT { + put_string(CONSOLE_ID, size, buffer, used) +} +extern "system" fn sandbox_id(_: This, size: usize, buffer: *mut u8, used: *mut usize) -> HRESULT { + put_string(SANDBOX, size, buffer, used) +} +/// The device id this title sees (titles see different ones). +extern "system" fn device_id(_: This, size: usize, buffer: *mut u8, used: *mut usize) -> HRESULT { + put_string(DEVICE_ID, size, buffer, used) +} + +#[repr(C)] +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct Version { + pub major: u16, + pub minor: u16, + pub build: u16, + pub revision: u16, +} + +#[repr(C)] +pub struct AnalyticsInfo { + pub os: Version, + pub hosting_os: Version, + /// NUL-terminated. + pub family: [u8; 64], + pub form: [u8; 64], +} + +const OS: Version = Version { + major: 10, + minor: 0, + build: 22000, + revision: 0, +}; + +fn text(s: &str) -> [u8; 64] { + let mut out = [0; 64]; + out[..s.len()].copy_from_slice(s.as_bytes()); + out +} + +/// A struct this large comes back through the caller's buffer, whose +/// address is also the return value. +extern "system" fn analytics_info(_: This, out: *mut AnalyticsInfo) -> *mut AnalyticsInfo { + let info = AnalyticsInfo { + os: OS, + hosting_os: OS, + family: text("Xbox"), + form: text(leonida_gpu::console::current().name()), + }; + // SAFETY: the caller passes room for the struct. + unsafe { out.write(info) }; + out +} + +static VTABLE: Methods<6> = Methods([ + missing::<0> as *const (), + add_ref as *const (), + add_ref as *const (), + console_id as *const (), // 0x18, by the older table; titles seen do not call it + sandbox_id as *const (), // 0x20 + device_id as *const (), // 0x28 +]); + +static ANALYTICS_VTABLE: Methods<4> = Methods([ + missing::<0> as *const (), + add_ref as *const (), + add_ref as *const (), + analytics_info as *const (), // 0x18 +]); + +/// The device type is not a runtime call: code linked into the title reads +/// `ConsoleMode` from this key (`RegOpenKeyW`, `RegQueryValueExW`) and +/// takes a missing value for a PC. +#[cfg(windows)] +mod device_type { + #![allow(non_snake_case)] + + use std::ffi::c_void; + + use leonida_gpu::console::{self, Console}; + + use crate::modules::files::host; + use crate::{HleModule, hle_export}; + + type Key = *mut c_void; + const LOCAL_MACHINE: Key = 0xffff_ffff_8000_0002_u64 as Key; + const KEY: &str = r"Software\Microsoft\Windows NT\CurrentVersion\OEM"; + const VALUE: &str = "ConsoleMode"; + const SUCCESS: u32 = 0; + const FILE_NOT_FOUND: u32 = 2; + const INVALID_PARAMETER: u32 = 87; + const MORE_DATA: u32 = 234; + const DWORD: u32 = 4; + + /// Stands for the key; never a host handle value. + static OEM: u8 = 0; + fn oem() -> Key { + (&raw const OEM).cast_mut().cast() + } + + /// What the title's code maps to each model's device type. + pub(super) fn console_mode(console: Console) -> u32 { + match console { + Console::SeriesX => 0x64, + Console::SeriesS => 0x60, + } + } + + fn is(text: *const u16, expected: &str) -> bool { + if text.is_null() { + return false; + } + // SAFETY: the title passes a NUL-terminated string. + let text = unsafe { + let len = (0..).take_while(|&i| *text.add(i) != 0).count(); + String::from_utf16_lossy(std::slice::from_raw_parts(text, len)) + }; + text.eq_ignore_ascii_case(expected) + } + + /// Opens our key for its path; the key has no subkeys. `None`: not + /// ours, ask the host. + fn open(root: Key, sub: *const u16, out: *mut Key) -> Option { + if root == oem() { + return Some(FILE_NOT_FOUND); + } + if root == LOCAL_MACHINE && is(sub, KEY) && !out.is_null() { + // SAFETY: checked non-null; the title passes room for a key. + unsafe { out.write(oem()) }; + return Some(SUCCESS); + } + None + } + + // Our titles import only these registry functions (and `RegOpenKeyExW` + // below), so no other call can reach the host with our key. + pub extern "system" fn RegOpenKeyW(root: Key, sub: *const u16, out: *mut Key) -> u32 { + open(root, sub, out).unwrap_or_else(|| { + host!("advapi32.dll", "RegOpenKeyW": extern "system" fn(Key, *const u16, *mut Key) -> u32)( + root, sub, out, + ) + }) + } + + pub extern "system" fn RegOpenKeyExW( + root: Key, + sub: *const u16, + options: u32, + access: u32, + out: *mut Key, + ) -> u32 { + open(root, sub, out).unwrap_or_else(|| { + host!("advapi32.dll", "RegOpenKeyExW": extern "system" fn( + Key, *const u16, u32, u32, *mut Key, + ) -> u32)(root, sub, options, access, out) + }) + } + + pub extern "system" fn RegQueryValueExW( + key: Key, + name: *const u16, + reserved: *mut u32, + kind: *mut u32, + data: *mut u8, + size: *mut u32, + ) -> u32 { + if key != oem() { + return host!("advapi32.dll", "RegQueryValueExW": extern "system" fn( + Key, *const u16, *mut u32, *mut u32, *mut u8, *mut u32, + ) -> u32)(key, name, reserved, kind, data, size); + } + if !is(name, VALUE) { + return FILE_NOT_FOUND; + } + if !data.is_null() && size.is_null() { + return INVALID_PARAMETER; + } + // SAFETY: the title passes valid or null pointers, sized by `size`. + unsafe { + if !kind.is_null() { + kind.write(DWORD); + } + if size.is_null() { + return SUCCESS; + } + let room = size.read(); + size.write(4); + if data.is_null() { + return SUCCESS; + } + if room < 4 { + return MORE_DATA; + } + data.cast::() + .write_unaligned(console_mode(console::current())); + } + tracing::debug!(console = console::current().name(), "device type read"); + SUCCESS + } + + pub extern "system" fn RegCloseKey(key: Key) -> u32 { + if key == oem() { + return SUCCESS; + } + host!("advapi32.dll", "RegCloseKey": extern "system" fn(Key) -> u32)(key) + } + + pub(crate) fn module() -> HleModule { + HleModule { + name: "device type", + dlls: &["advapi32.dll", "api-ms-win-core-registry-*"], + exports: vec![ + hle_export!(RegOpenKeyW), + hle_export!(RegOpenKeyExW), + hle_export!(RegQueryValueExW), + hle_export!(RegCloseKey), + ], + } + } + + #[cfg(test)] + mod tests { + use super::*; + + fn w(s: &str) -> Vec { + s.encode_utf16().chain([0]).collect() + } + + #[test] + fn titles_read_the_chosen_model() { + assert_eq!(console_mode(Console::SeriesX), 0x64); + assert_eq!(console_mode(Console::SeriesS), 0x60); + let mut key = std::ptr::null_mut(); + let path = w(&KEY.to_ascii_lowercase()); + assert_eq!(RegOpenKeyW(LOCAL_MACHINE, path.as_ptr(), &mut key), SUCCESS); + let (mut kind, mut value, mut size) = (0, 0u32, 4); + let name = w(VALUE); + let query = |data: *mut u32, size: *mut u32, kind: *mut u32| { + RegQueryValueExW( + key, + name.as_ptr(), + std::ptr::null_mut(), + kind, + data.cast(), + size, + ) + }; + assert_eq!(query(&mut value, &mut size, &mut kind), SUCCESS); + assert_eq!((kind, size), (DWORD, 4)); + assert_eq!(value, console_mode(console::current())); + let mut small = 2; + assert_eq!(query(&mut value, &mut small, &mut kind), MORE_DATA); + assert_eq!(small, 4); + let other = w("Other"); + assert_eq!( + RegQueryValueExW( + key, + other.as_ptr(), + std::ptr::null_mut(), + &mut kind, + std::ptr::null_mut(), + &mut size + ), + FILE_NOT_FOUND + ); + let mut sub = std::ptr::null_mut(); + assert_eq!( + RegOpenKeyExW(key, other.as_ptr(), 0, 1, &mut sub), + FILE_NOT_FOUND + ); + assert_eq!(RegCloseKey(key), SUCCESS); + let mut again = std::ptr::null_mut(); + assert_eq!( + RegOpenKeyExW(LOCAL_MACHINE, path.as_ptr(), 0, 1, &mut again), + SUCCESS + ); + assert_eq!(again, oem()); + } + + #[test] + fn other_keys_reach_the_host() { + let mut key = std::ptr::null_mut(); + let path = w(r"Software\Microsoft\Windows NT\CurrentVersion"); + assert_eq!(RegOpenKeyW(LOCAL_MACHINE, path.as_ptr(), &mut key), SUCCESS); + assert_ne!(key, oem()); + let (mut size, name) = (0, w("ProductName")); + assert_eq!( + RegQueryValueExW( + key, + name.as_ptr(), + std::ptr::null_mut(), + std::ptr::null_mut(), + std::ptr::null_mut(), + &mut size + ), + SUCCESS + ); + assert!(size > 0); + assert_eq!(RegCloseKey(key), SUCCESS); + } + } +} +#[cfg(windows)] +pub(crate) use device_type::module; + +#[cfg(test)] +mod tests { + use super::*; + use crate::modules::xgameruntime::{S_OK, method}; + + #[test] + fn identity_strings_fit_the_documented_sizes() { + type Get = extern "system" fn(This, usize, *mut u8, *mut usize) -> HRESULT; + let this: This = &OBJECT; + let mut buffer = [0u8; 64]; + let mut used = 0; + for (slot, size) in [(0x18, 39), (0x20, 16), (0x28, 45)] { + let get = method::(&OBJECT, slot); + assert_eq!(get(this, size, buffer.as_mut_ptr(), &mut used), S_OK); + assert!(used <= size && buffer[used - 1] == 0, "slot {slot:#x}"); + } + assert_eq!(&buffer[..7], b"VkljdG9"); + } + + #[test] + fn analytics_info_comes_back_through_the_buffer() { + type Get = extern "system" fn(This, *mut AnalyticsInfo) -> *mut AnalyticsInfo; + let mut info = std::mem::MaybeUninit::::uninit(); + let get = method::(&ANALYTICS_OBJECT, 0x18); + let back = get(&ANALYTICS_OBJECT, info.as_mut_ptr()); + assert_eq!(back, info.as_mut_ptr()); + // SAFETY: written by the call. + let info = unsafe { info.assume_init() }; + assert_eq!(size_of::(), 0x90); + assert_eq!(info.os.build, 22000); + assert_eq!(&info.form[..14], b"Xbox Series X\0"); + } +} diff --git a/crates/leonida-hle/src/modules/xuser.rs b/crates/leonida-hle/src/modules/xuser.rs new file mode 100644 index 000000000..601938159 --- /dev/null +++ b/crates/leonida-hle/src/modules/xuser.rs @@ -0,0 +1,425 @@ +//! XUser: one offline local user, signed in, never a guest, with every +//! privilege. Served as the user provider's objects from `QueryApiImpl`; +//! adding a user completes through `xasync` like any other async call. No +//! input device is associated with the user (there are none, `gameinput`). +#![allow(clippy::not_unsafe_ptr_arg_deref)] + +use std::ffi::{c_char, c_void}; + +use super::xasync::{self, AsyncBlock, ProviderData}; +use super::xgameruntime::{ + Guid, HRESULT, Interface, Methods, Object, S_OK, add_ref, missing, put, put_string, text, token, +}; + +/// The user provider. +pub const PROVIDER: Guid = Guid { + data1: 0x01ac_d177, + data2: 0x91f9, + data3: 0x4763, + data4: [0xa3, 0x8e, 0xcc, 0xbb, 0x55, 0xce, 0x32, 0xe0], +}; + +/// Its main interface. +pub const IID: Guid = Guid { + data1: 0xeb9b_f948, + data2: 0x18dc, + data3: 0x4d82, + data4: [0xbb, 0xcc, 0x40, 0xe0, 0xa8, 0x09, 0xc4, 0xc0], +}; + +/// The interface titles ask for to read a gamertag. +pub const GAMERTAG_IID: Guid = Guid { + data1: 0xcef4_fac0, + data2: 0x7676, + data3: 0x4a94, + data4: [0xa1, 0x19, 0x4c, 0x43, 0xf9, 0xeb, 0x5b, 0x74], +}; + +/// The user's devices and audio endpoints. +pub const DEVICE_PROVIDER: Guid = Guid::new( + 0x7d82_4997, + 0x10dc, + 0x45ab, + [0x86, 0xb7, 0x27, 0x37, 0x76, 0x7c, 0x0b, 0xf1], +); + +/// The device interface as Minecraft (2022) asks for it. +pub const DEVICE_IID: Guid = Guid::new( + 0x0cc6_a956, + 0xe7e1, + 0x4fdf, + [0x93, 0x41, 0x9d, 0x5d, 0xa6, 0x49, 0xeb, 0xc8], +); + +/// The documented "no such user" error. +pub const USER_NOT_FOUND: HRESULT = 0x8924_5104_u32 as i32; + +pub const XUID: u64 = 0x0009_0000_0000_0001; +pub const LOCAL_ID: u64 = 1; +const GAMERTAG: &str = "Player"; + +/// The only user; a handle is its address, duplicating and closing are free. +pub struct User; +static USER: User = User; +type Handle = *const User; + +fn user() -> Handle { + &USER +} + +fn found(found: bool, out: *mut Handle) -> HRESULT { + if found { + put(out, user()) + } else { + USER_NOT_FOUND + } +} + +pub static OBJECT: Object = Object::new("user", &VTABLE); +pub static GAMERTAG_OBJECT: Object = Object::new("user gamertag", &GAMERTAG_VTABLE); +pub static DEVICE_OBJECT: Object = Object::new("user devices", &DEVICE_VTABLE); + +pub const INTERFACES: &[Interface] = &[ + (PROVIDER, IID, &OBJECT), + // The title (2026) asks with the provider's id; its thunks call + // the same slots with the same arguments (0x108/0x110 change events). + (PROVIDER, PROVIDER, &OBJECT), + (PROVIDER, GAMERTAG_IID, &GAMERTAG_OBJECT), + (DEVICE_PROVIDER, DEVICE_IID, &DEVICE_OBJECT), +]; + +type This = *const Object; +extern "system" fn duplicate(_: This, _: Handle, out: *mut Handle) -> HRESULT { + put(out, user()) +} +extern "system" fn close(_: This, _: Handle) {} +extern "system" fn compare(_: This, a: Handle, b: Handle) -> i32 { + i32::from(a != b) +} + +/// The async provider for adding a user: done at once, the result is a +/// handle. +extern "system" fn add_provider(op: u32, data: *const ProviderData) -> HRESULT { + const BEGIN: u32 = 0; + const GET_RESULT: u32 = 2; + // SAFETY: the async runtime passes valid provider data. + let data = unsafe { &*data }; + match op { + BEGIN => xasync::XAsyncComplete(data.block, S_OK, size_of::()), + GET_RESULT => return put(data.buffer.cast::(), user()), + _ => {} + } + S_OK +} + +/// Tells our add calls apart from other async calls on the same block. +static ADD: u8 = 0; + +/// Any options add the one user, silently. +extern "system" fn add_async(_: This, options: u32, block: *mut AsyncBlock) -> HRESULT { + tracing::info!(options, "XUserAddAsync: the offline local user"); + xasync::XAsyncBegin( + block, + std::ptr::null_mut(), + (&raw const ADD).cast(), + std::ptr::null(), + Some(add_provider), + ) +} +extern "system" fn add_result(_: This, block: *mut AsyncBlock, out: *mut Handle) -> HRESULT { + xasync::XAsyncGetResult( + block, + (&raw const ADD).cast(), + size_of::(), + out.cast(), + std::ptr::null_mut(), + ) +} +extern "system" fn get_local_id(_: This, _: Handle, out: *mut u64) -> HRESULT { + put(out, LOCAL_ID) +} +extern "system" fn find_by_local_id(_: This, id: u64, out: *mut Handle) -> HRESULT { + found(id == LOCAL_ID, out) +} +extern "system" fn get_id(_: This, _: Handle, out: *mut u64) -> HRESULT { + put(out, XUID) +} +extern "system" fn find_by_id(_: This, id: u64, out: *mut Handle) -> HRESULT { + found(id == XUID, out) +} +extern "system" fn get_is_guest(_: This, _: Handle, out: *mut bool) -> HRESULT { + put(out, false) +} +/// 0: signed in. +extern "system" fn get_state(_: This, _: Handle, out: *mut u32) -> HRESULT { + put(out, 0) +} +/// The user's gamertag as the component asked for (`XUserGamertagComponent`): +/// it has no suffix, so the modern suffix is empty and every other component +/// (classic, modern, unique modern) is the name itself. +extern "system" fn get_gamertag( + _: This, + _: Handle, + component: u32, + size: usize, + buffer: *mut u8, + used: *mut usize, +) -> HRESULT { + const MODERN_SUFFIX: u32 = 2; + let text = match component { + MODERN_SUFFIX => "", + _ => GAMERTAG, + }; + put_string(text, size, buffer, used) +} +/// Granted; deny reason 0 (none). +extern "system" fn check_privilege( + _: This, + _: Handle, + _options: u32, + _privilege: u32, + has: *mut bool, + reason: *mut u32, +) -> HRESULT { + if !reason.is_null() { + // SAFETY: checked non-null. + unsafe { reason.write(0) }; + } + put(has, true) +} + +/// 3: adult. +extern "system" fn get_age_group(_: This, _: Handle, out: *mut u32) -> HRESULT { + put(out, 3) +} + +static RESOLVE: u8 = 0; +static TOKEN: u8 = 0; + +/// Every privilege is granted, so there is nothing to resolve. +extern "system" fn resolve_privilege_async( + _: This, + _: Handle, + _options: u32, + _privilege: u32, + block: *mut AsyncBlock, +) -> HRESULT { + xasync::finished(block, (&raw const RESOLVE).cast(), S_OK) +} +extern "system" fn resolve_privilege_result(_: This, block: *mut AsyncBlock) -> HRESULT { + let none = std::ptr::null_mut(); + xasync::XAsyncGetResult(block, (&raw const RESOLVE).cast(), 0, none, none.cast()) +} + +/// The documented "failed to get token": tokens come from the service. +pub const FAILED_TO_GET_TOKEN: HRESULT = 0x8924_5111_u32 as i32; + +#[allow(clippy::too_many_arguments)] +extern "system" fn token_async( + _: This, + _: Handle, + _options: u32, + _method: *const c_char, + url: *const c_char, + _header_count: usize, + _headers: *const c_void, + _body_size: usize, + _body: *const c_void, + block: *mut AsyncBlock, +) -> HRESULT { + tracing::info!( + url = text(url).unwrap_or_default(), + "token and signature: offline" + ); + xasync::finished(block, (&raw const TOKEN).cast(), FAILED_TO_GET_TOKEN) +} +extern "system" fn token_size(_: This, block: *mut AsyncBlock, out: *mut usize) -> HRESULT { + xasync::XAsyncGetResultSize(block, out) +} +extern "system" fn token_result( + _: This, + block: *mut AsyncBlock, + size: usize, + buffer: *mut c_void, + _data: *mut *const c_void, + used: *mut usize, +) -> HRESULT { + xasync::XAsyncGetResult(block, (&raw const TOKEN).cast(), size, buffer, used) +} + +/// The user never changes and no device is ever associated, so these +/// callbacks are never called. +extern "system" fn register( + _: This, + _queue: *const c_void, + _context: *mut c_void, + _callback: *const c_void, + out: *mut u64, +) -> HRESULT { + put(out, token()) +} +extern "system" fn unregister(_: This, _token: u64, _wait: bool) -> bool { + true +} + +/// No input device belongs to a user. +extern "system" fn find_for_device(_: This, _device: *const c_void, _: *mut Handle) -> HRESULT { + USER_NOT_FOUND +} + +// Unset slots (no title seen calls them): maximum users, gamer pictures, +// the UTF-16 token calls, issue resolution. +static VTABLE: Methods<35> = Methods([ + missing::<0> as *const (), // 0x00 QueryInterface + add_ref as *const (), // 0x08 AddRef + add_ref as *const (), // 0x10 Release: the object is static + duplicate as *const (), // 0x18 + close as *const (), // 0x20 + compare as *const (), // 0x28 + missing::<6> as *const (), // 0x30 maximum users + add_async as *const (), // 0x38 + add_result as *const (), // 0x40 + get_local_id as *const (), // 0x48 + find_by_local_id as *const (), // 0x50 + get_id as *const (), // 0x58 + find_by_id as *const (), // 0x60 + get_is_guest as *const (), // 0x68 + get_state as *const (), // 0x70 + get_gamertag as *const (), // 0x78 older gamertag slot + missing::<16> as *const (), // 0x80 gamer picture: begin + missing::<17> as *const (), // 0x88 result size + missing::<18> as *const (), // 0x90 result + get_age_group as *const (), // 0x98 + check_privilege as *const (), // 0xa0 + resolve_privilege_async as *const (), // 0xa8 with UI + resolve_privilege_result as *const (), // 0xb0 + token_async as *const (), // 0xb8 token and signature + token_size as *const (), // 0xc0 + token_result as *const (), // 0xc8 + missing::<26> as *const (), // 0xd0 the same, UTF-16: begin + missing::<27> as *const (), // 0xd8 result size + missing::<28> as *const (), // 0xe0 result + missing::<29> as *const (), // 0xe8 resolve issue with UI: begin + missing::<30> as *const (), // 0xf0 result + missing::<31> as *const (), // 0xf8 the same, UTF-16: begin + missing::<32> as *const (), // 0x100 result + register as *const (), // 0x108 change event + unregister as *const (), // 0x110 +]); + +static GAMERTAG_VTABLE: Methods<4> = Methods([ + missing::<0> as *const (), + add_ref as *const (), + add_ref as *const (), + get_gamertag as *const (), // 0x18 +]); + +static DEVICE_VTABLE: Methods<6> = Methods([ + missing::<0> as *const (), + add_ref as *const (), + add_ref as *const (), + find_for_device as *const (), // 0x18 + register as *const (), // 0x20 device association changed + unregister as *const (), // 0x28 +]); + +#[cfg(test)] +mod tests { + use super::*; + use crate::modules::xasync::E_NOT_SUFFICIENT_BUFFER; + use crate::modules::xgameruntime::method as slot; + + #[test] + fn a_gamertag_without_a_suffix_has_an_empty_modern_suffix() { + type Gamertag = + extern "system" fn(This, Handle, u32, usize, *mut u8, *mut usize) -> HRESULT; + let this: This = &OBJECT; + let user = std::ptr::null(); + // Classic, modern, modern suffix, unique modern; through both slots. + let expected: [&[u8]; 4] = [b"Player\0", b"Player\0", b"\0", b"Player\0"]; + for (object, at) in [(&GAMERTAG_OBJECT, 0x18), (&OBJECT, 0x78)] { + let get = slot::(object, at); + for (component, expected) in (0..).zip(expected) { + let (mut name, mut used) = ([0xff_u8; 16], 0); + let hr = get(this, user, component, 16, name.as_mut_ptr(), &mut used); + assert_eq!(hr, S_OK); + assert_eq!(&name[..used], expected, "component {component}"); + } + } + } + + #[test] + fn startup_adds_the_user_and_reads_its_id() { + type Add = extern "system" fn(This, u32, *mut AsyncBlock) -> HRESULT; + type AddResult = extern "system" fn(This, *mut AsyncBlock, *mut Handle) -> HRESULT; + type GetId = extern "system" fn(This, Handle, *mut u64) -> HRESULT; + type Gamertag = + extern "system" fn(This, Handle, u32, usize, *mut u8, *mut usize) -> HRESULT; + let this: This = &OBJECT; + let mut block = AsyncBlock { + queue: std::ptr::null(), + context: std::ptr::null_mut(), + callback: None, + internal: [0; 4], + }; + assert_eq!(slot::(&OBJECT, 0x38)(this, 1, &mut block), S_OK); + assert_eq!(xasync::XAsyncGetStatus(&mut block, true), S_OK); + let mut handle = std::ptr::null(); + assert_eq!( + slot::(&OBJECT, 0x40)(this, &mut block, &mut handle), + S_OK + ); + assert!(!handle.is_null()); + let mut xuid = 0; + assert_eq!(slot::(&OBJECT, 0x58)(this, handle, &mut xuid), S_OK); + assert_eq!(xuid, XUID); + + let mut name = [0u8; 16]; + let mut used = 0; + let get = slot::(&GAMERTAG_OBJECT, 0x18); + assert_eq!(get(this, handle, 0, 16, name.as_mut_ptr(), &mut used), S_OK); + assert_eq!(&name[..used], b"Player\0"); + assert_eq!( + get(this, handle, 0, 2, name.as_mut_ptr(), &mut used), + E_NOT_SUFFICIENT_BUFFER + ); + + type Age = extern "system" fn(This, Handle, *mut u32) -> HRESULT; + let mut age = 0; + assert_eq!(slot::(&OBJECT, 0x98)(this, handle, &mut age), S_OK); + assert_eq!(age, 3, "adult"); + type Token = extern "system" fn( + This, + Handle, + u32, + *const c_char, + *const c_char, + usize, + *const c_void, + usize, + *const c_void, + *mut AsyncBlock, + ) -> HRESULT; + let (null, url) = (std::ptr::null(), c"https://example.invalid/"); + let token = slot::(&OBJECT, 0xb8); + assert_eq!( + token( + this, + handle, + 0, + c"GET".as_ptr(), + url.as_ptr(), + 0, + null, + 0, + null, + &mut block + ), + S_OK + ); + assert_eq!( + xasync::XAsyncGetStatus(&mut block, true), + FAILED_TO_GET_TOKEN + ); + } +} diff --git a/crates/leonida-hle/src/registry.rs b/crates/leonida-hle/src/registry.rs new file mode 100644 index 000000000..e8744b48e --- /dev/null +++ b/crates/leonida-hle/src/registry.rs @@ -0,0 +1,95 @@ +//! The table of everything we implement. + +use std::sync::LazyLock; + +use crate::modules; + +/// One function we implement, under the name the title imports (`#n` for an +/// ordinal). +#[derive(Debug, Clone, Copy)] +pub struct HleExport { + pub name: &'static str, + pub address: usize, +} + +/// A group of implementations and the DLL names they answer for. +#[derive(Debug)] +pub struct HleModule { + /// Human-readable name, e.g. "kernel". + pub name: &'static str, + /// Lower-case DLL names served. A trailing `*` matches a prefix, which + /// covers versioned API sets (`api-ms-win-core-libraryloader-l1-2-0.dll`). + pub dlls: &'static [&'static str], + pub exports: Vec, +} + +impl HleModule { + pub fn serves(&self, dll: &str) -> bool { + let dll = dll.to_ascii_lowercase(); + self.dlls + .iter() + .any(|pattern| match pattern.strip_suffix('*') { + Some(prefix) => dll.starts_with(prefix), + None => dll == *pattern, + }) + } +} + +/// Declares an export whose Rust name equals the imported name. +#[macro_export] +macro_rules! hle_export { + ($f:ident) => { + $crate::HleExport { + name: stringify!($f), + address: $f as *const () as usize, + } + }; +} + +static REGISTRY: LazyLock> = LazyLock::new(modules::all); + +/// All modules we implement. +pub fn registry() -> &'static [HleModule] { + ®ISTRY +} + +pub(crate) fn lookup(dll: &str, name: &str) -> Option { + registry() + .iter() + .filter(|m| m.serves(dll)) + .flat_map(|m| m.exports.iter()) + .find(|e| e.name == name) + .map(|e| e.address) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn export_names_are_unique_per_dll_pattern() { + for module in registry() { + let mut names: Vec<_> = module.exports.iter().map(|e| e.name).collect(); + names.sort_unstable(); + let before = names.len(); + names.dedup(); + assert_eq!( + before, + names.len(), + "duplicate export in module {}", + module.name + ); + } + } + + #[test] + fn api_set_prefix_matching() { + let m = HleModule { + name: "t", + dlls: &["api-ms-win-core-libraryloader-*"], + exports: vec![], + }; + assert!(m.serves("API-MS-WIN-CORE-LIBRARYLOADER-L1-2-0.dll")); + assert!(!m.serves("api-ms-win-core-file-l1-1-0.dll")); + } +} diff --git a/crates/leonida-hle/src/runtime.rs b/crates/leonida-hle/src/runtime.rs new file mode 100644 index 000000000..3e4125de8 --- /dev/null +++ b/crates/leonida-hle/src/runtime.rs @@ -0,0 +1,236 @@ +//! Process-wide state the implementations need. + +use std::path::{Path, PathBuf}; +use std::sync::Mutex; +use std::sync::atomic::{AtomicUsize, Ordering}; + +static MAIN_IMAGE_BASE: AtomicUsize = AtomicUsize::new(0); + +/// Records where the title's main image is mapped. The title expects +/// `GetModuleHandle(NULL)` and friends to return this, not our own exe. +pub fn set_main_image(base: usize) { + MAIN_IMAGE_BASE.store(base, Ordering::Release); +} + +pub fn main_image() -> Option { + match MAIN_IMAGE_BASE.load(Ordering::Acquire) { + 0 => None, + base => Some(base), + } +} + +/// Original file of each title image we mapped, by base address. +static IMAGE_PATHS: Mutex> = Mutex::new(Vec::new()); + +/// Records the file a title image was mapped from: the title asks for its +/// own path (`GetModuleFileName`) to find its data, and must not get our +/// cache copy. +pub fn set_image_path(base: usize, path: &Path) { + let path = std::path::absolute(path).unwrap_or_else(|_| path.to_owned()); + let mut paths = IMAGE_PATHS.lock().unwrap_or_else(|e| e.into_inner()); + paths.retain(|(b, _)| *b != base); + paths.push((base, path)); +} + +/// Forgets a title image that was unmapped again. +pub fn forget_image(base: usize) { + let mut paths = IMAGE_PATHS.lock().unwrap_or_else(|e| e.into_inner()); + paths.retain(|(b, _)| *b != base); +} + +pub fn image_path(base: usize) -> Option { + let paths = IMAGE_PATHS.lock().unwrap_or_else(|e| e.into_inner()); + paths + .iter() + .find(|(b, _)| *b == base) + .map(|(_, p)| p.clone()) +} + +/// The title image whose original file is called `file` (any case). +pub fn image_named(file: &str) -> Option { + let paths = IMAGE_PATHS.lock().unwrap_or_else(|e| e.into_inner()); + paths + .iter() + .find(|(_, p)| p.file_name().is_some_and(|n| n.eq_ignore_ascii_case(file))) + .map(|(b, _)| *b) +} + +/// Maps a title DLL the title loads itself (`LoadLibrary`) and returns its +/// base; `Ok(None)` if `file` is not one of the title's DLLs. +pub type TitleDllLoader = Box Result, String> + Send + Sync>; + +static TITLE_DLL_LOADER: std::sync::OnceLock = std::sync::OnceLock::new(); + +/// Set once, by whoever mapped the title (it knows the folders and the +/// resolver); later calls are ignored. +pub fn set_title_dll_loader(loader: TitleDllLoader) { + let _ = TITLE_DLL_LOADER.set(loader); +} + +pub fn load_title_dll(file: &str) -> Result, String> { + TITLE_DLL_LOADER.get().map_or(Ok(None), |load| load(file)) +} + +/// What the title's manifest (`MicrosoftGame.config` beside its executable) +/// says about it, and where its persistent local storage lives. +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct Title { + pub id: u32, + /// The store's product id (empty if the manifest has none). + pub store_id: String, + /// Persistent local storage: our folder for it and the title's quota. + /// Game saves live beside it ([`Title::saves`]). + pub storage: PathBuf, + pub storage_bytes: u64, +} + +impl Title { + /// Id, store id and storage quota from the manifest (zero or empty + /// where it has none); the storage folder is left for the caller. + pub fn from_manifest(text: &str) -> Title { + let elements = elements(text); + let get = |path: &str| { + elements + .iter() + .find(|(p, _)| p == path) + .map(|(_, text)| text.as_str()) + }; + let id = get("Game/TitleId").and_then(|v| u32::from_str_radix(v, 16).ok()); + let storage_mb = get("Game/PersistentLocalStorage/SizeMB").and_then(|v| v.parse().ok()); + Title { + id: id.unwrap_or(0), + store_id: get("Game/StoreId").unwrap_or_default().to_owned(), + storage: PathBuf::new(), + storage_bytes: storage_mb.unwrap_or(0) << 20, + } + } + + /// Where game saves live: next to persistent local storage, under the + /// data directory, never the cache. + pub fn saves(&self) -> PathBuf { + self.storage.with_file_name("saves") + } +} + +/// Each element of an XML text as its path from the root (`Game/TitleId`) +/// and its trimmed text up to the first child, the predefined entities +/// decoded; comments, CDATA sections, declarations and attributes are +/// skipped. +fn elements(text: &str) -> Vec<(String, String)> { + let mut out = Vec::new(); + let mut path: Vec<&str> = Vec::new(); + let mut rest = text; + while let Some(open) = rest.find('<') { + rest = &rest[open..]; + let end = if rest.starts_with("").map(|e| e + 3) + } else if rest.starts_with("").map(|e| e + 3) + } else { + rest.find('>').map(|e| e + 1) + }; + let Some(end) = end else { break }; + let tag = &rest[1..end - 1]; + rest = &rest[end..]; + if tag.starts_with(['!', '?']) { + continue; + } + if let Some(name) = tag.strip_prefix('/') { + if let Some(at) = path.iter().rposition(|n| *n == name.trim()) { + path.truncate(at); + } + continue; + } + let closed = tag.ends_with('/'); + let name = tag + .trim_end_matches('/') + .split_whitespace() + .next() + .unwrap_or(""); + path.push(name); + let body = rest[..rest.find('<').unwrap_or(rest.len())].trim(); + let body = [("<", "<"), (">", ">"), (""", "\""), ("'", "'"), ("&", "&")] + .iter() + .fold(body.to_owned(), |b, (entity, c)| b.replace(entity, c)); + out.push((path.join("/"), body)); + if closed { + path.pop(); + } + } + out +} + +static TITLE: Mutex> = Mutex::new(None); + +pub fn set_title(title: Title) { + *TITLE.lock().unwrap_or_else(|e| e.into_inner()) = Some(title); +} + +/// The running title; the default (id 0, no storage) until set. +pub fn title() -> Title { + TITLE + .lock() + .unwrap_or_else(|e| e.into_inner()) + .clone() + .unwrap_or_default() +} + +/// Gives the process the console's millisecond timers. Titles pace +/// themselves with short waits (the title's audio mixer sleeps +/// about 4 ms per 5.3 ms block) and cannot tune the timer on the console; +/// a desktop process waits in 15.6 ms ticks unless it asks for finer ones, +/// and Windows 11 drops that request while the window is hidden unless the +/// process opts out. Process-wide, for the whole run. +#[cfg(windows)] +pub fn use_console_timers() { + use windows_sys::Win32::Media::timeBeginPeriod; + use windows_sys::Win32::System::Threading::{ + GetCurrentProcess, PROCESS_POWER_THROTTLING_CURRENT_VERSION, PROCESS_POWER_THROTTLING_EXECUTION_SPEED, + PROCESS_POWER_THROTTLING_IGNORE_TIMER_RESOLUTION, PROCESS_POWER_THROTTLING_STATE, + ProcessPowerThrottling, SetProcessInformation, + }; + // Also: the system does not run this process at reduced speed (its + // "efficiency mode": lower clock, the slow cores of a hybrid processor) + // when its window is not the one in front, as while its owner works in + // another window or streams. The console has eight cores alike and no + // such mode. `LEONIDA_EFFICIENCY_MODE=1` leaves the system its choice. + let execution = if std::env::var_os("LEONIDA_EFFICIENCY_MODE").is_some_and(|v| v == "1") { + 0 + } else { + PROCESS_POWER_THROTTLING_EXECUTION_SPEED + }; + let keep = PROCESS_POWER_THROTTLING_STATE { + Version: PROCESS_POWER_THROTTLING_CURRENT_VERSION, + ControlMask: PROCESS_POWER_THROTTLING_IGNORE_TIMER_RESOLUTION | execution, + StateMask: 0, + }; + // SAFETY: plain process settings; `keep` outlives the call. + unsafe { + SetProcessInformation( + GetCurrentProcess(), + ProcessPowerThrottling, + (&raw const keep).cast(), + size_of_val(&keep) as u32, + ); + timeBeginPeriod(1); + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn reads_title_id_store_id_and_storage_quota() { + let text = "\u{feff}\n\ + \ + \n 639AA8DD\n\ + 1 ]]> 9&C7\ + \n 1024 \n\ + "; + let t = Title::from_manifest(text); + assert_eq!((t.id, t.storage_bytes), (0x639A_A8DD, 1024 << 20)); + assert_eq!(t.store_id, "9&C"); + assert_eq!(Title::from_manifest("").storage_bytes, 0); + } +} diff --git a/crates/leonida-hle/tests/no_dll_planting.rs b/crates/leonida-hle/tests/no_dll_planting.rs new file mode 100644 index 000000000..373e5e9b3 --- /dev/null +++ b/crates/leonida-hle/tests/no_dll_planting.rs @@ -0,0 +1,29 @@ +//! Host pass-through must only load DLLs from System32, never from the +//! current folder (e.g. a title's folder shipping its own `msvcp140_*.dll`). +#![cfg(windows)] + +use leonida_hle::{HleResolver, HostPolicy}; +use leonida_pe::ImportSymbol; + +#[test] +fn ignores_dlls_in_current_folder() { + let name = "msvcp140_leonidatest.dll"; + assert!( + HostPolicy::default().allows(name), + "test needs an allow-listed name" + ); + assert!(HostPolicy::default().allows("vcruntime140_1.dll")); + + let dir = tempfile::tempdir().unwrap(); + // Any loadable DLL will do. + std::fs::copy(r"C:\Windows\System32\version.dll", dir.path().join(name)).unwrap(); + std::env::set_current_dir(dir.path()).unwrap(); + + let symbol = ImportSymbol::Name { + hint: 0, + name: "GetFileVersionInfoSizeW".into(), + }; + let found = HleResolver::default().classify(name, &symbol); + std::env::set_current_dir(env!("CARGO_MANIFEST_DIR")).unwrap(); + assert_eq!(found, None, "DLL was loaded from the current folder"); +} diff --git a/crates/leonida-loader/Cargo.toml b/crates/leonida-loader/Cargo.toml new file mode 100644 index 000000000..1bec91272 --- /dev/null +++ b/crates/leonida-loader/Cargo.toml @@ -0,0 +1,39 @@ +[package] +name = "leonida-loader" +description = "Runs an Xbox title's original x86-64 image natively inside our process." +version.workspace = true +edition.workspace = true +rust-version.workspace = true +license.workspace = true +publish.workspace = true + +[dependencies] +leonida-core.workspace = true +leonida-pe.workspace = true +anyhow.workspace = true +thiserror.workspace = true +tracing.workspace = true +blake3.workspace = true + +[target.'cfg(windows)'.dependencies] +windows-sys = { workspace = true, features = [ + "Wdk_System_Threading", + "Win32_Foundation", + "Win32_System_Diagnostics_Debug", + "Win32_System_Diagnostics_ToolHelp", + "Win32_System_Kernel", + "Win32_System_LibraryLoader", + "Win32_System_Memory", + "Win32_System_Performance", + "Win32_System_Threading", +] } + +[dev-dependencies] +tempfile.workspace = true + +[features] +# Debugging switches (scheduled stack dumps and the like). +diagnostics = [] + +[lints] +workspace = true diff --git a/crates/leonida-loader/src/console_insn.rs b/crates/leonida-loader/src/console_insn.rs new file mode 100644 index 000000000..f0fa3645c --- /dev/null +++ b/crates/leonida-loader/src/console_insn.rs @@ -0,0 +1,596 @@ +//! Instructions the console's CPU (Zen 2) has and an Intel PC's lacks, emulated: the title's +//! code raises STATUS_ILLEGAL_INSTRUCTION on them (the title zeroes memory with a `clzero` loop at +//! its first frames), and the vectored handler steps over them here. +//! +//! Ported from XCL (github.com/ivall/xcl, GPL-2.0-only): `insn.rs` (decoder, as +//! `console_insn_decode.rs`, unchanged) and `eh.rs` `emulate_console_only`. + +#[path = "console_insn_decode.rs"] +mod decode; + +use decode::ConsoleOnly; +use std::cell::Cell; +use std::sync::atomic::{AtomicU64, Ordering::Relaxed}; +use windows_sys::Win32::System::Diagnostics::Debug::CONTEXT; + +const CONTINUE_EXECUTION: i32 = -1; + +/// Whether what Windows said about memory is remembered per thread (the regions it found +/// writable, the code bytes it found readable) and not asked again at every emulated +/// instruction. A query walks the pages of the region it answers for: asked from outside, it +/// took 2-9 ms in the title's heaps of 0.6-2.2 GB and 89 ms in its 6.2 GB page pool (run 30), +/// and the title zeroes blocks of them with `clzero` loops all through a frame: six of its +/// threads spent 25-78 % of their time inside that query (runs 29 and 30), about 27 s of +/// processor time in Windows per 9 s frame. On by default; `LEONIDA_CLZERO_ASK=1` asks every +/// time, as before. +fn remembers() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("LEONIDA_CLZERO_ASK").is_none_or(|v| v != "1")) +} + +/// Answers a remembered region gives before Windows is asked about it again: one freed or +/// protected meanwhile is forgotten then. +const ANSWERS: u32 = 4096; + +thread_local! { + /// The regions Windows last said are committed and writable (start, end), newest first, + /// and the answers they gave since they were emptied. + static WRITABLE: Cell<([(usize, usize); 4], u32)> = const { Cell::new(([(0, 0); 4], 0)) }; + /// Faulting addresses and the code bytes found readable there, newest first. + static CODE: Cell<[(usize, usize); 8]> = const { Cell::new([(0, 0); 8]) }; +} + +/// Instructions emulated, the times Windows was asked about memory for them, and the bytes +/// `clzero` loops zeroed, since the start. +static EMULATED: AtomicU64 = AtomicU64::new(0); +static ASKED: AtomicU64 = AtomicU64::new(0); +static ZEROED: AtomicU64 = AtomicU64::new(0); + +/// Exceptions taken by kind since the last line: a lone `clzero`, the 12-byte loop, the +/// 15-byte loop taken whole, `monitorx`, `mwaitx`, everything else; and the 64-byte lines the +/// 15-byte loops zeroed (each was an exception of its own before they were taken whole). +static KINDS: [AtomicU64; 7] = [const { AtomicU64::new(0) }; 7]; +const K_CLZERO: usize = 0; +const K_LOOP12: usize = 1; +const K_LOOP15: usize = 2; +const K_MONITORX: usize = 3; +const K_MWAITX: usize = 4; +const K_OTHER: usize = 5; +const K_LOOP15_LINES: usize = 6; + +/// Waits the title made with `monitorx` / `mwaitx` (it waits for a fence that way, reading +/// the fence's value in memory: its +0x4fb0ad0) that have ended since the last line: how +/// many, their microseconds, and both again for those of 1 ms and more, 5 ms and more, +/// 20 ms and more. +static WAITS: [AtomicU64; 8] = [const { AtomicU64::new(0) }; 8]; +/// Waits said in the log one by one. +static WAITS_SAID: AtomicU64 = AtomicU64::new(0); +/// When the last line was written, in milliseconds of [`clock_us`]. +static LINE_AT: AtomicU64 = AtomicU64::new(0); + +thread_local! { + /// The address and the value this thread last armed a monitor for (`monitorx`: rax, and + /// the title's wanted value in rsi). + static MONITOR: Cell<(usize, u64)> = const { Cell::new((0, 0)) }; + /// This thread's wait under way: when it began and when its last `mwaitx` was, in + /// microseconds, what it waits for, and its `mwaitx` count. + static WAIT: Cell<(u64, u64, usize, u64, u32)> = const { Cell::new((0, 0, 0, 0, 0)) }; +} + +/// Microseconds on the performance counter. +fn clock_us() -> u64 { + static PER_SECOND: std::sync::OnceLock = std::sync::OnceLock::new(); + let per_second = *PER_SECOND.get_or_init(|| { + let mut f = 0i64; + // SAFETY: a valid out pointer. + unsafe { windows_sys::Win32::System::Performance::QueryPerformanceFrequency(&mut f) }; + f.max(1) + }); + let mut now = 0i64; + // SAFETY: a valid out pointer. + unsafe { windows_sys::Win32::System::Performance::QueryPerformanceCounter(&mut now) }; + (now as u128 * 1_000_000 / per_second as u128) as u64 +} + +/// Whether events are said one by one now: four seconds of every two minutes of the wall +/// clock, the same seconds in which the fence meter of the graphics side says its own +/// (`leonida_gpu::fence::pace`), so that the two can be laid side by side. +fn detail_now() -> bool { + std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).is_ok_and(|d| d.as_secs() % 120 < 4) +} + +/// Whether the 15-byte `clzero` loop is taken whole (`LEONIDA_CLZERO_LOOP15=0`: line by +/// line, as before). +fn loop15() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("LEONIDA_CLZERO_LOOP15").is_none_or(|v| v != "0")) +} + +/// A wait of this thread has ended: counted, and said if it is one to say. +fn wait_ended(begin: u64, last: u64, address: usize, wanted: u64, spins: u32) { + let us = last.saturating_sub(begin); + for (i, least) in [0u64, 1_000, 5_000, 20_000].into_iter().enumerate() { + if us >= least { + WAITS[2 * i].fetch_add(1, Relaxed); + WAITS[2 * i + 1].fetch_add(us, Relaxed); + } + } + if us >= 500 && (detail_now() || WAITS_SAID.fetch_add(1, Relaxed) < 40) { + // SAFETY: no preconditions. + let thread = unsafe { windows_sys::Win32::System::Threading::GetCurrentThreadId() }; + tracing::info!( + "mwait: thread {thread} waited {:.1} ms for the value at {address:#x} to reach {wanted} ({spins} mwaitx)", + us as f64 / 1e3 + ); + } +} + +/// A `mwaitx` of this thread: part of the wait under way, or the first of a new one. +fn wait_step() { + let now = clock_us(); + let (address, wanted) = MONITOR.with(Cell::get); + let (begin, last, was_at, was_for, spins) = WAIT.with(Cell::get); + if begin != 0 && was_at == address && was_for == wanted && now.saturating_sub(last) < 2_000 { + WAIT.with(|w| w.set((begin, now, address, wanted, spins + 1))); + return; + } + if begin != 0 { + wait_ended(begin, last, was_at, was_for, spins); + } + WAIT.with(|w| w.set((now, now, address, wanted, 1))); +} + +/// A line every five seconds: exceptions a second by kind, and the waits that ended. +fn line() { + let now = clock_us() / 1000; + let last = LINE_AT.load(Relaxed); + if now < last + 5_000 || LINE_AT.compare_exchange(last, now, Relaxed, Relaxed).is_err() { + return; + } + if last == 0 { + return; + } + let seconds = (now - last) as f64 / 1e3; + let k: Vec = KINDS.iter().map(|k| k.swap(0, Relaxed) as f64 / seconds).collect(); + let w: Vec = WAITS.iter().map(|w| w.swap(0, Relaxed) as f64).collect(); + tracing::info!( + "console CPU instructions, exceptions a second: clzero alone {:.0}, its 12-byte loop {:.0}, its 15-byte loop taken whole {:.0} ({:.0} lines a second, each an exception \ + before; LEONIDA_CLZERO_LOOP15=0: again), monitorx {:.0}, mwaitx {:.0}, others {:.0} | mwaitx waits ended a second: {:.0}, {:.1} ms of thread time a second; of 1 ms and \ + more {:.1} ({:.1} ms), of 5 ms and more {:.1} ({:.1} ms), of 20 ms and more {:.1} ({:.1} ms)", + k[K_CLZERO], + k[K_LOOP12], + k[K_LOOP15], + k[K_LOOP15_LINES], + k[K_MONITORX], + k[K_MWAITX], + k[K_OTHER], + w[0] / seconds, + w[1] / seconds / 1e3, + w[2] / seconds, + w[3] / seconds / 1e3, + w[4] / seconds, + w[5] / seconds / 1e3, + w[6] / seconds, + w[7] / seconds / 1e3, + ); +} + +fn readable(va: usize, bytes: usize) -> bool { + use windows_sys::Win32::System::Memory::{MEM_COMMIT, MEMORY_BASIC_INFORMATION, PAGE_GUARD, PAGE_NOACCESS, VirtualQuery}; + // SAFETY: plain data filled in by the query. + let mut m: MEMORY_BASIC_INFORMATION = unsafe { std::mem::zeroed() }; + // SAFETY: a valid out pointer of the right size. + let found = unsafe { VirtualQuery(va as *const _, &mut m, size_of_val(&m)) } != 0; + ASKED.fetch_add(1, Relaxed); + found && m.State == MEM_COMMIT && m.Protect & (PAGE_NOACCESS | PAGE_GUARD) == 0 && m.BaseAddress as usize + m.RegionSize >= va + bytes +} + +fn writable(va: usize, bytes: usize) -> bool { + writable_to(va, va + bytes) == Some(va + bytes) +} + +/// Where the committed, writable memory that `va` lies in ends, at most `end`; None if `va` +/// is not in such memory. A region found is remembered ([`remembers`]). +/// shortcut: a remembered region that was freed or protected since is written all the same +/// for up to [`ANSWERS`] answers: the write then faults inside the handler, which the guard +/// on view memory opens as it does any write, and which is a crash otherwise (as the +/// unchecked single-line emulation behind this one already is). +fn writable_to(va: usize, end: usize) -> Option { + use windows_sys::Win32::System::Memory::{MEM_COMMIT, MEMORY_BASIC_INFORMATION, PAGE_EXECUTE_READWRITE, PAGE_READWRITE, VirtualQuery}; + let remember = remembers(); + if remember { + let (regions, answers) = WRITABLE.with(Cell::get); + if let Some(&(_, to)) = regions.iter().find(|&&(from, to)| from <= va && va < to) { + let next = if answers >= ANSWERS { ([(0, 0); 4], 0) } else { (regions, answers + 1) }; + WRITABLE.with(|w| w.set(next)); + return Some(to.min(end)); + } + } + // SAFETY: plain data filled in by the query. + let mut m: MEMORY_BASIC_INFORMATION = unsafe { std::mem::zeroed() }; + // SAFETY: a valid out pointer of the right size. + let found = unsafe { VirtualQuery(va as *const _, &mut m, size_of_val(&m)) } != 0; + ASKED.fetch_add(1, Relaxed); + if !found || m.State != MEM_COMMIT || m.Protect & (PAGE_READWRITE | PAGE_EXECUTE_READWRITE) == 0 { + return None; + } + let (from, to) = (m.BaseAddress as usize, m.BaseAddress as usize + m.RegionSize); + if remember { + WRITABLE.with(|w| { + let (mut regions, answers) = w.get(); + regions.rotate_right(1); + regions[0] = (from, to); + w.set((regions, answers)); + }); + } + Some(to.min(end)) +} + +/// The register `r` of `ctx` (CONTEXT order: rax, rcx, rdx, rbx, rsp, rbp, rsi, rdi, r8..r15). +fn register(ctx: &mut CONTEXT, r: u8) -> &mut u64 { + match r & 15 { + 0 => &mut ctx.Rax, + 1 => &mut ctx.Rcx, + 2 => &mut ctx.Rdx, + 3 => &mut ctx.Rbx, + 4 => &mut ctx.Rsp, + 5 => &mut ctx.Rbp, + 6 => &mut ctx.Rsi, + 7 => &mut ctx.Rdi, + 8 => &mut ctx.R8, + 9 => &mut ctx.R9, + 10 => &mut ctx.R10, + 11 => &mut ctx.R11, + 12 => &mut ctx.R12, + 13 => &mut ctx.R13, + 14 => &mut ctx.R14, + _ => &mut ctx.R15, + } +} + +/// Where the lines of the loop `mov rax, ptr; add ptr, 0x40; clzero; cmp ptr, end; jb` end, +/// from the state the loop has at its `clzero`: the line at `rax` is zeroed now, and one +/// more at `ptr` for every pass the `cmp` sends back. None if this is not the plain case +/// the loop makes (the line at `rax` on a 64-byte boundary, `ptr` the next line, under +/// 2 GiB in all): then every line is taken alone, as the instruction itself does it. +fn loop15_end(rax: usize, ptr: usize, end: usize) -> Option { + if rax & 63 != 0 || ptr != rax.wrapping_add(64) || ptr < rax { + return None; + } + let more = if ptr < end { (end - ptr).div_ceil(64) } else { 0 }; + let last = ptr.checked_add(more.checked_mul(64)?)?; + (last - rax < 2 << 30).then_some(last) +} + +/// The `clzero` at `rip` in the loop `mov rax, ptr; add ptr, 0x40; clzero; cmp ptr, end; jb`, +/// with all the lines the loop would still zero: `Some(true)` when they are zeroed and the +/// registers stand as the loop leaves them at its last `clzero` (the caller steps over the +/// instruction; the title's own `cmp` and `jb` then leave the loop), `Some(false)` when the +/// first line is not writable (the real instruction faults there too), and when only a +/// first part was writable the registers stand at the line after it, where the instruction +/// runs again. None if it is not that loop: the lone instruction is emulated. +/// +/// # Safety +/// `rip` is the faulting instruction of `ctx`, whose bytes were read. +unsafe fn clzero_loop15(ctx: &mut CONTEXT, rip: usize, ptr_reg: u8, end_reg: u8) -> Option { + // The seven bytes in front of it: in the same page as the instruction, which ran. + if rip & 0xFFF < 7 && !readable(rip - 7, 7) { + return None; + } + // SAFETY: readable, as checked or as the instruction's own page. + let before = unsafe { std::slice::from_raw_parts((rip - 7) as *const u8, 7) }; + if !decode::loop15_head(before, ptr_reg) || end_reg == 0 || end_reg == ptr_reg { + return None; + } + let rax = ctx.Rax as usize; + let ptr = *register(ctx, ptr_reg) as usize; + let end = *register(ctx, end_reg) as usize; + let last = loop15_end(rax, ptr, end)?; + // Region by region, as the 12-byte loop: a block may lie across several views. + let mut at = rax; + while at < last { + let Some(to) = writable_to(at, last) else { break }; + // A region ends on a page boundary, so `to` is on a line boundary as `at` is. + // SAFETY: committed and writable from `at` to `to`. + unsafe { std::ptr::write_bytes(at as *mut u8, 0, to - at) }; + at = to; + } + if at == rax { + return Some(false); + } + ZEROED.fetch_add((at - rax) as u64, Relaxed); + KINDS[K_LOOP15_LINES].fetch_add(((at - rax) / 64) as u64, Relaxed); + if at < last { + // What follows is not writable: the loop stands at that line's `clzero` now, where + // the real one faults too. The instruction runs again (the caller must not step). + ctx.Rax = at as u64; + *register(ctx, ptr_reg) = (at + 64) as u64; + ctx.Rip = (rip as u64).wrapping_sub(3); + return Some(true); + } + ctx.Rax = (last - 64) as u64; + *register(ctx, ptr_reg) = last as u64; + Some(true) +} + +/// An illegal instruction at `ctx.Rip`: a console-only one is emulated and stepped over +/// (`CONTINUE_EXECUTION`); anything else returns 0 (the crash report and the title's handlers +/// see it). +/// +/// # Safety +/// `ctx` is the faulting thread's context, from the exception being dispatched. +pub(crate) unsafe fn emulate(ctx: &mut CONTEXT) -> i32 { + let rip = ctx.Rip as usize; + // The same few instructions fault again and again: their bytes are asked about once. + let known = if remembers() { CODE.with(Cell::get) } else { [(0, 0); 8] }; + let n = match known.iter().find(|&&(at, n)| at == rip && n > 0) { + Some(&(_, n)) => n, + None => { + if !readable(rip, 1) { + return 0; + } + let n = (1..=16).rev().find(|&n| readable(rip, n)).unwrap_or(0); + if remembers() { + let mut known = known; + known.rotate_right(1); + known[0] = (rip, n); + CODE.with(|c| c.set(known)); + } + n + } + }; + // SAFETY: `n` bytes at `rip` are readable. + let code = unsafe { std::slice::from_raw_parts(rip as *const u8, n) }; + let Some((what, len)) = decode::decode(code) else { return 0 }; + static SEEN: std::sync::Mutex>> = std::sync::Mutex::new(Vec::new()); + if let Ok(mut seen) = SEEN.lock() + && !seen.contains(&std::mem::discriminant(&what)) + { + seen.push(std::mem::discriminant(&what)); + if what != ConsoleOnly::Ud2 { + tracing::warn!(instruction = ?what, at = format_args!("{rip:#x}"), "a console CPU instruction this CPU lacks: emulated (logged once)"); + } + } + match what { + ConsoleOnly::Ud2 => return 0, + ConsoleOnly::Clwb => { + // nothing to write back on the PC: patched to NOPs, no exception next time + use windows_sys::Win32::System::Memory::{PAGE_EXECUTE_READWRITE, VirtualProtect}; + let mut old = 0u32; + // SAFETY: the instruction's own bytes, made writable for the patch and restored. + unsafe { + if VirtualProtect(rip as *const _, len, PAGE_EXECUTE_READWRITE, &mut old) != 0 { + std::slice::from_raw_parts_mut(rip as *mut u8, len).fill(0x90); + VirtualProtect(rip as *const _, len, old, &mut old); + } + } + } + ConsoleOnly::Monitorx => { + KINDS[K_MONITORX].fetch_add(1, Relaxed); + MONITOR.with(|m| m.set((ctx.Rax as usize, ctx.Rsi))); + } + ConsoleOnly::Mwaitx => { + KINDS[K_MWAITX].fetch_add(1, Relaxed); + wait_step(); + std::hint::spin_loop() + } + ConsoleOnly::Clzero | ConsoleOnly::ClzeroStep { .. } => { + // The loop `mov rax, ptr; add ptr, 0x40; clzero; cmp ptr, end; jb` (the title's + // +0x4e8ab4c and three more like it zero 896 to 7,040 bytes each, a line an + // exception) is taken whole from the line it stands at. + if let ConsoleOnly::ClzeroStep { ptr_reg, end_reg } = what + && loop15() + && let Some(done) = unsafe { clzero_loop15(ctx, rip, ptr_reg, end_reg) } + { + if !done { + return 0; + } + ctx.Rip += len as u64; + EMULATED.fetch_add(1, Relaxed); + KINDS[K_LOOP15].fetch_add(1, Relaxed); + line(); + return CONTINUE_EXECUTION; + } + KINDS[K_CLZERO].fetch_add(1, Relaxed); + // with an address-size prefix (0x67) the line is at EAX, zero-extended + let a32 = code[..len - 3].contains(&0x67); + let line = (if a32 { ctx.Rax & 0xFFFF_FFFF } else { ctx.Rax } as usize) & !63; + if !writable(line, 64) { + return 0; // the real instruction faults there too + } + // SAFETY: the 64-byte line is committed and writable. + unsafe { std::ptr::write_bytes(line as *mut u8, 0, 64) }; + } + ConsoleOnly::ClzeroLoop { end_reg } => { + KINDS[K_LOOP12].fetch_add(1, Relaxed); + // the whole `clzero; add rax,40h; cmp rax,end; jb` loop at once + let regs: [u64; 16] = [ + ctx.Rax, ctx.Rcx, ctx.Rdx, ctx.Rbx, ctx.Rsp, ctx.Rbp, ctx.Rsi, ctx.Rdi, ctx.R8, ctx.R9, ctx.R10, ctx.R11, ctx.R12, ctx.R13, ctx.R14, ctx.R15, + ]; + let end = regs[end_reg as usize & 15] as usize; + let start = ctx.Rax as usize; + if end > start && end - start < 2 << 30 { + // Region by region: a block may lie across several (the title's pages are + // mapped one view each), and one answer for all of it was a refusal, after + // which every 64-byte line took an exception of its own. + let mut at = start; + while at < end { + let Some(to) = writable_to(at, end) else { break }; + // SAFETY: committed and writable from `at` to `to`. + unsafe { std::ptr::write_bytes(at as *mut u8, 0, to - at) }; + at = to; + } + if at == start { + return 0; + } + ZEROED.fetch_add((at - start) as u64, Relaxed); + if at < end { + // What follows is not writable: the loop goes on there (the same + // instruction again), where the real one faults too. + ctx.Rax = at as u64; + return CONTINUE_EXECUTION; + } + } + ctx.Rax = end as u64; + } + ConsoleOnly::Rdpru => { + let mut v = 0i64; + // SAFETY: a valid out pointer. + unsafe { windows_sys::Win32::System::Performance::QueryPerformanceCounter(&mut v) }; + let v = if ctx.Rcx as u32 <= 1 { v as u64 } else { 0 }; + ctx.Rax = v & 0xFFFF_FFFF; + ctx.Rdx = v >> 32; + } + ConsoleOnly::Rdpid(r) => { + // SAFETY: no preconditions. + let cpu = unsafe { windows_sys::Win32::System::Threading::GetCurrentProcessorNumber() } as u64; + let regs: [&mut u64; 16] = [ + &mut ctx.Rax, &mut ctx.Rcx, &mut ctx.Rdx, &mut ctx.Rbx, &mut ctx.Rsp, &mut ctx.Rbp, &mut ctx.Rsi, &mut ctx.Rdi, &mut ctx.R8, &mut ctx.R9, &mut ctx.R10, &mut ctx.R11, &mut ctx.R12, &mut ctx.R13, + &mut ctx.R14, &mut ctx.R15, + ]; + *regs[r as usize & 15] = cpu; + } + // the low quadword changes; the high one is zeroed, as a Zen 5 does + ConsoleOnly::Extrq { dst, src, len, idx } => { + // SAFETY: the context's XMM registers (CONTEXT_FLOATING_POINT is captured for exceptions). + let x = unsafe { &mut ctx.Anonymous.FltSave.XmmRegisters }; + let (len, idx) = match src { + Some(s) => { + let c = x[s as usize & 15].Low; + (c as u8, (c >> 8) as u8) + } + None => (len, idx), + }; + let d = &mut x[dst as usize & 15]; + d.Low = decode::extrq(d.Low, len, idx); + d.High = 0; + } + ConsoleOnly::Insertq { dst, src, reg, len, idx } => { + // SAFETY: as above. + let x = unsafe { &mut ctx.Anonymous.FltSave.XmmRegisters }; + let s = x[src as usize & 15]; + let (len, idx) = if reg { (s.High as u8, (s.High >> 8) as u8) } else { (len, idx) }; + let d = &mut x[dst as usize & 15]; + d.Low = decode::insertq(d.Low, s.Low, len, idx); + d.High = 0; + } + } + if !matches!( + what, + ConsoleOnly::Monitorx | ConsoleOnly::Mwaitx | ConsoleOnly::Clzero | ConsoleOnly::ClzeroStep { .. } | ConsoleOnly::ClzeroLoop { .. } + ) { + KINDS[K_OTHER].fetch_add(1, Relaxed); + } + line(); + ctx.Rip += len as u64; + // How often this runs at all (each one is an exception: a trip into Windows and back). + let emulated = EMULATED.fetch_add(1, Relaxed) + 1; + if emulated >= 1 << 16 && emulated.is_power_of_two() { + tracing::info!( + emulated, + asked = ASKED.load(Relaxed), + zeroed_mb = ZEROED.load(Relaxed) >> 20, + "console CPU instructions emulated so far, the times Windows was asked about memory for them, and what clzero loops zeroed" + ); + } + CONTINUE_EXECUTION +} + +#[cfg(test)] +mod tests { + use super::*; + + /// What the title's loop leaves, run line by line as the processor would: the lines it + /// zeroed and the registers (rax, ptr) at the end, from the state at its first `clzero`. + fn by_hand(mut rax: usize, mut ptr: usize, end: usize) -> (Vec, usize, usize) { + let mut lines = vec![rax & !63]; + while ptr < end { + rax = ptr; + ptr += 0x40; + lines.push(rax & !63); + } + (lines, rax, ptr) + } + + #[test] + fn the_15_byte_loop_ends_where_the_processor_would_end_it() { + for (rax, len) in [(0x1000usize, 7040usize), (0x1000, 3264), (0x1000, 3776), (0x1000, 896), (0x4000, 64), (0x4000, 65), (0x4000, 100), (0x4000, 1), (0x4000, 0), (0x8000, 128)] { + let (ptr, end) = (rax + 64, rax + len); + let (lines, last_rax, last_ptr) = by_hand(rax, ptr, end); + let last = loop15_end(rax, ptr, end).expect("the plain case"); + assert_eq!(last, last_ptr, "rax {rax:#x} len {len}"); + assert_eq!(last - 64, last_rax, "rax {rax:#x} len {len}"); + assert_eq!((last - rax) / 64, lines.len(), "rax {rax:#x} len {len}"); + assert_eq!(*lines.last().unwrap(), last - 64); + } + // an end before the pointer: the line at rax alone + assert_eq!(loop15_end(0x1000, 0x1040, 0x800), Some(0x1040)); + // not the plain case: a line not on a boundary, a pointer that is not the next line + assert_eq!(loop15_end(0x1008, 0x1048, 0x2000), None); + assert_eq!(loop15_end(0x1000, 0x1080, 0x2000), None); + assert_eq!(loop15_end(0x1000, 0x1040, 0x1000 + (3 << 30)), None, "over 2 GiB"); + } + + /// The loop as the title has it at +0x4e8ab4c, for the given registers. + fn code(ptr_reg: u8, end_reg: u8) -> Vec { + let (ph, pl, eh, el) = (ptr_reg >> 3, ptr_reg & 7, end_reg >> 3, end_reg & 7); + vec![ + 0x48 | ph << 2, 0x89, 0xC0 | pl << 3, // mov rax, ptr + 0x48 | ph, 0x83, 0xC0 | pl, 0x40, // add ptr, 0x40 + 0x0F, 0x01, 0xFC, // clzero + 0x48 | eh << 2 | ph, 0x39, 0xC0 | el << 3 | pl, // cmp ptr, end + 0x72, 0xF1, // jb -15 + 0x90, + ] + } + + #[test] + fn the_15_byte_loop_is_zeroed_whole_and_leaves_the_loop_s_registers() { + for (ptr_reg, end_reg, len) in [(10u8, 11u8, 7040usize), (9, 10, 3264), (8, 9, 3776), (2, 8, 896), (10, 11, 64), (10, 11, 100)] { + let code = code(ptr_reg, end_reg); + // a block of 0xAA with room on both sides, its start on a line boundary + let mut block = vec![0xAAu8; 16384]; + let base = (block.as_mut_ptr() as usize + 4096 + 63) & !63; + // SAFETY: plain data. + let mut ctx: CONTEXT = unsafe { std::mem::zeroed() }; + ctx.Rip = code.as_ptr() as u64 + 7; + ctx.Rax = base as u64; + *register(&mut ctx, ptr_reg) = base as u64 + 64; + *register(&mut ctx, end_reg) = (base + len) as u64; + // SAFETY: the context points at the code above. + assert_eq!(unsafe { emulate(&mut ctx) }, CONTINUE_EXECUTION); + let (lines, last_rax, last_ptr) = by_hand(base, base + 64, base + len); + assert_eq!(ctx.Rip, code.as_ptr() as u64 + 10, "at the loop's own cmp"); + assert_eq!(ctx.Rax as usize, last_rax); + assert_eq!(*register(&mut ctx, ptr_reg) as usize, last_ptr); + assert_eq!(*register(&mut ctx, end_reg) as usize, base + len, "the end is left alone"); + let zeroed = lines.len() * 64; + let at = base - block.as_ptr() as usize; + assert!(block[at..at + zeroed].iter().all(|&b| b == 0), "{zeroed} bytes zeroed"); + assert!(block[..at].iter().all(|&b| b == 0xAA), "nothing before the block"); + assert!(block[at + zeroed..].iter().all(|&b| b == 0xAA), "nothing after its last line"); + } + } + + #[test] + fn a_clzero_that_only_looks_like_the_loop_is_one_line() { + // the same bytes behind it, another head in front (add ptr, 0x80): one line, one step + let mut code = code(10, 11); + code[6] = 0x80; + let mut block = vec![0xAAu8; 8192]; + let base = (block.as_mut_ptr() as usize + 2048 + 63) & !63; + // SAFETY: plain data. + let mut ctx: CONTEXT = unsafe { std::mem::zeroed() }; + ctx.Rip = code.as_ptr() as u64 + 7; + ctx.Rax = base as u64; + ctx.R10 = base as u64 + 64; + ctx.R11 = base as u64 + 640; + // SAFETY: the context points at the code above. + assert_eq!(unsafe { emulate(&mut ctx) }, CONTINUE_EXECUTION); + assert_eq!(ctx.Rip, code.as_ptr() as u64 + 10); + assert_eq!((ctx.Rax, ctx.R10), (base as u64, base as u64 + 64), "registers untouched"); + let at = base - block.as_ptr() as usize; + assert!(block[at..at + 64].iter().all(|&b| b == 0)); + assert!(block[at + 64..].iter().all(|&b| b == 0xAA), "one line only"); + } +} diff --git a/crates/leonida-loader/src/console_insn_decode.rs b/crates/leonida-loader/src/console_insn_decode.rs new file mode 100644 index 000000000..ccfeb4005 --- /dev/null +++ b/crates/leonida-loader/src/console_insn_decode.rs @@ -0,0 +1,284 @@ +//! Instructions the console's CPU (Zen 2) has and a PC's may lack – a title raises +//! STATUS_ILLEGAL_INSTRUCTION on them on an Intel CPU before Ice Lake / Alder Lake (CLWB, +//! SHA) or on any Intel CPU (CLZERO, RDPRU, MONITORX / MWAITX and SSE4a's EXTRQ / INSERTQ, +//! which are AMD's). The exception handler (`eh`) emulates the ones decoded here and steps over +//! them. + +/// A console-only instruction at the faulting address. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum ConsoleOnly { + /// `clwb m8`: write a cache line back – nothing to do, the PC's memory is coherent + Clwb, + /// `clzero`: zero the 64-byte cache line at rAX + Clzero, + /// `clzero` loop: `clzero; add rax, 0x40; cmp rax, ; jb -12` – zero `[rax..reg)` + ClzeroLoop { end_reg: u8 }, + /// `clzero` in the loop `mov rax, ; add , 0x40; clzero; cmp , ; jb -15` + /// (the seven bytes before it are the caller's to check, [`loop15_head`]): the length is + /// the `clzero`'s own + ClzeroStep { ptr_reg: u8, end_reg: u8 }, + /// `rdpru`: ecx = 0 MPERF / 1 APERF → edx:eax (a counter) + Rdpru, + /// `monitorx` / `mwaitx`: a wait the emulation skips + Monitorx, + Mwaitx, + /// `rdpid r64`: TSC_AUX (the processor number) into the register (CONTEXT order: rax, rcx, + /// rdx, rbx, rsp, rbp, rsi, rdi, r8..r15) + Rdpid(u8), + /// SSE4a `extrq xmm, imm8 (length), imm8 (index)` / `extrq xmm1, xmm2` (`src` Some: the + /// length and index in xmm2's bits 5:0 and 13:8): a bit field of the low quadword, moved + /// down and zero-extended (the high quadword zeroed). Registers are XMM numbers 0..15. + Extrq { dst: u8, src: Option, len: u8, idx: u8 }, + /// SSE4a `insertq xmm1, xmm2, imm8 (length), imm8 (index)` / `insertq xmm1, xmm2` (`reg`: + /// the length and index in xmm2's bits 69:64 and 77:72): the low bits of xmm2 put into a + /// bit field of xmm1's low quadword. + Insertq { dst: u8, src: u8, reg: bool, len: u8, idx: u8 }, + /// `ud2`: the title's own trap (not emulated) + Ud2, +} + +/// A field length of SSE4a's six bits: 0 is 64. +fn field_len(len: u8) -> u32 { + match len & 63 { + 0 => 64, + n => n as u32, + } +} + +/// EXTRQ on a low quadword: `len` bits from bit `idx`, zero-extended (a field past bit 63 is +/// undefined on the console; here it is what a shift gives). +pub fn extrq(v: u64, len: u8, idx: u8) -> u64 { + let (len, idx) = (field_len(len), (idx & 63) as u32); + let field = v.checked_shr(idx).unwrap_or(0); + if len >= 64 { + field + } else { + field & ((1u64 << len) - 1) + } +} + +/// INSERTQ on a low quadword: the low `len` bits of `src` put at bit `idx` of `dst`. +pub fn insertq(dst: u64, src: u64, len: u8, idx: u8) -> u64 { + let (len, idx) = (field_len(len), (idx & 63) as u32); + let ones = if len >= 64 { u64::MAX } else { (1u64 << len) - 1 }; + let mask = ones.checked_shl(idx).unwrap_or(0); + (dst & !mask) | ((src & ones).checked_shl(idx).unwrap_or(0) & mask) +} + +/// The length of a ModRM-encoded operand (ModRM, SIB and displacement) at `b[0]`, None when the +/// bytes run out. +fn modrm_len(b: &[u8]) -> Option { + let modrm = *b.first()?; + let (md, rm) = (modrm >> 6, modrm & 7); + if md == 3 { + return Some(1); + } + let mut len = 1; + let mut base = rm; + if rm == 4 { + base = *b.get(1)? & 7; + len += 1; + } + len += match md { + 0 if base == 5 => 4, // disp32 (rip-relative, or a SIB without a base) + 0 => 0, + 1 => 1, + _ => 4, + }; + (b.len() >= len).then_some(len) +} + +/// Whether `before`, the seven bytes in front of a [`ConsoleOnly::ClzeroStep`], are +/// `mov rax, ; add , 0x40` for that pointer register (neither rax nor rsp). +pub fn loop15_head(before: &[u8], ptr_reg: u8) -> bool { + let (hi, lo) = (ptr_reg >> 3 & 1, ptr_reg & 7); + ptr_reg != 0 + && ptr_reg != 4 + && before.len() == 7 + // mov rax, ptr: REX.W (+R for r8..r15) 89 /r with rm = rax + && before[0] == 0x48 | hi << 2 + && before[1] == 0x89 + && before[2] == 0xC0 | lo << 3 + // add ptr, 0x40: REX.W (+B) 83 /0 ib + && before[3] == 0x48 | hi + && before[4] == 0x83 + && before[5] == 0xC0 | lo + && before[6] == 0x40 +} + +/// The console-only instruction at the start of `code` and its length. +pub fn decode(code: &[u8]) -> Option<(ConsoleOnly, usize)> { + let mut i = 0; + // `rep`: the last of F2 / F3, which decides between them (and over 66) for SSE4a + let (mut p66, mut pf3, mut rep, mut rex) = (false, false, 0u8, 0u8); + while let Some(&b) = code.get(i) { + match b { + 0x66 => p66 = true, + 0xF2 => rep = 0xF2, + 0xF3 => { + pf3 = true; + rep = 0xF3; + } + 0x2E | 0x3E | 0x26 | 0x36 | 0x64 | 0x65 | 0x67 => {} + // REX counts only right before the opcode: one before a legacy prefix is ignored + 0x40..=0x4F => { + rex = b; + i += 1; + continue; + } + _ => break, + } + rex = 0; + i += 1; + } + if *code.get(i)? != 0x0F { + return None; + } + match (*code.get(i + 1)?, code.get(i + 2).copied()) { + (0x01, Some(0xFC)) => { + // clzero (0F 01 FC); add rax, 0x40 (48 83 C0 40); cmp rax, ([48|4C] 39 modrm); jb -12 (72 F4) + // (not after an 0x67: that CLZERO is at EAX, and the jb goes back to the 0F, past the + // prefix – it is stepped alone, the loop is taken from the next one) + if code.len() >= i + 12 + && !code[..i].contains(&0x67) + && code[i + 3..i + 7] == [0x48, 0x83, 0xC0, 0x40] + && (code[i + 7] == 0x48 || code[i + 7] == 0x4C) + && code[i + 8] == 0x39 + && code[i + 10..i + 12] == [0x72, 0xF4] + { + let rex_r = code[i + 7] == 0x4C; + let modrm = code[i + 9]; + let reg_idx = ((modrm >> 3) & 7) | if rex_r { 8 } else { 0 }; + Some((ConsoleOnly::ClzeroLoop { end_reg: reg_idx }, i + 12)) + } else if i == 0 + && code.len() >= 8 + && code[3] & 0xF8 == 0x48 + && code[3] & 0x02 == 0 + && code[4] == 0x39 + && code[5] >> 6 == 3 + && code[6..8] == [0x72, 0xF1] + { + // clzero; cmp , (REX.W 39 /r, register form); jb -15 + let (rex, modrm) = (code[3], code[5]); + let end_reg = ((modrm >> 3) & 7) | (rex & 4) << 1; + let ptr_reg = (modrm & 7) | (rex & 1) << 3; + Some((ConsoleOnly::ClzeroStep { ptr_reg, end_reg }, 3)) + } else { + Some((ConsoleOnly::Clzero, i + 3)) + } + } + (0x01, Some(0xFD)) => Some((ConsoleOnly::Rdpru, i + 3)), + (0x01, Some(0xFA)) => Some((ConsoleOnly::Monitorx, i + 3)), + (0x01, Some(0xFB)) => Some((ConsoleOnly::Mwaitx, i + 3)), + (0x0B, _) => Some((ConsoleOnly::Ud2, i + 2)), + // SSE4a: register operands only (ModRM mod 3); REX.R extends reg, REX.B rm + // (the last of F2 / F3 decides: F2 INSERTQ, F3 #UD; neither with 66: EXTRQ) + (0x78 | 0x79, Some(m)) if (rep == 0xF2 || (rep == 0 && p66)) && m >> 6 == 3 => { + let reg = ((m >> 3) & 7) | (rex & 4) << 1; + let rm = (m & 7) | (rex & 1) << 3; + let imm = |k: usize| code.get(i + 3 + k).copied(); + match (code[i + 1], rep == 0xF2) { + // extrq xmm(rm), imm8, imm8 – the ModRM reg field is /0 + (0x78, false) if (m >> 3) & 7 == 0 => Some((ConsoleOnly::Extrq { dst: rm, src: None, len: imm(0)?, idx: imm(1)? }, i + 5)), + (0x79, false) => Some((ConsoleOnly::Extrq { dst: reg, src: Some(rm), len: 0, idx: 0 }, i + 3)), + (0x78, true) => Some((ConsoleOnly::Insertq { dst: reg, src: rm, reg: false, len: imm(0)?, idx: imm(1)? }, i + 5)), + (0x79, true) => Some((ConsoleOnly::Insertq { dst: reg, src: rm, reg: true, len: 0, idx: 0 }, i + 3)), + _ => None, + } + } + // 66 0F AE /6 with a memory operand (without 66 it is xsaveopt) + (0xAE, Some(m)) if p66 && (m >> 3) & 7 == 6 && m >> 6 != 3 => Some((ConsoleOnly::Clwb, i + 2 + modrm_len(&code[i + 2..])?)), + // F3 0F C7 /7 with a register operand + (0xC7, Some(m)) if pf3 && (m >> 3) & 7 == 7 && m >> 6 == 3 => Some((ConsoleOnly::Rdpid((m & 7) | (rex & 1) << 3), i + 3)), + _ => None, + } +} + + +#[cfg(test)] +mod tests { + use super::*; + + /// EXTRQ / INSERTQ as AMD's manual gives them: a length of 0 is 64. + #[test] + fn sse4a_bit_fields() { + assert_eq!(extrq(0x1234_5678_9ABC_DEF0, 8, 16), 0xBC); + assert_eq!(extrq(0x1234_5678_9ABC_DEF0, 0, 0), 0x1234_5678_9ABC_DEF0); + assert_eq!(extrq(0x8000_0000_0000_0000, 1, 63), 1); + assert_eq!(insertq(0xFFFF_FFFF_FFFF_FFFF, 0xAB, 8, 8), 0xFFFF_FFFF_FFFF_ABFF); + assert_eq!(insertq(0, 0x1FF, 4, 60), 0xF000_0000_0000_0000); + assert_eq!(insertq(0x1111, 0xDEAD_BEEF_0000_0000, 0, 0), 0xDEAD_BEEF_0000_0000); + for (v, len, idx) in [(0x0123_4567_89AB_CDEFu64, 12u8, 20u8), (u64::MAX, 63, 1), (0x55, 3, 0)] { + assert_eq!(extrq(insertq(0, v, len, idx), len, idx), extrq(v, len, 0)); + } + } + + #[test] + fn decodes_the_console_only_instructions() { + assert_eq!(decode(&[0x0F, 0x01, 0xFC]), Some((ConsoleOnly::Clzero, 3))); + // clzero loop against r10 (4C 39 D0 = cmp rax, r10) + assert_eq!( + decode(&[0x0F, 0x01, 0xFC, 0x48, 0x83, 0xC0, 0x40, 0x4C, 0x39, 0xD0, 0x72, 0xF4]), + Some((ConsoleOnly::ClzeroLoop { end_reg: 10 }, 12)) + ); + // clzero loop against rdx (48 39 D0 = cmp rax, rdx) + assert_eq!( + decode(&[0x0F, 0x01, 0xFC, 0x48, 0x83, 0xC0, 0x40, 0x48, 0x39, 0xD0, 0x72, 0xF4]), + Some((ConsoleOnly::ClzeroLoop { end_reg: 2 }, 12)) + ); + // the same loop after an address-size prefix: that one CLZERO alone + assert_eq!(decode(&[0x67, 0x0F, 0x01, 0xFC, 0x48, 0x83, 0xC0, 0x40, 0x48, 0x39, 0xD0, 0x72, 0xF4]), Some((ConsoleOnly::Clzero, 4))); + // the title's other loop, as at its +0x4e8ab4c: mov rax, r10; add r10, 0x40; clzero; + // cmp r10, r11; jb -15 (and against r9/r10, r8/r9, rdx/r8) + assert_eq!(decode(&[0x0F, 0x01, 0xFC, 0x4D, 0x39, 0xDA, 0x72, 0xF1]), Some((ConsoleOnly::ClzeroStep { ptr_reg: 10, end_reg: 11 }, 3))); + assert_eq!(decode(&[0x0F, 0x01, 0xFC, 0x4D, 0x39, 0xD1, 0x72, 0xF1]), Some((ConsoleOnly::ClzeroStep { ptr_reg: 9, end_reg: 10 }, 3))); + assert_eq!(decode(&[0x0F, 0x01, 0xFC, 0x4D, 0x39, 0xC8, 0x72, 0xF1]), Some((ConsoleOnly::ClzeroStep { ptr_reg: 8, end_reg: 9 }, 3))); + assert_eq!(decode(&[0x0F, 0x01, 0xFC, 0x4C, 0x39, 0xC2, 0x72, 0xF1]), Some((ConsoleOnly::ClzeroStep { ptr_reg: 2, end_reg: 8 }, 3))); + assert!(loop15_head(&[0x4C, 0x89, 0xD0, 0x49, 0x83, 0xC2, 0x40], 10)); + assert!(loop15_head(&[0x4C, 0x89, 0xC8, 0x49, 0x83, 0xC1, 0x40], 9)); + assert!(loop15_head(&[0x4C, 0x89, 0xC0, 0x49, 0x83, 0xC0, 0x40], 8)); + assert!(loop15_head(&[0x48, 0x89, 0xD0, 0x48, 0x83, 0xC2, 0x40], 2)); + assert!(!loop15_head(&[0x4C, 0x89, 0xD0, 0x49, 0x83, 0xC2, 0x40], 9), "another register"); + assert!(!loop15_head(&[0x4C, 0x89, 0xD0, 0x49, 0x83, 0xC2, 0x80], 10), "another step"); + // not that loop: another jump back, a memory operand, a 32-bit compare + assert_eq!(decode(&[0x0F, 0x01, 0xFC, 0x4D, 0x39, 0xDA, 0x72, 0xF4]), Some((ConsoleOnly::Clzero, 3))); + assert_eq!(decode(&[0x0F, 0x01, 0xFC, 0x4D, 0x39, 0x1A, 0x72, 0xF1]), Some((ConsoleOnly::Clzero, 3))); + assert_eq!(decode(&[0x0F, 0x01, 0xFC, 0x45, 0x39, 0xDA, 0x72, 0xF1]), Some((ConsoleOnly::Clzero, 3))); + assert_eq!(decode(&[0x0F, 0x01, 0xFD]), Some((ConsoleOnly::Rdpru, 3))); + assert_eq!(decode(&[0x0F, 0x01, 0xFA]), Some((ConsoleOnly::Monitorx, 3))); + assert_eq!(decode(&[0x0F, 0x01, 0xFB]), Some((ConsoleOnly::Mwaitx, 3))); + assert_eq!(decode(&[0x0F, 0x0B]), Some((ConsoleOnly::Ud2, 2))); + // clwb [rax]; clwb [rcx+0x40]; clwb [rsp+8]; clwb [rip+disp32]; clwb [r8] + assert_eq!(decode(&[0x66, 0x0F, 0xAE, 0x30]), Some((ConsoleOnly::Clwb, 4))); + assert_eq!(decode(&[0x66, 0x0F, 0xAE, 0x71, 0x40]), Some((ConsoleOnly::Clwb, 5))); + assert_eq!(decode(&[0x66, 0x0F, 0xAE, 0x74, 0x24, 0x08]), Some((ConsoleOnly::Clwb, 6))); + assert_eq!(decode(&[0x66, 0x0F, 0xAE, 0x35, 1, 2, 3, 4]), Some((ConsoleOnly::Clwb, 8))); + assert_eq!(decode(&[0x66, 0x41, 0x0F, 0xAE, 0x30]), Some((ConsoleOnly::Clwb, 5))); + // rdpid rax; rdpid r9 + assert_eq!(decode(&[0xF3, 0x0F, 0xC7, 0xF8]), Some((ConsoleOnly::Rdpid(0), 4))); + assert_eq!(decode(&[0xF3, 0x41, 0x0F, 0xC7, 0xF9]), Some((ConsoleOnly::Rdpid(9), 5))); + // not console-only: clflushopt (/7), xsaveopt (no 66), a plain mov, truncated bytes + // SSE4a, as a retail game has it (#216: insertq xmm0, xmm1 with length / index bytes) + assert_eq!(decode(&[0xF2, 0x0F, 0x78, 0xC1, 0x08, 0x10]), Some((ConsoleOnly::Insertq { dst: 0, src: 1, reg: false, len: 8, idx: 16 }, 6))); + assert_eq!(decode(&[0xF2, 0x45, 0x0F, 0x79, 0xC1]), Some((ConsoleOnly::Insertq { dst: 8, src: 9, reg: true, len: 0, idx: 0 }, 5))); + assert_eq!(decode(&[0x66, 0x0F, 0x78, 0xC2, 0x04, 0x08]), Some((ConsoleOnly::Extrq { dst: 2, src: None, len: 4, idx: 8 }, 6))); + assert_eq!(decode(&[0x66, 0x0F, 0x79, 0xCA]), Some((ConsoleOnly::Extrq { dst: 1, src: Some(2), len: 0, idx: 0 }, 4))); + assert_eq!(decode(&[0xF2, 0x0F, 0x78, 0xC1, 0x08]), None, "an immediate missing"); + assert_eq!(decode(&[0x0F, 0x78, 0xC1, 0x08, 0x10]), None, "VMREAD without a prefix is not SSE4a"); + // prefixes as a Zen 5 runs them (Kalmarv on #209): the last of F2 / F3 decides, 66 next + // to them does not; 0x67 and a REX before a legacy prefix are ignored + let insertq = Some((ConsoleOnly::Insertq { dst: 0, src: 1, reg: false, len: 16, idx: 16 }, 7)); + for code in [[0x66, 0xF2, 0x0F, 0x78, 0xC1, 0x10, 0x10], [0xF2, 0x66, 0x0F, 0x78, 0xC1, 0x10, 0x10], [0xF3, 0xF2, 0x0F, 0x78, 0xC1, 0x10, 0x10], [0x67, 0xF2, 0x0F, 0x78, 0xC1, 0x10, 0x10], [0x41, 0xF2, 0x0F, 0x78, 0xC1, 0x10, 0x10]] { + assert_eq!(decode(&code), insertq, "{code:02x?}"); + } + for code in [[0xF2, 0xF3, 0x0F, 0x78, 0xC1, 0x10, 0x10], [0xF3, 0x66, 0x0F, 0x78, 0xC1, 0x10, 0x10], [0x66, 0xF3, 0x0F, 0x78, 0xC0, 0x10, 0x10]] { + assert_eq!(decode(&code), None, "#UD on the CPU: {code:02x?}"); + } + assert_eq!(decode(&[0x67, 0x0F, 0x01, 0xFC]), Some((ConsoleOnly::Clzero, 4))); + assert_eq!(decode(&[0x66, 0x0F, 0xAE, 0x38]), None); + assert_eq!(decode(&[0x0F, 0xAE, 0x30]), None); + assert_eq!(decode(&[0x48, 0x8B, 0x01]), None); + assert_eq!(decode(&[0x66, 0x0F, 0xAE, 0x74, 0x24]), None); + assert_eq!(decode(&[0x0F]), None); + } +} diff --git a/crates/leonida-loader/src/crash.rs b/crates/leonida-loader/src/crash.rs new file mode 100644 index 000000000..800357656 --- /dev/null +++ b/crates/leonida-loader/src/crash.rs @@ -0,0 +1,1000 @@ +//! Names the faulting code when title code crashes. +//! +//! A vectored handler sees every exception first, so it only prints the +//! kinds that end a process (access violations and the like, and +//! breakpoints: titles assert with `int3`, fatal without a debugger) as +//! first-chance, since a handler may still take them (ntdll's loader does +//! with its own probes). What nobody handles, of any kind (an uncaught C++ +//! exception too), is reported from the unhandled-exception filter +//! (`report_unhandled`, which the runtime calls ahead of the title's own) +//! and appended to the crash log, with the title's last debug output, which +//! often states the reason. Panics of ours go to the crash log too. + +use std::ptr::null_mut; +use windows_sys::Win32::Foundation::{ + EXCEPTION_ACCESS_VIOLATION, EXCEPTION_BREAKPOINT, EXCEPTION_ILLEGAL_INSTRUCTION, + EXCEPTION_INT_DIVIDE_BY_ZERO, EXCEPTION_PRIV_INSTRUCTION, EXCEPTION_STACK_OVERFLOW, HMODULE, +}; + +use windows_sys::Win32::System::Diagnostics::Debug::{ + AddVectoredExceptionHandler, CONTEXT, EXCEPTION_POINTERS, M128A, RtlLookupFunctionEntry, + RtlVirtualUnwind, SetUnhandledExceptionFilter, UNW_FLAG_NHANDLER, +}; +use windows_sys::Win32::System::LibraryLoader::{ + GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS, GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT, + GetModuleFileNameW, GetModuleHandleExW, +}; +use windows_sys::Win32::System::Threading::GetCurrentThreadStackLimits; + +const EXCEPTION_CONTINUE_SEARCH: i32 = 0; +/// Frames listed per report. +pub(crate) const MAX_FRAMES: usize = 40; + +/// Memory saved to files when a crash is reported: (address, length, file). +#[cfg(feature = "diagnostics")] +static SAVE: std::sync::OnceLock> = + std::sync::OnceLock::new(); + +/// Debugging aid: on a reported crash, also write each `[address, address +/// + len)` (readable title memory, e.g. an engine table) to its file. +#[cfg(feature = "diagnostics")] +pub fn save_on_crash(ranges: Vec<(usize, usize, std::path::PathBuf)>) { + let _ = SAVE.set(ranges); +} + +/// The file crash reports are appended to, besides being printed. +static LOG: std::sync::OnceLock = std::sync::OnceLock::new(); + +/// Also appends every unhandled-exception report and panic to `file`, so a +/// crash can be read after the console is gone. +pub fn log_crashes_to(file: std::path::PathBuf) { + if LOG.set(file).is_ok() { + let print = std::panic::take_hook(); + std::panic::set_hook(Box::new(move |info| { + print(info); + append_to_log(&format!( + "Leonida Legacy: panic on thread {:?}: {info}\n{}", + std::thread::current().name().unwrap_or("?"), + title_output() + )); + })); + } +} + +/// Appends a failure that is not an exception (the host GPU's) to the crash +/// log, with the title's last debug output, and prints it. +pub fn log_crash(text: &str) { + let text = format!("{text} +{}", title_output()); + eprint!("{text}"); + append_to_log(&text); +} + +fn append_to_log(text: &str) { + use std::io::Write; + let Some(file) = LOG.get() else { return }; + let now = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map_or(0, |d| d.as_secs()); + let opened = std::fs::OpenOptions::new().create(true).append(true).open(file); + if let Ok(mut f) = opened { + let _ = write!(f, "unix time {now}, process {}\n{text}\n", std::process::id()); + } +} + +/// The title's last lines of debug output, kept for crash reports. +static SAID: std::sync::Mutex> = + std::sync::Mutex::new(std::collections::VecDeque::new()); +const SAID_LINES: usize = 8; + +/// Keeps a line of the title's debug output for the next crash report. +pub fn note_title_output(line: &str) { + if line.is_empty() { + return; + } + let mut said = SAID.lock().unwrap_or_else(|e| e.into_inner()); + if said.len() == SAID_LINES { + said.pop_front(); + } + said.push_back(line.to_owned()); +} + +/// The kept lines, one per report line; nothing if another thread holds +/// them (it may be the one that faulted). +fn title_output() -> String { + let Ok(said) = SAID.try_lock() else { + return String::new(); + }; + said.iter().map(|l| format!(" title said: {l}\n")).collect() +} + +/// Installs the handlers; call once before running title code. +pub fn report_crashes() { + unsafe extern "system" fn filter(info: *const EXCEPTION_POINTERS) -> i32 { + // SAFETY: the system passes the exception being dispatched. + unsafe { report_unhandled(info) }; + EXCEPTION_CONTINUE_SEARCH + } + // SAFETY: registers handlers that only read the exception they are + // given; the title's own filter, once it sets one, takes the place of + // ours and calls `report_unhandled` first. + unsafe { + AddVectoredExceptionHandler(0, Some(handler)); + SetUnhandledExceptionFilter(Some(filter)); + } +} + +/// What the vectored handler reports as it happens. +const FATAL: [i32; 6] = [ + EXCEPTION_ACCESS_VIOLATION, + EXCEPTION_ILLEGAL_INSTRUCTION, + EXCEPTION_PRIV_INSTRUCTION, + EXCEPTION_INT_DIVIDE_BY_ZERO, + EXCEPTION_STACK_OVERFLOW, + EXCEPTION_BREAKPOINT, +]; + +/// Console CPUs are Zen 2: titles use AMD-only instructions Intel CPUs +/// lack. Does their job instead: `clzero` (`0f 01 fc`) zeroes the 64-byte +/// line at `rax`; `monitorx`/`mwaitx` (`0f 01 fa`/`fb`) are wait hints, so +/// a spin loop around them works with mwaitx as a yield. +unsafe fn emulate_amd_only(info: *mut EXCEPTION_POINTERS) -> bool { + // SAFETY: the system passes valid exception pointers; the faulting + // instruction's bytes are readable, as the CPU just fetched them. + unsafe { + let record = &*(*info).ExceptionRecord; + let context = &mut *(*info).ContextRecord; + if record.ExceptionCode != EXCEPTION_ILLEGAL_INSTRUCTION { + return false; + } + let code = context.Rip as *const u8; + match code.cast::<[u8; 3]>().read_unaligned() { + [0x0f, 0x01, 0xfc] => ((context.Rax & !63) as *mut u8).write_bytes(0, 64), + [0x0f, 0x01, 0xfa] => {} + [0x0f, 0x01, 0xfb] => std::thread::yield_now(), + _ => { + // Only bytes inside the faulting instruction's page are read: the next page may + // not be mapped. + let room = 0x1000 - (context.Rip as usize & 0xfff); + let mut bytes = [0u8; 32]; + let n = room.min(bytes.len()); + std::ptr::copy_nonoverlapping(code, bytes.as_mut_ptr(), n); + if let Some(pass) = clwb_loop(&bytes[..n]) { + // A whole write-back loop in one exception (see `clwb_loop`). + let limit = *gpr(context, pass.limit); + let base = gpr(context, pass.base); + *base = if *base <= limit { + base.wrapping_add(((limit - *base) / 64 + 1) * 64) + } else { + base.wrapping_add(64) + }; + let flags = cmp_flags(*base, limit); + context.EFlags = context.EFlags & !CMP_FLAGS | flags; + context.Rip += pass.len as u64; + return true; + } + if n >= 15 + && let Some(len) = clwb_len(bytes[..15].try_into().unwrap_or([0; 15])) + { + // A write-back hint: the PC's memory is coherent, so it has nothing to do. + context.Rip += len as u64; + return true; + } + let Some(len) = sse4a(code, &mut context.Anonymous.FltSave.XmmRegisters) else { + return false; + }; + context.Rip += len as u64; + return true; + } + } + context.Rip += 3; + } + true +} + +/// `clwb m8` (`66 [rex] 0f ae /6`, a memory operand), which Intel CPUs before +/// Ice Lake lack: its length, or `None` for any other instruction. +fn clwb_len(code: [u8; 15]) -> Option { + let at = if code[1] & 0xf0 == 0x40 { 2 } else { 1 }; + if code[0] != 0x66 || code[at] != 0x0f || code[at + 1] != 0xae { + return None; + } + let modrm = code[at + 2]; + let (mode, rm) = (modrm >> 6, modrm & 7); + if mode == 3 || (modrm >> 3) & 7 != 6 { + return None; + } + let mut len = at + 3; + let mut base = rm; + if rm == 4 { + base = code[len] & 7; + len += 1; + } + len += match mode { + 0 if rm == 5 || (rm == 4 && base == 5) => 4, + 1 => 1, + 2 => 4, + _ => 0, + }; + Some(len) +} + +/// A `clwb` write-back loop as the title's compilers build it, one cache line a +/// pass (`base` and `limit` any registers): +/// +/// ```text +/// top: clwb [base] +/// add base, 0x40 +/// cmp base, limit +/// jbe top +/// ``` +/// +/// An exception costs about a microsecond and the title writes back whole +/// buffers this way while it loads, so the loop is done in one: `clwb` has +/// nothing to do on the PC, `base` ends past `limit` as the last pass leaves it. +struct ClwbLoop { + base: u8, + limit: u8, + /// Bytes from `clwb` to the instruction after `jbe`. + len: usize, +} + +fn clwb_loop(code: &[u8]) -> Option { + // clwb [base]: 66 [40|41] 0f ae, ModRM mod 00, reg 6, no SIB or displacement. + let (rex, at) = match code.get(1)? { + 0x40 | 0x41 => (code[1], 2), + _ => (0, 1), + }; + if *code.first()? != 0x66 || code.get(at..at + 2)? != [0x0f, 0xae] { + return None; + } + let modrm = *code.get(at + 2)?; + let rm = modrm & 7; + if modrm >> 6 != 0 || (modrm >> 3) & 7 != 6 || rm == 4 || rm == 5 { + return None; + } + let base = rm | (rex & 1) << 3; + // add base, 0x40: REX.W(+B) 83 /0 ib. + let add = at + 3; + if *code.get(add..add + 4)? != [0x48 | base >> 3, 0x83, 0xc0 | (base & 7), 0x40] { + return None; + } + // cmp base, limit: REX.W 39 /r with base in r/m. + let cmp = add + 4; + let &[cmp_rex @ 0x48..=0x4f, 0x39, cmp_modrm] = code.get(cmp..cmp + 3)? else { + return None; + }; + if cmp_modrm >> 6 != 3 || (cmp_modrm & 7 | (cmp_rex & 1) << 3) != base { + return None; + } + let limit = (cmp_modrm >> 3) & 7 | (cmp_rex & 4) << 1; + // jbe top. + let jump = cmp + 3; + let len = jump + 2; + if *code.get(jump)? != 0x76 || i64::from(*code.get(jump + 1)? as i8) != -(len as i64) { + return None; + } + (limit != base).then_some(ClwbLoop { base, limit, len }) +} + +/// The general register numbered `n` as instructions encode it. +fn gpr(context: &mut CONTEXT, n: u8) -> &mut u64 { + match n & 15 { + 0 => &mut context.Rax, + 1 => &mut context.Rcx, + 2 => &mut context.Rdx, + 3 => &mut context.Rbx, + 4 => &mut context.Rsp, + 5 => &mut context.Rbp, + 6 => &mut context.Rsi, + 7 => &mut context.Rdi, + 8 => &mut context.R8, + 9 => &mut context.R9, + 10 => &mut context.R10, + 11 => &mut context.R11, + 12 => &mut context.R12, + 13 => &mut context.R13, + 14 => &mut context.R14, + _ => &mut context.R15, + } +} + +/// The status flags `cmp a, b` leaves (CF, PF, AF, ZF, SF, OF) as `EFLAGS` bits. +fn cmp_flags(a: u64, b: u64) -> u32 { + let r = a.wrapping_sub(b); + u32::from(a < b) + | u32::from((r as u8).count_ones().is_multiple_of(2)) << 2 + | (((a ^ b ^ r) >> 4) as u32 & 1) << 4 + | u32::from(r == 0) << 6 + | ((r >> 63) as u32) << 7 + | ((((a ^ b) & (a ^ r)) >> 63) as u32) << 11 +} +const CMP_FLAGS: u32 = 0x8d5; + +/// SSE4a's `extrq`/`insertq` (register forms, the only ones there are) on +/// the saved XMM registers; returns the instruction's length. +unsafe fn sse4a(code: *const u8, xmm: &mut [M128A; 16]) -> Option { + // SAFETY: the caller's code bytes are readable up to the instruction's end. + let b = |i: usize| unsafe { code.add(i).read() }; + let prefix = b(0); + let (rex, at) = if b(1) & 0xf0 == 0x40 { + (b(1), 2) + } else { + (0, 1) + }; + if !matches!(prefix, 0x66 | 0xf2) || b(at) != 0x0f || !matches!(b(at + 1), 0x78 | 0x79) { + return None; + } + let modrm = b(at + 2); + if modrm >> 6 != 3 { + return None; + } + let dst = usize::from((modrm >> 3) & 7 | (rex & 4) << 1); + let src = usize::from(modrm & 7 | (rex & 1) << 3); + let immediate = b(at + 1) == 0x78; + let (fields, len) = if immediate { + ((b(at + 3), b(at + 4)), at + 5) + } else { + // extrq reads its fields from src's low half, insertq from its high. + let f = if prefix == 0x66 { xmm[src].Low } else { xmm[src].High as u64 }; + ((f as u8, (f >> 8) as u8), at + 3) + }; + let (n, at_bit) = (u32::from(fields.0 & 63), u32::from(fields.1 & 63)); + let bits = if n == 0 { 64 } else { n }; + let mask = if bits == 64 { u64::MAX } else { (1u64 << bits) - 1 }; + if prefix == 0x66 { + // extrq: register form takes its fields from src, works on dst. + if immediate && (modrm >> 3) & 7 != 0 { + return None; + } + let target = if immediate { src } else { dst }; + xmm[target].Low = (xmm[target].Low >> at_bit) & mask; + } else { + let value = (xmm[src].Low & mask) << at_bit; + xmm[dst].Low = xmm[dst].Low & !(mask << at_bit) | value; + } + Some(len) +} + +unsafe extern "system" fn handler(info: *mut EXCEPTION_POINTERS) -> i32 { + // an instruction of the console's CPU this one lacks: emulated, the title goes on + // SAFETY: the system passes valid exception pointers. + if unsafe { (*(*info).ExceptionRecord).ExceptionCode } == EXCEPTION_ILLEGAL_INSTRUCTION { + // SAFETY: the faulting thread's context, for the exception being dispatched. + let r = unsafe { crate::console_insn::emulate(&mut *(*info).ContextRecord) }; + if r != 0 { + return r; + } + } + // SAFETY: the system passes valid exception pointers. + if unsafe { emulate_amd_only(info) } { + return -1; // EXCEPTION_CONTINUE_EXECUTION + } + // SAFETY: as above. + if FATAL.contains(&unsafe { (*(*info).ExceptionRecord).ExceptionCode }) { + // SAFETY: as above. + unsafe { report("first-chance exception", info, false) }; + } + EXCEPTION_CONTINUE_SEARCH +} + +/// For an unhandled-exception filter: reports the exception that is about +/// to end the process, and appends it to the crash log. +/// +/// # Safety +/// `info` comes from the system, for an exception being dispatched. +pub unsafe fn report_unhandled(info: *const EXCEPTION_POINTERS) { + // SAFETY: forwarded from the caller. + unsafe { report("unhandled exception", info, true) }; +} + +/// The bytes at `at` as hex, as many as the longest x86 instruction (15), +/// but none past the end of `at`'s page: the next page may not be mapped. +/// For an instruction the CPU refused, they name it (`0f 01 fd` is +/// `rdpru`), which the address alone does not. +/// +/// # Safety +/// `at`'s page is readable. +unsafe fn instruction_bytes(at: usize) -> String { + let n = (0x1000 - (at & 0xfff)).min(15); + // SAFETY: `n` bytes from `at` stay inside its page, which the caller + // says is readable. + let bytes = unsafe { std::slice::from_raw_parts(at as *const u8, n) }; + let hex: Vec<_> = bytes.iter().map(|b| format!("{b:02x}")).collect(); + hex.join(" ") +} + +/// MSVC's code for a C++ `throw`, and its magic first parameter. +const CPP_EXCEPTION: i32 = 0xE06D_7363_u32 as i32; +const CPP_MAGIC: usize = 0x1993_0520; + +/// What a C++ throw threw: the decorated name of its type, then its value +/// where that names the cause (an integer, e.g. an HRESULT; a standard +/// exception's message). +/// +/// # Safety +/// `p` are the parameters of a live MSVC throw (`p[0]` the magic). +unsafe fn thrown(p: &[usize]) -> String { + // SAFETY: the throw's ThrowInfo, its RVAs relative to `p[3]`: catchable + // type array at +12 (count, then type RVAs), each type's descriptor at + // +4, whose decorated name starts at +16; the object is at `p[1]`. + unsafe { + let rva = |at: usize| (at as *const u32).read_unaligned() as usize; + let types = p[3] + rva(p[2] + 12); + let name = |i: usize| { + let descriptor = p[3] + rva(p[3] + rva(types + 4 + 4 * i) + 4); + std::ffi::CStr::from_ptr((descriptor + 16) as *const std::ffi::c_char) + .to_string_lossy() + }; + let first = name(0); + let value = match &*first { + // int, unsigned, long (HRESULT), unsigned long + ".H" | ".I" | ".J" | ".K" if p[1] != 0 => { + format!(" = {:#010x}", (p[1] as *const u32).read_unaligned()) + } + // std::exception keeps its message after the table pointer. + _ if (0..rva(types)).any(|i| name(i) == ".?AVexception@std@@") => { + let message = (p[1] as *const *const std::ffi::c_char).add(1).read(); + if message.is_null() { + String::new() + } else { + format!(": {}", std::ffi::CStr::from_ptr(message).to_string_lossy()) + } + } + _ => String::new(), + }; + format!("{first}{value}") + } +} + +/// # Safety +/// See [`report_unhandled`]. +unsafe fn report(what: &str, info: *const EXCEPTION_POINTERS, to_file: bool) { + // SAFETY: the system passes valid exception pointers. + let (record, context) = unsafe { (&*(*info).ExceptionRecord, &*(*info).ContextRecord) }; + let code = record.ExceptionCode; + let at = record.ExceptionAddress as usize; + let p = record.ExceptionInformation; + let detail = if code == EXCEPTION_ACCESS_VIOLATION { + let kind = match p[0] { + 0 => "read", + 1 => "write", + _ => "execute", + }; + format!(" ({kind} {:#x}: {})", p[1], memory_at(p[1])) + } else if code == CPP_EXCEPTION && record.NumberParameters >= 4 && p[0] == CPP_MAGIC { + // SAFETY: a live MSVC throw. + format!(" (C++ {} thrown)", unsafe { thrown(&p) }) + } else if code == EXCEPTION_ILLEGAL_INSTRUCTION || code == EXCEPTION_PRIV_INSTRUCTION { + // SAFETY: the CPU refused the instruction at `at`, so it fetched it. + format!(" (code {})", unsafe { instruction_bytes(at) }) + } else { + String::new() + }; + // Printed line by line (a fault while unwinding must not lose the + // lines before it), and kept for the file. + let mut text = String::new(); + let mut line = |l: String| { + eprintln!("{l}"); + text.push_str(&l); + text.push('\n'); + }; + line(format!( + "Leonida Legacy: {what} {:#010x} at {}{detail}", + code as u32, + locate(at) + )); + line(format!( + " rax {:#x} rbx {:#x} rcx {:#x} rdx {:#x} rsi {:#x} rdi {:#x} rsp {:#x} rbp {:#x}", + context.Rax, + context.Rbx, + context.Rcx, + context.Rdx, + context.Rsi, + context.Rdi, + context.Rsp, + context.Rbp + )); + line(format!( + " r8 {:#x} r9 {:#x} r10 {:#x} r11 {:#x} r12 {:#x} r13 {:#x} r14 {:#x} r15 {:#x}", + context.R8, + context.R9, + context.R10, + context.R11, + context.R12, + context.R13, + context.R14, + context.R15 + )); + for (i, pc) in unwind(*context).into_iter().enumerate() { + line(format!(" #{i:<2} {}", locate(pc as usize))); + } + if to_file { + let said = title_output(); + eprint!("{said}"); + text.push_str(&said); + append_to_log(&text); + } + #[cfg(feature = "diagnostics")] + for (address, len, file) in SAVE.get().into_iter().flatten() { + // SAFETY: the caller of `save_on_crash` named readable memory. + let bytes = unsafe { std::slice::from_raw_parts(*address as *const u8, *len) }; + let saved = std::fs::write(file, bytes); + eprintln!( + " saved {address:#x}+{len:#x} to {} ({saved:?})", + file.display() + ); + } +} + +/// Return addresses of the faulting thread's frames, from the faulting +/// instruction up, by the unwind data of each image (the Windows loader +/// registered it for title images too). Code without unwind data (our +/// thunks, leaf functions) is taken to have its return address at `rsp`. +fn unwind(context: CONTEXT) -> Vec { + let (mut low, mut high) = (0, 0); + // SAFETY: writes the current thread's stack bounds. + unsafe { GetCurrentThreadStackLimits(&mut low, &mut high) }; + let mut frames = Vec::with_capacity(MAX_FRAMES); + unwind_into(context, low, high, &mut frames); + frames +} + +/// A `CONTEXT` at the 16-byte alignment the unwind and capture functions need. +#[repr(C, align(16))] +pub(crate) struct Aligned16(pub(crate) CONTEXT); + +/// [`unwind`] for any thread of the process, its stack being `low..high`; +/// pushes no more than `MAX_FRAMES`, so it does not allocate when `frames` +/// has that capacity (another thread may be suspended holding the heap). +pub(crate) fn unwind_into(context: CONTEXT, low: usize, high: usize, frames: &mut Vec) { + // `RtlVirtualUnwind` writes the context with 16-byte aligned stores, and + // windows-sys declares `CONTEXT` without that alignment: a by-value copy on + // the stack can land 8 bytes off and fault (seen in a debug build). + let mut aligned = Aligned16(context); + let context = &mut aligned.0; + frames.push(context.Rip); + while frames.len() < MAX_FRAMES { + // Stop where reading the stack would fault inside this handler. + let rsp = context.Rsp as usize; + if rsp < low || rsp + 8 > high { + break; + } + let mut image = 0; + // SAFETY: looks up the function table entry covering `Rip`, if any. + let entry = unsafe { RtlLookupFunctionEntry(context.Rip, &mut image, null_mut()) }; + if entry.is_null() { + // SAFETY: `rsp` is inside this thread's stack. + context.Rip = unsafe { (rsp as *const u64).read() }; + context.Rsp += 8; + } else { + let (mut data, mut frame) = (null_mut(), 0); + // SAFETY: `entry` belongs to `image`; the context is our copy. + unsafe { + RtlVirtualUnwind( + UNW_FLAG_NHANDLER, + image, + context.Rip, + entry, + context, + &mut data, + &mut frame, + null_mut(), + ) + }; + } + if context.Rip == 0 { + break; + } + frames.push(context.Rip); + } +} + +/// `module+rva`, or the bare address. +pub fn locate(address: usize) -> String { + module_of(address).unwrap_or_else(|| format!("{address:#x}")) +} + +fn module_of(address: usize) -> Option { + let mut module: HMODULE = std::ptr::null_mut(); + // SAFETY: looks up the module containing `address`; no reference taken. + let found = unsafe { + GetModuleHandleExW( + GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT, + address as *const u16, + &mut module, + ) + }; + if found == 0 { + return None; + } + let mut path = [0u16; 260]; + // SAFETY: `module` is a loaded module; the buffer length is passed. + let len = unsafe { GetModuleFileNameW(module, path.as_mut_ptr(), path.len() as u32) }; + let path = String::from_utf16_lossy(&path[..len as usize]); + let name = path.rsplit('\\').next().unwrap_or(&path); + Some(format!("{name}+{:#x}", address - module as usize)) +} + +/// What is at `address`, for an access violation there: nothing, memory +/// reserved but never committed, a guard page, or the protection the access +/// broke (with the module, for an image's pages). Each points at a different +/// cause: a wild pointer, an allocation whose commit failed, a stack +/// overrun, a write to code or constants. +fn memory_at(address: usize) -> String { + use windows_sys::Win32::System::Memory::{ + MEM_FREE, MEM_IMAGE, MEM_RESERVE, MEMORY_BASIC_INFORMATION, PAGE_EXECUTE, + PAGE_EXECUTE_READ, PAGE_EXECUTE_READWRITE, PAGE_EXECUTE_WRITECOPY, PAGE_GUARD, + PAGE_NOACCESS, PAGE_READONLY, PAGE_READWRITE, PAGE_WRITECOPY, VirtualQuery, + }; + // SAFETY: a zeroed MEMORY_BASIC_INFORMATION is valid. + let mut info: MEMORY_BASIC_INFORMATION = unsafe { std::mem::zeroed() }; + // SAFETY: reads the address space's bookkeeping, not `address` itself. + let n = unsafe { VirtualQuery(address as *const _, &mut info, size_of_val(&info)) }; + if n == 0 { + // Above the process's address space: Windows reports a + // non-canonical address as all ones. + return "outside the address space".into(); + } + let protect = match info.State { + MEM_FREE => return "nothing mapped there".into(), + MEM_RESERVE => return "reserved, never committed".into(), + _ if info.Protect & PAGE_GUARD != 0 => return "a guard page".into(), + _ => match info.Protect & 0xff { + PAGE_NOACCESS => "no access".into(), + PAGE_READONLY => "read-only".into(), + PAGE_READWRITE => "read-write".into(), + PAGE_WRITECOPY => "copy-on-write".into(), + PAGE_EXECUTE => "execute-only".into(), + PAGE_EXECUTE_READ => "read-execute".into(), + PAGE_EXECUTE_READWRITE => "read-write-execute".into(), + PAGE_EXECUTE_WRITECOPY => "copy-on-write, executable".into(), + _ => format!("protection {:#x}", info.Protect), + }, + }; + match module_of(address) { + Some(module) if info.Type == MEM_IMAGE => format!("{protect}, in {module}"), + _ => protect, + } +} + +#[cfg(test)] +mod tests { + use super::*; + use windows_sys::Win32::System::Diagnostics::Debug::{ + EXCEPTION_RECORD, RtlCaptureContext, RtlCaptureStackBackTrace, + }; + + #[test] + #[inline(never)] + fn unwinds_like_the_system_walk() { + // SAFETY: zeroed CONTEXT is valid; both calls write our buffers. + let (frames, walked) = unsafe { + // `RtlCaptureContext` wants it 16-byte aligned too. + let mut context = Aligned16(std::mem::zeroed()); + RtlCaptureContext(&mut context.0); + let mut walked = [null_mut(); 8]; + let n = RtlCaptureStackBackTrace(0, 8, walked.as_mut_ptr(), null_mut()); + (unwind(context.0), walked[..usize::from(n)].to_vec()) + }; + // Frame 0 differs (two call sites in this function); callers agree. + assert!(walked.len() >= 4, "{walked:?}"); + let ours: Vec<_> = frames[1..walked.len()] + .iter() + .map(|&f| f as usize) + .collect(); + let system: Vec<_> = walked[1..].iter().map(|&f| f as usize).collect(); + assert_eq!(ours, system); + } + + #[test] + fn memory_at_names_what_an_access_hit() { + use windows_sys::Win32::System::Memory::{ + MEM_COMMIT, MEM_RELEASE, MEM_RESERVE, PAGE_GUARD, PAGE_NOACCESS, PAGE_READONLY, + PAGE_READWRITE, VirtualAlloc, VirtualFree, + }; + // SAFETY: reserves four pages of ours and commits three of them; + // nothing reads or writes them. + let base = unsafe { + let base = VirtualAlloc(std::ptr::null(), 0x4000, MEM_RESERVE, PAGE_NOACCESS); + assert!(!base.is_null()); + let page = |i: usize, protect| { + let at = base.cast::().add(i * 0x1000).cast(); + assert!(!VirtualAlloc(at, 0x1000, MEM_COMMIT, protect).is_null()); + }; + page(1, PAGE_READONLY); + page(2, PAGE_READWRITE | PAGE_GUARD); + page(3, PAGE_NOACCESS); + base as usize + }; + assert_eq!(memory_at(base + 8), "reserved, never committed"); + assert_eq!(memory_at(base + 0x1008), "read-only"); + assert_eq!(memory_at(base + 0x2008), "a guard page"); + assert_eq!(memory_at(base + 0x3008), "no access"); + // SAFETY: releases the reservation made above. + unsafe { VirtualFree(base as *mut _, 0, MEM_RELEASE) }; + assert_eq!(memory_at(base + 8), "nothing mapped there"); + assert_eq!(memory_at(0), "nothing mapped there"); + assert_eq!(memory_at(usize::MAX), "outside the address space"); + // This test's own code: an image page, named by its module. + let code = memory_at(memory_at_names_what_an_access_hit as *const () as usize); + let named = code.starts_with("read-execute, in leonida_loader-"); + assert!(named, "{code}"); + } + + /// On an Intel CPU, the real instructions go through the vectored + /// handler. On an AMD CPU they run natively, and the tests below test + /// the emulation. + #[test] + fn clwb_loops() { + // clwb [rcx]; add rcx, 0x40; cmp rcx, rax; jbe top + let a = clwb_loop(&[ + 0x66, 0x0f, 0xae, 0x31, 0x48, 0x83, 0xc1, 0x40, 0x48, 0x39, 0xc1, 0x76, 0xf3, + ]) + .expect("rcx loop"); + assert_eq!((a.base, a.limit, a.len), (1, 0, 13)); + // clwb [r9]; add r9, 0x40; cmp r9, rax; jbe top + let b = clwb_loop(&[ + 0x66, 0x41, 0x0f, 0xae, 0x31, 0x49, 0x83, 0xc1, 0x40, 0x49, 0x39, 0xc1, 0x76, 0xf2, + ]) + .expect("r9 loop"); + assert_eq!((b.base, b.limit, b.len), (9, 0, 14)); + // A different stride, a jump elsewhere, or a cut-off loop is not one. + assert!( + clwb_loop(&[ + 0x66, 0x0f, 0xae, 0x31, 0x48, 0x83, 0xc1, 0x20, 0x48, 0x39, 0xc1, 0x76, 0xf3 + ]) + .is_none() + ); + assert!( + clwb_loop(&[ + 0x66, 0x0f, 0xae, 0x31, 0x48, 0x83, 0xc1, 0x40, 0x48, 0x39, 0xc1, 0x76, 0xf0 + ]) + .is_none() + ); + assert!(clwb_loop(&[0x66, 0x0f, 0xae, 0x31, 0x48, 0x83, 0xc1, 0x40]).is_none()); + // The flags the last cmp leaves: base just past limit. + assert_eq!(cmp_flags(0x1040, 0x1000) & 0x41, 0); // CF and ZF clear: the loop ends + assert_eq!(cmp_flags(0x1000, 0x1000) & 0x40, 0x40); + } + + #[test] + fn clwb_lengths() { + let pad = |b: &[u8]| { + let mut c = [0u8; 15]; + c[..b.len()].copy_from_slice(b); + c + }; + assert_eq!(clwb_len(pad(&[0x66, 0x41, 0x0f, 0xae, 0x31])), Some(5)); // clwb [r9] + assert_eq!(clwb_len(pad(&[0x66, 0x0f, 0xae, 0x30])), Some(4)); // clwb [rax] + assert_eq!(clwb_len(pad(&[0x66, 0x0f, 0xae, 0x70, 0x40])), Some(5)); // clwb [rax+0x40] + assert_eq!( + clwb_len(pad(&[0x66, 0x0f, 0xae, 0xb0, 0, 1, 0, 0])), + Some(8) + ); // [rax+disp32] + assert_eq!(clwb_len(pad(&[0x66, 0x0f, 0xae, 0x34, 0x24])), Some(5)); // clwb [rsp] + assert_eq!( + clwb_len(pad(&[0x66, 0x0f, 0xae, 0x35, 0, 0, 0, 0])), + Some(8) + ); // [rip+disp32] + assert_eq!(clwb_len(pad(&[0x66, 0x0f, 0xae, 0x38])), None); // clflushopt, /7 + assert_eq!(clwb_len(pad(&[0x0f, 0xae, 0x30])), None); // xsaveopt, no 66 + assert_eq!(clwb_len(pad(&[0x66, 0x0f, 0xae, 0xf0])), None); // register form + } + + #[test] + fn clzero_zeroes_its_line_on_any_cpu() { + report_crashes(); + #[repr(align(64))] + struct Line([u8; 128]); + let mut line = Line([0xff; 128]); + let at = line.0.as_mut_ptr().wrapping_add(5); // inside the first line + // SAFETY: clzero writes only the 64-byte line holding `at`, ours. + unsafe { std::arch::asm!(".byte 0x0f, 0x01, 0xfc", in("rax") at) }; + assert!(line.0[..64].iter().all(|&b| b == 0)); + assert!(line.0[64..].iter().all(|&b| b == 0xff)); + // insertq xmm0, xmm1, len 16, at 16; then extrq xmm0, len 8, at 20. + let out: u64; + // SAFETY: touches only the named registers. + unsafe { + std::arch::asm!( + "movq xmm0, {a}", "movq xmm1, {b}", + ".byte 0xf2, 0x0f, 0x78, 0xc1, 0x10, 0x10", + "movq {a}, xmm0", + ".byte 0x66, 0x0f, 0x78, 0xc0, 0x08, 0x14", + "movq {b}, xmm0", + a = inout(reg) 0x1111_2222_3333_4444u64 => _, b = inout(reg) 0xabcdu64 => out, + out("xmm0") _, out("xmm1") _) + }; + assert_eq!(out, 0xbc); // 0x1111_2222_abcd_4444 >> 20, 8 bits + // SAFETY: monitorx/mwaitx are wait hints that write no memory. + unsafe { + std::arch::asm!(".byte 0x0f, 0x01, 0xfa", ".byte 0x0f, 0x01, 0xfb", + in("rax") at, in("ecx") 0, in("edx") 0) + }; + } + + fn reg(low: u64, high: u64) -> M128A { + M128A { + Low: low, + High: high as i64, + } + } + + /// Gives `code` to the emulation as if it faulted with `exception` at + /// its first byte, with `rax` and `xmm` as the saved registers. The + /// emulation does not execute `code`, so this works on any CPU. Returns + /// the number of bytes that the emulation skipped, or `None` if it did + /// not emulate the instruction. `xmm` gets the saved registers after. + fn emulate_as(exception: i32, code: &[u8], rax: u64, xmm: &mut [M128A; 16]) -> Option { + // `int3` after the instruction, so that a decoder that reads too + // far sees no valid bytes. + let mut bytes = [0xcc_u8; 16]; + bytes[..code.len()].copy_from_slice(code); + let start = bytes.as_ptr() as u64; + // SAFETY: a zeroed record and context are valid; the emulation + // reads only `bytes` and writes only `context` (and memory at + // `rax` for clzero, which the caller owns). + unsafe { + let mut record: EXCEPTION_RECORD = std::mem::zeroed(); + record.ExceptionCode = exception; + let mut context: CONTEXT = std::mem::zeroed(); + context.Rip = start; + context.Rax = rax; + context.Anonymous.FltSave.XmmRegisters = *xmm; + let mut pointers = EXCEPTION_POINTERS { + ExceptionRecord: &mut record, + ContextRecord: &mut context, + }; + let emulated = emulate_amd_only(&mut pointers); + *xmm = context.Anonymous.FltSave.XmmRegisters; + emulated.then(|| context.Rip - start) + } + } + + fn emulate(code: &[u8], rax: u64, xmm: &mut [M128A; 16]) -> Option { + emulate_as(EXCEPTION_ILLEGAL_INSTRUCTION, code, rax, xmm) + } + + fn low(xmm: &[M128A; 16], i: usize) -> u64 { + xmm[i].Low + } + + #[test] + fn emulated_clzero_zeroes_its_line() { + #[repr(align(64))] + struct Line([u8; 128]); + let mut line = Line([0xff; 128]); + let at = line.0.as_mut_ptr().wrapping_add(5) as u64; // inside the first line + let mut xmm = [reg(0, 0); 16]; + assert_eq!(emulate(&[0x0f, 0x01, 0xfc], at, &mut xmm), Some(3)); + assert!(line.0[..64].iter().all(|&b| b == 0)); + assert!(line.0[64..].iter().all(|&b| b == 0xff)); + } + + #[test] + fn emulated_monitorx_and_mwaitx_are_skipped() { + let mut xmm = [reg(1, 2); 16]; + assert_eq!(emulate(&[0x0f, 0x01, 0xfa], 0, &mut xmm), Some(3)); + assert_eq!(emulate(&[0x0f, 0x01, 0xfb], 0, &mut xmm), Some(3)); + assert!(xmm.iter().all(|r| r.Low == 1 && r.High == 2)); + } + + #[test] + fn emulated_insertq_and_extrq_with_immediates() { + let mut xmm = [reg(0, 0); 16]; + xmm[0] = reg(0x1111_2222_3333_4444, 0x5555); + xmm[1] = reg(0xabcd, 0x6666); + // insertq xmm0, xmm1, length 16, index 16 + let insertq = [0xf2, 0x0f, 0x78, 0xc1, 0x10, 0x10]; + assert_eq!(emulate(&insertq, 0, &mut xmm), Some(6)); + assert_eq!(low(&xmm, 0), 0x1111_2222_abcd_4444); + assert_eq!((low(&xmm, 1), xmm[1].High), (0xabcd, 0x6666)); + // extrq xmm0, length 8, index 20 + let extrq = [0x66, 0x0f, 0x78, 0xc0, 0x08, 0x14]; + assert_eq!(emulate(&extrq, 0, &mut xmm), Some(6)); + assert_eq!(low(&xmm, 0), 0xbc); + } + + #[test] + fn emulated_insertq_and_extrq_with_fields_in_a_register() { + let mut xmm = [reg(0, 0); 16]; + // insertq xmm0, xmm1: length and index in xmm1's high half. + xmm[0] = reg(0x1111_2222_3333_4444, 0); + xmm[1] = reg(0xabcd, 0x10_10); + assert_eq!(emulate(&[0xf2, 0x0f, 0x79, 0xc1], 0, &mut xmm), Some(4)); + assert_eq!(low(&xmm, 0), 0x1111_2222_abcd_4444); + // extrq xmm0, xmm1: length and index in xmm1's low half. + xmm[1] = reg(0x14_08, 0); + assert_eq!(emulate(&[0x66, 0x0f, 0x79, 0xc1], 0, &mut xmm), Some(4)); + assert_eq!(low(&xmm, 0), 0xbc); + } + + #[test] + fn emulated_sse4a_reaches_xmm8_to_xmm15() { + let mut xmm = [reg(0, 0); 16]; + xmm[8] = reg(0x1111_2222_3333_4444, 0); + xmm[9] = reg(0xabcd, 0); + // insertq xmm8, xmm9, length 16, index 16 (REX.R and REX.B) + let insertq = [0xf2, 0x45, 0x0f, 0x78, 0xc1, 0x10, 0x10]; + assert_eq!(emulate(&insertq, 0, &mut xmm), Some(7)); + assert_eq!(low(&xmm, 8), 0x1111_2222_abcd_4444); + assert_eq!((low(&xmm, 0), low(&xmm, 1)), (0, 0)); + // extrq xmm9, length 8, index 4 (REX.B) + let extrq = [0x66, 0x41, 0x0f, 0x78, 0xc1, 0x08, 0x04]; + assert_eq!(emulate(&extrq, 0, &mut xmm), Some(7)); + assert_eq!(low(&xmm, 9), 0xbc); + assert_eq!(low(&xmm, 1), 0); + } + + #[test] + fn emulated_sse4a_length_0_is_64_bits() { + let mut xmm = [reg(0, 0); 16]; + xmm[0] = reg(0x1122_3344_5566_7788, 0); + // extrq xmm0, length 0 (64), index 0. A non-zero index with + // length 64 goes past bit 63, and AMD leaves that result undefined. + assert_eq!( + emulate(&[0x66, 0x0f, 0x78, 0xc0, 0x00, 0x00], 0, &mut xmm), + Some(6) + ); + assert_eq!(low(&xmm, 0), 0x1122_3344_5566_7788); + // insertq xmm0, xmm1, length 0 (64), index 0 + xmm[1] = reg(0xdead_beef_cafe_f00d, 0); + assert_eq!( + emulate(&[0xf2, 0x0f, 0x78, 0xc1, 0x00, 0x00], 0, &mut xmm), + Some(6) + ); + assert_eq!(low(&xmm, 0), 0xdead_beef_cafe_f00d); + } + + #[test] + fn other_instructions_and_exceptions_are_not_emulated() { + let mut xmm = [reg(0, 0); 16]; + assert_eq!(emulate(&[0x0f, 0x0b], 0, &mut xmm), None); // ud2 + // extrq with a memory operand, which does not exist + assert_eq!(emulate(&[0x66, 0x0f, 0x79, 0x00], 0, &mut xmm), None); + // extrq with immediates needs ModRM.reg 0 + let bad_extrq = [0x66, 0x0f, 0x78, 0xc8, 0x08, 0x14]; + assert_eq!(emulate(&bad_extrq, 0, &mut xmm), None); + // a clzero that did not cause an illegal instruction + let clzero = [0x0f, 0x01, 0xfc]; + assert_eq!( + emulate_as(EXCEPTION_ACCESS_VIOLATION, &clzero, 0, &mut xmm), + None + ); + } + + #[test] + fn instruction_bytes_stop_at_the_end_of_their_page() { + use windows_sys::Win32::System::Memory::{ + MEM_COMMIT, MEM_RELEASE, MEM_RESERVE, PAGE_NOACCESS, PAGE_READWRITE, VirtualAlloc, + VirtualFree, VirtualProtect, + }; + // rdpru, then the next instruction (mov rcx, rax) and padding. + let mut code = [0x90_u8; 16]; + code[..6].copy_from_slice(&[0x0f, 0x01, 0xfd, 0x48, 0x89, 0xc1]); + // SAFETY: two fresh pages of ours, the second made unreadable, so a + // read past the end of the first faults. + unsafe { + let page = VirtualAlloc( + std::ptr::null(), + 0x2000, + MEM_RESERVE | MEM_COMMIT, + PAGE_READWRITE, + ) + .cast::(); + assert!(!page.is_null()); + let mut old = 0; + let guard = page.add(0x1000).cast(); + assert_ne!(VirtualProtect(guard, 0x1000, PAGE_NOACCESS, &mut old), 0); + page.copy_from_nonoverlapping(code.as_ptr(), code.len()); + let whole = "0f 01 fd 48 89 c1 90 90 90 90 90 90 90 90 90"; + assert_eq!(instruction_bytes(page as usize), whole); + // The page's last three bytes: rdpru, and nothing read after it. + let end = page.add(0x1000 - 3); + end.copy_from_nonoverlapping(code.as_ptr(), 3); + assert_eq!(instruction_bytes(end as usize), "0f 01 fd"); + VirtualFree(page.cast(), 0, MEM_RELEASE); + } + } +} diff --git a/crates/leonida-loader/src/lib.rs b/crates/leonida-loader/src/lib.rs new file mode 100644 index 000000000..e6c0907f6 --- /dev/null +++ b/crates/leonida-loader/src/lib.rs @@ -0,0 +1,62 @@ +//! Runs a title's original x86-64 code natively, inside our process. +//! +//! Xbox Series X|S executables are x86-64 PE32+ images built for a Zen 2 +//! CPU, so the machine code needs no translation. What differs is the +//! platform underneath, so the loader's job is to: +//! +//! 1. [`prepare()`] a lightly patched copy of the image (pure, portable): mark +//! it as a DLL, remove its entry point and import directory, and detach +//! its TLS callbacks, so the Windows loader maps it, relocates it, +//! allocates its static TLS and registers its unwind tables, but runs +//! none of its code and resolves none of its imports; +//! 2. load that copy as a real module (debuggers, profilers, crash dumps +//! and stack walks all see it); this step is Windows-only; +//! 3. map the DLLs the title ships beside it the same way +//! (`load_title_dlls`); +//! 4. bind every import ourselves through an [`ImportResolver`], our +//! runtime (`leonida-hle`), the host or the title's DLLs, and route +//! anything unresolved to a generated stub that reports exactly what +//! was called; +//! 5. initialise the title's DLLs, then run TLS callbacks and the entry +//! point on a thread with the stack size the image asks for; from then +//! on, pass every thread start and end on to the attached images. + +#[cfg(windows)] +mod console_insn; +mod crash; +pub mod prepare; +pub mod resolve; +#[cfg(all(windows, feature = "diagnostics"))] +mod stacks; +#[cfg(windows)] +mod threads; +#[cfg(windows)] +mod thunks; +#[cfg(windows)] +mod tls; +#[cfg(windows)] +mod windows; + +#[cfg(windows)] +pub use crash::{ + locate, log_crash, log_crashes_to, note_title_output, report_crashes, report_unhandled, +}; +#[cfg(all(windows, feature = "diagnostics"))] +pub use crash::save_on_crash; +pub use prepare::{PrepareError, PreparedImage, prepare}; +pub use resolve::{ImportResolver, Provenance, Resolution}; +#[cfg(all(windows, feature = "diagnostics"))] +pub use stacks::{dump_stacks, dump_stacks_on_schedule}; +#[cfg(windows)] +pub use threads::disable_thread_calls; +#[cfg(windows)] +pub use thunks::{UnimplementedPolicy, unimplemented_call_count}; +#[cfg(windows)] +pub use windows::{ + BindReport, LoadedImage, MissingImport, WithTitleDlls, load, load_title_dll, load_title_dlls, +}; + +/// `DLL_PROCESS_ATTACH`, for TLS callbacks. +pub const DLL_PROCESS_ATTACH: u32 = 1; +/// `DLL_PROCESS_DETACH`. +pub const DLL_PROCESS_DETACH: u32 = 0; diff --git a/crates/leonida-loader/src/prepare.rs b/crates/leonida-loader/src/prepare.rs new file mode 100644 index 000000000..8cd15292a --- /dev/null +++ b/crates/leonida-loader/src/prepare.rs @@ -0,0 +1,283 @@ +//! Turns a title's image into something the Windows loader maps but does +//! not run. Pure byte manipulation, so it is testable on any host. + +use leonida_pe::layout::{self, dir, dll_flags, file_flags}; +use leonida_pe::{ImageInfo, PeError}; + +#[derive(Debug, thiserror::Error)] +pub enum PrepareError { + #[error(transparent)] + Pe(#[from] PeError), + #[error("cannot patch image: {0}")] + Patch(&'static str), +} + +/// A patched copy of an image plus everything we need from the original. +#[derive(Debug, Clone)] +pub struct PreparedImage { + /// Parsed from the *original* bytes: imports, TLS callbacks and entry + /// point as the title expects them. + pub info: ImageInfo, + /// The patched bytes to hand to the Windows loader. + pub bytes: Vec, + /// BLAKE3 of the original bytes: identifies the exact build. + pub original_hash: blake3::Hash, +} + +impl PreparedImage { + /// File name for the patched copy, unique per original build. + pub fn file_name(&self) -> String { + format!("leonida-image-{}.dll", &self.original_hash.to_hex()[..16]) + } +} + +/// Produces the patched copy. The changes are: +/// +/// * `IMAGE_FILE_DLL` set, entry point cleared: the OS maps it like a DLL +/// and calls nothing; +/// * import directory points to its empty terminator and the bound-import +/// directory is cleared: we bind the original slots using `info.imports`; +/// * TLS callback pointer cleared: the OS still allocates static TLS for +/// the image, but callbacks only run when we call them (after binding); +/// its base relocation is made a no-op so the 0 survives a rebase; +/// * `FORCE_INTEGRITY` cleared, checksum zeroed: the copy is unsigned. +pub fn prepare(original: &[u8]) -> Result { + let info = ImageInfo::parse(original)?; + let mut bytes = original.to_vec(); + + let fh = layout::file_header_offset(&bytes).ok_or(PrepareError::Patch("no file header"))?; + let opt = + layout::optional_header_offset(&bytes).ok_or(PrepareError::Patch("no optional header"))?; + + let characteristics = info.characteristics | file_flags::DLL; + write_u16( + &mut bytes, + fh + layout::FILE_HEADER_CHARACTERISTICS, + characteristics, + )?; + write_u32(&mut bytes, opt + layout::OPT_ADDRESS_OF_ENTRY_POINT, 0)?; + write_u32(&mut bytes, opt + layout::OPT_CHECKSUM, 0)?; + let dll_characteristics = info.dll_characteristics & !dll_flags::FORCE_INTEGRITY; + write_u16( + &mut bytes, + opt + layout::OPT_DLL_CHARACTERISTICS, + dll_characteristics, + )?; + + // Windows 10 assigns static TLS to the prepared DLL when its empty + // import table is present. The parser has already walked one descriptor + // per module up to the null terminator, regardless of the recorded Size. + if let Some(at) = layout::data_directory_offset(&bytes, dir::IMPORT) { + let rva = layout::read_u32(&bytes, at).ok_or(PrepareError::Patch("no import RVA"))?; + if rva != 0 { + let terminator = u32::try_from(info.imports.len()) + .ok() + .and_then(|count| count.checked_mul(IMPORT_DESCRIPTOR_SIZE)) + .and_then(|offset| rva.checked_add(offset)) + .ok_or(PrepareError::Patch("import terminator RVA overflow"))?; + write_u32(&mut bytes, at, terminator)?; + write_u32(&mut bytes, at + 4, IMPORT_DESCRIPTOR_SIZE)?; + } + } + if let Some(at) = layout::data_directory_offset(&bytes, dir::BOUND_IMPORT) { + write(&mut bytes, at, &[0; layout::DATA_DIRECTORY_SIZE])?; + } + + if let Some(tls) = &info.tls + && tls.callbacks_va != 0 + { + let at = info + .rva_to_file_offset(tls.directory_rva) + .ok_or(PrepareError::Patch("TLS directory is not file-backed"))?; + write_u64( + &mut bytes, + at as usize + layout::TLS64_ADDRESS_OF_CALLBACKS, + 0, + )?; + // The field's base relocation would turn the 0 into `delta` whenever + // the loader maps the copy away from its preferred base (Wine always + // does for DYNAMIC_BASE images), and the loader then reads callbacks + // from there. Make that entry a no-op. + let field_rva = tls.directory_rva + layout::TLS64_ADDRESS_OF_CALLBACKS as u32; + for (entry, target) in dir64_relocations(&bytes, &info) { + if target == field_rva { + write_u16(&mut bytes, entry, 0)?; // IMAGE_REL_BASED_ABSOLUTE + } + } + } + + Ok(PreparedImage { + info, + bytes, + original_hash: blake3::hash(original), + }) +} + +/// Size of an IMAGE_IMPORT_DESCRIPTOR in the PE file. +const IMPORT_DESCRIPTOR_SIZE: u32 = 20; + +/// Every `IMAGE_REL_BASED_DIR64` base relocation: (file offset of its entry, +/// RVA it patches). Empty if the image has no readable relocation table. +fn dir64_relocations(bytes: &[u8], info: &ImageInfo) -> Vec<(usize, u32)> { + const DIR64: u16 = 10; + let mut out = Vec::new(); + let Some(d) = layout::data_directory_offset(bytes, dir::BASERELOC) else { + return out; + }; + let (Some(rva), Some(size)) = (layout::read_u32(bytes, d), layout::read_u32(bytes, d + 4)) + else { + return out; + }; + let Some(start) = info.rva_to_file_offset(rva).filter(|_| size != 0) else { + return out; + }; + let (mut at, end) = (start as usize, start as usize + size as usize); + while at + 8 <= end { + let (Some(page), Some(block)) = + (layout::read_u32(bytes, at), layout::read_u32(bytes, at + 4)) + else { + break; + }; + let block = block as usize; + if block < 8 || at + block > end { + break; + } + for entry in (at + 8..at + block).step_by(2) { + let Some(e) = bytes.get(entry..entry + 2) else { + break; + }; + let e = u16::from_le_bytes([e[0], e[1]]); + if e >> 12 == DIR64 { + out.push((entry, page + u32::from(e & 0xFFF))); + } + } + at += block; + } + out +} + +fn write_u16(bytes: &mut [u8], at: usize, v: u16) -> Result<(), PrepareError> { + write(bytes, at, &v.to_le_bytes()) +} +fn write_u32(bytes: &mut [u8], at: usize, v: u32) -> Result<(), PrepareError> { + write(bytes, at, &v.to_le_bytes()) +} +fn write_u64(bytes: &mut [u8], at: usize, v: u64) -> Result<(), PrepareError> { + write(bytes, at, &v.to_le_bytes()) +} +fn write(bytes: &mut [u8], at: usize, v: &[u8]) -> Result<(), PrepareError> { + bytes + .get_mut(at..at + v.len()) + .ok_or(PrepareError::Patch("header field outside of file"))? + .copy_from_slice(v); + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn patches_own_test_binary() { + let original = std::fs::read(std::env::current_exe().unwrap()).unwrap(); + let prepared = prepare(&original).unwrap(); + assert!(!prepared.info.is_dll(), "info describes the original"); + assert!(prepared.info.import_count() > 0); + + let patched = ImageInfo::parse(&prepared.bytes).unwrap(); + assert!(patched.is_dll()); + assert_eq!(patched.entry_rva, 0); + assert!(patched.imports.is_empty()); + assert_eq!(patched.dll_characteristics & dll_flags::FORCE_INTEGRITY, 0); + if let Some(tls) = &patched.tls { + assert_eq!(tls.callbacks_va, 0); + let field = tls.directory_rva + layout::TLS64_ADDRESS_OF_CALLBACKS as u32; + assert!( + dir64_relocations(&prepared.bytes, &patched) + .iter() + .all(|&(_, target)| target != field), + "the cleared callback pointer must not be relocated" + ); + } + // Nothing else moved: same sections, same size. + assert_eq!(patched.sections.len(), prepared.info.sections.len()); + assert_eq!(prepared.bytes.len(), original.len()); + } + + #[test] + fn keeps_iat_slots_when_import_size_excludes_the_terminator() { + let mut original = std::fs::read(std::env::current_exe().unwrap()).unwrap(); + let info = ImageInfo::parse(&original).unwrap(); + let directory = layout::data_directory_offset(&original, dir::IMPORT).unwrap(); + // This linker layout counts the descriptors for real modules only. + let descriptor_bytes = u32::try_from(info.imports.len()).unwrap() * IMPORT_DESCRIPTOR_SIZE; + write_u32(&mut original, directory + 4, descriptor_bytes).unwrap(); + let prepared = prepare(&original).unwrap(); + let empty = layout::read_u32(&prepared.bytes, directory).unwrap(); + assert_eq!( + empty, + layout::read_u32(&original, directory).unwrap() + descriptor_bytes + ); + assert_eq!( + layout::read_u32(&prepared.bytes, directory + 4), + Some(IMPORT_DESCRIPTOR_SIZE) + ); + let at = info.rva_to_file_offset(empty).unwrap() as usize; + assert_eq!( + &prepared.bytes[at..at + IMPORT_DESCRIPTOR_SIZE as usize], + &[0; 20] + ); + let iat = layout::data_directory_offset(&original, dir::IAT).unwrap(); + assert_eq!( + &prepared.bytes[iat..iat + layout::DATA_DIRECTORY_SIZE], + &original[iat..iat + layout::DATA_DIRECTORY_SIZE] + ); + assert_eq!(prepared.info.import_count(), info.import_count()); + for module in &prepared.info.imports { + for entry in &module.entries { + let at = info.rva_to_file_offset(entry.iat_slot_rva).unwrap() as usize; + assert_eq!(&prepared.bytes[at..at + 8], &original[at..at + 8]); + } + } + } + + #[cfg(windows)] + #[test] + fn windows_assigns_static_tls_to_a_prepared_dll() { + // Model a title DLL using our own linked image. Loading a DLL leaves + // its assigned index intact; the executable-specific redirect resets it. + let mut original = std::fs::read(std::env::current_exe().unwrap()).unwrap(); + let flags = + layout::file_header_offset(&original).unwrap() + layout::FILE_HEADER_CHARACTERISTICS; + let characteristics = + ImageInfo::parse(&original).unwrap().characteristics | file_flags::DLL; + write_u16(&mut original, flags, characteristics).unwrap(); + let prepared = prepare(&original).unwrap(); + let info = &prepared.info; + let tls = info.tls.as_ref().expect("the test binary uses static TLS"); + let directory = info.rva_to_file_offset(tls.directory_rva).unwrap() as usize; + let index_va = layout::read_u64(&original, directory + 16).unwrap(); + let index_rva = index_va.checked_sub(info.image_base).unwrap(); + assert!(index_rva + 4 <= u64::from(info.size_of_image)); + + let folder = tempfile::tempdir().unwrap(); + let image = crate::load(&prepared, folder.path()).unwrap(); + // SAFETY: the mapped test image contains the checked DWORD above. + let assigned = + unsafe { ((image.base() + index_rva as usize) as *const u32).read_unaligned() }; + // SAFETY: the prepared DLL has never been attached or given to a caller. + unsafe { image.unload() }; + assert_ne!( + assigned, 0, + "the process executable already owns TLS slot zero" + ); + } + + #[test] + fn file_name_is_stable_per_build() { + let original = std::fs::read(std::env::current_exe().unwrap()).unwrap(); + let a = prepare(&original).unwrap(); + let b = prepare(&original).unwrap(); + assert_eq!(a.file_name(), b.file_name()); + } +} diff --git a/crates/leonida-loader/src/resolve.rs b/crates/leonida-loader/src/resolve.rs new file mode 100644 index 000000000..46819825a --- /dev/null +++ b/crates/leonida-loader/src/resolve.rs @@ -0,0 +1,33 @@ +//! How imports get their addresses. + +use leonida_pe::ImportSymbol; + +/// Who provides a bound import. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub enum Provenance { + /// Our implementation of the console API. + Hle, + /// The host's own implementation (e.g. Windows API sets that behave the + /// same on console and PC). + Host, + /// A DLL the title ships, mapped like the executable. + Title, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Resolution { + Found { + address: usize, + provenance: Provenance, + }, + /// Nobody implements it; the loader installs a reporting stub. + Missing, +} + +/// Supplies an address for each `dll!symbol` the title imports. +/// +/// `dll` is passed exactly as written in the image; implementations should +/// compare case-insensitively. +pub trait ImportResolver { + fn resolve(&self, dll: &str, symbol: &ImportSymbol) -> Resolution; +} diff --git a/crates/leonida-loader/src/stacks.rs b/crates/leonida-loader/src/stacks.rs new file mode 100644 index 000000000..6d8518950 --- /dev/null +++ b/crates/leonida-loader/src/stacks.rs @@ -0,0 +1,224 @@ +//! Where every thread is: `LEONIDA_STACKS=[,...]` prints +//! each thread's unwound stack as `module+rva` that many seconds after +//! [`dump_stacks_on_schedule`], to find what a title waits on. + +use std::ffi::c_void; + +use windows_sys::Wdk::System::Threading::{ + NtQueryInformationThread, ThreadBasicInformation, ThreadQuerySetWin32StartAddress, +}; +use windows_sys::Win32::Foundation::{CloseHandle, HANDLE, INVALID_HANDLE_VALUE, LocalFree}; +use windows_sys::Win32::System::Diagnostics::Debug::{ + CONTEXT, CONTEXT_FULL_AMD64, GetThreadContext, +}; +use windows_sys::Win32::System::Diagnostics::ToolHelp::{ + CreateToolhelp32Snapshot, TH32CS_SNAPTHREAD, THREADENTRY32, Thread32First, Thread32Next, +}; +use windows_sys::Win32::System::Threading::{ + GetCurrentProcessId, GetCurrentThreadId, GetThreadDescription, OpenThread, ResumeThread, + SuspendThread, THREAD_GET_CONTEXT, THREAD_QUERY_INFORMATION, THREAD_SUSPEND_RESUME, +}; + +use crate::crash::{MAX_FRAMES, locate, unwind_into}; + +/// Reads `LEONIDA_STACKS` and, if set, starts a thread that prints every +/// thread's stack at each listed time (seconds from now). +pub fn dump_stacks_on_schedule() { + let Ok(list) = std::env::var("LEONIDA_STACKS") else { + return; + }; + let mut times: Vec = list + .split(',') + .filter_map(|t| t.trim().parse().ok()) + .collect(); + times.sort_by(f64::total_cmp); + let start = std::time::Instant::now(); + std::thread::spawn(move || { + for t in times { + let at = std::time::Duration::from_secs_f64(t.max(0.0)); + std::thread::sleep(at.saturating_sub(start.elapsed())); + dump_stacks(); + } + }); +} + +/// `THREAD_BASIC_INFORMATION` (ntddk). +#[repr(C)] +struct BasicInfo { + exit_status: i32, + teb: *const usize, + client_id: [usize; 2], + affinity: usize, + priority: i32, + base_priority: i32, +} + +/// `GetThreadContext` wants a 16-byte aligned context. +#[repr(C, align(16))] +struct Aligned(CONTEXT); + +/// Prints every other thread's stack to stderr. Each thread is suspended +/// only while its context is read and unwound into a buffer allocated +/// beforehand (it may hold the heap lock). +pub fn dump_stacks() { + // SAFETY: plain queries and a snapshot of this process's threads. + let (me, process, snapshot) = unsafe { + ( + GetCurrentThreadId(), + GetCurrentProcessId(), + CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, 0), + ) + }; + if snapshot == INVALID_HANDLE_VALUE { + return; + } + let mut ids = Vec::new(); + // SAFETY: zeroed is a valid THREADENTRY32; its size is set before use. + let mut entry: THREADENTRY32 = unsafe { std::mem::zeroed() }; + entry.dwSize = size_of::() as u32; + // SAFETY: `snapshot` is open; `entry` is sized. + let mut more = unsafe { Thread32First(snapshot, &mut entry) } != 0; + while more { + if entry.th32OwnerProcessID == process && entry.th32ThreadID != me { + ids.push(entry.th32ThreadID); + } + // SAFETY: as above. + more = unsafe { Thread32Next(snapshot, &mut entry) } != 0; + } + // SAFETY: we opened it. + unsafe { CloseHandle(snapshot) }; + eprintln!("Leonida Legacy: stacks of {} threads", ids.len()); + for id in ids { + // SAFETY: opens a thread of our own process. + let thread = unsafe { + OpenThread( + THREAD_SUSPEND_RESUME | THREAD_GET_CONTEXT | THREAD_QUERY_INFORMATION, + 0, + id, + ) + }; + if thread.is_null() { + continue; + } + let (frames, (priority, base)) = frames_of(thread); + eprintln!( + " thread {id} \"{}\" start {} priority {priority} (base {base})", + name_of(thread), + locate(start_of(thread)) + ); + for (i, pc) in frames.into_iter().enumerate() { + eprintln!(" #{i:<2} {}", locate(pc as usize)); + } + // SAFETY: we opened it. + unsafe { CloseHandle(thread) }; + } +} + +/// The thread's frames and its current and base scheduling priority (0-31). +fn frames_of(thread: HANDLE) -> (Vec, (i32, i32)) { + let mut frames = Vec::with_capacity(MAX_FRAMES); + let mut info: BasicInfo = BasicInfo { + exit_status: 0, + teb: std::ptr::null(), + client_id: [0; 2], + affinity: 0, + priority: 0, + base_priority: 0, + }; + // SAFETY: writes `info`, whose layout and size are the system's. + let status = unsafe { + NtQueryInformationThread( + thread, + ThreadBasicInformation, + (&raw mut info).cast(), + size_of::() as u32, + std::ptr::null_mut(), + ) + }; + if status != 0 || info.teb.is_null() { + return (frames, (0, 0)); + } + // SAFETY: the TEB of a live thread of this process: its NT_TIB holds + // the stack base at +8 and the stack limit at +0x10. + let (high, low) = unsafe { (info.teb.add(1).read(), info.teb.add(2).read()) }; + // SAFETY: zeroed is a valid CONTEXT. + let mut context = Aligned(unsafe { std::mem::zeroed() }); + context.0.ContextFlags = CONTEXT_FULL_AMD64; + // SAFETY: suspends, reads and resumes a thread that is not this one; + // nothing between suspend and resume allocates or takes a lock the + // thread could hold besides the unwinder's own. + unsafe { + if SuspendThread(thread) == u32::MAX { + return (frames, (info.priority, info.base_priority)); + } + if GetThreadContext(thread, &mut context.0) != 0 { + unwind_into(context.0, low, high, &mut frames); + } + ResumeThread(thread); + } + (frames, (info.priority, info.base_priority)) +} + +fn start_of(thread: HANDLE) -> usize { + let mut start = 0usize; + // SAFETY: writes one pointer-sized start address. + unsafe { + NtQueryInformationThread( + thread, + ThreadQuerySetWin32StartAddress, + (&raw mut start).cast(), + size_of::() as u32, + std::ptr::null_mut(), + ) + }; + start +} + +fn name_of(thread: HANDLE) -> String { + let mut name = std::ptr::null_mut(); + // SAFETY: the system allocates the string; we free it with LocalFree. + unsafe { + if GetThreadDescription(thread, &mut name) < 0 || name.is_null() { + return String::new(); + } + let len = (0..).take_while(|&i| *name.add(i) != 0).count(); + let text = String::from_utf16_lossy(std::slice::from_raw_parts(name, len)); + LocalFree(name.cast::()); + text + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn another_threads_stack_unwinds_to_its_start() { + let (tx, rx) = std::sync::mpsc::channel(); + let (stop_tx, stop_rx) = std::sync::mpsc::channel::<()>(); + let parked = std::thread::spawn(move || { + // SAFETY: plain query. + tx.send(unsafe { GetCurrentThreadId() }).unwrap(); + stop_rx.recv().ok(); + }); + let id = rx.recv().unwrap(); + // SAFETY: a thread of this process. + let thread = unsafe { + OpenThread( + THREAD_SUSPEND_RESUME | THREAD_GET_CONTEXT | THREAD_QUERY_INFORMATION, + 0, + id, + ) + }; + assert!(!thread.is_null()); + let (frames, _) = frames_of(thread); + // Waiting in the kernel, several frames down from the thread start. + assert!(frames.len() >= 3, "{frames:?}"); + assert!(start_of(thread) != 0); + // SAFETY: opened above. + unsafe { CloseHandle(thread) }; + dump_stacks(); + stop_tx.send(()).unwrap(); + parked.join().unwrap(); + } +} diff --git a/crates/leonida-loader/src/threads.rs b/crates/leonida-loader/src/threads.rs new file mode 100644 index 000000000..7ded98a13 --- /dev/null +++ b/crates/leonida-loader/src/threads.rs @@ -0,0 +1,439 @@ +//! Thread notices for title images. The prepared copies have no entry point +//! and no TLS callbacks, so the Windows loader tells them nothing when a +//! thread starts or ends. Our own TLS callback, which Windows calls on every +//! thread of the process whoever created it (title, host CRT or our +//! runtime), passes each notice on to every attached image: its TLS +//! callbacks, then a DLL's `DllMain`. + +use std::ffi::c_void; +use std::sync::atomic::{AtomicBool, AtomicU32, Ordering}; +use std::sync::{Arc, Mutex}; +use std::time::{Duration, Instant}; + +use crate::{DLL_PROCESS_DETACH, LoadedImage}; + +const DLL_THREAD_ATTACH: u32 = 2; +const DLL_THREAD_DETACH: u32 = 3; + +struct Mapped { + image: Arc, + /// Its `DLL_PROCESS_ATTACH` is done; only then does it get thread notices. + attached: bool, + /// `DisableThreadLibraryCalls`: no more `DllMain` thread notices. + quiet: bool, +} + +/// Every title image we mapped, in load order. +static IMAGES: Mutex> = Mutex::new(Vec::new()); + +fn images() -> std::sync::MutexGuard<'static, Vec> { + IMAGES.lock().unwrap_or_else(|e| e.into_inner()) +} + +pub(crate) fn mapped(image: &LoadedImage) { + // SAFETY: reads our own static, so the linker keeps it (and its section). + unsafe { std::ptr::from_ref(&ON_THREAD).read_volatile() }; + let image = Arc::new(image.clone()); + let mut images = images(); + images.retain(|m| m.image.base() != image.base()); + images.push(Mapped { + image, + attached: false, + quiet: false, + }); +} + +/// Its `DLL_PROCESS_ATTACH` is done. The list keeps attach order, which is +/// the Windows loader's initialisation order. +pub(crate) fn attached(base: usize) { + let mut images = images(); + if let Some(i) = images.iter().position(|m| m.image.base() == base) { + let mut m = images.remove(i); + m.attached = true; + images.push(m); + } + static AT_EXIT: std::sync::Once = std::sync::Once::new(); + // Registered before the title's own exit functions, so it runs after + // them, as `ExitProcess` follows `exit`'s functions on Windows. + // SAFETY: registers a function with the host CRT's exit table. + AT_EXIT.call_once(|| unsafe { + atexit(detach_all); + }); +} + +pub(crate) fn detached(base: usize) { + if let Some(m) = images().iter_mut().find(|m| m.image.base() == base) { + m.attached = false; + } +} + +unsafe extern "C" { + fn atexit(f: extern "C" fn()) -> i32; +} + +/// Set once the process is ending: no more thread notices. +static EXITING: AtomicBool = AtomicBool::new(false); + +/// How long title images may take to detach before the process ends anyway +/// (a thread ended while holding a lock their detach code wants). +const DETACH_DEADLINE: Duration = Duration::from_secs(5); + +/// Process exit (the CRT's `exit`, which titles call), in `ExitProcess`'s +/// order: the title's exit functions have run; every other thread ends +/// (title threads and ours); every attached image gets +/// `DLL_PROCESS_DETACH`, DLLs in reverse initialisation order, then the +/// exe's TLS callbacks; then the CRT ends the process. +extern "C" fn detach_all() { + let attached: Vec<_> = images() + .iter_mut() + .filter(|m| m.attached) + .map(|m| { + m.attached = false; + m.image.clone() + }) + .collect(); + let (dlls, exes): (Vec<_>, Vec<_>) = + attached.into_iter().rev().partition(|i| i.info().is_dll()); + tracing::info!( + images = dlls.len() + exes.len(), + "process exit: ending other threads, detaching title images" + ); + EXITING.store(true, Ordering::SeqCst); + // As on Windows, a lock a thread held when it ended stays taken; detach + // code that waits for one would hang the exit. The watchdog runs before + // the other threads end: a thread that ends can hold the heap lock or + // the loader lock, and a new thread needs both to start. After the + // deadline it only ends the process; it does not log, because logging + // needs the heap and the log writer's lock. + // Its thread id, set when it runs its own code; 0 until then. + static WATCHDOG: AtomicU32 = AtomicU32::new(0); + drop(std::thread::spawn(|| { + // SAFETY: a plain query of the calling thread. + let id = unsafe { windows_sys::Win32::System::Threading::GetCurrentThreadId() }; + WATCHDOG.store(id, Ordering::SeqCst); + std::thread::sleep(DETACH_DEADLINE); + end_process(); + })); + // Its start (loader notices, Rust's thread set-up) is done only when + // it runs its own code. The loader notices need the loader lock. This + // thread can hold it, or a thread that waits for this thread can hold + // it. Then the watchdog does not start, so this wait has the same + // deadline. + let waiting = Instant::now(); + let watchdog = loop { + match WATCHDOG.load(Ordering::SeqCst) { + 0 if waiting.elapsed() >= DETACH_DEADLINE => end_process(), + 0 => std::thread::yield_now(), + id => break id, + } + }; + end_other_threads(&[watchdog]); + for image in dlls.iter().chain(&exes) { + // SAFETY: attached images are bound. A non-null third argument + // tells the entry points the process is ending. + unsafe { + image.notify( + DLL_PROCESS_DETACH, + true, + std::ptr::without_provenance_mut(1), + ) + }; + } +} + +/// Ends this process when the title images do not detach in time. It does +/// not use the heap or any lock: a thread that ended can hold them. +fn end_process() { + // SAFETY: ends this process, which is exiting anyway. + unsafe { + windows_sys::Win32::System::Threading::TerminateProcess( + windows_sys::Win32::System::Threading::GetCurrentProcess(), + 1, + ) + }; +} + +/// Ends every thread of the process but this one and those in `keep` (and +/// the ones started while doing so), as `ExitProcess` does first; except +/// the system's thread-pool workers, which `TerminateThread` refuses (the +/// process fails fast) and which run no title code (no title image uses +/// that pool). +fn end_other_threads(keep: &[u32]) { + use windows_sys::Win32::Foundation::{CloseHandle, INVALID_HANDLE_VALUE}; + use windows_sys::Win32::System::Diagnostics::ToolHelp::{ + CreateToolhelp32Snapshot, TH32CS_SNAPTHREAD, THREADENTRY32, Thread32First, Thread32Next, + }; + use windows_sys::Win32::System::Threading::{ + GetCurrentProcessId, GetCurrentThreadId, OpenThread, THREAD_TERMINATE, TerminateThread, + THREAD_QUERY_INFORMATION, + }; + // SAFETY: plain queries of the calling process and thread. + let (process, me) = unsafe { (GetCurrentProcessId(), GetCurrentThreadId()) }; + let mut ended = std::collections::HashSet::new(); + loop { + // SAFETY: a snapshot of every thread, walked with a sized entry. + let others: Vec = unsafe { + let snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, 0); + if snapshot == INVALID_HANDLE_VALUE { + break; + } + let mut entry = THREADENTRY32 { + dwSize: size_of::() as u32, + ..std::mem::zeroed() + }; + let mut ids = Vec::new(); + let mut more = Thread32First(snapshot, &mut entry) != 0; + while more { + if entry.th32OwnerProcessID == process + && entry.th32ThreadID != me + && !keep.contains(&entry.th32ThreadID) + { + ids.push(entry.th32ThreadID); + } + more = Thread32Next(snapshot, &mut entry) != 0; + } + CloseHandle(snapshot); + ids + }; + let new: Vec = others.into_iter().filter(|id| ended.insert(*id)).collect(); + if new.is_empty() { + break; + } + for id in new { + // SAFETY: a thread of this process, which is exiting. + unsafe { + let thread = OpenThread(THREAD_TERMINATE | THREAD_QUERY_INFORMATION, 0, id); + if !thread.is_null() { + if !starts_in(thread, c"ntdll.dll") { + TerminateThread(thread, 0); + } + CloseHandle(thread); + } + } + } + } +} + +pub(crate) fn unmapped(base: usize) { + images().retain(|m| m.image.base() != base); +} + +/// `DisableThreadLibraryCalls` for a title image; `None` if `base` is not +/// one. Fails, as on Windows, for an image with static TLS. +pub fn disable_thread_calls(base: usize) -> Option { + let mut images = images(); + let m = images.iter_mut().find(|m| m.image.base() == base)?; + if m.image.info().tls.is_some() { + return Some(false); + } + m.quiet = true; + Some(true) +} + +/// Windows calls every pointer between the CRT's markers `.CRT$XLA` and +/// `.CRT$XLZ`; `XLAV` sorts ahead of the usual `XLB`, so ours runs before +/// any other callback linked into the exe. +#[used] +#[unsafe(link_section = ".CRT$XLAV")] +static ON_THREAD: unsafe extern "system" fn(*mut c_void, u32, *mut c_void) = on_thread; + +unsafe extern "system" fn on_thread(_: *mut c_void, reason: u32, _: *mut c_void) { + if reason != DLL_THREAD_ATTACH && reason != DLL_THREAD_DETACH { + return; + } + if EXITING.load(Ordering::SeqCst) { + return; // our exit watchdog, or threads ending with the process + } + // A snapshot: title code may map and attach another DLL from here. + let notify: Vec<_> = images() + .iter() + .filter(|m| m.attached) + .map(|m| (m.image.clone(), !m.quiet)) + .collect(); + if notify.is_empty() { + return; + } + // Rust's std sets its threads up after this callback and aborts the + // process if their per-thread state was touched first (the current + // thread's id, which our logging asks for when title code calls us). + // That state is put back as the thread started. + let saved = (reason == DLL_THREAD_ATTACH && started_by_rust()).then(OwnTls::save); + // Starts in load order, ends in reverse, as the Windows loader does. + let notify_one = |(image, dll_main): &(Arc, bool)| { + // SAFETY: attached images have their imports bound. + unsafe { image.notify(reason, *dll_main, std::ptr::null_mut()) }; + }; + if reason == DLL_THREAD_ATTACH { + notify.iter().for_each(notify_one); + } else { + notify.iter().rev().for_each(notify_one); + } + if let Some(saved) = saved { + saved.restore(); + } +} + +/// Our own image's static TLS block on this thread (Rust's std keeps its +/// per-thread state there), as copied before title code ran. +struct OwnTls { + block: *mut u8, + saved: Vec, +} + +/// The TLS directory the linker emits for our image (the CRT's symbol). +#[repr(C)] +struct TlsDirectory { + start: usize, + end: usize, + index: *const u32, + callbacks: usize, + zero_fill: u32, + characteristics: u32, +} + +unsafe extern "C" { + static _tls_used: TlsDirectory; +} + +impl OwnTls { + fn save() -> OwnTls { + let array: *const *mut u8; + // SAFETY: reads TEB.ThreadLocalStoragePointer; the directory is our + // image's, and Windows set up its block on this thread before + // calling TLS callbacks. + let (block, len) = unsafe { + std::arch::asm!("mov {}, gs:[0x58]", out(reg) array, options(nostack, readonly)); + let dir = &raw const _tls_used; + let block = *array.add((*dir).index.read() as usize); + (block, (*dir).end - (*dir).start + (*dir).zero_fill as usize) + }; + // SAFETY: the block is `len` bytes, live for the thread's life. + let saved = unsafe { std::slice::from_raw_parts(block, len) }.to_vec(); + OwnTls { block, saved } + } + + fn restore(self) { + // SAFETY: the same block on the same thread, no reference to it held. + unsafe { std::ptr::copy_nonoverlapping(self.saved.as_ptr(), self.block, self.saved.len()) }; + } +} + +/// Whether Rust's std started this thread (its start routine is in our +/// exe): the title's main thread and our runtime's workers, which run +/// title callbacks. +fn started_by_rust() -> bool { + // SAFETY: the calling thread's pseudo handle. + starts_in(unsafe { windows_sys::Win32::System::Threading::GetCurrentThread() }, c"") +} + +/// Whether `thread`'s start routine lies in the module named `module` +/// (empty: our exe). +fn starts_in(thread: windows_sys::Win32::Foundation::HANDLE, module: &std::ffi::CStr) -> bool { + use windows_sys::Wdk::System::Threading::{ + NtQueryInformationThread, ThreadQuerySetWin32StartAddress, + }; + use windows_sys::Win32::System::LibraryLoader::{ + GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS, GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT, + GetModuleHandleA, GetModuleHandleExW, + }; + + let mut start = 0usize; + // SAFETY: writes one pointer-sized start address. + let status = unsafe { + NtQueryInformationThread( + thread, + ThreadQuerySetWin32StartAddress, + (&raw mut start).cast(), + size_of::() as u32, + std::ptr::null_mut(), + ) + }; + let mut found = std::ptr::null_mut(); + let name = if module.is_empty() { + std::ptr::null() + } else { + module.as_ptr().cast() + }; + // SAFETY: looks up the module containing an address, taking no reference. + status == 0 + && unsafe { + GetModuleHandleExW( + GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT, + start as *const u16, + &mut found, + ) + } != 0 + // SAFETY: a module handle by name (or our exe's); no reference taken. + && found == unsafe { GetModuleHandleA(name) } +} + +#[cfg(test)] +mod tests { + use std::sync::atomic::{AtomicU32, AtomicU64, Ordering}; + use std::time::Duration; + + /// A thread that counts in `ticks` until it ends; returns its thread id + /// when it has counted once. + fn busy(ticks: &'static AtomicU64) -> u32 { + static ID: AtomicU32 = AtomicU32::new(0); + ID.store(0, Ordering::SeqCst); + std::thread::spawn(move || { + // SAFETY: a plain query of the calling thread. + let id = unsafe { windows_sys::Win32::System::Threading::GetCurrentThreadId() }; + ID.store(id, Ordering::SeqCst); + loop { + ticks.fetch_add(1, Ordering::SeqCst); + std::thread::yield_now(); + } + }); + while ticks.load(Ordering::SeqCst) == 0 { + std::thread::yield_now(); + } + ID.load(Ordering::SeqCst) + } + + /// Whether `ticks` stays the same for a short time. + fn stopped(ticks: &AtomicU64) -> bool { + let at = ticks.load(Ordering::SeqCst); + std::thread::sleep(Duration::from_millis(50)); + ticks.load(Ordering::SeqCst) == at + } + + /// In a child process of the next test: ends the other threads but one + /// kept thread, and checks that a busy thread stopped and the kept one + /// did not. + #[test] + fn exit_child() { + if std::env::var_os("LEONIDA_EXIT_CHILD").is_none() { + return; + } + static ENDS: AtomicU64 = AtomicU64::new(0); + static KEPT: AtomicU64 = AtomicU64::new(0); + busy(&ENDS); + let kept = busy(&KEPT); + super::end_other_threads(&[kept]); + let ended = stopped(&ENDS); + let still_running = !stopped(&KEPT); + // The test harness's threads are gone too: leave at once. + println!( + "{} {}", + if ended { "ENDED" } else { "STILL RUNNING" }, + if still_running { "KEPT" } else { "NOT KEPT" } + ); + std::process::exit(0); + } + + #[test] + fn exit_ends_the_other_threads_first() { + let out = std::process::Command::new(std::env::current_exe().unwrap()) + .args(["--exact", "threads::tests::exit_child", "--nocapture"]) + .env("LEONIDA_EXIT_CHILD", "1") + .output() + .unwrap(); + let text = String::from_utf8_lossy(&out.stdout); + assert!( + out.status.success() && text.contains("ENDED KEPT"), + "{text}" + ); + } +} diff --git a/crates/leonida-loader/src/thunks.rs b/crates/leonida-loader/src/thunks.rs new file mode 100644 index 000000000..f53847f6a --- /dev/null +++ b/crates/leonida-loader/src/thunks.rs @@ -0,0 +1,187 @@ +//! Stubs for imports nobody implements yet. +//! +//! Each unresolved import gets 32 bytes of generated code: +//! +//! ```text +//! mov rcx, <&'static ImportSite> ; 48 B9 imm64 +//! mov rax, ; 48 B8 imm64 +//! jmp rax ; FF E0 +//! ``` +//! +//! The jump keeps the title's return address on the stack, so the handler +//! returns straight to the caller. Bring-up then shows exactly which API to +//! implement next, rather than failing at load time. + +use std::sync::atomic::{AtomicU64, Ordering}; + +use anyhow::{Result, bail}; +use windows_sys::Win32::System::Diagnostics::Debug::{ + DebugBreak, FlushInstructionCache, IsDebuggerPresent, +}; +use windows_sys::Win32::System::Memory::{ + MEM_COMMIT, MEM_RESERVE, PAGE_EXECUTE_READ, PAGE_READWRITE, VirtualAlloc, VirtualProtect, +}; +use windows_sys::Win32::System::Threading::GetCurrentProcess; + +/// What an unimplemented import does when called. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] +pub enum UnimplementedPolicy { + /// Log, break into an attached debugger, then abort. The default: + /// silently continuing usually crashes later and further from the cause. + #[default] + Trap, + /// Log once per import and return 0. Useful to push through bring-up. + ReturnZero, +} + +/// Identifies one unresolved import. Leaked: lives as long as the process. +#[derive(Debug)] +pub struct ImportSite { + pub dll: String, + pub symbol: String, + pub policy: UnimplementedPolicy, + pub calls: AtomicU64, +} + +static UNIMPLEMENTED_CALLS: AtomicU64 = AtomicU64::new(0); + +/// Total number of calls that reached an unimplemented-import stub. +pub fn unimplemented_call_count() -> u64 { + UNIMPLEMENTED_CALLS.load(Ordering::Relaxed) +} + +extern "system" fn unimplemented_import(site: &'static ImportSite) -> u64 { + UNIMPLEMENTED_CALLS.fetch_add(1, Ordering::Relaxed); + let previous = site.calls.fetch_add(1, Ordering::Relaxed); + match site.policy { + UnimplementedPolicy::ReturnZero => { + if previous == 0 { + tracing::warn!(dll = %site.dll, symbol = %site.symbol, "unimplemented import called, returning 0"); + } + 0 + } + UnimplementedPolicy::Trap => { + tracing::error!(dll = %site.dll, symbol = %site.symbol, "unimplemented import called"); + // Into the crash log too: `abort` ends the process without + // running the handlers that write it. + let (dll, symbol) = (&site.dll, &site.symbol); + let text = format!("Leonida Legacy: unimplemented import {dll}!{symbol} called"); + crate::log_crash(&text); + // SAFETY: plain Win32 calls without preconditions. + unsafe { + if IsDebuggerPresent() != 0 { + DebugBreak(); + } + } + std::process::abort(); + } + } +} + +const THUNK_SIZE: usize = 32; + +/// Executable memory holding one stub per unresolved import. +pub(crate) struct ThunkBlock { + base: *mut u8, + len: usize, + used: usize, +} + +impl ThunkBlock { + /// Reserves room for `count` stubs (writable until [`Self::seal`]). + pub(crate) fn new(count: usize) -> Result { + let len = (count.max(1) * THUNK_SIZE).next_multiple_of(4096); + // SAFETY: fresh anonymous allocation; no existing memory is touched. + let base = unsafe { + VirtualAlloc( + std::ptr::null(), + len, + MEM_COMMIT | MEM_RESERVE, + PAGE_READWRITE, + ) + } as *mut u8; + if base.is_null() { + bail!( + "VirtualAlloc for import stubs failed: {}", + std::io::Error::last_os_error() + ); + } + Ok(ThunkBlock { base, len, used: 0 }) + } + + /// Emits a stub for `site` and returns its address. + pub(crate) fn emit(&mut self, site: &'static ImportSite) -> Result { + if self.used + THUNK_SIZE > self.len { + bail!("import stub block is full"); + } + let mut code = [0xCC_u8; THUNK_SIZE]; // int3 padding + code[0..2].copy_from_slice(&[0x48, 0xB9]); + code[2..10].copy_from_slice(&(site as *const ImportSite as u64).to_le_bytes()); + code[10..12].copy_from_slice(&[0x48, 0xB8]); + let handler = unimplemented_import as extern "system" fn(&'static ImportSite) -> u64; + code[12..20].copy_from_slice(&(handler as *const () as u64).to_le_bytes()); + code[20..22].copy_from_slice(&[0xFF, 0xE0]); + // SAFETY: `used + THUNK_SIZE <= len`, and the block is still writable. + let at = unsafe { + let at = self.base.add(self.used); + std::ptr::copy_nonoverlapping(code.as_ptr(), at, THUNK_SIZE); + at + }; + self.used += THUNK_SIZE; + Ok(at as usize) + } + + /// Makes the block read+execute. The block is intentionally leaked: + /// title code may hold these addresses for the life of the process. + pub(crate) fn seal(self) -> Result<()> { + let mut old = 0; + // SAFETY: `base..base+len` is the allocation made in `new`. + let ok = unsafe { VirtualProtect(self.base as _, self.len, PAGE_EXECUTE_READ, &mut old) }; + if ok == 0 { + bail!( + "VirtualProtect for import stubs failed: {}", + std::io::Error::last_os_error() + ); + } + // SAFETY: flushing our own process's instruction cache for our own block. + unsafe { FlushInstructionCache(GetCurrentProcess(), self.base as _, self.len) }; + Ok(()) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + /// In a child process of the next test: calls an unimplemented import + /// that traps, with the crash log where `LEONIDA_TRAP_LOG` says. + #[test] + fn trap_child() { + let Some(log) = std::env::var_os("LEONIDA_TRAP_LOG") else { + return; + }; + crate::log_crashes_to(log.into()); + let site = Box::leak(Box::new(ImportSite { + dll: "probe.dll".into(), + symbol: "Missing".into(), + policy: UnimplementedPolicy::Trap, + calls: AtomicU64::new(0), + })); + unimplemented_import(site); + } + + #[test] + fn a_trapped_import_is_in_the_crash_log() { + let dir = tempfile::tempdir().unwrap(); + let log = dir.path().join("crashes.log"); + let out = std::process::Command::new(std::env::current_exe().unwrap()) + .args(["--exact", "thunks::tests::trap_child", "--nocapture"]) + .env("LEONIDA_TRAP_LOG", &log) + .output() + .unwrap(); + assert!(!out.status.success(), "the trap ends the process"); + let text = std::fs::read_to_string(&log).unwrap_or_default(); + let named = text.contains("Leonida Legacy: unimplemented import probe.dll!Missing called"); + assert!(named, "crash log: {text:?}"); + } +} diff --git a/crates/leonida-loader/src/tls.rs b/crates/leonida-loader/src/tls.rs new file mode 100644 index 000000000..83f7ad142 --- /dev/null +++ b/crates/leonida-loader/src/tls.rs @@ -0,0 +1,219 @@ +//! Static TLS of an executable mapped as a DLL. +//! +//! An exe always gets TLS index 0, so title code reaches its thread-local +//! block as `mov r64, gs:[0x58]` (the thread's TLS array) followed by +//! `[r64]`, without reading `_tls_index`. Mapped as a DLL, the image gets +//! another index. Every such load is turned into a call to a thunk that +//! yields `&array[index]` instead, and the image's `_tls_index` (which CRT +//! code does read, and adds to the array pointer) is set to 0. + +use std::ffi::c_void; + +use anyhow::{Result, bail}; +use leonida_pe::ImageInfo; +use windows_sys::Win32::System::Diagnostics::Debug::FlushInstructionCache; +use windows_sys::Win32::System::Memory::{ + MEM_COMMIT, MEM_RESERVE, PAGE_EXECUTE_READ, PAGE_EXECUTE_READWRITE, PAGE_READWRITE, + VirtualAlloc, VirtualProtect, +}; +use windows_sys::Win32::System::Threading::GetCurrentProcess; + +const SCN_MEM_EXECUTE: u32 = 0x2000_0000; +const TLS64_ADDRESS_OF_INDEX: usize = 16; +/// `mov r64, gs:[0x58]` is `65 REX 8B ModRM 25 58 00 00 00`. +const LOAD_LEN: usize = 9; +const THUNK_SIZE: usize = 32; + +/// Redirects the image's TLS-array loads if the OS gave it an index other +/// than 0. Returns the number of loads patched. +/// +/// # Safety +/// `base` is the image `info` describes, mapped and not yet running. +pub(crate) unsafe fn redirect(base: usize, info: &ImageInfo) -> Result { + let Some(tls) = &info.tls else { return Ok(0) }; + // SAFETY: the TLS directory and the index it points to are in the image; + // the OS relocated the pointer and wrote the index. + let index_at = unsafe { + ((base + tls.directory_rva as usize + TLS64_ADDRESS_OF_INDEX) as *const usize).read() + } as *mut u32; + // SAFETY: as above. + let index = unsafe { index_at.read() }; + if index == 0 { + return Ok(0); + } + let thunks = thunks(near(base, info.size_of_image as usize)?, index)?; + let mut patched = 0; + for section in info + .sections + .iter() + .filter(|s| s.characteristics & SCN_MEM_EXECUTE != 0) + { + let start = base + section.rva as usize; + let len = section.virtual_size as usize; + let mut old = 0; + // SAFETY: the section is part of the mapped image. + if unsafe { VirtualProtect(start as _, len, PAGE_EXECUTE_READWRITE, &mut old) } == 0 { + bail!( + "VirtualProtect(code) failed: {}", + std::io::Error::last_os_error() + ); + } + // SAFETY: writable now, and no title code runs yet. + let code = unsafe { std::slice::from_raw_parts_mut(start as *mut u8, len) }; + patched += patch(code, start, thunks); + // SAFETY: restoring the protection we changed; flushing our own code. + unsafe { + VirtualProtect(start as _, len, old, &mut old); + FlushInstructionCache(GetCurrentProcess(), start as _, len); + } + } + // SAFETY: see `index_at`; `.data` is writable. + unsafe { index_at.write(0) }; + tracing::info!(index, patched, "static TLS redirected"); + Ok(patched) +} + +/// Rewrites each `mov r64, gs:[0x58]` in `code` (at address `at`) as +/// `call thunks[r]; nop4`. `thunks` must be within 2 GiB of `code`. +fn patch(code: &mut [u8], at: usize, thunks: usize) -> usize { + let mut count = 0; + let mut i = 0; + while i + LOAD_LEN <= code.len() { + let c = &code[i..i + LOAD_LEN]; + let rex = c[1]; + let reg = usize::from((c[3] >> 3) & 7) | if rex & 4 != 0 { 8 } else { 0 }; + // shortcut: a byte match, not a decode. In the title all + // 53,246 hits are instruction starts and none is missed (checked + // against a full disassembly); decode .text if a title shows one. + if c[0] == 0x65 + && (rex == 0x48 || rex == 0x4C) + && c[2] == 0x8B + && c[3] & 0xC7 == 0x04 + && c[4..] == [0x25, 0x58, 0, 0, 0] + && reg != 4 + { + let rel = (thunks + reg * THUNK_SIZE) as i64 - (at + i + 5) as i64; + code[i] = 0xE8; + code[i + 1..i + 5].copy_from_slice(&(rel as i32).to_le_bytes()); + code[i + 5..i + 9].copy_from_slice(&[0x0F, 0x1F, 0x40, 0x00]); + count += 1; + i += LOAD_LEN; + } else { + i += 1; + } + } + count +} + +/// Fills `block` with one thunk per register: `mov r, gs:[0x58]; +/// lea r, [r + index * 8]; ret` (flags untouched, like the load it replaces). +fn thunks(block: *mut u8, index: u32) -> Result { + let disp = (index * 8).to_le_bytes(); + for reg in 0..16u8 { + let (r, low) = (reg >> 3, reg & 7); + let mut code = vec![0x65, 0x48 | r << 2, 0x8B, low << 3 | 4, 0x25, 0x58, 0, 0, 0]; + code.extend([0x48 | r << 2 | r, 0x8D, 0x80 | low << 3 | low]); + if low == 4 { + code.push(0x24); // SIB: [r12 + disp32] + } + code.extend(disp); + code.push(0xC3); + // SAFETY: `block` holds 16 thunks and is still writable. + unsafe { + std::ptr::copy_nonoverlapping( + code.as_ptr(), + block.add(usize::from(reg) * THUNK_SIZE), + code.len(), + ) + }; + } + let mut old = 0; + // SAFETY: `block` is our allocation of one page. + if unsafe { VirtualProtect(block as _, 4096, PAGE_EXECUTE_READ, &mut old) } == 0 { + bail!( + "VirtualProtect(TLS thunks) failed: {}", + std::io::Error::last_os_error() + ); + } + Ok(block as usize) +} + +/// One writable page within `rel32` reach of `[base, base + size)`. Leaked: +/// title code calls into it for the life of the process. +fn near(base: usize, size: usize) -> Result<*mut u8> { + const GRANULE: usize = 0x1_0000; + // The search spans 1 GiB each side, so every call site stays in reach. + if size >= 1 << 30 { + bail!("image too large for TLS thunks within rel32 reach"); + } + let above = (base + size).next_multiple_of(GRANULE); + for k in 0..(1usize << 14) { + for hint in [ + base.checked_sub((k + 1) * GRANULE), + Some(above + k * GRANULE), + ] { + let Some(hint) = hint else { continue }; + // SAFETY: a fresh allocation at a free address, or null. + let p = unsafe { + VirtualAlloc( + hint as *const c_void, + 4096, + MEM_COMMIT | MEM_RESERVE, + PAGE_READWRITE, + ) + }; + if !p.is_null() { + return Ok(p.cast()); + } + } + } + bail!("no free page near the image for TLS thunks") +} + +#[cfg(test)] +mod tests { + use super::*; + + /// Reads the thread's TLS array pointer the way title code does. + fn tls_array() -> usize { + let array: usize; + // SAFETY: reads TEB.ThreadLocalStoragePointer. + unsafe { std::arch::asm!("mov {}, gs:[0x58]", out(reg) array) }; + array + } + + #[test] + fn loads_become_calls_that_yield_the_title_slot() { + let page = near(tls_array as *const () as usize, 0).unwrap(); + let thunks = thunks(near(page as usize, 4096).unwrap(), 3).unwrap(); + // (before the load, REX, ModRM, after the load): each case returns + // the loaded register in rax; r12 is saved, being callee-saved. + let cases: [(&[u8], u8, u8, &[u8]); 3] = [ + (&[], 0x48, 0x04, &[0xC3]), // rax + (&[], 0x4C, 0x04, &[0x4C, 0x89, 0xC0, 0xC3]), // r8 + ( + &[0x41, 0x54], + 0x4C, + 0x24, + &[0x4C, 0x89, 0xE0, 0x41, 0x5C, 0xC3], + ), // r12 + ]; + for (before, rex, modrm, after) in cases { + let mut code = before.to_vec(); + code.extend([0x65, rex, 0x8B, modrm, 0x25, 0x58, 0, 0, 0]); + code.extend(after); + // SAFETY: the page is ours and writable. + let bytes = unsafe { std::slice::from_raw_parts_mut(page, code.len()) }; + bytes.copy_from_slice(&code); + assert_eq!(patch(bytes, page as usize, thunks), 1); + let mut old = 0; + // SAFETY: our page, made executable to run the patched code. + unsafe { VirtualProtect(page as _, 4096, PAGE_EXECUTE_READ, &mut old) }; + // SAFETY: the page holds the patched load and a return. + let f: extern "system" fn() -> usize = unsafe { std::mem::transmute(page) }; + assert_eq!(f(), tls_array() + 3 * 8, "REX {rex:#x} ModRM {modrm:#x}"); + // SAFETY: our page again. + unsafe { VirtualProtect(page as _, 4096, PAGE_READWRITE, &mut old) }; + } + } +} diff --git a/crates/leonida-loader/src/windows.rs b/crates/leonida-loader/src/windows.rs new file mode 100644 index 000000000..bdd9fbd05 --- /dev/null +++ b/crates/leonida-loader/src/windows.rs @@ -0,0 +1,432 @@ +//! Loading a prepared image as a real Windows module and binding it. + +use std::collections::HashSet; +use std::ffi::{CString, c_void}; +use std::os::windows::ffi::OsStrExt; +use std::path::{Path, PathBuf}; +use std::sync::Arc; +use std::sync::atomic::AtomicU64; + +use anyhow::{Context, Result, bail}; +use leonida_pe::{ImageInfo, ImportSymbol}; +use windows_sys::Win32::Foundation::{FreeLibrary, HMODULE}; +use windows_sys::Win32::System::LibraryLoader::{GetProcAddress, LoadLibraryExW}; +use windows_sys::Win32::System::Memory::{PAGE_READWRITE, VirtualProtect}; + +use crate::thunks::{ImportSite, ThunkBlock, UnimplementedPolicy}; +use crate::{ + DLL_PROCESS_ATTACH, DLL_PROCESS_DETACH, ImportResolver, PreparedImage, Provenance, Resolution, + prepare, +}; + +/// A title image mapped into this process. A clone names the same mapping +/// (no reference of its own): unload one copy only. +#[derive(Debug, Clone)] +pub struct LoadedImage { + module: HMODULE, + path: PathBuf, + info: ImageInfo, +} + +// SAFETY: HMODULE is a process-wide handle (the base address); using it from +// any thread is fine. +unsafe impl Send for LoadedImage {} +// SAFETY: as above; `LoadedImage` has no interior mutability. +unsafe impl Sync for LoadedImage {} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct MissingImport { + pub dll: String, + pub symbol: String, +} + +/// Outcome of [`LoadedImage::bind_imports`]. +#[derive(Debug, Default, Clone)] +pub struct BindReport { + pub hle: usize, + pub host: usize, + pub title: usize, + pub missing: Vec, +} + +/// Writes the prepared copy into `dir` and maps it with the Windows loader. +/// +/// `dir` receives derived game data, so it must be outside the repository. +pub fn load(prepared: &PreparedImage, dir: &Path) -> Result { + leonida_core::ensure_outside_repo(dir)?; + std::fs::create_dir_all(dir).with_context(|| format!("creating {}", dir.display()))?; + let path = dir.join(prepared.file_name()); + write_if_changed(&path, &prepared.bytes)?; + + let wide: Vec = path.as_os_str().encode_wide().chain(Some(0)).collect(); + // SAFETY: `wide` is a NUL-terminated path. The image has no entry point + // and no imports, so loading it runs no title code. + let module = unsafe { LoadLibraryExW(wide.as_ptr(), std::ptr::null_mut(), 0) }; + if module.is_null() { + bail!( + "LoadLibraryExW({}) failed: {}{}", + path.display(), + std::io::Error::last_os_error(), + if prepared.info.has_relocations { + "" + } else { + " (image has no relocations; its preferred base may be taken)" + } + ); + } + let loaded = LoadedImage { + module, + path, + info: prepared.info.clone(), + }; + // A DLL indexes its TLS properly; only an exe assumes index 0. + if !loaded.info.is_dll() { + // SAFETY: just mapped, and no title code has run. + unsafe { crate::tls::redirect(loaded.base(), &loaded.info) }?; + } + tracing::info!( + base = format_args!("{:#x}", loaded.base()), + preferred = format_args!("{:#x}", loaded.info.image_base), + path = %loaded.path.display(), + "image mapped" + ); + crate::threads::mapped(&loaded); + Ok(loaded) +} + +/// Maps the DLLs the title ships in `title_dir` that `main` imports, +/// directly or through each other, in initialisation order (dependencies +/// first). Only DLL names `wanted` accepts are considered, so DLLs the host +/// or our runtime provide stay with them. Imports are not bound. +pub fn load_title_dlls( + main: &ImageInfo, + title_dir: &Path, + cache_dir: &Path, + wanted: &dyn Fn(&str) -> bool, +) -> Result> { + let mut loaded = Vec::new(); + let dirs = (title_dir, cache_dir); + map_imports(main, dirs, wanted, &mut HashSet::new(), &mut loaded)?; + Ok(loaded) +} + +/// Maps the DLL `name` from `title_dir` like [`load_title_dlls`] does, with +/// the title DLLs it imports (dependencies first, `name` last); empty if +/// `wanted` refuses it or the folder has no such file. For DLLs a title +/// loads itself; `wanted` must refuse those already mapped. +pub fn load_title_dll( + name: &str, + title_dir: &Path, + cache_dir: &Path, + wanted: &dyn Fn(&str) -> bool, +) -> Result> { + let mut loaded = Vec::new(); + let dirs = (title_dir, cache_dir); + map_dll(name, dirs, wanted, &mut HashSet::new(), &mut loaded)?; + Ok(loaded) +} + +fn map_imports( + info: &ImageInfo, + dirs: (&Path, &Path), + wanted: &dyn Fn(&str) -> bool, + seen: &mut HashSet, + loaded: &mut Vec<(String, LoadedImage)>, +) -> Result<()> { + for module in info.imports.iter().chain(&info.delay_imports) { + map_dll(&module.dll, dirs, wanted, seen, loaded)?; + } + Ok(()) +} + +fn map_dll( + name: &str, + dirs: (&Path, &Path), + wanted: &dyn Fn(&str) -> bool, + seen: &mut HashSet, + loaded: &mut Vec<(String, LoadedImage)>, +) -> Result<()> { + let name = name.to_ascii_lowercase(); + let path = dirs.0.join(&name); + if !seen.insert(name.clone()) || !wanted(&name) || !path.is_file() { + return Ok(()); + } + let original = std::fs::read(&path).with_context(|| format!("reading {}", path.display()))?; + let prepared = prepare(&original).with_context(|| format!("preparing {}", path.display()))?; + let image = load(&prepared, dirs.1).with_context(|| format!("loading {}", path.display()))?; + map_imports(&image.info, dirs, wanted, seen, loaded)?; + loaded.push((name, image)); + Ok(()) +} + +/// Resolves through `inner`, then through the exports of the title's DLLs. +pub struct WithTitleDlls<'a> { + pub inner: &'a dyn ImportResolver, + pub dlls: &'a [(String, LoadedImage)], +} + +impl ImportResolver for WithTitleDlls<'_> { + fn resolve(&self, dll: &str, symbol: &ImportSymbol) -> Resolution { + let found = self.inner.resolve(dll, symbol); + if found != Resolution::Missing { + return found; + } + self.dlls + .iter() + .find(|(name, _)| name.eq_ignore_ascii_case(dll)) + .and_then(|(_, image)| image.export_symbol(symbol)) + .map_or(Resolution::Missing, |address| Resolution::Found { + address, + provenance: Provenance::Title, + }) + } +} + +fn write_if_changed(path: &Path, bytes: &[u8]) -> Result<()> { + if std::fs::read(path).is_ok_and(|existing| existing == bytes) { + return Ok(()); + } + let tmp = path.with_extension("tmp"); + std::fs::write(&tmp, bytes).with_context(|| format!("writing {}", tmp.display()))?; + std::fs::rename(&tmp, path).with_context(|| format!("renaming to {}", path.display()))?; + Ok(()) +} + +impl LoadedImage { + pub fn base(&self) -> usize { + self.module as usize + } + + /// Parsed from the original image (imports, entry point, TLS callbacks). + pub fn info(&self) -> &ImageInfo { + &self.info + } + + /// Address of an export of the image, if it has one by that name. + pub fn export(&self, name: &str) -> Option { + let name = CString::new(name).ok()?; + // SAFETY: valid module handle and NUL-terminated name. + unsafe { GetProcAddress(self.module, name.as_ptr().cast()) } + .map(|f| f as *const () as usize) + } + + /// Address of an export, by name or ordinal. + pub fn export_symbol(&self, symbol: &ImportSymbol) -> Option { + match symbol { + ImportSymbol::Name { name, .. } => self.export(name), + // SAFETY: MAKEINTRESOURCE-style ordinal lookup on a valid module. + ImportSymbol::Ordinal(o) => unsafe { GetProcAddress(self.module, *o as usize as _) } + .map(|f| f as *const () as usize), + } + } + + /// Fills every IAT slot of the image. + /// + /// Each import goes to `resolver`; whatever it cannot resolve gets an + /// unimplemented-import stub that behaves according to `policy`. + pub fn bind_imports( + &self, + resolver: &dyn ImportResolver, + policy: UnimplementedPolicy, + ) -> Result { + let mut report = BindReport::default(); + let mut slots: Vec<(u32, usize)> = Vec::with_capacity(self.info.import_count()); + let mut unresolved: Vec<(u32, &str, &ImportSymbol)> = Vec::new(); + + // Delay-load slots are bound eagerly too, so the title's own + // delay-load helper (which would ask the host) never runs. + for module in self.info.imports.iter().chain(&self.info.delay_imports) { + for entry in &module.entries { + match resolver.resolve(&module.dll, &entry.symbol) { + Resolution::Found { + address, + provenance, + } => { + match provenance { + Provenance::Hle => report.hle += 1, + Provenance::Host => report.host += 1, + Provenance::Title => report.title += 1, + } + slots.push((entry.iat_slot_rva, address)); + } + Resolution::Missing => { + unresolved.push((entry.iat_slot_rva, &module.dll, &entry.symbol)); + } + } + } + } + + if !unresolved.is_empty() { + let mut block = ThunkBlock::new(unresolved.len())?; + for (slot, dll, symbol) in unresolved { + let site: &'static ImportSite = Box::leak(Box::new(ImportSite { + dll: dll.to_owned(), + symbol: symbol.to_string(), + policy, + calls: AtomicU64::new(0), + })); + slots.push((slot, block.emit(site)?)); + report.missing.push(MissingImport { + dll: site.dll.clone(), + symbol: site.symbol.clone(), + }); + } + block.seal()?; + } + + self.write_slots(&slots)?; + tracing::info!( + hle = report.hle, + host = report.host, + missing = report.missing.len(), + "imports bound" + ); + Ok(report) + } + + /// Protects and restores each slot on its own: import tables can sit in + /// sections with different protections (delay-load tables in `.didat`). + fn write_slots(&self, slots: &[(u32, usize)]) -> Result<()> { + for &(rva, address) in slots { + let slot = (self.base() + rva as usize) as *mut u64; + let mut old = 0; + // SAFETY: the parser only yields slots inside the image. + if unsafe { VirtualProtect(slot as *const c_void, 8, PAGE_READWRITE, &mut old) } == 0 { + bail!( + "VirtualProtect(IAT slot {rva:#x}) failed: {}", + std::io::Error::last_os_error() + ); + } + // SAFETY: inside the image, now writable, 8-byte aligned by the PE format. + unsafe { slot.write_volatile(address as u64) }; + let mut ignored = 0; + // SAFETY: restoring the protection we just changed. + unsafe { VirtualProtect(slot as *const c_void, 8, old, &mut ignored) }; + } + Ok(()) + } + + /// Calls the image's TLS callbacks with `reason` (e.g. `DLL_PROCESS_ATTACH`). + /// + /// # Safety + /// Runs title code. Imports must be bound first. + pub unsafe fn run_tls_callbacks(&self, reason: u32) { + // SAFETY: forwarded from the caller. + unsafe { self.tls_callbacks(reason, std::ptr::null_mut()) } + } + + /// # Safety + /// See [`Self::run_tls_callbacks`]. + unsafe fn tls_callbacks(&self, reason: u32, reserved: *mut c_void) { + let Some(tls) = &self.info.tls else { return }; + for &rva in &tls.callback_rvas { + type TlsCallback = unsafe extern "system" fn(*mut c_void, u32, *mut c_void); + // SAFETY: the RVA came from the image's own TLS directory. + let callback: TlsCallback = unsafe { std::mem::transmute(self.base() + rva as usize) }; + // SAFETY: the caller guarantees imports are bound. + unsafe { callback(self.module, reason, reserved) }; + } + } + + /// Initialises a DLL as the Windows loader would: its TLS callbacks, + /// then `DllMain(DLL_PROCESS_ATTACH)`. From then on it hears of every + /// thread start and end (see `threads`). + /// + /// # Safety + /// Runs title code. Imports must be bound first, and the DLLs this one + /// depends on attached. + pub unsafe fn attach(&self) -> Result<()> { + // SAFETY: forwarded from the caller. + if unsafe { self.notify(DLL_PROCESS_ATTACH, true, std::ptr::null_mut()) } == Some(0) { + bail!("DllMain returned FALSE"); + } + crate::threads::attached(self.base()); + Ok(()) + } + + /// `DLL_PROCESS_DETACH` as `FreeLibrary` sends it (TLS callbacks, then + /// `DllMain`); the image hears of no more threads. + /// + /// # Safety + /// Runs title code. The image must have been attached (or its attach + /// failed), and no other thread may be using it. + pub unsafe fn detach(&self) { + crate::threads::detached(self.base()); + // SAFETY: forwarded from the caller. + unsafe { self.notify(DLL_PROCESS_DETACH, true, std::ptr::null_mut()) }; + } + + /// Runs the image's TLS callbacks with `reason`, then, if `dll_main` and + /// the image is a DLL with an entry point, its `DllMain`, whose result + /// is returned. `reserved` is the entry points' third argument. + /// + /// # Safety + /// Runs title code. Imports must be bound first. + pub(crate) unsafe fn notify( + &self, + reason: u32, + dll_main: bool, + reserved: *mut c_void, + ) -> Option { + // SAFETY: forwarded from the caller. + unsafe { self.tls_callbacks(reason, reserved) }; + if !dll_main || !self.info.is_dll() || self.info.entry_rva == 0 { + return None; + } + type DllMain = unsafe extern "system" fn(*mut c_void, u32, *mut c_void) -> i32; + // SAFETY: the entry RVA came from the original image header. + let main: DllMain = + unsafe { std::mem::transmute(self.base() + self.info.entry_rva as usize) }; + // SAFETY: forwarded from the caller. + Some(unsafe { main(self.module, reason, reserved) }) + } + + /// Starts the title: on a new thread with the stack size from the image + /// header, attaches `dlls` in order (see [`Self::attach`]), runs the + /// image's TLS callbacks (`DLL_PROCESS_ATTACH`), then its original entry + /// point. Returns the thread so the caller can join it. + /// + /// # Safety + /// Runs title code. Imports of the image and of `dlls` must be bound. + pub unsafe fn spawn_main( + self: Arc, + dlls: Vec<(String, LoadedImage)>, + ) -> Result>> { + if self.info.entry_rva == 0 { + bail!("image has no entry point"); + } + let stack = usize::try_from(self.info.stack_reserve) + .unwrap_or(usize::MAX) + .max(1 << 20); + std::thread::Builder::new() + .name("title-main".into()) + .stack_size(stack) + .spawn(move || { + for (name, dll) in &dlls { + // SAFETY: forwarded from the caller of `spawn_main`. + unsafe { dll.attach() }.with_context(|| format!("attaching {name}"))?; + } + // SAFETY: forwarded from the caller of `spawn_main`. + unsafe { self.run_tls_callbacks(DLL_PROCESS_ATTACH) }; + crate::threads::attached(self.base()); + type Entry = unsafe extern "system" fn(*mut c_void) -> u32; + // SAFETY: the entry RVA came from the original image header. + let entry: Entry = + unsafe { std::mem::transmute(self.base() + self.info.entry_rva as usize) }; + // SAFETY: forwarded from the caller of `spawn_main`. + Ok(unsafe { entry(std::ptr::null_mut()) }) + }) + .context("spawning title main thread") + } + + /// Unmaps the image. + /// + /// # Safety + /// No title code may be running or run later, and no pointer into the + /// image may be used afterwards. + pub unsafe fn unload(self) { + crate::threads::unmapped(self.base()); + // SAFETY: guaranteed by the caller. + unsafe { FreeLibrary(self.module) }; + } +} diff --git a/crates/leonida-loader/tests/load_probe.rs b/crates/leonida-loader/tests/load_probe.rs new file mode 100644 index 000000000..e73f14283 --- /dev/null +++ b/crates/leonida-loader/tests/load_probe.rs @@ -0,0 +1,268 @@ +//! End-to-end: prepare, load, bind and call into a stand-in title +//! (tests/fixtures/hle-probe), without any game data. +#![cfg(windows)] + +use std::ffi::CString; +use std::path::{Path, PathBuf}; +use std::process::Command; + +use leonida_loader::{ + ImportResolver, Provenance, Resolution, UnimplementedPolicy, WithTitleDlls, prepare, + unimplemented_call_count, +}; +use leonida_pe::ImportSymbol; +use windows_sys::Win32::Foundation::CloseHandle; +use windows_sys::Win32::System::LibraryLoader::{GetProcAddress, LoadLibraryA}; +use windows_sys::Win32::System::Threading::{CreateThread, INFINITE, WaitForSingleObject}; + +fn workspace_root() -> PathBuf { + Path::new(env!("CARGO_MANIFEST_DIR")).join("..").join("..") +} + +/// Builds the fixture into its own target dir (the outer cargo holds the +/// lock on the main one while tests run), in the outer one's scratch folder +/// for tests, so that it follows `CARGO_TARGET_DIR` like the rest of the +/// build. +fn build_probe() -> PathBuf { + let manifest = workspace_root().join("tests/fixtures/hle-probe/Cargo.toml"); + let target = Path::new(env!("CARGO_TARGET_TMPDIR")).join("hle-probe"); + let status = Command::new(env!("CARGO")) + .args(["build", "--quiet", "--manifest-path"]) + .arg(&manifest) + .arg("--target-dir") + .arg(&target) + .status() + .expect("running cargo"); + assert!(status.success(), "building hle-probe failed"); + target.join("debug").join("hle_probe.dll") +} + +extern "system" fn fake_xgameruntime_initialize() -> i32 { + 0x1234 +} +/// Asks for the current thread, as our logging does: on a thread std is +/// still starting, that must not abort the process. +extern "system" fn fake_get_tick_count() -> u32 { + let _ = std::thread::current().id(); + 777 +} +extern "system" fn fake_delayed() -> u32 { + 4242 +} + +struct TestResolver; + +impl ImportResolver for TestResolver { + fn resolve(&self, dll: &str, symbol: &ImportSymbol) -> Resolution { + let dll = dll.to_ascii_lowercase(); + let ImportSymbol::Name { name, .. } = symbol else { + return Resolution::Missing; + }; + let hle = match (dll.as_str(), name.as_str()) { + ("xgameruntime.dll", "XGameRuntimeInitialize") => { + Some(fake_xgameruntime_initialize as *const () as usize) + } + ("kernel32.dll", "GetTickCount") => Some(fake_get_tick_count as *const () as usize), + ("leonida-probe-delayed.dll", "LeonidaProbeDelayed") => { + Some(fake_delayed as *const () as usize) + } + _ => None, + }; + if let Some(address) = hle { + return Resolution::Found { + address, + provenance: Provenance::Hle, + }; + } + host(&dll, name) + .map(|address| Resolution::Found { + address, + provenance: Provenance::Host, + }) + .unwrap_or(Resolution::Missing) + } +} + +fn host(dll: &str, name: &str) -> Option { + let dll = CString::new(dll).ok()?; + let name = CString::new(name).ok()?; + // SAFETY: NUL-terminated strings; loading system DLLs into the test process. + unsafe { + let module = LoadLibraryA(dll.as_ptr().cast()); + if module.is_null() { + return None; + } + GetProcAddress(module, name.as_ptr().cast()).map(|f| f as *const () as usize) + } +} + +#[test] +fn loads_binds_and_calls_probe() { + let dll = build_probe(); + let original = std::fs::read(&dll).unwrap(); + let prepared = prepare(&original).unwrap(); + + let imports: Vec<_> = prepared + .info + .imports + .iter() + .map(|m| m.dll.to_ascii_lowercase()) + .collect(); + assert!( + imports.contains(&"xgameruntime.dll".to_owned()), + "{imports:?}" + ); + assert!( + imports.contains(&"leonida-probe-missing.dll".to_owned()), + "{imports:?}" + ); + assert!( + prepared + .info + .delay_imports + .iter() + .any(|m| m.dll.eq_ignore_ascii_case("leonida-probe-delayed.dll")), + "fixture must delay-load leonida-probe-delayed.dll" + ); + + let dir = tempfile::tempdir().unwrap(); + let image = leonida_loader::load(&prepared, dir.path()).unwrap(); + + // The "title" ships leonida-probe-title.dll: any real DLL will do. + let title_dir = tempfile::tempdir().unwrap(); + std::fs::copy( + r"C:\Windows\System32\version.dll", + title_dir.path().join("leonida-probe-title.dll"), + ) + .unwrap(); + let dlls = + leonida_loader::load_title_dlls(image.info(), title_dir.path(), dir.path(), &|_| true) + .unwrap(); + let names: Vec<_> = dlls.iter().map(|(n, _)| n.as_str()).collect(); + assert_eq!(names, ["leonida-probe-title.dll"]); + let resolver = WithTitleDlls { + inner: &TestResolver, + dlls: &dlls, + }; + for (_, dll) in &dlls { + dll.bind_imports(&resolver, UnimplementedPolicy::ReturnZero) + .unwrap(); + // SAFETY: its imports are bound, and it depends on no other title DLL. + unsafe { dll.attach() }.unwrap(); + } + let report = image + .bind_imports(&resolver, UnimplementedPolicy::ReturnZero) + .unwrap(); + assert_eq!(report.title, 1); + + assert_eq!(report.hle, 3); + assert!(report.host > 0); + assert_eq!(report.missing.len(), 1); + assert_eq!(report.missing[0].symbol, "LeonidaProbeNotImplemented"); + + let call = |name: &str| -> usize { image.export(name).unwrap_or_else(|| panic!("{name}")) }; + // SAFETY: the exports have the signatures declared in the fixture and + // every import they use has been bound. + unsafe { + let f: extern "system" fn() -> i32 = std::mem::transmute(call("probe_xgameruntime_init")); + assert_eq!(f(), 0x1234, "console API must reach our implementation"); + + let f: extern "system" fn() -> u32 = std::mem::transmute(call("probe_tick")); + assert_eq!(f(), 777, "host API must be overridable"); + + let f: extern "system" fn() -> u32 = std::mem::transmute(call("probe_pid")); + assert_eq!(f(), std::process::id(), "host API must pass through"); + + let f: extern "system" fn() -> u32 = std::mem::transmute(call("probe_title")); + assert_ne!(f(), 0, "title DLL export must be bound"); + + let f: extern "system" fn() -> u32 = std::mem::transmute(call("probe_delayed")); + assert_eq!(f(), 4242, "delay-loaded API must be bound"); + + let before = unimplemented_call_count(); + let f: extern "system" fn() -> u64 = std::mem::transmute(call("probe_missing")); + assert_eq!(f(), 0); + assert_eq!(unimplemented_call_count(), before + 1); + + // Once attached, every thread start reaches its TLS callback and + // DllMain (other tests may start threads too, hence at least one). + assert!( + image + .info() + .tls + .as_ref() + .is_some_and(|t| !t.callback_rvas.is_empty()) + ); + image.attach().unwrap(); + let f: extern "system" fn() -> u64 = std::mem::transmute(call("probe_thread_starts")); + let before = f(); + // A thread std starts, as our runtime's workers are: notified + // before std sets it up, which must still find its state pristine. + let worker = std::thread::Builder::new() + .name("probe-worker".into()) + .spawn(|| std::thread::current().name().map(str::to_owned)) + .unwrap(); + assert_eq!(worker.join().unwrap().as_deref(), Some("probe-worker")); + let mid = f(); + assert!(mid >> 32 > before >> 32 && mid as u32 > before as u32); + let before = mid; + // Starting in title code, as a title's threads do; the extra + // argument is ignored. + let start: unsafe extern "system" fn(*mut std::ffi::c_void) -> u32 = + std::mem::transmute(call("probe_pid")); + let thread = CreateThread( + std::ptr::null(), + 0, + Some(start), + std::ptr::null(), + 0, + std::ptr::null_mut(), + ); + assert!(!thread.is_null()); + WaitForSingleObject(thread, INFINITE); + CloseHandle(thread); + let after = f(); + assert!( + after >> 32 > before >> 32, + "TLS callback: {before:#x} → {after:#x}" + ); + assert!( + after as u32 > before as u32, + "DllMain: {before:#x} → {after:#x}" + ); + // It has static TLS, so Windows would refuse too. + assert_eq!( + leonida_loader::disable_thread_calls(image.base()), + Some(false) + ); + assert_eq!(leonida_loader::disable_thread_calls(1), None); + + // `FreeLibrary`'s notice, as a failed late load sends it. + let f: extern "system" fn() -> u32 = std::mem::transmute(call("probe_detaches")); + assert_eq!(f(), 0); + image.detach(); + assert_eq!(f(), 1); + image.unload(); + } +} + +#[test] +fn maps_a_title_dll_the_title_loads_itself() { + let title_dir = tempfile::tempdir().unwrap(); + let cache = tempfile::tempdir().unwrap(); + // Any real DLL will do; it imports only host DLLs, which are not in the folder. + std::fs::copy( + r"C:\Windows\System32\version.dll", + title_dir.path().join("Late.dll"), + ) + .unwrap(); + let load = |name: &str, wanted: &dyn Fn(&str) -> bool| { + leonida_loader::load_title_dll(name, title_dir.path(), cache.path(), wanted).unwrap() + }; + let dlls = load("LATE.DLL", &|_| true); + let names: Vec<_> = dlls.iter().map(|(n, _)| n.as_str()).collect(); + assert_eq!(names, ["late.dll"]); + assert!(dlls[0].1.export("GetFileVersionInfoW").is_some()); + assert!(load("absent.dll", &|_| true).is_empty()); + assert!(load("late.dll", &|_| false).is_empty()); +} diff --git a/crates/leonida-loader/tests/title_dlls.rs b/crates/leonida-loader/tests/title_dlls.rs new file mode 100644 index 000000000..787a848a7 --- /dev/null +++ b/crates/leonida-loader/tests/title_dlls.rs @@ -0,0 +1,16 @@ +//! A title DLL that cannot be loaded is named in the error. +#![cfg(windows)] + +#[test] +fn a_title_dll_that_does_not_prepare_is_named() { + let title = tempfile::tempdir().unwrap(); + let cache = tempfile::tempdir().unwrap(); + std::fs::write(title.path().join("broken.dll"), b"MZ not a PE").unwrap(); + let wanted = |_: &str| true; + let loaded = leonida_loader::load_title_dll("broken.dll", title.path(), cache.path(), &wanted); + let Err(error) = loaded else { + panic!("a DLL that is not a PE loaded"); + }; + let text = format!("{error:#}"); + assert!(text.contains("broken.dll"), "{text}"); +} diff --git a/crates/leonida-pe/Cargo.toml b/crates/leonida-pe/Cargo.toml new file mode 100644 index 000000000..7bd285eb9 --- /dev/null +++ b/crates/leonida-pe/Cargo.toml @@ -0,0 +1,15 @@ +[package] +name = "leonida-pe" +description = "Read-only analysis of PE32+ images and COFF import libraries." +version.workspace = true +edition.workspace = true +rust-version.workspace = true +license.workspace = true +publish.workspace = true + +[dependencies] +object.workspace = true +thiserror.workspace = true + +[lints] +workspace = true diff --git a/crates/leonida-pe/src/image.rs b/crates/leonida-pe/src/image.rs new file mode 100644 index 000000000..fc8f0f658 --- /dev/null +++ b/crates/leonida-pe/src/image.rs @@ -0,0 +1,547 @@ +use object::LittleEndian as LE; +use object::Object; +use object::pe::{self, ImageNtHeaders64}; +use object::read::pe::{ + ExportTarget, ImageNtHeaders, ImageOptionalHeader, Import, ImportTable, ImportThunkList, + PeFile64, +}; + +use crate::layout::{self, dir}; +use crate::{MACHINE_AMD64, PeError}; + +/// Everything we need to know about a PE32+ image, extracted in one pass. +#[derive(Debug, Clone)] +pub struct ImageInfo { + pub machine: u16, + /// `IMAGE_FILE_HEADER::Characteristics`. + pub characteristics: u16, + pub timestamp: u32, + pub subsystem: u16, + /// `IMAGE_OPTIONAL_HEADER64::DllCharacteristics`. + pub dll_characteristics: u16, + pub image_base: u64, + pub size_of_image: u32, + pub entry_rva: u32, + pub stack_reserve: u64, + pub stack_commit: u64, + pub sections: Vec, + pub imports: Vec, + pub delay_imports: Vec, + pub exports: Vec, + pub tls: Option, + pub has_relocations: bool, + pub has_exception_table: bool, + pub has_load_config: bool, + pub codeview: Option, +} + +#[derive(Debug, Clone)] +pub struct SectionInfo { + pub name: String, + pub rva: u32, + pub virtual_size: u32, + pub file_offset: u32, + pub file_size: u32, + pub characteristics: u32, +} + +/// One imported DLL and the functions taken from it. +#[derive(Debug, Clone)] +pub struct ImportModule { + /// DLL name exactly as written in the image (case preserved). + pub dll: String, + pub entries: Vec, +} + +#[derive(Debug, Clone)] +pub struct ImportEntry { + pub symbol: ImportSymbol, + /// RVA of the 8-byte IAT slot the loader must fill in. + pub iat_slot_rva: u32, +} + +#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)] +pub enum ImportSymbol { + Name { hint: u16, name: String }, + Ordinal(u16), +} + +impl std::fmt::Display for ImportSymbol { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + ImportSymbol::Name { name, .. } => f.write_str(name), + ImportSymbol::Ordinal(o) => write!(f, "#{o}"), + } + } +} + +#[derive(Debug, Clone)] +pub struct ExportInfo { + pub name: Option, + pub ordinal: u16, + /// `None` for forwarded exports. + pub rva: Option, + /// `"dll.name"` or `"dll.#ordinal"` for forwarded exports. + pub forward: Option, +} + +#[derive(Debug, Clone)] +pub struct TlsInfo { + /// RVA of `IMAGE_TLS_DIRECTORY64`. + pub directory_rva: u32, + /// VA (at the preferred base) of the callback array, 0 if none. + pub callbacks_va: u64, + /// Callback RVAs, in call order. + pub callback_rvas: Vec, +} + +/// CodeView (RSDS) record: identifies the exact build that produced an image. +#[derive(Debug, Clone)] +pub struct CodeViewInfo { + pub pdb_path: String, + pub guid: [u8; 16], + pub age: u32, +} + +impl CodeViewInfo { + /// The key symbol servers use: GUID (Windows byte order) + age. + pub fn symbol_key(&self) -> String { + let g = &self.guid; + let d1 = u32::from_le_bytes([g[0], g[1], g[2], g[3]]); + let d2 = u16::from_le_bytes([g[4], g[5]]); + let d3 = u16::from_le_bytes([g[6], g[7]]); + let mut s = format!("{d1:08X}{d2:04X}{d3:04X}"); + for b in &g[8..] { + s.push_str(&format!("{b:02X}")); + } + s.push_str(&format!("{:X}", self.age)); + s + } +} + +/// Upper bound on TLS callbacks we are willing to walk (defends against garbage). +const MAX_TLS_CALLBACKS: usize = 1024; + +impl ImageInfo { + /// Parses a complete PE32+ x86-64 image from its file bytes. + pub fn parse(data: &[u8]) -> Result { + let kind = object::FileKind::parse(data)?; + if kind != object::FileKind::Pe64 { + return Err(PeError::Unsupported(format!( + "expected PE32+, found {kind:?}" + ))); + } + let file = PeFile64::parse(data)?; + let nt = file.nt_headers(); + let fh = nt.file_header(); + let opt = nt.optional_header(); + + let machine = fh.machine.get(LE).0; + if machine != MACHINE_AMD64 { + return Err(PeError::Unsupported(format!( + "machine 0x{machine:04x} is not AMD64" + ))); + } + + let sections = file + .section_table() + .iter() + .map(|s| SectionInfo { + name: String::from_utf8_lossy(s.raw_name()).into_owned(), + rva: s.virtual_address.get(LE), + virtual_size: s.virtual_size.get(LE), + file_offset: s.pointer_to_raw_data.get(LE), + file_size: s.size_of_raw_data.get(LE), + characteristics: s.characteristics.get(LE).0, + }) + .collect(); + + let dir_present = |index: usize| { + file.data_directory(index) + .is_some_and(|d| d.virtual_address.get(LE) != 0 && d.size.get(LE) != 0) + }; + + let imports = match file.import_table()? { + Some(table) => parse_imports(&table, opt.size_of_image())?, + None => Vec::new(), + }; + let delay_imports = parse_delay_imports(&file, opt.size_of_image())?; + let exports = parse_exports(&file)?; + let tls = parse_tls(&file, data, opt.image_base())?; + let codeview = file.pdb_info()?.map(|cv| CodeViewInfo { + pdb_path: String::from_utf8_lossy(cv.path()).into_owned(), + guid: cv.guid(), + age: cv.age(), + }); + + Ok(ImageInfo { + machine, + characteristics: fh.characteristics.get(LE).0, + timestamp: fh.time_date_stamp.get(LE), + subsystem: opt.subsystem().0, + dll_characteristics: opt.dll_characteristics().0, + image_base: opt.image_base(), + size_of_image: opt.size_of_image(), + entry_rva: opt.address_of_entry_point(), + stack_reserve: opt.size_of_stack_reserve(), + stack_commit: opt.size_of_stack_commit(), + sections, + imports, + delay_imports, + exports, + tls, + has_relocations: dir_present(dir::BASERELOC) + && !has_flag( + fh.characteristics.get(LE).0, + layout::file_flags::RELOCS_STRIPPED, + ), + has_exception_table: dir_present(dir::EXCEPTION), + has_load_config: dir_present(dir::LOAD_CONFIG), + codeview, + }) + } + + pub fn is_dll(&self) -> bool { + has_flag(self.characteristics, layout::file_flags::DLL) + } + + /// Maps an RVA to an offset in the file, if it is backed by file data. + pub fn rva_to_file_offset(&self, rva: u32) -> Option { + self.sections.iter().find_map(|s| { + let delta = rva.checked_sub(s.rva)?; + // Raw data may be padded past the virtual size; that padding is + // not part of the section in memory. + let backed = match s.virtual_size { + 0 => s.file_size, + vs => vs.min(s.file_size), + }; + // Header values are untrusted: an offset near 4 GiB overflows. + (delta < backed).then(|| s.file_offset.checked_add(delta))? + }) + } + + pub fn import_count(&self) -> usize { + self.imports.iter().map(|m| m.entries.len()).sum() + } + + pub fn subsystem_name(&self) -> &'static str { + use layout::subsystem::*; + match self.subsystem { + WINDOWS_GUI => "windows-gui", + WINDOWS_CUI => "windows-cui", + XBOX => "xbox", + XBOX_CODE_CATALOG => "xbox-code-catalog", + _ => "other", + } + } +} + +fn has_flag(value: u16, flag: u16) -> bool { + value & flag != 0 +} + +fn utf8(bytes: &[u8]) -> String { + String::from_utf8_lossy(bytes).into_owned() +} + +fn convert_import(import: Import<'_>) -> ImportSymbol { + match import { + Import::Ordinal(o) => ImportSymbol::Ordinal(o), + Import::Name(hint, name) => ImportSymbol::Name { + hint, + name: utf8(name), + }, + } +} + +fn parse_imports( + table: &ImportTable<'_>, + size_of_image: u32, +) -> Result, PeError> { + let mut modules = Vec::new(); + let mut descriptors = table.descriptors()?; + while let Some(desc) = descriptors.next()? { + let iat_rva = desc.first_thunk.get(LE); + // Prefer the unbound name table; fall back to the IAT for old linkers. + let int_rva = match desc.original_first_thunk.get(LE) { + 0 => iat_rva, + rva => rva, + }; + modules.push(ImportModule { + dll: utf8(table.name(desc.name.get(LE))?), + entries: entries(table.thunks(int_rva)?, iat_rva, size_of_image, |t| { + table.import::(t) + })?, + }); + } + Ok(modules) +} + +fn parse_delay_imports( + file: &PeFile64<'_>, + size_of_image: u32, +) -> Result, PeError> { + let Some(table) = file.delay_load_import_table()? else { + return Ok(Vec::new()); + }; + let mut modules = Vec::new(); + let mut descriptors = table.descriptors()?; + while let Some(desc) = descriptors.next()? { + modules.push(ImportModule { + dll: utf8(table.name(desc.dll_name_rva.get(LE))?), + entries: entries( + table.thunks(desc.import_name_table_rva.get(LE))?, + desc.import_address_table_rva.get(LE), + size_of_image, + |t| table.import::(t), + )?, + }); + } + Ok(modules) +} + +/// Pairs each name-table entry with its IAT slot. The IAT RVA is not checked +/// by `object`, so every slot is checked to lie inside the image here. +fn entries<'data>( + mut thunks: ImportThunkList<'data>, + iat_rva: u32, + size_of_image: u32, + import: impl Fn(pe::ImageThunkData64) -> object::read::Result>, +) -> Result, PeError> { + let mut entries = Vec::new(); + while let Some(thunk) = thunks.next::()? { + let iat_slot_rva = u32::try_from(entries.len() * 8) + .ok() + .and_then(|offset| iat_rva.checked_add(offset)) + .filter(|&rva| rva.checked_add(8).is_some_and(|end| end <= size_of_image)) + .ok_or_else(|| { + PeError::Malformed(format!("IAT at {iat_rva:#x} runs outside the image")) + })?; + entries.push(ImportEntry { + symbol: convert_import(import(thunk)?), + iat_slot_rva, + }); + } + Ok(entries) +} + +fn parse_exports(file: &PeFile64<'_>) -> Result, PeError> { + let Some(table) = file.export_table()? else { + return Ok(Vec::new()); + }; + Ok(table + .exports()? + .into_iter() + // An address of 0 marks an unused slot in the address table (a gap + // in the ordinals), not an export at the image base. + .filter(|e| !matches!(e.target, ExportTarget::Address(0))) + .map(|e| { + let (rva, forward) = match e.target { + ExportTarget::Address(rva) => (Some(rva), None), + ExportTarget::ForwardByName(d, n) => { + (None, Some(format!("{}.{}", utf8(d), utf8(n)))) + } + ExportTarget::ForwardByOrdinal(d, o) => { + (None, Some(format!("{}.#{}", utf8(d), o.0))) + } + }; + ExportInfo { + name: e.name.map(utf8), + ordinal: e.ordinal.0, + rva, + forward, + } + }) + .collect()) +} + +fn parse_tls( + file: &PeFile64<'_>, + data: &[u8], + image_base: u64, +) -> Result, PeError> { + let Some(dd) = file.data_directory(pe::IMAGE_DIRECTORY_ENTRY_TLS) else { + return Ok(None); + }; + let directory_rva = dd.virtual_address.get(LE); + if directory_rva == 0 { + return Ok(None); + } + let sections = file.section_table(); + let tls = sections + .pe_data_at(data, directory_rva) + .ok_or_else(|| PeError::Malformed("TLS directory outside of sections".into()))?; + let callbacks_va = layout::read_u64(tls, layout::TLS64_ADDRESS_OF_CALLBACKS) + .ok_or_else(|| PeError::Malformed("truncated TLS directory".into()))?; + + let mut callback_rvas = Vec::new(); + if callbacks_va != 0 { + let array_rva = va_to_rva(callbacks_va, image_base)?; + let array = sections + .pe_data_at(data, array_rva) + .ok_or_else(|| PeError::Malformed("TLS callback array outside of sections".into()))?; + for slot in array.as_chunks::<8>().0.iter().take(MAX_TLS_CALLBACKS) { + let va = u64::from_le_bytes(*slot); + if va == 0 { + break; + } + callback_rvas.push(va_to_rva(va, image_base)?); + } + } + Ok(Some(TlsInfo { + directory_rva, + callbacks_va, + callback_rvas, + })) +} + +fn va_to_rva(va: u64, image_base: u64) -> Result { + va.checked_sub(image_base) + .and_then(|rva| u32::try_from(rva).ok()) + .ok_or_else(|| PeError::Malformed(format!("VA 0x{va:x} is outside the image"))) +} + +#[cfg(test)] +mod tests { + use super::*; + + /// The test binary itself is a real MSVC-linked PE32+ image. + fn own_image() -> Vec { + std::fs::read(std::env::current_exe().unwrap()).unwrap() + } + + #[test] + fn parses_own_test_binary() { + let info = ImageInfo::parse(&own_image()).unwrap(); + assert_eq!(info.machine, MACHINE_AMD64); + assert!(!info.is_dll()); + assert!(info.entry_rva != 0); + assert!(info.has_exception_table, "x64 images always carry .pdata"); + assert!(info.sections.iter().any(|s| s.name.starts_with(".text"))); + let kernel32 = info + .imports + .iter() + .find(|m| m.dll.eq_ignore_ascii_case("kernel32.dll")) + .expect("Rust std imports kernel32"); + assert!(kernel32.entries.iter().all(|e| e.iat_slot_rva != 0)); + // Rust std uses static TLS, so a TLS directory must be present (its + // callback array may legitimately be empty). + assert!(info.tls.is_some()); + } + + #[test] + fn rva_to_file_offset_maps_entry_point() { + let data = own_image(); + let info = ImageInfo::parse(&data).unwrap(); + let off = info.rva_to_file_offset(info.entry_rva).unwrap() as usize; + assert!(off < data.len()); + } + + #[test] + fn rva_to_file_offset_rejects_offsets_past_4_gib() { + let mut info = ImageInfo::parse(&own_image()).unwrap(); + let rva = info.sections[0].rva + 0x20; + assert!(info.rva_to_file_offset(rva).is_some()); + // Used to overflow (a panic in debug builds, a wrong offset in + // release ones). + info.sections[0].file_offset = u32::MAX - 0x10; + assert_eq!(info.rva_to_file_offset(rva), None); + } + + #[test] + fn rejects_garbage_without_panicking() { + assert!(ImageInfo::parse(b"").is_err()); + assert!(ImageInfo::parse(b"MZ not really").is_err()); + let mut truncated = own_image(); + truncated.truncate(0x200); + assert!(ImageInfo::parse(&truncated).is_err()); + } + + #[test] + fn rejects_iat_outside_image() { + let mut data = own_image(); + let dd = layout::data_directory_offset(&data, dir::IMPORT).unwrap(); + let import_rva = layout::read_u32(&data, dd).unwrap(); + let desc = ImageInfo::parse(&data) + .unwrap() + .rva_to_file_offset(import_rva) + .unwrap() as usize; + // First descriptor's FirstThunk, at the 4 GiB limit: used to overflow. + data[desc + 16..desc + 20].copy_from_slice(&0xFFFF_FFF8u32.to_le_bytes()); + assert!(matches!( + ImageInfo::parse(&data), + Err(PeError::Malformed(_)) + )); + } + /// A minimal PE32+ image: one section at RVA 0x1000 holding `body`, with + /// the export directory (RVA 0x1000, 0x80 bytes) pointing at it. + fn synthetic_image(body: &[u8]) -> Vec { + let mut d = vec![0u8; 0x200]; + d[0..2].copy_from_slice(b"MZ"); + d[0x3C..0x40].copy_from_slice(&0x40u32.to_le_bytes()); + d[0x40..0x44].copy_from_slice(b"PE\0\0"); + d[0x44..0x46].copy_from_slice(&MACHINE_AMD64.to_le_bytes()); + d[0x46..0x48].copy_from_slice(&1u16.to_le_bytes()); // sections + d[0x54..0x56].copy_from_slice(&240u16.to_le_bytes()); // optional header size + d[0x56..0x58].copy_from_slice(&0x2022u16.to_le_bytes()); // DLL, large address aware + let opt = 0x58; + d[opt..opt + 2].copy_from_slice(&0x20Bu16.to_le_bytes()); + d[opt + 24..opt + 32].copy_from_slice(&0x1_8000_0000u64.to_le_bytes()); + d[opt + 32..opt + 36].copy_from_slice(&0x1000u32.to_le_bytes()); + d[opt + 36..opt + 40].copy_from_slice(&0x200u32.to_le_bytes()); + d[opt + 56..opt + 60].copy_from_slice(&0x2000u32.to_le_bytes()); + d[opt + 60..opt + 64].copy_from_slice(&0x200u32.to_le_bytes()); + d[opt + 108..opt + 112].copy_from_slice(&16u32.to_le_bytes()); + d[opt + 112..opt + 116].copy_from_slice(&0x1000u32.to_le_bytes()); + d[opt + 116..opt + 120].copy_from_slice(&0x80u32.to_le_bytes()); + let sec = opt + 240; + d[sec..sec + 6].copy_from_slice(b".edata"); + d[sec + 8..sec + 12].copy_from_slice(&0x200u32.to_le_bytes()); // virtual size + d[sec + 12..sec + 16].copy_from_slice(&0x1000u32.to_le_bytes()); + d[sec + 16..sec + 20].copy_from_slice(&0x200u32.to_le_bytes()); // raw size + d[sec + 20..sec + 24].copy_from_slice(&0x200u32.to_le_bytes()); // raw offset + d.extend_from_slice(body); + d.resize(0x400, 0); + d + } + + #[test] + fn unused_export_slots_are_not_exports() { + // Ordinal base 1; three address slots: "alpha", an unused hole (0), + // and "gamma". The Windows loader treats address 0 as "not exported". + let mut body = vec![0u8; 0x100]; + let put32 = + |b: &mut Vec, at: usize, v: u32| b[at..at + 4].copy_from_slice(&v.to_le_bytes()); + put32(&mut body, 12, 0x1040); // name of the DLL + put32(&mut body, 16, 1); // ordinal base + put32(&mut body, 20, 3); // number of functions + put32(&mut body, 24, 2); // number of names + put32(&mut body, 28, 0x1028); // address table + put32(&mut body, 32, 0x1034); // name pointer table + put32(&mut body, 36, 0x103C); // name ordinal table + put32(&mut body, 0x28, 0x1200); + put32(&mut body, 0x2C, 0); + put32(&mut body, 0x30, 0x1204); + put32(&mut body, 0x34, 0x1044); + put32(&mut body, 0x38, 0x104A); + body[0x3C..0x3E].copy_from_slice(&0u16.to_le_bytes()); + body[0x3E..0x40].copy_from_slice(&2u16.to_le_bytes()); + body[0x40..0x44].copy_from_slice(b"t.dl"); + body[0x44..0x4A].copy_from_slice(b"alpha\0"); + body[0x4A..0x50].copy_from_slice(b"gamma\0"); + + let info = ImageInfo::parse(&synthetic_image(&body)).unwrap(); + let exports: Vec<_> = info + .exports + .iter() + .map(|e| (e.name.as_deref(), e.ordinal, e.rva)) + .collect(); + assert_eq!( + exports, + [ + (Some("alpha"), 1, Some(0x1200)), + (Some("gamma"), 3, Some(0x1204)) + ] + ); + } +} diff --git a/crates/leonida-pe/src/implib.rs b/crates/leonida-pe/src/implib.rs new file mode 100644 index 000000000..234c1ecf0 --- /dev/null +++ b/crates/leonida-pe/src/implib.rs @@ -0,0 +1,66 @@ +//! COFF import libraries (`.lib`). +//! +//! An umbrella import library tells us which DLL provides each API that a +//! console title may link against. That is the map the runtime needs to +//! decide which of our implementations answers which import. + +use object::read::archive::ArchiveFile; +use object::read::coff::{ImportFile, ImportName, ImportType}; + +use crate::{ImportSymbol, PeError}; + +/// One `dll!export` pair described by an import library. +#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)] +pub struct LibImport { + pub dll: String, + pub export: ImportSymbol, + pub kind: LibImportKind, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)] +pub enum LibImportKind { + Code, + Data, + Const, +} + +/// Result of reading an import library. +#[derive(Debug, Default)] +pub struct ImportLibrary { + pub imports: Vec, + /// Members that are not short-format import objects (regular objects, + /// long-format import descriptors). Reported so nothing is silently lost. + pub other_members: usize, +} + +impl ImportLibrary { + pub fn parse(data: &[u8]) -> Result { + let archive = ArchiveFile::parse(data)?; + let mut lib = ImportLibrary::default(); + for member in archive.members() { + let member = member?; + let bytes = member.data(data)?; + match ImportFile::parse(bytes) { + Ok(import) => lib.imports.push(LibImport { + dll: String::from_utf8_lossy(import.dll()).into_owned(), + export: match import.import() { + ImportName::Name(name) => ImportSymbol::Name { + hint: 0, + name: String::from_utf8_lossy(name).into_owned(), + }, + ImportName::Ordinal(o) => ImportSymbol::Ordinal(o), + }, + kind: match import.import_type() { + ImportType::Code => LibImportKind::Code, + ImportType::Data => LibImportKind::Data, + ImportType::Const => LibImportKind::Const, + }, + }), + Err(_) => lib.other_members += 1, + } + } + lib.imports.sort(); + lib.imports.dedup(); + Ok(lib) + } +} diff --git a/crates/leonida-pe/src/layout.rs b/crates/leonida-pe/src/layout.rs new file mode 100644 index 000000000..888f9d23f --- /dev/null +++ b/crates/leonida-pe/src/layout.rs @@ -0,0 +1,110 @@ +//! Raw byte offsets of PE32+ header fields, for code that patches images. +//! +//! All offsets are relative to the start of the structure named in the +//! constant's prefix. They follow the published PE/COFF specification. + +/// Offset of `e_lfanew` (u32) in the DOS header. +pub const DOS_E_LFANEW: usize = 0x3C; + +/// Size of the `PE\0\0` signature that precedes the file header. +pub const NT_SIGNATURE_SIZE: usize = 4; +/// Size of `IMAGE_FILE_HEADER`. +pub const FILE_HEADER_SIZE: usize = 20; + +/// `IMAGE_FILE_HEADER::Characteristics` (u16). +pub const FILE_HEADER_CHARACTERISTICS: usize = 18; + +/// `IMAGE_OPTIONAL_HEADER64::AddressOfEntryPoint` (u32). +pub const OPT_ADDRESS_OF_ENTRY_POINT: usize = 16; +/// `IMAGE_OPTIONAL_HEADER64::CheckSum` (u32). +pub const OPT_CHECKSUM: usize = 64; +/// `IMAGE_OPTIONAL_HEADER64::DllCharacteristics` (u16). +pub const OPT_DLL_CHARACTERISTICS: usize = 70; +/// `IMAGE_OPTIONAL_HEADER64::NumberOfRvaAndSizes` (u32). +pub const OPT_NUMBER_OF_RVA_AND_SIZES: usize = 108; +/// First `IMAGE_DATA_DIRECTORY` entry (each is `{ rva: u32, size: u32 }`). +pub const OPT_DATA_DIRECTORY: usize = 112; +/// Size of one `IMAGE_DATA_DIRECTORY`. +pub const DATA_DIRECTORY_SIZE: usize = 8; + +/// `IMAGE_TLS_DIRECTORY64::AddressOfCallBacks` (u64 VA). +pub const TLS64_ADDRESS_OF_CALLBACKS: usize = 24; + +/// Data directory indices. +pub mod dir { + pub const IMPORT: usize = 1; + pub const EXCEPTION: usize = 3; + pub const BASERELOC: usize = 5; + pub const LOAD_CONFIG: usize = 10; + pub const BOUND_IMPORT: usize = 11; + pub const IAT: usize = 12; +} + +/// `IMAGE_FILE_HEADER::Characteristics` flags. +pub mod file_flags { + pub const RELOCS_STRIPPED: u16 = 0x0001; + pub const DLL: u16 = 0x2000; +} + +/// `IMAGE_OPTIONAL_HEADER64::DllCharacteristics` flags. +pub mod dll_flags { + pub const HIGH_ENTROPY_VA: u16 = 0x0020; + pub const DYNAMIC_BASE: u16 = 0x0040; + pub const FORCE_INTEGRITY: u16 = 0x0080; + pub const NX_COMPAT: u16 = 0x0100; + pub const APPCONTAINER: u16 = 0x1000; + pub const GUARD_CF: u16 = 0x4000; +} + +/// `IMAGE_OPTIONAL_HEADER64::Subsystem` values. +pub mod subsystem { + pub const WINDOWS_GUI: u16 = 2; + pub const WINDOWS_CUI: u16 = 3; + pub const XBOX: u16 = 14; + pub const XBOX_CODE_CATALOG: u16 = 17; +} + +/// Offset of the optional header from the start of the file. +pub fn optional_header_offset(data: &[u8]) -> Option { + let lfanew = read_u32(data, DOS_E_LFANEW)? as usize; + lfanew.checked_add(NT_SIGNATURE_SIZE + FILE_HEADER_SIZE) +} + +/// Offset of the file header from the start of the file. +pub fn file_header_offset(data: &[u8]) -> Option { + let lfanew = read_u32(data, DOS_E_LFANEW)? as usize; + lfanew.checked_add(NT_SIGNATURE_SIZE) +} + +/// Offset of data directory `index` from the start of the file. +pub fn data_directory_offset(data: &[u8], index: usize) -> Option { + let opt = optional_header_offset(data)?; + let count = read_u32(data, opt.checked_add(OPT_NUMBER_OF_RVA_AND_SIZES)?)? as usize; + if index >= count { + return None; + } + opt.checked_add(OPT_DATA_DIRECTORY)? + .checked_add(index.checked_mul(DATA_DIRECTORY_SIZE)?) +} + +pub fn read_u32(data: &[u8], at: usize) -> Option { + let end = at.checked_add(4)?; + Some(u32::from_le_bytes(data.get(at..end)?.try_into().ok()?)) +} + +pub fn read_u64(data: &[u8], at: usize) -> Option { + let end = at.checked_add(8)?; + Some(u64::from_le_bytes(data.get(at..end)?.try_into().ok()?)) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn reads_reject_overflowing_offsets() { + let data = [0u8; 16]; + assert_eq!(read_u32(&data, usize::MAX - 1), None); + assert_eq!(read_u64(&data, usize::MAX - 2), None); + } +} diff --git a/crates/leonida-pe/src/lib.rs b/crates/leonida-pe/src/lib.rs new file mode 100644 index 000000000..78e7dc067 --- /dev/null +++ b/crates/leonida-pe/src/lib.rs @@ -0,0 +1,35 @@ +//! Read-only analysis of PE32+ (x86-64) images and COFF import libraries. +//! +//! Xbox Series X|S titles are ordinary x86-64 PE32+ images (the console CPU +//! is a Zen 2), so the same parser serves titles, console system DLLs and +//! host binaries alike. This crate never modifies anything; patching lives in +//! `leonida-loader`, which uses the raw offsets exported from [`layout`]. + +mod image; +pub mod implib; +pub mod layout; + +pub use image::{ + CodeViewInfo, ExportInfo, ImageInfo, ImportEntry, ImportModule, ImportSymbol, SectionInfo, + TlsInfo, +}; + +/// Errors produced while parsing an image or import library. +#[derive(Debug, thiserror::Error)] +pub enum PeError { + /// The file is a valid PE but not one we handle (e.g. 32-bit or ARM64). + #[error("unsupported image: {0}")] + Unsupported(String), + /// The file is truncated or internally inconsistent. + #[error("malformed image: {0}")] + Malformed(String), +} + +impl From for PeError { + fn from(e: object::read::Error) -> Self { + PeError::Malformed(e.to_string()) + } +} + +/// `IMAGE_FILE_MACHINE_AMD64`. +pub const MACHINE_AMD64: u16 = 0x8664; diff --git a/crates/leonida-pipeline/Cargo.toml b/crates/leonida-pipeline/Cargo.toml new file mode 100644 index 000000000..7fbc387a4 --- /dev/null +++ b/crates/leonida-pipeline/Cargo.toml @@ -0,0 +1,20 @@ +[package] +name = "leonida-pipeline" +description = "Offline conversion of user-supplied game data into host formats, with a content-addressed cache." +version.workspace = true +edition.workspace = true +rust-version.workspace = true +license.workspace = true +publish.workspace = true + +[dependencies] +leonida-core.workspace = true +anyhow.workspace = true +blake3.workspace = true +tracing.workspace = true + +[dev-dependencies] +tempfile.workspace = true + +[lints] +workspace = true diff --git a/crates/leonida-pipeline/src/cache.rs b/crates/leonida-pipeline/src/cache.rs new file mode 100644 index 000000000..039a8d577 --- /dev/null +++ b/crates/leonida-pipeline/src/cache.rs @@ -0,0 +1,159 @@ +use std::io::Write; +use std::path::{Path, PathBuf}; + +use anyhow::{Context, Result}; + +use crate::Converter; + +/// Identifies one conversion result. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub struct CacheKey(blake3::Hash); + +impl CacheKey { + pub fn new(converter: &dyn Converter, input: &[u8]) -> Self { + let mut h = blake3::Hasher::new(); + h.update(converter.id().as_bytes()); + h.update(&[0]); + h.update(&converter.version().to_le_bytes()); + h.update(input); + CacheKey(h.finalize()) + } + + pub fn to_hex(&self) -> String { + self.0.to_hex().to_string() + } +} + +/// Content-addressed store under the user's cache directory. +#[derive(Debug, Clone)] +pub struct Cache { + root: PathBuf, +} + +impl Cache { + /// Opens (creating) a cache at `root`. Refuses locations inside the repo. + pub fn open(root: impl Into) -> Result { + let root = root.into(); + leonida_core::ensure_outside_repo(&root)?; + std::fs::create_dir_all(&root).with_context(|| format!("creating {}", root.display()))?; + Ok(Cache { root }) + } + + pub fn path_for(&self, key: &CacheKey) -> PathBuf { + let hex = key.to_hex(); + self.root.join(&hex[..2]).join(&hex[2..]) + } + + /// Returns the cached output for `input`, converting it first if needed. + pub fn get_or_convert(&self, converter: &dyn Converter, input: &[u8]) -> Result { + let key = CacheKey::new(converter, input); + let path = self.path_for(&key); + if path.is_file() { + tracing::trace!(converter = converter.id(), key = %key.to_hex(), "cache hit"); + return Ok(path); + } + let output = converter + .convert(input) + .with_context(|| format!("converter {} v{}", converter.id(), converter.version()))?; + let dir = path.parent().expect("hashed path has a parent"); + std::fs::create_dir_all(dir)?; + // Write-then-rename so readers never see partial output. + let tmp = tempfile_in(dir); + let mut file = std::fs::OpenOptions::new() + .write(true) + .create_new(true) + .open(&tmp)?; + let written = file.write_all(&output); + drop(file); + let published = written.and_then(|()| std::fs::rename(&tmp, &path)); + if published.is_err() { + let _ = std::fs::remove_file(&tmp); + } + published?; + Ok(path) + } +} + +fn tempfile_in(dir: &Path) -> PathBuf { + use std::sync::atomic::{AtomicU64, Ordering}; + static COUNTER: AtomicU64 = AtomicU64::new(0); + let n = COUNTER.fetch_add(1, Ordering::Relaxed); + dir.join(format!(".tmp-{}-{n}", std::process::id())) +} + +#[cfg(test)] +mod tests { + use super::*; + use std::sync::atomic::{AtomicUsize, Ordering}; + + struct Upper { + version: u32, + runs: AtomicUsize, + } + + impl Converter for Upper { + fn id(&self) -> &'static str { + "test.upper" + } + fn version(&self) -> u32 { + self.version + } + fn convert(&self, input: &[u8]) -> Result> { + self.runs.fetch_add(1, Ordering::Relaxed); + Ok(input.to_ascii_uppercase()) + } + } + + #[test] + fn converts_once_then_hits() { + let tmp = tempfile::tempdir().unwrap(); + let cache = Cache::open(tmp.path().join("cache")).unwrap(); + let conv = Upper { + version: 1, + runs: AtomicUsize::new(0), + }; + let a = cache.get_or_convert(&conv, b"abc").unwrap(); + let b = cache.get_or_convert(&conv, b"abc").unwrap(); + assert_eq!(a, b); + assert_eq!(std::fs::read(&a).unwrap(), b"ABC"); + assert_eq!(conv.runs.load(Ordering::Relaxed), 1); + } + + #[test] + fn failed_publication_removes_the_staging_file() { + let tmp = tempfile::tempdir().unwrap(); + let cache = Cache::open(tmp.path().join("cache")).unwrap(); + let conv = Upper { + version: 1, + runs: AtomicUsize::new(0), + }; + let path = cache.path_for(&CacheKey::new(&conv, b"abc")); + std::fs::create_dir_all(&path).unwrap(); + + assert!(cache.get_or_convert(&conv, b"abc").is_err()); + assert!(path.is_dir()); + assert_eq!( + std::fs::read_dir(path.parent().unwrap()).unwrap().count(), + 1 + ); + } + + #[test] + fn version_bump_invalidates() { + let v1 = Upper { + version: 1, + runs: AtomicUsize::new(0), + }; + let v2 = Upper { + version: 2, + runs: AtomicUsize::new(0), + }; + assert_ne!(CacheKey::new(&v1, b"x"), CacheKey::new(&v2, b"x")); + } + + #[test] + fn refuses_cache_inside_repo() { + let inside = Path::new(env!("CARGO_MANIFEST_DIR")).join("cache"); + assert!(Cache::open(inside).is_err()); + } +} diff --git a/crates/leonida-pipeline/src/lib.rs b/crates/leonida-pipeline/src/lib.rs new file mode 100644 index 000000000..c417e5c1a --- /dev/null +++ b/crates/leonida-pipeline/src/lib.rs @@ -0,0 +1,23 @@ +//! Offline conversion of the user's game data into host formats. +//! +//! Everything here runs on the user's machine, reads the user's files and +//! writes into the user's cache. Nothing produced here is ever committed: +//! derived data is still game data (docs/asset-policy.md). +//! +//! The unit of work is a [`Converter`]: bytes in, bytes out, deterministic. +//! Results are stored in a content-addressed [`Cache`] keyed by converter +//! id, converter version and input bytes, so re-running the pipeline after +//! a game update or a converter fix only redoes what changed. + +mod cache; + +pub use cache::{Cache, CacheKey}; + +/// A deterministic transformation of one input into one output. +pub trait Converter: Send + Sync { + /// Stable identifier, e.g. `"texture.detile"`. Part of the cache key. + fn id(&self) -> &'static str; + /// Bump whenever the output for a given input changes. + fn version(&self) -> u32; + fn convert(&self, input: &[u8]) -> anyhow::Result>; +} diff --git a/crates/leonida-shader/Cargo.toml b/crates/leonida-shader/Cargo.toml new file mode 100644 index 000000000..50ae179d3 --- /dev/null +++ b/crates/leonida-shader/Cargo.toml @@ -0,0 +1,40 @@ +[package] +name = "leonida-shader" +description = "Xbox shader containers (DXBC/DXIL + precompiled GFX10) to host shaders." +version.workspace = true +edition.workspace = true +rust-version.workspace = true +license.workspace = true +publish.workspace = true + +[dependencies] +thiserror.workspace = true +zlib-rs.workspace = true + +[features] +# Host D3D12 pipeline checks (`emit::host`). +host = ["dep:windows"] +# Debugging switches (emitted-module dumps and the like). +diagnostics = [] + +[target.'cfg(windows)'.dependencies] +windows-sys = { workspace = true, features = ["Win32_System_LibraryLoader"] } +windows = { workspace = true, optional = true, features = [ + "Win32_Foundation", + "Win32_Graphics_Direct3D", + "Win32_Graphics_Direct3D12", + "Win32_Graphics_Dxgi", + "Win32_Graphics_Dxgi_Common", +] } + +[target.'cfg(windows)'.dev-dependencies] +windows = { workspace = true, features = [ + "Win32_Foundation", + "Win32_Graphics_Direct3D", + "Win32_Graphics_Direct3D12", + "Win32_Graphics_Dxgi", + "Win32_Graphics_Dxgi_Common", +] } + +[lints] +workspace = true diff --git a/crates/leonida-shader/build.rs b/crates/leonida-shader/build.rs new file mode 100644 index 000000000..cf99afc2e --- /dev/null +++ b/crates/leonida-shader/build.rs @@ -0,0 +1,65 @@ +//! Fingerprint of the translator's own source, for the shader cache key +//! (`leonida-gpu`'s `shader_cache`): a rebuilt executable whose translator did +//! not change keeps its cached translations. Also lists every `LEONIDA_*` +//! switch the translator reads, whose values join the key at run time. +//! Reads only this crate's `src` folder; writes nothing but cargo directives. + +use std::path::{Path, PathBuf}; + +fn files(dir: &Path, out: &mut Vec) { + let Ok(entries) = std::fs::read_dir(dir) else { + return; + }; + for e in entries.flatten() { + let p = e.path(); + if p.is_dir() { + files(&p, out); + } else if p.extension().is_some_and(|x| x == "rs") { + out.push(p); + } + } +} + +/// FNV-1a, 64 bits, two lanes with different offsets: a mismatch only costs +/// a cache miss, so this need not be cryptographic. +fn fnv(state: &mut [u64; 2], bytes: &[u8]) { + for &b in bytes { + for (i, s) in state.iter_mut().enumerate() { + *s ^= u64::from(b) ^ (i as u64 * 0x9e); + *s = s.wrapping_mul(0x0000_0100_0000_01b3); + } + } +} + +fn main() { + let src = Path::new(env!("CARGO_MANIFEST_DIR")).join("src"); + println!("cargo:rerun-if-changed=src"); + println!("cargo:rerun-if-changed=Cargo.toml"); + let mut list = Vec::new(); + files(&src, &mut list); + list.sort(); + let mut state = [0xcbf2_9ce4_8422_2325u64, 0x8422_2325_cbf2_9ce4u64]; + let mut switches = std::collections::BTreeSet::new(); + for p in &list { + let rel = p.strip_prefix(&src).unwrap_or(p).to_string_lossy().replace('\\', "/"); + let text = std::fs::read(p).unwrap_or_default(); + fnv(&mut state, rel.as_bytes()); + fnv(&mut state, &(text.len() as u64).to_le_bytes()); + fnv(&mut state, &text); + let s = String::from_utf8_lossy(&text); + let mut rest = &s[..]; + while let Some(at) = rest.find("\"LEONIDA_") { + let tail = &rest[at + 1..]; + let end = tail + .find(|c: char| !(c.is_ascii_uppercase() || c.is_ascii_digit() || c == '_')) + .unwrap_or(tail.len()); + if tail[end..].starts_with('"') { + switches.insert(tail[..end].to_string()); + } + rest = &tail[end..]; + } + } + println!("cargo:rustc-env=LEONIDA_SHADER_SOURCE_HASH={:016x}{:016x}", state[0], state[1]); + let joined: Vec<_> = switches.into_iter().collect(); + println!("cargo:rustc-env=LEONIDA_SHADER_SWITCHES={}", joined.join(",")); +} diff --git a/crates/leonida-shader/src/bvh.rs b/crates/leonida-shader/src/bvh.rs new file mode 100644 index 000000000..9f5400114 --- /dev/null +++ b/crates/leonida-shader/src/bvh.rs @@ -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 = 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}"); + } + } + } +} diff --git a/crates/leonida-shader/src/dxbc.rs b/crates/leonida-shader/src/dxbc.rs new file mode 100644 index 000000000..7a20963b6 --- /dev/null +++ b/crates/leonida-shader/src/dxbc.rs @@ -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>, +} + +const HEADER_SIZE: usize = 0x20; +const MAX_PARTS: usize = 256; + +impl<'a> Container<'a> { + pub fn parse(data: &'a [u8]) -> Result { + 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 { + 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 { + 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 { + 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 { + let table = HEADER_SIZE + 4 * parts.len(); + let total = table + parts.iter().map(|(_, d)| 8 + d.len()).sum::(); + 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()); + } +} diff --git a/crates/leonida-shader/src/dxil.rs b/crates/leonida-shader/src/dxil.rs new file mode 100644 index 000000000..8c7a71ce6 --- /dev/null +++ b/crates/leonida-shader/src/dxil.rs @@ -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 { + 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 { + 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 { + 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()); + } +} diff --git a/crates/leonida-shader/src/emit/bitcode.rs b/crates/leonida-shader/src/emit/bitcode.rs new file mode 100644 index 000000000..9702cb827 --- /dev/null +++ b/crates/leonida-shader/src/emit/bitcode.rs @@ -0,0 +1,1240 @@ +//! A DXIL module and its LLVM 3.7 bitcode, written with unabbreviated +//! records only (the format DXIL fixes; codes from LLVM's `LLVMBitCodes.h`). +//! +//! Values are symbolic while the module is built ([`V`]) and numbered when +//! it is written: functions, then constants (all at module level), then the +//! instructions of `main` in block order. + +use std::collections::HashMap; + +pub mod census; +pub mod opt; + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)] +pub(crate) struct Ty(u32); + +/// What the lowering made an instruction for, where it says so (counted by +/// [`census`], nothing else reads it). +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) enum Tag { + /// The select that keeps a register's old value in lanes a guard masks. + Guard, + /// An index clamp the translation adds (the console has none). + Clamp, + /// The iteration counter and limit test the translation adds to a loop. + Counter, +} + +#[derive(Debug, Clone, PartialEq, Eq, Hash)] +enum TypeDef { + Void, + Int(u32), + Float, + Double, + /// Pointee and address space. + Ptr(Ty, u32), + Struct(Option, Vec), + Array(u32, Ty), + Func(Ty, Vec), +} + +/// A value: a global variable, a function, a module constant, or an +/// instruction result. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)] +pub(crate) enum V { + Global(u32), + Func(u32), + Const(u32), + Inst(u32), +} + +/// A global variable declaration (thread-group shared memory). +struct Global { + name: String, + ty: Ty, + /// Its pointer type. + ptr: Ty, + space: u32, + /// An internal constant with this initialiser (a constant table). + init: Option, +} + +#[derive(Debug, Clone, PartialEq, Eq, Hash)] +enum Const { + Int(i64), + Float(u32), + Undef, + Aggregate(Vec), +} + +/// LLVM binary opcodes (the same codes serve the float forms). +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) enum Bin { + Add = 0, + Sub = 1, + Mul = 2, + UDiv = 3, + SDiv = 4, + URem = 5, + Shl = 7, + LShr = 8, + AShr = 9, + And = 10, + Or = 11, + Xor = 12, +} + +/// `atomicrmw` operations. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) enum Rmw { + Xchg = 0, + Add = 1, + Sub = 2, + And = 3, + Or = 5, + Xor = 6, + Max = 7, + Min = 8, + UMax = 9, + UMin = 10, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) enum Cast { + Trunc = 0, + ZExt = 1, + SExt = 2, + FpToUi = 3, + FpToSi = 4, + UiToFp = 5, + SiToFp = 6, + Bitcast = 11, +} + +/// Compare predicates: floats 0-15, integers 32-41. +pub(crate) mod pred { + pub const FALSE: u8 = 0; + pub const OEQ: u8 = 1; + pub const OGT: u8 = 2; + pub const OGE: u8 = 3; + pub const OLT: u8 = 4; + pub const OLE: u8 = 5; + // Not emitted: the AMD D3D12 driver treats it as UNE, so `v_cmp_lg` + // lowers as OLT | OGT instead. + #[allow(dead_code)] + pub const ONE: u8 = 6; + pub const ORD: u8 = 7; + pub const UNO: u8 = 8; + pub const UEQ: u8 = 9; + pub const UGT: u8 = 10; + pub const UGE: u8 = 11; + pub const ULT: u8 = 12; + pub const ULE: u8 = 13; + pub const UNE: u8 = 14; + pub const TRUE: u8 = 15; + pub const EQ: u8 = 32; + pub const NE: u8 = 33; + pub const IUGT: u8 = 34; + pub const IUGE: u8 = 35; + pub const IULT: u8 = 36; + pub const IULE: u8 = 37; + pub const SGT: u8 = 38; + pub const SGE: u8 = 39; + pub const SLT: u8 = 40; + pub const SLE: u8 = 41; +} + +#[derive(Debug, Clone)] +enum Op { + Bin(Bin, V, V), + Cast(Cast, V), + Cmp(u8, V, V), + Select(V, V, V), + Extract(V, u32), + Call(u32, Vec), + /// Filled in later: (value, block). + Phi(Vec<(V, usize)>), + /// `getelementptr` over the pointee type, from a pointer. + Gep(Ty, V, Vec), + Load(V), + /// Pointer, value. + Store(V, V), + AtomicRmw(Rmw, V, V), + /// Pointer, expected, new; returns `{i32, i1}`. + CmpXchg(V, V, V), +} + +#[derive(Debug, Clone)] +struct Inst { + ty: Ty, + op: Op, +} + +#[derive(Debug, Clone, Copy)] +pub(crate) enum Term { + Br(usize), + CondBr(V, usize, usize), + Ret, +} + +#[derive(Debug, Clone, Default)] +struct Block { + phis: Vec, + body: Vec, + term: Option, +} + +/// Function attributes of a `dx.op` declaration. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) enum Attr { + ReadNone = 1, + NoUnwind = 2, + ReadOnly = 3, + /// Barriers. + NoDuplicate = 4, +} + +struct Func { + name: String, + ty: Ty, + attr: Option, + body: bool, +} + +/// A metadata node operand. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) struct Md(u32); + +enum MdDef { + Str(String), + Value(Ty, V), + Node(Vec>), +} + +#[derive(Default)] +pub(crate) struct Module { + types: Vec, + type_ids: HashMap, + consts: Vec<(Ty, Const)>, + const_ids: HashMap<(Ty, Const), u32>, + globals: Vec, + funcs: Vec, + func_ids: HashMap, + insts: Vec, + blocks: Vec, + mds: Vec, + named: Vec<(String, Vec)>, + /// See [`Tag`]: by instruction. + tags: HashMap, +} + +impl Module { + fn ty(&mut self, def: TypeDef) -> Ty { + if let Some(&t) = self.type_ids.get(&def) { + return Ty(t); + } + let t = self.types.len() as u32; + self.types.push(def.clone()); + self.type_ids.insert(def, t); + Ty(t) + } + + pub fn void(&mut self) -> Ty { + self.ty(TypeDef::Void) + } + pub fn int(&mut self, bits: u32) -> Ty { + self.ty(TypeDef::Int(bits)) + } + pub fn float(&mut self) -> Ty { + self.ty(TypeDef::Float) + } + pub fn double(&mut self) -> Ty { + self.ty(TypeDef::Double) + } + pub fn ptr(&mut self, to: Ty) -> Ty { + self.ty(TypeDef::Ptr(to, 0)) + } + pub fn ptr_in(&mut self, to: Ty, space: u32) -> Ty { + self.ty(TypeDef::Ptr(to, space)) + } + pub fn array(&mut self, n: u32, of: Ty) -> Ty { + self.ty(TypeDef::Array(n, of)) + } + pub fn named_struct(&mut self, name: &str, fields: Vec) -> Ty { + self.ty(TypeDef::Struct(Some(name.into()), fields)) + } + pub fn func_ty(&mut self, ret: Ty, params: Vec) -> Ty { + self.ty(TypeDef::Func(ret, params)) + } + + fn is_void(&self, t: Ty) -> bool { + self.types[t.0 as usize] == TypeDef::Void + } + + fn constant(&mut self, ty: Ty, c: Const) -> V { + if let Some(&i) = self.const_ids.get(&(ty, c.clone())) { + return V::Const(i); + } + let i = self.consts.len() as u32; + self.consts.push((ty, c.clone())); + self.const_ids.insert((ty, c), i); + V::Const(i) + } + + pub fn int_const(&mut self, ty: Ty, v: i64) -> V { + self.constant(ty, Const::Int(v)) + } + pub fn i32(&mut self, v: u32) -> V { + let t = self.int(32); + self.int_const(t, i64::from(v as i32)) + } + pub fn i8(&mut self, v: u8) -> V { + let t = self.int(8); + self.int_const(t, i64::from(v as i8)) + } + pub fn bool(&mut self, v: bool) -> V { + let t = self.int(1); + self.int_const(t, -i64::from(v)) + } + pub fn f32(&mut self, bits: u32) -> V { + let t = self.float(); + self.constant(t, Const::Float(bits)) + } + pub fn undef(&mut self, ty: Ty) -> V { + self.constant(ty, Const::Undef) + } + /// A constant struct or array of constants. + pub fn aggregate(&mut self, ty: Ty, fields: &[V]) -> V { + let ids = fields + .iter() + .map(|f| match f { + V::Const(i) => *i, + _ => panic!("aggregate of a non-constant"), + }) + .collect(); + self.constant(ty, Const::Aggregate(ids)) + } + + /// The value of an integer constant; `None` for anything else. + pub fn int_value(&self, v: V) -> Option { + match v { + V::Const(i) => match self.consts[i as usize].1 { + Const::Int(x) => Some(x), + _ => None, + }, + _ => None, + } + } + + /// Gives constant `old` the content of `new` (both stay valid). + pub fn replace_const(&mut self, old: V, new: V) { + if let (V::Const(o), V::Const(n)) = (old, new) { + self.consts[o as usize] = self.consts[n as usize].clone(); + } + } + + /// A function declaration (or `main` with `body`), found by name. + pub fn function(&mut self, name: &str, ty: Ty, attr: Option, body: bool) -> V { + if let Some(&i) = self.func_ids.get(name) { + return V::Func(i); + } + let i = self.funcs.len() as u32; + self.funcs.push(Func { + name: name.into(), + ty, + attr, + body, + }); + self.func_ids.insert(name.into(), i); + V::Func(i) + } + + /// An external global of type `ty` in address space `space` (DXIL + /// declares thread-group shared memory this way). + pub fn global(&mut self, name: &str, ty: Ty, space: u32) -> V { + let ptr = self.ptr_in(ty, space); + self.globals.push(Global { + name: name.into(), + ty, + ptr, + space, + init: None, + }); + V::Global(self.globals.len() as u32 - 1) + } + + /// An internal constant global initialised with the constant `init`. + pub fn constant_global(&mut self, name: &str, init: V) -> V { + let V::Const(i) = init else { + panic!("a global initialised with a non-constant") + }; + let ty = self.consts[i as usize].0; + let g = self.global(name, ty, 0); + if let V::Global(n) = g { + self.globals[n as usize].init = Some(i); + } + g + } + + /// Notes what instruction `v` is for (see [`Tag`]); only when modules + /// are counted. + pub fn tag(&mut self, v: V, tag: Tag) { + if let V::Inst(i) = v + && census::enabled() + { + self.tags.insert(i, tag); + } + } + + pub fn new_block(&mut self) -> usize { + self.blocks.push(Block::default()); + self.blocks.len() - 1 + } + + pub fn type_of(&self, v: V) -> Ty { + match v { + V::Global(i) => self.globals[i as usize].ptr, + V::Const(i) => self.consts[i as usize].0, + V::Inst(i) => self.insts[i as usize].ty, + V::Func(i) => { + let t = self.funcs[i as usize].ty; + *self + .type_ids + .get(&TypeDef::Ptr(t, 0)) + .map(|t| Ty(*t)) + .as_ref() + .expect("function pointer type") + } + } + } + + fn push(&mut self, block: usize, ty: Ty, op: Op) -> V { + let i = self.insts.len() as u32; + self.insts.push(Inst { ty, op }); + // Terminators are kept apart, so a block can still grow at its end. + self.blocks[block].body.push(i); + V::Inst(i) + } + + pub fn bin(&mut self, block: usize, op: Bin, a: V, b: V) -> V { + let ty = self.type_of(a); + self.push(block, ty, Op::Bin(op, a, b)) + } + pub fn cast(&mut self, block: usize, op: Cast, v: V, to: Ty) -> V { + self.push(block, to, Op::Cast(op, v)) + } + pub fn cmp(&mut self, block: usize, pred: u8, a: V, b: V) -> V { + let t = self.int(1); + self.push(block, t, Op::Cmp(pred, a, b)) + } + pub fn select(&mut self, block: usize, c: V, t: V, f: V) -> V { + let ty = self.type_of(t); + self.push(block, ty, Op::Select(c, t, f)) + } + pub fn extract(&mut self, block: usize, agg: V, index: u32) -> V { + let ty = match &self.types[self.type_of(agg).0 as usize] { + TypeDef::Struct(_, f) => f[index as usize], + TypeDef::Array(_, t) => *t, + t => panic!("extractvalue from {t:?}"), + }; + self.push(block, ty, Op::Extract(agg, index)) + } + pub fn call(&mut self, block: usize, f: V, args: Vec) -> V { + let V::Func(i) = f else { + panic!("call of a non-function") + }; + let TypeDef::Func(ret, _) = self.types[self.funcs[i as usize].ty.0 as usize] else { + unreachable!() + }; + self.push(block, ret, Op::Call(i, args)) + } + /// A phi at the top of `block`; incoming values come with [`Module::set_phi`]. + pub fn phi(&mut self, block: usize, ty: Ty) -> V { + let i = self.insts.len() as u32; + self.insts.push(Inst { + ty, + op: Op::Phi(Vec::new()), + }); + self.blocks[block].phis.push(i); + V::Inst(i) + } + /// The address of element `index` of the array `ptr` points to. + pub fn element(&mut self, block: usize, ptr: V, index: V) -> V { + let TypeDef::Ptr(arr, space) = self.types[self.type_of(ptr).0 as usize] else { + panic!("element of a non-pointer") + }; + let TypeDef::Array(_, elem) = self.types[arr.0 as usize] else { + panic!("element of a non-array") + }; + let ty = self.ptr_in(elem, space); + let zero = self.i32(0); + self.push(block, ty, Op::Gep(arr, ptr, vec![zero, index])) + } + pub fn load(&mut self, block: usize, ptr: V) -> V { + let TypeDef::Ptr(ty, _) = self.types[self.type_of(ptr).0 as usize] else { + panic!("load from a non-pointer") + }; + self.push(block, ty, Op::Load(ptr)) + } + pub fn store(&mut self, block: usize, ptr: V, value: V) { + let void = self.void(); + self.push(block, void, Op::Store(ptr, value)); + } + pub fn atomic(&mut self, block: usize, op: Rmw, ptr: V, value: V) -> V { + let ty = self.type_of(value); + self.push(block, ty, Op::AtomicRmw(op, ptr, value)) + } + /// The old value of a compare-exchange. + pub fn cmpxchg(&mut self, block: usize, ptr: V, expected: V, new: V) -> V { + let (i32t, i1) = (self.type_of(new), self.int(1)); + let pair = self.ty(TypeDef::Struct(None, vec![i32t, i1])); + let r = self.push(block, pair, Op::CmpXchg(ptr, expected, new)); + self.extract(block, r, 0) + } + + pub fn set_phi(&mut self, phi: V, incoming: Vec<(V, usize)>) { + let V::Inst(i) = phi else { panic!() }; + self.insts[i as usize].op = Op::Phi(incoming); + } + pub fn terminate(&mut self, block: usize, t: Term) { + self.blocks[block].term = Some(t); + } + + pub fn md_str(&mut self, s: &str) -> Md { + self.mds.push(MdDef::Str(s.into())); + Md(self.mds.len() as u32 - 1) + } + pub fn md_value(&mut self, v: V) -> Md { + let ty = self.type_of(v); + self.mds.push(MdDef::Value(ty, v)); + Md(self.mds.len() as u32 - 1) + } + pub fn md_node(&mut self, ops: Vec>) -> Md { + self.mds.push(MdDef::Node(ops)); + Md(self.mds.len() as u32 - 1) + } + pub fn named_md(&mut self, name: &str, nodes: Vec) { + self.named.push((name.into(), nodes)); + } + + /// The module as bitcode. + /// Which instructions are written: every body instruction, the branch + /// conditions, and whatever they read, transitively (a phi nothing reads + /// is dropped). A worklist visits each instruction once, so a long chain + /// of merges costs one pass, not one pass per merge. + fn live(&self) -> Vec { + let mut live = vec![false; self.insts.len()]; + let mut work: Vec = Vec::new(); + let mark = |live: &mut [bool], work: &mut Vec, v: V| { + if let V::Inst(i) = v + && !live[i as usize] + { + live[i as usize] = true; + work.push(i); + } + }; + for b in &self.blocks { + for &i in &b.body { + mark(&mut live, &mut work, V::Inst(i)); + } + if let Some(Term::CondBr(c, ..)) = b.term { + mark(&mut live, &mut work, c); + } + } + while let Some(i) = work.pop() { + for_each_operand(&self.insts[i as usize].op, |v| { + mark(&mut live, &mut work, v) + }); + } + live + } + + pub fn write(&self) -> Vec { + let mut w = Writer::default(); + w.bytes(b"BC\xC0\xDE"); + w.enter(MODULE_BLOCK, 3); + w.record(1, &[1]); // VERSION: relative value ids + + // Attribute groups 1-4 and one list per group. + w.enter(PARAMATTR_GROUP_BLOCK, 3); + for (id, kinds) in [ + (1, &[18u64, 20][..]), + (2, &[18]), + (3, &[18, 21]), + (4, &[12, 18]), + ] { + let mut r = vec![id, 0xFFFF_FFFF]; + for &k in kinds { + r.extend([0, k]); + } + w.record(3, &r); + } + w.exit(); + w.enter(PARAMATTR_BLOCK, 3); + for id in 1..=4 { + w.record(2, &[id]); + } + w.exit(); + + w.enter(TYPE_BLOCK, 4); + w.record(1, &[self.types.len() as u64]); + for t in &self.types { + match t { + TypeDef::Void => w.record(2, &[]), + TypeDef::Float => w.record(3, &[]), + TypeDef::Double => w.record(4, &[]), + TypeDef::Int(b) => w.record(7, &[u64::from(*b)]), + TypeDef::Ptr(p, space) => w.record(8, &[u64::from(p.0), u64::from(*space)]), + TypeDef::Array(n, e) => w.record(11, &[u64::from(*n), u64::from(e.0)]), + TypeDef::Struct(name, fields) => { + let mut r = vec![0]; + r.extend(fields.iter().map(|f| u64::from(f.0))); + match name { + Some(n) => { + w.record(19, &chars(n)); + w.record(20, &r); + } + None => w.record(18, &r), + } + } + TypeDef::Func(ret, params) => { + let mut r = vec![0, u64::from(ret.0)]; + r.extend(params.iter().map(|p| u64::from(p.0))); + w.record(21, &r); + } + } + } + w.exit(); + + w.record(2, &chars("dxil-ms-dx")); + w.record( + 3, + &chars( + "e-m:e-p:32:32-i1:32-i8:32-i16:32-i32:32-i64:64-f16:32-f32:32-f64:64-n8:16:32:64", + ), + ); + let first_const = (self.globals.len() + self.funcs.len()) as u64; + for g in &self.globals { + // [type, address space << 2 | explicit type | constant, init id + // + 1, linkage (external 0, internal 3), log2 alignment + 1, + // section] + let (constant, init, linkage) = match g.init { + Some(i) => (1, first_const + u64::from(i) + 1, 3), + None => (0, 0, 0), + }; + w.record( + 7, + &[ + u64::from(g.ty.0), + u64::from(g.space) << 2 | 2 | constant, + init, + linkage, + 3, + 0, + ], + ); + } + for f in &self.funcs { + // [type, cc, isproto, linkage, paramattr, align, section, + // visibility, gc, unnamed_addr, prologue, dllstorage, comdat, prefix] + let attr = f.attr.map_or(0, |a| a as u64); + w.record( + 8, + &[ + u64::from(f.ty.0), + 0, + u64::from(!f.body), + 0, + attr, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + ], + ); + } + + // Value ids: globals, functions, constants, instructions. + let globals = self.globals.len() as u32; + let funcs = globals + self.funcs.len() as u32; + let const_id = |i: u32| u64::from(funcs + i); + w.enter(CONSTANTS_BLOCK, 4); + let mut current = None; + for (ty, c) in &self.consts { + if current != Some(*ty) { + w.record(1, &[u64::from(ty.0)]); + current = Some(*ty); + } + match c { + Const::Undef => w.record(3, &[]), + Const::Int(v) => w.record(4, &[signed(*v)]), + Const::Float(bits) => w.record(6, &[u64::from(*bits)]), + Const::Aggregate(ids) => { + let r: Vec = ids.iter().map(|&i| const_id(i)).collect(); + w.record(7, &r); + } + } + } + w.exit(); + + // Phis nothing reads are left out (one register per phi makes many). + let live = self.live(); + + // Blocks are laid out in reverse postorder, so every block follows + // its forward predecessors (drivers take a branch to an earlier + // block for a loop's back edge). + let succs = |b: usize| successors(self.blocks[b].term); + let mut seen = vec![false; self.blocks.len()]; + let mut post = Vec::new(); + let mut stack = vec![(0usize, 0usize)]; + seen[0] = true; + while let Some(top) = stack.last_mut() { + let (b, k) = *top; + top.1 += 1; + match succs(b).get(k) { + Some(&s) if !seen[s] => { + seen[s] = true; + stack.push((s, 0)); + } + Some(_) => {} + None => { + post.push(b); + stack.pop(); + } + } + } + post.reverse(); + let mut pos = vec![u64::MAX; self.blocks.len()]; + for (n, &b) in post.iter().enumerate() { + pos[b] = n as u64; + } + // An empty latch (only a branch back to its loop header) is folded + // into its one predecessor, so the exiting block is the latch as in + // DXC's loops; the AMD driver hangs on divergent loops otherwise. + let mut preds = vec![Vec::new(); self.blocks.len()]; + for &b in &post { + for &s in succs(b).iter() { + preds[s].push(b); + } + } + let mut fold = vec![None; self.blocks.len()]; + for &b in &post { + let blk = &self.blocks[b]; + if let (Some(Term::Br(h)), true, [p]) = ( + blk.term, + blk.phis.is_empty() && blk.body.is_empty(), + &preds[b][..], + ) && pos[h] < pos[b] + && !succs(*p).contains(&h) + { + fold[b] = Some((*p, h)); + } + } + let layout: Vec = post.into_iter().filter(|&b| fold[b].is_none()).collect(); + let mut pos = vec![u64::MAX; self.blocks.len()]; + for (n, &b) in layout.iter().enumerate() { + pos[b] = n as u64; + } + // Branch targets and phi blocks through folded latches. + let target = |t: usize| fold[t].map_or(pos[t], |(_, h)| pos[h]); + let from = |b: usize| fold[b].map_or(pos[b], |(p, _)| pos[p]); + + // Instruction value ids, in layout order. + let base = funcs + self.consts.len() as u32; + let mut ids = vec![u32::MAX; self.insts.len()]; + let mut next = base; + for b in layout.iter().map(|&b| &self.blocks[b]) { + for &i in b.phis.iter().filter(|&&i| live[i as usize]).chain(&b.body) { + if !self.is_void(self.insts[i as usize].ty) { + ids[i as usize] = next; + next += 1; + } + } + } + let abs = |v: V| -> u32 { + match v { + V::Global(i) => i, + V::Func(i) => globals + i, + V::Const(i) => funcs + i, + V::Inst(i) => { + let id = ids[i as usize]; + assert_ne!(id, u32::MAX, "use of a void value"); + id + } + } + }; + + w.enter(METADATA_BLOCK, 3); + for m in &self.mds { + match m { + MdDef::Str(s) => w.record(1, &chars(s)), + MdDef::Value(ty, v) => w.record(2, &[u64::from(ty.0), u64::from(abs(*v))]), + MdDef::Node(ops) => { + let r: Vec = ops + .iter() + .map(|o| o.map_or(0, |m| u64::from(m.0) + 1)) + .collect(); + w.record(3, &r); + } + } + } + for (name, nodes) in &self.named { + w.record(4, &chars(name)); + let r: Vec = nodes.iter().map(|m| u64::from(m.0)).collect(); + w.record(10, &r); + } + w.exit(); + // The metadata kinds an LLVM 3.7 module declares, as DXC writes them. + w.enter(METADATA_BLOCK, 3); + for (id, kind) in [ + "dbg", + "tbaa", + "prof", + "fpmath", + "range", + "tbaa.struct", + "invariant.load", + "alias.scope", + "noalias", + "nontemporal", + "llvm.mem.parallel_loop_access", + "nonnull", + "dereferenceable", + "dereferenceable_or_null", + ] + .into_iter() + .enumerate() + { + let mut r = vec![id as u64]; + r.extend(chars(kind)); + w.record(6, &r); + } + w.exit(); + + w.enter(VALUE_SYMTAB_BLOCK, 4); + let names = self.globals.iter().map(|g| &g.name); + for (i, name) in names.chain(self.funcs.iter().map(|f| &f.name)).enumerate() { + let mut r = vec![i as u64]; + r.extend(chars(name)); + w.record(1, &r); + } + w.exit(); + + w.enter(FUNCTION_BLOCK, 4); + w.record(1, &[layout.len() as u64]); + let mut inst_id = base; + // The operands of variable-length records, reused across them. + let mut r: Vec = Vec::new(); + for b in layout.iter().map(|&b| &self.blocks[b]) { + for &i in b.phis.iter().filter(|&&i| live[i as usize]).chain(&b.body) { + let inst = &self.insts[i as usize]; + let rel = |v: V| { + let a = abs(v); + assert!(a < inst_id, "forward reference outside a phi"); + u64::from(inst_id - a) + }; + match &inst.op { + Op::Bin(op, a, b) => w.record(2, &[rel(*a), rel(*b), *op as u64]), + Op::Cast(op, v) => w.record(3, &[rel(*v), u64::from(inst.ty.0), *op as u64]), + Op::Cmp(p, a, b) => w.record(28, &[rel(*a), rel(*b), u64::from(*p)]), + Op::Select(c, t, f) => w.record(29, &[rel(*t), rel(*f), rel(*c)]), + Op::Extract(a, idx) => w.record(26, &[rel(*a), u64::from(*idx)]), + Op::Call(f, args) => { + r.clear(); + r.extend([0, 1 << 15, u64::from(self.funcs[*f as usize].ty.0)]); + r.push(rel(V::Func(*f))); + r.extend(args.iter().map(|&a| rel(a))); + w.record(34, &r); + } + Op::Phi(incoming) => { + r.clear(); + r.push(u64::from(inst.ty.0)); + for &(v, b) in incoming { + r.push(signed(i64::from(inst_id) - i64::from(abs(v)))); + r.push(from(b)); + } + w.record(16, &r); + } + Op::Gep(ty, p, idx) => { + r.clear(); + r.extend([0, u64::from(ty.0), rel(*p)]); + r.extend(idx.iter().map(|&i| rel(i))); + w.record(43, &r); + } + // Alignment 4 (log2 + 1), not volatile. + Op::Load(p) => w.record(20, &[rel(*p), u64::from(inst.ty.0), 3, 0]), + Op::Store(p, v) => w.record(44, &[rel(*p), rel(*v), 3, 0]), + // Sequentially consistent, across threads. + Op::AtomicRmw(op, p, v) => { + w.record(38, &[rel(*p), rel(*v), *op as u64, 0, 6, 1]) + } + Op::CmpXchg(p, c, n) => { + w.record(46, &[rel(*p), rel(*c), rel(*n), 0, 6, 1, 6, 0]); + } + } + if !self.is_void(inst.ty) { + inst_id += 1; + } + } + match b.term.expect("unterminated block") { + Term::Ret => w.record(10, &[]), + Term::Br(t) => w.record(11, &[target(t)]), + Term::CondBr(c, t, f) => { + let a = abs(c); + assert!(a < inst_id); + w.record(11, &[target(t), target(f), u64::from(inst_id - a)]); + } + } + } + w.exit(); + w.exit(); + w.finish() + } +} + +const MODULE_BLOCK: u64 = 8; +const PARAMATTR_BLOCK: u64 = 9; +const PARAMATTR_GROUP_BLOCK: u64 = 10; +const CONSTANTS_BLOCK: u64 = 11; +const FUNCTION_BLOCK: u64 = 12; +const VALUE_SYMTAB_BLOCK: u64 = 14; +const METADATA_BLOCK: u64 = 15; +const TYPE_BLOCK: u64 = 17; + +/// Calls `f` with every value `op` reads, in operand order. +fn for_each_operand(op: &Op, mut f: impl FnMut(V)) { + match op { + Op::Bin(_, a, b) | Op::Cmp(_, a, b) | Op::Store(a, b) | Op::AtomicRmw(_, a, b) => { + f(*a); + f(*b); + } + Op::Cast(_, v) | Op::Extract(v, _) | Op::Load(v) => f(*v), + Op::Select(a, b, c) | Op::CmpXchg(a, b, c) => { + f(*a); + f(*b); + f(*c); + } + Op::Call(_, args) => args.iter().copied().for_each(f), + Op::Phi(inc) => inc.iter().for_each(|x| f(x.0)), + Op::Gep(_, p, idx) => { + f(*p); + idx.iter().copied().for_each(f); + } + } +} + +/// A block's successors (at most two), without allocating. +struct Succs { + to: [usize; 2], + len: usize, +} + +impl std::ops::Deref for Succs { + type Target = [usize]; + fn deref(&self) -> &[usize] { + &self.to[..self.len] + } +} + +fn successors(term: Option) -> Succs { + match term { + Some(Term::Br(t)) => Succs { to: [t, 0], len: 1 }, + Some(Term::CondBr(_, t, f)) => Succs { to: [t, f], len: 2 }, + _ => Succs { to: [0, 0], len: 0 }, + } +} + +fn chars(s: &str) -> Vec { + s.bytes().map(u64::from).collect() +} + +/// LLVM's signed VBR operand: magnitude shifted left, sign in bit 0. +fn signed(v: i64) -> u64 { + if v >= 0 { + (v as u64) << 1 + } else { + (v.unsigned_abs() << 1) | 1 + } +} + +/// The bitstream: little-endian 32-bit words filled from bit 0. +#[derive(Default)] +struct Writer { + words: Vec, + cur: u64, + bits: u32, + /// Per open block: abbreviation width, index of its length word. + stack: Vec<(u32, usize)>, +} + +impl Writer { + fn width(&self) -> u32 { + self.stack.last().map_or(2, |b| b.0) + } + + fn emit(&mut self, v: u64, width: u32) { + debug_assert!(width == 64 || v >> width == 0); + self.cur |= v << self.bits; + self.bits += width; + while self.bits >= 32 { + self.words.push(self.cur as u32); + self.cur >>= 32; + self.bits -= 32; + } + } + + fn vbr(&mut self, mut v: u64, width: u32) { + let hi = 1u64 << (width - 1); + while v >= hi { + self.emit(v & (hi - 1) | hi, width); + v >>= width - 1; + } + self.emit(v, width); + } + + fn align(&mut self) { + if self.bits > 0 { + self.words.push(self.cur as u32); + self.cur = 0; + self.bits = 0; + } + } + + fn bytes(&mut self, b: &[u8]) { + for &x in b { + self.emit(u64::from(x), 8); + } + } + + fn enter(&mut self, id: u64, width: u32) { + self.emit(1, self.width()); // ENTER_SUBBLOCK + self.vbr(id, 8); + self.vbr(u64::from(width), 4); + self.align(); + self.words.push(0); + self.stack.push((width, self.words.len())); + } + + fn exit(&mut self) { + self.emit(0, self.width()); // END_BLOCK + self.align(); + let (_, start) = self.stack.pop().expect("open block"); + self.words[start - 1] = (self.words.len() - start) as u32; + } + + /// An unabbreviated record. + fn record(&mut self, code: u64, ops: &[u64]) { + self.emit(3, self.width()); + self.vbr(code, 6); + self.vbr(ops.len() as u64, 6); + for &o in ops { + self.vbr(o, 6); + } + } + + fn finish(mut self) -> Vec { + self.align(); + self.words.iter().flat_map(|w| w.to_le_bytes()).collect() + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn vbr_and_blocks() { + let mut w = Writer::default(); + w.vbr(5, 6); + w.vbr(100, 6); // two chunks: 100 = 0b1100100 -> 0b100100 | 32, then 3 + assert_eq!(w.cur, 5 | (0b10_0100 << 6) | (3 << 12)); + let mut w = Writer::default(); + w.enter(8, 3); + w.record(1, &[1]); + w.exit(); + let bytes = w.finish(); + // header word, length word, one record word, end word. + assert_eq!(bytes.len() % 4, 0); + assert_eq!(u32::from_le_bytes(bytes[4..8].try_into().unwrap()), 1); + assert_eq!(signed(-3), 7); + assert_eq!(signed(2), 4); + } + + /// A structured shader's shape: `stages` if/else diamonds in a row, each + /// merge with one phi per register (as the lowering makes them), then a + /// loop, and a tail that reads only the first `read` registers. + fn synthetic(regs: usize, stages: usize, read: usize) -> Module { + let mut m = Module::default(); + let i32t = m.int(32); + let void = m.void(); + let fty = m.func_ty(i32t, vec![i32t, i32t]); + let f = m.function("dx.op.synthetic", fty, Some(Attr::ReadNone), false); + let main_ty = m.func_ty(void, vec![]); + m.function("main", main_ty, None, true); + let mut b = m.new_block(); + let mut cur: Vec = (0..regs).map(|r| m.i32(r as u32)).collect(); + for s in 0..stages { + let c = m.cmp(b, pred::EQ, cur[0], cur[s % regs]); + let (t, e, j) = (m.new_block(), m.new_block(), m.new_block()); + m.terminate(b, Term::CondBr(c, t, e)); + let x = m.call(t, f, vec![cur[s % regs], cur[(s + 1) % regs]]); + m.terminate(t, Term::Br(j)); + m.terminate(e, Term::Br(j)); + cur = (0..regs) + .map(|r| { + let p = m.phi(j, i32t); + let tv = if r == s % regs { x } else { cur[r] }; + m.set_phi(p, vec![(tv, t), (cur[r], e)]); + p + }) + .collect(); + b = j; + } + // A loop: header phis fed back from an empty latch (which is folded). + let (head, body, latch, exit) = + (m.new_block(), m.new_block(), m.new_block(), m.new_block()); + m.terminate(b, Term::Br(head)); + let phis: Vec = (0..regs).map(|_| m.phi(head, i32t)).collect(); + let one = m.i32(1); + let stepped: Vec = phis + .iter() + .map(|&p| m.bin(body, Bin::Add, p, one)) + .collect(); + let c = m.cmp(body, pred::IULT, stepped[0], cur[0]); + m.terminate(head, Term::Br(body)); + m.terminate(body, Term::CondBr(c, latch, exit)); + m.terminate(latch, Term::Br(head)); + for r in 0..regs { + m.set_phi(phis[r], vec![(cur[r], b), (stepped[r], latch)]); + } + let mut acc = stepped[0]; + for &v in &stepped[1..read.max(1)] { + acc = m.bin(exit, Bin::Add, acc, v); + } + let _ = m.call(exit, f, vec![acc, cur[0]]); + m.terminate(exit, Term::Ret); + m + } + + /// FNV-1a, to pin a written module's exact bytes. + fn fnv(bytes: &[u8]) -> u64 { + bytes.iter().fold(0xcbf2_9ce4_8422_2325, |h, &b| { + (h ^ u64::from(b)).wrapping_mul(0x0100_0000_01b3) + }) + } + + /// Liveness as `write` computed it before the worklist: whole passes over + /// the instructions until one changes nothing. + fn live_by_passes(m: &Module) -> Vec { + let mut live = vec![false; m.insts.len()]; + for b in &m.blocks { + for &i in &b.body { + live[i as usize] = true; + } + if let Some(Term::CondBr(V::Inst(c), ..)) = b.term { + live[c as usize] = true; + } + } + let mut changed = true; + while changed { + changed = false; + for (i, inst) in m.insts.iter().enumerate() { + if live[i] { + for_each_operand(&inst.op, |v| { + if let V::Inst(j) = v + && !live[j as usize] + { + live[j as usize] = true; + changed = true; + } + }); + } + } + } + live + } + + #[test] + fn worklist_liveness_matches_passes() { + for (regs, stages, read) in [(1, 0, 1), (1, 1, 1), (4, 3, 1), (8, 17, 3), (16, 40, 16)] { + let m = synthetic(regs, stages, read); + let live = m.live(); + assert_eq!(live, live_by_passes(&m), "{regs} regs x {stages} stages"); + } + } + + #[test] + fn unread_phis_are_dropped() { + let mut m = Module::default(); + let i32t = m.int(32); + let (entry, join) = (m.new_block(), m.new_block()); + let (a, b) = (m.i32(1), m.i32(2)); + m.terminate(entry, Term::Br(join)); + let read = m.phi(join, i32t); + let unread = m.phi(join, i32t); + // A cycle of phis that only feed each other stays dead. + let cyc_a = m.phi(join, i32t); + let cyc_b = m.phi(join, i32t); + m.set_phi(read, vec![(a, entry)]); + m.set_phi(unread, vec![(b, entry)]); + m.set_phi(cyc_a, vec![(cyc_b, entry)]); + m.set_phi(cyc_b, vec![(cyc_a, entry)]); + let sum = m.bin(join, Bin::Add, read, b); + m.terminate(join, Term::Ret); + let ids = |v: V| match v { + V::Inst(i) => i as usize, + _ => unreachable!(), + }; + let live = m.live(); + assert!(live[ids(read)] && live[ids(sum)]); + assert!(!live[ids(unread)] && !live[ids(cyc_a)] && !live[ids(cyc_b)]); + assert_eq!(live, live_by_passes(&m)); + } + + #[test] + fn successors_of_each_terminator() { + assert!(successors(None).is_empty()); + assert!(successors(Some(Term::Ret)).is_empty()); + assert_eq!(&*successors(Some(Term::Br(7))), &[7]); + assert_eq!(&*successors(Some(Term::CondBr(V::Const(0), 3, 5))), &[3, 5]); + } + + /// The written bytes are pinned to what the writer produced before the + /// worklist and the reused record buffers. + #[test] + fn written_bytes_unchanged() { + for ((regs, stages, read), len, hash) in [ + ((64, 64, 64), 38_916, 0x9586_730c_f953_4a45), + ((128, 256, 32), 295_952, 0x89e5_de2d_64f0_8785), + ] { + let bytes = synthetic(regs, stages, read).write(); + assert_eq!((bytes.len(), fnv(&bytes)), (len, hash), "{regs}x{stages}"); + } + } + + #[test] + #[ignore = "benchmark: cargo test --release -p leonida-shader bitcode -- --ignored --nocapture"] + fn bench_write() { + for (regs, stages, read) in [(64, 64, 64), (128, 256, 32), (256, 512, 256)] { + let m = synthetic(regs, stages, read); + let bytes = m.write(); + let runs = 5; + let t = std::time::Instant::now(); + for _ in 0..runs { + std::hint::black_box(m.write()); + } + let per = t.elapsed() / runs; + println!( + "write {regs} regs x {stages} stages ({} insts): {per:?}, {} bytes, fnv {:#018x}", + m.insts.len(), + bytes.len(), + fnv(&bytes) + ); + } + } +} diff --git a/crates/leonida-shader/src/emit/bitcode/census.rs b/crates/leonida-shader/src/emit/bitcode/census.rs new file mode 100644 index 000000000..ee54eea70 --- /dev/null +++ b/crates/leonida-shader/src/emit/bitcode/census.rs @@ -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. +//! +//! `LEONIDA_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/leonida/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> = 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 (`LEONIDA_SHADER_CENSUS` set). +pub fn enabled() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("LEONIDA_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 { + 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 = 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 = 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 + } +} diff --git a/crates/leonida-shader/src/emit/bitcode/opt.rs b/crates/leonida-shader/src/emit/bitcode/opt.rs new file mode 100644 index 000000000..bdbce3765 --- /dev/null +++ b/crates/leonida-shader/src/emit/bitcode/opt.rs @@ -0,0 +1,2136 @@ +//! Clean-up of a finished module before it is written: the lowering emits +//! one instruction after another as the console code names them, and +//! nothing stands between it and the driver's compiler. Every pass here is +//! exact: the module computes the same values and has the same effects for +//! every input. +//! +//! - [`DEAD`]: instructions without an effect whose result nothing reads +//! are left out (the lowering computes every dword of every register a +//! console instruction writes; a guarded write reads the register's old +//! value whether anything reads the new one or not). +//! - [`FOLD`]: integer arithmetic on constants is done here, and identities +//! (`x + 0`, `x & -1`, a select between a value and itself, a cast there +//! and back, a join of one value) give their operand. Float arithmetic is +//! left alone: `x + 0.0` and `x * 1.0` are not `x` for every `x`. +//! - [`REUSE`]: an instruction without an effect whose operands are those +//! of an earlier one that every path to it has run gives that one's +//! result (a descriptor handle made again in each block, an index clamped +//! again, a register read as a float again). +//! - [`FACTS`]: in the blocks only one side of a branch leads to, the +//! branch's condition is that side's constant, and so is what the +//! condition was made of (both terms of an `and` that held, the opposite +//! comparison). The lowering branches on a lane's condition and then +//! guards each instruction behind the branch with the same condition. +//! - [`LOADS`]: within a block, a read of the same place as an earlier read +//! gives that one's result while no store, atomic, barrier or other call +//! with an effect stands between them (another thread's unsynchronised +//! store may fall between any two reads or before both: the title's code +//! cannot tell which). +//! +//! Which passes run is `emit::shader_opt()` (`LEONIDA_SHADER_OPT`), part of +//! the translation and so of the shader cache's key. + +use std::collections::HashMap; + +use super::{ + Attr, Bin, Cast, Const, Func, MdDef, Module, Op, Term, Ty, TypeDef, V, for_each_operand, pred, + successors, +}; + +/// Dead-code elimination. +pub const DEAD: u32 = 1; +/// Constants folded, identities removed. +pub const FOLD: u32 = 2; +/// One instruction for one value. +pub const REUSE: u32 = 4; +/// What a branch taken says about its condition. +pub const FACTS: u32 = 8; +/// One read for one place within a block, while nothing is stored. +pub const LOADS: u32 = 16; +/// Not a pass over the module: the lowering of a first-lane read in a +/// wave64 program run as two host waves skips the exchange that asks which +/// half has a lane where every lane is in EXEC (`lower.rs`, +/// `v_readfirstlane_b32`). +pub const FIRST: u32 = 32; +/// The passes over the module. +pub const MODULE: u32 = DEAD | FOLD | REUSE | FACTS | LOADS; +/// Every pass. +pub const ALL: u32 = MODULE | FIRST; + +/// What the instructions a module writes use, of the features a shader +/// declares by flag (the validator's "flags must match usage"). +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +pub(crate) struct Usage { + /// A wave or quad operation. + pub wave_ops: bool, + /// A 64-bit integer, as a result or an operand. + pub int64: bool, + /// A typed load of several components from a UAV. + pub typed_uav_loads: bool, + /// A handle from the view heap. + pub heap_views: bool, + /// A handle from the sampler heap. + pub heap_samplers: bool, + /// A 64-bit atomic. + pub atomic64: bool, +} + +/// What makes two instructions without an effect the same value. +#[derive(Debug, Clone, PartialEq, Eq, Hash)] +enum Key { + Bin(u8, V, V), + Cast(u8, Ty, V), + Cmp(u8, V, V), + Select(V, V, V), + Extract(V, u32), + Call(u32, Vec), + Gep(Ty, V, Vec), + Load(V), +} + +/// The blocks reached from the entry, each after the blocks that dominate +/// it, and each block's children in the dominator tree. +struct Tree { + order: Vec, + children: Vec>, + /// Per block: the reached blocks that branch to it, once per edge. + preds: Vec>, +} + +/// The comparison that holds exactly when `p` does not (floats 0-15, +/// integers 32-41). +fn opposite(p: u8) -> u8 { + match p { + 0..=15 => 15 - p, + pred::EQ => pred::NE, + pred::NE => pred::EQ, + pred::IUGT => pred::IULE, + pred::IULE => pred::IUGT, + pred::IUGE => pred::IULT, + pred::IULT => pred::IUGE, + pred::SGT => pred::SLE, + pred::SLE => pred::SGT, + pred::SGE => pred::SLT, + _ => pred::SGE, + } +} + +/// What holds in the block being walked: values that are a known bit there, +/// and comparisons (by their operands) with a known outcome. +#[derive(Default)] +struct Facts { + bits: HashMap, + compares: HashMap<(u8, V, V), bool>, +} + +/// The facts a block added, to forget when its part of the tree is done. +#[derive(Default)] +struct Learned { + bits: Vec, + compares: Vec<(u8, V, V)>, +} + +fn mask(bits: u32) -> u64 { + if bits >= 64 { !0 } else { (1 << bits) - 1 } +} + +/// `x` of `bits` bits as a signed number. +fn signed(bits: u32, x: u64) -> i64 { + if bits < 64 && x >> (bits - 1) & 1 != 0 { + (x | !mask(bits)) as i64 + } else { + x as i64 + } +} + +/// What `v` stands for after the replacements so far. +fn resolve(repl: &[Option], mut v: V) -> V { + while let V::Inst(i) = v { + match repl[i as usize] { + Some(r) => v = r, + None => break, + } + } + v +} + +/// Replaces every value `op` reads by `f` of it. +fn map_operands(op: &mut Op, mut f: impl FnMut(V) -> V) { + match op { + Op::Bin(_, a, b) | Op::Cmp(_, a, b) | Op::Store(a, b) | Op::AtomicRmw(_, a, b) => { + *a = f(*a); + *b = f(*b); + } + Op::Cast(_, v) | Op::Extract(v, _) | Op::Load(v) => *v = f(*v), + Op::Select(a, b, c) | Op::CmpXchg(a, b, c) => { + *a = f(*a); + *b = f(*b); + *c = f(*c); + } + Op::Call(_, args) => args.iter_mut().for_each(|a| *a = f(*a)), + Op::Phi(inc) => inc.iter_mut().for_each(|x| x.0 = f(x.0)), + Op::Gep(_, p, idx) => { + *p = f(*p); + idx.iter_mut().for_each(|i| *i = f(*i)); + } + } +} + +/// What a call does besides returning its result. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(super) enum Effect { + /// Nothing, and the result depends on the arguments alone for the whole + /// run of the shader (arithmetic, handles, inputs, constant buffers, + /// resource sizes). + Pure, + /// Nothing, but the result depends on memory a store may change + /// (buffer and texture reads). + Reads, + /// Nothing, but the result depends on which lanes run the instruction + /// (wave and quad operations). + Lanes, + /// Stores, atomics, barriers, outputs, discards: always kept. + Writes, +} + +pub(super) fn effect(f: &Func) -> Effect { + let name = f.name.strip_prefix("dx.op.").unwrap_or(&f.name); + match f.attr { + Some(Attr::ReadNone) => Effect::Pure, + // A shader cannot write a constant buffer or resize a resource. + Some(Attr::ReadOnly) + if name.starts_with("cbufferLoadLegacy") || name.starts_with("getDimensions") => + { + Effect::Pure + } + Some(Attr::ReadOnly) if name.starts_with("wave") => Effect::Lanes, + Some(Attr::ReadOnly) => Effect::Reads, + // Declared with the attribute of calls that have effects, and have + // none: they read the other lanes' values. + _ if name.starts_with("wave") || name.starts_with("quad") => Effect::Lanes, + _ => Effect::Writes, + } +} + +impl Module { + /// Runs the clean-up passes named in `passes` ([`ALL`]: every one). + pub(crate) fn optimise(&mut self, passes: u32) { + if passes & (FOLD | REUSE | FACTS | LOADS) != 0 { + // Values merged in one round can make two joins the same in + // the next (a loop's registers that only go round), and a + // branch that goes one way leaves blocks with one way in. + for _ in 0..4 { + let mut changed = self.merge(passes); + if passes & FOLD != 0 { + changed |= self.prune(); + } + if !changed { + break; + } + } + } + if passes & DEAD != 0 { + self.drop_dead(); + } + } + + /// Per function: what a call of it does. + pub(super) fn effects(&self) -> Vec { + self.funcs.iter().map(effect).collect() + } + + /// The blocks reached from the entry. + pub(super) fn reached(&self) -> Vec { + let mut seen = vec![false; self.blocks.len()]; + if self.blocks.is_empty() { + return seen; + } + let mut stack = vec![0usize]; + seen[0] = true; + while let Some(b) = stack.pop() { + for &s in successors(self.blocks[b].term).iter() { + if !seen[s] { + seen[s] = true; + stack.push(s); + } + } + } + seen + } + + fn dominator_tree(&self) -> Tree { + let n = self.blocks.len(); + let succs = |b: usize| successors(self.blocks[b].term); + // Reverse postorder, as `write` lays the blocks out. + let mut seen = vec![false; n]; + let mut post = Vec::new(); + let mut stack = vec![(0usize, 0usize)]; + seen[0] = true; + while let Some(top) = stack.last_mut() { + let (b, k) = *top; + top.1 += 1; + match succs(b).get(k) { + Some(&s) if !seen[s] => { + seen[s] = true; + stack.push((s, 0)); + } + Some(_) => {} + None => { + post.push(b); + stack.pop(); + } + } + } + post.reverse(); + let order = post; + let mut number = vec![usize::MAX; n]; + for (k, &b) in order.iter().enumerate() { + number[b] = k; + } + let mut preds = vec![Vec::new(); n]; + for &b in &order { + for &s in succs(b).iter() { + preds[s].push(b); + } + } + // Immediate dominators (Cooper, Harvey and Kennedy's iteration). + let mut idom = vec![usize::MAX; n]; + idom[0] = 0; + let mut changed = true; + while changed { + changed = false; + for &b in &order[1..] { + let mut new = usize::MAX; + for &p in &preds[b] { + if idom[p] == usize::MAX { + continue; + } + if new == usize::MAX { + new = p; + continue; + } + let (mut x, mut y) = (p, new); + while x != y { + while number[x] > number[y] { + x = idom[x]; + } + while number[y] > number[x] { + y = idom[y]; + } + } + new = x; + } + if idom[b] != new { + idom[b] = new; + changed = true; + } + } + } + let mut children = vec![Vec::new(); n]; + for &b in &order[1..] { + children[idom[b]].push(b); + } + Tree { + order, + children, + preds, + } + } + + /// Notes that `v` (an i1) is `holds` in the block being walked, and what + /// follows from it for the values `v` was made of. + fn learn(&self, v: V, holds: bool, facts: &mut Facts, learned: &mut Learned, depth: u32) { + let V::Inst(i) = v else { return }; + if facts.bits.contains_key(&v) { + return; + } + facts.bits.insert(v, holds); + learned.bits.push(v); + if depth == 0 { + return; + } + match self.insts[i as usize].op { + // Both terms of an `and` that holds hold; neither of an `or` + // that does not. + Op::Bin(Bin::And, a, b) if holds => { + self.learn(a, true, facts, learned, depth - 1); + self.learn(b, true, facts, learned, depth - 1); + } + Op::Bin(Bin::Or, a, b) if !holds => { + self.learn(a, false, facts, learned, depth - 1); + self.learn(b, false, facts, learned, depth - 1); + } + Op::Bin(Bin::Xor, a, b) => { + let (x, k) = match (self.int_k(a), self.int_k(b)) { + (None, Some((1, k))) => (a, k), + (Some((1, k)), None) => (b, k), + _ => return, + }; + self.learn(x, holds != (k != 0), facts, learned, depth - 1); + } + // The opposite comparison of the same operands. + Op::Cmp(p, a, b) => { + let key = (opposite(p), a, b); + if let std::collections::hash_map::Entry::Vacant(e) = facts.compares.entry(key) { + e.insert(!holds); + learned.compares.push(key); + } + } + _ => {} + } + } + + fn int_bits(&self, ty: Ty) -> Option { + match self.types[ty.0 as usize] { + TypeDef::Int(bits) => Some(bits), + _ => None, + } + } + + /// An integer constant's width and value (the bits of that width). + fn int_k(&self, v: V) -> Option<(u32, u64)> { + let V::Const(i) = v else { return None }; + let (ty, Const::Int(x)) = &self.consts[i as usize] else { + return None; + }; + let bits = self.int_bits(*ty)?; + Some((bits, *x as u64 & mask(bits))) + } + + /// The constant `x` of the integer type `ty`, kept sign-extended as + /// [`Module::i32`] and [`Module::bool`] keep theirs. + fn k(&mut self, ty: Ty, bits: u32, x: u64) -> V { + self.int_const(ty, signed(bits, x & mask(bits))) + } + + /// The value instruction `i` is known to have without it, if any: a + /// constant or an earlier value. May instead give `i` simpler operands + /// (`changed` says so). + fn simplify(&mut self, i: u32, changed: &mut bool) -> Option { + let ty = self.insts[i as usize].ty; + match self.insts[i as usize].op { + Op::Bin(op, a, b) => { + // Floats: `x + 0.0`, `x * 1.0` and the like are not `x` for + // every `x` (a negative zero, a signalling NaN). + let bits = self.int_bits(ty)?; + let (ka, kb) = (self.int_k(a).map(|k| k.1), self.int_k(b).map(|k| k.1)); + let all = mask(bits); + if let (Some(x), Some(y)) = (ka, kb) { + // A shift by the width or more and a division by zero + // have no defined result: left as they are. + let amount = u32::try_from(y).ok().filter(|&y| y < bits); + let r = match op { + Bin::Add => x.wrapping_add(y), + Bin::Sub => x.wrapping_sub(y), + Bin::Mul => x.wrapping_mul(y), + Bin::And => x & y, + Bin::Or => x | y, + Bin::Xor => x ^ y, + Bin::Shl => x << amount?, + Bin::LShr => x >> amount?, + Bin::AShr => (signed(bits, x) >> amount?) as u64, + Bin::UDiv if y != 0 => x / y, + Bin::URem if y != 0 => x % y, + _ => return None, + }; + return Some(self.k(ty, bits, r)); + } + match (op, ka, kb) { + ( + Bin::Add | Bin::Sub | Bin::Or | Bin::Xor | Bin::Shl | Bin::LShr | Bin::AShr, + _, + Some(0), + ) => Some(a), + (Bin::Add | Bin::Or | Bin::Xor, Some(0), _) => Some(b), + (Bin::Mul | Bin::UDiv, _, Some(1)) => Some(a), + (Bin::Mul, Some(1), _) => Some(b), + (Bin::Mul | Bin::And, _, Some(0)) => Some(b), + (Bin::Mul | Bin::And, Some(0), _) => Some(a), + (Bin::And, _, Some(m)) if m == all => Some(a), + (Bin::And, Some(m), _) if m == all => Some(b), + (Bin::Or, _, Some(m)) if m == all => Some(b), + (Bin::Or, Some(m), _) if m == all => Some(a), + (Bin::And | Bin::Or, _, _) if a == b => Some(a), + _ => None, + } + } + Op::Cmp(p, a, b) if p <= pred::TRUE => { + // Two float constants compare one way (`v_mul_legacy` asks + // whether its constant factor is zero). + let (V::Const(x), V::Const(y)) = (a, b) else { + return None; + }; + let (Const::Float(x), Const::Float(y)) = + (&self.consts[x as usize].1, &self.consts[y as usize].1) + else { + return None; + }; + let (x, y) = (f32::from_bits(*x), f32::from_bits(*y)); + let unordered = x.is_nan() || y.is_nan(); + // Bits 0-2 of a predicate: equal, greater, less; bit 3: + // or unordered. + let holds = if unordered { + p & 8 != 0 + } else { + (p & 1 != 0 && x == y) || (p & 2 != 0 && x > y) || (p & 4 != 0 && x < y) + }; + Some(self.bool(holds)) + } + Op::Cmp(p, a, b) => { + if !(pred::EQ..=pred::SLE).contains(&p) { + return None; + } + let holds = |x: u64, y: u64, bits: u32| { + let (sx, sy) = (signed(bits, x), signed(bits, y)); + match p { + pred::EQ => x == y, + pred::NE => x != y, + pred::IUGT => x > y, + pred::IUGE => x >= y, + pred::IULT => x < y, + pred::IULE => x <= y, + pred::SGT => sx > sy, + pred::SGE => sx >= sy, + pred::SLT => sx < sy, + _ => sx <= sy, + } + }; + if let (Some((bits, x)), Some((_, y))) = (self.int_k(a), self.int_k(b)) { + return Some(self.bool(holds(x, y, bits))); + } + if a == b { + return Some(self.bool(holds(0, 0, 32))); + } + // A bit widened and tested again is the bit. + if p == pred::NE + && self.int_k(b).is_some_and(|k| k.1 == 0) + && let V::Inst(z) = a + && let Op::Cast(Cast::ZExt, x) = self.insts[z as usize].op + && self.type_of(x) == ty + { + return Some(x); + } + None + } + Op::Select(c, mut t, mut f) => { + if let Some((_, c)) = self.int_k(c) { + return Some(if c != 0 { t } else { f }); + } + // Under the same condition an inner select is one of its + // operands (two guarded writes of one register in a row). + let mut inner = false; + while let V::Inst(x) = t + && let Op::Select(c2, t2, _) = self.insts[x as usize].op + && c2 == c + { + (t, inner) = (t2, true); + } + while let V::Inst(x) = f + && let Op::Select(c2, _, f2) = self.insts[x as usize].op + && c2 == c + { + (f, inner) = (f2, true); + } + if t == f { + return Some(t); + } + if self.int_bits(ty) == Some(1) + && self.int_k(t).is_some_and(|k| k.1 == 1) + && self.int_k(f).is_some_and(|k| k.1 == 0) + { + return Some(c); + } + if inner { + self.insts[i as usize].op = Op::Select(c, t, f); + *changed = true; + } + None + } + Op::Cast(op, x) => { + let from = self.type_of(x); + let through = match x { + V::Inst(y) => match self.insts[y as usize].op { + Op::Cast(op2, z) => Some((op2, z)), + _ => None, + }, + _ => None, + }; + match op { + Cast::Bitcast => { + if from == ty { + return Some(x); + } + // There and back: the bits are the same. + if let Some((Cast::Bitcast, z)) = through + && self.type_of(z) == ty + { + return Some(z); + } + let V::Const(c) = x else { return None }; + let to_float = matches!(self.types[ty.0 as usize], TypeDef::Float); + match self.consts[c as usize].1 { + Const::Int(bits) if to_float && self.int_bits(from) == Some(32) => { + Some(self.f32(bits as u32)) + } + Const::Float(bits) if self.int_bits(ty) == Some(32) => { + Some(self.int_const(ty, i64::from(bits as i32))) + } + _ => None, + } + } + Cast::ZExt | Cast::SExt | Cast::Trunc => { + let to = self.int_bits(ty)?; + if let Some((bits, k)) = self.int_k(x) { + let k = if op == Cast::SExt { + signed(bits, k) as u64 + } else { + k + }; + return Some(self.k(ty, to, k)); + } + // Widened and narrowed again. + if op == Cast::Trunc + && let Some((Cast::ZExt | Cast::SExt, z)) = through + && self.type_of(z) == ty + { + return Some(z); + } + None + } + _ => None, + } + } + _ => None, + } + } + + /// What kind of instruction `i` is for merging. + fn class(&self, effects: &[Effect], i: u32) -> Effect { + match &self.insts[i as usize].op { + Op::Bin(..) + | Op::Cast(..) + | Op::Cmp(..) + | Op::Select(..) + | Op::Extract(..) + | Op::Gep(..) => Effect::Pure, + Op::Load(p) => { + // A constant table reads the same whatever is stored. + let base = match *p { + V::Inst(g) => match &self.insts[g as usize].op { + Op::Gep(_, base, _) => *base, + _ => *p, + }, + _ => *p, + }; + match base { + V::Global(g) if self.globals[g as usize].init.is_some() => Effect::Pure, + _ => Effect::Reads, + } + } + Op::Store(..) | Op::AtomicRmw(..) | Op::CmpXchg(..) => Effect::Writes, + Op::Phi(_) => Effect::Lanes, + Op::Call(f, _) => effects[*f as usize], + } + } + + fn key(&self, i: u32) -> Option { + let inst = &self.insts[i as usize]; + Some(match &inst.op { + Op::Bin(op, a, b) => { + // Integer sums, products and bit operations whichever way + // round; float ones as written (which NaN an operation of + // two NaNs gives is the hardware's choice by operand). + let commutes = matches!(op, Bin::Add | Bin::Mul | Bin::And | Bin::Or | Bin::Xor) + && self.int_bits(inst.ty).is_some(); + let (a, b) = if commutes && b < a { + (*b, *a) + } else { + (*a, *b) + }; + Key::Bin(*op as u8, a, b) + } + Op::Cast(op, v) => Key::Cast(*op as u8, inst.ty, *v), + Op::Cmp(p, a, b) => Key::Cmp(*p, *a, *b), + Op::Select(c, t, f) => Key::Select(*c, *t, *f), + Op::Extract(a, n) => Key::Extract(*a, *n), + Op::Call(f, args) => Key::Call(*f, args.clone()), + Op::Gep(ty, p, idx) => Key::Gep(*ty, *p, idx.clone()), + Op::Load(p) => Key::Load(*p), + _ => return None, + }) + } + + /// [`FOLD`], [`REUSE`], [`FACTS`] and [`LOADS`]: one walk over the + /// dominator tree. Returns whether anything changed. + fn merge(&mut self, passes: u32) -> bool { + if self.blocks.is_empty() { + return false; + } + let effects = self.effects(); + let tree = self.dominator_tree(); + let mut repl: Vec> = vec![None; self.insts.len()]; + let mut changed = false; + // Joins of one value: until none is left (one gone can leave + // another with one value). + if passes & FOLD != 0 { + let mut again = true; + while again { + again = false; + for &b in &tree.order { + for &p in &self.blocks[b].phis { + if repl[p as usize].is_some() { + continue; + } + let Op::Phi(incoming) = &self.insts[p as usize].op else { + continue; + }; + let mut one = None; + let mut same = true; + for &(v, _) in incoming { + let v = resolve(&repl, v); + if v == V::Inst(p) { + continue; + } + match one { + None => one = Some(v), + Some(o) if o == v => {} + Some(_) => same = false, + } + } + if let (true, Some(v)) = (same, one) { + repl[p as usize] = Some(v); + again = true; + changed = true; + } + } + } + } + } + // The values every path to the block being walked has computed + // (those of the blocks above it in the tree, and its own so far). + let mut known: HashMap = HashMap::new(); + // The reads of the block being walked since its last store. + let mut read: HashMap = HashMap::new(); + let mut facts = Facts::default(); + let (yes, no) = (self.bool(true), self.bool(false)); + enum Step { + Enter(usize), + Leave(Vec, Learned), + } + let mut steps = vec![Step::Enter(0)]; + while let Some(step) = steps.pop() { + let b = match step { + Step::Enter(b) => b, + Step::Leave(keys, learned) => { + for k in keys { + known.remove(&k); + } + for v in learned.bits { + facts.bits.remove(&v); + } + for k in learned.compares { + facts.compares.remove(&k); + } + continue; + } + }; + let mut added = Vec::new(); + // Reached from one block alone, by one side of its branch: the + // condition is that side's, here and in every block below. + let mut learned = Learned::default(); + if passes & FACTS != 0 + && let [p] = tree.preds[b][..] + && let Some(Term::CondBr(c, t, f)) = self.blocks[p].term + && t != f + { + self.learn(resolve(&repl, c), b == t, &mut facts, &mut learned, 8); + } + let known_bit = |facts: &Facts, v: V| match facts.bits.get(&v) { + Some(true) => yes, + Some(false) => no, + None => v, + }; + read.clear(); + // Two joins of the same values from the same blocks are one. + if passes & REUSE != 0 && self.blocks[b].phis.len() > 1 { + let mut joins: HashMap, V> = HashMap::new(); + for &p in &self.blocks[b].phis { + if repl[p as usize].is_some() { + continue; + } + let ty = self.insts[p as usize].ty; + let Op::Phi(incoming) = &self.insts[p as usize].op else { + continue; + }; + let mut key: Vec<(usize, V)> = incoming + .iter() + .map(|&(v, from)| (from, resolve(&repl, v))) + .collect(); + key.sort(); + // The type too: an undefined value of one type is not + // that of another. + key.push((ty.0 as usize, V::Global(u32::MAX))); + match joins.get(&key) { + Some(&first) => { + repl[p as usize] = Some(first); + changed = true; + } + None => { + joins.insert(key, V::Inst(p)); + } + } + } + } + let body = std::mem::take(&mut self.blocks[b].body); + let mut kept = Vec::with_capacity(body.len()); + for i in body { + map_operands(&mut self.insts[i as usize].op, |v| { + let v = resolve(&repl, v); + let bit = known_bit(&facts, v); + changed |= bit != v; + bit + }); + if let Op::Cmp(p, x, y) = self.insts[i as usize].op + && let Some(&holds) = facts.compares.get(&(p, x, y)) + { + repl[i as usize] = Some(if holds { yes } else { no }); + changed = true; + continue; + } + if passes & FOLD != 0 + && let Some(v) = self.simplify(i, &mut changed) + { + repl[i as usize] = Some(v); + changed = true; + continue; + } + let class = self.class(&effects, i); + if passes & REUSE != 0 + && class == Effect::Pure + && let Some(key) = self.key(i) + { + if let Some(&first) = known.get(&key) { + repl[i as usize] = Some(first); + changed = true; + continue; + } + known.insert(key.clone(), V::Inst(i)); + added.push(key); + } + // Reads of memory, and wave operations (the same lanes run + // the whole block): the block's own earlier one. + if passes & LOADS != 0 + && matches!(class, Effect::Reads | Effect::Lanes) + && let Some(key) = self.key(i) + { + if let Some(&first) = read.get(&key) { + repl[i as usize] = Some(first); + changed = true; + continue; + } + read.insert(key, V::Inst(i)); + } + if class == Effect::Writes { + read.clear(); + } + kept.push(i); + } + self.blocks[b].body = kept; + if let Some(Term::CondBr(c, t, f)) = self.blocks[b].term { + let c = known_bit(&facts, resolve(&repl, c)); + self.blocks[b].term = Some(Term::CondBr(c, t, f)); + } + steps.push(Step::Leave(added, learned)); + for &c in tree.children[b].iter().rev() { + steps.push(Step::Enter(c)); + } + } + if !changed { + return false; + } + // Everything that read a replaced value reads its replacement + // (joins read values from blocks walked after them). + for blk in &mut self.blocks { + blk.phis.retain(|&p| repl[p as usize].is_none()); + if let Some(Term::CondBr(c, t, f)) = blk.term { + blk.term = Some(Term::CondBr(resolve(&repl, c), t, f)); + } + } + let (blocks, insts) = (&self.blocks, &mut self.insts); + for blk in blocks { + for &i in blk.phis.iter().chain(&blk.body) { + map_operands(&mut insts[i as usize].op, |v| resolve(&repl, v)); + } + } + true + } + + /// [`FOLD`]: a branch on a constant goes one way. The side not taken + /// loses the branching block's values at its joins, and so do the joins + /// of blocks that nothing reaches any more. Returns whether a branch + /// changed. + fn prune(&mut self) -> bool { + let mut changed = false; + for b in 0..self.blocks.len() { + let Some(Term::CondBr(c, t, f)) = self.blocks[b].term else { + continue; + }; + // Both sides one block: two edges into it, left as they are. + if t == f { + continue; + } + let Some((_, k)) = self.int_k(c) else { + continue; + }; + let (taken, not) = if k != 0 { (t, f) } else { (f, t) }; + self.blocks[b].term = Some(Term::Br(taken)); + changed = true; + for n in 0..self.blocks[not].phis.len() { + let p = self.blocks[not].phis[n]; + if let Op::Phi(incoming) = &mut self.insts[p as usize].op { + incoming.retain(|&(_, from)| from != b); + } + } + } + if !changed { + return false; + } + let reached = self.reached(); + let (blocks, insts) = (&self.blocks, &mut self.insts); + for (_, blk) in blocks.iter().enumerate().filter(|(b, _)| reached[*b]) { + for &p in &blk.phis { + if let Op::Phi(incoming) = &mut insts[p as usize].op { + incoming.retain(|&(_, from)| reached[from]); + } + } + } + true + } + + /// Whether instruction `i` must stay whatever reads it. + fn has_effect(&self, effects: &[Effect], i: u32) -> bool { + match &self.insts[i as usize].op { + Op::Store(..) | Op::AtomicRmw(..) | Op::CmpXchg(..) => true, + Op::Call(f, _) => effects[*f as usize] == Effect::Writes, + _ => false, + } + } + + /// [`DEAD`]: keeps the instructions with an effect, the branch + /// conditions, and what they read, transitively; the rest leave their + /// blocks. Blocks no branch reaches are emptied (they are not written). + fn drop_dead(&mut self) { + let effects = self.effects(); + let reached = self.reached(); + let mut live = vec![false; self.insts.len()]; + let mut work: Vec = Vec::new(); + let mark = |live: &mut [bool], work: &mut Vec, v: V| { + if let V::Inst(i) = v + && !live[i as usize] + { + live[i as usize] = true; + work.push(i); + } + }; + for (b, blk) in self.blocks.iter().enumerate() { + if !reached[b] { + continue; + } + for &i in &blk.body { + if self.has_effect(&effects, i) { + mark(&mut live, &mut work, V::Inst(i)); + } + } + if let Some(Term::CondBr(c, ..)) = blk.term { + mark(&mut live, &mut work, c); + } + } + while let Some(i) = work.pop() { + for_each_operand(&self.insts[i as usize].op, |v| { + mark(&mut live, &mut work, v) + }); + } + for (b, blk) in self.blocks.iter_mut().enumerate() { + if reached[b] { + blk.body.retain(|&i| live[i as usize]); + blk.phis.retain(|&i| live[i as usize]); + } else { + blk.body.clear(); + blk.phis.clear(); + } + } + self.drop_unused_functions(); + self.drop_unused_tables(); + } + + /// See [`Usage`]: over the blocks reached from the entry. + pub(crate) fn usage(&self) -> Usage { + let mut u = Usage::default(); + let reached = self.reached(); + let wide = |ty: Ty| self.types[ty.0 as usize] == TypeDef::Int(64); + // The first field of a handle's annotation: its kind, with the UAV + // bit; the second: the component type and count. + let annotation = |h: V| -> Option<(i64, i64)> { + let V::Inst(a) = h else { return None }; + let Op::Call(f, args) = &self.insts[a as usize].op else { + return None; + }; + if self.funcs[*f as usize].name != "dx.op.annotateHandle" { + return None; + } + let V::Const(props) = *args.get(2)? else { + return None; + }; + let Const::Aggregate(fields) = &self.consts[props as usize].1 else { + return None; + }; + match ( + &self.consts[fields[0] as usize].1, + &self.consts[fields[1] as usize].1, + ) { + (Const::Int(kind), Const::Int(components)) => Some((*kind, *components)), + _ => None, + } + }; + for (_, blk) in self.blocks.iter().enumerate().filter(|(b, _)| reached[*b]) { + for &i in blk.phis.iter().chain(&blk.body) { + let inst = &self.insts[i as usize]; + u.int64 |= wide(inst.ty); + for_each_operand(&inst.op, |v| u.int64 |= wide(self.type_of(v))); + let Op::Call(f, args) = &inst.op else { + continue; + }; + let name = self.funcs[*f as usize].name.as_str(); + let name = name.strip_prefix("dx.op.").unwrap_or(name); + if name.starts_with("wave") || name.starts_with("quad") { + u.wave_ops = true; + } else if name == "createHandleFromHeap" { + match args.get(2).and_then(|&s| self.int_k(s)) { + Some((_, 0)) => u.heap_views = true, + _ => u.heap_samplers = true, + } + } else if name.starts_with("atomic") && name.ends_with(".i64") { + u.atomic64 = true; + } else if name.starts_with("textureLoad") || name.starts_with("bufferLoad") { + u.typed_uav_loads |= args.get(1).and_then(|&h| annotation(h)).is_none_or( + |(kind, components)| kind & 0x1000 != 0 && components >> 8 & 0xff > 1, + ); + } + } + } + u + } + + /// A constant table no remaining load reads leaves the module (the + /// validator refuses an internal declaration nothing uses). Shared + /// memory stays declared whether it is read or not. + fn drop_unused_tables(&mut self) { + let mut used: Vec = self.globals.iter().map(|g| g.init.is_none()).collect(); + if used.iter().all(|&u| u) { + return; + } + for blk in &self.blocks { + for &i in blk.phis.iter().chain(&blk.body) { + for_each_operand(&self.insts[i as usize].op, |v| { + if let V::Global(g) = v { + used[g as usize] = true; + } + }); + } + } + for md in &self.mds { + if let MdDef::Value(_, V::Global(g)) = md { + used[*g as usize] = true; + } + } + if used.iter().all(|&u| u) { + return; + } + let mut new = vec![u32::MAX; used.len()]; + for (next, (old, _)) in used.iter().enumerate().filter(|u| *u.1).enumerate() { + new[old] = next as u32; + } + let mut old = 0; + self.globals.retain(|_| { + old += 1; + used[old - 1] + }); + let renumber = |v: V| match v { + V::Global(g) if used[g as usize] => V::Global(new[g as usize]), + v => v, + }; + for inst in &mut self.insts { + map_operands(&mut inst.op, renumber); + } + for md in &mut self.mds { + if let MdDef::Value(_, v) = md { + *v = renumber(*v); + } + } + } + + /// Declarations no remaining call names leave the module (the validator + /// refuses an external function nothing uses); the others keep their + /// order, so `main` stays function 0. + fn drop_unused_functions(&mut self) { + let mut used: Vec = self.funcs.iter().map(|f| f.body).collect(); + for blk in &self.blocks { + for &i in blk.phis.iter().chain(&blk.body) { + if let Op::Call(f, _) = self.insts[i as usize].op { + used[f as usize] = true; + } + } + } + for md in &self.mds { + if let MdDef::Value(_, V::Func(f)) = md { + used[*f as usize] = true; + } + } + if used.iter().all(|&u| u) { + return; + } + let mut new = vec![u32::MAX; used.len()]; + for (next, (old, _)) in used.iter().enumerate().filter(|u| *u.1).enumerate() { + new[old] = next as u32; + } + let mut old = 0; + self.funcs.retain(|_| { + old += 1; + used[old - 1] + }); + self.func_ids = self + .funcs + .iter() + .enumerate() + .map(|(i, f)| (f.name.clone(), i as u32)) + .collect(); + // Instructions that left their block keep a stale number: nothing + // reads them again. + for inst in &mut self.insts { + if let Op::Call(f, _) = &mut inst.op + && used[*f as usize] + { + *f = new[*f as usize]; + } + } + for md in &mut self.mds { + if let MdDef::Value(_, V::Func(f)) = md { + *f = new[*f as usize]; + } + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + /// `main` with one block and a function of each kind of effect. + struct Kit { + m: Module, + b: usize, + pure: V, + reads: V, + writes: V, + } + + fn kit() -> Kit { + let mut m = Module::default(); + let i32t = m.int(32); + let void = m.void(); + let fty = m.func_ty(i32t, vec![i32t, i32t]); + m.ptr(fty); + let pure = m.function("dx.op.binary.i32", fty, Some(Attr::ReadNone), false); + let reads = m.function("dx.op.bufferLoad.i32", fty, Some(Attr::ReadOnly), false); + let writes = m.function("dx.op.bufferStore.i32", fty, Some(Attr::NoUnwind), false); + let main_ty = m.func_ty(void, vec![]); + m.ptr(main_ty); + m.function("main", main_ty, None, true); + let b = m.new_block(); + Kit { + m, + b, + pure, + reads, + writes, + } + } + + fn body(m: &Module, b: usize) -> usize { + m.blocks[b].body.len() + } + + #[test] + fn unread_results_without_effect_are_dropped() { + let Kit { + mut m, + b, + pure, + reads, + writes, + } = kit(); + let (one, two) = (m.i32(1), m.i32(2)); + let used = m.call(b, reads, vec![one, two]); + let dead = m.call(b, reads, vec![two, one]); + let chain = m.bin(b, Bin::Add, dead, one); + let _unread = m.call(b, pure, vec![chain, two]); + // A store's result is unread and stays, with what it reads. + let kept = m.bin(b, Bin::Add, used, two); + m.call(b, writes, vec![kept, one]); + m.terminate(b, Term::Ret); + m.optimise(DEAD); + assert_eq!(body(&m, b), 3, "the load, the add and the store"); + m.write(); + } + + #[test] + fn branch_conditions_and_phi_cycles() { + let Kit { + mut m, + b, + reads, + writes, + .. + } = kit(); + let i32t = m.int(32); + let (zero, one) = (m.i32(0), m.i32(1)); + let (head, exit) = (m.new_block(), m.new_block()); + m.terminate(b, Term::Br(head)); + // A counter that decides the branch, and a register that only + // feeds itself round the loop. + let count = m.phi(head, i32t); + let idle = m.phi(head, i32t); + let next = m.bin(head, Bin::Add, count, one); + let idle_next = m.call(head, reads, vec![idle, one]); + let more = m.cmp(head, pred::IULT, next, one); + m.terminate(head, Term::CondBr(more, head, exit)); + m.set_phi(count, vec![(zero, b), (next, head)]); + m.set_phi(idle, vec![(zero, b), (idle_next, head)]); + m.call(exit, writes, vec![zero, one]); + m.terminate(exit, Term::Ret); + m.optimise(DEAD); + assert_eq!(m.blocks[head].phis.len(), 1, "the counter"); + assert_eq!(body(&m, head), 2, "the step and the test"); + assert_eq!(body(&m, exit), 1); + m.write(); + } + + #[test] + fn wave_operations_have_no_effect_of_their_own() { + let mut k = kit(); + let i32t = k.m.int(32); + let fty = k.m.func_ty(i32t, vec![i32t, i32t]); + let first = k.m.function( + "dx.op.waveReadLaneFirst.i32", + fty, + Some(Attr::NoUnwind), + false, + ); + let barrier = + k.m.function("dx.op.barrier", fty, Some(Attr::NoDuplicate), false); + let one = k.m.i32(1); + k.m.call(k.b, first, vec![one, one]); + k.m.call(k.b, barrier, vec![one, one]); + k.m.terminate(k.b, Term::Ret); + k.m.optimise(DEAD); + assert_eq!(body(&k.m, k.b), 1, "the barrier"); + // The declarations nothing calls any more are gone, and the call + // that stayed names its function by the new number. + let names: Vec<&str> = k.m.funcs.iter().map(|f| f.name.as_str()).collect(); + assert_eq!(names, ["main", "dx.op.barrier"]); + let Op::Call(f, _) = k.m.insts[k.m.blocks[k.b].body[0] as usize].op else { + panic!("a call"); + }; + assert_eq!(k.m.funcs[f as usize].name, "dx.op.barrier"); + k.m.write(); + } + + /// The operands of each store left in block `b`. + fn stores(m: &Module, b: usize) -> Vec> { + m.blocks[b] + .body + .iter() + .filter_map(|&i| match &m.insts[i as usize].op { + Op::Call(g, args) if m.funcs[*g as usize].name.contains("Store") => { + Some(args.clone()) + } + _ => None, + }) + .collect() + } + + #[test] + fn constants_and_identities_fold() { + let Kit { + mut m, + b, + reads, + writes, + .. + } = kit(); + let (i32t, f32t) = (m.int(32), m.float()); + let (zero, one, all) = (m.i32(0), m.i32(1), m.i32(u32::MAX)); + let x = m.call(b, reads, vec![one, one]); + // x + 0, -1 & x, x >> 0, x * 1, x | x: all x. + let a = m.bin(b, Bin::Add, x, zero); + let a = m.bin(b, Bin::And, all, a); + let a = m.bin(b, Bin::LShr, a, zero); + let a = m.bin(b, Bin::Mul, a, one); + let a = m.bin(b, Bin::Or, a, a); + // There and back. + let f = m.cast(b, Cast::Bitcast, a, f32t); + let a = m.cast(b, Cast::Bitcast, f, i32t); + // Constants: (262168 >> 16) & 127 = 4, 7 & 31 = 7, -8 >>s 1 = -4. + let k = m.i32(262168); + let sixteen = m.i32(16); + let k = m.bin(b, Bin::LShr, k, sixteen); + let k127 = m.i32(127); + let k = m.bin(b, Bin::And, k, k127); + let minus8 = m.i32(-8i32 as u32); + let s = m.bin(b, Bin::AShr, minus8, one); + // A shift by the width is left alone. + let k32 = m.i32(32); + let wide = m.bin(b, Bin::Shl, one, k32); + // A select between a value and itself, and on a constant. + let c = m.cmp(b, pred::IULT, zero, one); + let sel = m.select(b, c, a, wide); + let same = m.select(b, c, sel, sel); + m.call(b, writes, vec![same, k]); + m.call(b, writes, vec![s, wide]); + m.terminate(b, Term::Ret); + m.optimise(FOLD | DEAD); + assert_eq!(body(&m, b), 4, "the read, the wide shift and two stores"); + let four = m.i32(4); + let minus4 = m.i32(-4i32 as u32); + let stores = stores(&m, b); + assert_eq!(stores, [vec![x, four], vec![minus4, wide]]); + m.write(); + } + + #[test] + fn float_arithmetic_is_not_folded() { + let Kit { + mut m, b, writes, .. + } = kit(); + let f32t = m.float(); + let fty = m.func_ty(f32t, vec![f32t, f32t]); + let input = m.function("dx.op.loadInput.f32", fty, Some(Attr::ReadNone), false); + let (zero, one, two) = (m.f32(0), m.f32(1.0f32.to_bits()), m.f32(2.0f32.to_bits())); + let x = m.call(b, input, vec![zero, zero]); + let y = m.call(b, input, vec![one, one]); + let a = m.bin(b, Bin::Add, x, zero); + let p = m.bin(b, Bin::Mul, a, one); + // The same sum the other way round is another instruction. + let xy = m.bin(b, Bin::Add, x, y); + let yx = m.bin(b, Bin::Add, y, x); + // Constants compare here: 1 < 2, and nothing equals a NaN. + let nan = m.f32(f32::NAN.to_bits()); + let lt = m.cmp(b, pred::OLT, one, two); + let eq = m.cmp(b, pred::OEQ, nan, nan); + let une = m.cmp(b, pred::UNE, nan, one); + let sel = m.select(b, lt, xy, yx); + let sel = m.select(b, eq, p, sel); + let sel = m.select(b, une, sel, p); + m.call(b, writes, vec![sel, p]); + m.terminate(b, Term::Ret); + m.optimise(ALL); + // Two inputs, x + 0.0, * 1.0, x + y and the store: y + x and the + // selects are gone. + assert_eq!(body(&m, b), 6); + assert_eq!(stores(&m, b), [[xy, p]]); + m.write(); + } + + /// entry: `c = x < y`, branch to `then` or `other`, which join. + struct Diamond { + k: Kit, + x: V, + y: V, + c: V, + then: usize, + other: usize, + join: usize, + } + + fn diamond() -> Diamond { + let mut k = kit(); + let (one, two) = (k.m.i32(1), k.m.i32(2)); + let x = k.m.call(k.b, k.reads, vec![one, one]); + let y = k.m.call(k.b, k.reads, vec![two, two]); + let c = k.m.cmp(k.b, pred::IULT, x, y); + let (then, other, join) = (k.m.new_block(), k.m.new_block(), k.m.new_block()); + k.m.terminate(k.b, Term::CondBr(c, then, other)); + k.m.terminate(then, Term::Br(join)); + k.m.terminate(other, Term::Br(join)); + k.m.terminate(join, Term::Ret); + Diamond { + k, + x, + y, + c, + then, + other, + join, + } + } + + #[test] + fn a_value_is_reused_below_its_block_and_not_beside_it() { + let Diamond { + k: + Kit { + mut m, + b, + pure, + writes, + .. + }, + x, + y, + then, + other, + join, + .. + } = diamond(); + // The entry's value again in a branch; a branch's value again in + // the other branch and in the join (neither is on every path). + let top = m.call(b, pure, vec![x, y]); + m.call(b, writes, vec![top, top]); + let again = m.call(then, pure, vec![x, y]); + let side = m.bin(then, Bin::Add, y, x); + m.call(then, writes, vec![again, side]); + let beside = m.bin(other, Bin::Add, x, y); + m.call(other, writes, vec![beside, beside]); + let after = m.bin(join, Bin::Add, x, y); + m.call(join, writes, vec![after, after]); + m.optimise(REUSE); + assert_eq!(stores(&m, then), [[top, side]]); + assert_eq!(body(&m, then), 2); + assert_eq!(body(&m, other), 2); + assert_eq!(body(&m, join), 2); + m.write(); + } + + #[test] + fn a_branch_taken_says_what_its_condition_is() { + let Diamond { + k: + Kit { + mut m, + b, + reads, + writes, + .. + }, + x, + y, + c, + then, + other, + join, + } = diamond(); + let three = m.i32(3); + let d = m.call(b, reads, vec![three, three]); + let d = m.cmp(b, pred::NE, d, three); + let both = m.bin(b, Bin::And, c, d); + // Behind the branch: the condition again (a guard), its opposite + // comparison, and a guarded write. + let guard = m.bin(then, Bin::And, c, d); + let old = m.select(then, guard, x, y); + let not = m.cmp(then, pred::IUGE, x, y); + let new = m.select(then, not, y, old); + m.call(then, writes, vec![new, new]); + let kept = m.select(other, c, x, y); + m.call(other, writes, vec![kept, kept]); + // After the join nothing is known. + let open = m.select(join, c, x, y); + m.call(join, writes, vec![open, open]); + m.optimise(FOLD | FACTS); + // then: select(d, x, y) and the store; other: y is stored. + assert_eq!(body(&m, then), 2); + let V::Inst(sel) = stores(&m, then)[0][0] else { + panic!() + }; + assert!(matches!(m.insts[sel as usize].op, Op::Select(g, a, z) if (g, a, z) == (d, x, y))); + assert_eq!(stores(&m, other), [[y, y]]); + assert_eq!(body(&m, join), 2); + let _ = both; + m.write(); + + // Both terms of an `and` that held hold behind it. + let Diamond { + k: + Kit { + mut m, + b, + reads, + writes, + .. + }, + x, + y, + c, + .. + } = diamond(); + let three = m.i32(3); + let d = m.call(b, reads, vec![three, three]); + let d = m.cmp(b, pred::NE, d, three); + let both = m.bin(b, Bin::And, c, d); + let (inner, out) = (m.new_block(), m.new_block()); + m.terminate(b, Term::CondBr(both, inner, out)); + let a = m.select(inner, c, x, y); + let z = m.select(inner, d, a, y); + m.call(inner, writes, vec![z, z]); + m.terminate(inner, Term::Br(out)); + // Where the `and` did not hold either term may. + let w = m.select(out, d, x, y); + m.call(out, writes, vec![w, w]); + m.terminate(out, Term::Ret); + m.optimise(FOLD | FACTS); + assert_eq!(stores(&m, inner), [[x, x]]); + assert_eq!(body(&m, out), 2); + m.write(); + } + + #[test] + fn a_branch_on_a_constant_goes_one_way() { + let Diamond { + k: Kit { + mut m, b, writes, .. + }, + x, + y, + c, + then, + other, + join, + } = diamond(); + let i32t = m.int(32); + // Behind the branch the same test again: its other side is never + // run, and the join behind it has one value. + let (deep, never, meet) = (m.new_block(), m.new_block(), m.new_block()); + m.terminate(then, Term::CondBr(c, deep, never)); + m.terminate(deep, Term::Br(meet)); + m.call(never, writes, vec![y, y]); + m.terminate(never, Term::Br(meet)); + let p = m.phi(meet, i32t); + m.set_phi(p, vec![(x, deep), (y, never)]); + m.call(meet, writes, vec![p, p]); + m.terminate(meet, Term::Br(join)); + let q = m.phi(join, i32t); + m.set_phi(q, vec![(p, meet), (y, other)]); + m.call(join, writes, vec![q, q]); + m.optimise(ALL); + assert!(matches!(m.blocks[then].term, Some(Term::Br(t)) if t == deep)); + assert_eq!(stores(&m, meet), [[x, x]]); + assert!(m.blocks[meet].phis.is_empty()); + assert_eq!(body(&m, never), 0, "emptied: nothing reaches it"); + let Op::Phi(incoming) = &m.insts[m.blocks[join].phis[0] as usize].op else { + panic!() + }; + assert_eq!(incoming, &vec![(x, meet), (y, other)]); + let _ = b; + m.write(); + } + + #[test] + fn a_read_is_reused_within_its_block_until_a_store() { + let Diamond { + k: + Kit { + mut m, + b, + reads, + writes, + .. + }, + x, + y, + then, + .. + } = diamond(); + let i32t = m.int(32); + // The entry reads (1, 1) for x: again in the entry it is x; in the + // next block it is read again. + let one = m.i32(1); + let again = m.call(b, reads, vec![one, one]); + m.call(b, writes, vec![again, y]); + let after = m.call(b, reads, vec![one, one]); + let twice = m.call(b, reads, vec![one, one]); + let sum = m.bin(b, Bin::Add, after, twice); + m.call(b, writes, vec![sum, sum]); + let below = m.call(then, reads, vec![one, one]); + m.call(then, writes, vec![below, below]); + // A constant buffer cannot change: one load for the function. + let cfty = m.func_ty(i32t, vec![i32t, i32t]); + let cb = m.function( + "dx.op.cbufferLoadLegacy.i32", + cfty, + Some(Attr::ReadOnly), + false, + ); + let top = m.call(b, cb, vec![one, one]); + m.call(b, writes, vec![top, top]); + let under = m.call(then, cb, vec![one, one]); + m.call(then, writes, vec![under, under]); + m.optimise(REUSE | LOADS); + let stores = stores(&m, b); + assert_eq!(stores[0], [x, y], "the second read is the first"); + let V::Inst(sum) = stores[1][0] else { panic!() }; + assert!( + matches!(m.insts[sum as usize].op, Op::Bin(Bin::Add, a, z) if a == after && z == after), + "read again after the store, once" + ); + assert_eq!(stores[2], [top, top]); + assert_eq!( + super::tests::stores(&m, then), + [vec![below, below], vec![top, top]] + ); + m.write(); + } + + #[test] + fn a_join_of_one_value_and_two_equal_joins() { + let Diamond { + k: Kit { mut m, writes, .. }, + x, + y, + then, + other, + join, + .. + } = diamond(); + let i32t = m.int(32); + let one = m.phi(join, i32t); + m.set_phi(one, vec![(x, then), (x, other)]); + let p = m.phi(join, i32t); + m.set_phi(p, vec![(x, then), (y, other)]); + let q = m.phi(join, i32t); + m.set_phi(q, vec![(y, other), (x, then)]); + m.call(join, writes, vec![one, p]); + let sum = m.bin(join, Bin::Add, p, q); + m.call(join, writes, vec![sum, q]); + m.optimise(FOLD | REUSE); + assert_eq!( + m.blocks[join].phis, + [match p { + V::Inst(i) => i, + _ => unreachable!(), + }] + ); + let stores = stores(&m, join); + assert_eq!(stores[0], [x, p]); + assert_eq!(stores[1][1], p); + m.write(); + } + + // ---- the passes against an interpreter, on random programs ---- + + /// Runs `m` on `inputs`: the stores it makes, in order (and how it + /// ended). Reads a value before its definition ran: a panic. + fn run(m: &Module, inputs: &[u32]) -> Vec<(String, Vec)> { + let mut vals: Vec> = vec![None; m.insts.len()]; + let mut memory = [0u64; 16]; + let mut trace = Vec::new(); + let eval = |vals: &[Option], v: V| -> u64 { + match v { + V::Inst(i) => vals[i as usize].expect("a value defined before its use"), + V::Const(c) => { + match (&m.consts[c as usize].1, m.int_bits(m.consts[c as usize].0)) { + (Const::Int(x), Some(bits)) => *x as u64 & mask(bits), + (Const::Float(bits), _) => u64::from(*bits), + _ => 0, + } + } + _ => panic!("a global or function as a value"), + } + }; + let (mut b, mut from) = (0usize, usize::MAX); + for _ in 0..4000 { + let blk = &m.blocks[b]; + // Joins take their values together, before any is assigned. + let joined: Vec<(u32, u64)> = blk + .phis + .iter() + .map(|&p| { + let Op::Phi(incoming) = &m.insts[p as usize].op else { + panic!("a join") + }; + let v = incoming + .iter() + .find(|x| x.1 == from) + .expect("a value for the edge taken"); + (p, eval(&vals, v.0)) + }) + .collect(); + for (p, x) in joined { + vals[p as usize] = Some(x); + } + for &i in &blk.body { + let inst = &m.insts[i as usize]; + let bits = m.int_bits(inst.ty); + let float = |x: u64| f32::from_bits(x as u32); + let r = match &inst.op { + Op::Bin(op, x, y) => { + let (x, y) = (eval(&vals, *x), eval(&vals, *y)); + match bits { + Some(bits) => { + let r = match op { + Bin::Add => x.wrapping_add(y), + Bin::Sub => x.wrapping_sub(y), + Bin::Mul => x.wrapping_mul(y), + Bin::And => x & y, + Bin::Or => x | y, + Bin::Xor => x ^ y, + Bin::Shl => x << y, + Bin::LShr => x >> y, + Bin::AShr => (signed(bits, x) >> y) as u64, + _ => panic!("no divisions here"), + }; + r & mask(bits) + } + None => { + let (x, y) = (float(x), float(y)); + let r = match op { + Bin::Add => x + y, + Bin::Sub => x - y, + _ => x * y, + }; + u64::from(r.to_bits()) + } + } + } + Op::Cmp(p, x, y) => { + let wide = m.int_bits(m.type_of(*x)); + let (x, y) = (eval(&vals, *x), eval(&vals, *y)); + let holds = match wide { + Some(bits) => { + let (sx, sy) = (signed(bits, x), signed(bits, y)); + match *p { + pred::EQ => x == y, + pred::NE => x != y, + pred::IUGT => x > y, + pred::IUGE => x >= y, + pred::IULT => x < y, + pred::IULE => x <= y, + pred::SGT => sx > sy, + pred::SGE => sx >= sy, + pred::SLT => sx < sy, + _ => sx <= sy, + } + } + None => { + let (x, y) = (float(x), float(y)); + if x.is_nan() || y.is_nan() { + p & 8 != 0 + } else { + (p & 1 != 0 && x == y) + || (p & 2 != 0 && x > y) + || (p & 4 != 0 && x < y) + } + } + }; + u64::from(holds) + } + Op::Select(c, t, f) => { + if eval(&vals, *c) != 0 { + eval(&vals, *t) + } else { + eval(&vals, *f) + } + } + Op::Cast(op, x) => { + let from_bits = m.int_bits(m.type_of(*x)); + let x = eval(&vals, *x); + match (op, from_bits, bits) { + (Cast::Bitcast, _, _) => x, + (Cast::ZExt, _, _) => x, + (Cast::SExt, Some(f), Some(t)) => signed(f, x) as u64 & mask(t), + (Cast::Trunc, _, Some(t)) => x & mask(t), + _ => panic!("a cast the generator does not make"), + } + } + Op::Call(f, args) => { + let a: Vec = args.iter().map(|&v| eval(&vals, v)).collect(); + let name = m.funcs[*f as usize].name.as_str(); + match name { + "dx.op.loadInput.i32" => { + u64::from(inputs[(a[0] ^ a[1]) as usize % inputs.len()]) + } + "dx.op.binary.i32" => a[0].min(a[1]), + "dx.op.cbufferLoadLegacy.i32" => u64::from( + inputs[a[0] as usize % inputs.len()].rotate_left(a[1] as u32 & 31), + ), + "dx.op.bufferLoad.i32" => memory[(a[0] ^ a[1]) as usize % 16], + "dx.op.waveReadLaneFirst.i32" => a[0] ^ a[1], + _ => { + memory[a[0] as usize % 16] = a[1]; + trace.push((name.to_owned(), a)); + 0 + } + } + } + _ => panic!("an instruction the generator does not make"), + }; + vals[i as usize] = Some(r); + } + from = b; + b = match blk.term.expect("a terminator") { + Term::Ret => { + trace.push(("ret".into(), Vec::new())); + return trace; + } + Term::Br(t) => t, + Term::CondBr(c, t, f) => { + if eval(&vals, c) != 0 { + t + } else { + f + } + } + }; + } + trace.push(("still running".into(), Vec::new())); + trace + } + + /// A random structured program over a few registers, as the lowering + /// makes them: every register joined at every join, conditions tested + /// again behind their branch, values computed again. + struct Gen { + k: Kit, + rng: u64, + regs: Vec, + conds: Vec, + cur: usize, + input: V, + table: V, + wave: V, + /// The operands of the block's last read (to read the place again, + /// and to store to it). + last: Option<(V, V)>, + } + + impl Gen { + fn next(&mut self, n: u64) -> u64 { + self.rng ^= self.rng << 13; + self.rng ^= self.rng >> 7; + self.rng ^= self.rng << 17; + (self.rng >> 11) % n + } + + fn reg(&mut self) -> V { + let n = self.next(self.regs.len() as u64) as usize; + self.regs[n] + } + + /// A register or a small constant. + fn value(&mut self) -> V { + match self.next(4) { + 0 => { + let k = [0u32, 1, 2, 31, u32::MAX, 0x8000_0000, 7][self.next(7) as usize]; + self.k.m.i32(k) + } + _ => self.reg(), + } + } + + fn cond(&mut self) -> V { + let c = self.cur; + let made = match self.next(6) { + 0 if !self.conds.is_empty() => { + let n = self.next(self.conds.len() as u64) as usize; + return self.conds[n]; + } + 1 if self.conds.len() > 1 => { + let (a, b) = ( + self.next(self.conds.len() as u64), + self.next(self.conds.len() as u64), + ); + let op = [Bin::And, Bin::Or, Bin::Xor][self.next(3) as usize]; + self.k + .m + .bin(c, op, self.conds[a as usize], self.conds[b as usize]) + } + 2 if !self.conds.is_empty() => { + let n = self.next(self.conds.len() as u64) as usize; + let t = self.k.m.bool(true); + self.k.m.bin(c, Bin::Xor, self.conds[n], t) + } + _ => { + let p = pred::EQ + self.next(10) as u8; + let (x, y) = (self.reg(), self.value()); + self.k.m.cmp(c, p, x, y) + } + }; + self.conds.push(made); + made + } + + fn statement(&mut self) { + let c = self.cur; + let d = self.next(self.regs.len() as u64) as usize; + let i32t = self.k.m.int(32); + let f32t = self.k.m.float(); + let r = match self.next(14) { + 0..=3 => { + let op = [Bin::Add, Bin::Sub, Bin::Mul, Bin::And, Bin::Or, Bin::Xor] + [self.next(6) as usize]; + let (x, y) = (self.value(), self.value()); + self.k.m.bin(c, op, x, y) + } + 4 => { + let op = [Bin::Shl, Bin::LShr, Bin::AShr][self.next(3) as usize]; + let x = self.value(); + let by = self.next(32) as u32; + let by = self.k.m.i32(by); + self.k.m.bin(c, op, x, by) + } + 5 | 6 => { + // A guarded write: the old value where the guard fails. + let g = self.cond(); + let x = self.value(); + self.k.m.select(self.cur, g, x, self.regs[d]) + } + 7 => { + let (x, y) = (self.value(), self.value()); + let f = [self.k.pure, self.input, self.table, self.wave][self.next(4) as usize]; + self.k.m.call(c, f, vec![x, y]) + } + 8 | 9 => { + let again = self.next(2) == 0; + let (x, y) = match self.last { + Some(last) if again => last, + _ => (self.value(), self.value()), + }; + self.last = Some((x, y)); + self.k.m.call(c, self.k.reads, vec![x, y]) + } + 10 => { + // A store, half the time to the place read last. + let (mut x, y) = (self.value(), self.value()); + let there = self.next(2) == 0; + if let Some((a, b)) = self.last + && there + { + x = self.k.m.bin(c, Bin::Xor, a, b); + } + self.k.m.call(c, self.k.writes, vec![x, y]); + return; + } + 11 => { + // Float arithmetic, read back as bits. + let (x, y) = (self.value(), self.value()); + let (x, y) = ( + self.k.m.cast(c, Cast::Bitcast, x, f32t), + self.k.m.cast(c, Cast::Bitcast, y, f32t), + ); + let op = [Bin::Add, Bin::Sub, Bin::Mul][self.next(3) as usize]; + let f = self.k.m.bin(c, op, x, y); + if self.next(2) == 0 { + let p = self.next(16) as u8; + let t = self.k.m.cmp(c, p, f, y); + self.conds.push(t); + } + self.k.m.cast(c, Cast::Bitcast, f, i32t) + } + 12 => { + let g = self.cond(); + self.k.m.cast(self.cur, Cast::ZExt, g, i32t) + } + _ => { + let x = self.value(); + let f = self.k.m.cast(c, Cast::Bitcast, x, f32t); + self.k.m.cast(c, Cast::Bitcast, f, i32t) + } + }; + self.regs[d] = r; + } + + fn code(&mut self, depth: u32) { + for _ in 0..1 + self.next(6) { + match self.next(8) { + 0 | 1 if depth > 0 => self.branch(depth - 1), + 2 if depth > 0 => self.repeat(depth - 1), + _ => self.statement(), + } + } + } + + /// if / else, every register joined. + fn branch(&mut self, depth: u32) { + let c = self.cond(); + let i32t = self.k.m.int(32); + let (then, other, join) = ( + self.k.m.new_block(), + self.k.m.new_block(), + self.k.m.new_block(), + ); + self.k.m.terminate(self.cur, Term::CondBr(c, then, other)); + let (before, known) = (self.regs.clone(), self.conds.len()); + self.cur = then; + self.last = None; + self.code(depth); + let (then_regs, then_end) = (std::mem::replace(&mut self.regs, before), self.cur); + self.k.m.terminate(then_end, Term::Br(join)); + self.conds.truncate(known); + self.cur = other; + self.last = None; + if self.next(3) != 0 { + self.code(depth); + } + let other_end = self.cur; + self.k.m.terminate(other_end, Term::Br(join)); + self.conds.truncate(known); + for (r, &t) in then_regs.iter().enumerate() { + let p = self.k.m.phi(join, i32t); + self.k + .m + .set_phi(p, vec![(t, then_end), (self.regs[r], other_end)]); + self.regs[r] = p; + } + self.cur = join; + self.last = None; + } + + /// A loop that runs at most a few times, every register joined at + /// its head. + fn repeat(&mut self, depth: u32) { + let i32t = self.k.m.int(32); + let (head, exit) = (self.k.m.new_block(), self.k.m.new_block()); + let before = self.cur; + self.k.m.terminate(before, Term::Br(head)); + let entering = self.regs.clone(); + let joins: Vec = (0..self.regs.len()) + .map(|_| self.k.m.phi(head, i32t)) + .collect(); + let count = self.k.m.phi(head, i32t); + self.regs = joins.clone(); + let known = self.conds.len(); + self.cur = head; + self.last = None; + self.code(depth); + let one = self.k.m.i32(1); + let next = self.k.m.bin(self.cur, Bin::Add, count, one); + let limit = 1 + self.next(3) as u32; + let limit = self.k.m.i32(limit); + let mut more = self.k.m.cmp(self.cur, pred::IULT, next, limit); + if self.next(2) == 0 { + let c = self.cond(); + more = self.k.m.bin(self.cur, Bin::And, more, c); + } + let latch = self.cur; + self.k.m.terminate(latch, Term::CondBr(more, head, exit)); + for (r, &p) in joins.iter().enumerate() { + self.k + .m + .set_phi(p, vec![(entering[r], before), (self.regs[r], latch)]); + } + let zero = self.k.m.i32(0); + self.k.m.set_phi(count, vec![(zero, before), (next, latch)]); + self.conds.truncate(known); + self.cur = exit; + self.last = None; + } + } + + fn random_program(seed: u64) -> Module { + let mut k = kit(); + let i32t = k.m.int(32); + let fty = k.m.func_ty(i32t, vec![i32t, i32t]); + let input = + k.m.function("dx.op.loadInput.i32", fty, Some(Attr::ReadNone), false); + let table = k.m.function( + "dx.op.cbufferLoadLegacy.i32", + fty, + Some(Attr::ReadOnly), + false, + ); + let wave = k.m.function( + "dx.op.waveReadLaneFirst.i32", + fty, + Some(Attr::NoUnwind), + false, + ); + let b = k.b; + let mut g = Gen { + k, + rng: seed.wrapping_mul(0x9E37_79B9_7F4A_7C15) | 1, + regs: Vec::new(), + conds: Vec::new(), + cur: b, + input, + table, + wave, + last: None, + }; + for r in 0..5 { + let (x, y) = (g.k.m.i32(r), g.k.m.i32(r * 3)); + let v = g.k.m.call(b, input, vec![x, y]); + g.regs.push(v); + } + g.code(3); + g.code(2); + // Every register is read at the end. + for r in 0..g.regs.len() { + let at = g.k.m.i32(r as u32); + g.k.m.call(g.cur, g.k.writes, vec![at, g.regs[r]]); + } + g.k.m.terminate(g.cur, Term::Ret); + g.k.m + } + + #[test] + fn every_pass_leaves_what_random_programs_store() { + let mut removed = 0; + for seed in 1..=400u64 { + let plain = random_program(seed); + let inputs: Vec> = (0..6u32) + .map(|n| { + (0..7u32) + .map(|i| match n { + 0 => 0, + 1 => i, + 2 => u32::MAX - i, + _ => { + (seed as u32 ^ n) + .wrapping_mul(0x9E37_79B9) + .rotate_left(i * 5) + ^ (i << 28) + } + }) + .collect() + }) + .collect(); + let expected: Vec<_> = inputs.iter().map(|i| run(&plain, i)).collect(); + let written: usize = plain + .blocks + .iter() + .map(|b| b.body.len() + b.phis.len()) + .sum(); + for passes in [ + DEAD, + FOLD, + REUSE, + FACTS, + LOADS, + FOLD | FACTS, + FOLD | REUSE | DEAD, + ALL, + ] { + let mut m = random_program(seed); + m.optimise(passes); + for (i, want) in inputs.iter().zip(&expected) { + assert_eq!(&run(&m, i), want, "seed {seed}, passes {passes}"); + } + if passes == ALL { + let left: usize = m.blocks.iter().map(|b| b.body.len() + b.phis.len()).sum(); + removed += written - left; + } + m.write(); + } + } + // The programs are of the wasteful kind: the passes find work. + assert!(removed > 4000, "{removed} instructions removed"); + } +} diff --git a/crates/leonida-shader/src/emit/container.rs b/crates/leonida-shader/src/emit/container.rs new file mode 100644 index 000000000..3c346d9a6 --- /dev/null +++ b/crates/leonida-shader/src/emit/container.rs @@ -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, + 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, + } + } + + 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 { + 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 = 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 = (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::(); + 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, + pub bindings: &'a [Binding], + /// Compute: thread-group size and required wave size. + pub threads: [u32; 3], + pub wave_size: Option, +} + +/// `PSV0` with runtime info version 2 (validator 1.6). +pub(crate) fn psv(p: &Psv) -> Vec { + 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, 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 = 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 = 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 { + hay.windows(needle.len()).position(|w| w == needle) +} + +/// The container: parts in order, hashed. +pub(crate) fn build(parts: &[(&[u8; 4], &[u8])]) -> Vec { + let table = 0x20 + 4 * parts.len(); + let total = table + parts.iter().map(|(_, d)| 8 + d.len()).sum::(); + 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 = 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"); + } +} diff --git a/crates/leonida-shader/src/emit/diff_tests.rs b/crates/leonida-shader/src/emit/diff_tests.rs new file mode 100644 index 000000000..9c7473796 --- /dev/null +++ b/crates/leonida-shader/src/emit/diff_tests.rs @@ -0,0 +1,1287 @@ +//! Differential tests: HLSL compiled by the console's shader compiler and +//! translated, against the same HLSL compiled for PC, both drawn (or +//! dispatched) on the host GPU with the same inputs. +//! +//! Needs `LEONIDA_CONSOLE_DXC` (the console SDK's `dxc.exe`) and a PC +//! `dxc.exe` (`LEONIDA_PC_DXC`, else the newest Windows SDK's); skipped +//! without them. Set `LEONIDA_WARP=1` to draw on WARP. + +use std::path::{Path, PathBuf}; + +use windows::Win32::Graphics::Direct3D12::*; +use windows::Win32::Graphics::Dxgi::Common::*; + +use super::host::{Draw, Host, Root}; +use super::{HostShader, RootType, translate}; + +const RS: &str = "RootFlags(ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT), \ + RootConstants(num32BitConstants=4, b0), \ + DescriptorTable(SRV(t0)), DescriptorTable(Sampler(s0)), \ + StaticSampler(s1, filter=FILTER_MIN_MAG_MIP_POINT, \ + addressU=TEXTURE_ADDRESS_WRAP, addressV=TEXTURE_ADDRESS_MIRROR), \ + StaticSampler(s2, filter=FILTER_MIN_MAG_LINEAR_MIP_POINT, \ + addressU=TEXTURE_ADDRESS_BORDER, addressV=TEXTURE_ADDRESS_CLAMP, \ + borderColor=STATIC_BORDER_COLOR_OPAQUE_WHITE, mipLODBias=0.5)"; + +const COMMON: &str = r#" +cbuffer K : register(b0) { float4 k; }; +Texture2D tex : register(t0); +SamplerState smp : register(s0); +struct V { float4 pos : SV_Position; float2 uv : TEXCOORD0; float4 col : COLOR0; }; +[RootSignature(RS)] +V vs(float4 p : POSITION, float2 uv : TEXCOORD0) { + V o; + o.pos = p; + o.uv = uv; + o.col = float4(uv * k.xy, p.x * k.z, 1); + return o; +} +"#; + +/// Pixel shaders, each `ps`. +const CASES: &[(&str, &str)] = &[ + ( + "constant", + "[RootSignature(RS)] float4 ps(V i) : SV_Target { return float4(0.25, 0.5, 1, 0.75); }", + ), + ( + "interpolated", + "[RootSignature(RS)] float4 ps(V i) : SV_Target { return i.col * 2 - float4(i.uv, 0, 0); }", + ), + ( + "sample and branch", + r#"[RootSignature(RS)] float4 ps(V i) : SV_Target { + float4 t = tex.Sample(smp, i.uv); + float4 r = t * i.col + k.w; + if (i.uv.x > 0.5) r.xy = sin(r.yx * 3.0); + else r.z = rcp(r.z + 2.0); + return r; + }"#, + ), + // A wave-wide range scalarises a per-pixel loop (as the title's light + // lists do): the console's 64-lane sections become host wave operations; + // the result is the same for any wave the pixel lands in. + ( + "wave range", + r#"[RootSignature(RS)] float4 ps(V i) : SV_Target { + uint idx = uint(i.pos.x * 0.37 + i.pos.y * 0.21) & 15; + uint lo = WaveActiveMin(idx), hi = WaveActiveMax(idx); + float s = 0; + for (uint n = lo; n <= hi; n++) if (n == idx) s += n * k.x; + return float4(s, lo <= idx, hi >= idx, WaveActiveCountBits(true) > 0); + }"#, + ), + ( + "uniform loop", + r#"[RootSignature(RS)] float4 ps(V i) : SV_Target { + float s = 0; + for (uint n = 0; n < (asuint(k.x) & 7); n++) s += i.uv.y * n; + return float4(s, 0, 0, 1); + }"#, + ), + ( + "bit loop", + r#"[RootSignature(RS)] float4 ps(V i) : SV_Target { + uint2 p = uint2(i.pos.xy); + uint s = p.y; + for (uint n = 0; n < (p.x & 7); n++) s = (s ^ (s << 3)) + n; + return float4(s & 255, 0, 0, 1); + }"#, + ), + ( + "integer loop", + r#"[RootSignature(RS)] float4 ps(V i) : SV_Target { + uint2 p = uint2(i.pos.xy); + uint s = 0; + for (uint n = 0; n < (p.x & 7); n++) s += n; + return float4(s, 0, 0, 1); + }"#, + ), + ( + "loop", + r#"[RootSignature(RS)] float4 ps(V i) : SV_Target { + uint2 p = uint2(i.pos.xy); + float s = 0; + for (uint n = 0; n < (p.x & 7); n++) s += i.uv.y * n + k.x; + return float4(s, 0, 0, 1); + }"#, + ), + ( + "discard", + r#"[RootSignature(RS)] float4 ps(V i) : SV_Target { + uint2 p = uint2(i.pos.xy); + if ((p.x ^ p.y) & 1) discard; + return i.col; + }"#, + ), + ( + "immediate samplers", + r#"SamplerState point_wrap : register(s1); + SamplerState linear_border : register(s2); + [RootSignature(RS)] float4 ps(V i) : SV_Target { + return tex.Sample(point_wrap, i.uv * 3 - 1) + 2 * tex.Sample(linear_border, i.uv * 2.5 - 0.7); + }"#, + ), + ( + "loop, discard and loads", + r#"[RootSignature(RS)] float4 ps(V i) : SV_Target { + uint2 p = uint2(i.pos.xy); + if ((p.x ^ p.y) & 1) discard; + float s = 0; + for (uint n = 0; n < (p.x & 7); n++) s += i.uv.y * n + k.x; + float4 t = tex.Load(int3(p & 3, 0)); + return float4(s, frac(i.uv.x * 7.3), max(t.x, t.y) * k.y, sqrt(abs(i.col.x)) + exp2(i.uv.y)); + }"#, + ), + ( + "level of detail", + r#"[RootSignature(RS)] float4 ps(V i) : SV_Target { + return float4(tex.CalculateLevelOfDetail(smp, i.uv * 4), + tex.CalculateLevelOfDetailUnclamped(smp, i.uv * 7), 0, 1); + }"#, + ), + // 16-bit outputs and inputs (one value per dword with the 2020 + // compiler; the title's two per dword cannot be compiled + // here) and the front face. + ( + "16-bit varyings and front face", + r#"struct V16 { float4 pos : SV_Position; half2 uv : TEXCOORD0; float4 col : COLOR0; half4 h : TEXCOORD1; }; + [RootSignature(RS)] V16 vs16(float4 p : POSITION, float2 uv : TEXCOORD0) { + V16 o; + o.pos = p; + o.uv = half2(uv * k.xy); + o.col = float4(uv, p.x * k.z, 1); + o.h = half4(uv.yx * 3 - 1, k.w, p.y); + return o; + } + [RootSignature(RS)] float4 ps(V16 i, bool f : SV_IsFrontFace) : SV_Target { + float4 c = i.col * float4(i.uv, i.h.xy) + float4(i.h.zw, 0, 0); + return f ? c : -c; + }"#, + ), +]; + +const CS_RS: &str = "RootConstants(num32BitConstants=4, b0), \ + DescriptorTable(SRV(t0, numDescriptors=4)), DescriptorTable(Sampler(s0)), \ + DescriptorTable(UAV(u0, numDescriptors=4)), CBV(b1), SRV(t4), \ + DescriptorTable(SRV(t0, space=2, numDescriptors=9)), \ +\ + StaticSampler(s3, filter=FILTER_COMPARISON_MIN_MAG_LINEAR_MIP_POINT, \ + comparisonFunc=COMPARISON_LESS_EQUAL, \ + addressU=TEXTURE_ADDRESS_CLAMP, addressV=TEXTURE_ADDRESS_CLAMP)"; + +const CS_COMMON: &str = r#" +cbuffer K : register(b0) { float4 k; }; +Texture2D tex : register(t0); +Buffer typed : register(t1); +struct S { float a; uint b; float2 c; }; +StructuredBuffer structured : register(t2); +ByteAddressBuffer raw : register(t3); +SamplerState smp : register(s0); +SamplerComparisonState cmp : register(s3); +RWByteAddressBuffer outb : register(u0); +RWTexture2D outt : register(u1); +cbuffer R : register(b1) { float4 table[16]; }; +ByteAddressBuffer rootraw : register(t4); +// `raw`'s bytes in typed views (the formats the console's typed loads name). +Buffer unorm8x4 : register(t0, space2); +Buffer snorm16x2 : register(t1, space2); +Buffer uint8x4 : register(t2, space2); +Buffer unorm10x3_2 : register(t3, space2); +Buffer uint16x4 : register(t4, space2); +Buffer unorm8 : register(t5, space2); +Buffer half16 : register(t6, space2); +Buffer snorm8x4 : register(t7, space2); +RWTexture2D ut : register(u2); +TextureCube cubet : register(t8, space2); +#define FMT(numeric, data) ((numeric) << 4 | (data)) +#define CS [RootSignature(RS)] [numthreads(8, 8, 1)] \ + void cs(uint3 g : SV_GroupID, uint3 t : SV_GroupThreadID, \ + uint3 d : SV_DispatchThreadID, uint i : SV_GroupIndex) +"#; + +/// Compute shaders, each `cs`, dispatched as 2×2 groups of 8×8 threads +/// over a 16×16 texture and a 256-dword buffer. +const CS_CASES: &[(&str, &str)] = &[ + ( + "ids and stores", + r#"CS { + outb.Store(4 * (d.y * 16 + d.x), asuint(d.x * k.x + d.y)); + outt[d.xy] = float4(g.x, g.y, t.x, t.y + i); + }"#, + ), + ( + "shared memory and barrier", + r#"groupshared float lds[64]; + groupshared uint cnt; + CS { + if (i == 0) cnt = 0; + lds[i] = d.x * k.x + d.y; + GroupMemoryBarrierWithGroupSync(); + InterlockedAdd(cnt, i); + float v = lds[63 - i] + lds[(i + 9) & 63]; + GroupMemoryBarrierWithGroupSync(); + outb.Store(4 * (d.y * 16 + d.x), asuint(v)); + outt[d.xy] = float4(v, cnt, 0, 1); + }"#, + ), + ( + "sample and divergent store", + r#"CS { + float4 s = tex.SampleLevel(smp, (d.xy + 0.5) / 16.0, 0); + if ((d.x ^ d.y) & 1) outt[d.xy] = s * k.y; + else outb.Store(4 * (d.y * 16 + d.x), asuint(s.x + s.w)); + }"#, + ), + ( + "buffers and root views", + r#"CS { + float4 a = typed[i & 15]; + S s = structured[(i * 3) & 7]; + uint r = raw.Load(4 * (i & 31)); + float4 c = table[d.x & 15]; + uint q = rootraw.Load(4 * ((i + 5) & 31)); + outb.Store(4 * (d.y * 16 + d.x), asuint(a.x + a.w * s.a) ^ s.b ^ r ^ q); + outt[d.xy] = c + float4(s.c, a.yz); + }"#, + ), + // (The 2020 compiler branches around every narrowed region, so these + // become branches, not guards.) + ( + "conditional memory access", + r#"CS { + float v = d.x * k.x + d.y; + if (i & 1) v = v * 3 + 1; + if (i & 4) v += tex.Load(int3(d.xy & 3, 0)).y; + if (i & 2) outb.Store(4 * (d.y * 16 + d.x), asuint(v)); + if (i & 8) outt[d.xy] = float4(v, 0, 0, 1); + }"#, + ), + // Each side of a per-group branch leaves a compare in VCC; the select + // after the join reads the joined mask (as `postfx_splines` does). + ( + "select on joined compares", + r#"CS { + float v = d.x * k.x + d.y; + float r; + bool ok; + [branch] if ((g.x ^ g.y) & 1) { + r = sqrt(v) * k.z + sin(v * k.w); + ok = r < 5; + } else { + r = v * k.y + 1; + ok = r > -4; + } + float o = ok ? r : -1; + outb.Store(4 * (d.y * 16 + d.x), asuint(o)); + outt[d.xy] = float4(o, r, v, 1); + }"#, + ), + // One host wave of 32 lanes holds the group, as the console's wave of 64 + // does, so lane numbers agree with the PC compile. + ( + "lane reads", + r#"[RootSignature(RS)] [numthreads(8, 4, 1)] + void cs(uint3 d : SV_DispatchThreadID) { + float v = d.x * k.x + d.y; + float w = WaveReadLaneAt(v, 5); + uint lane = WaveGetLaneIndex(); + uint q = QuadReadAcrossX(lane * 10) + QuadReadAcrossDiagonal(lane); + outb.Store(4 * (d.y * 16 + d.x), q); + outt[d.xy] = float4(v, w, QuadReadAcrossY(v), lane); + }"#, + ), + // Bytes and halves: SDWA operand and result selection, byte permutes, + // f16 conversions. + ( + "sub-dword operations", + r#"CS { + uint n = d.y * 16 + d.x; + uint x = raw.Load(4 * (n & 31)), y = raw.Load(4 * ((n * 7) & 31)); + float a = float(x >> 16) + float((y >> 8) & 255) * k.x; + float b = f16tof32(x >> 16) + f16tof32(y); + uint p = (x & 0xff) | ((y & 0xff) << 8) | (x & 0xff0000) | ((y >> 8) << 24); + uint q = f32tof16(a) | (f32tof16(b) << 16); + int s = int(x << 24) >> 24; + uint u = (x & 0xffff) + (y >> 16) + ((x >> 24) ^ (y & 0xffff)) + asuint(k.w) * 1000 + 77; + outb.Store4(16 * n, uint4(asuint(a), asuint(b) ^ p, q, asuint(float(s)) + u)); + }"#, + ), + // 64-bit additions (VALU carries as lane masks) and explicit gradients. + ( + "carries and gradients", + r#"CS { + uint n = d.y * 16 + d.x; + uint64_t a = (uint64_t(raw.Load(4 * (n & 31))) << 32) | raw.Load(4 * ((n * 3) & 31)); + uint64_t b = (uint64_t(raw.Load(4 * ((n * 5) & 31))) << 32) | raw.Load(4 * ((n * 7) & 31)); + uint64_t s = a + b, u = a - b; + float4 gr = tex.SampleGrad(smp, (d.xy + 0.5) / 16.0, float2(k.x, 0) * 0.1, float2(0, k.z) * 0.1); + outb.Store4(16 * n, uint4(uint(s), uint(s >> 32) ^ uint(u), uint(u >> 32), asuint(gr.x + gr.y * 3))); + }"#, + ), + // Comparison sampling at level 0 with an immediate comparison sampler. + ( + "comparison sampling", + r#"CS { + float r = tex.SampleCmpLevelZero(cmp, (d.xy + 0.25) / 15.0, k.x * d.x / 16.0); + outb.Store(4 * (d.y * 16 + d.x), asuint(r)); + }"#, + ), + // 16-bit texture results, two channels per register (`d16`). + ( + "16-bit texture reads", + r#"Texture2D htex : register(t0); + CS { + half4 a = htex.SampleLevel(smp, (d.xy + 0.5) / 16.0, 0); + half3 b = htex.Load(int3(d.xy & 3, 0)).xyz; + outb.Store4(16 * (d.y * 16 + d.x), uint4(asuint(float(a.x) + a.w), + asuint(float(a.y) * a.z), asuint(float(b.x)), asuint(float(b.y) - b.z))); + }"#, + ), + // Sizes: the console compiler computes them from descriptor bits + // (width, height, levels, record counts). + ( + "sizes from descriptors", + r#"CS { + uint w, h, l, n, b, ns, st; + tex.GetDimensions(0, w, h, l); + typed.GetDimensions(n); + raw.GetDimensions(b); + structured.GetDimensions(ns, st); + // Read too: the translation takes the views' kinds from those reads. + float r = tex.Load(int3(d.xy & 3, 0)).x + typed[i & 15].y + structured[i & 7].a; + outb.Store4(16 * (d.y * 16 + d.x), + uint4(w * 7 + h, l + asuint(r), n * 5 + ns * 3 + st, b + raw.Load(4 * (i & 31)))); + }"#, + ), + // Typed loads (`tbuffer_load_format_*`, the title's vertex + // fetch) convert by the format the instruction names: the PC reads the + // same bytes through typed views in those formats. Channels past the + // format's read (0, 0, 0, 1); a byte format at unaligned offsets. + ( + "typed loads", + r#"CS { + uint n = d.y * 16 + d.x, e = n & 31, f = n >> 5; + uint4 a, b, c, dd, ee, ff, gg, hh; + #ifdef CONSOLE + a = raw.XB_TypedLoad4(4 * e, FMT(0, 10)); + b = raw.XB_TypedLoad4(4 * e, FMT(1, 5)); + c = raw.XB_TypedLoad4(4 * e, FMT(4, 10)); + dd = raw.XB_TypedLoad4(4 * e, FMT(0, 9)); + ee = raw.XB_TypedLoad4(8 * (e & 15), FMT(4, 12)); + ff = uint4(raw.XB_TypedLoad((3 * e) & 127, FMT(0, 1)), 0, 0, 0); + gg = uint4(raw.XB_TypedLoad2(2 * e, FMT(7, 2)), 0, 0); + hh = raw.XB_TypedLoad4(4 * e, FMT(1, 10)); + #else + a = asuint(unorm8x4[e]); + b = asuint(snorm16x2[e]); + c = uint8x4[e]; + dd = asuint(unorm10x3_2[e]); + ee = uint16x4[e & 15]; + ff = uint4(asuint(unorm8[(3 * e) & 127]), 0, 0, 0); + gg = uint4(asuint(half16[e]), 0, 0, 0); + hh = asuint(snorm8x4[e]); + #endif + uint4 v = f == 0 ? a : f == 1 ? b : f == 2 ? c : f == 3 ? dd + : f == 4 ? ee : f == 5 ? ff : f == 6 ? gg : hh; + outb.Store4(16 * n, v); + }"#, + ), + // Wave operations: the console expands them into whole-wave sections + // (DPP, `v_permlanex16`, lane reads) and lane masks read as numbers + // (`s_bcnt1`, `s_ff1`, `v_mbcnt`). 32 threads: one wave on the console + // (lanes 32-63 inactive) and on the host; the branch leaves lanes out. + ( + "wave operations", + r#"[RootSignature(RS)] [numthreads(8, 4, 1)] + void cs(uint3 d : SV_DispatchThreadID, uint i : SV_GroupIndex) { + uint n = d.y * 16 + d.x; + float v = d.x * k.x + d.y; + uint u = raw.Load(4 * (i & 31)); + uint4 o = 0; + if (u & 3) { + o.x = WaveActiveSum(u >> 8) + WaveActiveCountBits((u & 4) != 0); + o.y = asuint(WaveActiveMax(v)) ^ WaveActiveMin(u) ^ WaveActiveBitOr(u) + ^ WaveActiveBitAnd(u | 1) ^ asuint(WaveActiveMin(v)) ^ WaveActiveMax(int(u)); + o.z = WavePrefixSum(u & 255) + WavePrefixCountBits(v > 2) * 1000; + // (The PC compile evaluates a wave operation in a `?:` arm + // in that arm's lanes only, so it stays outside.) + o.w = asuint(WaveActiveSum(v)) + (WaveIsFirstLane() ? WaveReadLaneFirst(u) : 0); + } + outb.Store4(16 * n, o); + }"#, + ), + // Atomics the console aggregates per wave (one add of the lane count, + // each lane's offset from `v_mbcnt`), and texture atomics. Results + // that depend on the lanes' order are left out. + ( + "aggregated and texture atomics", + r#"CS { + uint u = raw.Load(4 * (i & 31)), r, q; + outb.InterlockedAdd(0, 1, r); + outb.InterlockedAdd(4 * (1 + r % 8), 1); + if (u & 1) outb.InterlockedAdd(64, u & 255); + uint2 p = d.xy & 3; + InterlockedMax(ut[p], u); + InterlockedOr(ut[p + uint2(4, 0)], u >> (i & 7)); + InterlockedMin(ut[p + uint2(8, 0)], u); + InterlockedAdd(ut[p + uint2(12, 0)], u & 15, q); + InterlockedXor(ut[p + uint2(0, 4)], u); + }"#, + ), + // A loop whose count comes from a view that reads zeros (as a null or + // not yet mirrored one does) runs four billion times on the console; + // the translation leaves it after `LOOP_LIMIT` iterations. Run on WARP + // only (`LEONIDA_WARP=1`), ours only: without the limit it would hang + // the GPU. + ( + "terminates on zero data", + r#"CS { + uint cnt = outb.Load(4 * 1000), s = d.x; + for (uint j = 0; j != cnt - 1; j++) s = s * 3 + raw.Load(4 * (j & 31)); + outb.Store(4 * (d.y * 16 + d.x), s); + }"#, + ), + // Cube sampling: the console computes face coordinates (`v_cube*`) + // and samples the face; the host samples the direction rebuilt from + // them. Every face and texel: a major axis of ±2 and the others at + // texel centres, so both sides compute them exactly. + ( + "cube sampling", + r#"CS { + float sg = (i & 8) ? -2 : 2; + float a = (d.x & 3) - 1.5, b = (d.y & 3) - 1.5; + uint ax = i % 3; + float3 dir = ax == 0 ? float3(sg, a, b) : ax == 1 ? float3(a, sg, b) : float3(a, b, sg); + float4 p = cubet.SampleLevel(smp, dir, 0); + float4 q = cubet.SampleLevel(smp, -dir.zxy, 0); + outb.Store4(16 * (d.y * 16 + d.x), asuint(p + q * 3)); + }"#, + ), + // A local array indexed per lane (M0-relative VGPR moves), bit fields + // and first bits from the top. + ( + "indexed registers and bit fields", + r#"CS { + uint n = d.y * 16 + d.x; + uint x = raw.Load(4 * (n & 31)), y = raw.Load(4 * ((n * 5) & 31)); + uint arr[24]; + [unroll] for (uint j = 0; j < 24; j++) arr[j] = x ^ (j * 0x01010101); + [loop] for (uint m = 0; m < (y & 3); m++) arr[(y >> (m * 5)) % 24] = y + m; + uint v = arr[(x >> 3) % 24]; + uint w = asuint(k.x) & 31, o = n & 15; + uint bf = (x & ((1u << w) - 1)) << o; + uint fb = firstbithigh(asuint(k.y)) + firstbithigh(x) * 3 + firstbithigh(int(y)) * 7; + outb.Store4(16 * n, uint4(v, bf, fb, arr[n % 24])); + }"#, + ), + // Size queries at a level known per lane (`image_get_resinfo`). + ( + "size queries", + r#"CS { + uint w, h, l, cw, ch, cl; + tex.GetDimensions(d.x >> 4, w, h, l); + cubet.GetDimensions(d.y >> 4, cw, ch, cl); + float r = tex.Load(int3(d.xy & 3, 0)).x; + outb.Store4(16 * (d.y * 16 + d.x), uint4(w * 7 + h, l + asuint(r), cw * 3 + ch, cl)); + }"#, + ), + // Gathers with offsets computed per lane (programmable offsets). + ( + "gather with offsets", + r#"CS { + int2 o = int2(int(d.x & 7) - 4, int(d.y % 5) - 2); + float4 r = tex.GatherRed(smp, (d.xy + 0.5) / 16.0, o); + float4 q = tex.GatherGreen(smp, (d.yx + 0.25) / 16.0, -o); + outb.Store4(16 * (d.y * 16 + d.x), asuint(r + q * 3)); + }"#, + ), + // Constant arrays: the console compiler appends them to the code and + // reads them through `s_getpc_b64` (scalar loads for a uniform index, + // global loads per lane, 16-bit ones too). + ( + "constant tables", + r#"static const uint tbl[16] = { 3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5, 8, 9, 7, 9, 3 }; + static const float ftbl[8] = { 0.5, -1, 2.25, 3, -4.5, 6, 7.75, -8 }; + // (16-bit types: compiled with half precision enabled.) + static const uint16_t stbl[12] = { 100, 200, 300, 400, 500, 600, 700, 800, 900, 1000, 1100, 65535 }; + CS { + uint n = d.y * 16 + d.x; + uint u = asuint(k.x) & 15; + uint a = tbl[i & 15] ^ tbl[u] << 8; + float f = ftbl[(i * 3) & 7] * ftbl[u & 7]; + uint h = stbl[(n * 5) % 12] + stbl[u % 12]; + outb.Store4(16 * n, uint4(a, asuint(f), h, tbl[(n + u) & 15])); + }"#, + ), + // 16-bit arithmetic (scalar and packed), 16-bit compares, typed stores + // of halves (`buffer_store_format_d16`), 64-bit shifts and compares. + ( + "16-bit and 64-bit arithmetic", + r#"RWBuffer hb : register(u3); + CS { + uint n = d.y * 16 + d.x; + uint x = raw.Load(4 * (n & 31)), y = raw.Load(4 * ((n * 7) & 31)); + half a = half(d.x * k.x - 2), b = half(d.y + k.y), c = half(k.z); + half2 p = half2(a, b) * half2(b, c) + half2(c, a); + half m = max(a, b) - min(a, c) * a; + bool lt = a < b, ge = p.x >= p.y; + hb[n] = half4(p.x, m, lt ? a : b, ge ? p.y : a - b); + uint64_t q = (uint64_t(x) << (n & 31)) | y, w = uint64_t(y) << 3; + uint z = q < w ? 1 : q == w ? 2 : 3; + outb.Store2(8 * n, uint2(uint(q >> 7) ^ z, uint(w >> (n & 15)))); + }"#, + ), +]; + +const MS_COMMON: &str = r#" +#define RS "RootConstants(num32BitConstants=4, b0)" +cbuffer K : register(b0) { float4 k; }; +struct V { float4 pos : SV_Position; float4 col : COLOR0; float2 uv : TEXCOORD0; }; +[RootSignature(RS)] float4 mps(V i) : SV_Target { return i.col + float4(i.uv, 0, 0); } +#define MS_ATTR [RootSignature(RS)] [outputtopology("triangle")] +"#; + +/// Mesh shaders, each `ms` (the console runs one thread per output lane, so +/// groups of 32 run as 64 lanes there), with their group counts. Drawn +/// with `mps` into 16×16 targets. The 2020 compiler's containers do not +/// record the thread count, so cases reading the group id keep +/// max(threads, vertices, primitives) at the lane count (see `emit`). +const MS_CASES: &[(&str, u32, &str)] = &[ + ( + "one triangle", + 1, + r#"MS_ATTR [numthreads(32, 1, 1)] + void ms(uint i : SV_GroupIndex, out vertices V verts[3], out indices uint3 tris[1]) { + SetMeshOutputCounts(3, 1); + if (i < 3) { + verts[i].pos = float4(i == 1 ? 3 : -1, i == 2 ? 3 : -1, 0.5, 1); + verts[i].col = float4(k.x * i, k.y, k.z * (i == 2), 1); + verts[i].uv = float2(i * 0.5, k.w); + } + if (i == 0) tris[0] = uint3(0, 1, 2); + }"#, + ), + // A quad per group in its quadrant; a run-time vertex count, and a + // primitive count per group whose third triangle is culled. + ( + "groups, counts and culling", + 4, + r#"struct P { bool cull : SV_CullPrimitive; }; + MS_ATTR [numthreads(64, 1, 1)] + void ms(uint i : SV_GroupIndex, uint3 g : SV_GroupID, out vertices V verts[8], + out indices uint3 tris[4], out primitives P prims[4]) { + uint nv = 4 + (k.z > 1); + uint np = 2 + (g.x & 1); + SetMeshOutputCounts(nv, np); + float2 o = float2(g.x & 1, g.x >> 1) - 1; + if (i < nv) { + float2 p = i < 4 ? float2(i & 1, i >> 1) : float2(-0.75, 0.5); + verts[i].pos = float4(o + p, 0.5, 1); + verts[i].col = float4(k.x * i, g.x * 0.25, k.z, 1); + verts[i].uv = float2(i, g.x); + } + if (i < np) { + tris[i] = i == 0 ? uint3(0, 1, 2) : i == 1 ? uint3(1, 3, 2) : uint3(1, 4, 3); + prims[i].cull = i == 2; + } + }"#, + ), + // Two waves per group, as the title's mesh programs run: the + // second wave's lanes are threads 64-127. + ( + "two waves", + 1, + r#"MS_ATTR [numthreads(128, 1, 1)] + void ms(uint i : SV_GroupIndex, out vertices V verts[81], out indices uint3 tris[128]) { + SetMeshOutputCounts(81, 128); + if (i < 81) { + float2 p = float2(i % 9, i / 9) / 8.0; + verts[i].pos = float4(p * 2 - 1, 0.5, 1); + verts[i].col = float4(p.x * k.x, p.y, (i & 7) * 0.125, 1); + verts[i].uv = float2(i, k.y); + } + uint c = i / 2 % 8 + i / 16 * 9; + tris[i] = i & 1 ? uint3(c + 1, c + 10, c + 9) : uint3(c, c + 1, c + 9); + }"#, + ), + // Quad reads (DPP quad permutations on the console; the title's + // tessellating mesh programs swizzle within quads too). + ( + "quad reads", + 1, + r#"MS_ATTR [numthreads(128, 1, 1)] + void ms(uint i : SV_GroupIndex, out vertices V verts[81], out indices uint3 tris[128]) { + SetMeshOutputCounts(81, 128); + float w = i * k.x + k.y; + float a = QuadReadLaneAt(w, 0); + float b = QuadReadLaneAt(w, 2); + float c = QuadReadAcrossX(w); + if (i < 81) { + float2 p = float2(i % 9, i / 9) / 8.0; + verts[i].pos = float4(p * 2 - 1, 0.5, 1); + verts[i].col = float4(a, b, c, 1); + verts[i].uv = float2(i, k.y); + } + uint cc = i / 2 % 8 + i / 16 * 9; + tris[i] = i & 1 ? uint3(cc + 1, cc + 10, cc + 9) : uint3(cc, cc + 1, cc + 9); + }"#, + ), + // Vertices and indices written by other threads than their lanes: the + // console passes them through shared memory, with a loop and barriers. + ( + "grid through shared memory", + 2, + r#"MS_ATTR [numthreads(32, 1, 1)] + void ms(uint i : SV_GroupIndex, uint3 g : SV_GroupID, out vertices V verts[36], + out indices uint3 tris[64]) { + SetMeshOutputCounts(36, 50); + for (uint v = i; v < 36; v += 32) { + float2 p = float2(v % 6, v / 6) / 5.0; + verts[v].pos = float4(p.x - g.x, p.y * 2 - 1, 0.5, 1); + verts[v].col = float4(p * k.x, k.z * g.x, 1); + verts[v].uv = float2(v, k.y); + } + if (i < 25) { + uint c = i % 5 + i / 5 * 6; + tris[2 * i] = uint3(c, c + 1, c + 6); + tris[2 * i + 1] = uint3(c + 1, c + 7, c + 6); + } + }"#, + ), +]; + +fn tools() -> Option<(PathBuf, PathBuf)> { + let console = PathBuf::from(std::env::var_os("LEONIDA_CONSOLE_DXC")?); + let pc = match std::env::var_os("LEONIDA_PC_DXC") { + Some(p) => PathBuf::from(p), + None => super::validator::Validator::default_path()?.with_file_name("dxc.exe"), + }; + (console.exists() && pc.exists()).then_some((console, pc)) +} + +fn compile(dxc: &Path, dir: &Path, src: &str, entry: &str, profile: &str) -> Vec { + let input = dir.join("t.hlsl"); + let output = dir.join(format!("{entry}.bin")); + let text = if entry == "cs" { + format!("#define RS \"{CS_RS}\"\n{CS_COMMON}\n{src}\n") + } else if entry.starts_with('m') { + format!("{MS_COMMON}\n{src}\n") + } else { + format!("#define RS \"{RS}\"\n{COMMON}\n{src}\n") + }; + std::fs::write(&input, text).unwrap(); + let out = std::process::Command::new(dxc) + .args(["-T", profile, "-E", entry, "-Fo"]) + .arg(&output) + .arg(&input) + .args(src.contains("half").then_some("-enable-16bit-types")) + // `CONSOLE` marks the console compile (cases spell console-only + // intrinsics there). + .args( + std::env::var_os("LEONIDA_CONSOLE_DXC") + .is_some_and(|c| Path::new(&c) == dxc) + .then_some("-DCONSOLE"), + ) + .output() + .unwrap(); + assert!( + out.status.success(), + "{}", + String::from_utf8_lossy(&out.stderr) + ); + std::fs::read(output).unwrap() +} + +/// Root arguments for a translated stage: user data from the root values. +fn user_data(s: &HostShader, k: &[u32; 4]) -> Vec { + let mut data = vec![0; (s.user_data_dwords() as usize).max(1)]; + for u in &s.user_data { + data[u.index as usize] = match (u.root, u.slot) { + (RootType::Constants, 0) => k[u.dword as usize], + // The texture and sampler tables start at heap index 1, the UAV + // table (compute) at 5, in the console's units. + (RootType::Table, 1) => 32, + (RootType::Table, 2) => 16, + (RootType::Table, 3) => 5 * 32, + // The typed views of `raw` (compute) from 9. + (RootType::Table, 6) => 9 * 32, + other => panic!("unexpected user data {other:?}"), + }; + } + data +} + +#[test] +fn translated_shaders_draw_as_pc_ones() { + let Some((console, pc)) = tools() else { + eprintln!("no console or PC compiler; skipped"); + return; + }; + let Ok(host) = Host::new(false) else { + eprintln!("no SM 6.6 device; skipped"); + return; + }; + let dir = std::env::temp_dir().join(format!("leonida-diff-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let k = [0.75f32, -1.5, 2.0, 0.125].map(f32::to_bits); + let texels: Vec<[f32; 4]> = (0..16) + .map(|i| { + [ + i as f32 / 16.0, + (i % 4) as f32 * 0.3, + 1.0 - i as f32 / 20.0, + 0.5, + ] + }) + .collect(); + let dummy = [[9.0f32; 4]]; + let sampler = |filter, address| D3D12_SAMPLER_DESC { + Filter: filter, + AddressU: address, + AddressV: address, + AddressW: address, + MaxAnisotropy: 1, + MaxLOD: f32::MAX, + ..Default::default() + }; + let samplers = [ + sampler( + D3D12_FILTER_MIN_MAG_MIP_POINT, + D3D12_TEXTURE_ADDRESS_MODE_CLAMP, + ), + sampler( + D3D12_FILTER_MIN_MAG_MIP_LINEAR, + D3D12_TEXTURE_ADDRESS_MODE_WRAP, + ), + ]; + // A full-screen triangle: POSITION (4 floats), TEXCOORD0 (2 floats). + let vertices = [ + -1.0, -1.0, 0.5, 1.0, 0.0, 1.0, // + -1.0, 3.0, 0.5, 1.0, 0.0, -1.0, // + 3.0, -1.0, 0.5, 1.0, 2.0, 1.0, + ]; + let textures: [(u32, u32, &[[f32; 4]]); 2] = [(1, 1, &dummy), (4, 4, &texels)]; + let draw = |roots| Draw { + roots, + textures: &textures, + samplers: &samplers, + vertices: &vertices, + stride: 24, + size: (16, 16), + mesh_groups: 0, + }; + let mut failures = Vec::new(); + let only = std::env::var("LEONIDA_DIFF_ONLY").ok(); + for (name, src) in CASES + .iter() + .filter(|c| only.as_ref().is_none_or(|o| o == c.0)) + { + // A case may bring its own vertex shader. + let vs = if src.contains(" vs16(") { "vs16" } else { "vs" }; + let vs_c = translate(&compile(&console, &dir, src, vs, "vs_6_5")).unwrap(); + let ps_c = match translate(&compile(&console, &dir, src, "ps", "ps_6_5")) { + Ok(s) => s, + Err(e) => { + failures.push(format!("{name}: {e}")); + continue; + } + }; + if let Ok(out) = std::env::var("LEONIDA_EMIT_DUMP") { + let stem = name.replace([' ', ','], "_"); + std::fs::write( + format!("{out}/{stem}.ps.cdxil"), + compile(&console, &dir, src, "ps", "ps_6_5"), + ) + .unwrap(); + std::fs::write(format!("{out}/{stem}.ps.dxil"), &ps_c.dxil).unwrap(); + } + if let Ok(mut v) = super::validator::Validator::load( + super::validator::Validator::default_path().as_deref(), + ) { + for s in [&vs_c, &ps_c] { + v.validate(&mut s.dxil.clone()) + .unwrap_or_else(|e| panic!("{name}: {e}")); + } + } + let (root_t, pso_t) = host.pipeline(&vs_c, &ps_c).unwrap(); + let ours = host + .draw( + &root_t, + &pso_t, + &draw(vec![ + (0, Root::Constants(user_data(&vs_c, &k))), + (1, Root::Constants(user_data(&ps_c, &k))), + ]), + ) + .unwrap(); + + let (vs_p, ps_p) = ( + compile(&pc, &dir, src, vs, "vs_6_5"), + compile(&pc, &dir, src, "ps", "ps_6_5"), + ); + // SAFETY: the PC container carries its root signature. + let root_p: ID3D12RootSignature = + unsafe { host.device.CreateRootSignature(0, &ps_p) }.unwrap(); + let pso_p = host.pipeline_with(&root_p, &vs_p, &ps_p).unwrap(); + let theirs = host + .draw( + &root_p, + &pso_p, + &draw(vec![ + (0, Root::Constants(k.to_vec())), + ( + 1, + Root::Table { + sampler: false, + index: 1, + }, + ), + ( + 2, + Root::Table { + sampler: true, + index: 1, + }, + ), + ]), + ) + .unwrap(); + + let worst = ours + .iter() + .flatten() + .zip(theirs.iter().flatten()) + .enumerate() + .map(|(i, (a, b))| (((a - b).abs() / b.abs().max(1.0)), i, *a, *b)) + .max_by(|x, y| x.0.total_cmp(&y.0)) + .unwrap(); + eprintln!( + "{name}: worst relative difference {:.2e} (at {}: {} vs {})", + worst.0, worst.1, worst.2, worst.3 + ); + if worst.0.is_nan() || worst.0 > 1e-3 { + failures.push(format!("{name}: {worst:?}")); + } + } + let _ = std::fs::remove_dir_all(&dir); + assert!(failures.is_empty(), "{failures:#?}"); +} + +#[test] +fn translated_mesh_shaders_draw_as_pc_ones() { + let Some((console, pc)) = tools() else { + eprintln!("no console or PC compiler; skipped"); + return; + }; + let Ok(host) = Host::new(false) else { + eprintln!("no SM 6.6 device; skipped"); + return; + }; + let dir = std::env::temp_dir().join(format!("leonida-diff-ms-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let k = [0.75f32, -1.5, 2.0, 0.125].map(f32::to_bits); + let draw = |roots, mesh_groups| Draw { + roots, + textures: &[], + samplers: &[], + vertices: &[], + stride: 0, + size: (16, 16), + mesh_groups, + }; + let mut failures = Vec::new(); + let only = std::env::var("LEONIDA_DIFF_ONLY").ok(); + for &(name, groups, src) in MS_CASES + .iter() + .filter(|c| only.as_ref().is_none_or(|o| o == c.0)) + { + let console_ms = compile(&console, &dir, src, "ms", "ms_6_5"); + let ms_c = match translate(&console_ms) { + Ok(s) => s, + Err(e) => { + failures.push(format!("{name}: {e}")); + continue; + } + }; + let ps_c = translate(&compile(&console, &dir, src, "mps", "ps_6_5")).unwrap(); + if let Ok(out) = std::env::var("LEONIDA_EMIT_DUMP") { + let stem = name.replace([' ', ','], "_"); + std::fs::write(format!("{out}/{stem}.ms.cdxil"), &console_ms).unwrap(); + std::fs::write(format!("{out}/{stem}.ms.dxil"), &ms_c.dxil).unwrap(); + } + if let Ok(mut v) = super::validator::Validator::load( + super::validator::Validator::default_path().as_deref(), + ) { + v.validate(&mut ms_c.dxil.clone()) + .unwrap_or_else(|e| panic!("{name}: {e}")); + } + let (root_t, pso_t) = host.mesh_pipeline(&ms_c, &ps_c).unwrap(); + let ours = host + .draw( + &root_t, + &pso_t, + &draw( + vec![ + (0, Root::Constants(user_data(&ms_c, &k))), + (1, Root::Constants(user_data(&ps_c, &k))), + ], + groups, + ), + ) + .unwrap(); + let (ms_p, ps_p) = ( + compile(&pc, &dir, src, "ms", "ms_6_5"), + compile(&pc, &dir, src, "mps", "ps_6_5"), + ); + // SAFETY: the PC container carries its root signature. + let root_p: ID3D12RootSignature = + unsafe { host.device.CreateRootSignature(0, &ms_p) }.unwrap(); + let pso_p = host.mesh_pipeline_with(&root_p, &ms_p, &ps_p).unwrap(); + let theirs = host + .draw( + &root_p, + &pso_p, + &draw(vec![(0, Root::Constants(k.to_vec()))], groups), + ) + .unwrap(); + let worst = ours + .iter() + .flatten() + .zip(theirs.iter().flatten()) + .enumerate() + .map(|(i, (a, b))| (((a - b).abs() / b.abs().max(1.0)), i, *a, *b)) + .max_by(|x, y| x.0.total_cmp(&y.0)) + .unwrap(); + let drawn = theirs.iter().filter(|t| t[3] != 0.0).count(); + eprintln!( + "{name}: {drawn} texels drawn; worst relative difference {:.2e} (at {}: {} vs {})", + worst.0, worst.1, worst.2, worst.3 + ); + if worst.0.is_nan() || worst.0 > 1e-3 || drawn == 0 { + // Which texels each drew (alpha set), row by row. + for (o, t) in ours.chunks(16).zip(theirs.chunks(16)) { + let row = |r: &[[f32; 4]]| -> String { + r.iter() + .map(|x| if x[3] != 0.0 { '#' } else { '.' }) + .collect() + }; + eprintln!(" {} {}", row(o), row(t)); + } + failures.push(format!("{name}: {worst:?}")); + } + } + let _ = std::fs::remove_dir_all(&dir); + assert!(failures.is_empty(), "{failures:#?}"); +} + +/// Where PC code and the console differ by design, the translation must +/// give the console's results: float-to-int conversions saturate and give +/// 0 for NaN (`v_cvt_i32/u32_f32`), the legacy multiply the compiler +/// uses for `*` gives 0 for 0 × NaN, `frac` never reaches 1.0 (it gives +/// the largest value below; some hosts' own `frac` gives 1.0), and sine +/// and cosine take turns: the sine of a half turn and the cosine of a +/// quarter turn are exactly +0 (the host's functions of the rounded angle +/// give about 1e-7). The compiler takes whole turns off itself, so large +/// angles cannot be tried from here. +#[test] +fn float_semantics_are_the_consoles() { + use super::host::{Dispatch, View}; + let Some((console, _)) = tools() else { + eprintln!("no console compiler; skipped"); + return; + }; + let Ok(host) = Host::new(false) else { + eprintln!("no SM 6.6 device; skipped"); + return; + }; + let dir = std::env::temp_dir().join(format!("leonida-float-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let src = r#"[RootSignature(RS)] [numthreads(4, 1, 1)] + void cs(uint i : SV_GroupIndex) { + float x = i == 0 ? k.x : i == 1 ? -k.x : i == 2 ? k.y : k.z; + outb.Store(4 * i, asuint(int(x))); + outb.Store(16 + 4 * i, uint(x)); + outb.Store(32 + 4 * i, asuint(x * k.w)); + float y = i == 0 ? k.w - 1e-10 : i == 1 ? k.z : i == 2 ? k.w - 1e-8 : k.z + 0.25; + outb.Store(48 + 4 * i, asuint(frac(y))); + float r = i == 0 ? k.w + 3.14159274 : i == 1 ? k.w + 1.0 + : i == 2 ? k.w - 3.14159274 : k.w + 1.57079637; + outb.Store(64 + 4 * i, asuint(i == 3 ? cos(r) : sin(r))); + }"#; + let cs = translate(&compile(&console, &dir, src, "cs", "cs_6_5")).unwrap(); + let (root, pso) = host.compute_pipeline(&cs).unwrap(); + // 1e30, NaN, 3.5, 0. + let k = [1e30f32.to_bits(), 0x7FC0_0000, 3.5f32.to_bits(), 0]; + let views = [ + View::Texture(1, 1, &[[0.0; 4]]), + View::Texture(1, 1, &[[0.0; 4]]), + View::Texture(1, 1, &[[0.0; 4]]), + View::Texture(1, 1, &[[0.0; 4]]), + View::Texture(1, 1, &[[0.0; 4]]), + View::RawUav(20), + View::TextureUav(1, 1), + ]; + let out = host + .dispatch( + &root, + &pso, + &Dispatch { + roots: vec![(0, Root::Constants(user_data(&cs, &k)))], + views: &views, + samplers: &[], + groups: [1, 1, 1], + }, + ) + .unwrap(); + let _ = std::fs::remove_dir_all(&dir); + assert_eq!( + out[0][..16], + [ + 0x7FFF_FFFF, + 0x8000_0000, + 0, + 3, // int + u32::MAX, + 0, + 0, + 3, // uint + 0, + 0, + 0, + 0, // x * 0, NaN included + 0x3F7F_FFFF, + 0.5f32.to_bits(), + 0x3F7F_FFFF, + 0.75f32.to_bits(), // frac + ] + ); + // sin(pi), sin(-pi) and cos(pi/2): the compiler turns radians into + // exactly 0.5, -0.5 and 0.25 turns. + assert_eq!([out[0][16], out[0][18], out[0][19]], [0, 0, 0]); + // An ordinary angle is untouched: sin(1 rad). + let one = f32::from_bits(out[0][17]); + assert!((one - 0.841_470_96).abs() < 1e-4, "{one}"); +} + +/// Equal bits, both zero (the console's legacy multiply gives +0 where PC +/// code gives -0), or two normal floats within 1e-3 relative. +fn close(a: u32, b: u32) -> bool { + let (x, y) = (f32::from_bits(a), f32::from_bits(b)); + a == b + || x == 0.0 && y == 0.0 + || x.is_normal() && y.is_normal() && (x - y).abs() <= 1e-3 * y.abs().max(1.0) +} + +#[test] +fn translated_compute_matches_pc() { + use super::host::{Dispatch, Stride, View}; + let Some((console, pc)) = tools() else { + eprintln!("no console or PC compiler; skipped"); + return; + }; + let Ok(host) = Host::new(false) else { + eprintln!("no SM 6.6 device; skipped"); + return; + }; + let dir = std::env::temp_dir().join(format!("leonida-diff-cs-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let k = [0.75f32, -1.5, 2.0, 0.125].map(f32::to_bits); + let texels: Vec<[f32; 4]> = (0..16) + .map(|i| [i as f32 / 16.0, (i % 4) as f32 * 0.3, 0.5, 1.0]) + .collect(); + let dummy = [[9.0f32; 4]]; + let cube_texels: Vec<[f32; 4]> = (0..96) + .map(|i| { + [ + (i / 16) as f32, + (i % 4) as f32 * 0.25, + (i / 4 % 4) as f32 * 0.25, + 1.0, + ] + }) + .collect(); + // Buffers: 16 float4, 8 structures of 16 bytes, 32 raw dwords; the + // root CBV's 16 float4 and the root SRV's 32 dwords. + let floats = |n: usize, scale: f32| -> Vec { + (0..n).map(|i| (i as f32 * scale - 3.0).to_bits()).collect() + }; + let typed_data = floats(64, 0.25); + let structured_data: Vec = (0..32u32) + .map(|i| { + if i % 4 == 1 { + i * 0x0101_0101 + } else { + (i as f32 * 0.5).to_bits() + } + }) + .collect(); + let raw_data: Vec = (0..32u32).map(|i| i.wrapping_mul(0x9E37_79B9)).collect(); + let views = [ + View::Texture(1, 1, &dummy), + View::Texture(4, 4, &texels), + View::Buffer { + data: &typed_data, + stride: Stride::Typed, + }, + View::Buffer { + data: &structured_data, + stride: Stride::Structured(16), + }, + View::Buffer { + data: &raw_data, + stride: Stride::Raw, + }, + View::RawUav(1024), + View::TextureUav(16, 16), + View::UintTextureUav(16, 16), + View::HalfUav(256), + ]; + let typed_view = |format, bytes| View::Buffer { + data: &raw_data, + stride: Stride::Format(format, bytes), + }; + let views: Vec = views + .into_iter() + .chain([ + typed_view(DXGI_FORMAT_R8G8B8A8_UNORM, 4), + typed_view(DXGI_FORMAT_R16G16_SNORM, 4), + typed_view(DXGI_FORMAT_R8G8B8A8_UINT, 4), + typed_view(DXGI_FORMAT_R10G10B10A2_UNORM, 4), + typed_view(DXGI_FORMAT_R16G16B16A16_UINT, 8), + typed_view(DXGI_FORMAT_R8_UNORM, 1), + typed_view(DXGI_FORMAT_R16_FLOAT, 2), + typed_view(DXGI_FORMAT_R8G8B8A8_SNORM, 4), + View::Cube(4, &cube_texels), + ]) + .collect(); + let root_cbv = floats(64, -0.125); + let root_srv: Vec = (0..32u32).map(|i| i * 0x0001_0003 + 7).collect(); + 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() + }; 2]; + let dispatch = |roots| Dispatch { + roots, + views: &views, + samplers: &samplers, + groups: [2, 2, 1], + }; + let mut failures = Vec::new(); + let only = std::env::var("LEONIDA_DIFF_ONLY").ok(); + let warp = std::env::var("LEONIDA_WARP").is_ok_and(|v| v == "1"); + for (name, src) in CS_CASES + .iter() + .filter(|c| only.as_ref().is_none_or(|o| o == c.0)) + .filter(|c| warp || !c.0.starts_with("terminates")) + { + let console_cs = compile(&console, &dir, src, "cs", "cs_6_5"); + if let Ok(out) = std::env::var("LEONIDA_EMIT_DUMP") { + let stem = name.replace([' ', ','], "_"); + std::fs::write(format!("{out}/{stem}.cs.cdxil"), &console_cs).unwrap(); + } + let cs_c = match translate(&console_cs) { + Ok(s) => s, + Err(e) => { + failures.push(format!("{name}: {e}")); + continue; + } + }; + if let Ok(out) = std::env::var("LEONIDA_EMIT_DUMP") { + let stem = name.replace([' ', ','], "_"); + std::fs::write(format!("{out}/{stem}.cs.dxil"), &cs_c.dxil).unwrap(); + } + if let Ok(mut v) = super::validator::Validator::load( + super::validator::Validator::default_path().as_deref(), + ) { + v.validate(&mut cs_c.dxil.clone()) + .unwrap_or_else(|e| panic!("{name}: {e}")); + } + let (root_t, pso_t) = match host.compute_pipeline(&cs_c) { + Ok(p) => p, + // WARP runs no fixed wave size of 64. + Err(e) if std::env::var("LEONIDA_WARP").is_ok_and(|v| v == "1") => { + eprintln!("{name}: skipped on WARP ({e})"); + continue; + } + Err(e) => panic!("{name}: {e}"), + }; + // Our root views follow the user data in root parameter order. + let mut roots = vec![(0, Root::Constants(user_data(&cs_c, &k)))]; + let mut root_views: Vec<(u8, bool)> = cs_c.root_cbvs.iter().map(|&s| (s, false)).collect(); + root_views.extend(cs_c.root_srvs.iter().map(|&s| (s, true))); + root_views.sort_unstable(); + for (n, (slot, srv)) in root_views.into_iter().enumerate() { + assert_eq!(slot, 4 + u8::from(srv), "{name}: root view"); + let data = if srv { + root_srv.clone() + } else { + root_cbv.clone() + }; + roots.push((1 + n as u32, Root::View { srv, data })); + } + let ours = host.dispatch(&root_t, &pso_t, &dispatch(roots)); + if name.starts_with("terminates") { + match ours { + Ok(_) => eprintln!("{name}: finished"), + Err(e) => failures.push(format!("{name}: {e}")), + } + continue; + } + let ours = ours.unwrap(); + let cs_p = compile(&pc, &dir, src, "cs", "cs_6_5"); + // SAFETY: the PC container carries its root signature. + let root_p: ID3D12RootSignature = + unsafe { host.device.CreateRootSignature(0, &cs_p) }.unwrap(); + let pso_p = host.compute_pipeline_with(&root_p, &cs_p).unwrap(); + let table = |sampler, index| Root::Table { sampler, index }; + let theirs = host + .dispatch( + &root_p, + &pso_p, + &dispatch(vec![ + (0, Root::Constants(k.to_vec())), + (1, table(false, 1)), + (2, table(true, 1)), + (3, table(false, 5)), + ( + 4, + Root::View { + srv: false, + data: root_cbv.clone(), + }, + ), + ( + 5, + Root::View { + srv: true, + data: root_srv.clone(), + }, + ), + (6, table(false, 9)), + ]), + ) + .unwrap(); + let mismatch = ours + .iter() + .flatten() + .zip(theirs.iter().flatten()) + .enumerate() + .find(|(_, (a, b))| !close(**a, **b)); + match mismatch { + None => eprintln!("{name}: equal"), + Some((at, (a, b))) => failures.push(format!( + "{name}: word {at}: {a:#x} ({}) vs {b:#x} ({})", + f32::from_bits(*a), + f32::from_bits(*b) + )), + } + } + let _ = std::fs::remove_dir_all(&dir); + assert!(failures.is_empty(), "{failures:#?}"); +} diff --git a/crates/leonida-shader/src/emit/host.rs b/crates/leonida-shader/src/emit/host.rs new file mode 100644 index 000000000..c0d43ae78 --- /dev/null +++ b/crates/leonida-shader/src/emit/host.rs @@ -0,0 +1,1453 @@ +//! Host D3D12 checks for emitted shaders: pipeline creation and, for +//! tests, drawing a full-screen triangle and reading the target back. + +use std::ffi::CString; + +use windows::Win32::Graphics::Direct3D::*; +use windows::Win32::Graphics::Direct3D12::*; +use windows::Win32::Graphics::Dxgi::Common::*; +use windows::Win32::Graphics::Dxgi::*; +use windows::core::{Interface, PCSTR}; + +use super::HostShader; +use super::container::SigElement; +use crate::dxbc::{Container, FourCC}; + +pub struct Host { + pub device: ID3D12Device, +} + +/// What the stage declares that a pipeline must match. +fn sig(dxil: &[u8], fourcc: FourCC) -> Result, String> { + let c = Container::parse(dxil).map_err(|e| e.to_string())?; + match c.part(fourcc) { + Some(p) => super::signature(p.data).map_err(|e| e.to_string()), + None => Ok(Vec::new()), + } +} + +fn format(e: &SigElement) -> DXGI_FORMAT { + let i = usize::from(e.cols.clamp(1, 4)) - 1; + match e.comp { + 9 => [ + DXGI_FORMAT_R32_FLOAT, + DXGI_FORMAT_R32G32_FLOAT, + DXGI_FORMAT_R32G32B32_FLOAT, + DXGI_FORMAT_R32G32B32A32_FLOAT, + ][i], + 4 => [ + DXGI_FORMAT_R32_SINT, + DXGI_FORMAT_R32G32_SINT, + DXGI_FORMAT_R32G32B32_SINT, + DXGI_FORMAT_R32G32B32A32_SINT, + ][i], + _ => [ + DXGI_FORMAT_R32_UINT, + DXGI_FORMAT_R32G32_UINT, + DXGI_FORMAT_R32G32B32_UINT, + DXGI_FORMAT_R32G32B32A32_UINT, + ][i], + } +} + +fn target_format(e: &SigElement) -> DXGI_FORMAT { + match e.comp { + 9 => DXGI_FORMAT_R32G32B32A32_FLOAT, + 4 => DXGI_FORMAT_R32G32B32A32_SINT, + _ => DXGI_FORMAT_R32G32B32A32_UINT, + } +} + +fn err(e: windows::core::Error) -> String { + e.message().to_string() +} + +impl Host { + /// The default adapter, or WARP with `warp` (or `LEONIDA_WARP=1`). + pub fn new(warp: bool) -> Result { + let warp = warp || std::env::var("LEONIDA_WARP").is_ok_and(|v| v == "1"); + // SAFETY: plain D3D12/DXGI calls with valid out pointers. + unsafe { + // `LEONIDA_D3D12_DEBUG`: the debug layer, whose messages a + // refused pipeline's error then carries. + if std::env::var_os("LEONIDA_D3D12_DEBUG").is_some() { + let mut debug: Option = None; + if D3D12GetDebugInterface(&mut debug).is_ok() + && let Some(debug) = debug + { + debug.EnableDebugLayer(); + } + } + let mut device: Option = None; + if warp { + let factory: IDXGIFactory4 = + CreateDXGIFactory2(DXGI_CREATE_FACTORY_FLAGS(0)).map_err(err)?; + let adapter: IDXGIAdapter = factory.EnumWarpAdapter().map_err(err)?; + D3D12CreateDevice(&adapter, D3D_FEATURE_LEVEL_12_0, &mut device).map_err(err)?; + } else { + D3D12CreateDevice(None, D3D_FEATURE_LEVEL_12_0, &mut device).map_err(err)?; + // A machine without a graphics card gives the software + // adapter as its default device (a hosted test runner, + // whose first adapter is a display stub that cannot make a + // device): that is no hardware device, and the tests that + // ask for one skip it, as they do where there is none. + if let Some(made) = &device { + let factory: IDXGIFactory4 = + CreateDXGIFactory2(DXGI_CREATE_FACTORY_FLAGS(0)).map_err(err)?; + if let Ok(adapter) = factory.EnumAdapterByLuid::(made.GetAdapterLuid()) + && let Ok(desc) = adapter.GetDesc1() + && (desc.Flags & 2 != 0 || (desc.VendorId == 0x1414 && desc.DeviceId == 0x8c)) + { + return Err("the default device is the software adapter".to_owned()); + } + } + } + let device = device.ok_or("no device")?; + let mut sm = D3D12_FEATURE_DATA_SHADER_MODEL { + HighestShaderModel: D3D_SHADER_MODEL_6_6, + }; + device + .CheckFeatureSupport( + D3D12_FEATURE_SHADER_MODEL, + (&raw mut sm).cast(), + size_of_val(&sm) as u32, + ) + .map_err(err)?; + if sm.HighestShaderModel.0 < D3D_SHADER_MODEL_6_6.0 { + return Err(format!( + "the device supports SM {:#x} only", + sm.HighestShaderModel.0 + )); + } + Ok(Host { device }) + } + } + + /// The root signature translated shaders expect: user data per stage + /// at `b0`, immediate samplers per stage at `s`, heaps directly + /// indexed. + pub fn root_signature( + &self, + vs: &HostShader, + ps: &HostShader, + ) -> Result { + self.root_signature_for(&[ + (vs, D3D12_SHADER_VISIBILITY_VERTEX), + (ps, D3D12_SHADER_VISIBILITY_PIXEL), + ]) + } + + /// The root signature for these stages: user data of stage k is root + /// parameter k, root views follow. + pub fn root_signature_for( + &self, + stages: &[(&HostShader, D3D12_SHADER_VISIBILITY)], + ) -> Result { + let mut params: Vec = stages + .iter() + .map(|&(s, vis)| D3D12_ROOT_PARAMETER1 { + ParameterType: D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS, + Anonymous: D3D12_ROOT_PARAMETER1_0 { + Constants: D3D12_ROOT_CONSTANTS { + ShaderRegister: 0, + RegisterSpace: super::USER_DATA_SPACE, + Num32BitValues: s.user_data_dwords().max(1), + }, + }, + ShaderVisibility: vis, + }) + .collect(); + // By slot, then kind: 0 CBV, 1 SRV, 2 UAV. + let mut views: Vec<(u8, u8)> = stages + .iter() + .flat_map(|(s, _)| { + let cbvs = s.root_cbvs.iter().map(|&r| (r, 0)); + let srvs = s.root_srvs.iter().map(|&r| (r, 1)); + cbvs.chain(srvs).chain(s.root_uavs.iter().map(|&r| (r, 2))) + }) + .collect(); + views.sort_unstable(); + views.dedup(); + for (slot, kind) in views { + params.push(D3D12_ROOT_PARAMETER1 { + ParameterType: match kind { + 1 => D3D12_ROOT_PARAMETER_TYPE_SRV, + 2 => D3D12_ROOT_PARAMETER_TYPE_UAV, + _ => D3D12_ROOT_PARAMETER_TYPE_CBV, + }, + Anonymous: D3D12_ROOT_PARAMETER1_0 { + Descriptor: D3D12_ROOT_DESCRIPTOR1 { + ShaderRegister: u32::from(slot), + RegisterSpace: super::ROOT_CBV_SPACE, + Flags: D3D12_ROOT_DESCRIPTOR_FLAG_NONE, + }, + }, + ShaderVisibility: D3D12_SHADER_VISIBILITY_ALL, + }); + } + let mut samplers = Vec::new(); + for &(s, vis) in stages { + for (n, d) in s.static_samplers.iter().enumerate() { + let [u, v, w] = d.address.map(|a| D3D12_TEXTURE_ADDRESS_MODE(a as i32)); + samplers.push(D3D12_STATIC_SAMPLER_DESC { + Filter: D3D12_FILTER(d.filter as i32), + AddressU: u, + AddressV: v, + AddressW: w, + MipLODBias: d.mip_lod_bias, + MaxAnisotropy: d.max_anisotropy, + ComparisonFunc: D3D12_COMPARISON_FUNC(d.comparison as i32), + BorderColor: D3D12_STATIC_BORDER_COLOR(d.border as i32), + MinLOD: d.min_lod, + MaxLOD: d.max_lod, + ShaderRegister: n as u32, + RegisterSpace: super::SAMPLER_SPACE, + ShaderVisibility: vis, + }); + } + } + let desc = D3D12_VERSIONED_ROOT_SIGNATURE_DESC { + Version: D3D_ROOT_SIGNATURE_VERSION_1_1, + Anonymous: D3D12_VERSIONED_ROOT_SIGNATURE_DESC_0 { + Desc_1_1: D3D12_ROOT_SIGNATURE_DESC1 { + NumParameters: params.len() as u32, + pParameters: params.as_ptr(), + NumStaticSamplers: samplers.len() as u32, + pStaticSamplers: samplers.as_ptr(), + Flags: D3D12_ROOT_SIGNATURE_FLAG_ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT + | D3D12_ROOT_SIGNATURE_FLAG_CBV_SRV_UAV_HEAP_DIRECTLY_INDEXED + | D3D12_ROOT_SIGNATURE_FLAG_SAMPLER_HEAP_DIRECTLY_INDEXED, + }, + }, + }; + // SAFETY: the description points at live arrays. + unsafe { + let mut blob = None; + let mut error = None; + D3D12SerializeVersionedRootSignature(&desc, &mut blob, Some(&mut error)) + .map_err(err)?; + let blob: ID3DBlob = blob.ok_or("no root signature blob")?; + let bytes = std::slice::from_raw_parts( + blob.GetBufferPointer().cast::(), + blob.GetBufferSize(), + ); + self.device.CreateRootSignature(0, bytes).map_err(err) + } + } + + /// A compute pipeline; user data is root parameter 0. + pub fn compute_pipeline( + &self, + cs: &HostShader, + ) -> Result<(ID3D12RootSignature, ID3D12PipelineState), String> { + let root = self.root_signature_for(&[(cs, D3D12_SHADER_VISIBILITY_ALL)])?; + let pso = self.compute_pipeline_with(&root, &cs.dxil)?; + Ok((root, pso)) + } + + pub fn compute_pipeline_with( + &self, + root: &ID3D12RootSignature, + cs: &[u8], + ) -> Result { + let desc = D3D12_COMPUTE_PIPELINE_STATE_DESC { + // SAFETY: a borrowed pointer the descriptor never releases. + pRootSignature: unsafe { std::mem::transmute_copy(root) }, + CS: D3D12_SHADER_BYTECODE { + pShaderBytecode: cs.as_ptr().cast(), + BytecodeLength: cs.len(), + }, + ..Default::default() + }; + // SAFETY: the description points at live data. + unsafe { self.device.CreateComputePipelineState(&desc) }.map_err(|e| self.explained(e)) + } + + /// The error with the debug layer's messages since the last call, if + /// the layer is on (`LEONIDA_D3D12_DEBUG`). + fn explained(&self, e: windows::core::Error) -> String { + let mut text = err(e); + let Ok(queue) = self.device.cast::() else { + return text; + }; + // SAFETY: each message is read into a buffer of the size the queue + // asks for, aligned for the message header. + unsafe { + for i in 0..queue.GetNumStoredMessages() { + let mut len = 0usize; + let _ = queue.GetMessage(i, None, &mut len); + let mut buffer = vec![0u64; len.div_ceil(8)]; + let message = buffer.as_mut_ptr().cast::(); + if queue.GetMessage(i, Some(message), &mut len).is_ok() { + let m = &*message; + let bytes = std::slice::from_raw_parts(m.pDescription, m.DescriptionByteLength.saturating_sub(1)); + text.push_str(" | "); + text.push_str(&String::from_utf8_lossy(bytes)); + } + } + queue.ClearStoredMessages(); + } + text + } + + /// A graphics pipeline from a vertex and a pixel shader, with float or + /// integer 32-bit targets as the pixel shader writes them. + pub fn pipeline( + &self, + vs: &HostShader, + ps: &HostShader, + ) -> Result<(ID3D12RootSignature, ID3D12PipelineState), String> { + let root = self.root_signature(vs, ps)?; + let pso = self.pipeline_with(&root, &vs.dxil, &ps.dxil)?; + Ok((root, pso)) + } + + /// A graphics pipeline with the given root signature; vertex inputs + /// packed in register order. + pub fn pipeline_with( + &self, + root: &ID3D12RootSignature, + vs: &[u8], + ps: &[u8], + ) -> Result { + self.pipeline_with_gs(root, vs, None, ps) + } + + /// As [`Host::pipeline_with`], with a geometry shader between the two + /// (the rectangle stage, `rect_list_gs`). + pub fn pipeline_with_gs( + &self, + root: &ID3D12RootSignature, + vs: &[u8], + gs: Option<&[u8]>, + ps: &[u8], + ) -> Result { + let inputs = sig(vs, FourCC::ISG1)?; + let names: Vec = inputs + .iter() + .map(|e| CString::new(e.name.clone()).unwrap()) + .collect(); + let layout: Vec = inputs + .iter() + .zip(&names) + .filter(|(e, _)| e.kind == 0) + .map(|(e, n)| D3D12_INPUT_ELEMENT_DESC { + SemanticName: PCSTR(n.as_ptr().cast()), + SemanticIndex: e.index, + Format: format(e), + InputSlot: 0, + AlignedByteOffset: D3D12_APPEND_ALIGNED_ELEMENT, + InputSlotClass: D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, + InstanceDataStepRate: 0, + }) + .collect(); + let outputs = sig(ps, FourCC::OSG1)?; + let mut desc = D3D12_GRAPHICS_PIPELINE_STATE_DESC { + // SAFETY: a borrowed pointer the descriptor never releases. + pRootSignature: unsafe { std::mem::transmute_copy(root) }, + VS: D3D12_SHADER_BYTECODE { + pShaderBytecode: vs.as_ptr().cast(), + BytecodeLength: vs.len(), + }, + PS: D3D12_SHADER_BYTECODE { + pShaderBytecode: ps.as_ptr().cast(), + BytecodeLength: ps.len(), + }, + GS: gs.map_or(D3D12_SHADER_BYTECODE::default(), |gs| D3D12_SHADER_BYTECODE { + pShaderBytecode: gs.as_ptr().cast(), + BytecodeLength: gs.len(), + }), + SampleMask: u32::MAX, + RasterizerState: D3D12_RASTERIZER_DESC { + FillMode: D3D12_FILL_MODE_SOLID, + CullMode: D3D12_CULL_MODE_NONE, + DepthClipEnable: true.into(), + ..Default::default() + }, + InputLayout: D3D12_INPUT_LAYOUT_DESC { + pInputElementDescs: layout.as_ptr(), + NumElements: layout.len() as u32, + }, + PrimitiveTopologyType: D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE, + SampleDesc: DXGI_SAMPLE_DESC { + Count: 1, + Quality: 0, + }, + ..Default::default() + }; + for rt in &mut desc.BlendState.RenderTarget { + rt.RenderTargetWriteMask = D3D12_COLOR_WRITE_ENABLE_ALL.0 as u8; + } + for o in outputs.iter().filter(|o| o.kind == 16) { + let n = o.row.unwrap_or(0) as usize; + desc.RTVFormats[n] = target_format(o); + desc.NumRenderTargets = desc.NumRenderTargets.max(n as u32 + 1); + } + if outputs.iter().any(|o| matches!(o.kind, 17..=19)) { + desc.DSVFormat = DXGI_FORMAT_D32_FLOAT; + desc.DepthStencilState.DepthEnable = true.into(); + desc.DepthStencilState.DepthWriteMask = D3D12_DEPTH_WRITE_MASK_ALL; + desc.DepthStencilState.DepthFunc = D3D12_COMPARISON_FUNC_ALWAYS; + } + if outputs.iter().any(|o| o.kind == 20) { + desc.DSVFormat = DXGI_FORMAT_D32_FLOAT_S8X24_UINT; + desc.DepthStencilState.StencilEnable = true.into(); + } + // SAFETY: the description points at live data. + let pso = unsafe { self.device.CreateGraphicsPipelineState(&desc) }; + pso.map_err(err) + } + + /// A mesh pipeline from a mesh and a pixel shader (user data of the mesh + /// stage is root parameter 0, the pixel stage's 1). + pub fn mesh_pipeline( + &self, + ms: &HostShader, + ps: &HostShader, + ) -> Result<(ID3D12RootSignature, ID3D12PipelineState), String> { + let root = self.root_signature_for(&[ + (ms, D3D12_SHADER_VISIBILITY_MESH), + (ps, D3D12_SHADER_VISIBILITY_PIXEL), + ])?; + let pso = self.mesh_pipeline_with(&root, &ms.dxil, &ps.dxil)?; + Ok((root, pso)) + } + + /// A mesh pipeline with the given root signature: the pipeline-state + /// stream form, with the targets [`Host::pipeline_with`] would use. + pub fn mesh_pipeline_with( + &self, + root: &ID3D12RootSignature, + ms: &[u8], + ps: &[u8], + ) -> Result { + /// A stream subobject: its type, then its description, pointer-aligned. + #[repr(C, align(8))] + struct Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE, T); + #[repr(C)] + struct Stream { + root: Sub<*mut std::ffi::c_void>, + ms: Sub, + ps: Sub, + blend: Sub, + mask: Sub, + raster: Sub, + depth: Sub, + targets: Sub, + dsv: Sub, + samples: Sub, + } + let outputs = sig(ps, FourCC::OSG1)?; + let mut blend = D3D12_BLEND_DESC::default(); + for rt in &mut blend.RenderTarget { + rt.RenderTargetWriteMask = D3D12_COLOR_WRITE_ENABLE_ALL.0 as u8; + } + let mut targets = D3D12_RT_FORMAT_ARRAY::default(); + for o in outputs.iter().filter(|o| o.kind == 16) { + let n = o.row.unwrap_or(0) as usize; + targets.RTFormats[n] = target_format(o); + targets.NumRenderTargets = targets.NumRenderTargets.max(n as u32 + 1); + } + let mut depth = D3D12_DEPTH_STENCIL_DESC::default(); + let mut dsv = DXGI_FORMAT_UNKNOWN; + if outputs.iter().any(|o| matches!(o.kind, 17..=19)) { + dsv = DXGI_FORMAT_D32_FLOAT; + depth.DepthEnable = true.into(); + depth.DepthWriteMask = D3D12_DEPTH_WRITE_MASK_ALL; + depth.DepthFunc = D3D12_COMPARISON_FUNC_ALWAYS; + } + if outputs.iter().any(|o| o.kind == 20) { + dsv = DXGI_FORMAT_D32_FLOAT_S8X24_UINT; + depth.StencilEnable = true.into(); + } + let code = |b: &[u8]| D3D12_SHADER_BYTECODE { + pShaderBytecode: b.as_ptr().cast(), + BytecodeLength: b.len(), + }; + let mut stream = Stream { + root: Sub( + D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_ROOT_SIGNATURE, + root.as_raw(), + ), + ms: Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_MS, code(ms)), + ps: Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_PS, code(ps)), + blend: Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_BLEND, blend), + mask: Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_SAMPLE_MASK, u32::MAX), + raster: Sub( + D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_RASTERIZER, + D3D12_RASTERIZER_DESC { + FillMode: D3D12_FILL_MODE_SOLID, + CullMode: D3D12_CULL_MODE_NONE, + DepthClipEnable: true.into(), + ..Default::default() + }, + ), + depth: Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DEPTH_STENCIL, depth), + targets: Sub( + D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_RENDER_TARGET_FORMATS, + targets, + ), + dsv: Sub( + D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DEPTH_STENCIL_FORMAT, + dsv, + ), + samples: Sub( + D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_SAMPLE_DESC, + DXGI_SAMPLE_DESC { + Count: 1, + Quality: 0, + }, + ), + }; + let desc = D3D12_PIPELINE_STATE_STREAM_DESC { + SizeInBytes: size_of::(), + pPipelineStateSubobjectStream: (&raw mut stream).cast(), + }; + let device: ID3D12Device2 = self.device.cast().map_err(err)?; + // SAFETY: the stream points at live data and outlives the call. + unsafe { device.CreatePipelineState(&desc) }.map_err(err) + } +} + +/// A vertex shader that feeds `ps`'s inputs (zeros) and a position. +pub fn stub_vs(ps: &HostShader) -> Result { + let inputs = sig(&ps.dxil, FourCC::ISG1)?; + let mut outputs: Vec = inputs + .into_iter() + .filter(|e| matches!(e.kind, 0 | 3 | 6 | 7)) + .collect(); + if !outputs.iter().any(|e| e.kind == 3) { + let row = outputs + .iter() + .filter_map(|e| e.row) + .map(|r| r + 1) + .max() + .unwrap_or(0); + outputs.push(SigElement { + name: "SV_Position".into(), + index: 0, + kind: 3, + comp: 9, + interp: 4, + row: Some(row), + col: 0, + cols: 4, + usage: 0, + half: false, + }); + } + Ok(stub(false, outputs)) +} + +/// A pixel shader that reads nothing and writes target 0. +pub fn stub_ps() -> HostShader { + let target = SigElement { + name: "SV_Target".into(), + index: 0, + kind: 16, + comp: 9, + interp: 0, + row: Some(0), + col: 0, + cols: 4, + usage: 0, + half: false, + }; + stub(true, vec![target]) +} + +fn stub(pixel: bool, outputs: Vec) -> HostShader { + use super::bitcode::{Attr, Term}; + let mut s = super::shader::Shader::new(pixel); + let b = s.entry; + for (id, e) in outputs.iter().enumerate() { + for col in 0..e.cols { + let (suffix, zero) = if e.comp == 9 { + (".f32", s.m.f32(0)) + } else { + (".i32", s.m.i32(0)) + }; + let args = [s.m.i32(id as u32), s.m.i32(0), s.m.i8(col), zero]; + s.op( + b, + &format!("storeOutput{suffix}"), + Attr::NoUnwind, + s.t.void, + 5, + &args, + ); + } + } + s.outputs = outputs + .into_iter() + .map(|mut e| { + e.usage = (1 << e.cols) - 1; + e + }) + .collect(); + s.m.terminate(b, Term::Ret); + HostShader { + stage: if pixel { + crate::native::HwStage::Ps + } else { + crate::native::HwStage::Vs + }, + 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(), + } +} + +/// A root argument for [`Host::draw`]. +#[cfg(test)] +pub enum Root { + Constants(Vec), + /// A table starting at this heap index. + Table { + sampler: bool, + index: usize, + }, + /// A root CBV (or with `srv`, a root SRV) over a buffer of these + /// dwords ([`Host::dispatch`] only). + View { + srv: bool, + data: Vec, + }, +} + +/// Bindings for [`Host::draw`]: root arguments and the heap contents. +#[cfg(test)] +pub struct Draw<'a> { + pub roots: Vec<(u32, Root)>, + /// RGBA32F textures (width, height, texels) at view-heap indices 0.. + pub textures: &'a [(u32, u32, &'a [[f32; 4]])], + /// Samplers at sampler-heap indices 0.. + pub samplers: &'a [D3D12_SAMPLER_DESC], + /// Three vertices of stride bytes (none for position-free layouts). + pub vertices: &'a [f32], + pub stride: u32, + pub size: (u32, u32), + /// Mesh thread groups to dispatch instead of drawing (0: draw). + pub mesh_groups: u32, +} + +#[cfg(test)] +impl Host { + /// Draws one triangle into an RGBA32F target and returns its texels. + pub fn draw( + &self, + root: &ID3D12RootSignature, + pso: &ID3D12PipelineState, + d: &Draw, + ) -> Result, String> { + let dev = &self.device; + let (w, h) = d.size; + // SAFETY: D3D12 calls with descriptions that outlive them; resources + // are kept alive until the fence says the GPU is done. + unsafe { + let queue: ID3D12CommandQueue = dev + .CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC { + Type: D3D12_COMMAND_LIST_TYPE_DIRECT, + ..Default::default() + }) + .map_err(err)?; + let alloc: ID3D12CommandAllocator = dev + .CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT) + .map_err(err)?; + let list: ID3D12GraphicsCommandList = dev + .CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &alloc, pso) + .map_err(err)?; + let tex_desc = |w: u32, h: u32, flags| D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D, + Width: u64::from(w), + Height: h, + DepthOrArraySize: 1, + MipLevels: 1, + Format: DXGI_FORMAT_R32G32B32A32_FLOAT, + SampleDesc: DXGI_SAMPLE_DESC { + Count: 1, + Quality: 0, + }, + Flags: flags, + ..Default::default() + }; + let buf_desc = |size: u64| D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, + Width: size, + Height: 1, + DepthOrArraySize: 1, + MipLevels: 1, + SampleDesc: DXGI_SAMPLE_DESC { + Count: 1, + Quality: 0, + }, + Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, + ..Default::default() + }; + let heap = |t| D3D12_HEAP_PROPERTIES { + Type: t, + ..Default::default() + }; + let make = |props: D3D12_HEAP_TYPE, + desc: &D3D12_RESOURCE_DESC, + state, + clear: Option<&D3D12_CLEAR_VALUE>| { + let mut r: Option = None; + dev.CreateCommittedResource( + &heap(props), + D3D12_HEAP_FLAG_NONE, + desc, + state, + clear.map(|c| c as *const _), + &mut r, + ) + .map_err(err)?; + r.ok_or_else(|| "no resource".to_string()) + }; + let target = make( + D3D12_HEAP_TYPE_DEFAULT, + &tex_desc(w, h, D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET), + D3D12_RESOURCE_STATE_RENDER_TARGET, + Some(&D3D12_CLEAR_VALUE { + Format: DXGI_FORMAT_R32G32B32A32_FLOAT, + Anonymous: D3D12_CLEAR_VALUE_0 { Color: [0.0; 4] }, + }), + )?; + let rtv_heap: ID3D12DescriptorHeap = dev + .CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC { + Type: D3D12_DESCRIPTOR_HEAP_TYPE_RTV, + NumDescriptors: 1, + ..Default::default() + }) + .map_err(err)?; + let rtv = rtv_heap.GetCPUDescriptorHandleForHeapStart(); + dev.CreateRenderTargetView(&target, None, rtv); + let views: ID3D12DescriptorHeap = dev + .CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC { + Type: D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, + NumDescriptors: d.textures.len().max(1) as u32, + Flags: D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE, + ..Default::default() + }) + .map_err(err)?; + let sampler_heap: ID3D12DescriptorHeap = dev + .CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC { + Type: D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER, + NumDescriptors: d.samplers.len().max(1) as u32, + Flags: D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE, + ..Default::default() + }) + .map_err(err)?; + let view_size = dev + .GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV) + as usize; + let sampler_size = + dev.GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER) as usize; + let mut keep = Vec::new(); + for (i, &(tw, th, texels)) in d.textures.iter().enumerate() { + let tex = make( + D3D12_HEAP_TYPE_DEFAULT, + &tex_desc(tw, th, D3D12_RESOURCE_FLAG_NONE), + D3D12_RESOURCE_STATE_COPY_DEST, + None, + )?; + let pitch = (tw as usize * 16).next_multiple_of(256); + let upload = make( + D3D12_HEAP_TYPE_UPLOAD, + &buf_desc((pitch * th as usize) as u64), + D3D12_RESOURCE_STATE_GENERIC_READ, + None, + )?; + let mut p = std::ptr::null_mut(); + upload.Map(0, None, Some(&mut p)).map_err(err)?; + for y in 0..th as usize { + let row = &texels[y * tw as usize..(y + 1) * tw as usize]; + std::ptr::copy_nonoverlapping( + row.as_ptr().cast::(), + p.cast::().add(y * pitch), + row.len() * 16, + ); + } + upload.Unmap(0, None); + let dst = D3D12_TEXTURE_COPY_LOCATION { + pResource: std::mem::transmute_copy(&tex), + Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, + Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { + SubresourceIndex: 0, + }, + }; + let src = D3D12_TEXTURE_COPY_LOCATION { + pResource: std::mem::transmute_copy(&upload), + Type: D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT, + Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { + PlacedFootprint: D3D12_PLACED_SUBRESOURCE_FOOTPRINT { + Offset: 0, + Footprint: D3D12_SUBRESOURCE_FOOTPRINT { + Format: DXGI_FORMAT_R32G32B32A32_FLOAT, + Width: tw, + Height: th, + Depth: 1, + RowPitch: pitch as u32, + }, + }, + }, + }; + list.CopyTextureRegion(&dst, 0, 0, 0, &src, None); + list.ResourceBarrier(&[transition( + &tex, + D3D12_RESOURCE_STATE_COPY_DEST, + D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE + | D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE, + )]); + let mut at = views.GetCPUDescriptorHandleForHeapStart(); + at.ptr += i * view_size; + dev.CreateShaderResourceView(&tex, None, at); + keep.push(tex); + keep.push(upload); + } + for (i, s) in d.samplers.iter().enumerate() { + let mut at = sampler_heap.GetCPUDescriptorHandleForHeapStart(); + at.ptr += i * sampler_size; + dev.CreateSampler(s, at); + } + let vb = if d.vertices.is_empty() { + None + } else { + let bytes = d.vertices.len() * 4; + let vb = make( + D3D12_HEAP_TYPE_UPLOAD, + &buf_desc(bytes as u64), + D3D12_RESOURCE_STATE_GENERIC_READ, + None, + )?; + let mut p = std::ptr::null_mut(); + vb.Map(0, None, Some(&mut p)).map_err(err)?; + std::ptr::copy_nonoverlapping( + d.vertices.as_ptr().cast::(), + p.cast::(), + bytes, + ); + vb.Unmap(0, None); + Some(vb) + }; + list.SetDescriptorHeaps(&[Some(views.clone()), Some(sampler_heap.clone())]); + list.SetGraphicsRootSignature(root); + for (param, arg) in &d.roots { + match arg { + Root::Constants(data) => list.SetGraphicsRoot32BitConstants( + *param, + data.len() as u32, + data.as_ptr().cast(), + 0, + ), + Root::Table { sampler, index } => { + let (heap, size) = if *sampler { + (&sampler_heap, sampler_size) + } else { + (&views, view_size) + }; + let mut at = heap.GetGPUDescriptorHandleForHeapStart(); + at.ptr += (index * size) as u64; + list.SetGraphicsRootDescriptorTable(*param, at); + } + Root::View { .. } => return Err("root views in a draw".into()), + } + } + list.OMSetRenderTargets(1, Some(&rtv), false, None); + list.RSSetViewports(&[D3D12_VIEWPORT { + Width: w as f32, + Height: h as f32, + MaxDepth: 1.0, + ..Default::default() + }]); + list.RSSetScissorRects(&[windows::Win32::Foundation::RECT { + right: w as i32, + bottom: h as i32, + ..Default::default() + }]); + list.IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST); + if let Some(vb) = &vb { + list.IASetVertexBuffers( + 0, + Some(&[D3D12_VERTEX_BUFFER_VIEW { + BufferLocation: vb.GetGPUVirtualAddress(), + SizeInBytes: (d.vertices.len() * 4) as u32, + StrideInBytes: d.stride, + }]), + ); + } + if d.mesh_groups > 0 { + let list6: ID3D12GraphicsCommandList6 = list.cast().map_err(err)?; + list6.DispatchMesh(d.mesh_groups, 1, 1); + } else { + list.DrawInstanced(3, 1, 0, 0); + } + list.ResourceBarrier(&[transition( + &target, + D3D12_RESOURCE_STATE_RENDER_TARGET, + D3D12_RESOURCE_STATE_COPY_SOURCE, + )]); + let pitch = (w as usize * 16).next_multiple_of(256); + let readback = make( + D3D12_HEAP_TYPE_READBACK, + &buf_desc((pitch * h as usize) as u64), + D3D12_RESOURCE_STATE_COPY_DEST, + None, + )?; + let dst = D3D12_TEXTURE_COPY_LOCATION { + pResource: std::mem::transmute_copy(&readback), + Type: D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT, + Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { + PlacedFootprint: D3D12_PLACED_SUBRESOURCE_FOOTPRINT { + Offset: 0, + Footprint: D3D12_SUBRESOURCE_FOOTPRINT { + Format: DXGI_FORMAT_R32G32B32A32_FLOAT, + Width: w, + Height: h, + Depth: 1, + RowPitch: pitch as u32, + }, + }, + }, + }; + let src = D3D12_TEXTURE_COPY_LOCATION { + pResource: std::mem::transmute_copy(&target), + Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, + Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { + SubresourceIndex: 0, + }, + }; + list.CopyTextureRegion(&dst, 0, 0, 0, &src, None); + list.Close().map_err(err)?; + queue.ExecuteCommandLists(&[Some(list.cast().map_err(err)?)]); + let fence: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).map_err(err)?; + queue.Signal(&fence, 1).map_err(err)?; + while fence.GetCompletedValue() < 1 { + if dev.GetDeviceRemovedReason().is_err() { + return Err(format!( + "device removed: {}", + err(dev.GetDeviceRemovedReason().unwrap_err()) + )); + } + std::thread::yield_now(); + } + if let Err(e) = dev.GetDeviceRemovedReason() { + return Err(format!("device removed: {}", err(e))); + } + let mut p = std::ptr::null_mut(); + readback.Map(0, None, Some(&mut p)).map_err(err)?; + let mut out = Vec::with_capacity((w * h) as usize); + for y in 0..h as usize { + let row = std::slice::from_raw_parts( + p.cast::().add(y * pitch).cast::<[f32; 4]>(), + w as usize, + ); + out.extend_from_slice(row); + } + readback.Unmap(0, None); + drop(keep); + Ok(out) + } + } +} + +#[cfg(test)] +fn transition( + r: &ID3D12Resource, + before: D3D12_RESOURCE_STATES, + after: D3D12_RESOURCE_STATES, +) -> D3D12_RESOURCE_BARRIER { + D3D12_RESOURCE_BARRIER { + Type: D3D12_RESOURCE_BARRIER_TYPE_TRANSITION, + Flags: D3D12_RESOURCE_BARRIER_FLAG_NONE, + Anonymous: D3D12_RESOURCE_BARRIER_0 { + Transition: std::mem::ManuallyDrop::new(D3D12_RESOURCE_TRANSITION_BARRIER { + // SAFETY: a borrowed pointer; the barrier never releases it. + pResource: unsafe { std::mem::transmute_copy(r) }, + Subresource: D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES, + StateBefore: before, + StateAfter: after, + }), + }, + } +} + +/// A view in the heap for [`Host::dispatch`]. +#[cfg(test)] +pub enum View<'a> { + /// An RGBA32F texture SRV (width, height, texels). + Texture(u32, u32, &'a [[f32; 4]]), + /// An RGBA32F cube SRV (face size, texels of faces +x -x +y -y +z -z). + Cube(u32, &'a [[f32; 4]]), + /// A raw buffer UAV of this many dwords, zeroed. + RawUav(u32), + /// An RGBA32F texture UAV (width, height), zeroed. + TextureUav(u32, u32), + /// An R32_UINT texture UAV (width, height), zeroed (atomics). + UintTextureUav(u32, u32), + /// A typed RGBA16F buffer UAV of this many elements, zeroed. + HalfUav(u32), + /// A constant buffer of these dwords. + Cbv(&'a [u32]), + /// A buffer SRV over these dwords. + Buffer { data: &'a [u32], stride: Stride }, +} + +/// How [`View::Buffer`] is viewed. +#[cfg(test)] +#[derive(Clone, Copy)] +pub enum Stride { + Raw, + /// RGBA32F elements. + Typed, + /// Structured, elements of this many bytes. + Structured(u32), + /// Typed, elements in this format of this many bytes. + Format(DXGI_FORMAT, u32), +} + +/// Bindings for [`Host::dispatch`]: root arguments, the view heap in order, +/// the sampler heap, and the group counts. +#[cfg(test)] +pub struct Dispatch<'a> { + pub roots: Vec<(u32, Root)>, + pub views: &'a [View<'a>], + pub samplers: &'a [D3D12_SAMPLER_DESC], + pub groups: [u32; 3], +} + +#[cfg(test)] +impl Host { + /// Runs a compute pipeline and returns each UAV's contents in heap + /// order (texels as float bits, row by row). + pub fn dispatch( + &self, + root: &ID3D12RootSignature, + pso: &ID3D12PipelineState, + d: &Dispatch, + ) -> Result>, String> { + let dev = &self.device; + // SAFETY: D3D12 calls with descriptions that outlive them; resources + // stay alive until the fence says the GPU is done. + unsafe { + let queue: ID3D12CommandQueue = dev + .CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC { + Type: D3D12_COMMAND_LIST_TYPE_DIRECT, + ..Default::default() + }) + .map_err(err)?; + let alloc: ID3D12CommandAllocator = dev + .CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT) + .map_err(err)?; + let list: ID3D12GraphicsCommandList = dev + .CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &alloc, pso) + .map_err(err)?; + let make = |heap: D3D12_HEAP_TYPE, desc: &D3D12_RESOURCE_DESC, state| { + let mut r: Option = None; + dev.CreateCommittedResource( + &D3D12_HEAP_PROPERTIES { + Type: heap, + ..Default::default() + }, + D3D12_HEAP_FLAG_NONE, + desc, + state, + None, + &mut r, + ) + .map_err(err)?; + r.ok_or_else(|| "no resource".to_string()) + }; + let sample = DXGI_SAMPLE_DESC { + Count: 1, + Quality: 0, + }; + let texture_as = |w: u32, h: u32, flags, format| D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D, + Width: u64::from(w), + Height: h, + DepthOrArraySize: 1, + MipLevels: 1, + Format: format, + SampleDesc: sample, + Flags: flags, + ..Default::default() + }; + let texture = |w, h, flags| texture_as(w, h, flags, DXGI_FORMAT_R32G32B32A32_FLOAT); + let buffer = |size: u64, flags| D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, + Width: size, + Height: 1, + DepthOrArraySize: 1, + MipLevels: 1, + SampleDesc: sample, + Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, + Flags: flags, + ..Default::default() + }; + // Texel words: 4 for RGBA32F, 1 for R32_UINT. + let footprint_as = + |r: &ID3D12Resource, w: u32, h: u32, words: u32| D3D12_TEXTURE_COPY_LOCATION { + pResource: std::mem::transmute_copy(r), + Type: D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT, + Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { + PlacedFootprint: D3D12_PLACED_SUBRESOURCE_FOOTPRINT { + Offset: 0, + Footprint: D3D12_SUBRESOURCE_FOOTPRINT { + Format: if words == 1 { + DXGI_FORMAT_R32_UINT + } else { + DXGI_FORMAT_R32G32B32A32_FLOAT + }, + Width: w, + Height: h, + Depth: 1, + RowPitch: (w * 4 * words).next_multiple_of(256), + }, + }, + }, + }; + let footprint = |r: &ID3D12Resource, w: u32, h: u32| footprint_as(r, w, h, 4); + let subresource = |r: &ID3D12Resource| D3D12_TEXTURE_COPY_LOCATION { + pResource: std::mem::transmute_copy(r), + Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, + Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { + SubresourceIndex: 0, + }, + }; + let heap = |ty, n: usize| -> Result { + dev.CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC { + Type: ty, + NumDescriptors: n.max(1) as u32, + Flags: D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE, + ..Default::default() + }) + .map_err(err) + }; + // An upload buffer holding `data` (sized for a constant buffer). + let upload = |data: &[u32]| -> Result { + let size = (data.len() * 4).next_multiple_of(256); + let b = make( + D3D12_HEAP_TYPE_UPLOAD, + &buffer(size as u64, D3D12_RESOURCE_FLAG_NONE), + D3D12_RESOURCE_STATE_GENERIC_READ, + )?; + let mut p = std::ptr::null_mut(); + b.Map(0, None, Some(&mut p)).map_err(err)?; + std::ptr::copy_nonoverlapping(data.as_ptr(), p.cast::(), data.len()); + b.Unmap(0, None); + Ok(b) + }; + let views = heap(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, d.views.len())?; + let samplers = heap(D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER, d.samplers.len())?; + let view_size = dev + .GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV) + as usize; + let sampler_size = + dev.GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER) as usize; + let mut keep = Vec::new(); + // UAVs: (resource, dwords or texture size, readback buffer). + let mut uavs = Vec::new(); + for (i, v) in d.views.iter().enumerate() { + let mut at = views.GetCPUDescriptorHandleForHeapStart(); + at.ptr += i * view_size; + match *v { + View::Texture(..) | View::Cube(..) => { + let (w, h, texels, faces) = match *v { + View::Texture(w, h, t) => (w, h, t, 1), + View::Cube(n, t) => (n, n, t, 6), + _ => unreachable!(), + }; + let mut desc = texture(w, h, D3D12_RESOURCE_FLAG_NONE); + desc.DepthOrArraySize = faces as u16; + let tex = make( + D3D12_HEAP_TYPE_DEFAULT, + &desc, + D3D12_RESOURCE_STATE_COPY_DEST, + )?; + let pitch = (w as usize * 16).next_multiple_of(256); + for face in 0..faces as usize { + let upload = make( + D3D12_HEAP_TYPE_UPLOAD, + &buffer((pitch * h as usize) as u64, D3D12_RESOURCE_FLAG_NONE), + D3D12_RESOURCE_STATE_GENERIC_READ, + )?; + let mut p = std::ptr::null_mut(); + upload.Map(0, None, Some(&mut p)).map_err(err)?; + let texels = &texels[face * (w * h) as usize..]; + for y in 0..h as usize { + let row = &texels[y * w as usize..(y + 1) * w as usize]; + std::ptr::copy_nonoverlapping( + row.as_ptr().cast::(), + p.cast::().add(y * pitch), + row.len() * 16, + ); + } + upload.Unmap(0, None); + let mut at_face = subresource(&tex); + at_face.Anonymous.SubresourceIndex = face as u32; + list.CopyTextureRegion( + &at_face, + 0, + 0, + 0, + &footprint(&upload, w, h), + None, + ); + keep.push(upload); + } + list.ResourceBarrier(&[transition( + &tex, + D3D12_RESOURCE_STATE_COPY_DEST, + D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE, + )]); + let cube = D3D12_SHADER_RESOURCE_VIEW_DESC { + Format: DXGI_FORMAT_R32G32B32A32_FLOAT, + ViewDimension: D3D12_SRV_DIMENSION_TEXTURECUBE, + Shader4ComponentMapping: D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING, + Anonymous: D3D12_SHADER_RESOURCE_VIEW_DESC_0 { + TextureCube: D3D12_TEXCUBE_SRV { + MipLevels: 1, + ..Default::default() + }, + }, + }; + dev.CreateShaderResourceView( + &tex, + (faces == 6).then_some(&cube as *const _), + at, + ); + keep.push(tex); + } + View::RawUav(_) | View::HalfUav(_) => { + // (dwords, format, elements, flags) + let (n, format, elements, flags) = match *v { + View::HalfUav(e) => ( + 2 * e, + DXGI_FORMAT_R16G16B16A16_FLOAT, + e, + D3D12_BUFFER_UAV_FLAG_NONE, + ), + View::RawUav(n) => { + (n, DXGI_FORMAT_R32_TYPELESS, n, D3D12_BUFFER_UAV_FLAG_RAW) + } + _ => unreachable!(), + }; + let bytes = u64::from(n) * 4; + let b = make( + D3D12_HEAP_TYPE_DEFAULT, + &buffer(bytes, D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS), + D3D12_RESOURCE_STATE_COMMON, + )?; + let desc = D3D12_UNORDERED_ACCESS_VIEW_DESC { + Format: format, + ViewDimension: D3D12_UAV_DIMENSION_BUFFER, + Anonymous: D3D12_UNORDERED_ACCESS_VIEW_DESC_0 { + Buffer: D3D12_BUFFER_UAV { + NumElements: elements, + Flags: flags, + ..Default::default() + }, + }, + }; + dev.CreateUnorderedAccessView(&b, None, Some(&desc), at); + let rb = make( + D3D12_HEAP_TYPE_READBACK, + &buffer(bytes, D3D12_RESOURCE_FLAG_NONE), + D3D12_RESOURCE_STATE_COPY_DEST, + )?; + uavs.push((b, None, n, rb)); + } + View::TextureUav(w, h) => { + let t = make( + D3D12_HEAP_TYPE_DEFAULT, + &texture(w, h, D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS), + D3D12_RESOURCE_STATE_UNORDERED_ACCESS, + )?; + dev.CreateUnorderedAccessView(&t, None, None, at); + let pitch = (w * 16).next_multiple_of(256); + let rb = make( + D3D12_HEAP_TYPE_READBACK, + &buffer(u64::from(pitch * h), D3D12_RESOURCE_FLAG_NONE), + D3D12_RESOURCE_STATE_COPY_DEST, + )?; + uavs.push((t, Some((w, h)), 4, rb)); + } + View::UintTextureUav(w, h) => { + let t = make( + D3D12_HEAP_TYPE_DEFAULT, + &texture_as( + w, + h, + D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS, + DXGI_FORMAT_R32_UINT, + ), + D3D12_RESOURCE_STATE_UNORDERED_ACCESS, + )?; + dev.CreateUnorderedAccessView(&t, None, None, at); + let pitch = (w * 4).next_multiple_of(256); + let rb = make( + D3D12_HEAP_TYPE_READBACK, + &buffer(u64::from(pitch * h), D3D12_RESOURCE_FLAG_NONE), + D3D12_RESOURCE_STATE_COPY_DEST, + )?; + uavs.push((t, Some((w, h)), 1, rb)); + } + View::Cbv(data) => { + let b = upload(data)?; + dev.CreateConstantBufferView( + Some(&D3D12_CONSTANT_BUFFER_VIEW_DESC { + BufferLocation: b.GetGPUVirtualAddress(), + SizeInBytes: (data.len() * 4).next_multiple_of(256) as u32, + }), + at, + ); + keep.push(b); + } + View::Buffer { data, stride } => { + let b = upload(data)?; + let (format, elements, stride, flags) = match stride { + Stride::Raw => ( + DXGI_FORMAT_R32_TYPELESS, + data.len(), + 0, + D3D12_BUFFER_SRV_FLAG_RAW, + ), + Stride::Typed => ( + DXGI_FORMAT_R32G32B32A32_FLOAT, + data.len() / 4, + 0, + D3D12_BUFFER_SRV_FLAG_NONE, + ), + Stride::Structured(s) => ( + DXGI_FORMAT_UNKNOWN, + data.len() * 4 / s as usize, + s, + D3D12_BUFFER_SRV_FLAG_NONE, + ), + Stride::Format(f, bytes) => ( + f, + data.len() * 4 / bytes as usize, + 0, + D3D12_BUFFER_SRV_FLAG_NONE, + ), + }; + let desc = D3D12_SHADER_RESOURCE_VIEW_DESC { + Format: format, + ViewDimension: D3D12_SRV_DIMENSION_BUFFER, + Shader4ComponentMapping: D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING, + Anonymous: D3D12_SHADER_RESOURCE_VIEW_DESC_0 { + Buffer: D3D12_BUFFER_SRV { + FirstElement: 0, + NumElements: elements as u32, + StructureByteStride: stride, + Flags: flags, + }, + }, + }; + dev.CreateShaderResourceView(&b, Some(&desc), at); + keep.push(b); + } + } + } + for (i, s) in d.samplers.iter().enumerate() { + let mut at = samplers.GetCPUDescriptorHandleForHeapStart(); + at.ptr += i * sampler_size; + dev.CreateSampler(s, at); + } + list.SetDescriptorHeaps(&[Some(views.clone()), Some(samplers.clone())]); + list.SetComputeRootSignature(root); + for (param, arg) in &d.roots { + match arg { + Root::Constants(data) => list.SetComputeRoot32BitConstants( + *param, + data.len() as u32, + data.as_ptr().cast(), + 0, + ), + Root::Table { sampler, index } => { + let (h, size) = if *sampler { + (&samplers, sampler_size) + } else { + (&views, view_size) + }; + let mut at = h.GetGPUDescriptorHandleForHeapStart(); + at.ptr += (index * size) as u64; + list.SetComputeRootDescriptorTable(*param, at); + } + Root::View { srv, data } => { + let b = upload(data)?; + let va = b.GetGPUVirtualAddress(); + if *srv { + list.SetComputeRootShaderResourceView(*param, va); + } else { + list.SetComputeRootConstantBufferView(*param, va); + } + keep.push(b); + } + } + } + let [x, y, z] = d.groups; + list.Dispatch(x, y, z); + for (r, size, n, rb) in &uavs { + // (Buffers were promoted from the common state by the dispatch.) + list.ResourceBarrier(&[transition( + r, + D3D12_RESOURCE_STATE_UNORDERED_ACCESS, + D3D12_RESOURCE_STATE_COPY_SOURCE, + )]); + match size { + Some((w, h)) => list.CopyTextureRegion( + &footprint_as(rb, *w, *h, *n), + 0, + 0, + 0, + &subresource(r), + None, + ), + None => list.CopyBufferRegion(rb, 0, r, 0, u64::from(*n) * 4), + } + } + list.Close().map_err(err)?; + queue.ExecuteCommandLists(&[Some(list.cast().map_err(err)?)]); + let fence: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).map_err(err)?; + queue.Signal(&fence, 1).map_err(err)?; + while fence.GetCompletedValue() < 1 { + if let Err(e) = dev.GetDeviceRemovedReason() { + return Err(format!("device removed: {}", err(e))); + } + std::thread::yield_now(); + } + let mut out = Vec::new(); + for (_, size, n, rb) in &uavs { + let mut p = std::ptr::null_mut(); + rb.Map(0, None, Some(&mut p)).map_err(err)?; + let words = match size { + Some((w, h)) => { + let words = *n as usize; + let pitch = (*w as usize * 4 * words).next_multiple_of(256); + (0..*h as usize) + .flat_map(|y| { + std::slice::from_raw_parts( + p.cast::().add(y * pitch).cast::(), + *w as usize * words, + ) + .to_vec() + }) + .collect() + } + None => std::slice::from_raw_parts(p.cast::(), *n as usize).to_vec(), + }; + rb.Unmap(0, None); + out.push(words); + } + drop(keep); + Ok(out) + } + } +} diff --git a/crates/leonida-shader/src/emit/intersect.rs b/crates/leonida-shader/src/emit/intersect.rs new file mode 100644 index 000000000..78a1d99ed --- /dev/null +++ b/crates/leonida-shader/src/emit/intersect.rs @@ -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> = + 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 = 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) { + #[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, offset: u32, count: u32) -> Vec { + 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) { + 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 = 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 = (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) + }) + } +} diff --git a/crates/leonida-shader/src/emit/intersect_tests.rs b/crates/leonida-shader/src/emit/intersect_tests.rs new file mode 100644 index 000000000..0266579ac --- /dev/null +++ b/crates/leonida-shader/src/emit/intersect_tests.rs @@ -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 { + 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, + starts: Vec, +} + +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>) { + 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 = 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 { + 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::>(), + 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(|_| ())), + } +} diff --git a/crates/leonida-shader/src/emit/lower.rs b/crates/leonida-shader/src/emit/lower.rs new file mode 100644 index 000000000..37d386a53 --- /dev/null +++ b/crates/leonida-shader/src/emit/lower.rs @@ -0,0 +1,11896 @@ +//! IR to DXIL, one machine instruction at a time (decision 0003). +//! +//! Every register dword is an `i32` (SCC an `i1`); float operations bitcast +//! their operands. Lane masks exist only as the per-lane booleans of +//! structurisation; branches and guards are built from them. A value the +//! emitter cannot express is `Missing` with a reason, and only fails the +//! program when something with an effect (an export, a branch) needs it. + +use std::collections::{BTreeMap, HashMap, HashSet}; + +use super::UserData; +use super::bitcode::{Attr, Bin, Cast, Rmw, Tag, Term, V, pred}; +use super::container::SigElement; +use super::shader::{Shader, flags}; +use crate::ShaderError; +use crate::gfx10::{Dpp, Fields, NULL, Operand}; +use crate::io::{Barycentric, Export, Input, Interp, Io, Target}; +use crate::ir::{EXEC, Exit, Inst, Program, Reg, Value}; +use crate::native::{HwStage, NativeProgram, ResourceType, RootType, StageIo, Usage, UsedResource}; +use crate::resource::{Address, CODE, MEMORY, Resources, Role, Site, Source}; +use crate::structure::{Atom, Bool, LaneExit, Structured}; + +/// The ray-tracing node test (`image_bvh_intersect_ray`), a child module so +/// it shares the emitter's state. +#[path = "intersect.rs"] +pub(super) mod intersect; + +type Why = &'static str; + +/// How an interpolation evaluates an input channel. +#[derive(Debug, Clone, Copy)] +enum Eval { + /// Loaded with this DXIL interpolation mode (1: constant, P0). + Mode(u8), + /// From the vertex values of a constant element: P0 when `p0`, plus + /// i (P1 - P0), plus j (P2 - P0), weights as floats. + Weights { + p0: bool, + i: Option, + j: Option, + }, +} + +#[derive(Debug, Clone, Copy)] +enum Val { + I32(V), + Bit(V), + Missing(Why), +} + +pub(crate) struct Lowered { + pub dxil: Vec, + /// Bit n: immediate sampler n is used for comparisons. + pub cmp_samplers: u64, + pub root_cbvs: Vec, + pub root_srvs: Vec, + pub root_uavs: Vec, + pub user_data: Vec, + pub samplers: Vec<[u32; 4]>, + /// The wave size the shader requires of the host, if any. + pub wave_size: Option, + /// Heap handles made with a non-uniform index. + #[cfg(test)] + pub nonuniform_handles: u32, + /// Whether the program uses wave operations. + #[cfg(test)] + pub wave_ops: bool, +} + +pub(crate) struct Parts<'a> { + pub native: &'a NativeProgram, + pub p: &'a Program, + pub st: &'a Structured, + pub io: &'a Io, + pub res: &'a Resources, + pub inputs: Vec, + pub outputs: Vec, + pub prims: Vec, + /// Mesh: what the group id arrives multiplied by. + pub mesh_stride: u32, +} + +enum Stop { + /// A phi whose incoming value has no DXIL form was read: redo with it missing. + Retry(Value, Why), + Fail(ShaderError), +} + +pub(crate) fn lower(parts: &Parts) -> Result { + let mut bad = HashMap::new(); + loop { + match Lower::new(parts, &bad).run() { + Ok(l) => return Ok(l), + Err(Stop::Retry(v, why)) => { + if bad.insert(v, why).is_some() { + return Err(ShaderError::Unsupported { + offset: 0, + what: "a phi that does not settle", + }); + } + } + Err(Stop::Fail(e)) => return Err(e), + } + } +} + +const TWO_PI: f32 = std::f32::consts::TAU; +/// `s_sendmsg` id of a mesh or NGG stage's output allocation request. +const GS_ALLOC_REQ: u16 = 9; + +/// The f16 bits of inline float constant `c` (240..=248: 0.5, -0.5, 1.0, +/// -1.0, 2.0, -2.0, 4.0, -4.0, 1/(2 pi)). +fn inline_f16(c: u8) -> u32 { + [ + 0x3800, 0xB800, 0x3C00, 0xBC00, 0x4000, 0xC000, 0x4400, 0xC400, 0x3118, + ][usize::from(c - 240)] +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum Numeric { + Unorm, + Snorm, + Uscaled, + Sscaled, + Uint, + Sint, + Float, +} + +/// A GFX10 buffer format (the unified format of typed buffer loads): the +/// channel widths from the lowest bits up, and how the channels convert. +/// Formats are numbered in families (`8`, `16`, `8_8`, ...: AMD names +/// list channels from the highest bits), each with its numeric formats in +/// the order unorm, snorm, uscaled, sscaled, uint, sint, float. +fn buffer_format(format: u8) -> Option<(&'static [u32], Numeric)> { + use Numeric::*; + const NORM: &[Numeric] = &[Unorm, Snorm, Uscaled, Sscaled, Uint, Sint]; + const ALL: &[Numeric] = &[Unorm, Snorm, Uscaled, Sscaled, Uint, Sint, Float]; + const WIDE: &[Numeric] = &[Uint, Sint, Float]; + // Numbers and order from LLVM's `UfmtGFX10` (`SIDefines.h`); the GFX10 + // buffer formats have no 5_9_9_9. Channel order from Mesa + // (`ac_formats.c`): R11G11B10_FLOAT is 10_11_11, and 10_10_10_2 has + // its 2-bit channel in the lowest bits. + const FAMILIES: [(&[u32], &[Numeric]); 14] = [ + (&[8], NORM), + (&[16], ALL), + (&[8, 8], NORM), + (&[32], WIDE), + (&[16, 16], ALL), + (&[11, 11, 10], ALL), // 10_11_11 + (&[10, 11, 11], ALL), // 11_11_10 + (&[2, 10, 10, 10], NORM), // 10_10_10_2 + (&[10, 10, 10, 2], NORM), // 2_10_10_10 + (&[8, 8, 8, 8], NORM), + (&[32, 32], WIDE), + (&[16, 16, 16, 16], ALL), + (&[32, 32, 32], WIDE), + (&[32, 32, 32, 32], WIDE), + ]; + let mut n = usize::from(format.checked_sub(1)?); + for (bits, numerics) in FAMILIES { + if n < numerics.len() { + return Some((bits, numerics[n])); + } + n -= numerics.len(); + } + None +} + +/// How far a float channel of `width` bits (16, or the unsigned 11- and +/// 10-bit floats of the packed formats) shifts up to be a half: +/// the small floats are a half's exponent (5 bits, biased 15) and the top +/// of its mantissa, without the sign, so `legacyF16ToF32` widens them +/// exactly, denormals, infinities and NaNs included. +fn half_shift(width: u32) -> u32 { + debug_assert!(matches!(width, 10 | 11 | 16), "{width}-bit float"); + if width == 16 { 0 } else { 15 - width } +} + +struct Lower<'a> { + s: Shader, + x: &'a Parts<'a>, + bad: &'a HashMap, + lane_fail: HashMap, + vals: HashMap, + floats: HashMap, + /// DXIL block per IR block (unreachable: none). + block: Vec>, + cur: usize, + bools: HashMap<(usize, Bool), V>, + lane_bits: HashMap, + /// IR phi location by value. + phi_at: HashMap, + /// Descriptor dwords with no host value (addresses, formats, all of a constant + /// buffer's): no program reads them as numbers ([`Self::dead`]). + stale: HashSet, + mask_phis: HashMap, + pending_masks: Vec<(V, usize, usize)>, + data_phis: Vec<(V, usize, usize)>, + read_phis: HashSet, + params: HashMap, + user_data: Option, + user_reads: BTreeMap, + samplers: Vec<[u32; 4]>, + descriptors: HashMap<(Site, bool), &'a Source>, + scalar: HashMap, + exports: HashMap, + interps: HashMap, + handles: HashMap<(usize, Site, u8, bool, (u32, u32)), V>, + /// Element strides read from the host's table by heap slot + /// ([`super::shader::SLOT_STRIDES`]), by block and descriptor load. + strides: HashMap<(usize, Site, u8), V>, + /// Blocks splitting the edge from one IR block to another. + edges: HashMap<(usize, usize), usize>, + /// Per IR block: a `done` export is behind every lane entering it. + exported: Vec, + /// Reverse-postorder index per IR block. + rpo: Vec, + /// DXIL block each IR block ends in (guarded stores split blocks). + tail: Vec>, + /// The program writes UAVs: barriers fence them too. + writes_uavs: bool, + /// src0 of the current instruction as DPP fetched it. + src0: Option, + /// Compute code that reads other lanes: thread ids follow the host + /// lanes, so lane n is console lane n. + console_lanes: bool, + /// Mesh: the thread index in the group (made in the entry block). + flat: Option, + /// Mesh: IR blocks whose `s_barrier` is left out. + no_barrier: HashSet, + /// IR blocks whose `s_barrier` not every lane is sure to reach (a lane + /// branch lies between the entry and the block, or the program has a + /// loop a lane can be cut out of): the barrier there keeps its fences + /// and does not wait for the group ([`super::group_sync`]). + fence_only: HashSet, + /// A group barrier before every LDS access (a console wave run as two host waves). + split_lds: bool, + /// With `split_lds`, LDS accesses in lane branches: per IR block whether every lane runs + /// it, and whether the host waves meet at its start and before its exit ([`lds_meetings`]). + lds_meet: Option<(Vec, Vec<(bool, bool)>)>, + /// A console wave64 program run as two host waves of 32 that exchange through LDS: the first + /// of two exchange dwords, whether the group has no upper half (32 threads or fewer), and per + /// IR block whether every lane runs it (exchanges need both halves there). + exchange: Option<(u32, bool, Vec)>, + /// With `exchange`: nothing is exchanged, each host wave acts as a wave + /// of its own ([`with_local_waves`]). + local: bool, + /// The instruction being lowered may read a lane mask as a number under + /// `local` (a bit count, a first set bit, `v_mbcnt`). + local_ok: bool, + /// With `local`: every mask read and lane read is taken per host wave + /// ([`with_local_waves_any`]). + local_any: bool, + /// With `exchange`: VGPR values every lane holds alike ([`lane_uniform`]); a first-lane + /// read of one needs nothing from the other host wave. + uniform: HashSet, + /// With `exchange`: the wave ORs that only steer a loop over each lane's own bits, which + /// a host wave takes over its own lanes wherever they stand ([`super::own_bits`]). + own_bits: super::own_bits::OwnBits, + /// The console lane (0..63) of this thread, made in the entry block. + clane: Option, + /// The first exchange dword of this thread's console wave ([`Self::exchange_pair`]). + pair: Option, + /// A console wave64 program in host waves of 32: the LDS dword counting the console threads + /// handed to host waves (`wave_base`), and the base made in the entry block. + halves: Option, + wave_base: Option, + /// Vertex and mesh outputs holding 16-bit values: row, whether two per + /// dword, and the row packed after it. + half_outputs: HashMap)>, + /// How lane masks become data. + mask_data: MaskData, + /// The instruction being lowered may read lane masks as data. + mask_ok: bool, + /// Ballots of masks read as data, by low dword: (low, high). + ballots: HashMap, + /// Masks whose ballot is being built: a mask whose lane bit needs its + /// own value as a number (an opaque mask keyed by a dword it shares + /// with another) would otherwise recurse until the stack overflows. + balloting: HashSet, + /// Block writing each value. + def_block: HashMap, + /// IR block being lowered. + cur_ir: usize, + /// Whole-wave sections by block and start index. + sections: HashMap>, + /// Values written in a section that code outside it reads. + section_out: HashSet, + /// The program's constant table (the code from the first byte read + /// through `s_getpc_b64` on): global, first byte, dwords. + code_table: Option<(V, u32, u32)>, + /// Loop headers' iteration counters (see [`LOOP_LIMIT`]): the phi by + /// IR block, and its incoming (value, DXIL block) pairs. + counters: HashMap)>, + /// The block a loop stopped by [`LOOP_LIMIT`] leaves the program from. + abort: Option, +} + +/// Iterations after which a loop is left (per entry into it), unless +/// [`super::loop_limit`] says otherwise. The console runs a loop as long as +/// its data says; data the host has not mirrored yet (a null view reads +/// zeros) can make that four billion iterations, which hangs the host GPU +/// until the driver resets it. A lane that reaches the limit leaves the +/// program as killed (a pixel discards). +// shortcut: a genuine loop of more iterations than this is cut short too. +pub(super) const LOOP_LIMIT: u32 = 1 << 20; + +/// Lane masks read as numbers (`s_bcnt1`, `s_ff1`, `v_mbcnt`, scalar +/// compares, bit tests) are ballots of the lanes' booleans, taken where the +/// mask is written: structurisation's `active` masks hold only lanes that +/// reach that block, so the ballot misses none. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum MaskData { + /// Compute: host lane n is console lane n (the program declares the + /// console's wave size), so ballots are the console's masks bit for bit + /// and any use is exact. + Console, + /// Pixel and vertex programs: ballots over the host's wave, whatever its + /// size. Only uses that mean the same on any wave are allowed: counts, + /// the first lane, the count below a lane, equality (the HLSL wave + /// operations the console compiler expands). Lane numbers stay host + /// lanes throughout (`v_mbcnt`, `v_readlane` at a computed lane). + Host, + /// Mesh programs: their lanes and waves (LDS per console wave) are the + /// console's but no host wave size can be declared. + None, +} + +/// What a value holding a lane mask read as a number stops with. +pub(super) const LANE_MASK: Why = "a lane mask read as data"; +/// A mask with lanes outside EXEC where it is written, read as a number where the lanes that +/// run that block are not all of the wave. +pub(super) const MASK_ELSEWHERE: Why = "a lane mask holding lanes elsewhere read as data"; + +/// Instructions that read a lane mask (not EXEC implicitly, not a lane's +/// bit) as a number. +/// Per IR block: every lane of the wave that started the program runs it – no per-lane branch +/// separates it from the entry (it lies in no lane branch's region: the blocks reachable from +/// the branch that do not post-dominate it). None with an indirect exit (not followed). +fn all_lane_blocks(st: &Structured) -> Option> { + let n = st.exits.len(); + let mut all = vec![true; n]; + for (_, region) in lane_regions(st)? { + for b in (0..n).filter(|&b| region[b]) { + all[b] = false; + } + } + Some(all) +} + +/// Every per-lane branch (by its block) with its region: the blocks reachable from it that do +/// not post-dominate it, which only some lanes run. Not the branches the wave takes together +/// ([`Structured::wide`]), nor those on scalar conditions. None with an indirect exit. +fn lane_regions(st: &Structured) -> Option)>> { + let n = st.exits.len(); + let mut succ: Vec> = vec![Vec::new(); n]; + for (b, e) in st.exits.iter().enumerate() { + match *e { + LaneExit::Jump(t) => succ[b].push(t), + LaneExit::Branch { taken, not_taken, .. } => { + succ[b].push(taken); + succ[b].push(not_taken); + } + LaneExit::End => {} + LaneExit::Indirect => return None, + } + } + // post-dominators (bitsets; a virtual exit after every End) + let words = n.div_ceil(64); + let full = vec![u64::MAX; words]; + let mut pdom: Vec> = (0..n).map(|b| if succ[b].is_empty() { let mut v = vec![0; words]; v[b / 64] |= 1 << (b % 64); v } else { full.clone() }).collect(); + let mut changed = true; + while changed { + changed = false; + for b in (0..n).rev() { + if succ[b].is_empty() { + continue; + } + let mut v = full.clone(); + for &t in &succ[b] { + for w in 0..words { + v[w] &= pdom[t][w]; + } + } + v[b / 64] |= 1 << (b % 64); + if v != pdom[b] { + pdom[b] = v; + changed = true; + } + } + } + let mut regions = Vec::new(); + for (d, e) in st.exits.iter().enumerate() { + let LaneExit::Branch { when, .. } = *e else { continue }; + if st.wide.contains(&d) || st.bools.support(when).iter().all(|a| matches!(a, Atom::Uniform(_))) { + continue; // a wave-wide or uniform branch: all lanes go the same way + } + // blocks reachable from the lane branch that do not post-dominate it + let mut seen = vec![false; n]; + let mut stack: Vec = succ[d].clone(); + while let Some(b) = stack.pop() { + if seen[b] || pdom[d][b / 64] >> (b % 64) & 1 == 1 { + continue; + } + seen[b] = true; + stack.extend(succ[b].iter().copied()); + } + regions.push((d, seen)); + } + Some(regions) +} + +/// The per-lane branches (by block) whose regions hold a block of `needs` (blocks where two +/// host waves must meet, [`take_needs`]): the ones to take wave-wide +/// ([`crate::structure::structure_wide`]) so that every lane runs those blocks. None if one +/// of them is a branch whose wave-wide meaning is not known ([`Structured::wave_any`]). +pub(super) fn branches_around(st: &Structured, needs: &[usize]) -> Option> { + let mut out = Vec::new(); + for (d, region) in lane_regions(st)? { + if needs.iter().any(|&b| region.get(b).copied().unwrap_or(false)) { + st.wave_any.get(d).copied().flatten()?; + out.push(d); + } + } + Some(out) +} + +/// Whether a refusal is of code that needs every lane of the wave where it stands (two host +/// waves meeting there), which the other forms of the program may give it. +pub(super) fn needs_every_lane(what: &str) -> bool { + what.ends_with("where not every lane runs") || what == MASK_ELSEWHERE +} + +/// The blocks where the last lowering on this thread wanted every lane and did not have it +/// (its "... where not every lane runs" refusals), which it forgets. +pub(super) fn take_needs() -> Vec { + NEEDS.take() +} + +fn need(block: usize) { + NEEDS.with_borrow_mut(|n| { + if !n.contains(&block) { + n.push(block); + } + }); +} + +/// VGPR values that are the same in every lane holding them (`all` is [`all_lane_blocks`]): +/// written by an instruction every arriving lane runs (no guard), lane by lane, from scalars, +/// constants and such values; or loaded from an address made of them. The compiler keeps +/// wave-uniform data in VGPRs and fetches it with `v_readfirstlane`. +/// shortcut: a value joined by a phi counts only where every predecessor is a block all lanes +/// run (no lane branch can have split the arriving lanes); loop-carried values never do. +fn lane_uniform(p: &Program, st: &Structured, all: &[bool]) -> HashSet { + let is_mask = |v: Value| st.masks.contains_key(&v) || st.highs.contains_key(&v); + let mut same: HashSet = HashSet::new(); + for b in crate::ir::reverse_postorder(&p.blocks) { + let block = &p.blocks[b]; + let whole = block.preds.iter().all(|&q| all.get(q).copied().unwrap_or(false)); + for phi in &block.phis { + if matches!(phi.reg, Reg::V(_)) && whole && phi.args.iter().all(|a| same.contains(a)) { + same.insert(phi.value); + } + } + for (i, inst) in block.insts.iter().enumerate() { + let name = inst.name(); + let ops: Vec = match &inst.fields { + Fields::Valu(v) + if v.dpp.is_none() + && v.sdwa.is_none() + && !name.starts_with("v_mbcnt") + && !name.starts_with("v_cmpx") + && !name.contains("lane") => + { + v.src.clone() + } + _ => continue, + }; + if st.guards[b][i].is_some() { + continue; // lanes outside EXEC keep another value + } + let alike = ops.iter().all(|op| match *op { + Operand::Vector { reg, .. } => { + // every dword of the operand the instruction reads from that register on + let read: Vec = + inst.reads.iter().filter(|r| matches!(r.0, Reg::V(x) if x >= reg)).map(|r| r.1).collect(); + !read.is_empty() && read.iter().all(|x| same.contains(x)) + } + // a scalar is one value; a lane mask is not, unless a compare of such values made it + Operand::Scalar { code, .. } if code != NULL => { + inst.read(Reg::S(code)).is_none_or(|x| !is_mask(x) || same.contains(&x)) + } + _ => true, + }); + if alike { + same.extend(inst.writes.iter().filter(|w| w.0 != Reg::Scc).map(|w| w.1)); + } + } + } + same +} + +/// What a register value holds, for [`wave_local`]. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum Wave { + /// Nothing that depends on how the threads are divided into waves. + Plain, + /// The number of the wave's first lane in a mask (`s_ff1`). + First, + /// A reduction over the wave's lanes: a count, a sum, a minimum... + Total(super::wave::Op), + /// A count or sum over the lanes below this one. + Prefix, + /// Derived from what a first-lane atomic returned: the slots the wave reserved. + Base, + /// A mix the idiom does not make. + Mixed, +} + +/// Whether a console wave64 program may run with each host wave as a wave of its own +/// ([`with_local_waves`]): its wave-wide values are used only as the allocation idiom uses +/// them, which does not care how the threads are divided into waves. A first-lane number only +/// picks the first lane; a count or sum only goes into that lane's atomic on a shared counter; +/// a prefix only goes onto the base that atomic returned; the first lane does nothing else. +/// Anything else done with them takes one wave to be the whole thread group (a tile's result, +/// say) and is refused, with the offset and what was found. +/// Lane masks read as numbers by other instructions and lane reads outside whole-wave sections +/// are stopped by the lowering itself. +// shortcut: `v_readfirstlane` of a value that differs between lanes is taken as it is (this +// host wave's first lane), and a guarded write of a plain value over a wave-dependent one is +// the only mix of old and new lanes that is looked at. +pub(super) fn wave_local(p: &Program, st: &Structured) -> Result<(), (usize, &'static str)> { + use super::wave::{Op, Shape}; + const FIRST: Why = "a wave's first-lane number used as data"; + const TOTAL: Why = "a count or sum over the wave used as data"; + const PREFIX: Why = "a count or sum over the lanes below used without a reserved base"; + const MIXED: Why = "a value that depends on the wave on some paths only"; + const EFFECT: Why = "a write by the wave's first lane other than its reservation"; + fn of(kind: &HashMap, v: Option) -> Wave { + v.and_then(|v| kind.get(&v).copied()).unwrap_or(Wave::Plain) + } + fn put(kind: &mut HashMap, v: Value, k: Wave) { + if k == Wave::Plain { + kind.remove(&v); + } else { + kind.insert(v, k); + } + } + let wild = |k: Wave| !matches!(k, Wave::Plain | Wave::Base); + let why = |k: Wave| match k { + Wave::First => FIRST, + Wave::Total(_) => TOTAL, + Wave::Prefix => PREFIX, + _ => MIXED, + }; + // a mask (by its low dword) under which only a wave's first lane runs + let first_mask = |firsts: &HashSet, m: Option| { + m.and_then(|m| st.masks.get(&m)).is_some_and(|&b| { + st.bools + .support(b) + .iter() + .any(|a| matches!(a, Atom::Lane(v) if firsts.contains(v))) + }) + }; + // One instruction outside a section: the kind of what it writes, and whether it is a + // first lane's reservation. + let step = |inst: &Inst, kind: &HashMap, firsts: &mut HashSet| -> Result<(Wave, bool), Why> { + let name = inst.name(); + let val = |op: &Operand| match *op { + Operand::Vector { reg, .. } => inst.read(Reg::V(reg)), + Operand::Scalar { code, .. } if code != NULL => inst.read(Reg::S(code)), + _ => None, + }; + let ops: Vec = match &inst.fields { + Fields::Valu(v) => v.src.clone(), + Fields::Sop { dst, src, .. } => { + let mut o = src.clone(); + if matches!(name, "s_addk_i32" | "s_mulk_i32") { + o.extend(dst.iter().copied()); + } + o + } + Fields::Buffer { data, .. } if name.contains("_atomic_") || name.contains("_store_") => { + data.iter().copied().collect() + } + _ => Vec::new(), + }; + let kinds: Vec = ops.iter().map(|o| of(kind, val(o))).collect(); + // Everything else it reads (addresses, descriptors, SCC, the high dwords of wide + // operands) must not depend on the wave. Not EXEC, and not the old value of a VGPR it + // writes, which only the lanes outside EXEC keep. + let named: Vec = ops.iter().filter_map(&val).collect(); + for &(r, v) in &inst.reads { + let kept = matches!(r, Reg::V(_)) && inst.writes.iter().any(|w| w.0 == r); + if matches!(r, Reg::S(c) if c == EXEC || c == EXEC + 1) || kept || named.contains(&v) { + continue; + } + let k = of(kind, Some(v)); + if wild(k) { + return Err(why(k)); + } + } + let w = kinds.iter().copied().find(|&k| wild(k)).unwrap_or(Wave::Mixed); + let sum = |k: Wave| k == Wave::Total(Op::AddU); + let is_mask = |o: &Operand| { + val(o).is_some_and(|v| st.masks.contains_key(&v) || st.highs.contains_key(&v)) + }; + let mut reserved = false; + let out = match (name, &kinds[..]) { + ("s_ff1_i32_b64" | "s_ff1_i32_b32", _) if ops.first().is_some_and(is_mask) => Wave::First, + ("s_bcnt1_i32_b64" | "s_bcnt1_i32_b32", _) if ops.first().is_some_and(is_mask) => { + Wave::Total(Op::AddU) + } + // bits of a mask below the lane; with -1 for the mask, the lane's number + ("v_mbcnt_lo_u32_b32" | "v_mbcnt_hi_u32_b32", [_, b]) => { + match (matches!(ops[0], Operand::Scalar { .. }), *b) { + (_, Wave::Prefix) | (true, Wave::Plain | Wave::Base) => Wave::Prefix, + (false, Wave::Plain | Wave::Base) => Wave::Plain, + (_, k) => return Err(why(k)), + } + } + // nothing wave-dependent goes in; what derives from a reserved base stays marked + _ if !kinds.iter().any(|&k| wild(k)) => { + let derives = matches!(inst.fields, Fields::Valu(_) | Fields::Sop { .. }); + if derives && kinds.contains(&Wave::Base) { Wave::Base } else { Wave::Plain } + } + ("v_mov_b32" | "s_mov_b32", [k]) => *k, + ("v_cmp_eq_i32" | "v_cmp_eq_u32" | "v_cmpx_eq_i32" | "v_cmpx_eq_u32", [a, b]) => { + // the lane whose own number is the first lane's + let lane = match (*a, *b) { + (Wave::First, k) if !wild(k) => &ops[1], + (k, Wave::First) if !wild(k) => &ops[0], + _ => return Err(why(w)), + }; + if !matches!(lane, Operand::Vector { .. }) { + return Err(FIRST); + } + let mask = match &inst.fields { + _ if name.starts_with("v_cmpx") => inst.write(Reg::S(EXEC)), + Fields::Valu(v) => match v.dst { + Some(Operand::Scalar { code, .. }) => inst.write(Reg::S(code)), + _ => None, + }, + _ => None, + }; + firsts.extend(mask); + Wave::Plain + } + ("v_add_nc_u32" | "s_add_i32", [a, b]) => match (*a, *b) { + (Wave::Prefix, Wave::Base) | (Wave::Base, Wave::Prefix) => Wave::Base, + (Wave::Prefix, Wave::Plain | Wave::Prefix) | (Wave::Plain, Wave::Prefix) => Wave::Prefix, + (x, y) if sum(x) && sum(y) => x, + _ => return Err(why(w)), + }, + ("v_sub_nc_u32" | "s_sub_i32", [a, b]) => match (*a, *b) { + (Wave::Base, Wave::Prefix) => Wave::Base, + (Wave::Prefix, Wave::Plain) => Wave::Prefix, + (Wave::Plain, y) if sum(y) && matches!(ops[0], Operand::Const(128)) => y, + _ => return Err(why(w)), + }, + ("s_mul_i32" | "v_mul_lo_u32" | "v_mul_u32_u24", [a, b]) => match (*a, *b) { + (x, Wave::Plain) | (Wave::Plain, x) if sum(x) || x == Wave::Prefix => x, + _ => return Err(why(w)), + }, + ("s_lshl_b32", [x, Wave::Plain]) | ("v_lshlrev_b32", [Wave::Plain, x]) + if sum(*x) || *x == Wave::Prefix => + { + *x + } + ("v_lshl_add_u32", [Wave::Prefix, Wave::Plain, c]) if !wild(*c) => { + if *c == Wave::Base { Wave::Base } else { Wave::Prefix } + } + // the reservation: the first lane adds its wave's total to a shared counter + (_, [Wave::Total(op)]) if name.contains("_atomic_") => { + let want = match op { + Op::AddU => "buffer_atomic_add", + Op::MinU => "buffer_atomic_umin", + Op::MaxU => "buffer_atomic_umax", + Op::MinI => "buffer_atomic_smin", + Op::MaxI => "buffer_atomic_smax", + Op::Or => "buffer_atomic_or", + Op::And => "buffer_atomic_and", + Op::Xor => "buffer_atomic_xor", + _ => "", + }; + if name != want || !first_mask(firsts, inst.read(Reg::S(EXEC))) { + return Err(TOTAL); + } + reserved = true; + Wave::Base + } + _ => return Err(why(w)), + }; + Ok((out, reserved)) + }; + let sections: Vec<_> = (0..p.blocks.len()).map(|b| super::wave::sections(p, b)).collect(); + let order = crate::ir::reverse_postorder(&p.blocks); + let pass = |kind: &mut HashMap, firsts: &mut HashSet, check: bool| -> Result<(), (usize, Why)> { + for &b in &order { + let block = &p.blocks[b]; + for phi in &block.phis { + let mut k = Wave::Plain; + for (n, &a) in phi.args.iter().enumerate() { + let x = of(kind, Some(a)); + k = match (k, x) { + _ if n == 0 => x, + (k, x) if k == x => k, + (Wave::Plain, m @ (Wave::Base | Wave::Prefix)) + | (m @ (Wave::Base | Wave::Prefix), Wave::Plain) => m, + _ => Wave::Mixed, + }; + } + put(kind, phi.value, k); + } + for (i, inst) in block.insts.iter().enumerate() { + // inside a whole-wave section: what the simulation found each value to be + if let Some((_, sec)) = sections[b].iter().find(|(s, sec)| i > **s && i < sec.end) { + for &(_, w) in &inst.writes { + let k = match sec.shapes.get(&w) { + None => Wave::Mixed, + Some(&Shape::K(_)) => Wave::Plain, + Some(&Shape::Value(v)) => of(kind, Some(v)), + Some(&Shape::Masked(src, _, _)) => of(kind, Some(src)), + Some(&Shape::Active(op, src, mask, _)) => match of(kind, Some(src)) { + Wave::Plain | Wave::Base => Wave::Total(op), + // the first lane's own sum of a total is that total + Wave::Total(o) if o == op && first_mask(firsts, Some(mask)) => Wave::Total(op), + _ => Wave::Mixed, + }, + Some(&Shape::Prefix(Op::AddU, src, mask, _, _)) => match of(kind, Some(src)) { + Wave::Plain | Wave::Base => Wave::Prefix, + Wave::Total(Op::AddU) if first_mask(firsts, Some(mask)) => Wave::Prefix, + _ => Wave::Mixed, + }, + Some(_) => Wave::Mixed, + }; + put(kind, w, k); + } + continue; + } + let name = inst.name(); + if name.starts_with("s_cbranch") { + continue; // with the block's exit, below + } + let (k, reserved) = match step(inst, kind, firsts) { + Ok(r) => r, + Err(why) if check => return Err((inst.machine.offset, why)), + Err(_) => (Wave::Mixed, false), + }; + // the same test as `Lower::inst`'s `effect` + let effect = 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")); + if check && effect && !reserved && first_mask(firsts, inst.read(Reg::S(EXEC))) { + return Err((inst.machine.offset, EFFECT)); + } + let guarded = st.guards[b][i].is_some(); + for &(r, w) in &inst.writes { + let mut kw = match r { + // "some lane is counted" keeps the count's kind; any other SCC is one bit of data + Reg::Scc if !name.starts_with("s_bcnt1") => { + if wild(k) { Wave::Mixed } else { Wave::Plain } + } + _ => k, + }; + // a guarded write leaves the old value in the lanes outside EXEC + if guarded + && matches!(r, Reg::V(_)) + && kw == Wave::Plain + && matches!(of(kind, inst.read(r)), Wave::First | Wave::Total(_) | Wave::Prefix) + { + kw = Wave::Mixed; + } + put(kind, w, kw); + } + } + // a branch on "some lane is counted": fine where the structure made it the lane's + // own bit (the mask is EXEC under a scalar condition) + if check + && let Some(last) = block.insts.last() + && last.name().starts_with("s_cbranch_scc") + && let Some(scc) = last.read(Reg::Scc) + && wild(of(kind, Some(scc))) + { + let own = matches!(st.exits[b], LaneExit::Branch { when, .. } + if !st.bools.support(when).iter().any(|a| matches!(a, Atom::Uniform(v) if *v == scc))); + if !own { + return Err((last.machine.offset, TOTAL)); + } + } + } + Ok(()) + }; + let mut kind: HashMap = HashMap::new(); + let mut firsts: HashSet = HashSet::new(); + // to a fixpoint (values carried around loops), then once more to say what is wrong + let mut settled = false; + for _ in 0..16 { + let before = (kind.clone(), firsts.len()); + pass(&mut kind, &mut firsts, false)?; + if (&before.0, before.1) == (&kind, firsts.len()) { + settled = true; + break; + } + } + if !settled { + return Err((0, MIXED)); + } + pass(&mut kind, &mut firsts, true) +} + +/// The mode of a group barrier the translation adds (host waves meeting): +/// a wait for the group with a shared-memory fence; the fence alone with +/// `LEONIDA_GROUP_SYNC=0` ([`super::group_sync`]). +fn meeting_mode() -> u32 { + if super::group_sync() == 0 { 8 } else { 1 | 8 } +} + +/// LDS accesses of a console wave run as two host waves, where some sit in blocks that only +/// some lanes run (`all` is [`all_lane_blocks`]): per IR block, whether the host waves meet (a +/// group barrier) at its start and before its exit. `None` if barriers cannot keep the +/// console's order. +/// +/// The console runs the wave's lanes in step, so an LDS write is seen by every later read. Two +/// host waves keep that order if they meet between any two accesses of which one writes. A +/// barrier must be run by every thread, so it cannot stand in a lane branch's region; but +/// every way into and out of such a region passes a block all lanes run, and the waves meet +/// there: before the exit of an all-lane block into a region with LDS accesses, and at the +/// start of an all-lane block entered from one. Accesses in all-lane blocks get their own +/// barrier as before. What that cannot order is a write and a read inside one region (blocks +/// joined without an all-lane block between them): refused. +/// shortcut: two writes in one region are taken not to hit the same dword from both halves. +fn lds_meetings(p: &crate::ir::Program, st: &Structured, all: &[bool]) -> Option> { + let n = st.exits.len(); + let succ = |b: usize| -> Vec { + match st.exits[b] { + LaneExit::Jump(t) => vec![t], + LaneExit::Branch { taken, not_taken, .. } => vec![taken, not_taken], + LaneExit::End | LaneExit::Indirect => Vec::new(), + } + }; + // regions: blocks not every lane runs, joined by the edges between them + let mut region: Vec = (0..n).collect(); + fn find(region: &mut [usize], mut b: usize) -> usize { + while region[b] != b { + region[b] = region[region[b]]; + b = region[b]; + } + b + } + for b in 0..n { + for t in succ(b) { + if !all[b] && !all[t] { + let (x, y) = (find(&mut region, b), find(&mut region, t)); + region[x] = y; + } + } + } + // per region: LDS reads, LDS writes + let mut reads = vec![false; n]; + let mut writes = vec![false; n]; + for (b, block) in p.blocks.iter().enumerate().take(n) { + if all[b] { + continue; + } + let r = find(&mut region, b); + for i in &block.insts { + let name = i.name(); + if !matches!(i.fields, Fields::Ds { .. }) || name.starts_with("ds_swizzle") || name.contains("permute") { + continue; + } + if name.starts_with("ds_read") { + reads[r] = true; + } else { + writes[r] = true; + } + } + } + if (0..n).any(|r| reads[r] && writes[r]) { + return None; + } + let mut meet = vec![(false, false); n]; + for b in 0..n { + for t in succ(b) { + if all[b] && !all[t] { + let r = find(&mut region, t); + meet[b].1 |= reads[r] || writes[r]; + } else if !all[b] && all[t] { + let r = find(&mut region, b); + meet[t].0 |= reads[r] || writes[r]; + } + } + } + Some(meet) +} + +/// Masks held as numbers or constant lane sets in guards or lane branches: the lane tests its +/// own bit by its console lane. +fn lane_constant_masks(st: &Structured) -> bool { + let whens = st.exits.iter().filter_map(|e| match *e { + LaneExit::Branch { when, .. } => Some(when), + _ => None, + }); + let mut work: Vec = st.guards.iter().flatten().flatten().copied().chain(whens).collect(); + // Through lane-mask joins too: an edge that brings a number or a constant lane set needs + // the lane's own bit of it. + // shortcut: masks only selects read (`v_cndmask_b32`, carries in) are not followed; such + // a program still stops with "a constant lane mask" or "an opaque lane mask". + let (mut seen, mut joins) = (HashSet::new(), HashSet::new()); + while let Some(g) = work.pop() { + if !seen.insert(g) { + continue; + } + for a in st.bools.support(g) { + match a { + Atom::Opaque(_) | Atom::Constant(_) => return true, + Atom::Phi(id) if joins.insert(id) => { + if let Some(edges) = st.phi_masks.get(&id) { + work.extend(edges.iter().copied()); + } + } + _ => {} + } + } + } + false +} + +/// The widest wave the host GPU runs (0: not known – no host-specific forms); see +/// [`set_host_max_wave`]. +static HOST_MAX_WAVE: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); + +/// The host GPU's `WaveLaneCountMax`: 32 lets console wave64 compute programs whose cross-lane +/// code stays inside 32-lane halves run in waves of 32 instead of being refused. +pub fn set_host_max_wave(lanes: u32) { + HOST_MAX_WAVE.store(lanes, std::sync::atomic::Ordering::Relaxed); +} + +thread_local! { + /// See [`take_needs`]. + static NEEDS: std::cell::RefCell> = const { std::cell::RefCell::new(Vec::new()) }; + /// See [`with_local_waves`]. + static LOCAL_WAVES: std::cell::Cell = const { std::cell::Cell::new(false) }; + /// See [`with_local_waves_any`]. + static LOCAL_ANY: std::cell::Cell = const { std::cell::Cell::new(false) }; +} + +/// As [`with_local_waves`], with every other use of a lane mask as a number +/// and every lane read and write taken per host wave too: the program runs +/// as it would on a console of 32-lane waves, lanes numbered 0..31 or +/// 32..63 by half. Right for code that only relies on what HLSL's wave +/// operations promise; a program that takes one wave to be its whole +/// thread group gets per-half results. The last resort for programs that +/// do not translate otherwise. +pub(super) fn with_local_waves_any(f: impl FnOnce() -> R) -> R { + let was = LOCAL_ANY.replace(true); + let r = with_local_waves(f); + LOCAL_ANY.set(was); + r +} + +/// Runs `f` with console wave64 programs on 32-lane hosts lowered with each +/// host wave as a wave of its own ("local"): no exchange between the two +/// halves of a console wave, so no barriers and no need for every lane to +/// reach the code. What HLSL's wave operations promise holds for any +/// division of the threads into waves, and the idiom the title's compute +/// programs use them for does not care which wave a thread is in: count or +/// sum over the wave, the first lane reserves that many slots with an atomic +/// add, every lane takes the base (`WaveReadLaneFirst`) plus its prefix. +/// Each lane still gets a slot of its own; only the order differs. +/// Only that idiom's operations are lowered this way: a lane mask read as +/// a number by anything but a bit count, a first-set-bit or `v_mbcnt`, and +/// lane reads and writes outside whole-wave sections, stop the translation. +/// shortcut: where a count or sum goes is not checked. A program that uses +/// a wave-wide result as data for the whole console wave (a tile's maximum, +/// say, with one wave per thread group) gets its half's result. It is used +/// only for programs that do not translate otherwise. +pub(super) fn with_local_waves(f: impl FnOnce() -> R) -> R { + let was = LOCAL_WAVES.replace(true); + let r = f(); + LOCAL_WAVES.set(was); + r +} + +/// `LEONIDA_F16_NEAREST=1`: the results of 16-bit float operations (`v_add_f16`, +/// `v_mul_f16`, `v_cvt_f16_f32` ...) are rounded to nearest as the console rounds them +/// ([`Lower::f16_nearest`]) instead of as the host's `f32tof16` does (toward zero on NVIDIA: +/// the last place of a result that is not exact is then one lower than the console's). +/// Off by default: it is exact but untried in a game run, and adds instructions to every +/// such operation. The wave sum of 16-bit floats ([`Lower::half_sum`]) is always exact. +fn f16_nearest_on() -> bool { + #[cfg(test)] + if let Some(on) = TEST_F16_NEAREST.get() { + return on; + } + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("LEONIDA_F16_NEAREST").is_some_and(|v| v == "1")) +} + +#[cfg(test)] +thread_local! { + /// A test's choice for [`f16_nearest_on`], for its thread only. + pub(super) static TEST_F16_NEAREST: std::cell::Cell> = const { std::cell::Cell::new(None) }; +} + +/// `LEONIDA_WAVE_OWN_BITS=0`: a wave OR where not every lane runs is refused as before +/// ([`super::own_bits`]). +fn own_bits_on() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("LEONIDA_WAVE_OWN_BITS").is_none_or(|v| v != "0")) +} + +/// The refusal of a first half of an interpolation whose result is read +/// as data ([`Lower::interp`]). +pub(super) const FIRST_HALF: &str = "the first half of an interpolation"; + +thread_local! { + /// Whether first halves of interpolations are evaluated as the pair + /// they start ([`with_first_half_pairs`]). + static FIRST_HALF_PAIRS: std::cell::Cell = const { std::cell::Cell::new(false) }; +} + +/// Runs `translate` with first halves of interpolations evaluated as the +/// pair they start: the translation of a program refused with +/// [`FIRST_HALF`] (`LEONIDA_FIRST_HALF=0`: refused again, as before). +pub(super) fn with_first_half_pairs(translate: impl FnOnce() -> R) -> R { + let before = FIRST_HALF_PAIRS.replace(true); + let result = translate(); + FIRST_HALF_PAIRS.set(before); + result +} + +pub(super) fn host_max_wave() -> u32 { + #[cfg(test)] + if let Some(lanes) = TEST_HOST_WAVE.get() { + return lanes; + } + HOST_MAX_WAVE.load(std::sync::atomic::Ordering::Relaxed) +} + +#[cfg(test)] +thread_local! { + /// A test's host wave size, for its thread only ([`set_host_max_wave`] is the process's). + pub(super) static TEST_HOST_WAVE: std::cell::Cell> = const { std::cell::Cell::new(None) }; +} + +pub(super) fn reads_mask_as_data(st: &Structured, i: &Inst) -> bool { + let is_mask = |v: Value| st.masks.contains_key(&v) || st.highs.contains_key(&v); + let ops: Vec<&Operand> = match &i.fields { + // A mask operation (its result a mask) is no data use. + Fields::Sop { .. } + if i.writes + .iter() + .any(|&(r, w)| matches!(r, Reg::S(_)) && is_mask(w)) => + { + return false; + } + Fields::Sop { src, .. } => src.iter().collect(), + Fields::Valu(v) + if !matches!(i.name(), "v_cndmask_b32") && !i.name().contains("_co_ci_") => + { + v.src.iter().collect() + } + _ => return false, + }; + ops.into_iter().any(|op| match *op { + Operand::Scalar { code, .. } if code != NULL => i.read(Reg::S(code)).is_some_and(is_mask), + _ => false, + }) +} + +/// The parameters packing 16-bit rows two per dword and where each lays +/// its elements out: (first row, [(dword, register, column, columns)]). +/// +/// The console gives every 16-bit element whole dwords. A parameter leads +/// with the first element of its first row, then the first element of its +/// second row. An element that shares a register behind another one (the +/// signature packs a short element into the free columns of an earlier +/// register) is NOT in that row's halves: it follows in the first +/// parameter, in row order, that has whole dwords left. +/// The title's packed pedestrian shaders show both cases: TEXCOORD7 (register 1, +/// columns 2-3, behind the two columns of TEXCOORD0) is exported in dword 3 +/// of parameter 0, after TEXCOORD1's two dwords; TEXCOORD6 (register 4, +/// column 3, behind the three columns of TEXCOORD4) in dword 3 of +/// parameter 3, after TEXCOORD5 and TEXCOORD7, while the high half of +/// TEXCOORD4's second dword stays zero. +type PackedLayout = Vec<(u8, Vec<(u8, u8, u8, u8)>)>; + +fn packed_layout(elements: &[SigElement], packs: &[(u8, Option)]) -> PackedLayout { + let of_row = |r: u8| { + let mut of: Vec<&SigElement> = elements + .iter() + .filter(|e| e.row == Some(u32::from(r))) + .collect(); + of.sort_by_key(|e| e.col); + of + }; + let mut packs = packs.to_vec(); + packs.sort_unstable(); + packs.dedup_by_key(|p| p.0); + // Per parameter: its first row, the dwords used, the elements. + let mut layout: Vec<(u8, u8, Vec<(u8, u8, u8, u8)>)> = Vec::new(); + let mut behind = Vec::new(); + for &(a, b) in &packs { + let mut placed = Vec::new(); + let mut at = 0u8; + if !of_row(a).is_empty() { + for r in [Some(a), b].into_iter().flatten() { + let of = of_row(r); + let Some((lead, more)) = of.split_first() else { + continue; + }; + placed.push((at, r, lead.col, lead.cols)); + at += lead.cols.div_ceil(2); + behind.extend(more.iter().map(|e| (r, e.col, e.cols))); + } + } + layout.push((a, at, placed)); + } + behind.sort_unstable(); + for (r, col, cols) in behind { + let need = cols.div_ceil(2); + if let Some(p) = layout.iter_mut().find(|p| p.1 + need <= 4) { + p.2.push((p.1, r, col, cols)); + p.1 += need; + } + } + layout.into_iter().map(|(a, _, of)| (a, of)).collect() +} + +/// Where half `h` (dword h / 2, the high half when odd) of the parameter +/// whose first 16-bit row is `a` comes from: a register and column of +/// `elements`, none for padding ([`packed_layout`]; `packs` lists every +/// parameter packing two 16-bit rows per dword). +fn packed_half( + elements: &[SigElement], + packs: &[(u8, Option)], + a: u8, + h: u8, +) -> Option<(u8, u8)> { + let layout = packed_layout(elements, packs); + let (_, of) = layout.iter().find(|p| p.0 == a)?; + of.iter().find_map(|&(dword, row, col, cols)| { + let k = h.checked_sub(2 * dword)?; + (k < cols).then_some((row, col + k)) + }) +} + +/// The pixel inputs packing two 16-bit rows per dword, as (first row, +/// second row) ([`packed_layout`]). +fn input_packs(io: &StageIo, inputs: &[SigElement]) -> Vec<(u8, Option)> { + let StageIo::Ps { + inputs: entries, .. + } = io + else { + return Vec::new(); + }; + let partners = half_input_partners(io, inputs); + entries + .iter() + .filter(|i| i.fp16 && i.pack2) + .map(|i| { + let b = if i.row2 != i.row { + Some(i.row2) + } else { + partners.get(&i.row).copied() + }; + (i.row, b) + }) + .collect() +} + +/// Vertex or mesh outputs of 16-bit values (see [`Lower::half_outputs`]): +/// a packed row's partner is the next 16-bit row of the signature that no +/// output entry names, taken in row order. +fn half_outputs(io: &StageIo, outputs: &[SigElement]) -> HashMap)> { + let entries = match io { + StageIo::Vs { outputs, .. } => outputs, + StageIo::Ms(ms) => &ms.outputs, + _ => return HashMap::new(), + }; + let per_vertex = || entries.iter().filter(|o| o.param & 0x80 == 0); + let mut free: Vec = outputs + .iter() + .filter(|e| e.half && e.kind == 0) + .filter_map(|e| u8::try_from(e.row?).ok()) + .filter(|&r| !per_vertex().any(|o| o.row == r)) + .collect(); + free.sort_unstable(); + free.dedup(); + let mut halves: Vec<_> = per_vertex().filter(|o| o.fp16).collect(); + halves.sort_by_key(|o| o.row); + halves + .into_iter() + .map(|o| { + let b = o + .pack2 + .then(|| free.iter().position(|&r| r > o.row)) + .flatten(); + (o.row, (o.pack2, b.map(|i| free.remove(i)))) + }) + .collect() +} + +/// Pixel inputs packing two 16-bit rows per dword whose second row the +/// metadata leaves out (`row2` = `row`): as for outputs +/// ([`half_outputs`]), the next 16-bit row of the signature that no input +/// entry names, taken in row order (rows the metadata does give are taken +/// first). +fn half_input_partners(io: &StageIo, inputs: &[SigElement]) -> HashMap { + let StageIo::Ps { + inputs: entries, .. + } = io + else { + return HashMap::new(); + }; + let packed = || entries.iter().filter(|i| i.fp16 && i.pack2); + let mut free: Vec = inputs + .iter() + .filter(|e| e.half && e.kind == 0) + .filter_map(|e| u8::try_from(e.row?).ok()) + .filter(|&r| !entries.iter().any(|i| i.row == r)) + .filter(|&r| !packed().any(|i| i.row2 != i.row && i.row2 == r)) + .collect(); + free.sort_unstable(); + free.dedup(); + let mut missing: Vec<_> = packed().filter(|i| i.row2 == i.row).collect(); + missing.sort_by_key(|i| i.row); + let mut partners = HashMap::new(); + for i in missing { + if let Some(k) = free.iter().position(|&r| r > i.row) { + partners.insert(i.row, free.remove(k)); + } + } + partners +} + +fn unsupported(offset: usize, what: Why) -> Stop { + Stop::Fail(ShaderError::Unsupported { offset, what }) +} + +impl<'a> Lower<'a> { + fn new(x: &'a Parts<'a>, bad: &'a HashMap) -> Self { + let p = x.p; + let mut phi_at = HashMap::new(); + for (b, block) in p.blocks.iter().enumerate() { + for (i, phi) in block.phis.iter().enumerate() { + phi_at.insert(phi.value, (b, i)); + } + } + let mut s = Shader::new(x.native.stage == HwStage::Ps); + s.inputs = x.inputs.clone(); + s.outputs = x.outputs.clone(); + let insts = || p.blocks.iter().flat_map(|b| &b.insts); + let writes_uavs = insts().any(|i| { + matches!(i.fields, Fields::Image { .. } | Fields::Buffer { .. }) + && (i.name().contains("store") || i.name().contains("atomic")) + }); + let mut console_lanes = false; + // LDS accesses get a group barrier each (a console wave split in two host waves) + let mut split_lds = false; + // with `split_lds`, LDS accesses in lane branches: the blocks every lane runs, and + // where the host waves meet around those branches (`lds_meetings`) + let mut lds_meet: Option<(Vec, Vec<(bool, bool)>)> = None; + // a console wave64 program in two host waves of 32 (`exchange`) + let mut exchange: Option<(u32, bool, Vec)> = None; + // a console wave64 program in host waves of 32: the LDS dword of `wave_base`'s counter + let mut halves: Option = None; + if let StageIo::Cs(cs) = x.native.io { + s.threads = Some(cs.threads); + s.lds_dwords = cs.lds_bytes() / 4; + // Code reading other lanes needs the console's wave size and + // lane order; so do lane masks read as numbers, and LDS shared + // within one wave, where the console compiler leaves out barriers. + console_lanes = insts().any(|i| { + let n = i.name(); + n.starts_with("ds_swizzle") + || n.contains("permute") + || n.starts_with("v_mbcnt") + || matches!(n, "v_readlane_b32" | "v_writelane_b32") + || matches!(&i.fields, Fields::Valu(v) if v.dpp.is_some()) + || reads_mask_as_data(x.st, i) + }) || lane_constant_masks(x.st) + // (a branch the wave takes together asks the wave) + || !x.st.wide.is_empty(); + let mut wave = if x.native.wave64 { 64 } else { 32 }; + let group = cs.threads.iter().product::(); + let one_wave = group <= wave; + // A host whose waves are at most 32 lanes (NVIDIA) refuses `WaveSize(64)`. A console + // wave64 program whose cross-lane code stays inside 32-lane halves – DPP rows, + // `ds_swizzle`, `v_permlane16` / `v_permlanex16`, which the ISA confines there – runs + // exactly in waves of 32: the thread relabelling makes each host wave one half of a + // console wave (lanes 32k..32k+31). Not when it crosses halves (`v_mbcnt`, + // `v_readlane`, `v_writelane`, `ds_(b)permute`, masks as numbers or lane-constant + // masks), nor when LDS may be shared within the console wave without barriers (a + // group over 32 threads with LDS): those still need 64-lane waves. + if wave == 64 && host_max_wave() == 32 && (console_lanes || one_wave && s.lds_dwords > 0) { + let crosses = insts().any(|i| { + let n = i.name(); + n.starts_with("v_mbcnt") + || matches!(n, "v_readlane_b32" | "v_writelane_b32") + || n.starts_with("ds_permute") + || n.starts_with("ds_bpermute") + || reads_mask_as_data(x.st, i) + }) || lane_constant_masks(x.st) + || !x.st.wide.is_empty(); + if !crosses && (s.lds_dwords == 0 || group <= 32) { + wave = 32; + } else { + // (Groups of several console waves too: each console wave is two host + // waves, which exchange through their own pair of dwords.) + // LDS the console shares within its one wave without barriers: split into + // two waves of 32, a group barrier before every LDS access keeps their order + // – where every thread of the group gets there (no lane branch around it, + // no guard), else a barrier would hang the group + let lds = |i: &Inst| { + matches!(i.fields, Fields::Ds { .. }) + && !(i.name().starts_with("ds_swizzle") || i.name().contains("permute")) + }; + if let Some(all) = all_lane_blocks(x.st) { + let ok = p.blocks.iter().enumerate().all(|(b, blk)| { + blk.insts.iter().all(|inst| { + !lds(inst) || all.get(b).copied().unwrap_or(false) + }) + }); + let mut lds_ok = !(s.lds_dwords > 0 && group > 32) || ok; + if !lds_ok && let Some(meet) = lds_meetings(p, x.st, &all) { + lds_meet = Some((all.clone(), meet)); + lds_ok = true; + } + if !lds_ok { + // (the blocks whose LDS accesses not every lane runs: with the + // branches around them taken wave-wide they get their barriers) + for (b, blk) in p.blocks.iter().enumerate() { + if !all.get(b).copied().unwrap_or(false) && blk.insts.iter().any(lds) { + need(b); + } + } + } + if lds_ok { + wave = 32; + split_lds = s.lds_dwords > 0 && group > 32; + if crosses { + // lanes 32..63 are the other host wave: masks, lane reads and lane + // numbers go through two exchange dwords past the program's LDS + exchange = Some((s.lds_dwords, group <= 32, all)); + s.lds_dwords += 2 * group.div_ceil(64); + } + } + } + } + // `LEONIDA_WAVE_WHY=1`: why a program keeps 64-lane waves (one line per reason) + if wave == 64 && std::env::var_os("LEONIDA_WAVE_WHY").is_some() { + let mut why: Vec<&str> = Vec::new(); + for i in insts() { + let n = i.name(); + let r = if n.starts_with("v_mbcnt") { + "v_mbcnt" + } else if n == "v_readlane_b32" { + "v_readlane" + } else if n == "v_writelane_b32" { + "v_writelane" + } else if n.starts_with("ds_permute") || n.starts_with("ds_bpermute") { + "ds_(b)permute" + } else if reads_mask_as_data(x.st, i) { + "mask as data" + } else { + continue; + }; + if !why.contains(&r) { + why.push(r); + } + } + if lane_constant_masks(x.st) { + why.push("lane-constant mask"); + } + if s.lds_dwords > 0 && group > 32 { + why.push("LDS in a group over 32"); + match all_lane_blocks(x.st) { + None => why.push("an indirect exit"), + Some(all) if lds_meetings(p, x.st, &all).is_none() => { + why.push("an LDS read and write in one lane-branch region") + } + Some(_) => {} + } + } + why.sort_unstable(); + eprintln!("WAVE64-WHY group={group} lds={} [{}]", s.lds_dwords > 0, why.join(", ")); + } + } + if wave == 32 && x.native.wave64 { + // console threads go to host waves in the order the waves take them (`wave_base`) + halves = Some(s.lds_dwords); + s.lds_dwords += 1; + } + if console_lanes || one_wave && s.lds_dwords > 0 { + s.wave_size = Some(wave); + } + } + // The title's barriers a thread of the group may never reach, which + // leaves the others waiting on the host: those in blocks some lanes + // do not run, and all of them in a program with a loop closed by a + // plain jump (a lane still in it at the iteration limit leaves the + // program there, `abort_block`). + let fence_only: HashSet = if insts().any(|i| i.name() == "s_barrier") { + let order = crate::ir::reverse_postorder(&p.blocks); + let mut place = vec![usize::MAX; p.blocks.len()]; + for (n, &b) in order.iter().enumerate() { + place[b] = n; + } + let back = |from: usize, to: usize| { + let at = |b: usize| place.get(b).copied().unwrap_or(usize::MAX); + at(from) != usize::MAX && at(to) <= at(from) + }; + let cut_short = x + .st + .exits + .iter() + .enumerate() + .any(|(b, e)| matches!(*e, LaneExit::Jump(t) if back(b, t))); + let all = all_lane_blocks(x.st); + (0..p.blocks.len()) + .filter(|&b| p.blocks[b].insts.iter().any(|i| i.name() == "s_barrier")) + .filter(|&b| { + cut_short + || all + .as_ref() + .is_none_or(|all| !all.get(b).copied().unwrap_or(false)) + }) + .collect() + } else { + HashSet::new() + }; + let mut no_barrier = HashSet::new(); + if let StageIo::Ms(ms) = &x.native.io { + s.prims = x.prims.clone(); + s.threads = Some([ms.threads, 1, 1]); + s.lds_dwords = ms.lds_bytes.div_ceil(4); + s.mesh = Some(super::shader::Mesh { + max_vertices: ms.max_vertices, + max_primitives: ms.max_primitives, + topology: ms.topology, + }); + // Barriers order the lanes' LDS accesses; the console's + // allocation request needs them too, but the host does not. One + // lane sends that request, and what it dominates (the path for + // counts out of range) runs in that lane alone, so its barrier + // would hang the host. + 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 alloc: Vec = (0..p.blocks.len()) + .filter(|&b| { + p.blocks[b].insts.iter().any(|i| { + i.name() == "s_sendmsg" + && matches!(i.fields, Fields::Sopp { imm } if imm & 0xF == GS_ALLOC_REQ) + }) + }) + .collect(); + for &b in &order { + let mut d = b; + let dominated = loop { + if alloc.contains(&d) { + break true; + } + if idom[d] == d || idom[d] == usize::MAX { + break false; + } + d = idom[d]; + }; + if ms.lds_bytes == 0 || dominated { + no_barrier.insert(b); + } + } + } + Lower { + s, + x, + bad, + lane_fail: HashMap::new(), + vals: HashMap::new(), + floats: HashMap::new(), + block: vec![None; p.blocks.len()], + cur: 0, + bools: HashMap::new(), + lane_bits: HashMap::new(), + phi_at, + mask_phis: HashMap::new(), + pending_masks: Vec::new(), + data_phis: Vec::new(), + read_phis: HashSet::new(), + stale: HashSet::new(), + params: x.res.params.iter().map(|&(v, p, d)| (v, (p, d))).collect(), + user_data: None, + user_reads: BTreeMap::new(), + samplers: Vec::new(), + descriptors: x + .res + .descriptors + .iter() + .map(|d| ((d.site, d.role == Role::Sampler), &d.source)) + .collect(), + scalar: x.res.scalar.iter().copied().collect(), + exports: x.io.exports.iter().map(|e| (e.site, e)).collect(), + interps: { + let mut m: HashMap = x.io.interps.iter().map(|(s, i)| (*s, i)).collect(); + // A first half whose result is also read as data (an f16 second half keeps + // the other half of its dst, PS_DeferredTextured): evaluated as the pair it + // starts. Approximate for those other bits (P0 + i P10 on the console); a + // first half only the second half reads is gone before lowering. + // Only in the second translation of a program the first + // one refused for it ([`with_first_half_pairs`]). + if FIRST_HALF_PAIRS.get() && std::env::var_os("LEONIDA_FIRST_HALF").is_none_or(|v| v != "0") { + for (_, i) in &x.io.interps { + if let Interp::Interpolated { first, .. } = i { + for s in first { + m.entry(*s).or_insert(i); + } + } + } + } + m + }, + handles: HashMap::new(), + strides: HashMap::new(), + edges: HashMap::new(), + exported: vec![false; p.blocks.len()], + rpo: vec![usize::MAX; p.blocks.len()], + tail: vec![None; p.blocks.len()], + writes_uavs, + src0: None, + console_lanes, + split_lds, + lds_meet, + local: exchange.is_some() && LOCAL_WAVES.get(), + local_ok: false, + local_any: LOCAL_ANY.get(), + uniform: match &exchange { + Some((_, false, all)) if !LOCAL_WAVES.get() => lane_uniform(p, x.st, all), + _ => HashSet::new(), + }, + own_bits: match &exchange { + Some((_, false, _)) if !LOCAL_WAVES.get() && own_bits_on() => { + super::own_bits::find(p, x.st, std::env::var_os("LEONIDA_WAVE_WHY").is_some()) + } + _ => Default::default(), + }, + exchange, + clane: None, + pair: None, + halves, + wave_base: None, + flat: None, + no_barrier, + fence_only, + half_outputs: half_outputs(&x.native.io, &x.outputs), + mask_data: match x.native.stage { + HwStage::Cs => MaskData::Console, + HwStage::Ps | HwStage::Vs => MaskData::Host, + _ => MaskData::None, + }, + mask_ok: false, + ballots: HashMap::new(), + balloting: HashSet::new(), + def_block: p + .blocks + .iter() + .enumerate() + .flat_map(|(b, block)| { + block + .insts + .iter() + .flat_map(move |i| i.writes.iter().map(move |w| (w.1, b))) + .chain(block.phis.iter().map(move |phi| (phi.value, b))) + }) + .collect(), + cur_ir: 0, + sections: HashMap::new(), + section_out: HashSet::new(), + code_table: None, + counters: HashMap::new(), + abort: None, + } + } + + /// The dword of the program's code at byte `byte` (a constant table + /// the compiler appends to the code), as an internal constant array. + // shortcut: an index outside the table reads its last dword (the + // console would read whatever memory follows the code). + fn code_dword(&mut self, byte: V) -> Result { + let (g, base, len) = match self.code_table { + Some(t) => t, + None => { + let first = self + .x + .res + .scalar + .iter() + .map(|s| s.1) + .chain(self.x.res.descriptors.iter().flat_map(|d| { + d.source.leaves().into_iter().filter_map(|l| match l { + Source::Built { address, .. } => Some(*address), + _ => None, + }) + })) + .filter(|a| a.param == CODE) + .map(|a| a.offset & !3) + .min() + .ok_or("a code table")?; + let code = &self.x.native.code; + let words: Vec = code + .get(first as usize..) + .ok_or("a code table past the code")? + .chunks(4) + .map(|c| { + let mut w = [0u8; 4]; + w[..c.len()].copy_from_slice(c); + u32::from_le_bytes(w) + }) + .collect(); + if words.is_empty() { + return Err("a code table past the code"); + } + let elems: Vec = words.iter().map(|&w| self.s.m.i32(w)).collect(); + let arr = self.s.m.array(words.len() as u32, self.s.t.i32); + let init = self.s.m.aggregate(arr, &elems); + let g = self.s.m.constant_global("code", init); + let t = (g, first, words.len() as u32); + self.code_table = Some(t); + t + } + }; + let c = self.cur; + let k = self.s.m.i32(base); + let rel = self.s.m.bin(c, Bin::Sub, byte, k); + let two = self.s.m.i32(2); + let index = self.s.m.bin(c, Bin::LShr, rel, two); + let last = self.s.m.i32(len - 1); + let over = self.s.m.cmp(c, pred::IUGT, index, last); + let index = self.s.m.select(c, over, last, index); + let at = self.s.m.element(c, g, index); + Ok(self.s.m.load(c, at)) + } + + /// A global memory load (`global_load_*`): from the program's constant + /// table, or from a root SRV at the address the title sets. + fn flat(&mut self, inst: &Inst, b: usize, i: usize) -> Result<(), Why> { + let Fields::Flat { dst, .. } = &inst.fields else { + unreachable!() + }; + let name = inst.name(); + if self.scalar.get(&(b, i)).is_some_and(|a| a.param == MEMORY) { + return self.memory_flat(inst, b, i); + } + let rest = name + .strip_prefix("global_load_") + .ok_or("a global memory write")?; + let (n, sub) = match rest { + "dword" => (1, None), + "dwordx2" => (2, None), + "dwordx3" => (3, None), + "dwordx4" => (4, None), + "ubyte" => (1, Some((8, false))), + "sbyte" => (1, Some((8, true))), + "ushort" => (1, Some((16, false))), + "sshort" => (1, Some((16, true))), + _ => return Err(name), + }; + let a = *self + .scalar + .get(&(b, i)) + .ok_or("an untracked global address")?; + let guard = self.guard(b, i)?; + let Some(Operand::Vector { reg, .. }) = *dst else { + return Err("a global load result"); + }; + let c = self.cur; + let mut off = self.s.m.i32(a.offset); + if let Some(d) = a.dynamic { + let d = self.i32_of(d)?; + off = self.s.m.bin(c, Bin::Add, off, d); + } + let h = if a.param == CODE { + None + } else { + let src = Source::Built { + address: a, + bits: 0, + words: [0, 0], + }; + if let Some(bias) = self.root_bias(a.param) { + off = self.s.m.bin(c, Bin::Add, off, bias); + } + Some(self.handle((b, i), &src, false, (11, 0))?) + }; + let dword = |l: &mut Self, byte: V| -> Result { + match h { + None => l.code_dword(byte), + Some(h) => { + let c = l.cur; + let (u, mask, al) = (l.s.m.undef(l.s.t.i32), l.s.m.i8(1), l.s.m.i32(4)); + let r = l.s.op( + c, + "rawBufferLoad.f32", + Attr::ReadOnly, + l.s.t.res_ret, + 139, + &[h, byte, u, mask, al], + ); + let x = l.s.m.extract(c, r, 0); + Ok(l.as_int(x)) + } + } + }; + for k in 0..n { + let x = match sub { + None => { + let four = self.s.m.i32(4 * k); + let at = self.s.m.bin(c, Bin::Add, off, four); + dword(self, at)? + } + Some((width, signed)) => { + // shortcut: the field is taken not to cross a dword. + let (not3, three) = (self.s.m.i32(!3), self.s.m.i32(3)); + let at = self.s.m.bin(c, Bin::And, off, not3); + let w = dword(self, at)?; + let byte = self.s.m.bin(c, Bin::And, off, three); + let sh = self.s.m.bin(c, Bin::Shl, byte, three); + let x = self.s.m.bin(c, Bin::LShr, w, sh); + let left = self.s.m.i32(32 - width); + let x = self.s.m.bin(c, Bin::Shl, x, left); + self.s + .m + .bin(c, if signed { Bin::AShr } else { Bin::LShr }, x, left) + } + }; + self.write(inst, Reg::V(reg + k as u8), x, guard); + } + Ok(()) + } + + /// Finds the whole-wave sections and the values they leave. + fn find_sections(&mut self) { + let p = self.x.p; + let mut inside: HashMap = HashMap::new(); + for b in 0..p.blocks.len() { + let found = super::wave::sections(p, b); + for (&start, sec) in &found { + for i in start + 1..sec.end { + for &(_, w) in &p.blocks[b].insts[i].writes { + inside.insert(w, (b, start, sec.end)); + } + } + } + if !found.is_empty() { + self.sections.insert(b, found); + } + } + if inside.is_empty() { + return; + } + for (b, block) in p.blocks.iter().enumerate() { + for phi in &block.phis { + self.section_out + .extend(phi.args.iter().filter(|a| inside.contains_key(a))); + } + for (i, inst) in block.insts.iter().enumerate() { + for &(_, r) in &inst.reads { + if let Some(&(sb, start, end)) = inside.get(&r) + && !(sb == b && i > start && i < end) + { + self.section_out.insert(r); + } + } + } + } + } + + /// An instruction inside a whole-wave section: the values that leave + /// the section are made from what the simulation found them to be. + fn section_inst(&mut self, b: usize, i: usize, start: usize) { + const UNKNOWN: Why = "a whole-wave section step the simulation does not follow"; + let inst = &self.x.p.blocks[b].insts[i]; + for &(_, w) in &inst.writes { + let val = if self.section_out.contains(&w) { + let shape = self.sections[&b][&start].shapes.get(&w).copied(); + let own = self.own_bits.totals.contains(&w); + match shape.ok_or(UNKNOWN).and_then(|sh| self.shape(sh, own)) { + Ok(x) => Val::I32(x), + Err(why) => Val::Missing(why), + } + } else { + Val::Missing(UNKNOWN) + }; + self.vals.insert(w, val); + } + } + + /// A value a whole-wave section leaves, as DXIL wave operations over the + /// host's active lanes: the console's result with console lanes; on + /// another wave size, what the HLSL wave operation the console compiler + /// expanded gives on that wave. + /// + /// `own`: a wave OR that only steers a loop over each lane's own bits + /// ([`super::own_bits`]); where two host waves cannot exchange their halves' ORs it is + /// this host wave's. + fn shape(&mut self, shape: super::wave::Shape, own: bool) -> Result { + use super::wave::{Op, Shape}; + let (op, src, mask, ident, prefix) = match shape { + Shape::K(k) => return Ok(self.s.m.i32(k)), + Shape::Value(v) => return self.i32_of(v), + Shape::Active(op, src, mask, ident) => (op, src, mask, ident, None), + Shape::ActiveF64(lo, hi, mask, high) => { + return self.active_f64_sum(lo, hi, mask, high); + } + Shape::Masked(src, mask, ident) => { + let c = self.cur; + let &m = self + .x + .st + .masks + .get(&mask) + .ok_or("a wave reduction's untracked mask")?; + let on = self.boolean(m, c)?; + let x = self.i32_of(src)?; + let id = self.s.m.i32(ident); + return Ok(self.s.m.select(c, on, x, id)); + } + Shape::Prefix(op, src, mask, ident, inclusive) => { + (op, src, mask, ident, Some(inclusive)) + } + }; + // Mesh: no host wave size can be declared, so a reduction is over this host wave + // only. A minimum or maximum is taken that way: the compiler's "next distinct + // value" loop (the wave's minimum, then the lanes that hold it) serves every + // lane however the lanes are divided into waves. A sum, a bit reduction or a + // prefix would be of part of a console wave: still refused. + if self.mask_data == MaskData::None + && (prefix.is_some() + || !matches!( + op, + Op::MinU | Op::MaxU | Op::MinI | Op::MaxI | Op::MinF | Op::MaxF + )) + { + return Err("a wave reduction in a mesh shader"); + } + let c = self.cur; + let &m = self + .x + .st + .masks + .get(&mask) + .ok_or("a wave reduction's untracked mask")?; + let on = self.boolean(m, c)?; + let x = self.i32_of(src)?; + let id = self.s.m.i32(ident); + let x = self.s.m.select(c, on, x, id); + self.s.flags |= flags::WAVE_OPS; + if op == Op::AddH { + return match prefix { + Some(_) => Err("a wave prefix of an operation other than a sum"), + None => self.half_sum(x), + }; + } + let float = matches!(op, Op::AddF | Op::MinF | Op::MaxF); + let (i32t, f32t) = (self.s.t.i32, self.s.t.f32); + let arg = if float { self.as_float(x) } else { x }; + let ty = if float { f32t } else { i32t }; + let sfx = if float { "f32" } else { "i32" }; + let r = match (op, prefix) { + (Op::AddU | Op::AddF, Some(inclusive)) => { + let (k0, k1) = (self.s.m.i8(0), self.s.m.i8(1)); + let r = self.s.op( + c, + &format!("wavePrefixOp.{sfx}"), + Attr::NoUnwind, + ty, + 121, + &[arg, k0, k1], + ); + if inclusive { + self.s.m.bin(c, Bin::Add, r, arg) + } else { + r + } + } + (_, Some(_)) => return Err("a wave prefix of an operation other than a sum"), + (Op::Or | Op::And | Op::Xor, None) => { + let k = self.s.m.i8(match op { + Op::And => 0, + Op::Or => 1, + _ => 2, + }); + self.s + .op(c, "waveActiveBit.i32", Attr::NoUnwind, i32t, 120, &[arg, k]) + } + (_, None) => { + let (code, unsigned) = match op { + Op::AddU => (0, 1), + Op::AddF => (0, 0), + Op::MinU => (2, 1), + Op::MaxU => (3, 1), + Op::MinI | Op::MinF => (2, 0), + _ => (3, 0), + }; + let (k, u) = (self.s.m.i8(code), self.s.m.i8(unsigned)); + self.s.op( + c, + &format!("waveActiveOp.{sfx}"), + Attr::NoUnwind, + ty, + 119, + &[arg, k, u], + ) + } + }; + // two host waves of 32 hold the console's 64 lanes: their results combine + let r = if self.local || self.exchange.as_ref().is_some_and(|e| e.1) { + // this host wave's own result (and prefix): each wave on its own, or a group of + // 32 threads or fewer, which one host wave holds whole (combining with the 0 a + // missing half "gives" broke AND, MIN and signed MAX) + r + } else if own && prefix.is_none() && op == Op::Or && !self.all_lanes(self.cur_ir) { + // each thread walks the bits of this value and works only at its own, which the + // host wave's OR holds: the same run as with the console wave's OR + r + } else if self.exchange.is_some() { + if !self.all_lanes(self.cur_ir) { + need(self.cur_ir); + return Err("a wave reduction where not every lane runs"); + } + let bits = |l: &mut Self, v: V| if float { l.as_int(v) } else { v }; + let back = |l: &mut Self, v: V| if float { l.as_float(v) } else { v }; + match prefix { + Some(_) => { + // the upper half adds the lower half's total to its prefix + let (k0, ku) = (self.s.m.i8(0), self.s.m.i8(u8::from(!float))); + let total = self.s.op(c, &format!("waveActiveOp.{sfx}"), Attr::NoUnwind, ty, 119, &[arg, k0, ku]); + let tb = bits(self, total); + let c = self.cur; + let (lo, _) = self.exchange_halves(c, tb); + let lo = back(self, lo); + let cl = self.console_lane(); + let k32 = self.s.m.i32(32); + let upper = self.s.m.cmp(c, pred::IUGE, cl, k32); + let zero = if float { self.s.m.f32(0) } else { self.s.m.i32(0) }; + let add = self.s.m.select(c, upper, lo, zero); + self.s.m.bin(c, Bin::Add, r, add) + } + None => { + let rb = bits(self, r); + let c = self.cur; + let (lo, hi) = self.exchange_halves(c, rb); + let (lo, hi) = (back(self, lo), back(self, hi)); + match op { + Op::AddU | Op::AddF => self.s.m.bin(c, Bin::Add, lo, hi), + Op::Or => self.s.m.bin(c, Bin::Or, lo, hi), + Op::And => self.s.m.bin(c, Bin::And, lo, hi), + Op::Xor => self.s.m.bin(c, Bin::Xor, lo, hi), + _ => { + // FMax 35, FMin 36, IMax 37, IMin 38, UMax 39, UMin 40 + let code = match op { + Op::MaxF => 35, + Op::MinF => 36, + Op::MinU => 40, + Op::MaxU => 39, + Op::MinI => 38, + _ => 37, + }; + self.s.op(c, &format!("binary.{sfx}"), Attr::ReadNone, ty, code, &[lo, hi]) + } + } + } + } + } else { + r + }; + Ok(if float { self.as_int(r) } else { r }) + } + + /// `WaveActiveSum` of 64-bit floats (`f64(lo, hi)` in active lanes, `+0.0` elsewhere), + /// returning the low (`!high`) or high (`high`) 32-bit word. + fn active_f64_sum( + &mut self, + lo: Value, + hi: Value, + mask: Value, + high: bool, + ) -> Result { + if self.mask_data == MaskData::None { + return Err("a wave reduction in a mesh shader"); + } + let c = self.cur; + let &m = self + .x + .st + .masks + .get(&mask) + .ok_or("a wave reduction's untracked mask")?; + let on = self.boolean(m, c)?; + let lo = self.i32_of(lo)?; + let hi = self.i32_of(hi)?; + let z = self.s.m.i32(0); + let lo = self.s.m.select(c, on, lo, z); + let hi = self.s.m.select(c, on, hi, z); + self.s.flags |= flags::WAVE_OPS | flags::DOUBLES; + let f64t = self.s.m.double(); + let i32t = self.s.t.i32; + let split_ty = self + .s + .m + .named_struct("dx.types.splitdouble", vec![i32t, i32t]); + let arg = self + .s + .op(c, "makeDouble.f64", Attr::ReadNone, f64t, 101, &[lo, hi]); + let (k0, k0b) = (self.s.m.i8(0), self.s.m.i8(0)); + let sum = self + .s + .op(c, "waveActiveOp.f64", Attr::NoUnwind, f64t, 119, &[arg, k0, k0b]); + let split = self + .s + .op(c, "splitDouble.f64", Attr::ReadNone, split_ty, 102, &[sum]); + let mut r_lo = self.s.m.extract(c, split, 0); + let mut r_hi = self.s.m.extract(c, split, 1); + if self.exchange.is_some() { + if !self.all_lanes(self.cur_ir) { + need(self.cur_ir); + return Err("a wave reduction where not every lane runs"); + } + let (lo0, lo1) = self.exchange_halves(self.cur, r_lo); + let (hi0, hi1) = self.exchange_halves(self.cur, r_hi); + let c = self.cur; + let d0 = self + .s + .op(c, "makeDouble.f64", Attr::ReadNone, f64t, 101, &[lo0, hi0]); + let d1 = self + .s + .op(c, "makeDouble.f64", Attr::ReadNone, f64t, 101, &[lo1, hi1]); + let total = self.s.m.bin(c, Bin::Add, d0, d1); + let split = self + .s + .op(c, "splitDouble.f64", Attr::ReadNone, split_ty, 102, &[total]); + r_lo = self.s.m.extract(c, split, 0); + r_hi = self.s.m.extract(c, split, 1); + } + Ok(if high { r_hi } else { r_lo }) + } + + /// The sum of two 16-bit floats (the low halves of `a` and `b`) as the console's + /// `v_add_f16` gives it: added in f32 and rounded to 16 bits, to nearest + /// ([`Self::f16_nearest`]). + fn add_halves(&mut self, a: V, b: V) -> V { + let c = self.cur; + let f32t = self.s.t.f32; + let low = self.s.m.i32(0xFFFF); + let wide = |l: &mut Self, x: V| { + let h = l.s.m.bin(c, Bin::And, x, low); + l.s.op(c, "legacyF16ToF32", Attr::ReadNone, f32t, 131, &[h]) + }; + let (fa, fb) = (wide(self, a), wide(self, b)); + let f = self.s.m.bin(c, Bin::Add, fa, fb); + self.f16_nearest(f) + } + + /// `WaveActiveSum` of 16-bit floats (`x`: each lane's term in its low half, +0 in the + /// lanes outside the mask), bit for bit as the console adds it: every addition rounds to + /// 16 bits, so the order counts, and the compiler's is the balanced tree over the lanes + /// in their order (lanes 2k and 2k+1, then pairs, ... then the wave's two halves; + /// [`super::wave::buddies`]). Each lane adds its partner's partial sum, read from the + /// lane whose number differs in one bit, step by step; two host waves of 32 then exchange + /// their halves' sums for the last addition. The high half of the result is lane 0's, + /// which no `v_add_f16` writes. + /// That needs every lane of a full wave there to be read: refused where not every lane + /// runs, in a thread group that does not fill its waves, and for each half-wave on its + /// own (half a sum is no sum). + fn half_sum(&mut self, x: V) -> Result { + const WHERE: Why = "a wave sum of 16-bit floats where not every lane runs"; + let threads = self.s.threads.ok_or("a wave sum of 16-bit floats outside compute")?; + if threads.iter().product::() % 64 != 0 { + return Err("a wave sum of 16-bit floats in a wave that is not full"); + } + if self.local { + return Err("a wave sum of 16-bit floats in a half-wave"); + } + // two host waves of 32 that exchange, or one host wave of 64 lanes + let halves = match (&self.exchange, self.s.wave_size) { + (Some((_, false, _)), _) => true, + (None, Some(64)) if self.x.p.wave64 => false, + _ => return Err("a wave sum of 16-bit floats on these waves"), + }; + let every = if halves { + self.all_lanes(self.cur_ir) + } else { + all_lane_blocks(self.x.st).is_some_and(|all| all.get(self.cur_ir).copied().unwrap_or(false)) + }; + if !every { + if halves { + need(self.cur_ir); + return Err(WHERE); + } + return Ok(self.half_sum_present(x)); + } + let c = self.cur; + let i32t = self.s.t.i32; + let lane = self.s.op(c, "waveGetLaneIndex", Attr::ReadOnly, i32t, 111, &[]); + let mut sum = x; + for step in 0..if halves { 5 } else { 6 } { + let bit = self.s.m.i32(1 << step); + let partner = self.s.m.bin(c, Bin::Xor, lane, bit); + let theirs = self.read_lane(sum, partner); + sum = self.add_halves(sum, theirs); + } + let (high, low, zero) = (self.s.m.i32(0xFFFF_0000), self.s.m.i32(0xFFFF), self.s.m.i32(0)); + let first = self.read_lane(x, zero); + let first = self.s.m.bin(c, Bin::And, first, high); + let sum = self.s.m.bin(c, Bin::And, sum, low); + let mine = self.s.m.bin(c, Bin::Or, first, sum); + if !halves { + return Ok(mine); + } + let (lo, hi) = self.exchange_halves(c, mine); + let c = self.cur; + let total = self.add_halves(lo, hi); + let total = self.s.m.bin(c, Bin::And, total, low); + let first = self.s.m.bin(c, Bin::And, lo, high); + Ok(self.s.m.bin(c, Bin::Or, first, total)) + } + + /// [`Self::half_sum`] in one host wave of 64 where some lanes have left (a thread past + /// the end of the data returns early): the console runs the sum in every lane, a lane + /// outside EXEC with +0, so after step k every lane of an aligned run of 2^k lanes holds + /// that run's partial sum, the lanes that left included. A lane reads its partner run's + /// sum from the first lane of that run that is here, and +0 where none is (every lane of + /// the run left, so its terms were all +0). Lane 0's high half likewise: 0 if it left. + fn half_sum_present(&mut self, x: V) -> V { + let c = self.cur; + let i32t = self.s.t.i32; + self.s.flags |= flags::WAVE_OPS; + let four = self.s.m.named_struct("dx.types.fouri32", vec![i32t; 4]); + let here = self.s.m.bool(true); + let ballot = self.s.op(c, "waveActiveBallot", Attr::NoUnwind, four, 116, &[here]); + let (blo, bhi) = (self.s.m.extract(c, ballot, 0), self.s.m.extract(c, ballot, 1)); + let lane = self.s.op(c, "waveGetLaneIndex", Attr::ReadOnly, i32t, 111, &[]); + let [zero, k31, k32] = [0, 31, 32].map(|k| self.s.m.i32(k)); + // The lanes of the run of `size` lanes at `base` that are here, from bit 0. + let present = |l: &mut Self, base: V, size: u32| -> V { + let upper = l.s.m.cmp(c, pred::IUGE, base, k32); + let word = l.s.m.select(c, upper, bhi, blo); + let at = l.s.m.bin(c, Bin::And, base, k31); + let bits = l.s.m.bin(c, Bin::LShr, word, at); + if size >= 32 { + bits + } else { + let m = l.s.m.i32((1u32 << size) - 1); + l.s.m.bin(c, Bin::And, bits, m) + } + }; + let mut sum = x; + for step in 0..6u32 { + let size = 1u32 << step; + let (bit, run) = (self.s.m.i32(size), self.s.m.i32(!(size - 1))); + let other = self.s.m.bin(c, Bin::Xor, lane, bit); + let base = self.s.m.bin(c, Bin::And, other, run); + let bits = present(self, base, size); + // FirstbitLo (dx.op 32): the run's first lane that is here + let first = self.s.op(c, "unaryBits.i32", Attr::ReadNone, i32t, 32, &[bits]); + let any = self.s.m.cmp(c, pred::NE, bits, zero); + let first = self.s.m.select(c, any, first, zero); + let from = self.s.m.bin(c, Bin::Add, base, first); + let theirs = self.read_lane(sum, from); + let theirs = self.s.m.select(c, any, theirs, zero); + sum = self.add_halves(sum, theirs); + } + let (high, low, one) = (self.s.m.i32(0xFFFF_0000), self.s.m.i32(0xFFFF), self.s.m.i32(1)); + let lane0 = self.s.m.bin(c, Bin::And, blo, one); + let lane0 = self.s.m.cmp(c, pred::NE, lane0, zero); + let first = self.read_lane(x, zero); + let first = self.s.m.select(c, lane0, first, zero); + let first = self.s.m.bin(c, Bin::And, first, high); + let sum = self.s.m.bin(c, Bin::And, sum, low); + self.s.m.bin(c, Bin::Or, first, sum) + } + + fn run(mut self) -> Result { + let p = self.x.p; + let order = crate::ir::reverse_postorder(&p.blocks); + for (n, &b) in order.iter().enumerate() { + self.rpo[b] = n; + } + for (n, &b) in order.iter().enumerate() { + self.block[b] = Some(if n == 0 { + self.s.entry + } else { + self.s.m.new_block() + }); + } + // Loop headers count iterations (`LOOP_LIMIT`). + for &b in &order { + let header = p.blocks[b] + .preds + .iter() + .any(|&q| self.block[q].is_some() && self.rpo[b] <= self.rpo[q]); + if header { + let blk = self.block[b].expect("reachable"); + let phi = self.s.m.phi(blk, self.s.t.i32); + self.counters.insert(b, (phi, Vec::new())); + } + } + self.cur = self.s.entry; + self.find_sections(); + self.inputs()?; + if let Some(mesh) = self.s.mesh { + self.mesh_prologue(mesh).map_err(|w| unsupported(0, w))?; + self.block[order[0]] = Some(self.cur); + } + for &b in &order { + self.cur = self.block[b].expect("reachable"); + self.cur_ir = b; + let preds: Vec = p.blocks[b] + .preds + .iter() + .copied() + .filter(|&q| self.block[q].is_some()) + .collect(); + self.exported[b] = !preds.is_empty() && preds.iter().all(|&q| self.exported_out(q)); + for (i, phi) in p.blocks[b].phis.iter().enumerate() { + let val = match phi.reg { + Reg::S(c) if c == EXEC || c == EXEC + 1 => Val::Missing("a lane mask"), + _ if self.bad.contains_key(&phi.value) => Val::Missing(self.bad[&phi.value]), + Reg::Scc => { + let v = self.s.m.phi(self.cur, self.s.t.i1); + self.data_phis.push((v, b, i)); + Val::Bit(v) + } + _ => { + let v = self.s.m.phi(self.cur, self.s.t.i32); + self.data_phis.push((v, b, i)); + Val::I32(v) + } + }; + self.vals.insert(phi.value, val); + } + if self.lds_meet.as_ref().is_some_and(|(_, meet)| meet[b].0) { + self.lds_meeting(); + } + let mut i = 0; + while i < p.blocks[b].insts.len() { + self.inst(b, i)?; + if let Some(end) = self.sections.get(&b).and_then(|s| s.get(&i)).map(|s| s.end) { + for j in i + 1..end { + self.section_inst(b, j, i); + } + i = end; + continue; + } + i += 1; + } + self.mask_ok = self.mask_data == MaskData::Console; + if self.lds_meet.as_ref().is_some_and(|(_, meet)| meet[b].1) { + self.lds_meeting(); + } + self.tail[b] = Some(self.cur); + self.exit(b)?; + } + self.fill_phis()?; + let user_data = self.user_reads.values().copied().collect(); + self.s.samplers = self.samplers.len() as u32; + let root_cbvs = self.s.root_cbvs.iter().map(|r| r.0).collect(); + let root_srvs = self.s.root_srvs.iter().map(|r| r.0).collect(); + let root_uavs = self.s.root_uavs.iter().map(|r| r.0).collect(); + let cmp_samplers = self.s.cmp_samplers; + let wave_size = self.s.wave_size; + Ok(Lowered { + wave_size, + cmp_samplers, + root_cbvs, + root_srvs, + root_uavs, + #[cfg(test)] + nonuniform_handles: self.s.nonuniform_handles, + #[cfg(test)] + wave_ops: self.s.flags & flags::WAVE_OPS != 0, + dxil: self.s.finish(), + user_data, + samplers: self.samplers, + }) + } + + fn exported_out(&self, b: usize) -> bool { + self.exported[b] || self.has_done_export(b) + } + + fn has_done_export(&self, b: usize) -> bool { + (0..self.x.p.blocks[b].insts.len()) + .any(|i| self.exports.get(&(b, i)).is_some_and(|e| e.done)) + } + + /// Values of the program's input registers. + fn inputs(&mut self) -> Result<(), Stop> { + let io_inputs: HashMap = self.x.io.inputs.iter().copied().collect(); + for &(reg, v) in &self.x.p.inputs { + let val = match reg { + Reg::S(_) if self.params.contains_key(&v) => continue, // loaded on first use + // Most programs only interpolate with them: loaded on first + // use as a value (`get`). + Reg::V(_) if matches!(io_inputs.get(&v), Some(Input::Barycentric { .. })) => { + continue; + } + Reg::S(n) => match io_inputs.get(&v) { + Some(&input) => self.input(input), + // Above the SGPRs the hardware initializes, a register + // holds what the last wave left, so no program depends + // on it: a read the paths only seem to allow (a branch + // past the write, taken only with one past the read) + // reads zero, as VGPRs do. + None if n <= 105 && self.x.io.initialized_sgprs.is_some_and(|k| n >= k) => { + Val::I32(self.s.m.i32(0)) + } + // A scalar parked in a VGPR lane (`ir::unspill`), read where the + // paths only seem to allow it before any save: the lane of a VGPR + // nobody wrote, and VGPRs nobody set read as zero. + None if n >= crate::ir::PARKED => Val::I32(self.s.m.i32(0)), + None => Val::Missing("a hardware SGPR input"), + }, + Reg::Scc => Val::Missing("SCC on entry"), + Reg::V(_) => match io_inputs.get(&v) { + Some(&input) => self.input(input), + // Registers no one set read as zero (the validator + // refuses reads of undef). + None => Val::I32(self.s.m.i32(0)), + }, + }; + self.vals.insert(v, val); + } + Ok(()) + } + + fn input(&mut self, input: Input) -> Val { + let (kind, col) = match input { + Input::VertexId => (1, 0), + Input::InstanceId => (2, 0), + Input::Position(c) => (3, c), + Input::Attribute { row, channel } => { + return match self.find_input(row, channel) { + Some((id, col)) => self.load_input(id, col), + None => Val::Missing("a vertex input the signature lacks"), + }; + } + Input::Barycentric { kind, index } => return self.barycentric(kind, index), + Input::PrimitiveId => return Val::Missing("the primitive id"), + // The console code tests it against 0 (`v_cmp_ne_u32`), as the + // host's value can be. + Input::FrontFace => (13, 0), + Input::ThreadIdInGroup(c) => return self.thread_id(c), + Input::GroupId(c) => return self.compute_id("groupId.i32", 94, c), + Input::GroupInfo => return Val::Missing("the thread-group info SGPR"), + Input::MeshGroup => { + let Val::I32(g) = self.compute_id("groupId.i32", 94, 0) else { + unreachable!() + }; + let n = self.s.m.i32(self.x.mesh_stride); + return Val::I32(self.s.m.bin(self.s.entry, Bin::Mul, g, n)); + } + Input::MergedWaveInfo => { + // shortcut: only the wave index (bits 24-27) is set; the + // console's other bits (lane counts) are read by no program. + let f = self.mesh_thread(); + let shift = self.s.m.i32(self.wave().trailing_zeros()); + let w = self.s.m.bin(self.s.entry, Bin::LShr, f, shift); + let k24 = self.s.m.i32(24); + return Val::I32(self.s.m.bin(self.s.entry, Bin::Shl, w, k24)); + } + _ => return Val::Missing("a pixel system input"), + }; + let free = self + .s + .inputs + .iter() + .filter_map(|e| e.row) + .map(|r| r + 1) + .max() + .unwrap_or(0); + let id = match self.s.inputs.iter().position(|e| e.kind == kind) { + Some(id) => { + if kind != 3 { + self.s.inputs[id].row.get_or_insert(free); + } + id + } + None if kind >= 3 => return Val::Missing("a pixel system input the signature lacks"), + None => { + // The console signature leaves out vertex and instance ids; PC + // gives them a row after the others. + let row = self + .s + .inputs + .iter() + .filter_map(|e| e.row) + .map(|r| r + 1) + .max() + .unwrap_or(0); + self.s.inputs.push(SigElement { + name: ["", "SV_VertexID", "SV_InstanceID"][kind as usize].into(), + index: 0, + kind, + comp: 5, + interp: 0, + row: Some(row), + col: 0, + cols: 1, + usage: 0, + half: false, + }); + self.s.inputs.len() - 1 + } + }; + self.load_input(id, col) + } + + /// A component of a compute thread or group id, read in the entry block. + fn compute_id(&mut self, name: &str, opcode: u32, c: u8) -> Val { + let (entry, c) = (self.s.entry, self.s.m.i32(u32::from(c))); + Val::I32( + self.s + .op(entry, name, Attr::ReadNone, self.s.t.i32, opcode, &[c]), + ) + } + + fn find_input(&self, row: u8, channel: u8) -> Option<(usize, u8)> { + self.s.inputs.iter().enumerate().find_map(|(id, e)| { + let r = e.row?; + // `then`, not `then_some`: the channel is only past `col` when + // the condition holds. + (r == u32::from(row) && channel >= e.col && channel < e.col + e.cols) + .then(|| (id, channel - e.col)) + }) + } + + fn load_input(&mut self, id: usize, col: u8) -> Val { + if self.s.inputs[id].half { + // shortcut: 16-bit vertex inputs (the fetch routine's) are not + // unpacked; pixel inputs are (`interp`). + return Val::Missing("a 16-bit input"); + } + self.load_any_input(id, col) + } + + /// An input element's channel as declared (16-bit ones as 32-bit floats). + fn load_any_input(&mut self, id: usize, col: u8) -> Val { + let e = &mut self.s.inputs[id]; + e.usage |= 1 << col; + let (int, bit) = (e.comp != 9, e.comp == 1); + let ty = if bit { + self.s.t.i1 + } else if int { + self.s.t.i32 + } else { + self.s.t.f32 + }; + let suffix = if bit { + ".i1" + } else if int { + ".i32" + } else { + ".f32" + }; + let entry = self.s.entry; + let args = [ + self.s.m.i32(id as u32), + self.s.m.i32(0), + self.s.m.i8(col), + self.s.m.undef(self.s.t.i32), + ]; + let v = self.s.op( + entry, + &format!("loadInput{suffix}"), + Attr::ReadNone, + ty, + 4, + &args, + ); + if bit { + let z = self.s.m.cast(entry, Cast::ZExt, v, self.s.t.i32); + Val::I32(z) + } else if int { + Val::I32(v) + } else { + Val::I32(self.s.m.cast(entry, Cast::Bitcast, v, self.s.t.i32)) + } + } + + /// The DXIL form of an IR value. + fn get(&mut self, v: Value) -> Result { + if self.phi_at.contains_key(&v) { + self.read_phis.insert(v); + } + let is_mask = self.x.st.masks.contains_key(&v) || self.x.st.highs.contains_key(&v); + match self.vals.get(&v) { + Some(&Val::Missing(_)) | None if self.mask_ok && is_mask => { + return self.mask_dword(v).map(Val::I32); + } + Some(&Val::Missing(w)) => return Err(w), + Some(&val) => return Ok(val), + None => {} + } + if let Some(&(param, dword)) = self.params.get(&v) { + let val = self.user(param, dword); + self.vals.insert(v, val); + return Ok(val); + } + if let Some(loaded) = self.lazy_barycentric(v) { + loaded?; + return Ok(self.vals[&v]); + } + Err("a value defined after its use") + } + + /// Loads `v` if it is a barycentric input VGPR not loaded yet (see + /// `inputs`): `None` if it is not one. + fn lazy_barycentric(&mut self, v: Value) -> Option> { + let (kind, index) = self.x.io.inputs.iter().find_map(|&(w, i)| match i { + Input::Barycentric { kind, index } if w == v => Some((kind, index)), + _ => None, + })?; + let val = self.barycentric(kind, index); + self.vals.insert(v, val); + Some(match val { + Val::Missing(w) => Err(w), + _ => Ok(()), + }) + } + + /// Barycentric `index` (0 i, 1 j) of `kind` as a value: a channel of + /// `SV_Barycentrics` declared with the same interpolation mode. + /// + /// GFX10 interpolates P0 + i (P1 - P0) + j (P2 - P0), so i and j are + /// the weights of vertices 1 and 2. The host's weights (x, y, z) are + /// those of vertices 0, 1 and 2, vertex 0 being the provoking vertex, + /// which is the console's P0 (`v_interp_mov` P0 is lowered to a flat + /// input): i is y and j is z. + /// shortcut: triangles only; on lines and points the console's i and j + /// are not checked against the host's weights. + fn barycentric(&mut self, kind: Barycentric, index: u8) -> Val { + let Some(mode) = interp_mode(kind) else { + return Val::Missing("pull-model barycentrics"); + }; + if index > 1 { + return Val::Missing("pull-model barycentrics"); + } + // One element per interpolation mode (the console's own, if its + // signature declares one): DXIL allows two. + let bary = |e: &SigElement| e.kind == 28; + let id = match self + .s + .inputs + .iter() + .position(|e| bary(e) && (e.interp == mode || e.usage == 0)) + { + Some(id) => id, + None => { + let index = self.s.inputs.iter().filter(|e| bary(e)).count() as u32; + if index >= 2 { + return Val::Missing("barycentrics of a third interpolation mode"); + } + // A system value the validator wants unpacked (packing + // location -1), like other non-packed system values. + self.s.inputs.push(SigElement { + name: "SV_Barycentrics".into(), + index, + kind: 28, + comp: 9, + interp: mode, + row: None, + col: 0, + cols: 3, + usage: 0, + half: false, + }); + self.s.inputs.len() - 1 + } + }; + let e = &mut self.s.inputs[id]; + if e.col != 0 || e.cols < 3 { + return Val::Missing("a console barycentrics element without i and j"); + } + e.row = None; + e.interp = mode; + self.s.flags |= flags::BARYCENTRICS; + self.load_any_input(id, index + 1) + } + + fn i32_of(&mut self, v: Value) -> Result { + match self.get(v)? { + Val::I32(x) => Ok(x), + Val::Bit(x) => Ok(self.s.m.cast(self.cur, Cast::ZExt, x, self.s.t.i32)), + Val::Missing(w) => Err(w), + } + } + + /// A user-data dword: a root parameter's value. + fn user(&mut self, param: usize, dword: u32) -> Val { + let rp = self.x.native.layout[param]; + match rp.root { + RootType::ResourceHeap | RootType::SamplerHeap => return Val::I32(self.s.m.i32(0)), + RootType::Constants | RootType::Table => {} + _ => return Val::Missing("a root descriptor"), + } + let index = u32::from(rp.user_data) + dword - self.user_first(); + self.user_reads.insert( + index, + UserData { + index, + slot: rp.slot, + root: rp.root, + dword, + }, + ); + Val::I32(self.user_at(index)) + } + + /// The user-data index that is dword 0 of the host's user data: 0, or + /// 16 for a program with a spilled user-data table, whose parameters + /// all sit at 16 and above. (The host's root signature has 64 dwords: + /// a builder stage with constants up to index 45, eight root views, + /// their biases and the memory directory would not fit with 16 dwords + /// nothing reads in front.) + fn user_first(&self) -> u32 { + if crate::spill::is_spilled(self.x.native) { + 16 + } else { + 0 + } + } + + /// A user-data dword no register of the console's holds: one the host + /// computes when it binds (`root` says what, an `Other` code of + /// `shader.rs`), placed after the layout's own dwords. + fn host_word(&mut self, root: RootType, slot: u8, dword: u32) -> V { + let known = self + .user_reads + .values() + .find(|u| u.root == root && u.slot == slot && u.dword == dword) + .map(|u| u.index); + let index = match known { + Some(index) => index, + None => { + let first = self.user_first(); + let layout = &self.x.native.layout; + let mut index = layout + .iter() + .map(|e| u32::from(e.user_data) + e.sgprs) + .max() + .unwrap_or(0) + .saturating_sub(first); + while self.user_reads.contains_key(&index) { + index += 1; + } + self.user_reads.insert( + index, + UserData { + index, + slot, + root, + dword, + }, + ); + index + } + }; + self.user_at(index) + } + + /// User-data dword `index`, loaded in the entry block. + fn user_at(&mut self, index: u32) -> V { + self.s.user_data = self.s.user_data.max(index + 1); + let h = match self.user_data { + Some(h) => h, + None => { + let h = self.s.user_data_handle(); + self.user_data = Some(h); + h + } + }; + let entry = self.s.entry; + let row = self.s.m.i32(index / 4); + let r = self.s.op( + entry, + "cbufferLoadLegacy.i32", + Attr::ReadOnly, + self.s.t.cbuf_ret, + 59, + &[h, row], + ); + self.s.m.extract(entry, r, index % 4) + } + + /// Whether some instruction computes with `v` (scalar or vector + /// arithmetic), rather than only naming it in a descriptor operand, + /// moving it (at most `depth` moves are followed) or comparing it: a + /// waterfall loop keeps a descriptor's dwords per lane, reads the first + /// lane's back and compares the lanes' with them. + fn computed_with(&self, v: Value, depth: u32) -> bool { + self.x.p.blocks.iter().flat_map(|b| &b.insts).any(|i| { + if !i.reads.iter().any(|r| r.1 == v) { + return false; + } + let name = i.name(); + let moves = matches!( + name, + "s_mov_b32" + | "s_mov_b64" + | "v_mov_b32" + | "v_readfirstlane_b32" + | "v_readlane_b32" + | "v_writelane_b32" + | "v_cndmask_b32" + ); + match &i.fields { + Fields::Sop { .. } | Fields::Valu(_) if moves => { + depth > 0 && i.writes.iter().any(|w| self.computed_with(w.1, depth - 1)) + } + Fields::Sop { .. } | Fields::Valu(_) => { + !(name.starts_with("v_cmp") || name.starts_with("s_cmp")) + } + _ => false, + } + }) + } + + /// The title address (low dword, bits from 32 up) of the buffer view + /// whose descriptor the scalar load at `site` reads from the start of + /// a table entry, as the host tells it when it binds (`shader.rs` + /// `USER_VIEW_ADDRESS`); none for anything else. (The console's + /// descriptor holds more in the second dword, the stride from bit 16 + /// up; code that takes the address masks those away.) + fn view_address(&mut self, site: Site) -> Option<(V, V)> { + use super::shader::USER_VIEW_ADDRESS; + let a = self.scalar.get(&site).copied()?; + let rp = *self.x.native.layout.get(a.param)?; + if rp.root != RootType::Table || a.dynamic.is_some() || a.offset % 32 != 0 { + return None; + } + let dword = a.offset / 4; + let used = self + .x + .native + .used + .iter() + .filter(|u| { + u.root == RootType::Table + && u.user_data == rp.user_data + && u.table_offset_dwords <= dword + }) + .max_by_key(|u| u.table_offset_dwords)?; + if used.dwords != 4 || !matches!(used.kind, ResourceType::Srv | ResourceType::Uav) { + return None; + } + let lo = self.host_word(RootType::Other(USER_VIEW_ADDRESS), rp.slot, dword); + let hi = self.host_word(RootType::Other(USER_VIEW_ADDRESS + 1), rp.slot, dword); + Some((lo, hi)) + } + + /// `lo`, `hi` plus the instruction's byte offset `off`, with the carry. + fn address_plus(&mut self, lo: V, hi: V, off: i32) -> (V, V) { + if off == 0 { + return (lo, hi); + } + let c = self.cur; + let i32t = self.s.t.i32; + let k = self.s.m.i32(off as u32); + let sum = self.s.m.bin(c, Bin::Add, lo, k); + // Up: a carry when the sum wrapped below `lo`. Down: a borrow when + // it wrapped above. + let wrapped = self + .s + .m + .cmp(c, if off > 0 { pred::IULT } else { pred::IUGT }, sum, lo); + let one = self.s.m.cast(c, Cast::ZExt, wrapped, i32t); + let hi = self.s.m.bin(c, if off > 0 { Bin::Add } else { Bin::Sub }, hi, one); + (sum, hi) + } + + /// Title memory at the 40-bit address `lo`, `hi` (`shader.rs` + /// `SLOT_MEMORY`): the handle of the raw view of the host copy holding + /// it and the byte in that view. A page without a copy reads zeros + /// (and drops writes) through the null view at the first slot, and its + /// number is left for the host, for lanes that run (`guard`). + fn memory(&mut self, lo: V, hi: V, guard: Option) -> (V, V) { + use super::shader::{MEMORY_FAULTS, MEMORY_PAGES, SLOT_FAULTS, SLOT_MEMORY, USER_MEMORY_BASE}; + let c = self.cur; + let (i32t, res) = (self.s.t.i32, self.s.t.res_ret); + let k = |l: &mut Self, v: u32| l.s.m.i32(v); + let (k16, k8) = (k(self, 16), k(self, 0xFF)); + let low = self.s.m.bin(c, Bin::LShr, lo, k16); + let high = self.s.m.bin(c, Bin::And, hi, k8); + let high = self.s.m.bin(c, Bin::Shl, high, k16); + let page = self.s.m.bin(c, Bin::Or, low, high); + // Inside the directory whatever the address (lanes that do not run + // compute one too); its last entry is never filled. + let last = k(self, MEMORY_PAGES - 1); + let page = self + .s + .op(c, "binary.i32", Attr::ReadNone, i32t, 40, &[page, last]); + self.s.m.tag(page, Tag::Clamp); + let k3 = k(self, 3); + let at = self.s.m.bin(c, Bin::Shl, page, k3); + let directory = self.s.root_srv_handle(SLOT_MEMORY); + let (iu, both, align) = (self.s.m.undef(i32t), self.s.m.i8(3), k(self, 4)); + let entry = self.s.op( + c, + "rawBufferLoad.f32", + Attr::ReadOnly, + res, + 139, + &[directory, at, iu, both, align], + ); + let (copy, start) = (self.s.m.extract(c, entry, 0), self.s.m.extract(c, entry, 1)); + let (copy, start) = (self.as_int(copy), self.as_int(start)); + // A page without a copy: its number, at a place by the number, or + // at the sink for lanes that do not run and pages that have one. + let zero = k(self, 0); + let mut missing = self.s.m.cmp(c, pred::EQ, copy, zero); + if let Some(g) = guard { + missing = self.s.m.bin(c, Bin::And, missing, g); + } + let places = k(self, MEMORY_FAULTS - 1); + let place = self.s.m.bin(c, Bin::URem, page, places); + let one = k(self, 1); + let place = self.s.m.bin(c, Bin::Add, place, one); + let k2 = k(self, 2); + let place = self.s.m.bin(c, Bin::Shl, place, k2); + let place = self.s.m.select(c, missing, place, zero); + let faults = self.s.root_uav_handle(SLOT_FAULTS); + let void = self.s.t.void; + let mask = self.s.m.i8(1); + self.s.op( + c, + "rawBufferStore.i32", + Attr::NoUnwind, + void, + 140, + &[faults, place, iu, page, iu, iu, iu, mask, align], + ); + let base = self.host_word(RootType::Other(USER_MEMORY_BASE), 0, 0); + let slot = self.s.m.bin(c, Bin::Add, base, copy); + let h = self.s.heap_handle(c, slot, false, true, (11 | 0x1000, 0)); + let k64k = k(self, 0xFFFF); + let within = self.s.m.bin(c, Bin::And, lo, k64k); + let byte = self.s.m.bin(c, Bin::Add, start, within); + (h, byte) + } + + /// `global_load_*`, `global_store_*` and `global_atomic_*` on title + /// memory by address (`resource::MEMORY`): the address is the VGPR + /// pair, each lane its own. + fn memory_flat(&mut self, inst: &Inst, b: usize, i: usize) -> Result<(), Why> { + let Fields::Flat { + dst, + addr, + data, + saddr, + offset, + lds, + cache, + } = &inst.fields + else { + unreachable!() + }; + if *lds || !matches!(saddr, None | Some(Operand::Scalar { code: NULL, .. })) { + return Err("a global address with a scalar base"); + } + let Some(Operand::Vector { reg: areg, .. }) = *addr else { + return Err("a global address not in VGPRs"); + }; + let word = |l: &mut Self, k: u8| -> Result { + let v = inst.read(Reg::V(areg + k)).ok_or("a global address")?; + l.i32_of(v) + }; + let (lo, hi) = (word(self, 0)?, word(self, 1)?); + let (lo, hi) = self.address_plus(lo, hi, i32::from(*offset)); + let guard = self.guard(b, i)?; + let c = self.cur; + let (i32t, res, void) = (self.s.t.i32, self.s.t.res_ret, self.s.t.void); + let iu = self.s.m.undef(i32t); + let align = self.s.m.i32(4); + let name = inst.name(); + let count = |rest: &str| match rest { + "dword" => Ok(1u8), + "dwordx2" => Ok(2), + "dwordx3" => Ok(3), + "dwordx4" => Ok(4), + _ => Err(name), + }; + if let Some(rest) = name.strip_prefix("global_load_") { + let n = count(rest)?; + let Some(Operand::Vector { reg, .. }) = *dst else { + return Err("a global load result"); + }; + let (h, byte) = self.memory(lo, hi, guard); + let mask = self.s.m.i8((1u8 << n) - 1); + let r = self.s.op( + c, + "rawBufferLoad.f32", + Attr::ReadOnly, + res, + 139, + &[h, byte, iu, mask, align], + ); + for k in 0..n { + let x = self.s.m.extract(c, r, u32::from(k)); + let x = self.as_int(x); + self.write(inst, Reg::V(reg + k), x, guard); + } + return Ok(()); + } + if let Some(rest) = name.strip_prefix("global_store_") { + let n = count(rest)?; + let d = data.as_ref().ok_or("global store data")?; + let vals = self.vgprs(inst, d, n)?; + let (h, byte) = self.memory(lo, hi, guard); + let mut args = vec![h, byte, iu]; + args.extend(&vals); + args.resize(3 + 4, iu); + args.push(self.s.m.i8((1u8 << n) - 1)); + args.push(align); + let at = self.begin_guarded(guard); + self.s + .op(self.cur, "rawBufferStore.i32", Attr::NoUnwind, void, 140, &args); + self.end_guarded(at, &[]); + return Ok(()); + } + let Some(op) = name.strip_prefix("global_atomic_") else { + return Err(name); + }; + let d = data.as_ref().ok_or("global atomic data")?; + let v = self.vgprs(inst, d, 1)?[0]; + // With `glc` the value from before comes back, in the result + // register the instruction names. + let back = match (*dst, cache.glc) { + (Some(Operand::Vector { reg, .. }), true) => Some(reg), + _ => None, + }; + let old = match back.and_then(|reg| inst.read(Reg::V(reg))) { + Some(x) => self.i32_of(x)?, + None => self.s.m.i32(0), + }; + let (h, byte) = self.memory(lo, hi, guard); + // DXIL's atomic operations: add 0, and 1, or 2, xor 3, signed + // minimum 4 and maximum 5, unsigned 6 and 7, exchange 8. + let simple = match op { + "add" => Some((0, v)), + "sub" => { + let zero = self.s.m.i32(0); + Some((0, self.s.m.bin(c, Bin::Sub, zero, v))) + } + "and" => Some((1, v)), + "or" => Some((2, v)), + "xor" => Some((3, v)), + "smin" => Some((4, v)), + "smax" => Some((5, v)), + "umin" => Some((6, v)), + "umax" => Some((7, v)), + "swap" => Some((8, v)), + "fmin" | "fmax" => None, + _ => return Err(name), + }; + let at = self.begin_guarded(guard); + let was = match simple { + Some((code, x)) => { + let code = self.s.m.i32(code); + self.s.op( + self.cur, + "atomicBinOp.i32", + Attr::NoUnwind, + i32t, + 78, + &[h, code, byte, iu, iu, x], + ) + } + None => { + // A float minimum or maximum has no atomic operation on + // the host: the dword is exchanged for the smaller (larger) + // of itself and the value until no other thread got in + // between. Each failed pass means another one's succeeded; + // the limit only keeps a broken card from hanging. + let head = self.cur; + let mask = self.s.m.i8(1); + let first = self.s.op( + head, + "rawBufferLoad.f32", + Attr::ReadOnly, + res, + 139, + &[h, byte, iu, mask, align], + ); + let first = self.s.m.extract(head, first, 0); + let first = self.as_int(first); + let (pass, done) = (self.s.m.new_block(), self.s.m.new_block()); + self.s.m.terminate(head, Term::Br(pass)); + self.cur = pass; + let seen = self.s.m.phi(pass, i32t); + let n = self.s.m.phi(pass, i32t); + let (f32t, fv) = (self.s.t.f32, self.as_float(v)); + let fseen = self.as_float(seen); + // `dx.op.binary`: FMax 35, FMin 36. + let pick = if op == "fmin" { 36 } else { 35 }; + let wanted = self + .s + .op(pass, "binary.f32", Attr::ReadNone, f32t, pick, &[fseen, fv]); + let wanted = self.as_int(wanted); + let found = self.s.op( + pass, + "atomicCompareExchange.i32", + Attr::NoUnwind, + i32t, + 79, + &[h, byte, iu, iu, seen, wanted], + ); + let one = self.s.m.i32(1); + let n1 = self.s.m.bin(pass, Bin::Add, n, one); + let lost = self.s.m.cmp(pass, pred::NE, found, seen); + let limit = self.s.m.i32(1 << 16); + let more = self.s.m.cmp(pass, pred::IULT, n1, limit); + let again = self.s.m.bin(pass, Bin::And, lost, more); + self.s.m.terminate(pass, Term::CondBr(again, pass, done)); + let zero = self.s.m.i32(0); + self.s.m.set_phi(seen, vec![(first, head), (found, pass)]); + self.s.m.set_phi(n, vec![(zero, head), (n1, pass)]); + self.cur = done; + found + } + }; + let was = self.end_guarded(at, &[(was, old)])[0]; + if let Some(reg) = back { + self.write(inst, Reg::V(reg), was, None); + } + Ok(()) + } + + /// `s_load_dword*` from title memory by address (`resource::MEMORY`): + /// the SGPR pair plus the instruction's offsets. + fn memory_smem(&mut self, inst: &Inst) -> Result<(), Why> { + let Fields::Smem { + data: Some(Operand::Scalar { code, .. }), + base: Operand::Scalar { code: base, .. }, + offset, + soffset, + .. + } = inst.fields + else { + return Err("a scalar load from memory"); + }; + let count = match inst.name().strip_prefix("s_load_dword") { + Some("") => 1u8, + Some("x2") => 2, + Some("x4") => 4, + Some("x8") => 8, + Some("x16") => 16, + _ => return Err("a scalar memory access by address"), + }; + let word = |l: &mut Self, k: u8| -> Result { + let v = inst.read(Reg::S(base + k)).ok_or("an address not in SGPRs")?; + l.i32_of(v) + }; + let (mut lo, mut hi) = (word(self, 0)?, word(self, 1)?); + let c = self.cur; + let (i32t, res) = (self.s.t.i32, self.s.t.res_ret); + if !matches!(soffset, Operand::Scalar { code: NULL, .. }) { + // An offset register counts up from the address. + let so = self.operand(inst, &soffset)?; + let sum = self.s.m.bin(c, Bin::Add, lo, so); + let carry = self.s.m.cmp(c, pred::IULT, sum, lo); + let carry = self.s.m.cast(c, Cast::ZExt, carry, i32t); + hi = self.s.m.bin(c, Bin::Add, hi, carry); + lo = sum; + } + let (iu, align) = (self.s.m.undef(i32t), self.s.m.i32(4)); + for first in (0..count).step_by(4) { + let n = (count - first).min(4); + let (lo, hi) = self.address_plus(lo, hi, offset + 4 * i32::from(first)); + let (h, byte) = self.memory(lo, hi, None); + let mask = self.s.m.i8((1u8 << n) - 1); + let r = self.s.op( + c, + "rawBufferLoad.f32", + Attr::ReadOnly, + res, + 139, + &[h, byte, iu, mask, align], + ); + for k in 0..n { + let x = self.s.m.extract(c, r, u32::from(k)); + let x = self.as_int(x); + self.write(inst, Reg::S(code + first + k), x, None); + } + } + Ok(()) + } + + /// A dword of a lane mask as a number: the ballot of the lanes' bits, + /// taken in the block that writes the mask (see [`MaskData`]). + fn mask_dword(&mut self, v: Value) -> Result { + let (lo, high) = match self.x.st.highs.get(&v) { + Some(&lo) => (lo, true), + None => (v, false), + }; + let &m = self.x.st.masks.get(&lo).ok_or(LANE_MASK)?; + // A mask that holds lanes outside EXEC where it is written (the complement of one, + // say) is the ballot of the lanes that are there: all of them, where two exchanging + // host waves know every lane runs that block. + let made = self.def_block.get(&lo).copied(); + let whole = self.exchange.is_some() && !self.local && made.is_none_or(|b| self.all_lanes(b)); + if !self.x.st.active.contains(&lo) && !whole { + if self.exchange.is_some() && !self.local { + need(made.unwrap_or(0)); + } + return Err(MASK_ELSEWHERE); + } + let (x, y) = match self.ballots.get(&lo) { + Some(&xy) => xy, + None => { + let at = match self.def_block.get(&lo) { + // Program inputs (EXEC on entry). + None => self.s.entry, + Some(&b) if b == self.cur_ir => self.cur, + Some(&b) => self.tail[b].ok_or("a lane mask written after its use")?, + }; + if !self.balloting.insert(lo) { + return Err("a lane mask whose lanes depend on its own value"); + } + let bit = self.boolean(m, at); + self.balloting.remove(&lo); + let bit = bit?; + let i32t = self.s.t.i32; + let four = self.s.m.named_struct("dx.types.fouri32", vec![i32t; 4]); + let r = self + .s + .op(at, "waveActiveBallot", Attr::NoUnwind, four, 116, &[bit]); + self.s.flags |= flags::WAVE_OPS; + let mut xy = (self.s.m.extract(at, r, 0), self.s.m.extract(at, r, 1)); + if self.exchange.is_some() { + // a host wave's ballot is its half's 32 bits: the halves exchange them + let b = self.def_block.get(&lo).copied(); + if self.local { + if !self.local_ok && !self.local_any { + return Err("a lane mask read as data in a half-wave"); + } + } else if !self.exchange.as_ref().is_some_and(|e| e.1) && !b.is_none_or(|b| self.all_lanes(b)) { + // (a group of 32 or fewer has no other half to exchange with) + need(b.unwrap_or(0)); + return Err("a lane mask exchanged where not every lane runs"); + } + xy = self.exchange_halves(at, xy.0); + } + self.ballots.insert(lo, xy); + xy + } + }; + Ok(if high { y } else { x }) + } + + // ---- operands ---- + + fn operand(&mut self, inst: &Inst, op: &Operand) -> Result { + match *op { + Operand::Scalar { code: NULL, .. } => Ok(self.s.m.i32(0)), + Operand::Scalar { code, .. } => { + let v = inst.read(Reg::S(code)).ok_or("an unread operand")?; + self.i32_of(v) + } + Operand::Vector { reg, .. } => { + let v = inst.read(Reg::V(reg)).ok_or("an unread operand")?; + self.i32_of(v) + } + Operand::Const(c) => crate::resource::inline(c) + .map(|x| self.s.m.i32(x)) + .ok_or("a special operand (vccz, execz, scc, lds_direct)"), + Operand::Literal(x) => Ok(self.s.m.i32(x)), + Operand::Attr { .. } => Err("an attribute operand"), + } + } + + /// An operand read as f16 data: GFX10 puts an inline f16 constant in + /// the low half of the operand (upstream PR #637, checked there against + /// the instruction encodings; the half-and-half reading taken from PR + /// #458 gave the high half the constant too). + fn f16_operand(&mut self, inst: &Inst, op: &Operand) -> Result { + match *op { + Operand::Const(c @ 240..=248) => Ok(self.s.m.i32(inline_f16(c))), + _ => self.operand(inst, op), + } + } + + fn as_float(&mut self, x: V) -> V { + self.s.m.cast(self.cur, Cast::Bitcast, x, self.s.t.f32) + } + + fn as_int(&mut self, f: V) -> V { + self.s.m.cast(self.cur, Cast::Bitcast, f, self.s.t.i32) + } + + /// The SDWA operand selection of source `k`: a byte or word of the + /// dword, zero- or sign-extended (none: the whole dword). + fn sdwa_src(inst: &Inst, k: usize) -> Option<(u8, bool)> { + let Fields::Valu(v) = &inst.fields else { + return None; + }; + let s = v.sdwa?; + let sel = *s.src_sel.get(k)?; + let sext = s.sext >> k & 1 != 0; + (sel < 6).then_some((sel, sext)) + } + + /// Bits `sel` (0-3 a byte, 4-5 a word) of `x`, extended. + fn select_bits(&mut self, x: V, sel: u8, sext: bool) -> V { + let c = self.cur; + let (width, at) = if sel < 4 { + (8, 8 * sel) + } else { + (16, 16 * (sel - 4)) + }; + let left = self.s.m.i32(u32::from(32 - width - at)); + let t = self.s.m.bin(c, Bin::Shl, x, left); + let right = self.s.m.i32(32 - u32::from(width)); + let op = if sext { Bin::AShr } else { Bin::LShr }; + self.s.m.bin(c, op, t, right) + } + + /// A float source with its abs/neg modifiers. + fn fsrc(&mut self, inst: &Inst, k: usize) -> Result { + let Fields::Valu(v) = &inst.fields else { + unreachable!() + }; + let op = *v.src.get(k).ok_or("a missing operand")?; + let selected = Self::sdwa_src(inst, k); + let mut f = match op { + _ if selected.is_some() => { + let (sel, sext) = selected.expect("checked"); + let x = self.operand(inst, &op)?; + let x = self.select_bits(x, sel, sext); + self.as_float(x) + } + _ if k == 0 && self.src0.is_some() => { + let x = self.src0.expect("checked"); + self.as_float(x) + } + Operand::Vector { reg, .. } | Operand::Scalar { code: reg, .. } + if !matches!(op, Operand::Scalar { code: NULL, .. }) => + { + let r = if matches!(op, Operand::Vector { .. }) { + Reg::V(reg) + } else { + Reg::S(reg) + }; + let val = inst.read(r).ok_or("an unread operand")?; + match self.floats.get(&val) { + Some(&f) => f, + None => { + let x = self.i32_of(val)?; + self.as_float(x) + } + } + } + _ => { + let x = self.operand(inst, &op)?; + self.as_float(x) + } + }; + if v.abs >> k & 1 != 0 { + f = self.unary(6, f); + } + if v.neg >> k & 1 != 0 { + let z = self.s.m.f32(0x8000_0000); + f = self.s.m.bin(self.cur, Bin::Sub, z, f); + } + Ok(f) + } + + fn src(&mut self, inst: &Inst, k: usize) -> Result { + let Fields::Valu(v) = &inst.fields else { + unreachable!() + }; + let op = *v.src.get(k).ok_or("a missing operand")?; + if v.abs >> k & 1 != 0 || v.neg >> k & 1 != 0 { + return Err("integer operand modifiers"); + } + match self.src0 { + Some(x) if k == 0 => Ok(x), + _ => { + let x = self.operand(inst, &op)?; + Ok(match Self::sdwa_src(inst, k) { + Some((sel, sext)) => self.select_bits(x, sel, sext), + None => x, + }) + } + } + } + + fn unary(&mut self, op: u32, f: V) -> V { + self.s.op( + self.cur, + "unary.f32", + Attr::ReadNone, + self.s.t.f32, + op, + &[f], + ) + } + + fn binary(&mut self, op: u32, a: V, b: V) -> V { + self.s.op( + self.cur, + "binary.f32", + Attr::ReadNone, + self.s.t.f32, + op, + &[a, b], + ) + } + + /// The hardware's maximum (`max`) or minimum of two floats: as DXIL's + /// FMax/FMin, but -0 orders below +0 (RDNA2 ISA, `v_max_f32`), where + /// the compare and select DXIL specifies gives either zero. + fn max_min(&mut self, max: bool, a: V, b: V) -> V { + let c = self.cur; + let r = self.binary(if max { 35 } else { 36 }, a, b); + let (ia, ib) = (self.as_int(a), self.as_int(b)); + let either = self.s.m.bin(c, Bin::Or, ia, ib); + let magnitude = self.s.m.i32(0x7FFF_FFFF); + let either = self.s.m.bin(c, Bin::And, either, magnitude); + let zero = self.s.m.i32(0); + let zeros = self.s.m.cmp(c, pred::EQ, either, zero); + // Of two zeros, +0 unless both are -0 (max), -0 unless neither (min). + let op = if max { Bin::And } else { Bin::Or }; + let sign = self.s.m.bin(c, op, ia, ib); + let signed = self.as_float(sign); + self.s.m.select(c, zeros, signed, r) + } + + fn fmad(&mut self, a: V, b: V, c: V) -> V { + self.s.op( + self.cur, + "tertiary.f32", + Attr::ReadNone, + self.s.t.f32, + 46, + &[a, b, c], + ) + } + + /// `f` as an f16 in the low bits, rounded toward zero: the nearest-even + /// conversion, one step back toward zero where it rounded away (which + /// also turns an overflow to infinity into the largest finite half). + fn f16_toward_zero(&mut self, f: V) -> V { + let c = self.cur; + let i32t = self.s.t.i32; + let h = self + .s + .op(c, "legacyF32ToF16", Attr::ReadNone, i32t, 130, &[f]); + let back = self + .s + .op(c, "legacyF16ToF32", Attr::ReadNone, self.s.t.f32, 131, &[h]); + let (fa, ba) = (self.unary(6, f), self.unary(6, back)); + // Ordered: never for NaN. + let away = self.s.m.cmp(c, pred::OGT, ba, fa); + let one = self.s.m.i32(1); + let stepped = self.s.m.bin(c, Bin::Sub, h, one); + self.s.m.select(c, away, stepped, h) + } + + /// `f` as an f16 in the low bits, rounded to nearest, ties to even, as the console's + /// 16-bit float operations round, whatever the host's own conversion does: D3D lets + /// `f32tof16` round toward zero, and the NVIDIA driver's does (measured on an RTX 4070: + /// `wave64_tests`). The conversion toward zero, or the next half away from zero where + /// that one is nearer, or as near and the first one odd. Past the largest half the next + /// one counts as 2^16, the bound IEEE rounds by, so 65520 and up become infinity. + /// (`f` is an f32 result of two halves here; rounding it again to 16 bits gives the + /// rounding of the exact result, 24 bits being more than twice 11 and two.) + fn f16_nearest(&mut self, f: V) -> V { + let c = self.cur; + let f32t = self.s.t.f32; + let lo = self.f16_toward_zero(f); + let (one, zero) = (self.s.m.i32(1), self.s.m.i32(0)); + let hi = self.s.m.bin(c, Bin::Add, lo, one); + let size = |l: &mut Self, h: V| { + let w = l.s.op(c, "legacyF16ToF32", Attr::ReadNone, f32t, 131, &[h]); + l.unary(6, w) + }; + let (below, above) = (size(self, lo), size(self, hi)); + let (magnitude, infinity) = (self.s.m.i32(0x7FFF), self.s.m.i32(0x7C00)); + let m = self.s.m.bin(c, Bin::And, hi, magnitude); + let top = self.s.m.cmp(c, pred::EQ, m, infinity); + let bound = self.s.m.f32(65536.0f32.to_bits()); + let above = self.s.m.select(c, top, bound, above); + let fa = self.unary(6, f); + // (both differences are exact: the three values lie within one half's step) + let under = self.s.m.bin(c, Bin::Sub, fa, below); + let over = self.s.m.bin(c, Bin::Sub, above, fa); + // Ordered: never for NaN, which stays what the conversion made of it. + let nearer = self.s.m.cmp(c, pred::OLT, over, under); + let tie = self.s.m.cmp(c, pred::OEQ, over, under); + let odd = self.s.m.bin(c, Bin::And, lo, one); + let odd = self.s.m.cmp(c, pred::NE, odd, zero); + let tie = self.s.m.bin(c, Bin::And, tie, odd); + let up = self.s.m.bin(c, Bin::Or, nearer, tie); + self.s.m.select(c, up, hi, lo) + } + + /// `(a >> off[4:0]) & ((1 << width) - 1)`, sign-extended from the field's + /// top bit when `signed`; widths from 32 on take every bit. A signed + /// field that runs past bit 31 extends from bit 31, as the hardware + /// does: the shift is arithmetic then. + fn bfe(&mut self, a: V, off: V, width: V, signed: bool) -> V { + let c = self.cur; + let (k31, k32, zero, one, ones) = ( + self.s.m.i32(31), + self.s.m.i32(32), + self.s.m.i32(0), + self.s.m.i32(1), + self.s.m.i32(u32::MAX), + ); + let off = self.s.m.bin(c, Bin::And, off, k31); + let shift = if signed { Bin::AShr } else { Bin::LShr }; + let shifted = self.s.m.bin(c, shift, a, off); + let full = self.s.m.cmp(c, pred::IUGE, width, k32); + let w = self.s.m.bin(c, Bin::And, width, k31); + let mask = self.s.m.bin(c, Bin::Shl, one, w); + let mask = self.s.m.bin(c, Bin::Sub, mask, one); + let mask = self.s.m.select(c, full, ones, mask); + let r = self.s.m.bin(c, Bin::And, shifted, mask); + if !signed { + return r; + } + // Sign-extend a field narrower than 32 bits (none for width 0). + let left = self.s.m.bin(c, Bin::Sub, k32, w); + let left = self.s.m.bin(c, Bin::And, left, k31); + let t = self.s.m.bin(c, Bin::Shl, r, left); + let t = self.s.m.bin(c, Bin::AShr, t, left); + let is0 = self.s.m.cmp(c, pred::EQ, w, zero); + let keep = self.s.m.bin(c, Bin::Or, full, is0); + self.s.m.select(c, keep, r, t) + } + + /// Whether an f32 value is NaN, tested in integer arithmetic so host + /// drivers (such as NVIDIA) do not fold `fcmp uno` away under fast-math. + fn is_nan_f32(&mut self, f: V) -> V { + let c = self.cur; + let bits = self.as_int(f); + let mask = self.s.m.i32(0x7FFF_FFFF); + let abs = self.s.m.bin(c, Bin::And, bits, mask); + let inf = self.s.m.i32(0x7F80_0000); + self.s.m.cmp(c, pred::IUGT, abs, inf) + } + + /// The median of three. With a NaN among them the hardware gives the + /// minimum of the three instead (the host's minimum skips NaNs, so that + /// is the smallest number among them). + fn med3(&mut self, a: V, b: V, third: V) -> V { + let c = self.cur; + let lo = self.binary(36, a, b); + let hi = self.binary(35, a, b); + let t = self.binary(36, hi, third); + let median = self.binary(35, lo, t); + let least = self.binary(36, lo, third); + let nan_a = self.is_nan_f32(a); + let nan_b = self.is_nan_f32(b); + let nan_3 = self.is_nan_f32(third); + let nan_ab = self.s.m.bin(c, Bin::Or, nan_a, nan_b); + let nan = self.s.m.bin(c, Bin::Or, nan_ab, nan_3); + self.s.m.select(c, nan, least, median) + } + + /// `a - floor(a)`, which on the hardware never reaches 1.0: where it + /// would round to it (a tiny negative `a`), the result is `below_one`, + /// the largest value under 1.0 in the operation's width. Hosts differ + /// here (some give 1.0). Comparing against a `threshold` distinct from + /// `below_one` prevents drivers (observed on NVIDIA) from folding + /// `r > k ? k : r` into `minNum` (`FMNMX`) and swallowing NaN. + fn fract(&mut self, a: V, threshold: f32, below_one: f32) -> V { + let c = self.cur; + let r = self.unary(22, a); + let limit = self.s.m.f32(threshold.to_bits()); + let k = self.s.m.f32(below_one.to_bits()); + let over = self.s.m.cmp(c, pred::OGE, r, limit); + self.s.m.select(c, over, k, r) + } + + /// Sine, or cosine, of an angle in turns, as the hardware takes it. The + /// whole turns are taken off first (`x - round_even(x)`, exact, within + /// half a turn), so a large angle keeps its fraction; scaling to radians + /// first rounds it away. A zero passes unreduced (the sine of -0 is -0). + /// The sine of a half turn and the cosine of a quarter turn are exactly + /// +0 on the hardware, where the host's function of the rounded angle + /// gives about 1e-7. Infinities and NaN give NaN. + /// shortcut: below 2^-12 turns the hardware scales by a slightly + /// different constant than 2π (a last-place difference). + fn trig_turns(&mut self, x: V, cosine: bool) -> V { + let c = self.cur; + let zero = self.s.m.f32(0); + let whole = self.unary(26, x); + let part = self.s.m.bin(c, Bin::Sub, x, whole); + let is_zero = self.s.m.cmp(c, pred::OEQ, x, zero); + let part = self.s.m.select(c, is_zero, x, part); + let k = self.s.m.f32(TWO_PI.to_bits()); + let angle = self.s.m.bin(c, Bin::Mul, part, k); + let r = self.unary(if cosine { 12 } else { 13 }, angle); + let at = if cosine { 0.25f32 } else { 0.5 }; + let at = self.s.m.f32(at.to_bits()); + let size = self.unary(6, part); + let exact = self.s.m.cmp(c, pred::OEQ, size, at); + self.s.m.select(c, exact, zero, r) + } + + /// The high dword of a 32 × 32-bit product. + fn mul_hi(&mut self, a: V, b: V, signed: bool) -> V { + let c = self.cur; + let i64t = self.s.m.int(64); + let ext = if signed { Cast::SExt } else { Cast::ZExt }; + let a = self.s.m.cast(c, ext, a, i64t); + let b = self.s.m.cast(c, ext, b, i64t); + let m = self.s.m.bin(c, Bin::Mul, a, b); + let k32 = self.s.m.int_const(i64t, 32); + let hi = self.s.m.bin(c, Bin::LShr, m, k32); + self.s.flags |= flags::INT64; + self.s.m.cast(c, Cast::Trunc, hi, self.s.t.i32) + } + + /// `0 × anything = 0`, as in D3D9. + fn legacy_mul(&mut self, a: V, b: V) -> V { + let c = self.cur; + let m = self.s.m.bin(c, Bin::Mul, a, b); + let zero = self.s.m.f32(0); + let az = self.s.m.cmp(c, pred::OEQ, a, zero); + let bz = self.s.m.cmp(c, pred::OEQ, b, zero); + let z = self.s.m.bin(c, Bin::Or, az, bz); + self.s.m.select(c, z, zero, m) + } + + // ---- lane booleans ---- + + fn boolean(&mut self, b: Bool, at: usize) -> Result { + if b == Bool::TRUE || b == Bool::FALSE { + return Ok(self.s.m.bool(b == Bool::TRUE)); + } + if let Some(&v) = self.bools.get(&(at, b)) { + return Ok(v); + } + let (atom, lo, hi) = self.x.st.bools.node(b).expect("not a constant"); + let a = self.atom(atom, at)?; + let m = &mut self.s.m; + let v = match (lo, hi) { + (Bool::FALSE, Bool::TRUE) => a, + (Bool::TRUE, Bool::FALSE) => { + let t = m.bool(true); + m.bin(at, Bin::Xor, a, t) + } + (Bool::FALSE, h) => { + let h = self.boolean(h, at)?; + self.s.m.bin(at, Bin::And, a, h) + } + (l, Bool::TRUE) => { + let l = self.boolean(l, at)?; + self.s.m.bin(at, Bin::Or, a, l) + } + (l, h) => { + let l = self.boolean(l, at)?; + let h = self.boolean(h, at)?; + self.s.m.select(at, a, h, l) + } + }; + self.bools.insert((at, b), v); + Ok(v) + } + + fn atom(&mut self, atom: Atom, at: usize) -> Result { + match atom { + Atom::Lane(v) => self.lane_bits.get(&v).copied().ok_or_else(|| { + self.lane_fail + .get(&v) + .copied() + .unwrap_or("a lane mask from a carry") + }), + Atom::Uniform(v) => match self.get(v)? { + Val::Bit(x) => Ok(x), + Val::I32(x) => { + let z = self.s.m.i32(0); + Ok(self.s.m.cmp(at, pred::NE, x, z)) + } + Val::Missing(w) => Err(w), + }, + Atom::Phi(id) => { + if let Some(&v) = self.mask_phis.get(&id) { + return Ok(v); + } + let &(b, i) = self + .phi_at + .get(&id) + .ok_or("a lane-mask join without a phi")?; + let blk = self.block[b].ok_or("an unreachable join")?; + let v = self.s.m.phi(blk, self.s.t.i1); + self.mask_phis.insert(id, v); + self.pending_masks.push((v, b, i)); + Ok(v) + } + // shortcut: "some lane of the quad is set" is taken as true: the + // lanes it adds only feed derivatives, and exports keep their own + // masks. Wrong if such a section had a side effect. + Atom::Quad(_) => Ok(self.s.m.bool(true)), + // With console lanes, a mask held as a number is the console's: + // the lane tests its own bit. + Atom::Opaque(v) if self.console_lanes => { + let hi = match self.pair_high(v) { + Some(h) => Some(self.get(h)?), + None => None, + }; + let lo = self.get(v)?; + let word = |w: Val| match w { + Val::I32(x) => Ok(x), + _ => Err("an opaque lane mask"), + }; + let lo = word(lo)?; + let hi = hi.map(word).transpose()?; + Ok(self.lane_bit(at, lo, hi)) + } + Atom::Constant(k) if self.console_lanes => { + let lo = self.s.m.i32(k as u32); + let hi = self.s.m.i32((k >> 32) as u32); + Ok(self.lane_bit(at, lo, Some(hi))) + } + Atom::Opaque(_) => Err("an opaque lane mask"), + Atom::Constant(_) => Err("a constant lane mask"), + } + } + + /// A console wave64 program in host waves of 32: the first console thread of this host wave + /// (0, 32, 64, ...). A GPU need not give a host wave consecutive thread indices (NVIDIA's + /// 8 x 8 groups), so each wave takes the next 32 from an LDS counter instead: every thread + /// zeroes it, the group meets, each wave's first lane adds 32 and the wave takes what it + /// found. Branch-free, in the entry block, which every thread runs. + fn wave_base(&mut self) -> Option { + let slot = self.halves?; + if let Some(v) = self.wave_base { + return Some(v); + } + let (e, i32t) = (self.s.entry, self.s.t.i32); + let lds = self.s.lds(); + let k = self.s.m.i32(slot); + let ptr = self.s.m.element(e, lds, k); + let zero = self.s.m.i32(0); + self.s.m.store(e, ptr, zero); + self.group_sync(e); + let lane = self.s.op(e, "waveGetLaneIndex", Attr::ReadOnly, i32t, 111, &[]); + let first = self.s.m.cmp(e, pred::EQ, lane, zero); + let k32 = self.s.m.i32(32); + let add = self.s.m.select(e, first, k32, zero); + let ptr = self.s.m.element(e, lds, k); + let old = self.s.m.atomic(e, Rmw::Add, ptr, add); + let base = self.s.op(e, "waveReadLaneFirst.i32", Attr::NoUnwind, i32t, 118, &[old]); + self.s.flags |= flags::WAVE_OPS; + self.wave_base = Some(base); + Some(base) + } + + /// The console thread index of this thread in the group: `wave_base` plus the host lane + /// (host waves of 32), else the wave's first thread index rounded down plus the lane. + fn console_thread(&mut self) -> V { + let (e, i32t) = (self.s.entry, self.s.t.i32); + let lane = self.s.op(e, "waveGetLaneIndex", Attr::ReadOnly, i32t, 111, &[]); + if let Some(base) = self.wave_base() { + return self.s.m.bin(e, Bin::Add, base, lane); + } + let flat = self.s.op(e, "flattenedThreadIdInGroup.i32", Attr::ReadNone, i32t, 96, &[]); + let first = self.s.op(e, "waveReadLaneFirst.i32", Attr::NoUnwind, i32t, 118, &[flat]); + let wave = self.s.wave_size.unwrap_or(32); + let mask = self.s.m.i32(!(wave - 1)); + let base = self.s.m.bin(e, Bin::And, first, mask); + self.s.m.bin(e, Bin::Add, base, lane) + } + + /// This thread's console lane (0..63): its relabelled thread index (`thread_id`), whose host + /// wave holds a 32-aligned run of console lanes. Without `exchange`: the host lane. + fn console_lane(&mut self) -> V { + if self.exchange.is_none() { + return self.lane_index(); + } + if let Some(v) = self.clane { + return v; + } + let (e, i32t) = (self.s.entry, self.s.t.i32); + let f = self.console_thread(); + let _ = i32t; + let k63 = self.s.m.i32(63); + let cl = self.s.m.bin(e, Bin::And, f, k63); + self.s.flags |= flags::WAVE_OPS; + self.clane = Some(cl); + cl + } + + /// A group barrier with an LDS fence in `block`. + fn group_sync(&mut self, block: usize) { + let mode = self.s.m.i32(meeting_mode()); + let void = self.s.t.void; + self.s.op(block, "barrier", Attr::NoDuplicate, void, 80, &[mode]); + } + + /// `exchange`: each host wave gives `mine` (the same in all its lanes) for its half; both get + /// (lower half's, upper half's). A group with no upper half gets 0 for it. + fn exchange_halves(&mut self, at: usize, mine: V) -> (V, V) { + let Some((slot, small, _)) = self.exchange.as_ref().map(|(a, b, _)| (*a, *b, ())) else { + let z = self.s.m.i32(0); + return (mine, z); + }; + if small { + let z = self.s.m.i32(0); + return (mine, z); + } + if self.local { + // each host wave on its own: its half holds `mine`, the other nothing + let cl = self.console_lane(); + let (k32, z) = (self.s.m.i32(32), self.s.m.i32(0)); + let upper = self.s.m.cmp(at, pred::IUGE, cl, k32); + let lo = self.s.m.select(at, upper, z, mine); + let hi = self.s.m.select(at, upper, mine, z); + return (lo, hi); + } + // the pair of dwords of this thread's console wave: its half's, then both + let pair = self.exchange_pair(slot); + let cl = self.console_lane(); + let five = self.s.m.i32(5); + let half = self.s.m.bin(at, Bin::LShr, cl, five); + let index = self.s.m.bin(at, Bin::Add, pair, half); + let lds = self.s.lds(); + let ptr = self.s.m.element(at, lds, index); + self.s.m.store(at, ptr, mine); + self.group_sync(at); + let one = self.s.m.i32(1); + let k1 = self.s.m.bin(at, Bin::Add, pair, one); + let p0 = self.s.m.element(at, lds, pair); + let p1 = self.s.m.element(at, lds, k1); + let lo = self.s.m.load(at, p0); + let hi = self.s.m.load(at, p1); + // the slots are written again only after every thread read them + self.group_sync(at); + (lo, hi) + } + + /// The first of the two exchange dwords of this thread's console wave (made in the entry + /// block): a group of several console waves has a pair for each. + fn exchange_pair(&mut self, slot: u32) -> V { + if let Some(v) = self.pair { + return v; + } + let e = self.s.entry; + let thread = self.console_thread(); + let six = self.s.m.i32(6); + let wave = self.s.m.bin(e, Bin::LShr, thread, six); + let one = self.s.m.i32(1); + let twice = self.s.m.bin(e, Bin::Shl, wave, one); + let base = self.s.m.i32(slot); + let v = self.s.m.bin(e, Bin::Add, base, twice); + self.pair = Some(v); + v + } + + /// The console's decision of the branch closing IR block `b`, which the wave takes + /// together ([`Structured::wide`]): `when` is the lane's own bit, and the branch is taken + /// when some lane's `when` holds (`execnz`, `vccnz`, SCC of a mask operation set) or + /// when every lane's does (`execz`, `vccz`, that SCC clear), [`Structured::wave_any`]. + /// Each host wave asks its lanes and the halves exchange the answers, so both go the + /// same way and can meet again inside the branch. + /// SCC of a mask operation as data ([`Structured::scc_some`]): whether some lane of the + /// console wave has its bit of the result, asked where the operation stands. The lanes + /// that are elsewhere have no bit (the result is ANDed with EXEC or is EXEC), so with + /// the console's waves the host wave's answer is the console's; two host waves of 32 + /// exchange theirs, which needs every lane there. + fn scc_some(&mut self, scc: Value) -> Result { + let &m = self.x.st.scc_some.get(&scc).ok_or(LANE_MASK)?; + // (not for a console wave cut into host waves that do not exchange) + if !self.console_lanes || self.local || self.exchange.is_none() && self.halves.is_some() { + return Err(LANE_MASK); + } + let made = self.def_block.get(&scc).copied(); + let at = match made { + None => self.s.entry, + Some(b) if b == self.cur_ir => self.cur, + Some(b) => self.tail[b].ok_or("a lane mask written after its use")?, + }; + let bit = self.boolean(m, at)?; + let (i1t, i32t) = (self.s.t.i1, self.s.t.i32); + let some = self.s.op(at, "waveAnyTrue", Attr::NoUnwind, i1t, 113, &[bit]); + self.s.flags |= flags::WAVE_OPS; + if !self.exchange.as_ref().is_some_and(|e| !e.1) { + return Ok(some); + } + if !made.is_none_or(|b| self.all_lanes(b)) { + need(made.unwrap_or(0)); + return Err("a lane mask exchanged where not every lane runs"); + } + let some = self.s.m.cast(at, Cast::ZExt, some, i32t); + let (lo, hi) = self.exchange_halves(at, some); + let both = self.s.m.bin(at, Bin::Or, lo, hi); + let z = self.s.m.i32(0); + Ok(self.s.m.cmp(at, pred::NE, both, z)) + } + + fn wave_wide(&mut self, b: usize, when: Bool) -> Result { + const WHY: Why = "a wave-wide branch where not every lane runs"; + let any = self.x.st.wave_any.get(b).copied().flatten().ok_or("a wave-wide branch on a scalar condition")?; + if self.exchange.is_none() && self.halves.is_none() && self.console_lanes && self.mask_data == MaskData::Console { + // The host's waves are the console's: the wave's own answer. The lanes that are + // elsewhere have no bit set, as on the console, so "some lane" needs no one but + // the lanes here, and "every lane's bit is clear" is true of the others anyway. + let c = self.cur; + let mine = self.boolean(when, c)?; + let i1t = self.s.t.i1; + self.s.flags |= flags::WAVE_OPS; + let (name, code) = if any { ("waveAnyTrue", 113) } else { ("waveAllTrue", 114) }; + return Ok(self.s.op(c, name, Attr::NoUnwind, i1t, code, &[mine])); + } + if self.local || !self.exchange.as_ref().is_some_and(|e| !e.1) { + return Err(WHY); + } + if !self.all_lanes(b) { + need(b); + return Err(WHY); + } + let c = self.cur; + let mine = self.boolean(when, c)?; + // what the halves exchange is "some lane speaks against" either way (for `any`: + // some lane's `when` holds; else: some lane's does not), so a half with no lane says + // nothing + let set = if any { + mine + } else { + let t = self.s.m.bool(true); + self.s.m.bin(c, Bin::Xor, mine, t) + }; + let (i1t, i32t) = (self.s.t.i1, self.s.t.i32); + let some = self.s.op(c, "waveAnyTrue", Attr::NoUnwind, i1t, 113, &[set]); + self.s.flags |= flags::WAVE_OPS; + let some = self.s.m.cast(c, Cast::ZExt, some, i32t); + let (lo, hi) = self.exchange_halves(c, some); + let c = self.cur; + let both = self.s.m.bin(c, Bin::Or, lo, hi); + let z = self.s.m.i32(0); + Ok(self.s.m.cmp(c, if any { pred::NE } else { pred::EQ }, both, z)) + } + + /// Whether every lane runs IR block `b` (always true without `exchange`). + fn all_lanes(&self, b: usize) -> bool { + self.exchange.as_ref().is_none_or(|(_, _, all)| all.get(b).copied().unwrap_or(false)) + } + + /// This lane's bit of the mask `lo`, `hi` (wave64). + fn lane_bit(&mut self, at: usize, lo: V, hi: Option) -> V { + self.s.flags |= flags::WAVE_OPS; + let lane = if self.exchange.is_some() { + self.console_lane() + } else { + self.s.op(at, "waveGetLaneIndex", Attr::ReadOnly, self.s.t.i32, 111, &[]) + }; + let (k31, k32, one, z) = ( + self.s.m.i32(31), + self.s.m.i32(32), + self.s.m.i32(1), + self.s.m.i32(0), + ); + let word = match hi { + Some(hi) => { + let low = self.s.m.cmp(at, pred::IULT, lane, k32); + self.s.m.select(at, low, lo, hi) + } + None => lo, + }; + let sh = self.s.m.bin(at, Bin::And, lane, k31); + let t = self.s.m.bin(at, Bin::LShr, word, sh); + let t = self.s.m.bin(at, Bin::And, t, one); + self.s.m.cmp(at, pred::NE, t, z) + } + + /// The value of the high dword of the wave64 register pair whose low + /// dword holds `lo` (none in wave32). + fn pair_high(&self, lo: Value) -> Option { + if !self.x.native.wave64 { + return None; + } + let p = self.x.p; + let pick = |reg: Reg| match reg { + Reg::S(c) => Some(Reg::S(c + 1)), + _ => None, + }; + if let Some(&(reg, _)) = p.inputs.iter().find(|i| i.1 == lo) { + let h = pick(reg)?; + return p.inputs.iter().find(|i| i.0 == h).map(|i| i.1); + } + if let Some(&(b, i)) = self.phi_at.get(&lo) { + let h = pick(p.blocks[b].phis[i].reg)?; + return p.blocks[b] + .phis + .iter() + .find(|q| q.reg == h) + .map(|q| q.value); + } + let b = *self.def_block.get(&lo)?; + let inst = p.blocks[b] + .insts + .iter() + .find(|i| i.writes.iter().any(|w| w.1 == lo))?; + let &(reg, _) = inst.writes.iter().find(|w| w.1 == lo)?; + inst.write(pick(reg)?) + } + + fn guard(&mut self, b: usize, i: usize) -> Result, Why> { + match self.x.st.guards[b][i] { + None => Ok(None), + Some(g) => Ok(Some(self.boolean(g, self.cur)?)), + } + } + + // ---- results ---- + + fn set(&mut self, v: Option, val: Val) { + if let Some(v) = v { + self.vals.insert(v, val); + } + } + + /// Writes VGPR `reg` (or the SGPR of a lane read), under `guard`. + fn write(&mut self, inst: &Inst, reg: Reg, x: V, guard: Option) { + let x = match (Self::sdwa_dst(inst), reg) { + (Some((sel, unused)), Reg::V(_)) => self.place_bits(inst, reg, x, sel, unused), + _ => x, + }; + self.write_placed(inst, reg, x, guard); + } + + /// [`Self::write`] of a dword already placed (SDWA applied). + fn write_placed(&mut self, inst: &Inst, reg: Reg, x: V, guard: Option) { + let Some(new) = inst.write(reg) else { return }; + let x = match (guard, reg) { + (Some(g), Reg::V(_)) => { + let old = match inst.read(reg).map(|o| self.i32_of(o)) { + Some(Ok(o)) => o, + // The validator refuses reads of undef. + _ => self.s.m.i32(0), + }; + let v = self.s.m.select(self.cur, g, x, old); + self.s.m.tag(v, Tag::Guard); + v + } + _ => x, + }; + self.vals.insert(new, Val::I32(x)); + } + + /// The SDWA destination selection: a byte or word, and what the other + /// bits get (0 zeros, 1 the sign above the field, 2 the old bits). + fn sdwa_dst(inst: &Inst) -> Option<(u8, u8)> { + let Fields::Valu(v) = &inst.fields else { + return None; + }; + let s = v.sdwa?; + (s.dst_sel < 6).then_some((s.dst_sel, s.dst_unused)) + } + + /// The low byte or word of `x` placed at `sel` in VGPR `reg`. + fn place_bits(&mut self, inst: &Inst, reg: Reg, x: V, sel: u8, unused: u8) -> V { + let c = self.cur; + let (width, at) = if sel < 4 { + (8u32, 8 * u32::from(sel)) + } else { + (16, 16 * u32::from(sel - 4)) + }; + let left = self.s.m.i32(32 - width); + let t = self.s.m.bin(c, Bin::Shl, x, left); + let right = self.s.m.i32(32 - width - at); + if unused == 1 { + // Bits below the field shift in as zeros. + return self.s.m.bin(c, Bin::AShr, t, right); + } + let field = self.s.m.bin(c, Bin::LShr, t, right); + if unused != 2 { + return field; + } + let old = match inst.read(reg).map(|o| self.i32_of(o)) { + Some(Ok(o)) => o, + _ => self.s.m.i32(0), + }; + let keep = self.s.m.i32(!((((1u64 << width) - 1) as u32) << at)); + let old = self.s.m.bin(c, Bin::And, old, keep); + self.s.m.bin(c, Bin::Or, old, field) + } + + fn write_f(&mut self, inst: &Inst, f: V, guard: Option) -> Result<(), Why> { + let Fields::Valu(v) = &inst.fields else { + unreachable!() + }; + let mut f = f; + match v.omod { + 0 => {} + k => { + let factor = [1.0f32, 2.0, 4.0, 0.5][usize::from(k)]; + let c = self.s.m.f32(factor.to_bits()); + f = self.s.m.bin(self.cur, Bin::Mul, f, c); + } + } + if v.clamp { + f = self.unary(7, f); + } + let Some(Operand::Vector { reg, .. }) = v.dst else { + return Err("a float result outside a VGPR"); + }; + let x = self.as_int(f); + self.write(inst, Reg::V(reg), x, guard); + if guard.is_none() + && Self::sdwa_dst(inst).is_none() + && let Some(new) = inst.write(Reg::V(reg)) + { + self.floats.insert(new, f); + } + Ok(()) + } + + fn write_i(&mut self, inst: &Inst, x: V, guard: Option) -> Result<(), Why> { + let Fields::Valu(v) = &inst.fields else { + unreachable!() + }; + if v.clamp || v.omod != 0 { + return Err("integer output modifiers"); + } + match v.dst { + Some(Operand::Vector { reg, .. }) => self.write(inst, Reg::V(reg), x, guard), + Some(Operand::Scalar { code, .. }) => self.write(inst, Reg::S(code), x, None), + _ => return Err("a result without a register"), + } + Ok(()) + } + + /// Starts code only the lanes where `guard` holds run (a store under a + /// lane guard): returns where it started and the join block. + fn begin_guarded(&mut self, guard: Option) -> Option<(usize, usize)> { + let g = guard?; + let (then, join) = (self.s.m.new_block(), self.s.m.new_block()); + self.s.m.terminate(self.cur, Term::CondBr(g, then, join)); + let head = self.cur; + self.cur = then; + Some((head, join)) + } + + /// Ends guarded code; each (value inside, value outside) becomes a phi. + fn end_guarded(&mut self, at: Option<(usize, usize)>, values: &[(V, V)]) -> Vec { + let Some((head, join)) = at else { + return values.iter().map(|v| v.0).collect(); + }; + let then = self.cur; + self.s.m.terminate(then, Term::Br(join)); + self.cur = join; + values + .iter() + .map(|&(inside, outside)| { + let ty = self.s.m.type_of(inside); + let phi = self.s.m.phi(join, ty); + self.s.m.set_phi(phi, vec![(inside, then), (outside, head)]); + phi + }) + .collect() + } + + /// Code that depends on the lane layout: wave operations, and in compute + /// the console's wave size (lanes are thread ids in group order there). + /// Pixel lanes match only within a quad. + fn cross_lane(&mut self, quad: bool) -> Result<(), Why> { + if self.s.mesh.is_some() { + // shortcut: no wave size for mesh shaders in SM 6.6, so host + // lanes cannot follow the console's; emulate through group-shared + // memory if mesh programs turn out to need these. + return Err("a cross-lane operation in a mesh shader"); + } + if self.s.threads.is_none() && !(quad && self.s.pixel) { + return Err("a cross-lane operation outside compute"); + } + debug_assert!(self.s.threads.is_none() || self.console_lanes); + self.s.flags |= flags::WAVE_OPS; + Ok(()) + } + + /// Component `c` of the thread id in the group. With console lanes, the + /// thread is relabelled so that its host lane is its console lane: the + /// flat id is the wave's first lane's, rounded down to the wave size, + /// plus the lane index. (A bijection while each host wave holds a + /// wave-aligned run of flat ids, as the console's waves do.) + fn thread_id(&mut self, c: u8) -> Val { + if !self.console_lanes { + return self.compute_id("threadIdInGroup.i32", 95, c); + } + let [x, y, _] = self.s.threads.expect("compute"); + let e = self.s.entry; + let i32t = self.s.t.i32; + if self.halves.is_some() { + let f = self.console_thread(); + self.s.flags |= flags::WAVE_OPS; + let (xk, yk, xy) = (self.s.m.i32(x), self.s.m.i32(y), self.s.m.i32(x * y)); + return Val::I32(match c { + 0 => self.s.m.bin(e, Bin::URem, f, xk), + 1 => { + let t = self.s.m.bin(e, Bin::UDiv, f, xk); + self.s.m.bin(e, Bin::URem, t, yk) + } + _ => self.s.m.bin(e, Bin::UDiv, f, xy), + }); + } + let flat = self.s.op( + e, + "flattenedThreadIdInGroup.i32", + Attr::ReadNone, + i32t, + 96, + &[], + ); + let first = self.s.op( + e, + "waveReadLaneFirst.i32", + Attr::NoUnwind, + i32t, + 118, + &[flat], + ); + let wave = self.s.wave_size.expect("set with console lanes"); + let mask = self.s.m.i32(!(wave - 1)); + let base = self.s.m.bin(e, Bin::And, first, mask); + let lane = self.lane_index(); + let f = self.s.m.bin(e, Bin::Add, base, lane); + self.s.flags |= flags::WAVE_OPS; + let (xk, yk, xy) = (self.s.m.i32(x), self.s.m.i32(y), self.s.m.i32(x * y)); + Val::I32(match c { + 0 => self.s.m.bin(e, Bin::URem, f, xk), + 1 => { + let t = self.s.m.bin(e, Bin::UDiv, f, xk); + self.s.m.bin(e, Bin::URem, t, yk) + } + _ => self.s.m.bin(e, Bin::UDiv, f, xy), + }) + } + + /// Mesh: the counts and the primitives no lane exports. The console's + /// counts come from one lane's allocation request, which DXIL cannot + /// express (one call, dominating every output write). + // shortcut: the counts are the declared maxima and each lane first culls + // its primitive (all indices 0, zero area), so primitives past the + // program's count are culled and vertices past it unused; this costs + // the host the unused vertex and primitive slots. Pass the program's own + // counts if that shows in frame time. + fn mesh_prologue(&mut self, mut mesh: super::shader::Mesh) -> Result<(), Why> { + let threads = self.s.threads.expect("mesh")[0]; + if mesh.topology != 2 { + return Err("a mesh shader not drawing triangles"); + } + if threads > 128 || mesh.max_vertices > 256 || mesh.max_primitives > 256 { + return Err("a mesh shader beyond the host's limits"); + } + // D3D12 caps the outputs of the declared maxima at 32 KiB. Lane n + // writes only vertex n and primitive n, so maxima past the lanes are + // never reached: they come down to the lane count when the outputs + // do not fit. + use super::container::{MESH_OUTPUT_LIMIT, mesh_output_bytes}; + let (outputs, prims) = (&self.s.outputs, &self.s.prims); + let fits = |m: super::shader::Mesh| { + mesh_output_bytes(outputs, prims, m.max_vertices, m.max_primitives) <= MESH_OUTPUT_LIMIT + }; + if !fits(mesh) { + mesh.max_vertices = mesh.max_vertices.min(threads); + mesh.max_primitives = mesh.max_primitives.min(threads); + // shortcut: outputs past the cap even at the lane count are + // still emitted with the lower maxima (drivers take them); + // refuse them here if one hangs. + // Experiment (`LEONIDA_MESH_OUTPUT_STRICT=1`): they are refused. + if !fits(mesh) && std::env::var_os("LEONIDA_MESH_OUTPUT_STRICT").is_some() { + return Err("a mesh shader whose outputs pass the host's 32 KiB"); + } + self.s.mesh = Some(mesh); + } + let e = self.s.entry; + let void = self.s.t.void; + let (v, p) = ( + self.s.m.i32(mesh.max_vertices), + self.s.m.i32(mesh.max_primitives), + ); + self.s + .op(e, "setMeshOutputCounts", Attr::NoUnwind, void, 168, &[v, p]); + let flat = self.mesh_thread(); + let z = self.s.m.i32(0); + // Every primitive of the declared count starts culled, also those + // past the lanes (a count of 256 with 128 lanes): lane n culls + // primitives n, n + lanes, ... The host draws all it was promised, + // and one never written has whatever indices its memory held: long + // triangles over the whole target, each pixel of them shaded. + let passes = mesh.max_primitives.div_ceil(threads.max(1)); + for pass in 0..passes { + let index = if pass == 0 { + flat + } else { + let past = self.s.m.i32(pass * threads); + self.s.m.bin(self.cur, Bin::Add, flat, past) + }; + let guard = ((pass + 1) * threads > mesh.max_primitives) + .then(|| self.s.m.cmp(self.cur, pred::IULT, index, p)); + let at = self.begin_guarded(guard); + self.s.op( + self.cur, + "emitIndices", + Attr::NoUnwind, + void, + 169, + &[index, z, z, z], + ); + self.end_guarded(at, &[]); + } + Ok(()) + } + + /// Mesh: the thread's index in the group, which is its vertex and + /// primitive index. + fn mesh_thread(&mut self) -> V { + if let Some(f) = self.flat { + return f; + } + let e = self.s.entry; + let f = self.s.op( + e, + "flattenedThreadIdInGroup.i32", + Attr::ReadNone, + self.s.t.i32, + 96, + &[], + ); + self.flat = Some(f); + f + } + + /// The console wave size. + fn wave(&self) -> u32 { + if self.x.native.wave64 { 64 } else { 32 } + } + + fn lane_index(&mut self) -> V { + if self.s.mesh.is_some() { + // The console's lane: mesh code reads no other lanes, so host + // waves need not match the console's. + let f = self.mesh_thread(); + let m = self.s.m.i32(self.wave() - 1); + return self.s.m.bin(self.s.entry, Bin::And, f, m); + } + self.s.op( + self.cur, + "waveGetLaneIndex", + Attr::ReadOnly, + self.s.t.i32, + 111, + &[], + ) + } + + /// `x` of lane `src` (in this lane's quad) through quad reads, whose + /// lane must be a constant. + fn quad_pick(&mut self, x: V, src: V) -> V { + self.s.flags |= flags::WAVE_OPS; + let c = self.cur; + let three = self.s.m.i32(3); + let q = self.s.m.bin(c, Bin::And, src, three); + let mut r = x; + for n in 0..4 { + let kn = self.s.m.i32(n); + let read = self.s.op( + c, + "quadReadLaneAt.i32", + Attr::NoUnwind, + self.s.t.i32, + 122, + &[x, kn], + ); + let is = self.s.m.cmp(c, pred::EQ, q, kn); + r = self.s.m.select(c, is, read, r); + } + r + } + + /// `x` in the first lane of this host wave where `guard` holds, and whether it has such a + /// lane: the console reads the first lane of EXEC, and a lane that got here with EXEC clear + /// (a guard, not a branch) is not one. With none, `x` of the wave's first lane here. + fn first_lane(&mut self, x: V, guard: Option) -> (V, V) { + let c = self.cur; + let i32t = self.s.t.i32; + self.s.flags |= flags::WAVE_OPS; + let first = self.s.op(c, "waveReadLaneFirst.i32", Attr::NoUnwind, i32t, 118, &[x]); + let Some(g) = guard else { + return (first, self.s.m.bool(true)); + }; + let four = self.s.m.named_struct("dx.types.fouri32", vec![i32t; 4]); + let r = self.s.op(c, "waveActiveBallot", Attr::NoUnwind, four, 116, &[g]); + let (lo, hi) = (self.s.m.extract(c, r, 0), self.s.m.extract(c, r, 1)); + let (z, k32) = (self.s.m.i32(0), self.s.m.i32(32)); + // FirstbitLo (dx.op 32): the lowest set bit + let flo = self.s.op(c, "unaryBits.i32", Attr::ReadNone, i32t, 32, &[lo]); + let fhi = self.s.op(c, "unaryBits.i32", Attr::ReadNone, i32t, 32, &[hi]); + let fhi = self.s.m.bin(c, Bin::Add, fhi, k32); + let in_lo = self.s.m.cmp(c, pred::NE, lo, z); + let in_hi = self.s.m.cmp(c, pred::NE, hi, z); + let any = self.s.m.bin(c, Bin::Or, in_lo, in_hi); + let lane = self.s.m.select(c, in_lo, flo, fhi); + // no lane in EXEC: read this lane (one that is here); the read is not used + let me = self.s.op(c, "waveGetLaneIndex", Attr::ReadOnly, i32t, 111, &[]); + let lane = self.s.m.select(c, any, lane, me); + let at = self.read_lane(x, lane); + (self.s.m.select(c, any, at, first), any) + } + + fn read_lane(&mut self, x: V, lane: V) -> V { + self.s.op( + self.cur, + "waveReadLaneAt.i32", + Attr::NoUnwind, + self.s.t.i32, + 117, + &[x, lane], + ) + } + + /// The float value of a register value. + fn float_of(&mut self, v: Value) -> Result { + if let Some(&f) = self.floats.get(&v) { + return Ok(f); + } + let x = self.i32_of(v)?; + Ok(self.as_float(x)) + } + + /// The values of VGPRs `reg..reg + n` as `inst` reads them. + fn vgprs(&mut self, inst: &Inst, op: &Operand, n: u8) -> Result, Why> { + let Operand::Vector { reg, .. } = *op else { + return Err("a vector operand"); + }; + (0..n) + .map(|k| { + let v = inst.read(Reg::V(reg + k)).ok_or("an unread operand")?; + self.i32_of(v) + }) + .collect() + } + + /// LDS (thread-group shared memory) and `ds_swizzle`. + fn ds(&mut self, inst: &Inst, b: usize, i: usize) -> Result<(), Why> { + let Fields::Ds { + dst, + addr, + data, + offset0, + offset1, + gds, + } = &inst.fields + else { + unreachable!() + }; + if *gds { + return Err("GDS"); + } + let name = inst.name(); + let guard = self.guard(b, i)?; + let c = self.cur; + let offset = u32::from(*offset0) | u32::from(*offset1) << 8; + let dst_reg = match dst { + Some(Operand::Vector { reg, .. }) => Some(*reg), + _ => None, + }; + if name == "ds_swizzle_b32" { + // Bit 15 set: each lane of a quad picks a lane of it; else lanes + // of each group of 32 combine their index with and/or/xor masks. + let quad = offset & 0x8000 != 0 + || offset & 0x1C == 0x1C && offset & 0x380 == 0 && offset >> 10 & 0x1F < 4; + // Mesh: host quads are threads 4n..4n+3 of a 1D group, as the + // console's, so quad-local swizzles read through quad operations. + let mesh_quad = self.s.mesh.is_some() && quad; + if !mesh_quad { + self.cross_lane(quad)?; + } + // The source sits in the address field. + let x = self.vgprs(inst, addr.as_ref().ok_or("a swizzle source")?, 1)?[0]; + let lane = self.lane_index(); + let k = |l: &mut Self, v: u32| l.s.m.i32(v); + let src = if offset & 0x8000 != 0 { + let (three, one) = (k(self, 3), k(self, 1)); + let sel = self.s.m.bin(c, Bin::And, lane, three); + let sh = self.s.m.bin(c, Bin::Shl, sel, one); + let pattern = k(self, offset & 0xFF); + let pick = self.s.m.bin(c, Bin::LShr, pattern, sh); + let pick = self.s.m.bin(c, Bin::And, pick, three); + let not3 = k(self, !3); + let base = self.s.m.bin(c, Bin::And, lane, not3); + self.s.m.bin(c, Bin::Or, base, pick) + } else { + let and = k(self, offset & 0x1F | !0x1F); + let or = k(self, offset >> 5 & 0x1F); + let xor = k(self, offset >> 10 & 0x1F); + let t = self.s.m.bin(c, Bin::And, lane, and); + let t = self.s.m.bin(c, Bin::Or, t, or); + self.s.m.bin(c, Bin::Xor, t, xor) + }; + let r = if mesh_quad { + self.quad_pick(x, src) + } else { + self.read_lane(x, src) + }; + let reg = dst_reg.ok_or("a swizzle result")?; + self.write(inst, Reg::V(reg), r, guard); + return Ok(()); + } + if name == "ds_bpermute_b32" { + // Backward permute: no LDS is touched. Each lane takes the data + // register of the lane its address names, (address + offset) / 4 + // within the wave; a source lane outside EXEC gives 0. ( + // the title's checkerboard shadow-mask generators read their + // neighbours' samples with it; without them every shadowed light + // was multiplied by an empty mask.) + // shortcut: a source lane that is not at this instruction on the + // host (it left through a branch, not a guard) is read as the + // host gives it; the console reads 0. + self.cross_lane(false)?; + if self.exchange.as_ref().is_some_and(|e| !e.1) { + // a console wave of 64 run as two host waves: the lane named + // may be in the other one + return Err("a lane permute across two host waves"); + } + let at = self.vgprs(inst, addr.as_ref().ok_or("a permute address")?, 1)?[0]; + let x = self.vgprs(inst, data.first().ok_or("a permute source")?, 1)?[0]; + let o = self.s.m.i32(offset); + let at = self.s.m.bin(c, Bin::Add, at, o); + let two = self.s.m.i32(2); + let src = self.s.m.bin(c, Bin::LShr, at, two); + let last = self.s.m.i32(self.wave() - 1); + let src = self.s.m.bin(c, Bin::And, src, last); + let x = match guard { + Some(g) => { + let z = self.s.m.i32(0); + self.s.m.select(c, g, x, z) + } + None => x, + }; + let r = self.read_lane(x, src); + let reg = dst_reg.ok_or("a permute result")?; + self.write(inst, Reg::V(reg), r, guard); + return Ok(()); + } + if self.s.lds_dwords == 0 { + return Err("LDS the program does not allocate"); + } + let a = self.vgprs(inst, addr.as_ref().ok_or("an LDS address")?, 1)?[0]; + // shortcut: LDS addresses are taken as dword-aligned and in bounds + // (out-of-bounds console accesses read 0 and drop writes). + let dword = |l: &mut Self, bytes: u32| -> V { + let c = l.cur; + let o = l.s.m.i32(bytes); + let at = l.s.m.bin(c, Bin::Add, a, o); + let two = l.s.m.i32(2); + let index = l.s.m.bin(c, Bin::LShr, at, two); + let lds = l.s.lds(); + l.s.m.element(c, lds, index) + }; + let width = |n: &str| match n.rsplit('_').next() { + Some("b64") => 2, + Some("b96") => 3, + Some("b128") => 4, + _ => 1, + }; + // (byte offset, dwords) per element; read2/write2 scale their two + // offsets by the element size (×64 for st64). + let pair = |n: &str| -> Vec<(u32, u32)> { + let w = width(n); + let scale = 4 * w * if n.contains("st64") { 64 } else { 1 }; + vec![ + (u32::from(*offset0) * scale, w), + (u32::from(*offset1) * scale, w), + ] + }; + // Bytes and halves: the dword holding them, and their bit position + // in it (naturally aligned, so they never straddle dwords). + // `_d16` reads fill a register's low half (`_d16_hi` its high half) + // and keep the other; `_d16_hi` writes take the data's high half. + let base = name.trim_end_matches("_hi").trim_end_matches("_d16"); + let sub = match base { + "ds_read_u8" | "ds_read_i8" | "ds_write_b8" => Some(8u32), + "ds_read_u16" | "ds_read_i16" | "ds_write_b16" => Some(16), + _ => None, + }; + let sub = sub.filter(|_| { + base == name + || name.ends_with("_d16") && base.starts_with("ds_read") + || name.ends_with("_d16_hi") + }); + if let Some(bits) = sub { + let p = dword(self, offset); + let o = self.s.m.i32(offset); + let at = self.s.m.bin(c, Bin::Add, a, o); + let three = self.s.m.i32(3); + let byte = self.s.m.bin(c, Bin::And, at, three); + let sh = self.s.m.bin(c, Bin::Shl, byte, three); + let mask = self.s.m.i32((1u32 << bits) - 1); + if name.starts_with("ds_read") { + let reg = dst_reg.ok_or("an LDS read result")?; + let w = self.s.m.load(c, p); + let x = self.s.m.bin(c, Bin::LShr, w, sh); + let x = if base.contains("_i") { + let k = self.s.m.i32(32 - bits); + let x = self.s.m.bin(c, Bin::Shl, x, k); + self.s.m.bin(c, Bin::AShr, x, k) + } else { + self.s.m.bin(c, Bin::And, x, mask) + }; + let x = if base == name { + x + } else { + let old = match inst.read(Reg::V(reg)) { + Some(v) => self.i32_of(v)?, + None => self.s.m.i32(0), + }; + let half = self.s.m.i32(0xFFFF); + let x = self.s.m.bin(c, Bin::And, x, half); + let (x, keep) = if name.ends_with("_hi") { + let k16 = self.s.m.i32(16); + (self.s.m.bin(c, Bin::Shl, x, k16), half) + } else { + (x, self.s.m.i32(0xFFFF_0000)) + }; + let old = self.s.m.bin(c, Bin::And, old, keep); + self.s.m.bin(c, Bin::Or, old, x) + }; + self.write(inst, Reg::V(reg), x, guard); + } else { + // Clear, then set: two atomics, so lanes writing other + // bytes of the dword keep theirs. + let mut x = self.vgprs(inst, data.first().ok_or("an LDS write")?, 1)?[0]; + if name != base { + // The data's high half. + let k16 = self.s.m.i32(16); + x = self.s.m.bin(c, Bin::LShr, x, k16); + } + let x = self.s.m.bin(c, Bin::And, x, mask); + let x = self.s.m.bin(c, Bin::Shl, x, sh); + let m = self.s.m.bin(c, Bin::Shl, mask, sh); + let ones = self.s.m.i32(u32::MAX); + let keep = self.s.m.bin(c, Bin::Xor, m, ones); + use super::bitcode::Rmw; + let at = self.begin_guarded(guard); + self.s.m.atomic(self.cur, Rmw::And, p, keep); + self.s.m.atomic(self.cur, Rmw::Or, p, x); + self.end_guarded(at, &[]); + } + return Ok(()); + } + if let Some(rest) = name.strip_prefix("ds_read") { + let elements = if rest.starts_with('2') { + pair(name) + } else if matches!(rest, "_b32" | "_b64" | "_b96" | "_b128") { + vec![(offset, width(name))] + } else { + return Err("an LDS read of bytes or halves"); + }; + let reg = dst_reg.ok_or("an LDS read result")?; + let mut n = 0; + for (off, w) in elements { + for k in 0..w { + let p = dword(self, off + 4 * k); + let x = self.s.m.load(self.cur, p); + self.write(inst, Reg::V(reg + n), x, guard); + n += 1; + } + } + return Ok(()); + } + if let Some(rest) = name.strip_prefix("ds_write") { + let elements = if rest.starts_with('2') { + pair(name) + } else if matches!(rest, "_b32" | "_b64" | "_b96" | "_b128") { + vec![(offset, width(name))] + } else { + return Err("an LDS write of bytes or halves"); + }; + let mut stores = Vec::new(); + for (e, (off, w)) in elements.into_iter().enumerate() { + let vals = self.vgprs(inst, data.get(e).ok_or("an LDS write")?, w as u8)?; + for (k, x) in vals.into_iter().enumerate() { + stores.push((off + 4 * k as u32, x)); + } + } + let at = self.begin_guarded(guard); + for (off, x) in stores { + let p = dword(self, off); + self.s.m.store(self.cur, p, x); + } + self.end_guarded(at, &[]); + return Ok(()); + } + // Atomics: the old value returns with `_rtn`. + let op = name + .strip_prefix("ds_") + .map(|n| n.replace("_rtn", "")) + .ok_or("an LDS operation")?; + use super::bitcode::Rmw; + let rmw = match op.as_str() { + "add_u32" => Some(Rmw::Add), + "sub_u32" => Some(Rmw::Sub), + "and_b32" => Some(Rmw::And), + "or_b32" => Some(Rmw::Or), + "xor_b32" => Some(Rmw::Xor), + "min_i32" => Some(Rmw::Min), + "max_i32" => Some(Rmw::Max), + "min_u32" => Some(Rmw::UMin), + "max_u32" => Some(Rmw::UMax), + "wrxchg_b32" => Some(Rmw::Xchg), + "cmpst_b32" | "max_f32" | "min_f32" => None, + _ => return Err("an LDS operation"), + }; + let v0 = self.vgprs(inst, data.first().ok_or("an LDS atomic")?, 1)?[0]; + let v1 = match data.get(1) { + Some(d) => Some(self.vgprs(inst, d, 1)?[0]), + None => None, + }; + let old_reg = dst_reg.and_then(|r| inst.read(Reg::V(r)).map(|v| (r, v))); + let outside = match old_reg { + Some((_, v)) => self.i32_of(v).unwrap_or(self.s.m.i32(0)), + None => self.s.m.i32(0), + }; + let p = dword(self, offset); + if let Some(max) = match op.as_str() { + "max_f32" => Some(true), + "min_f32" => Some(false), + _ => None, + } { + let at = self.begin_guarded(guard); + let r = self.lds_float_min_max(p, v0, max); + let r = self.end_guarded(at, &[(r, outside)])[0]; + if let Some(reg) = dst_reg { + self.write(inst, Reg::V(reg), r, None); + } + return Ok(()); + } + let at = self.begin_guarded(guard); + let r = match rmw { + Some(op) => self.s.m.atomic(self.cur, op, p, v0), + // Compare with data0, store data1. + None => self + .s + .m + .cmpxchg(self.cur, p, v0, v1.ok_or("an LDS compare")?), + }; + let r = self.end_guarded(at, &[(r, outside)])[0]; + if let Some(reg) = dst_reg { + self.write(inst, Reg::V(reg), r, None); + } + Ok(()) + } + + /// `ds_max_f32` (`max`) or `ds_min_f32` on the LDS dword at `p` with + /// the float bits `data`; the old bits return. + /// + /// DXIL has no float atomics on group-shared memory, so this is a + /// compare-exchange loop around [`Lower::lds_float_pick`], which gives + /// what RDNA2 writes (measured on gfx1036, reported on the pull + /// request): an sNaN, data first, then memory, is written quieted; + /// otherwise a NaN loses to a number (two quiet NaNs give the data); + /// numbers compare as floats with -0 below +0. + // shortcut: f32 denormals compare as kept; with the console's MODE + // flushing them they would order as ±0 first (MODE is not modelled). + fn lds_float_min_max(&mut self, p: V, data: V, max: bool) -> V { + let pre = self.cur; + let init = self.s.m.load(pre, p); + let (lp, exit) = (self.s.m.new_block(), self.s.m.new_block()); + self.s.m.terminate(pre, Term::Br(lp)); + let i32t = self.s.t.i32; + let old = self.s.m.phi(lp, i32t); + self.cur = lp; + let new = self.lds_float_pick(old, data, max); + let prev = self.s.m.cmpxchg(lp, p, old, new); + let done = self.s.m.cmp(lp, pred::EQ, prev, old); + self.s.m.set_phi(old, vec![(init, pre), (prev, lp)]); + self.s.m.terminate(lp, Term::CondBr(done, exit, lp)); + self.cur = exit; + old + } + + /// What `ds_max_f32` (`max`) or `ds_min_f32` writes over the dword + /// `mem` with `data` (float bits; see [`Lower::lds_float_min_max`]). + fn lds_float_pick(&mut self, mem: V, data: V, max: bool) -> V { + let c = self.cur; + let k = |l: &mut Self, v: u32| l.s.m.i32(v); + let (abs_mask, inf, quiet, zero) = ( + k(self, 0x7FFF_FFFF), + k(self, 0x7F80_0000), + k(self, 0x40_0000), + k(self, 0), + ); + let nan = |l: &mut Self, x: V| { + let m = l.s.m.bin(c, Bin::And, x, abs_mask); + l.s.m.cmp(c, pred::IUGT, m, inf) + }; + let snan = |l: &mut Self, x: V| { + let n = nan(l, x); + let q = l.s.m.bin(c, Bin::And, x, quiet); + let sig = l.s.m.cmp(c, pred::EQ, q, zero); + l.s.m.bin(c, Bin::And, n, sig) + }; + // A total order of the numbers as signed integers, -0 below +0: + // negative floats' magnitude bits reversed. + let key = |l: &mut Self, x: V| { + let k31 = l.s.m.i32(31); + let sign = l.s.m.bin(c, Bin::AShr, x, k31); + let flip = l.s.m.bin(c, Bin::And, sign, abs_mask); + l.s.m.bin(c, Bin::Xor, x, flip) + }; + let (dk, mk) = (key(self, data), key(self, mem)); + let take = self + .s + .m + .cmp(c, if max { pred::SGT } else { pred::SLT }, dk, mk); + let r = self.s.m.select(c, take, data, mem); + let (dn, mn) = (nan(self, data), nan(self, mem)); + // One NaN: the number; two quiet NaNs: the data. + let r = self.s.m.select(c, mn, data, r); + let both = self.s.m.bin(c, Bin::And, dn, mn); + let only_data = { + let t = self.s.m.bool(true); + let not_both = self.s.m.bin(c, Bin::Xor, both, t); + self.s.m.bin(c, Bin::And, dn, not_both) + }; + let r = self.s.m.select(c, only_data, mem, r); + // Signalling NaNs win, quieted: the data's first. + let qm = self.s.m.bin(c, Bin::Or, mem, quiet); + let sm = snan(self, mem); + let r = self.s.m.select(c, sm, qm, r); + let qd = self.s.m.bin(c, Bin::Or, data, quiet); + let sd = snan(self, data); + self.s.m.select(c, sd, qd, r) + } + + // ---- instructions ---- + // ---- instructions ---- + + fn inst(&mut self, b: usize, i: usize) -> Result<(), Stop> { + let inst: &'a Inst = &self.x.p.blocks[b].insts[i]; + let offset = inst.machine.offset; + let name = inst.name(); + self.local_ok = name.starts_with("s_bcnt1_i32_") + || name.starts_with("s_ff1_i32_") + || name.starts_with("v_mbcnt_"); + self.mask_ok = match self.mask_data { + MaskData::Console => true, + MaskData::Host => { + name.starts_with("s_bcnt1_i32_") + || name.starts_with("s_ff1_i32_") + || name.starts_with("v_mbcnt_") + || matches!( + name, + "s_cmp_eq_u32" | "s_cmp_lg_u32" | "s_cmp_eq_u64" | "s_cmp_lg_u64" + ) + } + // Mesh: only "do all lanes hold the first lane's value?" (`uniform_test`), which + // each host wave answers for itself. + MaskData::None => self.uniform_test(inst), + }; + let effect = matches!(inst.fields, Fields::Exp { .. }) + || matches!(inst.fields, Fields::Flat { .. }) && !name.starts_with("global_load_") + || name.contains("store") + || name.contains("atomic") + || name == "s_barrier" + || matches!(inst.fields, Fields::Ds { .. }) + && !(name.starts_with("ds_read") + || name.starts_with("ds_swizzle") + || name.contains("permute")); + if self.split_lds + && matches!(inst.fields, Fields::Ds { .. }) + && !(name.starts_with("ds_swizzle") || name.contains("permute")) + && self.lds_meet.as_ref().is_none_or(|(all, _)| all[b]) + { + // the two host waves of a console wave meet before each LDS access: what the other + // half wrote is visible, and what it still reads is not overwritten + let mode = self.s.m.i32(meeting_mode()); + let void = self.s.t.void; + self.s.op(self.cur, "barrier", Attr::NoDuplicate, void, 80, &[mode]); + } + let r = match &inst.fields { + Fields::Sop { .. } => self.sop(inst), + Fields::Sopp { .. } if name == "s_barrier" && self.no_barrier.contains(&b) => Ok(()), + Fields::Sopp { .. } if name == "s_barrier" => { + // Thread-group sync with a shared-memory fence, and a UAV + // fence when the program writes UAVs (the waits before an + // s_barrier make those writes visible on the console). + let mut mode = if self.writes_uavs { 1 | 2 | 8 } else { 1 | 8 }; + // Without the wait for the group (bit 0) where not every + // lane arrives, or where the switch says so. + let waits = match super::group_sync() { + 0 => false, + 1 => !self.fence_only.contains(&b), + _ => true, + }; + if !waits { + mode &= !1; + } + let mode = self.s.m.i32(mode); + let void = self.s.t.void; + self.s + .op(self.cur, "barrier", Attr::NoDuplicate, void, 80, &[mode]); + Ok(()) + } + Fields::Sopp { .. } => Ok(()), + Fields::Smem { .. } => self.smem(inst, (b, i)), + Fields::Valu(_) if name.starts_with("v_interp_") => self.interp(inst, (b, i)), + Fields::Valu(_) => self.valu(inst, b, i), + Fields::Vintrp { .. } => self.interp(inst, (b, i)), + // The ray and node test. A failure is a refusal at once: an + // instruction without a side effect otherwise only stops the + // program where its results are needed, and two trace programs + // came out without their test that way. + Fields::Image { .. } if name.starts_with("image_bvh") => { + return self + .bvh(inst, b, i) + .map_err(|why| unsupported(offset, why)); + } + Fields::Image { .. } => self.image(inst, b, i), + Fields::Buffer { .. } => self.buffer(inst, b, i), + Fields::Exp { .. } => self.export(b, i), + Fields::Ds { .. } => self.ds(inst, b, i), + Fields::Flat { .. } if name.starts_with("global_") => self.flat(inst, b, i), + Fields::Flat { .. } => Err("flat memory"), + }; + match r { + Ok(()) => Ok(()), + Err(why) if effect => Err(unsupported(offset, why)), + Err(why) => { + for &(_, v) in &inst.writes { + self.vals.insert(v, Val::Missing(why)); + } + Ok(()) + } + } + } + + /// The two host waves of a console wave meet (a group barrier with a shared-memory + /// fence): LDS writes before are seen by reads after. + fn lds_meeting(&mut self) { + let mode = self.s.m.i32(meeting_mode()); + let void = self.s.t.void; + self.s.op(self.cur, "barrier", Attr::NoDuplicate, void, 80, &[mode]); + } + + /// Whether `v` is a register no program reads as a number: a descriptor dword without + /// a host value ([`Self::stale`]), a lane mask's dword (outside compute, where a ballot + /// gives the mask as data), or a join of only such values. Compiled code joins numbers + /// with numbers: where one of these meets numbers at a join, the register is dead on + /// that path (a variable set in one arm of a branch, its use behind a flag kept in a + /// VGPR). + fn dead(&self, v: Value, seen: &mut Vec) -> bool { + if self.stale.contains(&v) { + return true; + } + let st = self.x.st; + if self.mask_data != MaskData::Console + && (st.masks.contains_key(&v) || st.highs.contains_key(&v)) + { + return true; + } + let Some(&(b, i)) = self.phi_at.get(&v) else { + return false; + }; + if seen.contains(&v) { + return true; + } + seen.push(v); + self.x.p.blocks[b].phis[i] + .args + .iter() + .all(|&a| self.dead(a, seen)) + } + + /// `s_bcnt1_i32_b*` of the lanes that differ from the first lane's value: + /// `v_readfirstlane_b32 s, v`, `v_cmp_eq_u32 m, s, v`, `s_xor_b* d, m, exec`. The + /// compiler tests a value for being the same in the whole wave this way, to take a + /// scalar path; both paths give each lane the same result, so the lanes of a host + /// wave may ask it of their own first lane, whatever the wave's size. + fn uniform_test(&self, inst: &Inst) -> bool { + let p = self.x.p; + let writer = |v: Value| -> Option<&'a Inst> { + let b = *self.def_block.get(&v)?; + p.blocks[b] + .insts + .iter() + .find(|i| i.writes.iter().any(|w| w.1 == v)) + }; + let scalar = |i: &Inst, op: &Operand| match *op { + Operand::Scalar { code, .. } if code != NULL && code != EXEC => i.read(Reg::S(code)), + _ => None, + }; + if !inst.name().starts_with("s_bcnt1_i32_") { + return false; + } + let Fields::Sop { src, .. } = &inst.fields else { + return false; + }; + let Some(xor) = src.first().and_then(|o| scalar(inst, o)).and_then(writer) else { + return false; + }; + let Fields::Sop { src, .. } = &xor.fields else { + return false; + }; + if !matches!(xor.name(), "s_xor_b64" | "s_xor_b32") + || !src + .iter() + .any(|o| matches!(o, Operand::Scalar { code: EXEC, .. })) + { + return false; + } + let Some(cmp) = src.iter().find_map(|o| scalar(xor, o)).and_then(writer) else { + return false; + }; + let Fields::Valu(f) = &cmp.fields else { + return false; + }; + if !matches!(cmp.name(), "v_cmp_eq_u32" | "v_cmp_eq_i32") || f.sdwa.is_some() || f.dpp.is_some() { + return false; + } + let lanes = f.src.iter().find_map(|o| match *o { + Operand::Vector { reg, .. } => cmp.read(Reg::V(reg)), + _ => None, + }); + let first = f.src.iter().find_map(|o| scalar(cmp, o)).and_then(writer); + lanes.is_some() + && first.is_some_and(|fl| { + fl.name() == "v_readfirstlane_b32" + && matches!(&fl.fields, Fields::Valu(g) + if matches!(g.src.first(), Some(&Operand::Vector { reg, .. }) + if fl.read(Reg::V(reg)) == lanes)) + }) + } + + fn is_mask(&self, v: Option) -> bool { + v.is_some_and(|v| self.x.st.masks.contains_key(&v)) + } + + fn sop(&mut self, inst: &Inst) -> Result<(), Why> { + let Fields::Sop { dst, src, imm } = &inst.fields else { + unreachable!() + }; + let name = inst.name(); + let scc = inst.write(Reg::Scc); + let dst_code = match dst { + Some(Operand::Scalar { code, .. }) => Some(*code), + _ => None, + }; + let lo = dst_code.and_then(|c| inst.write(Reg::S(c))); + if inst.write(Reg::S(EXEC)).is_some() || self.is_mask(lo) { + return Err(LANE_MASK); + } + if matches!( + name, + "s_setreg_imm32_b32" | "s_setreg_b32" | "s_swappc_b64" | "s_version" + ) || name.starts_with("s_waitcnt") + { + // shortcut: the float MODE register is not modelled; s_swappc_b64 is the + // vertex fetch call, whose results arrive as inputs. + return Err("a register the emitter does not model"); + } + if name == "s_getpc_b64" { + // The address of the next instruction is no number the host has: tables in + // the code are read by their tracked address. As a number the counter is + // that instruction's offset in the code, so an address paths join before + // one load is the byte in the code, whichever table each path took + // (resource tracking gives such a join as the computed term, with no base). + let z = self.s.m.i32(0); + let at = self.s.m.i32(inst.machine.offset as u32 + 4); + let hi = dst_code.and_then(|c| inst.write(Reg::S(c + 1))); + self.set(lo, Val::I32(at)); + self.set(hi, Val::I32(z)); + return Ok(()); + } + let c = self.cur; + let src32 = |l: &mut Self, k: usize| -> Result { + // SOPK arithmetic reads its destination as the first source. + if k == 0 && matches!(name, "s_addk_i32" | "s_mulk_i32") { + let d = dst.as_ref().ok_or("a missing operand")?; + return l.operand(inst, d); + } + let op = src.get(k).ok_or("a missing operand")?; + l.operand(inst, op) + }; + let sext16 = |l: &mut Self| l.s.m.i32(i32::from(imm.unwrap_or(0) as i16) as u32); + // Dword `h` of 64-bit source `k` (inline constants sign-extend). + let half = |l: &mut Self, k: usize, h: u8| -> Result { + match src.get(k) { + Some(&Operand::Scalar { code, .. }) if code != NULL => { + let v = inst.read(Reg::S(code + h)).ok_or("an unread operand")?; + l.i32_of(v) + } + Some(op) if h == 0 => l.operand(inst, op), + Some(Operand::Const(k)) => { + let x = crate::resource::inline(*k).ok_or("a special operand")?; + Ok(l.s.m.i32(if (x as i32) < 0 { u32::MAX } else { 0 })) + } + _ => Ok(l.s.m.i32(0)), + } + }; + if let Some(op) = name.strip_prefix("s_bitcmp") { + // SCC is whether bit src1 (mod 32, or mod 64 for the 64-bit form) + // of src0 is clear (bitcmp0) or set (bitcmp1). + let (bit, k31) = (src32(self, 1)?, self.s.m.i32(31)); + let idx = self.s.m.bin(c, Bin::And, bit, k31); + let word = if op.ends_with("_b64") { + let (a, b) = (half(self, 0, 0)?, half(self, 0, 1)?); + let k32 = self.s.m.i32(32); + let upper = self.s.m.bin(c, Bin::And, bit, k32); + let z = self.s.m.i32(0); + let upper = self.s.m.cmp(c, pred::NE, upper, z); + self.s.m.select(c, upper, b, a) + } else { + src32(self, 0)? + }; + let shifted = self.s.m.bin(c, Bin::LShr, word, idx); + let one = self.s.m.i32(1); + let tested = self.s.m.bin(c, Bin::And, shifted, one); + let want = self.s.m.i32(u32::from(op.starts_with('1'))); + let r = self.s.m.cmp(c, pred::EQ, tested, want); + self.set(scc, Val::Bit(r)); + return Ok(()); + } + if let Some(op) = name.strip_prefix("s_cmp_").filter(|o| o.ends_with("_u64")) { + // eq and lg only: both dwords. + let mut r = None; + for h in 0..2 { + let (a, b) = (half(self, 0, h)?, half(self, 1, h)?); + let e = self.s.m.cmp(c, pred::EQ, a, b); + r = Some(match r { + Some(x) => self.s.m.bin(c, Bin::And, x, e), + None => e, + }); + } + let mut r = r.expect("two dwords"); + if op.starts_with("lg") { + let t = self.s.m.bool(true); + r = self.s.m.bin(c, Bin::Xor, r, t); + } + self.set(scc, Val::Bit(r)); + return Ok(()); + } + if let Some(op) = name.strip_prefix("s_cmp_").or(name.strip_prefix("s_cmpk_")) { + let (a, b) = if name.starts_with("s_cmpk_") { + let b = if op.ends_with("_i32") { + sext16(self) + } else { + self.s.m.i32(u32::from(imm.unwrap_or(0))) + }; + (src32(self, 0)?, b) + } else { + if op.ends_with("64") { + return Err("a 64-bit scalar compare"); + } + (src32(self, 0)?, src32(self, 1)?) + }; + let signed = op.ends_with("_i32"); + let p = match &op[..2] { + "eq" => pred::EQ, + "lg" => pred::NE, + "gt" if signed => pred::SGT, + "ge" if signed => pred::SGE, + "lt" if signed => pred::SLT, + "le" if signed => pred::SLE, + "gt" => pred::IUGT, + "ge" => pred::IUGE, + "lt" => pred::IULT, + "le" => pred::IULE, + _ => return Err("a scalar compare"), + }; + let r = self.s.m.cmp(c, p, a, b); + self.set(scc, Val::Bit(r)); + return Ok(()); + } + let wide = name.ends_with("_b64") || name.ends_with("_u64") || name.ends_with("_i64"); + if wide { + let hi = dst_code.and_then(|c| inst.write(Reg::S(c + 1))); + let nonzero = |l: &mut Self, a: V, b: V| { + let o = l.s.m.bin(c, Bin::Or, a, b); + let z = l.s.m.i32(0); + l.s.m.cmp(c, pred::NE, o, z) + }; + return match name { + "s_bcnt1_i32_b64" => { + let (a, b) = (half(self, 0, 0)?, half(self, 0, 1)?); + let i32t = self.s.t.i32; + let na = self + .s + .op(c, "unaryBits.i32", Attr::ReadNone, i32t, 31, &[a]); + let nb = self + .s + .op(c, "unaryBits.i32", Attr::ReadNone, i32t, 31, &[b]); + let r = self.s.m.bin(c, Bin::Add, na, nb); + self.set(lo, Val::I32(r)); + let z = self.s.m.i32(0); + let s = self.s.m.cmp(c, pred::NE, r, z); + self.set(scc, Val::Bit(s)); + Ok(()) + } + "s_ff1_i32_b64" => { + // The lowest set bit; -1 for none (as DXIL's first bit low). + let (a, b) = (half(self, 0, 0)?, half(self, 0, 1)?); + let i32t = self.s.t.i32; + let fa = self + .s + .op(c, "unaryBits.i32", Attr::ReadNone, i32t, 32, &[a]); + let fb = self + .s + .op(c, "unaryBits.i32", Attr::ReadNone, i32t, 32, &[b]); + let (z, k32) = (self.s.m.i32(0), self.s.m.i32(32)); + let fb32 = self.s.m.bin(c, Bin::Add, fb, k32); + let none = self.s.m.cmp(c, pred::EQ, b, z); + let fb = self.s.m.select(c, none, fb, fb32); + let low = self.s.m.cmp(c, pred::NE, a, z); + let r = self.s.m.select(c, low, fa, fb); + self.set(lo, Val::I32(r)); + Ok(()) + } + "s_and_b64" | "s_or_b64" | "s_xor_b64" | "s_andn2_b64" | "s_orn2_b64" + | "s_nand_b64" | "s_nor_b64" | "s_xnor_b64" | "s_not_b64" => { + let ones = self.s.m.i32(u32::MAX); + let mut r = Vec::new(); + for h in 0..2u8 { + let a = half(self, 0, h)?; + let x = if name == "s_not_b64" { + self.s.m.bin(c, Bin::Xor, a, ones) + } else { + let mut b = half(self, 1, h)?; + if name.contains("n2") { + b = self.s.m.bin(c, Bin::Xor, b, ones); + } + let op = match &name[2..5] { + "and" | "nan" => Bin::And, + "or_" | "orn" | "nor" => Bin::Or, + _ => Bin::Xor, + }; + let x = self.s.m.bin(c, op, a, b); + if matches!(name, "s_nand_b64" | "s_nor_b64" | "s_xnor_b64") { + self.s.m.bin(c, Bin::Xor, x, ones) + } else { + x + } + }; + r.push(x); + } + self.set(lo, Val::I32(r[0])); + self.set(hi, Val::I32(r[1])); + let s = nonzero(self, r[0], r[1]); + self.set(scc, Val::Bit(s)); + Ok(()) + } + "s_lshl_b64" | "s_lshr_b64" | "s_ashr_i64" => { + let (a, b) = (half(self, 0, 0)?, half(self, 0, 1)?); + let n = src32(self, 1)?; + let i64t = self.s.m.int(64); + self.s.flags |= flags::INT64; + let a = self.s.m.cast(c, Cast::ZExt, a, i64t); + let b = self.s.m.cast(c, Cast::ZExt, b, i64t); + let k32 = self.s.m.int_const(i64t, 32); + let b = self.s.m.bin(c, Bin::Shl, b, k32); + let x = self.s.m.bin(c, Bin::Or, a, b); + let k63 = self.s.m.i32(63); + let n = self.s.m.bin(c, Bin::And, n, k63); + let n = self.s.m.cast(c, Cast::ZExt, n, i64t); + let op = match name { + "s_lshl_b64" => Bin::Shl, + "s_lshr_b64" => Bin::LShr, + _ => Bin::AShr, + }; + let r = self.s.m.bin(c, op, x, n); + let rl = self.s.m.cast(c, Cast::Trunc, r, self.s.t.i32); + let rh = self.s.m.bin(c, Bin::LShr, r, k32); + let rh = self.s.m.cast(c, Cast::Trunc, rh, self.s.t.i32); + self.set(lo, Val::I32(rl)); + self.set(hi, Val::I32(rh)); + let s = nonzero(self, rl, rh); + self.set(scc, Val::Bit(s)); + Ok(()) + } + "s_mov_b64" => { + // Each half by itself: two numbers that travel as a pair (two scalars + // parked in neighbouring VGPR lanes, say) need not both have a value. + for (h, v) in [(0, lo), (1, hi)] { + let val = match half(self, 0, h) { + Ok(a) => Val::I32(a), + Err(why) => Val::Missing(why), + }; + self.set(v, val); + } + Ok(()) + } + "s_cselect_b64" => { + let cond = self.scc_in(inst)?; + for (h, v) in [(0, lo), (1, hi)] { + let (a, b) = (half(self, 0, h)?, half(self, 1, h)?); + let r = self.s.m.select(c, cond, a, b); + self.set(v, Val::I32(r)); + } + Ok(()) + } + _ => Err(name), + }; + } + let m = &mut self.s.m; + let _ = m; + let (r, carry): (V, Option) = match name { + "s_mov_b32" => (src32(self, 0)?, None), + "s_movk_i32" => (sext16(self), None), + "s_cselect_b32" => { + let cond = self.scc_in(inst)?; + let (a, b) = (src32(self, 0)?, src32(self, 1)?); + (self.s.m.select(c, cond, a, b), None) + } + "s_brev_b32" => { + let a = src32(self, 0)?; + let r = self + .s + .op(c, "unary.i32", Attr::ReadNone, self.s.t.i32, 30, &[a]); + (r, None) + } + "s_not_b32" => { + let a = src32(self, 0)?; + let ones = self.s.m.i32(u32::MAX); + (self.s.m.bin(c, Bin::Xor, a, ones), None) + } + "s_add_u32" | "s_add_i32" | "s_addk_i32" => { + let a = src32(self, 0)?; + let b = if name == "s_addk_i32" { + sext16(self) + } else { + src32(self, 1)? + }; + let r = self.s.m.bin(c, Bin::Add, a, b); + let carry = if name == "s_add_u32" { + Some(self.s.m.cmp(c, pred::IULT, r, a)) + } else { + None + }; + (r, carry) + } + "s_sub_u32" | "s_sub_i32" => { + let (a, b) = (src32(self, 0)?, src32(self, 1)?); + let r = self.s.m.bin(c, Bin::Sub, a, b); + let carry = (name == "s_sub_u32").then(|| self.s.m.cmp(c, pred::IULT, a, b)); + (r, carry) + } + "s_addc_u32" | "s_subb_u32" => { + let (a, b) = (src32(self, 0)?, src32(self, 1)?); + let cin = self.scc_in(inst)?; + let (r, carry) = self.add_sub_carry(c, name == "s_addc_u32", a, b, Some(cin)); + (r, Some(carry)) + } + "s_mul_i32" | "s_mulk_i32" => { + let a = src32(self, 0)?; + let b = if name == "s_mulk_i32" { + sext16(self) + } else { + src32(self, 1)? + }; + (self.s.m.bin(c, Bin::Mul, a, b), None) + } + "s_mul_hi_u32" | "s_mul_hi_i32" => { + let (a, b) = (src32(self, 0)?, src32(self, 1)?); + (self.mul_hi(a, b, name.ends_with("i32")), None) + } + "s_flbit_i32_b32" | "s_flbit_i32" => { + // The first bit from the top (differing from the sign for + // the signed form), -1 for none: DXIL's first-bit-high. + let a = src32(self, 0)?; + let op = if name == "s_flbit_i32_b32" { 33 } else { 34 }; + let r = self + .s + .op(c, "unaryBits.i32", Attr::ReadNone, self.s.t.i32, op, &[a]); + (r, None) + } + "s_ff1_i32_b32" | "s_bcnt1_i32_b32" => { + // First set bit (-1 for zero, as DXIL's), or the bit count. + let a = src32(self, 0)?; + let op = if name == "s_ff1_i32_b32" { 32 } else { 31 }; + let r = self + .s + .op(c, "unaryBits.i32", Attr::ReadNone, self.s.t.i32, op, &[a]); + (r, None) + } + "s_bfe_u32" | "s_bfe_i32" => { + // src1: offset in bits 0-4, width in bits 16-22. + let (a, b) = (src32(self, 0)?, src32(self, 1)?); + let (k16, k127) = (self.s.m.i32(16), self.s.m.i32(0x7F)); + let w = self.s.m.bin(c, Bin::LShr, b, k16); + let w = self.s.m.bin(c, Bin::And, w, k127); + (self.bfe(a, b, w, name == "s_bfe_i32"), None) + } + "s_and_b32" | "s_or_b32" | "s_xor_b32" | "s_andn2_b32" | "s_orn2_b32" + | "s_nand_b32" | "s_nor_b32" | "s_xnor_b32" => { + let (a, mut b) = (src32(self, 0)?, src32(self, 1)?); + let ones = self.s.m.i32(u32::MAX); + if name.contains("n2") { + b = self.s.m.bin(c, Bin::Xor, b, ones); + } + let op = match &name[2..5] { + "and" | "nan" => Bin::And, + "or_" | "orn" | "nor" => Bin::Or, + _ => Bin::Xor, + }; + let mut r = self.s.m.bin(c, op, a, b); + if matches!(name, "s_nand_b32" | "s_nor_b32" | "s_xnor_b32") { + r = self.s.m.bin(c, Bin::Xor, r, ones); + } + (r, None) + } + "s_lshl_b32" | "s_lshr_b32" | "s_ashr_i32" => { + let (a, b) = (src32(self, 0)?, src32(self, 1)?); + let k31 = self.s.m.i32(31); + let b = self.s.m.bin(c, Bin::And, b, k31); + let op = match name { + "s_lshl_b32" => Bin::Shl, + "s_lshr_b32" => Bin::LShr, + _ => Bin::AShr, + }; + (self.s.m.bin(c, op, a, b), None) + } + "s_lshl1_add_u32" | "s_lshl2_add_u32" | "s_lshl3_add_u32" | "s_lshl4_add_u32" => { + let (a, b) = (src32(self, 0)?, src32(self, 1)?); + let k = self.s.m.i32(u32::from(name.as_bytes()[6] - b'0')); + let t = self.s.m.bin(c, Bin::Shl, a, k); + (self.s.m.bin(c, Bin::Add, t, b), None) + } + "s_min_u32" | "s_max_u32" | "s_min_i32" | "s_max_i32" => { + let (a, b) = (src32(self, 0)?, src32(self, 1)?); + let p = match name { + "s_min_u32" => pred::IULT, + "s_max_u32" => pred::IUGT, + "s_min_i32" => pred::SLT, + _ => pred::SGT, + }; + let t = self.s.m.cmp(c, p, a, b); + (self.s.m.select(c, t, a, b), None) + } + "s_abs_i32" => { + let a = src32(self, 0)?; + let z = self.s.m.i32(0); + let neg = self.s.m.cmp(c, pred::SLT, a, z); + let n = self.s.m.bin(c, Bin::Sub, z, a); + (self.s.m.select(c, neg, n, a), None) + } + "s_bitset0_b32" | "s_bitset1_b32" => { + // Sets (clears) bit src[4:0] of the destination it reads. + let old = self.operand(inst, dst.as_ref().ok_or("a missing operand")?)?; + let a = src32(self, 0)?; + let (k31, one) = (self.s.m.i32(31), self.s.m.i32(1)); + let a = self.s.m.bin(c, Bin::And, a, k31); + let bit = self.s.m.bin(c, Bin::Shl, one, a); + if name == "s_bitset1_b32" { + (self.s.m.bin(c, Bin::Or, old, bit), None) + } else { + let ones = self.s.m.i32(u32::MAX); + let nb = self.s.m.bin(c, Bin::Xor, bit, ones); + (self.s.m.bin(c, Bin::And, old, nb), None) + } + } + "s_bfm_b32" => { + let (a, b) = (src32(self, 0)?, src32(self, 1)?); + let k31 = self.s.m.i32(31); + let one = self.s.m.i32(1); + let a = self.s.m.bin(c, Bin::And, a, k31); + let b = self.s.m.bin(c, Bin::And, b, k31); + let m = self.s.m.bin(c, Bin::Shl, one, a); + let m = self.s.m.bin(c, Bin::Sub, m, one); + (self.s.m.bin(c, Bin::Shl, m, b), None) + } + _ => return Err(name), + }; + self.set(lo, Val::I32(r)); + if let Some(scc) = scc { + let val = match carry { + Some(k) => Val::Bit(k), + None if matches!( + name, + "s_mov_b32" + | "s_movk_i32" + | "s_cselect_b32" + | "s_brev_b32" + | "s_mul_i32" + | "s_mulk_i32" + ) => + { + return Ok(()); + } + None if name.starts_with("s_add") || name.starts_with("s_sub") => { + Val::Missing("the carry of a scalar operation") + } + None => { + let z = self.s.m.i32(0); + Val::Bit(self.s.m.cmp(c, pred::NE, r, z)) + } + }; + self.vals.insert(scc, val); + } + Ok(()) + } + + /// `a + b (+ cin)` or `a - b (- cin)` with the carry (borrow) out, as the + /// scalar and vector add-with-carry instructions set it. + fn add_sub_carry(&mut self, c: usize, add: bool, a: V, b: V, cin: Option) -> (V, V) { + let op = if add { Bin::Add } else { Bin::Sub }; + let mut r = self.s.m.bin(c, op, a, b); + // Without a carry in: a + b wraps below a; a - b borrows when a < b. + let mut carry = if add { + self.s.m.cmp(c, pred::IULT, r, a) + } else { + self.s.m.cmp(c, pred::IULT, a, b) + }; + if let Some(cin) = cin { + let one = self.s.m.cast(c, Cast::ZExt, cin, self.s.t.i32); + let t = r; + r = self.s.m.bin(c, op, t, one); + // The carry in carries on when the partial result is all ones + // (add) or zero (sub). + let edge = self.s.m.i32(if add { u32::MAX } else { 0 }); + let at_edge = self.s.m.cmp(c, pred::EQ, t, edge); + let more = self.s.m.bin(c, Bin::And, cin, at_edge); + carry = self.s.m.bin(c, Bin::Or, carry, more); + } + (r, carry) + } + + fn scc_in(&mut self, inst: &Inst) -> Result { + let v = inst.read(Reg::Scc).ok_or("an unread SCC")?; + match self.get(v)? { + Val::Bit(x) => Ok(x), + _ => Err("SCC without a value"), + } + } + + fn smem(&mut self, inst: &Inst, site: Site) -> Result<(), Why> { + let Fields::Smem { + data, + offset, + soffset, + .. + } = &inst.fields + else { + unreachable!() + }; + let name = inst.name(); + if let Some(a) = self.scalar.get(&site).copied().filter(|a| a.param == CODE) { + return self.code_smem(inst, a); + } + if self.scalar.get(&site).is_some_and(|a| a.param == MEMORY) { + return self.memory_smem(inst); + } + let Some(rest) = name.strip_prefix("s_buffer_load_dword") else { + return self.descriptor_data(inst, site); + }; + let count = match rest { + "" => 1, + "x2" => 2, + "x4" => 4, + "x8" => 8, + "x16" => 16, + _ => return Err("a scalar buffer load"), + }; + let Some(Operand::Scalar { code, .. }) = *data else { + return Err("a scalar buffer load"); + }; + let src = self + .descriptors + .get(&(site, false)) + .copied() + .ok_or("an untracked descriptor")?; + let kind = self.used_kind(src); + let c = self.cur; + let (base, extra) = self.built_offset(src)?; + let offset = &((*offset as u32).wrapping_add(base) as i32); + let mut addr = self.s.m.i32(*offset as u32); + if let Some(x) = extra { + addr = self.s.m.bin(c, Bin::Add, addr, x); + } + if !matches!(soffset, Operand::Scalar { code: NULL, .. }) { + let so = self.operand(inst, soffset)?; + addr = self.s.m.bin(c, Bin::Add, addr, so); + } + if matches!(src, Source::Built { address, .. } if address.param == CODE) { + // A descriptor built around a table in the code. + for k in 0..count { + let off = self.s.m.i32(4 * k); + let a = self.s.m.bin(c, Bin::Add, addr, off); + let x = self.code_dword(a)?; + self.write(inst, Reg::S(code + k as u8), x, None); + } + return Ok(()); + } + // A buffer the program picks from the view heap by an index it + // computes (`ResourceHeap`) has no used-resource entry, and the + // heap holds a buffer view there, not a constant buffer: read as + // raw bytes, as a table's SRV is below. Read as a constant buffer + // (the host's validation: "Descriptor Type in Heap: SRV, Register + // Type: CBV", heap index 17) the loads gave nothing: + // the title's meshlet culling (BatchCullMeshlets, + // BatchCullPreSkinnedMeshlets, BatchCullBatchCSMeshlets) reads its + // batch records, mesh headers and instance transforms this way, so + // it passed no meshlet and every indirect mesh draw ran empty. + // The host's table of strides by heap slot tells a buffer view + // (not 0) from anything else, which is still read as a constant + // buffer; only the load that fits the slot runs. + let picked = match kind { + None => self.slot_stride(src)?, + Some(_) => None, + }; + if let Some(stride) = picked { + let zero = self.s.m.i32(0); + let is_buffer = self.s.m.cmp(self.cur, pred::NE, stride, zero); + let at = self.begin_guarded(Some(is_buffer)); + let h = self.handle(site, src, false, (11, 0))?; + let mut raw = Vec::new(); + for k in 0..count { + let b = self.cur; + let off = self.s.m.i32(4 * k); + let a = self.s.m.bin(b, Bin::Add, addr, off); + let mask = self.s.m.i8(1); + let (u, al) = (self.s.m.undef(self.s.t.i32), self.s.m.i32(4)); + let r = self.s.op( + b, + "rawBufferLoad.f32", + Attr::ReadOnly, + self.s.t.res_ret, + 139, + &[h, a, u, mask, al], + ); + let x = self.s.m.extract(b, r, 0); + let x = self.as_int(x); + raw.push((x, zero)); + } + let raw = self.end_guarded(at, &raw); + let other = self.s.m.cmp(self.cur, pred::EQ, stride, zero); + let at = self.begin_guarded(Some(other)); + let h = self.handle(site, src, false, (13, 0x1_0000))?; + let mut both = Vec::new(); + for (k, &r) in raw.iter().enumerate() { + let b = self.cur; + let off = self.s.m.i32(4 * k as u32); + let a = self.s.m.bin(b, Bin::Add, addr, off); + let x = self.cbuffer_dword(h, a); + both.push((x, r)); + } + let both = self.end_guarded(at, &both); + for (k, x) in both.into_iter().enumerate() { + self.write(inst, Reg::S(code + k as u8), x, None); + } + return Ok(()); + } + if matches!(kind, Some(u) if u.kind == ResourceType::Srv) { + let h = self.handle(site, src, false, (11, 0))?; + for k in 0..count { + let off = self.s.m.i32(4 * k); + let a = self.s.m.bin(c, Bin::Add, addr, off); + let mask = self.s.m.i8(1); + let (u, al) = (self.s.m.undef(self.s.t.i32), self.s.m.i32(4)); + let r = self.s.op( + c, + "rawBufferLoad.f32", + Attr::ReadOnly, + self.s.t.res_ret, + 139, + &[h, a, u, mask, al], + ); + let x = self.s.m.extract(c, r, 0); + let x = self.as_int(x); + self.write(inst, Reg::S(code + k as u8), x, None); + } + return Ok(()); + } + let h = self.handle(site, src, false, (13, 0x1_0000))?; + let constant = match addr { + V::Const(_) + if matches!(soffset, Operand::Scalar { code: NULL, .. }) && extra.is_none() => + { + Some(*offset as u32) + } + _ => None, + }; + let mut rows: HashMap = HashMap::new(); + for k in 0..count { + let x = match constant { + Some(base) => { + let byte = base + 4 * k; + let row = match rows.get(&(byte >> 4)) { + Some(&r) => r, + None => { + let ri = self.s.m.i32(byte >> 4); + let r = self.s.op( + c, + "cbufferLoadLegacy.i32", + Attr::ReadOnly, + self.s.t.cbuf_ret, + 59, + &[h, ri], + ); + rows.insert(byte >> 4, r); + r + } + }; + self.s.m.extract(c, row, (byte >> 2) & 3) + } + None => { + let off = self.s.m.i32(4 * k); + let a = self.s.m.bin(c, Bin::Add, addr, off); + self.cbuffer_dword(h, a) + } + }; + self.write(inst, Reg::S(code + k as u8), x, None); + } + Ok(()) + } + + /// A descriptor load (`s_load_dword*` from a table or heap) whose dwords + /// the code also reads as numbers: the console compiler computes sizes + /// from descriptor bits (an image's width, height, depth, levels; a + /// buffer's record count) instead of querying them. Those fields are + /// rebuilt from the host view's dimensions in the GFX10 layout (image + /// dword 1 bits 30-31 and dword 2 bits 0-13 width - 1, dword 2 bits + /// 14-29 height - 1, dword 3 identity swizzle, last level at 16, type at + /// 28, dword 4 depth or layers - 1; buffer dword 2 the record count). + // shortcut: the base level reads 0 (the host view starts at its own + // level 0, so sizes the code shifts by it come out right) and the other + // dwords (addresses, formats, tiling) have no host value: reading them + // stops the program. + fn descriptor_data(&mut self, inst: &Inst, site: Site) -> Result<(), Why> { + const OTHER: Why = "a descriptor's address or format read as data"; + let Fields::Smem { + data: Some(Operand::Scalar { code, .. }), + .. + } = inst.fields + else { + return Err("a scalar memory read as data"); + }; + let count = match inst.name().strip_prefix("s_load_dword") { + Some("") => 1u32, + Some("x2") => 2, + Some("x4") => 4, + Some("x8") => 8, + Some("x16") => 16, + _ => return Err("a scalar memory read as data"), + }; + // How the program uses the descriptor tells the view's kind: an image or buffer + // instruction before a scalar buffer load, which reads any buffer. + let x = self.x; + let uses = |of: Site| { + x.res + .descriptors + .iter() + .filter(|d| d.role == Role::Resource) + .filter_map(move |d| { + d.source.leaves().into_iter().find_map(|l| match *l { + Source::Loaded { load, first } if load == of => Some((d.site, first)), + _ => None, + }) + }) + }; + let by_scalar_load = |u: &(Site, u8)| { + matches!(x.p.blocks[u.0.0].insts[u.0.1].fields, Fields::Smem { .. }) + }; + let use_of = |of: Site| uses(of).find(|u| !by_scalar_load(u)).or_else(|| uses(of).next()); + // The console compiler loads a descriptor again wherever it needs it, and for a + // size it reads the dwords of a load that nothing uses as a descriptor (a texture + // picked from the heap by an index held per lane: one load for its width, one for + // its base level, one for each read of the image). Another load of as many dwords + // from the same address reads the same descriptor, so what uses that one tells + // this one's kind. The handle is still made from this load's own operands, which + // hold here. + let address = self.scalar.get(&site).copied(); + let twin = || { + let a = address?; + let same = |s: Site| x.p.blocks[s.0].insts[s.1].name() == inst.name(); + x.res + .scalar + .iter() + .filter(|(s, b)| *s != site && *b == a && same(*s)) + .find_map(|(s, _)| use_of(*s)) + }; + let use_at = use_of(site).or_else(twin); + // A descriptor nothing uses as one, whose size the code reads all the same (a + // texture picked from the heap by an index in a constant buffer, its width and + // height turned into a texel size; a buffer tested for being empty by its record + // count): the kind from its dwords and its used-resource entry. + let unused = if use_at.is_none() { + self.unused_descriptor_kind(inst, site, code, count) + } else { + None + }; + let (first, props, image, uav, used) = if let Some(kind) = unused { + kind + } else { + let Some((at, first)) = use_at else { + // A descriptor kept per lane in VGPRs (`Resources::lane_copied`): the code only + // copies its dwords and compares them, lane against first lane, and every load + // that reaches those lanes reads one address. Each dword stands in as its place + // in the table, so the lanes compare equal as they do on the console. + if self.x.res.lane_copied.contains(&site) + && let Some(a) = self.scalar.get(&site).copied() + { + for k in 0..count { + let x = self.s.m.i32(a.offset / 4 + k); + self.write(inst, Reg::S(code + k as u8), x, None); + } + return Ok(()); + } + // A sampler's descriptor: no program reads its dwords as numbers, so where one + // meets numbers at a join the register is dead on that path (`dead`), as a + // descriptor's address or format is. + let sampler = x.res.descriptors.iter().any(|d| { + d.role == Role::Sampler + && d.source.leaves().into_iter().any( + |l| matches!(*l, Source::Loaded { load, .. } if load == site), + ) + }); + if sampler { + self.stale.extend(inst.writes.iter().map(|w| w.1)); + return Err("a sampler's descriptor read as data"); + } + // A buffer view the code only takes the address of, to walk + // the memory behind it (a ray-tracing structure): the address + // from the host, the other dwords have no value. + if count <= 4 + && let Some((lo, hi)) = self.view_address(site) + { + for k in 0..count { + let reg = Reg::S(code + k as u8); + match k { + 0 => self.write(inst, reg, lo, None), + 1 => self.write(inst, reg, hi, None), + _ => { + if let Some(v) = inst.write(reg) { + self.vals.insert(v, Val::Missing(OTHER)); + self.stale.insert(v); + } + } + } + } + return Ok(()); + } + if std::env::var_os("LEONIDA_DESC_WHY").is_some() { + eprintln!( + "DESC-WHY {:#x} {} scalar={:?} lane_copied={}", + inst.machine.offset, + inst.name(), + address, + self.x.res.lane_copied.contains(&site) + ); + } + return Err("a descriptor read only as data"); + }; + let src = Source::Loaded { load: site, first }; + let used = self.used_kind(&src); + let ui: &Inst = &self.x.p.blocks[at.0].insts[at.1]; + let un = ui.name(); + let uav = un.contains("store") + || un.contains("atomic") + || used.is_some_and(|u| u.kind == ResourceType::Uav); + let u = if uav { 0x1000 } else { 0 }; + let (props, image) = match &ui.fields { + // A ray-tracing structure in a buffer of the host: read raw. + Fields::Image { .. } if un.starts_with("image_bvh") => ((11, 0), None), + Fields::Image { dim, .. } => { + let kind = match dim { + 0 => 1, + 1 => 2, + 2 => 4, + 4 => 6, + 5 => 7, + _ => return Err("an image dimension (cube or MSAA)"), + }; + ((kind | u, 0x409), Some(kind)) + } + Fields::Buffer { idxen, format, .. } => { + let stride = used.map_or(0, |u| u.stride); + let props = if un.starts_with("buffer_load_format") + || un.starts_with("buffer_store_format") + { + (10 | u, 0x409) + } else if *idxen && format.is_none() && stride >= 4 && stride.is_multiple_of(4) { + (12 | u, stride) + } else { + (11 | u, 0) + }; + if used.is_some_and(|u| u.kind == ResourceType::Cbv) { + self.stale.extend(inst.writes.iter().map(|w| w.1)); + return Err("a constant buffer's descriptor read as data"); + } + (props, None) + } + // Read by scalar buffer loads alone: the raw view `smem` reads it through. + Fields::Smem { .. } if used.is_some_and(|u| u.kind == ResourceType::Srv) => { + ((11, 0), None) + } + // A constant buffer: nothing of its descriptor is a number. + Fields::Smem { .. } => { + self.stale.extend(inst.writes.iter().map(|w| w.1)); + return Err("a constant buffer's descriptor read as data"); + } + _ => return Err("a scalar memory read as data"), + }; + (first, props, image, uav, used) + }; + let src = Source::Loaded { load: site, first }; + let h = self.handle(site, &src, false, props)?; + let c = self.cur; + let i32t = self.s.t.i32; + let dims = self.s.m.named_struct("dx.types.Dimensions", vec![i32t; 4]); + let mip = if image.is_some() && !uav { + self.s.m.i32(0) + } else { + self.s.m.undef(i32t) + }; + let d = self + .s + .op(c, "getDimensions", Attr::ReadOnly, dims, 72, &[h, mip]); + let field = |l: &mut Self, k: u32| l.s.m.extract(c, d, k); + let words: Vec<(u32, V)> = match image { + Some(kind) => { + let one = self.s.m.i32(1); + let w = field(self, 0); + let (height, depth) = match kind { + 1 => (one, one), + 2 => (field(self, 1), one), + 6 => (one, field(self, 1)), + _ => (field(self, 1), field(self, 2)), + }; + let levels = if uav { one } else { field(self, 3) }; + let less = |l: &mut Self, x: V| l.s.m.bin(c, Bin::Sub, x, one); + let (w, height, depth, levels) = ( + less(self, w), + less(self, height), + less(self, depth), + less(self, levels), + ); + let k = |l: &mut Self, v: u32| l.s.m.i32(v); + let (k30, k2, k14, k16, mask) = ( + k(self, 30), + k(self, 2), + k(self, 14), + k(self, 16), + k(self, 0x3FFF), + ); + let d1 = self.s.m.bin(c, Bin::Shl, w, k30); + let hi = self.s.m.bin(c, Bin::LShr, w, k2); + let hi = self.s.m.bin(c, Bin::And, hi, mask); + let ht = self.s.m.bin(c, Bin::Shl, height, k14); + let d2 = self.s.m.bin(c, Bin::Or, hi, ht); + let ty = [0, 8, 9, 0, 10, 0, 12, 13][kind as usize]; + let base = k(self, 0xFAC | ty << 28); + let last = self.s.m.bin(c, Bin::Shl, levels, k16); + let d3 = self.s.m.bin(c, Bin::Or, base, last); + vec![(1, d1), (2, d2), (3, d3), (4, depth)] + } + None => { + // A raw view counts bytes; the descriptor's record count is in elements. + let n = field(self, 0); + let stride = used.map_or(0, |u| u.stride); + let n = if props.0 & 0xFF == 11 && stride > 1 { + let k = self.s.m.i32(stride); + self.s.m.bin(c, Bin::UDiv, n, k) + } else { + n + }; + let mut words = vec![(2, n)]; + // Its address too, where the code computes with it and the + // host can tell it. + let computed = (0..2u8).any(|k| { + inst.write(Reg::S(code + first + k)) + .is_some_and(|v| self.computed_with(v, 6)) + }); + // (A descriptor nothing uses as one gets it whenever the host can tell it, as + // a buffer whose address alone is read does.) + if first == 0 + && (computed || unused.is_some()) + && let Some((lo, hi)) = self.view_address(site) + { + words.extend([(0, lo), (1, hi)]); + } + words + } + }; + for k in 0..count { + let rel = k.wrapping_sub(u32::from(first)); + match words.iter().find(|w| w.0 == rel) { + Some(&(_, x)) => self.write(inst, Reg::S(code + k as u8), x, None), + None => { + if let Some(v) = inst.write(Reg::S(code + k as u8)) { + self.vals.insert(v, Val::Missing(OTHER)); + self.stale.insert(v); + } + } + } + } + Ok(()) + } + + /// What [`Self::descriptor_data`] makes of a descriptor load that nothing uses as a + /// descriptor but whose dwords the code reads: the first dword, the handle properties, + /// the image kind (none for a buffer), whether it is an unordered view, and its + /// used-resource entry. An image's eight dwords read as a 2D texture's, a buffer's four + /// as a raw view's where the code reads its record count (dword 2); none for anything + /// else (a constant buffer, a sampler, a buffer whose address alone is read). + // shortcut: an image whose kind nothing tells is taken for a 2D texture (the title's + // reads are texel sizes of 2D textures: puddle masks, shadow masks); a host view of + // another kind would answer its own sizes. + #[allow(clippy::type_complexity)] + fn unused_descriptor_kind( + &self, + inst: &Inst, + site: Site, + code: u8, + count: u32, + ) -> Option<(u8, (u32, u32), Option, bool, Option<&'a UsedResource>)> { + // Kept per lane and compared (`Resources::lane_copied`), or a sampler's: the cases + // `descriptor_data` handles on their own. + if self.x.res.lane_copied.contains(&site) + || self.x.res.descriptors.iter().any(|d| { + d.role == Role::Sampler + && d.source.leaves().into_iter().any( + |l| matches!(*l, Source::Loaded { load, .. } if load == site), + ) + }) + { + return None; + } + let used = self.used_kind(&Source::Loaded { + load: site, + first: 0, + }); + if used.is_some_and(|u| !matches!(u.kind, ResourceType::Srv | ResourceType::Uav)) { + return None; + } + let read = |k: u32| { + inst.write(Reg::S(code + k as u8)).is_some_and(|v| { + self.x + .p + .blocks + .iter() + .flat_map(|b| &b.insts) + .any(|i| i.reads.iter().any(|r| r.1 == v)) + }) + }; + let uav = used.is_some_and(|u| u.kind == ResourceType::Uav); + let u = if uav { 0x1000 } else { 0 }; + match count { + // width (dwords 1-2), height (2), levels (3), depth (4) + 8 if (1..5).any(read) && used.is_none_or(|u| u.dwords == 8) => { + Some((0, (2 | u, 0x409), Some(2), uav, used)) + } + // the record count + 4 if read(2) && used.is_none_or(|u| u.dwords == 4) => { + Some((0, (11 | u, 0), None, uav, used)) + } + _ => None, + } + } + + /// `s_load_dword*` from the program's constant table. + fn code_smem(&mut self, inst: &Inst, a: Address) -> Result<(), Why> { + let Fields::Smem { + data: Some(Operand::Scalar { code, .. }), + .. + } = inst.fields + else { + return Err("a scalar load"); + }; + let count = match inst.name().strip_prefix("s_load_dword") { + Some("") => 1u32, + Some("x2") => 2, + Some("x4") => 4, + Some("x8") => 8, + Some("x16") => 16, + _ => return Err("a scalar load from the code"), + }; + let c = self.cur; + let mut addr = self.s.m.i32(a.offset); + if let Some(value) = a.dynamic { + let mut d = self.i32_of(value)?; + // A term held per lane reached the address through + // `v_readfirstlane_b32`: the first lane's. + let per_lane = self.def_block.get(&value).is_some_and(|&b| { + let writes = |i: &Inst| i.writes.iter().any(|w| w.1 == value && matches!(w.0, Reg::V(_))); + self.x.p.blocks[b].insts.iter().any(writes) + }); + if per_lane { + self.s.flags |= flags::WAVE_OPS; + let i32t = self.s.t.i32; + d = self.s.op(c, "waveReadLaneFirst.i32", Attr::NoUnwind, i32t, 118, &[d]); + } + addr = self.s.m.bin(c, Bin::Add, addr, d); + } + for k in 0..count { + let off = self.s.m.i32(4 * k); + let at = self.s.m.bin(c, Bin::Add, addr, off); + let x = self.code_dword(at)?; + self.write(inst, Reg::S(code + k as u8), x, None); + } + Ok(()) + } + + /// The dword at a computed byte address of a constant buffer. + fn cbuffer_dword(&mut self, h: V, a: V) -> V { + let c = self.cur; + let four = self.s.m.i32(4); + let ri = self.s.m.bin(c, Bin::LShr, a, four); + let r = self.s.op( + c, + "cbufferLoadLegacy.i32", + Attr::ReadOnly, + self.s.t.cbuf_ret, + 59, + &[h, ri], + ); + let two = self.s.m.i32(2); + let three = self.s.m.i32(3); + let comp = self.s.m.bin(c, Bin::LShr, a, two); + let comp = self.s.m.bin(c, Bin::And, comp, three); + let mut x = self.s.m.extract(c, r, 0); + for j in 1..4 { + let e = self.s.m.extract(c, r, j); + let jc = self.s.m.i32(j); + let is = self.s.m.cmp(c, pred::EQ, comp, jc); + x = self.s.m.select(c, is, e, x); + } + x + } + + /// `channels` channels of the element at byte `off` of raw buffer `h`, + /// converted from the GFX10 buffer format `format` as the hardware's + /// typed loads do (channels past the format's read 0, 0, 0, 1). + // shortcut: the descriptor's channel swizzle is taken as the identity + // (it is for raw views and the descriptors code builds), elements of 4 + // bytes or more as dword-aligned. Norm formats divide, which the AMD + // driver does 1 ULP off the hardware's correctly rounded conversion for + // some values; correct it with an integer check if a title compares + // converted values exactly. + fn format_load(&mut self, h: V, off: V, format: u8, channels: u32) -> Result, Why> { + let (bits, numeric) = buffer_format(format).ok_or("a buffer format")?; + let c = self.cur; + let total: u32 = bits.iter().sum(); + let (u, align) = (self.s.m.undef(self.s.t.i32), self.s.m.i32(4)); + let load = |l: &mut Self, at: V, n: u32| -> Vec { + let mask = l.s.m.i8((1u8 << n) - 1); + let r = l.s.op( + c, + "rawBufferLoad.f32", + Attr::ReadOnly, + l.s.t.res_ret, + 139, + &[h, at, u, mask, align], + ); + (0..n) + .map(|k| { + let x = l.s.m.extract(c, r, k); + l.as_int(x) + }) + .collect() + }; + let words = if total < 32 { + // A byte or half inside the dword that holds it. + let (not3, three) = (self.s.m.i32(!3), self.s.m.i32(3)); + let at = self.s.m.bin(c, Bin::And, off, not3); + let w = load(self, at, 1)[0]; + let byte = self.s.m.bin(c, Bin::And, off, three); + let sh = self.s.m.bin(c, Bin::Shl, byte, three); + vec![self.s.m.bin(c, Bin::LShr, w, sh)] + } else { + load(self, off, total / 32) + }; + let float = |l: &mut Self, f: V| l.as_int(f); + let mut out = Vec::new(); + let mut at = 0; + for &w in bits { + let word = words[(at / 32) as usize]; + let field = if w == 32 { + word + } else { + let sh = self.s.m.i32(at % 32); + let t = self.s.m.bin(c, Bin::LShr, word, sh); + let m = self.s.m.i32((1 << w) - 1); + self.s.m.bin(c, Bin::And, t, m) + }; + at += w; + // Sign-extended from the field's top bit. + let signed = |l: &mut Self| { + if w == 32 { + return field; + } + let k = l.s.m.i32(32 - w); + let t = l.s.m.bin(c, Bin::Shl, field, k); + l.s.m.bin(c, Bin::AShr, t, k) + }; + let f32t = self.s.t.f32; + let x = match numeric { + Numeric::Unorm => { + let f = self.s.m.cast(c, Cast::UiToFp, field, f32t); + let max = self.s.m.f32((((1u64 << w) - 1) as f32).to_bits()); + let q = self.s.m.bin(c, Bin::SDiv, f, max); + float(self, q) + } + Numeric::Snorm => { + let s = signed(self); + let f = self.s.m.cast(c, Cast::SiToFp, s, f32t); + let max = self.s.m.f32((((1u64 << (w - 1)) - 1) as f32).to_bits()); + let q = self.s.m.bin(c, Bin::SDiv, f, max); + let lo = self.s.m.f32((-1.0f32).to_bits()); + let q = self.binary(35, q, lo); + float(self, q) + } + Numeric::Uscaled => { + let f = self.s.m.cast(c, Cast::UiToFp, field, f32t); + float(self, f) + } + Numeric::Sscaled => { + let s = signed(self); + let f = self.s.m.cast(c, Cast::SiToFp, s, f32t); + float(self, f) + } + Numeric::Uint => field, + Numeric::Sint => signed(self), + Numeric::Float if w == 32 => field, + Numeric::Float => { + let h = match half_shift(w) { + 0 => field, + k => { + let sh = self.s.m.i32(k); + self.s.m.bin(c, Bin::Shl, field, sh) + } + }; + let f = self + .s + .op(c, "legacyF16ToF32", Attr::ReadNone, f32t, 131, &[h]); + float(self, f) + } + }; + out.push(x); + } + let one = match numeric { + Numeric::Uint | Numeric::Sint => 1, + _ => 1.0f32.to_bits(), + }; + for k in out.len() as u32..channels { + out.push(self.s.m.i32(if k == 3 { one } else { 0 })); + } + out.truncate(channels as usize); + Ok(out) + } + + /// The byte offset a buffer descriptor built around a root descriptor adds + /// (constant and computed parts); none for other descriptors. + fn built_offset(&mut self, src: &Source) -> Result<(u32, Option), Why> { + match src { + Source::Built { address, .. } => { + let mut x = match address.dynamic { + Some(v) => Some(self.i32_of(v)?), + None => None, + }; + if let Some(bias) = self.root_bias(address.param) { + x = Some(match x { + Some(d) => self.s.m.bin(self.cur, Bin::Add, d, bias), + None => bias, + }); + } + Ok((address.offset, x)) + } + _ => Ok((0, None)), + } + } + + /// For a root view the host binds as a raw view that may begin before + /// the title's address (`shader.rs` `USER_VIEW_BIAS`): the bytes to add + /// to offsets through it. Every root UAV, and the root SRVs of programs + /// with a spilled user-data table (the others keep the views they + /// have). + fn root_bias(&mut self, param: usize) -> Option { + use super::shader::USER_VIEW_BIAS; + let rp = *self.x.native.layout.get(param)?; + if rp.root != RootType::Descriptor { + return None; + } + let kind = self + .x + .native + .used + .iter() + .find(|u| u.user_data == rp.user_data) + .map(|u| u.kind); + let biased = match kind { + Some(ResourceType::Uav) => true, + Some(ResourceType::Srv) => crate::spill::is_spilled(self.x.native), + _ => false, + }; + biased.then(|| self.host_word(RootType::Other(USER_VIEW_BIAS), rp.slot, 0)) + } + + /// The used-resource entry a descriptor loaded from a table falls in. + fn used_kind(&self, src: &Source) -> Option<&'a UsedResource> { + if let Source::Phi { args, .. } | Source::Select { args, .. } | Source::Lanes { args, .. } = + src + { + return self.used_kind(args.first()?); + } + if let Source::LanePhi { args, .. } = src { + return args.iter().flatten().find_map(|a| self.used_kind(a)); + } + if let Source::Built { address, .. } = src { + let rp = self.x.native.layout.get(address.param)?; + return self + .x + .native + .used + .iter() + .find(|u| u.root == RootType::Descriptor && u.user_data == rp.user_data); + } + let (Source::Loaded { load, first } | Source::Fetched { load, first }) = src else { + return None; + }; + let a = self.scalar.get(load)?; + let rp = self.x.native.layout.get(a.param)?; + if rp.root != RootType::Table { + return None; + } + let dword = (a.offset / 4) + u32::from(*first); + self.x + .native + .used + .iter() + .filter(|u| { + u.root == RootType::Table + && u.user_data == rp.user_data + && u.table_offset_dwords <= dword + }) + .max_by_key(|u| u.table_offset_dwords) + } + + /// A handle for the descriptor `src` read at `site`. + fn handle( + &mut self, + site: Site, + src: &Source, + sampler: bool, + props: (u32, u32), + ) -> Result { + match src { + Source::Loaded { load, first } => { + let key = (self.cur, *load, *first, sampler, props); + if let Some(&h) = self.handles.get(&key) { + return Ok(h); + } + let index = self.heap_index(*load, *first, sampler)?; + // A waterfall loop's load at the first lane's offset reads + // each lane's own entry (see `resource::Waterfall`). + let per_lane = self.x.res.waterfall.loads.contains(load); + let h = self + .s + .heap_handle(self.cur, index, sampler, per_lane, props); + self.handles.insert(key, h); + Ok(h) + } + Source::Constant(words) if sampler => { + let words: [u32; 4] = words + .get(..4) + .and_then(|w| w.try_into().ok()) + .ok_or("a sampler constant")?; + let n = match self.samplers.iter().position(|w| *w == words) { + Some(n) => n, + None => { + self.samplers.push(words); + self.samplers.len() - 1 + } + }; + if props.0 & 0x8000 != 0 { + // shortcut: one sampler used with and without comparison + // would need two static samplers; it becomes a comparison one. + self.s.cmp_samplers |= 1 << n; + } + Ok(self.s.sampler_handle(self.cur, n as u32)) + } + Source::Constant(_) => Err("a constant resource descriptor"), + Source::Built { address, .. } => { + let rp = *self + .x + .native + .layout + .get(address.param) + .ok_or("a descriptor built around a table in the code")?; + let kind = self + .x + .native + .used + .iter() + .find(|u| u.user_data == rp.user_data) + .map(|u| u.kind); + match (rp.root, kind, props.0) { + (RootType::Descriptor, Some(ResourceType::Cbv) | None, 13) => { + Ok(self.s.root_cbv_handle(rp.slot)) + } + (RootType::Descriptor, Some(ResourceType::Srv), 11) => { + Ok(self.s.root_srv_handle(rp.slot)) + } + // A root UAV: a raw buffer whether the access reads + // (11) or writes (11 with the UAV bit). Indexed + // accesses reach here as raw ones at index times the + // entry's stride (`buffer`). + (RootType::Descriptor, Some(ResourceType::Uav), 11 | 0x100b) => { + Ok(self.s.root_uav_handle(rp.slot)) + } + (RootType::Descriptor, Some(ResourceType::Srv), 0x100b) => { + Err("a write through a root SRV") + } + _ => Err("a typed root view"), + } + } + Source::Phi { block, args } => { + let _ = site; + let phi = self.descriptor_phi(*block, args, sampler, 8)?; + Ok(self.s.heap_handle(self.cur, phi, sampler, false, props)) + } + Source::Select { scc, args } => { + // The heap index of each choice, picked by SCC (uniform). + let [ + Source::Loaded { load: a, first: fa }, + Source::Loaded { load: b, first: fb }, + ] = args[..] + else { + return Err("a descriptor chosen by a condition"); + }; + let cond = match self.get(*scc)? { + Val::Bit(x) => x, + _ => return Err("SCC without a value"), + }; + let set = self.heap_index(a, fa, sampler)?; + let clear = self.heap_index(b, fb, sampler)?; + let index = self.s.m.select(self.cur, cond, set, clear); + Ok(self.s.heap_handle(self.cur, index, sampler, false, props)) + } + Source::Fetched { .. } | Source::Lanes { .. } | Source::LanePhi { .. } => { + // A descriptor each lane has its own of (a waterfall loop + // reads it from the first active lane): each lane's heap + // index, non-uniform. + let index = self.lane_heap_index(src, sampler)?; + Ok(self.s.heap_handle(self.cur, index, sampler, true, props)) + } + } + } + + /// The heap index a descriptor phi picks. Each predecessor computes its + /// heap index at its end and the join picks one with a phi; a + /// predecessor whose descriptor is itself chosen by control flow (a + /// phi of an earlier join, which dominates it) gives that join's phi, + /// at most `depth` joins deep. + fn descriptor_phi( + &mut self, + block: usize, + args: &[Source], + sampler: bool, + depth: u32, + ) -> Result { + const WHY: Why = "a descriptor chosen by control flow"; + let p = self.x.p; + let mut incoming = Vec::new(); + for (&q, arg) in p.blocks[block].preds.iter().zip(args) { + if self.block[q].is_none() { + continue; + } + let tail = self.tail[q].ok_or(WHY)?; + let at = self.edges.get(&(q, block)).copied().unwrap_or(tail); + let index = match arg { + Source::Loaded { load, first } => { + let here = std::mem::replace(&mut self.cur, at); + let index = self.heap_index(*load, *first, sampler); + self.cur = here; + index? + } + Source::Phi { block: inner, args: inner_args } if depth > 0 => { + self.descriptor_phi(*inner, inner_args, sampler, depth - 1)? + } + _ => return Err(WHY), + }; + incoming.push((index, at)); + } + let join = self.block[block].ok_or(WHY)?; + let phi = self.s.m.phi(join, self.s.t.i32); + self.s.m.set_phi(phi, incoming); + Ok(phi) + } + + /// The bytes per element of the buffer view `src` names, if the program + /// picks it from the view heap at an index it computes (root type + /// `ResourceHeap`): read from the host's table by heap slot in the + /// current block. + fn slot_stride(&mut self, src: &Source) -> Result, Why> { + let Source::Loaded { load, first } = src else { + return Ok(None); + }; + let heap = self + .scalar + .get(load) + .and_then(|a| self.x.native.layout.get(a.param)) + .is_some_and(|p| p.root == RootType::ResourceHeap); + if !heap { + return Ok(None); + } + let key = (self.cur, *load, *first); + if let Some(&v) = self.strides.get(&key) { + return Ok(Some(v)); + } + let c = self.cur; + let slot = self.heap_index(*load, *first, false)?; + // Inside the table whatever the index (lanes that do not run + // compute one too): a root view has no bounds of its own. + let last = self.s.m.i32(super::shader::SLOT_STRIDES_COUNT - 1); + let i32t = self.s.t.i32; + let slot = self.s.op(c, "binary.i32", Attr::ReadNone, i32t, 40, &[slot, last]); + self.s.m.tag(slot, Tag::Clamp); + let two = self.s.m.i32(2); + let byte = self.s.m.bin(c, Bin::Shl, slot, two); + let h = self.s.root_srv_handle(super::shader::SLOT_STRIDES); + let iu = self.s.m.undef(self.s.t.i32); + let mask = self.s.m.i8(1); + let align = self.s.m.i32(4); + let r = self.s.op( + c, + "rawBufferLoad.f32", + Attr::ReadOnly, + self.s.t.res_ret, + 139, + &[h, byte, iu, mask, align], + ); + let f = self.s.m.extract(c, r, 0); + let v = self.as_int(f); + self.strides.insert(key, v); + Ok(Some(v)) + } + + /// The heap index of a descriptor that may differ between lanes, + /// computed in the current block (or, chosen by control flow, at the + /// join). + fn lane_heap_index(&mut self, src: &Source, sampler: bool) -> Result { + match src { + Source::Loaded { load, first } => self.heap_index(*load, *first, sampler), + Source::Fetched { load, first } => self.fetched_index(*load, *first, sampler), + Source::Lanes { mask, args } | Source::Select { scc: mask, args } => { + let [a, b] = &args[..] else { + return Err("a descriptor chosen per lane"); + }; + let cond = if matches!(src, Source::Lanes { .. }) { + let &m = self + .x + .st + .masks + .get(mask) + .ok_or("a descriptor chosen per lane by an untracked mask")?; + self.boolean(m, self.cur)? + } else { + match self.get(*mask)? { + Val::Bit(x) => x, + _ => return Err("SCC without a value"), + } + }; + let set = self.lane_heap_index(a, sampler)?; + let clear = self.lane_heap_index(b, sampler)?; + Ok(self.s.m.select(self.cur, cond, set, clear)) + } + Source::LanePhi { block, args } => { + // Each predecessor computes its heap index at its end (what + // it reads is there: the dwords are, on that edge); the join + // picks the one of the edge the lane came by. An edge no + // lane reading it takes gives index 0. + let join = + self.block[*block].ok_or("a per-lane descriptor chosen by control flow")?; + let mut incoming = Vec::new(); + for (&q, arg) in self.x.p.blocks[*block].preds.iter().zip(args) { + if self.block[q].is_none() { + continue; + } + let tail = + self.tail[q].ok_or("a per-lane descriptor joined from a later block")?; + let at = self.edges.get(&(q, *block)).copied().unwrap_or(tail); + let index = match arg { + Some(arg) => { + let here = std::mem::replace(&mut self.cur, at); + let index = self.lane_heap_index(arg, sampler); + self.cur = here; + index? + } + None => self.s.m.i32(0), + }; + incoming.push((index, at)); + } + let phi = self.s.m.phi(join, self.s.t.i32); + self.s.m.set_phi(phi, incoming); + Ok(phi) + } + _ => Err("a per-lane descriptor from neither a heap load nor a choice of them"), + } + } + + /// The heap index of the descriptor at dword `first` of what the global + /// load at `load` reads, in each lane: its address (base plus offsets) + /// over the descriptor size. + fn fetched_index(&mut self, load: Site, first: u8, sampler: bool) -> Result { + const WHY: Why = "a per-lane descriptor load"; + let a = *self + .scalar + .get(&load) + .ok_or("an untracked descriptor load")?; + match self.x.native.layout.get(a.param).map(|p| p.root) { + Some(RootType::Table | RootType::ResourceHeap | RootType::SamplerHeap) => {} + _ => return Err("a descriptor outside the heaps"), + } + let li: &Inst = &self.x.p.blocks[load.0].insts[load.1]; + let Fields::Flat { + addr: Some(Operand::Vector { reg, .. }), + saddr, + offset, + .. + } = li.fields + else { + return Err(WHY); + }; + let c = self.cur; + // The low dword of the address: SGPR base plus VGPR offset, or the + // VGPR pair's low half (heap addresses fit in 32 bits). + let mut at = self.i32_of(li.read(Reg::V(reg)).ok_or(WHY)?)?; + if let Some(Operand::Scalar { code, .. }) = saddr + && code != NULL + { + let base = self.i32_of(li.read(Reg::S(code)).ok_or(WHY)?)?; + at = self.s.m.bin(c, Bin::Add, base, at); + } + let k = self + .s + .m + .i32((offset as i32 as u32).wrapping_add(4 * u32::from(first))); + at = self.s.m.bin(c, Bin::Add, at, k); + let shift = self.s.m.i32(if sampler { 4 } else { 5 }); + Ok(self.s.m.bin(c, Bin::LShr, at, shift)) + } + + /// The heap index of the descriptor at dword `first` of what the scalar + /// load at `load` reads, computed in the current block. + fn heap_index(&mut self, load: Site, first: u8, sampler: bool) -> Result { + let a = *self + .scalar + .get(&load) + .ok_or("an untracked descriptor load")?; + match self.x.native.layout.get(a.param).map(|p| p.root) { + Some(RootType::Table | RootType::ResourceHeap | RootType::SamplerHeap) => {} + _ => return Err("a descriptor outside the heaps"), + } + let li: &Inst = &self.x.p.blocks[load.0].insts[load.1]; + let Fields::Smem { + base, + offset, + soffset, + .. + } = &li.fields + else { + return Err("a descriptor load"); + }; + let Operand::Scalar { code, .. } = *base else { + return Err("a descriptor load"); + }; + let c = self.cur; + let base = li.read(Reg::S(code)).ok_or("a descriptor load")?; + let mut addr = self.i32_of(base)?; + let k = self + .s + .m + .i32((*offset as u32).wrapping_add(4 * u32::from(first))); + addr = self.s.m.bin(c, Bin::Add, addr, k); + if !matches!(soffset, Operand::Scalar { code: NULL, .. }) { + let so = self.operand(li, soffset)?; + addr = self.s.m.bin(c, Bin::Add, addr, so); + } + let shift = self.s.m.i32(if sampler { 4 } else { 5 }); + Ok(self.s.m.bin(c, Bin::LShr, addr, shift)) + } + + fn valu(&mut self, inst: &Inst, b: usize, i: usize) -> Result<(), Why> { + let Fields::Valu(v) = &inst.fields else { + unreachable!() + }; + let name = inst.name(); + if self.x.res.waterfall.compares.contains(&(b, i)) { + // The first lane's dwords of a waterfall loop are each lane's + // own (see `resource::Waterfall`). + self.lane(inst, Some(true)); + return Ok(()); + } + if let Some(rest) = name.strip_prefix("v_cmp_").or(name.strip_prefix("v_cmpx_")) { + let r = if v.dpp.is_some() { + Err("a compare with DPP") + } else { + self.compare(inst, rest) + }; + if let Err(why) = r { + for &(_, w) in &inst.writes { + self.lane_fail.insert(w, why); + } + } + return r; + } + let mut guard = self.guard(b, i)?; + if let Some(d) = v.dpp { + let (x, enable) = self.dpp(inst, d)?; + guard = match (guard, enable) { + (Some(g), Some(e)) => Some(self.s.m.bin(self.cur, Bin::And, g, e)), + (g, e) => g.or(e), + }; + self.src0 = Some(x); + } + let r = self.valu_op(inst, guard); + self.src0 = None; + r + } + + /// DPP: src0 as read from another lane, and which lanes write their + /// result (none: all). + fn dpp(&mut self, inst: &Inst, dpp: Dpp) -> Result<(V, Option), Why> { + let Fields::Valu(v) = &inst.fields else { + unreachable!() + }; + let Some(&Operand::Vector { reg, .. }) = v.src.first() else { + return Err("a DPP operand"); + }; + let x = self.i32_of(inst.read(Reg::V(reg)).ok_or("a DPP operand")?)?; + // Quad permutations and DPP8 stay in groups the pixel layout shares. + let quad = matches!(dpp, Dpp::Row { ctrl: 0..=0xFF, .. }); + let mesh_quad = self.s.mesh.is_some() && quad; + if !mesh_quad { + self.cross_lane(quad)?; + } + let c = self.cur; + let lane = self.lane_index(); + let k = |l: &mut Self, n: u32| l.s.m.i32(n); + let (sixteen_mask, low) = (k(self, !15), k(self, 15)); + let row = self.s.m.bin(c, Bin::And, lane, sixteen_mask); + let pos = self.s.m.bin(c, Bin::And, lane, low); + // Source lane, and whether it lies in the row. + let (src, inside, masks, zero) = match dpp { + Dpp::Lanes { sel, .. } => { + let (seven, not7, three) = (k(self, 7), k(self, !7), k(self, 3)); + let p = self.s.m.bin(c, Bin::And, lane, seven); + let sh = self.s.m.bin(c, Bin::Mul, p, three); + let sel = k(self, sel); + let pick = self.s.m.bin(c, Bin::LShr, sel, sh); + let pick = self.s.m.bin(c, Bin::And, pick, seven); + let base = self.s.m.bin(c, Bin::And, lane, not7); + (self.s.m.bin(c, Bin::Or, base, pick), None, None, false) + } + Dpp::Row { + ctrl, + row_mask, + bank_mask, + bound_ctrl, + .. + } => { + let n = u32::from(ctrl & 15); + let (src, inside) = match ctrl { + 0..=0xFF => { + let (three, one, not3) = (k(self, 3), k(self, 1), k(self, !3)); + let p = self.s.m.bin(c, Bin::And, lane, three); + let sh = self.s.m.bin(c, Bin::Shl, p, one); + let perm = k(self, u32::from(ctrl)); + let pick = self.s.m.bin(c, Bin::LShr, perm, sh); + let pick = self.s.m.bin(c, Bin::And, pick, three); + let base = self.s.m.bin(c, Bin::And, lane, not3); + (self.s.m.bin(c, Bin::Or, base, pick), None) + } + 0x101..=0x10F | 0x111..=0x11F => { + let nn = k(self, n); + let left = ctrl < 0x110; + let (op, p) = if left { + (Bin::Add, pred::IULT) + } else { + (Bin::Sub, pred::IUGE) + }; + let s = self.s.m.bin(c, op, lane, nn); + // Left: pos + n < 16; right: pos >= n. + let bound = if left { k(self, 16 - n) } else { nn }; + (s, Some(self.s.m.cmp(c, p, pos, bound))) + } + 0x121..=0x12F => { + let nn = k(self, n); + let t = self.s.m.bin(c, Bin::Sub, pos, nn); + let t = self.s.m.bin(c, Bin::And, t, low); + (self.s.m.bin(c, Bin::Or, row, t), None) + } + 0x140 | 0x141 => { + let m = k(self, if ctrl == 0x140 { 15 } else { 7 }); + let t = self.s.m.bin(c, Bin::Xor, lane, m); + (t, None) + } + 0x150..=0x15F => { + let nn = k(self, n); + (self.s.m.bin(c, Bin::Or, row, nn), None) + } + 0x160..=0x16F => { + let nn = k(self, n); + (self.s.m.bin(c, Bin::Xor, lane, nn), None) + } + _ => return Err("a DPP lane pattern"), + }; + let masks = (row_mask != 0xF || bank_mask != 0xF).then_some((row_mask, bank_mask)); + (src, inside, masks, bound_ctrl) + } + }; + let mut r = if mesh_quad { + self.quad_pick(x, src) + } else { + self.read_lane(x, src) + }; + let mut enable = None; + if let Some(inside) = inside { + if zero { + let z = k(self, 0); + r = self.s.m.select(c, inside, r, z); + } else { + enable = Some(inside); + } + } + if let Some((rows, banks)) = masks { + // Row (16 lanes) and bank (4 lanes of a row) write masks. + let (four, two, three) = (k(self, 4), k(self, 2), k(self, 3)); + let ri = self.s.m.bin(c, Bin::LShr, lane, four); + let ri = self.s.m.bin(c, Bin::And, ri, three); + let bi = self.s.m.bin(c, Bin::LShr, lane, two); + let bi = self.s.m.bin(c, Bin::And, bi, three); + let (rm, bm) = (k(self, u32::from(rows)), k(self, u32::from(banks))); + let rb = self.s.m.bin(c, Bin::LShr, rm, ri); + let bb = self.s.m.bin(c, Bin::LShr, bm, bi); + let both = self.s.m.bin(c, Bin::And, rb, bb); + let (one, z) = (k(self, 1), k(self, 0)); + let both = self.s.m.bin(c, Bin::And, both, one); + let on = self.s.m.cmp(c, pred::NE, both, z); + enable = Some(match enable { + Some(e) => self.s.m.bin(c, Bin::And, e, on), + None => on, + }); + } + Ok((r, enable)) + } + + fn valu_op(&mut self, inst: &Inst, guard: Option) -> Result<(), Why> { + let Fields::Valu(v) = &inst.fields else { + unreachable!() + }; + let name = inst.name(); + let c = self.cur; + let f = |l: &mut Self, k| l.fsrc(inst, k); + let s = |l: &mut Self, k| l.src(inst, k); + let float = |l: &mut Self, r: V| l.write_f(inst, r, guard); + let int = |l: &mut Self, r: V| l.write_i(inst, r, guard); + if let Some(r) = self.valu16(inst, name, guard) { + return r; + } + if let Some(op) = name.strip_prefix("v_pk_") { + return self.packed16(inst, op, guard); + } + match name { + "v_mad_u64_u32" => { + // a * b + c, c and the result 64 bits wide; the carry out + // of the sum is this lane's bit of the mask it names. + let (a, b) = (s(self, 0)?, s(self, 1)?); + let x = self.src64(inst, 2)?; + let i64t = self.s.m.int(64); + self.s.flags |= flags::INT64; + let a = self.s.m.cast(c, Cast::ZExt, a, i64t); + let b = self.s.m.cast(c, Cast::ZExt, b, i64t); + let product = self.s.m.bin(c, Bin::Mul, a, b); + let r = self.s.m.bin(c, Bin::Add, product, x); + let carry = self.s.m.cmp(c, pred::IULT, r, x); + let Some(Operand::Vector { reg, .. }) = v.dst else { + return Err("a 64-bit result"); + }; + let (lo, hi) = self.split64(r); + self.write(inst, Reg::V(reg), lo, guard); + self.write(inst, Reg::V(reg + 1), hi, guard); + if let Some(Operand::Scalar { code, .. }) = v.carry + && let Some(w) = inst.write(Reg::S(code)) + { + self.lane_bits.insert(w, carry); + } + for &(_, w) in &inst.writes { + self.vals + .entry(w) + .or_insert(Val::Missing("a lane mask read as data")); + } + Ok(()) + } + "v_lshlrev_b64" | "v_lshrrev_b64" | "v_ashrrev_i64" => { + let n = s(self, 0)?; + let x = self.src64(inst, 1)?; + let i64t = self.s.m.int(64); + let k63 = self.s.m.i32(63); + let n = self.s.m.bin(c, Bin::And, n, k63); + let n = self.s.m.cast(c, Cast::ZExt, n, i64t); + let op = match name { + "v_lshlrev_b64" => Bin::Shl, + "v_lshrrev_b64" => Bin::LShr, + _ => Bin::AShr, + }; + let r = self.s.m.bin(c, op, x, n); + let Some(Operand::Vector { reg, .. }) = v.dst else { + return Err("a 64-bit result"); + }; + let (lo, hi) = self.split64(r); + self.write(inst, Reg::V(reg), lo, guard); + self.write(inst, Reg::V(reg + 1), hi, guard); + Ok(()) + } + "v_cubeid_f32" | "v_cubesc_f32" | "v_cubetc_f32" | "v_cubema_f32" => { + // Cube-map face coordinates (AMD's ISA): the major axis is z + // when |z| >= |x| and |z| >= |y|, else y when |y| >= |x|, + // else x. + let (x, y, z) = (f(self, 0)?, f(self, 1)?, f(self, 2)?); + let (ax, ay, az) = (self.unary(6, x), self.unary(6, y), self.unary(6, z)); + let zx = self.s.m.cmp(c, pred::OGE, az, ax); + let zy = self.s.m.cmp(c, pred::OGE, az, ay); + let zmaj = self.s.m.bin(c, Bin::And, zx, zy); + let ymaj = self.s.m.cmp(c, pred::OGE, ay, ax); + let zero = self.s.m.f32(0); + let neg = |l: &mut Self, v: V| l.s.m.cmp(c, pred::OLT, v, zero); + let minus = |l: &mut Self, v: V| { + let z = l.s.m.f32(0x8000_0000); + l.s.m.bin(c, Bin::Sub, z, v) + }; + let pick = |l: &mut Self, zv: V, yv: V, xv: V| { + let t = l.s.m.select(c, ymaj, yv, xv); + l.s.m.select(c, zmaj, zv, t) + }; + let r = match name { + "v_cubeid_f32" => { + let k = |l: &mut Self, v: f32| l.s.m.f32(v.to_bits()); + let (nz, ny, nx) = (neg(self, z), neg(self, y), neg(self, x)); + let (f5, f4, f3, f2, f1, f0) = ( + k(self, 5.0), + k(self, 4.0), + k(self, 3.0), + k(self, 2.0), + k(self, 1.0), + k(self, 0.0), + ); + let zf = self.s.m.select(c, nz, f5, f4); + let yf = self.s.m.select(c, ny, f3, f2); + let xf = self.s.m.select(c, nx, f1, f0); + pick(self, zf, yf, xf) + } + "v_cubesc_f32" => { + let (nz, nx) = (neg(self, z), neg(self, x)); + let (mx, mz) = (minus(self, x), minus(self, z)); + let zf = self.s.m.select(c, nz, mx, x); + let xf = self.s.m.select(c, nx, z, mz); + pick(self, zf, x, xf) + } + "v_cubetc_f32" => { + let ny = neg(self, y); + let (my, mz) = (minus(self, y), minus(self, z)); + let yf = self.s.m.select(c, ny, mz, z); + pick(self, my, yf, my) + } + _ => { + let t = pick(self, z, y, x); + let two = self.s.m.f32(2.0f32.to_bits()); + self.s.m.bin(c, Bin::Mul, t, two) + } + }; + float(self, r) + } + "v_movrels_b32" | "v_movreld_b32" | "v_movrelsd_b32" => { + // M0 indexes the source (movrels), the destination (movreld) + // or both, from the encoded register up to the program's + // VGPR count (the registers the instruction reads or writes). + let m0 = self.i32_of(inst.read(Reg::S(crate::ir::M0)).ok_or("M0")?)?; + let ( + Some(&Operand::Vector { reg: sreg, .. }), + Some(Operand::Vector { reg: dreg, .. }), + ) = (v.src.first(), v.dst) + else { + return Err("an M0-relative move"); + }; + let indexed_src = name != "v_movreld_b32"; + let value = if indexed_src { + let mut r = self.s.m.i32(0); + for k in 0..=255u8.saturating_sub(sreg) { + let Some(x) = inst.read(Reg::V(sreg + k)) else { + break; + }; + let x = self.i32_of(x)?; + let kk = self.s.m.i32(u32::from(k)); + let is = self.s.m.cmp(c, pred::EQ, m0, kk); + r = self.s.m.select(c, is, x, r); + } + r + } else { + s(self, 0)? + }; + if name == "v_movrels_b32" { + return int(self, value); + } + for k in 0..=255u8.saturating_sub(dreg) { + let Some(_) = inst.write(Reg::V(dreg + k)) else { + break; + }; + let old = match inst.read(Reg::V(dreg + k)) { + Some(o) => self.i32_of(o)?, + None => self.s.m.i32(0), + }; + let kk = self.s.m.i32(u32::from(k)); + let is = self.s.m.cmp(c, pred::EQ, m0, kk); + let x = self.s.m.select(c, is, value, old); + self.write_placed(inst, Reg::V(dreg + k), x, guard); + } + Ok(()) + } + "v_swap_b32" => { + let ( + Some(&Operand::Vector { reg: sreg, .. }), + Some(Operand::Vector { reg: dreg, .. }), + ) = (v.src.first(), v.dst) + else { + return Err("v_swap_b32"); + }; + let a = self.i32_of(inst.read(Reg::V(dreg)).ok_or("v_swap_b32")?)?; + let b = self.i32_of(inst.read(Reg::V(sreg)).ok_or("v_swap_b32")?)?; + self.write_placed(inst, Reg::V(dreg), b, guard); + if dreg != sreg { + self.write_placed(inst, Reg::V(sreg), a, guard); + } + Ok(()) + } + "v_ffbh_u32" | "v_ffbh_i32" => { + // Counted from the top bit, -1 when none (DXIL's too). + let a = s(self, 0)?; + let op = if name == "v_ffbh_u32" { 33 } else { 34 }; + let r = self + .s + .op(c, "unaryBits.i32", Attr::ReadNone, self.s.t.i32, op, &[a]); + int(self, r) + } + "v_mov_b32" => { + if v.abs != 0 || v.neg != 0 || v.clamp || v.omod != 0 { + let a = f(self, 0)?; + return float(self, a); + } + let a = s(self, 0)?; + int(self, a) + } + "v_add_f32" | "v_sub_f32" | "v_subrev_f32" | "v_mul_f32" | "v_mul_legacy_f32" + | "v_max_f32" | "v_min_f32" => { + let (a, bb) = (f(self, 0)?, f(self, 1)?); + let r = match name { + "v_add_f32" => self.s.m.bin(c, Bin::Add, a, bb), + "v_sub_f32" => self.s.m.bin(c, Bin::Sub, a, bb), + "v_subrev_f32" => self.s.m.bin(c, Bin::Sub, bb, a), + "v_mul_f32" => self.s.m.bin(c, Bin::Mul, a, bb), + "v_mul_legacy_f32" => self.legacy_mul(a, bb), + "v_max_f32" => self.max_min(true, a, bb), + _ => self.max_min(false, a, bb), + }; + float(self, r) + } + "v_fma_f32" | "v_fmaak_f32" | "v_fmamk_f32" => { + // shortcut: DXIL has no fused f32 multiply-add; FMad lets the driver fuse. + let (a, bb, cc) = (f(self, 0)?, f(self, 1)?, f(self, 2)?); + let r = self.fmad(a, bb, cc); + float(self, r) + } + "v_div_scale_f32" => { + // RDNA2 ISA: src0 = value to scale, src1 = denominator, src2 = numerator. + let (a, den, num) = (f(self, 0)?, f(self, 1)?, f(self, 2)?); + let (ai, ni, di) = (self.as_int(a), self.as_int(num), self.as_int(den)); + let (k23, k255, kabs) = ( + self.s.m.i32(23), + self.s.m.i32(0xFF), + self.s.m.i32(0x7FFF_FFFF), + ); + let (zero, k23_exp, k232_exp, k96) = ( + self.s.m.i32(0), + self.s.m.i32(23), + self.s.m.i32(232), + self.s.m.i32(96), + ); + let exp_of = |l: &mut Self, x: V| { + let s = l.s.m.bin(c, Bin::LShr, x, k23); + l.s.m.bin(c, Bin::And, s, k255) + }; + let (e1, e2) = (exp_of(self, ni), exp_of(self, di)); + let n_abs = self.s.m.bin(c, Bin::And, ni, kabs); + let d_abs = self.s.m.bin(c, Bin::And, di, kabs); + let z1 = self.s.m.cmp(c, pred::EQ, n_abs, zero); + let z2 = self.s.m.cmp(c, pred::EQ, d_abs, zero); + let any_zero = self.s.m.bin(c, Bin::Or, z1, z2); + let special = { + let s1 = self.s.m.cmp(c, pred::EQ, e1, k255); + let s2 = self.s.m.cmp(c, pred::EQ, e2, k255); + let a12 = self.s.m.bin(c, Bin::Or, s1, s2); + self.s.m.bin(c, Bin::Or, a12, any_zero) + }; + let is_den = self.s.m.cmp(c, pred::EQ, ai, di); + let diff = self.s.m.bin(c, Bin::Sub, e2, e1); + let den_tiny = self.s.m.cmp(c, pred::IULE, e2, k23_exp); + let den_huge = self.s.m.cmp(c, pred::IUGE, e2, k232_exp); + let num_tiny_exp = self.s.m.cmp(c, pred::IULE, e1, k23_exp); + let num_huge = self.s.m.cmp(c, pred::IUGE, e1, k232_exp); + let num_gap = self.s.m.cmp(c, pred::SGE, diff, k96); + let not_den_huge = { + let t = self.s.m.bool(true); + self.s.m.bin(c, Bin::Xor, den_huge, t) + }; + let num_gap = self.s.m.bin(c, Bin::And, num_gap, not_den_huge); + let num_tiny = self.s.m.bin(c, Bin::Or, num_tiny_exp, num_gap); + let up_raw = self.s.m.select(c, is_den, den_tiny, num_tiny); + let dn_raw = self.s.m.select(c, is_den, den_huge, num_huge); + let not_special = { + let t = self.s.m.bool(true); + self.s.m.bin(c, Bin::Xor, special, t) + }; + let up = self.s.m.bin(c, Bin::And, up_raw, not_special); + let dn = self.s.m.bin(c, Bin::And, dn_raw, not_special); + let uncancelled = { + let x_tiny = self.s.m.bin(c, Bin::Xor, den_tiny, num_tiny); + let x_huge = self.s.m.bin(c, Bin::Xor, den_huge, num_huge); + self.s.m.bin(c, Bin::Or, x_tiny, x_huge) + }; + let flag_raw = self.s.m.select(c, is_den, uncancelled, up_raw); + let flag = self.s.m.bin(c, Bin::And, flag_raw, not_special); + let k_up = self.s.m.f32(0x5F80_0000); + let k_dn = self.s.m.f32(0x1F80_0000); + let a_up = self.s.m.bin(c, Bin::Mul, a, k_up); + let a_dn = self.s.m.bin(c, Bin::Mul, a, k_dn); + let r = self.s.m.select(c, dn, a_dn, a); + let r = self.s.m.select(c, up, a_up, r); + let qnan = self.s.m.f32(0x7FC0_0000); + let r = self.s.m.select(c, any_zero, qnan, r); + float(self, r)?; + if let Some(Operand::Scalar { code, .. }) = v.carry + && let Some(w) = inst.write(Reg::S(code)) + { + self.lane_bits.insert(w, flag); + } + for &(_, w) in &inst.writes { + self.vals + .entry(w) + .or_insert(Val::Missing("a lane mask read as data")); + } + Ok(()) + } + "v_div_fmas_f32" => { + let (a, bb, cc) = (f(self, 0)?, f(self, 1)?, f(self, 2)?); + let m = inst + .read(Reg::S(crate::ir::VCC)) + .and_then(|v| self.x.st.masks.get(&v).copied()) + .ok_or("v_div_fmas_f32 without VCC")?; + let vcc = self.boolean(m, c)?; + let tmp = self.fmad(a, bb, cc); + let ci = self.as_int(cc); + let (k23, k255, k128) = (self.s.m.i32(23), self.s.m.i32(0xFF), self.s.m.i32(128)); + let sh = self.s.m.bin(c, Bin::LShr, ci, k23); + let exp = self.s.m.bin(c, Bin::And, sh, k255); + let exp_ge = self.s.m.cmp(c, pred::IUGE, exp, k128); + let (k_up, k_dn) = (self.s.m.f32(0x5F80_0000), self.s.m.f32(0x1F80_0000)); + let scale = self.s.m.select(c, exp_ge, k_up, k_dn); + let scaled = self.s.m.bin(c, Bin::Mul, tmp, scale); + let r = self.s.m.select(c, vcc, scaled, tmp); + float(self, r) + } + "v_div_fixup_f32" => { + let (q, den, num) = (f(self, 0)?, f(self, 1)?, f(self, 2)?); + let (qi, di, ni) = (self.as_int(q), self.as_int(den), self.as_int(num)); + let (ksign, kabs, kinf) = ( + self.s.m.i32(0x8000_0000), + self.s.m.i32(0x7FFF_FFFF), + self.s.m.i32(0x7F80_0000), + ); + let (kqnan_bit, kneg_qnan, zero) = ( + self.s.m.i32(0x0040_0000), + self.s.m.i32(0xFFC0_0000), + self.s.m.i32(0), + ); + let sign = { + let x = self.s.m.bin(c, Bin::Xor, ni, di); + self.s.m.bin(c, Bin::And, x, ksign) + }; + let q_abs = self.s.m.bin(c, Bin::And, qi, kabs); + let d_abs = self.s.m.bin(c, Bin::And, di, kabs); + let n_abs = self.s.m.bin(c, Bin::And, ni, kabs); + let q_nan = self.s.m.cmp(c, pred::IUGT, q_abs, kinf); + let d_nan = self.s.m.cmp(c, pred::IUGT, d_abs, kinf); + let n_nan = self.s.m.cmp(c, pred::IUGT, n_abs, kinf); + let d_inf = self.s.m.cmp(c, pred::EQ, d_abs, kinf); + let n_inf = self.s.m.cmp(c, pred::EQ, n_abs, kinf); + let d_zero = self.s.m.cmp(c, pred::EQ, d_abs, zero); + let n_zero = self.s.m.cmp(c, pred::EQ, n_abs, zero); + let both_inf = self.s.m.bin(c, Bin::And, n_inf, d_inf); + let both_zero = self.s.m.bin(c, Bin::And, n_zero, d_zero); + let invalid = self.s.m.bin(c, Bin::Or, both_inf, both_zero); + let make_inf = { + let t = self.s.m.bin(c, Bin::Or, n_inf, d_zero); + self.s.m.bin(c, Bin::Or, t, q_nan) + }; + let make_zero = self.s.m.bin(c, Bin::Or, d_inf, n_zero); + let signed_q = self.s.m.bin(c, Bin::Or, sign, q_abs); + let signed_inf = self.s.m.bin(c, Bin::Or, sign, kinf); + let n_qnan = self.s.m.bin(c, Bin::Or, ni, kqnan_bit); + let d_qnan = self.s.m.bin(c, Bin::Or, di, kqnan_bit); + let r = self.s.m.select(c, make_zero, sign, signed_q); + let r = self.s.m.select(c, make_inf, signed_inf, r); + let r = self.s.m.select(c, invalid, kneg_qnan, r); + let r = self.s.m.select(c, d_nan, d_qnan, r); + let r = self.s.m.select(c, n_nan, n_qnan, r); + let rf = self.as_float(r); + float(self, rf) + } + "v_fmac_f32" | "v_mac_f32" | "v_mac_legacy_f32" => { + let (a, bb) = (f(self, 0)?, f(self, 1)?); + let Some(Operand::Vector { reg, .. }) = v.dst else { + return Err("an accumulator"); + }; + let acc = inst.read(Reg::V(reg)).ok_or("an accumulator")?; + let acc = match self.floats.get(&acc) { + Some(&x) => x, + None => { + let x = self.i32_of(acc)?; + self.as_float(x) + } + }; + let r = match name { + "v_fmac_f32" => self.fmad(a, bb, acc), + "v_mac_f32" => { + let m = self.s.m.bin(c, Bin::Mul, a, bb); + self.s.m.bin(c, Bin::Add, m, acc) + } + _ => { + let m = self.legacy_mul(a, bb); + self.s.m.bin(c, Bin::Add, m, acc) + } + }; + float(self, r) + } + "v_mad_f32" | "v_madak_f32" | "v_madmk_f32" | "v_mad_legacy_f32" => { + let (a, bb, cc) = (f(self, 0)?, f(self, 1)?, f(self, 2)?); + let m = if name == "v_mad_legacy_f32" { + self.legacy_mul(a, bb) + } else { + self.s.m.bin(c, Bin::Mul, a, bb) + }; + let r = self.s.m.bin(c, Bin::Add, m, cc); + float(self, r) + } + "v_max3_f32" | "v_min3_f32" | "v_med3_f32" => { + let (a, bb, cc) = (f(self, 0)?, f(self, 1)?, f(self, 2)?); + let r = match name { + "v_max3_f32" => { + let t = self.max_min(true, a, bb); + self.max_min(true, t, cc) + } + "v_min3_f32" => { + let t = self.max_min(false, a, bb); + self.max_min(false, t, cc) + } + _ => self.med3(a, bb, cc), + }; + float(self, r) + } + "v_rcp_f32" | "v_rcp_iflag_f32" => { + // shortcut: the hardware reciprocal is approximate (1 ULP); this divides. + let a = f(self, 0)?; + let one = self.s.m.f32(1.0f32.to_bits()); + let r = self.s.m.bin(c, Bin::SDiv, one, a); + float(self, r) + } + "v_rsq_f32" | "v_sqrt_f32" | "v_log_f32" | "v_exp_f32" | "v_fract_f32" + | "v_trunc_f32" | "v_floor_f32" | "v_ceil_f32" | "v_rndne_f32" | "v_sin_f32" + | "v_cos_f32" => { + let a = f(self, 0)?; + let op = match name { + "v_rsq_f32" => 25, + "v_sqrt_f32" => 24, + "v_log_f32" => 23, + "v_exp_f32" => 21, + "v_fract_f32" => 22, + "v_trunc_f32" => 29, + "v_floor_f32" => 27, + "v_ceil_f32" => 28, + "v_rndne_f32" => 26, + "v_sin_f32" => 13, + _ => 12, + }; + let r = match op { + 12 | 13 => self.trig_turns(a, op == 12), + 22 => self.fract(a, 1.0, f32::from_bits(0x3F7F_FFFF)), + _ => self.unary(op, a), + }; + float(self, r) + } + "v_cvt_i32_f32" | "v_cvt_u32_f32" | "v_cvt_flr_i32_f32" | "v_cvt_rpi_i32_f32" => { + let mut a = f(self, 0)?; + if name == "v_cvt_rpi_i32_f32" { + let h = self.s.m.f32(0.5f32.to_bits()); + a = self.s.m.bin(c, Bin::Add, a, h); + } + if name != "v_cvt_i32_f32" && name != "v_cvt_u32_f32" { + a = self.unary(27, a); + } + // D3D's conversions saturate and give 0 for NaN, as the + // hardware does (checked on the RX 6700 XT and WARP). + let op = if name == "v_cvt_u32_f32" { + Cast::FpToUi + } else { + Cast::FpToSi + }; + let r = self.s.m.cast(c, op, a, self.s.t.i32); + int(self, r) + } + "v_permlane16_b32" | "v_permlanex16_b32" => { + // Each lane reads src0 of a lane of its own 32-lane half, + // picked by nibble (lane & 15) of {src2, src1}: within its + // own row of 16 (`v_permlane16`) or the other row of its + // half (`v_permlanex16`). The pick stays inside a half, so a + // console wave of 64 run as two host waves of 32 needs no + // exchange. + // shortcut: a source lane with EXEC clear is read as the host + // gives it (the console keeps vdst unless op_sel's fetch + // inactive bit is set). + self.cross_lane(false)?; + let x = s(self, 0)?; + let (s1, s2) = (s(self, 1)?, s(self, 2)?); + let i32t = self.s.t.i32; + let lane = self.s.op(c, "waveGetLaneIndex", Attr::ReadOnly, i32t, 111, &[]); + let [k15, k8, k7, k2, k16, not31, not15] = + [15, 8, 7, 2, 16, !31, !15].map(|x| self.s.m.i32(x)); + let low = self.s.m.bin(c, Bin::And, lane, k15); + // nibble `low` of the 64-bit selector: src1 holds lanes 0-7 + let hi_word = self.s.m.cmp(c, pred::IUGE, low, k8); + let word = self.s.m.select(c, hi_word, s2, s1); + let n = self.s.m.bin(c, Bin::And, low, k7); + let sh = self.s.m.bin(c, Bin::Shl, n, k2); + let pick = self.s.m.bin(c, Bin::LShr, word, sh); + let pick = self.s.m.bin(c, Bin::And, pick, k15); + let row = if name == "v_permlanex16_b32" { + // the other row of this half + let half = self.s.m.bin(c, Bin::And, lane, not31); + let other = self.s.m.bin(c, Bin::And, lane, k16); + let other = self.s.m.bin(c, Bin::Xor, other, k16); + self.s.m.bin(c, Bin::Or, half, other) + } else { + self.s.m.bin(c, Bin::And, lane, not15) + }; + let from = self.s.m.bin(c, Bin::Or, row, pick); + let r = self.read_lane(x, from); + int(self, r) + } + "v_cvt_f32_i32" | "v_cvt_f32_u32" | "v_cvt_f32_ubyte0" | "v_cvt_f32_ubyte1" + | "v_cvt_f32_ubyte2" | "v_cvt_f32_ubyte3" => { + let mut a = s(self, 0)?; + if let Some(n) = name.strip_prefix("v_cvt_f32_ubyte") { + let sh = self.s.m.i32(8 * u32::from(n.as_bytes()[0] - b'0')); + let ff = self.s.m.i32(0xff); + a = self.s.m.bin(c, Bin::LShr, a, sh); + a = self.s.m.bin(c, Bin::And, a, ff); + } + let op = if name == "v_cvt_f32_i32" { + Cast::SiToFp + } else { + Cast::UiToFp + }; + let r = self.s.m.cast(c, op, a, self.s.t.f32); + float(self, r) + } + "v_cvt_f32_f64" => { + let (lo, hi) = self.f64_pair(inst, 0)?; + let bits = self.f64_to_f32_bits(lo, hi); + let r = self.as_float(bits); + float(self, r) + } + "v_fma_mix_f32" | "v_fma_mixlo_f16" | "v_fma_mixhi_f16" => { + // Each source is f32, or with op_sel_hi the low (op_sel: high) + // f16 half; neg_hi is the absolute value here. + let mut xs = Vec::new(); + for i in 0..3 { + let op = v.src.get(i).ok_or("a missing operand")?; + let mut x = if v.opsel_hi >> i & 1 != 0 { + let x = self.f16_operand(inst, op)?; + let h = if v.opsel >> i & 1 != 0 { + let k16 = self.s.m.i32(16); + self.s.m.bin(c, Bin::LShr, x, k16) + } else { + x + }; + self.s + .op(c, "legacyF16ToF32", Attr::ReadNone, self.s.t.f32, 131, &[h]) + } else { + let x = self.operand(inst, op)?; + self.as_float(x) + }; + if v.neg_hi >> i & 1 != 0 { + x = self.unary(6, x); + } + if v.neg >> i & 1 != 0 { + let z = self.s.m.f32(0x8000_0000); + x = self.s.m.bin(c, Bin::Sub, z, x); + } + xs.push(x); + } + let mut r = self.fmad(xs[0], xs[1], xs[2]); + if name == "v_fma_mix_f32" { + return float(self, r); + } + if v.clamp { + r = self.unary(7, r); + } + // The f16 result goes to one half; the other half stays. + let Some(Operand::Vector { reg, .. }) = v.dst else { + return Err("a mixed-precision result"); + }; + let old = match inst.read(Reg::V(reg)) { + Some(o) => self.i32_of(o)?, + None => self.s.m.i32(0), + }; + let h = self + .s + .op(c, "legacyF32ToF16", Attr::ReadNone, self.s.t.i32, 130, &[r]); + let (keep, h) = if name == "v_fma_mixhi_f16" { + let k16 = self.s.m.i32(16); + (0xFFFF, self.s.m.bin(c, Bin::Shl, h, k16)) + } else { + (0xFFFF_0000, h) + }; + let keep = self.s.m.i32(keep); + let old = self.s.m.bin(c, Bin::And, old, keep); + let x = self.s.m.bin(c, Bin::Or, old, h); + self.write(inst, Reg::V(reg), x, guard); + Ok(()) + } + "v_cvt_pkrtz_f16_f32" => { + let (a, bb) = (f(self, 0)?, f(self, 1)?); + let lo = self.f16_toward_zero(a); + let hi = self.f16_toward_zero(bb); + let sh = self.s.m.i32(16); + let hi = self.s.m.bin(c, Bin::Shl, hi, sh); + let r = self.s.m.bin(c, Bin::Or, lo, hi); + int(self, r) + } + "v_cvt_f16_f32" if v.opsel == 0 => { + // Rounded to nearest even (the MODE default) into the low half. + let a = f(self, 0)?; + let r = self + .s + .op(c, "legacyF32ToF16", Attr::ReadNone, self.s.t.i32, 130, &[a]); + let Some(Operand::Vector { reg, .. }) = v.dst else { + return Err("a 16-bit result outside a VGPR"); + }; + let r = self.low_half(inst, reg, r); + int(self, r) + } + "v_pack_b32_f16" => { + // Two f16 sources (op_sel: their high halves; abs and neg on + // the sign bit) into the low and high half. + let mut halves = Vec::new(); + for k in 0..2 { + let op = v.src.get(k).ok_or("a missing operand")?; + let mut x = self.f16_operand(inst, op)?; + if v.opsel >> k & 1 != 0 { + let k16 = self.s.m.i32(16); + x = self.s.m.bin(c, Bin::LShr, x, k16); + } + let mask = if v.abs >> k & 1 != 0 { 0x7FFF } else { 0xFFFF }; + let mask = self.s.m.i32(mask); + x = self.s.m.bin(c, Bin::And, x, mask); + if v.neg >> k & 1 != 0 { + let sign = self.s.m.i32(0x8000); + x = self.s.m.bin(c, Bin::Xor, x, sign); + } + halves.push(x); + } + let k16 = self.s.m.i32(16); + let hi = self.s.m.bin(c, Bin::Shl, halves[1], k16); + let r = self.s.m.bin(c, Bin::Or, halves[0], hi); + int(self, r) + } + "v_cvt_f32_f16" if v.opsel == 0 => { + let a = s(self, 0)?; + let r = self + .s + .op(c, "legacyF16ToF32", Attr::ReadNone, self.s.t.f32, 131, &[a]); + float(self, r) + } + "v_cndmask_b32" => { + let mask = match v.src.get(2) { + Some(&Operand::Scalar { code, .. }) => inst.read(Reg::S(code)), + _ => None, + }; + const UNTRACKED: Why = "a select on an untracked mask"; + let cond = match mask.and_then(|m| self.x.st.masks.get(&m).copied()) { + Some(m) => self.boolean(m, c)?, + // A mask the code holds as a number (a constant bit + // pattern: every other lane, every other pair...): + // this lane's bit of it. Exact where host lanes are + // the console's. + None if self.mask_data == MaskData::Console => { + // Each host wave taken as a wave of its own has no + // console lane numbers to pick the bits by. + if self.local { + return Err("a constant lane mask in a half-wave"); + } + let m = mask.ok_or(UNTRACKED)?; + let lo = self.i32_of(m).map_err(|_| UNTRACKED)?; + // wave64: the register after it holds lanes 32-63. + let high = match v.src.get(2) { + Some(&Operand::Scalar { code, .. }) if self.x.native.wave64 => { + Some(inst.read(Reg::S(code + 1)).ok_or(UNTRACKED)?) + } + _ => None, + }; + let hi = match high { + Some(h) => Some(self.i32_of(h).map_err(|_| UNTRACKED)?), + None => None, + }; + self.cross_lane(false)?; + self.lane_bit(c, lo, hi) + } + None => return Err(UNTRACKED), + }; + if v.abs != 0 || v.neg != 0 { + let (a, bb) = (f(self, 0)?, f(self, 1)?); + let r = self.s.m.select(c, cond, bb, a); + return float(self, r); + } + let (a, bb) = (s(self, 0)?, s(self, 1)?); + let r = self.s.m.select(c, cond, bb, a); + int(self, r) + } + "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" => { + // The carry (borrow) out is a lane mask: this lane's bit. + let (mut a, mut bb) = (s(self, 0)?, s(self, 1)?); + if name.contains("subrev") { + std::mem::swap(&mut a, &mut bb); + } + let cin = if name.ends_with("_ci_u32") { + let m = match v.src.get(2) { + Some(&Operand::Scalar { code, .. }) => inst.read(Reg::S(code)), + _ => None, + }; + let m = m + .and_then(|m| self.x.st.masks.get(&m).copied()) + .ok_or("a carry-in from an untracked mask")?; + Some(self.boolean(m, c)?) + } else { + None + }; + let (r, carry) = self.add_sub_carry(c, name.starts_with("v_add"), a, bb, cin); + int(self, r)?; + if let Some(Operand::Scalar { code, .. }) = v.carry + && let Some(w) = inst.write(Reg::S(code)) + { + self.lane_bits.insert(w, carry); + } + for &(_, w) in &inst.writes { + self.vals + .entry(w) + .or_insert(Val::Missing("a lane mask read as data")); + } + Ok(()) + } + "v_readlane_b32" => { + let (a, lane) = (s(self, 0)?, s(self, 1)?); + // A computed lane in a pixel or vertex program is a host lane + // (from a mask or `v_mbcnt`); a constant one is the console's. + if self.mask_data == MaskData::Host && !matches!(lane, V::Const(_)) { + self.s.flags |= flags::WAVE_OPS; + } else { + self.cross_lane(false)?; + } + if let Some(slot) = self.exchange.as_ref().map(|e| e.0) { + if self.local && self.local_any { + // this host wave's lane of that number (lanes 32..63 are 0..31 here) + let k31 = self.s.m.i32(31); + let here = self.s.m.bin(self.cur, Bin::And, lane, k31); + let r = self.read_lane(a, here); + return int(self, r); + } + if self.local { + return Err("a lane read in a half-wave"); + } + if self.exchange.as_ref().is_some_and(|e| e.1) { + // a group of 32 or fewer: the lane is in this host wave + let r = self.read_lane(a, lane); + return int(self, r); + } + // the lane that holds it may be in the other host wave: it gives it through LDS + if !self.all_lanes(self.cur_ir) { + need(self.cur_ir); + return Err("a lane read where not every lane runs"); + } + let cl = self.console_lane(); + let is = self.s.m.cmp(self.cur, pred::EQ, cl, lane); + let k = self.exchange_pair(slot); + let at = self.begin_guarded(Some(is)); + let lds = self.s.lds(); + let ptr = self.s.m.element(self.cur, lds, k); + self.s.m.store(self.cur, ptr, a); + self.end_guarded(at, &[]); + let c2 = self.cur; + self.group_sync(c2); + let ptr = self.s.m.element(c2, lds, k); + let r = self.s.m.load(c2, ptr); + self.group_sync(c2); + return int(self, r); + } + let r = self.read_lane(a, lane); + int(self, r) + } + "v_writelane_b32" => { + // The lane given takes the scalar; the others keep their value. + let (a, lane) = (s(self, 0)?, s(self, 1)?); + let Some(Operand::Vector { reg, .. }) = v.dst else { + return Err("a lane write"); + }; + let old = match inst.read(Reg::V(reg)) { + Some(o) => self.i32_of(o)?, + None => self.s.m.i32(0), + }; + self.cross_lane(false)?; + if self.local && !self.local_any { + return Err("a lane write in a half-wave"); + } + let me = self.console_lane(); + let is = self.s.m.cmp(c, pred::EQ, me, lane); + let r = self.s.m.select(c, is, a, old); + int(self, r) + } + "v_readfirstlane_b32" + if inst + .writes + .first() + .is_some_and(|w| self.x.res.waterfall.reads.contains(&w.1)) => + { + // A waterfall loop's read of a descriptor dword: the lane's own. + let a = s(self, 0)?; + int(self, a) + } + "v_readfirstlane_b32" + if matches!(v.src.first(), Some(&Operand::Vector { reg, .. }) + if inst.read(Reg::V(reg)).is_some_and(|x| self.own_bits.alike.contains(&x))) => + { + // The bits a loop over a wave OR has still to visit (`own_bits`): every lane of + // the host wave holds the same, so the first lane's is the lane's own. + let a = s(self, 0)?; + int(self, a) + } + "v_readfirstlane_b32" => { + let a = s(self, 0)?; + let (mine, any) = self.first_lane(a, guard); + // two host waves that exchange: the console's first lane may be in the other + // one, unless every lane holds the same value + let alike = match v.src.first() { + Some(&Operand::Vector { reg, .. }) => { + inst.read(Reg::V(reg)).is_some_and(|x| self.uniform.contains(&x)) + } + _ => true, + }; + let halves = self.exchange.as_ref().is_some_and(|e| !e.1) && !self.local; + let r = if halves && !alike { + if !self.all_lanes(self.cur_ir) { + // shortcut: `LEONIDA_FIRSTLANE_OWN=1` takes the host wave's own + // first lane, exact when the value is the same in every lane of + // the console wave (the ray-tracing builder's scans read a sum of + // scalars this way, inside a loop whose exit is per console wave). + static OWN: std::sync::OnceLock = std::sync::OnceLock::new(); + if *OWN.get_or_init(|| std::env::var_os("LEONIDA_FIRSTLANE_OWN").is_some_and(|v| v == "1")) { + return int(self, mine); + } + need(self.cur_ir); + return Err("a first-lane read where not every lane runs"); + } + let c = self.cur; + if guard.is_none() && super::shader_opt() & super::bitcode::opt::FIRST != 0 { + // Every lane is in EXEC: the console's first lane is + // lane 0, which the lower half of every console wave + // has. No half needs to ask the other whether it has + // a lane (an exchange of the constant 1: two group + // barriers), and the lower half's value is the answer. + let (lo, _) = self.exchange_halves(c, mine); + lo + } else { + let i32t = self.s.t.i32; + let has = self.s.m.cast(c, Cast::ZExt, any, i32t); + let (lo_has, hi_has) = self.exchange_halves(c, has); + let (lo, hi) = self.exchange_halves(c, mine); + let z = self.s.m.i32(0); + let in_lo = self.s.m.cmp(c, pred::NE, lo_has, z); + let in_hi = self.s.m.cmp(c, pred::NE, hi_has, z); + // neither half has a lane in EXEC: the console reads lane 0 + let hi = self.s.m.select(c, in_hi, hi, lo); + self.s.m.select(c, in_lo, lo, hi) + } + } else { + mine + }; + int(self, r) + } + _ => { + let r = self.integer(inst, name)?; + int(self, r) + } + } + } + + /// A 64-bit source (a register pair; inline constants sign-extend). + fn src64(&mut self, inst: &Inst, k: usize) -> Result { + let Fields::Valu(v) = &inst.fields else { + unreachable!() + }; + if v.abs >> k & 1 != 0 || v.neg >> k & 1 != 0 || v.sdwa.is_some() || v.dpp.is_some() { + return Err("64-bit operand modifiers"); + } + let c = self.cur; + let i64t = self.s.m.int(64); + self.s.flags |= flags::INT64; + let op = *v.src.get(k).ok_or("a missing operand")?; + let pair = |l: &mut Self, r: Reg, r1: Reg| -> Result { + let lo = l.i32_of(inst.read(r).ok_or("an unread operand")?)?; + let hi = l.i32_of(inst.read(r1).ok_or("an unread operand")?)?; + Ok(l.join64(lo, hi)) + }; + match op { + Operand::Vector { reg, .. } => pair(self, Reg::V(reg), Reg::V(reg + 1)), + Operand::Scalar { code, .. } if code != NULL => { + pair(self, Reg::S(code), Reg::S(code + 1)) + } + Operand::Const(k @ 128..=208) => { + let x = crate::resource::inline(k).ok_or("a special operand")?; + Ok(self.s.m.int_const(i64t, i64::from(x as i32))) + } + _ => { + // Literals and the null register: zero-extended. + let x = self.operand(inst, &op)?; + Ok(self.s.m.cast(c, Cast::ZExt, x, i64t)) + } + } + } + + /// Reads an IEEE-754 binary64 operand as `(lo, hi)` 32-bit words, applying + /// `abs` and `neg` input modifiers on operand `k`. + fn f64_pair(&mut self, inst: &Inst, k: usize) -> Result<(V, V), Why> { + let Fields::Valu(v) = &inst.fields else { + unreachable!() + }; + if v.sdwa.is_some() || v.dpp.is_some() { + return Err("64-bit operand modifiers"); + } + let op = *v.src.get(k).ok_or("a missing operand")?; + let pair = |l: &mut Self, r: Reg, r1: Reg| -> Result<(V, V), Why> { + let lo = l.i32_of(inst.read(r).ok_or("an unread operand")?)?; + let hi = l.i32_of(inst.read(r1).ok_or("an unread operand")?)?; + Ok((lo, hi)) + }; + let (lo, mut hi) = match op { + Operand::Vector { reg, .. } => pair(self, Reg::V(reg), Reg::V(reg + 1))?, + Operand::Scalar { code, .. } if code != NULL => { + pair(self, Reg::S(code), Reg::S(code + 1))? + } + Operand::Const(128) => (self.s.m.i32(0), self.s.m.i32(0)), + Operand::Const(c @ 240..=248) => { + const INLINE_F64: [f64; 9] = [ + 0.5, + -0.5, + 1.0, + -1.0, + 2.0, + -2.0, + 4.0, + -4.0, + 1.0 / std::f64::consts::TAU, + ]; + let bits = INLINE_F64[(c - 240) as usize].to_bits(); + (self.s.m.i32(bits as u32), self.s.m.i32((bits >> 32) as u32)) + } + // GFX10 places a 32-bit literal in the high 32 bits of a 64-bit float operand. + Operand::Literal(x) => (self.s.m.i32(0), self.s.m.i32(x)), + _ => return Err("a 64-bit float operand"), + }; + let c = self.cur; + if v.abs >> k & 1 != 0 { + let mask = self.s.m.i32(0x7FFF_FFFF); + hi = self.s.m.bin(c, Bin::And, hi, mask); + } + if v.neg >> k & 1 != 0 { + let sign = self.s.m.i32(0x8000_0000); + hi = self.s.m.bin(c, Bin::Xor, hi, sign); + } + Ok((lo, hi)) + } + + /// Converts IEEE-754 binary64 `(lo, hi)` to binary32 bits with round-to-nearest-even, + /// without requiring host `DOUBLES` (`f64`) support. + fn f64_to_f32_bits(&mut self, lo: V, hi: V) -> V { + let c = self.cur; + let k0 = self.s.m.i32(0); + let k1 = self.s.m.i32(1); + let sign_mask = self.s.m.i32(0x8000_0000); + let sign = self.s.m.bin(c, Bin::And, hi, sign_mask); + + let k20 = self.s.m.i32(20); + let k7ff = self.s.m.i32(0x7FF); + let exp64 = self.s.m.bin(c, Bin::LShr, hi, k20); + let exp64 = self.s.m.bin(c, Bin::And, exp64, k7ff); + + let frac_mask = self.s.m.i32(0x000F_FFFF); + let frac_hi = self.s.m.bin(c, Bin::And, hi, frac_mask); + let frac_any = self.s.m.bin(c, Bin::Or, frac_hi, lo); + let frac_nz = self.s.m.cmp(c, pred::NE, frac_any, k0); + + let k3 = self.s.m.i32(3); + let k29 = self.s.m.i32(29); + let m23_hi = self.s.m.bin(c, Bin::Shl, frac_hi, k3); + let m23_lo = self.s.m.bin(c, Bin::LShr, lo, k29); + let m23 = self.s.m.bin(c, Bin::Or, m23_hi, m23_lo); + + let rem_mask = self.s.m.i32(0x1FFF_FFFF); + let rem = self.s.m.bin(c, Bin::And, lo, rem_mask); + let half_rem = self.s.m.i32(0x1000_0000); + let gt_half = self.s.m.cmp(c, pred::IUGT, rem, half_rem); + let eq_half = self.s.m.cmp(c, pred::EQ, rem, half_rem); + let m23_odd_bit = self.s.m.bin(c, Bin::And, m23, k1); + let m23_odd = self.s.m.cmp(c, pred::NE, m23_odd_bit, k0); + let tie_up = self.s.m.bin(c, Bin::And, eq_half, m23_odd); + let norm_round = self.s.m.bin(c, Bin::Or, gt_half, tie_up); + let norm_inc = self.s.m.select(c, norm_round, k1, k0); + + // Normal range: exp64 in [897, 1150] -> exp32 in [1, 254]. + let k896 = self.s.m.i32(896); + let k23 = self.s.m.i32(23); + let exp32 = self.s.m.bin(c, Bin::Sub, exp64, k896); + let exp32_sh = self.s.m.bin(c, Bin::Shl, exp32, k23); + let norm_body = self.s.m.bin(c, Bin::Add, exp32_sh, m23); + let norm_body = self.s.m.bin(c, Bin::Add, norm_body, norm_inc); + let norm_res = self.s.m.bin(c, Bin::Or, sign, norm_body); + + // Subnormal range: exp64 in [874, 896] -> shift in [1, 23]. + let k897 = self.s.m.i32(897); + let k32 = self.s.m.i32(32); + let k31 = self.s.m.i32(31); + let imp = self.s.m.i32(0x0080_0000); + let sig24 = self.s.m.bin(c, Bin::Or, imp, m23); + let raw_shift = self.s.m.bin(c, Bin::Sub, k897, exp64); + // Clamp shift to [1, 23] so shifts never produce poison outside the subnormal branch. + let lt1 = self.s.m.cmp(c, pred::IULT, raw_shift, k1); + let shift = self.s.m.select(c, lt1, k1, raw_shift); + let gt23 = self.s.m.cmp(c, pred::IUGT, shift, k23); + let shift = self.s.m.select(c, gt23, k23, shift); + let sub_m = self.s.m.bin(c, Bin::LShr, sig24, shift); + let inv_shift = self.s.m.bin(c, Bin::Sub, k32, shift); + let lost = self.s.m.bin(c, Bin::Shl, sig24, inv_shift); + let round_bit = self.s.m.bin(c, Bin::LShr, lost, k31); + let round_on = self.s.m.cmp(c, pred::NE, round_bit, k0); + let low31 = self.s.m.i32(0x7FFF_FFFF); + let lost_lo = self.s.m.bin(c, Bin::And, lost, low31); + let sticky = self.s.m.bin(c, Bin::Or, lost_lo, rem); + let sticky_on = self.s.m.cmp(c, pred::NE, sticky, k0); + let sub_odd_bit = self.s.m.bin(c, Bin::And, sub_m, k1); + let sub_odd = self.s.m.cmp(c, pred::NE, sub_odd_bit, k0); + let sub_tie = self.s.m.bin(c, Bin::Or, sticky_on, sub_odd); + let sub_round = self.s.m.bin(c, Bin::And, round_on, sub_tie); + let sub_inc = self.s.m.select(c, sub_round, k1, k0); + let sub_body = self.s.m.bin(c, Bin::Add, sub_m, sub_inc); + let sub_res = self.s.m.bin(c, Bin::Or, sign, sub_body); + + // Underflow range: exp64 < 874. Only exp64 == 873 with non-zero fraction rounds up to min subnormal (1). + let k873 = self.s.m.i32(873); + let eq873 = self.s.m.cmp(c, pred::EQ, exp64, k873); + let round_min = self.s.m.bin(c, Bin::And, eq873, frac_nz); + let min_bit = self.s.m.select(c, round_min, k1, k0); + let under_res = self.s.m.bin(c, Bin::Or, sign, min_bit); + + // Overflow / Inf / NaN: exp64 >= 1151. + let is_exp_all = self.s.m.cmp(c, pred::EQ, exp64, k7ff); + let is_nan = self.s.m.bin(c, Bin::And, is_exp_all, frac_nz); + let inf_bits = self.s.m.i32(0x7F80_0000); + let qnan_bits = self.s.m.i32(0x7FC0_0000); + let nan_body = self.s.m.bin(c, Bin::Or, qnan_bits, m23); + let over_body = self.s.m.select(c, is_nan, nan_body, inf_bits); + let over_res = self.s.m.bin(c, Bin::Or, sign, over_body); + + // Select final result by exponent range. + let k874 = self.s.m.i32(874); + let k1151 = self.s.m.i32(1151); + let is_under = self.s.m.cmp(c, pred::IULT, exp64, k874); + let is_sub = self.s.m.cmp(c, pred::IULT, exp64, k897); + let is_over = self.s.m.cmp(c, pred::IUGE, exp64, k1151); + let r = self.s.m.select(c, is_over, over_res, norm_res); + let r = self.s.m.select(c, is_sub, sub_res, r); + self.s.m.select(c, is_under, under_res, r) + } + + fn join64(&mut self, lo: V, hi: V) -> V { + let c = self.cur; + let ty = self.s.m.int(64); + let lo = self.s.m.cast(c, Cast::ZExt, lo, ty); + let hi = self.s.m.cast(c, Cast::ZExt, hi, ty); + let shift = self.s.m.int_const(ty, 32); + let hi = self.s.m.bin(c, Bin::Shl, hi, shift); + self.s.m.bin(c, Bin::Or, lo, hi) + } + + /// The bits of the float nearest the double whose dwords are `lo` and + /// `hi`, on 32-bit integers: round to nearest even, infinities and NaN + /// kept (a NaN stays quiet), a result below the smallest normal float + /// signed zero (flushed, as the console's default float mode does). + // The flush-to-zero form of v_cvt_f32_f64: kept beside the IEEE form in use until the console's + // float mode for this instruction is checked. + #[allow(dead_code)] + fn f64_bits_to_f32_bits(&mut self, lo: V, hi: V) -> V { + let c = self.cur; + let k = |l: &mut Self, x: u32| l.s.m.i32(x); + let (k20, k29, k3, k23) = (k(self, 20), k(self, 29), k(self, 3), k(self, 23)); + let sign_mask = k(self, 0x8000_0000); + let sign = self.s.m.bin(c, Bin::And, hi, sign_mask); + let e = self.s.m.bin(c, Bin::LShr, hi, k20); + let e_mask = k(self, 0x7ff); + let e = self.s.m.bin(c, Bin::And, e, e_mask); + // The top 23 bits of the 52-bit mantissa, and the 29 below them. + let m_mask = k(self, 0x000f_ffff); + let mh = self.s.m.bin(c, Bin::And, hi, m_mask); + let mh = self.s.m.bin(c, Bin::Shl, mh, k3); + let ml = self.s.m.bin(c, Bin::LShr, lo, k29); + let m = self.s.m.bin(c, Bin::Or, mh, ml); + let rest_mask = k(self, 0x1fff_ffff); + let rest = self.s.m.bin(c, Bin::And, lo, rest_mask); + // Round to nearest even: up past half, or at half when odd. + let half = k(self, 0x1000_0000); + let one = k(self, 1); + let above = self.s.m.cmp(c, pred::IUGT, rest, half); + let at = self.s.m.cmp(c, pred::EQ, rest, half); + let odd = self.s.m.bin(c, Bin::And, m, one); + let zero = k(self, 0); + let odd = self.s.m.cmp(c, pred::NE, odd, zero); + let tie = self.s.m.bin(c, Bin::And, at, odd); + let up = self.s.m.bin(c, Bin::Or, above, tie); + let up = self.s.m.select(c, up, one, zero); + // Rebias the exponent (1023 → 127); a carry out of the mantissa + // steps the exponent, up to infinity. + let bias = k(self, 1023 - 127); + let e32 = self.s.m.bin(c, Bin::Sub, e, bias); + let ex = self.s.m.bin(c, Bin::Shl, e32, k23); + let normal = self.s.m.bin(c, Bin::Add, ex, m); + let normal = self.s.m.bin(c, Bin::Add, normal, up); + let normal = self.s.m.bin(c, Bin::Or, normal, sign); + // Exponents out of the float's range (signed, after rebiasing). + let inf = k(self, 0x7f80_0000); + let inf = self.s.m.bin(c, Bin::Or, inf, sign); + let k255 = k(self, 255); + let big = self.s.m.cmp(c, pred::SGE, e32, k255); + let small = self.s.m.cmp(c, pred::SLE, e32, zero); + let r = self.s.m.select(c, big, inf, normal); + let r = self.s.m.select(c, small, sign, r); + // Infinity and NaN (a NaN with any mantissa bit set stays a NaN). + let all = k(self, 0x7ff); + let special = self.s.m.cmp(c, pred::EQ, e, all); + let any = self.s.m.bin(c, Bin::Or, mh, ml); + let any = self.s.m.bin(c, Bin::Or, any, rest); + let nan = self.s.m.cmp(c, pred::NE, any, zero); + let quiet = k(self, 0x0040_0000); + let quiet = self.s.m.select(c, nan, quiet, zero); + let special_bits = self.s.m.bin(c, Bin::Or, inf, quiet); + self.s.m.select(c, special, special_bits, r) + } + + /// The low and high dwords of an i64. + fn split64(&mut self, x: V) -> (V, V) { + let c = self.cur; + let i64t = self.s.m.int(64); + let k32 = self.s.m.int_const(i64t, 32); + let lo = self.s.m.cast(c, Cast::Trunc, x, self.s.t.i32); + let hi = self.s.m.bin(c, Bin::LShr, x, k32); + let hi = self.s.m.cast(c, Cast::Trunc, hi, self.s.t.i32); + (lo, hi) + } + + /// Source `k` of a 16-bit operation in the low 16 bits (the rest 0): + /// op_sel (or an SDWA word select) picks the high half; inline float + /// constants are f16 values here. + fn half_src(&mut self, inst: &Inst, k: usize) -> Result { + let Fields::Valu(v) = &inst.fields else { + unreachable!() + }; + let op = *v.src.get(k).ok_or("a missing operand")?; + let mut high = v.opsel >> k & 1 != 0; + if let Some(sd) = v.sdwa { + match sd.src_sel.get(k).copied().unwrap_or(6) { + 4 => {} + 5 => high = true, + 6 => {} + _ => return Err("a byte select on a 16-bit operation"), + } + } + let x = match self.src0 { + Some(x) if k == 0 => x, + _ => self.f16_operand(inst, &op)?, + }; + let c = self.cur; + let x = if high { + let k16 = self.s.m.i32(16); + self.s.m.bin(c, Bin::LShr, x, k16) + } else { + x + }; + let m = self.s.m.i32(0xFFFF); + Ok(self.s.m.bin(c, Bin::And, x, m)) + } + + /// An f16 source as an f32 (exact), with its abs/neg modifiers. + fn half_fsrc(&mut self, inst: &Inst, k: usize) -> Result { + let Fields::Valu(v) = &inst.fields else { + unreachable!() + }; + let h = self.half_src(inst, k)?; + let f32t = self.s.t.f32; + let mut f = self + .s + .op(self.cur, "legacyF16ToF32", Attr::ReadNone, f32t, 131, &[h]); + if v.abs >> k & 1 != 0 { + f = self.unary(6, f); + } + if v.neg >> k & 1 != 0 { + let z = self.s.m.f32(0x8000_0000); + f = self.s.m.bin(self.cur, Bin::Sub, z, f); + } + Ok(f) + } + + /// Writes a 16-bit result (low bits of `x`) into the destination's low + /// half, or its high half with op_sel bit 3 (or an SDWA WORD_1 select); + /// the other half is kept (GFX10). + fn write_half(&mut self, inst: &Inst, x: V, guard: Option) -> Result<(), Why> { + let Fields::Valu(v) = &inst.fields else { + unreachable!() + }; + let Some(Operand::Vector { reg, .. }) = v.dst else { + return Err("a 16-bit result outside a VGPR"); + }; + let mut high = v.opsel >> 3 & 1 != 0; + // SDWA: the word written, the other one kept (preserve) or zero + // (pad; a sign extension above the high word adds nothing). + let mut keep = true; + if let Some(sd) = v.sdwa { + match (sd.dst_sel, sd.dst_unused) { + (4, 2) => {} + (5, 2) => high = true, + (4 | 6, _) => keep = false, + (5, _) => (high, keep) = (true, false), + _ => return Err("an SDWA destination of a 16-bit operation"), + } + } + let c = self.cur; + let old = match inst.read(Reg::V(reg)).map(|o| self.i32_of(o)) { + Some(Ok(o)) if keep => o, + _ => self.s.m.i32(0), + }; + let (k16, low) = (self.s.m.i32(16), self.s.m.i32(0xFFFF)); + let x = self.s.m.bin(c, Bin::And, x, low); + let r = if high { + let o = self.s.m.bin(c, Bin::And, old, low); + let x = self.s.m.bin(c, Bin::Shl, x, k16); + self.s.m.bin(c, Bin::Or, o, x) + } else { + let keep = self.s.m.i32(0xFFFF_0000); + let o = self.s.m.bin(c, Bin::And, old, keep); + self.s.m.bin(c, Bin::Or, o, x) + }; + self.write_placed(inst, Reg::V(reg), r, guard); + Ok(()) + } + + /// 16-bit operations, computed in f32 or i32: f16 sums, differences and + /// products are exact there and round once to f16 (f32 has the 2 x 11 + + /// 2 bits that make double rounding harmless); `None` if `name` is none. + fn valu16(&mut self, inst: &Inst, name: &str, guard: Option) -> Option> { + const FLOAT2: &[&str] = &[ + "v_add_f16", + "v_sub_f16", + "v_subrev_f16", + "v_mul_f16", + "v_max_f16", + "v_min_f16", + ]; + const FLOAT3: &[&str] = &[ + "v_fma_f16", + "v_mad_f16", + "v_fmac_f16", + "v_mac_f16", + "v_max3_f16", + "v_min3_f16", + "v_med3_f16", + ]; + const FLOAT1: &[&str] = &[ + "v_rcp_f16", + "v_sqrt_f16", + "v_rsq_f16", + "v_log_f16", + "v_exp_f16", + "v_fract_f16", + "v_trunc_f16", + "v_floor_f16", + "v_ceil_f16", + "v_rndne_f16", + "v_sin_f16", + "v_cos_f16", + "v_cvt_f16_u16", + "v_cvt_f16_i16", + ]; + const INT: &[&str] = &[ + "v_add_nc_u16", + "v_sub_nc_u16", + "v_subrev_nc_u16", + "v_mul_lo_u16", + "v_lshlrev_b16", + "v_lshrrev_b16", + "v_ashrrev_i16", + "v_max_u16", + "v_max_i16", + "v_min_u16", + "v_min_i16", + "v_cvt_u16_f16", + "v_cvt_i16_f16", + "v_cvt_norm_i16_f16", + "v_cvt_norm_u16_f16", + ]; + let all = [FLOAT1, FLOAT2, FLOAT3, INT]; + if !all.iter().any(|l| l.contains(&name)) + && !matches!(name, "v_cvt_f16_f32" | "v_cvt_f32_f16") + { + return None; + } + Some(self.valu16_op(inst, name, guard, FLOAT1, FLOAT2, FLOAT3)) + } + + #[allow(clippy::too_many_arguments)] + fn valu16_op( + &mut self, + inst: &Inst, + name: &str, + guard: Option, + float1: &[&str], + float2: &[&str], + float3: &[&str], + ) -> Result<(), Why> { + let Fields::Valu(v) = &inst.fields else { + unreachable!() + }; + let c = self.cur; + let i32t = self.s.t.i32; + let f32t = self.s.t.f32; + if name == "v_cvt_f32_f16" { + let f = self.half_fsrc(inst, 0)?; + return self.write_f(inst, f, guard); + } + let float_result = |l: &mut Self, mut f: V| -> Result<(), Why> { + match v.omod { + 0 => {} + k => { + let factor = [1.0f32, 2.0, 4.0, 0.5][usize::from(k)]; + let k = l.s.m.f32(factor.to_bits()); + f = l.s.m.bin(l.cur, Bin::Mul, f, k); + } + } + if v.clamp { + f = l.unary(7, f); + } + // The console rounds to nearest; the host's conversion may round toward zero + // (NVIDIA's does), one step of the last place lower where the two differ. + // shortcut: the host's conversion unless `LEONIDA_F16_NEAREST=1` + // ([`f16_nearest_on`]), which costs a dozen instructions per result. + let h = if f16_nearest_on() { + l.f16_nearest(f) + } else { + l.s.op(l.cur, "legacyF32ToF16", Attr::ReadNone, i32t, 130, &[f]) + }; + l.write_half(inst, h, guard) + }; + if name == "v_cvt_f16_f32" { + let f = self.fsrc(inst, 0)?; + return float_result(self, f); + } + if float2.contains(&name) { + let (a, b) = (self.half_fsrc(inst, 0)?, self.half_fsrc(inst, 1)?); + let r = match name { + "v_add_f16" => self.s.m.bin(c, Bin::Add, a, b), + "v_sub_f16" => self.s.m.bin(c, Bin::Sub, a, b), + "v_subrev_f16" => self.s.m.bin(c, Bin::Sub, b, a), + "v_mul_f16" => self.s.m.bin(c, Bin::Mul, a, b), + "v_max_f16" => self.max_min(true, a, b), + _ => self.max_min(false, a, b), + }; + return float_result(self, r); + } + if float3.contains(&name) { + let (a, b) = (self.half_fsrc(inst, 0)?, self.half_fsrc(inst, 1)?); + let acc = if matches!(name, "v_fmac_f16" | "v_mac_f16") { + // The accumulator is the destination's half that is written. + let Some(Operand::Vector { reg, .. }) = v.dst else { + return Err("an accumulator"); + }; + let x = self.i32_of(inst.read(Reg::V(reg)).ok_or("an accumulator")?)?; + let x = if v.opsel >> 3 & 1 != 0 { + let k16 = self.s.m.i32(16); + self.s.m.bin(c, Bin::LShr, x, k16) + } else { + x + }; + let m = self.s.m.i32(0xFFFF); + let x = self.s.m.bin(c, Bin::And, x, m); + self.s + .op(c, "legacyF16ToF32", Attr::ReadNone, f32t, 131, &[x]) + } else { + self.half_fsrc(inst, 2)? + }; + let r = match name { + // shortcut: fused f16 multiply-adds as FMad in f32 (the + // product is exact; the sum rounds twice). + "v_fma_f16" | "v_fmac_f16" | "v_mad_f16" | "v_mac_f16" => self.fmad(a, b, acc), + "v_max3_f16" => { + let t = self.max_min(true, a, b); + self.max_min(true, t, acc) + } + "v_min3_f16" => { + let t = self.max_min(false, a, b); + self.max_min(false, t, acc) + } + _ => self.med3(a, b, acc), + }; + return float_result(self, r); + } + if float1.contains(&name) { + let r = match name { + "v_cvt_f16_u16" | "v_cvt_f16_i16" => { + let mut x = self.half_src(inst, 0)?; + let op = if name == "v_cvt_f16_i16" { + let k16 = self.s.m.i32(16); + let t = self.s.m.bin(c, Bin::Shl, x, k16); + x = self.s.m.bin(c, Bin::AShr, t, k16); + Cast::SiToFp + } else { + Cast::UiToFp + }; + self.s.m.cast(c, op, x, f32t) + } + "v_rcp_f16" => { + let a = self.half_fsrc(inst, 0)?; + let one = self.s.m.f32(1.0f32.to_bits()); + self.s.m.bin(c, Bin::SDiv, one, a) + } + _ => { + let a = self.half_fsrc(inst, 0)?; + let op = match name { + "v_sqrt_f16" => 24, + "v_rsq_f16" => 25, + "v_log_f16" => 23, + "v_exp_f16" => 21, + "v_fract_f16" => 22, + "v_trunc_f16" => 29, + "v_floor_f16" => 27, + "v_ceil_f16" => 28, + "v_rndne_f16" => 26, + "v_sin_f16" => 13, + _ => 12, + }; + match op { + 12 | 13 => self.trig_turns(a, op == 12), + // Any f16 in (-2^-11, 0) has fract >= 1 - 2^-12; clamp to 0x3bff (1 - 2^-11). + 22 => self.fract(a, 1.0 - 1.0 / 4096.0, 1.0 - 1.0 / 2048.0), + _ => self.unary(op, a), + } + } + }; + return float_result(self, r); + } + if matches!(name, "v_cvt_u16_f16" | "v_cvt_i16_f16") { + if v.clamp || v.omod != 0 { + return Err("modifiers on a 16-bit integer operation"); + } + // Toward zero, saturating at the 16-bit range (infinities + // included); NaN gives 0. Clamped in f32 first, where every + // f16 is exact, so the conversion never leaves i32's range + // (upstream PR #384's arithmetic; the source's abs and neg + // modifiers are applied by `half_fsrc`, as before). + let a = self.half_fsrc(inst, 0)?; + let (lo, hi) = if name == "v_cvt_u16_f16" { + (0.0f32, 65535.0f32) + } else { + (-32768.0, 32767.0) + }; + let (lo, hi) = (self.s.m.f32(lo.to_bits()), self.s.m.f32(hi.to_bits())); + let t = self.binary(35, a, lo); + let t = self.binary(36, t, hi); + let r = self.s.m.cast(c, Cast::FpToSi, t, i32t); + let nan = self.s.m.cmp(c, pred::UNO, a, a); + let z = self.s.m.i32(0); + let r = self.s.m.select(c, nan, z, r); + return self.write_half(inst, r, guard); + } + if matches!(name, "v_cvt_norm_i16_f16" | "v_cvt_norm_u16_f16") { + if v.clamp || v.omod != 0 { + return Err("modifiers on a 16-bit integer operation"); + } + let r = self.cvt_norm16(inst, name == "v_cvt_norm_i16_f16")?; + return self.write_half(inst, r, guard); + } + // 16-bit integers: computed on the low halves, the low 16 bits kept. + if v.clamp || v.omod != 0 || v.abs != 0 || v.neg != 0 { + return Err("modifiers on a 16-bit integer operation"); + } + let r = { + let (mut a, mut b) = (self.half_src(inst, 0)?, self.half_src(inst, 1)?); + let k16 = self.s.m.i32(16); + let sext = |l: &mut Self, x: V| { + let t = l.s.m.bin(c, Bin::Shl, x, k16); + l.s.m.bin(c, Bin::AShr, t, k16) + }; + if name.ends_with("_i16") { + a = sext(self, a); + b = sext(self, b); + } + let k15 = self.s.m.i32(15); + match name { + "v_add_nc_u16" => self.s.m.bin(c, Bin::Add, a, b), + "v_sub_nc_u16" => self.s.m.bin(c, Bin::Sub, a, b), + "v_subrev_nc_u16" => self.s.m.bin(c, Bin::Sub, b, a), + "v_mul_lo_u16" => self.s.m.bin(c, Bin::Mul, a, b), + "v_lshlrev_b16" | "v_lshrrev_b16" | "v_ashrrev_i16" => { + // src0 is the shift (4 bits), src1 the value. + let sh = self.s.m.bin(c, Bin::And, a, k15); + let x = if name == "v_ashrrev_i16" { + sext(self, b) + } else { + b + }; + let op = match name { + "v_lshlrev_b16" => Bin::Shl, + "v_lshrrev_b16" => Bin::LShr, + _ => Bin::AShr, + }; + self.s.m.bin(c, op, x, sh) + } + _ => { + let p = match name { + "v_max_u16" => pred::IUGT, + "v_min_u16" => pred::IULT, + "v_max_i16" => pred::SGT, + _ => pred::SLT, + }; + let t = self.s.m.cmp(c, p, a, b); + self.s.m.select(c, t, a, b) + } + } + }; + self.write_half(inst, r, guard) + } + + /// `v_cvt_norm_i16_f16` / `v_cvt_norm_u16_f16`: the f16 source (with its + /// abs/neg modifiers) clamped to [-1, 1] or [0, 1], times 32767 or 65535, + /// rounded to nearest even once from the exact product; NaN gives 0. + /// Worked on the f16's bits in integers, because in f32 the product + /// (up to 26 significant bits) would round before the rounding to an + /// integer. + fn cvt_norm16(&mut self, inst: &Inst, signed: bool) -> Result { + let Fields::Valu(v) = &inst.fields else { + unreachable!() + }; + let c = self.cur; + let k = |l: &mut Self, x: u32| l.s.m.i32(x); + let mut h = self.half_src(inst, 0)?; + if v.abs & 1 != 0 { + let m = k(self, 0x7FFF); + h = self.s.m.bin(c, Bin::And, h, m); + } + if v.neg & 1 != 0 { + let m = k(self, 0x8000); + h = self.s.m.bin(c, Bin::Xor, h, m); + } + let scale = if signed { 0x7FFF } else { 0xFFFF }; + let (k0, k1, k10) = (k(self, 0), k(self, 1), k(self, 10)); + let mag_mask = k(self, 0x7FFF); + let mag = self.s.m.bin(c, Bin::And, h, mag_mask); + let k15 = k(self, 15); + let neg = self.s.m.bin(c, Bin::LShr, h, k15); + let neg = self.s.m.cmp(c, pred::NE, neg, k0); + // |x| < 1: x = m * 2^-s with m < 2^11 and 11 <= s <= 24. + let exp = self.s.m.bin(c, Bin::LShr, mag, k10); + let man_mask = k(self, 0x3FF); + let man = self.s.m.bin(c, Bin::And, mag, man_mask); + let implicit = k(self, 0x400); + let normal = self.s.m.bin(c, Bin::Or, man, implicit); + let sub = self.s.m.cmp(c, pred::EQ, exp, k0); + let m = self.s.m.select(c, sub, man, normal); + let k25 = k(self, 25); + let s_norm = self.s.m.bin(c, Bin::Sub, k25, exp); + let k24 = k(self, 24); + let sh = self.s.m.select(c, sub, k24, s_norm); + let ks = k(self, scale); + let p = self.s.m.bin(c, Bin::Mul, m, ks); + let q = self.s.m.bin(c, Bin::LShr, p, sh); + let one_s = self.s.m.bin(c, Bin::Shl, k1, sh); + let low_mask = self.s.m.bin(c, Bin::Sub, one_s, k1); + let rem = self.s.m.bin(c, Bin::And, p, low_mask); + let half = self.s.m.bin(c, Bin::LShr, one_s, k1); + let above = self.s.m.cmp(c, pred::IUGT, rem, half); + let tie = self.s.m.cmp(c, pred::EQ, rem, half); + let odd = self.s.m.bin(c, Bin::And, q, k1); + let odd = self.s.m.cmp(c, pred::NE, odd, k0); + let tie_up = self.s.m.bin(c, Bin::And, tie, odd); + let up = self.s.m.bin(c, Bin::Or, above, tie_up); + let r = self.s.m.select(c, up, k1, k0); + let r = self.s.m.bin(c, Bin::Add, q, r); + // |x| >= 1 (and infinity) saturates; NaN gives 0. + let one_h = k(self, 0x3C00); + let big = self.s.m.cmp(c, pred::IUGE, mag, one_h); + let r = self.s.m.select(c, big, ks, r); + let inf = k(self, 0x7C00); + let nan = self.s.m.cmp(c, pred::IUGT, mag, inf); + let r = self.s.m.select(c, nan, k0, r); + let r = if signed { + let n = self.s.m.bin(c, Bin::Sub, k0, r); + self.s.m.select(c, neg, n, r) + } else { + self.s.m.select(c, neg, k0, r) + }; + let m16 = k(self, 0xFFFF); + Ok(self.s.m.bin(c, Bin::And, r, m16)) + } + + /// Half `high` of source `k` of a packed (VOP3P) operation, in the low + /// 16 bits: op_sel picks the half the low result reads, op_sel_hi the + /// half the high result reads. Packed integer instructions see the f32 + /// bits of an inline float constant. + fn packed_src(&mut self, inst: &Inst, k: usize, high: bool, float: bool) -> Result { + let Fields::Valu(v) = &inst.fields else { + unreachable!() + }; + let op = *v.src.get(k).ok_or("a missing operand")?; + let sel = if high { v.opsel_hi } else { v.opsel } >> k & 1 != 0; + let x = if float { + self.f16_operand(inst, &op)? + } else { + self.operand(inst, &op)? + }; + let c = self.cur; + let x = if sel { + let k16 = self.s.m.i32(16); + self.s.m.bin(c, Bin::LShr, x, k16) + } else { + x + }; + let m = self.s.m.i32(0xFFFF); + Ok(self.s.m.bin(c, Bin::And, x, m)) + } + + /// Packed 16-bit operations (`v_pk_*`): each half computed as the + /// 16-bit operation does, f16 through f32 as in [`Self::valu16`]. + fn packed16(&mut self, inst: &Inst, op: &str, guard: Option) -> Result<(), Why> { + let Fields::Valu(v) = &inst.fields else { + unreachable!() + }; + let float = op.ends_with("_f16"); + let n = match op { + "fma_f16" | "mad_u16" | "mad_i16" => 3, + "add_f16" | "mul_f16" | "min_f16" | "max_f16" | "add_u16" | "sub_u16" | "add_i16" + | "sub_i16" | "mul_lo_u16" | "lshlrev_b16" | "lshrrev_b16" | "ashrrev_i16" + | "max_u16" | "min_u16" | "max_i16" | "min_i16" => 2, + _ => return Err("a packed 16-bit operation"), + }; + if v.omod != 0 || !float && (v.clamp || v.neg != 0 || v.neg_hi != 0) { + return Err("modifiers on a packed integer operation"); + } + let c = self.cur; + let (i32t, f32t) = (self.s.t.i32, self.s.t.f32); + let mut halves = Vec::new(); + for high in [false, true] { + let mut xs = Vec::new(); + for k in 0..n { + let h = self.packed_src(inst, k, high, float)?; + if float { + let mut f = self + .s + .op(c, "legacyF16ToF32", Attr::ReadNone, f32t, 131, &[h]); + let neg = if high { v.neg_hi } else { v.neg }; + if neg >> k & 1 != 0 { + let z = self.s.m.f32(0x8000_0000); + f = self.s.m.bin(c, Bin::Sub, z, f); + } + xs.push(f); + } else { + xs.push(h); + } + } + let r = if float { + let mut f = match op { + "add_f16" => self.s.m.bin(c, Bin::Add, xs[0], xs[1]), + "mul_f16" => self.s.m.bin(c, Bin::Mul, xs[0], xs[1]), + "min_f16" => self.max_min(false, xs[0], xs[1]), + "max_f16" => self.max_min(true, xs[0], xs[1]), + // shortcut: FMad in f32, as v_fma_f16. + _ => self.fmad(xs[0], xs[1], xs[2]), + }; + if v.clamp { + f = self.unary(7, f); + } + self.s + .op(c, "legacyF32ToF16", Attr::ReadNone, i32t, 130, &[f]) + } else { + let k16 = self.s.m.i32(16); + let sext = |l: &mut Self, x: V| { + let t = l.s.m.bin(c, Bin::Shl, x, k16); + l.s.m.bin(c, Bin::AShr, t, k16) + }; + if op.ends_with("_i16") { + for x in &mut xs { + *x = sext(self, *x); + } + } + let k15 = self.s.m.i32(15); + match op { + "add_u16" | "add_i16" => self.s.m.bin(c, Bin::Add, xs[0], xs[1]), + "sub_u16" | "sub_i16" => self.s.m.bin(c, Bin::Sub, xs[0], xs[1]), + "mul_lo_u16" => self.s.m.bin(c, Bin::Mul, xs[0], xs[1]), + "mad_u16" | "mad_i16" => { + let m = self.s.m.bin(c, Bin::Mul, xs[0], xs[1]); + self.s.m.bin(c, Bin::Add, m, xs[2]) + } + "lshlrev_b16" | "lshrrev_b16" | "ashrrev_i16" => { + let sh = self.s.m.bin(c, Bin::And, xs[0], k15); + let o = match op { + "lshlrev_b16" => Bin::Shl, + "lshrrev_b16" => Bin::LShr, + _ => Bin::AShr, + }; + let x = if op == "ashrrev_i16" { + sext(self, xs[1]) + } else { + xs[1] + }; + self.s.m.bin(c, o, x, sh) + } + _ => { + let p = match op { + "max_u16" => pred::IUGT, + "min_u16" => pred::IULT, + "max_i16" => pred::SGT, + _ => pred::SLT, + }; + let t = self.s.m.cmp(c, p, xs[0], xs[1]); + self.s.m.select(c, t, xs[0], xs[1]) + } + } + }; + let m = self.s.m.i32(0xFFFF); + halves.push(self.s.m.bin(c, Bin::And, r, m)); + } + let k16 = self.s.m.i32(16); + let hi = self.s.m.bin(c, Bin::Shl, halves[1], k16); + let r = self.s.m.bin(c, Bin::Or, halves[0], hi); + let Some(Operand::Vector { reg, .. }) = v.dst else { + return Err("a packed result outside a VGPR"); + }; + self.write(inst, Reg::V(reg), r, guard); + Ok(()) + } + + fn integer(&mut self, inst: &Inst, name: &'static str) -> Result { + let c = self.cur; + let s = |l: &mut Self, k| l.src(inst, k); + let k = |l: &mut Self, x: u32| l.s.m.i32(x); + let m31 = |l: &mut Self, x: V| { + let k31 = l.s.m.i32(31); + l.s.m.bin(c, Bin::And, x, k31) + }; + Ok(match name { + "v_and_b32" | "v_or_b32" | "v_xor_b32" | "v_add_nc_u32" | "v_sub_nc_u32" + | "v_subrev_nc_u32" | "v_mul_lo_u32" => { + let (a, b) = (s(self, 0)?, s(self, 1)?); + let (op, a, b) = match name { + "v_and_b32" => (Bin::And, a, b), + "v_or_b32" => (Bin::Or, a, b), + "v_xor_b32" => (Bin::Xor, a, b), + "v_add_nc_u32" => (Bin::Add, a, b), + "v_sub_nc_u32" => (Bin::Sub, a, b), + "v_subrev_nc_u32" => (Bin::Sub, b, a), + _ => (Bin::Mul, a, b), + }; + self.s.m.bin(c, op, a, b) + } + "v_xnor_b32" => { + let (a, b) = (s(self, 0)?, s(self, 1)?); + let x = self.s.m.bin(c, Bin::Xor, a, b); + let ones = k(self, u32::MAX); + self.s.m.bin(c, Bin::Xor, x, ones) + } + "v_not_b32" => { + let a = s(self, 0)?; + let ones = k(self, u32::MAX); + self.s.m.bin(c, Bin::Xor, a, ones) + } + "v_lshlrev_b32" | "v_lshrrev_b32" | "v_ashrrev_i32" => { + let (sh, a) = (s(self, 0)?, s(self, 1)?); + let sh = m31(self, sh); + let op = match name { + "v_lshlrev_b32" => Bin::Shl, + "v_lshrrev_b32" => Bin::LShr, + _ => Bin::AShr, + }; + self.s.m.bin(c, op, a, sh) + } + "v_lshl_add_u32" | "v_lshl_or_b32" | "v_add_lshl_u32" | "v_and_or_b32" + | "v_or3_b32" | "v_xad_u32" | "v_add3_u32" | "v_xor3_b32" => { + let (a, b, d) = (s(self, 0)?, s(self, 1)?, s(self, 2)?); + match name { + "v_lshl_add_u32" | "v_lshl_or_b32" => { + let b = m31(self, b); + let t = self.s.m.bin(c, Bin::Shl, a, b); + let op = if name == "v_lshl_add_u32" { + Bin::Add + } else { + Bin::Or + }; + self.s.m.bin(c, op, t, d) + } + "v_add_lshl_u32" => { + let t = self.s.m.bin(c, Bin::Add, a, b); + let d = m31(self, d); + self.s.m.bin(c, Bin::Shl, t, d) + } + _ => { + let (o1, o2) = match name { + "v_and_or_b32" => (Bin::And, Bin::Or), + "v_or3_b32" => (Bin::Or, Bin::Or), + "v_xad_u32" => (Bin::Xor, Bin::Add), + "v_add3_u32" => (Bin::Add, Bin::Add), + _ => (Bin::Xor, Bin::Xor), + }; + let t = self.s.m.bin(c, o1, a, b); + self.s.m.bin(c, o2, t, d) + } + } + } + "v_mul_u32_u24" | "v_mul_i32_i24" => { + let (a, b) = (s(self, 0)?, s(self, 1)?); + let (sh, op) = ( + k(self, 8), + if name == "v_mul_i32_i24" { + Bin::AShr + } else { + Bin::LShr + }, + ); + let a = self.s.m.bin(c, Bin::Shl, a, sh); + let a = self.s.m.bin(c, op, a, sh); + let b = self.s.m.bin(c, Bin::Shl, b, sh); + let b = self.s.m.bin(c, op, b, sh); + self.s.m.bin(c, Bin::Mul, a, b) + } + "v_bfe_u32" | "v_bfe_i32" => { + let (a, off, w) = (s(self, 0)?, s(self, 1)?, s(self, 2)?); + let w = m31(self, w); + self.bfe(a, off, w, name == "v_bfe_i32") + } + "v_bfi_b32" => { + let (m, a, b) = (s(self, 0)?, s(self, 1)?, s(self, 2)?); + let ones = k(self, u32::MAX); + let nm = self.s.m.bin(c, Bin::Xor, m, ones); + let x = self.s.m.bin(c, Bin::And, m, a); + let y = self.s.m.bin(c, Bin::And, nm, b); + self.s.m.bin(c, Bin::Or, x, y) + } + "v_max_i32" | "v_min_i32" | "v_max_u32" | "v_min_u32" => { + let (a, b) = (s(self, 0)?, s(self, 1)?); + let p = match name { + "v_max_i32" => pred::SGT, + "v_min_i32" => pred::SLT, + "v_max_u32" => pred::IUGT, + _ => pred::IULT, + }; + let t = self.s.m.cmp(c, p, a, b); + self.s.m.select(c, t, a, b) + } + "v_mul_hi_u32" | "v_mul_hi_i32" => { + let (a, b) = (s(self, 0)?, s(self, 1)?); + self.mul_hi(a, b, name == "v_mul_hi_i32") + } + "v_alignbit_b32" | "v_alignbyte_b32" => { + // The low dword of {a, b} >> shift. + let (a, b, sh) = (s(self, 0)?, s(self, 1)?, s(self, 2)?); + let sh = if name == "v_alignbyte_b32" { + let three = k(self, 3); + let t = self.s.m.bin(c, Bin::And, sh, three); + let k3 = k(self, 3); + self.s.m.bin(c, Bin::Shl, t, k3) + } else { + m31(self, sh) + }; + let k32 = k(self, 32); + let lo = self.s.m.bin(c, Bin::LShr, b, sh); + let left = self.s.m.bin(c, Bin::Sub, k32, sh); + let left = m31(self, left); + let hi = self.s.m.bin(c, Bin::Shl, a, left); + let zero = k(self, 0); + let none = self.s.m.cmp(c, pred::EQ, sh, zero); + let hi = self.s.m.select(c, none, zero, hi); + self.s.m.bin(c, Bin::Or, lo, hi) + } + "v_bfrev_b32" => { + let a = s(self, 0)?; + self.s + .op(c, "unary.i32", Attr::ReadNone, self.s.t.i32, 30, &[a]) + } + "v_bcnt_u32_b32" => { + let (a, b) = (s(self, 0)?, s(self, 1)?); + let n = self + .s + .op(c, "unaryBits.i32", Attr::ReadNone, self.s.t.i32, 31, &[a]); + self.s.m.bin(c, Bin::Add, n, b) + } + "v_mad_u32_u24" | "v_mad_i32_i24" => { + let (a, b, d) = (s(self, 0)?, s(self, 1)?, s(self, 2)?); + let (sh, op) = ( + k(self, 8), + if name == "v_mad_i32_i24" { + Bin::AShr + } else { + Bin::LShr + }, + ); + let a = self.s.m.bin(c, Bin::Shl, a, sh); + let a = self.s.m.bin(c, op, a, sh); + let b = self.s.m.bin(c, Bin::Shl, b, sh); + let b = self.s.m.bin(c, op, b, sh); + let m = self.s.m.bin(c, Bin::Mul, a, b); + self.s.m.bin(c, Bin::Add, m, d) + } + "v_min3_i32" | "v_max3_i32" | "v_min3_u32" | "v_max3_u32" | "v_med3_i32" + | "v_med3_u32" => { + let (a, b, d) = (s(self, 0)?, s(self, 1)?, s(self, 2)?); + let signed = name.ends_with("i32"); + let (lt, gt) = if signed { + (pred::SLT, pred::SGT) + } else { + (pred::IULT, pred::IUGT) + }; + let pick = |l: &mut Self, p, x, y| { + let t = l.s.m.cmp(c, p, x, y); + l.s.m.select(c, t, x, y) + }; + match &name[2..6] { + "min3" => { + let t = pick(self, lt, a, b); + pick(self, lt, t, d) + } + "max3" => { + let t = pick(self, gt, a, b); + pick(self, gt, t, d) + } + _ => { + let lo = pick(self, lt, a, b); + let hi = pick(self, gt, a, b); + let t = pick(self, lt, hi, d); + pick(self, gt, lo, t) + } + } + } + "v_perm_b32" => { + // Byte i of the result is byte S of {src0, src1} (src1 the + // low dword) for selector byte S below 8; 8-11 repeat the + // sign of bytes 1 and 3 of src1, then of src0; 12 is 0x00, + // higher 0xFF. + let Fields::Valu(v) = &inst.fields else { + unreachable!() + }; + let sel = match v.src.get(2) { + Some(&Operand::Literal(x)) => x, + Some(&Operand::Const(k)) => crate::resource::inline(k).ok_or(name)?, + _ => { + // A computed selector: each byte picked at run time. + let (a, b, sv) = (s(self, 0)?, s(self, 1)?, s(self, 2)?); + let mut r = k(self, 0); + for i in 0..4u32 { + let (sh, ff) = (k(self, 8 * i), k(self, 0xFF)); + let sel = self.s.m.bin(c, Bin::LShr, sv, sh); + let sel = self.s.m.bin(c, Bin::And, sel, ff); + // Select a dword and a byte within it. + // Later selects handle codes 8 and above. + let four = k(self, 4); + let zero = k(self, 0); + let high = self.s.m.bin(c, Bin::And, sel, four); + let high = self.s.m.cmp(c, pred::NE, high, zero); + let word = self.s.m.select(c, high, a, b); + let three = k(self, 3); + let index = self.s.m.bin(c, Bin::And, sel, three); + let bits = self.s.m.bin(c, Bin::Shl, index, three); + let x = self.s.m.bin(c, Bin::LShr, word, bits); + let mut byte = self.s.m.bin(c, Bin::And, x, ff); + // 8-11: the sign of bytes 1, 3 of src1, then of src0. + for (n, src, bit) in [(8, b, 15), (9, b, 31), (10, a, 15), (11, a, 31)] + { + let left = k(self, 31 - bit); + let t = self.s.m.bin(c, Bin::Shl, src, left); + let k31 = k(self, 31); + let t = self.s.m.bin(c, Bin::AShr, t, k31); + let t = self.s.m.bin(c, Bin::And, t, ff); + let kn = k(self, n); + let is = self.s.m.cmp(c, pred::EQ, sel, kn); + byte = self.s.m.select(c, is, t, byte); + } + let (k12, z) = (k(self, 12), k(self, 0)); + let is12 = self.s.m.cmp(c, pred::EQ, sel, k12); + byte = self.s.m.select(c, is12, z, byte); + let above = self.s.m.cmp(c, pred::IUGT, sel, k12); + byte = self.s.m.select(c, above, ff, byte); + let at = k(self, 8 * i); + let byte = self.s.m.bin(c, Bin::Shl, byte, at); + r = self.s.m.bin(c, Bin::Or, r, byte); + } + return Ok(r); + } + }; + let (a, b) = (s(self, 0)?, s(self, 1)?); + let mut r = k(self, 0); + for i in 0..4 { + let pick = sel >> (8 * i) & 0xFF; + let byte = match pick { + 0..=7 => { + let (src, n) = if pick < 4 { (b, pick) } else { (a, pick - 4) }; + let sh = k(self, 8 * n); + let t = self.s.m.bin(c, Bin::LShr, src, sh); + let ff = k(self, 0xFF); + self.s.m.bin(c, Bin::And, t, ff) + } + 8..=11 => { + let src = if pick < 10 { b } else { a }; + let bit = if pick % 2 == 0 { 15 } else { 31 }; + let left = k(self, 31 - bit); + let t = self.s.m.bin(c, Bin::Shl, src, left); + let k31 = k(self, 31); + let t = self.s.m.bin(c, Bin::AShr, t, k31); + let ff = k(self, 0xFF); + self.s.m.bin(c, Bin::And, t, ff) + } + 12 => continue, + _ => k(self, 0xFF), + }; + let at = k(self, 8 * i); + let byte = self.s.m.bin(c, Bin::Shl, byte, at); + r = self.s.m.bin(c, Bin::Or, r, byte); + } + r + } + "v_bfm_b32" => { + // ((1 << src0[4:0]) - 1) << src1[4:0] + let (a, b) = (s(self, 0)?, s(self, 1)?); + let one = k(self, 1); + let (a, b) = (m31(self, a), m31(self, b)); + let m = self.s.m.bin(c, Bin::Shl, one, a); + let m = self.s.m.bin(c, Bin::Sub, m, one); + self.s.m.bin(c, Bin::Shl, m, b) + } + "v_cvt_pk_u8_f32" => { + // src0 rounded to nearest even and saturated to a byte, into + // byte src1[1:0] of src2. + let f = self.fsrc(inst, 0)?; + let (b, d) = (s(self, 1)?, s(self, 2)?); + let f = self.unary(26, f); + let (zero, max) = (self.s.m.f32(0), self.s.m.f32(255.0f32.to_bits())); + let f = self.binary(35, f, zero); + let f = self.binary(36, f, max); + let x = self.s.m.cast(c, Cast::FpToUi, f, self.s.t.i32); + let (three, k3) = (k(self, 3), k(self, 3)); + let sh = self.s.m.bin(c, Bin::And, b, three); + let sh = self.s.m.bin(c, Bin::Shl, sh, k3); + let x = self.s.m.bin(c, Bin::Shl, x, sh); + let ff = k(self, 0xFF); + let hole = self.s.m.bin(c, Bin::Shl, ff, sh); + let ones = k(self, u32::MAX); + let hole = self.s.m.bin(c, Bin::Xor, hole, ones); + let d = self.s.m.bin(c, Bin::And, d, hole); + self.s.m.bin(c, Bin::Or, d, x) + } + "v_ffbl_b32" => { + // -1 for zero, as DXIL's first-bit-low. + let a = s(self, 0)?; + self.s + .op(c, "unaryBits.i32", Attr::ReadNone, self.s.t.i32, 32, &[a]) + } + "v_mbcnt_lo_u32_b32" | "v_mbcnt_hi_u32_b32" => { + // Bits of the mask's low (high) half below this lane, plus src1: + // with an all-ones mask, the lane index. + let (a, b) = (s(self, 0)?, s(self, 1)?); + // Mesh lanes are the console's by construction; pixel and + // vertex lanes are the host's, as their masks are. + if self.mask_data == MaskData::Host { + // Host lanes: the mask must be one (a ballot) or all lanes. + let Fields::Valu(v) = &inst.fields else { + unreachable!() + }; + let host = match v.src.first() { + Some(&Operand::Const(193)) => true, + Some(&Operand::Scalar { code, .. }) => { + inst.read(Reg::S(code)).is_some_and(|m| { + self.x.st.masks.contains_key(&m) || self.x.st.highs.contains_key(&m) + }) + } + _ => false, + }; + if !host { + return Err("v_mbcnt of a mask that is no ballot (console lane layout)"); + } + self.s.flags |= flags::WAVE_OPS; + } else if self.s.mesh.is_none() { + self.cross_lane(false)?; + } + let lane = self.console_lane(); + let below = if name == "v_mbcnt_lo_u32_b32" { + lane + } else { + let (k32, z) = (k(self, 32), k(self, 0)); + let t = self.s.m.bin(c, Bin::Sub, lane, k32); + let low = self.s.m.cmp(c, pred::IULT, lane, k32); + self.s.m.select(c, low, z, t) + }; + // (1 << below) - 1, all ones from 32 on. + let (one, k32, ones) = (k(self, 1), k(self, 32), k(self, u32::MAX)); + let sh = m31(self, below); + let m = self.s.m.bin(c, Bin::Shl, one, sh); + let m = self.s.m.bin(c, Bin::Sub, m, one); + let full = self.s.m.cmp(c, pred::IUGE, below, k32); + let m = self.s.m.select(c, full, ones, m); + let x = self.s.m.bin(c, Bin::And, a, m); + let n = self + .s + .op(c, "unaryBits.i32", Attr::ReadNone, self.s.t.i32, 31, &[x]); + self.s.m.bin(c, Bin::Add, n, b) + } + _ => return Err(name), + }) + } + + fn compare(&mut self, inst: &Inst, rest: &str) -> Result<(), Why> { + let (op, ty) = rest.rsplit_once('_').ok_or("a compare")?; + let c = self.cur; + let r = match ty { + "f32" | "f16" if op == "class" => { + // Bit k of src1 tests class k: signalling NaN, quiet NaN, + // -inf, -normal, -denormal, -0, +0, +denormal, +normal, +inf. + let f16 = ty == "f16"; + let x = if f16 { + let Fields::Valu(v) = &inst.fields else { + unreachable!() + }; + let mut h = self.half_src(inst, 0)?; + if v.abs & 1 != 0 { + let m = self.s.m.i32(0x7FFF); + h = self.s.m.bin(c, Bin::And, h, m); + } + if v.neg & 1 != 0 { + let s = self.s.m.i32(0x8000); + h = self.s.m.bin(c, Bin::Xor, h, s); + } + h + } else { + let x = self.fsrc(inst, 0)?; + self.as_int(x) + }; + let mask = self.src(inst, 1)?; + let k = |l: &mut Self, v: u32| l.s.m.i32(v); + let (exp_sh, sign_sh, exp_mask, mant_mask, quiet_bit) = if f16 { + (10, 15, 0x1F, 0x03FF, 0x0200) + } else { + (23, 31, 0xFF, 0x7F_FFFF, 0x40_0000) + }; + let (k_exp, k_sign, k_emax, mant, quiet) = ( + k(self, exp_sh), + k(self, sign_sh), + k(self, exp_mask), + k(self, mant_mask), + k(self, quiet_bit), + ); + let e = self.s.m.bin(c, Bin::LShr, x, k_exp); + let e = self.s.m.bin(c, Bin::And, e, k_emax); + let m = self.s.m.bin(c, Bin::And, x, mant); + let neg = self.s.m.bin(c, Bin::LShr, x, k_sign); + let zero = k(self, 0); + let (e0, emax) = ( + self.s.m.cmp(c, pred::EQ, e, zero), + self.s.m.cmp(c, pred::EQ, e, k_emax), + ); + let m0 = self.s.m.cmp(c, pred::EQ, m, zero); + let q = self.s.m.bin(c, Bin::And, x, quiet); + let q = self.s.m.cmp(c, pred::NE, q, zero); + // Positive classes 6-9; negative ones are 11 minus those. + let (normal, inf, zero_c, denorm) = + (k(self, 8), k(self, 9), k(self, 6), k(self, 7)); + let t = self.s.m.select(c, m0, zero_c, denorm); + let t = self.s.m.select(c, e0, t, normal); + let t = self.s.m.select(c, emax, inf, t); + let eleven = k(self, 11); + let mirrored = self.s.m.bin(c, Bin::Sub, eleven, t); + let is_neg = self.s.m.cmp(c, pred::NE, neg, zero); + let t = self.s.m.select(c, is_neg, mirrored, t); + let (one, snan) = (k(self, 1), k(self, 0)); + let nan_class = self.s.m.select(c, q, one, snan); + let yes = self.s.m.bool(true); + let nan = self.s.m.bin(c, Bin::Xor, m0, yes); + let nan = self.s.m.bin(c, Bin::And, nan, emax); + let t = self.s.m.select(c, nan, nan_class, t); + let bit = self.s.m.bin(c, Bin::LShr, mask, t); + let bit = self.s.m.bin(c, Bin::And, bit, one); + self.s.m.cmp(c, pred::NE, bit, zero) + } + "f32" | "f16" => { + let (a, b) = if ty == "f16" { + (self.half_fsrc(inst, 0)?, self.half_fsrc(inst, 1)?) + } else { + (self.fsrc(inst, 0)?, self.fsrc(inst, 1)?) + }; + if op == "lg" { + // Ordered and not equal, false for a NaN, as `olt | ogt`. + // `fcmp one` means the same, but the AMD D3D12 driver + // runs it as unordered (true for a NaN) where NVIDIA + // and WARP do not; olt and ogt agree on all three. + let lt = self.s.m.cmp(c, pred::OLT, a, b); + let gt = self.s.m.cmp(c, pred::OGT, a, b); + self.s.m.bin(c, Bin::Or, lt, gt) + } else { + let p = match op { + "f" => pred::FALSE, + "lt" => pred::OLT, + "eq" => pred::OEQ, + "le" => pred::OLE, + "gt" => pred::OGT, + "ge" => pred::OGE, + "o" => pred::ORD, + "u" => pred::UNO, + "nge" => pred::ULT, + "nlg" => pred::UEQ, + "ngt" => pred::ULE, + "nle" => pred::UGT, + "neq" => pred::UNE, + "nlt" => pred::UGE, + "tru" => pred::TRUE, + _ => return Err(inst.name()), + }; + self.s.m.cmp(c, p, a, b) + } + } + "u64" | "i64" => { + let (a, b) = (self.src64(inst, 0)?, self.src64(inst, 1)?); + let signed = ty == "i64"; + let p = match op { + "eq" => pred::EQ, + "ne" | "lg" => pred::NE, + "lt" if signed => pred::SLT, + "le" if signed => pred::SLE, + "gt" if signed => pred::SGT, + "ge" if signed => pred::SGE, + "lt" => pred::IULT, + "le" => pred::IULE, + "gt" => pred::IUGT, + "ge" => pred::IUGE, + _ => return Err("a 64-bit compare"), + }; + self.s.m.cmp(c, p, a, b) + } + "u32" | "i32" | "u16" | "i16" => { + let (a, b) = if ty.ends_with("16") { + let (mut a, mut b) = (self.half_src(inst, 0)?, self.half_src(inst, 1)?); + if ty == "i16" { + let k16 = self.s.m.i32(16); + for x in [&mut a, &mut b] { + let t = self.s.m.bin(c, Bin::Shl, *x, k16); + *x = self.s.m.bin(c, Bin::AShr, t, k16); + } + } + (a, b) + } else { + (self.src(inst, 0)?, self.src(inst, 1)?) + }; + let signed = ty == "i32" || ty == "i16"; + let p = match op { + "eq" => pred::EQ, + "ne" | "lg" => pred::NE, + "lt" if signed => pred::SLT, + "le" if signed => pred::SLE, + "gt" if signed => pred::SGT, + "ge" if signed => pred::SGE, + "lt" => pred::IULT, + "le" => pred::IULE, + "gt" => pred::IUGT, + "ge" => pred::IUGE, + "f" | "t" => { + self.lane(inst, Some(op == "t")); + return Ok(()); + } + _ => return Err("an integer compare"), + }; + self.s.m.cmp(c, p, a, b) + } + _ => return Err(inst.name()), + }; + self.lane_bits_for(inst, r); + Ok(()) + } + + fn lane(&mut self, inst: &Inst, value: Option) { + let b = self.s.m.bool(value == Some(true)); + self.lane_bits_for(inst, b); + } + + fn lane_bits_for(&mut self, inst: &Inst, r: V) { + let Fields::Valu(v) = &inst.fields else { + return; + }; + let code = if inst.name().starts_with("v_cmpx") { + Some(EXEC) + } else { + match v.dst { + Some(Operand::Scalar { code, .. }) => Some(code), + _ => None, + } + }; + if let Some(lo) = code.and_then(|c| inst.write(Reg::S(c))) { + self.lane_bits.insert(lo, r); + } + for &(_, w) in &inst.writes { + self.vals + .entry(w) + .or_insert(Val::Missing("a lane mask read as data")); + } + } + + fn interp(&mut self, inst: &Inst, site: Site) -> Result<(), Why> { + let Some(&interp) = self.interps.get(&site) else { + // The first half of a pair: its second half interpolates the + // attribute itself, so nothing needs this half's partial sum. + // But an f16 second half that writes the high half of the + // register this one wrote keeps the low half as it was (the + // console compiler reuses the register; the low half is not + // read), so the register needs a value: 0. + let name = inst.name(); + if name == "v_interp_p1_f32" || name == "v_interp_p1ll_f16" { + let dst = match &inst.fields { + Fields::Vintrp { dst, .. } => Some(*dst), + Fields::Valu(v) => v.dst, + _ => None, + }; + if let Some(Operand::Vector { reg, .. }) = dst { + let zero = self.s.m.i32(0); + self.write(inst, Reg::V(reg), zero, None); + return Ok(()); + } + } + return Err(FIRST_HALF); + }; + let name = inst.name(); + let (dst, src) = match &inst.fields { + Fields::Vintrp { dst, src, .. } => (*dst, Some(*src)), + Fields::Valu(v) => { + if v.abs != 0 || v.neg != 0 { + return Err("interpolation operand modifiers"); + } + (v.dst.ok_or("an interpolation")?, v.src.get(1).copied()) + } + _ => unreachable!(), + }; + let Operand::Vector { reg, .. } = dst else { + return Err("an interpolation"); + }; + // A float operand of the instruction. + let float = |l: &mut Self, op: Option| -> Result { + let x = l.operand(inst, &op.ok_or("an interpolation operand")?)?; + Ok(l.as_float(x)) + }; + // What the result adds to the evaluated channel (a second half's + // first half, when the halves evaluate on their own). + let mut add = None; + let (attribute, eval) = match *interp { + Interp::Interpolated { + attribute, + barycentric, + .. + } => { + let mode = interp_mode(barycentric).ok_or("pull-model interpolation")?; + let eval = if self.per_vertex(attribute.row) { + // The element is read per vertex elsewhere, so it is + // constant: weigh its vertices with SV_Barycentrics. + let mut ij = [None; 2]; + for (index, w) in ij.iter_mut().enumerate() { + let x = match self.barycentric(barycentric, index as u8) { + Val::I32(x) => x, + Val::Missing(w) => return Err(w), + Val::Bit(_) => unreachable!(), + }; + *w = Some(self.as_float(x)); + } + Eval::Weights { + p0: true, + i: ij[0], + j: ij[1], + } + } else { + Eval::Mode(mode) + }; + (attribute, eval) + } + // P0, the provoking vertex: a flat (nointerpolation) input. + Interp::Vertex { + attribute, + vertex: 2, + } => (attribute, Eval::Mode(1)), + // P10 and P20: what the first and second halves weigh, P1 - P0 + // and P2 - P0, which is what the hardware holds for an + // attribute the program also interpolates. + Interp::Vertex { attribute, vertex } if self.interpolated(attribute.row) => { + let one = Some(self.s.m.f32(1f32.to_bits())); + let (i, j) = if vertex == 0 { + (one, None) + } else { + (None, one) + }; + (attribute, Eval::Weights { p0: false, i, j }) + } + Interp::Vertex { .. } => return Err("a non-provoking vertex value"), + // A half of an interpolation with computed i or j: P0 + i P10, + // or the old dst (f16: the third operand) + j P20. + Interp::Weighted { attribute } if name.starts_with("v_interp_p1") => { + let i = Some(float(self, src)?); + ( + attribute, + Eval::Weights { + p0: true, + i, + j: None, + }, + ) + } + Interp::Weighted { attribute } => { + let old = match &inst.fields { + Fields::Valu(v) => v.src.get(2).copied(), + _ => Some(dst), + }; + add = Some(float(self, old)?); + let j = Some(float(self, src)?); + ( + attribute, + Eval::Weights { + p0: false, + i: None, + j, + }, + ) + } + }; + let packing = match &self.x.native.io { + StageIo::Ps { inputs, .. } => inputs + .iter() + .find(|i| i.row == attribute.row && i.fp16) + .map(|i| { + let packs = if i.pack2 { + input_packs(&self.x.native.io, &self.s.inputs) + } else { + Vec::new() + }; + (i.pack2, packs) + }), + _ => None, + }; + let f16 = name.ends_with("_f16"); + // The evaluated channel plus `add`, as a float. + let total = |l: &mut Self, row: u8, ch: u8| -> Result { + let x = l.eval_channel(row, ch, eval)?; + let x = l.as_float(x); + Ok(match add { + Some(a) => l.s.m.bin(l.cur, Bin::Add, a, x), + None => x, + }) + }; + let x = match packing { + None if f16 || attribute.high => return Err("a 16-bit read of a 32-bit input"), + None => { + let x = total(self, attribute.row, attribute.channel)?; + self.as_int(x) + } + Some((pack2, packs)) => { + // 16-bit values: one in the low half of each dword, or two + // per dword (`packed_half`); the host's are 32-bit floats. + let half = |l: &mut Self, h: u8| -> Result, Why> { + let src = if pack2 { + packed_half(&l.s.inputs, &packs, attribute.row, h) + } else { + h.is_multiple_of(2).then_some((attribute.row, h / 2)) + }; + match src { + Some((row, ch)) => total(l, row, ch).map(Some), + None => Ok(None), + } + }; + let to_f16 = |l: &mut Self, f: V| { + let i32t = l.s.t.i32; + l.s.op(l.cur, "legacyF32ToF16", Attr::ReadNone, i32t, 130, &[f]) + }; + let h = 2 * attribute.channel + u8::from(attribute.high); + let c = self.cur; + if name == "v_interp_p1ll_f16" { + // An f32 result from 16-bit vertex values. + let f = half(self, h)?.ok_or("a packed input half no element holds")?; + self.as_int(f) + } else if f16 { + let f = half(self, h)?.ok_or("a packed input half no element holds")?; + let lo = to_f16(self, f); + self.low_half(inst, reg, lo) + } else if matches!(eval, Eval::Mode(1)) { + // The whole dword of a flat input: both halves. + let h = 2 * attribute.channel; + let z = self.s.m.i32(0); + let lo = match half(self, h)? { + Some(f) => to_f16(self, f), + None => z, + }; + let hi = match half(self, h + 1)? { + Some(f) => to_f16(self, f), + None => z, + }; + let k16 = self.s.m.i32(16); + let hi = self.s.m.bin(c, Bin::Shl, hi, k16); + self.s.m.bin(c, Bin::Or, lo, hi) + } else { + return Err("32-bit interpolation of a 16-bit input"); + } + } + }; + // A pixel interpolates in every lane; guards only hide inactive ones. + self.write(inst, Reg::V(reg), x, None); + Ok(()) + } + + /// Whether the program reads attribute row `row` per vertex (an + /// interpolation with computed barycentrics, or P10 or P20): then its + /// element is declared constant and read with `attributeAtVertex`. + fn per_vertex(&self, row: u8) -> bool { + self.x.io.interps.iter().any(|(_, i)| match *i { + Interp::Weighted { attribute } => attribute.row == row, + Interp::Vertex { attribute, vertex } => { + attribute.row == row && vertex != 2 && self.interpolated(row) + } + Interp::Interpolated { .. } => false, + }) + } + + /// Whether the program interpolates attribute row `row` (so the + /// hardware holds P1 - P0 and P2 - P0 for it). + fn interpolated(&self, row: u8) -> bool { + self.x.io.interps.iter().any(|(_, i)| match *i { + Interp::Interpolated { attribute, .. } | Interp::Weighted { attribute } => { + attribute.row == row + } + Interp::Vertex { .. } => false, + }) + } + + /// Channel `ch` of input row `row` evaluated as `eval` says, as raw bits. + fn eval_channel(&mut self, row: u8, ch: u8, eval: Eval) -> Result { + let (id, col) = self + .find_input(row, ch) + .ok_or("an input the signature lacks")?; + let mode = match eval { + Eval::Mode(mode) => mode, + Eval::Weights { .. } => 1, + }; + let e = &mut self.s.inputs[id]; + if e.interp != mode && e.usage != 0 { + return Err("one input interpolated two ways"); + } + e.interp = mode; + let Eval::Weights { p0, i, j } = eval else { + return match self.load_any_input(id, col) { + Val::I32(x) => Ok(x), + _ => Err("an input"), + }; + }; + let v0 = self.vertex_input(id, col, 0); + let c = self.cur; + let mut acc = p0.then_some(v0); + for (k, w) in [(1, i), (2, j)] { + let Some(w) = w else { continue }; + let vk = self.vertex_input(id, col, k); + let d = self.s.m.bin(c, Bin::Sub, vk, v0); + acc = Some(match acc { + Some(a) => self.fmad(w, d, a), + None => self.s.m.bin(c, Bin::Mul, w, d), + }); + } + let acc = acc.ok_or("an interpolation")?; + Ok(self.as_int(acc)) + } + + /// Vertex `k` (0 the provoking vertex, as `barycentric` orders them) + /// of a constant input element's channel, as a float. + fn vertex_input(&mut self, id: usize, col: u8, k: u8) -> V { + let e = &mut self.s.inputs[id]; + e.usage |= 1 << col; + let int = e.comp != 9; + let (ty, suffix) = if int { + (self.s.t.i32, ".i32") + } else { + (self.s.t.f32, ".f32") + }; + self.s.flags |= flags::BARYCENTRICS; + let entry = self.s.entry; + let args = [ + self.s.m.i32(id as u32), + self.s.m.i32(0), + self.s.m.i8(col), + self.s.m.i8(k), + ]; + let v = self.s.op( + entry, + &format!("attributeAtVertex{suffix}"), + Attr::ReadNone, + ty, + 137, + &args, + ); + if int { + self.s.m.cast(entry, Cast::Bitcast, v, self.s.t.f32) + } else { + v + } + } + + /// `x` (an f16 in the low bits) as the low half of VGPR `reg`: 16-bit + /// results keep the register's high half (GFX10). + fn low_half(&mut self, inst: &Inst, reg: u8, x: V) -> V { + let c = self.cur; + let old = match inst.read(Reg::V(reg)).map(|o| self.i32_of(o)) { + Some(Ok(o)) => o, + _ => self.s.m.i32(0), + }; + let (high, low) = (self.s.m.i32(0xFFFF_0000), self.s.m.i32(0xFFFF)); + let old = self.s.m.bin(c, Bin::And, old, high); + let x = self.s.m.bin(c, Bin::And, x, low); + self.s.m.bin(c, Bin::Or, old, x) + } + + fn image(&mut self, inst: &Inst, b: usize, i: usize) -> Result<(), Why> { + let Fields::Image { + data, + addr, + dmask, + dim, + unorm, + a16, + d16, + tfe, + lwe, + .. + } = &inst.fields + else { + unreachable!() + }; + if *tfe || *lwe { + return Err("an image access with tfe or lwe"); + } + let name = inst.name(); + // A load or sample with no channel enabled returns the first. + let dmask = if *dmask == 0 { &1 } else { dmask }; + let site = (b, i); + let guard = self.guard(b, i)?; + let c = self.cur; + let (kind, coords) = match dim { + 0 => (1, 1), + 1 => (2, 2), + 2 => (4, 3), + // Sampled (face coordinates and face, see `cube_direction`) or + // sized only. + 3 if name.starts_with("image_sample") + || name.starts_with("image_gather") + || name == "image_get_resinfo" => + { + (5, 3) + } + 4 => (6, 2), + 5 => (7, 3), + _ => return Err("an image dimension (cube loads or MSAA)"), + }; + // Address VGPRs in order. + let mut regs = Vec::new(); + for a in addr { + if let Operand::Vector { reg, dwords } = *a { + regs.extend((0..dwords).map(|k| reg + k)); + } + } + // Full 32-bit address VGPR at `reg_idx` (offset, bias, z-compare). + let addr_u32 = |l: &mut Self, reg_idx: usize| -> Result { + let r = *regs.get(reg_idx).ok_or("an image address")?; + let v = inst.read(Reg::V(r)).ok_or("an image address")?; + l.i32_of(v) + }; + // With a16, two 16-bit components per VGPR starting at `base_reg`, low half first. + let addr_packed = |l: &mut Self, base_reg: usize, k: usize| -> Result { + let x = addr_u32(l, base_reg + if *a16 { k / 2 } else { k })?; + if !*a16 { + return Ok(x); + } + let c = l.cur; + let (sh, mask) = (l.s.m.i32(16 * (k as u32 % 2)), l.s.m.i32(0xFFFF)); + let x = l.s.m.bin(c, Bin::LShr, x, sh); + Ok(l.s.m.bin(c, Bin::And, x, mask)) + }; + let addr_val = |l: &mut Self, k: usize| -> Result { addr_packed(l, 0, k) }; + let src = self + .descriptors + .get(&(site, false)) + .copied() + .ok_or("an untracked image")?; + let store = name.starts_with("image_store"); + let uav = store + || self + .used_kind(src) + .is_some_and(|u| u.kind == ResourceType::Uav); + let props = (kind | if uav { 0x1000 } else { 0 }, 0x409); + if let Some(op) = name.strip_prefix("image_atomic_") { + // GLC returns the old value. DXIL implements subtraction by adding + // the two's complement of the operand at the same width. + let code = match op { + "add" | "sub" => 0, + "and" => 1, + "or" => 2, + "xor" => 3, + "smin" => 4, + "smax" => 5, + "umin" => 6, + "umax" => 7, + "swap" => 8, + "cmpswap" => u32::MAX, + _ => return Err(name), + }; + let Fields::Image { cache, .. } = &inst.fields else { + unreachable!() + }; + if *d16 || *a16 { + return Err("a 16-bit image atomic"); + } + // Compare-exchange consumes a replacement followed by a comparand. + let compare = code == u32::MAX; + let wide = match (compare, *dmask) { + (false, 1) | (true, 3) => false, + (false, 3) | (true, 15) => true, + _ => return Err("an image atomic data mask"), + }; + let iu = self.s.m.undef(self.s.t.i32); + let mut cs = vec![iu; 3]; + for (k, slot) in cs.iter_mut().enumerate().take(coords) { + *slot = addr_val(self, k)?; + } + let Operand::Vector { reg, .. } = *data else { + return Err("image atomic data"); + }; + let width = if wide { 2 } else { 1 }; + let vals = self.vgprs(inst, data, if compare { 2 * width } else { width })?; + let (ty, component) = if wide { + self.s.flags |= flags::INT64 | flags::ATOMIC_TYPED64 | flags::ATOMIC_HEAP64; + (self.s.m.int(64), 0x107) // one uint64_t in an R32G32_UINT view + } else { + (self.s.t.i32, 0x105) + }; + let original = if wide { + self.join64(vals[0], vals[1]) + } else { + vals[0] + }; + let value = if op == "sub" { + let zero = self.s.m.int_const(ty, 0); + self.s.m.bin(c, Bin::Sub, zero, original) + } else { + original + }; + let h = self.handle(site, src, false, (kind | 0x1000, component))?; + let mut args = vec![h]; + let (intrinsic, opcode) = if compare { + let comparand = if wide { + self.join64(vals[2], vals[3]) + } else { + vals[1] + }; + args.extend(cs); + args.extend([comparand, value]); + let intrinsic = if wide { + "atomicCompareExchange.i64" + } else { + "atomicCompareExchange.i32" + }; + (intrinsic, 79) + } else { + args.push(self.s.m.i32(code)); + args.extend(cs); + args.push(value); + ( + if wide { + "atomicBinOp.i64" + } else { + "atomicBinOp.i32" + }, + 78, + ) + }; + let at = self.begin_guarded(guard); + let r = self + .s + .op(self.cur, intrinsic, Attr::NoUnwind, ty, opcode, &args); + if cache.glc { + let old = self.end_guarded(at, &[(r, original)])[0]; + if wide { + let (lo, hi) = self.split64(old); + self.write(inst, Reg::V(reg), lo, None); + self.write(inst, Reg::V(reg + 1), hi, None); + } else { + self.write(inst, Reg::V(reg), old, None); + } + } else { + self.end_guarded(at, &[]); + } + return Ok(()); + } + if store { + if name != "image_store" { + return Err("an image store to a mip level"); + } + // shortcut: stores are taken to write all four channels of a + // float format (the console converts by the view's format). + if *dmask != 0xF { + return Err("an image store of some channels"); + } + let iu = self.s.m.undef(self.s.t.i32); + let mut cs = vec![iu; 3]; + for (k, slot) in cs.iter_mut().enumerate().take(coords) { + *slot = addr_val(self, k)?; + } + let Operand::Vector { reg, .. } = *data else { + return Err("image store data"); + }; + let mut vals = Vec::new(); + for k in 0..4u8 { + // d16: two f16 channels per VGPR, low half first. + let r = if *d16 { k / 2 } else { k }; + let v = inst.read(Reg::V(reg + r)).ok_or("image store data")?; + vals.push(if *d16 { + let mut x = self.i32_of(v)?; + if k % 2 == 1 { + let k16 = self.s.m.i32(16); + x = self.s.m.bin(self.cur, Bin::LShr, x, k16); + } + let f32t = self.s.t.f32; + self.s + .op(self.cur, "legacyF16ToF32", Attr::ReadNone, f32t, 131, &[x]) + } else { + self.float_of(v)? + }); + } + let h = self.handle(site, src, false, props)?; + let at = self.begin_guarded(guard); + let mut args = vec![h]; + args.extend(cs); + args.extend(vals); + args.push(self.s.m.i8(0xF)); + let void = self.s.t.void; + self.s.op( + self.cur, + "textureStore.f32", + Attr::NoUnwind, + void, + 67, + &args, + ); + self.end_guarded(at, &[]); + return Ok(()); + } + let has_cl = name.ends_with("_cl"); + let (op, sample) = match name { + "image_sample" | "image_sample_o" | "image_sample_cl" => (60, true), + "image_sample_lz" | "image_sample_l" | "image_sample_lz_o" => (62, true), + "image_sample_b" | "image_sample_b_cl" => (61, true), + "image_sample_c_lz" => (65, true), + "image_sample_d" | "image_sample_d_cl" => (63, true), + "image_get_lod" if self.s.pixel => (81, true), + // Implicit derivatives: pixel shaders only. + "image_sample_c" if self.s.pixel => (64, true), + "image_sample_c_cl" if self.s.pixel => (64, true), + "image_gather4" | "image_gather4_lz" | "image_gather4_lz_o" | "image_gather4_l" | "image_gather4_l_o" => (73, true), + "image_load" | "image_load_mip" => (66, false), + "image_get_resinfo" => (72, false), + _ => return Err(name), + }; + if op == 72 { + // Width, height, depth or layers, levels (per dmask) of the level + // in the first address: DXIL's dimensions; a channel DXIL leaves + // out reads 1 (UAVs: one level). + let h = self.handle(site, src, false, props)?; + let mip = if uav { + self.s.m.undef(self.s.t.i32) + } else { + addr_val(self, 0)? + }; + let i32t = self.s.t.i32; + let dims = self.s.m.named_struct("dx.types.Dimensions", vec![i32t; 4]); + let d = self + .s + .op(c, "getDimensions", Attr::ReadOnly, dims, 72, &[h, mip]); + let one = self.s.m.i32(1); + let present = match kind { + 1 => [true, false, false, true], + 2 | 5 | 6 => [true, true, false, true], + _ => [true, true, true, true], + }; + let Operand::Vector { reg, .. } = *data else { + return Err("an image result"); + }; + for (k, ch) in (0..4u32).filter(|ch| dmask >> ch & 1 != 0).enumerate() { + let x = if ch == 3 && uav || !present[ch as usize] { + one + } else { + self.s.m.extract(c, d, ch) + }; + self.write(inst, Reg::V(reg + k as u8), x, guard); + } + return Ok(()); + } + if uav && op != 66 { + return Err("sampling a UAV"); + } + let h = self.handle(site, src, false, props)?; + let fu = self.s.m.undef(self.s.t.f32); + let iu = self.s.m.undef(self.s.t.i32); + // A gather at a named level, done as four texel reads (below). + let mut gathered: Option<[V; 4]> = None; + let r = if sample { + let ss = self + .descriptors + .get(&(site, true)) + .copied() + .ok_or("an untracked sampler")?; + // Comparison: the reference value is the first address after + // the bias, and the sampler is a comparison sampler. + let cmp = matches!(op, 64 | 65); + if cmp && (*a16 || dmask.count_ones() != 1) { + return Err("a comparison sample of 16-bit coordinates or several channels"); + } + let sh = self.handle(site, ss, true, (14 | if cmp { 0x8000 } else { 0 }, 0))?; + // Texel offsets (`_o`) come first: x in bits 0-5, y in 8-13, + // signed (programmable offsets: gathers only). + let offset_word = name.ends_with("_o"); + let first = usize::from(offset_word) + + usize::from(name.starts_with("image_sample_b")) + + usize::from(cmp); + // Coordinates the size divides (not the array slice); explicit + // gradients (x then y) come before the coordinates. + let spatial = coords - usize::from(kind == 6 || kind == 7); + // A cube's gradients are the two of its face coordinates. + let grads = if kind == 5 { 2 } else { spatial }; + let deriv_regs = if op == 63 { + if *a16 { + grads.div_ceil(2) + } else { + grads + } + } else { + 0 + }; + let coord_base = first + 2 * deriv_regs; + let mut cs = vec![fu; 4]; + // With a16, sampling coordinates, gradients, LOD and clamp are f16. + let to_float = |l: &mut Self, x: V| { + if *a16 { + let f = l.s.t.f32; + l.s.op(l.cur, "legacyF16ToF32", Attr::ReadNone, f, 131, &[x]) + } else { + l.as_float(x) + } + }; + if kind == 5 && (*unorm || op == 81) { + return Err("a cube sample with texel coordinates or a level query"); + } + for (k, slot) in cs.iter_mut().enumerate().take(coords) { + let x = addr_packed(self, coord_base, k)?; + *slot = to_float(self, x); + } + if kind == 5 { + let dir = self.cube_direction(cs[0], cs[1], cs[2]); + cs[..3].copy_from_slice(&dir); + } + if *unorm { + // Texel coordinates: divided by the size of level 0. + let i32t = self.s.t.i32; + let dims = self.s.m.named_struct("dx.types.Dimensions", vec![i32t; 4]); + let z = self.s.m.i32(0); + let d = self + .s + .op(c, "getDimensions", Attr::ReadOnly, dims, 72, &[h, z]); + for (k, slot) in cs.iter_mut().enumerate().take(spatial) { + let n = self.s.m.extract(c, d, k as u32); + let n = self.s.m.cast(c, Cast::UiToFp, n, self.s.t.f32); + *slot = self.s.m.bin(c, Bin::SDiv, *slot, n); + } + } + if op == 81 { + // The clamped then the unclamped level of detail. + let Operand::Vector { reg, .. } = *data else { + return Err("an image result"); + }; + let f32t = self.s.t.f32; + for (k, ch) in (0..2u32).filter(|ch| dmask >> ch & 1 != 0).enumerate() { + let clamped = self.s.m.bool(ch == 0); + let lod = self.s.op( + c, + "calculateLOD.f32", + Attr::ReadOnly, + f32t, + 81, + &[h, sh, cs[0], cs[1], cs[2], clamped], + ); + let x = self.as_int(lod); + self.write(inst, Reg::V(reg + k as u8), x, guard); + } + return Ok(()); + } + let offsets = if kind == 5 { + 0 + } else { + (coords - usize::from(kind == 6 || kind == 7)).min(3) + }; + let zero = self.s.m.i32(0); + let mut os = vec![iu; 3]; + for o in os.iter_mut().take(offsets) { + *o = zero; + } + if offset_word && offsets > 0 { + let w = addr_val(self, 0)?; + for (k, at) in [(0, 26), (1, 18)].into_iter().take(offsets.min(2)) { + // Bits at..at+5 sign-extended: shift up, then down. + let left = self.s.m.i32(at); + let t = self.s.m.bin(c, Bin::Shl, w, left); + let k26 = self.s.m.i32(26); + os[k] = self.s.m.bin(c, Bin::AShr, t, k26); + } + } + let mut args = vec![h, sh]; + args.extend(&cs); + let clamp = if has_cl { + let x = addr_packed(self, coord_base, coords)?; + to_float(self, x) + } else { + fu + }; + match op { + // Outside a pixel shader there are no screen derivatives: + // the validator refuses `sample` there ("features + // incompatible with the shader stage": 730 compute programs, + // among them the G-buffer resolves and the sky), and what a + // driver does with it is its own affair. + // shortcut: such a sample reads level 0 (a bias: that + // level). The console takes derivatives from neighbouring + // lanes there; compute them from the lanes if a resolve + // shows the wrong mip. + 60 if !self.s.pixel => { + args.extend(&os); + args.push(self.s.m.f32(0)); + self.s.op( + c, + "sampleLevel.f32", + Attr::ReadOnly, + self.s.t.res_ret, + 62, + &args, + ) + } + 60 => { + if offset_word { + // DXIL wants immediate offsets in -8..=7 here; the + // console's are 6-bit and may be computed. A + // constant word in range becomes immediates + // (upstream PR #634); anything else keeps the + // offsets computed above (upstream refuses those). + let w = addr_val(self, 0)?; + if let Some(w) = self.s.m.int_value(w) { + let w = w as u32; + let field = |k: usize| { + let x = (w >> (8 * k) & 0x3F) as i32; + if x >= 32 { x - 64 } else { x } + }; + let n = offsets.min(2); + if (0..n).all(|k| (-8..=7).contains(&field(k))) { + for (k, o) in os.iter_mut().enumerate().take(n) { + *o = self.s.m.i32(field(k) as u32); + } + } + } + } + args.extend(&os); + args.push(clamp); + self.s + .op(c, "sample.f32", Attr::ReadOnly, self.s.t.res_ret, 60, &args) + } + 61 => { + // With a16 the bias is an f16 in the low half of its + // word (the word is whole, the value is not). + let bias = addr_u32(self, usize::from(offset_word))?; + let bias = if *a16 { + let low = self.s.m.i32(0xFFFF); + let bias = self.s.m.bin(c, Bin::And, bias, low); + to_float(self, bias) + } else { + self.as_float(bias) + }; + args.extend(&os); + if self.s.pixel { + args.extend([bias, clamp]); + self.s.op( + c, + "sampleBias.f32", + Attr::ReadOnly, + self.s.t.res_ret, + 61, + &args, + ) + } else { + // As above: the bias is the level. + args.push(bias); + self.s.op( + c, + "sampleLevel.f32", + Attr::ReadOnly, + self.s.t.res_ret, + 62, + &args, + ) + } + } + 63 if kind == 5 => { + // A cube with explicit gradients: the host wants them + // as changes of the direction, the console gives the + // changes of the face coordinates (the face is one + // unit wide). The level they select is taken from the + // longer of the two, in texels, and sampled directly. + // shortcut: no anisotropic filtering for these samples + // (the longer axis alone decides the level). + let mut len = [fu; 2]; + for (axis, slot) in len.iter_mut().enumerate() { + let mut sum = self.s.m.f32(0); + for k in 0..2 { + let x = addr_packed(self, first + axis * deriv_regs, k)?; + let x = to_float(self, x); + let sq = self.s.m.bin(c, Bin::Mul, x, x); + sum = self.s.m.bin(c, Bin::Add, sum, sq); + } + *slot = self.unary(24, sum); // square root + } + let longer = self.binary(35, len[0], len[1]); // maximum + let i32t = self.s.t.i32; + let dims = self.s.m.named_struct("dx.types.Dimensions", vec![i32t; 4]); + let z = self.s.m.i32(0); + let d = self + .s + .op(c, "getDimensions", Attr::ReadOnly, dims, 72, &[h, z]); + let width = self.s.m.extract(c, d, 0); + let width = self.s.m.cast(c, Cast::UiToFp, width, self.s.t.f32); + let texels = self.s.m.bin(c, Bin::Mul, longer, width); + // log2 = natural logarithm / ln 2; a length of 0 gives + // minus infinity, which the sampler clamps to level 0. + let ln = self.unary(23, texels); + let per_ln2 = self.s.m.f32(std::f32::consts::LOG2_E.to_bits()); + let lod = self.s.m.bin(c, Bin::Mul, ln, per_ln2); + args.extend(&os); + args.push(lod); + self.s.op( + c, + "sampleLevel.f32", + Attr::ReadOnly, + self.s.t.res_ret, + 62, + &args, + ) + } + 63 => { + let mut g = vec![fu; 6]; + for k in 0..spatial { + let x = addr_packed(self, first, k)?; + g[k] = to_float(self, x); + let y = addr_packed(self, first + deriv_regs, k)?; + g[3 + k] = to_float(self, y); + } + args.extend(&os); + args.extend(g); + args.push(clamp); + self.s.op( + c, + "sampleGrad.f32", + Attr::ReadOnly, + self.s.t.res_ret, + 63, + &args, + ) + } + 64 | 65 => { + let reference = addr_u32(self, first - 1)?; + let reference = self.as_float(reference); + args.extend(&os); + args.push(reference); + let name = if op == 64 { + args.push(clamp); + "sampleCmp.f32" + } else { + "sampleCmpLevelZero.f32" + }; + self.s + .op(c, name, Attr::ReadOnly, self.s.t.res_ret, op, &args) + } + 62 => { + let lod = if name == "image_sample_l" { + let x = addr_packed(self, coord_base, coords)?; + to_float(self, x) + } else { + self.s.m.f32(0) + }; + args.extend(&os); + args.push(lod); + self.s.op( + c, + "sampleLevel.f32", + Attr::ReadOnly, + self.s.t.res_ret, + 62, + &args, + ) + } + _ => { + if name == "image_gather4" { + return Err("a gather with implicit level"); + } + if dmask.count_ones() != 1 { + return Err("a gather of several channels"); + } + if matches!(name, "image_gather4_l" | "image_gather4_l_o") + && coords == 2 + && spatial == 2 + { + // The host's gather has no level: it read level 0 + // where the title names one (the depth pyramid its + // occlusion tests read: most of the world was + // culled against the wrong depths). The four texels + // are read at the level instead, in the gather's + // order: (u0,v1) (u1,v1) (u1,v0) (u0,v0). + // With an offset too (`image_gather4_l_o`): the + // offset is in texels of that level. + // The title's meshlet culling takes a 4x4 block of + // the pyramid as one gather and three offset ones + // ((2,0), (0,2), (2,2)); the three read level 0, + // two texels beside the first one's place, so a + // meshlet three or four texels wide was tested + // against a quarter of what it covers. + // shortcut: the level is rounded to a whole one and + // coordinates past the edge are clamped, whatever + // the sampler says. + let lod = addr_packed(self, coord_base, coords)?; + let lod = to_float(self, lod); + let (i32t, f32t) = (self.s.t.i32, self.s.t.f32); + let zero = self.s.m.f32(0); + let lod = self.binary(35, lod, zero); // maximum + let lod = self.unary(26, lod); // round to nearest + let mip = self.s.m.cast(c, Cast::FpToUi, lod, i32t); + let dims = self.s.m.named_struct("dx.types.Dimensions", vec![i32t; 4]); + let d = self + .s + .op(c, "getDimensions", Attr::ReadOnly, dims, 72, &[h, mip]); + let half = self.s.m.f32(0.5f32.to_bits()); + let one = self.s.m.f32(1.0f32.to_bits()); + let (mut lo, mut hi) = ([iu; 2], [iu; 2]); + for k in 0..2 { + let n = self.s.m.extract(c, d, k as u32); + let n = self.s.m.cast(c, Cast::UiToFp, n, f32t); + let last = self.s.m.bin(c, Bin::Sub, n, one); + let t = self.s.m.bin(c, Bin::Mul, cs[k], n); + let t = self.s.m.bin(c, Bin::Sub, t, half); + let first = self.unary(27, t); // round down + // The offset word's field (0 without one). + let by = self.s.m.cast(c, Cast::SiToFp, os[k], f32t); + let first = self.s.m.bin(c, Bin::Add, first, by); + let next = self.s.m.bin(c, Bin::Add, first, one); + for (slot, x) in [(&mut lo[k], first), (&mut hi[k], next)] { + let x = self.binary(35, x, zero); // maximum + let x = self.binary(36, x, last); // minimum + *slot = self.s.m.cast(c, Cast::FpToSi, x, i32t); + } + } + let ch = dmask.trailing_zeros(); + let mut g = [fu; 4]; + let mut read = None; + let texels = [(lo[0], hi[1]), (hi[0], hi[1]), (hi[0], lo[1]), (lo[0], lo[1])]; + for (slot, (x, y)) in g.iter_mut().zip(texels) { + let r = self.s.op( + c, + "textureLoad.f32", + Attr::ReadOnly, + self.s.t.res_ret, + 66, + &[h, mip, x, y, iu, iu, iu, iu], + ); + *slot = self.s.m.extract(c, r, ch); + read = Some(r); + } + gathered = Some(g); + read.expect("four reads") + } else { + args.extend(&os[..2]); + args.push(self.s.m.i32(dmask.trailing_zeros())); + self.s.op( + c, + "textureGather.f32", + Attr::ReadOnly, + self.s.t.res_ret, + 73, + &args, + ) + } + } + } + } else { + let mut cs = vec![iu; 3]; + for (k, slot) in cs.iter_mut().enumerate().take(coords) { + *slot = addr_val(self, k)?; + } + let mip = if name == "image_load_mip" { + addr_val(self, coords)? + } else if uav { + // Our declarations have four channels. + self.s.flags |= flags::TYPED_UAV_LOADS; + iu + } else { + self.s.m.i32(0) + }; + let mut args = vec![h, mip]; + args.extend(&cs); + args.extend([iu, iu, iu]); + self.s.op( + c, + "textureLoad.f32", + Attr::ReadOnly, + self.s.t.res_ret, + 66, + &args, + ) + }; + let Operand::Vector { reg, .. } = *data else { + return Err("an image result"); + }; + let channels: Vec = if op == 73 { + vec![0, 1, 2, 3] + } else { + (0..4).filter(|ch| dmask >> ch & 1 != 0).collect() + }; + let mut xs = Vec::new(); + for ch in channels { + let x = match gathered { + Some(g) => g[ch as usize], + None => self.s.m.extract(c, r, ch), + }; + xs.push(if *d16 { + // shortcut: d16 results are taken as floats (rounded to + // nearest even); integer formats would keep 16 bits. + let i32t = self.s.t.i32; + self.s + .op(c, "legacyF32ToF16", Attr::ReadNone, i32t, 130, &[x]) + } else { + self.as_int(x) + }); + } + if *d16 { + // Two channels per VGPR, low half first (an odd last high half 0). + let k16 = self.s.m.i32(16); + xs = xs + .chunks(2) + .map(|p| match *p { + [lo, hi] => { + let hi = self.s.m.bin(c, Bin::Shl, hi, k16); + self.s.m.bin(c, Bin::Or, lo, hi) + } + _ => p[0], + }) + .collect(); + } + for (k, x) in xs.into_iter().enumerate() { + self.write(inst, Reg::V(reg + k as u8), x, guard); + } + Ok(()) + } + + /// The direction a cube sample's face coordinates stand for: the + /// console takes s and t in [1, 2] (`v_cubesc`/`v_cubetc` over + /// `|v_cubema|`, plus 1.5) and the face id (`v_cubeid`), which the + /// host's cube sampling turns back into the same texel. + // shortcut: the view is taken as a cube, not a cube array (whose face + // operand adds 8 × the slice). + fn cube_direction(&mut self, s: V, t: V, face: V) -> [V; 3] { + let c = self.cur; + let k = |l: &mut Self, v: f32| l.s.m.f32(v.to_bits()); + let (two, three) = (k(self, 2.0), k(self, 3.0)); + let u = self.s.m.bin(c, Bin::Mul, s, two); + let u = self.s.m.bin(c, Bin::Sub, u, three); + let v = self.s.m.bin(c, Bin::Mul, t, two); + let v = self.s.m.bin(c, Bin::Sub, v, three); + let z = self.s.m.f32(0x8000_0000); + let (nu, nv) = ( + self.s.m.bin(c, Bin::Sub, z, u), + self.s.m.bin(c, Bin::Sub, z, v), + ); + let (one, mone) = (k(self, 1.0), k(self, -1.0)); + let f = self.s.m.cast(c, Cast::FpToUi, face, self.s.t.i32); + // Per face +x, -x, +y, -y, +z, -z. + let table = [ + [one, mone, u, u, u, nu], + [nv, nv, one, mone, nv, nv], + [nu, u, v, nv, one, mone], + ]; + table.map(|row| { + let mut r = row[0]; + for (n, &x) in row.iter().enumerate().skip(1) { + let kn = self.s.m.i32(n as u32); + let is = self.s.m.cmp(c, pred::EQ, f, kn); + r = self.s.m.select(c, is, x, r); + } + r + }) + } + + fn buffer(&mut self, inst: &Inst, b: usize, i: usize) -> Result<(), Why> { + let Fields::Buffer { + data, + addr, + soffset, + offset, + offen, + idxen, + format, + lds, + tfe, + .. + } = &inst.fields + else { + unreachable!() + }; + let name = inst.name(); + if name == "buffer_gl0_inv" || name == "buffer_gl1_inv" { + // The host has no console buffer cache to invalidate. + return Ok(()); + } + if *lds || *tfe { + return Err("a buffer access to LDS or with tfe"); + } + if format.is_some() && !name.starts_with("tbuffer_load_format_") { + return Err(name); + } + let site = (b, i); + let guard = self.guard(b, i)?; + let c = self.cur; + let store = name.starts_with("buffer_store_"); + // DXIL atomic operations: add, and, or, xor, signed and unsigned + // min and max, exchange; compare-exchange apart. + let atomic = match name.strip_prefix("buffer_atomic_") { + None => None, + Some("add") => Some(0), + Some("and") => Some(1), + Some("or") => Some(2), + Some("xor") => Some(3), + Some("smin") => Some(4), + Some("smax") => Some(5), + Some("umin") => Some(6), + Some("umax") => Some(7), + Some("swap") => Some(8), + Some("cmpswap") => Some(u32::MAX), + Some(_) => return Err(name), + }; + // Byte and 16-bit accesses: bits, and whether a load sign-extends. + let narrow = match name { + "buffer_load_ubyte" | "buffer_store_byte" => Some((8, false)), + "buffer_load_sbyte" => Some((8, true)), + "buffer_load_ushort" | "buffer_store_short" => Some((16, false)), + "buffer_load_sshort" => Some((16, true)), + _ => None, + }; + // d16: two 16-bit channels per VGPR, low half first. + let d16 = name.starts_with("buffer_") && name.contains("_format_d16_"); + let plain = name.replace("_format_d16_", "_format_"); + let (typed, count) = match plain + .strip_prefix("buffer_load_") + .or(plain.strip_prefix("buffer_store_")) + .or(plain.strip_prefix("tbuffer_load_")) + { + _ if atomic.is_some() || narrow.is_some() => (false, 1), + Some("dword") => (false, 1), + Some("dwordx2") => (false, 2), + Some("dwordx3") => (false, 3), + Some("dwordx4") => (false, 4), + Some("format_x") => (true, 1), + Some("format_xy") => (true, 2), + Some("format_xyz") => (true, 3), + Some("format_xyzw") => (true, 4), + _ => return Err(name), + }; + let Operand::Vector { reg: areg, .. } = *addr else { + return Err("a buffer address"); + }; + let vaddr = |l: &mut Self, k: u8| -> Result { + let v = inst.read(Reg::V(areg + k)).ok_or("a buffer address")?; + l.i32_of(v) + }; + let index = if *idxen { Some(vaddr(self, 0)?) } else { None }; + let mut off = self.s.m.i32(u32::from(*offset)); + if *offen { + let o = vaddr(self, u8::from(*idxen))?; + off = self.s.m.bin(c, Bin::Add, off, o); + } + if !matches!( + soffset, + Operand::Scalar { code: NULL, .. } | Operand::Const(128) + ) { + let so = self.operand(inst, soffset)?; + off = self.s.m.bin(c, Bin::Add, off, so); + } + let src = self + .descriptors + .get(&(site, false)) + .copied() + .ok_or("an untracked buffer")?; + let used = self.used_kind(src); + let (base, extra) = self.built_offset(src)?; + if base != 0 { + let b = self.s.m.i32(base); + off = self.s.m.bin(c, Bin::Add, off, b); + } + if let Some(x) = extra { + off = self.s.m.bin(c, Bin::Add, off, x); + } + // A buffer the program picks from the view heap by an index it + // computes: no used-resource entry gives its stride, the host's + // table by heap slot does; the access becomes a raw one at the + // element's byte. (Also tells the host this shader reads such + // buffers.) + let mut index = index; + if let Some(stride) = self.slot_stride(src)? + && let Some(element) = index + && !typed + && used.is_none() + { + let at = self.s.m.bin(c, Bin::Mul, element, stride); + off = self.s.m.bin(c, Bin::Add, at, off); + index = None; + } + // A structured buffer by its used-resource entry's stride: raw + // bytes too. The host makes its buffer views raw (a raw read + // through a structured view gives zeros on NVIDIA), and one kind + // of view can then serve every shader that reads the buffer. + if let (Some(element), Some(u)) = (index, used) + && !typed + && u.kind != ResourceType::Cbv + && u.stride >= 4 + && u.stride.is_multiple_of(4) + { + let k = self.s.m.i32(u.stride); + let at = self.s.m.bin(c, Bin::Mul, element, k); + off = self.s.m.bin(c, Bin::Add, at, off); + index = None; + } + if used.is_some_and(|u| u.kind == ResourceType::Cbv) && !typed { + // A constant buffer read per lane (a dynamically indexed array). + // shortcut: the console's CBV descriptor is taken to have a 16-byte + // stride, as the vector loads of whole rows suggest. + let h = self.handle(site, src, false, (13, 0x1_0000))?; + let byte = match index { + Some(i) => { + let sixteen = self.s.m.i32(16); + let rows = self.s.m.bin(c, Bin::Mul, i, sixteen); + self.s.m.bin(c, Bin::Add, rows, off) + } + None => off, + }; + let Some(Operand::Vector { reg, .. }) = *data else { + return Err("a buffer result"); + }; + for k in 0..count { + let four = self.s.m.i32(4 * k); + let a = self.s.m.bin(c, Bin::Add, byte, four); + let x = self.cbuffer_dword(h, a); + self.write(inst, Reg::V(reg + k as u8), x, guard); + } + return Ok(()); + } + let uav = store || atomic.is_some() || used.is_some_and(|u| u.kind == ResourceType::Uav); + let u = if uav { 0x1000 } else { 0 }; + let iu = self.s.m.undef(self.s.t.i32); + if let Some((bits, signed)) = narrow { + // Below a dword: raw buffers are read and written in dwords on + // 4 bytes, so the dword that holds the value is read and + // shifted, or changed with two atomic operations that touch + // only the value's own bits (other lanes may write the rest of + // the dword at the same time). A 16-bit value at a dword's + // last byte continues in the next dword. + let byte = match index { + None => off, + Some(index) if used.is_some_and(|u| u.stride == 1) => { + self.s.m.bin(c, Bin::Add, index, off) + } + Some(_) => return Err("a byte or 16-bit buffer access by index"), + }; + let h = self.handle(site, src, false, (11 | u, 0))?; + let k3 = self.s.m.i32(3); + let within = self.s.m.bin(c, Bin::And, byte, k3); + let aligned = self.s.m.bin(c, Bin::Sub, byte, within); + let shift = self.s.m.bin(c, Bin::Shl, within, k3); + let four = self.s.m.i32(4); + let next = self.s.m.bin(c, Bin::Add, aligned, four); + let ones = self.s.m.i32(if bits == 8 { 0xff } else { 0xffff }); + let zero = self.s.m.i32(0); + let k8 = self.s.m.i32(8); + let straddles = self.s.m.cmp(c, pred::EQ, within, k3); + if !store { + let mask = self.s.m.i8(1); + let align = self.s.m.i32(4); + let dword = |l: &mut Self, at: V| { + let r = l.s.op( + c, + "rawBufferLoad.f32", + Attr::ReadOnly, + l.s.t.res_ret, + 139, + &[h, at, iu, mask, align], + ); + let f = l.s.m.extract(c, r, 0); + l.as_int(f) + }; + let low = dword(self, aligned); + let mut x = self.s.m.bin(c, Bin::LShr, low, shift); + if bits == 16 { + let high = dword(self, next); + let high = self.s.m.bin(c, Bin::Shl, high, k8); + let high = self.s.m.select(c, straddles, high, zero); + x = self.s.m.bin(c, Bin::Or, x, high); + } + x = self.s.m.bin(c, Bin::And, x, ones); + if signed { + let up = self.s.m.i32(32 - bits); + x = self.s.m.bin(c, Bin::Shl, x, up); + x = self.s.m.bin(c, Bin::AShr, x, up); + } + let Some(Operand::Vector { reg, .. }) = *data else { + return Err("a buffer result"); + }; + self.write(inst, Reg::V(reg), x, guard); + return Ok(()); + } + let d = data.as_ref().ok_or("buffer store data")?; + let v = self.vgprs(inst, d, 1)?[0]; + let v = self.s.m.bin(c, Bin::And, v, ones); + let all = self.s.m.i32(u32::MAX); + let clear = self.s.m.bin(c, Bin::Shl, ones, shift); + let keep = self.s.m.bin(c, Bin::Xor, clear, all); + let set = self.s.m.bin(c, Bin::Shl, v, shift); + let keep_next = self.s.m.i32(0xffff_ff00); + let set_next = self.s.m.bin(c, Bin::LShr, v, k8); + let (and, or) = (self.s.m.i32(1), self.s.m.i32(2)); + let i32t = self.s.t.i32; + let at = self.begin_guarded(guard); + for (op, x) in [(and, keep), (or, set)] { + let args = [h, op, aligned, iu, iu, x]; + self.s + .op(self.cur, "atomicBinOp.i32", Attr::NoUnwind, i32t, 78, &args); + } + if bits == 16 { + let second = self.begin_guarded(Some(straddles)); + for (op, x) in [(and, keep_next), (or, set_next)] { + let args = [h, op, next, iu, iu, x]; + self.s + .op(self.cur, "atomicBinOp.i32", Attr::NoUnwind, i32t, 78, &args); + } + self.end_guarded(second, &[]); + } + self.end_guarded(at, &[]); + return Ok(()); + } + if let Some(op) = atomic { + let d = data.as_ref().ok_or("buffer atomic data")?; + let vals = self.vgprs(inst, d, if op == u32::MAX { 2 } else { 1 })?; + let (h, coords) = match index { + // A raw buffer (stride 1) read by index: the index is the byte. + Some(index) if used.is_some_and(|u| u.stride == 1) => { + let byte = self.s.m.bin(c, Bin::Add, index, off); + (self.handle(site, src, false, (11 | u, 0))?, [byte, iu, iu]) + } + Some(index) => { + let stride = used.map_or(0, |u| u.stride); + if stride < 4 || !stride.is_multiple_of(4) { + return Err("a structured buffer of unknown stride"); + } + let h = self.handle(site, src, false, (12 | u, stride))?; + (h, [index, off, iu]) + } + None => (self.handle(site, src, false, (11 | u, 0))?, [off, iu, iu]), + }; + let Operand::Vector { reg, .. } = *d else { + return Err("buffer atomic data"); + }; + let returns = matches!(inst.fields, Fields::Buffer { cache, .. } if cache.glc); + let old = match inst.read(Reg::V(reg)) { + Some(v) if returns => self.i32_of(v)?, + _ => self.s.m.i32(0), + }; + let at = self.begin_guarded(guard); + let i32t = self.s.t.i32; + let r = if op == u32::MAX { + // cmpswap: data is (new, compare). + let mut args = vec![h]; + args.extend(coords); + args.extend([vals[1], vals[0]]); + self.s.op( + self.cur, + "atomicCompareExchange.i32", + Attr::NoUnwind, + i32t, + 79, + &args, + ) + } else { + let mut args = vec![h, self.s.m.i32(op)]; + args.extend(coords); + args.push(vals[0]); + self.s + .op(self.cur, "atomicBinOp.i32", Attr::NoUnwind, i32t, 78, &args) + }; + let r = self.end_guarded(at, &[(r, old)])[0]; + if returns { + self.write(inst, Reg::V(reg), r, None); + } + return Ok(()); + } + if store { + let regs = if d16 { count.div_ceil(2) } else { count }; + let mut vals = + self.vgprs(inst, data.as_ref().ok_or("buffer store data")?, regs as u8)?; + if d16 { + // shortcut: d16 data is taken as f16 (integer formats would + // keep 16 bits), widened for the 32-bit float store. + let mut wide = Vec::new(); + for k in 0..count { + let mut x = vals[(k / 2) as usize]; + if k % 2 == 1 { + let k16 = self.s.m.i32(16); + x = self.s.m.bin(c, Bin::LShr, x, k16); + } + let f32t = self.s.t.f32; + let f = self + .s + .op(c, "legacyF16ToF32", Attr::ReadNone, f32t, 131, &[x]); + wide.push(self.as_int(f)); + } + vals = wide; + } + let mut args = Vec::new(); + let (op, name) = if typed { + // shortcut: typed stores are taken to write all four channels + // of a float format. + if count != 4 || *offen || *offset != 0 { + return Err("a typed buffer store of some channels or at an offset"); + } + args.push(self.handle(site, src, false, (10 | u, 0x409))?); + args.extend([index.unwrap_or(self.s.m.i32(0)), iu]); + for x in vals { + args.push(self.as_float(x)); + } + (69, "bufferStore.f32") + } else { + match index { + // A raw buffer (stride 1) written by index: the index is the byte. + Some(index) if used.is_some_and(|u| u.stride == 1) => { + let byte = self.s.m.bin(c, Bin::Add, index, off); + args.push(self.handle(site, src, false, (11 | u, 0))?); + args.extend([byte, iu]); + } + Some(index) => { + let stride = used.map_or(0, |u| u.stride); + if stride < 4 || !stride.is_multiple_of(4) { + return Err("a structured buffer of unknown stride"); + } + args.push(self.handle(site, src, false, (12 | u, stride))?); + args.extend([index, off]); + } + None => { + args.push(self.handle(site, src, false, (11 | u, 0))?); + args.extend([off, iu]); + } + } + args.extend(&vals); + args.resize(3 + 4, iu); + (140, "rawBufferStore.i32") + }; + args.push(self.s.m.i8(if typed { 0xF } else { (1u8 << count) - 1 })); + if !typed { + args.push(self.s.m.i32(4)); + } + let at = self.begin_guarded(guard); + let void = self.s.t.void; + self.s.op(self.cur, name, Attr::NoUnwind, void, op, &args); + self.end_guarded(at, &[]); + return Ok(()); + } + if let Some(f) = *format { + if index.is_some() { + return Err("a typed-format load by index"); + } + let h = self.handle(site, src, false, (11 | u, 0))?; + let Some(Operand::Vector { reg, .. }) = *data else { + return Err("a buffer result"); + }; + for (k, x) in self.format_load(h, off, f, count)?.into_iter().enumerate() { + self.write(inst, Reg::V(reg + k as u8), x, guard); + } + return Ok(()); + } + let r = if typed { + if *offen || matches!(off, V::Inst(_)) || *offset != 0 { + return Err("a typed buffer load at an offset"); + } + if uav { + self.s.flags |= flags::TYPED_UAV_LOADS; + } + let h = self.handle(site, src, false, (10 | u, 0x409))?; + let index = index.unwrap_or(self.s.m.i32(0)); + self.s.op( + c, + "bufferLoad.f32", + Attr::ReadOnly, + self.s.t.res_ret, + 68, + &[h, index, iu], + ) + } else { + let mask = self.s.m.i8((1u8 << count) - 1); + let align = self.s.m.i32(4); + match index { + // A raw buffer (stride 1) read by index: the index is the byte. + Some(index) if used.is_some_and(|u| u.stride == 1) => { + let byte = self.s.m.bin(c, Bin::Add, index, off); + let h = self.handle(site, src, false, (11 | u, 0))?; + self.s.op( + c, + "rawBufferLoad.f32", + Attr::ReadOnly, + self.s.t.res_ret, + 139, + &[h, byte, iu, mask, align], + ) + } + Some(index) => { + let stride = used.map_or(0, |u| u.stride); + if stride < 4 || !stride.is_multiple_of(4) { + return Err("a structured buffer of unknown stride"); + } + let h = self.handle(site, src, false, (12 | u, stride))?; + self.s.op( + c, + "rawBufferLoad.f32", + Attr::ReadOnly, + self.s.t.res_ret, + 139, + &[h, index, off, mask, align], + ) + } + None => { + let h = self.handle(site, src, false, (11 | u, 0))?; + self.s.op( + c, + "rawBufferLoad.f32", + Attr::ReadOnly, + self.s.t.res_ret, + 139, + &[h, off, iu, mask, align], + ) + } + } + }; + let Some(Operand::Vector { reg, .. }) = *data else { + return Err("a buffer result"); + }; + if d16 { + // Two f16 channels per VGPR (an odd last high half 0). + let k16 = self.s.m.i32(16); + let i32t = self.s.t.i32; + for k in 0..count.div_ceil(2) { + let mut x = None; + for ch in (2 * k..(2 * k + 2).min(count)).rev() { + let f = self.s.m.extract(c, r, ch); + let h = self + .s + .op(c, "legacyF32ToF16", Attr::ReadNone, i32t, 130, &[f]); + x = Some(match x { + Some(hi) => { + let hi = self.s.m.bin(c, Bin::Shl, hi, k16); + self.s.m.bin(c, Bin::Or, h, hi) + } + None => h, + }); + } + self.write(inst, Reg::V(reg + k as u8), x.expect("a channel"), guard); + } + return Ok(()); + } + for k in 0..count { + let x = self.s.m.extract(c, r, k); + let x = self.as_int(x); + self.write(inst, Reg::V(reg + k as u8), x, guard); + } + Ok(()) + } + + fn export(&mut self, b: usize, i: usize) -> Result<(), Why> { + let e = *self + .exports + .get(&(b, i)) + .ok_or("an export I/O raising did not see")?; + if e.compressed { + return Err("a compressed export"); + } + let guard = self.guard(b, i)?; + let mesh = self.s.mesh.is_some(); + let c = self.cur; + if let Some(g) = guard + && !mesh + { + if !(e.done && self.s.pixel) { + return Err("a conditional export"); + } + let t = self.s.m.bool(true); + let kill = self.s.m.bin(c, Bin::Xor, g, t); + self.s + .op(c, "discard", Attr::NoUnwind, self.s.t.void, 82, &[kill]); + } + if mesh && e.target == Target::Primitive { + return self.emit_indices(e, guard); + } + let param_row = |usage: Usage, row: u8| match usage { + // The 2020 compiler leaves a mesh program's first entry zeroed + // (usage "position"): its row is the one no other entry names. + Usage::Other(0) if mesh => self.unnamed_row(), + _ => Some(row), + }; + // (output element, channel) per exported channel; per-primitive + // outputs are elements of `prims`. + let mut stores = Vec::new(); + let primitive = matches!(e.target, Target::PrimitiveParam { .. }); + let outputs = if primitive { + &self.s.prims + } else { + &self.s.outputs + }; + let by_kind = |kind: u8| outputs.iter().position(|o| o.kind == kind); + // 16-bit vertex outputs: the halves each dword carries, as (output + // element, channel, high half) per channel. + let halves = match e.target { + Target::Param { usage, row } => { + param_row(usage, row).and_then(|r| self.half_outputs.get(&r).map(|&h| (r, h))) + } + _ => None, + }; + if let Some((row, (pack2, _))) = halves { + let packs: Vec<(u8, Option)> = self + .half_outputs + .iter() + .filter(|(_, h)| h.0) + .map(|(&r, h)| (r, h.1)) + .collect(); + for ch in 0..4u8 { + let Some(value) = e.values[usize::from(ch)] else { + continue; + }; + for high in [false, true] { + let h = 2 * ch + u8::from(high); + let src = if pack2 { + packed_half(outputs, &packs, row, h) + } else { + (!high).then_some((row, ch)) + }; + let found = src.and_then(|(r, c)| { + outputs.iter().position(|o| { + o.row == Some(u32::from(r)) && c >= o.col && c < o.col + o.cols + }) + }); + if let Some(id) = found { + let col = src.expect("found").1 - outputs[id].col; + stores.push((id, col, value, Some(high))); + } + } + } + } + for ch in 0..4u8 { + let Some(value) = e.values[usize::from(ch)] else { + continue; + }; + if halves.is_some() { + break; + } + let found = match e.target { + Target::Color(n) => outputs + .iter() + .position(|o| o.kind == 16 && o.row == Some(u32::from(n))) + .map(|id| (id, ch)), + Target::Position(0) => by_kind(3).map(|id| (id, ch)), + Target::Depth => match ch { + 0 => by_kind(17) + .or(by_kind(18)) + .or(by_kind(19)) + .map(|id| (id, 0)), + 1 => by_kind(20).map(|id| (id, 0)), + 2 => by_kind(14).map(|id| (id, 0)), + _ => None, + }, + Target::Param { usage, row } | Target::PrimitiveParam { usage, row } => { + let row = param_row(usage, row); + outputs + .iter() + .position(|o| { + row.is_some_and(|r| o.row == Some(u32::from(r))) + && ch >= o.col + && ch < o.col + o.cols + }) + .map(|id| (id, ch - outputs[id].col)) + } + Target::Null | Target::Unread => None, + Target::Position(n @ 1..=2) => { + // shortcut: without the misc vector (point size, render + // target or viewport index) pos1 and pos2 carry the clip + // then cull distances, in semantic order. + if outputs.iter().any(|o| matches!(o.kind, 4 | 5)) { + return Err("render-target or viewport index exports"); + } + let mut dists: Vec = (0..outputs.len()) + .filter(|&i| matches!(outputs[i].kind, 6 | 7)) + .collect(); + dists.sort_by_key(|&i| (outputs[i].kind, outputs[i].index)); + let flat: Vec<(usize, u8)> = dists + .iter() + .flat_map(|&i| (0..outputs[i].cols).map(move |c| (i, c))) + .collect(); + // Channels past the distances the signature declares are + // ones the clipper does not enable (`PA_CL_VS_OUT_CNTL`). + let k = usize::from(n - 1) * 4 + usize::from(ch); + flat.get(k).copied() + } + Target::Position(_) => return Err("clip, cull or point-size exports"), + Target::Primitive => return Err("a primitive export"), + }; + if let Some((id, col)) = found { + stores.push((id, col, value, None)); + } + } + fn elements<'l>(l: &'l mut Lower, primitive: bool) -> &'l mut Vec { + if primitive { + &mut l.s.prims + } else { + &mut l.s.outputs + } + } + if stores + .iter() + .any(|s| s.3.is_none() && elements(self, primitive)[s.0].half) + { + return Err("a 16-bit output the stage data does not mark"); + } + // A mesh lane writes its own vertex or primitive, where it exports. + let at = if mesh { + let flat = self.mesh_thread(); + let limit = if let Some(m) = self.s.mesh { + if primitive { + m.max_primitives + } else { + m.max_vertices + } + } else { + 0 + }; + let threads = self.s.threads.map(|t| t[0]).unwrap_or(u32::MAX); + let mesh_guard = if limit > 0 && threads > limit { + let lim = self.s.m.i32(limit); + let in_bounds = self.s.m.cmp(self.cur, pred::IULT, flat, lim); + match guard { + Some(g) => Some(self.s.m.bin(self.cur, Bin::And, g, in_bounds)), + None => Some(in_bounds), + } + } else { + guard + }; + self.begin_guarded(mesh_guard) + } else { + None + }; + let (name, opcode) = match (mesh, primitive) { + (false, _) => ("storeOutput", 5), + (true, false) => ("storeVertexOutput", 171), + (true, true) => ("storePrimitiveOutput", 172), + }; + for (id, col, value, half) in stores { + let mut x = self.i32_of(value)?; + if let Some(high) = half { + // An f16 half, declared a 32-bit float on the host. + let c = self.cur; + if high { + let k16 = self.s.m.i32(16); + x = self.s.m.bin(c, Bin::LShr, x, k16); + } + let f32t = self.s.t.f32; + let f = self + .s + .op(c, "legacyF16ToF32", Attr::ReadNone, f32t, 131, &[x]); + x = self.as_int(f); + } + let el = &mut elements(self, primitive)[id]; + el.usage |= 1 << col; + let (suffix, x) = match el.comp { + 9 if half.is_some() => (".f32", self.as_float(x)), + 9 => { + let f = match self.floats.get(&value) { + Some(&f) => f, + None => self.as_float(x), + }; + (".f32", f) + } + _ => (".i32", x), + }; + let mut args = vec![ + self.s.m.i32(id as u32), + self.s.m.i32(0), + self.s.m.i8(col), + x, + ]; + if mesh { + args.push(self.mesh_thread()); + } + let void = self.s.t.void; + self.s.op( + self.cur, + &format!("{name}{suffix}"), + Attr::NoUnwind, + void, + opcode, + &args, + ); + } + self.end_guarded(at, &[]); + Ok(()) + } + + /// Mesh: `exp prim` as the lane's primitive. Bit 31 culls it (all + /// indices 0: no area). + fn emit_indices(&mut self, e: &Export, guard: Option) -> Result<(), Why> { + let v = e.values[0].ok_or("a primitive export without its indices")?; + let x = self.i32_of(v)?; + let flat = self.mesh_thread(); + let guard = if let Some(mesh) = self.s.mesh { + let threads = self.s.threads.map(|t| t[0]).unwrap_or(u32::MAX); + if threads > mesh.max_primitives { + let p = self.s.m.i32(mesh.max_primitives); + let in_bounds = self.s.m.cmp(self.cur, pred::IULT, flat, p); + match guard { + Some(g) => Some(self.s.m.bin(self.cur, Bin::And, g, in_bounds)), + None => Some(in_bounds), + } + } else { + guard + } + } else { + guard + }; + let at = self.begin_guarded(guard); + let c = self.cur; + let z = self.s.m.i32(0); + let mut culled = self.s.m.cmp(c, pred::SLT, x, z); + // A primitive that names a vertex past the declared count, or one + // no lane writes (lane n writes vertex n alone), is culled too: the + // host would read a vertex nothing set, at any position. + let written = self.s.mesh.map(|m| { + m.max_vertices + .min(self.s.threads.map_or(u32::MAX, |t| t[0])) + }); + let mut indices = [z; 3]; + for (k, slot) in indices.iter_mut().enumerate() { + let (shift, mask) = (self.s.m.i32(10 * k as u32), self.s.m.i32(0x3FF)); + let i = self.s.m.bin(c, Bin::LShr, x, shift); + let i = self.s.m.bin(c, Bin::And, i, mask); + if let Some(n) = written { + let n = self.s.m.i32(n); + let past = self.s.m.cmp(c, pred::IUGE, i, n); + culled = self.s.m.bin(c, Bin::Or, culled, past); + } + *slot = i; + } + let mut args = vec![flat]; + for i in indices { + args.push(self.s.m.select(c, culled, z, i)); + } + let void = self.s.t.void; + self.s + .op(c, "emitIndices", Attr::NoUnwind, void, 169, &args); + self.end_guarded(at, &[]); + Ok(()) + } + + /// The per-vertex arbitrary row no mesh output entry names but one + /// (the 2020 compiler's zeroed entry). + fn unnamed_row(&self) -> Option { + let StageIo::Ms(ms) = &self.x.native.io else { + return None; + }; + let named = |r: u32| { + ms.outputs + .iter() + .any(|o| o.param & 0x80 == 0 && o.usage != Usage::Other(0) && u32::from(o.row) == r) + }; + let free: std::collections::BTreeSet = self + .s + .outputs + .iter() + .filter(|o| o.kind == 0) + .filter_map(|o| o.row) + .filter(|&r| !named(r)) + .collect(); + match free.into_iter().collect::>()[..] { + [r] => u8::try_from(r).ok(), + _ => None, + } + } + + fn exit(&mut self, b: usize) -> Result<(), Stop> { + let offset = self.x.p.blocks[b] + .insts + .last() + .map_or(self.x.p.blocks[b].offset, |i| i.machine.offset); + let term = match self.x.st.exits[b] { + LaneExit::Jump(t) if self.counters.contains_key(&t) && self.rpo[t] <= self.rpo[b] => { + let ok = self.count_iteration(t, pred::IULT); + let abort = self.abort_block(); + Term::CondBr(ok, self.block[t].expect("reachable"), abort) + } + LaneExit::Jump(t) => { + self.enter_loop(b, t, self.cur); + Term::Br(self.block[t].expect("reachable")) + } + LaneExit::Branch { + when, + taken, + not_taken, + } => { + // A negated condition branches the other way round. + let (cond, taken, not_taken) = match self.x.st.bools.node(when) { + _ if self.x.st.wide.contains(&b) => { + let c = self.wave_wide(b, when).map_err(|w| unsupported(offset, w))?; + (c, taken, not_taken) + } + Some((atom, Bool::TRUE, Bool::FALSE)) => { + let a = self + .atom(atom, self.cur) + .map_err(|w| unsupported(offset, w))?; + (a, not_taken, taken) + } + _ => { + let c = self + .boolean(when, self.cur) + .map_err(|w| unsupported(offset, w))?; + (c, taken, not_taken) + } + }; + // A back edge is taken only below the iteration limit. + let back = + |l: &Self, to: usize| l.counters.contains_key(&to) && l.rpo[to] <= l.rpo[b]; + // (No `xor` of a compare: a loop exit testing one hung the + // AMD driver.) + let cond = if back(self, taken) { + let ok = self.count_iteration(taken, pred::IULT); + self.s.m.bin(self.cur, Bin::And, cond, ok) + } else if back(self, not_taken) { + let stop = self.count_iteration(not_taken, pred::IUGE); + self.s.m.bin(self.cur, Bin::Or, cond, stop) + } else { + cond + }; + // Critical edges get a block of their own, so loops have + // dedicated exits and preheaders as DXC emits them. + let (t, f) = (self.edge(b, taken), self.edge(b, not_taken)); + for (to, via) in [(taken, t), (not_taken, f)] { + if !back(self, to) { + // From an edge block, or from here. + let from = if Some(via) == self.block[to] { + self.cur + } else { + via + }; + self.enter_loop(b, to, from); + } + } + Term::CondBr(cond, t, f) + } + LaneExit::End => { + if self.s.pixel && !self.exported[b] && !self.has_done_export(b) { + // A lane leaving without its final export was killed. + let t = self.s.m.bool(true); + self.s + .op(self.cur, "discard", Attr::NoUnwind, self.s.t.void, 82, &[t]); + } + Term::Ret + } + LaneExit::Indirect => return Err(unsupported(offset, "an indirect jump")), + }; + let _ = Exit::End; + self.s.m.terminate(self.cur, term); + Ok(()) + } + + /// A forward edge into loop header `to` (from DXIL block `via`) starts + /// its count at 0. + fn enter_loop(&mut self, _from: usize, to: usize, via: usize) { + if let Some((_, incoming)) = self.counters.get_mut(&to) { + let z = self.s.m.i32(0); + incoming.push((z, via)); + } + } + + /// A back edge to header `to` (a back edge keeps its block, no + /// critical-edge block): the count goes up; the result compares it with + /// [`LOOP_LIMIT`] by `p` (below: go on; at or above: stop). + fn count_iteration(&mut self, to: usize, p: u8) -> V { + let c = self.cur; + let (phi, _) = self.counters[&to]; + let one = self.s.m.i32(1); + let next = self.s.m.bin(c, Bin::Add, phi, one); + self.s.m.tag(phi, Tag::Counter); + self.s.m.tag(next, Tag::Counter); + // Per stage unless the switch names one: a loop that never meets its + // exit (a count read from a buffer the host has not got yet, say) + // runs to the limit in every lane. A million iterations a pixel + // hung the GPU for seconds a draw until Windows reset it + // (PS_Textured_Eight, 2026-11-24, run 12). + // shortcut: a pixel loop past 128 iterations, a vertex or mesh loop + // past 256 or a compute loop past 4,096 is cut short. (They were + // 1,024, 4,096 and 65,536: the opening cutscene then lost the card + // 14-25 frames in, in a minimap or shadow mesh draw; with every + // loop cut at 64 it ran 90 frames. Raise them again once shaders + // stop reading data that is not there yet.) + let limit = match super::loop_limit() { + LOOP_LIMIT if self.s.pixel => 1 << 7, + LOOP_LIMIT if self.s.mesh.is_some() || self.s.threads.is_none() => 1 << 8, + LOOP_LIMIT => 1 << 12, + named => named, + }; + let limit = self.s.m.i32(limit); + self.counters + .get_mut(&to) + .expect("header") + .1 + .push((next, c)); + let over = self.s.m.cmp(c, p, next, limit); + self.s.m.tag(over, Tag::Counter); + over + } + + /// The block a lane stopped by [`LOOP_LIMIT`] leaves through. + fn abort_block(&mut self) -> usize { + if let Some(a) = self.abort { + return a; + } + let a = self.s.m.new_block(); + if self.s.pixel { + let t = self.s.m.bool(true); + self.s + .op(a, "discard", Attr::NoUnwind, self.s.t.void, 82, &[t]); + } + self.s.m.terminate(a, Term::Ret); + self.abort = Some(a); + a + } + + /// The DXIL block a branch from IR block `from` to `to` goes to. + fn edge(&mut self, from: usize, to: usize) -> usize { + let target = self.block[to].expect("reachable"); + let preds = self.x.p.blocks[to] + .preds + .iter() + .filter(|&&q| self.block[q].is_some()) + .count(); + // Back edges stay as they are: the exiting block is the latch. + if preds < 2 || self.rpo[to] <= self.rpo[from] { + return target; + } + let e = self.s.m.new_block(); + self.s.m.terminate(e, Term::Br(target)); + self.edges.insert((from, to), e); + e + } + + fn fill_phis(&mut self) -> Result<(), Stop> { + let p = self.x.p; + // Lane-mask joins first (what an edge brings may ask for more joins, + // of masks and of numbers): each edge's mask as the structure + // tracked it, a constant or a scalar-built one included. + let st = self.x.st; + while let Some((v, b, i)) = self.pending_masks.pop() { + let phi = &p.blocks[b].phis[i]; + let offset = p.blocks[b].offset; + let args = st + .phi_masks + .get(&phi.value) + .ok_or_else(|| unsupported(offset, "a lane-mask join of an untracked mask"))?; + let mut incoming = Vec::new(); + for (n, &q) in p.blocks[b].preds.iter().enumerate() { + let Some(qb) = self.tail[q] else { continue }; + let qb = self.edges.get(&(q, b)).copied().unwrap_or(qb); + let x = self.boolean(args[n], qb).map_err(|w| unsupported(offset, w))?; + incoming.push((x, qb)); + } + self.s.m.set_phi(v, incoming); + } + // A join that only another join reads is read wherever that one is. Left + // unmarked, a value without a DXIL form coming into it became zero without a + // word (the looked-up tint of the material resolve programs, whose size + // computation had no value, was zero in every lane that way). + // shortcut: only with `LEONIDA_STRICT_JOINS` set (the offline pack + // listing sets it to count them): 40 programs that translate today + // stop by name with it (vehicle paint pixel shaders at "the first + // half of an interpolation", foliage mesh shaders); until those are + // lowered they keep drawing with that zero. + static STRICT: std::sync::OnceLock = std::sync::OnceLock::new(); + let strict = *STRICT.get_or_init(|| std::env::var_os("LEONIDA_STRICT_JOINS").is_some()); + let mut work: Vec = if strict { + self.read_phis.iter().copied().collect() + } else { + Vec::new() + }; + while let Some(v) = work.pop() { + let Some(&(b, i)) = self.phi_at.get(&v) else { + continue; + }; + for &a in &p.blocks[b].phis[i].args { + if self.phi_at.contains_key(&a) && self.read_phis.insert(a) { + work.push(a); + } + } + } + for (v, b, i) in std::mem::take(&mut self.data_phis) { + let phi = &p.blocks[b].phis[i]; + let bit = phi.reg == Reg::Scc; + // A join of numbers with dead registers (`dead`): the paths that bring those + // never read the result, so they bring zero. Not for a join that is itself a + // lane mask (a ballot gives that one as data). + let st = self.x.st; + let numbers = !bit + && !st.masks.contains_key(&phi.value) + && !st.highs.contains_key(&phi.value) + && phi + .args + .iter() + .any(|a| matches!(self.vals.get(a), Some(Val::I32(_)))); + let mut incoming = Vec::new(); + for (n, &q) in p.blocks[b].preds.iter().enumerate() { + let Some(qb) = self.tail[q] else { continue }; + let qb = self.edges.get(&(q, b)).copied().unwrap_or(qb); + let arg = phi.args[n]; + if self.read_phis.contains(&phi.value) && !self.vals.contains_key(&arg) { + let _ = self.lazy_barycentric(arg); + // A root parameter nothing read before the join (user + // data is loaded on first use, in the entry block). + if !self.vals.contains_key(&arg) + && let Some(&(param, dword)) = self.params.get(&arg) + { + let val = self.user(param, dword); + self.vals.insert(arg, val); + } + } + let x = match (self.vals.get(&arg).copied(), bit) { + (Some(Val::I32(x)), false) | (Some(Val::Bit(x)), true) => x, + (Some(Val::Missing(_)) | None, false) + if numbers && self.dead(arg, &mut Vec::new()) => + { + self.s.m.i32(0) + } + // A lane mask joined with numbers (a traversal that keeps its lanes' masks on + // a stack with its node numbers): the mask comes as the number it is, the + // ballot of its lanes where it is written. + (Some(Val::Missing(_)) | None, false) + if self.read_phis.contains(&phi.value) + && self.mask_data == MaskData::Console + && (st.masks.contains_key(&arg) || st.highs.contains_key(&arg)) => + { + match self.mask_dword(arg) { + Ok(x) => x, + Err(why) => return Err(Stop::Retry(phi.value, why)), + } + } + // SCC of a mask operation ("some lane is left") joined with a scalar test: + // the compiler branches around code that sets SCC and tests SCC after it, + // the skip bringing "no lane" along. As data it is "some lane of the wave + // has the bit" - right only if the wave took that skip together, as the + // console does: a lane that skipped alone would bring "some lane" where the + // console has the skipped code's SCC. So the branch must be one the wave + // takes together; else its region is named for `emit`'s retry to widen it. + (Some(Val::Missing(_)) | None, true) + if self.read_phis.contains(&phi.value) + && self.mask_data == MaskData::Console + && st.scc_some.contains_key(&arg) => + { + let per_lane = !st.wide.contains(&q) + && matches!(st.exits[q], LaneExit::Branch { when, .. } + if !st.bools.support(when).iter().all(|a| matches!(a, Atom::Uniform(_)))); + if per_lane { + for &other in p.blocks[b].preds.iter().filter(|&&o| o != q) { + need(other); + } + return Err(Stop::Retry(phi.value, LANE_MASK)); + } + match self.scc_some(arg) { + Ok(x) => x, + Err(why) => return Err(Stop::Retry(phi.value, why)), + } + } + (Some(Val::Bit(_)), false) if self.read_phis.contains(&phi.value) => { + return Err(Stop::Retry(phi.value, "an SCC joined with SGPR values")); + } + (Some(Val::Missing(why)), _) if self.read_phis.contains(&phi.value) => { + return Err(Stop::Retry(phi.value, why)); + } + _ if self.read_phis.contains(&phi.value) => { + return Err(Stop::Retry(phi.value, "a join of mismatched values")); + } + _ if bit => self.s.m.bool(false), + _ => self.s.m.i32(0), + }; + incoming.push((x, qb)); + } + self.s.m.set_phi(v, incoming); + } + for (phi, incoming) in std::mem::take(&mut self.counters).into_values() { + self.s.m.set_phi(phi, incoming); + } + Ok(()) + } +} + +/// The DXIL interpolation mode of a kind of barycentrics (none for the +/// pull model). +fn interp_mode(kind: Barycentric) -> Option { + Some(match kind { + Barycentric::PerspectiveCenter => 2, + Barycentric::PerspectiveCentroid => 3, + Barycentric::PerspectiveSample => 6, + Barycentric::LinearCenter => 4, + Barycentric::LinearCentroid => 5, + Barycentric::LinearSample => 7, + Barycentric::PerspectivePullModel => return None, + }) +} + +#[cfg(test)] +mod tests { + use super::{Lowered, Numeric, Parts, buffer_format, half_shift, lower}; + use crate::native::{ + ComputeIo, HwStage, NativeProgram, ResourceType, RootParam, RootType, StageIo, UsedResource, + }; + use crate::{io, ir, resource, structure}; + + const S_ENDPGM: u32 = 0xBF81_0000; + + #[test] + fn packed_pixel_inputs_find_their_second_row() { + use super::super::container::SigElement; + use super::half_input_partners; + use crate::native::{PsInput, Usage}; + let entry = |row, row2, pack2| PsInput { + usage: Usage::Generic, + row, + mask: 0xF, + attr: row, + flat: false, + fp16: true, + pack2, + row2, + }; + let element = |row| SigElement { + name: "TEXCOORD".into(), + index: row, + kind: 0, + comp: 9, + interp: 2, + row: Some(row), + col: 0, + cols: 4, + usage: 0, + half: true, + }; + // Rows 0 and 3 pack and leave their second row out; 5 names its + // own (6). Unnamed 16-bit rows: 1, 4, 6, 7. + let io = StageIo::Ps { + inputs: vec![entry(0, 0, true), entry(3, 3, true), entry(5, 6, true)], + input_addr: 0, + db_shader_control: 0, + patches: vec![], + }; + let sig: Vec<_> = [0, 1, 3, 4, 5, 6, 7].map(element).into(); + let p = half_input_partners(&io, &sig); + assert_eq!(p.get(&0), Some(&1)); + assert_eq!(p.get(&3), Some(&4)); + assert_eq!(p.get(&5), None); + } + + /// The packed pedestrian layouts of the title: an element + /// behind another one in its register follows in the first parameter + /// with a dword left, and is not a half of its register's row. + #[test] + fn packed_elements_behind_another_take_the_first_free_dword() { + use super::super::container::SigElement; + use super::packed_half; + let element = |index, row, col, cols| SigElement { + name: "TEXCOORD".into(), + index, + kind: 0, + comp: 9, + interp: 2, + row: Some(row), + col, + cols, + usage: 0, + half: true, + }; + // MS_VS_PedTransformPreSkinD_Packed 005fe88ec1bdc0c7 and its pixel + // shader 93667197d3d05e1c: TEXCOORD6 is one value at register 4 + // column 3; parameter 3 (rows 6 and 7) carries it in dword 3. + let sig = vec![ + element(1, 2, 0, 4), + element(2, 3, 0, 4), + element(4, 4, 0, 3), + element(6, 4, 3, 1), + element(3, 5, 0, 4), + element(5, 6, 0, 4), + element(7, 7, 0, 2), + element(9, 9, 0, 3), + element(11, 10, 0, 3), + element(15, 12, 0, 4), + ]; + let packs = [ + (2, Some(3)), + (4, Some(5)), + (6, Some(7)), + (9, Some(10)), + (12, None), + ]; + let at = |a, h| packed_half(&sig, &packs, a, h); + // Parameter 2: TEXCOORD4's three values, a zero half, TEXCOORD3. + assert_eq!(at(4, 2), Some((4, 2))); + assert_eq!(at(4, 3), None); + assert_eq!(at(4, 4), Some((5, 0))); + assert_eq!(at(4, 7), Some((5, 3))); + // Parameter 3: TEXCOORD5, TEXCOORD7, then TEXCOORD6 alone. + assert_eq!(at(6, 3), Some((6, 3))); + assert_eq!(at(6, 5), Some((7, 1))); + assert_eq!(at(6, 6), Some((4, 3))); + assert_eq!(at(6, 7), None); + // Parameters without such an element are as before. + assert_eq!(at(9, 3), None); + assert_eq!(at(9, 4), Some((10, 0))); + assert_eq!(at(12, 3), Some((12, 3))); + assert_eq!(at(12, 4), None); + // The common layout (29805d23a495cdf8): TEXCOORD7 is two values at + // register 1 columns 2-3; parameter 0 is TEXCOORD0, TEXCOORD1, + // TEXCOORD7. + let sig = vec![ + element(0, 1, 0, 2), + element(7, 1, 2, 2), + element(1, 2, 0, 4), + element(2, 3, 0, 4), + element(4, 4, 0, 3), + ]; + let packs = [(3, Some(4)), (1, Some(2))]; + let at = |a, h| packed_half(&sig, &packs, a, h); + assert_eq!(at(1, 1), Some((1, 1))); + assert_eq!(at(1, 2), Some((2, 0))); + assert_eq!(at(1, 5), Some((2, 3))); + assert_eq!(at(1, 6), Some((1, 2))); + assert_eq!(at(1, 7), Some((1, 3))); + assert_eq!(at(3, 6), Some((4, 2))); + assert_eq!(at(3, 7), None); + // A row no element holds gives nothing, as before. + assert_eq!(packed_half(&sig, &[(8, None)], 8, 0), None); + } + + /// Whether a synthetic compute program translates with these input registers. + fn lowers(words: &[u32], rsrc2: u32) -> Result<(), crate::ShaderError> { + let code: Vec = words.iter().flat_map(|w| w.to_le_bytes()).collect(); + let native = NativeProgram { + stage: HwStage::Cs, + wave64: false, + vgprs: 256, + layout: vec![], + used: vec![], + io: StageIo::Cs(ComputeIo { + rsrc2, + threads: [1, 1, 1], + }), + code, + }; + let p = ir::build(&native.code, false, 256).unwrap(); + let st = structure::structure(&p).unwrap(); + let res = resource::track(&p, &native.layout, native.stage, Some(&st)).unwrap(); + let io = io::raise(&p, &native).unwrap(); + lower(&Parts { + native: &native, + p: &p, + st: &st, + io: &io, + res: &res, + inputs: vec![], + outputs: vec![], + prims: vec![], + mesh_stride: 0, + }) + .map(|_| ()) + } + + /// Lowers a compute program with the root parameters `layout` (in user + /// SGPRs from s0 on) and the used resources `used`. + fn lower_with( + words: &[u32], + layout: Vec, + used: Vec, + ) -> Result { + lower_wave(words, layout, used, false) + } + + /// [`lower_with`] in wave64 if `wave64`. + fn lower_wave( + words: &[u32], + layout: Vec, + used: Vec, + wave64: bool, + ) -> Result { + let code: Vec = words.iter().flat_map(|w| w.to_le_bytes()).collect(); + let sgprs: u32 = layout.iter().map(|p| p.sgprs).sum(); + let native = NativeProgram { + stage: HwStage::Cs, + wave64, + vgprs: 256, + layout, + used, + io: StageIo::Cs(ComputeIo { + // The layout's user SGPRs (at least two), 512 bytes of LDS. + rsrc2: 1 << 15 | sgprs.max(2) << 1, + threads: [1, 1, 1], + }), + code, + }; + let p = ir::build(&native.code, wave64, 256).unwrap(); + let st = structure::structure(&p).unwrap(); + let res = resource::track(&p, &native.layout, native.stage, Some(&st))?; + let io = io::raise(&p, &native).unwrap(); + lower(&Parts { + native: &native, + p: &p, + st: &st, + io: &io, + res: &res, + inputs: vec![], + outputs: vec![], + prims: vec![], + mesh_stride: 0, + }) + } + + /// Root parameter `slot` in user SGPRs from `user_data` on. + fn root(root: RootType, user_data: u8, slot: u8) -> RootParam { + RootParam { + root, + table_offset_dwords: 0, + sgprs: if root == RootType::Descriptor { 2 } else { 1 }, + base_register: 0, + user_data, + slot, + } + } + + #[test] + fn buffer_cache_invalidations_lower_as_no_ops() { + // MUBUF opcode 0x071/0x072 with no data operand: the title asks the + // host to invalidate its cached view of a buffer. + assert!(lowers(&[0xE1C4_0000, 0, S_ENDPGM], 0).is_ok(), "buffer_gl0_inv"); + assert!(lowers(&[0xE1C8_0000, 0, S_ENDPGM], 0).is_ok(), "buffer_gl1_inv"); + } + + #[test] + fn a_scalar_carry_chain_reaches_the_select() { + // The high dword of a 64-bit add or subtract, then a select on the + // carry (borrow) the high half leaves in SCC, and a branch on it + // (only code with an effect needs its operands). + let add = [ + 0xBE80_03C1, // s_mov_b32 s0, -1 + 0xBE81_0380, // s_mov_b32 s1, 0 + 0x8000_8100, // s_add_u32 s0, s0, 1 + 0x8201_8001, // s_addc_u32 s1, s1, 0 + 0x8502_0001, // s_cselect_b32 s2, s1, s0 + 0xBF07_8002, // s_cmp_lg_u32 s2, 0 + 0xBF85_0001, // s_cbranch_scc1 -> s_endpgm + 0xBE83_0380, // s_mov_b32 s3, 0 + S_ENDPGM, + ]; + let sub = [ + 0xBE80_0380, // s_mov_b32 s0, 0 + 0xBE81_0380, // s_mov_b32 s1, 0 + 0x8080_8100, // s_sub_u32 s0, s0, 1 + 0x8281_8001, // s_subb_u32 s1, s1, 0 + 0x8502_0001, // s_cselect_b32 s2, s1, s0 + 0xBF07_8002, // s_cmp_lg_u32 s2, 0 + 0xBF85_0001, // s_cbranch_scc1 -> s_endpgm + 0xBE83_0380, // s_mov_b32 s3, 0 + S_ENDPGM, + ]; + + for words in [add, sub] { + lowers(&words, 0).unwrap(); + } + } + + fn perm_features(selector: u32) -> u64 { + // Synthetic compute shader: + // v0 is the thread ID and can supply a dynamic selector. + // Store the result in LDS to keep the permutation live. + let words = [ + 0x7E02_02FFu32, + 0x817F_34AB, + 0x7E04_02FF, + 0xFE01_56CD, + 0xD744_0003, + 257 | (258 << 9) | (selector << 18), + 0x3408_0082, + 0xD834_0000, + 0x0000_0304, + S_ENDPGM, + ]; + + let code: Vec = words.iter() + .flat_map(|w| w.to_le_bytes()) + .collect(); + + let native = NativeProgram { + stage: HwStage::Cs, + wave64: false, + vgprs: 256, + layout: vec![], + used: vec![], + io: StageIo::Cs(ComputeIo { + rsrc2: 1 << 15, + threads: [64, 1, 1], + }), + code, + }; + + let p = ir::build(&native.code, false, 256).unwrap(); + + assert!(p.blocks.iter() + .flat_map(|b| &b.insts) + .any(|i| i.name() == "v_perm_b32")); + + let st = structure::structure(&p).unwrap(); + let res = resource::track(&p, &native.layout, native.stage, Some(&st)).unwrap(); + + let io = io::raise(&p, &native).unwrap(); + + let emitted = lower(&Parts { + native: &native, + p: &p, + st: &st, + io: &io, + res: &res, + inputs: vec![], + outputs: vec![], + prims: vec![], + mesh_stride: 0, + }).unwrap(); + + let container = + crate::Container::parse(&emitted.dxil).unwrap(); + + let features = + container.part(crate::FourCC::SFI0).unwrap(); + + u64::from_le_bytes(features.data.try_into().unwrap()) + } + + #[test] + fn perm_constant_selector_needs_no_int64() { + assert_eq!(perm_features(128) & 0x8000, 0); + } + + #[test] + fn perm_dynamic_selector_needs_no_int64() { + assert_eq!( + perm_features(256) & 0x8000, + 0, + "dynamic v_perm_b32 must not require INT64" + ); + } + + #[test] + fn a_descriptor_selected_by_scc_picks_its_heap_index() { + // Two buffer descriptors loaded from the table at s0, one picked by + // a root constant (s1) with s_cselect_b64 per half, and loaded + // through by index and stored to LDS so the load is needed. + let words = [ + 0xBE84_0300, // s_mov_b32 s4, s0 + 0xBE85_0380, // s_mov_b32 s5, 0 + 0xF408_0202, + 0xFA00_0000, // s_load_dwordx4 s[8:11], s[4:5], null + 0xF408_0302, + 0xFA00_0010, // s_load_dwordx4 s[12:15], s[4:5], 0x10 + 0xBF06_8001, // s_cmp_eq_u32 s1, 0 + 0x8590_0C08, // s_cselect_b64 s[16:17], s[8:9], s[12:13] + 0x8592_0E0A, // s_cselect_b64 s[18:19], s[10:11], s[14:15] + 0xE030_2000, + 0x8004_0100, // buffer_load_dword v1, v0, s[16:19], 0 idxen + 0xD834_0000, + 0x0000_0100, // ds_write_b32 v0, v1 + S_ENDPGM, + ]; + let layout = || vec![root(RootType::Table, 0, 0), root(RootType::Constants, 1, 1)]; + // Both are structured buffers of dwords in the table's range. + let used = || { + vec![UsedResource { + kind: ResourceType::Srv, + root: RootType::Table, + table_offset_dwords: 0, + lower_bound: 0, + stride: 4, + dwords: 4, + user_data: 0, + slot: 0, + }] + }; + lower_with(&words, layout(), used()).unwrap(); + } + + /// Tables of 2D textures at s0 and samplers at s1. + fn texture_tables() -> (Vec, Vec) { + let range = |kind, user_data, slot| UsedResource { + kind, + root: RootType::Table, + table_offset_dwords: 0, + lower_bound: 0, + stride: 0, + dwords: if kind == ResourceType::Sampler { 4 } else { 8 }, + user_data, + slot, + }; + ( + vec![root(RootType::Table, 0, 0), root(RootType::Table, 1, 1)], + vec![ + range(ResourceType::Srv, 0, 0), + range(ResourceType::Sampler, 1, 1), + ], + ) + } + + #[test] + fn waterfall_loops_over_per_lane_descriptors_sample_with_each_lanes_own() { + use crate::resource::tests::{ + WATERFALL_FETCHED_WAVE32, WATERFALL_FETCHED_WAVE64, WATERFALL_PICKED_WAVE32, + }; + for (words, wave64) in [ + (WATERFALL_FETCHED_WAVE32, false), + (WATERFALL_FETCHED_WAVE64, true), + (WATERFALL_PICKED_WAVE32, false), + ] { + let (layout, used) = texture_tables(); + let l = lower_wave(words, layout, used, wave64).unwrap(); + // The loop's reads of the first lane became each lane's own + // dwords: no wave operation is left. + assert_eq!(l.nonuniform_handles, 1); + assert!(!l.wave_ops); + } + } + + /// [`texture_tables`] with a raw buffer UAV at dword 16 of the first. + pub(crate) fn texture_and_uav_tables() -> (Vec, Vec) { + let (layout, mut used) = texture_tables(); + used.push(UsedResource { + kind: ResourceType::Uav, + root: RootType::Table, + table_offset_dwords: 16, + lower_bound: 0, + stride: 0, + dwords: 4, + user_data: 0, + slot: 0, + }); + (layout, used) + } + + #[test] + fn waterfall_loops_over_descriptors_joined_per_lane_sample_with_each_lanes_own() { + use crate::resource::tests::{WATERFALL_JOINED_MIXED_WAVE32, WATERFALL_JOINED_WAVE32}; + for words in [WATERFALL_JOINED_WAVE32, WATERFALL_JOINED_MIXED_WAVE32] { + let (layout, used) = texture_and_uav_tables(); + let l = lower_wave(words, layout, used, false).unwrap(); + // One image handle, from the join's per-lane heap index. + assert_eq!(l.nonuniform_handles, 1); + assert!(!l.wave_ops); + } + } + + #[test] + fn scalar_bit_tests_lower() { + // Each tests one bit of a constant into SCC and branches on it (only + // code with an effect needs its operands). + let tail = [ + 0xBF85_0001, // s_cbranch_scc1 -> s_endpgm + 0xBE84_0380, // s_mov_b32 s4, 0 + S_ENDPGM, + ]; + let bit_tests: [&[u32]; 4] = [ + &[0xBE81_0387, 0xBF0C_8301], // s_mov_b32 s1, 7; s_bitcmp0_b32 s1, 3 + &[0xBE81_0387, 0xBF0D_8301], // s_mov_b32 s1, 7; s_bitcmp1_b32 s1, 3 + &[ + 0xBE80_0387, // s_mov_b32 s0, 7 + 0xBE81_0380, // s_mov_b32 s1, 0 + 0xBF0E_8300, // s_bitcmp0_b64 s[0:1], 3 + ], + &[ + 0xBE80_0387, // s_mov_b32 s0, 7 + 0xBE81_0380, // s_mov_b32 s1, 0 + 0xBF0F_8300, // s_bitcmp1_b64 s[0:1], 3 + ], + ]; + for head in bit_tests { + let words: Vec = head.iter().chain(&tail).copied().collect(); + lowers(&words, 0).unwrap(); + } + } + + #[test] + #[ignore = "ours marks joins read through joins only with LEONIDA_STRICT_JOINS (40 programs stop otherwise)"] + fn a_missing_value_stays_missing_through_two_live_joins() { + let mut words = [ + 0xF490_0180, + 0, // s_memtime s[6:7] + 0xBF06_8000, // s_cmp_eq_u32 s0, 0 (s0 = group id X) + 0xBF85_0001, // skip the first overwrite + 0xBE86_0380, // s_mov_b32 s6, 0 + 0xBF06_8101, // s_cmp_eq_u32 s1, 1 (s1 = group id Y) + 0xBF85_0001, // skip the second overwrite + 0xBE86_0381, // s_mov_b32 s6, 1 + 0xBF07_8006, // s_cmp_lg_u32 s6, 0 + 0xBF85_0001, // use the result to branch + 0xBE83_0380, + S_ENDPGM, + ]; + let group_ids_xy = 3 << 7; + // Compare to a direct read so future timestamp support works in both cases. + let refusal = |code: &[u32]| match lowers(code, group_ids_xy) { + Ok(()) => None, + Err(crate::ShaderError::Unsupported { what, .. }) => Some(what), + Err(error) => panic!("{error}"), + }; + let direct = [&words[..2], &words[8..]].concat(); + assert_eq!(refusal(&words), refusal(&direct)); + words[8] = 0xBF07_8000; // read the group id instead; the timestamp is dead + lowers(&words, group_ids_xy).expect("dead timestamp"); + } + + #[test] + fn buffer_formats_by_number() { + // The numbers the disassembler names 8_8_8_8_UNORM, 16_16_SNORM, + // 2_10_10_10_UNORM, 16_FLOAT, 32_32_32_32_FLOAT. + assert_eq!(buffer_format(56), Some((&[8, 8, 8, 8][..], Numeric::Unorm))); + assert_eq!(buffer_format(24), Some((&[16, 16][..], Numeric::Snorm))); + assert_eq!( + buffer_format(50), + Some((&[10, 10, 10, 2][..], Numeric::Unorm)) + ); + assert_eq!(buffer_format(13), Some((&[16][..], Numeric::Float))); + assert_eq!( + buffer_format(77), + Some((&[32, 32, 32, 32][..], Numeric::Float)) + ); + // Invalid, past the table. + assert_eq!(buffer_format(0), None); + assert_eq!(buffer_format(78), None); + } + + #[test] + fn packed_buffer_formats_by_number() { + // LLVM's `UfmtGFX10`: 10_11_11 is 30-36, 11_11_10 37-43, + // 10_10_10_2 44-49. Channels from the lowest bits: R11G11B10_FLOAT + // is 10_11_11 (Mesa), 10_10_10_2 has the 2-bit channel first. + assert_eq!(buffer_format(30), Some((&[11, 11, 10][..], Numeric::Unorm))); + assert_eq!(buffer_format(36), Some((&[11, 11, 10][..], Numeric::Float))); + assert_eq!(buffer_format(37), Some((&[10, 11, 11][..], Numeric::Unorm))); + assert_eq!(buffer_format(43), Some((&[10, 11, 11][..], Numeric::Float))); + assert_eq!( + buffer_format(44), + Some((&[2, 10, 10, 10][..], Numeric::Unorm)) + ); + assert_eq!( + buffer_format(45), + Some((&[2, 10, 10, 10][..], Numeric::Snorm)) + ); + assert_eq!( + buffer_format(46), + Some((&[2, 10, 10, 10][..], Numeric::Uscaled)) + ); + assert_eq!( + buffer_format(47), + Some((&[2, 10, 10, 10][..], Numeric::Sscaled)) + ); + assert_eq!( + buffer_format(48), + Some((&[2, 10, 10, 10][..], Numeric::Uint)) + ); + assert_eq!( + buffer_format(49), + Some((&[2, 10, 10, 10][..], Numeric::Sint)) + ); + } + + /// A half's value (sign, 5-bit exponent biased 15, 10-bit mantissa), as + /// `legacyF16ToF32` widens it. + fn half(h: u32) -> f32 { + let (s, e, m) = ((h >> 15) & 1, (h >> 10) & 31, h & 1023); + let v = match e { + 0 => m as f32 * 2f32.powi(-24), + 31 if m == 0 => f32::INFINITY, + 31 => f32::NAN, + _ => (1024 + m) as f32 * 2f32.powi(e as i32 - 25), + }; + if s == 1 { -v } else { v } + } + + #[test] + fn small_floats_widen_as_halves() { + // Unsigned 11- and 10-bit floats: a 5-bit exponent biased 15 over a + // 6- or 5-bit mantissa, no sign; values from the D3D/GL spec. + let f11 = |x: u32| half(x << half_shift(11)); + let f10 = |x: u32| half(x << half_shift(10)); + assert_eq!(f11(0), 0.0); + assert_eq!(f11(0x001), 2f32.powi(-20)); // smallest denormal + assert_eq!(f11(0x03F), 63.0 * 2f32.powi(-20)); // largest denormal + assert_eq!(f11(0x040), 2f32.powi(-14)); // smallest normal + assert_eq!(f11(0x3C0), 1.0); + assert_eq!(f11(0x3E0), 1.5); + assert_eq!(f11(0x7BF), 65024.0); // largest + assert_eq!(f11(0x7C0), f32::INFINITY); + assert!(f11(0x7C1).is_nan()); + assert_eq!(f10(0x001), 2f32.powi(-19)); + assert_eq!(f10(0x020), 2f32.powi(-14)); + assert_eq!(f10(0x1E0), 1.0); + assert_eq!(f10(0x3DF), 64512.0); + assert_eq!(f10(0x3E0), f32::INFINITY); + assert!(f10(0x3FF).is_nan()); + // A 16-bit float is a half already, sign included. + assert_eq!(half(0xBC00 << half_shift(16)), -1.0); + } +} diff --git a/crates/leonida-shader/src/emit/mod.rs b/crates/leonida-shader/src/emit/mod.rs new file mode 100644 index 000000000..af521b239 --- /dev/null +++ b/crates/leonida-shader/src/emit/mod.rs @@ -0,0 +1,1786 @@ +//! DXIL emission (decision 0003, step 3): a console vertex, pixel, compute +//! or mesh shader as a PC DXIL container (SM 6.6) that host D3D12 accepts. +//! Compute shaders keep the console's thread-group size; one that depends +//! on the lane layout (cross-lane operations) declares the console's wave +//! size (`WaveSize`), so the host device must support it. +//! +//! What the host binds for a translated shader ([`HostShader`]): +//! +//! * **User data** at `b0, space 0` (32-bit root constants or a constant +//! buffer, per stage): dword `index` holds a root parameter's value, as +//! [`UserData`] lists. A root-constant dword is the constant. A +//! descriptor table is the byte offset of its first descriptor in its +//! heap: the descriptor index times 32 for CBV/SRV/UAV tables, times 16 +//! for sampler tables (the console's descriptor sizes; the code adds +//! offsets in those units). The heap bases of dynamic resources are 0 +//! and not listed. +//! * **Descriptors** through SM 6.6 `ResourceDescriptorHeap[]` and +//! `SamplerDescriptorHeap[]`, at the index the console address gives, so +//! the host heaps keep the title's descriptor order. The root signature +//! needs `CBV_SRV_UAV_HEAP_DIRECTLY_INDEXED` and +//! `SAMPLER_HEAP_DIRECTLY_INDEXED`. +//! * **Immediate samplers** as static samplers `s, space 0`, `n` the +//! position in [`HostShader::samplers`] (the console sampler words) and +//! [`HostShader::static_samplers`] (the same decoded into a D3D12 static +//! sampler description). Comparison sampling (added 2026-11-23): an +//! immediate sampler it uses has a comparison filter there (bit 0x80); +//! a heap sampler it uses must be a comparison sampler on the host. +//! * **Root CBVs and root SRVs** (raw buffers) as root descriptors +//! `b` / `t` in [`ROOT_CBV_SPACE`], `i` the title's root parameter +//! index ([`HostShader::root_cbvs`], [`HostShader::root_srvs`]); the +//! address the title sets is the buffer's. +//! * **Vertex fetch** (added 2026-11-23). The title's mesh and +//! vertex programs fetch vertices themselves with typed-format loads +//! (`tbuffer_load_format_*`): the format (8_8_8_8 unorm, 16_16 snorm, +//! 2_10_10_10 unorm, 8_8_8_8 and 16_16_16_16 uint...) is in the +//! instruction, so the translation reads raw bytes and converts them +//! itself. Their descriptors are built around a root SRV (stride 1, no +//! record limit): the host binds the root SRV `t` above with the +//! address the title sets, nothing more. The vertex index, the stride +//! and the attribute offset are the shader's own arithmetic on data in +//! that buffer (per-stream headers), not descriptor fields. +//! * **Buffer views in the heap** are declared by how the shader reads +//! them: raw (ByteAddressBuffer) for dword loads and stores, atomics and +//! typed-format loads without an index; structured with the used-resource +//! entry's stride when indexed; typed with four 32-bit float channels for +//! `buffer_load_format_*` and `buffer_store_format_*`. The host's view at +//! that index must be of that kind and start at the console descriptor's +//! base address (raw: `R32_TYPELESS` with the raw flag), whatever kind the +//! title's view description says. Typed-format loads from heap +//! descriptors (1,024 world compute programs, ray-tracing material +//! resolves) read raw views this way. +//! +//! * **Texture atomics** use a scalar integer UAV. The host binds R32_UINT +//! for 32-bit operations and R32G32_UINT for 64-bit operations. The latter +//! require SM 6.6 atomic support on typed and descriptor-heap resources. +//! +//! Entry points: [`translate`] (container bytes as the title passes them +//! at pipeline creation → [`HostShader`]), [`emit`] (the same with the +//! earlier stages already run). The root constants of each stage must +//! cover [`HostShader::user_data_dwords`]. Stability: these types and the +//! binding scheme are what pipeline creation builds on; changes are +//! announced. +//! * **Signatures** as the console container has them (same semantics, +//! registers and masks), so the input layout and stage linking are the +//! title's; pixel outputs are plain 32-bit values. +//! * **Mesh shaders** ([`HwStage::Ms`], `ms_6_6`): user data and +//! descriptors as above (the root constants visible to the mesh stage); +//! the pipeline is a mesh pipeline (pipeline-state stream, no input +//! layout) with the title's pixel shader. The thread group is the +//! console's in lanes (`[numthreads]` in the DXIL), the vertex and +//! primitive maxima its own, triangles only, no wave size required. The +//! console numbers groups in x only: the draw path passes the title's +//! count as `DispatchMesh(x, 1, 1)`. Per-primitive outputs (`PSG1`) are +//! the console's, without `SV_PrimitiveID` and `SV_CullPrimitive` (the +//! console never exports them). +//! * **Rectangle lists** ([`rect_list_gs`], `gs_6_6`): the console draws a +//! rectangle from three vertices; the host has no such topology. A +//! pipeline the title makes for rectangles (topology type 19) gets a +//! geometry shader of ours between the translated vertex and pixel +//! shaders and draws triangle lists with the title's own vertex counts. +//! It binds nothing. + +mod bitcode; +mod container; +#[cfg(all(test, windows))] +mod diff_tests; +#[cfg(all(test, windows))] +mod intersect_tests; +#[cfg(all(windows, any(test, feature = "host")))] +pub mod host; +mod lower; +mod own_bits; +mod rect; +mod sampler; +mod shader; +mod threading; +#[cfg(windows)] +pub mod validator; +#[cfg(all(test, windows))] +mod valu_tests; +#[cfg(all(test, windows))] +mod waterfall_tests; +#[cfg(all(test, windows))] +mod wave64_tests; +mod wave; + +use crate::dxbc::{Container, FourCC}; +use crate::native::{HwStage, NativeProgram, RootType}; +use crate::{ShaderError, io, ir, resource, structure}; + +pub use bitcode::census; +pub use sampler::StaticSampler; +pub use lower::set_host_max_wave; +pub use rect::rect_list_gs; +pub use shader::{ + MEMORY_FAULTS, MEMORY_PAGES, ROOT_CBV_SPACE, SAMPLER_SPACE, SLOT_FAULTS, SLOT_MEMORY, SLOT_STRIDES, + SLOT_STRIDES_COUNT, USER_DATA_SPACE, USER_MEMORY_BASE, USER_VIEW_ADDRESS, USER_VIEW_BIAS, + set_view_heap_limit, view_heap_limit, +}; + +/// The loop limit without an override: 2^20. +pub const DEFAULT_LOOP_LIMIT: u32 = lower::LOOP_LIMIT; + +/// The iteration count after which a translated loop is left, per lane and +/// per entry into the loop: [`DEFAULT_LOOP_LIMIT`]. +/// +/// With the `diagnostics` feature, `LEONIDA_SHADER_LOOP_LIMIT` (decimal or +/// `0x` hex, at least 1) sets it instead. A loop that hits the limit in +/// every lane of a full-screen pass still runs for seconds (2^20 times a +/// 4K screen is about 10^13 iterations); a much lower limit shows whether +/// such loops are what makes a frame slow. The value is part of the +/// translation, so the shader cache must key on it (`leonida-gpu`'s does). +pub fn loop_limit() -> u32 { + static LIMIT: std::sync::OnceLock = std::sync::OnceLock::new(); + *LIMIT.get_or_init(|| { + if cfg!(feature = "diagnostics") { + parse_loop_limit(std::env::var("LEONIDA_SHADER_LOOP_LIMIT").ok().as_deref()) + } else { + lower::LOOP_LIMIT + } + }) +} + +/// Which of a translated program's group barriers wait for the whole +/// group (`GroupMemoryBarrierWithGroupSync`); the others keep their memory +/// fence and lose the wait. A wait that some thread of the group never +/// reaches is undefined on the host, and NVIDIA's wait is for every +/// thread: the group stands until Windows resets the card. (The console's +/// barrier is the wave's, whatever lanes are live, and a wave that ended +/// is not waited for.) `LEONIDA_GROUP_SYNC`: +/// - unset or `2`: every barrier waits, as before. +/// - `1`: the title's `s_barrier` waits only in a block every lane runs, +/// in a program no lane can be cut out of at the iteration limit. +/// - `0`: no barrier waits, neither the title's nor the ones the +/// translation adds (wave64 programs in two host waves exchange through +/// them, so such programs compute wrong values). For one run that tells +/// whether a barrier is what stops the card: with it no run can stand in +/// a barrier. +/// +/// Part of the translation: the shader cache keys on it (`leonida-gpu`'s +/// does). +pub fn group_sync() -> u8 { + static MODE: std::sync::OnceLock = std::sync::OnceLock::new(); + *MODE.get_or_init(|| match std::env::var("LEONIDA_GROUP_SYNC").ok().as_deref().map(str::trim) { + Some("0") => 0, + Some("1") => 1, + _ => 2, + }) +} + +/// The clean-up passes that run over a translated program before it is +/// written (`bitcode::opt`): a set of that module's pass bits. Every pass +/// is exact, so the switch is for telling a translator fault from a +/// clean-up fault, and for measuring what the clean-up is worth. +/// `LEONIDA_SHADER_OPT`: +/// - unset: every pass. +/// - `0`: none (the module as the lowering made it). +/// - a number (decimal or `0x` hex): those passes; 1 dead code, 2 constants +/// and identities, 4 one instruction for one value, 8 what a branch taken +/// says about its condition, 16 one read for one place within a block, +/// 32 a first-lane read of two host waves without the round that asks +/// which half has a lane (where every lane has one). +/// +/// Part of the translation: the shader cache keys on it (`leonida-gpu`'s +/// does). +pub fn shader_opt() -> u32 { + static PASSES: std::sync::OnceLock = std::sync::OnceLock::new(); + *PASSES.get_or_init(|| parse_shader_opt(std::env::var("LEONIDA_SHADER_OPT").ok().as_deref())) +} + +/// Everything a translation depends on besides the container: the +/// translator's own source (hashed at build time), the value of every +/// `LEONIDA_*` switch it reads, the host facts the device hands it (widest +/// wave, view heap limit) and the settings above. The shader cache keys on +/// this instead of on the whole executable, so a rebuild that leaves the +/// translator alone keeps its translations. Call it after the device is made. +pub fn translation_fingerprint() -> Vec { + let mut out = Vec::new(); + out.extend_from_slice(env!("LEONIDA_SHADER_SOURCE_HASH").as_bytes()); + out.push(u8::from(cfg!(feature = "diagnostics"))); + out.push(u8::from(cfg!(debug_assertions))); + for name in env!("LEONIDA_SHADER_SWITCHES").split(',').filter(|n| !n.is_empty()) { + out.extend_from_slice(name.as_bytes()); + out.push(b'='); + if let Some(value) = std::env::var_os(name) { + out.extend_from_slice(value.as_encoded_bytes()); + } + out.push(0); + } + out.extend_from_slice(&lower::host_max_wave().to_le_bytes()); + out.extend_from_slice(&shader::view_heap_limit().to_le_bytes()); + out.extend_from_slice(&loop_limit().to_le_bytes()); + out.push(group_sync()); + out.extend_from_slice(&shader_opt().to_le_bytes()); + out +} + +/// `LEONIDA_SHADER_OPT`'s value; every pass when it is unset or +/// unreadable. Pure, for testing. +fn parse_shader_opt(value: Option<&str>) -> u32 { + let parsed = value + .map(str::trim) + .and_then(|v| match v.strip_prefix("0x") { + Some(hex) => u32::from_str_radix(hex, 16).ok(), + None => v.parse().ok(), + }); + parsed.map_or(bitcode::opt::ALL, |n| n & bitcode::opt::ALL) +} + +/// `LEONIDA_SHADER_LOOP_LIMIT`'s value; the default when it is unset, +/// unreadable or 0. Pure, for testing. +fn parse_loop_limit(value: Option<&str>) -> u32 { + let parsed = value + .map(str::trim) + .and_then(|v| match v.strip_prefix("0x") { + Some(hex) => u32::from_str_radix(hex, 16).ok(), + None => v.parse().ok(), + }); + match parsed { + Some(n) if n > 0 => n, + _ => lower::LOOP_LIMIT, + } +} + +/// A translated shader and what the host binds for it. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct HostShader { + pub stage: HwStage, + /// The DXIL container, hashed as D3D12 expects. + pub dxil: Vec, + /// The user-data dwords the shader reads. + pub user_data: Vec, + /// Immediate samplers: the four sampler words of `s`. + pub samplers: Vec<[u32; 4]>, + /// The same samplers decoded, `s` at position n: the static sampler + /// descriptions the host's root signature declares. + pub static_samplers: Vec, + /// Root CBVs the shader reads: root parameter indices, each bound as + /// `b` in [`ROOT_CBV_SPACE`]. + pub root_cbvs: Vec, + /// Root SRVs (raw buffers) the shader reads: `t` in + /// [`ROOT_CBV_SPACE`]. + pub root_srvs: Vec, + /// Root UAVs (raw buffers) the shader reads or writes: `u` in + /// [`ROOT_CBV_SPACE`]. + pub root_uavs: Vec, + /// Heap descriptors that can be selected from root state at bind time. + pub root_indexed_views: Vec, +} + +impl HostShader { + /// Size of the user-data buffer the shader declares, in dwords (a + /// multiple of 4; 0 when it reads none). Root constants must cover it. + pub fn user_data_dwords(&self) -> u32 { + let n = self + .user_data + .iter() + .map(|u| u.index + 1) + .max() + .unwrap_or(0); + n.next_multiple_of(4) + } +} + +/// One dword of user data and the root parameter that fills it. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct UserData { + /// Dword in the user-data buffer (the console's user-data index). + pub index: u32, + /// Root parameter index in the title's root signature. + pub slot: u8, + /// `Constants` or `Table` (see the module notes for the value). + pub root: RootType, + /// Dword within the parameter. + pub dword: u32, +} + +/// Translates the vertex, pixel, compute or mesh program of a console +/// shader container. +/// +/// A program refused because the first half of an interpolation is read as +/// data is translated once more with first halves evaluated as the pair +/// they start (`lower::with_first_half_pairs`), and only such a program: +/// with that on for every program, 8,551 pixel programs of the title that +/// already translated came out changed (an extra evaluation in each), for +/// the sake of 9 that did not translate. +pub fn translate(container: &[u8]) -> Result { + match translate_plain(container) { + Err(ShaderError::Unsupported { what, .. }) if what == lower::FIRST_HALF => { + lower::with_first_half_pairs(|| translate_plain(container)) + } + other => other, + } +} + +fn translate_plain(container: &[u8]) -> Result { + let c = Container::parse(container)?; + let dxil = c + .part(FourCC::DXIL) + .ok_or(ShaderError::Malformed("no DXIL part"))?; + let native = crate::native_programs(dxil.data)? + .into_iter() + .find(|p| { + matches!( + p.stage, + HwStage::Vs | HwStage::Ps | HwStage::Cs | HwStage::Ms + ) + }) + .ok_or(ShaderError::Unsupported { + offset: 0, + what: "a container without a vertex, pixel, compute or mesh program", + })?; + let p = crate::spill::build(&native)?; + // Structurisation first: tracing per-lane descriptors needs it (its + // failure is reported after the earlier stages'). + 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?; + emit(&c, &native, &p, &st, &io, &res) +} + +/// Emits a program whose earlier stages already ran. +pub fn emit( + c: &Container, + native: &NativeProgram, + p: &ir::Program, + st: &structure::Structured, + io: &io::Io, + res: &resource::Resources, +) -> Result { + // (what an earlier program's lowering on this thread left behind) + lower::take_needs(); + let original = emit_program(c, native, p, st, io, res); + // A console wave64 compute program on a host of 32-lane waves that + // still needs 64 lanes, or whose cross-lane code sits where not every + // lane runs: once more with its early-outs left out + // ([`ir::without_early_outs`]), which is what usually keeps the whole + // body from being a block every lane runs. + let stuck = match &original { + Ok((_, wave)) => *wave == Some(64), + Err(ShaderError::Unsupported { what, .. }) => lower::needs_every_lane(what), + Err(_) => false, + }; + // (a mask with lanes elsewhere is only helped by the exact forms: not by each half-wave + // on its own) + let exact_only = matches!(&original, Err(ShaderError::Unsupported { what, .. }) if *what == lower::MASK_ELSEWHERE); + if stuck && native.stage == HwStage::Cs && native.wave64 && lower::host_max_wave() == 32 { + let why = std::env::var_os("LEONIDA_WAVE_WHY").is_some(); + let report = |what: &str, r: &Result<(HostShader, Option), ShaderError>| { + if why { + match r { + Ok((_, wave)) => eprintln!("WAVE64-RETRY {what}: wave {wave:?}"), + Err(e) => eprintln!("WAVE64-RETRY {what}: {e}"), + } + } + }; + let done = |r: &Result<(HostShader, Option), ShaderError>| matches!(r, Ok((_, wave)) if *wave != Some(64)); + // Each host wave as a wave of its own (`lower::with_local_waves`), + // for programs still stopped where not every lane runs. + let local_on = std::env::var_os("LEONIDA_WAVE_LOCAL").is_none_or(|v| v != "0"); + // Where the wave operations are the allocation idiom + // ([`lower::wave_local`]) that is exact. Other programs are taken + // the same way last of all, each half-wave giving its own results + // (approximate: a tile-wide result becomes two half-tile ones); + // `LEONIDA_WAVE_LOCAL=idiom` refuses those instead. + let strict = std::env::var_os("LEONIDA_WAVE_LOCAL").is_some_and(|v| v == "idiom"); + let idiom = |p: &ir::Program, st: &structure::Structured| match lower::wave_local(p, st) { + Ok(()) => true, + Err((offset, what)) => { + if why { + eprintln!("WAVE64-RETRY local waves: not the allocation idiom at {offset:#x}: {what}"); + } + false + } + }; + // The program in two other forms: without its early-outs, and + // without any branch that only skips code no lane is left for. + let form = |p: Option| { + p.and_then(|p| { + let st = structure::structure(&p).ok()?; + let io = io::raise(&p, native).ok()?; + let res = resource::track(&p, &native.layout, native.stage, Some(&st)).ok()?; + Some((p, st, io, res)) + }) + }; + let forms = [ + ("without early-outs", form(ir::without_early_outs(p))), + ("without skips", form(ir::without_skips(p, false))), + ]; + for (name, f) in &forms { + if let Some((p, st, io, res)) = f { + let again = emit_program(c, native, p, st, io, res); + report(name, &again); + if done(&again) { + return again.map(|(shader, _)| shader); + } + } + } + // Off unless asked for (`LEONIDA_WAVE_WIDE=1`), for a console wave run as two host + // waves: this form puts group barriers inside branches and loops, and runs 121-124 + // lost the card in a submission of two programs that had just moved to it + // (`ptfx_CS_lightAtlas_Sprite` and `_Trail`). The 32-lane programs' form below, which + // has no barrier, stays on. + let wide_on = std::env::var_os("LEONIDA_WAVE_WIDE").is_some_and(|v| v == "1"); + // exact first: each host wave on its own where that is exact (the idiom, every + // form; no barriers), then the other exact forms; then approximate + for exact in [true, false] { + if !exact { + // Before anything approximate, the exact forms that cost group barriers. + // Every skip left out that the code after it cannot see + // ([`ir::without_skips`], `deep`): most of the body is then code every + // lane runs, where the two host waves can exchange. + // (`LEONIDA_WAVE_DEEP_SKIPS=0` and `LEONIDA_WAVE_WIDE=0` turn the two off.) + let deep_on = std::env::var_os("LEONIDA_WAVE_DEEP_SKIPS").is_none_or(|v| v != "0"); + let deep = if deep_on { form(ir::without_skips(p, true)) } else { None }; + if let Some((p, st, io, res)) = &deep { + let again = emit_program(c, native, p, st, io, res); + report("without skips, scalars followed", &again); + if done(&again) { + return again.map(|(shader, _)| shader); + } + } + // Still stopped where not every lane runs: the per-lane branches around + // those places taken as the console takes them, by the whole wave at once + // ([`widen`]), at two group barriers per such branch. + if wide_on { + let bases = [ + deep.as_ref().map(|f| &f.0), + forms[1].1.as_ref().map(|f| &f.0), + forms[0].1.as_ref().map(|f| &f.0), + Some(p), + ]; + if let Some(base) = bases.into_iter().flatten().next() { + let again = widen(c, native, base, why); + report("wave-wide branches", &again); + if done(&again) { + return again.map(|(shader, _)| shader); + } + } + } + if strict { + break; + } + } + if !local_on || exact_only { + continue; + } + for (name, f) in &forms { + if let Some((p, st, io, res)) = f + && idiom(p, st) == exact + { + let local = lower::with_local_waves(|| emit_program(c, native, p, st, io, res)); + report(&format!("local waves ({}), {name}", if exact { "idiom" } else { "APPROXIMATE" }), &local); + if done(&local) { + return local.map(|(shader, _)| shader); + } + } + } + if idiom(p, st) == exact { + let local = lower::with_local_waves(|| emit_program(c, native, p, st, io, res)); + report(if exact { "local waves (idiom)" } else { "local waves (APPROXIMATE)" }, &local); + if done(&local) { + return local.map(|(shader, _)| shader); + } + } + } + if local_on && !exact_only { + // Last: every mask and lane read per host wave. + if !strict { + for (name, f) in &forms { + if let Some((p, st, io, res)) = f { + let local = lower::with_local_waves_any(|| emit_program(c, native, p, st, io, res)); + report(&format!("local waves (APPROXIMATE, any mask), {name}"), &local); + if done(&local) { + return local.map(|(shader, _)| shader); + } + } + } + let local = lower::with_local_waves_any(|| emit_program(c, native, p, st, io, res)); + report("local waves (APPROXIMATE, any mask)", &local); + if done(&local) { + return local.map(|(shader, _)| shader); + } + } + } + } + // SCC of a mask operation joined with a scalar test behind a per-lane skip (the 32-lane + // trace programs): right once the wave takes that skip together ([`widen`]; the + // lowering has named the skipped blocks). + let original = match original { + Err(ShaderError::Unsupported { what, .. }) + if native.stage == HwStage::Cs + && what == lower::LANE_MASK + && std::env::var_os("LEONIDA_WAVE_WIDE").is_none_or(|v| v != "0") => + { + let again = widen(c, native, p, std::env::var_os("LEONIDA_WAVE_WHY").is_some()); + match again { + Ok(_) => again, + Err(_) => emit_program(c, native, p, st, io, res), + } + } + other => other, + }; + let original = original.map(|(shader, _)| shader); + // Retry unsupported programs only. Threading can separate an unknown + // register value from its apparent use on a mutually exclusive path. + if !matches!(original, Err(ShaderError::Unsupported { .. })) { + return original; + } + let edges = threading::constant_edges(p, st); + if edges.is_empty() { + return original; + } + let p = ir::thread_edges(p, &edges)?; + let st = structure::structure(&p)?; + let io = io::raise(&p, native)?; + let res = resource::track(&p, &native.layout, native.stage, Some(&st))?; + emit_program(c, native, &p, &st, &io, &res).map(|(shader, _)| shader) +} + +/// `p` (a console wave64 compute program on a host of 32-lane waves) with the per-lane +/// branches around its cross-lane code taken wave-wide ([`structure::structure_wide`]): the +/// lowering names the blocks where the two host waves must meet and could not +/// (`lower::take_needs`), the branches whose regions hold them are widened, and so on until +/// it translates or a branch cannot be widened. Only where a thread group is one console +/// wave: with several, the waves of a group would decide differently and a barrier inside +/// such a branch would wait for threads that never come. +fn widen( + c: &Container, + native: &NativeProgram, + p: &ir::Program, + why: bool, +) -> Result<(HostShader, Option), ShaderError> { + const NOT: ShaderError = ShaderError::Unsupported { + offset: 0, + what: "wave-wide branches in a thread group of several console waves", + }; + match native.io { + // (a program whose waves are the host's meets no one: no barrier, any group) + crate::native::StageIo::Cs(_) if !(native.wave64 && lower::host_max_wave() == 32) => {} + crate::native::StageIo::Cs(cs) if cs.threads.iter().product::() == 64 => {} + crate::native::StageIo::Cs(cs) => { + if why { + eprintln!("WAVE64-WIDE not tried: thread groups of {:?}", cs.threads); + } + return Err(NOT); + } + _ => return Err(NOT), + } + let mut wide = std::collections::HashSet::new(); + loop { + let st = structure::structure_wide(p, &wide)?; + let io = io::raise(p, native)?; + let res = resource::track(p, &native.layout, native.stage, Some(&st))?; + lower::take_needs(); + let r = emit_program(c, native, p, &st, &io, &res); + let needs = lower::take_needs(); + // (or translated for 64-lane waves still: shared memory read and written where not + // every lane runs, whose blocks the lowering names too) + let stuck = matches!(&r, Err(ShaderError::Unsupported { what, .. }) + if lower::needs_every_lane(what) || *what == lower::LANE_MASK && !needs.is_empty()) + || matches!(&r, Ok((_, Some(64)))) && !needs.is_empty(); + if !stuck { + if why { + eprintln!("WAVE64-WIDE {} branches taken wave-wide", wide.len()); + } + return r; + } + let more: Vec = lower::branches_around(&st, &needs) + .unwrap_or_default() + .into_iter() + .filter(|b| !wide.contains(b)) + .collect(); + if more.is_empty() { + if why { + eprintln!("WAVE64-WIDE stopped with {} branches wave-wide: a branch around it cannot be", wide.len()); + } + return r; + } + wide.extend(more); + } +} + +/// The translated program, and the wave size it requires of the host. +fn emit_program( + c: &Container, + native: &NativeProgram, + p: &ir::Program, + st: &structure::Structured, + io: &io::Io, + res: &resource::Resources, +) -> Result<(HostShader, Option), ShaderError> { + let sig = |fourcc| -> Result, ShaderError> { + match c.part(fourcc) { + Some(part) => signature(part.data), + None => Ok(Vec::new()), + } + }; + let pixel = native.stage == HwStage::Ps; + let mut inputs = sig(FourCC::ISG1)?; + let mut outputs = sig(FourCC::OSG1)?; + // Interpolation as DXC declares it by default; pixel inputs that are + // read get the mode their barycentrics say. + let interpolated = if pixel { &mut inputs } else { &mut outputs }; + for e in interpolated { + e.interp = match (e.kind, e.comp) { + (3, _) => 4, + // Constant, as DXC declares it (the AMD compiler crashed on a + // front face without a mode). + (13, _) => 1, + // Until a read says which mode (`lower`). + (28, _) => 2, + (0 | 6 | 7, 9) => 2, + (0, _) => 1, + _ => 0, + }; + } + // With a conservative depth output (SV_DepthLessEqual, GreaterEqual) DXIL + // wants the position centroid (or per sample), as DXC declares it then. + if pixel && outputs.iter().any(|e| matches!(e.kind, 18 | 19)) { + for e in inputs.iter_mut().filter(|e| e.kind == 3) { + e.interp = 5; + } + } + // Per-primitive outputs are constant. The console never exports a + // primitive id or cull flag a mesh shader writes (it culls with the + // primitive export), so those rows are left out. + let mut prims = sig(FourCC::PSG1)?; + prims.retain(|e| !matches!(e.kind, 10 | 30)); + for e in &mut prims { + e.interp = 1; + } + // A mesh group's id arrives multiplied by max(threads, vertices, + // primitives) (the code divides by that); the thread count is in PSV0 + // from runtime info version 2 on. + // shortcut: older containers fall back to the group's lane count, right + // when the HLSL group fills its waves (the title's do). + let mesh_stride = match &native.io { + crate::native::StageIo::Ms(ms) => { + let psv = c.part(FourCC::PSV0).map(|p| p.data); + let threads = psv + .filter(|d| crate::dxbc::u32_at(d, 0).is_ok_and(|n| n >= 48)) + .and_then(|d| crate::dxbc::u32_at(d, 4 + 36).ok()); + threads.map_or(ms.threads, |t| { + t.max(ms.max_vertices).max(ms.max_primitives) + }) + } + _ => 0, + }; + let l = lower::lower(&lower::Parts { + native, + p, + st, + io, + res, + inputs, + outputs, + prims, + mesh_stride, + })?; + let wave_size = l.wave_size; + let shader = HostShader { + stage: native.stage, + dxil: l.dxil, + user_data: l.user_data, + static_samplers: l + .samplers + .iter() + .enumerate() + .map(|(n, &w)| { + let mut s = StaticSampler::from_words(w); + if l.cmp_samplers >> n & 1 != 0 { + s.filter |= 0x80; + } + s + }) + .collect(), + samplers: l.samplers, + root_cbvs: l.root_cbvs, + root_srvs: l.root_srvs, + root_uavs: l.root_uavs, + root_indexed_views: res.root_indexed_views.clone(), + }; + Ok((shader, wave_size)) +} + +/// The rows of an `ISG1`/`OSG1` part. +fn signature(part: &[u8]) -> Result, ShaderError> { + use crate::dxbc::u32_at; + let count = u32_at(part, 0)? as usize; + let base = u32_at(part, 4)? as usize; + let mut out = Vec::with_capacity(count); + for i in 0..count { + let at = base + 32 * i; + let name_at = u32_at(part, at + 4)? as usize; + let name = part + .get(name_at..) + .and_then(|s| s.split(|&b| b == 0).next()) + .ok_or(ShaderError::Malformed("signature name out of bounds"))?; + let mask = *part + .get(at + 24) + .ok_or(ShaderError::Malformed("truncated"))?; + if u32_at(part, at + 28)? != 0 { + return Err(ShaderError::Unsupported { + offset: 0, + what: "a minimum-precision signature element", + }); + } + if u32_at(part, at)? != 0 { + return Err(ShaderError::Unsupported { + offset: 0, + what: "a signature element of another stream", + }); + } + let kind = match u32_at(part, at + 12)? { + 0 => 0, + 1 => 3, + 2 => 6, + 3 => 7, + 4 => 4, + 5 => 5, + 6 => 1, + 7 => 10, + 8 => 2, + 9 => 13, + 10 => 12, + 64 => 16, + 65 => 17, + 66 => 14, + 67 => 19, + 68 => 18, + 69 => 20, + 70 => 15, + 23 => 28, // barycentrics + 25 => 30, // cull primitive + _ => { + return Err(ShaderError::Unsupported { + offset: 0, + what: "a system value in the signature", + }); + } + }; + // 16-bit elements are declared 32-bit; reading or writing one + // converts (16-bit values travel packed on the console). + let raw = u32_at(part, at + 16)?; + let comp = match (kind, raw) { + // DXIL declares the front face a uint (the validator insists). + (13, _) => 5, + (_, 1 | 4) => 5, + (_, 2 | 5) => 4, + (_, 3 | 6) => 9, + (_, c) => { + return Err(ShaderError::Unsupported { + offset: 0, + what: match c { + 0 => "a signature element of unknown type", + _ => "a 64-bit signature element", + }, + }); + } + }; + let register = u32_at(part, at + 20)?; + out.push(container::SigElement { + name: String::from_utf8_lossy(name).into_owned(), + index: u32_at(part, at + 8)?, + kind, + comp, + interp: 0, + row: (register != u32::MAX).then_some(register), + col: mask.trailing_zeros().min(3) as u8, + cols: mask.count_ones().max(1) as u8, + usage: 0, + half: (4..=6).contains(&raw), + }); + } + Ok(out) +} + +#[cfg(test)] +mod tests { + use super::bitcode::Attr; + use super::lower::LOOP_LIMIT; + use super::parse_loop_limit; + + #[test] + fn the_clean_up_switch_parses_or_runs_every_pass() { + let all = super::bitcode::opt::ALL; + assert_eq!(parse_shader_opt(None), all); + assert_eq!(parse_shader_opt(Some("0")), 0); + assert_eq!(parse_shader_opt(Some(" 1 ")), 1); + assert_eq!(parse_shader_opt(Some("0x1")), 1); + assert_eq!(parse_shader_opt(Some("0xffffffff")), all); + assert_eq!(parse_shader_opt(Some("on")), all); + } + + #[test] + fn the_loop_limit_switch_parses_or_falls_back() { + assert_eq!(parse_loop_limit(None), LOOP_LIMIT); + assert_eq!(parse_loop_limit(Some("4096")), 4096); + assert_eq!(parse_loop_limit(Some(" 0x1000 ")), 4096); + assert_eq!(parse_loop_limit(Some("1")), 1); + for bad in ["", "0", "-5", "lots", "0x", "4294967296"] { + assert_eq!(parse_loop_limit(Some(bad)), LOOP_LIMIT, "{bad:?}"); + } + } + use super::container::SigElement; + use super::shader::Shader; + use super::*; + use crate::native::{ComputeIo, StageIo}; + + /// A pixel shader writing SV_StencilRef (channel y of `exp mrtz`). + /// DXC sets ShaderFlags.StencilRef (bit 11) for a pixel shader whose + /// output signature has SV_StencilRef, and the feature bit + /// D3D_SHADER_FEATURE_STENCIL_REF (0x200) in SFI0; the validator checks + /// both against the module. + #[test] + fn a_stencil_export_declares_the_stencil_ref_feature() { + let words = [ + 0x7E00_02F2u32, // v_mov_b32 v0, 1.0 + 0x7E02_0285, // v_mov_b32 v1, 5 + 0xF800_1883, + 0x0000_0100, // exp mrtz v0, v1, off, off done vm + 0xBF81_0000, + ]; + let native = NativeProgram { + stage: HwStage::Ps, + wave64: false, + vgprs: 2, + layout: vec![], + used: vec![], + io: StageIo::Ps { + inputs: vec![], + input_addr: 0, + db_shader_control: 0, + patches: vec![], + }, + code: words.iter().flat_map(|w| w.to_le_bytes()).collect(), + }; + let el = |name: &str, kind, comp| SigElement { + name: name.into(), + index: 0, + kind, + comp, + interp: 0, + row: None, + col: 0, + cols: 1, + usage: 1, + half: false, + }; + let osg1 = + container::signature(&[el("SV_Depth", 17, 9), el("SV_StencilRef", 20, 5)], false); + let bytes = crate::dxbc::build(&[(FourCC::OSG1, &osg1)]); + let c = Container::parse(&bytes).unwrap(); + let p = ir::build(&native.patched_code(), native.wave64, native.vgprs).unwrap(); + let st = structure::structure(&p).unwrap(); + let res = resource::track(&p, &native.layout, native.stage, Some(&st)).unwrap(); + let io = io::raise(&p, &native).unwrap(); + let out = emit(&c, &native, &p, &st, &io, &res).unwrap(); + // dxil.dll, where there is one, checks the flags against the module. + #[cfg(windows)] + if let Ok(mut v) = super::validator::Validator::load( + super::validator::Validator::default_path().as_deref(), + ) { + v.validate(&mut out.dxil.clone()).unwrap(); + } + let host = Container::parse(&out.dxil).unwrap(); + let sfi0 = host.part(FourCC::SFI0).unwrap().data; + let features = u64::from_le_bytes(sfi0.try_into().unwrap()); + assert_ne!(features & 0x200, 0, "SFI0 {features:#x}: no StencilRef"); + } + + /// A wave64 compute program that writes only EXEC's high dword + /// (`s_mov_b32 exec_hi, 0`) before a vector instruction. The new mask was + /// opaque and keyed by the unchanged low dword, so building its lane bit + /// needed the mask's own value: lowering recursed until the stack + /// overflowed, which takes the whole process down (found by + /// random-input testing). Now that low dword, seen with two high + /// dwords, has no mask, and the instruction fails like any other that + /// cannot be expressed: its result is missing, and only a side effect + /// that uses it would stop the translation. + #[test] + fn an_exec_high_write_does_not_overflow_the_stack() { + // s_mov_b32 exec_hi, 0; v_mov_b32 v1, v0; s_endpgm + let words = [0xBEFF_0380u32, 0x7E02_0300, 0xBF81_0000]; + let native = NativeProgram { + stage: HwStage::Cs, + wave64: true, + vgprs: 2, + layout: vec![], + used: vec![], + io: StageIo::Cs(ComputeIo { + rsrc2: 0, + threads: [64, 1, 1], + }), + code: words.iter().flat_map(|w| w.to_le_bytes()).collect(), + }; + let p = ir::build(&native.patched_code(), native.wave64, native.vgprs).unwrap(); + let st = structure::structure(&p).unwrap(); + let res = resource::track(&p, &native.layout, native.stage, Some(&st)).unwrap(); + let io = io::raise(&p, &native).unwrap(); + let container = crate::dxbc::build(&[]); + let c = Container::parse(&container).unwrap(); + if let Err(e) = emit(&c, &native, &p, &st, &io, &res) { + assert!(e.to_string().contains("its own value"), "{e}"); + } + } + + /// A wave64 compute program: `body`, then a store of v1 to a UAV. + fn stores_v1(body: &[u32]) -> Result<(), ShaderError> { + use crate::native::RootParam; + use crate::{ResourceType, RootType, UsedResource}; + // s_mov_b32 s1, 0; s_load_dwordx4 s[8:11], s[0:1], 0 + let mut words = vec![0xBE81_0380, 0xF408_0200, 0xFA00_0000]; + words.extend_from_slice(body); + // v_lshlrev_b32 v3, 2, v0; buffer_store_dword v1, v3, s[8:11], 0 offen; + // s_endpgm + words.extend_from_slice(&[0x3406_0082, 0xE070_1000, 0x8002_0103, 0xBF81_0000]); + let native = NativeProgram { + stage: HwStage::Cs, + wave64: true, + vgprs: 4, + layout: vec![RootParam { + root: RootType::Table, + table_offset_dwords: 0, + sgprs: 1, + base_register: 0, + user_data: 0, + slot: 0, + }], + used: vec![UsedResource { + kind: ResourceType::Uav, + root: RootType::Table, + table_offset_dwords: 0, + lower_bound: 0, + stride: 0, + dwords: 4, + user_data: 0, + slot: 0, + }], + io: StageIo::Cs(ComputeIo { + rsrc2: 2, + threads: [64, 1, 1], + }), + code: words.iter().flat_map(|w| w.to_le_bytes()).collect(), + }; + let p = ir::build(&native.patched_code(), native.wave64, native.vgprs).unwrap(); + let res = resource::track(&p, &native.layout, native.stage, None).unwrap(); + let io = io::raise(&p, &native).unwrap(); + let st = structure::structure(&p).unwrap(); + let container = crate::dxbc::build(&[]); + let c = Container::parse(&container).unwrap(); + emit(&c, &native, &p, &st, &io, &res).map(|_| ()) + } + + /// The high dword of a wave64 mask rewritten alone (`s_mov_b32 vcc_hi` + /// or `exec_hi`): lanes 32-63 took the mask the low dword was first + /// written with (the compare's, EXEC's on entry). Now the store refuses; + /// without the write it translates. + #[test] + fn a_mask_whose_high_dword_is_rewritten_is_refused() { + // v_cmp_eq_u32 vcc, 0, v0; v_mov_b32 v2, 11; v_cndmask_b32 v1, 0, v2, vcc + let select = [0x7D84_0080, 0x7E04_028B, 0x0202_0480]; + // The same with v_add_co_ci_u32 v1, vcc, 0, v2, vcc. + let carry = [0x7D84_0080, 0x7E04_028B, 0x5002_0480]; + // v_mov_b32 v1, 7 + let mov = [0x7E02_0287]; + for body in [&select[..], &carry, &mov] { + stores_v1(body).unwrap(); + } + // s_mov_b32 vcc_hi, 0 after the compare. + let select_hi = [0x7D84_0080, 0xBEEB_0380, 0x7E04_028B, 0x0202_0480]; + let carry_hi = [0x7D84_0080, 0xBEEB_0380, 0x7E04_028B, 0x5002_0480]; + // s_mov_b32 exec_hi, 0; v_mov_b32 v1, 7, then the same after + // s_mov_b64 s[2:3], exec. + let exec_hi = [0xBEFF_0380, 0x7E02_0287]; + let exec_hi_saved = [0xBE82_047E, 0xBEFF_0380, 0x7E02_0287]; + for body in [&select_hi[..], &carry_hi, &exec_hi, &exec_hi_saved] { + assert!(stores_v1(body).is_err(), "{body:x?}"); + } + } + + /// `ds_bpermute_b32` stores nothing: each lane reads the lane its address + /// names. It stopped as "LDS the program does not allocate" (sticky lips) + /// or "an LDS operation" (the checkerboard shadow masks). + #[test] + fn a_backward_permute_reads_the_lane_its_address_names() { + // v_mov_b32 v2, 11; ds_bpermute_b32 v1, v0, v2 + stores_v1(&[0x7E04_028B, 0xDACC_0000, 0x0100_0200]).unwrap(); + } + + /// A carry-in reading a join of compares after a divergent branch. A + /// lane that skipped the inner compare has VCC clear there (VOPC clears + /// inactive lanes), not the first compare's bit, so the join is no + /// per-lane phi: lowering refuses it. + #[test] + fn a_carry_in_from_a_divergent_join_is_refused() { + let body = [ + 0x7E04_028B, // v_mov_b32 v2, 11 + 0x7D84_0080, // v_cmp_eq_u32 vcc, 0, v0 + 0xBE82_376A, // s_andn1_saveexec_b64 s[2:3], vcc + 0xBF88_0001, // s_cbranch_execz 1 + 0x7D84_0081, // v_cmp_eq_u32 vcc, 1, v0 + 0x88FE_027E, // s_or_b64 exec, exec, s[2:3] + 0x5002_0480, // v_add_co_ci_u32 v1, vcc, 0, v2, vcc + ]; + let e = stores_v1(&body).unwrap_err().to_string(); + assert!(e.contains("a carry-in from an untracked mask"), "{e}"); + } + + /// A pixel shader writing a constant colour. + #[cfg(windows)] + fn constant_color() -> Vec { + let mut s = Shader::new(true); + s.outputs.push(SigElement { + name: "SV_Target".into(), + index: 0, + kind: 16, + comp: 9, + interp: 0, + row: Some(0), + col: 0, + cols: 4, + usage: 15, + half: false, + }); + let b = s.entry; + for (c, v) in [1.0f32, 0.5, 0.25, 1.0].into_iter().enumerate() { + let args = [ + s.m.i32(0), + s.m.i32(0), + s.m.i8(c as u8), + s.m.f32(v.to_bits()), + ]; + s.op(b, "storeOutput.f32", Attr::NoUnwind, s.t.void, 5, &args); + } + s.m.terminate(b, super::bitcode::Term::Ret); + s.finish() + } + + #[test] + #[cfg(windows)] + fn stub_pipeline_is_created() { + let Ok(host) = super::host::Host::new(false) else { + eprintln!("no SM 6.6 device; skipped"); + return; + }; + let ps = super::HostShader { + stage: crate::HwStage::Ps, + dxil: constant_color(), + 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(), + }; + let file = |var: &str, stage| { + std::env::var(var).ok().map(|p| super::HostShader { + stage, + dxil: std::fs::read(p).unwrap(), + 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(), + }) + }; + let ps = file("LEONIDA_REF_PS", crate::HwStage::Ps).unwrap_or(ps); + let vs = file("LEONIDA_REF_VS", crate::HwStage::Vs) + .unwrap_or_else(|| super::host::stub_vs(&ps).unwrap()); + if let Ok(mut v) = super::validator::Validator::load( + super::validator::Validator::default_path().as_deref(), + ) { + v.validate(&mut vs.dxil.clone()).unwrap(); + } + host.pipeline(&vs, &ps).unwrap(); + // The runtime checks the container hash: no hash or a wrong one is + // refused. (Recent runtimes also take sixteen 0x01 bytes, a bypass + // value; ours works with older ones too.) + let mut wrong = ps.dxil[4..20].to_vec(); + wrong[0] ^= 1; + for digest in [&[0u8; 16][..], &wrong] { + let mut other = ps.clone(); + other.dxil[4..20].copy_from_slice(digest); + assert!( + host.pipeline(&vs, &other).is_err(), + "digest {digest:02x?} accepted" + ); + } + } + + #[test] + #[cfg(windows)] + fn constant_color_validates() { + let mut c = constant_color(); + let path = super::validator::Validator::default_path(); + let Ok(mut v) = super::validator::Validator::load(path.as_deref()) else { + eprintln!("no dxil.dll; skipped"); + return; + }; + let ours = c[4..20].to_vec(); + v.validate(&mut c).unwrap(); + assert_eq!(c[4..20], ours[..], "our hash differs from the validator's"); + } + + /// A pixel shader interpolating at sample positions (PERSP_SAMPLE + /// barycentrics, `SPI_PS_INPUT_ADDR` bit 0) runs at sample frequency: + /// DXC's PSV0 says so in PSInfo.SampleFrequency (runtime info byte 1) + /// whenever an input is interpolated per sample. + #[test] + fn sample_interpolated_inputs_set_psv_sample_frequency() { + let words = [ + 0xC808_0000u32, // v_interp_p1_f32 v2, v0, attr0.x + 0xC809_0001, // v_interp_p2_f32 v2, v1, attr0.x + 0xF800_180F, + 0x0202_0202, // exp mrt0, v2, v2, v2, v2 done vm + 0xBF81_0000, + ]; + let psv_of = |input_addr: u32| { + let native = super::NativeProgram { + stage: super::HwStage::Ps, + wave64: false, + vgprs: 4, + layout: vec![], + used: vec![], + io: crate::native::StageIo::Ps { + inputs: vec![crate::native::PsInput { + usage: crate::native::Usage::Generic, + row: 0, + mask: 0b1111, + attr: 0, + flat: false, + fp16: false, + pack2: false, + row2: 0, + }], + input_addr, + db_shader_control: 0, + patches: vec![], + }, + code: words.iter().flat_map(|w| w.to_le_bytes()).collect(), + }; + let el = |name: &str, kind, usage| SigElement { + name: name.into(), + index: 0, + kind, + comp: 9, + interp: 0, + row: Some(0), + col: 0, + cols: 4, + usage, + half: false, + }; + let isg1 = super::container::signature(&[el("TEXCOORD", 0, 0)], true); + let osg1 = super::container::signature(&[el("SV_Target", 16, 15)], false); + let bytes = + crate::dxbc::build(&[(super::FourCC::ISG1, &isg1), (super::FourCC::OSG1, &osg1)]); + let c = super::Container::parse(&bytes).unwrap(); + let p = crate::ir::build(&native.patched_code(), native.wave64, native.vgprs).unwrap(); + let st = crate::structure::structure(&p).unwrap(); + let res = + crate::resource::track(&p, &native.layout, native.stage, Some(&st)).unwrap(); + let io = crate::io::raise(&p, &native).unwrap(); + let out = super::emit(&c, &native, &p, &st, &io, &res).unwrap(); + // dxil.dll, where there is one, checks PSV0 against the module. + #[cfg(windows)] + if let Ok(mut v) = super::validator::Validator::load( + super::validator::Validator::default_path().as_deref(), + ) { + v.validate(&mut out.dxil.clone()).unwrap(); + } + let host = super::Container::parse(&out.dxil).unwrap(); + host.part(super::FourCC::PSV0).unwrap().data.to_vec() + }; + // Runtime info starts after its size; PSInfo is {DepthOutput, SampleFrequency}. + let center = psv_of(1 << 1); + assert_eq!(center[4 + 1], 0, "center interpolation is per pixel"); + let sample = psv_of(1 << 0); + assert_eq!(sample[4 + 1], 1, "PSInfo.SampleFrequency"); + } + + /// A pixel shader reading channel z of an input whose element starts at + /// w. Looking the channel up subtracted the element's first channel + /// before checking the channel lies in it, so in a build with overflow + /// checks (tests, debug) any read below an element that starts at z or + /// w panicked, whichever row it was in (found by random-input testing). + #[test] + fn reading_a_channel_below_an_input_element_does_not_underflow() { + // v_interp_mov_f32 v3, p0, attr0.z; s_endpgm + let words = [0xC80E_0202u32, 0xBF81_0000]; + let native = super::NativeProgram { + stage: super::HwStage::Ps, + wave64: false, + vgprs: 4, + layout: vec![], + used: vec![], + io: crate::native::StageIo::Ps { + inputs: vec![crate::native::PsInput { + usage: crate::native::Usage::Generic, + row: 0, + mask: 0b1000, + attr: 0, + flat: false, + fp16: false, + pack2: false, + row2: 0, + }], + input_addr: 0, + db_shader_control: 0, + patches: vec![], + }, + code: words.iter().flat_map(|w| w.to_le_bytes()).collect(), + }; + let w_only = SigElement { + name: "TEXCOORD".into(), + index: 0, + kind: 0, + comp: 9, + interp: 0, + row: Some(0), + col: 3, + cols: 1, + usage: 0, + half: false, + }; + let isg1 = super::container::signature(&[w_only], true); + let bytes = crate::dxbc::build(&[(super::FourCC::ISG1, &isg1)]); + let c = super::Container::parse(&bytes).unwrap(); + let p = crate::ir::build(&native.patched_code(), native.wave64, native.vgprs).unwrap(); + let st = crate::structure::structure(&p).unwrap(); + let res = crate::resource::track(&p, &native.layout, native.stage, Some(&st)).unwrap(); + let io = crate::io::raise(&p, &native).unwrap(); + // Translated or refused with a reason; it must not panic. + let _ = super::emit(&c, &native, &p, &st, &io, &res); + } + + #[test] + fn valu_div_f32_sequence_executes_on_gpu() { + let words: &[u32] = &[ + 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 + 0x340E_0083, // v_lshlrev_b32 v7, 3, v0 + 0xE034_1000, + 0x8002_0107, // buffer_load_dwordx2 v[1:2], v7, s[8:11], 0 offen + 0xD56D_6A03, + 0x0406_0502, // v_div_scale_f32 v3, vcc_lo, v2, v2, v1 + 0xD56D_1008, + 0x0406_0501, // v_div_scale_f32 v8, s16, v1, v2, v1 + 0x7E08_5503, // v_rcp_f32 v4, v3 + 0xD54B_0005, + 0x23CA_0903, // v_fma_f32 v5, -v3, v4, 1.0 + 0xD54B_0004, + 0x0412_0905, // v_fma_f32 v4, v5, v4, v4 + 0x100A_0908, // v_mul_f32 v5, v8, v4 + 0xD54B_0006, + 0x2422_0B03, // v_fma_f32 v6, -v3, v5, v8 + 0xD56F_0004, + 0x0416_0906, // v_div_fmas_f32 v4, v6, v4, v5 + 0xD55F_0001, + 0x0406_0504, // v_div_fixup_f32 v1, v4, v2, v1 + 0x340E_0082, // v_lshlrev_b32 v7, 2, v0 + 0xE070_1000, + 0x8003_0107, // buffer_store_dword v1, v7, s[12:15], 0 offen + 0xBF81_0000, // s_endpgm + ]; + let native = super::NativeProgram { + stage: super::HwStage::Cs, + wave64: false, + vgprs: 9, + layout: vec![ + crate::RootParam { + root: crate::RootType::Constants, + table_offset_dwords: 0, + sgprs: 4, + base_register: 0, + user_data: 0, + slot: 0, + }, + crate::RootParam { + root: crate::RootType::Table, + table_offset_dwords: 0, + sgprs: 1, + base_register: 0, + user_data: 4, + slot: 1, + }, + ], + used: vec![ + crate::UsedResource { + kind: crate::ResourceType::Srv, + root: crate::RootType::Table, + table_offset_dwords: 0, + lower_bound: 0, + stride: 4, + dwords: 4, + user_data: 4, + slot: 1, + }, + crate::UsedResource { + kind: crate::ResourceType::Uav, + root: crate::RootType::Table, + table_offset_dwords: 8, + lower_bound: 0, + stride: 4, + dwords: 4, + user_data: 4, + slot: 1, + }, + ], + io: crate::native::StageIo::Cs(crate::native::ComputeIo { + rsrc2: 5 << 1, + threads: [7, 1, 1], + }), + code: words.iter().flat_map(|w| w.to_le_bytes()).collect(), + }; + let p = crate::ir::build(&native.code, native.wave64, native.vgprs).unwrap(); + let res = crate::resource::track(&p, &native.layout, native.stage, None).unwrap(); + let io = crate::io::raise(&p, &native).unwrap(); + let st = crate::structure::structure(&p).unwrap(); + let l = super::lower::lower(&super::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(); + let mut dxil = l.dxil; + #[cfg(windows)] + if let Ok(mut v) = super::validator::Validator::load( + super::validator::Validator::default_path().as_deref(), + ) { + v.validate(&mut dxil).unwrap(); + } + #[cfg(windows)] + if let Ok(host) = super::host::Host::new(false) { + let cs = super::HostShader { + stage: super::HwStage::Cs, + dxil, + user_data: l.user_data, + samplers: Vec::new(), + static_samplers: Vec::new(), + root_cbvs: l.root_cbvs, + root_srvs: l.root_srvs, + root_uavs: l.root_uavs, + root_indexed_views: Vec::new(), + }; + let (root, pso) = host.compute_pipeline(&cs).unwrap(); + let inputs: Vec = [ + 7.0f32, 3.0, -1.0, 1e-40, 1.0, 1e35, 1e-35, 1e-36, 0.0, 0.0, -1.0, 0.0, -1e35, 1e35, + ] + .into_iter() + .map(f32::to_bits) + .collect(); + let out = host + .dispatch( + &root, + &pso, + &super::host::Dispatch { + roots: vec![(0, super::host::Root::Constants(vec![0, 0, 0, 0, 0]))], + views: &[ + super::host::View::Buffer { + data: &inputs, + stride: super::host::Stride::Raw, + }, + super::host::View::RawUav(64), + ], + samplers: &[], + groups: [1, 1, 1], + }, + ) + .unwrap(); + let got: Vec = out[0][..7].iter().copied().map(f32::from_bits).collect(); + assert!((got[0] - (7.0f32 / 3.0)).abs() < 1e-6, "got {:?}", got); + assert_eq!(out[0][1], (-1.0f32 / 1e-40).to_bits()); + assert!( + (got[2] - 1e-35).abs() <= 1e-40, + "lane 2 got {:?} ({:#x})", + got[2], + out[0][2] + ); + assert!( + (got[3] - 10.0).abs() < 1e-5, + "lane 3 got {:?} ({:#x})", + got[3], + out[0][3] + ); + assert_eq!(out[0][4], 0xFFC0_0000); + assert_eq!(out[0][5], (-1.0f32 / 0.0).to_bits()); + assert!( + (got[6] - (-1.0)).abs() < 1e-6, + "lane 6 got {:?} ({:#x})", + got[6], + out[0][6] + ); + } + } +} + +#[cfg(test)] +mod atomic_tests { + use super::*; + use crate::native::{ComputeIo, RootParam, StageIo}; + + #[test] + fn heap_texture_atomic_widths() { + // A synthetic compute shader loads a 2D UAV from a root table, + // compares or adds at (0, 0), then uses the returned register(s). + for (opcode, mask, wide) in [ + (16u32, 3, false), + (16, 15, true), + (17, 1, false), + (17, 3, true), + ] { + let words = [ + 0xBE81_0380, // s_mov_b32 s1, 0 (table address high) + 0xF40C_0200, + 0xFA00_0000, // s_load_dwordx8 s[8:15], s[0:1], 0 + 0x7E00_0280, + 0x7E02_0280, // v0, v1 = coordinates + 0x7E04_0281, + 0x7E06_0282, + 0x7E08_0283, + 0x7E0A_0284, // v2..v5 = 1..4 + 0xF000_2008 | opcode << 18 | mask << 8, + 0x0002_0200, + // Use the old value in a second atomic at the same location. + 0xF044_0008 | (if wide { 3 } else { 1 }) << 8, + 0x0002_0200, + 0xBF81_0000, + ]; + let native = NativeProgram { + stage: HwStage::Cs, + wave64: false, + vgprs: 6, + layout: vec![RootParam { + root: RootType::Table, + table_offset_dwords: 0, + sgprs: 1, + base_register: 0, + user_data: 0, + slot: 0, + }], + used: vec![], + io: StageIo::Cs(ComputeIo { + rsrc2: 2, + threads: [32, 1, 1], + }), + code: words.iter().flat_map(|w| w.to_le_bytes()).collect(), + }; + let p = ir::build(&native.code, false, native.vgprs).unwrap(); + let bytes = crate::dxbc::build(&[]); + let shader = emit( + &Container::parse(&bytes).unwrap(), + &native, + &p, + &structure::structure(&p).unwrap(), + &io::raise(&p, &native).unwrap(), + &resource::track(&p, &native.layout, native.stage, None).unwrap(), + ) + .unwrap(); + let container = Container::parse(&shader.dxil).unwrap(); + let features = u64::from_le_bytes( + container + .part(FourCC::SFI0) + .unwrap() + .data + .try_into() + .unwrap(), + ); + let required = 0x1040_8000; // heap atomics, typed atomics, Int64Ops + assert_eq!(features & required, if wide { required } else { 0 }); + #[cfg(windows)] + if let Ok(mut v) = + validator::Validator::load(validator::Validator::default_path().as_deref()) + { + v.validate(&mut shader.dxil.clone()).unwrap(); + } + } + } +} + +#[cfg(test)] +mod barycentric_tests { + use super::container::SigElement; + use super::*; + use crate::native::{PsInput, StageIo, Usage}; + + /// `SPI_PS_INPUT_ADDR` bits: PERSP_CENTER, LINEAR_CENTER. + const PERSP_CENTER: u32 = 1 << 1; + const LINEAR_CENTER: u32 = 1 << 5; + + /// `exp mrt0, v, v, v, v done vm`. + fn exp_mrt0(r: u32) -> [u32; 2] { + [0xF800_180F, r * 0x0101_0101] + } + + /// VOP2 `v_add_f32 v, v, v`. + fn v_add_f32(dst: u32, a: u32, b: u32) -> u32 { + 3 << 25 | dst << 17 | b << 9 | (256 + a) + } + + fn element(name: &str, kind: u8, row: u32) -> SigElement { + SigElement { + name: name.into(), + index: 0, + kind, + comp: 9, + interp: 0, + row: Some(row), + col: 0, + cols: 4, + usage: 0, + half: false, + } + } + + /// Translates a pixel program with the input VGPRs `input_addr` + /// enables and one float4 TEXCOORD0 attribute (attr 0, row 0). + fn pixel(words: &[u32], input_addr: u32) -> Result { + let native = NativeProgram { + stage: HwStage::Ps, + wave64: false, + vgprs: 8, + layout: vec![], + used: vec![], + io: StageIo::Ps { + inputs: vec![PsInput { + usage: Usage::Generic, + row: 0, + mask: 0b1111, + attr: 0, + flat: false, + fp16: false, + pack2: false, + row2: 0, + }], + input_addr, + db_shader_control: 0, + patches: vec![], + }, + code: words.iter().flat_map(|w| w.to_le_bytes()).collect(), + }; + let mut target = element("SV_Target", 16, 0); + target.usage = 15; + let isg1 = container::signature(&[element("TEXCOORD", 0, 0)], true); + let osg1 = container::signature(&[target], false); + let bytes = crate::dxbc::build(&[(FourCC::ISG1, &isg1), (FourCC::OSG1, &osg1)]); + let c = Container::parse(&bytes).unwrap(); + let p = ir::build(&native.patched_code(), native.wave64, native.vgprs)?; + let res = resource::track(&p, &native.layout, native.stage, None)?; + let io = io::raise(&p, &native)?; + let st = structure::structure(&p)?; + emit(&c, &native, &p, &st, &io, &res) + } + + /// The translation's `SFI0` features and `ISG1` rows. + fn parts(shader: &HostShader) -> (u64, Vec) { + let c = Container::parse(&shader.dxil).unwrap(); + let sfi0 = c.part(FourCC::SFI0).unwrap().data.try_into().unwrap(); + ( + u64::from_le_bytes(sfi0), + signature(c.part(FourCC::ISG1).unwrap().data).unwrap(), + ) + } + + fn validate(shader: &HostShader) { + #[cfg(windows)] + if let Ok(mut v) = + validator::Validator::load(validator::Validator::default_path().as_deref()) + { + v.validate(&mut shader.dxil.clone()).unwrap(); + } + let _ = shader; + } + + /// Custom interpolation reads I and J (v0, v1 with PERSP_CENTER) as + /// plain floats: they are channels y and z of `SV_Barycentrics`, the + /// weights of vertices 1 and 2. + #[test] + fn barycentrics_read_as_values_are_sv_barycentrics() { + let [e0, e1] = exp_mrt0(2); + let words = [v_add_f32(2, 0, 1), e0, e1, 0xBF81_0000]; + let shader = pixel(&words, PERSP_CENTER).unwrap(); + let (features, inputs) = parts(&shader); + assert_ne!(features & 0x2_0000, 0, "no Barycentrics feature"); + let bary: Vec<_> = inputs.iter().filter(|e| e.kind == 28).collect(); + assert_eq!(bary.len(), 1, "{inputs:?}"); + assert_eq!((bary[0].index, bary[0].col, bary[0].cols), (0, 0, 3)); + // Not packed: the validator wants packing location -1. + assert_eq!(bary[0].row, None); + // Only y and z (I and J) are read. + let isg1 = Container::parse(&shader.dxil).unwrap(); + let isg1 = isg1.part(FourCC::ISG1).unwrap().data; + let rw: Vec = (0..2).map(|k| isg1[8 + 32 * k + 25]).collect(); + assert!(rw.contains(&0b110), "{rw:?}"); + validate(&shader); + } + + /// Two kinds of barycentrics read directly: one element per mode. + #[test] + fn two_barycentric_modes_get_two_elements() { + // v0-v1 perspective i, j; v2-v3 linear i, j. + let [e0, e1] = exp_mrt0(4); + let words = [v_add_f32(4, 0, 3), e0, e1, 0xBF81_0000]; + let shader = pixel(&words, PERSP_CENTER | LINEAR_CENTER).unwrap(); + let (_, inputs) = parts(&shader); + let mut indices: Vec = inputs + .iter() + .filter(|e| e.kind == 28) + .map(|e| e.index) + .collect(); + indices.sort(); + assert_eq!(indices, [0, 1], "{inputs:?}"); + validate(&shader); + } + + /// I and J only fed to `v_interp_*` stay host interpolation: no + /// barycentrics are declared. + #[test] + fn interpolation_alone_declares_no_barycentrics() { + let [e0, e1] = exp_mrt0(2); + let words = [ + 0xC808_0000, // v_interp_p1_f32 v2, v0, attr0.x + 0xC809_0001, // v_interp_p2_f32 v2, v1, attr0.x + e0, + e1, + 0xBF81_0000, + ]; + let shader = pixel(&words, PERSP_CENTER).unwrap(); + let (features, inputs) = parts(&shader); + assert_eq!(features & 0x2_0000, 0); + assert!(inputs.iter().all(|e| e.kind != 28), "{inputs:?}"); + validate(&shader); + } + + /// Both: the attribute is interpolated and J is used as a value. + #[test] + fn interpolation_and_a_barycentric_value_together() { + let [e0, e1] = exp_mrt0(3); + let words = [ + 0xC808_0000, // v_interp_p1_f32 v2, v0, attr0.x + 0xC809_0001, // v_interp_p2_f32 v2, v1, attr0.x + v_add_f32(3, 2, 1), // v3 = attribute + j + e0, + e1, + 0xBF81_0000, + ]; + let shader = pixel(&words, PERSP_CENTER).unwrap(); + let (features, inputs) = parts(&shader); + assert_ne!(features & 0x2_0000, 0); + assert_eq!(inputs.iter().filter(|e| e.kind == 28).count(), 1); + validate(&shader); + } + /// The `PSV0` interpolation mode of TEXCOORD0 (row 0, x-w, float). + fn texcoord_mode(shader: &HostShader) -> u8 { + let c = Container::parse(&shader.dxil).unwrap(); + let psv = c.part(FourCC::PSV0).unwrap().data; + let row = [1, 0, 0x44, 0, 3]; + let at = psv.windows(5).position(|w| w == row).unwrap(); + psv[at + 5] + } + + const S_ENDPGM: u32 = 0xBF81_0000; + + /// An interpolation whose i is computed (`v_mul_f32 v3, 0.5, v0`) reads + /// the attribute's vertices: TEXCOORD0 becomes constant, read with + /// `attributeAtVertex`; i and j are `SV_Barycentrics` values. + #[test] + fn computed_barycentrics_read_the_vertices() { + let [e0, e1] = exp_mrt0(2); + let words = [ + 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 + e0, + e1, + S_ENDPGM, + ]; + let shader = pixel(&words, PERSP_CENTER).unwrap(); + let (features, inputs) = parts(&shader); + assert_ne!(features & 0x2_0000, 0, "no Barycentrics feature"); + assert_eq!(inputs.iter().filter(|e| e.kind == 28).count(), 1); + assert_eq!(texcoord_mode(&shader), 1); + validate(&shader); + } + + /// Weights from constants alone: the vertices, no `SV_Barycentrics`. + #[test] + fn constant_weights_need_no_barycentrics() { + let [e0, e1] = exp_mrt0(2); + let words = [ + 0x7E06_02F0, // v_mov_b32 v3, 0.5 + 0xC808_0003, // v_interp_p1_f32 v2, v3, attr0.x + 0xC809_0003, // v_interp_p2_f32 v2, v3, attr0.x + e0, + e1, + S_ENDPGM, + ]; + let shader = pixel(&words, PERSP_CENTER).unwrap(); + let (features, inputs) = parts(&shader); + assert_ne!(features & 0x2_0000, 0, "no Barycentrics feature"); + assert!(inputs.iter().all(|e| e.kind != 28), "{inputs:?}"); + assert_eq!(texcoord_mode(&shader), 1); + validate(&shader); + } + + /// The same attribute interpolated with the loaded i and j and with a + /// computed j: both from its vertices, the first weighed with + /// `SV_Barycentrics`. + #[test] + fn computed_and_loaded_barycentrics_on_one_attribute() { + let [e0, e1] = exp_mrt0(2); + let words = [ + 0xC810_0100, // v_interp_p1_f32 v4, v0, attr0.y + 0xC811_0101, // v_interp_p2_f32 v4, v1, attr0.y + 0x1006_02F0, // v_mul_f32 v3, 0.5, v1 + 0xC808_0000, // v_interp_p1_f32 v2, v0, attr0.x + 0xC809_0003, // v_interp_p2_f32 v2, v3, attr0.x + v_add_f32(2, 2, 4), + e0, + e1, + S_ENDPGM, + ]; + let shader = pixel(&words, PERSP_CENTER).unwrap(); + let (_, inputs) = parts(&shader); + assert_eq!(inputs.iter().filter(|e| e.kind == 28).count(), 1); + assert_eq!(texcoord_mode(&shader), 1); + validate(&shader); + } + + /// P10 of an attribute the program interpolates is P1 - P0. + #[test] + fn p10_of_an_interpolated_attribute() { + let [e0, e1] = exp_mrt0(2); + let words = [ + 0xC808_0000, // v_interp_p1_f32 v2, v0, attr0.x + 0xC809_0001, // v_interp_p2_f32 v2, v1, attr0.x + 0xC812_0000, // v_interp_mov_f32 v4, p10, attr0.x + v_add_f32(2, 2, 4), + e0, + e1, + S_ENDPGM, + ]; + let shader = pixel(&words, PERSP_CENTER).unwrap(); + assert_eq!(texcoord_mode(&shader), 1); + validate(&shader); + // Alone, what the hardware holds is not known. + let [e0, e1] = exp_mrt0(4); + let words = [0xC812_0000, e0, e1, S_ENDPGM]; + assert!(pixel(&words, PERSP_CENTER).is_err()); + } +} diff --git a/crates/leonida-shader/src/emit/own_bits.rs b/crates/leonida-shader/src/emit/own_bits.rs new file mode 100644 index 000000000..3854666ff --- /dev/null +++ b/crates/leonida-shader/src/emit/own_bits.rs @@ -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. +//! `LEONIDA_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, + /// 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, +} + +#[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>, + /// The instruction writing each value. + def: HashMap, + /// Values an instruction reads, directly or through joins. + live: HashSet, + idom: Vec, + sections: Vec>, +} + +/// 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 { + 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 { + 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 { + 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 { + 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 { + 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> = HashMap::new(); + let mut def = HashMap::new(); + let mut live: HashSet = 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 { + let mut inside = vec![false; self.p.blocks.len()]; + let mut work: Vec = 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 { + 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, (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 = HashSet::from([t]); + let mut pattern: HashSet<(usize, usize)> = HashSet::new(); + let mut alike: Vec = Vec::new(); + // an unguarded copy + let copy = |u: (usize, usize)| -> Option { + 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 = 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 = 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 = 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> = 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>| { + 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 = 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 = 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 = 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 = 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()); + } +} diff --git a/crates/leonida-shader/src/emit/rect.rs b/crates/leonida-shader/src/emit/rect.rs new file mode 100644 index 000000000..9ec80fd8e --- /dev/null +++ b/crates/leonida-shader/src/emit/rect.rs @@ -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, ShaderError> { + let sig = |dxil: &[u8], fourcc| -> Result, 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, ps_inputs: &[SigElement]) -> Result, 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::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 = 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::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 { + 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"); + } + } +} diff --git a/crates/leonida-shader/src/emit/sampler.rs b/crates/leonida-shader/src/emit/sampler.rs new file mode 100644 index 000000000..e10c0c16e --- /dev/null +++ b/crates/leonida-shader/src/emit/sampler.rs @@ -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) + ); + } +} diff --git a/crates/leonida-shader/src/emit/shader.rs b/crates/leonida-shader/src/emit/shader.rs new file mode 100644 index 000000000..e970e6dd6 --- /dev/null +++ b/crates/leonida-shader/src/emit/shader.rs @@ -0,0 +1,890 @@ +//! 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` in this space. +pub const SAMPLER_SPACE: u32 = 0; +/// Where root CBVs and SRVs are bound: `b` and +/// `t` in this space. +pub const ROOT_CBV_SPACE: u32 = 1; + +/// The root SRV `t` 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` 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` 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(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, + pub outputs: Vec, + /// A mesh shader's per-primitive outputs. + pub prims: Vec, + /// A mesh shader (`threads` is its thread-group size). + pub mesh: Option, + /// A geometry shader (the rectangle stage, `rect.rs`); `pixel` is false. + pub geometry: Option, + /// 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, + /// 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, + /// Thread-group shared memory, in dwords. + pub lds_dwords: u32, + lds: Option, + 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, + 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.` (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` 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) + } + + pub fn annotate(&mut self, block: usize, h: V, props0: u32, props1: u32) -> V { + 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 { + 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::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 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(no), + 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 = 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("leonida"); + 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::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) -> Option { + 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)) + } +} diff --git a/crates/leonida-shader/src/emit/threading.rs b/crates/leonida-shader/src/emit/threading.rs new file mode 100644 index 000000000..01bd4feba --- /dev/null +++ b/crates/leonida-shader/src/emit/threading.rs @@ -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 { + 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::>(), + 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()); + } +} diff --git a/crates/leonida-shader/src/emit/validator.rs b/crates/leonida-shader/src/emit/validator.rs new file mode 100644 index 000000000..51371361b --- /dev/null +++ b/crates/leonida-shader/src/emit/validator.rs @@ -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 `LEONIDA_DXIL` if set, else the newest Windows SDK's +//! `bin\\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(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:: 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 { + if let Some(p) = std::env::var_os("LEONIDA_DXIL") { + return Some(p.into()); + } + let kits = PathBuf::from(r"C:\Program Files (x86)\Windows Kits\10\bin"); + let mut versions: Vec = 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 { + let name: Vec = 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) }; + } +} diff --git a/crates/leonida-shader/src/emit/valu_tests.rs b/crates/leonida-shader/src/emit/valu_tests.rs new file mode 100644 index 000000000..f5c20145a --- /dev/null +++ b/crates/leonida-shader/src/emit/valu_tests.rs @@ -0,0 +1,1624 @@ +//! End-to-end tests of synthetic GFX10 VALU shaders lowered to DXIL, validated +//! by `dxil.dll` when present, and executed on the host GPU and WARP. +//! +//! Covers RDNA2 hardware semantics that differ from naive DXIL lowering: +//! `v_med3_f32`/`v_med3_f16` with NaN operands, `v_fract_f32`/`v_fract_f16` +//! near `1.0`, turn-range reduction for `v_sin_*`/`v_cos_*`, and the LDS +//! float atomics `ds_min_f32`/`ds_max_f32`. + +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::{io, ir, resource, structure}; + +const S_ENDPGM: u32 = 0xBF81_0000; + +/// SOP1 `s_mov_b32 sdst, src0`. +const fn s_mov_b32(sdst: u8, src0: u8) -> u32 { + 0xBE80_0000 | (sdst as u32) << 16 | 0x03 << 8 | src0 as u32 +} + +/// SOP2 `op sdst, src0, src1`. +const fn sop2(op: u8, sdst: u8, src0: u8, src1: u8) -> u32 { + 0x8000_0000 + | (op as u32 & 0x7F) << 23 + | (sdst as u32 & 0x7F) << 16 + | (src1 as u32) << 8 + | src0 as u32 +} + +/// SMEM `s_load_dwordx4 s[dst:dst+3], s[base:base+1], 0` (soffset = null). +const fn s_load_dwordx4(dst: u8, base: u8) -> [u32; 2] { + [ + 0x3D << 26 | 0x02 << 18 | (dst as u32) << 6 | (base as u32 >> 1), + 125 << 25, + ] +} + +/// VOP1 `op vdst, src0` (`src0`: 0..105 = SGPR, 256..511 = VGPR). +const fn vop1(op: u16, vdst: u8, src0: u16) -> u32 { + 0x7E00_0000 | (vdst as u32) << 17 | (op as u32) << 9 | (src0 as u32 & 0x1FF) +} + +/// VOP3 `op vdst, src0, src1, src2` (no modifiers). +const fn vop3(op: u16, vdst: u8, src0: u16, src1: u16, src2: u16) -> [u32; 2] { + vop3_mod(op, vdst, src0, src1, src2, 0, 0, 0, false) +} + +/// VOP3 `op vdst, src0, src1, src2` with explicit `abs`, `neg`, `omod`, `clamp`. +#[allow(clippy::too_many_arguments)] +const fn vop3_mod( + op: u16, + vdst: u8, + src0: u16, + src1: u16, + src2: u16, + abs: u8, + neg: u8, + omod: u8, + clamp: bool, +) -> [u32; 2] { + [ + 0x35 << 26 + | (op as u32 & 0x3FF) << 16 + | (clamp as u32) << 15 + | (abs as u32 & 7) << 8 + | vdst as u32, + (neg as u32 & 7) << 29 + | (omod as u32 & 3) << 27 + | (src0 as u32 & 0x1FF) + | (src1 as u32 & 0x1FF) << 9 + | (src2 as u32 & 0x1FF) << 18, + ] +} + +/// MUBUF `buffer_store_dword vdata, off, s[srsrc:srsrc+3], 0 offset:byte_off`. +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, + ] +} + +const fn sgpr(n: u8) -> u16 { + n as u16 +} + +const fn vgpr(n: u8) -> u16 { + 256 + n as u16 +} + +/// Builds and lowers a 1-thread synthetic RDNA2 compute shader that receives +/// 4 dwords of root constants in `s0..s3`, runs `body` (leaving its result in +/// `v0`), and stores `v0` to dword 0 of the raw UAV at heap index 0. +fn build_valu_cs(body: &[u32]) -> HostShader { + build_cs(body, 1, 0) +} + +/// [`build_valu_cs`] with `threads` threads in x (thread index in `v0` +/// on entry, before `body`) and `lds_bytes` of LDS (a multiple of 512). +fn build_cs(body: &[u32], threads: u32, lds_bytes: u32) -> HostShader { + let mut words = Vec::new(); + // s[4:5] = descriptor table address (heap index 0 -> byte offset 0). + words.push(s_mov_b32(5, 0x80)); // inline constant 0 + words.extend_from_slice(&s_load_dwordx4(8, 4)); + // Copy root constants s0..s3 into v1..v4 so VALU instructions operate on + // VGPRs just as they do in real shaders. + for i in 0..4u8 { + words.push(vop1(0x001, i + 1, sgpr(i))); // v_mov_b32 + } + words.extend_from_slice(body); + words.extend_from_slice(&buffer_store_dword(0, 8, 0)); + words.push(S_ENDPGM); + + let code: Vec = words.iter().flat_map(|w| w.to_le_bytes()).collect(); + let native = NativeProgram { + stage: HwStage::Cs, + wave64: false, + vgprs: 8, + 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) | ((lds_bytes / 512) << 15), // 5 user SGPRs: s0..s4 + threads: [threads, 1, 1], + }), + code, + }; + + 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("resource::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"); + + 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, + }; + + if let Ok(mut v) = validator::Validator::load(validator::Validator::default_path().as_deref()) { + let mut copy = shader.dxil.clone(); + let ours = copy[4..20].to_vec(); + v.validate(&mut copy).expect("DXIL validation failed"); + assert_eq!(copy[4..20], ours[..], "container hash mismatch"); + } + + shader +} + +/// One GPU test at a time. With these tests on the hardware adapter and WARP +/// from several test threads at once, now and then none of their dispatches +/// ever completes and the test binary hangs; and two GPU tests at once on +/// WARP can end the test process with an access violation. Other GPU test +/// modules take this lock too. +pub(super) static ONE_AT_A_TIME: std::sync::Mutex<()> = std::sync::Mutex::new(()); + +/// Runs `shader` on every available SM 6.6 host (hardware GPU and WARP) for +/// each 4-dword input set and invokes `check(backend, case_index, inputs, result_dword)`. +fn run_cases( + shader: &HostShader, + cases: &[[u32; 4]], + check: impl FnMut(&str, usize, [u32; 4], u32), +) { + run_cases_on(shader, cases, &[("hardware", false), ("warp", true)], check); +} + +fn run_cases_on( + shader: &HostShader, + cases: &[[u32; 4]], + devices: &[(&str, bool)], + mut check: impl FnMut(&str, usize, [u32; 4], u32), +) { + let _one = ONE_AT_A_TIME.lock().unwrap_or_else(|e| e.into_inner()); + let mut ran = 0; + for &(label, warp) in devices { + 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 (i, &inputs) in cases.iter().enumerate() { + 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(1)], + samplers: &[], + groups: [1, 1, 1], + }, + ) + .unwrap_or_else(|e| panic!("{label}: dispatch failed: {e}")); + check(label, i, inputs, out[0][0]); + } + ran += 1; + } + if ran == 0 && devices.iter().all(|&(_, warp)| !warp) { + // A case for the hardware adapter alone, on a machine without one. + eprintln!("no SM 6.6 hardware device; a hardware-only case not run"); + return; + } + assert!(ran > 0, "no SM 6.6 device available ({devices:?})"); +} + +fn is_f16_nan(bits: u16) -> bool { + (bits & 0x7FFF) > 0x7C00 +} + +fn f16_to_f32(bits: u16) -> f32 { + let sign = u32::from(bits >> 15) << 31; + let exp = (bits >> 10) & 0x1F; + let mant = bits & 0x3FF; + let f32_bits = match exp { + 0 => { + if mant == 0 { + sign + } else { + let mut m = u32::from(mant); + let mut e = 127 - 14; + while (m & 0x400) == 0 { + m <<= 1; + e -= 1; + } + sign | (e << 23) | ((m & 0x3FF) << 13) + } + } + 0x1F => sign | (0xFF << 23) | (u32::from(mant) << 13), + _ => sign | ((u32::from(exp) + 112) << 23) | (u32::from(mant) << 13), + }; + f32::from_bits(f32_bits) +} + +#[test] +fn packed_add_selects_halves_of_inline_constants() { + // Add the inline constant 1/(2*pi) to v1 (zero) to read back its two halves. + // The same GFX10 source field (248) has a different bit pattern for a + // packed floating-point and a packed integer instruction. + let cases = [ + // v_pk_add_f16 v0, 0x3118, v1 + ([0xcc0f4000, 0x1a0202f8], 0x0000_3118), + // v_pk_add_f16 v0, 0x3118, v1 op_sel_hi:[0,1] (use low twice) + ([0xcc0f4000, 0x120202f8], 0x3118_3118), + // v_pk_add_u16 v0, 0x3e22f983, v1 + ([0xcc0a4000, 0x1a0202f8], 0x3e22_f983), + ]; + for (words, expected) in cases { + let shader = build_valu_cs(&words); + run_cases(&shader, &[[0; 4]], |backend, _, _, got| { + assert_eq!(got, expected, "{backend}: {words:08x?}"); + }); + } +} + +/// The float `v_cvt_f32_f64` gives for `x`: Rust's rounding (to nearest +/// even), with results below the smallest normal float flushed to signed +/// zero as the console's default float mode does. +fn cvt_f32_f64_reference(x: f64) -> u32 { + let r = x as f32; + if r.is_subnormal() || (r == 0.0 && x != 0.0) { + r.to_bits() & 0x8000_0000 + } else { + r.to_bits() + } +} + +#[test] +#[ignore = "expects results below the smallest normal float flushed to zero; the IEEE lowering (v_cvt_f32_f64_matches_ieee754) is kept until the console's mode is checked"] +fn v_cvt_f32_f64_rounds_to_nearest_even() { + // v_cvt_f32_f64 v0, v[1:2] (VOP1 opcode 0x0f) + let shader = build_valu_cs(&[vop1(0x00f, 0, vgpr(1))]); + let tie_even = 1.0f64 + f64::from(f32::EPSILON) / 2.0; // ties to 1.0 + let tie_odd = 1.0f64 + 1.5 * f64::from(f32::EPSILON); // ties up to 1 + 2 ulp + let values = [ + 0.0, + -0.0, + 1.0, + -2.5, + std::f64::consts::PI, + 1.0e-3, + 123_456_789.123, + tie_even, + tie_odd, + 1.0 + f64::from(f32::EPSILON) * 0.75, + f64::from(f32::MAX), + f64::from(f32::MAX) * 1.000_000_1, // rounds to infinity + 1.0e300, + -1.0e300, + 1.0e-40, // a float denormal: flushed + -1.0e-300, + f64::from(f32::MIN_POSITIVE), + f64::INFINITY, + f64::NEG_INFINITY, + f64::NAN, + ]; + let inputs: Vec<[u32; 4]> = values + .iter() + .map(|x| { + let b = x.to_bits(); + [b as u32, (b >> 32) as u32, 0, 0] + }) + .collect(); + run_cases(&shader, &inputs, |backend, i, _, got| { + let x = values[i]; + if x.is_nan() { + assert!(f32::from_bits(got).is_nan(), "{backend}: cvt({x}) = {got:#010x}, want NaN"); + return; + } + let want = cvt_f32_f64_reference(x); + assert_eq!(got, want, "{backend}: cvt({x:e}) = {got:#010x}, want {want:#010x}"); + }); +} + +/// The lane `v_permlane16_b32` (`cross` false) or `v_permlanex16_b32` reads +/// for `lane`, with selector dwords `s1` (lanes 0-7 of a row) and `s2`. +fn permlane_source(lane: u32, s1: u32, s2: u32, cross: bool) -> u32 { + let sel = u64::from(s1) | u64::from(s2) << 32; + let pick = (sel >> (4 * (lane & 15)) & 15) as u32; + let row = if cross { + (lane & !31) | ((lane & 16) ^ 16) + } else { + lane & !15 + }; + row | pick +} + +#[test] +fn v_permlane16_and_x16_read_the_lanes_their_selectors_pick() { + // 32 lanes, each with its lane number in v0; v1 = permute(v0, s0, s1); + // lane `read` of v1 into s12, then into v0 for the store. + let selectors: [(u32, u32); 3] = [ + (0x7654_3210, 0xfedc_ba98), // identity within the row + (0x89ab_cdef, 0x0123_4567), // reversed + (0x1111_1111, 0xf0f0_f0f0), // repeats + ]; + for (op, cross) in [(0x377u16, false), (0x378, true)] { + for read in [0u8, 5, 15, 16, 22, 31] { + let mut body = Vec::new(); + body.extend_from_slice(&vop3(op, 1, vgpr(0), sgpr(0), sgpr(1))); + // v_readlane_b32 s12, v1, read (inline constant 128 + read) + body.extend_from_slice(&vop3(0x360, 12, vgpr(1), 128 + u16::from(read), 0)); + body.push(vop1(0x001, 0, sgpr(12))); // v_mov_b32 v0, s12 + let shader = build_cs(&body, 32, 0); + let inputs: Vec<[u32; 4]> = selectors.iter().map(|&(a, b)| [a, b, 0, 0]).collect(); + // Cross-lane code declares WaveSize(32), which WARP's pipeline + // creation refuses: hardware only. + run_cases_on(&shader, &inputs, &[("hardware", false)], |backend, i, inp, got| { + let want = permlane_source(u32::from(read), inp[0], inp[1], cross); + assert_eq!( + got, want, + "{backend}: op {op:#x} selectors {:08x?}, lane {read}", + selectors[i] + ); + }); + } + } +} + +#[test] +fn v_med3_f32_matches_rdna2_with_nan() { + // v_med3_f32 v0, v1, v2, v3 (VOP3 opcode 0x157) + let shader = build_valu_cs(&vop3(0x157, 0, vgpr(1), vgpr(2), vgpr(3))); + let nan = f32::NAN.to_bits(); + let f = f32::to_bits; + + let cases: &[([u32; 4], Option)] = &[ + // Normal medians (all orderings). + ([f(1.0), f(2.0), f(3.0), 0], Some(2.0)), + ([f(3.0), f(1.0), f(2.0), 0], Some(2.0)), + ([f(-5.0), f(0.0), f(5.0), 0], Some(0.0)), + ([f(1.0), f(1.0), f(2.0), 0], Some(1.0)), + // One NaN: RDNA2 returns min3 of the non-NaN operands. + ([f(1.0), f(2.0), nan, 0], Some(1.0)), + ([nan, f(1.0), f(0.0), 0], Some(0.0)), + ([nan, f(0.0), f(1.0), 0], Some(0.0)), + ([f(2.0), nan, f(1.0), 0], Some(1.0)), + ([f(-3.0), nan, f(4.0), 0], Some(-3.0)), + // Two NaNs: returns the sole non-NaN operand. + ([nan, f(5.0), nan, 0], Some(5.0)), + ([nan, nan, f(-2.0), 0], Some(-2.0)), + ([f(7.0), nan, nan, 0], Some(7.0)), + // Three NaNs: returns NaN. + ([nan, nan, nan, 0], None), + ]; + + let inputs: Vec<[u32; 4]> = cases.iter().map(|c| c.0).collect(); + run_cases(&shader, &inputs, |backend, i, inp, got| { + let expect = cases[i].1; + let got_f = f32::from_bits(got); + match expect { + Some(want) => assert_eq!( + got_f, + want, + "{backend}: v_med3_f32({:?}, {:?}, {:?}) = {got_f} ({got:#010x}), want {want}", + f32::from_bits(inp[0]), + f32::from_bits(inp[1]), + f32::from_bits(inp[2]), + ), + None => assert!( + got_f.is_nan(), + "{backend}: v_med3_f32(NaN, NaN, NaN) = {got_f} ({got:#010x}), want NaN", + ), + } + }); +} + +/// RDNA2 orders -0 below +0 in its maximums and minimums; DXIL's FMax and +/// FMin compare and select, which can give either zero. +#[test] +fn max_and_min_order_negative_zero_below_positive_zero() { + let (pz, nz) = (0_u32, 0x8000_0000_u32); + // Each case has a -0 and a +0 among its first two operands. + let cases = [ + [nz, pz, nz, 0], + [pz, nz, nz, 0], + [nz, pz, pz, 0], + [pz, nz, pz, 0], + ]; + let ops = [ + ("v_max_f32", 0x110, pz), + ("v_min_f32", 0x10F, nz), + ("v_max3_f32", 0x154, pz), + ("v_min3_f32", 0x151, nz), + ]; + for (name, op, want) in ops { + let shader = build_valu_cs(&vop3(op, 0, vgpr(1), vgpr(2), vgpr(3))); + run_cases(&shader, &cases, |backend, _, inp, got| { + assert_eq!(got, want, "{backend}: {name} {inp:x?}"); + }); + } +} + +#[test] +fn v_med3_f16_matches_rdna2_with_nan() { + // v_med3_f16 v0, v1, v2, v3 (VOP3 opcode 0x357) + let shader = build_valu_cs(&vop3(0x357, 0, vgpr(1), vgpr(2), vgpr(3))); + let h0 = 0x0000u32; // 0.0 + let h1 = 0x3C00u32; // 1.0 + let h2 = 0x4000u32; // 2.0 + let h3 = 0x4200u32; // 3.0 + let h5 = 0x4500u32; // 5.0 + let hn2 = 0xC000u32; // -2.0 + let nan = 0x7E00u32; + + let cases: &[([u32; 4], Option)] = &[ + ([h1, h2, h3, 0], Some(h2 as u16)), + ([hn2, h0, h3, 0], Some(h0 as u16)), + ([h1, h2, nan, 0], Some(h1 as u16)), + ([nan, h1, h0, 0], Some(h0 as u16)), + ([nan, h0, h1, 0], Some(h0 as u16)), + ([h2, nan, h1, 0], Some(h1 as u16)), + ([nan, h5, nan, 0], Some(h5 as u16)), + ([nan, nan, nan, 0], None), + ]; + + let inputs: Vec<[u32; 4]> = cases.iter().map(|c| c.0).collect(); + run_cases(&shader, &inputs, |backend, i, inp, got| { + let expect = cases[i].1; + let got_h = got as u16; + match expect { + Some(want) => assert_eq!( + got_h, want, + "{backend}: v_med3_f16({:#06x}, {:#06x}, {:#06x}) = {got_h:#06x}, want {want:#06x}", + inp[0], inp[1], inp[2], + ), + None => assert!( + is_f16_nan(got_h), + "{backend}: v_med3_f16(NaN, NaN, NaN) = {got_h:#06x}, want NaN", + ), + } + }); +} + +/// `v_cmp_lg_*` is "less or greater": ordered and not equal, so false when +/// either operand is a NaN (RDNA2 ISA; the same on gfx1036 hardware). +#[test] +fn v_cmp_lg_is_false_for_nan() { + // v_cmp_lg_{f32,f16}_e64 s20, v1, v2 (VOPC 0x005 / 0x0cd in VOP3); + // v_cndmask_b32_e64 v0, 0, 1, s20 (VOP3 0x101) + let nan = f32::NAN.to_bits(); + let (inf, ninf) = (f32::INFINITY.to_bits(), f32::NEG_INFINITY.to_bits()); + let f = f32::to_bits; + let f32_cases: &[([u32; 4], u32)] = &[ + ([f(1.0), f(2.0), 0, 0], 1), + ([f(2.0), f(1.0), 0, 0], 1), + ([f(1.0), f(1.0), 0, 0], 0), + ([f(0.0), f(-0.0), 0, 0], 0), + ([inf, ninf, 0, 0], 1), + ([inf, inf, 0, 0], 0), + ([nan, f(1.0), 0, 0], 0), + ([f(1.0), nan, 0, 0], 0), + ([nan, nan, 0, 0], 0), + ([0x7F80_0001, f(0.0), 0, 0], 0), // a signalling NaN + ]; + let f16_cases: &[([u32; 4], u32)] = &[ + ([0x3C00, 0x4000, 0, 0], 1), + ([0x4000, 0x3C00, 0, 0], 1), + ([0x3C00, 0x3C00, 0, 0], 0), + ([0x0000, 0x8000, 0, 0], 0), + ([0x7C00, 0xFC00, 0, 0], 1), + ([0x7E00, 0x3C00, 0, 0], 0), + ([0x3C00, 0x7E00, 0, 0], 0), + ([0x7E00, 0x7E00, 0, 0], 0), + ([0x7C01, 0x0000, 0, 0], 0), // a signalling NaN + ([0xABCD_3C00, 0x1234_7E00, 0, 0], 0), // only the low halves are read + ]; + for (op, what, cases) in [ + (0x005u16, "v_cmp_lg_f32", f32_cases), + (0x0cd, "v_cmp_lg_f16", f16_cases), + ] { + let mut body = vop3(op, 20, vgpr(1), vgpr(2), 0x80).to_vec(); + body.extend_from_slice(&vop3(0x101, 0, 0x80, 0x81, sgpr(20))); + let shader = build_valu_cs(&body); + let inputs: Vec<[u32; 4]> = cases.iter().map(|c| c.0).collect(); + run_cases(&shader, &inputs, |backend, i, inp, got| { + let want = cases[i].1; + assert_eq!( + got, want, + "{backend}: {what}({:#010x}, {:#010x}) = {got}, want {want}", + inp[0], inp[1], + ); + }); + } +} + +#[test] +fn v_fract_f32_never_returns_one() { + // v_fract_f32 v0, v1 (VOP1 opcode 0x020) + let shader = build_valu_cs(&[vop1(0x020, 0, vgpr(1))]); + let f = f32::to_bits; + let below_one = 0x3F7F_FFFFu32; + + let cases: &[(u32, Option)] = &[ + // Tiny negatives: must clamp strictly below 1.0 (not 0x3f800000). + (f(-1e-10), Some(below_one)), + (f(-1e-8), Some(below_one)), + (f(-2.0f32.powi(-25)), Some(below_one)), + (f(-2.0f32.powi(-24)), Some(below_one)), + // Normal values. + (f(0.0), Some(f(0.0))), + (f(-0.0), Some(f(0.0))), + (f(0.25), Some(f(0.25))), + (f(3.75), Some(f(0.75))), + (f(-0.25), Some(f(0.75))), + (f(-3.25), Some(f(0.75))), + (f(1.0), Some(f(0.0))), + (f(-1.0), Some(f(0.0))), + // Non-finite inputs yield NaN. + (f(f32::NAN), None), + (f(f32::INFINITY), None), + (f(f32::NEG_INFINITY), None), + ]; + + let inputs: Vec<[u32; 4]> = cases.iter().map(|&(x, _)| [x, 0, 0, 0]).collect(); + run_cases(&shader, &inputs, |backend, i, inp, got| { + let expect = cases[i].1; + match expect { + Some(want) => assert_eq!( + got, + want, + "{backend}: v_fract_f32({:?} / {:#010x}) = {got:#010x} ({:?}), want {want:#010x}", + f32::from_bits(inp[0]), + inp[0], + f32::from_bits(got), + ), + None => assert!( + f32::from_bits(got).is_nan(), + "{backend}: v_fract_f32({:?}) = {got:#010x}, want NaN", + f32::from_bits(inp[0]), + ), + } + }); +} + +#[test] +fn v_fract_f16_never_returns_one() { + // v_fract_f16 v0, v1 (VOP1 opcode 0x05f) + let shader = build_valu_cs(&[vop1(0x05f, 0, vgpr(1))]); + let below_one = 0x3BFFu16; // 1.0 - 2^-11 + + assert_eq!(f16_to_f32(0x9400), -2.0f32.powi(-10)); + assert_eq!(f16_to_f32(0x9000), -2.0f32.powi(-11)); + assert_eq!(f16_to_f32(0x8C00), -2.0f32.powi(-12)); + + let cases: &[(u16, Option)] = &[ + // Negatives in (-2^-11, 0): must clamp to 0x3BFF, never 0x3C00 (1.0). + (0x8C00, Some(below_one)), // -2^-12 + (0x8400, Some(below_one)), // -2^-14 + (0x8001, Some(below_one)), // -2^-24 (smallest negative f16 subnormal) + (0x9000, Some(below_one)), // -2^-11 (exact 1 - 2^-11 = 0x3BFF) + (0x9400, Some(0x3BFE)), // -2^-10 (exact 1 - 2^-10 = 0x3BFE) + // Normal values. + (0x0000, Some(0x0000)), // 0.0 -> 0.0 + (0x3400, Some(0x3400)), // 0.25 -> 0.25 + (0xB400, Some(0x3A00)), // -0.25 -> 0.75 + (0x4300, Some(0x3800)), // 3.5 -> 0.5 + (0x3C00, Some(0x0000)), // 1.0 -> 0.0 + // Non-finite inputs yield NaN. + (0x7E00, None), // NaN + (0x7C00, None), // +inf + (0xFC00, None), // -inf + ]; + + let inputs: Vec<[u32; 4]> = cases + .iter() + .map(|&(x, _)| [u32::from(x), 0, 0, 0]) + .collect(); + run_cases(&shader, &inputs, |backend, i, inp, got| { + let expect = cases[i].1; + let got_h = got as u16; + match expect { + Some(want) => assert_eq!( + got_h, want, + "{backend}: v_fract_f16({:#06x}) = {got_h:#06x}, want {want:#06x}", + inp[0], + ), + None => assert!( + is_f16_nan(got_h), + "{backend}: v_fract_f16({:#06x}) = {got_h:#06x}, want NaN", + inp[0], + ), + } + }); +} + +/// RDNA2's flt16_to_snorm16 / flt16_to_unorm16: clamp, scale by 32767 or +/// 65535, round the exact product to nearest even; NaN gives 0. +fn cvt_norm16_reference(bits: u16, signed: bool) -> u16 { + let x = f16_to_f32(bits); + if x.is_nan() { + return 0; + } + let (lo, scale) = if signed { + (-1.0, 32767.0) + } else { + (0.0, 65535.0) + }; + // f64 holds the product of an f16 and a 16-bit scale exactly. + let p = f64::from(x.clamp(lo, 1.0)) * scale; + p.round_ties_even() as i32 as u16 +} + +#[test] +fn v_cvt_norm_i16_and_u16_f16_round_the_exact_product() { + // Every 251st f16 pattern, plus the values where an f32 product would + // round before the rounding to an integer, ties, and the edges. + let mut bits: Vec = (0..=u16::MAX).step_by(251).collect(); + bits.extend([ + 0x0000, 0x8000, 0x0001, 0x8001, 0x03FF, 0x0400, 0x3800, 0xB800, 0x3801, 0xB801, 0x37FF, + 0x3BFF, 0xBBFF, 0x3C00, 0xBC00, 0x3C01, 0x7BFF, 0x7C00, 0xFC00, 0x7E00, 0xFE00, 0x7C01, + 0x3A9B, 0xBA9B, 0x2E66, 0x1400, + ]); + for (op, signed, what) in [ + (0x063u16, true, "v_cvt_norm_i16_f16"), + (0x064, false, "v_cvt_norm_u16_f16"), + ] { + // v_cvt_norm_*16_f16 v0, v1 (VOP1); v0's high half starts at 0. + let shader = build_valu_cs(&[vop1(0x001, 0, 128), vop1(op, 0, vgpr(1))]); + let inputs: Vec<[u32; 4]> = bits.iter().map(|&b| [u32::from(b), 0, 0, 0]).collect(); + run_cases(&shader, &inputs, |backend, i, _, got| { + let want = cvt_norm16_reference(bits[i], signed); + assert_eq!( + got, + u32::from(want), + "{backend}: {what}({:#06x}) = {got:#010x}, want {want:#06x}", + bits[i], + ); + }); + } +} + +#[test] +fn v_sin_and_v_cos_f32_reduce_large_turns() { + let sin_shader = build_valu_cs(&[vop1(0x035, 0, vgpr(1))]); + let cos_shader = build_valu_cs(&[vop1(0x036, 0, vgpr(1))]); + let f = f32::to_bits; + let half_sqrt2 = std::f32::consts::FRAC_1_SQRT_2; + + let sin_cases: &[(f32, Option)] = &[ + (0.0, Some(0.0)), + (0.25, Some(1.0)), + (255.0, Some(0.0)), + (255.25, Some(1.0)), + (255.5, Some(0.0)), + (-255.25, Some(-1.0)), + (10_000.125, Some(half_sqrt2)), + (f32::NAN, None), + (f32::INFINITY, None), + (f32::NEG_INFINITY, None), + ]; + let sin_inputs: Vec<[u32; 4]> = sin_cases.iter().map(|&(x, _)| [f(x), 0, 0, 0]).collect(); + run_cases(&sin_shader, &sin_inputs, |backend, i, inp, got| { + let expect = sin_cases[i].1; + let got_f = f32::from_bits(got); + match expect { + Some(want) => assert!( + (got_f - want).abs() < 1e-5, + "{backend}: v_sin_f32({}) = {got_f}, want {want} (err = {})", + f32::from_bits(inp[0]), + (got_f - want).abs(), + ), + None => assert!( + got_f.is_nan(), + "{backend}: v_sin_f32({}) = {got_f}, want NaN", + f32::from_bits(inp[0]), + ), + } + }); + + let cos_cases: &[(f32, Option)] = &[ + (0.0, Some(1.0)), + (0.25, Some(0.0)), + (255.0, Some(1.0)), + (255.25, Some(0.0)), + (255.5, Some(-1.0)), + (-255.5, Some(-1.0)), + (10_000.125, Some(half_sqrt2)), + (f32::NAN, None), + (f32::INFINITY, None), + (f32::NEG_INFINITY, None), + ]; + let cos_inputs: Vec<[u32; 4]> = cos_cases.iter().map(|&(x, _)| [f(x), 0, 0, 0]).collect(); + run_cases(&cos_shader, &cos_inputs, |backend, i, inp, got| { + let expect = cos_cases[i].1; + let got_f = f32::from_bits(got); + match expect { + Some(want) => assert!( + (got_f - want).abs() < 1e-5, + "{backend}: v_cos_f32({}) = {got_f}, want {want} (err = {})", + f32::from_bits(inp[0]), + (got_f - want).abs(), + ), + None => assert!( + got_f.is_nan(), + "{backend}: v_cos_f32({}) = {got_f}, want NaN", + f32::from_bits(inp[0]), + ), + } + }); + + // Main's `trig_turns` preserves sin(-0.0) = -0.0 and produces exact +0.0 at + // half-turns (sin) and quarter-turns (cos). + let exact_sin: &[(u32, u32)] = &[ + (0x8000_0000, 0x8000_0000), // sin(-0.0) = -0.0 + (f(255.0), 0), // sin(255.0) = +0.0 + (f(255.5), 0), // sin(255.5) = +0.0 + ]; + let exact_sin_in: Vec<[u32; 4]> = exact_sin.iter().map(|&(x, _)| [x, 0, 0, 0]).collect(); + run_cases(&sin_shader, &exact_sin_in, |backend, i, inp, got| { + let want = exact_sin[i].1; + assert_eq!( + got, want, + "{backend}: v_sin_f32({:#010x}) = {got:#010x}, want {want:#010x}", + inp[0], + ); + }); + let exact_cos: &[(u32, u32)] = &[ + (f(0.25), 0), // cos(0.25) = +0.0 + (f(255.25), 0), // cos(255.25) = +0.0 + ]; + let exact_cos_in: Vec<[u32; 4]> = exact_cos.iter().map(|&(x, _)| [x, 0, 0, 0]).collect(); + run_cases(&cos_shader, &exact_cos_in, |backend, i, inp, got| { + let want = exact_cos[i].1; + assert_eq!( + got, want, + "{backend}: v_cos_f32({:#010x}) = {got:#010x}, want {want:#010x}", + inp[0], + ); + }); +} + +#[test] +fn v_cvt_u16_and_i16_f16_saturate() { + // v_mov_b32 v0, 0; v_cvt_u16_f16 / v_cvt_i16_f16 v0, v1 (VOP1 0x052 / 0x053). + let cases: &[(u16, u16, u16)] = &[ + // (f16 input, u16 result, i16 result) + (0x0000, 0, 0), // 0 + (0x8000, 0, 0), // -0 + (0x3E00, 1, 1), // 1.5 -> 1 (toward zero) + (0xBE00, 0, 0xFFFF), // -1.5 -> 0 / -1 + (0x57D0, 125, 125), // 125.0 + (0x7800, 32768, 32767), // 32768 saturates i16 + (0x77FF, 32752, 32752), // 32752, the largest f16 below 32768 + (0xF800, 0, 0x8000), // -32768 fits i16 + (0xF801, 0, 0x8000), // -32800 saturates i16 + (0x7BFF, 65504, 32767), // max finite f16 + (0xFBFF, 0, 0x8000), // -65504 + (0x7C00, 0xFFFF, 32767), // +inf + (0xFC00, 0, 0x8000), // -inf + (0x7E00, 0, 0), // NaN + (0xFE00, 0, 0), // -NaN + (0x0001, 0, 0), // smallest subnormal + ]; + for (op, what, pick) in [ + (0x052u16, "v_cvt_u16_f16", 0usize), + (0x053, "v_cvt_i16_f16", 1), + ] { + let shader = build_valu_cs(&[vop1(0x001, 0, 128), vop1(op, 0, vgpr(1))]); + let inputs: Vec<[u32; 4]> = cases.iter().map(|c| [u32::from(c.0), 0, 0, 0]).collect(); + run_cases(&shader, &inputs, |backend, i, _, got| { + let want = if pick == 0 { cases[i].1 } else { cases[i].2 }; + assert_eq!( + got, + u32::from(want), + "{backend}: {what}({:#06x}) = {got:#010x}, want {want:#06x}", + cases[i].0, + ); + }); + } +} + +#[test] +fn v_sin_and_v_cos_f16_reduce_large_turns() { + let sin_shader = build_valu_cs(&[vop1(0x060, 0, vgpr(1))]); + let cos_shader = build_valu_cs(&[vop1(0x061, 0, vgpr(1))]); + + // Sanity-check the f16 bit encodings of large turns. + assert_eq!(f16_to_f32(0x5BF8), 255.0); + assert_eq!(f16_to_f32(0x5BFA), 255.25); + assert_eq!(f16_to_f32(0x5BFC), 255.5); + assert_eq!(f16_to_f32(0x7BFF), 65504.0); + + let sin_cases: &[(u16, Option)] = &[ + (0x5BF8, Some(0.0)), // 255.0 + (0x5BFA, Some(1.0)), // 255.25 + (0x5BFC, Some(0.0)), // 255.5 + (0xDBFA, Some(-1.0)), // -255.25 + (0x7BFF, Some(0.0)), // 65504.0 (largest finite f16, exact integer) + (0x7E00, None), // NaN + (0x7C00, None), // +inf + (0xFC00, None), // -inf + ]; + let sin_inputs: Vec<[u32; 4]> = sin_cases + .iter() + .map(|&(x, _)| [u32::from(x), 0, 0, 0]) + .collect(); + run_cases(&sin_shader, &sin_inputs, |backend, i, inp, got| { + let expect = sin_cases[i].1; + let got_h = got as u16; + match expect { + Some(want) => { + let got_f = f16_to_f32(got_h); + assert!( + (got_f - want).abs() < 1e-3, + "{backend}: v_sin_f16({:#06x} = {}) = {got_f} ({got_h:#06x}), want {want}", + inp[0], + f16_to_f32(inp[0] as u16), + ); + } + None => assert!( + is_f16_nan(got_h), + "{backend}: v_sin_f16({:#06x}) = {got_h:#06x}, want NaN", + inp[0], + ), + } + }); + + let cos_cases: &[(u16, Option)] = &[ + (0x5BF8, Some(1.0)), // 255.0 + (0x5BFA, Some(0.0)), // 255.25 + (0x5BFC, Some(-1.0)), // 255.5 + (0x7BFF, Some(1.0)), // 65504.0 (largest finite f16, exact integer) + (0x7E00, None), // NaN + (0x7C00, None), // +inf + (0xFC00, None), // -inf + ]; + let cos_inputs: Vec<[u32; 4]> = cos_cases + .iter() + .map(|&(x, _)| [u32::from(x), 0, 0, 0]) + .collect(); + run_cases(&cos_shader, &cos_inputs, |backend, i, inp, got| { + let expect = cos_cases[i].1; + let got_h = got as u16; + match expect { + Some(want) => { + let got_f = f16_to_f32(got_h); + assert!( + (got_f - want).abs() < 1e-3, + "{backend}: v_cos_f16({:#06x} = {}) = {got_f} ({got_h:#06x}), want {want}", + inp[0], + f16_to_f32(inp[0] as u16), + ); + } + None => assert!( + is_f16_nan(got_h), + "{backend}: v_cos_f16({:#06x}) = {got_h:#06x}, want NaN", + inp[0], + ), + } + }); +} + +#[test] +fn bfe_signed_and_unsigned_match_rdna2() { + // v_bfe_i32 v0, v1, v2, v3 (VOP3 opcode 0x149) + let v_signed = build_valu_cs(&vop3(0x149, 0, vgpr(1), vgpr(2), vgpr(3))); + // v_bfe_u32 v0, v1, v2, v3 (VOP3 opcode 0x148) + let v_unsigned = build_valu_cs(&vop3(0x148, 0, vgpr(1), vgpr(2), vgpr(3))); + // s_bfe_i32 s6, s0, s1 (SOP2 opcode 0x28: s1 = off[4:0] | width[22:16]); v_mov_b32 v0, s6 + let s_signed = build_valu_cs(&[sop2(0x28, 6, 0, 1), vop1(0x001, 0, sgpr(6))]); + + let signed_cases: &[([u32; 4], u32)] = &[ + // Field crosses bit 31: extends from bit 31. + ([0xd2f9_0159, 28, 16, 0], 0xffff_fffd), + ([0x8000_0000, 31, 4, 0], 0xffff_ffff), + ([0x7000_0000, 28, 8, 0], 0x0000_0007), + // Normal fields inside 32 bits. + ([0x0000_0080, 4, 4, 0], 0xffff_fff8), + ([0x0000_0070, 4, 4, 0], 0x0000_0007), + // Edge widths: 0 yields 0; v_bfe masks width to 5 bits (32 -> 0), + // while 31 extracts all remaining bits from offset 4. + ([0xffff_ffff, 4, 0, 0], 0), + ([0x8000_0000, 4, 31, 0], 0xf800_0000), + ]; + let v_in: Vec<[u32; 4]> = signed_cases.iter().map(|c| c.0).collect(); + run_cases(&v_signed, &v_in, |backend, i, inp, got| { + let want = signed_cases[i].1; + assert_eq!( + got, want, + "{backend}: v_bfe_i32({:#010x}, {}, {}) = {got:#010x}, want {want:#010x}", + inp[0], inp[1], inp[2], + ); + }); + // v_bfe_i32 width is 5-bit (src2[4:0]), so width=32 wraps to 0. + run_cases( + &v_signed, + &[[0x8000_0000, 4, 32, 0]], + |backend, _, _, got| { + assert_eq!(got, 0, "{backend}: v_bfe_i32 width 32 should mask to 0"); + }, + ); + + // s_bfe_i32 width is 7-bit (src1[22:16]), so width=32 keeps all 32 bits. + let mut s_cases = signed_cases.to_vec(); + s_cases.push(([0x8000_0000, 4, 32, 0], 0xf800_0000)); + let s_in: Vec<[u32; 4]> = s_cases + .iter() + .map(|&(inp, _)| [inp[0], (inp[1] & 31) | ((inp[2] & 0x7F) << 16), 0, 0]) + .collect(); + run_cases(&s_signed, &s_in, |backend, i, inp, got| { + let want = s_cases[i].1; + assert_eq!( + got, want, + "{backend}: s_bfe_i32({:#010x}, {:#010x}) = {got:#010x}, want {want:#010x}", + inp[0], inp[1], + ); + }); + + let unsigned_cases: &[([u32; 4], u32)] = &[ + ([0xd2f9_0159, 28, 16, 0], 0x0000_000d), + ([0x8000_0000, 31, 4, 0], 0x0000_0001), + ([0xffff_ffff, 4, 0, 0], 0), + ([0x8000_0000, 4, 31, 0], 0x0800_0000), + ]; + let u_in: Vec<[u32; 4]> = unsigned_cases.iter().map(|c| c.0).collect(); + run_cases(&v_unsigned, &u_in, |backend, i, inp, got| { + let want = unsigned_cases[i].1; + assert_eq!( + got, want, + "{backend}: v_bfe_u32({:#010x}, {}, {}) = {got:#010x}, want {want:#010x}", + inp[0], inp[1], inp[2], + ); + }); +} + +#[test] +fn f16_omod_applies_before_clamp() { + // VOP3 v_add_f16 (0x132 = 0x100 + VOP2 0x32): v0 = (v1 + v2) * omod [clamp] + let mul2 = build_valu_cs(&vop3_mod(0x132, 0, vgpr(1), vgpr(2), 0, 0, 0, 1, false)); + let mul4 = build_valu_cs(&vop3_mod(0x132, 0, vgpr(1), vgpr(2), 0, 0, 0, 2, false)); + let div2 = build_valu_cs(&vop3_mod(0x132, 0, vgpr(1), vgpr(2), 0, 0, 0, 3, false)); + let div2_clamp = build_valu_cs(&vop3_mod(0x132, 0, vgpr(1), vgpr(2), 0, 0, 0, 3, true)); + + // f16 constants: 0.25=0x3400, 0.5=0x3800, 0.75=0x3A00, 1.0=0x3C00, 1.5=0x3E00, 2.0=0x4000, -0.5=0xB800 + run_cases( + &mul2, + &[[0x3400, 0x3800, 0, 0]], // (0.25 + 0.5) * 2 = 1.5 (0x3E00) + |backend, _, _, got| { + assert_eq!(got as u16, 0x3E00, "{backend}: v_add_f16 mul:2"); + }, + ); + run_cases( + &mul4, + &[[0x3400, 0x3400, 0, 0]], // (0.25 + 0.25) * 4 = 2.0 (0x4000) + |backend, _, _, got| { + assert_eq!(got as u16, 0x4000, "{backend}: v_add_f16 mul:4"); + }, + ); + run_cases( + &div2, + &[[0x3E00, 0x3E00, 0, 0]], // (1.5 + 1.5) / 2 = 1.5 (0x3E00) + |backend, _, _, got| { + assert_eq!(got as u16, 0x3E00, "{backend}: v_add_f16 div:2"); + }, + ); + // Ordering check: (0.75 + 0.75) = 1.5; div:2 before clamp gives 0.75 (0x3A00), + // whereas clamp before div:2 would give 0.5 (0x3800). + let clamp_cases: &[(u16, u16, u16)] = &[ + (0x3A00, 0x3A00, 0x3A00), // (0.75 + 0.75) / 2 = 0.75 -> 0.75 + (0x3E00, 0x3E00, 0x3C00), // (1.5 + 1.5) / 2 = 1.5 -> clamped to 1.0 + (0xB800, 0xB800, 0x0000), // (-0.5 + -0.5) / 2 = -0.5 -> clamped to 0.0 + ]; + let inputs: Vec<[u32; 4]> = clamp_cases + .iter() + .map(|&(a, b, _)| [u32::from(a), u32::from(b), 0, 0]) + .collect(); + run_cases(&div2_clamp, &inputs, |backend, i, _, got| { + let want = clamp_cases[i].2; + assert_eq!( + got as u16, want, + "{backend}: v_add_f16 div:2 clamp case {i}: got {:#06x}, want {want:#06x}", + got as u16, + ); + }); +} + +#[test] +fn cvt_16bit_int_from_f16_saturates_and_honors_modifiers() { + // VOP3 v_cvt_u16_f16 = 0x1D2 (0x180 + VOP1 0x52) + // VOP3 v_cvt_i16_f16 = 0x1D3 (0x180 + VOP1 0x53) + let cvt_u16 = build_valu_cs(&vop3_mod(0x1D2, 0, vgpr(1), 0, 0, 0, 0, 0, false)); + let cvt_u16_abs = build_valu_cs(&vop3_mod(0x1D2, 0, vgpr(1), 0, 0, 1, 0, 0, false)); + let cvt_i16 = build_valu_cs(&vop3_mod(0x1D3, 0, vgpr(1), 0, 0, 0, 0, 0, false)); + let cvt_i16_neg = build_valu_cs(&vop3_mod(0x1D3, 0, vgpr(1), 0, 0, 0, 1, 0, false)); + + let u16_cases: &[(u16, u16)] = &[ + (0xBC00, 0), // -1.0 -> 0 + (0xFC00, 0), // -inf -> 0 + (0x7E00, 0), // NaN -> 0 + (0x57BC, 123), // 123.75 -> 123 + (0x7BFF, 65504), // 65504.0 (max finite f16) -> 65504 + (0x7C00, 0xFFFF), // +inf -> 65535 (saturated) + ]; + let u16_in: Vec<[u32; 4]> = u16_cases.iter().map(|&(x, _)| [u32::from(x), 0, 0, 0]).collect(); + run_cases(&cvt_u16, &u16_in, |backend, i, inp, got| { + let want = u16_cases[i].1; + assert_eq!( + got as u16, want, + "{backend}: v_cvt_u16_f16({:#06x}) = {:#06x}, want {want:#06x}", + inp[0], got as u16, + ); + }); + run_cases( + &cvt_u16_abs, + &[[0xD7BC, 0, 0, 0]], // |-123.75| -> 123 + |backend, _, _, got| { + assert_eq!(got as u16, 123, "{backend}: v_cvt_u16_f16 |src0|"); + }, + ); + + let i16_cases: &[(u16, u16)] = &[ + (0xFC00, 0x8000), // -inf -> -32768 + (0xF8E2, 0x8000), // -40000.0 -> -32768 (saturated, not wrapped) + (0xD7BC, (-123i16) as u16), // -123.75 -> -123 + (0x7E00, 0), // NaN -> 0 + (0x57BC, 123), // 123.75 -> 123 + (0x78E2, 0x7FFF), // +40000.0 -> 32767 (saturated, not wrapped) + (0x7C00, 0x7FFF), // +inf -> 32767 + ]; + let i16_in: Vec<[u32; 4]> = i16_cases.iter().map(|&(x, _)| [u32::from(x), 0, 0, 0]).collect(); + run_cases(&cvt_i16, &i16_in, |backend, i, inp, got| { + let want = i16_cases[i].1; + assert_eq!( + got as u16, want, + "{backend}: v_cvt_i16_f16({:#06x}) = {:#06x}, want {want:#06x}", + inp[0], got as u16, + ); + }); + run_cases( + &cvt_i16_neg, + &[[0x57BC, 0, 0, 0], [0x78E2, 0, 0, 0]], // -(123.75) -> -123; -(40000.0) -> -32768 + |backend, i, _, got| { + let want = [(-123i16) as u16, 0x8000][i]; + assert_eq!(got as u16, want, "{backend}: v_cvt_i16_f16 -src0 case {i}"); + }, + ); +} + +const S_BARRIER: u32 = 0xBF8A_0000; + +/// VOP2 `op vdst, src0, vsrc1`. +const fn vop2(op: u8, vdst: u8, src0: u16, vsrc1: u8) -> u32 { + (op as u32 & 0x3F) << 25 | (vdst as u32) << 17 | (vsrc1 as u32) << 9 | (src0 as u32 & 0x1FF) +} + +/// DS `op vdst, addr, data0` at offset 0. +const fn ds(op: u8, vdst: u8, addr: u8, data0: u8) -> [u32; 2] { + [ + 0x36 << 26 | (op as u32) << 18, + (vdst as u32) << 24 | (data0 as u32) << 8 | addr as u32, + ] +} + +const DS_WRITE_B32: u8 = 0x0D; +const DS_MIN_F32: u8 = 0x12; +const DS_MAX_F32: u8 = 0x13; +const DS_MIN_RTN_F32: u8 = 0x32; +const DS_MAX_RTN_F32: u8 = 0x33; +const DS_READ_B32: u8 = 0x36; + +/// What RDNA2 writes for `ds_max_f32` / `ds_min_f32` over a dword holding +/// `old` with `data` (bits), as measured on gfx1036 with f32 denormals kept: +/// an sNaN, data first, then memory, is written quieted; otherwise a NaN +/// loses to a number (two quiet NaNs give the data); numbers compare as +/// floats with -0 below +0. +fn lds_min_max_ref(old: u32, data: u32, max: bool) -> u32 { + let nan = |x: u32| x & 0x7FFF_FFFF > 0x7F80_0000; + let snan = |x: u32| nan(x) && x & 0x40_0000 == 0; + let key = |x: u32| { + let b = x as i32; + if b < 0 { b ^ 0x7FFF_FFFF } else { b } + }; + if snan(data) { + return data | 0x40_0000; + } + if snan(old) { + return old | 0x40_0000; + } + match (nan(data), nan(old)) { + (true, true) | (false, true) => return data, + (true, false) => return old, + (false, false) => {} + } + let take = if max { + key(data) > key(old) + } else { + key(data) < key(old) + }; + if take { data } else { old } +} + +#[test] +fn ds_min_max_f32_order_floats_and_return_the_old_value() { + let values = [ + 0.0f32, + -0.0, + 1.0, + -1.0, + 2.5, + -2.5, + 1e-30, + -1e-30, + f32::from_bits(1), // denormal + f32::from_bits(0x8000_0001), + f32::INFINITY, + f32::NEG_INFINITY, + f32::MAX, + f32::MIN, + ]; + // Quiet and signalling NaNs of both signs, in memory and as data. + let nans = [ + 0x7FC0_0000u32, + 0xFFC0_0000, + 0x7F80_0001, + 0xFFA0_0000, + 0x7FBF_FFFF, + ]; + let bits: Vec = values.iter().map(|v| v.to_bits()).chain(nans).collect(); + let mut cases: Vec<[u32; 4]> = Vec::new(); + for &old in &bits { + for &data in &bits { + cases.push([old, data, 0, 0]); + } + } + for (rtn, plain, max, what) in [ + (DS_MAX_RTN_F32, DS_MAX_F32, true, "ds_max"), + (DS_MIN_RTN_F32, DS_MIN_F32, false, "ds_min"), + ] { + // v5 = 0; LDS[v5] = v1; the atomic with v2; v0 = the old value + // (rtn) or the dword afterwards (read back). + let mut returns_old = vec![vop1(0x001, 5, 0x80)]; + returns_old.extend(ds(DS_WRITE_B32, 0, 5, 1)); + returns_old.extend(ds(rtn, 0, 5, 2)); + let mut returns_new = vec![vop1(0x001, 5, 0x80)]; + returns_new.extend(ds(DS_WRITE_B32, 0, 5, 1)); + returns_new.extend(ds(plain, 0, 5, 2)); + returns_new.extend(ds(DS_READ_B32, 0, 5, 0)); + for (body, old_result) in [(returns_old, true), (returns_new, false)] { + // One thread with LDS declares WaveSize(32), which WARP's + // pipeline creation refuses: hardware only (the 64-thread test + // below runs on WARP too). + let shader = build_cs(&body, 1, 512); + run_cases_on( + &shader, + &cases, + &[("hardware", false)], + |backend, _, inp, got| { + let (old, data) = (f32::from_bits(inp[0]), f32::from_bits(inp[1])); + let want = if old_result { + inp[0] + } else { + lds_min_max_ref(inp[0], inp[1], max) + }; + assert_eq!( + got, + want, + "{backend}: {what}_f32 on {old:e} [{:#010x}] with {data:e} [{:#010x}] gave {got:#010x}, want {want:#010x} ({})", + inp[0], + inp[1], + if old_result { + "old value" + } else { + "dword after" + }, + ); + }, + ); + } + } +} + +#[test] +fn ds_min_max_f32_are_atomic_across_waves() { + // 64 threads (two host waves of 32 or one of 64): LDS[0] = v1, then + // every thread applies (thread - 32) as a float; v0 = LDS[0]. + for (op, max, init, want) in [ + (DS_MAX_F32, true, f32::NEG_INFINITY, 31.0f32), + (DS_MAX_F32, true, 100.0, 100.0), + (DS_MIN_F32, false, f32::INFINITY, -32.0), + (DS_MIN_F32, false, -0.0, -32.0), + ] { + let mut body = vec![vop1(0x001, 5, 0x80)]; + body.extend(ds(DS_WRITE_B32, 0, 5, 1)); + body.push(S_BARRIER); + body.push(vop2(0x26, 6, vgpr(0), 3)); // v_sub_nc_u32 v6, v0, v3 + body.push(vop1(0x005, 6, vgpr(6))); // v_cvt_f32_i32 + body.extend(ds(op, 0, 5, 6)); + body.push(S_BARRIER); + body.extend(ds(DS_READ_B32, 0, 5, 0)); + let shader = build_cs(&body, 64, 512); + run_cases( + &shader, + &[[init.to_bits(), 0, 32, 0]], + |backend, _, _, got| { + assert_eq!( + f32::from_bits(got), + want, + "{backend}: {} from {init} over 64 threads", + if max { "max" } else { "min" }, + ); + }, + ); + } +} + +#[test] +fn v_cmp_class_f16_matches_rdna2() { + // v_cmp_class_f16_e64 s6, v1, v2 (VOP3 opcode 0x08f); v_cndmask_b32_e64 v0, 0, 1, s6 + let cmp_lo = build_valu_cs(&[ + vop3(0x08f, 6, vgpr(1), vgpr(2), 0)[0], + vop3(0x08f, 6, vgpr(1), vgpr(2), 0)[1], + vop3(0x101, 0, 0x80, 0x81, sgpr(6))[0], + vop3(0x101, 0, 0x80, 0x81, sgpr(6))[1], + ]); + // Same with op_sel:[1,0] (high half of v1) + neg on src0 (bit 29 of w1). + let [mut w0, mut w1] = vop3(0x08f, 6, vgpr(1), vgpr(2), 0); + w0 |= 1 << 11; // opsel[0] = 1 (high half) + w1 |= 1 << 29; // neg[0] = 1 + let cmp_hi_neg = build_valu_cs(&[ + w0, + w1, + vop3(0x101, 0, 0x80, 0x81, sgpr(6))[0], + vop3(0x101, 0, 0x80, 0x81, sgpr(6))[1], + ]); + + // All 10 IEEE-754 binary16 classes: bit k corresponds to class k. + let classes: &[(u32, u32)] = &[ + (0x7C01, 0), // sNaN (+sNaN, quiet bit 0x0200 clear) + (0xFDFF, 0), // -sNaN (sign ignored for NaNs) + (0x7E00, 1), // +qNaN + (0xFE01, 1), // -qNaN + (0xFC00, 2), // -inf + (0xBC00, 3), // -normal (-1.0) + (0x8001, 4), // -denormal + (0x8000, 5), // -0.0 + (0x0000, 6), // +0.0 + (0x0001, 7), // +denormal + (0x3C00, 8), // +normal (+1.0) + (0x7C00, 9), // +inf + ]; + let mut cases = Vec::new(); + for &(bits, cls) in classes { + // Exact class bit -> true; complement of class bit across all 10 bits -> false. + cases.push(([bits, 1u32 << cls, 0, 0], 1u32)); + cases.push(([bits, 0x3FF & !(1u32 << cls), 0, 0], 0u32)); + } + let inputs: Vec<[u32; 4]> = cases.iter().map(|c| c.0).collect(); + run_cases(&cmp_lo, &inputs, |backend, i, inp, got| { + let want = cases[i].1; + assert_eq!( + got, want, + "{backend}: v_cmp_class_f16({:#06x}, {:#05x}) = {got}, want {want}", + inp[0], inp[1], + ); + }); + + // High half with neg: high half 0x3C00 (+1.0) negated -> -normal (class 3); + // high half 0x7C01 (+sNaN) negated -> still sNaN (class 0, not quieted). + let hi_cases: &[([u32; 4], u32)] = &[ + ([0x3C00_0000, 1 << 3, 0, 0], 1), + ([0x3C00_0000, 1 << 8, 0, 0], 0), + ([0x7C01_FFFF, 1 << 0, 0, 0], 1), + ([0x7C01_FFFF, 1 << 1, 0, 0], 0), + ]; + let hi_in: Vec<[u32; 4]> = hi_cases.iter().map(|c| c.0).collect(); + run_cases(&cmp_hi_neg, &hi_in, |backend, i, inp, got| { + let want = hi_cases[i].1; + assert_eq!( + got, want, + "{backend}: v_cmp_class_f16(-hi({:#010x}), {:#05x}) = {got}, want {want}", + inp[0], inp[1], + ); + }); +} + +#[test] +fn v_cvt_f32_f64_matches_ieee754() { + // v_cvt_f32_f64 v0, v[1:2] (VOP1 opcode 0x00f -> VOP3 opcode 0x18f). + let plain = build_valu_cs(&[vop1(0x00f, 0, vgpr(1))]); + // Same with abs + neg on src0 (VOP3: abs[0] = bit 8 of w0, neg[0] = bit 29 of w1). + let [mut w0, mut w1] = vop3(0x18f, 0, vgpr(1), 0, 0); + w0 |= 1 << 8; + w1 |= 1 << 29; + let neg_abs = build_valu_cs(&[w0, w1]); + + let values: &[f64] = &[ + 0.0, + -0.0, + 1.0, + -1.0, + 3.5, + -123456.75, + // Tie-to-even: even mantissa stays, odd mantissa rounds up. + f64::from_bits(0x3FF0_0000_1000_0000), // 1.0 + 0.5 ulp(f32) -> 1.0 + f64::from_bits(0x3FF0_0000_3000_0000), // (1.0 + 1 ulp) + 0.5 ulp -> 1.0 + 2 ulp + f64::from_bits(0x3FF0_0000_1000_0001), // > 0.5 ulp -> rounds up + // Largest finite f32 and overflow to +Inf / -Inf. + f64::from(f32::MAX), + f64::from(f32::MAX) * 1.000_001, + -f64::from(f32::MAX) * 1.000_001, + 1e300, + // Subnormal range (exp64 in [874, 896]), including carry into smallest normal. + f64::from(f32::MIN_POSITIVE), + f64::from(f32::MIN_POSITIVE) * 0.5, + f64::from(f32::MIN_POSITIVE) * 0.75, + f64::from(f32::from_bits(0x007F_FFFF)), + f64::from_bits(0x380F_FFFF_F000_0000), // max subnormal + 0.5 ulp -> min normal + // exp64 == 873: exact 2^-150 ties to 0; strictly greater rounds to min subnormal (1). + f64::from_bits(0x3690_0000_0000_0000), + f64::from_bits(0x3690_0000_0000_0001), + f64::from_bits(0xB690_0000_0000_0001), + // Deep underflow -> +/-0.0. + 1e-200, + -1e-200, + // Infinities and NaNs. + f64::INFINITY, + f64::NEG_INFINITY, + f64::from_bits(0x7FF8_0000_0000_0000), // +qNaN + f64::from_bits(0x7FF0_0000_0000_0001), // +sNaN -> quieted + ]; + let inputs: Vec<[u32; 4]> = values + .iter() + .map(|&x| { + let b = x.to_bits(); + [b as u32, (b >> 32) as u32, 0, 0] + }) + .collect(); + run_cases(&plain, &inputs, |backend, i, _, got| { + let x = values[i]; + let want = (x as f32).to_bits(); + if x.is_nan() { + assert!( + f32::from_bits(got).is_nan() && (got & 0x0040_0000) != 0, + "{backend}: v_cvt_f32_f64({:#018x}) = {got:#010x}, expected qNaN", + x.to_bits(), + ); + } else { + assert_eq!( + got, want, + "{backend}: v_cvt_f32_f64({x} / {:#018x}) = {got:#010x}, want {want:#010x}", + x.to_bits(), + ); + } + }); + + // -|x| via VOP3 abs + neg modifiers. + let mod_values: &[f64] = &[2.5, -2.5, 0.0, f64::INFINITY]; + let mod_in: Vec<[u32; 4]> = mod_values + .iter() + .map(|&x| { + let b = x.to_bits(); + [b as u32, (b >> 32) as u32, 0, 0] + }) + .collect(); + run_cases(&neg_abs, &mod_in, |backend, i, _, got| { + let x = mod_values[i]; + let want = (-(x.abs()) as f32).to_bits(); + assert_eq!( + got, want, + "{backend}: v_cvt_f32_f64(-|{x}|) = {got:#010x}, want {want:#010x}", + ); + }); +} + +#[test] +fn whole_wave_f64_sum_and_cvt_f32_f64() { + let s_or_saveexec_b32 = + |sdst: u8, src0: u8| 0xBE80_0000 | (sdst as u32) << 16 | 0x3D << 8 | src0 as u32; + 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 words = Vec::new(); + words.push(s_mov_b32(5, 0x80)); + words.extend_from_slice(&s_load_dwordx4(8, 4)); + // Per-lane f64 input in v[6:7] = (s0, s1). + words.push(vop1(0x001, 6, sgpr(0))); + words.push(vop1(0x001, 7, sgpr(1))); + // Whole-wave f64 sum over Wave32 with s_mov_b32 copy before EXEC restore. + words.push(s_or_saveexec_b32(12, 0xC1)); + words.extend_from_slice(&vop3(0x101, 2, 0x80, vgpr(6), sgpr(12))); + words.extend_from_slice(&vop3(0x101, 3, 0x80, vgpr(7), sgpr(12))); + for sel in [14570689u32, 9658386, 2340] { + words.extend_from_slice(&v_mov_dpp8(4, 2, sel)); + words.extend_from_slice(&v_mov_dpp8(5, 3, sel)); + words.extend_from_slice(&vop3(0x164, 2, vgpr(4), vgpr(2), 0)); // v_add_f64 + } + words.extend_from_slice(&v_mov_row_mirror(4, 2)); + words.extend_from_slice(&v_mov_row_mirror(5, 3)); + words.extend_from_slice(&vop3(0x164, 2, vgpr(4), vgpr(2), 0)); + words.extend_from_slice(&vop3(0x378, 4, vgpr(2), 0x80, 0x80)); // v_permlanex16_b32 + words.extend_from_slice(&vop3(0x378, 5, vgpr(3), 0x80, 0x80)); + words.extend_from_slice(&vop3(0x164, 2, vgpr(4), vgpr(2), 0)); + words.extend_from_slice(&vop3(0x360, 14, vgpr(2), 0x80, 0)); // v_readlane_b32 s14, v2, 0 + words.extend_from_slice(&vop3(0x360, 15, vgpr(3), 0x80, 0)); // v_readlane_b32 s15, v3, 0 + words.push(s_mov_b32(16, 14)); + words.push(s_mov_b32(17, 15)); + words.push(s_mov_b32(126, 12)); // restore exec_lo + words.push(vop1(0x00f, 0, sgpr(16))); // v_cvt_f32_f64 v0, s[16:17] + words.extend_from_slice(&buffer_store_dword(0, 8, 0)); + words.push(S_ENDPGM); + + let code: Vec = words.iter().flat_map(|w| w.to_le_bytes()).collect(); + let native = NativeProgram { + stage: HwStage::Cs, + wave64: false, + vgprs: 12, + 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, + threads: [4, 1, 1], + }), + code, + }; + + 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("resource::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"); + + 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()) { + let mut copy = shader.dxil.clone(); + v.validate(&mut copy).expect("DXIL validation failed"); + } + + let cases: &[(f64, f32)] = &[(1.25, 5.0), (-0.75, -3.0)]; + let _one = 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) = match host.compute_pipeline(&shader) { + Ok(p) => p, + // WARP does not support fixed WaveSize(32) on SM 6.6. + Err(e) if warp => { + eprintln!("{label}: compute_pipeline skipped ({e})"); + continue; + } + Err(e) => panic!("{label}: compute_pipeline failed: {e}"), + }; + for &(x, want) in cases { + 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(1)], + samplers: &[], + groups: [1, 1, 1], + }, + ) + .unwrap_or_else(|e| panic!("{label}: dispatch failed: {e}")); + assert_eq!( + out[0][0], + want.to_bits(), + "{label}: wave f64 sum({x}) = {:#010x}, want {:#010x}", + out[0][0], + want.to_bits(), + ); + } + } +} diff --git a/crates/leonida-shader/src/emit/waterfall_tests.rs b/crates/leonida-shader/src/emit/waterfall_tests.rs new file mode 100644 index 000000000..18425e06c --- /dev/null +++ b/crates/leonida-shader/src/emit/waterfall_tests.rs @@ -0,0 +1,251 @@ +//! 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)> { + 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)> { + 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 = (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 = (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 = (0..32).map(|i| 100 + i).collect(); + let second: Vec = (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 = (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 = (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 = (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}"); + } + } +} diff --git a/crates/leonida-shader/src/emit/wave.rs b/crates/leonida-shader/src/emit/wave.rs new file mode 100644 index 000000000..1d7a91b7f --- /dev/null +++ b/crates/leonida-shader/src/emit/wave.rs @@ -0,0 +1,1228 @@ +//! Whole-wave sections (decision 0003): code between `s_or_saveexec -1` +//! (or `s_nand_saveexec 0`) and the restore of the saved mask runs in every lane of the console's +//! wave, the inactive ones included, which is how the compiler expands +//! HLSL wave reductions and prefix sums (an identity put into the inactive +//! lanes with `v_cndmask`, then DPP, `v_permlanex16` and `v_readlane` +//! steps). A host lane that is elsewhere cannot run that code, so each +//! section is simulated on the console's lanes with symbolic values, and a +//! value it leaves is lowered by what it turned out to be: the reduction or +//! prefix of one operation over the lanes' (masked) inputs, which DXIL's +//! wave operations compute over the host's active lanes. No instruction +//! sequence is matched; any step the simulation does not model leaves the +//! values it writes unknown. + +use std::collections::HashMap; + +use crate::gfx10::{Dpp, Fields, NULL, Operand}; +use crate::ir::{EXEC, Inst, Program, Reg, Value}; + +/// An associative operation and its identity. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) enum Op { + AddU, + AddF, + /// A sum of 16-bit floats in the low halves (`v_add_f16`), each addition rounded to 16 + /// bits: not associative, so only the balanced tree over the lanes in their order is + /// followed (see [`buddies`]), which is how the compiler sums a wave. + AddH, + MinU, + MaxU, + MinI, + MaxI, + MinF, + MaxF, + Or, + And, + Xor, +} + +impl Op { + fn of(name: &str) -> Option { + Some(match name { + // the low dword of a 64-bit sum (`v_add_co_ci_u32` carries into + // the high one) is the 32-bit sum of the low dwords + "v_add_nc_u32" | "v_add_co_u32" => Op::AddU, + "v_add_f32" => Op::AddF, + "v_add_f16" => Op::AddH, + "v_min_u32" => Op::MinU, + "v_max_u32" => Op::MaxU, + "v_min_i32" => Op::MinI, + "v_max_i32" => Op::MaxI, + "v_min_f32" => Op::MinF, + "v_max_f32" => Op::MaxF, + "v_or_b32" => Op::Or, + "v_and_b32" => Op::And, + "v_xor_b32" => Op::Xor, + _ => return None, + }) + } + + /// Whether `k` leaves the other operand unchanged. + fn identity(self, k: u32) -> bool { + match self { + Op::AddU | Op::AddH | Op::Or | Op::Xor | Op::MaxU => k == 0, + Op::AddF => k == 0 || k == 0x8000_0000, + Op::MinU | Op::And => k == u32::MAX, + Op::MinI => k == 0x7FFF_FFFF, + Op::MaxI => k == 0x8000_0000, + Op::MinF => k == 0x7F80_0000, + Op::MaxF => k == 0xFF80_0000, + } + } + + /// Counting a lane twice changes the result. + fn counts(self) -> bool { + matches!(self, Op::AddU | Op::AddF | Op::AddH | Op::Xor) + } +} + +/// Whether the lane sets `a` and `b` are the two halves of one aligned run of lanes: lanes +/// 2k and 2k+1, then two such pairs side by side, and so on up to the two halves of the +/// wave. Sums joined only that way form the balanced tree over the lanes in their order, +/// whichever of the two a lane adds to the other (the addition is commutative). +fn buddies(a: u64, b: u64) -> bool { + let n = a.count_ones(); + if n != b.count_ones() || !n.is_power_of_two() || n == 64 { + return false; + } + let run = |s: u64| { + let first = s.trailing_zeros(); + (first.is_multiple_of(n) && s >> first == (1u64 << n) - 1).then_some(first) + }; + match (run(a), run(b)) { + (Some(x), Some(y)) => x.min(y) % (2 * n) == 0 && x.abs_diff(y) == n, + _ => false, + } +} + +/// A lane's value inside a section. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) enum Sym { + Unknown, + K(u32), + /// The lane's own value of a VGPR value from before the section. + Own(Value), + /// A uniform value from before the section. + Uni(Value), + /// `op` over `lanes` of `mask ? src : ident` (`op` none: one lane). + Red { + op: Option, + src: Value, + mask: Value, + ident: u32, + lanes: u64, + }, + /// Low (`!high`) or high (`high`) 32 bits of the 64-bit float sum over + /// `lanes` of `mask ? f64(lo, hi) : 0.0`. + Red64F { + lo: Value, + hi: Value, + mask: Value, + lanes: u64, + high: bool, + }, +} + +/// What a value a section leaves holds in every lane. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) enum Shape { + K(u32), + Value(Value), + /// The lane's own `mask ? src : ident`. + Masked(Value, Value, u32), + /// `op` over every lane. + Active(Op, Value, Value, u32), + /// Low (`!high`) or high (`high`) 32 bits of the 64-bit float sum over every lane. + ActiveF64(Value, Value, Value, bool), + /// `op` over the lanes below (`inclusive`: and including) each lane. + Prefix(Op, Value, Value, u32, bool), +} + +/// The section starting at instruction `start` of a block: its restore +/// index and the shapes of the values it writes. +pub(crate) struct Section { + pub end: usize, + pub shapes: HashMap, +} + +/// Every whole-wave section of `block`, by start index. +pub(crate) fn sections(p: &Program, block: usize) -> HashMap { + let insts = &p.blocks[block].insts; + let wave: u32 = if p.wave64 { 64 } else { 32 }; + let mut out = HashMap::new(); + let mut i = 0; + while i < insts.len() { + let inst = &insts[i]; + // EXEC becomes every lane: `s_or_saveexec -1` or `s_nand_saveexec 0`. + let all = match inst.name() { + "s_or_saveexec_b64" | "s_or_saveexec_b32" => Some(Operand::Const(193)), + "s_nand_saveexec_b64" | "s_nand_saveexec_b32" => Some(Operand::Const(128)), + _ => None, + }; + let start = all.is_some_and( + |k| matches!(&inst.fields, Fields::Sop { src, .. } if src.first() == Some(&k)), + ); + let saved = match &inst.fields { + Fields::Sop { + dst: Some(Operand::Scalar { code, .. }), + .. + } if start => inst.write(Reg::S(*code)), + _ => None, + }; + let Some(saved) = saved else { + i += 1; + continue; + }; + let end = (i + 1..insts.len()).find(|&j| { + insts[j].write(Reg::S(EXEC)).is_some() + && insts[j].read(Reg::S(saved_code(inst))) == Some(saved) + }); + let Some(end) = end else { + break; + }; + let shapes = simulate(&insts[i + 1..end], wave, saved); + out.insert(i, Section { end, shapes }); + i = end + 1; + } + out +} + +fn saved_code(inst: &Inst) -> u8 { + match &inst.fields { + Fields::Sop { + dst: Some(Operand::Scalar { code, .. }), + .. + } => *code, + _ => NULL, + } +} + +/// The lane `l` reads with DPP, whether it reads 0 instead, and whether it +/// writes; `None` for patterns not modelled. +fn dpp_lane(d: Dpp, l: u32) -> Option<(u32, bool, bool)> { + match d { + Dpp::Lanes { sel, .. } => Some(((l & !7) | (sel >> (3 * (l & 7)) & 7), false, true)), + Dpp::Row { + ctrl, + row_mask, + bank_mask, + bound_ctrl, + .. + } => { + let (row, pos, n) = (l & !15, l & 15, u32::from(ctrl & 15)); + let enabled = row_mask >> (l >> 4 & 3) & 1 != 0 && bank_mask >> (l >> 2 & 3) & 1 != 0; + let (src, inside) = match ctrl { + 0..=0xFF => ((l & !3) | (u32::from(ctrl) >> (2 * (l & 3)) & 3), true), + 0x101..=0x10F => (l + n, pos + n < 16), + 0x111..=0x11F => (l.wrapping_sub(n), pos >= n), + 0x121..=0x12F => (row | (pos.wrapping_sub(n) & 15), true), + 0x140 => (l ^ 15, true), + 0x141 => (l ^ 7, true), + 0x150..=0x15F => (row | n, true), + 0x160..=0x16F => (l ^ n, true), + _ => return None, + }; + match (inside, bound_ctrl) { + (true, _) => Some((src, false, enabled)), + (false, true) => Some((l, true, enabled)), + (false, false) => Some((l, false, false)), + } + } + } +} + +fn combine(op: Op, a: Sym, b: Sym) -> Sym { + match (a, b) { + (Sym::K(k), x) | (x, Sym::K(k)) if op.identity(k) => x, + ( + Sym::Red { + op: oa, + src, + mask, + ident, + lanes: la, + }, + Sym::Red { + op: ob, + src: sb, + mask: mb, + ident: ib, + lanes: lb, + }, + ) if (src, mask, ident) == (sb, mb, ib) + && op.identity(ident) + && oa.is_none_or(|o| o == op) + && ob.is_none_or(|o| o == op) + && (!op.counts() || la & lb == 0) + && (op != Op::AddH || buddies(la, lb)) => + { + Sym::Red { + op: Some(op), + src, + mask, + ident, + lanes: la | lb, + } + } + _ => Sym::Unknown, + } +} + +fn simulate(insts: &[Inst], wave: u32, saved: Value) -> HashMap { + let all = if wave == 64 { + u64::MAX + } else { + u64::from(u32::MAX) + }; + let mut exec = all; + let mut vec: HashMap> = HashMap::new(); + let mut uni: HashMap = HashMap::new(); + // Masks the section derives from the saved EXEC (`s_and` with it). + let mut masked = vec![saved]; + for inst in insts { + let name = inst.name(); + if inst.write(Reg::S(EXEC)).is_some() { + // Constant lane sets (prefix sums); anything else ends what + // the simulation can follow. + let lo = name + .starts_with("s_mov_b") + .then(|| constant(inst)) + .flatten(); + let Some(k) = lo else { + return shapes(vec, uni, wave); + }; + exec = (if name == "s_mov_b64" { + k + } else { + (exec & !0xFFFF_FFFF) | (k & 0xFFFF_FFFF) + }) & all; + continue; + } + if inst.write(Reg::S(EXEC + 1)).is_some() { + let Some(k) = name + .starts_with("s_mov_b") + .then(|| constant(inst)) + .flatten() + else { + return shapes(vec, uni, wave); + }; + exec = ((exec & 0xFFFF_FFFF) | ((k & 0xFFFF_FFFF) << 32)) & all; + continue; + } + if let Fields::Sop { dst, src, .. } = &inst.fields { + if name.starts_with("s_and_b") + && src.iter().any(|o| matches!(*o, Operand::Scalar { code, .. } if inst.read(Reg::S(code)).is_some_and(|v| masked.contains(&v)))) + && let Some(&(_, w)) = inst.writes.iter().find(|w| matches!(w.0, Reg::S(_))) + { + masked.push(w); + } + if name == "s_mov_b32" + && let (Some(Operand::Scalar { code: dc, .. }), Some(s0)) = (dst, src.first()) + && *dc != NULL + && let Some(w) = inst.write(Reg::S(*dc)) + { + let sym = match *s0 { + Operand::Scalar { code, .. } if code != NULL => inst + .read(Reg::S(code)) + .map_or(Sym::Unknown, |x| uni.get(&x).copied().unwrap_or(Sym::Uni(x))), + Operand::Const(c) => crate::resource::inline(c).map_or(Sym::Unknown, Sym::K), + Operand::Literal(x) => Sym::K(x), + _ => Sym::Unknown, + }; + uni.insert(w, sym); + } + for &(_, w) in &inst.writes { + uni.entry(w).or_insert(Sym::Unknown); + } + continue; + } + let Fields::Valu(v) = &inst.fields else { + for &(_, w) in &inst.writes { + vec.insert(w, vec![Sym::Unknown; wave as usize]); + } + continue; + }; + let lanes = |op: &Operand, + vec: &HashMap>, + uni: &HashMap| + -> Vec { + let one = |s: Sym| vec![s; wave as usize]; + match *op { + Operand::Vector { reg, .. } => match inst.read(Reg::V(reg)) { + Some(x) => vec + .get(&x) + .cloned() + .unwrap_or_else(|| (0..wave).map(|_| Sym::Own(x)).collect()), + None => one(Sym::Unknown), + }, + Operand::Scalar { code, .. } if code != NULL => match inst.read(Reg::S(code)) { + Some(x) => one(uni.get(&x).copied().unwrap_or(Sym::Uni(x))), + None => one(Sym::Unknown), + }, + Operand::Const(c) => one(crate::resource::inline(c).map_or(Sym::Unknown, Sym::K)), + Operand::Literal(x) => one(Sym::K(x)), + _ => one(Sym::Unknown), + } + }; + let modifiers = v.abs != 0 || v.neg != 0 || v.clamp || v.omod != 0 || v.sdwa.is_some(); + if name == "v_readlane_b32" { + let (Some(Operand::Scalar { code, .. }), Some(src), Some(lane)) = + (v.dst, v.src.first(), v.src.get(1)) + else { + continue; + }; + let l = match *lane { + Operand::Const(c) => crate::resource::inline(c), + Operand::Literal(x) => Some(x), + _ => None, + }; + let x = lanes(src, &vec, &uni); + if let Some(w) = inst.write(Reg::S(code)) { + let s = l + .and_then(|l| x.get(l as usize).copied()) + .unwrap_or(Sym::Unknown); + uni.insert(w, s); + } + continue; + } + if name == "v_add_f64" + && !modifiers + && v.dpp.is_none() + && let Some(Operand::Vector { reg: dreg, .. }) = v.dst + && let (Some(dst_lo), Some(dst_hi)) = + (inst.write(Reg::V(dreg)), inst.write(Reg::V(dreg + 1))) + { + let pair_lanes = |op: Option<&Operand>| -> Option<(Vec, Vec)> { + match *op? { + Operand::Vector { reg, .. } => Some(( + lanes(&Operand::Vector { reg, dwords: 1 }, &vec, &uni), + lanes( + &Operand::Vector { + reg: reg + 1, + dwords: 1, + }, + &vec, + &uni, + ), + )), + Operand::Scalar { code, .. } if code != NULL => Some(( + lanes(&Operand::Scalar { code, dwords: 1 }, &vec, &uni), + lanes( + &Operand::Scalar { + code: code + 1, + dwords: 1, + }, + &vec, + &uni, + ), + )), + _ => None, + } + }; + let old_lo = lanes( + &Operand::Vector { + reg: dreg, + dwords: 1, + }, + &vec, + &uni, + ); + let old_hi = lanes( + &Operand::Vector { + reg: dreg + 1, + dwords: 1, + }, + &vec, + &uni, + ); + let f64_term = |lo_s: Sym, hi_s: Sym| -> Option<(Value, Value, Value, u64)> { + match (lo_s, hi_s) { + ( + Sym::Red { + op: None, + src: lo, + mask: ml, + ident: 0, + lanes: ll, + }, + Sym::Red { + op: None, + src: hi, + mask: mh, + ident: 0, + lanes: lh, + }, + ) if ml == mh && ll == lh => Some((lo, hi, ml, ll)), + ( + Sym::Red64F { + lo: lo1, + hi: hi1, + mask: m1, + lanes: l1, + high: false, + }, + Sym::Red64F { + lo: lo2, + hi: hi2, + mask: m2, + lanes: l2, + high: true, + }, + ) if (lo1, hi1, m1, l1) == (lo2, hi2, m2, l2) => Some((lo1, hi1, m1, l1)), + _ => None, + } + }; + let mut out_lo = vec![Sym::Unknown; wave as usize]; + let mut out_hi = vec![Sym::Unknown; wave as usize]; + if let (Some((alo, ahi)), Some((blo, bhi))) = + (pair_lanes(v.src.first()), pair_lanes(v.src.get(1))) + { + for l in 0..wave as usize { + let (rl, rh) = match (f64_term(alo[l], ahi[l]), f64_term(blo[l], bhi[l])) { + (Some((lo1, hi1, m1, la)), Some((lo2, hi2, m2, lb))) + if (lo1, hi1, m1) == (lo2, hi2, m2) && la & lb == 0 => + { + ( + Sym::Red64F { + lo: lo1, + hi: hi1, + mask: m1, + lanes: la | lb, + high: false, + }, + Sym::Red64F { + lo: lo1, + hi: hi1, + mask: m1, + lanes: la | lb, + high: true, + }, + ) + } + _ => (Sym::Unknown, Sym::Unknown), + }; + out_lo[l] = if exec >> l & 1 != 0 { rl } else { old_lo[l] }; + out_hi[l] = if exec >> l & 1 != 0 { rh } else { old_hi[l] }; + } + } + vec.insert(dst_lo, out_lo); + vec.insert(dst_hi, out_hi); + continue; + } + let Some(Operand::Vector { reg: dreg, .. }) = v.dst else { + for &(_, w) in &inst.writes { + uni.insert(w, Sym::Unknown); + } + continue; + }; + let Some(dst) = inst.write(Reg::V(dreg)) else { + continue; + }; + let old = lanes( + &Operand::Vector { + reg: dreg, + dwords: 1, + }, + &vec, + &uni, + ); + // src0 as each lane fetches it (DPP), with the lanes that write. + let src0 = v.src.first().map(|o| lanes(o, &vec, &uni)); + let mut writes = exec; + let fetched: Option> = match (v.dpp, &src0) { + (Some(d), Some(s)) => { + if exec != all { + vec.insert(dst, vec![Sym::Unknown; wave as usize]); + continue; + } + let mut f = Vec::with_capacity(wave as usize); + let mut ok = true; + for l in 0..wave { + match dpp_lane(d, l) { + Some((src, zero, on)) if src < wave => { + f.push(if zero { Sym::K(0) } else { s[src as usize] }); + if !on { + writes &= !(1u64 << l); + } + } + _ => ok = false, + } + } + ok.then_some(f) + } + (None, Some(s)) => Some(s.clone()), + _ => None, + }; + let src = |k: usize| v.src.get(k).map(|o| lanes(o, &vec, &uni)); + let result: Vec = match (name, fetched) { + _ if modifiers => vec![Sym::Unknown; wave as usize], + ("v_mov_b32", Some(a)) => a, + ("v_bfrev_b32", Some(a)) => a + .into_iter() + .map(|s| match s { + Sym::K(k) => Sym::K(k.reverse_bits()), + _ => Sym::Unknown, + }) + .collect(), + ("v_cndmask_b32", Some(a)) => { + let mask = match v.src.get(2) { + Some(&Operand::Scalar { code, .. }) => inst.read(Reg::S(code)), + _ => None, + }; + let b = src(1).unwrap_or_default(); + (0..wave as usize) + .map(|l| match (a[l], b.get(l).copied(), mask) { + (Sym::K(ident), Some(Sym::Own(x)), Some(m)) if masked.contains(&m) => { + Sym::Red { + op: None, + src: x, + mask: m, + ident, + lanes: 1 << l, + } + } + _ => Sym::Unknown, + }) + .collect() + } + ("v_permlanex16_b32", Some(a)) => { + // Lanes of each row read the other row of their half; lane + // i's pick is nibble i of {src2, src1}. + let sel = |k: usize| match v.src.get(k) { + Some(&Operand::Const(c)) => crate::resource::inline(c), + Some(&Operand::Literal(x)) => Some(x), + _ => None, + }; + match (sel(1), sel(2)) { + (Some(s1), Some(s2)) => { + let s = u64::from(s1) | u64::from(s2) << 32; + (0..wave) + .map(|l| { + let other = (l & !31) | ((l & 16) ^ 16); + let pick = (s >> (4 * (l & 15)) & 15) as u32; + a[(other | pick) as usize] + }) + .collect() + } + _ => vec![Sym::Unknown; wave as usize], + } + } + ("v_sub_nc_u32", Some(a)) => { + // A prefix sum less the lane's own term: the exclusive one. + let b = src(1).unwrap_or_default(); + (0..wave as usize) + .map(|l| match (a[l], b.get(l).copied()) { + ( + Sym::Red { + op: None | Some(Op::AddU), + src, + mask, + ident: 0, + lanes, + }, + Some(Sym::Red { + op: None | Some(Op::AddU), + src: s2, + mask: m2, + ident: 0, + lanes: l2, + }), + ) if (src, mask) == (s2, m2) && lanes & l2 == l2 => { + let rest = lanes & !l2; + if rest == 0 { + Sym::K(0) + } else { + Sym::Red { + op: Some(Op::AddU), + src, + mask, + ident: 0, + lanes: rest, + } + } + } + _ => Sym::Unknown, + }) + .collect() + } + (n, Some(a)) => match (Op::of(n), src(1)) { + (Some(op), Some(b)) => (0..wave as usize) + .map(|l| combine(op, a[l], b[l])) + .collect(), + _ => vec![Sym::Unknown; wave as usize], + }, + _ => vec![Sym::Unknown; wave as usize], + }; + let merged = (0..wave as usize) + .map(|l| { + if writes >> l & 1 != 0 { + result[l] + } else { + old[l] + } + }) + .collect(); + vec.insert(dst, merged); + } + shapes(vec, uni, wave) +} + +fn constant(inst: &Inst) -> Option { + let Fields::Sop { src, .. } = &inst.fields else { + return None; + }; + let wide = inst.name() == "s_mov_b64"; + match *src.first()? { + Operand::Scalar { code: NULL, .. } => Some(0), + Operand::Const(c @ 128..=208) => { + let x = crate::resource::inline(c)?; + Some(if wide { + i64::from(x as i32) as u64 + } else { + u64::from(x) + }) + } + Operand::Const(c) if !wide => crate::resource::inline(c).map(u64::from), + Operand::Literal(x) => Some(u64::from(x)), + _ => None, + } +} + +/// The shape of each value, where every lane agrees on one. +fn shapes( + vec: HashMap>, + uni: HashMap, + wave: u32, +) -> HashMap { + let all = if wave == 64 { + u64::MAX + } else { + u64::from(u32::MAX) + }; + let mut out = HashMap::new(); + let single = |s: Sym| match s { + Sym::K(k) => Some(Shape::K(k)), + Sym::Own(x) | Sym::Uni(x) => Some(Shape::Value(x)), + Sym::Red { + op: Some(op), + src, + mask, + ident, + lanes, + } if lanes == all => Some(Shape::Active(op, src, mask, ident)), + Sym::Red64F { + lo, + hi, + mask, + lanes, + high, + } if lanes == all => Some(Shape::ActiveF64(lo, hi, mask, high)), + _ => None, + }; + for (v, s) in uni { + if let Some(sh) = single(s) { + out.insert(v, sh); + } + } + for (v, lanes) in vec { + if let Some(sh) = per_lane(&lanes, all) { + out.insert(v, sh); + } + } + out +} + +fn per_lane(lanes: &[Sym], all: u64) -> Option { + let first = lanes[0]; + let own = |l: usize, s: Sym| match s { + Sym::Red { + op: None, + src, + mask, + ident, + lanes, + } if lanes == 1 << l => Some((src, mask, ident)), + _ => None, + }; + if let Some(m) = own(0, first) + && lanes.iter().enumerate().all(|(l, &s)| own(l, s) == Some(m)) + { + return Some(Shape::Masked(m.0, m.1, m.2)); + } + if lanes.iter().all(|&s| s == first) { + return match first { + Sym::K(k) => Some(Shape::K(k)), + Sym::Uni(x) | Sym::Own(x) => Some(Shape::Value(x)), + Sym::Red { + op: Some(op), + src, + mask, + ident, + lanes, + } if lanes == all => Some(Shape::Active(op, src, mask, ident)), + Sym::Red64F { + lo, + hi, + mask, + lanes, + high, + } if lanes == all => Some(Shape::ActiveF64(lo, hi, mask, high)), + _ => None, + }; + } + // Prefixes: lane l holds lanes 0..l (exclusive) or 0..=l (inclusive). + let mut meta: Option<(Value, Value, u32, bool)> = None; + let mut op_found: Option = None; + for (l, &s) in lanes.iter().enumerate() { + let below = (1u64 << l) - 1; + let (op, src, mask, ident, set) = match s { + Sym::Red { + op, + src, + mask, + ident, + lanes, + } => (op, src, mask, ident, lanes), + // Lane 0 of an exclusive prefix holds the identity. + Sym::K(_) if l == 0 => continue, + _ => return None, + }; + let inclusive = set == below | (1u64 << l); + if !inclusive && set != below { + return None; + } + if l == 0 && !inclusive { + return None; + } + if op.is_none() && set.count_ones() != 1 { + return None; + } + let lane_meta = (src, mask, ident, inclusive); + match meta { + None => meta = Some(lane_meta), + Some(prev) if prev == lane_meta => {} + _ => return None, + } + if let Some(o) = op { + match op_found { + None => op_found = Some(o), + Some(prev) if prev == o => {} + _ => return None, + } + } + } + let (src, mask, ident, inclusive) = meta?; + let op = op_found?; + if !op.identity(ident) { + return None; + } + match lanes[0] { + Sym::K(k) if !inclusive && k == ident => {} + Sym::Red { .. } if inclusive => {} + _ => return None, + } + Some(Shape::Prefix(op, src, mask, ident, inclusive)) +} + +/// `WaveActiveBitOr(v7)` into s7 as the console compiler expands it: every lane takes part, +/// those outside the saved EXEC (s[4:5]) with 0. +#[cfg(test)] +pub(super) const WAVE_OR_V7_TO_S7: [u32; 20] = [ + 0xBE84_25C1, // s_or_saveexec_b64 s[4:5], -1 + 0xD501_0001, + 0x0012_0E80, // v_cndmask_b32 v1, 0, v7, s[4:5] + 0x3802_02E9, + 0xDE54_C101, // v_or_b32 v1, v1, v1 dpp8:[1,0,3,2,5,4,7,6] + 0x3802_02E9, + 0x9360_1201, // v_or_b32 v1, v1, v1 dpp8:[2,2,0,0,6,6,4,4] + 0x3802_02E9, + 0x0009_2401, // v_or_b32 v1, v1, v1 dpp8:[4,4,4,4,0,0,0,0] + 0x3802_02FA, + 0xFF09_4001, // v_or_b32 v1, v1, v1 row_mirror bound_ctrl:1 + 0xD778_0002, + 0x0201_0101, // v_permlanex16_b32 v2, v1, 0, 0 + 0x3802_0302, // v_or_b32 v1, v2, v1 + 0xD760_0007, + 0x0001_4101, // v_readlane_b32 s7, v1, 32 + 0x3802_0207, // v_or_b32 v1, s7, v1 + 0xD760_0007, + 0x0001_0101, // v_readlane_b32 s7, v1, 0 + 0xBEFE_0404, // s_mov_b64 exec, s[4:5] +]; + +#[cfg(test)] +mod tests { + use super::*; + + const S_ENDPGM: u32 = 0xBF81_0000; + + const fn sop1(sdst: u8, op: u8, ssrc0: u8) -> u32 { + 0xBE80_0000 | (sdst as u32) << 16 | (op as u32) << 8 | ssrc0 as u32 + } + + const fn vop1(vdst: u8, op: u8, src0: u16) -> u32 { + (0x3F << 25) | (vdst as u32) << 17 | (op as u32) << 9 | (src0 as u32 & 0x1FF) + } + + const fn vop2(vdst: u8, op: u8, src0: u16, vsrc1: u8) -> u32 { + (op as u32) << 25 | (vdst as u32) << 17 | (vsrc1 as u32) << 9 | (src0 as u32 & 0x1FF) + } + + const fn dpp16(vsrc0: u8, ctrl: u16, row_mask: u8, bank_mask: u8, bound_ctrl: bool) -> u32 { + (row_mask as u32) << 28 + | (bank_mask as u32) << 24 + | (bound_ctrl as u32) << 19 + | (ctrl as u32) << 8 + | vsrc0 as u32 + } + + const fn vop3(vdst: u8, op: u16, src0: u16, src1: u16, src2: u16) -> [u32; 2] { + [ + 0xD400_0000 | (op as u32) << 16 | vdst as u32, + (src0 as u32 & 0x1FF) | ((src1 as u32 & 0x1FF) << 9) | ((src2 as u32 & 0x1FF) << 18), + ] + } + + fn build(words: &[u32], wave64: bool) -> Program { + let code: Vec = words + .iter() + .copied() + .chain(std::iter::once(S_ENDPGM)) + .flat_map(u32::to_le_bytes) + .collect(); + crate::ir::build(&code, wave64, 256).unwrap() + } + + #[test] + fn dpp_lanes_follow_the_isa() { + // row_shr:1 with bound_ctrl: lane 16 reads 0, lane 17 lane 16. + let shr = Dpp::Row { + ctrl: 0x111, + row_mask: 0xF, + bank_mask: 0xF, + bound_ctrl: true, + fi: false, + }; + assert_eq!(dpp_lane(shr, 16), Some((16, true, true))); + assert_eq!(dpp_lane(shr, 17), Some((16, false, true))); + // row_mirror: lane 3 reads lane 12. + let mirror = Dpp::Row { + ctrl: 0x140, + row_mask: 0xF, + bank_mask: 0xF, + bound_ctrl: true, + fi: false, + }; + assert_eq!(dpp_lane(mirror, 3), Some((12, false, true))); + // dpp8 [1,0,3,2,5,4,7,6] swaps neighbours. + let swap = Dpp::Lanes { + sel: 1 | 3 << 6 | 2 << 9 | 5 << 12 | 4 << 15 | 7 << 18 | 6 << 21, + fi: false, + }; + assert_eq!(dpp_lane(swap, 8), Some((9, false, true))); + } + + #[test] + fn prefixes_are_recognised() { + let (x, m) = (Value(1), Value(2)); + let red = |lanes: u64| Sym::Red { + op: Some(Op::AddU), + src: x, + mask: m, + ident: 0, + lanes, + }; + let inclusive: Vec = (0..64).map(|l| red(u64::MAX >> (63 - l))).collect(); + assert_eq!( + per_lane(&inclusive, u64::MAX), + Some(Shape::Prefix(Op::AddU, x, m, 0, true)) + ); + let mut exclusive: Vec = (0..64).map(|l| red((1u64 << l) - 1)).collect(); + exclusive[0] = Sym::K(0); + assert_eq!( + per_lane(&exclusive, u64::MAX), + Some(Shape::Prefix(Op::AddU, x, m, 0, false)) + ); + assert_eq!( + per_lane(&vec![red(u64::MAX); 64], u64::MAX), + Some(Shape::Active(Op::AddU, x, m, 0)) + ); + } + + #[test] + fn constant_decodes_width_and_inline_kinds() { + let b64 = 0x04; + let b32 = 0x03; + let check = |words: &[u32], wave64: bool| -> Option { + let p = build(words, wave64); + constant(&p.blocks[0].insts[0]) + }; + + assert_eq!( + check(&[sop1(EXEC, b64, 194)], true), + Some(0xFFFF_FFFF_FFFF_FFFE) + ); + assert_eq!( + check(&[sop1(EXEC, b64, 196)], true), + Some(0xFFFF_FFFF_FFFF_FFFC) + ); + assert_eq!( + check(&[sop1(EXEC, b64, 208)], true), + Some(0xFFFF_FFFF_FFFF_FFF0) + ); + assert_eq!(check(&[sop1(EXEC, b64, 193)], true), Some(u64::MAX)); + assert_eq!(check(&[sop1(EXEC, b64, NULL)], true), Some(0)); + assert_eq!(check(&[sop1(EXEC, b64, 243)], true), None); + assert_eq!( + check(&[sop1(EXEC, b64, 255), 0x1234_5678], true), + Some(0x1234_5678) + ); + + assert_eq!(check(&[sop1(EXEC, b32, 194)], false), Some(0xFFFF_FFFE)); + assert_eq!(check(&[sop1(EXEC, b32, 243)], false), Some(0xBF80_0000)); + assert_eq!(check(&[sop1(EXEC, b32, NULL)], false), Some(0)); + assert_eq!( + check(&[sop1(EXEC, b32, 255), 0x1234_5678], false), + Some(0x1234_5678) + ); + assert_eq!(check(&[sop1(EXEC, b32, 0)], false), None); + } + + #[test] + fn exec_minus_two_masks_lane_zero_and_enforces_dpp_guard() { + for wave64 in [false, true] { + let mut w = Vec::new(); + let save_op = if wave64 { 0x25 } else { 0x3D }; + let mov_exec = if wave64 { 0x04 } else { 0x03 }; + let push_exec = |w: &mut Vec, k: u8| w.push(sop1(EXEC, mov_exec, k)); + let push_exec_lit = |w: &mut Vec, lit: u32| { + w.push(sop1(EXEC, mov_exec, 255)); + w.push(lit); + }; + + w.push(sop1(0, save_op, 193)); + w.extend(vop3(1, 0x101, 128, 256, 0)); + for shift in [1u16, 2, 4, 8] { + w.push(vop2(1, 0x25, 0xFA, 1)); + w.push(dpp16(1, 0x110 + shift, 0xF, 0xF, false)); + } + w.extend(vop3(2, 0x360, 257, 128 + 15, 0)); + push_exec_lit(&mut w, 0xFFFF_0000); + w.push(vop2(1, 0x25, 2, 1)); + + if wave64 { + w.extend(vop3(2, 0x360, 257, 128 + 31, 0)); + w.push(sop1(EXEC, 0x03, 128)); + w.push(sop1(EXEC + 1, 0x03, 255)); + w.push(0x0000_FFFF); + w.push(vop2(1, 0x25, 2, 1)); + + w.extend(vop3(2, 0x360, 257, 128 + 47, 0)); + w.push(sop1(EXEC, 0x03, 128)); + w.push(sop1(EXEC + 1, 0x03, 255)); + w.push(0xFFFF_0000); + w.push(vop2(1, 0x25, 2, 1)); + } + + push_exec(&mut w, 193); + w.push(vop1(3, 0x01, 257)); + w.push(vop1(3, 0x01, 0xFA)); + w.push(dpp16(1, 0x111, 0xF, 0xF, false)); + + w.extend(vop3(2, 0x360, 257, 128 + 15, 0)); + push_exec_lit(&mut w, 0x0001_0000); + w.push(vop1(3, 0x01, 2)); + + if wave64 { + w.extend(vop3(2, 0x360, 257, 128 + 31, 0)); + w.push(sop1(EXEC, 0x03, 128)); + w.push(sop1(EXEC + 1, 0x03, 129)); + w.push(vop1(3, 0x01, 2)); + + w.extend(vop3(2, 0x360, 257, 128 + 47, 0)); + w.push(sop1(EXEC, 0x03, 128)); + w.push(sop1(EXEC + 1, 0x03, 255)); + w.push(0x0001_0000); + w.push(vop1(3, 0x01, 2)); + } + + push_exec(&mut w, 193); + w.push(vop1(2, 0x01, 128)); + w.push(vop1(5, 0x01, 135)); + push_exec(&mut w, 194); + w.push(vop1(2, 0x01, 259)); + w.push(vop1(4, 0x01, 0xFA)); + w.push(dpp16(5, 0xE4, 0xF, 0xF, false)); + w.push(sop1(EXEC, mov_exec, 0)); + + let p = build(&w, wave64); + let insts = &p.blocks[0].insts; + let saved = insts[0].write(Reg::S(0)).unwrap(); + let v0_in = p + .inputs + .iter() + .find_map(|&(r, v)| (r == Reg::V(0)).then_some(v)) + .unwrap(); + let v2_val = insts[insts.len() - 4].write(Reg::V(2)).unwrap(); + let v4_val = insts[insts.len() - 3].write(Reg::V(4)).unwrap(); + let sec = §ions(&p, 0)[&0]; + assert_eq!( + sec.shapes.get(&v2_val), + Some(&Shape::Prefix(Op::AddU, v0_in, saved, 0, false)) + ); + assert_eq!(sec.shapes.get(&v4_val), None); + } + } + + /// `WaveActiveSum` of 16-bit floats, as compiled in + /// `compute_graph_ops:CS_TransposeVecMatMulAlignedOperation` (0x19c on): the tree the + /// lowering reproduces. A tree in another order is not followed. + #[test] + fn a_sum_of_halves_over_the_wave_is_followed_in_the_order_of_its_tree() { + let words = |first: [u32; 2], second: [u32; 2]| { + [ + 0xBE84_25C1, // s_or_saveexec_b64 s[4:5], -1 + 0xD501_0001, + 0x0012_0E80, // v_cndmask_b32 v1, 0, v7, s[4:5] + first[0], + first[1], + second[0], + second[1], + 0x6402_02E9, + 0x0009_2401, // v_add_f16 v1, v1, v1 dpp8:[4,4,4,4,0,0,0,0] + 0x6402_02FA, + 0xFF09_4001, // v_add_f16 v1, v1, v1 row_mirror bound_ctrl:1 + 0xD778_0002, + 0x0201_0101, // v_permlanex16_b32 v2, v1, 0, 0 + 0x6402_0302, // v_add_f16 v1, v2, v1 + 0xD760_0007, + 0x0001_4101, // v_readlane_b32 s7, v1, 32 + 0x6402_0207, // v_add_f16 v1, s7, v1 + 0xD760_0007, + 0x0001_0101, // v_readlane_b32 s7, v1, 0 + 0xBEFE_0404, // s_mov_b64 exec, s[4:5] + ] + }; + let pairs = [0x6402_02E9, 0xDE54_C101]; // v_add_f16 v1, v1, v1 dpp8:[1,0,3,2,5,4,7,6] + let quads = [0x6402_02E9, 0x9360_1201]; // v_add_f16 v1, v1, v1 dpp8:[2,2,0,0,6,6,4,4] + let shape = |w: &[u32]| { + let p = build(w, true); + let insts = &p.blocks[0].insts; + let saved = insts[0].write(Reg::S(4)).unwrap(); + let v7 = p.inputs.iter().find_map(|&(r, v)| (r == Reg::V(7)).then_some(v)).unwrap(); + // ..., v_readlane_b32 s7, v1, 0; s_mov_b64 exec, s[4:5]; s_endpgm + let total = insts[insts.len() - 3].write(Reg::S(7)).unwrap(); + (sections(&p, 0)[&0].shapes.get(&total).copied(), Shape::Active(Op::AddH, v7, saved, 0)) + }; + let (found, want) = shape(&words(pairs, quads)); + assert_eq!(found, Some(want)); + // lanes two apart first, neighbours second: every lane counted once, but + // (x0 + x2) + (x1 + x3) rounds differently from (x0 + x1) + (x2 + x3) + let (found, _) = shape(&words(quads, pairs)); + assert_eq!(found, None); + } + + #[test] + fn buddies_are_the_two_halves_of_an_aligned_run() { + assert!(buddies(0b01, 0b10)); + assert!(buddies(0b1100, 0b0011)); + assert!(buddies(0xF0, 0x0F)); + assert!(buddies(u64::from(u32::MAX), u64::from(u32::MAX) << 32)); + assert!(!buddies(0b010, 0b100)); // lanes 1 and 2: not one pair + assert!(!buddies(0b0011, 0b110000)); // pairs 0 and 2 + assert!(!buddies(0b0101, 0b1010)); // not runs + assert!(!buddies(0b01, 0b1100)); // unequal + assert!(!buddies(0b11, 0b11)); + } + + #[test] + fn wave32_mov_b64_all_lanes_keeps_exec_masked_for_dpp() { + let w = [ + sop1(0, 0x3D, 193), + vop1(1, 0x01, 135), + sop1(EXEC, 0x04, 193), + vop1(2, 0x01, 0xFA), + dpp16(1, 0xE4, 0xF, 0xF, false), + sop1(EXEC + 1, 0x03, 193), + vop1(3, 0x01, 0xFA), + dpp16(1, 0xE4, 0xF, 0xF, false), + sop1(EXEC, 0x03, 0), + ]; + let p = build(&w, false); + let insts = &p.blocks[0].insts; + let v2_val = insts[3].write(Reg::V(2)).unwrap(); + let v3_val = insts[5].write(Reg::V(3)).unwrap(); + let sec = §ions(&p, 0)[&0]; + assert_eq!(sec.shapes.get(&v2_val), Some(&Shape::K(7))); + assert_eq!(sec.shapes.get(&v3_val), Some(&Shape::K(7))); + } + + #[test] + fn per_lane_prefix_soundness() { + let (v0, v_other, m0, m_other) = (Value(1), Value(2), Value(3), Value(4)); + let red = |op: Option, src: Value, mask: Value, ident: u32, lanes: u64| Sym::Red { + op, + src, + mask, + ident, + lanes, + }; + + for (wave, all) in [(32usize, u64::from(u32::MAX)), (64usize, u64::MAX)] { + let below_mask = |l: usize| if l == 0 { 0 } else { (1u64 << l) - 1 }; + + let mut valid_inc: Vec = (0..wave) + .map(|l| red(Some(Op::AddU), v0, m0, 0, below_mask(l) | (1u64 << l))) + .collect(); + valid_inc[0] = red(None, v0, m0, 0, 1); + assert_eq!( + per_lane(&valid_inc, all), + Some(Shape::Prefix(Op::AddU, v0, m0, 0, true)) + ); + + let mut valid_exc: Vec = (0..wave) + .map(|l| red(Some(Op::AddU), v0, m0, 0, below_mask(l))) + .collect(); + valid_exc[0] = Sym::K(0); + valid_exc[1] = red(None, v0, m0, 0, 1); + assert_eq!( + per_lane(&valid_exc, all), + Some(Shape::Prefix(Op::AddU, v0, m0, 0, false)) + ); + + let mut mixed_other_src = valid_exc.clone(); + mixed_other_src[0] = red(None, v_other, m0, 0, 1); + assert_eq!(per_lane(&mixed_other_src, all), None); + + let mut mixed_same_src = valid_exc.clone(); + mixed_same_src[0] = red(None, v0, m0, 0, 1); + assert_eq!(per_lane(&mixed_same_src, all), None); + + let mut exc_bad_lane1_src = valid_exc.clone(); + exc_bad_lane1_src[1] = red(None, v_other, m0, 0, 1); + assert_eq!(per_lane(&exc_bad_lane1_src, all), None); + + let mut exc_bad_lane1_set = valid_exc.clone(); + exc_bad_lane1_set[1] = red(None, v0, m0, 0, 0b11); + assert_eq!(per_lane(&exc_bad_lane1_set, all), None); + + for bad0 in [ + red(None, v0, m0, 1, 1), + red(None, v_other, m0, 0, 1), + red(None, v0, m_other, 0, 1), + red(None, v0, m0, 0, 0), + Sym::K(0), + ] { + let mut bad_inc = valid_inc.clone(); + bad_inc[0] = bad0; + assert_eq!(per_lane(&bad_inc, all), None); + } + + let mut bad_ident: Vec = (0..wave) + .map(|l| red(Some(Op::AddU), v0, m0, 1, below_mask(l) | (1u64 << l))) + .collect(); + bad_ident[0] = red(None, v0, m0, 1, 1); + assert_eq!(per_lane(&bad_ident, all), None); + } + } +} diff --git a/crates/leonida-shader/src/emit/wave64_tests.rs b/crates/leonida-shader/src/emit/wave64_tests.rs new file mode 100644 index 000000000..524c9db1b --- /dev/null +++ b/crates/leonida-shader/src/emit/wave64_tests.rs @@ -0,0 +1,532 @@ +//! 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) -> Result { + 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, + host_wave: u32, +) -> Result { + 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 = (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"); + 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 = (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 `LEONIDA_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 { + 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"); +} diff --git a/crates/leonida-shader/src/gfx10/fields.rs b/crates/leonida-shader/src/gfx10/fields.rs new file mode 100644 index 000000000..2773b3c84 --- /dev/null +++ b/crates/leonida-shader/src/gfx10/fields.rs @@ -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, + src: Vec, + imm: Option, + }, + /// The 16-bit immediate: branch offset in dwords, wait counts, message... + Sopp { + imm: u16, + }, + Smem { + data: Option, + 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, + addr: Option, + data: Vec, + 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, + addr: Operand, + rsrc: Operand, + soffset: Operand, + offset: u16, + offen: bool, + idxen: bool, + format: Option, + lds: bool, + tfe: bool, + cache: Cache, + }, + Image { + data: Operand, + /// One range, or one VGPR per address with the NSA form. + addr: Vec, + rsrc: Operand, + sampler: Option, + 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, + addr: Option, + data: Option, + saddr: Option, + offset: i16, + lds: bool, + cache: Cache, + }, + Exp { + target: u8, + /// Per channel; `None` when disabled. + src: [Option; 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, + /// Carry-out or the second result of VOP3B (`v_add_co_u32`, `v_div_scale_f32`...). + pub carry: Option, + /// 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, + /// 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, + pub dpp: Option, +} + +#[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 + } +} diff --git a/crates/leonida-shader/src/gfx10/mod.rs b/crates/leonida-shader/src/gfx10/mod.rs new file mode 100644 index 000000000..f029ff405 --- /dev/null +++ b/crates/leonida-shader/src/gfx10/mod.rs @@ -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, +} + +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, 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 = 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 { + 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 { + 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, 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 { + 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::>()?, + }) +} + +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 { + 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()); + } +} diff --git a/crates/leonida-shader/src/gfx10/opcodes.rs b/crates/leonida-shader/src/gfx10/opcodes.rs new file mode 100644 index 000000000..d1ba275aa --- /dev/null +++ b/crates/leonida-shader/src/gfx10/opcodes.rs @@ -0,0 +1,1333 @@ +// GFX10 opcode names, generated from Mesa's src/amd/compiler/aco_opcodes.py +// (tag mesa-22.3.0, GFX10 column), which carries this notice: +// +// Copyright (c) 2018 Valve Corporation +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the "Software"), +// to deal in the Software without restriction, including without limitation +// the rights to use, copy, modify, merge, publish, distribute, sublicense, +// and/or sell copies of the Software, and to permit persons to whom the +// Software is furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice (including the next +// paragraph) shall be included in all copies or substantial portions of the +// Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL +// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS +// IN THE SOFTWARE. +// +// Each table is sorted by opcode. VOP3 holds only VOP3-only opcodes; VOP3 +// encodings of VOPC/VOP2/VOP1 ops (0x000-0x13f, 0x180-0x1ff) use those tables. + +pub(super) const SOP2: &[(u16, &str)] = &[ + (0x000, "s_add_u32"), + (0x001, "s_sub_u32"), + (0x002, "s_add_i32"), + (0x003, "s_sub_i32"), + (0x004, "s_addc_u32"), + (0x005, "s_subb_u32"), + (0x006, "s_min_i32"), + (0x007, "s_min_u32"), + (0x008, "s_max_i32"), + (0x009, "s_max_u32"), + (0x00a, "s_cselect_b32"), + (0x00b, "s_cselect_b64"), + (0x00e, "s_and_b32"), + (0x00f, "s_and_b64"), + (0x010, "s_or_b32"), + (0x011, "s_or_b64"), + (0x012, "s_xor_b32"), + (0x013, "s_xor_b64"), + (0x014, "s_andn2_b32"), + (0x015, "s_andn2_b64"), + (0x016, "s_orn2_b32"), + (0x017, "s_orn2_b64"), + (0x018, "s_nand_b32"), + (0x019, "s_nand_b64"), + (0x01a, "s_nor_b32"), + (0x01b, "s_nor_b64"), + (0x01c, "s_xnor_b32"), + (0x01d, "s_xnor_b64"), + (0x01e, "s_lshl_b32"), + (0x01f, "s_lshl_b64"), + (0x020, "s_lshr_b32"), + (0x021, "s_lshr_b64"), + (0x022, "s_ashr_i32"), + (0x023, "s_ashr_i64"), + (0x024, "s_bfm_b32"), + (0x025, "s_bfm_b64"), + (0x026, "s_mul_i32"), + (0x027, "s_bfe_u32"), + (0x028, "s_bfe_i32"), + (0x029, "s_bfe_u64"), + (0x02a, "s_bfe_i64"), + (0x02c, "s_absdiff_i32"), + (0x02e, "s_lshl1_add_u32"), + (0x02f, "s_lshl2_add_u32"), + (0x030, "s_lshl3_add_u32"), + (0x031, "s_lshl4_add_u32"), + (0x032, "s_pack_ll_b32_b16"), + (0x033, "s_pack_lh_b32_b16"), + (0x034, "s_pack_hh_b32_b16"), + (0x035, "s_mul_hi_u32"), + (0x036, "s_mul_hi_i32"), +]; + +pub(super) const SOPK: &[(u16, &str)] = &[ + (0x000, "s_movk_i32"), + (0x001, "s_version"), + (0x002, "s_cmovk_i32"), + (0x003, "s_cmpk_eq_i32"), + (0x004, "s_cmpk_lg_i32"), + (0x005, "s_cmpk_gt_i32"), + (0x006, "s_cmpk_ge_i32"), + (0x007, "s_cmpk_lt_i32"), + (0x008, "s_cmpk_le_i32"), + (0x009, "s_cmpk_eq_u32"), + (0x00a, "s_cmpk_lg_u32"), + (0x00b, "s_cmpk_gt_u32"), + (0x00c, "s_cmpk_ge_u32"), + (0x00d, "s_cmpk_lt_u32"), + (0x00e, "s_cmpk_le_u32"), + (0x00f, "s_addk_i32"), + (0x010, "s_mulk_i32"), + (0x012, "s_getreg_b32"), + (0x013, "s_setreg_b32"), + (0x015, "s_setreg_imm32_b32"), + (0x016, "s_call_b64"), + (0x017, "s_waitcnt_vscnt"), + (0x018, "s_waitcnt_vmcnt"), + (0x019, "s_waitcnt_expcnt"), + (0x01a, "s_waitcnt_lgkmcnt"), + (0x01b, "s_subvector_loop_begin"), + (0x01c, "s_subvector_loop_end"), +]; + +pub(super) const SOP1: &[(u16, &str)] = &[ + (0x003, "s_mov_b32"), + (0x004, "s_mov_b64"), + (0x005, "s_cmov_b32"), + (0x006, "s_cmov_b64"), + (0x007, "s_not_b32"), + (0x008, "s_not_b64"), + (0x009, "s_wqm_b32"), + (0x00a, "s_wqm_b64"), + (0x00b, "s_brev_b32"), + (0x00c, "s_brev_b64"), + (0x00d, "s_bcnt0_i32_b32"), + (0x00e, "s_bcnt0_i32_b64"), + (0x00f, "s_bcnt1_i32_b32"), + (0x010, "s_bcnt1_i32_b64"), + (0x011, "s_ff0_i32_b32"), + (0x012, "s_ff0_i32_b64"), + (0x013, "s_ff1_i32_b32"), + (0x014, "s_ff1_i32_b64"), + (0x015, "s_flbit_i32_b32"), + (0x016, "s_flbit_i32_b64"), + (0x017, "s_flbit_i32"), + (0x018, "s_flbit_i32_i64"), + (0x019, "s_sext_i32_i8"), + (0x01a, "s_sext_i32_i16"), + (0x01b, "s_bitset0_b32"), + (0x01c, "s_bitset0_b64"), + (0x01d, "s_bitset1_b32"), + (0x01e, "s_bitset1_b64"), + (0x01f, "s_getpc_b64"), + (0x020, "s_setpc_b64"), + (0x021, "s_swappc_b64"), + (0x022, "s_rfe_b64"), + (0x024, "s_and_saveexec_b64"), + (0x025, "s_or_saveexec_b64"), + (0x026, "s_xor_saveexec_b64"), + (0x027, "s_andn2_saveexec_b64"), + (0x028, "s_orn2_saveexec_b64"), + (0x029, "s_nand_saveexec_b64"), + (0x02a, "s_nor_saveexec_b64"), + (0x02b, "s_xnor_saveexec_b64"), + (0x02c, "s_quadmask_b32"), + (0x02d, "s_quadmask_b64"), + (0x02e, "s_movrels_b32"), + (0x02f, "s_movrels_b64"), + (0x030, "s_movreld_b32"), + (0x031, "s_movreld_b64"), + (0x034, "s_abs_i32"), + (0x035, "s_mov_fed_b32"), + (0x037, "s_andn1_saveexec_b64"), + (0x038, "s_orn1_saveexec_b64"), + (0x039, "s_andn1_wrexec_b64"), + (0x03a, "s_andn2_wrexec_b64"), + (0x03b, "s_bitreplicate_b64_b32"), + (0x03c, "s_and_saveexec_b32"), + (0x03d, "s_or_saveexec_b32"), + (0x03e, "s_xor_saveexec_b32"), + (0x03f, "s_andn2_saveexec_b32"), + (0x040, "s_orn2_saveexec_b32"), + (0x041, "s_nand_saveexec_b32"), + (0x042, "s_nor_saveexec_b32"), + (0x043, "s_xnor_saveexec_b32"), + (0x044, "s_andn1_saveexec_b32"), + (0x045, "s_orn1_saveexec_b32"), + (0x046, "s_andn1_wrexec_b32"), + (0x047, "s_andn2_wrexec_b32"), + (0x049, "s_movrelsd_2_b32"), +]; + +pub(super) const SOPC: &[(u16, &str)] = &[ + (0x000, "s_cmp_eq_i32"), + (0x001, "s_cmp_lg_i32"), + (0x002, "s_cmp_gt_i32"), + (0x003, "s_cmp_ge_i32"), + (0x004, "s_cmp_lt_i32"), + (0x005, "s_cmp_le_i32"), + (0x006, "s_cmp_eq_u32"), + (0x007, "s_cmp_lg_u32"), + (0x008, "s_cmp_gt_u32"), + (0x009, "s_cmp_ge_u32"), + (0x00a, "s_cmp_lt_u32"), + (0x00b, "s_cmp_le_u32"), + (0x00c, "s_bitcmp0_b32"), + (0x00d, "s_bitcmp1_b32"), + (0x00e, "s_bitcmp0_b64"), + (0x00f, "s_bitcmp1_b64"), + (0x012, "s_cmp_eq_u64"), + (0x013, "s_cmp_lg_u64"), +]; + +pub(super) const SOPP: &[(u16, &str)] = &[ + (0x000, "s_nop"), + (0x001, "s_endpgm"), + (0x002, "s_branch"), + (0x003, "s_wakeup"), + (0x004, "s_cbranch_scc0"), + (0x005, "s_cbranch_scc1"), + (0x006, "s_cbranch_vccz"), + (0x007, "s_cbranch_vccnz"), + (0x008, "s_cbranch_execz"), + (0x009, "s_cbranch_execnz"), + (0x00a, "s_barrier"), + (0x00b, "s_setkill"), + (0x00c, "s_waitcnt"), + (0x00d, "s_sethalt"), + (0x00e, "s_sleep"), + (0x00f, "s_setprio"), + (0x010, "s_sendmsg"), + (0x011, "s_sendmsghalt"), + (0x012, "s_trap"), + (0x013, "s_icache_inv"), + (0x014, "s_incperflevel"), + (0x015, "s_decperflevel"), + (0x016, "s_ttracedata"), + (0x017, "s_cbranch_cdbgsys"), + (0x018, "s_cbranch_cdbguser"), + (0x019, "s_cbranch_cdbgsys_or_user"), + (0x01a, "s_cbranch_cdbgsys_and_user"), + (0x01b, "s_endpgm_saved"), + (0x01e, "s_endpgm_ordered_ps_done"), + (0x01f, "s_code_end"), + (0x020, "s_inst_prefetch"), + (0x021, "s_clause"), + (0x022, "s_wait_idle"), + (0x023, "s_waitcnt_depctr"), + (0x024, "s_round_mode"), + (0x025, "s_denorm_mode"), + (0x028, "s_ttracedata_imm"), +]; + +pub(super) const SMEM: &[(u16, &str)] = &[ + (0x000, "s_load_dword"), + (0x001, "s_load_dwordx2"), + (0x002, "s_load_dwordx4"), + (0x003, "s_load_dwordx8"), + (0x004, "s_load_dwordx16"), + (0x005, "s_scratch_load_dword"), + (0x006, "s_scratch_load_dwordx2"), + (0x007, "s_scratch_load_dwordx4"), + (0x008, "s_buffer_load_dword"), + (0x009, "s_buffer_load_dwordx2"), + (0x00a, "s_buffer_load_dwordx4"), + (0x00b, "s_buffer_load_dwordx8"), + (0x00c, "s_buffer_load_dwordx16"), + (0x010, "s_store_dword"), + (0x011, "s_store_dwordx2"), + (0x012, "s_store_dwordx4"), + (0x015, "s_scratch_store_dword"), + (0x016, "s_scratch_store_dwordx2"), + (0x017, "s_scratch_store_dwordx4"), + (0x018, "s_buffer_store_dword"), + (0x019, "s_buffer_store_dwordx2"), + (0x01a, "s_buffer_store_dwordx4"), + (0x01f, "s_gl1_inv"), + (0x020, "s_dcache_inv"), + (0x021, "s_dcache_wb"), + (0x024, "s_memtime"), + (0x025, "s_memrealtime"), + (0x026, "s_atc_probe"), + (0x027, "s_atc_probe_buffer"), + (0x028, "s_dcache_discard"), + (0x029, "s_dcache_discard_x2"), + (0x02a, "s_get_waveid_in_workgroup"), + (0x040, "s_buffer_atomic_swap"), + (0x041, "s_buffer_atomic_cmpswap"), + (0x042, "s_buffer_atomic_add"), + (0x043, "s_buffer_atomic_sub"), + (0x044, "s_buffer_atomic_smin"), + (0x045, "s_buffer_atomic_umin"), + (0x046, "s_buffer_atomic_smax"), + (0x047, "s_buffer_atomic_umax"), + (0x048, "s_buffer_atomic_and"), + (0x049, "s_buffer_atomic_or"), + (0x04a, "s_buffer_atomic_xor"), + (0x04b, "s_buffer_atomic_inc"), + (0x04c, "s_buffer_atomic_dec"), + (0x060, "s_buffer_atomic_swap_x2"), + (0x061, "s_buffer_atomic_cmpswap_x2"), + (0x062, "s_buffer_atomic_add_x2"), + (0x063, "s_buffer_atomic_sub_x2"), + (0x064, "s_buffer_atomic_smin_x2"), + (0x065, "s_buffer_atomic_umin_x2"), + (0x066, "s_buffer_atomic_smax_x2"), + (0x067, "s_buffer_atomic_umax_x2"), + (0x068, "s_buffer_atomic_and_x2"), + (0x069, "s_buffer_atomic_or_x2"), + (0x06a, "s_buffer_atomic_xor_x2"), + (0x06b, "s_buffer_atomic_inc_x2"), + (0x06c, "s_buffer_atomic_dec_x2"), + (0x080, "s_atomic_swap"), + (0x081, "s_atomic_cmpswap"), + (0x082, "s_atomic_add"), + (0x083, "s_atomic_sub"), + (0x084, "s_atomic_smin"), + (0x085, "s_atomic_umin"), + (0x086, "s_atomic_smax"), + (0x087, "s_atomic_umax"), + (0x088, "s_atomic_and"), + (0x089, "s_atomic_or"), + (0x08a, "s_atomic_xor"), + (0x08b, "s_atomic_inc"), + (0x08c, "s_atomic_dec"), + (0x0a0, "s_atomic_swap_x2"), + (0x0a1, "s_atomic_cmpswap_x2"), + (0x0a2, "s_atomic_add_x2"), + (0x0a3, "s_atomic_sub_x2"), + (0x0a4, "s_atomic_smin_x2"), + (0x0a5, "s_atomic_umin_x2"), + (0x0a6, "s_atomic_smax_x2"), + (0x0a7, "s_atomic_umax_x2"), + (0x0a8, "s_atomic_and_x2"), + (0x0a9, "s_atomic_or_x2"), + (0x0aa, "s_atomic_xor_x2"), + (0x0ab, "s_atomic_inc_x2"), + (0x0ac, "s_atomic_dec_x2"), +]; + +pub(super) const VOP2: &[(u16, &str)] = &[ + (0x001, "v_cndmask_b32"), + (0x002, "v_dot2c_f32_f16"), + (0x003, "v_add_f32"), + (0x004, "v_sub_f32"), + (0x005, "v_subrev_f32"), + (0x006, "v_mac_legacy_f32"), + (0x007, "v_mul_legacy_f32"), + (0x008, "v_mul_f32"), + (0x009, "v_mul_i32_i24"), + (0x00a, "v_mul_hi_i32_i24"), + (0x00b, "v_mul_u32_u24"), + (0x00c, "v_mul_hi_u32_u24"), + (0x00d, "v_dot4c_i32_i8"), + (0x00f, "v_min_f32"), + (0x010, "v_max_f32"), + (0x011, "v_min_i32"), + (0x012, "v_max_i32"), + (0x013, "v_min_u32"), + (0x014, "v_max_u32"), + (0x016, "v_lshrrev_b32"), + (0x018, "v_ashrrev_i32"), + (0x01a, "v_lshlrev_b32"), + (0x01b, "v_and_b32"), + (0x01c, "v_or_b32"), + (0x01d, "v_xor_b32"), + (0x01e, "v_xnor_b32"), + (0x01f, "v_mac_f32"), + (0x020, "v_madmk_f32"), + (0x021, "v_madak_f32"), + (0x025, "v_add_nc_u32"), + (0x026, "v_sub_nc_u32"), + (0x027, "v_subrev_nc_u32"), + (0x028, "v_add_co_ci_u32"), + (0x029, "v_sub_co_ci_u32"), + (0x02a, "v_subrev_co_ci_u32"), + (0x02b, "v_fmac_f32"), + (0x02c, "v_fmamk_f32"), + (0x02d, "v_fmaak_f32"), + (0x02f, "v_cvt_pkrtz_f16_f32"), + (0x032, "v_add_f16"), + (0x033, "v_sub_f16"), + (0x034, "v_subrev_f16"), + (0x035, "v_mul_f16"), + (0x036, "v_fmac_f16"), + (0x037, "v_fmamk_f16"), + (0x038, "v_fmaak_f16"), + (0x039, "v_max_f16"), + (0x03a, "v_min_f16"), + (0x03b, "v_ldexp_f16"), + (0x03c, "v_pk_fmac_f16"), +]; + +pub(super) const VOP1: &[(u16, &str)] = &[ + (0x000, "v_nop"), + (0x001, "v_mov_b32"), + (0x002, "v_readfirstlane_b32"), + (0x003, "v_cvt_i32_f64"), + (0x004, "v_cvt_f64_i32"), + (0x005, "v_cvt_f32_i32"), + (0x006, "v_cvt_f32_u32"), + (0x007, "v_cvt_u32_f32"), + (0x008, "v_cvt_i32_f32"), + (0x00a, "v_cvt_f16_f32"), + (0x00b, "v_cvt_f32_f16"), + (0x00c, "v_cvt_rpi_i32_f32"), + (0x00d, "v_cvt_flr_i32_f32"), + (0x00e, "v_cvt_off_f32_i4"), + (0x00f, "v_cvt_f32_f64"), + (0x010, "v_cvt_f64_f32"), + (0x011, "v_cvt_f32_ubyte0"), + (0x012, "v_cvt_f32_ubyte1"), + (0x013, "v_cvt_f32_ubyte2"), + (0x014, "v_cvt_f32_ubyte3"), + (0x015, "v_cvt_u32_f64"), + (0x016, "v_cvt_f64_u32"), + (0x017, "v_trunc_f64"), + (0x018, "v_ceil_f64"), + (0x019, "v_rndne_f64"), + (0x01a, "v_floor_f64"), + (0x01b, "v_pipeflush"), + (0x020, "v_fract_f32"), + (0x021, "v_trunc_f32"), + (0x022, "v_ceil_f32"), + (0x023, "v_rndne_f32"), + (0x024, "v_floor_f32"), + (0x025, "v_exp_f32"), + (0x027, "v_log_f32"), + (0x02a, "v_rcp_f32"), + (0x02b, "v_rcp_iflag_f32"), + (0x02e, "v_rsq_f32"), + (0x02f, "v_rcp_f64"), + (0x031, "v_rsq_f64"), + (0x033, "v_sqrt_f32"), + (0x034, "v_sqrt_f64"), + (0x035, "v_sin_f32"), + (0x036, "v_cos_f32"), + (0x037, "v_not_b32"), + (0x038, "v_bfrev_b32"), + (0x039, "v_ffbh_u32"), + (0x03a, "v_ffbl_b32"), + (0x03b, "v_ffbh_i32"), + (0x03c, "v_frexp_exp_i32_f64"), + (0x03d, "v_frexp_mant_f64"), + (0x03e, "v_fract_f64"), + (0x03f, "v_frexp_exp_i32_f32"), + (0x040, "v_frexp_mant_f32"), + (0x041, "v_clrexcp"), + (0x042, "v_movreld_b32"), + (0x043, "v_movrels_b32"), + (0x044, "v_movrelsd_b32"), + (0x048, "v_movrelsd_2_b32"), + (0x050, "v_cvt_f16_u16"), + (0x051, "v_cvt_f16_i16"), + (0x052, "v_cvt_u16_f16"), + (0x053, "v_cvt_i16_f16"), + (0x054, "v_rcp_f16"), + (0x055, "v_sqrt_f16"), + (0x056, "v_rsq_f16"), + (0x057, "v_log_f16"), + (0x058, "v_exp_f16"), + (0x059, "v_frexp_mant_f16"), + (0x05a, "v_frexp_exp_i16_f16"), + (0x05b, "v_floor_f16"), + (0x05c, "v_ceil_f16"), + (0x05d, "v_trunc_f16"), + (0x05e, "v_rndne_f16"), + (0x05f, "v_fract_f16"), + (0x060, "v_sin_f16"), + (0x061, "v_cos_f16"), + (0x062, "v_sat_pk_u8_i16"), + (0x063, "v_cvt_norm_i16_f16"), + (0x064, "v_cvt_norm_u16_f16"), + (0x065, "v_swap_b32"), + (0x068, "v_swaprel_b32"), +]; + +pub(super) const VOPC: &[(u16, &str)] = &[ + (0x000, "v_cmp_f_f32"), + (0x001, "v_cmp_lt_f32"), + (0x002, "v_cmp_eq_f32"), + (0x003, "v_cmp_le_f32"), + (0x004, "v_cmp_gt_f32"), + (0x005, "v_cmp_lg_f32"), + (0x006, "v_cmp_ge_f32"), + (0x007, "v_cmp_o_f32"), + (0x008, "v_cmp_u_f32"), + (0x009, "v_cmp_nge_f32"), + (0x00a, "v_cmp_nlg_f32"), + (0x00b, "v_cmp_ngt_f32"), + (0x00c, "v_cmp_nle_f32"), + (0x00d, "v_cmp_neq_f32"), + (0x00e, "v_cmp_nlt_f32"), + (0x00f, "v_cmp_tru_f32"), + (0x010, "v_cmpx_f_f32"), + (0x011, "v_cmpx_lt_f32"), + (0x012, "v_cmpx_eq_f32"), + (0x013, "v_cmpx_le_f32"), + (0x014, "v_cmpx_gt_f32"), + (0x015, "v_cmpx_lg_f32"), + (0x016, "v_cmpx_ge_f32"), + (0x017, "v_cmpx_o_f32"), + (0x018, "v_cmpx_u_f32"), + (0x019, "v_cmpx_nge_f32"), + (0x01a, "v_cmpx_nlg_f32"), + (0x01b, "v_cmpx_ngt_f32"), + (0x01c, "v_cmpx_nle_f32"), + (0x01d, "v_cmpx_neq_f32"), + (0x01e, "v_cmpx_nlt_f32"), + (0x01f, "v_cmpx_tru_f32"), + (0x020, "v_cmp_f_f64"), + (0x021, "v_cmp_lt_f64"), + (0x022, "v_cmp_eq_f64"), + (0x023, "v_cmp_le_f64"), + (0x024, "v_cmp_gt_f64"), + (0x025, "v_cmp_lg_f64"), + (0x026, "v_cmp_ge_f64"), + (0x027, "v_cmp_o_f64"), + (0x028, "v_cmp_u_f64"), + (0x029, "v_cmp_nge_f64"), + (0x02a, "v_cmp_nlg_f64"), + (0x02b, "v_cmp_ngt_f64"), + (0x02c, "v_cmp_nle_f64"), + (0x02d, "v_cmp_neq_f64"), + (0x02e, "v_cmp_nlt_f64"), + (0x02f, "v_cmp_tru_f64"), + (0x030, "v_cmpx_f_f64"), + (0x031, "v_cmpx_lt_f64"), + (0x032, "v_cmpx_eq_f64"), + (0x033, "v_cmpx_le_f64"), + (0x034, "v_cmpx_gt_f64"), + (0x035, "v_cmpx_lg_f64"), + (0x036, "v_cmpx_ge_f64"), + (0x037, "v_cmpx_o_f64"), + (0x038, "v_cmpx_u_f64"), + (0x039, "v_cmpx_nge_f64"), + (0x03a, "v_cmpx_nlg_f64"), + (0x03b, "v_cmpx_ngt_f64"), + (0x03c, "v_cmpx_nle_f64"), + (0x03d, "v_cmpx_neq_f64"), + (0x03e, "v_cmpx_nlt_f64"), + (0x03f, "v_cmpx_tru_f64"), + (0x080, "v_cmp_f_i32"), + (0x081, "v_cmp_lt_i32"), + (0x082, "v_cmp_eq_i32"), + (0x083, "v_cmp_le_i32"), + (0x084, "v_cmp_gt_i32"), + (0x085, "v_cmp_ne_i32"), + (0x086, "v_cmp_ge_i32"), + (0x087, "v_cmp_t_i32"), + (0x088, "v_cmp_class_f32"), + (0x089, "v_cmp_lt_i16"), + (0x08a, "v_cmp_eq_i16"), + (0x08b, "v_cmp_le_i16"), + (0x08c, "v_cmp_gt_i16"), + (0x08d, "v_cmp_ne_i16"), + (0x08e, "v_cmp_ge_i16"), + (0x08f, "v_cmp_class_f16"), + (0x090, "v_cmpx_f_i32"), + (0x091, "v_cmpx_lt_i32"), + (0x092, "v_cmpx_eq_i32"), + (0x093, "v_cmpx_le_i32"), + (0x094, "v_cmpx_gt_i32"), + (0x095, "v_cmpx_ne_i32"), + (0x096, "v_cmpx_ge_i32"), + (0x097, "v_cmpx_t_i32"), + (0x098, "v_cmpx_class_f32"), + (0x099, "v_cmpx_lt_i16"), + (0x09a, "v_cmpx_eq_i16"), + (0x09b, "v_cmpx_le_i16"), + (0x09c, "v_cmpx_gt_i16"), + (0x09d, "v_cmpx_ne_i16"), + (0x09e, "v_cmpx_ge_i16"), + (0x09f, "v_cmpx_class_f16"), + (0x0a0, "v_cmp_f_i64"), + (0x0a1, "v_cmp_lt_i64"), + (0x0a2, "v_cmp_eq_i64"), + (0x0a3, "v_cmp_le_i64"), + (0x0a4, "v_cmp_gt_i64"), + (0x0a5, "v_cmp_ne_i64"), + (0x0a6, "v_cmp_ge_i64"), + (0x0a7, "v_cmp_t_i64"), + (0x0a8, "v_cmp_class_f64"), + (0x0a9, "v_cmp_lt_u16"), + (0x0aa, "v_cmp_eq_u16"), + (0x0ab, "v_cmp_le_u16"), + (0x0ac, "v_cmp_gt_u16"), + (0x0ad, "v_cmp_ne_u16"), + (0x0ae, "v_cmp_ge_u16"), + (0x0b0, "v_cmpx_f_i64"), + (0x0b1, "v_cmpx_lt_i64"), + (0x0b2, "v_cmpx_eq_i64"), + (0x0b3, "v_cmpx_le_i64"), + (0x0b4, "v_cmpx_gt_i64"), + (0x0b5, "v_cmpx_ne_i64"), + (0x0b6, "v_cmpx_ge_i64"), + (0x0b7, "v_cmpx_t_i64"), + (0x0b8, "v_cmpx_class_f64"), + (0x0b9, "v_cmpx_lt_u16"), + (0x0ba, "v_cmpx_eq_u16"), + (0x0bb, "v_cmpx_le_u16"), + (0x0bc, "v_cmpx_gt_u16"), + (0x0bd, "v_cmpx_ne_u16"), + (0x0be, "v_cmpx_ge_u16"), + (0x0c0, "v_cmp_f_u32"), + (0x0c1, "v_cmp_lt_u32"), + (0x0c2, "v_cmp_eq_u32"), + (0x0c3, "v_cmp_le_u32"), + (0x0c4, "v_cmp_gt_u32"), + (0x0c5, "v_cmp_ne_u32"), + (0x0c6, "v_cmp_ge_u32"), + (0x0c7, "v_cmp_t_u32"), + (0x0c8, "v_cmp_f_f16"), + (0x0c9, "v_cmp_lt_f16"), + (0x0ca, "v_cmp_eq_f16"), + (0x0cb, "v_cmp_le_f16"), + (0x0cc, "v_cmp_gt_f16"), + (0x0cd, "v_cmp_lg_f16"), + (0x0ce, "v_cmp_ge_f16"), + (0x0cf, "v_cmp_o_f16"), + (0x0d0, "v_cmpx_f_u32"), + (0x0d1, "v_cmpx_lt_u32"), + (0x0d2, "v_cmpx_eq_u32"), + (0x0d3, "v_cmpx_le_u32"), + (0x0d4, "v_cmpx_gt_u32"), + (0x0d5, "v_cmpx_ne_u32"), + (0x0d6, "v_cmpx_ge_u32"), + (0x0d7, "v_cmpx_t_u32"), + (0x0d8, "v_cmpx_f_f16"), + (0x0d9, "v_cmpx_lt_f16"), + (0x0da, "v_cmpx_eq_f16"), + (0x0db, "v_cmpx_le_f16"), + (0x0dc, "v_cmpx_gt_f16"), + (0x0dd, "v_cmpx_lg_f16"), + (0x0de, "v_cmpx_ge_f16"), + (0x0df, "v_cmpx_o_f16"), + (0x0e0, "v_cmp_f_u64"), + (0x0e1, "v_cmp_lt_u64"), + (0x0e2, "v_cmp_eq_u64"), + (0x0e3, "v_cmp_le_u64"), + (0x0e4, "v_cmp_gt_u64"), + (0x0e5, "v_cmp_ne_u64"), + (0x0e6, "v_cmp_ge_u64"), + (0x0e7, "v_cmp_t_u64"), + (0x0e8, "v_cmp_u_f16"), + (0x0e9, "v_cmp_nge_f16"), + (0x0ea, "v_cmp_nlg_f16"), + (0x0eb, "v_cmp_ngt_f16"), + (0x0ec, "v_cmp_nle_f16"), + (0x0ed, "v_cmp_neq_f16"), + (0x0ee, "v_cmp_nlt_f16"), + (0x0ef, "v_cmp_tru_f16"), + (0x0f0, "v_cmpx_f_u64"), + (0x0f1, "v_cmpx_lt_u64"), + (0x0f2, "v_cmpx_eq_u64"), + (0x0f3, "v_cmpx_le_u64"), + (0x0f4, "v_cmpx_gt_u64"), + (0x0f5, "v_cmpx_ne_u64"), + (0x0f6, "v_cmpx_ge_u64"), + (0x0f7, "v_cmpx_t_u64"), + (0x0f8, "v_cmpx_u_f16"), + (0x0f9, "v_cmpx_nge_f16"), + (0x0fa, "v_cmpx_nlg_f16"), + (0x0fb, "v_cmpx_ngt_f16"), + (0x0fc, "v_cmpx_nle_f16"), + (0x0fd, "v_cmpx_neq_f16"), + (0x0fe, "v_cmpx_nlt_f16"), + (0x0ff, "v_cmpx_tru_f16"), +]; + +pub(super) const VOP3: &[(u16, &str)] = &[ + (0x140, "v_mad_legacy_f32"), + (0x141, "v_mad_f32"), + (0x142, "v_mad_i32_i24"), + (0x143, "v_mad_u32_u24"), + (0x144, "v_cubeid_f32"), + (0x145, "v_cubesc_f32"), + (0x146, "v_cubetc_f32"), + (0x147, "v_cubema_f32"), + (0x148, "v_bfe_u32"), + (0x149, "v_bfe_i32"), + (0x14a, "v_bfi_b32"), + (0x14b, "v_fma_f32"), + (0x14c, "v_fma_f64"), + (0x14d, "v_lerp_u8"), + (0x14e, "v_alignbit_b32"), + (0x14f, "v_alignbyte_b32"), + (0x150, "v_mullit_f32"), + (0x151, "v_min3_f32"), + (0x152, "v_min3_i32"), + (0x153, "v_min3_u32"), + (0x154, "v_max3_f32"), + (0x155, "v_max3_i32"), + (0x156, "v_max3_u32"), + (0x157, "v_med3_f32"), + (0x158, "v_med3_i32"), + (0x159, "v_med3_u32"), + (0x15a, "v_sad_u8"), + (0x15b, "v_sad_hi_u8"), + (0x15c, "v_sad_u16"), + (0x15d, "v_sad_u32"), + (0x15e, "v_cvt_pk_u8_f32"), + (0x15f, "v_div_fixup_f32"), + (0x160, "v_div_fixup_f64"), + (0x164, "v_add_f64"), + (0x165, "v_mul_f64"), + (0x166, "v_min_f64"), + (0x167, "v_max_f64"), + (0x168, "v_ldexp_f64"), + (0x169, "v_mul_lo_u32"), + (0x16a, "v_mul_hi_u32"), + (0x16b, "v_mul_lo_i32"), + (0x16c, "v_mul_hi_i32"), + (0x16d, "v_div_scale_f32"), + (0x16e, "v_div_scale_f64"), + (0x16f, "v_div_fmas_f32"), + (0x170, "v_div_fmas_f64"), + (0x171, "v_msad_u8"), + (0x172, "v_qsad_pk_u16_u8"), + (0x173, "v_mqsad_pk_u16_u8"), + (0x174, "v_trig_preop_f64"), + (0x175, "v_mqsad_u32_u8"), + (0x176, "v_mad_u64_u32"), + (0x177, "v_mad_i64_i32"), + (0x178, "v_xor3_b32"), + (0x2ff, "v_lshlrev_b64"), + (0x300, "v_lshrrev_b64"), + (0x301, "v_ashrrev_i64"), + (0x303, "v_add_nc_u16"), + (0x304, "v_sub_nc_u16"), + (0x305, "v_mul_lo_u16"), + (0x307, "v_lshrrev_b16"), + (0x308, "v_ashrrev_i16"), + (0x309, "v_max_u16"), + (0x30a, "v_max_i16"), + (0x30b, "v_min_u16"), + (0x30c, "v_min_i16"), + (0x30d, "v_add_nc_i16"), + (0x30e, "v_sub_nc_i16"), + (0x30f, "v_add_co_u32"), + (0x310, "v_sub_co_u32"), + (0x311, "v_pack_b32_f16"), + (0x312, "v_cvt_pknorm_i16_f16"), + (0x313, "v_cvt_pknorm_u16_f16"), + (0x314, "v_lshlrev_b16"), + (0x319, "v_subrev_co_u32"), + (0x340, "v_mad_u16"), + (0x342, "v_interp_p1ll_f16"), + (0x343, "v_interp_p1lv_f16"), + (0x344, "v_perm_b32"), + (0x345, "v_xad_u32"), + (0x346, "v_lshl_add_u32"), + (0x347, "v_add_lshl_u32"), + (0x34b, "v_fma_f16"), + (0x351, "v_min3_f16"), + (0x352, "v_min3_i16"), + (0x353, "v_min3_u16"), + (0x354, "v_max3_f16"), + (0x355, "v_max3_i16"), + (0x356, "v_max3_u16"), + (0x357, "v_med3_f16"), + (0x358, "v_med3_i16"), + (0x359, "v_med3_u16"), + (0x35a, "v_interp_p2_f16"), + (0x35e, "v_mad_i16"), + (0x35f, "v_div_fixup_f16"), + (0x360, "v_readlane_b32"), + (0x361, "v_writelane_b32"), + (0x362, "v_ldexp_f32"), + (0x363, "v_bfm_b32"), + (0x364, "v_bcnt_u32_b32"), + (0x365, "v_mbcnt_lo_u32_b32"), + (0x366, "v_mbcnt_hi_u32_b32"), + (0x368, "v_cvt_pknorm_i16_f32"), + (0x369, "v_cvt_pknorm_u16_f32"), + (0x36a, "v_cvt_pk_u16_u32"), + (0x36b, "v_cvt_pk_i16_i32"), + (0x36d, "v_add3_u32"), + (0x36f, "v_lshl_or_b32"), + (0x371, "v_and_or_b32"), + (0x372, "v_or3_b32"), + (0x373, "v_mad_u32_u16"), + (0x375, "v_mad_i32_i16"), + (0x376, "v_sub_nc_i32"), + (0x377, "v_permlane16_b32"), + (0x378, "v_permlanex16_b32"), + (0x37f, "v_add_nc_i32"), +]; + +pub(super) const VOP3P: &[(u16, &str)] = &[ + (0x000, "v_pk_mad_i16"), + (0x001, "v_pk_mul_lo_u16"), + (0x002, "v_pk_add_i16"), + (0x003, "v_pk_sub_i16"), + (0x004, "v_pk_lshlrev_b16"), + (0x005, "v_pk_lshrrev_b16"), + (0x006, "v_pk_ashrrev_i16"), + (0x007, "v_pk_max_i16"), + (0x008, "v_pk_min_i16"), + (0x009, "v_pk_mad_u16"), + (0x00a, "v_pk_add_u16"), + (0x00b, "v_pk_sub_u16"), + (0x00c, "v_pk_max_u16"), + (0x00d, "v_pk_min_u16"), + (0x00e, "v_pk_fma_f16"), + (0x00f, "v_pk_add_f16"), + (0x010, "v_pk_mul_f16"), + (0x011, "v_pk_min_f16"), + (0x012, "v_pk_max_f16"), + (0x013, "v_dot2_f32_f16"), + (0x014, "v_dot2_i32_i16"), + (0x015, "v_dot2_u32_u16"), + (0x016, "v_dot4_i32_i8"), + (0x017, "v_dot4_u32_u8"), + (0x019, "v_dot8_u32_u4"), + (0x020, "v_fma_mix_f32"), + (0x021, "v_fma_mixlo_f16"), + (0x022, "v_fma_mixhi_f16"), +]; + +pub(super) const VINTRP: &[(u16, &str)] = &[ + (0x000, "v_interp_p1_f32"), + (0x001, "v_interp_p2_f32"), + (0x002, "v_interp_mov_f32"), +]; + +pub(super) const DS: &[(u16, &str)] = &[ + (0x000, "ds_add_u32"), + (0x001, "ds_sub_u32"), + (0x002, "ds_rsub_u32"), + (0x003, "ds_inc_u32"), + (0x004, "ds_dec_u32"), + (0x005, "ds_min_i32"), + (0x006, "ds_max_i32"), + (0x007, "ds_min_u32"), + (0x008, "ds_max_u32"), + (0x009, "ds_and_b32"), + (0x00a, "ds_or_b32"), + (0x00b, "ds_xor_b32"), + (0x00c, "ds_mskor_b32"), + (0x00d, "ds_write_b32"), + (0x00e, "ds_write2_b32"), + (0x00f, "ds_write2st64_b32"), + (0x010, "ds_cmpst_b32"), + (0x011, "ds_cmpst_f32"), + (0x012, "ds_min_f32"), + (0x013, "ds_max_f32"), + (0x014, "ds_nop"), + (0x015, "ds_add_f32"), + (0x018, "ds_gws_sema_release_all"), + (0x019, "ds_gws_init"), + (0x01a, "ds_gws_sema_v"), + (0x01b, "ds_gws_sema_br"), + (0x01c, "ds_gws_sema_p"), + (0x01d, "ds_gws_barrier"), + (0x01e, "ds_write_b8"), + (0x01f, "ds_write_b16"), + (0x020, "ds_add_rtn_u32"), + (0x021, "ds_sub_rtn_u32"), + (0x022, "ds_rsub_rtn_u32"), + (0x023, "ds_inc_rtn_u32"), + (0x024, "ds_dec_rtn_u32"), + (0x025, "ds_min_rtn_i32"), + (0x026, "ds_max_rtn_i32"), + (0x027, "ds_min_rtn_u32"), + (0x028, "ds_max_rtn_u32"), + (0x029, "ds_and_rtn_b32"), + (0x02a, "ds_or_rtn_b32"), + (0x02b, "ds_xor_rtn_b32"), + (0x02c, "ds_mskor_rtn_b32"), + (0x02d, "ds_wrxchg_rtn_b32"), + (0x02e, "ds_wrxchg2_rtn_b32"), + (0x02f, "ds_wrxchg2st64_rtn_b32"), + (0x030, "ds_cmpst_rtn_b32"), + (0x031, "ds_cmpst_rtn_f32"), + (0x032, "ds_min_rtn_f32"), + (0x033, "ds_max_rtn_f32"), + (0x034, "ds_wrap_rtn_b32"), + (0x035, "ds_swizzle_b32"), + (0x036, "ds_read_b32"), + (0x037, "ds_read2_b32"), + (0x038, "ds_read2st64_b32"), + (0x039, "ds_read_i8"), + (0x03a, "ds_read_u8"), + (0x03b, "ds_read_i16"), + (0x03c, "ds_read_u16"), + (0x03d, "ds_consume"), + (0x03e, "ds_append"), + (0x03f, "ds_ordered_count"), + (0x040, "ds_add_u64"), + (0x041, "ds_sub_u64"), + (0x042, "ds_rsub_u64"), + (0x043, "ds_inc_u64"), + (0x044, "ds_dec_u64"), + (0x045, "ds_min_i64"), + (0x046, "ds_max_i64"), + (0x047, "ds_min_u64"), + (0x048, "ds_max_u64"), + (0x049, "ds_and_b64"), + (0x04a, "ds_or_b64"), + (0x04b, "ds_xor_b64"), + (0x04c, "ds_mskor_b64"), + (0x04d, "ds_write_b64"), + (0x04e, "ds_write2_b64"), + (0x04f, "ds_write2st64_b64"), + (0x050, "ds_cmpst_b64"), + (0x051, "ds_cmpst_f64"), + (0x052, "ds_min_f64"), + (0x053, "ds_max_f64"), + (0x055, "ds_add_rtn_f32"), + (0x060, "ds_add_rtn_u64"), + (0x061, "ds_sub_rtn_u64"), + (0x062, "ds_rsub_rtn_u64"), + (0x063, "ds_inc_rtn_u64"), + (0x064, "ds_dec_rtn_u64"), + (0x065, "ds_min_rtn_i64"), + (0x066, "ds_max_rtn_i64"), + (0x067, "ds_min_rtn_u64"), + (0x068, "ds_max_rtn_u64"), + (0x069, "ds_and_rtn_b64"), + (0x06a, "ds_or_rtn_b64"), + (0x06b, "ds_xor_rtn_b64"), + (0x06c, "ds_mskor_rtn_b64"), + (0x06d, "ds_wrxchg_rtn_b64"), + (0x06e, "ds_wrxchg2_rtn_b64"), + (0x06f, "ds_wrxchg2st64_rtn_b64"), + (0x070, "ds_cmpst_rtn_b64"), + (0x071, "ds_cmpst_rtn_f64"), + (0x072, "ds_min_rtn_f64"), + (0x073, "ds_max_rtn_f64"), + (0x076, "ds_read_b64"), + (0x077, "ds_read2_b64"), + (0x078, "ds_read2st64_b64"), + (0x07e, "ds_condxchg32_rtn_b64"), + (0x080, "ds_add_src2_u32"), + (0x081, "ds_sub_src2_u32"), + (0x082, "ds_rsub_src2_u32"), + (0x083, "ds_inc_src2_u32"), + (0x084, "ds_dec_src2_u32"), + (0x085, "ds_min_src2_i32"), + (0x086, "ds_max_src2_i32"), + (0x087, "ds_min_src2_u32"), + (0x088, "ds_max_src2_u32"), + (0x089, "ds_and_src2_b32"), + (0x08a, "ds_or_src2_b32"), + (0x08b, "ds_xor_src2_b32"), + (0x08d, "ds_write_src2_b32"), + (0x092, "ds_min_src2_f32"), + (0x093, "ds_max_src2_f32"), + (0x095, "ds_add_src2_f32"), + (0x0a0, "ds_write_b8_d16_hi"), + (0x0a1, "ds_write_b16_d16_hi"), + (0x0a2, "ds_read_u8_d16"), + (0x0a3, "ds_read_u8_d16_hi"), + (0x0a4, "ds_read_i8_d16"), + (0x0a5, "ds_read_i8_d16_hi"), + (0x0a6, "ds_read_u16_d16"), + (0x0a7, "ds_read_u16_d16_hi"), + (0x0b0, "ds_write_addtid_b32"), + (0x0b1, "ds_read_addtid_b32"), + (0x0b2, "ds_permute_b32"), + (0x0b3, "ds_bpermute_b32"), + (0x0c0, "ds_add_src2_u64"), + (0x0c1, "ds_sub_src2_u64"), + (0x0c2, "ds_rsub_src2_u64"), + (0x0c3, "ds_inc_src2_u64"), + (0x0c4, "ds_dec_src2_u64"), + (0x0c5, "ds_min_src2_i64"), + (0x0c6, "ds_max_src2_i64"), + (0x0c7, "ds_min_src2_u64"), + (0x0c8, "ds_max_src2_u64"), + (0x0c9, "ds_and_src2_b64"), + (0x0ca, "ds_or_src2_b64"), + (0x0cb, "ds_xor_src2_b64"), + (0x0cd, "ds_write_src2_b64"), + (0x0d2, "ds_min_src2_f64"), + (0x0d3, "ds_max_src2_f64"), + (0x0de, "ds_write_b96"), + (0x0df, "ds_write_b128"), + (0x0fe, "ds_read_b96"), + (0x0ff, "ds_read_b128"), +]; + +pub(super) const MUBUF: &[(u16, &str)] = &[ + (0x000, "buffer_load_format_x"), + (0x001, "buffer_load_format_xy"), + (0x002, "buffer_load_format_xyz"), + (0x003, "buffer_load_format_xyzw"), + (0x004, "buffer_store_format_x"), + (0x005, "buffer_store_format_xy"), + (0x006, "buffer_store_format_xyz"), + (0x007, "buffer_store_format_xyzw"), + (0x008, "buffer_load_ubyte"), + (0x009, "buffer_load_sbyte"), + (0x00a, "buffer_load_ushort"), + (0x00b, "buffer_load_sshort"), + (0x00c, "buffer_load_dword"), + (0x00d, "buffer_load_dwordx2"), + (0x00e, "buffer_load_dwordx4"), + (0x00f, "buffer_load_dwordx3"), + (0x018, "buffer_store_byte"), + (0x019, "buffer_store_byte_d16_hi"), + (0x01a, "buffer_store_short"), + (0x01b, "buffer_store_short_d16_hi"), + (0x01c, "buffer_store_dword"), + (0x01d, "buffer_store_dwordx2"), + (0x01e, "buffer_store_dwordx4"), + (0x01f, "buffer_store_dwordx3"), + (0x020, "buffer_load_ubyte_d16"), + (0x021, "buffer_load_ubyte_d16_hi"), + (0x022, "buffer_load_sbyte_d16"), + (0x023, "buffer_load_sbyte_d16_hi"), + (0x024, "buffer_load_short_d16"), + (0x025, "buffer_load_short_d16_hi"), + (0x026, "buffer_load_format_d16_hi_x"), + (0x027, "buffer_store_format_d16_hi_x"), + (0x030, "buffer_atomic_swap"), + (0x031, "buffer_atomic_cmpswap"), + (0x032, "buffer_atomic_add"), + (0x033, "buffer_atomic_sub"), + (0x034, "buffer_atomic_csub"), + (0x035, "buffer_atomic_smin"), + (0x036, "buffer_atomic_umin"), + (0x037, "buffer_atomic_smax"), + (0x038, "buffer_atomic_umax"), + (0x039, "buffer_atomic_and"), + (0x03a, "buffer_atomic_or"), + (0x03b, "buffer_atomic_xor"), + (0x03c, "buffer_atomic_inc"), + (0x03d, "buffer_atomic_dec"), + (0x03e, "buffer_atomic_fcmpswap"), + (0x03f, "buffer_atomic_fmin"), + (0x040, "buffer_atomic_fmax"), + (0x050, "buffer_atomic_swap_x2"), + (0x051, "buffer_atomic_cmpswap_x2"), + (0x052, "buffer_atomic_add_x2"), + (0x053, "buffer_atomic_sub_x2"), + (0x055, "buffer_atomic_smin_x2"), + (0x056, "buffer_atomic_umin_x2"), + (0x057, "buffer_atomic_smax_x2"), + (0x058, "buffer_atomic_umax_x2"), + (0x059, "buffer_atomic_and_x2"), + (0x05a, "buffer_atomic_or_x2"), + (0x05b, "buffer_atomic_xor_x2"), + (0x05c, "buffer_atomic_inc_x2"), + (0x05d, "buffer_atomic_dec_x2"), + (0x05e, "buffer_atomic_fcmpswap_x2"), + (0x05f, "buffer_atomic_fmin_x2"), + (0x060, "buffer_atomic_fmax_x2"), + (0x071, "buffer_gl0_inv"), + (0x072, "buffer_gl1_inv"), + (0x080, "buffer_load_format_d16_x"), + (0x081, "buffer_load_format_d16_xy"), + (0x082, "buffer_load_format_d16_xyz"), + (0x083, "buffer_load_format_d16_xyzw"), + (0x084, "buffer_store_format_d16_x"), + (0x085, "buffer_store_format_d16_xy"), + (0x086, "buffer_store_format_d16_xyz"), + (0x087, "buffer_store_format_d16_xyzw"), +]; + +pub(super) const MTBUF: &[(u16, &str)] = &[ + (0x000, "tbuffer_load_format_x"), + (0x001, "tbuffer_load_format_xy"), + (0x002, "tbuffer_load_format_xyz"), + (0x003, "tbuffer_load_format_xyzw"), + (0x004, "tbuffer_store_format_x"), + (0x005, "tbuffer_store_format_xy"), + (0x006, "tbuffer_store_format_xyz"), + (0x007, "tbuffer_store_format_xyzw"), + (0x008, "tbuffer_load_format_d16_x"), + (0x009, "tbuffer_load_format_d16_xy"), + (0x00a, "tbuffer_load_format_d16_xyz"), + (0x00b, "tbuffer_load_format_d16_xyzw"), + (0x00c, "tbuffer_store_format_d16_x"), + (0x00d, "tbuffer_store_format_d16_xy"), + (0x00e, "tbuffer_store_format_d16_xyz"), + (0x00f, "tbuffer_store_format_d16_xyzw"), +]; + +pub(super) const MIMG: &[(u16, &str)] = &[ + (0x000, "image_load"), + (0x001, "image_load_mip"), + (0x002, "image_load_pck"), + (0x003, "image_load_pck_sgn"), + (0x004, "image_load_mip_pck"), + (0x005, "image_load_mip_pck_sgn"), + (0x008, "image_store"), + (0x009, "image_store_mip"), + (0x00a, "image_store_pck"), + (0x00b, "image_store_mip_pck"), + (0x00e, "image_get_resinfo"), + (0x00f, "image_atomic_swap"), + (0x010, "image_atomic_cmpswap"), + (0x011, "image_atomic_add"), + (0x012, "image_atomic_sub"), + (0x014, "image_atomic_smin"), + (0x015, "image_atomic_umin"), + (0x016, "image_atomic_smax"), + (0x017, "image_atomic_umax"), + (0x018, "image_atomic_and"), + (0x019, "image_atomic_or"), + (0x01a, "image_atomic_xor"), + (0x01b, "image_atomic_inc"), + (0x01c, "image_atomic_dec"), + (0x01d, "image_atomic_fcmpswap"), + (0x01e, "image_atomic_fmin"), + (0x01f, "image_atomic_fmax"), + (0x020, "image_sample"), + (0x021, "image_sample_cl"), + (0x022, "image_sample_d"), + (0x023, "image_sample_d_cl"), + (0x024, "image_sample_l"), + (0x025, "image_sample_b"), + (0x026, "image_sample_b_cl"), + (0x027, "image_sample_lz"), + (0x028, "image_sample_c"), + (0x029, "image_sample_c_cl"), + (0x02a, "image_sample_c_d"), + (0x02b, "image_sample_c_d_cl"), + (0x02c, "image_sample_c_l"), + (0x02d, "image_sample_c_b"), + (0x02e, "image_sample_c_b_cl"), + (0x02f, "image_sample_c_lz"), + (0x030, "image_sample_o"), + (0x031, "image_sample_cl_o"), + (0x032, "image_sample_d_o"), + (0x033, "image_sample_d_cl_o"), + (0x034, "image_sample_l_o"), + (0x035, "image_sample_b_o"), + (0x036, "image_sample_b_cl_o"), + (0x037, "image_sample_lz_o"), + (0x038, "image_sample_c_o"), + (0x039, "image_sample_c_cl_o"), + (0x03a, "image_sample_c_d_o"), + (0x03b, "image_sample_c_d_cl_o"), + (0x03c, "image_sample_c_l_o"), + (0x03d, "image_sample_c_b_o"), + (0x03e, "image_sample_c_b_cl_o"), + (0x03f, "image_sample_c_lz_o"), + (0x040, "image_gather4"), + (0x041, "image_gather4_cl"), + (0x044, "image_gather4_l"), + (0x045, "image_gather4_b"), + (0x046, "image_gather4_b_cl"), + (0x047, "image_gather4_lz"), + (0x048, "image_gather4_c"), + (0x049, "image_gather4_c_cl"), + (0x04c, "image_gather4_c_l"), + (0x04d, "image_gather4_c_b"), + (0x04e, "image_gather4_c_b_cl"), + (0x04f, "image_gather4_c_lz"), + (0x050, "image_gather4_o"), + (0x051, "image_gather4_cl_o"), + (0x054, "image_gather4_l_o"), + (0x055, "image_gather4_b_o"), + (0x056, "image_gather4_b_cl_o"), + (0x057, "image_gather4_lz_o"), + (0x058, "image_gather4_c_o"), + (0x059, "image_gather4_c_cl_o"), + (0x05c, "image_gather4_c_l_o"), + (0x05d, "image_gather4_c_b_o"), + (0x05e, "image_gather4_c_b_cl_o"), + (0x05f, "image_gather4_c_lz_o"), + (0x060, "image_get_lod"), + (0x068, "image_sample_cd"), + (0x069, "image_sample_cd_cl"), + (0x06a, "image_sample_c_cd"), + (0x06b, "image_sample_c_cd_cl"), + (0x06c, "image_sample_cd_o"), + (0x06d, "image_sample_cd_cl_o"), + (0x06e, "image_sample_c_cd_o"), + (0x06f, "image_sample_c_cd_cl_o"), + (0x080, "image_msaa_load"), + (0x0a2, "image_sample_d_g16"), + (0x0a3, "image_sample_d_cl_g16"), + (0x0aa, "image_sample_c_d_g16"), + (0x0ab, "image_sample_c_d_cl_g16"), + (0x0b2, "image_sample_d_o_g16"), + (0x0b3, "image_sample_d_cl_o_g16"), + (0x0ba, "image_sample_c_d_o_g16"), + (0x0bb, "image_sample_c_d_cl_o_g16"), + (0x0e6, "image_bvh_intersect_ray"), + (0x0e7, "image_bvh64_intersect_ray"), +]; + +pub(super) const FLAT: &[(u16, &str)] = &[ + (0x008, "flat_load_ubyte"), + (0x009, "flat_load_sbyte"), + (0x00a, "flat_load_ushort"), + (0x00b, "flat_load_sshort"), + (0x00c, "flat_load_dword"), + (0x00d, "flat_load_dwordx2"), + (0x00e, "flat_load_dwordx4"), + (0x00f, "flat_load_dwordx3"), + (0x018, "flat_store_byte"), + (0x019, "flat_store_byte_d16_hi"), + (0x01a, "flat_store_short"), + (0x01b, "flat_store_short_d16_hi"), + (0x01c, "flat_store_dword"), + (0x01d, "flat_store_dwordx2"), + (0x01e, "flat_store_dwordx4"), + (0x01f, "flat_store_dwordx3"), + (0x020, "flat_load_ubyte_d16"), + (0x021, "flat_load_ubyte_d16_hi"), + (0x022, "flat_load_sbyte_d16"), + (0x023, "flat_load_sbyte_d16_hi"), + (0x024, "flat_load_short_d16"), + (0x025, "flat_load_short_d16_hi"), + (0x030, "flat_atomic_swap"), + (0x031, "flat_atomic_cmpswap"), + (0x032, "flat_atomic_add"), + (0x033, "flat_atomic_sub"), + (0x035, "flat_atomic_smin"), + (0x036, "flat_atomic_umin"), + (0x037, "flat_atomic_smax"), + (0x038, "flat_atomic_umax"), + (0x039, "flat_atomic_and"), + (0x03a, "flat_atomic_or"), + (0x03b, "flat_atomic_xor"), + (0x03c, "flat_atomic_inc"), + (0x03d, "flat_atomic_dec"), + (0x03e, "flat_atomic_fcmpswap"), + (0x03f, "flat_atomic_fmin"), + (0x040, "flat_atomic_fmax"), + (0x050, "flat_atomic_swap_x2"), + (0x051, "flat_atomic_cmpswap_x2"), + (0x052, "flat_atomic_add_x2"), + (0x053, "flat_atomic_sub_x2"), + (0x055, "flat_atomic_smin_x2"), + (0x056, "flat_atomic_umin_x2"), + (0x057, "flat_atomic_smax_x2"), + (0x058, "flat_atomic_umax_x2"), + (0x059, "flat_atomic_and_x2"), + (0x05a, "flat_atomic_or_x2"), + (0x05b, "flat_atomic_xor_x2"), + (0x05c, "flat_atomic_inc_x2"), + (0x05d, "flat_atomic_dec_x2"), + (0x05e, "flat_atomic_fcmpswap_x2"), + (0x05f, "flat_atomic_fmin_x2"), + (0x060, "flat_atomic_fmax_x2"), +]; + +pub(super) const GLOBAL: &[(u16, &str)] = &[ + (0x008, "global_load_ubyte"), + (0x009, "global_load_sbyte"), + (0x00a, "global_load_ushort"), + (0x00b, "global_load_sshort"), + (0x00c, "global_load_dword"), + (0x00d, "global_load_dwordx2"), + (0x00e, "global_load_dwordx4"), + (0x00f, "global_load_dwordx3"), + (0x016, "global_load_dword_addtid"), + (0x017, "global_store_dword_addtid"), + (0x018, "global_store_byte"), + (0x019, "global_store_byte_d16_hi"), + (0x01a, "global_store_short"), + (0x01b, "global_store_short_d16_hi"), + (0x01c, "global_store_dword"), + (0x01d, "global_store_dwordx2"), + (0x01e, "global_store_dwordx4"), + (0x01f, "global_store_dwordx3"), + (0x020, "global_load_ubyte_d16"), + (0x021, "global_load_ubyte_d16_hi"), + (0x022, "global_load_sbyte_d16"), + (0x023, "global_load_sbyte_d16_hi"), + (0x024, "global_load_short_d16"), + (0x025, "global_load_short_d16_hi"), + (0x030, "global_atomic_swap"), + (0x031, "global_atomic_cmpswap"), + (0x032, "global_atomic_add"), + (0x033, "global_atomic_sub"), + (0x034, "global_atomic_csub"), + (0x035, "global_atomic_smin"), + (0x036, "global_atomic_umin"), + (0x037, "global_atomic_smax"), + (0x038, "global_atomic_umax"), + (0x039, "global_atomic_and"), + (0x03a, "global_atomic_or"), + (0x03b, "global_atomic_xor"), + (0x03c, "global_atomic_inc"), + (0x03d, "global_atomic_dec"), + (0x03e, "global_atomic_fcmpswap"), + (0x03f, "global_atomic_fmin"), + (0x040, "global_atomic_fmax"), + (0x050, "global_atomic_swap_x2"), + (0x051, "global_atomic_cmpswap_x2"), + (0x052, "global_atomic_add_x2"), + (0x053, "global_atomic_sub_x2"), + (0x055, "global_atomic_smin_x2"), + (0x056, "global_atomic_umin_x2"), + (0x057, "global_atomic_smax_x2"), + (0x058, "global_atomic_umax_x2"), + (0x059, "global_atomic_and_x2"), + (0x05a, "global_atomic_or_x2"), + (0x05b, "global_atomic_xor_x2"), + (0x05c, "global_atomic_inc_x2"), + (0x05d, "global_atomic_dec_x2"), + (0x05e, "global_atomic_fcmpswap_x2"), + (0x05f, "global_atomic_fmin_x2"), + (0x060, "global_atomic_fmax_x2"), +]; + +pub(super) const SCRATCH: &[(u16, &str)] = &[ + (0x008, "scratch_load_ubyte"), + (0x009, "scratch_load_sbyte"), + (0x00a, "scratch_load_ushort"), + (0x00b, "scratch_load_sshort"), + (0x00c, "scratch_load_dword"), + (0x00d, "scratch_load_dwordx2"), + (0x00e, "scratch_load_dwordx4"), + (0x00f, "scratch_load_dwordx3"), + (0x018, "scratch_store_byte"), + (0x019, "scratch_store_byte_d16_hi"), + (0x01a, "scratch_store_short"), + (0x01b, "scratch_store_short_d16_hi"), + (0x01c, "scratch_store_dword"), + (0x01d, "scratch_store_dwordx2"), + (0x01e, "scratch_store_dwordx4"), + (0x01f, "scratch_store_dwordx3"), + (0x020, "scratch_load_ubyte_d16"), + (0x021, "scratch_load_ubyte_d16_hi"), + (0x022, "scratch_load_sbyte_d16"), + (0x023, "scratch_load_sbyte_d16_hi"), + (0x024, "scratch_load_short_d16"), + (0x025, "scratch_load_short_d16_hi"), +]; + +#[cfg(test)] +mod tests { + fn bytes(words: &[u32]) -> Vec { + words.iter().flat_map(|w| w.to_le_bytes()).collect() + } + + /// `s_ttracedata_imm 0x1234` as LLVM's GFX10 disassembler tests have it + /// (`gfx10_sopp.txt`: `0x34,0x12,0xa8,0xbf`), SOPP opcode 0x28 as in + /// AMD's RDNA2 ISA. A thread-trace marker, which translation drops. + #[test] + fn s_ttracedata_imm_is_sopp_0x28() { + let code = bytes(&[0xBFA8_1234, 0xBF81_0000]); + let decoded = super::super::decode(&code).unwrap(); + assert_eq!(decoded[0].name(), Some("s_ttracedata_imm")); + assert!(crate::ir::build(&code, false, 1).is_ok()); + } +} diff --git a/crates/leonida-shader/src/gfx10/sp3.rs b/crates/leonida-shader/src/gfx10/sp3.rs new file mode 100644 index 000000000..0ca5ab414 --- /dev/null +++ b/crates/leonida-shader/src/gfx10/sp3.rs @@ -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_`. + 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!(""), + } +} + +fn join(ops: impl IntoIterator) -> String { + ops.into_iter().collect::>().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::>() + .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!(""), + }; + 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 = v + .dst + .iter() + .chain(&v.carry) + .map(|o| o.to_string()) + .collect(); + let mut order: Vec = (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 = (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 { + let mut code: Vec = 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 = 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); + } +} diff --git a/crates/leonida-shader/src/io.rs b/crates/leonida-shader/src/io.rs new file mode 100644 index 000000000..09b1f8e69 --- /dev/null +++ b/crates/leonida-shader/src/io.rs @@ -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` 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` 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); 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, + }, + /// 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; 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, + /// Compute: how many SGPRs the hardware initializes + /// ([`ComputeIo::initialized_sgprs`](crate::native::ComputeIo::initialized_sgprs)). + pub initialized_sgprs: Option, +} + +/// 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 { + 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 = 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| 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 = 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 = 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, + first: Vec, +} + +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, + phis: &'a std::collections::HashMap, +} + +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, + j: Option, + barycentric: &impl Fn(Option) -> Option<(Barycentric, u8)>, + ) -> Result { + 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, + out: &mut Vec, + ) -> 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 = words.iter().flat_map(|w| w.to_le_bytes()).collect(); + crate::ir::build(&code, false, 256).unwrap() + } + + fn pixel(inputs: Vec, 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::::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 = 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)), + ] + ); + } +} diff --git a/crates/leonida-shader/src/ir.rs b/crates/leonida-shader/src/ir.rs new file mode 100644 index 000000000..0b8fd9c6d --- /dev/null +++ b/crates/leonida-shader/src/ir.rs @@ -0,0 +1,1791 @@ +//! One-to-one SSA form of a native program (decision 0003, step 1). +//! +//! Every machine instruction becomes one [`Inst`], except scheduling-only +//! ones (`s_nop`, `s_waitcnt*`, `s_inst_prefetch`...), which are dropped. +//! Each register dword is a variable: a read names the [`Value`] it sees, a +//! write defines a new one, and [`Phi`]s merge values where control flow +//! joins. Nothing is raised: an instruction keeps its opcode and decoded +//! fields, so its exact semantics stay with it. +//! +//! Implicit operands are explicit: SCC, M0, and EXEC, which every vector +//! instruction reads. A write to a VGPR also reads the register's old value, +//! because lanes disabled in EXEC keep it. +//! +//! M0-relative VGPR access (`v_movrels/d/sd_b32`, `v_swaprel_b32`) names its +//! operand's whole possible range: from the encoded register up to the +//! program's VGPR count, all read (and all written, for a destination). + +use crate::ShaderError; +use crate::gfx10::{self, Fields, Flow, Instruction, Operand}; + +/// One register dword. Scalar codes as in [`Operand::Scalar`]: 0-105 SGPRs, +/// 106/107 VCC, 108-123 trap temporaries, 124 M0, 126/127 EXEC. Codes from +/// [`PARKED`] up are scalars the compiler parked in VGPR lanes (`unspill`): +/// no machine instruction names them. +#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] +pub enum Reg { + S(u8), + Scc, + V(u8), +} + +pub const VCC: u8 = 106; +pub const M0: u8 = 124; +pub const EXEC: u8 = 126; +/// The first scalar code past the machine's (0-127): see [`Reg`]. +pub const PARKED: u8 = 128; + +/// An SSA value: the content of one register dword (SCC: one bit). +#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] +pub struct Value(pub u32); + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Program { + pub wave64: bool, + /// VGPRs v0 up to this exist; bounds M0-relative access. + pub vgprs: u16, + /// In code order, then copies made to give every loop one entry; block 0 + /// is the entry. + pub blocks: Vec, + /// Registers read before any write, with their value on entry: what the + /// hardware or a called fetch routine set up (user SGPRs, system values, + /// vertex inputs). + pub inputs: Vec<(Reg, Value)>, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Block { + /// Byte offset of the block's first machine instruction (shared by a + /// block and its copies). + pub offset: usize, + pub preds: Vec, + pub phis: Vec, + pub insts: Vec, + pub exit: Exit, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Exit { + Jump(usize), + /// `s_cbranch_*`, the block's last instruction. + Branch { + taken: usize, + not_taken: usize, + }, + /// `s_endpgm` and its variants. + End, + /// `s_setpc_b64` to an address held in registers, e.g. the handover to + /// the next half of a merged hardware stage. + Indirect, +} + +impl Exit { + pub fn successors(&self) -> Vec { + match *self { + Exit::Jump(b) => vec![b], + Exit::Branch { taken, not_taken } => vec![taken, not_taken], + Exit::End | Exit::Indirect => vec![], + } + } +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Phi { + pub reg: Reg, + pub value: Value, + /// One per predecessor, in [`Block::preds`] order. + pub args: Vec, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Inst { + pub machine: Instruction, + pub fields: Fields, + /// Every register dword read, with the value it holds. + pub reads: Vec<(Reg, Value)>, + /// Every register dword written, with the value it receives. + pub writes: Vec<(Reg, Value)>, +} + +impl Inst { + pub fn name(&self) -> &'static str { + self.machine.name().unwrap_or("") + } + + /// The value `reg` holds when this instruction reads it. + pub fn read(&self, reg: Reg) -> Option { + self.reads.iter().find(|r| r.0 == reg).map(|r| r.1) + } + + /// The value this instruction writes to `reg`. + pub fn write(&self, reg: Reg) -> Option { + self.writes.iter().find(|w| w.0 == reg).map(|w| w.1) + } +} + +/// Decodes `code` and builds its SSA form; `vgprs` is the program's VGPR +/// count. Fails on instructions the IR cannot express yet +/// ([`ShaderError::Unsupported`]). +pub fn build(code: &[u8], wave64: bool, vgprs: u16) -> Result { + let mut list = gfx10::decode(code)?; + let lanes = 1 + u8::from(wave64); + let isa = |offset, reason| ShaderError::Isa { offset, reason }; + + let mut flows = Vec::with_capacity(list.len()); + let mut leaders = vec![0]; + for (i, inst) in list.iter().enumerate() { + let flow = gfx10::control(inst, code.len(), |at| { + list[..list.partition_point(|i| i.offset < at)].last() + })?; + if let Flow::Jump(t) | Flow::Branch(t) = flow { + leaders.push(t); + } + if flow != Flow::Next + && let Some(next) = list.get(i + 1) + { + leaders.push(next.offset); + } + flows.push(flow); + } + leaders.sort_unstable(); + leaders.dedup(); + let parked = unspill(&mut list, &leaders, wave64, lanes, vgprs); + let block_at = |offset: usize| { + leaders + .binary_search(&offset) + .map_err(|_| isa(offset, "jump into a block")) + }; + + let mut blocks: Vec = leaders + .iter() + .map(|&offset| Block { + offset, + preds: Vec::new(), + phis: Vec::new(), + insts: Vec::new(), + exit: Exit::End, + }) + .collect(); + let next_offsets: Vec> = (0..list.len()) + .map(|i| list.get(i + 1).map(|n| n.offset)) + .collect(); + for (n, ((machine, flow), next)) in list.into_iter().zip(flows).zip(next_offsets).enumerate() { + let b = leaders.partition_point(|&l| l <= machine.offset) - 1; + let name = machine.name().ok_or(ShaderError::Unsupported { + offset: machine.offset, + what: "unknown opcode", + })?; + let mut fields = machine.fields(wave64); + // A move to or from a scalar parked in a VGPR lane (`unspill`): its register + // codes may be ones the machine word cannot hold. + if let Ok(k) = parked.binary_search_by_key(&n, |m| m.0) + && let Fields::Sop { dst: Some(Operand::Scalar { code: to, .. }), src, .. } = &mut fields + && let Some(Operand::Scalar { code: from, .. }) = src.first_mut() + { + (*to, *from) = (parked[k].1, parked[k].2); + } + let fallthrough = || block_at(next.ok_or(isa(machine.offset, "falls off the code"))?); + let ends = flow != Flow::Next || next.is_none_or(|n| leaders.binary_search(&n).is_ok()); + if ends { + blocks[b].exit = match flow { + Flow::Next => Exit::Jump(fallthrough()?), + Flow::Jump(t) => Exit::Jump(block_at(t)?), + Flow::Branch(t) => Exit::Branch { + taken: block_at(t)?, + not_taken: fallthrough()?, + }, + Flow::Stop if name == "s_setpc_b64" => Exit::Indirect, + Flow::Stop => Exit::End, + }; + } + if let Some((mut reads, writes)) = effects(&machine, &fields, name, lanes, vgprs)? { + // Lanes disabled in EXEC keep the old value. + for w in writes.iter().filter(|w| matches!(w, Reg::V(_))) { + if !reads.contains(w) { + reads.push(*w); + } + } + let unset = |regs: Vec| regs.into_iter().map(|r| (r, NONE)).collect(); + blocks[b].insts.push(Inst { + machine, + fields, + reads: unset(reads), + writes: unset(writes), + }); + } + } + link(&mut blocks); + if !blocks[0].preds.is_empty() { + return Err(ShaderError::Unsupported { + offset: 0, + what: "a branch to the program entry", + }); + } + split_irreducible(&mut blocks)?; + + Ok(rename(blocks, wave64, vgprs)) +} + +/// Scalar registers the compiler parked in lanes of a VGPR, as scalar moves. +/// +/// When it runs out of SGPRs the console compiler saves one in a lane of a +/// spare VGPR (`v_writelane_b32 vN, sX, K`) and takes it back later +/// (`v_readlane_b32 sX, vN, K`). A VGPR whose every use in the program is one +/// of those two forms with a constant lane is such a store: lane K of it is a +/// scalar register by another name. Each (VGPR, lane) gets a register code +/// the program does not use (the trap temporaries first, then SGPRs it never +/// names, then codes from [`PARKED`] up, which no machine word can hold), and +/// the save and the restore become `s_mov_b32` to and from it. Returns those +/// moves (index in `list`, destination code, source code) in order, for +/// `build` to put the codes into the decoded fields. They are then copies for +/// every later stage: a parked descriptor is traced to its load, and nothing +/// is left of a cross-lane operation, which a console wave run as two host +/// waves could not do where not every lane runs (the lane may be in the other +/// wave, or not running). +/// A register pair parked in two neighbouring lanes (a lane mask, a 64-bit +/// address) moves as a pair (`s_mov_b64`) when every save and every restore +/// of the two lanes come together, so a parked lane mask comes back as the +/// mask it is; otherwise its halves come back as two scalars. +fn unspill( + list: &mut [gfx10::Instruction], + leaders: &[usize], + wave64: bool, + lanes: u8, + vgprs: u16, +) -> Vec<(usize, u8, u8)> { + /// `v_writelane_b32 vN, sX, K` / `v_readlane_b32 sX, vN, K`: (save, N, X, K). + fn parked(inst: &gfx10::Instruction, fields: &Fields) -> Option<(bool, u8, u8, u32)> { + let Fields::Valu(v) = fields else { return None }; + if v.abs != 0 || v.neg != 0 || v.opsel != 0 || v.clamp || v.omod != 0 || v.sdwa.is_some() || v.dpp.is_some() { + return None; + } + let lane = |op: &Operand| match *op { + Operand::Const(c @ 128..=191) => Some(u32::from(c) - 128), + _ => None, + }; + match (inst.name()?, v.dst?, v.src.as_slice()) { + ("v_writelane_b32", Operand::Vector { reg, .. }, [Operand::Scalar { code, .. }, k]) if *code < 105 => { + Some((true, reg, *code, lane(k)?)) + } + ("v_readlane_b32", Operand::Scalar { code, .. }, [Operand::Vector { reg, .. }, k]) if code < 105 => { + Some((false, *reg, code, lane(k)?)) + } + _ => None, + } + } + // VGPRs used by parking alone, the scalar codes the program uses, and + // per instruction the scalar codes it writes. + let mut stores = [false; 256]; + let mut other = [false; 256]; + let mut used = [false; 128]; + let mut parks: Vec> = Vec::with_capacity(list.len()); + let mut written: Vec> = Vec::with_capacity(list.len()); + let mut read: Vec> = Vec::with_capacity(list.len()); + for inst in list.iter() { + let Some(name) = inst.name() else { return Vec::new() }; + let fields = inst.fields(wave64); + let park = parked(inst, &fields); + let Ok(effects) = effects(inst, &fields, name, lanes, vgprs) else { + return Vec::new(); + }; + let mut codes = Vec::new(); + let mut from = Vec::new(); + if let Some((reads, writes)) = effects { + for ® in &writes { + if let Reg::S(c) = reg { + codes.push(c); + } + } + for ® in &reads { + if let Reg::S(c) = reg { + from.push(c); + } + } + // An M0-relative read (`v_movrels_b32`) names every VGPR from its + // base up; the compiler indexes a small array with it, never the + // lanes it parks scalars in, so it does not make those VGPRs + // ordinary ones. (Relative writes still do.) + let relative = name == "v_movrels_b32"; + let n_reads = reads.len(); + for (k, reg) in reads.into_iter().chain(writes).enumerate() { + if relative && k < n_reads && matches!(reg, Reg::V(_)) { + continue; + } + match reg { + Reg::S(c) => used[usize::from(c)] = true, + Reg::V(r) if park.is_some_and(|p| p.1 == r) => stores[usize::from(r)] = true, + Reg::V(r) => other[usize::from(r)] = true, + Reg::Scc => {} + } + } + } + parks.push(park); + written.push(codes); + read.push(from); + } + for (i, park) in parks.iter_mut().enumerate() { + if park.is_some_and(|p| other[usize::from(p.1)]) { + *park = None; + } + let _ = i; + } + if parks.iter().all(Option::is_none) { + return Vec::new(); + } + let leader = |i: usize| leaders.binary_search(&list[i].offset).is_ok(); + // Lane pairs (register, lower lane) that always move together: each + // save of the lower lane is followed, in the same block and before its + // register changes, by the save of the next register into the next + // lane; each restore of the lower lane is followed at once by the + // restore of the next lane into the next register. + // The second save may come any number of instructions after the first (the + // compiler puts loads and constants between the two: five instructions later + // in the ped mesh programs). Only wave64 programs have pairs: a wave32 mask + // is one dword, and a pair move of it with its neighbour would hide it. + let mut slots: Vec<(u8, u32)> = parks.iter().flatten().map(|p| (p.1, p.3)).collect(); + slots.sort_unstable(); + slots.dedup(); + // instruction -> the instruction that completes its pair + let partner = |i: usize| -> Option { + let (save, reg, code, lane) = parks[i]?; + if save { + let mut j = i + 1; + while j < list.len() && !leader(j) { + if parks[j] == Some((true, reg, code + 1, lane + 1)) { + return Some(j); + } + if parks[j].is_some_and(|p| p.1 == reg && (p.3 == lane || p.3 == lane + 1)) + || written[j].contains(&code) + || written[j].contains(&(code + 1)) + { + return None; + } + j += 1; + } + None + } else { + // The second restore may come a few instructions later (the + // compiler schedules other work between the two): the pair is + // restored at the first, so nothing between may read or write + // the second register, write the first, or save into the lanes. + let mut j = i + 1; + while j < list.len() && !leader(j) { + if parks[j] == Some((false, reg, code + 1, lane + 1)) { + return Some(j); + } + if parks[j].is_some_and(|p| p.0 && p.1 == reg && (p.3 == lane || p.3 == lane + 1)) + || written[j].contains(&code) + || written[j].contains(&(code + 1)) + || read[j].contains(&(code + 1)) + { + return None; + } + j += 1; + } + None + } + }; + let mut pairs: Vec<(u8, u32)> = Vec::new(); + for &(reg, lane) in &slots { + if !wave64 || pairs.iter().any(|&(r, l)| r == reg && l + 1 == lane) || !slots.contains(&(reg, lane + 1)) { + continue; + } + let lower: Vec = (0..list.len()).filter(|&i| parks[i].is_some_and(|p| (p.1, p.3) == (reg, lane))).collect(); + let upper = parks.iter().flatten().filter(|p| (p.1, p.3) == (reg, lane + 1)).count(); + let partners: Vec> = lower.iter().map(|&i| partner(i)).collect(); + let mut distinct: Vec = partners.iter().flatten().copied().collect(); + distinct.sort_unstable(); + distinct.dedup(); + if partners.iter().all(Option::is_some) && distinct.len() == lower.len() && upper == lower.len() { + pairs.push((reg, lane)); + } + } + // Codes for the parked scalars: the trap temporaries (108..=123), then + // user SGPRs the program never names, from the top, then the codes past + // the machine's (`PARKED`..=254; 255 stays unused so that the code after a + // parked one always exists). A material resolve program parks up to 63 + // scalars and leaves about 20 machine codes unused. + let past = usize::from(PARKED); + let mut free = [false; 256]; + for c in (0..105).chain(108..=123) { + free[c] = !used[c]; + } + free[past..255].fill(true); + let mut codes: Vec<((u8, u32), u8)> = Vec::new(); + for &(reg, lane) in &pairs { + let at = (108..123).chain((0..104).rev()).chain(past..254).find(|&c| free[c] && free[c + 1]); + // Not enough spare codes: leave the program as it is. + let Some(c) = at else { return Vec::new() }; + (free[c], free[c + 1]) = (false, false); + codes.push(((reg, lane), c as u8)); + codes.push(((reg, lane + 1), c as u8 + 1)); + } + for &slot in &slots { + if codes.iter().any(|c| c.0 == slot) { + continue; + } + let Some(c) = (108..=123).chain((0..105).rev()).chain(past..255).find(|&c| free[c]) else { + return Vec::new(); + }; + free[c] = false; + codes.push((slot, c as u8)); + } + let code_of = |reg: u8, lane: u32| codes.iter().find(|c| c.0 == (reg, lane)).map(|c| c.1); + let put = |list: &mut [gfx10::Instruction], i: usize, encoding, opcode: u16, word: u32| { + list[i] = gfx10::Instruction { + offset: list[i].offset, + encoding, + opcode, + words: vec![word], + }; + }; + // `s_mov_b32` / `s_mov_b64 dst, src` (SOP1, opcodes 3 and 4); `s_nop`. A code + // from `PARKED` up does not fit the word: s0 stands in for it there. + let field = |code: u8| if code < PARKED { u32::from(code) } else { 0 }; + let mov = |wide: bool, dst: u8, src: u8| 0xBE80_0000 | field(dst) << 16 | (3 + u32::from(wide)) << 8 | field(src); + const NOP: u32 = 0xBF80_0000; + let mut edits: Vec<(usize, Option<(bool, u8, u8)>)> = Vec::new(); + for i in 0..list.len() { + let Some((save, reg, code, lane)) = parks[i] else { + continue; + }; + let Some(slot) = code_of(reg, lane) else { return Vec::new() }; + if pairs.contains(&(reg, lane)) { + let Some(j) = partner(i) else { return Vec::new() }; + // A save moves the pair where its second half is saved; a + // restore where its first half is restored. + let (at, gone) = if save { (j, i) } else { (i, j) }; + let (dst, src) = if save { (slot, code) } else { (code, slot) }; + edits.push((at, Some((true, dst, src)))); + edits.push((gone, None)); + } else if lane > 0 && pairs.contains(&(reg, lane - 1)) { + // the upper half of a pair: moved with the lower + } else { + let (dst, src) = if save { (slot, code) } else { (code, slot) }; + edits.push((i, Some((false, dst, src)))); + } + } + let mut moves = Vec::new(); + for (i, edit) in edits { + match edit { + Some((wide, dst, src)) => { + put(list, i, gfx10::Encoding::Sop1, 3 + u16::from(wide), mov(wide, dst, src)); + moves.push((i, dst, src)); + } + None => put(list, i, gfx10::Encoding::Sopp, 0, NOP), + } + } + moves.sort_unstable(); + moves +} + +/// Rename register reads and writes after changing edges in a reducible graph. +fn rename(mut blocks: Vec, wave64: bool, vgprs: u16) -> Program { + let order = reverse_postorder(&blocks); + let (live_in, live_out) = liveness(&blocks, &order); + let mut values = 0u32; + let mut new_value = || { + values += 1; + Value(values - 1) + }; + let mut inputs = Vec::new(); + let mut outs: Vec> = vec![Vec::new(); blocks.len()]; + let mut current = [NONE; REGS]; + for &b in &order { + current.fill(NONE); + let block = &mut blocks[b]; + for reg in members(&live_in[b]) { + current[index(reg)] = match block.preds[..] { + [] => { + let v = new_value(); + inputs.push((reg, v)); + v + } + // A single predecessor comes earlier in reverse postorder. + [p] => lookup(&outs[p], reg), + _ => { + let value = new_value(); + block.phis.push(Phi { + reg, + value, + args: Vec::new(), + }); + value + } + }; + } + for inst in &mut block.insts { + for (reg, v) in &mut inst.reads { + *v = current[index(*reg)]; + debug_assert_ne!(*v, NONE, "{reg:?} read at {:#x}", inst.machine.offset); + } + for (reg, v) in &mut inst.writes { + *v = new_value(); + current[index(*reg)] = *v; + } + } + outs[b] = members(&live_out[b]) + .map(|reg| (reg, current[index(reg)])) + .collect(); + } + for block in &mut blocks { + for phi in &mut block.phis { + phi.args = block + .preds + .iter() + .map(|&p| lookup(&outs[p], phi.reg)) + .collect(); + debug_assert!(!phi.args.contains(&NONE), "{phi:?}"); + } + } + remove_trivial_phis(&mut blocks, values); + Program { + wave64, + vgprs, + blocks, + inputs, + } +} + +/// Duplicate a join for each proven (predecessor, join, destination) edge. +/// The instructions still execute on that path and define fresh SSA values. +pub(crate) fn thread_edges( + p: &Program, + edges: &[(usize, usize, usize)], +) -> Result { + let mut blocks = p.blocks.clone(); + for block in &mut blocks { + block.phis.clear(); + } + for &(pred, join, dest) in edges { + let mut copy = blocks[join].clone(); + copy.exit = Exit::Jump(dest); + let target = blocks.len(); + match &mut blocks[pred].exit { + Exit::Jump(t) => *t = target, + Exit::Branch { taken, not_taken } => { + if *taken == join { + *taken = target; + } + if *not_taken == join { + *not_taken = target; + } + } + _ => unreachable!("threading an incoming edge"), + } + blocks.push(copy); + } + link(&mut blocks); + split_irreducible(&mut blocks)?; + Ok(rename(blocks, p.wave64, p.vgprs)) +} + +/// The program without its early-outs: an `s_cbranch_execz` to a block that +/// only ends the program (`if (!inBounds) return;`, the outermost branch of +/// most compute programs) is left out, so the lanes that would have left +/// walk the body with EXEC clear. Vector instructions and every effect are +/// masked by EXEC already, as on the console, where the branch is taken +/// only when no lane of the wave is left; scalar code has no effects. The +/// body is then code every lane runs, which a console wave run as two host +/// waves needs for the barriers of its exchanges and LDS accesses. +/// `None` if the program has no such branch. +pub(crate) fn without_early_outs(p: &Program) -> Option { + let ends = |b: usize| { + p.blocks[b].exit == Exit::End + && p.blocks[b].insts.iter().all(|i| matches!(i.fields, crate::gfx10::Fields::Sopp { .. })) + }; + let mut blocks = p.blocks.clone(); + let mut any = false; + for block in &mut blocks { + let Exit::Branch { taken, not_taken } = block.exit else { + continue; + }; + if ends(taken) && block.insts.last().is_some_and(|i| i.name() == "s_cbranch_execz") { + block.insts.pop(); + block.exit = Exit::Jump(not_taken); + any = true; + } + } + if !any { + return None; + } + for block in &mut blocks { + block.phis.clear(); + } + link(&mut blocks); + split_irreducible(&mut blocks).ok()?; + Some(rename(blocks, p.wave64, p.vgprs)) +} + +/// As [`without_early_outs`], and also without the branches that only skip a +/// region when no lane is left for it: an `s_cbranch_execz` whose target is +/// where the skipped code ends up anyway (`if (c) { ... }` with nothing +/// else leaving the region). Every lane then walks the region with EXEC +/// clear for those that would have skipped it, and LDS accesses and +/// exchanges inside it are in code every lane runs. +/// The console takes such a branch only when no lane of the wave is left, +/// and then its scalar code does not run: a branch is kept if the code +/// after it could see that (a scalar register or SCC that the region +/// changes and the join merges with the value from before; EXEC aside, +/// which is empty either way). `None` if nothing changes. +/// +/// `deep` looks closer at what the code after the branch can see. A scalar the region moves +/// away and back (the compiler parks scalars in VGPR lanes around a branch and takes them +/// back before the join, `unspill`) is the value it copies; a join nothing reads shows no +/// one the difference (a restore of EXEC that the next one overwrites reads nothing); and +/// the join may have other ways in (an inner branch that ends together with an outer one). +/// That leaves out most of the skips of the title's large lighting programs, whose bodies +/// are then code every lane runs. +pub(crate) fn without_skips(p: &Program, deep: bool) -> Option { + let n = p.blocks.len(); + let ends = |b: usize| { + p.blocks[b].exit == Exit::End + && p.blocks[b].insts.iter().all(|i| matches!(i.fields, crate::gfx10::Fields::Sopp { .. })) + }; + // Scalars moved from register to register (a scalar the compiler parked in a VGPR lane + // comes back by such a move, `unspill`) are the value they copy. + let mut copy: std::collections::HashMap = Default::default(); + // Values something reads, directly or through joins. A scalar operation none of whose + // results is read reads nothing either (the compiler restores EXEC from a saved mask + // and overwrites it at once where two branches end together). + let mut live: std::collections::HashSet = Default::default(); + let idle = |inst: &Inst, live: &std::collections::HashSet| { + let name = inst.name(); + matches!(inst.fields, crate::gfx10::Fields::Sop { .. }) + && !(name.starts_with("s_setpc") + || name.starts_with("s_swappc") + || name.starts_with("s_call") + || name.starts_with("s_rfe") + || name.starts_with("s_movrel") + || name.starts_with("s_subvector")) + && inst.writes.iter().all(|w| !live.contains(&w.1)) + }; + for block in &p.blocks { + for inst in &block.insts { + if matches!(inst.name(), "s_mov_b32" | "s_mov_b64") + && inst.reads.len() == inst.writes.len() + && inst.reads.iter().chain(&inst.writes).all(|r| matches!(r.0, Reg::S(_))) + { + copy.extend(inst.writes.iter().zip(&inst.reads).map(|(w, r)| (w.1, r.1))); + } + } + } + let mut changed = true; + while changed { + changed = false; + for block in &p.blocks { + for inst in &block.insts { + if !idle(inst, &live) { + for r in &inst.reads { + changed |= live.insert(r.1); + } + } + } + for phi in &block.phis { + if live.contains(&phi.value) { + for &a in &phi.args { + changed |= live.insert(a); + } + } + } + } + } + let root = |mut v: Value| { + while deep && let Some(&c) = copy.get(&v) { + v = c; + } + v + }; + // The region a skip of `b` to `target` leaves out, if it is a pure skip. + let skipped = |b: usize, target: usize, first: usize| -> Option> { + let mut inside = vec![false; n]; + let mut stack = vec![first]; + while let Some(x) = stack.pop() { + if x == target || inside[x] { + continue; + } + if x == b { + return None; // a loop back to the branch + } + inside[x] = true; + match p.blocks[x].exit { + Exit::End | Exit::Indirect => return None, + exit => stack.extend(exit.successors()), + } + } + // entered only through the branch + for x in (0..n).filter(|&x| inside[x]) { + if p.blocks[x].preds.iter().any(|&q| q != b && !inside[q]) { + return None; + } + } + // the join sees no scalar the region changed + let join = &p.blocks[target]; + for phi in &join.phis { + let scalar = match phi.reg { + Reg::S(c) => c != 126 && c != 127, + Reg::Scc => true, + Reg::V(_) => false, + }; + // (a join nothing reads shows no one the difference) + if !scalar || deep && !live.contains(&phi.value) { + continue; + } + let before: Vec = + join.preds.iter().zip(&phi.args).filter(|(q, _)| **q == b).map(|(_, a)| root(*a)).collect(); + let within = join.preds.iter().zip(&phi.args).filter(|(q, _)| inside[**q]).map(|(_, a)| root(*a)); + if within.into_iter().any(|a| !before.contains(&a)) { + return None; + } + } + // Other ways into the join than the branch and the region (an inner branch that ends + // together with an outer one) change nothing in that: the lanes that would have + // skipped arrive from the region instead, with the same scalars. + if !deep && join.preds.iter().any(|&q| q != b && !inside[q]) { + return None; + } + Some(inside) + }; + let mut blocks = p.blocks.clone(); + let mut any = false; + for b in 0..n { + let Exit::Branch { taken, not_taken } = p.blocks[b].exit else { + continue; + }; + if !p.blocks[b].insts.last().is_some_and(|i| i.name() == "s_cbranch_execz") { + continue; + } + if ends(taken) || skipped(b, taken, not_taken).is_some() { + blocks[b].insts.pop(); + blocks[b].exit = Exit::Jump(not_taken); + any = true; + } + } + if !any { + return None; + } + for block in &mut blocks { + block.phis.clear(); + } + link(&mut blocks); + split_irreducible(&mut blocks).ok()?; + Some(rename(blocks, p.wave64, p.vgprs)) +} + +/// Placeholder before renaming. +const NONE: Value = Value(u32::MAX); +/// Scalar codes 0-255 (from [`PARKED`] up: parked scalars), SCC, VGPRs 0-255. +const REGS: usize = 256 + 1 + 256; +type RegSet = [u64; REGS.div_ceil(64)]; + +fn index(reg: Reg) -> usize { + match reg { + Reg::S(c) => usize::from(c), + Reg::Scc => 256, + Reg::V(r) => 257 + usize::from(r), + } +} + +fn reg_at(i: usize) -> Reg { + match i { + 0..256 => Reg::S(i as u8), + 256 => Reg::Scc, + _ => Reg::V((i - 257) as u8), + } +} + +fn insert(set: &mut RegSet, reg: Reg) { + let i = index(reg); + set[i / 64] |= 1 << (i % 64); +} + +fn contains(set: &RegSet, reg: Reg) -> bool { + let i = index(reg); + set[i / 64] >> (i % 64) & 1 != 0 +} + +/// In [`Reg`] order, which is also index order. +fn members(set: &RegSet) -> impl Iterator + '_ { + (0..REGS) + .filter(|&i| set[i / 64] >> (i % 64) & 1 != 0) + .map(reg_at) +} + +/// `outs` is sorted by register, and holds every register live out. +fn lookup(outs: &[(Reg, Value)], reg: Reg) -> Value { + outs.binary_search_by_key(®, |&(r, _)| r) + .map_or(NONE, |i| outs[i].1) +} + +pub(crate) fn reverse_postorder(blocks: &[Block]) -> Vec { + let mut seen = vec![false; blocks.len()]; + let mut post = Vec::with_capacity(blocks.len()); + let mut stack = vec![(0, 0)]; + seen[0] = true; + while let Some(top) = stack.last_mut() { + let (b, i) = *top; + top.1 += 1; + match blocks[b].exit.successors().get(i) { + Some(&s) if !seen[s] => { + seen[s] = true; + stack.push((s, 0)); + } + Some(_) => {} + None => { + post.push(b); + stack.pop(); + } + } + } + post.reverse(); + post +} + +/// Recomputes every block's predecessors from the exits. +fn link(blocks: &mut [Block]) { + for block in blocks.iter_mut() { + block.preds.clear(); + } + for b in 0..blocks.len() { + for s in blocks[b].exit.successors() { + blocks[s].preds.push(b); + } + } +} + +/// An edge to an earlier block in reverse postorder whose target does not +/// dominate its source, if any: there the control flow is irreducible. +/// `index` is each block's position in `order`. +pub(crate) fn irreducible_edge( + blocks: &[Block], + order: &[usize], + index: &[usize], +) -> Option<(usize, usize)> { + let &entry = order.first()?; + let idom = idoms(blocks, order, index); + for &b in order { + for s in blocks[b].exit.successors() { + if index[s] > index[b] { + continue; + } + let mut d = b; + while d != s && d != entry { + d = idom[d]; + } + if d != s { + return Some((b, s)); + } + } + } + None +} + +/// Each block's immediate dominator (the entry's is itself, unreachable +/// blocks' `usize::MAX`); `order` is reverse postorder, `index` each +/// block's position in it. +pub(crate) fn idoms(blocks: &[Block], order: &[usize], index: &[usize]) -> Vec { + let mut idom = vec![usize::MAX; blocks.len()]; + let Some(&entry) = order.first() else { + return idom; + }; + idom[entry] = entry; + let intersect = |idom: &[usize], mut a: usize, mut b: usize| { + while a != b { + while index[a] > index[b] { + a = idom[a]; + } + while index[b] > index[a] { + b = idom[b]; + } + } + a + }; + let mut changed = true; + while changed { + changed = false; + for &b in &order[1..] { + let mut new = usize::MAX; + for &q in blocks[b].preds.iter().filter(|&&q| idom[q] != usize::MAX) { + new = if new == usize::MAX { + q + } else { + intersect(&idom, q, new) + }; + } + if idom[b] != new { + idom[b] = new; + changed = true; + } + } + } + idom +} + +/// Node splitting, before SSA. While a loop is entered at several blocks +/// (a compiler-rotated loop whose peeled first test jumps into its body), +/// the entry first in reverse postorder stays the header, and another +/// entry's outside predecessors move to a copy of everything that entry +/// reaches in the loop before the header. The copies run the same +/// instructions, so behaviour is unchanged. +fn split_irreducible(blocks: &mut Vec) -> Result<(), ShaderError> { + let limit = 4 * blocks.len() + 64; + loop { + let order = reverse_postorder(blocks); + let mut index = vec![usize::MAX; blocks.len()]; + for (i, &b) in order.iter().enumerate() { + index[b] = i; + } + let Some((from, _)) = irreducible_edge(blocks, &order, &index) else { + return Ok(()); + }; + let found = multi_entry_loop(blocks, &vec![true; blocks.len()]); + let Some((region, mut entries)) = found.filter(|_| blocks.len() < limit) else { + return Err(ShaderError::Unsupported { + offset: blocks[from].offset, + what: "irreducible control flow", + }); + }; + entries.sort_by_key(|&e| index[e]); + let (header, entry) = (entries[0], entries[1]); + + // What `entry` reaches in the loop before the header, and its copies. + let mut copy = vec![usize::MAX; blocks.len()]; + let mut copied = Vec::new(); + let mut stack = vec![entry]; + while let Some(b) = stack.pop() { + if copy[b] != usize::MAX { + continue; + } + copy[b] = blocks.len() + copied.len(); + copied.push(b); + for s in blocks[b].exit.successors() { + if region[s] && s != header { + stack.push(s); + } + } + } + let retarget = |exit: &mut Exit, to: &dyn Fn(usize) -> usize| match exit { + Exit::Jump(s) => *s = to(*s), + Exit::Branch { taken, not_taken } => { + *taken = to(*taken); + *not_taken = to(*not_taken); + } + Exit::End | Exit::Indirect => {} + }; + for &b in &copied { + let mut block = blocks[b].clone(); + retarget(&mut block.exit, &|s| { + if copy[s] == usize::MAX { s } else { copy[s] } + }); + blocks.push(block); + } + let outside: Vec = blocks[entry] + .preds + .iter() + .copied() + .filter(|&p| !region[p]) + .collect(); + for p in outside { + retarget(&mut blocks[p].exit, &|s| { + if s == entry { copy[entry] } else { s } + }); + } + link(blocks); + } +} + +/// A loop among the `inside` blocks entered at more than one block, with +/// its entries. Loops nested in a single-entry loop are searched with its +/// header removed, so one is found whenever the control flow is irreducible. +fn multi_entry_loop(blocks: &[Block], inside: &[bool]) -> Option<(Vec, Vec)> { + let reach = |from: usize, forward: bool| { + let mut seen = vec![false; blocks.len()]; + let mut stack = vec![from]; + while let Some(b) = stack.pop() { + let next = if forward { + blocks[b].exit.successors() + } else { + blocks[b].preds.clone() + }; + for n in next { + if inside[n] && !seen[n] { + seen[n] = true; + stack.push(n); + } + } + } + seen + }; + let mut done = vec![false; blocks.len()]; + for v in (0..blocks.len()).filter(|&v| inside[v]) { + if done[v] { + continue; + } + // Blocks on a cycle through `v`; `v` itself only if there is one. + let (ahead, behind) = (reach(v, true), reach(v, false)); + let region: Vec = ahead.iter().zip(&behind).map(|(a, b)| a & b).collect(); + if !region[v] { + continue; + } + let members = (0..blocks.len()).filter(|&b| region[b]); + for b in members.clone() { + done[b] = true; + } + let entries: Vec = members + .filter(|&b| blocks[b].preds.iter().any(|&p| !region[p])) + .collect(); + match entries[..] { + [] => {} + [header] => { + let mut nested = region; + nested[header] = false; + if let Some(found) = multi_entry_loop(blocks, &nested) { + return Some(found); + } + } + _ => return Some((region, entries)), + } + } + None +} + +/// Registers live into and out of each block. +fn liveness(blocks: &[Block], order: &[usize]) -> (Vec, Vec) { + let empty = [0; REGS.div_ceil(64)]; + let mut uses = vec![empty; blocks.len()]; + let mut defs = vec![empty; blocks.len()]; + for (b, block) in blocks.iter().enumerate() { + for inst in &block.insts { + for &(reg, _) in &inst.reads { + if !contains(&defs[b], reg) { + insert(&mut uses[b], reg); + } + } + for &(reg, _) in &inst.writes { + insert(&mut defs[b], reg); + } + } + } + let mut live_in = vec![empty; blocks.len()]; + let mut live_out = vec![empty; blocks.len()]; + let mut changed = true; + while changed { + changed = false; + for &b in order.iter().rev() { + let mut out = empty; + for s in blocks[b].exit.successors() { + for (o, i) in out.iter_mut().zip(&live_in[s]) { + *o |= i; + } + } + let mut inn = empty; + for w in 0..inn.len() { + inn[w] = uses[b][w] | out[w] & !defs[b][w]; + } + if inn != live_in[b] || out != live_out[b] { + (live_in[b], live_out[b]) = (inn, out); + changed = true; + } + } + } + (live_in, live_out) +} + +/// Phis are placed for every live register at every join; those whose +/// arguments are all one value (or the phi itself) are replaced by it. +fn remove_trivial_phis(blocks: &mut [Block], values: u32) { + let mut replaced: Vec = (0..values).map(Value).collect(); + let find = |replaced: &[Value], mut v: Value| { + while replaced[v.0 as usize] != v { + v = replaced[v.0 as usize]; + } + v + }; + let mut changed = true; + while changed { + changed = false; + for block in blocks.iter_mut() { + block.phis.retain(|phi| { + let mut only = None; + for &a in &phi.args { + let a = find(&replaced, a); + if a == phi.value || Some(a) == only { + continue; + } + if only.is_some() { + return true; + } + only = Some(a); + } + let Some(v) = only else { return true }; + replaced[phi.value.0 as usize] = v; + changed = true; + false + }); + } + } + for block in blocks { + for phi in &mut block.phis { + for a in &mut phi.args { + *a = find(&replaced, *a); + } + } + for inst in &mut block.insts { + for (_, v) in &mut inst.reads { + *v = find(&replaced, *v); + } + } + } +} + +/// Scheduling hints, performance counters and tracing: no effect on results. +const DROPPED: &[&str] = &[ + "s_nop", + "s_waitcnt", + "s_waitcnt_vscnt", + "s_waitcnt_vmcnt", + "s_waitcnt_expcnt", + "s_waitcnt_lgkmcnt", + "s_waitcnt_depctr", + "s_wait_idle", + "s_inst_prefetch", + "s_clause", + "s_setprio", + "s_sleep", + "s_ttracedata", + "s_ttracedata_imm", + "s_incperflevel", + "s_decperflevel", + "v_nop", + "v_pipeflush", + "v_clrexcp", +]; + +/// Registers read, registers written. +type Effects = (Vec, Vec); + +/// The registers `inst` of `p` reads as operands: its reads without the old +/// value of a VGPR it only writes. +pub(crate) fn operand_reads(p: &Program, inst: &Inst) -> Vec { + let lanes = 1 + u8::from(p.wave64); + effects(&inst.machine, &inst.fields, inst.name(), lanes, p.vgprs) + .ok() + .flatten() + .map_or_else(Vec::new, |e| e.0) +} + +/// Registers an instruction reads and writes, one per dword, or `None` if +/// the IR drops it. +fn effects( + inst: &Instruction, + fields: &Fields, + name: &'static str, + lanes: u8, + vgprs: u16, +) -> Result, ShaderError> { + if DROPPED.contains(&name) { + return Ok(None); + } + let unsupported = || ShaderError::Unsupported { + offset: inst.offset, + what: name, + }; + let mask = |code: u8| (0..lanes).map(move |i| Reg::S(code + i)); + let (mut r, mut w) = (Vec::new(), Vec::new()); + let regs = |op: &Operand, out: &mut Vec| { + add_regs(op, lanes, out).map_err(|_| ShaderError::Isa { + offset: inst.offset, + reason: "register range out of bounds", + }) + }; + let vector = !matches!( + fields, + Fields::Sop { .. } | Fields::Sopp { .. } | Fields::Smem { .. } + ); + match fields { + Fields::Sop { dst, src, .. } => { + if name.starts_with("s_movrel") + || name.starts_with("s_subvector_loop") + || matches!(name, "s_call_b64" | "s_rfe_b64") + { + return Err(unsupported()); + } + for s in src { + regs(s, &mut r)?; + } + if let Some(d) = dst { + regs(d, &mut w)?; + // These change (or may keep) the destination's old value. + if name.starts_with("s_bitset") + || name.starts_with("s_cmov") + || matches!(name, "s_addk_i32" | "s_mulk_i32") + { + regs(d, &mut r)?; + } + } + if matches!(name, "s_addc_u32" | "s_subb_u32" | "s_cmovk_i32") + || name.starts_with("s_cselect_") + || name.starts_with("s_cmov_") + { + r.push(Reg::Scc); + } + if name.contains("saveexec") || name.contains("wrexec") { + r.extend(mask(EXEC)); + w.extend(mask(EXEC)); + } + if writes_scc(inst.encoding, name) { + w.push(Reg::Scc); + } + } + Fields::Sopp { .. } => match name { + "s_cbranch_scc0" | "s_cbranch_scc1" => r.push(Reg::Scc), + "s_cbranch_vccz" | "s_cbranch_vccnz" => r.extend(mask(VCC)), + "s_cbranch_execz" | "s_cbranch_execnz" => r.extend(mask(EXEC)), + "s_sendmsg" | "s_sendmsghalt" => r.push(Reg::S(M0)), + "s_endpgm" + | "s_endpgm_saved" + | "s_endpgm_ordered_ps_done" + | "s_code_end" + | "s_branch" + | "s_barrier" + | "s_icache_inv" + | "s_wakeup" + | "s_round_mode" + | "s_denorm_mode" => {} + _ => return Err(unsupported()), + }, + Fields::Smem { + data, + base, + soffset, + .. + } => match name { + "s_memtime" | "s_memrealtime" | "s_get_waveid_in_workgroup" => { + regs(data.as_ref().ok_or_else(unsupported)?, &mut w)?; + } + "s_gl1_inv" | "s_dcache_inv" | "s_dcache_wb" => {} + _ if name.contains("_load_") || name.contains("_store_") => { + regs(base, &mut r)?; + regs(soffset, &mut r)?; + let data = data.as_ref().ok_or_else(unsupported)?; + regs( + data, + if name.contains("_load_") { + &mut w + } else { + &mut r + }, + )?; + } + _ => return Err(unsupported()), + }, + Fields::Valu(v) => { + let (src_indexed, dst_indexed) = match name { + "v_movrels_b32" => (true, false), + "v_movreld_b32" => (false, true), + "v_movrelsd_b32" | "v_movrelsd_2_b32" | "v_swaprel_b32" => (true, true), + _ => (false, false), + }; + // v[reg + M0] for any M0 that stays inside the program's VGPRs. + let indexed = |op: &Operand, out: &mut Vec| match *op { + Operand::Vector { reg, .. } if u16::from(reg) < vgprs => { + out.extend((u16::from(reg)..vgprs).map(|r| Reg::V(r as u8))); + Ok(()) + } + _ => Err(ShaderError::Isa { + offset: inst.offset, + reason: "relative VGPR base outside the program's VGPRs", + }), + }; + for (i, s) in v.src.iter().enumerate() { + if i == 0 && src_indexed { + indexed(s, &mut r)?; + } else { + regs(s, &mut r)?; + } + } + // GFX10 compares into EXEC write nothing else. + if name.starts_with("v_cmpx") { + w.extend(mask(EXEC)); + } else if let Some(d) = &v.dst { + if dst_indexed { + indexed(d, &mut w)?; + } else { + regs(d, &mut w)?; + } + } + if let Some(c) = &v.carry { + regs(c, &mut w)?; + } + match name { + "v_swap_b32" => { + regs(&v.src[0], &mut w)?; + if let Some(d) = &v.dst { + regs(d, &mut r)?; + } + } + "v_swaprel_b32" => { + indexed(&v.src[0], &mut w)?; + if let Some(d) = &v.dst { + indexed(d, &mut r)?; + } + } + "v_div_fmas_f32" | "v_div_fmas_f64" => r.extend(mask(VCC)), + _ => {} + } + if name.starts_with("v_interp_") || src_indexed || dst_indexed { + r.push(Reg::S(M0)); + } + } + Fields::Vintrp { dst, src, .. } => { + regs(src, &mut r)?; + r.push(Reg::S(M0)); + regs(dst, &mut w)?; + } + Fields::Ds { + dst, + addr, + data, + gds, + .. + } => { + for o in addr.iter().chain(data) { + regs(o, &mut r)?; + } + if let Some(d) = dst { + regs(d, &mut w)?; + } + if *gds + || name.starts_with("ds_gws") + || name.contains("addtid") + || matches!(name, "ds_ordered_count" | "ds_append" | "ds_consume") + { + r.push(Reg::S(M0)); + } + } + Fields::Buffer { + data, + addr, + rsrc, + soffset, + offen, + idxen, + lds, + cache, + .. + } => { + if *offen || *idxen { + regs(addr, &mut r)?; + } + regs(rsrc, &mut r)?; + regs(soffset, &mut r)?; + if *lds { + r.push(Reg::S(M0)); + } + if let Some(d) = data { + if name.contains("_load_") { + if !lds { + regs(d, &mut w)?; + } + } else if name.contains("_store_") { + regs(d, &mut r)?; + } else if name.contains("_atomic_") { + regs(d, &mut r)?; + if cache.glc { + regs(&atomic_result(d, name), &mut w)?; + } + } else { + return Err(unsupported()); + } + } + } + Fields::Image { + data, + addr, + rsrc, + sampler, + cache, + .. + } => { + for a in addr.iter().chain([rsrc]).chain(sampler) { + regs(a, &mut r)?; + } + if name.contains("_store") { + regs(data, &mut r)?; + } else if name.contains("_atomic_") { + regs(data, &mut r)?; + if cache.glc { + regs(&atomic_result(data, name), &mut w)?; + } + } else { + regs(data, &mut w)?; + } + } + Fields::Flat { + dst, + addr, + data, + saddr, + .. + } => { + for o in [addr, data, saddr].into_iter().flatten() { + regs(o, &mut r)?; + } + if let Some(d) = dst { + regs(d, &mut w)?; + } + } + Fields::Exp { src, .. } => { + for s in src.iter().flatten() { + regs(s, &mut r)?; + } + } + } + if vector { + r.extend(mask(EXEC)); + } + let mut seen = Vec::with_capacity(r.len()); + r.retain(|reg| { + let new = !seen.contains(reg); + seen.push(*reg); + new + }); + Ok(Some((r, w))) +} + +/// Scalar ALU opcodes that set SCC (carry, overflow, comparison, or "result +/// is not zero"). +fn writes_scc(encoding: gfx10::Encoding, name: &str) -> bool { + use gfx10::Encoding::*; + match encoding { + Sopc => true, + Sopk => name.starts_with("s_cmpk_") || name == "s_addk_i32", + _ => { + let stem = name.split('_').nth(1).unwrap_or(""); + name.contains("saveexec") + || name.contains("wrexec") + || matches!( + stem, + "add" + | "sub" + | "addc" + | "subb" + | "min" + | "max" + | "and" + | "or" + | "xor" + | "andn2" + | "orn2" + | "nand" + | "nor" + | "xnor" + | "lshl" + | "lshr" + | "ashr" + | "bfe" + | "absdiff" + | "lshl1" + | "lshl2" + | "lshl3" + | "lshl4" + | "not" + | "wqm" + | "bcnt0" + | "bcnt1" + | "quadmask" + | "abs" + ) + } + } +} + +/// What an atomic with `glc` returns: the old value (for compare-and-swap, +/// half the data operand). +fn atomic_result(data: &Operand, name: &str) -> Operand { + match *data { + Operand::Vector { reg, dwords } if name.contains("cmpswap") => Operand::Vector { + reg, + dwords: dwords / 2, + }, + op => op, + } +} + +/// Appends the register dwords an operand names; reading `vccz`, `execz`, +/// `scc` or `lds_direct` reads the register behind it. +fn add_regs(op: &Operand, lanes: u8, out: &mut Vec) -> Result<(), ()> { + match *op { + Operand::Scalar { code, .. } if code == gfx10::NULL => {} + Operand::Scalar { code, dwords } => { + let end = u16::from(code) + u16::from(dwords); + // A machine operand ends within the machine's codes, a parked + // scalar (`unspill`) within those past them. + let limit = if code < PARKED { 128 } else { 256 }; + if end > limit { + return Err(()); + } + out.extend((u16::from(code)..end).map(|c| Reg::S(c as u8))); + } + Operand::Vector { reg, dwords } => { + if u16::from(reg) + u16::from(dwords) > 256 { + return Err(()); + } + out.extend((0..dwords).map(|i| Reg::V(reg + i))); + } + Operand::Const(251) => out.extend((0..lanes).map(|i| Reg::S(VCC + i))), + Operand::Const(252) => out.extend((0..lanes).map(|i| Reg::S(EXEC + i))), + Operand::Const(253) => out.push(Reg::Scc), + Operand::Const(254) => out.push(Reg::S(M0)), + Operand::Const(_) | Operand::Literal(_) | Operand::Attr { .. } => {} + } + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + + const S_ENDPGM: u32 = 0xBF81_0000; + + fn build_words(words: &[u32], wave64: bool) -> Program { + let code: Vec = words.iter().flat_map(|w| w.to_le_bytes()).collect(); + build(&code, wave64, 256).unwrap() + } + + fn input(p: &Program, reg: Reg) -> Value { + p.inputs.iter().find(|i| i.0 == reg).expect("input").1 + } + + /// `if (v0 < s0) { ... }` whose body changes s6: `body` are its words, `after` what + /// follows the join. + fn skip(body: &[u32], after: &[u32]) -> Program { + let mut w = vec![ + 0xBE94_0306, // s_mov_b32 s20, s6 + 0x7D88_0000, // v_cmp_gt_u32 vcc, s0, v0 + 0xBE8C_246A, // s_and_saveexec_b64 s[12:13], vcc + 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(after); + w.push(S_ENDPGM); + build_words(&w, true) + } + + fn skips(p: &Program) -> usize { + p.blocks + .iter() + .filter(|b| b.insts.last().is_some_and(|i| i.name() == "s_cbranch_execz")) + .count() + } + + #[test] + fn a_skip_is_left_out_when_the_scalars_it_changes_come_back_or_are_not_read() { + const SET: u32 = 0xBE86_0385; // s_mov_b32 s6, 5 + const USE: u32 = 0x7E02_0206; // v_mov_b32 v1, s6 + const BACK: u32 = 0xBE86_0314; // s_mov_b32 s6, s20 + const READ: u32 = 0x7E04_0206; // v_mov_b32 v2, s6 + // s6 is changed in the body and read after the join: the branch stays + let kept = skip(&[SET, USE], &[READ]); + assert_eq!(skips(&kept), 1); + assert!(without_skips(&kept, false).is_none()); + assert!(without_skips(&kept, true).is_none()); + // ... put back by a copy of what it held (as a scalar parked in a VGPR lane comes + // back): every lane may walk the body + let back = skip(&[SET, USE, BACK], &[READ]); + assert!(without_skips(&back, false).is_none()); + assert_eq!(skips(&without_skips(&back, true).expect("left out")), 0); + // ... or not read after the join at all + let unread = skip(&[SET, USE], &[]); + assert_eq!(skips(&without_skips(&unread, false).expect("left out")), 0); + assert_eq!(skips(&without_skips(&unread, true).expect("left out")), 0); + // ... or read only by a restore of EXEC that nothing uses before the next one + // (s_mov_b64 exec, s[6:7]; s_mov_b64 exec, s[12:13]; v_mov_b32 v2, s0) + let idle = skip(&[SET, USE], &[0xBEFE_0406, 0xBEFE_040C, 0x7E04_0200]); + assert!(without_skips(&idle, false).is_none()); + assert_eq!(skips(&without_skips(&idle, true).expect("left out")), 0); + } + + #[test] + fn joins_get_phis_only_where_values_differ() { + let code = [ + 0xBF06_0100, // s_cmp_eq_u32 s0, s1 + 0xBF85_0001, // s_cbranch_scc1 -> 12 + 0xBE82_0380, // s_mov_b32 s2, 0 + 0x7E00_0202, // 12: v_mov_b32 v0, s2 + 0x7E02_0200, // v_mov_b32 v1, s0 + S_ENDPGM, + ]; + for wave64 in [false, true] { + let p = build_words(&code, wave64); + let [b0, b1, b2] = &p.blocks[..] else { + panic!("{:?}", p.blocks) + }; + assert_eq!( + b0.exit, + Exit::Branch { + taken: 2, + not_taken: 1 + } + ); + assert_eq!(b1.exit, Exit::Jump(2)); + assert_eq!(b2.preds, [0, 1]); + assert_eq!(b0.insts[1].read(Reg::Scc), b0.insts[0].write(Reg::Scc)); + + // s2 differs per path; s0, EXEC, v0 and v1 do not. + let [phi] = &b2.phis[..] else { + panic!("{:?}", b2.phis) + }; + assert_eq!(phi.reg, Reg::S(2)); + assert_eq!( + phi.args, + [input(&p, Reg::S(2)), b1.insts[0].write(Reg::S(2)).unwrap()] + ); + let [mov0, mov1, end] = &b2.insts[..] else { + panic!() + }; + assert_eq!(mov0.read(Reg::S(2)), Some(phi.value)); + assert_eq!(mov1.read(Reg::S(0)), Some(input(&p, Reg::S(0)))); + // The old v1 is read: lanes outside EXEC keep it. + assert_eq!(mov1.read(Reg::V(1)), Some(input(&p, Reg::V(1)))); + assert_eq!(mov1.read(Reg::S(EXEC)), Some(input(&p, Reg::S(EXEC)))); + assert_eq!(mov1.read(Reg::S(EXEC + 1)).is_some(), wave64); + assert_eq!((end.name(), b2.exit), ("s_endpgm", Exit::End)); + } + } + + #[test] + fn in_place_scalar_ops_read_their_destination() { + let p = build_words( + &[ + 0xBE8D_1D94, // s_bitset1_b32 s13, 20 + 0xB78E_0010, // s_addk_i32 s14, 0x10 + 0xBE8F_0380, // s_mov_b32 s15, 0 + S_ENDPGM, + ], + false, + ); + let [bitset, addk, mov, _] = &p.blocks[0].insts[..] else { + panic!("{:?}", p.blocks[0].insts) + }; + assert_eq!(bitset.read(Reg::S(13)), Some(input(&p, Reg::S(13)))); + assert_eq!(addk.read(Reg::S(14)), Some(input(&p, Reg::S(14)))); + assert_eq!(mov.read(Reg::S(15)), None); + } + + #[test] + fn loops_carry_values_through_phis() { + let p = build_words( + &[ + 0xBE80_0380, // s_mov_b32 s0, 0 + 0x8000_8100, // 4: s_add_u32 s0, s0, 1 + 0xBF07_8400, // s_cmp_lg_u32 s0, 4 + 0xBF85_FFFD, // s_cbranch_scc1 -> 4 + S_ENDPGM, + ], + true, + ); + assert!(p.inputs.is_empty(), "{:?}", p.inputs); + let [b0, b1, b2] = &p.blocks[..] else { + panic!() + }; + assert_eq!(b1.preds, [0, 1]); + assert_eq!( + b1.exit, + Exit::Branch { + taken: 1, + not_taken: 2 + } + ); + let [phi] = &b1.phis[..] else { + panic!("{:?}", b1.phis) + }; + let add = &b1.insts[0]; + assert_eq!(phi.reg, Reg::S(0)); + assert_eq!( + phi.args, + [ + b0.insts[0].write(Reg::S(0)).unwrap(), + add.write(Reg::S(0)).unwrap() + ] + ); + assert_eq!(add.read(Reg::S(0)), Some(phi.value)); + assert_eq!(b1.insts[1].read(Reg::S(0)), add.write(Reg::S(0))); + assert_eq!(b2.insts[0].name(), "s_endpgm"); + } + + #[test] + fn drops_scheduling_and_follows_far_jumps() { + let p = build_words( + &[ + 0xBF80_0000, // s_nop 0 + 0xBE88_1F00, // s_getpc_b64 s[8:9] + 0x8008_FF08, + 20, // s_add_u32 s8, s8, 20 -> 8 + 20 = 28 + 0x8209_8009, // s_addc_u32 s9, s9, 0 + 0xBE80_2008, // s_setpc_b64 s[8:9] + 0xFFFF_FFFF, // not code + S_ENDPGM, + ], + false, + ); + let names: Vec<_> = p.blocks[0].insts.iter().map(Inst::name).collect(); + assert_eq!( + names, + ["s_getpc_b64", "s_add_u32", "s_addc_u32", "s_setpc_b64"] + ); + assert_eq!(p.blocks[0].exit, Exit::Jump(1)); + assert_eq!(p.blocks[1].offset, 28); + // s_addc_u32 reads the carry s_add_u32 left in SCC. + let i = &p.blocks[0].insts; + assert_eq!(i[2].read(Reg::Scc), i[1].write(Reg::Scc)); + } + + #[test] + fn reports_what_it_cannot_express() { + let code: Vec = [0xBE80_2E01_u32, S_ENDPGM] // s_movrels_b32 s0, s1 + .iter() + .flat_map(|w| w.to_le_bytes()) + .collect(); + assert_eq!( + build(&code, false, 256), + Err(ShaderError::Unsupported { + offset: 0, + what: "s_movrels_b32" + }) + ); + } + + #[test] + fn relative_vgpr_access_spans_up_to_the_vgpr_count() { + let code: Vec = [ + 0x7E04_8501_u32, // v_movreld_b32 v2, v1: v[2 + m0] = v1 + 0x7E00_8704, // v_movrels_b32 v0, v4: v0 = v[4 + m0] + S_ENDPGM, + ] + .iter() + .flat_map(|w| w.to_le_bytes()) + .collect(); + let p = build(&code, false, 6).unwrap(); + let [movreld, movrels, _] = &p.blocks[0].insts[..] else { + panic!() + }; + let vgprs = |regs: &[(Reg, Value)]| -> Vec { + regs.iter() + .filter_map(|r| match r.0 { + Reg::V(v) => Some(v), + _ => None, + }) + .collect() + }; + assert_eq!(vgprs(&movreld.writes), [2, 3, 4, 5]); + // v1 is the source; v2-v5 are read for the lanes and indices not written. + assert_eq!(vgprs(&movreld.reads), [1, 2, 3, 4, 5]); + assert!(movreld.read(Reg::S(M0)).is_some()); + assert_eq!(vgprs(&movrels.writes), [0]); + assert_eq!(vgprs(&movrels.reads), [4, 5, 0]); + assert_eq!(movrels.read(Reg::V(4)), movreld.write(Reg::V(4))); + assert!(build(&code, false, 4).is_err(), "v4 is past 4 VGPRs"); + } +} diff --git a/crates/leonida-shader/src/lib.rs b/crates/leonida-shader/src/lib.rs new file mode 100644 index 000000000..30b195262 --- /dev/null +++ b/crates/leonida-shader/src/lib.rs @@ -0,0 +1,38 @@ +//! 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. + +pub mod bvh; +pub mod dxbc; +pub mod dxil; +pub mod emit; +pub mod gfx10; +pub mod io; +pub mod ir; +pub mod native; +pub mod resource; +pub mod spill; +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 }, +} diff --git a/crates/leonida-shader/src/native.rs b/crates/leonida-shader/src/native.rs new file mode 100644 index 000000000..4c267e17c --- /dev/null +++ b/crates/leonida-shader/src/native.rs @@ -0,0 +1,1103 @@ +//! Native GFX10 programs that the console compiler stores in a `DXIL` part. +//! +//! An `XDAT` index after the program header lists blobs stored around the +//! bitcode; one or more of them hold native programs, zlib-packed (a vertex +//! shader can carry two: compiled for use with and without a geometry +//! shader). Layout as observed in shipped titles (index offsets are relative +//! to the part data): +//! +//! ```text +//! +0x18 "XDAT" u32 entry count, u32 (0x24 seen), then per entry: +//! u32 kind, u32 offset, u32 size +//! kind 0x0d "XBCH" u32 version (3), u64 packed size, u64 unpacked size, +//! zlib stream +//! unpacked "FSSM" u32 version (0x101), u64 payload size, payload +//! payload +0x00 u64 graphics slot count (6) +//! +0x08 u64 record offsets: LS HS ES GS VS PS (0x08..0x30), +//! mesh 0x48, compute 0x60; unused ones are 0xDEADBEEF_DEADBEEF +//! record +0x00 u64 code offset, +0x08 u64 code size (payload-relative), +//! +0x14 u32 flags: bit 5 wave32 (else wave64) +//! +0x28 u64 root layout table, +0x30 u64 used-resource table +//! (payload-relative), +0x38 u32 and +0x3c u32 their counts +//! +0x50 u32 bits 0-9 VGPRs used, bits 20-27 SGPRs used +//! layout 20 B: u32 root type, u32 table offset (dwords), u32 user SGPRs, +//! u32 base register, u8 first user-data dword, u8 root slot, +//! u16 0 +//! used 20 B: u8 resource type, u8 root type, u16 0, u32 table offset +//! (dwords), u32 lower bound, u32 stride, u8 descriptor +//! dwords, u8 first user-data dword, u8 root slot, u8 0 +//! ``` +//! +//! Stage data follows the record; offsets from its end (E = record + 0x54): +//! +//! ```text +//! PS E+0x24 32 inputs of 8 B: u8 usage, u8 signature row, u8 channel +//! mask, u8 attribute (v_interp `attr`), u8 default, u8 second +//! row (of a packed pair), u8 parameter slot, u8 flags (bit 0 +//! flat, 1 linear, 3 fp16, 4 fp16 packed); E+0x124 u32 count +//! E+0x134 u32 SPI_PS_INPUT_ADDR, E+0x138 u32 DB_SHADER_CONTROL +//! E+0x148 u32 export patch size (dwords), E+0x14c 8 patches, one per +//! MRT: u32 code offset (dwords, -1 none), then the export code +//! for each color format in 10 slots of 10 dwords (ZERO, 32_R, +//! 32_GR, 32_AR, FP16, UNORM16, SNORM16, UINT16, SINT16, 32_ABGR) +//! VS E+0x24 32 inputs of 5 B: u8 usage, u8 row, u8 channel mask, u8 VGPR +//! of channel 0 (channel k in VGPR + k), u8 highest channel; +//! E+0xc4 u32 count +//! E+0xc8 32 outputs of 6 B: u8 usage, u8 row, u8 parameter (`exp +//! param`), u8 row again, u8 slot, u8 flags (bit 0 fp16, +//! bit 1 two fp16 values per dword); E+0x188 u32 count +//! CS E+0x24 u32 COMPUTE_PGM_RSRC2, E+0x28 u32 x3 thread-group size +//! MS E+0xc8 outputs as VS, E+0x188 count; the param byte's bit 7 marks a +//! per-primitive output (`PSG1` row); the 3 bytes more are the +//! second row of a packed pair, a slot, flags (bit 0 fp16, bit 1 +//! two fp16 elements packed) +//! E+0x18c u32 SPI_VS_OUT_CONFIG, SPI_SHADER_POS_FORMAT, +//! PA_CL_VS_OUT_CNTL, VGT_STRMOUT_CONFIG, SPI_SHADER_PGM_RSRC2_GS, +//! VGT_GS_OUT_PRIM_TYPE, VGT_GS_INSTANCE_CNT, SPI_SHADER_IDX_FORMAT +//! E+0x448 u16 thread-group size in lanes, u16 maximum vertices, +//! u16 maximum primitives, u8 user SGPRs, u8 output topology +//! (2 triangles); code follows at E+0x45c +//! record +0x4c u32 LDS bytes (`lds_byte_size`; mesh programs read it here) +//! ``` +//! +//! Rows are registers of the container's signature parts (`ISG1`, `OSG1`). +//! Merged stages keep their stage data in another layout (not read). +//! +//! Other kinds seen: 0x07 program header + bitcode (or a stub when stripped), +//! 0x0a `xbop` (compiler options), 0x0e a table not decoded yet, 0x10 and +//! 0x12 16-byte blobs (0x10 is the shader hash). +//! Unknown versions are rejected so a format change shows up as an error. + +use crate::ShaderError::{self, Malformed}; +use crate::dxbc::{u32_at, u64_at}; + +const XDAT_OFFSET: usize = 0x18; +const MAX_XDAT_ENTRIES: usize = 64; +const KIND_NATIVE: u32 = 0x0d; +const XBCH_VERSION: u32 = 3; +const XBCH_HEADER: usize = 0x18; +const FSSM_VERSION: u32 = 0x101; +const FSSM_HEADER: usize = 0x10; +const GRAPHICS_SLOT_COUNT: u64 = 6; +/// Where each stage's record offset sits in the FSSM payload. +const SLOTS: [(HwStage, usize); 8] = [ + (HwStage::Ls, 0x08), + (HwStage::Hs, 0x10), + (HwStage::Es, 0x18), + (HwStage::Gs, 0x20), + (HwStage::Vs, 0x28), + (HwStage::Ps, 0x30), + (HwStage::Ms, 0x48), + (HwStage::Cs, 0x60), +]; +const ABSENT: u64 = 0xDEAD_BEEF_DEAD_BEEF; +const RECORD_SIZE: u64 = 0x54; +const RECORD_FLAGS: usize = 0x14; +const FLAG_WAVE32: u32 = 1 << 5; +const RECORD_REGS: usize = 0x50; +const RECORD_LAYOUT: usize = 0x28; +const RECORD_USED: usize = 0x30; +const RECORD_COUNTS: usize = 0x38; +const ENTRY_SIZE: u64 = 20; +const MAX_SEMANTICS: u32 = 32; +const PS_INPUTS: usize = 0x24; +const PS_INPUT_COUNT: usize = 0x124; +const PS_INPUT_ADDR: usize = 0x134; +const PS_DB_SHADER_CONTROL: usize = 0x138; +const PS_PATCH_SIZE: usize = 0x148; +const PS_PATCHES: usize = 0x14c; +const PATCH_SLOT_DWORDS: usize = 10; +/// The variant that exports every channel as a raw 32-bit value. +const PATCH_FULL: usize = 9; +const PATCH_BYTES: usize = 4 + 10 * PATCH_SLOT_DWORDS * 4; +const MRTS: usize = 8; +const VS_INPUTS: usize = 0x24; +const VS_INPUT_COUNT: usize = 0xc4; +const VS_OUTPUTS: usize = 0xc8; +const VS_OUTPUT_COUNT: usize = 0x188; +const CS_RSRC2: usize = 0x24; +const CS_THREADS: usize = 0x28; +const RECORD_LDS: usize = 0x4c; +const MS_CLIP_CNTL: usize = 0x194; +const MS_INFO: usize = 0x448; +/// Unpacked blobs are a few KiB; refuse to allocate for absurd sizes. +const MAX_UNPACKED: u64 = 16 << 20; + +/// Hardware shader stage a native program runs as. +#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] +pub enum HwStage { + Ls, + Hs, + Es, + Gs, + Vs, + Ps, + /// Mesh shader. + Ms, + Cs, +} + +impl HwStage { + /// The SGPR holding user-data dword `index`: merged stages (and mesh + /// shaders, which run as one) have 8 system SGPRs first. + pub fn user_sgpr(self, index: u8) -> u8 { + match self { + HwStage::Ls | HwStage::Hs | HwStage::Es | HwStage::Gs | HwStage::Ms => index + 8, + HwStage::Vs | HwStage::Ps | HwStage::Cs => index, + } + } +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct NativeProgram { + pub stage: HwStage, + /// Runs as 64 lanes per wave (else 32); sizes lane masks. + pub wave64: bool, + /// VGPRs the program uses (v0 up to this), the bound of indexed access. + pub vgprs: u16, + /// Where the root signature's parameters arrive (user SGPRs). + pub layout: Vec, + /// The descriptors the program reads, by root parameter. + pub used: Vec, + pub io: StageIo, + /// GFX10 machine code, as stored. + pub code: Vec, +} + +impl NativeProgram { + /// The code with each render target's export patched for its full + /// 32-bit format, so exports carry the shader's values unconverted (as + /// the console does at pipeline creation for that format). + pub fn patched_code(&self) -> Vec { + let mut code = self.code.clone(); + if let StageIo::Ps { patches, .. } = &self.io { + for p in patches { + let at = p.offset as usize * 4; + for (i, word) in p.code.iter().enumerate() { + code[at + 4 * i..at + 4 * i + 4].copy_from_slice(&word.to_le_bytes()); + } + } + } + code + } +} + +/// What a semantic is, as the stage data names it. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub enum Usage { + Generic, + ClipDistance, + Other(u8), +} + +impl Usage { + fn from_raw(raw: u8) -> Self { + match raw { + 6 => Usage::Generic, + 7 => Usage::ClipDistance, + n => Usage::Other(n), + } + } +} + +/// A pixel shader input: what `v_interp` of attribute `attr` reads. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct PsInput { + pub usage: Usage, + /// Register in the input signature. + pub row: u8, + pub mask: u8, + pub attr: u8, + pub flat: bool, + pub fp16: bool, + /// Two 16-bit values per dword ([`VsOutput::pack2`]); `row2` is the + /// second element's register. + pub pack2: bool, + pub row2: u8, +} + +/// A vertex attribute the fetch shader loads: channel k into VGPR `vgpr + k`. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct VsInput { + pub usage: Usage, + pub row: u8, + pub mask: u8, + pub vgpr: u8, +} + +/// What `exp param` of a vertex shader writes. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct VsOutput { + pub usage: Usage, + /// Register in the output signature. + pub row: u8, + pub param: u8, + /// 16-bit values, one per dword (low half) unless `pack2`: then two per + /// dword, channel c of this row in dword c / 2 (odd channels in the + /// high half), then a second 16-bit row from the next whole dword (the + /// next 16-bit row of the signature no entry names). + pub fp16: bool, + pub pack2: bool, +} + +/// The export code of one render target for its full 32-bit format. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct ExportPatch { + pub mrt: u8, + /// Where it goes in the code, in dwords. + pub offset: u32, + pub code: Vec, +} + +/// Inputs and outputs, for the stages whose stage data is read. +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub enum StageIo { + #[default] + None, + Vs { + inputs: Vec, + outputs: Vec, + }, + Ps { + inputs: Vec, + /// `SPI_PS_INPUT_ADDR`: which system values arrive in VGPRs. + input_addr: u32, + /// `DB_SHADER_CONTROL`: depth export, kill. + db_shader_control: u32, + patches: Vec, + }, + Cs(ComputeIo), + Ms(MeshIo), +} + +/// A mesh program's outputs and limits. It runs as one hardware NGG stage: +/// lane n of the group (`threads` lanes) exports vertex n (`exp pos`, +/// `exp param`) and primitive n (`exp prim`). +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct MeshIo { + /// `exp param` targets; `param` bit 7 set: a per-primitive output, + /// `row` then a row of the primitive signature (`PSG1`). + pub outputs: Vec, + /// `PA_CL_VS_OUT_CNTL`: which clip and cull distances `pos1+` carry. + pub clip_cntl: u32, + /// Thread-group size in lanes (the HLSL group rounded up to waves). + pub threads: u32, + pub max_vertices: u32, + pub max_primitives: u32, + /// 1 lines, 2 triangles. + pub topology: u8, + pub lds_bytes: u32, +} + +/// A compute program's dispatch settings. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct ComputeIo { + /// `COMPUTE_PGM_RSRC2`: user SGPRs, which system SGPRs and VGPRs + /// follow them, LDS size. + pub rsrc2: u32, + /// Thread-group size (`numthreads`). + pub threads: [u32; 3], +} + +impl ComputeIo { + /// User SGPRs before the system ones. + pub fn user_sgprs(&self) -> u8 { + (self.rsrc2 >> 1 & 0x1F) as u8 + } + + /// The SGPR of each enabled thread-group id component, in order after + /// the user SGPRs, then the thread-group info SGPR if enabled. + pub fn system_sgprs(&self) -> ([Option; 3], Option) { + let mut next = self.user_sgprs(); + let mut take = |bit: u32| { + (self.rsrc2 >> bit & 1 != 0).then(|| { + next += 1; + next - 1 + }) + }; + let ids = [take(7), take(8), take(9)]; + (ids, take(10)) + } + + /// SGPRs the hardware initializes: the user SGPRs, the enabled system + /// ones, then the scratch wave offset when scratch is enabled (bit 0). + /// The ones above hold whatever the previous wave left. + pub fn initialized_sgprs(&self) -> u8 { + let (ids, info) = self.system_sgprs(); + let end = ids.into_iter().chain([info]).flatten().map(|s| s + 1).max(); + end.unwrap_or(0).max(self.user_sgprs()) + (self.rsrc2 & 1) as u8 + } + + /// Thread id components in v0, v1, v2 (1 to 3). + pub fn thread_id_vgprs(&self) -> u8 { + (self.rsrc2 >> 11 & 3) as u8 + 1 + } + + /// LDS bytes per thread group (512-byte granules). + pub fn lds_bytes(&self) -> u32 { + (self.rsrc2 >> 15 & 0x1FF) * 512 + } +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub enum RootType { + Constants, + /// A 64-bit buffer address. + Descriptor, + /// The 32-bit heap address of a descriptor table range. + Table, + /// A sampler the root signature fixes. + ImmediateSampler, + /// The 32-bit address of the CBV/SRV/UAV heap (SM 6.6 dynamic resources). + ResourceHeap, + /// The 32-bit address of the sampler heap. + SamplerHeap, + Other(u32), +} + +impl RootType { + fn from_raw(raw: u32) -> Self { + match raw { + 0 => RootType::Constants, + 1 => RootType::Descriptor, + 3 => RootType::Table, + 4 => RootType::ImmediateSampler, + 5 => RootType::ResourceHeap, + 6 => RootType::SamplerHeap, + n => RootType::Other(n), + } + } +} + +/// One root parameter (or table range) and the user SGPRs holding it. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct RootParam { + pub root: RootType, + /// Of the range within its table. + pub table_offset_dwords: u32, + /// User SGPRs from `user_data` on. + pub sgprs: u32, + /// Shader register of the first descriptor (`b`/`t`/`u`/`s` number). + pub base_register: u32, + /// First user-data dword ([`HwStage::user_sgpr`]). + pub user_data: u8, + /// Index of the parameter in the root signature. + pub slot: u8, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub enum ResourceType { + Srv, + Sampler, + Cbv, + Uav, + Other(u8), +} + +/// A descriptor range the program reads. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct UsedResource { + pub kind: ResourceType, + pub root: RootType, + pub table_offset_dwords: u32, + /// Shader register of the first descriptor read. + pub lower_bound: u32, + pub stride: u32, + /// Size of the descriptor (4 or 8). + pub dwords: u8, + pub user_data: u8, + pub slot: u8, +} + +/// The native programs in a `DXIL` part's data; empty for the PC layout. +pub fn native_programs(part: &[u8]) -> Result, ShaderError> { + if part.get(XDAT_OFFSET..XDAT_OFFSET + 4) != Some(b"XDAT") { + return Ok(Vec::new()); + } + let count = u32_at(part, XDAT_OFFSET + 4)? as usize; + if count > MAX_XDAT_ENTRIES { + return Err(Malformed("implausible XDAT entry count")); + } + let mut out = Vec::new(); + for i in 0..count { + let at = XDAT_OFFSET + 12 + 12 * i; + if u32_at(part, at)? != KIND_NATIVE { + continue; + } + let offset = u32_at(part, at + 4)?.into(); + let size = u32_at(part, at + 8)?.into(); + let blob = bytes(part, offset, size).ok_or(Malformed("XDAT entry out of bounds"))?; + out.extend(programs(&unpack(blob)?)?); + } + Ok(out) +} + +fn unpack(blob: &[u8]) -> Result, ShaderError> { + if blob.get(0..4) != Some(b"XBCH") { + return Err(Malformed("native blob lacks XBCH magic")); + } + if u32_at(blob, 4)? != XBCH_VERSION { + return Err(Malformed("unknown XBCH version")); + } + let packed = u64_at(blob, 8)?; + let unpacked = u64_at(blob, 16)?; + if unpacked > MAX_UNPACKED { + return Err(Malformed("implausible XBCH unpacked size")); + } + let stream = + bytes(blob, XBCH_HEADER as u64, packed).ok_or(Malformed("XBCH stream out of bounds"))?; + let out = inflate_zlib_exact(stream, unpacked as usize) + .ok_or(Malformed("XBCH stream does not inflate to its stated size"))?; + Ok(out) +} + +/// Inflates a zlib stream incrementally up to `expected` bytes, rejecting +/// truncated, corrupt, under-filled, or oversized streams without eagerly +/// allocating the full declared size up front. +fn inflate_zlib_exact(source: &[u8], expected: usize) -> Option> { + let mut state = zlib_rs::Inflate::new(true, 15); + let mut out = Vec::new(); + let (mut in_pos, mut out_pos) = (0usize, 0usize); + loop { + if out_pos == expected { + let mut extra = [0u8; 1]; + let status = state + .decompress( + &source[in_pos..], + &mut extra, + zlib_rs::InflateFlush::NoFlush, + ) + .ok()?; + return (status == zlib_rs::Status::StreamEnd + && state.total_out() as usize == expected) + .then_some(out); + } + if out_pos == out.len() { + let next_len = if out.is_empty() { + expected.min(source.len().saturating_mul(4).max(4096)) + } else { + out.len().saturating_mul(2).min(expected) + }; + out.resize(next_len, 0); + } + let status = state + .decompress( + &source[in_pos..], + &mut out[out_pos..], + zlib_rs::InflateFlush::NoFlush, + ) + .ok()?; + let next_in = state.total_in() as usize; + let next_out = state.total_out() as usize; + match status { + zlib_rs::Status::StreamEnd => { + out.truncate(next_out); + return (next_out == expected).then_some(out); + } + zlib_rs::Status::Ok if next_in != in_pos || next_out != out_pos => { + in_pos = next_in; + out_pos = next_out; + } + zlib_rs::Status::Ok | zlib_rs::Status::BufError => return None, + } + } +} + +fn programs(fssm: &[u8]) -> Result, ShaderError> { + if fssm.get(0..4) != Some(b"FSSM") { + return Err(Malformed("native blob lacks FSSM magic")); + } + if u32_at(fssm, 4)? != FSSM_VERSION { + return Err(Malformed("unknown FSSM version")); + } + let payload = &fssm[FSSM_HEADER.min(fssm.len())..]; + if u64_at(fssm, 8)? != payload.len() as u64 { + return Err(Malformed("FSSM payload size disagrees")); + } + if u64_at(payload, 0)? != GRAPHICS_SLOT_COUNT { + return Err(Malformed("unexpected FSSM slot count")); + } + let mut out = Vec::new(); + for (stage, at) in SLOTS { + let start = u64_at(payload, at)?; + if start == ABSENT { + continue; + } + let record = + bytes(payload, start, RECORD_SIZE).ok_or(Malformed("FSSM record out of bounds"))?; + let code = bytes(payload, u64_at(record, 0)?, u64_at(record, 8)?) + .ok_or(Malformed("native code out of bounds"))?; + let vgprs = (u32_at(record, RECORD_REGS)? & 0x3FF) as u16; + if vgprs > 256 { + return Err(Malformed("implausible VGPR count")); + } + let table = |at: usize, count_at: usize| -> Result<&[u8], ShaderError> { + let len = ENTRY_SIZE * u64::from(u32_at(record, count_at)?); + if len == 0 { + return Ok(&[]); + } + bytes(payload, u64_at(record, at)?, len) + .ok_or(Malformed("FSSM root table out of bounds")) + }; + let layout = table(RECORD_LAYOUT, RECORD_COUNTS)? + .as_chunks::<{ ENTRY_SIZE as usize }>() + .0 + .iter() + .map(|e| RootParam { + root: RootType::from_raw(le32(e, 0)), + table_offset_dwords: le32(e, 4), + sgprs: le32(e, 8), + base_register: le32(e, 12), + user_data: e[16], + slot: e[17], + }) + .collect(); + let used = table(RECORD_USED, RECORD_COUNTS + 4)? + .as_chunks::<{ ENTRY_SIZE as usize }>() + .0 + .iter() + .map(|e| UsedResource { + kind: match e[0] { + 0 => ResourceType::Srv, + 1 => ResourceType::Sampler, + 2 => ResourceType::Cbv, + 3 => ResourceType::Uav, + n => ResourceType::Other(n), + }, + root: RootType::from_raw(e[1].into()), + table_offset_dwords: le32(e, 4), + lower_bound: le32(e, 8), + stride: le32(e, 12), + dwords: e[16], + user_data: e[17], + slot: e[18], + }) + .collect(); + // The record is in bounds, so its end is too. + let stage_data = &payload[(start + RECORD_SIZE) as usize..]; + let io = match stage { + HwStage::Ps => ps_io(stage_data, code.len())?, + HwStage::Vs => vs_io(stage_data)?, + HwStage::Cs => StageIo::Cs(ComputeIo { + rsrc2: u32_at(stage_data, CS_RSRC2)?, + threads: [ + u32_at(stage_data, CS_THREADS)?, + u32_at(stage_data, CS_THREADS + 4)?, + u32_at(stage_data, CS_THREADS + 8)?, + ], + }), + HwStage::Ms => ms_io(stage_data, u32_at(record, RECORD_LDS)?)?, + _ => StageIo::None, + }; + out.push(NativeProgram { + stage, + wave64: u32_at(record, RECORD_FLAGS)? & FLAG_WAVE32 == 0, + vgprs, + layout, + used, + io, + code: code.to_vec(), + }); + } + Ok(out) +} + +/// The entries of `size` bytes from `at`, with their count at `count_at`. +fn semantics(data: &[u8], at: usize, size: usize, count_at: usize) -> Result<&[u8], ShaderError> { + let count = u32_at(data, count_at)?; + if count > MAX_SEMANTICS { + return Err(Malformed("implausible semantic count")); + } + data.get(at..at + size * count as usize) + .ok_or(Malformed("stage data out of bounds")) +} + +fn ps_io(data: &[u8], code_len: usize) -> Result { + let inputs = semantics(data, PS_INPUTS, 8, PS_INPUT_COUNT)? + .as_chunks::<8>() + .0 + .iter() + .map(|e| PsInput { + usage: Usage::from_raw(e[0]), + row: e[1], + mask: e[2] & 0xf, + attr: e[3], + flat: e[7] & 1 != 0, + fp16: e[7] & 8 != 0, + pack2: e[7] & 0x10 != 0, + row2: e[5], + }) + .collect(); + let size = u32_at(data, PS_PATCH_SIZE)? as usize; + if size > PATCH_SLOT_DWORDS { + return Err(Malformed("implausible export patch size")); + } + let mut patches = Vec::new(); + for mrt in 0..MRTS { + let at = PS_PATCHES + mrt * PATCH_BYTES; + let offset = u32_at(data, at)?; + if offset == u32::MAX { + continue; + } + if (offset as usize + size) * 4 > code_len { + return Err(Malformed("export patch outside the code")); + } + let full = at + 4 + PATCH_FULL * PATCH_SLOT_DWORDS * 4; + let code = (0..size) + .map(|i| u32_at(data, full + 4 * i)) + .collect::>()?; + patches.push(ExportPatch { + mrt: mrt as u8, + offset, + code, + }); + } + Ok(StageIo::Ps { + inputs, + input_addr: u32_at(data, PS_INPUT_ADDR)?, + db_shader_control: u32_at(data, PS_DB_SHADER_CONTROL)?, + patches, + }) +} + +fn vs_io(data: &[u8]) -> Result { + let inputs = semantics(data, VS_INPUTS, 5, VS_INPUT_COUNT)? + .as_chunks::<5>() + .0 + .iter() + .map(|e| VsInput { + usage: Usage::from_raw(e[0]), + row: e[1], + mask: e[2] & 0xf, + vgpr: e[3], + }) + .collect(); + let outputs = semantics(data, VS_OUTPUTS, 6, VS_OUTPUT_COUNT)? + .as_chunks::<6>() + .0 + .iter() + .map(|e| VsOutput { + usage: Usage::from_raw(e[0]), + row: e[1], + param: e[2], + fp16: e[5] & 1 != 0, + pack2: e[5] & 2 != 0, + }) + .collect(); + Ok(StageIo::Vs { inputs, outputs }) +} + +fn ms_io(data: &[u8], lds_bytes: u32) -> Result { + let StageIo::Vs { outputs, .. } = vs_io(data)? else { + unreachable!() + }; + let info = data + .get(MS_INFO..MS_INFO + 8) + .ok_or(Malformed("stage data out of bounds"))?; + let half = |at: usize| u32::from(u16::from_le_bytes([info[at], info[at + 1]])); + Ok(StageIo::Ms(MeshIo { + outputs, + clip_cntl: u32_at(data, MS_CLIP_CNTL)?, + threads: half(0), + max_vertices: half(2), + max_primitives: half(4), + topology: info[7], + lds_bytes, + })) +} + +/// For entries already sized by `as_chunks`. +fn le32(entry: &[u8], at: usize) -> u32 { + u32::from_le_bytes(entry[at..at + 4].try_into().unwrap()) +} + +/// `data[offset..offset + len]` with untrusted 64-bit bounds. +fn bytes(data: &[u8], offset: u64, len: u64) -> Option<&[u8]> { + let start = usize::try_from(offset).ok()?; + data.get(start..start.checked_add(usize::try_from(len).ok()?)?) +} + +#[cfg(test)] +mod tests { + use super::*; + + const VS_CODE: [u8; 8] = [1, 2, 3, 4, 5, 6, 7, 8]; + const PS_CODE: [u8; 4] = [9, 10, 11, 12]; + const VGPRS: u32 = 28; + + fn slot(stage: HwStage) -> usize { + SLOTS.iter().find(|s| s.0 == stage).unwrap().1 + } + + /// Stage data: no semantics, and every export patch absent. + const STAGE_DATA: usize = PS_PATCHES + MRTS * PATCH_BYTES; + + fn empty_stage_data() -> Vec { + let mut data = vec![0; STAGE_DATA]; + for mrt in 0..MRTS { + let at = PS_PATCHES + mrt * PATCH_BYTES; + data[at..at + 4].copy_from_slice(&u32::MAX.to_le_bytes()); + } + data + } + + /// Where a one-program blob's stage data starts. + fn stage_data_at(blob: &[u8], stage: HwStage) -> usize { + FSSM_HEADER + + u64_at(blob, FSSM_HEADER + slot(stage)).unwrap() as usize + + RECORD_SIZE as usize + } + + /// FSSM blob with `programs` as (stage, code) pairs. + fn fssm(programs: &[(HwStage, &[u8])]) -> Vec { + let mut payload = GRAPHICS_SLOT_COUNT.to_le_bytes().to_vec(); + payload.resize(slot(HwStage::Cs) + 8, 0); + for (_, at) in SLOTS { + payload[at..at + 8].copy_from_slice(&ABSENT.to_le_bytes()); + } + for &(stage, code) in programs { + let slot = slot(stage); + let record = payload.len() as u64; + payload[slot..slot + 8].copy_from_slice(&record.to_le_bytes()); + let code_at = record + RECORD_SIZE + STAGE_DATA as u64; + payload.extend_from_slice(&code_at.to_le_bytes()); + payload.extend_from_slice(&(code.len() as u64).to_le_bytes()); + let flags = if stage == HwStage::Ps { FLAG_WAVE32 } else { 0 }; + payload.extend_from_slice(&[0; 4]); + payload.extend_from_slice(&flags.to_le_bytes()); + payload.resize(record as usize + RECORD_REGS, 0); + payload.extend_from_slice(&(VGPRS | 31 << 20).to_le_bytes()); + payload.extend_from_slice(&empty_stage_data()); + payload.extend_from_slice(code); + } + let mut out = b"FSSM".to_vec(); + out.extend_from_slice(&FSSM_VERSION.to_le_bytes()); + out.extend_from_slice(&(payload.len() as u64).to_le_bytes()); + out.extend_from_slice(&payload); + out + } + + fn xbch(unpacked: &[u8]) -> Vec { + let mut buf = vec![0u8; zlib_rs::compress_bound(unpacked.len())]; + let (stream, rc) = + zlib_rs::compress_slice(&mut buf, unpacked, zlib_rs::DeflateConfig::new(6)); + assert_eq!(rc, zlib_rs::ReturnCode::Ok); + let mut out = b"XBCH".to_vec(); + out.extend_from_slice(&XBCH_VERSION.to_le_bytes()); + out.extend_from_slice(&(stream.len() as u64).to_le_bytes()); + out.extend_from_slice(&(unpacked.len() as u64).to_le_bytes()); + out.extend_from_slice(stream); + out + } + + /// `DXIL` part data: program header, XDAT index, then the blobs. + fn part(blobs: &[(u32, &[u8])]) -> Vec { + let mut out = vec![0u8; XDAT_OFFSET]; + out.extend_from_slice(b"XDAT"); + out.extend_from_slice(&(blobs.len() as u32).to_le_bytes()); + out.extend_from_slice(&0x24u32.to_le_bytes()); + let mut offset = out.len() + 12 * blobs.len(); + for (kind, blob) in blobs { + for v in [*kind, offset as u32, blob.len() as u32] { + out.extend_from_slice(&v.to_le_bytes()); + } + offset += blob.len(); + } + for (_, blob) in blobs { + out.extend_from_slice(blob); + } + out + } + + #[test] + fn finds_graphics_programs() { + let native = xbch(&fssm(&[(HwStage::Vs, &VS_CODE), (HwStage::Ps, &PS_CODE)])); + let data = part(&[(0x0a, b"xbop"), (KIND_NATIVE, &native)]); + let found = native_programs(&data).unwrap(); + assert_eq!( + found, + [ + NativeProgram { + stage: HwStage::Vs, + wave64: true, + vgprs: 28, + layout: vec![], + used: vec![], + io: StageIo::Vs { + inputs: vec![], + outputs: vec![], + }, + code: VS_CODE.to_vec() + }, + NativeProgram { + stage: HwStage::Ps, + wave64: false, + vgprs: 28, + layout: vec![], + used: vec![], + io: StageIo::Ps { + inputs: vec![], + input_addr: 0, + db_shader_control: 0, + patches: vec![], + }, + code: PS_CODE.to_vec() + }, + ] + ); + } + + #[test] + fn reads_root_tables() { + let mut blob = fssm(&[(HwStage::Ps, &PS_CODE)]); + let record = FSSM_HEADER + u64_at(&blob, FSSM_HEADER + slot(HwStage::Ps)).unwrap() as usize; + let tables = (blob.len() - FSSM_HEADER) as u64; + // A table range in s9 (root slot 1), and an SRV read from it. + for v in [3u32, 2, 1, 5] { + blob.extend_from_slice(&v.to_le_bytes()); + } + blob.extend_from_slice(&[9, 1, 0, 0, 0, 3, 0, 0]); + for v in [2u32, 5, 4] { + blob.extend_from_slice(&v.to_le_bytes()); + } + blob.extend_from_slice(&[8, 9, 1, 0]); + let payload = (blob.len() - FSSM_HEADER) as u64; + blob[8..16].copy_from_slice(&payload.to_le_bytes()); + blob[record + RECORD_LAYOUT..][..8].copy_from_slice(&tables.to_le_bytes()); + blob[record + RECORD_USED..][..8].copy_from_slice(&(tables + ENTRY_SIZE).to_le_bytes()); + blob[record + RECORD_COUNTS..][..8].copy_from_slice(&[1, 0, 0, 0, 1, 0, 0, 0]); + + let p = &native_programs(&part(&[(KIND_NATIVE, &xbch(&blob))])).unwrap()[0]; + assert_eq!( + p.layout, + [RootParam { + root: RootType::Table, + table_offset_dwords: 2, + sgprs: 1, + base_register: 5, + user_data: 9, + slot: 1 + }] + ); + assert_eq!( + p.used, + [UsedResource { + kind: ResourceType::Srv, + root: RootType::Table, + table_offset_dwords: 2, + lower_bound: 5, + stride: 4, + dwords: 8, + user_data: 9, + slot: 1 + }] + ); + + blob[record + RECORD_COUNTS] = 9; + assert!(native_programs(&part(&[(KIND_NATIVE, &xbch(&blob))])).is_err()); + } + + #[test] + fn reads_pixel_io_and_applies_the_full_export_patch() { + let code = [0xBF80_0000u32; 4]; // s_nop + let bytes: Vec = code.iter().flat_map(|w| w.to_le_bytes()).collect(); + let mut blob = fssm(&[(HwStage::Ps, &bytes)]); + let e = stage_data_at(&blob, HwStage::Ps); + // TEXCOORD in row 1 (xy), read as attr0, flat. + blob[e + PS_INPUTS..][..8].copy_from_slice(&[6, 1, 3, 0, 0, 0, 1, 1]); + blob[e + PS_INPUT_COUNT..][..4].copy_from_slice(&1u32.to_le_bytes()); + blob[e + PS_INPUT_ADDR..][..4].copy_from_slice(&2u32.to_le_bytes()); + blob[e + PS_PATCH_SIZE..][..4].copy_from_slice(&2u32.to_le_bytes()); + // MRT1 at dword 1: the 32_ABGR variant is `exp mrt1 v0-v3 done`. + let patch = e + PS_PATCHES + PATCH_BYTES; + blob[patch..][..4].copy_from_slice(&1u32.to_le_bytes()); + let full = patch + 4 + PATCH_FULL * PATCH_SLOT_DWORDS * 4; + blob[full..][..8].copy_from_slice(&[0x1f, 0x18, 0, 0xf8, 0, 1, 2, 3]); + + let p = &native_programs(&part(&[(KIND_NATIVE, &xbch(&blob))])).unwrap()[0]; + let StageIo::Ps { + inputs, + input_addr, + patches, + .. + } = &p.io + else { + panic!("{:?}", p.io) + }; + let input = PsInput { + usage: Usage::Generic, + row: 1, + mask: 3, + attr: 0, + flat: true, + fp16: false, + pack2: false, + row2: 0, + }; + assert_eq!((&inputs[..], *input_addr), (&[input][..], 2)); + assert_eq!(patches.len(), 1); + assert_eq!((patches[0].mrt, patches[0].offset), (1, 1)); + let patched = p.patched_code(); + assert_eq!(patched[..4], p.code[..4]); + assert_eq!(patched[4..12], [0x1f, 0x18, 0, 0xf8, 0, 1, 2, 3]); + assert_eq!(patched[12..], p.code[12..]); + + blob[patch..][..4].copy_from_slice(&3u32.to_le_bytes()); + assert!(native_programs(&part(&[(KIND_NATIVE, &xbch(&blob))])).is_err()); + } + + #[test] + fn finds_mesh_and_compute_programs() { + for stage in [HwStage::Ms, HwStage::Cs] { + let data = part(&[(KIND_NATIVE, &xbch(&fssm(&[(stage, &VS_CODE)])))]); + let found = native_programs(&data).unwrap(); + assert_eq!(found.len(), 1); + assert_eq!(found[0].stage, stage); + } + } + + #[test] + fn reads_mesh_outputs_and_limits() { + let mut blob = fssm(&[(HwStage::Ms, &VS_CODE)]); + let e = stage_data_at(&blob, HwStage::Ms); + // param0 is row 1 per vertex, param2 row 0 of the primitive signature. + blob[e + VS_OUTPUTS..][..12].copy_from_slice(&[6, 1, 0, 0, 0, 0, 6, 0, 0x82, 0, 0, 0]); + blob[e + VS_OUTPUT_COUNT..][..4].copy_from_slice(&2u32.to_le_bytes()); + blob[e + MS_CLIP_CNTL..][..4].copy_from_slice(&0x0040_000Fu32.to_le_bytes()); + // 128 lanes, 128 vertices, 64 primitives, 13 user SGPRs, triangles. + blob[e + MS_INFO..][..8].copy_from_slice(&[0x80, 0, 0x80, 0, 0x40, 0, 13, 2]); + let record = e - RECORD_SIZE as usize; + blob[record + RECORD_LDS..][..4].copy_from_slice(&16u32.to_le_bytes()); + let p = &native_programs(&part(&[(KIND_NATIVE, &xbch(&blob))])).unwrap()[0]; + let out = |row, param| VsOutput { + usage: Usage::Generic, + row, + param, + fp16: false, + pack2: false, + }; + assert_eq!( + p.io, + StageIo::Ms(MeshIo { + outputs: vec![out(1, 0), out(0, 0x82)], + clip_cntl: 0x0040_000F, + threads: 128, + max_vertices: 128, + max_primitives: 64, + topology: 2, + lds_bytes: 16, + }) + ); + } + + #[test] + fn compute_dispatch_settings() { + // 5 user SGPRs, group id x and y, thread ids in v0-v1, 1 KiB LDS. + let cs = ComputeIo { + rsrc2: 0x1098A, + threads: [16, 16, 1], + }; + assert_eq!(cs.user_sgprs(), 5); + assert_eq!(cs.system_sgprs(), ([Some(5), Some(6), None], None)); + assert_eq!((cs.thread_id_vgprs(), cs.lds_bytes()), (2, 1024)); + // 6 user SGPRs, all three group ids, v0-v2, no LDS. + let cs = ComputeIo { + rsrc2: 0x138C, + threads: [8, 8, 1], + }; + assert_eq!(cs.system_sgprs(), ([Some(6), Some(7), Some(8)], None)); + assert_eq!((cs.thread_id_vgprs(), cs.lds_bytes()), (3, 0)); + } + + #[test] + fn initialized_sgprs_covers_user_system_and_scratch() { + // 5 user SGPRs, group ids x and y (s5, s6), no scratch: s0..=s6. + let cs = ComputeIo { + rsrc2: 0x1098A, + threads: [16, 16, 1], + }; + assert_eq!(cs.initialized_sgprs(), 7); + // All three group ids after 6 user SGPRs, plus the info SGPR: s0..=s9. + let cs = ComputeIo { + rsrc2: 0x78C, + threads: [8, 8, 1], + }; + assert_eq!(cs.initialized_sgprs(), 10); + // The same with scratch enabled adds the wave offset: s0..=s10. + let cs = ComputeIo { + rsrc2: 0x78D, + threads: [8, 8, 1], + }; + assert_eq!(cs.initialized_sgprs(), 11); + } + + #[test] + fn reads_every_native_blob() { + let es = xbch(&fssm(&[(HwStage::Es, &VS_CODE)])); + let vs = xbch(&fssm(&[(HwStage::Vs, &VS_CODE)])); + let data = part(&[(0x12, &[0; 16]), (KIND_NATIVE, &es), (KIND_NATIVE, &vs)]); + let stages: Vec<_> = native_programs(&data) + .unwrap() + .iter() + .map(|p| p.stage) + .collect(); + assert_eq!(stages, [HwStage::Es, HwStage::Vs]); + } + + #[test] + fn pc_layout_has_none() { + assert!(native_programs(&[0u8; 64]).unwrap().is_empty()); + assert!( + native_programs(&part(&[(0x0a, b"xbop")])) + .unwrap() + .is_empty() + ); + } + + #[test] + fn rejects_corrupt_blobs() { + let good = xbch(&fssm(&[(HwStage::Ls, &VS_CODE)])); + let corrupt = |at: usize, byte: u8| { + let mut blob = good.clone(); + blob[at] = byte; + native_programs(&part(&[(KIND_NATIVE, &blob)])) + }; + assert!(corrupt(4, 9).is_err(), "unknown version"); + assert!(corrupt(16, 0xFF).is_err(), "stated size"); + assert!(corrupt(XBCH_HEADER + 2, 0xFF).is_err(), "zlib stream"); + assert!(native_programs(&part(&[(KIND_NATIVE, &good[..20])])).is_err()); + + let mut bad_record = fssm(&[(HwStage::Ls, &VS_CODE)]); + let at = FSSM_HEADER + slot(HwStage::Ls); + bad_record[at..at + 8].copy_from_slice(&u64::MAX.to_le_bytes()); + assert!(native_programs(&part(&[(KIND_NATIVE, &xbch(&bad_record))])).is_err()); + } + + #[test] + fn rejects_truncated_oversized_and_bad_checksum_xbch_streams() { + let plain = fssm(&[(HwStage::Vs, &VS_CODE)]); + let good = xbch(&plain); + assert_eq!(unpack(&good).unwrap(), plain); + + // Truncated zlib stream (drop last byte, update packed length). + let mut truncated = good[..good.len() - 1].to_vec(); + let new_packed = (truncated.len() - XBCH_HEADER) as u64; + truncated[8..16].copy_from_slice(&new_packed.to_le_bytes()); + assert!(unpack(&truncated).is_err()); + + // Stated unpacked size smaller than the inflated output. + let mut oversized = good.clone(); + oversized[16..24].copy_from_slice(&((plain.len() - 1) as u64).to_le_bytes()); + assert!(unpack(&oversized).is_err()); + + // Stated unpacked size larger than the inflated output. + let mut underfilled = good.clone(); + underfilled[16..24].copy_from_slice(&((plain.len() + 1) as u64).to_le_bytes()); + assert!(unpack(&underfilled).is_err()); + + // Corrupt Adler-32 trailer. + let mut bad_adler = good.clone(); + *bad_adler.last_mut().unwrap() ^= 1; + assert!(unpack(&bad_adler).is_err()); + } +} diff --git a/crates/leonida-shader/src/resource.rs b/crates/leonida-shader/src/resource.rs new file mode 100644 index 000000000..2b6edd465 --- /dev/null +++ b/crates/leonida-shader/src/resource.rs @@ -0,0 +1,3848 @@ +//! Resource tracking (decision 0003): where each descriptor a program uses +//! comes from, in terms of the root signature. +//! +//! Root parameters arrive in user SGPRs ([`RootParam`]): a descriptor table +//! as the 32-bit heap address of its range (the code sets the high half to +//! 0), a root descriptor as a 64-bit buffer address, root constants as +//! themselves. A root signature with dynamic resources (SM 6.6) adds the +//! 32-bit base addresses of both heaps; a descriptor is then loaded from +//! one of them at an index the code computes (from a root constant, say). The code loads table descriptors from heap memory with +//! `s_load_dword*`, and builds a buffer descriptor around a root +//! descriptor's address itself. Each descriptor operand and each scalar +//! memory address is traced through the SSA values back to those +//! parameters, by data flow: copies, phis that agree, and additions. + +use crate::ShaderError; +use crate::gfx10::{Fields, NULL, Operand}; +use crate::ir::{EXEC, Exit, Inst, Program, Reg, Value}; +use crate::native::{HwStage, RootParam, RootType}; +use crate::structure::{Bool, LaneExit, Meets, Structured}; + +/// An instruction: block and index in [`crate::ir::Block::insts`]. +pub type Site = (usize, usize); + +/// A byte address: a root parameter's, plus a constant and at most one +/// value the program computes (an index times a stride, say). +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct Address { + /// Index into the layout, or [`CODE`]. + pub param: usize, + /// Added modulo 2^32 (with carry into the high half of a root + /// descriptor's address). + pub offset: u32, + pub dynamic: Option, +} + +/// [`Address::param`] of the program's own code: a constant table the +/// compiler appends after the code and reads through `s_getpc_b64`; the +/// offset is then the byte offset in the code. +pub const CODE: usize = usize::MAX; + +/// [`Address::param`] of title memory at an address no root parameter +/// gives: one the code computes from root constants, reads out of a +/// descriptor or loads from other memory (compute programs only: the +/// ray-tracing structure builder and the programs that walk its +/// structures). Offset and computed term are not used: lowering takes the +/// 64-bit address from the instruction's operands. +pub const MEMORY: usize = usize::MAX - 1; + +/// The reasons an address traces to no root parameter for which the +/// address is then taken as it stands ([`MEMORY`]). +const RAW: [&str; 5] = [ + "an address not from a root parameter", + "an address from a root parameter that is no address", + "an address in an SGPR that is no root parameter", + "an address loaded from memory", + "an address from a phi", +]; + +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Source { + /// Dwords `first..` of what the scalar load at `load` reads (see + /// [`Resources::scalar`] for its address). + Loaded { load: Site, first: u8 }, + /// A buffer descriptor built around an address: `bits` OR-ed into + /// dword 1 (stride, swizzle), dwords 2 and 3 as given. + Built { + address: Address, + bits: u32, + words: [u32; 2], + }, + /// Fixed in the code (an immediate sampler, say). + Constant(Vec), + /// Chosen by control flow: one source per predecessor of `block`, in + /// [`crate::ir::Block::preds`] order. + Phi { block: usize, args: Vec }, + /// Chosen by SCC (`scc`, the value an `s_cselect` or `s_cmov` of each + /// dword reads): the source when it is set, then when it is clear. + Select { scc: Value, args: Vec }, + /// Dwords `first..` of what the vector load at `load` (`global_load_*`) + /// reads, each lane at its own address (see [`Resources::scalar`]); the + /// dwords past that load come from loads of the bytes that follow. A + /// descriptor that differs between lanes. + Fetched { load: Site, first: u8 }, + /// Picked per lane by `v_cndmask_b32` reading the lane mask whose low + /// dword is `mask`: the source where the lane's bit is set, then where it + /// is clear. + Lanes { mask: Value, args: Vec }, + /// Per-lane dwords chosen by control flow (VGPRs joined where lanes + /// that took different paths meet): one source per predecessor of + /// `block`, in [`crate::ir::Block::preds`] order, `None` on an edge no + /// lane that accesses the descriptor takes. A descriptor that differs + /// between lanes. + LanePhi { + block: usize, + args: Vec>, + }, +} + +impl Source { + /// The sources this one picks from (itself unless a phi). + pub fn leaves(&self) -> Vec<&Source> { + match self { + Source::Phi { args, .. } | Source::Select { args, .. } | Source::Lanes { args, .. } => { + args.iter().flat_map(Source::leaves).collect() + } + Source::LanePhi { args, .. } => { + args.iter().flatten().flat_map(Source::leaves).collect() + } + s => vec![s], + } + } +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Role { + /// Image, buffer or `s_buffer_load` resource. + Resource, + Sampler, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Descriptor { + pub site: Site, + pub role: Role, + pub source: Source, +} + +/// A view-heap descriptor whose byte address can be evaluated when binding +/// the draw, using a table base and a root constant. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct RootIndexedView { + pub table_slot: u8, + pub constant_slot: u8, + pub constant_dword: u32, + pub byte_offset: u32, + pub shift: u8, +} + +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct Resources { + /// Every scalar memory access by address (`s_load_*`, `s_store_*`), and + /// every global memory access (`global_*`, the dynamic term per lane). + pub scalar: Vec<(Site, Address)>, + pub descriptors: Vec, + /// Direct descriptor sources with a draw-evaluable index. + pub root_indexed_views: Vec, + /// User SGPRs holding root parameters: value on entry, layout index, + /// dword within the parameter. + pub params: Vec<(Value, usize, u32)>, + /// Scalar loads of one descriptor the code keeps per lane in VGPRs + /// ([`Tracer::lane_copies`]): they read one address, so their dwords + /// stand in for each other. + pub lane_copied: Vec, + pub waterfall: Waterfall, + /// Every `image_bvh_intersect_ray` and `image_bvh64_intersect_ray`: where + /// its nodes are. + pub bvh: Vec<(Site, BvhNodes)>, +} + +/// Where a ray-tracing node test ([`crate::bvh`]) reads its nodes. Its +/// descriptor operand names a range of memory, not a texture. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum BvhNodes { + /// A buffer of the host: the descriptor is loaded from a table (it is + /// among [`Resources::descriptors`]), and node pointers count from the + /// buffer's start. Its flags are not known to the shader: boxes are + /// sorted and triangles return barycentrics, as every descriptor + /// the title builds asks. + Resource, + /// Title memory by address: the code makes the descriptor from numbers + /// (the title: the whole address space, or one structure's address in + /// dword 0). Dwords 1 and 3, which hold its flags. + Memory { word1: u32, word3: u32 }, +} + +/// Waterfall loops over descriptors that differ between lanes: each pass +/// reads the first active lane's descriptor with `v_readfirstlane_b32`, +/// compares it with every lane's own (`v_cmp_eq`), and runs the access with +/// the lanes that match. Their accesses take each lane's own descriptor +/// ([`Source::Fetched`], [`Source::Lanes`]), so the first lane's dwords are +/// each lane's own too: the compares hold in every lane and one pass serves +/// all lanes. +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct Waterfall { + /// The compares, true in every lane. + pub compares: Vec, + /// The `v_readfirstlane_b32` results they compare, each the lane's own + /// source dword. + pub reads: Vec, + /// Descriptor loads at a table offset among `reads` (the console + /// compiler's form): each lane loads its own entry. + pub loads: Vec, +} + +/// Traces every descriptor and scalar address of `p`, which runs as +/// `stage`, to the root parameters in `layout`. Fails on the first one it +/// cannot trace. `lanes`, `p` as one lane runs it, tells which paths the +/// lanes that access a per-lane descriptor took and which writes they ran; +/// without it, per-lane descriptors chosen by control flow are refused and +/// per-lane writes are taken to run in every lane. +pub fn track( + p: &Program, + layout: &[RootParam], + stage: HwStage, + lanes: Option<&Structured>, +) -> Result { + let t = Tracer::new(p, layout, stage, lanes)?; + let mut out = Resources { + params: p + .inputs + .iter() + .filter_map(|&(reg, v)| { + let (param, dword) = t.param_of(reg)?; + Some((v, param, dword)) + }) + .collect(), + ..Resources::default() + }; + // Group accesses in the same loop so a shared mask can select several + // descriptors together. + let mut first_lane_at = std::collections::BTreeMap::, Vec)>::new(); + // The console compiler's waterfall reads the first lane's table offset + // and loads that entry: accesses, offset reads and loads by block. + let mut offset_at = + std::collections::BTreeMap::, Vec, Vec)>::new(); + for (b, block) in p.blocks.iter().enumerate() { + t.at.set(Some(b)); + for (i, inst) in block.insts.iter().enumerate() { + let site = (b, i); + let fail = |what| ShaderError::Unsupported { + offset: inst.machine.offset, + what, + }; + let mut first_lane = Vec::new(); + let mut offset = Vec::new(); + let mut descriptor = |op: &Operand, role| -> Result<(), ShaderError> { + let source = t.descriptor(inst, op, b).map_err(fail)?; + // A descriptor the code keeps per lane ([`Tracer::lane_copies`]) + // is the same in every lane: its loop is lowered as it stands + // and needs no proof. + if !t.kept_per_lane(inst, op) { + first_lane.extend(t.first_lane_words(inst, op).unwrap_or_default()); + } + if let Source::Loaded { load, .. } = source + && out.scalar.iter().any(|s| s.0 == load) + && let Some(v) = t.first_lane_offset(load) + { + offset.push((v, load)); + } + out.descriptors.push(Descriptor { site, role, source }); + Ok(()) + }; + match &inst.fields { + Fields::Image { rsrc, .. } if inst.name().starts_with("image_bvh") => { + // The ray and node test names no texture. A descriptor + // whose flag dwords the code sets as numbers and whose + // type is a ray-tracing structure is a range of title + // memory (the title: all of it, or from one structure's + // address on), and the node's address is among the + // operands; any other descriptor must be a resource of + // the host. + let word = |k: u8| match *rsrc { + Operand::Scalar { code, dwords } if k < dwords => { + inst.read(Reg::S(code + k)).map(|v| t.origin(v)) + } + _ => None, + }; + match (word(1), word(3)) { + (Some(Term::Const(word1)), Some(Term::Const(word3))) + if word3 >> 28 == crate::bvh::DESCRIPTOR_TYPE => + { + out.bvh.push((site, BvhNodes::Memory { word1, word3 })); + } + _ => { + descriptor(rsrc, Role::Resource)?; + out.bvh.push((site, BvhNodes::Resource)); + } + } + } + Fields::Image { rsrc, sampler, .. } => { + descriptor(rsrc, Role::Resource)?; + if let Some(s) = sampler { + descriptor(s, Role::Sampler)?; + } + } + // Cache invalidations name a buffer's address space but do + // not read its descriptor; the host has no cache to drop. + Fields::Buffer { rsrc, .. } if !inst.name().ends_with("_inv") => { + descriptor(rsrc, Role::Resource)? + } + Fields::Buffer { .. } => {} + Fields::Smem { base, .. } if inst.name().starts_with("s_buffer_") => { + descriptor(base, Role::Resource)?; + } + Fields::Smem { + base, + offset, + soffset, + .. + } if inst.name().contains("_load_") || inst.name().contains("_store_") => { + let address = t + .smem_address(inst, base, *offset, soffset) + .or_else(|why| t.by_address(why)) + .map_err(fail)?; + out.scalar.push((site, address)); + } + Fields::Flat { + addr, + saddr, + offset, + .. + } if inst.name().starts_with("global_") => { + let address = t + .flat_address(inst, addr.as_ref(), saddr.as_ref(), *offset) + .or_else(|why| t.by_address(why)) + .map_err(fail)?; + out.scalar.push((site, address)); + } + _ => {} + } + if !first_lane.is_empty() { + let (accesses, reads) = first_lane_at.entry(b).or_default(); + accesses.push(i); + reads.extend(first_lane); + } + if !offset.is_empty() { + let (accesses, reads, loads) = offset_at.entry(b).or_default(); + accesses.push(i); + for (v, load) in offset { + reads.push(v); + loads.push(load); + } + } + } + } + // What follows traces no access of one block. + t.at.set(None); + // The proof needs the per-lane form. Without it nothing is emitted, and + // its failure is the one to report, so the reads stay unproven here. + if t.lanes.is_none() { + return Ok(out); + } + for (block, (accesses, mut reads)) in first_lane_at { + reads.sort_unstable(); + reads.dedup(); + let proof = t + .waterfall(block, &accesses, &reads) + .map_err(|what| ShaderError::Unsupported { + offset: t.inst((block, accesses[0])).machine.offset, + what, + })?; + out.waterfall.compares.extend(proof.compares); + out.waterfall.reads.extend(proof.reads); + } + // Unproven, an offset read stays the first lane's (one uniform entry), + // which is what the hardware reads outside a waterfall loop. + for (block, (accesses, mut reads, loads)) in offset_at { + reads.sort_unstable(); + reads.dedup(); + if let Ok(proof) = t.waterfall(block, &accesses, &reads) { + out.waterfall.compares.extend(proof.compares); + out.waterfall.reads.extend(proof.reads); + out.waterfall.loads.extend(loads); + } + } + out.lane_copied = t.lane_copied.take(); + out.lane_copied.sort_unstable(); + out.lane_copied.dedup(); + out.root_indexed_views = out + .descriptors + .iter() + .filter_map(|d| t.root_indexed_view(d, &out.scalar)) + .collect(); + Ok(out) +} + +/// A dword after copy propagation. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum Term { + Const(u32), + Value(Value), +} + +/// A 32-bit sum: optional root parameter (as its first dword), constant, +/// optional computed term. +struct Sum { + base: Option, + offset: u32, + dynamic: Option, +} + +struct Tracer<'a> { + p: &'a Program, + layout: &'a [RootParam], + stage: HwStage, + /// Defining instruction per value (phis and inputs have none). + defs: Vec>, + /// Block and index of each phi value. + phis: Vec>, + /// Register per input value. + inputs: Vec>, + origin: Vec, + /// See [`Resources::lane_copied`]. + lane_copied: std::cell::RefCell>, + lanes: Option<&'a Structured>, + /// While set, [`Self::sum`] keeps the first-lane read of an index as + /// the computed term instead of what the lanes hold. + read_first_lane: std::cell::Cell, + /// What the conditions asked of `lanes` so far came down to: the proofs + /// of one program ask about the same blocks and masks again and again. + meets: std::cell::RefCell, + /// Reverse-postorder index per block. + rpo: Vec, + /// The block of the access being traced ([`Self::live`]). + at: std::cell::Cell>, +} + +/// What lanes are known to satisfy: each [`Bool`] where its flag is set, +/// its negation where not. +type Known = Vec<(Bool, bool)>; + +const MAX_ROUNDS: usize = 64; +const MAX_JOINS: usize = 8; +/// VGPR values followed for one dword of a descriptor kept per lane. +const MAX_COPIES: usize = 64; + +impl<'a> Tracer<'a> { + fn new( + p: &'a Program, + layout: &'a [RootParam], + stage: HwStage, + lanes: Option<&'a Structured>, + ) -> Result { + let all = || { + 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))) + })) + }; + let n = all().map(|v| v.0 as usize + 1).max().unwrap_or(0); + let mut defs = vec![None; n]; + let mut phis = vec![None; n]; + let mut inputs = vec![None; n]; + for &(reg, v) in &p.inputs { + inputs[v.0 as usize] = Some(reg); + } + for (b, block) in p.blocks.iter().enumerate() { + for (i, phi) in block.phis.iter().enumerate() { + phis[phi.value.0 as usize] = Some((b, i)); + } + for (i, inst) in block.insts.iter().enumerate() { + for &(_, v) in &inst.writes { + defs[v.0 as usize] = Some((b, i)); + } + } + } + let mut rpo = vec![usize::MAX; p.blocks.len()]; + for (n, b) in crate::ir::reverse_postorder(&p.blocks) + .into_iter() + .enumerate() + { + rpo[b] = n; + } + let mut t = Tracer { + p, + layout, + stage, + defs, + phis, + inputs, + origin: Vec::new(), + lane_copied: Default::default(), + lanes, + read_first_lane: Default::default(), + meets: Default::default(), + rpo, + at: Default::default(), + }; + t.origin = t.propagate_copies(n)?; + Ok(t) + } + + /// Optimistic copy propagation: a move's result is its source's + /// origin, a phi's the one origin its arguments agree on. + fn propagate_copies(&self, n: usize) -> Result, ShaderError> { + let mut o: Vec> = vec![None; n]; + for &(_, v) in &self.p.inputs { + o[v.0 as usize] = Some(Term::Value(v)); + } + let order = crate::ir::reverse_postorder(&self.p.blocks); + for _ in 0..MAX_ROUNDS { + let mut changed = false; + for &b in &order { + let block = &self.p.blocks[b]; + for phi in &block.phis { + let own = Term::Value(phi.value); + let mut args = phi + .args + .iter() + .filter_map(|a| o[a.0 as usize]) + .filter(|&t| t != own); + let new = args + .next() + .map(|first| if args.all(|t| t == first) { first } else { own }); + if new.is_some() && new != o[phi.value.0 as usize] { + o[phi.value.0 as usize] = new; + changed = true; + } + } + for inst in &block.insts { + for (k, &(_, v)) in inst.writes.iter().enumerate() { + let new = match copy_source(inst, k).or_else(|| self.restored(inst)) { + Some(Moved::Const(c)) => Some(Term::Const(c)), + Some(Moved::Value(s)) => o[s.0 as usize], + None => Some(Term::Value(v)), + }; + if new.is_some() && new != o[v.0 as usize] { + o[v.0 as usize] = new; + changed = true; + } + } + } + } + if !changed { + return Ok(o + .into_iter() + .enumerate() + .map(|(v, t)| t.unwrap_or(Term::Value(Value(v as u32)))) + .collect()); + } + } + Err(ShaderError::Unsupported { + offset: 0, + what: "copies that do not settle", + }) + } + + /// Whether some lane can satisfy all of `conditions` ([`Bools::meet`]). + /// + /// [`Bools::meet`]: crate::structure::Bools::meet + fn meet(&self, lanes: &Structured, conditions: &[(Bool, bool)]) -> bool { + lanes + .bools + .meet_seen(conditions, &mut self.meets.borrow_mut()) + } + + fn inst(&self, (b, i): Site) -> &'a Inst { + &self.p.blocks[b].insts[i] + } + + fn def(&self, v: Value) -> Option<&'a Inst> { + self.defs[v.0 as usize].map(|s| self.inst(s)) + } + + fn origin(&self, v: Value) -> Term { + self.origin[v.0 as usize] + } + + /// The origin of a one-dword operand as `inst` reads it. + fn term(&self, inst: &Inst, op: &Operand) -> Option { + match *op { + Operand::Scalar { code: NULL, .. } => Some(Term::Const(0)), + Operand::Scalar { code, .. } => Some(self.origin(inst.read(Reg::S(code))?)), + Operand::Const(c) => inline(c).map(Term::Const), + Operand::Literal(x) => Some(Term::Const(x)), + _ => None, + } + } + + /// Layout index and dword of the root parameter `reg` holds on entry. + fn param_of(&self, reg: Reg) -> Option<(usize, u32)> { + let Reg::S(code) = reg else { return None }; + self.layout.iter().enumerate().find_map(|(i, p)| { + let first = self.stage.user_sgpr(p.user_data); + let dword = u32::from(code).checked_sub(first.into())?; + (dword < p.sgprs).then_some((i, dword)) + }) + } + + /// The SOP2 operands of `v` if an instruction with one of `names` wrote it. + fn sop2(&self, v: Value, names: &[&str]) -> Option<(&'a Inst, [Term; 2])> { + let inst = self.def(v)?; + if !names.contains(&inst.name()) || inst.writes.first()?.1 != v { + return None; + } + let Fields::Sop { src, .. } = &inst.fields else { + return None; + }; + Some(( + inst, + [ + self.term(inst, src.first()?)?, + self.term(inst, src.get(1)?)?, + ], + )) + } + + fn root_indexed_view( + &self, + descriptor: &Descriptor, + scalar: &[(Site, Address)], + ) -> Option { + if descriptor.role != Role::Resource { + return None; + } + let Source::Loaded { load, first } = descriptor.source else { + return None; + }; + let i = scalar.binary_search_by_key(&load, |(site, _)| *site).ok()?; + let address = scalar[i].1; + let base = self.layout.get(address.param)?; + if base.root != RootType::Table { + return None; + } + let dynamic = address.dynamic?; + let (input, shift) = match self.sop2(dynamic, &["s_lshl_b32"]) { + Some((_, [Term::Value(input), Term::Const(shift)])) => (input, (shift & 31) as u8), + _ => (dynamic, 0), + }; + let (param, constant_dword) = self.param_of(self.inputs[input.0 as usize]?)?; + let constant = self.layout.get(param)?; + if constant.root != RootType::Constants { + return None; + } + Some(RootIndexedView { + table_slot: base.slot, + constant_slot: constant.slot, + constant_dword, + byte_offset: address.offset.wrapping_add(u32::from(first) * 4), + shift, + }) + } + + fn sum(&self, t: Term) -> Sum { + let v = match t { + Term::Const(c) => { + return Sum { + base: None, + offset: c, + dynamic: None, + }; + } + Term::Value(v) => v, + }; + let dynamic = Sum { + base: None, + offset: 0, + dynamic: Some(v), + }; + if let Some(reg) = self.inputs[v.0 as usize] { + return match self.param_of(reg) { + Some((_, 0)) => Sum { + base: Some(v), + offset: 0, + dynamic: None, + }, + _ => dynamic, + }; + } + if self.getpc(v).is_some() { + return Sum { + base: Some(v), + offset: 0, + dynamic: None, + }; + } + // Paths that each add an index to a table in the code and meet before one + // load: the join itself is the computed term. Lowering gives every + // `s_getpc_b64` its own offset in the code as its value, so the join is the + // byte in the code whichever table a path took ([`Self::address`] adds no + // base to it). + if let Some(pc) = self.code_join(v) { + return Sum { + base: Some(pc), + offset: 0, + dynamic: Some(v), + }; + } + // An address computed in VGPRs and taken from the first lane (a + // table in the code indexed by a value held per lane, or a table + // offset held per lane, the console's waterfall): the sum of what + // the lanes hold. Loads at one offset in different loops (each with + // its own `v_readfirstlane_b32`) then have one address, which is + // what tells lowering that they read one descriptor. With + // `read_first_lane` a first-lane read of an index alone stays the + // computed term ([`Self::first_lane_offset`]). + if let Some(lane) = self.first_lane(v) { + let per_lane = self.sum(self.vorigin(lane)); + return if per_lane.base.is_some() || !self.read_first_lane.get() { + per_lane + } else { + dynamic + }; + } + let Some([a, b]) = self + .sop2(v, &["s_add_u32", "s_add_i32"]) + .map(|(_, t)| t) + .or_else(|| self.vadd(v)) + else { + return dynamic; + }; + let (x, y) = (self.sum(a), self.sum(b)); + if x.base.is_some() && y.base.is_some() || x.dynamic.is_some() && y.dynamic.is_some() { + return dynamic; + } + Sum { + base: x.base.or(y.base), + offset: x.offset.wrapping_add(y.offset), + dynamic: x.dynamic.or(y.dynamic), + } + } + + /// For a join `v` whose every incoming value adds to an `s_getpc_b64` low + /// dword: the first of those (one level of joins only). The paths may add + /// to different ones: two tables in the code, one picked by control flow + /// (the title's fog reconstruction reads its sample offsets from + /// one of two tables, by the sample's number; refused, the lit frame was + /// multiplied by a fog transmittance nothing had written). + fn code_join(&self, v: Value) -> Option { + let (b, i) = self.phis[v.0 as usize]?; + let mut base = None; + for &a in &self.p.blocks[b].phis[i].args { + let Term::Value(x) = self.vorigin(a) else { + return None; + }; + if x == v { + continue; + } + let pc = self.code_base(x, 4)?; + base = base.or(Some(pc)); + } + base + } + + /// `t` is the high dword of an `s_getpc_b64`, or `s_addc_u32`s of one: + /// the carry may be added in steps (the counter's high dword plus 0 + /// where the table's offset is added, then plus the index's high dword). + fn code_high(&self, t: Term) -> bool { + self.code_high_in(t, 4) + } + + /// [`Self::code_high`], at most `depth` additions deep. + fn code_high_in(&self, t: Term, depth: u32) -> bool { + let Term::Value(x) = t else { return false }; + if self.def(x).is_some_and(|i| { + i.name() == "s_getpc_b64" && i.writes.get(1).is_some_and(|w| w.1 == x) + }) { + return true; + } + depth > 0 + && self.sop2(x, &["s_addc_u32"]).is_some_and(|(_, [p, q])| { + self.code_high_in(p, depth - 1) || self.code_high_in(q, depth - 1) + }) + } + + /// The `s_getpc_b64` low dword among the terms `v` adds up (`depth` + /// additions deep; joins are not followed). + fn code_base(&self, v: Value, depth: u32) -> Option { + if self.getpc(v).is_some() { + return Some(v); + } + // Computed in VGPRs and taken from the first lane. + if let Some(lane) = self.first_lane(v) { + return match self.vorigin(lane) { + Term::Value(x) => self.code_base(x, depth), + Term::Const(_) => None, + }; + } + if depth == 0 || self.phis[v.0 as usize].is_some() { + return None; + } + let terms = self + .sop2(v, &["s_add_u32", "s_add_i32"]) + .map(|(_, t)| t) + .or_else(|| self.vadd(v))?; + terms.into_iter().find_map(|t| match t { + Term::Value(x) => self.code_base(x, depth - 1), + Term::Const(_) => None, + }) + } + + /// `t` is `high` or an `s_addc_u32` of it. + fn is_high(&self, t: Term, high: Value) -> bool { + match t { + Term::Value(x) => { + x == high + || self + .sop2(x, &["s_addc_u32"]) + .is_some_and(|(_, [p, q])| p == Term::Value(high) || q == Term::Value(high)) + } + Term::Const(_) => false, + } + } + + /// The VGPR value `v_readfirstlane_b32` reads to write the scalar `v`. + fn first_lane(&self, v: Value) -> Option { + let inst = self.def(v)?; + if inst.name() != "v_readfirstlane_b32" || inst.writes.first()?.1 != v { + return None; + } + let Fields::Valu(f) = &inst.fields else { + return None; + }; + if f.abs != 0 || f.neg != 0 || f.sdwa.is_some() || f.dpp.is_some() { + return None; + } + match *f.src.first()? { + Operand::Vector { reg, .. } => inst.read(Reg::V(reg)), + _ => None, + } + } + + /// The `s_getpc_b64` writing `lo` as its low dword. + fn getpc(&self, lo: Value) -> Option<&'a Inst> { + let inst = self.def(lo)?; + (inst.name() == "s_getpc_b64" && inst.writes.first().is_some_and(|w| w.1 == lo)) + .then_some(inst) + } + + /// The operands of a VALU addition (`v_add_co_u32`, `v_add_nc_u32`) + /// writing `v`, through VGPR copies of scalars. + fn vadd(&self, v: Value) -> Option<[Term; 2]> { + let inst = self.def(v)?; + let Fields::Valu(f) = &inst.fields else { + return None; + }; + if !matches!(inst.name(), "v_add_co_u32" | "v_add_nc_u32") + || f.dst.is_none_or(|d| !matches!(d, Operand::Vector { .. })) + || inst.write(Reg::V(match f.dst? { + Operand::Vector { reg, .. } => reg, + _ => return None, + })) != Some(v) + || f.abs != 0 + || f.neg != 0 + || f.sdwa.is_some() + || f.dpp.is_some() + { + return None; + } + Some([ + self.vterm(inst, f.src.first()?)?, + self.vterm(inst, f.src.get(1)?)?, + ]) + } + + /// The origin of a VALU operand. + fn vterm(&self, inst: &Inst, op: &Operand) -> Option { + match *op { + Operand::Vector { reg, .. } => Some(self.vorigin(inst.read(Reg::V(reg))?)), + op => self.term(inst, &op), + } + } + + /// A VGPR value's origin through `v_mov_b32` copies. + fn vorigin(&self, v: Value) -> Term { + if let Some(inst) = self.def(v) + && inst.name() == "v_mov_b32" + && let Fields::Valu(f) = &inst.fields + && f.abs == 0 + && f.neg == 0 + && f.sdwa.is_none() + && f.dpp.is_none() + && let Some(t) = f.src.first().and_then(|s| self.vterm(inst, s)) + { + return t; + } + self.origin(v) + } + + /// The address of an access that traces to no root parameter (`why` + /// says how it failed): title memory at the address as it stands, in a + /// compute program. + fn by_address(&self, why: &'static str) -> Result { + if self.stage == HwStage::Cs && RAW.contains(&why) { + Ok(Address { + param: MEMORY, + offset: 0, + dynamic: None, + }) + } else { + Err(why) + } + } + + /// A global memory address: an SGPR pair plus a VGPR offset, or a VGPR + /// pair. + fn flat_address( + &self, + inst: &Inst, + addr: Option<&Operand>, + saddr: Option<&Operand>, + offset: i16, + ) -> Result { + let Some(&Operand::Vector { reg, .. }) = addr else { + return Err("a global address not in VGPRs"); + }; + let off = offset as i32 as u32; + match saddr { + Some(&Operand::Scalar { code, .. }) if code != NULL => { + let word = |k| Some(self.origin(inst.read(Reg::S(code + k))?)); + let (Some(lo), Some(hi)) = (word(0), word(1)) else { + return Err("an address not in SGPRs"); + }; + let v = inst.read(Reg::V(reg)).ok_or("a global address")?; + let mut extra = self.sum(self.vorigin(v)); + if extra.base.is_some() { + return Err("an offset from a root parameter"); + } + extra.offset = extra.offset.wrapping_add(off); + self.address(lo, hi, extra) + } + _ => { + let word = |k| inst.read(Reg::V(reg + k)).map(|v| self.vorigin(v)); + let (Some(lo), Some(hi)) = (word(0), word(1)) else { + return Err("a global address"); + }; + self.address( + lo, + hi, + Sum { + base: None, + offset: off, + dynamic: None, + }, + ) + } + } + } + + /// The address `lo` and `hi` hold, plus `extra` (an instruction's + /// immediate and offset register). + fn address(&self, lo: Term, hi: Term, extra: Sum) -> Result { + // The high half as the lanes that read through the address hold + // it, where that is a constant or what a register held on entry + // (the code clears a table address's high half inside a branch + // and uses the address after the join). + let hi = match self.live(hi) { + t @ Term::Const(_) => t, + Term::Value(v) if self.inputs[v.0 as usize].is_some() => Term::Value(v), + _ => hi, + }; + let s = self.sum(lo); + if s.dynamic.is_some() && extra.dynamic.is_some() { + return Err("an address with two computed terms"); + } + let base = s.base.ok_or_else(|| self.why_no_base(s.dynamic))?; + if let Some(pc) = self.getpc(base) { + // A table in the code: the base is the next instruction's offset. + let high = pc.writes.get(1).map(|w| w.1); + if !self.high_half(hi, high) && !high.is_some_and(|h| self.carried(hi, h)) { + return Err("an address with an untracked high half"); + } + // A join of paths into tables in the code is the byte in the code + // already: each path's `s_getpc_b64` counts as its own offset. + let joined = s.dynamic.is_some_and(|d| self.code_join(d).is_some()); + let first = if joined { 0 } else { pc.machine.offset as u32 + 4 }; + return Ok(Address { + param: CODE, + offset: first.wrapping_add(s.offset).wrapping_add(extra.offset), + dynamic: s.dynamic.or(extra.dynamic), + }); + } + let reg = self.inputs[base.0 as usize].ok_or("an address not from a root parameter")?; + let (param, _) = self + .param_of(reg) + .ok_or("an address not from a root parameter")?; + let high = match self.layout[param].root { + RootType::Table | RootType::ResourceHeap | RootType::SamplerHeap => None, + RootType::Descriptor => { + let high = Reg::S(self.stage.user_sgpr(self.layout[param].user_data) + 1); + let input = self.p.inputs.iter().find(|i| i.0 == high); + Some(input.ok_or("a root descriptor without its high half")?.1) + } + _ => return Err("an address from a root parameter that is no address"), + }; + // shortcut: with a computed term, a high half that adds anything to the + // base's is taken as the carry of that term (offsets below 4 GB). + let dynamic = s.dynamic.or(extra.dynamic); + if !self.high_half(hi, high) + && !(dynamic.is_some() && high.is_some_and(|h| self.carried(hi, h))) + { + return Err("an address with an untracked high half"); + } + Ok(Address { + param, + offset: s.offset.wrapping_add(extra.offset), + dynamic: s.dynamic.or(extra.dynamic), + }) + } + + /// `hi` is `high` (0 for a table), possibly plus a carry. + fn high_half(&self, hi: Term, high: Option) -> bool { + let want = high.map_or(Term::Const(0), Term::Value); + hi == want + || matches!(hi, Term::Value(v) if self.sop2(v, &["s_addc_u32"]).is_some_and( + |(_, [a, b])| a == want && b == Term::Const(0) || b == want && a == Term::Const(0) + )) + } + + /// `hi` adds something (with carry) to `high`: `s_addc_u32` or + /// `v_add_co_ci_u32` with `high` as an operand. + fn carried(&self, hi: Term, high: Value) -> bool { + let Term::Value(v) = hi else { return false }; + if v == high { + return true; + } + // A join ([`Self::code_join`]): every path carries into the table's high half. + if let Some((b, i)) = self.phis[v.0 as usize] { + // A path may carry into another table's high half ([`Self::code_join`]). + let high_of = |t: Term| self.is_high(t, high) || self.code_high(t); + return self.p.blocks[b].phis[i].args.iter().all(|&a| { + let t = self.vorigin(a); + if t == Term::Value(v) || high_of(t) { + return true; + } + let Term::Value(x) = t else { + return false; + }; + // Computed in VGPRs and taken from the first lane. + let x = match self.first_lane(x).map(|lane| self.vorigin(lane)) { + Some(Term::Value(y)) => y, + Some(Term::Const(_)) => return false, + None => x, + }; + let Some(inst) = self.def(x) else { + return false; + }; + let Fields::Valu(f) = &inst.fields else { + return false; + }; + inst.name() == "v_add_co_ci_u32" + && f.src[..2.min(f.src.len())] + .iter() + .any(|o| self.vterm(inst, o).is_some_and(high_of)) + }); + } + if let Some(lane) = self.first_lane(v) { + return self.carried(self.vorigin(lane), high); + } + if let Some((_, [a, b])) = self.sop2(v, &["s_addc_u32"]) { + return self.carried(a, high) || self.carried(b, high); + } + let Some(inst) = self.def(v) else { + return false; + }; + let Fields::Valu(f) = &inst.fields else { + return false; + }; + inst.name() == "v_add_co_ci_u32" + && f.src[..2.min(f.src.len())] + .iter() + .any(|o| self.vterm(inst, o).is_some_and(|t| self.carried(t, high))) + } + + fn why_no_base(&self, dynamic: Option) -> &'static str { + let Some(v) = dynamic else { + return "a constant address"; + }; + if self.inputs[v.0 as usize].is_some() { + return "an address in an SGPR that is no root parameter"; + } + if self + .leaves(v) + .any(|l| self.def(l).is_some_and(|i| i.name() == "s_getpc_b64")) + { + return "an address relative to the program counter"; + } + match self.def(v).map(|i| i.name()) { + Some(n) if n.starts_with("s_load_") => "an address loaded from memory", + None => "an address from a phi", + _ => "an address not from a root parameter", + } + } + + /// The terms of the additions that compute `v`. + fn leaves(&self, v: Value) -> Box + '_> { + match self.sop2(v, &["s_add_u32", "s_add_i32"]) { + Some((_, terms)) => Box::new(terms.into_iter().flat_map(move |t| match t { + Term::Value(x) => self.leaves(x), + Term::Const(_) => Box::new(std::iter::empty()), + })), + None => Box::new(std::iter::once(v)), + } + } + + fn smem_address( + &self, + inst: &Inst, + base: &Operand, + offset: i32, + soffset: &Operand, + ) -> Result { + let Operand::Scalar { code, .. } = *base else { + return Err("an address not in SGPRs"); + }; + let word = |k| Some(self.origin(inst.read(Reg::S(code + k))?)); + let (Some(lo), Some(hi)) = (word(0), word(1)) else { + return Err("an address not in SGPRs"); + }; + let mut extra = self.sum( + self.term(inst, soffset) + .ok_or("an unknown offset operand")?, + ); + if extra.base.is_some() { + return Err("an offset from a root parameter"); + } + extra.offset = extra.offset.wrapping_add(offset as u32); + self.address(lo, hi, extra) + } + + /// The source of the descriptor operand `op` of `inst`, in block `at`. + fn descriptor(&self, inst: &Inst, op: &Operand, at: usize) -> Result { + let Operand::Scalar { code, dwords } = *op else { + return Err("a descriptor not in SGPRs"); + }; + let words = (0..dwords) + .map(|k| inst.read(Reg::S(code + k)).map(|v| self.origin(v))) + .collect::>>() + .ok_or("a descriptor not in SGPRs")?; + // Only the lanes that reach the access read the descriptor. + let mut known = Vec::from_iter(self.lanes.map(|l| (l.reach[at], true))); + self.classify(&words, &mut Vec::new(), &mut known) + } + + /// The source of a descriptor's words; `joins` are the phi blocks + /// being resolved, `known` holds in every lane that reads them. + fn classify( + &self, + words: &[Term], + joins: &mut Vec, + known: &mut Known, + ) -> Result { + if let Some(source) = self.phi(words, joins, known)? { + return Ok(source); + } + if let Some(source) = self.select(words, joins, known)? { + return Ok(source); + } + let read = |w: &Term| match *w { + Term::Value(v) => self.first_lane_source(v), + Term::Const(_) => None, + }; + if let Some(sources) = words.iter().map(read).collect::>>() { + // One descriptor the code keeps per lane: the lanes agree. + if let Some(source) = self.lane_copies(words) { + return Ok(source); + } + // Read from the first active lane, as a waterfall loop does: the + // dwords each lane holds. + let lanes: Vec = sources.into_iter().map(Term::Value).collect(); + return self.per_lane(&lanes, joins, known); + } + if words.iter().any(|w| read(w).is_some()) { + return Err("a descriptor partly read from the first lane"); + } + if let Some(consts) = words + .iter() + .map(|w| match *w { + Term::Const(c) => Some(c), + Term::Value(_) => None, + }) + .collect::>>() + { + return Ok(Source::Constant(consts)); + } + if let Some(source) = self.loaded(words) { + return Ok(source); + } + if let [lo, hi, Term::Const(w2), Term::Const(w3)] = *words { + let (mut hi, mut bits) = (hi, 0); + while let Term::Value(v) = hi + && let Some((x, more)) = self.set_bits(v) + { + (hi, bits) = (x, bits | more); + } + let address = self.address( + lo, + hi, + Sum { + base: None, + offset: 0, + dynamic: None, + }, + )?; + return Ok(Source::Built { + address, + bits, + words: [w2, w3], + }); + } + let loaded = |w: &Term| { + matches!(*w, Term::Value(v) + if self.def(v).is_some_and(|i| i.name().starts_with("s_load_"))) + }; + Err(if words.iter().any(loaded) { + "a descriptor changed after loading" + } else { + "a descriptor neither loaded nor built" + }) + } + + /// The one edge into the join `block` that lanes satisfying `known` + /// can have taken, if the lanes' paths ([`Structured`]) rule out every + /// other: the console compiler loads a descriptor (or clears an + /// address's high half) inside a branch that skips code when no lane + /// is left for it, and uses it after the join, where only lanes that + /// ran the branch are left (the title's + /// `CS_Alpha_Schedule`: the registers' values from before the branch, + /// which the join also sees, are what a wave with no such lane holds). + /// None at loop headers and without the lanes' paths. + fn only_edge(&self, block: usize, known: &mut Known) -> Option { + let lanes = self.lanes?; + let preds = &self.p.blocks[block].preds; + if preds.len() < 2 || preds.iter().any(|&q| self.rpo[q] >= self.rpo[block]) { + return None; + } + let mut only = None; + for (j, &q) in preds.iter().enumerate() { + let n = known.len(); + known.push((lanes.reach[q], true)); + if let LaneExit::Branch { + when, + taken, + not_taken, + } = lanes.exits[q] + && taken != not_taken + { + known.push((when, taken == block)); + } + let possible = self.meet(lanes, known); + known.truncate(n); + if possible { + if only.is_some() { + return None; + } + only = Some(j); + } + } + only + } + + /// Whether lowering can make a handle for `source` in any block: its + /// heap index comes from root parameters and constants alone (a table + /// offset the code computes exists only where the load is). + fn anywhere(&self, source: &Source) -> bool { + match source { + Source::Constant(_) => true, + Source::Built { address, .. } => address.dynamic.is_none(), + Source::Loaded { load, .. } => { + let inst = self.inst(*load); + match &inst.fields { + Fields::Smem { + base, + offset, + soffset, + .. + } => self + .smem_address(inst, base, *offset, soffset) + .is_ok_and(|a| a.dynamic.is_none()), + _ => false, + } + } + _ => false, + } + } + + /// `t` as the lanes that reach the access being traced hold it: through + /// joins they can have entered by one edge only ([`Self::only_edge`]). + fn live(&self, mut t: Term) -> Term { + let (Some(at), Some(lanes)) = (self.at.get(), self.lanes) else { + return t; + }; + let mut known = vec![(lanes.reach[at], true)]; + for _ in 0..MAX_JOINS { + let Term::Value(v) = t else { break }; + let Some((block, i)) = self.phis[v.0 as usize] else { + break; + }; + let Some(j) = self.only_edge(block, &mut known) else { + break; + }; + t = self.origin(self.p.blocks[block].phis[i].args[j]); + } + t + } + + /// Words that phis of one block join, traced per predecessor (words + /// defined before the join hold on every edge). + fn phi( + &self, + words: &[Term], + joins: &mut Vec, + known: &mut Known, + ) -> Result, &'static str> { + let phi_of = |w: &Term| match *w { + Term::Value(v) => self.phis[v.0 as usize], + Term::Const(_) => None, + }; + let Some((block, _)) = words.iter().find_map(phi_of) else { + return Ok(None); + }; + if words.iter().filter_map(phi_of).any(|(b, _)| b != block) { + return Err("a descriptor joined in several blocks"); + } + if joins.contains(&block) { + return Err("a descriptor that changes in a loop"); + } + // Each level multiplies the sources by the predecessor count. + if joins.len() >= MAX_JOINS { + return Err("a descriptor joined too often"); + } + joins.push(block); + let phis = &self.p.blocks[block].phis; + let edge = |j: usize| -> Vec { + words + .iter() + .map(|w| match phi_of(w) { + Some((_, i)) => self.origin(phis[i].args[j]), + None => *w, + }) + .collect() + }; + let args = (0..self.p.blocks[block].preds.len()) + .map(|j| self.classify(&edge(j), joins, known)) + .collect::>(); + let source = match args { + Ok(args) => Ok(Source::Phi { block, args }), + // An edge holds no descriptor. With only one edge the lanes + // that read the descriptor can have come by, it is what the + // registers hold on that one (a wave that took another edge + // has no lane left that reads it), if that can be named where + // it is read. + Err(e) => match self.only_edge(block, known) { + Some(j) => match self.classify(&edge(j), joins, known) { + Ok(source) if self.anywhere(&source) => Ok(source), + _ => Err(e), + }, + None => Err(e), + }, + }; + joins.pop(); + source.map(Some) + } + + /// Words that `s_cselect` (or `s_cmov`) picks by one SCC value, traced + /// per outcome (other words are the same for both). + fn select( + &self, + words: &[Term], + joins: &mut Vec, + known: &mut Known, + ) -> Result, &'static str> { + let picks: Vec<_> = words + .iter() + .map(|w| match *w { + Term::Value(v) => self.picked(v), + Term::Const(_) => None, + }) + .collect(); + let Some(scc) = picks.iter().flatten().map(|p| p.0).next() else { + return Ok(None); + }; + if picks.iter().flatten().any(|p| p.0 != scc) { + return Err("a descriptor chosen by several conditions"); + } + // Each level doubles the sources; selects count like joins (a + // marker no block index reaches). + if joins.len() >= MAX_JOINS { + return Err("a descriptor joined too often"); + } + joins.push(usize::MAX); + let side = |set: bool| -> Vec { + words + .iter() + .zip(&picks) + .map(|(w, p)| match p { + Some((_, t, f)) => { + if set { + *t + } else { + *f + } + } + None => *w, + }) + .collect() + }; + let args = [true, false] + .into_iter() + .map(|set| self.classify(&side(set), joins, known)) + .collect::>(); + joins.pop(); + Ok(Some(Source::Select { scc, args: args? })) + } + + /// For `v` written by `s_cselect_b32`/`_b64` or `s_cmov_b32`/`_b64`: + /// the SCC it reads and the dword it is when SCC is set, then clear. + fn picked(&self, v: Value) -> Option<(Value, Term, Term)> { + let inst = self.def(v)?; + let Fields::Sop { dst, src, .. } = &inst.fields else { + return None; + }; + let k = inst.writes.iter().position(|w| w.1 == v)? as u8; + let wide = match inst.name() { + "s_cselect_b32" | "s_cmov_b32" => false, + "s_cselect_b64" | "s_cmov_b64" => true, + _ => return None, + }; + // A dword of a 32- or 64-bit operand: 64-bit inline integers are + // sign-extended; 64-bit literals and float constants are not + // followed. + let dword = |op: &Operand| match *op { + Operand::Scalar { code: NULL, .. } => Some(Term::Const(0)), + Operand::Scalar { code, .. } => Some(self.origin(inst.read(Reg::S(code + k))?)), + Operand::Const(c) if !wide => inline(c).map(Term::Const), + Operand::Const(c @ 128..=208) => { + let low = inline(c)?; + Some(Term::Const(if k == 0 { + low + } else { + ((low as i32) >> 31) as u32 + })) + } + Operand::Literal(x) if !wide => Some(Term::Const(x)), + _ => None, + }; + let set = dword(src.first()?)?; + let clear = if inst.name().starts_with("s_cmov") { + dword(dst.as_ref()?)? + } else { + dword(src.get(1)?)? + }; + Some((inst.read(Reg::Scc)?, set, clear)) + } + + /// `v` as some other dword with constant bits set. + fn set_bits(&self, v: Value) -> Option<(Term, u32)> { + if let Some((_, [x, Term::Const(bits)] | [Term::Const(bits), x])) = + self.sop2(v, &["s_or_b32"]) + { + return Some((x, bits)); + } + let inst = self.def(v)?; + let Fields::Sop { + dst: Some(Operand::Scalar { code, .. }), + src, + .. + } = &inst.fields + else { + return None; + }; + match (inst.name(), self.term(inst, src.first()?)?) { + ("s_bitset1_b32", Term::Const(bit)) => { + Some((self.origin(inst.read(Reg::S(*code))?), 1 << (bit & 31))) + } + _ => None, + } + } + + /// For a `v_readfirstlane_b32` result: the VGPR value it reads. + fn first_lane_source(&self, v: Value) -> Option { + let inst = self.def(v)?; + let Fields::Valu(f) = &inst.fields else { + return None; + }; + if inst.name() != "v_readfirstlane_b32" || f.sdwa.is_some() || f.dpp.is_some() { + return None; + } + let Some(&Operand::Vector { reg, .. }) = f.src.first() else { + return None; + }; + inst.read(Reg::V(reg)) + } + + /// The `v_readfirstlane_b32` result the scalar load at `load` adds to + /// its address as a table offset (the console's waterfall, + /// `s_load_dwordx8 .., s[4:5], s20`): `track` proves the waterfall from + /// it, and lowering reads it per lane there. + fn first_lane_offset(&self, load: Site) -> Option { + let inst = self.inst(load); + let Fields::Smem { + base, + offset, + soffset, + .. + } = &inst.fields + else { + return None; + }; + self.read_first_lane.set(true); + let address = self.smem_address(inst, base, *offset, soffset); + self.read_first_lane.set(false); + match self.origin(address.ok()?.dynamic?) { + Term::Value(v) if self.first_lane_source(v).is_some() => Some(v), + _ => None, + } + } + + /// Whether the descriptor operand `op` of `inst` is one the code keeps + /// per lane ([`Self::lane_copies`]). + fn kept_per_lane(&self, inst: &Inst, op: &Operand) -> bool { + let Operand::Scalar { code, dwords } = *op else { + return false; + }; + (0..dwords) + .map(|k| inst.read(Reg::S(code + k)).map(|v| self.origin(v))) + .collect::>>() + .is_some_and(|words| self.lane_copies(&words).is_some()) + } + + /// The `v_readfirstlane_b32` results the descriptor operand `op` of + /// `inst` is, when every dword is one. + fn first_lane_words(&self, inst: &Inst, op: &Operand) -> Option> { + let Operand::Scalar { code, dwords } = *op else { + return None; + }; + (0..dwords) + .map(|k| match self.origin(inst.read(Reg::S(code + k))?) { + Term::Value(v) => self.first_lane_source(v).map(|_| v), + Term::Const(_) => None, + }) + .collect() + } + + /// `t` through VGPR copies (of VGPRs or of scalars) and copies. + fn lane_term(&self, mut t: Term) -> Term { + for _ in 0..MAX_JOINS * 2 { + let Term::Value(v) = t else { break }; + let next = self.vorigin(v); + if next == t { + break; + } + t = next; + } + t + } + + /// Whether `t` is a value each lane holds its own of (one in VGPRs). + fn varies(&self, t: Term) -> bool { + let Term::Value(v) = t else { return false }; + let reg = match (self.inputs[v.0 as usize], self.phis[v.0 as usize]) { + (Some(reg), _) => Some(reg), + (None, Some((b, i))) => Some(self.p.blocks[b].phis[i].reg), + (None, None) => self + .def(v) + .and_then(|i| i.writes.iter().find(|w| w.1 == v)) + .map(|w| w.0), + }; + matches!(reg, Some(Reg::V(_))) + } + + /// [`Self::lane_term`], where every lane in `known` runs each VGPR copy + /// it follows. + fn lane_value(&self, mut t: Term, known: &Known) -> Result { + for _ in 0..MAX_JOINS * 2 { + let Term::Value(v) = t else { break }; + let next = self.vstep(v); + if next == t { + break; + } + if self.varies(t) + && let Some(site) = self.defs[v.0 as usize] + { + self.runs(site, known)?; + } + t = next; + } + Ok(t) + } + + /// One copy of [`Self::vorigin`]: what the `v_mov_b32` writing `v` + /// reads, or `v`'s origin. + fn vstep(&self, v: Value) -> Term { + if let Some(inst) = self.def(v) + && inst.name() == "v_mov_b32" + && let Fields::Valu(f) = &inst.fields + && f.abs == 0 + && f.neg == 0 + && f.sdwa.is_none() + && f.dpp.is_none() + && let Some(t) = f.src.first().and_then(|s| self.raw(inst, s)) + { + return t; + } + self.origin(v) + } + + /// A VALU operand as `inst` reads it: a VGPR's value itself, other + /// operands' origins. + fn raw(&self, inst: &Inst, op: &Operand) -> Option { + match *op { + Operand::Vector { reg, .. } => Some(Term::Value(inst.read(Reg::V(reg))?)), + op => self.term(inst, &op), + } + } + + /// Fails unless every lane in `known` that reaches the vector + /// instruction at `site` runs it: one with its EXEC bit clear there + /// keeps what the registers held before. + fn runs(&self, site: Site, known: &Known) -> Result<(), &'static str> { + let Some(lanes) = self.lanes else { + return Ok(()); + }; + let Some(&Some(guard)) = lanes.guards.get(site.0).and_then(|g| g.get(site.1)) else { + return Ok(()); + }; + let mut skips = known.clone(); + skips.extend([(lanes.reach[site.0], true), (guard, false)]); + if self.meet(lanes, &skips) { + return Err("a per-lane descriptor written where some lanes may keep the old one"); + } + Ok(()) + } + + /// The source of descriptor dwords each lane holds its own of (a + /// waterfall loop reads them from the first active lane): the same in + /// every lane, loaded per lane from memory a heap address points to, or + /// picked per lane between such sources, by a lane mask or by the path + /// the lane took. `known` holds in every lane that accesses them. + fn per_lane( + &self, + words: &[Term], + joins: &mut Vec, + known: &mut Known, + ) -> Result { + let words = words + .iter() + .map(|&w| self.lane_value(w, known)) + .collect::, _>>()?; + let words = &words[..]; + let Some(&lane) = words.iter().find(|&&w| self.varies(w)) else { + return self.classify(words, joins, known); + }; + if let Some(source) = self.fetched(words, known)? { + return Ok(source); + } + if let Some(source) = self.lane_select(words, joins, known)? { + return Ok(source); + } + if let Some(source) = self.lane_phi(words, joins, known)? { + return Ok(source); + } + let Term::Value(v) = lane else { unreachable!() }; + let name = self.def(v).map(|i| i.name()); + Err(match name { + _ if self.inputs[v.0 as usize].is_some() => { + "a descriptor read from the first lane of an input VGPR" + } + None => "a descriptor read from the first lane of a phi", + Some(n) if n.starts_with("ds_read") => { + "a descriptor read from the first lane of an LDS read" + } + Some(n) if n.starts_with("buffer_load") => { + "a descriptor read from the first lane of a buffer load" + } + Some(n) if n.starts_with("global_load") || n.starts_with("flat_load") => { + "a descriptor read from the first lane of a partial or mixed load" + } + Some(_) => "a descriptor read from the first lane of computed VGPRs", + }) + } + + /// Dwords of `global_load_dword*` that line up: `first..` of one load, + /// then the bytes that follow (an image descriptor takes two + /// `global_load_dwordx4`). + fn fetched(&self, words: &[Term], known: &Known) -> Result, &'static str> { + let at = |w: &Term| -> Option<(Site, usize)> { + let Term::Value(v) = *w else { return None }; + let site = self.defs[v.0 as usize]?; + let inst = self.inst(site); + if !inst.name().starts_with("global_load_dword") { + return None; + } + let k = inst + .writes + .iter() + .filter(|w| matches!(w.0, Reg::V(_))) + .position(|w| w.1 == v)?; + Some((site, k)) + }; + let Some(sites) = words.iter().map(at).collect::>>() else { + return Ok(None); + }; + let address = |site: Site| { + let inst = self.inst(site); + let Fields::Flat { + addr, + saddr, + offset, + .. + } = &inst.fields + else { + return Err("a global load"); + }; + self.flat_address(inst, addr.as_ref(), saddr.as_ref(), *offset) + }; + let (load, first) = sites[0]; + let a0 = address(load)?; + for (k, &(site, dword)) in sites.iter().enumerate() { + self.runs(site, known)?; + let a = address(site)?; + let want = a0.offset.wrapping_add(4 * (first + k) as u32); + if (a.param, a.dynamic) != (a0.param, a0.dynamic) + || a.offset.wrapping_add(4 * dword as u32) != want + { + return Err("a descriptor read from the first lane of loads that do not line up"); + } + } + Ok(Some(Source::Fetched { + load, + first: first as u8, + })) + } + + /// Words that `v_cndmask_b32` picks by one lane mask, traced per outcome + /// (other words are the same for both). + fn lane_select( + &self, + words: &[Term], + joins: &mut Vec, + known: &mut Known, + ) -> Result, &'static str> { + let picks: Vec<_> = words + .iter() + .map(|w| match *w { + Term::Value(v) => self.lane_picked(v), + Term::Const(_) => None, + }) + .collect(); + let Some(mask) = picks.iter().flatten().map(|p| p.0).next() else { + return Ok(None); + }; + if picks.iter().flatten().any(|p| p.0 != mask) { + return Err("a descriptor chosen per lane by several masks"); + } + for (w, p) in words.iter().zip(&picks) { + if let (Term::Value(v), Some(_)) = (*w, p) + && let Some(site) = self.defs[v.0 as usize] + { + self.runs(site, known)?; + } + } + if joins.len() >= MAX_JOINS { + return Err("a descriptor joined too often"); + } + joins.push(usize::MAX); + // Each side holds where the lane's bit of the mask is set, or clear. + let bit = self.lanes.and_then(|l| l.masks.get(&mask).copied()); + let side = |set: bool| -> Vec { + words + .iter() + .zip(&picks) + .map(|(w, p)| match p { + Some((_, t, f)) => { + if set { + *t + } else { + *f + } + } + None => *w, + }) + .collect() + }; + let args = [true, false] + .into_iter() + .map(|set| { + let n = known.len(); + known.extend(bit.map(|b| (b, set))); + let arg = self.per_lane(&side(set), joins, known); + known.truncate(n); + arg + }) + .collect::>(); + joins.pop(); + Ok(Some(Source::Lanes { mask, args: args? })) + } + + /// For `v` written by a plain `v_cndmask_b32`: the low dword of the + /// lane mask it reads, and the dword it is where the lane's bit is set + /// (src1), then clear (src0). + fn lane_picked(&self, v: Value) -> Option<(Value, Term, Term)> { + let inst = self.def(v)?; + let Fields::Valu(f) = &inst.fields else { + return None; + }; + let Some(Operand::Vector { reg, .. }) = f.dst else { + return None; + }; + if inst.name() != "v_cndmask_b32" + || inst.write(Reg::V(reg)) != Some(v) + || f.abs != 0 + || f.neg != 0 + || f.clamp + || f.omod != 0 + || f.sdwa.is_some() + || f.dpp.is_some() + { + return None; + } + let [clear, set, Operand::Scalar { code, .. }] = f.src[..] else { + return None; + }; + let mask = inst.read(Reg::S(code))?; + Some((mask, self.raw(inst, &set)?, self.raw(inst, &clear)?)) + } + + /// Per-lane words that phis of one block join, as an if/else on a + /// per-lane condition leaves them: traced on each edge into the block + /// that lanes in `known` can take (other words hold on every edge). + /// Lanes take their own paths ([`Structured`]), so each gets the value + /// of the edge it came by; an edge they cannot take is `None` (a flow + /// block's phi joins an arm's dwords with what lanes that skipped the + /// arm held before, which only they read). + fn lane_phi( + &self, + words: &[Term], + joins: &mut Vec, + known: &mut Known, + ) -> Result, &'static str> { + let phi_of = |w: &Term| match *w { + Term::Value(v) => self.phis[v.0 as usize], + Term::Const(_) => None, + }; + let Some((block, _)) = words.iter().find_map(phi_of) else { + return Ok(None); + }; + if words.iter().filter_map(phi_of).any(|(b, _)| b != block) { + return Err("a descriptor joined in several blocks"); + } + if joins.contains(&block) { + return Err("a descriptor that changes in a loop"); + } + let preds = &self.p.blocks[block].preds; + if preds.iter().any(|&q| self.rpo[q] >= self.rpo[block]) { + // shortcut: what a lane holds after some passes is not traced. + return Err("a descriptor read from the first lane of a phi at a loop header"); + } + let Some(lanes) = self.lanes else { + return Err("a descriptor read from the first lane of a phi, without the lanes' paths"); + }; + // The other words must be there before the join: defined in a + // block that dominates it, which (both dominating the access) is + // one the join does not reach. + for w in words { + if let Term::Value(v) = *w + && phi_of(w).is_none() + && let Some((d, _)) = self.defs[v.0 as usize] + && (d == block || self.reaches(block, d)) + { + return Err("a descriptor partly joined by control flow"); + } + } + if joins.len() >= MAX_JOINS { + return Err("a descriptor joined too often"); + } + joins.push(block); + let phis = &self.p.blocks[block].phis; + let mut args = Vec::new(); + for (j, &q) in preds.iter().enumerate() { + let n = known.len(); + known.push((lanes.reach[q], true)); + if let LaneExit::Branch { + when, + taken, + not_taken, + } = lanes.exits[q] + && taken != not_taken + { + known.push((when, taken == block)); + } + let arg = if self.meet(lanes, known) { + let edge: Vec = words + .iter() + .map(|w| match phi_of(w) { + Some((_, i)) => Term::Value(phis[i].args[j]), + None => *w, + }) + .collect(); + self.per_lane(&edge, joins, known).map(Some) + } else { + Ok(None) + }; + known.truncate(n); + match arg { + Ok(a) => args.push(a), + Err(e) => { + joins.pop(); + return Err(e); + } + } + } + joins.pop(); + Ok(Some(Source::LanePhi { block, args })) + } + + /// Whether a path leads from block `from` to block `to` (to `from` + /// itself only through a back edge). + fn reaches(&self, from: usize, to: usize) -> bool { + let mut seen = vec![false; self.p.blocks.len()]; + let mut stack = self.p.blocks[from].exit.successors(); + while let Some(x) = stack.pop() { + if x == to { + return true; + } + if std::mem::replace(&mut seen[x], true) { + continue; + } + stack.extend(self.p.blocks[x].exit.successors()); + } + false + } + + /// Prove a single-block waterfall at the descriptor access. In each + /// iteration the access serves exactly the matching lanes, and the + /// back edge keeps exactly the other lanes active. Otherwise, why not. + /// + // shortcut: only the accesses are proven. Any other per-lane work in the + // loop is taken to run once for each lane, as the access does; a body + // whose effect adds up over the passes a lane waits through (a counter + // before the mask is narrowed) would differ. Compilers put nothing but + // the reads, the compares and the access in these loops. + fn waterfall( + &self, + b: usize, + accesses: &[usize], + reads: &[Value], + ) -> Result { + const LOOP: &str = "a descriptor read from the first lane outside a waterfall loop"; + const SPLIT: &str = "a waterfall loop nested in another or split over blocks"; + const SELECT: &str = "a waterfall loop whose compares do not select the access's lanes"; + const RETRY: &str = "a waterfall loop whose retry does not keep the lanes still waiting"; + let access = accesses[0]; + let block = &self.p.blocks[b]; + let lanes = self.lanes.ok_or(LOOP)?; + let exit = block.insts.last().ok_or(LOOP)?; + if !matches!(block.exit, Exit::Branch { taken, not_taken } if taken == b && not_taken != b) + || exit.name() != "s_cbranch_execnz" + { + return Err(LOOP); + } + let mask = |low: Option, high: Option| { + let high = if self.p.wave64 { Some(high?) } else { None }; + lanes.mask_bits(low?, high) + }; + let exec = |inst: &Inst| mask(inst.read(Reg::S(EXEC)), inst.read(Reg::S(EXEC + 1))); + // The reads belong to this loop's own block: a loop around this one + // (one per operand, as LLVM nests them for a per-lane image and + // sampler) is not followed. + if reads + .iter() + .any(|v| self.defs[v.0 as usize].is_none_or(|at| at.0 != b)) + { + return Err(SPLIT); + } + let selected = exec(&block.insts[access]).ok_or(SELECT)?; + if accesses + .iter() + .any(|&i| exec(&block.insts[i]) != Some(selected)) + { + return Err(SELECT); + } + let retry = exec(exit).ok_or(RETRY)?; + let first = self.defs[reads[0].0 as usize].ok_or(LOOP)?; + let remaining = exec(self.inst(first)).ok_or(SELECT)?; + if reads.iter().any(|v| { + self.defs[v.0 as usize] + .is_none_or(|at| at.1 >= access || exec(self.inst(at)) != Some(remaining)) + }) { + return Err(SELECT); + } + let reach = (lanes.reach[b], true); + let meet = |conditions: &[(Bool, bool)]| self.meet(lanes, conditions); + let mut out = Waterfall::default(); + let mut required = vec![(remaining, true)]; + for (i, inst) in block.insts[..access].iter().enumerate() { + let Fields::Valu(f) = &inst.fields else { + continue; + }; + let Some(ty) = inst + .name() + .strip_prefix("v_cmp_eq_") + .or(inst.name().strip_prefix("v_cmpx_eq_")) + else { + continue; + }; + let dwords = match ty { + "u32" | "i32" => 1, + "u64" | "i64" => 2, + _ => continue, + }; + if f.abs != 0 || f.neg != 0 || f.sdwa.is_some() || f.dpp.is_some() { + continue; + } + // The first lane's dwords on one side, the lane's own on the + // other. + let pair = |first: &Operand, own: &Operand| -> Option> { + let (&Operand::Scalar { code, .. }, &Operand::Vector { reg, .. }) = (first, own) + else { + return None; + }; + (0..dwords) + .map(|k| { + let Term::Value(x) = self.origin(inst.read(Reg::S(code + k))?) else { + return None; + }; + let lane = inst.read(Reg::V(reg + k))?; + let (_, read) = self.defs[x.0 as usize]?; + let same = reads.contains(&x) + && read < i + && self.lane_term(Term::Value(self.first_lane_source(x)?)) + == self.lane_term(Term::Value(lane)); + same.then_some(x) + }) + .collect() + }; + let (Some(a), Some(c)) = (f.src.first(), f.src.get(1)) else { + continue; + }; + if let Some(xs) = pair(a, c).or_else(|| pair(c, a)) { + let code = if inst.name().starts_with("v_cmpx_") { + EXEC + } else if let Some(Operand::Scalar { code, .. }) = f.dst { + code + } else { + continue; + }; + let Some(matched) = mask(inst.write(Reg::S(code)), inst.write(Reg::S(code + 1))) else { + continue; + }; + if meet(&[reach, (selected, true), (matched, false)]) { + continue; + } + required.push((matched, true)); + out.compares.push((b, i)); + for x in xs { + if !out.reads.contains(&x) { + out.reads.push(x); + } + } + } + } + if reads.iter().any(|v| !out.reads.contains(v)) + || meet(&[reach, (selected, true), (remaining, false)]) + { + return Err(SELECT); + } + // The access must take every match. + required.extend([reach, (selected, false)]); + if meet(&required) { + return Err(SELECT); + } + // The retry must keep exactly the lanes that were eligible but did + // not perform the access. + if meet(&[reach, (retry, true), (remaining, false)]) + || meet(&[reach, (retry, true), (selected, true)]) + || meet(&[reach, (remaining, true), (selected, false), (retry, false)]) + { + return Err(RETRY); + } + Ok(out) + } + + /// Consecutive dwords of one scalar load. + fn loaded(&self, words: &[Term]) -> Option { + let Term::Value(v0) = words[0] else { + return None; + }; + let load = self.defs[v0.0 as usize]?; + let inst = self.inst(load); + if !inst.name().starts_with("s_load_") { + return None; + } + let first = inst.writes.iter().position(|w| w.1 == v0)?; + let same = words.iter().enumerate().all(|(k, w)| { + inst.writes + .get(first + k) + .is_some_and(|x| *w == Term::Value(x.1)) + }); + same.then_some(Source::Loaded { + load, + first: first as u8, + }) + } + + /// A descriptor the code keeps per lane: every dword of `words` is the + /// first lane (`v_readfirstlane_b32`) of a VGPR that `v_mov_b32` filled + /// from SGPRs. The console compiler does this to a descriptor loaded on + /// both sides of a per-lane branch: the join is per lane, so it lives in + /// VGPRs, and the instruction that needs it in SGPRs runs in a loop over + /// the distinct values (the first lane's, the lanes holding the same, + /// then the rest). When every scalar those moves copy is the same dword + /// of loads from one constant address, the lanes agree and the + /// descriptor is any of those loads. + // shortcut: what else the VGPRs held (numbers, on paths or in lanes that + // never read them as a descriptor) is ignored, and a move is taken to + // leave either its source or what a move before it wrote; a descriptor + // read per lane from memory (`global_load_*`) refuses. + fn lane_copies(&self, words: &[Term]) -> Option { + let mut loads: Vec = Vec::new(); + let mut first = None; + for (k, w) in words.iter().enumerate() { + let Term::Value(v) = *w else { return None }; + let mut copies = Vec::new(); + if !self.scalar_copies(self.first_lane(v)?, &mut copies) { + return None; + } + let mut found = false; + for c in copies { + let Term::Value(c) = c else { continue }; + let Some(site) = self.defs[c.0 as usize] else { + continue; + }; + let load = self.inst(site); + if !load.name().starts_with("s_load_") { + continue; + } + // Dword k of the operand is dword `first + k` of each load. + let dword = load.writes.iter().position(|x| x.1 == c)?; + let f = dword.checked_sub(k)?; + if *first.get_or_insert(f) != f { + return None; + } + if !loads.contains(&site) { + loads.push(site); + } + found = true; + } + if !found { + return None; + } + } + let address = |site: Site| { + let inst = self.inst(site); + match &inst.fields { + Fields::Smem { + base, + offset, + soffset, + .. + } => self.smem_address(inst, base, *offset, soffset).ok(), + _ => None, + } + }; + let a = address(*loads.first()?)?; + if a.dynamic.is_some() || loads.iter().any(|&l| address(l) != Some(a)) { + return None; + } + // The handle is made where the descriptor is used, from the load's + // operands: take a load whose base is the root parameter's own SGPR. + loads.sort_unstable(); + let load = *loads.iter().find(|&&l| self.base_from_entry(l))?; + self.lane_copied.borrow_mut().extend(&loads); + Some(Source::Loaded { + load, + first: first? as u8, + }) + } + + /// The scalars (as origins) that `v_mov_b32` copies put in VGPR value + /// `v`, through joins, moves between VGPRs and per-lane selects; a move + /// keeps what it wrote over in the lanes it does not run. False if the + /// VGPR may hold something read per lane from memory. + fn scalar_copies(&self, v: Value, out: &mut Vec) -> bool { + let (mut seen, mut work) = (Vec::new(), vec![v]); + while let Some(v) = work.pop() { + if seen.contains(&v) { + continue; + } + if seen.len() == MAX_COPIES { + return false; + } + seen.push(v); + if let Some((b, i)) = self.phis[v.0 as usize] { + work.extend(&self.p.blocks[b].phis[i].args); + continue; + } + // An entry value, or a number some instruction computed. + let Some(inst) = self.def(v) else { continue }; + if inst.name().starts_with("global_load_") { + return false; + } + let Fields::Valu(f) = &inst.fields else { + continue; + }; + let sources = match inst.name() { + "v_mov_b32" => 1, + "v_cndmask_b32" => 2, + _ => continue, + }; + if f.abs != 0 || f.neg != 0 || f.sdwa.is_some() || f.dpp.is_some() { + continue; + } + for op in f.src.iter().take(sources) { + match *op { + Operand::Vector { reg, .. } => work.extend(inst.read(Reg::V(reg))), + Operand::Scalar { code, .. } if code != NULL => { + out.extend(inst.read(Reg::S(code)).map(|s| self.origin(s))); + } + _ => {} + } + } + // Lanes outside EXEC keep the old value. + if let Some(Operand::Vector { reg, .. }) = f.dst { + work.extend(inst.read(Reg::V(reg))); + } + } + true + } + + /// The load at `site` has a constant offset and takes its base from a + /// root parameter's SGPR through moves alone: a value that exists + /// wherever the descriptor is used. + fn base_from_entry(&self, site: Site) -> bool { + let inst = self.inst(site); + let Fields::Smem { + base: Operand::Scalar { code, .. }, + soffset: Operand::Scalar { code: NULL, .. }, + .. + } = &inst.fields + else { + return false; + }; + let Some(mut v) = inst.read(Reg::S(*code)) else { + return false; + }; + loop { + if self.inputs[v.0 as usize].is_some() { + return true; + } + let Some(def) = self.def(v) else { return false }; + let Some(k) = def.writes.iter().position(|w| w.1 == v) else { + return false; + }; + match copy_source(def, k) { + Some(Moved::Value(s)) => v = s, + _ => return false, + } + } + } +} + +#[derive(Clone, Copy, PartialEq, Eq)] +enum Moved { + Const(u32), + Value(Value), +} + +impl Tracer<'_> { + /// For `v_readlane_b32` of a constant lane: the SGPR spilled to that + /// lane, found by following the VGPR's `v_writelane_b32` writes. + fn restored(&self, inst: &Inst) -> Option { + let Fields::Valu(v) = &inst.fields else { + return None; + }; + if inst.name() != "v_readlane_b32" { + return None; + } + let [Operand::Vector { reg, .. }, lane] = v.src[..] else { + return None; + }; + self.spilled(inst.read(Reg::V(reg))?, lane_of(lane)?, &mut Vec::new()) + .ok() + .flatten() + } + + /// What lane `lane` of VGPR value `v` holds: `Ok(None)` for a phi in + /// `seen` (already being resolved), `Err` if not a spilled SGPR. + fn spilled(&self, v: Value, lane: u32, seen: &mut Vec) -> Result, ()> { + if let Some((b, i)) = self.phis[v.0 as usize] { + if seen.contains(&v) { + return Ok(None); + } + seen.push(v); + let mut found = None; + for &a in &self.p.blocks[b].phis[i].args { + if let Some(m) = self.spilled(a, lane, seen)? { + if found.is_some_and(|f| f != m) { + return Err(()); + } + found = Some(m); + } + } + return Ok(found); + } + let inst = self.def(v).ok_or(())?; + let Fields::Valu(w) = &inst.fields else { + return Err(()); + }; + let (Some(Operand::Vector { reg, .. }), [value, at]) = (w.dst, &w.src[..]) else { + return Err(()); + }; + if inst.name() != "v_writelane_b32" { + return Err(()); + } + if lane_of(*at).ok_or(())? != lane { + return self.spilled(inst.read(Reg::V(reg)).ok_or(())?, lane, seen); + } + match *value { + Operand::Scalar { code, .. } if code != NULL => { + inst.read(Reg::S(code)).map(Moved::Value) + } + Operand::Literal(x) => Some(Moved::Const(x)), + Operand::Const(c) => inline(c).map(Moved::Const), + _ => None, + } + .map(Some) + .ok_or(()) + } +} + +/// A lane select given as a constant. +fn lane_of(op: Operand) -> Option { + match op { + Operand::Const(c) => inline(c), + Operand::Literal(x) => Some(x), + _ => None, + } +} + +/// What dword `k` of a move's result copies. +fn copy_source(inst: &Inst, k: usize) -> Option { + let Fields::Sop { src, imm, .. } = &inst.fields else { + return None; + }; + if inst.name() == "s_movk_i32" { + return Some(Moved::Const(i32::from((*imm)? as i16) as u32)); + } + let src = src.first()?; + match (inst.name(), *src) { + ("s_mov_b32" | "s_mov_b64", Operand::Scalar { code, .. }) if code != NULL => { + inst.read(Reg::S(code + k as u8)).map(Moved::Value) + } + ("s_mov_b32" | "s_mov_b64", Operand::Scalar { .. }) => Some(Moved::Const(0)), + ("s_mov_b32", Operand::Literal(x)) => Some(Moved::Const(x)), + ("s_mov_b32", Operand::Const(c)) => inline(c).map(Moved::Const), + // shortcut: only the one-operand ways the compiler makes a constant + // that has no inline form; fold more if descriptors need it. + ("s_brev_b32", Operand::Const(c)) => inline(c).map(|x| Moved::Const(x.reverse_bits())), + ("s_not_b32", Operand::Const(c)) => inline(c).map(|x| Moved::Const(!x)), + // 64-bit inline integers are sign-extended. + ("s_mov_b64", Operand::Const(c @ 128..=208)) => { + let low = inline(c)?; + Some(Moved::Const(if k == 0 { + low + } else { + ((low as i32) >> 31) as u32 + })) + } + _ => None, + } +} + +/// The 32-bit value of an inline constant operand. +pub(crate) fn inline(code: u8) -> Option { + let float = |f: f32| Some(f.to_bits()); + match code { + 128..=192 => Some(u32::from(code) - 128), + 193..=208 => Some((192 - i32::from(code)) as u32), + 240 => float(0.5), + 241 => float(-0.5), + 242 => float(1.0), + 243 => float(-1.0), + 244 => float(2.0), + 245 => float(-2.0), + 246 => float(4.0), + 247 => float(-4.0), + 248 => Some(0x3E22_F983), + _ => None, + } +} + +#[cfg(test)] +pub(crate) mod tests { + use super::*; + use crate::native::RootType::*; + + const S_ENDPGM: u32 = 0xBF81_0000; + + fn track_words(words: &[u32], layout: &[RootParam], stage: HwStage) -> Resources { + let code: Vec = words.iter().flat_map(|w| w.to_le_bytes()).collect(); + let p = crate::ir::build(&code, false, 256).unwrap(); + track(&p, layout, stage, lanes(&p).as_ref()).unwrap() + } + + /// `p` as one lane runs it, if it structures. + fn lanes(p: &Program) -> Option { + crate::structure::structure(p).ok() + } + + fn param(root: RootType, user_data: u8, sgprs: u32) -> RootParam { + RootParam { + root, + table_offset_dwords: 0, + sgprs, + base_register: 0, + user_data, + slot: 0, + } + } + + fn at(param: usize, offset: u32) -> Address { + Address { + param, + offset, + dynamic: None, + } + } + + #[test] + fn table_descriptors_are_loaded_from_their_range() { + let r = track_words( + &[ + 0xBE82_0309, // s_mov_b32 s2, s9 + 0xBE89_0380, // s_mov_b32 s9, 0 + 0xBE83_0380, // s_mov_b32 s3, 0 + 0xF408_0204, + 0xFA00_0000, // s_load_dwordx4 s[8:11], s[8:9], null + 0xF40C_0001, + 0xFA00_0000, // s_load_dwordx8 s[0:7], s[2:3], null + 0xF080_0F08, + 0x0040_0002, // image_sample v[0:3], v[2:3], s[0:7], s[8:11] + S_ENDPGM, + ], + &[param(Table, 8, 1), param(Table, 9, 1)], + HwStage::Ps, + ); + assert_eq!(r.scalar, [((0, 3), at(0, 0)), ((0, 4), at(1, 0))]); + let roles: Vec<_> = r.descriptors.iter().map(|d| (d.role, &d.source)).collect(); + assert_eq!( + roles, + [ + ( + Role::Resource, + &Source::Loaded { + load: (0, 4), + first: 0 + } + ), + ( + Role::Sampler, + &Source::Loaded { + load: (0, 3), + first: 0 + } + ), + ] + ); + } + + #[test] + fn root_descriptors_are_built_in_code() { + let r = track_words( + &[ + 0x8801_FF0B, + 0x0010_0000, // s_or_b32 s1, s11, 0x100000 + 0xBE80_030A, // s_mov_b32 s0, s10 + 0xBE82_03C1, // s_mov_b32 s2, -1 + 0xBE83_03FF, + 0x1101_4FAC, // s_mov_b32 s3, 0x11014fac + 0xF430_0000, + 0xFA00_0000, // s_buffer_load_dwordx16 s[0:15], s[0:3], null + S_ENDPGM, + ], + &[param(Descriptor, 10, 2)], + HwStage::Vs, + ); + assert_eq!( + r.descriptors[0].source, + Source::Built { + address: at(0, 0), + bits: 0x10_0000, + words: [u32::MAX, 0x1101_4FAC] + } + ); + assert_eq!( + r.params.iter().map(|p| (p.1, p.2)).collect::>(), + [(0, 0), (0, 1)] + ); + } + + #[test] + fn heap_indices_from_root_constants_in_a_merged_stage() { + // User data starts at s8: the constant (index 6) is s14, the heap + // (index 10) s18. + let code = [ + 0x8F08_850E, // s_lshl_b32 s8, s14, 5 + 0xBE93_0380, // s_mov_b32 s19, 0 + 0xF408_0209, + 0x1000_0000, // s_load_dwordx4 s[8:11], s[18:19], s8 + 0xE000_2000, + 0x8002_0400, // buffer_load_format_x v4, v0, s[8:11], 0 idxen + S_ENDPGM, + ]; + let r = track_words( + &code, + &[param(Constants, 6, 1), param(ResourceHeap, 10, 1)], + HwStage::Ms, + ); + let index = r.params.iter().find(|p| p.1 == 0).unwrap().0; + let shift = r.scalar[0].1.dynamic.unwrap(); + assert_eq!(r.scalar[0].1.param, 1); + // The computed term is the shifted constant, not the constant itself. + assert_ne!(shift, index); + assert_eq!( + r.descriptors[0].source, + Source::Loaded { + load: (0, 2), + first: 0 + } + ); + assert!(r.root_indexed_views.is_empty()); + let table = RootParam { + slot: 7, + ..param(Table, 10, 1) + }; + let indexed = track_words(&code, &[param(Constants, 6, 1), table], HwStage::Ms); + assert_eq!( + indexed.root_indexed_views, + [RootIndexedView { + table_slot: 7, + constant_slot: 0, + constant_dword: 0, + byte_offset: 0, + shift: 5, + }] + ); + let nonconstant = track_words(&code, &[param(Table, 6, 1), table], HwStage::Ms); + assert!(nonconstant.root_indexed_views.is_empty()); + } + + #[test] + fn spilled_sgprs_are_followed_through_vgpr_lanes() { + let r = track_words( + &[ + 0xD761_0000, + 0x0001_0609, // v_writelane_b32 v0, s9, 3 + 0xD760_0002, + 0x0001_0700, // v_readlane_b32 s2, v0, 3 + 0xBE83_0380, // s_mov_b32 s3, 0 + 0xF40C_0001, + 0xFA00_0020, // s_load_dwordx8 s[0:7], s[2:3], 0x20 + S_ENDPGM, + ], + &[param(Table, 9, 1)], + HwStage::Ps, + ); + assert_eq!(r.scalar, [((0, 3), at(0, 0x20))]); + } + + #[test] + fn descriptors_joined_by_control_flow_are_traced_per_edge() { + let r = track_words( + &[ + 0xBE82_0309, // s_mov_b32 s2, s9 + 0xBE83_0380, // s_mov_b32 s3, 0 + 0xBF06_8001, // s_cmp_eq_u32 s1, 0 + 0xBF85_0003, // s_cbranch_scc1 -> 0x1c + 0xF408_0001, + 0xFA00_0000, // s_load_dwordx4 s[0:3], s[2:3], null + 0xBF82_0002, // s_branch -> 0x24 + 0xF408_0001, + 0xFA00_0010, // 0x1c: s_load_dwordx4 s[0:3], s[2:3], 0x10 + 0xF420_0100, + 0xFA00_0000, // 0x24: s_buffer_load_dword s4, s[0:3], null + S_ENDPGM, + ], + &[param(Table, 9, 1)], + HwStage::Ps, + ); + let Source::Phi { args, .. } = &r.descriptors[0].source else { + panic!("{:?}", r.descriptors) + }; + let offsets: Vec<_> = args + .iter() + .map(|a| match a { + Source::Loaded { load, .. } => { + r.scalar.iter().find(|s| s.0 == *load).unwrap().1.offset + } + a => panic!("{a:?}"), + }) + .collect(); + assert_eq!(offsets.len(), 2); + assert!( + offsets.contains(&0) && offsets.contains(&0x10), + "{offsets:?}" + ); + } + + /// Two paths add an index to one table in the code and meet before one load + /// (hair `CS_InterpolateStrands`): the join is the computed term, counted + /// from the `s_getpc_b64`. + #[test] + fn two_paths_into_one_code_table_load() { + let r = track_words( + &[ + 0xBE82_1F00, // 0x00: s_getpc_b64 s[2:3] + 0x8002_FF02, + 0x0000_0040, // s_add_u32 s2, s2, 0x40 + 0x8203_8003, // s_addc_u32 s3, s3, 0 + 0xBF06_8001, // 0x10: s_cmp_eq_u32 s1, 0 + 0xBF85_0005, // 0x14: s_cbranch_scc1 -> 0x2c + 0xD70F_0457, + 0x0000_054A, // 0x18: v_add_co_u32 v87, s4, v74, s2 + 0xD528_0458, + 0x0010_0680, // v_add_co_ci_u32 v88, s4, 0, s3, s4 + 0xBF82_0004, // 0x28: s_branch -> 0x3c + 0xD70F_0457, + 0x0000_054B, // 0x2c: v_add_co_u32 v87, s4, v75, s2 + 0xD528_0458, + 0x0010_0680, // v_add_co_ci_u32 v88, s4, 0, s3, s4 + 0xDC34_8000, + 0x577D_0057, // 0x3c: global_load_dwordx2 v[87:88], v[87:88], null + S_ENDPGM, + ], + &[], + HwStage::Cs, + ); + assert_eq!(r.scalar.len(), 1); + let a = r.scalar[0].1; + assert_eq!((a.param, a.offset), (CODE, 0)); + assert!(a.dynamic.is_some(), "the join is the computed term, the byte in the code"); + } + + /// An address into a table in the code computed per lane and taken from + /// the first lane (`avgLuminanceCompute` `ColorDownsample`): the per-lane + /// sum carries the `s_getpc_b64` base, so the first-lane read is looked + /// through and the lane's index is the computed term. (A first-lane read + /// of an index alone stays the computed term itself; see + /// `the_console_waterfall_over_a_first_lane_offset_is_one`.) + #[test] + fn a_code_table_address_taken_from_the_first_lane() { + let r = track_words( + &[ + 0xBE82_1F00, // 0x00: s_getpc_b64 s[2:3] + 0xD70F_0457, + 0x0000_054A, // v_add_co_u32 v87, s4, v74, s2 + 0xD528_0458, + 0x0010_0680, // v_add_co_ci_u32 v88, s4, 0, s3, s4 + 0x7E0C_0557, // v_readfirstlane_b32 s6, v87 + 0x7E0E_0558, // v_readfirstlane_b32 s7, v88 + 0xF400_0203, + 0xFA00_0000, // s_load_dword s8, s[6:7], 0x0 + S_ENDPGM, + ], + &[], + HwStage::Cs, + ); + assert_eq!(r.scalar.len(), 1); + let a = r.scalar[0].1; + assert_eq!((a.param, a.offset), (CODE, 4)); + assert!(a.dynamic.is_some(), "the lane's index is the computed term"); + } + + #[test] + fn a_descriptor_kept_per_lane_is_its_load_and_needs_no_waterfall() { + // The console compiler's way with a descriptor it joins per lane: + // the dwords go to VGPRs and come back from the first lane. Every + // lane holds the one load's dwords, so the descriptor is that load + // (`lane_copied`), and no waterfall is asked for. + let mut words = vec![ + 0xBE82_0309, // s_mov_b32 s2, s9 + 0xBE83_0380, // s_mov_b32 s3, 0 + 0xF40C_0001, + 0xFA00_0000, // s_load_dwordx8 s[0:7], s[2:3], null + ]; + // v_mov_b32 v10.., s0..; v_readfirstlane_b32 s16.., v10.. + words.extend((0..8).map(|k| 0x7E00_0200 | (10 + k) << 17 | k)); + words.extend((0..8).map(|k| 0x7E00_0400 | (16 + k) << 17 | (0x100 + 10 + k))); + words.extend([ + 0xF000_1700, + 0x0004_0D06, // image_load v[13:15], v6, s[16:23] + S_ENDPGM, + ]); + let r = track_words(&words, &[param(Table, 9, 1)], HwStage::Ps); + let load = (0, 2); + assert_eq!(r.scalar, [(load, at(0, 0))]); + let sources: Vec<_> = r.descriptors.iter().map(|d| &d.source).collect(); + assert_eq!(sources, [&Source::Loaded { load, first: 0 }]); + assert_eq!(r.lane_copied, [load]); + assert_eq!(r.waterfall, Waterfall::default()); + } + + #[test] + fn loads_at_one_first_lane_offset_have_one_address() { + // Two loads of the table entry at the offset v4 holds, each with + // its own first-lane read, as the console compiler loads a + // descriptor again wherever it needs it: one address, by which + // lowering knows them for the same descriptor. + let r = track_words( + &[ + 0xBE82_0309, // s_mov_b32 s2, s9 + 0xBE83_0380, // s_mov_b32 s3, 0 + 0x7E08_0504, // v_readfirstlane_b32 s4, v4 + 0xF40C_0201, + 0x0800_0000, // s_load_dwordx8 s[8:15], s[2:3], s4 + 0x7E0A_0504, // v_readfirstlane_b32 s5, v4 + 0xF40C_0401, + 0x0A00_0000, // s_load_dwordx8 s[16:23], s[2:3], s5 + 0xF000_1700, + 0x0004_0D06, // image_load v[13:15], v6, s[16:23] + S_ENDPGM, + ], + &[param(Table, 9, 1)], + HwStage::Ps, + ); + let [(_, a), (_, b)] = r.scalar[..] else { + panic!("{:?}", r.scalar) + }; + assert_eq!(a, b); + assert_eq!((a.param, a.offset), (0, 0)); + assert!( + a.dynamic.is_some(), + "the lane's offset is the computed term" + ); + } + + #[test] + fn descriptors_selected_by_scc_are_traced_per_outcome() { + // Two buffer descriptors loaded from the table at s9 and one + // picked with s_cselect_b64 per half, as the compiler makes a + // conditional choice of resources without a branch. + let r = track_words( + &[ + 0xBE8C_0309, // s_mov_b32 s12, s9 + 0xBE8D_0380, // s_mov_b32 s13, 0 + 0xF408_0006, + 0xFA00_0000, // s_load_dwordx4 s[0:3], s[12:13], null + 0xF408_0106, + 0xFA00_0010, // s_load_dwordx4 s[4:7], s[12:13], 0x10 + 0xBF06_800E, // s_cmp_eq_u32 s14, 0 + 0x8588_0400, // s_cselect_b64 s[8:9], s[0:1], s[4:5] + 0x858A_0602, // s_cselect_b64 s[10:11], s[2:3], s[6:7] + 0xF420_0404, + 0xFA00_0000, // s_buffer_load_dword s16, s[8:11], null + S_ENDPGM, + ], + &[param(Table, 9, 1)], + HwStage::Ps, + ); + let Source::Select { args, .. } = &r.descriptors[0].source else { + panic!("{:?}", r.descriptors) + }; + // SCC set picks the first operand. + assert_eq!( + args[..], + [ + Source::Loaded { + load: (0, 2), + first: 0 + }, + Source::Loaded { + load: (0, 3), + first: 0 + }, + ] + ); + assert_eq!(r.scalar, [((0, 2), at(0, 0)), ((0, 3), at(0, 0x10))]); + } + + #[test] + fn a_selection_that_mixes_two_descriptors_fails() { + // The high half picked from the first load whatever SCC is: when + // clear, the descriptor is half of one load and half of the other. + let code: Vec = [ + 0xBE8C_0309, // s_mov_b32 s12, s9 + 0xBE8D_0380, // s_mov_b32 s13, 0 + 0xF408_0006, + 0xFA00_0000, // s_load_dwordx4 s[0:3], s[12:13], null + 0xF408_0106, + 0xFA00_0010, // s_load_dwordx4 s[4:7], s[12:13], 0x10 + 0xBF06_800E, // s_cmp_eq_u32 s14, 0 + 0x8588_0400, // s_cselect_b64 s[8:9], s[0:1], s[4:5] + 0x858A_0202, // s_cselect_b64 s[10:11], s[2:3], s[2:3] + 0xF420_0404, + 0xFA00_0000, // s_buffer_load_dword s16, s[8:11], null + S_ENDPGM, + ] + .iter() + .flat_map(|w: &u32| w.to_le_bytes()) + .collect(); + let p = crate::ir::build(&code, false, 256).unwrap(); + let err = track(&p, &[param(Table, 9, 1)], HwStage::Ps, lanes(&p).as_ref()).unwrap_err(); + assert_eq!( + err, + ShaderError::Unsupported { + offset: 36, + what: "a descriptor changed after loading" + } + ); + } + + #[test] + fn untraceable_addresses_fail_with_a_reason() { + let code: Vec = [0xF408_0001, 0xFA00_0000, S_ENDPGM] // s_load_dwordx4 s[0:3], s[2:3] + .iter() + .flat_map(|w: &u32| w.to_le_bytes()) + .collect(); + let p = crate::ir::build(&code, false, 256).unwrap(); + let err = track(&p, &[param(Table, 9, 1)], HwStage::Ps, lanes(&p).as_ref()).unwrap_err(); + assert_eq!( + err, + ShaderError::Unsupported { + offset: 0, + what: "an address in an SGPR that is no root parameter" + } + ); + } + + /// A waterfall loop over an image descriptor each lane loads from the + /// table at s0 (wave32, assembled with llvm-mc for gfx1030): lane i + /// reads entry i with two `global_load_dwordx4`, the loop reads the + /// first active lane's descriptor into s[12:19], samples with the lanes + /// whose descriptor it is, and repeats for the others. The sampler comes + /// from the table at s1; the result goes to LDS so the sample is needed. + pub(crate) const WATERFALL_FETCHED_WAVE32: &[u32] = &[ + 0xBE84_0300, // s_mov_b32 s4, s0 + 0xBE85_0380, // s_mov_b32 s5, 0 + 0xBE86_0301, // s_mov_b32 s6, s1 + 0xBE87_0380, // s_mov_b32 s7, 0 + 0x3402_0085, // v_lshlrev_b32 v1, 5, v0 + 0xDC38_8000, + 0x0404_0001, // global_load_dwordx4 v[4:7], v1, s[4:5] + 0xDC38_8010, + 0x0804_0001, // global_load_dwordx4 v[8:11], v1, s[4:5] offset:16 + 0xF408_0203, + 0xFA00_0000, // s_load_dwordx4 s[8:11], s[6:7], 0x0 + 0x7E04_0D00, // v_cvt_f32_u32 v2, v0 + 0x7E06_0302, // v_mov_b32 v3, v2 + 0xBF8C_0070, // s_waitcnt vmcnt(0) lgkmcnt(0) + 0xBE94_037E, // s_mov_b32 s20, exec_lo + 0x7E18_0504, // 0x3c: v_readfirstlane_b32 s12, v4 + 0x7E1A_0505, // v_readfirstlane_b32 s13, v5 + 0x7E1C_0506, // v_readfirstlane_b32 s14, v6 + 0x7E1E_0507, // v_readfirstlane_b32 s15, v7 + 0x7E20_0508, // v_readfirstlane_b32 s16, v8 + 0x7E22_0509, // v_readfirstlane_b32 s17, v9 + 0x7E24_050A, // v_readfirstlane_b32 s18, v10 + 0x7E26_050B, // v_readfirstlane_b32 s19, v11 + 0xD4E2_0015, + 0x0002_080C, // v_cmp_eq_u64_e64 s21, s[12:13], v[4:5] + 0xD4E2_0016, + 0x0002_0C0E, // v_cmp_eq_u64_e64 s22, s[14:15], v[6:7] + 0x8715_1615, // s_and_b32 s21, s21, s22 + 0xD4E2_0016, + 0x0002_1010, // v_cmp_eq_u64_e64 s22, s[16:17], v[8:9] + 0x8715_1615, // s_and_b32 s21, s21, s22 + 0xD4E2_0016, + 0x0002_1412, // v_cmp_eq_u64_e64 s22, s[18:19], v[10:11] + 0x8715_1615, // s_and_b32 s21, s21, s22 + 0xBE95_3C15, // s_and_saveexec_b32 s21, s21 + 0xBF80_0000, // s_nop 0 + 0xF09C_0F08, + 0x0043_0C02, // image_sample_lz v[12:15], v[2:3], s[12:19], s[8:11] dmask:0xf dim:SQ_RSRC_IMG_2D + 0xBF8C_3F70, // s_waitcnt vmcnt(0) + 0x897E_157E, // s_xor_b32 exec_lo, exec_lo, s21 + 0xBF89_FFE6, // s_cbranch_execnz -> 0x3c + 0xBEFE_0314, // s_mov_b32 exec_lo, s20 + 0xD834_0000, + 0x0000_0C00, // ds_write_b32 v0, v12 + 0xBF81_0000, // s_endpgm + ]; + + /// [`WATERFALL_FETCHED_WAVE32`] in wave64: 64-bit lane masks. + pub(crate) const WATERFALL_FETCHED_WAVE64: &[u32] = &[ + 0xBE84_0300, // s_mov_b32 s4, s0 + 0xBE85_0380, // s_mov_b32 s5, 0 + 0xBE86_0301, // s_mov_b32 s6, s1 + 0xBE87_0380, // s_mov_b32 s7, 0 + 0x3402_0085, // v_lshlrev_b32 v1, 5, v0 + 0xDC38_8000, + 0x0404_0001, // global_load_dwordx4 v[4:7], v1, s[4:5] + 0xDC38_8010, + 0x0804_0001, // global_load_dwordx4 v[8:11], v1, s[4:5] offset:16 + 0xF408_0203, + 0xFA00_0000, // s_load_dwordx4 s[8:11], s[6:7], 0x0 + 0x7E04_0D00, // v_cvt_f32_u32 v2, v0 + 0x7E06_0302, // v_mov_b32 v3, v2 + 0xBF8C_0070, // s_waitcnt vmcnt(0) lgkmcnt(0) + 0xBE94_047E, // s_mov_b64 s[20:21], exec + 0x7E18_0504, // 0x3c: v_readfirstlane_b32 s12, v4 + 0x7E1A_0505, // v_readfirstlane_b32 s13, v5 + 0x7E1C_0506, // v_readfirstlane_b32 s14, v6 + 0x7E1E_0507, // v_readfirstlane_b32 s15, v7 + 0x7E20_0508, // v_readfirstlane_b32 s16, v8 + 0x7E22_0509, // v_readfirstlane_b32 s17, v9 + 0x7E24_050A, // v_readfirstlane_b32 s18, v10 + 0x7E26_050B, // v_readfirstlane_b32 s19, v11 + 0xD4E2_0016, + 0x0002_080C, // v_cmp_eq_u64_e64 s[22:23], s[12:13], v[4:5] + 0xD4E2_0018, + 0x0002_0C0E, // v_cmp_eq_u64_e64 s[24:25], s[14:15], v[6:7] + 0x8796_1816, // s_and_b64 s[22:23], s[22:23], s[24:25] + 0xD4E2_0018, + 0x0002_1010, // v_cmp_eq_u64_e64 s[24:25], s[16:17], v[8:9] + 0x8796_1816, // s_and_b64 s[22:23], s[22:23], s[24:25] + 0xD4E2_0018, + 0x0002_1412, // v_cmp_eq_u64_e64 s[24:25], s[18:19], v[10:11] + 0x8796_1816, // s_and_b64 s[22:23], s[22:23], s[24:25] + 0xBE96_2416, // s_and_saveexec_b64 s[22:23], s[22:23] + 0xBF80_0000, // s_nop 0 + 0xF09C_0F08, + 0x0043_0C02, // image_sample_lz v[12:15], v[2:3], s[12:19], s[8:11] dmask:0xf dim:SQ_RSRC_IMG_2D + 0xBF8C_3F70, // s_waitcnt vmcnt(0) + 0x89FE_167E, // s_xor_b64 exec, exec, s[22:23] + 0xBF89_FFE6, // s_cbranch_execnz -> 0x3c + 0xBEFE_0414, // s_mov_b64 exec, s[20:21] + 0xD834_0000, + 0x0000_0C00, // ds_write_b32 v0, v12 + 0xBF81_0000, // s_endpgm + ]; + + /// The same waterfall over one of two image descriptors loaded from the + /// table at s0, picked per lane by `v_cndmask_b32` (lanes below 16 take + /// the first). + pub(crate) const WATERFALL_PICKED_WAVE32: &[u32] = &[ + 0xBE84_0300, // s_mov_b32 s4, s0 + 0xBE85_0380, // s_mov_b32 s5, 0 + 0xBE86_0301, // s_mov_b32 s6, s1 + 0xBE87_0380, // s_mov_b32 s7, 0 + 0xF40C_0602, + 0xFA00_0000, // s_load_dwordx8 s[24:31], s[4:5], 0x0 + 0xF40C_0802, + 0xFA00_0020, // s_load_dwordx8 s[32:39], s[4:5], 0x20 + 0xF408_0203, + 0xFA00_0000, // s_load_dwordx4 s[8:11], s[6:7], 0x0 + 0x7E04_0D00, // v_cvt_f32_u32 v2, v0 + 0x7E06_0302, // v_mov_b32 v3, v2 + 0x7D88_0090, // v_cmp_gt_u32 vcc_lo, 16, v0 + 0xBF8C_C07F, // s_waitcnt lgkmcnt(0) + 0x7E08_0218, // v_mov_b32 v4, s24 + 0x0208_0820, // v_cndmask_b32 v4, s32, v4, vcc_lo + 0x7E0A_0219, // v_mov_b32 v5, s25 + 0x020A_0A21, // v_cndmask_b32 v5, s33, v5, vcc_lo + 0x7E0C_021A, // v_mov_b32 v6, s26 + 0x020C_0C22, // v_cndmask_b32 v6, s34, v6, vcc_lo + 0x7E0E_021B, // v_mov_b32 v7, s27 + 0x020E_0E23, // v_cndmask_b32 v7, s35, v7, vcc_lo + 0x7E10_021C, // v_mov_b32 v8, s28 + 0x0210_1024, // v_cndmask_b32 v8, s36, v8, vcc_lo + 0x7E12_021D, // v_mov_b32 v9, s29 + 0x0212_1225, // v_cndmask_b32 v9, s37, v9, vcc_lo + 0x7E14_021E, // v_mov_b32 v10, s30 + 0x0214_1426, // v_cndmask_b32 v10, s38, v10, vcc_lo + 0x7E16_021F, // v_mov_b32 v11, s31 + 0x0216_1627, // v_cndmask_b32 v11, s39, v11, vcc_lo + 0xBE94_037E, // s_mov_b32 s20, exec_lo + 0x7E18_0504, // 0x7c: v_readfirstlane_b32 s12, v4 + 0x7E1A_0505, // v_readfirstlane_b32 s13, v5 + 0x7E1C_0506, // v_readfirstlane_b32 s14, v6 + 0x7E1E_0507, // v_readfirstlane_b32 s15, v7 + 0x7E20_0508, // v_readfirstlane_b32 s16, v8 + 0x7E22_0509, // v_readfirstlane_b32 s17, v9 + 0x7E24_050A, // v_readfirstlane_b32 s18, v10 + 0x7E26_050B, // v_readfirstlane_b32 s19, v11 + 0xD4E2_0015, + 0x0002_080C, // v_cmp_eq_u64_e64 s21, s[12:13], v[4:5] + 0xD4E2_0016, + 0x0002_0C0E, // v_cmp_eq_u64_e64 s22, s[14:15], v[6:7] + 0x8715_1615, // s_and_b32 s21, s21, s22 + 0xD4E2_0016, + 0x0002_1010, // v_cmp_eq_u64_e64 s22, s[16:17], v[8:9] + 0x8715_1615, // s_and_b32 s21, s21, s22 + 0xD4E2_0016, + 0x0002_1412, // v_cmp_eq_u64_e64 s22, s[18:19], v[10:11] + 0x8715_1615, // s_and_b32 s21, s21, s22 + 0xBE95_3C15, // s_and_saveexec_b32 s21, s21 + 0xBF80_0000, // s_nop 0 + 0xF09C_0F08, + 0x0043_0C02, // image_sample_lz v[12:15], v[2:3], s[12:19], s[8:11] dmask:0xf dim:SQ_RSRC_IMG_2D + 0xBF8C_3F70, // s_waitcnt vmcnt(0) + 0x897E_157E, // s_xor_b32 exec_lo, exec_lo, s21 + 0xBF89_FFE6, // s_cbranch_execnz -> 0x7c + 0xBEFE_0314, // s_mov_b32 exec_lo, s20 + 0xD834_0000, + 0x0000_0C00, // ds_write_b32 v0, v12 + 0xBF81_0000, // s_endpgm + ]; + + /// The waterfall loop of [`WATERFALL_PICKED_WAVE32`] over one of two + /// image descriptors loaded from the table at s0, chosen by control flow + /// as the compiler lowers an if/else on a per-lane condition: lanes below + /// 16 move the first into v[4:11], the others the second, each arm + /// skipped when no lane takes it. The sample goes to the buffer at dword + /// 16 of the table, at lane * 4. + pub(crate) const WATERFALL_JOINED_WAVE32: &[u32] = &[ + 0xBE84_0300, // s_mov_b32 s4, s0 + 0xBE85_0380, // s_mov_b32 s5, 0 + 0xBE86_0301, // s_mov_b32 s6, s1 + 0xBE87_0380, // s_mov_b32 s7, 0 + 0xF40C_0602, + 0xFA00_0000, // s_load_dwordx8 s[24:31], s[4:5], 0x0 + 0xF40C_0802, + 0xFA00_0020, // s_load_dwordx8 s[32:39], s[4:5], 0x20 + 0xF408_0203, + 0xFA00_0000, // s_load_dwordx4 s[8:11], s[6:7], 0x0 + 0xF408_0A02, + 0xFA00_0040, // s_load_dwordx4 s[40:43], s[4:5], 0x40 + 0x7E04_0D00, // v_cvt_f32_u32 v2, v0 + 0x7E06_0302, // v_mov_b32 v3, v2 + 0x3420_0082, // v_lshlrev_b32 v16, 2, v0 + 0x7D88_0090, // v_cmp_gt_u32 vcc_lo, 16, v0 + 0xBF8C_C07F, // s_waitcnt lgkmcnt(0) + 0xBE94_3C6A, // s_and_saveexec_b32 s20, vcc_lo + 0x8914_147E, // s_xor_b32 s20, exec_lo, s20 + 0xBF88_0008, // s_cbranch_execz -> 0x70 + 0x7E08_0218, // v_mov_b32 v4, s24 + 0x7E0A_0219, // v_mov_b32 v5, s25 + 0x7E0C_021A, // v_mov_b32 v6, s26 + 0x7E0E_021B, // v_mov_b32 v7, s27 + 0x7E10_021C, // v_mov_b32 v8, s28 + 0x7E12_021D, // v_mov_b32 v9, s29 + 0x7E14_021E, // v_mov_b32 v10, s30 + 0x7E16_021F, // v_mov_b32 v11, s31 + 0xBE94_3D14, // 0x70: s_or_saveexec_b32 s20, s20 + 0x897E_147E, // s_xor_b32 exec_lo, exec_lo, s20 + 0xBF88_0008, // s_cbranch_execz -> 0x9c + 0x7E08_0220, // v_mov_b32 v4, s32 + 0x7E0A_0221, // v_mov_b32 v5, s33 + 0x7E0C_0222, // v_mov_b32 v6, s34 + 0x7E0E_0223, // v_mov_b32 v7, s35 + 0x7E10_0224, // v_mov_b32 v8, s36 + 0x7E12_0225, // v_mov_b32 v9, s37 + 0x7E14_0226, // v_mov_b32 v10, s38 + 0x7E16_0227, // v_mov_b32 v11, s39 + 0x887E_147E, // 0x9c: s_or_b32 exec_lo, exec_lo, s20 + 0xBE97_037E, // s_mov_b32 s23, exec_lo + 0x7E18_0504, // 0xa4: v_readfirstlane_b32 s12, v4 + 0x7E1A_0505, // v_readfirstlane_b32 s13, v5 + 0x7E1C_0506, // v_readfirstlane_b32 s14, v6 + 0x7E1E_0507, // v_readfirstlane_b32 s15, v7 + 0x7E20_0508, // v_readfirstlane_b32 s16, v8 + 0x7E22_0509, // v_readfirstlane_b32 s17, v9 + 0x7E24_050A, // v_readfirstlane_b32 s18, v10 + 0x7E26_050B, // v_readfirstlane_b32 s19, v11 + 0xD4E2_0015, + 0x0002_080C, // v_cmp_eq_u64_e64 s21, s[12:13], v[4:5] + 0xD4E2_0016, + 0x0002_0C0E, // v_cmp_eq_u64_e64 s22, s[14:15], v[6:7] + 0x8715_1615, // s_and_b32 s21, s21, s22 + 0xD4E2_0016, + 0x0002_1010, // v_cmp_eq_u64_e64 s22, s[16:17], v[8:9] + 0x8715_1615, // s_and_b32 s21, s21, s22 + 0xD4E2_0016, + 0x0002_1412, // v_cmp_eq_u64_e64 s22, s[18:19], v[10:11] + 0x8715_1615, // s_and_b32 s21, s21, s22 + 0xBE95_3C15, // s_and_saveexec_b32 s21, s21 + 0xBF80_0000, // s_nop 0 + 0xF09C_0F08, + 0x0043_0C02, // image_sample_lz v[12:15], v[2:3], s[12:19], s[8:11] dmask:0xf dim:SQ_RSRC_IMG_2D + 0xBF8C_3F70, // s_waitcnt vmcnt(0) + 0x897E_157E, // s_xor_b32 exec_lo, exec_lo, s21 + 0xBF89_FFE6, // s_cbranch_execnz -> 0xa4 + 0xBEFE_0317, // s_mov_b32 exec_lo, s23 + 0xE070_1000, + 0x800A_0C10, // buffer_store_dword v12, v16, s[40:43], 0 offen + 0xBF81_0000, // s_endpgm + ]; + + /// The console compiler's waterfall (the title's ray-tracing + /// resolve and others): each lane holds its entry's byte offset in the + /// table at s0 (v7 = (lane & 1) * 32); the loop reads the first active + /// lane's offset, narrows EXEC to the lanes with the same one + /// (`v_cmpx_eq_u32`), loads that entry with `s_load_dwordx8` and samples, + /// then drops those lanes (`s_andn2_wrexec_b32`). The sample goes to the + /// buffer at dword 16 of the table, at lane * 4. + pub(crate) const WATERFALL_INDEXED_WAVE32: &[u32] = &[ + 0xBE84_0300, // s_mov_b32 s4, s0 + 0xBE85_0380, // s_mov_b32 s5, 0 + 0xBE86_0301, // s_mov_b32 s6, s1 + 0xBE87_0380, // s_mov_b32 s7, 0 + 0xF408_0203, + 0xFA00_0000, // s_load_dwordx4 s[8:11], s[6:7], 0x0 + 0xF408_0A02, + 0xFA00_0040, // s_load_dwordx4 s[40:43], s[4:5], 0x40 + 0x7E04_0D00, // v_cvt_f32_u32 v2, v0 + 0x7E06_0302, // v_mov_b32 v3, v2 + 0x3420_0082, // v_lshlrev_b32 v16, 2, v0 + 0x360E_0081, // v_and_b32 v7, 1, v0 + 0x340E_0E85, // v_lshlrev_b32 v7, 5, v7 + 0xBF8C_C07F, // s_waitcnt lgkmcnt(0) + 0xBE97_037E, // s_mov_b32 s23, exec_lo + 0xBE95_037E, // s_mov_b32 s21, exec_lo + 0x7E28_0507, // 0x40: v_readfirstlane_b32 s20, v7 + 0x7DA4_0E14, // v_cmpx_eq_u32 exec_lo, s20, v7 + 0xF40C_0302, + 0x2800_0000, // s_load_dwordx8 s[12:19], s[4:5], s20 + 0xBF8C_C07F, // s_waitcnt lgkmcnt(0) + 0xF09C_0F08, + 0x0043_0C02, // image_sample_lz v[12:15], v[2:3], s[12:19], s[8:11] dmask:0xf dim:SQ_RSRC_IMG_2D + 0xBF8C_3F70, // s_waitcnt vmcnt(0) + 0xBE95_4715, // s_andn2_wrexec_b32 s21, s21 + 0xBF89_FFF6, // s_cbranch_execnz -> 0x40 + 0xBEFE_0317, // s_mov_b32 exec_lo, s23 + 0xE070_1000, + 0x800A_0C10, // buffer_store_dword v12, v16, s[40:43], 0 offen + 0xBF81_0000, // s_endpgm + ]; + + #[test] + fn the_console_waterfall_over_a_first_lane_offset_is_one() { + let r = waterfall(WATERFALL_INDEXED_WAVE32, false).unwrap(); + let image = r + .descriptors + .iter() + .find(|d| d.role == Role::Resource) + .unwrap(); + let Source::Loaded { load, first: 0 } = image.source else { + panic!("{:?}", image.source) + }; + let (_, address) = r.scalar.iter().find(|s| s.0 == load).unwrap(); + assert!(address.dynamic.is_some(), "{address:?}"); + assert_eq!(r.waterfall.compares.len(), 1); + assert_eq!(r.waterfall.reads.len(), 1); + assert_eq!(r.waterfall.loads, [load]); + } + + /// [`WATERFALL_JOINED_WAVE32`] with other sources on each path: lanes + /// below 16 load table entry (lane & 1) with two `global_load_dwordx4`, + /// the others pick per lane with `v_cndmask_b32` (lanes below 24 the + /// first entry, the rest the second). + pub(crate) const WATERFALL_JOINED_MIXED_WAVE32: &[u32] = &[ + 0xBE84_0300, // s_mov_b32 s4, s0 + 0xBE85_0380, // s_mov_b32 s5, 0 + 0xBE86_0301, // s_mov_b32 s6, s1 + 0xBE87_0380, // s_mov_b32 s7, 0 + 0xF40C_0602, + 0xFA00_0000, // s_load_dwordx8 s[24:31], s[4:5], 0x0 + 0xF40C_0802, + 0xFA00_0020, // s_load_dwordx8 s[32:39], s[4:5], 0x20 + 0xF408_0203, + 0xFA00_0000, // s_load_dwordx4 s[8:11], s[6:7], 0x0 + 0xF408_0A02, + 0xFA00_0040, // s_load_dwordx4 s[40:43], s[4:5], 0x40 + 0x7E04_0D00, // v_cvt_f32_u32 v2, v0 + 0x7E06_0302, // v_mov_b32 v3, v2 + 0x3420_0082, // v_lshlrev_b32 v16, 2, v0 + 0x3602_0081, // v_and_b32 v1, 1, v0 + 0x3402_0285, // v_lshlrev_b32 v1, 5, v1 + 0x7D88_0090, // v_cmp_gt_u32 vcc_lo, 16, v0 + 0xBF8C_C07F, // s_waitcnt lgkmcnt(0) + 0xBE94_3C6A, // s_and_saveexec_b32 s20, vcc_lo + 0x8914_147E, // s_xor_b32 s20, exec_lo, s20 + 0xBF88_0004, // s_cbranch_execz -> 0x68 + 0xDC38_8000, + 0x0404_0001, // global_load_dwordx4 v[4:7], v1, s[4:5] + 0xDC38_8010, + 0x0804_0001, // global_load_dwordx4 v[8:11], v1, s[4:5] offset:16 + 0xBE94_3D14, // 0x68: s_or_saveexec_b32 s20, s20 + 0x897E_147E, // s_xor_b32 exec_lo, exec_lo, s20 + 0xBF88_0011, // s_cbranch_execz -> 0xb8 + 0x7D88_0098, // v_cmp_gt_u32 vcc_lo, 24, v0 + 0x7E08_0218, // v_mov_b32 v4, s24 + 0x0208_0820, // v_cndmask_b32 v4, s32, v4, vcc_lo + 0x7E0A_0219, // v_mov_b32 v5, s25 + 0x020A_0A21, // v_cndmask_b32 v5, s33, v5, vcc_lo + 0x7E0C_021A, // v_mov_b32 v6, s26 + 0x020C_0C22, // v_cndmask_b32 v6, s34, v6, vcc_lo + 0x7E0E_021B, // v_mov_b32 v7, s27 + 0x020E_0E23, // v_cndmask_b32 v7, s35, v7, vcc_lo + 0x7E10_021C, // v_mov_b32 v8, s28 + 0x0210_1024, // v_cndmask_b32 v8, s36, v8, vcc_lo + 0x7E12_021D, // v_mov_b32 v9, s29 + 0x0212_1225, // v_cndmask_b32 v9, s37, v9, vcc_lo + 0x7E14_021E, // v_mov_b32 v10, s30 + 0x0214_1426, // v_cndmask_b32 v10, s38, v10, vcc_lo + 0x7E16_021F, // v_mov_b32 v11, s31 + 0x0216_1627, // v_cndmask_b32 v11, s39, v11, vcc_lo + 0x887E_147E, // 0xb8: s_or_b32 exec_lo, exec_lo, s20 + 0xBE97_037E, // s_mov_b32 s23, exec_lo + 0xBF8C_3F70, // s_waitcnt vmcnt(0) + 0x7E18_0504, // 0xc4: v_readfirstlane_b32 s12, v4 + 0x7E1A_0505, // v_readfirstlane_b32 s13, v5 + 0x7E1C_0506, // v_readfirstlane_b32 s14, v6 + 0x7E1E_0507, // v_readfirstlane_b32 s15, v7 + 0x7E20_0508, // v_readfirstlane_b32 s16, v8 + 0x7E22_0509, // v_readfirstlane_b32 s17, v9 + 0x7E24_050A, // v_readfirstlane_b32 s18, v10 + 0x7E26_050B, // v_readfirstlane_b32 s19, v11 + 0xD4E2_0015, + 0x0002_080C, // v_cmp_eq_u64_e64 s21, s[12:13], v[4:5] + 0xD4E2_0016, + 0x0002_0C0E, // v_cmp_eq_u64_e64 s22, s[14:15], v[6:7] + 0x8715_1615, // s_and_b32 s21, s21, s22 + 0xD4E2_0016, + 0x0002_1010, // v_cmp_eq_u64_e64 s22, s[16:17], v[8:9] + 0x8715_1615, // s_and_b32 s21, s21, s22 + 0xD4E2_0016, + 0x0002_1412, // v_cmp_eq_u64_e64 s22, s[18:19], v[10:11] + 0x8715_1615, // s_and_b32 s21, s21, s22 + 0xBE95_3C15, // s_and_saveexec_b32 s21, s21 + 0xBF80_0000, // s_nop 0 + 0xF09C_0F08, + 0x0043_0C02, // image_sample_lz v[12:15], v[2:3], s[12:19], s[8:11] dmask:0xf dim:SQ_RSRC_IMG_2D + 0xBF8C_3F70, // s_waitcnt vmcnt(0) + 0x897E_157E, // s_xor_b32 exec_lo, exec_lo, s21 + 0xBF89_FFE6, // s_cbranch_execnz -> 0xc4 + 0xBEFE_0317, // s_mov_b32 exec_lo, s23 + 0xE070_1000, + 0x800A_0C10, // buffer_store_dword v12, v16, s[40:43], 0 offen + 0xBF81_0000, // s_endpgm + ]; + + /// A waterfall loop whose descriptor changes on each pass: v[4:11] holds + /// the first table entry on entry and the second after every pass, so + /// the first lane's dwords are phis of the loop header. + pub(crate) const WATERFALL_LOOPED_WAVE32: &[u32] = &[ + 0xBE84_0300, // s_mov_b32 s4, s0 + 0xBE85_0380, // s_mov_b32 s5, 0 + 0xBE86_0301, // s_mov_b32 s6, s1 + 0xBE87_0380, // s_mov_b32 s7, 0 + 0xF40C_0602, + 0xFA00_0000, // s_load_dwordx8 s[24:31], s[4:5], 0x0 + 0xF40C_0802, + 0xFA00_0020, // s_load_dwordx8 s[32:39], s[4:5], 0x20 + 0xF408_0203, + 0xFA00_0000, // s_load_dwordx4 s[8:11], s[6:7], 0x0 + 0xF408_0A02, + 0xFA00_0040, // s_load_dwordx4 s[40:43], s[4:5], 0x40 + 0x7E04_0D00, // v_cvt_f32_u32 v2, v0 + 0x7E06_0302, // v_mov_b32 v3, v2 + 0x3420_0082, // v_lshlrev_b32 v16, 2, v0 + 0x7E08_0218, // v_mov_b32 v4, s24 + 0x7E0A_0219, // v_mov_b32 v5, s25 + 0x7E0C_021A, // v_mov_b32 v6, s26 + 0x7E0E_021B, // v_mov_b32 v7, s27 + 0x7E10_021C, // v_mov_b32 v8, s28 + 0x7E12_021D, // v_mov_b32 v9, s29 + 0x7E14_021E, // v_mov_b32 v10, s30 + 0x7E16_021F, // v_mov_b32 v11, s31 + 0xBF8C_C07F, // s_waitcnt lgkmcnt(0) + 0xBE97_037E, // s_mov_b32 s23, exec_lo + 0x7E18_0504, // 0x64: v_readfirstlane_b32 s12, v4 + 0x7E1A_0505, // v_readfirstlane_b32 s13, v5 + 0x7E1C_0506, // v_readfirstlane_b32 s14, v6 + 0x7E1E_0507, // v_readfirstlane_b32 s15, v7 + 0x7E20_0508, // v_readfirstlane_b32 s16, v8 + 0x7E22_0509, // v_readfirstlane_b32 s17, v9 + 0x7E24_050A, // v_readfirstlane_b32 s18, v10 + 0x7E26_050B, // v_readfirstlane_b32 s19, v11 + 0xD4E2_0015, + 0x0002_080C, // v_cmp_eq_u64_e64 s21, s[12:13], v[4:5] + 0xD4E2_0016, + 0x0002_0C0E, // v_cmp_eq_u64_e64 s22, s[14:15], v[6:7] + 0x8715_1615, // s_and_b32 s21, s21, s22 + 0xD4E2_0016, + 0x0002_1010, // v_cmp_eq_u64_e64 s22, s[16:17], v[8:9] + 0x8715_1615, // s_and_b32 s21, s21, s22 + 0xD4E2_0016, + 0x0002_1412, // v_cmp_eq_u64_e64 s22, s[18:19], v[10:11] + 0x8715_1615, // s_and_b32 s21, s21, s22 + 0xBE95_3C15, // s_and_saveexec_b32 s21, s21 + 0xBF80_0000, // s_nop 0 + 0xF09C_0F08, + 0x0043_0C02, // image_sample_lz v[12:15], v[2:3], s[12:19], s[8:11] dmask:0xf dim:SQ_RSRC_IMG_2D + 0xBF8C_3F70, // s_waitcnt vmcnt(0) + 0x897E_157E, // s_xor_b32 exec_lo, exec_lo, s21 + 0x7E08_0220, // v_mov_b32 v4, s32 + 0x7E0A_0221, // v_mov_b32 v5, s33 + 0x7E0C_0222, // v_mov_b32 v6, s34 + 0x7E0E_0223, // v_mov_b32 v7, s35 + 0x7E10_0224, // v_mov_b32 v8, s36 + 0x7E12_0225, // v_mov_b32 v9, s37 + 0x7E14_0226, // v_mov_b32 v10, s38 + 0x7E16_0227, // v_mov_b32 v11, s39 + 0xBF89_FFDE, // s_cbranch_execnz -> 0x64 + 0xBEFE_0317, // s_mov_b32 exec_lo, s23 + 0xE070_1000, + 0x800A_0C10, // buffer_store_dword v12, v16, s[40:43], 0 offen + 0xBF81_0000, // s_endpgm + ]; + + /// A waterfall loop over one of two buffer descriptors (four dwords) + /// loaded from the table at s0, chosen by nested if/else: lanes below 16 + /// move the first into v[4:7], lanes from 16 to 23 the second, and the + /// others keep what v[4:7] held. Only lanes below 24 (the same mask) + /// run the loop, which loads dword `lane` of the chosen buffer, and + /// store it to the buffer at dword 16 of the table. + pub(crate) const WATERFALL_JOINED_BUFFER_WAVE32: &[u32] = &[ + 0xBE84_0300, // s_mov_b32 s4, s0 + 0xBE85_0380, // s_mov_b32 s5, 0 + 0xF408_0602, + 0xFA00_0000, // s_load_dwordx4 s[24:27], s[4:5], 0x0 + 0xF408_0802, + 0xFA00_0020, // s_load_dwordx4 s[32:35], s[4:5], 0x20 + 0xF408_0A02, + 0xFA00_0040, // s_load_dwordx4 s[40:43], s[4:5], 0x40 + 0x3420_0082, // v_lshlrev_b32 v16, 2, v0 + 0xD4C4_001E, + 0x0002_0098, // v_cmp_gt_u32_e64 s30, 24, v0 + 0x7D88_0090, // v_cmp_gt_u32 vcc_lo, 16, v0 + 0xBF8C_C07F, // s_waitcnt lgkmcnt(0) + 0xBE94_3C6A, // s_and_saveexec_b32 s20, vcc_lo + 0x8914_147E, // s_xor_b32 s20, exec_lo, s20 + 0xBF88_0004, // s_cbranch_execz -> 0x50 + 0x7E08_0218, // 0x40: v_mov_b32 v4, s24 + 0x7E0A_0219, // v_mov_b32 v5, s25 + 0x7E0C_021A, // v_mov_b32 v6, s26 + 0x7E0E_021B, // v_mov_b32 v7, s27 + 0xBE94_3D14, // 0x50: s_or_saveexec_b32 s20, s20 + 0x897E_147E, // s_xor_b32 exec_lo, exec_lo, s20 + 0xBF88_0007, // s_cbranch_execz -> 0x78 + 0xBE9F_3C1E, // s_and_saveexec_b32 s31, s30 + 0xBF88_0004, // s_cbranch_execz -> 0x74 + 0x7E08_0220, // 0x64: v_mov_b32 v4, s32 + 0x7E0A_0221, // v_mov_b32 v5, s33 + 0x7E0C_0222, // v_mov_b32 v6, s34 + 0x7E0E_0223, // v_mov_b32 v7, s35 + 0x887E_1F7E, // 0x74: s_or_b32 exec_lo, exec_lo, s31 + 0x887E_147E, // 0x78: s_or_b32 exec_lo, exec_lo, s20 + 0xBE97_3C1E, // s_and_saveexec_b32 s23, s30 + 0xBF88_0013, // s_cbranch_execz -> 0xd0 + 0xBE9D_037E, // s_mov_b32 s29, exec_lo + 0x7E18_0504, // 0x88: v_readfirstlane_b32 s12, v4 + 0x7E1A_0505, // v_readfirstlane_b32 s13, v5 + 0x7E1C_0506, // v_readfirstlane_b32 s14, v6 + 0x7E1E_0507, // v_readfirstlane_b32 s15, v7 + 0xD4E2_0015, + 0x0002_080C, // v_cmp_eq_u64_e64 s21, s[12:13], v[4:5] + 0xD4E2_0016, + 0x0002_0C0E, // v_cmp_eq_u64_e64 s22, s[14:15], v[6:7] + 0x8715_1615, // s_and_b32 s21, s21, s22 + 0xBE95_3C15, // s_and_saveexec_b32 s21, s21 + 0xE030_1000, + 0x8003_0C10, // buffer_load_dword v12, v16, s[12:15], 0 offen + 0xBF8C_3F70, // s_waitcnt vmcnt(0) + 0x897E_157E, // s_xor_b32 exec_lo, exec_lo, s21 + 0xBF89_FFF1, // s_cbranch_execnz -> 0x88 + 0xBEFE_031D, // s_mov_b32 exec_lo, s29 + 0xE070_1000, + 0x800A_0C10, // buffer_store_dword v12, v16, s[40:43], 0 offen + 0x887E_177E, // 0xd0: s_or_b32 exec_lo, exec_lo, s23 + 0xBF81_0000, // s_endpgm + ]; + + fn waterfall(words: &[u32], wave64: bool) -> Result { + let code: Vec = words.iter().flat_map(|w| w.to_le_bytes()).collect(); + let p = crate::ir::build(&code, wave64, 256).unwrap(); + let layout = [param(Table, 0, 1), param(Table, 1, 1)]; + track(&p, &layout, HwStage::Cs, lanes(&p).as_ref()) + } + + #[test] + fn descriptors_read_from_the_first_lane_of_per_lane_loads_are_traced_to_them() { + for (words, wave64) in [ + (WATERFALL_FETCHED_WAVE32, false), + (WATERFALL_FETCHED_WAVE64, true), + ] { + let r = waterfall(words, wave64).unwrap(); + let image = r + .descriptors + .iter() + .find(|d| d.role == Role::Resource) + .unwrap(); + let Source::Fetched { load, first: 0 } = image.source else { + panic!("{:?}", image.source) + }; + // The first of the two loads: entry v0 * 32 of the table at s0. + let a = r.scalar.iter().find(|s| s.0 == load).unwrap().1; + assert_eq!((a.param, a.offset), (0, 0)); + assert!(a.dynamic.is_some()); + // The sampler is the same for every lane. + let sampler = r.descriptors.iter().find(|d| d.role == Role::Sampler); + assert!(matches!( + sampler.unwrap().source, + Source::Loaded { first: 0, .. } + )); + // Four 64-bit compares of the first lane's dwords with the lane's + // own; the eight reads become the lane's own dwords. + assert_eq!(r.waterfall.compares.len(), 4); + assert_eq!(r.waterfall.reads.len(), 8); + } + } + + #[test] + fn descriptors_read_from_the_first_lane_of_a_per_lane_choice_are_traced_per_lane() { + let r = waterfall(WATERFALL_PICKED_WAVE32, false).unwrap(); + let image = &r.descriptors[0]; + let Source::Lanes { args, .. } = &image.source else { + panic!("{:?}", image.source) + }; + // Lanes with their bit set take the first load (offset 0), the + // others the second (0x20). + let offsets: Vec = args + .iter() + .map(|a| match *a { + Source::Loaded { load, first: 0 } => { + r.scalar.iter().find(|s| s.0 == load).unwrap().1.offset + } + ref a => panic!("{a:?}"), + }) + .collect(); + assert_eq!(offsets, [0, 0x20]); + assert_eq!(r.waterfall.compares.len(), 4); + } + + #[test] + fn a_first_lane_read_outside_a_loop_is_no_waterfall() { + // The waterfall without its back edge: the s_cbranch_execnz is an + // s_nop, so lanes the first one does not match never get a pass. + let mut words = WATERFALL_FETCHED_WAVE32.to_vec(); + let back = words.iter().position(|&w| w == 0xBF89_FFE6).unwrap(); + words[back] = 0xBF80_0000; + let err = waterfall(&words, false).unwrap_err(); + assert!( + matches!( + err, + ShaderError::Unsupported { + what: "a descriptor read from the first lane outside a waterfall loop", + .. + } + ), + "{err:?}" + ); + } + + /// Why resource tracking refuses `words`. + fn refusal(words: &[u32], wave64: bool) -> &'static str { + match waterfall(words, wave64) { + Err(ShaderError::Unsupported { what, .. }) => what, + other => panic!("not refused: {other:?}"), + } + } + + const NO_LOOP: &str = "a descriptor read from the first lane outside a waterfall loop"; + const NOT_SELECTED: &str = "a waterfall loop whose compares do not select the access's lanes"; + const BAD_RETRY: &str = "a waterfall loop whose retry does not keep the lanes still waiting"; + const SPLIT: &str = "a waterfall loop nested in another or split over blocks"; + + /// The index of `word` in `words`. + fn word_at(words: &[u32], word: u32) -> usize { + words.iter().position(|&w| w == word).unwrap() + } + + #[test] + fn a_first_lane_read_without_its_compare_is_no_waterfall() { + // The loop without the compare of dwords 0 and 1: nothing makes + // the first lane's dwords the lane's own there. + let mut words = WATERFALL_FETCHED_WAVE32.to_vec(); + let cmp = word_at(&words, 0x0002_080C); + words[cmp - 1..=cmp].copy_from_slice(&[0xBF80_0000, 0xBF80_0000]); + assert_eq!(refusal(&words, false), NOT_SELECTED); + } + + #[test] + fn a_compare_that_does_not_mask_the_access_is_no_waterfall() { + // The compares are all there, but their result never narrows EXEC: + // every lane samples with the first lane's descriptor (reported by + // ifBars on upstream PR #566). + let mut words = WATERFALL_JOINED_WAVE32.to_vec(); + let save = word_at(&words, 0xBE95_3C15); + words[save] = 0xBE95_037E; // s_mov_b32 s21, exec_lo + assert_eq!(refusal(&words, false), NOT_SELECTED); + } + + #[test] + fn an_access_under_a_further_mask_is_no_waterfall() { + // The access runs for the matching lanes that VCC also holds, yet + // the retry removes every matching lane. + let mut words = WATERFALL_JOINED_WAVE32.to_vec(); + let nop = word_at(&words, 0xBE95_3C15) + 1; + assert_eq!(words[nop], 0xBF80_0000); + words[nop] = 0x877E_6A7E; // s_and_b32 exec_lo, exec_lo, vcc_lo + assert_eq!(refusal(&words, false), NOT_SELECTED); + } + + #[test] + fn a_loop_that_drops_unmatched_lanes_is_no_waterfall() { + let mut words = WATERFALL_JOINED_WAVE32.to_vec(); + let retry = word_at(&words, 0x897E_157E); + words[retry] = 0xBEFE_0380; // s_mov_b32 exec_lo, 0 + assert_eq!(refusal(&words, false), BAD_RETRY); + } + + #[test] + fn a_retry_that_keeps_other_lanes_than_those_waiting_is_no_waterfall() { + // The retry keeps the lanes of VCC that did not just sample, not + // the waiting ones: lanes 16 and up never sample on the console. + let mut words = WATERFALL_JOINED_WAVE32.to_vec(); + let retry = word_at(&words, 0x897E_157E); + words[retry] = 0x8A7E_7E6A; // s_andn2_b32 exec_lo, vcc_lo, exec_lo + assert_eq!(refusal(&words, false), BAD_RETRY); + } + + #[test] + fn a_wave64_retry_of_one_half_is_no_waterfall() { + // Only the low half of EXEC loses the lanes just served. + let mut words = WATERFALL_FETCHED_WAVE64.to_vec(); + let retry = word_at(&words, 0x89FE_167E); + words[retry] = 0x897E_167E; // s_xor_b32 exec_lo, exec_lo, s22 + assert_eq!(refusal(&words, true), BAD_RETRY); + } + + #[test] + fn a_descriptor_used_after_exec_is_restored_is_no_waterfall() { + let mut words = WATERFALL_JOINED_WAVE32.to_vec(); + let sample = word_at(&words, 0xF09C_0F08); + let restore = word_at(&words, 0xBEFE_0317); + let image = [words[sample], words[sample + 1]]; + words[sample..sample + 2].fill(0xBF80_0000); // Keep the branch offsets. + words.splice(restore + 1..restore + 1, image); + assert_eq!(refusal(&words, false), NO_LOOP); + } + + #[test] + fn a_wave64_access_with_exec_hi_overwritten_is_no_waterfall() { + let mut words = WATERFALL_FETCHED_WAVE64.to_vec(); + let save = word_at(&words, 0xBE96_2416); + words[save + 1] = 0xBEFF_03C1; // s_mov_b32 exec_hi, -1 + assert_eq!(refusal(&words, true), NOT_SELECTED); + } + + /// The waterfall with `v_cmpx_eq` narrowing EXEC itself, and the retry + /// as `todo & !EXEC` (`folded`: in one `s_andn2_wrexec`), as LLVM's + /// AMDGPU backend writes it for GFX10 and later. + pub(crate) fn cmpx_waterfall(wave64: bool, folded: bool) -> Vec { + let (base, todo, restore): (&[u32], u32, u32) = if wave64 { + (WATERFALL_FETCHED_WAVE64, 0xBE94_047E, 0xBEFE_0414) + } else { + (WATERFALL_JOINED_WAVE32, 0xBE97_037E, 0xBEFE_0317) + }; + let reads = word_at(base, 0x7E18_0504); + let sample = word_at(base, 0xF09C_0F08); + let mut w = base[..=word_at(base, todo)].to_vec(); + // s_mov_b32 s21, exec_lo / s_mov_b64 s[22:23], exec + w.push(if wave64 { 0xBE96_047E } else { 0xBE95_037E }); + w.extend(&base[reads..reads + 8]); // v_readfirstlane_b32 s12..s19 + w.extend([ + 0x7DE4_080C, // v_cmpx_eq_u64 s[12:13], v[4:5] + 0x7DE4_0C0E, // v_cmpx_eq_u64 s[14:15], v[6:7] + 0x7DE4_1010, // v_cmpx_eq_u64 s[16:17], v[8:9] + 0x7DE4_1412, // v_cmpx_eq_u64 s[18:19], v[10:11] + ]); + w.extend(&base[sample..sample + 2]); // image_sample_lz + match (wave64, folded) { + // s_andn2_wrexec_b32 s21, s21; s_cbranch_execnz + (false, true) => w.extend([0xBE95_4715, 0xBF89_FFF0]), + // s_andn2_b32 s21, s21, exec_lo; s_mov_b32 exec_lo, s21 + (false, false) => w.extend([0x8A15_7E15, 0xBEFE_0315, 0xBF89_FFEF]), + // s_andn2_wrexec_b64 s[22:23], s[22:23] + (true, true) => w.extend([0xBE96_3A16, 0xBF89_FFF0]), + // s_andn2_b64 s[22:23], s[22:23], exec; s_mov_b64 exec, s[22:23] + (true, false) => w.extend([0x8A96_7E16, 0xBEFE_0416, 0xBF89_FFEF]), + } + w.extend(&base[word_at(base, restore)..]); + w + } + + #[test] + fn a_waterfall_narrowed_by_v_cmpx_is_one() { + for wave64 in [false, true] { + for folded in [false, true] { + let r = waterfall(&cmpx_waterfall(wave64, folded), wave64) + .unwrap_or_else(|e| panic!("wave64 {wave64} folded {folded}: {e:?}")); + assert_eq!(r.waterfall.compares.len(), 4, "{wave64} {folded}"); + assert_eq!(r.waterfall.reads.len(), 8, "{wave64} {folded}"); + } + } + } + + #[test] + fn a_v_cmpx_waterfall_whose_retry_drops_lanes_is_none() { + let mut words = cmpx_waterfall(false, false); + let retry = word_at(&words, 0x8A15_7E15); + words[retry] = 0x8A15_7E6A; // s_andn2_b32 s21, vcc_lo, exec_lo + assert_eq!(refusal(&words, false), BAD_RETRY); + } + + #[test] + fn a_waterfall_nested_in_another_is_refused_by_name() { + // An image whose resource and sampler are both per lane, with one + // loop per operand, the one for the sampler inside the one for the + // resource (what the SelectionDAG legalisation in LLVM would give). + // The console gives each lane its own pair. Refused for now: the + // access of the inner loop reads the first-lane dwords of the outer + // loop, which another block holds. + let words = [ + 0xBE84_0300, // s_mov_b32 s4, s0 + 0xBE85_0380, // s_mov_b32 s5, 0 + 0xBE86_0301, // s_mov_b32 s6, s1 + 0xBE87_0380, // s_mov_b32 s7, 0 + 0xF408_0A02, + 0xFA00_0040, // s_load_dwordx4 s[40:43], s[4:5], 0x40 + 0x7E04_0D00, // v_cvt_f32_u32 v2, v0 + 0x7E06_0302, // v_mov_b32 v3, v2 + 0x3420_0082, // v_lshlrev_b32 v16, 2, v0 + 0x3602_0081, // v_and_b32 v1, 1, v0 + 0x3402_0285, // v_lshlrev_b32 v1, 5, v1 + 0x3622_0080, // v_and_b32 v17, 0, v0 + 0x3422_2284, // v_lshlrev_b32 v17, 4, v17 + 0xDC38_8000, + 0x0404_0001, // global_load_dwordx4 v[4:7], v1, s[4:5] + 0xDC38_8010, + 0x0804_0001, // global_load_dwordx4 v[8:11], v1, s[4:5] offset:16 + 0xDC38_8000, + 0x1406_0011, // global_load_dwordx4 v[20:23], v17, s[6:7] + 0xBF8C_0070, // s_waitcnt vmcnt(0) lgkmcnt(0) + 0xBE94_037E, // s_mov_b32 s20, exec_lo + // L1, the loop over the resource: + 0x7E18_0504, // v_readfirstlane_b32 s12, v4 + 0x7E1A_0505, + 0x7E1C_0506, + 0x7E1E_0507, + 0x7E20_0508, + 0x7E22_0509, + 0x7E24_050A, + 0x7E26_050B, // v_readfirstlane_b32 s19, v11 + 0xD4E2_0015, + 0x0002_080C, // v_cmp_eq_u64_e64 s21, s[12:13], v[4:5] + 0xD4E2_0016, + 0x0002_0C0E, // v_cmp_eq_u64_e64 s22, s[14:15], v[6:7] + 0x8715_1615, // s_and_b32 s21, s21, s22 + 0xD4E2_0016, + 0x0002_1010, // v_cmp_eq_u64_e64 s22, s[16:17], v[8:9] + 0x8715_1615, // s_and_b32 s21, s21, s22 + 0xD4E2_0016, + 0x0002_1412, // v_cmp_eq_u64_e64 s22, s[18:19], v[10:11] + 0x8715_1615, // s_and_b32 s21, s21, s22 + 0xBE95_3C15, // s_and_saveexec_b32 s21, s21 + 0xBE9A_037E, // s_mov_b32 s26, exec_lo + // L2, the loop over the sampler: + 0x7E10_0514, // v_readfirstlane_b32 s8, v20 + 0x7E12_0515, // v_readfirstlane_b32 s9, v21 + 0x7E14_0516, // v_readfirstlane_b32 s10, v22 + 0x7E16_0517, // v_readfirstlane_b32 s11, v23 + 0xD4E2_0018, + 0x0002_2808, // v_cmp_eq_u64_e64 s24, s[8:9], v[20:21] + 0xD4E2_0019, + 0x0002_2C0A, // v_cmp_eq_u64_e64 s25, s[10:11], v[22:23] + 0x8718_1918, // s_and_b32 s24, s24, s25 + 0xBE98_3C18, // s_and_saveexec_b32 s24, s24 + 0xF09C_0F08, + 0x0043_0C02, // image_sample_lz v[12:15], v[2:3], s[12:19], s[8:11] + 0x897E_187E, // s_xor_b32 exec_lo, exec_lo, s24 + 0xBF89_FFF2, // s_cbranch_execnz L2 + 0xBEFE_031A, // s_mov_b32 exec_lo, s26 + 0x897E_157E, // s_xor_b32 exec_lo, exec_lo, s21 + 0xBF89_FFDA, // s_cbranch_execnz L1 + 0xBEFE_0314, // s_mov_b32 exec_lo, s20 + 0xE070_1000, + 0x800A_0C10, // buffer_store_dword v12, v16, s[40:43], 0 offen + 0xBF81_0000, // s_endpgm + ]; + assert_eq!(refusal(&words, false), SPLIT); + } + + #[test] + fn descriptors_read_from_the_first_lane_of_lds_fail_naming_it() { + // The waterfall over descriptors each lane read from LDS: + // ds_read_b128 v[4:7], v1 and ds_read_b128 v[8:11], v1 offset:16 + // in place of the global loads. + let mut words = WATERFALL_FETCHED_WAVE32.to_vec(); + words[5..9].copy_from_slice(&[0xDBFC_0000, 0x0400_0001, 0xDBFC_0010, 0x0800_0001]); + let err = waterfall(&words, false).unwrap_err(); + assert!( + matches!( + err, + ShaderError::Unsupported { + what: "a descriptor read from the first lane of an LDS read", + .. + } + ), + "{err:?}" + ); + } + + /// The block of `p` at byte `offset`. + fn block_at(words: &[u32], offset: usize) -> usize { + let code: Vec = words.iter().flat_map(|w| w.to_le_bytes()).collect(); + let p = crate::ir::build(&code, false, 256).unwrap(); + p.blocks.iter().position(|b| b.offset == offset).unwrap() + } + + /// The table offset of what the scalar load of `s` reads. + fn table_offset(r: &Resources, s: &Source) -> u32 { + match *s { + Source::Loaded { load, first: 0 } => { + r.scalar.iter().find(|x| x.0 == load).unwrap().1.offset + } + ref s => panic!("{s:?}"), + } + } + + #[test] + fn descriptors_read_from_the_first_lane_of_an_if_else_join_are_traced_per_path() { + let words = WATERFALL_JOINED_WAVE32; + let r = waterfall(words, false).unwrap(); + let image = r + .descriptors + .iter() + .find(|d| matches!(d.source, Source::LanePhi { .. })) + .unwrap(); + // The join after the else arm: lanes that ran it (lanes from 16 on) + // take the second entry (0x20); the others come through the flow + // block, whose join gives lanes that ran the then arm the first one + // (0). No lane that skipped the then arm comes that way, so the + // dwords they held before (the inputs) are not traced. + let Source::LanePhi { block, args } = &image.source else { + unreachable!() + }; + assert_eq!(*block, block_at(words, 0x9c)); + let [Some(flow), Some(other)] = &args[..] else { + panic!("{args:?}") + }; + assert_eq!(table_offset(&r, other), 0x20); + let Source::LanePhi { block, args } = flow else { + panic!("{flow:?}") + }; + assert_eq!(*block, block_at(words, 0x70)); + let [None, Some(then)] = &args[..] else { + panic!("{args:?}") + }; + assert_eq!(table_offset(&r, then), 0); + // The loop's compares are of the joined dwords; still recognised. + assert_eq!(r.waterfall.compares.len(), 4); + assert_eq!(r.waterfall.reads.len(), 8); + // Without the lanes' paths the join is refused. + let code: Vec = words.iter().flat_map(|w| w.to_le_bytes()).collect(); + let p = crate::ir::build(&code, false, 256).unwrap(); + let layout = [param(Table, 0, 1), param(Table, 1, 1)]; + let err = track(&p, &layout, HwStage::Cs, None).unwrap_err(); + assert!( + matches!( + err, + ShaderError::Unsupported { + what: "a descriptor read from the first lane of a phi, without the lanes' paths", + .. + } + ), + "{err:?}" + ); + } + + #[test] + fn descriptors_joined_from_a_per_lane_load_and_a_per_lane_choice_are_traced_per_path() { + let words = WATERFALL_JOINED_MIXED_WAVE32; + let r = waterfall(words, false).unwrap(); + let image = r + .descriptors + .iter() + .find(|d| matches!(d.source, Source::LanePhi { .. })) + .unwrap(); + let Source::LanePhi { block, args } = &image.source else { + unreachable!() + }; + assert_eq!(*block, block_at(words, 0xb8)); + let [ + Some(Source::LanePhi { args: flow, .. }), + Some(Source::Lanes { args: picked, .. }), + ] = &args[..] + else { + panic!("{args:?}") + }; + // The then arm loads each lane's entry from the table at s0. + let [None, Some(Source::Fetched { load, first: 0 })] = flow[..] else { + panic!("{flow:?}") + }; + let a = r.scalar.iter().find(|s| s.0 == load).unwrap().1; + assert_eq!((a.param, a.offset), (0, 0)); + assert!(a.dynamic.is_some()); + // The else arm picks the first entry where vcc is set. + let offsets: Vec = picked.iter().map(|s| table_offset(&r, s)).collect(); + assert_eq!(offsets, [0, 0x20]); + assert_eq!(r.waterfall.compares.len(), 4); + } + + #[test] + fn a_descriptor_read_from_the_first_lane_of_a_loop_phi_fails_naming_it() { + let err = waterfall(WATERFALL_LOOPED_WAVE32, false).unwrap_err(); + assert!( + matches!( + err, + ShaderError::Unsupported { + what: "a descriptor read from the first lane of a phi at a loop header", + .. + } + ), + "{err:?}" + ); + } + + #[test] + fn a_per_lane_descriptor_some_lanes_do_not_write_fails() { + // The else arm of WATERFALL_JOINED_WAVE32 not skipped (its + // s_cbranch_execz an s_nop): it runs with EXEC clear in the lanes + // of the then arm, which keep the first entry; the second is not + // every lane's. + let mut words = WATERFALL_JOINED_WAVE32.to_vec(); + let skip = words.iter().rposition(|&w| w == 0xBF88_0008).unwrap(); + words[skip] = 0xBF80_0000; + let err = waterfall(&words, false).unwrap_err(); + assert!( + matches!( + err, + ShaderError::Unsupported { + what: "a per-lane descriptor written where some lanes may keep the old one", + .. + } + ), + "{err:?}" + ); + } + + #[test] + fn a_buffer_descriptor_joined_per_lane_is_traced_on_the_paths_of_lanes_that_load() { + let words = WATERFALL_JOINED_BUFFER_WAVE32; + let r = waterfall(words, false).unwrap(); + let buffer = r + .descriptors + .iter() + .find(|d| matches!(d.source, Source::LanePhi { .. })) + .unwrap(); + // The outer join: lanes from the else arm's inner join, or (below + // 16) through the flow block. + let Source::LanePhi { block, args } = &buffer.source else { + unreachable!() + }; + assert_eq!(*block, block_at(words, 0x78)); + let [ + Some(Source::LanePhi { args: flow, .. }), + Some(Source::LanePhi { + block: inner, + args: nested, + }), + ] = &args[..] + else { + panic!("{args:?}") + }; + let [None, Some(then)] = &flow[..] else { + panic!("{flow:?}") + }; + assert_eq!(table_offset(&r, then), 0); + // Lanes from 24 on skip the inner arm and keep the inputs, but do + // not load: that edge is not traced. + assert_eq!(*inner, block_at(words, 0x74)); + let [None, Some(other)] = &nested[..] else { + panic!("{nested:?}") + }; + assert_eq!(table_offset(&r, other), 0x20); + assert_eq!(r.waterfall.compares.len(), 2); + assert_eq!(r.waterfall.reads.len(), 4); + } +} diff --git a/crates/leonida-shader/src/spill.rs b/crates/leonida-shader/src/spill.rs new file mode 100644 index 000000000..a0feb6aeb --- /dev/null +++ b/crates/leonida-shader/src/spill.rs @@ -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 { + 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> { + 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 = 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 = 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) -> 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 = 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))); + } +} diff --git a/crates/leonida-shader/src/structure.rs b/crates/leonida-shader/src/structure.rs new file mode 100644 index 000000000..a913176c6 --- /dev/null +++ b/crates/leonida-shader/src/structure.rs @@ -0,0 +1,1848 @@ +//! Control-flow structurisation (decision 0003): the program as one lane +//! runs it, without EXEC. +//! +//! Lane masks (EXEC, compare and carry results, the SGPRs they are saved +//! in) become per-lane booleans ([`Bools`]). A branch on a wave-wide test of +//! a mask (`s_cbranch_execz`, `vccz`, SCC of a mask operation) becomes a +//! branch on the lane's own bit: compiled code only skips work that lanes +//! outside the mask would not change, or tests a value that is the same in +//! every lane, so either way each lane can decide alone. A path-sensitive +//! pass then proves, for each vector instruction, that EXEC holds in every +//! lane that reaches it; what it cannot prove stays as the instruction's +//! guard, a per-lane `if` around it. +//! +//! The control-flow graph keeps its shape and must be reducible (DXIL's +//! only requirement). Helper lanes of a pixel shader count as live: on PC +//! their side effects are dropped too, and what they compute is only read +//! through derivatives. + +use std::collections::{HashMap, HashSet}; +use std::hash::{BuildHasherDefault, Hasher}; + +use crate::ShaderError; +use crate::gfx10::{Fields, NULL, Operand}; +use crate::ir::{EXEC, Exit, Inst, Program, Reg, VCC, Value}; + +/// A per-lane boolean: a node of [`Bools`]. Equal functions are equal nodes. +#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] +pub struct Bool(u32); + +impl Bool { + pub const FALSE: Bool = Bool(0); + pub const TRUE: Bool = Bool(1); +} + +/// What a variable of [`Bools`] stands for. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub enum Atom { + /// The lane's bit of the compare or carry result in this VALU-written + /// value, before EXEC masking. + Lane(Value), + /// An SCC value, the same in every lane. + Uniform(Value), + /// A lane mask joined at a block entry, by its low dword's phi. + Phi(Value), + /// `s_wqm` result: some lane of the quad is in the source mask. + Quad(Value), + /// A mask the pass cannot see into (loaded, built from scalars, an + /// EXEC write it does not follow): the lane's bit of the register pair + /// this value is a dword of. + Opaque(Value), + /// A constant mask other than all lanes or none. + Constant(u64), +} + +/// Reduced ordered binary decision diagrams over [`Atom`]s. +#[derive(Debug, Clone)] +pub struct Bools { + /// (variable, low, high); nodes 0 and 1 are the constants. + nodes: Vec<(u32, Bool, Bool)>, + unique: Map<(u32, Bool, Bool), Bool>, + memo: Map<(Bool, Bool, Bool), Bool>, + atoms: Vec, + /// Reverse-postorder index of the block that defines each atom. + born: Vec, + ids: Map, + overflow: bool, +} + +/// The tables below have small integer keys; SipHash dominated run time. +type Map = HashMap>; + +/// FxHash's multiply-rotate step. +#[derive(Default)] +struct Fx(u64); + +impl Hasher for Fx { + fn finish(&self) -> u64 { + self.0 + } + + fn write(&mut self, bytes: &[u8]) { + for &b in bytes { + self.write_u64(u64::from(b)); + } + } + + fn write_u32(&mut self, n: u32) { + self.write_u64(u64::from(n)); + } + + fn write_u64(&mut self, n: u64) { + self.0 = (self.0.rotate_left(5) ^ n).wrapping_mul(0x517c_c1b7_2722_0a95); + } + + fn write_usize(&mut self, n: usize) { + self.write_u64(n as u64); + } +} + +const TERMINAL: u32 = u32::MAX; +const MAX_NODES: usize = 1 << 21; +/// Case splits [`Bools::meet`] makes before it gives up. +const MAX_MEET: usize = 1 << 16; +/// Conditions [`Meets`] keeps; past that, they are searched anew. +const MAX_MEETS: usize = 1 << 18; + +/// What [`Bools::meet`] found out about one [`Bools`], for its later calls: +/// the conditions no lane satisfies, and the case splits it took to find +/// that out of each. +#[derive(Debug, Default)] +pub struct Meets { + none: Map, usize>, +} + +impl Bools { + fn new() -> Self { + Bools { + nodes: vec![ + (TERMINAL, Bool::FALSE, Bool::FALSE), + (TERMINAL, Bool::TRUE, Bool::TRUE), + ], + unique: Map::default(), + memo: Map::default(), + atoms: Vec::new(), + born: Vec::new(), + ids: Map::default(), + overflow: false, + } + } + + /// The atom tested at the top of `b` and the results when it is false + /// and true; `None` for the constants. + pub fn node(&self, b: Bool) -> Option<(Atom, Bool, Bool)> { + let (v, lo, hi) = self.nodes[b.0 as usize]; + (v != TERMINAL).then(|| (self.atoms[v as usize], lo, hi)) + } + + /// The atoms `b` depends on, in variable order. + pub fn support(&self, b: Bool) -> Vec { + let mut vars = self.vars(b); + vars.sort_unstable(); + vars.into_iter().map(|v| self.atoms[v as usize]).collect() + } + + fn vars(&self, b: Bool) -> Vec { + let (mut seen, mut vars, mut stack) = (Vec::new(), Vec::new(), vec![b]); + while let Some(b) = stack.pop() { + let (v, lo, hi) = self.nodes[b.0 as usize]; + if v == TERMINAL || seen.contains(&b) { + continue; + } + seen.push(b); + if !vars.contains(&v) { + vars.push(v); + } + stack.extend([lo, hi]); + } + vars + } + + fn atom(&mut self, atom: Atom, born: usize) -> Bool { + let v = *self.ids.entry(atom).or_insert_with(|| { + self.atoms.push(atom); + self.born.push(born); + (self.atoms.len() - 1) as u32 + }); + self.mk(v, Bool::FALSE, Bool::TRUE) + } + + fn mk(&mut self, v: u32, lo: Bool, hi: Bool) -> Bool { + if lo == hi { + return lo; + } + if let Some(&b) = self.unique.get(&(v, lo, hi)) { + return b; + } + if self.nodes.len() >= MAX_NODES { + // The caller fails once it sees `overflow`. + self.overflow = true; + return Bool::FALSE; + } + let b = Bool(self.nodes.len() as u32); + self.nodes.push((v, lo, hi)); + self.unique.insert((v, lo, hi), b); + b + } + + /// Cofactors of `b` for `v`, which is `b`'s top variable or above it. + fn split(&self, b: Bool, v: u32) -> (Bool, Bool) { + match self.nodes[b.0 as usize] { + (bv, lo, hi) if bv == v => (lo, hi), + _ => (b, b), + } + } + + fn ite(&mut self, f: Bool, g: Bool, h: Bool) -> Bool { + if f == Bool::TRUE || g == h { + return g; + } + if f == Bool::FALSE { + return h; + } + if (g, h) == (Bool::TRUE, Bool::FALSE) { + return f; + } + if let Some(&r) = self.memo.get(&(f, g, h)) { + return r; + } + let top = |b: Bool| self.nodes[b.0 as usize].0; + let v = top(f).min(top(g)).min(top(h)); + let ((f0, f1), (g0, g1), (h0, h1)) = (self.split(f, v), self.split(g, v), self.split(h, v)); + let lo = self.ite(f0, g0, h0); + let hi = self.ite(f1, g1, h1); + let r = self.mk(v, lo, hi); + self.memo.insert((f, g, h), r); + r + } + + fn and(&mut self, a: Bool, b: Bool) -> Bool { + self.ite(a, b, Bool::FALSE) + } + + fn or(&mut self, a: Bool, b: Bool) -> Bool { + self.ite(a, Bool::TRUE, b) + } + + fn not(&mut self, a: Bool) -> Bool { + self.ite(a, Bool::FALSE, Bool::TRUE) + } + + fn xor(&mut self, a: Bool, b: Bool) -> Bool { + let nb = self.not(b); + self.ite(a, nb, b) + } + + /// Whether some lane can satisfy every `(b, holds)` of `all` at once: + /// `b` where `holds`, its negation where not. Yes when the search grows + /// too large to finish. + pub fn meet(&self, all: &[(Bool, bool)]) -> bool { + self.meet_seen(all, &mut Meets::default()) + } + + /// [`Self::meet`], which looks up in `seen` what earlier calls on these + /// `Bools` found out and adds what it finds. The answer is the one + /// `meet` gives. + pub fn meet_seen(&self, all: &[(Bool, bool)], seen: &mut Meets) -> bool { + self.meet_within(all, MAX_MEET, seen) + } + + /// [`Self::meet_seen`] with `budget` case splits. + fn meet_within(&self, all: &[(Bool, bool)], mut budget: usize, seen: &mut Meets) -> bool { + let mut work = all + .iter() + .map(|&(b, holds)| b.0 << 1 | u32::from(holds)) + .collect(); + self.meet_in(0, &mut work, &mut budget, seen) + } + + /// The search of [`Self::meet`] for the conditions `work[at..]` (a node + /// doubled, plus one where it must hold), which it takes off `work`. + /// + /// The search is a case split on the top variable, and the cofactors of + /// a few large functions come down to the same conditions over and over + /// (a block's reach under a mask and under its negation share most of + /// their nodes), so splitting each anew is exponential where the + /// distinct conditions are few. `seen` keeps the conditions that no lane + /// satisfies with the case splits it took to find that out: meeting + /// them again takes those splits off the budget at once. A search + /// therefore gives up exactly where one that split everything anew + /// would (nothing below such conditions ends it early, so it either + /// makes all those splits or runs out among them), and gives the same + /// answer. + fn meet_in( + &self, + at: usize, + work: &mut Vec, + budget: &mut usize, + seen: &mut Meets, + ) -> bool { + // Constants either fail or say nothing. + let mut kept = at; + for i in at..work.len() { + let (b, holds) = (work[i] >> 1, work[i] & 1 != 0); + if b > Bool::TRUE.0 { + work[kept] = work[i]; + kept += 1; + } else if (b == Bool::TRUE.0) != holds { + work.truncate(at); + return false; + } + } + work.truncate(kept); + if kept == at || *budget == 0 { + work.truncate(at); + return true; + } + // As a set: neither order nor repeats change the search. + work[at..].sort_unstable(); + let mut end = at + 1; + for i in at + 1..kept { + if work[i] != work[end - 1] { + work[end] = work[i]; + end += 1; + } + } + work.truncate(end); + if let Some(&splits) = seen.none.get(&work[at..]) { + let within = splits <= *budget; + *budget = budget.saturating_sub(splits); + work.truncate(at); + return !within; + } + let before = *budget; + *budget -= 1; + let top = |code: u32| self.nodes[(code >> 1) as usize].0; + let v = work[at..].iter().map(|&c| top(c)).min().expect("not empty"); + let mut found = false; + for value in [false, true] { + for i in at..end { + let (lo, hi) = self.split(Bool(work[i] >> 1), v); + work.push((if value { hi } else { lo }).0 << 1 | work[i] & 1); + } + if self.meet_in(end, work, budget, seen) { + found = true; + break; + } + } + if !found && seen.none.len() < MAX_MEETS { + seen.none.insert(work[at..end].into(), before - *budget); + } + work.truncate(at); + found + } + + fn implies(&mut self, a: Bool, b: Bool) -> bool { + let nb = self.not(b); + self.and(a, nb) == Bool::FALSE + } + + /// `b` with every atom born at reverse-postorder index `from` or later + /// existentially quantified: what still holds once those are redefined. + fn forget(&mut self, b: Bool, from: usize, memo: &mut Map) -> Bool { + let (v, lo, hi) = self.nodes[b.0 as usize]; + if v == TERMINAL { + return b; + } + if let Some(&r) = memo.get(&b) { + return r; + } + let lo = self.forget(lo, from, memo); + let hi = self.forget(hi, from, memo); + let r = if self.born[v as usize] >= from { + self.or(lo, hi) + } else { + self.mk(v, lo, hi) + }; + memo.insert(b, r); + r + } + + fn restrict(&mut self, b: Bool, v: u32, value: bool, memo: &mut Map) -> Bool { + let (bv, lo, hi) = self.nodes[b.0 as usize]; + if bv == TERMINAL || bv > v { + return b; + } + if bv == v { + return if value { hi } else { lo }; + } + if let Some(&r) = memo.get(&b) { + return r; + } + let l = self.restrict(lo, v, value, memo); + let h = self.restrict(hi, v, value, memo); + let r = self.mk(bv, l, h); + memo.insert(b, r); + r + } + + /// `b` with each atom that `known` decides replaced by its value. + fn given(&mut self, mut b: Bool, known: Bool) -> Bool { + for v in self.vars(b) { + let x = self.mk(v, Bool::FALSE, Bool::TRUE); + let nx = self.not(x); + if self.implies(known, x) { + b = self.restrict(b, v, true, &mut Map::default()); + } else if self.implies(known, nx) { + b = self.restrict(b, v, false, &mut Map::default()); + } + } + b + } +} + +/// How a lane leaves a block. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum LaneExit { + Jump(usize), + /// To `taken` in lanes where `when` holds. A condition over + /// [`Atom::Uniform`]s only is a uniform branch. + Branch { + when: Bool, + taken: usize, + not_taken: usize, + }, + End, + Indirect, +} + +/// A [`Program`] as one lane runs it: same blocks, per-lane branches. +#[derive(Debug, Clone)] +pub struct Structured { + pub bools: Bools, + /// Per block. + pub exits: Vec, + /// Per block and instruction: the condition, beyond reaching it, under + /// which a lane runs a vector instruction; `None` when reaching it is + /// enough (lanes outside EXEC then never get there, so a VGPR write + /// needs no old value). Always `None` for scalar instructions. + pub guards: Vec>>, + /// Per block: what holds in every lane that enters it (over forward + /// edges; a loop header forgets what its loop redefines). + pub reach: Vec, + /// The lane's bit of each lane-mask value, by its low dword's value. + pub masks: HashMap, + /// Exact Wave64 pairs for checking masks at their uses. + paired_masks: Map, + /// Wave64 masks: low dword's value by the high dword's. + pub highs: HashMap, + /// Masks (low dwords) set only in lanes whose EXEC bit is set where + /// they are written: every such lane reaches the writing block, so a + /// ballot there gives the mask as data. No split low dword, as in + /// `masks`. + pub active: HashSet, + /// Incoming lane boolean per predecessor edge (in block predecessor order) + /// for each [`Atom::Phi`] id. + pub phi_masks: HashMap>, + /// Blocks whose closing branch the whole wave takes together ([`structure_wide`]): its + /// `when` is still the lane's own bit; the wave goes by all of them. + pub wide: HashSet, + /// Per block closed by a branch on a lane mask: whether the console takes it when some + /// lane's `when` holds (`true`) or when every lane's does (`false`). + pub wave_any: Vec>, + /// SCC values a mask operation sets when some lane's bit of its result is set, with that + /// lane bit: as data such an SCC is "some lane of the wave has it". + pub scc_some: HashMap, +} + +impl Structured { + pub(crate) fn mask_bits(&self, low: Value, high: Option) -> Option { + match high { + Some(high) => self.paired_masks.get(&(low, high)), + None => self.masks.get(&low), + } + .copied() + } +} + +/// Builds the per-lane form of `program`. +pub fn structure(program: &Program) -> Result { + structure_wide(program, &HashSet::new()) +} + +/// [`structure`], with the branches that close the blocks of `wide` kept as the console has +/// them: one decision for the whole wave (`s_cbranch_execz` and `vccz`: taken when no lane's +/// bit is set; `execnz` and `vccnz`: when some lane's is; SCC of a mask operation likewise, +/// [`Structured::wave_any`]), which every lane follows. A lane +/// then learns nothing about its own bit from the way it went, so past such a branch EXEC +/// stays a guard on every vector instruction, as it is on the console. For a console wave +/// run as two host waves, which exchange that decision and can then meet (a group barrier) +/// inside the branch. +pub fn structure_wide(program: &Program, wide: &HashSet) -> Result { + let mut l = Lanes::new(program)?; + l.wide = wide.clone(); + loop { + let execs = l.masks_in_order(); + let cond = l.paths()?; + let (wrong, new_derived) = l.check_joins(&cond); + if l.b.overflow { + return Err(TOO_LARGE); + } + if wrong.is_empty() && new_derived.is_empty() { + return l.finish(&execs, &cond); + } + l.unresolved.extend(wrong); + l.derived_phis.extend(new_derived); + l.reset(); + } +} + +/// A lane mask by the values of its low and high dword (both the low one in +/// wave32). +type Key = (Value, Value); + +struct Lanes<'a> { + p: &'a Program, + order: Vec, + /// Reverse-postorder index per block. + index: Vec, + /// Per block, in predecessor order: (block, over its taken edge). + incoming: Vec>, + /// Block and instruction index writing each value. + defs: Map, + /// Block and index of each phi value. + phis: Map, + /// Mask joins found wrong when resolved to a constant: atoms instead. + unresolved: HashSet, + /// Phi ids whose joins depend on EXEC or VALU results (including along + /// back edges), carried across resets so their joins stay in `masks`. + derived_phis: HashSet, + b: Bools, + /// Masks derived from EXEC and VALU results. + masks: Map, + /// Other values read as masks: constants, uniform selects, opaque ones. + other: Map, + /// Pairs read as masks that `mask` does not see: carry-ins, and pairs + /// joins take over back edges. + seen: Vec, + /// For branches: SCC of a mask operation ("some lane is set") as the + /// lane's own bit. + scc_lane: Map, + /// Joins resolved to a constant, to check once all edges are known. + joins: Vec, + /// [`Atom::Phi`] joins created in the current pass, resolved in + /// `check_joins` and exported in `finish`. + phi_joins: Vec, + phi_join_ids: HashSet, + /// Per block: what a lane knows on entry, over forward edges only. + first: Vec, + /// Per block ending in a branch: when a lane takes it. + when: Vec>, + /// See [`Structured::active`]. + active: HashSet, + /// See [`Structured::wide`]. + wide: HashSet, + /// SCC values of [`Self::scc_lane`] that are set when EVERY lane's bit is (`s_cmp_eq` of + /// two masks: "no lane differs"); the others are set when some lane's is. + scc_every: HashSet, + /// See [`Structured::wave_any`]. + wave_any: Vec>, +} + +/// A mask join taken as `value` in every lane that reaches `block`: each +/// incoming mask held (or failed) on its edge. +struct Join { + block: usize, + /// The phi value naming the join. + id: Value, + value: bool, + derived: bool, + args: Vec, +} + +/// A mask join represented as [`Atom::Phi`], whose incoming edge masks are +/// resolved once every block (including loop back edges) has been visited. +struct PhiJoin { + block: usize, + id: Value, + derived: bool, + args: Vec, +} + +struct SopMasks { + dst: Option<(Key, Bool)>, + exec: Option<(Key, Bool)>, + /// Some operand derives from EXEC or a VALU result. + derived: bool, + /// For branches: SCC ("result is not zero") per lane. + scc: Option, +} + +const MAX_ROUNDS: usize = 256; + +impl<'a> Lanes<'a> { + fn new(p: &'a Program) -> Result { + let blocks = &p.blocks; + let order = crate::ir::reverse_postorder(blocks); + let mut index = vec![usize::MAX; blocks.len()]; + for (i, &b) in order.iter().enumerate() { + index[b] = i; + } + check_reducible(p, &order, &index)?; + let mut incoming = vec![Vec::new(); blocks.len()]; + let (mut defs, mut phis) = (Map::default(), Map::default()); + for (b, block) in blocks.iter().enumerate() { + for (k, s) in block.exit.successors().into_iter().enumerate() { + incoming[s].push((b, k == 0)); + } + for (i, phi) in block.phis.iter().enumerate() { + phis.insert(phi.value, (b, i)); + } + for (i, inst) in block.insts.iter().enumerate() { + for &(_, v) in &inst.writes { + defs.insert(v, (b, i)); + } + } + } + Ok(Lanes { + p, + order, + index, + incoming, + defs, + phis, + unresolved: HashSet::new(), + derived_phis: HashSet::new(), + b: Bools::new(), + masks: Map::default(), + other: Map::default(), + seen: Vec::new(), + scc_lane: Map::default(), + joins: Vec::new(), + phi_joins: Vec::new(), + phi_join_ids: HashSet::new(), + first: vec![Bool::FALSE; blocks.len()], + when: vec![None; blocks.len()], + active: HashSet::new(), + wide: HashSet::new(), + scc_every: HashSet::new(), + wave_any: vec![None; blocks.len()], + }) + } + + fn reset(&mut self) { + self.b = Bools::new(); + self.masks.clear(); + self.other.clear(); + self.seen.clear(); + self.scc_lane.clear(); + self.scc_every.clear(); + self.wave_any.fill(None); + self.joins.clear(); + self.phi_joins.clear(); + self.phi_join_ids.clear(); + self.first.fill(Bool::FALSE); + self.when.fill(None); + self.active.clear(); + } + + /// Lane masks, branch conditions and forward-edge knowledge, block by + /// block in reverse postorder; returns EXEC at each instruction reading it. + fn masks_in_order(&mut self) -> Vec>> { + let p = self.p; + let input = |reg| p.inputs.iter().find(|i| i.0 == reg).map(|i| i.1); + if let Some(lo) = input(Reg::S(EXEC)) { + let hi = if p.wave64 { + input(Reg::S(EXEC + 1)).unwrap_or(lo) + } else { + lo + }; + self.masks.insert((lo, hi), Bool::TRUE); + self.active.insert(lo); + } + let mut execs: Vec>> = + p.blocks.iter().map(|b| vec![None; b.insts.len()]).collect(); + for n in 0..self.order.len() { + let b = self.order[n]; + let mut c = if n == 0 { Bool::TRUE } else { Bool::FALSE }; + for k in 0..self.incoming[b].len() { + let (q, taken) = self.incoming[b][k]; + if self.index[q] < n { + let e = self.edge(self.first[q], q, taken); + c = self.b.or(c, e); + } + } + self.first[b] = c; + // EXEC joined at the block's entry holds the lanes that arrive. + for phi in &p.blocks[b].phis { + if phi.reg == Reg::S(EXEC) { + self.active.insert(phi.value); + } + } + // EXEC where known in this block (read or written so far). + let mut now = None; + for (i, inst) in p.blocks[b].insts.iter().enumerate() { + if inst.read(Reg::S(EXEC)).is_some() { + let e = self.exec(inst); + execs[b][i] = Some(e); + now = Some(e); + } + self.step(inst, now); + if let Some(k) = self.key(|r| inst.write(r), EXEC) { + now = self.masks.get(&k).or(self.other.get(&k)).copied(); + } + } + if let Exit::Branch { .. } = p.blocks[b].exit + && let Some(last) = p.blocks[b].insts.last() + { + self.when[b] = Some(self.branch(last)); + self.wave_any[b] = self.wave_kind(last); + } + } + execs + } + + /// `c` narrowed by the branch at the end of `q` towards one successor. + fn edge(&mut self, c: Bool, q: usize, taken: bool) -> Bool { + if self.wide.contains(&q) { + // the wave's decision: it says nothing about this lane's own bit + return c; + } + match self.when[q] { + Some(w) if taken => self.b.and(c, w), + Some(w) => { + let nw = self.b.not(w); + self.b.and(c, nw) + } + None => c, + } + } + + /// Joins whose constant fails on some edge, and joins that need another + /// pass because a later edge turned out to derive from EXEC or VALU. + fn check_joins(&mut self, cond: &[Bool]) -> (Vec, Vec) { + let mut wrong = Vec::new(); + let mut new_derived = Vec::new(); + let mut seen_derived = HashSet::new(); + let mut j = 0; + let mut p = 0; + // Checking an argument can resolve another join; it is checked too. + while j < self.joins.len() || p < self.phi_joins.len() { + while j < self.joins.len() { + let (block, id, value, was_derived) = ( + self.joins[j].block, + self.joins[j].id, + self.joins[j].value, + self.joins[j].derived, + ); + let mut failed = false; + for (n, a) in self.joins[j].args.clone().into_iter().enumerate() { + let (q, taken) = self.incoming[block][n]; + let e = self.edge(cond[q], q, taken); + let (mut m, d) = self.mask(a); + if !was_derived + && d + && !self.derived_phis.contains(&id) + && seen_derived.insert(id) + { + new_derived.push(id); + } + if !value { + m = self.b.not(m); + } + if !failed && !self.b.implies(e, m) { + wrong.push(id); + failed = true; + } + } + j += 1; + } + while p < self.phi_joins.len() { + let (id, was_derived) = (self.phi_joins[p].id, self.phi_joins[p].derived); + for a in self.phi_joins[p].args.clone() { + let (_, d) = self.mask(a); + if !was_derived + && d + && !self.derived_phis.contains(&id) + && seen_derived.insert(id) + { + new_derived.push(id); + } + } + p += 1; + } + } + (wrong, new_derived) + } + + fn finish( + mut self, + execs: &[Vec>], + cond: &[Bool], + ) -> Result { + let phi_joins = std::mem::take(&mut self.phi_joins); + let mut phi_masks = HashMap::with_capacity(phi_joins.len()); + for pj in phi_joins { + let incoming: Vec = pj + .args + .into_iter() + .enumerate() + .map(|(n, a)| { + let (q, taken) = self.incoming[pj.block][n]; + let e = self.edge(cond[q], q, taken); + let m = self.mask(a).0; + self.b.given(m, e) + }) + .collect(); + phi_masks.insert(pj.id, incoming); + } + let blocks = &self.p.blocks; + let b = &mut self.b; + let guards = blocks + .iter() + .enumerate() + .map(|(n, block)| { + block + .insts + .iter() + .zip(&execs[n]) + .map(|(inst, exec)| match (exec, &inst.fields) { + (None, _) + | (_, Fields::Sop { .. } | Fields::Sopp { .. } | Fields::Smem { .. }) => { + None + } + (&Some(e), _) if b.implies(cond[n], e) => None, + (&Some(e), _) => Some(b.given(e, cond[n])), + }) + .collect() + }) + .collect(); + let exits = blocks + .iter() + .enumerate() + .map(|(n, block)| match block.exit { + Exit::Jump(t) => LaneExit::Jump(t), + Exit::End => LaneExit::End, + Exit::Indirect => LaneExit::Indirect, + Exit::Branch { taken, not_taken } => LaneExit::Branch { + when: b.given(self.when[n].unwrap_or(Bool::FALSE), cond[n]), + taken, + not_taken, + }, + }) + .collect(); + if self.b.overflow { + return Err(TOO_LARGE); + } + // Exports go by low dword. A low dword read with two high dwords + // (one rewritten alone) names no one mask: it is left out, so + // lowering refuses what reads it instead of taking the other + // pair's lanes 32-63. Not where the low dword holds a number: see + // the shortcut in `mask`. + let (mut high, mut split) = (Map::default(), HashSet::new()); + let keys = self.masks.keys().chain(self.other.keys()); + for &(lo, hi) in keys.chain(&self.seen) { + if *high.entry(lo).or_insert(hi) != hi { + split.insert(lo); + } + } + self.masks.retain(|k, _| !split.contains(&k.0)); + self.active.retain(|lo| !split.contains(lo)); + Ok(Structured { + masks: self.masks.iter().map(|(&(lo, _), &m)| (lo, m)).collect(), + highs: self + .masks + .keys() + .filter(|(lo, hi)| lo != hi) + .map(|&(lo, hi)| (hi, lo)) + .collect(), + paired_masks: if self.p.wave64 { self.masks } else { Map::default() }, + active: self.active, + wide: self.wide, + wave_any: self.wave_any, + scc_some: self + .scc_lane + .iter() + .filter(|(scc, _)| !self.scc_every.contains(scc)) + .map(|(&scc, &m)| (scc, m)) + .collect(), + phi_masks, + bools: self.b, + exits, + guards, + reach: cond.to_vec(), + }) + } + + fn key(&self, value: impl Fn(Reg) -> Option, code: u8) -> Option { + let lo = value(Reg::S(code))?; + let hi = if self.p.wave64 { + value(Reg::S(code + 1))? + } else { + lo + }; + Some((lo, hi)) + } + + fn born(&self, v: Value) -> usize { + match (self.defs.get(&v), self.phis.get(&v)) { + (Some(&(b, _)), _) | (_, Some(&(b, _))) => self.index[b], + _ => 0, + } + } + + fn exec(&mut self, inst: &Inst) -> Bool { + match self.key(|r| inst.read(r), EXEC) { + Some(k) => self.mask(k).0, + None => Bool::TRUE, + } + } + + /// The mask a value pair holds, and whether it derives from EXEC or a + /// VALU result. + fn mask(&mut self, k: Key) -> (Bool, bool) { + if let Some(&m) = self.masks.get(&k) { + return (m, true); + } + if let Some(&m) = self.other.get(&k) { + return (m, false); + } + let p = self.p; + let (m, derived) = match self.join(k) { + Some(join) => join, + None => { + let (lo, hi) = (self.defs.get(&k.0).copied(), self.defs.get(&k.1).copied()); + let def = |d: Option<(usize, usize)>| d.map(|(b, i)| &p.blocks[b].insts[i]); + let m = match (lo, hi) { + (Some(at), Some(hi)) if at == hi => def(lo) + .and_then(|i| self.sop(i)) + .and_then(|r| r.dst) + .map(|d| d.1), + _ => None, + }; + // What an EXEC write the pass does not follow leaves there. + let exec_write = |d: Option<(usize, usize)>, v: Value| { + def(d).is_some_and(|i| { + i.write(Reg::S(EXEC)) == Some(v) || i.write(Reg::S(EXEC + 1)) == Some(v) + }) + }; + let derived = exec_write(lo, k.0) || exec_write(hi, k.1); + // shortcut: the atom names the pair by its low dword, and + // lowering takes the high dword written beside it. For halves + // written apart (two `s_mov_b32`) lanes 32-63 are wrong unless + // lowering has no value for the low dword (EXEC, compares) + // and refuses. Give the atom both dwords when such code + // turns up. + let m = m.unwrap_or_else(|| { + let born = self.born(k.0); + self.b.atom(Atom::Opaque(k.0), born) + }); + (m, derived) + } + }; + let cache = if derived { + &mut self.masks + } else { + &mut self.other + }; + cache.insert(k, m); + (m, derived) + } + + /// A mask joined by phis at a block entry, and whether a mask coming in + /// on a forward edge derives from EXEC or a VALU result. Where every + /// lane arriving so far has the incoming mask set (or clear), the join + /// is that constant, for a lane can only read it after arriving. + fn join(&mut self, k: Key) -> Option<(Bool, bool)> { + let p = self.p; + let (lo, hi) = (self.phis.get(&k.0).copied(), self.phis.get(&k.1).copied()); + let block = match (lo, hi) { + (Some((a, _)), Some((b, _))) if a != b => return None, + (Some((b, _)), _) | (_, Some((b, _))) => b, + _ => return None, + }; + let target = &p.blocks[block]; + let arg = |phi: Option<(usize, usize)>, own: Value, n: usize| { + phi.map_or(own, |(_, i)| target.phis[i].args[n]) + }; + let args: Vec = (0..target.preds.len()) + .map(|n| (arg(lo, k.0, n), arg(hi, k.1, n))) + .collect(); + let id = lo.map_or(k.1, |_| k.0); + let mut derived = self.derived_phis.contains(&id); + // (edge condition, mask) per forward edge; back edges come later. + let mut forward = Vec::new(); + for (n, &a) in args.iter().enumerate() { + let (q, taken) = self.incoming[block][n]; + if self.index[q] < self.index[block] { + let (m, d) = self.mask(a); + derived |= d; + let e = self.edge(self.first[q], q, taken); + forward.push((e, m)); + } else { + self.seen.push(a); + } + } + if forward.len() == args.len() + && let Some(&(_, m)) = forward.first() + && forward.iter().all(|f| f.1 == m) + { + return Some((m, derived)); + } + if !self.unresolved.contains(&id) { + for value in [true, false] { + let b = &mut self.b; + let holds = forward.iter().all(|&(e, m)| { + let m = if value { m } else { b.not(m) }; + b.implies(e, m) + }); + if holds { + self.joins.push(Join { + block, + id, + value, + derived, + args, + }); + let m = if value { Bool::TRUE } else { Bool::FALSE }; + return Some((m, derived)); + } + } + } + if self.phi_join_ids.insert(id) { + self.phi_joins.push(PhiJoin { + block, + id, + derived, + args, + }); + } + let born = self.index[block]; + Some((self.b.atom(Atom::Phi(id), born), derived)) + } + + fn operand(&mut self, inst: &Inst, op: &Operand) -> Option<(Bool, bool)> { + let wave64 = self.p.wave64; + let constant = |b: &mut Bools, v: u64| { + let v = if wave64 { v } else { v & 0xFFFF_FFFF }; + match v { + 0 => Bool::FALSE, + _ if v == u64::MAX >> (32 * u8::from(!wave64)) => Bool::TRUE, + _ => b.atom(Atom::Constant(v), 0), + } + }; + Some(match *op { + Operand::Scalar { code, .. } if code != NULL => { + let k = self.key(|r| inst.read(r), code)?; + self.mask(k) + } + Operand::Const(c @ 128..=208) => { + let v = if c <= 192 { + i64::from(c) - 128 + } else { + 192 - i64::from(c) + }; + (constant(&mut self.b, v as u64), false) + } + Operand::Literal(x) => (constant(&mut self.b, u64::from(x)), false), + _ => return None, + }) + } + + /// Lane-mask meaning of a lane-width scalar operation. + fn sop(&mut self, inst: &Inst) -> Option { + let Fields::Sop { dst, src, .. } = &inst.fields else { + return None; + }; + let width = if self.p.wave64 { "_b64" } else { "_b32" }; + let op = inst.name().strip_prefix("s_")?.strip_suffix(width)?; + let dst = match dst { + Some(Operand::Scalar { code, .. }) if *code != NULL => { + self.key(|r| inst.write(r), *code) + } + _ => None, + }; + let exec_out = self.key(|r| inst.write(r), EXEC); + let (save, f) = match (op.strip_suffix("_saveexec"), op.strip_suffix("_wrexec")) { + (Some(f), _) => (Some(true), f), + (_, Some(f)) => (Some(false), f), + _ => (None, op), + }; + let mut derived = exec_out.is_some() || save.is_some(); + let mut arg = |n: usize, l: &mut Self| { + let (m, d) = l.operand(inst, src.get(n)?)?; + derived |= d; + Some(m) + }; + if let Some(saveexec) = save { + let s = arg(0, self)?; + let exec = self.exec(inst); + let new = self.combine(f, s, exec)?; + let saved = if saveexec { exec } else { new }; + return Some(SopMasks { + dst: dst.map(|d| (d, saved)), + exec: exec_out.map(|e| (e, new)), + derived, + scc: Some(new), + }); + } + let (result, scc) = match op { + "mov" => (arg(0, self)?, None), + "not" => { + let a = arg(0, self)?; + let r = self.b.not(a); + (r, Some(r)) + } + "wqm" => { + let a = arg(0, self)?; + let lo = dst.or(exec_out)?.0; + let born = self.born(lo); + let q = self.b.atom(Atom::Quad(lo), born); + let r = self.b.or(a, q); + (r, Some(r)) + } + "cselect" => { + let (a, c) = (arg(0, self)?, arg(1, self)?); + let scc = inst.read(Reg::Scc)?; + if self.clear_after_loop(scc) { + (c, None) + } else { + let born = self.born(scc); + let u = self.b.atom(Atom::Uniform(scc), born); + (self.b.ite(u, a, c), None) + } + } + _ => { + let (a, c) = (arg(0, self)?, arg(1, self)?); + let r = self.combine(op, a, c)?; + (r, Some(r)) + } + }; + Some(SopMasks { + dst: dst.map(|d| (d, result)), + exec: exec_out.map(|e| (e, result)), + derived, + scc, + }) + } + + /// Whether SCC value `scc` is clear wherever it is read: the instruction before an + /// `s_cbranch_execnz` that closes a loop wrote it as "the EXEC it leaves is not + /// empty" (`s_andn2_wrexec`, say), and the wave leaves `do { .. } while (EXEC)` + /// with EXEC empty. A read inside the loop or behind another way out of it sees a + /// join of this value, not the value itself. + fn clear_after_loop(&self, scc: Value) -> bool { + let Some(&(b, i)) = self.defs.get(&scc) else { + return false; + }; + let block = &self.p.blocks[b]; + let (Some(writer), Some(last)) = (block.insts.get(i), block.insts.last()) else { + return false; + }; + let exec = writer.write(Reg::S(EXEC)); + let back = match block.exit { + Exit::Branch { taken, .. } => self.index[taken] <= self.index[b], + _ => false, + }; + back && i + 2 == block.insts.len() + && exec.is_some() + && last.name() == "s_cbranch_execnz" + && last.read(Reg::S(EXEC)) == exec + && (!self.p.wave64 || last.read(Reg::S(EXEC + 1)) == writer.write(Reg::S(EXEC + 1))) + } + + fn combine(&mut self, f: &str, a: Bool, c: Bool) -> Option { + let b = &mut self.b; + Some(match f { + "and" => b.and(a, c), + "or" => b.or(a, c), + "xor" => b.xor(a, c), + "andn2" => { + let nc = b.not(c); + b.and(a, nc) + } + "orn2" => { + let nc = b.not(c); + b.or(a, nc) + } + "andn1" => { + let na = b.not(a); + b.and(na, c) + } + "orn1" => { + let na = b.not(a); + b.or(na, c) + } + "nand" => { + let r = b.and(a, c); + b.not(r) + } + "nor" => { + let r = b.or(a, c); + b.not(r) + } + "xnor" => { + let r = b.xor(a, c); + b.not(r) + } + _ => return None, + }) + } + + /// Records the masks `inst` defines; `exec` is EXEC there, if known. + fn step(&mut self, inst: &Inst, exec: Option) { + let name = inst.name(); + match &inst.fields { + Fields::Sop { src, .. } => { + let mut takes_mask = false; + for s in src { + if let Operand::Scalar { code, .. } = *s + && code != NULL + && let Some(k) = self.key(|r| inst.read(r), code) + { + let phi = self.phis.contains_key(&k.0) || self.phis.contains_key(&k.1); + takes_mask |= self.masks.contains_key(&k) || phi && self.mask(k).1; + } + } + let touches_exec = + inst.write(Reg::S(EXEC)).is_some() || inst.read(Reg::S(EXEC)).is_some(); + if (takes_mask || touches_exec) + && let Some(r) = self.sop(inst).filter(|r| r.derived) + { + for (k, m) in r.dst.into_iter().chain(r.exec) { + self.masks.insert(k, m); + // EXEC itself holds the lanes that run here. + if r.exec.is_some_and(|e| e.0 == k) + || exec.is_some_and(|e| self.b.implies(m, e)) + { + self.active.insert(k.0); + } + } + if let (Some(scc), Some(m)) = (inst.write(Reg::Scc), r.scc) { + self.scc_lane.insert(scc, m); + } + } + // `s_cmp_eq/lg` of a mask: "no lane differs" per lane. + let width = if self.p.wave64 { "64" } else { "32" }; + if takes_mask + && let (Some(rest), Some(scc)) = + (name.strip_prefix("s_cmp_"), inst.write(Reg::Scc)) + && rest + .strip_suffix(width) + .is_some_and(|r| r == "eq_u" || r == "lg_u") + && let [a, c] = &src[..] + && let (Some((a, _)), Some((c, _))) = + (self.operand(inst, a), self.operand(inst, c)) + { + let ne = self.b.xor(a, c); + let m = if rest.starts_with("eq") { + self.b.not(ne) + } else { + ne + }; + self.scc_lane.insert(scc, m); + if rest.starts_with("eq") { + self.scc_every.insert(scc); + } + } + // `s_bcnt1` of a mask every running lane sees alike (EXEC under a scalar + // condition, or EXEC itself): its SCC, "some lane is set", is each lane's own + // bit. A branch on it then reads no ballot. + if takes_mask + && name.starts_with("s_bcnt1_i32_b") + && let Some(scc) = inst.write(Reg::Scc) + && let [a] = &src[..] + && let Some((m, true)) = self.operand(inst, a) + { + let e = exec.unwrap_or(Bool::TRUE); + let own = self.b.given(m, e); + if self.b.implies(m, e) + && self.b.support(own).iter().all(|a| matches!(a, Atom::Uniform(_))) + { + self.scc_lane.insert(scc, own); + } + } + } + Fields::Valu(v) => { + let exec = self.exec(inst); + let lane = |l: &mut Self, k: Key| { + let born = l.born(k.0); + let a = l.b.atom(Atom::Lane(k.0), born); + let m = l.b.and(exec, a); + l.masks.insert(k, m); + l.active.insert(k.0); + }; + // A select reads a mask nothing else may: a join of compare + // results is resolved here, as for EXEC. A carry-in is only + // recorded for `finish`: resolving its join would turn a + // refusal into a per-lane phi, wrong after a divergent branch. + if (name == "v_cndmask_b32" || name.contains("_co_ci_")) + && let Some(&Operand::Scalar { code, .. }) = v.src.get(2) + && code != NULL + && let Some(k) = self.key(|r| inst.read(r), code) + { + if name == "v_cndmask_b32" { + self.mask(k); + } else { + self.seen.push(k); + } + } + if matches!(name, "v_div_fmas_f32" | "v_div_fmas_f64") + && let Some(k) = self.key(|r| inst.read(r), VCC) + { + self.mask(k); + } + if name.starts_with("v_cmpx") { + if let Some(k) = self.key(|r| inst.write(r), EXEC) { + lane(self, k); + } + } else { + let compare = v.dst.filter(|_| name.starts_with("v_cmp")); + for op in compare.iter().chain(&v.carry) { + if let Operand::Scalar { code, .. } = *op + && let Some(k) = self.key(|r| inst.write(r), code) + { + lane(self, k); + } + } + } + } + _ => {} + } + } + + /// The per-lane condition under which a block's closing branch is taken. + /// How the console decides the branch `inst` on a lane mask, in terms of the lanes' own + /// `when` ([`Self::branch`]): taken when some lane's holds (`true`) or when every lane's + /// does (`false`). `execnz`/`vccnz` ask for some set bit, `execz`/`vccz` for none; SCC + /// of a mask operation is "some lane's bit is set", SCC of `s_cmp_eq` of two masks is + /// "every lane's is" ([`Self::scc_every`]), and `scc0` branches on the opposite. None + /// for a branch on a scalar condition. + fn wave_kind(&self, inst: &Inst) -> Option { + match inst.name() { + "s_cbranch_execnz" | "s_cbranch_vccnz" => Some(true), + "s_cbranch_execz" | "s_cbranch_vccz" => Some(false), + n @ ("s_cbranch_scc0" | "s_cbranch_scc1") => { + let scc = inst.read(Reg::Scc)?; + self.scc_lane.get(&scc)?; + // set: SCC is 1 when some lane's bit is set (every lane's, for a compare) + let every = self.scc_every.contains(&scc); + Some((n == "s_cbranch_scc1") != every) + } + _ => None, + } + } + + fn branch(&mut self, inst: &Inst) -> Bool { + let exec = self.exec(inst); + match inst.name() { + "s_cbranch_execz" => self.b.not(exec), + "s_cbranch_execnz" => exec, + n @ ("s_cbranch_vccz" | "s_cbranch_vccnz") => { + let vcc = match self.key(|r| inst.read(r), VCC) { + Some(k) => self.mask(k).0, + None => Bool::FALSE, + }; + let any = self.b.and(vcc, exec); + if n.ends_with("nz") { + any + } else { + self.b.not(any) + } + } + n => { + let Some(scc) = inst.read(Reg::Scc) else { + return Bool::FALSE; + }; + let set = match self.scc_lane.get(&scc) { + Some(&m) => m, + None => { + let born = self.born(scc); + self.b.atom(Atom::Uniform(scc), born) + } + }; + if n == "s_cbranch_scc1" { + set + } else { + self.b.not(set) + } + } + } + } + + /// What a lane knows on entering each block, to a fixpoint. A loop + /// header forgets what the back edge says about atoms the loop redefines. + fn paths(&mut self) -> Result, ShaderError> { + let n = self.p.blocks.len(); + let mut cond = vec![Bool::FALSE; n]; + if let Some(&entry) = self.order.first() { + cond[entry] = Bool::TRUE; + } + for _ in 0..MAX_ROUNDS { + let mut changed = false; + for i in 1..self.order.len() { + let s = self.order[i]; + let mut c = Bool::FALSE; + for k in 0..self.incoming[s].len() { + let (q, taken) = self.incoming[s][k]; + let mut e = self.edge(cond[q], q, taken); + if i <= self.index[q] { + e = self.b.forget(e, i, &mut Map::default()); + } + c = self.b.or(c, e); + } + if c != cond[s] { + cond[s] = c; + changed = true; + } + } + if self.b.overflow { + return Err(TOO_LARGE); + } + if !changed { + return Ok(cond); + } + } + Err(ShaderError::Isa { + offset: 0, + reason: "lane conditions do not settle", + }) + } +} + +const TOO_LARGE: ShaderError = ShaderError::Isa { + offset: 0, + reason: "lane conditions too large", +}; + +/// `ir::build` splits irreducible loops; checked again because everything +/// here assumes a reducible graph. +fn check_reducible(p: &Program, order: &[usize], index: &[usize]) -> Result<(), ShaderError> { + match crate::ir::irreducible_edge(&p.blocks, order, index) { + Some((from, _)) => Err(ShaderError::Unsupported { + offset: p.blocks[from].offset, + what: "irreducible control flow", + }), + None => Ok(()), + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::ir; + + const S_ENDPGM: u32 = 0xBF81_0000; + + fn build(words: &[u32], wave64: bool) -> Program { + let code: Vec = words.iter().flat_map(|w| w.to_le_bytes()).collect(); + ir::build(&code, wave64, 256).unwrap() + } + + fn guarded(s: &Structured) -> usize { + s.guards.iter().flatten().filter(|g| g.is_some()).count() + } + + /// The search of [`Bools::meet`] with every case split made anew, as it + /// was before [`Meets`]. + fn meet_anew(b: &Bools, mut all: Vec<(Bool, bool)>, budget: &mut usize) -> bool { + let fails = |&(b, holds): &(Bool, bool)| b == if holds { Bool::FALSE } else { Bool::TRUE }; + if all.iter().any(fails) { + return false; + } + all.retain(|&(b, _)| b != Bool::FALSE && b != Bool::TRUE); + if all.is_empty() || *budget == 0 { + return true; + } + *budget -= 1; + let top = |x: Bool| b.nodes[x.0 as usize].0; + let v = all.iter().map(|&(x, _)| top(x)).min().expect("not empty"); + [false, true].into_iter().any(|value| { + let next = all + .iter() + .map(|&(x, holds)| { + let (lo, hi) = b.split(x, v); + (if value { hi } else { lo }, holds) + }) + .collect(); + meet_anew(b, next, budget) + }) + } + + #[test] + fn a_search_that_remembers_answers_as_one_made_anew() { + // Functions of 12 variables put together at random, and conditions + // of two to five of them (repeats and constants among them), under + // budgets that run out early, late and never: the answer, and where + // no lane is found the budget left, are those of the search that + // remembers nothing; with what one `Meets` gathered over all of + // them, and with an empty one. + let mut b = Bools::new(); + let mut state = 0x9E37_79B9_7F4A_7C15_u64; + let mut random = move |n: usize| { + state ^= state << 13; + state ^= state >> 7; + state ^= state << 17; + (state % n as u64) as usize + }; + let mut f: Vec = (0..12).map(|i| b.atom(Atom::Constant(i + 2), 0)).collect(); + f.extend([Bool::FALSE, Bool::TRUE]); + for _ in 0..120 { + let (x, y) = (f[random(f.len())], f[random(f.len())]); + let made = match random(4) { + 0 => b.and(x, y), + 1 => b.or(x, y), + 2 => b.xor(x, y), + _ => b.not(x), + }; + f.push(made); + } + let mut seen = Meets::default(); + let (mut none, mut some, mut gave_up) = (0, 0, 0); + for _ in 0..1500 { + let all: Vec<(Bool, bool)> = (0..2 + random(4)) + .map(|_| (f[random(f.len())], random(2) == 0)) + .collect(); + for budget in [0, 1, 2, 3, 5, 9, 20, 60, 250, 1000, MAX_MEET] { + let mut left = budget; + let anew = meet_anew(&b, all.clone(), &mut left); + for fresh in [false, true] { + let mut empty = Meets::default(); + let seen = if fresh { &mut empty } else { &mut seen }; + let mut work = all + .iter() + .map(|&(x, holds)| x.0 << 1 | u32::from(holds)) + .collect(); + let mut mine = budget; + let found = b.meet_in(0, &mut work, &mut mine, seen); + assert_eq!(found, anew, "{all:?} within {budget}"); + assert!(work.is_empty()); + if !found { + assert_eq!(mine, left, "{all:?} within {budget}"); + } + } + assert_eq!(b.meet_within(&all, budget, &mut seen), anew); + if !anew { + none += 1; + } else if meet_anew(&b, all.clone(), &mut usize::MAX.clone()) { + some += 1; + } else { + gave_up += 1; + } + } + } + // All three outcomes came up, and searches were remembered. + assert!( + none > 100 && some > 100 && gave_up > 100, + "{none} {some} {gave_up}" + ); + assert!(seen.none.len() > 100); + } + + #[test] + fn divergent_if_becomes_a_lane_branch() { + let p = build( + &[ + 0x7D84_0080, // v_cmp_eq_u32 vcc, 0, v0 + 0xBE80_3C6A, // s_and_saveexec_b32 s0, vcc_lo + 0xBF88_0001, // s_cbranch_execz -> 16 + 0x7E02_0280, // v_mov_b32 v1, 0 + 0x887E_007E, // 16: s_or_b32 exec_lo, exec_lo, s0 + 0x7E04_0280, // v_mov_b32 v2, 0 + S_ENDPGM, + ], + false, + ); + let s = structure(&p).unwrap(); + let LaneExit::Branch { + when, + taken: 2, + not_taken: 1, + } = s.exits[0] + else { + panic!("{:?}", s.exits) + }; + // Skipped exactly where the compare fails. + let cmp = p.blocks[0].insts[0].write(Reg::S(VCC)).unwrap(); + assert_eq!( + s.bools.node(when), + Some((Atom::Lane(cmp), Bool::TRUE, Bool::FALSE)) + ); + assert_eq!(guarded(&s), 0, "{:?}", s.guards); + } + + #[test] + fn exec_narrowed_without_a_branch_leaves_a_guard() { + let p = build( + &[ + 0x7DA4_0080, // v_cmpx_eq_u32 exec, 0, v0 + 0x7E02_0280, // v_mov_b32 v1, 0 + S_ENDPGM, + ], + true, + ); + let s = structure(&p).unwrap(); + assert_eq!(s.guards[0][0], None, "the compare runs in every lane"); + let g = s.guards[0][1].expect("guard"); + assert!(matches!(s.bools.support(g)[..], [Atom::Lane(_)])); + } + + #[test] + fn divergent_loop_exits_per_lane() { + let p = build( + &[ + 0xBE82_0480, // s_mov_b64 s[2:3], 0 + 0x4A00_0081, // 4: v_add_nc_u32 v0, 1, v0 + 0x7D84_0080, // v_cmp_eq_u32 vcc, 0, v0 + 0x8882_026A, // s_or_b64 s[2:3], vcc, s[2:3] + 0x8AFE_027E, // s_andn2_b64 exec, exec, s[2:3] + 0xBF89_FFFB, // s_cbranch_execnz -> 4 + 0x88FE_027E, // s_or_b64 exec, exec, s[2:3] + 0x7E02_0280, // v_mov_b32 v1, 0 + S_ENDPGM, + ], + true, + ); + let s = structure(&p).unwrap(); + assert_eq!(guarded(&s), 0, "{:?}", s.guards); + let LaneExit::Branch { + when, + taken: 1, + not_taken: 2, + } = s.exits[1] + else { + panic!("{:?}", s.exits) + }; + // Back while the lane's compare fails. + assert!(matches!( + s.bools.node(when), + Some((Atom::Lane(_), Bool::TRUE, Bool::FALSE)) + )); + } + + /// `s_cselect` on the SCC a lane loop ended with (the blend-shape skinning + /// programs): the loop is left when no lane remains, so the select takes + /// its second operand; it was a uniform atom whose value no lane has. + #[test] + fn a_select_on_the_condition_a_lane_loop_ended_with_takes_its_second_operand() { + let cnd = 256 | (256 << 9) | (3 << 18); + let p = build( + &[ + 0xBE83_037E, // 0: s_mov_b32 s3, exec_lo + 0xBE9C_037E, // s_mov_b32 s28, exec_lo + 0x7E3A_0507, // 8: v_readfirstlane_b32 s29, v7 + 0x7DA4_0E1D, // v_cmpx_eq_u32 exec_lo, s29, v7 + 0xBE9C_471C, // s_andn2_wrexec_b32 s28, s28 + 0xBF89_FFFC, // s_cbranch_execnz -> 8 + 0xBEFE_0303, // s_mov_b32 exec_lo, s3 + 0x8503_807E, // s_cselect_b32 s3, exec_lo, 0 + 0xD501_0001, + cnd, // v_cndmask_b32 v1, v0, v0, s3 + S_ENDPGM, + ], + false, + ); + let s = structure(&p).unwrap(); + let select = p + .blocks + .iter() + .flat_map(|b| &b.insts) + .find(|i| i.name() == "s_cselect_b32") + .expect("the select"); + let mask = select.write(Reg::S(3)).unwrap(); + assert_eq!(s.masks.get(&mask), Some(&Bool::FALSE)); + } + + #[test] + fn scalar_branches_stay_uniform() { + let p = build( + &[ + 0xBF06_0100, // s_cmp_eq_u32 s0, s1 + 0xBF85_0001, // s_cbranch_scc1 -> 12 + 0x7E02_0280, // v_mov_b32 v1, 0 + S_ENDPGM, // 12 + ], + true, + ); + let s = structure(&p).unwrap(); + let LaneExit::Branch { when, .. } = s.exits[0] else { + panic!() + }; + assert!(matches!(s.bools.support(when)[..], [Atom::Uniform(_)])); + assert_eq!(guarded(&s), 0); + } + + #[test] + fn a_mask_whose_high_dword_is_rewritten_is_not_the_compare() { + for reader in [ + 0x0202_0480, // v_cndmask_b32 v1, 0, v2, vcc + 0x5002_0480, // v_add_co_ci_u32 v1, vcc, 0, v2, vcc + ] { + let p = build( + &[ + 0x7D84_0080, // v_cmp_eq_u32 vcc, 0, v0 + 0xBEEB_0380, // s_mov_b32 vcc_hi, 0 + reader, + S_ENDPGM, + ], + true, + ); + let s = structure(&p).unwrap(); + let lo = p.blocks[0].insts[2].read(Reg::S(VCC)).unwrap(); + assert_eq!(p.blocks[0].insts[0].write(Reg::S(VCC)), Some(lo)); + // The reader sees (compare low dword, 0): lanes 32-63 are clear. + // The mask exported for that low dword must not be the compare. + assert_ne!( + s.masks.get(&lo).and_then(|&m| s.bools.node(m)), + Some((Atom::Lane(lo), Bool::FALSE, Bool::TRUE)), + "{reader:#x}: vcc_hi was zeroed after the compare" + ); + } + } + + #[test] + fn a_mask_joined_over_a_back_edge_with_a_rewritten_high_dword_is_not_the_compare() { + let p = build( + &[ + 0x7D84_0080, // v_cmp_eq_u32 vcc, 0, v0 + 0x0202_0480, // 4: v_cndmask_b32 v1, 0, v2, vcc + 0x7D84_0280, // v_cmp_eq_u32 vcc, 0, v1 + 0xBEEB_0380, // s_mov_b32 vcc_hi, 0 + 0xBF85_FFFC, // s_cbranch_scc1 -> 4 + S_ENDPGM, + ], + true, + ); + let s = structure(&p).unwrap(); + // The select reads the loop header's join; over the back edge it + // takes (compare low dword, 0), which only the join sees. + let lo = p.blocks[1].insts[1].write(Reg::S(VCC)).unwrap(); + assert_ne!( + s.masks.get(&lo).and_then(|&m| s.bools.node(m)), + Some((Atom::Lane(lo), Bool::FALSE, Bool::TRUE)) + ); + } + + #[test] + fn irreducible_loops_are_split() { + let p = build( + &[ + 0xBF06_0100, // s_cmp_eq_u32 s0, s1 + 0xBF85_0001, // s_cbranch_scc1 -> 12, into the loop's middle + 0x8002_8102, // 8: s_add_u32 s2, s2, 1 + 0xBF84_FFFE, // 12: s_cbranch_scc0 -> 8 + S_ENDPGM, + ], + false, + ); + // The loop keeps 12 as its header; the entry into 8 gets a copy of it. + let copy = &p.blocks[4]; + assert_eq!((copy.offset, copy.exit), (8, ir::Exit::Jump(2))); + assert_eq!(p.blocks[0].exit.successors(), [2, 4]); + assert_eq!(p.blocks[1].preds, [2]); + assert!(structure(&p).is_ok()); + } + + #[test] + fn mask_phi_joining_constant_and_compare_records_edge_bools() { + let cnd = 258 | (259 << 9) | (2 << 18); + let p = build( + &[ + 0xBF06_8000, // 0: s_cmp_eq_u32 s0, 0 + 0xBF85_0002, // 4: s_cbranch_scc1 -> 16 + 0xBE82_0380, // 8: s_mov_b32 s2, 0 + 0xBF82_0002, // 12: s_branch -> 24 + 0xD4C2_0002, + 0x0002_0080, // 16: v_cmp_eq_u32 s2, 0, v0 + 0xD501_0001, + cnd, // 24: v_cndmask_b32 v1, v2, v3, s2 + S_ENDPGM, + ], + false, + ); + let s = structure(&p).unwrap(); + let phi = p + .blocks + .iter() + .flat_map(|b| &b.phis) + .find(|phi| phi.reg == Reg::S(2)) + .expect("mask phi for s2"); + assert_eq!( + s.masks.get(&phi.value).and_then(|&m| s.bools.node(m)), + Some((Atom::Phi(phi.value), Bool::FALSE, Bool::TRUE)) + ); + let edges = &s.phi_masks[&phi.value]; + assert_eq!(edges.len(), 2); + assert!(edges.contains(&Bool::FALSE), "{edges:?}"); + assert!( + edges + .iter() + .any(|&e| matches!(s.bools.support(e)[..], [Atom::Lane(_)])), + "{edges:?}" + ); + } + + #[test] + fn loop_mask_accumulator_from_zero_tracks_phi_and_edges() { + let cnd = 258 | (259 << 9) | (2 << 18); + let p = build( + &[ + 0xBE82_0480, // 0: s_mov_b64 s[2:3], 0 + 0xBE84_0380, // 4: s_mov_b32 s4, 0 + 0xD501_0001, + cnd, // 8: v_cndmask_b32 v1, v2, v3, s[2:3] + 0x7D84_0080, // 16: v_cmp_eq_u32 vcc, 0, v0 + 0x8882_026A, // 20: s_or_b64 s[2:3], vcc, s[2:3] + 0x8004_8104, // 24: s_add_u32 s4, s4, 1 + 0xBF0A_8404, // 28: s_cmp_lt_u32 s4, 4 + 0xBF85_FFF9, // 32: s_cbranch_scc1 -> 8 + 0xD501_0004, + cnd, // 36: v_cndmask_b32 v4, v2, v3, s[2:3] + S_ENDPGM, + ], + true, + ); + let s = structure(&p).unwrap(); + let phi = p + .blocks + .iter() + .flat_map(|b| &b.phis) + .find(|phi| phi.reg == Reg::S(2)) + .expect("loop mask phi for s[2:3]"); + assert!(s.masks.contains_key(&phi.value)); + let edges = &s.phi_masks[&phi.value]; + assert_eq!(edges.len(), 2); + assert!(edges.contains(&Bool::FALSE), "{edges:?}"); + assert!(edges.iter().any(|&e| { + let sup = s.bools.support(e); + sup.contains(&Atom::Phi(phi.value)) && sup.iter().any(|a| matches!(a, Atom::Lane(_))) + })); + } + + #[test] + fn loop_mask_phi_reset_to_constant_on_back_edge() { + let cnd = 258 | (259 << 9) | (2 << 18); + let p = build( + &[ + 0xD4C2_0002, + 0x0002_0080, // 0: v_cmp_eq_u32 s2, 0, v0 + 0xBE84_0380, // 8: s_mov_b32 s4, 0 + 0xD501_0001, + cnd, // 12: v_cndmask_b32 v1, v2, v3, s2 + 0xBE82_0380, // 20: s_mov_b32 s2, 0 + 0x8004_8104, // 24: s_add_u32 s4, s4, 1 + 0xBF0A_8404, // 28: s_cmp_lt_u32 s4, 4 + 0xBF85_FFFA, // 32: s_cbranch_scc1 -> 12 + S_ENDPGM, + ], + false, + ); + let s = structure(&p).unwrap(); + let phi = p + .blocks + .iter() + .flat_map(|b| &b.phis) + .find(|phi| phi.reg == Reg::S(2)) + .expect("loop mask phi for s2"); + assert!(s.masks.contains_key(&phi.value)); + let edges = &s.phi_masks[&phi.value]; + assert_eq!(edges.len(), 2); + assert!(edges.contains(&Bool::FALSE), "{edges:?}"); + assert!( + edges + .iter() + .any(|&e| matches!(s.bools.support(e)[..], [Atom::Lane(_)])), + "{edges:?}" + ); + } +} diff --git a/docs/README.md b/docs/README.md deleted file mode 100644 index 923b50a24..000000000 --- a/docs/README.md +++ /dev/null @@ -1,105 +0,0 @@ -# Documentation - -These notes record what has been measured in the local Xbox Series package and what is still open. -The headline counts are the measured numbers at the time of the note; the linked page has the -method, scope and caveats. No game data is included. - -## Start here - -| Document | What it covers | -|---|---| -| [design.md](design.md) | Overall project design, asset status, translator contract and open blockers. | -| [related_projects.md](related_projects.md) | Prior art we may read and the licence boundaries on it. | -| [ztrx-gap-analysis.md](ztrx-gap-analysis.md) | ztrx against the runtime, from source: licence, gap table; not run. | -| [rpf.md](rpf.md) | RPF9 archive layout, the carve tools and the unreadable encrypted TOC. | -| [linux.md](linux.md) | Linux in one page: what runs natively and what runs under Wine or Proton, the Ubuntu packages, `Build.sh`, the runtime cross-build, and why there is no native Linux `gta6rt`. | -| [testing.md](testing.md) | Running the GPU tests on your own GPU: setup per OS, wave64 emulation, running without a GPU on Mesa llvmpipe, and known problems. | -| [modding.md](modding.md) | The mod format: `mods//mod.json`, checked and loaded in name order by `gta6rt`; a swap takes effect once the game's archetype lookup is hooked (needs the executable, RT-5). A mod names game models and holds no game data. | -| [progress_dashboard.md](progress_dashboard.md) | A local page of what works, what changed since it last passed and what blocks next: unit and runtime tests, the translator contract by confirmation method, measured imports, corpus counts and, with `--github`, CI and the D3D- items (`tools/progress_dashboard.py`). | - -## Archives and assets - -| Document | Measured content | -|---|---| -| [models.md](models.md) | 382,781 models (0 decode failures) at the `e293917` pin, including 159,511 drawable-dictionary children; 55,417 fragments, 89,887 bone-bound and 2,636,248,990 triangles over all ten archives (`levels.rpf` from a full export); the re-count table is in models.md. | -| [strand_grooms.md](strand_grooms.md) | GPU strand grooms (`smh`): hair, beards, brows and fur are groom LOD resources consumed by the `smh_*` compute passes, not triangle drawables (each is a one-triangle stub); 5,751 assets / 20,046 LOD resources, 0 decode errors, 902,456,856 GPU buffer bytes and 112,491,621 strands; the measured resource layout, the `smh_gen_1` Class 0 strand scattering RNG, barycentric strand interpolation and split-chain rejoin, and a GLB export (`tools/smh_groom.py`). | -| [character_models.md](character_models.md) | `packs.rpf` character parts at `e293917`: 26,585 rows / 11,335 unique names, 2,865 fragments (all a flat 25-vertex / 32-triangle 5x5 bounds grid at z=0), Lucia's 22 named records and the decoded 13-part export, the `player_story000_00` drawable set, slot-name token counts, texture coverage (184/215), and what is not decoded (fragment children, ped variation, hair, bind pose). | -| [character_skeleton.md](character_skeleton.md) | Character `.#ft` fragments: the 597-name shared skeleton table (596 `joaat32` hashes), the 597-record instance tree with 580 measured parents, the model-side bone-hash mapping, and the measured vertex joint-index/skin-weight layouts (`tools/skin_streams.py`); the default bone transforms compose to the stored inverse bind matrices, and `tools/anim_glb.py` exports a skinned part with clips as an animated GLB. | -| [ped_catalogues.md](ped_catalogues.md) | Ped and wardrobe appearance catalogues: one schema rooted at struct `0x8dcb4cf5`, in `0DRP` v122 resources in `packs.rpf` and in the standalone `PSIN` player/wardrobe catalogue, with both framings' 1-based block table and 64-bit pointer encoding (`block = ptr & 0xfffff`, `offset = ptr >> 20`); 2,716 catalogues and 632,778 presets (612,950 in resource-packed `0DRP`, 19,828 in one standalone `PSIN`), 345,780 presets with a parent (chain depth 3, 0 cycles), 896,115 `0x37e52277` states resolved, 0 parse errors (`tools/ped_catalogues.py`). | -| [resource_names.md](resource_names.md) | RPF9 named-resource index: bounded-inflate lookup for `name.#dr`/`#ft`/`#dd` without the TOC. | -| [sgd5_render_states.md](sgd5_render_states.md) | The three effect-local render-state indices in an SGD5 pass, checked across all 28,798 passes. | -| [textures.md](textures.md) | 357,115 TTPF descriptors across 57 pools: `rpf9dump` (`e293917`) decodes 354,991 strict-clean (99.41%) directly including BCPack BC1/BC3/BC4/BC5; `tools/bcpack.py` decodes all six BCPack modes (BC1–BC7). | -| [textures_arrays.md](textures_arrays.md) | All 697 multi-slice TTPF descriptors resolved (127 mip-major `SW_64KB_D` 2D arrays, 567 streaming slice-major `SW_4KB_S` cubemaps, 3 `SW_4KB_S` 3D volumes) plus 357,115/357,115 chunk-page metadata validation. | -| [animation.md](animation.md) | 130,470 `anim.rpf` streams, 95.4% readable; 1,126 rig sets / 6,677 source-to-rig entries / 3,669 rigs. | -| [navmesh.md](navmesh.md) | 90,295 `navmeshes.rpf` streams (0 unclassified): 9,603 `0DRP` cover-point `0x7a` pages, 27,644 `0x00010015` navmesh tiles (`136×180` grid), 27,482 Band-3 sparse grids, 22 `PSIN`. | -| [bvh.md](bvh.md) | 565,596 `core_bvh4.rpf` streams; 271,627 BVH4 streams and 269,106 instances, prebuilt acceleration data. | -| [rbf0.md](rbf0.md) | 1,263 RBF0 resources, 475,461 elements; UI/Scaleform definitions, not a sectioned container; strict JSON/CSV/XML tree decoder. | -| [gamedata.md](gamedata.md) | `common.rpf`: 954 streams, 266 XML documents / 118 roots; 0 RBF0/PSIN; a streaming reader (`gamedata_reader.py`) converts 259 documents by root and `type`. | -| [gamedata_graph.md](gamedata_graph.md) | `common.rpf` mount graph: 25 manifest documents, 30 content-set ids, 14 include refs (12 resolve), 3,386 target refs, 0 cycles. | -| [weather.md](weather.md) | The weather document measured: 168 types (151 tagged / 17 untagged, a family split), exact-case `Mod*` vocabulary mismatches, axis-to-field Spearman (niceness tracks its field, `Rain` is a 7-of-25 data-set split), `TimeMult` and the inert `Honor*` values. | -| [world.md](world.md) | `levels.rpf` placement: 9,918 map files / 680,228 entities measured in 55% of the archive (lower bound; estimate 16k-39.6k / 1.03M-2.64M); `0x7a` resource layout. Building a placed world from entity rows (`world_build.py --placements`): shared geometry per chunk (`EXT_mesh_gpu_instancing`), bounded memory for the whole archive, and per-tier LOD chunk sets with distance bands (`--lod-sets`). | -| [world_census.md](world_census.md) | Full `levels.rpf` pass: 23,535 maps / 1,670,442 entities, 98.32% stream coverage, sharded and exact; the SixNG 30,785-map difference reconciled map by map (interiors and entity groups). | -| [world_names.md](world_names.md) | Name resolution: `archetypeName` and map `name`/`parent` are lower-cased joaat; 64-bit keys are MurmurHash3 x64 low 64. With `rpf9_names.py` names, 99.85% of the 1,670,435 entities a whole-archive `world_index` run reads resolve (64-bit verified); 5/23,535 map names, all five confirmed by the map 64-bit key. | -| [world_lights_paths.md](world_lights_paths.md) | Map lights (`CExtensionDefLightEffect`/`CLightAttrDef`, 280,105 lights, placed through map entities) and the vehicle lane graph (63,808 nodes, 145,518 links, 1,546 junctions, 369 signalised); identical to SixNG on the lane graph, lights reconciled resource by resource. | -| [page_directory.md](page_directory.md) | RPF9 `0DRP`: 0x60-byte header, `q38` 16-byte records; 15,768 pages / 60,880 records in `data.rpf`; targets and sizes, names still TOC-only. | -| [text.md](text.md) | 30,511 localized string tables (hash table, index, UTF-8 blob in `0DRP` resources) and the dialogue table: 138,104 lines joined to their subtitles in every language; language guessed per table. | -| [psin.md](psin.md) | PSIN metadata container: header, section walk, `LSCH`/`LENM` schema, and the instance data (block table, pointers, arrays, maps) read through it on 17,507 containers, 99.986% of block bytes reached; hash-typed members resolved to resource names. | -| [story.md](story.md) | `story000.rpf` 18.65 GiB mixed: 264 Bink 2 streams / 3.33 GB, 225,281 `RSC8` headers, 442 nested RPF9; `story000_script` PSIN, `shared_minigame` mixed content. | -| [restofworld.md](restofworld.md) | Six rest-of-world/script archives, 1.57 GB total: `core_restofworld` 1.21 GB (11 Bink 2, 37 models, 958 graphics pages), `story000_script` PSIN, small `appdata0`/licences. | -| [movies.md](movies.md) | Bink 2 streams and audio tracks; decode through the real loader and `Bink2Scarlett.dll`; stream names from the mount lists. | -| [pso_cache.md](pso_cache.md) | The PSO/shader cache: 0x80 header, 25,471 graphics and 2,693 compute records, two 8-byte index tables, meta chunk types 0x41/0x42/0x43 and 26,092 `s_endpgm`; `tools/psocache_extract.py` carves it, `tools/psocache_inspect.py --meta` decodes the chunks and `tools/psocache_usersig.py` maps the graphics user data to root parameters. | - -## Audio - -| Document | Measured content | -|---|---| -| [audio.md](audio.md) | AWC banks: Opus, PCM and XMA2; lossless Ogg Opus repack and WAV paths; stream names from dictionary hits with a salted control; names and subtitles written into the Ogg Opus tags. | -| [rsc8_audio.md](rsc8_audio.md) | 641,428 `RSC8` v8001 resources across 4 archives: 100% AWC tag `0x5c` facial/lip-sync `crClipDictionary` paired with 48 kHz mono Opus dialogue, 0 hidden audio containers; the undocumented `0x5a`/`0xd9` companion tags (1,185 `audio.rpf` streams) decoded structurally. | -| [awc_shorts.md](awc_shorts.md) | Export short streamed-music idents/stings by duration; stereo-aware, no re-encode. | -| [audio_config.md](audio_config.md) | The music/radio record table: 1,589 records, exact durations, AWC stream ids; no start offsets. AWC tag `0xBD`: 16-byte marker events on 938 of the 3,008 streamed-music banks, track markers in five long mixes. | -| [radio_stations.md](radio_stations.md) | Audio-config station blocks: 19 records, boundary u32, content-id lists; VCRR 80/80 mapping; no start offsets. | - -## Runtime, GPU and validation - -| Document | Measured content | -|---|---| -| [d3d12_vulkan.md](d3d12_vulkan.md) | Xbox D3D12 to Vulkan plan and status; device proxy, queues, command lists, barriers, copies. | -| [mobile.md](mobile.md) | arm64/mobile path: the x86-64 → arm64 static-recompiler groundwork (`tools/x64_recomp.py`), the `.pdata` coverage census (`tools/recomp_census.py`), and what still blocks iOS. | -| [boot.md](boot.md) | The first real boot: the `gta6rt --trace`/`--trace-d3d12` runbook, the startup + D3D12 trace summary (`tools/boot_trace.py`), the triage order and the Q1–Q22 checklist. | -| [retail_boot_chain.md](retail_boot_chain.md) | How far `gta6rt --run` gets with the retail executable: the stops in order and what clears each, the physical-page export shapes, and device slots 26, 48 and 73. | -| [retail_boot_intel_host.md](retail_boot_intel_host.md) | The retail boot on an Intel host with 16 GB: which stops of the two boot pages hold there with #7111, the commit-limit stop at the 6.1 GiB physical-page request that #7556 clears, the frame loop to the 900 s timeout with stub pipelines, and what the layer refuses at that depth (the console mesh-shader subobject among it). | -| [modding.md](modding.md) | The mod format: a `mods//mod.json` next to `gta6rt.exe` or under `--mods DIR`, swapping a named (or `joaat`) archetype for another; the `tools/leonida_mods.py` manager (`Mods.bat` on Windows, `Mods.sh` on Linux and macOS); load order, the start-up log, and the fact that a swap waits for the executable's archetype lookup address (RT-5). | -| [descriptor_lookup_apple.md](descriptor_lookup_apple.md) | M3 Max GPU timings for texture and sampler descriptor lookups at 1k, 10k and 100k live entries. | -| [descriptor_lookup_ada.md](descriptor_lookup_ada.md) | RTX 4070 SUPER (Ada, Windows) timings for the same lookups in VRAM, host-visible and ReBAR memory. | -| [descriptor_lookup_intel.md](descriptor_lookup_intel.md) | Intel UHD Graphics 770 (Xe-LP, Windows, driver 101.6129) timings for the same lookups at 1k–100k live entries; both memory placements within 0.6% of each other. | -| [d3d12_xs_surface.md](d3d12_xs_surface.md) | The 116-slot `d3d12_xs.dll` export surface; 83/83 standard GUIDs match the PC SDK. | -| [xdxr.md](xdxr.md) | `BATCHED_DESC2` (`0x50`) and `XDXR_STREAM_DESC` (`0x10`) from `XboxBvhBuilder.dll`'s reads; stream records' offsets and defaults; offline statistics not in the package. | -| [d3d12_command_objects.md](d3d12_command_objects.md) | Measured command queue/list/fence/`PresentX` surface; verified vs prior art vs open. | -| [xbox_d3d12_xs.md](xbox_d3d12_xs.md) | The `d3d12_xs` graphics ABI quoted from Microsoft's public GDK reference: root signatures, state objects, DXIL libraries, hit groups, shader cache sessions; which pages are missing or NDA-gated. | -| [runtime_imports.md](runtime_imports.md) | The 16 shipped modules' measured imports and shim/host/unimplemented split. | -| [xmem_exe_calls.md](xmem_exe_calls.md) | How the retail executable calls `xmem.dll`: call sites and constant arguments per import (`tools/import_call_sites.py`), the 23 `XMemVirtualAlloc` calls that all pass an attribute word, and the inferred shape of the physical-page family. | -| [audio_hal_exe_calls.md](audio_hal_exe_calls.md) | How the retail executable calls the 22 audio coprocessor, texture layout and DirectStorage imports that have no shim: call sites, constant arguments, and the four calls with a negative-result branch. | -| [xcl_compare.md](xcl_compare.md) | XCL's synthetic test title under `gta6rt --run` and under XCL (`tools/xcl_compare.py`): 5 of 50 checks pass here, both hangs are the documented manual-queue terminate deadlock, and each other difference mapped to an open item or a lead. | -| [gameinput.md](gameinput.md) | The GameInput shim on SDL3: `GameInputCreate` and the v0 `IGameInput`/`IGameInputDevice`/`IGameInputReading`/`IGameInputDispatcher` surface on any SDL gamepad, DualSense adaptive-trigger approximation and lightbar, force-feedback motors and trigger haptics through SDL's haptic API; 261 checks on virtual joysticks and a fake haptic backend; by hand on an Xbox Series X pad (Bluetooth) and a DualSense (USB). 261 checks on virtual joysticks and a fake haptic backend, not yet tried on a real pad. | -| [saves.md](saves.md) | Save containers: `JSAV` (index + JSON story save, byte-exact rebuild), `ASAV` header, `SLAYER1` packed copy (not decoded); `tools/saves.py` and import into the offline `XGameSave` folder; key hashes are case-sensitive joaat (`tools/save_keys.py`). | -| [pipeline_check.md](pipeline_check.md) | Driver-level corpus check: the full corpus, 26,503 of 26,503 modules and pipelines, 0 failures (RTX 4060 Ti); an earlier 10/12-shard run, 22,092 modules and 2,217 compute pipelines, also had 0 failures. Driver-level corpus check: 10/12 shards, 22,092 modules, 2,217 compute pipelines, 0 failures. | -| [multi_gpu_validation.md](multi_gpu_validation.md) | Running disjoint shards on eight identical RDNA1/RADV GPUs: PCI-BDF pinning, base controls, per-card logs, the V540 farm's aggregate results and its known driver limitations. | -| [shader_validation.md](shader_validation.md) | Differential CPU/GPU validation design and the current CPU interpreter prototype. | -| [isa_coverage.md](isa_coverage.md) | RDNA2 ISA coverage of the translator against AMD's machine-readable XML: which of its 1,153 instructions have a rule, and which matched names are not RDNA2. | -| [buffer_bounds.md](buffer_bounds.md) | V# `OOB_SELECT` bounds measured natively: RDNA2 (gfx1036) follows Mesa's GFX11 column (729/732 cases), not GFX10; raw mode also counts `soffset`. | -| [buffer_formats.md](buffer_formats.md) | Every GFX10 buffer data format a V# or MTBUF can name, loaded and stored, measured on a Radeon 880M (RDNA3.5, not RDNA2): 1.33 million validated elements, 0 mismatches; SCALED stores convert as NORM, float stores round toward zero. | -| [fssm_crosscheck.md](fssm_crosscheck.md) | FSSM/RDNA2 facts cross-checked against SCARAB; code starts at `code_off + 0x28`. | -| [fspx.md](fspx.md) | `FSPX`, the FidelityFX DLL's native compute programs (its shaders' `ACCC` part): directory as the DLL reads it, kind-0 dispatch state, the hash prologue, `gfx1030` for its `v_dot4` code; 20 of 29 translate and pass `spirv-val` with `tools/fspx_unpack.py` (the recount after SHADER-813 in fspx.md). | -| [first_light.md](first_light.md) | Draw an exported model's UVs or sample a supplied texture with `--dds`. The UV draw covered 78.1% on an RTX 2060 SUPER (4,213 vertices, 7,968 triangles). The first draw of a real game model with its own translated VS/PS on a GPU: 4,213 vertices / 7,968 triangles, 78.1% coverage on an RTX 2060 SUPER; `tools/first_light.py`, the `vk_harness` mesh mode, and the same draw through the D3D12 layer (`d3d12_first_light`). | -| [material_pass_replay.md](material_pass_replay.md) | How one authored mesh writes packed draw indices, how six compute programs read the layout, and which sibling passes read the surface material. | -| [embedded_shaders.md](embedded_shaders.md) | DXBC containers embedded in the package's DLLs: 52 in `XboxBvhBuilder.dll` (console `FSSM` via the `XDAT`/`XBCH` record; 51/52 pass `spirv-val` today) and 29 `ACCC`/`FSPX` in the FidelityFX upscaler; the scan/extract tool, the one rule still missing, and the build step and run-time lookup of the builder's programs (`/bvh/index.json`). | -| [shader_library.md](shader_library.md) | The pipeline library in `shaders.rpf`'s zlib part, which the carve doesn't read: 25,471 graphics and 2,693 compute pipeline records (stage slots: PS, VS, MS) and 21,522 native programs, 21,509 of them pipeline builds of 6,522 carved shaders (named by their `HASH` digest); `tools/shader_library.py`. | -| [shader_inputs.md](shader_inputs.md) | Inputs that specific game shaders need to be right, as a first check for a black frame or a device-lost: the studio-shot lighting shader's 512-byte light records, eight-light loop, plane count at +0x4C (#1892 said +0x40), profile table and shadow-strength byte; the ACES LUT bakes' two tone-curve splines (reference order at +0x00, points-first at +0x70 behind the +0x118 switch), the +0x13C luminance mode and the quasi-log addressing (#1896); the sky LUT order and the +0xD0 dword that picks RGB9E5 or float outputs (#1897); the shared atmosphere constant buffer, its table slots (+0x220, +0xC60) and the layout with the two scale-height dwords no pass consumes (#3990). | -| [sandbox.md](sandbox.md) | Placed world props through one translated VS/PS pair with a real camera, TTPF albedo and the game's sampler: 442 of 446 draws textured; fly/walk/drive window, `tools/sandbox.py --check`. | -| [coder.md](coder.md) | The compressed mass in `story000_script.rpf`: entry framing (`align16(entry+8)` payload), the 32-value tag alphabet, deflate-shaped but proprietary, variable-length 7/8-bit LSB-first codes with no stored table, and the `n7 = 116..127` search that finishes it. | -| [mission_logic.md](mission_logic.md) | Mission state tables: 0x20 record layout (band counter, byte offsets), the 64-byte pool element with world transforms, case-folding joaat keys, 53.5 % of states named, 113 state-set clusters covering 82.4 % of files. | -| [gbuffer.md](gbuffer.md) | Deferred G-buffer targets (`PS_DeferredTextured` and all 2,989 `*Deferred*` pixel shaders, `PROC-146`): 5- and 6-target `OSG1`/`PSV0` signatures (`float32` + `exp ... compr` on all outputs), the 24-bit octahedral normal split across `mrt1.gba` (`2047.5` scale, `1/255` byte packing), sqrt-encoded `mrt2`, byte IDs in `mrt3.zw`, float motion in `mrt4`, and why binding `f16` targets mangles the normal bytes. | - -## Other languages - -Community quickstarts (stable onboarding text only; English docs remain authoritative): [i18n/README.md](i18n/README.md) (`fr`, `pt-BR`, `pt-PT`, `zh-CN`, `pl-PL`, `tr`, `ru`, `ja`, `es`, `it`, `de`, `ar`). diff --git a/docs/animation.md b/docs/animation.md deleted file mode 100644 index ad13ec99b..000000000 --- a/docs/animation.md +++ /dev/null @@ -1,1258 +0,0 @@ -# Animation archive (`anim.rpf`) - -Measured state of the animation archive in the Xbox Series 1.0.2.1 package. Everything here was read from a -local copy; no archive, payload, name list or byte dump is committed. The tables are counts and short header -excerpts only. - -The table of contents of an RPF9 is encrypted. This work does not read or decrypt it. It indexes the data area -the same way `tools/rpf9_carve.py` does: every zlib stream that inflates cleanly to its end is one **stream** in -the tables below. A logical RAGE resource can span several streams, so "stream" is not "file". - -## Measured archive composition - -``` -archive 4,407,626,384 bytes -RPF9 magic b"9FPR" -data start 0x4660 (18,016) -data span 4,407,608,368 bytes -``` - -The requested command (`python -I tools/rpf9_carve.py /anim.rpf /anim-index --index-only`) prints: - -| Measure | rpf9_carve | -|---|---:| -| validated zlib streams | 130,449 | -| stored (compressed) bytes | 4,204,677,247 (3.92 GiB) | -| inflated bytes | 11,592,111,696 (10.80 GiB) | -| zero padding | 180,165,556 (4.09% of span) | -| unread bytes | 23,664,707 (0.54% of span) | -| readable | 95.40% of span | -| Bink 2 | 0 streams | -| elapsed | 141 s | - -`rpf9_carve.py` overreads its last stream: it advances a 1 MiB read cursor by 1 MiB even when the final mmap -slice is shorter. That makes the last `PSIN` stream look 974,742 bytes stored instead of 1,766 and skips 21 -streams at the tail. `tools/anim_index.py` advances by the actual slice length. Its corrected walk finds: - -| Measure | corrected walk | -|---|---:| -| streams | 130,470 | -| stored bytes | 4,203,762,662 (3.915 GiB) | -| inflated bytes | 11,593,460,132 (10.80 GiB) | -| zero padding | 180,167,209 (4.09%) | -| unread bytes | 23,678,497 (0.54%) | -| readable | 95.38% | -| elapsed | ~140 s | - -The 21 extra streams are the 1.35 MB `RBF0` rig metadata at the end of the data area (below). The class table -uses the corrected counts: the `PSIN` group is 213,747 stored in total, and the tail is its own row. - -| Class (first bytes) | Streams | Stored | Inflated | Median | Max | Where | -|---|---:|---:|---:|---:|---:|---| -| `0DRP` at +16 (page directory) | 22,823 | 169,144,668 (161 MiB) | 3,883,044,624 (3.62 GiB) | 196,608 | 5,636,096 | first 1/8 of data area | -| starts with 8 zero bytes | 78,688 | 3,569,562,146 (3.32 GiB) | 6,918,674,880 (6.44 GiB) | 46,864 | 20,578,304 | throughout | -| other (no match below) | 28,646 | 464,618,867 (443 MiB) | 789,033,180 (752 MiB) | 23,984 | 65,536 | throughout | -| `RBF0` rig blob (1 header + 20 blocks) | 21 | 58,391 (57 KiB) | 1,348,436 (1.29 MiB) | 65,536 | 65,536 | tail | -| `pack:/` name table at 0 | 273 | 164,654 (161 KiB) | 711,536 (695 KiB) | 896 | 61,056 | throughout | -| `PSIN` at 0 | 18 | 213,747 (209 KiB) | 646,580 (631 KiB) | 35,768 | 65,536 | scattered | -| `SKEL_` bone list at 0 | 1 | 189 | 896 | 896 | 896 | early | - -Only the first `RBF0` stream has the header; the other 20 are continuation blocks, so `anim_index.py` reports one -`rbf0` and 20 `raw:` records for that tail. - -Two observations matter for a decoder: - -- Every `0DRP` stream is in the first 1/8 of the data area (about 551 MB of span). The remaining 7/8 contains no - `0DRP` header at +16. -- The 78,688 zero-prefixed streams are not opaque blobs. In a 200-stream sample, 78% have a 64-bit pointer into - the `0x50000000` range at +8; the rest are mostly zero or other tables. Some pages carry a name table and - high-entropy blocks later in the same stream. - -## Container signatures actually observed - -### `0DRP` page marker at +16 - -22,823 streams. The fixed part of the header is: - -``` -+0x00 8 zero bytes -+0x08 u64 pointer into 0x50xxxxxx -+0x10 "0DRP" (bytes 30 44 52 50) -+0x14 u32 122 (same value in all 22,823) -+0x20 u64 page count (observed 1..41, 32 distinct values) -+0x28 four u64 pointers (0x50xxxxxx) -+0x48 four u16 values -``` - -Top page-count values: 1 (1,883), 2 (7,571), 3 (9,241), 4 (2,022), 19–26 (1,592). The largest sampled page -(5,636,096 bytes) is 94.6% zero bytes, with sparse pointers. That is a page directory/relocation table, not -keyframe data. The marker is reported as a page marker, not as a known GTA V resource magic. Each `0DRP` stream is -the first system page of a resource; the page map at the `+0x08` pointer gives its page count (see -[Keyframe decoding](#keyframe-decoding)). - -### `MoVE` container - -324 resources start with `"MoVE"` (325 zlib streams: 323 fit in a single RPF9 stream of 114–58,452 inflated bytes, and -one at `0x105a7d000` spans a 65,536-byte stream plus a 5,563-byte continuation stream at `0x105a7f9c0`, for 71,099 -bytes). All 324 share the same 32-byte fixed header prefix: - -``` -+0x00 "MoVE" (bytes 4D 6F 56 45) -+0x04 u32 19 (version 19 in all 324) -+0x08 three u32 0 (reserved zeros in all 324) -+0x14 u32 network_hash (324 distinct values; not a size) -+0x18 u32 body_size (68..71,048; equals total_bytes - 46 - 5 * N_desc in all 324) -+0x1c u32 0 (reserved zero in all 324) -``` - -What earlier looked like a fixed 46-byte header with "5/10/15/20 bytes of padding" on 140 streams is a **variable -preamble at `+0x20`** containing a table of `N_desc` 5-byte `{u32 hash; u8 kind}` descriptors that `body_size` does not -count (`total_bytes == 46 + 5 * N_desc + body_size` across all 324 resources, with zero tail padding). The full -preamble, state-machine hierarchy (`Type 1` = `StateMachine`, `Type 3` = `InlinedStateMachine`, `Type 22` = -`MotionTree`), transitions and parameter blocks are decoded in [`MoVE` state-machine containers](#move-state-machine-containers) -below (`tools/anim_move.py`, ASSET-86). - -### Name tables (`pack:/...`) - -273 streams start directly with NUL-terminated ASCII paths; there is no container header before the names. They -hold 711,536 inflated bytes and 2,298 distinct paths: - -| Suffix | Distinct paths | -|---|---:| -| `.clip` | 2,012 | -| `.anim` | 274 | -| `.motion` | 12 | - -Paths are padded to 16-byte boundaries. The records include a 32-bit name hash; a second 32-bit value recurs as -`0x98e1750c` in some tables. It is `joaat32("bonerotation")`, the track-type hash of rotation tracks (see -[Keyframe decoding](#keyframe-decoding)); these tables are second system pages of clip dictionaries. The name hash -is **joaat32 of the path stem**: -strip `pack:/`, strip the final extension, lowercase. In one 161-name table all 161 hashes matched exactly; -across the 273 tables, 3,229 of 3,637 name occurrences (88.8%) and 248 of 273 tables matched every name. The -remaining 11.2% are not explained (duplicate names, missing records or a different record layout). A separate scan of the first 4 KiB of the 130,449 `rpf9_carve` streams found 7,661 distinct -`pack:/...` paths and 31,020 -occurrences; 5,880 of those streams contain at least one path, bone name or animation word in that prefix. The -union of the two name sources is 8,020 distinct paths. Names also appear embedded at non-zero offsets in -zero-prefixed pages (for example at +0x497e0 and +0x4aa8 in one 327,680-byte page), not only in the 273 -start-of-stream tables. - -### Skeleton and bone names - -A full-corpus prefix scan found 31 distinct `SKEL_*` tokens, 170 occurrences, in the first 4 KiB of the streams; -the count includes fragments. The four full-name streams give the 30-name union below. Two forms were seen in -carved samples: - -- a plain NUL-terminated bone list (896-byte stream), and -- a front-coded table (2,064 bytes) whose entries are length-prefixed name fragments plus parent indices. - -The `SKEL__` shape is the conventional RAGE bone naming. The animation pages carry no model name next -to the bones, but a skeleton carries its own names (`joaat32` at bone record `+0x1C`, name at `+0x30`, -[character_skeleton.md](character_skeleton.md)), so the match is measured: see -[Bone tables and motion matchers](#bone-tables-and-motion-matchers). -Measured across all `SKEL_*` streams in -`anim.rpf` (`177` streams, `118` distinct `SKEL_*` tokens) against the decoded skeleton name tables in -`packs.rpf` (`2,866` `SKEL_`-bearing streams, `691` distinct `SKEL_*` tokens) using `tools/anim_skeleton_match.py`: -`117` of `118` (`99.2%`) match by exact case and all `118` of `118` (`100%`) match case-insensitively (and by -lowercased `joaat32`, since `SKEL_HEAD` corresponds to `SKEL_Head`); `166` of `177` streams match all of their -tokens by exact case. The animation pages still carry no model name next to the bones. - -### Type-hash containers - -1,371 streams share this 16-byte header shape: - -``` -+0x00 u32 type id -+0x04 u32 8 -+0x08 u32 chunk count (1..4096) -+0x0c u32 0 -``` - -The most frequent type ids are `0x88560988` (721 streams), `0x51e5606c` (220), `0x51404a31` (133), -`0x8db79d92` (119) and `0x98a13c55` (7). Their payload is chunk-like, entropy 2.57–4.26 bits/byte. `PSIN` is a -separate 18-stream group (`PSIN` at offset 0, 0.21 MB stored / 0.65 MB inflated); `docs/design.md` already -describes `PSIN` as PSO metadata, and these bytes do not show that it is animation data. - -### Packed clip streams - -1,781 streams start with: - -``` -02 00 00 00 01 01 00 00 ... or 03 00 00 00 01 01 00 00 ... -``` - -The historical `clip-stream` scan label selects **second system pages starting at the parent's auxiliary -table** (ASSET-158). The leading u32 counts tagged entries. The 1,781 pages occupy 18,168,950 bytes stored -and 32,691,776 bytes inflated, with 1,767 distinct page contents. - -To reproduce this on 1.0.2.1, walk `anim.rpf` with `anim_index.scan_rpf`. For every `clip-stream` row, -inflate the preceding `page-directory` row and the selected row. Check that the second compressed stream starts -at the next 16-byte boundary after the first. In **1,781/1,781** pairs the u64 at first-page `+0x40`, minus -`0x50000000`, equals the inflated first-page length. At that offset, read a u32 count, then that many -`{u32 tag, u32 payloadBytes}` entries, then the payloads in order. - -| Entries | Pages | Tags in order | -|---:|---:|---| -| 2 | 528 | `0x101`, `0x207` | -| 3 | 1,235 | `0x101`, `0x113`, `0x207` | -| 3 | 10 | `0x101`, `0x204`, `0x207` | -| 3 | 8 | `0x101`, `0x10F`, `0x207` | - -In every pair the declared payload lengths fit within page two. The instance blocks referenced by the -[`+0x38` instance block table](navmesh.md#schema-tables-q28-q30-q38-q40) fit wholly within page one. Schema tables also occupy page two after the auxiliary payloads, -and none overlaps the auxiliary table or its payloads. The same framing is measured independently for -[navigation resources](navmesh.md#schema-tables-q28-q30-q38-q40). The meaning of the individual payloads -in the animation archive remains open. -The leading u32 is 2 or 3; the next four bytes are constant. Stored 18,168,950 bytes, inflated 32,691,776 bytes. -1,767 distinct payloads (duplicates up to 10 copies). Entropy 4.03–7.79 bits/byte, so these are packed/quantized -bitstreams rather than zlib streams. The 24-byte header has five small fields after the type; the measured -version split and the track side are below. No keyframe values are claimed. Each of these streams is the second -system page of a `0DRP` resource, the one right after its `0DRP` stream (see [Keyframe -decoding](#keyframe-decoding)). - -### Partial clip decode - -Two named clips were followed from their `pack:/...` name-table records to page-0 payloads. The name record -stores `joaat32(stem)`, a second hash, and two 64-bit `0x50xxxxxx` pointers; the pointer rule is page-0 offset -when it is below the page-0 size, otherwise a name-table page offset. - -| Clip | Name hash | Page-0 stream | Clip record | Duration | Tracks | -|---|---|---:|---:|---:|---:| -| `breakout_quick_front` | `0xDC5BEF77` | `0x1D284010` | page0 `0x1F8A0` | 3.2333 s | 10 | -| `idle` | `0x71C21326` | `0x9F0E0010` | page0 `0xF580` | 6.0000 s | 8 | - -The durations are `f32` at record `+0x78` (breakout) and `+0x68` (idle). Track arrays are `0x48`-byte records -with `type = 0xFFFF0001` and two hashes per record. - -Bone masks: - -- Breakout: a 63-entry body mask and a 38-entry finger mask. -- Idle: a 12-entry head mask and the same 38-entry finger mask. -- The 38-entry mask is byte-identical between the clips and **all 38 hashes resolve** to - `SKEL_{L,R}_Finger{00..02,10..13,20..23,30..33,40..43}`. -- The 63-entry mask maps 25 body/`PH_` names; its other 38 entries are unresolved (likely facial or accessory - bones, not assumed). - -The 2,064-byte motionmatcher table also re-parses cleanly: 15 names, parent entries, and all 8 record hashes -resolve. - -Header fields measured over the 1,781 streams: - -- `+0x04` is always `0x00000101`. -- Version 3 (1,253 streams): `+0x0C = 0x0113` on 1,235, `+0x14 = 0x0207` on all 1,253. -- Version 2 (528 streams): `+0x0C = 0x0207` on all 528; `+0x14` is a 32-bit hash. -- `+0x08` is the leading packed-region length; the first 16-byte `(hash, 0, index, 0)` table follows a short - sub-header (for example at `0x2C8`, `0x4C8`, `0x6C8` in one page). - -**Still missing:** the page → packed-stream join. None of the 1,781 streams contains any of the 30 known bone -hashes or the nine tested clip-name hashes, as 32-bit or 64-bit values; only the shared track-type hash -`0x9A7B6E6D` crosses over. The track records and quantization-like blocks are visible, but the exact component -count/order/delta coding did not survive a unit-quaternion norm test. No keyframe value is claimed for these -`0DRP` pages. The clip dictionaries' keyframes are decoded in [Keyframe decoding](#keyframe-decoding). - -### Tail `RBF0` rig-set manager - -The last 21 streams appear to be one logical `RBF0` blob split into 64 KiB blocks (20 × 65,536 plus 37,716 -bytes); the first block ends mid-path (`...anim/rig`) and the next starts `/canonical/...`: - -``` -52 42 46 30 fb ff 01 00 00 00 15 00 "rage__crRigSetManager" -``` - -They hold 58,391 stored / 1,348,436 inflated bytes. The blob is a rig-set manager, not clip keyframes. Parsing -the `03 60` key strings, `fd ff` value strings and `ff ff 06 00`/`ff ff 07 00` field markers gives: - -| Measure | Value | -|---|---:| -| Rig-set keys | 1,126 | -| Source → rig entries | 6,677 | -| Distinct rig paths | 3,669 | -| Distinct names (rig sets + rigs) | 4,795 | -| Empty rig sets | 56 (object 53, vehicle 3) | -| Rig-set categories | ped 664, vehicle 346, object 115, system 1 | -| Max entries / distinct rigs in one set | 45 / 41 | -| Entries with a group string | 6,677 (16 distinct groups) | - -Source entries, with distinct rig paths in each source: - -| Source | Entries | Distinct rigs | -|---|---:|---:| -| `generated@source` | 3,616 | 1,188 | -| `pipelined@source` | 2,135 | 1,931 | -| `canonical@source` | 888 | 534 | -| `canonical@legacy` | 38 | 16 | - -Every distinct rig appears under exactly one source category. Every source tag is followed by exactly one rig -key before the next source (0 exceptions), and every entry is assigned to a rig-set by its offset. - -The first rig-set block starts at 0x0045. The tag/length layout is visible directly: - -``` -0x0045 03 60 03 00 "key" -0x004c 1f 00 <31-byte rig-set path> -0x009a fd ff 11 00 00 00 "canonical@source" 00 -0x00b1 ff ff 06 00 03 00 "Rig" ... -0x00c0 fd ff 30 00 00 00 <48-byte rig path> 00 -0x00f6 ff ff 07 00 05 00 "Group" ... -0x0107 fd ff 05 00 00 00 "pose" 00 -0x0112 ff ff 08 10 08 00 "Priority" ... a0 0f 00 00 -``` - -- Rig-set key: `03 60` + u16 length + ASCII (no NUL). The first block is special and puts the schema name `key` - before the first path; the following 1,125 blocks use `02 00 00 00 00 00 01 00 03 60` + u16 length + path. -- Entry: `fd ff` + u32 length including NUL + source, then `ff ff 06 00` (Rig), the rig key in the same - `fd ff` form, `ff ff 07 00` (Group), and the group string in the same form. A `ff ff 08 10` field and a mostly - zero u32 follow; the field semantics are not mapped. -- A non-empty rig-set ends with six `ff` bytes (1,070 occurrences). An empty rig-set has - `04 00` + six zero bytes + four `ff` bytes and no entry (56 occurrences). -- The group names are the rig's channel/group field; the observed values are `deformation` (2,169), - `deformation[2]` (1,702), `identity` (1,109), `pose` (938), `pose.ragdoll.post` (160), `facial` (152), and - ten smaller values. - -The grammar-driven tree decoder (`tools/rbf0_tree.py`; `docs/rbf0.md` section 9) parses the same 1,348,436-byte -blob to its last byte and confirms the counts above: 9 descriptors, 28,962 elements, 20,031 text records, 1,126 -string values, 6,677 integer values and maximum element depth 6. The 1,126 string values are the `key` attributes -on the rig-set `Item` elements. Each of the 6,677 entry `Item` elements contains `Dictionary`, `Rig` and `Group` -text children followed by a `Priority` integer. The record framing is consumed exactly; the numeric field -semantics remain unresolved. The `Dictionary` text names one of the four rig dictionaries and `Rig` is a key -there; see [Rig dictionaries](#rig-dictionaries). - -Mapping to the name tables: - -- The 2,298 distinct `pack:/...` paths resolve to a stored joaat32 stem hash for **1,901** names (82.7%); - **401** stay unresolved. By occurrence, 3,229 of 3,637 (88.8%) match, and 248 of 273 name tables are complete. -- The RBF0 names do **not** overlap the clip/anim/motion namespace: direct name overlap is 0 and stem-hash - overlap with the 2,298 paths is 0. -- The RBF0 table contains 4,795 distinct rig and rig-set names. An earlier version of the indexer reported - zero stored joaat32 matches for every input. The count for this corpus needs to be measured again with the - corrected `--rigs` report. A match indicates that the four hash bytes occur somewhere in the blob. - -### Bone tables and motion matchers - -Four small resources in this index carry full bone names. One is a standalone name list; three are motion-matcher -resources found in the prefix scan that embed a bone table and a `pack:/...motionmatcher` path: - -| Offset | Inflated | Distinct names | Occurrences | joaat32 present | Kind | -|---|---:|---:|---:|---:|---| -| `0x101a32160` | 896 | 28 | 68 | 0 | standalone name list | -| `0x101c379a0` | 4,272 | 28 | 55 | 14 | motion matcher | -| `0x101c41d50` | 2,064 | 15 | 15 | 8 | motion matcher | -| `0x101ea66c0` | 2,848 | 30 | 50 | 19 | motion matcher | - -The three motion matcher streams contain four distinct `pack:/...motionmatcher` paths. The union of all four -streams is 30 names (28 `SKEL_*` and 2 `PH_*`); 19 of the 30 have a joaat32 present in at least one stream; 11 -do not. The standalone 896-byte stream has no hash table. - -The 2,064-byte stream shows the embedded record layout most clearly: header `0f 00 e0 00 0c 00 16 00`, eight -0x30-byte records from 0x0528 to 0x0678, a u32 hash at +0x10, a parent-index array at 0x06d0, bind-pose floats -from 0x0100, the full name list at 0x0750, and a `pack:/...motionmatcher` path at 0x04a0: - -``` -0x0528 0c 00 01 00 00 00 00 00 00 00 00 00 19 de 33 81 0b 00 00 00 -0x0558 0c 00 00 00 06 00 01 00 00 00 00 00 00 00 00 00 55 a9 3f 2b 03 00 00 00 -``` - -All 8 of its +0x10 hashes match joaat32 of full names in its own 0x0750 list. The 2,848-byte stream has a -14-entry pointer table at 0x0000 (targets in the `0x5005xxxx` range), records at 0x02d0, and two motionmatcher -paths at 0x0210 and 0x0290; 19 of its 30 names hash-confirm. The 4,272-byte stream has 28 names and 14 hashes. - -**Which skeleton (ASSET-231).** `tools/anim_skel_match.py` reads every skeleton `anim_glb.read_skeleton` reads in -`packs.rpf` (14,212, 199 distinct joint-hash lists) and looks each name up by `joaat32` of its lowercased spelling: - -| Stream | Names | Joints of some skeleton | Same spelling as the joint | Skeletons holding all of them | -|---|---:|---:|---:|---| -| `0x101a32160` | 28 | 28 | 28 | 2 (the 596- and 560-bone humanoids) | -| `0x101c379a0` | 28 | 28 | 28 | 2 (596, 560) | -| `0x101c41d50` | 15 | 15 | 15 | 69 distinct, 124 copies (78 to 596 joints) | -| `0x101ea66c0` | 30 | 30 | 30 | 2 (596, 560) | -| union | 30 | 30 | 30 | 2 (596, 560) | - -So every bone name in these pages is a joint of the female (596) and male (560) humanoid skeletons that the clip -dictionaries already bind to ([character_skeleton.md](character_skeleton.md)), under the same name; no other -skeleton holds the 30. The 15-name table is a subset many smaller rigs share too. - -This is a measured **clip → bone-table binding for the four motionmatcher paths**: the path and the bone table -are in the same stream. It is not a rig → skeleton link for RBF0: - -- RBF0 contains no `SKEL_` token and no lowercase `bone`/`skeleton` string; the only `Bones`/`Skel` text is - inside two rig path names. -- 0 of the 3,669 rigs and 0 of the 1,126 rig sets match any of the 30 bone names or any of the 19 hashes present. -- The four motionmatcher paths are not in the 2,298 `.clip`/`.anim`/`.motion` name-table paths. - -So RBF0 gives rig-set → source → rig, and the motion matcher resources show how a clip can carry its own bone -table. The RBF0 rig itself resolves into a rig dictionary ([Rig dictionaries](#rig-dictionaries)); what it does not -give is a whole skeleton for the clips. - -### Magics not found - -At stream starts across the 130,449 `rpf9_carve` streams, the counts of `YCD`, `YDD`, `YLD`, `YFD`, `RSC7`, -`RSC8`, `ADAT`, `AWC`, `RBF0`, `FSSM` and `KB2` are all zero. The corrected walk adds 21 tail streams whose first -starts with `RBF0`; the rest start inside the same blob. One three-byte `YDD` sequence occurs at +0xE1 inside a -high-entropy stream; it is not at a header boundary and is treated as coincidence, not as a YDD file. - -## Keyframe decoding - -`tools/anim_clips.py` decodes the clip dictionaries down to per-frame track values. It starts from the same stream -walk as `anim_index.py`, so the stream numbers below are the corrected walk's 130,470. Run on the 1.0.2.1 copy: - -```powershell -python -I tools/anim_clips.py \anim.rpf \anim-clips.json --jobs 8 -python -I tools/anim_clips.py \anim.rpf --decode [--frames N] # values to stdout -``` - -The JSON holds counts and one row per dictionary (offset, hash and counts, plus the name read from your copy). -It holds no values. `--decode` prints one dictionary with its decoded values and writes no file. - -Provenance: channel types 0–8 follow the GTA V `crAnimation` channel set, as named by community tools such as -CodeWalker's YCD reader (static, quantized, indirect-quantized and cached-quaternion channels). No code was taken -from them. The resource framing, the GTA VI-only channel type 10, the type 3 and type 8 rules below and every -count in this section were measured on the local copy. - -### Clip dictionaries are RAGE resources - -A clip dictionary is a system-only RAGE resource. Its **root stream** is one of the `starts with 8 zero bytes` -streams above: - -``` -+0x00 8 zero bytes -+0x08 u64 page-map pointer (0x50xxxxxx) -+0x10 zero up to +0x38 -``` - -At the page map, the byte at +8 is the number of system pages and the byte at +9 the number of graphics pages. -Every dictionary has 1 or 2 system pages and no graphics pages. Its pages are that many back-to-back streams, -each 16-byte aligned after the one before it. Join them, and a pointer `p` is the offset `p - 0x50000000` into -the joined bytes. - -A continuation can begin with an animation pack whose header also looks like a dictionary root. -When that header has a verifiable page-local name and hash, the grouper requires the preceding pages -to contain the owner's complete pack table and an entry matching both the boundary pointer and the -hash. A table on the candidate or any later page could belong to the next dictionary. Such a layout -leaves the owner unresolved, even for a legitimate pack. This check applies only to recognized named -boundaries. A malformed reference already present in the prefix can still match. - -Measured: 61,510 root streams. 61,510 join into resources: 35,750 with one system page and 25,760 with two. -In 36 roots the page map says two pages, but the next listed stream does not start where the first one ends. Their -second page is right after the first stream, but `anim_index.py` does not list it: in 28 it is a zlib stream that -inflates to 16–48 bytes (`anim_index.py` lists streams of 64 bytes or more), and in 8 it is a 16-byte raw page, -like rpf9-explorer's raw system tail. `anim_clips.py` joins such a last page only when the joined pages then parse -as a clip dictionary; all 36 do, so no root is left unresolved. That recovery runs only after the page map itself -has been read from listed streams: a root whose page map is in such an unlisted last page stays unresolved ("page -map not in the next stream"). No anim.rpf root has that layout. In `story000.rpf` 5 roots do, with the page map in -a 32- or 48-byte zlib tail, and none of the 5 is a clip dictionary once that tail is joined. Of the joined resources, 61,505 are clip -dictionaries. 4 have `RIG` plus a version at +0x70 instead of a pack array (rig dictionaries, [decoded -below](#rig-dictionaries) by `tools/anim_rigs.py`), and -1 has some other value there. Together the dictionaries use 87,234 listed streams plus the 36 unlisted pages -(3,802,124,713 stored / 7,077,351,104 inflated bytes in the listed streams). By `anim_index.py` class those -streams are: zero-prefix 66,115, raw 20,845, name-table 273, skeleton-names 1. - -The other classes fit the same framing: - -- **The 273 `pack:/` name tables** at the start of a stream are the second system page of a clip dictionary. All - 273 sit inside dictionaries. -- **The `0DRP` (version 122) streams** are a different resource kind with the same page map. Their system pages are - one stream in 2,892 resources and two in 19,931. In 19,909 of the two-page ones the second page is the next stream; - in the other 22 it is not. Their second pages include all 1,781 "2/3 packed clip streams" and all 1,371 type-hash - streams. So those classes are not stand-alone clip payloads: each one is the page right after a `0DRP` stream in - the same resource. The `0DRP` root objects are not decoded here. The 324 `MoVE` resources are stand-alone flat binary - containers rather than `0DRP` or clip-dictionary pages; see [`MoVE` state-machine containers](#move-state-machine-containers). - -### Objects - -All offsets are page offsets. An `atString` is 16 bytes: `{char *ptr; u16 length; u16 capacity}`, or, when byte 15 -has bit 7 set, up to 15 characters stored inline with `byte 15 & 0x7F` as the length (909 clip names and 3 dictionary -names). An array is `{T *ptr; u16 count; u16 capacity}`, and an `atMap` is `{Entry **buckets; u32 bucket count (11); -u32; u32 count}` with `Entry {u64 key; T *value; Entry *next}`. Hashes are `joaat32` of the lowercased name. - -| Object | Field | Meaning | -|---|---|---| -| dictionary (page offset 0) | `+0x38` atString | dictionary name | -| | `+0x48` atMap | clips; key = `joaat32(dictionary name) << 32 \| clip hash` | -| | `+0x68` u32 | `joaat32(dictionary name)` (all 61,505 dictionaries) | -| | `+0x70` array, 16-byte items | `{pack *ptr; u32 hash; u32 0}`. With a pointer, a local pack and its `joaat32(name)`. With a null pointer, the hash is another clip dictionary's `joaat32(name)` (see `.motion` clips below) | -| animation pack | `+0x38` atString | pack name (`-N`) | -| | `+0x48` atMap | animations, key = `joaat32` of the animation name | -| | `+0x68` u32 | `joaat32(pack name)` | -| `.clip` (`+0x20` u32 < 16) | `+0x28` atString | `pack:/.clip` | -| | `+0x68` pointer | list `{entry *ptr; u16 count; u16 capacity}`, entries 0x38 bytes: `+0` animation pointer, `+8` animation hash, `+0x28`/`+0x2C` start/end (s), `+0x30` rate | -| | `+0x78` f32 | duration (s) | -| `.motion` (`+0x20` is a pointer) | `+0x18` pointer | the dictionary root (page offset 0) | -| | `+0x28` u32, `+0x2C` u32 | the clip hash (the low half of its `atMap` key) and `joaat32` of the dictionary name | -| | `+0x30` atString | `pack:/.motion` | -| | `+0x58` u32 | 1 or 2; selects where the parameter node is (see `+0x120`, `+0x138`); most likely the number of blend parameters (not verified) | -| | `+0x60` array, 16-byte items | children `{u64 0; u32 clip hash; u32 dictionary hash}`: the clips it blends | -| | `+0x70` array, 0x28-byte items | one item per child: `{f32 child duration; f32 duration in the blend; {ptr; u16 count} curve of (child time, blend time) f32 pairs; 16 zero bytes}` | -| | `+0x120` pointer (`+0x58` = 2) | a block whose `+0x18` points at the parameter node | -| | `+0x138` pointer (`+0x58` = 1) | the parameter node: `{u64 0; u32 type; u32 0; ...}` | -| parameter node, type 3 | `+0x10` array of u32, `+0x20` array of 8-byte items, `+0x30`/`+0x34` f32 | one sampled axis: its name hash(es), then `{u32 sample index; f32 value}` sorted by value, then min and max | -| `.motionmatcher` (`+0x20` is a pointer) | `+0x20` pointer | the feature object (below) | -| | `+0x28` 16 bytes, `+0x38` atString | an id, then `pack:/.motionmatcher` | -| | `+0x58` pointer, u32 count at `+0x54` | records `{f32; f32; f32 −1.0; u32 clip index; u64 0}`, 24 bytes. A `.motionmatcher` array keeps its u32 count just before the pointer, and a u32 capacity before that | -| | `+0x68` pointer, count at `+0x64` | u32 offsets, one more than the records, from 0 and never decreasing | -| | `+0x78` pointer, count at `+0x74` | u16, one per clip and then the record count: each clip's first record | -| | `+0xB8` pointer, count at `+0xB4` | u8, 0 or 1, one per clip | -| | `+0x98` pointer, count at `+0x94` | on 36 of 180: one `{u64 0; u32 clip hash; u32 dictionary hash}` per clip, like `.motion` children | -| | `+0xA0` u32 groups, `+0xA4` u32 entries, `+0xA8` pointer | a hash table of the clips: per group 16 control bytes (0x80 empty, below 0x80 full), then 16 slots `{u32 clip hash; u32 dictionary key; u32 clip index; u32 0}` | -| | `+0x170`/`+0x174`/`+0x178` | the same kind of table with 8-byte slots `{u32 hash; u32 index}` | -| | `+0x188` u32, `+0x18C` u32 | the clip's own hash and the dictionary's `joaat32(name)`, as `.motion` has at `+0x28`/`+0x2C` | -| | `+0x48` pointer, count at `+0x44` | one 40-byte item, zero except a u32 1 at its `+0x20` (`+0x40` holds the name's length and capacity, measured separately) | -| | `+0x118` pointer, count at `+0x114` | one u32: the pose sample count | -| | `+0x128` pointer, count at `+0x124` | one u16, 0 | -| matcher feature object | `+0x18` u32, `+0x28` pointer, `+0x30` pointer or null | 1 (measured separately), then the skeleton and the `+0x30` object (both below) | -| | `+0x40` pointer, count at `+0x3C` | pointers to the features, 0x30 bytes each: `{+0x08 u32 column; +0x0C u16 width; +0x0E u16 (1 or 5); +0x18 u32 name hash (a bone with 1); +0x1C u32 kind bits}` | -| | `+0x48` u32 groups, `+0x4C` u32 entries, `+0x50` pointer | a hash table like the clip table, 8-byte slots `{u32 hash; u32 feature index}` | -| | `+0xF0` pointer, count at `+0xEC` | the pose matrix, f16, in 32-byte chunks: one row of feature values per sample (layouts below) | -| | with `+0x30`: `+0xF8` u32, `+0xFC` u32, `+0x100` u32 | samples, columns, 32-byte chunks per row (rows are padded to 16 columns) | -| | with `+0x30`: `+0xA8` pointer, count at `+0xA4` | one 48-byte `{f32 quaternion[4]; f32 vec3; f32 0; f32 1, 1, 1; f32 0}` per sample | -| | without `+0x30`: `+0xFC` u32, `+0x128` u32 | columns, samples (the matrix is in blocks of 8 samples) | -| | `+0x98` pointer, count at `+0x94` | one u32 per sample: a bit mask over the matcher's key table indices, the same for every sample of a record | -| | `+0xB8` pointer, count at `+0xB4` (32-byte chunks) | one f32 weight per pose column, 8 to a chunk, zero after the last column | -| | `+0xC0` f32, `+0xC4` f32, `+0xC8` u32 | not decoded, then 1.0, then 1 with rows and 3 with blocks of 8 | -| matcher `+0x30` object (112 bytes, measured separately) | `+0x08` u32 | its form: 1 or 2 | -| | form 2: `+0x10`/`+0x14` u32, `+0x18`/`+0x1C` f32 | two bones (`joaat32` of their names) and their weights | -| | form 2: `+0x30` 0x30 bytes, `+0x68` u32, `+0x6C` u16 | a copy of the clip's first feature (its kind at `+0x4C`), that feature's width, a flag (6 or 9) | -| | form 1: `+0x10` f32[4], `+0x60` u32 | a unit quaternion (a reference rotation), a flag (6 or 7) | -| | form 1: `+0x40` {u32 n; u32 n; pointer}, `+0x50` the same | n u32 bones (`joaat32` of their names), then n f32 weights | -| matcher skeleton (feature object `+0x28`) | `+0x18` u32 slots, `+0x1C` u32 entries, `+0x20` pointer | tag table, 8-byte slots `{u32 tag; u32 bone}`, empty tag 0xFFFFFFFF | -| | `+0x28` pointer, `+0x6C` u16 count (`+0x6E` the same, measured separately) | the bones, 80 bytes each: `{f32 rotation quaternion[4]; f32 translation[3]; 4 bytes; f32 1.0[4]; char *name at +0x30; s16 parent at +0x46; u16 index at +0x48 and +0x4C; u16 bone id at +0x4A}` (the 1.0s and the two indices on 180 of 180, measured separately) | -| | `+0x30`, `+0x38` pointers | per bone a 4x4 f32 matrix: the inverse bind matrix, and the local matrix (row vectors, translation in row 3) | -| | `+0x40` pointer | the parents, one s16 per bone, −1 for the root | -| | `+0x48` pointer | a prefix tree of the bone names: `{u16 n; u16 size}`, nodes from `+4` `{u16 next sibling; u16 first child; s16 value; char text[]}` (offsets relative to the node), then n u16 bone indices at `+size` | -| animation | `+0x24` u16 | frame count | -| | `+0x28` f32 | duration = (frames − 1) / fps | -| | `+0x50` array | sequence pointers | -| | `+0x60` array, 12-byte items | tracks `{u32 bone hash; u32 track type; u32 format}` | - -A clip plays its animations at the same time, each over its own `[start, end]` window at its rate: animation time -`t` is clip time `(t − start) / rate`, and `(end − start) / rate` equals the clip's `+0x78` duration: over all -61,505 dictionaries of `anim.rpf` (`tools/anim_clips.py`, `clip_windows`), 784,562 of the 785,174 animation entries of -ordinary clips match to float32 precision (relative 1e-5) and the other 612 within 2.2e-4 relative, 581 of them in -one-frame (0.033 s) clips where the rounding shows most; none has rate 0 (the first check, 300 sampled -dictionaries, had 4,471 of 4,471). In the samples, the animations of one clip covered different bones and could -have different frame rates. `tools/anim_glb.py` plays clips on a fragment skeleton and writes them as glTF -animations; see [character_skeleton.md](character_skeleton.md#animated-gltf-export). - -**Track types** are `joaat32` of their names. This is the meaning of the recurring `0x98e1750c` noted above: - -| Hash | Name | Tracks | -|---|---|---:| -| `0x98e1750c` | `bonerotation` | 7,673,334 | -| `0xf791a95f` | `bonetranslation` | 2,440,527 | -| `0x2deefadd` | `genericcontrol` | 1,454,457 | -| `0xf5c3a5b6` | `generictranslation` | 69,844 | -| `0x6ddef121` | `cameratranslation` | 69,645 | -| `0x364d3bdb` | `facialtranslation` | 63,394 | -| `0x7aaa9f60` | `bonescale` | 24,590 | -| `0xd9ad1a74` | `camerarotation` | 476 | -| 36 other hashes | not named | 882,732 | - -A bone hash is `joaat32` of the lowercased bone name, for example `skel_pelvis`. In one checked rig, 64 of 66 -track bones matched the skeleton's names; bone hash 0 is the whole-body (mover) track. **Formats:** 0 = -quaternion `(x, y, z, w)`, 2 = vec3, 4 = float (7,935,044, 2,907,303 and 1,824,430 tracks; format 3 is used by 12,222 -tracks and is not mapped). - -### Sequences - -An animation's frames are split over one or more sequences. Consecutive sequences **share one frame**, so -`sum(sequence frames) = frames + sequences − 1` (true for 191,042 of 191,042 decoded animations). The repeated frame -decodes to the same pose on both sides: 814,011 of 814,880 quaternion boundaries are the same rotation (|q₁·q₂| > -0.9999, so q and −q count as equal), and 696,853 of 708,648 vec3/float boundaries agree within 1e-3. The cause of the -remaining 0.1% and 1.7% was not investigated. - -A sequence is a 0x20-byte header and `length` bytes of data: - -| Header | Type | Meaning | -|---|---|---| -| `+0x04` | u32 | data length (excluding the header) | -| `+0x0C` | u32 | frame-data offset in the data | -| `+0x16` | u16 | frames in this sequence | -| `+0x18` | u16 | bytes per frame | -| `+0x1C` | u16 | sum of the type-4 bit widths (true in 212,306 of 212,306 sequences) | -| `+0x1E` | u8 | 11 (the number of channel types) | - -The data holds, in order: - -1. **Channel definitions**, grouped by type 0 → 10. They end exactly at the frame-data offset in every decoded - sequence. -2. **Frame data**: `frames × bytes per frame`. Each frame is an LSB-first bit field holding the type-3 values, - then the type-4 values, then the type-5 indices, in channel order. -3. `u16 count[11]`, the number of channels of each type. -4. 11 lists of `u16 (track << 2 | component)`, one per type, each padded to a multiple of 4 entries. Item `i` of - list `t` names the track and component of the `i`-th channel of type `t`. - -### Channel types - -| Type | Definition | Value | Channels | -|---|---|---|---:| -| 0 | 3 × f32 x, y, z | constant quaternion, w = +√(1 − x² − y² − z²) | 3,579,477 | -| 1 | 3 × f32 | constant vec3 | 2,533,788 | -| 2 | f32 | constant | 5,428,131 | -| 3 | none | 32 frame bits = an f32 per frame | 40 | -| 4 | u32 bits, f32 quantum, f32 offset | `bits` frame bits × quantum + offset | 7,600,074 | -| 5 | u32 frame bits, u32 value bits, u32 words, f32 quantum, f32 offset, then the table (`words` u32, value-bits entries) | frame bits index the table; entry × quantum + offset | 484,616 | -| 6 | — | not seen | 0 | -| 7 | none | rebuilds one quaternion component (below) | 4,942,792 | -| 8 | none | marks a quaternion with four stored components (below) | 227,655 | -| 9 | — | not seen | 0 | -| 10 | variable, see below | second-order delta coding (GTA VI) | 6,836,654 | - -**Type 10** (new in this build, and the most common animated channel): - -``` -u32 word count (whole channel, header included) | u8 c1, c2, c3, 0 | f32 quantum | f32 offset | bits (LSB-first): - nc = ceil(frames / 64) chunks: nc × c1 bits chunk payload positions (redundant, for random access) - nc × c2 bits chunk start values - ceil((frames − 1) / 8) unary width codes: k zero bits then a one = bit width of the next 8 deltas - ... padding ... - last 8 × c3 u32 words: 8 lanes, interleaved (word w·8 + j belongs to lane j); - lane j holds delta j of every 8-delta group, k bits each, low bits first. -decode, per chunk: x = start; v = 0 - for each of the next 63 frames: v += zigzag(delta); x += v - value = x × quantum + offset; zigzag(u) = u / 2 for even u, −(u + 1) / 2 for odd u -``` - -Integrating a full chunk's 64th delta lands exactly on the next chunk's start value. That holds for -all 48,142,174 of 48,142,174 chunk boundaries. There is one width code per 8 *deltas*: reading `ceil(frames / 8)` -codes runs into the lanes. - -**Quaternion tracks.** A track with a type-0 channel is a constant `(x, y, z, +√(1 − x² − y² − z²))`. Otherwise -its components come from scalar channels: - -- **Type 7** appears on a track that stores three components (comp 0–2). The missing component is - `+√(1 − sum of squares)`, placed at the type-7 channel's comp position, and the stored three fill the other -positions in order. Measured: 4,942,792 sequence tracks; the largest |x, y, z| overshoot before normalising is -0.0971. -- **Type 8** always sits at comp 0 on a track that stores all four components. Nothing is rebuilt; the four values - are normalised. Measured: 227,655 sequence tracks; |q| of the four stored values is within 0.0190 of 1. - -Static quaternions: 3,579,477, and 0 of them have |x, y, z| > 1. The (x, y, z, w) order and the rebuilt sign fit the -boundary check above. An earlier local comparison against one skeleton's bind rotations also fits (dot products -0.97–1.0); that comparison is not part of the tool. - -### Coverage - -191,042 animations in 52,923 local packs; 191,042 decode with every check above passing and 0 fail (0 skipped by the -time budget). 8,582 dictionaries have no local pack; dictionaries refer to 27,559 packs by hash only (18,595 distinct -hashes), and none of those hashes is the hash of one of the 52,923 local packs: they are dictionary hashes. In -anim.rpf, 16,693 of the 18,595 distinct hashes are the `joaat32(name)` of a clip dictionary here (21,014 of the -27,559 references). Clips: 312,263, of which 17,247 are -`.motion` and 180 are `.motionmatcher` (`+0x20` is a pointer in both; the name is at `+0x30` for `.motion` and at -`+0x38` for `.motionmatcher`, after a 16-byte id); `.motion` clips are described below. Sequences: 212,306. Before -the gap-page join, a full run with `--jobs 44` took 5 min 44 s on 44 cores; the slowest dictionary takes about 32 s. - -### `.motion` and `.motionmatcher` clips - -A `.motion` clip has no animation of its own; it lists other clips (its children), which it presumably blends. Its -fields are in the object table above. Measured on all 17,247 `.motion` clips: - -- `+0x18` points at the dictionary root, `+0x28` is the clip's own hash (the low half of its `atMap` key) and `+0x2C` - is the dictionary's `joaat32(name)`. `+0x58` is 1 on 8,932 and 2 on 8,315. -- They have 159,584 children `{clip hash, dictionary hash}`. For every child, the dictionary hash is one of the - root's hash-only `+0x70` references (159,584 of 159,584), so those references are the dictionaries the - `.motion` clips draw from. -- 114,925 children name a dictionary in anim.rpf, and 111,948 of those (97.4%) name a `.clip` of that - dictionary. The other 2,977 name a hash that is not a clip there. -- The remaining 44,659 children name one of the 1,902 referenced dictionaries that are not in anim.rpf. A local - search of every clip-dictionary-like root page in `levels`, `packs`, `story000`, `story000_script`, - `story000_restofworld`, `core_restofworld`, `core_restofworld001`, `shared_minigame000`, `data`, `common` and - `script` found none of those hashes, so this package does not resolve them. -- **Child times (`+0x70`).** One 0x28-byte item per child on all 17,247: the child's duration, its duration in the - blend, and a piecewise-linear curve from child time to blend time. Of the 159,584 items, 158,991 have equal - durations and the two points (0, 0) and (d, d), so the child plays at its own speed. 402 have a 5–82 point curve - from (0, 0) to (duration, blend duration), increasing in both coordinates, so the child is time-warped. The other - 191 have two points, but 170 don't start at (0, 0) and 21 don't end at (d, d). For every child that names a - `.clip` in anim.rpf, the first float is bit-for-bit that `.clip`'s duration (`+0x78`): 111,948 of 111,948. -- **Parameter node.** When `+0x58` is 1 the node is at `+0x138`; when it is 2, `+0x120` points at a block whose - `+0x18` is the node. Every `.motion` has one, and it starts `{u64 0, u32 type, u32 0}`. By type: 3 on 10,171, 1 on - 3,557, 4 on 2,644, 5 on 482, 6 on 295, 8 on 98. -- **Axes by type.** Types 3, 4, 5, 6 and 8 have 1, 2, 3, 4 and 5 axes: `+0x10` is a `{ptr, count}` array of 8-byte - `{u32 name hash, u16, u16}` entries, with that count on every node of each type (the two u16 are not decoded). - Type 1 has no axis array and a sample count at `+0x20`: 1 on 3,552, 2 on 5. Types 4, 5, 6 and 8 keep their - sample count at `+0x90`, `+0x90`, `+0x50` and `+0xA0`: on all 2,281 of them that are a `.motion`'s only node, it - equals the number of `+0x90` sample lists below. The word list resolves 1,135 of their 8,404 axis names, the same - names as type 3 (`verticalheight`, `yawangle`, `surfaceincline` the most); `anim_clips.py` counts them as - `motion_node_axis_name::`. Types 4–8 have a second `{ptr, count}` array at `+0x20` - (found by @ismailchaka1): null on all 2,644 type-4 nodes and on 431 of the 482 type-5 nodes, present on the other - 51 type-5 nodes and on every type-6 (295) and type-8 (98) node. On all 393 type-6 and type-8 nodes its 16-byte - items read `{u32, u32 0, u32, u32 0}` and none of those words is one of the node's axis names or the `.motion`'s - child or dictionary hashes; on type 5 only 2 of the 51 arrays have that shape. The item count is 5 on 184 type-6 nodes, 3 on 57, 2 on 44; 9 on 47 type-8 nodes and 6 on 42. - It equals the child count on only 5 of the 444 nodes. Not decoded; `anim_clips.py` counts the item counts as - `motion_node_pairs::`. -- **Type 3: one sampled axis.** It has one axis entry, then 1–16 `{u32 sample index, f32 value}` items and the - axis min and max. On all 10,171 (29,123 samples), the items are sorted by value, min and max are the first and - last values, and the sample indices are 0..n−1 in some order. They are not child indices: the sample count - equals the child count on 4,589 of them. The name hashes are `joaat32` of a lower-case name. 88 distinct hashes - occur, and a word-list search resolved 10 of them, covering 5,604 axes: `yawangle` 2,524, `rotationz` 1,691, - `facingdirection` 638, `speed` 284, `surfaceincline` 271, `roll` 66, `verticalheight` 58, `pitch` 25, - `pitchangle` 25, `height` 22. The ranges fit the names: `speed` is within [0, 1], `surfaceincline` within - ±0.698 rad (40°), and `roll` within ±3.14. `anim_clips.py` reports every name as `motion_axis_name:`. -- **Samples to children (`+0x90`).** A `{ptr, count}` array of one `{ptr, count}` list per sample of the parameter - node; a list item is 12 bytes, `{u32 child index, f32, f32}`. On all 8,932 `.motion`s whose only node is at - `+0x138` (`+0x58` 1), the number of lists equals the node's sample count, every child index is below the child - count, and every child is played by at least one sample. So sample index k plays the child in list k: the type-3 - sample index is not a child index, it goes through this list. 8,903 have one item in every list; the other 29 - (types 5, 6 and 8) have lists of several children. On the 6,970 where the sample count equals the child count, - list k names child k; on the other 1,962 there are more samples than children and some children are played by - several samples. The first float is 1.0 on every item of types 1, 3 and 4 (36,830) and on all but 576 of the - 57,043 items of types 5, 6 and 8; the second is 1.0 on 76,604 of the 93,873 items. Neither is decoded. By type - (one-node motions, samples equal to children / more): 1: 1,176 / 0, 3: 4,545 / 930, 4: 1,009 / 479, 5: 154 / - 271, 6: 44 / 226, 8: 42 / 56. `anim_clips.py` counts these as `motion_samples::*`. -- Not decoded: where types 4, 5, 6 and 8 place their samples in parameter space (no array of theirs has one entry - per sample; most have a pointer at `+0x30`), the two u16 of an axis entry and the two floats of a sample item, how a - `.motion` with `+0x58` 2 (a block array at `+0x120` with several nodes) shares the `+0x90` lists among its - nodes, and the rest of the object from `+0x80`. - -The 180 `.motionmatcher` clips sit in 142 dictionaries that hold only `.motionmatcher` clips and no local pack. -The three motion matcher streams in [Bone tables and motion matchers](#bone-tables-and-motion-matchers) -(`0x101c379a0`, `0x101c41d50`, `0x101ea66c0`) are the second system pages of three of those dictionaries, with 2, 1 and 2 -`.motionmatcher` clips. - -A `.motionmatcher` object has fields up to `+0x18F`; they are in the object table above, and `anim_clips.py` decodes them -(`parse_matcher`) and counts them as `matcher_*`. Measured by `parse_matcher` on the pages of all 142 dictionaries -(180 clips): - -- **Arrays** keep a u32 count at pointer − 4 and a u32 capacity at pointer − 8, not the `{ptr; u16 count}` of the - rest of the dictionary. -- **Records (`+0x58`).** 4,562 records (1–346 per clip, measured separately). The third float is −1.0 in all of - them, and the u32 is the record's position on 175 of 180 clips. The first float is 0 or 0.03–2.37 and the second - one of 2.5, 5, 6.667, 10, 15, 20, 30 or 40 (also measured separately); that they are a start time and a sample - rate is a hypothesis. -- **Offsets (`+0x68`).** One more than the records on 180 of 180, starting at 0 and never decreasing, so an offset - table into data not decoded here. -- **Clip table (`+0xA0`).** An open-addressing hash table: the group count is a power of two (2 on 151 clips, - measured separately), every control byte is 0x80 or below 0x80, the last word of every slot is 0 (measured - separately), and the full slots equal the entry count on 180 of 180. Its 4,381 slots hold a clip hash that is a - clip in anim.rpf (4,381 of 4,381) and a clip index; the indices are 0..n−1 over the entries on 180 of 180. The - matcher's clips are these n entries, and its records are cut from them: a record's fourth word is its clip's - index and the record lies in that clip's `+0x78` range on 180 of 180 (`matcher_record_clip_in_its_u16_78_range`). - There is one clip per record on 175; on the other 5 some clips have several records. The second word names the - clip's dictionary: measured separately against the 60,778 dictionary names of anim.rpf, it is `joaat32` of the - dictionary's name behind a fixed 8-character prefix on 4,356 of 4,381 entries (the slot's clip is in that - dictionary on 4,349), the plain dictionary hash on 18, and neither on 7. 177 of 180 matchers resolve all their - entries this way. -- **References (`+0x98`).** 36 clips have one `{clip hash, dictionary hash}` per clip (439). All 439 resolve to a - clip of that dictionary in anim.rpf, and the item at each table slot's clip index names that slot's clip on all - 36. On those 36, the dictionary the second word names is the reference's on 438 of 439 (measured separately), so - the table gives the dictionary for the other 144 too. -- **Key table (`+0x170`).** The same table with 8-byte slots, 2 groups on all 180: 403 entries of `{u32 hash, u32 - index}`, the indices 0..n−1 on 180 of 180. 38 entries are clip hashes in anim.rpf; there are 23 distinct hashes - (measured separately). -- **Where an entry sits.** Every entry is where its hash h puts it: control byte h & 0x7F, in group - (h >> 7) & (groups − 1), or, when that group is full, in a later one with every group in between full (linear - probing), on 180 of 180 for each of the three tables (`table_placed_by_key`). The key table and the features' - `+0x48` table hash an entry by its own first u32. The clip table hashes the u64 of its first two words (clip - hash low, second word high) with MurmurHash3's 64-bit finaliser (`fmix64`, `clip_slot_hash`): 4,351 of its - 4,381 entries sit in their home group and the other 30 after full groups (measured separately). -- **Self (`+0x188`).** The clip's own hash and the dictionary's `joaat32(name)` on 180 of 180. -- **`+0x78` and `+0xB8`.** The u16 array has one item per clip and then one more, on 180 of 180: it starts at 0, - never decreases and ends at the record count, so item i is clip i's first record. The u8 array has one item per - clip on 180 of 180 and is 0 or 1; 16 items are 1. (With one clip per record, on 175, both also fit "one per - record".) -- **Features (`+0x20`).** Each matcher points to a feature object with a list of features: 1,873 in all, distinct - name hashes within each clip on 180 of 180 (1–21 per clip and 53 distinct names overall, measured separately). Widths are multiples of 3 on 180 of 180 - (3, 6, 9 or 12, measured separately), and the columns chain from 0 (each feature starts where the one before - ends) on 180 of 180, so a clip's features fill 6–126 columns (11,616 in all; the range measured separately), - and the pose matrix below has one column per feature column. The `+0x48` table has one slot per feature, with the indices 0..F−1 on - 180 of 180; its hashes are not the `+0x18` name hashes (0 of 180, measured separately). `+0x0E` is 1 on 1,842 - features and 5 on 31, all 31 in clips with the blocks layout (measured separately). With 1, the name hash is - `joaat32` of a bone name of the clip's skeleton on 1,842 of 1,842, and `+0x1C` is a set of bits that gives the - width: 3 columns for bit 0, 3 for bit 1 and 6 for bit 3, on 1,842 of 1,842 (kinds 1, 3, 9 and 11 are seen, - measured separately). That bit 0 is the bone's position, bit 1 its velocity and bit 3 a rotation written as two - vectors is a hypothesis; the pose check below supports it for position and rotation. With 5, `+0x18` names no - bone (0 of 31): `+0x1C` is 0 on 20 and `+0x18` is 0 on the other 11. Measured separately, the nonzero words of - the 30 three-column ones are `joaat32` of names that are not bones (a word list resolves some of them). -- **Skeleton (feature object `+0x28`).** 3,918 bones over the 180 clips. One root and every parent before its - child on 180 of 180, the bones' parent field is the `+0x40` array, and the tag table holds exactly two tags per - bone, `joaat32` of its name and its u16 id, on 180 of 180. The root's id is 0 and every other bone's is the ELF - hash of its upper-cased name, mod 0xFE8F, plus 0x170, on 180 of 180 (3,738 bones; `bone_id`). The local - matrix is the bone's rotation and translation, and the inverse bind matrix times the product of the local - matrices up the chain is the identity (to 2e-3), on 180 of 180. `+0x48` is a prefix tree of the bone names - (shared prefixes stored once): walking it, a node whose value lands in the u16 array after the tree names the - bone in that slot, and every bone's name leads to that bone, on 180 of 180 (`skeleton_name_tree`). The array - lists the bones in tree order (measured separately). `parse_matcher` returns it all as `skeleton`. -- **Per sample (`+0x98`).** In both layouts, one u32 per sample, the same for every sample of a record, on 180 of - 180. It is a bit mask over the key table's indices: the bits set over all samples are exactly bits 0..K−1, with - K the key table's entries, on 180 of 180 (`matcher_sample_u32_bits_are_key_indices`), so each record carries the - set of keys (tags) that apply to it. -- **Pose matrix (feature object `+0xF0`).** One row of f16 values per sample, one column per feature column. The - sample count equals the last `+0x68` offset on 180 of 180 (36,436 samples), so record i owns the rows from - offset i to offset i+1, and the column count is the features' total on 180 of 180. Two layouts, told apart by - the feature object's `+0x30` object (149 with it, 31 without): - - **Rows** (149): row-major, each row padded with zero columns to the next multiple of 16 (`+0x100` chunks of 16). - - **Blocks of 8** (31): 8 samples at a time, column-major inside a block, so column c of sample r is at - `(r // 8) · D' · 8 + c · 8 + r mod 8`, with D' the column count rounded up to even (the spare column is zero). - The lanes after the last sample repeat it. - - The sizes fit these layouts on 180 of 180 (`parse_matcher` refuses one that doesn't), every value is finite and - the padding is as described on 180 of 180. On the 149 with rows, `+0xA8` has one 48-byte item per sample: a - unit quaternion, a vec3 and a scale of (1, 1, 1) on 149 of 149. It is the sample's reference frame: the - quaternion is a rotation about z only on 30,946 of the 30,962 samples, and the frame comes from the `+0x30` - object's weighted bones (below). `anim_clips.matcher_pose` reads one row. - - Measured separately by decoding the clips' own keyframes at each sample's time (up to two clips per matcher, - 285 clips; record start + j / the record's rate), a feature holds its bone's pose in that frame: - - position columns are the bone's model-space position minus the frame's vec3, rotated by the frame's inverse, - on 11,469 of 12,873 samples (to 0.01 m); - - the two vectors of bit 3 are rows 0 and 1 of the bone's model-space rotation, in the same frame, on 2,233 of - 2,544 (to 0.02); - - the frame's x and y are the weighted centroid of the object's bones on 1,148 of 1,233 samples; its z is the - centroid's z with flag 6, and −1.0 on every sample on 29 of the 32 form 1 matchers with flag 7 (all 149 - matchers counted); - - its yaw is the heading from the first to the second bone with form 2 (682 of 752), and the z-twist of the - reference rotation's inverse times the bone's rotation with a one-bone form 1 (89 of 89). - - Velocity columns (bit 1) fit a plain difference of the model-space position on only 1,960 of 9,366 samples, so - they are not decoded. A record's rows cover part of its clip, not all of it: - with rows 1 / (the record's second float) seconds apart, they fit inside the clip's duration on 2,108 of the - 2,155 records whose clip duration is known without ambiguity (measured separately), which fits the sample-rate - hypothesis above. Which part of the clip they cover is not decoded. -- **One-item arrays.** The matcher's `+0x48` is one 40-byte item, zero except a u32 1 at `+0x20`; `+0x118` is - one u32 equal to the pose sample count; `+0x128` is one u16, 0; each on 180 of 180. -- **`+0x30` object.** On the 149 clips that have it, its `+0x08` is 2 on 93 and 1 on 56. It names the bones the - pose frame is built from (above). With 2: two distinct bones of the clip's skeleton by `joaat32` of their names - at `+0x10`/`+0x14` (93 of 93), and at `+0x30` a copy of the clip's first feature (its `+0x0E`, name hash and - kind, 93 of 93) whose width is at `+0x68` (by the bit rule above, 93 of 93); the u16 at `+0x6C` is 6 on 92 and - 9 on 1. With 1: the arrays at `+0x40` and `+0x50` have the same count n (1, 3, 4 or 6, measured separately), and - the first holds bones of the skeleton by `joaat32` of their names (56 of 56); `+0x10` is a unit quaternion (56 - of 56), and the u32 at `+0x60` is 6 on 24 and 7 on 32. Its weights (form 2: the f32s at `+0x18`/`+0x1C`; form - 1: the second array) are positive and sum to 1 on 149 of 149. -- **Column weights (`+0xB8`).** One f32 per pose column, stored 8 to a 32-byte chunk with zeros after the last - column (the count at `+0xB4` is the chunks), on 180 of 180. They are positive and sum to 1, and the three - columns of each vec3 have the same weight, on 180 of 180 (`matcher_column_weights_*`). They are not the - reciprocal, the deviation or the variance of their columns over the samples (measured separately), and a - clip's weights and `+0xC0` are the same for every clip with the same features on 20 of 23 feature sets - (measured separately), so they look like settings, not statistics. `+0xC4` is 1.0, and `+0xC8` is 1 with rows - and 3 with blocks of 8, on 180 of 180. -- Not decoded: the hash of the features' `+0x48` table. It is a function of the feature's `+0x0E` and `+0x18` - only (53 distinct pairs, no conflict), and, measured separately, it is not case-sensitive or case-folded - joaat32 (with any constant seed or prefix, or a suffix of up to 3 characters), one-at-a-time, FNV-1/1a 32 or 64, - ELF, CRC-32, MurmurHash3 32, MurmurHash64A, or `fmix32`/`fmix64` of the name hash or the bone id. Also not - decoded: the velocity columns, the yaw rule of a form 1 object with several bones (the z-twist of their - weighted inverse-bind rotations fits only to 0.15 rad, 353 of 392 samples), why form 1's quaternion is not - the blend of its bones' bind rotations (15 of 56), the width-9 feature with `+0x0E` = 5, and the f32 at - `+0xC0`. - -### Other archives - -The same tool reads `story000.rpf` with no change: of 34,533 roots with the dictionary header, 34,518 join (7 with a -gap page) and 9,190 are clip dictionaries. The other 25,328 roots have some other value at `+0x70` and are not clip -dictionaries; 15 roots do not join. All 59,593 animations of those dictionaries decode with every check passing, and -all 54,352,969 type-10 chunk boundaries close. Its 14 `.motion` clips have 75 children, and all 75 name a `.clip` of a -dictionary in `story000.rpf`. None of its 9,188 distinct dictionary hashes is a dictionary in anim.rpf, and none is -one of the 1,902 hashes anim.rpf refers to without having them. - -``` -python -I tools/anim_clips.py \pack\story000\story000.rpf \story000-clips.json --jobs 20 -``` - -## Rig dictionaries - -`tools/anim_rigs.py` reads the four `RIG` roots above (ASSET-20). Run on the 1.0.2.1 copy: - -```powershell -python -I tools/anim_index.py \anim.rpf \anim-index.json --rigs \rigs.json -python -I tools/anim_rigs.py \anim.rpf \anim-rigs.json --rigs \rigs.json -``` - -The output holds counts and one row per rig dictionary (offset, name, hash, entry count), no table items. - -**Layout.** The root is the clip dictionary's: `+0x38` atString name, `+0x48` atMap, `+0x68` `joaat32(name)` (4 of -4), and at `+0x70` the bytes `RIG` and a version byte (2 in all four). Every map key has a zero high half (3,897 of -3,897). Every map value has a pointer at `+0x20` to a **`RIG` block** (3,897 of 3,897): `RIG`, a version byte (2), -a u32 length of what follows, then tables `{u32 kind hash; u32 size = 0xC + 8 × count; u32 count; u32 word}`, each -followed by `count` 8-byte items `{u32 hash; u32 word}`, with other bytes between the tables. The other bytes and -the item words are not mapped. - -**The four dictionaries are the four RBF0 sources.** Their names are the four source strings of the rig-set -manager: - -| Name | Entries | Keys that are `joaat32` of an RBF0 rig | -|---|---:|---:| -| `canonical@legacy` | 22 | 16 | -| `canonical@source` | 543 | 534 | -| `generated@source` | 1,256 | 1,188 | -| `pipelined@source` | 2,076 | 1,931 | - -These are the distinct-rig counts per source in [the RBF0 table above](#tail-rbf0-rig-set-manager). The other 228 -keys are not named by any RBF0 entry. **All 6,677 RBF0 entries resolve**: the entry's `Dictionary` text is the -rig dictionary's name, and `joaat32(lowercase Rig path)` is a key in it (6,677 of 6,677; 0 in another dictionary, -0 missing). So a rig set reaches its rigs' `RIG` blocks through rig-set → `{Dictionary, Rig}` → rig dictionary → -key → `+0x20`. - -**Tables.** 6,606 tables are found in the 3,897 blocks. Four kind hashes hold all but 5 of them; the 5 are single -hits whose "kind" is an f32 near 1.0 (`0x3f7f....`, `0x3f76....`) or a small integer, so they are float data that -happens to fit the header rule. The kind names are not resolved: - -| Kind | Tables | Items | Items that are a clip track's bone hash | -|---|---:|---:|---:| -| `0x74d00508` | 2,642 | 13,210 | 0 | -| `0x2316833f` | 2,437 | 118,853 | 91,559 | -| `0xb688b77e` | 1,427 | 72,528 | 39,880 | -| `0x5e25d3bf` | 95 | 4,416 | 0 | - -"A clip track's bone hash" means the hash is the bone of some track in the 191,042 decoded animations. - -**Rigs are not the clips' skeletons.** The clip side was measured with a local script over the same -`anim_clips.py` parse: for each of the 52,752 clip dictionaries with bone tracks, the union of its -`bonerotation`/`bonetranslation` bone hashes (mover track 0 left out). - -- Against the 596 hashed names of the shared humanoid skeleton ([character_skeleton.md](character_skeleton.md)), - 44,359 dictionaries have at least 90% of their bones in it (16 have all of them). -- Against the rigs (the items of the two bone-bearing kinds above), no rig set covers the clips of a humanoid - dictionary. Even the union over all the rigs of one rig set reaches 80% of a dictionary's bones for 11 of those - 44,359. Only 4 dictionaries, all of objects, are covered completely by a rig set. - -So humanoid clips bind to the fragment skeleton, not to a `RIG` block. The rig tables look like per-rig bone or -channel subsets (the RBF0 groups are `deformation`, `pose`, `identity`, `facial` and others); that reading is not -measured. The auxiliary table on the second `0DRP` page is [framed above](#packed-clip-streams). Which model -or skeleton each non-humanoid clip dictionary drives remains open. - -### Can the fragment bone names identify a clip's model? (ASSET-158) - -In the ASSET-158 scan, bone coverage identified **zero unique fragments** for the 8,393 dictionaries below the 90% humanoid -threshold above. This comparison used the named fragment tables recovered from `packs.rpf` in Xbox 1.0.2.1. -The threshold selects dictionaries for investigation; some may still animate humanoids. - -| Coverage of a dictionary's nonzero rotation and translation bones | Dictionaries | -|---|---:| -| At least one bone absent from the union of the recovered fragment tables | 7,817 | -| Every bone in the union, but no individual table contains them all | 573 | -| One or more individual tables contain every bone | 3 | - -Each of the last three dictionaries animates just one bone. Each matches **82 fragment pages** spanning -**50 distinct bone sets**. Choosing the first matching page would assign a model arbitrarily. - -To reproduce the comparison: - -1. Walk all 144,364 streams returned by `anim_index.scan_rpf` for `packs.rpf`. In each inflated page, find - the first NUL-terminated `.#ft` suffix before the last NUL-terminated `skel` marker. Between them, hash - the NUL-terminated ASCII runs matching `[A-Za-z0-9_]+` with `anim_index.joaat32`. -2. Read aligned little-endian `{u32 hash, u32 index}` pairs in the page prefix ending before the suffix. - The archive scan retained a hash in the name set when its index was less than or equal to the number - of distinct name hashes. This inclusive filter selects candidates across pages. The reference - hash table itself uses zero-based indices 0 through 595. This recovers - 596 hashes on the [known reference page](character_skeleton.md#the-skeleton-name-table). Across the archive, - 2,849 pages yield a nonempty set, with 524 distinct sets. This check covers pages with that name and - hash layout; other skeleton layouts remain open. -3. Group and parse the `anim.rpf` dictionaries with `anim_clips.group` and `anim_clips.parse_dictionary`. - Union the nonzero rotation and translation bone hashes across each dictionary's local packs. Keep - dictionaries for which fewer than nine tenths of those hashes occur on the reference page. -4. Require **all** bones of a retained dictionary to occur on the **same** fragment page. Count matching - pages before deduplicating identical bone sets, so repeated fragments remain distinguishable. - -### Explicit model-to-dictionary references in `levels.rpf` - -The ASSET-158 scan of archetype metadata linked **1,324 model asset names and 159 clip dictionaries** -in Xbox 1.0.2.1. Of those dictionaries, **63** carry local rotation or translation tracks below the humanoid -coverage threshold. Their archetypes name **488 distinct model assets**. This identifies which dictionaries -the archetypes reference; the per-bone mapping onto each model's skeleton still needs independent evidence. - -1. Walk the complete version-122 `0DRP` metadata resources in `levels.rpf` with `world_census.assemble` - and the `Meta` reader in `world_lights_paths.py`. For each `CBaseArchetypeDef` or `CMloArchetypeDef` - block with the fields, find `assetName` and `clipDictionary` through the struct's own member table - using their case-sensitive joaat hashes. Read the two u32 name hashes from the same instance. - Across 188,449 complete metadata resources, 15,394 records carry a nonzero dictionary reference, - giving 161 distinct dictionary hashes. -2. Search **the same archive** for clip dictionary roots. At each 16-byte-aligned zlib stream start, - check `anim_clips.is_root` and the dictionary hash at `+0x68` against those references. Join consecutive - system pages as needed to parse the dictionary. Require a nonempty clip map and a name at `+0x38` - whose lowercase joaat equals the stored hash. The scan confirmed 159 of the 161 referenced hashes. - A direct hash comparison against the 52,752 bone-bearing dictionaries in `anim.rpf` found zero matches. - Applying the same root and clip-map checks to the other 21 RPF archives (85,152,072,416 bytes) - yielded no additional matches. The two references unresolved by that scan appeared in 43 and 64 archetype records, - covering two and 16 distinct asset names respectively. This search covers readable dictionary roots - at aligned zlib stream starts. Other storage layouts remain possible. -3. Deduplicate the resulting `(assetName, clipDictionary)` pairs. Of the 159 confirmed dictionaries, - 55 are referenced by one distinct asset name each. The remaining 104 are shared. Across their local - animation packs, 63 dictionaries have nonzero rotation or translation bone hashes and 96 have none. - All 63 fall below the 90% reference-skeleton threshold used above. -measured. Still open in ASSET-20: the `0DRP` "2/3 packed clip streams" ([above](#packed-clip-streams)) and which -model or skeleton each non-humanoid clip dictionary drives. - -## `MoVE` state-machine containers - -`tools/anim_move.py` decodes all 324 `MoVE` (version 19) resources in `anim.rpf` (ASSET-86): - -```powershell -python -I tools/anim_move.py \anim.rpf \anim-move.json -``` - -All 324 resources (325 zlib streams, 331,771 stored / 1,494,188 inflated bytes once the 64 KiB stream at -`0x105a7d000` is joined with its 5,563-byte continuation stream at `0x105a7f9c0`) decode with 0 errors. Unlike clip -dictionaries and `0DRP` resources, a `MoVE` resource has no virtual `0x50xxxxxx` pointers or RAGE page map: every -internal cross-reference is a signed 32-bit self-relative byte offset (`target = field_offset + rel_i32`). - -### Header and variable preamble - -After the fixed 32-byte header (`"MoVE"`, `u32 version = 19`, three zero `u32`s, `u32 network_hash` at `+0x14`, -`u32 body_size` at `+0x18`, `u32 0` at `+0x1C`), a variable-length preamble starts at `+0x20`: - -| Field | Type | Measured across 324 resources | -|---|---|---| -| `N_req`, `requests` | `u32`, `N_req × u32` | `0..16` request hashes (`> 0` in 149 resources, 543 entries total) | -| `N_flag`, `flags` | `u32`, `N_flag × u32` | `0..27` flag hashes (`> 0` in 123 resources, 687 entries total) | -| `preamble_mode` | `u32` | `0` in 225 resources, `1` in 91, `2` in 8 | -| `N_desc`, `descriptors_5b` | `u32`, `N_desc × {u32 hash; u8 kind}` | `0` in 184 resources, `1..15` in 140 (272 entries total; `kind` = `0`: 20, `1`: 92, `2`: 74, `4`: 1, `7`: 85) | -| `tail` | `{u16 sub_flag; u32 ref_hash_0; u32 ref_hash_1}` | 10 zero bytes whenever `preamble_mode` is `0` or `1` (316/316); `sub_flag = 1` with two non-zero reference hashes when `preamble_mode == 2` (8/8) | - -The root state container starts immediately after the 10-byte tail at -`node_start = 48 + 4 * (N_req + N_flag) + 5 * N_desc` (`58..244` bytes). `body_size` at `+0x18` counts the -request/flag arrays, three `u32` preamble words and the entire state graph (`body_size == 12 + 4 * (N_req + N_flag) + -graph_bytes`), excluding the 46 fixed/tail bytes and the `5 * N_desc` descriptor table: - -$$\text{total\_bytes} = 46 + 5 \cdot N_{\text{desc}} + \text{body\_size}$$ - -holds exactly for **324 of 324** resources. - -### Recursive state containers (`Type 1`, `Type 3`, `Type 22`) - -Every node in the graph starts with `{u16 type; u16 index; u32 name_hash}`. Three container types form the recursive -state-machine and motion-tree hierarchy (**1,616** containers across the 324 resources). All three share a 36-byte -(`0x24`) common prefix: - -``` -+0x00 u16 type (1 = StateMachine, 3 = InlinedStateMachine, 22 = MotionTree) -+0x02 u16 index (0 on root/child states; node index inside an enclosing MotionTree) -+0x04 u32 name_hash (joaat32; e.g. joaat32("statemachine") = 0x1997df3c, joaat32("motiontree") = 0x8d398f99) -+0x08 i32 init_or_root_rel (target = off + 0x08 + init_or_root_rel) -+0x0c u32 flags (0 or 1) -+0x10 u8 b10, u8 b11, u8 n_children, u8 n_transitions -+0x14 four u32 words (0 in all measured Type 1 and Type 3 headers) -``` - -| Container type | Instances | Header & body layout after `+0x24` | -|---|---:|---| -| `Type 1` (`StateMachine`) | 230 (63 at file root, 167 nested) | `0x58`-byte header: `+0x24` `i32 transitions_rel` (`off + 0x58 + 8 * n_children` when `n_transitions > 0`, or `0`), `+0x44` `f32 1.0`, `+0x50` `u32 n_default_transitions`, `+0x54` `i32 default_transitions_rel`. At `+0x58`: `n_children` 8-byte child directory entries `{u32 child_hash; i32 child_rel}` (`target = entry + 4 + child_rel`), then `n_transitions` outgoing transitions, `n_default_transitions` default transitions, and the `n_children` child state containers (`Type 1` or `Type 22`). In 230 of 230 instances, `init_target` is in the child directory and every child's `+0x04` hash matches its directory `child_hash`. | -| `Type 3` (`InlinedStateMachine`) | 132 (all inside a `MotionTree`, 332 child states) | Same header as `Type 1` through `+0x54`, plus `u32 n_inputs` at `+0x58` (`1..2`, 151 inputs total) and `n_inputs × i32 input_rel` at `+0x5c` (`target = (off + 0x5c + 4*i) + input_rel`, pointing to the input pose node in the enclosing `MotionTree`). The `n_children × 8`-byte child directory follows at `off + 0x5c + 4 * n_inputs`, then `n_default_transitions` (114 total) and the `n_children` child states. | -| `Type 22` (`MotionTree`) | 1,254 (261 at file root, 993 nested) | `0x30`-byte header: `+0x24` `i32 transitions_rel` (always `0x0c`, so transitions start at `off + 0x30`), `+0x28` `i32 param_blocks_rel`, `+0x2c` `u32 n_param_blocks`. Followed by `n_transitions` outgoing transitions, `n_param_blocks` length-prefixed parameter blocks, and the motion-tree node arena (`3,875` declared children; first node has `index == 0`, root expression node is at `off + 0x08 + init_or_root_rel`). | - -### Transitions, parameter blocks and motion-tree nodes - -- **Outgoing state transitions (1,097 total: 77 on `Type 1`, 1,020 on `Type 22`):** each transition record carries its - own byte length as `u32 size` at `+0x10` (`size >= 0x4c`; `76`, `84`, `88`, `92`, `96`, ... bytes), a signed relative - offset to the target state at `+0x48`, and (when `size >= 0x50`) a `u32 condition_kind` at `+0x4c` followed by - `size - 0x50` bytes of condition hashes and thresholds. Summing `size` across `n_transitions` matches the exact - transition block span in **100%** of containers. -- **Default / any-state transitions (491 total: 377 on `Type 1`, 114 on `Type 3`):** each record starts with - `{u16 size; u16 condition_count; i32 target_rel}` (`size >= 16`). Summing `size` across `n_default_transitions` - matches `first_child - def_tr_start` in **100%** of containers. -- **MotionTree parameter blocks (2,104 total across the 1,254 `MotionTree`s):** each block starts with - `{u32 block_size; u8 index, b1, b2, b3, b4, b5, b6, b7}` (`b7 == 0` in all 2,104), followed by - `(b1 + b2 + b3 + b4)` 16-byte parameter/signal bindings (`3,683` total), `b5` 8-byte output/event bindings (`591` - total), and `b6` variable-length curve/expression sub-records (`632` total, each carrying `u16 sub_size` at `+0x04`). - The byte identity - $$\text{block\_size} = 12 + 16(b_1 + b_2 + b_3 + b_4) + 8b_5 + \sum_{k=1}^{b_6} \text{sub\_size}_k$$ - holds in **2,104 of 2,104 (100%)** blocks. -- **MotionTree root expression nodes (1,254 total):** the root node at `init_target` is most commonly `Type 11` - (clip leaf, 216), `Type 4` (2-way blend, 193), `Type 3` (`InlinedStateMachine`, 132), `Type 2` (12-byte output leaf, - 116), `Type 28` (filter/modifier, 94), `Type 9` (directional blend, 83), `Type 1` (nested `StateMachine`, 81), - `Type 10` (N-way blend, 72), `Type 12` (parameterized motion, 55), `Type 19` (additive blend, 49), `Type 15` - (20-byte unary node, 48), `Type 5` (44-byte blend, 42), and `Type 23` (8-byte identity pose leaf, 20), plus 13 - rarer operator types (`6, 8, 18, 25, 27, 31, 32, 34, 36, 37, 39, 40, 41`, 53 total). - -## `MoVE` state-machine containers - -`tools/anim_move.py` decodes all 324 `MoVE` (version 19) resources in `anim.rpf` (ASSET-86): - -```powershell -python -I tools/anim_move.py \anim.rpf \anim-move.json -``` - -All 324 resources (325 zlib streams, 331,771 stored / 1,494,188 inflated bytes once the 64 KiB stream at -`0x105a7d000` is joined with its 5,563-byte continuation stream at `0x105a7f9c0`) decode with 0 errors. Unlike clip -dictionaries and `0DRP` resources, a `MoVE` resource has no virtual `0x50xxxxxx` pointers or RAGE page map: every -internal cross-reference is a signed 32-bit self-relative byte offset (`target = field_offset + rel_i32`). - -### Header and variable preamble - -After the fixed 32-byte header (`"MoVE"`, `u32 version = 19`, three zero `u32`s, `u32 network_hash` at `+0x14`, -`u32 body_size` at `+0x18`, `u32 0` at `+0x1C`), a variable-length preamble starts at `+0x20`: - -| Field | Type | Measured across 324 resources | -|---|---|---| -| `N_req`, `requests` | `u32`, `N_req × u32` | `0..16` request hashes (`> 0` in 149 resources, 543 entries total) | -| `N_flag`, `flags` | `u32`, `N_flag × u32` | `0..27` flag hashes (`> 0` in 123 resources, 687 entries total) | -| `preamble_mode` | `u32` | `0` in 225 resources, `1` in 91, `2` in 8 | -| `N_desc`, `descriptors_5b` | `u32`, `N_desc × {u32 hash; u8 kind}` | `0` in 184 resources, `1..15` in 140 (272 entries total; `kind` = `0`: 20, `1`: 92, `2`: 74, `4`: 1, `7`: 85) | -| `tail` | `{u16 sub_flag; u32 ref_hash_0; u32 ref_hash_1}` | 10 zero bytes whenever `preamble_mode` is `0` or `1` (316/316); `sub_flag = 1` with two non-zero reference hashes when `preamble_mode == 2` (8/8) | - -The root state container starts immediately after the 10-byte tail at -`node_start = 48 + 4 * (N_req + N_flag) + 5 * N_desc` (`58..244` bytes). `body_size` at `+0x18` counts the -request/flag arrays, three `u32` preamble words and the entire state graph (`body_size == 12 + 4 * (N_req + N_flag) + -graph_bytes`), excluding the 46 fixed/tail bytes and the `5 * N_desc` descriptor table: - -$$\text{total\_bytes} = 46 + 5 \cdot N_{\text{desc}} + \text{body\_size}$$ - -holds exactly for **324 of 324** resources. - -### Recursive state containers (`Type 1`, `Type 3`, `Type 22`) - -Every node in the graph starts with `{u16 type; u16 index; u32 name_hash}`. Three container types form the recursive -state-machine and motion-tree hierarchy (**1,616** containers across the 324 resources). All three share a 36-byte -(`0x24`) common prefix: - -``` -+0x00 u16 type (1 = StateMachine, 3 = InlinedStateMachine, 22 = MotionTree) -+0x02 u16 index (0 on root/child states; node index inside an enclosing MotionTree) -+0x04 u32 name_hash (joaat32; e.g. joaat32("statemachine") = 0x1997df3c, joaat32("motiontree") = 0x8d398f99) -+0x08 i32 init_or_root_rel (target = off + 0x08 + init_or_root_rel) -+0x0c u32 flags (0 or 1) -+0x10 u8 b10, u8 b11, u8 n_children, u8 n_transitions -+0x14 four u32 words (0 in all measured Type 1 and Type 3 headers) -``` - -| Container type | Instances | Header & body layout after `+0x24` | -|---|---:|---| -| `Type 1` (`StateMachine`) | 230 (63 at file root, 167 nested) | `0x58`-byte header: `+0x24` `i32 transitions_rel` (`off + 0x58 + 8 * n_children` when `n_transitions > 0`, or `0`), `+0x44` `f32 1.0`, `+0x50` `u32 n_default_transitions`, `+0x54` `i32 default_transitions_rel`. At `+0x58`: `n_children` 8-byte child directory entries `{u32 child_hash; i32 child_rel}` (`target = entry + 4 + child_rel`, 747 child states total), then `n_transitions` outgoing transitions, `n_default_transitions` default transitions, and the `n_children` child state containers (`Type 1` or `Type 22`). In 230 of 230 instances, `init_target` is in the child directory and every child's `+0x04` hash matches its directory `child_hash`. | -| `Type 3` (`InlinedStateMachine`) | 132 (all inside a `MotionTree`, 332 child states) | Same header as `Type 1` through `+0x54`, plus `u32 n_inputs` at `+0x58` (`1..2`, 151 inputs total) and `n_inputs × i32 input_rel` at `+0x5c` (`target = (off + 0x5c + 4*i) + input_rel`, pointing to the input pose node in the enclosing `MotionTree`). The `n_children × 8`-byte child directory follows at `off + 0x5c + 4 * n_inputs`, then `n_default_transitions` (114 total) and the `n_children` child states. | -| `Type 22` (`MotionTree`) | 1,254 (261 at file root, 993 nested) | `0x30`-byte header: `+0x24` `i32 transitions_rel` (always `0x0c`, so transitions start at `off + 0x30`), `+0x28` `i32 param_blocks_rel`, `+0x2c` `u32 n_param_blocks`. Followed by `n_transitions` outgoing transitions, `n_param_blocks` length-prefixed parameter blocks, and the motion-tree node arena (`3,875` declared children; first node has `index == 0`, root expression node is at `off + 0x08 + init_or_root_rel`). | - -### Transitions, parameter blocks and motion-tree nodes - -- **Outgoing state transitions (1,097 total: 77 on `Type 1`, 1,020 on `Type 22`):** each transition record carries its - own byte length as `u32 size` at `+0x10` (`size >= 0x4c`; `76`, `84`, `88`, `92`, `96`, ... bytes), a signed relative - offset to the target state at `+0x48`, and (when `size >= 0x50`) a `u32 condition_kind` at `+0x4c` followed by - `size - 0x50` bytes of condition hashes and thresholds. Summing `size` across `n_transitions` matches the exact - transition block span in **100%** of containers. -- **Default / any-state transitions (491 total: 377 on `Type 1`, 114 on `Type 3`):** each record starts with - `{u16 size; u16 condition_count; i32 target_rel}` (`size >= 16`). Summing `size` across `n_default_transitions` - matches `first_child - def_tr_start` in **100%** of containers. -- **MotionTree parameter blocks (2,104 total across the 1,254 `MotionTree`s):** each block starts with - `{u32 block_size; u8 index, b1, b2, b3, b4, b5, b6, b7}` (`b7 == 0` in all 2,104), followed by - `(b1 + b2 + b3 + b4)` 16-byte parameter/signal bindings (`3,683` total), `b5` 8-byte output/event bindings (`591` - total), and `b6` variable-length curve/expression sub-records (`632` total, each carrying `u16 sub_size` at `+0x04`). - The byte identity - $$\text{block\_size} = 12 + 16(b_1 + b_2 + b_3 + b_4) + 8b_5 + \sum_{k=1}^{b_6} \text{sub\_size}_k$$ - holds in **2,104 of 2,104 (100%)** blocks. -- **MotionTree root expression nodes (1,254 total):** the root node at `init_target` is most commonly `Type 11` - (clip leaf, 216), `Type 4` (2-way blend, 193), `Type 3` (`InlinedStateMachine`, 132), `Type 2` (12-byte output leaf, - 116), `Type 28` (filter/modifier, 94), `Type 9` (directional blend, 83), `Type 1` (nested `StateMachine`, 81), - `Type 10` (N-way blend, 72), `Type 12` (parameterized motion, 55), `Type 19` (additive blend, 49), `Type 15` - (20-byte unary node, 48), `Type 5` (44-byte blend, 42), and `Type 23` (8-byte identity pose leaf, 20), plus 13 - rarer operator types (`6, 8, 18, 25, 27, 31, 32, 34, 36, 37, 39, 40, 41`, 53 total). - -## Readable, compressed and still opaque - -- **Readable:** all 273 name tables (2,298 paths), the `0DRP` version/page count, 1,371 type-hash headers, - 1,781 clip-stream headers with their version split, two named clip records (durations and 0x48-byte track - arrays), the 63/38 and 12/38 bone masks (all 38 finger hashes resolve), the RBF0 mapping (1,126 rig sets / - 6,677 entries / 3,669 rigs), the four `RIG` dictionaries (3,897 entries / 6,606 tables), all 324 `MoVE` v19 - state-machine and motion-tree containers (1,616 state containers, 1,097 outgoing transitions, 491 default - transitions, 2,104 parameter blocks), one standalone bone-name list, and three motion matcher streams with - embedded bone tables (30-name union; 19 bone hashes present). -- **Outer compression:** the only compression this work inverts is the RPF9 zlib framing. Inflating the 130,470 - streams accounts for the 11.59 GB above. -- **No nested zlib:** in eight sampled zero-prefixed pages, none of the `78 01/5E/9C/DA` byte pairs started a - valid nested zlib stream. The outer zlib stream is the only compression layer observed. -- **No known codec at the sampled headers:** no zstd or LZ4 frame magic was found in the first 4 KiB of the - 130,449 indexed streams. gzip, bzip2 and lzma byte patterns occur, but none started a valid stream at the - sampled positions. - No Oodle signature is known from these bytes; none is guessed. -- **Still opaque:** high-entropy blocks inside `other` and zero-prefixed pages (4 KiB blocks up to 7.96 - bits/byte), the `0DRP` root objects and the meaning of their auxiliary payloads, the - 56 empty rig sets, the RBF0 numeric fields, and - the rig→skeleton link (0 measured matches). Of the 30 bone names, 19 have a confirmed stored hash and 11 do - not; the four motionmatcher paths bind to embedded tables, but not to an RBF0 rig. - -## Cross-check with the model and XML work - -- `models-out/data/models/manifest.json` (the only model manifest available here) has 1,350 models: 1,341 with - `HasBoneBindings`, 689 fragments, all with material entries. It exposes model names and 64-bit texture - `Id64` keys, but no bone names or skeleton hashes. -- None of the 1,350 model names occurs in the 8,020 animation paths collected here, and none occurs in the - `RBF0` rig metadata either. The sampled clip hash `0x25ed0554e58ba1fc` and the recurring `0x98e1750c` are - absent from all manifest names and integer/string values. A real cross-check needs the full model export - (382,781 models at `e293917` per `docs/design.md`) and the rig table. -- `common.rpf` is the readable metadata layer. It carved to 781 streams, 710 of them XML-ish. Strict keyword - occurrences: `clip` 734, `anim` 1,131, `motion` 237, `gesture` 2, `bone` 428 (214 `` open/close - pairs), `ped_` 1,308, `blend` 40; `facial`, `ycd` and `skeleton` 0. The tags include ``, - ``, `` and ``, and a path to `platform:/anim/animscenes/gesture/gesture.rpf`. - These are configuration references, not clip payloads. -- A 64 MiB sample of `data.rpf` (6,359 streams, 3 XML-ish) yielded no animation catalog. Its strict keyword - hits are dialogue or model/decal names; the five `ycd#` hits are part of a model hash table, not a container - header. - -## Likely format family - -The bytes support **new RAGE resource pages**, not the GTA V `YCD`/`RSC7` family: - -- RPF9 container, `0DRP` page directories with `0x50xxxxxx` virtual pointers and page counts. -- `pack:/...` path tables with 16-byte-aligned names and 16-byte hash/pointer records. -- `SKEL_*` bone tables in plain and front-coded forms. -- `RBF0` rig-set metadata (`rage__crRigSetManager`): 1,126 rig sets, 6,677 source→rig entries and 3,669 distinct - rigs, with source tags and group strings. The rig→skeleton key is not in RBF0 or the skeleton streams. -- `MoVE` (version 19) and the 2/3 clip streams as the animation payloads; neither is zlib inside the page. -- No `YCD`, `YDD`, `YLD`, `YFD`, `RSC7` or `RSC8` at any stream start. - -`MoVE` (version 19) is a flat relative-offset state-machine and motion-tree graph (`tools/anim_move.py`). - -### What the bytes do not prove - -- `0DRP` is a page marker with a version, page count and pointers. Its role is inferred from the page layout, not - decoded, and the marker is not proven to be animation-specific. -- `MoVE` v19's container layout, preamble tables, recursive state containers (`Type 1`, `Type 3`, `Type 22`), - transitions and parameter blocks are decoded (`tools/anim_move.py`), while the unhashed source names of most - network/request/flag hashes and the evaluation semantics of the rarest leaf operator node types remain unmapped. -- The two- and three-entry auxiliary tables bound their tagged payloads. Their contents have yet to be linked - to a clip. The clip dictionaries' keyframes are decoded in [Keyframe decoding](#keyframe-decoding). -- The `RBF0` rig-set/rig/group entries are parsed. The numeric fields, the schema type table and the - rig→skeleton reference are not; the measured skeleton match is 0. -- The three motion matcher streams embed bone tables, but whether those define a full skeleton or only the - motion-matching bones is not established. 19 of 30 names have a matching joaat32 in at least one stream. - -## What a future decoder needs - -1. **Use the parsed RBF0 rig mapping.** It is 1,126 rig sets, 6,677 source→rig entries and 3,669 distinct rigs; - 56 rig sets are empty. The key/tag layout is above. The field after `ff ff 08 10` and the rest of the schema - still need mapping. -2. **Resolve rig → skeleton.** None of the 3,669 rigs or 1,126 rig sets matches a stored skeleton name or one of - the 19 bone hashes present. Three motion matcher streams bind four paths to embedded bone tables (30-name - union; parent indices and bind data in the 2,064-byte example). Parse those records to learn the clip→bone - binding, then find how an RBF0 rig points at the same table. The missing key is likely a separate rig asset - or an unparsed numeric field, not these pages. Do not infer it from the category names. -3. **Group streams into resources.** The TOC is encrypted, so use the `0DRP` page header: count at +0x20, - pointers at +0x08 and +0x28..+0x40, four u16 values at +0x48. The sampled layout places page headers among - zero-prefixed pages; a logical resource can span several streams. Do not assume one stream is one file. The - page map at the `+0x08` pointer gives the system page count, and that is how `tools/anim_clips.py` joins the - clip dictionaries. -4. **Parse the name/hash tables.** Names are NUL-terminated and 16-byte aligned; the name hash is joaat32 of - the stem (path without `pack:/` and without the final extension). The record stride varies (16 or 32 bytes in - sampled tables), so do not assume one layout. The recurring `0x98e1750c` is `joaat32("bonerotation")`, a - track type. -5. **Trace the auxiliary payloads to their consumers.** Use the parent's `+0x40` table to bound each payload - before checking its fields against the root object's schema. The table framing alone establishes no - association with the two named page-0 clips. (`MoVE` v19 is now decoded separately by `tools/anim_move.py`.) -6. **Keep the compression boundary explicit.** Outer RPF9 zlib is understood. Do not add a zlib pass inside a - page without evidence; the sampled pages had no valid nested stream. -7. **Re-run the model cross-check with the full export.** The current 1,350-model data.rpf manifest has bone - bindings but no bone names or hashes. The full 382,781-model export plus the `RBF0` rig table is needed to - match skeletons to models. - -## Reproduction - -```powershell -# Full stream index and coverage (writes index.json only) -python -I tools/rpf9_carve.py \anim.rpf \anim-index --index-only - -# Signature index (CSV or JSON; --limit/--start for a bounded scan) -python -I tools/anim_index.py \anim.rpf \anim-index.csv -python -I tools/anim_index.py \anim-carve \anim-index.json - -# Keyframe decoding: counts and one row per clip dictionary; --decode prints one dictionary's values -python -I tools/anim_clips.py \anim.rpf \anim-clips.json --jobs 8 - -# Rig dictionaries and MoVE v19 state-machine containers -python -I tools/anim_rigs.py \anim.rpf \anim-rigs.json --rigs \rigs.json -python -I tools/anim_move.py \anim.rpf \anim-move.json -``` - -`tools/anim_index.py` reports `MoVE`, `0DRP`, `pack:/`, `SKEL_`, `RBF0`, `PSIN`, type-hash and 2/3 clip headers, -plus `raw:` for anything it does not recognise. It writes no payloads. `--start` must be 0 or more and -`--limit` at least 1 (decimal or `0x` hex); an out-of-range value stops with a one-line error and exit code 2 -before an index is written. - -## No-sharing rule - -Game files, carved streams, name lists, payload dumps and reports that quote them stay on the machine that owns -the package. Do not commit them, attach them to an issue or PR, or paste them into a chat. Short header excerpts -(a few bytes) and aggregate counts are allowed, as in `CONTRIBUTING.md`. The work folder is git-ignored; this -document contains no archive data. diff --git a/docs/architecture.md b/docs/architecture.md new file mode 100644 index 000000000..8268eba06 --- /dev/null +++ b/docs/architecture.md @@ -0,0 +1,99 @@ +# Architecture + +``` + user's files (outside repo) Leonida Legacy + ─────────────────────────── ───────────────────────────────────────── + game assets ──────────────────────────► leonida-pipeline + leonida-game + (leonida-formats, leonida-shader) + │ + ▼ + cache_dir: converted data + │ + game executable ─► leonida-loader ────► title code (native x86-64) + prepare, map, bind │ imports + ▼ + leonida-hle ── host Windows (shared APIs) + │ D3D12.X + ▼ + leonida-gpu ─► host D3D12 + │ shaders at pipeline creation + ▼ + leonida-shader ◄─► cache_dir +``` + +Shaders are translated when the title creates a pipeline, from the bytes it +passes, wherever it loaded them from (executable, archive, memory). +Converting them ahead of time from files is only a warm-up. + +## Crates + +| Crate | Role | +|-------|------| +| `leonida-core` | config, asset-policy guard, logging | +| `leonida-pe` | read-only PE32+ and import-library analysis | +| `leonida-loader` | prepare, map, bind and start the title image | +| `leonida-hle` | console API implementations, host pass-through policy | +| `leonida-gpu` | D3D12.X objects, command lists and GPU memory → host D3D12 | +| `leonida-shader` | Xbox shader containers → host shaders | +| `leonida-formats` | the GPU's texture layouts (sizes, tiling, detiling), audio codecs; planned: BCPack | +| `leonida-pipeline` | converter trait, content-addressed cache | +| `leonida-game` | the title-specific formats, build identities, hooks | +| `apps/leonida` | command-line front end | +| `xtask` | asset-policy check, git hooks | +| `tests/fixtures/hle-probe` | a stand-in "title" (our own code) for loader tests | + +Everything except `leonida-game` is platform-level and can be tested with +any Xbox Series title. + +## Import resolution + +For every `dll!function` the title imports, in order: + +1. our implementation in `leonida-hle::modules` (always wins); +2. the host's own function, if `HostPolicy` allows that DLL; +3. an export of a DLL the title ships beside its executable, mapped like + the executable (only DLLs neither of the above serves); +4. a generated stub that names the import when called (`--unimplemented + trap` breaks into the debugger and aborts; `zero` logs once and returns 0). + +`LoadLibrary*` of a console-only DLL we implement (e.g. `xgameruntime.dll`) +returns a pseudo handle; `GetProcAddress` on it finds our functions. +`LoadLibrary*` of a title DLL returns its mapped image, mapping it first if +nothing imports it. By name, as by import, a title gets only host DLLs +`HostPolicy` passes through, and `GetProcAddress` on one returns our +override where import binding would. +`QueryApiImpl` hands out our runtime objects by provider and interface id +(`leonida-hle::modules::xgameruntime` lists the areas); online areas answer +as an offline console. Game saves are files under `LEONIDA_DATA_DIR`. + +Title storage is a drive on the console, and titles build paths on that. +`leonida-hle::modules::files` binds every path-taking title import +(kernel32 and the C/C++ runtime) and rewrites paths on a virtual drive to +the host folder behind it; persistent local storage is one such drive over +a folder under `LEONIDA_DATA_DIR`. Other paths reach the host unchanged. + +An exe's code reaches its static TLS as slot 0; mapped as a DLL it gets +another slot, so the loader redirects those loads (`leonida-loader::tls`). +`leonida run --execute` installs a crash reporter that names faults as +`module+rva` and unwinds the faulting thread's stack +(`leonida-loader::crash`). + +`leonida census` shows this classification without running anything (it +does not map title DLLs; `leonida run` without `--execute` does). + +## Shaders + +`leonida_shader::ir::build` turns a native program into SSA, one +instruction per machine instruction. `leonida_shader::structure` then +removes EXEC: lane masks become per-lane booleans, wave-wide mask tests +become per-lane branches, and vector instructions keep a guard only where +a lane can reach them with its EXEC bit clear. `leonida_shader::resource` +traces each descriptor and scalar memory address to the root parameter it +comes from (table, heap, root descriptor or constant). A descriptor a +waterfall loop reads from the first lane (`v_readfirstlane_b32`) is traced +to the per-lane load or choice that gives each lane its own (a mask's +`v_cndmask_b32`, or an if/else whose arms each set it: traced on the paths +the lanes take, from structurisation), and accessed with a non-uniform heap +index in one pass. `leonida translate` +runs every shader it finds (containers, SGD5 files) through these and +lists what they cannot handle yet. diff --git a/docs/asset-policy.md b/docs/asset-policy.md new file mode 100644 index 000000000..fe71a5a15 --- /dev/null +++ b/docs/asset-policy.md @@ -0,0 +1,60 @@ +# Asset policy (rule #1) + +**Nothing from the game is ever stored in this repository.** Everything is +built on the user's machine from files the user supplies. The same applies +to other titles used for testing, and to any other proprietary material. + +## Not allowed + +In any form (files, string literals, fixtures, snapshots, docs): + +* assets: models, textures, shaders, audio, video, text, archives; +* the executable or any part of it: data sections, strings, tables, + resources, code beyond the signatures below; +* anything derived from those: converted assets, decompiled or + disassembled code, shader dumps, extracted tables, screenshots. + +## Allowed + +* our own code that understands formats; +* build identities: BLAKE3 of an executable, CodeView GUID/age; +* per-build offsets of functions we hook, under names we choose; +* byte-pattern signatures that locate functions or data in the executable; +* small interoperability constants (magic numbers, enum values) we write; +* synthetic test data generated by our own code. + +## The one exception + +`crates/leonida-formats/src/bcpack-tables.bin` (about 78 KB): the constant +tables of the BCPack format (entropy models, index rank tables, control +codes, per-format dictionaries). A BCPack stream cannot be decoded without +exactly these tables and they cannot be derived, so they ship with Leonida Legacy +by the project owner's decision (2026-11-23), entered as an exception in +`xtask/src/policy.rs`. They are part of the format, not our work, and the +repository's licence does not cover them. Nothing else of this kind is +accepted. + +## Where data lives + +Outside the repository, configured in `leonida.toml`: `game_dir` (the +user's dump), `test_titles`, and `cache_dir` for everything derived +(default `%LOCALAPPDATA%\leonida\cache`). + +## Enforcement + +1. `.gitignore` keeps common data types out of `git status`. +2. `cargo xtask policy` (run by the pre-commit hook; install with + `cargo xtask install-hooks`) is an allowlist: files must have an allowed + type, be under 512 KiB, contain no binary data or known binary + signatures, and hold no long hex/base64 runs. Exceptions need an entry + with a reason in `xtask/src/policy.rs`. +3. At runtime, everything that writes derived data calls + `leonida_core::ensure_outside_repo`. +4. Tests that need real files take their paths from environment variables + and skip when unset. They assert on properties, never on snapshots. + +## If something slips through + +A follow-up commit is not enough. Rewrite history +(`git filter-repo --path --invert-paths`), force-push, and have +everyone re-clone. diff --git a/docs/audio.md b/docs/audio.md deleted file mode 100644 index cb6b3fad8..000000000 --- a/docs/audio.md +++ /dev/null @@ -1,425 +0,0 @@ -# Audio - -`audio.rpf` is one of the few archives that is not mostly zlib. It holds **AWC** banks, and each bank uses the -little-endian **`ADAT`** container. The build exports the banks whole, then repackages or decodes their streams: - -- Opus (codec `0x0B`) becomes standard **Ogg Opus**, losslessly: the stored packets are rewrapped, not re-encoded. -- PCM (codec `0` and codec `2`) becomes **WAV**. -- XMA2 (codec `5`) becomes a RIFF XMA2 file, which **ffmpeg** decodes to WAV. - -This page describes the container, what each tool writes, and the bank types that are easy to misread when listening. -The corpus counts and verification results are in [design.md](design.md#asset-status-no-exe-needed). - -## The AWC (`ADAT`) container - -All integers are little-endian. - -``` -offset size field -0x00 4 "ADAT" -0x04 u32 flags -0x08 u32 stream count (n) -0x0C u32 header size -``` - -Optional tables follow the header, selected by `flags`. `tools/awc_opus.py` skips the ones seen in the package: - -| Flag | Extra bytes before the stream table | -|---|---| -| `0x00400000` | 4 | -| `0x00010000` | `n * 2` | -| `0x00200000` | `(n + 1) * 4` | - -Then comes the stream table, one `u32` per stream: - -``` -bits 31:29 tag count (0-7) -bits 28:0 stream id -``` - -Each stream's tags follow, 8 bytes each: - -``` -bits 63:56 tag type -bits 55:28 size -bits 27:0 offset (from the start of the bank) -``` - -The exporters use three tag types: - -| Tag | Meaning | -|---|---| -| `0x55` | stream data | -| `0x76` | format | -| `0x48` | streamed-music descriptor | - -`tools/rsc8_audio.py` additionally decodes the speech companions `0x36` (peaks), `0xa3` (seek -table), `0xb2` (loudness), `0xbd` (cue records) and the two structural tags below; every other tag type -is skipped. The `0xbd` record layout is in [rsc8_audio.md](rsc8_audio.md#the-0xbd-cue-records); the music banks -have the tag too (945 tags in 938 of the 3,008 streamed-music banks, counted by `tools/awc_markers.py`), and -what their records mark is in [audio_config.md](audio_config.md#marker-events-awc-tag-0xbd). - -| Tag | Meaning | -|---|---| -| `0x5a` | 20-byte entries, a sample position and a pitch each (`12345678` marker; see [rsc8_audio.md](rsc8_audio.md#the-undocumented-0x5a0xd9-companion-tags)) | -| `0xd9` | grouped ascending index runs into the sibling `0x5a` entries | - -Both appear only in `audio.rpf`, on 1,185 streams (32,000 Hz; 804 of them carry both). - -### Format tag (`0x76`) - -The fields the exporters read: - -``` -+0 u32 sample count (Opus: 48 kHz frames, interleaved across channels) -+8 u16 sample rate -+12 u32 Opus per-channel frame count (codec 0x0B; +0 for mono, +0/2 for stereo) -+28 u8 codec -+29 u8 channel count -``` - -The exporters ignore the remaining bytes. - -### Codecs - -| Codec | Format | Export | -|---|---|---| -| `0` | PCM, 16-bit | `.wav`, 16-bit PCM | -| `2` | PCM, 32-bit float (4 bytes per sample; values can exceed ±1, e.g. impulse responses) | `.wav`, IEEE float | -| `0x0B` (11) | Opus, 48 kHz | `.ogg`, Ogg Opus, lossless repackage | -| `5` | XMA2 | `.xma.wav`, RIFF XMA2; ffmpeg decodes it to PCM WAV | - -Opus data is stored in 2048-byte blocks. Each block is a sequence of `[u16 length][packet]`; a zero length pads -the rest of the block. The first 312 decoded samples are the encoder's lookahead. Measured on 30 real streams from -four banks: decoded with pre-skip 0, the 5% and 10% attack points are at 312 samples (median 312; the 10% point -ranges 278..868, none near 1920), so 312 is the exporter's default. The AWC does not store the value, so -`--pre-skip` overrides it for a stream encoded with a different lookahead. - -The exporter writes that value as `OpusHead` pre-skip and emits the EOS page at the first packet that reaches -`pre-skip + declared samples`; later packets are encoder padding and are dropped. Clamping only the last page -would let its granule go backwards when the trim point falls before that page starts, and decoders would keep the -excess: a 27-packet real-libopus fixture decoded 24,960 frames for 24,000 declared, while the reaching-packet -form decodes exactly 24,000. An oversized `--pre-skip` is clamped to the stream length so the final granule never -falls below it. - -The format tag's sample count is already in 48 kHz frames even when its rate field is 32 kHz, and `+0x0C` is the -per-channel frame count (equal to `+0` for mono and half of it for stereo in all 7,451 measured streams, 0.5% of -the 1.6M-stream corpus). The exporter uses `+0x0C` only when it agrees with `+0` (`frames * channels == samples`) -and otherwise falls back to `+0 / channels`, so a malformed block cannot silently truncate audio. It never scales -either count by the rate field, because scaling a 32 kHz stream by 48000/32000 leaves padding untrimmed. - -Codec `5` is not handled by `tools/awc_opus.py`. `rpf9dump xma` writes it as RIFF XMA2, and ffmpeg does the decode. - -### Streamed music (`0x48`) - -A `0x48` tag describes a streamed mix. Its descriptor is: - -``` -+0 u32 block count -+4 u32 chunk size -+8 u32 channel count -then 16 bytes per channel: -+0 u32 channel id (low 29 bits) -+4 u32 sample count -+10 u16 sample rate -+12 u8 codec -``` - -At the `0x55` data offset, each chunk starts with a 24-byte record per channel. The record's `+4` word is the -channel's subblock count and `+8` is a repeated-prefix sample count to skip. The channel data are its run of -2048-byte subblocks after the 2048-aligned header. The skipped samples repeat the previous chunk's tail. The -exporter verifies that the skip ends on a packet boundary and that the repeated packets match the previous -packets for that channel group, then writes each verified overlap once. Each descriptor channel becomes one Ogg -Opus file. Invalid repeat counts or payloads reject that music descriptor so independent streams can still export. -The chunk size gives the distance between blocks. The final block may use fewer bytes. The channel table and -all declared subblocks must fit within their own block and the `0x55` tag's data range. - -The descriptor's `channels` field is the number of channel groups, not necessarily the packet channel count. -An Opus packet's TOC stereo bit (`packet[0] & 0x04`) gives the real count, and the descriptor's `samples` field -counts interleaved samples across those packet channels. The exporter therefore writes a stereo Ogg with -`OpusHead channels=2` and `samples / 2` as the end granule when the packets are stereo; mono groups keep their -count unchanged. Reading `samples` as a frame count produces a file that reports twice its real duration. - -## What the exporters write - -`rpf9dump` puts output under `//`. For `audio.rpf`, that is `/audio/`. - -| Command | Output | -|---|---| -| `rpf9dump audio ` | `/audio/awc/.awc` (the original banks) and `/audio/audio_manifest.json` | -| `rpf9dump xma ` | `/audio/xma//.xma.wav` for every codec-5 stream | -| `python -I tools/awc_opus.py [--jobs N] [--pre-skip N]` | `//.ogg`, or `.wav` for codec 0/2; `--jobs` processes that many banks at once | -| `python -I tools/opus_tags.py --names [--dialogue ]` | the same `.ogg` files, with names, dialogue labels and subtitles in their `OpusTags` header (see *Tags: names and subtitles*) | -| `python -I tools/audio_wav.py --out [--jobs N]` | 16-bit PCM WAV mirroring the Ogg tree; `--jobs` ffmpeg processes at once | - -When exporting a directory, `awc_opus.py` keeps the path to each bank below the input root. For example, -`a/music.awc` writes under `/a/music/`. Passing that file on its own writes under `/music/`. -To regenerate a flat export from an earlier version, run `awc_opus.py` with the original bank directory and a fresh output directory. - -To import music cues into Audacity, run -`python -I tools/awc_cue_labels.py /cue_regions.json ` on a sheet -exported by `awc_opus.py --cue-sheet`. Open the channel Ogg in Audacity at time zero, then use -**File > Import > Labels** to load the matching `.txt` by filename stem. Each region shows its -hexadecimal cue hash followed by its one-based row number in the bank sheet. Overlapping and -repeated regions keep individual labels. Start and end times use nine decimal places in seconds -so rounding back to the nearest 48 kHz frame recovers both endpoints. -[Audacity label file format](https://manual.audacityteam.org/man/importing_and_exporting_labels.html) - -`audio_manifest.json` is the bank index: each bank's `Path`, `Offset`, `Size`, and its `Streams` with `Index`, -`Id` (hex), `Codec`, `Channels`, `SampleRate`, `DurationSeconds` and `IsStreamed`. For streamed music, -`Channels` is the Opus packet channel count and `DurationSeconds` is per channel: the tag `0x48` descriptor's -interleaved sample count is divided by that channel count. - -`audio_wav.py` runs ffmpeg with `-c:a pcm_s16le` at the stream's own rate and channel count. For a single stream -it trims to the final Ogg Opus granule minus pre-skip. Chained streams have a separate granule timeline for each -link, so ffmpeg handles their end trimming. Existing WAVs are normally skipped on resume. If the destination -filesystem treats two output names as the same file, the converter keeps the input extensions and adds a counter -where needed. It leaves a previously shared WAV untouched. Before reusing a name ending in `.ogg.wav` or `.opus.wav` -(including counters such as `.ogg~2.wav`), it decodes the source again and compares the PCM, rate and channel -layout. These checks read the full streams serially during planning. If the audio differs (including decoding -differences between ffmpeg versions) or the existing WAV cannot be verified, it stays in place and the converter -tries the next counter. Plain existing WAVs are -trusted by name, so resuming into the same output folder assumes the same set of inputs. -With no `--out`, a directory writes to `/wav` and a single file writes next to itself. - -## How `make_game.py --wav` uses them - -The `assets` stage runs these in order: - -``` -rpf9dump audio -> /assets/audio/awc + audio_manifest.json -awc_opus.py -> /assets/audio/ogg -audio_wav.py -> /assets/audio/wav (only with --wav) -rpf9dump xma -> /assets/audio/xma//.xma.wav -ffmpeg -> /assets/audio/xma//.wav -``` - -`--wav` is opt-in because 16-bit PCM is several times larger than Ogg Opus. It only adds PCM copies of the Ogg Opus -output; the XMA2 decode is separate and runs independently when ffmpeg is on PATH. If ffmpeg is missing, the -`.xma.wav` files are kept and the build says so. The stage skips work that is already present, including existing -WAVs. - -## Songs, station mixes and venue stems - -A bank is an asset container, not a radio station. The same `ADAT` framing holds several different things: - -| What you see | What it is | -|---|---| -| One stream, typically around five minutes | An individual song or music asset, not a station feed | -| A long continuous stream | A station-style mix, much longer than a single song | -| A bank with 3 or 8 channels | **Venue stems**: the music plus the audience/ambience channels for one venue | - -The multi-channel banks are the easy mistake. A 3-channel bank is not three radio stations, and an 8-channel bank is -not an eight-station lineup: it is one venue's mix split into stems, so the game can balance the music against the -crowd. `awc_opus.py` writes one mono Ogg per channel and does not mix them. Listening to a single stem can sound like -a dry music bed or like pure audience noise; the in-game result is the mix. - -Use the bank name, stream count, duration and channel count together before deciding what a bank is. Station -programming is assembled by the game from many assets, so a lone AWC is rarely a complete station. - -The music/radio **config table** is a separate structure: 1,589 records with exact durations, AWC stream ids, -contiguous station grouping and no per-track start offsets. See [audio_config.md](audio_config.md) for the record -layout, the station-content references and the marker events (tag `0xBD`) that mark track boundaries in five -long mixes. - -## Mission music: Home Sweet Home - -The credited "Burn This Shit Down" is not a radio-station track. It is the song for the -**Home Sweet Home** mission (Chapter 1, mission 21/25): Lucia at Jason's house in Key Lento -during the house fire and the escape. The mission and its localized objective/fail strings are -present in `data.rpf`. - -The song audio is in 1.0.2.1 too, as stems, not as one stream (found by @jefftern4 in the coordination thread, -PROC-178). It is the plain (not streamed) `audio.rpf` bank at offset `0x300695000`, 9,481,280 bytes, bank 5,573 of -7,162 in the exporter's `audio_manifest.json` order: - -| Field | Value | -|---|---| -| Streams | 73, all stereo, all codec `0x0B` (Opus, 48 kHz) | -| Common length | 47 streams declare 771,213 samples (16.067 s); the manifest's rounded `DurationSeconds` gives 771,213 for 32 of them and 771,214 for 15 | -| Other lengths | 6 × 1,156,820, 2 × 2,313,640 and 2 × 385,607 samples (1.5, 3 and 0.5 times the loop), and one 24,100-sample stream | -| Range | 0.439 s to 114.477 s, 1,297.2 s in total | - -The 47 equal-length streams are loop stems meant to play together (vocals, melodic, sub-bass and ad-lib layers per -slot, by the finder's listening), so no single stream is the song and a whole-file fingerprint of each stream -misses it. That is why the searches below came back empty. The bank's shape (field values above) was re-measured -from `audio_manifest.json` on a second 1.0.2.1 copy; the stem roles are the finder's and were not re-checked here. - -Measured coverage of the earlier search, which looked for the song as one stream. The `audio.rpf` all-banks row -is the one the stems fall under: - -| Container | Searched | Result | -|---|---|---| -| `story000.rpf` streamed-music banks | 753 banks / 2,642 channels | none | -| `story000.rpf` plain banks | 201 banks / 1,950 streams | none | -| `story000.rpf` Bink | 264 streams / 162 with audio / 165 tracks / 5,090 s | none | -| `movies.rpf` Bink | 229 tracks / 12,401 s | none | -| `audio.rpf` streamed cues under 30 s | 1,149 channels / 5.78 h | none | -| `audio.rpf` all banks | 7,162 banks, all streams | none as a single stream; the stems are bank `0x300695000` (above) | -| loop/chunked banks | 1,099 banks / 118,180 streams | none | -| `packs.rpf` inflated | 144,364 files / 9.74 GB | 0 AWC, 0 Bink2 | -| `data.rpf` inflated | 28,509 files / 1.41 GB | mission text, 0 song strings | -| `script.rpf`, `common.rpf`, `story000_script.rpf` | 1,058 / 955 / 2,633 files | none | -| `levels.rpf` raw | 94 `ADAT` magics, 2,820 `KB2` patterns | 0 valid AWC/Bink | - -Fingerprint search: about 19,807 files / 19.9 M Chromaprint frames / 653 fingerprint-hours, with a -0.50-2.00 tempo sweep over the story-music and long-AWC targets. No candidate passes the vote -threshold. The positive controls keep their earlier results: Sensimilla 2,284 votes / 0.911 bits -/ 100 %; Don't Break My Heart 88 votes / 7.046 bits / 94.5 %. - -A `data.rpf` hash table contains 12 occurrences of `joaat("burn")`, but it is not the song: the -config blob has none, no AWC stream ID matches its low 29 bits, and the table has no audio -reference. - -Residual uncertainty: `levels.rpf` (76 GB) was not fully inflated; the retail track may be a third -master or patch content not covered by the public references; sub-30 s stings were not exhaustively -fingerprinted. No game audio is stored in the repository; the searches ran on a local copy and -`radio-dump-v3` was not modified. -Residual uncertainty: how the game sequences the stems (which layers play in which slot, and the -order of the longer streams) is not decoded; the mission's audio config is the likely place (a -hypothesis, not measured). No game audio is stored in the repository; the searches ran on a local -copy and `radio-dump-v3` was not modified. - -This search first listed the `RSC8` resources of the story and minigame archives as the only -mission-side container not decoded. They are decoded in [rsc8_audio.md](rsc8_audio.md), and none of -them holds the song: all 641,428 raw `RSC8` headers in the package (225,281 in `story000.rpf`, 1,957 -in `shared_minigame000.rpf`, 9 in `story000_restofworld.rpf` and 414,181 in `audio.rpf`) are AWC tag -`0x5c` facial/lip-sync clips. Each sits in an `ADAT` bank next to the 48 kHz mono Opus dialogue line -it animates, none lies outside a bank, and none contains an `ADAT`, Ogg Opus or RIFF WAVE header. - -## Stream names - -The stream table stores only `joaat(lowercase name) & 0x1FFFFFFF`, so the exporters name files by id. -`tools/awc_names.py` recovers names by hashing dictionary words against those ids. With about 1.8 million distinct -ids in a 2^29 space, roughly 0.3% of arbitrary words collide by chance, so a hit is accepted only under one of two -rules: - -| Rule | Accepted when | -|---|---| -| `dialogue` | the word is shaped like a dialogue wave, `au_<4 letters>_`, and is in the dictionary exactly | -| `family` | one base (a name without its trailing `_`) hits ids in the same bank with several numbered suffixes (`''`, `_00`-`_40`, `_1`-`_9`): at least 3 members, or 2 with adjacent numbers. Every token of the base occurs in at least 5 dictionary words, and at least one member is itself a dictionary word | - -Each run repeats the attack with `zq` prepended to every word. Those names can't be right, so what the control -accepts estimates the false names. Per source, the dialogue rule is kept only when its control is under 2% of its -real count, and the family rule takes the smallest family size whose control is under 2%. - -The dictionary comes from two kinds of input: - -- `--words`: plain word lists, or a `hashdict.py` JSON (its values). -- `--conversations`: conversation data, which pairs a dialogue key with its line labels as - `AU_\0` stores exactly those - geometries as the float3 and uint32 buffers the next step takes, with the transform recorded in `export.json`; -4. `tools/bvh_rehydrate.py` on the same stream with those buffers and `--transform` gives the runtime layout, - byte-identical to what `XboxBvhBuilder.dll` writes on these samples (§4a). - -With the excluded shader hashes the run answers with one consistent candidate per sample; without them every -candidate is checked and the checks decide. Measured on the window above: 1,228 models in the export, 1 to 374 -candidates from the signature per sample, and a rehydrated structure of `64 * (totalSizeIn64BNodes + 1)` bytes from -the header. Its root parent-table entry is `0xFFFFFFFF` in all eight samples identified first (the entry at -`offsetToParents` read signed, plus `4 * ((root - offsetToElements) / 64)`), which is what the GPU builder writes -for a root and what `tools/xdxr_bvh.py validate` requires since #2625. - -`tools/image_bvh_census.py` (standard library only) counts how the game's shaders call `image_bvh*_intersect_ray`: -sites per form, the descriptor fields at each site, and how the four result words are read, as ratio (divided by word -1), high_half (`sext(w1[31:16])` into `v_mul_i32_i24`), raw integer, raw float, raw other or select. It walks forward -from each call with an EXEC lane rule (its docstring has the rule and the categories), and it prints counts, -mnemonics and field values only. On the 1.0.2.1 disassembly: 716 sites in 64 CS (638 `image_bvh_intersect_ray`, 78 -`image_bvh64_intersect_ray`). The descriptor has box_grow 0, box_sort_en 1, size all ones, triangle_return_mode 1, -llc_noalloc 0, big_page 1 and type 8 at all 716 sites. On every path from the call, 397 sites take `v_rcp_f32` of -word 1 and multiply word 0 by it (`v_mul_f32` 244, `v_mul_legacy_f32` 153), 335 of them words 2 and 3 as well, and -they read the high half of word 1. That high half's product is compared with `v_cmp_lt_i32` against -1 at 319 sites -and `v_cmp_gt_i32` against 0 at 78. All 716 read the words as integers: 397 sites through `v_lshlrev_b32`, -`v_and_or_b32`, `v_lshl_or_b32` and `v_or3_b32`, and 319 through `v_cmp_eq_u32` only. No site reads a word as an -undivided float, a memory operand or a select on every path. These are static candidates, not traces. 633 sites also -have reads on some paths only, where the register can also hold another value, and the census leaves them -unclassified. Of the 548 sites with such a raw-float read, 506 have every one after a later call in program order and -42 have one before the next call. The census does not follow the next pass of a loop around the call, or a value that -goes through memory. - -```powershell -python -I tools/image_bvh_census.py /shaders/dxbc/disasm --out /image_bvh_census.json -python -I tests/test_image_bvh_census.py -``` - -## 7a. Building runtime BVHs: `tools/xdxr_bvh.py` - -The Vulkan layer has to write acceleration structures in this runtime layout, because the game's traversal shaders -read the nodes themselves (`docs/d3d12_vulkan.md` §4.8). `tools/xdxr_bvh.py` (standard library only) is the CPU -reference for that builder. It encodes a BLAS from triangles or a TLAS from instances, runs one traversal step -with the semantics of the hardware instruction, walks a whole BVH to the closest hit, and checks a buffer's -structure. Its fixtures are synthetic. - -What it writes, and where each part comes from (line numbers in the public `.hlsli` quoted in §3.1): - -| Part | Layout | Source | -|---|---|---| -| Header | §3.1 table; `flags = 0x80000006` (BLAS) or `0x00000006` (TLAS); `crc32` and `compressionParams` 0 | `XboxBvh4Header` L2531, flag masks L2551, `XDXR_VERSION_2403 = 6` | -| BOX32 / BOX16 | four children, unused slots `0xffffffff` with an empty box (min > max); BOX16 rounds min down and max up to half | `Node32` L2302, `Node16` L2285, `XdxrDecompressBox16` | -| Leaf | vertex slots 0–3, then `GeometryIndexAndFlags` (index << 8 \| flags), `BasePrimitiveIndex` (TRI0), `PrimitiveIndex2` (TRI1), one remap byte per triangle node type | `Leaf` L2342, `XDXR_Runtime_Callback_GetPrimitiveIndex` | -| TRI0 / TRI1 | TRI0 reads slots (0, 1, 2), TRI1 reads (1, 3, 2); TRI2/TRI3 read slot 4, which overlaps the metadata, and are not emitted | `Read3Verts`, `XdxrGetVertexIndicesForNodeType` | -| Barycentric remap | byte `8 * type` of leaf `+60`: bits [1:0] pick which edge function is the first barycentric (0 U, 1 V, 2 W), [3:2] the second; U weighs the first vertex read | `TestXboxBvh4Leaf` | -| INSTANCE | 128 bytes: object-to-world 3×4, ID \| mask << 24, contribution \| flags << 24, BLAS root pointer with bit 31 = identity rotation, BLAS address >> 8, world-to-object 3×4, instance index, parent | `Instance` L2436, `XDXR_INSTANCE_INTERNAL_FLAGS_*` | -| Parent table | one dword per 64-byte unit from `offsetToElements` on; the entry for unit `u` is at dword `u - offsetToElements/64 + offsetToParents/4` | `XboxBvh4Node_GetParentTableOffset` | - -**ASSUMPTION:** the region order (header, parent table, elements, nodes), the median-split build and the greedy -pairing of triangles that share an edge into TRI0/TRI1 are this tool's choices. The console builder's own choices -are not public. A shader reaches every region through the header, so these choices don't change what it reads. - -The traversal step (`intersect_node`) follows `TestXboxBvh4Node` and `TestXboxBvh4Leaf`. A box child is kept when -its entry distance is at most the ray extent, and the children are sorted with the network (0,2) (1,3) (0,1) (2,3) -(1,2). A triangle returns `(t_num, t_denom, i_num, j_num)`, or `(inf, 1, 0, 0)` on a miss. A box miss stays a miss -for an unbounded ray: the public code's `<=` against an infinite extent would keep it. - -**Translator.** `image_bvh_intersect_ray` in `tools/rdna2spirv.py` used to follow RADV's software path on triangle -nodes: slots (0, 1, 2) for every type and (V, W) as the barycentrics, because RADV builds only one triangle per -node. It now reads the slots of the node type and applies the remap byte. AMD GPURT -(`CalcTriangleCompressionVertexIndices`, `SwizzleBarycentrics`) and the XDXR path agree on both. TRI1 nodes -therefore traverse to the right triangle (docs/design.md, Ray tracing row; `tests/semantic/test_image_bvh_tri.py`). -Its four triangle words are the ones native RDNA2 returns (docs/design.md, Ray tracing row; measured on an RX 6800 -with the kernels `tools/bvh_tri_probe.py` builds, `tests/semantic/test_image_bvh_tri_hw.py`): k·(T, det, b_i, b_j) -with k = |d[kz]|³ on a hit, and on a miss copysign(inf, k·det) in word 0 with the other three kept, where the step -above returns (inf, 1, 0, 0). A ray exactly on an edge or a vertex follows RDNA2's tie rule (docs/design.md, Ray -tracing row): the zero edge from P to Q passes when ty = 0 ? sign(det)·tx > 0 : sign(d[kz])·sign(det)·ty > 0, with -(tx, ty) = Q′ − P′ sheared and the d[kz] < 0 swap undone. It was read off measured x/y-dominant rows and then predicted -the z-dominant rows before they ran; the step above and RADV break those ties differently. Measured on gfx1030 only, -with dyadic inputs. - -**GPU builder.** `runtime/src/xdxr_build.comp` with `xdxr_build.h` writes the same layout on the GPU, straight into -the destination buffer: - -1. one thread per triangle (TRI0 leaves, remap `0x09`) or per instance (128-byte records, the world-to-object - inverse, the BLAS root and identity-rotation flag); -2. a 30-bit Morton key of each box centre, then a stable sort: up to 1,024 keys in one workgroup's shared memory - (one dispatch), more with a radix sort of 8 passes of 4-bit digits over 256-element tiles (24 dispatches - whatever the count, no padding to a power of two); -3. a binary radix tree over the sorted keys (Karras 2012; equal keys are told apart by their sorted position), one - thread per inner node; -4. the inner nodes: those at an even depth of the binary tree, each taking the children of its children (two to - four), numbered in sorted order by a scan, so the root is node 0; with the parent table. They are BOX32, or - BOX16 (below), and TRI1 pairing (below) happens here; -5. the boxes, bottom-up in one dispatch: each element writes its box into its parent's slot and merges it into the - parent's accumulator; the last child to arrive carries on with the parent's box. The invocations meet only - through atomics ordered by `memoryBarrierBuffer`, so no plain load reads another workgroup's store of the same - dispatch. An instance's `ParentNode` is written here; -6. the header. - -The tree used to group four consecutive sorted elements per node, level by level. Those groups ignore where the -Morton prefix changes, so sibling boxes overlapped and a ray took about twice as many steps (found by DaniSBR1 on -D3D-410). Measured with `xdxr_bvh.py check-build`, which counts the traversal steps (one per node or triangle -tested, the work of one `image_bvh_intersect_ray`) over 1,000 random rays per case: - -| Case | Steps per ray, four consecutive | Steps per ray, radix tree | -|---|---|---| -| `blas_three_sort_tiles` (5,000 random triangles) | 42.0 | 23.0 | -| `blas_box16_sort_tiles` (the same, BOX16) | 43.9 | 23.7 | -| `blas_paired_sort_tiles` (7,200-triangle grid, TRI1 pairing) | 37.6 | 19.5 | -| `blas_random` (1,000 random triangles) | 24.1 | 16.0 | -| `blas_grid_u16_stride16` (288-triangle height grid) | 11.0 | 8.0 | -| `blas_refit_in_place` (3,000 triangles, refitted after moving) | 74.8 | 55.5 | -| `tlas` (4 instances) | 26.3 | 18.1 | - -Every ray finds the same hit as brute force in both. A CPU model of the choice (a scratch script, not kept) gave -35.1 steps per ray for a greedy surface-area collapse of the same radix tree, 35.8 for the largest-subtree one and -35.7 for the even-depth one this builder uses, against 76.8 for four consecutive elements (5,000 random triangles; -11.2, 11.4, 11.5 and 24.4 on a height field). The even-depth collapse is the only one of the three that needs no -pass from the top down. - -The cost is in the build and in memory. Wall clock of `vk_xdxr_build_test ` (random triangles, best of 3): - -| GPU | Triangles | Build before → after (ms) | Refit before → after (ms) | -|---|---|---|---| -| RTX 5090 | 1,000 | 0.17 → 0.17 | 0.10 → 0.09 | -| RTX 5090 | 1,000,000 | 5.50 → 5.99 | 4.12 → 4.28 | -| Radeon iGPU (gfx1036) | 1,000 | 0.17 → 0.23 | 0.09 → 0.10 | -| Radeon iGPU (gfx1036) | 1,000,000 | 133 → 180 | 41.8 → 62.2 | - -On the iGPU about half of the refit's increase is the accumulator atomics (measured before BOX16 and pairing). The tree has more nodes: about one per -two elements, against one per three. A build writes 137,856 bytes for 1,000 triangles where it wrote 113,536, and -the layout leaves room for the most a tree can have. - -The radix sort's scan writes the prefix sums of the digit counts to their own scratch array, not over the counts. -No invocation of the builder stores to a word and then uses a value it loaded from that word earlier. SPIRV-Cross -`6c09849f`, in MoltenVK 1.4.2, breaks that pattern for a pointer made by `OpBitcast` from a `uvec2` -(`GL_EXT_buffer_reference_uvec2`): it moves the load to where the value is used, after the store, and the load -returns the new value. MoltenVK `main` at `5189f8de` pins SPIRV-Cross `aa217aeb`, which has the same bug. -SPIRV-Cross [`38abe362`](https://github.com/KhronosGroup/SPIRV-Cross/commit/38abe362c57311a77808b7ec4d1d0d9ceb8d9370) -fixes it. With the old in-place scan, the radix path (more than 1,024 elements) lost and duplicated elements on -MoltenVK: `xdxr_build_check` found about 130 of 200 rays wrong in `blas_three_sort_tiles` and 210 of 300 in -`blas_refit_in_place`, which refits a radix-sorted tree. Measured on an Apple M3 Max, the separate arrays pass -10 runs out of 10 on Homebrew MoltenVK 1.4.2, on MoltenVK `5189f8de` built with SPIRV-Cross `57e4efcc`, on -KosmicKrisp and on llvmpipe. A pointer from `OpConvertUToPtr`, which the translator uses, kept its load before the -store in the same test. - -**BOX16 nodes.** A bottom-level build with `MINIMIZE_MEMORY` writes BOX16 inner nodes: 64 bytes, not 128, so a BLAS -is about a fifth smaller (39,040 bytes against 48,768 for the 428-triangle BLAS of `d3d12_xdxr_rt_test`). The tree -is the same; only the node records and their offsets change, and -`GetRaytracingAccelerationStructurePrebuildInfo` gives the smaller size when it gets the same flag. Each child box -is rounded outward to halves (min toward -inf, max toward +inf) from the exact box, which the builder keeps in its -accumulators, so the rounding does not add up from level to level. The rounding is integer code, because `packHalf2x16` -rounds in an implementation-defined way (AMD's driver rounds toward zero). Beyond the half range a bound becomes -+-inf on its outward side and +-65504 on its inward side, so an empty slot (min +inf, max -inf) is still empty. A -bound smaller than the smallest normal half (2^-14) in magnitude becomes 0 or +-2^-14, whichever is on its outward -side, never a half denormal: a decoder that flushes those to zero would make the box smaller. `tools/xdxr_bvh.py` -`half_round` does the same, and `check-build` compares every BOX16 word bit for bit with `encode_box16` of the exact -box of the triangles under that child. Top-level builds keep BOX32 whatever the flags, because they are in world -space, where a half's step reaches 2 m at 2,048 m and 4 m at 4,096 m. An update must pass the same flags as its -build (D3D12 requires it), so a refit keeps the node type. **ASSUMPTION:** that `MINIMIZE_MEMORY` is the console's -switch for BOX16. The offline BLASes in the `*_bvh4.rpf` packs have BOX16 roots (§3.1), but `XboxBvhBuilder.dll`'s -choice between the two at run time is not traced. The one traced datum points at a finer rule: `docs/xdxr.md` §3 -finds a different bottom-level path that needs `MINIMIZE_MEMORY` and a stream setting (type 0, `+0x08`) above 10.0, -so the flag alone may not be the switch. A bottom-level structure authored in world coordinates gets looser boxes -from BOX16 the same way a top-level one would: slower to trace, never wrong. A BOX16 build ends with one spare, -zeroed 64-byte unit after the last node it wrote, and the header's size counts it: the translator's -`image_bvh_intersect_ray` loads a box node's 112 bytes of BOX32 bounds before it checks the type, so the last -64-byte node would otherwise be read past the structure, or past a compacted copy of it. - -**TRI1 pairing.** A bottom-level build without `ALLOW_UPDATE` pairs triangles into TRI0/TRI1 leaves, as the console -builder does in its offline BLASes (§4a, check 4 of "How a match is verified"). The pass that writes the nodes -pairs each triangle child of a node with a later triangle child of the same node (among its at most four children) -when four things hold. The two must share an edge in opposite directions, with the same two vertices bit for bit. They must come from -the same geometry, since a leaf holds one `GeometryIndexAndFlags`. And both must be active. The first triangle is -rotated so the shared edge is slots 1 -> 2, the sibling's third vertex goes in slot 3, its primitive index in -`PrimitiveIndex2`, and each node type's remap byte returns D3D12's barycentrics for its own vertex order. The node -still has one child per triangle, each with its own box: the TRI1 child points at the first triangle's leaf, and the -sibling's own leaf is left unused. The tree, the layout and the sizes are therefore the same as without pairing. -Nothing is saved yet: reclaiming the unused leaves would need a compaction that moves records and rewrites pointers, -and compaction here copies bytes. What pairing gives is the console's leaf format, with a pair's two triangles in -one 64-byte record. Because pairs never cross nodes, one thread owns each leaf it rewrites, and both pointers of a -pair have the same parent, so the parent table has one writer per entry. The pass records each triangle's pointer -(TRI0, or TRI1 for the sibling) in scratch, so the bottom-up box pass finds the sibling's slot through the first -triangle's leaf. On a sorted grid of 7,200 triangles, 2,208 of the 3,600 possible pairs form (2,625 with the tree of four -consecutive elements: a radix-tree node often has an inner node among its children, and only triangle children -pair). A refit rewrites every leaf as one triangle, so a structure that may be updated is -not paired. **ASSUMPTION:** that pairing only siblings is close enough. The console builder's pairing rule is not -traced; `tools/xdxr_bvh.py` `build_blas(pair=True)` pairs greedily over the whole mesh instead, and both traverse -the same way. `check-build` compares barycentrics as well as hits, and checks that a paired case has TRI1 nodes and -that cases that must not pair (other geometry, same direction) have none. - -The node count depends on the keys. A kept node has two children only when both of its binary children are -elements, so with N elements there are at most (3N - 2) / 4 nodes. `XdxrLayout` computes the result and scratch -sizes for that many when the build is recorded, and the same numbers answer -`GetRaytracingAccelerationStructurePrebuildInfo`. The header's `totalSizeIn64BNodes` counts only the nodes the build -wrote. -A triangle with a NaN vertex gets an empty box (D3D12 treats it as inactive). So do an instance with mask 0, one with -no BLAS and one with a singular transform. An instance record holds its BLAS address in 256-byte units in 32 bits, -so BLAS addresses must be below 2^40, as console GPU addresses are. Where device addresses are wider (llvmpipe's are -host pointers), the builder takes a bias that is added to the addresses read from instance descs. - -The Vulkan layer uses it for `BuildRaytracingAccelerationStructure` unless `LEONIDA_RT_AS=khr` -(`docs/d3d12_vulkan.md` §4.8); `d3d12_xdxr_rt_test ` builds a BLAS and a TLAS through the D3D12 API and writes -them the same way. - -`vk_xdxr_build_test ` builds nine synthetic cases on the GPU and writes each structure with a description of its -scene. `xdxr_bvh.py check-build ` validates them and traces rays against brute force. `ctest` runs both as -`xdxr_build` and `xdxr_build_check`. - -**Updates** (D3D12 `PERFORM_UPDATE`) refit: the source structure is copied to the destination unless it is the -destination (as many bytes as its header gives, so a compacted source works too), the elements are rewritten at -their slots, and each node's boxes are recomputed bottom-up from the children it already points to, through the -parent table, by the same pass as a build. The tree is kept, so a refit is valid for any motion and skips the Morton pass and -the sort. It took 0.07 ms for 1,000 triangles and 9.8 ms for 1,000,000 on an RTX 2050, against 0.19 ms and 22 ms for -a build, with the tree of four consecutive elements (the radix tree's times are above). The tree traverses more -slowly as the geometry moves away from where it was built. - -**Copies and postbuild info.** `CopyRaytracingAccelerationStructure` with `CLONE` or `COMPACT` copies the -structure's bytes. The records are position-independent: node pointers count from the structure's start, and a TLAS -names its BLASes by address, which a clone keeps. The size comes from the source header (`totalSizeIn64BNodes`), so -a copy can follow a build in the same command list, and it is bounded by the destination resource. A build's size -is the nodes it wrote, so `COMPACTED_SIZE` and `CURRENT_SIZE` (from -`EmitRaytracingAccelerationStructurePostbuildInfo` or the postbuild descs of a build) are both -`64 * (totalSizeIn64BNodes + 1)`, and compaction gives back the room the layout left for more nodes. Serialization, deserialization and the tools-visualization -mode are refused at replay as unsupported, not faked. In `LEONIDA_RT_AS=khr` mode the postbuild descs stay ignored, -as before. - -Not done yet: serialization; a compaction that reclaims the leaves that pairing leaves unused. A surface-area -collapse of the radix tree, or treelet restructuring, would trim a few more steps. - -```powershell -python -I tools/xdxr_bvh.py selftest --seed 1 --rays 400 # build BLASes, compare closest hits with brute force -python -I tools/xdxr_bvh.py validate # structural check of a runtime buffer -python -I tests/test_xdxr_bvh.py -``` - -## 7b. The first real pack BLAS on a GPU - -Measured on the 1.0.2.1 package with the tools above; counts and offsets only. - -* `core_bvh4.rpf` indexes to **271,637 BVH4 streams / 1,896,784,254 nodes (121.4 GB inflated)** in 1,034 s. -* The first BLAS (stream at `0x12060`, 39,257 nodes, 2,512,512 bytes rehydrated) matches **one** drawable among the - 258,037 models an export of `levels.rpf` produced: 12 geometries, 21,814 leaves, 0 leaves outside, 335/0 - overrides, area ratio 1.000 (`bvh_match.py`, `bvh_geometry_check.py`, `bvh_rehydrate.py` on the user's copy). -* The rehydrated header's `rootNodePtr` is the **dehydrated** root; the runtime root is the first node of the last - entry of the level table at the end of the structure. The leaves are in the leaf frame (`(R*v - t)*s`): the header - `sceneBounds` are the pre-frame AABB (±2.5), the leaf vertices are scaled (≈19,040), so test rays are built from a - leaf's own vertices. -* Descriptor base: the descriptor's dword0 is the base in **256-byte units**; the game passes `ptr >> 8` there, and - the `| 0x30` its shader ORs is only the temporary address it uses for the `rootNodePtr` load, not the descriptor - base. Measured at base 0 and at base 0x1000 (structure copied to VA 0x1000, dword0 `0x10`): the game's RT shadow - CS (`deferred_tiled` family, 32-bit form) on the RTX 2060 returns the CPU walker's children in the same order at - both. Its second traversal site still needs the executable. -* The base and the address formula were also measured on the **native instruction**, with no emulation in the path: - `tools/hw_oracle` ran `image_bvh_intersect_ray` and `image_bvh64_intersect_ray` on gfx1036 (Ryzen 9 9950X3D iGPU, - driver 32.0.21030.2001) over hand-built box32 nodes, a decoy node at the buffer start and the real one at +0x1000. - dword0 `(P >> 8) + 0x10` with node `0|5`, and dword0 `(P >> 8) + 0x08` with node `0x800>>3|5`, both traverse the - node at `P + 0x1000`: address = base × 256 + (node & ~7) × 8, and the base and the node offset add. The control - (base `P >> 8`, node `0|5`) reads the decoy. Both instruction widths agree. Not exercised: descriptor bits 39:32 - (the buffer fits in 32 bits), nodes other than box32, and a `0x1030`-style dword0, which the hardware would read as - base 0x103000. - -## 8. No-sharing rule - -Nothing from the packs may be committed: no `.rpf`, carved stream, decompressed buffer, XML text, tile list, -name hash, key or TOC dump. This document and the tool carry only aggregate counts, offsets, field layouts and a -handful of header bytes. The tests build their inputs by hand. Any future decoder must keep its fixtures synthetic -and write real output only to the user's private work folder. diff --git a/docs/character_models.md b/docs/character_models.md deleted file mode 100644 index ff1fe1dee..000000000 --- a/docs/character_models.md +++ /dev/null @@ -1,515 +0,0 @@ -# Character models and ped parts - -Measured from the pinned `e293917` export of `packs.rpf` (`tools/rpf9dump models`): **26,585 -manifest rows**, **11,335 unique names**, **23,720 `.#dr` drawable rows** and **2,865 `.#ft` -fragment rows**. One row is one LOD or variant, so these are row counts, not character counts. - -No game data is reproduced here. - -## A character is a drawable plus a fragment - -- A `.#dr` drawable carries the geometry, materials and texture references. -- A `.#ft` fragment carries the shared 597-name humanoid skeleton and the character's bounds. The - measured skeleton is in [character_skeleton.md](character_skeleton.md). - -The current exporter writes every fragment as a **flat 25-vertex / 32-triangle bounds grid** (a 5x5 -grid at z=0, `Min`/`Max` z = 0) with `Embedded: null` (2,865 of 2,865). Fragment child drawables -are not walked, so a part that exists only as a fragment child is not in the OBJ/GLB output even -though its parent fragment is. - -## Lucia records - -22 unique names contain `lucia` (12 contain `cs_lucia`). They are parts, not one assembled model. -The decoded export used by the previews contains 13 parts: - -| Part | Source drawable | Vertices | Triangles | Diffuse key (`0xC8E8C282` only) | -|---|---|---:|---:|---| -| head (hi) | `player_story000_00_head_fr1_lat_000_m.#dr` | 8,983 | 13,320 | `0x8EDB5664DA38C47E` (head-skin preset) | -| head L0 | same | 4,638 | 4,940 | same preset | -| head L2 | same | 599 | 514 | same preset | -| eyes | `…_head_fr1_lat_000_m_eyes.#dr` | 434 | 816 | `0x429453B7A2EB9980` (sRGB + alpha) | -| eyecap | `…_head_fr1_lat_000_m_eyecap.#dr` | 214 | 304 | `0x5CE55BAA340248BD` (sRGB + alpha) | -| hands | `hand_fr1_000_nude_cull.#dr` | 10,440 | 13,534 | no exact hit for `0x4D89F2311DBBB7A8` in the 57 scanned TTPF pools (see [Hands and feet](#hands-and-feet)) | -| feet | `feet_fr1_000_full.#dr` | 2,309 | 4,082 | no exact hit for `0xA54D9F8B51CA6034` in the 57 scanned TTPF pools (see [Hands and feet](#hands-and-feet)) | -| body (legacy) | `cs_lucia_legacypedcs_fr1_000_fullbody_ws00_full.#dr` | 874 | 908 | `0x996FDBA2DB30CC12` | -| legacy head | `cs_lucia_legacyheadcs_fr1_001_regular_ws00_full.#dr` | 592 | 1,028 | `0x707771F769AA3542` | -| jacket (biker) | `cs_lucia_jacketbiker_fr1_000_regular_c_hl_long_full.#dr` | 9,818 | 10,837 | none — `speculartex` only (`0xF5073AA039BB3CED`) | -| crop tee | `player_story000_00_tshirtcrop_fr1_001_slim_cc_un_long_full.#dr` | 4,932 | 6,756 | none — `speculartex` only (`0x46E8FA9436E9D43C`) | -| bikini top | `brabikini_fr1_012_regular_ws00_full.#dr` | 6,547 | 5,697 | `0xDF3615ADFB1F4787` (sRGB + alpha) | -| undies | `undiesgstring_fr1_002_slim_hw_full.#dr` | 961 | 913 | `0xCFD339832A9C724A` (sRGB + alpha) | - -### Higher-detail variants - -The rows above are the preview build, not the densest rows in the archive. LOD0 counts come from -the manifests; "distinct" is unique vertex positions decoded from a GLB, which removes duplicate -cull seams: - -| Component | Denser variant | LOD0 V / T | Distinct | -|---|---|---:|---:| -| jacket | `player_story000_00_jacketbiker_fr1_000_regular_o_hl_long_full` | 11,093 / 12,023 | 9,597 | -| crop tee | `player_story000_00_tshirtcrop_fr1_001_slim_cc_un_long_cull_00` | 12,254 / 15,437 | 4,558 | -| jeans | `player_story000_00_pantsjeans_fr1_002_regular_hw_mid_full` | 4,917 / 5,550 | 2,826 | -| boots | `cs_roxy_bootsankle_fr1_000_mid_hh_full` | 7,764 / 7,960 | - | - -The library maximum for jeans is `pantsjeans_fr1_019_slim_mw_long_full` at 23,880 V / 25,230 T; -that is a single 0.41 x 0.26 x 0.95 m mesh, but the raw count includes seams, so validate it -visually. `_cull_00` variants can have more raw vertices and less surface than their `_full` -sibling; compare distinct positions, not the manifest total. - -Two caveats that matter for any render: - -- **`body` is the shared player/cutscene body.** The only `lucia`-named full-body record in - `packs.rpf` is `cs_lucia_legacypedcs_fr1_000_fullbody_ws00_full`. Its LOD0 is **874 vertices / - 908 triangles** (468 distinct positions); the 1,748 / 1,816 figure is LOD0 + LOD1 counted - twice, and the 640-vertex row is LOD2. Its `FragName` is byte-identical to `cs_monalisa` and - `cs_mandy`, so it is the shared player/cutscene body, not a unique high-detail mesh. Do not - present it as a high-detail hero body. -- **The head drawable has no material texture references**, but its face comes from a **head-skin - preset** keyed by the head name's `joaat32` (see Textures). - -`player_story000_00` (Lucia's slot prefix) has 104 unique names: **63 drawables** plus **41 -`char_bipedbounds` fragments**. The largest drawables: - -| Drawable | Vertices | Triangles | -|---|---:|---:| -| `…_hoodiezip_fr1_001_regular_o_hd_long_cull_00.#dr` | 20,311 | 14,256 | -| `…_sweatshirtcrewneck_fr1_000_loose_cc_un_long_cull_00.#dr` | 19,217 | 13,600 | -| `…_hoodiezip_fr1_001_regular_h_hd_long_cull_00.#dr` | 19,141 | 14,106 | -| `…_shirtdress_fr1_000_slim_c_oc_un_long_cull_00.#dr` | 14,341 | 16,146 | -| `…_tshirtcrop_fr1_001_slim_cc_un_long_cull_00.#dr` | 12,254 | 15,437 | -| `…_jacketbiker_fr1_000_regular_o_hl_long_full.#dr` | 11,093 | 12,023 | - -## Slot tokens - -These are counts of unique names containing the token. They are a naming heuristic, not the game's -component table. - -| Token | Unique names | Note | -|---|---:|---| -| `player_story` | 196 | Lucia (`000_00`) and Jason (`000_01`) | -| `head` | 3,741 | heads and head attachments across all characters | -| `hair` | 278 | includes accessories and non-human fur | -| `belt` | 44 | accessories | -| `pants` | 459 | `pantsjeans`, `pantscargo`, `pantsleggings`, `pantstrack`, … | -| `jeans` | 157 | `pantsjeans` / `shortsjeans` | -| `jacket` | 327 | `jacketbiker`, `jacketdenim`, `jacketblazer`, `jackettrack`, … | -| `uppr` | 17 | 14 are `slod_uppr_*`; 3 are `char_bipedbounds_female_armor…_uppr_l/r.#ft` | -| `lowr` | 21 | 17 are `slod_lowr_*`; 4 are `char_bipedbounds_female_armor…_lowr_l/r.#ft` | -| `jbib` | 0 | the GTA V slot code is not a name token here | -| `hands` | 8 | the singular `hand_` appears in 35 names | -| `feet` | 26 | bare feet plus creature variants | -| `bikini` | 45 | `brabikini_*` and related | -| `undies` | 102 | `undiesgstring`, `undiesbriefs`, `undiesboxers`, … | - -## Textures - -The character export requested 215 texture keys and matched **184**. The only sRGB albedo slot is -`0xC8E8C282` (`diffusetex`); `0xC6F46E79` is `speculartex` (specular/gloss pack), `0x1E77BF4C` is -`bumptex` (the tangent-space normal), `0x739E3D0D` is `speculartex2` (packed ORM), and -`0x8ADB8480` is `materialid` (an ID/palette map). The jacket's and the crop tee's material rows -reference one (`0x6CD70ED1054EF726`, `0xF0722B975F329141`, both `BC4_UNORM` textures in the -`ttdb_peds` pools); the bikini top's and the undies' rows have no such slot. Whether a shader -samples it is not measured. The garment -shaders (`d5ed50f4`, `ea8d09d0`, `39ddb9ca`) do not declare a `0xC8E8C282` slot at all: none of -their 7,948 material rows in the export has one. The jacket and the crop tee are on them, so they -have no albedo. A part without one keeps a flat colour; it must not -be painted with `speculartex` or an ORM map. The garments' `_COLOR0` vertex data is baked shading -(alpha 255 on every vertex), not a tint, and the shader -declares no tint or palette slot. No authored base colour exists to recover for those two. - -The bikini top and the undies are not on the garment shaders, and they do have an albedo. All -three records of each drawable bind `0xC8E8C282` to the key in the table: the bikini top on -shaders `84af5c61` and `81153bcc` (`76c45dd8` and `428b44d6` in its smallest record), the undies -on `a9dfb1e7` (`428b44d6` in its smallest record). Every material row on those five shaders in -the export binds the slot (1,372 of 1,372). Both keys are 512x256 `BC3_UNORM_SRGB` textures with -7 mips in the `ttdb_peds` pools: an sRGB format with an alpha channel, as the eyes' and eyecap's -`BC7_UNORM_SRGB` keys are. Their `speculartex` keys are -other textures (`0x93CB433D30220BA6` and `0x5D237CCCD91F8E4D`, 256x128 `BC7_UNORM`), where the -jacket's and the crop tee's table keys are `BC7_UNORM` `speculartex` sheets themselves. - -The hands and feet bind albedo keys with no exact hit in the scanned TTPF catalogs (see [Hands and feet](#hands-and-feet)). -The head drawable has no material texture reference, but its face is selected by -a **head-skin preset** keyed by the head name's `joaat32`: - -| Head | Face albedo | Face normal | -|---|---|---| -| `player_story000_00_head_fr1_lat_000_m` | `0x8EDB5664DA38C47E` | `0x953715153D75447C` | -| `cs_monalisa_head_fr1_afr_000_m_full` | `0x53A2896F4E5A6BA6` | `0xE82C7F6E02C8B701` | - -The preset library covers 897 heads; `cs_lucia_head_fr1_lat_000_y_full` is not in it. - -### Hands and feet - -Measured against the catalogs of all 57 TTPF pools (357,115 textures). The hands and the feet bind -the four maps on the same two shaders (`210FBC6A`, `8D69EDAB`); for the two examples below, -**only the normal-map keys have exact catalog hits**. "None" means no matching full 64-bit -`AssetKey` in these scanned catalogs, not proof that no runtime source exists: - -| Part | `diffusetex` | `speculartex` | `bumptex` (normal) | `speculartex2` (ORM) | -|---|---|---|---|---| -| hands (`hand_fr1_000_*`) | `0x4D89F2311DBBB7A8` — none | `0xA805B9A446CCE950` — none | `0x9D337DABCA636906` — `ttdb_peds_2_3`, 512×1024 BC5 | `0x09D2C98C5B40D16C` — none | -| feet (`feet_fr1_000_*`) | `0xA54D9F8B51CA6034` — none | `0x752EA8A7A086558F` — none | `0x5091E86DE6196BC3` — `ttdb_peds_3_3`, 512×1024 BC7 | `0xD5C8D2A180326DE7` — none | - -Each material has ten slots; the other six bind `0x5D7A3A87CC19967D` on both shaders, with no -exact pool hit. The [independent indexed-record check](https://github.com/ItsNotRexed/Leonida/pull/3256#pullrequestreview-6014627459) -found this same reference in all 176 material -rows, including the 12 positive-control rows whose four named maps all resolve. An engine-supplied -default is a hypothesis: the repeated unresolved reference alone does not establish its runtime use. - -**Shared static material references.** The hands and feet have bindings in common with body skin -pieces in `pack/core_restofworld/core_restofworld.rpf`; these references do not establish runtime -sheet selection: - -- `bodynipplesgen_fr1_000_regular_ws00_full`, the female upper body, binds **the same four keys** - as the hands, on the same two shaders. -- `bodygenitalsgen_f{r,b,o}1_008_regular_ws00_full`, the female lower body (and the `fr1` - `_alt_00`–`_02` variants), binds the feet's - `speculartex`, `bumptex` and `speculartex2`, and its own `diffusetex` `0x5B6829CFEC0F41A1`, also in - no pool. -- The male lower body, `bodygenitalsgen_mr1_000_*`, has all four maps in the pools - (`diffusetex` `0xBCE4D91DA23689C7`). - -The unresolved female-body albedo, specular and ORM references above also have no exact hit in -these pools. The recorded search found none of these keys in another resource of `data.rpf`, -`common.rpf`, `script.rpf`, `packs.rpf`, -`anim.rpf`, `core_restofworld.rpf` or `core_restofworld001.rpf` (`story000.rpf` and -`story000_restofworld.rpf` recover no entries with this reader). These are static lookup results; -the source of skin colour and the runtime's sheet selection remain open. - -Across 162 indexed records (176 material rows, 56 distinct `hand_`/`feet_` drawable names), all -176 rows carry the four named references. Of the 56 names in `packs.rpf`, 52 have no exact -diffuse-key hit in the scanned pools; the four exceptions with all four maps resolved are -`hand_fsk1_000_nude_cull`, `feet_fsk1_000_nude_cull` and the first-person hands -`hand_mb1_000_nude_cull_fp` and `hand_mo1_000_nude_cull_fp`. The male hands and feet -(`hand_mr1_000_nude_cull`, `feet_mr1_000_nude_cull`) also have exact hits only for their normal -maps, and male and female feet bind the same `diffusetex` key. For previews, use the resolved normal -map and a flat skin tone; this is a fallback, not a reconstruction of the runtime's skin colouring. -Do not borrow another part's albedo. - -## Materials - -A binding audit of 120 exported scenes (232 material rows) found 35 rows with a real `C8E8C282` -albedo and 174 rows with `C6F46E79` but no `C8E8C282`, all on garment shaders. The four rows that -produced teal previews were the specular sheet used as the base colour, not a normal map. Those -parts have **no albedo**, so a preview must render them as clay rather than invent a colour. - -- **The belt is not a separate part.** It is 172 connected components / 2,229 vertices inside the - jeans mesh, with no node, material or texture key; it cannot be separated without editing the - geometry. -- **UVs above 1 are wraps, not atlas pages.** The blazer reaches U=2.0014 (1,628 vertices); after - subtracting 1, 90.9% of those vertices are within 1e-4 of a page-0 vertex. The jeans reach - U=-0.9936, a -1 mirror. -- **The body atlas is a shared collage.** `996FDBA2DB30CC12` is 256x256 and contains several ped - variants (faces, a tropical shirt, blue jeans, dark cloth). Only 43.7% of the sheet is covered - by the body's islands, so bilinear sampling at an island edge can read a neighbouring variant. - The blue in an earlier preview came from the authored `baseColorFactor` `(0.200, 0.270, 0.400)`, - not from this atlas. - -## Bodies - -A geometry-first census — every `packs.rpf` drawable and fragment, all 50,802 `levels.rpf` -fragments, 178,073 of 184,778 `levels.rpf` drawables (96.4%; the 6,705 above 3 MB were not -decoded), all 4,195 `story000.rpf` drawables, and the `anim.rpf` rig dictionaries — found no -Lucia or Mandy body. `story000.rpf` is mission map cells, not ped actors: its full read finds -4,195 drawables, 177,811 meshes, **0 skeletons, 0 fragments and 0 body-like names**, 28.5 M -vertices of unrigged 64 m cells. `anim.rpf`'s `LOD0_Body_Shapes_Female` is a rig program with no -mesh. - -A raw RSC8 scan of **862,555** resources across all 13 indexed RPF9 archives (every `rageobj` -entry, unnamed pages and the >3 MiB band included; 25.6 GB compressed / 56.3 GB inflated) found -2,631 ped-skeleton resources: 342 animal bounds, 2,212 `char_bipedbounds_*` fragments, -4 mannequins and 73 anim clips. **0** combined a ped skeleton with the skin/flesh shader, and -0 of the 908 resources that use the skin/flesh shader contained a single `SKEL_*` bone name. -The unnamed-resource route therefore does not add a body. - -The only **nude** continuous human-skeleton meshes are a **generic female mannequin** in -`levels.rpf`: `gmt_mannequin_proxy_f_01a` (15,488 vertices / 27,725 triangles, 95 bones, -1.72 m, A-pose) and `gmt_mannequin_f_01b` (the same body posed mid-stride). It has no Lucia or -Mandy name or texture link, and its rig is a clothing form, not the 596-bone ped skeleton. 78 of -95 bone names are shared, and all 71 weighted bones match; its pivots are a rigid 180° yaw plus a -31.7 mm drop, not a mirror, so no L/R weight swap is needed. A 39.59° upper-arm correction lands -the hand on the ped pivot. It has no skin albedo — only a flat tint swatch atlas — so it is an -untextured base proxy for a reconstruction, not Lucia's body. - -A separate bare female mesh exists only as a **scene monster** in `packs.rpf`: -`sc_fast_demon_bodyuppergen_fr1_000_m_full` (10,048 v / 13,124 t) and -`sc_fast_demon_bodylowergen_fr1_000_m_full` (3,717 v / 4,082 t), shader `0x210FBC6A`, with no -garment parts. It is a monster asset, not a player or ped body. The `bodyupper`/`bodylower` -families confirm the negative: all 18 rows are human male (`cs_farmm`, `cs_mister_mangrove`, -`u_m_m_farm_monster_man`) or monsters (`sc_*`), none female. The `hc_stripper_delights`, -`hc_stripper_joh` and `hc_stripper_nine1nine` characters ship heads and eyes only, with no body. - -The player and cutscene body is a separate shared **clothed** fragment, -`cs_lucia_legacypedcs_fr1_000_fullbody_ws00_full` (874 v), used by `cs_lucia`, `cs_monalisa` -and `cs_mandy` (their `FragName` is identical). It is the body the game uses; it is low-poly and -clothed, so it is not a high-detail nude body. A flat-skin render of the 874-v body with its -normal map disconnected still shows the modelled top, shorts and ankle boots, so the clothing -silhouette is geometry, not a painted-on atlas. - -## Modular ped construction pipeline and body assembly - -RAGE 9 constructs human peds from modular streamed slots rather than monolithic rigged meshes. -Spawning a character resolves a five-stage data graph across `packs.rpf`, `data.rpf`, `common.rpf`, -`anim.rpf` and `data/ttdb/peds/*.ttpf`: - -1. **Identity and archetype table.** `packs.rpf` archetype PSO (`00011d1ff000.pso`, root - `0xdd77771e`, 2,714 records, 384 B/record) holds each archetype's `joaat32` hash (`+0x08`) and - voice/short name (`+0x174`). -2. **Outfit slot resolution.** `packs.rpf` outfit-slot PSO (`00011cfbf000.pso`, root `0x890aca98`, - 2,713 archetypes -> 33,621 outfit hashes) maps each archetype to valid outfit slot hashes with a - 1:1 link to compiled `0DRP` appearance catalogues. -3. **Compiled appearance catalogues (`0DRP`) and variation pools.** 2,709 resource-packed `0DRP` - catalogues (`0x8dcb4cf5`, v122), the wardrobe catalogue (`00011ccb2000.pso`, 19,827 presets) and - 80 `0x1edee47e` variation PSOs resolve 88 B presets (`0xf795e8ba`) and 184 B wearable states - (`0x37e52277`) to `murmur64` drawable, albedo, normal and `cull_drawable` (`0x46e1a048`) keys. -4. **Modular geometry, skeleton, deformation and strand grooms.** Three streamed geometry LOD tiers - per slot, master `crSkeletonData` in `ambient_*` fragments (454–596 named bones; see - [character_skeleton.md](character_skeleton.md#master-skeletons-and-standing-space)), - `char_bipedbounds_*` collision rigs, 6,756 quantized blend-shape delta buffers, 449 ML Deformer - weight models and 5,751 `smh` GPU strand grooms (20,046 LOD resources; hair drawables in - `packs.rpf` are 3-vertex / 1-triangle stubs). -5. **GPU compute skinning, morphing and deferred/RT shading.** `ped_morphable_model_cs` -> - `ped_standard_head_cs` (blendshapes, sticky lips, per-meshlet stretch/wrinkles) -> - `ped_skinning_cs` -> `ped_skin_processing` / `ped_standard_skin_tattoo_bake` -> `bvh_skinning` - -> `meshlet_culling` (`CS_BatchCullPreSkinnedMeshlets`) -> deferred G-buffer, GPU subsurface - scattering and ray-tracing resolve. - -### Standing-space coordinate convention - -All human modular drawables share a single standing skeleton space anchored at -**`SKEL_ROOT = (0, 0, +1.0 m)`** in RAGE Z-up (`(0, +1.0 m, 0)` in glTF Y-up). Vertex buffers -store root-relative bind positions (feet sit near `Z = -1.0 m`), while drawable bounding boxes -(`root + 0x30..0x4f`) store standing-space bounds. Translating skinned parts by `(0, 0, +1.0 m)` -aligns `head`, `eyes`, `eyecap`, `teeth`, `hand_*_nude_cull`, `feet_*_nude_cull`, -`bodynipplesgen_*`, `bodygenitalsgen_*` and garments to sub-millimetre precision without per-slot -offset tables. Disabled slots use `<12 cm` at-root stub meshes at `(0, 0, -1.0 m)`. - -### Modular body slots, `_nude_cull` islands and watertight stitching - -Despite their legacy `hand_` and `feet_` prefixes, the canonical base nude body drawables cover the -entire torso and pelvis: - -- **Upper body (`hand__000_nude_cull`):** torso, chest, shoulders, arms and hands (first-person - arms ship separately as `hand__000_nude_cull_fp`). -- **Lower body (`feet__000_nude_cull`):** pelvis, hips, buttocks, legs and feet. -- **Female nipples (`bodynipplesgen_fr1_000_regular_ws00_full`):** separate `fr1` chest patch - sharing the `hand_fr1` `512×1024` UV layout (male `mr1` torsos bake nipples directly into - `hand_mr1_000_nude_cull`). -- **Adult genitals (`bodygenitalsgen_fr1_008_*` and `bodygenitalsgen_mr1_000_*`):** modular `fr1` - and `mr1` pelvic patches with four geometry variants (`base`, `_alt_00`, `_alt_01`, `_alt_02`; - female depth `6.83–7.58 cm`, male resting `8.9–9.0 cm` and extended `13.4–13.5 cm`). - -RAGE 9 uses a two-level culling architecture to prevent skin poke-through without runtime mesh -rebuilds: - -1. **Catalogue swaps (`0x46e1a048` = `"cull_drawable"`):** 385 unique drawables carry `_cull` - suffixes — 351 `_cull_00` garments (348/351 paired directly with a `_full` sibling) plus 28 - `_nude_cull` / `_nude_cull_fp` base skin meshes across the 12 rigs. Wearable states in `0DRP` - catalogues map `0x46e1a048` to `0x3d780b74` records (`25,292` resolving to `*_cull*` drawables). -2. **Physical `_nude_cull` cull islands and coplanar overlap bands:** Base nude drawables are - physically split into hundreds of disconnected island patches along garment cuts: - -| Drawable | Physical cull islands | Tier 0 V / T | Measured coplanar overlap | -|---|---:|---:|---| -| `hand_fr1_000_nude_cull` | **449** | 10,440 / 13,534 | **258** waist tris (`Z = 0.8981..1.0367 m`, 13.86 cm) + **26** nipple tris | -| `hand_mr1_000_nude_cull` | **290** | 9,914 / 13,534 | **258** waist tris (`Z = 0.9346..1.0739 m`, 13.93 cm) | -| `feet_fr1_000_nude_cull` | **257** | 4,103 / 4,462 | **64** female genital tris behind `bodygenitalsgen_fr1_008_*` | -| `feet_mr1_000_nude_cull` | **264** | 4,107 / 4,462 | shares the 258-tri waist band (`<1.5 mm` apart) | - -At runtime, an outfit occlusion mask suppresses the overlapping waist strip on one mesh plus any -islands hidden under garments or modular chest/pelvic patches. Rendering both `hand_*_nude_cull` -and `feet_*_nude_cull` offline without culling causes Z-fighting on those 258 waist triangles (and -on the 26 nipple and 64 female genital backing triangles). Culling the coplanar overlapping -triangles stitches the body with **0 boundary-edge holes** (watertight on both `fr1` and `mr1`). -`tools/ped_assemble.py` implements standing-space alignment, canonical vertex-key plus -coplanar-centroid/normal overlap culling and multi-part glTF 2.0 export, verified on synthetic -overlapping body meshes in `tests/test_ped_assemble.py`: - -```powershell -python -I tools/ped_assemble.py assemble -o -python -I tools/ped_assemble.py cull-overlap --target --ref -o -python -I tools/ped_assemble.py inspect-seams -``` - -### 15-channel meshlet vertex layout - -Character geometry uses GPU meshlets (16-byte headers, up to 128 local vertices per meshlet, -32-bit packed triangles `7b a | 7b b | 7b c | 11b meshlet_id` plus `uint16` vertex remap). The -23-slot vertex buffer header (`0x00..0x5b`) carries 15 active streams on modern character heads: - -| Slot | Format | Stride | Purpose | -|---:|---|---:|---| -| `0` | `0x42` (`0x4042`) | 8 B | Quantized 16-bit XYZ position (`base + q * step`) | -| `2` | `0x21` | 4 B | Packed octahedral normal + 15-bit tangent frame | -| `18` / `19` | `0x27` | 4 B | Secondary tangent / rest-pose octahedral normal (`19` heads, `18` body skin) | -| `6`, `7` | `0x26` | 4 + 4 B | Skinning blend weights (up to 8 influences per vertex) | -| `8`, `9` | `0x8c` or `0x25` | 16 + 16 B or 4 + 4 B | Bone indices: extended 32 B/vert (`0x8c`, hero heads) vs 8 B/vert (`0x25`, body skin / ambient) | -| `1`, `12`, `13` | `0x26` | 4 + 4 + 4 B | Three `RGBA8` vertex color / AO / blend-mask / skin-curvature channels | -| `3`, `4`, `14`, `15` | `0x28` / `0x42` | 4–8 B each | Four UV channels (`UV0` albedo, `UV1` tattoo/suntan/damage, `UV2` wrinkle/micro-detail, `UV3` morphable-model) | -| `17` | `0x84` | 16 B | Per-vertex basis / blend-shape / ML-deformer stream | - -The ped importer and exporter preserve authored `TEXCOORD_1` and higher sets alongside -`TEXCOORD_0`, including normalized integer input accessors. Ped JSON stores these extra -sets in `uvs_extra`, an object whose keys are the positive set indices (`"1"`, `"2"`, -and so on); `uvs` remains set 0. Overlap culling and vertex compaction keep each set -aligned with the surviving vertices. This preserves vertex data without expanding -the material importer's supported texture-coordinate bindings. - -### 3-tier LOD budgets and thresholds - -Modular ped drawables in `packs.rpf` stream three separate dictionary tiers per item name plus a -fourth `slod_human` crowd proxy. Body skin, eyes, teeth, genitals, nipples and garments encode -`rmcDrawable` `m_LodDist[4]` (`root + 0x70..0x7f`) as **`15.0 m` (LOD 0 -> 1), `30.0 m` (LOD 1 -> 2), -`60.0 m` (LOD 2 -> 3/SLOD), `9998.0 m`**; heads and `slod_human` store `(9998.0, 9998.0, 9998.0, -9998.0)` because head tier selection is driven dynamically by the ped component LOD manager. - -| Component | Tier 0 (High) | Tier 1 (Med) | Tier 2 (Low) | Notes | -|---|---:|---:|---:|---| -| Human head (canonical) | 8,983 v / 13,320 t | 2,958 v / 3,362 t | 599 v / 514 t | Shared topology across 1,600+ modern heads | -| Eyes (`*_eyes_full`) | 434 v / 816 t | 230 v / 398–408 t | 50–55 v / 80 t | Dual eyeball + cornea | -| Teeth (`teethmodular_*`) | 3,628 v / 5,582 t | 1,359 v / 2,144 t | 373 v / 556 t | Upper/lower arches + gums + tongue | -| Upper body nude (`hand_fr1_000_nude_cull`) | 10,440 v / 13,534 t | 5,821 v / 5,168 t | 2,365 v / 1,392 t | `hand_mr1`: 9,914 v / 13,534 t | -| Lower body nude (`feet_fr1_000_nude_cull`) | 4,103 v / 4,462 t | 2,794 v / 2,112 t | 1,134 v / 606 t | `feet_mr1`: 4,107 v / 4,462 t | -| First-person arms (`hand_*_nude_cull_fp`) | 8,127 v / 12,342 t | 4,337–4,360 v / 6,000 t | 932–934 v / 1,266 t | Dedicated close-up FP arms | -| Genitals — female (`bodygenitalsgen_fr1_008_*`) | 267 v / 356 t | 132–139 v / 153–170 t | 35 v / 38 t | Identical across `base`, `alt_00..02` | -| Genitals — male (`bodygenitalsgen_mr1_000_*`) | 246 v / 352 t | 113–115 v / 176 t | 22 v / 35–36 t | Resting + extended `alt_00..02` | -| Nipples — female (`bodynipplesgen_fr1_000_*`) | 106 v / 182 t | 90 v / 118 t | 3 v / 1 t | Collapses to 1-tri stub at Tier 2 | -| SLOD far crowd proxy (`slod_human`) | 392 v / 338 t | — | — | Whole distant character (-99.1%) | - -Assembled nude adult budget: ~**27,300–28,000 v / 38,000–38,250 t** at Tier 0 -> ~**13,400 t** at -Tier 1 (-65%) -> ~**3,200 t** at Tier 2 (-92%) -> **338 t** at SLOD (-99.1%). Clothed characters -typically span ~**35,000–55,000 t** at Tier 0 excluding GPU hair strands. - -## What is not decoded - -- **Fragment children.** A raw child-array walk (`tools/fragment_children.py`) covers every fragment - of `packs.rpf` and `levels.rpf`. The fragment header's u16 at `+0x30` is the number of drawables; - the records are 0x110 bytes apart, starting at the main drawable that `+0x18` points at, so - records 1 and up are the child drawables. All 2,865 `packs.rpf` fragments have a single drawable - and the flat 25-vertex / 32-triangle bounds grid, with **no child arrays**. The four - `gmt_mannequin*` fragments have no child arrays either; `ambient_femalebody` is a 596-bone - skeleton plus the same grid, with no skin mesh. The path is alive on world fragments - (`bus2_frag_hi`: 14 model structs, 11 children, a 650 KB `model_parts.glb`), so the negative is - a property of the character files; those figures come from a different walk and were not - re-derived by this one. In `levels.rpf` the walk finds **50,802 fragments** (the exporter's - manifest counts 50,798): 50,068 have a single drawable and **734 have a child array**, 733 of - one child and 1 of two, **735 child drawables** in all. Every declared child record passes the - drawable-body test, and a scan of all other 16-byte offsets of those fragments' system pages - finds 0 further drawables. 10,097 of the 50,802 have a null `+0x10`, `+0x20` or `+0x28`, and 6 - have a main drawable that fails the embedded-drawable header test. For comparison `data.rpf` has - 1,758 fragments, all single-drawable. The other header counts are unrelated to children: the - `+0x28` array of 0x50-byte part records (the u16 at `+0x34`) has 153,028 records over - `levels.rpf` (13,871 fragments with more than one) and 27,778 over `packs.rpf` (2,605). The gap - is closed: every fragment in both archives was walked, and the only ones with child drawables - are 734 of the `levels.rpf` ones. -- **A ped-variation table.** `common.rpf` contains `CPedVariationBodyTypeManager` - (`0x226000`) and `CPedComponentSetManager` (`0x228000`), but neither maps a component variation - index to a drawable plus texture. The first is height and body-shape presets - (`SCALE_PLAYER_STORY000_00` is 1.62 m); the second lists gameplay components. Slot selection - from names is a heuristic, not the game's rule. -- **Lucia's hair.** The `packs.rpf` manifest has three `player_story000_00` hair rows - (`hairbob`, `hairpixie`, `hairponytail`), each **3 vertices / 1 triangle**; `hairbuzzcut` - appears only in male `_mr1` rows. All 54 non-SLOD rows of those four styles are 3 v / 1 t. - Across `packs.rpf`, 219 of the 267 measurable hair rows are <=3 v / 1 t. The 48 larger rows - are 29 accessories (`hairaccsband`, `hairaccsclip`, `hairaccessoriescuff`; up to 7,251 v), 10 - SLOD proxies (71-147 v), 3 fused `cs_wyman_head_mr1_cau_000_o_hair_alt0` rows (up to 13,529 v), - 3 `hairbun` and 1 `hairlob` unit-box stubs (24 v / 12 t), and 2 blowfly - `cri_fly_blow_m_00_hair_00` rows (1,436 / 2,040 v); no stand-alone full-resolution female hair - mesh exists. `levels.rpf` and `story000.rpf` have zero character hair rows. A static Lucia - export is bald by design; a render needs a clearly labelled placeholder, not a missing decode. -- **`levels.rpf`.** The full archive was name-enumerated: 1,116,073 streams, 98.32% inflated, - 235,814 named streams, 318,266 unique names. It contains no Lucia, Mandy, `player_story` or - `ambient_female` drawable; the Lucia and Mandy hits are props (photos, frames, luggage, a - curtain). The only human-skeleton meshes in `levels.rpf` are the generic mannequin pair in - **Bodies**. -- **Bind pose and skinning in static exports.** The static preview and `rpf9dump` GLBs do not apply - the 8-influence bone-palette skinning (preview GLBs carry 0 skins, 0 `JOINTS_0` and 0 `WEIGHTS_0`; - `rpf9dump` emits identity inverse-bind matrices). The real inverse bind matrices are at skeleton - header `+0x30` (drawable `+0x18` points at the header) and agree with the default bone transforms; - `tools/anim_glb.py`, `tools/skinned_glb.py` and `tools/ped_assemble.py` export glTF skins with - those matrices (see [character_skeleton.md](character_skeleton.md#animated-gltf-export)). - -## Reproduce - -```powershell -rpf9dump models -python -I tools/fragment_children.py \levels.rpf --jobs 12 --json \levels_fragments.json -``` - -The second command prints the fragment and child-drawable totals quoted under "Fragment children"; it -reads the archive in place (about 22 minutes for `levels.rpf` with 12 workers over a WSL mount of -the dump) and writes nothing else. - -The material rows are in the same manifest, one per shader of a record, each with the texture -references by slot: - -```python -import json - -items = json.load(open(r"/packs/models/manifest.json", encoding="utf-8"))["Items"] -for item in items: - if item["Name"] == "brabikini_fr1_012_regular_ws00_full.#dr": - for material in item["Materials"]: - print(material["Shader"], {t["Param"]: t["Id64"] for t in material["Textures"]}) -``` - -A key's size and format come from the pool that holds it: the `AssetKey`, `Width`, `Height`, -`DxgiFormat` and `Mips` fields of the manifest `rpf9dump ttpf ` writes. - -The [Hands and feet](#hands-and-feet) tables also need `core_restofworld.rpf` and the 57 pool -catalogs (`AssetKey` in each pool's `manifest.json`). - -`rpf9dump ttpf` writes a pool's catalog to `\\manifest.json`, and pool -basenames repeat: the 57 pools in [`game/xbox-1.0.2.1.json`](../game/xbox-1.0.2.1.json) have 51 -distinct basenames (`ttdb_maps` and `ttdb_terrain_image_based` twice, `ttdb_ui` and `ttdb_vfx` three -times). With one output root for all of them, later pools overwrite earlier catalogs. Give each pool -its package-relative parent folder under `\ttpf` as its output root: - -```powershell -$game = (Resolve-Path "").Path.TrimEnd("\") -rpf9dump models "$game\pack\core_restofworld\core_restofworld.rpf" -Get-Item "$game\data\ttdb", "$game\pack\*\data\ttdb" | Get-ChildItem -Recurse -File -Filter *.ttpf | ForEach-Object { - rpf9dump ttpf $_.FullName "\ttpf\$($_.DirectoryName.Substring($game.Length + 1))" -} -``` - -Each catalog records its source pool in `src`. The lookup finds catalogs at any depth under -`\ttpf` and stops unless their sources are exactly the 57 pools of the game root, so a -catalog that was overwritten, exported in another layout or taken from another folder is caught -before an absent key is read as a lookup miss: - -```python -import json -import os -from pathlib import Path - -maps = {"C8E8C282": "diffusetex", "C6F46E79": "speculartex", "1E77BF4C": "bumptex", "739E3D0D": "speculartex2"} -game = Path(r"") -pool_root = Path(r"/ttpf") - - -def source(path): - return os.path.normcase(os.path.abspath(path)) - - -pools = {source(p) for pattern in ("data/ttdb/**/*.ttpf", "pack/*/data/ttdb/**/*.ttpf") for p in game.glob(pattern)} -sources, pooled = set(), set() -for m in pool_root.rglob("manifest.json"): - catalog = json.loads(m.read_text(encoding="utf-8")) - sources.add(source(catalog.get("src", m))) - pooled.update(t["AssetKey"] for t in catalog.get("Textures", [])) -if len(pools) != 57 or sources != pools: - raise ValueError(f"{len(pools)} pools under {game} (expected 57); {len(pools - sources)} have no catalog " - f"under {pool_root}, {len(sources - pools)} catalogs come from other sources") -items = [i for m in (r"/packs/models/manifest.json", r"/core_restofworld/models/manifest.json") - for i in json.load(open(m, encoding="utf-8"))["Items"]] -for name in ("hand_fr1_000_nude_cull.#dr", "feet_fr1_000_full.#dr", "bodynipplesgen_fr1_000_regular_ws00_full.#dr", - "bodygenitalsgen_fr1_008_regular_ws00_full.#dr", "bodygenitalsgen_mr1_000_regular_ws00_full.#dr"): - keys = {maps[t["Param"]]: t["Id64"] for i in items if i["Name"] == name - for mat in i["Materials"] for t in mat["Textures"] if t["Param"] in maps} - print(name, {k: (v, v in pooled) for k, v in keys.items()}) -``` - -The fragment and skinning fields are in the same manifest; the skeleton measurements are in -[character_skeleton.md](character_skeleton.md), and the world model export is in -[models.md](models.md). diff --git a/docs/character_skeleton.md b/docs/character_skeleton.md deleted file mode 100644 index 7261e7584..000000000 --- a/docs/character_skeleton.md +++ /dev/null @@ -1,547 +0,0 @@ -# Character skeleton and skin format - -Measured from the Xbox Series **1.0.2.1** package. This page covers the shared humanoid -skeleton stored in a character **fragment** (`.#ft`) and the model side that binds meshes to -it. It is separate from the world model exporter in [models.md](models.md): the world -drawables do not use this 597-name table. - -No game data is reproduced here. Offsets, counts, field layouts and a few short name/hash -examples are enough to reproduce the measurements against a reader's own package. - -The fragment carries the skeleton and a **25-vertex / 32-triangle bounds grid**, not a skin mesh. A -SixNG fragment-child walk finds no embedded drawables in any of the 2,865 `packs.rpf` character -fragments, while world fragments do have them; see -[character_models.md](character_models.md#what-is-not-decoded). - -## The skeleton name table - -Source resource: `ambient_femalebody_upper_nohead.#ft` in `packs.rpf`, stream offset -`0x45449F70` (stored 17,434 bytes, inflated 42,384 bytes). - -This stream is the **name table**, not the skeleton fragment. `tools/anim_glb.py --skeleton` takes a -fragment offset; on 1.0.2.1 the sibling `ambient_femalebody_head.#ft` at `0x45417010` exports the -596-joint skeleton with a 5.13e-6 bind error, while passing `0x45449F70` fails with -`page directory: not a system pointer`. - -| Range | Contents | -|---|---| -| `0x0008..0x7FF8` | 4,095-slot hash table, 8 bytes per slot: `u32 joaat32(name)`, `u32 boneIndex` | -| `0x8000` | page header; includes the `0x500280D0` pointer | -| `0x8088..0xA57E` | NUL-separated bone names (the first two entries repeat the fragment name) | -| `0xA57E` | `skel` marker | - -The page contains **597 names and 596 hash entries**. Every matched hash equals -`joaat32(name)` over the lowercased ASCII name. The name table repeats the fragment name -(`ambient_femalebody_upper_nohead`), so 597 names share 596 hashes; the duplicate at index 596 -is the entry without its own hash slot. Examples: - -| Index | Name | `joaat32` | -|---:|---|---| -| 0 | `SKEL_ROOT` | `0x6686685C` | -| 1 | `SKEL_Pelvis` | `0x8133DE19` | -| 117 | `SKEL_L_Hand` | `0xA49BBD43` | -| 220 | `SKEL_Head` | `0x34C53E77` | -| 342 | `SKEL_R_Hand` | `0xB35ABA83` | - -The table is a name/index dictionary, not a hierarchy. The hierarchy is in the next graphics -page. - -## The skeleton instance table - -The `.#ft` stream is followed by a 131,072-byte graphics page at `packs.rpf` offset -`0x4544F010`. Its `+0x08` pointer is `0x50027010`. The page-header pointer `0x500280D0` from -the `.#ft` page lands at `0x10C0` inside that graphics page. The page holds a **597-record -skeleton instance** starting at `0x150`, stride `0x50`: - -| Record offset | Type | Meaning | -|---:|---|---| -| `+0x00` | `u32` | id/flags | -| `+0x04` | `u16` | next sibling | -| `+0x06` | `u16` | **parent index** (`0xFFFF` = root) | -| `+0x08` | `u32` | low 16 = bone index, high 16 = checksum | -| `+0x0C` | `u16` | bone index | -| `+0x0E` | `u16` | next/last-child link | -| `+0x10` | 4 × `f32` | reference rotation quaternion, `(x, y, z, w)` | -| `+0x20` | 3 × `f32` + pad | reference translation | -| `+0x30` | 3 × `f32` + pad | reference scale (all 1.0 in this page) | -| `+0x40` | `u32` + pad | pointer to another record | - -Measured parent coverage: - -- **580** non-root records have a valid measured parent. -- **16** records are roots: `SKEL_ROOT` (0) and the detached helper/attachment range - 572-595. `596` is the fragment-name record, not a deform bone. -- No cycles; every parent index is in range. - -The parent field is enough to rebuild the real core hierarchy. Examples: - -``` -SKEL_ROOT(0) - SKEL_Pelvis(1) - SKEL_L_Thigh(2) -> SKEL_L_Calf(3) -> SKEL_L_Foot(4) -> SKEL_L_Toe0(7) ... - SKEL_R_Thigh(38) -> SKEL_R_Calf(39) -> SKEL_R_Foot(40) -> SKEL_R_Toe0(43) ... - SKEL_Spine_Root(106) -> SKEL_Spine0(107) ... SKEL_Spine6(113) - SKEL_L_Clavicle(114) -> SKEL_L_UpperArm(115) -> SKEL_L_Forearm(116) -> SKEL_L_Hand(117) ... - SKEL_Neck0(217) -> SKEL_Neck1(218) -> SKEL_Neck2(219) -> SKEL_Head(220) - SKEL_R_Clavicle(339) -> SKEL_R_UpperArm(340) -> SKEL_R_Forearm(341) -> SKEL_R_Hand(342) ... -``` - -**Correction: the table above reads each record 0x40 bytes late.** The skeleton header that a -drawable points at with `+0x18` (the fragment's drawable for these humanoid fragments) gives the -record array, and in it a record starts with its transform: - -| Header offset | Meaning | -|---:|---| -| `+0x28` | pointer to the 0x50-byte bone records | -| `+0x30` | pointer to one 64-byte **inverse bind matrix** per bone | -| `+0x40` | pointer to a `u16` parent index per bone (`0xFFFF` = root) | -| `+0x6C`, `+0x6E` | `u16` bone count, twice | - -| Record offset | Type | Meaning | -|---:|---|---| -| `+0x00` | 4 × `f32` | default rotation quaternion `(x, y, z, w)`, local to the parent | -| `+0x10` | 3 × `f32` | default translation, local to the parent | -| `+0x1C` | `u32` | `joaat32` of the lowercased bone name | -| `+0x20` | 3 × `f32` | default scale | -| `+0x30` | pointer | bone name | -| `+0x46` | `u16` | parent index (the same value as the parent array) | -| `+0x48` | `u16` | the bone's own index | - -So the table above's `+0x06` parent and `+0x08` index are `+0x46`/`+0x48` of this layout, and its -`+0x10`/`+0x20`/`+0x30` rotation, translation and scale are the **next** bone's. Measured on the -graphics page at `0x4544F010`: the parent at `+0x06` of each table row equals `+0x46` of the -record that starts 0x40 bytes earlier (597 of 597), that record's `+0x48` is its own index (596 of -596 bones), and a row's `+0x10` rotation is the next record's `+0x00` (596 of 596). Read from the -record start, the page's rotations and translations are those of the female skeleton below (596 of -596). The shifted pairing is why composing the table put the spine on the wrong side of the pelvis. - -Read this way, the default pose is the bind pose: composing the default transforms down the -hierarchy (`world = parent_world * local`) reproduces every stored inverse bind matrix. The -largest difference between a joint's composed origin and the one its inverse bind matrix gives is -5.1e-6 m on the 596-bone female skeleton (`ambient_femalebody_head.#ft`) and 3.3e-6 m on the -560-bone male one (`ambient_malebody_head.#ft`). All 14,212 skeletons that read this way in -`packs.rpf` (13,900 drawable-dictionary children and 312 fragments) agree within 1e-3. The -matrices are row-vector (D3D) matrices; stored row by row they are glTF's column-major layout as -is. `tools/anim_glb.py` exports them as the glTF skin's `inverseBindMatrices` and checks them. - -## Master skeletons and standing space - -Master `crSkeletonData` tables (`root + 0x18`, bone count `u16` at `skel + 0x6c`, `0x50`-byte -`crBoneData` records at `skel + 0x28`, inverse bind matrices at `skel + 0x30`) live inside the 22 -`ambient_*` ped fragment resources in `packs.rpf`. They fall into five master skeleton classes: - -| Master skeleton fragment | Rig token | Named bones | `SKEL_*` | `BM_*` | `MH_*` | `FB_*` | `PH_*` | `OH_*` | `HH_*` | `RB_*` | `SEC_*` | -|---|---|---:|---:|---:|---:|---:|---:|---:|---:|---:|---:| -| `ambient_femalebody` / `femalexxl` | `fr1` / `fo1` | **596** | 78 | 131 | 151 | 56 | 51 | 40 | 23 | 22 | 4 | -| `ambient_femalebb` | `fb1` | **574** | 78 | 131 | 134 | 54 | 50 | 40 | 23 | 22 | 4 | -| `ambient_malebody` / `malexxl` / `alien` | `mr1` / `mo1` | **560** | 78 | 131 | 129 | 46 | 51 | 40 | 23 | 22 | 4 | -| `ambient_malebb` | `mb1` | **552** | 78 | 130 | 126 | 44 | 49 | 40 | 23 | 22 | 4 | -| `ambient_kidbody` / `infantbody` | `mk1` / `mi1` | **454** | 78 | 104 | 124 | 44 | 15 | 36 | 0 | 22 | 4 | - -Subsystem roles (counts shown for the 596-bone `ambient_femalebody` master rig): - -- **`SKEL_*` (78):** Core animation tree — `SKEL_ROOT`, `SKEL_Pelvis`, a 7-segment spine - (`SKEL_Spine_Root`, `SKEL_Spine0..6`), a 3-segment neck (`SKEL_Neck0..2`), `SKEL_Head`, - clavicles, scapulae, limbs, 4-joint fingers (`Finger00..43`) and 3-part toes (`Toe0`, `Toe10`, - `Toe20`). -- **`BM_*` (131):** Body-morph and anatomical definition drivers (`BM_L/R_Bicep`, `BM_L/R_Deltoid*`, - `BM_L/R_Breast*`, `BM_Cleavage`, `BM_L/R_Butt`, `BM_Stomach*`, `BM_Spine0..5`). -- **`MH_*` (151 female / 129 male):** Muscle/crease helpers (`MH_L_KneeCrease`, `MH_L_PecUpper`, - `MH_L_Butt`) and garment/jewelry anchors (`MH_BraStrap`, `MH_BeltLoop`, `MH_Necklace_*`, - `MH_Choker_Spr_01`). -- **`FB_*` (56 female / 46 male):** Oral, jaw and mask rig — `FB_Root`, `FB_Jaw`, 24 individual - tooth bones, an 11-bone articulated tongue, mouth bags, plus female mask and earring anchors. -- **`PH_*` (51) and `HH_*` (23):** Prop, weapon, ground-contact and holster attachment bones. -- **`OH_*` (40) and `RB_*` (22):** Orientation/recoil helpers and limb twist/roll bones. -- **`SEC_*` (4):** Dedicated secondary-motion breast physics bones (`SEC_L/R_Full_Breast`, - `SEC_L/R_Mid_Breast`); buttocks and belly have zero `SEC_*` / `SPR_*` bones. -- **Ear and specialised helpers (40):** `EarRig_*` (10), `EarJaw_*` (2), `TGT_*` (2), `XH_*` (5), - `EO_*` (4), `IK_*` (4), `Tuck_L/R_Tgt` (2), `CH_*`/`WH_*` (4), `UV_L/R_Scapular` (2), plus watch, - ponytail, capsule-offset and camera-attach helpers. The 36-bone female-over-male delta is 39 - female clothing/jewelry/mask/scapular helpers minus 3 male-only bones (`MH_L/R_Toe`, `PH_HAT_LOC`). - -**Standing-space coordinate convention:** In bind space, bipedal feet sit near `Z = -1.0 m` below -`SKEL_ROOT` at the origin, whereas modular drawable bounds (`root + 0x30..0x4f`) are authored in -standing space with **`SKEL_ROOT = (0, 0, +1.0 m)`** in RAGE Z-up (`(0, +1.0 m, 0)` in glTF Y-up) -so feet rest on the ground plane. Translating the skeleton root node (or static mesh vertices) by -`+1.0 m` vertically aligns all modular ped parts without per-slot offset tables; see -`tools/ped_assemble.py` and [character_models.md](character_models.md#standing-space-coordinate-convention). - -## Model-side bone mapping - -Each character drawable's `grmModel` header points at a **bone-hash array** (at `+0x28`, as -rpf9-explorer's `RageSkeleton.ReadModelPalette` reads it; an earlier version of this table said `+0x20`, -which in 3,000 sampled part models is never a hash list that resolves): - -| `grmModel` offset | Meaning | -|---:|---| -| `+0x08` | geometry pointer array | -| `+0x10` | geometry count (also duplicated at +0x12 and +0x36) | -| `+0x14` | local bone count | -| `+0x18` | bounds pointer | -| `+0x28` | **bone-hash array pointer** | - -The array is `local bone count × u32`, sorted ascending. Each hash is matched against the -597-entry `joaat32` table to obtain the global bone index. Measured coverage: - -| Part | Local bones | Resolved to the 597 table | -|---|---:|---:| -| head | 51 | 51 | -| body | 28 | 28 | -| hands | 198/199 | 199 | -| feet | 35 | 35 | -| undies | 44 / 18 | 43 / 18 | -| brabikini | 75 / 33 | 55 / 33 | -| jacket | 107 | 0 (hash-only) | -| crop tee | 137 | 80 | - -Unresolved hashes are genuinely absent from the ambient table; they should be emitted as -`bone_0x...` fallbacks, never given invented names. - -## Vertex skin streams (ASSET-12) - -Measured with `tools/skin_streams.py` over every drawable resource that carves out of `packs.rpf`, -`data.rpf` and `levels.rpf` of the 1.0.2.1 package: the tool walks the same drawable → LOD → -`grmModel` → geometry chain as the readers above, joins each resource's pages (system pages first, -then graphics pages, one zlib stream per page) and reads the FVF semantic table, whose per-semantic -entries are a `u32` stream offset at `fvf + 4*i`, a `u8` element size at `fvf + 0xD0 + i` and a -`u8` format at `fvf + 0x104 + i` (vertex count = `u32` at `fvf + 0x138` >> 10). A size-0 slot is -a placeholder with no stream. The candidate scan only starts a resource at a 4096-aligned offset -with 16 preceding zero bytes — rpf9-explorer's recovery convention — and does not recurse into -nested archives, so the counts are a floor for the package. - -| Layout | Weights (semantic 16/17) | Indices (semantic 20/21) | Meshes | Vertices | -|---|---|---|---:|---:| -| 4 influences, 8-bit | 16: `R8G8B8A8_UNORM` | 20: `R8G8B8A8_UINT` | 38,721 | 40,631,019 | -| 8 influences, 8-bit | 16, 17: `R8G8B8A8_UNORM` | 20, 21: `R8G8B8A8_UINT` | 23,860 | 47,611,935 | -| 4 influences, packed | 16: `R8G8B8A8_UNORM` | 20: `R32G32B32A32_UINT` | 18,247 | 39,468,907 | -| 8 influences, packed | 16, 17: `R8G8B8A8_UNORM` | 20, 21: `R32G32B32A32_UINT` | 16,111 | 9,512,230 | -| rigid, 8-bit | none | 20: `R8_UINT` | 5,364 | 3,606,677 | -| rigid, 16-bit | none | 20: `R16_UINT` | — | — | - -Total: 102,303 skin meshes / 140,830,768 vertices. The meshes split by archive: `packs.rpf` -45,854 meshes / 60,142,591 vertices, `data.rpf` 3,222 / 3,854,484 (all 4-influence 8-bit), -`levels.rpf` 53,227 / 76,833,693. No 16-bit index form appears in the top-level streams of these -three archives; the 16-bit forms were measured (over nested-archive recovery) in the independent -measurement linked below. The format names are the DXGI equivalents of the measured format bytes — -28 for the weight slots, 30 for the 8-bit index slots, 3 for the packed index slots, 62 for the -rigid 8-bit index slot — anchored on the decoded bytes, not on a name table: the 1.0.2.1 FVF -format byte is not desktop DXGI numbering (desktop `R32G32B32A32_UINT` is 3 but desktop -`R8G8B8A8_UNORM` is 24, and here it is 28; `R16_UINT` is 56 in desktop DXGI and 57 here, as -breadbbbb/rpf9-explorer#10 reads it). - -Rules the bytes support, validated per mesh against the model's own bone count (`grmModel + 0x14`) -on a deterministic sample (96 meshes per layout per archive; the census itself covers every mesh): - -- **The index is into the model's own bone list.** Every component with a non-zero weight has an - index below the local bone count — zero violations in every sampled mesh; a zero-weight - component may carry any index, so the check masks by weight. -- **The weights are the UNORM bytes and sum to 255** over all present weight slots. Every sampled - vertex of every layout in `data.rpf` and `levels.rpf`, and of the 8-influence and 8-bit - 4-influence layouts in `packs.rpf`, sums to exactly 255. The packed 4-influence meshes in - `packs.rpf` round: of 50,648 sampled vertices, 31,884 sum to exactly 255, 11,604 to 247–254, - and 7,160 fall below 247 (as low as 164). -- **Packed `R32G32B32A32_UINT`: the bone index is bits 0–11 of each u32.** Bits 9–11 were never - set in the sampled meshes; bit 8 appears only where the model has more than 256 bones. Bits - 12–31 hold a separate, dense, unidentified field (smooth per-vertex values in the high bits — - not a weight: the weights are already complete in 16/17). -- **Rigid meshes carry one index per vertex and no weight slot.** -- The vertex buffer head carries one native buffer descriptor word per used semantic; every skin - slot's stream offset (bits 7–28 of the word) matched its descriptor. The word's size code - (bits 3–6) equals the element bytes for the 4- and 8-byte slots, reads 1 for the 16-byte packed - index slot and 0 for the 1-byte rigid slot, so only the offset is checked. - -This corrects the earlier reading of this section (semantic 20 as packed `(u16 bone, u16 weight)` -pairs, semantic 21 as weights): semantic 21 is always index-typed, and the weights are the UNORM -bytes of semantics 16/17. The earlier "16 bytes that do not form `(bone, weight)` pairs" note was -the packed index layout above. [An independent measurement of the same layouts, over rpf9-explorer -recovery with the bone-palette pull requests applied, was posted in -#634](https://github.com/ItsNotRexed/Leonida/issues/634#issuecomment-7074504326); the counts there -are higher because that recovery also walks nested archives. - -## Animated glTF export - -`tools/anim_glb.py` puts the three readers together: the skeleton above, the part meshes' skin -streams, and the clip dictionaries of `anim.rpf` (`tools/anim_clips.py`, see -[animation.md](animation.md#keyframe-decoding)). It writes one GLB with a glTF skin and one glTF -animation per `.clip`: - -```powershell -python -I tools/anim_glb.py \packs.rpf \walk.glb --skeleton ` - --part [:] --part ... ` - --anim \anim.rpf --dictionary [--clip ...] -python -I tools/anim_glb.py \packs.rpf --coverage --skeleton ` - --anim \anim.rpf --jobs 8 --report \coverage.json -``` - -On 1.0.2.1, `--skeleton 0x45417010` names the `ambient_femalebody_head.#ft` fragment; -`0x45449F70` in the section above is the name-table stream, not a fragment. - -`--clip` matches the full clip label or the dictionary hash. When the hash is the leaf-name hash, -one value selects every path with that leaf: in dictionary `0xfc91b010`, `0xe61dc582` is -`joaat32("move")` and selects all six `/move` clips. Pass the full label (for example -`gameplay@locomotion@female_generic@normal@standing@walk@slope@up/move`) to export one clip. - -Offsets are zlib stream offsets (as `tools/skin_streams.py` and `rpf9dump` report them). The -output is a standard glTF 2.0 file; Blender and the three.js editor play its animations. What -it does and why: - -- **Joints** are the skeleton's bones with their default transforms as the rest pose, and the - stored inverse bind matrices. The export refuses a skeleton whose default transforms disagree - with them by 1e-3 or more. -- **Part meshes** bind through their model's bone list: vertex bone index → `grmModel + 0x28` hash - → the skeleton bone with that `joaat32`. Weights are the UNORM bytes divided by their sum; up to - eight influences become `JOINTS_0/1` and `WEIGHTS_0/1`. three.js reads only the first set, and - eight matter here: on the arms part below, 3,746 of 5,821 vertices have more than four - influences, with up to 0.37 of the weight beyond the largest four. `--max-influences 4` keeps - the largest four, renormalised, for such viewers. A part with a *weighted* bone that is not in - the skeleton is refused with the missing hashes, never bound to a guessed bone. -- **Clips:** `bonerotation`, `bonetranslation` and `bonescale` tracks drive the joint whose hash is - the track's bone hash. Bone hash 0 drives a `mover` node above the skeleton (root motion; - `--no-root-motion` leaves it out). Other track types are counted, not exported. A clip entry - plays its animation's `[start, end]` window at `rate`, so animation time `t` is clip time - `(t − start) / rate`. `(end − start) / rate` equals the clip's `+0x78` duration for all 785,174 - entries of all 61,505 dictionaries, to within 2.2e-4 relative (see [animation.md](animation.md#clip-dictionaries-are-rage-resources)). -- The whole skeleton sits under one node that turns RAGE Z-up into glTF Y-up. Skinned mesh nodes - sit at the scene root, because glTF ignores a skinned mesh node's own transform. - -Measured on the 1.0.2.1 copy: - -| Check | Result | -|---|---| -| Skinned part drawables in `packs.rpf` (dictionary children with a bone list, no own skeleton) that read: positions, clustered triangles, skin streams | 9,571 of 9,571 (9,999 meshes: 9,091 8-bit, 908 packed indices) | -| … whose weighted bones all bind to the female skeleton | 6,359 (6,322 also bind to the male one) | -| … that use bones outside both skeletons (mostly clothing with its own cloth bones) | 3,212 | -| Clip bone tracks (rotation, translation, scale; mover left out) whose bone hash is a joint of the female skeleton | 9,167,307 of 10,137,825 (90.4%), in 52,752 dictionaries | -| … of the male skeleton | 9,164,859 (90.4%) | -| Dictionaries with at least 90% of their bones in the female skeleton | 44,346 | -| Clip rotation convention: joints whose default rotation is far from identity (rotation w below 0.9 in magnitude) and whose clip rotation is closer to the default than to its conjugate | 112 of 125, in four female locomotion and interaction dictionaries | - -Clip translations match the default bone lengths except on helper bones that are meant to move -(`IK_*`, `PH_*` ground references and placements, `SKEL_ROOT`), so clip values are local -transforms in the same convention as the skeleton's defaults. - -An export of a female head, arms and legs part with a locomotion walk dictionary (three clips) -was checked in Node with three r160's `GLTFLoader` and `AnimationMixer`: - -- At rest, skinned vertices equal the stored ones turned to Y-up, within 4.1e-7. -- Over nine samples of every clip, joint matrices are finite and bone lengths of joints without - translation tracks change by at most 3.9e-7. -- The figure is 1.72 m tall. The feet alternate front and back by about ±0.65 m, four steps per - 3.7 s clip, and the last frame equals the first. - -The same body with 40 randomly chosen female clip dictionaries (240 clips) exports without error. -The Khronos glTF Validator reports no errors, warnings or infos on any of the 40 files, and the -three.js checks above pass on all 240 clips. - -No textures are exported. A part binds to the one skeleton given, so clothing whose cloth bones -are not in it does not bind (see the table). -## Skinned GLB export - -`tools/skinned_glb.py` writes one skinned glTF 2.0 binary from a decoded ped skeleton -`model.json` and one or more decoded drawable directories. It reads the drawable's palette -(`grmModel + 0x20`), maps each palette hash through the drawable's own skeleton/string table -and then the ped table, and reads the 8-influence streams from the graphics buffer. The -section offsets are also in `drawable.buffers[vertex_buffer].mesh_blob.sections` as -`[semantic, offset, format]`; the 23-word mesh-block header encodes -`offset = (word >> 8) * 2`, `format = word & 0xFF`. - -| Component | Slot | Stream | Offset | Format | Bytes | -|---|---|---:|---:|---:|---:| -| head | 8 | `JOINTS_0`, 4 x u8 | 215,720 | `0x25` | 35,932 | -| head | 9 | `JOINTS_1`, 4 x u8 | 251,652 | `0x25` | 35,932 | -| head | 6 | `WEIGHTS_0`, 4 x u8 UNORM | 143,856 | `0x26` | 35,932 | -| head | 7 | `WEIGHTS_1`, 4 x u8 UNORM | 179,788 | `0x26` | 35,932 | -| jacket | 8 | `JOINTS_0` | 275,032 | `0x25` | 39,272 | -| jacket | 9 | `JOINTS_1` | 314,304 | `0x25` | 39,272 | -| jacket | 6 | `WEIGHTS_0` | 196,488 | `0x26` | 39,272 | -| jacket | 7 | `WEIGHTS_1` | 235,760 | `0x26` | 39,272 | -| *packed layout* | 8, 9 | `JOINTS_0/1`, 4 x u32 | section entry | `0x8C` | 16 x vertices | - -Joint slots may also use the packed `R32G32B32A32_UINT` layout, format `0x8C`: 16 bytes -per vertex, four little-endian u32 words whose low 12 bits are the joint index (bits -12–31 are a separate unidentified field). The exporter converts it to the same 4 x u8 row -as `0x25` and rejects an index above 255. Only `0x8C` is accepted: no `0x8B` joint layout -has been measured, so `0x8B` is rejected rather than guessed. - -The output has one skin. Its joints are the full ped skeleton plus any drawable-local helper -joints named by the palette; a palette hash that resolves nowhere is emitted as -`bone_0x........`, never given an invented name. Every vertex keeps all eight influences as -`JOINTS_0`/`JOINTS_1` and `WEIGHTS_0`/`WEIGHTS_1`. The source u8 weights sum to 255 and are -normalised to 1.0. Bind and inverse-bind matrices use the same Z-up to Y-up conversion as -positions, `(x, y, z) -> (x, z, -y)`. - -```bash -python -I tools/skinned_glb.py out.glb \ - --skeleton /model.json \ - --component /model.json \ - --component /model.json -``` - -The measured head/jacket export uses 596 ped joints plus 107 garment helper joints (703 -total). This is a static-export skip: only the components named on the command line are -exported, and no body or other unrequested component is assembled. No game data or generated -GLB is stored in the repository; `tests/test_skinned_glb.py` builds its own skeleton, skin -buffer and GLB. - -`python -I tools/glb_inspect.py out.glb` reads the written file back with no glTF library and -prints its mesh, skin (joint count) and animation counts, the POSITION bounding box and any -field the exporter dropped; [models.md](models.md#skinned-glb-export) lists what the rest of -the report carries. - -`python -I tools/glb_skinning.py out.glb` checks the skin data itself: each skin's joint and -`inverseBindMatrices` counts, the accessor types and finite values, which primitives carry -skinning data and which are static, `JOINTS_n`/`WEIGHTS_n` pairing, every vertex's weight sum -as FLOAT or normalized `UNSIGNED_BYTE`/`UNSIGNED_SHORT`, the joint-index range and the POSITION -bounds computed from the accessor. A malformed container, a file with no skin, or a skin whose -`inverseBindMatrices` count differs from its joint count exits nonzero; `--json report.json` -writes the same report as LF-only JSON. `python -I tests/test_glb_skinning.py` runs its 17 -synthetic tests and needs no game files. - -## Texture parameter split - -The character material blocks carry several 32-bit parameter hashes before each 64-bit asset -key. Across the measured character materials, the texture content separates cleanly: - -| Parameter | Common formats | Measured role | -|---|---|---| -| `0xC8E8C282` | BC1/BC3/BC7 sRGB, some BC1/BC7 UNORM | **sRGB albedo** when present | -| `0xC6F46E79` | BC7 UNORM, BC1 UNORM | `speculartex`: specular/gloss (packed), not a normal map | -| `0x1E77BF4C` | BC5 UNORM, some BC1/BC7 | `bumptex`: tangent-space normal/detail normal | -| `0x739E3D0D` | BC7 UNORM, some BC1 | `speculartex2`: ORM/mask (packed) | -| `0x8ADB8480` | BC4 UNORM | `materialid`: ID/palette map | - -This is a measured corpus split, not a claim that the hashes are globally unique semantics. -The practical rule for exporters: use `0xC8E8C282` as albedo, and **do not fall back to the -first texture** when it is absent. A normal map painted as a base colour is the usual symptom -of that fallback. - -To apply this rule, pass `--base-color-param C8E8C282` to `tools/world_build.py` (or -`base_color_param="C8E8C282"` to `build_world`): only references with that parameter hash are -used as base colour, and materials without a resolvable match stay untextured clay. Without the -option the exporter keeps its existing first-resolvable-reference behaviour, because these hash -roles are measured only on the character corpus. - -## The Mandy search - -Mandy is a KeyLento persistent/cutscene character schedule, not a unique drawable. `common.rpf` -contains the schedule entry `KeyLento/Perschars/Peds/Unique/Mandy` (pack -`PSP_KeyLento_perschars_peds`) in the `CPedScheduleInfoManager` XML. A read-only search of the -1.0.2.1 package found no `mandy`/`cs_mandy`/`ig_mandy`/`mp_mandy` drawable or fragment: - -| Container | Search | Mandy drawable | -|---|---|---| -| `packs.rpf` | 144,364 streams / 9.74 GB; 26,585 decoded models at `e293917` (24,034 at `917e9b9`); 12,338 name records | none | -| `data.rpf` | 28,509 streams / 1.41 GB | none (localization/UI text only) | -| `common.rpf` | 954 streams / 50 MB | none (schedule and ped-appearance XML) | -| `levels.rpf` | 2,051 page-aligned nested archives, every zlib stream's first 4 MiB | none (an iFruit billboard and a house photo prop are the only name hits) | -| `story000.rpf` | 0-4 GiB and the 14 GiB region | none (animation clips `*_mandy.clip`, no drawable) | -| `story000_script.rpf`, `script.rpf`, `shared_minigame000.rpf`, rest-of-world, `audio.rpf`, `anim.rpf`, `movies.rpf`, `textures.rpf`/peds TTPF | full raw scans | none | - -The name controls resolve `cs_kenton`, `u_f_o_rhonda`, `cs_monalisa` and `cs_lucia`; Mandy does -not. The delivered `mandy/` preview export is therefore a clearly labelled `cs_monalisa` proxy, -not a verified Mandy model. - -Two further checks refine that negative. A missing `mandy` name is the common case, not an -anomaly: of the 13 `KeyLento/Perschars/Peds/Unique` entries, two resolve cleanly by name -(`kenton` -> `cs_kenton`, `rhonda` -> `u_f_o_rhonda`), one plausibly maps (`Bert` -> -`hc_cs_herbert_watson`), and the other ten, including `Mandy`, have no name hit. Also, the -package manifest lists 108 files and its `pack/` directory contains only `story000`, -`core_restofworld`, `core_restofworld001`, `shared_minigame000` and their `_bvh4`/`_licenses` -companions; there is no `psp_*` archive, so the `PSP_KeyLento_perschars_peds` pack named by the -schedule is not present in this build. Mandy is therefore not disproven: her appearance is either -a generic ped assembled at runtime or in a pack this package does not include. - -Caveats: `levels.rpf` was prefix-bounded at 4 MiB per inflated stream, raw RSC8 bodies and -Bink/opaque regions were not decoded, and the encrypted RPF9 table of contents prevents a full -path enumeration (27 top-level entries remain). The evidence supports a shared ped-appearance -actor assembled from existing components, not a unique `mandy` resource. -The mission binding is now measured. `COM_KBOS_NEIGHB` is the internal id of the "Pipework" -mission: the replay table carries that ``, and the mission text names "Mandy's -house", "Follow Mandy" and "Bert died". Five PSIN state tables in -`pack/story000/story000_script.rpf` (`03fe4000`, `03fe8000`, `03feb000`, `03fee000`, -`03ff0000`) contain both characters as entity link hashes: `0x03A885E6` (`Mandy`) and -`0xE34ACBC8` (`Bert`); the schedule pack hash is `0x865F0DA9` -(`PSP_KeyLento_perschars_peds`). - -The model binding is also decoded. `PERSCHARS_INFO` (`data.rpf@0x1AA5F000`, record 3499) maps -`Name = 0x03A885E6` (`mandy`) to `ModelSetName = 0x03A885E6`; `CPedModelInfo__InitData` -(`packs.rpf@0x11D1FF000`, record 1219) maps that link to `cs_mandy` (`0xD7C0CDFF`). `cs_mandy` -is a live model id — a `story000.rpf` cutscene actor/voice table uses it — but there is **no -named `cs_mandy` drawable**. The `cs_mandy` ID above is the 32-bit `ModelName` at row offset -`+0x0C` (schema type `0x4D`). The adjacent 64-bit `FragName` at `+0x10` (type `0x4F`) -`0xC9888B65009B33B7` is the shared female cutscene base, carried by **904** female rows: -`player_story000_00` (Lucia's model id `0xE472B687`), `cs_monalisa` (`0x9CB9BCC6`) and -`cs_mandy` (`0xD7C0CDFF`), plus 901 others. No ped-model row carries `joaat("cs_lucia")` -(`0x95F1E309`); that is a name prefix, not a model id. A second base -`0x0A704516C676E805` is shared by `cs_shanese` (`0x3570D92E`) and 11 unnamed female rows, and -8 female models have wholly model-specific fragments. None resolves to a name, and neither -table contains an adult-token, `mp_f_*`, `nude`, `topless`, `stripper`, `prostitute`, `dancer`, -`escort`, `hooker`, `swim`, `lingerie` or `club` female model. The realistic full-body in the -shared base is `cs_lucia_legacypedcs` -(874 v), so Mandy uses the same body as Lucia. Her nine-entry variation table has 18 u32 hashes; -16 are unique to her. A deeper search — 373,484 shipped names / 725,869 normalised variants plus -about 25 million generated strings — gives **0/18** exact matches. The sibling nine-entry table -resolves 9 of 18 values to `joaat("outfit_01")` … `joaat("outfit_10")` (frequency corroborates -it), so the table stores build-time design labels, not shipped asset names; the 18 component -values are not recoverable by name enumeration. `common.rpf` holds `CPedVariationBodyTypeManager` -(77,422 bytes, 67 keys) and `CPedComponentSetManager`; neither maps a variation index to a -drawable plus texture. The first manager's keys are literal model names, and `joaat32` of all -67 gives 0 hits against the 18. The `3cba3fe6` float (0.942 / 0.971 for Lucia and Monalisa) is a -per-character body/height scale, not a name; there is no component/outfit-name manager in -`common.rpf`, and `outfit_NN` exists only as a hash in the packs table. - -The entities linked to Mandy carry three different per-state archetype hashes -(`0x18BB2550`, `0x73E83886`, `0x57DDFFC2`), which fits her outfit changing between states, not -three models. None of those hashes resolves through the package name dictionary, any drawable -or prop name pool, the `packs.rpf` PSOs, or a `0x7a` meta hash scan, so they are state/archetype -ids, not model names. The archetype-to-component-set lookup remains unidentified. - -**Component variation (ASSET-279).** At `packs.rpf@0x11D1FF000`, the first 16 inflated 64 KiB -pages cover the instance blocks and row schema and end inside LSNS. The 16-byte root has one -array of 2,714 model rows, each 384 bytes. The row schema has no array or map, and both struct -pointers (row offsets `+0x118` and `+0x178`) are null in every row. Only record 1219 carries its `ModelName` in this table. Its `FragName` -occurs in 906 rows, including the 904 female rows counted above. -This layout provides no inline array or live struct pointer for either nine-entry table. - -At `data.rpf@0x1B076000`, the PSIN walker reached 25 structures across all seven blocks -(756/756 instance bytes). One owner embeds both 12-byte settings at owner offsets `+0x0C` -and `+0x18`. Each holds a `textureIndex` and two floats. Four separate root maps contain -seven entries between them. The two settings are inline fields, and their subsystem is unknown. -Two XML roots in `common.rpf` describe scale and body-shape profiles (`0x226000`) and entity -components (`0x228000`). A byte comparison against the 1,576,148-byte character metadata prefix -at `data.rpf@0x1AA5F000` found none of the settings candidate's nine distinct nonzero typed -hashes at their original little-endian widths. That prefix did not validate as a complete PSIN. -None of these checks establishes a variation selector. An external lookup keyed by a model-row -field remains possible; confirming it requires tracing a component variation to both its -drawable and its texture. - -`Mandy_FirstTingle`, `Mandy_ComingUp` and `Drug_Mandy_*` in `common.rpf` are MDMA drug effects, -not the character. They are a red herring in any `mandy` name search. - -Caveats: the RPF9 table of contents is still not decoded; names come from carving and recovery -(318,266 unique `levels.rpf` names, 24,034 `packs.rpf` names), and raw RSC8 bodies and -Bink/opaque regions were not decoded. The evidence supports a shared ped-appearance actor: a -`cs_mandy` model id, a body fragment shared with `cs_lucia` and `cs_monalisa`, and a variation -table, not a unique `mandy` drawable. - -## Reproduction - -Steps 1-4 were measured with local tools that are not part of this repository; a reader can -reproduce them with a standard zlib/RPF9 reader: - -1. Inflate the `.#ft` **name-table** stream at `0x45449F70`; parse the 4,095-slot hash table and the - NUL-separated names; verify `joaat32` lowercased. -2. Inflate the following 131,072-byte graphics page at `0x4544F010`; parse the records at - `0x110 + 0x50*i`: rotation at +0x00, translation at +0x10, hash at +0x1C, parent at +0x46 - (see the correction above). `tools/anim_glb.py` reads the same records through the - skeleton header at drawable `+0x18`. -3. For a character `#dr` system page, read `grmModel+0x28`, then the `u32` bone hashes. -4. Map each hash through step 1; unresolved hashes are hash-only fallbacks. -5. Run `python -I tools/skin_streams.py [...] --json out.json` for the - skin-stream census and validation; `python -I tests/test_skin_streams.py` runs the same walk - and the same checks on synthetic resources built by the test. -6. Run `python -I tools/anim_glb.py ... --coverage` (above) for the clip-track counts, and - `python -I tests/test_anim_glb.py` for the export on synthetic skeleton, part and clip data. - -No archive, model, texture or audio file is stored in the repository or in any test fixture. diff --git a/docs/coder.md b/docs/coder.md deleted file mode 100644 index cd20845aa..000000000 --- a/docs/coder.md +++ /dev/null @@ -1,110 +0,0 @@ -# The compressed mass in the story script archives - -`story000_script.rpf` and `script.rpf` hold data in a framing the rest of the package does not use. -Most of it is ordinary zlib, but a large part of `story000_script.rpf` is compressed by an encoder that -no standard decoder reproduces. This page records what was measured about it, so the next attempt starts -from the numbers instead of from a guess. Everything below is counts, offsets, constants and -statistics over the user's own copy — no payload is stored here. - -Subject: `story000_script.rpf`, region `0x2000..0x3127000` (51,531,776 bytes), 905 page-blocks. - -## Two populations - -| population | blocks | bytes | share | decoder | -|---|---:|---:|---:|---| -| `78 DA` zlib at block start | 105 | 893,535 | 1.79 % | standard zlib, raw deflate at +2 with a 32 KiB window | -| anything else | 767 | 49,095,163 | 98.21 % | unidentified | - -The two are **interleaved**, not separated by region: 211 population switches across the first 120 -blocks. The zlib blocks yield ~2 MB of plaintext that is plainly structured data (8-byte aligned records, -`0x50000000`-space pointers, `FFFFFFFF` sentinels, ascending u32 tables). The other 767 do not decode yet. - -## Entry framing - -Each entry is: - -``` -u16 tag + 6 class-biased header bytes │ zero pad │ payload at the next 16-byte FILE boundary -``` - -i.e. `payload_offset = align16(entry_offset + 8)`, which is `+16` for 766 of the 800 entries measured. -The rule was confirmed 10/10: the predicted pad length equals the observed zero run every time, and the -absolute payload offset is `%16 == 0` every time. This is why earlier scans that assumed payloads start at -the entry start, or that stopped at skip +12, found nothing. - -Header shape (distinct byte values per position over the 800 unknown entries): -`52, 65, 191, 198, 171, 148, 176, 188, 219, 239, 243, 243, …` — i.e. bytes 0..7 are structured and byte 8 -onwards is noise. There is no size field in the header (60 width/endianness combinations tested, all -`|r| < 0.10` against the block length). - -The first two bytes form a **32-value tag alphabet**: 75 distinct u16 in total, but 32 codes carry nearly -all 800 entries at 15–33 each (800/32 = 25 expected). It is not a bitfield (byte 0 has 52 values, byte 1 -has 65, joint 75 ≪ 3380), and it correlates with nothing measured: length (`r = -0.035`), gap to the next -entry (`-0.036`), offset (`+0.035`), or neighbours' population. Codes never cluster in file order (881 runs -over 905 entries), so it is not a file or stream id. - -## What the payload is not - -Every decoder below was run at the **correct** `align16(entry+8)` offset, with a positive control that -passes on data compressed by that same decoder, and against a same-geometry random baseline. - -| family | result | -|---|---| -| deflate (raw, and raw with a 32 KiB zero window) | 0 of 800 entries give even 4 KiB of partial output | -| zlib, both framing and preset-dictionary (all 32 fcheck-valid CMF/FLG, FDICT set) | 0 — payloads never begin with a `78 xx` header at all | -| zstd (magicless and framed), brotli, snappy, lz4 (two decoders), LZAV, FastLZ, LZF, LZJB, bz2, xz, lzma-alone, lzma-raw | 0 | -| Oodle (oo2core 2.9.10, positive control bit-exact) | 0 over 11 offsets × 19 destination sizes × fuzzSafe 0/1 | -| 21 byte/bit transforms (bit-reverse, nibble-swap, rotates, delta, xor-prev, transposes, block reversal) × 4 decoders | 5 hits against a 2-hit random baseline, 4 degenerate | - -## What the payload is - -Statistical shape, measured against the same statistics computed on data compressed by each family: - -| statistic | zlib level 9 | lzma | bz2 | this payload | -|---|---:|---:|---:|---:| -| popcount correlation | +0.676 | −0.065 | −0.432 | **+0.632** | -| bit-plane bias | +0.0138 | −0.0007 | −0.0110 | **+0.0083** | - -So it is **deflate-shaped but proprietary**: an LZ+entropy coder in the deflate family, not LZMA and not a -BWT coder. AES-class output is excluded because all eight bit planes are biased the same way at ~40σ, -which ciphertext cannot do. Bit autocorrelation is +0.006 *inside* a byte and exactly 0 at byte boundaries, -so the stream is bit-domain with no byte framing. - -The code is **variable-length and LSB-first**. That was established from runs of one repeated symbol: a run -emits the same code repeatedly, so the bit spacing of a run equals the code length. Across the region, -21 non-zero period-7 runs show a uniform **7-bit** spacing and 6 show **8 bits**, in LSB-first order -(MSB-first gives 9, 9, 9, 9, 9, 2, 7 on the same patterns — inconsistent). - -The only visible structure in the 331,760-byte single-block sample at `script.rpf+0x2010` is a 496-byte -field at payload+0x14460, 16-byte aligned at both ends, made of exact period-7 repeats in two groups -(54 and 16 copies). Decomposed as 8 symbols × 7 bits, each group is **one plaintext u32 repeated**: - -``` -group A: 63 30 48 16 | 63 30 48 16 -group B: 2 7 115 102 | 2 7 115 102 -``` - -at 28 bits per 4 bytes = **7.00 bits/byte**. So the field is a table of ~140 identical 4-byte entries -(default records), the repeats are literals rather than matches, and the coder achieves roughly 1/8 -compression on repeated data. The eight 7-bit code values read out are `2, 7, 16, 30, 48, 63, 102, 115`. - -## The one missing piece - -The coder stores **no table**: the longest run of identical bytes anywhere in 331 KB is the 32-byte zero -tail, and a canonical-Kraft scan over 8,192 offsets finds nothing. With variable-length codes of 7 and 8 -bits and no stored table, the symbol→length mapping is a **static array in the executable**. - -That array is narrow enough to search for. A Kraft-exact length vector for 7- and 8-bit codes satisfies -`2·n7 + n8 = 256`; with the largest observed code value 115 requiring `n7 ≥ 116`, the candidate families -are `n7 = 116..127`, i.e. a **129–140 byte vector of 7s and 8s**, most likely `n7 = 116, n8 = 24` -(140 symbols). Search the executable for a 129–140 byte run of values in `{7,8}` satisfying that equation. -It is not in the package: the 16 bundled DLLs and the whole 348 MB `gameos.xvd` contain no such run -(byte-exact search), and no `oo2core`/`Oodle`/codec string exists in either. - -## Recovered plaintext, for calibration - -Two independent extractions recovered 1,961,559 bytes and 855,961 bytes of payload (the second from -entries whose zlib part is buried behind the aligned header). The 0x88-byte record structure in it is -described in the mission notes; the useful calibration here is that a correct decode of the remaining -767 entries should produce the same record discipline: 8-byte alignment, pointers of the form -`0x50000000 | offset` with the high dword 0, and 96.7 % of pointers at even dword indices. diff --git a/docs/cpu_features.md b/docs/cpu_features.md deleted file mode 100644 index 4b72ca2f5..000000000 --- a/docs/cpu_features.md +++ /dev/null @@ -1,64 +0,0 @@ -# CPU instructions the executable needs - -The Xbox Series CPU is an AMD Zen 2, and the runtime runs the game's code natively -([design.md](design.md), "Why a loader before a recompiler"). Code built for one known CPU can use every instruction -that CPU has without asking CPUID first. An instruction the host lacks raises `#UD` -(`STATUS_ILLEGAL_INSTRUCTION`) where it is reached, and a privileged one faults in user mode. This page records -which such instructions `game_scarlett_master.exe` contains, measured with `tools/cpu_feature_scan.py`. Counts only; -nothing from the executable is quoted. - -## Reproduce - -```powershell -python -I tools\cpu_feature_scan.py \game_scarlett_master.exe # summary -python -I tools\cpu_feature_scan.py \game_scarlett_master.exe --sites # plus the RVA of each flagged site -``` - -It streams MSVC `dumpbin /disasm:nobytes` (a few minutes for this executable, with no listing written to disk; a saved -listing works too, with `--image ` for `.pdata`). Each instruction is mapped to the CPUID feature or privilege class it -needs, and each count is split by whether the site lies inside a `.pdata` function range. A linear disassembly also -decodes data in `.text` (jump tables, padding), so a hit outside every `.pdata` range is often not code; a leaf -function that does not touch the stack has no `.pdata` entry either, so those sites need a look by hand. - -## Measured result (1.0.2.1) - -26,674,075 instructions decoded in `.text`, 22,435,554 of them inside the 299,257 `.pdata` ranges. - -| Feature | Class | Sites | Inside `.pdata` | What a host without it does | -|---|---|---:|---:|---| -| SSE4a (`insertq`) | AMD only | 19 | 17 | `#UD` on every Intel CPU | -| CLZERO | AMD only | 10 | 0 | `#UD` on every Intel CPU | -| MONITORX (`monitorx`, `mwaitx`) | AMD only | 4 | 4 | `#UD` on every Intel CPU | -| CLWB | newer Intel only | 8 | 6 | `#UD` on Intel client CPUs before Ice Lake / Tiger Lake (Skylake to Comet Lake) | -| Port I/O, `cli`/`hlt` | privileged | 8 | 2 | fault in user mode | -| `int n` (not 3/29h/2Ch/2Dh) | kernel call | 1 | 1 | a software interrupt Windows does not serve | -| CPUID / XGETBV | host query | 9 / 2 | 9 / 2 | run everywhere; answer with the host's values | - -Each flagged site was read by hand in a private copy (not quoted here): - -- All 41 SSE4a, CLZERO, MONITORX and CLWB sites are real code: each sits among instructions of the same kind of - code (vector arithmetic around the `insertq` sites, cache-line loops around CLZERO and CLWB, a wait on a memory - address around the two `monitorx`/`mwaitx` pairs). The 10 CLZERO sites are one leaf routine, a cache-line zeroing - loop with no `.pdata` entry, which is why none of them is inside a `.pdata` range. -- The 8 privileged and 1 `int n` hits are data: tables of 32-bit offsets placed in `.text` (some inside a `.pdata` - range) that the linear sweep decodes as instructions. They are listed for completeness, not as code to replace. - -No AVX-512, VAES, VPCLMULQDQ, SHA, RDPID, RDPRU, XOP, FMA4, TBM, SYSCALL or SYSENTER instruction was found. The -256-bit integer, FMA3, F16C, BMI1/2, ADX, MOVBE, AES-NI and PCLMULQDQ instructions it uses are on every Intel CPU -since Haswell/Broadwell and every AMD CPU since Zen, so they are counted but not flagged. No RDTSC or RDTSCP is -in the image. - -## What it means for the runtime - -- On an AMD Zen 2 or later host every flagged user-mode instruction runs as on the console. -- On an Intel host the SSE4a, CLZERO and MONITORX sites, and on Intel client CPUs before Ice Lake the CLWB sites, - raise `STATUS_ILLEGAL_INSTRUCTION` when reached. `gta6rt` emulates them (`runtime/src/cpu_emulation.h`, see - [runtime/README.md](../runtime/README.md), "PE loader"): CLZERO zeroes the 64-byte line, CLWB is a write-back hint - with nothing to do on coherent memory, MWAITX returns at once (an early return is one the manual allows), and - `insertq`/`extrq` are bit-field operations on the low quadword. `cpu_emulation_test` checks each form against the - CPU on a host that has it and against the handler on one that does not (an i7-10700K: all four lacking, all checks - pass). -- The CPUID sites see the host's vendor, family and features, not the console's. What the game does with the - answers is not measured here. - -Not measured: which of these sites a boot reaches, and in which order. diff --git a/docs/d3d12_command_objects.md b/docs/d3d12_command_objects.md deleted file mode 100644 index 5a214e325..000000000 --- a/docs/d3d12_command_objects.md +++ /dev/null @@ -1,960 +0,0 @@ -# D3D12 command objects: the measured queue, list, fence and `PresentX` surface - -Status: gap analysis, sourced. This page records what can be measured about the Xbox Series -`ID3D12CommandQueue`, `ID3D12GraphicsCommandList` (and 4/6/8), `ID3D12Fence`, -`ID3D12CommandAllocator` and `PresentX` from the shipped package and from the Windows SDK, and -separates that from prior-art claims. It does not propose a vtable and does not copy code. - -Confidence legend, consistent with [d3d12_vulkan.md](d3d12_vulkan.md) and -[d3d12_xs_surface.md](d3d12_xs_surface.md): - -- **Measured** — produced in this tree by a read-only inspection (PE import/export scan, GUID - byte scan, static disassembly) or by a test in this repository. -- **SDK** — checked against the installed Windows SDK 10.0.26100.0 headers. -- **Prior art** — a claim by another project, not independently reproduced here. -- **Derived** — follows from a documented rule plus stated anchors; the derivation is shown. -- **Open** — no evidence. - -Scope limit: no game data, keys or decryption was used; no vendor binary was executed. The -package DLLs are read-only inputs. The game executable that would answer most of the remaining -questions is not in the package (section 1). - -## 1. What the package contains, and what it does not - -### 1.1 Inventory - -The package root contains **16 DLLs** and no D3D12 runtime DLL: - -| Group | Modules | -|---|---| -| Middleware | `amd_fidelityfx_loader_xbox.dll`, `amd_fidelityfx_upscaler_xbox.dll`, `Bink2Scarlett.dll`, `libHttpClient.GDK.dll`, `XboxBvhBuilder.dll`, `XCurl.dll` | -| CRT | `concrt140.dll`, `msvcp140.dll`, `msvcp140_1.dll`, `msvcp140_2.dll`, `msvcp140_atomic_wait.dll`, `msvcp140_codecvt_ids.dll`, `vccorlib140.dll`, `vcomp140.dll`, `vcruntime140.dll`, `vcruntime140_1.dll` | - -The following files are **absent** from the package root and from every subdirectory: - -- `d3d12_xs.dll` — the console D3D12 runtime that owns the queue/list/fence/allocator vtables - and the `PresentX` method; -- `xgameruntime.dll` — the GDK runtime; -- `game_scarlett_master.exe` — the executable that imports the runtime and calls the command - objects. - -The package layout XML lists the executable at -`layout_3202719e-b4b4-421c-9f8f-70d1c4a7d60b_xs.xml:14`, but the file is not in the folder. The -same XML lists the 16 DLLs; it does not list `d3d12_xs.dll` or `xgameruntime.dll`, which are -system/GDK dependencies rather than package payload. This confirms -[d3d12_vulkan.md §2](d3d12_vulkan.md) and Appendix A.4, which already record the absent -executable. - -**Consequence:** the export table, import table and vtable of `d3d12_xs.dll` cannot be read from -this package. Any statement about the console queue/list/fence/allocator slot order in this page -is either SDK-derived, prior art, or a measurement of a *client* of those interfaces (the shipped -BVH builder), never a measurement of the runtime itself. - -### 1.2 What the 16 DLLs import - -A PE import scan (normal and delay-load) of all 16 DLLs gives the complete static D3D12 picture: - -| DLL | `d3d12_xs.dll` import | `d3d12.dll` / `dxgi.dll` import | `xmem.dll` import | -|---|---|---|---| -| `XboxBvhBuilder.dll` | `D3D12SerializeVersionedRootSignature` (1) | none | `XMemVirtualQuery` (1) | -| `amd_fidelityfx_upscaler_xbox.dll` | `D3D12CreateRootSignatureDeserializer` (1) | none | `XMemAlloc`, `XMemFree`, `XMemGetWorkingSetStatistics` (3) | -| `Bink2Scarlett.dll` | none | none | `XMemAlloc`, `XMemFree` (2) | -| the other 13 DLLs | none | none | none | - -No shipped module imports `d3d12.dll`, `dxgi.dll` or `xgameruntime.dll`. No shipped module -imports a queue, list, fence, allocator or `PresentX` free function. The only two `d3d12_xs` -imports are the root-signature calls already recorded in -[d3d12_vulkan.md §7](d3d12_vulkan.md) and Appendix A.2/A.3. This is consistent with the -prior-art statement that the bundled middleware surface is tiny and the command-object surface -belongs to the executable. - -Reproduce: `python tools/pe_inspect.py --game-dir --out ` for each DLL, or -the import scan described in section 8.2. - -### 1.3 What this rules out - -The package cannot tell us: - -- the `d3d12_xs.dll` export names or ordinals for `D3D12CreateDevice`/`D3D12XboxCreateDevice`, - `D3D12SerializeVersionedRootSignature`, the `DXGIX*` present functions or - `InternalDriverCallX`; -- the Xbox queue, command-list, fence or allocator vtable layout; -- the `PresentX` slot, signature or plane struct; -- any return-convention quirk on those interfaces. - -It can tell us which interfaces the shipped BVH builder was compiled against, and it contains -one client that actually calls a command list. That is the useful measurement in section 3. - -## 2. The public slot baseline - -This section is the **SDK** baseline a replacement runtime can implement today. It is not a -statement that the Xbox build uses these slots; section 3 gives the few Xbox call sites that -have been measured. - -Slots are absolute vtable indices including `IUnknown` (0–2) and `ID3D12Object` (3–6). A byte -offset in an 8-byte-slot vtable is `slot * 8`. The counts below were produced by parsing -`d3d12.h` in the installed SDK; each interface's declaration line is given. - -### 2.1 Device creation slots - -| Slot | Byte offset | Method | SDK line | -|---:|---:|---|---| -| 8 | `0x040` | `ID3D12Device::CreateCommandQueue` | `d3d12.h:9006` | -| 9 | `0x048` | `ID3D12Device::CreateCommandAllocator` | `d3d12.h:9011` | -| 12 | `0x060` | `ID3D12Device::CreateCommandList` | `d3d12.h:9026` | -| 36 | `0x120` | `ID3D12Device::CreateFence` | `d3d12.h:9178` | - -The Xbox device is **not** uniformly the public order. Prior art measured slots -1/14/15/16/18/19/27/38 in desktop order, plus a compute-PSO method at 62 and an extra -texture-creation method at 76 where the PC interface has `CreateStateObject`/something else -([d3d12_vulkan.md §7](d3d12_vulkan.md), -[`d3d12_xs_surface.md §2.4`](d3d12_xs_surface.md)). **Slots 8, 9, 12 and 36 were not measured -by that work.** They are the four calls a game must make before it can have a queue, allocator, -list or fence, so they are the first thing a trace must confirm. - -**They cannot be measured from the package either (D3D-350).** The package ships no D3D12 runtime: -the 16 DLLs in [`game/xbox-1.0.2.1.json`](../game/xbox-1.0.2.1.json) do not include -`d3d12_xs.dll`, which is part of the console OS, and the device clients that are shipped never call -these four slots. Measured on 1.0.2.1 (counts only): - -| Image | `ID3D12*` IIDs it contains | Imports from `d3d12_xs.dll` | Calls at `0x40`/`0x48`/`0x60`/`0x120` on the device | -|---|---|---|---| -| `XboxBvhBuilder.dll` | `PipelineState`, `RootSignature` | `D3D12SerializeVersionedRootSignature` | none: no indirect call at any of the four offsets | -| `amd_fidelityfx_upscaler_xbox.dll` | `CommandSignature`, `DescriptorHeap`, `Device`, `Heap`, `PipelineState`, `Resource`, `RootSignature`, `RootSignatureDeserializer` | `D3D12CreateRootSignatureDeserializer` | none: the 3 calls at `0x40` are `ID3D12Resource::Map` on a resource it has just created, the 29 at `0x48` are `Close`/`Unmap`-shaped calls with no `(type, &IID, &out)` arguments, the 4 at `0x60` are a function-pointer field in a plain struct (no vtable load), and there are none at `0x120` | -| `amd_fidelityfx_loader_xbox.dll`, `Bink2Scarlett.dll` | none | none | — | - -Neither image contains the IID of `ID3D12CommandQueue`, `ID3D12CommandAllocator`, -`ID3D12CommandList`, `ID3D12GraphicsCommandList`, `ID3D12Fence` or `ID3D12Fence1`, and neither -can take one from `d3d12_xs.dll`: each imports one function there and no GUID data (ordinals -23–115). A creator called through `IID_PPV_ARGS` needs that IID, so these clients do not create -queues, allocators, lists or fences; they record into lists the game gives them. The interfaces -that *are* present are the positive control: they are what each client is known to create -(compute PSOs through slot 62, root signatures, descriptor heaps, and resources through slots 27 -and 76). The IID column is reproduced by `python -I tools/d3d12_iid_scan.py /*.dll` -(`tests/test_d3d12_iid_scan.py`); the call-site column comes from `dumpbin /disasm` listings, -following each `0x40`/`0x48`/`0x60`/`0x120` call back to its receiver. - -So the four slots' callers are in the game executable, which the package does not contain (the -same blocker as RT-5). Confidence for slots 8, 9, 12 and 36 stays **Open**: the table in §2.1 is -still the SDK baseline. Once the executable is available, `tools/d3d12_iid_scan.py` run on it -shows whether it carries these IIDs, and its call sites through them give the slots. - -### 2.2 Queue, allocator and fence - -`ID3D12CommandQueue` is declared at `d3d12.h:8701`. It has 19 slots (0–18); its own methods start -at 8 because `IUnknown` + `ID3D12Object` + `ID3D12DeviceChild` + `ID3D12Pageable` contribute -eight slots and `ID3D12Pageable` adds none. - -| Slot | Byte offset | Method | SDK line | -|---:|---:|---|---| -| 8 | `0x040` | `UpdateTileMappings` | `d3d12.h:8704` | -| 9 | `0x048` | `CopyTileMappings` | `d3d12.h:8716` | -| 10 | `0x050` | `ExecuteCommandLists` | `d3d12.h:8724` | -| 11 | `0x058` | `SetMarker` | `d3d12.h:8728` | -| 12 | `0x060` | `BeginEvent` | `d3d12.h:8733` | -| 13 | `0x068` | `EndEvent` | `d3d12.h:8738` | -| 14 | `0x070` | `Signal` | `d3d12.h:8740` | -| 15 | `0x078` | `Wait` | `d3d12.h:8744` | -| 16 | `0x080` | `GetTimestampFrequency` | `d3d12.h:8748` | -| 17 | `0x088` | `GetClockCalibration` | `d3d12.h:8751` | -| 18 | `0x090` | `GetDesc` (returns the 16-byte desc by value on MSVC) | `d3d12.h:8756` | - -`ID3D12CommandAllocator` is declared at `d3d12.h:5193`; it has 9 slots (0–8), with -`Reset` at slot 8 (`d3d12.h:5196`). - -`ID3D12Fence` is declared at `d3d12.h:5323`; it has 11 slots (0–10): - -| Slot | Byte offset | Method | SDK line | -|---:|---:|---|---| -| 8 | `0x040` | `GetCompletedValue` | `d3d12.h:5326` | -| 9 | `0x048` | `SetEventOnCompletion` | `d3d12.h:5328` | -| 10 | `0x050` | `Signal` | `d3d12.h:5332` | - -`ID3D12Fence1` (`d3d12.h:5477`) adds `GetCreationFlags` at slot 11 (`d3d12.h:5480`), for 12 -slots total. The console runtime's exported IID table stops at `IID_ID3D12Fence1` and -`IID_ID3D12GraphicsCommandList2`; that is a property of the **exported IID set**, not a bound on -the interfaces the game uses ([`d3d12_xs_surface.md §2.4`](d3d12_xs_surface.md)). - -### 2.3 `ID3D12GraphicsCommandList` and 1–8 - -`ID3D12GraphicsCommandList` is declared at `d3d12.h:6337`. Its own methods occupy slots 9–59 -(51 methods), after `IUnknown` (3), `ID3D12Object` (4), `ID3D12DeviceChild` (1) and -`ID3D12CommandList` (1). The chain then grows as follows: - -| Interface | Own slots | Total slots | Last byte offset | SDK line | -|---|---|---:|---:|---| -| `ID3D12GraphicsCommandList` | 9–59 | 60 | `0x1d8` | `d3d12.h:6337` | -| `ID3D12GraphicsCommandList1` | 60–65 | 66 | `0x208` | `d3d12.h:7216` | -| `ID3D12GraphicsCommandList2` | 66 | 67 | `0x210` | `d3d12.h:7982` | -| `ID3D12GraphicsCommandList3` | 67 | 68 | `0x218` | `d3d12.h:20165` | -| `ID3D12GraphicsCommandList4` | 68–76 | 77 | `0x260` | `d3d12.h:21255` | -| `ID3D12GraphicsCommandList5` | 77–78 | 79 | `0x270` | `d3d12.h:30275` | -| `ID3D12GraphicsCommandList6` | 79 | 80 | `0x278` | `d3d12.h:31123` | -| `ID3D12GraphicsCommandList7` | 80 | 81 | `0x280` | `d3d12.h:31965` | -| `ID3D12GraphicsCommandList8` | 81 | 82 | `0x288` | `d3d12.h:32816` | - -The methods that matter for this page: - -| Slot | Byte offset | Method | SDK line | -|---:|---:|---|---| -| 9 | `0x048` | `Close` | `d3d12.h:6340` | -| 10 | `0x050` | `Reset` | `d3d12.h:6342` | -| 14 | `0x070` | `Dispatch` | `d3d12.h:6362` | -| 25 | `0x0c8` | `SetPipelineState` | `d3d12.h:6418` | -| 26 | `0x0d0` | `ResourceBarrier` | `d3d12.h:6421` | -| 33 | `0x108` | `SetComputeRoot32BitConstant` | `d3d12.h:6446` | -| 39 | `0x138` | `SetComputeRootShaderResourceView` | `d3d12.h:6476` | -| 45 | `0x168` | `SOSetTargets` | `d3d12.h:6500` | -| 59 | `0x1d8` | `ExecuteIndirect` | `d3d12.h:6580` | -| 68 | `0x220` | `GCL4::BeginRenderPass` | `d3d12.h:21258` | -| 69 | `0x228` | `GCL4::EndRenderPass` | `d3d12.h:21264` | -| 72 | `0x240` | `GCL4::BuildRaytracingAccelerationStructure` | `d3d12.h:21276` | -| 73 | `0x248` | `GCL4::EmitRaytracingAccelerationStructurePostbuildInfo` | `d3d12.h:21281` | -| 74 | `0x250` | `GCL4::CopyRaytracingAccelerationStructure` | `d3d12.h:21286` | -| 75 | `0x258` | `GCL4::SetPipelineState1` | `d3d12.h:21291` | -| 76 | `0x260` | `GCL4::DispatchRays` | `d3d12.h:21294` | -| 79 | `0x278` | `GCL6::DispatchMesh` | `d3d12.h:31126` | -| 80 | `0x280` | `GCL7::Barrier` (enhanced barriers) | `d3d12.h:31968` | -| 81 | `0x288` | `GCL8::OMSetFrontAndBackStencilRef` | `d3d12.h:32819` | - -**Not a bound on the game.** The console runtime's 93 GUID exports include only -`IID_ID3D12GraphicsCommandList`, `…1`, `…2`; the shipped BVH builder names `…4`, `…6` and `…8` -in its exported signatures (section 3.1). The export table's IID set is therefore not the game's -interface set, a point already made in [`d3d12_xs_surface.md §2.4`](d3d12_xs_surface.md). - -## 3. Direct measurements from the shipped binaries - -### 3.1 `XboxBvhBuilder.dll`'s interface types - -`XboxBvhBuilder.dll` is 884,224 bytes, PE32+ x86-64, with 12 named exports (ordinals 1–12). -The mangled export names are direct evidence of the C++ parameter types the DLL was compiled -against; no symbols were guessed. The relevant exports: - -| Ordinal | RVA | Export (demangled shape) | Interface named | -|---:|---:|---|---| -| 1 | `0x21330` | `XboxBvhBuilder(ID3D12Device11*, bool)` | `ID3D12Device11` | -| 3 | `0x21610` | `BuildRaytracingAccelerationStructure(ID3D12GraphicsCommandList4*, const D3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_DESC*, UINT, const D3D12_RAYTRACING_ACCELERATION_STRUCTURE_POSTBUILD_INFO_DESC*)` | GCL4 | -| 4 | `0x216a0` | `BuildRaytracingAccelerationStructureBatched2X(ID3D12GraphicsCommandList6*, UINT, const D3D12XBOX_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_BATCHED_DESC2*)` | GCL6 | -| 5 | `0x21980` | `CopyRaytracingAccelerationStructure(ID3D12GraphicsCommandList4*, UINT64, UINT64, D3D12_RAYTRACING_ACCELERATION_STRUCTURE_COPY_MODE)` | GCL4 | -| 6 | `0x21b40` | `CpuValidateResultX(ID3D12GraphicsCommandList4*, const D3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_DESC*)` | GCL4 | -| 8 | `0x219d0` | `RehydrateRaytracingAccelerationStructureBatched2X(ID3D12GraphicsCommandList8*, UINT, const D3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_DESC*, const UINT64*)` | GCL8 | -| 9 | `0x219a0` | `RehydrateRaytracingAccelerationStructureBatchedX(ID3D12GraphicsCommandList8*, UINT, const D3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_DESC*)` | GCL8 | -| 10 | `0x219f0` | `RehydrateRaytracingAccelerationStructureX(ID3D12Device11*, const D3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_DESC*)` | `ID3D12Device11` | - -The DLL imports only `d3d12_xs.dll!D3D12SerializeVersionedRootSignature` and -`xmem.dll!XMemVirtualQuery`; it does not import a queue, list, fence or allocator function. -This is the same import result recorded in -[d3d12_vulkan.md Appendix A.2](d3d12_vulkan.md), re-measured here. - -**What this proves:** the helper's public signatures require GCL4, GCL6, GCL8 and Device11 -objects. **What this does not prove:** that the helper calls the public vtable slots for those -interfaces. Section 3.3 measures the call sites. - -### 3.2 The shipped modules do not contain the command-object IIDs - -A byte scan for the 80 `IID_ID3D12*` values defined by the installed `d3d12.h`, plus the two -console GUIDs recorded in [`d3d12_xs_surface.md §4`](d3d12_xs_surface.md), found: - -| Binary | IIDs found | -|---|---| -| `XboxBvhBuilder.dll` | `IID_ID3D12RootSignature` at `0xc9ee8`, `IID_ID3D12PipelineState` at `0xc9ed8` | -| `amd_fidelityfx_upscaler_xbox.dll` | `IID_ID3D12Device` `0x472f0`, `IID_ID3D12Resource` `0x47310`, `IID_ID3D12RootSignatureDeserializer` `0x47320`, `IID_ID3D12PipelineState` `0x47330`, `IID_ID3D12Heap` `0x47340`, `IID_ID3D12RootSignature` `0x47350`, `IID_ID3D12DescriptorHeap` `0x472e0`, `IID_ID3D12CommandSignature` `0x47300` | -| the other 14 DLLs | none of the scanned IIDs | - -No shipped module contains `IID_ID3D12CommandQueue`, `IID_ID3D12GraphicsCommandList` (any -version), `IID_ID3D12Fence`/`Fence1`, `IID_ID3D12CommandAllocator` or -`IID_ID3D12ConsDmaCommandList`. The helper receives command lists through its exported -parameters; the corresponding IID constants are not in its own data. That is a fact about the -shipped modules, not a claim that the game never queries for them. - -The `GraphicsCommandList` ASCII string occurs 30 times in `XboxBvhBuilder.dll` (type/debug -names); `PresentX` does not occur in any of the 16 DLLs. - - -### 3.2a No shipped module passes an unknown GUID at a call site - -Section 3.2's byte scan can only recognise *known* IIDs; a console-only GUID (the four list IIDs of -[`d3d12_xs_surface.md §4`](d3d12_xs_surface.md)) would scan as anonymous data. The call-site scan closes -that hole: `tools/d3d12_guid_sites.py` enumerates every 16-byte constant a module's code can name — -RIP-relative `lea` targets in data sections, absolute pointers stored in data, two adjacent -`movabs` immediates that inline a GUID without a constant pool, and `mov reg, [rip+...]` loads -through import slots (a GUID imported as data) — and reports which are GUID-shaped. Over all 16 -modules of the 1.0.2.1 package: - -| Binary | GUID-shaped constants the code references | -|---|---| -| `XboxBvhBuilder.dll` | 2: `IID_ID3D12RootSignature`, `IID_ID3D12PipelineState` (the same pair as §3.2) | -| `amd_fidelityfx_upscaler_xbox.dll` | 8: the §3.2 set, nothing else | -| `amd_fidelityfx_loader_xbox.dll` | 0 | -| the other 13 modules | 0–44 GUIDs each (six have none); where present they are HTTP, WinRT and CRT interfaces — none of these modules imports `d3d12_xs.dll`, so none can call D3D12 at all | - -No module loads a GUID through an import slot, and no `movabs` pair inlines one. As a control, the -upscaler's single `IID_ID3D12Device` reference (rva `0x482f0`) is the IID of a real slot-0 -`QueryInterface` call (`(this, &IID, &out)`, decompiled at rva `0xde66`). So the only -interfaces any shipped module can name at a `QueryInterface` or a creation call are the ten it -already uses; a console compute/copy list IID cannot appear in the package, statically, in any -form. The same scan looks for code-referenced static `D3D12_COMMAND_QUEUE_DESC` windows -`{Type, Priority, Flags, NodeMask}`: 10 windows in 3 modules survive the shape filter, every one with -`Type` 1 — a PC enum value — and all of them offset tables read by stride arithmetic, not queue -descriptions (checked by decompiling the referencing function of the upscaler's six). None has a -value past `VIDEO_DECODE` (4), so the DMA type's numeric value has no static source in the package -either. - -Reproduce: `python -I tools/d3d12_guid_sites.py /*.dll --known -IID_ID3D12ConsDmaCommandList=30bc77b9-8379-4b25-95de-b8588c42275d` (prints GUID values and counts -only). The four list IIDs and the DMA type remain reachable only through the running title, as -[`d3d12_xs_surface.md §4`](d3d12_xs_surface.md) already requires for the IIDs. - -### 3.3 The BVH builder's command-list call sites - -The exported `BuildRaytracingAccelerationStructure` (ordinal 3, RVA `0x21610`) copies the input -description into a stack structure and **delegates to ordinal 4** -(`BuildRaytracingAccelerationStructureBatched2X`) at RVA `0x2166d`, passing the same command-list -pointer in RDX and a count of 1. The batched entry therefore carries both the non-batched and the -batched paths. - -Disassembling the exported bodies and the functions they call directly gives these calls through -the object received in the command-list parameter: - -The console list is not in PC order past slot 26 (section 3.5a), so the method column reads each call in the -console order, from the arguments at the call and from the inline write it falls back from (section 3.5a, last -paragraph). Every call below except the two barriers is the fallback branch of an inline write of the same values. - -| RVA | Vtable offset | Console slot → PC method | Observed arguments | Confidence | -|---:|---:|---|---|---| -| `0x2171e` | `+0xd0` | 26 → 26 `ResourceBarrier` | `NumBarriers=1`, `&{Type=2 (UAV), Flags=0, pResource=null}` | **Measured**: the shape is a global UAV barrier; slot 26 is the SDK `ResourceBarrier`; the site is gated (section 3.3b), so the call never fires in the shipping DLL | -| `0x1d9cb` | `+0x70` | 14 → 14 `Dispatch` | `(1, 1, 1)` | **Measured**: exact `Dispatch` shape | -| `0x1d85e` | `+0xc8` | 25 → 25 `SetPipelineState` | `RCX=list`, `RDX=[rdi+8]`: loaded at `0x1d7fa` and not changed before the call; the inline branch (`0x1d822`–`0x1d850`) copies 28 bytes from that object's `+0x10` | **Measured**: RDX is the pipeline the inline branch reads | -| `0x1d7f4` | `+0x108` | 33 → 29 `SetComputeRootSignature` | one argument, `RDX=[rcx]`: the pointer stored next to the pipeline (`[rdi]`; the pipeline is `[rdi+8]`) | **Measured** shape; agrees with slot 33 in section 3.5a | -| `0x1d8b9` | `+0x138` | 39 → 35 `SetComputeRoot32BitConstants` | `(3, 1, &value, offset)`: `EDX=3`, `R8D=EDX-2=1`, `R9=rsp+0x30`, fifth argument `EDI` | **Measured**: four arguments with a count and a source pointer; a root SRV takes two | -| `0x1d956` | `+0x138` | 39 → 35 `SetComputeRoot32BitConstants` | `(3, count, source, offset)`: `R8D=EDI` (the count of the inline copy loop above it), `R9=RSI` | **Measured** | -| `0x1d8f9` | `+0x168` | 45 → 41 `SetComputeRootUnorderedAccessView` | `(0, VA)`: `EDX=0`, `R8=RBP`; the inline branch writes a header word and the same 64-bit `RBP` (12 bytes) | **Measured**: a root index and a 64-bit address | -| `0x1da02` | `+0x490` | 146 → GCL7 80 `Barrier` | `(1, &group)`, group `{Type=0, NumBarriers=1, pGlobalBarriers}`; the barrier is the 16 bytes at RVA `0xcdf60`: `{0x80, 0x80, 0x10, 0x10}` | **Measured**: the public `Barrier(UINT32, const D3D12_BARRIER_GROUP*)` shape with public enum values | - -The `+0x490` call is after the `Dispatch(1,1,1)` at `0x1d9cb`, in the per-descriptor path. It is -**beyond the last public GCL8 slot** (slot 81 is `0x288`), but its arguments are the public enhanced-barrier -call: one `D3D12_BARRIER_GROUP` of type `D3D12_BARRIER_TYPE_GLOBAL` (0) holding one `D3D12_GLOBAL_BARRIER` with -`SyncBefore = SyncAfter = D3D12_BARRIER_SYNC_COMPUTE_SHADING` (`0x80`) and -`AccessBefore = AccessAfter = D3D12_BARRIER_ACCESS_UNORDERED_ACCESS` (`0x10`), values as in SDK 10.0.26100 -`d3d12.h`. The public PC equivalent is GCL7 slot 80. - -@MoonYueya's static enumeration of the Xbox Series 1.0.2.1 builder found 29 calls through console slot 146 -across seven functions. It counted 11 direct calls through the vtable entry and 18 calls through a register -loaded from that entry. All 29 passed one global barrier group containing one `D3D12_GLOBAL_BARRIER` with -the same compute-shading and unordered-access arguments described above. The counts cover the two -enumerated dispatch forms in the builder's `.text`. [Static corroboration and coverage details](https://github.com/ItsNotRexed/Leonida/issues/1626) - -The same two inner functions (`0x1d540` and `0x1d7c0`) contain the `+0x70`, `+0xc8`, `+0x108`, -`+0x138`, `+0x168` and `+0x490` calls; the outer batched function contains the `+0xd0` barrier. -The exported `CopyRaytracingAccelerationStructure` (ordinal 5) and the rehydrate exports -(ordinals 8–9) do not call the passed command list in their exported bodies; they forward to -internal functions using objects cached in the builder (`[this+0x10]` and `[this+8]`). Their -signatures still require GCL4/GCL8 objects, but those bodies do not measure command-list slots. - -### 3.3a Other builder call sites past the PC order - -The rest of `.text` has further calls through the list pointer. The table shows examples, including one of the -slot-146 sites counted in section 3.3. Each name rests on the call shape. “Inline” means the call is the fallback -of an inline write of the same values. - -| RVA | Vtable offset | Console slot → PC method | Observed arguments | Confidence | -|---:|---:|---|---|---| -| `0x1a1e9` | `+0x128` | 37 → 33 `SetComputeRoot32BitConstant` | `(2, value, 0)`: `EDX=R9D+2`, `R9D=0` (inline: header + one dword) | **Measured** shape | -| `0x14e81` | `+0x138` | 39 → 35 `SetComputeRoot32BitConstants` | `(0, 19, rsp+0xc0, 0)` (inline: header + 19 dwords) | **Measured** shape | -| `0x14e11` | `+0x158` | 43 → 39 `SetComputeRootShaderResourceView` | `(3, VA)`: `EDX=3`, `R8=R13` (inline: header + the 64-bit `R13`) | **Measured** shape | -| `0x1a3b0` | `+0x168` | 45 → 41 `SetComputeRootUnorderedAccessView` | `(0, VA)` (inline: header + a 64-bit value) | **Measured** shape | -| `0x20ed6` | `+0x4a0` | 148 → none | `(list, count * 40, 16)` returns a pointer; on null the DLL prints `D3D12 XDXR Error: Failed to allocate upload buffer` and throws `E_FAIL` | **Measured**: an upload allocator `(size, alignment)` | -| `0x20f99` | `+0x158` | 43 → 39 `SetComputeRootShaderResourceView` | `(0, p)`, `p` the pointer slot 148 returned at `0x20ed6`, unchanged | **Measured**: the CPU pointer is used as the GPU address | -| `0x149ba` | `+0x280` | 80 → none | `(x, 1, 1, 0x8020)`: `EDX=EDI`, `R8D=R9D=1`, fifth argument `0x8020` (inline: the five-dword packet `0x4003cc00, x, 1, 1, W` of section 3.5a; the calls at `0x1525d` and `0x153b4` pass `0x20`, the one at `0x1d047` `0x8020`) | Inferred: a `Dispatch` with one extra word | -| `0xd6de` | `+0x238` | 71 → none | `(&label, counter, 0 or 0x1000, 0)`: the counter at `[rbx+0x9c]` is incremented first; `0x1000` on the last item of a batch | Inferred: a GPU write of a 32-bit value to memory | -| `0xd679` | `+0x248` | 73 → none | `(&label, 3, reference, 0xffffffff, 0)` | Inferred: a GPU wait until the masked value compares (function 3) with the reference | -| `0xd7b4` | `+0x490` | 146 → GCL7 80 `Barrier` | the same global UAV barrier as `0x1da02` | **Measured** | - -So the compute root-binding group keeps its PC order four slots later (33, 37, 39, 43 and 45 here; 35 and 41 in -section 3.5a), and the console list has methods well past the PC tail: 71, 73, 80, 146 and 148 here, 141 in the -FSR DLL. - -Slot 148 matters beyond the builder: the address it returns is written by the CPU and passed unchanged to the GPU -as a root SRV address, so console upload memory has the same address for the CPU and the GPU. A replacement must -return memory whose CPU pointer is also a valid GPU address (for this layer: inside the arena of -[d3d12_vulkan.md §3.3](d3d12_vulkan.md)). - -The function at `0xd580` uses the 71/73 pair instead of the slot-146 barrier when the byte at RVA `0xd773c` is set. -That byte is one of seven bools at `0xd7738`–`0xd773e` in zero-initialised `.bss`. The only accesses to them in -`.text` are about 50 RIP-relative reads (`cmp`, `movzx`); there is no write and no export that points there. So in -the shipping DLL the label path is unreachable unless something writes that byte through a computed pointer, and -the barrier path is the one that runs. - -### 3.3b The batched build validates the geometry descriptors on the CPU first - -A logging-proxy harness (section 7, item 1) never reached the first list-vtable call: both runs of the -batched export faulted at RVA `0x142d3`, before the object received in the command-list parameter was -touched once. The reason is a CPU-side validation of the build items that the section 7 descriptor -guidance did not cover. The batched entry (`0x216a0`) reaches it through `0xe6a0` (call at `0x216dc`), -the packet processor `0xcc00` (call at `0xe781`) and a per-record validator at `0x14270` (call at -`0xce18`; a second call site exists at `0x11c25`). The processor walks the batched descriptor's 80-byte -build items (item `i` at descriptor `+ i*0x50`) and routes each by the dword at its `+0x08` — the -pointer's `+0x00` at the validator: kind 1 reaches the validator, kind 0 goes through `0xc820`/`0xc780` -instead, other values take an error path (`0xd52f`). The validator reads, from the pointer it receives -(all **measured** in the static disassembly): - -| Offset | Field | Check | -|---:|---|---| -| `+0x08` | descriptor count | loop bound | -| `+0x0c` | elements layout (`D3D12_ELEMENTS_LAYOUT`) | 0 = inline array of 0x38-byte records, 1 = array of pointers to records; other values print `D3D12 XDXR Error: Unexpected value for D3D12_ELEMENTS_LAYOUT` and throw `E_INVALIDARG` | -| `+0x10` | descriptor base | mode 0: record `i` at `base + i*0x38`; mode 1: record `i` at `[base + i*8]` | -| record `+0x00` | geometry type (`D3D12_RAYTRACING_GEOMETRY_TYPE`) | 0 = triangles, 1 = AABBs; others print `D3D12 XDXR Error: Unrecognized D3D12_RAYTRACING_GEOMETRY_TYPE` and throw `E_INVALIDARG` | -| record `+0x08` | AABB count (type 1) | accumulated | -| record `+0x10` | index format (type 0) | at most `0x39` and in the bitset `0x0220040000000000` — `DXGI_FORMAT_R32_UINT` (42), `DXGI_FORMAT_R16_TYPELESS` (53), `DXGI_FORMAT_R16_UINT` (57); others print `D3D12 XDXR Error: Unsupported index buffer format provided` and throw `E_NOTIMPL` | -| record `+0x18` | index count (type 0, format ≠ 0) | exact multiple of 3; otherwise prints `D3D12 XDXR Error: Triangle index count must be a multiple of 3 when an index buffer is provided` and throws `E_INVALIDARG` | -| record `+0x1c` | vertex count (type 0, format = 0) | checked instead of the index count, also an exact multiple of 3; otherwise prints `D3D12 XDXR Error: Triangle vertex count must be a multiple of 3 when no index buffer is provided` and throws `E_INVALIDARG` | - -The fault that stopped the dynamic runs is the base dereference itself: at `0x142d3` (`mov ecx,[rdx]`, -`rdx = base + i*0x38` in the inline mode) the record's type word is read with a CPU load, so a descriptor -whose base is a GPU address that is not CPU-readable faults there. For a replacement runtime this is a -measured host-side contract: the geometry descriptors must be backed by CPU-readable memory, not only by -the GPU arena. The validator returns the summed primitive count (the triangle counts ÷ 3 plus the AABB -counts), which the packet processor stores (`0xce1d`). It reads nothing past record `+0x1f`; what the -`+0x20..+0x37` tail of a record is used for is open — the dynamic runs stopped at the first record read. - -The same static pass settles what the first list calls would have been, and finds that three of the sites -section 3.3 and 3.3a list or miss are gated by the zero-initialised bytes of section 3.3a, so in the -shipping DLL they never run: - -- The `+0xd0` `ResourceBarrier` at `0x2171e` (section 3.3) needs a non-zero item count (`0x216e1`) and the - byte at `0xd773c` (`0x216e9`). Its shape stays as measured; in the shipping DLL the call never fires. -- Slot 90 (`+0x2d0`, call at `0xe836`) is new — it is not in the section 3.3a tail list. Its shape is - `(list, p, 0, last)`: `RDX = [item+0x28] + [item+0x54]*4`, where `item` is one 160-byte element of the - processor's output array, selected through the dword array beside it, `R9 = 1` on the last iteration, - and the element's dword at `+0x9c` is cleared first. The loop is behind the same `0xd773c` byte - (`0xe7d0`) and the count check, so it does not run in the shipping DLL either. -- The direct slot-146 barrier at `0xea99` is behind the adjacent byte `0xd773b` (`0xea41`, after the - per-item callback reports true); the wrapper calls at `0xebbb`, `0xec79`, `0xed37` and `0xee17` are not - gated by these bytes, and each ends in the measured slot-146 global UAV barrier (section 3.3a). - -The path also reads one byte past the seven bools of section 3.3a: `0xd773f` at `0xce3f` and `0x11c35`. -A linear sweep of `.text` finds no writes to `0xd7738`–`0xd773f` (only `cmp`/`movzx` reads; the two `lea` -sites take the address of `0xd7740`, one past the last byte), so the read-only range is eight bytes. - -With the gated sites removed, the shipping-DLL order for one item is (measured with a postbuild-info -type of 2, which routes to the `0x1d7c0` worker): the validation above → slot 146 four times through -the `0xd580` wrapper → the upload function `0x20ea0` (called at `0xee85`; a second site at `0xf0f9`): -slot 148 for `count * 40` bytes at alignment 16 (`0x20ed6`; the size is -`lea edx,[rsi+rsi*4]; shl edx,3`), root signature (33), pipeline (25, or its inline write), the -slot-148 pointer as root SRV (43, or inline), the count as a 32-bit root constant (37), and -`Dispatch((count+31)/32, 1, 1)` (`0x21054`, or its inline four-word packet) — then the per-entry -worker `0x1d7c0` (called at `0x217d0`) whose sequence section 3.3 lists, ending in the slot-146 -barrier at `0x1da02`. Postbuild-info types 0 and 3 route to the mirrored worker `0x1d540` (called at -`0x217e2`). Slot 148 is therefore asked before the per-entry dispatch, and the first dispatch on the -path is the upload function's own — the two refinements to section 7's prediction. The `+0x490` barrier -arguments (one global UAV group `{0x80, 0x80, 0x10, 0x10}`) and slot 148's `count * 40`/16 are confirmed -by both passes (D3D-293's static disassembly and this section's independent iced-x86 re-check). - -### 3.4 The object is wider than the public vtable - -The inner function at `0x1d7c0` receives the command-list pointer in RDX, copies it to RBX -(`0x1d7da`–`0x1d7dd`), and then does more than call public methods: - -- writes 32 bytes at `[rbx+0x544]` (`0x1d803`, `0x1d810`: the pipeline object's `+0x10`..`+0x2f`); -- writes a byte at `[rbx+0x140]` (`0x1d841`, `0x1d884`); -- reads `[rbx+0x350]` (`0x1d877`) and `[rbx+0x344]` (`0x1d8c9`); -- maintains a pointer at `[rbx+0x18]` against limits at `[rbx+0x30]` (`0x1d818`, `0x1d871`); -- calls a method at vtable offset `+0x490` (`0x1da02`), past the end of the public GCL8 chain. - -A client that knows only the public COM interface cannot legally read or write those fields. -The helper is therefore compiled against a **wider contract** than the public vtable: either the -Xbox command-list object is an internal class whose layout first-party code may use, or the game -passes a builder-specific object that also implements the interface. Section 3.5a explains most of the fields -(the inline command buffer), and section 3.3 identifies `+0x490` as `Barrier` at console slot 146. - -This is the most important compatibility finding on this page. A replacement command list that -implements only the public GCL7/GCL8 vtable is **not** safe to hand to `XboxBvhBuilder`'s build path. (Section 3.5a -shows it is not safe for console-compiled callers' public calls either: the console list order differs from the PC -order past slot 26.) The helper will touch fields the public -object does not define and call `+0x490` (console slot 146, `Barrier`), which a public-only vtable does not have. - -### 3.5a The FSR DLL as a second device client - -`amd_fidelityfx_upscaler_xbox.dll` is a second shipped module compiled against the console device, the second -measured client of the console **command list** after the BVH builder (section 3.3), and the first one run. It is run -by `fsr_dispatch_test` with its measured Xbox backend -descriptor ([d3d12_vulkan.md Appendix A.3](d3d12_vulkan.md)), on a PC device behind the Xbox-ABI proxy, and its -command recorder (RVA `0x59a0`) was read with Ghidra 12.2 through REA. RVAs are from image base `0x180000000`. The -run's command-list calls are the same 13, in the same order, on an RTX 2000 Ada (driver 597.06) and on WARP. - -**Device.** At context creation it calls slots 14, 15, 18, 19, 27, 38 and 76 and heap slot 9, all with the shapes the -PC order and the measured overrides predict; slot 76 takes the seven `CreateCommittedResource` arguments. During -`ffxDispatch` it adds 16 `CreateRootSignature` and heap slot 10 (the recorder also has a path that calls 24 -`CopyDescriptorsSimple`, not taken in this run), plus its two compute-pipeline paths below. - -Which descriptor-copy path runs is decided by a **byte at `+0x18` of the device object**, read before each copy at -`0x5bb8`, `0x5dd1`, `0x5f8c` and `0x617e`. When it is 0 (the run), the DLL copies the 32 bytes at the source CPU -handle to the destination CPU handle itself (two 16-byte moves, e.g. `0x5bc0`–`0x5bce`), so CPU descriptor handles -must be pointers to at least 32 writable bytes. When it is set, the same copy is device slot 24, -`CopyDescriptorsSimple(1, dst, src, 0)` (calls at `0x5bed`, `0x5e06`, `0x5fc2`, `0x61b3`). A device proxy that sets -that byte therefore sees this DLL's descriptor copies as calls. Like the list's fields (below), the byte is past the -vtable pointer of a public object. - -- **Slot 67** (call at `0x56d9`) is **not** the PC `CreateProtectedResourceSession1`: it takes `(desc, riid, out)` - with `IID_ID3D12PipelineState`. The DLL's own messages name it `DeserializeComputePipelineStateX`. Its desc is the - root signature at `+0x00`, then pointer and size pairs for the shader's `FSPX` entries: kind 0 at `+0x08`, kind 1 - at `+0x18`, a copy of the kind-6 program at `+0x28` with its exact size at `+0x30`, and kind 7 at `+0x38` - ([fspx.md](fspx.md)). The proxy maps the console desc to `D3D12_COMPUTE_PIPELINE_STATE_DESC` and routes it to - `CreateComputePipelineState` (PC slot 11). On a PC device that call fails (`E_FAIL`) because the code is not a PC - shader, so the DLL falls back to slot 62; its message for that failure calls the fallback "NewBE". With kind 0 in - the description (always, from this DLL) the proxy passes all four pairs on as one `FSPX` payload, checking each pair - before reading it. The Vulkan device then finds the translated module by `fspx_code_sha256` and `fspx_state_sha256` - ([fspx.md](fspx.md), "Build and run-time lookup"), for the programs the build translated. - - **The layout is pinned from the DLL's code:** its FSPX reader (`0x1a20`), the same loop inline for a container, - and the copy into the description. The kind 0 and kind 6 of one call come from the same payload. With the - reader run on all 29 programs, every translated program resolves to its own entry ([fspx.md](fspx.md), "How - the table was pinned"). - - **A failed call is logged with its number** (`slot 67 call N failed`). The DLL creates its pipelines one after - another, so a miss is not necessarily the first call's. -- **Slot 62** (call at `0x5825`) takes the measured `(D3D12_COMPUTE_PIPELINE_STATE_DESC*, 0, 0, riid, out)`. The PC - runtime refuses the DLL's code (`E_FAIL`): it is not a PC shader. The DLL's pipeline function then returns - `0x8000000d` (`0x4b85`), but the dispatch goes on, records the null pipeline and faults (`0x65ff`), which is where a - PC device stops. The Vulkan device (`LEONIDA_D3D12=vulkan`) takes the container: it hashes the kind-6 bytes of the - `ACCC` part and creates the pipeline from the translated module, for the programs the build translated; others, - and a malformed `FSPX` directory, are refused with `E_INVALIDARG`. -- **Pipeline slot 11 sizes the compute scratch.** After either path succeeds (slot 67 jumps to `0x5833`), the DLL - calls the new pipeline's slot 11 as `(0, 0, &obj)` (`0x586d`); the public `ID3D12PipelineState` ends at slot 8, so - this is a console-only method. On success it reads a dword through `obj`'s slot 3 (`0x5881`), multiplies it by - 1024 (`shl ecx, 0xa`), stores it in the pipeline's record at `+0x44` and releases `obj` (slot 2). The context keeps - the largest value (`+0x10f8`). Before a dispatch whose pipeline has a non-zero value (`0x64d3`; zero skips the - binding), the DLL creates the scratch buffer once, `largest * 0xd0` bytes rounded up to 64 KiB, through device - slot 27 in state `UNORDERED_ACCESS` (`0x65ab`), names it `FFX_XBox_ComputeScratch`, and binds it with list slot - 141 `(2, GPU VA, buffer size, this pipeline's value)` (`0x65f8`). Measured: the calls and the arithmetic. - - **Failure and zero (measured, `0x585c` to `0x58b1`).** The value at `+0x44` is set to 0 before the call. A failed - HRESULT or a null `obj` skips to the function's success return with the value still 0, so pipeline creation does - not depend on slot 11. At dispatch a value of 0 skips both the scratch buffer and list slot 141 (`0x64d6`). - - **The object (measured shape, hypothesis about its type).** Slot 3 is called with no arguments and its result is - read as a pointer to the dword; slot 2 releases it. That is the shape of `ID3DBlob::GetBufferPointer` and - `Release`. - - **No per-program size (measured on the 29 programs).** `COMPUTE_PGM_RSRC2.SCRATCH_EN` is clear in all 29, no - program has a `scratch_*` or `flat_scratch` instruction, and kind-0 words 0, 1 and 2 are each one value across - all 29. - - **Implemented.** The Vulkan device's pipeline answers slot 11 with a blob holding 0; console slots 9 and 10 - return `E_NOTIMPL`. A translated module keeps its private data in SPIR-V, not in a console scratch buffer. - - **Open.** What the console returns there for these programs, the unit of the dword (the factor 1024 suggests - KiB), the meaning of `0xd0`, and of the leading `2`. -- The DLL's 29 shaders are `DXBC` containers with `SFI0`, `ISG1`, `OSG1`, `PSV0`, `RTS0`, `HASH` and `ACCC` parts - and no `DXIL`. The `ACCC` payload starts with the tag `FSPX` in all 29; the game's own native shaders are `FSSM` - inside `XBCH` ([design.md](design.md)). `FSPX` is a directory around an uncompressed RDNA2 program and its - dispatch state; `tools/fspx_unpack.py` unpacks it for the translator, which takes 17 of the 29 today, and - `make_game.py`'s `shaders` stage does both for the package's DLL. What stops the other 12 is listed in - [fspx.md](fspx.md), "Translation status". - -**Command list.** The console list is **not** the PC order past `ResourceBarrier`. Each row is backed by the -argument shape at the call and, where marked "run", by the call seen in the run. Rows marked "inferred" fit the -shape and the shift around them, but the shape alone does not single the method out: - -| Console slot (offset) | PC slot | Method | Evidence | -|---|---|---|---| -| 14 (`+0x70`) | 14 | `Dispatch` | the vtable path of the inline dispatch at `0x59a0`; the BVH builder's `Dispatch(1,1,1)` at `+0x70` | -| 15 (`+0x78`) | 15 | `CopyBufferRegion` | run: `(resource, 0, resource, …)` | -| 25 (`+0xc8`) | 25 | `SetPipelineState` | `(pipeline)` at `0x59a0` | -| 26 (`+0xd0`) | 26 | `ResourceBarrier` | run: `(1, barriers)`; the BVH builder's `+0xd0` | -| 32 (`+0x100`) | **28** | `SetDescriptorHeaps` | run: `(1, &heap)`, the heap a device-proxy descriptor heap | -| 33 (`+0x108`) | **29** | `SetComputeRootSignature` | one pointer argument, the first call at `0x59a0` (null in the run, where pipeline creation had failed); in the BVH builder the pointer stored next to the pipeline (section 3.3) | -| 35 (`+0x118`) | **31** | `SetComputeRootDescriptorTable` | `(index, heap GPU start + offset)` at `0x59a0` | -| 41 (`+0x148`) | **37** | `SetComputeRootConstantBufferView` (inferred) | `(index, 64-bit GPU VA from the constant allocator)` at `0x6738`; the root SRV/UAV setters take the same shape | -| 53 (`+0x1a8`) | **49** | `ClearUnorderedAccessViewUint` | run: `(GPU handle, CPU handle, resource, …)` | -| 54 (`+0x1b0`) | **50** | `ClearUnorderedAccessViewFloat` | `(GPU handle, CPU handle, resource, values, 0, null)` at `0x7296`; chosen over the slot-53 call at `0x72ee` by a compare of a local with `0x12` (`0x7266`), with the four values passed in place where the 53 path copies them to the stack | -| 55 (`+0x1b8`) | **51** | `DiscardResource` | `(resource, null)` at `0x6dcb`, after the pending barriers are flushed through slot 26 | -| 59 (`+0x1d8`) | — | console only (shape) | four calls, two shapes: `(1, blob, size)` at `0x6b5a` and `0x6d53`, the blob a run of qwords whose first is `0xf3080 \| (qword count & 0x7f)`; and `(0, &qword, 8)` with the qword 1 at `0x6e52` and `0x6eb8`, only when a profiling bit of the context is set (`0x6e2a`). The first argument is set as a byte (`mov dl, 1` / `xor edx, edx`). It looks like one slot for both ends of a GPU event; no public method takes a bool first. With 55 at +4 and 61 at +2, the two slots the console lacks are among 56–60 | -| 61 (`+0x1e8`) | **59** | `ExecuteIndirect` | `(signature, 1, argument buffer, offset, null, 0)` at `0x59a0` | -| 85 (`+0x2a8`) | — | `CopyTextureRegion` shape (inferred) | run: `(stack pointer, 0, 0)`, twice per dispatch. Statically six arguments, `(&dst, 0, 0, 0, &src, null)`: the public `CopyTextureRegion` (PC 16) with two `D3D12_TEXTURE_COPY_LOCATION`s, not one pointer. At `0x7147` dst is `{texture, SUBRESOURCE_INDEX, 0}` and src `{buffer, PLACED_FOOTPRINT, footprint}`, the footprint from device slot 38 (`GetCopyableFootprints`, `0x708b`); at `0x7191` both are subresource 0 (texture to texture). The caller also clears the next stack argument (`0x70e7`); whether the method takes a seventh is open, as is what console slot 16 is | -| 141 (`+0x468`) | — | console only | `(2, GPU VA, size, n)` at `0x65f8`: binds a buffer the DLL names `FFX_XBox_ComputeScratch`; `n` is the bound pipeline's scratch value from pipeline slot 11 (see above) | - -So the console list has four more methods than the PC list between `ResourceBarrier` (26) and `SetDescriptorHeaps` -(console 32), and two fewer between `ClearUnorderedAccessViewUint` (console 53) and `ExecuteIndirect` (console 61). -Mapping the console list as "PC plus a constant" is wrong. The BVH builder adds 37, 39, 43 and 45 (the rest of the -+4 root group) and the console-only 71, 73, 80, 146 (`Barrier`) and 148 (sections 3.3 and 3.3a). - -**The list object is wider than its vtable, and this is what that width is for.** Before a root-argument or dispatch -call the DLL checks a write cursor at `+0x18` against a limit (`+0x30` for root arguments, `+0x28` for a dispatch). While there is room, -it writes the command into that buffer itself instead of calling: a root argument is a header word from the -per-root-parameter table at `+0x344` and then the value (32 bits for a descriptor table, 64 for the slot-41 GPU VA), -a dispatch four words (`0x4002c400`, or `(flag | 0x1000ba00) << 2`, then x, y, z). -The BVH builder also writes a five-word dispatch, `0x4003cc00, x, 1, 1, W`. -- **Sites:** `0x14972`, `0x15215`, `0x1536a` and `0x1d002`, each checked against the dispatch limit `+0x28`. The - cursor advances 20 bytes and the flag byte at `+0x140` is cleared. -- **It is the inline form of console slot 80** (section 3.3a). When the buffer is full, each site calls slot 80 - (`+0x280`) instead, as `(x, 1, 1, W)` with the same `W`. -- **`W` is `0x8020`** at `0x14972` and `0x1d002`, and **`0x20`** at `0x15215` and `0x1536a`. What bit 15 selects is - open. - -The FSR DLL never writes this form. -**Byte `+0x143` is console-runtime state:** the BVH builder reads it at 31 sites and the FSR DLL at one (all `cmp -byte ptr [reg+143h]`), but neither DLL writes it. Every store into `+0x140`..`+0x143` in either DLL is a byte store to -`+0x140` or `+0x141`, and no wider store reaches `+0x143`. A replacement list can leave it 0. -It sets a flag byte at `+0x140`, stores a flag at `+0x141` from the -pipeline, and copies 32 bytes of the pipeline object (from its `+0x10`) to `+0x544`. These are the fields -section 3.4 measured in the BVH builder's helper without a meaning (`+0x18`, `+0x30`, `+0x140`, `+0x344`, `+0x544`). -**With the cursor at the limit, every command goes through the vtable**: that is how `fsr_dispatch_test` records -them, and it is the simplest contract for a layer that does not want to decode these packets. Whether the game's -executable makes the same check before writing is unknown until it is available; it is compiled against the same -console headers. - -**Every inline write in the package's DLLs checks first.** `tools/inline_scan.py` finds each cursor store-back -(`mov [list+18h],reg` after stores through the cursor) and looks for the compare in front of it. On the 1.0.2.1 -DLLs (dumpbin 14.44 listings): - -| Image | Inline writes | Checked | Not checked | Limit compared | Fallback slot (sites) | -|---|---:|---:|---:|---|---| -| `XboxBvhBuilder.dll` | 196 | 196 | 0 | `+0x30` ×165, `+0x28` ×30, a register loaded in another block ×1 | 45 ×71, 37 ×35, 25 ×34, 14 ×24, 39 ×16, 43 ×9, 80 ×4; 3 reach theirs through a shared jump the tool does not follow | -| `amd_fidelityfx_upscaler_xbox.dll` | 9 | 9 | 0 | `+0x30` ×8, `+0x28` ×1 | 35 ×6, 25, 41, 14 | - -**Measured.** The packet headers it reads back are the two dispatch forms above: `0x4002c400` (26 four-word -dispatches in the builder, one in FSR) and `0x4003cc00` (the builder's four five-word ones). The other 14 DLLs have -no inline write, except one checked site in `libHttpClient.GDK.dll`, which imports nothing from D3D12: read a -result as an upper bound of about one site per image. Removing the compare and branch in front of the builder's -`0x14972` write turns exactly that site into "not checked", so a missing check is visible. - -On the executable, `python -I tools/inline_scan.py --sites` answers the question in one pass (see the day-one -list in `docs/design.md`): no unchecked site means a cursor-at-limit layer sees every command the game records; each -unchecked site is listed by RVA and is a write that layer never sees. Its fallback-slot line is the set of console -list methods the game reaches through the vtable. Limit offsets other than `+0x28`/`+0x30` would be command kinds -the DLLs never write (draws, input-assembler and output-merger state); read a few of those sites by hand. - -**The five-word dispatch.** The BVH builder also writes `0x4003cc00, x, 1, 1, W`: - -- **Sites:** `0x14972`, `0x15215`, `0x1536a` and `0x1d002`, each checked against the dispatch limit `+0x28`. The - cursor advances 20 bytes and the flag byte at `+0x140` is cleared. -- **Its vtable fallback is console slot 80** (section 3.3a), read from the code: when the buffer is full, each site - calls slot 80 (`+0x280`) instead, as `(x, 1, 1, W)` with the same `W` (`0x149ba`, `0x1525d`, `0x153b4`, `0x1d047`). - So the packet is slot 80's inline form; that slot 80 is a `Dispatch` with one extra word stays inferred. -- **`W` is `0x8020`** at `0x14972` and `0x1d002`, and **`0x20`** at `0x15215` and `0x1536a`. What bit 15 of `W` - selects is not known. - -The FSR DLL never writes this form. - -**Byte `+0x143` is console-runtime state:** the BVH builder reads it at 31 sites and the FSR DLL at one (all `cmp -byte ptr [reg+143h]`), but neither DLL writes it. Every store into `+0x140`..`+0x143` in either DLL is a byte store to -`+0x140` or `+0x141`, and no wider store reaches `+0x143`. A replacement list can leave it 0. - -**The root-argument header word** is the root parameter's table entry `table[root]` (`+0x344 + 4·root`), adjusted -only for root constants: - -- **Several 32-bit constants at once:** `table[root] + ((count − 1) << 16)`, then `count` dwords. Examples: - `+ 0x120000` for 19 constants (`0x14e3b`), `+ 0x70000` for 8 (`0x1d324`), `+ 0x30000` for 4. -- **One constant at a non-zero offset:** `table[root] + 4 · destOffset`. At `0x19fca` the builder adds `0xc` and its - vtable fallback is slot 37 `(2, value, 3)`; at `0x1a346` it adds `0x14` and the fallback is `(2, value, 5)`. -- **Otherwise the entry is written unchanged:** one constant at offset 0, a descriptor table (then 4 bytes), a root - CBV/SRV/UAV (then the full 8-byte GPU address, e.g. `0x19fff`). - -No site combines both adjustments. Before writing, every reader tests the entry against `0xC0000000` (98 sites in the -builder, 7 in the FSR DLL), and sets the flag byte at `+0x140` only when both of those bits are clear. - -### 3.5 What the package does not measure - -There is no shipped client for `ID3D12CommandQueue`, `ID3D12Fence`, `ID3D12CommandAllocator`, -`PresentX`, `CreateCommandQueueX`, `SuspendX` or `ResumeX`: - -- the BVH builder's constructor takes a device, and its build functions take a command list; no - call at the public device creation slots 8/9/12/36 appears in its `pdata` functions, and it - does not create a swapchain; -- no shipped module imports `d3d12_xs.dll` beyond the two root-signature calls; -- no shipped module contains a queue/fence/allocator IID or the string `PresentX`. - -The queue/fence/allocator Xbox surface is therefore **not measured here at all**. The only -command-object facts from the package are the command-list call sites in section 3.3. - -## 4. Prior-art claims - -Prior art is cited for facts only; no code is copied. Licence details are in section 8. - -### 4.1 SCARAB (GPL-3.0-only) - -SCARAB measured the console `d3d12_xs.dll` export surface and reports the console-only -extensions. The parts relevant to this page: - -| Claim | Status | Detail | -|---|---|---| -| `PresentX` is an `ID3D12CommandQueue` method | **Prior art** | Class-attributed by a UMD validation message and by 367 call sites in the console SDK samples ([`d3d12-xs-wrapper.md:69-97`](https://github.com/p-portela/SCARAB/blob/d304fa2/docs/d3d12-xs-wrapper.md)). | -| `PresentX` carries at most 2 planes and 8 views per plane | **Prior art** | `D3D12CONS_PRESENT_PLANES_MAX = 2`, `D3D12CONS_PRESENT_VIEWS_MAX = 8`; the UMD message names `pPlaneParameters[%d].ResourceCount <= 2`. | -| Present flags `NONE`, `IMMEDIATE`, `PERSIST`, `UNIQUE_VIEW_RESOURCES` exist | **Prior art** | Names are recovered; the numeric values are **not** measured. `console_extensions.h` assigns `0x1/0x2/0x4` while `present_adapter.h` says the values are unknown and uses zero; the two contradict each other ([`d3d12_xs_surface.md §7`](d3d12_xs_surface.md)). | -| `PresentX` signature and slot | **Open** | No signature, slot or call sequence is recovered. | -| `SuspendX` / `ResumeX` are queue methods | **Prior art** | 122 sample call sites each; no signature or slot. | -| `CreateCommandQueueX` is a device method | **Prior art** | UMD message ties it to `ID3D12Device`; the inferred shape is `(pDesc, pShaderQueueParams, riid, out)`; the UMD says a shader-based queue supports only `D3D12_COMMAND_LIST_TYPE_COMPUTE`; SCARAB returns `E_NOTIMPL`. Slot and parameter layout are **Open**. | -| `ID3D12ConsDmaCommandList` IID `30bc77b9-8379-4b25-95de-b8588c42275d` | **Prior art** | Exported at ordinal 100; the DMA list rule is quoted from the UMD. `D3D12CONS_COMMAND_LIST_TYPE_DMA = 6` is **Derived** by appending to the PC enum, not measured. | -| Command-list extension order | **Assumed** | SCARAB's own header says the order within the appended block is not recovered; every appended slot logs its name and raw arguments ([`console_extensions.h:13-31`](https://github.com/p-portela/SCARAB/blob/d304fa2/components/extension-wrapper/console_extensions.h)). Do not copy it. | -| `OMSetFrontAndBackStencilRef` is public GCL8 | **SDK fact, not an extension** | Same signature at `d3d12.h:32819`; the SCARAB catalogue's placement after GCL6 would land in the wrong slot ([`d3d12_xs_surface.md §5.1`](d3d12_xs_surface.md)). | - -The `DXGIXPresentArray`, `DXGIXSetFrameNotification`, `DXGIXSetVLineNotification` and -`DXGIXGetFrameStatistics` names are **free functions** at ordinals 20/21/22/19, not queue -methods; no parameter layouts are recovered. `DXGIXGetFrameStatistics` is reported to write 64 -bytes, so a zero-argument stub is not safe ([`d3d12_xs_surface.md §7`](d3d12_xs_surface.md)). - -### 4.2 `americas-recomp` (GPL-2.0-only) - -The prior art that ran the package DLLs against a PC D3D12 device measured the **device** -surface, not the command objects: - -- device slots 1/14/15/16/18/19/27/38 in desktop order; slot 14 is `CreateDescriptorHeap`; -- device slot 62 is called as `CreateComputePipelineState` (the PC interface's slot 62 is - `CreateStateObject`), and slot 76 is Xbox texture creation; -- descriptor-heap `GetCPU/GPUDescriptorHandleForHeapStart` (heap slots 9/10) return the 8-byte - handle in RAX; -- Xbox root-signature descriptors carry flags `0x03000000`, masked on a copy; -- the BVH builder's 53 compute shaders are Xbox DXIL. - -Its own summary explicitly stops before **presentation (`PresentX` and plane parameters), -command-list extensions, and queue/fence creation slots** -([`d3d12_vulkan.md §7`](d3d12_vulkan.md), -[`PLATFORM_SURFACE.md`](https://github.com/realdody/americas-recomp/blob/xbox-series/docs/xbox/PLATFORM_SURFACE.md)). -So it adds **no** measured queue/list/fence slot to this page. The device slots it did measure -are useful context: they are the reason a replacement cannot assume the whole device vtable is -public order, and the reason the four creation slots 8/9/12/36 still need a trace. - -### 4.3 What prior art does not close - -Even taking both projects at face value, the following remain **Open**: - -- the Xbox slots for `CreateCommandQueue`, `CreateCommandAllocator`, `CreateCommandList`, - `CreateFence`; -- the Xbox queue vtable beyond the public chain (`PresentX`, `SuspendX`, `ResumeX`); -- the `PresentX` signature, plane struct, resource/view arrays and swapchain parameters; -- the command-list extension slots other than the ones sections 3.3a and 3.5a measured (71, 73, 80, 85, 141, 146, 148); -- the DMA list type's real numeric value and the compute/copy console list IIDs, which the package - itself cannot supply (§3.2a): they need the running title or a vendor runtime; -- any Xbox-specific return convention on these interfaces. - -## 5. What a runtime can do without the executable - -### 5.1 Implementable and testable now - -The repository already implements the public-chain objects on Vulkan: - -- `ID3D12CommandQueue`, `ID3D12CommandAllocator`, `ID3D12GraphicsCommandList7` and - `ID3D12Fence1` are defined in `runtime/shims/d3d12_com.cpp:41-352`, on the Windows SDK vtable - order, with generated stubs for every method they do not implement - (`runtime/shims/d3d12_com.h:1-5`); -- `CreateCommandQueue`/`CreateCommandAllocator`/`CreateCommandList`/`CreateFence` are wired at - the public device slots in `runtime/shims/d3d12_vulkan_device.cpp:345-382`; -- `runtime/test/d3d12_com_test.cpp:77-153` creates all four, records clears and both barrier - kinds, rejects an open list at `ExecuteCommandLists`, executes behind a queue `Wait`, and - checks fence signalling and `SetEventOnCompletion`. The test is source-level evidence; this - page did not rebuild the Vulkan runtime. - -The builder's `ResourceBarrier` call at `+0xd0` and `Dispatch(1,1,1)` at `+0x70` are consistent -with the SDK slots the runtime already implements. Legacy barriers (slot 26) and enhanced -barriers (slot 80 in GCL7) both have IR and Vulkan replay support -(`runtime/src/command_list.h`, `runtime/src/vulkan_replay.h`; see -[d3d12_vulkan.md §3.2](d3d12_vulkan.md)). - -### 5.2 Implementable, but unverified against the Xbox device - -A runtime can create the four objects and hand them out at the **public** device slots 8/9/12/36 -today. That is an assumption, not a measurement: the Xbox device was measured at -1/14/15/16/18/19/27/38/62/76, and slots 8/9/12/36 are exactly the ones this page needs. If the -Xbox slots differ, a generic forward-to-PC thunk calls the wrong method. The current proxy -(`runtime/shims/d3d12_xs_device.h:1-18`) forwards every unshadowed slot in PC order and logs -first calls; a wrong slot would therefore be visible as a misnamed call, not a silent success. - -Queues and fences are wrapped the same way. - -- **What is wrapped.** Device slots 8 (`CreateCommandQueue`), 75 (`CreateCommandQueue1`), 36 - (`CreateFence`) and 32 (`OpenSharedHandle`, when it opens a fence) return queue and fence proxies. Each - proxy forwards the public chain in PC order: 19 queue slots, and 11 or 12 fence slots, in SDK 10.0.26100. -- **Logging.** Each slot logs its first call. `--trace-d3d12` records every call except `AddRef`/`Release`, - as `XboxID3D12CommandQueue::Signal called` or `XboxID3D12Fence::Slot40 unsupported` (the README's trace - grammar); on the Vulkan device the layer's own record of the same call follows it. An interface the real - object implements but the proxy does not model is logged once and refused. -- **The refused tail.** A slot past the public chain, up to the end of the proxy's own table (128 queue and - 64 fence slots, every one a thunk), logs its first four argument words once and returns `E_NOTIMPL`. -- **The guard region.** Each table sits at the end of the first page of a 64 KiB reservation, and the rest - of that reservation is never committed. A slot past the table therefore faults on the vtable read itself, - inside the reservation, and a vectored handler logs the slot before the fault goes on. A vtable read that - lands beyond the reservation is not caught. -- **Unwrapping.** Wherever a device or queue method hands a heap, queue or fence object to the real - runtime, the proxy passes the real object instead: queue `Signal`/`Wait` (14/15), and device `CreateSharedHandle` (31), `MakeResident` - and `Evict` (34/35), `SetEventOnMultipleFenceCompletion` (45), `SetResidencyPriority` (46) and - `EnqueueMakeResident` (50). -- **QueryInterface.** It answers only the modelled interfaces, so no real object reaches the title. -- **What is not covered.** Command lists are not wrapped yet: `ExecuteCommandLists` passes the lists through, - and a heap proxy given to a list's `SetDescriptorHeaps` reaches the real list unchanged. The command-list - proxy of §3.5a adds the unwrap at both places. - -Command allocators get the same kind of proxy: device slot 9 (`CreateCommandAllocator`) returns one. - -- **What is forwarded.** The public chain, 9 slots: the base chain and `Reset` at 8. A slot past it, up to the - end of a 64-slot table, is logged and refused, and a read past the table faults in its own guard region. - The console allocator's extra methods cannot be measured from the package (D3D-360). No shipped module creates, - receives or calls an allocator (§3.5). The package has no `d3d12_xs.dll` either, and no export of the three - D3D12 clients takes an allocator. `dumpbin /exports` (MSVC 19.52) lists the BVH builder's 12 exports, which take - an `ID3D12Device11` or a command list (`docs/d3d12_xs_surface.md`), and the FSR loader's and upscaler's - `ffxConfigure`, `ffxCreateContext`, `ffxDestroyContext`, `ffxDispatch` and `ffxQuery`. A call past slot 8 could - only show up in the game executable, which the package doesn't contain, so such a slot stays logged and refused. -- **Where a list takes it.** A list takes an allocator from the title in `CreateCommandList` and `Reset`, so - the proxy is safe only where the list side resolves it. Slot 9 therefore wraps an allocator only when it - answers `kLeonidaCommandAllocatorTag` (`d3d12_xs_device.h`). That is the Vulkan layer's own allocator, whose - `CommandAllocator::from()` resolves the proxy for both list calls. -- **On the host runtime.** A PC runtime allocator comes back unwrapped, logged once, because the PC runtime's - lists would take a proxy for their own allocator. A command-list proxy that unwraps at `Reset` (§3.5a) is - what lets the host backend wrap allocators too. -- **Residency.** An allocator is a pageable, so `MakeResident`/`Evict`/`SetResidencyPriority`/ - `EnqueueMakeResident` unwrap allocator proxies like heap, queue and fence proxies. - -`allocator_proxy_test` checks this on the Vulkan device and on the host runtime, and the mock test checks it -over allocators with and without the tag. On the Vulkan device it checks forwarding, the refused tail, the guard -region, identity, and D3D12's allocator rules through the proxy, and runs a list created and `Reset` on the -proxy whose copies go through the queue and fence proxies and are read back. - -Which of this is measured: the slot numbers and signatures are the SDK's (public). That the console -keeps the public queue and fence slots, and device slots 8/32/36/75, is an assumption the package cannot -test, as above. The proxies make a wrong assumption visible in the log; they do not prove it right. -`queue_proxy_test` checks all of this with no game files, on the host runtime (WARP and a hardware -adapter) and on the Vulkan device; `OpenSharedHandle` of a shared fence only on the host runtime, since the -Vulkan device does not share fences (the test prints "not checked" there). Each error case runs in its own -process and is compared with the real object's HRESULT. The test also includes a console-style client: it makes a heap through slot 14 (handle in -RAX) and buffers through slot 76 (layout word 0x1). It then copies through the queue proxy, finishes through -the fence proxy, reads the data back, and makes residency calls that carry the heap, queue and fence proxies. -`device_proxy_test` gets its queue and fence through the registered `D3D12XboxCreateDevice` shim. - -The package-gated `bvh_builder_test` and `fsr_dispatch_test` stay at `SKIP (no package)` without -`LEONIDA_GAME_DIR`, and they would not cover these paths if they ran. Neither creates a queue or a fence: -the BVH builder's constructor calls device slots only, and `fsr_dispatch_test` records into a logging list it -never executes. Neither DLL calls the device slots the proxies change (§3.5, §3.5a). - -The same caveat applies to **return conventions**: the public AMD64 COM convention (HRESULT in -EAX, `void` methods, out-parameters through pointers, `GetDesc` returning a 16-byte struct by -value) is what the runtime implements. No Xbox-specific convention on a queue, list, fence or -allocator has been measured. The only measured Xbox return-convention quirk in the graphics -surface is the descriptor-heap start handle in RAX (prior art), which is a heap method, not a -command object. - -### 5.3 Blocked on the executable or console driver - -| Item | Why it is blocked | -|---|---| -| `PresentX` | No slot, signature, plane struct or swapchain/plane parameters. Prior art gives only names, the 2-plane/8-view limits and four flag names. | -| `CreateCommandQueueX` | No slot or parameter layout; only the UMD message and an inferred shape. | -| `SuspendX` / `ResumeX` | No slot or signature. | -| Xbox queue/list/fence/allocator slot deviations | No runtime binary and no game executable; the package has no queue, fence or allocator client, and its only command-list client is the BVH builder. | -| Builder's list field `+0x350` | Read once (`0x1d877`) and not explained by the inline buffer of section 3.5a, which covers `+0x18`, `+0x28`, `+0x30`, `+0x140`, `+0x141`, `+0x344` and `+0x544`. | -| DMA list use/value | The IID is prior art; type 6 is derived; no shipped module uses it, and no module can name any GUID at a call site beyond its known ten or holds a static queue description with a non-PC type (§3.2a). | -| Compute/copy console list IIDs | Not exported (see #3520) and not present at any call site (§3.2a); only the running title can supply them. | - -### 5.4 GCL8 (resolved in PR #164) - -The shipped builder's rehydrate exports name `ID3D12GraphicsCommandList8`, and -`OMSetFrontAndBackStencilRef` is public GCL8 at slot 81. **PR #164 adds the public GCL8 interface** -to `runtime/shims/d3d12_com.cpp`: it records the front/back values, resets them in `Reset`, answers -`IID_ID3D12GraphicsCommandList8`, and registers the `d3d12_gcl8` CTest (9/9). The values are recorded -but not applied because this layer still has no pipeline/draw path. The builder's `+0x490` call is the -enhanced-barrier `Barrier` at console slot 146 (section 3.3), which a console-order list routes to GCL7 slot 80. - -## 6. Return conventions - -| Interface | Public convention | Xbox-specific measurement | -|---|---|---| -| `ID3D12CommandQueue` | `ExecuteCommandLists`, `SetMarker`, `BeginEvent`, `EndEvent` are `void`; `Signal`, `Wait`, `GetTimestampFrequency`, `GetClockCalibration` return `HRESULT`; `GetDesc` returns `D3D12_COMMAND_QUEUE_DESC` by value | None measured | -| `ID3D12CommandAllocator` | `Reset` returns `HRESULT` | None measured | -| `ID3D12Fence`/`Fence1` | `GetCompletedValue` returns `UINT64`; `SetEventOnCompletion`/`Signal` return `HRESULT`; `GetCreationFlags` returns the flags enum | None measured | -| `ID3D12GraphicsCommandList`/1–8 | Most recording methods are `void`; `Close`/`Reset` return `HRESULT`; `GetType` returns the list type; GCL8 `OMSetFrontAndBackStencilRef` is `void` | The builder's `+0xd0` and `+0x70` calls ignore RAX, consistent with `void`; no other convention measured | - -The `GetDesc` by-value return is the one place a generic thunk can get the ABI wrong on x64; -the runtime implements it directly (`runtime/shims/d3d12_com.cpp:309`). No Xbox variant of that -return has been measured. - -## 7. Next measurable step - -The executable is absent, so the next step should use the one shipped client that exists rather -than invent slots. - -1. **Confirm sections 3.3, 3.3a and 3.3b with a logging proxy.** Create a test-only command - list whose public GCL6/GCL8 vtable logs `(slot, raw arguments)` and whose tail is a page of - logged unknown slots. Pass it to - `XboxBvhBuilder::BuildRaytracingAccelerationStructureBatched2X` with a minimal non-empty - descriptor. The proxy ran twice; both runs stopped one step short, at the CPU-side geometry - validation of section 3.3b (fault at `0x142d3`), before the first list call. The static pass - settled what the first calls will be: not the `+0xd0` barrier — it is gated and never fires - in the shipping DLL — but the wrapper's slot-146 barriers, then the upload function's slot - 148 for `count * 40` bytes and its own `Dispatch((count+31)/32, 1, 1)`, and only then the - per-entry `Dispatch(1,1,1)` of section 3.3; the other new slot, 90, is gated too - (section 3.3b). Keep the cursor at its limit so every call reaches the vtable, and back the - geometry descriptors with CPU-readable memory holding valid 0x38-byte records per section 3.3b - (type 0, index format 0, vertex count a multiple of 3 — prior art measured a 3,000-vertex - triangle geometry; the prebuild answer is 204,800 bytes / 128,704 scratch). A descriptor shaped - like the one `GetRaytracingAccelerationStructurePrebuildInfo` accepts is not enough by itself, - because the validation reads the records with CPU loads. -2. **GCL8 is now implemented** in PR #164 (public slot 81, recorded/reset, CTest 9/9); the - builder's `+0x490` is `Barrier` (section 3.3), and its slot 148 needs an upload allocator (section 3.3a). -3. **When the executable appears, trace the four creation calls first.** Per-slot counters on - device slots 8/9/12/36, then queue slots 10/14/15, fence slots 8/9/10, and every slot beyond - the public chain. The first `PresentX` call and the queue vtable tail are the only way to - recover the present surface; a DXGI import would make the DXGI path the first - implementation instead ([d3d12_vulkan.md §8.2 Q6](d3d12_vulkan.md)). The counters exist: device, - queue and fence proxies count every slot, and the queue and fence tails are logged with their - first argument words (§5.2). - -Do not fill the unknown slots with guesses. A wrong slot is worse than a clean refusal; the -existing device proxy already follows that rule (`runtime/shims/d3d12_xs_device.h:16-18`). - -## 8. References and provenance - -### 8.1 Licence - -Leonida is GPL-3.0-or-later. SCARAB is GPL-3.0-only and `americas-recomp` is GPL-2.0-only; both -are cited for ABI facts only. No code, headers, generated stubs, comments or tables were copied -from either project. The PE and disassembly facts in section 3 were produced locally from the -shipped `XboxBvhBuilder.dll`; the public slot table was parsed from the installed Windows SDK -10.0.26100.0. No game data was read, decrypted or executed. See -[`docs/related_projects.md`](related_projects.md) for the project-level rule. - -The XboxBvhBuilder export names quoted in section 3.1 are mangled C++ symbols from the DLL's -export table, reproduced as ABI facts. The GUID values in section 3.2 are 16-byte constants from -the SDK; the console GUIDs are attributed to SCARAB in -[`d3d12_xs_surface.md §4`](d3d12_xs_surface.md). - -### 8.2 Reproduction - -- Package inventory and absent files: directory listing plus - `layout_3202719e-b4b4-421c-9f8f-70d1c4a7d60b_xs.xml:14`. -- Imports/exports: `python tools/pe_inspect.py --game-dir --out `; the - 16-DLL summary in section 1.2 used `pefile` normal + delay-load directories. -- IID scan: read the 80 `DEFINE_GUID(IID_ID3D12…)` values from - `C:\Program Files (x86)\Windows Kits\10\Include\10.0.26100.0\um\d3d12.h`, plus the two console - GUIDs from [`d3d12_xs_surface.md §4`](d3d12_xs_surface.md), and search each DLL for the - 16-byte little-endian value. Absence is evidence about static constants, not about runtime - `QueryInterface` calls. -- Builder call sites: Capstone 5.0.7 x86-64 disassembly of the 12 exported functions and the - functions they call directly; RVAs are PE relative virtual addresses. The - `0xd0` call is in the batched entry (`0x216a0`, site `0x2171e`); the `0x490` call is in the - per-descriptor function reached from it (`0x1d7c0`, site `0x1da02`). Section 3.3a: the - `call [reg+disp]` sites in the rest of `.text` whose object register holds the list pointer, - each read with the argument registers set before it and the inline write it falls back from; - the barrier constant is the 16 bytes at RVA `0xcdf60` (file offset from the section table). -- Section 3.3b and the gated sites: a second, independent disassembly pass (iced-x86, run for the - D3D-293 measurement) of the batched entry, the validation chain (`0xe6a0`, `0xcc00`, `0x14270`), - the upload function `0x20ea0` and the wrapper call sites; the dynamic side is D3D-293's - logging-proxy harness, whose two runs faulted at `0x142d3` before the first list call. The - quoted validation messages are the DLL's own wide strings at the `.rdata` addresses the throw - paths load. The gate-byte sentence is a linear sweep of `.text` collecting memory operands - targeting `0xd7738`–`0xd773f`. -- Public slots: parse the `MIDL_INTERFACE`/`virtual` declarations in `d3d12.h`; the counts in - section 2 include the seven `IUnknown`+`ID3D12Object` slots. Cross-check selected values with - `python tools/d3d12_xs_surface.py --check --sdk` (116 slots, 83 standard GUIDs) and - `python -I tests/test_d3d12_xs_surface.py`. - -### 8.3 References - -- [d3d12_vulkan.md](d3d12_vulkan.md) §3.1, §3.2, §4, §4.4, §4.5, §7, §8.2, Appendix A.2, - Appendix B — the COM/vtable assumptions, the record/replay design, the known/unknown list and - the BVH builder evidence. -- [d3d12_xs_surface.md](d3d12_xs_surface.md) §2, §4, §5, §5.1, §6, §7, §9 — the export/IID - contract, console GUIDs, extension catalogue, GCL8 correction, DMA list rule and `PresentX` - status. -- [related_projects.md](related_projects.md) — the GPL-2.0-only and GPL-3.0-only provenance - rules. -- SCARAB, pinned at `d304fa26c0292e2f3ba76f23b15c9f30734bec02`: - [`docs/d3d12-xs-wrapper.md:69-97`](https://github.com/p-portela/SCARAB/blob/d304fa2/docs/d3d12-xs-wrapper.md), - [`components/extension-wrapper/console_extensions.h:13-31,45-72,84-191`](https://github.com/p-portela/SCARAB/blob/d304fa2/components/extension-wrapper/console_extensions.h), - [`docs/d3d12-xs-bridge.md:239-245`](https://github.com/p-portela/SCARAB/blob/d304fa2/docs/d3d12-xs-bridge.md). -- `americas-recomp`, branch `xbox-series`: - [`docs/xbox/PLATFORM_SURFACE.md`](https://github.com/realdody/americas-recomp/blob/xbox-series/docs/xbox/PLATFORM_SURFACE.md), - [`tools/xbox/platform/README.md`](https://github.com/realdody/americas-recomp/blob/xbox-series/tools/xbox/platform/README.md). -- Windows SDK 10.0.26100.0: - `um/d3d12.h:5193,5323,5477,6337,7216,7982,8701,9006,9011,9026,9178,20165,21255,30275,31123,31965,32816`. diff --git a/docs/d3d12_vulkan.md b/docs/d3d12_vulkan.md deleted file mode 100644 index 639cfc099..000000000 --- a/docs/d3d12_vulkan.md +++ /dev/null @@ -1,4229 +0,0 @@ -# Xbox D3D12 (`d3d12_xs`) to Vulkan - -**Status: in progress. A Vulkan-backed `ID3D12Device` (queues, allocators, command lists, fences, descriptor heaps, -render-target and depth views, texture views and samplers, committed and reserved buffers, 2D textures and 3D texture transfers and color clears, and query heaps) -runs behind the Xbox-ABI device proxy, and a presenter puts back buffers in a window (section 3.2). The M0 -milestone passes in a synthetic test (section 6), M1 with stand-in shaders in `d3d12_draw_test`, M1.5 with -hand-written RDNA2 run through the translator in `d3d12_translated_draw_test`, and the synthetic part of M2 -(descriptor heaps, SRVs, a sampler and a translated textured-quad draw, 4,096 exact pixels) in -`d3d12_m2_textured_test`. `D3D12XboxCreateDevice` uses it when `LEONIDA_D3D12=vulkan` is -set and the host PC device otherwise. Root signatures (packed into the 32 user-data dwords), graphics and compute -PSOs, draws, dispatches, `ExecuteIndirect`, and presentation through `PresentX` or a DXGI swapchain are implemented -and have GPU tests; which present path the game uses is still open (question 6). Shader-resource views of buffers, -pipeline-state streams (`CreatePipelineState`), tessellation and stream-output pipelines are not implemented, and -mesh shaders are reported as not supported (stream PSOs and mesh shaders: D3D-29, #1712). The device reports -`RaytracingTier` as `NOT_SUPPORTED`, yet `BuildRaytracingAccelerationStructure` builds XDXR BVH4 structures on the -GPU (section 4.8).** This is the plan for -replacing the console's `d3d12_xs.dll` with an implementation that records D3D12 commands and replays them on -Vulkan, while producing exactly the shader-visible contract that `tools/rdna2spirv.py` already emits against (see -[design.md](design.md#translator-status-and-runtime-contract)). - -The document is deliberately conservative about what is known. Every claim is marked: - -- **Verified** — observed in this repository or in the game package, with a way to reproduce it. -- **Public** — documented in the Windows SDK, Microsoft's public GDK/D3D12 documentation, or the Vulkan - specification. -- **Assumption** — a design choice that must be checked against the game's executable when it is available. -- **Open** — unknown; listed with a way to resolve it. - -Nothing here uses game data, keys or decryption. The package is read-only; the executable that would answer most -of the open questions is not in it. - -## 1. The job - -The game is an Xbox Series build (`game_scarlett_master.exe`, `d3d12_xs.h` / `d3d12_xs.lib`). It was compiled -against the Xbox flavour of D3D12 and calls the console driver through COM interfaces. The layer must: - -1. **Intercept the D3D12 surface.** Free functions exported by `d3d12_xs.dll` (device creation, root-signature - serialization) and every COM method the game calls on the returned objects. The objects are our own C++ - objects; the vtables must have the exact method order the game was compiled against. -2. **Preserve D3D12 semantics that affect output.** Command lists record; execution is deferred; descriptors are - values (GPU virtual addresses or CPU handles); resource states are explicit; root arguments are set at record - time; allocators and fences control reuse. -3. **Produce the translator's shader contract.** The translated SPIR-V is already written against a bindless set - 0, a 144-byte push-constant block, a descriptor hash table and one GPU address space. Changing that contract - would invalidate 26,503 translated shaders and the GPU tests that check them. - -The layer is not a general D3D12-on-Vulkan compatibility layer. It only needs the calls this game makes, but each -call it accepts must behave like D3D12. - -## 2. What is verifiable today - -| Fact | Evidence | Confidence | -|---|---|---| -| The public D3D12 interface chain and method order are in the Windows SDK `d3d12.h` (10.0.26100.0 here). The Xbox public reference lists the same base interfaces and method names under `d3d12_xs.h` / `d3d12_xs.lib`; the measured Xbox device ABI is mostly that order, with deviations at slots 62/76 and heap slots 9/10 (section 7). | Local SDK header; [Xbox public graphics reference](https://devdocs.xbox.com/reference/graphics/d3d12); e.g. [CreateCommittedResource](https://devdocs.xbox.com/reference/graphics/d3d12/interfaces/id3d12device/methods/id3d12device_createcommittedresource_public) | Public; measured deviations in section 7 | -| The game's raytracing helper is a shipped DLL, `XboxBvhBuilder.dll`, whose export signatures name `ID3D12Device11`, `ID3D12GraphicsCommandList4`, `ID3D12GraphicsCommandList6` and `ID3D12GraphicsCommandList8`, plus Xbox XDXR batched/streaming acceleration-structure types. | PE export table of `XboxBvhBuilder.dll` (884,224 bytes); see Appendix A | Verified | -| That DLL imports only `d3d12_xs.dll!D3D12SerializeVersionedRootSignature` and `xmem.dll!XMemVirtualQuery` from console libraries. It receives the device and command lists from the game. | PE import table; Appendix A | Verified | -| `amd_fidelityfx_upscaler_xbox.dll` imports only `d3d12_xs.dll!D3D12CreateRootSignatureDeserializer` and contains the base `ID3D12Device`, `ID3D12Resource`, `ID3D12PipelineState`, `ID3D12RootSignature`, `ID3D12Heap`, `ID3D12DescriptorHeap` and `ID3D12CommandSignature` IIDs. | PE import table and GUID byte scan; Appendix A | Verified | -| None of the other scanned non-CRT DLLs (`amd_fidelityfx_loader_xbox`, `Bink2Scarlett`, `libHttpClient.GDK`, `XCurl`) imports `d3d12_xs`. | PE import scan; Appendix A | Verified | -| The package layout lists `game_scarlett_master.exe`, but the file is not in the package folder. | `layout_..._xs.xml`, chunk 1001; directory listing | Verified | -| `gameos.xvd` is an XVD (`msft-xvd` at file offset 0x200, format version 3) with a high-entropy payload and no plaintext PE headers or D3D12 strings. Extracting `d3d12_xs.dll` from it would require keys, which this project does not do. | Entropy and string scan; Appendix A | Verified | -| Prior art runs the package DLLs against a PC D3D12 device and measured the Xbox ABI: 6 Xbox-specific static imports across the 16 DLLs, `D3D12XboxCreateDevice`, device slots 62/76, descriptor-heap start handles in RAX, root-signature flags `0x03000000`, and the BVH builder's Xbox DXIL shaders. | [PLATFORM_SURFACE.md](https://github.com/realdody/americas-recomp/blob/xbox-series/docs/xbox/PLATFORM_SURFACE.md), [platform README](https://github.com/realdody/americas-recomp/blob/xbox-series/tools/xbox/platform/README.md) | Verified by the prior art (running the package DLLs / static imports; section 7) | -| The translator and its GPU tests already define the shader contract: set 0 bindings 0–19, 144-byte push constants, heap/code base, FNV-1a descriptor hash table, buffer device addresses. | [design.md](design.md#translator-status-and-runtime-contract); `runtime/test/vk_texture_test.cpp` | Verified | - -What this does **not** tell us: the full `d3d12_xs.dll` export list, the `D3D12XboxCreateDevice` params/flag -layout, the remaining Xbox slot deviations (presentation, command lists, queues, fences), the -root-signature-to-`s0..s31` mapping, the console descriptor layout, the present path, the raytracing path, and the -GPU VA window. Section 8.2 lists each with a way to resolve it. - -The first run with the executable should be a **trace build**: every free function and COM method is a logging -stub that returns a failure, and the methods are filled in in the order the game calls them. Section 3.1 describes -the interception; section 8.2 turns the trace into a work list. - -## 3. Architecture - -### 3.1 Interception and COM - -The current shim (`runtime/shims/d3d12_xs.cpp`) forwards only two free functions to the host `d3d12.dll`. That is -enough for the bundled middleware's `d3d12_xs` calls, not for the game. The layer adds: - -- **Free functions.** Every `d3d12_xs.dll` export the executable imports. The import table is the source of truth. - Prior art names the device entry point `D3D12XboxCreateDevice(adapter, params, riid, out)`; its 24-word params - struct is only logged there, and the signature is taken from public documentation rather than a header. Treat the - params/flag layout as **Open**, accept the call, log the words, and create the device. Do not assume - `D3D12CreateDevice` is the console entry point. -- **COM objects.** `Device`, `CommandQueue`, `CommandAllocator`, `GraphicsCommandList`, `RootSignature`, - `PipelineState`, `DescriptorHeap`, `Resource`, `Heap`, `Fence`, `QueryHeap`, `CommandSignature`, - `PipelineLibrary`, and the raytracing/lifetime objects if used. -- **Vtable layout.** Use the Windows SDK's `d3d12.h` declarations for the public chain, but treat the vtable as - **mostly public, not universally public**. Prior art measured device slots 1, 15, 18, 19, 27 and 38 in the - desktop order, but also an extra texture-creation method at slot 76, a `CreateComputePipelineState` call at - slot 62 where the PC interface it forwarded to presents `CreateStateObject` (different arity), and descriptor-heap - start handles returned in RAX at heap slots 9/10. Implement the public chain plus those measured overrides - explicitly; do not assume every slot. Device 11 adds `CreateSampler2`; command list 8 adds - `OMSetFrontAndBackStencilRef` (public SDK). -- **Unknown IIDs and slots.** `QueryInterface` must log the IID and return `E_NOINTERFACE` if it is not in the - public chain. If the game then fails, the IID and the call site identify the Xbox-specific interface to reverse. - Do not invent a vtable for an unknown IID: a wrong slot is worse than a clean failure. -- **No host D3D12 or DXGI.** The PE loader currently lets unknown system DLLs bind to the host. `dxgi.dll` and - `d3d12.dll` must be shimmed, not resolved from System32. Host DXGI would hand the game a desktop adapter and - swapchain that cannot see our Vulkan device, and host D3D12 would create a second, unrelated device. This is an - integration requirement, not an optimisation. -- **Trace first.** `gta6rt --trace-d3d12` emits numbered records for device entry points, Vulkan device operations, - command-list recording and queue submission. Records contain fixed API names and outcomes only. See - [the runtime guide](../runtime/README.md#first-boot-d3d12-trace) for collecting a trace. - -**Measured, not assumed:** the Xbox device ABI is not uniformly the desktop order. Slots 1/15/18/19/27/38 matched -in the prior art, while slots 62 and 76 and the heap start-handle return convention did not. Treat every slot as -unverified until traced; the public interface names and IIDs may still be usable, but the slot mapping is not -guaranteed. - -### 3.2 Record and replay - -D3D12 command lists are recorded, then executed later. Vulkan command buffers are also recorded, but the layer -must not simply translate each D3D12 call into a Vulkan call as it arrives, because: - -- descriptor heaps can be updated between recording and execution; -- a command list can be reset and rerecorded; -- a bundle is recorded once and executed many times. - -The design is therefore an **IR per command list**: - -- `SetPipelineState`, root arguments, vertex/index buffers, viewport/scissor, render targets, descriptor-heap - bindings and the other sticky state update a state block. -- Each draw/dispatch/copy/barrier appends a compact command with a snapshot of the state that affects it. - GPU descriptor tables can refer to shader-visible heap entries at execution. CPU descriptors such as RTVs - are consumed while recording, so their view contents go into the IR. An application can reuse the CPU - descriptor slot after the call. See Microsoft's [descriptor overview][descriptor-overview]. -- `ExecuteCommandLists` replays the IR into a fresh `VkCommandBuffer`, resolving descriptors, uploading dirty - descriptor ranges and the hash table, and emitting barriers. Bundles are inlined when they are executed (see `ExecuteBundle` below). -- `Reset` on a command list discards its IR; the allocator owns the memory. D3D12 already requires the application - not to reset an allocator whose lists are in flight; the layer can rely on that and assert in debug builds. -- Command-list and allocator misuse returns what the PC runtime returns (D3D-51). `d3d12_vulkan_device_test` runs - the same 25 calls on the host runtime and on this layer and compares the HRESULTs. One list at a time records into - an allocator: creating or resetting a second list onto it gives `E_INVALIDARG`, and resetting the allocator while - a list records into it gives `E_FAIL`. `Close` twice and `Reset` of an open list give `E_FAIL`. Resetting an - allocator whose lists are still executing gives `S_OK` on the PC runtime too (keeping that safe is the - application's job). Two differences remain. `Reset` with a null allocator crashes the PC runtime, while ours - returns `E_INVALIDARG`, so that call is not compared. Executing a list that is still open removes the PC device - (`GetDeviceRemovedReason` gives `DXGI_ERROR_INVALID_CALL`), while this layer submits nothing and keeps the device: - an invalid call does not remove it. - Creation answers as the host runtime too (`compare_invalid_arguments`, "command allocator:", "command list:" and - "command list1:", RTX 5070 / 621.14): a type past `VIDEO_ENCODE` and a node other than node 0 are `E_INVALIDARG`, - checked before the output; a null output is then `E_UNEXPECTED`. Video list types are created as graphics lists - here, while the host hands out a video list (`E_NOINTERFACE` for `ID3D12GraphicsCommandList`), so they are not - compared. -- `Close` freezes the IR. `ExecuteBundle` is accepted only on a direct list, with an already-closed bundle as its callee; the bundle's recorded commands and calls are replayed at the call site, so the source can be reused or reset without changing the parent. Command-list creation and reset require an allocator of the same type. A bundle cannot be submitted directly to a command queue. -- Bundle restrictions are checked while recording for the IR operations currently implemented here (barriers, clears, copies, resolves, `SetPredication`, `DiscardResource`, the atomic copies, `RSSetViewports`, `RSSetScissorRects`, `OMSetRenderTargets` and `ClearState`; `WriteBufferImmediate` is allowed in a bundle); those calls are not legal inside a D3D12 bundle and make `Close` return `E_INVALIDARG`. `d3d12_bundle_forbidden_test` measured the last four on the PC runtime without the debug layer: the bundle's `Close` fails (`E_FAIL`, where this layer gives `E_INVALIDARG`) on the default adapter and on WARP, and executing a bundle whose `Close` failed crashes the runtime, so the layer refuses it in `ExecuteBundle` instead. A bundle has no render targets, viewport or root signature of its own, so its state calls (pipeline state, root signature and arguments, vertex and index buffers, topology, blend factor, stencil references) and its draws and dispatches are kept as they were called, and `ExecuteBundle` plays them on the parent through the same members the application would have called. A draw then snapshots the parent's state plus what the bundle set, and what the bundle set stays on the parent afterwards. Commands that need no state (markers, immediate writes) are copied between them in order. `d3d12_bundle_test` measured the rule on the PC runtime, where the default adapter (an RTX 4060 Ti) and WARP drew the same picture in every case it ran. A bundle's draws see the parent's render targets, viewport and scissor, root signature and arguments (also when the bundle sets the same root signature first, so those arguments stay), and vertex and index buffers. A bundle starts with the pipeline state it was created or reset with, not the parent's. After `ExecuteBundle` the parent has that pipeline state and whatever else the bundle set: topology, root arguments, vertex and index buffers, and a different root signature with the bundle's arguments in place of the parent's. Topology: the default adapter takes the parent's when the bundle sets none. That is more lenient than Microsoft's stated rule (topology is undefined when a bundle begins), and WARP follows the rule by removing the device when a bundle draws or hands back without one, so a bundle should set it; the layer follows the default adapter. A bundle that sets a root argument before any root signature crashes the NVIDIA driver (the layer applies it to the parent's signature). The deferred calls are checked when they play, against the parent's root signature, so a bad one makes the parent's `Close` fail, not the bundle's. A per-list state setter must go through the deferred path (`defer()` in `d3d12_com.cpp`, replaying through a private member that does not trace) to work in a bundle. Not deferred yet: `ExecuteIndirect` in a bundle, and bundle `Dispatch` has no GPU test. -- What `Close` returns after one recorded call is compared with the PC runtime over WARP (no debug layer) by - `d3d12_close_parity_test`, 113 cases on fresh lists, nothing executed. 82 agree; the other 31 are listed in the - test as known differences. In 16 the layer fails a list WARP closes: draws and dispatches with no pipeline, - root arguments before a root signature, a `CopyTextureRegion` box that is empty or inverted, footprint to - footprint or at an unaligned footprint offset or pitch, `CopyResource` of a resource onto itself, - `ClearDepthStencilView` with an unknown flag, vertex-buffer slots past 31, - 17 viewports, an `OCCLUSION` query ended as `BINARY_OCCLUSION`, and `WriteBufferImmediate` at an address that - is not 4-aligned. Since one failed list fails the whole `ExecuteCommandLists`, each of these drops a submission - D3D12 would run. In 15 the layer closes a list WARP fails (redundant or out-of-range barriers, copies past a - resource's end or between formats of another family, resolves the PC runtime refuses, a query index past the - heap); what the layer does with those at execution is not part of this test. A refused list's code is always - `E_INVALIDARG` here, where the PC runtime also answers `E_FAIL`, so the test compares the verdict and prints both - codes. -- A queue's `ExecuteCommandLists` submits in order with one timeline semaphore signal. `Wait`/`Signal` become - timeline-semaphore waits/signals. `Present` queues after the frame's work. - -The command-list surface maps to the IR as follows: - -| Recorded call | IR / replay | -|---|---| -| `SetPipelineState` | state; bind the `VkPipeline` before the next draw/dispatch | -| `SetGraphicsRootSignature` / `SetComputeRootSignature` | state; select the pipeline layout and root map | -| `Set*Root32BitConstant(s)` / `Set*Root*View` / `Set*RootDescriptorTable` | update root args; build the push-constant block at the draw/dispatch | -| `SetDescriptorHeaps` | state; scan/populate the bindless arrays and hash table at execute | -| `IASetVertexBuffers` / `IASetIndexBuffer` / `IASetPrimitiveTopology` | state; bind arena buffer + offset, dynamic topology | -| `RSSetViewports` / `RSSetScissorRects` | state; dynamic viewport/scissor | -| `OMSetRenderTargets` / `OMSetBlendFactor` / `OMSetStencilRef` | state; rendering scope and dynamic state | -| `DrawInstanced` / `DrawIndexedInstanced` | command with a state snapshot | -| `Dispatch` / `DispatchMesh` | command with a state snapshot | -| `Copy*` / `Resolve*` / `Clear*` | copy/clear command | -| `ResourceBarrier` / `Barrier` | barrier command; state tracking | -| `DiscardResource` / `WriteBufferImmediate` / `AtomicCopyBufferUINT(64)` | discard, immediate-write and atomic-copy commands (section 4.2) | -| `BeginQuery` / `EndQuery` / `ResolveQueryData` | query commands | -| `ExecuteIndirect` | command; signature + argument buffer | -| `BeginRenderPass` / `EndRenderPass` | rendering scope | -| `ExecuteBundle` | play the bundle's state calls and draws on this list, copy its state-free commands in order | - -The IR is the place to add the trace, validation and "unsupported call" reporting. It also lets the layer replay a -frame deterministically from a capture, which is valuable for comparing against the game. - -What is implemented (all of it testable without the game): - -- **IR** (`runtime/src/command_list.h`): legacy barriers (transition, UAV, aliasing; split barriers record their end - half), enhanced barriers (global, buffer, texture; the half with `SyncAfter = SPLIT` is dropped and the other is - replayed as a full barrier), `ClearRenderTargetView` / `ClearDepthStencilView`, whole view or rectangles, - `CopyBufferRegion` / `CopyTextureRegion` / `CopyResource`, colour resolves, - `ClearUnorderedAccessViewUint` / `ClearUnorderedAccessViewFloat` (whole view or rectangles), (D3D-26) - `DiscardResource`, `WriteBufferImmediate` and `AtomicCopyBufferUINT` / `AtomicCopyBufferUINT64`, and `BeginQuery` / - `EndQuery` / `ResolveQueryData` (section 4.6). - Views and rectangles are copied while recording, so the CPU descriptor slot can be rewritten afterwards. - A `ClearDepthStencilView` flag for a plane the view's format doesn't have is ignored, as the PC runtime (WARP) - does: `STENCIL` on a `D32_FLOAT` view clears nothing and `DEPTH | STENCIL` clears the depth plane. Until 2026-11-23 - `prepare` returned `invalid_clear` for it and the whole list was dropped (D3D-437); `d3d12_clear_test` compares three - such cases with WARP. The depth value is kept as given: on a `D32_FLOAT` target WARP stores 1.5, -0.5 and NaN - unchanged, and a clear whose flags name no plane clears nothing, so neither fails the list any more - (`d3d12_clear_test` reads the texels back on WARP and here; `d3d12_close_parity_test` compares the `Close` verdicts). -- **Replay** (`runtime/src/vulkan_replay.h`): `prepare` resolves and checks a list without writing anything, `emit` - writes it. Legacy states map through the section 4.3 table (`vulkan_access`), enhanced barriers through - `vulkan_sync` / `vulkan_barrier_access` / `vulkan_layout` to `vkCmdPipelineBarrier2`. Whole-view clears are - transfer clears inside a layout round trip; rectangle clears are `vkCmdClearAttachments` in a dynamic-rendering - scope, with rectangles clipped to the mip. Copies become `vkCmdCopyBuffer`, `vkCmdCopyBufferToImage`, - `vkCmdCopyImageToBuffer` and `vkCmdCopyImage`. A placed footprint's row pitch becomes `bufferRowLength`, and - block-compressed extents stop at the mip edge (D3D12 pads footprints to whole blocks, Vulkan does not; a - texture-to-texture box of a block-compressed format is rounded up to whole blocks, as on the PC runtime, must fit - the destination's padded mip, and the Vulkan extent is cut where it reaches an image's edge; Vulkan wants that per - image, so when no single cut extent is a block multiple or at the edge of both images, for example a 4x4 box into - a 3x3 mip, the copy goes through transfer scratch (`vulkan_scratch.h`, as depth <-> colour copies do): - `vkCmdCopyImageToBuffer` with the source's own cut extent into whole blocks, then `vkCmdCopyBufferToImage` with the - destination's. The box fits the source's padded mip, so the scratch holds every block the destination reads). Each - range and buffer bound is checked before anything is written. A copy runs in `TRANSFER_SRC`/`TRANSFER_DST`, or - in place in `GENERAL` when the texture is in `COMMON`: that is D3D12's implicit promotion to a copy state. - A same-subresource `CopyTextureRegion` uses `GENERAL` for both sides; preparation rejects overlapping regions. - Cross-format `CopyTextureRegion` from an uncompressed texture into a partial BC edge block also uses transfer - scratch. Each source texel supplies one block, and the destination's write extent stops at the actual mip edge. - A 3D mip is one subresource. Boxed volume transfers preserve the full footprint's row and slice strides. - Whole-resource depth/stencil copies issue one `vkCmdCopyImage` per aspect, with a transfer write-to-read/write - dependency between them; all mips and layers stay batched within each aspect. This avoids stencil corruption - observed on RX 5700 XT, Windows driver 32.0.21045.5002, when both aspects share one multi-region copy command. - A standalone synthetic Vulkan multi-mip array reproduces the corruption with validation clean; this is a - conservative compatibility measure, not evidence that the Vulkan specification requires this dependency. - `d3d12_stencil_copy_test` checks D24S8/D32S8 across mip/layer counts and odd dimensions against WARP (CTest) - or `LEONIDA_HOST_ADAPTER` (manual runs), plus the deterministic upload pattern for both planes and sources. - **Depth ↔ colour copies** (`CopyResource` / `CopyTextureRegion` between `D32_FLOAT` and `R32_FLOAT/UINT/SINT`, - or `D16_UNORM` and `R16_FLOAT/UNORM`, single-sampled, single-plane depth) copy the bits as the PC runtime does. - `vkCmdCopyImage` refuses mismatched aspects, so each region goes image → scratch buffer → image - (`src/vulkan_scratch.h`: device-local chunks kept until the submission completes, on every GPU). Not covered: - depth with stencil (two planes), a D24 stored as D32, and multisampled textures; they are still refused. A float - written into a `D32_SFLOAT` image outside [0, 1] is undefined in Vulkan without `VK_EXT_depth_range_unrestricted`, - where D3D12 keeps the bits; `d3d12_copy_xfmt_test` uses values in [0, 1). - **D24_UNORM_S8_UINT without a native D24** (the Radeon 880M, AMD hardware generally, RADV): the layer stores - `D32_SFLOAT_S8_UINT` and makes it behave as D24 (`src/depth24.h`, `src/vulkan_depth24.h`). A footprint - of the depth plane holds 24-bit UNORM words (bits 0-23; the top byte is unspecified, the PC runtime reads it as - nothing and writes 0), the stencil plane is plain bytes. An upload converts the words with a compute pass - (`src/depth24_convert.comp`, integer arithmetic) into a scratch buffer of floats, the nearest float to - `d / 16777215`, which `vkCmdCopyBufferToImage` then moves into the image; a readback copies the image into the - scratch and the pass writes the words (a float is multiplied by 16777215 in float and rounded to nearest, ties to - even, which is what WARP and AMD's D3D12 driver do; NaN and negatives are 0, 1 and above the maximum). Every - 24-bit word makes the round trip unchanged (checked on all 16777216 by `depth24_convert_test`). Texture to - texture copies move the floats as they are. `ClearDepthStencilView` of any D24 texture, native or stored as D32, clears with the float of the quantised value (an exact 24-bit value, so no driver tie rounding is left), - so the texture reads back as D3D's quantisation of the clear value. The scratch buffers and descriptors live - until the submission that used them completes. A copy larger than the device's `maxStorageBufferRange` (128 MiB at - least) is split into several dispatches, by slices or by rows of one slice. The dispatch runs even under a - `SetPredication` that would skip copies: the layer runs copies unpredicated (section 4.7) and the conversion - must go with them, so conditional rendering is ended around it. The D3D11.3 functional spec (3.2.3.6, FLOAT to - UNORM) says: NaN is 0, the value is clamped to 0..1, multiplied by 2^n - 1 in float, 0.5 is added and the - fraction dropped, with a tolerance of 0.6 ULP on the integer side; read literally a tie rounds up, and 3.2.2 - lists this conversion as an exception to round-to-nearest-even without fixing ties. WARP and AMD's D3D12 driver - were measured to round the float product to nearest even (2.5 gives 2, 0.5 gives 0), which the tolerance - allows; NVIDIA's D3D12 driver (and a native D24 clear in its Vulkan driver) breaks some of those ties the other way; - the layer follows WARP and AMD there, a measurement and not a rule of the spec. **Draws** (D3D-309, - `src/depth24_fragment.h`): a single-sampled graphics pipeline with depth enabled and a D24 DSV stored as D32 has - its pixel stage write `FragDepth = quantise(z + bias)`, with D3D's bias in D24 units (`DepthBias / (2^24 - 1) + - SlopeScaledDepthBias * max(|dz/dx|, |dz/dy|)`, clamped by `DepthBiasClamp`) and the same quantisation as - `depth24_convert.comp`, so depth tests and stored depth match D24; the rasteriser's bias is off for these - pipelines (so a clamp needs no `depthBiasClamp` there). A pipeline without a pixel shader, with or without a - geometry shader, gets a built-in one; a shader that writes its own depth has it quantised, unbiased, as in D3D. The slope comes from the derivatives of the - interpolated depth, so a slope-scaled bias can land up to two 24-bit steps from D24 hardware's plane-exact one - (`d3d12_depth24_draw_test`). Not covered: multisampled targets (a `FragDepth` write is per pixel; they keep float - bias and precision, logged), pixel shaders with `EarlyFragmentTests` (which ignore a `FragDepth` write; logged), a - viewport depth range narrower than the biased depth (D3D clamps before quantising), and early depth testing, which - a `FragDepth` write turns off for these pipelines. A depth texture sampled in a shader still sees the float. - `ResolveSubresource` becomes `vkCmdResolveImage` in the same layouts as a copy: a multisampled colour - subresource into a single-sampled one of the same size and format. Integer colour formats in the requested - format or either resource are refused at recording; `Close` fails. `ResolveSubresourceRegion` uses the same - Vulkan operation for non-integer colour with average mode, taking a source rectangle (or the entire subresource) - and a destination offset. A `ResolveSubresourceRegion` of one depth or stencil plane (the subresource's plane - slice, the same on both sides) runs in a rendering scope of its own with no draws: the multisampled plane is the - depth or stencil attachment (load `LOAD`, store `NONE`), the destination its resolve target with the mode, the - render area the source rectangle. Both move from their resolve layouts to `DEPTH_STENCIL_ATTACHMENT_OPTIMAL` and - back around it; the destination's other plane is not attached and keeps its contents. A rectangle smaller than the - subresource has the texels around it copied into a scratch buffer before the scope and back after it, on every - GPU: Vulkan resolves only inside the render area, but MoltenVK (1.4.2 and 1.4.3, Apple M3 Max) resolves the whole - destination subresource, because it resolves through Metal's store action, which has no render area. Measured - with a raw Vulkan program (a 4x D32 attachment, render area (2,1) 5x4 of 8x6, `MIN`, `MAX` and `SAMPLE_ZERO`, - store `NONE` or `STORE`): MoltenVK writes all 48 destination texels, KosmicKrisp only the 20 inside. No device - property reports it, so nothing is gated. The format is the depth - format or the plane's own (`R32_FLOAT`, `R24_UNORM_X8_TYPELESS`, `X24_TYPELESS_G8_UINT`, and for D32S8 - `R32_FLOAT_X8X24_TYPELESS` and `X32_TYPELESS_G8X24_UINT`; all compared with the PC runtime, TEST-847). A depth-only source above array layer 0 is resolved in a - `VkRenderPass` with a framebuffer of the same two views instead of the rendering scope, on every GPU (D3D-417, a - driver workaround): AMD's Windows driver (32.0.21042.62, Ryzen 7 9700X iGPU) resolves a dynamic-rendering depth - attachment from layer 0 of the image when the multisampled view starts at another layer, while it honours the - resolve view's first layer. Measured with a raw Vulkan program on a 4x D32 image of four layers: a layer range - cleared with `vkCmdClearDepthStencilImage`, a `CLEAR` load or `vkCmdClearAttachments` reads back right through a - `texelFetch` of every sample, through a resolve of all four layers in one scope and through a copy of the layer - into a one-layer image that is then resolved, but a one-layer view resolved in a rendering scope gives layer 0 - for every layer (view type `2D` or `2D_ARRAY`, store `NONE` or `STORE`), and views of layers 1-3 resolved in one - scope give layers 0-2. The render pass gives the right layer there; an RTX 3070 (610.74) does in every variant. - `d3d12_view_slices_test` reads a 4x D32 array back slice by slice. A depth-stencil source above layer 0 still - uses the rendering scope, because its two planes can be in different layouts, which the render pass's attachment - description cannot say without the planes' layouts at recording; a 4x D24S8 or D32S8 array is still read back - as its slice 0 on that driver (measured). The format is the depth - format or the plane's own (`R32_FLOAT`, `R24_UNORM_X8_TYPELESS`, `X24_TYPELESS_G8_UINT`, and the D32S8 pair, untested). - What the PC runtime accepts was measured on an RTX 5070 (driver 621.24) and on WARP: `MIN` and `MAX` of either - plane by either format, and `AVERAGE` of the depth plane by its own format only (its `Close` fails for `AVERAGE` - by the depth format or of stencil); the layer accepts the same. WARP is no reference for two of them: a resolve - with the format `D32_FLOAT` passes its `Close` but removes the device when run (`DXGI_ERROR_DRIVER_INTERNAL_ERROR`), - and a one-plane D24S8 resolve writes both planes; the RTX 5070 resolves only the plane named. A scope resolves each pixel in place, so a - destination offset other than the source rectangle's corner is refused, as is a mode missing from the device's - `supportedDepthResolveModes`/`supportedStencilResolveModes` (queried at device creation; one plane per scope, so - `independentResolve` never applies). Refused calls fail `Close` and record nothing. `d3d12_depth_resolve_test` - compares D32, D24S8 and D32S8 resolves (typed and typeless resources, whole and rectangle) with the PC runtime and - WARP. Its edge cases (TEST-848) draw a triangle over the cleared 4x source first (depth 0.5, stencil 0x44): the - pixels on its diagonal edge hold differing samples, and MIN, MAX and AVERAGE over them match the PC runtime on an - RTX 5070 (driver 621.01) and WARP byte for byte. `DECOMPRESS`, - `ResolveSubresource` of depth (which D3D12 does not offer) and resolves between two formats of one typeless family - remain open. A multisampled texture copies only to one with the same sample count - and has no footprint. - Discards, immediate writes and atomic copies replay as section 4.2 describes. -- **UAV clears** (`ClearUnorderedAccessViewUint` / `ClearUnorderedAccessViewFloat`). The CPU handle's slot is read - while recording as the GFX10 descriptor a shader would load (section 3.4), so the clear works with any - view-creation code that writes them and with descriptors the game builds itself; the GPU handle is not needed. - A T# gives the view's format (FORMAT plus DST_SEL, which tells BGRA from RGBA), mip and layers; a 3D view clears - every slice of its mip. A V# gives a byte range: its address minus the resource's `GetGPUVirtualAddress`, and - NUM_RECORDS bytes (stride 0, no format: raw), records (a stride: structured) or elements (a format: typed). A view - that reaches past the end of the buffer stops there, as the hardware's bounds check would. - - Values follow D3D's rules (`runtime/src/uav_clear.h`): Uint copies the low bits of each value into its channel - with no conversion, whatever the format's type; Float converts (UNORM/SNORM clamp and round to nearest, NaN is - 0; 16-bit and the packed 11/10-bit floats round to nearest even). A raw or structured view takes value 0 for - every 32-bit word (Float: its bits). D3D11 calls Float on an integer view invalid and D3D12 does not say; here - the value is converted (toward zero, clamped, NaN 0) so the result is defined. These are checked against - hand-computed elements in `d3d12_uav_clear_test`. - - Buffers: elements of up to 4 bytes repeat in every aligned word, so `vkCmdFillBuffer` writes the aligned middle - and `vkCmdCopyBuffer` copies the unaligned ends from it (an 8-bit view at an odd offset, say). 8- and 16-byte - elements are written with `vkCmdUpdateBuffer` (up to 64 KiB) and doubled with copies. A rectangle is an - element range `[left, right)` on row 0. If a range contains no complete aligned word, prepare reserves eight - transfer-scratch bytes, retained until submission completion. Replay fills that scratch with the repeated - element and copies only the requested bytes, preserving neighbouring bytes even at resource boundaries. - Rectangles within one clear reuse that pattern with transfer dependencies between them. Ownerless replay - callers without `copy_scratch` still refuse these short ranges before emitting anything. - `d3d12_short_uav_clear_test` compares Uint/Float whole-view and clipped/overlapping rectangle clears against - WARP (CTest) or `LEONIDA_HOST_ADAPTER` (manual runs), checking the entire buffer against literal patterns. - Portable native comparisons keep rectangles on row 0. Out-of-row controls run separately against WARP: - NVIDIA D3D12 was observed to ignore Y where WARP and AMD preserve the buffer, so those controls do not assert - that native drivers behave uniformly. This test distinction does not change the replay policy. - Portable UNORM Float clears use `0.25f` (R8: `0x40`, R16: `0x4000`), away from a conversion midpoint; - `0.5f` remains covered by separate WARP-only midpoint controls. Native NVIDIA was observed to clear that - midpoint to `0x7f`/`0x7fff` where WARP and AMD give `0x80`/`0x8000`. All comparisons remain byte-exact. - - Textures: the values become one element of the view's format, and that element is cleared into the image as - the value that decodes it in the image's own format, so a typeless texture viewed as UINT gets exactly the bits - asked for. Exact for every typed-UAV format except the SNORM pattern `0x80..` (Vulkan writes -1.0 as `0x81..`) - and NaN payloads. A whole view is `vkCmdClearColorImage`; rectangles are `vkCmdClearAttachments` in a - dynamic-rendering scope, so a texture created with `ALLOW_UNORDERED_ACCESS` also gets `COLOR_ATTACHMENT` usage - when its format supports it. Both run in place in `GENERAL`, the UAV layout. Rectangle clears of volumes, or of - formats without attachment support, are refused as `unsupported`. - - The clear is fenced as the UAV state widened to transfers, so a following UAV barrier, transition, or enhanced - barrier from `SYNC_CLEAR_UNORDERED_ACCESS_VIEW` sees it. - - Under `SetPredication`, a whole-view texture clear runs as one rectangle through the attachment path, as - render-target clears do, so conditional rendering applies. Buffer clears, and texture clears that cannot use an - attachment, are transfers that conditional rendering does not cover; they run unconditionally and are counted - with the copies (`unpredicated_copies`). -- **Layout tracking** (`LayoutTracker`): the current Vulkan layout of every image subresource, so barriers start - from the real layout instead of the application's `before`. This is how implicit promotion and decay work: a - texture in `COMMON` sits in `GENERAL`, which every promotable access can use, so a later barrier naming the - promoted state still starts from `GENERAL`, and decay changes no layout. Buffers have no layout, and - simultaneous-access textures stay in `GENERAL` for life. With `separateDepthStencilLayouts` the depth and stencil - planes are tracked apart, so a depth-only clear or a one-plane transition leaves the other plane where it is. -- **Execution** (`runtime/src/vulkan_backend.h`): `VulkanContext` (registered resources, the tracker, a view cache), - `VulkanQueue` (`ExecuteCommandLists` prepares every list before writing any, so a bad list submits nothing and - leaves the tracker as it was; `Signal`; `Wait`, which is attached to the next submission because a Vulkan wait - only holds back its own batch) and `VulkanFence` (a timeline semaphore). -- **COM** (`runtime/shims/d3d12_com.cpp`): `ID3D12GraphicsCommandList8` (the GCL7 chain plus - `OMSetFrontAndBackStencilRef`), `ID3D12CommandQueue`, `ID3D12CommandAllocator` and `ID3D12Fence1` (with - `SetEventOnCompletion` events). Every method they do not implement is a stub generated at build time from the - SDK's `d3d12.h` by `tools/gen_d3d12_stubs.py`. The stub reports its name once, so the vtables follow the SDK - order exactly and nothing derived from the SDK is checked in. Unknown IIDs are logged and refused. Resources - are identified by their `ID3D12Resource` pointer, and RTV/DSV CPU handles point at a `TargetView`. - `OMSetFrontAndBackStencilRef` records its two `UINT`s on the list (and `Reset` clears them), but nothing applies - them yet: Vulkan can set the faces with `vkCmdSetStencilReference` and a face mask, but only a pipeline that - consumes the dynamic state can, and this layer has no pipeline or draw path. -- **Device** (`runtime/shims/d3d12_vulkan_device.cpp`): an `ID3D12Device11` (PC ABI, 80 slots) that the Xbox-ABI - proxy (`d3d12_xs_device.cpp`) forwards to, so slot 14's heap-handle conversion and slot 76's resource creation - work unchanged. It creates the objects above, plus: - - descriptor heaps whose slots are 32 bytes (`GetDescriptorHandleIncrementSize`; the console's increments are - question 4). RTV/DSV slots hold a `TargetView`; shader-visible heaps return a GPU handle, but nothing reads it - yet; - - `CreateRenderTargetView` / `CreateDepthStencilView` for whole resources, `TEXTURE1D`, `TEXTURE1DARRAY` (D3D-63), - `TEXTURE2D`, `TEXTURE2DMS`, `TEXTURE2DARRAY` and `TEXTURE2DMSARRAY` (a slice range; `ArraySize` -1 is every - slice from the first on, as on the host, `d3d12_view_slices_test`); - - `CopyDescriptors` / `CopyDescriptorsSimple`. A descriptor is the bytes of its slot, so a copy is a byte copy: - the destination and source range lists are walked together, one descriptor at a time, and null size arrays - mean one descriptor per range; - - committed buffers (upload and readback heaps mapped persistently and zeroed), 1D textures and 1D arrays (render - targets and depth-stencils too: their attachment views are `VK_IMAGE_VIEW_TYPE_1D_ARRAY`), and - 2D textures in the common render-target, depth and texture formats (typeless families become mutable-format - images; `R24G8_TYPELESS` and `R32G8X24_TYPELESS` are depth-stencil images with or without - `ALLOW_DEPTH_STENCIL`, as Vulkan has no colour format with their layout), plus non-attachment 3D textures with - mipmapped upload, image copy and readback, and multisampled 2D textures (single-mip render targets or - depth-stencils, in the sample counts the GPU has for the format); - - packed `R9G9B9E5_SHAREDEXP` textures map to `VK_FORMAT_E5B9G9R9_UFLOAT_PACK32` for uploads and sampled views. - When `ALLOW_UNORDERED_ACCESS` is requested on a GPU whose `VK_FORMAT_E5B9G9R9_UFLOAT_PACK32` lacks native - `STORAGE_IMAGE` support (for example NVIDIA), the layer backs the texture with a mutable `VK_FORMAT_R32_UINT` - image (`MUTABLE_FORMAT | EXTENDED_USAGE` + `VkImageFormatListCreateInfo` `{R32_UINT, E5B9G9R9_UFLOAT_PACK32}`), - refusing `ALLOW_RENDER_TARGET`, `ALLOW_DEPTH_STENCIL` and `DENY_SHADER_RESOURCE`: `CheckFeatureSupport` advertises - `TYPED_UNORDERED_ACCESS_VIEW` and `UAV_TYPED_STORE` (plus `UAV_TYPED_LOAD` with `R32_UINT` storage atomics) while - keeping `RENDER_TARGET` off; SRV and UAV descriptors emit the `E5B9G9R9` T# (`FORMAT 132`, RGB1) and reject - incompatible casts, while set 0 creates a `VK_IMAGE_USAGE_SAMPLED_BIT` `E5B9G9R9` sampled view and a - `VK_IMAGE_USAGE_STORAGE_BIT` `R32_UINT` storage view (bound in `as_uint` / `r32ui`, never `as_float`); - `ClearUnorderedAccessViewFloat` packs RGB9E5 with round-half-up (clamping negative/NaN to 0 and +Inf/overflow to - 65408, bumping on 512) and `ClearUnorderedAccessViewUint` writes 0, matching WARP (`d3d12_r9g9b9e5_uav_test`, - `d3d12_uav_clear_test`); - - the descriptor shader samples `B5G5R5A1_UNORM` through a 2D SRV. Opaque and transparent red check bit 15, - and mixed-channel texels check the five-bit color fields; - - `B5G5R5A1_UNORM` with `ALLOW_UNORDERED_ACCESS` on a GPU whose `VK_FORMAT_A1R5G5B5_UNORM_PACK16` lacks - `STORAGE_IMAGE` (for example NVIDIA) is backed the same way, by a mutable `VK_FORMAT_R16_UINT` image with - `{R16_UINT, A1R5G5B5_UNORM_PACK16}` in its format list (`Format::uint_backed`). Unlike `R9G9B9E5`, render - targets are kept: RTVs and clears go through an `A1R5G5B5` attachment view, SRVs through an `A1R5G5B5` - sampled view, and the UAV's storage view is `R16_UINT` in `as_uint`. SRV and UAV descriptors name the texture's - own T# format (`1_5_5_5_UNORM`, 134), so a shader store needs the translator to pack the 5-5-5-1 bits for that - view; until it does, `CheckFeatureSupport` does not advertise the typed UAV. Multisampled UAV textures are still - refused (`d3d12_b5g5r5a1_uav_test`); - - `R8G8B8A8_UNORM_SRGB` and `B8G8R8A8_UNORM_SRGB` with `ALLOW_UNORDERED_ACCESS`, which the host runtime sizes and - creates (RTX 4090 and WARP) and a retail title sizes as a 2048x2048, 12-mip render target, on a GPU whose sRGB - format lacks `STORAGE_IMAGE` (most): a mutable image of the UNORM format of the same order, with both formats in - its format list (`Format::uint_backed`). Its storage view is UNORM, as every D3D12 typed UAV of these textures - is, so shaders and `ClearUnorderedAccessViewFloat` write raw bytes; RTVs and SRVs are sRGB, so clears and - rendering encode and sampling decodes. BGRA8 needs `B8G8R8A8_UNORM` storage. Both clears match WARP byte for - byte; multisampled ones are still refused (`d3d12_srgb_uav_test`); - - `B8G8R8X8_UNORM`, `_UNORM_SRGB` and `_TYPELESS` (D3D-87) are `B8G8R8A8` images: clears, copies and footprints - keep all four bytes (WARP writes the clear's alpha into the X byte too), and shader views read alpha as 1. Its - typeless family is its own, so views to or from `B8G8R8A8` are refused, unless the texture's castable-format - list names the view's format (relaxed casting, which WARP and AMD's D3D12 driver accept both ways). The view's - format then decides the alpha: a `B8G8R8X8` view of a `B8G8R8A8` texture reads 1, a `B8G8R8A8` view of a - `B8G8R8X8` one the stored byte. It decides the channel order too: an `R8G8B8A8` texture whose list names - `B8G8R8A8` or `B8G8R8X8` reads red and blue swapped through those views, as on the host (both orders share one - T# format code, so the T#'s swizzle carries the order). An RTV in a format the list names stores clears and - draws in the view's channel order and encoding, as on the host (see the castable-list RTVs under D3D-275 below). - As on the host runtime, the family has no typed UAV, and a typed `B8G8R8X8` - texture cannot allow unordered access (the host accepts one whose castable-format list names `B8G8R8A8`; the - layer doesn't yet). Blending into a `B8G8R8X8` render target reads destination - alpha as 1, as WARP and AMD's D3D12 driver do: the PSO turns `DEST_ALPHA` into `ONE`, `INV_DEST_ALPHA` into - `ZERO` and the colour `SRC_ALPHA_SAT` into `ZERO`, where the BGRA8 image would read the X byte. What a draw - leaves in the X byte is not defined (WARP writes 0, AMD the blended alpha), and no view reads it; - - `R10G10B10_XR_BIAS_A2_UNORM` maps to `VK_FORMAT_A2B10G10R10_UNORM_PACK32`, the same packed 10:10:10:2 - layout; the bias and scale are the application's shader work. Like the PC runtime, it accepts only a - single-mip, single-sample 2D texture: extra mips, multisampling and 3D are refused in creation, allocation - and footprints. Format support reports `TEXTURE2D` and `CAST_WITHIN_BIT_LAYOUT`, not the host's display, - back-buffer-cast or video-processor bits; - - `CheckFeatureSupport` for feature levels (up to 12_1), architecture, D3D12 options (`OPTIONS`, `OPTIONS1`–`5`, - `7`–`9`, `11`–`21`), GPU virtual-address support, format support, format plane counts, multisample quality - levels, shader model, root signature version, predication (`VK_EXT_conditional_rendering`), command-queue - priority support, protected-resource session queries, shader cache, existing heaps, serialization, cross-node - sharing, displayable resources, meta-command queries (`E_INVALIDARG`), application-specific driver state, and - bytecode bypass hash support. `D3D12_OPTIONS8` reports unaligned block textures when the Vulkan logical device - enables BC texture compression, and `D3D12_OPTIONS12` reports `RelaxedFormatCastingSupported = TRUE`, so a - committed or placed texture accepts a castable-format list. Other queries (including `OPTIONS6` and `OPTIONS10`) - are logged and refused until the trace shows what the game asks (question 11); - - Single-sampled `A8_UNORM` 2D textures use one byte per texel in `VK_FORMAT_R8_UNORM`. Their SRVs expose - (0, 0, 0, A) before applying the caller's component mapping. Format support includes `MIP` when the Vulkan - image supports multiple levels. Render-target, depth-stencil and UAV creation are unsupported for this format. - - reserved resources and `GetResourceTiling` (section 4.2); - - query heaps for occlusion, timestamps and pipeline statistics, and `GetTimestampFrequency` on the queue - (section 4.6); - - `GetCopyableFootprints` for buffers, 1D and 1D-array textures, 2D textures and volumes, including BC1–7 and the - two-plane depth-stencil formats. - The test compares every output with the PC runtime's; that comparison found that planar - depth-stencil rows are padded to 512 bytes, not 256, and that subresources are aligned to 512 bytes counting - from `BaseOffset`, not from 0: the PC runtime moves the whole layout by the base, so an unaligned base (513, - 2^32 + 1) keeps the same relative offsets and the same total (measured on an AMD Radeon RX 7600, drivers 26.11.1 - and 26.11.2, Windows 10 in-box runtime; aligning from 0 gives mismatching offsets and totals at both unaligned - bases and none at 0 and 1024, which is why it went unnoticed). - - the `1`/`2`/`3` variants as wrappers over the methods above (D3D-28): `CreateCommittedResource1/2/3`, - `CreateCommandQueue1` and `GetCopyableFootprints1`. `D3D12_RESOURCE_DESC1` drops to `D3D12_RESOURCE_DESC`, - and the initial state or `D3D12_BARRIER_LAYOUT` is not used, because new textures start `UNDEFINED` and move - on first use. The newer arguments are answered as the PC runtime answers them. `d3d12_method_variants_test` - compares each answer below with the host runtime live, measured on an RTX 4090 (driver 621.14): - - `CreateCommandSignature` (`ID3D12CommandSignature`) and `ID3D12GraphicsCommandList::ExecuteIndirect` (including - GPU-written `CountBuffer` via Vulkan 1.2 core `vkCmdDrawIndirectCount` / `vkCmdDrawIndexedIndirectCount`). - - Optional `VK_KHR_acceleration_structure` + `VK_KHR_deferred_host_operations` + `VK_KHR_ray_query`: - `ID3D12Device5::GetRaytracingAccelerationStructurePrebuildInfo`, `ID3D12GraphicsCommandList4::BuildRaytracingAccelerationStructure` - (BLAS + TLAS), `vkGetBufferDeviceAddress` in `ID3D12Resource::GetGPUVirtualAddress()`, and RT-aware `UAV` - barriers (cleanly disabled/skipped on GPUs without RT). - -- **DXGI Swapchain** (`runtime/shims/dxgi_swapchain.h`, `runtime/shims/dxgi_com.{h,cpp}`): `IDXGIFactory4` and - `IDXGISwapChain3` over `VK_KHR_win32_surface` + `VkSwapchainKHR`, exposed via `rt::d3d12::create_dxgi_factory`. - Swapchain backbuffers are real `ID3D12Resource` COM objects (`BackBufferResource` inheriting from - `ID3D12ResourceStubs`) registered directly with `VulkanContext`, supporting `CreateSwapChainForHwnd`, - `GetCurrentBackBufferIndex`, `GetBuffer`, `CreateRenderTargetView`, `Present`, and `ResizeBuffers` (preserving - explicit buffer dimensions even when the HWND client size is unchanged via an offscreen backbuffer + blit path, - and exposing exactly the requested `BufferCount` even when Vulkan's native image count differs, in which case the - offscreen ring is the app-visible swapchain and each present blits the current slot into the acquired image). - The factory answers up to `IDXGIFactory7` (D3D-2). `EnumAdapterByGpuPreference` returns the one Vulkan adapter - at index 0 for every preference. It accepts a preference outside the enum, as the host does, and gives - `DXGI_ERROR_INVALID_CALL` for a null `out` and `DXGI_ERROR_NOT_FOUND` past the end. The adapter list never - changes, so `RegisterAdaptersChangedEvent` never signals its event. It still gives the host's answers: a null - event or cookie, or an event that is already registered, is `DXGI_ERROR_INVALID_CALL`. Cookies start at 1 and - are separate from the occlusion cookies, and an unknown cookie is `DXGI_ERROR_NOT_FOUND`. All of these were - measured on the host's `dxgi.dll` (Windows 11, RTX 3070) and are checked in `dxgi_swapchain_test`. - explicit buffer dimensions even when the HWND client size is unchanged via an offscreen backbuffer + blit path, - and exposing exactly the requested `BufferCount` even when Vulkan's native image count differs, in which case the - offscreen ring is the app-visible swapchain and each present blits the current slot into the acquired image). - - | Argument | Answer | - |---|---| - | a protected resource session | `E_INVALIDARG`; the layer reports no `D3D12_FEATURE_PROTECTED_RESOURCE_SESSION_SUPPORT` | - | `SamplerFeedbackMipRegion` on a texture | `E_INVALIDARG` from `CreateCommittedResource2/3`; `GetCopyableFootprints1` returns its failure answer (every output all ones) | - | `SamplerFeedbackMipRegion` on a buffer | ignored | - | a buffer's initial layout other than `UNDEFINED` | `E_INVALIDARG` | - | a castable-format count with a null list | no list (`S_OK`) | - | a castable-format list | accepted on a texture when the formats map to Vulkan formats: the image is mutable and carries a `VkImageFormatListCreateInfo`; a buffer or an unmapped format is `E_INVALIDARG`. A cast whose texel size differs from the resource's is also `E_INVALIDARG` — the host refuses other sizes, and a size-mismatched format list is a Vulkan validation error (`VUID-VkImageCreateInfo-pNext-06722`). The list is kept on the resource, so an SRV whose format is neither the resource format nor in the list leaves a null descriptor. The resource's own format is always accepted and is added to the Vulkan format list when the D3D12 list omits it. A listed same-size cross-family cast, such as `R8G8B8A8_UINT` to `R32_UINT`, is accepted. An RTV in a listed RGBA8 family format on a typed `R8G8B8A8_UNORM` texture clears through the cast, the same reinterpretation a typeless RTV uses; without a list a typed resource still refuses a different-format RTV. `D3D12_OPTIONS12` reports `RelaxedFormatCastingSupported = TRUE` (this layer requires Vulkan 1.3, where the format list is core). `CreatePlacedResource2`'s list reaches its placed image through the same rules (D3D-90) | - | `CreateCommandQueue1`'s creator ID | ignored | - - `CreatePlacedResource1/2` wrap the placed path above; `2` carries the castable-format list. `CreateHeap1` - remains a stub. - - `CreateSampler2` as a wrapper over `CreateSampler` (D3D-28, part 2). Without flags it writes the same S#. - `D3D12_SAMPLER_FLAG_UINT_BORDER_COLOR` reads the union as integers. `(0,0,0,0)`, `(0,0,0,1)` and `(1,1,1,1)` - take the S#'s transparent-black, opaque-black and opaque-white types. The S# has no separate integer types, - since the hardware reads them by the image's format. Vulkan does not: an integer image sampled with a - `VK_BORDER_COLOR_FLOAT_*` border reads 0. Vonsek found this on an RTX 5080 (#538), and `d3d12_descriptor_test` - reproduces it on an RTX 4090 when the layer uses the float enums. So the layer marks an integer border in the S# - with `BORDER_COLOR_PTR = 0x800` (`gfx10::kIntegerBorderPtr`). The hardware reads that pointer only for a table - colour, and Mesa writes it only for `SQ_TEX_BORDER_COLOR_REGISTER`. The mark gives the integer border its own - key in the descriptor hash table, so it does not share the float border's `VkSampler`, and `vulkan_sampler` - makes it `VK_BORDER_COLOR_INT_*`. Any other colour is a table colour (`BorderColor::table`). With - `VK_EXT_custom_border_color` (D3D-73), the layer registers custom float and UINT border colours in a device-wide - table of up to 4000 entries; the table index is stored in `BORDER_COLOR_PTR [11:0]` of the S#, so distinct custom - colours produce distinct keys in the descriptor hash table and distinct `VkSampler` objects. On sampler creation, - `VkSamplerCustomBorderColorCreateInfoEXT` passes the colour components with `VK_BORDER_COLOR_FLOAT_CUSTOM_EXT` or - `VK_BORDER_COLOR_INT_CUSTOM_EXT` and `format = VK_FORMAT_UNDEFINED` (via `customBorderColorWithoutFormat`). Without - the extension, custom colours fall back to transparent black with a diagnostic log line, using - `VK_BORDER_COLOR_INT_TRANSPARENT_BLACK` for integer borders and `VK_BORDER_COLOR_FLOAT_TRANSPARENT_BLACK` for - float borders to satisfy Vulkan input validation rules on integer views. An integer border colour - with the bits of `1.0f` is not white and receives a table colour index. - `D3D12_SAMPLER_FLAG_NON_NORMALIZED_COORDINATES` sets `FORCE_UNNORMALIZED` (word 0, bit 15) and changes nothing - else; `vulkan_sampler` makes it `unnormalizedCoordinates`. The layer answers `D3D12_OPTIONS17` with - `NonNormalizedCoordinateSamplersSupported` (core Vulkan, with the same restrictions) and no - `ManualWriteTrackingResourceSupported`. That is what the RTX 4090 and WARP report. The runtime on a Radeon 680M - (D3D12 driver 31.0.14084.6002) reports no non-normalized samplers, and leaves every non-normalized description - unwritten, including those the table below says are written. - - A description the PC runtime refuses leaves the slot as it was. The runtime itself does this, without the - debug layer, on the RTX 4090 (driver 621.14) and on WARP; the debug layer's message names the rule. - `d3d12_sampler2_test` compares each row with the host runtime live: - - | `CreateSampler2` input | Answer | - |---|---| - | a null description | the slot is left as it was | - | a flag other than the two | the slot is left as it was | - | non-normalized, with MIN ≠ MAG, a linear MIP filter, anisotropy or comparison | the slot is left as it was; `MINIMUM`/`MAXIMUM` filters are accepted | - | non-normalized, with `AddressU` or `AddressV` not `CLAMP`/`BORDER` | the slot is left as it was; `AddressW` is free, as in Vulkan | - | non-normalized, with `MinLOD`, `MaxLOD` or `MipLODBias` not 0 | the slot is left as it was; `-0` is 0 | - | non-normalized, a point filter with `MaxAnisotropy` or `ComparisonFunc` set | written; both are ignored (the debug layer warns about `ComparisonFunc`) | - | both flags | written | - - BC1–7 textures need `textureCompressionBC`, which the device enables when the GPU has it, as it does - `occlusionQueryPrecise` and `pipelineStatisticsQuery` for the query heaps. -- **Presentation** (`leonida::VulkanPresenter` in `runtime/src/vulkan_present.h`, which - `rt::d3d12::create_window_presenter` makes for a device and a window). This is the part the - `PresentX` front end uses; which of DXGI or `PresentX` the game uses is still open (question 6). It takes a back - buffer, an ordinary texture in the D3D12 `PRESENT` state, and blits it to an acquired `VkSwapchainKHR` image, - scaling when the window size differs. The blit goes on the same `VkQueue` after the application's work, so the - frame contains everything submitted before the present. Details: - - two frames in flight, and a present semaphore per swapchain image; - - FIFO when vsync is asked for, otherwise MAILBOX or IMMEDIATE; with `VK_KHR/EXT_swapchain_maintenance1` the FIFO - swapchain can also present one frame in IMMEDIATE or FIFO_RELAXED (`present(..., tear)`, section 4.5); - - the swapchain is recreated on resize or when the surface reports it out of date or suboptimal, and a minimised - window skips presents; - - a back buffer that was never written is zero-filled like any other texture; - - `presented()` counts the presents the engine took (`VK_SUCCESS` or `VK_SUBOPTIMAL_KHR`), not ones it reported - out of date; - - a recreation is published only when the swapchain, its images and every per-image semaphore exist. On a - failure the partial objects are released and the next present tries again, so no image is acquired without - its semaphore; - - if the blit's submission fails after an image was acquired, an empty batch takes the acquire semaphore and - signals the frame's fence, and the swapchain is recreated next time to get the image back. The next present - therefore does not wait forever on a fence nothing signals. If even that batch fails, or a fence wait or reset - fails, the presenter stops (`ok()` is false) and its owner makes a new one. - - for `PresentX` (section 4.5): a source rectangle, a blank present, an sRGB swapchain format for an sRGB source, - and an optional capture of each presented frame to host memory (what `xbox_present_test` reads back). - - The device needs `VK_KHR_swapchain` (and the instance the surface extensions). The standalone device enables - them when present. - - New textures are not touched at creation. They are tracked as `UNDEFINED`, and the first command that uses a - part of one zero-fills it (D3D12 committed resources start zeroed; `CREATE_NOT_ZEROED` skips this) and moves it - to the layout that command expects, so creation needs no submission. Block-compressed textures are not - zero-filled, because Vulkan cannot clear them; they start undefined until the application uploads them. Each - submission ends with a barrier to the host, so a readback buffer holds the GPU's writes once the fence wait - returns. Children hold a reference to the proxy, not - the inner device, so `GetDevice` always returns the Xbox-ABI object. Each live D3D12 queue leases a distinct - `VkQueue` while one is free (its own type's family first, then the graphics family); the standalone device - requests up to 16 per family. The queues still share a submit lock for - replay state, but Wait-before-Signal between them can make progress (D3D-97), and a batch that waits for a Signal - not yet submitted is held on the CPU so layouts follow dependency order (section 4.4). Caller-owned Vulkan devices can - supply additional handles through `VulkanDeviceInfo::command_queues`; without them they retain legacy single-queue - behavior. When every handle is in use, the new D3D12 queue shares the `VkQueue` that has the fewest D3D12 queues - (section 4.4, "More D3D12 queues than Vulkan queues"); it used to fail with `E_OUTOFMEMORY`. - Dedicated compute/transfer - *families* would also require resource queue-family ownership handling and remain future work. - -Descriptors and the bindless set (milestone M2, without the pipelines that will bind the set), from the shader's -side inwards: -- **`runtime/src/vulkan_bindless.h`**: set 0 includes the twenty bindings the translator declares, and - `DescriptorTable` (`runtime/src/descriptor_table.h`, section 5.1) behind binding 2. One set for the device. - The translator declares every array as a runtime array, so the counts are the runtime's choice. Details: - - The device sizes the arrays once, when it creates the set. It does not recreate the set, because pipeline - layouts are built on `bindless_set_layout()`. `bindless::size_bindings` reads the update-after-bind limits - (`maxPerStageDescriptorUpdateAfterBind*`, `maxDescriptorSetUpdateAfterBind*`, - `maxPerStageUpdateAfterBindResources`, `maxUpdateAfterBindDescriptorsInAllPools`), or the plain limits for a - set without update-after-bind. It starts from the default counts below (4096 sampled 2D images, 1024 - samplers, 1024 2D-array, 256 1D, 256 3D and 256 per storage array). Where a limit is lower, it clamps the - sampler, storage and 2D arrays, in that order, and the device logs it. Next come the MS pairs that fit. Then it - grows the arrays, in the same order, towards the maximums: - - samplers: up to 4096, and at most `maxSamplerAllocationCount` less 64 for samplers outside the set. That - covers a full 2048-sampler D3D12 heap plus room for literal and static S#s. - - 2D images: up to 65536. - - storage arrays: up to 4096 each. - - Growth leaves 64 descriptors of each limit to the other sets of a pipeline layout. It also stays within - `maxPerSetDescriptors`, which never shrinks the default counts, because a layout past it may still be - supported: past it, the device grows only where `vkGetDescriptorSetLayoutSupport` accepts the grown layout. - Intel's UHD 770 (101.7092) reports 6159 and accepts the full sizes, so it gets the same set as an RTX (D3D-219). - MoltenVK (1.4.2 and 1.4.3 on an M3 Max) reports 1212 and accepts only layouts with fewer descriptors than that - (`MVKDevice::getDescriptorSetLayoutSupport` compares the sum with it), although it creates and samples a set of - 65536 2D images and 4096 samplers correctly (a native repro, and `d3d12_descriptor_test` under Wine with the set - grown). So on MoltenVK the D3D12 device doesn't ask: the per-type update-after-bind limits, which MoltenVK takes - from Metal's argument-buffer limits (500000 samplers on an M3 Max), decide alone, and the set grows as on other - GPUs. Where a set still ends up short of a full 2048-sampler D3D12 heap, the device logs that at startup. Past - the last free index, `CreateShaderResourceView` and `CreateSampler` log once that the array is full, and a - shader reads the fallback. `d3d12_descriptor_test` then fills each short array to its last index and checks that - the next view and sampler are refused. - The other arrays keep their default counts. On an RTX 5070 (driver 621.24, 1048576 of each type - and 4000 samplers) the set has 65536 2D images, 3936 samplers and 4096 storage indices in 2D: 93793 - descriptors, 3-6 MiB at 32-64 bytes a descriptor. The device prints the counts it chose, and - `bindless_sizing_test` checks the rules on synthetic limits. - - An image has one index in its dimension (2D, 2D array, 3D, 1D, 2DMS or 2DMS array), shared by the - bindings for that dimension. The runtime adds sampled-image bindings in pairs for 2DMS and 2DMS array: - 20/21 for floating-point and normalized color, 22/23 for unsigned integers, and 24/25 for signed integers. - The runtime enables pairs that fit the device's descriptor limits and have a multisampled zero fallback - of the matching numeric class. A missed key reads zero at texel (0, 0), layer 0, sample 0. - - The storage arrays are shorter (`BindlessSet::storage_capacity`). Each array holds at most as many images - as its dimension, and the 2D r32ui array is the same size as the other 2D storage arrays. So an image with a - storage view gets an index the storage arrays hold, and a read-only one goes above where there is room. - - Index 0 of every array is a fallback (a 1x1 image of zeros, a nearest clamping sampler), because a miss is - index 0. - - Changes are queued and written by `flush()`, one write a slot, so a view that is removed before the next - flush is never written. - - `flush()` also uploads the table to its buffer: device-local memory, written from a mapped staging copy when - the buffers are created (first use or growth) and with `vkCmdUpdateBuffer` for slot changes. Adding a key only - puts a new entry in an empty slot, and the copy of an entry is not atomic; a running lookup that does not know - the key cannot resolve to it, which is accepted. Erasing a key empties its slot and moves no other entry - (every lookup, CPU and shader, compares all eight probe slots and never stops at an empty one), so it is - uploaded like an add. Replacing a live key's index, an insert that relocates a live entry, and a table that - has grown (a new buffer behind binding 2) change what running lookups see: `flush_replaces_table()` says when a - flush would do one of those, and the flush then makes a new generation instead of writing in place (D3D-314; see the - paragraph on the flush at every `ExecuteCommandLists`, below). Erasing used to compact the probe cluster, which - moved other keys and made every texture release wait for the whole GPU. -- **`runtime/src/gfx10_descriptors.h`**: the T#, S# and V# structures (section 5.3), encoded and decoded, with - their mapping to Vulkan formats, view types, component mappings and samplers. Field positions are Mesa's - (`src/amd/registers/gfx10-rsrc.json`) and agree with what the translator and the GPU tests already use. Bits - that only the console's driver could give a meaning (tiling, compression metadata, performance hints) are - written as zero. -- **Device**: `CreateShaderResourceView` and `CreateUnorderedAccessView` of textures write a T# into the slot, - `CreateSampler` an S#; each then makes sure set 0 has the view or sampler and the table has the key. Details: - - The key is the descriptor's bytes, so a copied descriptor needs nothing more, and an unordered-access view - and a shader-resource view of the same mip are one entry. - - A D3D12 comparison sampler with function NEVER and an ordinary sampler both encode zero in the hardware - depth comparison field. The layer marks the NEVER comparison in S# word 3, bit 12 (unused with - DERIV_ADJUST_EN clear) to give it a separate lookup key and a comparison-enabled Vulkan sampler. - - A view the layer cannot show (below) leaves a null descriptor, all zeros, which finds the fallback. - - A typed multisampled color texture has one mip. Its default SRV covers every layer. An explicit - `TEXTURE2DMS` view reads layer zero, while `TEXTURE2DMSARRAY` selects a range starting at - `FirstArraySlice` (`ArraySize = UINT_MAX` selects the remaining layers). The format-support query - advertises `MULTISAMPLE_LOAD` when the format can be sampled with MSAA and its binding pair is available. - - A texture is named in its T#s by an address of its own, above 4 GiB and 256 bytes apart, that nothing - dereferences; its entries leave the set and the table when it is destroyed. - - `VulkanDeviceInfo::bindless` says the Vulkan device has the features this needs: `runtimeDescriptorArray`, - dynamic indexing of sampled- and storage-image arrays, and update after bind for sampled images, storage - images and storage buffers. The standalone device enables them where the GPU has them. - - Every `ExecuteCommandLists` flushes the set before its commands are written. - - `rt::d3d12::bindless_set` and `bindless_set_layout` hand out the set and its layout: what a pipeline whose - shader declares set-0 bindings is created with and binds. Nothing in the layer creates such a pipeline yet. -- **Layouts.** A descriptor in set 0 has one image layout for as long as it lives, but D3D12 lets a texture be - sampled in a shader-resource state and also while promoted from `COMMON`, which is `GENERAL` here (section - 4.3). So with the bindless set, a texture's shader-resource states use `GENERAL` too - (`ResourceBinding::sampled_in_general`), and every descriptor is written with `GENERAL`. This follows from the - Vulkan rule that a descriptor's layout matches the image's; no test here can see it broken, because the - validation layer does not follow which element of a runtime array a shader reads. A depth texture sampled - while it is also bound read-only (`DEPTH_READ` with a shader-resource state) is in - `DEPTH_STENCIL_READ_ONLY_OPTIMAL` and is not handled. - -A typed single-sampled 3D texture can use a default SRV or an explicit `TEXTURE3D` SRV of the same format. -An `R8G8B8A8_TYPELESS` volume supports explicit `R8G8B8A8_UNORM` and `R8G8B8A8_UNORM_SRGB` SRVs. -The sRGB view decodes RGB and preserves linear alpha. A typeless volume requires an explicit typed view. -The T# records the base depth, the view's mip range and `ResourceMinLODClamp`. Binding 6 holds the 3D Vulkan view, -which has one array layer. `d3d12_descriptor_test` checks samples at four W coordinates through two views of the same -volume, plus minimum-LOD clamped views (inside the mip range via `VK_EXT_image_view_min_lod`, at or below -`MostDetailedMip`, and above the last mip). - -Known gaps in the descriptor path: buffer shader-resource views and constant-buffer views (the V# a shader would -load for them; the structure is in `gfx10_descriptors.h`, the views are not written; buffer UAVs of every kind are, -section 3.4 "Buffer UAVs", `d3d12_m4_compute_test` and `d3d12_buffer_uav_test`); -1D-array SRVs, 1D and 3D storage views, other typeless volume formats, multisampled depth/stencil and typeless -color SRVs, and shader-translator lowering for multisample loads. Single-sampled depth-plane views (`R24_UNORM_X8_TYPELESS`, -`R32_FLOAT_X8X24_TYPELESS`) are a T# of the texture's depth format (8_24_UNORM, X24_8_32_FLOAT) through the -depth aspect (the texture's backing format, so X24_8_32_FLOAT for a D24 texture where the layer stores it as -`D32_SFLOAT_S8_UINT`), each on its own family only (the other family's is a null -descriptor, as D3D12 refuses it), and stencil-plane views (`PlaneSlice` 1, as -`X24_TYPELESS_G8_UINT` or `X32_TYPELESS_G8X24_UINT`) are an 8_UINT T# that set 0 shows through the stencil -aspect, in its float-typed sampled arrays like other single-sampled UINT views. Other gaps include descriptors -the game writes itself, which need -the execute-time scan of section 3.4 (only descriptors made through the device are registered); the literal S#s of shaders (`literal_samplers` in the index), -which `rt::d3d12::register_samplers` registers without a heap slot but which nothing passes to it yet (the call at -pipeline creation comes with the shader index, #291); -custom border colours without VK_EXT_custom_border_color, and minimum/maximum filters, anisotropy or mirror-once addressing without the Vulkan -feature, each logged and approximated (note: in Vulkan, `VK_FORMAT_FEATURE_SAMPLED_IMAGE_FILTER_MINMAX_BIT` is -per-format; because bindless set 0 hashes `T#` and `S#` independently in the shader, `bind_sampler` cannot know -which image format a sampler will be paired with — on Radeon iGPUs `BC*` formats lack `MINMAX` while uncompressed -formats support it, whereas RTX supports all queried formats); the storage arrays hold 255 images a dimension at the default counts, more -where the device has room (4095 2D and 1023 2D-array on an RTX 5070); nothing writes through a -storage view in a D3D12-level test yet (`vk_bindless_test` goes through the storage bindings at the Vulkan -level). The set is flushed at every `ExecuteCommandLists`. A flush that moves the table to a larger buffer, changes -the index of a live key or relocates one (`BindlessSet::flush_replaces_table()`) does not write in place and does not -wait (D3D-314; D3D-76 first waited for the whole device, which stalled every queue and would have at every texture -release of a game that churns textures). It makes a new generation: new table buffers (the whole table uploaded to -them in that submission's command buffer), a new one-set descriptor pool and set (binding 2 names the new table, and -every descriptor written so far is written again from a CPU shadow of the set, in runs, so unwritten elements stay -unwritten under `partially_bound`), and replay binds that set at the dispatches and draws of the submission -(`ReplayFunctions::bindless_set`; the pipelines' own `bindless_set` only marks that they use one). Submissions made -before keep reading the old set and table, which nothing writes again. The old generation is stamped with the -latest submission ticket and freed at a later `ExecuteCommandLists` (and at device teardown) once -`completed_retire_ticket()` has reached it. Those tickets are the layer's per-submission records of (queue timeline -semaphore, value): the stamp is therefore the latest submitted value of every queue that could have bound the -set, and the free waits until each of those timelines has passed its value; nothing is waited for. The completed -prefix is global and in order, so a queue blocked on a fence only delays the free, never another queue. The stamp -is taken under `tracker_mutex_`, which `execute()` holds from the flush to the end of its submit, so no submission -that bound the old set is unsubmitted when it is read. `LEONIDA_BINDLESS_IDLE_WAIT=1` restores the old wait -(a counted `vkDeviceWaitIdle` before the flush) to compare frame times; nothing else uses it. The cost of the new -path is a full upload of the table and a rewrite of the set's descriptors per replacing flush, where the old one -uploaded the changed slots after the stall; `d3d12_bindless_churn_test` prints both. - -The pattern is the one vkd3d-proton uses to retire GPU-visible objects without a device idle (approach only, no -code taken): stamp the object with what every queue has submitted and free it at a later submit once those -submissions have completed. Two further rules come with it here. The submission that carries a new generation's -table upload makes every other queue's next submission wait for its timeline value (`bindless_upload_semaphore_`, -like the storage-image initialisation), because that submission is the first to bind the new set and a queue with no -D3D12 fence on it could otherwise run before the copy; the table's buffers need no ownership transfer because every -D3D12 queue of the device is made in `info.queue_family`. And at most 8 retired generations are kept: past that, the -next flush waits (logged once, with the descriptor lock released) for the submissions up to the oldest one's ticket, -which is a wait for those queues' timelines and not for the device. The commit of a submit's result runs under -`tracker_mutex_`, so a later flush never sees an earlier submit's outcome unrecorded. If the new generation cannot be -made (out of memory) the flush leaves the in-use set and the pending writes alone and fails. -Two bindless hazards that vkd3d-proton documents for games and that this change does not remove: descriptors -written for resources allocated after the submit that reads them, and an image and a buffer descriptor aliasing one -heap slot (vkd3d-proton PR #3033, https://github.com/HansKristian-Work/vkd3d-proton/pull/3033). Future path, not -implemented: `VK_EXT_descriptor_heap` (https://www.khronos.org/blog/vulkan-introduces-roadmap-2026-and-new-descriptor-heap-extension) -would replace descriptor sets with application-sized heaps. - -A typed 3D color target supports default and explicit RTVs. The default covers mip 0; `FirstWSlice` and -`WSize` select the depth slices in an explicit view's mip. `d3d12_clear_test --volume` checks full and -rectangular clears of overlapping slice ranges against both Windows WARP and expected RGBA bytes. - -The compute path, end to end: -- `runtime/src/shader_library.h` finds the translated SPIR-V for a shader the game hands to D3D12 (section 3.6). - It extracts the FSSM program from the DXBC container (DXIL → XDAT entry 0x0D → XBCH → zlib) and looks up its - SHA-256 as `fssm_sha256` in `spirv/index.json`. Its own inflate, SHA-256 and JSON reader keep it free of - dependencies (`shader_library_test`). - - A container with two different 0x0D payloads (195 of 26,503) is read at the last one, as - `tools/fssm_unpack.py` does by default and so as `fssm_sha256` was computed. - - Index entries that share a program are all kept (789 groups of 1,182 entries in the corpus). A PSO takes the - first entry that fits (for a VS: whose input signature the input layout feeds) and declares no set-0 - bindings (the cheaper pipeline: a binding-free entry has no set 0 in its layout). - - A malformed index (bad numbers or `\u` escapes) is refused with an error instead of throwing into the shim, - and an integer field outside 0..2^32−1 reads as 0. -- Root signatures use the model already on `main` (`runtime/src/root_signature.h`, `rt::rootsig`): `parse_rts0` - reads the serialized blob and `pack()` lays out the 32 user-data dwords by the section 3.5 default mapping, - refusing anything that would spill. `pack_stage()` lays them out in the console layout of one stage (section 3.5, - D3D-448); the compute bind point uses it. -- **GPU address arena** (section 3.3, when the device has `bufferDeviceAddress`): one host-visible, - device-addressable buffer, 256 MiB by default (`LEONIDA_ARENA_MB`, at most 4095 MiB, so every VA fits 32-bit - table pointers). - - It is also no larger than the device's `maxBufferSize` (Vulkan 1.3) and, counting the buffer's memory - requirement, `maxMemoryAllocationSize` (Vulkan 1.1), whichever is smaller (`runtime/src/arena_size.h`). When a - limit cuts the request, one log line names the limit and the size used. `arena_size_test` (CPU) checks the - decision on synthetic limits; `d3d12_compute_test` checks the arena against the device's limits and a simulated - 32 MiB `maxMemoryAllocationSize`. - - The RX 6800 (RDNA2, AMD driver 26.11.2, Windows 11, measured 2026-11-22) reports 2 GiB for both, so - `LEONIDA_ARENA_MB` above 2048 gets a 2048 MiB arena there. - - Before the cap, that driver did create a 3000 MiB arena. Buffers placed past 2 GiB in it (VA 0x89820000) were - written by a compute shader and read back correctly, but the validation layer reports the allocation as over - `maxMemoryAllocationSize`. Nothing relies on this out-of-spec behaviour. - - The device logs the arena's high-water mark when it is destroyed: the peak end offset against the size, the - most bytes live at once (by use: buffers, descriptor heaps, shaders, heaps), allocations and refusals (D3D-55). - `LEONIDA_ARENA_LOG=1` also logs one line per VA handed out, per refused allocation, and per upload or readback - buffer VA outside the arena. - - Default-heap buffers are 64 KiB-aligned ranges in it, zeroed through its mapping; their console VA is the offset. - - Shader-visible descriptor heaps also live in it: the CPU handle is its host mapping and the GPU handle is the VA, - so descriptor bytes the application writes itself are what shaders load. - - Upload and readback buffers keep their own memory, and their VA is their device address minus the heap base. - - Shader programs (FSSM blobs) are copied in as the code base. -- **`CreateRootSignature`** parses the blob with `parse_rts0` and keeps each parameter's place in two layouts: - `pack()` for the graphics bind point and `pack_stage(Stage::Compute)` for the compute one (from s4, one dword per - table; section 3.5, D3D-448). A signature neither can place (more than 32 user dwords: the spill layout is open; the - translated shaders have no below-base spill-pointer candidates) is refused with both reasons; one only a single layout places is created with a log line, and binding it at the other bind point - invalidates the list. Before - that it answers as the host runtime does (`compare_invalid_arguments`, "root signature:", RTX 5070 / 621.14): - `S_FALSE` for a null output whatever the blob, then `E_INVALIDARG` for a node other than node 0 or a DXBC - container whose size (the dword at +24) is not the size passed. - **`CreateComputePipelineState`** (PC slot 11, Xbox slot 62 through the proxy) finds the shader by its FSSM - hash, builds a pipeline with the 144-byte push-constant range and registers it for replay. Shaders that declare - set-0 bindings get the device's bindless set 0 in their layout and bound at every dispatch (M2); on a device without - that set they are refused with a log. -- **Command list**: `Set{Compute,Graphics}RootSignature` (a different signature clears the arguments, as D3D12 - leaves them undefined; setting the bound one again keeps them, as D3D12 does), `SetPipelineState`, the 32-bit - constant, root view and descriptor-table setters, `SetDescriptorHeaps` and `ClearState`. A wrong parameter type, - out-of-range constants, or an invalid `SetDescriptorHeaps` call makes `Close` return `E_INVALIDARG`. - - `SetDescriptorHeaps` tracks the currently bound shader-visible `CBV_SRV_UAV` and `SAMPLER` heaps and their - arena GPU base VAs, holds references to them until `Reset` or list destruction, unbinds omitted types (clearing - both on `ClearState` and `Reset`), refuses `COPY` lists, > 2 heaps, null arrays/elements, non-shader-visible or - `RTV`/`DSV`/duplicate-type/foreign-device heaps, and enforces bundle matching against the parent list (`parent`'s - currently bound heap for each non-null heap the bundle specifies, `d3d12_set_descriptor_heaps`). - - The list holds a reference to every root signature and pipeline state it is given, until `Reset` or its own - release. D3D12 lets an application release them right after setting them, so the root layout the setters read - and the pipeline `ExecuteCommandLists` looks up must outlive that. Keeping them alive while the GPU runs the - submission stays the application's job, as in D3D12. - `Dispatch` records the block as it is at that moment. Replay binds the pipeline, pushes s0..s31, the heap base - and the code base, and dispatches. -- **Graphics pipelines and draws (M1).** `CreateGraphicsPipelineState` (PC slot 10) finds the VS and PS by FSSM hash. - - **Vertex input:** each input-layout element is matched to the VS input signature by semantic name and index, - and its location is the element's register (the translator's vertex-fetch rule). An input the layout leaves - unfed is refused, as D3D12 refuses it. - - **Fixed-function state:** rasterizer, blend and depth-stencil state map one to one. Viewport, scissor, - topology, stencil references and the blend factor are dynamic, and so are vertex strides when the pipeline has - vertex bindings. A pipeline without them (a full-screen pass from `SV_VertexID`) does not declare the stride - state, since nothing would set it (`VUID-vkCmdDraw-pStrides-04913`). - `d3d12_state_sweep_test` checks the mapping against the host on the same adapter: 482 full-screen draws over - every blend factor pair, blend operation, write mask, comparison function and stencil operation, with the stencil - plane read back, are byte-identical on an RTX 5080 and a Radeon iGPU. - - **Logic ops** come from `RenderTarget[0]`, as in D3D12, and apply to every target (Vulkan has one per - pipeline; it skips float formats). **`DepthClipEnable = FALSE`** is depth clamping: D3D12 clamps output depth - to the viewport's range anyway. - - **Conservative rasterization (Tier 1/2):** the standalone device enables `VK_EXT_conservative_rasterization` - when available; caller-owned devices must set `VulkanDeviceInfo::conservative_rasterization` only if they - enabled it. OPTIONS reports at least Tier 1 only with at least eight subpixel precision bits and a finite, nonnegative - primitive overestimation no greater than `0.5 - 1/512` pixels, leaving half a minimum grid step within the - Tier 1 uncertainty bound. `ConservativeRaster=ON` uses overestimate mode with zero extra overestimation, - including unbound-attachment variants. OFF keeps the ordinary pipeline. Missing support, unknown modes, - wireframe and non-triangle PSOs are refused; conservative TIR (`ForcedSampleCount != 0`) remains `E_NOTIMPL`. - Tier 2 additionally requires `degenerateTrianglesRasterized` and primitive overestimation plus half a - device subpixel step no greater than 1/256 pixel. Other eligible devices retain Tier 1. The standalone - device does not expose Tier 3: the Xbox `SV_InnerCoverage` input mapping has not been confirmed. See - [Microsoft's rules](https://learn.microsoft.com/en-us/windows/win32/direct3d12/conservative-rasterization) - and [Vulkan's properties](https://docs.vulkan.org/refpages/latest/refpages/source/VkPhysicalDeviceConservativeRasterizationPropertiesEXT.html). - `d3d12_conservative_tier2_test` checks the tighter geometric uncertainty bound, post-snap and exact - degenerates with distinct indices, provoking-vertex colour, constant depth, back-facing classification, - culling, indexed permutations, triangle strips, scissor and unbound-attachment variants. On RX 5700 XT - (Windows driver 32.0.21045.5002), 16 tight-bound scenes and 480 degenerate draws pass across Vulkan and native - AMD D3D12. The WARP comparison omits only its pixel-corner fixture: WARP drops that tiny triangle even though - Vulkan and native AMD cover it. `--warp-corner` retains the strict failing software-reference reproducer; - Vulkan always checks the corner. Variable `SV_Position.z` is not a provoking-vertex oracle: both native - references and Vulkan exhibit extrapolation for screen-space degenerates. This test checks constant depth - and separately varying colour, and does not claim a depth-buffer readback or variable-depth conformance. - `d3d12_conservative_raster_test` checks geometric required/forbidden coverage, subpixel/sliver and degenerate - triangles, culling, scissor, 1x/4x MSAA, variants, feature reporting and refusals. Uncertain edge pixels are - allowed to differ. On RX 5700 XT (Windows 32.0.21045.5002), 48 scenario pairs pass on Vulkan and native AMD; - 24 single-sample pairs pass on WARP. WARP's 4x subpixel fixture covers outside the geometric bound; it remains - reproducible with `--warp-msaa4`, separately from CTest's 1x software comparison. Vulkan's 4x oracle remains - strict. On RTX 3060 (Windows 11, NVIDIA 610.88), 48 pairs pass on Vulkan and native NVIDIA. The oracle judges - the layer alone. A native render that fails it is printed as "host not comparable", with its normal and - conservative pixel counts, and that scenario isn't compared with the host. For example, Windows 10's WARP - (`d3d10warp.dll` 10.0.19041, the host CTest selects with `LEONIDA_HOST_ADAPTER=warp`) misses pixel (4,4) of - scene 4 with conservative rasterization on: seen on an RTX 5060 Ti and an RTX 2060 machine, both of which pass - with their NVIDIA GPU as the host (TEST-907). - The GPU test needs the current graphics path's 144-byte push-constant support; CPU capability checks - do not need a GPU. No game-pass usage is claimed by these synthetic tests. - `d3d12_conservative_tier3_reference` is a native D3D12 reference probe, not Tier 3 support in the Vulkan layer. - **Explicit InnerCoverage library contract (experimental):** a caller-owned device can set - `VulkanDeviceInfo::inner_coverage_abi` only for a shader library whose InnerCoverage input is already lowered - to the boolean SPIR-V `FullyCoveredEXT` built-in (false maps to uint 0, true to uint 1). Tier 3 then also - requires all Tier 2 properties and `fullyCoveredFragmentShaderInputVariable`. The default remains false, - including for the standalone device; this is not an inferred FSSM/VGPR layout or automatic game-shader support. - Graphics PSOs inspect the actual SPIR-V capability, even if index capability metadata is absent, and refuse - `FragmentFullyCoveredEXT` with `E_NOTIMPL` before shader-module creation unless the contract and device support - are present. A module using `PostDepthCoverage` additionally requires - `conservativeRasterizationPostDepthCoverage`. The tests use explicit synthetic GLSL; no new translator rule - or retail shader coverage is claimed. - `inner_coverage_oracle` checks false positives, missed interior values and missing invocations on the CPU. - `d3d12_inner_coverage_guards` checks that neither opt-in nor metadata omission can bypass missing support. - `d3d12_inner_coverage_native` checks 48 native D3D12 scenarios on the matching adapter: six triangles, - 1x/4x MSAA, scissor and unbound-target variants. These pass on RX 5700 XT (Windows 32.0.21045.5002) with - Vulkan validation active. `d3d12_conservative_tier3` runs the same 48 scenario pairs on Vulkan and native D3D12 - when Vulkan has the property and native D3D12 has Tier 3; it skips on this RX 5700 XT. The positive Vulkan - path still requires independent execution on a capable GPU. InnerCoverage with conservative rasterization - off is undefined in D3D12 and is not compared. Edge pixels within the uncertainty region are not required - to match byte-for-byte; both backends must independently satisfy the geometric guarantees. - To validate the explicit path, configure with Vulkan SDK/glslang available, build - `d3d12_conservative_tier3_test`, select an adapter with `LEONIDA_VK_DEVICE` if needed, and run - `ctest --test-dir runtime/build -C RelWithDebInfo -R "^(inner_coverage_oracle|d3d12_inner_coverage_guards|d3d12_inner_coverage_native|d3d12_conservative_tier3)$" -V`. - Check that the positive test prints 48 Vulkan/native paired scenarios rather than `Skipped`. - `d3d12_conservative_tier3_reference` remains a native D3D12 reference probe; it does not opt in to that Vulkan contract. - It reports the selected Vulkan device's `fullyCoveredFragmentShaderInputVariable`, matches that device to its - native D3D12 adapter by LUID, then checks the adapter's Tier 3 `SV_InnerCoverage` output on four synthetic - triangles. On Windows with Visual Studio 2022 and Windows SDK 10.0.26100 or newer, run - `.\scripts\run_conservative_tier3_reference.ps1` from the repository root; by default this uses Vulkan's default - adapter. Pass `-Device ` to select a specific one when multiple GPUs are present. It builds only - this test, needs no glslang, and fetches the pinned Vulkan headers only if none are installed. The verbose CTest - output reports the capability and result; it skips if the selected device lacks a matching native D3D12 adapter - or Tier 3. - - **Formats:** dynamic rendering takes the RTV and DSV formats. A draw that leaves a slot unbound for which the - PSO names a format (D3D12 allows it and discards those writes) uses a variant of the pipeline with that format - undefined, built on first use and kept with the PSO. Bit i of the variant key is colour slot i, and bit 8 is - depth/stencil. - - **Instance step rate 0:** every instance reads element 0, done with a stride of 0 for that slot at draw time. - - **Features:** independent blend state, wireframe fill, a depth-bias clamp, SRC1 blend factors, logic ops and - disabled depth clipping need `independentBlend`, `fillModeNonSolid`, `depthBiasClamp`, `dualSrcBlend`, `logicOp` - and `depthClamp`. The standalone device enables those the GPU has and reports them in - `VulkanDeviceInfo::features`. A PSO that needs a missing one is refused with a log. - - **Shader features:** the standalone device also enables `shaderInt64` (declared by 25,803 of 26,503 index - entries), `shaderFloat64`, `shaderInt16`, `shaderClipDistance` and `shaderCullDistance` where the GPU has them. - Without one, `vkCreateShaderModule` reports the capability (`VUID-VkShaderModuleCreateInfo-pCode-08740`). The - index's `features` list is not read yet, so a shader that needs a feature the GPU lacks is not refused up front. - - **Stores and atomics outside compute:** a pixel shader that stores to an image or does an image atomic declares - that storage image without `NonWritable` (of the 1,038 translated 1.0.2.1 modules that contain an image atomic, - counted as modules with an `OpImageTexelPointer` and split by the index's stage, 1,018 are pixel shaders and 20 - compute), - which Vulkan allows only with `fragmentStoresAndAtomics` (`VUID-RuntimeSpirv-NonWritable-06340`); a vertex or - geometry shader needs `vertexPipelineStoresAndAtomics` (`-06341`). The standalone device enables both where the - GPU has them. A graphics PSO whose stage declares writable storage (read off the module's declarations, - `src/spirv_stores.h`) on a device without the feature is refused with `E_NOTIMPL` and a log naming the shader. - `d3d12_stores_atomics_test` checks both under the validation layer. - - **Geometry shaders:** `desc.GS` is the translator's Vulkan geometry stage (docs/design.md, "Geometry - shaders": triangles in, a triangle strip out) between the VS and PS. It needs `geometryShader`, which the - standalone device enables where the GPU has it and reports in `VulkanDeviceInfo::features`; without it such a - PSO is `E_NOTIMPL`. The PSO's topology type must be `TRIANGLE`, the GS's input (`E_INVALIDARG` otherwise). The - push-constant range names the geometry stage only on such a device (`d3d12_geometry_test`). - - **Refused with a log:** hull and domain stages, stream output, MSAA, set-0 bindings, and two stages - that both read their code base (question 14, section 5.2). More than eight render targets is `E_INVALIDARG`. - - **Push constants:** both PSO paths declare the 144-byte block as one range. Its stage flags are the whole - stage table the graphics path accepts, and the replay pushes with the same flags. A device whose - `maxPushConstantsSize` is below 144 (#224's `push_constants_need_fallback`) has every PSO refused, with the - limit in the log, until the uniform-buffer tail exists. - - The command list keeps the input-assembler, viewport, scissor, render-target (read at `OMSetRenderTargets`, as - D3D12 does), blend-factor and stencil-reference state, including CommandList8's front/back references. Each - `DrawInstanced` / `DrawIndexedInstanced` records a copy of that state. A draw with no viewport (never set, or - unbound with `RSSetViewports(0, …)`) or an empty one rasterizes nothing in D3D12. Such a draw is not recorded, - since Vulkan forbids a 0×0 viewport. - - At replay: - - **Buffers:** vertex and index views resolve to buffers by VA (arena or upload). A view that runs past its - buffer is cut at the buffer's end. An unbound vertex slot, or an indexed draw with no index buffer, reads the - arena's reserved first 64 KiB, which is kept zero (stride 0), so it gets the zeros D3D12 gives. - - **Attachments:** they move to attachment layouts through the tracker, and the draw runs in a - dynamic-rendering scope. Its layer count is the smallest layer count of the bound views. - - **Viewport:** it is flipped (negative height), because translated vertex shaders write D3D clip coordinates; - front-face winding then matches D3D12's. - - Only the first viewport and scissor are used, and primitive restart is not modelled yet. - - **Resources and heaps:** - - A buffer of 0 bytes, or one whose size wraps when aligned, is `E_INVALIDARG`. One the arena cannot hold is - `E_OUTOFMEMORY`, and so is a shader-visible descriptor heap the arena cannot hold (in host memory its GPU - handle would be 0). - - If the arena cannot be created, its buffer is released, so other buffers keep their own memory and get no VA. - - With `VK_EXT_conditional_rendering`, the arena is created with the conditional-rendering usage, and - `SetPredication` on a default-heap buffer reads at the buffer's offset in the arena plus the call's offset. - - `CreateHeap` reserves the requested size in the arena at 64 KiB, and a buffer placed in it gets the heap's - place plus the placed offset as its console VA. A placed texture keeps its own `VkDeviceMemory` and a null VA, - 1D, 2D and 3D alike (arrays and mips included), and a dimension outside the enum is `E_INVALIDARG`, as on the - host (RTX 2080 Ti and WARP, `d3d12_placed_dimensions_test`); - tiled (`64KB_UNDEFINED_SWIZZLE` and Xbox `0x101`) 2D/3D placed textures are backed the same way with - tile-multiple `GetResourceAllocationInfo`, `GetResourceTiling`, and host-matched `E_INVALIDARG` checks - (D3D-191). `CreatePlacedResource2`'s castable-format list reaches the placed texture's image as the committed - path's does (D3D-90). `CreateHeap` refuses with `E_INVALIDARG`, as the host does (RX 5700 and WARP, D3D-238), - an alignment other than 0, 64 KiB and 4 MiB, a heap type outside the enum, a custom heap without a CPU page - property and memory pool or a non-custom heap with either, and a heap with all three `DENY_*` flags. It also - refuses `ALLOW_DISPLAY` (committed resources only), as an RTX 4070 SUPER and a UHD 770 host do. It accepts - `HARDWARE_PROTECTED`, as those hosts do, though the `D3D12_HEAP_FLAGS` documentation calls it unsupported. - (D3D-191). Multisampled 2D placed textures (`UNKNOWN` and `4x` tiled) share that backing with host-matched heap - and offset alignment checks (`4 MiB` vs `64 KiB`, `D3D-222`). `CreatePlacedResource2`'s castable-format list - reaches the placed texture's image as the committed path's does (D3D-90). - -Known gaps: set 0 in pipelines (the device keeps the bindless set, but no pipeline declares or binds it yet) and -therefore every translated shader that declares bindings; tessellation, geometry and mesh pipelines, -multisampled pipelines, several viewports, primitive restart; `requiredSubgroupSize = 64` for wave64 compute; -the game's present entry point (`PresentX`; the DXGI factory/swapchain and the presenter above are what it -- **Subgroup size (compute and graphics PSOs).** A translated shader assumes one subgroup size, and a GPU whose - default differs runs it inexact: a wave64 shader reads lanes 32-63 of a 32-wide subgroup, and a wave32 pixel - shader on a 64-wide default reads the other half's lanes (AnyPS5 #487 on RDNA4). `runtime/src/subgroup_size.h` - decides, per stage, from the shader's index entry and what the device offers; the PSO chains the result. - - **Index fields:** `wave64`, `subgroup_size` (64 for wave64, 32 otherwise, `null` when emulated) and - `wave64_exchange` (present: translated with `--wave64-emulate`, exact on any size). - - **Device:** `subgroupSizeControl` and `computeFullSubgroups` are enabled where supported; - `minSubgroupSize`, `maxSubgroupSize`, `maxComputeWorkgroupSubgroups`, `requiredSubgroupSizeStages` (from - `VkPhysicalDeviceSubgroupSizeControlProperties`) and the default `subgroupSize` are kept in - `VulkanDeviceInfo::subgroup` and printed at device creation. - - **Emulated shaders:** nothing is required. - - **Native shaders:** `VkPipelineShaderStageRequiredSubgroupSizeCreateInfo{subgroup_size}` when the feature is - enabled, the stage is in `requiredSubgroupSizeStages`, the size is a power of two in [min, max] and, for - compute and mesh, the workgroup fits in size x `maxComputeWorkgroupSubgroups` (VUID-VkPipelineShaderStageCreateInfo-pNext-02755 - and -02756, VUID-VkPipelineShaderStageRequiredSubgroupSizeCreateInfo-requiredSubgroupSize-02760..02762). - A compute stage also gets `VK_PIPELINE_SHADER_STAGE_CREATE_REQUIRE_FULL_SUBGROUPS_BIT` when - `computeFullSubgroups` is enabled and local size X is a multiple of the size (-flags-02785 for the feature, - -flags-08988 for the stage, -pNext-02757 for X). Wave32 shaders ask for 32 the same way. A device whose only size is the wanted one (NVIDIA, - wave32) needs no chain. Where the size cannot be required (stage not listed, feature off) but the device default is - the wanted one, the shader works as it is (`device_default`; nothing guarantees the default, so it is not logged - as inexact); any other size is `unavailable` and logged. - - **Which stages can be required:** it is the driver's list, not a fixed rule, and AMD's Windows driver gives - different lists for different GPUs, on the same 26.11.2 release too: - - Radeon 880M (RDNA3.5, gfx1150), 26.11.2: FRAGMENT | COMPUTE | TASK | MESH, sizes 32..64, so wave64 and wave32 - pixel shaders run exact there. - - RX 6800 (RDNA2 like the console; gfx1030), 26.11.2 (Windows driver 32.0.21045.29003), measured 2026-11-22: - COMPUTE only, sizes 32..64, default 64 (`vulkaninfo`; the device log says `requirable in stages 0x20`). No - size can be requested for pixel or mesh shaders (`vk_harness` chains none for `VKH_SUBGROUP_SIZE`), and at the - default they run 64-wide: a GLSL probe pixel shader drawn by `vk_harness` counts 64 live invocations per - subgroup (`subgroupBallotBitCount`) on a full-screen draw (SPIR-V 1.5 and 1.6), and `ms_w64x_ballot` (both - halves of a wave64) passes natively. For the translated SPIR-V 1.5 modules, made without - `ALLOW_VARYING_SUBGROUP_SIZE`, the specification fixes `SubgroupSize` at that default ("Varying Subgroup - Size"); only the driver's default could change. So wave64 pixel and mesh shaders work at the default - (`device_default`; the layer has no mesh PSO yet), and a wave32 pixel shader is `unavailable`: two of its - waves share a subgroup. `ps_bitmask_perm` shows it: lanes 0-31 exact, while the - other 2,048 of 4,096 pixels read `v_mbcnt_lo` = 32 instead of their lane (the fixture's check judges lanes - 0-31 only). Of the 1,127 wave32 pixel shaders in the corpus, 1,010 contain a `v_readlane`/`v_writelane`/ - `v_readfirstlane`, 146 a `v_mbcnt`, 105 an `s_bcnt1`/`s_ff1` of a lane mask, and all 1,127 a branch on EXEC - or VCC or an SCC vote on a mask, which the translator decides by a subgroup vote (117 have only those). 926 - also have `v_permlanex16` and row DPP and 826 quad ops, which stay inside a 32-lane half as translated - (`tools/wave32_pixel_scan.py`; counts of candidates, not verdicts). - - Ryzen 7 9800X3D iGPU (RDNA2, gfx1036), Windows driver 32.0.21045.5002: COMPUTE only, sizes 32..64; RX 9070 XT - (RDNA4, gfx1201), Windows driver 32.0.31041.1004: FRAGMENT | COMPUTE | TASK | MESH, sizes 32..64 - (@AC-Storm-YT, `vulkaninfoSDK` from Vulkan SDK 1.4.363.1, - [#313](https://github.com/ItsNotRexed/Leonida/issues/313#issuecomment-7086133354)). The same two lists on - AMD 26.11.2 (Windows drivers 32.0.21045.29003 and 32.0.32029.2010), where `ps_bitmask_perm` also shows the - live fragment width: the gfx1036 iGPU gets the RX 6800's split (2,048 of 4,096 pixels read lane 32), the - RX 9070 XT is exact on all 4,096 (@AC-Storm-YT, - [#3982](https://github.com/ItsNotRexed/Leonida/pull/3982#issuecomment-7088523396) and #4225). - - Current Mesa RADV on GFX10+ lists COMPUTE | FRAGMENT | task/mesh (Mesa main at 152b9cde, - `src/amd/vulkan/radv_physical_device.c`, `requiredSubgroupSizeStages`; older Mesa reported compute only), so - pixel shaders run exact there. NVIDIA lists every stage but only size 32, so a native wave64 shader cannot get 64 - there. Vertex and geometry stages are in neither list. - - **A size the device cannot give** is logged once per stage with the first shader's name (and again at 10, 100, - 1000 shaders of that stage): `[rt] d3d12: () is a 64-wide shader but this device cannot require that - subgroup size ...`. For compute and mesh the fix is the build, `--wave64-emulate` (`make_game.py - --wave64-emulate auto` picks it for this GPU); a wave64 vertex, geometry or pixel shader has no emulation yet - (the ~10,000 wave64 pixel shaders are the open case on NVIDIA, SHADER-10). - - **Test:** `subgroup_size_test` (CPU) checks the decision against AMD-like, NVIDIA-like and old-RADV - properties and the resulting create-info chain; `d3d12_subgroup_test` (GPU) runs `cs_w64x_readlane` natively - and with `--wave64-emulate`, and `cs_wqm_w32`, through D3D12 PSOs and compares the read-back words. - -Known gaps: set 0 in pipelines (the device keeps the bindless set, but no pipeline declares or binds it yet) and -therefore every translated shader that declares bindings; tessellation, geometry and mesh pipelines, -multisampled pipelines, several viewports, primitive restart; subgroup size for mesh pipelines (the decision covers them, no mesh PSO exists to chain it into), and for wave64 vertex, geometry and, on a GPU that cannot require 64 for pixel shaders (NVIDIA), pixel shaders, which have no emulation (SHADER-10); wave32 pixel shaders on a GPU that runs the fragment stage 64-wide and cannot require 32 for it (RDNA2 under AMD's Windows driver, "Subgroup size" above), where two waves share a subgroup; -the game's present entry point (DXGI factory/swapchain or `PresentX`; the presenter above is what either -calls), HDR and fullscreen; buffer and constant-buffer views (UAV clears read the descriptor bytes, so they do -not wait on view creation), typeless volume RTVs, depth-stencil resolves to a destination offset other than -the source rectangle's; -default-heap buffers are not zero-filled yet; a fence cannot be signalled to a lower value (Vulkan timelines only -increase; such a signal is reported and dropped); a CPU `Signal` above a queue `Signal` the GPU has not reached -yet is held until it has (`vkSignalSemaphore` must stay below every pending signal, -`VUID-VkSemaphoreSignalInfo-value-03259`), so `GetCompletedValue` shows it only then, and a fence released -while it holds one drops it; instance step rates above 1 (they need vertex attribute -divisors); read-only DSVs (the depth image always moves to `DEPTH_STENCIL_ATTACHMENT_OPTIMAL`, which matters once -depth SRVs are sampled next to a read-only DSV, M2); the index buffer is bound without its view's size -(`vkCmdBindIndexBuffer2`, Vulkan 1.4, takes one). - -Known gaps found in review, not fixed here: -- **Queues:** every D3D12 queue submits to one `VkQueue`, which runs batches in order. So a queue that waits on a - fence another queue signals later (`B->Wait(f, n)` recorded before `A->Signal(f, n)`) holds back that signal, - and the GPU never progresses (woreksami's probe). Queues on separate Vulkan queues (#306 for copy and compute) - or holding back a batch until its wait value is submitted would fix it. -- **Lookups:** `buffer_at` searches every resource for each vertex and index view; an ordered map by VA would do - when it shows. -- **Fences:** a CPU `ID3D12Fence::Signal` checks only the semaphore's current value, so it can signal below a GPU - signal that is still pending (`VUID-VkSemaphoreSignalInfo-value-03258`). - -Build `runtime/` (Vulkan SDK and Python 3 on `PATH`) and run `ctest --test-dir --output-on-failure` for the -CPU tests: -- `command_list_test` covers the recording rules. -- `d3d12_state_map_test` covers both state tables, subresource and barrier-range decoding, layout tracking, the - subresource ranges `DiscardResource` prepares, Resizable BAR detection, and the memory type order on a no-ReBAR - heap layout. On Windows it also checks every D3D12 constant the IR copies against the SDK's `d3d12.h`. -- `gfx10_descriptors_test` covers the T#, S# and V#: every field alone at its bit position, round trips, what - decoding refuses and ignores, the T#s the image test shaders build, sampler words as radv writes them, and the - format table. `tests/test_gfx10_descriptors.py` compares that table with `tools/gfx10_formats.json`. -- `subgroup_size_test` covers the subgroup-size decision of section 3.2 without a GPU: synthetic index entries - (native and emulated wave64, wave32; compute, pixel, mesh, vertex) against AMD-like (32..64, FRAGMENT | COMPUTE | - TASK | MESH), NVIDIA-like (32 only, every stage) and old-RADV (COMPUTE only) properties, the limits (feature off, - `maxComputeWorkgroupSubgroups`, a size that is not a power of two), and the create-info chain. - -The GPU tests read their results back. With `LEONIDA_VK_VALIDATION=1` they run under `VK_LAYER_KHRONOS_validation`, -and any validation error fails them. -- `vk_command_replay_test`, part A: only Vulkan 1.0 functions and no tracker. -- `vk_command_replay_test`, part B: rectangle clears, a depth clear while the stencil plane is read-only, a promoted - texture, and enhanced barriers including a discard. -- `vk_command_replay_test`, part C: a 4x4x4 volume uploaded from a footprint, copied as a 2x2x2 block and whole, - and read back; a 4x multisampled target cleared and resolved; and the copies and resolves that must be refused - (a z range past the volume or its footprint, a footprint past the buffer, a resolve from a single-sampled - texture or into another size, a multisampled texture copied to a footprint or to another sample count). -- `vk_command_replay_test`, part D: every D3D12 sync bit against every access bit (360 pairs), each as a global, - a buffer and a texture barrier. Under the validation layer none may be rejected; before - `vulkan_barrier_scope` there were 462 validation errors on Intel(R) Graphics. -- `vk_command_replay_test`, part F (D3D-26): `WriteBufferImmediate` in all three modes at console VAs, one of them - in a binding that is a range inside another buffer (as arena resources are); UINT and UINT64 atomic copies - ordered between the writes so that a missing barrier would copy a stale or a later value; a buffer discard - (kept), a texture cleared, discarded and cleared again, and a rectangle discard (kept); and the lists that must - be refused (an address past a binding or in none, no `vkCmdUpdateBuffer`, a copy or dependent range past its - buffer, an unknown dependent resource, a subresource the resource does not have, and an explicit discard count of - `UINT_MAX`, which is a range and not the whole resource). -- `vk_command_replay_test`, part I: a 4x D32 `MIN` resolve of a rectangle; the texels around it must keep the - destination's clear value (MoltenVK overwrote all 28 of them before the scratch copy). It is skipped where the - device has no `MIN` depth resolve (llvmpipe), and without `copy_scratch` the list is refused. -- `d3d12_vulkan_device_test` also runs both atomic copies and the discards through COM, and checks that - `WriteBufferImmediate` is refused at execution while no buffer has a GPU virtual address on `main`. -- `vk_bindless_test` (run by `runtime/test/shaders/check.py` and `scripts/run_gpu_tests.py`): the translator's - own lookup against the table and the set. `ps_tex.asm`, a hand-written RDNA2 pixel shader built by `build.py`, - loads a T# and an S# from a descriptor table and samples. The test draws the gradient with the T# at the fourth - slot probed, the fallback after the key is erased, the gradient again after the table has grown into a new - buffer, another view at the same index, and the fallback after removal, with and without the - descriptor-indexing flags. Last, it draws through a 2D image past 5000 others and a sampler past 2100 others. -- `vk_sampler_test` (run the same way): the S# and T# mip fields as `gfx10_descriptors.h` maps them. `ps_ssharp.asm` - loads a T# and an S# from the heap and samples a 128x128 two-level texture twice, with `image_sample_lz` (LOD 0) - and `image_sample` (LOD 1 at this size). The sampler is `vulkan_sampler(decode(S#))` and the view's levels come - from `decode(T#)`. `check.py`'s `SAMPLER_CASES` cover a point mip filter, MAX_LOD 0, MIN_LOD 1, LOD_BIAS ±1, - MIP_FILTER_NONE with and without MIN_LOD, and a T# whose BASE_LEVEL is 1. Each pixel is judged against levels - worked out from the S# and T# bits in Python, independently of the header. On Vulkan, the sampler's minLod and - mipLodBias apply to an explicit LOD as well. The T#'s MIN_LOD (D3D12's ResourceMinLODClamp) is not covered by - this test. -- **Measured on RDNA2** (SHADER-539): `tools/sampler_lod_probe.py --oracle hw` samples a linear 64x64 R32_SFLOAT - texture with seven levels at its top-left texel. The texture memory is a dword ramp, so each result names the - level it was read from, and a calibration row per level finds the level starts. It runs 43 rows of - `image_sample_l` and `image_sample_lz` on a gfx1036 (Radeon iGPU, Windows 11, AMD 26.10.1, `tools/hw_oracle` - HIP launcher, rocm-sdk-core 10.0.0 clang). wave32 and wave64 gave the same level in every row, and three runs - were identical. - - **The S# fields apply to explicit LODs.** LOD_BIAS (±), MIN_LOD and MAX_LOD apply to `image_sample_l`'s - explicit LOD and to `image_sample_lz`'s LOD 0, bias before the clamp, as radv assumes. MIP_FILTER none ignores - them and reads the view's base level. - - **The T#'s MIN_LOD applies too.** It counts from the resource's level 0, not the view's BASE_LEVEL: BASE_LEVEL - 1 with MIN_LOD 2 reads level 2. - - **Where the hardware is not Vulkan:** - - **Rounding.** The point mip filter's level is floor(lambda + 0.5), so an exact .5 rounds up: LOD 0.5, 1.5 and - 2.5 read levels 1, 2 and 3, and so do S# MIN_LOD 1.5 or MAX_LOD 1.5 and LOD 1 with bias +0.5. Vulkan's - nearest is ceil(lambda + 0.5) - 1, which reads 0, 1 and 2. - - **The T#'s MIN_LOD clamps the still fractional LOD before that rounding.** MIN_LOD 2.25, 2.5 and 2.75 at - LOD 0 read levels 2, 3 and 3. `VK_EXT_image_view_min_lod` raises the integer level to floor(minLod), which - gives 2, 2 and 2. - - **MIP_FILTER none with the T#'s MIN_LOD.** The level is the base raised to floor(MIN_LOD): 2.5 reads level 2, - the same as Vulkan. - - So a host whose Vulkan driver follows the spec's nearest rule reads one level lower than the console on 8 of - the 43 rows: an exact half-level LOD, or a fractional ResourceMinLODClamp. LOD 1.49 reads level 1 on both. The - AMD driver does not follow it. Through the runtime's own path (`vk_sampler_test`, `vulkan_sampler(decode(S#))`), - an S# LOD_BIAS of +0.5 on `image_sample_lz` reads level 1, like the console, on the same gfx1036 and on an RX 7800 - XT (both AMD 26.10.1). So on AMD hosts the S# case matches. On other hosts the result splits: Mesa llvmpipe - (Mesa 23.2.1, LLVM 15.0.7) and an Apple M2 (macOS 26.4, MoltenVK 1.4.2) follow the spec's nearest rule — the - same `vk_sampler_test` S# with LOD_BIAS +0.5 reads level 0 (on the M2 the same explicit `image_sample_lz` with - bias 0 and -0.5 also reads level 0; llvmpipe switches to level 1 at 129/256, for LOD_BIAS and MIN_LOD alike), - while NVIDIA reads level 1, like the console: an RTX 5070 (driver 610.88) switches at exactly 128/256. Intel - is not measured here. - - **Layout.** gfx1036 lays a linear mip chain out smallest level first, each row padded to 256 bytes. Levels 6..0 - of the 64-wide R32 chain start at dwords 0, 64, 192, 448, 960, 1984 and 4032. - - `tests/test_sampler_lod_probe.py` checks the descriptor fields against `check.py` and `gfx10_descriptors.h`, and - the model against these levels, without a GPU. -- `d3d12_com_test`: drives the COM objects through their vtables. It also checks that a queue `Wait` on a fence - the CPU has not signalled holds the GPU back. -- `dxgi_swapchain_test`: creates a Win32 HWND and exercises `rt::d3d12::create_dxgi_factory`, - `IDXGIFactory4::CreateSwapChainForHwnd`, `IDXGISwapChain3::GetCurrentBackBufferIndex`, `GetBuffer` + `GetDesc()`, - backbuffer `CreateRenderTargetView` + clear + readback verification + `Present`, and `ResizeBuffers` with 0 - validation errors. -- `d3d12_indirect_rt_test`: validates `ID3D12Device::CreateCommandSignature` + `ExecuteIndirect` with a GPU - `CountBuffer` (`vkCmdDrawIndirectCount`, `count = 0` skipped and `count = 1` rendered) and optional - `VK_KHR_acceleration_structure` + `VK_KHR_ray_query` (`GetRaytracingAccelerationStructurePrebuildInfo`, BLAS + TLAS - `BuildRaytracingAccelerationStructure`, and a `RayQueryKHR` compute shader verifying hit vs. miss; clean SKIP on - GPUs without RT). -- `d3d12_gcl8_test`: the public `ID3D12GraphicsCommandList8` surface: `QueryInterface` for its IID, - `OMSetFrontAndBackStencilRef(1, 2)` with the recorded values, and the reference count around the query. It - creates only an allocator and a list, so it needs no GPU or Vulkan loader. -- `d3d12_depth_resolve_test`: depth and stencil `ResolveSubresourceRegion` of a 4x D32 or D24S8 target cleared with - three overlapping values, whole and by rectangle, compared with the PC runtime on the layer's own adapter and WARP; - the refused calls must fail `Close` and leave the destination as cleared. -- `d3d12_vulkan_device_test`: the Vulkan device behind the Xbox-ABI proxy, called the way the game will call it. - It creates heaps through slot 14 and reads their start handles in RAX, creates a render target through slot 76 - with the Xbox layout word, then creates views, records clears and barriers, executes and waits on a fence. - Results come back through D3D12 itself (`CopyTextureRegion` into a readback heap, then `Map`): the render - target, the depth and stencil planes, and a never-written texture (which must be zero). A second list uploads a - pattern and copies it on: whole into a texture created in `COMMON`, a boxed part into a smaller texture, a BC1 - round trip, a 1D texture and a 1D-array layer, and a buffer region. A 4x multisampled render target is cleared through a `TEXTURE2DMS` view and - resolved into a texture that is read back; the multisampled shapes D3D12 refuses are refused, and so is a - resolve from a single-sampled texture. `GetCopyableFootprints` is compared with the PC runtime's, and a short - run repeats on a standalone device, the path `LEONIDA_D3D12=vulkan` takes. That standalone run also covers - heaps and placed resources: a castable list on a placed texture is cleared through an RTV in a cast format and - read back against the host's answer, and refused lists match the host's `E_INVALIDARG` (D3D-90). - The comparison tests run against a PC D3D12 device: the layer's own adapter (the default adapter when the Vulkan - device has no LUID or that adapter gives no D3D12 device), or the one named by - `LEONIDA_HOST_ADAPTER` (`warp`, or part of an adapter's name; the adapter used is printed). `d3d12_vulkan_device` - picks it through `runtime/test/d3d12_copy_compare.h`; `d3d12_copy_xfmt`, `d3d12_depth_resolve`, - `d3d12_fence_events`, `d3d12_indirect_zero`, `d3d12_node_mask`, `d3d12_query_rules` and `d3d12_resource_desc`, - which also compare with WARP, through `runtime/test/host_adapter.h`. Some answers are the - driver's choice, so pick the host side when two adapters disagree: `GetResourceTiling` splits standard and packed - mips differently on an NVIDIA, an AMD and a WARP host, and the test accepts any split. - - Copies against the host (D3D-46, `d3d12_copy_compare.h`): the same scenario runs on the layer and on the host and - the bytes read back are compared; a failing case prints its name, the region (subresource, mip, slice, plane) - and the first differing byte. Every case uploads deterministic bytes into a texture and then runs - `CopyResource`, `CopyTextureRegion` texture to texture (an inner box to the origin, and the origin box into - another array slice at an offset), footprint to texture (an inner box at an offset) and texture to footprint - (an inner box at an offset into a readback buffer prefilled with `0xcd`), and reads every subresource back. - Formats: R8, R8G8 SNORM, RGBA8 (UNORM, SRGB, typeless), BGRA8, R16 UNORM, RG16 and RGBA16 float, R32 UINT, - RG32 UINT, RGBA32 float, R10G10B10A2, R11G11B10, R9G9B9E5, B5G6R5, B5G5R5A1, D16, D32, D24S8, D32S8 and BC1-BC7 - (SRGB and signed variants included), as a 36x20 texture with three slices and six mips (odd mip sizes), 3D - textures with boxes in depth, a single-mip single-slice texture and a one-block BC7. Buffers: `CopyBufferRegion` - at odd offsets and sizes, a `CopyResource` of a 4093-byte buffer, and an upload buffer straight to a readback - buffer. Only the bytes inside a footprint row are compared (row padding is the driver's; a difference there is - printed, not failed); every byte a partial copy must leave alone is compared. It found: - - `R8G8_SNORM`, `R16_UNORM`, `R32G32_UINT`, `R9G9B9E5_SHAREDEXP`, `B5G6R5_UNORM` and `B5G5R5A1_UNORM` textures were - refused (no Vulkan mapping); they map to `R8G8_SNORM`, `R16_UNORM`, `R32G32_UINT`, `E5B9G9R9_UFLOAT_PACK32`, - `R5G6B5_UNORM_PACK16` and `A1R5G5B5_UNORM_PACK16`. - - A texture-to-texture box on a block-compressed texture that reaches the padded edge of a mip (for example a - box of whole blocks over a 9x5 mip) was refused as `invalid_copy`; the PC runtime accepts it. - - Copies between different mips of one texture are compared too (mips 24, 12, 6, 3, 1; RGBA8, BC1, BC7): sizes that - are no block multiple, boxes to a padded edge, and boxes that do not fit the destination, which both sides must - refuse (the host at `Close` with `E_INVALIDARG`, the layer at execution with `invalid_copy`). It found: - - **Block-compressed copies into a mip whose size is no block multiple** (a 0..8 box into a 6-wide mip, a 6x6 - mip into a larger one, a 4x4 box into a 3x3 mip) were refused with `invalid_copy`: the host copies whole - blocks, and one `vkCmdCopyImage` cannot (its extent must be a block multiple or reach each image's edge). They - are staged through transfer scratch now (above) and match the host byte for byte, as do a box 4..8 of a 6x6 - mip into a 3x3 one and a 3x3 mip into a 6x6 one at (4, 4). Measured on an RTX 5070 Ti and an RTX 3060 (driver - 621.24) and an integrated AMD Radeon(TM) Graphics (`0x1002:0x164e`, Vulkan driver 2.0.353), Windows 11, each - against its own host. `d3d12_state_map_test` checks the staged regions on the CPU. - - Known gaps shown by it and by the formats, not fixed: - - **`TEXTURE1D`** resources are not supported by the layer (creation, footprints and allocation info refuse - them), so 1D copies are not compared. - - On a GPU with a native D24, a readback leaves the unspecified `X8` byte of the depth plane untouched where the PC - runtime writes 0; the comparison ignores it. Where the layer stores D24 as D32 (see section 3.2) it writes 0. - A PC driver's copy flushes denormal float depth to zero, so the test keeps its values normal. A - `LEONIDA_HOST_ADAPTER` that matches no adapter fails the run instead of skipping the comparisons. - - D24 against the host (`d3d12_depth24_compare.h`, `depth24_convert_test`): the D24S8 row of the copy test - above runs with random 24-bit words on every GPU, the Radeon 880M's `D32_SFLOAT_S8_UINT` fallback included - (72 regions, byte for byte, upload, readback and copies). `d3d12_depth24_compare.h` clears 5215 depth values - (steps, half steps and the floats around them, powers of two, random) as a whole-view clear of a 4x4 texture - (the first 160) and as one rectangle clear per value of a wide texture, with a stencil value, and compares both - planes read back. The layer is checked against the reference (`depth24_quantize`), and against the host byte for byte - where the host agrees with it; NVIDIA's host rounds some ties the other way (478 of 5215 values) and is logged as a host quirk, not a failure. It also clears an - `R24G8_TYPELESS` texture through a typed D24 DSV (200 values, compared the same way), and reports whether - shader-resource views of both planes (`R24_UNORM_X8_TYPELESS`, `X24_TYPELESS_G8_UINT`) write the T# of the - texture's backing format (D3D-75): X24_8_32_FLOAT for the depth plane where the layer stores the texture as - `D32_SFLOAT_S8_UINT`, 8_24_UNORM where the GPU has D24, and 8_UINT for the stencil plane. An SRV read is not compared with the host (no shader runs in these tests and the host's - descriptor is opaque). It also runs an upload and readback under a `SetPredication` that skips copies, which the - layer must still convert and which is compared with the host's unpredicated run. `depth24_convert_test` runs the - compute pass on the GPU for all 16777216 words (to float, and back), 16777216 float bit patterns against - `depth24_quantize` (with a 1 MiB range so the copy splits into 65 dispatches), and a pitched copy at an offset - split by a 1 KiB range. It tests the pass, which needs no D24 absence, on whatever device - `VK_LOADER_DRIVERS_SELECT` picks; the layer's own D24 path (the D3D12 tests above) is used only on a GPU without - D24 depth-attachment support, so run those with the AMD driver selected (the Radeon 880M, RADV). -- `d3d12_translated_draw_test`: milestone M1.5 (D3D-53), the same path with translator output. - - **Shaders:** `test/shaders/vs_m15.asm` and `ps_m15.asm` are hand-written RDNA2 (gfx1013). The build assembles them - with `llvm-mc` and translates them with `tools/rdna2spirv.py` through `test/shaders/build.py`. `build.py` also writes - each one's synthetic FSSM program (`; fssm-at` / `; fssm-data` in the header) to `fssm/` and the translator puts its - SHA-256 in `spirv/index.json`, so the layer's lookup is the one the game uses; the test loads that index as it is. - An unknown program is refused. - - **User data:** root parameter 0 is a descriptor table (`s0:s1`, the VA of its first slot), parameter 1 four root - constants (`s2..s5`: the draw's clip offset, and a bias for the PS). - - **Vertex fetch:** the VS has no input layout. It `s_load`s a V# the application wrote into a shader-visible slot and - fetches position and colour with `buffer_load_dwordx4 ... idxen`; the V# points at a DEFAULT-heap buffer in the arena. - - **Code base:** the PS starts with `s_getpc_b64` and `s_load`s four floats from offset 0x100 of its own FSSM program, - so the layer must have uploaded that program at the push-constant code base (dwords 34-35). - - **Draws:** a quad and a second V# over the same buffer, with different table slots and constants, into a - `R32G32B32A32_FLOAT` target. Every value is a short binary fraction, so the comparison is bit for bit: 4064 of 4096 - pixels are exact, and the 32 whose centres lie on the triangle's long edge are counted apart. - - **Zero-based ids:** all draws use `StartVertexLocation` 0 and `StartInstanceLocation` 0, so `v0` is the same with - and without the translator's zero-based VS ids (#436, not in this tree: with its translator change applied the - result was identical, checked on both GPUs). Both devices enable `shaderDrawParameters` where supported, which - #436's shaders need. A non-zero base would differ (hardware: zero-based, the base in an SGPR), so the test avoids one. -- `d3d12_method_variants_test`: each variant against the method it wraps, on the device directly (the proxy's - slot 76 is the Xbox texture method, not `CreateCommittedResource3`). It runs 12 creation cases (buffers on the - three heap types, textures, a volume, a multisampled target, and three shapes the base refuses) through every - `CreateCommittedResource` variant, which must give the same result, description, heap properties and `Map` - answer. It runs the edge cases in the table above and compares them with the host's PC runtime when there is - one; protected sessions are checked on the layer alone, and castable lists have their own success/refusal - checks. `GetCopyableFootprints1` must match `GetCopyableFootprints` field by field, including the failure - answer. A texture from `CreateCommittedResource3` - is uploaded, copied back and compared on a queue from `CreateCommandQueue1`. -- `d3d12_sampler2_test`: `CreateSampler2` against `CreateSampler`, on the slots' bytes. It checks: - - 10 descriptions without flags, which must be byte for byte the same; - - 6 UINT and float-bit border colours against their float equivalents (the three built-in UINT colours with - the integer mark, which must decode to `VK_BORDER_COLOR_INT_*`); - - custom float and UINT border colours registered in the table on `VK_EXT_custom_border_color` (D3D-73), - verifying index reuse for identical colours and distinct S# descriptors for distinct colours or integer vs - float representations; - - 3 non-normalized samplers, which must be `CreateSampler`'s S# with `FORCE_UNNORMALIZED` set; - - the `D3D12_OPTIONS17` answer; - - the 22 written-or-refused cases behind the table in section 3.2, compared with the host's PC runtime when - there is one. -- `xbox_present_test`: `PresentX` and the frame events (section 4.5, "what is implemented"), checked on swapchain pixels. - there is one. A host that reports no non-normalized samplers is compared only on the 3 cases without the - flag. The other 19 are then checked against their recorded answers only. -- `d3d12_subgroup_test`: subgroup size control through D3D12 PSOs, on the PSOs of the device proxy. - - **Shaders:** `cs_w64x_readlane` (a `v_readlane` across both halves of a wave64) translated natively and with - `--wave64-emulate`, and `cs_wqm_w32`, built by `test/shaders/build.py` (needs `llvm-mc`: `LLVM_MC`). - - **Check:** each is dispatched through a PSO found by FSSM hash and the eight words it stores are compared. The - PSO's request (`pipeline_subgroup_requests`) must equal the decision function's. The native wave64 shader - must be exact where the device can give 64 (AMD: required size 64 plus full subgroups) and is reported, not - judged, where it cannot (NVIDIA); the emulated one must be exact everywhere. - - **Control:** a second run with nothing requested is printed. On the Radeon 880M the default compute subgroup is - already 64, so the wave64 controls are exact as well. - - **Probes:** GLSL shaders (`cs_sg_probe.comp`, `ps_sg_probe.frag`, `vs_sg_fullscreen.vert`) store `gl_SubgroupSize`, - so the size the driver used is observed for a wave64 entry, a wave32 entry and an emulated one. Where the PSO - required a size, the observed size must equal it. For a wave32 compute shader on a device whose default is not 32, - the control is asserted to differ (the request matters); a wave32 pixel shader on the 880M goes from 64-wide to - 32-wide with the request. - - **Wave64 pixel shader:** `ps_w64x_readlane.asm` (`v_readlane` of lanes 40, 5, 33 and 63) is drawn over 64x64 - pixels through a graphics PSO into a float target, and every pixel must carry the four values derived in the - .asm header where the PSO required 64: 4096 of 4096 on the 880M. The control is asserted to differ only where the - default pixel subgroup is not 64; the 880M runs pixel shaders 64-wide by default, so its control is exact too. On - the RTX 5070 the shader gets no 64 (0 of 4096 exact, not judged). - - **RX 6800 (RDNA2, AMD Windows driver 26.11.2, 2026-11-22):** the compute requests take effect (wave32 compute - goes from 64-wide to 32-wide), but nothing can be requested for the fragment stage: the pixel probe runs at the - 64-wide default for the wave64, wave32 and emulated entries (outcomes `device_default`, `unavailable`, `emulated`), and - `ps_w64x_readlane` is not judged; its control, at the 64-wide default, is 4096 of 4096 exact. -- `d3d12_descriptor_test`: descriptors through the proxy. - - Copies, checked on the slots' bytes: one run, range lists of different shapes on each side, null size - arrays, and a destination longer than its source. - - What views and samplers write, decoded: a view of an uploaded 8x8 texture and a sampler, mips 1 and 2 of a - BGRA cube with a component mapping, an unordered-access view (the same bytes as the shader-resource view of - that mip), and the null descriptors of a missing resource, a texture without `ALLOW_UNORDERED_ACCESS`, a view - past the mips and a volume. - - UINT border colours (Vonsek's case on #538): an `R8G8B8A8_UINT` texture sampled one tile to the right - through `CreateSampler2` samplers with a UINT `(0,0,0,0)` and `(1,1,1,1)` border reads 0 and 1 in every - channel. A float white border on the UNORM texture reads 255; its S# differs from the UINT white one only in - the integer mark. - - That set 0 holds them: a compute shader (`test/glsl/cs_sample.comp`, GLSL, compiled with `glslangValidator`; - skipped without it) is handed a slot's T# and the sampler's S#, looks them up in the hash table as a - translated shader does, and samples. The sampler wraps in U and the shader samples one tile to the right, - so a missed S# shows too: the fallback sampler clamps. The layer has no pipelines yet, so the test creates - this one in Vulkan and binds the device's set. It reads the texture through the view's own slot and through - a copy of it, and gets the fallback from a slot of bytes no view was made for and, after the texture is - destroyed, from the view's own bytes. - - Capacity: 5000 distinct SRVs of that texture and one more, and 2100 distinct wrapping samplers in two - 2048-slot heaps. The last view through the last sampler reads the texture one tile to the right. With the - sizes of before, both were past their arrays ("array is full") and the shader read the fallback. -- `d3d12_compute_test`: the compute path through the proxy. It creates a root signature from the PC serializer's - blob, and a PSO through slot 62 from a container shaped like the game's, found in a translator-style index by its - FSSM hash (an unknown program is refused). It sets root constants, a root UAV and a descriptor table whose - application-written entry points at an upload buffer, then runs two dispatches that change s0 and the UAV in - between. The results come back through a readback buffer. The shader, `test/glsl/cs_user_data.comp`, is GLSL - written to the translator's push-constant and address contract, compiled with `glslangValidator`. It also checks: - - the dispatches' root signature and PSO are released right after being set, and the same signature is set - again after the arguments, so the list must hold both and keep the arguments (without the hold the test - crashes); - - the index has an entry with set-0 bindings for the same program ahead of the binding-free one, and the PSO - must take the binding-free one; - - a device that reports 128 bytes of push constants refuses the PSO. -- `d3d12_fspx_compute_test`: the FidelityFX DLL's two ways of passing an FSPX program, with synthetic programs - ([fspx.md](fspx.md), "Build and run-time lookup"). A PSO through slot 62 from a `DXBC` container whose `ACCC` part - is an FSPX payload, and one through `CreateComputePipelineState` from a bare kind-6 program, as the slot-67 - description carries it. Both are found by `fspx_code_sha256` in `/fspx/index.json` and dispatched once with - `cs_user_data.comp`, which adds dword 1 of its code base: each must read its own kind-6 program. Ten inputs are - refused with `E_INVALIDARG`: an untranslated program, bare and in a container; kind-6 entries that end past the - payload, start inside the directory, wrap 32 bits, are too large or are empty; a container without `ACCC`; bytes - without the prologue; and the program with four bytes appended. -- `d3d12_bindless_churn_test`: the table churn of D3D-314 through D3D12 alone, on a direct and a compute queue with - three frames in flight. Each of 96 frames makes 24 textures with SRVs in a ring of shader-visible heap slots and - releases those of seven frames earlier (about 190 live keys, so the table grows), the direct queue uploads, the - compute queue waits for it on the GPU, and each queue runs the `cs_set0_sample.comp` shader eight times on SRVs - of the frame and the three before it. All 98,304 sampled texels per run are compared with what the CPU wrote. - The two D3D12 queues get distinct `VkQueue`s where the device's family has two (`queue_count_wanted = 2`, - `command_queues`; the test prints which it got and says so when the family has only one). Two queues on one - `VkQueue` are ordered by submission, which hides a missing wait between them. It runs four times: as the layer is (0 - `vkDeviceWaitIdle` for the bindless set required, at least one generation made, a retired generation seen pending - right after the submit that made it); with the compute queue never waiting on the direct queue's fence (it samples - textures the CPU has seen finished, so only the grown table is new to it); and both again with - `LEONIDA_BINDLESS_IDLE_WAIT=1` (the old wait, counted above 0). Times are printed, not asserted. The async runs - are what the layer's wait on the uploading submission keeps correct: with that wait removed, the RTX 5070 run - failed at frame 5 (compute read a zeroed table: the grown binding 2 with the upload not yet run), as @duudiis - reported on #2740; the old-wait path shares that bug on `main` (the idle wait only covers work already submitted, - not another queue's later submission that binds the new table). The Radeon 880M did not reproduce it in two - runs. `d3d12_bindless_churn_validated` runs it under the validation layer. - The table's growth is the only replacing flush this scenario produces (3 generations). The other kinds (a live - key's index replaced, a relocation) and the failed-submit retry are checked at the Vulkan level by - `vk_bindless_test` cases 3 to 6 (the set changes; `release_retired` frees only what its ticket allows). That test - needs the translated `vs_ids`, `ps_tex` and `ps_imgatomic`; it was not in ctest before D3D-314 (only - `scripts/run_gpu_tests.py` and `check.py` ran it), and is now, as `vk_bindless_ps_tex` and `vk_bindless_ps_imgatomic`. - without the prologue; and the program with four bytes appended. It also covers the dispatch state: - - one program in containers with three kind-0 entries picks its own entry for each, an unknown kind 0 is refused, and - the bare program is refused as ambiguous; - - slot 67 with all four pairs picks by kind 0 too (one entry's module is missing on purpose, so the pick shows as - `E_FAIL`), and four inconsistent pairs are refused before they are read; - - slot 67 with the description built the way the DLL builds it (`dll_slot67`: the reader's pair order over the - container's own directory, kinds 0, 1 and 7 pointing into the payload, kind 6 copied into a 256-rounded buffer - padded with `0xcc`) resolves each program to its own translation with its own state; - - console slot 11 on a slot-67 and a slot-62 pipeline returns an object whose slot 3 points at the dword 0 and whose - slot 4 gives 4 bytes; it releases to 0, and the pipeline's reference count is unchanged. -- `d3d12_set0_compute_test`: set 0 from the compute bind point, through the proxy and D3D12 alone. The index entry - of its shader lists set-0 bindings, so the PSO's layout holds the device's bindless set and replay binds it at - each dispatch; nothing in the test binds it. Four dispatches of `test/glsl/cs_set0_sample.comp` (GLSL written to - the translator's contract) load a T# and an S# from two descriptor tables and sample one tile to the right in U: - - two SRVs give their textures texel for texel, so the T# decides the image; - - 32 bytes no view was made for give the fallback image, one colour everywhere; - - a clamping sampler gives the texture's right edge, so the S# decides the sampler; - - a device without the bindless set refuses the PSO. - - Removing the set-0 bind from the dispatch path makes this test fail (`VUID-vkCmdDispatch-None-08600`, measured on - llvmpipe); `d3d12_m2_textured_test` covers the bind at draws in the same way. -- `d3d12_draw_test`: milestone M1, through the proxy. - - **Pipeline:** a VS+PS PSO found by FSSM hash. The input layout is POSITION then COLOR, while the VS has them in - the opposite register order, so a match by position would fail. - - **Buffers:** the vertex buffer is copied into the arena, and the index buffer is read from an upload heap. - - **Draws:** two indexed draws with different root constants and root CBVs, then a back-facing triangle that must - be culled. Each of these also checks a fix: - - the first draw uses a PSO with a second RT format and a DSV format, with neither bound (a variant); - - before the second draw, the same root signature is set again after the arguments, which must keep them; - - two more draws, through a viewport on the top-right quadrant, read COLOR per instance with step rate 0 (two - instances that must both read element 0) and from an unbound slot (zeros). - - **Second pass** on the same target, cleared again: a full-screen triangle from a VS with no inputs - (`test/glsl/vs_fullscreen.vert`), first in its submission so no vertex buffer was bound before it, through a - viewport on the bottom-right quadrant; then, where the GPU has `logicOp`, the red quad XORed over the blue - top-left quadrant, which must read `(255,0,255,0)`. - - **Refusals:** - - PSOs that need wireframe fill, independent blend, a depth-bias clamp or depth clamping are refused on this - device, which enables none of them; - - nine render targets is refused, at PSO creation and at `OMSetRenderTargets`; - - 0-byte and wrapping buffer sizes are refused, and a buffer or shader-visible heap larger than the arena runs - out of memory; - - a draw with no viewport executes cleanly and draws nothing. - - **Check:** all 4096 pixels of the read-back target are compared. Where the red and green quadrants land also - checks the viewport flip and the winding. The test fails with any of these fixes undone: the rebind, step - rate and logic op show wrong pixels, the variant breaks `dynamicRenderingUnusedAttachments-08912`, and the - stride state breaks `pStrides-04913`. - - The shaders are GLSL written to the translator's contract (`test/glsl/vs_draw.vert`, `vs_fullscreen.vert`, - `ps_draw.frag`). -- `d3d12_present_test`: milestone M0. It opens a window and presents 60 frames, each one: reset the list, move - the back buffer `PRESENT` → `RENDER_TARGET`, clear, move it back, execute, present, signal a fence. It then - resizes the window and presents 10 more (70 in all), which recreates the swapchain, scales the blit and switches - to unsynchronised presents. The presenter's capture copies every presented image back, and the test checks - that the whole image holds the clear colour at the swapchain's size (after the first 60 frames, after the - resize and at the end). Last, it reads the colour on screen with GDI when the window is in front, no other - window lies over its centre (an always-on-top one can, even over the foreground window) and GDI can read the - screen. On a GPU that does not drive the window's monitor (the UHD 770 with the desktop on an RTX 4080 SUPER) the - desktop never shows the swapchain, so the test prints the pixel, does not assert it and says why. Under Wine's macOS driver it can't: `GetPixel` on the screen DC returns `CLR_INVALID` even - for a pixel GDI painted itself, and the window's own DC holds Wine's GDI surface (white), not the image - presented through the Metal layer. There the capture checks are what confirms the colour. - - The injected failures below make the runtime log `[rt] d3d12: present failed` three times (VkResult - -1000001004 twice, then -1, `VK_ERROR_OUT_OF_HOST_MEMORY`). The test announces them on stderr first; they - are expected and are not out-of-date presents from the driver (the closing line counts those). - - The device and the presenter get their Vulkan functions through a driver double in the test. It forwards to - the real driver, counts the presents the driver reports out of date (the frame counts allow for them), and - tracks the binary semaphores alive. - - Through the double, the test reports one successful present as out of date (not counted) and one as - suboptimal (counted). - - It fails the second per-image semaphore of a recreation: only the two acquire semaphores may remain, and a - retry at the same vsync must make a complete swapchain. - - It fails one blit submission: the next four presents must go through without hanging. - - Run against the presenter before these fixes, the test fails at the frame count after the resize, where the - driver reported a real out-of-date present (RTX 5060 Ti, driver 621.24). - -**Open:** whether the game uses command-list flags, bundles, or `ExecuteCommandLists` with many lists at once. All -are supported by the IR; the trace will show which are hot. - -[descriptor-overview]: https://learn.microsoft.com/en-us/windows/win32/direct3d12/descriptors-overview - -### 3.3 One GPU address space - -The shader contract is the constraint that shapes everything else. The translator computes: - -``` -host_address = heap_base + console_va -``` - -where `heap_base` is push-constant dwords 32–33 and `console_va` is an Xbox GPU virtual address the game writes -into a descriptor, a root argument, or a buffer. This applies to buffer, descriptor-table and shader-code -addresses. Image descriptors (T#) are hashed by the translator, not dereferenced, so an image's base can be a -separate key range (below). Most shaders also force the high dword of a descriptor-table pointer to zero (25,865 -of the 26,503 in package 1.0.2.1, counted 2026-11-22; see "Descriptor-table high-dword truncation" below), so -**shader-visible descriptor heaps must live below 4 GB** in this address space. - -The layer therefore owns the console VAs. It returns them from `ID3D12Resource::GetGPUVirtualAddress` and from -`GetGPUDescriptorHandleForHeapStart`; the game only sees values the layer chose. The design is: - -| Piece | Design | -|---|---| -| Address space | Two ranges. A **BDA arena** holds buffers, descriptor heaps and shader code; its device address is `heap_base`. A separate **image key range** supplies unique console VAs for images; those keys are never added to `heap_base`. The arena's `VkBuffer` is created with all buffer usages the game can bind (uniform, storage, vertex, index, indirect, transfer) plus `SHADER_DEVICE_ADDRESS`, and its memory with `VK_MEMORY_ALLOCATE_DEVICE_ADDRESS_BIT`. | -| Buffers | A buffer resource is a range in the arena's single `VkBuffer`: offset = its console VA, size = the resource size. Buffer commands bind the arena buffer with that offset, so its device address is exactly `arena_bda + offset`; no per-resource `VkBuffer` object is needed. | -| Images | Each image gets a unique console VA key and lives in its own `VkDeviceMemory` (or a suballocated device-local image heap) with optimal tiling. Shader image access goes through the T#/hash table, so nothing dereferences the key. Keeping images out of the arena avoids forcing optimal-tiled images into the arena's memory type and keeps the arena sized by buffers, not textures. | -| Heaps and placed resources | `CreateHeap` reserves the requested size in the arena, so a buffer placed at a 64 KiB-aligned offset is that offset into the arena and its console VA is the heap's place plus the offset. A placed texture (1D, 2D or 3D) gets its own `VkDeviceMemory`; one the title placed at its own address through the console's `CreatePlacedResourceX` (Xbox device slot 133) reports that title address from `GetGPUVirtualAddress`, as the console does — a title turns it into the CPU pointer it clears the texture through — while its pixels do not alias the title's pages yet. Any other texture answers a null VA, as on D3D12. Tiled (`64KB_UNDEFINED_SWIZZLE` and Xbox `0x101`) 2D/3D placed textures (D3D-191) and multisampled 2D placed textures (D3D-222) share that backing, answer `GetResourceAllocationInfo` and `GetResourceTiling`, and check heap/offset alignments. Reserved buffers can use heap tile mappings (section 4.2). | -| Descriptor heaps | Shader-visible CBV/SRV/UAV and sampler heaps are allocated in the low 4 GB of the arena. RTV/DSV heaps are host-side only. | -| Shader code | Each FSSM blob is uploaded to the arena; its console VA is the code base. | -| Upload/readback | `D3D12_HEAP_TYPE_UPLOAD`/`READBACK` resources are separate host-visible buffers outside the arena. Their console VAs are only used by copy APIs; if the game binds one as a vertex/index buffer or reads it in a shader, the layer biases the view/descriptor by `-heap_base` so the shader's addition lands on the host BDA (**ASSUMPTION**; **measured to fail for a V#**, see below). | - -**Measured (XCL, retail title, PR #168):** the console answers a placed texture's `GetGPUVirtualAddress` with the -address the title placed it at; the title clears a 256×256 `R32_FLOAT` texture through that value as a CPU pointer. -On the PC, where D3D12 answers 0 for a texture, that write went to address 0. XCL returns the title address when the -PC answers 0 and leaves buffers and resources with a PC address unchanged -([`real.rs`](https://github.com/ivall/xcl/blob/main/crates/xcl/src/hle/d3d12x/real.rs), PR -[#168](https://github.com/ivall/xcl/pull/168)). Facts only: XCL is GPL-2.0-only and no code is copied. This layer -sets a slot-133 fallback texture's `GetGPUVirtualAddress` to the title address; the image itself still does not -alias the title's pages. - -Non-arena buffers (upload/readback) can still be addressed by the shader without putting them in the arena: pass -`console_va = host_bda - heap_base` (mod 2^64) in root descriptors and vertex/index/indirect views, so the shader's -`heap_base + console_va` equals the host BDA. For descriptors, patch the V# base field the same way when the layer -copies or scans them. This relies on the game not using the raw VA for anything except shader addressing -(**ASSUMPTION**); if it does, the resource must move into the arena instead. - -**Measured (D3D-53, `d3d12_translated_draw_test`):** the bias works for 64-bit root arguments (`d3d12_compute_test`: a root -CBV and a table slot that point at an upload buffer) but **not for a V#**. A V#'s base field is 48 bits -(dword0 and dword1[15:0]), and an upload buffer's console VA, its device address minus `heap_base`, is negative on both test -GPUs (`0xffffffffffce0000` on the AMD Radeon 880M, `0xffffffffffedc000` on the RTX 5070 Laptop; the buffer's device -address lay below the arena's, an allocation-order fact of these runs, so it is not guaranteed either way). The shader -adds `heap_base` to the truncated 48-bit value, which is a wild address: the draw faults and the whole queue submission is lost -(the clear that came before it is lost as well). Any resource a game can put in a V# (a vertex, constant or structured buffer -behind a descriptor) must therefore be an arena range, whatever the allocator happens to do, upload and readback heaps included. Until the layer does that, the -translated-draw test fetches from a DEFAULT-heap buffer and does not draw from the upload buffer. - -**Measured (static, `XboxBvhBuilder.dll`): the BVH builder only takes destination addresses below 2^40.** Its -validation function at `0xc8f0` loads `DestAccelerationStructureData` (the first field of the build description it -reaches through `[rcx+0x68]`) and checks it twice: - -| Check | Instruction | On failure | -|---|---|---| -| 256-byte alignment | `test r8b,r8b` | message "…must be 256-byte aligned…" | -| below 2^40 | `cmp r8,10000000000h` / `jae` | message "…can not have more than 40b of address set" | - -On a failed check it prints its message through `OutputDebugStringW` after a "D3D12 XDXR Error: " prefix, and then -throws `E_INVALIDARG`: a C++ exception out of the DLL, not an `HRESULT` return. -- The alignment rule is the public `D3D12_RAYTRACING_ACCELERATION_STRUCTURE_BYTE_ALIGNMENT`. -- The 40-bit rule has no PC counterpart. - -Arena VAs (at most 4095 MiB, so 32-bit) pass. A VA biased from outside the arena does not: the negative upload-heap -VAs above are at or above 2^40 as unsigned values. That is one more reason for the rule above that every buffer -a console client can address is an arena range, whichever heap it comes from. - -Why not give each buffer its own BDA and set `heap_base = 0`? Because 25,865 of the 26,503 shaders (97.6%) -truncate descriptor-table pointers to 32 bits, and host BDAs are not guaranteed to be below 4 GB. The arena keeps console VAs low and stable. - -Why one arena rather than several? Because the shader gets exactly one `heap_base` for buffer, descriptor-table and -code accesses. A draw can reference a descriptor table in one heap and a vertex buffer in another; both must -satisfy the same `heap_base + va` equation. Several non-contiguous VkBuffers cannot provide that equation. - -Image keys are 256-byte-aligned byte addresses. The [RDNA 2 ISA, §8.2.6, Table 45][rdna2-image-resource] defines -the 40-bit T# base field as address bits 47:8. `gfx10_descriptors.h` encodes bits 39:8 in word 0 and bits 47:40 -in word 1[7:0]. The largest representable key is `0xFFFFFFFFFF00` (2^48 − 256 bytes). Bit 48 is not stored, -so keys separated by 2^48 bytes produce the same base field. - -The runtime allocates image keys from `0x100000000` (4 GiB) in 256-byte steps, above the 4095 MiB arena cap. -**Open:** whether any shader in the game uses an image VA as a raw pointer rather than through its T#. - -[rdna2-image-resource]: https://www.amd.com/content/dam/amd/en/documents/radeon-tech-docs/instruction-set-architectures/rdna2-shader-instruction-set-architecture.pdf - -**Memory type policy.** The first boot needs correctness, not bandwidth: - -- M0–M3: allocate the arena as `HOST_VISIBLE | HOST_COHERENT` (preferably also `DEVICE_LOCAL` when large BAR is - available). The CPU can then write descriptor heaps, shader blobs and uploaded buffers directly. Images are - already device-local, so rendering still uses fast memory for textures. This is slow for dynamic buffers but - removes staging and host/console address translation from the bring-up path. - - A memory type is only tried when its heap can hold the whole allocation (`memory_type_order` in - `runtime/src/vulkan_memory.h`, beside D3D-96's `resizable_bar`). Without Resizable BAR the only `DEVICE_LOCAL | HOST_VISIBLE` type sits in a - heap of 256 MiB or less (214 MiB on an RTX 3090 with driver 616.56), so the 256 MiB default arena lands in - system memory there. Asking that heap for it broke VUID-vkAllocateMemory-pAllocateInfo-01713 even though the - driver returned `VK_SUCCESS` (reported by CharlyRien). -- M4+: allocate the arena `DEVICE_LOCAL` and stage CPU writes (descriptor heaps, shader blobs, buffer uploads) - through a host-visible staging buffer, copied before the commands that use them. The hash table is not in the - arena either: it is a normal storage buffer in `DEVICE_LOCAL` memory, uploaded from a mapped staging copy before - the commands that read it (D3D-76). -- Upload-heap buffers prefer `DEVICE_LOCAL | HOST_VISIBLE | HOST_COHERENT` memory when the GPU has Resizable BAR - (D3D-96): the CPU writes them through the BAR and the GPU reads them from VRAM. `leonida::resizable_bar` - (`runtime/src/vulkan_memory.h`) calls it Resizable BAR when such a type sits in a device-local heap larger than - 256 MiB. Without Resizable BAR that type lives in a window of 256 MiB or less (214 MiB on an RTX 3090) that every - upload buffer would share, so they stay in system memory. If VRAM is full, the allocation falls back to system - memory. The device logs which one it uses (`[rt] d3d12: upload heaps in ...`), and `LEONIDA_UPLOAD_SYSMEM=1` - keeps them in system memory to compare the two. Readback buffers keep preferring `HOST_CACHED`. -- Textures and default-heap buffers outside the arena prefer `DEVICE_LOCAL` and need no host access. When VRAM is - full they still get memory, from the next type `memory_type_order` lists, which is system memory. The first one - that does is logged once (`[rt] d3d12: a N-byte allocation did not fit in device-local memory ...`, D3D-299, - `leonida::spilled_to_host`), so a run on a 4 GB GPU shows that it spilled (#2375). - -**Capacity.** The arena is sized by buffers, descriptor heaps and shader code, not by textures. The allocator -tracks the high-water mark; start with a configurable capacity (for example 4 GiB for the loading/menu path) and -fail with a clear message when a console VA would fall outside it. Growing means creating a new arena, copying, -and updating `heap_base` for all subsequent commands; do it at a frame boundary, never with work in flight. - -**Open:** the game's real buffer VA range and peak working set are unknown until it runs. `maxBufferSize` (with -`VK_KHR_maintenance4`) and `maxMemoryAllocationSize` bound the arena; a large open-world buffer working set may not -fit on smaller PC GPUs. This is a product requirement, not something the layer can hide. - -**Reserved resources.** `CreateReservedResource` and the queue tile APIs use Vulkan sparse binding for buffers and -compatible single-mip RGBA8 2D textures (section 4.2). Other descriptions have fully allocated backing. Wider -texture coverage and the game's use of tile streaming remain open. - -### 3.4 Descriptor heaps and the bindless model - -The game can use D3D12 descriptors in three ways, and the layer must handle all of them: - -1. **Root descriptor tables.** `SetGraphicsRootDescriptorTable` supplies a GPU handle; the shader receives the - table's console VA in its user data and loads T#/S# structures from it. -2. **Direct heap indexing.** The root signature has `D3D12_ROOT_SIGNATURE_FLAG_CBV_SRV_UAV_HEAP_DIRECTLY_INDEXED` - and/or `..._SAMPLER_HEAP_DIRECTLY_INDEXED`, and the shader indexes `ResourceDescriptorHeap` / - `SamplerDescriptorHeap` directly. The console driver supplies the bound heap base and stride; the shader loads - the descriptor at `base + index * stride`. **Measured (D3D-329): each heap base arrives as a 32-bit pointer in - an input SGPR the shader reads directly, inside the user data for compute; no stride arrives at all.** - `tools/heap_index_census.py` over the 1.0.2.1 corpus (26,503 listings; 1,473 with embedded data words skipped) - follows every descriptor-width `s_load_dwordx4/x8/x16` back to the SGPRs it starts from. Of 770,412 such loads, - 769,366 (99.86%) start from an entry SGPR used as a 32-bit pointer (high word a constant 0), 0 from a pointer - loaded from memory, and 1,041 could not be followed (0.14%, all but 63 in heap-indexing shaders). That holds for - the 18,066 shaders whose `SFI0` sets either heap-indexing bit as much as for the 6,964 that set neither. The - heap-indexing shaders add a base read with a run-time offset (the heap index): for example `s10` in CS, `s23` in - MS and `s15` in PS for the resource heap, and a separate base for the sampler heap (`s11` in CS, `s24` in MS, - `s16` in PS). For compute this is settled: every base lies below the shader's `COMPUTE_PGM_RSRC2` `USER_SGPR` - count, so it is user data. For VS, PS, MS and GS no user-SGPR count is measured; every base lies below `s32` and - none is the NGG `s3`, so they are user data under the translator's 32-SGPR assumption, and the user count of the - graphics stages (question 3 in the table below) is what would confirm it. Which SGPR holds which heap varies - with the stage and the root signature, so placing the bases belongs to the root-signature mapping, not to a new - translator input. No stride is read at run time: static offsets of T# loads are multiples of 32 and of S# loads - multiples of 16, so the stride is compiled into the code. In the runtime shim, `CreateRootSignature` records the - `CBV_SRV_UAV_HEAP_DIRECTLY_INDEXED` and `SAMPLER_HEAP_DIRECTLY_INDEXED` root-signature flags and `SetDescriptorHeaps` - tracks the bound shader-visible heap GPU bases (`d3d12_set_descriptor_heaps`), while placing those bases into - per-stage user SGPRs remains open on question 3. -3. **Game-built descriptor memory.** The game writes raw T#/S# bytes into a heap itself, without calling - `CreateShaderResourceView`. The shaders then read those bytes exactly as in case 1. - -The layer's descriptor model: - -- A `DescriptorHeap` has a host shadow and, if shader-visible, an arena range. CPU handles point into the shadow; - GPU handles are arena VAs. `Create*View`, `CopyDescriptors` and `CopyDescriptorsSimple` write the shadow and mark - the range dirty. The execute-time scan below is the correctness path, so a game that writes raw descriptor bytes - through a CPU handle still works; dirty tracking is only an optimisation. -- **Heap start-handle ABI.** Prior art measured `GetCPUDescriptorHandleForHeapStart` and - `GetGPUDescriptorHandleForHeapStart` (heap slots 9/10) returning the 8-byte handle in RAX on the Xbox build, - while the PC call returns it through a hidden pointer in RDX. A generic sret/IDL thunk must special-case these - two slots or the handle is garbage. This is a method-level ABI quirk; the heap object is still the public - `ID3D12DescriptorHeap` interface. -- The bytes written for an image/sampler descriptor are **GFX10 T#/S# structures**, the same structures the - translator reads. The layer writes them itself in `Create*View`; this does not depend on what the console driver - wrote. If the game builds descriptors in memory itself, it must use the same format (the shader reads raw T#/S#), - which is the assumption to verify. If it uses an opaque format, the layer must translate at bind time. -- At execution, for each bound table (or the whole bound heap when direct indexing is enabled), the layer walks - the declared descriptor range with the heap's stride, parses each T#/S#, and ensures a bindless entry exists: - - image T# → `VkImageView` (format, view type, mip range, array layers) → bindless image index; - - sampler S# → `VkSampler` (filter, address modes, LOD, compare, anisotropy) → bindless sampler index; - - buffer V# / CBV → no Vulkan view; the descriptor already contains a console VA the shader dereferences. -- **Buffer UAVs.** `CreateUnorderedAccessView` on a buffer writes a V# in the first 16 bytes of the slot (the rest of - the 32 bytes is zero): `BASE_ADDRESS` = the resource's GPU VA + `FirstElement` * the element size, and by view kind - - *raw* (`R32_TYPELESS` + `RAW`): stride 0, `NUM_RECORDS` = bytes, `OOB_SELECT` 3 (raw); - - *structured* (`UNKNOWN` + `StructureByteStride`): stride, `NUM_RECORDS` = records, `OOB_SELECT` 0; - - *typed* (any other format the typed-UAV table has: `uav_clear.h` layouts that `gfx10_descriptors.h`'s - `format_table` names with a code below 128): `FORMAT` = the `GFX10_FORMAT_*` code, stride = the element size in - bytes, `NUM_RECORDS` = elements, `DST_SEL` = the format's own channel order (`format_swizzle`: R8 reads as - (x, 0, 0, 1), B8G8R8A8 as (z, y, x, w)), `OOB_SELECT` 1 (structured: only the index is checked against - `NUM_RECORDS`, `docs/buffer_bounds.md`). This is what `buffer_load_format_*` / `buffer_store_format_*` / the - `buffer_atomic_*` of a translated `RWBuffer` read; the translator decodes the element from the V#'s `FORMAT` - at run time (`rdna2spirv.py` `FORMATS`) and bounds-checks the whole element against `NUM_RECORDS`. A format the - layer cannot name (a typeless or 96-bit one, a compressed one, anything whose code is 128 or more, `R16G16_SNORM` - and the other texture formats `vulkan_format` has no row for) leaves a null slot, logged once. Typed clears - (`ClearUnorderedAccessViewUint/Float`) read the same V# back, so they work on these views and on game-built ones. - - **UAV counters** (`pCounterResource` + `CounterOffsetInBytes`, structured views only). D3D12 keeps the counter in - an application-visible buffer: there is no `CopyStructureCount` (that is D3D11); a game copies the counter with - `CopyBufferRegion` from `pCounterResource` at `CounterOffsetInBytes` (this is "CopyStructureCount" in D3D12 and - needs nothing from the layer), and resets it with `ClearUnorderedAccessViewUint` on a raw view of that word or a - copy from an upload buffer. The layer refuses (null slot, logged once) a counter on a non-structured view, a - counter resource that is not a buffer created with `ALLOW_UNORDERED_ACCESS`, an offset that is not a multiple of - `D3D12_UAV_COUNTER_PLACEMENT_ALIGNMENT` (4096) or leaves no room for 4 bytes, and a non-zero offset with no counter - resource, the combinations D3D12 documents as invalid. **Hypothesis for the console contract (not measured):** the - shader gets the counter as a second V#, raw, 4 bytes (stride 0, `NUM_RECORDS` 4, `OOB_SELECT` 3) at address - counter VA + offset, in **bytes 16..31 of the same descriptor slot**, which is otherwise unused for a buffer - (a V# is 16 bytes in a 32-byte slot), and `AppendStructuredBuffer` / `ConsumeStructuredBuffer` compile to - `buffer_atomic_add` / `buffer_atomic_sub` with `glc` on it, the returned old value (minus one for consume) being - the record index. Why this guess: the translator has no `ds_append` / `ds_consume` / GDS path and the corpus scan - (open-questions table below, row 10) found no GDS instruction, so a counter in memory is the only form left; where the - counter V# sits (a second slot, a user SGPR pair, a spill) is open until a shader that uses one is traced - (row 16 of the same table). `d3d12_buffer_uav_test` runs `cs_buf_counter.asm`, a hand-written shader of exactly that shape: - 256 lanes append, 128 consume, the counter reads 256 and then 128 through `CopyBufferRegion`, and the 256 - appended records are each present once. If the console puts the counter elsewhere, only `write_buffer_uav` moves. -- Unbounded descriptor ranges (`NumDescriptors = UINT_MAX`) have no end. Scan from the table handle to the end of - the bound heap, and cache parsed descriptors by key so unchanged slots cost nothing. **Open:** whether the game - uses unbounded tables; the trace will show the root-signature ranges. -- The heap stride is the value the layer returns from `GetDescriptorHandleIncrementSize`. Prior art forwards device - slot 15 (`GetDescriptorHandleIncrementSize`) unchanged, but the actual increment values are still **Open**. Choose - 32 bytes for CBV/SRV/UAV (the T# size) and 32 bytes for samplers (16 bytes of S# plus padding) pending the console - value. The game may hardcode the console increments or infer them from shader address arithmetic; the shader's - shift amount gives the stride it expects, and the layer must match it. -- `CopyDescriptors` copies raw bytes. If the descriptor was produced by our `Create*View`, the copy is a valid - T#/S#; if it came from game memory, it is still valid raw data. No re-encoding is needed. -- Handle validation: a GPU descriptor handle is an arena VA; the heap registry maps the containing range to a - heap. A table handle outside the bound heaps is a validation error; log it and resolve to fallback index 0 - rather than reading arbitrary memory. -- RTV/DSV creation builds a `VkImageView` and stores it in the host-side heap; `OMSetRenderTargets` resolves those - handles to views for the rendering scope. RTV/DSV descriptors are never shader-visible. -- View creation maps `D3D12_SRV_DIMENSION`/`D3D12_UAV_DIMENSION` to `VkImageViewType`, the mip and layer ranges, - sample count, and `D3D12_SHADER_COMPONENT_MAPPING` to `VkComponentMapping`. Single-layer 1D textures have default and - explicit shader-resource views on sampled binding 5. Single-sampled 1D, 2D, 2D-array, cube and 3D colour SRVs apply - the T# minimum LOD in resource mip coordinates. A clamp inside the exposed mip range uses - `VK_EXT_image_view_min_lod`. Vulkan allows the image-view minimum to be rounded down to an integer. - With nearest mip filtering, the UHD 770 and Arrow Lake Xe-LPG returned mip 0 for a 2D minimum of 0.75. - The Xe-LPG also returned mip 1 for a 2D-array minimum of 1.75. RTX and Radeon returned mips 1 and 2. - `d3d12_descriptor` accepts either rule for a fractional clamp (all texels of a view following the float or the - floored minimum), and prints which one the driver used. - See [Vulkan image-level selection](https://docs.vulkan.org/spec/latest/chapters/textures.html#textures-image-level-selection) - and the [Intel readbacks](https://github.com/ItsNotRexed/Leonida/pull/1015#issuecomment-7075135647). - If the logical device lacks the feature, the runtime logs the unsupported view - and its descriptor resolves to the fallback. A clamp at or below the first mip needs no extension. Above the - last mip, the view retains its dimensions and maps sampled channels to zero while preserving constant channels. -- Set 0 is a fixed bindless layout, sized once when the device creates it. The defaults are 4096 sampled 2D - images, 1024 samplers, 1024 2D-array images, 256 1D, 256 3D and 256 per storage dimension/class. The 2D, sampler and - storage arrays grow to what the device's limits allow, up to 65536, 4096 and 4096 (see `vulkan_bindless.h` - above). The set is not recreated to grow, because recreating it would invalidate the pipeline - layouts built on it. Use `UPDATE_AFTER_BIND` and `PARTIALLY_BOUND` so a new view does not require rewriting - every descriptor; without those features, rebuild the set when it changes. -- The command buffer binds set 0 once; descriptor-heap changes only update the arrays and the hash table. - -**Descriptor lifetime.** A bindless index may be referenced by in-flight command buffers after the resource is -destroyed. Views/samplers are retired on a fence-value queue; the hash-table entry can stay (a stale key is only a -miss for a new descriptor, not a correctness problem) until the slot is reused. Reusing a slot for a new resource -updates the index in place; the key match makes the lookup correct. - -### 3.5 Root signature to user SGPRs - -This is the least verifiable part of the layer. D3D12 gives the application a root signature; the console driver -turns it into the user SGPRs (`s0..s31`) that the shader reads. The translator already copies those 32 dwords from -push constants into `s0..s31`. The layer must produce them. - -The default mapping (implemented by `rt::rootsig::pack` in `runtime/src/root_signature.{h,cpp}`) follows root -parameter order: - -| Root parameter | User-data dwords | -|---|---| -| `D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS` | one dword per constant | -| `D3D12_ROOT_PARAMETER_TYPE_CBV` / `_SRV` / `_UAV` | two dwords: the 64-bit console VA passed to `Set*Root*View` | -| `D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE` | two dwords: the table's console VA (a `D3D12_GPU_DESCRIPTOR_HANDLE`) | -| static sampler | none; registered in the hash table at root-signature creation | - -Before the draw/dispatch, the layer copies the current root arguments into a 32-dword block in that order and -uploads it as push constants. Missing parameters are zero. - -Measured on the corpus (`python -I tools/user_sgpr_census.py --base ps=8 vs=8 gs=8 cs=4 ms=16`, all 26,503 shaders). These are physical user SGPRs; the tool cannot see logical root-parameter indices. -- The lowest user SGPR read as a pointer is s8 in most PS (9,830 of 12,101) and VS (1,660 of 2,236), s4 in CS (2,364 of 2,689) and s16 in mesh shaders (7,977 of 9,282). -- Pointers are 32-bit (`ptr32_lo`) in every PS/VS/CS/MS shader that reads one; only the 195 GS read a 64-bit pointer (`ptr64_lo` at s8). -- Consecutive pointer SGPRs in one shader are most often adjacent (distance 1: 22,008 PS, 14,548 MS, 3,059 CS, 1,836 VS), and the SGPR after a 32-bit pointer is never read as a `ptr64_hi`. -- Below those bases only `const32` reads appear, at odd SGPRs in PS/VS/CS (s1, s3, s5, s7), and s2 in GS: a reserved block whose meaning is not established here. - -Taken together this disagrees with the packing above (from s0, two dwords per table) and is consistent with a per-stage base (s8 VS/PS, s4 CS, s16 MS) and one dword per table pointer. It is a census of shader reads, not a confirmed mapping: it does not show which root parameter feeds which SGPR, and the GS behave differently. `--expect ps=8 vs=8 cs=4 ms=16` turns it into a check; `tests/test_user_sgpr_census.py` shows that the two packing models give different results. - -**Console layout, measured for compute (D3D-448).** `rt::rootsig::pack_stage` lays the parameters out for one stage: -in root order from the stage base, each while it fits whole, a constant taking one dword per value, a root -CBV/SRV/UAV two (its 64-bit VA), a descriptor table **one** (the 32-bit VA of its first descriptor; the heaps live -below 4 GiB). A parameter that does not fit goes, with every later one, to the spill array behind `s[0:1]` -(section 7), which is not modelled, so such a signature is refused. How each part is known: -- **Compute, base s4: measured three ways.** - - The console compiler's output (section 7). - - The package's FidelityFX DLL, whose 29 compute containers carry their `RTS0` next to the console-compiled - program (`tools/rootsig_census.py --disasm /disasm`, Xbox Series 1.0.2.1). Base s4 plus the - signature's span in this layout equals the program's RSRC2 `USER_SGPR` count in 29 of 29: 27 signatures - (table, table, four root CBVs) span 10 dwords and launch with 14 user SGPRs, 2 (table, table, one root CBV) - span 4 and launch with 8. The `pack()` layout spans 12 and 6, two short of both. - - The reads: `tools/root_sig_contract.py --rootsig --model console` finds all 20 - translated programs compatible (tables read at s4/s5 as 32-bit pointers, each root CBV's VA copied whole as - two dwords from s6). The `pack()` layout contradicts 7 of them, which read the second table at s5, the first - table's high half in that layout. -- **Vertex/pixel/geometry s8 and mesh s16: a hypothesis.** It rests on the census above only; no signature - confirms these bases, and visibility is not modelled (every parameter takes its place in every stage). - -The runtime uses the console layout for the **compute** bind point only. Graphics keeps `pack()`: every stage of a -pipeline reads `s0..s31` from one push-constant block at offset 0 (`tools/rdna2spirv.py`, `ShaderUserData` in -`runtime/src/vulkan_replay.h`), so a mesh shader (base s16) and a pixel shader (base s8) in one pipeline would need -the same root argument at two offsets. That needs per-stage user-data windows in the translator's push-constant -contract (D3D-448 follow-up). A root signature carries both layouts; one that only one of them can place is -created, and binding it at the other bind point invalidates the command list (`Close` returns `E_INVALIDARG`). -`s0..s3` of a compute dispatch are the driver's block; the layer leaves them zero (109 CS read `s1` as a constant, -42 `s3`; their meaning is open). - -**Measured: a real signature beside the count it produced.** `tools/fspx_unpack.py` decodes `COMPUTE_PGM_RSRC2` of -each of the 29 compute programs in `amd_fidelityfx_upscaler_xbox.dll`, and its `USER_SGPR` field is the count the -console launched the dispatch with. Every one of those 29 containers also carries an `RTS0`, which makes this the -only place in the package where a serialized root signature sits beside the dword count it produced -(`tools/rootsig_census.py`). The game's own 26,503 containers carry no `RTS0`, so their read sets cannot be joined -with a signature and cannot settle it either. - -All 29 are version 1.1 with `Flags = 0`, 168 parameters in total (58 tables and 110 root CBVs, no 32-bit constants, -SRVs or UAVs), every parameter at `D3D12_SHADER_VISIBILITY_ALL`, and 27 of them carry one static sampler. They come -in two shapes: - -| Parameters | Signatures | `USER_SGPR` | Layer model (2 dwords per table) | One dword per table | -|---|---|---|---|---| -| 4 CBV + 2 tables | 27 | 14 | 12 | 10 | -| 1 CBV + 2 tables | 2 | 8 | 6 | 4 | - -The surplus is 2 dwords under the layer's model and 4 under one-per-table, and it is the same for both shapes: the -driver put a fixed block below the parameters. Arithmetic alone therefore does not separate the two models. The -disassembly does (`tools/rootsig_census.py --disasm`, over the same 29 programs): - -- `s4` is copied into the low half of a pair, the high half zeroed, and passed to `s_load` as the base in 29 of 29; - `s5` is in 16. The two declared tables therefore sit at s4 and s5, one dword each, in signature order, and the 13 - programs that never read `s5` are using only the first. -- A 64-bit pair is copied whole from `s6:s7` in 27 of the 29. Five of those also copy from `s8:s9`, `s10:s11` and - `s12:s13`, which matches their four root CBVs at two dwords each. The other two read none of `s6` to `s13`: they - declare four CBVs and never touch them. -- 27 read none of `s0` to `s3`. In `_05` the program adds `s0` and `s3` to `s4`, and `_07` multiplies by `s0`, so - the block below the tables is not always dead, but no program here uses one of those dwords as a pointer. - -That is `USER_SGPR = 4 + 2 per table + 2 per CBV`, which gives the measured 14 and 8, and it is the one-dword-per- -table model behind a four-dword prefix. The CS census above agrees: its lowest pointer is s4, where a four-dword -block puts the first table, while two dwords per table would put it at s2. - -Still open: which CBV index lands in which pair. The four pairs do appear in declaration order, but nothing in the -package proves that order, and every parameter in these 29 is `D3D12_SHADER_VISIBILITY_ALL`, so they say nothing -about the visibility question below. - -Spill policy: a signature needing more than 32 user SGPRs, or more than the 64-dword D3D12 cost limit, is -refused loudly (`pack` returns the offending parameter) instead of being truncated. The console spills through -`__XB_GetRootSignatureSpillPointer`; until that layout is measured, refusing is the only correct behaviour. - -Measured (D3D-315): zero below-base spill-pointer candidates in the translated shaders. -`python -I tools/root_spill_census.py --carve --expect-no-spill` exits 0 on -the 26,501 translated shaders (all but the 2 compute shaders refused for workgroup memory under wave64 emulation), -Xbox Series 1.0.2.1: -- **No root signatures in the containers.** 0 of the 26,503 carved containers have an `RTS0` part. The game - builds its root signatures at run time, so the number that exceed 32 dwords is open until they are dumped from - the executable. -- **No spill-pointer candidates.** No user-SGPR read used as an address (`ptr32_lo`, `ptr64_lo`, `ptr64_hi`) sits - below the stage base (ps/vs/gs s8, cs s4, ms s16) in any stage. For compute that block holds the measured spill - pointer `s[0:1]` (section 7); here `s0` and `s1` are never read as an address, only `s1` as a constant - (109 CS, 551 PS, 12 VS). -- **Compute stays far below the budget.** The largest RSRC2 `USER_SGPR` count is 14 (31 of 2,687 shaders), so at - most 10 of the 28 root dwords above s4 are used. -- **The highest reads are not spills.** PS reads reach s31 (8 shaders), s29 (7), s27 (1) and s25 (8); MS s29 (2) - and s27 (8); VS s25 (2). Each of those top reads is a 32-bit constant after a gap, not an address. - -What this does not settle: -- **How many runtime-created signatures exceed the budget.** The containers carry none, so that count waits for - signatures dumped from the executable. -- **Why a particular `pack()` refusal happens.** `pack()` counts two dwords per table from s0, which the census - above disagrees with, so its 32-dword limit and the console's budget need not agree. Whether a given refusal is - that model or a real spill is open until the signature and its shaders are compared. -- **A spill behind a pointer at or above the base.** It reads the same as a table pointer, so the census can't - tell the two apart. - -The spill layout stays unimplemented: no shader in the translated set reads a candidate a spill could sit behind. - -Reconciliation: `tools/root_sig_contract.py` checks a candidate root signature against every shader's -`user_sgpr_reads` from `spirv/index.json` (const32 vs constant dwords, 64-bit VAs vs view/table pairs) and fails -the build on the first contradiction. Until the console mapping in §3.5 is confirmed by a PSO, this check — not -a rendered frame — is the acceptance gate for the mapping above. - -Blob format: `rt::rootsig::parse_rts0` reads the `RTS0` chunk of a serialized root signature, versions 1.0, 1.1 -and 1.2. `root_signature_oracle_test` checks it on Windows against blobs the PC `d3d12.dll` serializes. These -layouts are measured, not assumed: -- a descriptor table's payload is `{num_ranges, ranges_offset}`, with the ranges at that offset; -- ranges are 20 bytes, or 24 with the 1.1/1.2 flags dword, in `D3D12_DESCRIPTOR_RANGE(1)` order: - `{type, count, base register, space, offset}` in 1.0 and `{type, count, base register, space, flags, offset}` in - 1.1/1.2, so the flags come *before* `OffsetInDescriptorsFromTableStart` (a range with `DATA_STATIC` and offset 7 - serializes as `… 8 7`). The parser keeps all six fields; -- root descriptors carry a flags dword from 1.1 on; -- static samplers are 13 dwords (`D3D12_STATIC_SAMPLER_DESC` order). In 1.2 they are 14: `D3D12_STATIC_SAMPLER_DESC1` - appends `Flags`, i.e. UINT border colours and non-normalized coordinates. - -Static samplers take no user-data dwords, so 1.2 changes nothing in `pack`. - -**Root-signature flag quirk.** Prior art measured Xbox root-signature descriptors carrying flags `0x03000000`; the -PC serializer rejects them with `E_INVALIDARG` because its flags live in the low 16 bits. Clear the high byte on a -private copy before calling the host serializer/deserializer; never modify the game's descriptor. The meaning of the -bits is unknown. The v1.0 `D3D12SerializeRootSignature` path keeps flags at offset +32, and a descriptor with -`0x3000001` also fails on the PC runtime. - -**Measured: where the bits come from in the package.** Of the two console-compiled clients, only `XboxBvhBuilder.dll` -sets them, and it does so twice. - -- **In its shaders:** all 52 `RTS0` parts in its DXBC containers (version 2, i.e. 1.1) carry `Flags = 0x03000000`. -- **At run time:** the builder's only `D3D12SerializeVersionedRootSignature` call (`0xc32f`, import address table - `0x180024250`, `d3d12_xs.dll`) is in the function at `0xc2d0`, which ten call sites reach. That function copies the - 48-byte `D3D12_VERSIONED_ROOT_SIGNATURE_DESC` to the stack (`[rsp+40h]`) and, with no branch before it, ORs the - bits into the copy's v1.1 `Flags` (`+0x28`): `or dword ptr [rsp+68h],3000000h` at `0xc30e`. - -`amd_fidelityfx_upscaler_xbox.dll` does neither. Its 29 `RTS0` parts carry `Flags = 0`, and no instruction in it uses -the constant `0x3000000`. So the bits are not a property of every console root signature; this builder adds them. The -game executable is not in the package, so whether its root signatures carry them is open. - -**Version 1.2 on older runtimes.** The in-box `d3d12.dll` of Windows 10 (measured on 22H2, 10.0.19045, without the -Agility SDK) and of Windows 11 23H2 (#361) serializes root signatures only up to 1.1. On Windows 10 it rejects even an -empty 1.2 description with `E_INVALIDARG`, and `D3D12_FEATURE_ROOT_SIGNATURE` reports `HighestVersion` 1.1 (#528). -Version 1.2 differs from 1.1 only in -`D3D12_STATIC_SAMPLER_DESC1::Flags`. So on such a host, the `d3d12_xs` serializer rewrites a 1.2 description whose -static samplers all have `Flags == 0` as the same root signature in 1.1. It refuses one that uses sampler flags (a -UINT border colour or non-normalized coordinates) with a log line, since 1.1 can't express them. The host is probed -once with an empty 1.2 description. `root_sig_test` checks the rewrite field by field and through the host -deserializer. - -Things that can invalidate this simple model, all **Open**: - -- **Shader visibility.** The layer starts with one global block in root-parameter order and treats visibility as - access control, not as a per-stage reordering. If the console driver instead omits invisible parameters per - stage, a VS and a PS would need different values at the same push-constant offsets, which Vulkan cannot express - with one block; that would force per-stage blocks or a per-stage indirection. **Measured, VS/PS (D3D-318):** - consistent with one block in root order. The game's shaders carry no `RTS0` and the executable that pairs them - into pipelines is not in the package, so `python -I tools/user_sgpr_census.py --pairs` pairs - a VS with a PS by technique name instead (names alike apart from the `VS_`/`PS_` token) and compares the user - SGPRs both read. Over the 1.0.2.1 corpus: 166 techniques have both stages (225 VS, 203 PS, 358 combinations). - - The 379 SGPRs both stages read have the same kind (pointer or constant) in every case. Over all 26,196,976 - VS × PS combinations, the control, 25.5% of the shared reads differ in kind. - - In 79 combinations one stage reads an SGPR the other skips, below an SGPR both read. If that parameter were - omitted from the other stage, the parameters above it would move down one SGPR there; all 111 shared reads - above such an SGPR still agree. - - It can't tell a hidden parameter from a visible one a stage doesn't read, and it doesn't see the root signature, - so the executable's pipeline table would settle it; `tests/test_user_sgpr_census.py` shows that the two models - give different counts. Mesh shaders (base s16) and the compute signatures are not covered here. -- **Root signature larger than 32 dwords.** D3D12 allows up to 64 dwords. The console has 32 user SGPRs, so a - driver must spill the rest to memory, probably behind a pointer in the user data. The current shader contract has - no representation for that. The likely answer is that this game keeps its root signatures small (bindless - descriptors, a few constants), but it must be measured. If a large root signature appears, the spill layout has - to be reverse-engineered from the shader's loads. Measured on the shader side (D3D-315, spill policy above): - zero below-base spill-pointer candidates in the translated shaders. The root signatures themselves, and how many - exceed the budget, are still to be dumped from the executable. -- **Direct heap indexing.** The bound heap base and stride are not root parameters. Measured (D3D-329, section - 3.4): each heap's base reaches the shader as a 32-bit pointer in an entry SGPR, inside the user data for compute - (and below `s32` for the graphics stages, whose user count is not measured yet), and the stride is compiled into - the shader's offsets. So the translator needs no new runtime value; the layer has to write the bound heap bases - into the user-data slots the root-signature mapping assigns them. The root signature - flag tells us direct indexing is enabled; the shader's address arithmetic identifies the base. -- **Static samplers.** D3D12 static samplers do not consume root parameters. The console driver may place their - S# values in a fixed table. The layer registers every static sampler's S# in the hash table, so a shader that - loads it by value works; a shader that expects a driver table needs that table's location (**Open**). - `CreateRootSignature` does the registering, for 1.0, 1.1 and 1.2 blobs: each static sampler is encoded as - `CreateSampler2` encodes the same description (the five `D3D12_STATIC_BORDER_COLOR` values, two of them UINT, and - the 1.2 flags), and gets a sampler in set 0 and a key in the hash table without a heap slot. The entry outlives - the root signature. `d3d12_descriptor_test` checks the key before and after and samples with it. - loads it by value works; a shader that expects a driver table needs that table's location. **Measured - (SHADER-735): no sampling instruction in the corpus was found reading an S# from a fixed table** (0 of 366,628; - 0.66% stay undetermined under the conservative reading), so on this evidence the layer has none to emulate; the - counts and their limits are under "Where the sampled S# comes from" below. -- **Descriptor-table high-dword truncation.** If a shader forces the high dword of a table pointer to zero, the - table must be below 4 GB; the layer allocates all shader-visible heaps there. If a shader forces a resource VA's - high dword to zero, the resource must also be low; that would constrain the arena layout. Measured on 2026-11-22 - over package 1.0.2.1 (`python -I tools/ptr_truncation_census.py /shaders/disasm`, all 26,503 shaders, the - `truncates_high` / `ptr32_lo` rule of `tools/shader_meta.py`): 25,865 shaders truncate at least one pointer - (VS 2,038 of 2,236, PS 11,666 of 12,101, CS 2,684 of 2,689, GS 195 of 195, MS 9,282 of 9,282), 86,036 truncated - pointers in all, at most 5 per shader. Every one is the base of a 4/8/16-dword descriptor load (`s_load_dwordx4/x8/x16`, - a table pointer) from a user SGPR, and no 1–2 dword `s_load` base is truncated. No `global_*` in the corpus - takes its base from SGPRs: its 10,548 `global_*` instructions (530 shaders) address through VGPR pairs, which the - classifier does not follow. 25,669 shaders truncate every user-SGPR pointer they dereference, 196 only some (the - 195 GS, whose 64-bit s8 pointer has a high dword the classifier cannot resolve, and one CS), and the other 638 - dereference no user-SGPR pointer. Bases not rooted in a user SGPR (462 shader/access combinations) never have a constant-zero - high dword. So what is measured to need the low 4 GB is the descriptor heaps; buffer addresses reach the shaders - inside V#s (48-bit bases) or in VGPRs for `global_*`, and this count sees neither, so it does not show that - buffers may sit above 4 GB. - -**Where the sampled S# comes from** (SHADER-735; counts only). `tools/sampler_source_census.py` follows the four -SGPRs of the sampler operand of every `image_sample*`, `image_gather4*` and `image_get_lod` back to where their -values are made: through constants, scalar loads, SGPRs spilled to a VGPR and read back, and joins, where it keeps -the sources of every path. Over the 1.0.2.1 corpus (26,503 listings, none skipped; the ones with embedded data -words are re-anchored as the translator does) 14,025 shaders sample, with 366,628 such instructions: - -| stage | sampling instructions | loaded through user data | literal | held in user SGPRs | other base | undetermined | -|---|---|---|---|---|---|---| -| CS | 120,816 | 63,141 | 57,674 | 0 | 0 | 1 | -| MS | 21,992 | 10,142 | 9,723 | 0 | 0 | 2,127 | -| PS | 221,157 | 115,109 | 106,048 | 0 | 0 | 0 | -| VS | 2,663 | 1,020 | 1,351 | 0 | 0 | 292 | -| all (the 195 GS do not sample) | 366,628 | 189,412 | 174,796 | 0 | 0 | 2,420 | - -- **Other base** is what a driver table would be: some dword of the S#, on some path, held in or loaded through a - constant address, a system SGPR (at or above `USER_SGPR` in CS; `s32` and up in the graphics stages, and the - NGG `s3` in MS and GS) or a code-relative address. It wins over every other class, the undetermined one - included, and it is empty in every stage. -- **Loaded through user data**: an `s_load_dwordx4` or wider at an address that starts from a user SGPR, 179,602 - at a static offset (0x540 at most) and 9,810 at a run-time one. No constant is added to any of these pointers, - so `constant table address + user index`, which is the same arithmetic as `user pointer + constant` and which - the classes could not tell apart, does not occur either. All 189,412 are in shaders whose `SFI0` sets the - sampler-heap bit: no shader without it loads an S# from memory. Whether one of these loads goes through a - descriptor table or through the sampler heap base of section 3.4 the shader cannot say; both are a user SGPR. -- **Literal**: four immediates, 105,235 in shaders with the sampler-heap bit and 69,561 in shaders without it, - which sample with nothing else. 28,659 of them, in 6,824 shaders, build one dword with `s_brev_b32`. - `tools/shader_meta.py` does not fold that instruction, so `literal_samplers` in the index does not list those - S#s yet and the layer cannot register them from it. -- **Undetermined** (0.66%, in 300 shaders): with every edge followed, some path brings something else into the S# - registers. 2,355 read the S# back from a VGPR it was spilled to, and one path does not save it there (on the - paths that do, it is a load through user data); in 64 the paths bring a literal and a load through user data; - in 1 a path brings a value the dataflow does not follow. All of them go away with one kind of edge: the S# is - made or saved inside a region the compiler jumps over with `s_cbranch_execz` when no lane is active, and the - sample comes after the region. Without the taken edge of those branches (the region always runs, as it does - whenever a lane is active) the same analysis gives all 2,420 a class: 2,419 loaded through user data, 1 - literal. The table keeps them apart because that second reading trusts that nothing samples on the skipping - path; lane masks are not modelled. - -So, as far as the shaders can answer it, this corpus gives no evidence of a driver sampler table: no instruction -lands in the other-base class, and the 2,420 undetermined ones are not shown to be free of it by the conservative -reading, only by the one that assumes nothing samples on an exec-zero skip. -What the census does not show: it reads the shaders, not what the driver writes at the addresses they load from; -the graphics stages' user count is the translator's 32, not a measured one (question 3 in section 8.2); and it -cannot say which S# is a root signature's static sampler. The literals are the candidates, since a static sampler -is known when the shader is compiled and half of the sampling instructions build their S# from immediates, but -that is a hypothesis until the root signatures are matched against them. Reproduce with -`python -I tools/sampler_source_census.py /shaders/dxbc/disasm --jobs 4 --expect-none other_base`, which -exits 1 if an instruction lands in that class. - -**What the console's own D3D12 libraries show** (names only, read statically from a user's console system-file -dump; nothing from those files is in this repository): - -- Two root-signature ABIs exist. The driver's validation messages name a flag - `D3D12XBOX_ROOT_SIGNATURE_FLAG_FORCE_MEMORY_BASED_ABI`, and require it for ray tracing (XDXR) and for pipelines - with an amplification shader. So the default is the register-based ABI this section describes, and a root - signature can opt into a memory-based one. The shader compiler has the matching switch, - `XBOX_FORCE_MEMORY_BASED_ABI`. -- The ABI is decided when the shader is compiled, not by the driver at bind time. The shader compiler has the - intrinsics `__XB_GetShaderUserData` and `__XB_GetRootSignatureSpillPointer`. That answers the "larger than - 32 dwords" question above: parameters that don't fit in the user SGPRs spill to memory, and the shader reads a - spill pointer from its user data. Because the game ships precompiled shaders, each shader's own user-SGPR reads - (and any loads through a spill pointer) are the authoritative map; the metadata below is how to recover it. -- `d3d12_xs.dll` is a thin front end (about 50 KB). It loads the user-mode driver, `xgs12_10.dll`, which implements - the device and command lists and exports `UMD*` entry points. `xg_xs.dll` exports the texture layout functions - (`XGComputeTexture2DLayout`, `XGComputeOptimalSwizzleMode`, ...), the reference for untiling textures. -- The driver keeps the standard D3D12 root-signature cost limit: 64 dwords, with descriptor tables costing 1 and - root views 2. - -**Required build metadata.** To solve the mapping without guessing, `spirv/index.json` should gain, per shader: - -- the set of user-SGPR dwords read before first write, and whether each is used as a 32-bit constant or a 64-bit - pointer; -- the descriptor stride(s) implied by descriptor address arithmetic; -- whether the shader uses the code base (`s_getpc_b64`) and, if so, in which stage; -- the literal S# values it builds from immediates; -- the input signature (semantic name/index, register, mask, component type), not just the register numbers; -- the FSSM content hash (the PSO lookup key, section 3.6); -- the descriptor-table / heap-direct-indexing mode the shader was compiled for. - -The runtime can then reconcile the root signature with the shader's reads and fail loudly on a mismatch instead of -rendering silently wrong. - -`tools/shader_meta.py` (invoked by `tools/rdna2spirv.py` and verified by `tests/test_shader_meta.py`) now emits these -fields into `spirv/index.json`: `user_sgpr_reads` (`const32`, `ptr64_lo`/`ptr64_hi`, `ptr32_lo`, `vsharp`, `tsharp`, -`ssharp`), `descriptor_strides`, `uses_code_base`, `literal_samplers`, `input_signature` (ISG1 semantic name/index, -register, masks, system value, component type), `fssm_sha256`, and `descriptor_access` (DXBC `SFI0` direct-indexing -bits 25/26 plus table-load and high-dword-truncation flags). A missing or malformed ISG1 signature leaves the vertex shader -without recorded inputs. In that case the runtime accepts any input layout when filtering shader candidates. - -### 3.6 Shader identity, PSOs and feature selection - -A D3D12 PSO carries DXBC containers, not SPIR-V. The layer identifies a shader by hashing the **FSSM payload** (the -native RDNA2 program inside the container) and looking it up in a build-time table keyed by `(stage, hash)`. The -build emits that hash for every translation; the runtime extracts the FSSM chunk from the DXBC container the same -way `tools/fssm_unpack.py` does. The current `spirv/index.json` is keyed by carve name, which the runtime may not -have; add the content hash to the index. - -Pipeline creation: - -- `D3D12_GRAPHICS_PIPELINE_STATE_DESC` is supported today (`CreateGraphicsPipelineState`), as is the compute desc. The - `D3D12_PIPELINE_STATE_STREAM_DESC` subobjects (`CreatePipelineState`) are not implemented yet. The plan: parse the - stream subobjects in order; unknown types are a hard error with the type number logged. -- Build `VkPipelineShaderStageCreateInfo` from the translated module and the index entry. Mesh shaders use - `VK_EXT_mesh_shader` (`AS`/`MS` subobjects → task/mesh stages); geometry uses the geometry stage; compute uses a - compute pipeline. -- The index's `max_vertices`/`max_primitives` already size the SPIR-V mesh output arrays. Vulkan has no - per-pipeline mesh output limit: check them against - `VkPhysicalDeviceMeshShaderPropertiesEXT::maxMeshOutputVertices`/`maxMeshOutputPrimitives` and fail at pipeline - creation if the device is smaller. -- Vertex input comes from the PSO input layout plus the shader's ISG1 signature. The translator's rule is - **location = D3D input register**, not the semantic's HLSL slot. Match the layout element's semantic name/index - to the ISG1 element to get the register, then create a `VkVertexInputAttributeDescription` with that location - and the DXGI format. Resolve `D3D12_APPEND_ALIGNED_ELEMENT` against the preceding element and honour - `InputSlotClass`/`InstanceDataStepRate`. The index entry needs the semantic map (section 3.5). -- Enable the features the index entry lists: barycentrics, fragment interlock, mesh, geometry, Float64, Int64, - buffer device address, storage image without format, maintenance8. -- Request the subgroup size each shader was translated for (`requiredSubgroupSize` 64 or 32) where the device lists the stage - in `requiredSubgroupSizeStages`, and say so in the log where it cannot (section 3.2, "Subgroup size"). -- Pipeline caches: graphics and compute PSOs use one `VkPipelineCache` per device. On first use the runtime reads - the `pipelines` build stage's `pipeline_cache.bin` beside the executable if its Vulkan header matches the device - and pipeline-cache UUID. When the file is absent or incompatible, the runtime starts with an empty cache. - The offline checker matches the runtime's layout and subgroup request for compute shaders with no descriptor - bindings and the standard 144-byte push-constant range. - `GetCachedBlob` records the vendor, device, driver version, `pipelineCacheUUID` and a SHA-256 of the description - without `Flags`, sealed by a checksum (`runtime/src/cached_pso.h`). The answers are the host's, measured on an - RTX 3060 and WARP: the same description is accepted; another - shader, root signature content or state, a changed byte, a truncated blob or a pointer with size 0 give - `E_INVALIDARG`; a null pointer with a size is ignored; another adapter gives `D3D12_ERROR_ADAPTER_NOT_FOUND` and - another driver `D3D12_ERROR_DRIVER_VERSION_MISMATCH`. `ID3D12PipelineLibrary` is an in-memory map plus the Vulkan - cache. Its arguments answer as the host's (`d3d12_pipeline_library_host_test`, 74 values from 46 calls that need no - PSO, each run on the host in a process of its own, since a call it faults on leaves its runtime broken and the next - one failing fast; RTX 3060, driver 610.88): - - `CreatePipelineLibrary`: a foreign, truncated or corrupt blob, the other device's blob, or a null pointer with a - size is `E_INVALIDARG`, and `*ppPipelineLibrary` is left as it was. One of the layer's own blobs from another - format version is `D3D12_ERROR_DRIVER_VERSION_MISMATCH`, the documented code for a cache from another driver. - A pointer with size 0 is an empty library; a longer blob than the header is accepted; a null output is - `S_FALSE`. - - The library is a device child, not a pageable object: `QueryInterface(ID3D12Pageable)` is `E_NOINTERFACE`. - - `LoadComputePipeline`/`LoadGraphicsPipeline`/`LoadPipeline` with a null output are `E_INVALIDARG`, as is an - unknown or empty name. `Serialize` with a buffer smaller than `GetSerializedSize()` is `E_INVALIDARG`. The - serialized size and bytes are each device's own (the host's empty library is 900 bytes, the layer's 16). - - Not compared: the calls the host runtime faults on (`Serialize(nullptr, n)`, `StorePipeline` with a null PSO, - `Load*` with a null name or description); the layer answers `E_INVALIDARG` for each. - -**Open:** whether the game uses `D3D12_PIPELINE_STATE_STREAM_DESC` for mesh/RT and which subobject types appear. -The trace will enumerate them. - -**Implemented (D3D-29): pipeline state streams, mesh PSOs and `DispatchMesh`.** -- **Device:** `VK_EXT_mesh_shader` with `meshShader` is enabled where the GPU has it (`VulkanDeviceInfo::mesh_shader`). - `taskShader` is not enabled, since the corpus has no amplification shaders. `D3D12_OPTIONS7` reports - `MeshShaderTier` 1 only then; without the extension it reports `NOT_SUPPORTED` and mesh PSOs are `E_NOTIMPL`. -- **Streams:** `CreatePipelineState` parses the stream in the d3dx12.h layout: a subobject type, then its - description at that description's alignment, each subobject pointer-aligned. - - Every type up to `RASTERIZER2` is read. - - Missing subobjects take the runtime's defaults: depth test on with `LESS`, back-face culling, no blending, sample - mask `0xFFFFFFFF`, one sample. - - The stream becomes the same descriptions `CreateGraphicsPipelineState` and `CreateComputePipelineState` take, so - a VS stream builds the same PSO as the classic call. - - `E_INVALIDARG`, as on the PC runtime: a type given twice, an unknown type, a truncated stream, MS with VS, - tessellation or GS, CS with a graphics stage, or no stage at all. - - `E_NOTIMPL` with a log, for what is not built yet: an AS, a depth-bounds test, separate front and back stencil - masks, view instancing. - - `RASTERIZER1`/`2`'s float depth bias is truncated to the integer the PSO path takes, with a log. -- **Mesh PSO:** the MS (`ms` index entry by FSSM hash) and PS on the mesh stage. It has no vertex input or input - assembly; the input layout, topology type and strip cut are ignored, as D3D12 ignores them for mesh PSOs. Topology - and strides are not dynamic state there (VUID-VkGraphicsPipelineCreateInfo-pDynamicStates-07065/07066). Creation - is refused when the index's `max_vertices`/`max_primitives` or the workgroup size exceed the device's - `VkPhysicalDeviceMeshShaderPropertiesEXT`. -- **`DispatchMesh`:** recorded as a `Draw` with `mesh` set; the thread-group counts go in `count`/`instances`/`first`. - It takes the same state snapshot as `DrawInstanced`: render targets, root arguments, viewport, scissor, blend - factor, stencil references. Replay issues `vkCmdDrawMeshTasksEXT`. - - **Recording errors** (`Close` returns `E_INVALIDARG`): a grid above 65535 per count or 2^22 groups. - - **Not recorded:** an empty grid. - - **Execution error** (`ReplayResult::invalid_draw`): a mesh draw with a VS pipeline, or the reverse. -- **Tests:** `d3d12_mesh_test` checks the refusals and three draws pixel by pixel on an RX 9060 XT (RADV, under - Wine), validation-clean. - - **The three draws:** a 2×2×1 and a 1×1×2 mesh grid, plus a VS PSO from a stream. - - **What it doesn't cover:** whether the console flattens a 3D `DispatchMesh` grid the same way. That is an open - question in `docs/design.md`, "Mesh shaders"; the test shader reads the workgroup ID directly. - -## 4. Object model mapping - -| D3D12 / Xbox object | Vulkan / layer object | Notes | -|---|---|---| -| `ID3D12Device` … `ID3D12Device11` | one `Device` object with the public chain plus measured Xbox overrides | The shipped BVH builder names Device11; slots 1/15/18/19/27/38 matched desktop in prior art, slot 62 is called as `CreateComputePipelineState`, slot 76 is Xbox texture creation, and heap slots 9/10 return in RAX. Unknown Xbox IIDs/slots are logged and refused. | -| `ID3D12CommandQueue` | one leased `VkQueue` per live queue: direct queues on the graphics family, compute queues on an async-compute family and copy queues on a transfer-only (DMA) family when the GPU has them (`src/queue_families.h`), else graphics-family leases | Distinct Vulkan queues allow cross-queue waits and signals to make progress. With more than one family in use, buffers, images, the arena and staging are created `VK_SHARING_MODE_CONCURRENT` over those families, so no ownership transfers are needed. Barriers on copy and compute queues are narrowed to the stages their family has; render-target and depth clears are refused there (as in D3D12), and the D24/RGB96 copy conversions and bindless flushes stay off a transfer-only queue. Tested by `vk_queue_test`. `PresentX`, `SuspendX`, `ResumeX` are Xbox queue methods, not in the public vtable; public GDKX samples present only through them (§4.5). Call shapes known, slots **Open**. | -| `ID3D12CommandAllocator` | IR arena + `VkCommandPool` | Reset only when the previous submission's fence is complete. | -| `ID3D12GraphicsCommandList` … `8` | `CommandList` with IR | Replay at `ExecuteCommandLists`; bundles inlined. Supports render passes, mesh dispatch, enhanced barriers; records the GCL8 front/back stencil references (applied only once a pipeline path consumes them). `Draw` views are inlined and moved into the command stream (D3D-289), eliminating per-draw heap allocations. | -| `ID3D12RootSignature` | `RootSignature` + `VkPipelineLayout` | Deserialize the blob with the host `D3D12CreateVersionedRootSignatureDeserializer` when possible; clear the measured `0x03000000` flag byte on a copy first; fall back to a local parser. Build the user-SGPR map and static samplers. | -| `ID3D12PipelineState` | `VkPipeline` + a `PipelineInfo` | Shader hash → SPIR-V + index entry; PSO state → Vulkan state; dynamic state where possible. The BVH builder's compute PSOs arrive at device slot 62 with a plain `D3D12_COMPUTE_PIPELINE_STATE_DESC`. | -| `ID3D12DescriptorHeap` | `DescriptorHeap` (shadow + optional arena range) | CBV/SRV/UAV and sampler heaps can be shader-visible; RTV/DSV are host-only. Start handles use the measured RAX return at heap slots 9/10. Increments are layer-chosen (32/32) pending the console value. | -| `ID3D12Resource` | `Resource` (a range in the arena buffer; a separate `VkImage` for textures) | Committed, placed and reserved. Reserved buffers use sparse memory where supported (section 4.2). Xbox textures may arrive through device slot 76. `GetGPUVirtualAddress` returns a console VA (a buffer offset or an image key). | -| `ID3D12Heap` | `Heap` (a reserved VA range) | Buffer ranges are backed by the arena; images get their own `VkDeviceMemory`. Residency calls are no-ops. True buffer/image aliasing inside a heap is **Open**. | -| `ID3D12Fence` / `ID3D12Fence1` | `Fence` over a timeline `VkSemaphore` | `GetCompletedValue` = counter value; `SetEventOnCompletion` = wait thread + Win32 event; CPU `Signal` = host signal. | -| Resource barriers (legacy) | `vkCmdPipelineBarrier` | Per-subresource state tracking; `BEGIN_ONLY`/`END_ONLY` become conservative full barriers at the begin point. | -| Enhanced barriers (`ID3D12GraphicsCommandList7::Barrier`) | `vkCmdPipelineBarrier2` | Direct mapping of sync/access/layout; prefer it when the game uses it. | -| `IDXGISwapChain` / `IDXGIFactory` | Factory/adapter/output: fake objects. `Swapchain` over `VkSwapchainKHR` + Win32 surface: only for the PC-style path | Shim DXGI; do not bind host DXGI. A GDKX title likely creates no swapchain (§4.5); it needs `IDXGIDevice1`→`GetAdapter`→`EnumOutputs` and a `PresentX` + frame-event presenter instead. | -| `ID3D12QueryHeap` | `VkQueryPool` | Occlusion, binary occlusion, pipeline statistics, timestamps. Binary results clamped to 0/1. | -| `ID3D12CommandSignature` | `IndirectLayout` | Simple draw/dispatch signatures map to indirect calls; root-constant/vertex/index/descriptor changes need expansion. | -| `ID3D12PipelineLibrary` | map + `VkPipelineCache` | D3D12 cached blobs are ignored. | -| `ID3D12StateObject` (ray tracing) | likely unused | RT work includes compute traversal (`image_bvh*`) plus `XboxBvhBuilder`; a DXR state-object path is stubbed until the trace shows it. | -| `ID3D12ShaderCacheSession` | `VkPipelineCache` | Stub with logging. | -| DRED, protected sessions, meta commands, shared handles | stubs | Not needed for single-player boot; return a clean failure and log. | - -### 4.1 Device and feature queries - -`CheckFeatureSupport` is a boot-critical diagnostic. Answer from the Vulkan device, not from a wish list: - -- `D3D12_FEATURE_ARCHITECTURE`: report the host GPU's UMA property. The console is UMA; a discrete PC GPU is not. - Reporting the truth may change the game's upload strategy; reporting a lie can make it map memory it cannot map. - Start truthful and log the game's reaction. -- `D3D12_FEATURE_LEVELS`: report the highest feature level the Vulkan device can satisfy (12_2 when mesh/RT - features are present). -- `D3D12_FEATURE_SHADER_MODEL`: answer the shader model the layer can honour, not the driver's maximum. Nothing in - the runtime compiles DXIL: the game's shaders arrive as SPIR-V from the offline translator, and the BVH - builder's container also carries a console FSSM program that the same translator handles. A request above 6.0 is - clamped down to 6.0, a request for 5.1 is answered with 5.1 (D3D12's own baseline, which a caller asking for the - minimum expects), and a value below 5.1 is refused with `E_INVALIDARG`. Measured against the host PC runtime - (616.86) on an RTX 5070: 5.1-6.8 echo the request, 6.9 clamps to 6.8, and `0` is `E_INVALIDARG`; `0x5f` crashed - the host runtime, which the test records in a comment rather than repeating. WARP answers a 5.1 request the same - way. -- `D3D12_FEATURE_ROOT_SIGNATURE`: 1.1, the version the proxy can always produce. A 1.2 blob is rewritten as 1.1 when - the host's serializer stops at 1.1 and nothing is lost (`d3d12_xs_rootsig.cpp`), and Windows 10's `d3d12.dll` stops - there, so 1.1 is what the game can rely on everywhere. A 1.2 request is clamped down to 1.1, and an undefined value - (0, or anything above 1.2) is `E_INVALIDARG` with the value left as it was. Measured against the host PC runtime - (616.86): 1.0-1.2 echo the request, and a wrong `DataSize` is `E_INVALIDARG`; the host crashed on a null buffer, so - the test never gives it one. The refusal above 1.2 was measured on an RTX 4070 Laptop (621.24) and WARP. -- `D3D12_FEATURE_D3D12_OPTIONS1`: answer from the Vulkan device's subgroups. `WaveOps` is true only when every - operation group the wave intrinsics map to is present (`BASIC`, `VOTE`, `BALLOT`, `SHUFFLE`, `ARITHMETIC`), - because D3D12 promises them all behind that one bool. `WaveLaneCountMin`/`Max` are the subgroup size range - (`VkPhysicalDeviceSubgroupSizeControlProperties`, or the single `subgroupSize` without those 1.3 properties). - The exception is an Intel integrated GPU of the pre-Xe-LPG lines (D3D-121): Vulkan reports 8..32 there, Intel's - D3D12 driver a fixed 16..16, and the layer answers 16..16 like the host. Measured on Xe-LP: UHD 770 - (32.0.101.6129), Raptor Lake-S Mobile (101.7092) and Tiger Lake 0x9a78 (101.7088). From Xe-LPG on the driver - answers the same range Vulkan reports (D3D-280, measured Meteor Lake 0x7d55 on 32.0.101.6127: 8..32 on both - sides), so those lines keep the Vulkan range (Meteor/Arrow Lake device IDs 0x7d40-0x7dc5, Lunar Lake - 0x64a0-0x64b6). Discrete Arc keeps the Vulkan range until it is measured (TEST-57). - `TotalLaneCount` has no Vulkan equivalent: D3D12 counts every lane of the device, and the layer answers one full - wave, so a game that sizes work from it plans for less parallelism than the GPU has, never more. Measured - against the host PC runtime (616.86) on an RTX 5070: `S_OK` with `WaveOps` 1, lanes 32..32 and a total of 6144, - and `E_INVALIDARG` for a `DataSize` one field too short or too long. The host crashed the process on a null - buffer, so the layer refuses one without asking the host (as with root signatures). -- `D3D12_OPTIONS` families: report the tier the Vulkan feature set can honour (resource binding tier 3 when - descriptor indexing and update-after-bind are available), plus wave ops, 16-bit, barycentrics, render passes, - VRS, mesh shader tier, and RT tier 1.1 only if the layer can honour them. The game may branch on these; a false - "supported" is worse than a false "unsupported" at boot. For `OPTIONS2`–`5`, `7`, `9`, `11`, `13`–`16`, and - `18`–`21` (D3D-86; leaving `OPTIONS1` to #745, `OPTIONS6`/`10` to #469, `OPTIONS8` to #715, and `OPTIONS12` to - #693): - - `OPTIONS4` reports `MSAA64KBAlignedTextureSupported = TRUE` (implemented in `GetResourceAllocationInfo`); - - `OPTIONS19` maps `SupportedSampleCountsWithNoOutputs` from `framebufferNoAttachmentsSampleCounts`, ties - `AnisoFilterWithPointMipSupported` to `VulkanDeviceInfo::sampler_anisotropy`, and reports the baseline heap - limits (`2048` samplers, `1000000` views); - - `OPTIONS21` reports baseline `D3D12_EXECUTE_INDIRECT_TIER_1_0`, and unimplemented features/tiers (`DepthBounds`, - `CastingFullyTypedFormat`, MSAA UAVs, independent stencil masks, render passes, RT, mesh shaders, sampler - feedback, wave MMA, work graphs, GPU upload heaps) stay `FALSE`/`NOT_SUPPORTED`/`TIER_0`. Checked live against - the host D3D12 runtime on the same adapter (`NVIDIA GeForce RTX 5080`, driver `616.56`, Windows 11): 15/15 feature - queries compared with `0` mismatches (`MSAA64KBAlignedTextureSupported = TRUE`, - `SupportedSampleCountsWithNoOutputs = 0x1d`, `LEONIDA_VK_VALIDATION=1` with `0` validation errors). -- `D3D12_FEATURE_FORMAT_SUPPORT`: map to `vkGetPhysicalDeviceFormatProperties`; multisample render-target - and resolve bits also require the format's image-usage/sample-count query to succeed. D3D12's per-format - rules then apply, as native D3D12 reports them (RX 9070 XT, AMD 26.11.2, and WARP): - - `MIP` wherever the image can have more than one level. - - `SHADER_GATHER` with `SHADER_SAMPLE`, including `A8_UNORM`. Its swizzled R8 view gathered the same four - alpha values as native D3D12 and WARP on 49 footprints. `d3d12_descriptor` also verifies a view that forces - alpha to zero. - - `UAV_TYPED_LOAD` with every typed UAV. Typed UAV texture reads use the sampled binding (`image_read_typed`), - not a storage-image read. Typed buffer UAVs: the layer now writes their V# (section 3.4, "Buffer UAVs"); the - gap left is `rdna2spirv.py` `FORMATS`, which decodes only some buffer formats (the 32-bit SINT ones, but no - 8/16-bit SINT/UINT other than the RGBA8 and RGBA16 UINT ones, and no 10_11_11). - - The UAV atomic bits other than exchange for `R32_UINT`, whose UAV views get the `r32ui` storage view. Today - that works on 2D UAVs only: the translator's image atomics and the `r32ui` slots cover 2D and 3D, and the - layer creates no 3D UAV views yet. There is no `image_atomic_swap`, and `R32_SINT` gets no `r32ui` view. - - `MULTISAMPLE_RENDERTARGET` for depth formats, from the same usages `MULTISAMPLE_QUALITY_LEVELS` queries. - - No integer resolve, no 1D block-compressed. Depth formats are 2D and cube only: no 3D, shader reads, UAVs, - buffer or vertex use, and no 1D, which native D3D12 allows but the layer's resource creation refuses. - - TYPELESS formats report texture dimensions and `MIP` only. - - `d3d12_vulkan_device_test` checks these bits for every format that both the layer and native D3D12 on the same - adapter (matched by LUID or PCI ID) support. Some checks compare with the host and some check the layer's own - consistency; the comment on `compare_format_support` lists which are which. Formats the layer answers with no - uses, such as D24 without Vulkan D24, are listed but not checked. It skips when there is no host on the same - adapter (Wine, or no LUID/PCI match). -- `D3D12_FEATURE_FORMAT_INFO`: report the DXGI plane count independently of Vulkan texture support. Both - depth/stencil families (including their view formats), NV12, P010, P016 and NV11 have two planes. The - device test compares counts and HRESULTs with native D3D12 on the same adapter. If an older host rejects the - sampler-feedback formats or `A4B4G4R4_UNORM` with `E_INVALIDARG`, the test still requires the layer to return - `S_OK` and one plane for them. -- `D3D12_FEATURE_MULTISAMPLE_QUALITY_LEVELS`: query `vkGetPhysicalDeviceImageFormatProperties` for the matching - colour or depth/stencil attachment usage, plus the transfer and sampled usages used by the resource implementation. - Vulkan exposes one standard sample pattern, so a supported sample count reports one quality level (quality index 0); - only D3D12's legal sample counts (powers of two up to 32) are exposed. -- `D3D12_FEATURE_GPU_VIRTUAL_ADDRESS_SUPPORT` (`D3D12_FEATURE_DATA_GPU_VIRTUAL_ADDRESS_SUPPORT`): report the - arena's limits, not the console's. -- `GetResourceAllocationInfo` and `GetCopyableFootprints`: implement D3D12's rules locally; the game uses them to - suballocate and to lay out uploads. They are deterministic and public. Validate against a host D3D12 device in - tests if one is available; do not require one at runtime. `GetResourceAllocationInfo` (and `1`/`2`): a buffer - takes its width rounded up to 64 KiB, aligned to 64 KiB. A texture's size is the memory its `VkImage` needs - (`vkGetDeviceImageMemoryRequirements`), rounded up to its D3D12 alignment. That alignment is 64 KiB, or 4 MiB with - MSAA. The small alignments (4 KiB, or 64 KiB with MSAA) apply only when the application asks for them. 4 KiB - also needs the texture to fit in 64 KiB and not be a render target or depth buffer; if it doesn't qualify, the - description is invalid (`UINT64_MAX`), as the PC runtime answers. The MSAA 64 KiB alignment has no size limit - on the PC runtime, so none here either. Texture sizes are the driver's on both runtimes, so only buffer sizes, - alignments and invalid descriptions are compared with the host. One known difference: a mip count beyond the - full chain is invalid here (Vulkan can't create it), while the PC runtime still answers with a size. - A total over several resources that passes 2^64 saturates at `0xFFFFFFFFFFFF0000` here. Hosts disagree on it: - WARP and the RTX 5070 host of #1204 saturate too, while on Windows 26300.9974 (D3D12Core 10.0.26100.9818) the - Intel Raptor Lake-S (101.7092) and RTX 5060 Laptop (621.24) hosts wrap, two 2^63 buffers to 0, and WARP on that - PC still saturates. A wrapped total could make a caller allocate less than one of its resources, so the layer - keeps saturating, and the test accepts a host that wraps. -- `GetAdapterLuid` (implemented): `VkPhysicalDeviceIDProperties::deviceLUID`, which on Windows is the DXGI - adapter's LUID; `d3d12_fence_timing_test` finds it with `IDXGIFactory4::EnumAdapterByLuid` (RTX 4090, driver - 621.14). A driver that reports `deviceLUIDValid = VK_FALSE` gets a zero LUID, logged. -- `GetCustomHeapProperties` (implemented): the D3D12 documentation's table for the architecture - `D3D12_FEATURE_ARCHITECTURE` reports. On a discrete GPU (`UMA = FALSE`): `DEFAULT` is `NOT_AVAILABLE`/`L1`, - `UPLOAD` `WRITE_COMBINE`/`L0`, `READBACK` `WRITE_BACK`/`L0`, `GPU_UPLOAD` `WRITE_COMBINE`/`L1`. On an integrated - GPU (`UMA = TRUE`, `CacheCoherentUMA = FALSE`) the same pages, all in `L0`, and a custom heap in `L1` is refused - with `E_INVALIDARG` (`CreateHeap`, `CreateCommittedResource`), as the host runtime does on - a Radeon 780M (AMD 32.0.13030.13001) and on WARP. All answers have type `CUSTOM` and node masks 1. `CUSTOM`, - unknown types and node masks above 1 get an all-zero answer, logged. The test compares `DEFAULT`, `UPLOAD` and - `READBACK` byte for byte with the host runtime's answer when the host adapter has the layer's architecture (RTX - 4090: identical); `d3d12_heap_properties` compares the `L1` heaps with the layer's own adapter. -- Residency and power (D3D-33) are no-ops that still check their arguments (`d3d12_vulkan_device.cpp`, tested in - `d3d12_vulkan_device_test`). Vulkan has no residency API: memory from `vkAllocateMemory` stays usable until - `vkFreeMemory`, and paging under pressure is the kernel driver's job, so every pageable object is always resident. - The residency answers are the host runtime's: `d3d12_residency_test` runs the same 58 steps on both devices - with a committed buffer, a heap, a placed buffer, a descriptor heap, a query heap and a fence, and compares every - HRESULT, the device-removed reason after each step, and the value `EnqueueMakeResident` leaves the fence at - (110 values; RTX 3060, driver 610.88). Steps that leave the host runtime unusable run there in a child process with a - fresh device. - - `MakeResident` and `Evict` return `S_OK` for any count of this device's pageable objects, the same one twice, - an evicted one or a resident one. D3D12 documents `Evict` as a hint the runtime may defer, so dropping it is - allowed. - - `SetResidencyPriority` (Device1): only objects that own their memory take a priority, committed resources and - heaps; any `UINT` is a valid priority for them. A placed resource (a reserved one too, by the same rule; not measured), a descriptor heap, a query heap - or a fence is `E_INVALIDARG`, also inside a longer list. The host runtime then removes its device as well - (`DXGI_ERROR_INVALID_CALL`); the layer doesn't, since a console title that sets priorities on its placed - resources would lose its device over a hint. - - `EnqueueMakeResident` (Device3) signals its fence from the CPU with the given value before returning, since - the work is already complete. A queue `Wait` on that fence must not hang, which is why the signal stays. A null - fence is accepted and nothing is signalled. `E_INVALIDARG` for flags other than `NONE` and `DENY_OVERBUDGET`; - a refused call does not signal. A value below the fence's current one moves the host's fence back; the layer's - stays where it was (see the fence note above). - - Not compared: a nonzero count with a null array, and a null entry in an array, which the host runtime - dereferences (an access violation). The layer answers `E_INVALIDARG` for the null arrays, skips a null entry in - `MakeResident`, `Evict` and `EnqueueMakeResident`, and refuses one in `SetResidencyPriority`. - - `SetStablePowerState` returns `S_OK`: Vulkan has no clock control, and the result of a frame does not depend - on the clocks. - - `SetBackgroundProcessingMode` (Device6): no Vulkan API steers driver background work, so nothing runs. The - completion event is set at once and `*pbFurtherMeasurementsDesired` is `FALSE`. A mode or action outside the - SDK's enum is `E_INVALIDARG`. - -### 4.2 Resources, heaps, placed and reserved - -- **Xbox texture creation is a separate device method at slot 76**, not `CreateCommittedResource`. Prior art - reports its shape as heap properties / heap flags / description / initial state / clear value / iid / output, - forwarded on the PC side to `CreateCommittedResource` slot 27. The description is 56 bytes plus extension words, - and its layout field is `0x101` (tiled) or `0x1` (row-major buffer). The PC proxy replaces the layout with a - driver-chosen one; our layer must recognise slot 76 and `0x101` explicitly and must not pass `0x101` to the public - layout enum. The FidelityFX upscaler creates 10 default-heap resources through this slot, so it is not optional - for middleware. The console tiled data layout is GFX10 `SW_64KB_D` (Mesa addrlib `GFX10_SW_64K_D_RBPLUS_PATINFO`), - and the detile and tile path is implemented in `resource_detile.h` and verified by `resource_detile_test` (D3D-316). -- `CreateCommittedResource`: allocate an aligned range in the arena for a buffer, or a separate `VkDeviceMemory` - for an image; record the initial state. Map `D3D12_HEAP_TYPE_DEFAULT` to device-local memory, `UPLOAD`/`READBACK` - to separate host-visible buffers. This remains the path for buffers and for any PC-style committed resource. -- `ID3D12Resource::GetDesc` returns the description with its defaults filled in, as the PC runtime does: `MipLevels` - 0 becomes the full chain, and `Alignment` 0 becomes the placement alignment, 64 KiB, or 4 MiB for a multisampled - texture (an alignment the description asked for is kept). **Implemented** and compared field by field with the - PC runtime and WARP by `d3d12_resource_desc_test`: 25 committed and reserved buffers and 2D, array, volume and - multisampled textures (measured on an RTX 3060 host and WARP, Windows 10). -- **Invalid arguments (D3D-49).** `CreateCommittedResource`, `CreateDescriptorHeap`, `CreateCommandQueue`, - `CreateFence` and `Map` return the host PC runtime's HRESULTs (no debug layer) for the cases in - `compare_invalid_arguments` (`d3d12_vulkan_device_test`): invalid ones, their valid neighbours, and - `ALLOW_RENDER_TARGET`/`ALLOW_DEPTH_STENCIL` on every format both devices create. Rules the host keeps that are easy - to get wrong: a committed resource takes no heap flag except `SHARED`, `ALLOW_DISPLAY` (textures only), - `HARDWARE_PROTECTED`, `CREATE_NOT_RESIDENT`, `CREATE_NOT_ZEROED` and `ALLOW_SHADER_ATOMICS` (only with - `ALLOW_UNORDERED_ACCESS`; measured on an RTX 4070 Laptop and WARP); a buffer refuses `ALLOW_SIMULTANEOUS_ACCESS`; - MSAA takes quality 0 or one of the two standard patterns; a buffer may be `ALLOW_RENDER_TARGET` but not - `ALLOW_DEPTH_STENCIL`, and is aligned 0 or 64 KiB only; upload heaps start in any part of `GENERIC_READ` (or - `COMMON`), readback heaps in `COPY_DEST` or `COMMON`, neither with UAVs; a texture starts in exactly - `GENERIC_READ`, in one write state alone (`RENDER_TARGET`, `UNORDERED_ACCESS` and `DEPTH_WRITE` only with the - matching resource flag, `COPY_DEST`, `RESOLVE_DEST`) or in a mix of read states (`DEPTH_READ` only with - `ALLOW_DEPTH_STENCIL`, the shader-resource states not with `DENY_SHADER_RESOURCE`), never with a buffer-only or - undefined state bit, while a buffer takes any bits except `RAYTRACING_ACCELERATION_STRUCTURE` without UAV access - (RTX 3060 / 610.88; the same rule applies to placed and reserved resources), or at all where the host reports no - ray tracing (an integrated Radeon without DXR, @aguedou-34 on #2462): the layer refuses it on a device with - neither KHR acceleration structures nor the XDXR builds; `ALLOW_DEPTH_STENCIL` is accepted for every - format of the R32, R16, R24G8 and R32G8X24 families and nothing else; a clear value needs a render target or depth - buffer and a format of the resource's family; descriptor heaps may have zero descriptors; non-monitored fences are - refused; a null output is `S_FALSE` (a capability check) except for `CreateCommandQueue`, which answers - `E_UNEXPECTED`, and `CreateDescriptorHeap` answers it before its flag, type and node rules (`S_FALSE` even for a - shader-visible RTV heap) where committed resources and fences check their arguments first; a `GPU_UPLOAD` heap is - refused, since `CheckFeatureSupport` reports `OPTIONS16.GPUUploadHeapSupported` FALSE (a host with GPU upload - heaps, which needs Resizable BAR, accepts it, so that case is compared only on a host without them); a - global-realtime queue is `DXGI_ERROR_ACCESS_DENIED` without the privilege; `Map` refuses a - non-empty read range past the buffer. Not compared, because the host faults or the layer cannot follow it: a null - heap-properties or descriptor-heap description (the host faults), more mips than the full chain (the RX 9070 XT - runtime keeps up to 16 on a 16×16 texture and dies on 17), `D32_FLOAT` and `D16_UNORM` as render targets and the R32 - and R16 colour formats as depth buffers (accepted by the host; the layer creates the Vulkan format of the same name, - and the Vulkan drivers measured can't make that attachment, so the test prints these instead of failing), - cross-adapter resources (the host takes a row-major texture on a `SHARED | SHARED_CROSS_ADAPTER` heap; the layer has - no cross-adapter sharing), an unknown descriptor heap type (accepted by the host), and the driver's own answers: - R32G32B32 render targets, 2D textures wider than 16384, `L1` custom heaps, 16x MSAA and video formats and queues - differ between the RX 9070 XT, an integrated Radeon and WARP. The rest of the table agrees on all three. -- `CreateHeap`: reserve a VA range with the requested size/alignment. `CreatePlacedResource`: assign the resource - the range at `heap_va + offset`; a buffer uses that range in the arena, an image uses the offset as a key and - binds its own memory. Vulkan image alignment can exceed D3D12's 64 KiB; because images do not share the arena, - this mostly affects true aliasing, which is **Open** until tested on the target GPU. - Its arguments are answered as the host runtime answers them (`compare_placed_reserved` in - `d3d12_vulkan_device_test`, RTX 3060 / 610.88): the description, initial-state and clear-value rules of a committed - resource (but any initial state for a buffer in an upload or readback heap, and no UAVs there); a buffer at a - 64 KiB-aligned offset; a texture at a multiple of its `GetResourceAllocationInfo` alignment (4 KiB for a small - texture), in a heap aligned at least as much, and whole inside the heap; the heap's `DENY` flags against the - resource; then a null output is `E_UNEXPECTED` and nothing is made. -- `CreateReservedResource` **implemented** (`d3d12_vulkan_device.cpp`, `src/resource_tiling.h`, checked by - `d3d12_vulkan_device_test` and `resource_tiling_test`): - - `CreateReservedResource`, `CreateReservedResource1` (no protected sessions) and `CreateReservedResource2` - (castable formats ignored) create sparse buffers when the device can bind and alias 64 KiB tiles and guarantees - zero reads from unbound pages. Reserved textures and buffers on other devices use a fully backed resource. - D3D12's description rules are kept, as measured on the PC - runtime: buffers are `ROW_MAJOR`, textures `64KB_UNDEFINED_SWIZZLE` (anything else, or a format without a tile - shape, is `E_INVALIDARG`; `64KB_STANDARD_SWIZZLE` too, since `CheckFeatureSupport` reports - `StandardSwizzle64KBSupported` as FALSE), and `GetHeapProperties` on a reserved resource is `E_INVALIDARG`. - The description, initial-state and clear-value rules are a committed resource's on a default heap, and a null - output is `E_UNEXPECTED` after them (`compare_placed_reserved`, RTX 3060 / 610.88). - `GetHeapProperties` answers as the host runtime's (`d3d12_heap_properties_test`: 561 values for committed - resources in every heap type, custom ones and SHARED / ALLOW_DISPLAY / CREATE_NOT_ZEROED / CREATE_NOT_RESIDENT - included, placed resources in heaps of each kind, reserved ones, and null arguments; RTX 3060, driver 610.88). - A committed resource's flags are the caller's without the two creation-only bits, plus the DENY bits of the - resource classes it isn't; a placed resource reports its heap's flags as they are, so one in an `ALLOW_ALL` - heap reads back 0. - `CheckFeatureSupport` still reports `TiledResourcesTier` as not supported, so a game that checks it creates - committed resources instead. Buffer mappings alone do not implement a full tiled-resources tier. - The Xbox tiled layout word `0x101` is accepted as `64KB_UNDEFINED_SWIZZLE` (**ASSUMPTION**: - that the console uses it for reserved resources too). - - `GetResourceTiling`: the standard 64 KiB tile shapes, standard and packed mips (a mip stays standard while it is - wider than half the tile or taller than the tile, depth not counting, as AMD's PC runtime does on RDNA2 and RDNA4 - and so, most likely, the console (D3D-65); an NVIDIA GPU packs from the first mip smaller than a tile on any axis. - D3D11.3 functional spec 5.9.2.8.5 only requires that - a mip filling a tile in every dimension stays standard, a smaller one "may or may not be packed, depending on the - IHV"), each standard mip's tile counts, and the tile order (each array slice holds - its standard mips, then its packed tiles). The test compares the tile shape and the tile counts of the mips both - sides keep standard with the PC runtime, and checks that no mip filling a tile is packed, for 18 - buffer, 2D, array, block-compressed and volume layouts, and skips a layout the host refuses: which ones a PC - driver accepts varies (an RTX 3090 on driver 616.56, at tier 3, refuses texture arrays whose mips reach the - packed tail, measured by @CharlyRien in #295; an RTX 5070 on 621.01 accepts them). How many tiles the packed mips take is the driver's - choice: here it is one tile per tile-depth slice the tail spans, as AMD reports (below), and never fewer than - their tight linear size in whole tiles; the PC runtime on an RTX 5070 reported one tile more than the tight size - for 1000x300 and 100x100 RGBA8 and a 128^3 R8 volume, and the same count for the other layouts probed. Two - further measured differences: on array slices after the first, the PC runtime - writes a tile index into packed subresources instead of the documented `D3D12_PACKED_TILE` (ours follows the - documentation), and a resource that is not reserved has no tiles (all outputs zero), as on the PC runtime. - - **Measured on AMD** (RX 9070 XT, RDNA4, driver 32.0.31041.1004, Windows 11, `main` `91b36cf`): the AMD PC - runtime splits standard and packed mips differently, which `d3d12_vulkan_device_test`'s tiling comparison used - to report as a failure; the spec leaves the split to the driver, so the comparison now takes any split (a Radeon - 880M on 26.11.2 behaves the same, and WARP keeps every mip standard: it packs nothing, down to 1x1). - Tile shapes agree in all 17 texture layouts, and 11 of them match exactly; in the other 6, AMD keeps more - mips as standard tiles before the packed tail: - - | Layout | Tile | Standard mips: NVIDIA (the layer before D3D-65) | AMD (the layer now) | - |---|---|---|---| - | 1000x300 RGBA8 sRGB, 3 slices | 128x128 | 2 | 4 | - | 2048x1024 BC7, 2 slices | 256x256 | 3 | 4 | - | 1000x600 BC3 | 256x256 | 2 | 3 | - | 100x100 RGBA8 | 128x128 | 0 | 1 | - | 4096x64 BGRA8 | 128x128 | 0 | 6 | - | 256x256x64 RGBA8 volume | 32x32x16 | 3 | 4 | - - An RDNA2 GPU (the Ryzen 7 9800X3D's, driver 32.0.21045.5002) gives the same splits as the RDNA4 one - ([#374](https://github.com/ItsNotRexed/Leonida/issues/374#issuecomment-7071869388)). With 30 more layouts that - probe the edges (a mip exactly at or just past half a tile, thin and tall textures, non-square 2D and volume - tiles), the rule that fits all 47 on both GPUs is: **a mip stays standard while it is wider than half the tile or - taller than the tile; depth does not count**. An earlier "every axis at most half the tile's largest side" fitted - the first 17 but missed four tall or deep edge cases. All 47 layouts and AMD's values are in - `runtime/test/resource_tiling_test.cpp`. AMD's packed tile count is one tile per tile-depth slice the tail spans, - `ceil(depth of the first packed mip / tile depth)`: 1 for every 2D layout, and for 32 further volumes whose tail - is deeper than a tile it steps at each tile depth (8x8x32 R8 takes 1 tile, 8x8x33 takes 2, 8x8x256 takes 8), even - where the bytes would fit in fewer (16x16x128 RGBA8: 8 tiles for 3 tiles of data). Those 32 are in the test too, - 79 layouts in all, identical on both GPUs. The console is RDNA2, so the layer follows this rule (D3D-65; - **ASSUMPTION**: that the console's runtime splits like the PC's AMD driver). - - `UpdateTileMappings` and `CopyTileMappings` bind pages in reserved buffers to default heaps from D3D-16. - Sequential, NULL, SKIP and single-tile reuse ranges are supported. Queue timeline waits order binding between - ordinary submissions, and the previous heap allocation is retained until an in-flight unbind completes. - `CopyTiles` copies 64 KiB tiles between sparse buffers and linear buffers in either explicit direction. - `d3d12_buffer_tiles_test` compares three full readbacks with native D3D12, including a fence-gated queue. - - Drivers that exclude the host-visible arena memory type from sparse buffers (including NVIDIA 621.01 on the - RTX 3090) use a dedicated device-local allocation per heap for its tiles. A heap with this dedicated backing - cannot mix placed buffers and sparse mappings. - - D3D-285 extends these mappings to single-sample `R8G8B8A8_UNORM` reserved 2D textures with one mip, one - layer and no resource flags. The Vulkan image must support sparse aliases and zero reads from unmapped tiles, - with 128 × 128 color blocks aligned to 64 KiB. Images requiring an opaque mip tail or separately bound metadata - keep the fully allocated fallback. The image is transitioned while still unbound and kept in `GENERAL` so - mapping an alias preserves contents. Image tiles use dedicated device-local heap memory and can alias tiles - of compatible sparse images. Buffer and placed-resource aliases with texture tiles are outside this path. - - `CopyTiles` transfers RGBA8 tiles in either direction. Partial edge blocks use the full 512-byte linear row - pitch and transfer only in-bounds texels. Byte-unaligned offsets use transfer scratch. - `d3d12_texture_tiles_test` compares initially unmapped tiles, column mappings, aliases, and a fence-delayed - remap with native D3D12, including clipped edges and byte-unaligned offsets. -- `D3D12_RESOURCE_DESC::Layout`: the public `ROW_MAJOR` and `64KB_STANDARD_SWIZZLE` values plus the Xbox `0x101` - tiled value from slot 76. Row-major textures need `VK_IMAGE_TILING_LINEAR` (not usable for RT/DS) or a staging - copy; `64KB_STANDARD_SWIZZLE` and `0x101` have no direct Vulkan equivalent. If the game uploads console-tiled data, - the layer uses a detile step. `runtime/src/resource_detile.h` (`detile_surface_64k` / `tile_surface_64k`, `resource_detile_test`) - and `runtime/src/gfx10_tiling.h` provide GFX10/RbPlus `SW_64KB_D` detiling. Which mode `0x101` uses, the mip tail and - upload wiring remain **Open**. -- Formats: a `DXGI_FORMAT` → `VkFormat` table, including sRGB and typeless variants. Typeless resources get a - concrete image format plus `VK_IMAGE_CREATE_MUTABLE_FORMAT_BIT` and a `VK_KHR_image_format_list` when views cast - within the family; unsupported casts are logged and fall back to the resource format. `CreateCommittedResource3`'s - castable-format lists are mapped to a `VkImageFormatListCreateInfo`; buffers and unmapped formats are refused. - `CreatePlacedResource2`'s list is mapped the same way on the placed path (D3D-90). Depth/stencil, BCn and packed - formats map directly; any format the device rejects is a hard error with the DXGI value. -- `Map`/`Unmap`: upload/readback buffers map their host-visible memory; default-heap resources return - `E_INVALIDARG` as D3D12 does. A texture in a CPU-visible custom heap maps only with a null pointer (its layout is - the driver's), as on D3D12. -- `WriteToSubresource`/`ReadFromSubresource` (implemented in `d3d12_vulkan_device.cpp`) complete before they - return, as D3D12 requires; a read cannot wait for a later submit. Textures in CPU-visible custom heaps are - created with `VK_IMAGE_USAGE_HOST_TRANSFER_BIT_EXT` when the device supports that usage with the requested - image format and flags, moved to - `GENERAL` and zero-filled on the host at creation, and copied with `vkCopyMemoryToImageEXT`/ - `vkCopyImageToMemoryEXT` while they stay in `GENERAL` (D3D12's `COMMON`). A driver can accept the usage and then - name no memory type for the image (NVIDIA 582.66 on a GTX 1070 Ti: `memoryTypeBits` 0 with the usage, 0x82 - without it); the image is then made again without the usage. Every other case (no extension, such an image, a - texture a barrier has moved, a default-heap texture, which D3D12 does not allow but the layer copies and logs) is - a `CopyTextureRegion` from or to a host-visible staging buffer, replayed on the device's queue and waited for, so - the layout tracker and a first use's zero fill behave exactly as for the application's own copies. - Their arguments answer as the host runtime's do (`d3d12_subresource_copy_test` runs the same 117 steps on both - devices and compares every HRESULT and the whole destination of every read; RTX 3060, driver 610.88): a - subresource past the last, a box whose right, bottom or back edge lies past the mip's, or one that cuts a - compressed block is `E_INVALIDARG`; an empty or inverted box that passes those checks is `S_OK` and copies - nothing; the row and depth pitches are not checked, so rows or slices that overlap (a pitch smaller than a row, - or 0) are copied in order. Not compared: null data, which the host faults on (the layer answers `E_INVALIDARG`); - which bytes win when a read's rows overlap, which is the driver's copy order; and a default-heap texture, which - the host refuses and the layer copies on purpose. -- 96-bit textures (`R32G32B32_FLOAT`/`_UINT`/`_SINT`/`_TYPELESS`, D3D-62) are `R32G32B32A32` images - (`ResourceBinding::rgb96`), on every GPU. Most GPUs have no optimal-tiling RGB32 image (an RX 9070 XT reports - no optimal features for `R32G32B32_SFLOAT`), and one that has would not avoid the repack: D3D12 places - subresources at multiples of 512 bytes and Vulkan requires a copy's buffer offset to be a multiple of the - 12-byte texel (VUID-vkCmdCopyBufferToImage-dstImage-07975). What the application sees stays D3D12's: - `GetCopyableFootprints` gives 12-byte texels (compared with WARP in `d3d12_rgb96_test`), and a view's T# names - `GFX10_FORMAT_32_32_32_*`, whose swizzle reads alpha as one, so the image's fourth channel is never read. - - `CopyTextureRegion` between a texture and a buffer is repacked by the D24 compute pass - (`src/depth24_convert.comp` modes 2 and 3, `Depth24Job::rgb96`): the same scratch buffers, parts and lifetime, - with texels of three words in the footprint and four in the scratch, copied as they are (an upload writes the - fourth word as 0). The words are not interpreted, so NaN payloads, denormals and integers pass unchanged. On - an RX 9070 XT (AMD 26.11.2) an upload and a readback take about 5 and 2 ms at 1024x1024 and about 20 and 45 ms - at 4096x4096 (`d3d12_rgb96_test` with `LEONIDA_RGB96_LARGE` set; single runs that vary by a few ms, each the - first submission of a new queue). The converter is created on every device for this, whether or not the - GPU has a native D24. - - Texture-to-texture copies and `CopyResource` are plain image copies, and only between two 96-bit textures. - - `WriteToSubresource`/`ReadFromSubresource` always take the staged copy, as a D24 texture stored as D32 does: - a host image copy would not repack. - - Not done: render targets. WARP creates 96-bit render targets; this layer refuses `ALLOW_RENDER_TARGET` and - leaves `RENDER_TARGET` out of `FORMAT_SUPPORT`, since a writable fourth channel changes destination-alpha - blending. `ALLOW_UNORDERED_ACCESS` and `ALLOW_DEPTH_STENCIL` are refused, as on WARP (measured in the test). - `GetResourceAllocationInfo` gives no size for a description creation refuses. A typed 96-bit texture has - views of its own format only; the `TYPELESS` one has `FLOAT`, `UINT` and `SINT` views (sampled in - `d3d12_descriptor_test`). `GetResourceTiling` reports no tiling for a committed 96-bit texture on both - Microsoft WARP and an NVIDIA GTX 1660 SUPER: total tiles, the tile shape and every packed-mip field are zero, - and the returned subresource-tiling count is zero (so its output element is untouched). This holds for - `FLOAT`, `UINT`, `SINT` and `TYPELESS`; there is no standard tile shape to implement for a 12-byte texel. -- Resource flags map to Vulkan usage: `ALLOW_RENDER_TARGET` → `COLOR_ATTACHMENT`, `ALLOW_DEPTH_STENCIL` → - `DEPTH_STENCIL_ATTACHMENT`, `ALLOW_UNORDERED_ACCESS` → `STORAGE`, `ALLOW_SIMULTANEOUS_ACCESS` → concurrent - sharing, `DENY_*` → omit the corresponding usage. Buffers get the union of usages their states and flags imply; - images copy dimension, format, mip levels, array layers and sample count. -- Copies: `CopyBufferRegion` → `vkCmdCopyBuffer` with arena offsets; `CopyTextureRegion` → - `vkCmdCopyBufferToImage`/`vkCmdCopyImageToBuffer`/`vkCmdCopyImage`, using the `D3D12_PLACED_SUBRESOURCE_FOOTPRINT` - row pitch and height; `CopyResource` → a whole-subresource copy; colour resolves → `vkCmdResolveImage`; - depth and stencil resolves → a `vkCmdBeginRendering` scope with a resolve attachment (section 3.2). - Partial resolve regions to another offset need a shader or a region copy. - - A placed footprint must have an `Offset` that is a multiple of 512 and a `RowPitch` that is a multiple of 256 - (`D3D12_TEXTURE_DATA_PLACEMENT_ALIGNMENT`, `D3D12_TEXTURE_DATA_PITCH_ALIGNMENT`). Any other is refused when it is - recorded, so `Close` returns `E_INVALIDARG` (`CommandList::valid(const CopyLocation&)` in - `runtime/src/command_list.h`; `command_list_test` has both cases). That is D3D12's rule for a device that - reports `UnrestrictedBufferTextureCopyPitchSupported` as `FALSE` in `D3D12_FEATURE_D3D12_OPTIONS13`, which this - device does on purpose (`d3d12_vulkan_device_test` fails on a `TRUE`). The PC runtime answers differently: on an - RTX 4090 (driver 621.14) and on WARP it reports the capability as supported, and a list with `Offset` 16 and - `RowPitch` 260 for an `R8G8B8A8_UNORM` footprint closes with `S_OK` (measured with a stand-alone D3D12 program, - Windows 11 26200). An older PC runtime keeps the rule: on Windows 10 22H2 (`d3d12.dll` and `d3d10warp.dll` - 10.0.19041.3636) the query for `D3D12_FEATURE_D3D12_OPTIONS13` answers `E_INVALIDARG`, and WARP and a GTX 1070 Ti - close such a list with `E_INVALIDARG`, as the layer does; `d3d12_close_parity_test` counts its three cases as - matches on such a WARP. The layer cannot simply say the same: Vulkan takes a copy's buffer offset as a multiple of - the texel block size and its row length in texels (VUID-vkCmdCopyBufferToImage-dstImage-07975), while the - capability lifts D3D12's two alignments and is not documented as keeping offsets and pitches texel multiples - (not tested here), so a footprint that is not texel-aligned would have to be repacked through scratch memory - the way a 96-bit one is (section 4.2). The replay already accepts any pitch that is a texel multiple and any - offset that is one, except that a depth, stencil or 96-bit copy needs an offset that is a multiple of 4 - (`prepare_texture_copy` in `runtime/src/vulkan_replay.h`; anything else is `unsupported` there), so accepting - those needs only the record-time check changed; reporting the capability needs the repack as well. What the - console's runtime reports is not measured, and no title code that depends on it has been seen. -- `WriteBufferImmediate` (D3D-26) → `vkCmdUpdateBuffer` of 4 bytes. The address is resolved when the list is - executed, through `ReplayFunctions::buffer_at`: the buffer whose `ResourceBinding::va` range holds it, at - `buffer_offset + (address - va)`. `VulkanContext` finds it by binary search over the buffers' VA ranges - (`runtime/src/buffer_va_index.h`, kept in step with the registered resources); aliasing placed buffers can - overlap: the one whose range starts closest below the address and also holds the bytes the view or write needs - wins, or, when none holds all of them, the one that starts closest below (`buffer_va_index_test`). These are the same fields and lookup as #291's arena, and the device fills - `va` once `GetGPUVirtualAddress` lands (#157/#291); until then, a list with an immediate write is refused as - `unresolved_resource`. `DEFAULT` adds no barrier: it is ordered like any copy, by the application's barriers. - `MARKER_OUT` waits for every earlier command to finish and sees its writes (`ALL_COMMANDS`/`MEMORY_WRITE` → - `TRANSFER`/`TRANSFER_WRITE`). `MARKER_IN` only needs earlier commands to have started. Vulkan cannot express - that, because `TOP_OF_PIPE` in a first synchronisation scope is no stage at all, so it gets an execution-only - `ALL_COMMANDS` → `TRANSFER` dependency: stricter than D3D12 requires, never weaker. Recording refuses a null - or unaligned address and an unknown mode (the debug layer's `WRITEBUFFERIMMEDIATE_*` messages, IDs 1090-1092 in - `d3d12sdklayers.h`). -- `AtomicCopyBufferUINT` / `AtomicCopyBufferUINT64` (D3D-26) → one `vkCmdCopyBuffer` region of 4 or 8 bytes, after - a `ALL_COMMANDS`/`MEMORY_WRITE` → `TRANSFER`/`TRANSFER_READ|WRITE` barrier. That barrier covers every earlier - write, those to the dependent resources among them, so the copy sees them all, as D3D12 requires. The dependent - ranges are checked against their buffers (`end == UINT64_MAX` resolves to the buffer's size) but add nothing a - global barrier does not already cover. Recording matches live Windows 11 WARP and hardware D3D12 `Close` - validation: offsets aligned to and within the buffer for the copy size, zero dependencies allowed (with null - arrays), buffer dependency ranges with `begin < end` and either `end == UINT64_MAX` or `end <= width`, and - texture dependency ranges `{0, UINT64_MAX}` on a valid subresource or `ALL_SUBRESOURCES`. **ASSUMPTION:** Vulkan - promises no atomicity for a transfer, and the layer relies on a naturally aligned 4- or 8-byte copy being a - single write on the GPU. This matters only to a reader racing the copy on another queue or on the host. -- Clears: a full-subresource clear maps to `vkCmdClearColorImage`/`vkCmdClearDepthStencilImage` (UAV buffers to - `vkCmdFillBuffer`); a rect clear uses `vkCmdClearAttachments` inside the rendering scope. UAV image clears use - `vkCmdClearColorImage` in `GENERAL`, and rectangles `vkCmdClearAttachments`. Buffer patterns of other sizes - need no compute clear: 8/16-bit elements are a 32-bit fill with copied ends, 64/128-bit ones an update doubled by - copies (section 3.2, UAV clears). -- **Typed UINT RTV clears:** `ClearRenderTargetView` still takes `FLOAT[4]`. For the currently exposed - `R8G8B8A8_UINT`, `R32_UINT` and `R32G32B32A32_UINT` resources, convert those values numerically into - `VkClearColorValue::uint32` for both image and rectangle clears; copying float bits gives incorrect stored - integers without a Vulkan validation error. **Measured:** Windows D3D12 on WARP and AMD RX 5700 XT clamps - negatives/NaN to zero, positive overflow/infinity to the component maximum, and truncates fractions. - `d3d12_clear_test` (renamed from `d3d12_uint_clear_test` in #525, D3D-45) compares full and rectangular D3D12 - readbacks with WARP over eleven integer input sets on every UINT and SINT render-target format it lists, beside - the UNORM/SNORM/FLOAT and depth/stencil cases. ctest runs only its `--rgb9e5` mode (`d3d12_rgb9e5_rtv`), so the - WARP comparison is run by hand until #521's 0.5 tie rounding lands (`runtime/cmake/d3d12_vulkan.cmake`). - `clear_color_test` checks both replay paths without a GPU, including unchanged float values. - This does not add typed-view reinterpretation of typeless resources or new integer formats. -- **RGBA8 typeless RTV clears:** explicit UNORM, SRGB, UINT, SINT and SNORM RTVs on a - `R8G8B8A8_TYPELESS` 2D resource with sample count 1, selecting a mip and a contiguous array-layer range. - `TargetView` captures its format by value; copies and layout tracking keep the resource's base format. - Reinterpreted full clears use dynamic rendering because `vkCmdClearColorImage` cannot select a view format. - Rectangle clears use the same typed attachment view. The view-cache key includes the format, and views - request only color-attachment usage so SRGB does not inherit an unrelated storage requirement. - Same-format image clears and legacy float-only replay clients retain their existing path. - On an RX 5700 XT, 13 synthetic full/rectangle readbacks match Windows WARP (UINT exact, normalized - channels within one byte), including descriptor rewrites, format switches and an SRGB RTV on a UAV resource. - The same tests fail without this change and when the cache ignores format. CPU replay covers 31 scenarios; - 17 unsupported/invalid frontend views fail `Close` without submission. Typed-resource casts, MSAA and 3D - typeless RTVs remain unsupported. - Phase 2 adds 54 mip/array and 12 non-array higher-mip readbacks against WARP, including untouched sentinels. - D3D-161 adds SINT and SNORM views when the Vulkan format supports color attachments. SINT uses the existing - integer clear conversion, and SNORM passes floating-point values to the attachment. Signed channels matched - WARP byte for byte in full and rectangular clears on an RX 9070 XT (driver 32.0.32029.2010) and the integrated - Radeon in a Ryzen 5 9600X (32.0.21045.29003), including mip and array selections. The SNORM vectors avoid - half-step rounding ties. -- **Typed RTVs of the other typeless families (D3D-275):** an RTV of any TYPELESS color texture (B8G8R8A8, - R16G16B16A16, R32G32B32A32, R32G32, R16G16, R10G10B10A2, R8G8, R32, R16, and R8 once it is mapped) names a typed - format of its family; `TargetView` carries that view's VkFormat (`ColorViewFormat` holds VkFormat numbers) and - `color_view_format` accepts any format of the resource's family (`typeless_view_family`), so the clear writes - through a view in that format. Typeless images are already mutable without a format list. Before, only RGBA8 was - reinterpreted and the others cleared through the resource's own format (an `R8_UINT` RTV cleared to 7 wrote 0xff). - `d3d12_typeless_families_test` clears every typed RTV format of each family with two value sets and compares the - bytes with the host D3D12 on the same adapter: 62 of 62 equal on an RTX 3060 (NVIDIA 32.0.16.1714) with - `LEONIDA_VK_VALIDATION=1`; WARP differs from that host in 8 (rounding of 0.5 to UNORM/SNORM and the - R10G10B10A2_UNORM alpha). Formats the layer does not map yet (R16G16B16A16_SNORM, R16G16_UNORM/SNORM, - R16_UINT/SNORM/SINT, the R8 family; #1914) are reported and skipped. Draws need no change: the replay builds a - draw's attachment view in the PSO's `RTVFormats[slot]` (`GraphicsPipeline::color_formats`, applied in - `vulkan_replay.h`'s draw setup), which D3D12 requires to equal the RTV's format, so pipeline and attachment - already agree and the mutable image is written in the typed format. The same test draws a full-screen pass (GLSL - stand-ins for translated shaders found by FSSM hash; HLSL through d3dcompiler_47 on the host) writing - `uint4(7, 300, 1000, 3)` or `float4(0.5, -2, 1.5, 0.25)` into R16G16B16A16_UINT/FLOAT/UNORM, R32_UINT/FLOAT, - R10G10B10A2_UINT/UNORM and R8G8B8A8_UINT views of the matching TYPELESS textures: 8 of 8 equal the host, with no - validation error, before and after the clear fix. -- **RTVs through a castable-format list in the other channel order:** an `R8G8B8A8` or `B8G8R8A8` texture (UNORM or - SRGB, `B8G8R8X8` included) whose castable-format list names the RTV's format in the other channel order, across - `B8G8R8X8` and `B8G8R8A8`, or a typed `B8G8R8A8` texture's listed SRGB format, gets an RTV in that format. - `CreateRenderTargetView` checks the list as the application gave it (`lists_castable_format`), and - `color_view_format` lets a castable image's clear cross between the RGBA8 and BGRA8 orders. WARP and AMD's D3D12 - driver (RX 9060 XT, 26.11.2) store clears and draws in the view's channel order and encoding: an `R8G8B8A8` texture - cleared to (0.2, 0.4, 0.6, 0.25) through a `B8G8R8A8` RTV holds the bytes 153, 102, 51, 64. Before, the RTV was - refused for an `R8G8B8A8` texture (its clear failed `Close` and its draws were dropped), and a typed `B8G8R8A8` - texture's RTV kept the image's format whatever the view named, so its clears came out in BGRA order and without - the sRGB encoding (its draws were right already, as they use the PSO's format). A format the list doesn't name - is refused, on a typed `B8G8R8A8` or `B8G8R8X8` texture as on an `R8G8B8A8` one (the `B8G8R8A8` and - `B8G8R8X8` ones kept the image's format before); a typed `B8G8R8A8` texture without a list still ignores the - RTV's format, as before. `d3d12_clear_test` compares 8 such textures with WARP in full and rectangle clears - within 1 (the X byte of an X8 view left out: WARP and AMD write different values there) and checks that an - `R8G8B8A8`, a `B8G8R8A8` and a `B8G8R8X8` texture each take their own and their listed format and refuse 3 - formats their lists don't name, `d3d12_draw_test` draws through the same views, and `typeless_rtv_test` checks - the replay's crossing and its refusals. -- **Typed RTV clears:** `ClearRenderTargetView` still takes `FLOAT[4]`. For every integer RTV format the device - exposes (`R8G8`, `R8G8B8A8`, `R16G16`, `R16G16B16A16`, `R32`, `R32G32` and `R32G32B32A32` in `_UINT` and `_SINT`, - plus `R10G10B10A2_UINT`; `R8`/`R16` `_UINT`/`_SINT` are handled in replay too) convert those values numerically - into `VkClearColorValue` for both image and rectangle clears; copying float bits gives incorrect stored integers - without a Vulkan validation error. **Measured:** Windows D3D12 on WARP clamps negatives/NaN to zero, positive - overflow/infinity to the component maximum (and signed below the minimum), and truncates fractions; signed formats - use `int32` with the same NaN/overflow rules. `R10G10B10A2_UINT` clamps RGB to 1023 and alpha to 3 (inputs 4, 4.5 - and 2^32 in alpha match WARP). `d3d12_clear_test` compares full and rectangular D3D12 readbacks with WARP across - UNORM, SNORM, FLOAT, all 15 exposed UINT/SINT render targets (11 value vectors, including 8-/16-/10-/2-bit range - boundaries) and depth/stencil; `clear_color_test` checks both replay paths for 19 integer formats without a GPU, - including unchanged float values. SRGB clears are omitted from the comparison: the - linear→sRGB encoding rounds differently at the `.5` boundary on WARP vs Vulkan (a 1-ulp driver difference). - **Open:** on NVIDIA RTX 5080 (driver 616.56) clears that land exactly on a `.5` UNORM/SNORM step round down where - WARP rounds up: `R8G8B8A8_UNORM`/`SNORM` 0.5 store `7f`/`3f` vs WARP `80`/`40`, and a `D16_UNORM` 0.5 depth clear - stores `0x7fff` vs WARP `0x8000` (all on `main` before this change; same 1-ulp class as SRGB, not addressed here). - `D32_FLOAT` and `D32_FLOAT_S8X24_UINT` match WARP. - This does not add typed-view reinterpretation of typeless resources. -- `D3D12XBOX_RESOURCE_FLAG_FORCE_TEXTURE_COMPATIBILITY` (public release note) and DCC: ignore the flag, let the - Vulkan driver choose compression, and fail loudly if the game aliases a buffer over a compressed image or reads - raw DCC metadata. -- **G-buffer render targets stay 8-bit UNORM.** Reported by @Silliana in #603 (not reproduced here): the material - shaders pack data into plain bytes (the normal is octahedral-packed across three bytes of one target, and ID - bytes sit in another) and the lighting shaders unpack them with a `* 255` and a truncate. If the layer or a test - gives those targets another format (say f16 for everything), a byte is lost in many pixels: the normals go wrong - and the specular sparkles. Create them with the format the game asks for (`R8G8B8A8_UNORM` and the like) and don't - substitute a wider or float format for them. - -### 4.3 Barriers and layouts - -Track a current state/layout per subresource. D3D12 states are bitmasks; a combined state takes the union of the -mapped stages/accesses, and if no single layout serves all uses, use `GENERAL` and log it. Legacy -`D3D12_RESOURCE_STATE_*` maps to a (stage, access, layout) triple: - -| D3D12 state | Vulkan layout | Stage / access | -|---|---|---| -| `COMMON` | `GENERAL` for images, no layout for buffers | Promote on first use | -| `RENDER_TARGET` | `COLOR_ATTACHMENT_OPTIMAL` | `COLOR_ATTACHMENT_OUTPUT` / write | -| `DEPTH_WRITE` / `DEPTH_READ` | `DEPTH_STENCIL_ATTACHMENT_OPTIMAL` / `DEPTH_STENCIL_READ_ONLY_OPTIMAL` | early/late tests | -| `PIXEL_SHADER_RESOURCE` | `SHADER_READ_ONLY_OPTIMAL` | fragment shader / read | -| `NON_PIXEL_SHADER_RESOURCE` | `SHADER_READ_ONLY_OPTIMAL` | vertex/compute/etc. / read | -| `UNORDERED_ACCESS` | `GENERAL` | shader / read+write | -| `COPY_DEST` / `COPY_SOURCE` | `TRANSFER_DST_OPTIMAL` / `TRANSFER_SRC_OPTIMAL` | transfer | -| `RESOLVE_DEST` / `RESOLVE_SOURCE` | `TRANSFER_DST_OPTIMAL` / `TRANSFER_SRC_OPTIMAL` | resolve | -| `STREAM_OUT` | no layout for buffers | transform feedback write (if used) | -| `VERTEX_BUFFER` / `INDEX_BUFFER` / `INDIRECT_ARGUMENT` | no layout for buffers | vertex input / index / draw indirect | -| `PRESENT` | `PRESENT_SRC_KHR` for swapchain images, `GENERAL` otherwise | present | -| `RAYTRACING_ACCELERATION_STRUCTURE` | buffer, no layout | acceleration structure read/write | - -- Split barriers (`BEGIN_ONLY`/`END_ONLY`, and enhanced `SYNC_SPLIT`) are an optimisation. The resource is unusable - between the halves, so one full barrier at either point is correct; the IR records it at the end point - (`command_list.h`). Use `VK_KHR_synchronization2` events if profiling needs the overlap. -- Implicit promotion and decay need no extra barriers: `COMMON` is `GENERAL`, and the layout tracker makes later - barriers start from it (section 3.2). -- Aliasing barriers: if image aliasing is implemented (one `VkDeviceMemory` per D3D12 heap range, with - `VK_IMAGE_CREATE_ALIAS_BIT`), transition the old image to `UNDEFINED`, issue a global memory barrier, then - transition the new image. Until then, log aliasing and allocate distinct memory; do not silently return the - wrong contents. -- Enhanced barriers (`D3D12_BARRIER_SYNC_*`, `D3D12_BARRIER_ACCESS_*`, `D3D12_BARRIER_LAYOUT_*`) map directly to - `VkPipelineStageFlags2`, `VkAccessFlags2` and `VkImageLayout` (`vulkan_sync`, `vulkan_barrier_access`, - `vulkan_layout`). Queue-specific layouts map like their generic forms; ray tracing, video and split scopes use - `ALL_COMMANDS`; `LayoutBefore = UNDEFINED` or the discard flag becomes `oldLayout = UNDEFINED`. -- `DiscardResource` (D3D-26): each discarded image subresource gets a barrier from `oldLayout = UNDEFINED` to the - layout the tracker already has for it, so the driver may drop the contents while later commands see no layout - change. The other cases are no-ops, which "contents undefined" allows: buffers, discards with rectangles (only - part of each subresource), a part never used yet (it is still to be zero-filled on first use), a list replayed - without a tracker, and one plane of a combined depth-stencil image without `separateDepthStencilLayouts` - (discarding one plane would also discard the other). A null region is recorded as `whole`; a region is always an - explicit range, even with `NumSubresources = UINT_MAX`, so its `FirstSubresource` is checked like any other. -- Access bits and sync scopes are not one-to-one. D3D12 lets an access be named with a sync scope whose Vulkan - stages cannot perform it: `SYNC_ALL_SHADING` with `ACCESS_VERTEX_BUFFER` is valid D3D12, but - `VK_ACCESS_2_VERTEX_ATTRIBUTE_READ_BIT` needs `VERTEX_ATTRIBUTE_INPUT`, which shading stages are not. Vulkan - rejects such a barrier. `vulkan_barrier_scope` therefore widens each side's stages by the narrowest stage that - can perform each access without one. The table is the synchronization2 chapter's "supported access types". The - stages it adds: - - `DRAW_INDIRECT` for indirect arguments; - - `INDEX_INPUT` and `VERTEX_ATTRIBUTE_INPUT` for index and vertex buffers; - - all shading for constant buffers, SRVs and UAVs; - - `COLOR_ATTACHMENT_OUTPUT` for render targets; - - the fragment tests for depth/stencil; - - `ALL_TRANSFER` for copies and resolves. `CLEAR` alone cannot read, and `ALL_GRAPHICS` contains no transfer stage. - - The access itself is never dropped, so the dependency still covers everything the application named, over a - slightly larger scope. -- Render passes: `BeginRenderPass`/`EndRenderPass` map to `vkCmdBeginRendering`/`vkCmdEndRendering` (dynamic - rendering). The `D3D12_RENDER_PASS_BEGINNING_ACCESS`/`ENDING_ACCESS` types give the load/store ops and resolve - targets. Suspending/resuming passes have no direct Vulkan equivalent; split them into two rendering scopes with - the same attachments and `LOAD`/`STORE`. If the game does not use render passes, build a rendering scope per draw - from the bound RTVs/DSV and let explicit `Clear*View` calls do the clears. - -### 4.4 Fences, queues and frames in flight - -- One timeline semaphore per `ID3D12Fence`. Queue `Signal` = `vkQueueSubmit` signal; queue `Wait` = submit wait. -- **Wait before Signal across queues, with resources handed over** (`src/queue_holds.h`, `VulkanQueue`; test - `d3d12_queue_handover_test`). Vulkan accepts a timeline wait whose signal comes later, but the layer replays every - `ExecuteCommandLists` against one `LayoutTracker` in the order the calls arrive, so a queue that waits for work - submitted afterwards would be recorded against the layouts from before that work (a copy list that reads a texture - a compute list has not yet written was replayed against `UNDEFINED`: zero-filled, and a validation error). The layer - therefore tracks, per fence, the highest value a Signal has been *submitted* for (or the CPU has set; the creation - value counts), which is not the completed value. A queue that is asked to run a batch (or a `Signal`) while a - `Wait` it carries names a value above that, or while an earlier batch of the queue is held, copies the lists - (`CommandList` is a value; the application may `Reset` its list at once) and holds the operation. Everything the - queue is asked to do after it (batches, Signals, queue markers) goes behind it, so per-queue order is kept. - The held operations are recorded and submitted, in order, on their own `VkQueue` as soon as the Signals they wait for - have been submitted: by the thread that submits that Signal (or makes the CPU `Signal`), after it has dropped its own - queue's state lock. There is no worker thread and no GPU wait is added, but the call that releases is not free: that - thread records the held batches (what the `ExecuteCommandLists` would have cost, including whatever `execute` does - for the lists, such as the bindless upload's wait for the device until D3D-314 removes it) while it still holds the - mutex of the D3D12 queue whose `Signal` or `Wait` it is in, so other calls on that queue wait meanwhile; and - `remove_fence`, queue destruction and presenter destruction wait for a release in progress. One thread releases at a - time (the others leave a note and the running one makes another pass); a release that submits a Signal lets the - next queue's front run in the same pass, so chains (C waits B, B waits A, in any submission order) and operations - with several waits resolve in dependency order, and the layout tracker follows that order. A wait whose value has - been reached by a submitted Signal never blocks again (vkd3d-proton's rule too). The normal case (the Signal - submitted first) is unchanged: no copy, no hold, the same `vkQueueSubmit`. Holding on the CPU also avoids a Wait and - its Signal landing in the wrong order on one `VkQueue`, which would not make forward progress on the GPU - (Vulkan-Docs issue 1262): the test also runs with every D3D12 queue on one `VkQueue` and with two. - What a held operation keeps alive, as D3D12's queue does: the fences it waits on and signals, until its submission - has completed on the GPU (a released fence stays until then, which also removes the destroy-while-pending - validation error the unheld path could hit); the pipeline states and root signatures of its lists (copied from the - recording before the application may `Reset` it, so releasing a PSO right after `ExecuteCommandLists` is fine). - Resources are not kept: a resource released while a batch that names it is held fails that batch at release. - Order against other work: a held `Signal(F, v)` released after an unheld `Signal(F, w)` with `w >= v` leaves the - Vulkan signal out (timelines only increase; waits for `v` already pass), decided under the submit lock so the - order of the checks is the order of the submissions, and the value counts as submitted only once the - `vkQueueSubmit` succeeded (a failed Signal releases nobody and its retry goes through); `Present` is queued behind - held work too (below). Fence keep-alives are released outside the queue lock, at the next `ExecuteCommandLists`, - `Signal`, `Wait` or marker once their submission has completed. Edge cases: - a queue destroyed with held operations reports them once (stderr: `queue destroyed with N held operation(s) never - submitted: waits for a fence value (V) that no Signal reached`) and goes on without waiting, and the CPU waits on - the fences of its held Signals are completed, as a released fence completes them; queues that wait for those fences - stay held and are reported when they go; a fence nobody signals holds back only the queues that wait for it (and - for what they would have signaled), never the others; a Signal value that is not above the fence's is still - dropped with a note at call time, as before (vkd3d-proton instead maps virtual fence values to physical timeline - values; the layer does not yet). A held `ExecuteCommandLists` that fails when it is released does not return its - result to a call that has returned: it is printed, `last_execute_result` and `VulkanQueue::take_held_failure` - report it, the `Signal` behind it still signals (the work did not run; nothing waits forever, as for a failure that is - not held), and its waits stay for the queue's next submission, as after a failed `vkQueueSubmit`. A queue does not - hold `UpdateTileMappings` / `CopyTileMappings`: they still submit at once, before earlier held work, and take the - queue's pending waits (documented limit). `VulkanQueue::idle` waits for submitted work only. - `Present` (`VulkanPresenter`): when any queue holds work, a presented back buffer would be blitted as it was before - that work, so the Present is queued instead (`QueueHolds::after_held`), returns success as a held - `ExecuteCommandLists` does, and is submitted, in order with the presents queued before it, by the thread that - releases the last operation held when it was called. It is not blocked on the calling thread because the Signal that - releases the work may be one that thread makes after `Present` returns. Held work that is never released holds back - the presents after it (device-wide, since the layer cannot tell which batch draws into which back buffer). A - blank present reads nothing and is only ordered behind earlier queued presents. At most 8 presents queue up; the - next one waits for held work to release (logged once; `set_abort` ends the wait), as a full frame-latency queue - does. A queued present reports `last_present_tore()` false, which the Xbox PresentX path turns into the default - vblank sync for the frame pacer. The presenter's state is guarded by one mutex (the counters are atomics, so - reading them never waits for a present blocked on a swapchain image); `set_abort` has its own. - Facts from vkd3d-proton (LGPL, approach only, nothing copied): it keeps a CPU-side virtual value and pending signals - per fence and blocks the queue's submission thread until a signal that satisfies a wait has been submitted, so Vulkan - never sees a wait without a submitted signal. Resources are `VK_SHARING_MODE_EXCLUSIVE` and every D3D12 queue is in - the graphics family, so no ownership transfer is needed; with dedicated compute/transfer families they would need - `CONCURRENT` (vkd3d-proton does that, because D3D12 gives no information for transfers). - Every mode of the handover test ends with the same cases on the host runtime (the expected data is the CPU's - pattern in all of them, so that run shows the cases are valid D3D12 and holds the layer's modes to one bar). - The pipeline-state and root-signature pins are covered end to end by `d3d12_m4_compute_test`: the compute list is - executed while held, its two PSOs and root signature are released and the list is Reset, the copy that releases - it is submitted, and the output is compared with the CPU (it reads zeros without the pins). - Measured: `d3d12_queue_handover_test` (three modes: the standalone device with a `VkQueue` per D3D12 queue, then the - host runtime; `--two-queues`, a caller-owned device with two `VkQueue`s handed over; `--shared-queue`, one) runs - 592 cases on the layer on the Radeon 880M and the RTX 5070 (also with one shared `VkQueue`; 8 with two handed over) and 587 on the host runtime: pairs and three-stage chains (produce, relay, consume) - over the queue type assignments that fit and all 6 submission orders (consumer first among them), two producers - (texture from one queue, buffer from another) with one consumer, a chain released by a CPU `Signal`, a CPU - `Signal` before and after the `Wait`, a never-signaled fence, a fence released while a batch waits, a held Signal - of a fence the application released, a held Signal below an unheld one on a shared fence, teardown with a held - Signal under a CPU wait, and 200 rounds with two threads signalling and releasing at once; results compared byte - for byte, sync validation clean. With holding disabled the test fails 236 cases and validation reports - `VUID-vkCmdDraw-None-09600`; with the monotonic check disabled it reports - `VUID-VkSubmitInfo-pSignalSemaphores-03242`; `vk_presenter_sync_test` and `d3d12_m4_compute_test` (which - submits the compute list first and releases its PSOs and root signature before the copy that feeds it) fail - without the Present ordering and the pins. -- **More D3D12 queues than Vulkan queues** (`pick_queue_slot` in `src/queue_families.h`, `CreateCommandQueue`; - test `d3d12_queue_share_test`). A GPU can expose fewer `VkQueue`s than a title creates D3D12 queues: the Intel - UHD 770 on Windows and lavapipe have one family with `queueCount` 1, so the second D3D12 queue of any type was - refused with `E_OUTOFMEMORY` ("no independent Vulkan queue available") and a title with a DIRECT and a COMPUTE - queue stopped at boot (PingasMech, #4863). A new D3D12 queue takes an unused `VkQueue` of its own type's family, - then of the graphics family, as before (D3D-97: one `VkQueue` per live D3D12 queue while there are enough, so - nothing changes on a GPU with enough queues; an RTX 5080 gives 16 graphics, 8 compute and 2 transfer queues); when - every one is in use it shares the one with the fewest D3D12 queues (its own family's first on a tie) and logs that - once per type. D3D12 queues on one `VkQueue` stay separate objects: each keeps its own batches in order, its own - progress timeline and its own held operations; the `VkQueue` runs their batches one after the other, in the order - they reach it, so they lose concurrency, not correctness (as on one family, below). What would break is a GPU - wait that no submitted signal satisfies landing on the shared `VkQueue` ahead of the signal it waits for, which - never makes progress. The holding above already rules that out: a batch reaches `vkQueueSubmit` only once every - fence value it waits for has a *submitted* Signal (earlier on the same `VkQueue`, or on another one) or has been - set by the CPU. One case let the CPU half slip: a CPU `Signal` that has to wait behind a queue Signal the GPU has - not reached yet (`VUID-VkSemaphoreSignalInfo-value-03259`, applied later by the fence wait thread) never told the - held queues, so a queue waiting for that value was held for ever, on separate `VkQueue`s too. The wait thread now - reports the value once it has set it, and releases what it satisfies; reporting it earlier, when the CPU called - `Signal`, would send the waiting batch ahead of the queue Signal it depends on, which on a shared `VkQueue` never - completes. `vkQueueSubmit`, `vkQueueBindSparse`, `vkQueuePresentKHR`, `vkQueueWaitIdle` and the queue labels - need the `VkQueue` externally synchronised; every call the layer makes holds the device's one submit lock - (`VulkanContext::submit_mutex`), which covers shared `VkQueue`s as it covers the staging queue the first DIRECT - queue already shares. A per-`VkQueue` lock (#3841) must key on the `VkQueue` handle, not the D3D12 queue. Costs on - a shared `VkQueue`: `GetClockCalibration` without calibrated timestamps and the destruction of a D3D12 queue wait - for the other D3D12 queues' submitted work too, and queue debug labels (`BeginEvent`/`EndEvent`) of the D3D12 - queues interleave on it. Two test settings make the standalone device look like such a GPU, so the sharing path - runs anywhere: `LEONIDA_VK_MAX_QUEUES_PER_FAMILY=N` (at most N `VkQueue`s per family) and - `LEONIDA_VK_GRAPHICS_FAMILY_ONLY=1` (COMPUTE and COPY in the graphics family); both together are one family with - one queue (`docs/testing.md`, "Choosing the GPU"). Only the test executables apply them: the game's device - (`d3d12_xs`, `LEONIDA_D3D12=vulkan`) ignores them and says so, so a variable left in the environment cannot put - every queue of the game on one `VkQueue` (`run_tiny_frame_queue_test_settings`). Measured on an RTX 5080 (Linux, driver 580.65.06, Wine 11) - and on lavapipe, under the validation layer with synchronization validation: `d3d12_queue_share_test` passes - with no setting, with one queue per family, with one queue in all and on lavapipe (36 queues, a buffer copied - exactly through all of them consumer first and producer first, 9 deferred CPU Signal cases, 4 threads on 9 queues: - 2,000 iterations with all 9 on one `VkQueue` of the RTX 5080, 80,000 on lavapipe; a fence released right after - the GPU passed the queue Signal its deferred CPU Signal waited behind, 900 times per mode, the held batch running - every time), 0 validation messages; on main - it fails at the 27th queue on the RTX 5080 and at the 2nd on lavapipe, and the first deferred case hangs. The layer - half of `d3d12_queue_handover_test` runs its 371 cases exact in all four (on lavapipe main ran 0: one queue). -- `SetEventOnCompletion(value, hEvent)`: a small wait thread calls `vkWaitSemaphores` and `SetEvent`. Reuse one - thread with a condition variable; do not create a thread per fence. -- `GetCompletedValue` is `vkGetSemaphoreCounterValue`; CPU `Signal` is `vkSignalSemaphore`. -- `SetEventOnMultipleFenceCompletion` (implemented). With a null event it is one blocking `vkWaitSemaphores` over - every fence's semaphore, with `VK_SEMAPHORE_WAIT_ANY_BIT` for `D3D12_MULTIPLE_FENCE_WAIT_FLAG_ANY` and no flag for - `ALL`. With an event, the device's fence wait thread counts down one shared waiter (1 for `ANY`, the fence - count for `ALL`, kept as the API's unsigned `UINT`) and the hit that reaches zero sets the event, so no thread is - added; later hits stay at zero (`d3d12_fence_waiter_test` checks counts past `INT_MAX`). Values already reached are - counted before the call returns. Zero fences, other flags, a null array or a fence from elsewhere are - `E_INVALIDARG`, as on the PC runtime. A fence released while an event waits on it counts as reached for that - wait, as on the PC runtime (RTX 5070 and WARP): `SetEventOnCompletion` and `ANY` set the event, `ALL` counts it - as one fence (`d3d12_fence_events_test`). -- The swapchain owns acquire/present semaphores and N frames in flight. A present waits for the frame's - render-finished semaphore; the next acquire waits for the image's present-complete semaphore. -- Queue types: a direct queue maps to a graphics+compute queue, a compute queue to a compute-only family if one - exists, a copy queue to a transfer-only family. If the host exposes only one family, serialize and log; async - compute is a performance feature, not a correctness one. -- `GetTimestampFrequency`/`GetClockCalibration` use `VK_EXT_calibrated_timestamps` where available. - `GetClockCalibration` (implemented) returns the GPU stamp in device ticks (`1e9 / timestampPeriod` per second, - the units of `GetTimestampFrequency`) and the CPU stamp in `QueryPerformanceCounter` units. When the device has - `VK_KHR_calibrated_timestamps` or `VK_EXT_calibrated_timestamps` enabled (`VulkanDeviceInfo::calibrated_timestamps`; - the standalone device enables whichever the GPU has) and offers the `DEVICE` and `QUERY_PERFORMANCE_COUNTER` - domains, it is one `vkGetCalibratedTimestampsKHR` call. Otherwise the queue waits until idle, submits a - `vkCmdWriteTimestamp` and waits for it, and answers with the midpoint of the `QueryPerformanceCounter` reads - around that submission. This stalls the queue, which is acceptable for a call made once per profiling capture. A - queue family with `timestampValidBits = 0` fails with `E_FAIL`. `d3d12_fence_timing_test` takes two calibrations - 50 ms apart and compares the GPU and CPU intervals. On an RTX 4090 (driver 621.14) the gap is 2 us with calibrated - timestamps, 20 us with the fallback, and 0.4 ms with the fallback under the validation layer. The test fails - above 2 ms. - -### 4.5 Swapchain and present - -The game package does not include `dxgi.dll`, so the executable imports it from the system (or from the GDK). -That import must be shimmed. The shim provides: - -- `CreateDXGIFactory`/`CreateDXGIFactory2` → one fake factory with one adapter describing the host Vulkan device. - `IDXGIAdapter::GetDesc` reports host memory/LUID; the game may use these for settings. **Open:** whether it - expects Xbox Series X values (16 GB, fixed clocks) instead. -- `IDXGIFactory::CreateSwapChain`/`CreateSwapChainForHwnd` → `VkSurfaceKHR` for the HWND + `VkSwapchainKHR`. - `GetBuffer(i)` wraps each swapchain image as an `ID3D12Resource` so the game can create RTVs. -- `Present` → `vkQueuePresentKHR`; `ResizeBuffers`/`ResizeTarget` recreate the swapchain; `SetFullscreenState` - toggles borderless/fullscreen; `GetFrameStatistics` is a stub. -- `DXGI_PRESENT_TEST`/`DO_NOT_WAIT` map to a no-op/`VK_NOT_READY` path. - -**What exists.** The DXGI shim's `Present` (`runtime/shims/dxgi_com.cpp`) has its own surface, swapchain and -blit (`leonida::VulkanSwapchain`, `runtime/shims/dxgi_swapchain.h`); `PresentX` (`runtime/shims/xbox_present.cpp`) -is implemented over `leonida::VulkanPresenter` (section 3.2) instead. `PresentX` takes ordinary committed -textures and blits them at present time, which frees the game's buffer count and format from the surface's. The -DXGI shim's `GetBuffer(i)` returns the swapchain images themselves, and switches to offscreen images blitted at -present only when the requested size or format differs from the surface's (`runtime/shims/dxgi_swapchain.h`); its -buffer count is the swapchain's image count. - -**PresentX and frame events (GDKX).** Public Microsoft samples present on Xbox without a DXGI swapchain. Facts -below come from MIT/zlib-licensed code and docs, read directly; none is from the game or the SDK. Sources: -[SimpleDeviceAndSwapChain](https://github.com/microsoft/Xbox-GDK-Samples/tree/main/Samples/IntroGraphics/SimpleDeviceAndSwapChain) -(readme: "Instead of using DXGI for presentation, this uses the new PresentX API"), -[FramePacing](https://github.com/microsoft/Xbox-GDK-Samples/tree/main/Samples/Graphics/FramePacing), -[DirectXTK12 wiki, DeviceResources](https://github.com/Microsoft/DirectXTK12/wiki/DeviceResources) ("The GDKX -platform uses PresentX, so the method WaitForOrigin has to be called each frame loop"), -[directxtk12modelviewer `DeviceResourcesGXDK.cpp`](https://github.com/walbourn/directxtk12modelviewer) (MIT) and -SDL2 `src/render/direct3d12/SDL_render_d3d12_xbox.cpp` (zlib). - -*Fact (call sequence in those samples):* - -1. `D3D12XboxCreateDevice(nullptr, ¶ms, iid, &device)`: adapter pointer null, a params struct (ring and scratch - sizes, `D3D12XBOX_DEFAULT_SIZE_BYTES` = use default), IID, out pointer. SDL asks for `ID3D12Device1`. -2. Back buffers are ordinary `CreateCommittedResource` calls with `D3D12_HEAP_FLAG_ALLOW_DISPLAY`, initial state - `D3D12_RESOURCE_STATE_PRESENT`, `ALLOW_RENDER_TARGET`, 2D, one mip (SDL: `B8G8R8A8_UNORM`). They are the - game's own resources, not objects owned by a swapchain. -3. DXGI is used only to find the output: QI the device for `IDXGIDevice1`, `GetAdapter`, `EnumOutputs(0)`. -4. `device->SetFrameIntervalX(output, D3D12XBOX_FRAME_INTERVAL_60_HZ, n-1, D3D12XBOX_FRAME_INTERVAL_FLAG_NONE)`: - 4 arguments; the third is the allowed frame latency (SimpleDeviceAndSwapChain passes buffer count minus 1, - SDL passes 1). Then `device->ScheduleFrameEventX(D3D12XBOX_FRAME_EVENT_ORIGIN, 0, nullptr, ..._FLAG_NONE)`: - 4 arguments (event, a `UINT` passed as 0, a pointer passed as null, flags). -5. Per frame: `device->WaitFrameEventX(D3D12XBOX_FRAME_EVENT_ORIGIN, INFINITE, nullptr, ..._FLAG_NONE, &token)`: - 5 arguments, the last an out pointer to a `D3D12XBOX_FRAME_PIPELINE_TOKEN` (SDL stores it in a `UINT64`; the - null value is `D3D12XBOX_FRAME_PIPELINE_TOKEN_NULL`). Then render, `ExecuteCommandLists`, then - `queue->PresentX(planeCount, planes, params)`: 3 arguments (`UINT`, pointer to an array of - `D3D12XBOX_PRESENT_PLANE_PARAMETERS`, optional pointer to `D3D12XBOX_PRESENT_PARAMETERS`; null in the simple - samples). -6. Plane fields used: `Token` (the value from the wait), `ResourceCount` (1), `ppResources` (pointer to the - resource pointer(s)), `pSrcViewRects` (pointer to a rect, HDR case only) and `ColorSpace` (a - `DXGI_COLOR_SPACE_TYPE`). The HDR path uses 2 planes sharing the token: plane 0 `RGB_FULL_G2084_NONE_P2020` - (HDR10), plane 1 `RGB_FULL_G22_NONE_P709` (the GameDVR/SDR copy, its own back-buffer set). Non-HDR uses 1 - plane. This agrees with the UMD limit of 2 planes in `d3d12_xs_surface.md` §7. -7. `D3D12XBOX_PRESENT_PARAMETERS` has at least `ImmediateThresholdPercent` (float). Per the FramePacing text: a - late frame is shown immediately only if scanout has not passed that percentage of the screen; 0 disables - limited tearing, 100 allows a late flip anywhere in the scan. -8. Suspend: `queue->SuspendX(0)` (one argument, passed 0; no other thread may be rendering). Resume: - `queue->ResumeX()`, then **re-run** steps 4's `SetFrameIntervalX`/`ScheduleFrameEventX`. The samples - say frame events must be registered again after resume. -9. Shutdown: `PresentX(0, nullptr, nullptr)` presents a blank screen before resources are released. -10. Statistics: `device->GetFrameStatisticsX(token, typeMask, &count, array)`: 4 arguments. Type bits seen: - `FRAME_INTERVAL`, `FRAME_EVENT`, `RENDER`, `PRESENT`, `DISPLAY`; `count` is in/out; `S_FALSE` or a short - count means "not available yet"; no statistics for the first presented frame; render/present/display - entries carry a `PlaneIndex`; display entries carry `PercentScanned`. -11. Xbox titles do not handle `DXGI_ERROR_DEVICE_REMOVED`/`RESET`. - -*Public corroboration (not measured here).* XCL, a GPL-2.0-only compatibility layer that runs retail Xbox Series -titles, records `PresentX` at queue slot 30 for the older runtime layout (XDefiant, Minecraft, Fortnite) and 32 for -a newer one (Unicorn Overlord), and the four frame calls at device slots 78-81: `SetFrameIntervalX`, -`ScheduleFrameEventX`, `WaitFrameEventX`, `GetFrameStatisticsX` (0-based, `QueryInterface` = 0). The Apache-2.0 -ebiten Xbox binding has the same device order, declares `D3D12XBOX_PRESENT_PLANE_PARAMETERS` as a 0x48-byte x64 -struct and `D3D12XBOX_PRESENT_PARAMETERS` as 0x20 bytes, and stores the token in 64 bits. So the plane and -present-parameter layouts and the token width in `runtime/shims/xbox_present.h` are no longer guesses; the enum -values and the `SuspendX`/`ResumeX` slots still are. XCL returns `S_FALSE` from a timed-out `WaitFrameEventX` -where this layer returns `HRESULT_FROM_WIN32(WAIT_TIMEOUT)`. The full comparison is in -[d3d12_xs_surface.md §7.1](d3d12_xs_surface.md#71-public-sources-for-the-presentation-and-device-abi). - -*Hypothesis (the game is not observed):* a GDKX title follows this pattern, so the DXGI swapchain shim (D3D-2) -is probably **not** on its boot path. What is on it: `D3D12XboxCreateDevice`, `IDXGIDevice1`/`IDXGIAdapter`/ -`IDXGIOutput` enumeration, committed `ALLOW_DISPLAY` resources, the frame events and `PresentX`. Without the -frame events and `PresentX` no frame reaches the screen. To confirm: trace which of `CreateSwapChain*` or the -queue's `PresentX` slot the game calls first; check the executable's `dxgi`/`d3d12_xs` imports. - -Layer plan: - -- Keep the DXGI factory, adapter and output enumeration (adapter `GetDesc`, `EnumOutputs`); no host DXGI. -- Step 3 of the sequence is on the device proxy: it answers `IDXGIObject`, `IDXGIDevice` and `IDXGIDevice1` as one - COM object with the device (a PC `ID3D12Device` has no `IDXGIDevice`, so nothing is forwarded), and `GetAdapter` - and `GetParent` return the adapter of the device behind it: the layer's own on the Vulkan device, the host adapter - with the device's LUID on the host backend. The 14 slots are the public `dxgi.h` order, an assumption like the - queue's. `SetMaximumFrameLatency` and `SetGPUThreadPriority` are kept and read back only. `dxgi_device_test` - walks it on both backends; the output itself is `EnumOutputs` (D3D-313). -- `ALLOW_DISPLAY` committed resources are normal `Resource`s that the presenter may blit to a Vulkan - swapchain image; `PRESENT` state maps per the resource-state table (`PRESENT_SRC_KHR` only for swapchain images). -- Presentation core: `PresentX` with 0-2 planes presents into the `VkSwapchainKHR` (one plain plane is a blit; scaling, - placement, HDR10 and an overlay plane 1 go through a compose pass, see "Plane composition" below); `SetFrameIntervalX`/`ScheduleFrameEventX`/`WaitFrameEventX` run on a vblank - timer and hand the token through to the present; `GetFrameStatisticsX` minimal; `SuspendX`/`ResumeX`; 0 - planes = blank screen. Test the methods directly with a fake clock, before slots are known. -- The DXGI `CreateSwapChain*` path stays as the fallback and for PC-style tests, not as the first-boot target. - -**What is implemented (the presentation core).** Everything in the plan above that does not need a slot exists as -methods of `rt::d3d12::XboxPresentation` (`runtime/shims/xbox_present.h`), on top of the presenter of section 3.2 and -`leonida::FramePacer` (`runtime/src/frame_pacer.h`, no Vulkan, no Windows headers). The plane and present-parameter -layouts and the 64-bit token are confirmed on x64 by the public code cited above; the constant values and HRESULTs -are **our own provisional definitions**, because the samples give call shapes and field names only and the enum -values are still unmeasured. The class is the surface the proxy will forward to. The queue-side calls ignore which -queue they came on (one `VkQueue` behind all of them). - -- *Frame pacing* (`FramePacer`, time from an injectable clock; real time is a steady timer, a host vblank source - can replace it). `SetFrameIntervalX` takes the interval as a period in microseconds and the latency, and starts - the vblank grid. `ScheduleFrameEventX` arms the origin event, delayed by an offset inside the frame. - `WaitFrameEventX` returns at the next origin with the next token (1, 2, 3, ...; 0 is the null token) and does not - return while `latency` presented frames are still waiting for their vblank. A frame presented before the origin event - is armed is not paced (`PresentX` does not hold it for a vblank), so it is shown at once and never waits for a vblank: - blank presents of a loading screen do not delay the first wait. A wait that comes late returns at once - with the newest passed origin; the missed ones are skipped. A finite timeout gives - `HRESULT_FROM_WIN32(WAIT_TIMEOUT)`; nothing registered, or suspended, gives `HRESULT_FROM_WIN32(ERROR_INVALID_STATE)`. - `LEONIDA_PRESENT_UNCAP` (any non-empty value other than "0", read when the object is made) takes the frame-rate - cap off: a wait hands its token out at once (no vblank grid, no latency throttle) and `PresentX` presents - unsynced — MAILBOX or IMMEDIATE, not FIFO — so the frame rate is whatever the title renders; registration and - suspension errors are unchanged, and the statistics of an uncapped frame report its present time. This covers - the frame-event cap only: a cap inside the game's own code would still apply, and the DXGI swapchain fallback - keeps the app's sync interval. - `GetFrameStatisticsX` keeps the last 64 frames and reports the event, present and display times (not render; - `PercentScanned` only for a frame shown at once by `ImmediateThresholdPercent`, else 0); `S_FALSE` with count 0 for what it does not have. -- *`PresentX`*: 0 planes presents a black frame (no token needed). 1 plane blits plane 0's first resource (a - single-sample 2D colour texture in `PRESENT`) to the swapchain image, limited to `pSrcViewRects[0]` when set - (bilinear, so the rectangle's outer texels blend with their neighbours). The blit converts between formats; an sRGB - source gets an sRGB swapchain format and every other source a UNORM one, so the encoded bytes go through unchanged. - A source the GPU cannot blit gives `DXGI_ERROR_UNSUPPORTED` and presents nothing: the checks are - `vkGetPhysicalDeviceFormatProperties` (`BLIT_SRC` on the source, `BLIT_DST` on the swapchain format, cached per - format; the scaling filter is linear only with `SAMPLED_IMAGE_FILTER_LINEAR`, else nearest), plus integer formats, - which a UNORM swapchain cannot take. Multisampled planes are refused the same way: resolving one into a temporary - image is not done. 2 planes must share one token (see "Plane composition" for what happens to plane 1). More than 2 - planes, null planes, or an empty/outside rectangle give `E_INVALIDARG`. A missing `ALLOW_DISPLAY` heap flag is logged - once and presented anyway. -- *Plane composition* (M7). *Fact* (public MIT sample, Xbox-GDK-Samples `Samples/Graphics/HDR10/DeviceResources.cpp` and - its readme): the two-plane form there is **not** an overlay. Plane 0 is the HDR10 back buffer - (`RGB_FULL_G2084_NONE_P2020`), plane 1 is a second back-buffer set holding the SDR rendering of the same frame - (`RGB_FULL_G22_NONE_P709`), both with the same full-output `pSrcViewRects`; the readme says the SDR signal "is still - required for GameDVR and screenshots" and the SimpleHDR readme says the system can generate it itself - (`D3D12XBOX_RESOURCE_FLAG_ALLOW_AUTOMATIC_GAMEDVR_TONE_MAP`). *Fact* (field names seen in a public Go binding of the - header, hajimehoshi/ebiten, Apache-2.0; no layout or values): `D3D12XBOX_PRESENT_PLANE_PARAMETERS` is `Token`, - `ResourceCount`, `ppResources`, `pSrcViewRects`, `pDestPlacementBase` (a `D3D12XBOX_VIEW_RECT*`, four floats - left/top/right/bottom), `ColorSpace`, `ScaleFilter`, `ExtendedDescCount`, `pExtendedDescs`, `Flags`; - `D3D12XBOX_PRESENT_PARAMETERS` is `ImmediateThresholdPercent`, `ViewCount`, `ExtendedDescCount`, `pExtendedDescs`, - `Flags`. *Fact* (GDK reference text for `XGameStreamingSetResolution`, read through a third-party mirror of the docs, not - on Microsoft's site): `pDestPlacementBase` scale factors of 0.0-1.0 refer to the output size (the streaming resolution, - else 1920x1080 or 3840x2160), and `pSrcViewRects` with `pDestPlacementBase` is how a plane is scaled. Not found in public - material (so **hypotheses**, all labelled ours in `xbox_present.h`): the values of `ScaleFilter` and `Flags`, whether - plane 1 can be a blended overlay at all on the console (the plane limit of 2 and the field set suggest a display-plane - model, but no public sample uses it that way), premultiplied or straight alpha, what is shown outside a plane's - placement, the blending space, the SDR white level, and every colour space but the two of the HDR sample. - - What the layer does. A plain single plane (SDR colour space, no placement, default filter) is the old blit, unchanged - (`composed_presents()` does not move; the test compares the bytes of a blit with the compose pass at 1:1 and they are - equal). Anything else goes through `VulkanPresenter::present_planes`: a compute pass (`runtime/src/present_compose.comp`, - SPIR-V embedded as `depth24_convert` is, built with `glslc --target-env=vulkan1.1 -O -mfmt=c`) writes an RGBA16F image of - the swapchain's size, and a `vkCmdBlitImage` (same size, nearest) puts it in the swapchain image, so the layer writes - the swapchain only by transfer (no storage usage) and the capture path is unchanged. The swapchain also asks for - `COLOR_ATTACHMENT`, which the layer never uses: overlays that hook the swapchain (Bandicam's - `VK_LAYER_bandicam_helper`, measured) draw into its images through a framebuffer, and without it every frame raised - `VUID-VkFramebufferCreateInfo-pAttachments-00877` and `VUID-VkImageViewCreateInfo-image-04441`. Surfaces always - report it, and the DXGI swapchain (`dxgi_swapchain.h`) already requested it. The planes are read with `texelFetch` (no sampler, so any - sampled float/UNORM/sRGB format works and filtering never reads outside the source rectangle); an sRGB-format source is - decoded by the texture unit and encoded again, so its bytes are read as stored. Plane 0: `pSrcViewRects[0]` (else the - whole texture) scaled to `pDestPlacementBase` (fractions of the output; null is the whole output; outside it is black), - `ScaleFilter` point (the texel containing the sample) or linear/default (bilinear, clamped inside the source rectangle). - Plane 1 is blended over plane 0 (in linear light after conversion, see "Linear-light filtering and blending"; alpha premultiplied by default or - straight with `xbox_plane_flag_straight_alpha`) **only** when it carries our `xbox_plane_flag_overlay`; without it plane 1 - is not composed (logged once), as before, because in the public sample it is the GameDVR copy of the frame and blending - a plane of unknown alpha would draw the frame twice (hypothesis: whether the console blends a second plane at all is - unmeasured). The extra fields are read defensively, since their types and values are unmeasured: a placement that is not - a sub-rectangle of 0..1 (empty, inverted, outside, NaN), an unknown `ScaleFilter` and `ExtendedDescCount` are ignored and - logged once, and the plane is shown as if they were absent; a single SDR plane with null/zero extras stays on the plain - blit. Planes the pass cannot read (multisampled, depth, integer, block-compressed) give `DXGI_ERROR_UNSUPPORTED`. The struct - in `xbox_present.h` follows the field order of the binding cited above exactly (`Token`, `ResourceCount`, `ppResources`, - `pSrcViewRects`, `pDestPlacementBase`, `ColorSpace`, `ScaleFilter`, `ExtendedDescCount`, `pExtendedDescs`, `Flags`); the - types and sizes are ours. The compose target follows the swapchain when it is recreated (resize, out-of-date acquire); - `xbox_present_test` resizes the window between composed presents. - - Colour. Only `RGB_FULL_G22_NONE_P709` (0, SDR, also the default for a zeroed struct) and `RGB_FULL_G2084_NONE_P2020` (12, - HDR10) are composed; any other value is composed as SDR and logged once. The swapchain is UNORM. If a plane is HDR10 and - the surface lists an ST.2084 format (`VK_COLOR_SPACE_HDR10_ST2084_EXT`, `A2B10G10R10` or `A2R10G10B10`; needs - `VK_EXT_swapchain_colorspace` enabled on the instance, the test device does) the swapchain is created in it and an HDR10 - plane goes through the working space unchanged; else the swapchain is SDR (the logged fallback). The real runtime's - instance (`create_vulkan_device_standalone`) enables `VK_EXT_swapchain_colorspace` when the loader has it (it did not - before; only the test device did), so the HDR10 surface formats can be listed there; `xbox_present_test` checks this on - the standalone path. Limited-range and YCbCr colour spaces are not modelled. - - *Linear-light filtering and blending* (decision from the sources below; the console's own blending space is unmeasured). - Every texel of a plane is decoded to linear light before it is weighted, the filtered plane is converted to the output's - working space, plane 1 is blended over plane 0 there, and the sum is encoded once: - - 1. Decode. SDR planes: the SDR EOTF (below) gives linear Rec.709 with 1.0 = SDR white. HDR10 planes: PQ inverse to linear - nits (Rec.2020). Premultiplied data is divided by alpha for the decode and multiplied again after, so what is filtered - and blended is linear premultiplied colour; straight-alpha colour is premultiplied after the decode, so a transparent - texel adds no colour of its own (found in review by @Flyander). - 2. Convert, still linear. HDR10 output: SDR to Rec.2020 (the Rec.709 to Rec.2020 matrix from the primaries; rows sum to 1) - times the SDR white level in nits. SDR output: HDR10 to Rec.709 (the inverse matrix), divided by the SDR white level, then - tone mapped (below). A plane already in the output's space is not converted. - 3. Blend `over + (1 - alpha) * base` (premultiplied; straight alpha was premultiplied in step 1); black outside plane 0. - 4. Encode once: PQ of the nits for an HDR10 output (argument clamped to 0..10000 nits), the inverse SDR EOTF (clipped to - 0..1) for an SDR one. - - Why. Microsoft's Advanced Color documentation says DWM composes in linear scRGB (FP16, "excellent precision for linear - gamma blend operations"), that an app which puts SDR and HDR content into one surface must apply the SDR boost itself, in - linear space (multiply by SdrWhiteLevel / 80), and, for a non-linear space such as HDR10, to "consider converting into - linear gamma to apply the adjustment"; it describes no blending in PQ, and a weighted sum of PQ values is not a sum of - light. (Some compositors blend in a gamma space to avoid banding; KDE's KWin is reported to do so since Plasma 6.2, - https://planet.kde.org/xavers-blog-2024-11-01-hdr-and-color-management-in-kwin-part-4-nonlinear-blending, **unverified**: only - a search snippet of that post was seen. Our intermediate image is RGBA16F, so banding is not what limits us here.) Each plane costs a decode and an encode per texel; a single SDR plane - still comes out byte for byte (`xbox_present_test`: within the 8-bit rounding of the RGBA16F intermediate, and equal to the - plain blit at 1:1). What changes against the first version of this section: bilinear filtering and alpha now weight light, - not encoded values, so a 50% white overlay on black is byte 188 (piecewise sRGB) or 186 (gamma 2.2), not 128, and a - bilinear edge between a dark and a bright texel is brighter than the same edge filtered in the encoded values. Whether - the title's art expects the encoded-space result (UI is often authored that way on SDR consoles; inference) is unmeasured - and is to be settled by a comparison with the title; the blend space is the one place that would then get a switch. - - *SDR EOTF* (selectable). Default: the piecewise sRGB curve (IEC 61966-2-1: `e / 12.92` up to 0.04045, else - `((e + 0.055) / 1.055)^2.4`). Option: a pure power of 2.2 (`XboxPresentation::set_sdr_eotf`, or the environment variable - `LEONIDA_SDR_EOTF=gamma22` (or `2.2`, any case; `srgb` or unset is the default, other values are logged once and ignored) read when the object is made; `PresentPlanes::sdr_eotf` in the presenter). The inverse of the - same curve encodes an SDR output, so SDR in an SDR output stays the identity. Why piecewise as the default: - **community-sourced**, not a Microsoft statement. KDE developer Xaver Hugl reports that Windows decodes SDR content with - the piecewise sRGB curve when HDR is on (raised darks, "washed out") while SDR displays use gamma 2.2 - (https://planet.kde.org/xavers-blog-2025-03-31-on-brightness-and-calibrating-your-displays/), and the ledoge - win11hdr-srgb-to-gamma2.2-icm project exists to make Windows use 2.2 instead - (https://github.com/ledoge/win11hdr-srgb-to-gamma2.2-icm). What a PC player compares against is Windows, so that is the - default; art mastered on a gamma 2.2 display looks closer to its intent with the option. The Xbox's own SDR-in-HDR decode - is unmeasured. An sRGB-format source is encoded again with the sRGB curve first (the texture unit had decoded it), so its - stored bytes are decoded by the chosen EOTF exactly as UNORM bytes would be. - - *SDR white level* (the nits that SDR white 1.0 maps to in an HDR10 output, and what HDR10 is divided by for an SDR one). - `XboxPresentation::set_sdr_white_nits(n)` with n > 0 overrides everything (n = 0 goes back to automatic). Otherwise, while - the swapchain is HDR10, Windows' SDR content brightness for the output the window is on: - `DisplayConfigGetDeviceInfo(DISPLAYCONFIG_DEVICE_INFO_GET_SDR_WHITE_LEVEL)` on the active display path whose GDI source name - is the window's monitor, `nits = SDRWhiteLevel / 1000 * 80` (1000 is 80 nits, the scRGB 1.0; - https://learn.microsoft.com/en-us/windows/win32/api/wingdi/ns-wingdi-displayconfig_sdr_white_level), read at most once a - second **by a background thread** (the query is not run on the present path, see below); `PresentX` reads the cached value, and a failed - query keeps the last good one. Otherwise (an SDR swapchain, or nothing read yet) 203 nits, the HDR reference white of ITU-R BT.2408 (graphics white, 58% PQ; - https://www.itu.int/dms_pub/itu-r/opb/rep/R-REP-BT.2408-9-2026-TOC-HTM-E.htm; the W3C CSS Color HDR module uses 203 too, - https://www.w3.org/TR/css-color-hdr-1; the report's text itself was not parsed here). Windows' setting is a PC desktop's; - the console's is unknown, which is why the override exists. Why a thread: the query is a `QueryDisplayConfig` (with the documented retry on - `ERROR_INSUFFICIENT_BUFFER`) plus two `DisplayConfigGetDeviceInfo` calls; measured by `xbox_present_test` on the author's - machine (12 us mean, 70 us worst over 50 calls on the AMD run; 47 us mean, 361 us worst on the NVIDIA run; this laptop's display setup, HDR off). That is - small here, but the call goes into the display driver stack and its worst case with several displays or during a mode change - is not bounded by anything measured (inference), and a stall under the present lock would feed `ImmediateThresholdPercent` - lateness; so it is kept off the present path. What is - measured about the value: the query returns 80.0 nits on the SDR desktop of both test GPUs' output, which is only the path - where the layer ignores it (it uses 203 nits unless HDR10 is active); the HDR value itself has not been read on real HDR - hardware here. 1000, 2500 and 6000 convert to 80, 200 and 480 (arithmetic only). - - *HDR10 content on an SDR output*: tone mapped, no longer clipped. After step 2, the luminance Y of the Rec.709 value - (0.2126 R + 0.7152 G + 0.0722 B, 1.0 = SDR white) goes through a shoulder: identity up to a knee at 0.8 of SDR white - (162 nits at 203), and above it extended Reinhard (Reinhard, Stark, Shirley, Ferwerda, "Photographic Tone Reproduction for - Digital Images", SIGGRAPH 2002, eq. 4) applied to the excess: with `t = 1 - knee`, `u = (Y - knee) / t`, - `w = (Lw - knee) / t`, `Yd = knee + t u (1 + u / w^2) / (1 + u)`, where `Lw = peak / SDR white` and `peak` is the content's - peak (default 1000 nits, `set_hdr_peak_nits`; no metadata is read, so this is an assumption). The colour is scaled by - Yd / Y. This is continuous in value and slope at the knee (slope 1 there), monotonic, and maps `Y = Lw` to exactly 1.0; - colours with Y below the knee (SDR-range content, up to 162 nits) are not touched. Above the knee it compresses: 203 nits - (SDR white) comes out at 0.90 of white at peak 1000 (byte 243), 300 nits at 250. Per-channel values above 1 after the - scaling (saturated highlights) are still clipped; there is no gamut mapping and no dither. Microsoft's Advanced Color - document lists tone mapping choices, among them a scaled Reinhard (`x / (1 + x)`) and the BT.2390 EETF, as simple options - (https://learn.microsoft.com/en-us/windows/win32/direct3darticles/high-dynamic-range). The BT.2390 EETF itself is not done - (its constants were not checked against the Recommendation here). - - *HDR metadata*: not sent. The presenter never calls `vkSetHdrMetadataEXT`. Microsoft's page for - `IDXGISwapChain4::SetHDRMetaData` (https://learn.microsoft.com/en-us/windows/win32/api/dxgi1_5/nf-dxgi1_5-idxgiswapchain4-sethdrmetadata, - fetched in the research) says calling it is not recommended, that Windows does not guarantee the metadata is sent to the monitor - and that monitors handle it inconsistently, and that an app should tone map into the range of `IDXGIOutput6::GetDesc1` - instead. vkd3d-proton forwards `SetHDRMetaData` to `vkSetHdrMetadataEXT` only for an explicit - `DXGI_HDR_METADATA_TYPE_HDR10` block (libs/vkd3d/swapchain.c, https://github.com/HansKristian-Work/vkd3d-proton; **partly read**: - the first ~100k of ~175k characters of the file, which include the HDR10 conversion and the setter), so a title that sets none gets none there either. - We invent no mastering values (Vulkan treats unknown `VkHdrMetadataEXT` fields as 0). Forwarding a title's explicit HDR10 - block is possible once a `SetHDRMetaData` slot exists. - - Sources for the PQ chain: the constants are the exact rationals of SMPTE ST 2084 / ITU-R BT.2100 (m1 = 2610/16384, - m2 = 2523/4096 x 128, c1 = 3424/4096, c2 = 2413/128, c3 = 2392/128; https://en.wikipedia.org/wiki/Perceptual_quantizer), - 1.0 = 10,000 nits; the Rec.709 to Rec.2020 matrix is computed from the primaries (ITU-R BT.2087 specifies the same - conversion; its PDF was not parsed). Microsoft's Advanced Color document: - https://learn.microsoft.com/en-us/windows/win32/direct3darticles/high-dynamic-range. - - *Verified* by `xbox_present_test` against a CPU model written from the above (not from the shader; it decodes, converts, - blends and encodes in double precision): point filtering between opaque SDR planes is byte exact; bilinear, alpha blending - (premultiplied and straight, point and bilinear), the sRGB and gamma 2.2 EOTFs and the linear 50% overlay are within 1 - level of 255; the HDR10 to SDR shoulder tone map (peaks 1000 and 600 nits; the expected bytes of an eight-step ramp and of an HDR10 plane 1 over an SDR plane 0 are hand calculations, as are the 50% overlay bytes 188 and 186) and the PQ encoder (an 8-bit swapchain forced to hold - PQ values with `force_hdr_encoding`, a test hook) are within 2 levels (GPU `pow`; the PQ codes of the source are 10-bit). - The HDR10 swapchain itself (format choice, 10-bit - capture, pass-through): **verified on an RTX 5080 (driver 616.56, Windows 11) with an HDR10 surface by @JavierBlanco23 - in #2069** (native ST.2084 swapchain within 1 code, GameDVR plane drop, tearing); **not verified on AMD**: the - author's Radeon 880M and RTX 5070 Laptop (desktop without HDR enabled) list no ST.2084 surface, where the test logs - that case as skipped and checks the 10-bit codes only where the surface has the format. -- *`ImmediateThresholdPercent`* (hypothesis from the FramePacing text, item 7 above; not measured on the console): - a frame is due at the vblank after the origin that handed out its token. One that is presented later than that - is late, and when the scan would not be further down the screen than the threshold percentage (late time modulo the - interval, as a fraction of the interval) it is flipped at once, mid-scan, instead of waiting a whole interval. 0, - negative and NaN never tear; 100 or more tears wherever the scan is; a frame on time never does. The decision is - the pure `leonida::decide_present_sync(late_us, interval_us, threshold)` in `frame_pacer.h`. A frame behind one - that still waits for its vblank is not torn (it would overtake it), and neither is an unpaced present. The tear - is shown in `GetFrameStatisticsX` (the display entry's `PercentScanned` is set and its time is the present time) - and in `XboxPresentation::immediate_presents()`. In Vulkan: with `VK_KHR_swapchain_maintenance1` (else the EXT - original; the structures are the same and the tests' GPUs list both; the instance gets `VK_KHR_get_surface_capabilities2` - and the matching `*_surface_maintenance1`) a vsync swapchain is created with `VkSwapchainPresentModesCreateInfoKHR` - listing FIFO plus IMMEDIATE (FIFO_RELAXED when the surface does not list IMMEDIATE as compatible with FIFO, - checked with `VkSurfacePresentModeCompatibilityKHR`), and a present that tears chains `VkSwapchainPresentModeInfoKHR` - with that mode. The extension and its feature are enabled only where the GPU has them. Without them, or without - either mode, the threshold is ignored and logged once, and a late frame waits for its vblank as before. - `LEONIDA_PRESENT_NO_TEAR=1` turns it off. Caveats: FIFO_RELAXED tears only when the queue is empty and a vblank was - missed (close to the semantics, but the driver decides), and the lateness is measured on the pacer's clock (a - timer, not the display's real scan), so on a real display the tear position is whatever the driver does at that - moment. What is checked is that the immediate mode is chosen and presented with 0 VUIDs in our runs with `LEONIDA_VK_VALIDATION=1`; no scan-out - or tearing was observed. -- *Tokens*: what the console does with a null, repeated or out-of-order token is **unmeasured**, and a title that - presents a loading screen with `Token = 0`, presents again with one token, or presents from a render thread out of - order must not freeze. So those are presented anyway and logged once per kind; only a token that was never handed - out gives `E_INVALIDARG` (nothing presented). Skipping a token is fine. -- *Frame capture* (`LEONIDA_CAPTURE=`, `LEONIDA_CAPTURE_EVERY=`, `LEONIDA_CAPTURE_LIMIT=`): writes - every n-th presented frame (default 30, at most 24) to `/frame_NNNNN.ppm`, a binary P6 of the swapchain image - converted to 8-bit RGB, and appends one line per frame to `/index.txt` with the extent and the mean RGB. Off - unless the variable is set, and the folder is created. This is what a check reads when it has to know what the - layer actually presented: the window is not readable in every setup (under Wine it is not even mapped), and the - mean is enough to tell a real frame from a black one. `d3d12_present_test` turns it on and checks the files against - the colour it clears to. -- *`SuspendX`/`ResumeX`*: suspend drops the interval, the origin event and the frames in flight, wakes blocked waits - with `ERROR_INVALID_STATE` and refuses presents (a `PresentX` waiting for a swapchain image polls the suspended - state every 50 ms and gives up, so `SuspendX` never waits on it); resume allows presents again, but waits fail until - `SetFrameIntervalX` and `ScheduleFrameEventX` are called again, as the samples do. Tokens keep counting. Calling - `SetFrameIntervalX` again outside suspend keeps the origin event armed and re-bases the vblank grid on that moment. -- *Not done*: the BT.2390 tone map and gamut mapping for HDR10 on an SDR swapchain (a Reinhard shoulder only), scRGB, limited-range - and YCbCr colour spaces, `ResourceCount` above 1 (refused with `DXGI_ERROR_UNSUPPORTED` before either path, logged once, since only resource 0 would be read; found in review by @Flyander), extended descriptors (`pExtendedDescs`) and `ViewCount`, capturing a - second (GameDVR) output, resolving multisampled planes, a mutable-format swapchain (an sRGB/UNORM - alternation recreates the swapchain; `VK_KHR_swapchain_mutable_format` is not enabled on the device), a host-vblank clock (the timer drifts from the - display; with FIFO presents the swapchain holds the queue to the real refresh anyway), render statistics, - `PercentScanned` of frames shown at a vblank (a scan position is never measured), and the vtable wiring. The - public slots are the device's `SetFrameIntervalX`/`ScheduleFrameEventX`/`WaitFrameEventX`/`GetFrameStatisticsX` - at 78-81 and `PresentX` at queue 30 (older runtime layout) or 32 (newer); `SuspendX`/`ResumeX` have no public - slot. Nothing here is wired to those slots yet, and the game's own runtime is not observed. -- *Tests*: `frame_pacer_test` (fake clock: interval, offset, late waits, timeouts, latency blocking, tokens, - statistics, suspend/resume, a real 10 ms timer; no GPU) and `xbox_present_test` (the Vulkan device, reading the - swapchain image back: blank, solid, two colours, source rectangles, RGBA/BGRA/sRGB sources, 2 planes, plane composition - (placement, point/bilinear, alpha overlay, HDR10 and PQ conversions, refusals; against a CPU model), token errors, - statistics, suspend/resume, `ImmediateThresholdPercent` with a late frame at several thresholds (immediate mode - chosen, or not for 0, below the lateness, on time) and with `LEONIDA_PRESENT_NO_TEAR=1`, 30 frames at 60 Hz in real - time; skipped, exit 77, without a Vulkan device). `frame_pacer_test` also sweeps `decide_present_sync`. - -### 4.6 Queries - -Implemented (`QueryHeap` in `runtime/shims/d3d12_vulkan_device.cpp`, the query commands in `command_list.h` and -`vulkan_replay.h`), checked on one GPU by `d3d12_vulkan_device_test` under the validation layer: - -- **Heaps.** One `VkQueryPool` per `ID3D12QueryHeap`, registered with the `VulkanContext` by its pointer, as - resources are. `OCCLUSION` heaps are `VK_QUERY_TYPE_OCCLUSION` pools and hold both `OCCLUSION` and - `BINARY_OCCLUSION` queries, as in D3D12. `TIMESTAMP` and `COPY_QUEUE_TIMESTAMP` heaps are - `VK_QUERY_TYPE_TIMESTAMP` pools; they are refused when the queue family's `timestampValidBits` is 0. - `PIPELINE_STATISTICS` heaps count all eleven Vulkan statistics (`0x7ff`), whose result order is the field order - of `D3D12_QUERY_DATA_PIPELINE_STATISTICS` (IA vertices, IA primitives, VS, GS invocations, GS primitives, - clipper invocations and primitives, PS, HS, DS, CS), so one 88-byte result per query is copied as is. They need - `pipelineStatisticsQuery`. `VIDEO_DECODE_STATISTICS` and `PIPELINE_STATISTICS1` (mesh and amplification counts) - are logged and refused with `E_NOTIMPL`. Invalid descriptions are answered as the host runtime answers them - (`compare_invalid_arguments`, "query heap:", RTX 5070 / 621.14): `E_INVALIDARG` for no queries, a node other than - node 0, or a type past `PIPELINE_STATISTICS1` (7), checked before the output; a valid description with a null - output is then `E_UNEXPECTED`, not `S_FALSE`. -- **Stream-output statistics** (D3D-302). The layer has no stream output: a graphics PSO with `StreamOutput` - entries is refused and `SOSetTargets` is not implemented, so no primitive reaches a stream and every - `SO_STATISTICS_STREAM0..3` query counts 0 written and 0 needed. An `SO_STATISTICS` heap is therefore made without - a `VkQueryPool`: `BeginQuery`/`EndQuery` record nothing in Vulkan (D3D12's call rules are still kept, and the - heap's queries track ended or not as the others do), they overlap no other query, and `ResolveQueryData` writes - zeros (`vkCmdFillBuffer`, 16 bytes per query: `NumPrimitivesWritten`, `PrimitivesStorageNeeded`), with no - statistics split since nothing is dispatched. When stream output lands, the heap becomes a - `VK_QUERY_TYPE_TRANSFORM_FEEDBACK_STREAM_EXT` pool begun with `vkCmdBeginQueryIndexedEXT` on the stream, whose two - results are in the same order. -- **Recording.** The list keeps D3D12's rules for the calls: timestamps only have `EndQuery`; every other query is - begun and ended in the same list with the same type, is not begun again while it runs, and is not resolved while - it runs; resolve offsets are multiples of 8. A list closed with a query still running reports `E_INVALIDARG` and - is refused at execution. Heap types, index ranges and the destination buffer are checked at - `ExecuteCommandLists`, when the heap and buffer are known (`ReplayResult::invalid_query`). -- **Replay.** D3D12 queries need no reset; a Vulkan query does. Each `BeginQuery` and each timestamp `EndQuery` is - preceded by `vkCmdResetQueryPool` of that one query. Nothing in the layer runs inside a render pass yet, so the - reset is legal where it stands; a draw path that opens a render pass around queries must reset them before it. - `OCCLUSION` begins with `VK_QUERY_CONTROL_PRECISE_BIT` when `occlusionQueryPrecise` is enabled. A timestamp is - `vkCmdWriteTimestamp` at `BOTTOM_OF_PIPE` (every earlier command finished). `ResolveQueryData` is - `vkCmdCopyQueryPoolResults` with `VK_QUERY_RESULT_64_BIT | VK_QUERY_RESULT_WAIT_BIT`. A query keeps its result - across executions until it is begun or written again, as in D3D12. -- **Binary occlusion.** The queue resolves to a scratch buffer in chunks, reduces each 64-bit value to 0 or 1 - with a compute dispatch, and copies it into the destination. This works with readback buffers, which need - only transfer-destination usage. The helper runs outside conditional rendering so a predicate cannot suppress - the resolve. `vk_binary_occlusion` checks more than one scratch chunk, gaps, suballocated destinations, - consecutive submissions and an ordinary occlusion count on a real Vulkan device. -- **Queries never ended.** D3D12 leaves their result undefined; a Vulkan copy with `WAIT_BIT` would wait for them - forever. Each heap records on the host which queries were ended, in submission order, and a resolve writes zeros - (`vkCmdFillBuffer`) for the ones that were not. -- **Overlapping occlusion queries and statistics (D3D-252).** On a graphics queue with compute, the replay opens - a new physical query whenever the set of active queries changes. Ordinary and binary occlusion share the one - physical pool (both are `VK_QUERY_TYPE_OCCLUSION`, so one physical query is open at a time, and the shared - intersection interval is counted by both logical queries); pipeline-statistics queries split the same way into - the statistics pool, where every non-timestamp resolve and every helper dispatch while a query runs also closes - and reopens the open segment (D3D-162), for every query open at that point. Each logical query keeps a - contiguous range in the submission's pool. Resolving it sums the results on the GPU, then copies them to the - destination; a binary resolve normalizes the summed counts to 0 or 1 (`sum_binary_occlusion`, the sum followed - by the existing normalize). Both occlusion compute helpers reuse one scratch buffer per queue. Logical results - and in-flight submissions retain the pools independently, so later resolves and overwrites can be recorded - before the earlier commands complete. `vk_overlapping_occlusion` checks crossing and nested scopes, more than - one scratch chunk, alternating binary and ordinary resolves under a predicate, gated submissions, crossing - statistics queries against three unsplit references word by word, and an ordinary query around a binary one, on - a GPU; `replay_query_predication` pins the segment layouts, the helper dispatches inside an overlap and the - binary sum-and-normalize without a GPU. On a device without `pipelineStatisticsQuery` (MoltenVK) the test - leaves the statistics lists out; `vk_overlapping_occlusion_no_statistics` runs it that way (`--no-statistics`) - on a device that has the feature, so that path is also run where no such device is at hand. -- **Helper dispatches during a pipeline-statistics query** (D3D-162). The helper dispatches above (binary - normalisation, occlusion sums), statistics sums, `SetPredication` captures, predicated buffer copies and D24/RGB96 footprint - conversions would count in the application's `CSInvocations` if they ran inside its query. Such a query is split. - Its counters go to physical `PIPELINE_STATISTICS` segments in a pool of the submission's own; a segment ends - before each helper and a new one begins after it. Non-query helpers and resolves share the segment numbering. - Its result is the sum of its segments, added per counter by a compute dispatch (`statistics_sum.comp`) on the - same scratch buffer, which is itself kept out of any statistics query still running. - Whether a resolve dispatches is only known once the list is planned against the heaps, so every such resolve - splits the query. `vk_binary_occlusion` checks that a binary resolve and a statistics sum inside statistics queries - leave every counter at 0. `vk_overlapping_occlusion` puts a native draw in each segment and checks the split sums - against unsplit queries with the same draws, word by word. `vk_predicated_copy` checks captures, rebindings and - predicated copies; `depth24_convert` checks both conversion directions for D24 and RGB96. Their byte-exact - results still match and all 11 statistics counters are zero. Without a statistics pool (single-list `replay()` or - a queue without the summation helper), these three commands are refused before helper scratch allocation or - recording. The resolve fallback is unchanged: only resolves needing dispatches are refused there. -- **Mesh draws during a pipeline-statistics query** (D3D-291). D3D12 allows `DispatchMesh` inside a statistics query - and reads its input-assembly, vertex, geometry and tessellation fields as 0. Vulkan forbids `vkCmdDrawMeshTasksEXT` - while a query with those counters is active (`VUID-vkCmdDrawMeshTasksEXT-pipelineStatistics-07076`), and the heap's - pool has all eleven. So a statistics query that holds a mesh draw is split as above, and a split before a draw stays - outside its rendering scope. A segment's first draw decides its pool: the submission's full pool, or a second pool - with only clipping invocations and primitives, fragment and compute invocations. A later draw of the other kind ends - the segment and begins one of its own kind; dispatches and segments without draws use the full pool, and - `ExecuteIndirect` draws count as vertex draws. The sum copies a mesh segment's four counters into fields 5 to 8 of - its record, and `statistics_sum.comp` adds them as `CInvocations`, `CPrimitives`, `PSInvocations` and - `CSInvocations`, so the other fields get nothing from it. A query that holds only mesh draws is one mesh segment, - resolved through the same sum. Without the compute helper there is no segment pool and such a list is refused - (`unsupported`) rather than run unsplit; so is one on the single-list `replay()` (D3D-399), whose - `create_segment_pool` gives no mesh pool. Overlapping statistics queries (D3D-252) split the same way inside their - shared segments: a draw of the other kind than the open segment's opens a new one, so every query that segment - belongs to sums both kinds. `replay_query_predication_test` (cases 15 and 16) checks the split points, the segment - kinds and the resolve plan on the CPU. `d3d12_mesh_test` resolves a query around a vertex, two mesh and a vertex - draw, one around a mesh draw and one around the two vertex draws: the vertex fields count only the two triangles, - and the mixed query has more pixel-shader invocations than the vertex-only one, and more clipping invocations - wherever the mesh-only query counts any. On the RX 9060 XT (RADV), the clipping counts add up exactly - (2 + 10 = 12); the device of the Wine CI jobs counted no clipping for the mesh-only query, next to 1024 - pixel-shader invocations (run 45442389069, Wine 11.0). -- **Timestamps.** `GetTimestampFrequency` is `1e9 / timestampPeriod` (1 GHz on the test GPU). Every D3D12 queue - shares one `VkQueue` for now (question 12), so they share one frequency. -- **Timestamp resolves on MoltenVK.** On Apple GPUs, MoltenVK delays every `vkCmdWriteTimestamp` to the end of - the current Metal encoder, where it is sampled by a blit pass of its own (`encodeTimestampStageCounterSamples`, - because Apple GPUs sample only at stage boundaries). `vkCmdCopyQueryPoolResults` resolves the counters with a - blit that nothing orders after that pass. The copy then reads the previous value, or 0 for a timestamp never - written before. This happens when the copy is in the timestamp's open blit encoder, in a later encoder, in a later - command buffer or in the next `vkQueueSubmit`. The spec needs no barrier here: `WAIT_BIT` waits for the query. - `vkGetQueryPoolResults` on the host is right. A minimal Vulkan program (two timestamps around a - `vkCmdCopyBuffer`, resolved with `64_BIT | WAIT_BIT`, compared with `vkGetQueryPoolResults`, 200 runs per case - on an M3 Max, macOS 27.3) got the right values 0 to 13 times out of 200 for each of these placements with - MoltenVK 1.4.3 (`main` 5189f8de). With a pipeline barrier or a fill before the copy it was 9 and 3 out of 200. - MoltenVK 1.4.2 got 0 to 43 out of 200, measured while other GPU work ran. Every case was right 200/200 on - KosmicKrisp (Mesa 26.3.1) and llvmpipe. Two things order the copy on MoltenVK, right in every run (200 or 500 - runs, both versions). One is `vkCmdSetEvent` + `vkCmdWaitEvents` on a fresh event before the copy, which MoltenVK - encodes as a Metal event signal and wait on the command buffer. The other, across submissions, is a timeline - semaphore wait for the earlier submission. So where `driverID` is `VK_DRIVER_ID_MOLTENVK` (Wine reports the - host's driver), the queue sets and waits for an event before each timestamp resolve that copies, and a - submission with such a resolve waits on the queue's own timeline for the submission before it. The values are - still the GPU's own timestamps, nothing is emulated. MoltenVK picks at submit time, from the event's host state, - whether a set or wait does anything. So each resolve gets an event of its own, which goes back to the queue's pool - after a host `vkResetEvent` once the submission completes. `d3d12_vulkan_device` checks the same list (timestamp, - clear, copy, timestamp, resolve) and a resolve in the next execution with no wait between them. Under Wine - (CrossOver 26.3, MoltenVK 1.4.3) the first case failed every run before this change (`t1` read 0). - -The single-list `replay()` helper replays overlapping occlusion kinds and statistics queries too (D3D-399) when -the caller passes a `keep` vector and sets `ReplayFunctions::create_segment_pool` with the four sum helpers: it -makes one occlusion and one pipeline-statistics segment pool sized to the list, plans them as the batched path does, -and hands them to `keep`, which the caller holds until the command buffer has completed. Without them such a list is -still refused with `ReplayResult::unsupported`. `replay_query_predication_test` case 14 checks both, on case 13's -statistics list and case 10's occlusion pair (no GPU). - -Not implemented yet: - -- **Overlapping queries in the single-list `replay()` helper.** It has no segment pool, so a list whose occlusion - kinds or statistics queries overlap each other is refused there with `ReplayResult::unsupported`; the batched - path above replays them. -- Mesh-shader statistics (`PIPELINE_STATISTICS1`, D3D-132), and stream-output statistics that count real - primitives (they wait for stream output itself). (`GetClockCalibration` is implemented: see section 4.4, - "Fences, queues and frames in flight".) -- Stream-output and mesh-shader statistics. (`GetClockCalibration` is implemented: see section 4.4, "Fences, - queues and frames in flight".) -- Xbox-specific query heap types (if any) are **Open**; unknown types are logged. - -### 4.7 Indirect commands and command signatures - -- `D3D12_COMMAND_SIGNATURE_DESC` describes the argument stride and a list of argument types. Simple draw, - draw-indexed, dispatch and mesh-dispatch signatures map to `vkCmdDraw*Indirect`, `vkCmdDispatchIndirect` and - `vkCmdDrawMeshTasksIndirectEXT`; use the `*Count` variants (`VK_KHR_draw_indirect_count`, core 1.2) when the - `ExecuteIndirect` call supplies a count buffer. -- Signatures that change root constants, vertex/index buffers or descriptors per argument cannot be expressed by - one Vulkan indirect call. Use a compute expansion pass that writes a Vulkan-shaped indirect buffer, or - `VK_NV_device_generated_commands` on NVIDIA. Start with the simple signatures; the trace will show which - signatures the game creates. -- Predication (`SetPredication`) maps to `VK_EXT_conditional_rendering` (D3D-18). Done: `GraphicsCommandList:: - SetPredication` records a `Predication` command (`runtime/src/command_list.h`; offset 8-byte aligned, op - `EQUAL_ZERO` or `NOT_EQUAL_ZERO`, a null buffer turns it off). The replay (`runtime/src/vulkan_replay.h`) begins - conditional rendering on the captured condition, plain for `EQUAL_ZERO` (Vulkan discards when the word is 0) and - `VK_CONDITIONAL_RENDERING_INVERTED_BIT_EXT` for `NOT_EQUAL_ZERO`, ends it before a new predicate (it cannot - nest) and at the end of the list (predication does not carry over to the next list). While a predicate is set, - whole-view clears are replayed as one rectangle with `vkCmdClearAttachments`, because `vkCmdClearColorImage` and - `vkCmdClearDepthStencilImage` ignore conditional rendering. The standalone device enables the extension and its - `conditionalRendering` feature when the GPU has them, and then creates buffers with - `VK_BUFFER_USAGE_CONDITIONAL_RENDERING_BIT_EXT`; without it a predicated list is rejected (`unsupported`). - `D3D12_RESOURCE_STATE_PREDICATION` is the same bit as `INDIRECT_ARGUMENT` (and `SYNC_PREDICATION` / - `ACCESS_PREDICATION` the same as `EXECUTE_INDIRECT` / `INDIRECT_ARGUMENT`), so with the extension enabled - barriers into and out of that state also cover `VK_ACCESS_CONDITIONAL_RENDERING_READ_BIT_EXT` at - `VK_PIPELINE_STAGE_CONDITIONAL_RENDERING_BIT_EXT`, where the predicate is read: without it a `ResolveQueryData` - into the predicate had no dependency on the read (`vulkan_access`, `vulkan_barrier_scope`). - Checked by part E of `vk_command_replay_test` on an NVIDIA GeForce RTX 3070, and end to end by - `d3d12_vulkan_device_test` (an occlusion query resolved into a predicate, through legacy and enhanced barriers) - on an NVIDIA GeForce RTX 5070. - The 64-bit value is captured on the GPU at each `SetPredication`: an internal eight-byte copy and a - one-invocation compute pass OR the two dwords into a private 32-bit condition. Later writes to the source do - not change that snapshot. A null buffer disables predication; rebinding ends the previous conditional scope - before the capture, so the internal dispatch is never predicated. Bounds checks require all eight bytes. - Capture arenas and descriptors remain alive until their command buffer's timeline ticket completes. No - CPU readback or per-predicate wait is used. This helper requires a compute-capable configured queue family; - unsupported queues fail preparation instead of falling back to the low word. The synthetic GLSL source and - embedded SPIR-V are shipped together; normal builds do not need a shader compiler. - Capturing a new predicate inside an active pipeline-statistics query splits the query around the capture - dispatch (D3D-162, section 4.6), keeping its invocation out of the application's result. Without a statistics - segment pool, preparation still refuses the capture before allocating its scratch. - Integration notes for #291 and D3D-27: the capture helper binds its own compute pipeline, descriptor set 0 - and push constants. The compute path must restore those bindings afterward, or bind its application state - before each dispatch. Copies and compute dispatches cannot execute inside dynamic rendering, so render-pass - integration must place the capture outside the rendering scope while preserving capture at `SetPredication`. - These are requirements for those future integrations, not compute-dispatch or render-pass support added here. - `CopyBufferRegion` under a predicate instead uses a byte-granular compute dispatch inside the captured - conditional scope; both operations, unaligned offsets and lengths, and the full 64-bit predicate are covered. - Zero-byte copies are no-ops, as checked against native WARP. Unpredicated copies retain `vkCmdCopyBuffer`. - The compute helper requires enabled Vulkan 1.2 `storageBuffer8BitAccess` (not `shaderInt8`) and a compute queue; - without it, preparation rejects the predicated buffer copy rather than executing it unconditionally. - Descriptor windows respect storage-buffer alignment/range and dispatch limits, including arena offsets. - Copy descriptors are owned by command-buffer slots until the submission timeline completes. Memory dependencies order prior writes, - subsequent reads and successive windows. Direct and compute queues support the helper; copy queues reject - active predication. Preparation is serialized under the tracker lock, preserving resource -> tracker -> submit - lock order and the copy-then-commit tracker. Readback writes accumulate COMPUTE_SHADER for the helper and COPY - for ordinary copies; mixed lists accumulate both before main's queue-specific host-stage filtering. - This helper also binds compute pipeline/set 0/push constants, so the - application-state restoration requirement above applies. A predicated copy inside an active pipeline-statistics - query splits that query around the helper dispatches (D3D-162); without a statistics segment pool it is refused - before copy scratch allocation. - Synthetic checks: `predicated_copy_test` covers preparation and rejection paths without a GPU; - `d3d12_predicated_copy_test` compares 180 byte-exact cases against WARP and an independent literal oracle, - plus 16 query-to-copy cases: real empty ordinary/binary occlusion queries resolve zero into a default-heap - predicate at offsets 0/16, both predicate operations govern copies, and executing overwrite copies replace zero - with a high-word-only value. Four paired controls verify that recapturing the same address changes exactly one - 13-byte destination region; without recapture, later copies keep using the captured zero. Predicate-buffer guards - and all untouched destination bytes are checked too. These query cases do not cover nonzero visible-draw counts; - `vk_predicated_copy_test` forces small windows and dispatches, arena prefixes, dependent copies, offset rebinding, - reset, 32 gated plus 32 reused submissions, failed-submit cleanup and host stages on all three queue kinds. - Binary and overlapping occlusion fixtures also verify that query results resolve under a false predicate while - a dedicated copy destination remains unchanged; disabling predication copies into a separate region. - The embedded shader is generated from `predicated_copy.comp` - with glslang 16.6.0 (`-V --target-env vulkan1.2 -Os`) and validated for Vulkan 1.2. - - Open: - - Texture copies, `CopyResource` and resolves. Vulkan's conditional rendering does not cover transfer - commands, so these still run unconditionally and `PreparedList::unpredicated_copies` counts them. - - - Draws, dispatches and `ExecuteIndirect` are covered by conditional rendering as soon as they are replayed - (D3D-3, D3D-4, D3D-17); `ClearUnorderedAccessView*` and `ResolveSubresource` need the same check when added. - -### 4.8 Ray tracing and XDXR - -This is the largest Xbox-specific area, and the shipped `XboxBvhBuilder.dll` gives concrete evidence. The DLL's -own names use the `XDXR` prefix for Xbox's raytracing path: - -- Its constructor takes `ID3D12Device11*`; its build/copy/rehydrate methods take - `ID3D12GraphicsCommandList4/6/8*`. -- Prior art measured its constructor creating 53 compute pipelines through device slot 62, called with the - compute-PSO shape (a plain `D3D12_COMPUTE_PIPELINE_STATE_DESC`, two zero words, iid, out); on the PC interface used - there slot 62 is `CreateStateObject` (a different arity), so the proxy overrides it. The layer must implement - slot 62 as compute-PSO creation, not as a state object. -- It exposes standard `D3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_DESC` builds, batched Xbox builds - (`D3D12XBOX_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_BATCHED_DESC2`), XDXR stream descriptions - (`D3D12XBOX_XDXR_STREAM_DESC`), post-build offline statistics, and a `DEHYDRATE` build flag. The Xbox types are - not public. **Measured** from the DLL's own reads ([xdxr.md](xdxr.md), `runtime/src/xdxr_descs.h`): `BATCHED_DESC2` - is the public build desc, the postbuild count and pointer, and a 16-byte `XDXR_STREAM_DESC` (`0x50` bytes); the - stream desc is a size and a pointer to 16-byte typed records. The DLL rejects the offline-statistics postbuild type - (`0x10`) for every build, so that layout is not in the package. -- The translator's `image_bvh_intersect_ray` / `image_bvh64_intersect_ray` already emulate the AMD hardware BVH - node format: node id = address >> 3 | type, box16/box32/triangle nodes, 256-byte base units. That is the format - the runtime must produce for the game's compute traversal. - -**The builder's own shaders are console FSSM, not Xbox DXIL.** Each of the 52 containers carries an LLVM -bitcode blob and an `XDAT`/`XBCH` record; the PC experiment below compiled the bitcode, but the console runtime -executes the `XBCH` record. Measured from that record: 52/52 unpack to `FSSM`, 51 translate and all 51 pass -`spirv-val` with the same translator the game's 26,503 shaders use; the one left (`Box16Rehydration`) needs -`buffer_store_short` (#1864) ([embedded_shaders.md](embedded_shaders.md)). The -raw 64-bit addresses are the corpus's existing raw-address path, not a separate lowering. Open: whether the game -uses the builder at all (RT-5) and whether the translated programs match a reference on a GPU. - -The design choice follows from that: **build AMD-format BVH data, not a `VkAccelerationStructureKHR`, unless the -shaders are changed to `OpTraceRayKHR`.** The game's 64 RT compute shaders traverse the nodes themselves; a -Vulkan AS would be invisible to them. Two paths: - -1. If `XboxBvhBuilder` does the build with its own compute dispatches (the likely case, given it ships as a DLL - with a device and command lists), the layer must translate and run its compute shaders. The console programs - are `FSSM` and 51 of the 52 already pass `spirv-val`; only `Box16Rehydration` still needs `buffer_store_short` (#1864). Buffers, - UAVs, descriptors, barriers and indirect dispatch are necessary but not sufficient. The standard - `BuildRaytracingAccelerationStructure` calls may never reach our command list. -2. If the game calls `ID3D12GraphicsCommandList4::BuildRaytracingAccelerationStructure`, the layer must implement - it. Produce the AMD node layout in the arena, with the same geometry/instance rules the translator assumes, - and make `GetRaytracingAccelerationStructurePrebuildInfo` return sizes for that layout. - The layout is the XDXR BVH4 runtime form ([bvh.md](bvh.md) §3.1). `tools/xdxr_bvh.py` encodes it on the - CPU, with a reference traversal and a validator ([bvh.md](bvh.md) §7a). `runtime/src/xdxr_build.h` builds it on - the GPU and is checked against that reference. The standalone device uses it for `BuildRaytracingAccelerationStructure` - and answers `GetRaytracingAccelerationStructurePrebuildInfo` from its layout, exactly. Acceleration-structure - buffers then keep their console VAs, the addresses the records name each other by. `LEONIDA_RT_AS=khr` keeps - #743's `VkAccelerationStructureKHR` builds (for `RayQueryKHR`), which the game's shaders can't read. Updates refit - the source structure instead of rebuilding it, `CopyRaytracingAccelerationStructure` clones and compacts, and the - postbuild compacted and current sizes are written ([bvh.md](bvh.md) §7a). A bottom-level build with - `MINIMIZE_MEMORY` gets BOX16 nodes (half boxes, about a fifth smaller; top-level builds stay BOX32), and one - without `ALLOW_UPDATE` pairs sibling triangles that share an edge into TRI0/TRI1 leaves. Serialization and the Xbox - #743's `VkAccelerationStructureKHR` builds (for `RayQueryKHR`), which the game's shaders can't read. A top-level - build with `D3D12_ELEMENTS_LAYOUT_ARRAY_OF_POINTERS` is supported there: the console VAs in the pointer list are - translated to Vulkan device addresses in a staged copy, without changing the guest's input. The list must be in - CPU-writable memory (an UPLOAD or write-back CUSTOM heap; WRITE_COMBINE CUSTOM is CPU-writable too); GPU-written - DEFAULT and READBACK lists are refused as `unsupported` before submission, since their mapped bytes can still hold - an earlier frame's pointers when the CPU prepares the build. Completed staging buffers - are reused, so a per-frame rebuild does not allocate memory each frame. Updates refit the source structure instead of rebuilding it, `CopyRaytracingAccelerationStructure` clones and compacts, and the - postbuild compacted and current sizes are written ([bvh.md](bvh.md) §7a). Serialization and the Xbox - batched/streaming builds are not implemented. The - reported `RaytracingTier` is unchanged (`NOT_SUPPORTED`). Checked by `runtime/test/d3d12_xdxr_rt_test.cpp` through - the D3D12 API. - -**Open:** which path the game uses. Resolve by logging the first call to the standard AS methods and by tracing the -builder's command-list usage. If XDXR batched/streaming builds are used, their structs and compression formats need -to be recovered from call sites (or the NDA GDK headers, if a developer has access); they cannot be guessed. - -### 4.9 Xbox-specific surface - -| Feature | Public evidence | Design | -|---|---|---| -| No ESRAM | Xbox Series X\|S uses unified GDDR6; ESRAM was Xbox One | Do not implement ESRAM-era APIs. The `d3d12_xs.cpp` comment about "ESRAM-era extensions" should be read as Xbox One, not Series. | -| Binning | The GDK topic index names Xbox binning modes (NDA content) | Should be a no-op if the game uses it only as an optimisation: it changes how a render pass uses on-chip memory, not the result. Log and ignore for the first boot; revisit for performance. **Open** whether the game relies on binning for correctness. | -| DCC / texture compatibility | Public release note for `D3D12XBOX_RESOURCE_FLAG_FORCE_TEXTURE_COMPATIBILITY` | Let Vulkan choose compression; fail if the game aliases/reads raw compressed data. | -| PresentX / present planes / frame events | Public GDK samples (MIT/zlib), §4.5 | Likely the only present path of a GDKX title. Presenter + vblank-timed frame events; 1-2 planes composed into the Vulkan swapchain (placement, filter, alpha overlay, HDR10 conversions). Call shapes known; slots/layouts **Open**. | -| Device slots 48/73/78/79/80 | Public HLE `Freminet`/`ScarlettX` (third-party, not Microsoft documentation) | `d3d12_xs_device.cpp` routes `CreateCommandQueueX` (48), `CreateCommandListX` (73), `SetFrameIntervalX` (78), `ScheduleFrameEventX` (79) and `WaitFrameEventX` (80) before it indexes the PC vtable. Queue and list creation use the existing create paths. The frame-event calls are a per-device token counter: `WaitFrameEventX` returns at once with a fresh non-zero token, because there is no vblank source before a presenter exists. The five indices can be moved with `LEONIDA_XS_QUEUE_X_SLOT`, `LEONIDA_XS_LIST_X_SLOT`, `LEONIDA_XS_FRAME_INTERVAL_SLOT`, `LEONIDA_XS_SCHEDULE_EVENT_SLOT` and `LEONIDA_XS_WAIT_EVENT_SLOT` (3..127; a value that names a slot the proxy already handles keeps that slot's handler); a trace that disagrees wins. | -| VRS | Public `D3D12_SHADING_RATE` / `D3D12_AXIS_SHADING_RATE` | `VK_KHR_fragment_shading_rate`; `RSSetShadingRate`/image-based rate map to `vkCmdSetFragmentShadingRateKHR`. | -| Mesh shader tier | Public `D3D12_MESH_SHADER_TIER` | `VK_EXT_mesh_shader`; the 9,282 translated mesh shaders make this a hard requirement for any content that uses them. | -| Wave MMA | Public `D3D12_WAVE_MMA_TIER` | Not used: no shader sets `WAVE_MMA` in SFI0 and none contains `v_mfma`/`v_wmma` (all 26,503, `tools/feature_scan.py`). Answer the tier query truthfully; no cooperative-matrix mapping is needed. | -| Enhanced barriers | Public Xbox Series `D3D12_BARRIER_GROUP` | `VK_KHR_synchronization2`; implement directly. | -| XDXR batched/streaming BVH | `XboxBvhBuilder.dll` exports | See 4.8. | - -### 4.10 Debug markers and private data - -Games and middleware call these every frame (PIX events), so they must be cheap and never fail. Implemented -(D3D-24) in `runtime/shims/d3d12_com.cpp`, `runtime/shims/d3d12_com_object.h`, `runtime/src/command_list.h`, -`runtime/src/vulkan_replay.h` and `runtime/src/vulkan_backend.h`; tested by `runtime/test/d3d12_debug_markers_test.cpp`. - -- **Labels, only with `VK_EXT_debug_utils`.** It is an instance extension, so `VulkanDeviceInfo::debug_utils` says - whether the instance enabled it; `create_vulkan_device_standalone` enables it when the loader lists it. Without - it every marker call is a no-op (nothing logged, nothing recorded on the queue). -- **Command lists.** `SetMarker`/`BeginEvent`/`EndEvent` are recorded in the IR (`DebugMarker`) in order with the - other commands and replayed as `vkCmdInsertDebugUtilsLabelEXT`/`vkCmdBeginDebugUtilsLabelEXT`/ - `vkCmdEndDebugUtilsLabelEXT` into the submission's command buffer. -- **Queues.** The same three methods on `ID3D12CommandQueue` call `vkQueueInsert/Begin/EndDebugUtilsLabelEXT` under - the device's submit lock, so they fall between the submissions issued before and after them. -- **Balancing.** D3D12 does not make a list balance its events; Vulkan requires every end to have a begin. - One `ExecuteCommandLists` is one command buffer, so a begin in one list may be ended by a later list of the - same call. An end with nothing open is dropped, and labels still open when the last list ends are ended - before the command buffer is ended. Queue labels are balanced per queue the same way (an unmatched end is - dropped; open ones are ended when the queue is destroyed). Command-buffer labels never span two - `ExecuteCommandLists` calls. -- **Labels.** The `Metadata` argument says what the data is, following WinPixEventRuntime's `pix3_win.h`: - 0 (`PIX_EVENT_UNICODE_VERSION`) a UTF-16 string, 1 (`PIX_EVENT_ANSI_VERSION`) an ANSI string, both cut at the - terminator or at `Size` bytes and converted to UTF-8; 2 (`PIX_EVENT_PIX3BLOB_VERSION`) PIX's own encoded event, - which is not decoded and gets the fixed label `PIX event` so the nesting is still visible (question 21). Other - values get the same label and log once. -- **Private data, on every object.** `SetPrivateData`, `GetPrivateData`, `SetPrivateDataInterface` and `SetName` - live in the shared `Object` base, so the device, queues, allocators, lists, fences, descriptor heaps and - resources all have them. Every answer is the host runtime's: `d3d12_private_data_test` runs the same 672 steps - on the device, a fence, a buffer, an allocator and a descriptor heap of both devices and compares each HRESULT, - returned size, byte and reference count (RTX 3060, driver 610.88, no debug layer): - - `SetPrivateDataInterface` holds a reference until the entry is replaced (by bytes or another interface), - removed or the object is destroyed; `GetPrivateData` returns the pointer with a reference added. A null - interface releases the one held and stays as a pointer-sized entry that reads back as null. - - A buffer too small for the entry gets `DXGI_ERROR_MORE_DATA`, nothing copied and no reference added, and - `*pDataSize` set to the size needed; a missing entry is `DXGI_ERROR_NOT_FOUND` with `*pDataSize` 0; a null - `pDataSize` is `E_INVALIDARG`. - - `SetPrivateData` with null data removes the entry whatever the size: `S_OK` when there was one, `S_FALSE` when - there wasn't. Zero bytes with data keep an empty entry (`S_OK`, size 0). - - `SetName` is `SetPrivateData` with `WKPDID_D3DDebugObjectNameW` (`{4cca5fd8-921f-42c8-8566-70caf2a9b741}`) and - the name with its terminator, as D3D12 documents: `GetPrivateData` reads it back, an empty name is a 2-byte - entry, and the narrow `WKPDID_D3DDebugObjectName` is not touched. A null name, which the host runtime faults on, - changes nothing (`E_INVALIDARG`). Before #2533 the layer stored the name under a mistyped GUID. - Names are not forwarded to `vkSetDebugUtilsObjectNameEXT` yet: one D3D12 object may own several Vulkan objects. - -## 5. Producing the shader contract - -The table below is the contract from [design.md](design.md#translator-status-and-runtime-contract) and where the -runtime gets each piece. The shader side is already proven by `runtime/test/vk_texture_test.cpp` and the compute, -store, load, mesh, geometry and BVH tests; this layer is the other half. - -| Contract | Runtime source | -|---|---| -| `s0..s31` user data | Root signature state at draw/dispatch: root constants copied, root CBV/SRV/UAV addresses and descriptor-table base addresses as 64-bit console VAs. Mapping per section 3.5; absent parameters zero. | -| `heap_base` (dwords 32–33) | The arena's `vkGetBufferDeviceAddress`. One value per command buffer; updated only if the arena is recreated. | -| `code_base` (dwords 34–35) | The console VA of the current shader's FSSM blob in the arena. Per-stage conflict: see below. | -| Descriptor hash table (set 0, binding 2) | `uint mask` + entries of `key[8], index, pad`; FNV-1a over the 8 key dwords; linear probe up to 8; miss = index 0. Implemented in `runtime/src/descriptor_table.h` (`DescriptorTable`). The layer inserts every T#/S# it sees and keeps a fallback image/sampler at index 0. | -| Bindless images (bindings 0, 3, 5, 6) | 2D, 2D-array/cube, 1D, 3D sampled-image arrays; one `VkImageView` per distinct T#. Cube textures are 6-layer 2D arrays and cube arrays 6N-layer ones, as the translator expects. | -| Samplers (binding 1) | One `VkSampler` per distinct S#; literal S# values from shader constants are pre-registered. | -| Storage images (bindings 4, 7, 8–19) | r32ui/float/sint views by dimension and numeric class; the layer binds each storage image into the float/uint/sint arrays of its dimension (the translator picks by the T# format at run time), with all three arrays as the safe default. | -| Buffer/image binding | Descriptors contain console VAs, never host BDAs. Buffers are in the arena at their VA; images are keyed by T# through the hash table. | -| Vertex fetch | PSO input layout + ISG1 signature; location = D3D input register; format from `DXGI_FORMAT`; instance step rate from the layout. The fetch subroutine is already replaced by Vulkan inputs. | -| PS system inputs | `FragCoord` (xy/z/w), `FrontFacing`, barycentrics; enable `fragmentShaderBarycentric` and `fragmentShaderPixelInterlock` when the index entry asks. | -| Mesh/geometry stages | `VK_EXT_mesh_shader`; the index's max vertices/primitives size the SPIR-V output arrays and are checked against the device's mesh properties; geometry stage for the 195 voxelize shaders; `DispatchMesh` → `vkCmdDrawMeshTasksEXT`. | -| POPS collision | The runtime puts 0 (no collision, bit 31 clear) in the POPS collision SGPR; the translator uses fragment-shader interlock for ordering. **Open:** the exact SGPR location is a translator/driver detail not named in the current contract. | -| Wave size | The PSO asks for the size the shader was translated for (`requiredSubgroupSize` 64 or 32, section 3.2 "Subgroup size") where the stage is in `requiredSubgroupSizeStages`; a shader translated with `--wave64-emulate` asks for nothing. A size the device cannot give is named in the log. | -| Code-embedded data | The whole FSSM blob is in the arena; `s_getpc_b64` becomes `code_base + next-instruction offset`. | - -### 5.1 Descriptor hash table details - -The exact layout the shader reads (from `tools/rdna2spirv.py`, `desc_lookup`): - -``` -uint32 mask; // slot count - 1 -struct entry { // 10 uints = 40 bytes - uint32 key[8]; // T#: 8 dwords; S#: 4 dwords then 0xFFFFFFFF x4 - uint32 index; // bindless index - uint32 pad; // unused by the shader -} entries[mask + 1]; -``` - -- Hash: FNV-1a over the eight key dwords as dwords (not bytes): `h = 2166136261; h = (h ^ key[i]) * 16777619`. -- Probe: `slot = (h + k) & mask` for `k = 0..7`; the first entry whose eight key dwords match yields its - `index`; no match yields 0. -- The layer must keep the table sparse enough that no live key needs more than eight probes. When all eight slots are occupied, - the runtime tries to move one resident to the next empty slot within that resident's own probe window. - A relocation requires an idle flush because it overwrites a live slot. Grow when this fails or when the next - insertion would exceed 50% load. Update binding 2 after - the rebuild, at a point where no in-flight command buffer reads the old table. -- Insert on `CreateShaderResourceView`, `CreateUnorderedAccessView`, `CreateSampler`, `CopyDescriptors` and heap - scans. A duplicate key updates the index in place. -- Index 0 is the fallback: a 1×1 texture and a default sampler (and a valid dummy storage image for the storage - arrays). The translator returns 0 on a miss, so index 0 must always be valid. -- The table buffer is a normal storage buffer, not part of the arena. It can be host-visible and updated directly - (host-coherent, or flushed before submit); if the game is sensitive to PCIe traffic, stage it like any other - upload. The shader only reads it. -- Inserts can come from several threads (view creation is often parallel). Serialise them with a mutex, or stage - per-thread and merge at submit. The shader only reads the table, and D3D12 already forbids modifying a descriptor - that an in-flight command list is using, so the same rule applies. - -**Measured (D3D-56, `runtime/test/vk_descriptor_bench.cpp`).** Measured on an NVIDIA GeForce RTX 5080 (discrete, `0x10de:0x2c02`, subgroup 32, driver `NVIDIA 621.24`, Vulkan 1.4.357), Windows 11 Pro 26H2 (build 26300), revision `ec8ec4c9`, using 64-bit Vulkan GPU timestamps (`1.000 ns` period) against `leonida::DescriptorTable` (90% T# / 10% S#) with the exact `tools/rdna2spirv.py` `desc_probe` loop. Unless noted, dispatches run `4096 x 64` invocations x `64` iterations (`16.78M` single / `33.55M` T#+S# pair lookups); wave-uniform sweeps use `group_stride = iters` (`64`), `lane_stride = 0` so all distinct entries are visited (at 100k: `90,000` T#, `10,000` S#, `100,000` T#+S# pairs, `131,072` miss keys; `uniform_hot_tsharp` repeats `1` key and measures `2.6–4.4 us/1M` in `device_local`). This run includes `bc8e604`'s bounded slot relocation, so its 100k row is at the same `524,288`-slot geometry as the AMD RDNA3/RDNA4 tables below and directly comparable to them, and it refreshes an earlier pre-relocation RTX 5080 table. `device_local` and `host_device_local` are the median of 4 processes, `host_visible` one; every row is `timing_status=ok` with no dispatch auto-scaling: - -| Entries (cap / load / bytes / mean probes) | Placement | `uniform_tsharp_hit` (us/1M, Glk/s) | `uniform_pair_ts` (us/1M, Glk/s) | `divergent_tsharp_hit` (us/1M, Glk/s) | `divergent_pair_ts` (us/1M, Glk/s) | `divergent_miss` (us/1M, Glk/s) | -|---|---|---|---|---|---|---| -| 1k (4,096 / 24.4% / 160 KiB / 1.316; 900 T#, 1k pair, 1,024 miss) | `device_local` | 3.322 (301.06) | 2.917 (342.84) | 24.008 (41.65) | 23.759 (42.09) | 96.175 (10.40) | -| 1k | `host_device_local` `host_visible` | 3.317 (301.49) 4.890 (204.48) | 2.918 (342.73) 3.583 (279.10) | 23.973 (41.71) 27.582 (36.26) | 23.732 (42.14) 26.426 (37.84) | 96.148 (10.40) 395.433 (2.53) | -| 10k (65,536 / 15.3% / 2.50 MiB / 1.310; 9k T#, 10k pair, 16,384 miss) | `device_local` | 12.842 (77.87) | 5.142 (194.49) | 38.202 (26.18) | 39.618 (25.24) | 206.654 (4.84) | -| 10k | `host_device_local` `host_visible` | 12.838 (77.89) 211.889 (4.72) | 5.166 (193.59) 16.257 (61.51) | 38.223 (26.16) 10261.465 (0.10) | 39.468 (25.34) 3334.286 (0.30) | 209.528 (4.77) 181717.455 (0.01) | -| 100k (524,288 / 19.1% / 20.00 MiB / 1.416; 90k T#, 100k pair, 131,072 miss) | `device_local` | 6.007 (166.47) | 7.159 (139.69) | 71.939 (13.90) | 47.306 (21.14) | 483.346 (2.07) | -| 100k | `host_device_local` `host_visible` | 6.025 (165.97) 213.404 (4.69) | 7.161 (139.64) 183.383 (5.45) | 71.895 (13.91) 15149.069 (0.07) | 47.277 (21.15) 16289.665 (0.06) | 482.358 (2.07) 205561.481 (0.00) | - -Three consequences for the runtime and table layout (additional GPU measurements follow, including AMD RDNA3): - -1. **In `DEVICE_LOCAL` VRAM, the hash probe itself is cheap at all three sizes:** wave-uniform full-table sweeps (`uniform_tsharp_hit`) run at `3.3–12.8 us / 1M`, divergent lookups at `24.0–71.9 us / 1M`, and the 8-probe miss at `96–483 us / 1M`. -2. **`BindlessSet::create()` currently allocates PCIe `HOST_VISIBLE | HOST_COHERENT` system memory (`runtime/src/vulkan_bindless.h`):** once working sets exceed cache at 10k–100k entries, `host_visible` slows `uniform_tsharp_hit` by **16.5x–35.5x**, divergent T# hits by **210x–269x**, and 8-probe misses by **425x–879x** (`181,717 us / 1M` at 10k, `205,561` at 100k). `host_device_local` (ReBAR `DEVICE_LOCAL | HOST_VISIBLE | HOST_COHERENT`) matches `device_local` within **1.4%** on every row here (largest delta 10k `divergent_miss`, `+1.4%`). Staging binding 2 to `DEVICE_LOCAL` (or preferring `DEVICE_LOCAL | HOST_VISIBLE` when small) avoids this cliff without touching the shader contract. -3. **`bc8e604`'s bounded slot relocation keeps the table dense:** 100k settles at `524,288` slots (`19.07%` load, `20.00 MiB`, `max_probes=8`) instead of doubling to `2,097,152` on a 9-probe collision, so the large-table cost is bounded by the 8-probe window; the dominant divergent cost is the 8-probe miss (`483 us / 1M` at 100k). - -Raw CSV rows (297, 9 processes): [D3D-56 RTX 5080 report](https://github.com/ItsNotRexed/Leonida/issues/313#issuecomment-7084711283). - -**Measured (D3D-56, AMD RDNA3).** The same benchmark and 64-bit timestamps on an AMD Radeon RX 7900 XTX (discrete, `0x1002:0x744c`, subgroup 64, driver `AMD proprietary 26.10.1 (LLPC)`, Vulkan 1.4.359), Windows 11 build 26200, revision `2aed144`. Dispatches, iterations and reps match the NVIDIA run above, but the table code does not: this revision includes `bc8e604`'s bounded slot relocation, so at 100k it settles at `524,288` slots (`20.00 MiB`, `19.07%` load, `max_probes=8`), the same geometry as the refreshed RTX 5080 table above. The two tables now describe the same `DescriptorTable` code and their 100k rows are comparable; the remaining caveat is subgroup size (AMD `64` vs NVIDIA `32`). - -| Entries (cap / load / bytes / mean probes) | Placement | `uniform_tsharp_hit` (us/1M, Glk/s) | `uniform_pair_ts` (us/1M, Glk/s) | `divergent_tsharp_hit` (us/1M, Glk/s) | `divergent_pair_ts` (us/1M, Glk/s) | `divergent_miss` (us/1M, Glk/s) | -|---|---|---|---|---|---|---| -| 1k (4,096 / 24.4% / 160 KiB / 1.316) | `device_local` | 6.220 (160.76) | 5.705 (175.27) | 15.285 (65.42) | 14.051 (71.17) | 50.461 (19.82) | -| 1k | `host_device_local` `host_visible` | 8.783 (113.85) 9.508 (105.17) | 5.360 (186.58) 5.783 (172.93) | 15.380 (65.02) 15.869 (63.02) | 13.974 (71.56) 13.465 (74.27) | 49.765 (20.09) 51.978 (19.24) | -| 10k (65,536 / 15.3% / 2.50 MiB / 1.310) | `device_local` | 5.152 (194.09) | 4.880 (204.90) | 27.998 (35.72) | 20.506 (48.77) | 146.217 (6.84) | -| 10k | `host_device_local` `host_visible` | 5.066 (197.38) 7.536 (132.69) | 4.841 (206.57) 6.236 (160.36) | 28.322 (35.31) 72.932 (13.71) | 20.641 (48.45) 54.183 (18.46) | 144.532 (6.92) 334.096 (2.99) | -| 100k (524,288 / 19.1% / 20.00 MiB / 1.416) | `device_local` | 7.618 (131.28) | 6.005 (166.54) | 53.558 (18.67) | 54.927 (18.21) | 290.279 (3.45) | -| 100k | `host_device_local` `host_visible` | 7.660 (130.54) 47.905 (20.87) | 6.040 (165.55) 29.887 (33.46) | 53.983 (18.52) 3492.770 (0.29) | 54.804 (18.25) 2240.356 (0.45) | 292.561 (3.42) 32108.853 (0.03) | - -On this GPU: - -1. **`device_local` is stable and cheap at every size.** Wave-uniform sweeps run `4.9–7.6 us / 1M` (the 100k `uniform_tsharp_hit` is `7.618`), divergent lookups `14.1–54.9 us / 1M`, and the 8-probe miss `50.5–290.3 us / 1M`. Repeating the 10k measurement keeps `divergent_miss` at `141–143 us / 1M` net, so this column is not noise. -2. **`host_visible` falls off a cliff at 100k, and is unreliable below it.** At 100k it is `5.0x–6.3x` slower than `device_local` on wave-uniform sweeps, `41x–65x` on divergent hits and pairs, and `111x` on 8-probe misses. At 10k the same rows varied by up to 6x between runs (`divergent_miss` net `147–845 us / 1M` over five runs), so the 10k host row above is one representative run; the uniform rows moved much less (`6.1–8.7 us / 1M`). The conclusion does not change: `device_local` is stable, `host_visible` is not. -3. **`host_device_local` (ReBAR) is a safe fallback on AMD.** It is within 1% of `device_local` at 100k and within 2% at 10k; at 1k it is within 1.5% on the divergent and miss rows, `uniform_pair_ts` is 6% faster (`5.36` vs `5.71 us / 1M`) and `uniform_tsharp_hit` is 41% slower (`8.78` vs `6.22 us / 1M`). The `DEVICE_LOCAL | HOST_VISIBLE` allocation succeeds and runs here; it is not guaranteed on every Windows driver. -4. **At the shared `524,288`/8-probe geometry, the 100k rows are comparable across the tables.** The RX 7900 XTX `divergent_miss` (`290 us / 1M`) is below the refreshed RTX 5080 (`483`), with the RX 9070 XT (RDNA4) between at `422` ([#313](https://github.com/ItsNotRexed/Leonida/issues/313)); the RX 7900 XTX is also faster on 100k divergent T# hits (`54` vs `72`) but slower on wave-uniform sweeps (`7.6` vs `6.0 us / 1M`). The subgroup size differs (AMD `64`, NVIDIA `32`), so this is a device-plus-subgroup comparison, not a pure microarchitecture one. - -Raw CSV rows: [D3D-56 report](https://github.com/ItsNotRexed/Leonida/issues/313#issuecomment-7074181793), addendum with the repeatability runs: [same issue](https://github.com/ItsNotRexed/Leonida/issues/313#issuecomment-7074220711). - -**Measured (D3D-56, Intel integrated + RTX 5070 Ti Laptop).** These synthetic runs use `vk_descriptor_bench` from revision `f85582e`, Windows 11 Pro Insider Preview `10.0.29704`, MSVC 19.51, Vulkan SDK 1.4.363.0, and the exact `4096 x 64` invocations x `64` iterations (`16.78M` single / `33.55M` T#+S# pair lookups, median of 25 reps). NVIDIA runs used `--sizes 1000,1000,10000,100000 --warmup 200`; the Intel run additionally duplicated 100k (`--sizes 1000,1000,10000,100000,100000 --warmup 200`). The first 1k block is excluded because its `baseline_uniform` timing differed from the duplicate (Intel device-local: `0.771 ms` vs `0.594 ms`; NVIDIA device-local: `0.0555 ms` vs `0.0765 ms`). For Intel 100k, the second block is retained after the duplicate confirmed stable timing per allocation. Retained rows were not auto-scaled. Intel's device-local and host-visible placements ran together on the integrated GPU. NVIDIA device-local and ReBAR were measured in separate processes. The RTX 5070 Ti Laptop is `0x10de:0x2f58` (driver `621.01`, Vulkan `1.4.357`); Intel Graphics is `0x8086:0x7d67` (driver `32.0.101.8132`, Vulkan `1.4.325`). - -| GPU / entries (cap / load / bytes / mean probes) | Placement | `uniform_tsharp_hit` (us/1M, Glk/s) | `uniform_pair_ts` (us/1M, Glk/s) | `divergent_tsharp_hit` (us/1M, Glk/s) | `divergent_pair_ts` (us/1M, Glk/s) | `divergent_miss` (us/1M, Glk/s) | -|---|---|---|---|---|---|---| -| Intel iGPU, 1k (4,096 / 24.4% / 160 KiB / 1.316) | `device_local` | 85.669 (11.67) | 76.483 (13.07) | 468.524 (2.13) | 431.528 (2.32) | 1,735.402 (0.58) | -| Intel iGPU, 1k | `host_visible` | 85.356 (11.72) | 76.500 (13.07) | 468.750 (2.13) | 425.419 (2.35) | 1,741.669 (0.57) | -| Intel iGPU, 10k (65,536 / 15.3% / 2.50 MiB / 1.310) | `device_local` | 86.806 (11.52) | 76.642 (13.05) | 597.170 (1.67) | 507.250 (1.97) | 2,495.724 (0.40) | -| Intel iGPU, 10k | `host_visible` | 87.665 (11.41) | 76.415 (13.09) | 597.099 (1.67) | 506.874 (1.97) | 2,496.882 (0.40) | -| Intel iGPU, 100k (524,288 / 19.1% / 20.00 MiB / 1.416) | `device_local` | 101.132 (9.89) | 84.286 (11.86) | 672.021 (1.49) | 964.268 (1.04) | 5,580.289 (0.18) | -| Intel iGPU, 100k | `host_visible` | 100.269 (9.97) | 84.437 (11.84) | 668.788 (1.50) | 975.549 (1.02) | 5,581.019 (0.18) | -| RTX 5070 Ti Laptop, 1k (4,096 / 24.4% / 160 KiB / 1.316) | `device_local` | 11.028 (90.68) | 9.652 (103.60) | 48.388 (20.67) | 48.201 (20.75) | 195.543 (5.11) | -| RTX 5070 Ti Laptop, 1k | `host_device_local` (ReBAR) | 11.072 (90.32) | 9.682 (103.29) | 51.245 (19.51) | 48.427 (20.65) | 194.840 (5.13) | -| RTX 5070 Ti Laptop, 10k (65,536 / 15.3% / 2.50 MiB / 1.310) | `device_local` | 11.562 (86.49) | 10.164 (98.38) | 63.725 (15.69) | 66.871 (14.95) | 367.062 (2.72) | -| RTX 5070 Ti Laptop, 10k | `host_device_local` (ReBAR) | 11.494 (87.00) | 10.184 (98.19) | 63.858 (15.66) | 66.909 (14.95) | 297.104 (3.37) | -| RTX 5070 Ti Laptop, 100k (524,288 / 19.1% / 20.00 MiB / 1.416) | `device_local` | 11.993 (83.38) | 46.172 (21.66) | 116.020 (8.62) | 82.513 (12.12) | 788.086 (1.27) | -| RTX 5070 Ti Laptop, 100k | `host_device_local` (ReBAR) | 9.186 (108.86) | 46.162 (21.66) | 99.737 (10.03) | 141.439 (7.07) | 632.504 (1.58) | - -On these devices: - -1. **The Intel placements are close on the lookup workloads.** Gross dispatch times for `device_local` and `host_visible` track within 1.5%; after subtracting `baseline_uniform`, differences are within 1.7% through 10k and within 11.2% on 100k uniform hits. At 100k, the baseline itself is repeatable per allocation but differs between them (`0.730 ms` device-local vs `0.608 ms` host-visible), so the net uniform rows carry more uncertainty. Both allocations use the iGPU's shared system memory; this does not predict discrete-GPU PCIe behavior. -2. **NVIDIA ReBAR is close to device-local for uniform sweeps at 1k–10k and at 100k T#+S# pairs.** The 100k divergent and miss cases differ by workload (ReBAR is not uniformly faster or slower), so this run does not support a blanket placement ranking. -3. **The NVIDIA host-visible run is omitted.** A separate full run returned `vkWaitForFences -> -4` while measuring the 10k host-visible cases; those partial timings are not reported. A safer capped profile is needed before drawing conclusions about PCIe system-memory lookup on this laptop. - -The run is synthetic and contains no game data. Raw retained rows and the corrected methodology are recorded in [the D3D-56 report on issue #313](https://github.com/ItsNotRexed/Leonida/issues/313#issuecomment-7078191651). - -### 5.2 Per-stage code base - -The current 144-byte block has one 64-bit code base at dwords 34–35. A graphics pipeline has at least a vertex and -a pixel shader, and each may use `s_getpc_b64` for its own constant table. One block cannot hold two different -code bases at the same offset. The pipeline layout declares the block for every stage that may read it (or for all -graphics stages), and `vkCmdPushConstants` is called with those stage bits. This is a real gap in the current -contract, not a runtime bug: - -- Only 155 shaders use code-embedded data, and a graphics pipeline has at least two stages (typically VS+PS, or - MS+PS). If only one stage in a pipeline uses it, the layer can set that stage's code base; the other stage never - reads it. This probably covers the first boot. **ASSUMPTION.** -- If both stages use it, the layer cannot satisfy both with the current contract. The clean fix is a translator - change: give each stage its own code-base slot (for example dwords 34–35 VS, 36–37 PS, 38–39 CS, 40–41 GS/MS, - extending the block to 168 bytes) and have each compiled shader read its stage's slot. A 168-byte push-constant - block is still under the 256-byte limit of common desktop GPUs, but above Vulkan's 128-byte minimum; the device - requirement must be checked. -- A second option is a per-stage uniform/storage buffer for the code base, patched in at pipeline creation. That - adds a descriptor binding and a load per `s_getpc`, but avoids growing push constants. Decide after measuring - how many real PSOs have two code-base stages. - -Measured per stage (all 26,503, `tools/feature_scan.py`): `s_getpc_b64` is kept to read code-embedded data in 54 -VS, 93 PS, 266 MS and 263 CS (0 GS); the 147 VS/PS match the translator's own note. Both stages of a VS+PS or -MS+PS pipeline can therefore need a code base. - -**Measured:** across the GPU test fleet (Issue #166), desktop NVIDIA (Turing, Ampere, Ada, Blackwell: 256 bytes), desktop AMD (RDNA2: 256 bytes) and Apple Silicon (MoltenVK: 4096 bytes) all satisfy the 144-byte contract natively (`maxPushConstantsSize >= 144`). Intel Arc is not uniform: the earlier fleet entries report the 128-byte specification minimum (`maxPushConstantsSize == 128`) for Arc, but an Arc B580 (Battlemage) on Windows 11, driver 32.0.101.9175, reports 256 bytes (#166, @rtrexmass), so there D3D-14's fallback never engages. The 128 figure may be specific to another OS or driver (Mesa ANV on Linux is the guess; no Arc run on Linux that records the OS is cited here, and an ANV result would settle it). So does an integrated AMD RDNA2 GPU, a Radeon 680M on the Windows driver 22.40.84.06, so the minimum is not Intel-only. That figure follows the driver as well: a Radeon 610M reports 128 on 24.10.16.14 and 256 on 26.11.2 (#166). 128 bytes cannot fit the 16-byte tail (dwords 32–35: heap base and code base) inside push constants. The runtime detects `maxPushConstantsSize < 144` at device creation (`d3d12_vulkan_device.cpp`) and flags `push_constants_need_fallback` for the uniform-buffer fallback. -**Open:** the exact count of such PSOs (the pairing is in the executable), and the minimum `maxPushConstantsSize` across target GPUs. If a GPU only -supports 128 bytes, the current 144-byte contract already fails; the layer needs a fallback (uniform buffer for the -tail) regardless. - -At run time, `CreateGraphicsPipelineState` refuses a pair where both stages read their code base, with a log, so -the first boot measures the pair count. A device whose `maxPushConstantsSize` is below 144 has every PSO refused, -with the limit in the log, until the uniform-buffer tail exists. - -### 5.3 Descriptor T#/S# parsing - -The runtime needs a C++ decoder for the structures the shaders read. The fields it needs: - -- **T# (image SRV):** base console VA, format (GFX10 format code), width/height/depth, mip levels, array layers, - sample count, destination swizzle, dimension. The format table is `tools/gfx10_formats.json` (Mesa's - `gfx10-rsrc.json`), the same one the translator uses. -- **S# (sampler):** filter modes, address modes (U/V/W), border color, min/max LOD, LOD bias, compare function, - anisotropy, coordinate normalization. -- **V# (buffer):** base console VA, stride, record count, format, destination swizzle. Buffer descriptors are - dereferenced directly by the shader; the layer only needs to validate the VA and the format for typed loads. - -If the game calls `CreateShaderResourceView`/`CreateSampler`, the layer can encode these structures itself from -the D3D12 descriptors. If the game writes them, the layer decodes them. Both paths meet in the same parser. The -GPU texture test already proves the shader-side contract on a synthetic T#/S#; the runtime parser is new code. - -## 6. Boot milestones - -Each milestone is a capability gate with a synthetic test; the game is the integration test once it is available. -M0–M2 do not need the executable. - -| # | Scope | What it proves | Done when | -|---|---|---|---| -| **M0** | `D3D12XboxCreateDevice` and the measured device overrides (heap start handles in RAX), one direct queue, allocator/list, fence, fake DXGI factory/adapter/output, `ALLOW_DISPLAY` back buffers, frame events + `PresentX` (DXGI swapchain only if the game creates one), clear + present | COM interception, the known Xbox device entry point and ABI overrides, presentation (`PresentX` + frame events, or swapchain), frame loop, clean shutdown | A window shows a stable clear colour for 60 frames, no Vulkan validation errors, every D3D12 call traced. **Synthetic part met** by `d3d12_present_test`: 60 frames through the proxy on Vulkan, validation clean, colour checked in the presented images and on screen where GDI can read it. Still open: the game's present front end (frame events + `PresentX`, or a DXGI swapchain) and the per-call trace | -| **M1** | Root signature with root constants (mask the measured `0x03000000` flag byte on a copy), one translated VS+PS, PSO, vertex buffer in the arena, draw, push constants `s0..s31` + heap base | PSO translation, shader hash lookup, vertex input, root-constant packing, heap base, present | The triangle matches a CPU/GPU reference; the existing texture-test style comparison passes with error 0. **Met with stand-in shaders** by `d3d12_draw_test`: every pixel of two indexed draws and a culled triangle matches, through the proxy, validation clean. With translated game shaders most of them declare bindings, which M2 (pipelines bind set 0) lets through. **M1.5 (D3D-53) met with translator output** by `d3d12_translated_draw_test`: see below | -| **M1.5** | The same, with real translator output: hand-written RDNA2 VS+PS, PSO found by FSSM hash, vertex fetch through a V# loaded from the user-data table, a root constant, a table in the arena, the code base | The push-constant, vertex-fetch and code-base contracts on translated code | Met by `d3d12_translated_draw_test`: three draws, every pixel off the triangle's edge exact in a float target, validation clean on the AMD Radeon 880M and the RTX 5070 Laptop. An upload buffer behind a V# is not supported (section 3.3) | -| **M2** | Descriptor heap (heap slots 9/10 return in RAX), `CreateShaderResourceView`, sampler, root descriptor table, hash-table insert, bindless sampling | The full D3D12 descriptor path and the shader's T#/S# contract | A textured quad matches the synthetic 8×8 gradient or a known texture with error 0; the hash table has the expected entries. **Synthetic part met** by `d3d12_m2_textured_test`: through the proxy, D3D12 API only, a shader-visible CBV/SRV/UAV heap and a sampler heap (start handles from slots 9/10), two 8×8 textures uploaded with `Map` + `CopyTextureRegion`, `CreateShaderResourceView` and a POINT `CreateSampler`, a root signature of two descriptor tables, `SetDescriptorHeaps`, `SetGraphicsRootDescriptorTable` and `DrawIndexedInstanced` of a quad whose PS is translator output (`ps_m2.asm`: `s_load` of the T# and the S# from the tables, `image_sample`). Every one of the 4096 pixels matches the CPU-computed gradient (left half) and its point reflection (right half, second table) with error 0, and the hash table holds a distinct non-zero index for each of the two T#s and the S# and none for bytes nothing created; validation clean on the AMD Radeon 880M and the RTX 5070 Laptop. The layer change it needed: pipelines whose shader declares set-0 bindings (graphics and compute) were refused; their layout now holds the device's bindless set 0 and replay binds it at every draw and dispatch. Still open: shaders of the game itself (direct heap indexing, unbounded tables, static samplers, descriptors the game writes itself), no host D3D12/WARP byte comparison (the reference is computed on the CPU). Formats, mips and arrays through a PSO: `d3d12_m2_formats_test` samples an 8×8 BC1 and an 8×8 BC7 texture with 4 mips each and an R8G8B8A8 2D array of 3 slices through the same path (every subresource uploaded at its `GetCopyableFootprints` layout, POINT samplers with `MinLOD = MaxLOD` pinning each level, a view from mip 1, two array views read by `ps_m2_array.asm`); all 12 cases match the CPU with error 0, validation clean on the RTX 4070 Ti SUPER, with no layer change needed | -| **M3** | Depth/stencil, multiple render targets, resource barriers, render passes, occlusion queries, fences, 2–3 frames in flight; run the game's first frames | Real frame structure and the first game code | The game reaches its first rendered frame (loading screen/menu or whatever the executable does) or stops on a single unsupported call with a clean report. **Synthetic part met** by `d3d12_m3_frame_test`: through the proxy, D3D12 API only, six frames through a ring of three slots (three frames in flight; each slot has its own allocator, list, targets, depth buffer, query and fence, and a frame waits with `SetEventOnCompletion` + an event for the fence its slot signalled three frames earlier before reading back and recording the slot again). Pass 1 draws three rectangles from root constants with translator-output shaders (`vs_m3.asm`, `ps_m3.asm`, hand-written RDNA2) through `OMSetRenderTargets` into two render targets (R8G8B8A8_UNORM and R32_FLOAT) and a `D24_UNORM_S8_UINT` depth/stencil buffer (the layer substitutes D32_SFLOAT_S8_UINT on the Radeon; the RTX has it natively): depth LESS with write, stencil REPLACE with references 1 and 2, then a draw with no depth test whose stencil test is EQUAL; before the far rectangle, a single-output probe (`ps_m3_query.asm`) uses the same depth/stencil tests with color, depth and stencil writes disabled, inside `BeginQuery`/`EndQuery(OCCLUSION)`, and `ResolveQueryData` writes its sample count to a readback buffer. The actual far-rectangle draw still writes both render targets with depth/stencil writes enabled. Resource barriers move the first target RENDER_TARGET → PIXEL_SHADER_RESOURCE\|COPY_SOURCE and the second to COPY_SOURCE (and back at the next frame, from resources created in those states). Pass 2 samples the first target through an SRV in a descriptor table (the M2 path) with `ps_m3_post.asm` into a third target. Every pixel of all three targets (the float one bit for bit) matches the CPU reference with error 0 in each of the six frames, and the single-output probe's occlusion count equals the exact visible area of the far rectangle in each frame (3555 samples over the six frames). The original version was validation clean (including synchronization validation) on the AMD Radeon 880M and the RTX 5070 Laptop; current probe/isolation results are recorded below. @whattheflop's run on #1584 (GeForce RTX 3080 and a Ryzen 7 9800X3D Radeon iGPU) sampled the fences with nonblocking reads after each submit and saw 1, 2, 3, 1, 2, 3 slots still incomplete on NVIDIA and 1, 1, 1, 1, 1, 1 on AMD: up to three slots in flight on NVIDIA, one on AMD (sampled fence completion; GPU execution overlap was not measured). **Still open for M3:** render passes (`BeginRenderPass`, D3D-27) are not exercised, nor `BINARY_OCCLUSION`, occlusion during pipeline statistics (D3D-162), MSAA or depth/stencil copies and read-only DSV states in this test; the game's own first frames need the executable | -| **M4** | Compute PSOs, UAVs, storage images, indirect dispatch, copy queues, async streaming | Asset loading and GPU compute | The world's streaming path runs without device loss; compute results match a CPU/reference check. **Synthetic part met** by `d3d12_m4_compute_test`: through the proxy, D3D12 API only, with translator-output compute shaders (`cs_m4_fill.asm` and `cs_m4_indirect.asm`, hand-written RDNA2). A COPY queue streams an input buffer in (`CopyBufferRegion` from an UPLOAD buffer into a DEFAULT buffer created in COMMON), `Signal`; a COMPUTE queue `Wait`s on it and runs one list: a compute root signature (four root constants and a descriptor table of five UAVs: a structured buffer, three raw buffers and an `R32_UINT` `RWTexture2D`), a compute PSO and `Dispatch` (256 threads) that fills the structured buffer and the image from the input and writes the arguments of the next dispatch into a raw buffer; barriers (the argument buffer to `INDIRECT_ARGUMENT`, UAV barriers on the buffer and the image); `ExecuteIndirect` with a dispatch command signature running a second PSO for the 3 groups the first dispatch asked for, which reads the buffer and the image back (`image_load`) and writes a raw output; then everything to COMMON and `Signal`. A COPY queue `Wait`s on that fence, copies the five results (the image through `CopyTextureRegion`) to a readback buffer, and the CPU waits with `SetEventOnCompletion`. Each D3D12 queue has its own `VkQueue` where the family has two (both test GPUs); all 1,924 result words match the CPU reference with error 0; validation (with synchronization validation) clean on the AMD Radeon 880M and the RTX 5070 Laptop. Layer gaps this test found, closed with it: buffer UAVs (structured and raw) were not written (`CreateUnorderedAccessView` stubbed them, now a V# in the slot); `ExecuteIndirect` of a dispatch ran whatever pipeline and root arguments the command buffer had bound instead of the list's (now recorded with the command, as `Dispatch` does); an image created in `UNORDERED_ACCESS` and first used by a shader was zero-filled by the first barrier or copy that named it, losing the shader's writes (now moved to GENERAL, zeroed, by the first submission after its UAV view is created that is not on a copy queue and dispatches or draws; every other queue's next submission waits for that one); and a queue submitted before the queue whose fence it waits on, when a resource's layout is handed over between them (the layout tracker followed submission order, so a copy list was replayed against the layout from before the compute list ran and the run stopped on a validation error): such a batch is now held on the CPU until a Signal that satisfies its Wait has been submitted, and recorded in dependency order (section 4.4, "Wait before Signal across queues"; `d3d12_queue_handover_test`, every queue-type and submission order, exact against the host runtime). **Still open for M4:** the storage-image initialization is tied to the first shader-running submission, not to the list that uses the image, so a list that only reaches an image through a barrier or copy before any dispatch or draw is submitted still zero-fills it first (as before), and an image used by a shader only on a queue that never runs one of its own dispatches or draws first relies on another queue's submission; buffer SRVs and CBVs as V#s (typed buffer UAVs and UAV counters are done: `d3d12_buffer_uav_test`, section 3.4 "Buffer UAVs"), `ExecuteIndirect` signatures that change root arguments or use count buffers for dispatches, and async streaming itself and the world's streaming path, which need the game | -| **M5** | Mesh shaders, `ExecuteIndirect`, bindless-table pressure, multi-threaded command lists, pipeline cache | World rendering | A stable open-world frame at any frame rate; then profile and optimise | -| **M6** | Ray tracing/XDXR: standard AS builds or the shipped `XboxBvhBuilder` compute path; BVH node format; the builder's 52 console `FSSM` programs (51 pass `spirv-val`, one rule left: [embedded_shaders.md](embedded_shaders.md)) | RT shadows and any RT effects | RT output matches a reference; the builder's shaders run through the `FSSM` translator or a substitute; no unknown XDXR call remains | -| **M7** | HDR, VRS, `PresentX` planes (2-plane HDR + GameDVR compose, `ImmediateThresholdPercent`), resize, alt-tab, `SuspendX`/`ResumeX`, frame pacing and `GetFrameStatisticsX` | Presentation polish | HDR and resize work on the target display; no validation errors over a long run. **Partly met:** `ImmediateThresholdPercent` (late frame flipped at once through `VK_KHR/EXT_swapchain_maintenance1` IMMEDIATE/FIFO_RELAXED, section 4.5; checked on the fake-clock decision and on the Vulkan present mode, 0 VUIDs in our runs with `LEONIDA_VK_VALIDATION=1` on two GPUs, no tearing observed on a display; the console's real semantics are unmeasured). **Plane compose** (section 4.5): 1-2 planes scaled from a source rectangle to a destination placement, point or bilinear, plane 1 alpha-blended (premultiplied or straight), filtered and blended in linear light, SDR (sRGB or gamma 2.2) and HDR10 (PQ) planes converted to the swapchain, SDR white from Windows' setting when HDR10 is active (else 203 nits), checked against a CPU model on two GPUs with 0 VUIDs (exact for point filtering, within 1-2 levels for bilinear, alpha, tone map and PQ conversions); the layouts, flag values and alpha convention are ours, the console's plane semantics are unmeasured, and the public HDR sample's second plane is the GameDVR copy, not an overlay. HDR10 swapchain (ST.2084 surface): verified on an RTX 5080 with an HDR10 display by @JavierBlanco23 in #2069, not on AMD (our test displays list no ST.2084 surface); HDR10 on an SDR swapchain is tone mapped (identity below 0.8 of SDR white, Reinhard shoulder above, then clipped per channel). `SuspendX`/`ResumeX`, frame pacing and a minimal `GetFrameStatisticsX` exist; VRS, alt-tab, an AMD HDR10 display run are open | - -**M3 occlusion portability (D3D-209).** Vulkan's [occlusion query specification](https://registry.khronos.org/vulkan/specs/latest/html/vkspec.html#queries-occlusion) -permits a count multiplied by the number of written color outputs, even with `VK_QUERY_CONTROL_PRECISE_BIT`. -The original two-output query returned twice the CPU area on Intel UHD (Windows driver 31.0.101.4146), -while NVIDIA RTX 3050 6GB Laptop (617.14) returned the area itself. Synthetic direct Vulkan and native D3D12 -controls also returned 8192 on Intel for a 64×64 quad with two outputs, versus 4096 with one; -NVIDIA and D3D12 WARP returned 4096 in both cases. This does not establish duplicated replay commands. -The test now measures a single-output, write-free probe, keeping its exact CPU oracle and the original -MRT rendering and pixel checks. It does not divide application query results or change the runtime backend. - -`d3d12_m3_first_pass` runs the same executable with `--first-pass-only`: all six frames, MRT pixels, -depth/stencil, barriers, queries and slot fences are still checked, and the third target must stay clear. -It isolates post-pass pipeline creation and execution: it skips creating the post-process PSO and recording -the sampled draw. All five FSSM files and their shader-library entries, including `vs_m2` and `ps_m3_post`, -are still required at startup. The second-pass root signature and descriptor heaps are still created, -so missing post-pass shaders or failed descriptor setup still fail this mode. `d3d12_m3_frame` remains -the full test. The first-pass mode passes with validation on both GPUs above (3555 samples). The full test passes on NVIDIA; -on this older Intel driver it still fails validation because `ps_m3_post` declares `Int64` without -`shaderInt64` support. The full test continues to report that separate capability issue. - -### 6.1 Minimum API set for the first frame - -M0–M3's synthetic tests need only this subset. The game itself may need more as soon as its first frame does; -everything else can be absent or a clean failure: - -- `D3D12XboxCreateDevice` and `CheckFeatureSupport`; the measured device overrides (heap start handles in RAX; - slot 76 texture creation if the game uses it; slot 62, compute-PSO creation in the builder's ABI, is not needed - for the first frame); one direct queue, one allocator, one command list, one fence; -- DXGI factory/adapter/output enumeration; frame events and `PresentX` (or `GetBuffer`/`Present` if the game creates a swapchain); -- a root signature with root constants and one descriptor table, masking `0x03000000` on a copy; one VS+PS PSO and - an input layout; -- a shader-visible CBV/SRV/UAV heap and a sampler heap; `CreateShaderResourceView`, `CreateSampler`, - `SetDescriptorHeaps`, `SetGraphicsRootDescriptorTable`; -- one committed vertex/index buffer, one texture, upload through `Map`/`Unmap` or `WriteToSubresource`, - `CopyBufferToImage`; -- resource barriers, RTV/DSV, `OMSetRenderTargets`, `Clear*View`, `DrawIndexedInstanced`, `PresentX`/`Present`; -- the runtime side: descriptor hash table, bindless set 0, push constants (`s0..s31`, heap base, code base), - vertex input from the PSO layout. - -Not needed for the first frame: compute, mesh, geometry, ray tracing, VRS, PresentX plane compose, reserved/tiled resources, -heap aliasing, indirect draws, multiple queues, pipeline libraries. (`PresentX` itself is needed; only its plane compose, HDR and statistics are not.) - -**Why this order.** M0–M2 isolate the layer from the game: they exercise every contract piece with known data. -M3 is the first point where the game's own root signatures, PSOs and descriptors appear; expect the trace to -rewrite parts of section 3.5. M4/M5 are ordered by dependency: assets must stream before the world can draw, and -the corpus's 9,282 mesh shaders (and, very likely, indirect draws) are world-rendering features. M6 is last -because the game ships its own BVH builder; the layer may only need to run its compute work, not implement a full -DXR path. - -**First-boot minimum.** Strictly, the first boot needs M0–M3 plus whatever the game does before its first frame. -If the first frame is a loading screen with a simple UI draw, M3 may be enough; if it is the world, M5 is the real -minimum. The trace decides, not the milestone labels. - -## 7. Prior art and measured Xbox ABI - -A GPL-2.0-only fork of AnyPS5 (`americas-recomp`, branch `xbox-series`) recompiles the same GTA VI Xbox Series -shaders and has run the package's DLLs against a PC D3D12 device behind an Xbox-ABI proxy. Its measurements are -prior art for this design. The findings below are paraphrased; no code or long passages are copied. They were -verified there by running the package DLLs (`XS_TRACE=1`, per-slot hit counters) or by static import analysis, not -independently re-measured here. **Basis:** *static imports* means PE import-table analysis; *run* means the package -DLLs were executed against a PC D3D12 device through the Xbox-ABI proxy. - -Other Xbox Series compatibility-layer efforts have since measured overlapping parts of the same surface — running -the package's own console DLLs and shader pack, retail titles, or a console-compiler output. Their findings are -folded into the table below with the measurement basis noted per row; nothing is re-derived from their code. - -| Finding | Basis and link | Consequence for this design | -|---|---|---| -| Across the 16 package DLLs there are only 6 Xbox-specific static imports: `xmem.dll` → `XMemAlloc`, `XMemFree`, `XMemGetWorkingSetStatistics`, `XMemVirtualQuery`; `d3d12_xs.dll` → `D3D12SerializeVersionedRootSignature`, `D3D12CreateRootSignatureDeserializer`. Both `d3d12_xs` names exist with the same names in the PC `d3d12.dll`. The other 492 functions are standard Windows and 113 are shipped in the package. Argument shapes for the less common `xmem` calls come from caller disassembly; some attribute bits are inferred. | *Static imports* — [PLATFORM_SURFACE.md](https://github.com/realdody/americas-recomp/blob/xbox-series/docs/xbox/PLATFORM_SURFACE.md) | Confirms the middleware surface is tiny. The repo's `xmem` shim already covers all four; `d3d12_xs` still forwards only the two root-signature functions. The device/queue/command-list surface belongs to the executable. | -| `D3D12XboxCreateDevice(adapter, params, riid, out)` returns a PC `ID3D12Device` behind the Xbox-ABI proxy. The params struct is 24 words and is only logged; the signature comes from public documentation, not a header. | *Run* — [platform README](https://github.com/realdody/americas-recomp/blob/xbox-series/tools/xbox/platform/README.md), [PLATFORM_SURFACE.md](https://github.com/realdody/americas-recomp/blob/xbox-series/docs/xbox/PLATFORM_SURFACE.md) | Corrects "device entry point unknown": the entry point is named. The params/flag layout remains **Open**. Do not assume `D3D12CreateDevice`. | -| Xbox texture creation is device slot 76 (heap properties / heap flags / description / initial state / clear value / iid / out), not `CreateCommittedResource`. The description is 56 bytes plus extension words; its layout field is `0x101` (tiled) or `0x1` (row-major buffer), and the PC proxy forwards it to `CreateCommittedResource` slot 27 with a driver-chosen layout. The FidelityFX upscaler creates 10 default-heap resources this way. | *Run* — [PLATFORM_SURFACE.md](https://github.com/realdody/americas-recomp/blob/xbox-series/docs/xbox/PLATFORM_SURFACE.md) | Adds a required Xbox-specific device method and a non-public layout value. `0x101` must not be passed to the public layout enum; the tiled data layout/detile path remains **Open**. See section 4.2. | -| Device slot 14 is the public `CreateDescriptorHeap`; the returned heap is wrapped because `GetCPUDescriptorHandleForHeapStart` / `GetGPUDescriptorHandleForHeapStart` (heap slots 9/10) return the 8-byte handle in RAX on the Xbox build. The PC call returns it through a hidden pointer in RDX, so the proxy special-cases the return. | *Run* — [PLATFORM_SURFACE.md](https://github.com/realdody/americas-recomp/blob/xbox-series/docs/xbox/PLATFORM_SURFACE.md) | Adds a return-convention quirk to the descriptor-heap ABI. A generic IDL/sret thunk will corrupt the handle. See section 3.4. | -| Xbox root-signature descriptors carry flags `0x03000000`. The PC serializer rejects them with `E_INVALIDARG`; the proxy clears the high byte on a copy. The v1.0 `D3D12SerializeRootSignature` path keeps flags at +32, and `0x3000001` also fails on the PC runtime. | *Run* — [PLATFORM_SURFACE.md](https://github.com/realdody/americas-recomp/blob/xbox-series/docs/xbox/PLATFORM_SURFACE.md) | Narrows the root-signature reflection risk. Mask the high byte on a private copy; the meaning of the bits remains **Open**. See section 3.5. | -| The BVH builder's constructor creates 53 compute pipelines through device slot 62, called with a compute-PSO shape (a plain `D3D12_COMPUTE_PIPELINE_STATE_DESC`, two zero words, iid, out). On the PC interface the prior art forwards to, slot 62 is `CreateStateObject` (wrong arity), so the proxy overrides it. | *Run* — [PLATFORM_SURFACE.md](https://github.com/realdody/americas-recomp/blob/xbox-series/docs/xbox/PLATFORM_SURFACE.md) | Corrects the assumption that the whole device vtable is public order. Slot 62 must be compute-PSO creation for the builder, not a state object. Slots 1/15/18/19/27/38 did match the desktop order. | -| A reusable `xbox_device_proxy.h` forwards every slot to a PC object, counts hits per slot and logs first calls with `XS_TRACE=1`; the observed device slots include 1, 14, 15, 16, 18, 19, 27, 38, 62 and 76. Their `xgr` stand-in covers 48 of 398 methods; Xodus (LGPL-2.1) covers 152 of 396 via IDL-generated stubs. | *Run* — [platform README](https://github.com/realdody/americas-recomp/blob/xbox-series/tools/xbox/platform/README.md), [PLATFORM_SURFACE.md](https://github.com/realdody/americas-recomp/blob/xbox-series/docs/xbox/PLATFORM_SURFACE.md) | Confirms the trace-first approach and shows the long tail. We adopt the *method* (per-slot counters, first-call logging), not the code. | -| The BVH builder's 53 compute shaders are Xbox DXIL with `@xbox.*` intrinsics; 44 of 53 fail the PC D3D12 shader compiler, 22 have been lowered to standard DXIL and accepted as pipelines, and 31 use raw 64-bit GPU addresses. | *Run* — [PLATFORM_SURFACE.md](https://github.com/realdody/americas-recomp/blob/xbox-series/docs/xbox/PLATFORM_SURFACE.md) | A separate translation path from the FSSM RDNA2 corpus when measured on the **bitcode**. See section 4.8 and the paragraph below. Measured later on the console `XBCH` record of the same containers: 52 programs, 51 pass `spirv-val` through the FSSM translator ([embedded_shaders.md](embedded_shaders.md)). 52 programs, 42 pass `spirv-val` through the FSSM translator ([embedded_shaders.md](embedded_shaders.md)). | -| On the console's own shader compiler, compute user parameters go into user SGPRs `s4`… in root-signature order while each fits whole (root constant = 1 dword, root descriptor = 2, descriptor table = 1 dword holding the 32-bit address of its first descriptor); `s0`..`s3` are the driver's. From the first parameter that does not fit, it and all after it go into a packed array addressed by a 40-bit pointer in `s[0:1]` (constant 4 B, descriptor 8 B, no alignment). Thread-group ids follow the user SGPRs. | *Console-compiler output, sibling layer* | Narrows question 3 for the compute stage: the inline-from-`s4` model matches this repo's census (lowest CS pointer SGPR `s4`), and the spill target is named (the array at `s[0:1]`), not guessed. VS/PS/MS bases were not measured there; verify against the game's own signatures. | -| The command list's inline records: a `Dispatch` is `0x4002C400` followed by x, y, z (16 B); a 20-byte record `0x4003CC00` stands in for console slot 80; the pipeline record is a 28-byte copy of the PSO object's +0x10..+0x2B; a root parameter starts from the header word at list +0x344+4·i (the high half carries n−1 for a multi-constant write), then a descriptor is 12 B, one constant 8 B and n constants 4+4n B. | *Console-DLL run, sibling layer* | Supplies the record opcode for the "five-dword packet" this repo inferred at slot 80 and the header encoding for parameter groups; consistent with our own measurements of +0x18/+0x28/+0x30/+0x140/+0x344/+0x544. | -| Mesh (NGG) inputs measured across the corpus: `s3[27:24]` = wave index in the group, `v5` = group·128 + thread, `s16`–`s24` = user data. | *Corpus measurement, sibling layer* | Confirms the `s16` mesh base of §3.5's census and the `v5` group numbering already used for the mesh stage. | -| Console unified memory can be mapped GPU-side without copying: a region of at most 4,095 MB at a 4 GiB-aligned address, committed up front, opened through `ID3D12Device3::OpenExistingHeapFromAddress` (a partial commit and a full 4 GiB are rejected). The low 32 bits of a console address then index the buffer directly. | *Measured on PC D3D12, sibling layer* | A concrete recipe for §3.3's single address space: game addresses as offsets into one buffer that shaders reach through `PhysicalStorageBuffer64`. | -| The title physical-page calls use 64 KiB pages; mapping a run of consecutive pages returns a contiguous range inside the unified region, and scattered or explicitly addressed mappings are refused. | *Console-DLL run, sibling layer* | Sizes the page granularity the `xmem` shim should answer before the executable's real calls are known. | -| On a retail UE5 title the graphics command list takes console slot 83 for `CopyTextureRegion`, 84 for `CopyResource`, 26 for barriers, 127 for direct mesh dispatch, 59 for a second indirect/mesh dispatch path, and 96 for an async-compute budget call that accepts six zero words. | *Retail-title run, sibling layer* | Narrows question 2: mesh dispatch is not at the PC position (GCL6 slot 79) on the console, and the copy/barrier/budget slots add to the shifted groups already measured here. | -| The console `d3d12_xs.dll` also exports `D3D12XboxCreateSyntheticDevice` and `D3D12XboxSetProcessDebugFlags`; sibling console modules include `xg_xs.dll` (`XGCreateTexture2DComputer`, `XGComputeOptimalSwizzleMode`), `AcpHal.dll` (`ApuAlloc`, `ApuFree`, `ApuMapVirtualAddress`, `ApuIsVirtualAddressValid`, `AcpHalCreate`, `AcpHalAllocateShapeContexts`, `AcpHalReleaseShapeContexts`) and `dstorage_xs.dll` (console DirectStorage); `XAudio2_9.dll` ordinal 1 is `XAudio2Create` and `GameInput.dll` ordinal 1 is `GameInputCreate`. | *Export inventory, sibling layer* | Names the console-only modules the loader's shim registry should expect beyond `xgameruntime`/`d3d12_xs`/`xmem`/`gameinput`. | -| Console `xaudio2_9.dll` voices accept the console formats: XMA/XMA2 and an Opus voice format `0x704F`; a `CO_E_NOTINITIALIZED` from the system XAudio2 is retried after `CoInitializeEx` on the calling thread. | *Console-DLL run, sibling layer* | Forwarding console `XAudio2_9.dll` to the system XAudio2 2.9 works; the retry rule and the format remapping are the quirks to reproduce. | -| A retail title boots to its menu and lobby through the same shim-layer route (native x64 code, console-library stand-ins); its console-only library set adds `chad` (`XDsp*`), `xapu` (`XApu*`), `xcrdapi` and `*legacy` DLL variants to the list. | *Retail-title run, sibling layer* | Confirms the architecture end to end on retail code and extends the console-DLL checklist. | - -### 7.1 What this confirms, corrects and narrows - -**Confirms.** - -- The 16 middleware DLLs need only four `xmem` functions and the two `d3d12_xs` root-signature functions. Our - earlier statement that the bundled DLLs only import the two root-signature calls was right but incomplete; the - four `xmem` imports complete the static surface. The repo's `xmem` shim already implements all four. -- Device slots 1 (AddRef), 15 (`GetDescriptorHandleIncrementSize`), 18 (`CreateShaderResourceView`), - 19 (`CreateUnorderedAccessView`), 27 (`CreateCommittedResource`) and 38 (`GetCopyableFootprints`) match the - desktop order. Device slot 14 is the public `CreateDescriptorHeap`; only the returned heap's start-handle return - is wrapped. The public chain is a usable base for those methods, not a guess. -- The BVH builder receives the device and command lists from the caller; prior art runs it exactly that way. - -**Corrects.** - -- **Device creation.** `D3D12XboxCreateDevice` is the entry point. The 24-word params struct is only logged, so - the flag/layout meaning is still unknown; the name and call shape are no longer unknown. Prior art returns a PC - D3D12 device behind the proxy; this design returns the Vulkan-backed `Device` behind the same call shape. -- **Vtable.** The Xbox device is not uniformly the public order. Slot 76 is an extra texture-creation method, - slot 62 is called with a compute-PSO signature where the PC interface has a state-object method, and the - descriptor-heap start handles use a different return convention. Implement the public chain plus explicit - measured overrides; do not trust a single generic thunk for every slot. -- **Texture layout.** Xbox `0x101` tiled is not a public `D3D12_TEXTURE_LAYOUT` value, and slot 76 is the texture - path. Our earlier `D3D12_RESOURCE_DESC::Layout` discussion covered only the public enum; it now includes the - Xbox value and slot 76. -- **Root signatures.** The `0x03000000` flags must be masked on a copy before the host serializer/deserializer. - Our earlier "forward the blob to the host" was too simple; the PC serializer rejects the Xbox bits. -- **BVH builder.** Its console programs are `FSSM`; the bitcode in the same container is the representation the - PC compiler consumed. "Run the builder's dispatches" therefore takes the same FSSM → SPIR-V path as the game, - with one rule still missing ([embedded_shaders.md](embedded_shaders.md)). - -**Narrows.** - -- Presentation slots and struct layouts (`PresentX` and plane parameters; call shapes are known from public samples, §4.5), command-list extensions, and queue/fence creation slots remain - unknown; the prior art explicitly stops before them. -- Descriptor start-handle ABI is known; descriptor bytes and heap increments are still **Open**. Slot 15 is - forwarded unchanged, but the actual increment values were not measured. -- Texture creation ABI and the `0x101` value are known; the tiled data layout, detile path and DCC remain - **Open**. -- The device params (command-queue ring size, scratch memory, debug flags) are unused and their meanings are - still unknown. -- The `xgr` 48/398 and Xodus 152/396 coverage numbers show how large the long tail is. They do not change the - plan: implement what the game calls, in the order it calls it. - -### 7.2 The BVH builder's shader path - -The builder's 52 compute shaders are a second *corpus*, not a second shader front end. Each container carries an -LLVM bitcode blob and an `XDAT`/`XBCH` record; the bitcode is what the PC D3D12 compiler experiment consumed -(44 of 53 rejected, 22 lowered), while the console runtime executes the `XBCH` record. That record decompresses -to `FSSM`, the same container the game's own compute shaders use: 52/52 unpack, 51 translate and all 51 pass -`spirv-val` with `tools/rdna2spirv.py`. The one left, `Box16Rehydration`, stops at `buffer_store_short`; -[embedded_shaders.md](embedded_shaders.md) lists the rules that closed the other nine. The raw 64-bit addresses are the translator's existing raw-address path, so no address-to-resource -table is needed on top. A port that runs `XboxBvhBuilder` therefore needs the FSSM translator plus one rule, -not a DXIL front end (a substitute builder remains the alternative). -`spirv-val` with `tools/rdna2spirv.py`. The single program left (`Box16Rehydration`) stops at `buffer_store_short` -(#1864); [embedded_shaders.md](embedded_shaders.md) lists it. The raw 64-bit addresses are the translator's -existing raw-address path, so no address-to-resource table is needed on top. A port that runs `XboxBvhBuilder` -therefore needs the FSSM translator plus that rule, not a DXIL front end (a substitute builder remains the -alternative). -Correctness is still unverified on a GPU and the call sites need the executable (RT-5). - -### 7.3 Licence - -`americas-recomp` / AnyPS5 is **GPL-2.0-only**. GPL-2.0-only is not compatible with this repository's -GPL-3.0-or-later, so no code, headers, generated stubs or other implementation text from that tree may be copied -into Leonida. This section records ABI/format facts and links only; the designs in this document are independent. -Xodus is LGPL-2.1 and is cited only for its coverage number, not as a code source. The same line holds for the -other compatibility-layer efforts whose measurements are folded in above: facts and numbers only, paraphrased — -nothing is copied from their trees. - -## 8. Known vs unknown - -### 8.1 Known - -- The public D3D12 ABI and method order (Windows SDK `d3d12.h` 10.0.26100.0); the Xbox public reference lists the - same base interfaces and method names under `d3d12_xs.h`, but the measured Xbox device ABI is only mostly the - public order: slots 1/15/18/19/27/38 matched, while slots 62 and 76 and the descriptor-heap start-handle return - did not (section 7). -- The translator/runtime shader contract, and that it works on a real GPU for the tested paths. -- The package evidence in section 2 and Appendix A: the BVH builder's Device11/CommandList4/6/8 signatures and - XDXR types, the FSR IIDs, the other DLLs' lack of `d3d12_xs` imports, `gameos.xvd`'s encrypted payload, and the - absent executable. -- The prior art's measured Xbox ABI (section 7): 6 Xbox-specific static imports across the 16 DLLs, - `D3D12XboxCreateDevice`, device slots 62/76, descriptor-heap start handles in RAX, root-signature flags - `0x03000000`, and the BVH builder's container format (a DXIL bitcode blob plus the console `XBCH` record). - -### 8.2 Unknown / open questions - -| # | Question | How to resolve | -|---|---|---| -| 1 | The device entry point is now named `D3D12XboxCreateDevice(adapter, params, riid, out)`. What do its 24-word params and flag bits mean? | Public documentation and the executable's call sites. Log the words and accept any flag bits; do not treat a wrong params layout as fatal until the fields are understood. | -| 2 | Which Xbox device/heap/queue/command-list slots differ? Prior art measured device slots 62 and 76 and descriptor-heap slots 9/10; slot 14 is the public `CreateDescriptorHeap`, with only the returned heap's start-handle return wrapped. **Partly measured** with the FSR DLL ([d3d12_command_objects.md §3.5a](d3d12_command_objects.md)): device slots 14, 15, 16, 18, 19, 27, 38, 62 and 76 at their expected shapes (24 in the code, not called), slot 67 a console-only pipeline call; command-list slots 14, 15, 25 and 26 at their PC positions, then shifted (+4 from `SetDescriptorHeaps` at 32, +2 at `ExecuteIndirect` at 61), with console-only methods at 85 and 141. The BVH builder's call sites add the rest of the +4 root group (37, 39, 43, 45) and console slots 71, 73, 80, 146 (the GCL7 `Barrier`) and 148 (an upload allocator whose pointer is also the GPU address) ([d3d12_command_objects.md §3.3, §3.3a](d3d12_command_objects.md)). A second, retail-title measurement adds console slots 83 (`CopyTextureRegion`), 84 (`CopyResource`), 26 (barriers), 127 (direct mesh dispatch — not the PC position, GCL6 slot 79), 59 (a second indirect/mesh dispatch path) and 96 (an async-compute budget call) (section 7). Presentation, queue and fence slots remain unknown. | Trace every `QueryInterface` and every method slot with per-slot hit counters. A wrong slot shows as an immediate crash or wrong argument; compare against the SDK vtable. | -| 3 | How does the console map a root signature to `s0..s31` (order, per-stage visibility, spills above 32 dwords, static samplers, direct-heap base)? | **Compute partly measured** by a sibling project's console-compiler output (section 7): parameters inline in user SGPRs from `s4` in root order while each fits whole; the first that does not fit, and all after it, go into a packed array addressed by a 40-bit pointer at `s[0:1]`; thread-group ids follow the user SGPRs. That matches this repo's CS census (lowest CS pointer SGPR `s4`). VS/PS/MS bases remain open. Static samplers: no sampling instruction was found reading one from a driver table (SHADER-735, section 3.5; 0.66% undetermined); which S# is a static sampler remains open. Dump the game's root-signature blobs with the host deserializer; mask the `0x03000000` flag byte on a copy first; match against the per-shader user-SGPR read sets. If a signature exceeds 32 dwords, reverse the spill pointer from the shader. | -| 4 | Are Xbox descriptor bytes GFX10 T#/S#, and what are the heap increments? Does the game use `Create*View` or build descriptors itself? | Dump a shader-visible heap after the first `CreateShaderResourceView` and after the first draw; compare the bytes the shader loads with the T# parser. The start-handle return ABI is known (RAX); the increment values still need measuring. | -| 5 | What is the buffer/descriptor/code VA range, and what arena capacity is needed? | Log every `GetGPUVirtualAddress` and every descriptor base; track the high-water mark. Choose a capacity; grow at a frame boundary if needed. | -| 6 | Which swapchain/present path is used: DXGI, `PresentX`, or both? | **Partly answered from public samples (§4.5):** GDKX samples use `PresentX` + frame events and no DXGI swapchain (DXGI only for `IDXGIDevice1`→adapter→output). Hypothesis for the game, not observed: same. Still open: vtable slots, `D3D12XBOX_*` layouts, and whether the game also creates a swapchain. Check imports and the first present call. Implement the `PresentX` + frame-event presenter first; keep DXGI swapchain as fallback. | -| 7 | Does the game build acceleration structures through the standard D3D12 calls or through `XboxBvhBuilder`'s own compute path? | Log `BuildRaytracingAccelerationStructure`, `CopyRaytracingAccelerationStructure`, `Emit...PostbuildInfo`, and the builder's command-list method calls on the first RT frame. The builder's container carries a DXIL bitcode blob and a console `XBCH` record; the record is `FSSM` and 51 of 52 programs pass `spirv-val` ([embedded_shaders.md](embedded_shaders.md)). If the builder path is used, translate the `XBCH` record rather than the bitcode. | -| 8 | What are the layouts of `D3D12XBOX_XDXR_STREAM_DESC`, the batched build desc, and the offline statistics desc? | **Measured** from `XboxBvhBuilder.dll`'s reads ([xdxr.md](xdxr.md)): `BATCHED_DESC2` (`0x50`) and `XDXR_STREAM_DESC` (`0x10`) with every field's offset, and the stream records' offsets, types and defaults. Still open: the record names, and the offline statistics layout, which the DLL never writes (it rejects that postbuild type). | -| 9 | Xbox texture creation is device slot 76 with layout `0x101` (tiled) or `0x1` (row-major). What is the tiled data layout, and does the game upload console-tiled or DCC data? | Trace slot 76, `CopyTextureRegion` and the resource descs. If the game uploads console-tiled data, add a detile step or a matching layout. | -| 10 | Does the game use binning, DCC, VRS, wave MMA, stream output, tessellation, or amplification shaders? | **Shaders: answered** by `tools/feature_scan.py` over all 26,503 (1.0.2.1): no hull, domain or amplification shader (DXIL program kinds: 2,236 VS, 12,101 PS, 195 GS, 2,689 CS, 9,282 MS); no `WAVE_MMA` or `SHADING_RATE` in any SFI0, and no `v_mfma`/`v_wmma`/`v_smfmac` in the disassembly; no output-signature element on a stream other than 0 (all 195 GS write stream 0 only) and no GDS / `ds_ordered_count` / GWS instruction, so no stream-output path. Also from SFI0: 10 PS need ROVs (pixel interlock), 30 shaders `TILED_RESOURCES` (see #18), 685 `ATOMIC_INT64_ON_TYPED_RESOURCE`. Binning and DCC are not shader-visible; they stay open for the PSO/stream subobjects. | -| 11 | What should `CheckFeatureSupport` answer for UMA, resource binding tier, mesh tier, RT tier? | **Implemented** (D3D-11). Reports truthful host architecture (a discrete GPU: non-UMA; an integrated GPU, `VK_PHYSICAL_DEVICE_TYPE_INTEGRATED_GPU`: UMA, not cache-coherent, as the host runtime answers on a Radeon 780M), ResourceBindingTier 3 (descriptor indexing / bindless support), 48-bit GPU virtual address support matching the arena, and maps `D3D12_FEATURE_FORMAT_SUPPORT` to Vulkan format properties plus multisample render-target/resolve support and one quality level per supported sample count. | -| 12 | Does the game rely on async compute or copy queues for correctness? | Trace queue creation and cross-queue fences. If only performance, serialize on one queue for boot. | -| 13 | Is 144 bytes of push constants available on all target GPUs? | **Resolved / Measured** (D3D-14). Checked at device creation in `runtime/shims/d3d12_vulkan_device.cpp`. Measured across the test fleet (#166): NVIDIA (256 B), desktop AMD (256 B), and Apple M1/MoltenVK (4096 B) satisfy 144 B natively. A Radeon 680M on the Windows driver 22.40.84.06 and the earlier Intel Arc entries expose only the core minimum 128 B (`maxPushConstantsSize == 128`), but an Arc B580 on Windows 11 (driver 32.0.101.9175) reports 256 B (#166), so the 128 B figure for Arc depends on the OS or driver; an Arc result on Linux (Mesa ANV) would settle which side it is. `d3d12_vulkan_device_test` accepts either answer and checks that the fallback flag matches it. Below 144 B, the device logs a warning and marks `push_constants_need_fallback`, routing the 16-byte tail (dwords 32..35: heap base and code base) to a uniform-buffer fallback. | -| 14 | Are there PSOs with two code-base stages? | Count from the PSO/shader hash table and the index metadata. If yes, implement per-stage code-base slots (section 5.2). **Per stage, measured** (`tools/feature_scan.py`, `s_getpc_b64` kept for data rather than a far branch): 54 VS, 93 PS, 266 MS, 263 CS, 0 GS; the translator's `uses_code_base` gives the same counts (with LLVM 23 that needs #223, without which these 1,471 shaders are rejected). So VS+PS and MS+PS pipelines with two code-base stages are possible; whether any exists depends on which shaders a PSO pairs, which is in the executable, not in `shaders.rpf`. | -| 15 | Is `ExecuteIndirect` used with signatures Vulkan cannot express directly? | Trace `CreateCommandSignature` and `ExecuteIndirect`; implement simple signatures first, expand the complex ones with compute. The simple signatures are D3D-17 (#313). | -| 16 | Does the game use append/consume UAV counters or typed buffer formats the translator does not model? | **Shaders: answered** by `tools/feature_scan.py` over all 26,503 (1.0.2.1, disassembled with LLVM 21.1.8 for gfx1013; SHADER-65). **No append/consume counters:** none of the 445,394 PSV0 binding records is a structured UAV with a counter, and there is no `ds_append`/`ds_consume`/GDS instruction. Typed buffers are declared in 5,359 shaders as SRVs (17,328 records) and in 2,177 as UAVs (4,005). **MTBUF** (format in the instruction): 52,890 loads in 10,278 shaders, all in five formats the translator decodes (`16_16_SNORM` 24,881, `8_8_8_8_UNORM` 19,835, `8_8_8_8_UINT` 5,099, `2_10_10_10_UNORM` 2,648, `16_16_16_16_UINT` 427), and no MTBUF store. **MUBUF** `buffer_*_format_*` (format from V# word 3): 90,316 accesses (84,908 loads, 5,408 stores) in 11,591 shaders; word 3 comes from a scalar load in 88,924 of them, is computed in 1,390, and is a literal in 2 (FORMAT 0, INVALID, which reads 0 on the hardware and in the translator). So the shaders fix no MUBUF format: the descriptors the executable writes decide it. Still open: which formats those descriptors carry; the runtime can log a V# format outside `Gen.FORMATS` (those read 0 today) when the descriptor is created or copied. Trace UAV descs and shader `buffer_*` ops; extend the translator/runtime together. **Runtime side done, console side open:** the layer writes typed buffer V#s and a counter V# (a hypothesis for where the shader finds it, section 3.4 "Buffer UAVs"); whether the game uses either is for the trace. | -| 17 | Do upload/readback resources ever reach shaders (as vertex/index buffers or descriptors), and does the `-heap_base` bias work for them? | Trace `CreateCommittedResource` heap types and every VB/IB/descriptor that points at an upload resource; test the bias with a synthetic draw. | -| 18 | Does the game alias buffers/images in a heap, or use reserved/tiled resources? | Trace `CreatePlacedResource` ranges, aliasing barriers, `CreateReservedResource` and tile mappings. If yes, implement shared memory per heap range or fall back to linear allocations with a clear log. Shaders: 30 declare `TILED_RESOURCES` in SFI0 (`tools/feature_scan.py`), so reserved/tiled resources are likely used. Placed resources are D3D-16 and reserved resources D3D-20 (#313). | -| 19 | What do the `0x03000000` root-signature flag bits mean? | Masking them on a copy works around the PC serializer; the semantics remain unknown. **Origin measured** (section "Root-signature flag quirk"): in the package only `XboxBvhBuilder.dll` sets them, in its 52 compiled `RTS0` parts and unconditionally at `0xc30e` before serialising; the FSR DLL's 29 `RTS0` parts carry 0. Compare against the public flag enum and observe the game's behaviour with and without the mask; check whether the executable's root signatures carry them. | -| 20 | Which of the BVH builder's 52 `FSSM` programs does the game actually use, and do the translated programs match a reference? | Dump the slot-62 compute PSOs on the first RT frame and map each to its container by the `ILDN` name; 51/52 pass `spirv-val` today and the one missing rule is named in [embedded_shaders.md](embedded_shaders.md); compare against the builder's CPU validation (`CpuValidateResultX`) or a captured reference. 42/52 pass `spirv-val` today and the four missing rules are named in [embedded_shaders.md](embedded_shaders.md); compare against the builder's CPU validation (`CpuValidateResultX`) or a captured reference. | -| 21 | Which `Metadata` values and blob format does the console's PIX use for `SetMarker`/`BeginEvent`? The layer reads 0 and 1 as strings and labels 2 (the PC PIX3 blob) `PIX event` (section 4.10). | Log the `Metadata` values the game passes; if it is 2, decode the console blob from the executable's PIX calls rather than assuming the PC WinPixEventRuntime layout. | -| 22 | Does the game ask `CheckFeatureSupport(D3D12_OPTIONS5)` for `RaytracingTier` and switch ray tracing off when it reads `NOT_SUPPORTED`? The layer answers `NOT_SUPPORTED` because full DXR (`CreateStateObject`, `DispatchRays`) is not implemented, even though the XDXR acceleration-structure path the game's own traversal shaders use is ([bvh.md](bvh.md) §7a). On the console, ray tracing is always present, so the game may never ask. | The first-boot trace (`--trace-d3d12`) logs every `CheckFeatureSupport` call and its answer. If the game asks and gates its RT on the tier, decide with the maintainer whether to report `TIER_1_0`/`1_1` for this game while `DispatchRays` stays unimplemented; until then, keep the conservative answer. | - -## 9. Risks and non-goals - -**Risks.** - -- **Xbox ABI deviations.** The device vtable is mostly public but not uniformly: slot 76 adds texture creation, - slot 62 is compute-PSO creation for the BVH builder, descriptor-heap slots 9/10 return in RAX, and root signatures - carry `0x03000000`. Use a per-slot proxy with counters; presentation, command-list, queue and fence slots remain - unknown. A wrong return convention or slot mapping corrupts state rather than failing cleanly. -- **Root-signature mapping.** A wrong `s0..s31` packing produces silently wrong rendering, not a crash. The - per-shader read-set metadata and a strict mismatch check are the mitigation. The `0x03000000` flag mask is a - workaround, not an explanation. -- **The arena.** A single BDA arena is required by the shader contract for buffers, descriptor tables and code; the - game's buffer working set may exceed `maxBufferSize` or PC VRAM. Host-visible arenas are slow; device-local - arenas need staging and careful upload/readback handling. This is the main performance risk. -- **Hash-table cost.** Every image/sampler access hashes a T#/S# and probes a storage buffer. **Measured (D3D-56, section 5.1)** on an RTX 5080 (driver 621.24): in `DEVICE_LOCAL` VRAM the lookup itself stays fast up to 100k entries (wave-uniform full sweeps `3.3–12.8 us/1M`, divergent hits `24–72 us/1M`), whereas `HOST_VISIBLE | HOST_COHERENT` system memory slows uniform full sweeps 16x–36x and divergent lookups 210x–879x at 10k–100k entries; `bc8e604`'s bounded slot relocation keeps the 100k table at `20.00 MiB` (`19.07%` load, `max_probes=8`) instead of doubling. **The runtime now keeps that table in `DEVICE_LOCAL` memory** and uploads only the slots that changed, from a mapped staging copy, with the copy and its barrier in the command buffer that will read it (D3D-76; 46.2x on a divergent miss at 100k on an RTX 2060 SUPER). Improving slot placement within the 8-probe window is the open optimisation (SHADER-100); Intel, RTX 5070 Ti Laptop and AMD RDNA3 are measured in section 5.1; Apple numbers remain open via `vk_descriptor_bench`. -- **Wave64.** A native wave64 shader needs a 64-wide subgroup in its stage: AMD (Windows driver, RADV on GFX10+) can require - it for compute, mesh and pixel shaders, NVIDIA cannot (32 only). There, compute and mesh shaders translated with - `--wave64-emulate` are exact; wave64 pixel, vertex and geometry shaders have no emulation and keep the - translator's 32-wide approximation (cross-half ops are approximate). This is a known fidelity gap, not specific to - the layer. -- **Xbox tiling/DCC.** Slot 76 and layout `0x101` are known, but the tiled data layout, detile path and DCC remain - unknown. If the game assumes console tiling or compression metadata, the layer needs a detile/repack step. -- **BVH builder shaders.** The container's DXIL bitcode is Xbox DXIL that PC drivers reject; its console `XBCH` - record is `FSSM`, and 51 of the 52 programs already pass `spirv-val` through the same translator as the game - ([embedded_shaders.md](embedded_shaders.md)). The one left needs `buffer_store_short` (#1864). Translation is not execution: - there is no GPU reference for any of the 52 yet. -- **Ray tracing.** The game's RT work includes 64 compute shaders that traverse AMD-format BVH nodes, and it ships - a BVH builder; a standard D3D12 AS path may also exist. If it is used, the layer must build AMD-format nodes, not - a Vulkan AS. - -**Non-goals.** - -- Xbox One ESRAM or `d3d12_x` (the Xbox One flavour); this is a Series build. -- D3D11, D3D12 video, protected content, cross-process sharing, meta commands, DRED tooling. -- A general D3D12 compatibility layer for arbitrary applications. -- Any use of game data, keys or decryption. -- Copying code, headers or generated stubs from the GPL-2.0-only prior art; its ABI/format facts are cited with - links only. -- Replacing the translator's shader contract. The layer adapts to it; changes to it (per-stage code base, extra - metadata) are coordinated with `tools/rdna2spirv.py`. - -## 10. References - -Prior art (facts and links only; no code copied; GPL-2.0-only, see section 7.3): - -- [americas-recomp, branch `xbox-series`](https://github.com/realdody/americas-recomp/tree/xbox-series) -- [PLATFORM_SURFACE.md: package import surface and measured device ABI](https://github.com/realdody/americas-recomp/blob/xbox-series/docs/xbox/PLATFORM_SURFACE.md) -- [platform tools README: proxy, `XS_TRACE`, xgr, first-run workflow](https://github.com/realdody/americas-recomp/blob/xbox-series/tools/xbox/platform/README.md) -- [GPL-2.0 license text](https://github.com/realdody/americas-recomp/blob/xbox-series/LICENSE) - -Public D3D12: - -- [D3D12 programming guide](https://learn.microsoft.com/en-us/windows/win32/direct3d12/directx-12-programming-guide) -- [Root signatures](https://learn.microsoft.com/en-us/windows/win32/direct3d12/root-signatures) -- [`D3D12_ROOT_SIGNATURE_FLAGS`](https://learn.microsoft.com/en-us/windows/win32/api/d3d12/ne-d3d12-d3d12_root_signature_flags) -- [Resource binding in HLSL](https://learn.microsoft.com/en-us/windows/win32/direct3d12/resource-binding-in-hlsl) -- [Descriptor heaps](https://learn.microsoft.com/en-us/windows/win32/direct3d12/descriptor-heaps) -- [Recording command lists and bundles](https://learn.microsoft.com/en-us/windows/win32/direct3d12/recording-command-lists-and-bundles) -- [Using resource barriers](https://learn.microsoft.com/en-us/windows/win32/direct3d12/using-resource-barriers-to-synchronize-resource-states-in-direct3d-12) -- [Enhanced barriers (DirectX spec)](https://microsoft.github.io/DirectX-Specs/d3d/D3D12EnhancedBarriers.html) -- [Executing and synchronizing command lists](https://learn.microsoft.com/en-us/windows/win32/direct3d12/executing-and-synchronizing-command-lists) -- [Fence-based resource management](https://learn.microsoft.com/en-us/windows/win32/direct3d12/fence-based-resource-management) -- [Queries](https://learn.microsoft.com/en-us/windows/win32/direct3d12/queries) -- [Mesh shader (DirectX spec)](https://microsoft.github.io/DirectX-Specs/d3d/MeshShader.html) -- [Direct3D 12 raytracing](https://learn.microsoft.com/en-us/windows/win32/direct3d12/direct3d-12-raytracing) -- [`ID3D12Device10`](https://learn.microsoft.com/en-us/windows/win32/api/d3d12/nn-d3d12-id3d12device10), - [`ID3D12GraphicsCommandList7`](https://learn.microsoft.com/en-us/windows/win32/api/d3d12/nn-d3d12-id3d12graphicscommandlist7) - (the Win32 reference does not yet have pages for `Device11`/`CommandList8`; the Windows SDK header defines them) - -Xbox public documentation: - -- [Xbox graphics API reference](https://devdocs.xbox.com/reference/graphics/d3d12) -- [Xbox `ID3D12Device::CreateCommittedResource`](https://devdocs.xbox.com/reference/graphics/d3d12/interfaces/id3d12device/methods/id3d12device_createcommittedresource_public) -- [Xbox-GDK-Samples (MIT): SimpleDeviceAndSwapChain, FramePacing](https://github.com/microsoft/Xbox-GDK-Samples) -- [DirectXTK12 wiki: DeviceResources](https://github.com/Microsoft/DirectXTK12/wiki/DeviceResources); [directxtk12modelviewer](https://github.com/walbourn/directxtk12modelviewer) (MIT); SDL2 `SDL_render_d3d12_xbox.cpp` (zlib) -- [`PresentX` mentioned in `XGameStreamingSetResolution`](https://docs.xbox.com/reference/system/xgamestreaming/functions/xgamestreamingsetresolution) -- [GDK release notes mentioning `D3D12XBOX_RESOURCE_FLAG_FORCE_TEXTURE_COMPATIBILITY`](https://docs.xbox.com/announcements/gdk/2510/release-notes-2510) - -Vulkan: - -- [Descriptor indexing](https://registry.khronos.org/vulkan/specs/latest/man/html/VK_EXT_descriptor_indexing.html) -- [Buffer device address](https://registry.khronos.org/vulkan/specs/latest/man/html/VK_KHR_buffer_device_address.html) -- [Synchronization2](https://registry.khronos.org/vulkan/specs/latest/man/html/VK_KHR_synchronization2.html) -- [Dynamic rendering](https://registry.khronos.org/vulkan/specs/latest/man/html/VK_KHR_dynamic_rendering.html) -- [Timeline semaphores](https://registry.khronos.org/vulkan/specs/latest/man/html/VK_KHR_timeline_semaphore.html) -- [Mesh shader](https://registry.khronos.org/vulkan/specs/latest/man/html/VK_EXT_mesh_shader.html) -- [Fragment shader barycentric](https://registry.khronos.org/vulkan/specs/latest/man/html/VK_KHR_fragment_shader_barycentric.html) -- [Fragment shader interlock](https://registry.khronos.org/vulkan/specs/latest/man/html/VK_EXT_fragment_shader_interlock.html) -- [Subgroup size control](https://registry.khronos.org/vulkan/specs/latest/man/html/VK_EXT_subgroup_size_control.html) -- [Maintenance4](https://registry.khronos.org/vulkan/specs/latest/man/html/VK_KHR_maintenance4.html) - -## Appendix A: evidence and reproduction - -REA was used for the PE import/export and string inventory. The XVD header and entropy scan used local .NET, -because `gameos.xvd` is an XVD container rather than a PE. Nothing was decrypted or executed. - -### A.1 `gameos.xvd` - -- Size 348,069,888 bytes. `msft-xvd` magic at file offset **0x200**; the 512 bytes before it are a high-entropy - block, consistent with a signature. Using the standard XVD header layout, the first two dwords after the magic - are `volume_flags = 1` and `format_version = 3`. -- 64 KiB Shannon entropy sampled at offsets 0, 0x1000, 0x10000, 1 MiB, 16 MiB, 64 MiB, 128 MiB, 256 MiB: - 6.40, 6.69, 7.68, 7.68, 7.997, 7.998, 7.997, 7.997 bits/byte. -- A chunked ASCII scan (4 MiB chunks) of the whole file found no `d3d12_xs.dll`, `d3d12.dll`, - `D3D12CreateDevice`, `ID3D12Device`, `gameos`, or `xboxgip` strings. A token spanning a chunk boundary could be - missed, but the entropy result does not depend on the scan. -- Conclusion: the payload is encrypted or compressed. It cannot supply the D3D12 API surface without keys, which - are out of scope. No key search or decryption was attempted. - -Reproduce: read the first 4 KiB, locate `msft-xvd`; compute per-block entropy; scan for the ASCII tokens above. -The file is an XVD container, not a PE; PE-oriented import tools do not apply. - -### A.2 `XboxBvhBuilder.dll` - -- Size 884,224 bytes; PE32+ x86-64; export directory RVA 861,536, 12 named exports. -- The exported C++ signatures name: - - `ID3D12Device11` (constructor, rehydration), - - `ID3D12GraphicsCommandList4` (standard build, copy, CPU validation), - - `ID3D12GraphicsCommandList6` (batched build), - - `ID3D12GraphicsCommandList8` (batched rehydration), - - `D3D12XBOX_XDXR_STREAM_DESC` and `D3D12XBOX_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_BATCHED_DESC2`, - - `D3D12_RAYTRACING_ACCELERATION_STRUCTURE_POSTBUILD_INFO_DESC` and the standard build/copy/prebuild types. -- Imports: `d3d12_xs.dll!D3D12SerializeVersionedRootSignature` (ILT RVA 864,368, IAT RVA 148,048) and - `xmem.dll!XMemVirtualQuery` (ILT RVA 864,384, IAT RVA 148,064). No other console graphics imports. -- GUID byte scan against the Windows SDK `d3d12.h` found `IID_ID3D12PipelineState` at file offset 0x0c9ed8 and - `IID_ID3D12RootSignature` at 0x0c9ee8. Presence in a read-only data table is evidence of the interface version - the DLL was compiled against, not proof that every method is called. - -Reproduce: `rea.inspect_native_exports` and `rea.inspect_pe_imports` on the DLL, then a byte scan for the -little-endian GUIDs from `d3d12.h`. - -Constructed by `runtime/test/bvh_builder_test.cpp` (1.0.2.1: `rt::Loader`, `Loader::initialise()` for TLS and -`DllMain`, `.pdata` registered by the loader (#176), then `XboxBvhBuilder(ID3D12Device11*, bool)` -on a PC device behind the Xbox-ABI proxy). Measured: - -- 0 unimplemented imports; `D3D12SerializeVersionedRootSignature` and `XMemVirtualQuery` bind to shims. The constructor writes 24 bytes of the object (`sizeof(XboxBvhBuilder)` >= 24; - the rest of its state is elsewhere). It prints nothing through `OutputDebugString` and never calls - `TerminateProcess`. On failure it throws the failing `HRESULT` as a C++ `long`. -- **Device slot 62 is called as `(desc, 0, 0, &IID_ID3D12PipelineState, out)`**, with a plain - `D3D12_COMPUTE_PIPELINE_STATE_DESC` (root signature set, node mask 0, flags 0). The proxy used to read - `(desc, riid, out)`, so the first call returned `E_POINTER` and the constructor threw it. -- With slot 62 read that way, on **WARP** the constructor returns after 62 ms: 17 root signatures (slot 16) and 53 - compute PSOs (slot 62, 53 of 53 `S_OK`), CS bytecode 4–75 KB each. `~XboxBvhBuilder` returns and makes no device - call. Created is not the same as correct: the container's DXIL bitcode is Xbox DXIL with `@xbox.*` intrinsics - (section 7.2), its console `XBCH` record is `FSSM`, and nothing has been dispatched yet. -- **NVIDIA (RT-54).** On an RTX 3060 (616.64), an RTX 4090 (621.14) and an RTX 5070 Ti (621.24), all on Windows 11, - the first 48 PSOs return `S_OK`, and the 49th (38,248 bytes) never does. Some runs return `E_OUTOFMEMORY` for it, - which the constructor throws. Other runs end the process inside `nvwgf2umx.dll` with `0xC0000409`, after the - driver's LLVM 7.0.1 bitcode reader prints `Invalid record` or `Never resolved value found in function`. That - can't be caught. The D3D12 debug layer prints nothing first. - - **Cause: the input, not Leonida.** The proxy passes the bytecode through unchanged, so nothing is wrong in what - it forwards. The input is the problem: `LEONIDA_BVH_RECORD62=1 LEONIDA_BVH_DXIL=1` shows that every one of the - 53 PSO calls (52 distinct containers) is signed, has the same 9 parts, and is shader model 6.5 / DXIL 1.5. But dxil.dll (Windows SDK - 10.0.26100) rejects all 53 (`0x80aa0009`): the target triple is `dxil-ms-xb2` and the module carries - `xbox.compiler.options` metadata. Most also have Xbox-only externals (44 of 53), `extractvalue` on non-DXIL types - (16) or other disallowed instruction types (5). No PC driver has to accept this, and WARP happens to. - - **What sets the 49th apart: one error kind.** It is the only shader of the 53 that the validator reports for a - resource in a function signature (a non-entry function that takes a resource). Its other counts are 265 - `extractvalue`, 6 Xbox externals and 514 `i64` mentions; the 36th shader has the same 265 and 468 and is created. - - **Workaround: the test uses WARP on every hardware vendor.** AMD doesn't take these shaders either: on an RX 7900 - XTX (32.0.32029.2010) the constructor faults with `0xC0000005` right after the first slot 62 call (RT-89, #166). - So `bvh_builder_test` uses WARP whenever there is a hardware adapter, unless `LEONIDA_BVH_HARDWARE=1`, and it - prints the reason with the adapter's PCI vendor id. WARP creates all 53 PSOs, and the constructor and destructor - return. - - **The runtime itself still shouldn't hand Xbox DXIL to a PC driver.** The same container carries the console - `XBCH` record, which decompresses to `FSSM`; 51 of the 52 programs translate and pass `spirv-val` today - ([embedded_shaders.md](embedded_shaders.md)). Translating that record is the path that avoids a DXIL lowering - front end (section 7.2, M6); the bitcode is a second representation. -- **On the Vulkan device (D3D-557).** With `LEONIDA_BVH_DEVICE=vulkan` the constructor runs on the Vulkan-backed - device, where slot 62 needs the translated module of each container's `FSSM` program. `make_game.py` translates - the DLL's programs into `/bvh/` and the shader library reads that index - ([embedded_shaders.md](embedded_shaders.md) section 7). Measured on 1.0.2.1: before that step creation #1 failed - (`E_FAIL` with no library, `E_INVALIDARG` with the game's corpus loaded). With it, on an RTX 3070 (NVIDIA 610.74) - and on a Ryzen 7 9700X's integrated Radeon (AMD 32.0.21042.62), both with the `--wave64-emulate` translation, 49 of - the first 50 creations return `S_OK` and the constructor throws `E_INVALIDARG` at #50, `Box16Rehydration`, the one - program the translator has no rule for yet (#1864). With that rule applied locally all 53 are created and the - constructor and destructor return. Nothing has been dispatched. - -### A.3 `amd_fidelityfx_upscaler_xbox.dll` - -- Size 786,432 bytes; PE32+ x86-64. -- Import: `d3d12_xs.dll!D3D12CreateRootSignatureDeserializer` (IAT RVA 164,672). -- GUID byte scan found `IID_ID3D12Device` (0x0472f0), `IID_ID3D12Resource` (0x047310), - `IID_ID3D12RootSignatureDeserializer` (0x047320), `IID_ID3D12PipelineState` (0x047330), - `IID_ID3D12Heap` (0x047340), `IID_ID3D12RootSignature` (0x047350), `IID_ID3D12DescriptorHeap` (0x0472e0) and - `IID_ID3D12CommandSignature` (0x047300). Again, presence ≠ use. -- Run through the public FidelityFX API by `runtime/test/fsr_dispatch_test.cpp` (1.0.2.1: `rt::Loader` and - `Loader::initialise()`, with #93's static TLS, which the DLL's thread-safe statics need, and `.pdata` registered by - the loader (#176); PC D3D12 device on an RTX 4090 behind the Xbox-ABI proxy). Measured: - - It maps with 0 unimplemented imports: `D3D12CreateRootSignatureDeserializer` and `XMemAlloc` / - `XMemFree` / `XMemGetWorkingSetStatistics` bind to the shims, 82 imports to host DLLs. Its TLS template is - 8 bytes with no callbacks. `DllMain(DLL_PROCESS_ATTACH)` returns TRUE. - - `ffxConfigure(GLOBALDEBUG)` and the CPU-only upscale queries accept the **PC struct type ids**: the - Performance ratio is 2.0 and 3840x2160 Quality renders at 2560x1440. `GET_VERSIONS` for the upscaler lists one - provider, `0xf5a5ca1e01001001` "4.1.1". - - `ffxCreateContext` reports, through the message callback, that only one configuration is built in: - `maxUpscaleSize` 1920x1080 ("only the fixed-resolution Quality shader tables are included", so a 1280x720 - render size), with `HIGH_DYNAMIC_RANGE`, `DEPTH_INVERTED` and `AUTO_EXPOSURE` all required. It also requires an - `ffxCreateContextDescUpscaleVersion` in the chain; 4.1.2 is rejected as invalid, 4.1.1 and 4.0.0 are accepted. - - With all of that, `ffxCreateContext` returns `FFX_API_RETURN_ERROR` with no message, no XMem allocation and no - call on the device proxy, for the PC DX12 backend descriptor (`0x2`), for the same `{header, device}` layout - under `0x02000000`, `0x02000001` and `0x02000002`, and with no backend descriptor at all. -- **The Xbox backend descriptor, measured from the DLL** (Ghidra 12.2 through REA; RVAs, image base `0x180000000`): - - `ffxCreateContext` (`0x11d0`) picks its one provider (`ffxProvider_FSR4_Int8` by RTTI) by finding a device in - the chain: type 4 (`GET_VERSIONS`) at `+0x18`, types `0x10009` and **`0x01000002`** at `+0x10`. - - The provider's create (`0xc9b0`) wants `CreateContextDescUpscale` (`0x10000`) first, checks the version - descriptor (`0x1000b`, 4.0.0 to 4.1.1), then walks `pNext` for **type `0x01000002`: `{header, device}`, the device - at `+0x10`**, the same layout as the PC DX12 descriptor. Two of them, or none, is `FFX_API_RETURN_ERROR` - without a message: that is what the ids above got. An optional type `0x01000003` sets function pointers: when the - one at `+0x20` is set (with `+0x28`), the backend calls it instead of `CreateHeap` (device slot 28, `0x7390`); what - its other fields do is open. - - The HRESULT checks at the calls seen here (`0x33d4`, `0x65b3`, `0x74a8`) go through one helper (`0x1c60`): - `FormatMessageW` of the code, then `throw 1`. -- **Run with that descriptor** (`fsr_dispatch_test`, PC device on an RTX 2000 Ada, driver 597.06, behind the - Xbox-ABI proxy): the DLL creates its backend through the proxy. Device slots called: 14 `CreateDescriptorHeap` (5), - 15 `GetDescriptorHandleIncrementSize`, 18 `CreateShaderResourceView`, 19 `CreateUnorderedAccessView` and **76** (4), - plus heap slot **9** `GetCPUDescriptorHandleForHeapStart` (Xbox RAX form). No earlier test in this repository - reached slot 76 or heap slot 9 with a real client; their measured shapes hold. Slot 76 is called with the 7 - arguments of `CreateCommittedResource` - (heap properties, heap flags, resource desc, state, clear value, IID, out; call at `0x33cc`), the desc being the - 56-byte `D3D12_RESOURCE_DESC` with layout `0x101` and the word 3 at `+0x34`. - - On that GPU it stops at its 4th slot-76 texture: 1920x1080 `DXGI_FORMAT_R9G9B9E5_SHAREDEXP` with - `ALLOW_UNORDERED_ACCESS`, which the NVIDIA driver refuses (`E_INVALIDARG`); WARP creates it. The console build - creates it, so the console takes that format as a UAV. On the same GPU Vulkan has no `STORAGE_IMAGE` support for - `VK_FORMAT_E5B9G9R9_UFLOAT_PACK32` either (vulkaninfo, driver 597.06), so the layer needs an emulation (32-bit - storage plus a pack/unpack) where a GPU lacks it. @Vonsek measured the same texture on more devices (#864): - refused on an RTX 5080 (616.92), created on an AMD Radeon and on WARP, where typed UAV writes round-trip; and on - both GPUs one allocation can serve both uses, a mutable `R32_UINT` Vulkan image with `E5B9G9R9_UFLOAT_PACK32` in - its format list, written through an `R32_UINT` storage view and sampled through an `E5B9G9R9` view. - **Implemented** in `d3d12_vulkan_device.cpp` and `src/uav_clear.h` (`d3d12_r9g9b9e5_uav_test`): on an RTX 3060 Ti - (driver 621.01, `LEONIDA_FSR_DEVICE=vulkan LEONIDA_FSR_NO_STANDIN=1`, `LEONIDA_VK_VALIDATION=1`), - `ffxCreateContext` and `ffxDestroyContext` both return OK without `standin_slot76` and with 0 validation errors. - Open: a float store to that format rounds differently on PC devices (@Vonsek, #864: AMD Radeon truncates the - mantissas, WARP rounds to nearest even; 609 of 794 test triples differ). Which rule the console FSR needs, and - whether its shaders store floats to that texture at all (requiring shader-side packing into the `R32_UINT` storage - view), waits on decoding its `FSPX` shaders. - - With that one texture created as `R32_UINT` instead (the test's PC stand-in, `standin_slot76`), or as is on - WARP, `ffxCreateContext` and `ffxDestroyContext` both return OK. Device slots called: 14 (5), 15 (26), 18 (10), - 19 (16), **27 - `CreateCommittedResource` (4)**, **38 `GetCopyableFootprints` (4)**, 76 (10); heap slot 9 (26). So the console - device also serves the PC `CreateCommittedResource` at slot 27, and slots 14, 15, 18, 19, 27 and 38 keep their PC - positions for this client. No compute pipeline or root signature is created at context creation. - - On that context, one `ffxDispatch` recorded into a logging command list measures the **console command list**: - slots 14, 15, 25 and 26 are at their PC positions, then `SetDescriptorHeaps` is at 32 (PC 28), the compute root - setters four slots later (33, 35, 41; two of them inferred from their shapes), `ExecuteIndirect` two slots later - (61), and there are console-only methods at 85 and 141. The list object also carries a write cursor and limits - (`+0x18`, `+0x28`, `+0x30`) the DLL writes commands through while there is room. Table and evidence: - [d3d12_command_objects.md §3.5a](d3d12_command_objects.md). - Device slot 67 is a console-only compute-pipeline call, `DeserializeComputePipelineStateX` in the DLL's own - messages, not the PC method at that index; the proxy routes it to `CreateComputePipelineState`. The dispatch stops where the PC runtime - refuses the DLL's compute code at slot 62: the DLL's shaders carry an `ACCC` part instead of DXIL, an `FSPX` - payload with an RDNA2 program ([fspx.md](fspx.md)). The Vulkan device takes both forms at - `CreateComputePipelineState`: the `ACCC` container slot 62 gets, and the `FSPX` payload the proxy builds from the - slot-67 description's four pairs. It finds the translated module by `fspx_code_sha256` and `fspx_state_sha256` in - `/fspx/index.json`, which `make_game.py` writes ([fspx.md](fspx.md), "Build and run-time lookup"; - `d3d12_fspx_compute_test`). The pipeline answers the console slot 11 the DLL calls afterwards with 0, so no - compute scratch buffer is made ([d3d12_command_objects.md](d3d12_command_objects.md) §3.5a). Not run here: the - DLL's own dispatch on this device (`fsr_dispatch_test` needs MSVC structured exception handling). - - Its `throw 1` reaches the caller. Before #965 the throw carried an image base of 0, because `_CxxThrowException` - did not know manually mapped images; with #965 it carries the DLL's base, and the DLL still does not catch it on - that path (measured with `fsr_dispatch_test` and `LEONIDA_FSR_NO_STANDIN=1`). - - `xmem.dll!XMemGetWorkingSetStatistics` takes two arguments, `(0x20000001, stats*)`, at all seven call sites; - the one-argument shim wrote through the constant. Fixed in `runtime/shims/xmem.cpp`. - -### A.4 Other DLLs and the executable - -- `amd_fidelityfx_loader_xbox.dll`, `Bink2Scarlett.dll`, `libHttpClient.GDK.dll`, `XCurl.dll`: no `d3d12_xs` - imports. -- The package layout XML, chunk 1001, lists `game_scarlett_master.exe`; the file is absent from the folder. No - claim in this document depends on the executable's contents. -- The repository's existing import survey (`docs/design.md`, "Baseline already recorded") records that the 16 - bundled DLLs need only `xmem` and the two `d3d12_xs` root-signature calls; our scan of the six non-CRT DLLs is - consistent. - -## Appendix B: interface versions seen in shipped binaries - -| Interface | Evidence | Public methods beyond the previous version | -|---|---|---| -| `ID3D12Device11` | `XboxBvhBuilder.dll` constructor and rehydration signatures | `CreateSampler2` (public SDK) | -| `ID3D12GraphicsCommandList4` | standard BVH build/copy/validation signatures | `BeginRenderPass`/`EndRenderPass`, `BuildRaytracingAccelerationStructure`, `EmitRaytracingAccelerationStructurePostbuildInfo`, `CopyRaytracingAccelerationStructure`, `DispatchRays`, `SetPipelineState1` | -| `ID3D12GraphicsCommandList6` | batched BVH build signature | `DispatchMesh` | -| `ID3D12GraphicsCommandList8` | batched rehydration signatures | `OMSetFrontAndBackStencilRef` | - -The public Xbox graphics index retrieved for this document lists interfaces up to `ID3D12Device10` and -`ID3D12GraphicsCommandList7`; the shipped DLL names `Device11` and `CommandList8`, which the index does not cover. -This is why the layer targets the Windows SDK's newer public chain rather than assuming the Xbox public index is -complete. diff --git a/docs/d3d12_xs_surface.md b/docs/d3d12_xs_surface.md deleted file mode 100644 index 4e4b018d4..000000000 --- a/docs/d3d12_xs_surface.md +++ /dev/null @@ -1,786 +0,0 @@ -# The measured `d3d12_xs` surface, from SCARAB - -Status: reference, sourced. This page records what SCARAB measured about the Xbox Series -`d3d12_xs.dll` ABI, checks those claims against the files and the Windows SDK, and states what -Leonida can use. It does **not** adopt SCARAB's forwarding architecture: Leonida translates D3D12 -to Vulkan, while SCARAB forwards to PC `d3d12.dll` / vkd3d-proton. Only ABI facts, IID values and -call-sequence constraints are taken from it. No SCARAB code is copied. - -Source pin: `p-portela/SCARAB` at commit `d304fa26c0292e2f3ba76f23b15c9f30734bec02` -(2026-11-21), read-only clone. Licence: GPL-3.0-only; see §11. - -Verification environment: Windows SDK 10.0.26100.0 headers, plus a read-only inventory of the -local 1.0.2.1 package (the 16 DLL export tables, and the `gameos.xvd` header, entropy and string -scan). No `d3d12_xs.dll` or game data was opened for this page, and no Wine run was made. Where a -statement depends on SCARAB's vendor DLL, it is marked **Reported** and cannot be reproduced from -either repository. - -Confidence legend, consistent with [d3d12_vulkan.md](d3d12_vulkan.md): - -- **Verified** — checked here against a committed file or the Windows SDK headers. -- **Reported** — SCARAB states it from a vendor binary that is not in either repository. -- **Derived** — follows from a documented rule plus stated anchors; the derivation is shown. -- **Open** — no evidence. - -## 1. What the runtime is - -SCARAB identifies `d3d12_xs.dll` as a 51,576-byte, PE32+ x86-64 front end -(`FileVersion 10.0.26100.6247`, product string `... D3D12.CONSOLE Runtime Library for Offline -PC`) that loads a user-mode driver at runtime. Its only non-CRT import is `KERNEL32.dll`. That is -why 116 exports fit in 51 KB: the implementation is in the UMD, not in this DLL -([`docs/d3d12_xs-findings.md:5-45`](https://github.com/p-portela/SCARAB/blob/d304fa2/docs/d3d12_xs-findings.md)). -For a replacement DLL, the export table is therefore the complete free-function contract. -SCARAB de-brands platform names throughout, so its quoted strings use "console" where the vendor -string would carry the platform name; §2.3 covers the consequence for export names. - -SCARAB also measured that the console runtime and the PC D3D12 runtime define the same COM -interfaces: 28 `IID_*` data exports that exist on both sides are byte-identical. That is the fact -that makes the standard D3D12 surface forwardable rather than reimplementable — and for Leonida it -means a `QueryInterface` for a standard interface can be answered with the PC GUID without a -translation table. - -Scope limit: the "28" are the *D3D12* IIDs compared against the D3D12 headers. The runtime also -exports 55 other standard GUIDs (D3D11, DXGI, `ID3D10Blob`, debug GUIDs). §3 checks all 83. - -## 2. The export contract: 116 = 23 functions + 93 GUID data - -SCARAB's plan records the composition as 23 functions and 93 GUID data exports -([`docs/plans/2026-11-21-translation-layer-architecture.md:30`](https://github.com/p-portela/SCARAB/blob/d304fa2/docs/plans/2026-11-21-translation-layer-architecture.md)). -The 93 is internally consistent: 5 `DXGI_DEBUG_*` + `IID_ID3D10Blob` + 43 D3D11/DXGI IIDs at -29–71 + 28 D3D12 IIDs at 72–99 + 16 IIDs at 100–115 = 93, and -`components/runtime-bridge/src/iid_table.cpp:104` declares `scarab_iid_count = 93` with exactly -93 definitions. - -### 2.1 The 23 function exports - -Ordinals are documented in -[`docs/d3d12-xs-bridge.md:99-113`](https://github.com/p-portela/SCARAB/blob/d304fa2/docs/d3d12-xs-bridge.md) -and the individual stubs in -[`components/runtime-bridge/src/d3d12_xs_bridge.cpp`](https://github.com/p-portela/SCARAB/blob/d304fa2/components/runtime-bridge/src/d3d12_xs_bridge.cpp). -"Leonida today" describes `runtime/shims/d3d12_xs.cpp` at the time of writing. - -| # | Export (SCARAB's spelling) | Kind | Leonida today | Note | -|---:|---|---|---|---| -| 1 | `D3D12ZeroMemoryX` | console | absent | console fast-zero; `memset` is equivalent | -| 2 | `PixGetPixieEntryPoints` | console (PIX) | absent | no PIX path | -| 3 | `D3D10CreateBlob` | console (D3D10) | absent | local `ID3D10Blob`; no D3D10 dependency needed | -| 4 | `D3D12ConfigureVirtualMemoryX` | console | present (returns `S_OK`) | VM policy; PC/Vulkan owns it. Measured: one pointer argument (a zeroed 32-byte block, dword +4 set to a count); the title only tests the result for failure | -| 5 | `D3D12CreateDevice` | standard | **absent** | Leonida exports only the Xbox entry point; see §2.3 | -| 6 | `D3D12CreateRootSignatureDeserializer` | standard | present | forwarded | -| 7 | `D3D12CreateVersionedRootSignatureDeserializer` | standard | absent | forward if imported | -| 8 | `D3D12EnableExperimentalFeatures` | standard | absent | forward if imported | -| 9 | `D3D12GetDebugInterface` | standard | absent | forward if imported | -| 10 | `D3D12SerializeRootSignature` | standard | present | forwarded, flags cleared on a copy | -| 11 | `D3D12SerializeVersionedRootSignature` | standard | present | forwarded, flags cleared on a copy | -| 12 | `D3D12UploadCustomMicrocodeX` | console | absent | **the shader seam**: hands pre-compiled microcode to the driver | -| 13 | `D3D12ConsCreateDevice` | console | present as `D3D12XboxCreateDevice` | same call shape; see §2.3 on the name | -| 14 | `D3D12ConsEnableMemoryProfiling` | console | absent | record / no-op | -| 15 | `D3D12ConsGetProcessDebugFlags` | console | absent | record | -| 16 | `D3D12ConsSetProcessDebugFlags` | console | absent | record | -| 17 | `D3D12ConsUnloadDriverModule` | console | absent | no UMD to unload; no-op | -| 18 | `D3DFlushEntireCpuCache` | console | absent | fence-equivalent | -| 19 | `DXGIXGetFrameStatistics` | console present | absent | no PC/Vulkan equivalent | -| 20 | `DXGIXPresentArray` | console present | absent | presents an *array* of swapchains | -| 21 | `DXGIXSetFrameNotification` | console present | absent | frame notification | -| 22 | `DXGIXSetVLineNotification` | console present | absent | scanline/vblank notification | -| 116 | `InternalDriverCallX` | console private | absent | runtime↔UMD escape hatch; nothing to forward to | - -The seven standard functions are 5–11. The other sixteen are console-only. Leonida serves four of -the twenty-three today (6, 10, 11, 13). Any function in the table other than those four is an -unimplemented import if the game imports it; the PE loader's dry-run report (`docs/runtime_imports.md` -on the runtime-imports branch) is the place to see it. - -### 2.2 The 93 GUID data exports - -Ordinals 23–71 and 100–115 are documented per entry in -[`components/extension-wrapper/src/iid_console.inc`](https://github.com/p-portela/SCARAB/blob/d304fa2/components/extension-wrapper/src/iid_console.inc). -Ordinals 23–28 and 72–99 are derived in §2.4. Names are SCARAB's; the 10 console-only GUIDs are in -§4. "Std" marks a GUID that is also defined by the Windows SDK; all 83 were checked in §3. The -order within 23–27 is inferred and immaterial: those are debug GUIDs, not interfaces a title QIs -for. - -The 93 are the documented GUID data exports. They do **not** include the four console -command-list IIDs in §4: SCARAB's provenance note says the runtime does not export them, so they -have no ordinal here and are absent from this export dump. - -| # | GUID export | Std | Evidence | -|---:|---|---|---| -| 23 | `DXGI_DEBUG_ALL` | yes | derived (debug block, alphabetical) | -| 24 | `DXGI_DEBUG_APP` | yes | derived | -| 25 | `DXGI_DEBUG_D3D11` | yes | derived | -| 26 | `DXGI_DEBUG_DX` | yes | derived | -| 27 | `DXGI_DEBUG_DXGI` | yes | derived | -| 28 | `IID_ID3D10Blob` | yes | derived (only unplaced name; by elimination) | -| 29 | `IID_ID3D11Asynchronous` | yes | documented | -| 30 | `IID_ID3D11BlendState` | yes | documented | -| 31 | `IID_ID3D11BlendState1` | yes | documented | -| 32 | `IID_ID3D11Buffer` | yes | documented | -| 33 | `IID_ID3D11ClassInstance` | yes | documented | -| 34 | `IID_ID3D11ClassLinkage` | yes | documented | -| 35 | `IID_ID3D11CommandList` | yes | documented | -| 36 | `IID_ID3D11ComputeShader` | yes | documented | -| 37 | `IID_ID3D11Counter` | yes | documented | -| 38 | `IID_ID3D11CounterSampleX` | **no** | documented | -| 39 | `IID_ID3D11CounterSetX` | **no** | documented | -| 40 | `IID_ID3D11DepthStencilState` | yes | documented | -| 41 | `IID_ID3D11DepthStencilView` | yes | documented | -| 42 | `IID_ID3D11Device` | yes | documented | -| 43 | `IID_ID3D11Device1` | yes | documented | -| 44 | `IID_ID3D11DeviceChild` | yes | documented | -| 45 | `IID_ID3D11DeviceContext` | yes | documented | -| 46 | `IID_ID3D11DeviceContext1` | yes | documented | -| 47 | `IID_ID3D11DeviceContextX` | **no** | documented | -| 48 | `IID_ID3D11DeviceX` | **no** | documented | -| 49 | `IID_ID3D11DmaEngineContextX` | **no** | documented | -| 50 | `IID_ID3D11DomainShader` | yes | documented | -| 51 | `IID_ID3D11GeometryShader` | yes | documented | -| 52 | `IID_ID3D11HullShader` | yes | documented | -| 53 | `IID_ID3D11InputLayout` | yes | documented | -| 54 | `IID_ID3D11PerformanceContextX` | **no** | documented | -| 55 | `IID_ID3D11PerformanceDeviceX` | **no** | documented | -| 56 | `IID_ID3D11PixelShader` | yes | documented | -| 57 | `IID_ID3D11Predicate` | yes | documented | -| 58 | `IID_ID3D11Query` | yes | documented | -| 59 | `IID_ID3D11RasterizerState` | yes | documented | -| 60 | `IID_ID3D11RasterizerState1` | yes | documented | -| 61 | `IID_ID3D11RenderTargetView` | yes | documented | -| 62 | `IID_ID3D11Resource` | yes | documented | -| 63 | `IID_ID3D11SamplerState` | yes | documented | -| 64 | `IID_ID3D11ShaderResourceView` | yes | documented | -| 65 | `IID_ID3D11Texture1D` | yes | documented | -| 66 | `IID_ID3D11Texture2D` | yes | documented | -| 67 | `IID_ID3D11Texture3D` | yes | documented | -| 68 | `IID_ID3D11UnorderedAccessView` | yes | documented | -| 69 | `IID_ID3D11UserDefinedAnnotationX` | **no** | documented | -| 70 | `IID_ID3D11VertexShader` | yes | documented | -| 71 | `IID_ID3D11View` | yes | documented | -| 72 | `IID_ID3D12CommandAllocator` | yes | derived | -| 73 | `IID_ID3D12CommandList` | yes | derived | -| 74 | `IID_ID3D12CommandQueue` | yes | derived | -| 75 | `IID_ID3D12CommandSignature` | yes | derived | -| 76 | `IID_ID3D12Debug` | yes | derived; **anchored** by `iid_provenance.json` | -| 77 | `IID_ID3D12DescriptorHeap` | yes | derived | -| 78 | `IID_ID3D12Device` | yes | derived | -| 79 | `IID_ID3D12Device1` | yes | derived | -| 80 | `IID_ID3D12Device2` | yes | derived | -| 81 | `IID_ID3D12Device3` | yes | derived | -| 82 | `IID_ID3D12Device4` | yes | derived | -| 83 | `IID_ID3D12DeviceChild` | yes | derived | -| 84 | `IID_ID3D12Fence` | yes | derived | -| 85 | `IID_ID3D12Fence1` | yes | derived | -| 86 | `IID_ID3D12GraphicsCommandList` | yes | derived | -| 87 | `IID_ID3D12GraphicsCommandList1` | yes | derived | -| 88 | `IID_ID3D12GraphicsCommandList2` | yes | derived | -| 89 | `IID_ID3D12Heap` | yes | derived | -| 90 | `IID_ID3D12Object` | yes | derived | -| 91 | `IID_ID3D12Pageable` | yes | derived | -| 92 | `IID_ID3D12PipelineLibrary` | yes | derived | -| 93 | `IID_ID3D12PipelineLibrary1` | yes | derived | -| 94 | `IID_ID3D12PipelineState` | yes | derived | -| 95 | `IID_ID3D12Resource` | yes | derived | -| 96 | `IID_ID3D12RootSignature` | yes | derived | -| 97 | `IID_ID3D12RootSignatureDeserializer` | yes | derived | -| 98 | `IID_ID3D12Tools` | yes | derived | -| 99 | `IID_ID3D12VersionedRootSignatureDeserializer` | yes | derived | -| 100 | `IID_ID3D12ConsDmaCommandList` | **no** | documented; pinned out of alphabetical order | -| 101 | `IID_ID3DDeviceContextState` | yes | documented | -| 102 | `IID_IDXGIAdapter` | yes | documented | -| 103 | `IID_IDXGIAdapter1` | yes | documented | -| 104 | `IID_IDXGIAdapter2` | yes | documented | -| 105 | `IID_IDXGIDevice` | yes | documented | -| 106 | `IID_IDXGIDevice1` | yes | documented | -| 107 | `IID_IDXGIDevice2` | yes | documented | -| 108 | `IID_IDXGIDeviceSubObject` | yes | documented | -| 109 | `IID_IDXGIFactory` | yes | documented | -| 110 | `IID_IDXGIFactory1` | yes | documented | -| 111 | `IID_IDXGIFactory2` | yes | documented | -| 112 | `IID_IDXGIObject` | yes | documented | -| 113 | `IID_IDXGISwapChain` | yes | documented | -| 114 | `IID_IDXGISwapChain1` | yes | documented | -| 115 | `IID_IGraphicsUnknown` | **no** | documented | - -### 2.3 The published names are not all wire names - -This matters if the table is used to build a replacement DLL. SCARAB deliberately de-brands the -vendor token: - -- `tools/gen_def.py` derives the console-only token from the export table, then emits - `EXPORTS =` using `OUR_TOKEN = "Cons"` - ([`tools/gen_def.py:2-24,38,149-183`](https://github.com/p-portela/SCARAB/blob/d304fa2/tools/gen_def.py)). - The generated `.def` is **not committed**; it is built from the user-supplied vendor DLL. -- The bridge source defines `D3D12ConsCreateDevice` and `D3D12Cons*` symbols - ([`d3d12_xs_bridge.cpp:451-475`](https://github.com/p-portela/SCARAB/blob/d304fa2/components/runtime-bridge/src/d3d12_xs_bridge.cpp)). -- The string `Xbox` does not occur anywhere in SCARAB's tree, and the README contains the - tell-tale "an console Series" — the tree was mechanically de-branded before the first commit. - -Therefore `D3D12ConsCreateDevice` (ordinal 13) and the other four `D3D12Cons*` exports are -SCARAB's internal spellings, not evidence of the runtime's export names. Leonida already uses -`D3D12XboxCreateDevice`, which is the public GDK name and the same call shape -(`adapter, params, riid, out`). That is the likely wire name, but it should be confirmed from the -game's import table. The same caveat applies to `IID_ID3D12ConsDmaCommandList`: the GUID in §4 is -the fact; the spelling may be de-branded. - -The other 18 function names and all 83 standard GUID names carry no token and can be used as -published. - -### 2.4 How ordinals 72–99 were recovered - -SCARAB does not publish a per-ordinal map for the 28 standard D3D12 IIDs. The map is derivable -because the runtime's GUID exports behave as if they were ordered alphabetically by name, with one -deliberate exception: - -- Sort the 93 GUID export names. `23 + index` matches **58 of the 59** ordinals documented in - `iid_console.inc`. The single mismatch is `IID_ID3D12ConsDmaCommandList`: documented at 100, - alphabetically at 76. -- SCARAB's own provenance correction says the IID at the runtime's table slot 47 is - `IID_ID3D12Debug`, **exported at ordinal 76** - ([`components/extension-wrapper/iid_provenance.json:2`](https://github.com/p-portela/SCARAB/blob/d304fa2/components/extension-wrapper/iid_provenance.json)). - Alphabetical placement of the 28 standard names puts `IID_ID3D12Debug` at 76. The anchor and the - rule agree. -- With `IID_ID3D12ConsDmaCommandList` pinned at 100, the remaining 15 names at 101–115 are again - alphabetical, and 72–99 are exactly the 28 standard D3D12 IIDs in alphabetical order. -- 23–28 follow by the same rule: 23–27 are the five `DXGI_DEBUG_*` GUIDs and 28 is - `IID_ID3D10Blob`, the only GUID name not otherwise placed. - -Confidence: **Derived**. The 23 function ordinals, the 59 documented IID ordinals, and the 28+10 -IID values are **Verified** (the values against the SDK in §3; the console values are **Reported** -by SCARAB). If a real export table ever contradicts 72–99, the derivation is what is wrong, not -the rest of the table. - -A second lesson from the same data: the runtime exports IIDs only up to `ID3D12Device4`, -`ID3D12GraphicsCommandList2`, `ID3D12Fence1` and `ID3D12PipelineLibrary1`. That is a property of -the *exported IID table*, not proof that the console device stops at those interface versions — -the shipped `XboxBvhBuilder.dll` names `ID3D12Device11` and `ID3D12GraphicsCommandList4/6/8` -(see [d3d12_vulkan.md](d3d12_vulkan.md) Appendix B). Do not use the absence of newer IIDs from -this table to bound the game's interface use. - -## 3. Standard IIDs: 28/28 holds, and 83/83 is the stronger measured fact - -SCARAB's headline is exact: the 28 D3D12 `IID_*` values it extracted from the console runtime are -byte-identical to the PC headers. I checked all 28 against the Windows SDK 10.0.26100.0 on this -machine: 27 are in `um/d3d12.h` and `IID_ID3D12Debug` is in `um/d3d12sdklayers.h`; all 28 match -byte-for-byte. SCARAB's claim that they match "the PC Agility SDK headers" is therefore true, with -the nuance that one of the 28 is a debug-layer IID, not a `d3d12.h` IID. - -The check extends further. SCARAB's `iid_table.cpp` also reproduces 49 standard D3D11/DXGI IIDs, -`IID_ID3D10Blob`, and 5 `DXGI_DEBUG_*` GUIDs. All **78 standard IIDs + 5 debug GUIDs = 83/83** -match the SDK headers (`d3d11*.h`, `dxgi*.h`, `dxgi1_*.h`, `d3dcommon.h`, `dxgidebug.h`, -`d3d11sdklayers.h`, `d3d12sdklayers.h`). The 10 console-only GUIDs are absent from the SDK. - -The chain of evidence has two links, and only one is checkable here. This page checks -**SCARAB's table against the SDK**. SCARAB's gate G1 checks **its table against the vendor -runtime** (`93/93` GUID bytes); that gate needs the vendor DLL and was not run here. So the -correct statement is: SCARAB's table is exactly the PC SDK's standard GUID set, and SCARAB reports -that the table is byte-identical to the runtime's. The second link is **Reported**, not verified -in this session. - -Reproduce the first link: - -``` -python tools/d3d12_xs_surface.py --check --sdk -python tools/d3d12_xs_surface.py --check --sdk --scarab -python -I tests/test_d3d12_xs_surface.py -``` - -The first command checks the 116-slot table and the 83 standard GUIDs against the installed SDK. -The second also compares all 93 values and the 59 documented ordinals against a SCARAB checkout. -The third is the standalone test; `pytest tests/test_d3d12_xs_surface.py` works where pytest is -installed. - -Consequences for Leonida: - -- A QI for any standard interface can be answered with the SDK GUID. No translation table is - needed, and a captured GUID can be looked up directly in the SDK headers. -- The 28-IID claim understates the evidence. If the game uses D3D11 on the console — SCARAB's - open question 1 — the existing D3D11/DXGI IIDs are the PC ones too. Leonida still lists D3D11 - as a non-goal, so this is information, not a work item. -- The GUID values are facts about the runtime; for the 83 standard GUIDs, the *names* come from - the SDK and are not proprietary. - -The 28 D3D12 values, for reference (all verified): - -| IID | GUID | -|---|---| -| `IID_ID3D12CommandAllocator` | `6102dee4-af59-4b09-b999-b44d73f09b24` | -| `IID_ID3D12CommandList` | `7116d91c-e7e4-47ce-b8c6-ec8168f437e5` | -| `IID_ID3D12CommandQueue` | `0ec870a6-5d7e-4c22-8cfc-5baae07616ed` | -| `IID_ID3D12CommandSignature` | `c36a797c-ec80-4f0a-8985-a7b2475082d1` | -| `IID_ID3D12Debug` | `344488b7-6846-474b-b989-f027448245e0` | -| `IID_ID3D12DescriptorHeap` | `8efb471d-616c-4f49-90f7-127bb763fa51` | -| `IID_ID3D12Device` | `189819f1-1db6-4b57-be54-1821339b85f7` | -| `IID_ID3D12Device1` | `77acce80-638e-4e65-8895-c1f23386863e` | -| `IID_ID3D12Device2` | `30baa41e-b15b-475c-a0bb-1af5c5b64328` | -| `IID_ID3D12Device3` | `81dadc15-2bad-4392-93c5-101345c4aa98` | -| `IID_ID3D12Device4` | `e865df17-a9ee-46f9-a463-3098315aa2e5` | -| `IID_ID3D12DeviceChild` | `905db94b-a00c-4140-9df5-2b64ca9ea357` | -| `IID_ID3D12Fence` | `0a753dcf-c4d8-4b91-adf6-be5a60d95a76` | -| `IID_ID3D12Fence1` | `433685fe-e22b-4ca0-a8db-b5b4f4dd0e4a` | -| `IID_ID3D12GraphicsCommandList` | `5b160d0f-ac1b-4185-8ba8-b3ae42a5a455` | -| `IID_ID3D12GraphicsCommandList1` | `553103fb-1fe7-4557-bb38-946d7d0e7ca7` | -| `IID_ID3D12GraphicsCommandList2` | `38c3e585-ff17-412c-9150-4fc6f9d72a28` | -| `IID_ID3D12Heap` | `6b3b2502-6e51-45b3-90ee-9884265e8df3` | -| `IID_ID3D12Object` | `c4fec28f-7966-4e95-9f94-f431cb56c3b8` | -| `IID_ID3D12Pageable` | `63ee58fb-1268-4835-86da-f008ce62f0d6` | -| `IID_ID3D12PipelineLibrary` | `c64226a8-9201-46af-b4cc-53fb9ff7414f` | -| `IID_ID3D12PipelineLibrary1` | `80eabf42-2568-4e5e-bd82-c37f86961dc3` | -| `IID_ID3D12PipelineState` | `765a30f3-f624-4c6f-a828-ace948622445` | -| `IID_ID3D12Resource` | `696442be-a72e-4059-bc79-5b5c98040fad` | -| `IID_ID3D12RootSignature` | `c54a6b66-72df-4ee8-8be5-a946a1429214` | -| `IID_ID3D12RootSignatureDeserializer` | `34ab647b-3cc8-46ac-841b-c0965645c046` | -| `IID_ID3D12Tools` | `7071e1f0-e84b-4b33-974f-12fa49de65c5` | -| `IID_ID3D12VersionedRootSignatureDeserializer` | `7f91ce67-090c-4bb7-b78e-ed8ff2e31da0` | - -## 4. Console-only IIDs - -Ten IIDs exported by the runtime are absent from the Windows SDK. Values are **Reported** by -SCARAB from the vendor runtime's export table; the ordinal is from `iid_console.inc`, so it is -**Verified** against SCARAB's file, not against the vendor binary. - -| Ordinal | IID | GUID | What it is | Leonida relevance | -|---:|---|---|---|---| -| 100 | `IID_ID3D12ConsDmaCommandList` | `30bc77b9-8379-4b25-95de-b8588c42275d` | DMA command-list interface | **High.** If the game creates a DMA list, this is the IID it passes to `CreateCommandList` | -| 115 | `IID_IGraphicsUnknown` | `aceeea63-e0a9-4a1c-bbec-71b2f485f758` | unknown purpose | Do not invent a vtable; log and refuse | -| 48 | `IID_ID3D11DeviceX` | `177700f9-876a-4436-b368-36a604f82cef` | D3D11 device extension | Out of scope (D3D11 is a non-goal) | -| 47 | `IID_ID3D11DeviceContextX` | `48800095-7134-4be7-9186-b86becb26477` | D3D11 context extension | Out of scope | -| 49 | `IID_ID3D11DmaEngineContextX` | `a6332ddb-8e02-427d-b0b7-34a1e61a6488` | D3D11 DMA engine | Out of scope | -| 54 | `IID_ID3D11PerformanceContextX` | `9458fe06-c78d-47f7-96a0-ec7b727be1e9` | D3D11 performance | Out of scope | -| 55 | `IID_ID3D11PerformanceDeviceX` | `88671610-712e-4f1e-84ab-01b5948bd373` | D3D11 performance | Out of scope | -| 69 | `IID_ID3D11UserDefinedAnnotationX` | `b2daad8b-03d4-4dbf-95eb-32ab4b63d0ab` | D3D11 annotation | Out of scope | -| 39 | `IID_ID3D11CounterSetX` | `f9f6a732-c5f8-4a57-ba36-eae7c27ba74a` | D3D11 counters | Out of scope | -| 38 | `IID_ID3D11CounterSampleX` | `806ceee4-280b-43d9-9008-b4fdf7febee2` | D3D11 counters | Out of scope | - -The four command-list IIDs are **not runtime exports** according to SCARAB's provenance, so they -have no row above and no ordinal: -`ID3D12ConsComputeCommandList`, `...6`, `...8`, and `ID3D12ConsCopyCommandList6`. SCARAB's -provenance note says they are "NOT exported by the runtime and are NOT recovered" and that a -`QueryInterface` for one is logged by the wrapper's audit hook -([`iid_provenance.json:13`](https://github.com/p-portela/SCARAB/blob/d304fa2/components/extension-wrapper/iid_provenance.json)). -This 1.0.2.1 package's own DLL export tables do not contain them either: its root has the 16 -middleware/CRT DLLs and no D3D12 runtime DLL, its layout XML lists no `d3d12_xs.dll`, the -executable that would call `QueryInterface` with them is absent, and `gameos.xvd` is an encrypted -XVD with a high-entropy payload and no plaintext `d3d12_xs.dll` name in ASCII or UTF-16 (measured -in [d3d12_command_objects.md](d3d12_command_objects.md) §1 and -[d3d12_vulkan.md](d3d12_vulkan.md) Appendix A.1). SCARAB also holds seven candidate v4 UUIDs -found 16-byte-aligned after `IID_ID3D12Device4` in the UMD's `.rdata` and marks them `CANDIDATE`, -not used. Do not use them or assign them by position. A QI for one of those interfaces must be -logged and refused until a title trace or another artifact supplies the GUID. - -The DMA IID is the load-bearing one. SCARAB's end-to-end test created a console DMA command list -through a PC D3D12 device and got an object that served both `IID_ID3D12ConsDmaCommandList` and -`IID_ID3D12GraphicsCommandList` -([`docs/d3d12-xs-wrapper.md:134-162`](https://github.com/p-portela/SCARAB/blob/d304fa2/docs/d3d12-xs-wrapper.md)). -That is **Reported** (Wine, no GPU). It proves the wrapper's QI routing, not the game's use of DMA -lists. - -## 5. The extension method surface - -SCARAB's catalogue has 105 rows labelled `method` and 106 labelled `enum` -([`components/extension-wrapper/docs/console-extension-catalogue.tsv`](https://github.com/p-portela/SCARAB/blob/d304fa2/components/extension-wrapper/docs/console-extension-catalogue.tsv)). -The names were mined from the UMD's validation strings. Read the catalogue as a *name list for a -trace filter*, not as an ABI: - -- **At least 11 of the 105 "method" rows are not interface methods**: `UINT_MAX`, - `UINT64_MAX`, `DXGI_DEBUG_DX`, `D3D12_MESSAGE_ID_INVALID_NODE_INDEX`, - `D3D12CONS_PRESENT_PLANES_MAX`, `D3D12CONS_PRESENT_VIEWS_MAX` (both also in the enum list), - `UMDInternalDriverCallX` (a UMD export), `WorldRayOriginX`, `WorldRayDirectionX`, - `DispatchRaysDimensionsX` (DXR builtin names), and `TopLeftX` (not a method-shaped name). That - leaves at most 94 plausible methods, which is consistent with the wrapper document's own "~95". -- The counts drift between files: 105/106 in the TSV and the wrapper doc; 104/108 in - `console_extensions.h:8`; "60 console-specific GUIDs" in `wrap.cpp:84` against 59 entries in - `iid_console.inc`. None of these is a measurement of the ABI; they are documentation drift. -- Only 10 methods are class-attributed by a UMD message naming the interface, and 6 more by call - sites in the console SDK samples - ([`docs/d3d12-xs-wrapper.md:69-97`](https://github.com/p-portela/SCARAB/blob/d304fa2/docs/d3d12-xs-wrapper.md)). - The rest are unattributed, and the **order within the appended block is not recovered**. -- SCARAB's own honesty rule is right and worth keeping: every appended slot logs its name and raw - arguments, and unknown slots log their index, so a wrong order is diagnosable. - -SCARAB's wrapper class derives from the genuine `ID3D12Device4` and -`ID3D12GraphicsCommandList6` interfaces and marks every forwarded method `override`, so the -compiler proves **53 device and 76 command-list** signatures against the real `d3d12.h` -([`docs/d3d12-xs-wrapper.md:53-63`](https://github.com/p-portela/SCARAB/blob/d304fa2/docs/d3d12-xs-wrapper.md)). -That proves the PC-side vtable layout of its wrapper; it says nothing about the appended console -block, which is the part Leonida must not copy. - -Class placement that is evidence-backed: - -| Class | Methods | Evidence | -|---|---|---| -| device | `CreateCommandQueueX`, `GetFrameStatisticsX`, `ScheduleFrameEventX`, `SetFrameIntervalX`, `SetDebugErrorFilterX`, `WaitFrameEventX` | UMD messages name the interface; the samples call `SetFrameIntervalX` 122, `ScheduleFrameEventX` 122 and `WaitFrameEventX` 121 times on the device | -| queue | `PresentX`, `SuspendX`, `ResumeX` | UMD names `ID3D12CommandQueue::PresentX`; the samples call `PresentX` 367, `SuspendX` 122, `ResumeX` 122 times on the queue | -| DMA list | `FillRawBuffer`, `CopyResource` | UMD names `ID3D12ConsDmaCommandList::FillRawBuffer` | -| graphics list | `RSSetDepthBiasX`, `OMSetSampleMaskX`, `OMSetFrontAndBackStencilRef`, `FillMemoryWithPattern` | UMD messages | -| unattributed | the other ~90 names | strings only | - -**Do not copy the appended order.** Leonida implements the public vtable chain; an unknown X -method should be logged with its slot and arguments and refused, exactly as SCARAB does, until the -game's trace identifies it. - -### 5.1 Some "console extensions" are public D3D12 methods - -This is the most useful correction in the whole comparison. SCARAB's wrapper derives from -`ID3D12GraphicsCommandList6`, so it treats anything added to D3D12 later as a console extension. -The Windows SDK 10.0.26100.0 has since promoted several of these names: - -| SCARAB catalogue name | Public method in SDK 10.0.26100.0 | Consequence | -|---|---|---| -| `OMSetFrontAndBackStencilRef` | `ID3D12GraphicsCommandList8::OMSetFrontAndBackStencilRef(UINT, UINT)` (`d3d12.h:32819`) | identical signature; it is the GCL8 slot, not an appended slot | -| `RSSetDepthBiasX` | `ID3D12GraphicsCommandList9::RSSetDepthBias(FLOAT, FLOAT, FLOAT)` (`d3d12.h:33680`) | SCARAB declares `INT` for the first argument and says "no command-list state to set"; both are wrong for the 26100 header | -| `OMSetDepthBoundsX` | `ID3D12GraphicsCommandList1::OMSetDepthBounds(FLOAT, FLOAT)` (`d3d12.h:7237`) | a base-D3D12 method; the X variant may add something, but "no PC equivalent" needs proof | -| `RSSetShadingRateX` | `ID3D12GraphicsCommandList5::RSSetShadingRate(...)` (`d3d12.h:30278`) | same | -| `DispatchMeshX` | `ID3D12GraphicsCommandList6::DispatchMesh(UINT, UINT, UINT)` (`d3d12.h:31126`) | same | - -The lesson is not that the catalogue is useless; it is that a name with an `X` suffix is not proof -of a console-only method. Check every name against the SDK version the game was compiled against -before treating it as new. For `OMSetFrontAndBackStencilRef` the signature is identical, so a -GCL8-compiled game calls it at the public slot; SCARAB's placement after GCL6 would land in the -wrong slot. Leonida's public-chain command list already has it at GCL8. - -## 6. Command lists and `CreateCommandList` - -The one measured console command-list rule, quoted from the UMD: - -> `CreateCommandList: An riid of __uuidof(ID3D12ConsDmaCommandList) is required for -> D3D12CONS_COMMAND_LIST_TYPE_DMA.` - -SCARAB records `D3D12CONS_COMMAND_LIST_TYPE_DMA = 6` -([`console_extensions.h:45-47`](https://github.com/p-portela/SCARAB/blob/d304fa2/components/extension-wrapper/console_extensions.h)). -The *name* is evidence-backed; the value 6 is **Derived** from appending to the PC enum (0–5), not -measured. It is a strong inference, but treat it as a hypothesis until the game's -`CreateCommandList` call is traced. - -SCARAB's interception logic -([`wrap.cpp:279-326`](https://github.com/p-portela/SCARAB/blob/d304fa2/components/extension-wrapper/src/wrap.cpp)): - -- if `type == 6`, map it to PC `D3D12_COMMAND_LIST_TYPE_COPY` and require the DMA IID; -- otherwise create the list normally; -- prefer `CreateCommandList1` and `Reset` to apply the initial state; -- return a wrapper that serves the DMA IID only for DMA lists. - -For Leonida, the transferable facts are the rule and the IID, not the wrapper: - -- On `CreateCommandList`, log `(nodeMask, type, riid)` once. If `type` is outside 0–5, or `riid` is - not a standard GCL IID, treat it as a console list. -- If `type == 6` **and** `riid == 30bc77b9-8379-4b25-95de-b8588c42275d`, implement it as a copy - list (Vulkan transfer queue / transfer-only command buffer). If the IID is anything else, log - the GUID and refuse; SCARAB reports that the compute/copy console IIDs are not runtime exports - and they are not known. -- `D3D12CONS_COMMAND_LIST_FLAG_ENABLE_IB_CHAINING` is a recovered name (value unknown). A console - list flag must not be passed to `vkCmd...` as if it were a D3D12 flag. -- The console also has `ID3D12ConsComputeCommandList` (and 6/8 variants) and - `ID3D12ConsCopyCommandList6`, plus `D3D12ConsRehydrateRaytracingAccelerationStructure` - ([`docs/d3d12-xs-bridge.md:239-245`](https://github.com/p-portela/SCARAB/blob/d304fa2/docs/d3d12-xs-bridge.md)). - Their IIDs are not runtime exports according to SCARAB, so this package's export tables cannot - supply them; the values and the layouts are **Open**. - -What this does not tell us: the slot of `CreateCommandList` in the console device vtable (Leonida -already measures device slot 14/62/76 independently), the real numeric value of the DMA type, or -whether the game uses DMA lists at all. It is a conditional branch to add to the trace, not a -proven path. - -## 7. Presentation: `PresentX`, `DXGIX*`, frame events - -This is where the expectation that SCARAB closes Leonida's §7 list is **not** met. SCARAB gives -names and constraints, not signatures, slots or a working present path. - -What is evidence-backed: - -- `PresentX` is an `ID3D12CommandQueue` method. The UMD message is quoted as - `ID3D12CommandQueue::PresentX - pPlaneParameters[%d].ResourceCount must currently be less than - or equal to 2`, and the console SDK samples call it on the queue (367 sites) - ([`docs/d3d12-xs-wrapper.md:79-97`](https://github.com/p-portela/SCARAB/blob/d304fa2/docs/d3d12-xs-wrapper.md)). -- Present flags are named `D3D12CONS_PRESENT_FLAG_NONE`, `_IMMEDIATE`, `_PERSIST`, - `_UNIQUE_VIEW_RESOURCES`; `D3D12CONS_PRESENT_PLANES_MAX = 2` and - `D3D12CONS_PRESENT_VIEWS_MAX = 8` - ([`console_extensions.h:62-72`](https://github.com/p-portela/SCARAB/blob/d304fa2/components/extension-wrapper/console_extensions.h)). - The **values are not measured**: `console_extensions.h` assigns 0x1/0x2/0x4, while - `present_adapter.h:38-44` says the values are unknown and sets them all to 0. The two headers - contradict each other; use neither as an ABI. -- `DXGIXPresentArray`, `DXGIXSetFrameNotification`, `DXGIXSetVLineNotification` and - `DXGIXGetFrameStatistics` are **free functions** at ordinals 20, 21, 22 and 19 — not queue - methods. SCARAB's bridge implements them as recorded no-ops; `DXGIXGetFrameStatistics` zeroes - 64 bytes ([`d3d12_xs_bridge.cpp:520-551`](https://github.com/p-portela/SCARAB/blob/d304fa2/components/runtime-bridge/src/d3d12_xs_bridge.cpp)). - No parameter layouts are recovered. -- Device-side frame pacing names: `SetFrameIntervalX`, `ScheduleFrameEventX`, `WaitFrameEventX`, - `GetFrameStatisticsX`. The first three are called on the device in the samples; the enum names - `D3D12CONS_FRAME_EVENT_ORIGIN` and `D3D12CONS_SCHEDULE_FRAME_EVENT_FLAG_DISABLE_SIGNAL` exist. - Queue-side `SuspendX`/`ResumeX` exist. No signatures or slots. -- SCARAB's `present-adapter` is a seam only: its header proposes a swapchain registry and - `D3DKMTWaitForVerticalBlankEvent` for vblank, and its flag enum is all zeroes - ([`present_adapter.h:11-66`](https://github.com/p-portela/SCARAB/blob/d304fa2/components/present-adapter/include/present_adapter.h)). - Nothing is implemented. - -Public samples add the call shapes (not slots). From MIT/zlib code -([Xbox-GDK-Samples](https://github.com/microsoft/Xbox-GDK-Samples) SimpleDeviceAndSwapChain and FramePacing, -[directxtk12modelviewer](https://github.com/walbourn/directxtk12modelviewer), SDL2's Xbox D3D12 backend), as -collected in [d3d12_vulkan.md §4.5](d3d12_vulkan.md): - -- `PresentX(planeCount, planes, params)` on the queue, 3 arguments; plane fields `Token`, `ResourceCount`, - `ppResources`, `pSrcViewRects`, `ColorSpace`; 2 planes for HDR + GameDVR; `params` carries - `ImmediateThresholdPercent`. `SuspendX(0)` and `ResumeX()` on the queue. -- On the device: `SetFrameIntervalX` (4 args), `ScheduleFrameEventX` (4), `WaitFrameEventX` (5, returns a frame - token), `GetFrameStatisticsX` (4). Back buffers are committed resources with `ALLOW_DISPLAY`; DXGI is used - only for `IDXGIDevice1`→`GetAdapter`→`EnumOutputs`. No DXGI swapchain. - -Vtable slots and struct layouts are **not** unmeasured any more: public, licensed code and Microsoft's public -reference give most of them. Enum values are still mostly **unmeasured**. - -§8.2 question 6 ("DXGI, `PresentX`, or both") is **partly answered**: public GDKX code presents through -`PresentX` and frame events only. That the game does the same is a **hypothesis**; the game is not observed. -The call site must still be found by tracing the queue vtable beyond the public chain, not by guessing a -slot. The plan in [d3d12_vulkan.md §4.5](d3d12_vulkan.md) is now a `PresentX` + frame-event presenter first, -with DXGI factory/adapter/output enumeration kept and the DXGI swapchain as fallback. - -The `DXGIX*` free functions are a separate question. If the game imports them from `d3d12_xs.dll`, -Leonida's loader will report them as unimplemented; a Vulkan present-array implementation would -need a swapchain registry, which does not exist yet. SCARAB's no-op behavior is not acceptable for -Leonida because it would silently present nothing. - -### 7.1 Public sources for the presentation and device ABI - -Microsoft's public GDK graphics reference does not document the console interfaces. The -[graphics index](https://docs.xbox.com/_llms/en/apis/gdk-apis/graphics-api-reference.txt) lists 528 pages, -8 of them under `d3d12_xs` (six enums, `D3D10CreateBlob`, `DXGI_ADAPTER_DESC2`); the `ID3D12CommandQueue` -page lists the PC methods only, and there is no `PresentX`, `SetFrameIntervalX` or `D3D12XboxCreateDevice` -page, while the `D3D12_ROOT_SIGNATURE_FLAGS` pages return 404. The slots and layouts below therefore come from public code -that is not Microsoft documentation: XCL and the Microsoft samples measure other titles' runtimes, ebiten and -Mesa are public code compiled against the GDK headers, and docs.xbox.com is Microsoft's reference. - -| Item | Public source and value | Verdict on this repository's provisional value | -|---|---|---| -| Queue `PresentX` slot | `ivall/xcl` (GPL-2.0-only; facts only) dispatches `PresentX(planeCount, planes, params)` at queue slot **30** in the older runtime layout (XDefiant, Minecraft, Fortnite) and slot **32** in a newer one (Unicorn Overlord), with the same SDK version but two methods inserted before `Signal` ([`present.rs`](https://github.com/ivall/xcl/blob/95bda116cfc1b118156901984052ff5698dbf4cc/crates/xcl/src/hle/d3d12x/present.rs), [`real.rs`](https://github.com/ivall/xcl/blob/95bda116cfc1b118156901984052ff5698dbf4cc/crates/xcl/src/hle/d3d12x/real.rs), [`HANDOFF.md`](https://github.com/ivall/xcl/blob/95bda116cfc1b118156901984052ff5698dbf4cc/HANDOFF.md)). | **Confirms a slot, not one number.** The version moves it; trace the game's runtime, do not hard-code either value. | -| Queue `SuspendX` / `ResumeX` slots | No public slot in XCL or the samples. The signatures are `SuspendX(UINT flags)` and `ResumeX()` from the Apache-2.0 ebiten C++ binding ([`api_microsoftgdk_windows.go`](https://github.com/hajimehoshi/ebiten/blob/d438df689b19544c82543ad522b36be86a5a60b7/internal/graphicsdriver/directx/api_microsoftgdk_windows.go)); the samples call `SuspendX(0)` and `ResumeX()`. | **Leaves provisional.** | -| `D3D12XBOX_PRESENT_PLANE_PARAMETERS` | 0x48 bytes on x64: `Token` u64 @0x00, `ResourceCount` u32 @0x08, `ppResources` @0x10, `pSrcViewRects` @0x18, `pDestPlacementBase` @0x20 (four floats), `ColorSpace` int32 @0x28, `ScaleFilter` int32 @0x2C, `ExtendedDescCount` u32 @0x30, `pExtendedDescs` @0x38, `Flags` u32 @0x40. ebiten's Go mirror of the GDK struct ([`d3d12_windows.go`](https://github.com/hajimehoshi/ebiten/blob/d438df689b19544c82543ad522b36be86a5a60b7/internal/graphicsdriver/directx/d3d12_windows.go)); XCL independently reads token @0, count @8 and resource list @0x10 ([`present.rs`](https://github.com/ivall/xcl/blob/95bda116cfc1b118156901984052ff5698dbf4cc/crates/xcl/src/hle/d3d12x/present.rs)). | **Confirms** the field order, types and size in `xbox_present_types.h` and `xbox_present.h`. `ScaleFilter` and `Flags` values stay ours. | -| `D3D12XBOX_PRESENT_PARAMETERS` | 0x20 bytes on x64: `ImmediateThresholdPercent` float @0x00, `ViewCount` u32 @0x04, `ExtendedDescCount` u32 @0x08, `pExtendedDescs` @0x10, `Flags` u32 @0x18. Mesa's MIT Xbox WGL backend sets `Flags = D3D12XBOX_PRESENT_FLAG_IMMEDIATE` for an immediate present ([`d3d12_wgl_framebuffer_xbox.cpp`](https://github.com/openbsd/xenocara/blob/f3893fcf57cec33c2bd4275edd8ca6d865e3adf2/lib/mesa/src/gallium/winsys/d3d12/wgl/d3d12_wgl_framebuffer_xbox.cpp)); ebiten has the field order. The flag's numeric value is not public. | **Corrects** "at least this field": the repository's one-float struct is the first 4 bytes of a 0x20-byte object. Safe as a pointer prefix; never size a copy by it. | -| Device frame calls | Slots **78** `SetFrameIntervalX`, **79** `ScheduleFrameEventX`, **80** `WaitFrameEventX`, **81** `GetFrameStatisticsX` (0-based, `QueryInterface` = 0). XCL's [`frame.rs`](https://github.com/ivall/xcl/blob/95bda116cfc1b118156901984052ff5698dbf4cc/crates/xcl/src/hle/d3d12x/frame.rs) numbers the calls and documents the arguments; ebiten's `ID3D12Device` vtable has `SetFrameIntervalX`/`ScheduleFrameEventX`/`WaitFrameEventX` at 78/79/80 and leaves 81 unnamed ([`d3d12_windows.go`](https://github.com/hajimehoshi/ebiten/blob/d438df689b19544c82543ad522b36be86a5a60b7/internal/graphicsdriver/directx/d3d12_windows.go)). | **Confirms** all four slots, two independent public sources. | -| `D3D12XBOX_FRAME_STATISTICS` | The MIT FramePacing sample names `Type`, `Interval`, `Event`, `Render`/`Present`/`Display` with `PlaneIndex`, and `Display.PercentScanned`; it treats `S_FALSE` or a count below the request as "not available yet" ([`FramePacing.cpp`](https://github.com/microsoft/Xbox-GDK-Samples/blob/b1e77b6ac10f95b07296025fda171ca2ddc42dbe/Samples/Graphics/FramePacing/FramePacing.cpp)). XCL's implementation writes `Type` at +0, origin at +0x10 and flip at +0x18, so its record is at least 0x20 bytes ([`frame.rs`](https://github.com/ivall/xcl/blob/95bda116cfc1b118156901984052ff5698dbf4cc/crates/xcl/src/hle/d3d12x/frame.rs)). | **Partly confirms** the field meanings and the two timestamp offsets; the full record layout and the union members stay unmeasured. | -| Token and timeout | `D3D12XBOX_FRAME_PIPELINE_TOKEN` is a 64-bit integer with 0 as `..._NULL` (ebiten). Microsoft's Game Streaming page says `WaitFrameEventX` returns the token at frame start and `PresentX` sends it with the frame to the client ([Learn](https://learn.microsoft.com/en-us/gaming/gdk/docs/features/common/game-streaming/game-streaming-latency-compensation-deep-dive)). XCL's implementation issues 48-bit nonzero tokens (mask `0xFFFF_FFFF_FFFF`), i.e. it leaves the top 16 bits unused, returns `S_FALSE` on a finite timeout, writes the token on timeout only with flag 2, and returns `E_INVALIDARG` for an unscheduled event; `ScheduleFrameEventX` returns `S_FALSE` or `0x10000000` when it starts the clock. | **Confirms** the 64-bit storage and the `0` null. **Contradicts** this layer's `HRESULT_FROM_WIN32(WAIT_TIMEOUT)` on timeout (XCL: `S_FALSE`) and `ERROR_INVALID_STATE` for an unscheduled event (XCL: `E_INVALIDARG`); both are recorded here, not changed in this PR. The 48-bit range is XCL's implementation choice, not a documented mask. | -| `D3D12XBOX_CREATE_DEVICE_PARAMETERS` | Public field names and (for ebiten's version) x64 offsets: `Version` @0, `ProcessDebugFlags` @4, `GraphicsCommandQueueRingSizeBytes` @8, `pOffchipTessellationBuffer` @0x10, `GraphicsScratchMemorySizeBytes` @0x18, `ComputeScratchMemorySizeBytes` @0x1C, `DisableGeometryShaderAllocations` @0x20, `DisableTessellationShaderAllocations` @0x24, `DisableDXR` @0x28, `DisableAutomaticDPBBBreakBatchEvents` @0x2C, `pDXRStackBuffer` @0x30, `DXRStackBufferOverrideSizeBytes` @0x38, `CreateDeviceFlags` @0x3C, `AutoHDRPaperWhiteLevelNits` @0x40, `DisableAutomaticCommandSegmentChaining` @0x44 ([`d3d12_windows.go`](https://github.com/hajimehoshi/ebiten/blob/d438df689b19544c82543ad522b36be86a5a60b7/internal/graphicsdriver/directx/d3d12_windows.go)). The MIT samples add `AmplificationShaderIndirectArgsBufferSize` and `AmplificationShaderPayloadBufferSize` by name ([`SimpleDeviceAndSwapChain.cpp`](https://github.com/microsoft/Xbox-GDK-Samples/blob/b1e77b6ac10f95b07296025fda171ca2ddc42dbe/Samples/IntroGraphics/SimpleDeviceAndSwapChain/SimpleDeviceAndSwapChain.cpp)). | **Partly confirms.** Seventeen named fields cover the first 18 words (word 3 is the x64 alignment pad at 0x0C); the samples name two more fields without a public layout. A 24-word (96-byte) block still has at least four words with no public name or meaning. | -| Root-signature flags `0x03000000` | Not documented: the [graphics index](https://docs.xbox.com/_llms/en/apis/gdk-apis/graphics-api-reference.txt) has no `D3D12_ROOT_SIGNATURE_FLAGS` entry, and both URL forms under `docs.xbox.com/reference/graphics/` (`d3d12` and `d3d12_xs`) return 404. | **Leaves provisional.** Keep masking the byte on a copy; no public bit meaning. | -| `CheckFeatureSupport(D3D12_OPTIONS)` with 0x40 bytes | Microsoft publishes the 15-field PC structure, 0x3C bytes, with no extra member ([`D3D12_FEATURE_DATA_D3D12_OPTIONS`](https://docs.xbox.com/reference/graphics/d3d12/structs/d3d12_feature_data_d3d12_options_public.md)); its `CheckFeatureSupport` page says a size mismatch is `E_INVALIDARG` ([`CheckFeatureSupport`](https://docs.xbox.com/reference/graphics/d3d12/interfaces/id3d12device/methods/id3d12device_checkfeaturesupport_public.md)). XCL measured XDefiant asking 0x40 and retries with 0x3C, zeroing the tail ([`HANDOFF.md`](https://github.com/ivall/xcl/blob/95bda116cfc1b118156901984052ff5698dbf4cc/HANDOFF.md), [`real.rs`](https://github.com/ivall/xcl/blob/95bda116cfc1b118156901984052ff5698dbf4cc/crates/xcl/src/hle/d3d12x/real.rs)). | **Confirms the 0x40 request size; leaves the extra 4 bytes unknown.** The measurement fixes the size, not the field. No public source names them; `MaxGPUVirtualAddressBitsPerProcess` is a member of the separate `D3D12_FEATURE_DATA_GPU_VIRTUAL_ADDRESS_SUPPORT`, not a published member of `D3D12_OPTIONS`. The repository's accept-and-zero-tail behaviour matches the observed failure and is safe. | - -The call shapes are the samples' (and XCL's) shapes: `SetFrameIntervalX(output, interval_us, period, flags)`, -`ScheduleFrameEventX(type, offset_us, ancillary, flags)`, -`WaitFrameEventX(type, timeout_ms, ancillary, flags, &token)`, -`GetFrameStatisticsX(token, type_mask, &count, stats)`, and `PresentX(plane_count, planes, params)`. Type 0 is -the frame origin (the samples use only it); XCL also uses 1 and 2 for later points in the frame. The -`D3D12XBOX_SCHEDULE_FRAME_OBJECT_LIST` / `D3D12XBOX_WAIT_FRAME_OBJECT_LIST` ancillary block is -`{ u32 count; HANDLE* objects @0x08; i32* signaled @0x10 }` per XCL. - -The meanings the public samples give the create-device words: `Version` is the SDK version (`D3D12_SDK_VERSION` -in `SimpleDeviceAndSwapChain`), `GraphicsCommandQueueRingSizeBytes` is the command-queue ring, -`GraphicsScratchMemorySizeBytes` and `ComputeScratchMemorySizeBytes` are shader scratch memory, -`D3D12XBOX_DEFAULT_SIZE_BYTES` asks for the runtime's default, the `Disable*` BOOLs save title memory when the -stage is unused, and `CreateDeviceFlags` is `D3D12XBOX_CREATE_DEVICE_FLAG_NONE` in the sample. XCL logs word 0 -as the SDK version. ebiten also gives the `D3D12XBOX_PROCESS_DEBUG_FLAG_*` values (`DEBUG` 1, `INSTRUMENTED` -0x00100000, `NULL_GPU` 0x00400000, `ENABLE_COMMON_STATE_PROMOTION` 0x01000000, `ENHANCED_VALIDATION` -0x02000000); these are process debug flags, not `CreateDeviceFlags` bits. The `0x03000000` root-signature bit -is separate and has no public meaning. - -The provisional layouts in the split `xbox_present_types.h` on the PresentX-capture branch (not yet on main) are -the same as `xbox_present.h`: the plane struct agrees byte for byte with the 0x48 layout above, the -present-parameter struct is the 4-byte prefix of the 0x20 console object, and `uint64_t Token` is the confirmed -width. Its colour-space values are the documented DXGI numbers; `ScaleFilter` and the plane flags are still ours. -The 60/30/120 Hz periods (`16667`/`33333`/`8333` us) are the public ones; this layer does not carry 24/40/50 Hz. - -Still unknown after this search: the queue slots of `SuspendX`/`ResumeX`; which of the two queue layouts the -game's runtime uses; the values of `ScaleFilter` and the plane flags; the full `D3D12XBOX_FRAME_STATISTICS` -layout (the samples name `Type`, `Interval`, `Event`, `Render`/`Present`/`Display.PlaneIndex` and -`Display.PercentScanned`, but no public byte layout); the four extra `D3D12_OPTIONS` bytes; the last words of -the create-device block; the `0x03000000` meaning; and the console's behaviour for a null, repeated or -out-of-order token. - -### 7.2 What the public samples give Bink, XAudio2 and FidelityFX - -- **FidelityFX.** The MIT `Kits/AMDTK` GDK backend includes ``, calls - `XMemGetWorkingSetStatistics(XMEM_WORKING_SET_TITLE, ...)` for its memory report, and on Scarlett creates - resources with `CreateCommittedResourceX` and a `D3D12XBOX_RESOURCE_DESC` carrying DCC options - ([`ffx_gdk.cpp`](https://github.com/microsoft/Xbox-GDK-Samples/blob/b1e77b6ac10f95b07296025fda171ca2ddc42dbe/Kits/AMDTK/fidelityfx/src/backends/gdk/ffx_gdk.cpp)). - Its frame-interpolation swapchain calls the title's `PresentX` callback with `framePipelineTokenOriginal` - and `framePipelineTokenToSubmit`; the FSR3 sample can pass `D3D12XBOX_FRAME_PIPELINE_TOKEN_NULL` for the - real frame ([`ffx_gdk.h`](https://github.com/microsoft/Xbox-GDK-Samples/blob/b1e77b6ac10f95b07296025fda171ca2ddc42dbe/Kits/AMDTK/fidelityfx/include/FidelityFX/host/backends/gdk/ffx_gdk.h), - [`DeviceResources.cpp`](https://github.com/microsoft/Xbox-GDK-Samples/blob/b1e77b6ac10f95b07296025fda171ca2ddc42dbe/Samples/Graphics/AMDFidelityFX_FSR3FrameInterpolation/DeviceResources.cpp)). - This matches the three `xmem` imports of the shipped `amd_fidelityfx_upscaler_xbox.dll`; only the - allocation/capability part transfers, because that DLL is an upscaler and the public sample is the - frame-interpolation swapchain. -- **XAudio2.** `SimplePlaySound` calls `XAudio2Create(&pXAudio2, 0)` in `InitializeXAudio`, after the device - resources are made, and sets `XAUDIO2_DEBUG_CONFIGURATION` only in debug. XMA2 playback needs the compressed - audio in APU memory: `ApuAlloc(&m_xmaMemory, nullptr, bytes, SHAPE_XMA_INPUT_BUFFER_ALIGNMENT)`, filled with - `memcpy`, and freed with `ApuFree` - ([`SimplePlaySound.cpp`](https://github.com/microsoft/Xbox-GDK-Samples/blob/b1e77b6ac10f95b07296025fda171ca2ddc42dbe/Samples/Audio/SimplePlaySound/SimplePlaySound.cpp)). - That is the console-specific part a title using XMA reaches; the sample does not show a slot or an ABI addition - beyond it. -- **Bink.** No Bink use exists in the public GDK samples (the tree has none), so there is nothing to borrow; - the repository's existing `Bink2Scarlett.dll` path stands. - -## 8. Memory, heaps, compression and tiling - -SCARAB's `memory-adapter` is also a seam only: every flag is declared with value 0 and the header -says the numeric values are not recovered -([`memory_adapter.h:21-57`](https://github.com/p-portela/SCARAB/blob/d304fa2/components/memory-adapter/include/memory_adapter.h)). -The catalogue contributes **names**, which are useful as a checklist: - -- Resource flags: `ALLOW_DCC`, `FORCE_DCC_TEXTURE_COMPATIBILITY`, `FORCE_FMASK_TEXTURE_COMPATIBILITY`, - `FORCE_HTILE_TEXTURE_COMPATIBILITY`, `FORCE_TEXTURE_COMPATIBILITY`, `DENY_COLOR_COMPRESSION_DATA`, - `DENY_DEPTH_COMPRESSION_DATA`, `DENY_DEPTH_COMPRESSION_EXPCLEAR`, - `DENY_DEPTH_COMPRESSION_PLANES`, `DENY_DEPTH_STENCIL_HTILE`, `DENY_STENCIL_COMPRESSION_DATA`, - `DENY_STENCIL_COMPRESSION_EXPCLEAR`, `DENY_STENCIL_COMPRESSION_SMEM`, `ALLOW_INDIRECT_BUFFER`, - `ALLOW_AUTOMATIC_GAMEDVR_TONE_MAP`, `INTERNAL_TILED`, `PREFER_INDEX_BUFFER`, - `PREFER_PREDICATION_BUFFER`, `PREFER_STREAM_OUTPUT`. -- Heap flags: `D3D12CONS_HEAP_FLAG_ALLOW_INDIRECT_BUFFERS`. -- Copy flags: `FORCE`, `FORCE_DECOMPRESS`, `FORCE_DECOMPRESS_EXPAND_COLOR`, - `FORCE_ELIMINATE_DCC`, `FORCE_GATHER_COLOR_FMASK`, `FORCE_PROPAGATE_COLOR_CLEAR`, - `RESUMMARIZE_HTILE`. -- Resource states: `PRESERVE`, `PRESERVE_COMPRESSED_COLOR/DEPTH/STENCIL`, - `PRESERVE_EXPANDED_COLOR/DEPTH/STENCIL`, `PRESERVE_SCATTERED_COLOR_FMASK`. -- Layout/alignment names: `D3D12CONS_TEXTURE_LAYOUT_SWIZZLE_MODE_64KB_R_X`, - `D3D12CONS_TEXTURE_DATA_PITCH_ALIGNMENT`, `D3D12CONS_DCC_COMPRESSION_LEVEL_128B_TEXTURE_COMPATIBLE`. - -None of these has a numeric value in SCARAB, and none has a layout. The tiling/DCC question is -therefore **described, not answered**: the names tell Leonida what to look for in the game's -resource descriptions, and the copy/state names tell it which compression transitions the game -may perform, but the actual swizzle and DCC metadata format still has to come from Leonida's own -`tools/amd_swizzle.py` (the mode's equation, read from the public AMD header and evaluated to -detile with), `tools/tile_probe.py` (the block-endpoint feature and smoothness score measured on -a blob) and `tools/swizzle_search.py` (the brute-force search over every bit ordering with the -right x/y split inside a tile, scored with `tile_probe`), or from the console `xg_xs.dll` -functions `XGComputeOptimalSwizzleMode`, `XGEncodeDCC`, `XGDecodeDCC` (SCARAB names them; it does -not call them). - -Two names are worth adding to the trace filter because they affect correctness, not just -performance: `D3D12CONS_RESOURCE_STATE_PRESERVE_*` (a barrier that preserves compressed data) and -`D3D12CONS_COPY_FLAG_FORCE_ELIMINATE_DCC` / `RESUMMARIZE_HTILE` (a copy that changes compression). -If the game uses either, a naive Vulkan copy or barrier will read stale or compressed bytes. - -## 9. What this answers for Leonida - -Mapping to [d3d12_vulkan.md §8.2](d3d12_vulkan.md). "Answered" means a fact Leonida can implement -against; "described" means names or constraints but no layout; "still unknown" means no usable -evidence. - -| Leonida unknown | Status after SCARAB (and §7.1) | What is actually new | -|---|---|---| -| #1 device entry point and 24-word params | **described** | The separate console device export exists at ordinal 13 and is named `D3D12ConsCreateDevice` internally / `D3D12XboxCreateDevice` publicly; the params struct is named `D3D12CONS_CREATE_DEVICE_PARAMETERS`. Public sources name 17 fields and their x64 offsets, plus two more field names; a 24-word block still has at least four words unaccounted (§7.1). | -| #2 device/heap/queue/command-list slots | **partly measured** | SCARAB has no console slot map. Its appended-after-GCL6 model conflicts with the SDK's GCL8/GCL9 methods (§5.1). Public §7.1 gives the presentation slots (device 78-81, queue 30/32); the heap and command-list slot map is still unknown. Do not use SCARAB as a slot source. | -| #3 root signature → `s0..s31` | **still unknown** | Only flag names (`D3D12CONS_ROOT_SIGNATURE_FLAG_FORCE_MEMORY_BASED_ABI`, `_RAYTRACING`); no mapping. Leonida's own register-based/spill facts already go further. | -| #4 descriptor bytes and increments | **still unknown** | No measured increment. `D3D12CONS_DESCRIPTOR_HEAP_TYPE_SAMPLER_UNBOUNDED` is a new name, not a size. | -| #5 VA range / arena capacity | **still unknown** | — | -| #6 DXGI vs `PresentX` | **partly answered** | `PresentX` is a queue method; public code gives its queue slot (30 in the older runtime layout, 32 in the newer) and the x64 plane/present layouts (§7.1). Public samples give the call sequence and argument counts (no DXGI swapchain; frame events + `PresentX`), see §7. The game itself is not observed. | -| #7 standard AS vs BVH builder | **still unknown** | New names: `D3D12ConsRehydrateRaytracingAccelerationStructure`, `D3D12CONS_RAYTRACING_ACCELERATION_STRUCTURE_BUILD_FLAG_DEHYDRATE`, `DispatchRaysX`, `DispatchRaysDimensionsX`. No layouts. | -| #8 XDXR struct layouts | **still unknown** | Nothing from SCARAB. Measured since from `XboxBvhBuilder.dll` itself, see [xdxr.md](xdxr.md). | -| #9 tiled data layout / DCC | **described** | Flag, copy and state names; no values, no swizzle. | -| #10 binning/DCC/VRS/WMMA usage | **described** | `D3D12CONS_PIPELINE_STATE_FLAG_DISABLE_AUTO_DPBB`, `_DISABLE_RB_PLUS`, `RSSetShadingRateX`; usage still unknown. | -| #11 `CheckFeatureSupport` answers | **partly measured** | A console title asks `D3D12_OPTIONS` with 0x40 bytes where the PC struct is 0x3C (XCL/XDefiant); the extra 4 bytes are unnamed. The layer answers the PC fields and zeroes the tail (§7.1). | -| #12 async compute / copy queues | **described** | `CreateCommandQueueX` creates a shader-based queue, which the UMD says only supports `D3D12_COMMAND_LIST_TYPE_COMPUTE`; `SuspendX`/`ResumeX` exist. No params. | -| #18 heap aliasing / reserved | **still unknown** | — | -| console IIDs | **10 exported; 4 not exported** | The DMA list IID is proven and the other nine console GUIDs are reported. SCARAB's provenance reports that the four command-list IIDs are not runtime exports, so they have no ordinal; this package has no D3D12 DLL to read. They stay unresolved until a title trace or another artifact supplies them. | -| standard IIDs | **answered** | 83/83 standard GUIDs match the SDK; the 28 D3D12 ones are exact. | -| export contract | **answered** | 116 = 23 functions + 93 GUIDs; 23 function ordinals and 59 IID ordinals are documented, 34 are derived. The four command-list IIDs are outside the 93 and have no ordinal. | -| free-function dispositions | **answered as a list** | 7 standard + 16 console-only; Leonida serves 4 today. | - -The honest summary: SCARAB closes the **export/IID contract** and the **DMA-list rule**, and gives -a **name-level map** of the extension surface. It does not close presentation, slots, struct -layouts, numeric flags or tiling. - -## 10. Claims that did not hold up - -These are stated plainly because a future reader will otherwise trust the wrong part. - -1. **"The 116 export names" are not in the repository.** The `.def` and CSV are generated from the - user-supplied vendor DLL; the docs publish SCARAB's internal, de-branded spellings for five - `D3D12Cons*` exports (§2.3). Use the ordinals and the 18 token-free names; confirm the other - five wire names from the game's import table. -2. **`RSSetDepthBiasX` has a PC equivalent.** SCARAB says depth bias is PSO-only. The 26100 SDK - has `ID3D12GraphicsCommandList9::RSSetDepthBias(FLOAT, FLOAT, FLOAT)`. SCARAB's declared - `INT` first argument is also inconsistent with the SDK. Recording the call and dropping it - would render with the wrong depth bias on a GCL9 title. -3. **`OMSetFrontAndBackStencilRef` is not a console extension in the 26100 SDK.** It is public - GCL8 with the same signature. SCARAB's wrapper puts it after GCL6; a GCL8-compiled game calls - the public slot. Do not copy the placement. -4. **The catalogue overcounts methods.** 105 rows include at least 11 non-methods (§5); the real - recovered method-name count is at most 94, and the docs elsewhere say "~95". The wrapper's - "105 method names" is not a measured method count. -5. **The present flag values are guesses.** `console_extensions.h` assigns 0x1/0x2/0x4; - `present_adapter.h` says the values are unknown and uses 0. Neither is a measurement. -6. **The unknown-arity stubs are not all safe.** The stated policy is a zero-argument stub that - ignores its arguments, which is safe on the x64 ABI. But `DXGIXGetFrameStatistics` writes 64 - bytes through its first pointer, `PixGetPixieEntryPoints` writes 8, and `D3D12ZeroMemoryX` - writes `Size` bytes. If the arity or the struct size is wrong, these corrupt memory. The policy - covers only the genuinely zero-argument stubs. -7. **`iid_console.inc` is mislabelled.** It says "console-specific interfaces"; 49 of its 59 - entries are standard D3D11/DXGI. The values are right; the label can mislead a reader into - treating a standard IID as console-only. -8. **The build claims need artifacts that are not in the repo.** The wrapper's 53+76 `override` - proof needs `vendor/d3d12/include/d3d12.h`; the generated `gen_device.inc` / `gen_clist.inc` - are not committed; the 116/116 export check needs the vendor DLL. The measurements are stated - with commands, but a clean clone cannot reproduce them without the user-supplied files. That is - a deliberate policy, not a false claim; it does mean "verified" in SCARAB's README means - "verified on the author's artifact set". -9. **The Wine results are not reproducible here.** "All 7 DLLs load", "the whole console graphics - stack runs on Linux", and the DMA round-trip are **Reported**. This page did not open - `d3d12_xs.dll` and did not run Wine. Nothing in this doc depends on them. -10. **The package's D3D12 DLL exports do not contain the four command-list IIDs with 1.0.2.1.** - The package has 16 DLLs and no D3D12 runtime DLL, and `gameos.xvd` is encrypted; SCARAB's - provenance says the runtime does not export these four IIDs. There is no export ordinal to - read in this package or in the vendor DLL. A `QueryInterface` trace from the running title is - one possible way to establish the mapping; the package evidence does not exclude other - sources. - -The central claim does hold, with one link stated: **SCARAB's table reproduces 28/28 D3D12 IIDs, -and in fact 83/83 standard GUIDs, byte-identically**, checked against the Windows SDK here. That -the table also equals the vendor runtime's exports is SCARAB's G1 measurement (`93/93` GUID bytes), -which needs the vendor DLL and was not reproduced. The DMA IID and the export composition also -hold as files, subject to the name caveat. - -## 11. Licence and provenance - -SCARAB is **GPL-3.0-only**: its README says so and every first-party file carries -`SPDX-License-Identifier: GPL-3.0-only`. Leonida is GPL-3.0-or-later. The two are compatible in the -direction that matters — GPL-3.0-only code can be combined into a GPL-3.0 work — but the combined -work cannot be relicensed as "or later" for the SCARAB-derived part. This page copies **no SCARAB -code**. It records interface names, ordinal numbers and 16-byte GUIDs, which are ABI facts, with -the source file and line cited. The 28 standard GUIDs are also facts from the Windows SDK; the 10 -console GUIDs are reported from the vendor runtime and are attributed to SCARAB. - -The public sources in §7.1 are used as facts only: XCL is GPL-2.0-only (no code copied), ebiten is Apache-2.0, -the Mesa WGL file is MIT, and the Microsoft samples are MIT. Only names, numbers, field offsets and slot indices -are taken from them; no code or prose is copied. - -If any code is later adapted from SCARAB, it must carry the SCARAB copyright and -`GPL-3.0-only` notice, and the file must say exactly which SCARAB file it came from. The checker -in `tools/d3d12_xs_surface.py` is original code written for this repository; it reads only the -tables above and, optionally, a local SDK or a SCARAB checkout. - -## 12. References - -SCARAB, pinned at `d304fa2`: - -- `README.md:14-39` — the 28/28 claim, component states. -- `docs/ARCHITECTURE.md:169-185` — E1–E17, the evidence table. -- `docs/d3d12-xs-bridge.md:17-28,82-123` — IID identity, console IIDs, the 116-export disposition. -- `docs/d3d12-xs-wrapper.md:69-97,134-162` — what is proven, class placement, DMA round-trip. -- `docs/d3d12_xs-findings.md:47-67` — the export surface composition. -- `docs/plans/2026-11-21-translation-layer-architecture.md:30` — 23 functions + 93 GUIDs. -- `components/extension-wrapper/docs/console-extension-catalogue.tsv` — 105 + 106 names. -- `components/extension-wrapper/iid_provenance.json:2-20` — the Debug@76 correction and 7 candidates. -- `components/extension-wrapper/src/iid_console.inc:9-67` — 59 GUIDs and their ordinals. -- `components/runtime-bridge/src/iid_table.cpp:7-105` — 93 GUID values. -- `components/runtime-bridge/src/d3d12_xs_bridge.cpp:336-576` — the function stubs. -- `components/extension-wrapper/console_extensions.h:45-191` — type/method declarations. -- `components/extension-wrapper/src/wrap.cpp:279-326` — `CreateCommandList` interception. -- `tools/gen_def.py:2-24,38,149-183` — the token alias rule. -- `components/present-adapter/include/present_adapter.h`, `components/memory-adapter/include/memory_adapter.h` - — the two seams. - -Windows SDK 10.0.26100.0: - -- `um/d3d12.h:7237,30278,31126,32819,33680` — `OMSetDepthBounds`, `RSSetShadingRate`, - `DispatchMesh`, `OMSetFrontAndBackStencilRef`, `RSSetDepthBias`. -- `um/d3d12sdklayers.h:4243` — `IID_ID3D12Debug`. -- `um/d3d11*.h`, `shared/dxgi*.h`, `um/d3dcommon.h`, `um/dxgidebug.h` — the other standard GUIDs. - -Leonida: - -- [d3d12_vulkan.md](d3d12_vulkan.md) §3.5, §4.5, §7, §8.2 — the gaps this page maps onto. -- `docs/runtime_imports.md` (runtime-imports branch) — which imports the shipped DLLs actually bind. -- `runtime/shims/d3d12_xs.cpp` — the four functions Leonida serves today. diff --git a/docs/descriptor_lookup_ada.md b/docs/descriptor_lookup_ada.md deleted file mode 100644 index c5a6fced3..000000000 --- a/docs/descriptor_lookup_ada.md +++ /dev/null @@ -1,70 +0,0 @@ -# Descriptor lookup cost on NVIDIA RTX 4070 SUPER (Ada) - -Divergent misses showed the largest change with table size. On the GPU-only memory type, one million logical lane lookups took 150 µs at 1,000 live descriptors, 657 µs at 10,000 and 998 µs at 100,000. Divergent texture hits took 39.7, 75.0 and 119.0 µs. The ReBAR type (device-local and host-visible) stayed within 0.5% of GPU-only in every cell. Host-visible memory outside VRAM was within 8% of them at 1,000 entries, and at 100,000 it was 2.5× slower for divergent misses and 6.0× slower for uniform texture hits. These are synthetic compute results from one GeForce RTX 4070 SUPER on Windows 11 with NVIDIA driver 621.01. The benchmark ran unchanged at `dcd8ecf`. [D3D-56 benchmark PR #639](https://github.com/ItsNotRexed/Leonida/pull/639) · [Measured revision](https://github.com/ItsNotRexed/Leonida/commit/dcd8ecf10b138566d567020562b7afd853a89024) - -## Measurements - -Each cell is gross GPU time in **µs per million logical lane lookups**, including key reads and result accumulation. The benchmark also prints a figure with a key-read baseline subtracted. The table uses its gross column. - -| Live descriptors | Memory type | Uniform T# hit | Uniform S# hit | Divergent T# hit | Divergent T#+S# pair | Divergent miss | -|---:|:---|---:|---:|---:|---:|---:| -| 1,000 | GPU-only | 8.6 | 8.3 | 39.7 | 40.3 | 150.0 | -| 1,000 | Host-visible | 9.2 | 9.0 | 39.9 | 40.4 | 150.6 | -| 1,000 | ReBAR | 8.6 | 8.3 | 39.6 | 40.3 | 149.9 | -| 10,000 | GPU-only | 8.7 | 8.5 | 75.0 | 89.4 | 657.4 | -| 10,000 | Host-visible | 11.5 | 10.1 | 90.0 | 106.3 | 886.8* | -| 10,000 | ReBAR | 8.7 | 8.5 | 75.2 | 89.3 | 658.8 | -| 100,000 | GPU-only | 9.1 | 9.1 | 119.0 | 167.1 | 998.4 | -| 100,000 | Host-visible | 54.4 | 13.9 | 172.4 | 236.6* | 2,460.9* | -| 100,000 | ReBAR | 9.1 | 9.1 | 119.3 | 166.8 | 1,002.1 | - -\* Shortened by the benchmark's Windows timeout guard in 11 or 12 of the 12 rounds (see Method). - -At 100,000 entries on type 1, a divergent T# dispatch took 2.00 ms and a T#+S# dispatch took 5.61 ms. Each paired iteration resolves two descriptors. - -GPU-only is type 1, `DEVICE_LOCAL`, on heap 0 (11,997 MiB). Host-visible is type 2, `HOST_VISIBLE | HOST_COHERENT` without `HOST_CACHED`, on heap 1 (16,243 MiB, not device-local). ReBAR is type 4, `DEVICE_LOCAL | HOST_VISIBLE | HOST_COHERENT`, on heap 0. Every allocation on type 4 succeeded, up to the 20 MiB table. Resizable BAR was enabled: `nvidia-smi` reported a 16,384 MiB BAR1 aperture. On a similar card where the ReBAR type is missing or refuses the allocation, the benchmark skips that placement and the ReBAR rows are absent. - -At 100,000 entries, the 12 round medians for GPU-only and ReBAR split into two groups. The four rounds whose process ran the 10,000-entry table first (rounds 3, 6, 7 and 10) measured 293–299 µs per million for divergent misses and 59.6–60.2 for divergent T# hits. The other eight rounds measured 992–1,015 and 118.7–142.9. The table medians follow the eight. The cause was not measured. Host-visible round medians for divergent misses ranged from 1,870–2,810 µs per million, and the spread did not follow the size order. At 1,000 and 10,000 entries, the round medians for each table cell differed by at most 10% on GPU-only and ReBAR, and by up to 37% on host-visible. - -The tables contain 90% T# texture keys and 10% S# sampler keys. Their allocations were 163,844, 2,621,444 and 20,971,524 bytes (0.156, 2.50 and 20.0 MiB). The capacities were 4,096, 65,536 and 524,288 slots, at 24.4%, 15.3% and 19.1% load. At 100,000 entries the ordinary uniform hit runs covered all 90,000 textures or all 10,000 samplers. Each workgroup shared a key for each iteration. The separate hot-key control reused one texture and measured 7.2 µs per million on all three types and sizes. Divergent misses visited 1,024, 16,384 and 131,072 distinct absent keys across the three sizes. Those counts describe the query schedule. Cache residency and memory traffic were unmeasured. - -## Method and replay - -Each dispatch used 4,096 groups of 64 lanes and 64 iterations. The RTX 4070 SUPER reported 32-lane subgroups. The denominator was 16,777,216 logical lookups per single-key dispatch and 33,554,432 per paired dispatch, counting the texture and sampler separately. Vulkan timestamps bracketed one dispatch. The queue advertised 64 valid bits and a 1 ns tick period. - -Each cell is the median of 12 process medians, each from 25 timed dispatches after five warmups. The 11 scenarios ran in the benchmark's fixed order. There were 36 processes: three memory types in each of 12 rounds. Across them there were 28,948 timed dispatches. Every process exited 0, wrote nothing to stderr and reported `timing_status` `ok` on all 1,188 rows. The run used the default Windows Vulkan loader with validation layers off. - -Unlike the [M3 Max run](descriptor_lookup_apple.md), this run kept the benchmark's default `--max-dispatch-ms 120`, so that a slow dispatch cannot reach the Windows 2 s GPU timeout (TDR). Before each scenario, a 64-group, four-iteration probe estimates the full dispatch time. If the estimate exceeds 120 ms, the benchmark lowers the iteration count to aim at 60 ms and uses nine timed dispatches after two warmups. The figure stays per million lookups. Only host-visible cells were shortened. The 10,000-entry divergent miss ran with 17–20 iterations in 11 rounds. At 100,000 entries, divergent misses ran with 13–15 iterations in all 12 rounds, and T#+S# pairs with 25–31 in 11 rounds. The table marks these cells. Shortened dispatches had medians of 0.49–9.84 ms, far below the 120 ms limit. - -From a Leonida checkout on Windows, with Visual Studio 2022 (C++ desktop workload, C++ CMake tools) and the Vulkan SDK installed: - -```powershell -git fetch https://github.com/ItsNotRexed/Leonida.git dcd8ecf10b138566d567020562b7afd853a89024 -git worktree add --detach ..\leonida-ada FETCH_HEAD -cd ..\leonida-ada -powershell -ExecutionPolicy Bypass -File scripts\build_runtime.ps1 -runtime\build\vk_descriptor_bench.exe --list-devices -runtime\build\vk_descriptor_bench.exe --self-test -foreach ($memory in 'device', 'host', 'rebar') { - runtime\build\vk_descriptor_bench.exe --device 0 --memory $memory --sizes 1000,10000,100000 ` - --groups 4096 --iters 64 --warmup 5 --reps 25 --csv -} -``` - -These commands predate `--warmup-ms` (TEST-277, default 300 ms of extra warm-up). With a current build add `--warmup-ms 0` to reproduce them as run. - -Device 0 was the RTX 4070 SUPER, the only Vulkan device. For the full 12-round series, let A, B and C denote 1k, 10k and 100k. The rounds used the same size orders and starting memory types as the M3 Max run. The first six size orders were ABC, CBA, BAC, CAB, ACB and BCA, starting with device, host, device, device, host and host respectively. The next six reversed the sequence of rounds and swapped the starting memory type in each. Each round ran the other of device and host second, and ReBAR third. - -## System - -| | | -|:---|:---| -| GPU | NVIDIA GeForce RTX 4070 SUPER, 12,282 MiB (discrete) | -| PCI id | `0x10de:0x2783`, subsystem `0x89521043` | -| Link | PCIe 4.0 x16 (maximum reported by `nvidia-smi`) | -| Resizable BAR | On (BAR1 aperture 16,384 MiB, `nvidia-smi -q -d MEMORY`) | -| Subgroup size | 32 | -| Driver | NVIDIA 621.01 (`nvidia-smi`), Vulkan API 1.4.357 | -| OS | Windows 11 Home 25H2, build 26200.9974 | -| Vulkan SDK | 1.4.363.1 (headers for the build) | -| Compiler | Visual Studio 2022 Build Tools, `RelWithDebInfo` via `scripts\build_runtime.ps1` | diff --git a/docs/descriptor_lookup_apple.md b/docs/descriptor_lookup_apple.md deleted file mode 100644 index fad071ec6..000000000 --- a/docs/descriptor_lookup_apple.md +++ /dev/null @@ -1,48 +0,0 @@ -# Descriptor lookup cost on Apple M3 Max - -Divergent misses showed the largest change with table size. On the GPU-only memory type, one million logical lane lookups took 49 µs at 1,000 live descriptors, 156 µs at 10,000 and 479 µs at 100,000. Divergent texture hits took 65, 68 and 74 µs. These are synthetic compute results from one M3 Max on AC power, running macOS 27.3 and MoltenVK 1.4.0. The 40-core GPU ran the benchmark unchanged at `f165a13`. [D3D-56 benchmark PR #639](https://github.com/ItsNotRexed/Leonida/pull/639) · [Measured revision](https://github.com/ItsNotRexed/Leonida/commit/f165a13ff8bc12d2516e399bb87f923553fa107e) - -## Measurements - -Each cell is gross GPU time in **µs per million logical lane lookups**, including key reads and result accumulation. The benchmark also prints a figure with a key-read baseline subtracted. The table uses its gross column. - -| Live descriptors | Memory type | Uniform T# hit | Uniform S# hit | Divergent T# hit | Divergent T#+S# pair | Divergent miss | -|---:|:---|---:|---:|---:|---:|---:| -| 1,000 | GPU-only | 20.8 | 23.2 | 65.0 | 64.0 | 49.3 | -| 1,000 | Host-visible | 20.8 | 23.2 | 65.1 | 64.0 | 49.3 | -| 10,000 | GPU-only | 21.3 | 20.8 | 67.6 | 67.4 | 155.9 | -| 10,000 | Host-visible | 21.3 | 20.8 | 67.7 | 67.4 | 155.8 | -| 100,000 | GPU-only | 20.8 | 20.5 | 73.9 | 74.7 | 479.3 | -| 100,000 | Host-visible | 20.9 | 20.5 | 73.8 | 74.7 | 482.7 | - -At 100,000 entries on type 0, a divergent T# dispatch took 1.24 ms and a T#+S# dispatch took 2.51 ms. Each paired iteration resolves two descriptors. - -Both Vulkan memory types use the same 128 GiB unified heap. Type 0 is device-local. Type 1 is device-local, host-visible, coherent and cached. At 100,000 entries, the 12 round medians for divergent misses ranged from 467–525 µs per million on type 0 and 471–505 on type 1. - -The tables contain 90% T# texture keys and 10% S# sampler keys. Their allocations were approximately 0.156, 2.50 and 80 MiB. At 100,000 entries the ordinary uniform hit runs covered all 90,000 textures or all 10,000 samplers. Each workgroup shared a key for each iteration. The separate hot-key control reused one texture. Divergent misses exhausted the eight-probe search and visited 1,024, 16,384 and 131,072 distinct absent keys across the three sizes. Those counts describe the query schedule. Cache residency and memory traffic were unmeasured. - -## Method and replay - -Each dispatch used 4,096 groups of 64 lanes and 64 iterations. The M3 Max reported 32-lane subgroups. The denominator was 16,777,216 logical lookups per single-key dispatch and 33,554,432 per paired dispatch, counting the texture and sampler separately. Vulkan timestamps bracketed one dispatch. The queue advertised 64 valid bits and a 1 ns tick period. - -Each cell is the median of 12 process medians, each from 25 timed dispatches after five warmups. The 11 scenarios ran in the benchmark's fixed order. Across both memory types and three sizes there were 19,800 timed dispatches. A separate pre-timing dispatch checked 5,042 of 262,144 lane accumulators against the CPU oracle for each case. The run used the default macOS loader with validation layers off. - -From a Leonida checkout with Vulkan headers, CMake, Ninja and MoltenVK installed: - -```sh -git fetch https://github.com/ItsNotRexed/Leonida.git f165a13ff8bc12d2516e399bb87f923553fa107e -git worktree add --detach ../leonida-639 FETCH_HEAD -cd ../leonida-639 -cmake -S runtime -B build -G Ninja -DCMAKE_BUILD_TYPE=RelWithDebInfo -cmake --build build --target vk_descriptor_bench -build/vk_descriptor_bench --self-test -build/vk_descriptor_bench --list-devices -for memory in device host; do - build/vk_descriptor_bench --device 0 --memory "$memory" --sizes 1000,10000,100000 \ - --groups 4096 --iters 64 --warmup 5 --reps 25 --max-dispatch-ms 0 -done -``` - -These commands predate `--warmup-ms` (TEST-277, default 300 ms of extra warm-up). With a current build add `--warmup-ms 0` to reproduce them as run. - -Device 0 was the M3 Max. For the full 12-round series, let A, B and C denote 1k, 10k and 100k. The first six size orders were ABC, CBA, BAC, CAB, ACB and BCA, starting with device, host, device, device, host and host respectively. The next six reversed the sequence of rounds and swapped the starting memory type in each. diff --git a/docs/descriptor_lookup_intel.md b/docs/descriptor_lookup_intel.md deleted file mode 100644 index 3420caf30..000000000 --- a/docs/descriptor_lookup_intel.md +++ /dev/null @@ -1,39 +0,0 @@ -# Descriptor lookup cost on Intel UHD Graphics 770 - -@kapitche ran the D3D-56 `vk_descriptor_bench` synthetic compute benchmark on an Intel -UHD Graphics 770 (Xe-LP integrated GPU) under Windows 11 with Intel driver `101.6129`. -Vulkan reported a subgroup size of 32 and a timestamp period of 52.083 ns. The run used -`main` at [`8df277f`](https://github.com/ItsNotRexed/Leonida/commit/8df277fb035b384971497f6f9790f7fc4b9ec1d1). -[Original report by @kapitche](https://github.com/ItsNotRexed/Leonida/issues/313#issuecomment-7073751039) - -## Measurements - -The benchmark used its defaults of 4,096 workgroups of 64 invocations, 64 iterations -per invocation and a median of 25 timed dispatches per case. Each dispatch counted -16,777,216 logical lane lookups for single-key cases and 33,554,432 for paired cases, -where each iteration resolves one texture (T#) and one sampler (S#). - -All values are **net µs per million logical lane lookups**, after the benchmark -subtracts the matching key-read baseline scaled to the number of lookups per iteration. -The lookup layout and eight-probe limit are described in -[the Vulkan design, §5.1](d3d12_vulkan.md#51-descriptor-hash-table-details). - -| Live entries | Placement | Uniform T# hit | Uniform T#+S# pair | Divergent T# hit | Divergent miss | -|---:|:---|---:|---:|---:|---:| -| 1,000 | `device_local` | 263.0 | 300.5 | 1,350 | 6,249 | -| 1,000 | `host_visible` | 263.3 | 300.3 | 1,350 | 6,249 | -| 10,000 | `device_local` | 264.2 | 296.2 | 1,364 | 6,413 | -| 10,000 | `host_visible` | 263.9 | 296.3 | 1,363 | 6,402 | -| 100,000 | `device_local` | 280.5 | 316.0 | 1,483 | 8,263 | -| 100,000 | `host_visible` | 280.9 | 316.5 | 1,481 | 8,217 | - -## Interpretation - -For each size and scenario, the two placements differ by less than 0.6% relative -to `device_local`. For this run, Vulkan memory type 0 (`device_local`) and type 1 -(`host_visible`, with `DEVICE_LOCAL | HOST_VISIBLE | HOST_COHERENT`) both used -shared system RAM. The small differences apply to these two memory types on this setup. - -From 1,000 to 100,000 entries, the hit timings rose by about 5–10% across the two -placements, while divergent misses, which exhaust the eight-probe search, rose by -about 31–32%. diff --git a/docs/design.md b/docs/design.md deleted file mode 100644 index 18c62c49c..000000000 --- a/docs/design.md +++ /dev/null @@ -1,652 +0,0 @@ -# Design notes - -Groundwork for running the Xbox Series build of GTA VI natively on Windows. The work that does not need the -executable is in place; booting can start as soon as `game_scarlett_master.exe` is available. - -## Ground rules - -- Everything here runs from **your own copy** and stays on **your PC**. Game files, generated code, shader caches and - reports that quote game data are never committed, uploaded or shared. `reports/` is git-ignored for this reason. -- Nothing in this folder decrypts, unpacks or works around Xbox package protection. The tools only read files that - are already plain on disk. -- The store keeps the game as one packaged container (`.xvc`): an XVD file whose contents are encrypted, so the - build can't use it and needs the folder that holds `MicrosoftGame.Config`. Given one as `--game`, finding one - with `--find`, or finding one alone in the folder given, `make_game.py` reads only its plain 4 KiB header to say - what it is instead of "not found". Fields read, at file offsets (xvdtool's `XvdHeader` + 0x200 for the - signature in front of it), checked on one 1.0.2.1 package: `msft-xvd` magic at 0x200; VolumeFlags at 0x208 - (`0x41`, ReadOnly and RegionIdInXts; EncryptionDisabled `0x2` is clear); ContentType at 0x284 (1, Title); - XvcDataLength at 0x290 (non-zero for an XVC); PackageVersion at 0x3BC, four u16 stored lowest part first - (1, 2, 0, 1 is 1.0.2.1). No key field is read. - -## Why a loader before a recompiler - -The Xbox Series CPU is x86-64, the same as a PC. Unlike Hookshot, where ARM64 code has to be -translated, most of the game's code can run as-is. The work is everything around it: - -| Layer | Approach | Folder | -|---|---|---| -| CPU code | Map the PE image and run it natively. Patch only what can't run on desktop (privileged instructions, console-only intrinsics). Each mapped image's `.pdata` is checked (in bounds, sorted, non-overlapping; zero-length entries allowed, as in System32's `symcryptk.dll`) and registered with `RtlAddFunctionTable`, so SEH/C++ exceptions and stack walks unwind through its frames; the host MSVC runtime's `RtlPcToFileHeader` import is redirected so an MSVC `throw` in a mapped image finds its image base. The loader installs static TLS for the calling thread and, through `gta6rt_tls_host.dll`'s thread events, for every thread started after the image was loaded. | `runtime/src` | -| Imports (GameOS / GDK / Xbox DLLs) | Every imported `dll!function` goes to a shim. Unimplemented ones log once and return a failure, so the missing surface shows up at runtime. | `runtime/shims` | -| Graphics | Xbox D3D12 (`d3d12_xs`) to Vulkan. Shaders ship as compiled RDNA2 machine code; `tools\rdna2spirv.py` translates all 26,503 to SPIR-V. The D3D12 layer replays on Vulkan and is still in progress ([d3d12_vulkan.md](d3d12_vulkan.md)). | `tools\` (translator), `runtime\shims\d3d12_*`, `runtime\src\vulkan_*` | -| Assets | `.rpf` archives (RPF9) read through the runtime's file layer. | later | - -## Layout - -``` -tools/ Python analysis tools (no game data inside) - pe_inspect.py PE headers, sections, entropy, imports sorted by where they resolve, .pdata, TLS - rpf_probe.py RPF header survey of a game folder - manifest.py SHA-256 manifest of a game folder (create), plus a verify subcommand - inline_scan.py inline command-list writes in an image, and whether each checks the cursor limit first -scripts/ - first_look.ps1 run once the exe arrives: the full report set for it -runtime/ C++ native loader (CMake + Ninja, MSVC) - src/ PE mapper, relocations, import binding, TLS - shims/ per-DLL shim tables -reports/ generated output (git-ignored) -docs/ notes -``` - -## Day one, when the exe is here - -```powershell -.\scripts\first_look.ps1 -Exe "\game_scarlett_master.exe" -``` - -This writes `reports/exe/` (JSON plus a readable summary). Check it in this order: - -1. **Section entropy.** Sections near 8.0 bits/byte are still encrypted or compressed. If `.text` is one of them, - nothing else can be done yet. -2. **Import table.** Each DLL is marked `bundled` (in the game folder), `system` (present on this Windows), or - `shim` (needs a reimplementation). The `shim` list is the real to-do list. -3. **.pdata function count.** This gives function boundaries for patching and later analysis. -4. **Inline command-list writes.** `python -I tools/inline_scan.py \game_scarlett_master.exe --sites` (a few - minutes; it streams `dumpbin /disasm`; it exits 2 when it reads no instructions). "UNCHECKED 0" means every - inline write checks the cursor limit, so a layer that keeps the cursor at the limit receives every command - through the vtable; any unchecked site is a write that layer never sees. The package's DLLs check at every site - ([d3d12_command_objects.md](d3d12_command_objects.md), "Every inline write in the package's DLLs checks first"). -5. **GDK runtime classes.** The exe imports no GDK function by name; `.gdk_calls.txt` lists the runtime classes - and vtable slots it calls through `xgameruntime.lib`'s thunks, and the classes the runtime's - `runtime/shims/xgameruntime*.cpp` don't serve yet - ([runtime_imports.md](runtime_imports.md#measuring-which-runtime-classes-a-binary-calls)). -6. **What to confirm.** `checklist.md` (`tools/exe_checklist.py`) gathers every `ASSUMPTION`, `UNVERIFIED` and - `VERIFY` note of the runtime and the docs, with file and line. Notes in a shim whose class the exe calls are - marked **called** and come first: those are the ones its first boot reaches, such as the `XStoreGameLicense` - sizes. - -Then `runtime\build\gta6rt.exe --dry-run ` maps the image and binds every import to the shim table without -running any game code. It reports what it couldn't bind. - -## Reproduce the shader tests - -Build the hand-written tests where LLVM supports AMDGPU and SPIRV-Tools is available. Run the generated shaders -with the Vulkan test tools on the target GPU. Use the same output folder in both commands. - -```text -python -I runtime/test/shaders/build.py -python -I runtime/test/shaders/check.py [runtime-build-directory] -``` - -The wave-mask fixture checks every lane and the wave64 ballot fixture checks mask counts and first-set lanes -across both halves of a wave. Rebuild `vk_compute_test` before running `check.py`. It uses a full 64-wide compute -subgroup for these two checks, and the summary reports them as skipped if the device cannot provide one. -`cs_exec64` still checks per-lane EXEC writes on 32-wide subgroups. With `LEONIDA_W64_EMULATE=1` in the environment of both commands, `build.py` translates with `--wave64-emulate` and `check.py` runs every wave64 check without asking for a 64-wide subgroup, so a 32-wide GPU runs them all (`scripts/run_gpu_tests.py` honours the same variable). Pick one of several GPUs with the Vulkan loader, e.g. `VK_LOADER_DRIVERS_SELECT='*nv*'` or `'*amd*'`. The flat-input fixture checks both integer -IDs and interpolated UVs. The corpus comparison is a separate test and uses shader files from the local build. - -On macOS the test tools default to MoltenVK. To test another Vulkan driver, set -`LEONIDA_VULKAN_LOADER` to the standard loader dylib and `VK_DRIVER_FILES` to the driver's ICD manifest, for example -`LEONIDA_VULKAN_LOADER=/path/to/libvulkan.1.dylib VK_DRIVER_FILES=/path/to/lvp_icd.json`. -These tools do not request portability enumeration, so use the default for MoltenVK. - -Run `python -I scripts/run_gpu_tests.py --filter ms_v5_workgroup` to check the mesh workgroup index. The synthetic -shader exports its incoming `v5` from lanes 0, 1 and 31 in the RGB channels of a full-screen triangle. One `vkCmdDrawMeshTasksEXT(2, 3, 4)` -produces 24 triangles. A stencil countdown lets pixel *i* record only triangle *i* in Vulkan rasterization order. -For `g = x + 2*y + 6*z`, the CPU compares each pixel with `(32*g, 32*g + 1, 32*g + 31, 1)` (the 32-thread fixture's `g * NumThreads + lane` values). This checks the translator's register mapping on the host GPU. -SPIRV-Tools 2026.1 validates this fixture. Version 2025.1 reports a known error on `CullPrimitiveEXT`. -[Vulkan mesh rasterization order](https://docs.vulkan.org/features/latest/features/proposals/VK_EXT_mesh_shader.html) · [Validator fix](https://github.com/KhronosGroup/SPIRV-Tools/pull/6155). - -## Build the runtime - -```powershell -.\scripts\build_runtime.ps1 -``` - -It sets up MSVC through `vcvars64.bat` and builds at BelowNormal priority on half the cores, writing to `runtime\build\`. -If VS's "C++ CMake tools" component is installed, it uses CMake and Ninja. Otherwise it calls `cl` directly. That -component may not be installed, and the devkitPro MSYS `cmake` on PATH can't build MSVC projects. When you -add a source file, add it to `runtime\cmake\windows_runtime.cmake` and to the file list in `build_runtime.ps1`. - -## Asset status (no exe needed) - -| Asset | State | Where | -|---|---|---| -| Archive data | Carved without the encrypted tables of contents. Most archives are 93–99% plain zlib (`levels.rpf` 98.3%, 1.1M files; full census **23,535 placement maps / 1,670,442 entities**). Not zlib: `audio.rpf` (99.9%), about half of `story000.rpf` and `shared_minigame000.rpf`. | `\carve\\`, `coverage.json`; [world_census.md](world_census.md) | -| Videos | 797 Bink 2 files (`KB2n`), cut out whole. | `*.bk2` in the carve folders | -| Shaders | 26,503 carved from `shaders.rpf`, native RDNA2 code unpacked (`FSSM`), disassembled, and translated to SPIR-V; all validate (see *Translator status*). | `\shaders\` (`.dxbc`, `fssm\`, `disasm\`, `spirv\`) | -| Textures | **Solved.** Headers are in CPU segments: GPU pointer at q[k], u16 width/height/depth and DXGI format at q[k+4], mip count at byte 2 of q[k+5]. Data is AMD `SW_4K_S` tiled, largest mip first. The GPU segment is the blob run after the CPU blob. On 200 samples, 173 decode at least 1.5× smoother detiled than untiled (median 2.56×). Exports the top mip, slice 0, as DDS. **22,342 exported (1.23 GiB)**: every header whose GPU data follows its CPU blob. World and model textures are handled by the TXD and TTPF exporters below. GPU offsets must be 256-byte aligned, which drops the false headers in `navmeshes`/`anim`. | `tools\tex_headers.py`, `tools\tex_export.py`, `\textures\` | -| Models | **Done: 382,781 models measured at the `e293917` pin** (`levels.rpf` 343,327, `packs` 26,585, `story000` 7,461, `data` 3,175, `shared_minigame000` 1,294, `core_restofworld` 936, `story000_restofworld` 3; 0 decode failures across all 382,781 models; **159,511 drawable-dictionary children**, **223,270 standalone**; the other archives measure **4,686 fragments**, **30,343 bone-bound**, **126,301,454 triangles** and 512 embedded textures, while the `levels.rpf` fragments/bone-bound/triangles/embedded cells are **not independently reproduced** (**†**) (no `levels.rpf` manifest; the count harness emits no such fields); 72 unrecovered scan candidates vs 1,282 at `917e9b9`). Earlier baselines: 350,251 at `917e9b9` (159,486 dictionary children, 190,765 standalone) and 190,792 at `c3708fb`; the +32,530 gain at `e293917` comes from upstream `v1.2` PRs #8–#12 (optional fragment pointers, texture-dictionary filtering, probe-cap parity, and zero-radius drawables; see [models.md](models.md)). Exported with `tools\rpf9dump` (built on breadbbbb/rpf9-explorer's Core; see below). Resources are found at page offset +16 after 16 zero bytes, followed by a zlib system blob with a drawable/fragment header and then the following zlib blocks as graphics data. Positions are quantized: `bias + scale * ((q >> 8) & 0xFFFFFF)`. Output is OBJ (positions, UVs, indices) plus a manifest with real model names (e.g. `cvar_int_grg2b_toys_1`), bounds, per-mesh shader index and material texture references (parameter hash, name hash, 64-bit asset key). My earlier `0x1380`/`0x1601` descriptor notes stand, but the "data not located" blocker was wrong. Character skeletons are separate: the shared 597-name `.#ft` table and its model-side bone-hash mapping are in [character_skeleton.md](character_skeleton.md). | `\assets\\models\` | -| Texture dictionaries | Same tool: TXD resources become DDS per texture. | `\assets\\textures\` | -| World textures (TTPF) | **Done (all 57 pools, 357,115 catalog entries, 0 failures):** the original exporter baseline exported **308,895** (98,603 complete, 210,292 partial) and skipped **48,220** (33,507 BCPack, 14,030 compact mapping, 678 arrays/volumes, 5 unsupported format, 0 unmapped). The compact-tail tool resolves 14,011 of the 14,030 layouts (305,264 complete, 1,100,865 mips, 4.59 GiB), the multi-slice pass resolves all 697 arrays/cubemaps/volumes ([textures_arrays.md](textures_arrays.md)), and DXGI 11 resolves the last 5 format skips, bringing the measured zlib/raw split to **305,959 complete, 16,423 partial, and 34,733 skipped** (0 remaining layout/format skips; all 34,733 are BCPack). Clean-room `tools/bcpack.py` decodes all six active BCPack modes (BC1, BC3, BC4, BC5, BC6H, BC7), giving a `tools/ttpf_mips.py scan` codec-availability projection of **357,115 complete / 0 partial / 0 skipped**; on full-corpus chunk decode with `--allow-provisional --history `, BC6H decodes 268 / 268 chunks (0 strict) and BC7 decodes 5,150 / 5,167 chunks (583 strict), while **17 / 5,167 BC7 chunks (0.33%)** still cleanly refuse in provisional mode. `rpf9dump`'s C# `TtpfReader` (`e293917` pin, `breadbbbb/rpf9-explorer#7`) decodes compact tails, multi-slice layouts, DXGI 11, and strict BCPack BC1/BC3/BC4/BC5 directly; BC6H/BC7 and provisional-history chunks remain skipped by `rpf9dump` and can be completed by `tools/ttpf_assets.py` ([textures.md](textures.md)). 46 pools are in `data\ttdb\**`, 11 in `pack\\data\ttdb\**` (exported under `ttpf_pack\\`). `data\ttdb\**\*.ttpf` (57 pools, 58 GiB) are loose RDS5 texture pools, **not** inside RPFs. rpf9-explorer's `TtpfReader` reads the catalog and detiles them; checked visually (`ttdb_graphics`: scope reticles, clean lines). Names are generated (`texture_N_`); models reference textures by asset key. Measured breakdowns and decode caveats are in [textures.md](textures.md). | `\assets\ttpf\\` + `manifest.json` | -| Animation | Indexed without the TOC: 130,470 zlib streams (4,203,762,662 stored / 11,593,460,132 inflated), 95.4% readable. New RAGE page directories (`0DRP`, version 122), `MoVE` (version 19), 273 `pack:/` name tables (2,298 paths), and a tail `RBF0` rig-set manager (`rage__crRigSetManager`: 1,126 rig sets, 6,677 source→rig entries, 3,669 distinct rigs; 56 empty). Bone data: one standalone 28-name table and 3 motion-matcher streams with embedded bone tables (30-name union, 19 joaat32 hashes present, 4 motionmatcher paths); no rig→skeleton link was found. Clip dictionaries are system-only RAGE resources (page map at the `+0x08` pointer). `tools/anim_clips.py` decodes 191,042 of 191,042 animations in 61,505 of them to per-frame values (channel types 0–5, 7, 8 and the GTA VI type 10) and resolves 111,948 of 159,584 `.motion` children to a clip. For each `.motion` it reads the per-child durations and time curves and, on 10,171 of 17,247, the one-axis parameter node (axis name hash, sorted sample values, range). All 1,781 second pages labelled `clip-stream` begin at the parent `0DRP` auxiliary table (+0x40), with two or three tagged payloads followed by schema data. The 2/3 packed streams are second pages of `0DRP` resources, which are not decoded. No `YCD`/`RSC7` at any stream start. The `rpf9_carve` tail overread is measured in `docs/animation.md`. | `tools\anim_index.py`, `\anim-index\` | -| Audio | `audio.rpf` holds raw (not zlib) **AWC** banks: Opus (codec 0x0B) and XMA2 streams. Exported as whole `.awc` files plus `audio_manifest.json` (stream ids, codec, channels, rate, duration). **Done: 7,162 banks, 27 GiB, 1,603,231 streams, about 1,324 hours** (codec 0x0B Opus 1,601,167; 5: 1,818; 2: 227; 0 PCM: 19). `tools/awc_opus.py` repackages every Opus stream **losslessly** into a standard Ogg Opus file (no re-encode; PCM streams become .wav). The AWC framing is 2048-byte blocks of [u16 length][packet], with a zero length padding the block (as rpf9-explorer's OpusPreview reads it). The final granule is `pre-skip + declared samples`; the EOS page is emitted at the packet that reaches that target and later padding packets are dropped, so decoders stop at the declared end. Checked: 20 real streams at 48 and 32 kHz decode to exactly their declared counts; 300 random streams decode with ffmpeg with no errors. XMA2 streams (codec 5, 1,818) are written as RIFF XMA2 files by `rpf9dump xma` (rpf9-explorer's `AwcRecovery.WriteXmaWave`) and decoded to PCM WAV by ffmpeg: all 1,818 decode. Streamed music (tag 0x48: chunks with a per-channel record table, each channel's 2048-byte subblocks after the aligned header, and a repeated-prefix skip per chunk) becomes one Ogg Opus per descriptor channel (3,008 banks contain music). The Opus TOC stereo bit gives the packet channel count; a 1-channel descriptor can carry stereo packets, whose interleaved sample count is halved for the end granule. Checked: a 4-channel bank gives four 42.0 s mono channels; 1-channel stereo banks export at the config duration. Output: `\assets\audio\ogg\\.ogg`. **Done: 1,598,051 Opus streams + 3,116 music channels as Ogg Opus (22 GB), 19 PCM16 and 227 codec-2 streams (32-bit float PCM, 4 bytes per sample; values can exceed ±1) as WAV, 1,818 XMA2 as WAV. Every audio stream is converted; all WAVs decode.** `make_game.py --wav` also decodes the Ogg Opus output to 16-bit PCM WAV with `tools/audio_wav.py` (ffmpeg required; existing WAVs are skipped on resume). | `\assets\audio\awc\` | -| World placement | **Full census of `levels.rpf`:** 23,535 map resources / 1,670,442 entities; all maps/entities exact, 36/36 shards, 98.32% stream coverage. Map files occupy a continuous band from ~7.5 to ~62.9 GiB; the earlier 9,918 / 680,228 sample was a 55% lower bound. `0x7a` resources: `CMapData` root, 0x90-byte `CEntityDef` with position/quaternion/scale/archetype/flags/per-entity id/per-archetype key/LOD fields; names and most archetypes are hash-only. Archetype and map names are lower-cased joaat, confirmed by a MurmurHash3 x64 low-64 key; see [world_names.md](world_names.md). | `tools\world_index.py`, `tools\world_census.py`, `tools\world_names.py`; [world.md](world.md), [world_census.md](world_census.md), [world_names.md](world_names.md) | -| Navmeshes | `navmeshes.rpf`: 90,295 zlib streams (6,540,238,392 stored / 20,551,068,624 inflated), 97.5% readable; 9,603 `0DRP` pages and 27,644 `0x00010015` pages, no `NAVM`/`CNavMesh`/`NVMS` magic. `0DRP` is generic RPF paging, not a navmesh container. | `tools\navmesh_index.py`; [navmesh.md](navmesh.md) | -| BVH | `core_bvh4.rpf`: 565,596 streams, 271,627 complete BVH4 streams + 10 eight-MiB split continuations, 269,106 instance records. Header `0x81020006` at +0x100, 64-byte node units, 208-byte instances with a 3x4 transform; prebuilt acceleration data, not source meshes or shaders. | `tools\bvh_index.py`; [bvh.md](bvh.md) | -| RBF0 | 1,263 `data.rpf` resources, 475,461 elements, 44,887 descriptors and 340,859 strings. Inline record stream with no section table; UI/Scaleform (`rage__fwui*`, screens, subtitles, settings). The `anim.rpf` tail uses the same format (`rage__crRigSetManager`). `tools/rbf0_tree.py` decodes every resource to a strict JSON/CSV/XML element, value and text tree. | `tools\rbf0_index.py`, `tools\rbf0_tree.py`; [rbf0.md](rbf0.md) | -| Gamedata | `common.rpf`: 954 streams (5,647,255 stored / 50,231,123 inflated), 85.5% readable; 266 XML documents / 118 roots (time/weather, vehicles/handling, peds/schedules, tuning, manifests, world/navigation); `tools/gamedata_xml.py` catalogs 267 payloads / 259 well-formed / 118 roots / 428,611 elements. No RBF0/PSIN. | `tools\gamedata_index.py`, `tools\gamedata_xml.py`; [gamedata.md](gamedata.md) | -| PSIN | `script.rpf`: 671 streams start with `PSIN`, 670 complete; sections `LSCH`, `LENM`, `LSNS`, `LGID`, `LRSC`, `CHKS`. `data.rpf`: 2,281 streams, 1,045 complete after joining. `LSCH` (type schema: structs and members) and `LENM` (enums) are decoded on all 17,664 / 17,641 whole sections across every archive, names as case-sensitive joaat. The instance data before `LSCH` is a block table plus 16-byte-aligned blocks with 20-bit-block pointers; read from the `LRSC` root through the schema, it reaches 129,100,004 of 129,117,812 block bytes on 17,507 containers. `LSNS` is a block table of 16-byte records (5,217 sections, 0 layout errors); the records are uniformly random, match no tested name hash and may be encrypted, so they stay unread. No plaintext scripts or names. Hash-typed members name other resources (u32: lower-cased joaat; u64: MurmurHash3 x64 low 64 bits): 228,427 values in 5,355 of 18,404 containers resolve against `rpf9_names.py` names, 299 control hits. | `tools/psin_index.py`, `tools/psin_data.py`, `tools/psin_names.py`; [psin.md](psin.md) | -| Audio config | `audio.rpf` first 19.5 MiB: 837 zlib streams / 54,143,493 inflated bytes. 1,589 music records, 1,589 distinct ids, exact milliseconds; `hash & 0x1fffffff` is the AWC stream id. 1,584/1,589 durations match the AWC manifest / 2; no per-track start offsets. | `tools/audio_config.py`; [audio_config.md](audio_config.md) | -| Page directory | `0DRP`: fixed 0x60-byte header, version 122; `q38` at +0x38 gives 16-byte records `{u32 hash, u32 size, u64 0x50000000 + target}`. `data.rpf`: 15,768 pages / 60,880 records; targets tile with zero overlaps. Names still need the TOC. | `tools/page_index.py`; [page_directory.md](page_directory.md) | -| Story / minigame | `story000.rpf` (18.65 GiB) is mixed: 264 Bink 2 streams (3.33 GB), 225,281 raw `RSC8` headers (v8001, AWC tag `0x5c` facial/lip-sync clips in its `ADAT` banks, see [rsc8_audio.md](rsc8_audio.md)), 442 nested RPF9 headers and zlib resource pages. `story000_script.rpf` is 2,309 PSIN streams (2,118 complete), not a named script container; `shared_minigame000` mixes pages, PSIN and XML. | `tools/story_index.py`; [story.md](story.md) | -| Rest-of-world / script | Six archives, 1.57 GB total: `core_restofworld` 1.21 GB (11 Bink 2 streams / 1.24 GB, 37 decoded models, 958 graphics pages, 6 PSIN), `story000_restofworld` 189 MB, `story000_script` 74 MB (2,309 PSIN, 2,118 complete), small `appdata0`/licences. No maps; no validated script container. | `tools/restofworld_index.py`; [restofworld.md](restofworld.md) | -| Audio stations | Audio config `0x762160`: 19 station blocks of `{station hash, u32 boundary, ordered u32 content ids}`; the boundary is a byte offset, not a count. VCRR content ids `0x28F2-0x2941` map exactly to records `0xBD73-0xBDC2` (80/80); other clusters are context-dependent or shared. Title-keyed stream ids resolve 702/800 resolved titles exactly and 746/800 with case/punctuation/feature variants. No per-track start offsets. | [radio_stations.md](radio_stations.md) | -| D3D12 command objects | Measured command queue / command list / fence / `PresentX` surface, split into verified exports and slots, prior-art claims, and open questions. Queue/list/fence creation and barriers are scoped; `PresentX` signature/slot and exact swapchain/plane parameters remain open until the executable is available. | [d3d12_command_objects.md](d3d12_command_objects.md) | - -### rpf9dump (bulk export) - -`tools\rpf9dump` is a small CLI over the Core library from https://github.com/breadbbbb/rpf9-explorer (a friend's tool; source at `third_party\rpf9-explorer`, audited: no keys, no network, no custom build targets). It decrypts nothing. It carves validated resources, as `rpf9_carve.py` does, but with working model and texture decoders. - -``` -dotnet build tools\rpf9dump\rpf9dump.csproj -c Release -o \tools\rpf9dump -rpf9dump models \assets -rpf9dump textures \assets -rpf9dump ttpf \assets\ttpf -rpf9dump audio \assets -rpf9dump xma \assets -python -I make_game.py --stages assets # everything, in order; skips what is done -``` - -Full-scan indexes are also saved to `%LOCALAPPDATA%\RpfPreview\Indexes`, so the rpf9-explorer GUI opens these archives with complete listings instead of its 16 MiB preview scan. - -## Other prepared pieces - -- `python -I tools\shader_profile.py \shaders\dxbc\disasm` writes the instruction profile to - `\shaders\dxbc\profile.json` by default. Use `--out` to choose a different file. An earlier corpus run - reported 551 distinct mnemonics, with 204 accounting for 99% of instructions. Those counts predate the filter - for assembler directives and comments. -- `tools\shader_ir.py`: parses every disassembled instruction into opcode, typed operands (s/v registers and - ranges, NSA register lists, constants, literals, export targets, interpolation attributes), modifiers and - encoding bytes. On 1,000 shaders, 12 of 2.2M operands were left untyped before the last fix. This is the front end - for an RDNA→SPIR-V translator. -- `tools\rtti_scan.py`: MSVC x64 RTTI scanner (class names, bases, vtables). Tested on the bundled DLLs; run it on - the exe first. -- `tools\hashdict.py`: joaat hash→name dictionary (`\hashes.json`, 1.9M entries, checked against - `adder` = 0xB779A091). On day one, rerun with `--extra ` so PSO field and type names resolve. Without the exe - only about 1% do. -- Runtime shims: all of `xmem.dll` is shimmed with the measured argument shapes (`XMemAlloc`, `XMemFree`, - `XMemVirtualQuery(process, address, out64)`, `XMemGetWorkingSetStatistics(kind, out)`, with `kind` 0x20000001 at all seven FSR call sites). The `d3d12_xs` root-signature - serializer forwards to the PC `d3d12.dll` after clearing the Xbox flag byte; the deserializer forwards unchanged. - `D3D12XboxCreateDevice` returns an Xbox-ABI proxy over the PC device: every PC vtable slot is forwarded with - `this` adjusted, Xbox slot 62 is `CreateComputePipelineState`, and Xbox slot 76 maps resource creation to - `CreateCommittedResource` with the Xbox `0x101`/`0x1` layout word replaced by the PC layout. Slots 9/10 are - `ID3D12DescriptorHeap` methods, not device methods. The PC heap getters take a hidden return pointer (RDX), - while Xbox expects the 8-byte handle in RAX, so slot 14 wraps the heap and slots 9/10 convert it. The heap holds - a reference to the device proxy and its `GetDevice` returns that same proxy. Queues, fences, command lists and - `PresentX` extensions remain unimplemented. -- PSO metadata is a new variant (`PSIN`, `LSCH` schema, `LENM`, `LSNS`, `LGID`, `LRSC`, `CHKS`, little-endian). - CodeWalker's parser reads the container but not the new schema; dump it once the exe gives the field names. - -## Shader translation (RDNA → SPIR-V) - -`tools\rdna2spirv.py` (needs `spirv-val` on PATH — Vulkan SDK, or `spirv-tools` in WSL — and `spirv-as` too -unless `--assembler python` assembles in process with `tools\spirv_asm.py`) translates parsed RDNA code to -SPIR-V assembly, assembles it (`spirv-as` by default), and validates it with `spirv-val` (Vulkan 1.2). It runs one -lane per invocation and keeps VGPRs and SGPRs as uint arrays with exact bit patterns. Version 0 treated EXEC as -all-ones and covered only branch-free vertex and pixel shaders with no memory loads: common float and integer ALU -ops and exports to `gl_Position`, params and MRTs. Unsupported instructions are reported by name, never guessed. -In that version, `VS_Passthrough` and `VS_BlurFilter` translated and validated. Coverage across the corpus -and the blocking instructions are in `\shaders\spirv_run.log`; the former next steps, structured branches -(EXEC masks) and the descriptor/binding model for `s_load`, `s_buffer_load`, `buffer_*` and `image_*`, are now -implemented. Current coverage is in *Translator status* below. - -Also handled: 64-bit scalar moves, per-invocation EXEC reads, whole-quad mode on EXEC, `m0`, SCC, vector and scalar -compares, `v_mul_hi_u32`, `v_cvt_pkrtz_f16_f32` (now exact round-toward-zero; the earlier round-to-nearest version -could overflow to inf), and pixel interpolation (`v_interp_p1/p2/mov` become fragment inputs at their attribute's -location). MODE writes (`s_setreg`) model the f16/f64 rounding field, FP_ROUND[3:2], the only MODE field the -corpus writes; other MODE writes are refused (see Known approximations). - -`--opt` is off by default and runs a basic-block peephole pass, `tools/spirv_opt.py`, over the emitted -module before it is assembled: register store-to-load forwarding, `OpAccessChain` CSE, dead-store -elimination, `OpSelect`/`OpCopyObject` folding and DCE. Only Function-scope variables that do not escape -are tracked, and a variable with any dynamic index is excluded from whole-function dead-slot elimination. - -Measured on five hand-written pixel fixtures from `tests/semantic/fixtures/disasm`, with every result still -passing `spirv-val --target-env vulkan1.2`: `ps_ops` 76→33 instructions and 7,876→4,516 bytes, `ps_flat` -60→22 and 4,560→1,676, `ps_sdwa` 61→19 and 5,720→2,192, `ps_vcc_x2` 63→26 and 5,260→2,552, and -`ps_fnan_med3` 76→26 and 8,060→4,264. - -### GPU tests (RTX 4060 Ti) - -`runtime\test\vk_harness.cpp` (CMake target `vk_harness`, built by `scripts\build_runtime.ps1` or -`cmake --build runtime\build --target vk_harness`; see "Build the test programs" in `docs/testing.md`. It loads -`vulkan-1.dll` at runtime.) draws one triangle with a given VS + FS into an RGBA32F target and dumps the floats. -Test shaders are in `\gputest`. - -- **`VS_Passthrough` (translated) is bit-exact.** All 64×64 pixels are written, and `param0.xy` = (u, 1 − v) with max - error **0**, with zw = (0, 1) as exported. This covers the VertexIndex input, integer/float ALU, inline constants, - and position/param exports. -- **400 arithmetic-only translated pixel shaders** (no buffers, descriptors or subgroup ops), driven by a generic - full-screen VS feeding locations 0–15: the driver compiled every pipeline, every draw completed, and every output - was finite. This is a stability check, not a value check (there's no reference for these). -- **Texture path is exact** (`runtime\test\vk_texture_test.cpp`): translated `PS_PassthroughCopy` gives max error - **0.0** over all 64×64 pixels against the expected nearest-sampled 8×8 test texture. That covers push-constant - user data, a heap-relative `s_load_dwordx8` of the T#, the hash-table lookup of the T# and of the shader's - literal S#, bindless sampling, `v_interp`, and the f16 compressed export. **It also caught a translator bug** - that validation can't: compressed exports read the wrong register pair (LLVM prints `v4, v4, v5, v5`), giving - (r,g,r,g). That's fixed. -- After the export fix, 2 of the 400 smoke-test shaders (`PS_ImposterShadow` variants) gave non-finite red values. - The cause was round-to-nearest `pkrtz` overflowing to inf, fixed with exact RTZ. One variant is now fully finite. - The other was reported with 1 inf and 4 NaN in red, put down to the shader's own maths on the synthetic inputs. - **That doesn't reproduce, and the shader has no maths to produce it** (TEST-643): both variants are the same - nine-instruction body, whose red is `v_cvt_pkrtz_f16_f32` of v2 and 1.0. Both read only `SV_Position.z` (input - signature rw mask 4), so v2 is POS_Z_FLOAT, which the translator maps to `gl_FragCoord.z`; red is f16(depth), - finite for every rasterized fragment. Redrawn with `vk_harness` (64×64, a full-screen triangle with depth 0, 0.5 - and 1 at its vertices, synthetic values on locations 0–15) on an AMD RDNA2 iGPU (gfx1036, driver 32.0.21043) and - an RTX 5090: 4,096 of 4,096 pixels written, 0 inf and 0 NaN in red, red in [0.0059, 0.744], for both variants as - translated by `main` and by the initial commit's translator; all eight images are bit-identical. **Measured on - the hardware** with the pixel-shader oracle (#3061's `ps_oracle.py`, not on `main` yet; same iGPU, wave64): with a - template PS that reads only `FragCoord.z` and front facing, the driver enables PERSP_CENTER, POS_Z_FLOAT and - FRONT_FACE, so v0/v1 are the barycentrics, v2 the depth and v3 the facing, as the translator assumes. The raw - body (its export made uncompressed, so the packed words come back as they are) over the same draw gives 0 inf - and 0 NaN in 4,096 of 4,096 pixels; each red half is the round-toward-zero f16 of that pixel's v2 (4,096 of - 4,096, checked on the CPU), and the translated shaders' red equals it bit for bit on both GPUs. - -### Translator status and runtime contract - -Full corpus (verified pixel-shader inputs incl. front face, ACO-confirmed 16-bit semantics, `vcc_hi` as an SGPR, -code-embedded data via `s_getpc_b64`, global memory, exact packed-f16 modifiers): **All 26,503 shaders translate and pass `spirv-val`** (Vulkan 1.2 target, `--allow-offset-texture-operand`): 2,236 VS, 12,101 PS, 2,689 CS, 9,282 mesh, 195 geometry. `spirv/index.json` lists each one's requirements. Output: -`\shaders\spirv\` (`.spvasm` + `.spv`), and the log is `\shaders\spirv_run.log`. - -How the generated SPIR-V expects the runtime to work: - -| Piece | Contract | -|---|---| -| Null sources in 64-bit integer VALU compares | `v_cmp` and `v_cmpx` relations `eq`, `ne`, `lt`, `le`, `gt`, `ge` on `u64` and `i64` read `null` as the 64-bit value 0 in either source, like immediate `0`. Register pairs and immediates retain their existing semantics; `v_cmp` writes the active lane's comparison to VCC/SGPR, while `v_cmpx` narrows EXEC without changing VCC. Source: RDNA2 ISA special operand `null` reads zero; LLVM `llvm-mc -mcpu=gfx1013` accepts the encoding. CPU-checked by `tests/semantic/test_vcmp64_null_src.py` (both sources, signed/unsigned ordering, equality, e32/e64, EXEC and inactive lanes); **not GPU-verified, no corpus count**. | -| Execution model | One invocation = one lane. Compute and mesh waves derive lanes from the workgroup-local index; other stages use the subgroup lane. A wave = a subgroup, so cross-lane ops (`ds_swizzle`, `v_permlane*`, `v_readlane`/`v_writelane`, `v_mbcnt`) become subgroup shuffles. Wave32 pixel shaders split a 64-lane physical subgroup into two logical waves: lane IDs are `SubgroupLocalInvocationId & 31`, shuffle sources retain the current half (`& 32`), and ballots/votes use that half's 32-bit word. A value the translator knows is uniform (the bindless descriptor index) is read from the half's first running lane, never from a fixed lane, which need not be running (SHADER-1016). Other stage/wave combinations still require subgroup size == wave size or wave64 emulation. **Requires subgroup size == wave size** (wave32 maps directly onto NVIDIA GPUs; wave64 shaders need a 64-wide subgroup or emulation). `v_readlane_b32`/`v_writelane_b32` mask the lane select with 63 in wave64 (`S1[5:0]`) and 31 in wave32 (`S1[4:0]`); until SHADER-52 both used 63, so a wave32 select ≥ 32 pointed past a 32-wide subgroup. GPU-checked with `cs_w32_lane_wrap.asm` (lane 40 → 8). For the fragment-half rule, `ps_bitmask_perm` produced 4096/4096 exact pixels on an AMD Radeon RX 5700 XT; Vulkan reported a default subgroup size of 64 (range 32..64), but does not permit pinning fragment subgroup size on this device. CPU semantic tests compare a 64-lane wave32 pixel subgroup against two 32-lane subgroups for reads/writes, permutations, ballots, and votes. | -| DPP | VOP1/VOP2 `_dpp` applies to src0. DPP16 controls (`quad_perm`, `row_shl/shr/ror/share/xmask/mirror/half_mirror`) and DPP8 (`dpp8` + `fi`) select the source lane, then `row_mask` (one bit per 16-lane row) and `bank_mask` (one bit per 4-lane bank) decide which destination lanes update. A lane whose row/bank is off is not written. A source lane outside the row is invalid: `bound_ctrl` 1 uses 0 as src0, otherwise the lane is not written. A source lane inactive under EXEC is used when `fi` is 1; otherwise `bound_ctrl` decides. DPP8 always writes an enabled lane: `fi` 1 reads the inactive source, `fi` 0 uses 0. DPP16/8 never leaves its 16/8-lane group, so this is exact on every subgroup at least that wide; under `--wave64-emulate` the exchange goes through the workgroup buffer like the other cross-lane ops. GPU-checked with `runtime/test/shaders/cs_dpp*.asm` on an RTX 3070 and hardware-measured on an RX 6800. On an RX 6700 XT (gfx1031), `tools/crosslane_fuzz.py --dpp-sweep --oracle hw` checks every DPP16 control × `bound_ctrl` × `fi`, every `row_mask`/`bank_mask` pair and the DPP8 selects in wave32 and wave64: 14,412 cases, all matching these rules (BUILD-162, `docs/shader_validation.md` FUZZ-7). The ballot of the source lanes' EXEC bits and the shuffle are each stored to a Function variable of their own (`Gen.eager`): SPIRV-Cross (MoltenVK) inlines a single-use result into the expression that uses it, which put the ballot on the right of a short-circuiting `&&` and the shuffle in a ternary's arm, so lanes out of their row skipped the ballot and row_shr:1's lane 1 found lane 0 inactive (`cs_dpp_ops` on MoltenVK; SHADER-529). A store is a statement every lane runs. Checked in SPIRV-Cross 1.3.239's MSL for the `cs_dpp*` tests (each op is now its own statement) and by `tests/semantic/test_dpp_eager_subgroup.py`; not yet run on a Mac. Semantics from the RDNA2 ISA, AMD LLVM modifier syntax and the GPUOpen DPP notes. | -| EXEC | A per-invocation `active` flag. VALU writes and exports are masked by it, scalar ops aren't, and `v_cmpx`, saveexec and EXEC writes update it. A pixel lane still inactive at the end is discarded. Measured on native gfx1100 (8 threads): a `v_mov_b32` under `EXEC=0x0F` leaves the other lanes untouched, `EXEC=0` writes nothing, a store writes only active lanes and `v_cmpx_gt_u32` narrows EXEC (4 of 4 cases); note that AMD clang 20 rejects `v_add_co_u32`, `v_sub_co_u32`, `v_add_co_ci_u32` and `v_mad_u64_u32` for `gfx1100`, `gfx1101` and `gfx1102`, so this toolchain could not reproduce the RX 7600 result below, which leaves open whether those parts support the opcodes and says only that they could not be assembled here. **A pixel is written when its lane was on in EXEC at the last `exp ... vm` the path executed (if it executed one) and at the last export to the color target; a path with no export at all goes by EXEC at the end.** The `vm` half is the RDNA2 ISA reference guide's rule (30-November-2020, §11.1 and §11.2.1: EXEC at the export is the valid mask and the final one sent is used; an `exp null ... vm` carries only the mask). The color half is measured: an export sends data only for the lanes that are on, a later export to the same target replaces the earlier one for the whole wave, and a lane with no data from the last one is not written even when a later `exp null done vm` marks it valid. So `exp mrt0 done` (no `vm`) with every lane on, followed by an EXEC write, still writes every pixel, and EXEC off at that export and back on afterwards writes none. **Measured on RDNA2** (AMD Radeon iGPU, gfx1036, driver 26.10.1) with the pixel-shader oracle of #3061 (`ps_oracle.py`), hand-written ISA as the pixel shader of a real draw (wave64 stage): 18 programs that cut EXEC to half of the target before, between or after `exp mrt0` (with and without `vm` and `done`) and `exp null done vm`; all 18 fit the rule, 6 of them differed from the translator, which until 2026-11-23 discarded by EXEC at the end on a path without `vm` and kept the older export's value (or the output's initial value) for a lane that was off at the last color export. The latches (`%vm_mask`, `%col_mask_mrtN`) are only emitted where a path can write EXEC after a `vm` or color export; everywhere else EXEC at the end is the same mask and the SPIR-V is unchanged. With several color targets a pixel stays when any target got an export from its lane (Vulkan cannot skip one attachment per pixel; not measured, the oracle's pipeline has one target); `mrtz` is not part of the color mask (not measured). **Measuring exports needs `s_waitcnt expcnt(0)` after each one**: an export is asynchronous, and without the wait the hardware takes the data and the EXEC of a later moment (`v_mov v9, A; exp mrt0 v9 done vm; v_mov v9, B` shows B, and an EXEC write right after the export decides which pixels are written, which looks like "EXEC at the end decides"); 64 `s_nop 15` have the same effect as the wait. Checked on the CPU by `tests/semantic/test_export_valid_mask.py` and on the GPU by `runtime/test/shaders/ps_exp_color_mask.asm` (RTX 5080 and the Radeon). VALU scalar lane-mask destinations (`v_cmp_*`, `v_add_co_u32`, `v_add_co_ci_u32`, `v_sub_co_u32`, `v_sub_co_ci_u32`, `v_subrev_co_u32`, `v_subrev_co_ci_u32`, `v_mad_u64_u32`, `v_mad_i64_i32`) write 0 for lanes off in EXEC (`SDST[lane] = EXEC[lane] ? bit : 0`, AMD RDNA2 ISA). Until 2026-11-22 the six `*_co_*` ops and `v_mad_u64_u32`/`v_mad_i64_i32` did not AND the carry/sign bit with `active`, so inactive lanes leaked 1 bits into `VCC`/SGPR masks (`s_bcnt1`, `s_cbranch_vccz`, `v_cndmask_b32`). Checked on the CPU by `tests/semantic/test_carry_exec_mask.py` (wave32, wave64, and `--wave64-emulate` structure), and **hardware-verified on an AMD RX 7600 (gfx1102)** with `v_add_co_u32` and `v_add_co_ci_u32` carrying on every active lane: VCC reads `0xffffffff` with full EXEC, `0x0000ffff` for the mask `0x0000ffff` and `0xaaaaaaaa` for `0xaaaaaaaa` in wave32, `vcc_lo = 0x0000ffff` with `vcc_hi = 0x0000000f` for the same partial mask in wave64, and `0` when EXEC is 0 even with VCC preloaded to all ones; with one carrying lane under mask `0x0000ffff` VCC is `0x00000001`, and `v_sub_co_u32`/`v_subrev_co_u32` with a borrow under that mask give `0x0000ffff` too. The `*_co_ci_` forms, `v_mad_u64_u32` and `v_mad_i64_i32` share the same path but were not measured separately; it is also GPU-verified on native RDNA2 (gfx1036, AMD Radeon Graphics) with partial EXEC masks (inactive lanes write 0 in sdst for `v_add_co_u32` and `v_mad_u64_u32`). In a shader that writes EXEC, a run of two or more lane-local VALU instructions (no cross-lane read, no lane-mask, SCC, carry or EXEC write) sits inside one `if (active)` and writes its VGPRs directly, instead of an `OpSelect(active, new, old)` per write: the same result, but the driver predicates the run with its own EXEC instead of keeping both values live. On an RX 5700 XT (RADV) a pixel shader with 8 divergent if/else regions of `v_fma`/`v_mul`/`v_add`/`v_min`/`v_max` went from 0.85 ms to 0.69 ms (the same program as native SPIR-V: 0.65 ms). Not under `--wave64-emulate`. Checked by `tests/semantic/test_active_runs.py`. | -| `s_*_saveexec_b32/b64`, `s_andn1/andn2_wrexec_b32/b64` | RDNA2 ISA SOP1. saveexec: `D = EXEC; EXEC = f(S0, EXEC); SCC = (EXEC != 0)`. wrexec: `EXEC = f(S0, EXEC); D = EXEC`. `f` is one of `and`, `or`, `xor`, `andn1` (`~S0 & EXEC`), `andn2` (`S0 & ~EXEC`), `orn1` (`~S0 \| EXEC`), `orn2` (`S0 \| ~EXEC`), `nand`, `nor`, `xnor`, the table in `Gen.EXEC_LOGIC`. The definitions match `tools/cf_ref.py` `_SAVEEXEC`, the FUZZ-8 model. Each invocation holds its own lane's bit (0 or ~0), so `f` is the bitwise op on that bit. A lane EXEC had off becomes active when `f` gives 1 for it (`nand`, `nor`, `orn1`, `orn2`, `xnor`, ...), as on hardware, and SCC is the wave vote. Until 2026-11-22 only `and`/`or`/`andn2_saveexec` and `andn2_wrexec` were translated. CPU-checked by `tests/semantic/test_saveexec_variants.py` (all ten saveexec kinds in wave32 and wave64, both wrexec kinds, partial EXEC and S0, an empty result, every lane against `cf_ref._SAVEEXEC`) and by `tools/cf_diff.py` (300 programs × wave32/64 still pass). Hardware-verified on native RDNA2 (`gfx1036`, Windows 11, driver `32.0.21045.29003`, wave32 & wave64, 0 mismatches): all 10 `saveexec` kinds and both `wrexec` kinds (`andn1`/`andn2`) match bit-for-bit on non-symmetric masks (`src0 = 0x0F0F0F0F`, `exec = 0x33333333` in wave32; `0x0F0F0F0F_00FF00FF` / `0x33333333_55555555` in wave64), zero-result `SCC = 0`, wave64 upper-32-bit-only `new_exec = 0x00000001_00000000` setting `SCC = 1`, and `sdst == src0` register aliasing (`s4, s4` and `s[4:5], s[4:5]`) reading original `src0` before writing old `EXEC` to `sdst`. **Not GPU-verified** for the seven new kinds. Measured on native gfx1100 (single 8-lane workgroup, 36 programs): all ten `saveexec` kinds and both `wrexec` forms follow `f` for three `S0`/`EXEC` pairs, including lanes `EXEC` had off being switched back on (`nand` with `S0=0x03`, `EXEC=0x0F` leaves `0xFFFFFFFC`, activating lanes 4-7), `D` holding the old `EXEC` for `saveexec` and the new one for `wrexec`, and `SCC` the `EXEC != 0` vote. | -| Control flow | Reducible graphs use structured branches and natural loops. Irreducible graphs use the dispatch-loop form, which can also be forced with `--dispatch-loop` for comparisons. The control-flow unit test checks 18,228 generated graphs. Irreducible graphs use node splitting (`cfg_structure.split_irreducible`, up to `min(2*N, N+64)` blocks) and fall back to the dispatch-loop form when capped; it can also be forced with `--dispatch-loop` for comparisons. `cfg_structure.structure`, `cfg_structure.run`, and `rdna2spirv.assemble`'s structured emitter are iterative and hoist each guarded member's dominated tail continuation out of its enclosing guard (exact by strict dominance: no block outside the guard's subtree can target the continuation), keeping `OpSelectionMerge` nesting O(1) on sequential diamond/loop chains instead of nesting O(N) deep and hitting Python's recursion limit on multi-thousand-block shaders (e.g. 2,000 sequential diamonds nest to depth 2 instead of 2,000). The control-flow unit test (`tests/test_cfg_structure.py`) checks 20,000 generated graphs plus 2,000-diamond, 1,200-loop, and 1,500-early-exit chains. AMD A/B checks compare the two forms for selected pixel shaders with defined test inputs. For shaders that never export colour, the comparison checks pixel coverage. **Nesting is bounded (SHADER-299):** a tree deeper than `MAX_STRUCTURED_DEPTH` (16) is emitted in the dispatch-loop form instead, since `spirv-val` time grows roughly with the cube of the measured nesting depth. **Nesting is bounded (SHADER-299, SHADER-427):** a tree deeper than `MAX_STRUCTURED_DEPTH` (64; `--max-structured-depth N`, 0 = no bound) is emitted in the dispatch-loop form instead, since `spirv-val` time grows roughly with the cube of the measured nesting depth. Before #1904, over the 1.0.2.1 corpus (26,503 modules, `spirv-val` 2026.4): the deepest block of a module is nested 118 constructs deep, 12,963 modules are structured (median 15) and 6,000 of those are deeper than 16; an estimated 85% of the corpus's `spirv-val` time is in modules nested 20 or deeper. Median `spirv-val` time for the same module in each form: depth 20 181 -> 129 ms (1.4x), 30 507 -> 371 (1.4x), 50 1,712 -> 738 (2.3x), 64 2,692 -> 1,163 (2.3x), 77 5,122 -> 1,130 (4.5x), and the deepest (118) 13,683 -> 1,352 ms (10.1x). Depth 5-12 shows no gain (at depth 6 the flat form is slightly slower), which is why the bound first sat at 16. Since #1904 (`cfg_structure` hoists tails) the deepest tree in the corpus is 29: of 12,944 structured modules, 1,031 are deeper than 16 (747 CS, 284 PS), 57 deeper than 20, 24 deeper than 24. For those 1,031 the flat form saves only 12% of `spirv-val` time (1,235 -> 1,091 s summed, slowest module 8.3 -> 5.9 s), while on an RTX 5070 Ti (NVIDIA 621.24) it compiles slower: the 284 pixel shaders 1.67x (827 -> 1,382 s summed, two rounds), four compute modules at depth 19-24 2.0x (297 -> 591 s, 1.6-2.7x each), so the bound now sits above the corpus (SHADER-427). Both forms pass `spirv-val` on a 200-shader slice (200/200 each), and `gen.nesting` records the tree depth. AMD's Windows driver adds a reason to keep the structured form (SHADER-995): on a Radeon gfx1036 iGPU (32.0.21042.62) the dispatch-loop module of `XboxBvhBuilder.dll`'s `LeafRehydration` (tree depth 18, a 581-case switch) takes 34 minutes to create (XXDESIGN), where its structured module is created in 2.9 s; ten other programs of that DLL compile in the dispatch-loop form there in 0.4-40 s, 2.5-5x their structured time ([embedded_shaders.md](embedded_shaders.md), section 7). | -| User data | **Push constants, 144 bytes:** dwords 0–31 = initial s0–s31 (the user SGPRs the console driver loads from the root signature: descriptor-table pointers, constants and so on), dwords 32–33 = the 64-bit **heap base**, dwords 34–35 = the **code base**: the Xbox VA where the runtime uploaded this shader's whole FSSM blob. `--mesh-compute` modules add dwords 36–37, the output buffer address (152 bytes; see "Mesh shaders as compute"). `--pc-tail-ubo` keeps only dwords 0–31 here (128 bytes) and moves the rest to a uniform block (see "Push-constant tail as a uniform block"). The runtime has to reproduce the console driver's root-signature-to-user-SGPR mapping; that comes from the exe or driver behaviour. | -| Xbox GPU addresses | Shaders build Xbox GPU virtual addresses, and some force the high dword to 0 (descriptor tables in the low 4 GB). Every memory access goes to **heap base + Xbox VA**, so the runtime maps the console's GPU address window into one host buffer-device-address allocation. | -| Code-embedded data | 155 VS/PS had "undecodable words". They're **constant tables inside the code range** (float values like 0x3EF7…, plus zeros), read through `s_getpc_b64` + `s_add_u32`/`s_addc_u32` + `s_load` (147 of 155). The translator re-anchors each instruction to its true FSSM offset by matching encodings, translates only code reachable from entry (a branch into data is rejected), and turns `s_getpc_b64` into code base + next-instruction offset. **The runtime uploads each shader's FSSM blob into the heap and passes that VA as the code base.** Re-anchoring compares bytes exactly, except that VOP3P `op_sel_hi[2]` (bit 14) is ignored on two-source packed ops: the compiler stores 0 there, and LLVM prints its default of 1. Unused VOP3/VOP3P `SRC1` (bits 49:41) and `SRC2` (bits 58:50) fields are also ignored when stored as 0 and printed as `0x80`: LLVM 23 re-encodes a source it doesn't read as inline constant 0 (one-source `v_rcp`/`v_log`/`v_sqrt_f32_e64`, two-source `v_sub_f32_e64`/`v_cmp_*_e64`/`v_mul_lo_u32`/`v_pk_mul_f16`). Both checks for clean listings and re-anchoring use the parsed operand count to apply this exception only to unused sources. A used source encoded as 0 reads `s0` and is never treated as inline zero. `tests/semantic/test_printed_encoding.py` checks used `SRC1`/`SRC2` and an unused field with synthetic listings. Confirmed by a count over the corpus with LLVM 23.1.5: without it, 1,471 of the 1,473 shaders with embedded data are rejected ("reachable instruction with normalized encoding"); with it, all 1,473 translate and pass `spirv-val`. Runs with LLVM 21 already translated all of them, so older LLVMs presumably print the stored 0 (not re-checked). Data words that decode with ignored fields set are printed re-encoded (e.g. `0xbe8d2242` as `s_rfe_b64` `0xbe802242`), so they can never match. Since the decoder consumed the same length, they are anchored in sequence and marked. A shader that can *reach* a marked word is rejected; none of the corpus does. All 155 now translate. A reachable instruction that falls through into words llvm-mc skipped (it printed no instruction there) is rejected too, as `fall-through into undecodable words`: until SHADER-813 the reachable path ended there without a word, so everything after the gap (exports, stores) was dropped from a module that still passed `spirv-val`. No VS/PS of the corpus has such a gap on a reachable path; in the FidelityFX FSPX programs it is the `v_dot4_i32_i8 ... op_sel` words LLVM 23 cannot decode (`docs/fspx.md`), so those programs are now refused instead of translated without their stores, until those words are decoded (#2038, #2323). `tests/test_rdna2spirv_decode.py` (`test_fall_through_into_undecodable_words_is_refused`). | -| VOP3 opcode 0x140 | LLVM disassembly of the synthetic words in `tests/test_rdna2_decode.py` gives `v_mad_legacy_f32` on gfx1010 through gfx1013 and `v_fma_legacy_f32` on gfx1030. The direct decoder defaults to gfx1013, matching the disassembler CLI. Checked by the unit test `test_vop3_legacy_mad_fma_target` in `tests/test_rdna2_decode.py`, which decodes the same words directly and runs the Python disassembler backend for gfx1013 and gfx1030. | -| Printed encodings | A listing is LLVM's text for what it decoded, not the bytes it read, so the translator checks the two against each other: the re-anchoring above for listings with undecodable words, and, for every other listing whose header names its code range and whose blob sits next to it (`fssm/`, or `fspx/` for FSPX), each instruction's printed encoding against the bytes at its offset, with the same exceptions (`same_encoding`). A difference is `Unsupported`, naming the instruction, its offset and both byte strings, instead of a translation of the field as 0. The case that prompted it: llvm-mc's gfx1013 decoder (LLVM 21.1.8) drops the VOP3 `op_sel` bits (word 0, bits 14:11) of a 16-bit VOPC compare: `0a 08 a9 d4 01 05 02 00` disassembles as `v_cmp_lt_u16_e64 s10, v1, v2` and re-encodes with the bits cleared (its assembler rejects `op_sel` on VOPC for gfx1013 and gfx1030 alike). Counted over the 1.0.2.1 corpus: the 25,030 clean listings hold 30,335,381 instructions, and none differs from its bytes beyond those exceptions (754); the 166 16-bit VOPC compares (154 shaders, all `f16`) have `op_sel` clear. Hand-written listings, `run_gpu_tests.py`'s `code 0x0..0x0 (synthetic)` listings and a blob that doesn't hold the listing's code range (the tests' header-only FSSM) are not checked. `tests/semantic/test_printed_encoding.py` (a dropped VOPC `op_sel`, a later instruction, the SRC2 exception, and the unchecked cases). One difference is repaired instead of refused: a `v_fma_mix*` literal that llvm-mc prints cut to its low 16 bits (and re-encodes with a zero high half). llvm-mc 23.1.5 prints some of these literals in full as `lit(V)` (an f32 source, or a low half that is an inline constant; LLVM 21 printed the inline constant and dropped the literal word) and still re-encodes only the low half: `tools/shader_ir.py` reads `lit(V)` as V, and the same repair applies (5,733 such operands in the pipeline library, [shader_library.md](shader_library.md)). When the 8 instruction bytes match (`same_encoding` with all three sources counted as used, so a live `s0` can't pass as an inline 0) and the printed literal is the stored one's low half, every source the bytes encode as the literal (SRC field `0xff`) takes the stored 32 bits, so a source with `op_sel_hi` and `op_sel` set reads the high half instead of +0.0. Seen in one program of the FidelityFX DLL's `FSPX` code ([fspx.md](fspx.md)): src0 the low half, src2 the high half; the game's clean listings have no such difference (the count above). That the hardware gives op_sel's high half of the literal to that source is not measured; it is what Mesa's ACO compiler relies on (public: `optimize_constants()` in `src/amd/compiler/aco_optimizer.cpp`, Mesa `main` at `bb986060`, packs two constants as the two f16 halves of one literal, read through `v_fma_mix`'s `op_sel_hi` with the second source extracting the high half), and what the console compiler emitted here. `tools/fma_mix_literal_probe.py --oracle hw` measures it on an AMD GPU (the instruction's exact bytes through `tools/hw_oracle`; not run on one yet). `tests/semantic/test_fma_mix_literal.py` (the value through the interpreter, the re-anchoring path, an inline constant with the literal's printed value left alone, and the refused cases, a live source printed as inline 0 among them). A second shape is repaired too (`mix_inline_literal`): LLVM 21's form above. llvm-mc 21.1.8 (`-mcpu=gfx1013`) prints a `v_fma_mix*` literal whose low 16 bits are the f16 value of an inline constant as that constant and re-encodes the instruction in **8** bytes: every SRC field that held `0xff` holds the inline code, and the literal word is gone (`0x3f800000`, 1.0 as an f32 source, prints as `0`; `0x3c003800` as `0.5`, losing the high half 1.0). Swept with llvm-mc 21.1.8 over all 65,536 low halves under three high halves: exactly 90 low halves print this way (0..64, -1..-16, ±0.5, ±1.0, ±2.0, ±4.0, 1/(2π) as f16: `MIX_INLINE_F16`), whatever the high half; llvm-mc 23.1.6 prints all of them as `lit(V)`. The printed 8 bytes are 4 short of what the decoder read, so the later offsets of a clean listing were 4 low and its first such instruction was refused as a dropped field (one FSPX program, `tupacfan04`'s count in #8683). When every differing SRC field is `0xff` in the blob and the inline code of the stored literal's low half in the print, and the rest of the 8 bytes match exactly (`same_encoding`, all three sources live), each such source reads the stored 32 bits with the stored neg and abs (`NEG_HI`) bits, the instruction takes the 12 stored bytes, and the following offsets move up by 4 (also on the re-anchoring path). Any other difference stays `Unsupported`. CPU-checked by `tests/semantic/test_fma_mix_literal.py` (`FmaMixInlineLiteralTest`: an f32 source, two f16 halves, neg and abs, all 90 codes, both listing paths, the refused cases). | -| Global memory | `global_load/store_dword*`: address = (64-bit SGPR base + zero-extended 32-bit VGPR offset, or a 64-bit VGPR address) + the instruction offset, translated through the heap base. Inactive lanes don't access memory, and loads merge their previous values with OpPhi. The offset is the **signed 12-bit** byte value as llvm-mc prints it, -2048..2047 (`offset:-4` is the field 0xffc; llvm-mc rejects `offset:0xffc` and disassembles that field as `offset:-4`, so no repo path delivers the raw unsigned field), added to the address as is; a tool that printed the raw field (`0xffc`) would mean the same offset, and a value outside 12 bits is rejected. Measured on an AMD Radeon RX 6800 (gfx1030) running `global_load_dword` as a raw compute kernel, wave32 and wave64 alike, with the dword at byte n = 0x10000000+n and the pointer at 0x1000: offset 0 reads 0x10001000, -4 0x10000ffc, -2048 0x10000800, 2044 0x100017fc, -1024 0x10000c00. The translator used to subtract 0x1000 from an already negative value (4096 bytes too low). Checked by `tests/semantic/test_global_mem_offset.py` (both addressing modes, dword/x2/x4, byte/short loads and stores at -4, -2048, 2047 and 0) and the GPU test `runtime/test/shaders/cs_global_neg_offset.asm` (`vk_compute_test ... 40 dump`). | -| Global atomics (`global_atomic_*`, 32-bit) | `add`, `sub`, `smin/umin`, `smax/umax`, `and`, `or`, `xor`, `swap` and `cmpswap` at the `global_load/store` address (same `Gen.global_address`: saddr pair plus zero-extended vaddr, or a 64-bit vaddr with `off`, plus the signed 12-bit offset), as one `OpAtomic*` on the PhysicalStorageBuffer dword, device scope, guarded so inactive lanes don't touch memory. `fmin` and `fmax` (32-bit float) lower to a structured `OpAtomicCompareExchange` CAS loop using GLSL.std.450 `NMin`/`NMax` (no Vulkan float-atomic extension needed; NaN returns the non-NaN operand, `-0.0 < +0.0`). `inc` and `dec` (32-bit unsigned wrapping against `DATA`: `inc` gives `(M >= DATA) ? 0 : M + 1`, `dec` gives `(M == 0 \|\| M > DATA) ? DATA : M + 1`, `dec` gives `(M == 0 With `glc` the pre-op value lands in `vdst`, the first operand; without `glc` there is no `vdst`, and the first-read analysis counts operand 0 as the address (a source). `cmpswap` takes `vdata` as the pair {DATA, CMP}: `M = (M == CMP) ? DATA : M`, as `buffer_atomic_cmpswap`. Still `Unsupported`: the `_x2` 64-bit forms, `inc`/`dec`, the float atomics, and `slc`/`dlc`. `and/or/xor/swap_x2` work on a 64-bit element (two dwords, low first) as one 32-bit atomic per dword, with no Int64 atomics: a bitwise op leaves the same memory that way, since its bits are independent. **Approximation:** an exchange can tear, since two lanes swapping into one element at once can leave one's low dword with the other's high dword (A.lo, B.lo, B.hi, A.hi), and the returned pair comes from two reads, so another lane's 64-bit op on the same element between them can show up half done (as for `ds_and/or/xor_b64`). **Approximation:** the returned pair comes from two reads, so another lane's 64-bit op on the same element between them can show up half done (as for `ds_and/or/xor_b64`). Still `Unsupported`: the other `_x2` forms (`add/sub/min/max/fmin/fmax_x2` carry or compare across the dwords, and `cmpswap_x2` compares all 64 bits), `inc`/`dec`, `fcmpswap`, and `slc`/`dlc`. Until 2026-11-22 every global atomic was rejected. CPU-checked by `tests/semantic/test_global_atomics.py` (all ten ops on a value grid with and without `glc`, `cmpswap`, offsets from -2048 to 2044, `off` addressing, seeded values, rejected forms, the first-read analysis). CPU-checked by `tests/semantic/test_global_atomics.py` (all ten integer ops plus `fmin`/`fmax` on a value grid with and without `glc`, NaN/±0/±inf, multi-lane CAS contention, `cmpswap`, offsets from -2048 to 2044, `off` addressing, seeded values, rejected forms, the first-read analysis) and `tests/semantic/test_global_atomics_x2.py` (the four `_x2` forms with and without `glc`, an offset, seeded values, the carrying forms rejected), and validated with `spirv-val` (native and `--wave64-emulate`). **Not GPU-verified.** \|\| M > DATA) ? DATA : M - 1`, RDNA2 ISA) also lower to a structured `OpAtomicCompareExchange` CAS loop via `Gen.atomic_inc_dec_cas` for both `global_atomic_{inc,dec}` and MUBUF `buffer_atomic_{inc,dec}` (preserving MUBUF bounds checks: OOB/inactive lanes leave memory untouched and return 0 with `glc`). With `glc` the pre-op value lands in `vdst`, the first operand; without `glc` there is no `vdst`, and the first-read analysis counts operand 0 as the address (a source). `cmpswap` takes `vdata` as the pair {DATA, CMP}: `M = (M == CMP) ? DATA : M`, as `buffer_atomic_cmpswap`. `and/or/xor/swap_x2` work on a 64-bit element (two dwords, low first) as one 32-bit atomic per dword: a bitwise op or an exchange leaves the same memory that way, with no Int64 atomics. **Approximation:** the returned pair comes from two reads, so another lane's 64-bit op on the same element between them can show up half done (as for `ds_and/or/xor_b64`). Still `Unsupported`: the other `_x2` forms (`add/sub/min/max/inc/dec/fmin/fmax_x2` carry or compare across the dwords, and `cmpswap_x2` compares all 64 bits), `fcmpswap`, and `slc`/`dlc`. Until 2026-11-22 every global atomic was rejected. CPU-checked by `tests/semantic/test_global_atomics.py` (all ten integer ops plus `fmin`/`fmax` on a value grid with and without `glc`, NaN/±0/±inf, multi-lane CAS contention, `cmpswap`, offsets from -2048 to 2044, `off` addressing, seeded values, rejected forms, the first-read analysis), `tests/semantic/test_atomic_inc_dec.py` (`global_atomic_{inc,dec}` and `buffer_atomic_{inc,dec}` edge grid, wraparound, `glc` vs non-`glc`, signed offsets, `off` addressing, MUBUF bounds/OOB, inactive lanes, multi-lane CAS contention, first-read analysis, rejected `_x2`/`slc`/`dlc` forms), and `tests/semantic/test_global_atomics_x2.py` (the four `_x2` forms with and without `glc`, an offset, seeded values, the carrying forms rejected), and validated with `spirv-val` (native and `--wave64-emulate`). **Not GPU-verified.** | -| `global_atomic_csub`, `buffer_atomic_csub` (GFX10.3) | `tmp = M; M = (DATA > tmp) ? 0 : tmp - DATA`, unsigned: a subtract clamped at 0 that never wraps; with `glc` the old M comes back. Measured on gfx1036 by @Vonsek (#3193): 162/162 (memory, data) pairs over both forms. Same `OpAtomicCompareExchange` loop as `inc`/`dec` (`Gen.atomic_inc_dec_cas`), so exact under contention; operands, inactive lanes, buffer bounds and `glc` as `inc`/`dec`. Until 2026-11-22 both raised `Unsupported`. CPU-checked by `tests/semantic/test_atomic_csub.py` (a 9×9 value grid, no `glc`, buffer bounds, 32 lanes on one dword against 32 sequential subtracts, seeded values). The translation is not GPU-verified. | -| Sub-dword MUBUF loads and `GFX10_FORMAT_8_UINT` | `buffer_load_ubyte`, `buffer_load_sbyte`, `buffer_load_ushort` and `buffer_load_sshort` read 1 or 2 bytes at `Gen.buffer_address(..., elem=1 \| 2)` (same `OOB_SELECT` end check with element size 1 or 2 bytes; out-of-bounds returns 0 without reading memory; inactive lanes preserve `vdst`), zero- or sign-extending to 32 bits; 16-bit loads at byte offset 3 within a dword merge byte 0 of the next dword (`idx1 = (b3 == 3) ? 1 : 0`) without over-reading past the buffer. `FORMATS` adds code 5 (`GFX10_FORMAT_8_UINT`, 1-byte unsigned integer) for `tbuffer_load_format_*` / `buffer_load_format_*` (with `DST_SEL` integer 1). Needed by `XboxBvhBuilder.dll` (#1813 follow-ups: `Box16Rehydration`, `Box32Rehydration`, `ReloadTriangles`, `LeafRehydration`). CPU-checked by `tests/semantic/test_buffer_load_sub.py` and validated with `spirv-val` (native and `--wave64-emulate`). GPU-checked (TEST-510) through Vulkan by `runtime/test/shaders/cs_buf_load_sub.asm` (ubyte/sbyte/ushort/sshort zero- and sign-extended, the dword-crossing ushort at offset 3, and the RAW end check by element size: a ushort at 7 of 8 bytes reads 0, where a start-only check would read the next bytes) and `cs_buf_fmt8.asm` (`BUF_FMT_8_UINT` at offsets 0..3, out of range, an INVALID V# format, `DST_SEL` integer 1), both in `scripts/run_gpu_tests.py`: pass on an NVIDIA GeForce RTX 3070 Ti (driver 610.88) and, with the same eight words, on an AMD RX 7600 (`gfx1102`) and a Ryzen 5 9600X iGPU (`gfx1036`, RDNA2, RADV Mesa 27.0.0-devel), so the `vdst` preservation, the sign/zero extension, the ushort load across a dword and the element-size end check are GPU-checked on AMD too. `tools/hw_oracle` was not used for this; the Vulkan path above is what the translator runs. Not measured on AMD hardware (`tools/hw_oracle`). **Not GPU-verified.** Measured on an AMD Radeon RX 7900 XTX (`gfx1100`, driver 26.10.1) by running the instructions as a raw compute kernel (`tools/hw_oracle`, wave32, seeded synthetic bytes): the four loads zero-/sign-extend at byte offsets 0..7, the ushort at byte offset 3 merges byte 0 of the next dword, and with `NUM_RECORDS` = 8 the end check uses the element size (a ubyte at 7 reads where one at 8 returns 0, a ushort at 6 reads 0x5eee where one at 7 returns 0, an sshort at 7 returns 0 where an sbyte at 7 reads). `buffer_load_format_x` with `FORMAT` code 5 and `tbuffer_load_format_x format:[BUF_FMT_8_UINT]` return that byte zero-extended with the same 1-byte end check (at `NUM_RECORDS` 8, offset 7 reads 0x5e and 8 returns 0), and a V# whose `DST_SEL`s are 1/2/3/4 returns the integer 1 in all four components, not the fetched byte. The inactive-lane clause rests on the NVIDIA run. **Not GPU-verified.** | -| 8/16-bit global stores and d16 loads | `global_store_byte`/`short` write the low 8/16 bits of the data VGPR (the `_d16_hi` forms its high half). `global_load_{u,s}byte_d16` and `global_load_short_d16` write the low 16 bits of `vdst` (the `_hi` forms the high 16) and keep the other half; `ubyte` zero-extends and `sbyte` sign-extends the byte to 16 bits. The address is the `global_load/store` one (`Gen.global_address`). The access goes one byte at a time, so a 16-bit access that crosses a dword (at byte 3) is exact too. A store merges each byte into its dword with atomic and/or, which keeps neighbouring bytes even when another lane writes them, as buffer byte stores do. A load reads each byte. Inactive lanes neither store nor load. The first-read analysis counts a d16 load's `vdst` as read, for the half it keeps. `global_load/store_dword_addtid` (lane-id and M0 addressing) raise `Unsupported`; until 2026-11-22 they crashed with `IndexError`, and the ten sub-dword ops raised `Unsupported`. CPU-checked by `tests/semantic/test_global_sub_dword.py` (every byte offset 0 to 7 for each op, an inactive lane, rejected forms, the first-read analysis). **Not GPU-verified.** Hardware-measured natively on `gfx1100`** (RX 7900 XTX, driver 26.10.1) with `tools/hw_oracle`, 16 cases that use the output buffer as scratch memory (seven stores, nine d16 loads), all matching: `b8`/`b16` change only the addressed bytes (`0x11223344` with `0xbeef` stored at offset 2 reads back `0xbeef3344`), `_d16_hi` stores take the data VGPR's high half (`0x12340000` at offset 0 gives `0x11221234`), a 16-bit store at offset 3 splits across the dword exactly (`0xfe223344` then `0x556677ca`), `ubyte`/`sbyte` d16 loads fill the low 16 bits of `vdst` and keep the other half (`0x85` gives `0xbeefff85` from a `0xbeef0000` vdst, `0x7f` gives `0xbeef007f`), `short`/`short_hi` d16 loads fill the low/high 16 and keep the rest, and both dword-crossing loads at offset 3 are exact (`0xbeef8811`, `0x88110000`). Not measured: an inactive lane. **Not GPU-verified.** | -| Literal samplers | Some shaders build their S# from immediates (for example `0x92, 0xC00000, 0x14500000, 0`). The runtime registers those in the descriptor hash table too, by scanning the translated shaders' constant S# values, not only S#s the game binds. The translator lists them per shader (`literal_samplers` in the index). `CreateGraphicsPipelineState` and `CreateComputePipelineState` register each stage's list in the descriptor hash table, since no heap slot names these S#s. Until 2026-11-22 nothing called `register_samplers` (#1169) outside its test, so such a shader's lookup found the fallback sampler and sampled with the wrong filter. The game's `$PS_PassthroughCopy` drew a coordinate ramp point-sampled: worst error 0.0078, against 0.00049 once registered. Checked by `d3d12_m2_textured_test` (`ps_m2_literal.asm`: no key before the PSO, a sampler index after it). | -| Scalar/buffer memory | `s_load*`, `s_buffer_load*`, `buffer_load*` and `buffer_store*` use buffer device addresses (`PhysicalStorageBuffer64`). LLVM `VCCTuple` scalar register lists ending in `vcc_lo,vcc_hi` (e.g. `[s100,s101,s102,s103,s104,s105,vcc_lo,vcc_hi]`, `[s92,...,s105,vcc_lo,vcc_hi]`, seen in 6 FidelityFX FSPX shaders) are parsed as `slist` operands in `tools/shader_ir.py`, clear `vcc` from the lane-mask state in `tools/lane_masks.py`, and route `sN` slots to `%sgpr` and `vcc_lo`/`vcc_hi` to `%vcc`/`%vcc_hi` across SMEM loads, T#/S#/V# descriptor reads, and `global_*` `saddr`. `src_scc` reads `%scc` (0 or 1, RDNA2 inline constant 253), matching `scc`. `image_atomic_*` and `image_atomic_cmpswap` accept `a16` packed 16-bit unsigned coordinates (low half first, matching `image_store`). CPU-checked by `tests/semantic/test_fspx_rules.py` and validated with `spirv-val` (native and `--wave64-emulate`). **Not GPU-verified.** The base comes from the 64-bit SGPR pointer or the V# (dword0 \ \| dword1[15:0] << 32), and the stride is V# dword1[29:16]. **The runtime must put the game's GPU heap in buffer-device-addressable memory at the same addresses the game writes into descriptors** (or remap them). `s_load*` and `s_buffer_load*` take an immediate or an SGPR offset, or both at once (llvm-mc prints `sOFF offset:IMM`). Rules, measured on AMD Radeon RX 6800 (gfx1030, Windows driver 32.0.21045.29003) by running the instructions as a raw compute kernel, wave32 and wave64 (155 runs, every result either 0 or the stored data, wave32 = wave64 in every dword): **address** = (base & ~3) + (sOFF & ~3) + (IMM & ~3) + 4·i for dword i: base, sOFF and IMM are each truncated to a multiple of 4, then added (`s_buffer_load_dword s9, s[24:27], 0x3` with base & 3 = 1 reads +0, not bytes 4..7; sOFF 3 + IMM 3 reads +0 and sOFF 2 + IMM 6 reads +4, where truncating the sum gives +4 and +8; sOFF 8 + IMM 4 reads +12; the same for `s_load*` with pointer & 3 = 1 or 3). **`s_buffer_load*` bound**: dword i is 0, and memory is not read, when (sOFF & ~3) + (IMM & ~3) + 4·i + 4 > limit, with limit = NUM_RECORDS (V# dword2) bytes when the stride is 0 and NUM_RECORDS × stride bytes when it is not. Per dword (x4 at 0xc with NUM_RECORDS 21: data, data, 0, 0; x8 at 0 with 21: five data, three 0), on the truncated offset (IMM 0x10 with NUM_RECORDS 18: 0; IMM 0x13 with 21: the dword at +0x10; sOFF 0xe + IMM 2 with 16: the dword at +0xc; sOFF 0x10 + IMM 4 with 20: 0), not seeing base & 3 (base & 3 = 3, IMM 0x13, NUM_RECORDS 20: data); with a stride the test is still on bytes (stride 4, NUM_RECORDS 5: IMM 0x10 data, 0x14 0; stride 1, NUM_RECORDS 17: IMM 0x10 is 0, so it is not an index test). IMM is unsigned (0xffffc reads +0xffffc). OOB_SELECT (V# word3[29:28]) 0, 1, 2 and 3 gave the same pattern (7 probes per value). **`s_load*`**: no bound (+0x1ffffc reads the dword there); IMM is sign-extended from 21 bits and added in 64 bits (sOFF 8 + IMM −4 reads +4 where zero-extension reads 4 GiB further; sOFF 0xb + IMM −1 reads +4, so the negative IMM is truncated on its own: −1 → −4). **Negative sums** (SHADER-336), measured on the integrated GPU of a Ryzen 9 9950X3D (gfx1036, RDNA2, Windows driver 32.0.21045.16010) with `tools/smem_neg_probe.py --oracle hw`, wave32 = wave64: `s_load` with IMM −4 or −0x40 and no sOFF, sOFF 4 + IMM −8, sOFF 0xc + IMM −0x20 and the x2 form with sOFF 4 + IMM −0x10 read below the pointer at the 64-bit signed sum, and sOFF 6 + IMM −1 reads +0 (4 + −4, each term truncated on its own). `s_buffer_load` adds sOFF and IMM without wrapping at 32 bits: sOFF 0xfffffffc + IMM 8 and sOFF 0xfffffff0 + IMM 0x20 give 0 (past NUM_RECORDS 0x100), and sOFF 0xfffffffc, 0x80000000 and 0x7ffffffc alone give 0 (the translator has the same rule in both offset forms since #1686). An `s_buffer_load` IMM with bit 20 set (llvm-mc rejects it; −4, −0x10, 0x100000 and 0x100004 were encoded by hand) reads data that is neither 0 nor the buffer's own words, differently in wave32 and wave64: the bound does not hold for that encoding, so no compiler output uses it and the translator does not model it. `SmemHardwareRuleTests` in `tests/semantic/test_scalar_mem_smem.py` runs these rows with sOFF in a register and with sOFF known. **Measured since** on native RDNA2 (gfx1036, the Radeon iGPU of a Ryzen 7 9800X3D, Windows driver 32.0.21042.62) through `tools/hw_oracle`, one raw kernel, wave32 = wave64 in every dword (22 cases): **`x16`** takes the per-dword bound like x8 (`s_buffer_load_dwordx16` at offset 0 with NUM_RECORDS 0x24 gives nine data dwords and seven 0; offset 0x20 with 0x40 gives eight and eight; offset 4 with 0x3d gives fourteen and two; stride 4 with NUM_RECORDS 9 gives nine and seven), and `s_load_dwordx16` reads all sixteen; **NUM_RECORDS ≥ 2^31** is compared unsigned (0x80000000 and 0xffffffff with offset 0x10, and 0x80000000 with an x4 at 0x2f0, all read data); **NUM_RECORDS × stride ≥ 2^32** does not wrap (stride 4 × 0x40000001, stride 0x100 × 0x01000001 and stride 0x40 × 0x04000004 wrap to 4, 0x100 and 0x100 in 32 bits, yet offsets 0x10, 0x200 and 0x2f0 read data), as the translator's 64-bit product assumes; **V# dword1[31:30]** = 1, 2 or 3 changes nothing (a dword at 0x10, an x4 at 0xf8 with NUM_RECORDS 0x100 giving two data and two 0, and the same with stride 8 and NUM_RECORDS 4 at 0x18). Not measured: gfx1013 (PS5) itself. **Bound edges**, measured on the same GPU and driver with `tools/hw_oracle` (wave32 = wave64, every read inside a seeded region): `s_buffer_load_dwordx16` is bounded per dword like x8 (NUM_RECORDS 0x14 gives d0..d4 and 0 for d5..d15; 0x20 with IMM or sOFF 8 gives d0..d5); NUM_RECORDS × stride is not cut to 32 bits (stride 0x1000 × 0x100000 and 0x2000 × 0x80000 = 2^32, stride 8 × 0x20000001 = 2^32 + 8: all four dwords of an x4 at 0 are data; stride 8 × 1 gives two); NUM_RECORDS 0x80000000 and 0xFFFFFFFF are unsigned (an x4 at 0 reads all four). These are the rules the translator already used; `SmemHardwareRuleTests` pins them too (a 32-bit product, a signed NUM_RECORDS or one bound for the whole load each fail a test). Not measured: `x16` (gets the x8 rule), NUM_RECORDS ≥ 2^31 and NUM_RECORDS × stride ≥ 2^32, V# dword1[31:30], and gfx1013 (PS5) itself. `s_load`/`s_buffer_load` with sOFF + IMM < 0 (a negative IMM without sOFF included; the translator uses the 64-bit signed sum, an inference), an `s_buffer_load` IMM with bit 20 set (llvm-mc rejects it) or a negative one (kept as the 32-bit value: for stride 0 that is past any NUM_RECORDS below 4 GiB), `x16` (gets the x8 rule), sOFF ≥ 2^31, NUM_RECORDS ≥ 2^31 and NUM_RECORDS × stride ≥ 2^32, V# dword1[31:30], and gfx1013 (PS5) itself. The translator checks each `s_buffer_load` dword with its own structured `if` and an `OpPhi` with 0, so an out-of-range dword issues no load (when descriptor limit and offset are compile-time constants, in-range dwords fold to straight-line loads and out-of-range dwords emit constant zero without branches); `s_load` stays straight-line. Before this the translator added base + sOFF + IMM unaligned, had no `s_buffer_load` bound and zero-extended a negative `s_load` IMM. Checked by `tests/semantic/test_scalar_mem_smem.py` (`SmemHardwareRuleTests`, the measurement's rows, values and the addresses read; `SmemSoffsetImmTranslatorTests`) and by the GPU tests `runtime/test/shaders/cs_smem_soffset_imm.asm`, `cs_smem_bounds.asm`, `cs_smem_stride_align.asm` and `cs_smem_sload_neg.asm` (never run that one with a translator that zero-extends the immediate: it reads 4 GiB past the heap), all in `check.py` and `scripts/run_gpu_tests.py`, which pass on the RX 6800 (Vulkan, driver 26.11.2). See *Buffer bounds checking* below for the MUBUF `num_records` checks. **A constant SGPR offset** (`s_mov_b32 s12, C`, folded at translate time) is added as the run-time path adds `sOFF`: zero-extended, `& ~3`, after the immediate has been normalised (unsigned for `s_buffer_load`, 21-bit signed for `s_load`), with no 32-bit wrap. Until 2026-11-22 (#1686) the fold added it before the truncation, so `s12 = -4` with `offset:20` read byte 16 instead of being out of range, and an `s_load` `sOFF` of 2^20 or more was sign-extended from 21 bits (found by @Impre-visible; hardware measured by @Pierre-Kookis on gfx1036: 0xFFFFFFFC + 20 reads 0). CPU-checked by `tests/semantic/test_smem_const_offset.py` (each case constant vs run-time offset, and against the measured rule). | -| 2D array resource dimensions | For `image_get_resinfo` on a 2D array, X/Y are the width/height at the requested mip, Z is the view layer count and W is its mip count. The query reads the sampled array at binding 3. A native gfx1036 kernel returned (19,11,5,3), (9,5,5,3) and (4,2,5,3) for the three mips of a synthetic array. On RTX 5080 and Radeon Graphics the translated query matched those tuples and returned (4,2,3,2) at relative mip 1 with a view starting at mip 1 and covering three layers. The registered `ps_array_resinfo` draw checks all 4096 pixels against (8,8,12,1). | -| Images and samplers | `image_sample_l` on 2D arrays used to read its LOD from the array layer; it now reads the LOD after all coordinates. `image_get_lod` and `image_gather4_lz` also work on 2D arrays. With `d16` every sample result is f16, packed two to a VGPR from the low half (the packed D16 of GFX10, as LLVM returns D16 image data); `image_sample_c_lz`/`_c_lz_o` follow it too, and until 2026-11-21 their compare result was written as f32 bits, which read as 0 in the low half. Checked by `tests/test_translate.py` (`test_depth_compare_sample_result_width`) and GPU-checked with `runtime/test/shaders/ps_sample_c_lz.asm` (`vk_texture_test dref`: a D32 texture and a LESS_OR_EQUAL compare sampler) on an NVIDIA GeForce RTX 2060 SUPER (Linux, driver 620.70.06): 4096/4096 pixels exact for f32 and `d16`; with the old translator the `d16` result read 0 in the 2048 pixels whose compare passes. | -| Images and samplers (core) | Bindless. Set 0: binding 0 = 2D sampled images, 1 = samplers, 2 = descriptor hash table (storage buffer), 3 = 2D-array images (**cube textures are bound here as 6-layer 2D-array views**, cube arrays as 6N layers: the shader already selected the face with `v_cube*`), 4 = r32ui storage images, 5 = 1D, 6 = 3D. A cube sample's s and t come in [1, 2] and its third coordinate is 8·slice + face, as the hardware takes them (Mesa `ac_nir_lower_tex_coords.c`, LLPC `ImageBuilder.cpp`); the view is read at (s − 1, t − 1), layer 6·slice + face. GPU-checked with `runtime/test/shaders/ps_cube_sample.asm` (`vk_texture_test cube`). For a native Metal path, `tools/spirv_metal_set0.py` sizes set 0's runtime arrays from `vulkan_bindless.h` and moves each binding to its own argument-buffer ID range (binding b starts at the capacities of bindings 0..b-1 added up), to convert with SPIRV-Cross `--msl-decoration-binding`: SPIRV-Cross 1.4.363.0 otherwise puts every runtime array at one ID and comments all but one out as "Overlapping binding" (SHADER-161). `cs_imgstore` converted this way writes all 3×64 texels correctly in a native Metal dispatch on an Apple A18 Pro. | -| Typed buffer loads | The format is V# word3[18:12] (GFX10_FORMAT, from Mesa's `gfx10-rsrc.json`, saved as `tools\gfx10_formats.json`). Supported: f32 ×1–4, u32 ×1–4, i32 ×1–4 (formats 21/63/73/76), f16 ×1/2/4, unorm8 ×1/2/4, snorm8 ×1/2/4, uint8 ×1/2/4, sint8 ×1/2/4, unorm16 ×1/2/4, snorm16 ×1/2/4, uint16 ×1/2/4, sint16 ×1/2/4, 10-10-10-2 and 2-10-10-10 unorm, and, since 2026-11-22, the other GFX10 buffer codes 1–77 (every USCALED/SSCALED, 10_11_11 and 11_11_10 FLOAT, the 10_10_10_2 and 2_10_10_10 families, 8_8_8_8 and 16_16_16_16 SINT and SCALED; see *Typed buffer formats*). Others (code 0 and 78 up) give 0. The 8- and 16-bit UINT/SINT formats 5, 6, 11, 12, 18, 19, 28, 61 and 70 were missing until 2026-11-22 and read 0: UINT channels zero-extend, SINT channels sign-extend, d16 packs them as 16-bit integers, measured natively on gfx1036 (wave32 and wave64) with `tools/hw_oracle` and checked word for word by `tests/semantic/test_buffer_format_narrow_int.py`; GPU-checked by `runtime/test/shaders/cs_fmt_int_narrow.asm`, whose 136 expected words are the same program run natively on gfx1036 (exact on an RTX 5080 and on the gfx1036 iGPU through Vulkan). Full-width SINT accesses preserve integer bits. D16 SINT loads saturate to signed 16-bit and D16 stores sign-extend, covered by the synthetic `cs_fmt_sint32.asm` readback. DST_SEL swizzle is applied (0→0, 1→1.0f for float/norm or integer 1 for UINT/SINT, 4..7→X..W). Missing channels repeat the format's own (component *c* = *c* mod *n*), measured on an RX 6700 (SHADER-86). UNORM/SNORM give the correctly rounded quotient by (2ⁿ−1), as the hardware does (0 mismatches vs hardware over 395,776 conversions on that GPU). It is built with integer ops (`Gen.norm_bits`): x/(2ⁿ−1) in binary is x's bits repeated, so a 64-bit multiply by the repeat pattern, `FindUMsb` and the round bit give the f32 exactly (the tail never ends, so there are no ties). `OpFDiv` is not enough on the GPU: Vulkan allows it 2.5 ULP, and on an RX 6700 (AMD Windows 26.11.2) and an RTX 5090 it returned the reciprocal-multiply bits (8_UNORM 130/256 exact, #599). Checked against exact values in `tests/semantic/test_norm_decode.py` (every value up to 8 bits, edges and the reciprocal-multiply misses for 10, 15 and 16 bits). 8_SNORM (2), 16_SNORM (8) and 8_8_SNORM (15) were missing until 2026-11-22 and decoded to 0. Format names list the channel widths from the top bit, so `2_10_10_10` (50) is R10G10B10A2 and `10_10_10_2` (44) has a 2-bit x (Mesa `gfx10_format_table.py`, `ac_formats.c`). Until 2026-11-22 the two were swapped, in stores too. Until 2026-11-21 an element that started mid-dword re-read dword 0 for its tail (`need` was `ceil(size/4)` and only the first dword was shifted); loads now take `need = ceil((byte_shift + size) / 4)` dwords and shift the whole window so the packed stream starts at the element (FUZZ-5, leftover from #234). The 10:10:10:2 order is checked by `cs_fmt_1010102` in `tests/semantic/test_value_semantics.py` (the shader decodes the format, so a GPU run can't check it). Mid-dword spanning elements are checked by `tests/semantic/test_buffer_load_format.py` (`CrossingDwordBoundary`); repeat / UNORM / DST_SEL 1 by the SHADER-86 cases in the same file. The `_xy` and `_xyz` forms (buffer and tbuffer) are GPU-checked by `cs_fmt_xy_xyz.asm`, whose words were measured natively on a Radeon 680M (gfx1035, RDNA2): they write only their 2 or 3 VGPRs, and missing channels repeat there too (TEST-185). | -| Descriptor hash table | `uint mask; entries[mask+1] of 10 uints: key[0..7], index, pad`. The key is a T# or a padded S#. FNV-1a over the eight key words selects the first slot. The shared SPIR-V lookup probes up to eight slots and returns index 0 on a miss. The runtime supplies a fallback at index 0 and maps live descriptor keys to bindless indices. Outside the wave64 emulation, the lookup's result goes through `OpGroupNonUniformBroadcastFirst` before it indexes the image or sampler array. The lookup key words come from SGPRs, so every invocation in a subgroup has the same index; the broadcast is an identity on all drivers and marks the value uniform for the compiler. It declares `GroupNonUniform` and `GroupNonUniformBallot`, without a shuffle capability or subgroup-lane input. The shader index records the capabilities; its `features` field lists optional Vulkan device features. Mesa ANV 26.2.7 on an Intel Alder Lake-S UHD (Xe-LP, Linux) segfaults in `vkCreate*Pipelines` on a sampler index taken straight from the probe loop when that sampler serves both a float and an integer image (`cs_sample_lz_int_d16`, `ps_ssharp`); with the broadcast both pass. Checked by the unit test `test_lookup_result_is_broadcast_before_use` in `tests/test_desc_cache.py` (standard library only: no GPU, LLVM or SPIRV-Tools). | -| Run-time format decode cost | A `buffer_load_format_*` whose format comes from the V# is decoded by table, without a branch: one shared function per output component (`%fmt_dec_c0`…`%fmt_dec_c3`) reads the format's kind, channel count and channel widths from the module table `%fmt_desc_tab`, and the kind picks the conversion with `OpSelect`; the exact UNORM/SNORM quotient comes from the shared `%fmt_norm_bits`, whose width's 64-bit repeat constant is read from `%fmt_norm_rep_tab`. A code outside the table gives zeros, a format with fewer channels repeats its own (component *c* = *c* mod *n*), and the element size is selected from the format alone (`%fmt_size_tab`), the per-lane byte offset added once. Until 2026-11-23 the shared function instead held every format's decode and a binary search over the codes (`OpSelectionMerge` with `DontFlatten`): 3,498 instructions and 306 branches in the module of a shader with one dynamic-format load (250,869 bytes). Now the four functions hold 565 instructions and no branch, and that module is 56,763 bytes. The decode functions take the format code and the element's four dwords as a `v4uint`, so their function type has a structure of its own: a type of `uint` × 5 repeats the type of the `x_round` helpers, and SPIR-V forbids two non-aggregate types with the same structure. Over the 1.0.2.1 corpus the 11,400 shaders that use this path all translate and pass \spirv-val\ (the previous translator included), and their modules shrink from 11,163,872,428 to 10,454,474,528 bytes (-6.35%). The 15,103 shaders without a run-time FORMAT come out byte for byte identical (checked on a 297-shader sample, every 51st of them). The values are unchanged: every one of the 128 codes gives the same words as the branch search, checked by `tests/semantic/test_format_decode_table.py` (each code against a reference decoded from the raw bits with exact quotients, plus the branch-free and shared-per-component shape). The old translation was confirmed on an RTX 4090 (621.01) against the decode-everything translation: identical output buffers for all 128 codes in four configurations (four byte alignments, out-of-range records, constant DST_SEL), xyzw and d16_xyzw. The branch-free decode costs more ALU per load than the search (every kind's conversion is computed and one is kept), so it trades run time for module size and compile time. | -| 3D explicit-gradient texture samples | For `image_sample_d` and `image_sample_d_cl` on a 3D view, the first six address VGPRs contain dP/dx.xyz and dP/dy.xyz. XYZ and the optional minimum LOD follow. With `a16`, the six derivative VGPRs still hold f32; the following two words contain packed f16 coordinates and the optional clamp. The hand-written `tests/semantic/fixtures/volume_gradients.asm` checks the source registers of both gradients, coordinates and clamp. LLVM gfx1030 assembles all four forms and their modules validate for Vulkan 1.2. [LLVM GFX10 address sizing](https://reviews.llvm.org/D102231) and [SPIR-V Grad operands](https://registry.khronos.org/SPIR-V/specs/unified1/SPIRV.html#Image_Operands) | -| `image_sample_c_l` | Scalar 2D depth comparison (`dmask:0x1`) takes the f32 reference, XY coordinates and explicit mip in that order. Under A16 the reference stays full-width; XY share a VGPR and LOD uses the next low half. D16 returns the comparison in the low half of the destination. Confirmed against LLVM AMDGPU's `llvm.amdgcn.image.sample[.a16].dim.ll` lowering and synthetic Vulkan 1.2 modules in `test_explicit_mip_depth_compare`. | -| Packed sample addresses | GFX10 `image_sample_d` with `a16` keeps the non-G16 gradients as f32 and packs the following coordinates as f16 pairs, following LLVM's GFX10 operand layout. `test_a16_sample_gradients_use_full_vgprs` checks the emitted gradient operands, and `ps_texture_grad_a16` checks coordinate selection with a single-mip texture on RTX 5080. The same holds for every extra argument before the coordinates (LLVM `getAddrSizeMIMGOp`: one word each, then the gradients, then the packed halves; llvm-mc takes `v[0:2]` for a 2D `image_sample_c_b ... a16`): an `image_sample_b` bias keeps its VGPR with the f16 in the low half, an `image_sample_c_lz` z-compare its f32 VGPR, and `image_sample_d_cl` its four f32 gradients, with the clamp the half right after the coordinates (an f16 pad may follow it). Until 2026-11-21 those were unpacked as pairs too, and the clamp was taken from the last half. GPU-checked on an NVIDIA GeForce RTX 2060 SUPER (Linux, driver 620.70.06) with `ps_texture_bias_a16`, `ps_sample_c_lz_a16` (`vk_texture_test dref_a16`) and `ps_texture_grad_cl_a16`, which draws on the `--two-mip` texture with the clamp 0 on the left half and 1 on the right: 4096/4096 pixels exact each. The old reading got 4,032 bias pixels and both depth-compare results in 2,048 pixels wrong, a clamp taken from the pad read mip 1 on the left half, and the sample without its clamp mip 0 on the right half (2,048 pixels each). | -| Depth-compare samples with implicit LOD (`image_sample_c`, `image_sample_c_b`, and the `_o` forms) | In a pixel shader `image_sample_c` is `OpImageSampleDrefImplicitLod` and `image_sample_c_b` adds `Bias` (the LOD comes from the quad derivatives; the sampler is the comparison sampler `image_sample_c_lz` already uses, and the result is one value, f32 bits or with `d16` an f16 in the low half). The address order after the optional texel-offset dword is **bias, z-compare, coordinates** (GFX10 MIMG: offset, bias, zcompare, derivatives, coordinates, LOD, clamp): `image_sample_c_b` read the compare first until this change, the one place that order was wrong, which `ps_sample_c_b` catches (a bias of 1.0 read as the reference compares false everywhere). Outside the pixel stage there are no derivatives: `image_sample_c` samples LOD 0 (like `image_sample`), `image_sample_c_b` is `Unsupported`. `_o` takes the offset as the other `_o` forms do (`Offset`, or with `--texel-offset-fallback` the coordinate shift and a `Grad` sample of the unshifted coordinate's derivatives, scaled by `2^bias` for `_c_b`). Refused still: `_cl`, `_c_d`, `_c_cd` and the gradient forms of the compare samples; `image_sample_c_l` is #2685. GPU tests: `ps_sample_c`, `ps_sample_c_b` (`vk_texture_test dref_c`, `dref_c_b`: the D32 8x8 depth texture of `ps_sample_c_lz`, all 4096 pixels exact for the f32 result and the d16 one); semantic: `tests/semantic/test_sample_c.py` and the forms in `tests/test_texel_offsets.py`. `vk_texture_test` now takes the GPU `LEONIDA_VK_DEVICE` names, as the other harnesses do (it ignored it before). | -| Min-LOD clamp forms (`image_sample_cl`, `_b_cl`, `_c_cl`, `_c_b_cl`, and the `_o` forms) | The clamp is the component after the coordinates (address order: offset, bias, z-compare, coordinates, clamp), and becomes the `MinLod` image operand of the implicit-LOD sample (`OpImageSampleImplicitLod` / `OpImageSampleDrefImplicitLod`, with `Bias` and `Offset` before it in mask order), the same as the `image_sample_d_cl` that already existed; the module declares `MinLod` (`shaderResourceMinLod`, the harnesses skip a device without it). Outside the pixel stage there are no derivatives and the LOD is 0, so the clamp raises it: explicit `Lod = max(0, clamp)` and no `MinLod`. Under `a16` the clamp is packed with the coordinates (its own f16, with a pad after it in the last VGPR), as for `_d_cl`. With `--texel-offset-fallback` the Grad sample takes `Grad\|MinLod`. A clamp on a form that has no `_cl` instruction (`_l`, `_lz`, `_c_lz`) stays `Unsupported`. GPU tests: `ps_texture_cl` and `ps_texture_b_cl` on `vk_texture_test --two-mip` (coordinates / 4 so the unclamped LOD is -1; clamp 0.0 left of x = 32 reads mip 0 red, 1.0 from there on reads mip 1 cyan; dropping the MinLod operand turns the right half red); semantic: `tests/semantic/test_sample_cl.py` and the `_cl_o` forms in `tests/test_texel_offsets.py`. The compare forms (`_c_cl`, `_c_b_cl`) have no GPU test: the depth fixture has one mip level. Not translated: `_c_d`, `_c_cd`, `_d_cl` with compare, the g16 forms. | -| Flat and scratch store operands | Register analysis reads the full address and data VGPR ranges and defines neither. A store after a block terminator can still appear in the listing scanned for PS live-ins. The CPU branch regression in `tests/semantic/test_store_liveins.py` checks both exported barycentric weights. LLVM gfx1013 confirms operand order. Reachable flat and scratch stores still raise `Unsupported`. | -| Vertex fetch | `s_swappc_b64` at the start of a VS calls a driver-generated fetch program that isn't in the blob. It's replaced by Vulkan vertex inputs: each `ISG1` input-signature element (DXBC container) becomes an input at **location = its D3D input register**, typed by its component type, and is written to **v(4 + 4·register + component)**. That rule was checked over all 788 fetch-calling shaders: in 783 every read-before-write VGPR is predicted by it (715 exact). Reads of components the element doesn't declare (e.g. `.w` of an `xyz` position, 3 VS) are allowed: the fetch returns the format defaults (0, 0, 1), and Vulkan fills a `vec4` input from a narrower format the same way. Inputs are declared as `vec4`. **The runtime must bind vertex buffers by the game's D3D12 input layout, location = input register.** | -| `v_swap_b32` and pixel inputs | The swap reads and writes both VGPRs (AMD RDNA2 ISA, VOP1). A barycentric coordinate in the first operand is therefore a live input, and a coordinate or copy in the second operand is overwritten. When the swap changes an interpolation weight, the other incoming weight is still available to the pair. Checked by `tests/semantic/test_interp_computed_ij.py`: `test_swap_reads_both_incoming_barycentrics`, `test_swap_overwrites_interpolation_weight_in_second_operand` and `test_swapped_copies_swap_the_weights` run synthetic fragment exports through the SPIR-V interpreter. | -| PS system inputs | v0–v1 = barycentrics (consumed by `v_interp`, which becomes attribute inputs). **v2.. = the `SV_Position` components the shader reads, packed in order**. Counted over all 12,101 PS listings of 1.0.2.1 (names starting with `.` included; `rdna2spirv.read_before_write_vgprs`, with `v_interp`'s I/J operands left out as the translator does, against the ISG1 read masks from `input_signature_full`; an earlier sample gave 2,531 of 3,000): in 12,098 the VGPRs they read before writing inside the system-input range (v2 up to the last hardware input) equal exactly the position components their input signature reads, then front face when its read mask is non-zero. The 1,639 PS that declare `SV_IsFrontFace` with read mask 0 never read that slot; the translator still places it, last of the inputs this layout models, so no other modelled input moves. The other 3 read fewer position components than their read mask says. Verified on 2,531 of 3,000 PS: the VGPRs they read before writing equal exactly the position components their input signature reads. Filled from `FragCoord`: xy/z directly, and **w directly too**, because AMD's position-w register holds 1/w (Mesa lowers `load_frag_coord_w_rcp` straight to `frag_pos[3]`, `ac_nir_lower_intrinsics_to_args.c`), the same as Vulkan's `FragCoord.w`. **Front face** follows the used position components when the signature declares `SV_IsFrontFace`, as ±1.0 (Mesa: `load_front_face` = `front_face > 0`). Only enabled inputs are packed, in hardware order (Mesa `radv_shader_args.c`: barycentric pairs, POS_X/Y/Z/W, FRONT_FACE, ANCILLARY, SAMPLE_COVERAGE, POS_FIXED_PT). That explains the earlier "unverified" shaders: of the 345 PS that read front face, 130 read pos.xy + front face and 141 pos.x/y/w + front face. That explains the earlier "unverified" shaders: 102 read pos.xy + front face, and 76 read pos.x/y/w + front face. **Raw barycentric reads** (321 PS, e.g. `v_readfirstlane_b32 s41, v1`): AMD interpolates P = P0 + i(P1 − P0) + j(P2 − P0), so i/j are the weights of vertices 1/2, which is `BaryCoordKHR.y`/`.z` (`VK_KHR_fragment_shader_barycentric`). GPU-checked with `runtime/test/shaders/ps_bary.asm`: raw i/j equal the interpolated weights on every pixel. `ps_persp_bary.asm` (the same code drawn by `vs_persp.asm`, clip w = 1, 2, 4) checks them, and the interpolated attributes, against perspective-correct CPU weights; the affine weights differ by at least 0.006 on every covered pixel (all 1158 judged), so `NoPerspective` interpolation fails it. The pair is perspective-center, the only pair this layout models; that holds for every corpus PS (row "PS interpolation modes"). A PS that reads any other unexplained register inside the system-input range is still rejected (none left in the corpus). Reads past the last hardware input are values undefined on some path, so zero stands in for them. 373 PS have one (and 85 more whose raw listing holds embedded data words). In each of the 373 a branch instruction comes earlier in listing order than the first such read; in 364 the register is written later in listing order, which suggests a loop-carried value (inferred from listing order, not measured on the control flow), in 9 never after the read. All register arrays start at zero, so translated shaders are deterministic. | -| Partial pixel color exports | Each MRT retains channels from earlier exports when the current `exp` disables them. Uncompressed exports enable individual RGBA channels and compressed exports enable the RG and BA pairs. Partial MRT outputs start at zero so a channel the shader never writes keeps its existing translator default. The CPU test in `tests/semantic/test_export_valid_mask.py` checks the eight RGBA words from two interleaved targets in `partial_color_exports.asm`. [AMD RDNA 2 ISA, sections 11.1 and 11.2.1](https://www.amd.com/content/dam/amd/en/documents/radeon-tech-docs/instruction-set-architectures/rdna2-shader-instruction-set-architecture.pdf) | -| Inputs and outputs | VS: **legacy (non-NGG) hardware VS, measured** over all 2,236 (`scripts/vs_input_survey.py`): no `exp prim`, no `s_sendmsg` (so no `GS_ALLOC_REQ`) and no `v_mbcnt` in any of them, and every one exports `pos0` and `param`. The input VGPRs are Mesa's GFX10 legacy-VS layout (`radv_shader_args.c`, `declare_vs_input_vgprs`, not `is_ngg`): `v0` = vertex id, `v1` unused, `v2` = primitive id, `v3` = instance id. On entry no VS reads `v1` or `v2`; 788 start with the fetch call (see *Vertex fetch*) and read the fetched attributes from `v4` up, and of the other 1,448, 1,052 read `v0` only, 386 `v0` and `v3`, and 10 neither (NGG would have put the VS inputs at `v5`/`v8`, after five GS VGPRs). **Both ids are zero-based on the hardware**: `v0` excludes the draw's base vertex and `v3` its first instance (Mesa `ac_nir_lower_intrinsics_to_args.c`: `vertex_id` is `load_vertex_id_zero_base`, `instance_id` is `load_instance_id`; the bases come in the `base_vertex` / `start_instance` SGPRs). Vulkan's `VertexIndex` / `InstanceIndex` include `firstVertex`/`vertexOffset` / `firstInstance`, so the translator seeds `v0 = VertexIndex - BaseVertex` and `v3 = InstanceIndex - BaseInstance` (`DrawParameters`, device feature `shaderDrawParameters`, in every VS's `features`). GPU-checked with `runtime/test/shaders/vs_base_ids.asm` (`VKH_DRAW=16,7`): `0x101` on every pixel, where `VertexIndex`/`InstanceIndex` alone gave `0x7111`. `exp pos0` → `Position`, `exp pos1..pos3` → `ClipDistance` / `CullDistance` (and `Layer`/`ViewportIndex` in VS when `pos1` is the misc vector), `exp paramN` → location N. RDNA2/GFX10 packs clip distances before cull distances contiguously across 4-component `pos` exports (up to 8 floats total), starting at `pos2` when a misc vector (`PointSize`, `EdgeFlag`, `ShadingRate`, `Layer`, `ViewportIndex`; GFX9+ packs `Layer` in `z[10:0]` and `ViewportIndex` in `z[19:16]`) occupies `pos1`, and at `pos1` otherwise (Mesa `src/amd/common/nir/ac_nir_prerast_utils.c`: `ac_nir_export_position`; AMD LLPC `lgc/lowering/LowerInOut.cpp`: `LowerInOut::visitReturnInst`). Slot assignment follows the DXBC `OSG1` signature (`SV_ClipDistance` = 2, `SV_CullDistance` = 3, `SV_RenderTargetArrayIndex` = 4, `SV_ViewportArrayIndex` = 5, `SV_ShadingRate` = 23), ordered by `(semantic_index, register, component)` with clip before cull; when `OSG1` is absent (or declares none of those system values), `pos1..pos3` exports are discarded. PS: `v_interp_*` attribute N → input location N. `exp mrtK` → the location of the K-th declared `SV_Target` (**Pixel colour exports**): colour exports are packed, so a shader that declares `SV_Target0` and `SV_Target2` exports `mrt0` and `mrt1`, and `mrt1` is render target 2. Counted over the 1.0.2.1 corpus (SHADER-210): of 10,500 pixel shaders with `SV_Target` outputs (OSG1 system value 64, register = semantic index in all 29,290), the 221 that declare non-consecutive targets all export `mrt0`..`mrt(k-1)`, never `mrtN` at register N. Without an OSG1 (hand-written listings, `run_gpu_tests.py` fixtures) `mrtK` is location K. An export past the declared targets is `Unsupported`. `tests/semantic/test_sparse_sv_target.py`. `exp mrtN` → location N, `exp mrtz` x → `FragDepth` only when x is on in an uncompressed export; the 16-bit `compr` form holds stencil and sample mask, never Z (Mesa `ac_nir_lower_ps_late.c` `emit_ps_mrtz_export`), and an export without Z must not declare `DepthReplacing`. `exp mrtN` → location N, `exp mrtz` x → `FragDepth`. | -| VS input layout, per PAL hardware stage | `scripts/vs_layout_census.py` joins every tag-0x0D payload's PAL stage record (`tools/pal_stages.py`) with its code markers over all 26,698 payloads of the 26,503 1.0.2.1 containers: the 2,236 stage-4 (VS) payloads are **all** legacy non-NGG — no `exp prim`, no `s_sendmsg`, no `v_mbcnt`, and every one exports `pos0` and `param` — so the Mesa GFX10 legacy-VS layout of *Inputs and outputs* holds for every VS the corpus translates, and `v0` = `VertexIndex` (zero-based, `DrawParameters`) is confirmed rather than NGG. The NGG markers belong to the 9,282 stage-7 payloads (every one has `exp prim`, `s_sendmsg MSG_GS_ALLOC_REQ` and `v_mbcnt`), the 195 stage-3 payloads are the geometry shaders (`s_sendmsg` + `v_mbcnt`, no position export), and the 195 stage-2 payloads are the ES variants of the next row; the PS (12,101) and CS (2,689) payloads carry `v_mbcnt` (332 and 266) and, in ten PS, an `s_sendmsg`, but no `exp prim`. | -| VS as ES (two-payload VS containers) | 195 `$VS_VoxelizeGeneric_*` containers carry **two** tag-0x0D payloads: besides the legacy VS above, a stage-2 (`es`) payload — the vertex shader compiled for the export-shader stage of a legacy geometry-shader pipeline. It has **no `exp`** (the vertex outputs go to LDS with `ds_write*` for the GS to read), takes its lane id from `v_mbcnt`, and on entry its read-before-write VGPRs are `v5`, `v9`, `v10`, `v11`, `v13` and `v14` (never `v0`/`v3`); none of the 195 starts with the fetch call. `fssm_unpack.py` defaults to the **last** payload, so the corpus translates the VS variant; the ES variant is untranslated, and which payload a GS-bound pipeline selects is open (`docs/fssm_crosscheck.md` §6). | -| 16-bit results | From Mesa ACO (`aco_ir.cpp`: `instr_is_16bit`, `can_use_opsel`) for GFX10: **f16 VOP1/VOP2 ops** (`v_add/sub/subrev/mul/max/min_f16`, `v_fmac_f16`, `v_cvt_f16_f32`, f16 unary) and **opsel-capable VOP3 ops** (`v_fma_f16`, `_e64` forms of the 16-bit integer ops) are **partial writes that keep the high half**. The **VOP2 (`_e32`) 16-bit integer ops** (`v_lshrrev_b16`…) define the whole register, so the high half is modelled as zero. An op_sel destination bit writes the high half. The translator used to clear the high half on f16 ops; that's fixed. **op_sel on f16 VOP3 ops** (`v_fma_f16`, `v_med3_f16`, `v_add/sub/subrev/mul/max/min_f16`, f16 unary, `v_fmac_f16`): bit i (i < number of sources) reads the high half of source i, the last bit writes the high half of the destination; neg/abs apply to the selected half. Source: Mesa ACO `can_use_opsel` and the RDNA2 ISA VOP3 `OP_SEL` field. Checked by the structural tests in `tests/test_f16_op_sel.py` (which half is read, where the result goes) and the value tests in `tests/test_f16_op_sel_values.py`. **Hardware-verified** on an AMD RX 6800 (gfx1030), the instructions run as a raw compute kernel in wave32 and in wave64 (IEEE off, DX10 clamp on, denormals kept, round to nearest; the bytes assemble identically for gfx1013 and gfx1030): **`v_med3_f16`** with all 16 `op_sel` patterns, with neg/abs on a selected high half, with `clamp`, and with the destination also a source; the **plain forms** `v_add/sub/mul/max/min_f16` (`_e32`, and `_e64` with neg/abs/`clamp`), `v_fmac_f16` (`_e32`, and `_e64` with neg/abs; the accumulator is the low half of the destination), `v_rndne/floor/ceil/trunc/fract/sqrt/rcp/rsq_f16` (`_e32` and `_e64`) and `v_cvt_f16_f32`: low halves in, low half out, high half of the destination kept. 336 words per wave size (plus `v_rsq_f16_e64` and `v_ceil_f16_e64` in a later run), all as the rule says and as the translator computes. **Vulkan** (AMD Radeon RX 6800, Windows, driver 26.11.2; the nine `ps_f16_*` fixtures also pass on an NVIDIA RTX 4050 Laptop and an AMD Radeon 740M (RADV), both Linux): `ps_f16_med3_opsel`, `ps_f16_med3_mods`, `ps_f16_vop2`, `ps_f16_vop2b`, `ps_f16_vop1`, `ps_f16_vop1b`, whose expected words are the hardware ones (`tests/test_f16_hw_words.py` checks them against the rule and the translator without a GPU). **Not expressible, so not verified:** `op_sel` on the VOP2 and VOP1 ops in VOP3 encoding (`v_add/sub/mul/max/min_f16_e64`, `v_fmac_f16_e64`, the unary `_e64` forms, `v_cvt_f16_f32_e64`): llvm-mc 21 rejects the modifier for gfx1013 and gfx1030, and its disassembler prints bytes that have those bits set without it (`03 08 32 d5 01 05 02 00` comes back as `v_add_f16_e64 v3, v1, v2`). The translator's `op_sel` handling for these forms is therefore never reached from a disassembly listing and rests on the ISA field description alone; whether the hardware honours the bits there is unknown, and a blob that set them would be translated as if they were clear. Also unverified: NaN and denormal operands, other rounding and IEEE modes, outside the f16 transcendentals (measured, see the f16 transcendentals row). **Driver quirk (AMD Windows driver 26.11.1, RX 9070):** `valu_fuzz` f16 seed 3 programme 38 loses the high half of v26: `v_add_f16_e32 v26, v29, v32` then `v_sub_nc_u16_e64 v28, v32, v27 op_sel:[1,1,0]` then `v_add_f16_e64 v26, v26, v28` — the final add should keep `0xCD52` in the high half, but the GPU returns `0xEEEEEEEE` (native) / `0x00000000` (`--emulate`), all 64 threads. Bisected to the pair: the add's two sources must both have been produced by earlier partial writes; either alone, a NaN input alone, or `dst==src0` alone all pass. The emitted SPIR-V was checked with `spirv-dis` in both modes: the keep (load old v26, `AND 0xFFFF0000`, `OR` new low half, store to index 26) is present and correctly addressed, so the translator is clear and this is the driver miscompiling the pattern. Minimal reproducer: the three ops above with programme 38's inits (v26 `0xCD524000`, v28 `0xC692D243`, v29 `0xBC004200`, v32 `0xB35ABD4B`, v27 `0xB48ABA06`). Pinned by `tests/test_values.py` (`v_add_f16_e64_keep_hi`, `v_add_f16_e32_keep_hi`), which check the translator's keep, not the driver. Found and bisected by 1TrickOmen, reported on #634. | -| 16-bit SDWA result with `dst_sel:DWORD` | A 16-bit op in SDWA form (`v_add/sub/subrev/mul/min/max_f16_sdwa`, the f16 unary ops, `v_cvt_u16_f16`, `v_cvt_i16_f16`, `v_cvt_f16_u16`, `v_cvt_f16_i16`) with `dst_sel:DWORD` writes the whole VGPR: the 16-bit result zero-extended, **whatever `dst_unused` says**. The keep-the-high-half rule of the row above is for the non-SDWA forms only; with `dst_sel:WORD_0 dst_unused:UNUSED_PRESERVE` the high half is kept as usual. **Until 2026-11-22 the translator kept the high half for `dst_sel:DWORD`** (`Gen.insn` marked an SDWA destination only for a `dst_sel` other than DWORD). Measured natively on an AMD Radeon iGPU (gfx1036, RDNA2, Windows driver 26.10.1) with `python -I tools/sdwa_diff.py --oracle hw` (#2113) and with the program of `runtime/test/shaders/ps_sdwa_dword_hi.asm` through `tools/hw_oracle`: destinations 0xdeadbeef give 0x00004000 (`v_add_f16`, PRESERVE), 0x00000003 (`v_cvt_u16_f16`, PAD), 0x00004700 (`v_cvt_f16_u16`, PRESERVE), 0x0000c000 (`v_mul_f16`, SEXT); the same ops with `dst_sel:WORD_0 UNUSED_PRESERVE` give 0xdead4000, 0xdead0003, 0xdead4700, 0xdeadc000. GPU-checked through Vulkan with `ps_sdwa_dword_hi.asm` on an RTX 5080 (driver 616.92) and the same Radeon iGPU (4096/4096 pixels each); CPU-checked in `tests/semantic/test_value_semantics.py`. | -| f16 inline constants | An inline float constant (`0.5`, `1.0`, `2.0`, `4.0`, their negatives, `0.15915494`) in an operand of a 16-bit float op is the **f16 value in the low half with a zero high half**, not f32 bits (the translator used to unpack the f32 pattern, whose low half is 0, so `v_add_f16 d, 1.0, v` added 0.0). Measured on an AMD RX 6800 (gfx1030) raw kernel, wave32 and wave64: `v_add/mul/max_f16`, `v_sub_f16_e64`, `v_fma_f16`, `v_fmac_f16`, `v_rcp_f16`, `v_med3_f16`, `v_cmp_lt_f16`, `v_cvt_f32_f16` (`0.5` gives `0x3f000000`), `v_cos_f16`, `v_pk_add_f16`/`v_pk_mul_f16` (the high result half sees 0.0), `v_pack_b32_f16`; `0.15915494` is `0x3118`; the high half `op_sel` selects from a constant reads +0.0 (`v_med3_f16`, `v_fma_f16`, `v_pack_b32_f16`, `v_pk_add_f16` with swapped halves). GPU tests `ps_f16_const`, `ps_f16_const2` and `ps_f16_pack` (Vulkan: AMD Radeon RX 6800, Windows, driver 26.11.2; all three fail without the fix). Constants in `v_fma_mix_f32`/`v_fma_mixlo/mixhi_f16` operands follow the same rule per operand (measured on an RDNA2 iGPU, gfx1036, SHADER-135): f32 bits where `op_sel_hi` makes the operand f32, the f16 constant with a zero high half where it makes it f16, so `op_sel` with `op_sel_hi` reads +0.0; an integer constant is its 32-bit integer. The translator gives the same words for the float constants in every `op_sel`/`op_sel_hi` combination and for the integer constants as f16 halves, but not for `1` and `64` as f32 operands: their bits are f32 denormals, which gfx1036 flushes to a zero of their sign (`denorm_mode_32 = 0`, the MODE the translator assumes for the game) and the translator keeps (difference 4 in docs/shader_validation.md, "f16 output modifiers, clamp and `v_fma_mix*` operands on RDNA2"). | -| `v_fmamk_f16`, `v_fmaak_f16` | VOP2 with a literal K: `fmamk` computes `D = S0 * K + S1` (printed `vdst, src0, K, vsrc1`), `fmaak` computes `D = S0 * S1 + K` (printed `vdst, src0, vsrc1, K`). In print order both are `a[1] * a[2] + a[3]`, as for `v_fmamk/fmaak_f32`. K is the f16 in the literal's low 16 bits; a float literal is converted to f16 (`src_h`). One rounding to f16, as `v_fmac_f16` (SHADER-55). The GFX10 f16 VOP2 write puts the result in the low half and keeps the high half. Until 2026-11-22 both raised `Unsupported`. CPU-checked by `tests/semantic/test_valu_fmamk_fmaak_f16.py`, against `v_fma_f16` with K in a VGPR (value grids, a float literal, the operand order, seeded values). **Hardware-measured natively on `gfx1100`** (RX 7900 XTX, driver 26.10.1) with `tools/hw_oracle`, 17 cases: the print order, the one-rounding rule and the kept high half hold (`1*2+3`, `1.5*2+0.5`, both orders, `(1+2^-10)*3` rounding the exact 3.0029296875 to the tie's even `0x4202`, `65504*2` overflowing to `+inf`); f16 VALU keeps denormals, unlike the LDS float adder, so `0x0001*1+0x0001` gives `0x0002`; an sNaN is quieted with its payload kept (`0x7c01` gives `0x7e01`) and `inf + -inf` gives the negative default `0xfe00`. **Not GPU-verified.** | -| SDWA select on an f16 inline constant | In an `_sdwa` 16-bit float op, an inline float constant is first the f16 value over a zero high half (row above) and `src0_sel`/`src1_sel` then narrows those 32 bits like a register's, zero-extended, before neg/abs and the op: `1.0` under `WORD_1` reads +0.0, `2.0` under `BYTE_1` reads the f16 denormal `0x0040`. An SGPR source, and an integer op reading the f32 bits of a float constant (`v_cvt_f16_u16_sdwa d, 1.0 src0_sel:WORD_1` converts 0x3f80), are narrowed the same way. **Until 2026-11-22 the translator used the whole f16 constant** (`v_add_f16_sdwa d, 1.0, v src0_sel:WORD_1` with v = 0.5 gave 1.5). Measured on an AMD Radeon iGPU (gfx1036, Ryzen 9 9950X3D, driver 26.10.1) with `tools/hw_oracle` (raw HIP kernel, wave32): the four words of `runtime/test/shaders/ps_sdwa_f16_const.asm`; found with `python -I tools/sdwa_diff.py --oracle hw` (#2113). GPU test `ps_sdwa_f16_const`, 4096/4096 pixels on an NVIDIA GeForce RTX 5080 (driver 616.92) and the same Radeon iGPU through Vulkan; both fail without the fix. Also executed by `tests/semantic/test_value_semantics.py`. | -| `v_pack_b32_f16` input `neg` | A VOP3 `neg` on an operand of this instruction flips the sign bit of **the 16-bit half that operand contributes**, not of the whole 32-bit source, and only that half: measured on gfx1036 (RDNA2 iGPU, AMD Windows driver 32.0.21044.64) with 192 raw kernels, `0x7c01` gives `0xfc01` under IEEE mode 0 and `0xfe01` under mode 1, in either half and with `op_sel`. The translator moved the bits unchanged and refused every modifier; it now XORs `0x8000` into the selected half. `abs` is implemented too: it clears bit 15 of the selected half before `neg` is applied, and the rule is measured on gfx1036 (1,088 raw kernels across wave32 and wave64, 0 mismatches; SHADER-260). The mode-1 quieting of a signalling-NaN half is not modelled while SHADER-190 is open; under mode 0, where the bits move unchanged, the translation is exact. Checked on the CPU by `tests/test_values.py` and `tests/semantic/test_vop3_const_mods.py`; the gfx1036 measurement above is @Sanonymous01's, not repeated here. | -| Packed 16-bit integer ops (`v_pk_add/sub_u16/i16`, `v_pk_mul_lo_u16`, `v_pk_mad_u16/i16`, `v_pk_max/min_u16/i16`) | VOP3P: result half 0 takes each source's half from `op_sel[i]`, result half 1 from `op_sel_hi[i]` (defaults `[0,..]` and `[1,..]`), as for `v_pk_lshlrev_b16`. Each half is computed on its own and wraps to 16 bits. `clamp` (add, sub, mad) saturates the half to its type's range (the exact value fits in 32 bits), whereas on `v_pk_mul_lo_u16` and `v_pk_max/min_u16/i16` VOP3P `clamp` is a hardware no-op (`v_pk_mul_lo_u16 clamp` wraps modulo 2^16 rather than saturating to `0xFFFF`, and `max`/`min` results are unchanged; until 2026-11-23 `clamp` on those five ops raised `Unsupported`). `neg_lo`/`neg_hi` are float-only and unsupported modifiers (such as `mul:*`/`div:*`) raise `Unsupported`. `clamp` (add, sub, mad) saturates the half to its type's range; the exact value fits in 32 bits. `neg_lo`/`neg_hi` are float-only and raise `Unsupported`, as does `clamp` on the other ops. A constant operand is treated as a 32-bit dword `C`: `op_sel[i] == 0` selects bits `[15:0]`, `op_sel[i] == 1` selects bits `[31:16]`. Positive inline constants zero-extend (`5` → `0x00000005`), negative inline constants sign-extend (`-1` → `0xFFFFFFFF`, `-16` → `0xFFFFFFF0`), and 32-bit literals retain their full dword (`0x12345678`). Lowered via `OpBitField*Extract` at `16 * sl[i]` (the packed 16-bit *shifts* read their halves with a shift and a mask instead, like every other high-half reader: see the 16-bit high-half reads row). Lowered via `OpBitField*Extract` at `16 * sl[i]`. Until 2026-11-22 reading the high half of a constant raised `Unsupported`. A constant operand reads as its low 16 bits. Its high half under `op_sel`/`op_sel_hi` is **not measured** for integer ops (for f16 constants it reads +0.0, see the row above), so a constant whose high half would be read raises `Unsupported` instead of guessing; the compiler's usual form, `op_sel_hi:[1,0]` with the constant second, reads only the low half. Until 2026-11-22 all eleven ops raised `Unsupported`. CPU-checked by `tests/semantic/test_alu_pk_int16.py` (value grids, seeded `mad`, `op_sel`/`op_sel_hi` combinations, `clamp` including the unsigned `sub` floor, inline and literal constants, rejected forms) and `tests/semantic/test_pk_int16_clamp.py` (all 26 probe cases plain vs `clamp`, SPIR-V non-saturation assertion, inactive `EXEC` preservation, `spirv-val` Vulkan 1.2 validation, rejected modifiers), plus `tests/test_pk_int16_clamp_probe.py`. **Hardware-verified on RDNA2** (`gfx1035`, Windows 11, driver `26.5.1`, wave32 & wave64 via `tools/int_hw_probe.py --oracle both --group valu_pk_int16`, and independently on `gfx1036` desktop APU, Windows 11, driver `32.0.21045.29003`, across 380 raw compute kernels covering all 11 ops, constants under `op_sel`/`op_sel_hi`, `clamp`, and wave32/wave64 parity with 0 wave diffs and 0 mismatches, and via `tools/pk_int16_clamp_probe.py --hw-arch gfx1036` across 624 wave32 & wave64 evaluations with `mismatches=0, wave_diffs=0, target_clamp_diffs=0, control_clamp_diffs=34`, plus a 96-word wave32 Vulkan compute check under `VK_LAYER_KHRONOS_validation` passing with 0 mismatches on `AMD Radeon RX 9070 XT` driver `26.11.2` and `AMD Radeon(TM) Graphics` driver `26.11.2`): all eleven ops (wrap, `clamp` saturation on add/sub/mad, `clamp` no-op on `mul_lo`/`max`/`min`, and constant `op_sel`/`op_sel_hi`) match bit-for-bit. CPU-checked by `tests/semantic/test_alu_pk_int16.py` (value grids, seeded `mad`, `op_sel`/`op_sel_hi` combinations, `clamp` including the unsigned `sub` floor, inline and literal constants, rejected forms). **Hardware-verified on RDNA2** (`gfx1035`, Windows 11, driver `26.5.1`, wave32 & wave64 via `tools/int_hw_probe.py --oracle both --group valu_pk_int16`, and independently on `gfx1036` desktop APU, Windows 11, driver `32.0.21045.29003`, across 380 raw compute kernels covering all 11 ops, constants under `op_sel`/`op_sel_hi`, `clamp`, and wave32/wave64 parity with 0 wave diffs and 0 mismatches): all eleven ops (wrap, `clamp` saturation on add/sub/mad, and constant `op_sel`/`op_sel_hi`) match bit-for-bit. **Not GPU-verified.** **Hardware-verified on RDNA2** (`gfx1035`, Windows 11, driver `26.5.1`, wave32 & wave64 via `tools/int_hw_probe.py --oracle both --group valu_pk_int16`): all eleven ops (wrap, `clamp` saturation on add/sub/mad, and `op_sel`/`op_sel_hi`) match bit-for-bit. **`v_pk_mul_lo_u16` low 16 bits (found with `pk16_diff --oracle hw,vk`, GPU test `cs_pk_mul_lo_const`):** each half is `((x << 16) * y) >> 16`, not `(x * y) & 0xffff`: with a constant half of 0 in the other half of the result the AMD Windows driver (Radeon iGPU gfx1036, 26.10.1) dropped the mask (`0x1234 * 0xaaaa` gave `0x0c229e88`, hardware `0x00009e88`); the RTX 5080 was right either way. Words measured on the same gfx1036 in `runtime/test/shaders/cs_pk_mul_lo_const.asm`. | -| `v_sin_f32`, `v_cos_f32`, `v_sin_f16`, `v_cos_f16` | The operand is an angle in turns (the ISA says valid over +-256; the measurement below finds no such limit on gfx1030). `turn_angle` reduces it in turns first, `x - RoundEven(x)` (exact in binary32, in [-0.5, 0.5]), then scales by `2*pi` and calls `Sin`/`Cos`, so the angle stays in [-pi, pi], the only range where GLSL guarantees them (2^-11 absolute). Scaling first rounded the fractional turn away (about 1.2e-4 rad near 255 turns, #594); the first fix (#1283) reduced with `Fract`, which rounds `1 - \| x \| ` for a negative x and lost `-2^-26` (it returned +0; absolute errors up to ~1.7e-7 at -0.1 turns), so the reduction is `RoundEven`-centred. `RoundEven` rather than `Round` so +-0.5 turn reduce symmetrically. inf and NaN still give NaN, and a zero operand is passed through unreduced so `sin(-0)` stays -0. CPU-checked by `tests/semantic/test_alu_sincos.py` against `sin`/`cos(2*pi*x)` in double (large angles, tiny arguments, whole turns of either sign, +-0, inf/NaN, modifiers, f16) and `tests/semantic/test_valu_sin_cos_turns.py` (#1283). GPU test `cs_w32_sincos` (large angles within 1e-3, since the driver `Sin` is only good to 2^-11) is a regression guard, not proof the old form failed on a given driver. Measured on an AMD Radeon RX 6800 (gfx1030, not the console's gfx1013) by @shelbykb2 (#616): whole and half turns of either sign give +0 (only `sin(-0)` is -0, so no sign needs copying onto a zero result, as here); there is no +-256 limit on that card (any finite x reduces exactly: `sin(300.25)` = 1, `sin(2^24)` = +0); the f16 forms reduce the same way as the f32 ones; +-inf gives a NaN and a NaN passes through, quieted with IEEE mode on. Re-measured natively on gfx1036 (RDNA2, SHADER-134) for f32 and f16 over every quarter turn from 0.25 to 2^24 of either sign and around +-256: the same rules. At an odd half turn `sin`, and at an odd quarter turn `cos`, is exactly +0 (either sign of x), where `Sin`/`Cos` of the rounded 2*pi give about -+8.7e-8 (f32) or a +-1-ulp f16 denormal; since 2026-11-22 the translator selects +0 there (`Gen.trig_exact_zero`), checked against 500 measured words by `tests/semantic/test_alu_sincos_turns_hw.py`. Known differences from this translation: for Known differences from this translation: at half turns `Sin` of the rounded pi gives about -+8.7e-8 where the hardware returns exactly 0, likewise `cos` at quarter turns; for \| x \| <= 2^-12 the hardware multiplies by `0x40c90fd5`, not the rounded 2*pi; the inf/NaN words are whatever the host driver returns. Not checked on gfx1013. | -| `v_pack_b32_f16` source modifiers | A VOP3 `abs` or `neg` on an operand of this instruction acts on **the 16-bit half that operand contributes**, not on the whole 32-bit source, and only on that half: `abs` clears bit 15 and `neg` flips it, `abs` first, both as plain bit moves — the operand is not converted to a float. Until 2026-11-22 any such operand was rejected as `Unsupported`. **`neg` is measured** on gfx1036 (RDNA2 iGPU, AMD Windows driver 32.0.21044.64) with 192 raw kernels: `0x7c01` gives `0xfc01` under IEEE mode 0 and `0xfe01` under mode 1, in either half and with `op_sel`, so the sign move does not depend on the mode. **`neg`, `abs`, and `neg_abs` are hardware-verified on RDNA2** across both `gfx1035` (Windows 11, driver 26.5.1, wave32 & wave64 via `tools/int_hw_probe.py --oracle both --group valu_pack_b32_f16_abs` and raw `ieee=0` kernels) and `gfx1036` (Windows 11, driver 32.0.21045.29003, 1,088 raw kernels across wave32 and wave64, 0 mismatches): **`abs` and `- **`neg`, `abs`, and `- **`abs` rests on the ISA's definition of ABS on a float operand as the sign clear, applied before `neg`; no hardware run of this instruction with `abs` exists yet**, and `abs` on a NaN half is therefore unmeasured too. **Not modelled: IEEE mode 1 also quiets a signalling-NaN half** (`0x7c01` → `0x7e01`); which mode the game's shaders run in is SHADER-190, and under mode 0, where the bits move unchanged, the translation is exact. Checked by `tests/test_values.py`, `tests/semantic/test_vop3_const_mods.py`, `tests/semantic/test_pack_b32_f16_mods.py` (exact bits through the interpreter) and the GPU fixture `ps_f16_pack_mods` (words derived from the rule, not a readback); the gfx1036 measurement above is @Sanonymous01's, not repeated here. \| x src \| ` are hardware-verified on RDNA2** across both `gfx1035` (Windows 11, driver 26.5.1, wave32 & wave64 via `tools/int_hw_probe.py --oracle both --group valu_pack_b32_f16_abs` and raw `ieee=0` kernels) and `gfx1036` (Windows 11, driver 32.0.21045.29003, 1,088 raw kernels across wave32 and wave64): ` (neg+abs) are measured** on gfx1036 (RDNA2 iGPU, AMD Windows driver 32.0.21045.29003) with 1,088 raw kernels across wave32 and wave64 (0 mismatches): `abs` clears bit 15 (`& 0x7FFF`), `neg` flips it (`^ 0x8000`), and `neg_abs` sets bit 15 across all normal numbers, zeros, infinities, subnormals, quiet NaNs, and signaling NaNs, in either half and with `op_sel`. Under IEEE mode 0, signaling NaN payloads are preserved untouched (`0x7c01` gives `0xfc01` under `neg` and `0x7c01` under `abs`); under IEEE mode 1, a signaling-NaN half is quieted (bit 9 set: `0x7c01` gives `0xfe01` under `neg` and `0x7e01` under `abs`). ` are hardware-verified on RDNA2** (`gfx1035`, Windows 11, driver `26.5.1`, wave32 & wave64 via `tools/int_hw_probe.py --oracle both --group valu_pack_b32_f16_abs` and raw `ieee=0` kernels): On `gfx1035`, `abs` clears bit 15 and applies before `neg` on `-1.0`, `-0.0`, `-qNaN` (`0xfe05` → `0x7e05`), and `-sNaN` (`0xfc01` → `0x7c01` under `ieee=0`), with and without `op_sel`. **Not modelled: IEEE mode 1 also quiets a signalling-NaN half** (`0x7c01` → `0x7e01`); which mode the game's shaders run in is SHADER-190, and under mode 0, where the bits move unchanged, the translation is exact. Checked by `tests/test_values.py`, `tests/semantic/test_vop3_const_mods.py`, `tests/semantic/test_pack_b32_f16_mods.py` (exact bits through the interpreter) and the GPU fixture `ps_f16_pack_mods` (words derived from the rule, not a readback); the gfx1036 measurement above is @Sanonymous01's, not repeated here. | -| Packed integer dot products (`v_dot2_i32_i16`, `v_dot2_u32_u16`, `v_dot4_u32_u8`, `v_dot8_i32_i4`, `v_dot8_u32_u4`, plus VOP2 accumulating `v_dot2c_i32_i16`, `v_dot2c_u32_u16`, `v_dot4c_u32_u8`, `v_dot8c_i32_i4`, `v_dot8c_u32_u4`), `v_dot2_f32_f16` / `v_dot2c_f32_f16`, and `v_pk_fmac_f16` | RDNA2 ISA: `v_dot2_i32_i16`/`u16` (2×16-bit), `v_dot4_u32_u8` (4×8-bit unsigned), and `v_dot8_i32_i4`/`u4` (8×4-bit) — and their VOP2 accumulating `v_dot*c_*` forms (reading old `vdst` as `acc`) — extract each element with `OpBitFieldSExtract`/`OpBitFieldUExtract`, sum the elementwise products with `S2` (or old `vdst`) wrapping at 32 bits, and saturate to `[INT32_MIN, INT32_MAX]` / `[0, UINT32_MAX]` under `clamp` (signed carry tracking handles the `v_dot2_i32_i16` `(-32768)^2 + (-32768)^2 + acc` overflow/cancellation edge). For VOP3P `v_dot*_*`, the hardware default `op_sel:[0,0,0]` and `op_sel_hi:[1,1,1]` is accepted and any other `op_sel`/`op_sel_hi`, `neg_lo`/`neg_hi`, DPP/SDWA, or source `neg`/`abs` raises `Unsupported`; for VOP2 `v_dot*c_*`, only optional `clamp` and VGPR `vdst` are accepted. `v_dot2_f32_f16` (VOP3P) and `v_dot2c_f32_f16` (VOP2) compute `a0*b0 + a1*b1 + acc` in f32 (`f16_in` per half, `flush_f32` on `acc`, optional `clamp`, and for `v_dot2_f32_f16` `op_sel`/`op_sel_hi`/`neg_lo`/`neg_hi` on the inputs and `neg_lo[2]` on `acc`). All 6 new `v_dot*c_*` ops mark `vdst` as read-before-write in `read_before_write_vgprs` and `reg_reads_writes`. (`v_dot4_i32_i8` and `v_dot4c_i32_i8` are covered separately in the Signed-byte dot products row, #1754.) `v_pk_fmac_f16` (VOP2) unpacks `src0`, `vsrc1` and `vdst` as `f16x2` (`Gen.src_h`, so inline float constants apply in the low half with `+0.0` high), computes `fma(src0[k], vsrc1[k], vdst[k])` per half with single f16 rounding (`Gen.fma_f16_odd`, SHADER-55), and packs with `Gen.f16_pack2`; any modifier outside `_dpp` or non-VGPR `vdst` raises `Unsupported`, and `v_pk_fmac_f16` marks `vdst` as read before write in `read_before_write_vgprs` and `reg_reads_writes`. **Hardware-confirmed on RDNA2** for the 5 VOP3P integer forms and `v_pk_fmac_f16`: on `gfx1036` (Ryzen 9 7950X3D iGPU, `tools/hw_oracle`, @aslan2142), all 60 integer dot-product sets and all 22 `v_pk_fmac_f16` default-MODE words match; independently confirmed on `gfx1035` (Radeon 680M, @Youssefrah16) across 18 cases × wave32/wave64 (36/36 bit-exact), pinned by `tests/semantic/test_alu_dot_pk_fmac.py`. The 5 VOP2 `v_dot*c_*` integer forms and `v_dot2_f32_f16` / `v_dot2c_f32_f16` are CPU-checked by `tests/semantic/test_alu_dot_complete.py` and not yet hardware-measured on RDNA2. Non-default f16 MODEs (denormal flush, RTZ) are not modelled on `v_pk_fmac_f16` while the translator has no MODE input. | -| Packed integer dot products (`v_dot2_i32_i16`, `v_dot2_u32_u16`, `v_dot4_u32_u8`, `v_dot8_i32_i4`, `v_dot8_u32_u4`) and `v_pk_fmac_f16` | RDNA2 ISA: `v_dot2_i32_i16`/`u16` (2×16-bit), `v_dot4_u32_u8` (4×8-bit unsigned), and `v_dot8_i32_i4`/`u4` (8×4-bit) extract each element with `OpBitFieldSExtract`/`OpBitFieldUExtract`, sum the elementwise products with `S2` wrapping at 32 bits, and saturate to `[INT32_MIN, INT32_MAX]` / `[0, UINT32_MAX]` under VOP3P `clamp` (signed carry tracking handles the `v_dot2_i32_i16` `(-32768)^2 + (-32768)^2 + S2` overflow/cancellation edge). The hardware default `op_sel:[0,0,0]` and `op_sel_hi:[1,1,1]` (whether omitted or written explicitly) is accepted; any other `op_sel`/`op_sel_hi` (such as `op_sel_hi:[0,0,0]` or `[0,1,1]`, which select the low half for lane 1 on `v_dot2_*`), `neg_lo`/`neg_hi`, DPP/SDWA forms, and source `neg`/`abs` raise `Unsupported`. (`v_dot4_i32_i8` and `v_dot4c_i32_i8` are covered separately in the Signed-byte dot products row, #1754.) `v_pk_fmac_f16` (VOP2) unpacks `src0`, `vsrc1` and `vdst` as `f16x2` (`Gen.src_h`, so inline float constants apply in the low half with `+0.0` high), computes `fma(src0[k], vsrc1[k], vdst[k])` per half with single f16 rounding (`Gen.fma_f16_odd`, SHADER-55), and packs with `Gen.f16_pack2`; any modifier outside `_dpp` or non-VGPR `vdst` raises `Unsupported`, and `v_pk_fmac_f16` marks `vdst` as read before write in `read_before_write_vgprs` and `reg_reads_writes`. Until 2026-11-22 all six ops raised `Unsupported`. **Hardware-confirmed on RDNA2:** on `gfx1036` (Ryzen 9 7950X3D iGPU, `tools/hw_oracle`, @aslan2142), all 60 integer dot-product sets (plain, swapped/SGPR sources, and `clamp`) match bit-for-bit, all measured `op_sel`/`neg_*` variants are refused, and all 22 `v_pk_fmac_f16` default-MODE (`0x000003C0`: round-to-nearest-even, f16 denormals kept, IEEE and DX10_CLAMP on) words match in both source orders (all 34 non-NaN halves bit-exact; the 10 NaN halves yield quiet f16 NaN, as SPIR-V does not preserve NaN payload bits or sign); independently confirmed on `gfx1035` (Radeon 680M, `tools/hw_oracle`, @Youssefrah16) across 18 cases × wave32/wave64 (36/36 bit-exact). Pinned by `tests/semantic/test_alu_dot_pk_fmac.py` (all 82 `gfx1036` measured tables plus hand-written `.asm` fixture, boundary/clamp cases, default/non-default `op_sel`/`op_sel_hi`, `read_before_write_vgprs`/`reg_reads_writes`, DPP, seeded sweeps, and rejected forms). Non-default f16 MODEs (denormal flush, RTZ) are not modelled on `v_pk_fmac_f16` while the translator has no MODE input. | -| `v_med3_f32` output modifiers | The translator applies `mul:2`, `mul:4` or `div:2` to the median before clamping to [0, 1], following [LLVM’s modifier order](https://llvm.org/docs/AMDGPUModifierSyntax.html#omod). The finite-input fixture `ps_med3_mods.asm` produced 4,096 exact pixels on an Apple M3 Max with MoltenVK and on Mesa llvmpipe (software Vulkan); it also passes (4,096/4,096) on an NVIDIA RTX 4050 Laptop and an AMD Radeon 740M (RADV), both Linux, and on an RTX 2060 SUPER per #634. This uses the existing float MODE assumptions described above. | -| `v_div_fmas_f32`, `v_div_fmas_f64` | Scaled FMA for IEEE-754 division (VOP3): `D = fma(S0, S1, S2)` when `VCC[lane] == 0`; when `VCC[lane] == 1`, `D = (exp(S2) > bias ? 2^+S : 2^-S) * fma_exact(S0, S1, S2)` where `(bias, S)` is `(127, 64)` for f32 and `(1023, 128)` for f64 (`OpCapability Float64`, no `Int64`), i.e. `\|S2\| >= 2.0` scales up and `\|S2\| < 2.0` scales down. Scale-up uses `fma(S0, S1, S2) * 2^S` (any non-zero cancellation residual against `\|S2\| >= 2.0` stays well above normal minimum). Scale-down pre-scales `S0`/`S1` only when `\|S0*S1\|` can overflow (`\|S0\| >= 2^S` and `\|S1\| >= 1`, symmetric, or both `>= 2^(S/2)`), with a raw-bit sticky value `copysign(min_normal, S2)` whenever `0 < \|S2\| < 2^(Emin + S)` so half-ULP tie-breaking stays exact; otherwise it post-scales `fma(S0, S1, S2) * 2^-S`, with a TwoSum + product-error half-ULP tie adjustment in f64 when `\|fma\|` falls in `[2^-947, 2^-894)` so f64 subnormal outputs single-round. For f32 under the game MODE (`denorm32=0`), subnormal inputs and intermediate products are kept while subnormal outputs flush to signed zero before (and after) output modifiers; for f64 (`denorm16_64=3`), subnormals are kept throughout. VOP3 input (`abs`/`neg`) and output (`mul:2`/`mul:4`/`div:2`, then `clamp`) modifiers apply via `clamp_mods` / `clamp_mods_f64`. **Until 2026-11-22 the translator scaled unconditionally by `2^32` (f32) / `2^64` (f64) whenever `VCC[lane] == 1`, omitting the `exp(S2) > bias` branch and using half the hardware exponent shift.** **Hardware-verified on RDNA2** (`gfx1036`, AMD Radeon Graphics, Windows driver 32.0.21042.62, `tools/hw_oracle`, wave32 and wave64, game MODE `ieee=0`/`dx10_clamp=1`/`denorm32=0`/`denorm16_64=3`): 150/150 f32 and 153/153 f64 stress cases match bit-for-bit, including the `\|S2\| = 2.0` vs `nextbelow(2.0)` threshold, scale-down overflow prevention, sticky-bit tie-breaking, f32 output denormal flushing, and f64 subnormal single rounding. Checked bit-for-bit on the CPU (`spirv_mini_interp` for f32, SSA `%double` evaluator for f64) and assembled with `tools/spirv_asm.py` (plus `spirv-val` when present) by `tests/semantic/test_alu_div_fmas.py`; not run on the shader corpus. | -| POPS | Primitive-ordered pixel shading (10 PS, `src_pops_exiting_wave_id` wait loop, `s_sleep`, `MSG_ORDERED_PS_DONE`) becomes **fragment-shader interlock** (`PixelInterlockOrderedEXT`). It begins at the end of the entry block and ends at shader exit: a longer critical section with the same ordering. `src_pops_exiting_wave_id` reads 0, and **the runtime must put 0 (no collision, bit 31 clear) in the POPS collision SGPR**, so the hardware wait loop is skipped. Needs `VK_EXT_fragment_shader_interlock` (`fragmentShaderPixelInterlock`). | -| Coherent image accesses (`glc`) | On GFX10 a device-scope (coherent) load is `glc dlc` and a device-scope store `glc`: Mesa sets exactly these bits for `ACCESS_COHERENT` ([`ac_get_hw_cache_flags`](https://gitlab.freedesktop.org/mesa/mesa/-/blob/main/src/amd/common/ac_shader_util.c), GFX10–10.3 branch). In the corpus only the 10 POPS pixel shaders use them: 30 `image_load ... glc dlc` and 50 `image_store ... glc`, all 2D, and in each shader the 3 T#s it loads are the 3 it stores, a read-modify-write of its ordered images. A `glc` `image_load` therefore reads the **storage view the stores write** (`OpImageRead` on binding 8 + 3·dim + class, the class picked from the T# FORMAT as for stores), not the sampled array of "Typed image loads": a sampled read has no coherent form in SPIR-V, and between critical sections the fragment-shader interlock only makes coherent memory visible ([Vulkan memory model](https://docs.vulkan.org/spec/latest/appendices/memorymodel.html): non-atomic accesses are private unless `Coherent`; [ARB_fragment_shader_interlock](https://registry.khronos.org/OpenGL/extensions/ARB/ARB_fragment_shader_interlock.txt): stores to `coherent` memory in one critical section are visible to reads in the next). A shader with a `glc` image load or store decorates its storage views **`Coherent`**, as vkd3d-proton's dxil-spirv does for rasterizer-ordered views (`dxil_converter.cpp`: "ROV implies coherent"). These 10 modules need `shaderStorageImageReadWithoutFormat` (listed in their index features); every other `image_load` keeps the sampled path and needs no storage feature (SHADER-151). `dlc` alone is a CU-scope load and stays non-coherent; `glc` on a sampled read (`image_sample*`, `image_gather*`, `image_load_mip`) is `Unsupported`. A cube has no storage view of its own: it is bound as a six-layer 2D array, so a coherent `image_load` on `dim:SQ_RSRC_IMG_CUBE` is supported (bindings 11/12/13, the third coordinate is the face). Until 2026-11-22 the coherent loads read the sampled array and nothing was `Coherent`, so a POPS read could miss the previous fragment's store. Confirmed by these references, `tests/semantic/test_image_coherent.py` (each read and write's view and type, decorations, capabilities, index features; 7 of its 10 tests fail on the old translator) and a corpus count; **not GPU-checked**: a stale read is a cache race no deterministic test forces. | -| 2D `image_sample_lz` | The T# FORMAT selects the float, UINT or SINT sampled view at LOD zero. With nearest sampling, native gfx1036 returned the original 32-bit integer components. RTX 5080 and gfx1036 Vulkan readbacks matched all four channels on RGBA8 UINT, SINT and UNORM for full-width and D16 results. The R32 UINT/SINT saturation-boundary fixture also matched all 64 sampled sums on both adapters. | -| 2D `image_sample_l` | The T# FORMAT selects the sampled image type, and every type uses the LOD following the two coordinates. Vulkan requires the sampled type and signedness to match the view. The unit test `test_2d_lod_samples_use_matching_typed_views` in `tests/test_image_load_typed.py` checks the R32 UINT, SINT and FLOAT descriptor branches, the float fallback on a lookup miss and the LOD register with full-width and D16 results. [Vulkan sampling validation](https://docs.vulkan.org/spec/latest/chapters/textures.html#textures-input-validation) | -| `image_sample_l` / `image_sample_lz` in every dimension | The T# FORMAT rule applies to a 2D-array, 3D, cube and 1D image too: the sample reads the uint/sint alias of that dimension's sampled binding (3, 6 and 5; a cube uses its 6-layer 2D-array view) and keeps the float view for a float format, the same `image_read_typed` dispatch `image_load` uses. Confirmed by `tests/semantic/test_sample_typed_dims.py` (the alias and sampled-image type each dimension emits, that a float format still samples the float view, and `spirv-val --target-env vulkan1.2`) and `runtime/src/vulkan_bindless.h` (`sampled_binding`). The format rule itself is the 2D row above; a GPU readback on a non-2D integer texture is not measured yet. | -| Implicit 2D pixel-shader integer samples | For `image_sample`, take the UV derivatives before branching on the T# format, then sample the matching float, UINT or SINT view with those gradients. In `ps_sample_implicit_sint` a 128×128 signed texture minifies onto 64×64 pixels, and `ps_sample_implicit_uint` samples the same image through the unsigned view. Clamping the sampler to level 0 returned four color quadrants; allowing level 1 returned cyan. All four signed D16 channels matched at every pixel on RTX 5080 and gfx1036; both fixtures are 4096/4096 pixels exact on an Intel UHD Graphics 630 (CFL GT2), Mesa 25.2.8. | -| Texel offsets | `image_sample*_o`: the first address dword packs signed 6-bit offsets (x [5:0], y [13:8], z [21:16]), which become the SPIR-V `Offset` operand. A non-constant `Offset` outside gather needs **`VK_KHR_maintenance8`**, and is validated with `spirv-val --allow-offset-texture-operand`. The operand is always a run-time value: the translator extracts the fields from the register, also when the shader loaded the dword from an immediate, so every `_o` sample needs the extension. `image_gather4_lz_o` / `_l_o` read x and y the same way; a gather `Offset` needs `shaderImageGatherExtended`, not maintenance8. **GPU-tested** with `runtime/test/shaders/ps_texoff.asm` on `vk_texture_test` (in `check.py` and `scripts/run_gpu_tests.py`; SKIP on a device without the extension), on an AMD Radeon RX 6800, Windows driver 26.11.2, maintenance8 enabled: an 8×8 texture whose texels are all different, a point sampler that clamps to the edge, 2D targets, mip 0. `image_sample_lz_o` with an offset computed per pixel (all 64 pairs of x, y in −4..3, none clamped), `image_sample_l_o` with (−3, +2) and `image_sample_lz_o` with (+16, −32) from immediates, and `image_gather4_lz_o` of red and of green with the per-pixel offset gave, on all 4096 pixels, the texels worked out by hand from this rule (derivation in the `.asm` header). Run with a sabotaged translator, the test fails when the sample offset is dropped, has x and y swapped, takes y from bit 6, or uses 4-bit or 5-bit fields, and when the gather offset is dropped, has x and y swapped or takes y from bit 6; 4-bit and 5-bit gather fields pass, because the gather offsets stay in −4..3. What it shows is that the translated SPIR-V implements this rule on Vulkan; it does not measure the field layout on the hardware. **It cannot see the sign extension on this driver**: with the fields read unsigned the same texels come back: `Offset` 60..63 sampled as −4..−1 and +32 as −32 (the device reports texel offset limits −64..63, gather −32..31). The sign extension and the gather field width are therefore pinned by the structural test `tests/test_texel_offsets.py` (signed, bit 8k, 6 bits, for `_lz_o`, `_l_o`, `_o`, 3D and gather) and are not GPU-tested through Vulkan. **The x field is measured on hardware:** `image_sample_lz_o` run as a raw compute kernel on the same RX 6800 (gfx1030, wave32 and wave64), on a 64×1 `R32_FLOAT` image whose texel i holds i, with a point sampler that clamps to the last texel: from texel 40, offset dword `0x20` reads texel 8 and `0x3c` reads texel 36 (unsigned would clamp both to 63); from texel 10, `0x1f` reads 41 and `0x20` clamps to 0; `0x40`, `0x80` and `0xc0` read the centre texel (bits 6–7 are ignored); and a non-zero y field, z field or top byte leaves x alone. All 36 rows fit x = sign-extended bits [5:0]. **The y and z fields are measured too** (SHADER-337): `tools/texoff_probe.py --oracle hw` on the integrated GPU of a Ryzen 9 9950X3D (gfx1036, RDNA2, Windows driver 32.0.21045.16010), wave32 and wave64, samples a linear `R32_SFLOAT` texture whose texel holds its index (2D 64×64 for y, 3D 64×1×64 for z) with `image_sample_lz_o` and a point sampler that clamps to the last texel. From row 40, y = `0x20` reads row 8 and `0x3c` row 36, `0x21` row 9 (unsigned would clamp all three to 63); from row 10, `0x1f` reads 41 and `0x20` clamps to 0 (unsigned: 42); `0xc0` (bits 14–15 set, field 0) reads row 40 and `0x7f` row 39, so those bits are ignored; x −2 with y −4 in one dword reads both. The z field at bits [21:16] gives the same 7 results on the 3D image. All 15 rows fit each field = sign-extended 6 bits, the bits above it ignored, which is the translator's rule; `tests/test_texoff_probe.py` checks that every row with a negative field tells the signed reading from the unsigned one. The (+16, −32) sample is outside Vulkan's guaranteed −8..7 and is judged only where the device limits cover it. **`image_sample_o`, `image_sample_b_o` and `image_gather4_l_o` are GPU-tested** with `runtime/test/shaders/ps_texoff_forms.asm` (the same texture, sampler and per-pixel offset as `ps_texoff`, all 64 offset pairs in −4..3; in `check.py` and `scripts/run_gpu_tests.py`): 4096/4096 pixels exact on an NVIDIA GeForce RTX 4090 (driver 621.24) and on the integrated GPU of a Ryzen 9 9950X3D (gfx1036, driver 32.0.21045.16010), both with maintenance8 enabled. Not GPU-tested: `_c_lz_o`, the z field (3D), 1D, 2D-array and cube targets (offset next to an array layer), wrap or mirror addressing, linear filtering, mips other than 0, other vendors' drivers, and a device without maintenance8 (the test skips there; the translator has no fallback for it). **Without maintenance8 (`--texel-offset-fallback`, NVIDIA Pascal for one):** an `image_sample*_o` gets no `Offset`; the offset is folded into the coordinate instead, as coordinate + offset ÷ the size of the sampled level. The level is 0 for `_lz` / `_c_lz`, the given LOD for `_l`, and `OpImageQueryLod`'s for implicit samples (plus the bias for `_b`), rounded the way the S#'s `MIP_FILTER` (word 2 [27:26], literal or read at run time) picks a level, and clamped to the image's levels: floored for linear, nearest with a tie rounding up for point (floor(LOD + 0.5), computed as floor + (fraction ≥ 0.5) so binary32 rounding of the sum can't move it; Vulkan allows either tie rule, and RTX 5070 GPUs (drivers 616.56, 621.01) sample LOD 0.5 and 0x3f000001 at mip 1, as `tools/image_query_probe.py` records RDNA2 doing) and for the value 3, and 0 for none, whose LOD the runtime holds in [0, 0.25] (SHADER-699: a point-mip sample at LOD 0.75 reads mip 1, so flooring shifted it by mip-0 texels; checked in `tests/test_texel_offsets.py` by evaluating the emitted level chain). A texel offset applies before wrapping and clamping, and an integer offset commutes with both, so the shift is exact for every address mode at that level. The one case that differs is a trilinear blend of two levels, where the coarser level moves by offset ÷ 2 of its texels. Implicit samples become `Grad` samples with the derivatives of the unshifted coordinate (× 2^bias for `_b`), so the LOD and anisotropy are those of the original sample even when the offset varies per pixel. Gathers keep their `Offset` (`shaderImageGatherExtended`). Only 4 of the 12,101 PS need it, all through `image_sample_o`. **GPU-tested** on an NVIDIA GeForce GTX 1060 6GB (no maintenance8; driver 560.94, Windows 10) with `LEONIDA_TEXOFF_FALLBACK=1`: `ps_texoff` and `ps_texoff_implicit` (the per-pixel sample as `image_sample_o`) are 4096/4096 pixels exact, with the +16/−32 sample judged too, since a coordinate shift has no device offset limit. Checked in `tests/test_texel_offsets.py`, including `spirv-val` without `--allow-offset-texture-operand`. | -| A16 sample offsets | For the supported `image_sample*_o` forms, the first address VGPR retains the signed texel-offset fields. The following coordinates and any trailing LOD use packed binary16 halves, low half first. LLVM counts extra operands as whole words before packing coordinates and LOD ([getAddrSizeMIMGOp](https://llvm.org/docs/doxygen/AMDGPUBaseInfo_8cpp_source.html#l00342)). On RTX 5080 and Radeon Graphics, `ps_texoff.asm` checked 64 distinct offsets applied to packed U/V at texel (3,5) against the expected texel for each of 4096 pixels. Swapping the halves or dropping the offset changed 4032 pixels per GPU. | -| `s_memtime`, `s_memrealtime` | Behind `--shader-clock khr` (default `off`: both stay `Unsupported`, as before). `s_memtime` is the per-CU shader clock: `OpReadClockKHR` with Subgroup scope; `s_memrealtime` is the constant-rate REFCLK counter: Device scope. The 64-bit result goes to the destination SGPR pair, low word first; other destinations are `Unsupported`. Each module declares `ShaderClockKHR` + `SPV_KHR_shader_clock` and lists `shaderSubgroupClock` and/or `shaderDeviceClock` in the index `features`, only for the scopes it reads. The runtime enables `VK_KHR_shader_clock` with whichever feature the GPU has (`VulkanDeviceInfo::shader_subgroup_clock` / `shader_device_clock`, checked by `d3d12_vulkan_device_test`); the shader library does not read `features`, which is why the rule is opt-in: a module with a scope the device lacks fails `vkCreateShaderModule`. Values are not comparable with a console GPU's (different clock and frequency), so time differences work and fixed-frequency assumptions don't. CPU-checked by `tests/semantic/test_smem_clock.py` (scopes, capability/extension, features, spirv-val, off by default). GPU: a PS reading both clocks creates its pipeline (`vk_pipeline_check`) on an RTX 6000 Ada (Linux) and an RX 9060 XT (RADV, #2817). The values themselves are not measured. | -| A16 gather offsets | On GFX10, `image_gather4_lz_o` and `image_gather4_l_o` take the packed signed texel offset in a full VGPR before the packed binary16 coordinates and optional LOD. LLVM [counts the extra operand before packing coordinate words](https://llvm.org/docs/doxygen/AMDGPUBaseInfo_8cpp_source.html#l00342). The synthetic `gather_offset_a16.asm` checks an offset of (−1,+1) with distinct U and V and a nonzero mip. Checked by the unit test `test_a16_offset_gathers_preserve_offset_and_unpack_uv_lod` in `tests/test_image_load_typed.py`, which translates that fixture and its `gather4_lz_o` variant and follows the offset fields and the packed U, V and LOD halves back to their source VGPRs. | -| Optional device features | Shaders may need `fragmentShaderBarycentric`, `fragmentShaderPixelInterlock` and `maintenance8`. All three are present on an RTX 4060 Ti (and an RTX 2060 SUPER), and `runtime/test/vk_harness.cpp` enables them when available, as does the runtime's `create_vulkan_device_standalone`, each with its extension (`VulkanDeviceInfo::fragment_shader_barycentric`, `fragment_shader_interlock`, `maintenance8`; checked by `d3d12_vulkan_device_test`). All three are present on an RTX 4060 Ti, and `runtime/test/vk_harness.cpp` enables them when available. (It is guarded by the header macro `VK_KHR_MAINTENANCE_8_EXTENSION_NAME`, so older Vulkan headers build without it. `vk_texture_test` enables it too, and `shaderImageGatherExtended`.) A device without `fragmentShaderBarycentric` (NVIDIA Pascal) runs the raw-barycentric PS with `--bary-fallback` (below). Shaders translated with `--fma khr` need `VK_KHR_shader_fma` and its `shaderFmaFloat32` feature (`VkPhysicalDeviceShaderFmaFeaturesKHR`): `create_vulkan_device_standalone`, `runtime/test/vk_test_device.h` and the `vk_*` test programs enable it when the device offers it (`VulkanDeviceInfo::shader_fma`), and a test program refuses (exit 77) a module with `OpCapability FMAKHR` on a device without it. | -| Wave size | **Most of the game's shaders are wave64: 23,841 of 26,503** (`fssm_header.wave_size()`: FSSM header flags word `u32[0xD4]` bit 5, `0x20` = wave32, `0` = wave64; 0 contradictions against GFX10 code-proven wave32/wave64 instructions across all 26,503 blobs): 10,974 of 12,101 PS, 9,282 of 9,282 mesh shaders, 2,236 of 2,236 VS, 1,154 of 2,689 CS and 195 of 195 GS, against 2,662 wave32 (1,535 CS and 1,127 PS). A full-corpus translation at `ec8ec4c9` marks exactly these 23,841 `wave64` (`subgroup_size` 64) in the index. Before the FSSM flag (#1900) the wave size came from code markers (64-bit EXEC/mask writes, `exec_hi`, `*_saveexec_b64`): at `6a6704df` they made 21,538 of the 26,487 shaders translated then wave64 (the figure quoted here was 21,545). 10,031 PS, 9,282 mesh shaders, 1,179 VS, 851 CS and 195 GS (the 16 shaders refused then are all wave64 CS by the flag; the figure quoted here was 21,545). Against the flag they call 2,287 wave64 shaders wave32 (943 PS, 1,057 VS, 287 CS), whose code has no 64-bit EXEC/mask marker, and none the other way. An older marker scan (`s_mov_b64 exec, -1`, `exec_hi`, `s_and/or_saveexec_b64` and 64-bit masks) counted 9,930 PS, 8,666 mesh shaders, 1,115 VS and 923 CS, but it left out the 769 listings whose names start with `.` (616 of them mesh shaders; Python's `glob` skips such names). Over all 26,503, the translator's own marker test (`WAVE64_RE`, or a 64-bit op on EXEC/VCC) on the code `translate()` keeps finds 21,554 wave64: 10,031 PS, 9,282 mesh shaders, 1,179 VS, 867 CS and 195 GS. With the 2,287 above that is exactly the flag's 23,841, and none contradicts it; read raw, 104 more wave32 listings (80 CS, 24 PS) seem to carry a marker, all from embedded data words decoded as instructions. The first marker scan (`s_mov_b64 exec, -1`, `exec_hi`, `s_and/or_saveexec_b64` and 64-bit masks, written into this row at `0082ad53`) counted 9,930 PS, 8,666 mesh shaders, 1,115 VS and 923 CS: 20,634 without the GS, so not the 21,545 total either. The translator maps a wave to a subgroup, and NVIDIA subgroups are 32 wide. What that means: (1) lane-independent code, which is most pixel-shader math, is exact; (2) wave-wide branch decisions and reductions are made per 32-lane half, which is exact unless scalar state computed for one half is later consumed by the other; (3) lane indices from `v_mbcnt_lo/hi` and wave IDs from the merged-wave SGPR must be 64-lane values. Mesh and compute shaders build thread IDs as wave_id·64 + mbcnt, so those need a mapping from `LocalInvocationIndex` (lane = index & 63, wave = index >> 6). Full fidelity needs either 64-wide subgroups (AMD GPUs, via `VK_EXT_subgroup_size_control` requiredSubgroupSize = 64) or emulating cross-half ops (ballot, readlane, shuffles across halves) through workgroup memory. | -| Mesh shaders | NGG wave64 programs → `VK_EXT_mesh_shader` (`MeshEXT`). **PSV0** (DXBC) gives NumThreads (128×1×1 in the corpus), MaxOutputVertices/Primitives (128/128) and the topology (triangles). System inputs, from Mesa's RADV setup for mesh as NGG on GFX10.3: v5 = first launch vertex ID of the lane (the "vertex_id" slot), `linearGroupIndex * NumThreads + LocalInvocationIndex` with the linear index from WorkgroupId/NumWorkgroups; all 9,282/9,282 corpus mesh shaders read `v5` once with `v_readfirstlane_b32 sX, v5` and use `sX` only via `s_lshr_b32 D, sX, 7` to recover the group index (NumThreads is 128 in the corpus), matching TomBox's mesh ABI (`gid.x * numThreads + gi`) on 1D launches. GPU-checked with `runtime/test/shaders/ms_v5_workgroup.asm` (24/24 groups exact on RTX 4060 Ti and RTX 3080, and on an RTX 4050 Laptop and an AMD Radeon 740M (RADV)); still unverified on Xbox hardware: the low 7 bits of `v5` on lanes 1..127 and whether 3D `DispatchMesh` flattens XYZ or uses X only. The merged-wave-info SGPR (s3 in this ABI) = wave ID << 24, from LocalInvocationIndex >> 6; `v_mbcnt` lanes = LocalInvocationIndex & 63; user data in s16.. as usual. All 9,282 mesh-shader listings of 1.0.2.1 (names starting with `.` included) read exactly v5 before writing anything (`rdna2spirv.read_before_write_vgprs` over the code `translate()` keeps). An earlier sample of 1,500 put 27 aside as adding loop-carried registers; over the corpus no extra read is loop-carried. Read raw, 266 of the 309 listings with embedded data words seem to read more VGPRs, each after a branch (in 101 the register is written after the read); they come from data words decoded as instructions and are gone once the listing is re-anchored to the FSSM code and cut to reachable code, as `translate()` does. 1,473 of 1,500 sampled mesh shaders read exactly v5, and the rest only add loop-carried registers. Exports: on NGG, thread t exports vertex t (`pos0`, `paramN`) and primitive t (`prim`). They're staged per invocation; an all-`off` export is the dummy a wave with no vertices must issue, and writes nothing. `s_sendmsg GS_ALLOC_REQ` (m0 = prims << 12 \| verts, sent by thread 0) stores the counts in a workgroup variable. At shader end, in uniform control flow: workgroup barrier, `OpSetMeshOutputsEXT(min(verts, max), min(prims, max))`, then each thread writes its staged vertex (Position + Location N) and primitive (`PrimitiveTriangleIndicesEXT` = bits [8:0], [18:10], [28:20]; `CullPrimitiveEXT` = bit 31). `pos1..pos3` clip/cull distances are staged per invocation and emitted in a per-vertex `Block` output struct (`Position` + `ClipDistance`/`CullDistance` arrays, `VK_EXT_mesh_shader`) when used, keeping the standalone `%ms_out_pos` layout unchanged for shaders without `pos1+`. The distances are copied to that struct one float at a time, not as a whole array: SPIRV-Cross 1.4.363.0 turns a whole-array store into a mesh output into a C array assignment that Metal rejects (SHADER-155; `ms_clip` then compiles and draws its 2048/4096 pixels in a native Metal mesh draw on an Apple A18 Pro). GPU-checked with `runtime/test/shaders/ms_tri.asm` (`VKH_MESH=1 vk_harness`), built from the game's own idioms (thread ID from s3 and mbcnt across two waves, thread-0 ALLOC_REQ, per-thread exports): 0 error on every pixel. | -| Mesh shaders as compute (`--mesh-compute`) | For devices without `VK_EXT_mesh_shader` (NVIDIA Pascal, for one), and on by itself in `make_game.py` on Intel's Windows Vulkan driver (`VK_DRIVER_ID_INTEL_PROPRIETARY_WINDOWS` with mesh shaders, `runtime_gpu_mesh_draws_crash`): there `vkCmdDrawMeshTasksEXT` crashes (0xC0000409 in `igvk64.dll`) for a mesh shader with a live push-constant load at byte 32 or later, which every corpus mesh shader has, while `--mesh-compute` is exact (BUILD-2202, Arc A770, driver 32.0.101.9175; no fixed version known; `--native-mesh` keeps native mesh shaders). Each mesh shader becomes a `GLCompute` module with the same workgroup size and code; only the epilogue changes. Instead of `OpSetMeshOutputsEXT` and the mesh outputs, after the same barrier lane 0 writes the vertex and primitive counts, lane i < vertex count writes its vertex and lane i < primitive count its primitive into this workgroup's **slot** of an output buffer: slot = linear workgroup index (x + y·nx + z·nx·ny) × `slot_bytes`, computed in 64 bits. The buffer's device address is in push-constant dwords 36–37, so these modules declare 152 bytes. Slot layout (`rdna2spirv.mesh_compute_layout`, recorded per shader as `mesh_compute` in the index), all 16-byte aligned: a header (vertex count, primitive count), then `max_vertices` vertices, each holding the position, the clip and then cull distances padded to whole vec4s, and one vec4 per param location; then `max_primitives` primitives of three vertex indices plus 1 if culled. The modules need no mesh capability, extension or `shaderClipDistance`. `tools/mesh_compute_vs.py` writes the vertex shader that draws the slots with a non-indexed `vkCmdDraw(groups × max_primitives × 3)`: vertex v is workgroup v / (3·max_primitives), primitive (v / 3) mod max_primitives, corner v mod 3. A primitive past the count, or one culled, gets one position outside the clip volume at all three corners and is clipped. Otherwise the corner's index, clamped to `max_vertices` − 1, selects the vertex, and its position, distances and params go out at the mesh shader's locations, so the pixel shader is unchanged. One draw rasterizes in vertex order, which is workgroup then primitive order, as with mesh workgroups. Corpus: all 9,282 mesh shaders are 128×1×1 with 128/128 outputs, wave64, 0–18 params, clip distances in 1,906, cull distances and per-primitive attributes in none, no task shaders. On a 32-wide device combine it with `--wave64-emulate`. GPU-checked on an NVIDIA GeForce GTX 1060 6GB (Pascal: no mesh shaders; driver 560.94, Windows 10) with `LEONIDA_MESH_COMPUTE=1 LEONIDA_W64_EMULATE=1`: `ms_tri`, `ms_w64x_ballot` and `ms_wave_info_s3` 4096/4096 pixels exact, `ms_clip` 2048/4096 covered as expected, `ms_v5_workgroup` 24/24 workgroup coordinates, zero Khronos validation messages. Checked in `tests/test_mesh_compute.py`. The runtime side, turning a `DispatchMesh` into that dispatch, a barrier and the draw, is the follow-up (it needs the graphics pipelines of #291). Unused primitives still run the vertex shader; compaction with an indirect draw would avoid that. | -| Mesh primitive export and allocation (`exp prim`, `MSG_GS_ALLOC_REQ`) | The GFX10 NGG formats, from Mesa 22.3 `src/amd/llvm/ac_llvm_build.c`: `ac_build_sendmsg_gs_alloc_req` (lines 4475–4477) puts `prim_cnt << 12 \| vtx_cnt` in m0, and `ac_pack_prim_export` (lines 4518–4539) packs index 0, 1 and 2 in bits 0–8, 10–18 and 20–28, the edge flags in bits 9, 19 and 29 and "null primitive (skip)" in bit 31. Thread t exports vertex t and primitive t, only below the vertex and primitive counts (`src/amd/common/ac_nir_lower_ngg.c`, `emit_ms_finale`, lines 4056–4067). Translated: the counts from m0 (each clamped to PSV0's maximum) go to `OpSetMeshOutputsEXT` or the `--mesh-compute` header; `PrimitiveTriangleIndicesEXT` takes the three 9-bit fields without the edge flags, and `CullPrimitiveEXT` (or the slot's culled word) is bit 31; invocations at or past a count write nothing. Executed for both paths in `tests/semantic/test_ms_prim_export.py` (72 threads in two wave64 waves: odd threads set the edge flags, threads with t & 2 the null bit). Open: the index fields are not clamped to the vertex count as Mesa's mesh lowering clamps them (`ac_nir_lower_ngg.c` line 4112), so a null primitive whose fields point past the count (skipped on hardware) would be undefined in SPIR-V; no corpus count of such exports exists. | -| Geometry shaders | On output stream zero, `GS_OP_EMIT_CUT` emits the staged vertex and ends its strip under the same EXEC guard. The synthetic `gs_emit_cut.asm` checks that six vertices form two separate triangles. [RDNA 2 ISA, S_SENDMSG](https://docs.amd.com/api/khub/documents/Et~wpu9g~Ffl7d9q0QZ~Og/content). All 195 are `$GS_VoxelizeGeneric` permutations: legacy (merged ES/GS) wave32 programs on LDS rings, with no `exp`. All 195 are `$GS_VoxelizeGeneric` permutations: legacy (merged ES/GS) programs on LDS rings, with no `exp`, written for wave64 (the FSSM header's wave-size flag says wave64 in 195 of 195, see *Wave size*, and the translator's index marks all 195 `wave64` with `subgroup_size` 64 at `f847748c`; the code agrees: the EXEC prologue that `gs_tri.asm` mirrors compares the thread count with 64 and writes a 64-bit EXEC, the count in #94 finds `v_mbcnt_hi_u32_b32` in all 195, and the translator marks all 195 `wave64`; an earlier version of this row said wave32, TEST-251). Inputs: vertex i sits at the dword offset in v0 lo / v0 hi / v1 lo; an LDS read at vertex base + 4·(4·reg + comp) is input-signature register reg, component comp (checked: SV_Position xyz in dwords 0–2 and TEXCOORD0.xy in 4–5, as ISG1 declares). Outputs: emitted vertex k is dwords [k·4·nreg, (k+1)·4·nreg) of the lane's GSVS area, dword = 4·reg + comp of the output signature (20 dwords = 5 OSG1 registers; every write matches a declared mask). Translation: synthetic offsets (vertex i at dword 64·i), LDS reads → `gl_in[i]` inputs, LDS writes → staged slots, `MSG_GS EMIT` → copy slot (emit count) to the outputs + `OpEmitVertex`, `CUT` → `OpEndPrimitive`, `GS_DONE` → nothing. The prologue's `s_bfm_b64`/`s_cselect` EXEC setup is fed s3 = 64 << 8. GPU-checked with `runtime/test/shaders/gs_tri.asm` (`VKH_GS=… vk_harness`): 0 error. Without a geometry stage (Apple GPUs: Metal, MoltenVK), `tools/spirv_gs_to_compute.py` lowers the translated module to a compute capture pass, one invocation per input primitive: inputs come from a buffer, each `OpEmitVertex` guards its record/meta stores and `%gsc_n` increment on `n < OutputVertices` (dropping excess vertices rather than overflowing into the next primitive's slots, and updating `OpPhi` predecessors across split blocks, and rejecting (`Unsupported`) an `OpEmitVertex` in a loop header before its `OpLoopMerge`, which the split would move; SHADER-617, checked on the CPU by `tests/test_spirv_gs_to_compute_bounds.py`), and a meta buffer holds each primitive's vertex count (`<= OutputVertices`) and strip ends, for an ordinary draw afterwards (SHADER-159). Metal, MoltenVK), `tools/spirv_gs_to_compute.py` lowers the translated module to a compute capture pass, one invocation per input primitive: inputs come from a buffer, each `OpEmitVertex` writes the outputs to a record buffer, and a meta buffer holds each primitive's vertex count and strip ends, for an ordinary draw afterwards (SHADER-159). `gs_tri` lowered this way, converted with SPIRV-Cross and run natively on an Apple A18 Pro: 195/195 records exact for 65 random triangles, and the captured fullscreen triangle drawn from the records matches all 4096 gradient pixels. Not done: wiring it into a draw path, and GS that use cross-lane operations or more than one invocation. | -| Integer clamp | The VOP3 `clamp` bit on `v_add_nc_u32`, `v_sub_nc_u32`, `v_subrev_nc_u32` saturates the result to [0, 0xFFFFFFFF], and on `v_add_nc_i32`/`v_sub_nc_i32` to [0x80000000, 0x7FFFFFFF]; without it they wrap. GFX9+ semantics: LLVM selects `uaddsat`/`usubsat` and `saddsat`/`ssubsat` to exactly these ops with clamp set. **Until this change clamp was silently ignored on the unsigned ops** (and the signed ones were `Unsupported`). Checked on the CPU by `tests/semantic/test_alu_add_nc_clamp.py`. The carry-out unsigned ops (`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`) with VOP3 `clamp` likewise saturate D to `0xFFFFFFFF` on add carry or `0` on sub borrow while still reporting the real carry/borrow bit in `sdst` (**until 2026-11-22 the translator ignored `clamp` on all six**); confirmed natively on RDNA2 (AMD Radeon 680M `gfx1035` wave32 & wave64 via `tools/hw_oracle`, and independently on `gfx1036` in #1746) and CPU-checked by `tests/semantic/test_alu_add_co_clamp.py`. The 16-bit unsigned add/sub (`v_add_nc_u16`, `v_sub_nc_u16`, and the `v_add_u16`/`v_sub_u16`/`v_subrev_u16` `_e64` names) saturate to [0, 0xFFFF] with `clamp` (llvm-mc 21 gfx1030 encodes the bit on them, and LLVM selects i16 `uaddsat`/`usubsat` to them); **until 2026-11-22 the translator wrapped instead**. `clamp` on any other 16-bit integer op raises `Unsupported`. CPU-checked by `tests/semantic/test_alu_u16_clamp.py` (the high half of the destination is kept), **not GPU-verified**. CPU-checked by `tests/semantic/test_alu_u16_clamp.py` (the high half of the destination is kept), and **Hardware-verified on RDNA2** (AMD Radeon 680M, `gfx1035`, Windows 11, driver `26.5.1`, wave32 and wave64 via `tools/int_hw_probe.py --oracle both`, SHADER-137): all 32-bit and 16-bit `*_nc_*` `clamp` cases (including `op_sel` and kept destination half on u16) match hardware bit-for-bit. **Open divergence measured on the same hardware:** `v_add_co_u32`, `v_sub_co_u32`, `v_subrev_co_u32`, `v_add_co_ci_u32`, `v_sub_co_ci_u32` and `v_subrev_co_ci_u32` with `clamp` saturate D (`0xFFFFFFFF` / `0`) while still reporting the real carry/borrow in `sdst`, whereas the translator currently ignores `clamp` on these carry-out ops. | -| Push-constant tail as a uniform block (`--pc-tail-ubo`) | For devices whose `maxPushConstantsSize` is 128, Vulkan's minimum, which can't take the 144-byte block (152 with `--mesh-compute`): AMD's older Windows drivers on RDNA2 iGPUs (Radeon 680M on 22.40.84.06, 610M on 24.10.16.14, the Ryzen 5 7600's iGPU on 24.10.24; a 610M on 26.11.2 reports 256) and some Intel Arc drivers (D3D-14, `push_constants_need_fallback` in `d3d12_vulkan_device.cpp`). The push-constant block keeps dwords 0–31 (s0–s31, 128 bytes). The tail that follows them by default, the heap base and code base and, with `--mesh-compute`, the output address, becomes `%pc_tail`: a uniform block at **set 1, binding 0** with the same members in the same order at offsets 0, 4, … (16 bytes, 24 with `--mesh-compute`). Set 1 is otherwise unused, so set 0's update-after-bind table doesn't change. The block is declared, and listed in the entry point's interface, only when the shader reads the tail (a memory access through the heap base, `s_getpc_b64`, or the `--mesh-compute` epilogue); the index then records `"pc_tail": {"set": 1, "binding": 0, "bytes": 16}`, and `"push_constant_bytes"` is 128 for every module. `"bindings"` still lists set 0 only. Without the flag nothing changes. **Checked:** `tests/test_pc_tail_ubo.py` (on `cs_store` and `ps_m15`: the block, its interface entry, `spirv-val`, the metadata, no block without a tail read, and the `--mesh-compute` address). The whole hand-written GPU test set in `runtime/test/shaders` is translated with the flag by `build.py` or `scripts/run_gpu_tests.py` under `LEONIDA_PC_TAIL_UBO=1`, and the index's `pc_tail` entries say which modules read the tail; how many do changes as shaders are added, so no count is kept here. The GPU test programs bind the block (`runtime/test/vk_pc_tail.h`; the list is in docs/testing.md), except with `--mesh-compute`, whose tests skip. The D3D12 layer does not yet: it refuses pipelines on a device with fewer than 144 push-constant bytes (`push_constants_fit` in `d3d12_vulkan_device.cpp`). | -| `v_mad_u32_u16` / `v_mad_i32_i16` op_sel on S2 and D, and clamp | D = S0.half · S1.half + S2, the halves zero- (u16) or sign-extended (i16), op_sel bit 0 / 1 reading the high half of S0 / S1. The other bits and `clamp` were refused (`Unsupported: op_sel/clamp`) until their results were measured on RDNA2 (AMD Radeon iGPU, gfx1036, Windows driver 26.10.1, raw kernels through `tools/hw_oracle`, wave32 and wave64 alike; EGEN-HW-MAD-U32-U16, 44 words): **op_sel bit 2 adds S2[31:16] zero-extended, in the i16 op too** (`v_mad_i32_i16 d, 3, 3, 0xffff8000 op_sel:[0,0,1,0]` gives `0x00010008`, not 8); an inline float constant there is its f32 pattern (`1.0` adds `0x3f80`); **op_sel bit 3 writes the result shifted left by 16** (low half 0, the old D not kept); **`clamp` saturates the 32-bit sum** to [0, 0xffffffff] (u16) or [0x80000000, 0x7fffffff] (i16), before that shift (the 16-bit product itself never overflows). GPU-checked with `runtime/test/shaders/ps_valu16_mad_sel.asm` (4096/4096 on NVIDIA GeForce RTX 5080, driver 616.92, and the gfx1036 iGPU); CPU-checked by `tests/semantic/test_alu_mad_32_16.py` (40 seeded cases against a Python reference) and `tests/semantic/test_value_semantics.py`. | -| `v_add_nc_i16`, `v_sub_nc_i16` | GFX10 VOP3-only signed 16-bit add and subtract. Without `clamp` they are bit-identical to `v_add_nc_u16`/`v_sub_nc_u16` (the low 16 bits wrap) and take the same path: `op_sel:[s0,s1,dst]` picks each source's half and the destination half, and the other half of D is kept. With `clamp`, the exact sum or difference of the sign-extended halves saturates to [-32768, 32767] (`SClamp`), where the u16 forms saturate to [0, 0xFFFF]. RDNA2 (GFX10.3) dropped reversed 16-bit integer subtraction (`v_subrev_nc_u16` / `v_subrev_nc_i16` do not exist on hardware; `v_subrev_f16` is the only 16-bit reverse subtract opcode). Checked by `tests/semantic/test_valu_add_sub_nc_i16.py` (a value grid with and without `clamp`, `op_sel`, literals, SGPR sources, and untouched half preservation) and **Hardware-verified on AMD RDNA2** (`gfx1036`, wave32 and wave64 via `tools/int_hw_probe.py`, `valu_add_nc_clamp/v_add_sub_nc_i16_clamp`): signed saturation to [-32768, 32767], `op_sel` source selection, and untouched destination half preservation match hardware bit-for-bit. Until 2026-11-22 both raised `Unsupported`. CPU-checked by `tests/semantic/test_valu_add_sub_nc_i16.py` (a value grid with and without `clamp`, `op_sel` including the destination half, and equality with the u16 forms without `clamp`). **GPU-verified** on native RDNA2 (gfx1036, the Radeon iGPU of a Ryzen 7 9800X3D, Windows driver 32.0.21042.62) through `tools/hw_oracle`, one-thread raw kernels: 112 of 112 directed cases (both ops; 0x7FFF+1, 0x8000+1, 0x8000+0xFFFF, 0x7FFF+0x7FFF, 0x8000+0x8000 and others, each with and without `clamp` and with `op_sel` `[0,0,0]`, `[1,0,1]`, `[0,1,0]` and `[1,1,1]`, the destination preset to 0xA5A5A5A5). For example `v_add_nc_i16(0x7FFF, 1)` gives 0x8000 wrapped and 0x7FFF with `clamp`, `v_sub_nc_i16(0x8000, 1) clamp` gives 0x8000, and the destination half `op_sel` doesn't pick keeps its 0xA5A5. `tools/pk16_diff.py --oracle translator,hw --ops v_add_nc_i16,v_sub_nc_i16 --programs 3000 --seed 1`: 3000 of 3000 programs agree with the hardware and the translator. **Not GPU-verified.** Measured on native gfx1100: `clamp` saturates the exact sign-extended sum to [-32768, 32767] and the other half of D is kept. | -| Gather sampler LOD | Before choosing the mip for the four fetches in `image_gather4_l(_o)`, clamp the requested LOD to S# word 1's MIN_LOD [11:0] and MAX_LOD [23:12] (unsigned 4.8). `ps_gather_sampler_lod.asm` reads the S# from the heap. On RTX 5080 and Radeon Graphics, a maximum of 0.25 selects the base quadrants and a minimum of 0.75 selects the cyan mip across the 64×64 draw. Without these bounds half of each frame reads the wrong level. Radeon also agreed with native `OpImageGather Lod` (`VK_AMD_texture_gather_bias_lod`) for those bounds. At exactly 0.5, with bounds [0,1], that native draw selected mip 1; the emulation now computes the mip as `Floor(LOD + 0.5)`, ties up, and also selects mip 1 (before SHADER-152 it used `RoundEven`, which selected mip 0). It computes `floor(LOD) + (LOD - floor(LOD) >= 0.5)`, which is exact in binary32, not `Floor(LOD + 0.5)`: that sum rounds `0x3effffff` up to 1.0, and on an RTX 5070 (621.24) the gather then read mip 1 where native `image_sample_l` at the same LOD reads mip 0. | -| `s_absdiff_i32`, `s_mul_hi_i32` | `s_absdiff_i32`: D = \|S0 − S1\| with the 32-bit difference wrapped first (0x7FFFFFFF − 0x80000000 → 1; a difference of −2³¹ stays 0x80000000), SCC = D ≠ 0. `s_mul_hi_i32`: high word of the signed 64-bit product, SCC kept. From the RDNA2 ISA pseudocode; checked on the CPU by `tests/semantic/test_salu_absdiff_mul_hi.py`. **Hardware-verified** on an AMD Radeon RX 7900 XTX (gfx1100, Windows 11, driver 26.10.1) as raw wave32 kernels through `tools/hw_oracle`: `s_absdiff_i32(0x7FFFFFFF, 0x80000000)` = 1 and `s_absdiff_i32(0x80000000, 0)` = 0x80000000, both with SCC = 1, and equal operands give 0 with SCC = 0; `s_mul_hi_i32(0x7FFFFFFF, 0x7FFFFFFF)` = 0x3FFFFFFF and `s_mul_hi_i32(-1, 1)` = 0xFFFFFFFF, with SCC left as it was. Also verified on native RDNA2 (gfx1036, AMD Radeon Graphics): 500 programs in `tools/salu_diff.py` (`--oracle translator,hw`) matched bit-for-bit with 0 mismatches, and the high product word and SCC retention confirmed across edge values. | -| SCC from scalar ALU | `s_and/or/xor/andn2/orn2/nand/nor/xnor_b32` and `s_lshl/lshr_b32` set SCC = result ≠ 0, `s_add/sub_i32` and `s_addk_i32` set it to signed overflow, `s_min_u32`/`s_max_u32` to S0 < S1 / S0 > S1, and `s_min_i32`/`s_max_i32` to the same compared signed: SCC is 1 when S0 is the one chosen, and a tie chooses S1 (RDNA2 ISA, S_MIN_I32: D = S0 < S1 ? S0 : S1, SCC = 1 if S0 is chosen). **Before this fix these ops left SCC unchanged**, so a following `s_cbranch_scc*` read a stale flag, and until 2026-11-21 `s_min_i32`/`s_max_i32` set SCC on a tie. 32-bit scalar shifts now mask the amount to 5 bits. GPU-checked with `runtime/test/shaders/ps_scc.asm` and `ps_scc_minmax.asm` (NVIDIA GeForce RTX 2060 SUPER, Linux, driver 620.70.06: 4096/4096 pixels exact, and all 4096 differ with the old translator). **On lane masks in a wave32 program** (a source is EXEC, VCC or a mask SGPR, or the result goes to EXEC) the 32-bit bitwise ops' result is the whole wave's mask, so SCC is a subgroup vote (`OpGroupNonUniformAny`), as for the `_b64` forms. Until 2026-11-22 each lane took its own bit: `s_and_b32 s0, vcc_lo, exec_lo; s_cbranch_scc0` skipped the block in lanes whose bit was 0, and a loop closed by `s_andn2_b32 exec_lo, ...; s_cbranch_scc1` let each lane leave early. Found and checked by `tools/cf_diff.py` (FUZZ-8, CPU differential against the ISA model); GPU test `runtime/test/shaders/ps_scc_mask32.asm` passes (s5 == 8 on 2,048 pixels, 192 of them with bit 0, and s5 == 7 on 2,048) on an NVIDIA RTX 4050 Laptop (Linux, driver 620.73.04, natively and under `LEONIDA_W64_EMULATE=1`) and an AMD Radeon 740M (RADV, Mesa 26.3.1), and on an RTX 2060 SUPER per #634. A 32-bit op on one half of a wave64 mask still takes the lane's bit (its SCC would be a vote of that half). | -| Chained scalar constant folding (PERF) | Multi-step constant calculations on SGPRs (`s_mov_b32`, `s_lshl_b32`, `s_lshr_b32`, `s_mul_i32`, `s_add_u32`, `s_sub_u32`, `s_lshl1..4_add_u32`, `s_bfe_u32/i32`, `s_min/max_u32/i32`, `s_andn2/orn2/nand/nor/xnor_b32`, `s_abs_i32`, `s_absdiff_i32`, `s_sext_i32_i8/i16`, `s_pack_*_b32_b16`, `s_bfm_b32`) fold completely at translation time and record folded literal values in `self.sgpr_imm`, allowing downstream instructions within the basic block to propagate constants. `s_buffer_load` offset expressions computed via constant SALU fold statically into 64-bit addresses, and in-bounds reads eliminate runtime bounds check branches and Phi nodes. `s_bfe` with constant control words emits static offset/width operands directly. Checked by `tests/semantic/test_salu_chained_const_prop.py` and `tests/semantic/test_scalar_alu_and_smem_folding.py`. | -| Far branches | `s_getpc_b64; s_add_u32 K; s_addc_u32 0/−1; s_setpc_b64` on the same pair is a branch beyond `s_branch`'s ±32K-dword range. It's folded into one branch to (address after `s_getpc`) + K before CFG construction. The `s_sub_u32 K; s_subb_u32 0` form is the backward jump (a loop back-edge), as is `s_add_u32 -K; s_addc_u32 -1`. K is a byte distance, so the fold needs the instructions' `; encoding:` bytes; a listing without them is `Unsupported` ("without encoding"), not a crash. GPU-checked by `ps_far_branch.asm` (two forward jumps, a `sub`/`subb` loop, an `add`/`addc -1` loop and a conditional one run twice, K and the expected words derived by hand; RTX 5080 and Radeon gfx1036, 4096/4096 exact), CPU side `tests/semantic/test_far_branch.py`. | -| No-op SOPP/SMEM (`s_icache_inv`, `s_ttracedata`, `s_ttracedata_imm`, `s_code_end`, `s_version`, `ds_nop`, `v_clrexcp`) | Instruction-cache invalidate, thread-trace data, end-of-code padding, the ISA version marker and the DS no-operation have no register, memory, SCC, VCC or EXEC effect, so they are in `NOOPS` with `s_nop` / `v_nop` / `v_pipeflush`. `v_clrexcp` clears the TRAPSTS exception bits, which nothing translated reads (`s_getreg_b32` is unsupported and there are no traps), so it is a no-op too (since 2026-11-22; before, both it and `ds_nop` raised `Unsupported`). The data-cache invalidations (`buffer_gl0_inv`, `buffer_gl1_inv`, `s_dcache_inv`, `s_gl1_inv`) concern coherence between waves and stay `Unsupported`. Source: RDNA2 ISA SOPP/SOPK/SMEM/DS/VOP1. CPU-checked by `tests/semantic/test_sopp_noops.py` (values, SCC and VCC survive; the data-cache invalidations are still rejected). | -| Buffer format stores | `buffer_store_format_*` and `_d16_*` encode every format the loads decode (the same FORMATS table: f32/u32, f16, unorm/snorm 8/16/10-10-10-2, uint/sint 8/16, and the formats of the *Typed buffer formats* row). 1–2-byte elements are merged into their dword with atomic and/or so neighbours are kept. The atomics use element 0 of the array at the aligned dword address, which also compiles on MoltenVK 1.4.0 (checked with `cs_store` on an Apple M3 Max and Mesa llvmpipe). d16 data is unpacked first (f16 → float for float kinds, 16-bit integers for integer kinds). Before this, only four f32 formats, rgba16f and rgba8 unorm were stored, and everything else silently stored nothing. GPU-checked with `runtime/test/shaders/cs_store.asm` (rgba8 unorm, R10G10B10A2 (`2_10_10_10`), two r16f halves of one dword, d16 rgba16f: exact, neighbours untouched). `buffer_load_format_d16_*` packs pairs the same way. UNORM/SNORM stores convert NaN to zero before clamping. On native gfx1036, `buffer_store_format_d16_xyzw` into RGBA8_UNORM/SNORM matched clamp, scale by 255/127 and round to nearest even for all 63,488 finite binary16 encodings. Both infinities saturated and all 2,046 NaNs stored zero in both wave32 and wave64. The translated sweep matched all 65,536 bytes per format on RTX 5080 and Radeon Graphics. For normalized stores with format 56 (8/8/8/8) or 50 (10/10/10/2), a Z,Y,X,W descriptor exchanges the red and blue memory fields after filling absent input components with zero. Native gfx1036 confirmed both channel orders at all four instruction widths for packed and ordinary stores in wave32 and wave64. A store with fewer components than its format writes the whole element, with 0 for the components it doesn't give (`_xy` into 32_32_32_32 leaves z = w = 0, `_xyz` into 16_16_16_16 leaves w = 0); into a one-channel format only x is written. Measured natively on a Radeon 680M (gfx1035, RDNA2), and GPU-checked by `cs_fmt_xy_xyz.asm` for 32_32_32_32, 16_16_16_16, 8_8_8_8 UNORM and UINT and 32 (TEST-185). Unsigned integer stores saturate to the destination channel width. On native gfx1036, RGBA8_UINT, RG16_UINT and RGBA16_UINT clipped overflowing inputs to 255 or 65535, with RGBA32_UINT as a full-width control. For normalized stores with format 56 (8/8/8/8) or 50 (10/10/10/2), a Z,Y,X,W descriptor exchanges the red and blue memory fields after filling absent input components with zero; native gfx1036 confirmed both channel orders at all four instruction widths for packed and ordinary stores in wave32 and wave64. `tbuffer_store_format_*` is not translated. 8- and 16-bit SINT stores clamp the signed 32-bit value to [-2^(w-1), 2^(w-1) - 1] (300 stores 127 into 8_SINT, -129 stores -128), and the 8/16-bit UINT formats 5, 11 and 18 saturate like the others; measured natively on gfx1036 for x, xy, xyzw and d16_xyzw stores (a d16 half is read as a signed 16-bit integer for SINT, so 0xff80 stores -128) with the runtime's selectors (X001, XY01, XYZW) and checked by `tests/semantic/test_buffer_format_narrow_int.py` (until 2026-11-22 those formats stored nothing). `tbuffer_store_format_*` and its `_d16_*` forms take the instruction's format instead of the V#'s, as the tbuffer loads do: only that format is encoded, and its element size decides the bounds check (an 8_UNORM byte is stored where the V#'s 16-byte element would not fit; a 16-byte element is dropped where the V#'s 4-byte one would fit). A V# whose FORMAT is 0 (INVALID) still disables the store. No `format:` modifier is GFX10's default, BUF_FMT_8_UNORM; a format FORMATS has no encoder for stays `Unsupported`. Measured natively on a Radeon 680M (gfx1035, wave32 = wave64) and GPU-checked by `cs_tbuffer_store.asm` (13 stores: f32, f16, 8_8_8_8 UINT and UNORM, 2_10_10_10, d16, the default format, more and fewer components than the format has, both bounds cases, a V# with FORMAT 0; exact on an RTX 3050 and the 680M); CPU-checked by `tests/semantic/test_tbuffer_store.py`. | -| Typed buffer formats | `Gen.FORMATS` holds all 77 GFX10 codes a V# or MTBUF can carry (a buffer's `FORMAT` is 7 bits; codes from 128 are image-only, and there are no 5_6_5, 1_5_5_5, 5_5_5_1 or 4_4_4_4 buffer formats): the 8/16-bit UINT, SINT, USCALED and SSCALED families (USCALED/SSCALED: the integer converted to float, not divided), 10_11_11 and 11_11_10 in all seven numeric formats (the FLOAT ones are unsigned floats: 5 exponent bits, bias 15, 6 or 5 mantissa bits, no sign; the first number is the top field, so 36 has x in bits 10:0 and a 10-bit z on top), and the 10_10_10_2 (44–49) and 2_10_10_10 (50–55) families. Codes outside the table decode to 0 and store nothing. **Stores**: UINT and SINT saturate; UNORM and SNORM round the exact product once (`Gen.encode_norm_bits`: 0.3 · 65535 stores 19661; nearest even, but a half rounds away from zero in a 2-bit SNORM field); a SCALED store converts as the matching NORM format; float stores (16_FLOAT and the small floats) **round toward zero, saturate to the largest finite value (65504), keep a NaN a NaN and give 0 for a negative number in an unsigned float** (`Gen.ufloat_encode_bits`); **a two-component format stored through a V# takes channel y as its second component when DST_SEL_Y is Y and DST_SEL_Z a constant (the runtime's X,Y,0,1), channel w otherwise (identity XYZW: `_xy` writes (x, 0))**, and `tbuffer_store_format_*` takes (x, y) whatever the V# says. The typed-store encode is emitted once per module (`Gen.format_encode_call`: one encode function and one element-size function, each store site a call, like the shared decode), because inlined every site carried every format. **How confirmed**: `tools/buffer_format_fuzz.py --oracle hw` runs raw `buffer_load_format_xyzw` / `buffer_store_format_xyzw` / `_xy` / `tbuffer_*_format_*` kernels and compares every result word with a CPU model (a distinct value in every register). **Radeon 880M (gfx1150, RDNA3.5; GFX11 numbers its formats differently, so formats are mapped by name)**: 1,390,400 elements over the 63 formats GFX11 has, 0 mismatches. **Real RDNA2, gfx1036, by @AwkGrep256 on the Linux DRM backend ([#2022](https://github.com/ItsNotRexed/Leonida/pull/2022))**: the same totals, 1,330,469 validated and 26,523 elements of the (x, w) routing, 0 mismatches, and 199,144 elements of the 14 codes GFX11 lacks (10_11_11 and 11_11_10 non-FLOAT, 10_10_10_2 USCALED/SSCALED), 0 mismatches. Per-format counts in [buffer_formats.md](buffer_formats.md); `--negative-control` catches a wrong V# format on all but one or two elements. The translated SPIR-V is held to the same model by `tests/semantic/test_buffer_formats_all.py` (every added format, loads through the V# and tbuffer, stores, every older format's store, hand-worked values) and by the GPU test `cs_fmt_all.asm` (32 loads and 20 stores, on an AMD Radeon 880M and an NVIDIA RTX 5070); `cs_store`, `cs_fmt_*`, `cs_oob_*` and `cs_tbuffer_store` pass on both too. Three older stores used to differ from the hardware (f16 format stores rounded to nearest and overflowed to infinity, NORM stores rounded an f32 product twice, a two-component V# store always took (x, y)) and follow it now. **Unmeasured**: the console's gfx1013, d16 forms of the new kinds and of the (x, w) routing, `_xyz` into a two-component format, selector sets that reorder channels. | -| No-op SOPP/SMEM (`s_icache_inv`, `s_ttracedata`, `s_ttracedata_imm`, `s_code_end`, `s_version`, `ds_nop`, `v_clrexcp`, `s_atc_probe`, `s_atc_probe_buffer`) | Instruction-cache invalidate, thread-trace data, end-of-code padding, the ISA version marker and the DS no-operation have no register, memory, SCC, VCC or EXEC effect, so they are in `NOOPS` with `s_nop` / `v_nop` / `v_pipeflush`. `v_clrexcp` clears the TRAPSTS exception bits, which nothing translated reads (`s_getreg_b32` is unsupported and there are no traps), so it is a no-op too (since 2026-11-22; before, both it and `ds_nop` raised `Unsupported`). `s_atc_probe` and `s_atc_probe_buffer` (SMEM) probe, that is prefetch, an address in the address translation cache: no data comes back and nothing is written, so they are no-ops too (since 2026-11-22). The data-cache invalidations (`buffer_gl0_inv`, `buffer_gl1_inv`, `s_dcache_inv`, `s_gl1_inv`) concern coherence between waves and stay `Unsupported`. Source: RDNA2 ISA SOPP/SOPK/SMEM/DS/VOP1. CPU-checked by `tests/semantic/test_sopp_noops.py` (values, SCC and VCC survive; the data-cache invalidations are still rejected). | -| No-op SOPP/SMEM (`s_icache_inv`, `s_ttracedata`, `s_ttracedata_imm`, `s_code_end`, `s_version`, `ds_nop`, `v_clrexcp`, `s_atc_probe`, `s_atc_probe_buffer`, `s_incperflevel`, `s_decperflevel`, `s_wakeup`) | Instruction-cache invalidate, thread-trace data, end-of-code padding, the ISA version marker and the DS no-operation have no register, memory, SCC, VCC or EXEC effect, so they are in `NOOPS` with `s_nop` / `v_nop` / `v_pipeflush`. `v_clrexcp` clears the TRAPSTS exception bits, which nothing translated reads (`s_getreg_b32` is unsupported and there are no traps), so it is a no-op too (since 2026-11-22; before, both it and `ds_nop` raised `Unsupported`). `s_atc_probe` and `s_atc_probe_buffer` (SMEM) probe, that is prefetch, an address in the address translation cache: no data comes back and nothing is written, so they are no-ops too (since 2026-11-22). `s_incperflevel` and `s_decperflevel` increment or decrement a performance counter (RDNA2 ISA SOPP, SIMM16[3:0]) and `s_wakeup` pings the other waves of the threadgroup out of an `s_sleep`, which is itself a no-op here; none writes a register, memory, SCC, VCC or EXEC, so they are no-ops too (since 2026-11-22). The data-cache invalidations (`buffer_gl0_inv`, `buffer_gl1_inv`, `s_dcache_inv`, `s_gl1_inv`) concern coherence between waves and stay `Unsupported`. Source: RDNA2 ISA SOPP/SOPK/SMEM/DS/VOP1. CPU-checked by `tests/semantic/test_sopp_noops.py` (values, SCC and VCC survive; the data-cache invalidations are still rejected). | -| Two-byte typed buffer load alignment | On gfx1036, MUBUF and MTBUF two-byte format loads at an odd effective byte address give zero for a fetched channel. A constant-one descriptor selector still gives one. Native wave32 and wave64 tests on AMD Radeon Graphics (Windows driver 32.0.21042.62) compared aligned and odd loads for every two-byte format (codes 7–19). Moving the base by one byte reversed which offsets returned data for 16_UINT. Regression fixture: `tests/semantic/fixtures/typed_load_alignment.asm`. | -| Buffer format store rounding and 2-component `DST_SEL` (SHADER-364) | UNORM/SNORM stores (`Gen.encode_norm_bits`) round the exact product `clamp(x) * scale` once in 64-bit integer arithmetic with ties away from zero, instead of double-rounding through `OpFMul` + `RoundEven` (`UNORM16(0.3)` stores 19661, not 19660; `SNORM2(±0.5)` stores ±1). MUBUF `buffer_store_format_*` (and `_d16_*`) into 2-component formats infer `COMP_SWAP` from V# `DST_SEL_X/Y/Z`: `use_y = (sy >= 4) and (sz < 4)`, `rev = (sx != 4) and (sy >= 4 or sz >= 4)` (`XY01` → `(x, y)`, `YX01` → `(y, x)`, `XYZW` → `(x, w)` so `_xy` writes `(x, 0)`, `YXZW`/`ZYXW` → `(w, x)`); MTBUF `tbuffer_store_format_*` ignores `DST_SEL` and always stores `(x, y)`. Measured natively on RDNA2 (`gfx1036`, AMD Ryzen 7 9800X3D iGPU, Linux AMDGPU DRM via `tools/hw_oracle`, wave32 and wave64) with `tools/buffer_store_probe.py`: 0 mismatches across 5 UNORM/SNORM formats (2,474 inputs × MUBUF/MTBUF × wave32/64 = 9,896 runs) + SNORM2 ties, all 12 2-component formats (`XY01` vs `XYZW`), and all 216 `(sx, sy, sz)` triples on `32_32_UINT`. Checked on CPU + `spirv-val` by `tests/semantic/test_buffer_store_rdna2.py` and `tests/test_buffer_store_probe.py`. | -| `_d16_hi_` typed buffer forms (SHADER-755) | Only the single-component forms are instructions. `buffer_load_format_d16_hi_x` and `buffer_store_format_d16_hi_x` are the `_x` forms of the d16 load and store with their one component in bits 31:16 instead of 15:0; #1885 (SHADER-320) adds them. The multi-component spellings (`buffer_load_format_d16_hi_xy`, `_xyz`, `_xyzw`, and `buffer_store_format_d16_hi_*`) name no RDNA instruction and stay `Unsupported`: AMD's machine-readable [RDNA1 and RDNA2 ISA XML](isa_coverage.md) lists `BUFFER_LOAD_FORMAT_D16_HI_X` and `BUFFER_STORE_FORMAT_D16_HI_X` (MUBUF opcodes 0x026 and 0x027) as the only format D16 high-half instructions, and the packed widths `BUFFER_*_FORMAT_D16_X` to `_XYZW` (0x080-0x087) have no high-half counterpart; LLVM's gfx10 to gfx12 MUBUF tables define the same two, and the console's gfx1013 decodes through the gfx10 table, so no listing can carry one (the 25,735-shader corpus has none, reported in #4084). CPU-checked by `tests/semantic/test_buffer_format_d16_hi_absent.py`: every multi-component spelling raises `Unsupported`, and the packed forms translate as a control. | -| `s_lshl1..4_add_u32` | D = (S0 << N) + S1. SCC = the sum taken in 64 bits is ≥ 2³², so a bit shifted out of S0 sets it as well as a carry out of the add (RDNA ISA pseudocode: `tmp = (64'U(S0) << N) + 64'U(S1)`). Checked on the CPU by `tests/semantic/test_salu_lshl_add.py`. **Hardware-verified** on the same gfx1100 part through `tools/hw_oracle`: `s_lshl1_add_u32(0x80000000, 0)` = 0 with SCC = 1 (the bit shifted out of S0 sets it, with no carry out of the add), `s_lshl2_add_u32(5, 3)` = 0x17 with SCC = 0, `s_lshl4_add_u32(1, 0)` = 0x10. Also verified on native RDNA2 (gfx1036, AMD Radeon Graphics): 500 programs in `tools/salu_diff.py` (`--oracle translator,hw`) matched bit-for-bit with 0 mismatches across shift amounts 1–4, confirming that bits shifted out of S0 set SCC as well as sum overflow. | -| Other additions | `image_gather4_l(_o)`: no explicit-LOD gather in core Vulkan, so four `OpImageFetch` at the mip the "Gather sampler LOD" row chooses, in gather order. `image_gather4_l(_o)`: no explicit-LOD gather in core Vulkan, so four `OpImageFetch` at mip `Floor(clamp(LOD, S# MIN_LOD, MAX_LOD) + 0.5)` (ties up, as native) in gather order. With `d16` those four taps round to binary16 and pack low half first into two consecutive VGPRs. The packed words and the first untouched VGPR were checked with `ps_gather_wrap.asm` on RTX 5080 and Radeon Graphics. Each of the four texel coordinates goes through the S#'s own address mode, read from S# word0 (`CLAMP_X` = bits [2:0], `CLAMP_Y` = [5:3]; fields from Mesa `src/amd/registers/gfx10-rsrc.json`, values `SQ_TEX_*` in Mesa `gfx6.json`, matching RADV's `radv_tex_wrap` mapping of Vulkan address modes): 0 wrap (`c mod n`), 1 mirror (`c mod 2n`, reflected), 2 clamp to the last texel, 3 mirror-once (`-1-c` for negative `c`, then clamped), as in Vulkan's address-mode definitions. The modulo is `OpSRem` plus the period when the remainder is negative, not `OpSMod`. On a Ryzen 5 7600's iGPU (RDNA2) with AMD's Windows driver 24.10.24, `OpSMod` of a negative coordinate came out with the dividend's sign: the three `ps_gather_wrap` cases whose wrap or mirror coordinate is negative (1, 2 and 6) fetched outside the image and read zeros, while the same module passed on an RTX 4070 SUPER. With `OpSRem` and the fix-up, all 4096 pixels are exact on both. A literal S# (`s_mov_b32` earlier in the block) is decoded at translation time; otherwise the mode is read from the SGPR at run time. Modes 6 (clamp border) and 7 (mirror once border) give a tap whose coordinate, before the clamp, is outside [0, n-1] on either axis the S# border colour's channel instead of the fetched texel: BORDER_COLOR_TYPE = word 3 [31:30] (Mesa `gfx10-rsrc.json` `SQ_IMG_SAMP_WORD3`, `SQ_TEX_BORDER_COLOR_*` in `gfx6.json`), 0 transparent black, 1 opaque black (alpha 1), 2 opaque white; 1 for an integer format, as Vulkan's `INT_OPAQUE_*`. Type 3 (a colour from the border-colour table, `BORDER_COLOR_PTR`) is `Unsupported` on a literal S# and transparent black at run time (SHADER-348: since #1567 made the game's S# words literals, 16 of the corpus's mode-6 gathers failed as `Unsupported`; before that they ran as clamp-to-edge). A literal S# with a half-border mode (4, 5) or `FORCE_UNNORMALIZED` is `Unsupported`; a run-time S# can't be judged, so modes 4 and 5 act as clamp-to-edge there and `FORCE_UNNORMALIZED` (word0 bit 15) is not applied (coordinates are still scaled by the image size). Those two, and a table border colour (BORDER_COLOR_TYPE 3) on a run-time S#, which gives transparent black, are the remaining approximations; the unnormalized rules (texel-unit coordinates, mip 0) weren't confirmed on hardware, so they were not guessed. GPU-checked with `runtime/test/shaders/ps_gather_wrap.asm` (`vk_texture_test`; expected values derived by hand in its header; six border cases, three literal and three run-time S#) on AMD (Radeon 880M, wave64) and NVIDIA RTX 5070; the border modes with `runtime/test/shaders/ps_gather_border.asm` (two literal and two run-time S#s, opaque white and transparent black, modes 6 and 7) on NVIDIA RTX 4070 SUPER (driver 621.01), with `tests/test_translate.py`'s `test_gather4_l_*border*`. `image_gather4_lz_o`: `OpImageGather … Offset`. `image_store` on 1D (bindings 17–19, `Image1D`) and with a16 coordinates. `ds_swizzle BITMASK_PERM` ("pippi" masks; GPU-checked). `v_add_f64`, `v_cvt_f32_f64` (`Float64`). `v_mul/mad_i32_i24`, `v_alignbyte_b32`, `v_xnor_b32`, `v_ffbh_i32`, `v_swap_b32`, `s_abs_i32`, `s_bfm_b32/b64`, 64-bit ordered and `v_cmpx` compares, 16-bit compares, 8/16-bit global loads, `neg(…)` constant operands (GPU-checked where listed in `runtime/test/shaders`). | -| `v_mad_u64_u32`, `v_mad_i64_i32` | {sdst, D} = S0 × S1 + S2 as a 65-bit result (RDNA ISA pseudocode), the product unsigned or signed. sdst (a lane mask) gets bit 64 for active lanes and 0 for lanes off in EXEC (`EXEC[lane] ? bit64 : 0`, matching `v_cmp_*` and `*_co_*`): the carry out for u64, and for i64 the sign of the exact sum (bit 64 of a 65-bit two's-complement value), not a signed-overflow flag. `tools/lane_masks.py` tracks sdst as a lane mask (until 2026-11-22 it only matched `*_co_*`, so `s_bcnt1`/`s_ff1`/`v_mbcnt` on sdst read each lane's own mask word as plain data). `clamp` is rejected. Checked on the CPU by `tests/test_lane_masks.py`, `tests/semantic/test_alu_mad64.py` (including 64-lane `s_bcnt1_i32_b64`/`s_ff1_i32_b64` ballot tests), and `tests/semantic/test_carry_exec_mask.py` (EXEC masking on inactive lanes). **Hardware-verified on RDNA2** (AMD Radeon 680M, `gfx1035`, wave32 and wave64 via `tools/int_hw_probe.py --oracle both`, SHADER-137): unsigned carry, signed positive overflow `(-2³¹)² + INT64_MAX` giving `sdst = 0`, negative sum giving `sdst = 1`, and inactive EXEC lane leaving D untouched with `sdst = 0` all match bit-for-bit. | -| Ray tracing | `image_bvh_intersect_ray` / `image_bvh64_intersect_ray` (64 CS: RT shadows) are one traversal step against AMD's hardware BVH node format. The traversal loop lives in the game's shader. The step is emulated over buffer reads following Mesa RADV's software path (`radv_nir_rt_common.c`, `intersect_ray_amd_software_box/_tri`; node layouts from `bvh_defines.h`). Node id = address >> 3 \| type (0–3 triangle, 4 box16, 5 box32). Box nodes give the four child ids, with misses and NaN boxes = `0xFFFFFFFF`, sorted by entry distance when descriptor bit 63 (box_sort_enable) is set. **The box test is the native one, measured on RDNA2** (SHADER-650; RX 6900 XT, gfx1030, `tools/hw_oracle` raw kernels, 338 cases: BOX32 and BOX16, four rays including negative directions, NaN in every position, empty boxes, planes on the origin, and every tie order of four children; the translator now matches all 338 bit for bit, `main` before it 43, and all 811 rounding cases below): per axis, the near plane is min and the far plane max when the inverse direction (taken as given, not clamped) is ≥ 0, swapped otherwise; t = (plane − origin) × inverse direction, so `0 × inf` is NaN. **Both the subtraction and the multiply round toward zero** (811 more cases, 800 randomized slabs at origins 2^18 to 2^27 away plus 11 ties: round-to-nearest predicts 769 of them, round-toward-zero all 811; among the ties, a box with min.x = 1 > max.x = 0 at origin.x = −2^25 is a hit on hardware because both planes round to the same t). The translator emulates this exactly: the subtraction's error comes from TwoSum, the product's error sign from a Dekker split of the two mantissas scaled to [1, 2), and a result rounded away from zero steps one ulp back; a finite overflow gives ±FLT_MAX. tnear = max of the three near t, tfar = min of the three far t, **each skipping NaN**; all three near or all three far NaN is a miss. Hit when max(tnear, 0) ≤ tfar and tnear < extent (the extent boundary itself was not measured). So a lone NaN bound leaves its own plane open (a box with min.x = NaN is hit wherever x ≤ max.x), an empty box (min > max on any axis, ±inf or ±65504 included) is a miss without a separate check, and a plane exactly on the origin along a zero-direction axis is open. The sort key is max(tnear, 0), so boxes around the origin tie at 0, ordered by the network (0,2) (1,3) (0,1) (2,3) (1,2) with a strict `<` swap (all 88 measured tie orders). `tests/semantic/test_image_bvh_box_hw.py` holds measured words. Triangle nodes read their three vertices from the slots the node type picks: TRI0 (0,1,2), TRI1 (1,3,2), TRI2 (2,3,4), TRI3 (2,4,0), 12 bytes each. They use the watertight test with RADV's shared edge/vertex tie-breaks and give (t/\|det\|, sign(det), b_i/\|det\|, b_j/\|det\|), or (inf, 1, 0, 0) on a miss. The weights i and j are chosen by the node type's byte of the triangle-ID word at +60: bits [1:0] and [3:2], 0/1/2 = vertex 0/1/2 and 3 = vertex 0, bits [7:4] ignored; `0x09` gives RADV's (v, w). Vertex slots and remap follow AMD GPURT (`CalcTriangleCompressionVertexIndices`, `SwizzleBarycentrics`) and the public XDXR software path ([bvh.md](bvh.md) §7a), and the hardware agrees. **The triangle step is the native one, measured on RDNA2** (AMD Radeon RX 6800, gfx1030, AMD Windows driver 26.11.2, Windows 11, 2026-11-22; the `tools/hw_oracle` kernels `tools/bvh_tri_probe.py` builds, hand-built nodes and rays: 14 kernels, 308 single-lane cases and 7 cases on 64 lanes, 1,204 results, each in both forms; the 32-bit form with the descriptor base at the node and the 64-bit form with base 0, wave32 and wave64, NSA and contiguous operands all gave the same words). A NaN anywhere in t max, the origin, the direction or the inverse direction, or an infinite origin, returns (+inf, 1.0, +0, +0). Otherwise the watertight test runs with its shear taken from the direction (kz = the axis of the largest \|d\|, ties x, y, z; kx and ky swapped when d[kz] < 0; Sz = 1/d[kz]): **the supplied inverse direction is not used**. With the edge functions U, V, W, det = U + V + W, T = t·det and k = \|d[kz]\|³, a hit returns (k·T, k·det, k·b_i, k·b_j) and a miss (copysign(inf, k·det), k·det, k·b_i, k·b_j): numerators over the denominator k·det, and a miss keeps the plane's barycentric numerators. det = 0 is a miss with word 0 = +inf. The hit needs t ≥ 0 (t = 0 hits); there is no test against t max. Every zero word is +0 and every NaN word 0xFFC00000, so a NaN det gives word 0 = −inf. An edge function of 0 is inside when its edge passes RDNA2's tie rule, which is not RADV's: the edge from P to Q (U: B→C, V: C→A, W: A→B), with (tx, ty) = Q′ − P′ in the sheared frame with the d[kz] < 0 swap of kx and ky undone, passes when ty = 0 ? sign(det)·tx > 0 : sign(d[kz])·sign(det)·ty > 0, and every zero edge must pass. Every shared edge and shared vertex gave exactly one hit. How this rule was found: the first fit (ty = 0 ? tx < 0 : sign(det)·ty > 0, on the 49 tie rows of the first measurement, all z dominant) was confounded, because every one of those rows had det < 0 with d[kz] > 0 or det > 0 with d[kz] < 0, and it was wrong in the cells it never saw. A second measurement (2026-11-23, same part and driver; 8 more kernels, 256 rows: ties with x, y and z dominant, both windings, both signs of d[kz], every edge direction class in each of those cells, tilted triangles with oblique rays, equal \|d\| components) fitted none of the eight rules registered before it ran. The rule above was then read off its x/y rows (post hoc), and it predicted the z-dominant bridge kernel `tri_t8` before that ran: 32 of 32 cases, 10 of them rows where it and the first fit disagree. The translator computes these words without a division, with the shear multiplied through by \|d[kz]\| (a shear divided by d[kz] gives the same words on every measured row but d.z = +inf, and divides by zero at d = 0; this form gives d = 0 → (+inf, 0, 0, 0) and d.z = +inf → (−inf, NaN, −inf, −inf) as measured, a fit after the runs), and fixes zero signs and NaN bits with integer selects, so every measured input is defined SPIR-V. `tests/semantic/test_image_bvh_tri_hw.py` asserts all 308 rows and 84 lane results of the first measurement and the 256 rows of the second bit for bit (the translator before it: 129 of the first 308; the first fit: 210 of the 256); `tests/semantic/test_image_bvh_tri.py` runs every node type and remap byte on the interpreter. **A consumer that divides by word 1** (t = w0/w1, weights w2/w1 and w3/w1) gets t and the weights on a hit (k cancels; word 1 keeps det's sign); +inf for t on a miss of either winding, with the plane's weights; t = +inf/+0 = +inf and weights 0/0 on a zero-area triangle; t = NaN with a NaN or inf vertex, so a `t < t max` test fails as on a miss; t = +inf with a NaN in the ray or an infinite origin. It must compare t with t max itself. The translator's earlier normalised words (t/\|det\|, sign(det), b_i/\|det\|, b_j/\|det\|; a miss (inf, 1, 0, 0)) gave such a consumer the same t on every row and the same weights on every hit except on 14 shared-edge rows (RADV's tie rule), 3 rows whose inverse direction is not 1/d, 3 rows with a NaN in the ray (it reported a hit or other words), the v0.x = −inf and d.z = +inf rows, and 14 rows that were undefined SPIR-V there (zero area, a NaN or inf vertex, a NaN, inf or zero ray). **Not measured:** gfx1013 (the console); node types 6 and 7; the box extent boundary; descriptor words other than w2 = 0xFFFFFFFF, w3 = 0x81000000 (return mode 0 included); the dominant axis on equal \|d\| components except where a measured tie row tells the axes apart: x for \|dx\| = \|dy\| > \|dz\| (only with dx, dy > 0), x for \|dx\| = \|dz\| > \|dy\| (not with dx > 0 > dz), y for \|dy\| = \|dz\| > \|dx\| (only with dy, dz of the same sign) and x with all three equal (in the four of the eight sign patterns that ran), which is the translator's `>=` order (a non-tie row gives the same words whatever the choice, and every sign pattern could show it with the right tie); rounding-sensitive inputs (every input is dyadic, so the divided versus multiplied-through shear and fused versus separate rounding are not told apart); d = 0 and infinite d beyond one row each; the remap's high nibble on TRI1–TRI3. These two references agree; one real pack BLAS is now matched, rehydrated and traversed (§7b), though the rule has not been counted over the whole corpus. The triangle rule has not been measured on the native instruction yet: `tools/hw_oracle` can run it on RDNA2, and box32 nodes were measured that way (gfx1036, address = base × 256 + (node & ~7) × 8 in both instruction widths, §7b), so the triangle counterpart is a possible follow-up rather than an impossibility. These two references agree; no game BVH is decoded yet to count over. The triangle rule has not been run natively yet; the box rule above has (`tools/hw_oracle` on an AMD RDNA2 card runs the instruction itself). `tests/semantic/test_image_bvh_tri.py` runs every node type and remap byte on the interpreter, including the descriptor-base case. The game's code divides by `.y` exactly as for the hardware's numerator/denominator. Address = descriptor base + ((node & ~7) << 3). The descriptor's dword0 is the base in 256-byte units: the game passes `ptr >> 8` there, and the `\| 0x30` its shader ORs is only the temporary address it uses to load `rootNodePtr`, not the descriptor base. Measured at base 0 and at base 0x1000 (structure at VA 0x1000, dword0 `0x10`): the GPU returns the CPU walker's children in the same order at both, so the `<< 8` is correct and a nonzero base needs no masking. `tests/semantic/test_image_bvh_tri.py` runs the nonzero base (`0x10` → `0x1000`). Address = descriptor base + ((node & ~7) << 3), base = descriptor bits [39:0] in 256-byte units (measured on gfx1030: the 32-bit form with a non-zero base and the 64-bit form with base 0 and the full address gave the same words in 71 cases). **The runtime must build the game's acceleration structures in this AMD node format** (RADV's GPU BVH builder produces it) wherever the game's D3D12 calls build them. Far branches with `s_sub_u32`/`s_subb_u32` (backward) are folded too. GPU-checked with `runtime/test/shaders/cs_bvh.asm`: sorted box children and the triangle result are exact; its box with a NaN min.x is entered at t = 0 and sorts first (`0x68 0x48 0x40 0xffffffff`), as native gfx1030 returns for that scene. The 32-bit form (11 address dwords: the node id has no high dword) runs the same scene in `cs_bvh32.asm` and gives the same eight words. Corpus counts (`tools/image_bvh_census.py`, static, [bvh.md](bvh.md) §7): 716 sites, 638 32-bit and 78 64-bit; the descriptor has box_sort_en 1, big_page 1, size all ones and type 8 at every site; on every path from the call, 397 sites take `v_rcp_f32` of word 1, multiply word 0 (335 also words 2 and 3) by it and read `sext(w1[31:16])`, all 716 read the words as integers (397 through shifts and `v_and_or_b32`/`v_lshl_or_b32`/`v_or3_b32`, 319 through `v_cmp_eq_u32` only), and none reads a word undivided as a float; 633 sites also have reads on some paths only, which the census leaves unclassified. | -| Coverage | Every shader in the corpus translates. The remaining fidelity gap is wave64 cross-half code on 32-wide subgroups in VS/PS/GS (tier C of the *Wave64 graphics* row; tiers A and B are exact); compute and mesh shaders are exact there with `--wave64-emulate` (see the wave-size and wave64 rows). | -| Flat pixel inputs | A pixel input location read only by `v_interp_mov_f32` with the p0 select is declared `Flat` (a location a p10/p20 mov reads is `PerVertexKHR`, next row). A pixel input location read only by `v_interp_mov_f32` is declared `Flat`. Locations read with `v_interp_p1/p2` remain interpolated. The `ps_flat` GPU test passes integer IDs through the first vertex alongside interpolated UVs. On the CPU, `test_v_interp_mov_emits_flat_decoration` and `test_attribute_read_both_flat_and_interpolated_is_not_flat` in `tests/semantic/test_interp_mov_flat.py` check the Flat decoration of a p0-only location and that a location also read with p1/p2 is not decorated Flat. | -| v_interp operand guards (SHADER-177) | The single-lane model reads the attribute's own value for `v_interp_p1/p2`, which is only right when the VGPR source really holds the barycentric coordinate that op interpolates with — **p1 reads I = v0 and p2 reads J = v1, per op** — and `v_interp_mov_f32` p0 is the provoking vertex (p10/p20 are the deltas of the vertex-delta row above). A p1/p2 (f32 and f16 forms) whose source is not its own coordinate — v0 for p1, v1 for p2, each either the hardware register or a plain `v_mov_b32` copy rooted at it (the copy's single write in the whole shader, defined before the use, copy chains followed, and its source v0/v1 itself unwritten up to the copy: a copy of an already-overwritten v0/v1 carries a computed value — zeroing the source before copying renders (0,0) on hardware — while a write after the copy is fine, the copy saved the value) — is **Unsupported**, naming the register and the role, so a swapped p1(v1)/p2(v0) pair, a both-v0 pair, or a copy of an overwritten source is refused rather than silently mistranslated; `v_interp_mov_f32` with p10/p20 was **Unsupported** until the vertex-delta row above; any other select still is, naming it. `v_interp_mov_f32` with p10/p20 is **Unsupported**, naming the select. A **direct** v0/v1 read stays accepted even when the shader overwrites v0/v1 first (evaluate-at-offset/snapped barycentrics; up to 213 PS, #1218): modelling that computed value is the separate provenance follow-up. Zero corpus cost: over the 26,503-shader corpus every f32 I/J source is v0/v1 (117,001 / 116,997) except one PS whose four `v_interp_p2_f32` read J through `v_mov_b32 v14, v1` (its v1 unwritten up to the copy; the later overwrites are the saved-copy case), which the copy rule keeps translating (bit-identical .spv), every f16 source is v0/v1 (58,950 / 58,950), and all 6,926 `v_interp_mov_f32` use p0. Confirmed by `tests/semantic/test_interp_guards.py` (refusals name the operand and its role, including swapped and both-v0 pairs, a wrong-root copy, and a copy of an overwritten source; the copy, copy-chain, matching-role and saved-from-later-zero cases translate and compute; a second write or a dpp copy no longer qualifies; a mutation check that the guard consults the copy analysis) and by re-translating a 200-shader corpus slice plus that PS before and after: translated/valid counts and every .spv unchanged. | -| Pixel-shader interpolants | When a sidecar `fssm/.fssm` holds a pixel-input table (`tools/fssm_header.py`: 8-byte records from 0x138 while the first byte is 6; table position = `v_interp attr` number), every position 0..count−1 is declared as a fragment input at that Location, including positions the code never reads (the table overcounts the code's distinct `v_interp` attrs in 775 of 12,101 PS: 300 by one, 475 by two or more; only the 10 records starting with kind 7 undercount). A 32-bit `v_interp` read (`p1/p2/mov`) of a 16-bit-flagged position (flag bit 4; **measured natively on RDNA2**, AMD Radeon 680M `gfx1035` in wave32 and wave64 via `tools/vinterp_hw_probe.py --oracle both`, SHADER-430: the VINTRP unit reads the same LDS parameter-cache dwords at `M0 + 48·attr + {8·c, 8·c + 4, 32 + 4·c}` with no hidden 16-bit unpacking, so `v_interp_mov_f32` returns the raw 32-bit parameter word and `v_interp_p1_f32`/`v_interp_p2_f32` interpolate those 32-bit words as binary32), and reads past the table still declare an input (the value is undefined on hardware). 11,199 such inputs corpus-wide, matching the `*_f16` interpolation opcodes in 99.7%) sees the value rounded to f16 (round to nearest, f16 denormals flushed to signed zero, back to f32) via a single `OpQuantizeToF16` (a `PackHalf2x16`/`UnpackHalf2x16` round-trip is folded to a no-op by at least one Vulkan driver, RTX 5080); reads through the `*_f16` opcodes already narrow and are unchanged (on a location an f16 op also reads, the f32 read is of the per-vertex raw word, "16-bit interpolation"; on gfx1036 a 32-bit `p1/p2_f32` read of a packed channel takes the raw LDS words as f32 bits, one fma each (SHADER-430, `tools/interp_hw_probe.py`); what P10/P20 words the SPI stores for such a channel is unverified), and reads past the table still declare an input (the value is undefined on hardware). Without a sidecar, or with an empty table, the output is byte-identical to the code-driven path. Confirmed by synthetic fixtures plus mini-interpreter agreement (`tests/test_rdna2spirv_pixelinput.py`: an f32 read of a flagged slot with input 1.1 yields the f16-rounded 1.099609375; unflagged and table-less controls yield exact 1.1) and `tests/test_vinterp_hw_probe.py`. The `index.json` entry records `ps_interpolants` (count) and `ps_fp16_interpolants` (flagged positions). | -| PS interpolation modes (SHADER-181) | Every interpolated generic pixel input in this build is **perspective-correct at the pixel center**, and every other input is flat, so the single v0/v1 pair the code reads is `PERSP_CENTER`. The translator models exactly these two: Flat for `v_interp_mov_f32`, plain (perspective, center) inputs and `BaryCoordKHR` for `v_interp_p1/p2` and the f16 forms. Two records describe each input, and they state **different facts**: PSV0 (DXBC) stores the interpolation **mode**; the FSSM input record's flags byte (byte 7) stores the **read method** — bit 0 (0x01) marks `v_interp_mov_f32` (4,600 records), bit 1 (0x02) 32-bit `v_interp_p1/p2` (51,191; values 0 and 3 never occur), bit 3 (0x08) a Float16-typed parameter (11,619), bit 4 (0x10) the `*_f16` opcodes (11,199; 24 f16-read records lack it). The flag/usage cross-table over all 55,791 records has no contradiction: every bit-0 position the code reads is read only by `v_interp_mov_f32` (4,295 positions), every bit-1 position only by `v_interp_p1/p2` or the f16 forms (49,594), and no position is read both ways (1,902 positions are unread, and 88 reads fall past the table). **The mode is in PSV0, not the FSSM**: `tools/ps_interp_modes.py` decodes it from the PSV0 signature elements (`DXIL::InterpolationMode`, "must match D3D_INTERPOLATION_MODE": 1 Constant, 2 Linear, 3 LinearCentroid, 4 LinearNoperspective, 5 LinearNoperspectiveCentroid, 6 LinearSample, 7 LinearNoperspectiveSample; the 16-byte elements carry row, cols, semantic kind, component type and the mode — layout in the Pixel-shader inputs section) and maps the modes onto the `SPI_PS_INPUT_ENA` barycentric-pair bits (Mesa `gfx103.json` register type SPI_PS_INPUT_ENA: PERSP_SAMPLE/CENTER/CENTROID = bits 0/1/2, LINEAR_SAMPLE/CENTER/CENTROID = bits 4/5/6; the same type serves `SPI_PS_INPUT_ADDR`). **No FSSM word stores ENA/ADDR**: every u16 in bytes 0x00–0x138 of all 12,101 PS was compared against the signature-reconstructed ENA and only constant coincidences matched, and the register addresses (0x286CC/0x286D0, or 0xA1B3/0xA1B4 as context-register indices) appear in no PS blob, so the v2.. position layout of "PS system inputs" (one enabled pair) is the only ENA witness. The #2735 packed-component census matched PSV0, FSSM and disassembly for all 12,101 indexed PS. Of 101,024 declared input rows, 77,245 have a nonzero read mask. Census (12,101 PS; 101,024 declared / 77,245 read inputs): every arbitrary, clip and cull input is Constant (6,333 rows, 4,529 read) or Linear = perspective-centre (81,385 rows, attributes plus 1,806 `SV_ClipDistance` and 2 `SV_CullDistance`); zero centroid, sample or noperspective generics; per shader 6,350 linear only, 4,507 linear and constant, 6 constant only, 1,238 no interpolated input. 101,024 declared / 76,215 read inputs): every arbitrary, clip and cull input is Constant (6,333 rows, 3,652 read) or Linear = perspective-centre (81,385 rows, attributes plus 1,806 `SV_ClipDistance` and 2 `SV_CullDistance`); zero centroid, sample or noperspective generics; per shader 6,350 linear only, 4,507 linear and constant, 6 constant only, 1,238 no interpolated input. ISG1 has no mode field, and the DXIL part carries no bitcode. SV_Position is mode 4 (11,295 rows) or mode 5 (27), both noperspective by the D3D rule. With packed-component read masks, the classifier assigns 10,260 shaders to the perspective-centre pair and 1,841 to no pair. None classify as linear-centre. Hardware delivery of SV_Position is outside the scope of the census. Front face is a system input (1,984 rows, 345 read, at most one per shader). It assigns none to a linear pair. This count measures input classification; it does not directly measure how the hardware delivers SV_Position; front face is a system input (1,984 rows, 345 read, at most one per shader). SV_Position is mode 4 (11,295 rows) or mode 5 (27) — noperspective by the D3D rule — and is delivered through the system VGPRs in every shader except **4**, which interpolate it through the parameter cache with the *linear* pair (`FragCoord` stays at the pixel center, which only differs at partly covered MSAA pixels); front face is a system input (1,984 rows, 345 read, at most one per shader). The code reads **at most one** barycentric pair per shader: v0/v1 in 10,259, none in 1,841, and one shader reads J from v14 (a copy of v1), so the perspective-centre assumption holds for every interpolated generic input. **Mode and read method disagree in thousands of rows** — the residual surface for modelling is: those 4 linear-pair position shaders, Constant rows read via `p1/p2` or `*_f16` (2,190 records at the matching table position; flat semantics in hardware, not modelled), and Linear rows read only by `v_interp_mov_f32` (3,197; already declared `Flat`). The translator's table check (`check_read_methods`, the row below) compares each read's opcode against the record's read-method bits (`fssm_header.read_methods`) — since the bits restate the read method, it rejects 0 of 12,101 PS: a consistency check between the two encodings of the read, not a mode check (a centroid/sample/noperspective input would still read `v_interp_p1/p2` and pass; that every interpolated generic input is perspective-centre is the PSV0 census result above, so keying a refusal on genuinely unmodelled modes means decoding PSV0, not reading these bits). Counted with `tools/ps_interp_modes.py` (stdlib; PSV0, FSSM and disassembly in one pass; #1301 removed the earlier #1246 census tool in favour of it) on the 1.0.2.1 corpus; tests `tests/test_ps_interp_modes.py`, `tests/test_fssm_header.py` and `tests/test_rdna2spirv_pixelinput.py` (synthetic). No GPU test: no shader needs centroid or sample interpolation. **Not covered:** bit 3 (0x08) is set in 11,619 records (all 11,199 16-bit ones, 396 flat, 24 linear). The 213 PS that overwrite v0/v1 before a `v_interp` (SHADER-178) compute their own barycentrics in code; PSV0 gives them no other mode. | -| `v_interp_mov_f32` p10 / p20 | The VINTRP mov returns one of the three values the hardware keeps per attribute for the p1/p2 pair, {P10, P20, P0}[S] (RDNA2 ISA, VINTRP; P = P0 + i·P10 + j·P20). p0 stays the provoking vertex (`Flat`, exact bits). p10 and p20 read the location `PerVertexKHR` (the per-vertex path the `*_f16` interps use, so the PS needs `fragmentShaderBarycentric`) and return P1 − P0 and P2 − P0 as one f32 `OpFSub` of the producer's words, vertices ordered as in the f16 row (BaryCoordKHR .y/.z weight vertices 1/2). Refused (`Unsupported`) under `--bary-fallback` and `--f16-interp-fallback` (no per-vertex inputs) and on a 16-bit-flagged interpolant (FSSM table), where whether the hardware forms the delta in f16 is unmeasured. Until 2026-11-22 both selects were refused; all 6,926 `v_interp_mov_f32` in the corpus use p0, so the corpus translation is unchanged. Confirmed on the CPU by `tests/semantic/test_interp_mov_delta.py` (distinct per-vertex words give the deltas, and P0 + i·P10 + j·P20 from the three movs matches the p1/p2 pair bit for bit). **Unverified:** a GPU run, and AMD's rounding of P10/P20 for denormal or NaN words. | -| PS `v_interp` read methods (SHADER-181, translator side) | Bits 0–1 of the FSSM input record's flags byte (byte 7; `fssm_header.read_methods`) give the **read method** of each table position: bit 0 (0x01) = read through `v_interp_mov_f32`, bit 1 (0x02) = read through `v_interp_p1/p2` or the f16 forms. They do not give the D3D interpolation mode, which is PSV0's (row "PS interpolation modes", `tools/ps_interp_modes.py`, #1256). Exactly one bit is set in every corpus record (bit 1 in 51,191, bit 0 in 4,600). In all 12,101 PS every bit-0 position the code reads is read only by `v_interp_mov_f32` (4,295 read positions), every bit-1 position only by `p1/p2` or the f16 forms (49,594), and no position is read both ways (1,902 positions are unread, and 88 reads fall past the table). The translator follows the read method, which is what the code does: `v_interp_mov` → `Flat`, `p1/p2` → a plain input (perspective, pixel center; `BaryCoordKHR` for raw i/j). That this one pair is perspective-center holds because PSV0 lists no centroid, sample or noperspective generic input, and the code reads one barycentric pair (#1256). Table positions don't pair one-to-one with PSV0 rows, since the table keeps only the inputs the compiled code uses, so a PSV0 row's mode and the record's read method can differ at a paired position; #1256 counts those cases. `rdna2spirv.check_read_methods` refuses a PS whose read position disagrees with its record's read method (`v_interp_mov` of a bit-1 position, `p1/p2`/f16 of a bit-0 one), or whose record has neither or both bits, instead of reading it as perspective-center. It refuses 0 of 12,101 PS, and shard 0/12 translates byte-identically to before the check. `index.json` records `ps_flat_interpolants`, the bit-0 positions. Tests: `tests/test_rdna2spirv_pixelinput.py` and `tests/test_fssm_header.py` (synthetic). GPU-checked by @Vonsek on #1246 (RTX 5080 and Radeon integrated graphics, stock `ps_flat` with a hand-built table of read methods 2 and 1): the smooth channels match a per-center perspective reference, the flat channel keeps the provoking value, and flipping either record's read method makes the translator refuse the shader. Bit 3 (0x08, 11,619 records) is a Float16-typed parameter per #1256. | -| Mixed flat and smooth f32 reads | A pixel shader may use `v_interp_mov_f32 p0` and `v_interp_p1/p2_f32` on the same input location. The translator declares it `PerVertexKHR`, takes vertex 0 for the MOV, and interpolates the smooth read with the triangle weights. The fallback modes without per-vertex inputs reject this combination. The synthetic `mixed_f32_varying.asm` fixture and the SPIR-V interpreter check both reads at two points of one triangle, and both fallback modes raise Unsupported (`test_p0_and_interpolated_read_of_one_f32_location` in `tests/semantic/test_interp_mov_flat.py`). [AMD RDNA 2 ISA, VINTRP instructions](https://www.amd.com/content/dam/amd/en/documents/radeon-tech-docs/instruction-set-architectures/rdna2-shader-instruction-set-architecture.pdf) | -| Computed I/J barycentrics (SHADER-177) | `v_interp_p1/p2` weight the interpolation with the values their operand VGPRs hold at the two ops, not with the hardware's own pair. Vonsek's image evidence on a synthetic triangle (#1224): zeroed sources render P0 = (0,0) on all 4,096 pixels, and copies of the pair read in swapped order render (v,u) — both follow the two VINTRP equations in the RDNA2 ISA guide; the centre interpolation the single-lane model used to emit is wrong for both. When a write of the operand register reaches an interp site (earlier in its own basic block, or in any block a path runs through first — loops included; a write at the site itself, an interp whose destination is its own I/J register, happens after the operand is read), the attribute is read `PerVertexKHR` and both ops interpolate with the operand values loaded from `%vgpr`, which holds whatever the program computed: constants (snapped coordinates, 577 straight-line sites), copies and copy chains (575), arithmetic (8), multi-writer sequences (1,135). The p1 loads its I and keeps it for the p2, which loads its J fresh — the program often sets J up between the two ops (574 sites) — so the final value uses the I of the p1 with the J of the p2; the p1's own full-sum value is dead because nothing may read the partial between the ops. Pipodi's straight-line scan puts the upper bound at 213 PS (#1218 comment 7076614458; 2,290 v0/v1 sites plus one PS reading J through a copy, all branchy); the reaching-write analysis finds 207 with a write that can reach an interp, and 6 whose overwrites sit on paths that cannot (left pristine, `.spv` unchanged). The other 11,888 PS keep the interpolated-input read and a byte-identical `.spv`. Composes with the operand guards (row above, #1224): a pristine plain `v_mov` copy of the pair stays the guards' to model (centre interpolation, bit-identical `.spv`, including the corpus's one copy PS), an operand that is neither v0/v1 nor written stays the guards' role-naming refusal, and a computed site is exempt from `interp_pair_src` and modelled here — which relaxes exactly the guards' copy-based refusals whose operand a program write reaches: a twice-written register (`v_mov` then arithmetic — the load reads the value the later write left; value-proven by `test_copy_written_again_is_computed`), a copy of an already-overwritten v0/v1 (Vonsek's zero-before-copy row: hardware renders P0, which is exactly the loaded zeros), and a modified `v_mov_b32_dpp` source (any write of the operand is a `%vgpr` value; translation-only test). A pristine copy in the wrong role still refuses (no computed value to model). Over the corpus the relaxation is empty — every one of the 213 PS names v0/v1 (or the one qualified copy), so on main and on this branch alike the set translates 213/213 and passes `spirv-val` 213/213, and no shader changes class; the guards' refusals that relax are the synthetic ones the tests cover. Refused (naming the pattern): a computed pair whose p1 partial is rewritten or read between the ops (its hardware value P10·I would be observable), one whose ops are not in one basic block (the captured I would not dominate the p2), a dangling op without its partner, any computed pair under `--bary-fallback` or `--f16-interp-fallback` (neither has PerVertexKHR inputs; the latter's decoded-half read would otherwise drop the computed weights), and a computed 32-bit read of a 16-bit-flagged interpolant — every one empty over the corpus. Confirmed by `tests/semantic/test_interp_computed_ij.py` and `tests/semantic/test_interp_guards.py` (Vonsek's rows, the between-ops J, f16 pairs, the refusals, the relaxed classes) and the `ps_ij_computed` GPU test (RTX 5060 Ti: snapped quarter pair = 0.5, zeroed pair = P0 = 0, (i, j/2) halving the second weight with 0.0 max error over 4,096 pixels; the same fixture built on main is wrong on 4,096 of 4,096). | -| Whole-wave masks | `tools/lane_masks.py` tracks per-lane mask bits through scalar registers, vector operations and saved EXEC spills. Whole-mask counts, first-set-lane queries, the leading-bit scans `s_flbit_i32_b32` / `s_flbit_i32` of `vcc_lo`/`exec_lo` (and `_hi`) and equality use subgroup operations (`tests/semantic/test_salu_flbit_lane_mask.py`; until then the flbit scans saw this lane's 0 / ~0). Whole-mask counts, first-set-lane queries and equality use subgroup operations. `cs_wavemask` checks all 64 lanes with a partially active EXEC mask. A physical 32-lane subgroup cannot directly exchange mask bits with the other half of a wave64, so `cs_wavemask` and the `cs_wave64_ballot` / `cs_wm_*` tests are exact only on 64-wide subgroups (AMD): on an RTX 4090 (subgroup 32) `s_bcnt1_i32_b64` of lanes 16–47 counts 16, one half (#101). `check.py` skips them where the GPU has no 64-wide compute subgroup. A mask copied into a VGPR with `v_mov_b32` goes through the normal EXEC-gated store, so inactive lanes keep the old VGPR (SHADER-21 part 2, #210); per-lane mask computations still store in all lanes, because whole-wave readers (`wave_mask`, `v_readfirstlane`) read every lane's bit. `cs_mask_vgpr_exec` checks it. Vector bitwise mask tracking (`VECTOR_BITWISE`) also includes `v_and_or_b32`, `v_xnor_b32` and `v_bfi_b32` when every source is a lane mask or `0`/`-1` (CPU-checked by `tests/test_lane_masks.py` and `tests/semantic/test_lane_masks_vector_bitwise.py`). | -| Floating-point operations | Separate floating-point instructions carry `NoContraction` so the driver preserves their individual rounding. The instructions that fuse multiply-add (`v_fma_f32`, `v_fmac_f32`, `v_fmaak_f32`, `v_fmamk_f32`, `v_fma_mix*`) round **once** on RDNA2 (measured on gfx1150 by `tools/f32_fuzz.py --oracle hw`: 72 of 72 cancellation probes fused). SPIR-V has two ways to say that. `GLSL.std.450 Fma` is the default (`--fma glsl`), but the Vulkan SPIR-V environment gives it the precision "inherited from `OpFMul` followed by `OpFAdd`", so a driver may legally round twice; `tools/f32_fuzz.py` and `runtime/test/shaders/cs_fma_fused.asm` are the tests that notice — on Mesa RADV/ACO (Linux), `--fma glsl` splits a subset of the 7 f32 FMAs in `cs_fma_fused` depending on GPU, Mesa version, and shader execution modes (measured: 4 of 7 on RX 6800 / Mesa 26.2.6-arch3.1 and RX 7600 / Mesa 27.0.0-devel with `SignedZeroInfNanPreserve 32`, 5 of 7 on RX 6800 before float controls, and 7 of 7 on Radeon Pro V540 RDNA1 / Mesa 25.2.8), while `--fma khr` emits single-rounded `v_fma_f32` (8/8 exact). `tools/f32_fuzz.py` and `runtime/test/shaders/cs_fma_fused.asm` are the tests that notice. `tools/f32_fuzz.py` and `runtime/test/shaders/cs_fma_fused.asm` are the tests that notice — on an AMD Radeon RX 6800 (Mesa RADV 26.2.6-arch3.1, Linux), RADV/ACO actually splits 5 of the 7 f32 FMAs in `cs_fma_fused` under `--fma glsl` (folding/splitting against the live `v_mul_f32` product `a*a`) and emits single-rounded `v_fma_f32` (8/8 exact) under `--fma khr`. `--fma khr` emits `OpFmaKHR` (`SPV_KHR_fma`, capability `FMAKHR`; "correctly rounded"), which needs `VK_KHR_shader_fma` with `shaderFmaFloat32` on the device. The index then lists capability `FMAKHR`, extension `SPV_KHR_fma` and feature `shaderFmaFloat32` for exactly the shaders that use it, and the output of every shader without a fused multiply-add is byte-identical under both options. `khr` is not the default because a device without the extension would fail pipeline creation; a runtime that knows its device has `shaderFmaFloat32` should translate with `--fma khr`. A device that has neither can split `Fma`: the Intel UHD Graphics driver (Xe-LP, Windows 101.7088) does, `cs_fma_fused` words 0, 2, 3 and 5 coming out split, with no `VK_KHR_shader_fma` (SHADER-497). RADV (Mesa 26.3.1, RX 6700 XT) splits the same four words, measured in #3004's review, but it has `VK_KHR_shader_fma` since Mesa 26.2, so `--fma khr` covers it. For it, `--fma exact` (`Gen.fma_exact`, no extension; per multiply-add about 110 instructions more than `glsl`, plus 31 `NoContraction` decorations and 13 constants) builds the single rounding from `NoContraction` f32 operations, after Boldo and Melquiond (IEEE Transactions on Computers 57(4), 2008): Dekker's exact product with the factors split by masking their low 12 mantissa bits, a TwoSum of the addend and the product, the two error terms summed with round-to-odd, and one final rounding. Power-of-two scaling keeps every intermediate in the normal range: by 2^-64 when the product or the addend is at least 2^126, by 2^96 when both are tiny, and 2^64 traded between a factor below 2^-100 and one above 2^-20. Infinite or NaN operands, and a product beyond even the scaled range (the result is ±inf), take the plain `Fma`. Confirmed: `tests/semantic/test_fma_exact.py` runs the emitted instructions in the interpreter with its `Fma` split as on that driver and compares 700 random and 96 edge cases with an exact rational reference; a model of the same steps matched 399,989 of 399,989 cases with a normal or zero result, with f32 denormals kept and flushed; on the GPU, `cs_fma_fused` (and #2211's `cs_w32_fma_mix`) pass with `--fma exact` on that Intel UHD and on an RTX 3050 Laptop (617.42). Not exact: a result in the denormal range (scaled back with a second rounding) and denormal operands, which follow the driver's denormal mode as every f32 operation does here. The f16 forms (`v_fma_f16`, `v_fmac_f16`, `v_pk_fma_f16`) never use either: they are exact round-to-odd arithmetic built from `OpFMul`/`OpFAdd` with `NoContraction` (`Gen.fma_f16_odd`), so a fused f32 `Fma` would not change them (`v_fma_mixlo_f16`/`v_fma_mixhi_f16` under the toward-zero MODE are the exception: `fma_mix_odd` needs the exact product error `Fma(x, y, -p)`, which is only guaranteed with `OpFmaKHR`), and an f16 `OpFmaKHR` (`shaderFmaFloat16`) is not used. The f64 multiply-adds of `v_div_fmas_f64` (the plain `fma`, the pre-scaled one and the exact product error) are `GLSL.std.450 Fma` on doubles by default, and the Vulkan environment lets a driver round that twice too: NVIDIA's does (RTX 4090, driver 621.24, Windows 11: `runtime/test/shaders/cs_div_fmas_f64.asm`, `fma(a, a, c)` with a = 1 + 2^-30 and c = -(1 + 2^-29) gives the split 0 instead of 2^-60, while the f32 `cs_fma_fused` fuses 8/8). `--fma khr` emits them as `OpFmaKHR` on doubles, which needs `shaderFmaFloat64` (the index lists that feature, and `shaderFmaFloat32` only for a module with an f32 FMA; `vk_pipeline_check` checks each); on the RTX 4090 it gives the fused 2^-60. `--fma exact` has no f64 form and keeps `Fma`. Checked by `tests/semantic/test_fma_khr_f64.py` (emission, index features, `spirv-val`). | -| `NoContraction` cost on MoltenVK (SHADER-234) | MoltenVK's SPIRV-Cross turns each `NoContraction` `OpFAdd`, `OpFSub` and `OpFMul` into a call to a `[[clang::optnone]]` helper (`spvFAdd`, `spvFSub`, `spvFMul`), and Metal does not inline it. MoltenVK 1.4.2 and `main` up to at least `5189f8de` are affected. SPIRV-Cross `98cbb7c0` inlines the helpers from MSL 3.2 with bit-identical output, and MoltenVK on macOS 26 or newer compiles MSL 4.0. On an Apple M3 Max, a translated compute shader of `v_mul_f32`, `v_add_f32` and `v_sub_f32` in a loop took 7.6 to 15.7 times as long on the GPU with the optnone helpers as with `98cbb7c0`. With independent operations and no `NoContraction`, it took two thirds of the `98cbb7c0` time, which is the cost of the decoration itself ([measurement](https://github.com/ItsNotRexed/Leonida/issues/1380#issuecomment-7078722086)). The same `spvFMul` helper drops the sign of a -0 product (SHADER-182, #1376). | -| `NoContraction` multiply on MoltenVK (SHADER-182) | On MoltenVK, a multiply whose exact product is a negative zero (`+0 × -1.5`, `-0 × 1.0`) returns +0 in f32, f16 and packed f16 (#1203). MoltenVK's SPIRV-Cross turns every `NoContraction` `OpFMul` into its `spvFMul` helper, which returns `fma(l, r, T(0))`. A -0 product plus +0 is +0. The f16 multiplies are `OpFMul` on `float` or `v2float`, so they take the same path. So does the product inside `fma_f16_odd`: `v_fma_f16`, `v_fmac_f16` and `v_pk_fma_f16` return +0 for a -0 product plus a -0 addend. SPIRV-Cross [300681bb](https://github.com/KhronosGroup/SPIRV-Cross/commit/300681bbcb8365a8d1eacdacdbdd0249bbf1d6b1) changes the addend to `T(-0.0)`. MoltenVK 1.4.2 has the old helper, and so does MoltenVK `main` at `5189f8de` (2026-10-13), which pins the parent commit `aa217aeb`. The translator does not change for this. `MVK_CONFIG_FAST_MATH_ENABLED=0` does not help, because the helper itself adds +0, and per #1203 neither does `SignedZeroInfNanPreserve` (#664). Measured on an Apple M3 Max (macOS 27.3): Metal keeps the sign for `a * b` and for `fma(a, b, -0.0)` with `MTLMathModeFast` and with `MTLMathModeSafe`, and loses it only with the +0 addend. With `valu_fuzz.py --family f16`, MoltenVK `5189f8de` as pinned matches 49/50 programs with `--seed 1 --wave 32`, 98/100 with `--seed 1 --emulate` and 98/100 with `--seed 4 --emulate`, and Homebrew MoltenVK 1.4.2 gives the same counts. Each mismatch is a -0 product read as +0. The same build with SPIRV-Cross `300681bb` matches 50/50, 100/100 and 100/100, as does KosmicKrisp (Mesa 26.3.1). For the FMA path, `--seed 330 --wave 32` with `--skip-op v_mul_f16 --skip-op v_pk_mul_f16` matches 49/50 with `aa217aeb` (a `v_fmac_f16` result) and 50/50 with `300681bb` and on KosmicKrisp. | -| MoltenVK fast-math (SHADER-234, NaN compares) | MoltenVK compiles every shader's MSL with Metal's fast-math on by default (`MVK_CONFIG_FAST_MATH_ENABLED`, default 1), and with it Metal folds an f32 compare of a NaN with itself as if the NaN were an ordinary number: `v_cmpx_eq_f32` and `v_cmpx_le_f32` on (NaN, NaN) give true where the ISA, AMD and NVIDIA give false (`ps_vcmpx_forms`, #1374: word 1 `0xf05e8e16`, want `0xf05e8a12`, bits 2 and 10; found by @zneel and @DomasUrbonas). The translation is not involved: the compare is `OpFOrdEqual` / `OpFOrdLessThanEqual`, and the MSL MoltenVK generates (`MVK_CONFIG_SHADER_DUMP_DIR`) is byte-identical with fast-math on and off, so it is Metal's compile option. `MVK_CONFIG_FAST_MATH_ENABLED=2` (on demand) does not help, because translated modules don't declare an execution mode that asks for IEEE behaviour; 0 does. The test tools (`runtime/test/vulkan_loader.h`, which every Vulkan test program uses to load MoltenVK) set `MVK_CONFIG_FAST_MATH_ENABLED=0` before MoltenVK reads its configuration, unless the variable is already set, so a user's own value still wins; the variable also reaches MoltenVK through the Vulkan loader. A runtime that loads MoltenVK on a Mac must do the same. Fast-math off does **not** remove the `[[clang::optnone]]` `spvFAdd`/`spvFSub`/`spvFMul` helpers SPIRV-Cross emits for `NoContraction` (11 calls in `ps_ops`'s MSL either way: their cost is the other part of SHADER-234), and it does not fix the row above (SHADER-182): `valu_fuzz.py --family f16 --seed 1` gives the same `v_mul_f16` +0 mismatch with fast-math on and off. Confirmed on an Apple A18 Pro (macOS 26.6.2, MoltenVK 1.4.2): `ps_vcmpx_forms` fails on all 4,096 pixels with fast-math on and matches all 4,096 with it off, natively and with wave64 emulation; no other `run_gpu_tests.py` result and none of the 25 `ctest` tests changes. | -| `v_cmp(x)_lg_f32/f16` on MoltenVK (ordered not-equal) | LG is less-or-greater, false when either source is a NaN. The translator emits it as the `OpLogicalOr` of `OpFOrdLessThan` and `OpFOrdGreaterThan`, not as `OpFOrdNotEqual`. MoltenVK's SPIRV-Cross writes `OpFOrdNotEqual` as a plain `!=`, the same text it gives `OpFUnordNotEqual`, and Metal's `!=` is true on a NaN. That happens with fast-math off too, so it is not the row above: `ps_vcmp_f32_nan`'s SPIR-V has 8 `OpFOrdNotEqual` and 8 `OpFUnordNotEqual`, and the MSL MoltenVK dumps (`MVK_CONFIG_SHADER_DUMP_DIR`) has 16 identical `as_type(a) != as_type(b)`. Confirmed on an Apple M4 (MoltenVK 1.4.2, fast-math off, MoltenVK logs "MathMode Safe"). `ps_vcmp_f32_nan`, `ps_vcmp_f16`, `ps_vcmp_f16_e64`, `ps_vcmpx_f16` and `ps_vcmpx_f16_e64` failed only in the LG bits of their NaN pairs (f16 word 1 `0x4ce9bda2`, want `0x4ce9b1a2`; f32 `0x377c`, want `0x376c`). With this form all five pass, and no other `run_gpu_tests.py` result changes. f64 LG compares integer words and is not affected. `v_cmp(x)_lg_f32/f16` is in 13,795 of the 25,734 listings. The form is pinned on the CPU by `tests/semantic/test_vcmp_f32_predicates.py` (`test_lg_is_ordered_without_ord_not_equal`). | -| Denormal flush and special results in `v_rcp_f32`, `v_rsq_f32`, `v_sqrt_f32`, `v_log_f32`, `v_exp_f32`, `v_rcp_iflag_f32` | Measured on an RX 6800 (gfx1030, not the console's gfx1013) with raw kernels in both wave sizes and all four IEEE/DX10_CLAMP combinations: all six read a denormal input as a zero of its sign and flush a denormal result, even with MODE's denormal field set to keep them. `v_rcp_f32(±0)` = ±inf, `v_rsq_f32(-0)` = -inf, `v_sqrt_f32(-0)` = -0, `v_log_f32(±0)` = -inf, `v_rcp_f32(FLT_MAX)` = +0, `v_exp_f32(-127)` = +0, `v_exp_f32(128)` = +inf, and every invalid result (`v_sqrt_f32`/`v_rsq_f32`/`v_log_f32` of a negative, …) is `0xffc00000`. Each is within 1 ulp of correctly rounded on the values tried, and `v_rcp_iflag_f32` is bit-identical to `v_rcp_f32`. **Not modelled yet:** the translator leaves all six on Vulkan's default denormal handling, and the ±0 and negative inputs above stay undefined in the emitted SPIR-V (`OpFDiv` by zero, `Sqrt`/`Log2` of a negative), as listed in the multiply-add and output modifiers row; the `clamp`/`omod` bits on `v_cvt_f32_*` and `v_rcp_iflag_f32` are modelled there. Source: [@shelbykb2's hardware words](https://github.com/ItsNotRexed/Leonida/issues/634#issuecomment-7074348963), not the ISA text. The corpus only ever writes MODE's FP_ROUND field and carries `mul:2`/`mul:4`/`div:2` on 102,365 float instructions (a compiler does not emit one that is ignored), so the inferred f32 state, IEEE off with denormals flushed, is the one to model. Corpus count (`tools/shader_profile.py`, 26,503 shaders; the shader count of each op deduplicates its `_e32`/`_e64` forms): `v_rcp_f32` 17,393 shaders / 424,863 occurrences, `v_rsq_f32` 17,221 / 269,310, `v_sqrt_f32` 14,511 / 201,422, `v_log_f32` 8,454 / 90,199, `v_exp_f32` 8,603 / 148,846, `v_rcp_iflag_f32` 7,395 / 34,852; 20,193 shaders (76.2%) use at least one, 1,169,492 occurrences (2.6% of the corpus's 44,406,870 instructions). | -| f16 transcendentals (`v_exp_f16`, `v_log_f16`, `v_rcp_f16`, `v_rsq_f16`, `v_sqrt_f16`, `v_sin_f16`, `v_cos_f16`) | Measured on an RX 6700 XT (gfx1031, not the console's gfx1013) with `tools/f16_trans_sweep.py`: all 65,536 inputs of each op, wave32 and wave64 (identical on every input), five MODEs (FUZZ-29). With f16 denormals kept (`denorm_mode_16_64 = 3`, the assembler default and what the translator assumes), `v_exp/log/rcp/rsq/sqrt_f16` are **correctly rounded on every input that is not a NaN** (0 ulp). `v_sin/v_cos_f16` take turns and reduce them exactly over the whole f16 range (no ±256 limit): compared with sin/cos(2πx), every result for \|x\| > 1 is bit-exact, and for \|x\| ≤ 1 only 14 (sin) and 4 (cos) of 30,722 are 1 ulp off. So the translator's rule (widen to f32, the GLSL.std.450 function, round to nearest even back to f16) matches the hardware as far as the driver's f32 function is accurate. For sin/cos that holds only once the angle is reduced in turns first (#594): with the f32 product 6.2831855 · x, 16,366 sin and 2,036 cos inputs are more than 1 ulp off, up to 9,944 ulp (sin of 64,640 turns: 0.0267 instead of 0). With `denorm_mode_16_64 = 0`, a denormal operand reads as a zero of its sign, and a denormal result is written as a zero of its sign. That differs from the f32 ops in the row above, which flush in both modes. The f16 field of FP_ROUND is ignored: round toward zero gives the same words as round to nearest on every input. IEEE changes only signalling NaNs. With IEEE off they pass through unchanged; with IEEE on they are quieted (bit 9 set). Payload and sign are kept either way, and quiet NaNs pass unchanged in every mode. Where SPIR-V leaves the result undefined, the hardware gives: log(±0) = -inf, rcp(±0) = ±inf, rsq(+0) = +inf, rsq(-0) = -inf, sqrt(-0) = -0, and `0xfe00` for log/rsq/sqrt of a negative (-inf included) and for sin/cos(±inf). `v_exp_f16`/`v_log_f16` give the same counts on gfx1036 (RDNA2, AMD Windows driver; SHADER-135). Since 2026-11-22 the translator selects those hardware words for `v_rcp_f16`, `v_rsq_f16` and `v_sqrt_f16` itself (the operand is replaced by 1.0 for the f32 `OpFDiv`/`InverseSqrt`/`Sqrt`, which SPIR-V leaves undefined at 0 or below 0) and `0xfe00` is the negative quiet NaN; checked bit for bit through the interpreter by `tests/semantic/test_valu_rcp_f16.py`, `test_valu_rsq_f16.py` and `test_valu_sqrt_f16.py` against exactly rounded references. The undefined cases of `v_exp_f16`/`v_log_f16`/`v_sin_f16`/`v_cos_f16` are still left to the driver. **Not modelled yet:** `Gen.f16_bits` quiets every NaN (the hardware keeps a signalling NaN with IEEE off), and the undefined cases above are left to the driver. | -| f64 literal sources | For `v_cvt_f32_f64` and either source of `v_add_f64`, a literal dword supplies bits 63:32 and bits 31:0 are zero. For `v_cvt_f32_f64`, `v_rcp_f64`, `v_rsq_f64`, `v_sqrt_f64`, `v_frexp_mant_f64`, `v_frexp_exp_i32_f64` and either source of `v_add_f64`, a literal dword supplies bits 63:32 and bits 31:0 are zero. Inline integers are sign-extended and inline floats use their binary64 value. For example, gfx1030 `llvm-mc` encodes 1.5 as the literal word `0x3ff80000`. The synthetic `tests/semantic/fixtures/f64_literals.asm` checks both source words in the translated SPIR-V, including the distinction between the printed literal `0x1` and inline `1`. [LLVM AMDGPU operand conversions](https://releases.llvm.org/15.0.0/docs/AMDGPUOperandSyntax.html#integer-literals) In the synthetic `unary_f64_literals.asm`, LLVM gfx1030 encodes the five unary literal sources in trailing dwords. The regression checks the emitted high and low operand words for reciprocal, reciprocal square root and square root. It executes the integer-only frexp paths: for 6.0 the mantissa words are (0, 0x3fe80000) and the exponent is 3. The full fixture passes Vulkan 1.2 validation; the semantic interpreter cannot execute its Float64 instructions. The rule keys on the literal's printed width, not only its value: LLVM pads nothing, so a value that fits one literal dword prints in at most 8 hex digits, and a spelling of more than 8 is the whole binary64 constant (the full-width form `tools/f64_diff.py` writes: `0x0000000012345678` is the low word `0x12345678` and a zero high word, while `0x12345678` stays the high word). gfx1013 `llvm-mc` refuses a literal wider than 32 bits for these ops ("invalid operand"), so a listing from the game carries only the one-dword form and its words do not change. The wider form used to be refused by the four rounding ops; they now read the whole constant, which is what the differential check's generated programs needed. `tests/semantic/test_f64_literal_whole.py` checks those emitted words for `v_sqrt_f64`, `v_rsq_f64`, `v_rcp_f64`, the four rounding ops and the frexp exponent path, next to the one-dword, padded-width and inline-integer controls; `tests/test_f64_diff.py` checks that the CPU reference reads a literal the same way; `tools/f64_diff.py`'s CPU reference judged the whole-literal `v_add_f64`/`v_rsq_f64`/`v_sqrt_f64` programs as mismatches before the change. | -| `v_cvt_f32_f64` output modifiers | Convert to f32, apply `mul:2`, `mul:4`, or `div:2` if present, then apply `clamp` to [0, 1] if requested. [LLVM GFX10 assembler tests](https://github.com/llvm/llvm-project/blob/main/llvm/test/MC/AMDGPU/gfx10_asm_vop1.s#L3044-L3054) confirm the modifier encodings. `tests/test_f64_conversion.py` checks the resulting SPIR-V data flow. | -| 32-bit integers to binary64 | `v_cvt_f64_i32` sign-extends the input value and `v_cvt_f64_u32` treats it as unsigned. Every 32-bit integer is exactly representable in binary64. The low word goes in the first destination VGPR. **The output scaling is gated by `MODE`, measured by @fiestorra**: on a gfx1036 iGPU (Radeon(TM) Graphics, drivers `31.0.24002.92` and `32.0.21045.29003` (the same counts on both), raw ISA through `tools/hw_oracle`, `tools/f64_omod_probe.py`, 6 inputs x 5 modifier forms x 5 MODEs, wave32 and wave64 identical) `mul:2`/`mul:4`/`div:2` scale the binary64 result only under `IEEE=0` with `denorm_mode_16_64=0`; under `denorm_mode_16_64=3`, which is what the translator assumes, and under `IEEE=1` they are ignored, while `clamp` applies in every MODE — so only `clamp` reaches `dst_f64` for these two ops, as `v_ldexp_f64` already does. For input `0x80000001`, SPIRV-Tools constant folding reproduced both words of each result in the synthetic `ps_int32_to_f64.s` fixture. [AMD RDNA 2 ISA, VOP1 conversions](https://www.amd.com/content/dam/amd/en/documents/radeon-tech-docs/instruction-set-architectures/rdna2-shader-instruction-set-architecture.pdf) | -| `v_add_f64` output modifiers | The double sum is scaled by `mul:2`, `mul:4` or `div:2` if present, then clamped to [0, 1] if `clamp` is set, as for f32 (`clamp_mods_f64`, GLSL.std.450 `FClamp` on the double, so a NaN result and the sign of a -0 result are left to the driver, also as for f32). **Until 2026-11-22 both were ignored.** Source: LLVM AMDGPU defines it as `VOP3Inst<"v_add_f64", VOP3_Profile>` (VOP3Instructions.td), and `VOPProfile` sets `HasClamp` (f64 is a modifier type) and `HasOMod` (floating-point destination) (SIInstrInfo.td). It is the only f64 arithmetic the translator handles; `v_cvt_f32_f64` has the row above. `tests/test_f64_output_modifiers.py` checks the SPIR-V data flow; `runtime/test/shaders/ps_f64_mods.asm` is the GPU test (needs `shaderFloat64`, which `vk_harness` now enables when the fragment shader declares `Float64`), passed on an NVIDIA RTX 6000 Ada (driver 615.71.09, Linux; 4096/4096 pixels exact, and the `main` translator gives the predicted old words). | -| `v_rcp_f64`, `v_rsq_f64`, `v_sqrt_f64` | Double-precision reciprocal (`OpFDiv %double 1.0 x`), inverse square root (`GLSL.std.450 InverseSqrt`), and square root (`GLSL.std.450 Sqrt`), requiring `Float64` (`shaderFloat64`). VOP3 input modifiers (`abs`, `neg`) apply to the double operand, and output modifiers (`mul:2`, `mul:4`, `div:2`, then `clamp` to [0, 1]) apply via `clamp_mods_f64` (LLVM `VOP1Inst` / `VOP_F64_F64` in `VOP1Instructions.td`, `HasClamp` and `HasOMod` via `VOPProfile`). Special-value edge cases (`±0`, negative inputs, NaN) follow the driver's SPIR-V `OpFDiv`/`InverseSqrt`/`Sqrt` rules, as for the f32 forms. Checked by `tests/test_f64_transcendentals.py` (SPIR-V data flow and `spirv-val`). **Measured on RDNA2** (gfx1036 iGPU, Windows driver 31.0.24002.92, `tools/hw_oracle` raw kernels, MODE with IEEE on and f64 denormals kept): `v_sqrt_f64` is not the correctly rounded root. `sqrt(4.0)` stored `0x4000000004000000` (2.0000000298), `sqrt(9.0)` `0x4008000004000000`, `sqrt(0.25)` `0x3fe0000004000000` and `sqrt(2.0)` `0x3ff6a09e64000000`. Against the correctly rounded roots, the first three are exactly +2^26 ulps off, and `sqrt(2.0)` is −41,892,813 ulps (about −2^25.3) from `0x3ff6a09e667f3bcd` (1.4142135624), so only about 26 of the 53 significand bits are right. `GLSL.std.450 Sqrt` is the more accurate lowering, and a difference from the instruction on RDNA2 hardware is not a translator bug. `v_rcp_f64` and `v_rsq_f64` returned exact values, but only powers of two were tried, so their accuracy is unmeasured. None of the three occurs in the 26,503 game listings ([measurement](https://github.com/ItsNotRexed/Leonida/issues/4084#issuecomment-7088412190), @fiestorra). | -| `v_trunc_f64`, `v_ceil_f64`, `v_rndne_f64`, `v_floor_f64` | Round binary64 toward zero, positive infinity, nearest-even, or negative infinity respectively; the result stays binary64. The translator maps these to GLSL.std.450 `Trunc`, `Ceil`, `RoundEven`, and `Floor` with `shaderFloat64` (no intermediate f32). Register pairs are low word first, literal dwords fill bits 63:32 with a zero low word, and inactive lanes keep both destination words. VOP3 applies source modifiers before rounding and the existing f64 scale/clamp path afterwards. Sources: AMD [RDNA 2 ISA](https://gpuopen.com/download/rdna2-shader-instruction-set-architecture.pdf) §6.2.1 and §12.8 (VOP1 opcodes 23–26), and LLVM's [GFX10 assembler tests](https://github.com/llvm/llvm-project/blob/1a7ece827ab3543387ee1adf1eb4c8878905b577/llvm/test/MC/AMDGPU/gfx10_asm_vop1.s). Value and SPIR-V checks: `tests/semantic/test_f64_round.py`. Hardware-confirmed natively on RDNA2 (`gfx1036` iGPU, Windows driver 32.0.21042.62, `tools/hw_oracle`, wave32 and wave64 identical on every case) by @timelery: exact IEEE-754 rounding that keeps signed zeros and binary64 subnormals (`ceil(+sub)` = +1.0, `ceil(-sub)` = -0.0, `floor(+sub)` = +0.0, `floor(-sub)` = -1.0, `trunc(±sub)` = ±0.0, `rndne(±0.5)` = ±0.0, `rndne(±1.5)` = ±2.0, `rndne(±2.5)` = ±2.0, ±inf stays ±inf, and ±qNaN/±sNaN pass through unchanged under IEEE=0), where `sub` is the smallest binary64 subnormal; the hex literal dword populates bits 63:32 with a zero low word (`v_floor_f64 v[4:5], 0x3ff80000` -> `0x3ff0000000000000`); and the VOP3 output modifiers behave as for `v_add_f64`/`v_sqrt_f64`: applied on hardware under `denorm16_64=0` and ignored under `denorm16_64=3` (IEEE=0), while the translator applies them through `clamp_mods_f64` as those rows do. | -| Floating-point class compare | `v_cmp_class_f32` writes the selected class to a lane mask. `v_cmpx_class_f32` intersects the existing EXEC with that same predicate and preserves VCC, as specified in [AMD's RDNA2 ISA §12.9](https://www.amd.com/content/dam/amd/en/documents/radeon-tech-docs/instruction-set-architectures/rdna2-shader-instruction-set-architecture.pdf). VOP3 `abs` and `neg` on `src0` are applied as raw sign-bit moves on the 32-bit integer bits (`OpBitwiseAnd 0x7FFFFFFF`, then `OpBitwiseXor 0x80000000`) rather than `FAbs`/`OpFNegate`, so signalling NaNs stay signalling (class bit 0) and subnormals are never flushed. **Hardware-measured natively on RDNA2 (`gfx1036`)** via `tools/hw_oracle` (Ryzen 7 9800X3D iGPU, Linux AMDGPU DRM): 672/672 exact across 21 representative IEEE-754 values (including 5 sNaNs) × 4 modifier forms (`v`, `-v`, ` `cs_cmpx_class_f32` checks both encodings with quiet NaN, positive infinity and signed zero, and verifies that a previously inactive lane stays inactive. GPU-checked on an RTX 4070 SUPER (driver 616.92). \| v \| `, `- \| v \| `) × 10 class bits for both `v_cmp_class_f32_e64` and `v_cmpx_class_f32_e64` in wave32 and wave64 across all four `(IEEE=0/1, denorm32=0/3)` modes (until 2026-11-22 `Gen.cmp_class` used `src_f` → `FAbs`/`OpFNegate`, which quieted modified sNaNs in `spirv_mini_interp.py`). 672/672 exact across 21 representative IEEE-754 values (including 5 sNaNs) × 4 modifier forms (`v`, `-v`, `\|v\|`, `-\|v\|`) × 10 class bits for both `v_cmp_class_f32_e64` and `v_cmpx_class_f32_e64` in wave32 and wave64 across all four `(IEEE=0/1, denorm32=0/3)` modes (until 2026-11-22 `Gen.cmp_class` used `src_f` → `FAbs`/`OpFNegate`, which quieted modified sNaNs in `spirv_mini_interp.py`). Corpus count (26,503 shaders): `v_cmp_class_f32` appears 37,026 times in 7,101 shaders (0 with VOP3 `abs`/`neg` on `src0`). Checked on CPU + `spirv-val` by `tests/semantic/test_cmp_class_f32_mods.py` and `tests/semantic/test_valu_f32_class_rndne.py`; `cs_cmpx_class_f32` checks both encodings with quiet NaN, positive infinity and signed zero, and verifies that a previously inactive lane stays inactive (GPU-checked on RTX 4070 SUPER driver 616.92 and AMD RX 9070 XT RADV Mesa 26.2.6, plus direct Vulkan compute verification of modified sNaNs on RX 9070 XT and Radeon 610M `gfx1036`). | -| Float controls (NaN, ±inf, −0) (SHADER-99) | RDNA2 float ops return NaN, ±inf and −0 as computed, and Vulkan lets the driver assume none of them occur unless the module says otherwise. Every module therefore declares `OpExecutionMode %main SignedZeroInfNanPreserve 32` (capability `SignedZeroInfNanPreserve`, core since SPIR-V 1.4). Its index entry lists `"float_controls": ["shaderSignedZeroInfNanPreserveFloat32"]`, the device property it needs; `vk_pipeline_check` skips the shader where that property is false, and `--no-float-controls` leaves the mode out. Measured on AMD Radeon RX 9070 XT (driver 26.11.2). Without the mode, `runtime/test/shaders/cs_signed_zero_nan.asm` gets 0 in out[4..7]: the `x != x` NaN checks fold to false and a NaN `v_cvt_f16_f32` is lost. The f16 fuzzer (`tools/valu_fuzz.py --family f16`) also saw `v_pk_mul_f16` −0 products come back +0, and, with integer f16 narrowing (#575), NaN results that were never stored. With the mode, the test and those programs match. Other drivers, from testers in #664: RADV (RX 7800 XT) folds the f16 NaN check (out[6]) without the mode; NVIDIA and Intel Arc keep all three either way. Apple GPUs (MoltenVK) report the property, and the mode fixes their NaN checks, but −0 products (out[0], out[2], out[3]) still come back +0 with or without it (#1203, SHADER-182). `check.py` and `scripts/run_gpu_tests.py` don't judge those three words on an Apple device. Mesa's llvmpipe, where the CI runs these tests, returns 0 for the `0 × inf` NaN check (out[5]) with or without the mode, while its other NaN checks give 1 (#664), so out[5] isn't judged there (`UNJUDGED_WORDS` in `check.py`). f64 has its own row below (SHADER-597); its `SignedZeroInfNanPreserve 64` isn't declared yet. | -| Float controls (f16 denormals) (SHADER-526) | RDNA2 keeps f16 denormals, so every module also declares `OpExecutionMode %main DenormPreserve 16` (capability `DenormPreserve`, core since SPIR-V 1.4 like `SignedZeroInfNanPreserve`, so no extension at `--target-env vulkan1.2`). The translator models f16 arithmetic in f32 with integer narrowing (`Gen.f16_bits`), so an f16 denormal is an ordinary f32 value in the module and no f32 denormal is involved: the 16-bit mode is what governs the f16→f32 conversion the driver emits for an f16 source. NVIDIA flushed that conversion without it: in `runtime/test/shaders/ps_sdwa_f16_const.asm` the y lane (`src0_sel:BYTE_1` of `2.0` is the denormal 0x0040 = 2^−18, × 1024.0 = 2^−8 = 0x1c00) read 0x0000, 4096/4096 pixels wrong, while x, z and w matched; with the mode the test is 4096/4096 exact (RTX 4070 SUPER, driver 610.88, Windows 11, validation layers on). The same lane read 0x0000 on an RTX 3090 (driver 610.88, found by @Rainmaker33). Assembling the same module with only the two `DenormPreserve` lines removed reads 0x0000 again, so it is the mode the driver honours, not a change in the translated code. Not every NVIDIA build flushes it: on `main` without the mode an RTX 4060 Ti (621.24), an RTX 5070 Ti (620.73.04, Linux) and an RTX 5080 (616.92) pass the test. The index entry lists `"shaderDenormPreserveFloat16"` after `"shaderSignedZeroInfNanPreserveFloat32"`; `vk_pipeline_check` skips the shader where the device reports that property false, and `--no-float-controls` leaves both modes out. Where the property is false the module has no f16 denormal guarantee, so an f16 denormal read can come back +0 exactly as in that lane above (NVIDIA's default without the mode); that is a value difference in the shader, and the GPU test's y lane is then expected to fail. The AMD Radeon iGPU (RDNA2, driver 24.10.24, Vulkan 1.3.280) reports `shaderDenormPreserveFloat16` true with `denormBehaviorIndependence` `32_BIT_ONLY`, and `vk_pipeline_check` builds the module and its pipeline there (`ps_sdwa_f16_const`: 1 module ok, 1 pipeline ok, wave32 and wave64); the GPU test itself skips on that device, which has 128 push-constant bytes where the test needs 144. `tests/semantic/test_f16_denorm_preserve.py` pins the mode, the index property and the four words. | -| `v_mul_legacy_f32` default-mode f32 denormal flushing | Under the inferred game `MODE` (`IEEE=0`, `denorm_mode_32=0`), the DX9 legacy multiplication reads f32 denormal operands as signed zeros, then its zero-operand override produces **+0** even when an operand was negative or the other is infinity/NaN. A nonzero subnormal product flushes to a zero retaining its sign, *before* VOP3 `mul:2`/`mul:4`/`div:2`; with IEEE off an output multiplier converts a resulting -0 to +0 on native RDNA2. The translated result is flushed after the modifier. This uses software f32 bit tests (`Gen.flush_f32`) rather than driver-specific denormal controls. Native gfx1031 (39,101 programs) and gfx1036 (38,858 programs) measured the MODE and DX9 mul rule (see the output-modifier rows below); the previous translator allowed f32 denormal operands and products through raw `OpFMul`. Synthetic regression: `tests/semantic/test_valu_mul_legacy_denorm.py`, `ps_mul_legacy_denorm.asm` and `ps_mul_legacy_denorm_mods.asm` (CPU, spirv-val and Vulkan GPU). This models the inferred game mode, not all possible dynamically changed MODE configurations. | -| Float controls for f64 (SHADER-597) | A module that declares `Float64` (the translator's native f64 ops) also declares `OpExecutionMode %main SignedZeroInfNanPreserve 64`, since Vulkan does not guarantee −0, NaN or ±inf for 64-bit float ops without it (e.g. `v_add_f64` of −0 and −0 = −0). Same capability as the 32-bit mode, no extension; modules without `Float64` don't get it. The index entry then lists `"float_controls": ["shaderSignedZeroInfNanPreserveFloat32", "shaderSignedZeroInfNanPreserveFloat64", "shaderDenormPreserveFloat16"]`, `vk_pipeline_check` skips the shader where any of them is false, and `--no-float-controls` leaves all three modes out. Found by @Jolymmiles (issue #3047). `tests/test_f64_float_controls.py` checks the module and the index entry; **not yet GPU-verified** (`ps_f64_mods.asm` and the f64 fixtures need a run on a device with `shaderFloat64`). | -| Multiply-add with a literal | `v_fmamk_f32`/`v_madmk_f32` are D = S0 × K + S1 and `v_fmaak_f32`/`v_madak_f32` are D = S0 × S1 + K, K being the 32-bit literal. LLVM prints them `vdst, src0, K, vsrc1` and `vdst, src0, vsrc1, K`, so in print order all four are a[1] × a[2] + a[3] (fused for fmamk/fmaak). **Until 2026-11-21 fmamk and madmk computed S0 × S1 + K.** Source: RDNA2 ISA (V_FMAMK_F32, V_MADMK_F32) and the operand fields of the llvm-mc encoding. Checked by `tests/semantic` and GPU-checked with `runtime/test/shaders/ps_fma_literal.asm` on an NVIDIA GeForce RTX 2060 SUPER (Linux, driver 620.70.06): 4096/4096 pixels exact, and 4096/4096 differ with the old translator. | -| Multiply-add and output modifiers | `v_mac_f32` is the VOP2 form of `v_mad_f32`, **not** of `v_fma_f32`: the product is rounded before the add (`OpFMul` + `OpFAdd`, both `NoContraction`). It used to emit `Fma`, one ULP off on some inputs. Source: LLVM `SIInstrInfo.cpp` `getNewFMAInst` (`V_MAC_F32` -> `V_MAD_F32_e64`, `V_FMAC_F32` -> `V_FMA_F32_e64`). VOP3 `clamp` and `mul:2`/`mul:4`/`div:2` now apply to `v_cvt_f32_i32`/`u32`/`ubyte0..3`, `v_cvt_f32_f16` and `v_rcp_iflag_f32` (they were dropped). Source: LLVM `VOPProfileI2F` (`Ins64 = $src0, $clamp, $omod`) and the float-source profiles. Found by `tools/f32_fuzz.py` (FUZZ-3: an exact-arithmetic model against the translated SPIR-V; 0 mismatches over 10,000 seeded programs after the fix) and pinned by `runtime/test/shaders/ps_f32_mods.asm` (`tests/semantic/test_f32_valu.py`); **GPU-checked** (TEST-298): `ps_f32_mods` gives the expected four words (`0xc0256a01 0x3f800000 0x41e00000 0x3fc00000`, so the `v_mac_f32` product is not fused and the `clamp`, `mul:4` and `div:2` on `v_cvt_f32_ubyte1`/`u32`/`f16` and `v_rcp_iflag_f32` apply) on an NVIDIA GeForce RTX 2060 SUPER (Linux, driver 615.78.08); `mul:2` on the conversions is not in that fixture. **not yet GPU-verified**. Still open: on some inputs the ISA defines a result but the emitted SPIR-V is undefined: `v_rcp_f32(±0)` (`OpFDiv` by zero), `v_rsq_f32`/`v_log_f32` of ±0 or a negative, `v_sqrt_f32` of a negative. `v_cvt_pk_u8_f32(NaN)` now selects +0 before `FClamp` (see "Float-to-byte pack"). `v_rcp_f32(±0)` (`OpFDiv` by zero), `v_rsq_f32`/`v_log_f32` of ±0 or a negative, `v_sqrt_f32` of a negative (`v_cvt_pk_u8_f32(NaN)` now selects +0 before `FClamp`, see "Float-to-byte pack"). | -| Output modifiers on hardware (gfx1150, RDNA2) | Measured on a Radeon 880M (gfx1150, RDNA3.5; **not** RDNA2) with `tools/f32_fuzz.py --oracle hw`, 46,967 programs: `mul:2`/`mul:4`/`div:2` turn a -0 result (a flushed denormal result included) into +0, and are ignored with MODE.IEEE = 1; with f32 denormals kept they are also ignored for the ALU ops (the transcendental and cube ops still apply them). LLVM notes that omod mishandles signed zeros (`SIFoldOperands.cpp`) and D30209 describes -0 being forced to +0 before the modifier. The translator keeps -0 (`OpFMul`), so on that evidence it likely differs from hardware (see #1006). **RDNA2 does the same, rule for rule** (SHADER-353): on an RX 6700 XT (gfx1031, a discrete RDNA2 part, not the console's gfx1013; AMD Windows driver 26.11.2), seeds 1 to 6, 39,101 programs, 0 mismatch and 66 omod -0 → +0 deviations. Per MODE, counting only the programs where the omod changes the result: with IEEE off and f32 denormals flushed (the game's mode) it is applied every time (2,680, and the 66 -0 results become +0); with denormals kept it is ignored by the ALU ops (1,811) and applied by `v_rcp/rcp_iflag/rsq/sqrt/exp/log_f32` and the four cube ops (869, -0 → +0 only there); with IEEE on it is ignored (2,650) and a -0 result stays -0. Earlier, gfx1036 (the integrated GPUs of a Ryzen 9 7950X3D and a Ryzen 7 9800X3D) gave seeds 1 to 6, 38,858 programs, 0 mismatch and 56 such deviations, with identical counts through the Linux libdrm launcher and the Windows HIP launcher; `v_rcp_iflag_f32` with `clamp`/`omod` on the same GPU, 6,552 programs, 0 mismatch and 35 such deviations, otherwise behaves like `v_rcp_f32`. Also measured there: with `denorm_mode_32 = 0` f32 denormal operands read as zero and denormal results flush (add/mul/fma/min/max/rounding ops, DX9 mul), exact with 3. `v_fma_mix*` f32 operands read as zero when denormal too (SHADER-298: gfx1036, `0x00000001`, `0x807fffff`, and the integer inline constants 1 and 64; f16 operands widen to normal values); its result is not flushed, since that was not measured. Invalid operations give `0xffc00000`; a signalling NaN passes unchanged with IEEE off and is quieted with IEEE on. Details in docs/shader_validation.md ("32-bit float VALU on the GPU"). | -| Float min/max/med3 with NaN, `v_fract` | Measured on an AMD Radeon RX 6800 (gfx1030, not the console's gfx1013) with the hw-oracle tool from the AnyPS5 project, 537 input rows in all four IEEE/DX10_CLAMP combinations and in wave32 and wave64, the same for every combination with quiet NaNs. `v_min_f32`/`v_max_f32`, `v_min_f16`/`v_max_f16` and each half of `v_pk_min_f16`/`v_pk_max_f16`: one NaN operand gives the other operand, bits unchanged; both NaN give src0; -0 < +0. `v_min3`/`v_max3` = f(f(s0, s1), s2) with that min/max. `v_med3_f32`/`_f16`: with any NaN operand the result is min3(s0, s1, s2), otherwise the median (-0 < +0). `v_fract_f32` rounds x − floor(x) once and returns 0x3f7fffff (the largest float below 1) where that gives 1.0, e.g. fract(-1e-10); f16 gives 0x3bff; fract(-0) = +0, fract(±inf) = NaN, a NaN passes through. Measured natively on gfx1036 (RDNA2) in the MODE inferred for the game (IEEE 0, f32 denormals flushed): `v_floor_f32`, `v_ceil_f32` and `v_fract_f32` read a denormal operand as a zero of its sign (floor(-1e-45) = -0, ceil(+1e-45) = +0, fract of either 0), fract(±inf) is exactly `0xffc00000`, and a NaN operand comes back unchanged, a signalling one too. The translator flushes the operand and selects those words itself (`Gen.round_f32_flushed`) instead of leaving them to the driver's f32 denormal handling, which Vulkan does not fix; until 2026-11-22 a driver that keeps denormals gave -1.0, +1.0 and 0x3f7fffff there. `v_cvt_flr_i32_f32` likewise returns 0 for a negative denormal (the translator gave -1). Checked against 119 measured words by `tests/semantic/test_alu_floor_ceil_fract_hw.py`. For `v_fract_f16`, either infinity gives the gfx1036 word `0xfe00`, or +0 with the DX10 clamp. The translator selects these results explicitly. The hand-written `ps_fract_f16_infinity.asm` fixture checks both signs, the preserved destination bits and a color channel computed from the result sign in the CPU interpreter (`tests/semantic/test_fract_f16_infinity.py`). A source `neg` on a signalling NaN operand still quiets it in the translator. Not changed: f16 fract(±inf) is `0xfe00` on the hardware and a quiet positive NaN in the translator, and `neg` on a signalling NaN operand quiets it in the translator. The translator emits `NMin`/`NMax` for these min/max ops (before: `FMin`/`FMax`, whose NaN result GLSL.std.450 leaves to the implementation). med3 is `NMin(NMax(z, NMin(x, y)), NMax(x, y))` (until 2026-11-22 this used `FClamp(z, lo, hi)`, which was GLSL.std.450 undefined whenever `z` was NaN or both `x` and `y` were NaN), and when an operand can be a NaN, `OpIsNan` of each such operand (none for an inline or literal constant that is not a NaN) selects `NMin(NMin(x, y), z)` instead; all 1-, 2-, and 3-NaN operand positions for both `v_med3_f32` and `v_med3_f16` were hardware-verified on RDNA2 (`gfx1035`, wave32 & wave64). `FMin`/`FMax`, whose NaN result GLSL.std.450 leaves to the implementation). med3 is `FClamp(z, NMin(x, y), NMax(x, y))`, and when an operand can be a NaN, `OpIsNan` of each such operand (none for an inline or literal constant that is not a NaN) selects `NMin(NMin(x, y), z)` instead. `v_fract_f32` is `Fract` followed by `OpFOrdEqual` with 1.0 and an `OpSelect` of 0x3f7fffff, so the NaN of fract(±inf) is kept; `v_fract_f16` does the same before packing and then replaces a packed 0x3c00 with 0x3bff (not after an output multiplier, where 1.0 can be a true result). Other `FMin`/`FMax`/`FClamp` uses (the `clamp` bit, LOD and conversion clamps, `v_cvt_pk_u8_f32`, the BVH slab test) are unchanged. Not modelled: signalling NaNs under IEEE mode; NaN under the `clamp` bit (hardware gives +0 with DX10_CLAMP=1 and the NaN with DX10_CLAMP=0; the translator still emits `FClamp`). All-NaN float min/max/med3 ops (`v_min/max/min3/max3/med3_f32` via `Gen.nminmax_f32`, `v_min/max/min3/max3/med3_f16` via `Gen.f16_in_bits`/`Gen.all_f16_nan_cond`, and per-half `v_pk_min/max_f16` when `clamp` is unset) explicitly preserve `src0`'s NaN bits (including sign, payload, and signalling bit under `IEEE = 0`, matching the RX 6800 and `gfx1036` hardware rules). The CPU tests `tests/semantic/test_minmax_f32_payload.py` and `tests/semantic/test_alu_min3_max3_med3_16_hw.py` check operand-order payload and signalling NaN preservation. Also, without the `SignedZeroInfNanPreserve` execution mode Vulkan does not strictly guarantee NaN or signed-zero behaviour, so these rules hold where the driver keeps them. NaN under the `clamp` bit (hardware gives +0 with DX10_CLAMP=1 and the NaN with DX10_CLAMP=0; the translator still emits `FClamp`); the NaN payload when both operands are NaN (`NMin` only promises a NaN); and without the `SignedZeroInfNanPreserve` execution mode Vulkan does not strictly guarantee NaN or signed-zero behaviour, so these rules hold where the driver keeps them. With an output modifier (`mul:2`, `mul:4`, `div:2`) on `v_fract_f16` the translator applies the modifier to the f32 fract before narrowing to f16; the hardware order of rounding and modifier for that case was not measured, so a result can differ by one f16 step for tiny negative inputs (e.g. x = -1e-4 with `div:2`). GPU-checked with `runtime/test/shaders/ps_fnan_med3.asm` and `ps_fnan_fract.asm` (inputs read from memory at run time) on an AMD Radeon RX 6800, Windows 11, driver 26.11.2: 4096/4096 pixels exact; on that driver the two med3 words differed before the change (0x40e00000 and 0x40600000 instead of 0x40a00000 and 0xc0200000), and so did the f16 fract word (0x3c00 instead of 0x3bff) once f16 results were narrowed with integer round-to-nearest; the f32 fract and the min/max words were already the hardware words there. `tests/semantic/test_float_nan_fract.py` runs the measured rows through the translator and the interpreter. | -| `ds_swizzle_b32` | An active destination reads the selected source lane's VGPR. If EXEC disables that source, the read returns zero; a disabled destination keeps its prior value. The [hardware measurements](shader_validation.md#hardware-oracle-for-the-lds-programs---oracle-hw) confirm the disabled-source result on gfx1036 and gfx1150. In the seven-invocation CPU fixture, lane 6 selects lane 7, which is absent. The translator returns zero in that case; the corresponding result on hardware is unverified. The fixture exercises `QUAD_PERM` and `SWAP` in `test_ds_permute.py`. A numeric `offset:N` below 0xC000 is decoded like its symbolic `swizzle(...)` form since #4177; 0xC000–0xFFFF is refused (`Unsupported`), which RDNA2 treats as a separate mode (measured on gfx1036 for all 16,384 offsets). **No game shader is affected either way** (SHADER-811): over the 1.0.2.1 package's 26,503 DXBC listings and the FidelityFX DLL's 29 FSPX programs, llvm-mc prints all 105,529 `ds_swizzle_b32` (in 6,296 DXBC programs; the FSPX programs have none) in a symbolic form, with 17 distinct offsets: 101,913 in 0x8000–0xBFFF (`QUAD_PERM`), 3,616 below 0x8000 (the bitmask mode: `BROADCAST`, `SWAP`, `BITMASK_PERM`) and none at or above 0xC000. Counted from each instruction's printed encoding (offset = bits 15:0 of the first dword) in every listing, the 1,473 with embedded data words included (only decoded instructions count), and matched by a count of the printed offset classes on a second copy (#4566). | -| Output modifiers on hardware (gfx1150) | Measured on a Radeon 880M (gfx1150, RDNA3.5; **not** RDNA2) with `tools/f32_fuzz.py --oracle hw`, 46,967 programs: `mul:2`/`mul:4`/`div:2` turn a -0 result (a flushed denormal result included) into +0, and are ignored with MODE.IEEE = 1; with f32 denormals kept they are also ignored for the ALU ops (the transcendental and cube ops still apply them). LLVM notes that omod mishandles signed zeros (`SIFoldOperands.cpp`) and D30209 describes -0 being forced to +0 before the modifier. The translator keeps -0 (`OpFMul`), so on that evidence it likely differs from hardware (see #1006). RDNA2 itself is unmeasured (see #1006). Also measured there: with `denorm_mode_32 = 0` f32 denormal operands read as zero and denormal results flush (add/mul/fma/min/max/rounding ops, DX9 mul), exact with 3. `v_fma_mix*` f32 operands read as zero when denormal too (SHADER-298: gfx1036, `0x00000001`, `0x807fffff`, and the integer inline constants 1 and 64; f16 operands widen to normal values); its result is not flushed, since that was not measured. Invalid operations give `0xffc00000`; a signalling NaN passes unchanged with IEEE off and is quieted with IEEE on. RDNA2 does the same: gfx1036 (the integrated GPUs of a Ryzen 9 7950X3D and a Ryzen 7 9800X3D; RDNA2, but not the console's gfx1013), seeds 1 to 6, 38,858 programs, 0 mismatch and 56 omod -0 → +0 deviations, with identical counts through the Linux libdrm launcher and the Windows HIP launcher; `v_rcp_iflag_f32` with `clamp`/`omod` on the same GPU, 6,552 programs, 0 mismatch and 35 such deviations, otherwise behaves like `v_rcp_f32`. Also measured there: with `denorm_mode_32 = 0` f32 denormal operands read as zero and denormal results flush (add/mul/fma/min/max/rounding ops, DX9 mul), exact with 3; invalid operations give `0xffc00000`; a signalling NaN passes unchanged with IEEE off and is quieted with IEEE on. Details in docs/shader_validation.md ("32-bit float VALU on the GPU"). | -| Wave64 handling | Wave size is detected per shader from the code (64-bit EXEC writes, `exec_hi`, `v_mbcnt_hi`, `*_saveexec_b64`/`*_wrexec_b64`, and 64-bit lane-mask SOP ops `s_bcnt[01]_i32_b64` / `s_ff[01]_i32_b64` / `s_wqm_b64` / `s_bfm_b64` even when the mask is an ordinary SGPR pair; mesh shaders are always wave64). In wave32 code (a header or FSPX dispatch state that says so) `s_bfm_b64` is 64-bit data instead: the translator writes `((1 << (S0 & 63)) - 1) << (S1 & 63)` to the pair, `tools/lane_masks.py` leaves it data, and it doesn't count against an FSPX program's wave32 state. The pipeline library's wave32 compute programs build an S# in place with it (`s_bfm_b64 s[88:89], 2, 54`, then `s_mov_b64` of words 2-3; 958 programs, [shader_library.md](shader_library.md)). Only constant operands are translated there; none other is seen. `tests/semantic/test_wave32_bfm64_data.py`. Wave size comes from the sidecar `fssm/.fssm` header flags word `u32[0xD4]` bit 5 (`0x20` = wave32, `0` = wave64; `fssm_header.wave_size()`), cross-checked against wave64/wave32 code markers (`WAVE64_RE` / `WAVE32_RE`: a contradicting header and code listing raises `Unsupported`), and falls back to the code-marker heuristic (64-bit EXEC/VCC writes, `exec_hi`, `v_mbcnt_hi`, `*_saveexec_b64`/`*_wrexec_b64`, and 64-bit lane-mask SOP ops `s_bcnt[01]_i32_b64` / `s_ff[01]_i32_b64` / `s_wqm_b64` / `s_bfm_b64`, plus wave64 for mesh shaders) when no `FSSM`-magic sidecar is present (synthetic listings). **An FSPX program** (the FidelityFX DLL's, no FSSM blob) takes its wave size from its dispatch state instead: kind 0 word 4 bit 20, set = wave32 (`fspx/.json` `wave32`). Only a strict marker (`WAVE64_RE` against wave32, `WAVE32_RE` against wave64) contradicts it and raises `Unsupported`; a `_b64` op on `vcc` or `exec` does not, since these programs move `vcc` as an ordinary SGPR pair. Without that field the heuristic stays. Confirmed on the 29 programs of 1.0.2.1: strict markers never contradict the bit, the `RSRC1` VGPR granule fits it in all 21 programs that decode cleanly, and `PSV0` lane counts agree with it in all 5 that state one ([fspx.md](fspx.md), "Kind 0: dispatch state"). Translated with the bit, the 4 programs the heuristic got wrong change size, and the other 22 translated modules are byte-identical. CPU-checked by `tests/semantic/test_fspx_wave_size.py`, including a `v_readlane_b32` whose result differs between the two sizes; `vk_pipeline_check` builds all 26 modules. Not GPU-checked on these programs' own data. Confirmed across all 26,503 corpus blobs with 0 contradictions against GFX10 SOP1/SOP2/SOPC/VOP3 encodings: 23,841 wave64 (1,154 CS, 195 GS, 9,282 MS, 10,974 PS, 2,236 VS) and 2,662 wave32 (1,535 CS, 1,127 PS); the code-marker heuristic alone misclassified 2,287 markerless wave64 shaders as wave32 (287 CS: 162 straight-line and 125 branchy, including 11 with `v_readlane_b32`, 35 `v_readfirstlane_b32`, 29 `ds_swizzle_b32`, 14 `s_barrier`; 943 PS: 906 straight-line and 37 branchy; 1,057 VS: 1,020 straight-line and 37 branchy); CPU-checked by `tests/test_fssm_header.py` and `tests/test_fssm_wave_size.py`. Until 2026-11-21 a mask-only wave64 program with no EXEC markers was translated as wave32, so `s_bcnt1_i32_b64` counted one half (#210). GPU-checked with `runtime/test/shaders/cs_w64_mask_detect.asm` (48 set bits of `(lane & 5) != 0`) on NVIDIA GeForce RTX 5060 under `LEONIDA_W64_EMULATE=1`. The hardware lane is exact in compute and mesh shaders (LocalInvocationIndex mod 64 or 32) and is used by `v_mbcnt` and EXEC writes. In other stages it's the subgroup lane. Constant EXEC writes (`s_mov_b32 exec_lo/exec_hi, K`) set each lane from its own bit of K, as `(K >> lane) & 1` (shift and mask: Intel's Windows driver evaluated `OpBitFieldUExtract` of a constant that fits in 16 bits with the lane taken mod 16, so `exec_lo = 0xffff` ran all 32 lanes; GPU-checked with `runtime/test/shaders/cs_exec_const.asm` on Intel UHD Graphics 770, driver 32.0.101.6129, and NVIDIA GeForce RTX 4080 SUPER); before, any non-zero constant turned every lane on. A register written to `exec_hi` sets lanes 32–63 only. VCC's halves follow the same rule while VCC holds a lane mask: a 32-bit write to `vcc_lo` sets lanes 0–31 of the mask and one to `vcc_hi` lanes 32–63 (until 2026-11-22 a `vcc_lo` write set all 64 lanes and a `vcc_hi` write never reached the mask that `s_cbranch_vccz`/`v_cndmask` read; CPU-checked by `tests/semantic/test_wave64_vcc_half_write.py`, not GPU-checked). Mask and `0`/`-1` half-writes to `vcc_lo`/`vcc_hi` keep VCC tracked as a lane mask across subsequent ops (`s_bcnt1_i32_b64`, further half-writes), whereas plain-data writes (`s_buffer_load_dword vcc_lo`, `s_load_dword`, scalar ALU, non-mask constants) end VCC's mask state and store the scalar word across all 64 lanes instead of updating only one mask half (confirmed on 1 wave64 PS in the 1.0.2.1 corpus and `tests/semantic/test_wave64_vcc_half_write.py`). GPU-checked with `runtime/test/shaders/cs_exec64.asm`: lanes 16–47 enabled from two constants, exact on a 32-wide-subgroup GPU. Still approximate on 32-wide subgroups: cross-lane ops between the two halves of a wave64 (readlane/permlane/DPP/shuffles across lane 31/32, wave-wide reductions). The metadata index marks every wave64 shader so a runtime can request `requiredSubgroupSize = 64` where supported (AMD), which makes those exact too. | -| Lane select (`v_readlane_b32` / `v_writelane_b32`) | The lane is **S1[4:0] in wave32** and S1[5:0] in wave64, from an SGPR or a constant, and EXEC is ignored (RDNA 3 ISA guide pseudocode for both opcodes; RDNA 2 has the same encoding and gives no pseudocode). **Until #488 (SHADER-52) a wave32 shader masked with 63 as well**: a lane select of 32 or more wrote no lane, and a read shuffled from a lane past the end of a 32-wide subgroup, which SPIR-V leaves undefined (NVIDIA wraps it, so reads happened to come out right there). Found by the FUZZ-7 cross-lane fuzzer: 23 of 100 random wave32 programs, each minimized to `s_mov_b32 s28, K; v_writelane_b32 vD, x, s28` with K ≥ 32. GPU-checked with `runtime/test/shaders/cs_w32_lane_wrap.asm` (25 16 777 777) on NVIDIA GeForce RTX 5060 (#488) and RTX 4090 (subgroup 32, driver 621.14); `tests/test_translate.py` checks the masks in the SPIR-V, and `tests/semantic/test_wave32_lane_select.py` runs the shader across 32 lanes, where a mask of 63 is an out-of-range shuffle. | -| First active lane in a vertex shader (`v_readfirstlane_b32`, MoltenVK) | A native `v_readfirstlane_b32` is a ballot of the EXEC lanes, its lowest set bit, and a shuffle from that lane (lane 0 when no lane is on). **In a vertex shader the lowest bit is taken with `FindILsb` over the ballot's four words** (the lowest non-zero word wins), not with `OpGroupNonUniformBallotFindLSB`. The two give the same lane, because a ballot has no bit at or above the subgroup size. Other stages keep `BallotFindLSB`; the `--wave64-emulate` form already used `FindILsb` on its two mask words. Why: MoltenVK lowers `BallotFindLSB`, like the `SubgroupSize` built-in, to Metal's `threads_per_simdgroup` input, which a vertex function can't declare ("invalid 'threads_per_simdgroup' attribute for input declaration in a vertex function"), so every VS with a readfirstlane failed to compile there. **Confirmed on an Apple M4 (MoltenVK 1.4.2):** hand-written VS with `subgroupBallotFindLSB` or `gl_SubgroupSize` fail, and ballot, shuffle, broadcast-first, elect, votes, and ballot + `findLSB` + shuffle (32- and 64-lane forms) create. Corpus (1.0.2.1, translated from `4eb6155d`): 572 of the 2,236 VS contain `v_readfirstlane_b32`, and exactly those 572 modules change; all 2,236 stay `spirv-val`-valid. VS pipelines on the M4 go from 667 to 672 of 2,236 on main (the rest fail on the subgroup lane built-in, #1784), and from 1,662 to 2,233 with #1784's vertex-subgroup workaround (its flag is not on main) (the 571 `threads_per_simdgroup` failures are gone). `tests/semantic/test_vs_readfirstlane.py` runs it on the wave interpreter with the first EXEC lane in word 0 and word 1. | -| Wave64 emulation (`--wave64-emulate`) | Wave64 compute and mesh shaders exact on **any** subgroup size (32-wide NVIDIA, Intel, AMD in wave32 mode), with no subgroup operation at all. One invocation is still one lane. Everything a lane needs from the rest of its wave goes through a Workgroup buffer `%x_buf`: votes (`s_cbranch_vccz/vccnz/execz/execnz`, SCC of mask ops, `s_cmp` of masks), whole-mask words (`s_bcnt1`, `s_ff1`, `v_mbcnt`), `v_readlane`, `v_readfirstlane`, `ds_bpermute`, `ds_swizzle`, `v_permlane16/x16`. The program runs in rounds: in each round every wave that is neither done nor waiting at `s_barrier` runs one segment of its program (a basic block, cut at each cross-lane op), then the whole workgroup meets at one `OpControlBarrier` (Workgroup, AcquireRelease, workgroup + uniform + image memory) that sits in uniform control flow, because every invocation runs every round. A cross-lane op ends its segment after the lane has stored its value (per-lane data, double-buffered by round parity) or ORed its bit (two mask words per wave, three slots by round mod 3, each slot cleared two rounds after it was read); the code after it runs one round later, when all 64 lanes have written. SSA values live across a cut go through Function variables. `s_barrier` is a scheduler state: the wave stops running segments until every wave that isn't done is waiting, which is also how hardware counts finished waves. A memory access that conflicts with an earlier one in the same segment (read after write, write after read, write after write; LDS and buffer/image memory separately) starts a new round, so two halves of a wave in different subgroups access memory in instruction order, as the lanes of one hardware wave do. A scalar load (`s_load*`, `s_buffer_load*`) counts as a buffer read: until #1587 it was left out, so a store and a later scalar load of the same address shared a segment and the half in the other subgroup could load before this half had stored (`valu_fuzz.py --family mem --emulate`: lanes 32-63 read the fill pattern after an `s_buffer_load`/`s_load` of the slot lane 0 had written, on RDNA1 RADV and an RTX 5060; `v_readfirstlane_b32`, which gives that slot, already reads the whole wave). Pinned by `tests/semantic/test_w64x_scalar_load_order.py` (no segment of the emitted rounds accesses buffer memory after a write or writes after a read; three of its five cases fail without the rule). Confirmed by that CPU test and the ordering argument above; the race does not show on an RX 7900 XTX (AMD 26.10.1 LLPC, Windows 11): `valu_fuzz.py --family mem --seed 5 --programs 21 --wave 64 --emulate` matches 21/21 before and after the rule (3 runs each), so a GPU reproduction on RDNA1/RADV (where #1587 was found) is still pending. Not ordered: sampling an image the wave wrote. The missing lanes of a partial last wave read as 0. Without the flag the output is unchanged, apart from two fixes that apply to every wave64 compute/mesh shader: `v_writelane_b32` selects the lane by the wave lane (on a 32-wide subgroup writes to lanes 32–63 were lost; `cs_w64x_writelane`), and `ds_bpermute_b32` (see the LDS row). Fewer rounds, same results: a whole-mask read (`s_bcnt1`, `v_mbcnt_lo/hi`, ...) of the value of the same register (or EXEC) that an earlier read in the block already exchanged reuses that exchange (the value's identity is the SSA id last stored to the register, forgotten at block start and at any label); and a block that ends in a voted branch (`s_cbranch_vccz/vccnz/execz/execnz`) runs its successor in the round that reads the vote, since that segment only reads the vote and picks the next block (an inner loop in the scheduler, flag `%x_chain`). Both rules are pinned by `cs_w64x_mask_reuse` (a mask register and EXEC rewritten between reads), `cs_w64x_mask_reuse2` (EXEC read twice, a read after a buffer store, one half of a mask pair rewritten while the other is kept, a voted branch whose successor starts with a load of the other half's earlier store) and `cs_w64x_chain_barrier` (a voted branch whose successor starts with `s_barrier`, two waves): expected values from the ISA, first run on the AMD 880M with its native 64-wide subgroup, then emulated on both GPUs; `tests/test_translate.py` counts the exchanges in the SPIR-V (one per value, a new one after a rewrite of the register or EXEC), and the translator refuses (`Unsupported`) a voted branch whose segment was not started by the vote's own round. Under `--wave64-emulate`, `tools/wave64_emulate_opt.py` runs three exact CFG/dataflow passes to eliminate redundant scheduler rounds and global `OpSwitch` blow-up (#884): (1) backward `SCC` liveness skips `scc_from_mask` / `scc_any_half` votes on lane-mask ops (`s_*_saveexec_*`, `s_andn1/andn2_wrexec_*`, `s_and/or/xor/andn2/orn2/nand/nor/xnor/not_b64`, `s_wqm_*`) whenever `SCC` is dead-out (never read before an unconditional overwrite or `s_endpgm`), (2) safe lane-local `s_cbranch_execz`/`execnz` region folding inlines single-entry, single-exit post-dominated regions with no cross-lane ops, no `s_barrier`, no unmasked side effects, no `write_all_lanes` mask spills, no `EXEC`-widening, no live-out scalars, and for each memory domain (`mem`/`lds`) either read-only accesses or an acyclic single write/atomic behind `if (%active)` (issuing any uniform `x_memory_order` split/barrier before the branch — including scalar `s_load*`/`s_buffer_load*` per #1587 — and chaining single-predecessor continuations), and (3) structured emulation (`plan_structured_emulation`, `control_flow = "emulated wave64 structured"`) removes the global round-loop `OpSwitch` on multi-superblock reducible CFGs without non-uniform 32-bit half-mask SCC: single-wave workgroups (`<= 64` threads) run 100% inline structured SPIR-V with direct workgroup barriers (`0` `OpSwitch`, `0` `x_spill`, strictly monotone GEN/KILL 4-bit `dirty_in` memory ordering across blocks and loop back-edges), while multi-wave workgroups (`> 64` threads, without divergent `s_barrier`) emit post-dominating spine blocks and barrier-free guards/loops (including live-out scalars, single-write stores, `EXEC`-widening, and read-only loops) inline and isolate any remaining wave-divergent barrier regions into local mini-schedulers (or a tail scheduler at early `s_endpgm`). Checked on the CPU by `tests/semantic/test_wave64_emulate_opt.py` (40/64/128/256-thread workgroup interpreter with strict uniform barrier checks, ScreenProbes-shaped chains, nested/reused `saveexec` folds, single-store WAR/RAW ordering, single-wave `inline_all` loop-carried WAR, monotone `dirty_in` regression after `x_round`, multi-wave `structured_hybrid` + local `mini_scheduler`, divergent `s_barrier` fallback, `cs_w64x_saveexec_b64.s` fixture, and negative controls; **not yet GPU-verified** for the structured emulation pass). In addition, `wave64_emulate_opt.py` excludes lane-mask `s_flbit_i32_b32`/`s_flbit_i32` and mixed mask+data `s_cmp_eq_u64`/`s_cmp_lg_u64` from folded/sync-free blocks and `Gen.x_memory_order` skips `ds_nop` (matching `_x_memory_order_access`), pinned by `tests/semantic/test_wave64_emulate_barriers.py` (CPU workgroup interpreter only, not GPU-checked). (1) backward `SCC` liveness skips `scc_from_mask` / `scc_any_half` votes on lane-mask ops (`s_*_saveexec_*`, `s_andn1/andn2_wrexec_*`, `s_and/or/xor/andn2/orn2/nand/nor/xnor/not_b64`, `s_wqm_*`) whenever `SCC` is dead-out (never read before an unconditional overwrite or `s_endpgm`), and (2) safe lane-local `s_cbranch_execz`/`execnz` region folding inlines single-entry, single-exit post-dominated regions with no cross-lane ops, no `s_barrier`, no memory/LDS writes, no unmasked side effects, no `write_all_lanes` mask spills, no `EXEC`-widening, and no live-out scalars behind `if (%active)` (issuing any uniform `x_memory_order` split before the branch — including scalar `s_load*`/`s_buffer_load*` per #1587 — and chaining single-predecessor continuations), keeping all 64 lanes of each wave in the same scheduler round. Checked on the CPU by `tests/semantic/test_wave64_emulate_opt.py` (64-thread and 128-thread workgroup interpreter with uniform barrier checks, ScreenProbes-shaped chains, nested/reused `saveexec` folds, internal loop, `cs_w64x_saveexec_b64.s` fixture, RAW memory/scalar-load ordering, and negative controls for live-out scalars, stores, cross-lane ops, and EXEC-widening). `scripts/bench_wave64.py` times `cs_bench_mix` native and emulated and checks the emulated output bytes against the native AMD run. Cost: one workgroup barrier per segment, and `%x_buf` = (2·L + 6·W + 7) dwords for L invocations in W waves, counted in `lds_bytes`. GPU-checked on NVIDIA GeForce RTX 5070 Laptop (subgroup 32, driver 617.42) and AMD Radeon 880M (subgroup 64, AMD driver 26.11.2 LLPC): `check.py` 38/39 (the mesh test runs in the other script) and `scripts/run_gpu_tests.py` 40/40 on both with `LEONIDA_W64_EMULATE=1`, including every wave64 test (`cs_wavemask`, `cs_wave64_ballot`, `cs_wm_*`) and the cross-half suite `cs_w64x_*` / `ms_w64x_ballot`: readlane and writelane at lanes ≥ 32, readfirstlane with only upper lanes active, branches voted by one lane of either half, ballot + `v_mbcnt_lo/hi` compaction over 64 lanes (also in a mesh shader, 4096/4096 pixels), a 128-thread workgroup whose two waves take different branches, `s_barrier` between waves with different loop counts, LDS read-after-write and write-after-read across the halves without a barrier, a load, ballot and load in one block, and a partial wave (group 40). Without the flag the same RTX 5070 passes 19/37 (the wave64 tests skip there). Not covered: VS/PS/GS (no workgroup memory or barrier there). Known driver bug: AMD's Windows shader compiler for RDNA2 crashes (access violation in `vkCreateComputePipelines`) on many emulated compute shaders with LDS (#857: drivers 32.0.21030 to 32.0.21045.29003, iGPUs and RX 6000; 23.20.44, RDNA3, RDNA4, RADV and NVIDIA are fine), so `make_game.py --wave64-emulate auto` leaves emulation off when the runtime's GPU is such a device and runs wave64 natively (`rdna2_amd_windows` in `tools/vk_subgroup_info.py`, by PCI device ID and driver ID). | -| Workgroup memory limit (SHADER-309) | A compute shader's Workgroup variables, the LDS array plus `%x_buf` (the wave64 exchange, 2·L + 6·W + 7 dwords, or the 3 barrier-round counts, which move into the LDS array when they would push the total past 16,384 B: see "Barrier-round count in LDS (SHADER-579)"), must fit in the device's `maxComputeSharedMemorySize`. `spirv-val` does not check device limits, and RADV (Mesa 27.0.0-devel, RX 7600) dies with SIGFPE in `vkCreateComputePipelines` on a module 4 bytes over 64 KiB (#1721, hand-built repro by YaBulochka). The limit differs per device: 65536 on RADV and NVIDIA, 32768 on the AMD Windows driver (RX 9070 XT, 32.0.32029.2010) and Intel (UHD 770, 101.7092), measured by towade in #1745; the Vulkan minimum is 16384. The translator runs offline, so it has two parts. (1) `rdna2spirv.py` keeps every module under a hard cap, `MAX_SHARED_BYTES` (`--max-shared-memory`, default 65536): the LDS array is the program's need (RSRC2 LDS_SIZE, or the end of the furthest constant-offset access, counted exactly from the offset and the access width: a b32 at offset 65,532 ends at 16,384 dwords) rounded up to a power of two; when that plus `%x_buf` is over the cap but the need still fits, the array shrinks to the RSRC2 allocation and its accesses are bounds-checked (below); when the need itself does not fit (a 64 KiB LDS under `--wave64-emulate`) the shader is refused (`Unsupported`, with the byte counts). The array is clipped to 16,384 dwords, but an RSRC2 allocation over the cap (LDS_SIZE above 128 units, so 66,048 B or more) is counted at its full size and refused, native or emulated, instead of being cut. LDS bounds: RDNA2 LDS does not wrap, and an access outside the workgroup's allocation reads 0 and its write is dropped (RDNA2 ISA sections 3.6.1 and 3.6.6). The wrapped power-of-two array aliases such an access onto a valid word, so when a program's constant offsets reach past its RSRC2 allocation, or the array was shrunk, the array is the allocation and `Gen.lds_access` checks every dword (`index < allocation`, else a read or an atomic's old value is 0 and the write or atomic is skipped): `ds_read*`/`ds_write*` of every width (b64/b96/b128 and read2/write2 per dword), the sub-dword reads and writes, every LDS atomic, `ds_cmpst`, `ds_mskor`, `ds_wrxchg*`. `ds_swizzle`/`ds_bpermute`/`ds_permute` do not use `%lds`; `ds_append`/`ds_consume` were already refused. Every other shader keeps the wrapped array and emits no check, as before. **No game shader takes this path.** Counted over a 1.0.2.1 corpus by towade (#1882, counts only), and again at `main` `aa2988cc` by running `translate()` on every CS: with the exact need (offset + access width), none of the 485 LDS-using CS reaches past its RSRC2 allocation with a constant offset, and none is shrunk, natively or with `--wave64-emulate`. So none gets a bounds check (no `OpULessThan` added), and only the synthetic tests below exercise it. The earlier "16 of 486" came from the older offset + 4-dword estimate; at `aa2988cc` that bound flags 37 of the 485, all inside their allocation. Hypothesis, not yet counted over the corpus: the 16 of 486 LDS-using CS that index past LDS_SIZE with constant offsets (the Compute shaders row) now read 0 there, as the ISA says, where they used to read the wrapped word. Counted over a 1.0.2.1 corpus by towade (#1882, counts only): with the exact need (offset + access width) none of the 485 LDS-using CS reaches past its RSRC2 allocation with a constant offset, so none gets a bounds check (no `OpULessThan` added, native or emulated); the "16 of 486" in the Compute shaders row came from the older offset + 4-dword estimate. `%x_buf` is already sized to the workgroup's waves, so it has nothing to give back. `lds_bytes` in `index.json` is the module's whole Workgroup total (LDS, `%x_buf`, a mesh shader's `%ms_counts`). (2) The D3D12 shim's `create_compute` compares `lds_bytes` with the device's `maxComputeSharedMemorySize` and refuses the pipeline with a log line (`E_NOTIMPL`) instead of creating an invalid one. Pinned by `tests/semantic/test_cs_shared_memory_limit.py` (Workgroup bytes counted from the emitted SPIR-V: under the cap unchanged, shrunk to the 51,200 B allocation and bounds-checked, the exact-cap boundary, an access ending at 64 KiB counted exactly, a 64 KiB LDS refused when emulated and accepted natively, a native 66,048 B allocation refused, run through `spirv_mini_interp`: an out-of-range write dropped with the word it would wrap to intact, out-of-range reads (b32, u16) giving 0, a b64 write straddling the allocation's end, out-of-range atomics returning 0 and changing nothing, and an in-range shader with no check; `lds_bytes` equal to the SPIR-V total) and `shader_library_test` (`lds_bytes` read from the index). Confirmed by those CPU tests only; GPU runs (RADV; AMD Windows and Intel at 32 KiB) are pending. Not covered: mesh shaders against `maxMeshSharedMemorySize`. | -| Wave64 leading-bit scans | With `--wave64-emulate`, `s_flbit_i32_b32` and `s_flbit_i32` of a lane mask use the same wave-wide exchange as `s_bcnt1` and `s_ff1`. These reads prevent lane-local EXEC-zero folding and require synchronized scheduling in wave-divergent blocks. Plain scalar inputs still allow the fold. Hand-written compute shaders in `tests/semantic/test_wave64_emulate_opt.py` check EXECZ at 64 and 128 threads and a branch on SCC taken by just one wave at 128 threads. The strict CPU workgroup interpreter observes the unsigned scan of VCC_LO = 8 returning 28 in the expected invocations. Both scan forms pass `spirv-val --target-env vulkan1.2`. | -| Wave64 emulation: scalar exits from a folded EXECZ region | A folded lane-local `s_cbranch_execz`/`execnz` region may leave to its join from inside, for example `s_cmp` + `s_cbranch_scc0/scc1` straight to the label that restores EXEC. The ISA then skips the rest of the region for the whole wave. `find_local_exec_folds` in `tools/wave64_emulate_opt.py` builds the region's sub-CFG with an exit node for every edge to the join, so `cfg_structure.structure` puts each later block of the region behind a `%pc` guard; the exit node itself emits nothing. Before this the edge was dropped and the block after the branch ran whenever the lane was active. Confirmed on the CPU against the native wave64 translation and the ISA: `tests/semantic/test_wave64_emulate_opt.py` `test_folded_region_scalar_branch_to_join_skips_the_rest` (taken and not-taken `scc0`/`scc1`, 64 and 128 threads, the region still folded) fails before the change on the four taken cases. **Not GPU-verified.** | -| Barycentric fallback (`--bary-fallback`) | For devices without `VK_KHR_fragment_shader_barycentric` (NVIDIA Pascal, for one), and for Mesa ANV's known BaryCoordKHR.i bug (SHADER-925). The raw pair a PS reads comes from an ordinary vec3 input, `%bary`, at the lowest location none of the shader's attributes uses, instead of `BuiltIn BaryCoordKHR`. The module needs neither the `FragmentBarycentricKHR` capability nor the extension, and the index records the location as `bary_fallback_input`. `tools/bary_fallback_gs.py` writes a pass-through geometry shader that supplies (1,0,0), (0,1,0), (0,0,1) at the triangle vertices. GPU-checked on NVIDIA Pascal and Intel Arc B580/Mesa ANV: ANV native `ps_uniform_branch` and `ps_scc_mask32` fail with i=0.0, while the fallback passes and `ps_bary` passes natively. `make_game.py` and `scripts/run_gpu_tests.py` select the fallback automatically for Mesa ANV. `LEONIDA_BARY_FALLBACK=1` forces fallback and `LEONIDA_BARY_FALLBACK=0` forces native barycentrics consistently in both entry points; explicit `--bary-fallback` also forces the fallback in `make_game.py`. The standalone `build.py`/`check.py` path follows the same variable/probe rule. Checked in `tests/semantic/test_bary_fallback.py` and the builder/runner wiring tests. | -| Metadata index | `spirv/index.json`: one entry per translated shader with its stage, `wave64` / `subgroup_size`, SPIR-V capabilities and extensions, the Vulkan **features** to enable (barycentrics, interlock, mesh, geometry, Float64, Int64, buffer device address, write-without-format, `shaderFmaFloat32` for `--fma khr`, …), `needs_maintenance8`, the descriptor bindings it uses (set 0), push-constant size, `local_size`, `user_sgprs` (CS), `lds_bytes`, mesh `max_vertices`/`max_primitives`/`params`, geometry inputs/outputs, vertex-input locations and types, full `vertex_input_signature` (ISG1 register/mask/system-value/component-type, for PSO lookup), `wave64_emulated` (true for VS/PS/GS wave64, which the translator emits as per-subgroup code with no cross-half exchange, and for compute/mesh translated with `--wave64-emulate`; the runtime does not use it: it reads `wave64`, `subgroup_size` and `wave64_exchange`), `dynamic_format` (runtime V# FORMAT: codes outside FORMATS decode to 0) / `fixed_format_codes`, `src_sha256` and optional `fssm_sha256` (via `--fssm-dir`), PS system inputs, `bary_fallback_input` (`--bary-fallback`: the location of the barycentric input), `mesh_compute` (`--mesh-compute`: the slot layout and push-constant size), `pc_tail` (`--pc-tail-ubo`: the set, binding and size of the uniform block that holds the push-constant tail), and input/output locations. A shader translated with `--wave64-emulate` carries `wave64_exchange: "workgroup"` and `subgroup_size: null`: any subgroup size is exact, request none. Otherwise `subgroup_size` (64 for wave64, 32) is what the PSO asks for through `VkPipelineShaderStageRequiredSubgroupSizeCreateInfo` where the device lists the stage in `requiredSubgroupSizeStages` (docs/d3d12_vulkan.md section 3.2): that list is the driver's, not "compute/mesh only". The AMD Windows driver reports FRAGMENT, COMPUTE, TASK and MESH (measured on a Radeon 880M, driver 26.11.2, sizes 32..64), and current Mesa RADV on GFX10+ reports COMPUTE, FRAGMENT and task/mesh (`src/amd/vulkan/radv_physical_device.c`, `requiredSubgroupSizeStages`, Mesa main at 152b9cde; older Mesa: compute only), so wave64 pixel shaders can run exact there. NVIDIA lists every stage but only size 32, so there a native wave64 shader cannot get 64 and wave64 PS/VS/GS stay 2x32. A runtime can create every pipeline at load time from it without parsing SPIR-V. | -| Full-corpus pipeline build | `vk_pipeline_check pipeline_cache.bin --jobs 4` on an RTX 4060 Ti (NVIDIA 595 driver): **all 26,503 shaders become real pipelines, 0 failures** (cs 2,689, ps 12,101, ms 9,282, vs 2,236, gs 195; graphics stages with generated stub partners). Compile time 40,784 s of CPU (2.84 h wall on 4 threads): cs 23,633 s (mean 8.8 s; the ray-tracing ScreenProbes/RTShadowTrace shaders take 2-19 min each), ps 11,481 s, ms 5,395 s, vs 275 s. The resulting `VkPipelineCache` is 3.81 GB; seeding a run with it makes those pipelines instant, which is what a fast first boot needs. The cache is per driver and GPU, and a shader whose SPIR-V changes compiles again (the checker resumes from the file). Neither register storage (one variable per register) nor smaller SPIR-V cut NVIDIA compile time: the big ray-tracing shaders are expensive as such, so the runtime should compile them in the background rather than block on them. | -| `v_cndmask_b32` source modifiers | `v_cndmask_b32` only moves bits, so a VOP3 `abs` on `src0`/`src1` clears bit 31 and `neg` flips it (`abs` first) as plain bit moves (`OpBitwiseAnd 0x7FFFFFFF`, then `OpBitwiseXor 0x80000000`, `Gen.src_u_sign_mods`), never `FAbs`/`OpFNegate`: a signalling NaN stays signalling and a denormal isn't flushed. Until 2026-11-23 the sources went through `Gen.modify`, and the mini interpreter quieted them (`-v1` of `0x7F800001` gave `0xFFC00001`, not `0xFF800001`). **Not measured on hardware for this instruction**: the rule follows the same VOP3 input modifiers measured as sign-bit moves on `v_cmp_class_f32` (gfx1036, all four IEEE/denorm modes, row "Floating-point class compare" above), and LLVM's AMDGPU backend moves `fneg`/`fabs` through a select into `v_cndmask_b32_e64`'s source modifiers (`AMDGPUTargetLowering::foldFreeOpFromSelect`), which is only exact if they are sign-bit moves. Checked on the CPU and with `spirv-val` by `tests/semantic/test_cndmask_sign_mods.py` (15 words including signalling/quiet NaNs, denormals, zeros and infinities x `v`, `-v`, `\|v\|`, `-\|v\|` x both operands). | -| Wave-uniform branches | VCC and EXEC are wave-wide registers, but one invocation holds only its own lane's bit. `s_cbranch_vccz/vccnz/execz/execnz` therefore reduce the condition across the subgroup (`OpGroupNonUniformAny`), so the whole wave takes the branch together, as on hardware. Before this, each lane decided alone. A lane could skip scalar instructions that the hardware wave executes (its SGPRs went stale for later code), and cross-lane ops or barriers inside the block saw a split wave. `v_cmp`/`v_cmp_class`/64-bit compares now write 0 for inactive lanes (hardware VOPC behaviour), so the reduction sees the true mask. GPU-checked with `runtime/test/shaders/ps_uniform_branch.asm`: lanes whose own VCC bit is 0 run the block's scalar add when their wave has any set bit. `s_cbranch_scc0/1` stay per lane; SCC is uniform as long as the SGPRs feeding it are. | -| Compute shaders | FSSM header word **0x138 = `COMPUTE_PGM_RSRC2`**: USER_SGPR [5:1], TGID_X/Y/Z_EN [9:7], TG_SIZE_EN [10], TIDIG_COMP_CNT [12:11], LDS_SIZE [23:15] in 512-byte units. Words **0x13C/0x140/0x144 = thread-group size**. Counted over all 2,689 CS listings of 1.0.2.1 by the SGPRs each reads before writing (operand roles from `shader_meta._split_operands`, over the code `translate()` keeps; in wave64 code a lane mask printed as one SGPR covers the pair; an earlier check gave 2,281 exact): 2,540 read nothing past the user SGPRs and enabled TGIDs (2,193 up to the last of them, 342 fewer, 5 none), and the other 149 overshoot only through loop-carried registers in the straight-line check: every extra read follows a branch, and the register is written later in program order. Followed through the CFG (written on every path before the read), 22 still overshoot; each extra register is written on some other path (only loop-carried ones in 15), so these are values undefined on some path, not a missing input. Read raw, 268 overshoot: the other 119 are listings with embedded data words, decoded as instructions. 0x110, which looked similar, doesn't match. Layout: s0..user−1 = user data (push constants), then the enabled workgroup IDs (`WorkgroupId`), and v0/v1/v2 = thread ID x/y/z (`LocalInvocationId`, separate VGPRs on GFX10). Example: the 1,013 shaders with RSRC2 `0x998` have 12 user SGPRs, group ID x/y in s12/s13, and compute x = s12·32 + v0. Shaders with TG_SIZE_EN are rejected for now. GPU-checked with `runtime/test/shaders/cs_lds.asm` through `runtime/test/vk_compute_test.cpp`: 4 groups × 64 threads, LDS exchange between the two waves of a group behind `s_barrier`, store through a V# into the device-address heap, 0 mismatches. | -| Signed-byte dot products | `v_dot4_i32_i8 D, S0, S1, S2` (VOP3P) is S2 plus the sum of the four products of the sign-extended bytes of S0 and S1, modulo 2^32; `v_dot4c_i32_i8 D, S0, S1` (VOP2) adds the same sum to D. Emitted as four pairs of `OpBitFieldSExtract`, `OpIMul` and `OpIAdd`. **Confirmed on RDNA2 hardware** (gfx1036, raw kernels through `tools/hw_oracle`): 10 operand sets, both instructions and both source orders of the accumulating one, with sign-mixed bytes and sums that wrap; the measured words are the table in `tests/semantic/test_alu_dot4_i8.py`. `clamp` and `op_sel`/`op_sel_hi` are translated and checked against the same `gfx1036` hardware table: `clamp` saturates `v_dot4_i32_i8` to signed 32-bit `[-2^31, 2^31-1]` (both overflowing sets), and `op_sel`/`op_sel_hi` pick the 16-bit half of S0/S1 for byte pairs 0..1 and 2..3 (e.g. `op_sel` 2 / `op_sel_hi` 5 exchanges the 16-bit halves of S1, matching all 5 measured sets — the form of the 89 words `llvm-mc` does not decode, [fspx.md](fspx.md)); non-default S2 half selection stays refused. `neg_lo`/`neg_hi`, which `llvm-mc` accepts on `v_dot4_i32_i8` only, are not ignored (`neg_lo` flips bit 15 and `neg_hi` bit 31 of S0 or S1, and on S2 `neg_hi` clears bit 31 before `neg_lo` flips it; 5 sets under 8 forms, 45 words): any set bit stays Unsupported, while an all-zero field is the plain instruction. Counts: the 29 FSPX programs use the pair 27,271 times (`v_dot4c_i32_i8` 25,813, `v_dot4_i32_i8` 1,458), all in 13 programs; none of the game's own 26,503 shaders has either encoding (0 of the 12,791 words `llvm-mc` cannot decode there with gfx1013). | -| Workgroup barriers | `s_barrier` (cs/ms) is one `OpControlBarrier` (workgroup scope, workgroup memory). On RDNA every `s_barrier` counts against the same workgroup barrier and a wave that has ended no longer counts, while Vulkan requires a barrier to be reached by every invocation in uniform control flow. Under `--wave64-emulate` the round loop keeps a single barrier at the top level, so this holds. **Native wave32 compute shaders run in barrier rounds** when an `s_barrier` sits anywhere but a top-level block of the structured tree (one every invocation runs): under a guard, in a loop, or in the dispatch loop (`needs_barrier_rounds`, `bar_scheduler`). That is the emulated loop without its cross-lane part: `s_barrier` ends a segment, each invocation runs its blocks until its next `s_barrier` or the end, then the whole workgroup meets at one `OpControlBarrier` (the same workgroup/acquire-release/workgroup-memory semantics) at the end of the round. A wave that is done no longer holds the others, and a per-round count of the invocations not done (three `Workgroup` words, by round mod 3) ends the loop. A wave that is done no longer holds the others, and a per-round count of the invocations not done (three `Workgroup` words, by round mod 3, or a borrowed LDS word with a large LDS: "Barrier-round count in LDS (SHADER-579)") ends the loop. Cross-lane operations stay subgroup operations, as in the dispatch loop, since a wave's lanes run the same segment. A barrier in a top-level block keeps the single `OpControlBarrier` in place. In the 1.0.2.1 corpus 43 of the 55 wave32 cs shaders with `s_barrier` have one nested (SHADER-91's count), so those 43 now run in rounds. Why: an Intel GPU does not survive the nested form. `cs_barrier_divergent.asm` (two barrier sites in different branches), `cs_barrier_early_end.asm` (the other waves end without a barrier) and `cs_barrier_loop.asm` (a barrier in a loop whose trip count differs per wave) each lose the device (`vkQueueWaitIdle` → `VK_ERROR_DEVICE_LOST`) on an Intel Arrow Lake Xe-LPG iGPU (Windows 32.0.101.8132), and `cs_barrier_divergent` hangs or writes nothing on a UHD 770 (101.6129, #634). With barrier rounds all three pass there and on an RTX 5070 Ti Laptop (617.42). NVIDIA passed them before too (RTX 4070 Ti on 610.88 and 621.24, RTX 5090 on Linux 595.99, RTX 5070 Ti). **Still not proven on the native wave64 path** (wave64 cs and every ms, run natively only on AMD's 64-wide subgroups): there the barrier stays where `s_barrier` is, inside a selection or loop construct in every ms and most wave64 cs shaders of the corpus. Branches are scalar, so whole waves take the same path, and RDNA's own barrier counts the way the shader expects. | -| Barrier-round count in LDS (SHADER-579) | Barrier rounds (see "Workgroup barriers") count the invocations not done in `%x_buf`, three `Workgroup` dwords (#930). On a full 32 KiB LDS that made 32,780 B, 12 bytes over the 32,768 B `maxComputeSharedMemorySize` of the AMD Windows (RX 9070 XT) and Intel (UHD 770) drivers, so the runtime refused those pipelines (2 native wave32 cs in towade's 1.0.2.1 corpus, [finding](https://github.com/ItsNotRexed/Leonida/pull/1882#issuecomment-7084298032)). Rule (`bar_counts_in_lds`): when the shader uses its LDS and the LDS array plus 12 bytes is over 16,384 B (the Vulkan minimum limit, so in practice an array of 16, 32 or 64 KiB), there is no `%x_buf`. The count borrows LDS word 0 at the end of each round (`bar_scheduler_tail`): after the round's barrier every invocation is done or waits at `s_barrier`, so no shader code runs; invocation 0 saves the word in a Function variable and clears it, barrier, every invocation not done adds 1 atomically, barrier, all read the count, barrier, invocation 0 stores the saved word back, barrier. The shader sees its LDS bit for bit as before, and the four extra barriers sit where the whole workgroup already waits, so `s_barrier`'s semantics are unchanged; the cost is four more `OpControlBarrier`s per round in those shaders only. Below the threshold `%x_buf` stays (12 bytes fit every device) with one barrier per round; a shader that never touches its LDS also keeps it (no array to borrow from, 12 B in all). A 32 KiB LDS is now exactly 32,768 B and a 64 KiB one 65,536 B (before: 65,548 B, refused or shrunk to its allocation). Not chosen: putting the count in LDS the shader never touches (unprovable with dynamic addresses), or deciding per device (the translator runs offline). Pinned by `tests/semantic/test_cs_barrier_counts_lds.py` (Workgroup bytes from the emitted SPIR-V and `lds_bytes` for 32 KiB, 64 KiB and small LDS, under a 32 KiB `--max-shared-memory`; ring shifts across 10 barriers that read word 0 and an early-ending wave in the workgroup interpreter, whose LDS starts as 0xDEADBEEF, in both wave orders). Confirmed by those CPU tests only; GPU runs on the 32 KiB devices are pending. | -| LDS | A `Workgroup` uint array sized from LDS_SIZE, rounded up to a power of two that also covers every constant offset (15 of 486 shaders index past LDS_SIZE). Covers `ds_read/write_b32..b128`, `read2/write2` (+`st64`), `u16`/`i16`/`u8`/`i8` reads (also `ds_read_u16_d16`/`_d16_hi` and, since SHADER-85, `ds_read_u8_d16`/`_d16_hi` and `ds_read_i8_d16`/`_d16_hi`: the byte is zero- or sign-extended 8→16 into one half of the destination VGPR and the other half is kept, per the RDNA2 ISA DS opcode descriptions (opcodes 162–165) and as for the u16 d16 reads; GPU-checked with `cs_w32_lds_u8_d16.asm`, byte values 0x80/0xFF/0x7F with a non-zero `offset:`), `b16`/`b8` writes (atomic and/or, so neighbouring lanes don't race; a 16-bit read or write at byte 3 of a dword also reads or writes byte 0 of the next dword, as llc-15 `-mcpu=gfx1030 -mattr=+unaligned-access-mode` emits one `ds_read_u16`/`ds_write_b16 ... offset:3` for an align-1 halfword; until 2026-11-22 the reads extracted 16 bits at bit 24, undefined in SPIR-V, and the writes kept only byte 3; `tests/semantic/test_lds_u16_cross_dword.py`), the add/sub/min/max/and/or/xor atomics with and without return, `wrxchg`, `cmpst` (`OpAtomicCompareExchange` with DATA as comparator and DATA2 as value), and `ds_bpermute_b32` as a subgroup shuffle. GPU-checked with `cs_w32_lds_u8_d16.asm`, byte values 0x80/0xFF/0x7F with a non-zero `offset:`), `b16`/`b8` writes (atomic and/or, so neighbouring lanes don't race), the add/sub/min/max/and/or/xor atomics with and without return, `wrxchg`, `cmpst` (`OpAtomicCompareExchange` with DATA as comparator and DATA2 as value), and `ds_bpermute_b32` as a subgroup shuffle. `ds_permute_b32`, its forward (scatter) form, has no Vulkan equivalent: each source lane that is on in EXEC publishes `((vAddr + offset) >> 2) mod 32` and each destination lane scans the 32 sources of its half and keeps the last one that targets it (a shuffle of target and data per source lane; under `--wave64-emulate` two buffer rounds and a Function variable instead). Per the ISA pseudocode (`tmp[0..63] = 0`; `next if !EXEC[i]` on the source; `VGPR[VDST][i] = tmp[i]` only `if EXEC[i]`): a destination lane nobody targets gets 0, an off source sends nothing, an off destination keeps its VDST, and the half rule above applies as for `ds_bpermute_b32`. When several sources target one lane the ISA leaves the winner unpredictable ("the value from one of the writers"; its pseudocode says the highest-numbered); the translator takes the highest, and nothing may depend on it. Confirmed by the GPU tests `cs_w32_permute.asm` and, per half of a wave64, `cs_w64x_permute.asm` (SHADER-90: rotation, offset, unwritten lane = 0, off destination keeps its value, off source does not win), `cs_w32_partial_permute.asm` (a 20-thread wave32: a launched lane whose source lane was never launched gets 0, and a send to a missing lane is lost; the same words from a raw 20-thread `hw_oracle` kernel on `gfx1036`) and `tests/semantic/test_ds_permute.py`. **Hardware-verified on RDNA2 (`gfx1036`, AMD Ryzen 7 9800X3D iGPU, Linux AMDGPU DRM via `tools/hw_oracle`, wave32 and wave64, SHADER-133)** with `tools/ds_permute_probe.py` (9/9 cases exact in both wave sizes): unaddressed active lanes get 0, off destinations keep VDST, off sources send nothing, 2-/4-/32-way collisions deterministically take the highest-numbered active lane in the 32-lane half (matching the translator), `vAddr + offset` carries from the low 2 bits before `>> 2` mod 32, wave64 runs as two independent 32-lane halves (`+32` wraps within each half), and missing lanes of a partial wave (20 threads in wave32, 40 in wave64) send nothing. A source lane that is off in EXEC reads 0 and an off destination lane keeps its value (RDNA ISA §10.4.4), in wave32 as in wave64. In wave64 the permute also runs as two wave32s: each half reads lanes of its own half. Until 2026-11-21 lanes 32–63 of a 64-wide subgroup read the low half and inactive sources kept their value (`cs_w64x_bpermute`, AMD Radeon 880M); the wave32 path shuffled the raw value until the same day (`cs_bpermute32`: wave32, EXEC without lanes 8–15, so lane 6 reads 0; GPU-checked on RTX 5070 and Radeon 880M). A source lane that doesn't exist, in the missing lanes of a partial wave, also reads 0: the shuffle result is kept only where a ballot of the running invocations has the source lane, since SPIR-V leaves a shuffle from an invocation that isn't running undefined. Before this, RADV returned stale register values that changed between runs (`cs_w64x_partial`, a 40-thread group, native wave64 on AMD RX 6700 XT, RADV Mesa 26.3.1). Writes and atomics run only in active lanes. Indices wrap at the array size, where hardware would return 0 for out-of-range reads. `s_barrier` = `OpControlBarrier` Workgroup/Workgroup, AcquireRelease + WorkgroupMemory. | -| LDS access order within a wave (`Volatile`) | RDNA2 runs a wave in lockstep with an in-order LDS queue, so a `ds_read` issued after a `ds_write` sees every lane's write with no `s_barrier` between them (`cs_w64x_lds_raw`), and a `ds_write` issued after a `ds_read` does not change what that read returned (`cs_w64x_lds_war`). Translated, a lane is an invocation, and the Vulkan memory model orders nothing between invocations without a barrier or an atomic, so a driver's compiler may move an invocation's load ahead of its own earlier store to another address, or merge two loads of one address. Results consistent with these optimizations were observed with AMD's Windows driver 24.30.46 (LLPC, Vulkan 1.3.302) on a Radeon 880M (RDNA3.5, native 64-wide compute subgroups): on `main` `561b65a8` both tests failed on every run with uninitialized Workgroup memory in all eight words, and in `cs_w64x_lds_war` the second read returned the same words as the first. Rule: every plain LDS `OpLoad` and `OpStore` (`lds_load`, `lds_store` and the two ADDTID forms) carries the `Volatile` memory operand, which prevents elimination, duplication or combination of the access ([SPIR-V memory operands](https://registry.khronos.org/SPIR-V/specs/unified1/SPIRV.html#Memory_Access)). This rule applies to plain accesses only. On that GPU and driver `Volatile` on the store alone or on the load alone made `cs_w64x_lds_raw` return its expected words (hand-edited SPIR-V, 3 of 3 runs each, against 0 of 4 unmodified), and with the rule both tests pass: `run_gpu_tests.py` goes from 210 to 212 of 232 passed with none failing (20 skipped), native and with `LEONIDA_W64_EMULATE=1`. An RTX 5070 Laptop (NVIDIA 621.01) gives the same results before and after (183 of 232 native, 214 emulated; `ms_wave_info_s3` fails both times). The operand changes 17 of the 238 test shaders and nothing but those loads and stores. A [full Xbox 1.0.2.1 corpus comparison](https://github.com/ItsNotRexed/Leonida/pull/6714#issuecomment-7107280378) translated and validated all 26,503 shaders at both 561b65a8 and 58deee34. Only the added operands differed in the 484 compute and 5 mesh modules that changed. The RAW and WAR results establish a workaround on the tested driver. Portable ordering between invocations requires synchronization appropriate to the accesses (see #2345). Under `--wave64-emulate` the halves meet at the round barriers as before; the operand is emitted there too. CPU-checked by `tests/semantic/test_lds_volatile.py` (every plain access form on the wave32, wave64 and emulated paths, and no other access is Volatile). | -| `ds_cmpst_b32` | The non-returning compare-and-store: `M = (M == data0) ? data1 : M`, the same `OpAtomicCompareExchange` as `ds_cmpst_rtn_b32` with the old value dropped (operands vaddr, data0, data1). Source: RDNA2 ISA DS_CMPST_B32. CPU-checked by `tests/semantic/test_lds_atomics_values.py`; GPU-checked by `runtime/test/shaders/cs_lds_b64_cmpst.asm` (hit and miss on an RTX 3070, driver 621.01, Windows 11), and measured on native gfx1100 through `tools/hw_oracle` (hit, miss and hit-to-zero), where GFX11 spells it `ds_cmpstore_b32` with the store value before the compare value. **Not GPU-verified.** GPU-checked by `runtime/test/shaders/cs_lds_b64_cmpst.asm` (hit and miss on an RTX 3070, driver 621.01, Windows 11). | -| `ds_cmpst_f32`/`_rtn_f32`, `global_atomic_fcmpswap`, `buffer_atomic_fcmpswap` | `tmp = M; M = (tmp == CMP as binary32) ? DATA : tmp`, and the returning forms give `tmp` (RDNA2 ISA). The compare is a float compare (`OpFOrdEqual`): −0 matches +0, and a NaN never matches, not even the same bits. `OpAtomicCompareExchange` compares bits, so this is a loop (`Gen.float_cmpswap_loop`): read M, pick DATA or M by the float compare, and swap that in if M still holds what was read. Exact under contention. Operands: `ds_cmpst_f32` takes CMP then DATA, as `ds_cmpst_b32`; the global and buffer forms take `vdata` as {DATA, CMP}, as `cmpswap`. Inactive lanes, bounds and `glc` are as for their integer siblings. **Not measured:** subnormal inputs; the interpreter compares them exactly. `_x2` forms stay `Unsupported`; the image form is #2653's. Until 2026-11-22 all four raised `Unsupported`. CPU-checked by `tests/semantic/test_float_cmpswap.py` (±0, NaN, ∞, a subnormal, no `glc`, buffer bounds, 32 lanes on one dword). **Not GPU-verified.** | -| LDS ADDTID (`ds_read_addtid_b32`, `ds_write_addtid_b32`) | The LDS forms address one dword at `M0[15:0] + offset + 4 * lane`, where `offset` is an unsigned 16-bit byte offset and `lane` is the invocation index within the RDNA wave. The Workgroup array supplies LDS_BASE. The compute/mesh path uses the ordinary LDS addressing and EXEC guard. The GDS form raises `Unsupported`. Source: RDNA2 ISA §10.4 and §12.13 (opcodes 176/177), LLVM GFX1030 assembly syntax. `tests/semantic/test_lds_addtid.py` compares the two forms with ordinary LDS reads/writes over two waves, including partial EXEC and emulated wave64. | -| `ds_add_f32`, `ds_add_rtn_f32` | Atomic binary32 add on LDS (`Workgroup` memory); `ds_add_rtn_f32` returns the exact pre-addition 32-bit value in `vdst`, while `ds_add_f32` discards it. Lowered to a core SPIR-V structured `OpAtomicCompareExchange` (`Workgroup` scope `2`, relaxed `None`/`None` equal and unequal semantics) CAS loop over `%v_lds` (`%uint` storage, `OpBitcast` <-> `%float` + `OpFAdd`, bitwise `OpIEqual` exit check so `NaN` terminates in 1 iteration without looping, returning loop-header `%cur` for `ds_add_rtn_f32` with no `VK_EXT_shader_atomic_float` dependency). Hardware-verified on native RDNA2 (`gfx1036`, Windows 11, driver `32.0.21045.29003`, wave32 & wave64, 0 mismatches): confirmed normal binary32 sums (`1.5 + 2.25 -> 3.75`), signed zero rules (`+0.0 + +0.0 -> +0.0`, `-0.0 + -0.0 -> -0.0`, `+0.0 + -0.0 -> +0.0`), infinities/NaNs (`+Inf + 1.0 -> +Inf`, `+Inf + -Inf -> 0xffc00000` qNaN, quiet NaN payload `0x7fc12345` preserved), exact old-value return on `_rtn_` vs unchanged `vdst` on non-return, `offset:` variants (4, 16, 64, 256, 1020), unaligned byte addressing (unaligned non-4-byte-multiple byte addresses dropped by hardware), `EXEC` inactive-lane masking (0x55555555 leaves LDS untouched by inactive lanes), and wave32/wave64 multi-lane same-address contention (32 and 64 lanes concurrently adding 1.0f yield exact sums 32.0 / 64.0 and return unique permutation chains with zero lost updates). Subnormal note: native `gfx1036` flushed FP32 subnormal inputs/outputs to zero (FTZ/DAZ) in the LDS adder, whereas core SPIR-V `OpFAdd` leaves FP32 denorm flushing to the host Vulkan driver / `DenormFlushToZero` mode. CPU-checked by `tests/semantic/test_lds_add_f32.py`. `M = M + DATA` as binary32 on the LDS dword (RDNA2 ISA, `DS_ADD_F32`); the `_rtn_` form returns the old M. No core SPIR-V atomic adds floats on Workgroup memory, so it is an `OpAtomicCompareExchange` loop with an `OpFAdd` (round to nearest even, `NoContraction`). That is exact under contention: every update is one successful exchange of the value it read. **Not measured:** how the LDS adder treats denormals and NaN payloads; the result is `OpFAdd`'s IEEE sum. The f32 min/max forms are #2495's. Until 2026-11-22 both raised `Unsupported`. CPU-checked by `tests/semantic/test_lds_add_f32.py` (a value grid, the non-returning form, `offset:`, ties to even, -0 + +0, overflow to ±inf, seeded values, against a once-rounded double sum). **Hardware-measured natively on `gfx1100`** (RX 7900 XTX, driver 26.10.1) with `tools/hw_oracle`, 49 cases: the LDS adder **flushes denormal inputs and denormal results to zero** (`0x00800001 + -0x00800000` gives `+0`, not `0x00000001`; `0x007fffff + 0x00800000` gives `0x00800000`, not the tie's `0x00ffffff`; `0x00000001 + 0x00000001` gives `+0`), while the `OpFAdd` the translator emits keeps them, so denormal operands and results are a known divergence. A NaN is quieted with its payload and sign kept (sNaN `0x7f800001` becomes `0x7fc00001`) and when both operands are NaN the DATA operand wins whatever the payloads (`0x7fc00007 + 0x7fc00000` gives `0x7fc00000`); `inf + -inf` gives `0xffc00000`. Normal sums match that model on the same run: ties to even (`1.0 + 2^-24` stays `1.0`, `1.0 + 3*2^-25` goes up), `-0 + -0` is `-0`, `+0 + -0` is `+0`, overflow to `±inf`, and the `_rtn_` form returns the raw pre-op dword, denormal or not. | -| `ds_mskor_b32`, `ds_mskor_rtn_b32` | `tmp = M[A]; M[A] = (tmp & ~DATA) \| DATA2`; the `_rtn_` form returns `tmp` (RDNA2 ISA, DS). Emitted as an atomic AND with `~DATA`, whose result is `tmp`, then an atomic OR with `DATA2`, so the returned value is exact. DATA2 bits outside DATA are ORed in too, as the formula says; it isn't a masked insert. **Approximation:** the memory ends as the single op leaves it unless another lane's op on the same dword lands between the two atomics. Until 2026-11-22 both raised `Unsupported`. CPU-checked by `tests/semantic/test_lds_mskor.py` (a value grid, the non-returning form, DATA2 outside DATA, `offset:`, seeded values). Measured on native gfx1100, including DATA2 bits outside DATA being ORed in, so it is not a masked insert. **GPU-verified** on native RDNA2 (gfx1036, the Radeon iGPU of a Ryzen 7 9800X3D, Windows driver 32.0.21042.62) through `tools/hw_oracle`: 20 of 20 one-thread cases (five M/DATA/DATA2 triples including DATA2 bits outside DATA, both forms, `offset:` 0 and 12) leave `(M & ~DATA) \| DATA2` and return M. **The approximation, measured:** 32 lanes on one dword (M = 0xABCD12FF, DATA = 0xFF, DATA2 = 1 << (lane & 7)) run one lane at a time in lane order on the hardware: each lane returns the word the lane before it left (lane 0 0xABCD12FF, lane 1 0xABCD1201, lane 2 0xABCD1202, …) and the dword ends 0xABCD1280. The two-atomic emission does every AND before every OR, so it would end 0xABCD12FF and return 0xABCD1200 to lanes 1..31 (expected, not run through the translator). **Not GPU-verified.** | -| `ds_{inc,dec,rsub}_u32`, `ds_{min,max}_f32` (and `_rtn_`) | 32-bit LDS atomics lowered inside `Gen.lds_op` via a Workgroup-scope `OpAtomicCompareExchange` CAS loop (no shader float atomic extension needed): `ds_inc_u32` gives `(M >= DATA) ? 0 : M + 1` (unsigned), `ds_dec_u32` gives `(M == 0 \|\| M > DATA) ? DATA : M - 1` (unsigned), `ds_rsub_u32` gives `DATA - M` (wrapping), and `ds_{min,max}_f32` use GLSL.std.450 `NMin`/`NMax` (NaN returns the non-NaN operand, `-0.0 < +0.0`, matching `global_atomic_fmin`/`fmax`). The `_rtn_` forms return the pre-op word in `vdst`; inactive lanes skip the op and preserve `vdst`. Source: AMD RDNA2 ISA DS encoding. CPU-checked by `tests/semantic/test_lds_atomics_cas.py` (edge value grids, NaN/±0/±inf, `offset:`, `vdst` aliasing, inactive lanes, sequential wraparound, Workgroup CAS loop structure, outside-compute and bad-operand rejections). Measured on native gfx1100 (single thread, 28 cases): `ds_inc_u32` gives `M + 1` until `M >= DATA` and 0 from there, `ds_dec_u32` gives `M - 1` or `DATA` when `M == 0` or `M > DATA`, `ds_rsub_u32` wraps, the `_rtn_` forms return the pre-op word, and `ds_{min,max}_f32` take the non-NaN operand and rank `-0.0` below `+0.0`. **Not GPU-verified.** | -| `ds_wrxchg2_rtn_b32`, `ds_wrxchg2st64_rtn_b32` | Two atomic exchanges, addressed as `ds_write2_b32` addresses its dwords: `vaddr + offset0 * 4` and `vaddr + offset1 * 4` (times 64 for st64). `M[A0] = data0` and `M[A1] = data1`, and `vdst` (a VGPR pair) gets the two old words. Both exchanges run before either result is written, so `vdst` may alias the address or data VGPRs. When both offsets name one dword, the second exchange returns `data0`. Each exchange is atomic on its own, not the pair together, as on hardware (two DS operations). Until 2026-11-22 both ops raised `Unsupported`. CPU-checked by `tests/semantic/test_lds_wrxchg2.py` (offsets, st64 = 256-byte steps, the same dword twice, aliasing, a single-VGPR `vdst` rejected). Measured on native gfx1100: with `vaddr` 16 the offsets 0/4 read `vaddr + 0` and `vaddr + 16`, the `_st64_` form's offsets 1/2 read `vaddr + 256` and `vaddr + 512` (64 dwords per step), `vdst` takes the two old words, and with both offsets on one dword the second exchange returns `data0`; `vdst` may alias the address or the data pair, which still lands both data words in LDS and leaves the old words in `vdst`. **Not GPU-verified.** | -| `ds_wrxchg_rtn_b64`, `ds_wrxchg2_rtn_b64`, `ds_wrxchg2st64_rtn_b64` | 64-bit LDS exchanges (two dwords, low first): `M[A] = DATA`, and `vdst` gets the old 64 bits. `wrxchg_rtn_b64` has one element at `vaddr + offset`. The `2` forms have two, at `vaddr + offset0/offset1 * 8` (times 64 for st64), as `ds_write2_b64` addresses them, and `vdst` is four VGPRs. Each dword is its own 32-bit `OpAtomicExchange`, without Int64 atomics on Workgroup memory. All exchanges run before `vdst` is written. **Approximation:** two lanes exchanging into one element at once can tear it, leaving one's low dword with the other's high dword (A.lo, B.lo, B.hi, A.hi), which a 64-bit exchange never does; and the returned pair comes from two reads, so another lane's 64-bit op on the same element between them can show up half done (as for `ds_and/or/xor_b64`). Until 2026-11-22 these three raised `Unsupported`. CPU-checked by `tests/semantic/test_lds_wrxchg_b64.py` (values, `offset:`, `vdst` aliasing the data, both 2 forms, st64 = 512-byte steps, bad operands rejected). Measured on native gfx1100: `M[vaddr]` takes the data pair and `vdst` gets the old pair, the `2` form's offsets 0/2 read `vaddr + 0` and `vaddr + 16` with four old dwords in `vdst`, and the `_st64_` form's offsets 1/2 read `vaddr + 512` and `vaddr + 1024` (64 pairs per step). **Not GPU-verified.** GPU-checked by `runtime/test/shaders/cs_lds_xchg64_ext.asm` (all three forms: both dwords and the returned pair of `ds_wrxchg_rtn_b64`, the four old and four new dwords of `ds_wrxchg2_rtn_b64` at offsets 0/2, the low dwords of `ds_wrxchg2st64_rtn_b64` at offsets 1/2; one lane, on an RX 7900 XT, RADV NAVI31, Mesa 26.3.1, Linux, native wave64 and `LEONIDA_W64_EMULATE=1`). | -| `ds_and_b64`, `ds_or_b64`, `ds_xor_b64` (and `_rtn_`) | `M = M op DATA` on the 64-bit LDS element at `vaddr + offset` (two dwords, low first); the `_rtn_` form returns the old 64 bits in a VGPR pair. A bitwise op works on each bit alone, so it is emitted as one 32-bit `OpAtomicAnd/Or/Xor` per dword. That leaves exactly the memory a 64-bit atomic would, without Int64 atomics on Workgroup memory (optional in Vulkan). **Approximation:** the returned pair comes from two reads, so another lane's 64-bit op on the same element between them can show up half done; the memory result is exact. The other 64-bit LDS atomics (`add/sub/min/max_u64`, `wrxchg_b64`, `cmpst_b64`) carry between dwords or need the pair to move together, and still raise `Unsupported`. Until 2026-11-22 these three were rejected as well. CPU-checked by `tests/semantic/test_lds_bitwise_b64.py` (all six forms, offsets, `vdst` aliasing the data, seeded values). **GPU-verified** on native RDNA2 (gfx1036, the Radeon iGPU of a Ryzen 7 9800X3D, Windows driver 32.0.21042.62) through `tools/hw_oracle`: 39 of 39 one-thread cases (all six forms on three 64-bit M/DATA pairs, `offset:` 0 and 24, and `vdst` aliasing the data pair for each `_rtn_` op) leave M op DATA in both dwords and return the old pair. 32 lanes `ds_xor_rtn_b64` with (1 << lane) in both dwords on one element ran in lane order: lane i returned (2^i − 1) in both words, so the hardware never shows a half-done pair, unlike the two-read emission under contention. **Not GPU-verified.** Measured on native gfx1100 for all six forms, both dwords of each pair, with the returning forms giving the old pair. | -| `ds_bpermute_b32` subgroup convergence | Native wave32 and wave64 apply bitwise masks to the shuffle result and the destination write so both the ballot and shuffle execute before lane predication. If the ballot has no source lane, the shuffle reads the calling lane before the result is masked to zero. MoltenVK 1.4.2 lowered the scalar selects to nested Metal ternaries, placing the subgroup operations in divergent control flow. The `cs_bpermute32` inactive-source case returned 64 on an Apple M1 Max, and all eight fixture words match with bitwise masking. | -| LDS 2-address b64 (`ds_read2_b64`, `ds_write2_b64`, `ds_read2st64_b64`, `ds_write2st64_b64`) | Two elements at vaddr + offset0·unit and vaddr + offset1·unit, unit = 8 bytes (×64 for st64); each element is two consecutive dwords, low first. `read2_b64` fills v[d:d+3] after all four loads (a vdst overlapping vaddr is safe); `write2_b64` takes two VGPR pairs. The b32 forms share the code with unit 4. Source: RDNA2 ISA DS 2-address forms. CPU-checked by `tests/semantic/test_lds_read2_write2_b64.py` (compute listings, LDS as a Workgroup variable); GPU-checked by `runtime/test/shaders/cs_lds_b64_cmpst.asm` (unit 8 and the 512-byte st64 forms, plus vdst/vaddr overlap, on an RTX 3070, driver 621.01, Windows 11; the same eight words also on an AMD RX 7600 (`gfx1102`) and a Ryzen 5 9600X iGPU (`gfx1036`, RDNA2, RADV Mesa 27.0.0-devel)). | -| Compute workgroup IDs Y/Z | With four user SGPRs and only TGID_Y and TGID_Z enabled (RSRC2 `0x308`), s4 receives Y and s5 receives Z. The synthetic `cs_workgroup_yz.asm` fixture checks a 2 × 3 × 4 dispatch and each of its 24 origins against a CPU reference. | -| Typed image stores | `image_store` (2D, 2D array, 3D, cube) writes the dmask components (missing ones = 0). The image's numeric type lives in the T# (word 1 FORMAT [28:20], 512 GFX10 formats), so it is decided at run time. A 512-bit table built from `tools/gfx10_formats.json` (30 UINT and 15 SINT formats) picks a **sint**, **uint** or **float** view (bindings 8 + 3·dim + class; dim 0 = 2D, 1 = 2D array, 2 = 3D; class 0 float, 1 uint, 2 sint). Views have Unknown format (`shaderStorageImageWriteWithoutFormat`). **The runtime binds every storage image into all three arrays of its dimension, or at least the one matching its format.** The earlier path wrote only component 0 as `r32ui`, which was wrong for every other format. GPU-checked with `runtime/test/shaders/cs_imgstore.asm` through `runtime/test/vk_store_test.cpp`: rgba8 unorm, r32 uint and r32 sint images, every texel correct. A cube storage image is bound as a six-layer 2D array (bindings 11/12/13 for float/uint/sint, `OpTypeImage ... 2D 0 1 0 2 Unknown`, `%v3int` coordinates (x, y, face)); `tfe` and `lwe` are refused. CPU-checked by `tests/semantic/test_image_cube_store_glc.py`; **not GPU-verified**: no GPU fixture covers a cube store yet. | -| Typed image loads | A noncoherent cube `image_load` reads the 2D-array sampled binding (3) with integer coordinates and layer. Its T# format selects the float, uint or sint alias, including for D16. The [RDNA2 ISA §8.2.1](https://docs.amd.com/v/u/en-US/rdna2-shader-instruction-set-architecture) assigns D16 conversion to the image format. The synthetic `cube_load_d16.asm` checks the generated views and format choices on the CPU. `image_load` on 1D/2D/2D-array/3D images uses the same T# FORMAT tables as stores, and fetches every format with `OpImageFetch` from the sampled array of its dimension (bindings 0, 3, 6, 5): UINT/SINT formats through **uint/sint aliases of that array** (same set and binding, an `OpTypeImage` of `%uint`/`%int`; Vulkan allows several variables on one binding when the descriptor type fits), everything else through the float array. A lookup miss (index 0) takes the float path, since the fallback there is RGBA8_UNORM. Results are the raw bits of the dmask components. **The runtime binds each image's view in its own format at its index of the sampled array** (what `bind_image` in `runtime/shims/d3d12_vulkan_device.cpp` already does for SRVs and UAVs), so the view's numeric type matches the alias that reads it. No storage image is read, so shaders that only load need neither `shaderStorageImageReadWithoutFormat` (missing on Intel Xe-LP, #619) nor `shaderStorageImageWriteWithoutFormat` (SHADER-151). Until 2026-11-22 integer formats were read with `OpImageRead` from the uint/sint storage arrays (bindings 8–19), which hold only unordered-access views and 256 entries: a read-only integer texture found the fallback there, or an index past the array's end. Like the float path, the fetch goes through the texture path, so it sees writes made before the dispatch, not ones made earlier in the same dispatch. **d16 loads take the same branch** (#1136) and pack the dmask components two per VGPR, low half first: f16 (round to nearest even, integer ops, no `PackHalf2x16`) from the float array, the low 16 bits of each value from the uint/sint aliases (truncated). **d16 loads take the same branch** (#1136) and pack the dmask components two per VGPR, low half first: f16 (round to nearest even, integer ops, no `PackHalf2x16`) from the float array, each value from the uint/sint aliases saturated to the 16-bit range of its signedness (`saturate_int16`). For odd component counts (1 or 3 in `dmask`), the trailing destination VGPR preserves its existing high 16 bits (`write_lo16`), matching native `gfx1036` hardware where a seeded `0x5a5a` high half survived 1-component UINT/SINT `image_load` and `image_load_mip`; until 2026-11-22 the unused high half was zeroed. Before #1136, a d16 load always read the float view, so a `Texture2D` `Load` returned garbage. CPU-checked by `tests/test_image_load_typed.py` (capabilities, bindings and component types for every dimension; the branch for all 512 FORMAT values, found and missed). GPU-checked with `runtime/test/shaders/cs_imgload.asm` through `vk_store_test load`, on a device made without `shaderStorageImageReadWithoutFormat`: r32 uint and r32 sint images filled before the dispatch, both read with `image_load` and their sum stored, every texel exact on an RTX 2080 Ti (NVIDIA 621.14, Windows 11), clean under the validation layer with GPU-assisted validation; the test fails a module that declares `StorageImageReadWithoutFormat`. d16: CPU-checked by `tests/test_image_load_d16_typed.py` (the uint/sint fetches go through the aliases, no storage image is read, the SPIR-V validates); GPU-checked with `runtime/test/shaders/cs_imgload_d16.asm` through `vk_store_test load`: both pre-filled texels read with d16 loads (the sint one sign-extended from bit 15 in the shader) and their sum stored, every texel exact on the RTX 2080 Ti with GPU-assisted validation (#1136 checked its first form, a store and d16 read-back in one dispatch, on an RTX 5070, and `cs_imgload_d16` passes unchanged on an AMD RX 7600 (gfx1102, RADV Mesa 27.0.0-devel) in `run_gpu_tests.py`). GPU-checked with `runtime/test/shaders/cs_imgload_d16.asm` through `vk_store_test load`: both pre-filled texels read with d16 loads (the sint one sign-extended from bit 15 in the shader) and their sum stored, every texel exact on the RTX 2080 Ti with GPU-assisted validation (#1136 checked its first form, a store and d16 read-back in one dispatch, on an RTX 5070). 2D `image_load_mip` uses the same numeric-type selection and passes the address register's mip to each fetch. Its D16 form packs the selected components in ascending order, two per VGPR. An RGBA8 two-level texture was checked on RTX 5080 and Radeon Graphics: all four exported halves matched the CPU reference for UINT, SINT and UNORM, and forcing level 0 changed every pixel. Checked on RTX 5080 and Radeon Graphics with R8G8B8A8 UINT, SINT and UNORM textures: level 1 matched the CPU reference at every pixel with GPU-assisted validation, and forcing level 0 changed all 4096 pixels for each format. Native gfx1036 saturated 32-bit UINT/SINT texels to the unsigned/signed 16-bit range in both D16 load forms; the translated 2D load matched both limits on RTX 5080 and Radeon Graphics. Native gfx1036 does the same on every dimension (SHADER-387, `tools/image_d16_probe.py`): 32_UINT and 32_32_UINT texels saturate to [0, 0xffff] and 32_SINT and 32_32_SINT texels to [-32768, 32767], never truncate, in 1D, 2D, 2D-array and 3D images, through `image_load` and `image_load_mip` alike; two-channel results pack x low and y high, and a one-channel result keeps the seeded high half. The translated d16 loads on 1D, 2D-array and 3D images still lack GPU checks. With `tfe`, every image read and query (`image_load`, `image_load_mip`, `image_sample*`, `image_gather4*`, `image_get_resinfo`, `image_get_lod`) also writes the fetch status at `vdata[data_count]` — after the data, the dmask bit count in dwords (4 for a gather), halved and rounded up under d16 — and a Vulkan image is always resident, so the status is 0; before this the status VGPR was never written and a shader that read it saw its previous value. `lwe` alone adds no register (`llvm-mc` 18.1.8 sizes `vdata` from dmask, d16 and tfe and rejects `image_load v[16:17] ... dmask:0x1 lwe`), so nothing is written after the data. The `image_load` form is GPU-checked with `runtime/test/shaders/cs_imgload_tfe.asm` and `cs_imgload_d16_tfe.asm` through `vk_store_test load` (the status VGPR is seeded with 1000 and added into the result, so an unwritten status shows up as a constant 1000-per-load offset); CPU-checked by `tests/test_image_load_typed.py` (`test_tfe_status_vgpr_is_written_zero`). | -| Packed 2D mip-load addresses | For `image_load_mip` with `a16`, the first VGPR holds unsigned X (low half) and Y (high half). The low half of the second VGPR selects the mip and its high half is unused. Both ordinary and D16 results use the same address. LLVM gfx1030 assembles both forms in `tests/semantic/fixtures/packed_mip_load_2d.asm`. `tests/test_image_load_typed.py` checks the texel and mip operands of the float, UINT and SINT fetches, including noncontiguous address registers. [AMD RDNA 2 ISA, MIMG A16 field](https://www.amd.com/content/dam/amd/en/documents/radeon-tech-docs/instruction-set-architectures/rdna2-shader-instruction-set-architecture.pdf) | -| 3D explicit-mip loads | `image_load_mip` reads x, y, z and mip from four address VGPRs. T# FORMAT selects the float, UINT or SINT 3D sampled view at binding 6. D16 narrows the selected components before packing them low half first. The unit test `test_volume_mip_fetch_uses_xyz_level_and_descriptor_type` in `tests/test_image_load_typed.py` checks the four address registers and the RGBA32 format selection on the translated module. Native gfx1036 measured UINT and SINT saturation for 3D `image_load_mip` at mip zero. [Volume load measurements](https://github.com/ItsNotRexed/Leonida/pull/2217) | -| Typed 2D gathers | `image_gather4_lz(_o)` takes one channel from four taps. For `image_gather4_l(_o)` the four manual fetches share the rounded, clamped mip and addressed footprint. The T# FORMAT selects the float, UINT or SINT sampled image at binding 0. For d16, integer taps are packed low half first, two per VGPR; float taps round to f16. \| AMD RDNA 2 ISA §8.2 (MIMG D16). RTX 5080 and Radeon Graphics matched a CPU clamp-to-edge gather over all 4096 RGBA32F pixels for 8-bit UINT, SINT and UNORM, both packed and unpacked, with zero offset and with (+1,-1). Selecting red in place of green changed all 4096 pixels. Explicit LOD 1 on two-level UINT, SINT and UNORM images also matched all 4096 pixels for both offset forms on both GPUs. Forcing mip 0 changed every pixel. Native gfx1036 saturates out-of-range integer taps as in the typed image loads below. On the CPU, the unit tests `test_explicit_lod_gather_fetches_four_taps_from_each_typed_view` and `test_2d_gather_picks_the_sampled_type_and_selected_component` in `tests/test_image_load_typed.py` check the typed views at binding 0, the selected component, the shared mip footprint and the d16 packing. | -| Dynamic sampled descriptor indices | Set 0 bindings 0 (2D), 3 (2D array and cube), 5 (1D) and 6 (3D), including their integer sampled aliases, use runtime T# hash results for sampling, gather, texel fetch and image queries. Binding 1 uses runtime S# hash results for sampling, gather and LOD queries. Explicit-LOD gather emulation takes its sampler state directly from S# words and uses sampled-image fetches. Literal descriptor words and the zero-on-miss fallback still go through the runtime lookup. Emit `SampledImageArrayDynamicIndexing` and record `shaderSampledImageArrayDynamicIndexing` in the shader index whenever such an array is indexed. A storage-only shader can declare sampled arrays without indexing them. The hash table is one storage buffer containing an array of words. T# and S# operands are scalar across an RDNA2 wave (AMD RDNA 2 ISA, MIMG fields SRSRC/SSAMP). The Vulkan contract requires the resulting index to be dynamically uniform in the subgroup or invocation group, and in the invocation group when the effective subgroup size is one. If wave and Vulkan execution mappings break that uniformity, the affected accesses need separate non-uniform indexing support. Confirmed by the synthetic `sampled_dynamic_index.asm` regression (`test_sample_with_literal_sampler_still_indexes_both_arrays_dynamically` and `test_fetch_and_query_paths` in `tests/semantic/test_sampled_dynamic_index.py`), `spirv-val`, and the declaration-only GPU positive control in [#2806](https://github.com/ItsNotRexed/Leonida/pull/2806#issuecomment-7083836498). [Vulkan VUID 10128](https://docs.vulkan.org/spec/latest/appendices/spirvenv.html#VUID-StandaloneSpirv-SampledImageArrayDynamicIndexing-10128) and [runtime VUIDs 10135 and 10142](https://docs.vulkan.org/refpages/latest/refpages/source/RuntimeSpirv.html#VUID-RuntimeSpirv-SampledImageArrayNonUniformIndexing-10135). | -| Descriptor hash-table probe loop (`%desc_lookup_fn`) | `Gen.desc_probe` marks its FNV-1a probe loop `OpLoopMerge %dl_end %dl_cont DontUnroll` and breaks straight to `%dl_end` on a match (`OpBranch %dl_end`) instead of clobbering `%dl_k` to fall through `%dl_next`. Keeping `%dl_idx` on a single-exit loop-header phi caused Mesa ANV 26.1.6 (Intel UHD Graphics 630, CFL GT2) to hoist the post-loop binding-table-index addition (`add bti, idx, 2`) into `B0` before the probe loop in `ps_table_fetch` (observed in `INTEL_DEBUG=wm` across SIMD8, SIMD16 and SIMD32: every `fetch-sint` and `fetch-uint` pixel read slot 0's magenta fallback `0x3f800000`). Breaking directly to `%dl_end` with `DontUnroll` keeps one compact rolled loop (avoiding 8× unroll bloat) while giving `%dl_end` a post-loop exit phi so the addition stays after the loop. Confirmed on Intel UHD 630 / Mesa ANV 26.1.6 (`ps_table_fetch` 4096/4096 exact, full suite `185/241`, 0 failed), NVIDIA GTX 1050 Ti / 555.58.02 (`180/241`, 0 failed) and Mesa llvmpipe 26.1.6 (`ps_table_fetch` 4096/4096 exact); CPU-checked by `test_desc_probe_breaks_directly_with_dont_unroll` in `tests/test_desc_cache.py` (`spirv-as`, `tools/spirv_asm.py` and `spirv-val`). | -| Half-precision coordinates for LOD queries | For `image_get_lod a16` on 2D and 2D-array images, the low and high halves of the first address VGPR supply U and V. The array layer is excluded from `OpImageQueryLod`; the selected clamped and raw LOD outputs are f32. `tests/semantic/fixtures/get_lod_a16.asm` assembles for gfx1030 and checks the query operands and output components through `tests/test_image_load_typed.py`. [AMD RDNA2 ISA, MIMG](https://gpuopen.com/download/rdna2-shader-instruction-set-architecture.pdf) | -| Dynamic storage image descriptor indices | The runtime T# hash result indexes the r32ui arrays (bindings 4 and 7) used by `OpImageTexelPointer` for image atomics and the typed storage arrays (bindings 8 through 19) used by `OpImageWrite` for stores and `OpImageRead` for coherent loads. Literal T# words still go through the hash table. Emit `StorageImageArrayDynamicIndexing` and record `shaderStorageImageArrayDynamicIndexing` in the shader index when a storage array is accessed this way. Plain typed loads use sampled aliases and follow the sampled indexing rule. The same Vulkan dynamic-uniformity contract applies to storage indices. Confirmed by [Vulkan VUID 10130](https://docs.vulkan.org/spec/latest/appendices/spirvenv.html#VUID-StandaloneSpirv-StorageImageArrayDynamicIndexing-10130), the synthetic `storage_dynamic_index.asm` regression (`test_literal_storage_descriptor_and_mixed_sampled_load`, `test_storage_aliases_in_every_dimension` and `test_atomic_texel_pointers_use_storage_indices` in `tests/semantic/test_sampled_dynamic_index.py`) and `spirv-val`. | -| Image atomics, size and LOD queries | `image_atomic_add/sub/and/or/xor/smin/smax/umin/umax` are `OpAtomicIAdd/ISub/And/Or/Xor/SMin/SMax/UMin/UMax` on the texel (`OpImageTexelPointer`) of an r32ui storage image, binding 4 for 2D and 7 for 3D, at the T#'s index (the view `StorageViews::r32ui` of `runtime/src/vulkan_bindless.h`). The data VGPR is the operand; with `glc` it receives the texel's previous value, without it it is not written (RDNA2 ISA, MIMG: the previous value is returned if glc is 1). `image_atomic_cmpswap` takes two data VGPRs, the new value and then the comparand (`OpAtomicCompareExchange`). A lane that EXEC turns off skips the access entirely (`OpAccessChain`, `OpImageTexelPointer`, `OpAtomic*`, and any `glc` write-back sit inside `if (active)`), leaving memory and `vdata` untouched. Two-VGPR `dmask:0x3` forms of the nine standard ops currently still operate on the low 32-bit dword as before; true 64-bit image atomics remain separate follow-up work. `image_get_resinfo` (2D, no sampler) gives, for the mip level in its address VGPR, width, height, depth (0 for 2D; a 2D array's layers minified from BASE_LEVEL, T# word 3 [15:12]) and the level count in VGPRs 0..3, with width, height and depth 0 past the last level (the size isn't queried there) (ISA: {num_mip_levels, depth, height, width} in VGPRs 3..0; `OpImageQuerySizeLod`, `OpImageQueryLevels`). `image_get_lod` (pixel shaders; 2D and 2D array, the slice ignored) gives the clamped LOD and the calculated LOD in VGPRs 0..1 (ISA: {rawLOD, clampedLOD} in VGPRs 1..0; `OpImageQueryLod`). In both, dmask keeps components and packs them into consecutive VGPRs. GPU-checked (TEST-184) on an RX 7900 XTX and a Ryzen 9 7950X3D integrated GPU (RADV, Mesa 26.3.1) and on Mesa llvmpipe, with the expected words derived by hand in each `.asm` header: `cs_imgatomic.asm` (every op on a 2D image: 0xfffffff0 tells the signed min/max from the unsigned ones, each with a case that goes the other way; cmpswap hit and miss; an op without `glc`; 63 lanes off; 64 threads adding to one texel) and `cs_imgatomic3d.asm` (six cases on a 4x4x4 volume, the three coordinates all different), through `vk_store_test words`; `cs_resinfo.asm` (a 16x4 image with five levels: levels 0, 1 and 3 in full, then dmask 0x3, 0xa and 0x8); `ps_get_lod.asm` and `ps_get_lod_array.asm` through `vk_texture_test` (calculated LOD 1 and 3 on the two-mip texture, the clamped LOD held at the last level, and at 0 by a sampler MAX_LOD of 0.25; 2 and -3 on the one-level array). Measured natively on RDNA2 (gfx1036, SHADER-388: `tools/image_query_probe.py`, 614 results in wave32 and wave64, all as follows). resinfo's depth word is 0 for a 2D image whatever T# WORD4 DEPTH holds; for a 2D array it is the layer count minified like a 3D depth, max(1, layers >> (BASE_LEVEL + level)). Past the last level, width, height and depth are 0. The level count is LAST_LEVEL - BASE_LEVEL + 1 and sizes count from BASE_LEVEL. The translator follows all three (`Gen.resinfo_words`; `cs_resinfo.asm` checks the 2D depth word and level 5 of five on RTX 5080 and Radeon Graphics, `tests/test_translate.py` the array rule). `image_get_lod`'s raw LOD includes the S#'s LOD_BIAS. Its clamped LOD is min(max(min(raw, MAX_LOD), MIN_LOD), levels - 1) under a linear mip filter (MIN_LOD wins when it is above MAX_LOD), that value rounded half up (the level read) under a point mip filter, and 0 with MIP_FILTER none: `OpImageQueryLod`'s definition. u is scaled by the width and v by the height (a 64x4 image). Unverified: the clamped LOD under a linear mip filter (the test's sampler is point-filtered, where 0.25 selects level 0), and the order of u and v in the LOD query (the test textures are square, where it makes no difference). `image_get_resinfo` on other dimensions is `Unsupported`. A host quirk the LOD test steps around: Mesa llvmpipe 26.3.1 does not apply a sampler's LOD range to `OpImageQueryLod` when its minimum and maximum are equal (0..0 gave level 1), so the second draw uses 0..0.25. | -| `image_atomic_{swap,inc,dec,fmin,fmax,fcmpswap}` | The six remaining 32-bit MIMG image atomics on 2D (binding 4) and 3D (binding 7) `r32ui` storage images (including `a16` packed coordinates and optional `glc` return), guarded by `active_b` so inactive lanes skip memory access and preserve `vdata`. `image_atomic_swap` emits `OpAtomicExchange`; `inc`/`dec`/`fmin`/`fmax`/`fcmpswap` emit `OpAtomicLoad` (valid on `OpImageTexelPointer` `Image` pointers) followed by a Device-scope `OpAtomicCompareExchange` CAS loop (`inc`: `(M >= D) ? 0 : M + 1`; `dec`: `(M == 0 \|\| M > D) ? D : M - 1`; `fmin`/`fmax`: GLSL.std.450 `NMin`/`NMax`, no float-atomic extension required; `fcmpswap`: integer IEEE-754 binary32 ordered equality on raw 32-bit words — equal iff neither is NaN and `(cur == cmp) \|\| (both ±0.0)`, preserving subnormals even on Vulkan drivers reporting `shaderDenormPreserveFloat32 = false`, exiting without writing on mismatch or NaN; native RDNA2 subnormal behavior under denormal flush is unmeasured). Source: AMD RDNA2 ISA MIMG `IMAGE_ATOMIC_*`. CPU-checked structurally (including `spirv_mini_interp.check_structure` CFG validation) by `tests/semantic/test_image_atomics_32.py` (all 6 ops on 2D and 3D images, `a16`, `glc` and non-`glc`, no `AtomicFloat` capability, rejected widths/coords/dims). **Not GPU-verified on RDNA2.** | -| Hand-written short assembler forms | `llvm-mc` accepts `v_add_co_ci_u32 vD, src0, src1` (also `v_sub_co_ci_u32`, `v_subrev_co_ci_u32`) with the carry out and in left to VCC, and a modifier list shorter than the operands (`op_sel_hi:[0,0]`, `neg_lo:[1,0]` on a three-source op), whose missing entries are 0; it prints them as `v_add_co_ci_u32_e32 vD, vcc_lo, src0, src1, vcc_lo` and `[0,0,0]`. The GPU runner assembles through `llvm-mc -show-encoding`, so it sees the printed form; `tests/semantic/regen_fixtures.py` copies the `.asm` text as written, so the translator takes the source spelling too (it used to raise `IndexError` for these: the carry forms, `v_pk_fma_f16`, `v_fma_mix_*`). A probe of 42,000 operand and modifier variations of 302 ALU mnemonics, in the source spelling and as `llvm-mc` prints them, found no other `IndexError`, `KeyError` or `TypeError`. CPU-checked by `tests/semantic/test_short_asm_forms.py`. | -| SDWA | `_sdwa` forms: each source is narrowed to `src0_sel`/`src1_sel` (BYTE_n/WORD_n, zero-extended, or sign-extended under `sext()`) **before** neg/abs and the op. A VGPR result goes to `dst_sel`, with `dst_unused` setting the other bits: PAD = 0, SEXT = sign copies above the field, PRESERVE = old bits kept. A byte or word destination with PRESERVE reads its incoming VGPR on first use. The synthetic `sdwa_bary_input.asm` checks this with two raw fragment weights, following the [LLVM SDWA destination rules](https://llvm.org/docs/AMDGPUModifierSyntax.html#dst-unused). VOPC has no `dst_sel`, and GFX10 `v_cmpx` has no written destination. **Until 2026-11-20 the selects were silently ignored.** That affected 3,826 of the 13,926 translated shaders: they passed `spirv-val` but computed wrong values. GPU-checked with `runtime/test/shaders/ps_sdwa.asm` and `ps_ops.asm` (also `v_pk_fma_f16`, `v_min3_u32`, `v_max3_i32`, `v_bfe_i32`): byte/word source selects, `sext()`, `UNUSED_PRESERVE` into WORD_1 and `UNUSED_SEXT` at BYTE_2 all match on every pixel. **Measured natively on RDNA2** (gfx1036 iGPU, `tools/hw_oracle`, the game's MODE): all 172 distinct SDWA forms of the 26,503 listings (79,307 instructions: opcode, operand kinds, sels, `sext`, neg/abs, `dst_unused`, omod), 12 operand words per source, 21,204 cases. 18,885 give the translator's word. The rest are: a 16-bit result with `dst_sel:DWORD`, where the hardware zeroes the high half and the translator keeps it (1,888, #2187); a NaN result, where the hardware keeps the input's sign and payload (826, of which 556 also fall in the first group, so the groups add up to 21,204; as in the f16 transcendentals row); `div:2` on -0, which gives +0 (1, as in the output-modifier rows); and 160 cases whose translation is undefined in SPIR-V (`FClamp`/`FDiv`/`Sqrt` on NaN, zero or negative operands). `tests/semantic/test_alu_sdwa_hw.py` replays 624 of the matching words, up to four per form. | -| VOP3 output and source modifiers in the game's forms, on RDNA2 | Every distinct float VALU form in the 26,503 listings that carries `clamp`, an omod (`mul:2`/`mul:4`/`div:2`), `op_sel`/`op_sel_hi` or neg/abs: 572 forms, 1,270,932 instructions (`v_mul_legacy_f32 … clamp` alone is 147,499; `v_fma_mix_f32` has 222 forms), up to 120 random operand triples each, run natively on gfx1036 (`tools/hw_oracle`, the game's MODE) and through the translator: 542 forms, 64,802 cases (the GFX10.1-only `v_mad_f32`/`v_mad_legacy_f32`/`v_mac_f32` and `v_permlanex16` are left out). 51,761 give the translator's word. The rest are differences already on record: NaN sign and payload (5,074); f32 denormal operands or results, and a denormal intermediate that the hardware flushes before the omod or clamp (1,178; SHADER-377); an omod turning a -0 result into +0 (121; the Output modifiers rows, #1281); 1 ulp or the known sin/cos precision in `v_rcp/v_rcp_iflag/v_log/v_sin/v_cos` with an omod (56); and 6,430 whose translation is undefined in SPIR-V, mostly `FClamp` of a NaN, where the hardware gives +0 under DX10_CLAMP (#2437). 182 cases were my harness's (three distinct SGPRs, over GFX10's two-read limit). No other modifier difference. `tests/semantic/test_alu_vop3_mods_hw.py` replays 1,616 matching words, up to three per form; it fails without `clamp` (326 rows) or without the omod (237). | -| Byte permute | `v_perm_b32`: result byte i = BYTE_PERMUTE({src0, src1}, selector byte i), src1 = bytes 0–3 (AMD "RDNA 2" ISA reference, VOP3 opcode 836 V_PERM_B32, `byte_permute` pseudocode, page 189 of the PDF). Selector 0–7 picks that byte; **8, 9, 10, 11 give 0xff if bit 7 of byte 1, 3, 5, 7 is set, else 0x00**; 12 gives 0x00; 13 and above give 0xff. **Until 2026-11-21 selectors 8–11 gave 0x00 regardless of the sign bit**. In the 26,503-shader disassembled corpus (measured via `tools/feature_scan.py`), 0 of 10,500 shaders (11,930 `v_perm_b32` instructions) use selectors 8–11 or >= 13: all 11,258 immediate and 672 constant-register selectors (0 unresolved) use only bytes 0–7 (36,234) and 12 (11,486). GPU-checked with `runtime/test/shaders/ps_ops7.asm` (also `v_alignbit_b32` with a shift of 36, `v_med3_i32` vs `v_med3_u32`) and `ps_ops8.asm` (`v_mul_hi_u32/i32`, `v_bcnt_u32_b32`, `v_ffbl_b32`, `v_ffbh_u32` of 0, `v_xad_u32`, `v_add3_u32`), 4096/4096 pixels on an AMD Radeon iGPU (Ryzen 7 9800X3D, RDNA2, AMD driver 25.10.36) and an NVIDIA GeForce RTX 5070 (driver 621.24); before the fix `ps_ops7` gave 0x00000000 for the sign-selector word on both. Also executed by `tests/semantic/test_value_semantics.py`. When S2 is a literal or a currently known SGPR constant, the translator emits fixed byte extracts/inserts (including sign replication), folds the zero and 0xff bytes, and uses the selected source directly for a whole-word identity. `tests/semantic/test_perm_known_selector.py` checks the resulting words and that selector dispatch only remains for a clobbered SGPR. | -| Sum of absolute differences (`v_sad_u8`, `v_sad_hi_u8`, `v_sad_u16`, `v_sad_u32`, `v_msad_u8`) | Unsigned, wrapping at 32 bits, with ABSDIFF(x, y) = `UMax − UMin`: `v_sad_u8` = S2 + the sum over the four bytes; `v_sad_hi_u8` = (that byte sum << 16) + S2; `v_sad_u16` = S2 + the sum over the two halves; `v_sad_u32` = \ \| S0 − S1\ \| + S2; `v_msad_u8` skips a byte where S1's byte is 0. `clamp` raises `Unsupported`: the ISA pseudocode doesn't say what it does to these ops. Source: RDNA2 ISA VOP3 opcodes 346–349 and 369 (pseudocode re-read for this row). CPU-checked by `tests/semantic/test_alu_sad.py` (#544): a 9×9 grid of edge words per op, 40 seeded cases, masked bytes, an SGPR source, `clamp` rejected; the PR also reports a 300-case differential run per op with 0 mismatches. None of them is in the translated corpus, and none is GPU-checked. **Hardware-verified on RDNA2** (`gfx1035`, wave32 and wave64 via `tools/int_hw_probe.py --oracle both`, SHADER-137). Measured on native gfx1036 (AMD Radeon Graphics, RDNA2) through tools/hw_oracle across edge byte/half patterns, zero masks, and wrap cases: all match the ISA reference with 0 mismatches. | -| Quad-byte SAD 64-bit source operands | The GFX10.3 `null` operand supplies zero for the 64-bit input window in all three quad-byte SAD operations and for the 64-bit addend of the two packed forms. Confirmed with LLVM gfx1030 assembly and scalar byte-difference references in `tests/semantic/test_alu_qsad.py` (`test_null_pixel_source_and_null_accumulator`) and `tests/semantic/test_alu_mqsad_u32.py` (`test_null_pixel_source`). | -| `v_mqsad_u32_u8` | Four masked byte-SADs with full 32-bit accumulators: D[k] = S2[k] + `v_msad_u8` of the 32-bit window S0[8k+31:8k] of the 64-bit S0 against S1, wrapping at 32 bits (S2 and D are four VGPRs). Every source is read before the first write; `clamp` raises `Unsupported`. Source: RDNA ISA pseudocode. CPU-checked by `tests/semantic/test_alu_mqsad_u32.py`. **Hardware-verified on RDNA2** (`gfx1035`, wave32 and wave64 via `tools/int_hw_probe.py --oracle both`, SHADER-137). Measured on native gfx1036 (AMD Radeon Graphics, RDNA2) through tools/hw_oracle across 64-bit sliding window and masked byte values against the 32-bit accumulators: bit-exact with the ISA reference. | -| `s_sext_i32_i8`, `s_sext_i32_i16`, `s_flbit_i32` | The first two sign-extend the low byte or the low half of S0 to 32 bits (`OpBitFieldSExtract`). `s_flbit_i32` counts how many bits in a row from the MSB equal the sign bit, and gives −1 when all bits are the same (0 and −1); it is the scalar form of `v_ffbh_i32` and goes through the same code. None of the three writes SCC. Source: RDNA2 ISA SOP1 opcodes 23, 25 and 26. CPU-checked by `tests/semantic/test_salu_sext_flbit.py` (#549): edge words with SCC starting at 0 and at 1, and 30 seeded values with long runs of sign bits. Not in the translated corpus, not GPU-checked. **Hardware-verified on RDNA2** (`gfx1035`, wave32 and wave64 via `tools/int_hw_probe.py --oracle both`, SHADER-137, SCC kept). Measured on native gfx1036 (AMD Radeon Graphics, RDNA2) through tools/hw_oracle and tools/salu_diff.py (500 programs, --oracle translator,hw): 500 pass, 0 mismatches against the reference; confirmed s_flbit_i32 gives 0xFFFFFFFF for 0 and -1. | -| `v_lerp_u8` | Per byte i: `D.b[i] = (S0.b[i] + S1.b[i] + (S2.b[i] & 1)) >> 1`, an unsigned average where bit 0 of S2's byte decides whether 0.5 rounds up. The translator uses the per-byte identity `x + y = 2*(x & y) + (x ^ y)`. It clears each byte's low bit before shifting, then adds the rounding bit only to an odd sum. Each result fits in one byte, so the packed additions do not carry across bytes. The 9-bit sum shifted right by 1 fits back in its byte, so nothing carries between bytes. `clamp` raises `Unsupported` (the ISA doesn't define it for this op). Source: RDNA2 ISA VOP3 opcode 333. CPU-checked by `tests/semantic/test_alu_lerp_u8.py` (#577): a 9×9×5 grid of edge and rounding words, 40 seeded cases, an SGPR source with an inline S2, `clamp` rejected. The synthetic `tests/semantic/fixtures/lerp_packed_bytes.asm` gives exact words across a 64x64 draw on an RTX 3070 (NVIDIA 591.86). Not in the translated corpus, not GPU-checked. **Hardware-verified on RDNA2** (`gfx1035`, wave32 and wave64 via `tools/int_hw_probe.py --oracle both`, SHADER-137). Measured on native gfx1036 (AMD Radeon Graphics, RDNA2) through tools/hw_oracle across byte edge values and rounding bit variations: 0 mismatches against the ISA reference. | -| Scalar select and pack (`s_cmov_b32`, `s_cmovk_i32`, `s_cmov_b64`, `s_pack_ll/lh/hh_b32_b16`) | `s_cmov_b32` / `s_cmovk_i32`: D = SCC ? S0 : D (`s_cmovk_i32`'s S0 is the 16-bit immediate, sign-extended); SCC is read, not written; the destination must be an SGPR (a lane-mask destination stays `Unsupported`, #210). `s_cmov_b64`: D[63:0] = SCC ? S0[63:0] : D[63:0] on plain 64-bit data pairs (SGPR pair, immediate or `null`), SCC read and not written; a pair that is or has been a lane mask (EXEC, VCC or a mask SGPR) stays `Unsupported` (#210) — conservatively, because a CFG join can drop a register that is a mask on only one path — while 0/-1 EITHER constants are data; selecting a per-lane bit as data would silently return a bool instead of the wave's mask. D[63:0] on plain 64-bit data pairs (SGPR pair, immediate or `null`), SCC read and not written; a pair that is or has been a lane mask stays `Unsupported` (#210). D[63:0], SCC read and not written, on plain 64-bit data pairs (SGPR pair, immediate or `null`); any dword that is or has been a lane mask (EXEC, VCC or a mask SGPR) makes the pair `Unsupported` — conservatively, because a CFG join can drop a register that is a mask on only one path — while 0/-1 EITHER constants are data; selecting a per-lane bit as data would silently return a bool instead of the wave's mask (#210). `s_pack_*`: the low half of D from S0, the high half from S1, the letters naming the half of each (l = 15:0, h = 31:16), S0 first; GFX10 has no `s_pack_hl`; SCC not written. Source: RDNA2 ISA SOP1/SOP2/SOPK and LLVM AMDGPU `SOPInstructions.td` (`S_CMOV_B64 : RDNA2 ISA SOP1/SOP2/SOPK. CPU-checked by `tests/semantic/test_salu_cmov.py` and `test_salu_pack.py`; the translated shaders were run on NVIDIA by reviewers (`s_cmov*`: RDNA2 ISA SOP1/SOP2/SOPK and LLVM AMDGPU [SOPInstructions.td](https://github.com/llvm/llvm-project/blob/2bfedf3338162e2c841a73cd7cd9e98d00add608/llvm/lib/Target/AMDGPU/SOPInstructions.td) (`S_CMOV_B64 : SOP1_64` under `Uses = [SCC]`). CPU-checked by `tests/semantic/test_salu_cmov.py`, `tests/semantic/test_salu_cmov_b64.py` and `test_salu_pack.py`; no corpus count; **not GPU-verified, no corpus count**; the translated shaders were run on NVIDIA by reviewers (`s_cmov_b32/k_i32`: **no corpus count**; Hardware: on native `gfx1036` (Ryzen 9 9950X3D iGPU, Windows 11, driver 26.10.1) `tools/int_hw_probe.py --oracle both --wave both` matches the translator in wave32 and wave64 for all five `salu_cmov_pack` cases and for the 14 `s_cmov_b64` cases (`--group salu_cmov_b64`: GPU-checked for `s_cmov_b32` (`cs_w32_salu64.asm`, SCC = 1 selects S0) and `s_pack_lh_b32_b16` (`cs_w32_int_ext.asm`) on the Radeon iGPU of a Ryzen 9 9950X3D (RDNA2, `gfx1036`, driver 26.10.1) and an RTX 5080 (driver 616.92); `s_cmovk_i32`, `s_cmov_b64` and the other `s_pack_*` forms have no GPU test on main; the translated shaders were also run on NVIDIA by reviewers (`s_cmov_b32/k_i32`: RTX 5090, RTX 4050 and Radeon 740M in #613; `s_pack_*`: RTX 5090 in #449). **Hardware-verified on RDNA2** (`gfx1035`, wave32 and wave64 via `tools/int_hw_probe.py --oracle both`, SHADER-137, SCC kept), and on native gfx1036 (AMD Radeon Graphics, Windows 11, driver 26.10.1) through `tools/hw_oracle`: all five `salu_cmov_pack` cases and the 14 `s_cmov_b64` cases match the translator in wave32 and wave64 (SCC 0 and 1; an SGPR pair, the inline constants -1/-16/64, the literal 0x89abcdef, `null` and the destination itself; SCC = 1 takes S0, 0 keeps D, SCC is never written), `s_cmov_b32` matches under SCC=0 and SCC=1, and `s_pack_ll/lh/hh_b32_b16` is bit-exact on 500 random programs with 0 mismatches (`--oracle translator,hw`). **Hardware-verified on RDNA2** (`gfx1035`, wave32 and wave64 via `tools/int_hw_probe.py --oracle both`, SHADER-137, SCC kept). Also **measured on RDNA2 gfx1036** (Radeon iGPU of a Ryzen 9 9950X3D, Windows 11, driver 26.10.1, `tools/hw_oracle` HIP launcher, rocm-sdk-core clang): `tools/int_hw_probe.py --oracle both --wave both` gives the same words as the translator for all five `salu_cmov_pack` cases in wave32 and wave64, and the 14 `s_cmov_b64` cases of the `salu_cmov_b64` group (`python -I tools/int_hw_probe.py --oracle both --wave both --group salu_cmov_b64`; SCC 0 and 1; source an SGPR pair, the inline constants -1, -16 and 64, the literal 0x89abcdef, `null`, and the destination itself; SCC preset and read back after): SCC preset and read back after) match the translator in wave32 and wave64: SCC = 1 takes S0 (a literal zero-extended, an inline constant sign-extended, `null` gives 0), SCC = 0 keeps D, SCC is never written. Also on `gfx1035` via `int_hw_probe` (SHADER-137, SCC kept), and on `gfx1036` and an RTX 5080 through the fixtures `cs_w32_salu64.asm` (`s_cmov_b32`) and `cs_w32_int_ext.asm` (`s_pack_lh_b32_b16`). `tools/hw_oracle` + `tools/salu_diff.py` verify `s_cmov_b32` under SCC 0/1 and `s_pack_ll/lh/hh_b32_b16` bit-exact on 500 random programs with 0 mismatches. Reviewers ran `s_cmov*` on an RTX 5090, an RTX 4050 and a Radeon 740M (#613) and `s_pack_*` on an RTX 5090 (#449). Measured on native gfx1036 (AMD Radeon Graphics, RDNA2) through tools/hw_oracle and tools/salu_diff.py: s_cmov_b32 verified under SCC=0 and SCC=1 (preserving destination and updating respectively); s_pack_ll/lh/hh_b32_b16 verified bit-exact on 500 random programs with 0 mismatches (--oracle translator,hw). **Not measured on RDNA2.** | -| `v_bfi_b32` | `(S0 & S1) \| (~S0 & S2)` (RDNA2 ISA, VOP3 opcode 330). A literal or known same-block SGPR mask of zero or all ones selects S2 or S1 directly. A contiguous mask uses `OpBitFieldInsert` with S1 shifted down by the field offset, since RDNA2 reads the bits in place. For sparse constant masks the translator precomputes the complement. Runtime masks use the full bitwise expression. Checked by the hand-written `bfi_known_mask.asm` and `tests/semantic/test_bfi_known_mask.py`. | -| `v_bfm_b32` | The low five bits of S0 give the width and those of S1 give the offset. The result is the low 32 bits of `((1 << width) - 1) << offset` (RDNA2 ISA §12.12, VOP3 opcode 867). Literal and same-block SGPR constants are folded in the translator, including zero width and shifts that discard the high bits. Runtime operands keep their low-five-bit masks. Checked by `tests/semantic/test_bfm_known_operands.py` and `test_alu_int_misc.py`. | -| `s_bfe_u32` / `s_bfe_i32` past bit 31 | offset = S1[4:0], width = S1[22:16] (7 bits; S1 bits 23 to 31 are ignored). When offset + width > 32 the field stops at bit 31: width = min(width, 32 - offset), and `s_bfe_i32` sign-extends from the top bit that exists. Example: `s_bfe_i32 s4, 0xd2f90159, 0x7f001c` gives `0xfffffffd` (4-bit field `0xd`), not `0xd`. SCC = D ≠ 0. Source: measured on gfx1150 (Radeon 880M) with `tools/salu_diff.py --oracle hw`, 4000 random control words, all bit-exact, on gfx1201 (Radeon RX 9070, RDNA4) with 10,000 `salu_diff --oracle hw` programs, 0 mismatches (seed 500 with `--bfe-any`), and **on RDNA2** (AMD Radeon 680M, `gfx1035`: `tools/salu_diff.py --oracle hw,translator --bfe-any --programs 500 --seed 1`, 500/500 match, plus `tools/int_hw_probe.py --oracle both` wave32 and wave64, SHADER-137; and RDNA2 `gfx1036`, Windows 11, driver 26.10.1, `tools/hw_oracle` HIP launcher: `tools/salu_diff.py --oracle translator,hw --bfe-any --ops s_bfe_u32,s_bfe_i32 --programs 2000` with seeds 1, 2 and 3, 6,000 of 6,000 programs pass on both sides, plus seed 4 over every opcode with `--bfe-any`, 2,000 of 2,000, and `int_hw_probe.py`'s `salu_bfe_past31` cases in wave32 and wave64); the translator (`bfe_width`) already did this. `tools/salu_diff.py --oracle hw,translator --bfe-any --programs 500 --seed 1`, 500/500 match, plus `tools/int_hw_probe.py --oracle both` wave32 and wave64, SHADER-137); the translator (`bfe_width`) already did this. Source: measured on gfx1150 (Radeon 880M) with `tools/salu_diff.py --oracle hw`, 4000 random control words, all bit-exact, and on gfx1201 (Radeon RX 9070, RDNA4) with 10,000 `salu_diff --oracle hw` programs, 0 mismatches (seed 500 with `--bfe-any`); the translator (`bfe_width`) already did this. LLVM's v_bfe fold (`constantFoldBFE`) is analogous but has a 5-bit width. **RDNA2 is not measured**; the ISA pseudocode does not say. | -| 64-bit scalar data ops (`s_brev_b64`, `s_bfe_u64`/`s_bfe_i64`, `s_bitset0_b64`/`s_bitset1_b64`, `s_flbit_i32_b64`/`s_flbit_i32_i64`) | The SGPR pair is 64-bit data, as for `s_lshl_b64`; a pair that `lane_masks.py` marks as a lane mask (or EXEC) stays `Unsupported` (#210). `s_brev_b64`: D.lo = reverse(S0.hi), D.hi = reverse(S0.lo). `s_bfe_*64`: offset = S1[5:0], width = S1[22:16]; width 0 gives 0; a field past bit 63 stops there (the 64-bit form of the `s_bfe_u32` rule, LLVM `constantFoldBFE`); SCC = D ≠ 0. `s_bitset*_b64`: bit S0 & 63 of the pair cleared / set. `s_flbit_i32_b64`: zeros above the top 1 from bit 63, −1 for 0; `s_flbit_i32_i64`: the same of ~S0 when S0 < 0, −1 for 0 and −1. None but `s_bfe` writes SCC. Source: RDNA2 ISA SOP1/SOP2. CPU-checked by `tests/semantic/test_salu_brev_b64.py`, `test_salu_bfe_64.py`, `test_salu_bitset_b64.py`, `test_salu_flbit_64.py` (#723, #726, #729, #733). **Hardware-verified** on an AMD Radeon RX 7900 XTX (gfx1100, Windows 11, driver 26.10.1), one raw wave32 kernel per op through `tools/hw_oracle`: `s_brev_b64` of 0x12345678_0000000F has low word 0x1E6A2C48, `s_bfe_u64(0x00000123_45678000, w16 o28)` = 0x1234, `s_bfe_i64(0x00000001_80000000, w2 o31)` has 0xFFFFFFFF in both words, `s_bitset1_b64(0, 40)` has high word 0x100, `s_flbit_i32_b64(0x00010000)` = 47 and `s_flbit_i32_i64(0xFFFFFFFF_FFFF0000)` = 48. These are the words `runtime/test/shaders/cs_w32_salu64.asm` expects. Also **hardware-verified on RDNA2** (`gfx1035`, wave32 and wave64 via `tools/int_hw_probe.py --oracle both`, SHADER-137). | -| `v_bfe_u32` / `v_bfe_i32` past bit 31 | offset = S1[4:0] and width = S2[4:0]: the bits above are ignored, so an offset of 36 reads as 4 and a width of 32 as 0 (a width of 0 gives 0). When offset + width > 32 the field stops at bit 31, as for `s_bfe`: width = min(width, 32 - offset), and `v_bfe_i32` sign-extends from bit 31. Example: `v_bfe_i32` of `0xd2f90159` with offset 28 and width 16 gives `0xfffffffd` (4-bit field `0xd`), not `0xd`, and `0x80000000` with offset 31 and width 4 gives `0xffffffff`. The translator (`bfe_width` for VGPR or SGPR offset and width, the same cut folded at translation time for constants) already did this. Source: **measured on RDNA2**, AMD Radeon 610M (`gfx1036`, Windows 11, AMD driver 32.0.11016.14003), wave32 and wave64 identical, 16 words over VGPR, inline-constant and literal operands: `tools/int_hw_probe.py --oracle both --group valu_bfe_past31`, 4/4 cases match the translator. The words are pinned on the CPU by the unit test `ValuBfeMeasuredOnRdna2.test_translator_gives_the_gfx1036_words` in `tests/test_int_hw_probe.py`. | -| `s_quadmask_b32`/`_b64`, `s_bitreplicate_b64_b32` | On scalar data (RDNA2 ISA SOP1): `s_quadmask_b32` sets D[i] to the OR of S0[4i+3:4i] for the 8 quads, `s_quadmask_b64` does the same for the 16 quads of the 64-bit S0 (D[63:16] = 0), and both set SCC = D != 0. `s_bitreplicate_b64_b32` copies each bit S0[i] to D[2i] and D[2i+1] and leaves SCC. Built from fixed shift/mask steps, with no loop. A lane-mask source (EXEC, VCC or an SGPR that `holds_lane_mask`) or an EXEC/VCC destination raises `Unsupported`: each invocation holds only its own lane's bit, and these ops read the other lanes of a quad or move bits between lanes. Until 2026-11-22 all three were rejected. CPU-checked by `tests/semantic/test_salu_quadmask_bitreplicate.py` (fixed and seeded values, SCC written or kept, immediates, aliasing, lane masks rejected). **Hardware-verified** on an AMD Radeon RX 7900 XTX (gfx1100, Windows 11, driver 26.10.1) through `tools/hw_oracle`, one raw wave32 kernel per op: `s_quadmask_b32(0xF)` = 1 with SCC 1, `(0xF0000000)` = 0x80, `(0x0F0F0F0F)` = 0x55 (the set quads are 0, 2, 4 and 6), `(0)` = 0 with SCC 0; `s_quadmask_b64` of 0xF = 1 and of 0xF0000000_00000000 (quad 15, bits 60..63) = 0x8000 in the low word with D[63:16] = 0; `s_bitreplicate_b64_b32` of 5 = 0x33 and of 0x80000000 = 0xC0000000_00000000, with SCC left as it was. **GPU-checked** by `runtime/test/shaders/cs_w32_new_ops.asm` (`s_quadmask_b32(0x01020408)` = 0x55, `s_quadmask_b64(0x80000000_00000001)` low word 0x8001, `s_bitreplicate_b64_b32(0x80000001)` high word 0xC0000000, with the expected words from the ISA pseudocode), exact on the Radeon iGPU of a Ryzen 9 9950X3D (RDNA2, `gfx1036`, driver 26.10.1) and an RTX 5080 (driver 616.92). **Not GPU-verified.** | -| 64-bit scalar bitwise ops (`s_and_b64`, `s_or_b64`, `s_xor_b64`, `s_andn2_b64`, `s_orn2_b64`, `s_nand_b64`, `s_nor_b64`, `s_xnor_b64`, `s_not_b64`) | Dispatched like `s_cselect_b64`: when destination is `exec`/`vcc` or any source is a lane mask (`holds_lane_mask` or `exec`/`vcc`), uses the per-lane mask path (`mask_src`/`mask_dst` including `null` dst) and votes SCC across the wave (`scc_from_mask`). Otherwise operates on both 32-bit dwords of non-mask 64-bit scalar data (SGPR pairs, sign-extended inline/literal immediates, `null` = 0), reads all source dwords before storing (preserving destination aliasing), accepts `null` destination, and sets `SCC = ((D.lo \ \| D.hi) != 0)`. Until 2026-11-22 these ops always took the lane-mask path, duplicating D.lo into D.hi and voting SCC on D.lo alone. `s_nand/nor/xnor_b64` compute `~(S0 op S1)` on both paths (a lane's mask value is 0 or ~0, so the NOT is per lane); until 2026-11-22 they were rejected as unsupported. Source: RDNA2 ISA SOP1/SOP2. CPU-checked by `tests/semantic/test_salu64_bitwise_data.py` (all 9 ops, 4-corner SCC, immediates, aliasing, stale mask overwrite, wave32/wave64 lane-mask regression, and `--wave64-emulate`); **Hardware-verified** on the same part through `tools/hw_oracle` for the plain-data path: `s_and_b64(0xFFFFFFFF_00000000, 0x0F0F0F0F_0F0F0F0F)` = 0x0F0F0000_00000000, `s_xnor_b64(0xFFFF0000_00000000, 0_FFFFFFFF)` = 0x0000FFFF_00000000, `s_nand_b64(0xFFFF0000_0, 0)` = 0xFFFFFFFF_FFFFFFFF, `s_not_b64(0x0000FFFF_0)` = 0xFFFF0000_FFFFFFFF and `s_andn2_b64(0xFFFF0000_0, 0)` = 0xFFFF0000_0, all with SCC 1, while `s_or_b64(0, 0)` = 0 with SCC 0: SCC = ((D.lo ≠ 0) or (D.hi ≠ 0)). The lane-mask path (EXEC/VCC sources, or a mask destination) is a translator model and cannot be measured this way; on RDNA3 the same plain-data path is **hardware-verified on an AMD RX 7600 (gfx1102)**: on four A/B pairs with high-bit-only and cross-half values, `s_and_b64`, `s_or_b64`, `s_xor_b64`, `s_andn2_b64` and `s_orn2_b64` write both dwords and set `SCC = (D.lo The lane-mask path (EXEC/VCC sources, or a mask destination) is a translator model and cannot be measured this way; on RDNA3 the same plain-data path is **hardware-verified on an AMD RX 7600 (gfx1102)**: on four A/B pairs with high-bit-only and cross-half values, `s_and_b64`, `s_or_b64`, `s_xor_b64`, `s_andn2_b64` and `s_orn2_b64` write both dwords and set `SCC = (D.lo \| The measured plain-data words: The lane-mask path (EXEC/VCC sources, or a mask destination) is a translator model and cannot be measured this way; on RDNA3 the same plain-data path is **hardware-verified on an AMD RX 7600 (gfx1102)**: on four A/B pairs with high-bit-only and cross-half values, `s_and_b64`, `s_or_b64`, `s_xor_b64`, `s_andn2_b64` and `s_orn2_b64` write both dwords and set `SCC = (D.lo \| The measured plain-data words: `s_and_b64(0xFFFFFFFF_00000000, 0x0F0F0F0F_0F0F0F0F)` = 0x0F0F0000_00000000, `s_xnor_b64(0xFFFF0000_00000000, 0_FFFFFFFF)` = 0x0000FFFF_00000000, `s_nand_b64(0xFFFF0000_0, 0)` = 0xFFFFFFFF_FFFFFFFF, `s_not_b64(0x0000FFFF_0)` = 0xFFFF0000_FFFFFFFF and `s_andn2_b64(0xFFFF0000_0, 0)` = 0xFFFF0000_0, all with SCC 1, while `s_or_b64(0, 0)` = 0 with SCC 0. The lane-mask path (EXEC/VCC sources, or a mask destination) is a translator model and cannot be measured this way. **Not GPU-verified.** **hardware-verified on an AMD RX 7600 (gfx1102)**: on four A/B pairs with high-bit-only and cross-half values, `s_and_b64`, `s_or_b64`, `s_xor_b64`, `s_andn2_b64` and `s_orn2_b64` write both dwords and set `SCC = (D.lo \| The measured plain-data words: **Not GPU-verified.** **hardware-verified on an AMD RX 7600 (gfx1102)**: on four A/B pairs with high-bit-only and cross-half values, `s_and_b64`, `s_or_b64`, `s_xor_b64`, `s_andn2_b64` and `s_orn2_b64` write both dwords and set `SCC = (D.lo \| D.hi) != 0`, the `andn2`/`orn2` pairs separate negation of the second source from negation of the first, `s_not_b64` inverts both dwords and clears SCC on a zero result, and `s_nand_b64`/`s_nor_b64`/`s_xnor_b64` invert the per-dword result (`and`/`or` of all ones gives `0` with SCC 0, `xnor` of equal pairs gives all ones with SCC 1); the lane-mask dispatch (`exec`/`vcc` destinations) was not re-measured. The lane-mask dispatch (`exec`/`vcc` destinations) was not re-measured. D.hi) != 0`, the `andn2`/`orn2` pairs separate negation of the second source from negation of the first, `s_not_b64` inverts both dwords and clears SCC on a zero result, and `s_nand_b64`/`s_nor_b64`/`s_xnor_b64` invert the per-dword result (`and`/`or` of all ones gives `0` with SCC 0, `xnor` of equal pairs gives all ones with SCC 1); the lane-mask dispatch (`exec`/`vcc` destinations) was not re-measured. **Not GPU-verified.** **hardware-verified on an AMD RX 7600 (gfx1102)**: on four A/B pairs with high-bit-only and cross-half values, `s_and_b64`, `s_or_b64`, `s_xor_b64`, `s_andn2_b64` and `s_orn2_b64` write both dwords and set `SCC = (D.lo The lane-mask path (EXEC/VCC sources, or a mask destination) is a translator model and cannot be measured this way; on RDNA3 the same plain-data path is **hardware-verified on an AMD RX 7600 (gfx1102)**: on four A/B pairs with high-bit-only and cross-half values, `s_and_b64`, `s_or_b64`, `s_xor_b64`, `s_andn2_b64` and `s_orn2_b64` write both dwords and set `SCC = (D.lo | The measured plain-data words: `s_and_b64(0xFFFFFFFF_00000000, 0x0F0F0F0F_0F0F0F0F)` = 0x0F0F0000_00000000, `s_xnor_b64(0xFFFF0000_00000000, 0_FFFFFFFF)` = 0x0000FFFF_00000000, `s_nand_b64(0xFFFF0000_0, 0)` = 0xFFFFFFFF_FFFFFFFF, `s_not_b64(0x0000FFFF_0)` = 0xFFFF0000_FFFFFFFF and `s_andn2_b64(0xFFFF0000_0, 0)` = 0xFFFF0000_0, all with SCC 1, while `s_or_b64(0, 0)` = 0 with SCC 0. The lane-mask path (EXEC/VCC sources, or a mask destination) is a translator model and cannot be measured this way. The lane-mask dispatch (`exec`/`vcc` destinations) was not re-measured. D.hi) != 0`, the `andn2`/`orn2` pairs separate negation of the second source from negation of the first, `s_not_b64` inverts both dwords and clears SCC on a zero result, and `s_nand_b64`/`s_nor_b64`/`s_xnor_b64` invert the per-dword result (`and`/`or` of all ones gives `0` with SCC 0, `xnor` of equal pairs gives all ones with SCC 1); the lane-mask dispatch (`exec`/`vcc` destinations) was not re-measured. \| -| Constant lane masks (`Gen.mask_src` immediates) | A constant read as a lane mask is one bit per lane: lane L takes bit L. The 64-bit forms (`s_and/or/andn2_saveexec_b64`, `s_andn2_wrexec_b64`, `s_mov_b64`/`s_not_b64` into EXEC or VCC, `s_and/or/xor/andn2/orn2_b64` and `s_cselect_b64` on the lane-mask path) read the 64-bit value, an inline constant sign-extended (`-16` = lanes 4-63) and a literal with a zero high word, as `src64_data` reads 64-bit constants; the b32 forms (`s_*_saveexec_b32`, `s_andn2_wrexec_b32`) read the 32-bit value at bit L mod 32. 0 and -1 still give no lane and every lane, with no per-lane code. `s_bcnt0/1_i32_b64` and `s_ff0/1_i32_b64` of a constant read the constant's 64 bits via `src64_data` (scalar data: inline negative constants sign-extend to 64 bits, so `s_ff0_i32_b64 s0, -1` gives −1 rather than 32, and 32-bit literals zero-extend; CPU-checked in `tests/semantic/test_scalar_bitcmp.py`, **not yet GPU-verified**). `s_bcnt0/1_i32_b64` of a constant counts the constant's 64 bits (scalar data, like `s_ff0/1_i32_b64`). **Before this fix every lane took bit 0 of the constant**: `s_and_saveexec_b32 s7, 0xff00` with all 32 lanes on left none on, `5` left all 32 on, and `s_bcnt1_i32_b64 s0, 0xff00ff` gave 32. llvm-mc rejects a constant as the mask operand of `v_cndmask_b32_e64` / `v_add_co_ci_u32_e64` and decodes one as "Invalid immediate", so those VALU callers never see a constant. **A constant held in an SGPR** (`s_mov_b32 s20, 0x3ffffc00`) is read the same way when it reaches a mask consumer: `mask_src` takes bit L of an SGPR that `holds_lane_mask` doesn't flag (a pair in a wave64 64-bit context: the high SGPR for lanes 32-63). In a wave32 or wave64 program a 32-bit bitwise SALU op (`s_not_b32`, `s_and/or/xor/andn2/orn2/nand/nor/xnor_b32`, `s_cselect_b32`) that writes EXEC/VCC (`exec_lo`/`vcc_lo` in wave32; `exec_lo`/`exec_hi` and mask-holding `vcc_lo`/`vcc_hi` in wave64, including after `s_mov_b64 vcc, 0/-1`) skips scalar constant folding, reads its operands through `Gen._mask_b32_src` / `mask_src` (collecting the opposite half through `wave_mask` if a wave64 op mixes `lo` and `hi` halves), preserves the untouched half of EXEC/VCC in wave64 (`exec_half_write` / `put_mask`), and votes SCC over the wave (wave32) or that 32-lane half (wave64, `scc_any_half`), matching `s_not_b32` and the binary ops on lane-mask SGPRs too; into a plain SGPR with a constant it stays a data read, because `lane_masks.py` classifies that SGPR as data when the other operand is a constant (`s_and_b32 s20, exec_lo, 1` then `s_bcnt1` must count the wave's bits: found by @Pierre-Kookis on #1792, GPU-reproduced), and `s_mov_b32 exec_lo/exec_hi, sN` takes each lane's bit. In a wave32 program a 32-bit bitwise SOP2 (`s_and/or/xor/andn2/orn2/nand/nor/xnor_b32`, `s_cselect_b32`) that writes EXEC/VCC reads both operands through `mask_src` (`Gen.sop2_b32_srcs`); into a plain SGPR it stays a data read, because `lane_masks.py` classifies that SGPR as data when the other operand is a constant (`s_and_b32 s20, exec_lo, 1` then `s_bcnt1` must count the wave's bits: found by @Pierre-Kookis on #1792, GPU-reproduced), and `s_mov_b32 exec_lo/exec_hi, sN` takes each lane's bit. A real mask is unchanged: it holds 0 or ~0 per lane, and bit L of that is the same 0 or 1. Until 2026-11-22 these took the value whole, so `s_and_saveexec_b32 s6, s20` with that constant, or `s_and_b32 exec_lo, exec_lo, 0xff00`, left every lane on (found writing `cs_w32_saveexec_ext`, #1771; CPU-checked by `tests/semantic/test_mask_src_sgpr_const.py`, and `tools/cf_diff.py` / `tools/salu_diff.py` still pass). `s_not_b32` on lane masks, `s_and/or/xor_b32` with two immediates into `vcc_lo`, and wave64 half-mask bitwise ops (destination half preservation, `exec_hi`, and `scc_any_half`) are CPU-checked in `tests/semantic/test_salu_b32_lane_masks.py` (wave32, wave64, and `--wave64-emulate`, validated with `spirv-val`) and GPU-checked on gfx1036, RTX 5080 (`--wave64-emulate`), and RX 9060 XT (RADV). Not covered here: a b32 op on one half of a wave64 mask, masks read as data (#293), and a literal with bit 31 set in a 64-bit position (zero- vs sign-extension not measured). GPU-checked with `runtime/test/shaders/cs_w32_mask_imm.asm` and `cs_w64_mask_imm.asm` on an NVIDIA GeForce RTX 5080 (driver 616.92; wave64 with `LEONIDA_W64_EMULATE=1`) and an AMD Radeon RDNA2 iGPU (driver 26.10.1, native 64-wide subgroup): both failed before on both GPUs. Run across every lane in `tests/semantic/test_value_semantics.py` (`LaneMaskConstants`). **A computed value written to EXEC** (`s_lshl_b32`, `s_add_u32`, `s_bfm_b32`, and every other SALU result that reaches `exec_lo`/`exec_hi` through `Gen.dst`) takes each lane's bit too: until 2026-11-24 the generic path tested the value for non-zero, so `s_lshl_b32 exec_lo, 1, s5` ran all 32 lanes of that half (SHADER-1264; `Gen.exec_bit`). The words are the GPU's, recorded in `runtime/test/shaders/cs_w32_exec_computed.asm` and `cs_w64_exec_computed.asm` (RTX 5070), and `tests/semantic/test_exec_computed.py` replays them through the CPU interpreter. A value that already holds this lane's bit of a mask (0 or ~0) gives the same answer. | -| Scalar select and pack (`s_cmov_b32`, `s_cmovk_i32`, `s_pack_ll/lh/hh_b32_b16`) | `s_cmov_b32` / `s_cmovk_i32`: D = SCC ? S0 : D (`s_cmovk_i32`'s S0 is the 16-bit immediate, sign-extended); SCC is read, not written; the destination must be an SGPR (a lane-mask destination, and `s_cmov_b64`, stay `Unsupported`, #210). `s_pack_*`: the low half of D from S0, the high half from S1, the letters naming the half of each (l = 15:0, h = 31:16), S0 first; GFX10 has no `s_pack_hl`; SCC not written. Source: RDNA2 ISA SOP1/SOP2/SOPK. CPU-checked by `tests/semantic/test_salu_cmov.py` and `test_salu_pack.py`; the translated shaders were run on NVIDIA by reviewers (`s_cmov*`: RTX 5090, RTX 4050 and Radeon 740M in #613; `s_pack_*`: RTX 5090 in #449). **Hardware-verified on RDNA2** (`gfx1035`, wave32 and wave64 via `tools/int_hw_probe.py --oracle both`, SHADER-137, SCC kept). | -| Vector integer additions (`v_mul_hi_u32_u24`/`v_mul_hi_i32_i24`, `v_lshrrev_b64`/`v_ashrrev_i64`, `v_qsad_pk_u16_u8`/`v_mqsad_pk_u16_u8`) | `v_mul_hi_*24`: the high 32 bits of the 48-bit product of the low 24 bits, zero-extended (u24) or sign-extended from bit 23 (i24); the high halves of `v_mul_u32_u24` / `v_mul_i32_i24`. `v_lshrrev_b64` / `v_ashrrev_i64`: the pair (or a 64-bit constant) shifted right by S0 & 63, logically or arithmetically, through the `v_lshlrev_b64` code. `v_qsad_pk_u16_u8` / `v_mqsad_pk_u16_u8`: D.u16[k] = (S2.u16[k] + byte SAD of the 32-bit window S0[8k+31:8k] against S1) & 0xFFFF; the m form skips bytes where S1's byte is 0; `clamp` raises `Unsupported`. Source: RDNA ISA pseudocode. CPU-checked by `tests/semantic/test_alu_mul_hi_24.py`, `test_alu_shift_b64.py`, `test_alu_qsad.py`; run on NVIDIA by reviewers (`v_mul_hi_*24`: RTX 5090 and RTX 5070 in #440; `v_qsad`/`v_mqsad`: 24 cases bit-exact on an RTX 3060 in #623). **Not measured on RDNA2.** **Hardware-verified on RDNA2** (`gfx1035`, wave32 and wave64 via `tools/int_hw_probe.py --oracle both`, SHADER-137), and on native `gfx1036` (AMD Radeon Graphics) with 0 mismatches across signed/unsigned products, shifts, and sliding windows. **Hardware-verified on RDNA2** (`gfx1035`, wave32 and wave64 via `tools/int_hw_probe.py --oracle both`, SHADER-137). | -| 64-bit constant vector compares | For `i64`, `u64` and `f64`, V_CMP writes the predicate to VCC or the named scalar mask, with inactive lane bits cleared. V_CMPX ANDs the predicate into EXEC and preserves VCC. Both predicates ignore the source values, including NaNs. The 12 instructions in `tests/semantic/fixtures/vopc_constant_64.asm` assemble for gfx1030 and are CPU-checked with active and inactive lanes in `test_vopc_const_ordered.py`. Measured on native gfx1100 (Radeon RX 7900 XTX, driver 26.10.1) as raw compute kernels: with EXEC preset to 0x55555555, `v_cmp_t_i64`, `v_cmp_t_u64` and `v_cmp_tru_f64` write 0x55555555 into the destination mask and the `v_cmp_f_*` forms write 0, so the inactive lane bits are cleared, while the other mask keeps its preset words (`s[10:11]` stays 0xdeadbeef/0xfeedface, VCC stays 0x0f0f0f0f/0xf0f0f0f0); `v_cmpx_t_*` leaves EXEC at 0x55555555 and `v_cmpx_f_*` clears it to 0, with VCC untouched in both; an operand holding a quiet NaN changes nothing. In wave32 only the low 32-bit mask register is written — `s11` and `vcc_hi` keep their previous words for a constant and a real `v_cmp_eq_i64` alike — where the wave64 pair `s[10:11]` receives 0xffffffff in both halves. [AMD RDNA 2 ISA, VOPC](https://www.amd.com/content/dam/amd/en/documents/radeon-tech-docs/instruction-set-architectures/rdna2-shader-instruction-set-architecture.pdf) | -| Constant and ordered VOPC, `v_cmp(x)_nlg_*`, `v_cvt_off_f32_i4`, `v_pipeflush` | `v_cmp(x)_f_*` is always false, `v_cmp(x)_t_*` (integers) and `v_cmp(x)_tru_*` (floats) always true; `v_cmp(x)_o_{f32,f16}` is true when neither source is NaN, `_u_` when either is (`OpIsNan`), and `_nlg_` when `x == y` or either source is NaN (`OpFUnordEqual`, completing all 16 IEEE-754 RDNA2 float VOPC predicates; LLVM `gfx10_asm_vopc.s`); the result goes through the usual VOPC path (VCC, an SGPR mask, or EXEC for `v_cmpx`; off lanes give 0). `v_cvt_off_f32_i4`: D = sext(S0[3:0]) / 16 (the ISA's CVT_OFF_TABLE, -0.5 .. 0.4375), exact, output modifiers apply. `v_pipeflush` only flushes the VALU pipeline and is translated as nothing, like `v_nop`. Source: RDNA2 ISA VOPC and VOP1. CPU-checked by `tests/semantic/test_vopc_const_ordered.py`, `tests/semantic/test_float_compares.py` (`nlg`; GPU-checked by `ps_cmp_nlg.asm`: f32 and f16 with ±0, quiet and signalling NaN, ±inf and ignored f16 high halves, the e64 form with `abs`/`neg`, and `v_cmpx_nlg` on equal and NaN operands, Tesla V100 (NVIDIA 580.95.05, Linux)), `test_alu_cvt_off.py` (GPU-checked by `ps_cvt_off.asm`, upper bits ignored and `mul:4` with and without `clamp`), `test_valu_pipeflush.py`; the constant/ordered float compares were run on an RTX 5090 (16 draws, quiet and signalling NaNs) and the suite on RTX 4050 / Radeon 740M in #620; `v_pipeflush` on RTX 5090 / RTX 3060 in #735. All 16 f16 predicates (`v_cmp_{f,lt,eq,le,gt,lg,ge,o,u,nge,nlg,ngt,nle,neq,nlt,tru}_f16`, e32 and e64) are GPU-checked on quiet and signalling NaN, +-0, +-inf, denormals and junk high halves by `ps_vcmp_f16.asm` and `ps_vcmp_f16_e64.asm` (RTX 5080 and Radeon gfx1036, 4096/4096 exact), CPU side `tests/semantic/test_vcmp_f16.py`. The 16 `v_cmpx_*_f16` forms (e32 and e64) are GPU-checked the same way by `ps_vcmpx_f16.asm` and `ps_vcmpx_f16_e64.asm` (EXEC result on every case, VCC kept, EXEC only narrowed; RTX 5080 and Radeon gfx1036), CPU side `tests/semantic/test_vcmpx_f16.py`. | -| Relative VGPR moves (`v_movrel*`) | The VGPR file is a Function-scope uint array, so `v_movrels_b32`/`v_movreld_b32`/`v_movrelsd_b32` become dynamic array accesses at `reg + M0` (the whole of M0, as the RDNA2 ISA's opcode descriptions say). `v_movrelsd_2_b32` (VOP1 opcode 72) offsets each side by its own field: VGPR[D + M0[25:16]] = VGPR[S0 + M0[9:0]], other M0 bits ignored (RDNA2 ISA §12.8 opcode description and the RDNA3 ISA; the RDNA2 §6.6 summary table prints M0[7:0] for the source). The write keeps inactive lanes. The SPIR-V register array has 256 entries. An effective index outside this array reads VGPR0 or drops the write, following RDNA2 ISA §3.6.1. A smaller per-wave hardware allocation is not available to this check. The boundary is checked by `tests/semantic/test_relative_vgpr_bounds.py`. Not modelled: the hardware's range check against the wave's VGPR allocation (an out-of-range source reads VGPR0, an out-of-range write is dropped). CPU-checked by `tests/semantic/test_alu_movrelsd_2.py` (including set ignored M0 bits); GPU-checked with `runtime/test/shaders/cs_movrelsd_2.asm` (the ISA's own example, v25 ← v17 with M0 = (20 << 16) \ \| 10) on NVIDIA RTX 4050 Laptop (Ada) and AMD Radeon 740M (RADV). | -| `v_swaprel_b32` | GFX10 VOP1 opcode 104: swap `VGPR[D + M0[25:16]]` and `VGPR[S0 + M0[9:0]]`, the two M0 fields `v_movrelsd_2_b32` uses; the other M0 bits are ignored (RDNA2 ISA opcode description). Both registers are read before either is written. When both name one register it keeps its value. Inactive lanes keep both registers (`OpSelect` on `active`). As for `v_movrel*`, the bounds check uses the 256 entries in the SPIR-V array. Both operands are destinations, so either invalid index suppresses the whole swap (RDNA2 ISA §3.6.1). As for `v_movrel*`, the hardware's range check against the VGPR allocation is not modelled. A non-VGPR operand raises `Unsupported`. Until 2026-11-22 the op raised `Unsupported`. CPU-checked by `tests/semantic/test_alu_swaprel.py` (both fields, ignored M0 bits, a self-swap, a register-file model). **Not GPU-verified.** **Hardware-verified on RDNA2** (`gfx1035`, Windows 11, driver `26.5.1`, wave32 & wave64 via `tools/int_hw_probe.py --oracle both --group valu_swaprel`): M0[25:16] & M0[9:0] offsets, ignored upper M0 bits (`0xfc01fc02`), self-swap, and inactive EXEC lanes all match bit-for-bit. | -| Relative SGPR reads (`s_movrels_b32`, `s_movrels_b64`) | `D = SGPR[S0 + M0]`; the b64 form reads the pair at `S0 + M0` and `S0 + M0 + 1` (RDNA2 ISA SOP1). The SGPR file is a Function-scope uint array, so this is a dynamic load, as for `v_movrels`. Every SGPR write stores into that array (`store_reg`), so the load sees the current value. All reads happen before the destination is written, so D may overlap the source. SCC is not written. The index wraps to the 128 array slots, so it cannot reach the lane-mask parking slots past them. An SGPR that `lane_masks.py` marks as a lane mask (a saved EXEC, a `v_cmp` result) holds only this lane's bit, so the whole wave's mask word is collected for each such SGPR (as for `s_bcnt1`) and read instead when the index lands on it; D then holds the mask as data (SHADER-284, CPU-checked by `tests/semantic/test_salu_movrels_lane_mask.py`, wave32 and wave64). **Not modelled:** the hardware's range check, and reads past s105 landing on VCC and the other special registers. `s_movreld_b32/b64`, the relative writes, stay `Unsupported`, because the translator keeps translate-time knowledge of SGPR values (literal S# words, descriptor caches) that a dynamic write would invalidate. Until 2026-11-22 both reads raised `Unsupported`. CPU-checked by `tests/semantic/test_salu_movrels.py` (M0 from 0 to 5 and from a register, the b64 pair, an overlapping destination, SCC kept, `s_movreld` rejected). **Hardware-verified on RDNA2** (`gfx1035`, wave32 and wave64 via `tools/int_hw_probe.py --oracle both`, SHADER-137, SCC kept; lane-mask SGPR collection is CPU-checked only). **Not GPU-verified.** | -| `v_div_fixup_f16`, `v_div_fixup_f64` | Final IEEE-754 special-case fixup for division (VOP3, `S0` quotient, `S1` denominator, `S2` numerator) under the game's `MODE` (`ieee=0, denorm16_64=3, dx10_clamp=1`): `sign_out = sign(S1) ^ sign(S2)`; `NaN(S2)` → quieted `S2`; `NaN(S1)` → quieted `S1`; `NaN(S2)` → `S2` unchanged (sNaN not quieted under `IEEE=0`); `NaN(S1)` → `S1` unchanged; `(0/0)` or `(±inf/±inf)` → canonical negative qNaN (`0xFE00` for f16, `0xFFF80000_00000000` for f64); `(x/±inf)`, `(±0/y)`, or guaranteed exponent underflow (`exp(S2) - exp(S1) <= -25` for f16, `<= -1075` for f64) → `±0` with `sign_out`; `(x/±0)`, `(±inf/y)`, or guaranteed exponent overflow (`exp(S2) - exp(S1) >= 16` for f16, `>= 1024` for f64) → `±inf` with `sign_out`; otherwise `copysign(S0, sign_out)` (including `NaN(S0)` keeping its payload with `sign_out`). `(x/±inf)` or `(±0/y)` (plus `exp(S2) - exp(S1) <= -1076` on f64 only; f16 has no exponent-difference cutoff) → `±0` with `sign_out`; `(x/±0)`, `(±inf/y)`, or `NaN(S0)` → `±inf` with `sign_out` (no exponent-difference overflow cutoff on either f16 or f64); otherwise `copysign(S0, sign_out)`. Computed bit-exactly on integer words (no `OpCapability Float64` for plain `v_div_fixup_f64`); VOP3 input modifiers (`abs`/`neg`, plus `op_sel:[s0,s1,s2,dst]` on f16 with the unwritten half preserved) and `clamp`, which applies in every MODE. `mul:2`/`mul:4`/`div:2` are ignored by hardware here: measured by @fiestorra on a gfx1036 iGPU (Radeon(TM) Graphics, drivers `31.0.24002.92` and `32.0.21045.29003` (the same counts on both), raw ISA through `tools/hw_oracle`, `tools/f64_omod_probe.py`, 4 inputs x 5 modifier forms x 5 MODEs for each of the two ops, wave32 and wave64 identical), the f16 and the binary64 result scale only under `IEEE=0` with `denorm_mode_16_64=0`; under `denorm_mode_16_64=3` the scaling is dropped while `clamp` still saturates, which is the `MODE` this row assumes, so only `clamp` is applied and `Float64` is enabled on f64 only when `clamp` is requested. Source: AMD [RDNA 2 ISA reference](https://www.amd.com/content/dam/amd/en/documents/radeon-tech-docs/instruction-set-architectures/rdna2-shader-instruction-set-architecture.pdf) (`V_DIV_FIXUP_F16`, `V_DIV_FIXUP_F64`). **Not measured on RDNA2 hardware** (translated GPU output checked on RTX 5070 by @duudiis). **Hardware-measured on RDNA2** (`gfx1036`, Windows driver `32.0.21042.62`, `tools/hw_oracle`, `ieee=0, denorm16_64=3, dx10_clamp=1`, wave32, by @timelery): `NaN(S0)` → `±inf`, f16 has no exponent-difference underflow/overflow check, f64 has underflow cutoff `e2 - e1 <= -1076` with no overflow check, and sNaN passes through unchanged under `IEEE=0`. Checked bit-for-bit on the CPU (`spirv_mini_interp`) and with `spirv-val` by `tests/semantic/test_alu_div_fixup.py`; not run on the shader corpus. | -| Image instruction without a VGPR data operand | `llvm-mc` accepts `off`, an SGPR or a constant where an `image_*` instruction names the VGPR range of its result or data (`image_sample off, v[1:2], s[16:23], s[24:27] dmask:0xf dim:SQ_RSRC_IMG_2D`); no compiler emits it (the texels would have nowhere to go). The translator raises `Unsupported` (` destination` for `image_op` and `image_get_lod`, ` data` for the `image_misc` group: `image_load_mip`, `image_get_resinfo`, `image_store`, the atomics) instead of the `KeyError` it gave when it wrote the result. A probe of about 60,000 DS, MUBUF, MTBUF, MIMG, SMEM and FLAT/GLOBAL/SCRATCH operand and modifier variations (glc, slc, dlc, lds, tfe, d16, a16, unorm, dmask, dim, offset, idxen, offen, addr64, format; as written and as `llvm-mc` prints them; pixel and compute stages) found no other `IndexError`, `KeyError` or `TypeError`. CPU-checked by `tests/semantic/test_mem_crash_forms.py`. | -| 16-bit float widening in typed buffer loads | A half NaN in a `buffer_load_format_*` / `tbuffer_load_format_*` load of formats 13 (`16_FLOAT`), 29 (`16_16_FLOAT`) or 71 (`16_16_16_16_FLOAT`) widens to f32 as `sign \| 0x7F800000 \| (payload << 13)`: the sign is kept, the 10-bit payload moves into the f32 mantissa unchanged, and the quiet bit is not forced, so an sNaN stays signalling. Measured natively on RDNA2 (gfx1036, wave32 and wave64, `_x`/`_xy`/`_xyzw`, MUBUF and MTBUF, `tools/f16_widen_probe.py`): 0x7ddb → 0x7fbb6000, 0x7fe6 → 0x7ffcc000, 0x7fbb → 0x7ff76000, 0xffb2 → 0xfff64000, 0x7fcb → 0x7ff96000, 0xff96 → 0xfff2c000, 0x7c01 → 0x7f802000, 0xfc01 → 0xff802000, and the controls 0x3c00 → 0x3f800000, 0xc000 → 0xc0000000. `v_cvt_f32_f16` (what a driver lowers `UnpackHalf2x16` to) differs on an sNaN, which it quiets with the payload kept (0x7ddb → 0x7ffb6000), and `UnpackHalf2x16`'s NaN result is undefined; the mini interpreter canonicalised it to 0x7fc00000. Until 2026-11-23 `Gen.decode_format` used `UnpackHalf2x16` for every half and so lost NaN payloads on all three formats; it now keeps `UnpackHalf2x16` for the non-NaN halves (an exact widening) and builds the NaN word from the bits with integer ops. `tools/mem_diff.py`'s reference was right only on Python 3.14 (its `struct` `'= 0.25`, `cl * (scale + 1)` is an exact even integer in f32, so `cl * (scale + 1) - RoundEven(cl)` rounds the exact product once without binary32 double-rounding ties near `±0.5`. `clamp` and output multipliers (`mul:*`/`div:*`) are rejected as `Unsupported`. VOP3 `clamp`, `mul:2`, `mul:4`, `div:2` (and combinations) and SDWA `clamp` are hardware no-ops on these integer-destination conversions and are accepted without changing output semantics; unsupported modifiers or invalid form/modifier pairs (e.g., `mul:8`, `_sdwa mul:*`, `_e32`/`_dpp` output modifiers) still raise `Unsupported`. Source: AMD [RDNA 2 ISA reference](https://www.amd.com/content/dam/amd/en/documents/radeon-tech-docs/instruction-set-architectures/rdna2-shader-instruction-set-architecture.pdf) (`V_CVT_NORM_I16_F16`, `V_CVT_NORM_U16_F16`). **Hardware-verified on RDNA2** (AMD Radeon RDNA2 iGPU `gfx1036`, Windows 11, driver `32.0.21043.5001`, wave32 and wave64 via `tools/hw_oracle`, @Pierre-Kookis): 655,360 / 655,360 exact words across all 65,536 f16 inputs in five forms (`_e32`, `_e32 ieee=1`, `_e64 -v1`, `_e64 \|v1\|`, `_sdwa WORD_1`), including NaN → 0, ±inf clamps, denormals, single-rounding ties near ±0.5, and the untouched destination half; Checked on the CPU and with `spirv-val` by `tests/semantic/test_alu_cvt_norm_f16.py`. **Hardware-verified on RDNA2** (AMD Radeon gfx1036, wave32 and wave64, `tools/int_hw_probe.py --oracle both --group valu_cvt_norm_f16`): the same 34 inputs through both ops with the unwritten half kept and with `neg`/`abs`, bit-identical to the translator; the RDNA2 assembler takes no `op_sel` on these two opcodes, so only the VOP3P-style `pknorm` forms have an `op_sel` check. Not run on the shader corpus. **output modifiers additionally verified natively on RDNA2** (`gfx1036`, Windows 11, driver `32.0.21045.29003`, wave32 and wave64 via `tools/cvt_norm_mods_probe.py --hw-arch gfx1036`): exhaustive 65,536/65,536 f16 sweeps across VOP3 `plain`, `clamp`, `mul:2`, `mul:4`, `div:2`, `clamp mul:2`, `clamp div:2`, plus `MODE.FP_ROUND=RTZ` (`0xCC`), `IEEE=1` (`0x2C0`), `_e64` high-half preservation, and `_sdwa clamp` (`WORD_0`/`WORD_1`, `UNUSED_PRESERVE`/`UNUSED_SEXT`/`UNUSED_PAD`) all match with 0 mismatches and 0 wave diffs (`1,050,708` total word evaluations across the four probe ops). **GPU-verified through Vulkan** (wave32 synthetic compute shader via `vk_compute_test` with `VK_LAYER_KHRONOS_validation` `1.4.363`, 20 `v_cvt_norm_*` output words): bit-exact on `AMD Radeon RX 9070 XT` (driver `26.11.2 (LLPC)`, `driverVersion 2.0.416`, Vulkan `1.4.359`) and `AMD Radeon(TM) Graphics` (`gfx1036`, driver `26.11.2`, `driverVersion 2.0.353`, Vulkan `1.4.315`), 0 validation errors. Checked on the CPU and with `spirv-val` by `tests/semantic/test_alu_cvt_norm_f16.py` and `tests/semantic/test_cvt_norm_mods.py`; not run on the shader corpus. | -| `v_frexp_mant_f32`, `v_frexp_exp_i32_f32`, `v_ldexp_f32` | Computed on the binary32 word, with no float arithmetic. A normal input has a biased exponent of 1..254. `v_frexp_mant_f32` returns the input with its exponent set to 126 (a mantissa in [0.5, 1), sign kept); `v_frexp_exp_i32_f32` returns the biased exponent minus 126, so mantissa × 2^exponent is the input. Zero and denormals (read as zero) give a signed zero and exponent 0; infinities and NaNs give the input unchanged and exponent 0. `v_ldexp_f32` is S0 × 2^S1 with S1 a signed integer: S1 is clamped to [-512, 512] and added to the exponent field; a new field above 254 gives ±infinity, one of 0 or below gives ±0 (no denormal results), and zero, infinities and NaNs ignore S1. Neg/abs, `clamp` and the output multipliers apply as for other float ops (not to the integer exponent result). Source: the AMD [RDNA 2 ISA reference](https://www.amd.com/content/dam/amd/en/documents/radeon-tech-docs/instruction-set-architectures/rdna2-shader-instruction-set-architecture.pdf) pseudocode for these three opcodes. **Measured natively** on an RDNA2 iGPU (gfx1036, `tools/hw_oracle`): under the MODE inferred for the game (IEEE 0, f32 denormals flushed) the hardware gives the translator's word for all 30 special inputs of each frexp op and 741 ldexp cases (denormal inputs, results in and below the denormal range, every exponent clamp edge, NaN payloads). With f32 denormals kept the hardware normalizes denormal inputs and returns denormal ldexp results, and with IEEE 1 it quiets signalling NaNs; neither is modelled, since the game runs with both off. Checked on the CPU by `tests/semantic/test_alu_frexp_ldexp.py`; not run on the shader corpus. | -| `v_mad_u16`, `v_mad_i16` | `D = S0 * S1 + S2` on the low 16-bit halves (VOP3 only). The product and sum are formed in 32 bits, so nothing overflows, and the low 16 bits are the result. `op_sel` bits 0..2 read the high half of a source and bit 3 writes the high half of the destination; like the other opsel-capable 16-bit VOP3 ops the other half of the destination is kept (see *16-bit results*). `clamp` saturates the full-width result to [0, 65535] (`v_mad_u16`) or [-32768, 32767] (`v_mad_i16`). Source: the AMD [RDNA 2 ISA reference](https://www.amd.com/content/dam/amd/en/documents/radeon-tech-docs/instruction-set-architectures/rdna2-shader-instruction-set-architecture.pdf) pseudocode and Mesa ACO's `can_use_opsel`. Checked on the CPU by `tests/semantic/test_alu_mad_u16_i16.py`; **hardware-verified on RDNA2** (`gfx1035`, wave32 and wave64 via `tools/int_hw_probe.py --oracle both`, SHADER-137): full-width `clamp`, `op_sel` and the untouched destination half match bit-for-bit. Not run on the shader corpus. | -| `v_frexp_mant_f16`, `v_frexp_exp_i16_f16`, `v_ldexp_f16` | The binary16 versions of `v_frexp_mant_f32`, `v_frexp_exp_i32_f32` and `v_ldexp_f32`, computed on the f16 word of the low half with no float arithmetic (`op_sel` picks the high half of a source; the last `op_sel` bit sends the result to the high half of the destination; the other half of the destination is kept). A normal input has a biased exponent of 1..30. `v_frexp_mant_f16` returns the input with its exponent set to 14 (a mantissa in [0.5, 1), sign kept); `v_frexp_exp_i16_f16` returns the biased exponent minus 14 as a 16-bit integer, so mantissa × 2^exponent is the input. Zero and denormals (read as zero) give a signed zero and exponent 0; infinities and NaNs give the input unchanged and exponent 0. Zero gives a signed zero and exponent 0; infinities and NaNs give the input unchanged and exponent 0. f16 denormals are kept, as in the MODE inferred for the game (`denorm_mode_16_64` = 3): a denormal input is normalized (`v_frexp_mant_f16(0x0001)` = 0.5 with exponent -23, `0x03ff` gives `0x3bfe` and -14). `v_ldexp_f16` is S0 × 2^S1 with S1 the low 16 bits of the source read as a signed integer: S1 is clamped to [-64, 64] and added to the exponent field; a new field above 30 gives ±infinity, one of 0 or below gives ±0 (no denormal results), and zero, infinities and NaNs ignore S1. S1 is clamped to [-64, 64]; a result above the f16 range gives ±infinity, and one below the smallest normal is a denormal rounded to nearest even (1.0 × 2^-15 = `0x0200`, 1.5 × 2^-24 = `0x0002`, 1.0 × 2^-25 = 0, 65504 × 2^-30 rounds up to `0x0400`); zero, infinities and NaNs ignore S1. Source neg/abs apply to the float operand. Under the game's console MODE (`0x1c0`: `IEEE=0`, `DX10_CLAMP=1`, `denorm_mode_16_64=3`) and under `IEEE=1` (`0x3c0`), VOP3 `mul:2`, `mul:4`, and `div:2` are hardware no-ops on `v_frexp_mant_f16` and `v_ldexp_f16` (since `denorm_mode_16_64=3` disables `omod` on f16 results), while `clamp` clamps to [0.0, 1.0] (negative values and NaNs clamp to +0.0, values > 1.0 and +Inf clamp to 1.0, [0.0, 1.0] kept) both alone and combined with `mul:*`/`div:*`; on `v_frexp_exp_i16_f16` (16-bit integer result), `clamp` and `mul:2`/`mul:4`/`div:2` are all hardware no-ops under every MODE (`0x1c0`, `0x100`, `0x3c0`). Under the `denorm_mode_16_64=0, IEEE=0` (`0x100`) control, `mul:2`/`mul:4`/`div:2` scale `v_frexp_mant_f16` and `v_ldexp_f16` (not modelled because the game runs with `denorm_mode_16_64=3`). Unknown or unmodelled modifiers raise `Unsupported`. Source: the AMD [RDNA 2 ISA reference](https://www.amd.com/content/dam/amd/en/documents/radeon-tech-docs/instruction-set-architectures/rdna2-shader-instruction-set-architecture.pdf) pseudocode for these three opcodes. **Not measured on hardware**: the denormal input and result handling, the NaN payload, and whether `v_frexp_exp_i16_f16` keeps the high half of its destination (it is modelled like the other 16-bit ops here, which keep it) are the translator's choice. **Measured natively** on an RDNA2 iGPU (gfx1036, AMD Windows driver 32.0.21045.16010, `tools/hw_oracle`) under IEEE 0, DX10_CLAMP 1, f32 denormals flushed and f16 denormals kept: the translated rule gives the hardware's word for every one of the 65,536 f16 inputs of both frexp ops and of `v_ldexp_f16` under 16 exponents (1,048,576 cases), and the high half of the destination is kept by all three. Until 2026-11-22 the translator read f16 denormals as zero and flushed denormal ldexp results, which the hardware does only with `denorm_mode_16_64` = 0. Not modelled (the game runs with IEEE 0): with IEEE 1 a signalling NaN is quieted (`0x7c01` gives `0x7e01`). VOP3 output modifiers (`clamp`, `mul:2`, `mul:4`, `div:2`, `clamp` + `mul:*`/`div:*`, and source `abs`/`neg`) were additionally measured natively on an RDNA2 iGPU (`AMD Radeon(TM) Graphics`, `gfx1036`, Windows driver `32.0.21045.29003`, wave32 & wave64 via `tools/frexp_ldexp_f16_mods_probe.py`): 3,466 / 3,466 exact words (3,360 console-MODE grid words, 22 source-modifier words, and 84 `0x100`/`0x3c0` control words, 0 wave diffs, 0 omod diffs). Checked on the CPU and with `spirv-val` by `tests/semantic/test_alu_frexp_ldexp_f16.py`, `tests/semantic/test_frexp_ldexp_f16_mods.py`, and `tests/test_frexp_ldexp_f16_mods_probe.py`; not run on the shader corpus. | -| `v_frexp_mant_f64`, `v_frexp_exp_i32_f64` | Binary64 versions of `v_frexp_mant_f32` and `v_frexp_exp_i32_f32`, computed bit-exactly on the `(lo, hi)` dword pair without requiring `OpCapability Float64` or `Int64` unless VOP3 output modifiers are used. A normal input has biased exponent `1..2046` (bits `[62:52]`): `v_frexp_mant_f64` sets the biased exponent to `1022` (`0x3FE00000`, mantissa in `[0.5, 1)` with sign and low mantissa bits kept), and `v_frexp_exp_i32_f64` returns `e - 1022` as a 32-bit signed integer so `mantissa × 2^exponent == input`. Under the default f16/f64 denormal mode (`denorm_mode_16_64` = 3, matching `v_frexp_mant_f16`/`v_frexp_exp_i16_f16`), non-zero subnormals (`e == 0`, 52-bit fraction `≠ 0`) are normalized into `[0.5, 1)` with sign preserved and exponent `msb − 1073` (`-1073..-1022`; e.g. `0x0000000000000001` → `0x3FE0000000000000` / `-1073`, `0x000FFFFFFFFFFFFF` → `0x3FEFFFFFFFFFFFFE` / `-1022`). Zero and denormals give signed zero and exponent `0`; infinities and NaNs pass through unchanged with exponent `0`. VOP3 source `abs`/`neg` flip/clear bit 31 of `hi`; VOP3 output modifiers are gated by the `MODE`, measured for this row by @fiestorra on a gfx1036 iGPU (Radeon(TM) Graphics, drivers `31.0.24002.92` and `32.0.21045.29003` (the same counts on both), raw ISA through `tools/hw_oracle`, `tools/f64_omod_probe.py`, 7 mantissa inputs x 5 modifier forms x 5 MODEs, wave32 and wave64 identical): `clamp` applies to `v_frexp_mant_f64` in every MODE via `clamp_mods_f64` (`OpCapability Float64`), while `mul:2`/`mul:4`/`div:2` scale the mantissa only under `IEEE=0` with `denorm_mode_16_64=0` and are ignored under `IEEE=1` and under `denorm_mode_16_64=3`, the mode this row assumes, so only `clamp` needs `Float64` here. All output modifiers are rejected on `v_frexp_exp_i32_f64`. Source: AMD [RDNA 2 ISA reference](https://www.amd.com/content/dam/amd/en/documents/radeon-tech-docs/instruction-set-architectures/rdna2-shader-instruction-set-architecture.pdf) (`V_FREXP_MANT_F64`, `V_FREXP_EXP_I32_F64`) and LLVM `VOP1Instructions.td`. **Measured natively** on an AMD Radeon(TM) Graphics RDNA2 GPU (`gfx1036`, not the console's `gfx1013`; Windows driver 32.0.21042.62, `tools/hw_oracle`, wave32 and wave64 identical on every case): under `IEEE=0, denorm_mode_16_64=3, DX10_CLAMP=1` all 71 cases (all 52 single-bit subnormal positions `0..51`, lo/hi boundary-crossing multi-bit subnormals, negative subnormals, `±0`, normals, `±inf`, `qNaN`, `sNaN`, plus VOP3 `abs`/`neg`/`clamp`) matched bit-for-bit. Until 2026-11-22 the translator flushed binary64 subnormals to `±0` / exponent `0`, which the hardware does only under `denorm_mode_16_64=0`. Not modelled (the game runs with `IEEE=0, denorm_mode_16_64=3`): `IEEE=1` quieting signalling NaNs (`0x7FF0000000000001` → `0x7FF8000000000001`), `denorm_mode_16_64=0` flushing subnormals, and `denorm_mode_16_64=3` ignoring `omod`. **Not measured on hardware** beyond that gate: it was measured by @fiestorra with `tools/f64_omod_probe.py` (see the modifiers sentence above), while the pass-through of NaN payloads under `IEEE=0` is part of the 71 cases above and denormal-input handling follows the f32 rule. Checked on the CPU and with `spirv-val` by `tests/semantic/test_alu_frexp_f64.py`; not run on the shader corpus. | -| `v_ldexp_f64` | Binary64 load-exponent (`D.f64 = S0.f64 × 2^(S1.i32)`), lowered bit-exactly on the `(lo, hi)` dword pair using only 32-bit integer ops (no `OpCapability Float64` or `OpCapability Int64`, even with `clamp`). `±0`, `±inf`, and both quiet and signalling NaNs (under `IEEE = 0`) pass through bit-for-bit unchanged after `S0` `abs`/`neg`. Subnormal inputs (`denorm_mode_16_64 = 3`) are normalized via `FindUMsb` before adding `clamp(S1, -4096, 4096)` to the exponent field; overflow (`e2 >= 2047`) gives `±inf`, and subnormal outputs (`e2 <= 0`) shift the 53-bit significand right by `sh = 1 - e2` (`1..53`) and round to nearest even (carry into bit 52 yields `±min_norm`; `sh >= 54` flushes to `±0`). VOP3 `clamp` applies bit-exactly in integer ops (`DX10_CLAMP = 1`: `NaN`, `-0.0`, `<0` → `+0.0`; `>1.0` including `+inf` → `1.0`). VOP3 `omod` (`mul:2`/`mul:4`/`div:2`) is rejected as `Unsupported` because hardware ignores it under `denorm_mode_16_64 = 3` and applies it under `denorm_mode_16_64 = 0`. For immediate `S0` operands, inline integers `-16..64` sign-extend across 64 bits while 32-bit literals occupy `[63:32]` with `[31:0] = 0`. Source: AMD [RDNA 2 ISA reference](https://www.amd.com/content/dam/amd/en/documents/radeon-tech-docs/instruction-set-architectures/rdna2-shader-instruction-set-architecture.pdf) (`V_LDEXP_F64`). **Measured natively** on an RDNA2 iGPU (`gfx1036`, Windows driver `32.0.21042.62`, wave32 and wave64 via `tools/hw_oracle` under game MODE `IEEE=0`, `DX10_CLAMP=1`, `denorm32=0`, `denorm16_64=3`): 870 / 870 cases bit-exact across all 52 subnormal input bit positions, all 54 subnormal right-shift boundaries and exact half-ULP ties, carry into `min_norm`, `±0`/`±inf`/qNaN/sNaN, `abs`/`neg`/`clamp`, immediate/literal `S0`, and seeded random inputs (not modelled: `IEEE=1` quiets signalling NaNs). Checked on the CPU and assembled by `tests/semantic/test_alu_ldexp_f64.py`; not run on the shader corpus. | -| `v_min3_f16`, `v_max3_f16`, `v_min3_i16`, `v_min3_u16`, `v_max3_i16`, `v_max3_u16`, `v_med3_i16`, `v_med3_u16` | Three-operand 16-bit min/max/median (VOP3 only). `op_sel` bits 0..2 read the high half of S0..S2, bit 3 writes the high half of D, and the unwritten half of D is kept (see *16-bit results*). `v_min3_f16` and `v_max3_f16` read each selected f16 half through `Gen.f16_in` (`neg`/`abs` apply to the selected half), fold with `NMin`/`NMax` (so a NaN operand yields the other operand and −0 orders below +0, matching `v_min3_f32`/`v_max3_f32` and `v_med3_f16`), then apply VOP3 `omod`/`clamp` and `Gen.f16_out`. The 16-bit integer ops zero-extend (`u16`) or sign-extend (`i16`) the selected 16-bit halves, evaluate `UMin`/`UMax`/`UClamp` or `SMin`/`SMax`/`SClamp`, and write the low 16 bits into the selected half of D; `clamp` is supported on integer min3/max3/med3 as an identity no-op on the 16-bit container (hardware-verified on gfx1036 across wave32 and wave64); non-VGPR `op_sel` destinations raise `Unsupported`. `clamp` and non-VGPR `op_sel` destinations raise `Unsupported`. Until 2026-11-22 all eight raised `Unsupported`. Source: AMD [RDNA 2 ISA reference](https://www.amd.com/content/dam/amd/en/documents/radeon-tech-docs/instruction-set-architectures/rdna2-shader-instruction-set-architecture.pdf) VOP3 opcodes `0x351`–`0x356`, `0x359`–`0x35A`, and Mesa ACO's `can_use_opsel`. **Hardware-verified on RDNA2** (gfx1036 iGPU, AMD Windows driver 32.0.21045.16010, `tools/hw_oracle`, IEEE 0 with f16 denormals kept): 6,092 cases (every triple of ±0, a denormal, 1.0, -1.0, 2.0, ±inf, a quiet and a signalling NaN for each f16 op; every triple of 8 edge values for the i16/u16 ops; `op_sel` on each source and the destination; a 0xabcd high half on every source) match the translator's word, including keeping the destination half and returning `src0`'s NaN bits unchanged (`0x7c01` stays signalling under IEEE 0) when all three operands are NaN (`ALL_NAN_SRC0_SIGNALLING` in `tests/semantic/test_alu_min3_max3_med3_16_hw.py`, alongside 540 sampled measured words). `tests/semantic/test_alu_min3_max3_med3_16_hw.py` holds 540 of the measured words. **Not GPU-verified.** CPU-checked by `tests/semantic/test_alu_min3_max3_med3_16.py`, `tests/test_f16_op_sel.py`, and `tests/test_f16_op_sel_values.py`. CPU-checked by `tests/semantic/test_alu_min3_max3_med3_16.py`, `tests/test_f16_op_sel.py`, and `tests/test_f16_op_sel_values.py`; also **hardware-verified on RDNA2** (`gfx1035`, Windows 11, driver `26.5.1`, wave32 & wave64 via `tools/int_hw_probe.py --oracle both --group valu_min3_max3_med3_16`): all eight ops (`op_sel`, untouched destination half, NaN, −0/+0 ordering, and `v_max3_f16` `clamp`) match bit-for-bit. | -| `v_cvt_flr_i32_f32`, `v_cvt_rpi_i32_f32` | RDNA ISA pseudocode: `f32_to_i32(floor(S0))` and `f32_to_i32(floor(S0 + 0.5))`, the `+ 0.5` rounded in binary32 like any f32 add (so 0.49999997 gives 1, where an exact round-half-up would give 0). `f32_to_i32` saturates as in the row above: INT_MAX / INT_MIN at or past ±2³¹ and for ±inf, 0 for NaN. `sat_i32(floor(S0))` and exact `sat_i32(floor(S0 + 0.5))` (computed via `f = Floor(x); (x - f >= 0.5) ? f + 1 : f`, with no binary32 rounding of `S0 + 0.5`: `0x3effffff` → `0`, `0x4b000001` → `0x00800001`, `0x4b7fffff` → `0x00ffffff`). Out-of-range values (±2³¹ and beyond, ±inf) and NaNs all saturate by the sign bit of the operand (`+NaN` → `0x7FFFFFFF`, `-NaN` → `0x80000000`, unlike `v_cvt_i32_f32` which returns `0` for NaN); the sign is read from `x` before `Floor` so driver NaN canonicalization cannot flip it. Source neg/abs apply first. Checked on the CPU by `tests/semantic/test_alu_cvt_flr_rpi.py`, **not yet GPU-verified**. **Until 2026-11-22 the translator rounded `S0 + 0.5` in binary32 and returned `0` for NaN.** Hardware-verified natively on RDNA2 (AMD Radeon 680M `gfx1035`: 82/82 wave32 and 82/82 wave64 via `tools/hw_oracle`, plus `gfx1036` confirmation in #1746) and CPU-checked by `tests/semantic/test_alu_cvt_flr_rpi.py`. | -| `v_cvt_pknorm_i16_f32`, `v_cvt_pknorm_u16_f32` | D[15:0] from S0 and D[31:16] from S1: the f32 is clamped to [-1, 1] (i16) or [0, 1] (u16), multiplied by 32767 or 65535 and rounded to nearest even **once, from the exact product** (SHADER-363). Mesa ACO emits these opcodes for NIR `pack_snorm_2x16`/`pack_unorm_2x16`, which `nir_opcodes.py` defines as `fround_even(fclamp(x) * 32767.0 / 65535.0)`. Emitted as `FClamp`, `OpFMul`, `RoundEven` and a convert, not `PackSnorm2x16`, whose rounding GLSL leaves to the driver. The f32 `OpFMul` can land exactly on k + 0.5 when the exact product is just below or above it, and `RoundEven` would then pick the even neighbour; the product's error `Fma(c, s, -p)` is exact, so on such a tie the translator takes floor(p) + 1 when it is positive, floor(p) when negative, and `RoundEven` when it is 0 (an exact tie). Away from a tie the two roundings agree, since k + 0.5 is an f32 there. NaN gives 0, as `v_cvt_i32_f32` does: **measured** on an RDNA2 iGPU (gfx1036, SHADER-339), 74 of 74 NaN halves (quiet and signalling, both signs, payloads, in S0 and S1) gave 0 in wave32 and wave64 under the game's MODE and with IEEE 1, DX10_CLAMP 0 or f32 denormals kept (`tools/pknorm_probe.py --oracle hw`). **The rounding differs:** the hardware rounds the exact product x · 32767 (or 65535) once, while the translator rounds the f32 `OpFMul` product and then `RoundEven`, so it is one off where the f32 product lands exactly on k + 0.5 (28 of 28 such near-tie inputs, both directions; `docs/shader_validation.md`, "`v_cvt_pknorm_*` NaN and rounding on RDNA2"). On gfx1035 (SHADER-137, `tools/int_hw_probe.py --oracle both`, wave32 and wave64) ±qNaN → 0, ±inf saturation and the round-to-nearest-even ties at ±0.5 match bit for bit. Not fixed here. NaN gives 0, as `v_cvt_i32_f32` does; that is **not measured on hardware**. Source modifiers apply. VOP3 `clamp` is a hardware no-op on RDNA2 and is accepted without changing the result; other modifiers (`mul:*`/`div:*`, `op_sel:*`) raise `Unsupported`. `clamp` raises `Unsupported`. Until 2026-11-22 both ops were rejected. CPU-checked by `tests/semantic/test_alu_cvt_pknorm_f32.py` (ties at the scale steps, ±inf, ±NaN, subnormals, out-of-range values, 40 seeded pairs, abs/neg). **Measured on RDNA2:** on an iGPU (gfx1036, SHADER-339/363, `tools/pknorm_probe.py --oracle hw`) 74 of 74 NaN halves (quiet and signalling, both signs, payloads, in S0 and S1) gave 0 and 28 of 28 near-tie inputs (both directions) gave the single-rounded word, in wave32 and wave64 under the game's MODE and with IEEE 1, DX10_CLAMP 0 or f32 denormals kept; the translator matches all 134 probe words in all ten runs (it was one off on the 28 near ties before SHADER-363; additionally, `tools/cvt_norm_mods_probe.py --hw-arch gfx1036` verified `plain` vs VOP3 `clamp` across 40 edge/near-tie/NaN/±inf/subnormal pairs + 3 source-modifier cases across 6 `HW_REG_MODE` configurations and wave32/wave64 on `gfx1036` driver `32.0.21045.29003`: 2,064/2,064 words exact with 0 clamp diffs and 0 wave diffs). CPU-checked by `tests/semantic/test_alu_cvt_pknorm_f32.py` (the twelve measured near-tie words, ties at the scale steps, ±inf, ±NaN, subnormals, out-of-range values, 40 seeded pairs, abs/neg, `clamp`), `tests/semantic/test_cvt_norm_mods.py`, and `tests/test_pknorm_probe.py`. **GPU-verified through Vulkan** (wave32 synthetic compute shader via `vk_compute_test` with `VK_LAYER_KHRONOS_validation` `1.4.363`, 8 `v_cvt_pknorm_*` plain & `clamp` output words): bit-exact on `AMD Radeon RX 9070 XT` (driver `26.11.2 (LLPC)`, `driverVersion 2.0.416`, Vulkan `1.4.359`) and `AMD Radeon(TM) Graphics` (`gfx1036`, driver `26.11.2`, `driverVersion 2.0.353`, Vulkan `1.4.315`), 0 validation errors. **Not checked through Vulkan on a GPU.** **Hardware-verified on RDNA2** (`gfx1035`, wave32 and wave64 via `tools/int_hw_probe.py --oracle both`, SHADER-137): ±qNaN → 0, ±inf saturation, and round-to-nearest-even ties at ±0.5 match bit-for-bit (the near-tie rounding above is a separate case). **Not GPU-verified.** | -| f16 rounding (SHADER-55, SHADER-56) | **Narrowing to f16 uses integer ops, not `PackHalf2x16`.** Every f16 ALU result (`v_*_f16` VOP1/VOP2/VOP3, `v_pk_*_f16`, `v_cvt_f16_f32`, `v_interp_p2_f16`, `v_fma_mix*`) and `v_cvt_pkrtz_f16_f32` go through `Gen.f16_bits` (round to nearest even, or round toward zero for pkrtz; f16 denormals kept, f32 denormal inputs give ±0, NaN stays a quiet NaN). After a MODE.FP_ROUND toward-zero write the ALU results take the toward-zero form instead (`Gen.f16_res`; see Known approximations). GLSL.std.450 leaves `PackHalf2x16`'s rounding to the implementation, and drivers fold a `PackHalf2x16` → `UnpackHalf2x16` round trip to a no-op, so the next f16 op saw the unrounded f32: #513 (RTX 6000 Ada, `--wave64-emulate`, `v_pk_add_f16` → `v_pk_mul_f16` 1 ulp off), and pkrtz giving round-to-nearest on llvmpipe. **f16 FMAs round once** (`v_fma_f16`, `v_fmac_f16`, `v_pk_fma_f16`): x·y is exact in f32, TwoSum gives the exact error of the f32 sum, and round-to-odd at f32 then rounds correctly to f16. An RX 6700 matched a correctly rounded f16 FMA in 12,612 of 12,612 cases (#374); `Fma` then narrowing double-rounded. Checked by `tests/semantic/test_f16_int_convert.py` (edges + seeded sweep against Python's binary16), `tests/semantic/test_f16_fma_rounding.py` (exact rational reference; built near-tie cases fail on the old translation) and `tools/valu_fuzz.py --family f16` on an RTX 6000 Ada. Image/buffer d16 packing (#489) and the 16-bit interpolant quantize (#512) are separate. **Widening an f16 ALU operand doesn't trust `UnpackHalf2x16` with denormals** (`Gen.f16_in`): on an RTX 5060 Ti (610.88) it gives 0 for a denormal that an SDWA `BYTE_1` select produced, from an inline constant or a VGPR alike, while the same denormal as a literal or already in a VGPR widens right (a local probe of all four, before and after). It depends on the driver: `ps_sdwa_f16_const` failed this way on `main` with NVIDIA 610.88 (RTX 5060 Ti, RTX 3060 Ti, Windows), 595.99 (RTX 5090, Linux) and 580.173 (RTX 3060 Ti, Linux), and passed with 621.01 (RTX 5080) and 621.24 (RTX 5070, RTX 3080 Laptop) (#3220). So a half whose exponent field is 0 is widened as sign × mantissa × 2^-24 with integer ops. Confirmed by the GPU test `ps_sdwa_f16_const` (word y, the denormal `0x0040` × 1024.0 = `0x1c00`), which gave `0x0000` on an RTX 5060 Ti (610.88) natively and under `--wave64-emulate` before and 4096/4096 exact after, and by `tests/semantic/test_value_semantics.py` running it with a flushing `UnpackHalf2x16`. The other `UnpackHalf2x16` uses (packed-f16 reads, interpolants, d16 image results) are not changed. `v_fma_mix*` with f32 sources rounds once straight to f16 via round-to-odd in both nearest and toward-zero modes (measured on an RDNA2 iGPU, gfx1036: `tools/fma_mix_probe.py --oracle hw` gave the single-rounded word for all 7 of 7 tie inputs where the two rules differ, SHADER-135; see Known approximations). `v_fma_mix*` rounds once straight to f16 via round-to-odd in both nearest-even and toward-zero modes, matching hardware (7 of 7 tie inputs of `tools/fma_mix_probe.py --oracle hw` on gfx1036, SHADER-135; see Known approximations). `v_fma_mix*` rounds once straight to f16 via round-to-odd in both nearest and toward-zero modes (see Known approximations); the hardware rounds once: 7 of 7 tie inputs of `tools/fma_mix_probe.py --oracle hw` on gfx1036 (SHADER-135). `v_fma_mix*` with f32 sources uses `Fma` then narrows (two roundings, unmeasured) in nearest-even mode; toward zero it rounds once (see Known approximations). 7 of 7 tie inputs of `tools/fma_mix_probe.py --oracle hw` on gfx1036 (SHADER-135; not fixed yet); toward zero it rounds once (see Known approximations). | -| `v_cvt_pknorm_i16_f16`, `v_cvt_pknorm_u16_f16` | VOP3 packed normalized conversion from two f16 sources (`D[15:0]` from `S0.f16`, `D[31:16]` from `S1.f16`): each selected f16 half (`op_sel[0..1]`, with `neg`/`abs` source modifiers and inline f16 constants via `Gen.f16_in`) is clamped to `[-1, 1]` (`i16`) or `[0, 1]` (`u16`), scaled by `32767` or `65535`, and rounded once to nearest even (`+inf → 32767`/`65535`, `-inf → -32767`/`0`, `NaN → 0`, `±0` and f16 denormals `→ 0`). Uses `cl * (scale + 1) - RoundEven(cl)` for `\|cl\| >= 0.25` to avoid binary32 double-rounding at near-tie f16 inputs (e.g. `0x3801` = `0.5 + 2^-11`). **Measured natively on RDNA2** (`AMD Radeon(TM) Graphics`, `gfx1036`, wave32 & wave64 via `tools/cvt_pknorm_f16_probe.py`): across all 65,536 binary16 inputs in `plain`, `clamp`, `op_sel:[0,0,1]`, and `op_sel:[0,0,1] clamp` (1,048,576 half evaluations) plus 33 targeted edge cases (264 words), VOP3 `clamp` is a **hardware no-op**, destination `op_sel[2] = 1` (`op_sel:[s0,s1,1]`) shifts the 32-bit packed result left by 16 bits (`D[31:16] = norm16(S0.f16)`, `D[15:0] = 0x0000`, overwriting prior `vdst` and dropping `S1`), and raw reserved VOP3 `omod` bits `[60:59]` (`1..3`) are ignored by silicon (rejected by `llvm-mc` on `gfx1036`). The translator accepts `clamp` (no-op) and `op_sel[2] = 1` (`OpShiftLeftLogical` by 16), while `mul:*`/`div:*`, VOP3P modifiers (`op_sel_hi:*`, `neg_lo:*`, `neg_hi:*`), `_dpp`/`_sdwa`, duplicate `op_sel:`, and malformed `op_sel` lists raise `Unsupported`. Output modifiers (`clamp`, `mul:*`, `div:*`), `op_sel` destination bit, and VOP3P modifiers raise `Unsupported`. Source: AMD [RDNA 2 ISA reference](https://www.amd.com/content/dam/amd/en/documents/radeon-tech-docs/instruction-set-architectures/rdna2-shader-instruction-set-architecture.pdf) (VOP3 `v_cvt_pknorm_i16_f16` / `v_cvt_pknorm_u16_f16`) and LLVM AMDGPU `VOP3Instructions.td`. Checked bit-for-bit against an exact rational `fractions.Fraction` reference on the CPU (`spirv_mini_interp`) and with `spirv-val` by `tests/semantic/test_alu_cvt_pknorm_f16.py` and `tests/semantic/test_cvt_pknorm_f16_mods.py`, by unit tests `tests/test_cvt_pknorm_f16_probe.py`, and through Vulkan (`vk_compute_test` with `VK_LAYER_KHRONOS_validation`, 116/116 exact words, 0 clamp diffs, 0 validation errors) on `AMD Radeon RX 9070 XT` (driver `26.11.2 (LLPC)`) and `AMD Radeon(TM) Graphics` (`gfx1036`, driver `26.11.2`); not run on the shader corpus. Checked bit-for-bit against an exact rational `fractions.Fraction` reference on the CPU (`spirv_mini_interp`) and with `spirv-val` by `tests/semantic/test_alu_cvt_pknorm_f16.py`; **Hardware-verified on RDNA2** (AMD Radeon gfx1036, wave32 and wave64, `tools/int_hw_probe.py --oracle both --group valu_cvt_norm_f16`): 33 programs of four conversions each over +-0, +-1, 1 +- 1ulp, +-0.5 and the f16 neighbours of the 0.5 and 0.25 ties, an f16 denormal, +-65504, +-inf and quiet and signalling NaNs, with `op_sel:[1,0]`/`[0,1]` and `neg`/`abs`, all bit-identical to the translator. Not run on the shader corpus. **not GPU-verified** and not run on the shader corpus. . **Hardware-measured natively on `gfx1100`** (RX 7900 XTX, driver 26.10.1) with `tools/hw_oracle`, 38 cases against the same exact-rational model, all matching: the halves pack in the documented order (`0.3333 \| 0.5+2^-11` and `1.5 \| -0.5` are asymmetric), each result is one round-to-nearest-even of the exact `cl * 32767` or `cl * 65535` (`0x3801` gives `32799` for `u16`), out-of-range values and infinities saturate the same way (`+inf` gives `32767`/`65535`, `-inf` gives `-32767`/`0`, so an infinity clamps to `±1`), and `NaN` (quiet or signalling), `-0` and a denormal f16 input all give `0`. Not measured: the `op_sel` destination bit and the `neg`/`abs` source modifiers, and not run on the shader corpus. | -| `s_round_mode` | SIMM16[3:0] sets FP_ROUND. The translator accepts FP32 nearest-even with FP16/64 nearest-even or toward-zero and writes the same per-invocation state as `s_setreg_imm32_b32`. Other rounding modes raise Unsupported. AMD RDNA2 ISA tables 15 and 24; synthetic positive and negative halfway-neighbour conversions check both modes in one shader (`test_round_mode_switches_half_precision_color_rounding` in `tests/semantic/test_scalar_noop_waitcnt.py`). | -| f16 narrowing size | `Gen.f16_bits` leaves out or shares steps where that can't change the result. In nearest-even mode there is no separate infinity select: infinity is already at or above the overflow threshold (65520), which gives 0x7C00. For `v_add_f16`, `v_sub_f16`, `v_subrev_f16` and `v_pk_add_f16` without omod (`exact_tiny`), the range below 2^-14 is neither rounded nor tested for underflow: a sum of two f16 values is a multiple of 2^-24, so there it is already an f16 value, and clamp keeps that true. With an omod the rounding stays, since `div:2` can create a tie. No range has an underflow test: below 2^-25 the shift is 25, which moves the mantissa (plus the rounding bias) out to 0. The subnormal range rounds like the normal one, by adding half - 1 + the kept low bit before the shift. When the program writes MODE, `Gen.f16_res` makes one pass: toward zero selects a bias of 0, the 65536 overflow threshold and 0x7BFF, and keeps the infinity select. Confirmed by running the emitted integer sequences before and after on all 2^32 f32 inputs (both roundings) and on all 2^32 f16 operand pairs (both roundings, with and without clamp): no difference. Regression test: `tests/semantic/test_f16_sum_narrowing.py`. | -| `v_interp_p2_f16` clamp | The VOP3 `clamp` bit on `v_interp_p2_f16` clamps its f16 result to [0, 1], applied before the narrowing like the other f16 results (Mesa ACO `aco_opcodes.py` declares the op `dst(F16)`, which takes output modifiers; llvm-mc encodes `clamp` on it but no omod). Until 2026-11-22 the translator dropped it. Checked by `tests/semantic/test_interp_f16.py`: attributes 1.5 and -0.25 read with clamp give 1.0 and +0.0, and without it 1.5 and -0.25. No GPU test: `vs_ids` gives attributes in [0, 1) only. | -| 16-bit interpolation (`v_interp_p1ll_f16` / `v_interp_p2_f16`, `high`) | A 16-bit varying shares its 32-bit param channel with another: the producer packs them as low half, high half (Mesa `ac_nir_prerast_utils.c`: `nir_pack_32_2x16_split` by `io_sem.high_16bits`), the PS sets `FP16_INTERP_MODE` (plus `ATTR1_VALID` when the high half is used, RADV `radv_ps_input_type_bits`), and the `high` bit picks the half on both ops of the pair (ACO `emit_interp_instr`, `aco_isel_helpers.cpp`; llvm-mc gfx1013 sets the same bit, byte 5 bit 0, on both: p1ll `v2, v0, attr0.x high` 0x00 → 0x01, p2 `v2, v1, attr0.x, v3 high` 0x02 → 0x03). The translated VS exports the channel's raw bits, so interpolating them as one f32 gives neither half. A location any `*_f16` interp reads is therefore declared `PerVertexKHR` (`vec4[3]`, no `Flat`; it still matches a producer's vec4 output at that location); this needs `VK_KHR_fragment_shader_barycentric` (`fragmentShaderBarycentric`) for every such PS, not just the raw-barycentric ones; the index records it like any capability (`features: ["fragmentShaderBarycentric"]`), so `vk_pipeline_check` and `vk_harness` skip such a PS on a device without it. Nothing picks `--bary-fallback` from the device: it is a translation-time flag. Each f16 read decodes its half of each vertex's word (`UnpackHalf2x16` component 0 or 1) and weights them as AMD does, P0 + i(P1 − P0) + j(P2 − P0) with i, j = `BaryCoordKHR`.y/.z, then p2 clamps and narrows as before. f32 reads of such a location (`p1/p2_f32`) interpolate the raw word the same way, and `v_interp_mov_f32` takes vertex 0's. Until 2026-11-22 `high` was ignored and both halves read the smooth-f32 interpolation of the whole word; abilliontokens counted `high` in 4,776 of 12,101 PS (39.5%, 51,684 instructions, always p1ll/p2 pairs, no `p1lv`), and Pipodi found 4,731 of those 4,776 read both halves of the same channel, with p1ll and p2 always agreeing on attribute, channel and `high`. Like the f32 path, the pair's I/J operands are not read: the weights come from `BaryCoordKHR` (213 PS that compute their own barycentrics into v0/v1 first are a separate gap). Confirmed by `tests/semantic/test_interp_f16_high.py` (per-vertex halves 0.5/1.5/2.5 and −4/8/16 at weights (0.25, 0.25, 0.5) give 1.75 and 9.0; fails on the old translation) and the GPU fixture `ps_interp_f16_high` drawn with `vs_f16_pack` (u and v packed in one channel both ways, f32 control) and, through `scripts/run_gpu_tests.py`, with the mesh producer `ms_f16_pack` (mesh `exp paramN` stores the same raw words, `Gen.ms_export`): both pass on an RTX 5070 and fail on the old translation (off by 0.984). spirv-val and `vk_pipeline_check` (real pipelines against the vec4 VS stubs, RTX 5070) also accept PS mixing high, low, f32 and flat reads of one location and of several. **Measured natively on RDNA2** (AMD Radeon 680M, `gfx1035`, wave32 and wave64 via `tools/vinterp_hw_probe.py --oracle both`, SHADER-430): the VINTRP unit reads `P0`, `P10` and `P20` from LDS at `M0 + 48·attr + {8·c, 8·c + 4, 32 + 4·c}`; `v_interp_p1ll_f16` (and `v_interp_p1lv_f16`, taking `P0.half` from `vsrc2`) widens the selected f16 half (`[15:0]` or `[31:16]` with `high`) to binary32 and writes the fused binary32 `fma(i, f32(P10.half), f32(P0.half))`, while `v_interp_p2_f16` rounds the exact `partial_f32 + j · f32(P20.half)` once to f16 following `MODE.FP_ROUND.16_64` (like `v_fma_mixlo_f16`, whereas the translator narrows the f32 sum) and writes `vdst[15:0]` while hardware keeps `vdst[31:16]`; f16 subnormal halves are preserved with `denorm_mode_16_64 = 3` (`0x0001 + 0.5·0x0200 + 0.5·0x0200 → 0x0201`, flushed to `±0` when `0`), and f16 NaN halves quiet with payload preserved (`0x7e05 → 0x7e05`, `0x7c01 → 0x7e01`). **ALU half measured on AMD hardware** (SHADER-430, `tools/interp_hw_probe.py`, gfx1036, every case matched; `docs/shader_validation.md`): `p1ll_f16` widens the chosen f16 halves exactly and computes fma(h10, I, h0) with one rounding to f32. `p2_f16` computes fma(h20, J, p1ll) and rounds it once, straight to f16: 30 hand-built ties gave that result and never f32-then-f16. It keeps vdst's high 16 bits. The translator used to zero them and now keeps them (`write_lo16`; `test_p2_f16_keeps_the_high_half_of_vdst`). **Still unverified:** what the SPI writes into LDS for a packed channel in a real draw (P10/P20 as f32 differences of the raw words, or per-half f16 differences under `FP16_INTERP_MODE`), which needs a pixel-shader harness; also f16 inf/NaN halves and `p1lv_f16`. **Unverified:** AMD hardware (whether it computes P10/P20 in f16 or rounds the p1ll intermediate differently), f16 denormal and NaN halves. **`--bary-fallback`** has no per-vertex inputs, so it keeps the old smooth-f32 read and cannot honour `high`; `check.py` skips the fixture there. MoltenVK can't compile `PerVertexKHR`: see the next row. | -| 16-bit interpolation without `PerVertexKHR` (`--f16-interp-fallback`) | MoltenVK reports `fragmentShaderBarycentric` but can't create a pipeline with the row above's inputs: its SPIR-V to MSL conversion stops with "PerVertexKHR decoration is not supported in MSL" (MoltenVK 1.4.2 on an Apple A18 Pro and, reported by @DomasUrbonas in #166, an M4 Pro), so `ps_interp_f16_high` failed on every Mac. With the flag no `PerVertexKHR` (and, for these reads, no `BaryCoordKHR`) is used: every VS `exp paramN`, mesh param and `--mesh-compute` vertex (`tools/mesh_compute_vs.py`) also exports the channel's two f16 halves decoded to f32 (`UnpackHalf2x16`), low halves at location 28 − 2N and high halves at 29 − 2N, so nothing goes above location 29: MoltenVK's `maxVertexOutputComponents` is 124 because Metal counts `gl_Position` in its 128 vertex-output scalars, and the Khronos validation layer counts it too, so a VS output at location 30 failed VUID-RuntimeSpirv-Location-06272 on `vs_ids` (SHADER-291); a PS `*_f16` read of attrN.c takes component c of that ordinary smooth input, then p2 clamps and narrows as before. Interpolation is linear, so the device interpolating the decoded halves gives the same P0 + i(P1 − P0) + j(P2 − P0) as the per-vertex path, with the interpolator's rounding instead of explicit f32 arithmetic. f32 and `v_interp_mov_f32` reads of such a location are the raw word as on any location (flat = the provoking vertex's word, exact). A producer leaves out the halves of a param whose locations would land on one of its own params (params 0..P−1 leave room for the halves of params 0..(28 − P) / 2), and when a PS's canonical decoded-half locations collide with an attribute it reads, its halves are packed into free locations instead (dynamic packing, below). The index records `f16_halves` ({param: [low, high location]}) on both sides; a pipeline links when the PS's entries are among its producer's. Chosen like the wave64 mode: `tools/vk_subgroup_info.py` reports `per_vertex_inputs` (false without `fragmentShaderBarycentric` or on driver ID MoltenVK), and `make_game.py` and `run_gpu_tests.py` turn the flag on where it is false (`LEONIDA_F16_INTERP_FALLBACK=1`/`0` overrides the runner; `build.py` takes only the variable, since it may run in WSL). Without the flag the translation is unchanged: all 139 GPU-test modules are byte-identical to main's, with and without `--bary-fallback` and with `--mesh-compute --wave64-emulate`, so NVIDIA and AMD keep the exact per-vertex path. Confirmed on an Apple A18 Pro (macOS 26.6.2, MoltenVK 1.4.2): `ps_interp_f16_high` drawn with `vs_f16_pack` passes natively and with wave64 emulation, every one of its 4,096 pixels bit-exact to f16 of the exact u and v in both halves (it failed before at pipeline creation), and `ms_f16_pack` through `--mesh-compute` (`LEONIDA_MESH_COMPUTE=1`) passes too; `tests/semantic/test_f16_interp_fallback.py` checks the PS reads (1.75 and 9.0 from the decoded halves), the VS exports (one-lane interpreter), the overlap rules and the default being unchanged. **Unverified:** a PS whose producer exports more params than leave room for the halves it reads (it reads that producer's param, not halves: the `f16_halves` entries then don't match); devices with fewer than 31 output locations. CPU check (TEST-398, `FallbackStagePair`): with ordinary VS exports at 28 and 29, the PS reads those values (5 and 7 in the test) in place of attr0's decoded halves (2 and 3). Only the PS lists attr0 in `f16_halves`. With param28 as the last export, location 28 carries its ordinary value and location 29 has no VS output. When the last ordinary export is at 27, both stages list the pair and the PS reads 2 and 3. The move from 30 to 29 (SHADER-291) was checked on an Apple M5 (macOS 27.2.1, MoltenVK 1.4.2, Khronos validation layer 1.4.363): over the 170 GPU-test modules `vk_pipeline_check` reported VUID-RuntimeSpirv-Location-06272 on 6 vertex shaders at location 30 and on none at 29; the same 15 modules list `f16_halves` for the same params, `run_gpu_tests.py` gives the same result per test, and `ps_interp_f16_high` reads back byte-identical pixels. **Dynamic packing and per-pipeline PSO linking (SHADER-378):** when a PS's canonical `28 − 2N`/`29 − 2N` slots collide with its raw attributes (266 corpus PS where f16-read attrs reach `n >= 7` and raw attrs reach 12–14, all with `2·\|F\| <= 29 − max`) or fall below 0, `assign_f16_half_locations` in `tools/rdna2spirv.py` packs all `f16_halves` pairs downward from location 29 into locations disjoint from its raw attributes (keeping the canonical slots byte-identical whenever collision-free, and refusing only genuine `> 30` location budget overflows); `tools/mesh_compute_vs.py` adds `pair_f16_halves` and an optional `f16_halves` override to `vs_spvasm`; and at graphics PSO creation `runtime/src/shader_library.h` loads `f16_halves` while `runtime/src/spirv_f16_halves.h` (called from `runtime/shims/d3d12_vulkan_device.cpp`) fast-paths exact matches, relocates PS/VS `Location` decorations when needed, demotes unneeded VS static half outputs to `Private`, and synthesizes `UnpackHalf2x16` half exports before `OpReturn` for params a high-param producer (`param0..15`) could not emit statically. Checked by `tests/semantic/test_f16_interp_fallback.py`, `tests/semantic/test_interp_p1lv_f16.py`, `tests/test_mesh_compute_vs.py`, `runtime/test/shader_library_test.cpp`, `runtime/test/spirv_f16_halves_test.cpp`, and `runtime/test/d3d12_f16_halves_test.cpp` (real Vulkan 1.3 draw on NVIDIA GeForce RTX 4060 Ti, driver 32.0.16.1088, Windows 11: 16-param VS + colliding PS both synthesized and relocated render exact RGBA `(64, 191, 127, 255)`). **Unverified:** native MoltenVK validation run on macOS and full-corpus recount under `--f16-interp-fallback` (needs game copy); native `MeshEXT` runtime PSO specialization (mesh PSOs are not on `main` yet); devices with fewer than 124 vertex output components. Combined with `--bary-fallback`'s geometry shader (`tools/rdna2spirv.py` allocates `%bary` outside all occupied read and reserved f16-half slots; covered by `tests/semantic/test_bary_fallback.py`, and all `3/3` whole-corpus shaders combining both draw `11/11` targets bit-exact on an RX 6650 XT). | -| `v_fmac_f16`, `v_interp_p2/mov_f32` output modifiers | VOP3 `mul:2`/`mul:4`/`div:2` (applied first) and `clamp` to [0, 1] apply to `v_fmac_f16_e64` (before narrowing to f16, matching `v_fma_f16`, high half preserved) and to `v_interp_p2_f32_e64` / `v_interp_mov_f32_e64` (no-op when no modifier is present). Until 2026-11-22 all three dropped output modifiers. Source: LLVM `llvm/test/MC/AMDGPU/gfx10_asm_vop2.s` (`v_fmac_f16_e64`) and `gfx10_asm_vop3.s` (`v_interp_p2_f32_e64`, `v_interp_mov_f32_e64`). Checked on the CPU by `tests/semantic/test_f16_fma_rounding.py` (`test_fmac_output_modifiers`) and `tests/semantic/test_interp_f32_mods.py`, and on a GPU by `ps_fmac_f16_mods.asm`, `ps_interp_f32_mods.asm` and `ps_interp_mov_mods.asm` (the last two drawn with `vs_interp_consts.asm`, whose params are constant over the triangle; each modifier and the omod-before-clamp order change a word; Tesla V100 (NVIDIA 580.95.05, Linux)). **The hardware ignores the f16 omod in the MODE the translator assumes:** on an RDNA2 iGPU (gfx1036) `mul:2`/`mul:4`/`div:2` change an f16 result (`v_fmac_f16`, `v_add/mul/fma_f16`, `v_cvt_f16_f32`, `v_exp/rcp_f16`) only with IEEE 0 and `denorm_mode_16_64 = 0`, and do nothing with f16 denormals kept; omod comes before clamp, and clamp gives +0 for -0 and, with DX10_CLAMP 1, for a NaN (SHADER-135, docs/shader_validation.md). The translator is not changed yet: which of omod and the kept f16 denormals is wrong for the game is a corpus question. | -| `v_fmac_f16`, `v_interp_p2/mov_f32`, and f16 output modifiers | VOP3 `omod` (`[60:59]`) scales the floating-point result by `2`, `4`, or `0.5` before `clamp` (`[0.0, 1.0]`), gated by RDNA2 silicon on **both** `MODE.ieee == 0` and output denorms for the **destination precision** being flushed (`fp32_denorm` for `f32` destinations; `fp16_fp64_denorm` for `f16`/`f64` destinations). Under Leonida's default shader `MODE` (`IEEE=0`, FP32 denorms flushed, FP16/FP64 denorms kept `denorm16_64=3`), `Gen.clamp_mods(..., allow_omod=True)` applies `omod` then `clamp` on `f32` destinations (including `v_interp_p2_f32_e64`, `v_interp_mov_f32_e64`, and `v_cvt_f32_f16`), whereas `Gen.clamp_f16` (`allow_omod=False`) drops `omod` and keeps `clamp` on all `f16`-destination instructions (`v_add/sub/subrev/mul/min/max_f16`, `v_fma/fmac/min3/max3/med3_f16`, unary/transcendental/exponent `*_f16`, `v_cvt_f16_*`, `v_interp_p2_f16`, `v_fma_mixlo/hi_f16`). Hardware-verified on native RDNA2 (`gfx1036`, Windows 11, driver `32.0.21045.29003`, AMD clang `23.0.0git`, wave32 & wave64 parity, ELF binary disassembly confirming non-zero VOP3 `[60:59]` bits emitted, in-wave `v_add_f32_e64 mul:2` witness proving `IEEE=0` active -> `6.0` vs `IEEE=1` -> `3.0`): across all 4 `f16`-destination classes (binary ALU, 3-op ALU, unary/transcendental, and `v_cvt_f16_{f32,u16,i16}`), `mul:2`/`mul:4`/`div:2` are completely ignored under `IEEE=0, denorm16_64=3` while `clamp` still saturates `[0.0, 1.0]`, whereas the `f32`-destination control `v_cvt_f32_f16` scales (`2.0 -> 4.0 / 8.0 / 1.0`); flipping `MODE` to `IEEE=0, denorm16_64=0` (flushed FP16 denorms) re-enables `f16` `omod` scaling (`v_fma_f16 mul:2 -> 6.0`, `v_rcp_f16 mul:2 -> 1.0`, `v_cvt_f16_f32 mul:2 -> 4.0`), confirming the exact hardware gating condition. CPU-checked by `tests/semantic/test_f16_omod_rdna2.py`. **The gate is RDNA2 behaviour, not a general RDNA rule.** `tools/f64_omod_probe.py` (added by this PR) measures the same gate by destination precision on a gfx1036 iGPU (driver `31.0.24002.92`, raw ISA, 175 cases, `mismatches=0`, `wave_diffs=0`): `v_cvt_f64_i32`, `v_cvt_f64_u32`, `v_frexp_mant_f64`, `v_div_fixup_f64` and `v_div_fixup_f16` are f16/binary64 destinations and ignore `mul:2`/`mul:4`/`div:2` under `denorm16_64=3`, while `v_cvt_f32_f64` has binary64 sources and an f32 destination and scales under `denorm16_64=3` whenever `denorm32=0`. And @bunbeans2-arch reported in #4371 that RDNA4 `gfx1201` (RX 9070 XT, Windows driver 26.10.1, where IEEE is fixed on) applies the scaling for all 8 binary64 ops with `denorm16_64=3` kept, `v_add_f64 1.5+1.5 mul:2 = 0x4018000000000000`; that run is quoted from the thread and is not reproduced here. The two readings together are why the translator follows the console's RDNA2 MODEs rather than a hardware-agnostic rule, and why no row here should be read as describing RDNA3 or RDNA4. | -| `v_cvt_f16_f32` output modifiers | VOP3 `clamp` and `mul:2`/`mul:4`/`div:2` apply to the f16 result (Mesa ACO declares the op `dst(F16)`), in the order an RX 6800 (`gfx1030`) and Radeon Graphics (`gfx1036`) apply them: the value is rounded to f16 first, then scaled, then clamped, so in RNE `65520 div:2` is inf, not 32768. The scaling works on the f16 bits (`Gen.f16_omod`): a zero or denormal f16, before or after it, gives +0, inf and NaN pass through, and a finite overflow gives inf (±65504 under MODE toward zero, unmeasured). The scaling works on the f16 bits (`Gen.f16_omod`): a pre-omod zero or denormal f16 (`e == 0`) gives `+0`, `div:2` underflowing an exponent-1 normal (`e == 1`) gives signed zero (`h & 0x8000`, so negative inputs give `-0.0`, which a trailing `clamp` still turns into `+0`), `inf` and `NaN` pass through, and finite `mul:2`/`mul:4` overflow gives `±inf` in RNE or `±65504` under `MODE` toward zero (`FP_ROUND = 3`), where `±65520` / `±FLT_MAX` with `div:2` also round to `±65504` before halving to `±32752`. Until 2026-11-22 both modifiers were dropped; `Gen.f16_omod` also flushed `e == 1 div:2` to `+0` until the `gfx1036` measurement. Sources: [@shelbykb2's RX 6800 words](https://github.com/ItsNotRexed/Leonida/pull/718#issuecomment-7074230544) (gfx1030, not the console's gfx1013): [@shelbykb2's RX 6800 words](https://github.com/ItsNotRexed/Leonida/pull/718#issuecomment-7074230544) (gfx1030, not the console's gfx1013) and `tools/cvt_f16_omod_probe.py` on `gfx1036` (Radeon(TM) Graphics, Windows 11 driver `32.0.21045.29003`, wave32 & wave64, 2,880 evaluations, 0 diffs across static/dynamic `MODE`): `clamp` applies in every float mode, the omod only with IEEE off and f16 denormals flushed (with `denorm16_64=3` or `ieee=1` omod is ignored while `clamp` still applies), which is the mode a compiler emits an omod for, as the f32 rows above argue; 2^-15 `mul:2` and -0 `mul:2` gave 0x0000 there. That flush is modelled only on results that carry an omod. The f16 ALU results (`v_fma_f16`, `v_fmac_f16`, …) still scale before narrowing, which differs from this only on overflow, denormals and the sign of zero. Checked by `ps_outmods_f16.asm` (`tests/semantic/test_value_semantics.py`, and on a GPU in both runners): each of its six results changes a word when its modifier is dropped, and two words change when the omod is applied before the rounding. Checked by `ps_outmods_f16.asm` (`tests/semantic/test_value_semantics.py`, and on a GPU in both runners), `tests/test_cvt_f16_omod_probe.py`, and `tests/semantic/test_cvt_f16_omod.py`. | -| 16-bit vector compare `op_sel` (`v_cmp(x)_*_{f16,u16,i16}`) | VOP3 `op_sel:[s0,s1]` selects bit `[15:0]` (`0`) or `[31:16]` (`1`) of each source before f16 input modifiers (`neg`/`abs`, via `Gen.f16_in`) or `u16`/`i16` zero-/sign-extension (`OpBitFieldUExtract`/`OpBitFieldSExtract` at bit offset 16 when set, 0 otherwise); VOPC writes a scalar lane mask (VCC/SGPR or EXEC for `v_cmpx`), so there is no destination `op_sel` bit. Measured (TEST-650) with `tools/vcmp16_opsel_probe.py --oracle hw`, which writes `v_cmp_{lt,eq,gt}_{f16,u16,i16}_e64` as raw words with OPSEL set by hand in word 0 [12:11]: llvm-mc rejects `op_sel` on these compares and drops the bits when disassembling, so no listing carries it. On an RDNA2 iGPU (gfx1036), with the Windows HIP launcher (AMD 26.10.1) and independently with the Linux DRM launcher (#3329), all 50 rows read the low halves in wave32 and wave64, including the 20 where the selected halves would answer differently (f16 with and without `neg`, u16, sign-extended i16). The same hand-set bits on `v_add_nc_u16_e64` do select the high halves, so the encoding is right. The translator still honours `op_sel` here (from the ISA text and Mesa ACO `can_use_opsel`), which only a hand-encoded word can reach: #3487, which made it read the low halves as TEST-650 measured, was reverted because the constant, literal and SGPR-high-half checks below (row 403, measured natively) expect `op_sel` to select; the two measurements disagree and are open. Until 2026-11-22 `Gen.compare` hardcoded the low half and ignored `mods`. Source: AMD RDNA2 ISA VOP3 `op_sel` and Mesa ACO `can_use_opsel`. **Measured natively on RDNA2** (gfx1036, AMD Ryzen 7000 iGPU, driver 26.11.2) across wave32 and wave64: `v_cmp` writes 0 for inactive lanes in `sdst` (`s4` in wave32, `s[4:5]` in wave64); `v_cmpx` kills inactive lanes in EXEC; inline float constants (`1.0`, `-2.0`, `0.5`, `4.0`) read f16 in low half with `op_sel=0` and +0.0 with `op_sel=1`; inline integer constants (`1`, `-1`) read low half with `op_sel=0` and high half with `op_sel=1` (`0` for `1`, `0xFFFF` for `-1`); 32-bit literals read `[15:0]` (`op_sel=0`) and `[31:16]` (`op_sel=1`, including signed negative high halves in `i16`); SGPR high halves as src0 and src1 with modifiers (`neg`, `abs`); and f16 ordered vs unordered relations on `qNaN`/`sNaN`. Probed natively with zero divergences by `tools/probe_gfx1036_vcmp16.py`, and checked on the CPU by `tests/semantic/test_vcmp16_opsel.py` (all four `op_sel` combinations, spirv-val compliance, wave32/wave64 EXEC updates and inactive-lane 0 writes in `sdst`). Checked on the CPU by `tests/semantic/test_vcmp16_opsel.py` (all four `op_sel` combinations across `f16` relations/ordered/unordered/NaN/`neg`/`abs`, `u16`, signed `i16`, and `v_cmpx` wave32/wave64 EXEC updates via `spirv_mini_interp` and `spirv_wave_interp`); Not measured: `v_cmpx`, `abs`, RDNA1. **not GPU-verified**. | -| `v_cmp_class_f16`, `v_cmpx_class_f16`, `v_cmp_class_f64`, `v_cmpx_class_f64` | IEEE-754 floating-point class tests against the 10-bit class mask (`0: sNaN, 1: qNaN, 2: -inf, 3: -normal, 4: -denormal, 5: -0, 6: +0, 7: +denormal, 8: +normal, 9: +inf`), writing VCC/SGPR or narrowing EXEC (`v_cmpx`). Computed bit-exactly on integer words (so `sNaN` is never quieted by float ops and `v_cmp(x)_class_f64` does not require `OpCapability Float64`): `f16` reads both the value operand (`op_sel[0]`) and the class mask operand via `src_h` (so float inline constants like `0.5`, `1.0`, `-2.0`, `0.15915494` take their 16-bit binary16 value over a zero high half before SDWA selection, matching `tools/sdwa_diff.py --oracle hw` on RDNA2 `gfx1036`; until 2026-11-23 `cmp_class` read the mask with `src_u`, turning inline float constants into 32-bit binary32 bits and failing `sdwa_diff --ops v_cmp_class_f16` 12/500) and applies `abs`/`neg` on bits `[15:0]`; `f16` reads the selected half (`op_sel[0]`, inline f16 constants via `src_h`) and applies `abs`/`neg` on bits `[15:0]`; `f64` reads the `(lo, hi)` pair (32-bit literals placed in the upper word with `lo = 0` per RDNA2 ISA) and applies `abs`/`neg` on `hi`. Output modifiers (`clamp`, `mul:*`, `div:*`) and unsupported `op_sel` bits raise `Unsupported`. Source: AMD [RDNA 2 ISA reference](https://www.amd.com/content/dam/amd/en/documents/radeon-tech-docs/instruction-set-architectures/rdna2-shader-instruction-set-architecture.pdf) (VOPC `V_CMP_CLASS_F16/F64`, `V_CMPX_CLASS_F16/F64`). Checked bit-for-bit across all 10 classes on the CPU (`spirv_mini_interp`) and with `spirv-val` by `tests/semantic/test_alu_cmp_class_f16_f64.py`, and across 500 SDWA programs (`v_cmp_class_f16`, 0 mismatches) via `tools/sdwa_diff.py`; **not GPU-verified** and not run on the shader corpus. . **Hardware-measured natively on `gfx1100`** (RX 7900 XTX, driver 26.10.1) with `tools/hw_oracle`, 85 cases, all matching the operand's own bits: the ten classes on ten `f16` words (`0x7c01` sNaN, `0x7e00` qNaN, `0xfc00` -inf, `0xbc00` -normal, `0x8001` -denormal, `0x8000` -0, `0x0000` +0, `0x0001` +denormal, `0x3c00` +normal, `0x7c00` +inf) and on ten `f64` pairs, each against its own class bit, all ten bits, no bits and the nine other bits (80), plus both `v_cmpx` forms on the launched lane (5). Not measured: `abs`/`neg`/`op_sel`, an inactive lane's `vdst`/`EXEC` under `v_cmpx`, wave64, and the shader corpus. | -| Float-to-byte pack | `v_cvt_pk_u8_f32` rounds to nearest even (the default MODE round mode; the hardware follows the MODE register's f32 round mode, which the translator ignores, see #358), clamps to [0, 255], and gives 0 for NaN and negative values, then inserts the byte at `src1[1:0]` of `src2` and keeps the other three. NaN is replaced by +0 before `FClamp`, which is undefined for a NaN operand. **Measured natively** on RDNA2 (gfx1036, the Ryzen 7 9800X3D iGPU, AMD driver 25.10, the instruction run through inline assembly): all 256 inputs k + 0.5 round to even, 0.5 gives 0, 0x3f000001 gives 1, +inf and 300.0 give 255, -inf, -1.0, ±0, denormals and quiet, signalling and negative NaNs give 0 (#358). `cs_cvt_pk_u8.asm` holds eight of these words, checked by `check.py`/`run_gpu_tests.py` and bit-for-bit by `tests/semantic/test_cvt_pk_u8.py`. | -| Known approximations | `v_cvt_pkrtz_f16_f32` is now **exact round-toward-zero** (finite overflow gives ±65504, not inf). The GPU smoke test caught the old round-to-nearest version producing inf in `PS_ImposterShadow`. The other f16 packs (`v_cvt_f16_f32`, d16 results, mix ops) round to nearest, which matches the default mode; the ALU ones follow a MODE toward-zero write (see the f16 rounding row). `v_fma_mixlo/mixhi_f16` round the exact `x*y+z` once in every mode (measured on an RDNA2 iGPU, gfx1036, 7 of 7 discriminating tie inputs, SHADER-135); the translator does that in both modes through `Gen.fma_mix_odd`; the ALU ones follow a MODE toward-zero write (below; `v_fma_mixlo/mixhi_f16` round the exact `x*y+z` once in every mode (measured on an RDNA2 iGPU, gfx1036, 7 of 7 discriminating tie inputs, SHADER-135); toward zero the translator does that already, while in nearest-even mode it still narrows an f32 `Fma`, which is 1 f16 ulp off on ties until #1774 (SHADER-296) lands; the ALU ones follow a MODE toward-zero write (below; ALU sites: see the f16 rounding row). MODE: `s_setreg_imm32_b32 hwreg(HW_REG_MODE, 2, 2)` (f16/f64 rounding) is tracked in a per-invocation variable, the only MODE field the corpus writes (9,417 writes in 6,333 shaders: 6,694 toward zero, 2,723 back to nearest even). While it is toward zero, every VALU f16 result except the transcendentals listed below (`v_cvt_f16_f32`, f16 arithmetic, `v_pk_*_f16`, `v_fma_mix{lo,hi}_f16`, `v_interp_p2_f16`) rounds toward zero exactly, with the integer conversion `v_cvt_pkrtz_f16_f32` uses (`f16_bits(rtz=True)`, see the f16 rounding row), and `v_add_f64` steps back one ulp when the TwoSum error shows it rounded away from zero; finite overflow gives the largest finite value. The `v_add_f64` output modifiers apply after that step and round to nearest, so an omod that overflows or lands on a subnormal is not toward zero. **omod versus denormal mode is unmodelled:** the translator applies `mul:2`/`mul:4`/`div:2` regardless of the MODE denormal fields (as before this change), whereas hardware ignores omod when denormals are kept (denorm fields = 3) and applies it when they are flushed (both measured on an RX 6800: `v_add_f64 (1 - 2^-60) mul:2` with denormals kept gave 3ff00000:00000000 nearest and 3fefffff:ffffffff toward zero, unscaled; mul:2 was applied with denormals flushed); the tests therefore claim no omod order. CPU-checked by `tests/test_mode_round.py` (the RX 6800 words for f16 add/sub, `v_fma_mix`, the transcendentals, f64 overflow). f16 add and sub (f16 operands) and `v_pk_add_f16` take the exact TwoSum error of the f32 result into account, so they are exact toward zero too (f32 then f16 rounding alone would be wrong: 2 - 2^-24 is an f32 tie that rounds up to 2.0); f16 FMAs need nothing extra, since their round-to-odd f32 value (SHADER-55) narrows exactly in either mode. `v_fma_mix{lo,hi}_f16` rounds the exact fma once, straight to f16, in both nearest-even and toward-zero modes (measured on AMD RDNA2 gfx1036, finding 7079901079; an RX 6800 gave 0x3fff for 1 * 2 - 2^-30, where rounding to f32 first and then narrowing gives 0x4000): `v_fma_mix{lo,hi}_f16` rounds the exact fma once, straight to f16, in both nearest-even and toward-zero modes (measured on AMD RDNA2 gfx1036 across 7 of 7 discriminating tie inputs with `tools/fma_mix_probe.py --oracle hw`, SHADER-135, finding 7079901079, and on an RX 6800 where toward zero gave 0x3fff for 1 * 2 - 2^-30 vs 0x4000 with double rounding; fixed for nearest mode in SHADER-296 / #1774; see docs/shader_validation.md, "`v_fma_mix*` f16 rounding in nearest mode"): `v_fma_mix{lo,hi}_f16` rounds the exact fma once, straight to f16, toward zero (an RX 6800 gave 0x3fff for 1 * 2 - 2^-30, where rounding to f32 first and then narrowing gives 0x4000): `v_fma_mix{lo,hi}_f16` rounds the exact fma once, straight to f16, in both nearest-even and toward-zero modes (measured on AMD RDNA2 gfx1036 and verified by `tools/fma_mix_probe.py`; finding 7079901079; toward zero an RX 6800 gave 0x3fff for 1 * 2 - 2^-30, where rounding to f32 first and then narrowing gives 0x4000): `Gen.fma_mix_odd` corrects the f32 `Fma` to round-to-odd by the sign of its exact residual (product error by `Fma(x, y, -x*y)`, TwoSum of the sum), which narrows exactly in either direction; the nearest-even path is unchanged (f32 `Fma`, then narrow). `fma_mix_odd` also handles a tiny product ( \| a x*y \| >= < 2^-64: its error underflows or is flushed, so the residual sign is sign(x) xor sign(y), independent of the driver's denormal mode) and an f32 overflow with finite operands (toward zero gives ±FLT_MAX, so f16 ±65504). `v_rcp_f16`, `v_rsq_f16`, `v_sqrt_f16`, `v_sin_f16`, `v_cos_f16`, `v_exp_f16` and `v_log_f16` ignore the rounding mode on hardware, so they always narrow to nearest even; all seven are measured (an RX 6700 XT gave the same words with FP_ROUND round-toward-zero and round-to-nearest on every input of each; see the f16 transcendentals row). `v_rcp_f16`, `v_rsq_f16`, `v_sqrt_f16`, `v_sin_f16`, `v_cos_f16`, `v_exp_f16` and `v_log_f16` ignore the rounding mode on hardware (RX 6800 for the first four, plus an exhaustive 65,536-input RNE vs RTZ sweep of all seven in wave32 and wave64 on native `gfx1036` via `tools/mode_round_probe.py`, SHADER-132: 0/65,536 inputs differ on every op; the same probe also confirmed all 17 f16/f64 RNE vs RTZ cases including `v_cvt_f16_f32`, `v_add/sub/mul/fma_f16`, `v_pk_add/fma_f16`, `v_fma_mix{lo,hi}_f16` and `v_add_f64` overflow saturation in both wave32 and wave64), so they always narrow to nearest even. In nearest mode the hardware rounds once as well: `v_rcp_f16`, `v_rsq_f16`, `v_sqrt_f16`, `v_sin_f16`, `v_cos_f16`, `v_exp_f16` and `v_log_f16` ignore the rounding mode on hardware, so they always narrow to nearest even; all seven are measured (an RX 6700 XT gave the same words with FP_ROUND round-toward-zero and round-to-nearest on every input of each, see the f16 transcendentals row; independently confirmed by an exhaustive 65,536-input RNE vs RTZ sweep of all seven in wave32 and wave64 on native `gfx1036` via `tools/mode_round_probe.py`, SHADER-132: `v_rcp_f16`, `v_rsq_f16`, `v_sqrt_f16` and `v_sin_f16` ignore the rounding mode on hardware (RX 6800: the same words in every mode), so they always narrow to nearest even; `v_cos_f16`, `v_exp_f16` and `v_log_f16` are unmeasured, assumed like those four and treated the same. The "every VALU f16 result rounds toward zero" sentence above therefore excludes these seven; the f16 results of `v_floor/ceil/trunc/rndne/fract_f16` are exact and need no rounding. `tools/fma_mix_probe.py --oracle hw` on an RDNA2 iGPU (gfx1036, SHADER-135) gave the single-rounded word for all seven inputs where the two rules differ by one f16 ulp, as `Gen.fma_mix_odd` produces (docs/shader_validation.md, "`v_fma_mix*` f16 rounding in nearest mode"). In nearest mode the translator still rounds `v_fma_mix{lo,hi}_f16` twice (f32 `Fma`, then narrow), but the hardware rounds once there as well: `tools/fma_mix_probe.py --oracle hw` on an RDNA2 iGPU (gfx1036, SHADER-135) gave the single-rounded word for all seven inputs where the two rules differ by one f16 ulp, so the translator, which rounded twice there (f32 `Fma`, then narrow) until #1774, was one f16 ulp off on exactly those ties (docs/shader_validation.md, "`v_fma_mix*` f16 rounding in nearest mode"; the fix is `Gen.fma_mix_odd` in nearest mode too, SHADER-296). Nearest-mode `v_fma_mix*` still rounds twice (f32 `Fma`, then narrow): main's behaviour, unmeasured. `tools/fma_mix_probe.py --oracle hw` measures it on an AMD GPU, with seven inputs where the two rules differ by one f16 ulp (docs/shader_validation.md). The `v_add_f64` step needs f64 denormals preserved (not flushed) by the driver for subnormal sums. Shaders that never write MODE emit the same code as without this. Writes to other MODE bits (f32 rounding, denormals), directed rounding (+inf/-inf) and register-valued writes are refused, so nothing changes silently; none occur in the corpus. Denormal behaviour is still Vulkan's default. Format conversions in memory and texture units don't follow MODE. `v_mul_legacy_f32` now keeps the `0 × anything = 0` rule like `v_mad_legacy_f32` (GPU-checked with `runtime/test/shaders/ps_legacy_mul.asm` on AMD Radeon RX 9070 XT). \| b \| `, `FastTwoSum`: `bb = r - a`, `e = b - bb`) and steps back one ulp when the rounding error shows it rounded away from zero; finite overflow gives the largest finite value (unordered `TwoSum` `r - x` can overflow to `±inf` and yield `NaN` error for opposite-sign finite operands with ` \| x \| < \| y \| ` near `±DBL_MAX`, e.g. `0x7fdd9bb47daa1333 + 0xffefffffffffffff` found by `@Jolymmiles`; GPU-checked with `runtime/test/shaders/ps_f64_round.asm` on NVIDIA GeForce RTX 5060 Ti, 4096/4096 pixels exact). The `v_add_f64` output modifiers apply after that step and round to nearest, so an omod that overflows or lands on a subnormal is not toward zero. **omod versus denormal mode is unmodelled:** the translator applies `mul:2`/`mul:4`/`div:2` regardless of the MODE denormal fields (as before this change), whereas hardware ignores omod when denormals are kept (denorm fields = 3) and applies it when they are flushed (both measured on an RX 6800: `v_add_f64 (1 - 2^-60) mul:2` with denormals kept gave 3ff00000:00000000 nearest and 3fefffff:ffffffff toward zero, unscaled; mul:2 was applied with denormals flushed); the tests therefore claim no omod order. CPU-checked by `tests/test_mode_round.py` (the RX 6800 words for f16 add/sub, `v_fma_mix`, the transcendentals, f64 overflow). f16 add and sub (f16 operands) and `v_pk_add_f16` take the exact TwoSum error of the f32 result into account, so they are exact toward zero too (f32 then f16 rounding alone would be wrong: 2 - 2^-24 is an f32 tie that rounds up to 2.0); f16 FMAs need nothing extra, since their round-to-odd f32 value (SHADER-55) narrows exactly in either mode. `v_fma_mix{lo,hi}_f16` rounds the exact fma once, straight to f16, in both nearest-even and toward-zero modes (measured on AMD RDNA2 gfx1036 across 7 of 7 discriminating tie inputs with `tools/fma_mix_probe.py --oracle hw`, SHADER-135, finding 7079901079, and on an RX 6800 where toward zero gave 0x3fff for 1 * 2 - 2^-30 vs 0x4000 with double rounding; fixed for nearest mode in SHADER-296 / #1774; see docs/shader_validation.md, "`v_fma_mix*` f16 rounding in nearest mode"): `v_fma_mix{lo,hi}_f16` rounds the exact fma once, straight to f16, toward zero (an RX 6800 gave 0x3fff for 1 * 2 - 2^-30, where rounding to f32 first and then narrowing gives 0x4000): `v_fma_mix{lo,hi}_f16` rounds the exact fma once, straight to f16, in both nearest-even and toward-zero modes (measured on AMD RDNA2 gfx1036 and verified by `tools/fma_mix_probe.py`; finding 7079901079; toward zero an RX 6800 gave 0x3fff for 1 * 2 - 2^-30, where rounding to f32 first and then narrowing gives 0x4000): `Gen.fma_mix_odd` corrects the f32 `Fma` to round-to-odd by the sign of its exact residual (product error by `Fma(x, y, -x*y)`, TwoSum of the sum), which narrows exactly in either direction; the nearest-even path is unchanged (f32 `Fma`, then narrow). `fma_mix_odd` also handles a tiny product ( \| x*y \| < 2^-64: its error underflows or is flushed, so the residual sign is sign(x) xor sign(y), independent of the driver's denormal mode) and an f32 overflow with finite operands (toward zero gives ±FLT_MAX, so f16 ±65504). `v_rcp_f16`, `v_rsq_f16`, `v_sqrt_f16`, `v_sin_f16`, `v_cos_f16`, `v_exp_f16` and `v_log_f16` ignore the rounding mode on hardware (RX 6800 for the first four, plus an exhaustive 65,536-input RNE vs RTZ sweep of all seven in wave32 and wave64 on native `gfx1036` via `tools/mode_round_probe.py`, SHADER-132: 0/65,536 inputs differ on every op; the same probe also confirmed all 17 f16/f64 RNE vs RTZ cases including `v_cvt_f16_f32`, `v_add/sub/mul/fma_f16`, `v_pk_add/fma_f16`, `v_fma_mix{lo,hi}_f16` and `v_add_f64` overflow saturation in both wave32 and wave64), so they always narrow to nearest even. In nearest mode the hardware rounds once as well: `v_rcp_f16`, `v_rsq_f16`, `v_sqrt_f16`, `v_sin_f16`, `v_cos_f16`, `v_exp_f16` and `v_log_f16` ignore the rounding mode on hardware, so they always narrow to nearest even; all seven are measured (an RX 6700 XT gave the same words with FP_ROUND round-toward-zero and round-to-nearest on every input of each; see the f16 transcendentals row). `v_rcp_f16`, `v_rsq_f16`, `v_sqrt_f16` and `v_sin_f16` ignore the rounding mode on hardware (RX 6800: the same words in every mode), so they always narrow to nearest even; `v_cos_f16`, `v_exp_f16` and `v_log_f16` are unmeasured, assumed like those four and treated the same. The "every VALU f16 result rounds toward zero" sentence above therefore excludes these seven; the f16 results of `v_floor/ceil/trunc/rndne/fract_f16` are exact and need no rounding. In nearest mode the translator still rounds `v_fma_mix{lo,hi}_f16` twice (f32 `Fma`, then narrow), but the hardware rounds once there as well: `tools/fma_mix_probe.py --oracle hw` on an RDNA2 iGPU (gfx1036, SHADER-135) gave the single-rounded word for all seven inputs where the two rules differ by one f16 ulp, so the translator, which rounded twice there (f32 `Fma`, then narrow) until #1774, was one f16 ulp off on exactly those ties (docs/shader_validation.md, "`v_fma_mix*` f16 rounding in nearest mode"; the fix is `Gen.fma_mix_odd` in nearest mode too, SHADER-296). Nearest-mode `v_fma_mix*` still rounds twice (f32 `Fma`, then narrow): main's behaviour, unmeasured. `tools/fma_mix_probe.py --oracle hw` measures it on an AMD GPU, with seven inputs where the two rules differ by one f16 ulp (docs/shader_validation.md). The `v_add_f64` step needs f64 denormals preserved (not flushed) by the driver for subnormal sums. Shaders that never write MODE emit the same code as without this. Writes to other MODE bits (f32 rounding, denormals), directed rounding (+inf/-inf) and register-valued writes are refused, so nothing changes silently; none occur in the corpus. Denormal behaviour is still Vulkan's default. Format conversions in memory and texture units don't follow MODE. `v_mul_legacy_f32` now keeps the `0 × anything = 0` rule like `v_mad_legacy_f32` (GPU-checked with `runtime/test/shaders/ps_legacy_mul.asm` on AMD Radeon RX 9070 XT). | -| Denormal flush in `v_mad_f32`, `v_mac_f32`, `v_mad_legacy_f32` (SHADER-118) | The three have no f32 denormal support: a subnormal operand, the rounded product or the result reads as signed zero, whatever the MODE register says. `Gen.flush_f32` emits ` \| x \| < FLT_MIN → copysign(0, x)` on the three operands, after the product rounding and (via `Gen.flush_f32_mods`) both before and after `omod`/`clamp`; inf and NaN compare false and pass through, and 0 keeps its sign. Source: LLVM AMDGPU `SIISelLowering.cpp`, `SITargetLowering::isFMADLegal` (llvm-project `1922c0c`), which forms `v_mad_f32`/`v_mac_f32` only when f32 denormals are flushed. Corpus count with `tools/shader_profile.py` over the 26,503 gfx1013 shaders: `v_mad_f32` in 7,298 shaders (139,287 occurrences), `v_mac_f32` in 5,889 (276,806: 265,901 `_e32`, 10,811 `_e64`, 94 `_dpp`), `v_mad_legacy_f32` in 6,059 (24,765); 9,297 shaders (35.1%) use at least one, 440,858 occurrences (0.99% of the corpus's 44,406,870 instructions). **Measured natively on RDNA1** (`AMD Radeon RX 5600 XT`, `gfx1010`, Windows driver `32.0.21045.29003`, `tools/mad_denorm_probe.py --oracle hw`, SHADER-340): 48 of 48 cases match in wave32 and wave64 across `game` (`IEEE=0`, `denorm32=0`), `dx10_clamp=0` and `denorm32=3` (`v_mul_f32(FLT_MIN, 0.5)` confirms `denorm32=3` keeps subnormals on the GPU while the mad/mac ops still flush them), and all 40 non-`omod` cases match under `IEEE=1` (where hardware ignores `mul:2`/`mul:4`/`div:2` as for other f32 VALU ops). Before SHADER-340 the translator ran `flush_f32` only after `clamp_mods`, which gave `FLT_MIN` (`0x00800000`) instead of `+0` (`0x00000000`) on `(1.5*2^-126 - 2^-126) mul:2` (and `0x01000000` on `mul:4`), whereas hardware flushes the sum before `omod` (`+0`) as well as after (`FLT_MIN div:2` → `+0`, `-FLT_MIN div:2` → `-0`). Checked on the CPU by `tests/semantic/test_valu_f32_min3_max3_mad.py` (`DenormalFlushTests`: the flush column, pre- and post-`omod` cases, NaN/inf/zero pass-through, and a sabotaged pass-through that fails) and `tests/test_mad_denorm_probe.py`. No RDNA2 part has these opcodes, and on gfx103x the encodings of `v_mad_legacy_f32` (VOP3 0x140) and `v_mac_legacy_f32` (VOP2 0x06) are the fused `v_fma_legacy_f32` / `v_fmac_legacy_f32`, so a raw-encoding run on a gfx1036 oracle would measure a different instruction (see the GFX10.1/GFX10.3 opcode row). | -| 16-bit high-half reads (`Gen.u16_half` / `Gen.i16_half`, #1506) | Reading the high 16 bits of a 32-bit word emits `OpShiftRightLogical %uint u 16` (`u16_half`) or `OpShiftRightArithmetic %int (as_int(u)) 16` (`i16_half`) alone, without a trailing `OpBitwiseAnd ... 0xFFFF` or `OpBitFieldSExtract ... 0 16` (used for the low half only). On 32-bit inputs `>> 16` already zero- or sign-extends bits 31..16, and AMD's Windows LLPC compiler (measured on RDNA2, drivers 22.40.84.06 in #1506 and 24.10.24 on Ryzen 5 7600 iGPU) miscompiles both `(u >> 16) & 0xFFFF` and `OpBitFieldSExtract (u >> 16) 0 16` after two partial-half writes to `u` by dropping the `>> 16` when the result feeds `OpIAdd`, `OpIMul`, or `OpShiftLeftLogical` (e.g. `(0x41b1 << 1) & 0xFFFF` became `0x0000` instead of `0x8362` in `cs_f16fuzz_s2_163_w64`, `s_bitreplicate`'s `((0x41b1 << 8) \| 0x41b1) & 0x00ff00ff` became `0xb10000` instead of `0x4100b1`, and `SExtract(0x91b1138b >> 16, 0, 16) + 1` became `0x91b10001` instead of `0xffff91b2`). Applies across all 16-bit half readers (`v_*_b16`/`u16`/`i16`, `v_mad_{u,i}16`, `v_min3/max3/med3_{u,i}16`, `v_cvt_f16_{u,i}16`, `v_pack_b32_f16`, `v_frexp_*_f16`, `v_ldexp_f16`, `s_bitreplicate_b64_b32`, and `buffer_store_format_d16_*`). Checked by the unit tests in `tests/test_u16_high_half.py` and `tools/valu_fuzz.py --family f16 --seed 2 --programs 200 --wave both` on AMD Ryzen 5 7600 iGPU (driver 24.10.24: 400/400 native, up from 399/400; 200/200 wave64 emulated on both AMD and NVIDIA). **The packed 16-bit shifts follow the same rule** (`v_pk_lshlrev_b16`, `v_pk_lshrrev_b16`, `v_pk_ashrrev_i16`, since 2026-11-23): the shift amount comes from `OpShiftRightLogical %uint s0 16` then `& 15`, and the value from `OpShiftRight{Logical,Arithmetic} %uint s1 16`, where the code used `OpBitField{S,U}Extract … 16 16`. A field extract at offset 16 is what an AMD Windows driver 25.10.36 on a gfx1036 iGPU reads with the offset taken mod 16, so both result halves got the **low** half of the source: 5 of 2,000 `tools/valu_fuzz.py --family f16 --programs 2000 --seed 1 --wave 32` programs, all in wave32 and none in native wave64 (@Darkz0rz, reported in the coordination issue as SHADER-777). The same 2,000 programs match 2000/2000 on a second gfx1036 (Radeon iGPU of a Ryzen 7 7800X3D, driver 31.0.24002.92), where the field-extract form was already correct, and its SPIR-V does contain the offset-16 extracts, so the change is a lowering that survives both drivers, not a value change: `OpBitField{S,U}Extract(x, 16, 16)` equals `x >> 16` with the matching right shift and `OpBitFieldUExtract(x, 16, 4)` equals `(x >> 16) & 15`, checked for 200,010 inputs including 0, 1, 0xFFFF, 0x10000, 0x80000000, 0xFFFFFFFF, 0x7FFFFFFF and 0x8000. Counted over the 26,503 listings: 1 `v_pk_lshlrev_b16` in 1 compute listing (`op_sel_hi:[0,1]`) and 1 `v_pk_lshrrev_b16` in 1 other (`op_sel:[1,0] op_sel_hi:[0,0]`), no `v_pk_ashrrev_i16` and no `_sdwa` form; those two modules are the only ones whose output changes. Values are checked by the unit tests in `tests/test_pk16_diff.py` and the `ps_ops4` / `ps_ops6` fixtures. | -| `v_mac_legacy_f32` | The GFX10.1 VOP2 form of `v_mad_legacy_f32` with D as the addend: D = legacy(S0 * S1) + D, where 0 times anything (inf and NaN included) is +0, with the same denormal flush and VOP3 modifiers. D is read before it is written, as for `v_mac_f32` (LLVM `VOP2Instructions.td`: `V_MAC_LEGACY_F32` has `$src2` tied to `$vdst`). Until 2026-11-22 it raised `Unsupported`. CPU-checked by `MacLegacyF32Tests` in `tests/semantic/test_valu_f32_min3_max3_mad.py` (a 15x8x6 grid against the `v_mad_legacy_f32` reference, the zero rule, clamp/neg, D aliased as a source). **Not GPU-verified**: like the other mad opcodes it exists on gfx1010-1013 only, so no RDNA2 desktop part runs it. | -| `v_cmp_*_f64`, `v_cmpx_*_f64` | All 16 binary64 vector compare predicates (`f`, `lt`, `eq`, `le`, `gt`, `lg`, `ge`, `o`, `u`, `nge`, `nlg`, `ngt`, `nle`, `neq`, `nlt`, `tru`) for both `v_cmp_` (VCC/SGPR lane mask) and `v_cmpx_` (EXEC narrowing), lowered in `Gen.compare_f64_cond` via pure 32-bit `%uint` IEEE-754 ordering (NaN detection, `-0.0` canonicalized to `+0.0`, sign-magnitude to monotonic unsigned 64-bit key) with no `Float64` capability required and no denormal flushing. Supports VGPR/SGPR pairs, `fimm`, sign-extended inline integers (`-16..64`), 32-bit upper-half literals, and VOP3 `abs`/`neg` sign-bit modifiers on both sources; inactive lanes write 0 for `v_cmp_*_f64` and stay inactive for `v_cmpx_*_f64`. Source: AMD RDNA2 ISA VOPC/VOP3 binary64 compares. CPU-checked by `tests/semantic/test_cmp_f64.py` (all 16 predicates across full IEEE-754 edge grid including subnormals/1-ULP pairs/±0/±inf/sNaN/qNaN, SGPR pairs, constants, `abs`/`neg`, `v_cmpx_*_f64`, inactive lanes, no `Float64` capability, bad-operand rejections). **Not GPU-verified.** Measured on native gfx1100 (single thread, 116 cases): all 16 predicates return IEEE-754 results (`eq` on `NaN` is 0 while `neq`/`nlt`/`nge`/`ngt` are 1, `lg` is 0 for `NaN` with `o`/`u` splitting on it, `eq(+0.0, -0.0)` is 1, `inf` compares equal to itself) and `v_cmpx_*_f64` narrows `EXEC` instead of writing `VCC`. | -| Whole-quad mode (`s_wqm_b64` / `s_wqm_b32`) | A lane mask register holds only this lane's bit, so WQM on one (EXEC, VCC, an SGPR the mask analysis found) ORs the bit of the lane's quad, lanes 4n..4n+3 of the wave: two `OpGroupNonUniformQuadSwap` (horizontal, then vertical; capability `GroupNonUniformQuad`) in the default mode in fragment and compute shaders (quad operations are only guaranteed there; vertex, geometry and mesh shaders shuffle from the quad's four lanes), or the four lanes' values read through `%x_buf` under `--wave64-emulate` (no subgroup operation there). A quad never crosses lane 31/32, so the mask bits are exact per half on a 32-wide subgroup; SCC is a wave vote, so on wave64 it needs a 64-wide subgroup or `--wave64-emulate` (as every wave-wide mask op). The result goes to EXEC, VCC or an SGPR pair as a mask, SCC = the wave-wide any of it (same vote as the other mask ops). A 32-bit form in wave64 (`exec_lo`/`exec_hi`, `vcc_lo`/`vcc_hi`, a half-mask SGPR) writes only its own half (`exec_half_write`) and votes SCC over that half only (`cs_wqm_w64_half`). A source that is not a lane mask (a value loaded from memory, a literal) is data: `((x \| x>>1 \| x>>2 \| x>>3) & 0x11111111) * 15` per 32-bit word and SCC = result != 0, no subgroup operation. Assumptions: in compute and mesh shaders the subgroup lane is `LocalInvocationIndex` mod the subgroup size (as for every cross-lane op); a hardware quad is four consecutive lanes of a wave, and in a pixel shader Vulkan's quad (the 2x2 pixels, helper invocations included) is the same four lanes; GPU-checked on both AMD and NVIDIA with `ps_wqm.asm` (every 2x2 block of a 64x64 target, fully covered). **Helper lanes at a triangle edge, measured on RDNA2** (gfx1036, wave64, raw ISA through `tools/ps_oracle.py` on RADV; `tools/ps_helper_probe.py`, docs/shader_validation.md): a pixel wave's entry EXEC is exactly its covered pixels (helpers off); `s_wqm_b64 exec, exec` turns on exactly the quads with a covered pixel, which are packed from lane 0 (a quad with no covered pixel isn't in the wave); lane % 4 = (x & 1) + 2 (y & 1), so lanes 0-3 are top-left, top-right, bottom-left, bottom-right; a helper's `v_interp` gives its own pixel centre (extrapolated, as precisely as a covered pixel), and its v0/v1 hold its own I/J before `s_wqm` too; without `s_wqm` its VGPRs aren't written; an `exp ... vm` with helpers on in EXEC writes no pixel outside the triangle. Not covered: helper-invocation behaviour at triangle edges is untested, and in native mode an absent invocation in a partial quad (a compute group whose size is not a multiple of 4) gives an undefined value (emulated, the missing lanes of a partial wave read as 0). Before this the instruction was the identity, so helper lanes stayed off (#156 SHADER-34: `s_wqm_b64` appears in 4,285 pixel shaders). GPU-checked with `runtime/test/shaders/cs_wqm_w64.asm`, `cs_wqm_w64_half.asm`, `cs_wqm_w32.asm` and `ps_wqm.asm` on AMD Radeon 880M (subgroup 64) and NVIDIA GeForce RTX 5070 Laptop (subgroup 32; `cs_wqm_w64` there needs `LEONIDA_W64_EMULATE=1`), with and without `--wave64-emulate`. | -| `buffer_atomic_{and,or,xor,swap}_x2` | `M = op(M, DATA)` on the 64-bit element at the MUBUF address (two dwords, low first); with `glc` the old 64 bits are returned in `vdata[0:1]`. A bitwise op or an exchange leaves the same memory done one dword at a time, so each dword is its own 32-bit `OpAtomic*` and no Int64 atomics are needed. **Approximation:** the returned pair comes from two reads, so another lane's 64-bit op on the same element between them can show up half done. Each dword is its own 32-bit `OpAtomic*`, so no Int64 atomics are needed; a bitwise op leaves the same memory that way, since its bits are independent. **Approximation:** an exchange can tear, since two lanes swapping into one element at once can leave one's low dword with the other's high dword (A.lo, B.lo, B.hi, A.hi), and the returned pair comes from two reads, so another lane's 64-bit op on the same element between them can show up half done. **Bounds:** the check covers the whole 8-byte element, all or nothing, as for a typed 32_32 element (`buffer_address(elem="fmt")`). An out-of-range or inactive lane leaves memory alone and returns 0, as `buffer_atomic` does. How hardware treats a 64-bit atomic that is only partly in range is **not measured**. Still `Unsupported`: `add/sub/min/max_x2` and `cmpswap_x2`. Until 2026-11-22 every `_x2` buffer atomic was rejected. CPU-checked by `tests/semantic/test_buffer_atomics_x2.py` (the four ops with and without `glc`, an element ending exactly at `num_records`, half and fully out of range, seeded values, rejected forms). **Not GPU-verified.** | -| Wave64 graphics: partition invariance (SHADER-10) | A wave64 VS/PS/GS on a 32-wide subgroup is exact **iff its observable results do not change when the wave is cut into two 32-lane halves** (the host forms the subgroups of graphics stages, so there is no partner half to exchange with). `tools/wave64_halves.py` decides it from the code (forward taint dataflow over the basic blocks, plus control dependence on wave-wide votes) and the translator records it in `index.json` as `wave64_graphics` (`A`/`B`/`C`), `wave64_graphics_reasons` (tier C) and `wave64_graphics_idioms` (tier B). **A**: only per-lane arithmetic, votes that skip lane-masked work (`s_cbranch_execz/execnz`; `vccz/vccnz` whose run side starts by narrowing EXEC to that VCC and whose other side is the join, with no code of its own: a half that votes no runs that side, the wave does not; the same holds for `s_cbranch_execz/execnz`: the side that runs when EXEC is zero is taken by a half with no active lane, so it must be the join (or only jumps to it) or the exit of a loop the vote closes, else tier C `unsafe-execz-branch`; `s_cbranch_scc*` after a vote is the same kind of skip, any other reader of that SCC, `s_cselect`/`s_cmov`/`s_addc`, is tier C; a vote is on the mask register's value when it was taken, so a new value in that register before the branch (`v_cmp` into the pair or VCC, `s_mov_b64`, `s_cselect_b64`: none of them writes SCC) ends it, and the branch is judged as a plain SCC branch, SHADER-820), whole-quad masks, `ds_bpermute`/`ds_permute`/`v_permlane16`/`v_permlanex16`/`ds_swizzle` (they stay inside a half), a `ds_bpermute`/`ds_permute` address made from the lane id (`v_mbcnt_lo` then `v_mbcnt_hi` of -1) when it is the same modulo 128 bytes in the wave and in a half (the id is 0..63 there and 0..31 here, equal modulo 32 lanes; sums, differences and bitwise ops with invariant values keep that, a left shift by c multiplies the modulus by 2^c, and the permute uses address bits 2..6 of its half only: `(id ^ 1) << 2` is exact, `id << 1`, a right shift of the id or the low count alone stay tier C `lane-id`), loops closed by `execnz` with no scalar state carried, and the early exit of a pixel kill: `s_cbranch_scc0/scc1` (or `vccz/vccnz`) on a lane mask's own "not empty" (the last SCC writer is a 64-bit logic op into that mask, e.g. `s_andn2_b64 live, live, exec`, or `s_cmp_lg_u64 mask, 0`, and nothing rewrites the mask before the branch) to a block that only sets EXEC from that mask or 0 (`s_mov_b64 exec`, or `s_and_b64 exec` with it), may then export with that EXEC (an export is allowed, not required), and ends (no other code, store or successor), while the run side narrows EXEC into the mask's whole quads before anything but mask arithmetic (`s_mov_b64`, `s_and_b64`, `s_wqm_b64`) runs, the narrowing itself possibly an `s_and_saveexec_b64` / `s_andn2_saveexec_b64` (or `_wrexec_`) whose source is inside, and keeps it inside on every path from there, loops included (a must-dataflow: an EXEC write keeps it inside only when it is provably a subset: `v_cmpx`, `s_and_b64` with one operand known inside, `s_andn2_b64` / `s_andn2_saveexec_b64` whose first operand is, `s_and_saveexec_b64` while inside or from one that is, `s_andn1`/`s_or`/`s_xor_saveexec_b64` only while inside (the latter two also from one that is), and copies, `s_wqm_b64`, `s_or_b64` and `s_xor_b64` of operands known to be inside (0 counts as inside); a saveexec destination holds the old EXEC and a wrexec one the new, each inside only if that EXEC was), and no `exp ... vm` can run before the vote. A half whose mask is empty then writes nothing and discards its pixels in the exit, and in the wave its lanes are off to the end, so the wave discards them too; an exit shared by several kills reads a mask redefined behind the earlier votes and stays tier C. GPU-checked by `ps_w64_a_discard` (below). `s_cbranch_scc*` after a vote is the same kind of skip, any other reader of that SCC, `s_cselect`/`s_cmov`/`s_addc`, is tier C; a vote is on the mask register's value when it was taken, so a new value in that register before the branch (`v_cmp` into the pair or VCC, `s_mov_b64`, `s_cselect_b64`: none of them writes SCC) ends it, and the branch is judged as a plain SCC branch, SHADER-820), whole-quad masks, `ds_bpermute`/`v_permlane16` (they stay inside a half, not GPU-tested here: no fixture; `s_cbranch_scc*` after a vote is the same kind of skip, any other reader of that SCC, `s_cselect`/`s_cmov`/`s_addc`, is tier C), whole-quad masks, `ds_bpermute`/`v_permlane16` (they stay inside a half, not GPU-tested here: no fixture; `ds_swizzle` and `v_permlanex16` likewise; GPU-checked at required 64 and 32 lanes by `ps_w64_a_bpermute`, `ps_w64_a_permlane` (`v_permlane16` and `v_permlanex16`) and `ps_w64_a_swizzle` in `w64_graphics.py`, TEST-433), loops closed by `execnz` with no scalar state carried. `ds_swizzle` and `v_permlanex16` likewise), loops closed by `execnz` with no scalar state carried. A `vccz`/`vccnz` on a wave-uniform compare is no lane vote and is tier A too: a `v_cmp` made while EXEC is the launch mask from untainted immediates, scalars that are no lane mask and VGPRs written from them (optionally ANDed with EXEC, the LLVM form `s_and_b64 vcc, exec, s[..]`) gives every launch lane or none, so each half votes as the wave does and both sides may have code and scalars of their own (if/else, a uniform loop back edge; the mask itself read as data, e.g. exported, is still tier C `cross-lane`), while the same compare under a narrowed EXEC (a half with no active lane votes no and keeps its own scalars) or on a tainted value (`v_readfirstlane` of a varying VGPR, a lane count, an AND with a lane mask) stays tier C; confirmed on the wave interpreter (`UniformVote` in `tests/semantic/test_wave64_halves.py`: 64 lanes against two waves of 32, equal for the accepted forms with s4 = 9 and s4 = 1, different for each near miss) and by `ps_w64_a_uniform_vote`, which gives its derived words on an NVIDIA GeForce RTX 5080 (Linux, driver 580.65.06, 32 only). **B**: also a waterfall loop (`v_readfirstlane` of a varying value, `v_cmp_eq` against the same VGPR, `saveexec`, body, `s_xor exec`, `execnz`; the scalar only used inside the body), a wave-aggregated atomic (`s_bcnt1` of EXEC, `v_mbcnt` rank of that same EXEC, one `buffer_atomic_add` of that count (the count of the mask the rank ranks) by the rank-0 lane only, at a wave-uniform address (a uniform VGPR, or one the elected lane wrote from scalars and constants since EXEC last changed; a per-lane address such as a pixel coordinate is tier C `elected-lane`, since each half elects its own lane and bumps another counter), `v_readfirstlane` of the result with EXEC restored, base + rank as a store address, the rank counting the very mask the atomic's count was taken of (a rank of the entry EXEC or of a saved copy next to a base of the narrowed one is tier C `lane-rank`); the rank alone or the base alone is not a slot: exact as a set of slots, **the order of the slots within a wave is not preserved**, a 64-lane wave takes one run of slots, two halves take two), `v_readfirstlane` / `v_readlane` of a VGPR written from scalars and constants while EXEC was the launch mask (the same in every lane), a `v_writelane` / `v_readlane` spill pair on one constant lane below 32. **C**: anything else that reaches an export, a store's data, a branch or EXEC: lane count / rank / first-lane index / raw lane id (`v_mbcnt` of -1), `v_readlane` of a varying value at any lane (on a wave64 every lane gets hardware lane N, in halves each half gets its own lane N, so lane 7 is as wrong as lane 40; the research note's row 9 is too generous here); an analysis failure is tier C with reason `analysis-error` (the translation does not fail), `v_writelane` to a non-constant or >= 32 lane, a 32-bit access to half of a lane mask (`exec_hi`, `vcc_hi`, a mask pair's odd register), a mask read as data (including a mask combined by `s_and/or/andn2_b64` with a register that is not one: a user value, a loaded mask), a scalar defined behind a wave-wide vote and read where it may not have run (`s_add s5, s5, 1` after `s_cbranch_vccz`; a trip count in an SGPR of a divergent loop: the halves vote differently), a branch on a count, an elected-lane side effect that is not a count, `ds_append`/`ds_consume`. The check is conservative: unknown means C. `--wave64-graphics=warn` (default) marks tier C and counts it in the summary line, `error` refuses it (`Unsupported`), `off` skips the analysis; `python tools/wave64_halves.py --census /index.json` prints tier, reason and idiom counts (no names); it complements `tools/wave64_graphics_scan.py` (#1132), which counts candidate cross-half opcodes in the disassembly before translation and decides nothing. **Corpus census** (1.0.2.1, all 26,503 shaders translated at `main` `f847748c` with `--wave64-emulate`, `--census` over that index): 13,405 wave64 graphics shaders (2,236 VS, 10,974 PS, 195 GS, the FSSM header's wave size, see *Wave size*); tier A 4,033 (30.1%), B 85 (0.6%), C 9,287 (69.3%): VS 1,455/79/702, PS 2,383/6/8,585, GS 195/0/0. Tier C reasons (a shader can have several): unsafe-vote-branch 8,285, tainted-branch 6,547, tainted-exec 5,189, cross-lane 4,764, stale-scalar 3,415, mask-half 759, unsafe-execz-branch 583, first-lane 353, waterfall-scalar 161, lane-id 152, lane-count 1. Idiom tags, counted on every shader that carries one whatever its tier (`--census` prints them as "tier B idioms"; 85 shaders are tier B): readfirstlane-uniform 626, lane-spill 287, waterfall 35. (Earlier censuses counted 11,405 shaders, from when the wave size came from code markers: TEST-319 had A 1,919, B 17, C 9,469 with all 195 GS in C; its re-run with the GS ring rule below and #1982 had A 2,117, B 17, C 9,271 with all 195 GS in A.) The lane-id bpermute rule moves no corpus shader. (The TEST-319 census, from when the wave size came from code markers and before the GS ring-address rule below, counted 11,405 shaders: A 1,919, B 17, C 9,469, with all 195 GS in C.) The lane-id bpermute rule moves no corpus shader. **Corpus census** (TEST-319, 1.0.2.1, `--census` over the translated index, re-run with the GS ring rule below and #1982): 11,405 wave64 graphics shaders (1,179 VS, 10,031 PS, 195 GS); tier A 2,117 (18.6%), B 17 (0.1%), C 9,271 (81.3%): VS 479/14/686, PS 1,443/3/8,585, GS 195/0/0. Tier C reasons (a shader can have several): unsafe-vote-branch 8,285, tainted-branch 6,550, tainted-exec 5,189, cross-lane 4,760, stale-scalar 3,415, mask-half 758, unsafe-execz-branch 583, first-lane 353, waterfall-scalar 161, lane-id 152, lane-count 1. 11,405 wave64 graphics shaders (1,179 VS, 10,031 PS, 195 GS); tier A 1,919 (16.8%), B 17 (0.1%), C 9,469 (83.0%): VS 465/14/700, PS 1,454/3/8,574, GS 0/0/195. Tier C reasons (a shader can have several): unsafe-vote-branch 8,175, tainted-branch 6,582, cross-lane 6,111, tainted-exec 4,959, stale-scalar 3,162, mask-half 758, unsafe-execz-branch 583, first-lane 353, lane-id 277, waterfall-scalar 167, lane-count 1. Tier B idioms: readfirstlane-uniform 558, lane-spill 287, waterfall 35. The lane-id bpermute rule moves no corpus shader. **Corpus coverage is not measured here**: it needs a run over the game's shaders by someone who has them. **Rewrite (the only one the emission needs)**: `v_readlane_b32` of a proven-uniform VGPR reads the lane's own copy instead of shuffling from lane N, because a subgroup shuffle from lane >= 32 of a 32-wide subgroup is undefined (143 of 144 test shaders translate byte-identically to origin/main, only `ps_w64_b_readlane_uniform` changed). Everything else tier B needs is what the translator already emits per subgroup: the ballot/count/rank/first-lane words of `wave_mask` are the subgroup's own (the high word is 0), `v_readfirstlane` is the subgroup's first active lane, a waterfall runs once per distinct value of the subgroup. GPU-checked on AMD Radeon 880M (driver 26.11.2; `requiredSubgroupSizeStages` has FRAGMENT, size 32..64) with `runtime/test/shaders/w64_graphics.py`: each `ps_w64_*` fixture drawn with the fragment subgroup size required to 64 (one hardware wave) and to 32 (two halves). `ps_w64_a_skip`, `_b_waterfall`, `_b_readfirstlane`, `_b_readlane_uniform` and `_b_ballot_atomic` (counter 1024 and the 1024 slot words as a set; slot order differs) match each other and the words their headers derive; `_c_bcnt_export`, `_c_lane_id`, `_c_readlane`, `_c_vote_stale`, `_c_vote_else`, `_c_scc_vote`, `_c_execz_sgpr` (an SGPR written on the exec-zero side and exported) and `_c_waterfall_count` differ between 64 and 32 (the detector is right). `ps_w64_a_one_lane` is the case where only one pixel votes yes (so one half votes and the other does not, in the wave and in the halves): its skip regions (`execz`, `vccz`, `vccnz` with a jump-only fall-through) give equal images at 64 and 32; `_c_vote_else` (code on the vote's no side) and `_c_scc_vote` (SCC of a vote as data) differ. `ps_w64_a_discard` (three kills, two of them dropping whole regions so that some halves lose every pixel while the other half of their wave lives) was drawn on an AMD Radeon RX 580 (RADV, Mesa 26.0.8, required size 64, saved with `W64G_SAVE_REF`) and an NVIDIA GeForce RTX 5070 (32 only, driver 620.73.04, compared with `W64G_REF`): both equal the derived words, discarded pixels keeping the clear value, and each other. NVIDIA GeForce RTX 5070 Laptop (32 only, driver 617.42): tier A/B fixtures equal the derived words and the 880M@64 images (`W64G_SAVE_REF` / `W64G_REF`), tier C fixtures differ from the 880M@64 images. `ps_w64_a_permlane`, `_a_swizzle` and `_a_bpermute` (TEST-319: permlane16 neighbour selects, permlanex16 there and back, swizzle quad-permute, swap and broadcast modes, bpermute from lane-id addresses; every read stays in the pixel's 2x2 quad or comes back, so the words do not depend on how pixels are packed into lanes) give the derived words on an NVIDIA GeForce RTX 5070 (Linux, driver 620.73.04, 32 only). With an AMD Radeon RX 580 (Polaris, RADV Mesa 26.0.8) as the 64-lane reference (`W64G_SAVE_REF`; GCN has one subgroup size, 64, in every stage but no FRAGMENT in `requiredSubgroupSizeStages`, so `vk_harness` counts a requested size equal to a device's only size as applied), the RTX 5070 run of every fixture (`W64G_REF`) equals the reference for all 13 tier A/B fixtures and differs from it for all 11 tier C ones, pixel and vertex; the same reads in a vertex shader run on the wave interpreter (64 lanes against two waves of 32, equal) because a GPU's partial vertex waves leave the lanes they would read empty. Vertex shaders: the VS stage cannot be forced on the 880M (no VERTEX in `requiredSubgroupSizeStages`), so VS is covered by the strict wave interpreter (`tests/semantic/test_wave64_halves.py`: 64 lanes against two waves of 32; tier A/B equal, tier C differs); geometry shaders are not tested (the corpus ones are wave64, see *Wave size*; no fixture). 64 lanes against two waves of 32; tier A/B equal, tier C differs), and on RADV also on the GPU (TEST-251): RADV runs the VS stage (NGG) as wave64 by default and as wave32 with `RADV_PERFTEST=gewave32` (GFX10+, seen in the `RADV_DEBUG=shaders` dump: 64-bit EXEC operations against `exec_lo`), so `w64_graphics.py` draws each `vs_w64_*` fixture both ways, 960 zero-area vertices (`VKH_VERTICES`) that store four words each to the heap, with `vs_w64_c_lane_id` as the probe that the wave size changed (largest lane id 63, then 31). RADV packs 62 or 64 vertices into a wave64 and 30 or 32 into a wave32, so the 32-lane run repacks the vertices rather than halving the waves; tier A/B words are keyed on the vertex index, which makes this the stricter test. `vs_w64_a_skip`, `_b_waterfall`, `_b_readlane_uniform` (readfirstlane and readlane 40/63 of uniform VGPRs) and `_b_ballot_atomic` (240 slots as a set) give the derived words at both sizes; `_c_bcnt_export`, `_c_readlane` and `_c_lane_id` differ (the detector is right), on an RX 9070 XT (GFX1201) and a Ryzen 9800X3D iGPU (GFX1036, RDNA2), RADV Mesa 26.3.1; geometry shaders are not tested (no fixture; the corpus has 195 wave64 geometry shaders, all tier C, see the census). `_c_bcnt_export`, `_c_readlane` and `_c_lane_id` differ (the detector is right), on an RX 9070 XT (GFX1201) and a Ryzen 9800X3D iGPU (GFX1036, RDNA2), RADV Mesa 26.3.1; geometry shaders likewise (TEST-251): RADV runs the GS stage (NGG) as wave64 by default and as wave32 with `gewave32`, and `w64_graphics.py` draws each `gs_w64_*` fixture after `vs_ids` (960 vertices, 320 triangles, `VKH_GS`), each invocation finding its triangle from `vs_ids`'s vertex number and storing four words to the heap, with `gs_w64_c_lane_id` as the probe (largest lane id 41, RADV puts at most 42 GS invocations in a wave64, then 31). **LDS writes of a legacy GS:** `rdna2spirv.gs_ds` maps one to an output slot from its offset alone and drops the VGPR address (the lane's GSVS area), so `wave64_halves.py` checks only the data a GS `ds_write` writes, not its address; before, a lane id that only formed the GSVS base made the shader tier C `lane-id`. Confirmed three ways: a hand-written GS with the base `lane id * 96` translates, after `spirv-opt -O`, to the same instructions as without it; `gs_w64_a_ring` (that shape) gives the derived records at wave64 and wave32 on both GPUs; and `tests/semantic/test_wave64_halves.py` (`GeometryRing`) keeps the lane id in the written data, or in a memory store's address, tier C. The corpus GS were that false tier C: all 195 contain `v_mbcnt_hi`, all 195 were tier C in the TEST-319 census, and `wave64_halves.py --census` on the corpus translated at `f847748c` puts all 195 in tier A. `_c_bcnt_export`, `_c_readlane` and `_c_lane_id` differ (the detector is right), on an RX 9070 XT (GFX1201) and a Ryzen 9800X3D iGPU (GFX1036, RDNA2), RADV Mesa 26.3.1; geometry shaders are not tested (the corpus ones are wave64, see *Wave size*; no fixture). The corpus GS form their GSVS base from `v_mbcnt_lo/hi` (all 195 contain `v_mbcnt_hi`): they were all a false tier C, and the census above has all 195 at tier A. `wave64_halves.py --census` on a translated corpus shows it. `_c_bcnt_export`, `_c_readlane` and `_c_lane_id` differ (the detector is right), on an RX 9070 XT (GFX1201) and a Ryzen 9800X3D iGPU (GFX1036, RDNA2), RADV Mesa 26.3.1; geometry shaders are not tested (the corpus ones are wave32; no fixture). Not checked: helper lanes of partial quads; `VK_KHR_shader_maximal_reconvergence` is assumed for waterfall and election loops. Tiers A and B assume subgroups of at least 32 lanes: a fragment stage may run fewer live lanes than the subgroup size it reports (Intel UHD 770: gl_SubgroupSize 32, ballot count 16, a shuffle from lane L^16 returns garbage; measured by kapitche, TEST-433), so `w64_graphics.py` skips the tier A/B pixel fixtures on a device whose minimum subgroup size is below 32 when neither the 64 nor the 32 run took effect; deriving the skip from a measured live fragment width (ballot count) in `vk_harness` is a follow-up. **ADD_TID_ENABLE** (SHADER-833, finding by @shdann in #4571): an access with no `idxen` through a V# whose word3 is a literal (`s_mov_b32` earlier in the block, the notion `rdna2spirv` uses for `sgpr_imm`) with bit 23 set takes the wave lane as its index (`idxen` ignores the bit, see *Swizzled buffer addressing*), so its `buffer_load*`/`tbuffer_load*` result and its `buffer_store*`/`tbuffer_store*`/`buffer_atomic*` address carry the raw lane id: tier C `lane-id`. A literal with the bit clear, and every access with `idxen`, are unchanged. **Assumption**: through a run-time V# (loaded from memory or user data) tiers A and B take ADD_TID_ENABLE as 0 for an access without `idxen`; the code cannot say otherwise. The literal is tracked with the same folds `rdna2spirv` applies to `sgpr_imm` (mirrored in `Analysis.literal_sgpr`: `s_mov_b32/b64`, `s_movk_i32`, `s_pack_*`, `s_bfm_b32`, `s_not_b32`, `s_and/lshl/lshr_b32`, `s_mul_i32`; other folded ops count as run-time). The corpus census was not re-measured with this rule: its tier counts above are from before it and may change. Follow-up, needs the game: count the bound V#s with word3 bit 23 set at run time, and re-run `--census`. | -| GFX10.1 (console gfx1013) / GFX10.3 (gfx1030, gfx1036 oracle) opcode differences | Found by disassembling every opcode of every GFX10 encoding (SOP1/SOP2/SOPK/SOPC/SOPP, SMEM, VOP1/VOP2/VOPC/VOP3/VOP3P, DS, FLAT/GLOBAL/SCRATCH, MUBUF/MTBUF, MIMG) with LLVM 21 `llvm-mc` for `-mcpu=gfx1013` and for `gfx1030`/`gfx1036` (the two gfx103x lists are identical). Every other opcode slot decodes to the same mnemonic on both, so the hardware-oracle rows measured on gfx1036 are about the same instructions the console runs (the microarchitectures still differ, which no opcode table shows). **On gfx1013 only:** `v_mac_f32`/`v_mad_f32` (VOP2 0x1f, VOP3 0x11f/0x141) and `v_mac_legacy_f32`/`v_mad_legacy_f32` (VOP2 0x06, VOP3 0x106/0x140), translated (rows above; not measurable on gfx103x, where 0x06/0x106/0x140 are the fused `v_fmac_legacy_f32`/`v_fma_legacy_f32`); `v_mul_lo_i32` (VOP3 0x16b; `Unsupported` until #3504 translates it); `s_get_waveid_in_workgroup` (SMEM 0x2a), translated in compute and mesh shaders; scalar stores (`s_store_dword*`, `s_buffer_store_dword*`), scalar atomics (`s_atomic_*`, `s_buffer_atomic_*`, 32- and 64-bit), scalar scratch (`s_scratch_load/store_dword*`), `s_dcache_wb`, `s_dcache_discard(_x2)` and the 31 LDS `ds_*_src2_*` forms, all `Unsupported`. **On gfx103x only:** `v_dot2c_f32_f16`, `v_dot4c_i32_i8`, the VOP3P `v_dot2_f32_f16`, `v_dot2_i32_i16`/`u32_u16`, `v_dot4_i32_i8`/`u32_u8`, `v_dot8_i32_i4`/`u32_u4`, `v_fmac_legacy_f32`/`v_fma_legacy_f32`, `global_load/store_dword_addtid`, `global_atomic_csub`, `buffer_atomic_csub`. The console's code can't contain these; the translator handles the integer dot products (rows above, measured on gfx1036) and refuses the rest, so a listing disassembled for the wrong target (VOP2 0x06 printed as `v_fmac_legacy_f32`) fails loudly instead of being translated as a fused multiply-add. Not covered by the sweep: opcodes whose operand template did not decode on either target, and behaviour that differs without an opcode change. | -| Buffer bounds checking | MUBUF `buffer_load*`, `buffer_store*`, and `buffer_atomic*` enforce `num_records` (V# word 2). Out-of-bounds stores/atomics skip memory access completely and out-of-bounds loads return 0 without a load. **The RX 6800 measurement behind RAW loads** (`buffer_load_dword`/`x2`/`x3`/`x4`, stride 0, no `idxen`, OOB_SELECT 3; the per-mode rule below covers every mode, stride and `idxen`): the byte offset O = inst_offset + soffset + (offen ? vaddr : 0) is exact (nothing truncated, and the address keeps base & 3), and dword i is data when O + 4·i + 4 ≤ num_records, else 0, measured on AMD Radeon RX 6800 (gfx1030, Windows driver 32.0.21045.29003) by running the instructions as a raw compute kernel, wave32 and wave64 (155 runs, every result either 0 or the stored data, wave32 = wave64 in every dword), for x1/x2/x4 with V# word3 0x31016fac (OOB_SELECT 3) at offsets 0..63 per lane, NUM_RECORDS 17..23 and 0x1000, base & 3 = 0 and 3: a dword at 0xf with NUM_RECORDS 18 is 0 (a start-only check reads it); x4 at 3 with 18 gives three data dwords and 0 for the fourth, which starts at 15 < 18 (so neither a whole-load nor a per-dword start check), and the zero is a whole 0, not partial bytes; x4 at offset:13 with 20 gives data, 0, 0, 0; inst_offset, soffset and offen are summed before the check; base & 3 = 3 flips at the same offsets. `x3` gets the rule without a measurement. **Per-mode check (V# OOB_SELECT, word3 bits [29:28])**, for every MUBUF/MTBUF access, as measured natively on RDNA2 (gfx1036, 732 cases, `docs/buffer_bounds.md`; Mesa's GFX11 column, not its GFX10 one). `idx` = `vindex` (0 without `idxen`), `off` = inst_offset + vaddr offset (offen), `offs` = `off` + soffset. A dword at byte 4·k of the access is out of range when: **0 STRUCTURED_WITH_OFFSET** `idx >= num_records` or `off + 4k + 4 > stride`; **1 STRUCTURED** `idx >= num_records` (no `idxen`: idx 0, so only `num_records == 0`); **2 DISABLED** `num_records == 0`; **3 RAW** `offs + 4k + 4 > num_records` (`idx * stride` is in the address, not in the check). A literal word3 (`s_mov_b32` earlier in the block) folds the mode, a run-time one selects with `OpSelect`. Multi-dword accesses, measured on the Radeon 880M (gfx1150, a valid proxy: gfx1036 follows the same column and gfx1150 matched it bit-exactly): in modes 0 and 3 **`buffer_load_dwordx2..x4` and `buffer_store_dwordx2..x4` are per dword**, for loads and stores alike (x4 at off 20 of 32 in RAW loads/stores 3 dwords, at 28 one, at 32 none; mode 0 likewise at the stride); modes 1 and 2 check once and always take the whole access. **A typed element (`buffer_load_format_*`, `buffer_store_format_*`) is all or nothing and ends at its format's size** (32_32_32_32 at off 20 of 32 reads or writes nothing), and an atomic checks its dword's end like a dword access. The translator does the same: per-dword guarded loads and stores for modes 0 and 3 (a store that straddled the edge used to write past it), the element size from the instruction's format, a literal word3 or the V#. The same oracle confirmed the terms (504 `buffer_load_dword` probes, idxen/offen/inst_offset/soffset at the stride and record edges, 0 disagreements): mode 0's `off` has `inst_offset` and no soffset, mode 1 reads nothing but the index, mode 3 adds inst_offset and soffset. `s_buffer_load` (SMEM) is separate: it keeps the `num_records` bound of the Scalar/buffer row and ignores OOB_SELECT (the same pattern for 0 to 3). **Swizzle**: SWIZZLE_ENABLE (V# word1 bit 31, Mesa `gfx10-rsrc.json` line 326; word1 [31:30] on GFX11, `gfx11-rsrc.json` line 259) and ADD_TID_ENABLE (word3 bit 23, line 337) change the address and the bounds in every mode and are modelled; see the Swizzled buffer addressing row. SWIZZLE_ENABLE and ADD_TID_ENABLE are modelled; see the Swizzled buffer addressing row. SWIZZLE_ENABLE (V# word1 bit 31, Mesa `gfx10-rsrc.json` line 326; word1 [31:30] on GFX11, `gfx11-rsrc.json` line 259) and ADD_TID_ENABLE (word3 bit 23, line 337) change the address and the bounds in every mode and are not modelled: a literal V# with either set is `Unsupported`, a run-time V# with them is translated unswizzled, which is silently wrong (known gap). Until 2026-11-22 the translator ignored OOB_SELECT and checked by stride alone (`offset < num_records`, `index < num_records`, or `offset < num_records * stride`): a V# with word3 = 0 (mode 0, stride 0) was fully readable and is now always out of range, as on hardware, so the test harnesses' output V# is `0x31016fac` now (`vk_compute_test`, the interpreter tests, `cs_bounds.asm`, `cs_fmt_1010102.asm`, `cs_store.asm`). **How confirmed**: the native RDNA2 measurement (gfx1036) and the gfx1150 oracle (RDNA3.5, same column); GPU test `cs_oob_select.asm` (every mode, literal and run-time V#, words derived from the rules) on an NVIDIA RTX 5070 and an AMD Radeon 880M, which checks the translation, not RDNA2; `tests/semantic/test_buffer_oob_select.py` (a hand-written table of 33 cases over the four modes, loads and stores, both V# forms, plus the multi-dword stores and typed elements); `cs_oob_tail.asm` pins the end-based edge, per-dword x4 loads and stores and the all-or-nothing element, where Mesa's GFX10 column gives other words. **RDNA1 (gfx1011, Navi 12) follows the same RDNA2/GFX11 column**: `tools/buffer_bounds_probe.py` ran 12 one-lane 4-byte `buffer_load_dword` cases at wave32 and wave64 through `tools/hw_oracle` (24 groups, 0 wave32/64 differences); all matched the measured column and 8 disagreed with Mesa's GFX10 column (SHADER-341, results in `docs/buffer_bounds.md`). **Unmeasured**: gfx1013/GFX10.1 itself (see `docs/buffer_bounds.md`), swizzle, unaligned addresses, and the mode 1/2 boundary of `buffer_load_dwordx2..x4` on RDNA2 hardware proper (the gfx1150 proxy shows all dwords in). Checked by `tests/semantic/test_value_semantics.py` (`RawBufferTailBounds`: the RX 6800 rows, values and the addresses loaded) and the GPU tests `runtime/test/shaders/cs_bounds.asm` (AMD Radeon RX 9070 XT, RX 6800), `cs_buf_tail.asm` (RX 6800, Vulkan, driver 26.11.2; aligned offsets only, since the translator's `Aligned 4` loads at byte-exact addresses were not checked on a Vulkan driver) `cs_oob_select.asm` and `cs_oob_tail.asm`. `cs_fmt_xy_xyz.asm` shows the whole element deciding for `_xy` and `_xyz` too, measured natively on a Radeon 680M (gfx1035, RDNA2): components that end inside num_records, in an element that doesn't, read 0 and store nothing. | -| 8/16-bit MUBUF d16 loads and stores | (The plain `buffer_load_{u,s}byte`/`{u,s}short` are `Gen.buffer_load_sub`'s; `tests/semantic/test_buffer_sub_dword.py` checks them too.) The `_d16` loads (`buffer_load_{u,s}byte_d16[_hi]`, `buffer_load_short_d16[_hi]`) write one 16-bit half of `vdata` (`_hi` the high one; a byte zero- or sign-extended to 16 bits) and keep the other. `buffer_store_byte`/`short` write the low 8/16 bits of `vdata` (the `_d16_hi` forms its high half). The address is `buffer_address`'s, and the bounds check covers the access's own size, 1 or 2 bytes, as for a typed element of that size (`elem="fmt"`, format 1 or 7). Out of range, a load gives 0 (in the half it writes, for d16; **not measured** for d16) and a store writes nothing. Each byte is its own access, so a 16-bit one that crosses a dword is exact; in a swizzled buffer the next dword is `step` bytes on. A store merges each byte into its dword with atomic and/or, as buffer byte format stores do. Inactive lanes neither load nor store, and the first-read analysis counts a d16 load's `vdata` as read. Until 2026-11-22 these ten raised `Unsupported`. CPU-checked by `tests/semantic/test_buffer_sub_dword.py` (every op at byte offsets 0 to 7, the edge of `num_records`, an inactive lane, rejected forms). GPU fixture `cs_w32_buffer_sub16` (the six d16 loads with their kept half and the sign extension, the two `_d16_hi` stores taking bits 23:16 / 31:16), passes on llvmpipe (Mesa 26.0.8) and on an NVIDIA RTX 5090 (595.99.02, @tylerstraub on #1864), all eight words; GPU fixture `cs_w32_buffer_store_sub` for the plain `buffer_store_byte`/`buffer_store_short` (Box16Rehydration's blocker, @YaBulochka on #1864), including a short at byte 3 that writes its high byte into the next dword, passes on llvmpipe with LLVM 21 and 23, and on an Apple M4 (MoltenVK 1.4.2) once the second dword of a 16-bit load is indexed from the first one's pointer instead of a second pointer converted from the same address, which Apple's compiler read as 0 (@sovljanskii on #1864). | -| Swizzled buffer addressing (V# SWIZZLE_ENABLE, ADD_TID_ENABLE) | MUBUF/MTBUF `buffer_load*`, `buffer_store*`, `buffer_atomic*`, `buffer_load_format_*`/`buffer_store_format_*` and `tbuffer_load/store_format_*` follow the rules measured natively on RDNA2 (`AMD Radeon(TM) Graphics`, gfx1036, Windows driver `32.0.21042.62`, wave32 and wave64; `tools/buffer_swizzle_probe.py`, SHADER-343). MUBUF/MTBUF `buffer_load*`, `buffer_store*`, `buffer_atomic*`, `buffer_load_format_*`/`buffer_store_format_*` and `tbuffer_load_format_*` follow the RDNA2 ISA ("RDNA 2" Instruction Set Architecture, 8.1.5 Buffer Addressing, "Swizzled Buffer Addressing" and tables 33, 35 and 37). Fields, Mesa 24.0.6 `src/amd/registers/gfx10-rsrc.json` (`SQ_BUF_RSRC_WORD1`, `SQ_BUF_RSRC_WORD3` and its `_gfx103` twin, the same bits): `SWIZZLE_ENABLE` word1 bit 31, `STRIDE` word1 `[29:16]`, `INDEX_STRIDE` word3 `[22:21]` (`IS = 8 << n`, i.e., 8, 16, 32 or 64), `ADD_TID_ENABLE` word3 bit 23; element size is fixed at 4 bytes (`word3[20:19]` and `word1[30]` do not alter addressing or stepping). **Effective index:** `index = idxen ? vindex : 0)`, where `lane` is the wave lane (`thread_id[5:0]` within the wave, wrapping at 32 in wave32 and 64 in wave64; `Gen.wave_lane`); **`idxen = 1` completely ignores `ADD_TID_ENABLE`** (linear or swizzled, address and bounds, loads/stores/typed/atomics). **Activation:** `SWIZZLE_ENABLE` activates (`swz_active`) only when `idxen = 1` or `ADD_TID_ENABLE = 1`; with neither, addressing is linear (`base + soffset + off`) and `OOB_SELECT 3` stays RAW even when `stride ≠ 0`. **Address formula (when `swz_active`):** `off = uint32((offen ? vaddr : 0) + inst_offset)` (32-bit wrap), `buffer_offset = (index / IS · stride + (off & ~3)) · IS + (index % IS) · 4 + (off & 3)`, `address = base + soffset + buffer_offset` (confirmed byte-exact for IS 8/16/32/64, non-4-multiple strides, stride 0, and unaligned offsets). **Two swizzle sub-modes:** (1) **Scratch swizzle** (`SWIZZLE_ENABLE = 1`, `idxen = 0`, `ADD_TID_ENABLE = 1`): raw multi-dword `buffer_load/store_dwordx2..x4` step by **`+4 · IS`** bytes per dword (and unaligned 4-byte raw accesses crossing a dword boundary split across `+4 · IS` on hardware), while **typed formats > 4 bytes** (8/12/16-byte MUBUF and MTBUF loads/stores, regardless of component count) and **8-byte `buffer_atomic_*_x2`** are **suppressed** (loads return 0, stores/atomics are no-ops, even in `OOB_SELECT 2`); typed formats ≤ 4 bytes work normally. (2) **Indexed swizzle** (`SWIZZLE_ENABLE = 1`, `idxen = 1`, regardless of `ADD_TID_ENABLE`): raw `x2..x4`, typed formats (8/12/16 bytes), and `buffer_atomic_*_x2` step **linearly by `+4` bytes** from the swizzled base address, even across `IS` boundaries, and typed formats > 4 bytes execute normally. **Bounds (`OOB_SELECT`):** modes 0, 1 and 2 follow the Buffer bounds checking row with `idx = index`; **`OOB_SELECT 3` with `swz_active` and `stride ≠ 0`** checks **`uint64(index) + uint64(soffset) >= num_records` or `off + payload > stride`** (per-dword for raw `x1..x4`, whole element for typed), while inactive swizzle or `stride = 0` keeps the RAW check `uint64(off) + uint64(soffset) + payload > num_records` (no 32-bit wrap on `off + soffset`, whereas `vaddr + inst_offset` wraps at 32 bits before bounds checking). A literal word1 / word3 (`s_mov_b32` earlier in the block) folds each bit; a run-time V# selects dynamically with `L = swz_u · (3 + INDEX_STRIDE)` (IS = 1 gives the linear address). Until 2026-11-22 the translator added `vindex + lane` when `idxen = 1` and `ADD_TID_ENABLE = 1`, swizzled even when both were 0, stepped all swizzled multi-dword/typed accesses by `4 · IS`, allowed > 4-byte typed/atomic_x2 accesses in scratch-swizzle mode, omitted `soffset` from swizzled mode 3's index check, and wrapped `off + soffset` at 32 bits in RAW mode 3. **How confirmed:** native RDNA2 measurement on `AMD Radeon(TM) Graphics` (gfx1036, Windows driver `32.0.21042.62`, wave32 & wave64) via `tools/buffer_swizzle_probe.py --oracle both` (22/22 cases across 8 groups match bit-exactly, 0 unexpected mismatches, 0 unexpected wave32/64 diffs, 64-thread `ADD_TID_ENABLE` wave-lane wrap verified at both wave sizes); CPU semantic tests `tests/semantic/test_buffer_swizzle.py` (literal and run-time V#, both sub-modes, mode 3 `soffset`, 32-bit wrap, typed/`atomic_x2` suppression, and `cs_buf_swizzle.asm`); `tests/test_buffer_swizzle_probe.py`. **Remaining approximations / unmeasured:** unaligned raw accesses splitting across `+4 · IS` in scratch-swizzle mode (the translator uses `Aligned 4` PSB loads/stores), general typed-format / `buffer_atomic_*_x2` natural alignment suppression (`16_UINT` at odd offsets, `32_*` at non-4B offsets, `atomic_*_x2` at non-8B addresses, observed on gfx1036 in both linear and swizzled modes), and GFX11's two-bit `SWIZZLE_ENABLE` (`word1[31:30]`). SWIZZLE_ENABLE word1 bit 31, STRIDE word1 [29:16], INDEX_STRIDE word3 [22:21] (IS = 8, 16, 32 or 64 indices), ADD_TID_ENABLE word3 bit 23; there is no ELEMENT_SIZE field, the element is fixed at 4 bytes (ISA 8.1.5; LLVM `SIInstrInfo::getScratchRsrcWords23` sets it only up to GFX8). `index` = (idxen ? vindex : 0) + (ADD_TID_ENABLE ? lane : 0), where the lane is thread_id[5:0] within the wave (`Gen.wave_lane`), swizzled or not: table 33 adds the thread id with no swizzle condition and table 36's ring column is linear with add_tid. `offset` = (offen ? vaddr : 0) + inst_offset, without soffset. Swizzled: buffer_offset = (index / IS · stride + offset / 4 · 4) · IS + index % IS · 4 + offset % 4, address = base + soffset + buffer_offset, so dword k of a multi-dword access (and of a typed element over 4 bytes) is 4 · IS bytes after dword k − 1, not 4. Bounds as in Buffer bounds checking, with `idx` = `index` (the lane included), except that OOB_SELECT 3 with SWIZZLE_ENABLE and stride ≠ 0 checks `index >= num_records` or `off + 4k + 4 > stride` (table 35), like mode 0; stride 0 keeps the raw check. A literal word1 / word3 (`s_mov_b32` earlier in the block) folds each bit. A run-time word1 makes IS = 2^(SWIZZLE_ENABLE · (3 + INDEX_STRIDE)): IS = 1 is the linear address, so one formula serves both and nothing is selected but the mode 3 check; a run-time word3 multiplies the lane by ADD_TID_ENABLE. Cost, measured on the 116 shaders of `runtime/test/shaders` that both versions translate (all `spirv-val` clean before and after): the 56 with a MUBUF access through a run-time V# grow by 15.1 % in SPIR-V lines (+10.4 % over all 116), 30 to 45 instructions per access (address, lane, 4 per extra dword, a select per dword of the bounds check); a literal linear V# gives the same SPIR-V as before. Outside compute and mesh shaders the lane is `SubgroupLocalInvocationId`, so a VS, PS or GS with a run-time V# now declares `GroupNonUniform`. The offset arithmetic is 32-bit, like the linear address. Until 2026-11-22 a literal V# with either bit was `Unsupported` and a run-time one was translated unswizzled. **How confirmed**: Mesa/LLVM and AMD's ISA reference (fields and formula), not measured on hardware; `tests/semantic/test_buffer_swizzle.py` (hand-worked addresses for IS 8/16/64, index msb/lsb, soffset after the swizzle, the mode 3 rule with and without a stride, per-dword x2/x3/x4 loads and stores, a 16-byte typed element, ADD_TID on lane 5 linear and swizzled, each with a literal and a run-time V#); GPU test `runtime/test/shaders/cs_buf_swizzle.asm` (check.py, `scripts/run_gpu_tests.py`), which checks the translation, not RDNA2. **Unmeasured**: the swizzled layout on RDNA2 hardware, offsets that are not dword aligned (the ISA requires alignment for swizzled accesses; the translation adds offset % 4), wrap of the 32-bit offset, and GFX11's two-bit SWIZZLE_ENABLE (word1 [31:30]). **Unmeasured** (the layout itself is measured: `docs/shader_validation.md`, SHADER-343, gfx1036, 22 of 22 cases bit-exact): offsets that are not dword aligned (the ISA requires alignment for swizzled accesses; the translation adds offset % 4), wrap of the 32-bit offset, and GFX11's two-bit SWIZZLE_ENABLE (word1 [31:30]). In the corpus `SCRATCH_EN` is 0 in every CS, so a swizzled V# can only come from a descriptor the game writes itself. | -| `v_permlane16_b32` / `v_permlanex16_b32` with the source lane off in EXEC (SHADER-74) | The VOP3 modifier `op_sel:[FI, BOUND_CTRL]` decides what a lane gets when the lane it reads is off in EXEC. **FI=1** (`op_sel` bit 0, encoding 0x0800): the source lane's value, as before. **FI=0** (the default): the destination lane is not written and keeps its old value when BOUND_CTRL=0, and gets 0 when BOUND_CTRL=1 (`op_sel` bit 1, 0x1000). A source lane that is on gives its value whatever FI / BOUND_CTRL are, and a lane that is itself off is never written (normal EXEC rule). The translator shuffles the active bit with the same selector as the value (also in `--wave64-emulate`, where it is a second exchange). On a native subgroup the two shuffles are combined with bitwise masks, not a scalar select: absent source lanes are redirected to the calling lane first (as `ds_lane_read`), the value and the activity bit are fetched through the redirected index, and `ok` masks the shuffled value over the old one (over zero with BOUND_CTRL=1) and the destination write is masked too, so the ballot and both shuffles run before lane predication — MoltenVK 1.4.2 and MoltenVK main at SPIRV-Cross aa217aeb lowered the scalar select to a short-circuiting Metal ternary and the FI=0 lanes read the source lane's value instead, which `cs_w32_permlane_fi` caught on an Apple M1 Max (#5895); `v_permlanex16_b32` pairs the rows 0↔1 and 2↔3 of a wave64 as before. Until SHADER-74 every case returned the source value (right only for FI=1). Source of the bit mapping: LLVM `llvm.amdgcn.permlane16/permlanex16 ` (IntrinsicsAMDGPU.td) is selected in `VOP3Instructions.td` (`PermlanePat`) with `fi` as the `src0` op_sel bit and `bound_control` as the `src1` one, and the CodeGen tests `llvm.amdgcn.permlane.ll` print `op_sel:[1,0]` for FI and `op_sel:[0,1]` for BOUND_CTRL; `llvm-mc -mcpu=gfx1013` encodes `op_sel:[1,0]` as 0x0800 and `op_sel:[0,1]` as 0x1000 in the second byte pair of the first word (0xD777 / 0xD778). Behaviour: hardware measurement on RDNA2 (Ryzen 7950X3D iGPU, raw kernel, wave64 and wave32 consistent; the same on RDNA3.5) by aslan2142 in [#374](https://github.com/ItsNotRexed/Leonida/issues/374#issuecomment-7071597516). Pinned by `runtime/test/shaders/cs_w32_permlane_fi.asm` (EXEC 0x55555555, every active lane's source is off; out[0..7] = 1000 0 4 1 1000 0 52 49) in `check.py` and `scripts/run_gpu_tests.py`, and on the CPU by `tests/semantic/test_permlane_fi.py`. | -| Null mask source | The scalar register `null` supplies zero when read as a lane mask. The wave64 fixture in `tests/semantic/fixtures/null_mask_source.asm` checks a high-bit test, a zero-bit count, a first-set-bit search and a masked vector write after `s_and_saveexec_b64`. LLVM 21.1.8 assembles each instruction for gfx1030. [LLVM GFX10 null operand](https://releases.llvm.org/15.0.0/docs/AMDGPUOperandSyntax.html#null) | -| Wave64 mask ballot | `tools/lane_masks.py` tracks per-lane masks (including 32-bit `MASK_LO`/`MASK_HI` halves, `vcc_lo`/`vcc_hi`, `s_bfm_b64` bitfields, `_b64` copies of immediates into `vcc`, and `_b64` bitwise/select ops combining a lane mask or `vcc` destination with immediates; 32-bit mask + non-0/-1 immediate into an SGPR stays plain data, #1792). Split wave64 SGPR pairs whose two dwords hold separately written half-masks or a half-mask paired with a 0/-1 `EITHER` constant (`include_either=True`) are recognized by `holds_lane_mask` and read `s[r]` for lanes 0–31 and `s[r+1]` for lanes 32–63 in `mask_src`, and `--wave64-emulate`'s `x_mcache` keys `wave_mask` on every dword of an SGPR operand so rewriting `s[r+1]` invalidates a cached 64-bit exchange. `s_bcnt1_i32_b64`/`b32`, `s_bcnt0_i32_b64`/`b32`, `s_ff1_i32_b64`/`b32`, `s_ff0_i32_b64`/`b32`, `s_bitcmp0/1_b32/b64`, and `v_mbcnt_lo/hi_u32_b32` reconstruct the 64-bit wave mask via `OpGroupNonUniformBitwiseOr` (`GroupNonUniformArithmetic`), restricting 32-bit half ops (including `v_mbcnt_lo/hi_u32_b32` on `vcc_hi`/`vcc_lo`/`exec_lo` via `mask_half`) and `s_cmp_eq/lg_u32` (`wave_equal`) to the known 32-bit half in wave64. `tools/lane_masks.py` tracks per-lane masks (including 32-bit `MASK_LO`/`MASK_HI` halves, `vcc_lo`/`vcc_hi`, and `s_bfm_b64` bitfields). `s_bcnt1_i32_b64`/`b32`, `s_bcnt0_i32_b64`/`b32`, `s_ff1_i32_b64`/`b32`, `s_ff0_i32_b64`/`b32`, and `s_bitcmp0/1_b32/b64` reconstruct the 64-bit wave mask via `OpGroupNonUniformBitwiseOr` (`GroupNonUniformArithmetic`), restricting 32-bit half ops and `s_cmp_eq/lg_u32` (`wave_equal`) to the known 32-bit half in wave64. Opposite-half `s_cmp_*_u32/i32` comparisons (lo vs hi), ordering comparisons on mask halves, and `s_cmp_*_u32/i32/u64` comparing a lane mask against an arbitrary scalar or immediate reconstruct the exact 32/64-bit mask words via `wave_mask`. A compare with 0 keeps the vote, but a compare with -1 (all ones) does not: lanes that were never launched (a group smaller than the wave) don't vote, while their bits are 0 in the real mask, so until 2026-11-22 `s_cmp_eq_u32 vcc_hi, -1` read 1 in a 40-thread wave64 for `vcc_hi` = 0xff. GPU-checked with `cs_w64x_partial_scmp.asm` (40-thread wave64, native and `--wave64-emulate`) and `cs_w32_partial_scmp.asm` (20-thread wave32) on an AMD Radeon RX 7800 XT (RADV, Mesa 26.2.6): all 8 words as the headers derive, and 4 of 8 wrong in each with the old translator. GPU-checked with `runtime/test/shaders/cs_wave64_ballot.asm` and `cs_wm_*.asm` on AMD Radeon RX 9070 XT (64-wide subgroup); semantic test coverage in `tests/semantic/test_scalar_bitcmp.py`, `tests/semantic/test_scalar_alu_shifts.py`, `tests/semantic/test_loop_ballot_barrier.py`, and `tests/test_lane_masks.py` (split SGPR pairs, dual-dword `x_mcache`, `_b64` mask+imm, and `v_mbcnt` half selection CPU-checked, not yet GPU-verified). GPU-checked with `runtime/test/shaders/cs_wave64_ballot.asm` and `cs_wm_*.asm` on AMD Radeon RX 9070 XT (64-wide subgroup); semantic test coverage in `tests/semantic/test_scalar_bitcmp.py` and `tests/semantic/test_scalar_alu_shifts.py`. | -| 64-bit mask equality (SHADER-551) | `s_cmp_eq_u64` / `s_cmp_lg_u64` compare both exact 32-bit words and set a uniform SCC. Canonical full-wave masks (`exec`, mask-valued `vcc`, or a wave64 `MASK_LO`/`MASK_HI` SGPR pair) compared with another full mask or zero may use a whole-wave equality vote. Other SGPR pairs materialize each mask half separately and retain scalar data and constant words, including split, swapped, duplicated, mixed mask/data and wave32 pairs. Comparing with all ones also materializes words, so unlaunched lanes remain zero bits in partial waves. CPU-checked by `tests/semantic/test_scmp_u64_mask_pairs.py` with full and partial wave64, wave32, and wave64-emulation cases; independent synthetic Vulkan readback is reported in [PR #3007](https://github.com/ItsNotRexed/Leonida/pull/3007). No native RDNA2 instruction oracle was run for this rule. | -| VOP3 FP modifiers on constants | `tools/shader_ir.py` keeps VOP3 FP source modifiers (`neg(...)`, `\|...\|`, `-\|...\|`, `abs(...)`, and nested combinations) as `abs`/`neg` flags on `imm` and `fimm` operands so `abs` clears the sign bit first and `neg` flips it second (matching LLVM `AMDGPUInstPrinter.cpp::printOperandAndFPInputMods` and `llvm/test/MC/AMDGPU/vop3-modifiers.s`). Plain signed literals (`-1`, `-1.0`) are unchanged. Until 2026-11-22, `-\|1.0\|` folded `-` into the float before `FAbs` (yielding `+1.0`), `neg(0x3f800000)` / `neg(1)` applied two's-complement integer negation (`-4.0f` / `0xffffffff` NaN instead of `-1.0f` / `0x80000001`), and `\|0x...\|` / `-\|0x...\|` dropped `abs`. `tools/shader_meta.py` applies the same bit operations in `_imm_u32`. Checked on the CPU by `tests/test_shader_ir.py`, `tests/test_shader_meta.py` and `tests/semantic/test_vop3_const_mods.py` (f32, f16, `v_fma_mix_f32`, `v_cmp_class_f32`, f64 SPIR-V structure); GPU-checked for `-\|-2.0\|`, `neg(0x3f800000)`, `\|0xbf800000\|` and f16 `-\|0x3c00\|` by `ps_vop3_const_mods.asm` (Tesla V100 (NVIDIA 580.95.05, Linux)). | -| `v_cmp_class_f64`, `v_cmpx_class_f64` | IEEE-754 binary64 numeric class test against the 10-bit mask (`0` sNaN, `1` qNaN, `2` `-inf`, `3` `-normal`, `4` `-subnormal`, `5` `-0`, `6` `+0`, `7` `+subnormal`, `8` `+normal`, `9` `+inf`), lowered in `Gen.cmp_class_f64` using pure 32-bit `%uint` bit extraction on `(lo, hi)` with no `Float64` capability required. Supports VGPR/SGPR pairs, float inline constants (`fimm`), sign-extended inline integers (`-16..64`), 32-bit literals placed in bits `[63:32]` (as on RDNA2), and VOP3 `abs`/`neg` sign-bit modifiers on `src0` (`abs` clears bit 63, `neg` flips bit 63 without quieting sNaN). Inactive lanes produce 0 for `v_cmp_class_f64` and stay inactive for `v_cmpx_class_f64`. Source: AMD RDNA2 ISA VOPC/VOP3 `V_CMP_CLASS_F64` / `V_CMPX_CLASS_F64`. CPU-checked by `tests/semantic/test_cmp_class_f64.py` (all 10 classes with low- and high-word payload bits, mask combinations and high-bit ignores, SGPR pairs, `fimm`/inline/literal constants, `abs`/`neg`/`-\|x\|`, `v_cmpx_class_f64` EXEC narrowing, inactive lanes, no `Float64` capability, bad-operand rejections). **Not GPU-verified.** Hardware-measured natively on `gfx1100`** (RX 7900 XTX, driver 26.10.1) through `tools/hw_oracle`: the ten classes as `f64` pairs (`0x7ff0000000000001` sNaN, `0x7ff8000000000000` qNaN, `0xfff0000000000000` -inf, `0xbff0000000000000` -normal, `0x8000000000000001` -denormal, `-0`, `+0`, `0x0000000000000001` +denormal, `0x3ff0000000000000` +normal, `0x7ff0000000000000` +inf) against their own bit, all ten bits, no bits and the nine other bits (40), and `v_cmpx_class_f64` on the launched lane true and false (2), all matching the same CPU model. Not measured: `abs`/`neg`, inactive lanes and wave64. **Not GPU-verified.** | -| Mesh/compute input registers (historical measurement) | An early read-before-write analysis over all compute and mesh shaders found **compute** v0 (880), v0–v1 (614), v0–v2 (50), consistent with AMD's local thread ID x/y/z in v0/v1/v2, and scalar inputs centred on a pointer at s[4:5] and s6/s7. **Mesh:** every one of 2,969 reads exactly **v5**, plus s3 (always arithmetic), s[16:17] and s19–s23. The early pass also read FSSM 0x13C as the group width and compared the first SGPR multiply against it (82 match, 151 don't, 1,447 no simple multiply) and wrongly concluded that 0x13C was not the group width; the matching register varied by shader (s6/s10/s7/s9…). PSV0 gave the real thread-group sizes (32×1×1 for 1,253, 8×8×1 for 416, …). **Superseded:** 0x13C/0x140/0x144 are the thread-group size, `COMPUTE_PGM_RSRC2` at 0x138 gives the per-shader user-SGPR count and enabled workgroup IDs, and mesh takes NumThreads, limits and topology from PSV0 with `v5 = linearGroupIndex * NumThreads + LocalInvocationIndex`. All 2,689 CS and 9,282 mesh shaders translate now (see the Compute shaders and Mesh shaders rows). | -| Formerly untranslated | Mesh (9,282), geometry (195) and compute (2,689) now translate; `s_swappc_b64` is replaced by Vulkan vertex inputs (see *Vertex fetch*) and the `tbuffer_load_format_*` forms use the instruction's format. Packed `tbuffer_load_format_d16_{x,xy,xyz,xyzw}` load two 16-bit components per VGPR, with the same final partial write as MUBUF. Native gfx1036 wave32/64 confirmed all four widths for RGBA8_UINT and RGBA8_UNORM with a conflicting 32_UINT V# format. Both packed and ordinary MTBUF loads ignore the V# channel selectors and use identity for the instruction format, zero-filling missing channels. Native gfx1036 measurements compared multiple V# permutations with MUBUF as a control. An INVALID V# format (0) suppresses the MTBUF fetch even at a valid address inside its bounds. Native gfx1036 wave32/64 returned zero components at all four widths and preserved the untouched half of an odd D16 destination, as specified for unbound resources in the [RDNA2 ISA, §8.1.4](https://www.amd.com/content/dam/amd/en/documents/radeon-tech-docs/instruction-set-architectures/rdna2-shader-instruction-set-architecture.pdf). A translated vertex fetch on RTX 5080 and Radeon Graphics also followed a change to the instruction format between two draws with identical vertex records and V#. Fixed UNORM and SNORM loads share the exact integer quotient for each magnitude width across instructions and channels (checked against rationally rounded binary32 values on RTX 5080 and Radeon Graphics). The gfx1013 disassembler omits `format:` for the [GFX10 MTBUF default](https://llvm.org/docs/AMDGPUModifierSyntax.html#ufmt), `BUF_FMT_8_UNORM` (code 1). A few rare ops are still reported by name rather than guessed. | -| `v_cubema_f32` signed zero | Whenever the selected major axis is ±0.0, `v_cubema_f32` returns `+0.0` (`0x00000000`), never `-0.0` (`0x80000000`), while preserving NaNs and signed non-zero major-axis values (`2.0 * m`). Emitted as `OpFOrdEqual %bool m %f0` selecting `%f0` over `OpFMul m 2.0`, so `-0.0` maps to `+0.0`, NaN compares false and propagates, and non-zero finite/infinite values double with sign preserved. Until 2026-11-22 both `tools/rdna2spirv.py` and `tools/f32_fuzz.py` multiplied `m` by `2.0` directly and returned `-0.0` when `z = -0.0` on `(±0.0, ±0.0, -0.0)` (or when `-0.0` was selected alongside NaN axes). **Measured natively on RDNA2** (`gfx1036`, AMD Radeon(TM) Graphics, Windows driver `32.0.21042.62`, wave32 & wave64, all four MODE combinations `flush`/`keep`/`no_dx10`/`ieee` via `tools/hw_oracle/`): all 8 `(±0.0, ±0.0, ±0.0)` triples, `-v` source negation of `+0.0`, `mul:2`, negative denormals, and `(-0.0, qNaN, qNaN)` returned `0x00000000`, while `(-qNaN, 1.0, 1.0)` returned `0xffc00000` and `(-1.0, qNaN, qNaN)` returned `0xc0000000`. Checked by `tests/semantic/test_valu_cube.py` (`test_signed_zero_triples_and_nan_cubema`), `tests/test_f32_fuzz.py` (`test_cube_major_axis`), and `tools/f32_fuzz.py --oracle hw --ops v_cubema_f32,v_cubeid_f32,v_cubesc_f32,v_cubetc_f32`. | -| `v_dot2c_i32_i16`, `v_dot8c_i32_i4` | VOP2/VOP3 accumulating forms of `v_dot2_i32_i16` and `v_dot8_i32_i4` (`D = sum(S0.elem[k] * S1.elem[k]) + D`, signed 2×16-bit and 8×4-bit). Wraps at 32 bits by default and saturates to `[INT32_MIN, INT32_MAX]` with VOP3 `clamp` (sharing the `v_dot2_i32_i16`/`v_dot8_i32_i4` signed-carry path); `op_sel`, `neg`/`abs`, and DPP/SDWA are refused. Registered in read-before-write VGPR tracking alongside `v_dot4c_i32_i8`. Source: LLVM AMDGPU `VOP2Instructions.td` (`HasDot4Insts` / `HasDot3Insts`, `gfx908` VOP2/VOP3 syntax; not in the default `gfx1013`/`gfx103x` feature set). **Not measured on AMD hardware** (translated Vulkan lowering checked on RTX 5070 by @duudiis: 40,960/40,960 exact words across wave32 and emulated wave64). Checked bit-for-bit on the CPU (`spirv_mini_interp`) and with `spirv-val` by `tests/semantic/test_alu_dotc.py`; not run on the shader corpus. | -| Out-of-bounds typed buffer loads and `DST_SEL=1` | When a MUBUF `buffer_load_format_{x,xy,xyz,xyzw}` or `buffer_load_format_d16_{x,xy,xyz,xyzw}` is out of bounds (`OOB_SELECT` 0–3, `num_records == 0`, partial-element spill, or swizzled OOB), memory is not accessed and raw data channels (`DST_SEL` 4..7) read 0, while the V# `DST_SEL` swizzle still runs: `DST_SEL=0` returns 0 and `DST_SEL=1` returns `1.0f` (`0x3F800000`, `d16` `0x3C00`) iff V# `FORMAT[6:0]` is a valid float, normalized or scaled buffer format (`1..77` ending in `_UNORM`, `_SNORM`, `_USCALED`, `_SSCALED`, or `_FLOAT`), and integer `1` (`0x00000001`, `d16` `0x0001`) for `UINT`/`SINT`, `INVALID` (`0`), and reserved codes (`78..127`). `d16_x` and `d16_xyz` preserve the unaddressed upper 16 bits of the final destination VGPR, and MTBUF `tbuffer_load_format_*` ignores V# `DST_SEL` on both out-of-bounds and `FORMAT=0` loads (returning 0 in addressed channels). Until 2026-11-22 `Gen.buffer_load_format` clamped the post-swizzle result to 0 when `in_b` was false (`SHADER-429`), dropping `DST_SEL=1` on out-of-bounds loads and returning `1.0f` instead of `1` for `DST_SEL=1` with `FORMAT=0`. **Hardware-verified on RDNA2** (`gfx1036`, Windows 11, driver `32.0.21042.62`, wave32 and wave64, 746 kernels via `tools/hw_oracle`: all 41 `Gen.FORMATS` across `xyzw`/`d16_xyzw`/`d16_xyz`/`d16_x`, all 128 7-bit `FORMAT` codes `0..127` for both `f32` and `d16`, `OOB_SELECT` 0–3, partial spill, swizzled OOB, MTBUF controls, and inactive EXEC lanes), Vulkan GPU-checked across all 128 7-bit `FORMAT` codes (`xyzw`, `d16_xyzw`, `d16_xyz`, `d16_x`) and the `cs_fmt_*`/`cs_oob_*`/`cs_bounds`/`cs_buf_*` fixtures on NVIDIA GeForce RTX 5090 (driver `32.0.16.1088`) and AMD Radeon Graphics (`gfx1036`, driver `32.0.21042.62`), and CPU/`spirv-val`-checked by `tests/semantic/test_buffer_oob_dst_sel.py`. | -| `v_div_fixup_f32` | Measured natively on an AMD Radeon(TM) Graphics RDNA2 GPU (`gfx1036`, not the console's `gfx1013`; Windows driver 32.0.21042.62, `tools/hw_oracle`, wave32 and wave64 identical on every case: 256 seeded triples across 4 MODEs plus 73 targeted special-case/modifier rows, 0 mismatches). Computes `div_fixup_f32(S0=quotient, S1=denom, S2=numer)` with pure integer SPIR-V ops under the game's inferred MODE (`IEEE=0`, `denorm32=0`, `DX10_CLAMP=1`): VOP3 `abs` (clear bit 31) then `neg` (flip bit 31) apply bitwise to `S0`/`S1`/`S2` before classification (including NaN payloads); `S1`/`S2` subnormals flush to signed zero (`exp == 0`) while `S0` subnormals are preserved; priority order is (1) `NaN(S2) → S2`, (2) `NaN(S1) → S1` (signalling NaNs pass unchanged under `IEEE=0`, quieted only when `IEEE=1`), (3) `0/0` or `±inf/±inf → 0xFFC00000` (`-qNaN`), (4) `zero(S2) ∨ inf(S1) → ±0.0`, (5) `zero(S1) ∨ inf(S2) → ±inf`, (6) `exp(S2) − exp(S1) ≤ −151 → ±0.0` (pure biased-exponent check, beats `NaN(S0)` and `inf(S0)`; no overflow check), (7) `NaN(S0) → ±inf`, (8) `copysign(S0, sign(S1) ⊕ sign(S2))`. Output modifiers `mul:2`/`mul:4`/`div:2` apply before `clamp`, and `clamp` maps NaN to `+0.0` (`DX10_CLAMP=1`) before `FClamp` to `[0, 1]`. Not modelled: `IEEE=1` sNaN quieting, `denorm32=3` keeping `S1`/`S2` subnormals, and the hardware `omod` `-0 → +0` quirk (same as the other f32 ops). Checked bit-for-bit against 73 measured `gfx1036` words in `tests/semantic/test_alu_div_fixup_f32.py`. | -| Atomic natural alignment, 64-bit bounds, and `buffer_atomic_{fmin,fmax}` | Measured natively on RDNA2 (AMD Radeon(TM) Graphics, `gfx1036`, Windows driver `32.0.21042.62`, wave32 and wave64 via `tools/hw_oracle/`): **natural alignment** is enforced on every 32-bit and 64-bit buffer/global atomic (`buffer_atomic*`, `buffer_atomic*_x2`, `global_atomic*`, `global_atomic*_x2`), even under `OOB_SELECT = 2` (DISABLED). A 32-bit atomic requires `(addr & 3) == 0` (`offset = 1, 2` and `base + 2, offset = 0` are dropped; `base + 2, offset = 2` succeeds) and a 64-bit `_x2` atomic requires `(addr & 7) == 0` (`offset = 2, 4` and `base + 4, offset = 0` are dropped; `base + 4, offset = 4` succeeds). When dropped (OOB or unaligned), memory is untouched, an active `glc` lane receives `0` (32-bit) or `(0, 0)` (64-bit) in `vdst`/`vdata`, and an inactive lane (`EXEC = 0`) preserves `vdst`/`vdata`. Independently confirmed on a second `gfx1036` (driver `24.10.24`): without the alignment guard, an unaligned SPIR-V `OpAtomicAdd` corrupts the aligned dword (`100 -> 0xDEADBEF3`), whereas with the guard memory stays untouched and `0` is returned. `Gen.atomic_aligned` guards all six atomic emitters on `addr & 3 == 0` / `addr & 7 == 0`, merges `0` via `OpPhi` on skipped paths, and writes through `Gen.dst` so inactive lanes keep their prior register value while active unaligned/OOB lanes receive `0`. **64-bit partial bounds (`buffer_atomic*_x2`)**: the same `gfx1036` wave32/wave64 measurements confirm the all-or-nothing 8-byte bounds rule (`fixed_fmt = 62`) across all four `OOB_SELECT` modes (answering the unmeasured note in the `buffer_atomic_{and,or,xor,swap}_x2` row): mode 3 (RAW) requires `offs + 8 <= num_records` (`0/8` and `8/16` succeed; `0/7`, `0/5`, `0/4`, `8/15`, `8/12` drop cleanly); mode 0 (STRUCTURED_WITH_OFFSET) requires `idx < num_records` and `off + 8 <= stride` (`stride = 8, off = 0`, `stride = 16, off = 8`, `stride = 12, off = 0` succeed; `stride = 7, off = 0` and `stride = 12, off = 8` drop); mode 1 (STRUCTURED) checks `idx < num_records`; mode 2 (DISABLED) checks `num_records != 0`. **`buffer_atomic_{fmin,fmax}`**: lowered via `Gen.buffer_atomic_float` sharing `Gen._emit_atomic_fminmax_cas` (relaxed Device-scope `OpAtomicLoad` seed + `OpAtomicCompareExchange` + `GLSL.std.450` `NMin`/`NMax` CAS loop, no float-atomic extension required), enforcing V# bounds, 4-byte alignment, and `glc` return (`lds` and non-1-VGPR `vdata` raise `Unsupported`). On `gfx1036`, normal floats, `±inf`, `-0` vs `+0` (`fmin(-0, +0) = -0`, `fmax(-0, +0) = +0`), and `qNaN` (returns the non-NaN operand) match `NMin`/`NMax`; **known approximation**: the `gfx1036` L2 atomic unit quiets `sNaN` (`0x7f800001 -> 0x7fc00001`) regardless of `MODE`, while f32 subnormal handling follows the wave's `MODE.denorm32` and preserves sign (independently verified on a second `gfx1036`, wave32/wave64: under `denorm32 = 0`, subnormals flush to signed zero — `fmax(0x80000001, 0x80000002) -> 0x80000000 (-0)`, `fmax(0x00000001, 0x00000002) -> +0` — whereas under `denorm32 = 3`, subnormals are preserved and `NMin`/`NMax` is exact); `NMin`/`NMax` does not model `sNaN` quieting or `denorm32 = 0` subnormal flushing. CPU-checked by `tests/semantic/test_buffer_atomic_fminmax_and_align.py` (value grid, multi-lane CAS contention, OOB/partial-bounds matrix, inactive vs active-unaligned distinction across all six atomic families, and SPIR-V structural checks). | - -### System values confirmed on the corpus (SHADER-4) - -Counted with `scripts/audit_shader4_regs.py` on the disassembled game shaders (counts only): - -- **Compute shaders:** Confirmed by corpus counts across all 2,689 CS (`TIDIG_COMP_CNT` 0/1/2/3 = 724/1,786/179/0; `TGID` X/Y/Z 100/110/111 = 724/1,786/179; `TG_SIZE_EN` = 0, `SCRATCH_EN` = 0, `TRAP_PRESENT` = 0; RBW VGPRs: `v0` in 2,602, `v1` in 893, `v2` in 57) + GPU tests `cs_lds.asm` and #186's `cs_workgroup_yz.asm` (Y/Z `WorkgroupId`). -- **Mesh shaders:** Confirmed by corpus counts (all 9,282 MS are 128×1×1 in PSV0, 100% read `v5` once, through `v_readfirstlane_b32` followed only by `s_lshr_b32 D, sX, 7`, 100% read `s3` exclusively via `s_bfe_u32 D, s3, 0x40018` for bits [27:24]; 0 read `s3` [31:28], [23:16], or [15:0]; audited with `scripts/audit_shader4_regs.py`) + GPU tests `ms_tri.asm`, `ms_wave_info_s3.asm` (`s3[27:24]` across both waves), and #219 (mesh `v5` workgroup index on a 2 × 3 × 4 grid). -- **Geometry shaders:** Confirmed by corpus counts (all 195 GS read only `v0` and `v1`; 0 read `v2`, `v3`, or `v4`) + GPU test `gs_tri.asm`. - -**Main blocker at the time (superseded): descriptor loads.** On a 3,000-shader sample, `s_load_dwordx4`/`x8` stop over half of them. Shaders -load texture, buffer and sampler descriptors through user-data SGPR pointers, and how the game's root signatures -map onto those SGPRs is set up by game code. Reading that mapping from the exe (root signature creation plus the -FSSM user-data metadata) before building the binding layer was the next step; guessing it would give silent -rendering bugs. The translator now handles those loads against the push-constant user-data contract (*User data*, -*Scalar/buffer memory* and the descriptor rows); the D3D12 layer still has to supply the root-signature mapping. -The other blockers listed then (mesh, the vertex-fetch call, geometry, compute and compressed exports) are closed -for the corpus: all 26,503 shaders translate (see *Translator status*). The remaining fidelity gap is wave64 -cross-half code on 32-wide subgroups. - -## Day one, in order - -1. `scripts\first_look.ps1 -Exe ...` checks the exe is plain, lists the imports to shim, and does a dry run. -2. Read the RPF9 table of contents only where it is already plain on disk. Five archives have tables that look packed - or encrypted; under the ground rules above they stay unread and are recorded, not decrypted. Where a table is - readable, a reader in `rpf9_carve.py` gives carved blobs real names and types, and the remaining unread data shows - what it is. -3. Find the texture and mesh resource structures in the exe (their loaders give exact field layouts), which turns - carved blobs into named textures and meshes. -4. Shader translation: already complete for all 26,503 shaders (see *Translator status*); the day-one work is - validating them through the runtime. - -## Disassembling shaders - -The AMDGPU disassembler needs LLVM 21+ built with the AMDGPU target (`llvm-mc`; on Linux the `llvm-21` package -installs it at `/usr/lib/llvm-21/bin/llvm-mc`). The official Windows LLVM build has no AMDGPU target and ships no -`llvm-mc.exe`. On Windows, either build a native one or run it from WSL. - -Native: `scripts\build_llvm_mc.ps1` fetches the LLVM sources the tool needs (sparse, shallow), builds `llvm-mc` alone -with `LLVM_TARGETS_TO_BUILD=AMDGPU`, static CRT and the DIA SDK off (its headers need ATL, which the C++ build tools -don't always include), checks it disassembles an `s_endpgm` for `gfx1013`, keeps only `llvm-mc.exe` (by default in -`%USERPROFILE%\.leonida\llvm-mc`) and sets `LLVM_MC` for the user. It needs git, Python and Visual Studio with the C++ -x64 tools, about 2 GB of temporary space and 20-40 minutes. `-Dest`, `-NoEnv`, `-Keep` and `-Version` change the -defaults. Keep `-Dest` out of AppData: `python` from the Python install manager (the `WindowsApps` alias) doesn't see -folders that other programs create under `%LOCALAPPDATA%` or `%APPDATA%`, so `make_game.py` reports `llvm-mc` missing -and the fuzzers stop with `WinError 2`, although `LLVM_MC` names the file; `py`, or the same `python.exe` started by -its full path, sees it (measured with Python 3.14.7 on Windows 11). - -``` -powershell -ExecutionPolicy Bypass -File scripts\build_llvm_mc.ps1 -python -I make_game.py --game "D:\path\to\your\package" --stages shaders -``` - -WSL: install `llvm-21` and give `LLVM_MC` the whole command: - -``` -set LLVM_MC=wsl -d Ubuntu -e /usr/lib/llvm-21/bin/llvm-mc -python -I make_game.py --game "D:\path\to\your\package" --stages shaders -``` - -The same form works in every tool that reads `LLVM_MC`. `tools/mc_command.py` splits it for `shader_disasm.py`, -the tests, `runtime/test/shaders/build.py` and `scripts/run_gpu_tests.py`; the assembler callers pass the assembly -on stdin, so a WSL command never receives a Windows file path. - -`shader_disasm.py` disassembles one `s_endpgm` before starting, so a missing tool or AMDGPU target stops the run -with that reason instead of writing empty `.s` files. To disassemble by hand inside WSL: - -``` -LLVM_MC=/usr/lib/llvm-21/bin/llvm-mc python3 -I /tools/shader_disasm.py /shaders/fssm -``` - -Code starts at the u32 at FSSM offset 0xC0 (the code-section offset) plus 0x28 bytes into that section, and ends at the -last `s_endpgm`. Use `--mcpu gfx1013`. On 300 random shaders it decoded 284 cleanly (134 invalid words in total), -against 201 clean and 6,560 invalid for gfx1030 and 283 clean for gfx1010–1012. - -Some blobs end with a constant-data block after the real code: `s_endpgm`, a dword count N, N dwords of data, a -closing `s_endpgm`, then `s_code_end` padding. The data is not code, so the tool ends the range at the count -(`data_block_start`) and no longer reports those words as invalid. Over a 26,503-blob build, 1,473 blobs had such a -block (N from 0 up to several hundred); with the block excluded all 1,473 decode with no invalid word, and none of -the other 25,030 blobs matches the pattern. -## PAL stage descriptors - -The FSSM header starts a table of 0x88-byte hardware-stage records at offset 0x100. A record's first qword is -`0x000000C0_0002_AAHH`: `HH` (byte 0) is the PAL hardware stage and `AA` (byte 1) the API stage. Record k -starts at `0x100 + 0x88*k`; the table ends at the first zero or non-tag qword. On the 26,503-blob corpus -26,308 blobs carry one record and 195 (all GS) carry two, the second at 0x188 being the same shader's VS -copy. API ids: 0 VS (2,236), 1 PS (12,101), 2 GS (195), 3 CS (2,689), 6 MS (9,282), each equal to the carve -index's stage. Hardware ids: 2 ES (the first tag-0x0D payload of the 195 two-payload VS containers), 3 GS -(195), 4 VS (2,431, the 195 GS copies included), 5 PS (12,101), 6 CS (2,689) and 7 (9,282, every mesh -shader: the NGG/primitive path). Unused record fields are zero in 25,643 records; 1,055 records (860 blobs, -the 195 GS pairs included) carry paired `0xDEADBEEFDEADBEEF` qwords, a lone 32-bit `0xDEADBEEF` never -occurs, and those 860 are the blobs whose 0x120/0x12C/0x130 directory words are `0xDEADBEEF`. The hardware -ids 0/1 and the API ids 4/5 are not in the corpus; the rest of a record is not decoded. -`tools/pal_stages.py` prints the records of an FSSM or a container (every tag-0x0D payload); -`tests/test_pal_stages.py` covers the layout with synthetic blobs. -`scripts/vs_layout_census.py` checks these hardware ids against the code of every payload: every stage-7 -payload carries the NGG markers (`exp prim`, `s_sendmsg MSG_GS_ALLOC_REQ`, `v_mbcnt`), every stage-4 payload -is a legacy non-NGG VS, and the stage-2 ES payloads have no `exp` (they write the vertex outputs to LDS for -the geometry stage) — see *VS input layout, per PAL hardware stage* and *VS as ES* above. - -## Pixel-shader inputs - -`tools/fssm_header.py` decodes the FSSM input table: 8-byte records from 0x138 while the first byte is 6. -Byte 1 is the semantic id, byte 2 the component mask, byte 3 the running index, byte 6 the parameter slot, -and byte 7 holds flags (bits 0–1 = the **read method**: 0x01 read through `v_interp_mov_f32`, 0x02 through -32-bit `v_interp_p1/p2`; values 0 and 3 never occur; bit 3 marks a Float16-typed parameter; bit 4 = 16-bit -interpolant). The record's position is the `v_interp attr` number. `read_methods()` returns those bits by -position (the #1246 accessor was named `interpolation_modes`; #1301 renamed it) — they are the read method, -not the D3D interpolation mode (the mode is PSV0's; see the "PS interpolation modes (SHADER-181)" row and the -"PS `v_interp` read methods" row). `interpolants()` returns the count and a fp16 bitmask by position; -`rdna2spirv.py` uses it for the pixel-input declarations. `wave_size()` decodes the compiled wave size from -the header flags word `u32[0xD4]` bit 5 (`0x20` = wave32, `0` = wave64), consumed by `rdna2spirv.py` for -every stage (see *Wave64 handling*). Measured on the 26,503-blob corpus: every blob starts with `FSSM` and -is at least 0xD8 bytes long, 2,662 are wave32 (1,535 CS, 1,127 PS) and 23,841 are wave64 (1,154 CS, 195 GS, -9,282 MS, 10,974 PS, 2,236 VS) with 0 contradictions against GFX10 code-proven wave32/wave64 instructions; -25,643 satisfy `u32[0x120] + u32[0x12C] == u32[0x130]` (the 860 that do not store 0xDEADBEEF at 0x130); 12,101 are PS, -10,307 with a non-empty table (55,791 records, 11,199 of them 16-bit). The count equals the number of -distinct `v_interp attr` numbers in 11,316/12,101 PS (93.5%); 300 more declare one unread input, 475 -declare two or more, and the 10 undercounts are one family whose first record at 0x138 has kind 7. A -200-PS spot check agreed on 187/200. Flag bit 4 matches the `*_f16` interpolation opcodes in -12,067/12,101 (99.7%). - -`tools/ps_interp_modes.py` decodes the interpolation mode of each PS input from the DXBC container -carved next to the FSSM, and runs the census. The mode is not in the FSSM: no FSSM word stores -`SPI_PS_INPUT_ENA`/`ADDR` (every u16 in bytes 0x00–0x138 of all 12,101 PS was compared against the -value reconstructed from the DXBC signature; only constants coincide). The PSV0 chunk -(writer: dxc `lib/DxilContainer/DxilPipelineStateValidation.{h,cpp}`) holds, after the runtime info, -resource bindings, string table and semantic-index table, a u32 element size (16) and then one -16-byte input element per row: u32 semantic-name offset (0 = system value), u32 semantic-index -offset, u8 rows, u8 start row, u8 cols[3:0] | start col[5:4] | allocated[6], u8 semantic kind -(`DXIL::SemanticKind`: 0 Arbitrary, 3 Position, 6 ClipDistance, 7 CullDistance, 13 IsFrontFace), -u8 component type (`DxilProgramSigCompType`: 1 UInt32, 3 Float32, 6 Float16), u8 interpolation mode, -u8 dynamic mask | output stream, u8 reserved. The ISG1 chunk (the repo's 32-byte elements) supplies -the read mask that marks live rows. The FSSM record flags decode as the read method — bit 0 (0x01) -`v_interp_mov_f32`, bit 1 (0x02) 32-bit `v_interp_p1/p2`, bit 3 (0x08) Float16-typed parameter, -bit 4 (0x10) `*_f16` opcodes — and the disassembly supplies the I/J operand of every interpolation. -Per shader the code reads one barycentric pair (v0/v1 in 10,259 PS, none in 1,841, one v14 copy), -and the pair's class follows the read rows: perspective-centre when a perspective generic is read, -linear only in the 4 PS that interpolate SV_Position through the parameter cache (D3D forces -noperspective on SV_Position), flat otherwise. Synthetic tests: `tests/test_ps_interp_modes.py`. - -## Baseline already recorded - -- `reports/manifest.json`: SHA-256 of all 108 files in `Documents\GTA6` (208.5 GiB). Run - `python -I tools\manifest.py verify ` to check a copy against it. -- `reports/rpf_probe.json`: all 22 archives are **RPF9**. Five have tables that look packed or encrypted (`levels`, - `movies`, `core_bvh4`, `navmeshes`, `data`). -- `reports/pe/`: the 16 bundled DLLs are plain x86-64 PE with no encrypted sections. Through the loader their - `xmem.dll` imports and two `d3d12_xs.dll` root-signature calls bind to shims. Every other import resolves on - desktop Windows. The proxy covers the measured device slots and forwards the rest in PC vtable order; the Xbox - queue/fence/command-list extensions and `PresentX` remain unknown. diff --git a/docs/dev-tools.md b/docs/dev-tools.md deleted file mode 100644 index d36091ec3..000000000 --- a/docs/dev-tools.md +++ /dev/null @@ -1,93 +0,0 @@ -# Development tools - -From the Leonida checkout root, use Python 3 to list the development tools: - -```powershell -python -I scripts/dev.py --help -python -I scripts/dev.py discover -python -I scripts/dev.py discover --json -``` - -From another directory, pass the path to `scripts/dev.py`, quoting it if needed. -The inventory always describes the checkout containing that script. - -`boot-trace` points to the analyzer for startup JSONL and D3D12 stderr logs. -`guest-scene` points to the headless synthetic guest runner. Run a listed help -command from the checkout root to see the producer's options. The text -inventory displays commands for PowerShell on Windows and POSIX shells -on other platforms. The inventory -checks for each producer script and lists its prerequisites without checking -those prerequisites or running the producer. Live attach, pause, step, input, -and screenshots are unavailable through this entry point. - -## JSON output - -`discover --json` writes one object to stdout: - -- `schema_version` identifies the format. The current version is `1`. -- `tools` lists entries by `id`. Each `path` uses forward slashes and is - relative to the checkout root. `present` indicates whether the script is - a file. `help_argv` is a list of arguments for a command run from the checkout - root. Its first argument is the Python executable running discovery. It - is `null` when the script is missing. `requirements` lists prerequisites - for using the producer. -- `live_controls` contains an `available` boolean and a `reason`. - -Exit code `0` indicates that the inventory was emitted, including when a -producer script is missing. Invalid CLI arguments exit with code `2`. - -## Analyze a boot trace - -Use the existing analyzer through the development CLI: - -```powershell -python -I scripts/dev.py boot-trace --help -python -I scripts/dev.py boot-trace "logs/startup trace.jsonl" -python -I scripts/dev.py boot-trace "logs/startup trace.jsonl" --d3d12 "logs/d3d12 stderr.log" --json -``` - -Pass a startup JSONL from `gta6rt --trace`, a D3D12 stderr log from -`gta6rt --trace-d3d12`, or both. Relative input paths are interpreted from -the directory where you run the CLI. From outside the checkout, give the -path to `scripts/dev.py` and keep the trace paths relative to your directory. - -The analyzer supplies the help, output, diagnostics and exit status. If one -input fails but the other can be read, `--json` can still emit a partial -summary on stdout with a diagnostic on stderr and exit code `2`. If neither -input can be analyzed, there is no JSON summary. The summary describes the -recorded events, and the exit status reports the analysis result. - -You can also run `python -I tools/boot_trace.py` with the same arguments. - -## Run a synthetic guest scene - -Use the existing headless runner with a loader and guest built on Windows -with Vulkan, static SDL3 and `LEONIDA_GUEST_SCENE=ON`. Supply the synthetic -M1.5 shader fixture root containing `spirv/`. See the -[runtime instructions](../runtime/README.md#a-600-frame-headless-guest-scene) -for the build, fixture and Wine setup. - -```powershell -python -I scripts/dev.py guest-scene --help -python -I scripts/dev.py guest-scene --loader "build/gta6rt.exe" --guest "build/tiny_guest_draw.exe" --shaders "m15 shaders" --out "scene run" --negative-controls -``` - -Pass `--out PATH` or `--out=PATH` with a new or empty directory. Relative -paths are interpreted from the directory where you run the CLI, including -when you invoke `scripts/dev.py` by its full path from another directory. - -The CLI forwards the runner's exit code and diagnostics. Exit code `0` -means the scene checks passed. Exit code `1` can indicate a scene check -failure or a failure before the runner can write a report, such as an -output directory it cannot create. Exit code `2` indicates a usage or -prerequisite error. - -When the runner writes `report.json`, it prints the path. Open that file -for the scene result and per-run details. For example, if the full run -starts and the loader exits with an error, `runs.full.returncode` records -the loader's exit code while the CLI returns the runner's exit code. -The output directory also holds any logs, frame records and PPM images -the runner produced. If the runner rejects an occupied directory, any -report already there belongs to an earlier run. - -You can also invoke `python -I scripts/run_guest_scene.py` directly. diff --git a/docs/directstorage.md b/docs/directstorage.md deleted file mode 100644 index c7d933275..000000000 --- a/docs/directstorage.md +++ /dev/null @@ -1,197 +0,0 @@ -# DirectStorage - -The console title reads its streamed data through Xbox DirectStorage: `DStorageGetFactory` hands out a factory, the -factory opens files and creates queues, and a queue reads file or memory ranges into memory and reports completion -through status arrays, `ID3D12Fence` signals and events. `runtime/shims/dstorage.cpp` serves that API on the PC: -files open through the runtime's `GAME:` mapping and write overlay, and a worker thread per queue does the reads -and inflates zlib requests. -This page records which DLL and ABI the console title is expected to use, how sure that is, and what the shim does. - -## Which DLL and which ABI: the evidence - -The game executable is not in the package available here, so its import table is unmeasured -([runtime_imports.md](runtime_imports.md)). What is known: - -| Evidence | Source | What it says | -|---|---|---| -| None of the 16 shipped DLLs imports DirectStorage | [runtime_imports.md](runtime_imports.md) (6 Xbox-specific imports, all `xmem`/`d3d12_xs`), [textures.md](textures.md) "The shipped binaries" (no `DStorage` import, export or string) | DirectStorage, if used, is called by the executable itself | -| The texture chunks carry the `DSTORAGE_BCPACK_MODE` values 1-7 and mix zlib and BCPack chunks | [textures.md](textures.md) "What BCPack is" | The data is laid out for console DirectStorage's decompression (DEFLATE, then BCPack, then swizzle) | -| A sibling console layer's export inventory names `dstorage_xs.dll` as console DirectStorage | [d3d12_vulkan.md §7](d3d12_vulkan.md#7-prior-art-and-measured-xbox-abi) | The console module name, measured elsewhere, not here | -| A retail title run by a sibling layer has `xcrdapi` in its console-only library set | [d3d12_vulkan.md §7](d3d12_vulkan.md#7-prior-art-and-measured-xbox-abi) | Only the name. Nothing in this repository says what `xcrdapi.dll` exports | -| The GDK reference: `DStorageGetFactory` is in header `dstorage_xs.h`, library `dstorage_xs.lib`; the interface pages give library `dstorage.lib`; all say "Xbox Series consoles" | [GDK DStorage reference](https://learn.microsoft.com/en-us/gaming/gdk/docs/reference/system/dstorage/dstorage_members) | The console API has its own names (`IDStorageFactoryX`, `IDStorageQueueX`, `IDStorageFileX`, `IDStorageStatusArrayX`) and structures that differ from the PC API | -| `registry.cpp` classified `dstorage.dll`/`dstorage_xs.dll` `DStorageGetFactory` as returning an HRESULT | `runtime/shims/registry.cpp` | It was an unimplemented import; `xcrdapi.dll` was not named | - -**Chosen ABI: the console one** (the GDK's `IDStorageFactoryX2`/`IDStorageQueueX2`/`IDStorageFileX`/ -`IDStorageStatusArrayX` and its `DSTORAGE_REQUEST`), served as `DStorageGetFactory` under all three names: - -| Module | Confidence | Why | -|---|---|---| -| `dstorage_xs.dll` | medium | The reference's `dstorage_xs.lib` and the sibling inventory agree; not measured in this title | -| `xcrdapi.dll` | low | Only a name in a library list. Owning the module also means a title's `LoadLibrary("xcrdapi.dll")` gets the shims' pseudo-handle, and `GetProcAddress` for any other name returns `NULL` (logged). Static imports of other `xcrdapi` names are unchanged | -| `dstorage.dll` | low | The interface pages name `dstorage.lib`. Every caller of `gta6rt`'s import table is a console build, so this name serves the console ABI too, not the PC one | - -The PC DirectStorage ABI (`dstorage.h`: `IDStorageFactory` with `DSTORAGE_REQUEST` source and destination unions, -`ID3D12Resource` destinations) is **not served**. A caller that asks for a PC interface id gets `E_NOINTERFACE` and a -log line, never an object of the wrong shape. The one exception is `IDStorageStatusArray`, whose two methods are the -console interface's in the same order (console D3D12 binaries reuse the PC SDK's ids), so a status array accepts its -id. - -Owning a module has a run-time side: `LoadLibrary` of `xcrdapi.dll` or `dstorage.dll` (or `dstorage_xs.dll`) gets -the shims' pseudo-handle even when the package ships its own copy of that DLL, so the shim shadows a packaged copy -at run time (`library_loader.cpp` asks the registry before the bundled loader). None of the 16 shipped DLLs is one -of these, so nothing is shadowed today. - -### What is not public, and the choice made - -| Unknown | Choice | Confidence | Where to change it | -|---|---|---|---| -| Vtable order of the console interfaces (the reference lists methods alphabetically) | The PC header's order for the methods both APIs have; console-only methods where the overview lists them: factory `CreateQueue, OpenFile, CreateStatusArray, SetCpuAffinity, SetDebugFlags, SetStagingBufferSize`, then `GetStats` (X1), `CreateQueue1` (X2); queue `EnqueueRequest, EnqueueStatus, EnqueueSignal, Submit, CancelRequestsWithTag, Close, GetErrorEvent, RetrieveErrorRecord, Query`, then `EnqueueSetEvent` (X1), `Query1` (X2); status array `IsComplete, GetHResult`; file `Close, GetHandle` | queue, status array: medium; file: medium; factory: low (the `SetCpuAffinity` slot is a guess) | `runtime/shims/dstorage_xs_abi.h`, one declaration per interface | -| Interface ids of the X interfaces | A creating call (`DStorageGetFactory`, `CreateQueue*`, `OpenFile`, `CreateStatusArray`) accepts an id it has not seen for the kind of object it hands out and logs it once (`[rt] dstorage: ... asked for {...}: serving the ... interface`), so the first boot records them. It refuses an id seen for another kind, a PC DirectStorage id, and the system COM interfaces (the `{xxxxxxxx-0000-0000-C000-000000000046}` range with `IMarshal`, `IClientSecurity`, ..., and `IAgileObject`, `INoMarshal`, `IInspectable` and a few more). `QueryInterface` follows [d3d12_vulkan.md](d3d12_vulkan.md)'s rule (an unknown id is `E_NOINTERFACE`, logged): it accepts only `IUnknown`, the declared `IDStorageStatusArray` id for a status array, and the ids a creating call accepted for that kind of object | n/a (a policy, not a fact) | `IidPolicy` in `runtime/shims/dstorage.cpp` | -| `DSTORAGE_MIN_QUEUE_CAPACITY`, `DSTORAGE_MAX_QUEUE_CAPACITY`, `DSTORAGE_REQUEST_MAX_NAME` | The PC header's values: `0x80`, `0x2000`, 64 | medium | `dstorage_xs_abi.h` | -| `E_DSTORAGE_*` values | The PC `dstorageerr.h` values (`FACILITY_GAME`, `0x8924xxxx`). That header also defines the console-only failures (zlib, BCPack, swizzle, XVD), so the space is shared. `E_DSTORAGE_DECOMPRESSION_ERROR` (`0x89240030`) is on the public constants page; `E_DSTORAGE_ZLIB_BAD_HEADER`, `_ZLIB_BAD_DATA` and `_ZLIB_PARITY_FAIL` (`0x89240031`-`33`) have no public description, and their names and values come from the header-generated bindings of the `direct-storage` crate (Sources). Which failure the console reports with each zlib code is inferred from the names | medium-high (values); medium (zlib codes' meaning) | `dstorage_xs_abi.h` | -| Struct layouts | The compiler's x64 layout of the reference's declarations, pinned with `static_assert` (`DSTORAGE_REQUEST` 72 bytes, `DSTORAGE_QUEUE_DESC` 24, `DSTORAGE_QUEUE_DESC1` 32); `DSTORAGE_REQUEST_OPTIONS` is decoded from `AsUINT64` by explicit bit positions (zlib bit 0, BCPack 1-4, swizzle 5-20, destination pages 21, source type 22, source pages 23, reserved 24-63) | high for member order and types, medium for the bit allocation (MSVC allocates bit-fields from bit 0 up) | `dstorage_xs_abi.h` | - -The first boot with the executable settles most of this: the dry-run report shows which module it imports -`DStorageGetFactory` from, and the log lines give the interface ids. - -## What the shim does - -- **Factory**: one object for the process, never freed (its reference count does not drop below one). - `SetDebugFlags` and `SetCpuAffinity` are stored only (a console core mask means nothing on the host). - `SetStagingBufferSize` accepts 0, 16, 20, 24, 28 and 32 MiB, fails with `E_DSTORAGE_INVALID_STAGING_BUFFER_SIZE` - otherwise and with `E_DSTORAGE_STAGING_BUFFER_LOCKED` while a queue or file exists; there is no staging buffer. - `GetStats` reports the counts the shim keeps (queues per priority, requests, bytes, files, errors, zlib - inflates: `TotalDecompressionRequestCount` grows when a zlib request's inflate starts, which is after its checks - passed and its source was read, `PendingDecompressionRequestCount` is the inflates running, and - `DecompressionErrors` the streams that failed). As - `DSTORAGE_PRIORITY_STATS` defines them, `TotalRequestCount` and the byte totals grow when a request is submitted - (not when it is enqueued), and `PendingRequestCount` counts the requests the worker is processing; status and fence - entries are counted when they are enqueued. A bad - argument (a null pointer, an invalid queue desc or staging size) is logged once per method and kind, so a wrong - vtable guess shows up in the log as arguments that make no sense for the method. -- **Files**: `OpenFile` goes through the registry's `kernel32.dll!CreateFileW`, the shim in `file_system.cpp`, so a - `GAME:` path reads the overlay copy first, then the package, and a path that climbs out is refused (a host path is - passed through). Read access, `FILE_SHARE_READ`, as the overview says; a failed open returns the Win32 error as an - HRESULT. `GetHandle` returns a handle of its own (`ReOpenFile`, read access, `FILE_SHARE_READ`) that the caller - closes; it has its own file position, which the shim's reads do not move. `Close` waits for the submitted requests - that read the file; a request processed after it fails with `E_DSTORAGE_FILE_NOT_OPEN`. A request holds a reference - on its file, so the last `Release` cannot close a file a request still reads. -- **Queues**: capacity `0x80`..`0x2000`, priority `LOW`..`REALTIME`, a memory-sourced queue must be `REALTIME` - (`E_DSTORAGE_INVALID_QUEUE_CAPACITY`, `_INVALID_QUEUE_PRIORITY`, `_INVALID_MEMORY_QUEUE_PRIORITY`). A queue - holds `capacity - 1` entries; `Query` reports the empty slots and the entries left before the automatic submit, - which happens when the entries enqueued since the last submit reach half the capacity (unless - `DSTORAGE_QUEUE_OPTIONS::AutoSubmitDisabled`). An enqueue into a full queue waits for space, as the reference - says; with auto-submit disabled only a `Submit` from another thread frees it. One worker thread per queue runs - the submitted entries in order, so every notification follows all the entries before it. -- **Requests**: copied at enqueue. A file request reads `SourceSize` bytes at `FileOffset` into `Destination`; a - memory request copies `Source` to `Destination` (`memmove`, so an overlapping pair is safe); a zlib request - inflates those `SourceSize` bytes into `Destination` (below). Checked in this order when the worker reaches the - request: - 1. cancelled: a success, whatever else is wrong with it; - 2. found at enqueue: a null request pointer (`E_INVALIDARG`) or a file object the shim did not make - (`E_DSTORAGE_INVALID_FILE_HANDLE`); - 3. reserved option bits (`E_DSTORAGE_RESERVED_FIELDS`), then the source type against the queue's - (`E_DSTORAGE_INVALID_SOURCE_TYPE`); - 4. BCPack mode above 7, swizzle mode above 4 (`_INVALID_BCPACK_MODE`, `_INVALID_SWIZZLE_MODE`), then BCPack or - swizzle, with or without zlib, then physical pages (`E_NOTIMPL`, logged once: later PRs); - 5. an `IntermediateSize` (`_INVALID_INTERMEDIATE_SIZE`: it is the size between the inflate and the BCPack decode, - so only a zlib + BCPack request has one), a `DestinationSize` other than `SourceSize` without zlib, or not - larger than `SourceSize` with it (`_INVALID_DESTINATION_SIZE`: the rule `dstorageerr.h` gives for that code, - and what `DSTORAGE_REQUEST` says of `DestinationSize`), more than 1 GiB in total, then a buffer over 32 MiB - (`_REQUEST_TOO_LARGE` for both: `DSTORAGE_REQUEST` allows a buffer over 32 MiB only with 64 KiB or 2 MiB pages, - which are not implemented yet; the source is never larger than the destination here, so the destination's - limit covers it), then a zlib file request whose `FileOffset` is not 16-byte aligned (`_INVALID_FILE_OFFSET`, - as `DSTORAGE_REQUEST` requires); - 6. a null destination, a null source (memory) or a null file (`E_INVALIDARG`), a closed file (`_FILE_NOT_OPEN`); - 7. a zero size: a success that touches no memory (an assumption: the reference does not say); - 8. a range past the end of the file (`E_DSTORAGE_END_OF_FILE`), then a destination or source the process cannot - access (`E_DSTORAGE_ACCESS_VIOLATION`; the worker survives it). This needs asynchronous exceptions under - clang-cl, so `runtime/cmake/windows_runtime.cmake` builds `dstorage.cpp` with `/EHa` there; MSVC always catches it. - - Step 7 does not apply to a zlib request (its `DestinationSize` is never 0 after step 5); its stream fails as - described next. -- **zlib** (`ZlibDecompress` alone): the source, `SourceSize` bytes of the file or of memory, is read into a staging - buffer and inflated there by the runtime's RFC 1950 inflater (`leonida::zlib_inflate` in - `runtime/src/shader_library.h`, the one the shader library uses for XBCH blobs). The result is copied to - `Destination` only when it is exactly `DestinationSize` bytes, so a stream that fails leaves the destination as it - was, and a memory source inside its own destination (in-place loading) inflates correctly. Both buffers are at - most 32 MiB (step 5). Step 5 also means a stream of stored blocks only, which is larger than what it holds, is - refused with `_INVALID_DESTINATION_SIZE` before it is read, as the documented rule implies. The stream is a zlib - stream: the two header bytes, the deflate blocks (stored, fixed and - dynamic Huffman), the Adler-32 of the result. Bytes after the Adler-32 are not read, so a `SourceSize` rounded up - over padding works (an assumption: the reference does not say). The game's own data agrees with RFC 1950: the - texture pools' codec-8 chunks, laid out for this decompression ([textures.md](textures.md)), inflate with - Python's `zlib.decompress`, which checks the header and the Adler-32 (`tools/ttpf_mips.py`). A failure: - - | Stream | HRESULT | - |---|---| - | header not deflate, a window over 32 KiB, a wrong check value, or a preset dictionary | `E_DSTORAGE_ZLIB_BAD_HEADER` (`0x89240031`) | - | a reserved block type, an invalid code, a distance before the start, or a truncated stream | `E_DSTORAGE_ZLIB_BAD_DATA` (`0x89240032`) | - | Adler-32 mismatch | `E_DSTORAGE_ZLIB_PARITY_FAIL` (`0x89240033`) | - | inflates to more or fewer bytes than `DestinationSize` | `E_DSTORAGE_DECOMPRESSION_ERROR` (`0x89240030`; no code names a size mismatch, so the generic one) | - - The inflater decodes one bit at a time, on the queue's worker: correct, not fast. A faster decoder (table lookup) - can replace it behind `zlib_inflate` without touching the request path. -- **Cancel**: `CancelRequestsWithTag(mask, value)` marks every request enqueued before the call and not yet started - whose `(CancellationTag & mask) == value`. A cancelled request completes as a success without reading and is not - counted as a failure, as the overview and the reference say, even when it also had an error found at enqueue. -- **Notifications**: `EnqueueStatus` sets the entry to `E_PENDING` at once and, when reached, to the first failure - since the previous status or signal (else `S_OK`); `IsComplete` is `GetHResult != E_PENDING`; an index past the - array is `E_DSTORAGE_INDEX_BOUND`, a foreign or null array `E_DSTORAGE_INVALID_STATUS_ARRAY`. `EnqueueSignal` calls - `ID3D12Fence::Signal` (PC slot 10, which the `d3d12_xs` fence proxies forward) on the worker thread; a null fence is - `E_DSTORAGE_INVALID_FENCE`. `EnqueueSetEvent` duplicates the handle at once and sets the duplicate, then closes it, - so an event the title closes in the meantime (and a handle value reused for another object) is never the one set; a - null or invalid handle is recorded as a failure. Each notification holds a reference on its array or fence until it - has run. -- **Errors**: a failure goes into the status entry, the queue's error record (failure count and the first failure - since the last `RetrieveErrorRecord`, with the file name the title opened) and sets the error event. - `GetErrorEvent` returns a duplicate handle (the reference says the caller closes it). `RetrieveErrorRecord` - clears the record and resets the event; with nothing recorded it returns `DSTORAGE_COMMAND_TYPE_NONE`. A failed - `SetEvent` is recorded with command type 3 (the PC API's `EVENT`; the console enum stops at 2). -- **Close and release**: `Close` submits what is enqueued, waits until the worker has run it all and stops the - worker; later enqueues are dropped and recorded as `E_DSTORAGE_QUEUE_CLOSED`. The last `Release` closes the same - way, so a queue released with requests in flight finishes them first. - -## Not done yet (later PRs) - -- **BCPack** (`BcpackMode`; `tools/bcpack.py` is the reference decoder), then **swizzle** (`SwizzleMode`). The - decode order is DEFLATE, BCPack, swizzle; with both zlib and BCPack `IntermediateSize` is the size between them - (the inflate's output, the BCPack decoder's input), and `FileOffset` must be 16-byte aligned. Each becomes a stage - after `inflate_request`'s inflate and before its destination write, so the request checks above stay where they - are. -- **Physical pages** (`SourceIsPhysicalPages`, `DestinationIsPhysicalPages`): arrays of 64 KiB page numbers from - `XMemAllocatePhysicalPages`; needs the `xmem` shim to translate a page number to the address it mapped. -- **GPU memory**: the console API has no GPU destinations of its own (memory is unified, so a destination is an - address). An address inside memory the Vulkan layer backs will need its write routed to that memory. The destination - is written in two places, both in `execute_request` (`read_file_range` for a file source, `guarded_move` for a - memory source), so that change stays inside the request path. -- **Parallel reads**: the worker reads one request at a time. Overlapped reads with in-order retirement of - notifications would keep the order guarantee. - -## Tests - -`runtime/test/dstorage_test.cpp` (ctest `dstorage`) runs on synthetic files in `%TEMP%` through the registry entries -under all three module names: `GAME:` reads with an overlay copy winning, offsets, zero size, a range past the end, -cancellation, auto-submit, a full queue, status arrays, fences (a CPU fence object that checks the data is in place -when it is signalled), events, error records, file and queue close with requests in flight, a destination the -process cannot write, four threads enqueueing at once, the interface-id policy (unknown and system ids refused by -`QueryInterface`, learned by creating calls), a `GetHandle` handle with its own file position, an event closed (and -its handle value reused) before it is set, and cancelled requests that also had an enqueue error. zlib requests use -synthetic streams only: two made with Python's `zlib` (level 9: one dynamic-Huffman block; level 1: one -fixed-Huffman block) from text the test rebuilds, and stored-block streams the test builds, one of them a stored -block followed by the dynamic one. They are read from a file and from memory (also in place); a bad header, a -preset dictionary, a reserved block type, a truncated stream, an Adler-32 mismatch, a stream shorter and one longer -than `DestinationSize`, a stored stream larger than its result, an unaligned offset, an `IntermediateSize`, zlib with -BCPack or swizzle (`E_NOTIMPL`), an unreadable source and an unwritable destination each get their code, a failed -stream leaves its destination untouched, and the decompression statistics count them. - -## Sources and licences - -| Source | Facts used | Licence / use | -|---|---|---| -| [GDK DStorage reference](https://learn.microsoft.com/en-us/gaming/gdk/docs/reference/system/dstorage/dstorage_members) and its function, interface, structure and enumeration pages | Names, method signatures, structure members, enum values, requirements rows | [Microsoft Learn Terms of Use](https://learn.microsoft.com/en-us/legal/termsofuse); facts paraphrased, no text copied | -| [DirectStorage overview (GDK)](https://learn.microsoft.com/en-us/gaming/gdk/docs/features/console/storage/directstorage/directstorage-overview) | Queue, auto-submit, cancellation, notification order, file sharing, decode order | Same terms; paraphrased | -| `dstorage.h`, `dstorageerr.h` in the public `Microsoft.Direct3D.DirectStorage` 1.3.0 NuGet package | PC method order, interface ids (to refuse them), capacity and name-length constants, `E_DSTORAGE_*` values | Read for facts only; not vendored. `runtime/shims/dstorage_xs_abi.h` is Leonida's own declaration | -| [DirectStorage constants](https://learn.microsoft.com/en-us/windows/win32/dstorage/dstorage-constants) (Win32 reference) | `E_DSTORAGE_DECOMPRESSION_ERROR` = `0x89240030`; `E_DSTORAGE_INVALID_DESTINATION_SIZE`: equal to the length without decompression, larger with it; `E_DSTORAGE_INVALID_FILE_OFFSET` is the offset invalid for a decompression mode | [Microsoft Learn Terms of Use](https://learn.microsoft.com/en-us/legal/termsofuse); paraphrased | -| [`direct-storage` crate](https://docs.rs/direct-storage/0.5.1/src/direct_storage/bindings.rs.html) 0.5.1 (bindings generated by `windows-bindgen` from the DirectStorage headers; 0.2.0's `errors.rs` has the same values) | `E_DSTORAGE_ZLIB_BAD_HEADER` `0x89240031`, `E_DSTORAGE_ZLIB_BAD_DATA` `0x89240032`, `E_DSTORAGE_ZLIB_PARITY_FAIL` `0x89240033` (names and values only) | MIT/Apache-2.0; two constants' names and values, no code copied | -| [RFC 1950](https://www.rfc-editor.org/rfc/rfc1950) and [RFC 1951](https://www.rfc-editor.org/rfc/rfc1951) | The zlib stream and DEFLATE formats `zlib_inflate` decodes | Public specifications | diff --git a/docs/embedded_shaders.md b/docs/embedded_shaders.md deleted file mode 100644 index ed3a254d7..000000000 --- a/docs/embedded_shaders.md +++ /dev/null @@ -1,395 +0,0 @@ -# Shader containers embedded in the package's DLLs - -**Status: measured** on the 1.0.2.1 package. This note covers the shader programs that ship outside -`shaders.rpf`: the DXBC containers inside the package's DLLs, what each one carries, and what the measurement -changes for the ray-tracing and upscaling paths. No container, shader or payload is reproduced here; the tables -hold counts, offsets, chunk names and module identifiers. - -## 1. Why they matter - -`tools/shader_carve.py` carves `shaders.rpf` only. Two DLLs in the same package carry compute programs of their -own, and `make_game.py`'s `shaders` stage translates both sets after the game's shaders (section 7 for the -builder, [fspx.md](fspx.md) for FidelityFX): - -* `XboxBvhBuilder.dll`, Microsoft's XDXR acceleration-structure builder. Its constructor creates compute PSOs - through device slot 62, and the builder is on the critical path for ray tracing. -* `amd_fidelityfx_upscaler_xbox.dll`, the FidelityFX 4.1.1 upscaler. Its programs are the `ACCC`/`FSPX` format - covered in [fspx.md](fspx.md); this note only counts them. - -`tools/pe_shader_containers.py` scans a binary for DXBC containers, validates the chunk table, reads the `ILDN` -module name and reports what each container carries. `--extract` writes the containers and an `index.json` the -translator reads; extracted shaders are game data and must stay in the user's work folder. - -```sh -python -I tools/pe_shader_containers.py --json /containers.json --extract /embedded/dxbc -``` - -## 2. Inventory - -The 16 DLLs and the package's root files were scanned first (`XboxBvhBuilder.dll` and `amd_fidelityfx_upscaler_xbox.dll`); `game_scarlett_master.exe` (RT-5) adds 10 more console containers: - -| image | containers | bytes | min / median / max | chunks | -|---|---:|---:|---:|---| -| `XboxBvhBuilder.dll` | 52 | 674,404 | 4,072 / 7,454 / 74,508 | `SFI0 ISG1 OSG1 PSV0 RTS0 STAT ILDN HASH DXIL` | -| `amd_fidelityfx_upscaler_xbox.dll` | 29 | 289,656 | 1,764 / 5,176 / 42,616 | `SFI0 ISG1 OSG1 PSV0 RTS0 HASH ACCC` | -| other 14 DLLs | 0 | 0 | — | — | -| `game_scarlett_master.exe` | 10 | 9,520 | 924 / 936 / 992 | `SFI0 ISG1 OSG1 PSV0 HASH DXIL PRIV` | - -The 29 `ACCC` containers hold `FSPX` payloads ([fspx.md](fspx.md)); the 52 `DXIL` containers are the subject of -this note. The FSR DLL has one rejected `DXBC` hit: the bytes are an immediate in its own magic check, and the -validator rejects it (the scan reports both counts). - -### Retail executable (`game_scarlett_master.exe`, RT-5) - -Scanning the retail executable (120,181,760 bytes, SHA-256 `e95020b2fa4a721db3df59fdecf75621730ac559d8835252f6c3b658d5a08993`) -with `tools/pe_shader_containers.py` finds **10** valid DXBC containers (9,520 bytes total, file offsets -`0x688cd3c`..`0x688fdf6`, sizes 924–992 bytes) and 1 rejected `DXBC` hit: - -* **Stages (`PSV0`):** **1** vertex shader (`0x688cd3c`, 992 bytes) and **9** pixel shaders (924–980 bytes). Unlike the - DLL containers above, none carries `ILDN`, `STAT`, `RTS0`, or LLVM bitcode (`has_bitcode = false`). All 10 carry - console-only `XBCH` (`XDAT` tag `0x0d`, 307–368 bytes) and `NOBC` (tag `0x07`, 28 bytes), plus a 12-byte `PRIV` chunk. -* **Translation and GPU check:** `tools/pe_shader_containers.py --extract` previously hardcoded `"stage": "cs"` in - `index.json`, causing `rdna2spirv.py` to reject all 10 with `CS group size`. With `stage` read from `PSV0`, all 10 - unpack via `tools/fssm_unpack.py` (10/10 `FSSM`, 1,245–4,176 bytes), disassemble cleanly via `tools/shader_disasm.py --backend python` - (10/10 clean), translate via `tools/rdna2spirv.py` (10/10 translated, all wave64 tier A), and pass `vk_pipeline_check` - on an NVIDIA GeForce RTX 5060 Laptop GPU (driver `617.14`, Windows 11): **10/10 modules and 10/10 pipelines OK** (1 VS, 9 PS, 0 failed, 0 skipped). - -**Every one of the 52 containers carries two representations of its program:** - -* an LLVM bitcode blob in the `DXIL` chunk (`BC C0 DE`, 1,820 to 70,276 bytes), and -* an `XDAT` directory with tag `0x0d` whose payload starts with `XBCH`: the console program. The same chunk also - holds tag `0x07` (a second `DXIL` program header) and tag `0x12` (a 16-byte hash). The `STAT` chunk holds a - second, different bitcode blob, not the same one. - -### `STAT` and the `0x07` program header - -Measured over all 52 builder containers in one local 1.0.2.1 package; no shader data is included here. The -bitcode spans below use the `DxilProgramHeader`/`DxilBitcodeHeader` offsets and sizes defined by -[DirectXShaderCompiler](https://github.com/microsoft/DirectXShaderCompiler/blob/main/include/dxc/DxilContainer/DxilContainer.h). -All spans fit inside their enclosing parts, and all 104 `STAT` and outer `DXIL` bitcode modules were accepted by -`llvm-dis` 21.1.8. The header's size-in-dwords equals its enclosing part or record length in every case. - -* **`STAT`:** 52/52 contain a `DXIL` program header and a bitcode module distinct from the outer `DXIL` bitcode. - All have `dx.entryPoints` and `dx.resources` metadata, and none defines a function in the `llvm-dis` output; - the outer modules define functions. DirectXShaderCompiler calls this the shader-statistics part and uses a valid - `STAT` module for reflection (see its - [container reflection implementation](https://github.com/microsoft/DirectXShaderCompiler/blob/main/lib/HLSL/DxilContainerReflection.cpp)). - The metadata-only shape is consistent with that role; the builder's actual consumption of `STAT` is not measured. -* **XDAT tag `0x07`:** 52/52 contain a `DXIL` program header whose declared bitcode is byte-identical to that of - the outer `DXIL` part. None contains the `NOBC` marker. The whole `0x07` record is not the same as the whole - outer part, which also contains `XDAT`. This differs from the `NOBC` form documented for the game's shader - corpus in [fssm_crosscheck.md](fssm_crosscheck.md); it does not change that separate measurement. - -The bitcode is what a PC D3D12 compiler consumes; the runtime path is the `XBCH` record. The constructor passes -the **whole container** to the compute-PSO call: at `0x180021330` it loads `DAT_180025700` with size `0x1134` -(4,404 bytes, the size of container 0, `CopyAndCompactBVH`) and calls `FUN_18000c470`, whose vtable call at -`+0x1f0` (slot 62) receives that pointer, its size and two zero words. `FUN_18001d400` creates the -`XDXR GetBVHCompactedSize` PSO (0x14a4 bytes; measured below). `bvh_builder_test` measures **53** PSO -creations during construction over the **52** containers ([d3d12_vulkan.md](d3d12_vulkan.md) A.2), so one -container is created twice. It is **`GetBVHCompactedSize`** (5,284 bytes = 0x14a4): creations **#47 and #53** pass -byte-identical containers (RT-182, `LEONIDA_BVH_RECORD62=1`, which now prints each creation's module from its `ILDN` -part and says when a container repeats). The test now also prints each creation's call site and the name the builder -gives the returned PSO (RT-266, WARP, default constructor flag): the builder names every one of the 53 PSOs with -`SetName`, `XDXR ` (for example `XDXR InitPartitionedHeaders`; some modules are shortened, as -`XDXR CopyAndCompact`, or numbered, as `XDXR CalculateMortonCodes 0`/`1`). **#47 and #53 both get `XDXR -GetBVHCompactedSize`**, from the same call site in `FUN_18001d400` (return address `+0x1d503`, called through -`FUN_18000c470` at `+0xc4e4`); `FUN_18001d400` is called twice, once from `FUN_18000d850` (#47) and once from -`FUN_180021330` directly (#53). So the repeat is one PSO created twice under one name, not one container under two -names, and no creation is named `XDXR PostBuildInfoQuery` in this run (default flag, WARP; the flag-true -constructor was not run). The creation order, by module (it is not the table -order of section 3; `CopyAndCompactBVH` is #52, not the first): - -| creations | modules, in the order of the `CreateComputePipelineState` calls | -|---|---| -| #1-#13 | `InitPartitionedHeaders`, `PT_WriteOfflinePartition`, `PT_WritePartitions`, `PT_WriteInstances`, `PT_LoadInstances`, `PT_BeginPass`, `ResetCounterValues`, `InitHeaders`, `CopyForBVHUpdate`, `ResetToIndexBuffer`, `CopyCounters`, `CalculateMortonCodes`, `CalculateMortonCodes64` | -| #14-#29 | `BitonicPreSortCS`, `BitonicOuterSortCS`, `BitonicInnerSortCS`, `BitonicPreSort64CS`, `BitonicOuterSort64CS`, `BitonicInnerSort64CS`, `RadixReset`, `RadixCount`, `PrefixSum64`, `PrefixSum128`, `PrefixSum256`, `PrefixSum512`, `PrefixSum1024`, `PrefixSum2048`, `PrefixSum4096`, `RadixAlloc` | -| #30-#46 | `RearrangeTriangles`, `RearrangeBVHs`, `LoadInstances`, `SplitInstances`, `LoadTriangles`, `LoadProceduralGeometry`, `ReloadTriangles`, `ReloadProcedurals`, `PT_ConstructBVH4`, `ConstructBVH4`, `RefitBVH4`, `BuildBVHSplits`, `BuildBVHSplits64`, `FindTreelets`, `ResetKDOP`, `BuildKDOP`, `BuildApexPointMap` | -| #47-#53 | `GetBVHCompactedSize`, `DecompressHeader`, `LeafRehydration`, `Box16Rehydration`, `Box32Rehydration`, `CopyAndCompactBVH`, `GetBVHCompactedSize` (again) | - -The test also prints each creation's container with its `ILDN` module name and the first bytes of its digest -(RT-182): creations 1 to 51 are 51 distinct containers, `GetBVHCompactedSize` (5,284 bytes, 0x14a4) among them at 47; -creation 52 is `CopyAndCompactBVH` (4,404 bytes, 0x1134); creation 53 is `GetBVHCompactedSize` again, with the -same digest and size. So the 0x14a4-byte container `FUN_18001d400` passes is the `GetBVHCompactedSize` module, and -the PSO for it is created twice (under one name, `XDXR GetBVHCompactedSize`, per the SetName record above). Measured on 1.0.2.1 with an RTX 5080 (driver -621.01): all 53 creations return `S_OK`. - -## 3. The 52 modules - -The `ILDN` PDB path gives one module per container, all under -`X:\americas\src\dev\rage\3rdparty\Microsoft\XboxBvhBuilder\Build\Release\Output\XboxBvhBuilder\` (Microsoft's -component integrated into RAGE, not Rockstar shader code). Grouped by phase: - -| phase | modules | -|---|---| -| sort (11) | `BitonicPreSortCS`, `BitonicPreSort64CS`, `BitonicInnerSortCS`, `BitonicInnerSort64CS`, `BitonicOuterSortCS`, `BitonicOuterSort64CS`, `RadixCount`, `RadixAlloc`, `RadixReset`, `CalculateMortonCodes`, `CalculateMortonCodes64` | -| prefix (7) | `PrefixSum64`, `PrefixSum128`, `PrefixSum256`, `PrefixSum512`, `PrefixSum1024`, `PrefixSum2048`, `PrefixSum4096` | -| kdop (3) | `BuildKDOP`, `ResetKDOP`, `BuildApexPointMap` | -| build (7) | `ConstructBVH4`, `BuildBVHSplits`, `BuildBVHSplits64`, `SplitInstances`, `FindTreelets`, `RearrangeBVHs`, `RearrangeTriangles` | -| refit (2) | `RefitBVH4`, `CopyForBVHUpdate` | -| load (6) | `LoadTriangles`, `ReloadTriangles`, `LoadInstances`, `LoadProceduralGeometry`, `ReloadProcedurals`, `ResetToIndexBuffer` | -| path tracing (6) | `PT_ConstructBVH4`, `PT_BeginPass`, `PT_LoadInstances`, `PT_WriteInstances`, `PT_WritePartitions`, `PT_WriteOfflinePartition` | -| rehydration (3) | `Box16Rehydration`, `Box32Rehydration`, `LeafRehydration` | -| headers/util (7) | `DecompressHeader`, `InitHeaders`, `InitPartitionedHeaders`, `GetBVHCompactedSize`, `CopyCounters`, `ResetCounterValues`, `CopyAndCompactBVH` | - -## 4. They are console FSSM, and the existing translator already takes them - -The `XBCH` record has the same shape as the game's own shaders: `XBCH` + stored/unpacked sizes + a zlib stream -that expands to `FSSM` ([fssm_crosscheck.md](fssm_crosscheck.md)). On all 52 containers: - -| step | result | -|---|---| -| `tools/fssm_unpack.py` | **52/52** decompress to a valid `FSSM` blob (716 B to 101,320 B, median 2,200 B) | -| `tools/shader_disasm.py --mcpu gfx1013` | **52/52** disassemble; 42 with no invalid word, 10 with invalid words in the code | -| `tools/rdna2spirv.py` | **51** translate and pass `spirv-val` (`main` `49475796`) | - -When this page was first written, 42 translated and 10 stopped at four rules. Three of those rules have landed since -(`427c1376`, from #1968), and one program still waits on a fifth rule: - -| module(s) | blocker then | now | -|---|---|---| -| `BuildKDOP`, `LoadInstances`, `ReloadProcedurals`, `LoadProceduralGeometry`, `LoadTriangles` | `global_atomic_fmax` | translate | -| `PT_LoadInstances` | `global_atomic_fmin` | translates | -| `Box32Rehydration`, `ReloadTriangles` | `buffer_load_ushort` | translate | -| `LeafRehydration` | `tbuffer_load_format_x GFX10_FORMAT_8_UINT` | translates | -| `Box16Rehydration` | `buffer_load_ushort` | stops at `buffer_store_short` (#1864) | - -The disassembly count is unchanged: the same 42 programs have no invalid word, and 10 have invalid words in the -code. All 10 of those translate; `Box16Rehydration` is one of the 42 clean ones. - -On current `main`, 51 of the 52 programs translate and pass `spirv-val`. The four earlier blockers were -implemented in #1871 and #1968 (`427c1376`): - -* `tbuffer_load_format_x GFX10_FORMAT_8_UINT` (#1871) unblocked `LeafRehydration`. -* `global_atomic_fmax` (#1968) unblocked `BuildKDOP`, `LoadInstances`, `ReloadProcedurals`, `LoadProceduralGeometry`, and `LoadTriangles`. -* `global_atomic_fmin` (#1968) unblocked `PT_LoadInstances`. -* `buffer_load_ushort` (#1968) unblocked `Box32Rehydration`, `ReloadTriangles`, and the load half of `Box16Rehydration`. - -The single remaining untranslated program stops at one rule: - -| module(s) | blocker | -|---|---| -| `Box16Rehydration` | `buffer_store_short` (#1864) | - -Reproduction, after `--extract` above: - -```sh -python -I tools/fssm_unpack.py /embedded/dxbc -python -I tools/shader_disasm.py /embedded/dxbc/fssm --out /embedded/dxbc/disasm --mcpu gfx1013 -python -I tools/rdna2spirv.py /embedded/dxbc/disasm --out /embedded/spirv -``` - -`make_game.py` runs the same four tools as a build step (section 7). - -## 5. What this changes - -* **The RT builder does not need a DXIL path for the console code.** Its programs are RDNA2 `FSSM`, and 51 of - 52 already pass `spirv-val` with the translator the project uses for the game's 26,503 shaders. The bitcode in - the same container is a second representation (the one the PC-compiler experiment measured); it is not what - the console runtime executes. -* **The missing rules were small, and only one is left.** `global_atomic_fmax`/`fmin` (6 programs), - `buffer_load_ushort` (3) and `tbuffer_load_format_x` with format 8 (1) were ordinary translator rules, not a new - compiler backend, and they are on `main`. The one left is `buffer_store_short` (#1864), for `Box16Rehydration`. -* **The rehydration programs are the ones closest to the shipped data.** `Box16Rehydration`, - `Box32Rehydration` and `LeafRehydration` are exactly the programs that would turn the dehydrated BVH packs - into runtime trees ([bvh.md](bvh.md) §3.1). `LeafRehydration` translates since #1871, `Box32Rehydration` - translates since #1968 (`427c1376`), and only `Box16Rehydration` awaits #1864 (`buffer_store_short`). -* **What is still open.** None of the 52 has been executed on a GPU; translation and `spirv-val` do not prove the - output. Which of them the game actually creates is a call-site question (RT-5). The module-to-pipeline order - above comes from `ILDN`, not from a runtime trace. The `STAT` metadata-only shape is consistent with reflection, - but whether the builder consumes it has not been measured. -* **They run on a GPU (TEST-594).** `tools/bvh_gpu_smoke.py` translates them from the package and runs each through - `vk_compute_test`. Each program reads its root arguments from a table at `s[0:1]`, the heap base there, which the - tool seeds with `VKC_HEAP_INIT`: every table word points past the table into zeros. **All 49 that aren't - rehydration programs pass**: exit 0, no Khronos validation error, and the same heap bytes on a second run (AMD - Radeon RX 9070, Windows 11, `--max-shared-memory 32768`, package 1.0.2.1). With these inputs only seven change any - heap word (`InitHeaders`, `InitPartitionedHeaders`, `LoadInstances`, `LoadProceduralGeometry`, `LoadTriangles`, - `PT_BeginPass`, `PT_WriteInstances`); the others leave early. So this alone shows that the translated programs - run cleanly, not that their output is right. **Six are checked byte for byte** (`--checked`), the ones whose effect - reads straight off their code. `RadixReset`, `ResetKDOP`, `ResetToIndexBuffer`, `CopyCounters` and - `ResetCounterValues` get their root-table fields (an output address, a count of 20, a value or a source), and the - tool compares all 20 entries they write and the bytes after them, which must stay untouched. `PrefixSum64` scans 64 - words in place into their exclusive prefix sum through five `ds_swizzle_b32` broadcast steps and stores the group's - total; the input wraps past 2^32. All six match exactly. Negative controls: with the translator made to skip - `v_add_nc_u32`, `ResetToIndexBuffer` fails (entries hold `base+4i` and zeros); with it skipping `ds_swizzle_b32`, - `PrefixSum64` fails from element 2 on. So the check sees a wrong translation. Two things found on the way: - * the wave64 bitonic sorts (`BitonicPreSort64CS`, `BitonicInnerSort64CS`) declare 32,780 bytes of workgroup memory - with the translator's default cap, 12 over the 32 KiB AMD's Windows driver allows - (`VUID-RuntimeSpirv-Workgroup-06530`). Their highest LDS offset is 8192, and `--max-shared-memory 32768` shrinks - the array to what they use. That was before SHADER-579 moved the barrier-round counts into the LDS array: today - both declare 32,768 bytes with the default cap, and section 7 has what the cap still changes; - * with every table word 0 instead, the descriptors point at the table itself, and `RadixCount` then writes into the - table that other waves are reading, so its output differs between runs. That is the test input, not the - translator; the tool's default avoids it. -* **What is still open.** The other programs' outputs (the sorts, prefix sums, builders, refit and loaders) are not - checked against a reference yet; the rehydration trio has one in TEST-376 (`tools/bvh_rehydrate.py`); `LeafRehydration` does not finish within 60 s with either table described - above. Which of them the game actually creates is a call-site question (RT-5). The module-to-pipeline order - above comes from `ILDN`, not from a runtime trace. The `STAT` bitcode and the `0x07 NOBC` record are not - explained. - -## 6. Tool and tests - -`tools/bvh_gpu_smoke.py --game-dir [--max-shared-memory N] [--checked] [--json report.json]` reproduces the -GPU run above: the extraction and translation of §4, then two dispatches per program, and with `--checked` the six -byte-exact cases. Its report holds module names, statuses -and counts only. `tests/test_bvh_gpu_smoke.py` checks the heap image, the word count and the judging of runs with a -fake `vk_compute_test`, and the checked cases' inputs and judging (a fake that does what each case describes passes, -one wrong byte fails), without a GPU or game files. - -`tools/pe_shader_containers.py` is standard library only and reads the file, never runs it. It accepts a -container only when the chunk table is sorted, 4-byte aligned, entirely inside the declared total and its last -chunk ends exactly at that total; that is what rejects the FSR DLL's `DXBC` immediate. The synthetic tests in -`tests/test_pe_shader_containers.py` build containers by hand (no game data) and cover the accepted layout, a -bare magic, a truncated chunk, an `ACCC`/`FSPX` container, the `ILDN` name and the extraction index. - -## 7. Build step and run-time lookup - -**Build (D3D-557).** `make_game.py`'s `shaders` stage, after the game's own shaders and the FidelityFX step, runs -`bvh_shaders()` on the package's `XboxBvhBuilder.dll`. It is the recipe of section 4, with the extraction index -passed along so that each tool reads only what the one before it wrote: - -```sh -python -I tools/pe_shader_containers.py /XboxBvhBuilder.dll --extract /shaders/bvh -python -I tools/fssm_unpack.py /shaders/bvh --carve-index /shaders/bvh/index.json -python -I tools/shader_disasm.py /shaders/bvh/fssm --unpack-index /shaders/bvh/fssm_index.json --out /shaders/bvh/disasm --mcpu gfx1013 -python -I tools/rdna2spirv.py /shaders/bvh/disasm --out /shaders/spirv/bvh --no-asm --max-shared-memory 32768 -``` - -The last line also gets `--wave64-emulate` and the fallback flags of the build, like the game's shaders. - -* **The key is the game shaders' key.** The programs are `FSSM` (section 4), so each index entry gets - `fssm_sha256`, the SHA-256 of the blob `fssm_unpack.py` inflates from the container's `XBCH` record. That is what - the runtime computes from the container the DLL passes to slot 62, as it does for a shader of `shaders.rpf`. No - second key or name table was added. The 52 blobs are 52 different programs, and none of them is in a translated - 1.0.2.1 corpus of `shaders.rpf` (0 of 52 hashes among its 26,501 index entries), so the two indexes do not meet; - if a program were in both, both entries would be candidates, the game's first. -* **One folder, redone as a whole.** The step is reused only when both indexes, every module the translation index - names and a matching `bvh_build.json` (written last) are there. It runs again when the DLL, one of the three - tools before the translator, the translator, `llvm-mc`, the wave64 mode, the flags or the memory cap change, and - it never makes the game's shaders translate again. Before it runs, it removes the containers, blobs, listings and modules of the run before: - `pe_shader_containers.py` never overwrites a container, so a second extraction into the same folder would write - `_NN.dxbc` beside the first and those would be translated as more programs. A package without the DLL - skips the step. -* **A program without a rule is reported, not skipped.** There is no skip list. After the translation the step - compares the extraction index with the translation index and logs the counts and the name of every program the - runtime cannot find (no entry with an `fssm_sha256`, which includes an entry whose metadata failed). It logs them - on every run, also when the step is reused. Today that is one line: 51 of 52, `Box16Rehydration` - (`buffer_store_short`, #1864). The other 51 are published. When no program translates the step fails and keeps - no index. -* **`--max-shared-memory 32768`.** The constructor creates a pipeline for every program and throws at the first - failure, and the runtime refuses a module over the device's `maxComputeSharedMemorySize` (`E_NOTIMPL`, - [design.md](design.md), "Workgroup memory limit"). 32,768 is what the AMD Windows and Intel drivers report. - Measured on `main` `3faac557`, by `lds_bytes` and by comparing the modules byte for byte: - - | translation | default cap (65,536) | `--max-shared-memory 32768` | - |---|---|---| - | native | largest 32,768 B (`BitonicPreSort64CS`, `BitonicInnerSort64CS`, `RadixAlloc`), none over | all 51 modules identical | - | `--wave64-emulate` | `RadixAlloc` 37,084 B, the others at most 32,768 B | `RadixAlloc` 22,236 B, the other 50 modules identical | - - So the cap changes one module, and only in an emulated build; the same 51 programs translate with and without - it. Without it that build stops on a 32,768-byte device at creation #29: measured on the Radeon below with the - emulated modules made at the default cap, `RadixAlloc` is refused (`declares 37084 bytes of workgroup memory`, - `0x80004001`) after 28 creations. - -**Run time.** `ShaderLibrary::load(dir)` (`runtime/src/shader_library.h`) reads `/index.json`, then -`/fspx/index.json` and `/bvh/index.json` when they are there. The builder's entries are named -`bvh/`, the path of their module below ``, and go into the table of the game's shaders, so -`create_compute` finds them through the lookup it already had (`compute_program()` gives an `FSSM` program, looked up -by `(cs, fssm_sha256)`). A missing or unreadable `bvh/index.json` leaves the other indexes loaded, and the main -index is still required. `bvh_size()` counts the entries, which `shader_library_corpus_test` leaves out of the -entries a carved container must reach, like the FSPX ones. - -**Measured: `LEONIDA_BVH_DEVICE=vulkan bvh_builder_test`** (package 1.0.2.1, `LEONIDA_BVH_RECORD62=1`, -`LEONIDA_SHADERS` on a folder holding this step's output and an empty main index, since only this step was run). -Before the step, on `main` `3faac557`, creation #1 failed on both GPUs: `0x80004005` with no library, `0x80070057` -with a translated corpus of 26,521 entries, none of them the builder's. - -| GPU | translation | result | -|---|---|---| -| RTX 3070, NVIDIA 610.74 (subgroups 32..32, limit 49,152) | `--wave64-emulate` | 49 of 50 creations `S_OK`; #50 `Box16Rehydration` has no module, `E_INVALIDARG`, and the constructor throws `0x80070057` | -| same | native | the same 49 of 50; the runtime warns that this device cannot require 64-wide subgroups | -| Radeon integrated (Ryzen 7 9700X), AMD 32.0.21042.62 (subgroups 32..64, limit 32,768) | `--wave64-emulate` | 49 of 50 `S_OK`, stops at #50 the same way | -| same | native | 49 of 50 `S_OK`, stops at #50 the same way. That is the translator of `main` `561b65a8`; with the one of `3faac557`, 48 creations returned `S_OK` and #49 `LeafRehydration` did not come back from the driver's pipeline compile in 16 minutes (below) | - -The rows above were measured before #1864 (`buffer_store_short`) was on `main`. With it (`main` `8575d36e`) the -step translates 52 of 52, and on the Radeon with the emulated modules all 53 creations return `S_OK` and -`bvh_builder_test` passes on the Vulkan device; the RTX 3070 and the native modules were not run again. - -Before that, with #1864's translator change applied to a local copy of the tools (not part of this step), 52 of 52 translate -and pass `spirv-val`, and with the emulated modules all 53 creations return `S_OK` on both GPUs: the constructor -and the destructor return and the test passes. So with the emulated modules the one thing between this step and a -constructed builder on the Vulkan device is `buffer_store_short`. The PC-device run of the test (WARP) is -unchanged: 53 of 53. - -**`LeafRehydration` on the AMD driver (SHADER-995).** The step was first measured with the translator of `main` -`3faac557`. `vk_pipeline_check` then created the same pipelines without the D3D12 layer: all 51 on the RTX 3070 -(native and emulated) and on the Radeon (emulated), and on the Radeon with the native modules 50 of 51, while -`LeafRehydration`, a 1.66 MB wave64 module, was still compiling when the check was stopped after 15 minutes. Its -emulated module was created in 12 s on that driver, and its native module in 11 s on the RTX 3070. - -The stop was that driver's compile time for the control-flow form of one module, not the lookup, native wave64 or -the module's size. The translator of `3faac557` emitted a structured tree deeper than 16 in the dispatch-loop form -(SHADER-299: one loop around an `OpSwitch` with a case per basic block), and this program's tree nests 18 deep -(`ReloadTriangles`' 17; found by lowering `--max-structured-depth` until the form changes). Since SHADER-427 the -bound is 64, so with `main` `561b65a8` all 51 native modules are structured (47) or barrier rounds (4), the native -row of the table above is that translation, and `vk_pipeline_check` creates all 51 native pipelines on the Radeon -(18.4 s on one thread, `LoadInstances` 8.6 s the slowest; the 51 emulated ones 26.9 s, `LeafRehydration` 11.6 s the -slowest). No build option is involved, and the step needed no change. @Jadiac5 measured the same translation on an -RX 9070 XT (RDNA4, AMD 32.0.32029.2010): 51 of 51 native and 51 of 51 emulated, the slowest module in 19 to 35 s -([their comment](https://github.com/ItsNotRexed/Leonida/pull/5680#issuecomment-7101091229)). Those are the -structured modules too, so the dispatch-loop module below has only been tried on the gfx1036 and the RTX 3070. - -Measured on the Radeon (gfx1036, AMD 32.0.21042.62) with `vk_pipeline_check --jobs 1`, one module in the driver at -a time beside the one long run. That driver keeps compiled shaders on disk and gives back a module it has seen in -0.2 s, so every time is the first compile of a module, or of a copy with another generator word in its header: - -| `LeafRehydration` module | size | shape | pipeline creation | -|---|---|---|---| -| dispatch loop, translator of `3faac557` | 1,658,968 B | 1,532 blocks: one loop around an `OpSwitch` with 581 cases | created after 2,039.5 s (34 minutes): 2,014 s of CPU time, one busy thread, the process at 1.2 GB after 5 minutes and 1.7 GB after 21. Slow, not hung | -| the same module, pipeline requiring 32-wide subgroups, or no size | | | not within 150 s either way | -| dispatch loop, current translator (`--dispatch-loop` or `--max-structured-depth 16`, the same bytes) | 1,192,148 B | 2,954 blocks, the same loop and switch | XXnot created within 10 minutes; the run was stopped there | -| structured, the default now | 1,238,360 B | 4,108 blocks, 1,763 selections, no loop, no switch | 2.9 s (3.6 s and 3.2 s for two more copies) | -| `--wave64-emulate`, translator of `3faac557` | 1,703,748 B | emulated wave64 structured | 12.6 s | -| `--wave64-emulate`, current translator | 1,358,436 B | emulated wave64 structured | 12.4 s | - -What the time depends on, tried on the current translator's dispatch-loop module with a limit of 45 to 150 s per -compile: - -* **Not the subgroup operations or the subgroup size.** All three native forms hold the same 590 - `OpGroupNonUniformAny` and no other subgroup operation. A copy with each of them replaced by an `OpLogicalOr` (a - compile-time probe, not an equivalent module) did not finish in 120 s, and neither did the first module with - 32-wide or no required subgroup size. -* **Not the size of the switch by itself.** The other programs compile in the dispatch-loop form on that driver, - 2.5 to 5 times slower than structured: `LoadInstances` (628 cases, 5.35 MB) in 40.3 s against 8.6 s, - `ReloadTriangles` (311) 3.6 s against 0.7 s, `ConstructBVH4` (206) 2.2 s against 0.6 s, `PT_ConstructBVH4` (186) - 1.9 s, `LoadTriangles` (185) 2.1 s, `SplitInstances` (153, 1.53 MB) 4.0 s against 1.2 s, `RefitBVH4` (125) 1.3 s, - `FindTreelets` (89) 0.9 s, and the wave64 `Box32Rehydration` (47) 0.5 s and `RadixAlloc` (17) 0.4 s. -* **It is how much of this program the loop reaches.** With only the first K of the 581 cases left in the - `OpSwitch` (the other blocks unreachable; a probe again): K = 64 0.8 s, 128 1.5 s, 256 3.6 s, 272 5.4 s, 280 - 23.1 s, 284 24.5 s, 286 43.5 s, 287 42.9 s, and 288, 320, 384 and 512 not within 60 to 90 s. So past case 272 a - few more blocks multiply the time. That looks like growth with the paths through the program rather than with - its size, which these numbers suggest and do not show. -* **Nothing done to the module from outside changed that.** `spirv-opt -O` (1,350,016 B) and the local SSA - rewrite with dead-code elimination (`--ssa-rewrite` after the two local eliminations and before - `--eliminate-dead-code-aggressive`, 1,120,512 B) validate and did not finish in 120 s; - `--eliminate-dead-branches --merge-blocks --cfg-cleanup` returns the module unchanged. Marking every load and - store of the dispatch variables `%pc` and `%done` `Volatile`, which keeps the module equivalent, did not finish in - 150 s either (whether that driver honours the flag was not checked). `-Os`, `--merge-return` and - `--scalar-replacement` were not run. - -So the AMD compiler's time on this module comes from the dispatch-loop form of this one program: of the eleven -tried it is the only one that is both large and without a loop of its own (its structured module has no -`OpLoopMerge`), which is an observation, not an explanation, and which of the driver's passes takes the time was -not looked into. The default translation does not emit that form for any of these 51 programs, so the step keeps -what `wave64_settings` chooses for this driver (native, #857) and makes no exception for the builder. A module can -still come out in the dispatch-loop form elsewhere (a graph `cfg_structure` cannot make reducible, a tree deeper -than the bound, `--dispatch-loop`); [testing.md](testing.md), "Known problems", has the row for that. - -Still open: nothing has dispatched one of these pipelines through the D3D12 layer, so this shows that the -constructor's pipelines are created, not that a build produces the right tree (section 5). - -`tests/test_bvh_shaders_stage.py` runs the step on a synthetic DLL (hand-built containers around a made-up `FSSM` -blob, no game data): the key the extracted layout gives the translator, the tools and arguments, reuse and each -reason to run again, a second run that leaves no duplicate containers, the report of an untranslated program on -every run and the failure when nothing translates. `shader_library_test` covers the `bvh/` index (found by the -container's program hash, counted apart, a broken or missing index beside the others) and `d3d12_compute_test` -creates a pipeline through slot 62 whose only translation is in `/bvh/index.json`. diff --git a/docs/first_light.md b/docs/first_light.md deleted file mode 100644 index 9eaff8f37..000000000 --- a/docs/first_light.md +++ /dev/null @@ -1,215 +0,0 @@ -# Drawing model UVs and textures with First Light - -**Status: measured** on the 1.0.2.1 package and an NVIDIA RTX 2060 SUPER (driver 620.73.04, Vulkan 1.4.357, -CachyOS). The untextured fixture draws a model from the package with a shader pair chosen to display its UVs. -With `--dds`, the default pixel shader samples the supplied texture at those UVs. Section 6 gives the textured -draw recipe. The image stays in the user's work folder. - -## 1. What was drawn - -The model is one static drawable exported from `data.rpf` by `rpf9dump models`: one mesh, 4,213 vertices and -7,968 triangles, with positions and UVs and no bones or fragments. Its OBJ is the only `data.rpf` export with -those counts and has SHA-256 -`a7178cf4b7a00c9df838fb072c59e2c048ceed52306620d859faae4d3991d6b9`; `manifest.json` records it. The tool that -assembles it, `tools/first_light.py`, centres and fits X/Y to NDC and flattens Z (the chosen VS applies no -matrix), so the draw is an orthographic projection of the model's own geometry. - -The untextured fixture uses two containers from `shaders.rpf`, carved and translated by the repository's tools. - -| stage | FSSM SHA-256 | what it does | -|---|---|---| -| VS | `128867d3233a97ba5b203c313a24ab8a77df20c2a308091a5595bb9f669677f4` | forwards POSITION and TEXCOORD from the vertex fetch to clip space and a varying | -| PS | `ed4147a5f7514947c2eb8d79255bd80f72761ac1ba2205dd811d3e050cf1b495` | writes the interpolated TEXCOORD as the colour; no bindings, no texture | - -The model's authored shader assignment can be checked separately. In the model export manifest for the OBJ -above, `MeshShaders[0]` selects material slot 0, the only slot. Looking up its `Materials[0].Shader` in the -native shader database yields one effect with one technique and four compute-only passes. The VS and PS -in the table are the fixture's chosen pair. The model's use during gameplay remains unverified. -See the [effect lookup tool](../tools/sgd5_effects.py) and the -[Windows reproduction of the UV draw](https://github.com/ItsNotRexed/Leonida/pull/2893#issuecomment-7084947193). - -Both disassemble with no invalid word, translate, and pass `spirv-val`; `tools/shader_link_check.py check` reports -the pair compatible. At 128×128 the draw covers **12,804 of 16,384 pixels (0.781)** and the centre pixel is -`(0.498, 0.496, 0.0, 1.0)`: the model is the disc its geometry projects to, and the colour is its own UV map. The -test derives the expected centre UV from the mesh on the CPU (`0.4978, 0.4965`), so the GPU pixel has to match -the geometry, not just be non-clear; it also requires the `[0, 0]` corner to keep the clear value and bounds the -coverage at 0.5–0.99, which an all-opaque image cannot pass. Four extra probes where U and V differ by more than -0.15 catch a swapped-U/V image even when the centre is symmetric (this model's centre has U ≈ V). The -`OracleTests` run those checks on synthetic images without a GPU or a package: the accepted fixture, an -all-opaque image, a swapped UV and a short buffer. The same `check_image` function backs the tool's `--check`, so -the command line and the test agree. The PPM the harness writes is a real image of the model; it stays in the -user's folder. - -## 2. Why it matters - -Until now the D3D12 draw tests (M1, M1.5, M2, M3) were met with hand-written RDNA2 or GLSL shaders and synthetic -geometry, and the pipeline check compiles the game's 26,503 shaders without ever drawing with one -([pipeline_check.md](pipeline_check.md)). This closes the "shaders of the game itself" gap for the native Vulkan -path: a real model, a real translated VS/PS pair, a vertex buffer, a pipeline and a readback, end to end, on a -consumer GPU. It does not need the executable and it does not use a synthetic stand-in for either side. - -The pieces it proves are the ones the D3D12 layer also relies on: ISG register → Vulkan vertex input location, -the 144-byte push-constant block, the translator's SPIR-V for a graphics pair, and `vk_harness`'s device, -pipeline and readback code. The same pair also draws through the port's D3D12 layer (section 5). - -## 3. Reproduce it - -```sh -git submodule update --init -dotnet build tools/rpf9dump/rpf9dump.csproj -c Release -DOTNET_ROLL_FORWARD=Major tools/rpf9dump/bin/Release/net8.0/rpf9dump models \ - "/data.rpf" ~/leonida-work/assets - -python -I tools/first_light.py --game "" --work ~/leonida-work --list -python -I tools/first_light.py --game "" --work ~/leonida-work \ - --obj ~/leonida-work/assets/data/models/.obj --no-fit --run -# .obj: 4,213 vertices, 7,968 triangles; the manifest records its SHA-256 -LEONIDA_FIRST_LIGHT_DIR=~/leonida-work/first_light/out python -I tests/test_first_light.py -v -python -I tools/first_light.py --check --out ~/leonida-work/first_light/out -``` - -`--check` on an existing folder re-runs the harness through the same fresh path and `check_image` as the test; a -harness that exits 0 without writing, an all-opaque image and a swapped-U/V image all exit 1. The test has -twenty-five cases: the two package-gated draw/manifest checks, the `--check` command, four oracle fixtures, the -mesh depth fit, a preview with non-finite readback channels, the stage files of two shaders with the same name, two -OBJ parsing checks, seven checks of the textured path (section 6) and six CPU checks of `--camera` (section 7). - -`first_light.py` carves `shaders.rpf` if the work folder does not have it, translates only the chosen pair, converts -the OBJ to the harness's mesh file (`u32 vertex_count, u32 index_count`, `(x,y,z,u,v) f32` vertices, `u32` -indices), writes `manifest.json` with the counts and FSSM hashes, and runs `vk_harness`. `--vs` and `--ps` take -other names from the carve index; `--no-fit` keeps a model that is already in NDC (the sky dome is). The test is -package-gated: without `LEONIDA_FIRST_LIGHT_DIR` it skips, and it writes its image to that folder. - -Each run stages its pair in `/first_light/dxbc` and translates it into `/first_light/spirv`. Both folders -are removed at the start of a run, so they hold that run's two shaders and nothing an earlier run selected; do not -keep files there. The output folder (`first_light/out` or `--out`) and `/shaders` are not emptied. If either -folder is a symlink or a junction, or a file in it cannot be removed, the run stops and names it. -With `--keep-z` or `--no-fit`, a triangle can cross the near or far clip plane. For the -passthrough VS, the CPU predicts a UV only where the interpolated depth is between 0 and 1, -inclusive. If several triangles cover a probe there, the last one drawn supplies its UV. - -## 4. The harness mode - -`runtime/test/vk_harness.cpp` gained two environment options, inert when unset (the existing three-vertex and -mesh-shader paths are unchanged): `VKH_DRAW_MESH=` with `VKH_VERTEX_LAYOUT=0:3f,1:2f` reads the binary mesh, -creates a vertex and an index buffer, and draws it with `vkCmdDrawIndexed`. The layout lists `location:components` -and only float attributes. The first-light pair above uses no other harness option: the VS reads no user SGPRs and -the PS has no bindings. - -## 5. Through the D3D12 layer - -`runtime/test/d3d12_first_light_test.cpp` (ctest `d3d12_first_light`) draws the same model and pair through the -Xbox-ABI device proxy over the Vulkan device, natively on Windows. `CreateGraphicsPipelineState` gets the game's -own containers and finds both stages by the FSSM hash inside them, in the index `first_light.py` writes next to -the SPIR-V (`vs.dxbc`, `ps.dxbc`, `index.json`); the input layout (POSITION float3, TEXCOORD float2) is matched -to the VS signature, the mesh goes through DEFAULT vertex and index buffers, and one `DrawIndexedInstanced` draws -it into a cleared R32G32B32A32 target read back with `CopyTextureRegion`. - -D3D12 clip space is y-up and the layer flips the viewport, so `vk_harness` row r is row 127 − r here. On an RTX -3060 (Windows 11, driver 616.64, Vulkan SDK 1.4.363.1) the draw covers the same **12,804 of 16,384 pixels**, the -centre pixel is `(0.49756, 0.49634, 0.0, 1.0)` and the corner keeps the clear (−1). Against `vk_harness`'s -`image.raw`, 16,383 pixels are bit-exact and one is one f16 step apart (0.74219 here, 0.74170 there): the PS -exports with `v_cvt_pkrtz_f16_f32`, which rounds toward zero, so an f32 interpolant a few ulps lower under the -opposite viewport direction drops one step. `vk_harness` drawing the mesh mirrored in y reproduces the D3D12 -image bit for bit. The test allows that one step and nothing else; it is clean under `LEONIDA_VK_VALIDATION=1`. - -```sh -python -I tools/first_light.py ... --no-fit --run # as in section 3; writes vs.dxbc, ps.dxbc, index.json -LEONIDA_FIRST_LIGHT_DIR=~/leonida-work/first_light/out ctest --test-dir -R d3d12_first_light -V -``` - -Without `LEONIDA_FIRST_LIGHT_DIR` the test prints SKIP and exits 77. - -## 6. With a texture (`TEST-524`) - -Passing `--dds ` to `tools/first_light.py` switches the default pixel shader to a translated -single-sample game pixel shader (`PS_Copy_3ea4b38a_Wrapped`, FSSM SHA-256 -`19e2e7612505b9d3b19e6607b47e09dcdde02a2c9987a63e834d9586f217090f`, wave32, `inputs=[0]`, `outputs=[0]`, -`shader_link_check.py check`: compatible with `VS_main_170e32e6_Wrapped`). `first_light.py` decodes the DDS -(for example a BCPack-decoded TTPF albedo) with `tools/dds_png.py`, writes `texture.rgba` (`u32 width, u32 height` + -`R8G8B8A8_UNORM` texels) into the output folder, and passes `VKH_TEX_RGBA`, `VKH_TSHARP_VA` (`0x100`), -`VKH_SSHARP` (the shader's literal sampler `0x92, 0xc00000, 0x14500000, 0`, bilinear + clamp-to-edge) and -`VKH_SGPRS` (`s9 = 0x100`) to `vk_harness`. - -`vk_harness` enables `bufferDeviceAddress`, `runtimeDescriptorArray` and `descriptorIndexing` only when -`VKH_TEX_RGBA` is set (inert otherwise), writes the 8-dword `T#` at `VKH_TSHARP_VA` in the 64 KiB heap, binds -set 0 (`binding 0` 2D images with a 1×1 magenta fallback at index 0 and the decoded texture at index 1; `binding 1` -samplers with the decoded `S#` at index 1; `binding 2` the `DescriptorTable` hash buffer), and draws the mesh. - -The CPU oracle (`check_image`) samples the decoded `R8G8B8A8_UNORM` texture bilinearly (clamp-to-edge) at -`centre_uv` and each `uv_probes` entry and requires the GPU readback to match within `0.02` (rejecting the -magenta unbound-texture fallback and wrong-colour probes). Verified on Windows 11 with an NVIDIA GeForce RTX 3060 -(driver 621.24, Vulkan 1.4.357): **12,804/16,384 (0.781)** covered. Without `LEONIDA_FIRST_LIGHT_DIR`, -`python -I tests/test_first_light.py -v` runs **46 tests: 42 passed, 4 skipped** (the 3 package-gated -`FirstLightTests` require `LEONIDA_FIRST_LIGHT_DIR`, and `test_harness_rejects_wrapped_tsharp_va_overflow` needs a -built `vk_harness`; the 4 `OracleTests` and the other 11 `TexturedOracleTests` run without a package). With -`LEONIDA_FIRST_LIGHT_DIR` set against a local package run (and `vk_harness` built) none of the 46 is skipped. - -```sh -python -I tools/first_light.py --game "" --work ~/leonida-work \ - --obj ~/leonida-work/assets/data/models/.obj \ - --dds ~/leonida-work/assets/ttpf//.dds --no-fit --run -LEONIDA_FIRST_LIGHT_DIR=~/leonida-work/first_light/out python -I tests/test_first_light.py -v -``` - -## 7. A camera (TEST-523) - -`first_light.py --camera` draws the same model in perspective with a game VS that applies a world matrix and a -view-projection matrix of its own, read from two constant buffers. The PS is the one from section 1: - -| stage | FSSM SHA-256 | what it does | -|---|---|---| -| VS | `e909a9e5a0096e00bc2b621ae3bdc96ac904f3047aed3917835774cbccb09716` | POSITION × world × view-projection to clip space (computed w); TEXCOORD to a varying | -| PS | `ed4147a5f7514947c2eb8d79255bd80f72761ac1ba2205dd811d3e050cf1b495` | as in section 1 | - -The VS's scalar loads give its constant layout. The 32-bit address of a descriptor table is in s9 (the high half is -0). The V# at table + 0x20 points at the world rows: X, Y, Z and translation, one float4 each at 0x00–0x30, of -which the VS reads xyz. The V# at table + 0x60 points at a constant buffer whose view-projection rows sit at -0x160–0x19f. Both matrices multiply a row vector: `world = [x y z 1] W`, `clip = [world 1] VP`. The view-projection -block is common in the game: on 1.0.2.1, all 9 translated VS modules with exactly POSITION and TEXCOORD inputs and -a clip w that is not the constant 1.0 read 16 dwords at 0x160 of a constant buffer, as do 123 of the 254 VS -modules with a POSITION input and a computed w, and 1,266 of all 2,236 VS modules. That it is the view-projection -everywhere is a hypothesis; for this VS the arithmetic shows it. - -The mesh keeps the model's own coordinates. The tool builds a world matrix that centres the model and scales its -bounding sphere to radius 1. The camera sits 3 radii away, `--yaw` degrees around Z (the game's up axis) from −Y -and `--pitch` degrees above the XY plane, with a vertical `--fov` (defaults 30, 25 and 50). The projection is -Vulkan's, with the near and far planes just outside the sphere, so depth clips no vertex. The tool writes the two -matrices, the two V#s (raw buffers, stride 0, sized to what the VS reads) and the table into `vk_harness`'s heap -(`VKH_HEAP`) and the table address into s9 (`VKH_SGPRS`). The manifest's `camera` block keeps both, so `--check` -and the test draw with the same constants. The prediction projects the same vertices with the same float32 -matrices on the CPU and interpolates UV perspective-correctly, dividing each screen-space weight by its vertex's -clip w. The output goes to `/first_light/camera`, leaving the orthographic folder for section 5. - -On an Apple M4 (macOS, MoltenVK 1.4.2), with the section 1 model and the default camera at 128×128: - -* The draw covers **6,851 of 16,384 pixels (0.418)**. -* The centre pixel matches the predicted UV `(0.8100, 0.3096)`, and so do the four U ≠ V probes, within the - oracle's 2e-3. The corner keeps the clear value. -* On a full 32×32 grid of pixel centres, the predicted coverage agrees on all 1,024. The UV agrees within 2e-3 on - all 428 covered ones, with the worst at 5.05e-4. -* The same draw without the constants covers nothing and is rejected. With the camera turned 2° in yaw, the - centre pixel is off and the check is rejected too. -* The pair passes `spirv-val`, and `shader_link_check.py check` reports it compatible. - -The model's triangles are small, so perspective-correct and affine UV differ by at most 1e-4 at the probes. The -image therefore does not tell the two apart; `CameraTests` in `tests/test_first_light.py` checks the -perspective-correct weights on one large triangle instead. Those CPU tests also read the constants back the way -the VS's loads do (table, V#, num_records, rows) and compare the result with the matrices the prediction uses. - -```sh -python -I tools/first_light.py --game "" --work ~/leonida-work \ - --obj ~/leonida-work/assets/data/models/.obj --camera --run # coverage window 0.2-0.99 -LEONIDA_FIRST_LIGHT_DIR=~/leonida-work/first_light/camera python -I tests/test_first_light.py -v -``` - -## 8. Limits and next - -* The camera draw (section 7) runs in `vk_harness` only. Through the D3D12 layer, s9 and the table it points at - have to come from root arguments, which `d3d12_first_light_test` does not set up yet. -* `--camera` and `--dds` don't combine: the camera VS's table and the textured PS's T# both take s9 of the shared - push constants and heap VA 0x100, so `first_light.py` refuses the pair. A textured perspective draw needs a - second constant layout. -* One model and one draw. The `levels.rpf` windows have world props with POSITION/NORMAL/COLOUR/UV layouts that - match the `sga_dr_*`/`Rage_Transform*` families by signature; pairing one of those is the natural next image. -* The game still cannot boot: the executable is not in the package (RT-5), so no call site selects these programs. diff --git a/docs/fork-notes.md b/docs/fork-notes.md new file mode 100644 index 000000000..9b62986d3 --- /dev/null +++ b/docs/fork-notes.md @@ -0,0 +1,383 @@ +# Fork notes + +The detailed log of what this fork measured and changed, moved here from the README. +The status summary is in [README.md](../README.md). + +## Newest (2026-11-25, later the same day) + +**Update, 2026-11-25 afternoon: what a frame is made of, measured, and two +changes that hold.** First rooms, about 3,850 draws a frame: 104 ms a frame +(9.6 frames a second) with the first two changes below, 97 ms (10.3) +with all of them, from about 120 ms in the morning. Still far from the console's 33 ms. +- How the title paces itself (new meters in `fence.rs` and + `console_insn.rs`): it never asks for an event. Each frame begins with + one small submission and a signal, and a title thread then waits for + that fence value by reading it in memory with `monitorx` / `mwaitx` + (AMD-only: about 280,000 emulated exceptions a second on an Intel + processor, all from this wait). The value is set when the layer has + finished the whole frame before. So a frame is the time the layer needs + for one frame's burst of submissions plus about 20 ms of the title's + own; putting presents behind the line, or giving the title's threads + more processors, changes nothing (both measured). +- Two walls stand side by side and both are full: the layer's submit + thread (about 95 ms of a 120 ms frame in the morning) and the card + (about 102 ms busy, by a timestamp pair around every host list: + `cardmeter.rs`). Taking time off one alone moved the frame by 0 to 7 %. +- `LEONIDA_JOIN_PARTS=1` (off by default): the title's lists wait for + memory values, which cut its ~15 submissions a frame into ~29 parts; + parts that follow one another now go to the host as one submission + (9 a frame), the same lists in the same order. About 6 %. +- `LEONIDA_BACK_OWN_VIEW=1` (off by default): what shaders wrote goes + back into title view memory through a view of the layer's own, so the + copy that wrote it is not read in again. About 9 % (submit thread 93 -> + 81 ms a frame, 104 -> 80 MB a frame checked). A CORRECTION: an earlier + run seemed to show washed-out frames with this switch; the same frames + turn up in about 6 of 21 runs with no switch at all (cause not known), + and `LEONIDA_BACK_OWN_CHECK=1` counted 0 stores gone astray in 1.36 + million. +- Where the card's time goes now (`LEONIDA_CARD_METER_PIPELINES=1`, a + table by pipeline): no pass is large. About 82 ms of the title's lists + are spread over ~3,400 pipeline bindings a frame; ~2,400 of the + indirect commands still get a clamp pass of the layer's with draw + windows on (960 are compute dispatches; about 1,000 are mesh records + the title keeps scattered through a 100 MB argument buffer, which a + window of records at one step cannot serve). +- `LEONIDA_INDIRECT_GATHER=1` (off by default): a single indirect record + that misses its window gets a slot in a scratch buffer of its list, and + the list's prelude clamps all such records in one pass by a table of + their offsets (the clamp shader with a gather bit), where each draw had + a compute pass of the layer's in front of it. Proved by clamping every + gathered record again at its draw and comparing on the card + (`LEONIDA_INDIRECT_WINDOW_CHECK=1`): 7.9 million records, none differed. + About 600 of the ~1,600 draws that missed a window are served; the + others come after a dispatch or a storing draw in their list. With + `LEONIDA_CARD_REHASH_RUNS=1`: 104 -> 97 ms a frame (10.3 frames a + second at 3,800 draws). +- What the card's time is now, added up: of ~87 ms busy in a 97 ms + frame, the layer's own lists are ~19 ms and its clamp passes 10-20 ms; + about 50 ms are the title's own ~30 compute passes and its geometry at + 2560x1440 as translated. With every pass of the layer's gone, this + scene would still be near 20 frames a second on this card: the + translated shaders have to get cheaper too. +- The frame rate is drawn into the top left corner of every frame shown + (`fpsbox.rs`; `LEONIDA_FPS_COUNTER=0`: not): the window's caption has + it too, but a capture of the picture does not carry the caption. +- `LEONIDA_COPY_CHANGED=1` (off by default): a refresh of a copy in the + card's memory sends on only the 256-byte chunks that differ from the + copy's CPU side. The layer's sync lists on the card fall from 12 to 8 + ms a frame, the submit thread pays 3.6 ms for the compare and is then + the limit: no net gain yet. +- HONEST LIMIT OF ALL THE ABOVE: those numbers are the scene standing + still. While the camera moves the title streams assets, and about half + the time goes to frames of ~490 ms in which the card is idle for ~330 + ms: some 850 remaps of title memory, 260 texture uploads and 450 disk + reads in one frame. That is the next thing to measure and cut. +- The dips while moving, measured (a sampling profile of the opening + cutscene, and a 370 s play session): the mean is 4.5 frames a second, + with half the time in frames of ~490 ms in which the card is idle for + ~330 ms. In those frames the title's render thread waits for its own + jobs, not for the layer. One of those jobs is the title's page-mapping + copies (`CopyPageMappingsBatchX` -> `xmem::map_alias`): the title maps + every streamed texture page into its tiled heap, a range of one page + each (over 4,096 different pool pages in a minute, about 850 pages in + a frame that streams), and each is a view taken away and a view mapped + in the kernel: 32 ms of every cutscene frame, 246 ms of a streaming + frame, nearly all of it waiting on the process's address space. +- Two attempts on that, both taken back out: leaving alone pages that + already show what is asked (counted: there are none, every remap is a + real change), and mapping pool pages in a row as one view (1.8 to 4.2 + pages a view, remap time 140 -> 79 ms a frame, BUT faces came out black + or red and one run drew garbage in 3 launches of 3, against none in 6 + launches without it). Reverted; why a longer view breaks texture + streaming is not known yet. +- Measured and found to give nothing (switches left in, off): + `LEONIDA_REFRESH_ONCE`, `LEONIDA_ASYNC_PRESENT`, `LEONIDA_VIEW_KNOWN`, + `LEONIDA_SPREAD`, `LEONIDA_QUEUE2=3`, `LEONIDA_WINDOW_JUMP`. Each has an + `=alt` form (twenty seconds on, twenty off, each change said in the + log) so that one run measures both in the same scene. + +**Update, the same night: the first room now renders right on the test +machine** (walls, textures, people, lamps), at 190 to 450 ms a frame (2 to 5 +frames a second): the picture work has caught up, the frame rate has not. +What did it, on top of the list below: +- Descriptor records the title copies into its heap as plain bytes are + mirrored before every submission (pull request #305 by Flyander, after + upstream VIctory 86a5ed6). Measured here: about 40,000 records a frame + that no call had announced; their host slots were empty or stale. +- A buffer view that does not start on an element of its buffer's host + copy gets a copy of its own bytes instead of being refused (after + upstream 86a5ed6): 3 to 6 such views a frame. +- Room on the card is kept for the render targets and buffer copies a + world makes in its first frame: 98 buffer copies are made (945 MB) where + the runs before made 1, and the processor no longer compares 550 to + 710 MB a frame looking for shader writes (25 MB now). +- Levels on demand ran on the card for the first time + (`LEONIDA_LEVELS_ON_DEMAND=1`, still off by default; with the fixes of + pull request #747 by AscilCH): 3.1 GB of the card not allocated for + texture levels the title does not hold, no device loss. +- Guarded blocks under storage writes are opened by default; 14 more + shader programs translate; a program is translated with first-half + interpolation pairs only if it was refused for one (with that on for + every program, 8,551 working pixel programs came out changed). +- Frame rate, first cuts on the processor side: the descriptor sync uses a + cheap fingerprint and leaves draw-table slots to their draws (the pass + over the heap went from 70-220 ms a frame to about 3), and memory the + guards already hold is not asked of the write watch (pull request #670 + by Jonirulah). Card copies' pieces can come down inside their own + flights (pull request #648 by Jonirulah, `LEONIDA_CARD_FETCH_INFLIGHT=1`, + off by default: the copy-back thread's wait went from 181 ms a frame to + 0 here, but the card got busier, so no gain is claimed yet). The frame is + still 250 to 380 ms: the card is the limit now, most of it the + per-record clamp before each of some 6,700 indirect draws a frame. +- Pull request #220 (cheaper indirect draws) is IN this tree now, its + windows off by default (`LEONIDA_INDIRECT_WINDOW=1`). History, so nobody + repeats it: with windows on it lost the device three times here. Its own + checker (`LEONIDA_INDIRECT_WINDOW_CHECK=1`) then showed one list drawing + 90 records of 2^24 vertices from a window, where the per-draw path lets + eight through; a record of 2^23 vertices an instance or more now runs + empty. Since that fix: eight runs with windows on, seven without a + device loss and one that lost the device 44 s into the world (cause not + found; see the driver watch below). One earlier loss after the fix had + the in-flight fetch (#648) on as well; do not combine the two. The + in-flight fetch itself measured slower here in two runs and stays off. +- Frame rate, second night (an RTX 4070; the first room went from about + 3.5-4 to 6-7 frames a second with ALL of the switches below; the + defaults are unchanged and give about 4.5-5): + - `LEONIDA_ASYNC_SUBMIT=1`: submissions are prepared and sent by a + thread of the layer, not by the title's render thread, which a + profile showed inside the submit path for 257 of 292 ms a frame. + - `LEONIDA_QUEUE2=1`: fetches of what shaders wrote go to a copy queue + (brought back, with the fix for a piece fetched beside a later + flight); the copy-back thread's wait fell from about 125 to 7 ms a + frame. + - `LEONIDA_INDIRECT_WINDOW=1`: see above. + - `LEONIDA_TEXTURE_NO_WAIT=1`: a texture refresh no longer waits while + the title remaps memory; the loading phase had 5 readings over a + second where it had 18. + - `LEONIDA_MERGE_GAP=64 LEONIDA_MERGE_RUNS=4096`: title bytes put in + under flights' shader writes are joined over small gaps (NOT exact: + read the comment at `merge_gap` before using it). + - On by default: fills of upload memory and read-only buffer copies no + longer wait for flights and are checked against what the flights then + wrote (`LEONIDA_FILL_WAIT=1` waits as before; no mismatch in any run + so far); up to 512 idle host lists and texture staging buffers are + reused instead of made and freed every frame. + - `LEONIDA_PROFILE=1` (diagnostics builds): a sampling profiler inside + the layer; it is how the above was found. +- Frame rate, third session: measuring first (same RTX 4070, first room). + - A frame log (`LEONIDA_FRAME_LOG`, on in diagnostics builds): every + frame's length, and for the usual frame and each long one what it was + made of (the render thread's time in the present call, the submit + thread's work, copies, copy-back, recording, texture work, faults, + disk). A card meter (`LEONIDA_CARD_METER`) adds the card's time by + kind of list from a timestamp at each list's start and end. + - What they showed, windows off: a usual frame of 136 ms; the title's + render thread waits 77 ms of it in the present call for the submit + thread, which works 118 ms (copies of title memory 41, copy-back 40); + the card is 85-98 % busy, of about 130 ms a frame 16 ms in our lists + that bring card copies up to date, 10 ms in our compare lists and 102 + ms in the title's own lists with the per-record clamp. Frame time is + linear in draws (about 32 microseconds a draw all-in): the title draws + about twice as much on some frames, which are the long ones. + - The regular dips of earlier test runs were the test harness: a saved + frame (`LEONIDA_CAPTURE_WORLD`, every 8th world frame) is read back + and written as a PNG inside the present, 235 ms each. + `LEONIDA_CAPTURE_WORLD_EVERY=64` for runs that measure speed. + - `LEONIDA_INDIRECT_WINDOW=1` measured again with those instruments. A + CORRECTION: the first figures given here (6.0 against 8.9 frames a + second) compared two runs that stood in different scenes during the + measured window (about 4,300 against 1,550 draws a frame) and are + withdrawn. Compared at equal draws, by a line fitted to each run's + frame times against its draws per frame: windows off 145 ms at 4,500 + draws and 271 ms at 10,000; windows on with `LEONIDA_COPY_PLAIN=1` + 124 ms and 211 ms. On screen: 7-8 frames a second in the first rooms, + 10-12 in their lighter views. + - A driver watch (on by default; `LEONIDA_DRIVER_WATCH=0` off): the + layer subscribes to the system's event log and logs every entry of a + display driver as it is recorded; the first one turns draw windows + off for the rest of the run. Every device loss here had such entries + 2.7 to 55 seconds before the device was removed, and no run without + them lost its device. + - A copy between two title textures that share one host texture is no + longer recorded (the host does not allow a texture copied onto + itself): 402 of them in a five-minute run. + - The list of shader-visible heaps is a reader-writer lock (recording + threads waited 48 ms a frame, summed, behind the heap sync); the heap + sync looks at a changed page's records under one lock, fingerprint + first; guarded view memory is left out of a submission's write-watch + askings ahead (after triippywhale). + - `LEONIDA_COPY_PLAIN=1`: copies of title memory made in place by this + process, with a handler that falls back to the kernel's copy on a + missing page. Its first form also took the layer's one-byte "is this + page there" reads, 1,000 to 1,300 faults a frame, and won nothing; + reads under 256 bytes now stay with the kernel and a source that + faulted is left alone for two seconds (4 to 9 faults a frame). The + submit thread's kernel time fell from 44 to 20 ms a frame; the + picture is the same. + - The layer's submit and copy-back threads ask for the fast cores of a + hybrid processor (`LEONIDA_FAST_CORES=0`: not): the submit thread was + found on a slow core in 6 % of its looks, now in none of 21,059. + `LEONIDA_DISK_CORES=slow` (off, not measured) asks the slow cores for + the DirectStorage workers, which are as many as the logical + processors and free to run anywhere. + - Behind switches, built and unit-tested, not yet shown to pay: + `LEONIDA_REFRESH_ONCE=1`, `LEONIDA_VIEW_KNOWN=1`, + `LEONIDA_BACK_OWN_VIEW=1` (picture to be checked), + `LEONIDA_ASYNC_PRESENT=1` (the present goes behind the queue's line; + no gain while the card is the limit). + - Tried and refused: `LEONIDA_BVH_HOLD=1` holds back the 64 programs + that walk ray-tracing structures nothing has built; the picture loses + its indirect light with it, so it stays off. + - The process opts out of the system's efficiency mode + (`LEONIDA_EFFICIENCY_MODE=1` leaves it); on a hybrid processor the + frame log found the title's render and recording threads on fast + cores in every look of a run, and the layer's submit thread on a slow + core in 6 % of its looks. + Still open: the per-record clamp is most of the card's time, and the + copies between the PC's memory and the card's are most of the submit + thread's; the cause of the one device loss with windows is not known. + A first play session past the first rooms reached the open world and + lost the device there with no driver entry (reason "device removed"): + the card had no room for new textures from the opening cutscene on + (9.2 of a 10.3 GB budget on a 12 GB card; 2,073 passes made no texture + for lack of room; 44,613 textures let go and made again in 13 minutes). + Cause of that removal not known either. +- Known and counted, not fixed yet: an indirect compute pass asks for + about 77,500 thread groups in x where one dispatch runs 65,535 (the + rest is cut off). + +Memory sync between the title's memory and the copies on the card: +- **A write through one view of a physical page is seen by the copies taken + through its other views** (`LEONIDA_VIEW_GUARD=0` turns it off). The title + shows one page at several addresses and a copy was guarded at one of them + only. Measured on the test machine: 0.8 to 1.0 million such writes in a + five-minute run, every one of which used to leave a copy stale. Since it + went in, the first room had its walls in the later frames of 4 runs out of + 4 (2 of 5 before); the room's very first shot still comes up without walls + in some runs. +- Kernel reads into title memory are read beside and copied in, so a block + guarded again in between no longer fails the read. +- Writes of the storage layer into physical pages are counted where the title + has those pages mapped (10,000 to 50,000 guarded blocks of copies lay under + them in every run) and can open the guards there: + `LEONIDA_PAGE_WRITES=guards` (off by default; `1`, `slots`, `all` do more). +- Failed page-destination reads are retried (`LEONIDA_DSTORAGE_RETRIES=0` = as before). + +Card memory (the test card is full from the first frame of the world: 85 to +99 % of its budget for a whole run, about 26,000 texture copies let go and +3,400 made again in five minutes, 2.8 GB of render targets that are all in +use): +- Levels on demand, **off by default** (`LEONIDA_LEVELS_ON_DEMAND=1`): a + texture the title fills takes card memory only for the levels the title + holds (2.2 to 3.0 GB of the copies were levels it does not hold). Its test + runs on the software adapter; it has not run on a card yet. +- Refused texture slots are held back for a few seconds so that a pass + reaches the slots behind them (`LEONIDA_FULL_CARD_PASS=0` = as before); + room can be kept for the card copies of title buffers + (`LEONIDA_CARD_ROOM_FOR_BUFFERS=1`, off). + +Tools and diagnostics: +- `leonida translate --warm all --jobs N` translates every + shader ahead of a run, on the processor only (about 4.5 to 6.5 minutes + here); the shader cache is keyed on the translator's source, so a new + build that does not touch the translator starts warm. +- Counters, all off or diagnostics-only: `LEONIDA_MERGE_RACE=1` (title bytes + a copy-back is about to put back to older values: none found in 138,000 + copy-backs), `LEONIDA_WALLS_TRACE`, `LEONIDA_CARD_ACCOUNTING`, and a census + of the copies the texture sweep never lets go. + +## What this fork changed (summary) + +Rendering: +- Meshlet culling read its scene buffers as the wrong kind of view, so the world drew almost nothing; fixed. +- Per-draw descriptor tables could run out, after which draws used slots never made for them and the card hung; fixed. +- Light packed by the game's compute shaders was read back through empty copies (sky, probes, fog); fixed for every mip level and layer. +- The fog reconstruction, shadow-mask, hair, blend-shape skinning, fire and several material programs did not translate; fixed. +- Gathers at a named mip level (with and without an offset) read level 0; fixed. +- Implicit-level samples outside pixel shaders produced invalid DXIL in 730 compute programs; fixed. +- Rectangle lists, depth and stencil twins for depth textures written by compute, texture read-backs. +- Ray tracing, in progress and off by default: the game's own structure-builder programs translate, title memory can be read by raw address from shaders, the hardware ray/box and ray/triangle test is emulated in DXIL (checked against a reference on the GPU), and 59 of the 64 trace programs translate. Nothing is lit by it yet. See [docs/fork-ray-tracing.md](docs/fork-ray-tracing.md). + +Speed and memory: +- Waits for memory values, write-watch queries and page queries no longer walk page tables per call. +- Large title buffers get a copy in card memory, with shader writes found by hashing on the card. +- Submissions can be sent ahead of the wait for the card (`LEONIDA_LATE_WAIT`), with a relay thread that lands results as the card finishes (`LEONIDA_RELAY`): in a first five-minute run the card's idle time behind the submitting thread fell from about 136 to 30 ms per frame. +- Title memory can be opened as a graphics heap so that buffers are used in place instead of copied (`LEONIDA_INPLACE`, first stage only; a probe confirmed the approach on the test GPU). +- The bindless texture queue no longer uploads stale views; the view table no longer grows without bound; the pipeline library is mapped instead of read into memory. +- An intermittent device loss was traced to the pipeline library file being replaced while mapped; fixed. + +- Translated shaders get clean-up passes over the finished module (dead code, constant folding, reuse of values, branch facts); the pack's host instruction count falls by about 43 %, worth about 20 ms of GPU time per frame on the test machine (`LEONIDA_SHADER_OPT=0` turns them off). + +Most of the newer speed changes sit behind environment switches that are off +by default (`LEONIDA_LATE_WAIT`, `LEONIDA_RELAY`, `LEONIDA_WIDE_BACK`, +`LEONIDA_CARD_BUFFERS_MIN_MB`, `LEONIDA_INPLACE`, `LEONIDA_BVH_BUILDER`, ...). +Each is described in a comment where it is read. + +## Upstream status (2026-11-23) + +Upstream VIctory's own status when this fork was taken, with its switches renamed. + +**Not playable yet.** The title boots, runs its menus at its own 30 fps and +loads the world, where rendering fails. + +| Stage | State | +|-------|-------| +| Boot, first-boot screens (accessibility, language, settings, legal) | works, 30 fps | +| Intro video with sound | works | +| Start screen, profile and saves | works | +| Loading into the world (about 50 s) | works | +| The world (first mission's intro) | reached and runs with indirect draws; its title card renders, the scene after it is still dark; 0.5-1.8 s per frame | + +Tested on one machine: Windows 11, AMD RX 6700 XT. + +> **Warning.** Entering the world on a real GPU can currently hang it, and +> Windows then resets the display driver (every monitor goes black for a +> moment). To look further, use a diagnostics build with +> `LEONIDA_D3D12_WARP=1`, which renders on the software adapter. + +What each part does today and what it still needs: + +| Subsystem | Today | Needs | +|-----------|-------|-------| +| Loader | Runs the title's executable and its DLLs in our process; crash reports name the faulting code and are kept in `crashes.log` | – | +| Runtime services | One signed-in offline user, licences, packages, saves that survive a kill at any step, text entry dialog | Speech is silent; the dialog and relaunch are untested live | +| Network | Offline by design: the title cannot reach the network | – | +| Files and streaming | Archives and streamed data read, zlib and BCPack decoded in parallel | Loading is limited by writes into title memory | +| Input | XInput pads, keyboard, keyboard stand-in pad | Trigger rumble | +| Audio | Menu, video and loading sound; XMA voices and Opus streams decode | Reverb is silent; Opus results unverified against the title | +| GPU: menus | Draws, compute and presentation on host D3D12; only changed title memory is copied | Frame pacing drifts on one screen in release builds | +| GPU: world | Mesh pipelines, shader-written buffers, descriptor lifetimes, indirect execution (arguments clamped), pipelines made by worker threads and kept on disk | Most of the scene is still missing (untranslated shaders drop draws); frames take seconds; real queries, depth bounds, HDR and scaling are missing | +| Shaders | Console GPU code recompiled to DXIL at first use, cached on disk. Menus: all. World: mesh 8,191 of 8,506, vertex/pixel 10,617 of 12,346, compute 1,643 of 2,539 | 64-bit image atomics, merged geometry stages, the ray-tracing builder's shaders; some compute programs need a GPU with 64-lane waves | +| Textures | Console tiled layouts and detiling for the modes the title uses | Render-target metadata planes | +| Series S mode | Runs through the menus to the loading screen | The world, as above | + +## Debugging + +A release build has no debugging aids. Build them in with + +```powershell +cargo build --profile diag -p leonida --features diagnostics # target\diag\leonida.exe +``` + +| Variable | Effect | +|----------|--------| +| `LEONIDA_LOG==debug,...` | debug and trace output | +| `LEONIDA_STACKS=20,60` | every thread's stack at those seconds | +| `LEONIDA_WATCH=,...` | logs a title u32 when it changes | +| `LEONIDA_KEYS=30:Enter,35:X` | presses keys at those seconds, focus or not | +| `LEONIDA_CRASH_SAVE=:,...` | saves title memory to the cache folder on a crash | +| `LEONIDA_CAPTURE=` | saves presented frames (powers of two, or `LEONIDA_CAPTURE_FRAMES=`) | +| `LEONIDA_DUMP_TARGETS=1` | with the two above, saves every render target of those frames | +| `LEONIDA_D3D12_DEBUG=1` | host debug layer | +| `LEONIDA_D3D12_GBV=1` | with the above, GPU-based validation (bad descriptor use reported, not faulted; slow) | +| `LEONIDA_D3D12_DRED=1` | on a GPU failure, the allocation hit and the commands in flight | +| `LEONIDA_PIPELINE_WAIT_MS=24` | reduce the per-frame wait for background pipeline creation from the default of 500 ms. A draw can be omitted until its pipeline is ready | +| `LEONIDA_SKIP_PIPELINES=,...` | omit draws and dispatches, including indirect ones, whose pipeline contains a listed 16-digit shader hash | +| `LEONIDA_GPU_TIMING=1` | with the above, each list of a submission run and timed on its own; slow lists logged with their slowest commands | +| `LEONIDA_D3D12_WARP=1` | host device on the software adapter (slow; cannot reset the driver) | +| `LEONIDA_SHADER_LOOP_LIMIT=` | translated shader loops stop after `n` iterations per lane instead of 2^20 (own shader cache entries); if a lower `n` makes world frames much faster, loops hitting the limit are what makes them slow | +| `LEONIDA_AUDIO_CAPTURE=` | records what the title plays (our process only) | +| `LEONIDA_XMA_DUMP=` | saves the first 32 XMA voices' context and input | + +Every build appends crashes and host GPU failures to `crashes.log` in the +title's data folder. diff --git a/docs/fork-ray-tracing.md b/docs/fork-ray-tracing.md new file mode 100644 index 000000000..50df126d0 --- /dev/null +++ b/docs/fork-ray-tracing.md @@ -0,0 +1,85 @@ +# Ray tracing in this fork: what the title does and what has been built + +Status, 2026-11-25: **nothing is lit by ray tracing yet.** Most of the +machinery translates and is unit-tested; it has not yet run end to end in the +game. Everything here is off by default. + +## What the title does + +The title's indirect light (probes, bounce, reflections) and the +shadows of its lamps and sun are ray traced. Without them, anything the sun +does not hit directly is black: interiors, the shadowed side of a face, rooms +lit only by lamps. + +The title does not use a ray-tracing API: + +- Traversal is ordinary compute-shader code: a per-thread stack in shared + memory, and loads through raw 40-bit addresses of title memory. +- The static world's acceleration structures ship pre-built in the title's + data, in the console GPU's native node format (64-byte nodes: box nodes with + four children and 16-bit float bounds, 128-byte box nodes with 32-bit float + bounds, triangle nodes, instance nodes). They are unpacked on the GPU. +- A set of builder programs (from the title's `XboxBvhBuilder.dll`, 52 compute + programs) builds and refits the dynamic structures on the GPU every frame. +- Only the per-node test is hardware: the instructions + `image_bvh64_intersect_ray` and `image_bvh_intersect_ray`. One call tests a + ray against a box node's four children (returning the hit children, nearest + first) or against a triangle node (returning the intersection's numerator, + denominator and barycentric numerators). + +So mapping this onto the host's own ray tracing (DXR) is not practical: the +layer would have to know the geometry behind structures the title never +describes to it, and the traversal loops live in 64 of the title's own +programs. This fork runs the title's builder and traversal as translated +shaders and emulates the one instruction. + +## What this fork adds + +1. **The builder programs translate** (49 of 52; all that the title creates in + the scenes tested). They pass buffer addresses in a spilled parameter table + rather than in descriptors. Added: the spilled user-data table, root + unordered-access views (translator and host binding), byte and 16-bit buffer + accesses, and several control-flow shapes. +2. **Title memory by raw address from shaders.** A directory with one entry per + 64 KiB of title address space leads a shader to the layer's host copy of + that memory; loads, stores, atomic add/sub and float min/max go through it. + Before a dispatch the host makes ready the memory its root views and root + constants name. +3. **The ray test, emulated in DXIL.** Four slab tests and a sorting network + for box nodes; a watertight ray/triangle test for triangle nodes; both forms + of the instruction. A plain Rust reference lives in + `crates/leonida-shader/src/bvh.rs`; tests run the emitted DXIL on the GPU + over 311 ray/node cases and compare with the reference bit for bit. +4. **The trace and shading programs translate** (59 of 64 trace programs, and + the irradiance-cache shading program). This needed lane masks treated as + plain numbers on some paths, and exact forms for programs written for + 64-lane waves running on a GPU with 32-lane waves. +5. **A safety rule on the host side.** The builder's stages run only while + every builder pipeline the title has created has a host pipeline; otherwise + none run (`LEONIDA_BVH_BUILDER=1` asks for it; `LEONIDA_BVH_QUARANTINE=1` + also keeps the builder's stores out of title memory, for a first test). A + partly working builder wrote garbage bounds into title memory and crashed + the title. + +## Known gaps + +- With `LEONIDA_BVH_BUILDER=1` the builder still stays off in a real run: a few + of its pipelines are refused by the host (they still ask for 64-lane waves on + a 32-lane GPU) or do not translate. +- Five shadow-mask trace programs do not translate yet. +- An access to a title page that has no host copy is lost (a read gives zero, a + store is dropped). +- Not publicly documented, and assumed: the instruction's rounding, the order + of two boxes entered at the same distance, and the result for a ray exactly + through an edge. +- Cost on the GPU is unmeasured. + +## Where to look + +- `crates/leonida-shader/src/bvh.rs`: the reference for the node test. +- `crates/leonida-shader/src/emit/lower.rs`: the lowering of the two + instructions and of memory by address (`Lower::memory`). +- `crates/leonida-shader/src/resource.rs`: address tracking for descriptors + and raw addresses. +- `crates/leonida-gpu/src/pipeline.rs`, `draw.rs`: the builder rule and the + host side of root views and title memory. diff --git a/docs/fspx.md b/docs/fspx.md deleted file mode 100644 index a603545e9..000000000 --- a/docs/fspx.md +++ /dev/null @@ -1,262 +0,0 @@ -# FSPX: the FidelityFX DLL's native compute programs - -The package's FSR upscaler, `amd_fidelityfx_upscaler_xbox.dll`, carries 29 compute shaders as `DXBC` containers with -`SFI0`, `ISG1`, `OSG1`, `PSV0`, `RTS0`, `HASH` and `ACCC` parts and no `DXIL` ([d3d12_command_objects.md](d3d12_command_objects.md) -§3.5a). The `ACCC` part is an `FSPX` payload: a small directory around a precompiled RDNA2 program. It is not the -`XBCH`/`FSSM` format of the game's own shaders ([design.md](design.md)), but it holds the same kind of program, and -`tools/fspx_unpack.py` lays it out so `tools/rdna2spirv.py` translates it like a game compute shader. - -Everything below was measured on the 1.0.2.1 package's DLL (SHA-256 `faff02f2…a75fa`). "Read from the DLL" means -Ghidra 12.2 output (through REA) for the named function; "measured" means checked on all 29 programs unless a count is -given; anything else is marked as inferred. - -## Layout - -``` -u32 'FSPX' -u32 version 1 in all 29; the DLL does not read it -u32 count 4 in all 29 -u32 total size == the ACCC part size in all 29 -count x { u32 kind, u32 offset, u32 size, u32 0 } offset from the start of the payload -``` - -| Kind | Size | What it is | -|---|---|---| -| 0 | 28 bytes in all 29 | Dispatch state, see below. Required by the DLL. | -| 1 | 20 bytes in all 29 | Unknown. Optional for the DLL. | -| 6 | 768 to 41,536 bytes | The RDNA2 program, at offset 0x100 in all 29. Required by the DLL. | -| 7 | 152 to 696 bytes | Resource and hash words, see below. Optional for the DLL. | - -### How the DLL reads it - -The DLL's reader (RVA 0x1a20, read from the DLL) clamps the total to the buffer, then returns: - -- 1 for a null or shorter-than-16-byte buffer, 2 when the magic is not `FSPX`, -- 4 when `16 + 16 * count` does not fit the total, -- 5 when kind 0 or kind 6 is missing or empty, else 0. - -It skips an entry whose range starts inside the directory or ends past the total, and keeps the last entry of each -kind 0, 1, 6 and 7; other kinds are ignored. `tools/fspx_unpack.py`'s `parse_fspx` follows the same rules and codes. - -The pipeline function (RVA 0x4aa0, read from the DLL) accepts either a bare `FSPX` payload or a `DXBC` container whose -`ACCC` part is one. It copies kind 6 into an `XMemAlloc` block (size rounded up to 256 bytes, attributes -`0xa8004000`) and calls device slot 67 with: - -| Offset | Field | -|---|---| -| +0x00 | root signature | -| +0x08, +0x10 | kind 0 pointer, size | -| +0x18, +0x20 | kind 1 pointer, size | -| +0x28, +0x30 | the copied kind 6, its size | -| +0x38, +0x40 | kind 7 pointer, size | - -The size at `+0x30` is kind 6's own size, not the rounded allocation: the DLL rounds it into a separate register for -`XMemAlloc` and stores the original, which is also the copy's length (read from the DLL's code with `objdump`, `0x5649` to -`0x56d5`). So -the bytes at `+0x28` with that size are exactly kind 6, and their SHA-256 is the key below. - -**How the table was pinned** (read from the DLL's code with `objdump`; checked by running the DLL's reader on all 29 -payloads): -- **The reader (`0x1a20`).** It zeroes four (pointer, size) pairs, then stores kind 0 in pair 0, kind 1 in pair 1, - kind 6 in pair 2 and kind 7 in pair 3 (`0x1bcb` to `0x1bfb`). Each pointer points into the payload itself. -- **The container branch (`0x5510` to `0x55ea`).** For a `DXBC` container the pipeline function runs the same loop - inline over the `ACCC` part and fills the same four places. Unlike the reader, it does not zero the kind-1 and - kind-7 places first; all 29 payloads have both kinds. -- **The copy into the description (`0x567d` to `0x56d5`).** Pair 0 goes to `+0x08`, pair 1 to `+0x18`, the kind-6 - copy to `+0x28` with pair 2's size at `+0x30`, and pair 3 to `+0x38`. -- **Code and state come from one payload.** Kind 0 and kind 6 of one call therefore always belong to the same - program, so the run-time lookup by code key and state key (below) has the pairing the build gives it. -- **Run.** A harness mapped the DLL without running it and called its reader on each of the 29 payloads. It built the - description that way and called slot 67 on the Vulkan device with the 26 programs translated on `main` at - `aa2988cc`: - - all 26 resolve to their own entry with their own state, and the other 3 are refused with `E_INVALIDARG`; - - the same on llvmpipe, the Ryzen 9 7950X3D's integrated GPU and the RX 7900 XTX (Mesa 26.3.1, under Wine). - -`d3d12_fspx_compute_test` builds its slot-67 descriptions the same way, from a container's own directory. - -**What happens when a program is not translated.** The DLL creates its pipelines one after another as a dispatch -needs them. When one of them has no translation, slot 67 fails, and so does the slot-62 fallback with the same -container. The DLL then records the null pipeline and faults at `0x65ff`, as on a PC device. The proxy logs every -failed slot-67 call with its number (`slot 67 call N failed`), because only the first call of a slot is announced. - -The DLL's own messages name that call `DeserializeComputePipelineStateX` and the path "ACO". When the call fails, -the message says it falls back to "NewBE", and the DLL sets the environment variable `FFX_FSR4_XBOX_ACO_ACTIVE` to -`0`. Its next pipeline call is slot 62 (measured in #864), so "NewBE" is inferred to be that path, the one a PC -device refuses (§3.5a). - -## Kind 0: dispatch state - -Seven u32 words. - -| Word | Meaning | How far it is checked | -|---|---|---| -| 0, 1 | Unknown | The same two values in all 29. | -| 2 | 0 | All 29. | -| 3 | `NumThreadsX` (bits 15..0), `NumThreadsY` (31..16) | Measured: equal to the container's `PSV0` thread-group size in all 29. | -| 4 | `NumThreadsZ` (15..0); bit 20 set = wave32 | Z measured against `PSV0` in all 29. Wave size: bit 20 is set in 24 programs and clear in 5, and nothing measured contradicts it (below the table). The translator takes it as the wave size. | -| 5 | `COMPUTE_PGM_RSRC1` | Inferred. `FLOAT_MODE` 0xC0, `DX10_CLAMP` and `MEM_ORDERED` in all 29. With a VGPR granule of 8 for wave32 and 4 for wave64, the highest VGPR the code uses is inside the allocation in all 21 programs that decode with no invalid word, at its last register in several. | -| 6 | `COMPUTE_PGM_RSRC2` | Inferred. `LDS_SIZE` covers the largest `ds_*` offset in all 29. `USER_SGPR` plus the enabled `TGID` SGPRs cover the SGPRs the code reads before writing them in 20 of those 21 (8 or 14 user SGPRs here). In the 21st, a wave64 program, the only SGPRs past them are the carry-out destination of a `v_add_co_ci_u32_e64`, which the check counted as a read. | - -`rdna2spirv.py` reads words 3, 4 and 6 from `fspx/.json` where it reads the FSSM header for a game compute -shader: the thread-group size, `RSRC2`, and the wave size from word 4 bit 20 (the `wave32` field). - -**Word 4 bit 20 is the wave size.** Over the 29 programs of 1.0.2.1 (`tests/semantic/test_fspx_wave_size.py` has -the rule): - -- **Strict markers (measured).** A strict wave64 marker (`rdna2spirv`'s `WAVE64_RE`: `exec_hi`, `v_mbcnt_hi`, - `*_saveexec_b64` and the 64-bit lane-mask SOP ops) is in 4 of the 5 programs with the bit clear and in none of the - 24 with it set. A wave32 marker (`*_saveexec_b32`, `*_wrexec_b32`) is in 4 programs with the bit set and in none - with it clear. -- **VGPR granule (measured).** In the 21 programs that decode with no invalid word, the highest VGPR is inside the - `RSRC1` allocation with the granule the bit gives (8 for wave32, 4 for wave64) in all 21. All 18 of those with the - bit set use a VGPR past what the wave64 granule would allocate. The 3 with the bit clear would fit either granule. -- **`PSV0` (measured).** Its expected wave lane counts are stated in 5 programs and agree with the bit in all 5 (64 in - 3 programs with it clear, 32 in 2 with it set); the other 24 leave them open (0 and the maximum). -- **Thread groups (measured; the reading is a hypothesis).** The programs with the bit clear have 64 or 256 threads - per group; 17 with it set have 32, which as one wave64 would leave half its lanes idle. -- **`_b64` ops on `vcc` are not markers (measured counts; the reading is a hypothesis).** The three wave32 programs - the old heuristic called wave64 write `vcc` from an SGPR pair with `s_mov_b64` (2 to 5 times each) and otherwise use - `vcc_lo` and `vcc_hi`, including `vcc_lo` as the lane mask of `v_cmp`/`v_cndmask`: `vcc` held as an ordinary pair. -- **The one program with no evidence beyond the bit.** It has the bit clear and no marker either way, and its highest - VGPR is the last register of the wave64 allocation, so the bit alone decides. - -A strict marker against the bit makes the translation refuse the program, as a contradicting FSSM header does. A -program whose kind 0 is too short for word 4 keeps the code heuristic. - -## Kind 6: the program - -- **Not compressed.** Each program holds exactly one `s_endpgm`, followed by padding (mostly `s_nop 0`). -- **A 36-byte prologue** comes first. It is three 12-byte VOP3 words with opcode 0x180 (bits 31..16 = `0xD580`), plus - literals. - - They carry the container's shader hash. Measured: the low halves of words 0 and 3 and the literals in words 2 and - 5 equal the 16 bytes after kind 7's `0x43` word, which are the digest in the container's `HASH` part, in all 29. - - `llvm-mc` rejects them. Measured on RDNA2 hardware (`gfx1031`, AMD Radeon RX 6700 XT, driver 26.11.2, through - `tools/fspx_prologue_probe.py` / `tools/hw_oracle`): in wave32 and wave64 across 5 synthetic 36-byte prologues - (50 positive checks and 8 negative controls), executing the raw words leaves VGPRs (`v0`, `v1`, `v8`..`v15`), - SGPRs (`s[0:1]`, `s4`..`s15`), `M0`, `VCC`, `EXEC` (including inactive lanes across 64 threads) and `SCC` (both 0 - and 1) unchanged, and execution resumes cleanly at `+36` bytes. So they are hardware no-ops on RDNA2. - - `tools/fspx_unpack.py` disassembles from the end of the prologue. -- **Target.** The programs use `v_dot4_i32_i8` (1,458 times) and `v_dot4c_i32_i8` (25,813 times), which fits the - provider's name (`FSR4_Int8`). `llvm-mc` (LLVM 23.1.5) decodes them for `gfx1011`, `gfx1012`, `gfx1030`, `gfx1031`, - `gfx1033`, `gfx1034` and `gfx1036`, but not for `gfx1010`, `gfx1013` (the target `shader_disasm.py` uses for the - game) or `gfx1100`. Measured on one 10,432-byte program, prologue included: 13 invalid words with the first group, - 1,276 with `gfx1010` and `gfx1013`, 1,290 with `gfx1100`. - - `fspx_unpack.py --disasm` defaults to `gfx1030`. -- **What llvm-mc still rejects.** With `gfx1030`, 21 of the 29 decode with no invalid word. The other 89 words, in 8 - programs, are all VOP3P opcode 0x16 with `op_sel` 2 and `op_sel_hi` 5. That is the opcode of the 1,458 - `v_dot4_i32_i8` that `llvm-mc` does decode, all of which have `op_sel` 0. - - Measured on RDNA2 hardware (gfx1036, through `tools/hw_oracle`, the instruction given as two raw words): with - `op_sel` 2 and `op_sel_hi` 5 the result is the dot product with the two 16-bit halves of the second source - exchanged, in all 5 operand sets (4 of them give another word under the plain rule). So `op_sel` selects halves - here as it does for the packed 16-bit ops. The words are in `tests/semantic/test_alu_dot4_i8.py`. - -## Kind 7: records - -- **Format.** It starts with the word `0x403` in all 29, and the words `0x41`, `0x42` and `0x43` appear in all 29. - That they tag records is inferred from the layout around them. -- **Records `0x41` and `0x42`.** The word 3 after each `0x41` or `0x42` is a register number: the 121 such numbers - in the 29 programs are all among the register numbers the container's `RTS0` declares (measured; the check ignores - the register class, so it is weaker than it looks). That the records list the resources the program uses is - inferred: in one program, checked by hand, a declared SRV does not appear. -- **Record `0x43`.** The 16 bytes after it are the container's shader hash (its `HASH` part), the value embedded in - the program's prologue. -- **Not read by the translator,** which does not read the game's FSSM binding table either. The programs load their - descriptors with `s_load` and `s_buffer_load`, as the game's shaders do; that this is all they need is inferred. - -## Build and run-time lookup - -**Build.** `make_game.py`'s `shaders` stage, after the game's own shaders, runs `tools/fspx_unpack.py --disasm` on -the package's `amd_fidelityfx_upscaler_xbox.dll` into `/shaders/fspx/` and `tools/rdna2spirv.py` on that -disassembly into `/shaders/spirv/fspx/`, with the same `--wave64-emulate` and fallback flags. Each index entry -of a program without an FSSM blob gets two keys (`tools/shader_meta.py`): - -- `fspx_code_sha256`, the SHA-256 of `fspx/.code`: the whole kind-6 entry, prologue and padding included; -- `fspx_state_sha256`, the SHA-256 of `fspx/.state`: the kind-0 entry (dispatch state) as it is. - -The same kind-6 bytes can come with different kind-0 entries, for example two thread-group sizes, and then translate -to different modules. Such a pair is allowed: the run time tells them apart by the state key. Two entries with the -same code key and the same state key must have identical modules; when they do not, the step fails and names both -programs, and leaves no `index.json` for the runtime to load. In the 1.0.2.1 DLL the 29 kind-6 programs are 29 -different byte strings, so every code key has one entry (measured). - -The step is redone as a whole when the DLL, the unpacking or translating tools, `llvm-mc`, the wave64 mode or the -flags change (`fspx_build.json`, written last); it never makes the game's shaders translate again. A package without -the DLL skips it. - -The executable calls slot 67 itself, for the compute pipelines of the pipeline library in `shaders.rpf` -([shader_library.md](shader_library.md)): a compute record's state blob, blob, program and layout blob have the sizes -and shapes of kinds 0, 1, 6 and 7. The next step of the same stage, `library_shaders`, unpacks those programs with -`tools/shader_library.py --stages cs` (which writes each one's `.code` and its record's state as `.state`) and -translates them into `/shaders/spirv/library/`, with the same keys, the same clash check and its own -`library_build.json`. - -**Run time.** `ShaderLibrary::load(dir)` (`runtime/src/shader_library.h`) reads `/index.json` and then, when they -are there, `/fspx/index.json`, `/bvh/index.json` ([embedded_shaders.md](embedded_shaders.md)), and -`/library/index.json`, whose entries are named `fspx/`, `bvh/`, and `library/`. A missing or -unreadable one leaves the others loaded. Entries are found by `fssm_sha256` or by `fspx_code_sha256`, in two separate -tables. -`compute_program()` decides what a compute PSO's bytecode is looked up by: - -| Bytecode | Key | Who passes it | -|---|---|---| -| `FSSM` blob, bare or in a `DXIL` part | `fssm_sha256` of the blob | the game (unchanged) | -| `DXBC` container whose `ACCC` part is an FSPX payload | `fspx_code_sha256` of its kind-6 bytes, then only the entries whose `fspx_state_sha256` is that of its kind-0 entry | the DLL, slot 62 | -| bare FSPX payload | the same two keys | the DLL's pipeline function accepts one (none measured at a slot) | -| bare kind-6 program: 4-byte multiple, at least 36 bytes, the prologue's words 0, 3 and 6 with bits 31..16 = `0xD580` | `fspx_code_sha256` of the bytes as they are; kind 0 is not passed | the slot-67 description at `+0x28`, size at `+0x30` | -| anything else | none: `E_INVALIDARG`, as before | | - -With kind 0 (the first two rows), an input whose state key matches no entry for its code key has no program and gets -`E_INVALIDARG`, like any untranslated shader. Without it (a bare kind-6 program), the entries for the code key are -used when they all have the same module; when their modules differ, the program is ambiguous without its kind-0 -state, so the call is refused with `E_INVALIDARG` and a log line saying so, instead of taking one of them. - -The payload is parsed with the DLL reader's rules above (sizes and offsets checked in 64-bit arithmetic against the -clamped total), so a malformed directory, or one without kind 0 or kind 6, gives no program and `E_INVALIDARG`. The -pipeline's code base, which a translated shader reads its embedded constants through, is the kind-6 bytes: the -translator's code offsets are into `fspx/.code`. - -**Slot 67.** The proxy maps slot 67's description onto `CreateComputePipelineState` (#1714). When kind 0 is in the -description, which the DLL always passes (its reader refuses a payload without one), the proxy builds one FSPX -payload from the four pointer and size pairs (`leonida::fspx_payload_from_parts`) and passes that as `CS`, the -bare-payload row above. Two programs with the same code and different dispatch state therefore stay apart at slot 67 -too. Each pair is checked before it is read: a pointer without a size or a size without a pointer, a size over -16 MiB, or a missing kind 6 refuses the call with `E_INVALIDARG`. Only a description without kind 0 still passes the -kind-6 bytes alone (the bare-program row). - -**Slot 11.** After either path the DLL calls the pipeline's console slot 11. The Vulkan device's pipeline answers -with a blob holding the dword 0, so the DLL creates no compute scratch buffer; why 0 is justified is in -[d3d12_command_objects.md](d3d12_command_objects.md) §3.5a. - -Not done here: using kind 0 at run time beyond what the translated module already carries (its thread-group size -and `RSRC2`). - -## Translation status - -With `tools/fspx_unpack.py --disasm` and `tools/rdna2spirv.py` on the 29 programs (`main` at `aa2988cc` with the -`v_fma_mix*` literal repair in [design.md](design.md), "Printed encodings"): -**Wave size.** On `main` at `aa2988cc`, `make_game.py`'s FSPX step translates 26 of the 29, and each now gets the -wave size of its dispatch state. Before, the code heuristic gave 4 of the 26 the other size: one wave64 program -was translated as wave32, and three wave32 programs as wave64, because they write `vcc` with `s_mov_b64`. The -translated and `spirv-val`-valid count is the same (26) either way. The breakdown below was measured when 17 translated. - -With `tools/fspx_unpack.py --disasm` and `tools/rdna2spirv.py` on the 29 programs: - -- **27 translate and pass `spirv-val`**, 11 of the 13 programs that use dot4 among them (design.md, "Signed-byte - dot products"). Without the repair, 26: the `v_fma_mix_f32` it is for is refused. -- **The other 2** (both use dot4) stop at a reachable `v_dot4_i32_i8` VOP3P word with `op_sel` 2 that `llvm-mc` does - not decode (the VOP3P words above). - -These counts predate SHADER-813. A program whose reachable code falls through into those undecodable VOP3P words used -to translate with the path cut at the gap, so its later stores were missing from a module that passed `spirv-val`; -it is now refused (`fall-through into undecodable words`): programs 04, 05, 06, 09, 12 and 15 of package 1.0.2.1 -(found by @aslan2142). Recount by @CuteBooty with LLVM 23.1.5 (gfx1030 listings, `spirv-val --target-env vulkan1.2`): -26 of 29 translated and passed before the change, **20 of 29** after it; the 20 kept give byte-identical SPIR-V, and -8 of the 9 refused stop at a fall-through into undecodable words. - -## Unknown - -- Kind 0 words 0 and 1. -- Kind 1. -- The exact layout of the kind-7 records. -- What the prologue does on the GPU. -- Whether the game itself ships FSPX programs. Its shaders measured so far are `FSSM`. diff --git a/docs/fssm_crosscheck.md b/docs/fssm_crosscheck.md deleted file mode 100644 index 7b85df1ea..000000000 --- a/docs/fssm_crosscheck.md +++ /dev/null @@ -1,254 +0,0 @@ -# FSSM / RDNA2 cross-check against SCARAB - -Status: facts checked 2026-11-21 against `p-portela/SCARAB` (`d304fa2`) and the Leonida -tree at `793b06f`. This note records **facts and measurements, not code**. SCARAB is -GPL-3.0-only; Leonida is GPL-3.0-or-later. No SCARAB code was copied. Any later code -adaptation needs the GPL-3.0 notice and attribution to Pedro Portela / SCARAB. - -The corpus used for the measurements is the local Leonida extraction: -**26,503 `.dxbc` containers and 26,503 decompressed `.fssm` blobs**. Only counts and -container fields are reported here; no game data is included. SCARAB's own counts -(25,321 extracted streams, 25,782 parseable blobs, 25,889 payloads) come from a different -title build and are not directly comparable. - -The short version: - -- The FSSM unwrap is **not the same** as `tools/fssm_unpack.py`. Leonida parses the XDAT - directory and selects tag `0x0D`; SCARAB scans for `XBCH`. Both are correct on the - common shape, but they disagree on duplicate entries (below). -- SCARAB's **code start is 24 bytes early**: on the Leonida corpus the code starts at - `u32[0xC0] + 0x28`, not `+0x10`. The bytes at `+0x10` are a fixed two-record descriptor. -- SCARAB's **"RDNA2 / gfx10.3"** label is not supported by the encoding. The stream decodes - as **gfx10.1.3 (`gfx1013`)**, the PS5/custom RDNA1.5 target; `gfx1030` is markedly worse. -- SCARAB's **"XBSC ISA"** is the name of the vendor DLL (`xbsc_xs.dll`), not a distinct ISA. - The extracted files are a 1,542-name AMD mnemonic list plus 856 prose sentences; they - contain no numeric encodings apart from the standard VOP3 base-plus-offset convention. -- SCARAB's family classifier is sound; its VOP1/VOP2/SOP1 **mnemonic tables and length - model** are not. Leonida's `llvm-mc` path is the better decoder. -- **Leonida bug found, since fixed:** `xdat_entries` kept only the last of a container's two - `0x0D` entries. 195/26,503 containers have two distinct `XBCH` payloads. #2479 added - `xdat_entries_all` and a `payload=` choice; `tests/test_fssm_crosscheck.py` pins both. - -## 1. Container and unwrap - -| Claim | SCARAB source | Leonida behaviour / measurement | Verdict | -|---|---|---|---| -| Outer file is a DXBC-shaped container; chunk table at `0x1C` (count) / `0x20` (offsets); chunks are `SFI0;ISG1;OSG1;PSV0;HASH;DXIL;PRIV`. | `components/shader-bridge/fssm_lib.py` docstring; `fssm_to_rdna2.py` docstring | 26,503/26,503 have exactly that chunk set; `fssm_unpack.parts()` uses the same table. | **Verified** | -| `DXIL` chunk payload starts with `u32 0x00010066`, `u32 0x61`, `DXIL`, `u32 0x106`, `containerSize`, `partCount`. | `fssm_lib.py` docstring | The first word is the DxilProgramHeader **ProgramVersion**, not a marker: `0x66` PS (12,101), `0x10066` VS (2,236), `0x20066` GS (195), `0x50066` CS (2,689), `0xD0066` MS (9,282). The next word is that shader's program-header **size** (0x61 in SCARAB's sample, not constant). `0x106` is constant, `0x10 == DXIL chunk size - 12`, `0x14 == part count` (3 or 4). | **Corrected** | -| `XDAT` holds the part table; `XBCH` is one of its sections. | `fssm_lib.py` docstring (describes `XDAT`, but the code scans for `XBCH` and never parses the directory) | `tools/fssm_unpack.py` parses `XDAT`: count/header at `+4/+8`, 12-byte entries at `+12`; tags `0x07` (DxilProgramHeader/NOBC), `0x0D` (XBCH), `0x12` (hash). 26,503/26,503 have that tag set. The header word is `0x24` (36) in all 26,503, but 195 containers have `count = 4` and a fourth entry beyond that declared header size; the count-based loop is what reads it. | **Corrected** | -| `XBCH` = fourcc, `u32 version=3`, `u32 compressedSize`, `u32 0`, `u32 uncompressedSize`, `u32 0`, then zlib. | `fssm_lib.py`, `fssm_to_rdna2.py` | 26,503/26,503: version 3; both zero words 0; `compressedSize == entry size - 24`; decompressed length `== uncompressedSize`; zlib magic `78 9c`; result starts `FSSM` v0x101. | **Verified** | -| The unwrap is a full chain `.dxbc -> DXIL chunk -> XBCH -> zlib -> FSSM`. | `fssm_lib.fssm_from_dxbc()` | `fssm_unpack.unpack()` does the same, but selects the `XBCH` by XDAT tag and checks the decompressed length. SCARAB scans for `XBCH` (the extractor additionally requires version 3) and does not check the length. | **Equivalent in result, different in mechanism** | -| A bare `FSSM` blob is accepted as input. | `fssm_to_rdna2.unwrap()` | `fssm_unpack.unpack()` accepts only `.dxbc`; the rest of Leonida (`shader_disasm.py`) accepts a bare `.fssm`. | **Minor input-form gap** | -| `FSSM` magic is asserted after decompression. | `fssm_lib.fssm_from_dxbc()` | `fssm_unpack.unpack()` also rejects a payload that doesn't start with `FSSM` (`ValueError`, counted as a problem, nothing written). All 26,503 are `FSSM`, so there is no corpus failure. | **Verified** | -| **Duplicate XDAT tag `0x0D`.** | `fssm_lib` / `fssm_to_rdna2` pick the **first** version-3 `XBCH` | `xdat_entries` was a dict, so the **last** tag-`0x0D` entry won. 195/26,503 containers (all `$VS_*` VoxelizeGeneric) have **two different** tag-`0x0D` payloads; the two FSSM payloads differ in code size and content. Since #2479 `xdat_entries_all` returns every entry in directory order and `unpack(payload=…)` picks one; `xdat_entries` keeps the last-wins view for old callers. | **Corrected — real Leonida bug, fixed in #2479** | - -### The duplicate-XBCH exception (the important one) - -`tools/fssm_unpack.py` does: - -```python -ents = {} -for k in range(count): - tag, off, size = ... - ents[tag] = dxil[off:off + size] -``` - -For the 195 `$VS_*` containers the directory holds two entries with tag `0x0D` (`count = 4`, -but the header word stays `0x24`, so the fourth entry is beyond the declared header size). -The first payload and the second payload both decompress to `FSSM` v0x101, but their code -differs. -In the measured pair the first is 3,679 bytes and starts with a GS/ES-like prologue -(`s_bfm_b64`, `s_barrier`, no `exp`); the second is 3,551 bytes and has two `exp` -instructions. The 24-byte descriptor at `code_off + 0x10` is identical in the measured -pairs, so they belong to the same container record. - -Leonida writes the second payload as `.fssm` by default; `fssm_unpack.py --payload first` -writes the first instead, which is the one SCARAB takes when it scans from the start. The -default is unchanged, so the two projects still extract **different payloads** for these -containers unless that flag is passed. The authoritative mapping (which payload the game's -pipeline uses) is not established here. - -Covered by `tests/test_fssm_crosscheck.py::DuplicateXbchTest`: -`test_xdat_entries_all_preserves_both_payloads_in_order` pins the directory order, -`test_xdat_entries_keeps_the_last_payload_per_tag` the compatibility view, and -`test_unpack_selects_first_or_last_payload` the `payload=` choice. - -## 2. FSSM header and code range - -| Claim | SCARAB source | Leonida behaviour / measurement | Verdict | -|---|---|---|---| -| `0x00 FSSM`, `0x04 u32 0x101`, `0x08 u64 len-16`, `0x10 u64 6`. | `fssm_parse.py`, `docs/fssm-analysis.md` | 26,503/26,503 match all four. | **Verified** | -| `0xC0 u64 code_off`, `0xC8 u64 code_size`, `0xE8 u64 code_end`, `0xF0 u64 meta_ptr`. | `fssm_parse.py` | Same fields. `code_off` is 8-aligned: 11,971 blobs are `0 mod 16`, 14,532 are `8 mod 16`. `code_size` is `0 mod 16` in all 26,503. `meta_ptr` is `0xDEADBEEFDEADBEEF` in 635. | **Verified** | -| `code_end == code_off + code_size` in 99.9%. | `fssm_parse.is_code_consistent()`, `docs/fssm-analysis.md` | 26,486/26,503. The 17 exceptions are not malformed: `code_end` is the `0xDEADBEEFDEADBEEF` "unset" sentinel. `code_off + code_size` is still valid in all 17. SCARAB's `fssm_to_rdna2.code_words()` uses `code_end` as the slice end, so for these 17 it would read from `code_off + 0x10` to EOF, including the metadata and name record. | **Verified claim; exception missing** | -| `code_off + 0x00..0x10` is a 16-byte sub-header, `code_off + 0x10` is raw instructions. | `fssm_parse.py`, `fssm_to_rdna2.py`, `include/shader_bridge.h`, `docs/fssm-analysis.md`, `docs/shader-abi-notes.md` | **Wrong on this corpus.** The code starts at `code_off + 0x28`. `code_off + 0x10..0x28` is a fixed 24-byte block: dwords 0 and 3 have `0xD580` in their high 16 bits in 26,503/26,503; dwords 1 and 4 are `0x03FE0000` or `0x03FF0000`; dwords 2 and 5 vary. LLVM rejects the single word at `+0x10` in 100/100 sampled blobs; the single word at `+0x28` is a valid one-word instruction in 100/100. The family census over all 26,503 gives SOPP 25,715 (all opcode 32 = `s_inst_prefetch`) and SOP1 788 (all opcode 4 = `s_swappc_b64`). | **Corrected** | -| The 16-byte sub-header is `(0,0,0,0)` or `(8,1,0,0)`. | `fssm_to_rdna2.py` docstring, `fssm_parse.py` | Those two values cover 14,965/26,503 (56.5%). Other common values: `(0x2110080,8,0,0)` 8,119, `(1,1,0,0)` 1,794, `(0x2100080,8,0,0)` 767. The tuple is not a two-value enum. | **Incomplete** | -| `0x18`/`0x20` are sentinel-filled slots. | `docs/fssm-analysis.md` | Both are `0xDEADBEEFDEADBEEF` in 26,503/26,503. | **Verified** | -| `0x78` is a `(2,N)` pair; `0x80` is `0x44`/`0x45`. | `docs/fssm-analysis.md` | `0x78` low word is `2` in all; high word is `0` (14,532), `2` (9,282), or `3` (2,689). `0x80` is `0x44` (17,221) or `0x45` (9,282). | **Verified** | -| Code is padded with `0xBF9F0000` (`s_code_end`) up to `code_end`; `code_end` is the code end. | `fssm_parse.py`, `fssm_to_rdna2.py` | The last `s_endpgm` is immediately followed by a run of `s_code_end` words up to `code_end` in 26,486/26,486 valid blobs. The last `s_endpgm` is the real program end; the filler is not code. Leonida stops at the last `s_endpgm`, SCARAB includes the filler. | **Behavioural difference; Leonida's end is cleaner** | -| Multiple programs per blob. | Not stated in SCARAB; `branch_report` walks the whole section | In the code range of the 26,486 blobs with a valid `code_end`: `s_endpgm` count is 1 in 18,558; 2 in 5,799; 3 in 1,535; 4 in 232; 5+ in 362. Leonida's last-`s_endpgm` range covers all of them. | **Missing fact in SCARAB** | -| The post-`code_end` tail is 16 bytes of `0xBF9F0000` filler, a u32 header and a zero word, a 20-byte-record table ended by `0xFFFFFFFF`, then `u32 0, u16 0, u16 len, name`. | `fssm_header.binding_table` | 26,503/26,503 blobs parse. 5,640,704 records (mean 212.8, max 385, 17 empty). Header is 4 in 24,572, 3 in 1,914 and 0 in the 17 `code_end = DEAD` blobs. The tail name is a substring of the container name in all 26,503 cases, exact in 691. At least 40 bytes follow the name and are not parsed. | **Verified; layout corrected** | - -### Why `+0x28` matters - -SCARAB's extractor emits `payload[code_off + 0x10 : code_end]`. On the Leonida corpus -that is 6 dwords of the fixed descriptor followed by the real program, then 28-42+ -`s_code_end` filler dwords. The descriptor is not harmless padding: its first word fails -LLVM in 100/100 sampled blobs, so it changes the first decoded instruction and the -instruction count. SCARAB's observation that its walk is "never lower" than the vendor is -consistent with this: both decoders see the same extra 6 words, and the filler adds more. -The constant 0x18 shift does not invalidate relative branch targets, which is why -`branch_report` still looks healthy. - -Leonida's rule is `u32[0xC0] + 0x28` to the last `s_endpgm` (also `docs/design.md`, -"Disassembling shaders"). The 17 `code_end = DEAD` blobs are handled because the last -`s_endpgm` is used instead of `code_end`. - -### Initial float mode (SHADER-190) - -The 1.0.2.1 scan tested 88 aligned little-endian words in each of the 26,503 indexed FSSM blobs as possible -packed `PGM_RSRC1` registers carrying `FLOAT_MODE`, `DX10_CLAMP` and `IEEE`. It covered 78 word starts at -FSSM offsets `0x00` through `0x134` and 10 at `code_off + 0x00` through `code_off + 0x24`, inclusive. -Local Python scripts walked the exported DXBC `index.json`, opened the matching `fssm/.fssm` for each row, -and read each candidate with `struct.unpack_from("\carve\common -``` - -Its `index.json` has `off`, `stored`, `size`, `pre` and `head` per stream. The `.bin` files are named by -offset and are **zlib streams, not files**. RPF9 splits a large file into 64 KiB inflated blocks, each with -its own zlib stream. A logical XML document is the concatenation of consecutive streams until its root element -closes; 178 of the 257 header-bearing documents are one stream, and the largest document spans 218. - -`tools/gamedata_index.py` groups those blocks into payloads and writes an offset/size/type/root index: - -```powershell -python -I tools/gamedata_index.py \carve\common --csv common.csv --json common.json -``` - -The CSV/JSON contain offsets, sizes, the coarse type and the XML root element. They contain no element values -or entry names, but they are still local work products and must not be committed or attached to an issue. -`--csv` and `--json` refuse a path that would replace the carve's `index.json` or one of its -`.bin`/`.bk2` streams, so a report cannot be written over a carved input. - -### Coverage - -| Measure | Value | Share of data span | -|---|---:|---:| -| Data span (file size minus header) | 6,603,920 B | 100.0% | -| zlib streams | 954 | - | -| Stored stream bytes | 5,647,255 B | 85.5% | -| Inflated bytes | 50,231,123 B | 8.9x the stored bytes | -| Zero padding | 386,138 B | 5.8% | -| Unread bytes | 570,527 B | 8.6% | - -The earlier 781-stream / 39.5 MB / 87.3% figure came from the carver that advanced by the 1 MiB read request. -It counted skipped regions as part of the preceding stream, so its stored-byte total was too high and its -inflated total was too low. The fixed carver finds 173 more streams and 10.7 MB more data; its stored total is -lower because it measures each zlib stream's real end. Treat the old figures as superseded. - -The 8.6% unread region is the non-zero gaps between streams: high-entropy bytes that do not decode as complete -zlib streams. Some contain a zlib header but fail the Adler check or are truncated. This is why 9 XML documents -survive only from their closing half and one 64 KiB XML block has no recoverable root. The carve does not guess -their content. - -## Type split - -Stream-level split, using the requested classes. `other` is 2 `MHIU` payloads (38 streams), 1 `PAMH` and 1 -`SPS1`; there are no `RBF0`, `PSIN` or Bink 2 streams in this archive. - -| Type | Streams | Stored B | Inflated B | Logical payloads | -|---|---:|---:|---:|---:| -| XML (`\carve\levels --json levels.json -``` - -The tool prints one `PAMH census 64x64: ...` line and writes the per-group -counts. Only header fields and counts are written, never the height bytes. - -### Cross-check and Z mapping - -MHIU and PAMH cover slightly different boxes at different resolutions. -Sampling MHIU at the PAMH cell centres over their overlap gives a Pearson -correlation of **r = 0.861** for payload `0x144000` and **r = 0.870** for -`0x16E000` against the PAMH max layer. Mirrored or transposed orientations -give `r <= 0.64`. The land masks (`MHIU > 23` and `PAMH max > 110`) overlap -with **IoU 0.61**. Row 0 is therefore `bounds.min.y`, column 0 is -`bounds.min.x`, and the linear Z formula above is the same for both. - -The HMAP header and row-table rules were cross-checked against the public -[rage-formats](https://github.com/VIRUXE/rage-formats) reader (`Unlicense`) -and [gta-op/heightmap](https://github.com/gta-op/heightmap) (`MIT`); no code is -copied. The MHIU field offsets, the span checks and the Z correlation are -measured on this package. - -```powershell -python -I tools/gamedata_maps.py \carve\common --json maps.json -``` - -### Checksum and unknown fields - -- The `common.rpf` `PAMH` payload holds `0x1BBC8CED` at GTA V's `compressed` - offset, 0x08. The level tiles overlap this word with the coordinate label - described above. The common value is not CRC32, Adler32, FNV-1a, joaat32 or a hashlib - digest of the max/min arrays; it is reported as a flag word, not a proven - checksum. -- `MHIU` 0x28 is a `u8` default height, not a 32-bit word (ASSET-48). Its - value is 23 in both payloads, the same value the empty rows were measured - to hold, and the row cropping above uses it. A full scan of all 12 archives - of package 1.0.2.1 (every zlib stream inflated far enough to read its magic) - finds **2 MHIU payloads**, both in `common.rpf`, so N = 2 for the header - values; the cropping rule is measured over all 6,902 span ends. -- `MHIU` 0x29..0x2B differ between the two files and match none of CRC32, - Adler32, FNV-1/FNV-1a, joaat32 or an MD5/SHA-1/SHA-256/SHA3/BLAKE2 digest - (any 3-byte window, either byte order, or a 24-bit slice of the 32-bit - hashes) over the grid, the packed bytes, the row table, the header, the - body or the payload with 0x28..0x2B zeroed. They do not equal any count or - sum of the grid. They are most likely uninitialised struct padding after the - `u8` and are reported as `pad_29`; with N = 2 this is a hypothesis. - -## `SPS1` shader-preset table - -The single `SPS1` payload in `common.rpf` (`0x650000`, `43,791` B inflated, 1 stream) is the material shader-preset -lookup table (`tools/gamedata_sps1.py`), not an `"SPS1Z"` five-byte magic: - -| Offset | Type | Meaning | Measured in 1.0.2.1 `common.rpf` | -|---|---|---|---| -| `0x00` | `char[4]` | Magic | `"SPS1"` | -| `0x04` | `u32` | `entry_count` | `858` (`0x0000035A`; its low byte `0x5A == 'Z'` caused the old `"SPS1Z"` reading) | -| `0x08` | `entry[858]` | `{u8 preset_len, char preset[], u8 effect_len, char effect[], u8 render_bucket}` | `43,783` B consuming the entire payload to EOF (`0` extra bytes) | - -Measured over all **858** records and cross-checked against `shaders.rpf`'s two `SGD5` databases: - -- **Presets:** all `858` carry a unique case-insensitive `.sps` path (`8`..`51` bytes), split into `846` root - names and `12` one-folder paths with zero basename stem collisions. -- **100% `SGD5` target resolution:** all **858 of 858** records (`539 of 539` distinct target effects, `4`..`47` - bytes) match an effect in `shaders.rpf` `SGD5` Database 0 (`0x10E39`, `910` effects; `0` in Database 1). -- **Aliases:** `532` presets have `preset_stem == effect` and `326` alias a preset name onto a shared effect; only - `589` preset stems match an `SGD5` effect name directly (`269` preset stems are defined only in `SPS1`). -- **Default render buckets (`0..7`):** `0` (`401`), `1` (`161`), `2` (`101`), `3` (`162`), `4` (`1`), `5` (`1`), - `6` (`30`), `7` (`1`). `63` target effects span multiple buckets across their presets (`58` in `{0, 3}`, `2` in - `{0, 1, 3}`, `1` in `{1, 3}`, `1` in `{0, 1, 2, 3, 6, 7}`, and `1` in `{4, 5}` — the single bucket-`4` and bucket-`5` - presets both point to effect hash `0xFC34F08B`, matching [`models.md`](models.md#shader-render-buckets)). - -```powershell -python -I tools/gamedata_sps1.py \carve\common --shaders shaders.rpf --json sps1.json -``` - -Only counts, bucket distributions and `--preset-hash` hashes are written; preset and effect names stay local. - -## Grid atlases - -Four `GridAtlasInfo` documents describe world-space texture grids streamed by position. All four have the -same numeric fields; the rest are names (`type`, `clientSystemName`, tile prefix/suffix, fallback texture). - -| Field | Measured (identical in all 4) | -|---|---| -| `width`, `height` | 16,384 x 33,792 world units | -| `tileSize` | 512, so **32 x 66 = 2,112 tiles** | -| `origin` | the grid **centre** (see below) | -| `streamRadius` | 512 (one tile) | -| `zInflation` | 1,000 | -| `hasOwnGlobalFallback`, `useGlobalFallback` | true, true | -| `sectorOverrides/Item` | 1, with one sector at start (0, 0) and span (32, 66): the whole grid | - -The tile count is the only reading under which the sector override's span matches: 16,384 / 512 = 32 and -33,792 / 512 = 66, so `width`/`height` are world units, not tile or texel counts. - -Which corner `origin` names was tested against entity positions from a local index of map resources: 2,036,542 -placements from 23,361 resources at every LOD level, 2,011,519 of them in `levels.rpf` and the rest in the -minigame and story packs (x 0.1th to 99.9th percentile -9,955 to 4,577, y -8,096 to 9,440). This is a -different count from the 1,670,442 entities of the levels census in [world_census.md](world_census.md); it was -only used for the share below. With `origin` as the grid centre, 99.83% fall inside the grid; as the minimum -corner, 1.0%; as the top-left corner with y growing downwards, 82.5%. The `levels.rpf` subset alone gives the -same picture: 99.83%, 1.0% and 83.0%. The centre -reading also gives a minimum x of exactly -13,312, the `PAMH` heightmap's minimum x above. - -Tile names: the tile textures do exist, but none is named after the tile. Every tile carries only the grid's -`tileTextureNameSuffix` as its texture name, one tile per texture dictionary, and the dictionary names are not in -the data. That is why `tileTextureNamePrefix` spellings and the fallback names matched no archive entry or item name -in the earlier catalog search. `tools/world_grid_atlas.py` (below) finds them in the texture manifests of -`make_game.py --stages assets`. - -### What the four grids hold - -All four are water data. Every count below is in the tool's printed summary or is the named `--json` field; -`levels` and `textures` are `levels.rpf` and `textures.rpf`. - -| Grid (`clientSystemName`) | Tile texture | Tile dictionaries | Fallback (pixels per tile) | Placed | -|---|---|---:|---|---:| -| `WaterSystemHeightMap` | `watersystemheightmap`, 512 x 512 `R16_UNORM` | 738 in `levels` | 1024 x 2112 `R16_UNORM` (32) | 737 | -| `shorelinegrid1` | `shore_wave_placement_set1`, 256 x 256 `B8G8R8A8_UNORM` | 268 in `levels` | 1024 x 2112 `BC7_UNORM` (32) | 262 | -| `waterfogatlas` | `waterfog`, 128 x 128 `BC6H_UF16` | 1,313 in `textures` | 512 x 1056 `BC6H_UF16` (16) | 592 | -| `waterfogatlas2` | `waterfog2`, 128 x 128 `BC6H_UF16` | the same 1,313 | 512 x 1056 `BC6H_UF16` (16) | 592 | - -- Each `globalFallbackTextureName` is a mosaic of the whole 32 x 66 grid. Fallback image row 0 is the grid's north - edge (largest y, see the fit below), and cell = row * 32 + column. -- The two fog grids share their dictionaries: each of the 1,313 holds one `waterfog` and one `waterfog2`. -- `shared_minigame000` holds the `mapswap_tblux` sector-override fallback of all four grids (`sector_fallbacks`) - and a few more tiles (`tiles_in_other_archives`: 10 water height, 2 shoreline, 1 fog pair). They are counted - and printed, not placed. -- The water-height fallback has 1,134 constant cells of 2,112; its most common value, 20,480, covers 55.74% of the - pixels, and the values run from 20,470 to 49,247. - -### Placing the tiles - -A tile's cell is recovered by comparing it with its grid's fallback mosaic, then checked against archive order. - -- Water height and fog (`method: content`): each tile is point-sampled to the fallback's pixels per tile and - compared with every cell by mean absolute difference; the two fog textures of a dictionary are matched together. - An anchor is a tile with detail (standard deviation above 0.5) whose runner-up distance is at least twice the - best and 0.5 above it. 737 of 738 water-height tiles are anchors; the one flat tile stays unplaced. For fog, - 617 dictionaries have detail in either texture and 561 are anchors. -- Shoreline (`method: mask`): the fallback's most common colour, `(0, 128, 0, 128)`, is background. Tiles and cells - are compared by intersection over union of their feature masks (pixels more than 32 from the background), 264 - fallback cells have features and 6 tiles have none. The tiles, in archive order, are aligned to cells in text - order (next point) by a dynamic programme that maximises the summed overlap. A tile is placed when it overlaps - the cell it is aligned to: 262 are (median overlap 0.83, `overlap_median`), and the 6 unplaced ones are the 6 - without features. 208 tiles match one cell clearly without the order (best overlap more than 0.2 above the - runner-up); these are the shoreline anchors, and the alignment moves none of them - (`anchors_moved_by_alignment` 0). -- **Archive order:** the tile dictionaries are stored in the order of their cells sorted as text of the decimal - cell index (`sorted(cells, key=str)`). Ascending steps of the anchors in archive order (`anchor_order`): - -| Order of the cells | Water height | Fog | Shoreline | -|---|---:|---:|---:| -| text of the cell index | 736 / 736 | 560 / 560 | 207 / 207 | -| cell index as a number | 735 / 736 | 559 / 560 | 206 / 207 | -| text of `row_column` | 709 / 736 | 540 / 560 | 189 / 207 | -| text of `column_row` | 700 / 736 | 526 / 560 | 173 / 207 | - -Number order differs from text order only where the cell index changes its digit count. The one break of -number order in each grid is there: in the `--json` placements the three-digit cells (from 912 in water height) -are stored after the last four-digit cells, where text order puts them. The dictionary names most likely -contain the decimal cell index; with one deciding step per grid this is a strong hint, not a read name. -- Between two anchors, tiles are placed by archive order when their number equals the free cells between them - (`placed_by_order`): 31 fog tiles, none for water height. 721 fog dictionaries stay unplaced; 677 of them have - no detail in either texture (`unplaced_without_detail`), which content cannot place. -- Cross-check (`in_water_height_cells`, `anchors_in_water_height_cells`, `placed_by_order_in_water_height_cells`): - all 262 placed shoreline tiles and all 561 fog anchors lie in a cell that also has a water-height tile; of the - 31 fog tiles placed by order, 16 do. - -### Water-height values and `zInflation` - -The water-height values follow the ground. Over the fallback pixels above 36,000, a least-squares fit against the -`MHIU` terrain heights (`water_fit`) gives: - -| `MHIU` payload | Units per metre | Value at 0 m | r (north up) | r (south up) | -|---|---:|---:|---:|---:| -| `0x144000` | 40.81 | 32,947 | 0.9457 | -0.2193 | -| `0x16E000` | 40.97 | 32,815 | 0.9935 | -0.2187 | - -Reading row 0 as the south edge destroys the fit, which is why row 0 is north. Under the better fit, the -fallback's 20,470 to 49,247 is -301.3 to 401.1 m (`water_metres`), close to the `PAMH` Z box of -302 to 404 m. The -fit is consistent with a `R16_UNORM` value spread over -800 to 800 m (65,536 / 1,600 = 40.96 units per metre, 0 m -at 32,768). Under that reading the dominant 20,480 is -300 m, at the floor of the `PAMH` Z box (-302 m) and below -all ground in `MHIU` (-50 m), which would make it a "no water" value. Both readings are hypotheses: the scale comes from a fit, not from a field. - -`zInflation` was not observed at runtime. All four documents have origin z = 0 and `zInflation` 1,000, so if the -runtime turns each 2D tile into a box from origin z - 1,000 to origin z + 1,000 for its stream test, that box -covers every height the world data describes. The tool reports (`z_check`) that all 3 heightmap Z ranges in -`common.rpf` (`PAMH` -302 to 404 m, both `MHIU` -50 to 500 m) lie inside -1,000 to 1,000, and the water heights -above fall inside it as well. This is a consistency check of that reading, not a measurement of the runtime: -nothing here shows whether the box is used for the stream test, the camera, or something else. - -```powershell -python -I tools/rpf9_carve.py \common.rpf \carve\common -python -I tools/world_grid_atlas.py --carve \carve\common --json \grid_atlas.json -python -I tests/test_world_grid_atlas.py -``` - -The tool imports numpy and Pillow (Pillow decodes `BC6H`); its placement, ordering and fitting logic is plain -Python, and the tests of that part run on the standard library alone. The forward check in the tests builds four -synthetic grids with tiles at known cells, stored in text order, and requires every tile with content to come back -at its cell; stored in number order instead, the text-order check reports breaks. The `--json` file holds the cell -of every placed tile, derived from your own copy of the game: keep it local. - -The shoreline mask matcher can use a dependency-free Rust library for overlap ranking and order-constrained -alignment. Build it in the default Cargo target directory; the tool picks up the release library automatically. -Without a usable library, or with `LEONIDA_WORLD_ATLAS_NATIVE=0`, the NumPy/Python matcher still runs. This does -not change image decoding, mask extraction, the other grid matchers, or the report format. - -```powershell -cargo build --release --locked --offline --manifest-path tools/world_atlas_native/Cargo.toml -python -I tests/test_world_grid_atlas_native.py -``` - -Set `LEONIDA_WORLD_ATLAS_BENCHMARK=1` to include a synthetic benchmark. It times the matching kernel (including -Python-to-Rust packing) separately from the full mask report, where finding the background and extracting the -masks can dominate runtime. Neither test reads game files. - -### `TextureGridInfo` - -In the 1.0.2.1 exports, one content change set lists four grid metadata registrations and three candidate -archive paths as siblings. The list gives no per-grid archive assignment. The two fog grids share a tile -prefix, while the shore-wave and water-height grids each have a distinct prefix. A case-insensitive search -of the 30,516 other plain export blobs (30,520 total, excluding the four grid documents) found none of the -three prefixes or the grids' global or sector fallback names in ASCII or UTF-16LE. None of the three -archive filenames appeared as a loose file in the local package. The single catalog hash match above -remains uncorroborated. The tile payloads and the mapping from tile coordinates to archive entries remain -unverified. - -A fifth grid uses the same base fields: one `TextureGridInfo` document has `origin`, `width`, `height`, -`tileSize`, `streamRadius` and `zInflation`, plus a low- and a high-detail fallback name, but no sector -overrides. It is 32,768 x 32,768 units with the same 512 tile, so **64 x 64 tiles**, the same 512 stream -radius and the same 1,000 `zInflation`, around a different origin. Tested the same way, 100.00% of the -placements fall inside with `origin` as the centre, 0.01% as the minimum corner and 11.8% as the top-left -corner, so the centre convention holds for both document types. - -The tool looks up both fallback names of this document (`texture_grids`): `fallen_snow_cov_fallback_low` is in -`textures.rpf` and `fallen_snow_cov_fallback_high` is in none of the exported manifests. The document has no tile -name field, so the tool does not look for its tiles, and what this grid holds is not measured. - -## XML documents - -257 documents start with an XML declaration and all 257 parse as well-formed XML with a standard parser. -Nine more complete documents are visible only from their closing root tag because their first block was in -the unread region; 2 of those 9 still parse from their first retained byte, and 7 are truncated at the start. -One 64 KiB XML block has no root at all. That gives 266 recoverable documents and 118 distinct root elements. - -Size distribution of the 257 header-bearing documents: minimum 88 B, median 13,435 B, mean 165,603 B, -maximum 14,262,150 B. 59 are at most 1 KiB, 178 are at most 64 KiB, 3 exceed 1 MiB and the largest spans 218 -streams. 41 start with a UTF-8 BOM; 255 declare UTF-8 (214 uppercase, 41 lowercase), 2 omit the encoding -attribute, 11 say `standalone="yes"`, and the 412 comments are hand-edit notes. - -### Root elements - -| Root element | Documents | -|---|---:| -| `timecycle_modifier_data` | 49 | -| `CVehiclePoints` | 32 | -| `timecycle_keyframe_data` | 27 | -| `CDataFileMgr__ContentChangeSetDef` | 23 | -| `CTuningFile` | 10 | -| `CDamageDataManager` | 5 | -| `GridAtlasInfo` | 4 | -| `CCoverProcessorTuning` | 3 | -| `CDataFileMgr__ContentDef` | 2 | -| `CVehiclePerformanceMaps` | 2 | -| `CVehicleBoneOffsetsArray` | 2 | -| 107 other root elements | 107 | -| **total** | **266** | - -The repeated roots matter: a root element alone does not identify a file. There are 49 timecycle modifier -documents, 32 vehicle-point documents and so on. Original paths and names would have to come from the missing -table of contents. - -### Functional categories - -The 118 root elements group into these categories. Counts and bytes cover the 266 recoverable documents -(41.2 MiB), not the one unattributed block. - -| Category | Files | Inflated B | Roots | Representative root elements | -|---|---:|---:|---:|---| -| time, weather, sky, water | 87 | 17,339,011 | 13 | `timecycle_modifier_data`, `timecycle_keyframe_data`, `CContentsOfWeatherXmlFile`, `ShoreWavePlacementData` | -| vehicles, tyres, handling data | 45 | 19,618,605 | 12 | `CVehiclePoints`, `CVehicleBoneOffsetsArray`, `CTyreDataSet`, `CVehiclePerformanceMaps` | -| peds, schedules, appearance | 29 | 2,029,321 | 29 | `CPedScheduleInfoManager`, `CPedVariationBodyTypeManager`, `CPairedPedDataBlock`, `CEnergyConfigInfos` | -| tuning, parameters, effects | 28 | 343,601 | 14 | `CTuningFile`, `CCoverProcessorTuning`, `GridAtlasInfo`, `PatchConstants` | -| mount / content manifests | 25 | 450,316 | 2 | `CDataFileMgr__ContentChangeSetDef`, `CDataFileMgr__ContentDef` | -| world, navigation, map | 19 | 1,660,133 | 19 | `GameShape__Data__LocationNameLoopkup`, `PathingStyleData`, `CTrainConfigs`, `CHazardNodes` | -| combat and AI behaviour | 13 | 809,074 | 13 | `CCombatInfoMgr`, `CFiringPatternInfoManager`, `CFleeDecisionMakerData`, `Combat__GoalData__Store` | -| animation, poses, weapons | 6 | 162,778 | 6 | `WeaponAnimations__FullbodyControllerData`, `WeaponAnimations__ConfigData`, `CAimUpperBodyDataBlock` | -| damage | 5 | 485,482 | 1 | `CDamageDataManager` | -| audio, video, speech | 4 | 13,741 | 4 | `LandingPageVideos`, `CTVPlaylistContainer`, `naSpeechEventTypeBatchRequestParams` | -| missions, scenarios, respawn | 3 | 57,327 | 3 | `CDynamicScenarioManager`, `CMissions`, `Respawn__MetaData` | -| conversation | 2 | 250,000 | 2 | `CConversationList`, `CConversationDictionary` | -| **total** | **266** | **43,219,389** | **118** | | - -This archive has no root element for popcycle, weapon stats or handling. Weapon-related documents here cover -loadouts, combat references and animation configuration. Vehicle handling-style values appear under the -vehicle/tyre roots, and the remaining gameplay tables are not XML. Do not infer a full gameplay schema from -`common.rpf` alone. - -## Fog volumes - -Volumetric fog comes in two documents: `FogVolumeProfileList` (the media) and -`CScatteringTransmittance__FogVolumeListData` (placed volumes). Counts; no values or names. - -**Profiles** (`ProfileList/Item`, 43): `Name`, `UUID`, `Anisotropy`, `WaterDropletDensity`, -`DiffusionIntensity`, `ScatteringColorBlend`, `AbsorptionColorBlend`, `Scattering` and `Absorption` (`x y z`), -`IntExtMode`, plus optional `WaterDropletVariance` (8) and `WindDensityInfluence` (15). Names and UUIDs are -unique. `Scattering` and `Absorption` are within 0..1 per channel in 41 of 43. `IntExtMode` is 0 in 31 and 1 in 12. - -**Volumes** (`FogVolumeList/Item`, 14), 37 fields each: shape (`IsBox`, `Position`, `PositionOffset`, `Scale`, -`Rotation`, `Shear`, `Wedge`), falloff (`Falloff`, `FalloffCurve` and per-axis versions), two 3x3 matrices -(`RotationMtx`, `TransformMtx`, 9 numbers each), ambient/emissive intensity, noise and wind, `Scattering`, `Density`, -`Anisotropy`, `WaterDropletDensity`, `Color`, `BlendMode`, `IntExtMode`, `SortKey`, `ProfileIndex`, -`SecondaryProfileIndex`, `ProfileInterpolation`, `uuid` and `Name`. - -| Check | Result | -|---|---| -| `ProfileIndex` and `SecondaryProfileIndex` in `0..42` | 14 of 14 each: profiles are referenced by **list position**, not by UUID | -| Volume `uuid` equal to a profile `UUID` | 0 of 14 (separate id spaces) | -| Distinct profiles referenced | 2 of 43; primary equals secondary in 12; `ProfileInterpolation` is 0 in all 14 | -| `RotationMtx` and `TransformMtx` | identity in all 14, while `Rotation` is zero and `Scale` ranges 0.6 to 28 | -| `Shear` | zero in all 14 | -| `IsBox` | true in 13, false in 1 | -| `BlendMode` / `IntExtMode` | 0 or 1, seven each / 0 in all 14 | -| Positions | 7 at exactly (0, 0, 0); 8 distinct; all within x -2,093..30, y 0..803, z 0..109 | - -Two consequences for a loader. The stored matrices do not include `Scale`, so the volume transform has to be -built from `Position`, `Rotation` and `Scale` rather than read from `TransformMtx`. Profile indices are -positions in `ProfileList`, so its order must be kept. - -**Package-wide census (ASSET-308, `tools/fog_volumes.py`).** Scanning all `0x7a` resources (assembled via -`world_census.assemble`, up to 64 MiB and multi-stream, without a 256 KiB per-stream cutoff) in `packs.rpf`, -`levels.rpf`, `data.rpf`, and `story000.rpf`, plus bounded zlib-stream scans across the remaining package -archives (`common.rpf`, `anim.rpf`, `navmeshes.rpf`, `textures.rpf`, `script.rpf`, `story000_script.rpf`, -`core_restofworld.rpf`, `core_restofworld001.rpf`, `story000_restofworld.rpf`, `shared_minigame000.rpf`, -`core_bvh4.rpf`, `shared_minigame000_bvh4.rpf`, `appdata0.rpf`, `core_licenses_data.rpf`) for XML, RBF0, and -`0x7a` schemas matching `CScatteringTransmittance__FogVolumeListData` (`0x03073767`) or -`CScatteringTransmittance__FogVolume` (`0x81907918`) finds: - -- **`levels.rpf`** (`188,449` complete `0x7a`, `0` incomplete), **`data.rpf`** (`15,768` complete `0x7a`, `0` - incomplete — matching `docs/world.md` and `docs/page_directory.md` — plus `1,263` `RBF0`), **`story000.rpf`** - (`48,084` complete `0x7a`, `0` incomplete, plus `1` `RBF0`), and all other archives except `common.rpf` and - `packs.rpf`: **0** `FogVolumeListData` / `FogVolume` resources. -- **`common.rpf`**: remains the only archive with the XML `FogVolumeProfileList` (`0x236000`, 43 profiles) and - world-coordinate `CScatteringTransmittance__FogVolumeListData` (`0x64c000`, 14 volumes). -- **`packs.rpf`** (`4,678` complete `0x7a` resources assembled, `0` incomplete): **231 complete `0x7a` - resources** (`0x8ae9010..0xc120010`) containing **770 stored** `CScatteringTransmittance__FogVolume` - (`0x81907918`, 512 bytes, 45 members) records and **384 distinct serialized records**: - - **230 smaller resources** (`{1: 80, 2: 146, 3: 3, 4: 1}`, median `2`) carrying **385** stored records (`384` - distinct). - - **1 larger resource** carrying **385** stored records (`384` distinct) that match the 385 records from the 230 - smaller resources byte-for-byte (including multiplicities). - -| Check (`packs.rpf` 0x7a, 770 stored / 384 distinct across 231 resources) | Result (stored occurrences) | -|---|---| -| `Position` | `(0, 0, 0)` in all 770 (local-space attachments) | -| `PositionOffset` | non-zero in 766 of 770: X `-2.46..2.46`, Y `-9.20..20.62`, Z `-6.50..6.66` m | -| `Scale` | X `0.43..6.00`, Y `0.13..28.00`, Z `0.13..2.63` m | -| `Rotation` / `Shear` | non-zero in 82 / 388 of 770 | -| `RotationMtx` and `TransformMtx` | identity in all 770 (even where `Rotation` or `Shear` is non-zero) | -| `IsBox` (`+0x000`, `ty=0x01`) | `1` in 730, `0` in 40 | -| `BlendMode` / `IntExtMode` | `1` in all 770 / `1` in 760, `0` in 10 | -| `ProfileIndex` / `SecondaryProfileIndex` | `{0: 2, 10: 4, 12: 764}` (all in `0..42`) / `0` in all 770; `ProfileInterpolation` is 0 in all 770 | -| `Type` / `SortKey` | `{0: 768, 2: 2}` / `{0: 768, 10: 2}` | - -This resolves the earlier hypothesis: across all 188,449 complete `0x7a` resources in `levels.rpf`, none carries -`FogVolumeListData` or `FogVolume`. Instead, `packs.rpf` holds 231 resources totalling 770 stored local-space -records (384 distinct serialized 512-byte records: 385 in 230 per-asset resources duplicated by 385 in one larger -resource; `Position = 0`, non-zero `PositionOffset` and `Shear`, `IntExtMode = 1` in 760/770), and -`RotationMtx`/`TransformMtx` stay identity there too — confirming a loader must compose the volume transform from -`Position`, `PositionOffset`, `Rotation`, `Shear`, and `Scale`. Runtime placement identity, resource-relative -reference targets, and what `IntExtMode` and `BlendMode` select at runtime remain untested. -Not measured here (hypothesis): with half the volumes at the origin, two profiles in use and no interpolation, -this list looks like a sample or default set; the placed fog of the map is probably elsewhere (map resources -or another archive). - -**`IntExtMode` and `BlendMode` against placement and interiors (ASSET-312).** Measured on the same 14 volumes -(`common.rpf`, `CScatteringTransmittance__FogVolumeListData` at `0x64c000`) and on the interior positions of -`GameShape__Data__LocationNameLoopkup` (`InteriorNames`, 2,280 `Pos`; see [world.md](world.md)), both read with -`tools/gamedata_reader.py --root --out `. That document gives interior points, not bounds; no -document in `common.rpf` stores interior extents (the `CMloArchetypeDef` bounds in `levels.rpf` are in interior -space and need the placing instance). So containment cannot be tested: what is measured is only the distance -from a volume centre (`Position` + `PositionOffset`) to the nearest interior point, and a point nearby would not -show that a volume is inside an interior. - -| Field value | Volumes | `Position` | Nearest interior point | Within 100 m of one | -|---|---|---|---|---| -| `BlendMode` 0 | 7 | world coordinates, none at the origin | 117.48 to 230.16 m | 0 | -| `BlendMode` 1 | 7 | exactly (0, 0, 0) in all 7, offset only | unknown (parent transform not known) | unknown | -| `IntExtMode` 0 | 14 | both groups above | as above | 0 of the 7 world-placed | - -- `BlendMode` splits the list exactly by placement: 0 on the 7 world-placed volumes, 1 on the 7 at the origin. - The world position of those 7 is unknown: their offsets are local to a parent this document does not name. - #3873 reports `BlendMode` 1 on the 385 local-space records of `packs.rpf`; that counts record occurrences in - one representation of the pack block, so it agrees with the split without being independent placement - evidence. Hypothesis: 1 marks a volume attached to (and blended with) a parent transform; what it does in the - renderer is not measured. -- `IntExtMode` cannot be correlated here: it is 0 in all 14, and none of the 7 world-placed centres is near an - interior point. The 2 volumes that use a profile with `IntExtMode` 1 (`ProfileIndex` 10) are origin volumes - with `IntExtMode` 0, so the volume field does not copy the profile's. Whether 1 means interior stays a - hypothesis; deciding it needs world-placed volumes with `IntExtMode` 1 and placed interior bounds. - -## Schema style - -Four patterns cover almost everything: - -1. **Mount/content manifests.** `CDataFileMgr__ContentChangeSetDef` has ``, optional registration/map - fields, a `` of `` with `` and ``, plus flags and map phases. - `CDataFileMgr__ContentDef` is the companion content description. There are 25 such documents and 3,315 - `` elements in total. The path tokens are `$(common)`, `$(target)` and `platform:/`; no XInclude - is used. -2. **Typed object graphs.** `CCombatInfoMgr` and the conversations/damage roots use ``. - Fields are usually child elements, scalars use `value="..."`, and enums are bare text. Across the 259 - parseable documents there are 428,611 elements, 5,293 distinct tag names, 318 distinct `type` values - (7,181 `type` attributes) and 33 distinct attribute names. The most common are `value` (84,585), `x`/`y` - (20,825 each), `content` (13,449), `key` (9,180), `type` (7,181), `name` (4,688) and `ref` (924). -3. **Compact numeric tables.** `CVehicleBoneOffsetsArray` stores `` - and `` as whitespace-separated numbers, with `numEntries` and - `bitsPerIndex`. `content` values seen: `short_array` (10,309), `float16_array` (2,481), - `float_array` (536), `matrix34` (46), `vector2_array` (40), `matrix33` (28), `vec3v_array` (9). - `CTyreDataSet` uses nested groups of named floats. These tables are why the largest single document is - 14.26 MB and spans 218 streams. -4. **Timecycle arrays.** `timecycle_modifier_data` has a version root attribute, `` records with - name/description/apply-tag/index/user-flag attributes, and parameter elements whose text is a - space-separated vector (`a b`, sometimes `a b c d`). Keyframe documents add ``/``/``. - This is not the `name=value` attribute style of pattern 2. - -A runtime consumer needs: - -- a UTF-8 XML parser that tolerates a BOM, CRLF, tabs, comments and inconsistent whitespace around `=`; -- a root-element dispatch table (118 roots, 5,293 tag names), or an RTTI/class-metadata bridge if the - executable's class names are available; -- a polymorphic `Item` type registry for `type=`; -- enum and symbolic-reference resolution: this archive uses symbolic `ref`/`key`/`name` strings - (924 `ref`, 9,180 `key`); only 28 `key` values look like 8-digit hex hashes, so a name registry matters more - than a joaat table here; -- whitespace-array and float16/packed-index decoders for the compact vehicle tables; -- a mount resolver for `$(common)`, `$(target)` and `platform:/` prefixes; -- streaming rather than whole-file parsing for the 14 MB table; -- strict handling of the 9 tail-only and 1 unattributed blocks: they are incomplete evidence, not documents - to guess at. - -## Custom clouds - -One `CustomClouds` document places individual weather clouds over the world. Counts and ranges; no values or -names: - -| Path | Count | Content | -|---|---:|---| -| `CustomCloudGroupList/Item` | 26 | `Name` (26 distinct), `Position` (`x`, `y`), `CustomCloudList` | -| `.../CustomCloudList/Item` | 630 | `Name` (429 distinct), `Position` (`x`, `y`), `Density`, `Rain`, `Fog`, `FogHeight`, `StrikeChance`, `BurstChance`, `CoverageMinMax` (`x`, `y`), and five booleans `Nimbus0`, `Nimbus1`, `Cumulus`, `Stratus`, `CirroStratus` | - -Measured over the 630 clouds: - -- **Positions are absolute world x/y.** Every group `Position` is (0, 0), so the group offset cannot be - distinguished from none, and cloud positions span x -33,515 to 28,596 and y -31,920 to 37,612. 386 of the 630 - fall inside the 2D box of the world grid atlases (x -13,312..3,072, y -9,216..24,576; #1180); 136 lie more than - 20,000 units from the origin, far outside the map placements. There is no z component. -- **Groups** hold 1 to 74 clouds (median 18). -- **Cloud types are flags, not weights.** Per cloud the number of `true` flags is 0 (91 clouds), 1 (418), 2 (55), - 3 (26), 4 (3) or 5 (37). Clouds per type: `Cumulus` 357, `Nimbus0` 158, `Nimbus1` 131, `CirroStratus` 84, - `Stratus` 73. -- **`CoverageMinMax` is a distance range, not a fraction**: min <= max in all 630, values 0 to 30,000, medians 200 - (min) and 2,000 (max), so it reads as an inner/outer radius in world units. -- `StrikeChance` and `BurstChance` are within 0..1 in all 630. `Rain` and `Fog` are within -1..1 (median 0), - `Density` within -100..100 (median 0.5) and `FogHeight` within -100..300. - -The cloud renderer's settings sit in one `STS_Config` document with 44 top-level sections: four cloud layers -(`Nimbus`, `Cumulus`, `Stratus`, `Alto`) that share one set of 13 fields (noise weights and blends, erosion, -density, lighting and multi-scattering density scale, shape fade, transition and altitude ranges, dilation, -noise displacement); six media (`GlobalFog`, `LocalFog`, `Rain`, `Clouds`, `CloudsCirrus`, `CloudsHaze`) that -share another set of 9; and 34 single-value or vector settings. Of the five cloud flags above, `Cumulus` and -`Stratus` match a layer name, `Nimbus0`/`Nimbus1` would both fall on the one `Nimbus` layer, and -`CirroStratus` has no layer of its own (`CloudsCirrus` is a medium, not a layer). The weather data's -`CloudType` has 14 distinct fractional values from 0.01 to 0.67 over the 25 weathers. - -### Custom-cloud map draw (ASSET-337) - -One atmospheric technique in the 1.0.2.1 shader dictionary lists a cloud-map compute pass, a custom-cloud -vertex/pixel draw and a cloud-density compute pass in consecutive entries, in that order. The density -program has two distinct resource rows whose compiled and authored name hashes match `CloudMapA` and -`CloudMapB`. Across the resource and constant-buffer member rows of all 932 effects and 26,503 programs, -neither hash column has an exact match for `Rain`, `Fog`, `Density`, `CoverageMinMax` or `CloudType`. - -The draw reads three consecutive words from a cloud record. They hold a half-precision coefficient and a -16-bit selector, two half-precision radii, and a half-precision center pair. For distance `d` from that -center in map coordinates and `outer > inner`, the pixel contribution before render-target blending is -`coefficient * clamp((outer - d) / (outer - inner), 0, 1)`. Selectors 0 through 3 route it to R, G, B -or A of the first target. Selector 4 writes it to both R and G of the second target. - -A Vulkan replay used the translated draw with synthetic records and blending disabled. Switching only the -coefficient from +0.75 to -0.75 reversed all 1,804 nonzero pixels exactly. A coefficient of -1 also produced -a negative contribution. Equal positive radii gave a hard edge at the sampled distances, all strictly inside -or outside the radius. Across fifteen 64×64 readbacks, the largest absolute error against the expected -pixel values was below 0.00048. - -The missing link is the producer that converts an XML cloud into these draw records. The world-to-map conversion -for `CoverageMinMax`, the fields that supply the coefficient and selector (including the two `Nimbus` flags), -and any handling of negative `Rain`, `Fog` or `Density` before the draw remain open. The replay also leaves -the live target formats, overlap blending, and the relationship between the weather's `CloudType` and the -two maps unmeasured. - -## XML catalog - -`tools/gamedata_xml.py` turns a carve into a per-file and per-root catalog. It is stdlib-only and rebuilds -multi-stream documents with `gamedata_index.py`, so it reads the same 267 XML payloads the index reports: - -```powershell -python -I tools/gamedata_xml.py \carve\common --json xml.json --csv xml.csv --check -``` - -The file rows carry offset/bytes/chunks, root, category, element count, maximum depth, attribute names, `$(name)` -and `platform:/` counts, include-like counts and the well-formed/fragment flags. The root rows add the -element-name and attribute histograms and the reference targets. `--check` separates a rootless fragment, a -tail-only document and a malformed document instead of treating all three as parse failures. - -Measured over the 267 payloads (43,284,925 B): - -| Measure | Value | -|---|---:| -| Well-formed | 259 (257 with a declaration, 2 complete without a declaration) | -| Truncated at the start | 7 | -| Rootless fragment | 1 | -| Malformed | 0 | -| Named roots / catalogued roots | 118 (+1 unattributed) / 118 | -| Elements / distinct element names | 428,611 / 5,293 | -| Attribute names / `type` values / `content` kinds | 33 / 318 / 7 | -| Maximum depth | 17 | -| Comment starts (all / declaration-bearing) | 507 / 412 | -| `filename` / `parentPath` / `parentFile` / XInclude | 3,315 / 40 / 3 / 0 | -| `platform:/` references (levels / other) | 2,674 (2,346 / 328) | -| `$(common)` / `$(root)` / `$(target)` references | 588 / 28 / 23 | - -Macro counts cover all element text; 587 of the 588 `$(common)` hits are in `` elements, which is the -filename-only bucket in the table above. - -The root and element distribution is the one in the tables above: the five repeated roots hold 141 of the 266 -documents, and the element histogram is dominated by the general node names `Item` (118,179), `item` (16,316) -and `Name` (12,850). The long tail is per-system parameter names; the manifest and timecycle names are a small -part of it. A category is a dispatch bucket, not a schema: for the 266 documents the catalog reproduces the -file and root counts in the functional table and assigns each root one category. No root has more than one -handler. - -Reference handling is narrow. Every `$(...)` and `platform:/` string is element text, not an attribute; no -document uses XInclude. The macro alphabet is `$(common)`, `$(target)` and `$(root)`, and the platform targets -split into `platform:/levels/` and everything else. `filename` is the only include-like element with a large -population; `parentPath`/`parentFile` are the only relative references outside it. A resolver therefore needs -four prefix rules and a content-set/mount walk, not a general include processor. - -A runtime dispatcher needs the 118-root table (or an RTTI class bridge), the 12 category buckets, the 318-value -`type` registry, the 33-name attribute whitelist, the `content=` array decoders and a streaming reader for the -14 MB document. The mount/reference half of that layer is measured separately in -[gamedata_graph.md](gamedata_graph.md): 25 manifest documents, 30 content-set ids, 12 resolved include edges -and 3,343 reachable target references. It also needs to mark the 9 tail-only documents and the one rootless -block as incomplete evidence: `gamedata_xml.py --check` is the reference for that split. The catalog is a local work product. Only -aggregate counts and schema/root/element/attribute names belong in git; the CSV/JSON, the element values, the -`type`/`content` values and per-file paths stay on the local machine. The tests are synthetic. - -## Weather types - -One `CContentsOfWeatherXmlFile` document defines the weather system. Element tree (counts per path; no values -or names): - -| Path | Count | Content | -|---|---:|---| -| `WeatherTimeCycleFileNames/Item` | 25 | one timecycle file path each, all with the same path prefix | -| `WeatherTypeDatas/Item` | 25 | `Name`, `TimeCycleName`, 72 numeric `value=` fields (wind, gusts, rain, snow, fog, sandstorm, ripples, ocean and shore waves, foam, puddles, accumulation), one-token `LocalizedDensityMap`, `CloudMapA` and `CloudMapB`, an empty `Variations` on all 25, and `PedDirtDefinition` / `DirtCannedColor` (set on 1 of 25) | -| `WeatherTypes/Item` | 168 | `Name`, `ShortName`, `DataName`, eight `Mod*` tags, `WeatherAppDataName` (151), `SkipDebugCycling` | -| `WeatherAppTypeDatas/Item` | 26 | `Name`, `Icon`, `IconNight` (23), `Background`, `Description` | -| `Mod*List/Item` | 73 | allowed tags: Atmosphere 17, Precipitation 16, Temperature 9, Humidity 5, Wind 11, Fetch 5, Misc 7, Niceness 3 | -| `WeatherCycles/Item` | 2 | `CycleName`, `TimeMult` | -| `WeatherTypeIndirectionList/Item` | 15 | `From`, `To` | -| `WeatherMiscData` | 1 | four `Honor*` thresholds and times | - -How the pieces link, checked by name (case-insensitive) over the archive: - -- **25 weather datas = 25 timecycles.** Every `WeatherTypeDatas/Item` has `TimeCycleName` equal to its own - `Name`, the 25 are distinct, and each matches the `cycle` `name` of one of the 27 `timecycle_keyframe_data` - documents. The 25 matched documents are exactly the ones with 1,142 variables per region; the two keyframe - documents with 515 and 520 variables are not referenced. All 25 file paths contain one of the 25 names; - 19 are in the same order as the data list. -- **168 weather types over 25 datas.** Every `WeatherTypes/Item` has a distinct `Name` and a `DataName` that - resolves to one of the 25 datas, and every data is used. A weather type is therefore a named variant of a - data entry, not a separate timecycle. 151 types carry all eight `Mod*` tags and a `WeatherAppDataName`; the - other 17 carry none, and 16 of those have `Name == DataName` (the plain base weathers). -- **Mod tags resolve to their lists**, with three exceptions: Atmosphere, Precipitation, Temperature, Humidity, - Fetch and Niceness resolve 151/151; Wind 150/151 (the miss is two characters from a list entry); Misc only - 14/151, because 137 types use one of two values that are not in `ModMiscList`. A loader should not reject a - type over an unknown `ModMisc`. -- `WeatherAppDataName` resolves 151/151 to `WeatherAppTypeDatas`. In the 15 indirection pairs, 14 `From` - and 14 `To` values are weather type names, and 13 pairs have both. -- The two `WeatherCycles` names occur in other `common.rpf` documents (2 and 1 documents), not as weather types. - -Measured further in [weather.md](weather.md): the `Mod*` axes against the numeric fields, the exact-case -vocabulary mismatches, `TimeMult`, and the `Honor*` values. - -## `OceanSimPresets` - -`tools/gamedata_xml.py` lists `OceanSimPresets` among the time/weather/water roots. There is one such document. -Its element tree (counts per path; no values or names): - -| Path | Count | Content | -|---|---:|---| -| `Presets/Item` | 10 | one preset per sea region | -| `Presets/Item/Name`, `Id` | 10 each | region label and id | -| `Presets/Item/Location` | 10 | `x`, `y`, `z` attributes in world units. The 10 elevations are distinct. Horizontal extents are x -7,995 to 3,183 and y -4,572 to 8,645. | -| `Presets/Item/Direction` | 10 | wave direction | -| `Presets/Item/Octaves/Item` | 30 | exactly 3 per preset | -| `Presets/Item/Octaves/Item/ControlPoints` | 30 | 4 `(x, y)` pairs each, both in 0..1 | -| `WavefrontShapeA`, `B`, `G`, `R` `/Item/ControlPoints` | 1 each | one curve each | - -The presets supply three octave curves per world position. A separate timecycle input, -`water_ocean_beaufort_scale`, occurs 676 times across 26 keyframe documents and ranges from 0 to 10. - -The authored curves and locations provide two controls for a runtime capture. - -- Hold position fixed at an authored site and compare the octave amplitudes at Beaufort 10. All 30 curves - have strictly increasing x and endpoints at x = 0 and x = 1. Under piecewise-linear interpolation, 19 - differ by more than 0.000001 between inputs 1 and 5/6, the predictions for division by 10 and by 12. - The other 11 are unsuitable as controls at that weather setting. The interpolation is an assumption of this test. -- Hold the normalized input at 1. In the horizontal (XY) plane, 11 of the 45 pairs of sites have a midpoint - closer to the pair than to any third site. At 49% and 51% along each of those 11 segments, the nearest site switches. In every - case at least one octave's endpoint amplitudes differ by more than 0.000001 across the pair. A hard - nearest-site rule predicts a step there. Samples approaching the midpoint from both sides can distinguish - that prediction from a continuous blend. -- To test whether elevation enters the selection, hold XY at one of those midpoints. Evaluate the 3D distance - first at one site's elevation and then at the other's. The unique nearest site switches for all 11 pairs. - A selector using only XY sees identical inputs for both measurements. - -The ocean simulation technique has six compute programs. Four declare the same nine constant-buffer members -in the same order and at the same byte offsets. In all four, the pipeline reflection binds one constant buffer -at `b5, space1`. The other two declare zero members and zero constant buffers. To reproduce the program -selection, run `python -I tools/sgd5_effects.py --effect OceanWaveSim --technique oceanWaveSim`. -Compare the member keys and offsets in each program's counted trailer against the other passes, then check -the constant-buffer register in its `PSV0` reflection. - -Which preset applies at a position, how Beaufort maps to the curve input, and what the four `WavefrontShape` -curves drive remain open. The reflected member keys give a concrete target for tracing the writer or comparing -dispatch inputs with position and weather varied independently. - -## Timecycle documents - -Two of the three most repeated roots are the timecycle tables: 27 `timecycle_keyframe_data` and 49 -`timecycle_modifier_data` documents. All 76 parse. Counts below; no values, modifier names or region names. - -**Keyframe documents** (root attribute `version`, the same value in all 27): - -| Path | Count | Content | -|---|---:|---| -| `cycle` | 27 | exactly one per document; attributes `name`, `description`, `regions` | -| `cycle/region` | 54 | exactly two per cycle; attribute `name` | -| `cycle/region/` | 59,170 | one element per variable, text = **13** space-separated numbers | - -Every one of the 59,170 variables has 13 values, the same as GTA V's 13 time-of-day samples, so a keyframe -document reads as one weather's day curve per variable and region. In 25 documents each region has -**1,142 variables**; the other two have 515 and 520. Within every document the two regions list the same -variables in the same order. The 1,142-variable set and the two short documents together use 1,301 distinct -names: 362 of the 521 short-document names are in the 1,142 set and 159 are not, so the short documents -follow an older or separate variable list rather than a prefix of the current one. A loader should therefore -bind variables by element name, not by position. - -**Modifier documents** (root attribute `version`, the same value in all 49): - -| Path | Count | Content | -|---|---:|---| -| `modifier` | 4,593 | attributes `name`, `description`, `groupApplyTag`, `localApplyIndex`, `userFlags` on all; 4,592 distinct names | -| `modifier/` | 29,738 | 29,727 hold 2 numbers, 11 are empty | -| `modifier/submodifiers/item` | 8,043 | in 1,928 modifiers (4 items is the usual count: 1,252); attributes `flags` (29), `alpha` (14), `blendSpeed` (3) | -| `modifier/axis` | 405 | in the 302 modifiers that carry `numAxes` and `numKeyframes`; attribute `controlValue` on all | -| `modifier/axis/keyframe_t_value` | 302 | exactly one per axis modifier (on one of its axes), `numKeyframes` numbers | -| `modifier/axis/` | 2,713 | `numKeyframes` numbers each | - -Modifiers come in two shapes: - -- **Plain** (4,291): variables are direct children with two numbers each, as in GTA V's modifier files. - Per modifier: 0 to 407 variables. 1,025 have none: 759 of those only list submodifiers and 266 are empty. The 1,054 modifier variable - names include 947 keyframe variables and 107 that occur only in modifiers. -- **Axis-driven** (302): every variable sits inside an `axis` and has exactly `numKeyframes` values; the axis's - `keyframe_t_value` lists the input positions (one list per modifier, even with several axes). All 2,713 axis variables match their modifier's - `numKeyframes`, and all 302 `keyframe_t_value` lists have that length and are sorted ascending. - `numAxes` is 1 (235), 2 (49) or 4 (18) and always equals the number of `axis` children - (`(numAxes, numKeyframes)` most often `(1, 6)`: 93), and `numKeyframes` ranges from - 2 to 25 (2 to 7 in 271 of the 302; 6 alone in 107). `controlValue` takes 43 distinct symbolic names, so the input is a named game - quantity rather than time of day. 61 axes add `input_min`/`input_max`, and 7 add `blendType`; 23 of the - 302 position lists fall outside `[input_min, input_max]` or, without those attributes, outside 0..1, so - the range is not a clamp on the stored positions. - -`submodifiers/item` text is one token. 8,042 of the 8,043 items equal the `name` of a modifier in the same -49 documents, so a submodifier is a by-name reference to another modifier, with its own blend attributes. -The one unresolved item points outside this archive or at a document lost to the unread region. - -**Sample hours come from data.** One `time_data` document (root attributes `version` and `mode`) has exactly 13 -`sample` elements, each with `name`, `hour`, `uw_tc_mod` and `interpolation_type`, plus one `region`. The 13 -hours are integers from 0 to 22 in strictly increasing order, with gaps of 1 hour (7 times), 2 (twice), 3 (once) -and 4 (twice); `interpolation_type` is `EASE_LINEAR_IN` on 9 samples and `EASE_QUARTIC_INOUT` on 4, and all 13 -`uw_tc_mod` values are the same name, which resolves to one of the 4,592 modifier names. The `region` name equals one of the two keyframe -region names. So unlike GTA V, where the 13 sample times are compiled in, this build stores them in `time_data`; -their count matches the 13 values of every keyframe variable. The `interpolation_type` labels are stored metadata: -how the runtime selects the interval between two samples, and whether it applies the label, is not verified. - -The `hour` attributes of the 13 `sample` elements, in document order, are **0, 4, 5, 6, 7, 9, 12, 16, 18, 19, 20, -21, 22**. They come from the one `time_data` payload of the `common.rpf` carve, at archive offset 1,773,568 -(`0x1b1000`): a single zlib stream, 268 B stored and 1,370 B inflated. The samples at hours 4, 20, 21 and 22 -carry the `EASE_QUARTIC_INOUT` label. That value *i* of a keyframe variable belongs to sample *i* is a -hypothesis: it rests on the equal count and the document order, not on the executable. To export the sample -records as JSON from a carve (the CLI prints summary counts; the JSON is game data and stays local): - -``` -python -I tools/gamedata_reader.py /carve/common --root time_data --out -``` - -Not measured here (hypothesis): how the two regions are chosen at runtime, what the two plain-modifier numbers -are (GTA V reads them as a value pair blended by strength), and how `controlValue` maps onto game state. - -**The two plain-modifier numbers.** Measured over the 29,727 two-number variables of the plain modifiers -(1,051 variable names, 3,257 modifiers with at least one such variable): - -- The second number is `0` in 26,186 pairs (88 %) and `1` in 3,104; only 437 take another value. In 2,300 of - the 3,257 modifiers it is `0` on every variable, in 21 it repeats the first number on every variable, and - 936 mix. Per variable name, 624 names never have a non-zero second number (8,410 pairs), 83 always do - (1,289 pairs) and the other 344 vary from one modifier to the next. -- The pair is not an ordered range: the first number is larger in 20,833 pairs, smaller in 4,604 and equal in - 4,290. -- Where the second number is non-zero (3,541 pairs) it does not follow the first: Pearson correlation 0.009, - and the first is `0` in 570 of them. -- Against the keyframe documents (25,732 pairs with a second number of `0` whose name is also a keyframe - variable): `0` lies outside every value that variable takes in the 27 keyframe documents in 17,041 pairs, - but the first number is outside that range too in 15,183 of the same pairs. Plain-modifier values are not - bounded by the keyframe ranges, so this comparison does not tell what either number means. - -So `0` is the most frequent stored value of the second number. What it means, and how the runtime blends the -two numbers by strength, is not settled by these counts. - -Not measured here (hypothesis): the hour of each of the 13 samples (GTA V's are fixed in code), how the two -regions are chosen at runtime, what the two plain-modifier numbers mean and how the runtime blends them (see -above), and how `controlValue` maps onto game state. -**Plain-modifier number pairs `(a, b)`** (`tools/timecycle_pairs.py`, measured over all **29,727** two-number -elements in the 4,291 plain modifiers across all 49 `timecycle_modifier_data` documents): - -| Measure | First number (`a`) | Second number (`b`) | -|---|---:|---:| -| Range (`min .. max`, median) | `-31,869.0 .. 400,000.0` (`0.789439`) | `-3.0 .. 5,000.0` (`0.0`) | -| Distinct values (rounded to 6 dp) | 4,566 | 71 | -| `< 0` | 2,972 (10.0%) | 7 (0.02%) | -| `== 0` | 3,590 (12.1%) | 26,186 (88.1%) | -| `(0, 1)` | 10,230 (34.4%) | 88 (0.30%) | -| `== 1` | 6,973 (23.5%) | 3,104 (10.4%) | -| `> 1` | 5,962 (20.1%) | 342 (1.15%) | - -Three patterns establish what the pair stores (matching RAGE's two-float `tcModData` slot): - -1. **`a` carries the variable's value; `b` is zero (`0.0`) on 88.1% of entries.** Across the 1,051 distinct plain - variables, 624 always have `b == 0.0`, 75 always have `b == 1.0`, and 343 appear with both `b == 0.0` and - `b == 1.0` (272 of them mixed within a single document, and 579 modifiers mix `0` and `1` across their own - variables) with the same physical range in `a`. A loader that applied `lerp(base, a, strength * b)` uniformly - would discard 88.1% of all modifier entries. -2. **Fractional `b` in `(0, 1)` is a shared per-colour blend weight.** Only 18 variables ever take `b` outside - `{0, 1}`; 15 of them stay in `[0, 1]` (88 entries total). Across all **1,875 / 1,875** RGB triplets - (`*_r`/`*_g`/`*_b`) present in the same modifier, `b` is identical across all three channels (`1,554` with `0`, - `301` with `1`, `20` fractional — `0` mismatches). -3. **Only three variables take `b` outside `[0, 1]` (349 entries, all keyframe variables), where `(a, b)` is a - same-unit value/range pair:** `far_clip` (`172/172` with `b > 1`, `a` in `0..5,000`, `b` in `40..5,000`, - `a == b` in 110, `a == 0` in 54, `0 < a < b` in 7, `a > b` in 1), `fog_start` (`161` with `b > 1`, `7` with - `b < 0`, `a` in `-1,000..5,000`, `b` in `-3..5,000`, `a == b` in 94, `a < b` in 89, `a > b` in 7), and - `fog_isotropic_phase` (`a == b` in all `10/10`, `1.0..6.0`). - -Not measured here (hypothesis): the hour of each of the 13 samples (GTA V's are fixed in code), how the two -regions are chosen at runtime, the exact runtime rule distinguishing `b == 0` from `b == 1` on the 343 variables -where both occur, and how `controlValue` maps onto game state. -## Vehicle and tyre XML documents - -Four roots account for 37 of the 45 documents (4,547,932 inflated bytes) in the vehicles/tyres category: -`CVehiclePoints` (32), `CVehicleBoneOffsetsArray` (2), `CVehiclePerformanceMaps` (2), and `CTyreDataSet` (1). -All 37 parse cleanly with no truncation errors. Only counts, element/attribute names, encodings, and numeric -ranges are recorded below; no vehicle names or entry values are included. - -### `CVehiclePoints` (32 documents, 33,516 B) - -Each document fits in one stream (370 to 10,425 B, median 592 B) and holds one vehicle entry (31 distinct -`DefinitionName` values across the 32 documents; `DefinitionName` equals `ModelName` in all 32). Element tree: - -| Path | Count | Content | -|---|---:|---| -| `DefinitionName`, `ModelName` | 32 each | text identifier (equal in all 32) | -| `Flags`, `iNumBoardingPoints` | 32 each | `value="0"` in all 32 | -| `Points`, `Props`, `AuthoredMeshName` | 32 each | empty in all 32 | -| `fNavOverrideRecastCellSize` | 32 | `value=` float `0.0000..0.0625` (median `0.0312`, 4 distinct values) | -| `fMinPatchAreaBeforeCulling` | 31 | `value=` float `0.1000..4.0000` (median `1.0000`, 6 distinct values) | -| `fNavMaxHeightChange`, `fNavMinZDist` | 30 each | `value=` constant `0.35` and `0.50` | -| `fNavOverrideAgentRadius`, `fNavOverrideAgentHeight` | 30 each | `value=` `0.00..0.15` (4 values) and `0.00..1.20` (2 values) | -| `fNavOverrideRecastCellHeight` | 26 | `value=` `0.00..0.04` (2 values) | -| `ModDefs` / `ModDefs/Item` | 6 / 49 | 1 to 32 mod entries per document (median 4) | - -Every `ModDefs/Item` carries `ChassisModName` (49/49 non-empty), `PropsetExteriorModName` (35/49 non-empty), -`UtilityModName` (32/49 non-empty), `InteriorModName` (4/49 non-empty), and `CargoModName` (0/49 non-empty); -17 items also include `RoofModName` (8 non-empty). Cross-referencing `ModelName` against the two -`CVehiclePerformanceMaps` documents matches 20 keys in the watercraft map and 4 in the land/air map, matching -the navmesh-override fields used for walkable/boardable hulls and large vehicles. - -### `CVehicleBoneOffsetsArray` (2 documents, 4,303,883 B) - -Two documents share the `CVehicleBoneOffsetsArray` root (`boneOffsets/Item`, 2,481 entries total) with a clean -split between identifier fields: - -| Document | Inflated B | Streams | `boneOffsets/Item` | Identifier field | `attachBones/Item` per entry | `numEntries` per entry | -|---|---:|---:|---:|---|---:|---:| -| Doc 0 | 4,283,195 | 66 | 2,447 | `name` (2,447/2,447; `vehicleName` empty) | 8..3,200 (median 8; 66,128 total, 9,345 non-empty) | 24..9,600 (median 24; 740,376 total) | -| Doc 1 | 20,688 | 1 | 34 | `vehicleName` (34/34; `name` empty) | 4 in all 34 (136 total, all non-empty) | 12 in all 34 (408 total) | - -33 of Doc 1's 34 `vehicleName` entries match keys in `CVehiclePerformanceMaps` Doc 0 (0 in Doc 1). - -Each `boneOffsets/Item/offsets` block stores a palette-compressed float16 table with four elements: `numEntries` -(`value=`), `bitsPerIndex` (`value=`), `packedIndices` (`content="short_array"`), and `palette` -(`content="float16_array"`). Measured over all **2,481 / 2,481** tables (740,784 unpacked entries): - -- **`numEntries` divisibility:** exact multiple of `len(attachBones)` in all 2,481 entries (remainder 0) and exact - multiple of 12 in all 2,481 entries. `numEntries / len(attachBones)` is `3` in 2,319 entries (including all 34 - of Doc 1 — one 3-component vector per bone slot); the remaining 162 entries take multiples of 3 from `9` to - `1,200` (`9, 12, 27, 36, 48, 75, 108, 300, 1200`). -- **Bit width and palette:** `bitsPerIndex` is `1` (253 tables, palette length 2), `2` (1,951 tables, length - 3..4), `3` (258 tables, length 5..8), or `4` (19 tables, length 9..14) — always minimal for `len(palette)`. - Palette values span `-30.90625` to `2.542969`, with `0.0` present in 2,119/2,481 palettes. -- **Exact packing rule:** `packedIndices` holds 107,229 non-negative unsigned 16-bit integers (`0..65535`) - encoding a continuous **LSB-first bitstream** across 16-bit words. The array length equals - `floor(numEntries * bitsPerIndex / 16) + 1` in **2,481 / 2,481** tables (when `numEntries * bitsPerIndex` is a - multiple of 16 — 2,043 tables — the writer appends one trailing `0` word; all 2,043 trailing words and all - unused tail bits across all 2,481 tables are `0`). -- **Bounds check:** unpacking all 740,784 indices produces **0 out-of-bounds** palette indices. - -### `CVehiclePerformanceMaps` (2 documents, 133,848 B) - -Two documents with disjoint `Map/Item[@key]` sets (285 distinct keys total, 0 overlap). Every `Map/Item` carries -the exact same 10 scalar `value=` children: `topSpeed`, `accelZeroTwenty`, `accelZeroSixty`, `brakingSixtyZero`, -`turnRadius`, `maxGforceLateral`, `maxGforceSteering`, `idlePitchAngle`, `buoyancyOffsetZ`, and `takeOffSpeed`. - -| Document | Inflated B | Streams | Entries | Non-zero road braking/turn/G | Non-zero `buoyancyOffsetZ` | Non-zero `takeOffSpeed` | `topSpeed` range (median) | -|---|---:|---:|---:|---:|---:|---:|---| -| Doc 0 (land/air) | 117,808 | 2 | 251 | 203..223 | 0 | 10 (max `57.64`) | `0.00..115.96` (`45.32`) | -| Doc 1 (watercraft) | 16,040 | 1 | 34 | 0 | 34 (`-1.11..1.91`) | 1 (`21.54`) | `0.00..55.05` (`16.82`) | - -### `CTyreDataSet` (1 document, 76,685 B, 2 streams) - -One document containing 40 `TyreDataEntries/Item` records (40 distinct `key` attributes, max tree depth 5). Each -entry combines up to four nested parameter groups with 12 direct scalar `value=` fields: - -| Path under `TyreDataEntries/Item` | Present | Schema | -|---|---:|---| -| `roadPerformance` | 40 / 40 | 8 scalars: `fPeakSlipAngle`, `fAdhesionLimitAngle`, `fLateralFrictionMult`, `fPeakSlipRatio`, `fAdhesionLimitRatio`, `fLongitudinalFrictionMult`, `fPeakForceCoefficient`, `fSlidingForceCoefficient` | -| `offRoadPerformance` | 38 / 40 | identical 8-scalar schema (omitted on 2 entries) | -| `roadPenalties`, `offRoadPenalties` | 40 / 40 each | identical 6-scalar schema: `fMaterialTractionLoss`, `fMaterialRollingDragGain`, `fMaterialSinkDragGain`, `fMaterialSurfaceDragGain`, `fWetTractionLoss`, `fWetDragGain` | -| Direct scalars (required) | 40 / 40 each | `fLoadShapeVarianceScale`, `fDamageShapeVarianceScale`, `fDamageCoefficientScale`, `fOptimumTyreTemp` (all `100.0`), `fOptimumTyreTempRange` (all `100.0`), `fGripDropOffWithTemp` (`0.01..0.05`) | -| Direct scalars (optional) | 36..39 / 40 | `fPuncturedTyreGripReduction`, `fBurstTyreGripReduction`, `fTractionStiffnessSpeedMult`, `fTractionStiffnessSpeedCap` (39 each); `fLoadStability` (37); `fLoadSensitivity` (36) | -**Sample hours come from data.** One `time_data` document (root attributes `version` and `mode`) has exactly 13 -`sample` elements, each with `name`, `hour`, `uw_tc_mod` and `interpolation_type`, plus one `region`. The 13 -hours are integers from 0 to 22 in strictly increasing order, with gaps of 1 hour (7 times), 2 (twice), 3 (once) -and 4 (twice); `interpolation_type` is `EASE_LINEAR_IN` on 9 samples and `EASE_QUARTIC_INOUT` on 4, and all 13 -`uw_tc_mod` values are the same name, which resolves to one of the 4,592 modifier names. The `region` name equals one of the two keyframe -region names. So unlike GTA V, where the 13 sample times are compiled in, this build reads them (and the easing -between them) from `time_data`; their count matches the 13 values of every keyframe variable. - -Not measured here (hypothesis): how the two regions are chosen at runtime, the exact runtime rule distinguishing -`b == 0` from `b == 1` on the 343 plain-modifier variables where both occur (see *Plain-modifier number pairs* -above), and how `controlValue` maps onto game state. - -## Relationship to `data.rpf` and `script.rpf` - -| Archive | Size | Streams | Inflated | Dominant payloads | XML | `RBF0` | `PSIN` | -|---|---:|---:|---:|---|---:|---:|---:| -| `common.rpf` | 6.6 MB | 954 | 50.2 MB | XML/config, text, `MHIU`, `PAMH`, `SPS1` | 844 streams | 0 | 0 | -| `data.rpf` | 481.5 MB | 28,509 | 1,403.3 MB | models/GPU pages, 1,263 `RBF0`, 2,281 `PSIN`, 3,132 resource pages | 0 | 1,263 | 2,281 | -| `script.rpf` | 4.4 MB | 714 | 5.0 MB | 671 `PSIN` plus binary | 0 | 0 | 671 | - -There is **no XML, `RBF0` or `PSIN` duplication** between them: `common.rpf` contains no `RBF0`/`PSIN`, and -`data.rpf`/`script.rpf` have no XML documents at all — no stream starts as XML and no inflated stream contains -an XML declaration (the ten `<`-leading `data.rpf` streams are binary). This is a type-level and stream-start -check, not a byte hash of all 1.4 GB of inflated `data.rpf`; without the table of contents a duplicate stored -at a different block boundary would not be recognised. - -The manifests in `common.rpf` reference the other archives by path token, not by archive handle. Counted over -the 3,315 `` elements: - -| Reference bucket | Count | -|---|---:| -| `platform:/levels/` | 2,346 | -| `$(common)/` | 587 | -| other `platform:/` | 328 | -| relative/other | 31 | -| `$(target)/data/` | 23 | -| `$(target)/script/` | 0 | - -So `common.rpf` is the XML/config layer that mounts levels content and references 23 `data.rpf` paths; none -of its `` entries use the `script` token. It may still reference script content through non-path -content names, which this count does not cover. The 587 `$(common)/` entries are mostly movie paths (537 end -in `.bk2`), not XML. Of the 57 `.xml` path entries, 50 are under `$(common)/` and 7 are relative/other; none -are under `data/` or `script/`. A further 40 `parentPath` attributes are XPath-style -`../Item[@key='...']` steps that all resolve to sibling items inside their own document, so they need no table -of contents (see [gamedata_graph.md](gamedata_graph.md#what-the-locators-point-at)). No XInclude (`xi:include`) elements occur. - -## Shore wave placement - -The shore-break waves are placed by one `ShoreWavePlacementData` document, the coastline counterpart of -`OceanSimPresets`. Element tree (counts per path; no values): - -| Path | Count | Content | -|---|---:|---| -| `Context` | 1 | empty | -| `Patches/item` | 434 | `loop` and `waveType` (`value=`), then `ControlPoints` | -| `Patches/item/ControlPoints/item` | 7,839 | `position` and `direction` (`x`, `y`), `lateralCoord`, `maxDistance`, `amplitude` (`value=`) | - -Measured over the 434 patches and 7,839 points: - -- **Patches are open 2D polylines.** 2 to 124 points per patch (median 14), median spacing 9.5 world units. - `loop` is false on all 434; 11 patches still repeat their first point at the end. Positions span x -9,602 to - 2,335 and y -7,955 to 9,474, a larger box than the ten ocean preset locations. Positions have no z - component. -- **`waveType`** takes 5 values, used by 181, 147, 69, 31 and 6 patches. -- **`direction` is a unit vector** at every point (length 1.000 to three decimals). It runs across the polyline - rather than along it: the median |cos| between it and the local polyline tangent is 0.24 (quartiles 0.11 and - 0.44), consistent with a wave travelling across the line towards the shore. -- **`amplitude` is 1.0 at all 7,839 points**, so it carries no per-point variation in this build. The height - presumably comes from elsewhere, for example the per-weather `ShoreWaveAmplitude`, `ShoreWaveMinAmplitude`, - `ShoreWaveMaxAmplitude` and `ShoreWaveWindScale` fields of the `CContentsOfWeatherXmlFile` weather data - (its layout is documented in #1175). -- **`maxDistance`** ranges 3.0 to 120.4 (median 74.9): how far the wave runs from the line. -- **`lateralCoord`** is a float in -2.94..3.50 with 7,820 distinct values. It is a coordinate *along* the line, - not across it: within a patch it is linear in arc length (distance along the polyline from the first point), - `lateralCoord ≈ a + b × arc length`. - - The least-squares fit leaves a median largest residual of 0.012 per patch (90th percentile 0.059). - - The per-patch correlation with arc length has magnitude at least 0.994 on more than three quarters of the - patches. - - The rate is the same everywhere: |b| has a median of 0.00200 per world unit, so it changes by 1.0 every - 500 world units (median 500.4; 10th to 90th percentile 473 to 544). The median rate per `waveType` is 0.00199 - to 0.00202, so the wave type doesn't set it. - - It *decreases* along the point order: strictly on 416 of the 434 patches, and b < 0 on 426. Only 197 of the - 7,405 point-to-point steps go against the patch's direction, by a median of 0.018. (It is monotonic, just not - increasing; an earlier count here only tested increasing.) - - On those 426 patches, `direction` points to the left of the polyline, so the coordinate runs the same way - relative to the waves everywhere. - - The offset a spreads over -2.0 to 3.4 (median 0.70), and a whole patch changes it by a median of -0.33. So - neighbouring patches can continue one another rather than each starting at 0 (10 start within 1e-4 of 0). - - Hypothesis, from the shape rather than a consumer: a phase or texture coordinate along the coast that repeats - every 500 world units. -- **`waveType`** doesn't change `amplitude` (1.0 at every point of every type) or the `lateralCoord` rate, and the - types overlap across the map. What differs: - - Type 3 (147 patches) has the shortest reach: its `maxDistance` median is 64.6, with the only values below - 17 (down to 3.0). Types 0, 1 and 4 have medians of 72.4 to 78.1. - - The six type 2 patches lie in one area (patch centres x 358 to 1,560, y -1,685 to 6,041). The other types - span the whole coastline box. - -Not measured here: what the five `waveType` values select. Reach is the only measured difference besides type 2's -location; a consumer of the field would settle it. - -## Readable vs binary - -Readable: the 266 XML documents, 3 text/INI-like files, and the two `MHIU` 2048 x 2048 -heightmaps plus the `PAMH` max/min heightmap and the `SPS1` shader-preset table. The XML is ordinary text -and can be consumed by any parser. `tools/gamedata_maps.py` decodes the `MHIU` row table and -packed heights and the `PAMH` row table and max/min arrays, and `tools/gamedata_sps1.py` decodes the -`858`-entry `SPS1` preset table and joins it to `shaders.rpf`'s `SGD5` effect records. - -Not fully readable: the 8.6% unread span, the two opaque binary blobs, and the missing first blocks of the 9 -tail-only documents (their retained tails are readable but incomplete). The encrypted table of contents is -outside this work by rule; names and exact file boundaries stay unknown until a documented table reader exists. - -## Text and binary tables (`tools/gamedata_blobs.py`) - -`tools/gamedata_blobs.py` decodes all five non-XML text and binary payloads in `common.rpf` (counts and structural -bounds only; zero names or raw bytes): - -| Payload | Inflated B (streams) | Format & measured structure | -|---|---:|---| -| `0x64e000` (`.fx` preload list 0) | 24,285 (1) | `965` unique `.fx` lines (`0` comments, `0` folder separators): all **910 of 910** `shaders.rpf` `SGD5` Database 0 effect records appear in exact index order (`0..909`), plus `55` unshipped `.fx` names | -| `0x64f1c0` (`.fx` preload list 1) | 575 (1) | `22` unique `.fx` lines (`0` comments): all **22 of 22** match `SGD5` Database 1 (`0x10289C81`) in exact index order (`0..21`) | -| `0x640000` (`VFX_SETTINGS_FILE` `.dat`) | 117,176 (2) | `3,198` lines: `2,566` data lines (`2,537` ` ` pairs, `2` `key = value` lines, `27` multi-value rows of `5..24` tokens), `248` comments, `384` blanks (`13` of `122` distinct key prefixes, `381` data lines, match an `SGD5` Database 0 effect name) | -| `0xad000` (fixed table) | 1,038,100 (16) | `u32 count = 801` followed by `801 x 1,296` B records to EOF (`4 + 801 x 1,296 = 1,038,100` B, `0` trailing bytes). Every record opens with `{u32 w0, u32 w1, u32 w2, u32 w3}` where `(w0, w1) == (w2, w3)` in **801 of 801** (`801` distinct pairs) before an undecoded `1,280`-byte record body (arithmetic permits `64 x 20` B; sub-record layout is not decoded by the tool) | -| `0x23c000` (3-region spatial grid) | 3,274,036 (50) | **Region 1** (`0x000000..0x07FFFF`, `131,072` `u32` cells): `32` empty `0xC0000000` sentinels and `131,040` populated cells whose low 23 bits point (`131,040 / 131,040` aligned) into **Region 3** (`0x166934..0x31F533`, EOF `0x31F534`, `451,328` `u32` words partitioned by the `46,019` distinct cell offsets into spans of `1..24` words); located as the trailing run of 4-byte-aligned offsets matching `min(cell_offs)` (`0x166934`), with every word (`451,328 of 451,328`) falling in **Region 2** (`0x080000..0x166933`, `944,436` B partitioned with zero gaps into `21,662` records: `21,273` of `44` B, `313` of `24` B, `76` of `12` B) | - -```powershell -python -I tools/gamedata_blobs.py \carve\common --shaders shaders.rpf --json blobs.json -``` - -## Dirt and canned colours (`CGraphicsDefinitionsData`) - -One `CGraphicsDefinitionsData` document holds the dirt/grime presets for peds, vehicles and props and the -colour table they draw from. Seven sections, each a list of `Item key="..."` records (the table gives counts, -no values or names): - -| Section | Items | Fields per item | `key` | -|---|---:|---:|---| -| `CannedColors` | 44 | none: `x`, `y`, `z`, `w` attributes | text | -| `AlphaChannels` | 7 | `Name`, `Channels` (1 or 2 `Probability`/`Channel` pairs; 10 in total) | equals `Name` in 6 of 7 | -| `DirtDefinitions` | 24 | 25 (alpha curves and thresholds, vertex multipliers, normal/roughness/material contribution, spawn range, 6 `ClothHideDirtModifiers`) | equals `Name` in 22 of 24 | -| `VehDirtDefinitions` | 1 | 12, including a `DirtTunings` block of tile, detail-map, mud and modulate start/end values | equals `Name` | -| `VehDirtControls` | 5 | 13 | equals `Name` | -| `VehSpawnIntensities` | 31 | Name, `IntensitySets` (7 `Item`s of `DirtMin`/`DirtMax`/`MudMin`/`MudMax`), `DirtRainChance`, `DirtRainMin`, `DirtRainMax` | equals `Name` | -| `PropDirtDefinitions` | 9 | 4 | equals `Name` | - -The keys are plain text, not joaat hashes, and a loader can index each section by `key`. - -**Canned colours are 8-bit RGB.** In all 44, `x`, `y` and `z` are integers from 0 to 255 and `w` is -1, so -`w` is not alpha; read it as an unused component or "no alpha". - -**References** (case-insensitive equality with another section's `key` or `Name`): - -| Field | Resolves to | Count | -|---|---|---:| -| `DirtDefinitions/Item/ColorLookup` | `CannedColors` | 24 of 24 | -| `DirtDefinitions/Item/AlphaMasksLookup` | `AlphaChannels` | 18 of 24 (the other 6 are empty) | -| `VehDirtDefinitions/Item/ColorLookup` | `CannedColors` | 1 of 1 | -| `PropDirtDefinitions/Item/Color0Lookup`, `Color1Lookup`, `Color2Lookup` | `CannedColors` | 9 of 9 each | -| weather data `PedDirtDefinition` (see the weather document) | `DirtDefinitions` | 1 of 1 | -| weather data `DirtCannedColor` | none | 0 of 1 | - -So every dirt preset gets its colour from the canned table, and one weather selects a ped dirt preset. The -weather's `DirtCannedColor` is a single non-numeric token that matches no canned-colour key, even as a -substring; where it resolves is unknown. Other `common.rpf` documents share only a few short generic words -with the `VehSpawnIntensities` keys, which is not evidence of a reference. - -`AlphaChannels` probabilities do not sum to 1 in any of the 7 entries, so they are not a probability -distribution over the listed channels (independent chances or weights would fit). The `Channel` values are 0, 1 or 2. - -**`Channel` numbers the mask texture's channels in component order: 0 = R, 1 = G, 2 = B** (ASSET-304). The -dirt presets are ped presets, and `textures.rpf` holds one texture whose name marks it as the ped dirt masks -(1024×1024 BC7, 11 mips, next to the ped dirt normal/roughness map). `tools/mask_channels.py` on its export: - -| Channel | Range | Mean | Cover ≥ 64 / 128 | Blobs ≥ 64 / 128 | Largest blob ≥ 64 | -|---|---|---:|---:|---:|---:| -| R | 0-255 | 124.1 | 66.5% / 49.3% | 4,612 / 9,167 | 92.0% | -| G | 90-255 | 193.6 | 100% / 99.5% | 1 / 7 | 100% | -| B | 0-255 | 88.4 | 50.7% / 34.9% | 35,175 / 49,374 | 21.0% | -| A | 255 only | 255 | 100% | 1 | 100% | - -Alpha is constant, so the three `Channel` values can only be R, G and B; an order that counts alpha leaves one -value on a channel with nothing in it. G is a soft layer that never drops below 90, and the two entries whose names -describe a light dusty or urban grime use only `Channel` 1. R is a broad layer, one connected region at ≥ 64, and -the snow entry uses only 0. B is the speckled one, with 7.6 times R's blobs at ≥ 64, and the entry named for spots -uses only 2. The reversed order (0 = B) would put the spots on the broad layer and the snow on the speckled one. -The three mixed entries combine 0 and 2. Each tie is a name read against measured texture content, so this is -measured, not confirmed against the shader that samples the mask. - -Not measured here (hypothesis): how `VehSpawnIntensities` are chosen at spawn. -**Spawn intensities are keyed by vehicle class.** Measured on 2026-11-23 from one retail Xbox Series -1.0.2.1 install with `tools/veh_spawn_intensities.py` (numbers and ranges only; the tool never prints -entry names). The 31 entries are 30 generic vehicle-class tokens plus one entry whose rain fields differ -from every other chance-0.5 entry; each carries 7 intensity bands, so the section's own "5 fields" summary -is top-level children only: - -| Measure | Value | -|---|---| -| `IntensitySets` bands per entry | 7 in all 31 | -| distinct band signatures | 9, carrying 12, 8, 3, 2, 2, 1, 1, 1, 1 entries | -| band 7 ranges over the signatures | `DirtMin` 0.353400..0.804305, `DirtMax` 0.450900..1.240000 | -| mud (a `MudMin`/`MudMax` above zero) | in band 6 of 1 signature, band 7 of 6 signatures; everywhere it exists the range is 0.8..1.0 | -| bands overlap | yes: each band is a draw range, not a partition (band 1's `DirtMax` exceeds band 2's `DirtMin` in the largest signature) | -| `DirtRainChance` groups | 4: 0.5 in 24 entries (`DirtRainMin` 0.818644 except one at 0.7), 0.0 in 6, 0.3 in 1 | - -Band 1 to band 7 in the largest signature ladder through the same recurring endpoints -(0.007828, 0.174168, 0.391389, 0.485323, 0.659491, 0.804305), so a run draws its dirt intensity from one -of the seven ranges, and rain applies another random factor gated by `DirtRainChance`. Each entry has 7 -bands while `AlphaChannels` has 7 entries and `DirtDefinitions` references 5 of them; whether a spawn picks -one band per `AlphaChannels` entry is open. - -Not measured here (hypothesis): whether a spawn selects one `IntensitySets` band per `AlphaChannels` entry. - -## Entity component sets and component LOD - -Four documents describe which runtime components an entity gets and how far away each stays alive. Counts only; -no set or type names. - -| Root | Content | -|---|---| -| `CEntityComponentLodManagerData` | `EntityComponentCounts/Components/Item` x 33: `Type` (33 distinct) and `DesiredCount` (0 to 250, 2,684 in total; one type is 0), plus optional distance-scale factors for not-visible (5 and 2 items), interior (1) and deep-interior (1) entities and per-frame create/remove limits (4 and 2) | -| `CVehicleComponentSetManager` | 7 `CVehicleComponentSetInfo` sets with 11 to 14 components each (90 in all): `Type`, `MinDistance`, `MaxDistance` | -| `CPedComponentSetManager` | 15 `CPedComponentSetInfo` sets with 8 to 17 components each (173 in all), plus feature flags: `HasFacial` (true in 12), `HasRagdollConstraints` (13), `HasLookAt` (10), `HasInventory` (8), `HasPhone` (2), `HasReins` (1), `HasDistraction` (2 of 3 sets that carry it), `IsRidable` (false in all 15) | -| `CObjectComponentSetManager` | 1 `CObjectComponentSetInfo` set with an empty component list | - -Each manager has a `DefaultSet ref`, and all three refs name one of their own sets. - -**The component types form one closed list.** Vehicle sets use 14 distinct `Type`s and ped sets 18, with none -in common, and every one of the 32 is among the 33 types of `CEntityComponentLodManagerData`; only one LOD-manager -type is used by no set. So a runtime can treat the LOD manager's list as the component registry, with -`DesiredCount` as the pool size per type. - -**Distances.** `MinDistance <= MaxDistance` in all 263 components. Vehicle components reach up to 3,000 units -and ped components up to 200 (both medians 100); the natural reading is the range within which the component is kept -alive. - -Not measured here (hypothesis): whether the distances are metres from the camera or the player, and what the -not-visible and interior scale factors multiply. - -## Damage and tuning XML documents - -Three repeated roots in the top-ten table above cover the damage and tuning tables: `CDamageDataManager` (5 documents, -485,482 B), `CTuningFile` (10 documents, 27,718 B), and `CCoverProcessorTuning` (3 documents, 34,380 B). All 18 parse -cleanly. Counts and schemas only; no entry names or parameter values. - -### `CDamageDataManager` (5 documents, 485,482 B, 10 streams) - -Rather than repeating one table type, the five documents partition the damage system by sub-table: - -| Document | Inflated B | Streams | Top-level section | Measured structure | -|---|---:|---:|---|---| -| Doc 0 | 257,008 | 4 | `DamageCleanlinessDatas/Item` (5) | `25` `RegionData/Item` blocks (5 per entry) containing `528` keyed `WeaponData/Item` records (`key=`), with `616` `CleanlinessResults/Item` and `328` `CleanlinessResultsLegendary/Item` pairs `{MaxBulletHits, MaxDamageCleanliness}` | -| Doc 1, Doc 4 | 104,082 / 107,078 | 2 / 2 | `DamageModifiers/Item` (147 / 96) | `243` top-level modifiers across 19 polymorphic `CDamageModifier*` classes (`CDamageModifierMultiply` 63, `CDamageModifierMultiReference` 58, `CDamageModifierClamp` 39, `CDamageModifierFirstSuccessfulReference` 36, `CDamageModifierMulti` 19, `CDamageModifierInstantKill` 5, 13 others) and `336` nested `Modifiers/Item` entries, gated by `Condition` trees across 65 `CDamageCondition*` classes (`CDamageConditionAnd` 144, `CDamageConditionNot` 126, `CDamageConditionOr` 72, `CDamageConditionFromDamageType` 60, `CDamageConditionFromWeaponType` 49, `CDamageConditionIsPlayerBuddy` 44) | -| Doc 2 | 12,498 | 1 | `DismembermentData` (1) | Dismemberment thresholds and bone/region rules | -| Doc 3 | 4,816 | 1 | `HitReactData` (13), `HitReactGripData` (2) | Hit-reaction and weapon-grip impulse parameters | - -### `CTuningFile` (10 documents, 27,718 B) and `CCoverProcessorTuning` (3 documents, 34,380 B) - -- **`CTuningFile` (10 single-stream documents, 266 to 11,727 B, median 1,875 B):** each wraps a `` list of - polymorphic `` blocks (`14` items total across 14 distinct `type` classes, including - `CConversationManager__Tunables`, `CDeadeyeSpecialAbility__Tunables`, `CLasso__Tunables`, and - `CPlayerFocusSpecialAbility__Experimental__Tunables`). Sub-structures include `36` keyed - `EntityMaskConfig/EntityMaskProfiles/Item` records (`MaskValue` 4D `x/y/z/w`, `MaskValueExtras` 2D `x/y` on 33, - `BlendOutCurveType` on 4) and a nested `ClipSetTree` (`5` `TransportMotionHelpers__ClipsetTransportConditionNode` - branches over `8` `GameplayHelpers__ClipsetLeafNode` leaves). -- **`CCoverProcessorTuning` (3 single-stream documents: 11,554, 11,422, and 11,404 B):** flat scalar tables with - `212`, `211`, and `210` direct `value=` children per document (`fAdditionalDistanceFromTreeToRejectAdditionalCoverpoints`, - `fAICanAimSweepCount`, `fCornerCoverPointDotThreshold`, `fCornerDistanceCheckResolutionFine`, etc.). - -## Combat, AI behaviour and weapon animation documents - -The representative roots of the combat/AI (13 documents, 809,074 B) and weapon-animation (6 documents, 162,778 B) -categories use typed polymorphic `` and keyed map tables: - -| Root | Inflated B (streams) | Status | Measured schema | -|---|---:|---|---| -| `CCombatInfoMgr` | 237,621 (4) | well-formed | `CombatInfos/Item` × 66 (`type="CCombatInfo"`), each with `Name`, `CombatMovement`, `BehaviourFlags`, `CombatAbility`, `AttackRanges`, `CoverHeightPreference`, `WeaponShootRateModifier` (`value=`), `FiringPatternSetHash`, `AccuracyProfile`, and `CombatFloats` (`BlindFireChance` and related scalars) | -| `CFiringPatternInfoManager` | 208,240 (4) | tail-only | One of the 7 start-truncated XML payloads whose first block fell in an unread RPF9 gap; identified by its closing tag | -| `CFleeDecisionMakerData` | 17,561 (1) | well-formed | `Profiles/Item` × 8 (`key=`), each defining `{Weight, Weights}` blocks for `Cower`, `RunAway`, `Mount`, and `TakeVehicle` (8 each), plus `Fly/Weights` (14 entries) | -| `Combat__GoalData__Store` | 4,550 (1) | well-formed | `RoleSettings` (`Default` + `DataMap/Item` × 5 keyed `StyleMod` entries) and `PriorityCalculators/DataMap/Item` × 8 (`type="Combat__GoalData__EntityDistanceBasedPriorityCalculator"` with `13` `{MaxDistSq, Priority}` pairs) | -| `WeaponAnimations__FullbodyControllerData` | 21,281 (1) | well-formed | `AnimRequestConfigMap/Item` × 11 (`type="WeaponAnimations__FBAnimRequestConfig"`, `DefaultRequestType` on 11, polymorphic `RequiredCondition` on 9, `7` `Variants/Item`) and `AnimRequestDataMap/Item` × 17 (`type="WeaponAnimations__FBRequestData"`, `LocoParams` on 16, `ControlGraphParams` on 11), plus `Timeouts` (1) | -| `WeaponAnimations__ConfigData` | 1,733 (1) | well-formed | `AIHandPoseRules` and `BuddyHandPoseRules` (`type="WeaponAnimations__HandPoseRules"`), with nested `CAIConditionOr` / `CAIConditionAnd` / `CAIConditionBlackboardBool` trees under `PosePrefOverrides/ForceTwoHanded` | -| `CAimUpperBodyDataBlock` | 1,813 (1) | tail-only | Start-truncated single-stream payload identified from its closing root tag | - -## Ped schedules, body variation, formations and energy - -Four representative roots account for 1,032,473 B (18 streams) of the 29-document peds/schedules/appearance category: - -| Root | Inflated B (streams) | Top-level sections and counts | -|---|---:|---| -| `CPedScheduleInfoManager` | 784,294 (12) | `Schedules/Item` × 4,861 (`{Name, Pack}` pairs), `PedScheduleTuning` (18 children), `PedDynamicScheduleTuning` (19 children), `Volumes/Item` × 9 (`VolumeType`, 3D `Position`/`Orientation`/`Scale`, `IsPenVolume`, and `SpawnPositions` `content="vec3v_array"`), `Routes` (1) | -| `CPedVariationBodyTypeManager` | 77,462 (2) | `BodyShapePresets/Item` × 16 containing `432` `Expressions/Item` records (`27` per preset, `{Id, Values content="float_array"}`), `ScaleVariationProfiles/Item` × 26 (`key=`, `34` `ScaleVariations/Item` with `{Min, Max, SelectionWeight, ValueType}`), `BodyShapeVariationProfiles/Item` × 22 (`key=`, `53` `BodyShapeVariations/Item` with `{BodyShapePreset, SelectionWeight}`), `ScaleProfiles` (2), `HeightPresets` (1) | -| `CPairedPedDataBlock` | 10,011 (1) | `SpacingData/Item` × 4 (seven 2D `x/y` distance pairs per item: `Spacing`, `MiddleSpacing`, `MinSpacing`, `MinSpacing_Crossing`, `MinMiddleSpacing`, `MinMiddleSpacing_Crossing`, `MaxSpacing`), `BespokeSpacingData` (2), `VehicleSpacingData` (1), `AmbientFormationData` (3, 6 2D `Pos` slots), `BespokeFormationData` (3, 11 2D `Pos` slots), `VehicleFormationData` (1) | -| `CEnergyConfigInfos` | 160,706 (3) | `HealthConfig/Item` × 63 (`key=`, `parentFile` on 3, `MeleeProperties/KnockedOutWakeUpCount` on 62, `FireVulnerability` on 61, `EnergyReserveProperties/Reserves` `content="float_array"` on 59), `EnergyReserveConfigs/Item` × 58 (`153` `EnergyReserves/Item` with `{Type, EnergyAmount, Enabled, RechargeRate, RechargeEnabled, RechargeThreshold}`), `EnergyConfig` (54), `StaminaConfig` (8), `EnergyHealthStateMap` (4), `HealthRechargeConfig` (3), `SpecialAbilityConfig` (2) | - -In `CEnergyConfigInfos`, **60 of 60** `HealthConfig/Item/EnergyReserveConfig` references resolve case-insensitively to -an `EnergyReserveConfigs/Item` entry in the same document. - -## World locations, pathing styles, trains and hazard nodes - -Four representative roots in the world/navigation/map category (826,397 B across 15 streams; all 4 well-formed): - -- **`GameShape__Data__LocationNameLoopkup` (1 document, 671,393 B, 11 streams):** (root spelling preserves the double - `o` in `Loopkup`.) Contains four keyed lookup tables (`key=`): - - `LocationNames/Item` × 2,318 (`Name` on all 2,318; `TextureDictionary` and `Texture` on 46). - - `InteriorNames/Item` × 1,358, holding `2,280` nested `` records with `{Name, Pos}`. Their 2,280 3D positions - span `x = -9,673.0..4,705.3`, `y = -7,308.0..8,589.9`, `z = -78.0..820.9` — their 2D `x`/`y` coordinates fall 100% - inside the `x`/`y` extent of the `PAMH` heightmap (`-13,312..5,120`, `-9,728..11,264`) and `GridAtlasInfo` grids - above, while `z` reaches `820.9` (above the `PAMH` `404` m ceiling). - - `RoadNames/Item` × 409 (`Name` on all 409) and `RiverNames/Item` × 66. -- **`PathingStyleData` (1 document, 5,993 B, 1 stream):** `StyleProfiles/Item` × 12 (`key=`), each defining - `CurvatureStyle`, `CorneringStyle`, `ApproachStyle`, `ContinuityStyle`, `SlowdownStyle`, `SplineConfig`, and - `AvoidanceStyle`, plus optional `Flags` (9) and `DoorPathingStyle` (5). -- **`CTrainConfigs` (1 document, 125,494 B, 2 streams):** `trainConfigs/Item` × 46, each carrying `name`, - `populateTrainDist`, three station stop-duration scalars (`stopAtStationDurationNormal`, - `stopAtStationDurationPlayer`, `stopAtStationDurationPlayerWithGang`), `announceStations`, `doorsBeep`, and `1..17` - `carriages/Item` entries (median 8, **314 carriages** total, each with `maxPedsPerCarriage`, `flipModelDir`, - `doInteriorLights`, `modelName` on 304, and `modelSetName` on 300). -- **`CHazardNodes` (1 document, 23,517 B, 1 stream):** a 20-state hazard state machine (`Nodes/Item` × 20, - `type="CHazardNode"`, `key=`, `Name`, `ClipSet`, `ClipVictim`, `ClipThreat`, `UseMTH`, `RumbleCurve`, - `RumbleCurveStart`) linked by `43` `Successes/Item` transitions (`type="CHazardTransition"`, gated by - `CAIConditionGatorPit` [36], `CAIConditionAmbientEventDirection` [5], `CAIConditionOr` [1], `CAIConditionAnd` [1]). - All **18 of 18** non-empty transition target `` references resolve to one of the 20 `CHazardNode` keys. - -## Door interaction, ped loadouts, climbing, lasso and AI rule schemas - -Fourteen previously undocumented well-formed `common.rpf` documents span **1,682,656 inflated bytes** across **32** -streams. Counts, schemas, `type` classes and internal/cross-document key resolutions only; no entry names or values: - -### `CDoorInteractionDataList` (404,957 B, 7 streams, 5,831 elements) - -Fourteen top-level keyed sections (all 14 named across the reference paths and target sections below; `372` `key=` attributes, `979` `type=` attributes across `31` classes, `44` `content="matrix34"` transforms, `133` vectors, `791` `value=` scalars) form a self-contained internal lookup graph: - -| Section / reference path | Count | Resolves to / notes | -|---|---:|---| -| `DoorTypeToDataSetCollectionsMapping` / `List/Item` | 7 / 80 | `CDoorAssetList`; **80 of 80** resolve to `DataSetCollections` (`18` distinct) | -| `DataSetCollections` / `List/Item` | 21 / 60 | `CDoorAssetList`; **60 of 60** resolve to `DoorInteractionDataSets` (`56` of `56` sets) | -| `DoorInteractionDataSets` (`key=`, `type="CDoorInteractionDataSet"`) | 56 | `40` carry `parentPath`, all **40 of 40** resolving via `../Item[@key='...']` (`gamedata_graph.md`); `DoorType` (**20 of 20** → `DoorTypeToDataSetCollectionsMapping`), `OverlayDataSet` (**9 of 9** → `DoorInteractionAnimOverlayDataSets`), `PedHeadingData` (**11 of 11** non-empty → `DoorInteractionHeadingDatas`), `Interactions/Item` (**93 of 93** → `DoorInteractionDatas`), `PostAlignInteractions/Item` (**11 of 11** → `DoorInteractionPostAlignDatas`) | -| `DoorInteractionDatas` (`91`) & `DoorInteractionPostAlignDatas` (`11`) | 102 | `DoorType` (**91 of 91** on interactions), `BreakoutData` (**91 of 91** + **11 of 11** → `DoorInteractionBreakoutDatas` [`6`]), `UpperbodyRequestData` (**91 of 91** + **11 of 11** → `DoorInteractionUpperbodyPoseDatas` [`8`]), `MTHWeightData` (**73 of 73** non-empty → `DoorInteractionMTHDatas` [`3`]), `InterruptToIdleBlendout` (**7 of 7** → `DoorInteractionBodyBlendOutDatas` [`1`]), `PedHeadingData` (**11 of 11** on interactions; **73 of 73** non-empty across all `.//PedHeadingData` → `DoorInteractionHeadingDatas` [`5`]), `AnimData/UpperbodyBodyBlendFilterTemplateOrSelector` (**4 of 4** → `HashSelectors` [`1`]) | -| `DoorInteractionAnimOverlayDataSets` (`1`) & `DoorInteractionAnimOverlayDatas` (`8`) | 9 | `OverlayDatas/Item`: **8 of 8** resolve to `DoorInteractionAnimOverlayDatas` | -| `DoorInteractionUpperbodyPoseDatas` (`8`) & `UpperbodyPoseRequiredBlackboardVariables` (`4`) | 12 | `WeaponData1H/DesiredPose` (**8 of 8**) and `WeaponData2H/DesiredPose` (**8 of 8**) resolve to `UpperbodyPoseRequiredBlackboardVariables` | - -### Ped loadouts, task tuning, headbob, speeds, motivation and motion prediction - -| Root | Inflated B (streams) | Measured schema and key resolution | -|---|---:|---| -| `CPedInventoryLoadOutManager` | 411,101 (7) | `8,103` elements, `5` `type` classes (`1,692` nested `Items/Item` across the document): `LoadOuts/Item` × `569` (`Name`, `Items`, holding `1,013` direct items: `601` `CLoadOutWeapon`, `302` `CLoadOutRef`, `110` `CLoadOutRandom`) and `NamedLoadoutItems/Item` × `191` (`key=`: `136` `CLoadOutRandom`, `45` `CLoadOutWeapon`, `10` `CLoadOutRef`). `DefaultLoadout` resolves **1 of 1** to `LoadOuts`, and **521 of 521** `CLoadOutRef/Name` elements (`184` distinct) resolve case-insensitively to `NamedLoadoutItems` (`518 of 521` / `185` distinct under exact case); `CLoadOutWeapon` carries `551` `WeaponRecipe` and `546` `WeaponPreset` (`231` distinct) fields | -| `CTaskDataInfoManager` | 192,988 (3) | `3,532` elements (`2,990` `value=`): `aTaskData/Item` × `49` (`type="CTaskDataInfo"`, `27` distinct child fields) and `DefaultSet ref` (**1 of 1** → `aTaskData`). In `FleeStyleSets/{Base,InVehicle,OnMount}`, **47 of 49** entries each (`41` of `42` distinct) resolve case-insensitively to `aTaskData` (`16 of 49` / `13 of 42` under exact case) | -| `STPedNavigationPredictiontPresetContainer` | 92,999 (2) | `1,648` elements (`1,597` `value=`; preserves `Predictiont` spelling): `mapPredictionPresets/Item` × `14` (`key=`), holding `21` `arPredictionSetConfigs/Item` blocks (`1..8` per preset, `71..75` fields each, `81` distinct field names across the 21 blocks covering collision, capsule, drops, step-ups, walls, cover shadows, corners, slope and climb flags) | -| `STPedMotionPredictionSetContainer` | 50,327 (1) | `898` elements (`864` `value=`): `mapPredictionPresets/Item` × `10` (`key=`), holding `12` `arPredictionSets/Item` blocks (`1..3` per preset, `67` fields each from the same prediction-flag schema) | -| `CPedHeadbobSettingsManager` → `CHeadbobConditionManager` | 88,190 (2) + 16,610 (1) | `CPedHeadbobSettingsManager` (`1,347` elements) defines `OnFootSettings` (`12` `IntensitySettingsMap/Item`, `6` `BodyBlendSettingsMap/Item`) and `InTransportSettings` (`12` and `0`) across `CPedHeadbobSettings` (`2`), `CPedHeadbobIntensitySettings` (`24`) and `CPedHeadbobBodyBlendSettings` (`6`). All **84 of 84** `pCondition ref` links (`15` distinct) resolve **across documents** to `CHeadbobConditionManager/Conditions/Item/@key` (`18` `CHeadbobCondition` entries built from `CAICondition*` condition trees) | -| `CPedSpeedDataBlock` | 86,390 (2) | `2,248` elements (`1,455` `value=`, `0` `type=`): `Data/Item` × `16` (distinct `Name` entries, each with `WanderSpeeds`, `Default`, `Combat`, `Flee` over `{Walk,Jog,Run,Sprint}{Min,Max}` plus `QuadBike`, `EScooter`, `MobScooter`, `Caddy` × `16` and `Bike` × `15`, and `1` `ItemSpeeds/Item`) plus `DefaultItemSpeeds/Item` × `1` | -| `CPedMotivationInfoManager` | 32,388 (1) | `872` elements (`499` `value=`): `EventMotivationImpactProfiles/Item` × `7` (`key=`, `35` `EventTypes/Item` across `5` keys, `51` `MotivationImpacts/Item` pairs `{Motivation, ImpactParams}`), `PedMotivationDefinitions/Item` × `14`, and `aFearResponseProfiles/Item` × `4`; `DefaultFearProfileName` resolves **1 of 1** to `aFearResponseProfiles` | - -### Lasso, climbing, animal attack behaviours, relationships and AI search POIs - -| Root | Inflated B (streams) | Measured schema and key resolution | -|---|---:|---| -| `CLassoDataManager` | 126,639 (2) | `2,718` elements across `11` top-level sections (`99` `key=`, `692` `value=`, `380` 3D vectors with `7` `w`): `LassoHogtieFlagSets/Item` (`8`, referenced **24 of 24** by `ModelToLassoHogtieFlagsKey` plus all **3** default flag fields), `EntityLassoAttachInfo/Item` (`18`, referenced **26 of 26** by `ModelNameToEntityLassoAttachInfo` plus `DefaultHumanEnityLassoAttachInfo` and `DefaultHorseEnityLassoAttachInfo` [`Enity` preserved in XML]), and `LassoAttachments/Item` (`23`, referenced **18 of 18** by `DefaultAttachment` and **20 of 20** by `Attachments/Item`), plus `LassoWeaponLoopBoneTags/Item` × `15` | -| `CAnimalAttackBehaviours` | 55,388 (1) | `877` elements (`378` `type=`): `Behaviours/Item` × `6` (`type="CAnimalAttackBehaviour"`, `{Name, AnimalTuning, Task, Triggers}`) holding `64` `CAnimalAttackTrigger` entries, `58` gated by `CAICondition*` boolean trees (`308` nodes across `32` condition classes, led by `CAIConditionAnd` [`53`], `CAIConditionNot` [`31`], `CAIConditionDistanceBetweenEntities` [`21`]) | -| `CClimbTuneMgr` | 54,137 (1) | `1,102` elements across `12` top-level sections (`TraversalData`, `LandData`, `PlayerClimbData` [20 scalars], `PlayerStepUpData` [15 scalars], `PlayerLedgeGrabData` [16 entries], `PlayerJumpData` [11 entries], `AnimalJumpData` [11 scalars], `InputControlData` [4 scalars], `aClimbParams/Item` × `2` [`CClimbParams`], `aDropdownDetectorParams/Item` × `2` [`CDropDownDetectorParams`, with `matOverride` `content="matrix34"`]); `DefaultClimbParams ref` and `DefaultDropDownParams ref` resolve **1 of 1** each | -| `Relationships__GroupsData` | 35,555 (1) | `554` elements: `Groups/Item` × `64` (`key=`) containing `423` `Relationships/Item` entries across `4` relationship-level text values (`62` distinct targets); all **423 of 423** resolve internally to `Groups/Item/@key` | -| `CSearchPointOfInterestRuleSet` | 34,987 (1) | `684` elements (`47` `CAICondition*` nodes across `14` classes): `PointOfInterestDefinitions/PointOfInterest` × `12` (`key=`) and `SearchSituations/Situation` × `13` (`key=`). All **112 of 112** `AllowedPointsOfInterest/Type/@key` (`12` of `12` POIs) resolve to `PointOfInterestDefinitions`, and all **7 of 7** non-empty `NextSituation` links (`6` distinct) resolve to `SearchSituations` | - -## No-sharing rule - -The archive, every carved `.bin`, `index.json` (its `head`/`pre` fields contain payload bytes), XML -excerpts, entry names, values, paths, screenshots and per-file reports stay on the local machine. Only -aggregate counts, sizes and schema/category names belong in git, issues or pull requests. The unit test uses -synthetic data; CI never reads a game folder. This is the same rule as `AGENTS.md` and `CONTRIBUTING.md`, and -it applies to this note as well. - -## Streaming reader (`tools/gamedata_reader.py`, ASSET-139) - -`tools/gamedata_reader.py` reads the carved documents with `iterparse` and turns each into plain Python values, -without a schema per tag. Each top-level field is converted when its end tag arrives and then dropped, so memory is -bounded by the largest field. The generic conversion follows the parser's own conventions: - -- `value=` is a scalar: bool, decimal or `0x` integer, float (a C `f` suffix allowed), else text. -- `x/y/z/w` is a vector tuple. -- `content=` is the array body. `short_array`, `float_array` and `float16_array` give number lists; - `vector2_array`, `vec3v_array`, `matrix33` and `matrix34` give tuples. -- `type="Class"` is a polymorphic object `{"$type": ...}`, and `type="NULL"` is `None`. -- `ref=` is `{"$ref": ...}`. -- All-`Item` children are a list, or a dict when every one carries `key=`. A repeated tag is a list. A text-only - element is its text. Any other attribute is kept as `"@name"`. - -`register_root(tag)` and `register_type(name)` plug in a handler where a schema is known. Everything else stays -generic. - -``` -python -I tools/gamedata_reader.py /common [--root TAG] [--out DIR] # counts; --out: one JSON per document (local only) -``` - -On the 1.0.2.1 carve of `common.rpf` the run takes about 5 s, with 0 conversion errors: - -| | count | -|---|---:| -| documents read | 259 of the 267 payloads | -| roots | 111 | -| not well-formed (the tail-only and incomplete carves counted above) | 8 | -| scalars | 84,585 | -| vectors | 20,825 | -| arrays | 13,449 | -| lists | 13,465 | -| keyed maps | 526 | -| polymorphic objects | 6,490 (317 `type` classes over 6,903 typed elements) | -| `NULL` pointers | 278 | -| references | 924 | -| elements with extra attributes | 5,262 | - -The 7 roots missing from the 118 occur only in documents that are not well-formed. Counts only: the JSON that -`--out` writes is the game's data and stays local. `tests/test_gamedata_reader.py` checks every convention, -both dispatch tables, that streaming equals a whole-tree conversion, and the CLI, on synthetic XML. - -## Next step - -The most useful next step is the other half of the **schema bridge**: check whether the 118 XML root tags (and the -317 `type` classes) match RTTI class names in the executable, then register typed handlers for them in -`tools/gamedata_reader.py`. That turns the measured XML into the runtime's config layer without hand-writing 5,293 -tags. The streaming reader that dispatches on root and `type` exists now (above). The `MHIU`/`PAMH` -heightmaps are decoded by `tools/gamedata_maps.py`; every MHIU header field is identified (0x28 is the -default height), and the row-table layouts and the value-to-Z mapping are measured. diff --git a/docs/gamedata_graph.md b/docs/gamedata_graph.md deleted file mode 100644 index de247ed7c..000000000 --- a/docs/gamedata_graph.md +++ /dev/null @@ -1,158 +0,0 @@ -# The `common.rpf` content-set graph - -This note measures the mount/reference graph in the XML documents recovered from `common.rpf` in the -Xbox Series 1.0.2.1 package. It extends [gamedata.md](gamedata.md), which counts the documents and -reference tokens, and uses the same local carve. Only aggregate counts, root/category names and -reference-prefix names are recorded here. No archive, carved file, XML value, content-set id, entry -name or target path is committed. - -`tools/gamedata_graph.py` rebuilds the documents with `gamedata_index.py` and -`gamedata_xml.load_documents`, then keeps the reference strings long enough to join them. It is -standard-library only and reads the same carve as the index and catalog. XML with an unsupported -encoding counts as an unparsed payload; it supplies no edges and does not stop the other documents. - -## Graph model - -| Node | Count | What it represents | -|---|---:|---| -| document | 267 | one XML payload, including the unparsed ones | -| content set | 30 | every ``, plus every `` id | -| target | 3,364 | every distinct ``, ``, `parentPath` and `parentFile` value | -| **total** | **3,661** | | - -| Edge | Count | Meaning | -|---|---:|---| -| `defines` | 28 | document to its top-level or nested `` id | -| `includes` | 14 | document to an `` id (12 resolve to a document) | -| `contains_file` | 3,315 | set (or document) to a `` target | -| `loads_changeset` | 28 | document to an `/` target | -| `parent_path` / `parent_file` | 40 / 3 | document to a `parentPath` / `parentFile` locator | -| **total** | **3,428** | | - -The document/content-set part is 42 edges; the target part is 3,386 edges. An include becomes a -document-to-document edge only when its text exactly equals a set id. There is no fuzzy match and -no prefix normalization. Missing ids stay dangling content-set nodes, so a spelling difference is -visible as an unresolved include instead of becoming an invented document edge. - -## Measured shape - -| Measure | Value | -|---|---:| -| XML payloads | 267 | -| Complete documents | 266 | -| Parsed documents | 259 | -| Unparsed payloads | 8 (7 truncated, 1 rootless) | -| Named roots (+ one unattributed) | 118 (+1) | -| Manifest documents | 25 (23 `CDataFileMgr__ContentChangeSetDef`, 2 `CDataFileMgr__ContentDef`) | -| Content-set ids | 30 (28 defined, 2 dangling) | -| Duplicate set ids | 0 | -| Reference sites | 3,400 (3,386 target + 14 include) | -| Distinct target strings | 3,364 | -| Include sites / document edges | 14 / 12 | -| Cycles in the include graph | 0 | -| Include-graph roots (in-degree zero) | 13 | -| Reachable documents from those roots | 25 of 25 manifest documents | -| Maximum include depth | 1 | -| Reachable content sets | 30 | -| Reachable target sites | 3,343 | -| Reachable distinct targets | 3,343 | - -The manifest layer is closed at the document level: all 12 resolved includes point at documents that -are already among the 25 manifests, so no non-manifest document is reachable by an id. The graph -therefore measures the mount walk, not a general include system. The 21 distinct targets outside the -reachable set are the `parentPath`/`parentFile` locators in the two non-manifest documents. - -## Prefix rules - -The four documented rules cover 3,312 of the 3,386 target sites. `common:/` also occurs but is not -one of those rules, so it is reported separately and is not rewritten to `$(common)/`. - -| Reference form | Sites | Resolution in this catalog | -|---|---:|---| -| `$(common)/` | 587 | common archive namespace; the TOC name is missing | -| `$(target)/` | 23 | target data namespace; the TOC name is missing | -| `$(root)/` | 28 | changeset root; not a document in this archive | -| `platform:/levels/` | 2,346 | levels namespace; the TOC name is missing | -| other `platform:/` | 328 | other platform namespace; the TOC name is missing | -| `common:/` | 31 | unrecognized scheme alias; left unresolved | -| relative locator | 43 | `parentPath` / `parentFile`, not an archive path | -| **total** | **3,386** | | - -`parentPath` values are XPath-like locators, not mount paths, and `parentFile` is a relative name. -The 43 locator sites are 21 distinct strings in 2 non-manifest documents. None of them is used to -invent a document edge. - -### What the locators point at - -The two kinds behave differently, and only one needs the table of contents: - -| Locator | Sites | Distinct | Shape | Resolves | -|---|---:|---:|---|---| -| `parentPath` | 40 | 20 | always `../Item[@key='']` | **40 of 40** to a sibling `Item` in the same list of the same document | -| `parentFile` | 3 | 1 | `/.`, a relative file path | no: needs a file name, so the table of contents | - -All 40 `parentPath` sites are in the one `CDoorInteractionDataList` document, on items of its -`DoorInteractionDataSets` list (56 items, 56 distinct `key`s). Read as an XPath step from the item, `..` is the -list and `Item[@key='K']` selects the sibling with that key; every `K` exists (case-insensitive). The result is -single inheritance inside the list: following parents gives depth 0 for 16 items, 1 for 35, 2 for 3, 3 for 1 -and 4 for 1, with no cycles. So these are in-document references that a loader can resolve without any archive -path, by key lookup within the parent list. The 3 `parentFile` sites are all in `CEnergyConfigInfos` and name -the same other file. - -## Unresolved references - -| Bucket | Sites | Note | -|---|---:|---| -| Recognized archive namespace, no document identity | 3,312 | `$(common)` 587, `$(target)` 23, `$(root)` 28, `platform:/levels` 2,346, other `platform:/` 328 | -| Unrecognized scheme (`common:/`) | 31 | not one of the four prefix rules | -| Relative locator | 43 | 21 distinct `parentPath`/`parentFile` values | -| Include id with no exact definition | 2 | one differs only by the `common:/` vs `$(common)/` spelling; one has no exact set id | -| **total** | **3,388** | excludes the 12 resolved include edges | - -The first bucket is not a failure by itself: the table of contents is encrypted, so an archive path -cannot be mapped to a carved document or to an entry name. It remains a target node. Only the two -include ids are unresolved content-set joins. Both are kept dangling rather than normalized. - -## Runtime use - -A mount resolver can follow the same shape: read a manifest, take its `` and ``, -resolve the four prefixes to archive namespaces, and follow `` only on an exact id. The -measured walk from the 13 in-degree-zero manifests reaches all 25 manifest documents and 30 set ids -in this archive, at depth 1. It does not reach any of the other 242 XML payloads, because those are -not mounted through content-set ids in this catalog. - -This is not a runtime schema. The catalog knows 118 root names, 5,293 element names and 33 attribute -names, but not field types. It also cannot supply names for the archive targets: that needs a -documented TOC reader, which is outside this work. - -`parentPath` inheritance is the one reference a loader can follow inside a document. The tool reports it -under `parent_path_inheritance`: a locator of the form `../Tag[@attr='value']` is resolved against the -siblings of the element that carries it, by exact string match. On this `common.rpf` all 40 sites take that -form and all 40 resolve (none ambiguous), in one document; the linked items sit at inheritance depth 1 (35), -2 (3), 3 (1) and 4 (1), with no cycles. These links stay outside the document graph and its edge counts. - -## Limits - -- The table of contents is encrypted, so target paths are namespaces and strings, not document ids. - No path is joined to a carved document. -- Eight payloads are unparsed (seven truncated at the start, one rootless). Their references are - unknown and contribute no edges. -- Content-set joining is exact string equality. `common:/`, `$(common)/`, case and slash variants - are not normalized; the 31 `common:/` entries stay unresolved. -- `parentPath` and `parentFile` are locators, not mounts. They are counted, not followed by the tool. - The 40 `parentPath` sites resolve inside their own document (see above); the 3 `parentFile` sites do not. -- Only `filename`, `loadPath`, `includedSets`, `parentPath` and `parentFile` are modeled. No - XInclude occurs in the corpus, and no general include processor is implemented. -- The counts are for this version's `common.rpf`; another package can differ. - -## Reproduce - -```powershell -python -I tools/rpf9_carve.py common.rpf \carve\common -python -I tools/gamedata_graph.py \carve\common --json \graph.json -python -I tests/test_gamedata_graph.py -``` - -The JSON is an aggregate work product: counts, root names, category names and prefix names. It -contains no target strings, content-set ids, offsets or per-file names, so it can be reviewed -without copying game data. diff --git a/docs/gameinput.md b/docs/gameinput.md deleted file mode 100644 index a9fee120b..000000000 --- a/docs/gameinput.md +++ /dev/null @@ -1,568 +0,0 @@ -# Controller input: the GameInput shim on SDL3 - -The Xbox build reads controllers through Microsoft's GameInput API. `runtime/shims/gameinput.cpp` answers -`GameInputCreate` with its own implementation of that API, backed by [SDL3](https://libsdl.org) gamepads, so -every controller SDL supports works the way an Xbox pad would: DualSense, DualShock 4, Switch Pro, Xbox pads, and the -rest of SDL's controller database. On a DualSense the impulse-trigger rumble becomes adaptive-trigger effects, and -the lightbar colour can be set. - -Without the shim the loader would bind `GameInputCreate` to the host's `GameInput.dll` if there is one -([#279](https://github.com/ItsNotRexed/Leonida/pull/279)). That works for Xbox pads only, and gives no DualSense -features. That path is tested without the game: `gameinput_host_test` (ctest `gameinput_host`) maps a synthetic DLL -built against the SDK's `gameinput.lib` and checks that its `GameInput.dll` import binds to the host's copy, that -`GameInputCreate` and `GetCurrentTimestamp` work from mapped code, and that `GetCurrentReading` answers; with a pad -attached, `GetGamepadState` must succeed on the reading. It passes on Windows 11 build 26300 (GameInput 0.2309) without -a pad attached. The test skips only where Windows cannot load `GameInput.dll`; with the DLL present, an import that binds to nothing fails it. The game executable is not available yet, -so whether it imports GameInput this way, and under which -module, is unverified (see [VERIFY](#verify)). - -## Building - -The shim is optional, and the build downloads nothing unless asked. SDL3 is zlib-licensed. CMake builds the shim when -SDL3 is available in one of these ways: - -- **Installed SDL3**, 3.2 or newer, found by `find_package(SDL3)`: set `SDL3_DIR` or `CMAKE_PREFIX_PATH`, for example - `-DSDL3_DIR=C:/SDL3/cmake`. No flag is needed. -- **`-DLEONIDA_SDL3_FETCH=ON`**: downloads the pinned release `SDL3-3.4.20.tar.gz` from SDL's GitHub releases once at - configure time, checks its SHA-256, and builds it static with only the gamepad parts (no audio, video, GPU or - render). That takes about a minute on the first build. `scripts/build_runtime.ps1 -FetchSdl3` passes it. -- **A local copy of that tarball**: extract it and pass `-DFETCHCONTENT_SOURCE_DIR_SDL3=`; it is - built the same way, without a download. - -Without any of these, or with `-DLEONIDA_SDL3=OFF`, configure prints a message and `gta6rt` is built without the shim: -it has no `GameInputCreate`, as before, so the loader binds it to the host's `GameInput.dll` or the unimplemented -thunk. `gameinput_test` and `gameinput_probe` are not built, and CTest lists `gameinput` as not run (disabled) rather -than failing. - -`scripts/build_runtime.ps1` (what `make_game.py` runs) builds the shim only on its CMake path, when Visual Studio's -C++ CMake tools are installed. Its direct-`cl.exe` fallback compiles a fixed file list without the shim and warns -about it. - -## Mapping - -GameInput's buttons are positional, as on an Xbox pad, and SDL's are too, so the face buttons go by position, not by -label: - -| GameInput | SDL3 | DualSense | Switch Pro | -|---|---|---|---| -| `A` | south | Cross | B | -| `B` | east | Circle | A | -| `X` | west | Square | Y | -| `Y` | north | Triangle | X | -| `View` | back | Create | Minus | -| `Menu` | start | Options | Plus | -| shoulders, stick clicks, d-pad | same | L1/R1, L3/R3, d-pad | L/R, stick clicks, d-pad | -| guide button callback | guide | PS | Home | - -The DualSense touchpad click, mute button and paddles are not in GameInput's gamepad state; they are in the -controller-button array (`GetControllerButtonState`, indexed in SDL's `SDL_GamepadButton` order). - -- Sticks: -1..1 with +Y up (SDL reports +Y down; the shim flips it). Triggers: 0..1. No deadzone is applied, as on - console: the title applies its own. -- `GetUiNavigationState` is derived from the pad: A accept, B cancel, X/Y context 1/2, stick clicks context 3/4, d-pad - or left stick past half for up/down/left/right, shoulders for page left/right, triggers past half for page up/down, - right stick past half for scrolling, Menu and View as themselves. -- Controller axes (`GetControllerAxisState`): LX, LY, RX, RY, LT, RT in 0..1, sticks at rest at 0.5. -- Every pad is reported as family `GameInputFamilyXboxOne` with its real USB vendor and product id. -- Player LEDs (and SDL's default lightbar colour) follow connection order: the first pad is player 1, and a pad - plugged in later takes the lowest free slot. - -## Keyboard pad - -The title reads gamepads only, so keyboard input has to arrive as a gamepad. With `LEONIDA_KEYBOARD_PAD` set, the -shim attaches one SDL virtual gamepad named `Keyboard pad (Leonida)` and presses its buttons from the keyboard on -every poll. It then goes through the same path as a real pad: a device object, the next free player slot, readings, -reading and device callbacks, and UI navigation derived from its buttons. It reports no rumble motors. It is off by -default. - -| key | button | -|---|---| -| arrow keys | d-pad | -| Enter | `A` | -| Backspace | `B` | -| X | `X` | -| Y | `Y` | -| Q / E | left / right shoulder | -| Esc | `Menu` | -| Tab | `View` | -| W / A / S / D | left stick up / left / down / right | -| mouse movement | right stick | -| right mouse button | left trigger (aim) | -| left mouse button | right trigger (fire) | - -Letters are Windows virtual-key codes, so `Y` is the key labelled Y on the active layout (it sits where Z does on a -QWERTY keyboard with a German layout). Mouse buttons are the physical ones: `GetAsyncKeyState` ignores the -swapped-buttons setting. - -WASD pushes the left stick to full deflection. Opposite keys cancel (W+S is centered on Y), and a diagonal sits on -the round gate as a real stick reports it: about 0.707 on each axis, not 1. - -The right stick follows the mouse's movement, not the cursor's position. Each poll (2 ms with the background thread) -the stick keeps 7/8 of its value and adds 1024 axis units (of 32767, times `LEONIDA_MOUSE_SENSITIVITY`) per count the mouse moved since the last poll, -clamped to full. Steady movement of 4 counts a poll (2000 a second) is full deflection; when the mouse stops, the -stick falls back from full to exactly 0 in 67 polls (134 ms). Moving the mouse down pushes the stick down. - -The movement comes from raw input (`WM_INPUT`): what the mouse itself reports, so it does not stop at the edge of the -screen and Windows' pointer acceleration does not change it. When the keyboard pad attaches, the shim starts one -thread with a message-only window (never shown) registered for raw mouse input (`RIDEV_INPUTSINK`), which adds each -relative movement to a running total; the poll takes the difference of that total between polls. Absolute reports -(remote desktop, some virtual machines, pen tablets) are ignored. If the window or the registration fails, the shim -logs it and falls back to `GetCursorPos` deltas, which stop at the screen edge. A count is one step of the mouse's -sensor, about a pixel at Windows' default pointer speed without acceleration, so the feel depends on the mouse's DPI. - -With raw input on and a window of this process in the foreground, the cursor is kept inside that window's client -area (`ClipCursor`, re-applied every 100 ms) so that a click cannot land on another window; it is released when focus -moves away or the keyboard pad is turned off. The cursor stays visible: hiding it has to happen on the thread that -owns the game's window, which is the title's, not the shim's. - -Keys are read with `GetAsyncKeyState`, which needs no window or message loop (SDL's keyboard is part of its video -subsystem, which this build leaves out) and works under Wine. With `LEONIDA_KEYBOARD_PAD=1` keys count only while a -window of this process is in the foreground, so typing in another application presses nothing, and every button, -stick and trigger is released when focus moves away (the cursor is read afresh when focus returns, so the right -stick does not jump). `LEONIDA_KEYBOARD_PAD=always` reads them whatever has focus; a console tool such as - `gameinput_probe` needs it, because its console window belongs to the terminal, not to the tool. -- Force feedback and haptics run through a fake haptic backend (`rt::gameinput::set_haptic_source`), because SDL's - virtual joysticks report no haptics: the motor count, axes and effect flags a wheel reports, and a pad without SDL - haptics reporting no motor at all; `CreateForceFeedbackEffect` and its `E_INVALIDARG` cases; a constant effect - becoming `SDL_HAPTIC_CONSTANT` at the right level, not re-sent while unchanged, updated once when the parameters - change; the effect's gain and the motor's device gain; a 50 Hz sine's period, phase, length and play count; a - spring's coefficients, saturations, dead zone and centre; a finished effect reporting stopped; `Paused` stopping it; - `LEONIDA_RUMBLE=0` silencing it and the mute lifting; the SDL effect destroyed when the title releases it; and, on a - pad with trigger motors, the two haptic motors, `SetHapticMotorState`'s intensity, deadline, `playCount` 0 and null, - and the trigger rumble sharing the one message. - -To try it by hand: `set LEONIDA_KEYBOARD_PAD=always`, then `gameinput_probe --seconds 20` and press keys. - -## Rumble and triggers - -`IGameInputDevice::SetRumbleState` takes four motor levels, 0..1. The two body motors go to `SDL_RumbleGamepad` on -every pad that has rumble. The two trigger motors depend on the pad: - -- Xbox One and Series pads (and anything else SDL reports trigger rumble for): `SDL_RumbleGamepadTriggers`, the same - impulse triggers as on console. -- DualSense: the trigger level becomes an adaptive-trigger effect sent with `SDL_SendGamepadEffect`, chosen by - `LEONIDA_DS_TRIGGERS`. -- Others (DualShock 4, Switch Pro): the trigger levels are dropped and the device reports no trigger motors. - -**This is an approximation.** The Xbox title only sends an impulse-trigger vibration level per frame. The PS5 version -of a game has effects authored per weapon and vehicle (weapon resistance, a click at a trigger position, and so on); -none of that exists in the Xbox build, so the shim can only turn the level it gets into a generic effect. Expect it to -feel like the Xbox signal played through the DualSense's trigger motors, not like the PS5 release. - -The DualSense effect is SDL's 47-byte DualSense effects block (`DS5EffectsState_t` in SDL's `SDL_hidapi_ps5.c`, the -format `test/testcontroller.c` uses): byte 0 holds the valid flags `0x04 | 0x08` (right and left trigger effect), -bytes 10-20 the right trigger effect and bytes 21-31 the left one. The effect modes are the three SDL's test program -uses: - -| `LEONIDA_DS_TRIGGERS` | level 0 | level > 0 | -|---|---|---| -| `rumble` (default) | `05` (effect off) | `06 00`: vibration at `LEONIDA_DS_TRIGGER_FREQ` Hz from the start of the pull | -| `resistance` | `05` | `01 00 `: constant resistance over the whole pull | -| `off` | nothing is sent; the triggers stay as they are | | - -An effect is sent only when its bytes change, so a steady level costs one report. - -## Force feedback and haptics - -`IGameInputDevice` reports the motors a pad really has, and drives them. There are two kinds, and they come from two -places: - -| GameInput | comes from | the shim reports | -|---|---|---| -| `forceFeedbackMotorCount`, `forceFeedbackMotorInfo` | SDL opened the pad's joystick as a haptic device (`SDL_OpenHapticFromJoystick`), which it does for a wheel or a stick, never for a gamepad | one motor at index 0: `supportedAxes` LinearX, `maxSimultaneousEffects` SDL's limit, and one flag per effect kind from SDL's feature bits | -| `hapticFeedbackMotorCount`, `hapticFeedbackMotorInfo` | the trigger motors the pad already has for rumble: Xbox impulse triggers, or a DualSense with `LEONIDA_DS_TRIGGERS` on | two motors, left and right trigger, one waveform each | - -A pad with neither keeps the answer the shim gave before this existed: no force-feedback or haptic motors, -`CreateForceFeedbackEffect` `E_INVALIDARG`, `IsForceFeedbackMotorPoweredOn` false, `SetHapticMotorState` `E_INVALIDARG`. -The keyboard pad is one of those, and so is any pad SDL opens as a gamepad only. - -### Force feedback: `CreateForceFeedbackEffect` - -`IGameInputForceFeedbackEffect` is the title's object; SDL is touched only on the poll thread. `SetParams`, `SetGain` -and `SetState` record the change and bump a version, and the next poll creates, updates, runs or stops the SDL effect, -so a title call still costs a lock and a copy. GameInput's eleven effect kinds are SDL's eleven force-feedback effects: - -| GameInput kind | SDL type | fields | -|---|---|---| -| `Constant` | `SDL_HAPTIC_CONSTANT` | `level` = magnitude × gain | -| `Ramp` | `SDL_HAPTIC_RAMP` | `start` and `end` from the start and end magnitude | -| `SineWave`, `SquareWave`, `TriangleWave`, `SawtoothUpWave`, `SawtoothDownWave` | `SDL_HAPTIC_SINE`, `SQUARE`, `TRIANGLE`, `SAWTOOTHUP`, `SAWTOOTHDOWN` | `period` = 1000/frequency in ms, `magnitude`, `offset` = bias, `phase` = the effect's degrees × 100 | -| `Spring`, `Friction`, `Damper`, `Inertia` | `SDL_HAPTIC_SPRING`, `FRICTION`, `DAMPER`, `INERTIA` | positive and negative coefficient, saturation and dead zone on all three axes, `center` from the magnitude | - -- Only the X magnitude is read, because the motor reports LinearX: the axis a wheel's or a stick's motor acts on. An -effect for another axis is played on this one, not dropped. -- `SetForceFeedbackMotorGain` is SDL's device gain (`SDL_SetHapticGain`, 0..100) and scales every effect on the motor; -`IGameInputForceFeedbackEffect::SetGain` scales that one effect's levels. Both are clamped to 0..1. -- The envelope: attack and release become SDL's `attack_length` and `fade_length` with the gains as their levels, -`sustainGain` scales the magnitude, attack + sustain + release is SDL's `length`, and `playCount` is the iteration count, -where 0 is "until stopped". No duration at all is a 60 s SDL length re-run every 20 s — the same refresh the rumble -motors get — so an effect with no end keeps playing without being restarted every poll. An effect that plays its -length reports `GameInputFeedbackStopped` afterwards. -- An all-zero envelope (what a title that only sets a magnitude leaves behind) means "no envelope", not silence, so -the effect plays at its own magnitude rather than at gain 0. -- A new effect starts `GameInputFeedbackRunning`: `CreateForceFeedbackEffect` already carried its parameters, and the -documented use — create once, `SetParams` per frame — never reaches `SetState`. `GameInputFeedbackPaused` stops the -SDL effect, because SDL pauses the device where GameInput pauses one effect. -- `LEONIDA_RUMBLE=0` stops every effect, like every other output path. -- The kind is checked against the motor's flags when the effect is created, so a kind the pad does not list is -`E_INVALIDARG`. SDL is not asked there — that is a title call — so if SDL still refuses an effect the poll thread sends -nothing for it rather than guessing. - -### Haptics: `SetHapticMotorState` - -The trigger motors play one waveform each: an intensity, which is the one thing SDL lets the shim send on a trigger, -through the same output as the trigger rumble — `SDL_RumbleGamepadTriggers`, or the DualSense effect block. `duration` -and `repeatDelay` are microseconds, `playCount` 0 plays until the state is set again, and a null `params` stops the -motor. For a waveform with a duration, each repetition plays for that duration and then leaves a quiet interval of -`repeatDelay` before the next repetition. The poll thread samples the current phase. During a pulse, the stronger of -the haptic intensity and ordinary trigger rumble wins. During the interval, ordinary trigger rumble continues. - -**This is an approximation too, and a coarser one than the rumble.** A real haptic motor has a table of waveforms, each -with its own HID usage; SDL exposes no such table — a DualSense takes one effects block and everything else takes a -trigger impulse — so the shim reports a single waveform per motor (an intensity, usage 0x0F/0x58) instead of the pad's -real ones, and plays any request as an intensity. A title that picks waveform 3 by name cannot be served beyond -intensity 0; waveform indices other than 0 are `E_INVALIDARG`. - -## Motion - -Pads whose SDL gamepad reports both a gyroscope and an accelerometer (a DualSense, a Switch Pro, Steam Input pads) get -`GameInputKindMotion` in `supportedInput` and a `motionInfo` (`GameInputMotionInfo`, Microsoft's v0 layout); `IGameInputReading::GetMotionState` -returns a `GameInputMotionState` on their readings, and `GetCurrentReading`/`GetNextReading` answer a -`GameInputKindMotion` query for such a pad and return `GAMEINPUT_E_READING_NOT_FOUND` for a pad without sensors. A -reading callback registered for `GameInputKindMotion` hears only such pads: like a device callback, it is limited to -devices that support at least one of the kinds it names (Microsoft's `RegisterReadingCallback` reference). The -sensors are enabled when the pad is opened, at SDL's requested rate, and every poll reads the latest sample. - -- The state carries **signed fractions of the maxima `motionInfo` reports** (1.0 = full magnitude), which is the - convention Microsoft documents for `GameInputMotionState`. SDL delivers accel in m/s² (gravity included) and gyro - in rad/s, so the shim divides by the maxima. The maxima are this shim's choice — SDL does not expose a sensor - range — and are 2 g (19.6133 m/s²) and 2000 deg/s (34.9066 rad/s), a DualSense's accelerometer and gyro ranges - (VERIFY against the game and a real pad). -- A pad at rest sits at about 0.5 on the gravity axis and 0.0 on all gyro axes. SDL answers sensor reads with zeros - before the device's first sample arrives; since a real accelerometer never reads exactly zero (gravity), all-zero - accel means "no sample yet" and the reading carries no motion at all — `GetMotionState` returns false. -- SDL's gamepad API has no compass and the shim synthesises no orientation quaternion, so the magnetic-field and - orientation members are zero with `GameInputMotionAccuracyUnknown`. -- A pad with sensors streams a reading every ~8 ms (~125 Hz) even when nothing else changes, so motion is not stuck - at the last button event; pads without sensors keep the old change-driven behaviour. The 8 ms window and the 512- - reading history cap bound the cost. -- `gameinput_probe` prints the accel and gyro fractions when the pad has sensors (a resting pad shows ~0.5 g). - -## Active input - -The title is told that every pad is an Xbox One pad, so it cannot know what the player is holding. The shim keeps -that record itself, for the runtime's own use, such as button prompt glyphs that follow the device in use: -`rt::gameinput::active_input()` returns the family of the device used last, a generation that goes up by one with each -change, and whether `LEONIDA_PROMPTS` forced it. It needs no lock and can be read from any thread, every frame. - -| SDL gamepad type | family | -|---|---| -| `PS5` (DualSense, DualSense Edge) | PlayStation 5 | -| `PS4` (DualShock 4) | PlayStation 4 | -| `PS3` (DualShock 3) | PlayStation 3 | -| `NINTENDO_SWITCH_PRO`, the Joy-Con types | Nintendo | -| the [keyboard pad](#keyboard-pad) | keyboard and mouse | -| everything else (Xbox One/Series, Xbox 360, generic, unknown) | Xbox | - -SDL takes the type from the pad's vendor and product id. Only deliberate input changes the answer -(`runtime/src/active_input.h`, tested by `active_input_test` without SDL): - -- an edge: a button going down (any of SDL's, the DualSense touchpad included), a trigger rising past 0.3, or a stick - leaving a radius of 0.35. A held button, trigger or stick, stick drift inside the radius and analog noise never - count. The mouse moves the keyboard pad's right stick, so a real mouse movement counts through the same rule and a - jitter of a count or two does not; -- a pad's first reading after it connects is its baseline, so connecting a pad with a button held, or with a worn - stick resting past the radius, changes nothing; -- after a change, the next one waits `LEONIDA_PROMPTS_SWITCH_MS` (300 ms by default). Input from another family inside - that time is ignored, not queued, so two devices used at once cannot make the answer flicker; -- input from a second device of the family already in use changes nothing. - -Before the first deliberate input the answer is Xbox. Each change logs one line, for example -`input in use: PlayStation 5 (DualSense Wireless Controller, button press)`. `LEONIDA_PROMPTS` forces a family (a -line is logged when it takes effect); tracking goes on underneath, so clearing it returns at once to the device in use. - -## Environment variables - -| variable | default | effect | -|---|---|---| -| `LEONIDA_DS_TRIGGERS` | `rumble` | DualSense trigger effects: `off`, `rumble` or `resistance` (above) | -| `LEONIDA_DS_TRIGGER_GAIN` | `1` | scales the trigger level before it becomes an effect, 0..4 | -| `LEONIDA_DS_TRIGGER_FREQ` | `30` | vibration frequency of the `rumble` mode, 1..255 | -| `LEONIDA_DS_LIGHTBAR` | unset | `RRGGBB` (hex) sets the DualSense/DualShock 4 lightbar when the pad connects; `off` turns it dark; unset keeps SDL's player colour | -| `LEONIDA_RUMBLE` | `1` | `0` turns all rumble, trigger and force-feedback output off | -| `LEONIDA_PROMPTS` | `auto` | forces the [active input](#active-input) family: `xbox`, `playstation` (or `ps5`), `ps4`, `ps3`, `nintendo` or `keyboard`; `auto` follows the devices | -| `LEONIDA_PROMPTS_SWITCH_MS` | `300` | shortest time between two changes of the active input family, 0..2000 ms | -| `LEONIDA_GAMEINPUT_THREAD` | `1` | `0` stops the background poll thread; only `rt::gameinput::poll()` then reads the pads (tests) | -| `LEONIDA_KEYBOARD_PAD` | `off` | `1` adds the [keyboard pad](#keyboard-pad), read while this process has focus; `always` reads keys whatever has focus | -| `LEONIDA_MOUSE_SENSITIVITY` | `1` | scales how far the mouse moves the keyboard pad's right stick, 0.1..10 | - -SDL's own hints (`SDL_JOYSTICK_*`, see SDL's `SDL_hints.h`) also apply, for example `SDL_JOYSTICK_HIDAPI_PS5=0` to -leave a DualSense to the generic driver, or `SDL_GAMECONTROLLERCONFIG` to add a mapping for an unknown pad. - -## How it runs - -One thread owns SDL: a background thread started by the first `GameInputCreate` that polls every 2 ms. It opens new -pads, closes removed ones, takes a reading of each, and applies rumble, haptic and force-feedback requests. Title calls -never touch SDL: they read the latest reading or leave a request, so a call costs a lock and a copy. Callbacks (device, reading, guide -button) run on that thread, as GameInput runs them on its own threads. Once the title creates a dispatcher -(`IGameInput::CreateDispatcher`), callbacks are queued instead, the dispatcher's wait handle is signalled, and -`IGameInputDispatcher::Dispatch` runs them on the title's thread, oldest first, within its quota: at least one queued -event per call (a quota of 0 runs exactly one), no further event once the quota has passed, and only the events -queued when the call started (later ones wait for the next call, so even an unlimited quota returns). The wait -handle is signalled again while events remain. - -The API surface: - -| interface | implemented | not implemented | -|---|---|---| -| `IGameInput` | `GetCurrentTimestamp` (µs), `GetCurrentReading`, `GetNextReading`, `GetPreviousReading`, `RegisterReadingCallback`, `RegisterDeviceCallback` (blocking and async enumeration), `RegisterGuideButtonCallback`, `RegisterKeyboardLayoutCallback` (never fires), `StopCallback`, `UnregisterCallback`, `CreateDispatcher`, `FindDeviceFromId`, `EnableOemDeviceSupport` (no-op), `SetFocusPolicy` (no-op) | `GetTemporalReading` (`E_NOTIMPL`, as in GameInput v0 itself; see below), `CreateAggregateDevice`, `FindDeviceFromObject/PlatformHandle/PlatformString` | -| `IGameInputReading` | kind, sequence number, timestamp, device, gamepad state, UI navigation state, controller axes and buttons, motion state, raw report (pads opened through HID, see [Raw HID](#raw-hid)) | keyboard, mouse, touch, arcade/flight stick, racing wheel (all return nothing) | -| `IGameInputDevice` | device info, status, battery, `SetRumbleState`, force-feedback motors with `CreateForceFeedbackEffect`/`IGameInputForceFeedbackEffect`, `IsForceFeedbackMotorPoweredOn`, `SetForceFeedbackMotorGain`, haptic trigger motors with `SetHapticMotorState`, `CreateRawDeviceReport`, `GetRawDeviceFeature`, `SetRawDeviceFeature`, `SendRawDeviceOutput` (pads opened through HID) | `SendRawDeviceOutputWithResponse`, `ExecuteRawDeviceIoControl`, exclusive raw access, power off, input synchronization (no-ops) | -| `IGameInputRawDeviceReport` | device, report info (kind, id, size), raw data size, get and set raw data | item values (`Get/Set/ResetItemValue`, `ResetAllItems` answer false: no item tables) | -| `IGameInputReading` | kind, sequence number, timestamp, device, gamepad state, UI navigation state, controller axes and buttons, motion state | raw report, keyboard, mouse, touch, arcade/flight stick, racing wheel (all return nothing) | -| `IGameInputDevice` | device info, status, battery, `SetRumbleState`, force-feedback motors with `CreateForceFeedbackEffect`/`IGameInputForceFeedbackEffect`, `IsForceFeedbackMotorPoweredOn`, `SetForceFeedbackMotorGain`, haptic trigger motors with `SetHapticMotorState` | raw device I/O, power off, input synchronization (no-ops) | -| `IGameInputDispatcher` | `Dispatch` (with its quota), `OpenWaitHandle` | | - -`CreateAggregateDevice` takes exactly one of the keyboard, mouse, gamepad, arcade stick, flight stick or racing wheel -kinds (none, several, or another kind is `E_INVALIDARG`) and returns one device per kind, the same object on every -call: family `GameInputFamilyAggregate`, always connected, with that kind as its `supportedInput`, and a fixed -`deviceId` per kind that `FindDeviceFromId` also answers. Readings asked -through it (`GetCurrentReading`, `GetNextReading`, `GetPreviousReading`) come from every connected device of that -kind (`GetCurrentReading` answers the most recent of them); asking it for another kind is -`GAMEINPUT_E_READING_NOT_FOUND`. A reading or device callback registered with an aggregate device as its filter is -refused with `E_NOTIMPL` and an invalid token. - -A device object stays alive for the whole process. When a pad is unplugged its status drops to -`GameInputDeviceNoStatus` and its device callback runs; when the same pad is plugged in again (matched by SDL GUID and -serial or device path) the title gets the same object back, connected again. - -## Raw HID - -A title can read a pad's raw HID input reports and send it output and feature reports (RT-175). The shim opens each -pad's HID device through SDL's hidapi (`SDL_hid_*`), by the device path SDL reports for the pad. When that path is not -a HID path, it falls back to the pad's vendor and product id, but only when exactly one game-pad collection (usage page -1, usage 5) has them, so twins never mix. It reads the report descriptor to find every input, output and feature -report: its id (0 when the descriptor declares none) and its payload size in bytes, without the id byte. - -A pad opened this way gets the following: - -- `GameInputKindRawDeviceReport` in `supportedInput` and `GameInputDeviceRawIoEnabled` in its status. -- `inputReportInfo`, `outputReportInfo` and `featureReportInfo` tables with their counts. Every report has `itemCount` - 0: the descriptor's items (usages, logical ranges, units) are not decoded. -- Readings that carry the newest raw input report. Each poll drains the reports that arrived, the last declared one - wins, and a report with new bytes makes a reading of its own. Before the first report, a reading carries none. -- These device calls, each on any `IGameInputRawDeviceReport` of the right kind whose id the pad declares: - - `CreateRawDeviceReport(id, kind)` makes a zeroed report. - - `GetRawDeviceFeature(id)` reads a feature report. - - `SetRawDeviceFeature` sends one. - - `SendRawDeviceOutput` writes an output report. - - An undeclared id or kind is `E_INVALIDARG`, and a failed transfer `E_FAIL`. - -`SetRawData` takes a buffer of exactly the report's size and refuses any other size, so a report is never half old and -half new. The item calls answer false. `SendRawDeviceOutputWithResponse`, `ExecuteRawDeviceIoControl` and exclusive -access still return `E_NOTIMPL` / false. - -A pad without such a HID device keeps the old answers: no raw kind, no tables, `E_NOTIMPL` from the raw calls. - -- **Xbox pads on Windows** are read by SDL through XInput (path `XInput#n`). SDL's hidapi skips their XInput HID - interface (`&IG_` in the path), noting that it carries no full HID reports. So they have no raw I/O here, and the log - says so. -- **SDL virtual joysticks and the keyboard pad** have no path, so no HID device either. -- **Pads SDL reads through hidapi** can have raw I/O: DualSense, DualShock 4, Switch Pro, and most others in DirectInput - mode. - -`rt::gameinput::set_hid_backend` replaces the hidapi backend (tests). `rt::gameinput::parse_report_descriptor` is the -descriptor walk: main items Input, Output and Feature add Report Size × Report Count bits to the current Report ID, Push -and Pop save and restore the globals, and long items are skipped. It refuses a truncated item, Report ID 0 or above -255, a Pop without a Push, and a report over 64 KiB. - -## Reading history - -Each pad keeps the readings the poll took for it, one per change it saw, so `GetNextReading` and `GetPreviousReading` -can step through input the title has not read yet, such as a button pressed and released between two of its frames. -A reading leaves the history once the reading after it is more than 500 ms old, so the current state stays reachable -however long the pad then idles. A pad keeps at most 512 readings, and none once it is unplugged. A reading the title -holds stays valid after it leaves the history. - -- With a device the search covers that pad; with none, every connected pad. Readings of different pads are ordered by - when the shim took them, not by timestamp, since pads polled together share one. -- `GetNextReading` returns the first reading after the reference, `GetPreviousReading` the last one before it. -- The horizon is the newest reading dropped from the histories searched (with no device, the reference's pad counts - too, even unplugged). A step that would cross it fails rather than skip input. - -| situation | result | -|---|---| -| output null; reference null | `E_POINTER`; `E_INVALIDARG` | -| no supported kind in the mask | `GAMEINPUT_E_READING_NOT_FOUND` | -| the device given is unplugged | `GAMEINPUT_E_DEVICE_DISCONNECTED` | -| next: the horizon is after the reference; previous: it is not before it | `GAMEINPUT_E_REFERENCE_READING_TOO_OLD` | -| nothing newer, or nothing older after the horizon | `GAMEINPUT_E_READING_NOT_FOUND` | - -After a pad is plugged back in, its last reading before the unplug leads to the reconnect snapshot, older ones are -`REFERENCE_READING_TOO_OLD`, and sequence numbers carry on. Timestamps are poll times, so a change shorter than one poll -(2 ms with the thread) is not seen. - -### Device identity - -`AppLocalDeviceId` is the SDL GUID in bytes 0-15 and an FNV-1a hash of the serial or path in bytes 16-31. Pads that -SDL cannot tell apart, such as two of the same model with no serial and no path, would share that id, and -`FindDeviceFromId` would return the first for both. They are twins: the first keeps the id, so a single pad's id is -unchanged, and each further one gets an id hashed from its twin number (`t::` before the serial or path). A new id -is checked against every device seen in the process and moved to the next number if taken, so no two devices share -one. A pad that comes back takes the lowest-numbered disconnected twin's object and id; a connected device is never -reused. - -That is assignment by order, not identification. With one twin unplugged, the right object comes back if the same pad -returns, but another identical pad plugged in instead gets it too. With two or more unplugged, nothing tells them -apart: if they return in a different order, the objects and ids are swapped between the physical pads, and the shim -cannot detect it. The same sequence of plugs gives the same ids in every run, since the ids depend only on the GUID, -the serial or path and the order; for pads already connected at start, that order is SDL's (see [VERIFY](#verify)). - -## ABI - -`runtime/shims/gameinput_abi.h` declares the v0 GameInput API as Leonida's own code: the interfaces in vtable order, -the enums the shim uses and the structs it has to lay out. It was written against Microsoft's public v0 header (the -GDK version, also published as the `Microsoft.GameInput` NuGet package 0.2303.22621.3038). The header is not in the -repository. Its struct offsets were checked by compiling both side by side with `offsetof` asserts for every field the -shim fills (`GameInputDeviceInfo` 320 bytes with `deviceFamily` at 96 and the info pointers from 160, -`GameInputGamepadState` 28 bytes, and the rest in `gameinput_abi.h`). Four structs had only their size compared, or -were taken as empty, and were wrong: `GameInputControllerAxisInfo` (48 bytes) and `GameInputControllerButtonInfo` (32) -have a `GameInputLabel` at offset 4, in what would otherwise be padding, so the members behind it sat four bytes early, -and `GameInputGamepadInfo` and `GameInputUiNavigationInfo` are tables of 14 and 21 labels (56 and 84 bytes). Every -member of the four now compares equal side by side, and `gameinput_abi.h` pins each offset. The host's GameInput 0.2309 -fills the two tables in that order: a DualSense (`054c:0ce6`) over USB has the cross, circle, square and triangle icons -for A, B, X and Y, `Menu`, `View`, `Up`/`Down`/`Left`/`Right`, `L1`/`R1` and `L3`/`R3`, and null axis and button arrays. -The shim gives every control the Xbox label of its position on every pad, because every pad is presented as an Xbox -One pad; an Xbox pad's labels on the host are not measured. - -The force-feedback and haptic declarations (`GameInputForceFeedbackMotorInfo`, `GameInputHapticWaveformInfo`, -`GameInputHapticFeedbackMotorInfo`, the envelope and parameter structs, `IGameInputForceFeedbackEffect`) were -transcribed from that header's public source and pinned with the same kind of `static_assert` on their sizes and -fields — they were not compiled against it, since it is not in the repository. That is the one place the shim's ABI -rests on a transcription rather than on a side-by-side compile. - -## Tests - -- `active_input_test` (CTest, no SDL): the [active input](#active-input) tracker's rules on synthetic samples with - its own clock. `gameinput_test` runs them on a DualSense, a DualShock 4 (Sony `054c:09cc`), an Xbox pad and the - keyboard pad: no change when pads connect (one with a button held) or a held button is let go, each family by a - button, the touchpad, a trigger or a stick, stick drift and a one-count mouse jitter ignored, a real mouse movement - counted, the 300 ms window on the real clock, and `LEONIDA_PROMPTS` forcing, changing, ignoring an unknown value - and clearing. -- `gameinput_test` (CTest, no controller): turns SDL's real backends off and drives the shim through - `rt::shims::find` with SDL virtual joysticks, an Xbox-style pad with trigger motors, a DualSense (Sony - `054c:0ce6`) and a pad without trigger motors. It checks enumeration and device callbacks, the button, stick, - trigger and UI-navigation mapping, reading callbacks and sequence numbers, the reading history (a tap read after - the fact, both directions, two pads interleaved and filtered by device, ageing out, held readings, unplug and - replug), the guide button, motor and trigger - rumble as SDL receives them, the DualSense effect bytes in each `LEONIDA_DS_TRIGGERS` mode, the lightbar, a - dispatcher and its quota, async and blocking enumeration, unregistering, unplugging and replugging, and three identical pads - (an id each, `FindDeviceFromId` and device-filtered readings per pad, replugging one, two and all three, and the - first twin's id equal to the single-pad id). Motion runs on a virtual pad with sensors (`nsensors` in the - virtual-joystick description, fed with `SDL_SendJoystickVirtualSensorData`): the kind and `motionInfo` on a sensor - pad and not on a plain one, no motion before the first sample, normalisation against the `motionInfo` maxima, the - accuracy values, the ±1 clamp, the ~8 ms cadence, that a motion query on a pad without sensors is - `GAMEINPUT_E_READING_NOT_FOUND`, and that a Motion reading callback hears only the sensor pad. The keyboard pad is - driven through `rt::gameinput::set_keyboard_source` and `set_cursor_source` with fake keys, focus and cursor: every - binding, two keys at once, each WASD direction, opposite keys cancelling, diagonals, the mouse moving the right - stick, clamping and decaying to 0, the mouse-button triggers, no input out of focus, release of buttons, sticks and - triggers on focus loss, the `always` mode, and turning it off and on again. - Raw HID (RT-175) is tested in two ways: - - `parse_report_descriptor` runs on synthetic descriptors: report ids, none, Push/Pop, a long item, and the refused - forms. - - A fake backend (`set_hid_backend`) stands behind a virtual pad with pid.codes test ids. The test checks the report - tables, the kind and status bits, a reading's raw report (newest declared id, without the id byte, an undeclared id - ignored), creating, sending and reading back output and feature reports with their id byte, `SetRawData`'s exact - size, the item calls, `E_INVALIDARG` / `E_FAIL` / `E_NOTIMPL`, and the HID device closing on unplug. -- `gameinput_probe [--seconds N] [--rumble] [--force-feedback]` (by hand, with a pad connected): lists the pads with - each one's raw HID report tables (or why it has none), plays each motor and trigger for a second with `--rumble`, - holds a constant force at magnitude 1.0 on motor 0 for a second with `--force-feedback` (skipped, with the reason - printed, on a pad the shim reports no force-feedback motor for), and prints whether SDL created that effect and is - running it, separately from GameInput accepting it, then prints the live reading and the newest raw input report. - -On hardware so far, with `gameinput_probe` and SDL 3.4.20 on Windows 11: a DualSense (`054c:0ce6`) over USB. It -connects as player 1 with trigger effects and gyro (`motors=0xf forcefeedback=0 haptic=2`). Pressed one at a time, -each of the 14 gamepad buttons set the one bit of the name [Mapping](#mapping) gives it: Cross, Circle, Square and Triangle -as `A`, `B`, `X` and `Y`, the d-pad, L1/R1, L3/R3, Create as `View` and Options as `Menu`. Both triggers reached -1.00 and both sticks -1.00 and +1.00 on each axis. At rest the accelerometer read about 0.5 on one axis and the gyro -0.0; shaking the pad by hand reached 1.00 on the accelerometer. With `--rumble` (the default `rumble` trigger mode) -and `LEONIDA_DS_LIGHTBAR=00ff00`, the person holding the pad reported the motors, the trigger effects and the lightbar -as working; nothing measured them, and the `resistance` mode was not tried. - size, the item calls, `E_INVALIDARG` / `E_FAIL` / `E_NOTIMPL`, the HID device closing on unplug, and a held - reading's `GetRawReport` waiting while a reconnect rebuilds the report tables. -- `gameinput_probe [--seconds N] [--rumble]` (by hand, with a pad connected): lists the pads with each one's raw HID - report tables (or why it has none), plays each motor and trigger for a second with `--rumble`, then prints the live - reading and the newest raw input report. - -## VERIFY - -These need the game executable or a test on hardware: - -- **Which API version and module.** The shim is GameInput v0 and registers `GameInputCreate` under `gameinput.dll` - and `xgameruntime.dll`. GameInput v1 and later (NuGet 1.x and up) changed the interfaces; if the executable was - built against one of those, the vtables need a second set. -- **IIDs.** `QueryInterface` answers the v0 IIDs from the public header. -- **Reading history.** Microsoft's [next reading](https://learn.microsoft.com/en-us/gaming/gdk/docs/reference/input/gameinput/interfaces/igameinput/methods/igameinput_getnextreading) - and [previous reading](https://learn.microsoft.com/en-us/gaming/gdk/docs/reference/input/gameinput/interfaces/igameinput/methods/igameinput_getpreviousreading) pages describe half a second of readings per device and failure when old readings leave the stream. The table above records the shim's HRESULT choices. Changes faster than the poll are not seen. - `GetTemporalReading` returns `E_NOTIMPL` with a null reading on purpose: Microsoft's - [reference page](https://learn.microsoft.com/en-us/gaming/gdk/docs/reference/input/gameinput/deprecated/interfaces/igameinput/methods/igameinput_gettemporalreading) - says it "was never implemented in v0" and returns `E_NOTIMPL`, and v1 removed it. The v0 header (NuGet - `Microsoft.GameInput` 0.2303.22621.3038) declares it as `(timestamp, device, reading)`, the layout the shim has; - the page's five-parameter form does not match that header. -- **UI navigation mapping** and the **controller-axis convention** (0..1 with sticks at 0.5) are this shim's choice, - not measured from a console. -- **Battery capacity** is reported as a fraction (remaining 0..1 of full 1), not in device units. -- **`UnregisterCallback` timeout** is not honoured; it waits for a callback that is running. -- **Motion normalisation maxima** (2 g accel, 2000 deg/s gyro) are this shim's choice; SDL exposes no sensor range, - and whether the game reads motion, and against what scale, is unknown until it runs. The accelerometer range a - DualSense exposes can also be wider than 2 g, so hard shakes may clamp at 1.0: a hand shake of a real DualSense - did reach 1.00 on one axis. -- **Motion members the shim does not provide** (magnetic field, orientation) are zero with - `GameInputMotionAccuracyUnknown`; whether a title wants a synthesised quaternion there is unknown. -- **Device family**: every pad is reported as `GameInputFamilyXboxOne`; a title that filters on family sees only - that. -- **Active input behind Steam Input**: when Steam turns a PlayStation pad into a virtual Xbox pad, SDL may report the - virtual one's type, and the active input then says Xbox; `LEONIDA_PROMPTS` is the way round it until that is - checked on a real setup. -- **Identical pads at start**: twins are numbered in the order the shim opens them. For pads already connected when - it starts, that is SDL's enumeration order, not measured on Windows for identical pads; if it varies between runs, - so does which pad gets which id. -- **Raw mouse registration**: Windows keeps one raw-input target window per device type and process, so if the title - registers raw mouse input itself (a console title is not expected to), it replaces the shim's registration and the - right stick falls back to nothing. The shim does not detect that yet. -- **Keyboard pad as a second pad**: it is one more connected gamepad, so with a controller plugged in the title sees - two. A title that follows only the first pad it saw, or asks the player to press a button to pick the active pad, - may ignore one of them; whether the game does either is unknown. -- **Mouse on the right stick**: the scale (1024 units per pixel per poll) and decay (7/8 per poll) are a starting - point, not tuned in game. The title adds its own stick acceleration and deadzone on top, so aiming may feel slow - near center or jumpy. -- **Force feedback on hardware**: which pads SDL opens as haptic devices on Windows (a DirectInput wheel or stick, - not an Xbox pad) and how many force-feedback motors a title would really see there. The shim reports one motor with - LinearX; whether a wheel wants a second axis, or LinearY for a stick, is unknown until one is attached. - `gameinput_probe` prints `forcefeedback=` and `haptic=` per pad. -- **How a force-feedback effect feels**: the magnitudes go out 1:1 (SDL's -32767..32767 from GameInput's -1..1) with - no scaling beyond the two gains. Whether a game's curb weight, road texture and crash feel right, and whether - `SDL_SetHapticGain` is the right place for a motor's master gain on the driver SDL picks, needs a wheel in game. -- **Envelope and phase units**: GameInput's `phase` is read as degrees (SDL takes hundredths of a degree) and its - durations as microseconds summed into SDL's `length`. Neither came from a measurement, only from the header's - remarks. -- **A new effect starting stopped or running**: the shim starts it running, because the documented use creates an - effect once and only ever calls `SetParams`. A title that creates one and waits for `SetState` would play a frame - early; whether this one does is unknown until it runs. -- **Haptic waveforms**: the single intensity waveform (usage 0x0F/0x58) is this shim's choice, not the pad's table, so - a title that asks for a particular waveform gets intensity-only behaviour. Whether the game uses haptic motors at - all — as opposed to `SetRumbleState` — is unknown. -- **Raw HID on a real pad**: the synthetic tests, the XInput refusal and one DualSense over USB have run. - - What ran: an Xbox Series X controller over Bluetooth on Windows 11 connects and plays normally, with no raw I/O, - and the log names the reason. - - What ran: a DualSense (`054c:0ce6`) over USB on Windows 11 through `gameinput_probe`. Its descriptor gives 1 - input report (id 1, 63 bytes), 1 output report (id 2, 47 bytes) and 20 feature reports, and the raw input report - changed on every reading (2,442 distinct reports in a 40 s capture). No output or feature report was sent - through the raw calls. - - Still to confirm: a DualSense over Bluetooth, a DualShock 4 or a Switch Pro through `gameinput_probe`, which - should print the descriptor's reports and changing raw input bytes. - - Size convention: report sizes exclude the id byte, and `GetRawData` returns the payload without it. What - Microsoft's runtime does for a device with report ids is not documented on the reference pages. - - Readings: a pad that streams reports makes a reading for each changed one, like the runtime's - `GameInputKindRawDeviceReport` stream, but whether the title asks for raw reports at all is unknown. diff --git a/docs/gbuffer.md b/docs/gbuffer.md deleted file mode 100644 index 936c6ea85..000000000 --- a/docs/gbuffer.md +++ /dev/null @@ -1,141 +0,0 @@ -# Deferred G-buffer targets and declared output signatures (`PROC-146`) - -Reported by @Silliana in [#1891](https://github.com/ItsNotRexed/Leonida/issues/1891) for `PS_DeferredTextured` and -checked here across all **2,989 `*Deferred*` pixel shaders** (and all **1,703 six-target pixel shaders**) in the -1.0.2.1 `shaders.rpf` corpus. Counts, target masks, numeric constants and format requirements only; no shader text or -disassembly. -checked here across the `*Deferred*` pixel shaders and six-output pixel shaders in the 1.0.2.1 `shaders.rpf` corpus. -Counts, target masks, numeric constants and format requirements only; no shader text or disassembly. - -## 1. Corpus census of deferred pixel-shader output signatures (`OSG1` / `PSV0`) - -Every DXBC container in `shaders.rpf` carries an `OSG1` (and `PSV0`) output signature table with `{register, -semantic_index, component_type, mask, min_precision}` per declared output element. (The FSSM header dword at `+0x0FC` -holds `5` and `6` on the two sampled `PS_DeferredTextured` blobs below, but holds `16` and `18` on two stock vehicle -deferred passes, so target counts must be read from `OSG1` rather than FSSM `+0x0FC`.) - -Depending on whether container names are matched case-insensitively on raw RPF entry names (`2,989` pixel shaders) or -case-sensitively on `Deferred` in the carved `.dxbc` file stems (`3,004` pixel shaders, including `807` -`PS_DeferredTextured` variants: 380 five-target, 371 six-target and 56 three-target): - -| `OSG1` outputs declared | `*Deferred*` PS (entry match / `.dxbc` stem match) | `PS_DeferredTextured` count | Corpus-wide PS (entry / `.dxbc` stem) | `OSG1` component type on all colour targets | Per-target `OSG1` write masks (`SV_Target0..N-1`) | -|---|---:|---:|---:|---|---| -| 6 colour (`SV_Target0..5`) | 953 / 949 | 371 | 955 / 955 | `float32` (`ctype = 3`, `prec = 0`) | `0xF, 0xF, 0xF, 0xF, 0x3, 0xF` (`SV_Target4` mask is 2-component `RG`) | -| 6 colour (`SV_Target0..5`) | 737 / 735 | 0 | 747 / 747 | `float32` (`ctype = 3`, `prec = 0`) | `0xF, 0xF, 0xF, 0xF, 0xF, 0xF` (all six `RGBA`) | -| 5 colour + `SV_Depth` | 0 / 0 | 0 | 1 / 0 | `float32` (`ctype = 3`, `prec = 0`) | `0xF, 0xF, 0xF, 0xF, 0x3` + `SV_Depth` (`0x1`) | -| 5 colour (`SV_Target0..4`) | 1,160 / 1,160 | 380 | 1,168 / 1,166 | `float32` (`ctype = 3`, `prec = 0`) | `0xF, 0xF, 0xF, 0xF, 0x3` (`SV_Target4` mask is 2-component `RG`) | -| 5 colour (`SV_Target0..4`) | 2 / 2 | 0 | 20 / 20 | `float32` (`ctype = 3`, `prec = 0`) | `0xF, 0xF, 0xF, 0xF, 0xF` | -| 3 colour (`SV_Target0..2`) | 125 / 125 | 56 | 248 / 248 | `float32` (`ctype = 3`, `prec = 0`) | `0xF, 0xF, 0x3` (`SV_Target2` mask is 2-component `RG`) | -| other (`0..4` outputs) | 12 / 33 | 0 | — | `float32` (3 single-target `uint32`) | depth-only, discard, or reduced passes | - -The two six-colour-target rows total **1,702** pixel shaders corpus-wide (`955 + 747`; plus 1 five-colour-target + -`SV_Depth` shader with 6 `OSG1` rows = 1,703 six-row `OSG1` tables). In the compiled RDNA2 code across the `*Deferred*` -pixel shaders, **16,306 of 16,306 (100%)** `exp mrtN` instructions use compressed half-float export (`compr`, -`EXP_FORMAT_FP16_ABGR`), fed by `v_cvt_pkrtz_f16_f32`. - -## 2. G-buffer target layout (`mrt0..mrt5`) - -Comparing #1891 against the 5-target (`mrt0..mrt4`) and 6-target (`mrt0..mrt5`) `PS_DeferredTextured` programs (note -that the RTV format column below is **inferred from the shader-side encoding and #1891**, not declared by `OSG1` or a -captured PSO): - -| Target | `OSG1` mask | Inferred RTV format class (from shader encoding / #1891) | Channel layout and shader-side encoding in `PS_DeferredTextured` | -|---|---|---|---| -| `mrt0` (`SV_Target0`) | `0xF` (`RGBA`) | `R8G8B8A8_UNORM` | **Albedo + alpha/material byte:** `rgb` holds base colour/albedo; in the sampled 6-target variant `a` packs a byte extracted from an integer register (`ubyte0`) and scaled by `1.0 / 255.0` (`0x3b808081`). | -| `mrt1` (`SV_Target1`) | `0xF` (`RGBA`) | `R8G8B8A8_UNORM` | **Scalar in `r` + 24-bit octahedral world normal split across `g`, `b`, `a`:** see section 3 below. | -| `mrt2` (`SV_Target2`) | `0xF` (`RGBA`) | `R8G8B8A8_UNORM` | **Square-root encoded channels:** producer applies hardware square root (`sqrt(x)` or `sqrt(1.0 - sqrt(x))`) before `v_cvt_pkrtz_f16_f32` export; #1891 notes that the lighting consumer squares `mrt2` back (tentatively specular / $F_0$ material terms, pending lighting-consumer verification). | -| `mrt3` (`SV_Target3`) | `0xF` (`RGBA`) | `R8G8B8A8_UNORM` | **Flags + byte IDs:** `x` and `y` carry clamped `[0, 1]` values biased by a dither term (`scale = 2.0 / 255.0` = `0x3c008081`, `offset = -1.0 / 255.0` = `0xbb808081`); `z` and `w` carry two 8-bit integer IDs extracted with byte-to-float conversion (`ubyte0`, `ubyte1`) and multiplied by `1.0 / 255.0` (`0x3b808081`). | -| `mrt4` (`SV_Target4`) | `0x3` (`RG`, 2,113 / 2,109 deferred PS) or `0xF` (`RGBA`, 739 / 737 deferred PS) | Float format (e.g. `R16G16_FLOAT`) | **Motion vectors:** unscaled signed float screen-space motion offset (`xy`; in the sampled 5- and 6-target `PS_DeferredTextured` disassembly with `mask = 0x3`, exported as `exp mrt4, vN, vN, off, off compr`). | -| `mrt5` (`SV_Target5`) | `0xF` (`RGBA`, 1,690 / 1,684 deferred PS) | `R8G8B8A8_UNORM` | **Sixth deferred target** on the 6-target permutations (`rgb` material terms + clamped alpha). | - -## 3. The 24-bit octahedral normal in `mrt1.gba` and why binding `f16` targets breaks lighting -semantic_index, component_type, mask, min_precision}` per declared output element. (The FSSM header dword at `+0x0FC` -holds `5` and `6` on the two sampled `PS_DeferredTextured` blobs below, but holds `16` and `18` on two stock vehicle -deferred passes, so target counts must be read from `OSG1` rather than FSSM `+0x0FC`.) - -Depending on whether container names are matched case-insensitively on raw RPF entry names (`2,989` pixel shaders) or -case-sensitively on `Deferred` in the carved `.dxbc` file stems (`3,004` pixel shaders, including `807` -`PS_DeferredTextured` variants: 380 five-target, 371 six-target and 56 three-target): - -| `OSG1` outputs declared | `*Deferred*` PS (entry match / `.dxbc` stem match) | `PS_DeferredTextured` count | Corpus-wide PS (entry / `.dxbc` stem) | `OSG1` component type on all colour targets | Per-target `OSG1` write masks (`SV_Target0..N-1`) | -|---|---:|---:|---:|---|---| -| 6 colour (`SV_Target0..5`) | 953 / 949 | 371 | 955 / 955 | `float32` (`ctype = 3`, `prec = 0`) | `0xF, 0xF, 0xF, 0xF, 0x3, 0xF` (`SV_Target4` mask is 2-component `RG`) | -| 6 colour (`SV_Target0..5`) | 737 / 735 | 0 | 747 / 747 | `float32` (`ctype = 3`, `prec = 0`) | `0xF, 0xF, 0xF, 0xF, 0xF, 0xF` (all six `RGBA`) | -| 5 colour + `SV_Depth` | 0 / 0 | 0 | 1 / 0 | `float32` (`ctype = 3`, `prec = 0`) | `0xF, 0xF, 0xF, 0xF, 0x3` + `SV_Depth` (`0x1`) | -| 5 colour (`SV_Target0..4`) | 1,160 / 1,160 | 380 | 1,168 / 1,166 | `float32` (`ctype = 3`, `prec = 0`) | `0xF, 0xF, 0xF, 0xF, 0x3` (`SV_Target4` mask is 2-component `RG`) | -| 5 colour (`SV_Target0..4`) | 2 / 2 | 0 | 20 / 20 | `float32` (`ctype = 3`, `prec = 0`) | `0xF, 0xF, 0xF, 0xF, 0xF` | -| 3 colour (`SV_Target0..2`) | 125 / 125 | 56 | 248 / 248 | `float32` (`ctype = 3`, `prec = 0`) | `0xF, 0xF, 0x3` (`SV_Target2` mask is 2-component `RG`) | -| other (`0..4` outputs) | 12 / 33 | 0 | — | `float32` (3 single-target `uint32`) | depth-only, discard, or reduced passes | - -The two six-colour-target rows total **1,702** pixel shaders corpus-wide (`955 + 747`; plus 1 five-colour-target + -`SV_Depth` shader with 6 `OSG1` rows = 1,703 six-row `OSG1` tables). In the compiled RDNA2 code across the `*Deferred*` -pixel shaders, **16,306 of 16,306 (100%)** `exp mrtN` instructions use compressed half-float export (`compr`, -`EXP_FORMAT_FP16_ABGR`), fed by `v_cvt_pkrtz_f16_f32`. - -## 2. G-buffer target layout (`mrt0..mrt5`) - -Comparing #1891 against the 5-target (`mrt0..mrt4`) and 6-target (`mrt0..mrt5`) `PS_DeferredTextured` programs (note -that the RTV format column below is **inferred from the shader-side encoding and #1891**, not declared by `OSG1` or a -captured PSO): - -| Target | `OSG1` mask | Inferred RTV format class (from shader encoding / #1891) | Channel layout and shader-side encoding in `PS_DeferredTextured` | -|---|---|---|---| -| `mrt0` (`SV_Target0`) | `0xF` (`RGBA`) | `R8G8B8A8_UNORM` | **Albedo + alpha/material byte:** `rgb` holds base colour/albedo; in the sampled 6-target variant `a` packs a byte extracted from an integer register (`ubyte0`) and scaled by `1.0 / 255.0` (`0x3b808081`). | -| `mrt1` (`SV_Target1`) | `0xF` (`RGBA`) | `R8G8B8A8_UNORM` | **Scalar in `r` + 24-bit octahedral world normal split across `g`, `b`, `a`:** see section 3 below. | -| `mrt2` (`SV_Target2`) | `0xF` (`RGBA`) | `R8G8B8A8_UNORM` | **Square-root encoded channels:** producer applies hardware square root (`sqrt(x)` or `sqrt(1.0 - sqrt(x))`) before `v_cvt_pkrtz_f16_f32` export; #1891 notes that the lighting consumer squares `mrt2` back (tentatively specular / $F_0$ material terms, pending lighting-consumer verification). | -| `mrt3` (`SV_Target3`) | `0xF` (`RGBA`) | `R8G8B8A8_UNORM` | **Flags + byte IDs:** `x` and `y` carry clamped `[0, 1]` values biased by a dither term (`scale = 2.0 / 255.0` = `0x3c008081`, `offset = -1.0 / 255.0` = `0xbb808081`); `z` and `w` carry two 8-bit integer IDs extracted with byte-to-float conversion (`ubyte0`, `ubyte1`) and multiplied by `1.0 / 255.0` (`0x3b808081`). | -| `mrt4` (`SV_Target4`) | `0x3` (`RG`, 2,113 / 2,109 deferred PS) or `0xF` (`RGBA`, 739 / 737 deferred PS) | Float format (e.g. `R16G16_FLOAT`) | **Motion vectors:** unscaled signed float screen-space motion offset (`xy`; in the sampled 5- and 6-target `PS_DeferredTextured` disassembly with `mask = 0x3`, exported as `exp mrt4, vN, vN, off, off compr`). | -| `mrt5` (`SV_Target5`) | `0xF` (`RGBA`, 1,690 / 1,684 deferred PS) | `R8G8B8A8_UNORM` | **Sixth deferred target** on the 6-target permutations (`rgb` material terms + clamped alpha). | - -## 3. The 24-bit octahedral normal in `mrt1.gba` and `UNORM8` vs `FLOAT16` storage - -`PS_DeferredTextured` does not store a 3-channel `(nx, ny, nz)` normal in `mrt1`. Instead: - -1. The unit world normal `(nx, ny, nz)` is divided by its $L_1$ norm $|nx| + |ny| + |nz|$ and octahedral-folded across - the $nz \le 0$ hemisphere into $(u, v) \in [-1, 1]^2$. -2. Both coordinates are quantized to 12-bit unsigned integers $q_u, q_v \in [0, 4095]$ with the scale constant - `2047.5` (`0x44fff000`): - $$q_u = \operatorname{uint32}(u \cdot 2047.5 + 2047.5), \qquad q_v = \operatorname{uint32}(v \cdot 2047.5 + 2047.5)$$ -3. The two 12-bit integers are combined into one 24-bit word $q = (q_v \ll 12) \mid q_u$ (`q_u` in bits `[11:0]`, - `q_v` in bits `[23:12]`). -4. The three bytes of $q$ (`ubyte0 = q[7:0]`, `ubyte1 = q[15:8]`, `ubyte2 = q[23:16]`) are converted to `f32`, - multiplied by `1.0 / 255.0` (`0x3b808081`), rounded toward zero to `f16` (`v_cvt_pkrtz_f16_f32`), and exported to - `mrt1.g`, `mrt1.b`, and `mrt1.a`. - -### Arithmetic across all 256 byte values and consequence for the runtime - -- **Declared signatures do not separate `UNORM8` from `FLOAT16`:** because `OSG1` and `PSV0` declare `float32` on all - six `SV_Target0..5` outputs and the RDNA2 code uses `exp mrtN ... compr` (`EXP_FORMAT_FP16_ABGR`) for all of them, - neither the DXBC signature nor the FSSM export opcode indicates that `mrt0..mrt3` (and `mrt5`) are `R8G8B8A8_UNORM` - while `mrt4` is a float motion target. -- **Why binding `R16G16B16A16_FLOAT` to `mrt1` or `mrt3` corrupts the packed bytes:** `v_cvt_pkrtz_f16_f32` rounds - `byte * (1.0 / 255.0)` **toward zero** (`RTZ`), producing an `f16` value slightly *below* `byte / 255.0` for most byte - values `1..254`. When `mrt1` is bound as `R8G8B8A8_UNORM`, the render-target output stage quantizes with - $\lfloor x \cdot 255.0 + 0.5 \rfloor$ and restores the exact byte `0..255`. When `mrt1` is bound as an `f16` float - target and the lighting pass reconstructs the bytes by multiplying by `255.0`, the RTZ truncation drops 1 LSB on - `ubyte1` (bits `[15:8]`, which straddles the 12-bit split between $q_u$ and $q_v$) and `ubyte2` (bits `[23:16]`), - shifting the reconstructed normal by whole octahedral steps and producing speckled lighting (#1891). -- The runtime must always bind the PSO's declared `RTVFormats[]` (`R8G8B8A8_UNORM` for the byte-packed G-buffer targets - and a float format for `mrt4`) and must never infer `R16G16B16A16_FLOAT` for all G-buffer attachments from `OSG1` or - `exp ... compr`. -### Arithmetic across all 256 byte values and consequence for the runtime - -- **Declared signatures do not separate `UNORM8` from `FLOAT16`:** because `OSG1` and `PSV0` declare `float32` on all - six `SV_Target0..5` outputs and the RDNA2 code uses `exp mrtN ... compr` (`EXP_FORMAT_FP16_ABGR`) for all of them, - neither the DXBC signature nor the FSSM export opcode indicates which G-buffer targets are `R8G8B8A8_UNORM` and which - target (`mrt4`) is a float motion target. -- **`UNORM8` vs `SFLOAT16` round-trip across `b = 0..255`:** `v_cvt_pkrtz_f16_f32(float32(b) * 0x3b808081)` rounds - **toward zero** (`RTZ`) to binary16, placing all **254 intermediate bytes (`b = 1..254`)** slightly *below* `b / 255.0` - (with a maximum shortfall of `0.1240234375` of a byte before integer conversion): - - When the attachment is `R8G8B8A8_UNORM`, the render-target output stage quantizes with nearest-integer rounding - ($\lfloor x \cdot 255.0 + 0.5 \rfloor$) and stores **256 of 256** bytes exactly in every channel. - - When the attachment is `R16G16B16A16_SFLOAT`, the stored binary16 RTZ value is kept verbatim. How a downstream - lighting shader recovers each byte from `x * 255.0` determines whether a 1-LSB error occurs: **nearest-integer - rounding** recovers **256 of 256** bytes, whereas **integer truncation** (`uint32(x * 255.0)`) recovers only - **2 of 256** bytes (`0` and `255`) and yields `b - 1` on all **254** intermediate values `1..254` across all three - byte positions (`ubyte0`, `ubyte1`, `ubyte2`). When `ubyte1` (bits `[15:8]`, straddling the 12-bit boundary between - $q_u$ and $q_v$) or `ubyte2` (bits `[23:16]`) drops by 1 under a truncating consumer, the reassembled 24-bit - octahedral normal shifts by large steps (#1891; actual lighting-consumer decode and PSO formats remain to be - verified against the lighting pass). -- The runtime must therefore bind the PSO's declared `RTVFormats[]` rather than inferring `R16G16B16A16_FLOAT` for all - G-buffer attachments from `OSG1` or `exp ... compr`. diff --git a/docs/gpu_test_results.md b/docs/gpu_test_results.md deleted file mode 100644 index c63966620..000000000 --- a/docs/gpu_test_results.md +++ /dev/null @@ -1,184 +0,0 @@ -# GPU test results - -This page keeps a local record of GPU test runs. The project's public tracker is -[#166](https://github.com/ItsNotRexed/Leonida/issues/166) (one comment per GPU and driver); -post counts and pass/fail lines there, never game shaders, logs or private paths. - -| GPU | Driver, OS | Commit | build.py | check.py | run_gpu_tests.py | Failed | Entry | -|---|---|---|---|---|---|---|---| -| AMD Radeon RX 9070 GRE (RDNA4, GFX1201), subgroup 32..64 | RADV, Mesa 26.3.1-arch3.5, Vulkan 1.4.363, CachyOS | `05961f0` | 264/264 translated and valid | 203/206 pass, 3 skipped | 218/235 passed, 16 skipped (native and emulated) | `ms_wave_info_s3`, flaky (see below) | [local note](../gpu-test-results/RX9070GRE.txt) | -| AMD Radeon RX 9070 XT (RDNA4, GFX1201), subgroup 32..64 | AMD 26.11.2 (LLPC), Vulkan 1.4.359, Windows 11 26300.9550 | `5d74c27` | not run | not run | 224/241 passed, 16 skipped, 1 failed (native); 225/241 passed, 0 failed (`LEONIDA_W64_EMULATE=1`) | `ms_wave_info_s3`, every native run, flaky emulated (see below) | [local note](../gpu-test-results/RX9070XT.txt) | -| AMD Radeon RX 7900 GRE (RDNA3, gfx1100), subgroup 32..64 | AMD proprietary 26.11.2 (LLPC), Vulkan 1.4.359, Windows 11 x64 | `5d74c27` | 247/247 translated and valid | run via run_gpu_tests.py | 225/241 passed, 16 skipped | none | [#166](https://github.com/ItsNotRexed/Leonida/issues/166#issuecomment-7115041436) | -| Intel Graphics (Meteor Lake, Xe-LPG), subgroup 8..32 | ANV, Mesa 26.2.7, Vulkan 1.4.354, Fedora 45 | `84347bb` | 279/279 translated and valid | 177/219 pass, 40 skipped, 2 failed | 194/248 passed, 52 skipped (native); 226/248 passed, 20 skipped (`LEONIDA_W64_EMULATE=1`) | `cs_imgload_tfe`, `cs_imgload_d16_tfe` (#31; pass with #98) | [local note](../gpu-test-results/IntelMTL.txt) | -| NVIDIA GeForce GTX 1080 (Pascal / GP104), subgroup 32..32 | NVIDIA 582.78, Vulkan 1.4.312, Windows 11 Pro 10.0.26300 | `0edd0b6` | not run | not run | 257 shaders: 256 translated, 256 pass spirv-val; 187/248 passed, 59 skipped, 2 failed | `cs_imgload_tfe`, `cs_imgload_d16_tfe` (#31; pass with #98) | [local note](../gpu-test-results/GTX1080.txt) | - -## AMD Radeon RX 9070 GRE — 2026-11-23 - -``` -GPU: AMD Radeon RX 9070 GRE (RDNA4 / GFX1201, Navi 48, PCI 1002:7550), subgroup 32..64 -Driver: RADV (Mesa 26.3.1-arch3.5), Vulkan 1.4.363 -Subgroup: 32..64 (minSubgroupSize 32, maxSubgroupSize 64; default 64) -OS: CachyOS, kernel 7.3.5-2-cachyos -Commit: 05961f0eeb24486ce25ddc7dfb453ca87db2be5f (main, 2026-11-23) -Tools: llvm-mc 23.1.5 (native), SPIRV-Tools v2026.4, CMake 4.4.5 + Ninja 1.13.2, GCC 16.2.1, Python 3.14.9 -build.py: 264 shaders: 264 translated, 264 pass spirv-val (6 mesh fixtures not built: ms_clip, ms_f16_pack, ms_tri, ms_v5_workgroup, ms_w64x_ballot, ms_wave_info_s3) -check.py: 203 of 206 pass, 3 skipped (the three mesh fixtures built only by run_gpu_tests.py) -run_gpu_tests.py: 218/235 passed, 16 skipped, 1 failed (native and LEONIDA_W64_EMULATE=1 alike) -Failed: ms_wave_info_s3: at (0,0) got (-1,-1,-1,-1), want (0.0078,0.0078,0.5,1.0). Flaky on this RADV GPU: 1 pass and 2 fails in three isolated --filter reruns; same signature as the known round-44 mesh regression (#6172, fixed by #5741/#5855). Not a new failure. -Skipped: 16 skips are the documented "run by d3d12_*_test / w64_graphics.py" cases. -``` - -Setup: `cmake -S runtime -B runtime/build/linux -G Ninja -DCMAKE_BUILD_TYPE=Release -DLEONIDA_VULKAN_HEADERS_FETCH=ON`; -implicit Vulkan layers disabled (`VK_LOADER_LAYERS_DISABLE='~implicit~'`) because MangoHud/Steam layers are installed. -Inside `run_gpu_tests.py`, 241/241 shaders translated and passed `spirv-val` in both the native and emulated runs. -Every pixel test other than the flaky mesh fixture was exact (4096/4096). - -AI-assisted (Hermes Agent): built `main` at `05961f0`, ran `build.py`, `check.py` and -`run_gpu_tests.py` (native and emulated) on this GPU, and verified the isolated reruns of the one failure. - -## AMD Radeon RX 9070 XT — 2026-11-23 - -``` -GPU: AMD Radeon RX 9070 XT (RDNA4 / GFX1201, Navi 48, PCI 1002:7550), subgroup 32..64 -Driver: AMD proprietary 26.11.2 (LLPC), Vulkan 1.4.359 -Subgroup: 32..64 (minSubgroupSize 32, maxSubgroupSize 64; default 64, subgroupSizeControl) -OS: Windows 11, 10.0.26300.9550 -Commit: 5d74c272363f2703265d44e6aaab1a1df8ddfaf3 (main, 2026-11-23) -Tools: llvm-mc from ROCm/AOMP 18.0-12 (LLVM 19.0.0git), SPIRV-Tools v2026.4, - CMake 4.4.5, Visual Studio 17 2022 generator, MSVC 19.44.35230.0, Python 3.11.9 -run_gpu_tests.py: 247 shaders: 247 translated, 247 pass spirv-val - native: 224/241 passed, 16 skipped, 1 failed - LEONIDA_W64_EMULATE=1: 225/241 passed, 16 skipped, 0 failed -Failed: ms_wave_info_s3: at (0,0) got (-1,-1,-1,-1), want (0.0078,0.0078,0.5,1.0). - Native: 3 of 3 isolated --filter reruns failed. Emulated: the full-suite - run passed it, then 1 of 3 isolated reruns passed, so the emulated path - is flaky here while native fails every time. Same signature as #6172 / - #5273 and as the RTX 4060 record (#8752), where it failed 3 of 3. -Skipped: 16 skips are the documented "run by d3d12_*_test / w64_graphics.py" cases. -``` - -Setup: `cmake -S runtime -B runtime/build` (default Visual Studio 17 2022 generator) and -`cmake --build runtime/build --config RelWithDebInfo`. The suite ran on the AMD LLPC driver with -the project's own `vk_harness`, `vk_compute_test` and `vk_store_test` binaries; no implicit layer -beyond the Vulkan SDK's. Every other pixel and compute case was exact. - -The one failure is worth a note for #6172: on this machine the native 64-wide path fails -`ms_wave_info_s3` on every run, while `LEONIDA_W64_EMULATE=1` passes it most of the time, which is -the shape a lane-set-dependent race takes rather than a driver-specific miscompile. It also -reproduces with an AMD proprietary driver, so the symptom is not tied to RADV or to Mesa's shader -cache. - -`build.py` and `check.py` (the D3D12-side rows in the table) were not run here; the counts above -come from `run_gpu_tests.py`, which builds and translates the same fixtures. - -AI-assisted (Cline): built `main` at `5d74c27` with MSVC, ran `run_gpu_tests.py` native and under -`LEONIDA_W64_EMULATE=1`, and reran the failure in isolation three times each way. - -## AMD Radeon RX 7900 GRE — 2026-11-23 - -``` -GPU: AMD Radeon RX 7900 GRE (RDNA3 / gfx1100, PCI 1002:744C), subgroup 32..64 -Driver: AMD proprietary 26.11.2 (LLPC), Vulkan 1.4.359 -Subgroup: 32..64 (minSubgroupSize 32, maxSubgroupSize 64; default 64) -OS: Windows 11 x64 -Commit: 5d74c2723 (main, 2026-11-23) -Tools: llvm-mc 23.1.5 (MSYS2 UCRT64), Vulkan SDK 1.4.363 / SPIRV-Tools v2026.4, MSVC 14.51 (VS 2026 Community), Python 3.12.1 -build.py: 247 shaders: 247 translated, 247 pass spirv-val - wave64 VS/PS/GS on 32-wide subgroups: tier A: 1, tier C: 1 -check.py: not run separately (run_gpu_tests.py below) -run_gpu_tests.py: 225/241 passed, 16 skipped -Failed: none -Skipped: 16 skips are the documented "run by d3d12_*_test / w64_graphics.py" cases. -``` - -Setup: `scripts\build_runtime.ps1` from a plain PowerShell. Without Ninja on `PATH` it took the cl.exe fallback, which -builds every Vulkan program the GPU tests use. `llvm-mc` came from the MSYS2 package `mingw-w64-ucrt-x86_64-llvm` -(23.1.5, AMDGPU target included) with `C:\msys64\ucrt64\bin` on `PATH`; on an old MSYS2 install, run `pacman -Syu` -until it reports nothing to do before installing it. Loader warnings from installed Medal/OBS Vulkan layers did not -affect the run. This is the first RDNA3 entry: wave64 and mesh shader tests ran natively (all `ms_*` pass). - -AI-assisted (Claude): helped set up the tools and write this entry; the build and test run were done on this GPU. - -## Intel Graphics (Meteor Lake) — 2026-11-24 - -``` -GPU: Intel Graphics (Meteor Lake-P, Xe-LPG, PCI 8086:7d45, integrated), Core Ultra 5 135U -Driver: ANV (Mesa 26.2.7), Vulkan 1.4.354 -Subgroup: 8..32 (minSubgroupSize 8, maxSubgroupSize 32; subgroupSizeControl, computeFullSubgroups) -OS: Fedora Linux 45, kernel 7.3.4-300.fc45.x86_64 -Commit: 84347bbb6 (main, 2026-11-24, after #24) -build.py: 279 shaders: 279 translated, 279 pass spirv-val -check.py: 177 of 219 pass, 40 skipped, 2 failed -run_gpu_tests.py: native 194/248 passed, 52 skipped, 2 failed - LEONIDA_W64_EMULATE=1: 226/248 passed, 20 skipped, 2 failed -Failed: cs_imgload_tfe, cs_imgload_d16_tfe (#31); both pass with #98 on the same main -``` - -The device has no 64-wide subgroup. Natively, the 32 tests that need one skip; under `LEONIDA_W64_EMULATE=1` all 32 -run and pass. Besides the 16 documented "run by d3d12_*_test / w64_graphics.py" cases, four more skip in both modes -because this device cannot run them as written: `ps_bitmask_perm`, `ps_vcmpx_forms`, `ps_w64x_readlane` and -`ps_ij_computed`. The seven texture fixtures of the TEST-399 row in [testing.md](testing.md) pass with this Mesa -26.2.7. That row records 26.2.7 crashing on Iris Xe, so the crash may depend on the GPU generation or on the -distribution's build. The full record, with every skip by name, is in -[`gpu-test-results/IntelMTL.txt`](../gpu-test-results/IntelMTL.txt). - -AI-assisted (Claude Code): built `main` at `84347bb`, ran `build.py`, `check.py` and `run_gpu_tests.py` native and -emulated on this GPU, and reran the tfe pair with #98 applied. - -## NVIDIA GeForce GTX 1080 — 2026-11-24 - -``` -GPU: NVIDIA GeForce GTX 1080 (Pascal / GP104, PCI 10de:1b80), subgroup 32..32 -Driver: NVIDIA 582.78, Vulkan 1.4.312 -Subgroup: 32..32 (minSubgroupSize 32, maxSubgroupSize 32; no 64-wide) -OS: Windows 11 Pro, 10.0.26300 -Commit: 0edd0b669eeaa31ea22fba40060c12432eb8054b (main, 2026-11-24) -Tools: llvm-mc 23.1.6 (conda-forge, AMDGPU target), SPIRV-Tools v2026.4, MinGW GCC 15.2.0, - CMake 4.5.0 + Ninja, Python 3.15.2, Vulkan SDK 1.4.363 headers -run_gpu_tests.py: 257 shaders: 256 translated, 256 pass spirv-val - 187/248 passed, 59 skipped, 2 failed -Failed: cs_imgload_tfe, cs_imgload_d16_tfe (#31): exit 1. vk_store_test reports - "r32 sint (sint view): 64 bad, texel(5,3) = 2071" where the expected value is - 100 - (8y + x) = 71: every texel is off by exactly 2000, the value the fixture - seeds the tfe status VGPR with, so the fetch status VGPR is read but never - written. The float and uint views are exact (0 bad). Both pass with #98 on the - same main (see the Intel MTL record). -Skipped: 59 skips: 31 no 64-wide compute subgroup, 5 no VK_EXT_mesh_shader, 4 - d3d12_m3_frame_test, 4 d3d12_m2_textured_test, 2 d3d12_translated_draw_test, - 2 d3d12_m4_compute_test, 2 d3d12_buffer_uav_test, 4 BaryCoordKHR, 1 - d3d12_m2_formats_test, 1 mesh shading unavailable, 1 no 64-wide fragment - subgroup (ps_w64x_readlane), 1 w64_graphics.py, 1 computed I/J PerVertexKHR - (ps_ij_computed). -``` - -Setup: `cmake -S runtime -B build-gpu -G Ninja -DCMAKE_BUILD_TYPE=Release -DCMAKE_C_COMPILER= -DCMAKE_CXX_COMPILER= -DLEONIDA_BUILD_WINDOWS_RUNTIME=OFF`, with `VULKAN_SDK` pointed at Vulkan SDK 1.4.363. No MSVC or Windows SDK, so the D3D12-side runtime and its tests are not built; `build.py` and `check.py` were not run. This is the first Pascal entry: wave64 and mesh shader cases skip (no 64-wide subgroup, no mesh shaders, no barycentric). - -The two `cs_imgload_*_tfe` failures track #31 and are deterministic (identical signature on the 780M and Intel MTL records), so they are not a Pascal-specific effect. `cs_w32_exec_computed` passes here (259 1028 3088 7682 512 4100 0 3), so the SHADER-1264 exec fix (#24) is on this main; only the tfe pair remains. - -Real shader corpus — 2026-11-24 - -The full main shader corpus (`shaders.rpf`, v1.0.2.1) run through the translation pipeline -(`shader_carve` → `fssm_unpack` → `shader_disasm` → `rdna2spirv`, default flags, no fallbacks) -on the same toolchain: - -``` -Corpus: shaders.rpf v1.0.2.1, 26503 carved shader containers (1 candidate rejected at carve) -Result: 26503/26503 translated, 26503 pass spirv-val (100.000%; 0 refused, 0 failed) -Stages: vs 2236, ms 9282, ps 12101, gs 195, cs 2689 -Subgroup: 32-wide 2662, 64-wide 23841 -Control flow: structured 23213, straight-line 3249, barrier-rounds 39, dispatch-loop 2 -FMA: glsl (all) -wave64 VS/PS/GS on 32-wide subgroups: 13405 shaders - tier A (exact) 5059 (37.7%), tier B (exact via idiom) 101 (0.8%), - tier C (not exact on 32-wide) 8245 (61.5%) - by stage: gs A 195; ps A 3396 / B 27 / C 7551; vs A 1468 / B 74 / C 694 -tier C reasons (a shader may have several): tainted-branch 6534, unsafe-vote-branch 6496, - tainted-exec 6360, cross-lane 4630, stale-scalar 3487, mask-half 759, - unsafe-execz-branch 583, first-lane 353, lane-id 152, waterfall-scalar 3, lane-count 1 -``` - -On a 32-wide-subgroup GPU the 8245 tier C wave64-graphics shaders (mostly pixel shaders, 7551 of -them) are not bit-exact: a lane count, rank, first-lane index or lane id reaches an export or -memory in a way that changes when the wave is split across two 32-lane subgroups. That is the -Pascal-specific exactness gap; the translation and `spirv-val` themselves are GPU-independent and -complete (100%) for the whole corpus. diff --git a/docs/i18n/README.md b/docs/i18n/README.md deleted file mode 100644 index 35fa1ef96..000000000 --- a/docs/i18n/README.md +++ /dev/null @@ -1,26 +0,0 @@ -# Community quickstarts (other languages) - -The English documentation ([`README.md`](../../README.md), [`CONTRIBUTING.md`](../../CONTRIBUTING.md), and -[`docs/`](../README.md)) is **authoritative**. - -Community translations live here and cover **stable onboarding text only** (what the project is, own-copy and -no-game-data rules, prerequisites, build commands, stage order, and common troubleshooting). They intentionally -omit the daily-moving project status table, format notes, and `docs/design.md` so copies do not drift out of -date, and they require no build or CI changes. - -A language is added when a contributor volunteers to maintain it and keeps the synced commit below up to date. - -| Language | File | Synced commit | Maintainer | -|---|---|---|---| -| Français (`fr`) | [`fr/quickstart.md`](fr/quickstart.md) | `aa2988cc` | `@Urban225` | -| Português (Brasil) (`pt-BR`) | [`pt-BR/quickstart.md`](pt-BR/quickstart.md) | `f847748c` | `@Andretuta` | -| Português (Portugal) (`pt-PT`) | [`pt-PT/quickstart.md`](pt-PT/quickstart.md) | `867d922f` | `@enzoduarte1` | -| 简体中文 (`zh-CN`) | [`zh-CN/quickstart.md`](zh-CN/quickstart.md) | `aa2988cc` | `@liang-kai-shui` | -| Polski (Polish) (`pl-PL`) | [`pl-PL/quickstart.md`](pl-PL/quickstart.md) | `f847748c` | `@Dom-in, @t91a60` | -| Türkçe (`tr`) | [`tr/quickstart.md`](tr/quickstart.md) | `561b65a` | `@emirhan-karaca` | -| Русский (`ru`) | [`ru/quickstart.md`](ru/quickstart.md) | `aa2988cc` | `@DmitryBykov-ISPO` | -| 日本語 (`ja`) | [`ja/quickstart.md`](ja/quickstart.md) | `003e781` | `@bingll123` | -| Español (`es`) | [`es/quickstart.md`](es/quickstart.md) | `561b65a8` | `@NolanCotter` | -| Deutsch (`de`) | [`de/quickstart.md`](de/quickstart.md) | `aa2988cc` | `@zGLados` | -| Italiano (`it`) | [`it/quickstart.md`](it/quickstart.md) | `49475796` | `@MeNoSkills` | -| العربية (`ar`) | [`ar/quickstart.md`](ar/quickstart.md) | `561b65a` | `@Mohamed-Leo` | diff --git a/docs/i18n/ar/quickstart.md b/docs/i18n/ar/quickstart.md deleted file mode 100644 index f81448310..000000000 --- a/docs/i18n/ar/quickstart.md +++ /dev/null @@ -1,96 +0,0 @@ -
- -# دليل البدء السريع لمشروع Leonida - -الوثائق الإنجليزية هي المرجع المعتمد. يستند هذا الدليل إلى المراجعة `561b65a` ويغطي خطوات البدء الأساسية. -راجع [ملف README بالإنجليزية](../../../README.md#project-status) لمعرفة حالة المشروع الحالية، و[فهرس الوثائق](../../README.md) للمزيد من التفاصيل. - -## ما هو Leonida؟ - -Leonida مشروع لإعادة ترجمة إصدار Xbox Series من Grand Theft Auto VI لتشغيله مباشرةً على Windows. -يُبنى المشروع على جهازك من نسختك الخاصة من اللعبة. تُترجم برامج التظليل من RDNA2 إلى SPIR-V لاستخدامها مع Vulkan، -وتُقرأ الموارد من حزمة اللعبة المحلية، ويُعيد المشروع تنفيذ واجهات النظام التي تحتاجها اللعبة. - -لا يحتوي المستودع على اللعبة أو ملفها التنفيذي أو مفاتيحها. تتطلب الأدوات ملفات قابلة للقراءة أصلًا على القرص، -ولا تفك التشفير أو تتجاوز الحماية. احتفظ بملفات اللعبة والملفات الناتجة عن البناء على جهازك. لا ترفقها أو ترفق سجلات تقتبس منها عند الإبلاغ عن مشكلة أو فتح طلب دمج. - -## المتطلبات - -- نسختك الخاصة من حزمة Xbox Series بالإصدار `1.0.2.1`. اختر المجلد الذي يحتوي على `MicrosoftGame.Config` وأرشيفات `.rpf`. -- Windows 10 أو 11 بمعمارية x64، مع نحو 400 غيغابايت متاحة لملفات العمل. هذا الرقم للبناء الكامل: التشغيل وحده يكفيه `--stages check,shaders,runtime` بنحو 30 غيغابايت، ومرحلة `assets` وحدها تطلب نحو 370 غيغابايت. يمكن وضعها على قرص آخر باستخدام `--work` و`--out`. -- Git و[Python 3.12 أو أحدث](https://www.python.org/downloads/) و[حزمة .NET 8 SDK](https://dotnet.microsoft.com/download/dotnet/8.0). - عند تثبيت Python على Windows، اختر إضافة `python.exe` إلى `PATH`. -- [حزمة Vulkan SDK](https://vulkan.lunarg.com/) لتوفير `spirv-as` و`spirv-val` و`vulkaninfo`. -- [LLVM 21 أو أحدث](https://github.com/llvm/llvm-project/releases) مع دعم AMDGPU في `llvm-mc`. - نسخة LLVM الرسمية لـWindows لا تتضمن هذا الدعم. من جذر المستودع، شغّل `scripts/build_llvm_mc.ps1` من PowerShell لبناء `llvm-mc.exe`. - يتطلب السكربت Git وأدوات C++ في Visual Studio ويضبط `LLVM_MC`. افتح نافذة PowerShell جديدة بعد انتهائه. - إذا كنت تستخدم [conda](https://docs.conda.io/)، فطريقة أسرع هي `conda install -c conda-forge llvm-tools` (نسخة Windows منه تتضمن هدف AMDGPU؛ استخدم [دليل الاختبارات](../../testing.md) الإصدار 23.1.6)، ثم اضبط `LLVM_MC` على المسار الكامل لملف `llvm-mc.exe` الذي يثبّته (يعرض `where.exe llvm-mc` مساره بعد تنشيط البيئة؛ أما `where` المجرد في PowerShell فهو `Where-Object`). - إذا ثبّتَّ `llvm-21` على Ubuntu داخل WSL، اضبط `LLVM_MC` في نافذة PowerShell التي ستشغّل منها البناء. - - ```powershell - $env:LLVM_MC = 'wsl -d Ubuntu -e /usr/lib/llvm-21/bin/llvm-mc' - ``` - -- Visual Studio 2022 مع حزمة **Desktop development with C++** وWindows SDK بالإصدار `10.0.26100` أو أحدث لبناء مكوّن التشغيل. -- [ffmpeg](https://ffmpeg.org/download.html) ضمن `PATH`، وهو اختياري لفك ترميز XMA2 ومطلوب عند استخدام `--wav`. - -## البناء على Windows - -بعد تثبيت المتطلبات، استنسخ المستودع مع وحدته الفرعية. - -```powershell -git clone --recursive https://github.com/ItsNotRexed/Leonida -cd Leonida -``` - -انقر نقرًا مزدوجًا على `Build.bat`. يبحث البرنامج عن نسختك على الجهاز. إذا وجد أكثر من نسخة فسيطلب منك الاختيار، -وإذا لم يجد أي نسخة فسيطلب مسار المجلد. يتحقق من الأدوات والمساحة المتاحة قبل بدء البناء. تُحفظ النتيجة افتراضيًا -في `Documents\Leonida`، ويمكن استئناف البناء إذا توقف. - -### البناء من PowerShell - -شغّل الأوامر من جذر المستودع. يعرض `--find` النسخ التي عُثر عليها محليًا، ويُستخدم `--check` لفحص الحزمة فقط. -يضيف `--full-check` مقارنة بصمة SHA-256 لكل ملف، وقد يستغرق ذلك وقتًا. في أمر البناء، استبدل المسارات بالمسارات على جهازك. - -```powershell -python -I make_game.py --find -python -I make_game.py --pick -python -I make_game.py --check -python -I make_game.py --check --full-check -python -I make_game.py --game "D:\path\to\package" --out "D:\Games\Leonida" --work "E:\leonida-work" -``` - -تبدأ المرحلة `check` دائمًا أولًا؛ ثم تعمل المراحل `shaders` و`assets` و`runtime` معًا عند اختيارها (لا تعتمد إحداها على الأخرى)، ويبدأ `pipelines` عندما تصبح الشوارد المترجمة جاهزة. -يمكن اختيار مراحل بعينها باستخدام `--stages shaders,assets`. عادةً ما تستغرق ترجمة برامج التظليل أطول وقت، -ويمكن ضبط عدد عملياتها باستخدام `--jobs`. اترك `--wave64-emulate` على القيمة الافتراضية `auto` ما لم تحتج إلى تجاوز اختيار الأداة. -يضيف `--wav` نسخًا بصيغة PCM WAV من مسارات Ogg Opus ويزيد المساحة المطلوبة. - -### البناء على Linux - -يعمل `make_game.py` على Linux، ويجد `llvm-mc` تلقائيًا إذا كان ضمن `PATH`. تأكد من أن نسخته تدعم AMDGPU. -يعمل محمّل اللعبة، وهو برنامج Windows، عبر Wine أو Proton. إذا كان لديك بناء Windows جاهز للمحمّل، -فمرّر مجلده باستخدام `--runtime-build`. راجع [تعليمات البناء والتشغيل على Linux](../../linux.md). - -## حل المشاكل الشائعة - -- **الوحدة الفرعية غير موجودة بعد تنزيل ZIP.** استنسخ المستودع باستخدام `--recursive` كما في المثال أعلاه. - وإذا كان لديك مستودع Git مستنسخ بالفعل، شغّل `git submodule update --init --recursive` من جذره. -- **يرفض `llvm-mc` هدف الترجمة `gfx1013`.** تحقق من استخدام نسخة تدعم AMDGPU، ومن أن `LLVM_MC` يشير إلى الأداة الصحيحة. -- **يطلب CMake حزمة Windows SDK أحدث.** ثبّت الإصدار `10.0.26100` أو أحدث من Visual Studio Installer، ثم أعد تهيئة مجلد البناء. -- **المساحة على قرص النظام غير كافية.** استخدم `--work` لتخزين ملفات العمل على قرص أوسع، و`--out` إذا أردت نقل المخرجات أيضًا. -- **يحظر Windows تشغيل أدوات الاختبار المبنية محليًا.** راجع [المشاكل المعروفة في دليل الاختبارات](../../testing.md#known-problems). - -## المساهمة - -1. اقرأ [دليل المساهمة](../../../CONTRIBUTING.md) وراجع [مسألة التنسيق][coord] وطلبات الدمج المفتوحة قبل البدء. -2. احجز المهمة بتعليق `claiming: ` في مسألة التنسيق، أو اكتب وصفًا من سطر واحد إن لم يكن لها معرّف بعد. -3. شغّل الاختبارات المناسبة بمدخلات اصطناعية. لتعديلات التوثيق مثلًا، يمكن تشغيل `python -I tests/test_docs_links.py` من جذر المستودع. -4. في طلب الدمج، اذكر معرّف المهمة أو رابط الحجز والاختبارات التي شغّلتها. اذكر البطاقة الرسومية وإصدار تعريفها إذا اختبرت على GPU، - واذكر أي مساعدة من الذكاء الاصطناعي. - -يوضح [دليل اختبارات GPU](../../testing.md) طريقة تشغيل الاختبارات من دون ملفات اللعبة. -يمكن نشر النتائج في [مسألة الاختبارات رقم 166](https://github.com/ItsNotRexed/Leonida/issues/166). - -[coord]: https://github.com/ItsNotRexed/Leonida/issues?q=is%3Aissue%20is%3Aopen%20in%3Atitle%20%22Coordinating%20who%20works%20on%20what%22 - -
diff --git a/docs/i18n/de/quickstart.md b/docs/i18n/de/quickstart.md deleted file mode 100644 index a0c72a15f..000000000 --- a/docs/i18n/de/quickstart.md +++ /dev/null @@ -1,179 +0,0 @@ -# Leonida — Schnellstart (`de`) - -> [!NOTE] -> Die englische Dokumentation ([`README.md`](../../../README.md), [`CONTRIBUTING.md`](../../../CONTRIBUTING.md) und -> [`docs/README.md`](../../README.md)) ist **maßgeblich**. Diese Anleitung enthält nur die stabilen Schritte zum -> Einrichten und Bauen (abgeglichen mit Commit `aa2988cc`). Den aktuellen Projektstand findest du in der -> [`README.md`](../../../README.md). - -## Was ist Leonida? - -Leonida ist ein Static-Recompilation-Projekt, das Grand Theft Auto VI (Xbox Series) nativ unter Windows ausführen -soll. Der Port wird **auf deinem PC aus deiner eigenen Kopie des Spiels** gebaut. Die CPU der Xbox Series ist wie ein -PC x86-64, daher wird der Code des Spiels geladen und direkt ausgeführt, und die Systemsoftware der Konsole wird als -sogenannte Shims nachgebaut. Die vorkompilierten RDNA2-Shader der Konsole werden nach SPIR-V (Vulkan) übersetzt, -Modelle, Texturen und Audio werden direkt aus deinem Paket gelesen. - -> [!IMPORTANT] -> Dieses Repository **enthält weder das Spiel noch Schlüssel oder eine ausführbare Datei** und erklärt auch nicht, -> wie man sie bekommt. Nichts hier entschlüsselt Daten oder umgeht einen Schutz. Alles, was der Build erzeugt -> (übersetzte Shader, extrahierte Assets, der Arbeitsordner und deine Spielstände), stammt aus deiner Kopie und -> **muss auf deinem PC bleiben**. Hänge diese Dateien niemals an Issues oder Pull Requests an und teile sie nicht -> (siehe [`CONTRIBUTING.md`](../../../CONTRIBUTING.md)). - -Das Projekt steht noch am Anfang: **Das Spiel startet noch nicht.** - -## Plattformen - -Auf keiner Plattform ist bisher etwas spielbar. Was heute wo läuft: - -- **Windows**: alles (`make_game.py`, die Tools und die Runtime `gta6rt` mit der D3D12 → Vulkan-Schicht und ihren - Tests). -- **Linux**: Der Übersetzer, die Asset-Tools und die Vulkan-GPU-Testtools bauen und laufen nativ (getestet mit RADV - und NVIDIA). Die Runtime ist Windows-Code: Sie wird mit clang-cl und xwin cross-kompiliert, ihre Tests laufen unter - Wine oder Proton. Das Spiel soll später genauso laufen (#217). -- **macOS (Apple Silicon)**: Die Python-Tools und die Vulkan-Testtools laufen nativ, auf MoltenVK (Homebrew) oder - KosmicKrisp. Die Runtime läuft wie unter Linux unter Wine. Bekannte Lücken: keine Geometry-Stufe und kein - `VK_EXT_mesh_shader`, 32 breite Subgroups (Wave64-Shader laufen emuliert) und MoltenVKs Umgang mit - Gleitkommazahlen; [`docs/testing.md`](../../testing.md) listet sie alle auf. -- **AMD RDNA1 (RX 5000)**: ein unterstütztes Ziel, nah am RDNA2 der Konsole; seine 64 breiten Subgroups führen die - Wave64-Shader nativ aus. - -GPU-Ergebnisse von allen Plattformen werden in [Issue #166](https://github.com/ItsNotRexed/Leonida/issues/166) -gesammelt. - -## Voraussetzungen - -- **Deine eigene Kopie** des Xbox-Series-Pakets in Version `1.0.2.1` (der Ordner mit `MicrosoftGame.Config` und den - `.rpf`-Archiven, als normale, lesbare Dateien auf der Festplatte). -- **Windows 10/11 x64** mit etwa **400 GB freiem Speicher** für die Arbeitsdateien (mit `--work` auch auf einem - anderen Laufwerk). -- [Python 3.12+](https://www.python.org/downloads/) (bei der Installation *„Add python.exe to PATH“* anhaken). -- [.NET 8 SDK](https://dotnet.microsoft.com/download/dotnet/8.0). -- [Vulkan SDK](https://vulkan.lunarg.com/) (`spirv-as`, `spirv-val` und `vulkaninfo`). -- [LLVM 21+](https://github.com/llvm/llvm-project/releases) mit dem **AMDGPU-Target** (`llvm-mc`): - - Der offizielle LLVM-Build für Windows enthält das AMDGPU-Target **nicht**. - - Ein natives `llvm-mc.exe` mit AMDGPU baut `.\scripts\build_llvm_mc.ps1`, ausgeführt in PowerShell im - Hauptordner des Repositorys. Das Skript braucht `git` und die C++-Tools von Visual Studio, setzt die Variable - `LLVM_MC` für deinen Benutzer und bittet dich, danach ein neues Terminal zu öffnen, damit sie sichtbar wird. Das - dauert etwa 20-40 Minuten. - - Schneller, wenn du [conda](https://docs.conda.io/) nutzt: `conda install -c conda-forge llvm-tools` (der - Windows-Build enthält das AMDGPU-Target), dann `LLVM_MC` auf den vollen Pfad des installierten `llvm-mc.exe` - setzen (`where.exe llvm-mc` zeigt ihn bei aktivierter Umgebung; das nackte `where` ist in - PowerShell das Cmdlet `Where-Object`). - - Mit WSL: `llvm-21` in Ubuntu installieren und die Variable in derselben PowerShell-Sitzung setzen, in der du - `make_game.py` startest: - - ```powershell - $env:LLVM_MC = 'wsl -d Ubuntu -e /usr/lib/llvm-21/bin/llvm-mc' - ``` - - Mehr dazu in [`docs/design.md`](../../design.md#disassembling-shaders). - - Unter Linux reicht `llvm-mc` im `PATH`. -- **Visual Studio 2022** mit der Workload *Desktopentwicklung mit C++* und dem **Windows SDK `10.0.26100` oder - neuer** (für die Stufe `runtime`, die Root Signatures der Version 1.2 verwendet). -- [ffmpeg](https://ffmpeg.org/download.html) im `PATH` *(optional: dekodiert die XMA2-Streams und wird für `--wav` - gebraucht)*. - -## So baust du es - -### Der einfache Weg (Windows) - -1. Installiere die Voraussetzungen oben. -2. Klone das Repository **mit seinem Submodul**: - ```powershell - git clone --recursive https://github.com/ItsNotRexed/Leonida - ``` - Ein „Download ZIP“ von GitHub lässt `third_party/rpf9-explorer` weg. Der Build holt es nach, wenn `git` - installiert ist, und sagt dir sonst, was zu tun ist. -3. Optional: Doppelklicke auf **`Check-PC.bat`** oder `python -I scripts/pc_readiness.py --lang de`, um Werkzeuge, - Speicherplatz, Spielpaket und GPU zu prüfen — ohne einen Build zu starten (UI-Texte in `scripts/i18n/pc_readiness/`). -4. Doppelklicke auf **`Build.bat`**. - -Der Build findet deine Kopie selbst: Er sucht in Downloads, Desktop, Dokumente (auch dort, wo Windows sie ablegt, -etwa in OneDrive), Games, deinem Benutzerordner und oben auf jedem Laufwerk, jeweils zwei Ordner tief. Die Version -erkennt er an ein paar Dateigrößen, ohne große Dateien zu lesen. Findet er mehrere Kopien, fragt er, welche er nehmen -soll, findet er keine, bittet er dich, den Ordner einzufügen. Vor dem Start prüft er, ob alles installiert ist und -genug Platz frei ist, und listet alles Fehlende auf einmal auf. Das Ergebnis landet in `Documents\Leonida`. Ein -abgebrochener Build macht beim nächsten Start dort weiter, wo er aufgehört hat. - -### Wenig Speicherplatz - -Der Platzbedarf oben gilt für den vollständigen Build. Um den Port nur zu *starten*, braucht -`--stages check,shaders,runtime` etwa 30 GB; die Stufe `assets`, die fast den ganzen Rest belegt, ist nur für die -Asset-Tools da, und `--wav` kommt mit einem Mehrfachen der Ogg-Opus-Größe hinzu. `--work` und `--out` können auf -einem anderen Laufwerk liegen. Die Runtime liest das Paket an Ort und Stelle; liegt es auf einem schreibgeschützten -Laufwerk, brauchst du `gta6rt --overlay ` (eine Option von `gta6rt`, nicht von -`make_game.py`). Lösche die `.s`-Dateien in `work/shaders/dxbc/disasm` nicht: Ohne sie und ohne -`work/shaders/spirv/index.json` kann die Stufe `shaders` mit null Shadern fertig aussehen. - -### Aus dem Terminal (`make_game.py`) - -```powershell -python -I make_game.py --find # zeigt die auf diesem PC gefundenen Kopien -python -I make_game.py --pick # Spielordner in einem Ordnerdialog auswählen -python -I make_game.py --check # prüft deine Kopie, baut nichts -python -I make_game.py --check --full-check # vergleicht zusätzlich die SHA-256 jeder Datei (langsam) -python -I make_game.py --game "D:\pfad\zum\paket" --out "D:\Games\Leonida" --work "E:\leonida-work" -python -I make_game.py --stages shaders,assets # nur bestimmte Stufen -python -I make_game.py --game "D:\pfad\zum\paket" --wav # dekodiert Opus zusätzlich zu PCM-WAV (groß) -python -I make_game.py --wave64-emulate auto # auto (Standard), on oder off -``` - -Die Stufe `check` läuft immer zuerst; danach laufen `shaders`, `assets` und `runtime` zusammen, wenn sie ausgewählt sind (sie hängen nicht voneinander ab). `pipelines` startet, sobald die übersetzten Shader bereit sind. - -- **`--wave64-emulate`**: emuliert Wave64-Compute- und -Mesh-Shader auf GPUs mit 32 breiten Subgroups (NVIDIA und - Intel). Der Standard `auto` fragt `vulkaninfo` und schaltet die Emulation selbst ein, wenn sie gebraucht wird. - AMD-Karten (RDNA) führen Wave64 nativ aus. -- **`--work`**: am besten ein Laufwerk mit mindestens 400 GB freiem Platz angeben. Die Stufe `shaders` dauert am - längsten und nutzt standardmäßig die Hälfte der CPU-Threads (änderbar mit `--jobs`). -- **`pipelines`**: erstellt jeden übersetzten Shader auf deinem GPU-Treiber, prüft, dass er kompiliert, meldet die - übersprungenen und speichert einen Pipeline-Cache in `pipeline_cache.bin` in `--out`. Die Runtime lädt diesen - Cache noch nicht, er beschleunigt den ersten Start also nicht. -- **Fallback-Optionen** für Geräte, denen eine Vulkan-Funktion fehlt; sie werden neben den übersetzten Shadern - gespeichert, und eine Änderung übersetzt sie neu: `--no-float-controls`, `--bary-fallback` (ohne - `VK_KHR_fragment_shader_barycentric`), `--texel-offset-fallback` (ohne `VK_KHR_maintenance8`) und `--mesh-compute` - (ohne `VK_EXT_mesh_shader`). Siehe [`docs/design.md`](../../design.md). -- **Was automatisch neu gemacht wird**: Der Build merkt sich Befehl und Version von `llvm-mc`, die Quellen des - Übersetzers und den Asset-Decoder (`third_party/rpf9-explorer` und `tools/rpf9dump`). Ändert sich etwas davon, - wird nur der betroffene Schritt wiederholt (Disassemblierung, Übersetzung oder Export der Modelle und Texturen). -- **Linux und Wine/Proton**: `make_game.py` läuft auch unter Linux. Die Stufe `pipelines` nutzt - `vk_pipeline_check` (mit CMake in `runtime/build/linux` gebaut; fehlt es, baut das Skript es selbst). Der Loader ist - ein Windows-Programm und läuft unter Wine oder Proton: Die Stufe `runtime` cross-kompiliert ihn mit clang-cl und - lld-link (LLVM 19+, aber nicht 22.1.7 oder 22.1.8) gegen das Windows SDK, das - [xwin](https://github.com/Jake-Shadle/xwin) bereitlegt; siehe [`docs/testing.md`](../../testing.md). Alternativ - gibst du mit `--runtime-build ` einen anderswo gemachten Windows-Build an (`gta6rt.exe` und - `gta6rt_tls_host.dll`). In beiden Fällen legt das Skript `gta6rt.sh` an, das das Programm mit `wine` startet (oder - mit dem Wine aus der Variable `WINE`, etwa von Proton). - -Zu `--wave64-emulate`: `auto` schaltet die Emulation ein, wenn eine GPU keine 64 breiten Subgroups hat oder ihre -Größe unbekannt ist. Mit dem Windows-Treiber von AMD bleibt `auto` auf RDNA1 und RDNA2 bei nativem Wave64, wenn die -GPU der Runtime es kann, denn dieser Treiber kann bei emuliertem LDS-Code abstürzen (#857). Der Modus wird neben den -übersetzten Shadern gespeichert, und eine Änderung übersetzt sie neu. - -## Häufige Probleme - -- **Repository über „Download ZIP“ auf GitHub geladen**: Das ZIP enthält das Submodul `third_party/rpf9-explorer` - nicht. Nimm `git clone --recursive` oder führe im Repository-Ordner `git submodule update --init --recursive` aus. -- **`llvm-mc` lehnt `gfx1013` / AMDGPU ab**: Du hast vermutlich den offiziellen LLVM-Installer für Windows. Nimm - `scripts\build_llvm_mc.ps1` oder setze `LLVM_MC` auf das `llvm-mc` aus WSL (`llvm-21`). -- **Fehler `D3D12_ROOT_SIGNATURE_DESC2` beim Bauen der Runtime**: Aktualisiere das Windows SDK auf `10.0.26100` oder - neuer (über den Visual Studio Installer oder `winget install Microsoft.WindowsSDK.10.0.26100`), lösche den - Build-Ordner und konfiguriere neu. -- **Kein Platz auf `C:`**: Mit `--work "D:\leonida-work"` legst du die Arbeitsdateien auf ein anderes Laufwerk. - -## Mithelfen und GPU-Tests ausführen - -1. Schau dir die offenen Pull Requests und das [Koordinations-Issue][coord] an, damit keine Arbeit doppelt gemacht - wird. Reserviere eine Aufgabe dort mit `claiming: ` oder mit einer kurzen Beschreibung, wenn sie noch keine ID - hat. -2. Führe die passenden Tests mit synthetischen Eingaben aus, zum Beispiel den Manifest-Prüfer mit - `python -I tests/test_manifest_verifier.py` im Hauptordner des Repositorys. -3. Nenne im Pull Request die Aufgaben-ID, beschreibe, was du getestet hast, und bei GPU-Tests die Grafikkarte und die - Treiberversion. Gib an, ob du KI-Unterstützung genutzt hast. Die Regeln stehen in - [`CONTRIBUTING.md`](../../../CONTRIBUTING.md). - -Die [Anleitung zu den GPU-Tests](../../testing.md) zeigt, wie sie ohne Spieldateien laufen. -Ergebnisse von GPU-Tests gehören in [Issue #166](https://github.com/ItsNotRexed/Leonida/issues/166). - -[coord]: https://github.com/ItsNotRexed/Leonida/issues?q=is%3Aissue%20is%3Aopen%20in%3Atitle%20%22Coordinating%20who%20works%20on%20what%22 diff --git a/docs/i18n/es/quickstart.md b/docs/i18n/es/quickstart.md deleted file mode 100644 index e46dcc840..000000000 --- a/docs/i18n/es/quickstart.md +++ /dev/null @@ -1,223 +0,0 @@ -# Leonida — Guía de inicio (`es`) - -> [!NOTE] -> La documentación en inglés ([`README.md`](../../../README.md), [`CONTRIBUTING.md`](../../../CONTRIBUTING.md) y -> [`docs/README.md`](../../README.md)) es **la referencia oficial**. Esta guía solo recoge las instrucciones -> estables de instalación y compilación (sincronizada con el commit `561b65a8`). Para el estado del proyecto, que -> cambia a diario, consulte el [`README.md`](../../../README.md). - -## Qué es Leonida - -Leonida es un proyecto de recompilación estática de Grand Theft Auto VI (versión Xbox Series) para ejecutarlo de -forma nativa en Windows. Se compila **en su PC, a partir de su propia copia del juego**. Los shaders RDNA2 de la -consola se traducen a SPIR-V (Vulkan), los recursos se leen directamente de su paquete y el software de sistema de -la consola se reimplementa como shims. - -> [!IMPORTANT] -> Este repositorio **no contiene el juego, ni claves, ni ejecutables**, y no explica cómo conseguirlos. Nada de lo -> que hay aquí descifra ni elude una protección. Todo lo que la compilación produce (shaders traducidos, recursos -> extraídos, carpeta de trabajo, guardados) proviene de su copia y **debe permanecer en su máquina**: no adjunte ni -> comparta nunca esos archivos en una issue o en una pull request (véase -> [`CONTRIBUTING.md`](../../../CONTRIBUTING.md)). - -El proyecto está en una fase inicial: **el juego todavía no arranca**. - -## Requisitos previos - -- **Su propia copia** del paquete de Xbox Series, versión `1.0.2.1`: la carpeta que contiene `MicrosoftGame.Config` - y los archivos `.rpf`, como ficheros legibles en el disco. -- **Windows 10/11 x64**, con unos **400 GB libres** para los archivos de trabajo. Pueden ir a otra unidad con - `--work`; más abajo se explica cómo omitir la exportación de recursos y usar unos 30 GB. -- [Python 3.12+](https://www.python.org/downloads/) (marque «Add python.exe to PATH» durante la instalación). -- [SDK de .NET 8](https://dotnet.microsoft.com/download/dotnet/8.0). -- [SDK de Vulkan](https://vulkan.lunarg.com/) (`spirv-as`, `spirv-val` y `vulkaninfo`). -- [LLVM 21+](https://github.com/llvm/llvm-project/releases) con el **destino AMDGPU** (`llvm-mc`): - - La versión oficial de LLVM para Windows **no incluye** el destino AMDGPU. - - Para compilar un `llvm-mc.exe` nativo con ese destino, ejecute `.\scripts\build_llvm_mc.ps1` en PowerShell - desde la raíz del repositorio. El script necesita `git` y las herramientas de C++ de Visual Studio. Define - `LLVM_MC` para su usuario: abra después un terminal nuevo para que la variable se aplique. - - Si usa [conda](https://docs.conda.io/), `conda install -c conda-forge llvm-tools` ofrece una alternativa cuyo - paquete para Windows incluye AMDGPU. Con el entorno activado, `where.exe llvm-mc` muestra la ruta del - ejecutable; asigne esa ruta completa a `LLVM_MC`. - - Con WSL, instale `llvm-21` en Ubuntu y pase el comando completo a `LLVM_MC`, en la sesión de PowerShell - donde vaya a ejecutar `make_game.py`: - - ```powershell - $env:LLVM_MC = 'wsl -d Ubuntu -e /usr/lib/llvm-21/bin/llvm-mc' - ``` - - Véase [`docs/design.md`](../../design.md#disassembling-shaders) para los detalles. - - En Linux basta con un `llvm-mc` presente en el `PATH`. -- **Visual Studio 2022** con la carga de trabajo *Desarrollo para el escritorio con C++* y el **SDK de Windows - `10.0.26100` o superior**, para la etapa `runtime` (el runtime usa las root signatures 1.2, ausentes en SDK - más antiguos). -- [ffmpeg](https://ffmpeg.org/download.html) en el `PATH` *(opcional: decodifica los flujos XMA2 y es obligatorio - con `--wav`)*. - -## Compilar - -### La forma sencilla (Windows) - -1. Instale los requisitos anteriores. -2. Clone el repositorio **con su submódulo**: - ```powershell - git clone --recursive https://github.com/ItsNotRexed/Leonida - ``` -3. Haga doble clic en **`Build.bat`**. - -El script encuentra su copia por sí solo: busca en Descargas, Escritorio y Documentos (también si Windows los ha -movido a OneDrive), Games, su carpeta de usuario y en la raíz de cada disco, dos niveles de carpetas en -profundidad. Reconoce la versión por el tamaño de algunos archivos, sin leer archivos grandes. Si encuentra -varias copias, le pregunta cuál usar; si no encuentra ninguna, le pide que pegue la ruta de la carpeta. Antes de -empezar comprueba los requisitos y el espacio libre, y enumera de una vez todo lo que falta. El resultado va a -`Documents\Leonida`. Una compilación interrumpida se reanuda donde quedó. - -### Si dispone de poco espacio - -Los 400 GB corresponden a la compilación completa. Puede omitir la exportación de recursos con -`--stages check,shaders,runtime`, que necesita unos **30 GB**. La etapa `assets` (unos 370 GB) sirve para las -herramientas de recursos; `--wav` añade varias veces el tamaño de los archivos Ogg Opus. La comprobación previa -ofrece la alternativa sin `assets` cuando esa etapa no cabe. Puede situar tanto `--work` como `--out` en otra -unidad. - -El runtime accede al paquete en su ubicación original. Si la unidad del paquete es de solo lectura, use -`gta6rt --overlay `: `--overlay` es una opción de `gta6rt`. - -Conserve los archivos `.s` de `work/shaders/dxbc/disasm`: la siguiente ejecución los compara con la lista de `disasm.done` y vuelve a desensamblar los que faltan (todos los de una carpeta cuyo `disasm.done` sea anterior a esa lista) y después traduce todos los shaders de nuevo. Borrarlos junto con `work/shaders/spirv/index.json` puede hacer que la etapa de shaders parezca terminada con cero shaders. -Si la etapa necesita vaciar `disasm`, rechazará esa carpeta cuando sea un enlace simbólico. - -### Desde un terminal (`make_game.py`) - -```powershell -python -I make_game.py --find # enumera las copias encontradas en este PC -python -I make_game.py --pick # elige la carpeta mediante un diálogo -python -I make_game.py --check # verifica su copia, sin compilar nada -python -I make_game.py --check --full-check # también comprueba los SHA-256 de todos los archivos (lento) -python -I make_game.py --game "D:\ruta\al\paquete" --out "D:\Games\Leonida" --work "E:\leonida-work" -python -I make_game.py --stages check,shaders,runtime # sin la exportación de recursos (unos 30 GB) -python -I make_game.py --stages shaders,assets # solo algunas etapas -python -I make_game.py --game "D:\ruta\al\paquete" --wav # además decodifica el Opus a WAV PCM (ocupa mucho) -python -I make_game.py --wave64-emulate off # auto (predeterminado), on u off -``` - -La etapa `check` se ejecuta siempre primero; después, cuando se seleccionan, `shaders`, `assets` y `runtime` se ejecutan a la vez (no dependen entre sí). `pipelines` empieza en cuanto los shaders traducidos están listos. - -La traducción de shaders es la etapa más larga; por defecto usa la mitad de los hilos del procesador (ajustable -con `--jobs`). La etapa `pipelines` comprueba que el controlador de su GPU puede crear los shaders traducidos e -informa de los que debe omitir. Guarda `pipeline_cache.bin` en `--out`, pero el runtime todavía no carga esa -caché, así que no acelera el primer arranque. - -`--wav` está desactivado por defecto, porque el WAV PCM de 16 bits ocupa varias veces más que el Ogg Opus. -Cuando se activa, decodifica los Ogg Opus a `work/assets/audio/wav` después de exportar los bancos de audio; -al reanudar, omite los WAV ya existentes. - -### Emulación wave64 y compatibilidad de la GPU - -`--wave64-emulate` decide si los shaders compute y mesh wave64 se traducen de forma exacta para cualquier tamaño -de subgrupo. Las GPU NVIDIA e Intel usan subgrupos de 32 y lo necesitan. El valor predeterminado, `auto`, consulta -`vulkaninfo` y activa la emulación si alguna GPU no admite subgrupos de 64 o su tamaño es desconocido. También -comprueba que la GPU del runtime admita compute y mesh con subgrupos de 64; con `--mesh-compute` solo necesita -esa capacidad en compute. - -Con el controlador de AMD para Windows, `auto` usa wave64 nativo en RDNA1 y RDNA2 si la GPU del runtime lo admite, -aunque otra GPU use subgrupos de 32 o no esté disponible `vulkaninfo`. Así evita un fallo del controlador con -código LDS emulado ([#857](https://github.com/ItsNotRexed/Leonida/issues/857)). En RDNA1 sin mesh nativo comprueba -la capacidad de compute. Puede forzar la emulación con `--wave64-emulate on` o el modo nativo con -`--wave64-emulate off`. - -Estas opciones ofrecen alternativas para GPU o controladores con capacidades limitadas. Los detalles y sus -límites están en [`docs/design.md`](../../design.md): - -| Opción | Cuándo se usa | -|---|---| -| `--no-float-controls` | Cuando la GPU no admite las capacidades de conservación de valores especiales de coma flotante requeridas por los shaders. | -| `--bary-fallback` | Cuando falta `VK_KHR_fragment_shader_barycentric`. | -| `--texel-offset-fallback` | Cuando falta `VK_KHR_maintenance8` para los desplazamientos de muestreo. | -| `--mesh-compute` | Cuando falta `VK_EXT_mesh_shader`: traduce los shaders mesh como compute. | -| `--f16-interp-fallback` | Interpolación de 16 bits sin entradas `PerVertexKHR`; se activa automáticamente cuando la GPU del runtime no puede usarlas, como ocurre con MoltenVK. | -| `--pc-tail-ubo` | Para GPU cuyo límite de push constants es insuficiente; se activa automáticamente cuando el runtime detecta ese límite. | - -El modo wave64 y estas opciones se guardan junto a los shaders. Cambiarlos vuelve a ejecutar la traducción. -`auto` normalmente reutiliza los shaders ya emulados, salvo cuando la alternativa de AMD para Windows requiere -reconstruirlos en modo nativo. - -### Reanudar tras una actualización - -La compilación registra el comando y la versión de `llvm-mc` que generaron el desensamblado: si cambian, o si la -carpeta de trabajo es anterior a ese registro, vuelve a desensamblar y traducir, conservando las entradas extraídas. -También registra los archivos fuente del traductor; un cambio en ellos repite la traducción a partir del -desensamblado guardado. - -Para modelos y texturas registra el commit de `third_party/rpf9-explorer` y el código de `tools/rpf9dump`. Cuando -cambia ese decodificador, elimina la exportación de cada archivo afectado y la genera de nuevo. Las carpetas -antiguas sin esos registros necesitan repetir una vez la traducción o la exportación correspondiente. - -### Linux y Wine/Proton - -`make_game.py` también funciona en Linux. Las herramientas de diagnóstico Vulkan se compilan de forma nativa -con CMake 3.24+, un compilador C++20 y las cabeceras y el cargador de Vulkan: - -```sh -cmake -S runtime -B runtime/build/linux -cmake --build runtime/build/linux --parallel -./runtime/build/linux/vk_pipeline_check /ruta/a/spirv -``` - -El último comando recibe la carpeta que contiene `index.json` y los shaders traducidos. La etapa `pipelines` -usa `vk_pipeline_check` de `runtime/build/linux` o `runtime/build`, y lo compila antes de iniciar el resto del -trabajo si falta. - -El cargador es un programa de Windows y se ejecuta bajo Wine o Proton. En Linux la etapa `runtime` puede -compilarlo de forma cruzada con `clang-cl` y `lld-link` (LLVM 19+, excepto 22.1.7 y 22.1.8) y el CRT de MSVC y el -SDK de Windows preparados por [xwin](https://github.com/Jake-Shadle/xwin), en `XWIN_DIR` o -`~/.local/share/xwin-sdk`. La [guía de pruebas](../../testing.md#the-windows-runtime-on-linux-under-wine-or-proton) -explica la preparación. Si faltan esas herramientas, `runtime` se omite de las etapas predeterminadas; pedirlo -explícitamente enumera lo que falta antes de empezar. - -También puede pasar `--runtime-build ` con una compilación de Windows (`gta6rt.exe` y -`gta6rt_tls_host.dll`), por ejemplo el artefacto `runtime-windows` del trabajo `windows` del workflow Runtime, -descomprimido. Así evita compilar el runtime; la misma opción funciona en Windows. En Linux el script escribe -`gta6rt.sh`, que lanza `gta6rt.exe` con `wine`, o con el Wine indicado por la variable `WINE` (para Proton, su -`files/bin/wine`). -- **`--wave64-emulate`**: traduce los shaders compute y mesh wave64 de forma exacta cualquiera que sea el tamaño de - subgrupo de la GPU. Las GPU NVIDIA e Intel usan subgrupos de 32 y lo necesitan. El valor predeterminado, `auto`, - consulta `vulkaninfo` y activa la emulación salvo que todas las GPU anuncien subgrupos de 64. -- **`--work`**: elija un disco con al menos 400 GB libres. La traducción de shaders es la etapa más larga; por - defecto usa la mitad de los hilos del procesador (ajustable con `--jobs`). -- **`--wav`**: desactivado por defecto, porque el WAV PCM de 16 bits ocupa varias veces más que el Ogg Opus. -- **Linux y Wine/Proton**: `make_game.py` también funciona en Linux. El cargador es un programa de Windows y se - ejecuta bajo Wine o Proton. Para la etapa `runtime` puede pasar `--runtime-build ` con una compilación - de Windows (`gta6rt.exe` y `gta6rt_tls_host.dll`): el script escribe entonces `gta6rt.sh`, que lanza - `gta6rt.exe` con `wine`, o con el Wine indicado por la variable `WINE` (para Proton, su `files/bin/wine`). - -## Problemas habituales - -- **Usó «Download ZIP» en GitHub**: el ZIP no contiene el submódulo `third_party/rpf9-explorer`. Use - `git clone --recursive`, o ejecute `git submodule update --init --recursive` en la carpeta del repositorio. -- **`llvm-mc` rechaza `gfx1013` o el destino AMDGPU**: probablemente usa el instalador oficial de LLVM para - Windows. Ejecute `scripts\build_llvm_mc.ps1`, o apunte `LLVM_MC` al `llvm-mc` de WSL (`llvm-21`). -- **CMake se detiene en «needs the Windows SDK 10.0.26100 or newer»**, o MSVC indica que `Desc_1_2` no es miembro - de `D3D12_VERSIONED_ROOT_SIGNATURE_DESC`: actualice el SDK de Windows a `10.0.26100` o superior, con el - Instalador de Visual Studio o con `winget install Microsoft.WindowsSDK.10.0.26100`, y luego borre - `runtime/build` y repita la configuración. -- **Se quedó sin espacio en `C:`**: pase `--work "D:\leonida-work"` para situar los archivos temporales en otra - unidad; también puede cambiar `--out` u omitir `assets` con `--stages check,shaders,runtime` (unos 30 GB). -- **Windows se niega a lanzar los programas de prueba recién compilados** («An Application Control policy has - blocked this file»): es el control inteligente de aplicaciones de Windows 11. Véase - [`docs/testing.md`](../../testing.md#known-problems). - -## Contribuir y ejecutar las pruebas de GPU - -1. Revise las pull requests abiertas y la [issue de coordinación][coord] para no rehacer un trabajo en curso. - Reserve la tarea con `claiming: `, o con una descripción de una línea si aún no hay identificador. -2. Ejecute las pruebas pertinentes, con entradas sintéticas. Por ejemplo, - `python -I tests/test_manifest_verifier.py` desde la raíz del repositorio. -3. En la pull request, indique el identificador de la tarea, qué probó, y la GPU y el controlador si ejecutó - pruebas de GPU. Diga si recibió ayuda de una IA. Las reglas están en - [`CONTRIBUTING.md`](../../../CONTRIBUTING.md). - -La [guía de pruebas de GPU](../../testing.md) explica cómo ejecutarlas sin ningún archivo del juego. Publique sus -resultados en la [issue #166](https://github.com/ItsNotRexed/Leonida/issues/166), un comentario por GPU y por -controlador. - -[coord]: https://github.com/ItsNotRexed/Leonida/issues?q=is%3Aissue%20is%3Aopen%20in%3Atitle%20%22Coordinating%20who%20works%20on%20what%22 diff --git a/docs/i18n/fr/contributing.md b/docs/i18n/fr/contributing.md deleted file mode 100644 index dfbe85fe3..000000000 --- a/docs/i18n/fr/contributing.md +++ /dev/null @@ -1,95 +0,0 @@ -# Leonida : contribuer (`fr`) - -> [!NOTE] -> La version anglaise de [`CONTRIBUTING.md`](../../../CONTRIBUTING.md) **fait foi**. Cette traduction est -> synchronisée avec le commit `1ab957b3`. En cas de différence, suivez l'anglais. - -Merci de votre aide. Quelques règles permettent au projet de rester hébergeable : - -- **Aucune donnée du jeu, jamais.** Cela comprend les archives, l'exécutable, les fichiers extraits, les shaders - (DXBC, FSSM, désassemblage, SPIR-V), les textures, les modèles, l'audio, les vidéos, ainsi que les rapports ou - journaux qui les citent. Le `.gitignore` bloque les types courants ; vérifiez quand même `git status` avant de - commiter. -- **Pas de clés, de déchiffrement ni de contournement de protection**, et aucun lien vers un endroit où les obtenir. - Les outils ne lisent que des fichiers déjà en clair sur le disque. -- De courts extraits nécessaires pour expliquer un format (quelques octets d'en-tête, une séquence d'instructions) - sont acceptés dans la documentation et les commentaires. - -## Avant de commencer - -Réservez la tâche dans [l'issue de coordination][claims] : l'issue ouverte intitulée « Coordinating who works on -what ». Quand le fil devient trop long, elle est remplacée par une nouvelle issue, c'est pourquoi le lien lance une -recherche. Consultez ses tableaux et les pull requests ouvertes, publiez `claiming: ` dans l'issue (ou une -description d'une ligne pour une tâche qui n'y figure pas encore), puis indiquez l'identifiant dans votre pull -request. - -Vous avez repéré quelque chose à faire mais vous ne comptez pas vous en charger ? Publiez `finding: ` dans -l'issue, en précisant où se trouve le problème et pourquoi il compte. La tâche rejoint alors la liste pour quelqu'un -d'autre. Si deux pull requests se recoupent malgré tout, celle qui arrive en premier est fusionnée et l'autre doit -être rebasée ou fermée. - -Une fois la pull request ouverte, publiez `done: -> #` dans l'issue. Les pull requests visent `main`. - -Le dépôt d'origine (`ItsNotRexed/Leonida`) est devenu privé le 23 novembre 2026, avec ses issues et ses pull -requests. Un `#N` écrit avant cette date dans la documentation, un commentaire de code ou un message de commit est -un **ancien** numéro et ne mène plus nulle part, y compris les deux vers lesquels cette page renvoyait : #166 -(résultats des tests GPU) et #313 (la page de la couche D3D12 → Vulkan). - -- Les titres des issues qui y étaient ouvertes sont répertoriés dans - [#18](https://github.com/ubiquitarianism/leonida/issues/18). Pour en reprendre une, rouvrez-la ici avec un lien - vers cet index. -- Les pull requests qui y étaient ouvertes sont conservées dans des branches `old-pr/`, listées dans - [#17](https://github.com/ubiquitarianism/leonida/issues/17). Pour en reprendre une, rebasez-la sur `main`, - gardez les commits de son auteur et ouvrez une pull request ici. -- Un résultat de test GPU est une pull request qui ajoute un fichier dans - [`gpu-test-results/`](../../../gpu-test-results), au format des fichiers qui s'y trouvent ; - [docs/testing.md](../../testing.md) explique comment lancer les tests. -- Le plan et l'état de la couche D3D12 → Vulkan sont dans [docs/d3d12_vulkan.md](../../d3d12_vulkan.md). - -[claims]: https://github.com/ubiquitarianism/leonida/issues?q=is%3Aissue%20is%3Aopen%20in%3Atitle%20%22Coordinating%20who%20works%20on%20what%22 - -## Travailler sur le code - -- Les outils Python se lancent avec `python -I` et n'utilisent que la bibliothèque standard, sauf si le fichier - indique le contraire. -- Un fichier texte écrit par un outil (JSON, CSV, manifeste, listing d'assembleur) précise sa fin de ligne : - `open(path, "w", encoding="utf-8", newline="\n")` (de même pour `Path.open`, `Path.write_text` et un - `tempfile.NamedTemporaryFile` en mode texte). La sortie est ainsi en LF même sous Windows, et une même entrée - donne les mêmes octets sur toutes les plateformes. `tests/test_text_write_line_endings.py` échoue si un outil - l'oublie. -- Un générateur de rapport refuse une sortie qui désigne l'une de ses entrées ou une autre de ses sorties. Pour le - vérifier, il appelle `tools/report_paths.same_report_path(a, b)` au lieu de refaire le calcul lui-même : la - fonction résout les deux chemins, applique les règles de casse du volume et se rabat sur `os.path.samefile`. Un - nouvel outil réutilise donc cette réponse plutôt que d'en garder sa propre copie. `tests/test_report_paths.py` - couvre ce cas. -- `tools/rpf9dump` a besoin du sous-module : `git submodule update --init`. -- Une nouvelle règle du traducteur de shaders va dans le tableau de contrat de `docs/design.md`, avec la façon dont - elle a été confirmée : un test GPU, une référence Mesa/LLVM ou un comptage sur le corpus. -- `python -I tests/test_.py` lance un test unitaire (bibliothèque standard uniquement ; la CI les lance tous). - Les fichiers de test sans bloc `__main__`, ou qui contiennent un `import pytest` (ils ont besoin des paquets de - `tests/requirements.txt`), se lancent plutôt avec `python -m pytest tests/test_.py`, comme l'explique - [AGENTS.md](../../../AGENTS.md). Avec `python -I`, ils échouent à l'import ou ne lancent rien. -- Tests du runtime : `cmake -S runtime -B runtime/build`, `cmake --build runtime/build --config RelWithDebInfo`, - puis `ctest --test-dir runtime/build -C RelWithDebInfo --output-on-failure`. Les tests CPU qui ne demandent aucune - donnée du jeu sont configurés sous Windows ; Linux et macOS configurent le sous-ensemble portable (`gta6rt` et les - shims n'existent que pour Windows). Les tests qui ont besoin du paquet commercial le lisent sur place via - `LEONIDA_GAME_DIR` (et `LEONIDA_MOVIE` pour le test de décodage Bink), et affichent `SKIP` quand la variable n'est - pas définie. Ne copiez et ne commitez jamais ces fichiers. -- Tests du streaming du viewer : `node --test tests/test_viewer_streaming.cjs` (Node.js 22+, la CI teste la 24 LTS ; - ni paquets, ni navigateur, ni réseau, ni données du jeu). Ils exécutent le code de streaming du viewer avec un - chargeur et une horloge synthétiques. -- `loader_test` écrit de petites images PE dans un dossier `leonida_loader_test` de `%TEMP%`. Si un antivirus bloque - les exécutables tout juste écrits, le test s'arrête en donnant cette raison. Excluez le dossier, ou faites pointer - `LEONIDA_TEST_DIR` vers un dossier que l'antivirus ignore. -- Vérification des outils : `python -m compileall -q make_game.py tools tests`. L'outil facultatif - `vk_pipeline_check [cache.bin] [--jobs N]` crée un module (et, pour les shaders compute, un pipeline) - pour chaque shader traduit, puis signale les échecs et le chemin du cache enregistré. -- Les tests GPU sont de petits programmes RDNA2 écrits à la main, dans `runtime/test/shaders`. `build.py` les - convertit en SPIR-V avec `llvm-mc` et la cible AMDGPU (LLVM 21+), puis `check.py` les exécute sur votre GPU et - compare les résultats. Un nouveau test donne ses valeurs attendues dans le commentaire en tête du fichier, et - reçoit sa vérification dans `check.py`. [docs/testing.md](../../testing.md) décrit l'installation pour chaque - système, y compris les options natives sous Windows, ainsi que les problèmes connus. -- Dans la pull request, indiquez ce que vous avez testé et sur quel GPU. -- Lancez les tests du traducteur avec `python -I scripts/run_semantic_tests.py tests/semantic` (voir - `tests/semantic/README.md`). Une nouvelle règle du traducteur doit venir avec une petite fixture `.asm` écrite à la - main et les mots de sortie attendus. diff --git a/docs/i18n/fr/quickstart.md b/docs/i18n/fr/quickstart.md deleted file mode 100644 index 933a74d4e..000000000 --- a/docs/i18n/fr/quickstart.md +++ /dev/null @@ -1,183 +0,0 @@ -# Leonida — Guide de démarrage (`fr`) - -> [!NOTE] -> La documentation en anglais ([`README.md`](../../../README.md), [`CONTRIBUTING.md`](../../../CONTRIBUTING.md) et -> [`docs/README.md`](../../README.md)) **fait foi**. Ce guide ne reprend que les instructions stables d'installation -> et de compilation (synchronisé avec le commit `aa2988cc`). Pour l'état d'avancement du projet, qui change tous les -> jours, consultez le [`README.md`](../../../README.md). - -## Ce qu'est Leonida - -Leonida est un projet de recompilation statique de Grand Theft Auto VI (version Xbox Series) pour le faire tourner -nativement sous Windows. Il se construit **sur votre PC, à partir de votre propre copie du jeu**. Les shaders RDNA2 de -la console sont traduits en SPIR-V (Vulkan), les ressources sont lues directement dans votre paquet et le logiciel -système de la console est réimplémenté sous forme de shims. - -> [!IMPORTANT] -> Ce dépôt **ne contient ni le jeu, ni clés, ni exécutable**, et n'explique pas comment les obtenir. Rien ici ne -> déchiffre ni ne contourne une protection. Tout ce que la compilation produit (shaders traduits, ressources -> extraites, dossier de travail, sauvegardes) provient de votre copie et **doit rester sur votre machine** : ne -> joignez et ne partagez jamais ces fichiers dans une issue ou une pull request (voir -> [`CONTRIBUTING.md`](../../../CONTRIBUTING.md)). - -Le projet en est à ses débuts : **le jeu ne démarre pas encore**. - -## Plateformes - -Rien n'est jouable, sur aucune plateforme. Ce qui tourne aujourd'hui : - -- **Windows** : tout (`make_game.py`, les outils, et le runtime `gta6rt` avec la couche D3D12 → Vulkan et ses tests). -- **Linux** : le traducteur, les outils de ressources et les outils de test GPU Vulkan tournent nativement (testés - sur RADV et NVIDIA). Le runtime est du code Windows : il se compile en croisé avec clang-cl et xwin, et ses tests - tournent sous Wine ou Proton. Le jeu est prévu pour tourner de la même façon (#217). -- **macOS (Apple Silicon)** : les outils Python et les outils de test Vulkan tournent nativement, sur MoltenVK - (Homebrew) ou KosmicKrisp. Le runtime tourne sous Wine, comme sous Linux. Limites connues : pas d'étape geometry ni - de `VK_EXT_mesh_shader`, sous-groupes de 32 (les shaders wave64 sont émulés) et la gestion des flottants de - MoltenVK ; [`docs/testing.md`](../../testing.md) les détaille. -- **AMD RDNA1 (RX 5000)** : une cible prise en charge, proche du RDNA2 de la console ; ses sous-groupes de 64 - exécutent les shaders wave64 nativement. - -Les résultats GPU de toutes les plateformes sont regroupés dans -l'[issue #166](https://github.com/ItsNotRexed/Leonida/issues/166). - -## Prérequis - -- **Votre propre copie** du paquet Xbox Series, version `1.0.2.1` : le dossier qui contient `MicrosoftGame.Config` et - les archives `.rpf`, sous forme de fichiers lisibles sur le disque. -- **Windows 10/11 x64**, avec environ **350 Go libres** pour les fichiers de travail. Ils peuvent aller sur un autre - disque avec `--work`. -- [Python 3.12+](https://www.python.org/downloads/) (cochez « Add python.exe to PATH » à l'installation). -- [SDK .NET 8](https://dotnet.microsoft.com/download/dotnet/8.0). -- [SDK Vulkan](https://vulkan.lunarg.com/) (`spirv-as`, `spirv-val` et `vulkaninfo`). -- [LLVM 21+](https://github.com/llvm/llvm-project/releases) avec la **cible AMDGPU** (`llvm-mc`) : - - La version officielle de LLVM pour Windows **n'inclut pas** la cible AMDGPU. - - Pour compiler un `llvm-mc.exe` natif avec cette cible, lancez `.\scripts\build_llvm_mc.ps1` dans PowerShell - depuis la racine du dépôt. Le script a besoin de `git` et des outils C++ de Visual Studio. Il définit `LLVM_MC` - pour votre utilisateur : ouvrez ensuite un nouveau terminal pour que la variable soit prise en compte. Comptez - 20 à 40 minutes. - - Plus rapide si vous utilisez [conda](https://docs.conda.io/) : `conda install -c conda-forge llvm-tools` (sa - version Windows inclut la cible AMDGPU), puis faites pointer `LLVM_MC` vers le chemin complet du `llvm-mc.exe` - installé (`where.exe llvm-mc` l'affiche une fois l'environnement activé ; le `where` seul est - l'alias `Where-Object` de PowerShell). - - Avec WSL, installez `llvm-21` dans Ubuntu et donnez la commande entière à `LLVM_MC`, dans la session PowerShell - où vous lancerez `make_game.py` : - - ```powershell - $env:LLVM_MC = 'wsl -d Ubuntu -e /usr/lib/llvm-21/bin/llvm-mc' - ``` - - Voir [`docs/design.md`](../../design.md#disassembling-shaders) pour les détails. - - Sous Linux, un `llvm-mc` présent dans le `PATH` suffit. -- **Visual Studio 2022** avec la charge de travail *Développement Desktop en C++* et le **SDK Windows `10.0.26100` ou - plus récent**, pour l'étape `runtime` (le runtime utilise les root signatures 1.2, absentes des SDK plus anciens). -- [ffmpeg](https://ffmpeg.org/download.html) dans le `PATH` *(facultatif : décode les flux XMA2, et obligatoire avec - `--wav`)*. - -## Compiler - -### La méthode simple (Windows) - -1. Installez les prérequis ci-dessus. -2. Clonez le dépôt **avec son sous-module** : - ```powershell - git clone --recursive https://github.com/ItsNotRexed/Leonida - ``` - Un « Download ZIP » depuis GitHub n'inclut pas `third_party/rpf9-explorer` : la compilation le récupère si `git` - est installé, et sinon vous dit quoi faire. -3. Double-cliquez sur **`Build.bat`**. - -Le script trouve votre copie tout seul : il cherche dans Téléchargements, Bureau, Documents (y compris là où Windows -les range, par exemple dans OneDrive), Games, votre dossier utilisateur et à la racine de chaque disque, sur deux -niveaux de dossiers. Il reconnaît la version à la taille de quelques fichiers, sans rien lire de volumineux. S'il -trouve plusieurs copies, il demande -laquelle utiliser ; s'il n'en trouve aucune, il vous demande de coller le chemin du dossier. Avant de commencer, il -vérifie les prérequis et l'espace libre, et liste d'un coup tout ce qui manque. Le résultat va dans -`Documents\Leonida`. Une compilation interrompue reprend là où elle s'était arrêtée. - -### Peu d'espace disque - -L'espace indiqué plus haut correspond à la compilation complète. Pour *lancer* le portage, -`--stages check,shaders,runtime` a besoin d'environ 30 Go ; l'étape `assets`, qui prend presque tout le reste, ne sert -qu'aux outils de ressources, et `--wav` ajoute plusieurs fois la taille de l'Ogg Opus. `--work` et `--out` peuvent être sur un autre disque. Le runtime lit le paquet sur -place : si son disque est en lecture seule, passez `gta6rt --overlay ` (c'est une -option de `gta6rt`, pas de `make_game.py`). Ne supprimez pas les fichiers `.s` de `work/shaders/dxbc/disasm` : sans -eux et sans `work/shaders/spirv/index.json`, l'étape `shaders` peut sembler terminée avec zéro shader. - -### Depuis un terminal (`make_game.py`) - -```powershell -python -I make_game.py --find # liste les copies trouvées sur ce PC -python -I make_game.py --pick # ouvre une fenêtre pour choisir le dossier du jeu -python -I make_game.py --check # vérifie votre copie, sans rien compiler -python -I make_game.py --check --full-check # vérifie aussi le SHA-256 de chaque fichier (lent) -python -I make_game.py --game "D:\chemin\vers\le\paquet" --out "D:\Games\Leonida" --work "E:\leonida-work" -python -I make_game.py --stages shaders,assets # seulement certaines étapes -python -I make_game.py --game "D:\chemin\vers\le\paquet" --wav # décode aussi l'Opus en WAV PCM (volumineux) -python -I make_game.py --wave64-emulate off # auto (par défaut), on ou off -``` - -`check` passe toujours en premier ; ensuite, `shaders`, `assets` et `runtime` tournent en même temps quand ils sont -demandés (ils ne dépendent pas les uns des autres). `pipelines` démarre dès que les shaders traduits sont prêts et, -si l'exécution comprend `runtime`, une fois que cette étape a recompilé `vk_pipeline_check` : elle peut donc tourner -pendant la fin d'`assets`. L'étape -`pipelines` crée chaque shader traduit avec le pilote de votre GPU, vérifie qu'il compile, signale ceux qu'elle doit -ignorer et enregistre un cache de pipelines dans `pipeline_cache.bin` (dans `--out`) ; le runtime ne charge pas -encore ce cache. - -- **`--wave64-emulate`** : traduit les shaders compute et mesh wave64 de façon exacte quelle que soit la taille des - sous-groupes du GPU. Les GPU NVIDIA et Intel ont des sous-groupes de 32 et en ont besoin. La valeur par défaut, - `auto`, interroge `vulkaninfo` et active l'émulation si un GPU n'a pas de sous-groupes de 64 ou si leur taille est - inconnue. Avec le pilote Windows d'AMD, `auto` garde le wave64 natif sur RDNA1 et RDNA2 quand le GPU du runtime le - permet, car ce pilote peut planter sur le code émulé (#857). Le mode est enregistré à côté des shaders traduits, et - le changer les retraduit. -- **Options de repli** pour les appareils auxquels manque une fonction Vulkan, enregistrées et retraduites de la même - façon : `--no-float-controls`, `--bary-fallback` (sans `VK_KHR_fragment_shader_barycentric`), - `--texel-offset-fallback` (sans `VK_KHR_maintenance8`) et `--mesh-compute` (sans `VK_EXT_mesh_shader`). Voir - [`docs/design.md`](../../design.md). -- **Ce qui est refait automatiquement** : la compilation enregistre la commande et la version de `llvm-mc`, les - sources du traducteur et le décodeur des ressources (`third_party/rpf9-explorer` et `tools/rpf9dump`). Si l'un - d'eux change, seule l'étape concernée est refaite (désassemblage, traduction ou export des modèles et textures). -- **`--work`** : choisissez un disque avec au moins 350 Go libres. La traduction des shaders est l'étape la plus - longue ; elle utilise par défaut la moitié des threads du processeur (réglable avec `--jobs`). -- **`--wav`** : désactivé par défaut, car le WAV PCM 16 bits est plusieurs fois plus volumineux que l'Ogg Opus. -- **Linux et Wine/Proton** : `make_game.py` fonctionne aussi sous Linux. L'étape `pipelines` utilise - `vk_pipeline_check` (compilé avec CMake dans `runtime/build/linux`, ou par le script lui-même s'il manque). Le - chargeur est un programme Windows et tourne sous Wine ou Proton : l'étape `runtime` le compile en croisé avec - clang-cl et lld-link (LLVM 19+, sauf 22.1.7 et 22.1.8) et le SDK Windows préparé par - [xwin](https://github.com/Jake-Shadle/xwin) ; voir [`docs/testing.md`](../../testing.md). Vous pouvez aussi passer - `--runtime-build ` avec une compilation Windows faite ailleurs (`gta6rt.exe` et `gta6rt_tls_host.dll`) : - dans les deux cas, le script écrit `gta6rt.sh`, qui lance - `gta6rt.exe` avec `wine`, ou avec le Wine désigné par la variable `WINE` (pour Proton, son `files/bin/wine`). - -## Problèmes courants - -- **Vous avez utilisé « Download ZIP » sur GitHub** : le ZIP ne contient pas le sous-module - `third_party/rpf9-explorer`. Utilisez `git clone --recursive`, ou lancez `git submodule update --init --recursive` - dans le dossier du dépôt. -- **`llvm-mc` refuse `gfx1013` ou la cible AMDGPU** : vous utilisez probablement l'installateur officiel de LLVM pour - Windows. Lancez `scripts\build_llvm_mc.ps1`, ou faites pointer `LLVM_MC` vers le `llvm-mc` de WSL (`llvm-21`). -- **CMake s'arrête sur « needs the Windows SDK 10.0.26100 or newer »**, ou MSVC signale que `Desc_1_2` n'est pas - membre de `D3D12_VERSIONED_ROOT_SIGNATURE_DESC` : mettez à jour le SDK Windows en `10.0.26100` ou plus récent, par - le Visual Studio Installer ou avec `winget install Microsoft.WindowsSDK.10.0.26100`, puis supprimez - `runtime/build` et relancez la configuration. -- **Plus de place sur `C:`** : passez `--work "D:\leonida-work"` pour placer les fichiers temporaires sur un autre - disque. -- **Windows refuse de lancer les programmes de test tout juste compilés** (« An Application Control policy has - blocked this file ») : c'est le Contrôle intelligent des applications de Windows 11. Voir - [`docs/testing.md`](../../testing.md#known-problems). - -## Contribuer et lancer les tests GPU - -1. Consultez les pull requests ouvertes et l'[issue de coordination][coord] pour ne pas refaire un travail en cours. - Réservez la tâche avec `claiming: `, ou avec une description d'une ligne s'il n'y a pas encore d'identifiant. -2. Lancez les tests concernés, avec des entrées synthétiques. Par exemple, `python -I tests/test_manifest_verifier.py` - depuis la racine du dépôt. -3. Dans la pull request, indiquez l'identifiant de la tâche, ce que vous avez testé, et le GPU et le pilote si vous - avez lancé des tests GPU. Précisez si vous avez été assisté par une IA. Les règles sont dans - [`CONTRIBUTING.md`](../../../CONTRIBUTING.md). - -Le [guide des tests GPU](../../testing.md) explique comment lancer les tests sans aucun fichier du jeu. Publiez vos -résultats dans l'[issue #166](https://github.com/ItsNotRexed/Leonida/issues/166), un commentaire par GPU et par -pilote. - -[coord]: https://github.com/ItsNotRexed/Leonida/issues?q=is%3Aissue%20is%3Aopen%20in%3Atitle%20%22Coordinating%20who%20works%20on%20what%22 diff --git a/docs/i18n/it/quickstart.md b/docs/i18n/it/quickstart.md deleted file mode 100644 index d42f35727..000000000 --- a/docs/i18n/it/quickstart.md +++ /dev/null @@ -1,156 +0,0 @@ -# Leonida — Guida rapida (`it`) - -> [!NOTE] -> La documentazione in inglese ([`README.md`](../../../README.md), [`CONTRIBUTING.md`](../../../CONTRIBUTING.md) e -> [`docs/README.md`](../../README.md)) è la **fonte di riferimento**. Questa guida raccoglie solo le istruzioni -> stabili di configurazione e compilazione (sincronizzata con il commit `49475796`). Per lo stato quotidiano del -> progetto consulta il [`README.md`](../../../README.md). - -## Che cos'è Leonida - -Leonida è un progetto di ricompilazione statica di Grand Theft Auto VI (Xbox Series) per eseguirlo nativamente su -Windows, **costruito sul tuo PC a partire dalla tua copia**. Il codice del gioco viene caricato ed eseguito -nativamente (la CPU di Xbox Series è x86-64 come quella di un PC), il software di sistema della console è -reimplementato in shim e i programmi GPU RDNA2 della console vengono tradotti in SPIR-V per Vulkan. Modelli, -texture e audio sono letti dal tuo pacchetto. - -> [!IMPORTANT] -> Questo repository **non contiene il gioco, chiavi né eseguibili**, e non spiega come ottenerli. Nulla qui -> decifra o aggira protezioni. Tutto ciò che la build produce (shader tradotti, asset estratti, cartella di -> lavoro e salvataggi) deriva dalla tua copia e **deve restare solo sul tuo computer**: non allegare né -> condividere questi file in issue o pull request (vedi [`CONTRIBUTING.md`](../../../CONTRIBUTING.md)). - -Il progetto è in fase iniziale: **il gioco non si avvia ancora**. - -## Prerequisiti - -- **La tua copia** del pacchetto Xbox Series, versione `1.0.2.1` (la cartella che contiene `MicrosoftGame.Config` - e gli archivi `.rpf` come file normali su disco). -- **Windows 10/11 x64** con circa **400 GB liberi** per i file di lavoro (possono stare su un altro disco con - `--work`). -- [Python 3.12+](https://www.python.org/downloads/) (spunta «Add python.exe to PATH»). -- [.NET 8 SDK](https://dotnet.microsoft.com/download/dotnet/8.0). -- [Vulkan SDK](https://vulkan.lunarg.com/), per `spirv-as` / `spirv-val` (e `vulkaninfo`). -- [LLVM 21+](https://github.com/llvm/llvm-project/releases) con il **target AMDGPU**, per `llvm-mc`: - - La build ufficiale di LLVM per Windows **non** include il target AMDGPU. - - Per compilare un `llvm-mc.exe` nativo con AMDGPU, esegui questo comando dalla radice del repository - (non serve WSL): - - ```powershell - powershell -ExecutionPolicy Bypass -File scripts\build_llvm_mc.ps1 - ``` - - Lo script richiede `git` e gli strumenti C++ di Visual Studio (vedi sotto), imposta `LLVM_MC` per il tuo - utente e ti chiede di aprire un nuovo terminale per caricare la variabile. - - In alternativa, installa `llvm-21` in WSL (Ubuntu) e imposta la variabile con il comando completo, nella - stessa sessione PowerShell da cui avvierai `make_game.py`: - - ```powershell - $env:LLVM_MC = 'wsl -d Ubuntu -e /usr/lib/llvm-21/bin/llvm-mc' - ``` - - Vedi [`docs/design.md`](../../design.md#disassembling-shaders) per i dettagli. - - Su Linux basta avere `llvm-mc` nel `PATH`. -- **Visual Studio 2022** con il carico di lavoro **Sviluppo di applicazioni desktop con C++** e il **Windows SDK - `10.0.26100` o successivo**, necessari per la fase `runtime` (il runtime usa le root signature versione 1.2, - che gli SDK più vecchi non dichiarano). -- [ffmpeg](https://ffmpeg.org/download.html) nel `PATH` *(facoltativo: decodifica gli stream XMA2 ed è - obbligatorio con `--wav`)*. - -## Come compilare - -### Modo semplice (Windows) - -1. Installa i prerequisiti qui sopra. -2. Scarica il progetto **con il suo sottomodulo**: - - ```powershell - git clone --recursive https://github.com/ItsNotRexed/Leonida - ``` - - Il «Download ZIP» di GitHub non include `third_party/rpf9-explorer`. La build lo scarica da sola se `git` è - installato, altrimenti ti dice cosa fare. -3. Fai doppio clic su **`Build.bat`**. - -Lo script cerca da solo la tua copia del gioco: Download, Desktop, Documenti (anche dove Windows li sposta, per -esempio in OneDrive), Giochi, la cartella utente e la radice di ogni disco, fino a due livelli di profondità. -Riconosce la versione da poche dimensioni di file, senza leggere nulla di grande. Se hai più copie ti chiede -quale usare, e se non ne trova nessuna ti chiede di incollare il percorso della cartella. Prima di partire -verifica che tutto il necessario sia installato e che ci sia abbastanza spazio libero, e ti elenca in un colpo -solo ciò che manca. Il risultato va in `Documents\Leonida`. Se la build viene interrotta, riprende da dove si era -fermata. - -### Dal terminale (`make_game.py`) - -Stesso comportamento, con più controllo: - -```powershell -python -I make_game.py --find # elenca le copie trovate su questo PC -python -I make_game.py --pick # scegli la cartella del gioco in una finestra -python -I make_game.py --check # verifica la tua copia, senza compilare -python -I make_game.py --check --full-check # confronta anche lo SHA-256 di ogni file (lento) -python -I make_game.py --game "D:\percorso\del\pacchetto" --out "D:\Games\Leonida" --work "E:\leonida-work" -python -I make_game.py --stages shaders,assets # solo alcune fasi -python -I make_game.py --game "D:\percorso\del\pacchetto" --wav # decodifica anche Opus in PCM WAV (grande) -python -I make_game.py --wave64-emulate off # auto (predefinito), on oppure off -``` - -La fase `check` viene eseguita sempre per prima; poi, quando sono selezionate, `shaders`, `assets` e `runtime` vengono eseguite insieme (non dipendono l'una dall'altra). `pipelines` parte quando gli shader tradotti sono pronti. -`pipelines` crea ogni shader tradotto sul driver della tua GPU e salva una cache delle pipeline, così al primo -avvio non devono essere compilati. La traduzione degli shader è il passaggio più lungo: usa `--jobs` processi -(per impostazione predefinita metà dei thread della CPU). - -- **`--wave64-emulate`**: traduce gli shader compute e mesh wave64 in modo che siano esatti con qualunque - dimensione di subgruppo. Le GPU NVIDIA e Intel hanno subgruppi da 32 lane e ne hanno bisogno. Il valore - predefinito `auto` interroga `vulkaninfo` (parte del Vulkan SDK) e attiva l'emulazione a meno che ogni GPU - non dichiari subgruppi da 64, oppure quando non riesce a stabilirlo. Resta spenta quando la GPU del runtime è - una scheda o iGPU RDNA2 (RX 6000, grafica integrata Ryzen 6000/7000/9000) con il driver AMD per Windows, che - esegue wave64 in modo nativo. La modalità viene salvata accanto agli shader tradotti, e cambiarla li traduce - di nuovo. Vedi «Wave64 emulation» in [`docs/design.md`](../../design.md). -- **Opzioni di ripiego** (inoltrate al traduttore, salvate accanto agli shader; cambiarle li traduce di nuovo): - `--no-float-controls`, `--bary-fallback` (GPU senza `VK_KHR_fragment_shader_barycentric`), - `--texel-offset-fallback` (GPU senza `VK_KHR_maintenance8`) e `--mesh-compute` (GPU senza - `VK_EXT_mesh_shader`). Sono documentate in [`docs/design.md`](../../design.md). -- **`--work`**: conviene puntarlo a un disco con almeno 400 GB liberi. -- **`--wav`**: disattivato di default perché il WAV PCM a 16 bit occupa molto più dell'Ogg Opus. -- **Linux e Wine/Proton**: `make_game.py` funziona anche su Linux. Per la fase `runtime` fuori da Windows passa - `--runtime-build ` con una build Windows (`gta6rt.exe` e `gta6rt_tls_host.dll`, per esempio - l'artefatto `runtime-windows` della CI scompattato): lo script copia i file in `--out` e scrive `gta6rt.sh`, - che avvia `gta6rt.exe` con `wine` (o con il Wine indicato dalla variabile `WINE`; per Proton, il suo - `files/bin/wine`). La stessa opzione salta la compilazione anche su Windows. In alternativa, su Linux la fase - `runtime` può cross-compilare il loader con clang-cl e lld-link (LLVM 19+, esclusi 22.1.7 e 22.1.8) contro - l'SDK di Windows preparato da [xwin](https://github.com/Jake-Shadle/xwin): vedi - [`docs/testing.md`](../../testing.md#the-windows-runtime-on-linux-under-wine-or-proton). - -## Problemi comuni - -- **Hai scaricato con «Download ZIP» di GitHub**: lo ZIP non include il sottomodulo `third_party/rpf9-explorer`. - Usa `git clone --recursive` oppure esegui `git submodule update --init --recursive` nella cartella del - repository. -- **`llvm-mc` rifiuta `gfx1013` / AMDGPU**: probabilmente hai l'installer ufficiale di LLVM per Windows. Segui - una delle opzioni LLVM descritte nei prerequisiti. -- **Errore su `D3D12_ROOT_SIGNATURE_DESC2` durante la build del runtime**: aggiorna il Windows SDK alla versione - `10.0.26100` o successiva dal Visual Studio Installer oppure con - `winget install Microsoft.WindowsSDK.10.0.26100`, elimina la cartella di build e riconfigura. -- **Spazio esaurito sul disco `C:`**: passa `--work "D:\leonida-work"` per spostare i file temporanei su un'altra - partizione. - -## Come contribuire ed eseguire i test GPU - -1. Controlla le pull request aperte e l'[issue di coordinamento][coord] per evitare lavoro duplicato. Riserva - l'attività scrivendo `claiming: ` (oppure una descrizione di una riga se non esiste ancora un ID) prima - di aprire la pull request. -2. Esegui i test pertinenti con input sintetici. Per esempio, per il verificatore dei manifest: - `python -I tests/test_manifest_verifier.py` dalla radice del repository. La suite del traduttore si esegue - con `python -m unittest discover -s tests/semantic -v`. -3. Nella pull request indica l'ID dell'attività, cosa hai provato e, se hai eseguito test GPU, quale GPU e - quale driver. Le regole sono in [`CONTRIBUTING.md`](../../../CONTRIBUTING.md). Se hai usato un assistente - IA, dichiaralo nella pull request, come richiesto da [`AGENTS.md`](../../../AGENTS.md). - -**Mai** allegare a issue o pull request file del gioco, asset estratti o shader generati: condividi solo -risultati (conteggi, esito dei test, classi di errore). - -La [guida ai test GPU](../../testing.md) spiega come eseguirli senza i file del gioco. I risultati dei test GPU -vanno pubblicati nell'[issue #166](https://github.com/ItsNotRexed/Leonida/issues/166). - -[coord]: https://github.com/ItsNotRexed/Leonida/issues?q=is%3Aissue%20is%3Aopen%20in%3Atitle%20%22Coordinating%20who%20works%20on%20what%22 diff --git a/docs/i18n/ja/quickstart.md b/docs/i18n/ja/quickstart.md deleted file mode 100644 index 2924be033..000000000 --- a/docs/i18n/ja/quickstart.md +++ /dev/null @@ -1,138 +0,0 @@ -# Leonida クイックスタート(`ja`) - -> [!NOTE] -> 英語のドキュメント([`README.md`](../../../README.md)、[`CONTRIBUTING.md`](../../../CONTRIBUTING.md)、 -> [`docs/README.md`](../../README.md))が**正式版**です。このページは安定したセットアップとビルド手順のみを -> まとめたもので、commit `003e781` に同期しています。日々の進捗は [`README.md`](../../../README.md) -> を参照してください。 - -## Leonida とは - -Leonida は、Xbox Series 版 Grand Theft Auto VI を Windows 上でネイティブに動かすための**静的リコンパイル** -プロジェクトです。Xbox Series の CPU は PC と同じ x86-64 なので、ゲームのコードはそのまま読み込まれて -ネイティブに実行され、本体側のシステムソフトウェアは shim として再実装されます。本体用にコンパイル済みの -RDNA2 GPU プログラムは Vulkan 向けの SPIR-V に翻訳され、モデル・テクスチャ・音声はあなたのパッケージから -直接読み込まれます。これらはすべて**あなたの PC 上で、あなた自身のゲームのコピーから**行われます。 - -> [!IMPORTANT] -> このリポジトリにはゲーム、キー、実行ファイルは**含まれません**。入手方法も説明しません。自分用のコピーが -> 必要で、そのファイルはあらかじめディスク上で読める状態になっている必要があります。ここには復号や保護の -> 回避を行うものは何もありません。ビルドが生成するもの(翻訳されたシェーダー、抽出されたアセット、 -> runtime フォルダー、セーブデータ)はすべてあなたのゲームに由来し、あなたの PC に残ります。これらの -> ファイルを共有しないでください([`CONTRIBUTING.md`](../../../CONTRIBUTING.md))。 - -プロジェクトはまだ初期段階で、**ゲームはまだ起動しません**。 - -## 前提条件 - -- **自分用の Xbox Series パッケージ**(バージョン `1.0.2.1`)。`MicrosoftGame.Config` と `.rpf` アーカイブが - プレーンなファイルとして置かれているフォルダーが、ゲームフォルダーです。 -- **Windows 10/11 x64** と、作業ファイル用に約 **400 GB** の空き容量(`--work` で別ドライブに置けます)。 -- [Python 3.12+](https://www.python.org/downloads/)(インストール時に "Add python.exe to PATH" を有効に)。 -- [.NET 8 SDK](https://dotnet.microsoft.com/download/dotnet/8.0)。 -- [Vulkan SDK](https://vulkan.lunarg.com/)(`spirv-as` / `spirv-val` 用)。 -- **AMDGPU target** を含む [LLVM 21+](https://github.com/llvm/llvm-project/releases)(`llvm-mc` 用)。 - - Windows 版の公式 LLVM には AMDGPU target が**含まれていません**。 - - Windows では、リポジトリのルートで次のコマンドを実行すると、AMDGPU target 付きのネイティブ `llvm-mc.exe` を - ビルドし(WSL 不要。`git` と下記の Visual Studio の C++ ツールが必要)、`LLVM_MC` を設定します: - - ```powershell - powershell -ExecutionPolicy Bypass -File scripts\build_llvm_mc.ps1 - ``` - - または WSL に `llvm-21` を入れて、`LLVM_MC` にコマンド全体を設定します: - `LLVM_MC="wsl -d Ubuntu -e /usr/lib/llvm-21/bin/llvm-mc"` - ([docs/design.md](../../design.md#disassembling-shaders))。 - - Linux では `PATH` に `llvm-mc` があれば十分です。 -- **Visual Studio 2022**(**C++ によるデスクトップ開発**)と **Windows SDK 10.0.26100 以降**。 - `runtime` ステージで必要です(バージョン 1.2 の root signature を使い、古い SDK には宣言がないためです)。 -- [ffmpeg](https://ffmpeg.org/download.html) を `PATH` に(任意: XMA2 ストリームのデコード。`--wav` では必須)。 - -## ビルド方法 - -ポートはビルド済みで配布されているものではありません。**あなたの PC 上で、あなた自身のコピーから**ビルドします。 - -### 簡単な方法(Windows) - -1. 上記の前提条件をインストールします。 -2. サブモジュール込みでリポジトリを取得します。 - - ```powershell - git clone --recursive https://github.com/ItsNotRexed/Leonida - ``` - - GitHub の "Download ZIP" では `third_party/rpf9-explorer` が含まれません。`git` があればビルドが自動で - 取得し、なければ必要な操作を表示します。 -3. **`Build.bat`** をダブルクリックします。 - -すると、ゲームのコピーが自動で見つかります。ダウンロード、デスクトップ、ドキュメント(OneDrive など -Windows が保存する場所を含む)、Games、ホームフォルダー、各ドライブの先頭から 2 階層までを探し、いくつかの -ファイルサイズからバージョンを判定します(大きなファイルは読みません)。複数ある場合はどれを使うか確認し、 -見つからない場合はフォルダーの貼り付けを求めます。開始前に上記の前提条件と空き容量を確認し、足りないものを -まとめて表示します。出力先は `Documents\Leonida` です。中断したビルドは続きから再開します。 - -### コマンドライン(`make_game.py`) - -```powershell -python -I make_game.py --find # この PC で見つかったコピーを一覧 -python -I make_game.py --pick # フォルダーダイアログでゲームフォルダーを選ぶ -python -I make_game.py --check # コピーを確認するだけでビルドしない -python -I make_game.py --check --full-check # すべてのファイルの SHA-256 も比較(低速) -python -I make_game.py --game "D:\path\to\your\package" --out "D:\Games\Leonida" --work "E:\leonida-work" -python -I make_game.py --stages shaders,assets # 一部のステージだけ -python -I make_game.py --game "D:\path\to\your\package" --wav # Opus を PCM WAV にもデコード(大容量) -python -I make_game.py --wave64-emulate off # auto(既定)、on、off のいずれか -``` - -`check` ステージは常に最初に実行され、選択した場合は `shaders`、`assets`、`runtime` が同時に実行されます(互いに依存しません)。`pipelines` は翻訳済みのシェーダーが揃い次第開始されます。このステージは -翻訳済みの各シェーダーをあなたの GPU ドライバー上で生成してパイプラインキャッシュを保存するので、初回起動時の -コンパイルが不要になります。最も時間がかかるのはシェーダーの翻訳で、`--jobs` 個のプロセスで実行されます -(既定では CPU スレッド数の半分)。 - -- **`--wave64-emulate`**: wave64 の compute / mesh シェーダーを、どのサブグループサイズでも正確になるように - 翻訳するかどうかを決めます。NVIDIA と Intel の GPU は 32 レーンのサブグループなので必要です。既定の `auto` は - `vulkaninfo`(Vulkan SDK に含まれる)に問い合わせ、すべての GPU が 64 レーンのサブグループを報告しない場合、 - または判定できない場合に有効にします。ただし runtime が使う GPU が、AMD の Windows ドライバーで wave64 を - ネイティブに実行できる RDNA2 のカードや iGPU の場合は、そのドライバーのシェーダーコンパイラーが - エミュレーションされた LDS コードでクラッシュするため(#857)、オフのままにします。設定は翻訳済みシェーダーの - 隣に保存され、変更すると翻訳し直しになります。 -- **`--work`**: 中間ファイル用のフォルダーです。最低でも 400 GB 空いているドライブを指定してください。 -- **`--wav`**: 既定では無効です。16-bit PCM WAV は Ogg Opus より数倍大きいためです。 -- **Linux と Wine/Proton**: `make_game.py` は Linux でも動作します。ローダーは Windows プログラムなので - Wine または Proton で動きます。`runtime` ステージは Linux 上で clang-cl と lld-link(LLVM 19 以降)を使い、 - [xwin](https://github.com/Jake-Shadle/xwin) が `XWIN_DIR` または `~/.local/share/xwin-sdk` に用意した - MSVC CRT と Windows SDK に対して `runtime/build/windows` へクロスビルドします - ([docs/testing.md](../../testing.md#the-windows-runtime-on-linux-under-wine-or-proton) に一度だけ実行する - `xwin` コマンドがあります)。これらがない場合、このステージは既定のステージから外れ、明示的に指定すると - 何が足りないかを作業開始前に表示します。別の場所で作った Windows 版も使えます: - - ```sh - python3 -I make_game.py --runtime-build ~/Downloads/runtime-windows - ``` - - どちらの場合も `gta6rt.exe` と `gta6rt_tls_host.dll` を `--out` にコピーし、隣に `gta6rt.sh` を書き出します。 - これは `gta6rt.exe` を `wine`、または `WINE` で指定した Wine(Proton なら `files/bin/wine`)で起動します。 - Windows で同じオプションを指定すると、ビルドは省略されます。 - -## よくある問題 - -- **GitHub の "Download ZIP" を使った**: ZIP には `third_party/rpf9-explorer` サブモジュールが含まれません。 - `git clone --recursive` を使うか、リポジトリのフォルダーで `git submodule update --init --recursive` を - 実行してください。 -- **`llvm-mc` が `gfx1013` や AMDGPU を拒否する**: Windows 版の公式 LLVM を使っている可能性が高いです。 - リポジトリのルートで `powershell -ExecutionPolicy Bypass -File scripts\build_llvm_mc.ps1` を実行するか、 - `LLVM_MC` を WSL の `llvm-mc`(`llvm-21`)に向けてください。 -- **CMake が "needs the Windows SDK 10.0.26100 or newer" で止まる**、または MSVC が `Desc_1_2` は - `D3D12_VERSIONED_ROOT_SIGNATURE_DESC` のメンバーではないと報告する: Windows SDK を `10.0.26100` 以降に - 更新し(Visual Studio Installer、または `winget install Microsoft.WindowsSDK.10.0.26100`)、 - `runtime/build` を削除してから構成し直してください。 -- **`C:` ドライブの空きが足りない**: `--work "D:\leonida-work"` を指定して中間ファイルを別のドライブに置きます。 -- **Windows がビルド直後のテストプログラムの実行を拒否する**("An Application Control policy has blocked this - file"): Windows 11 のスマート アプリ コントロールです。 - [docs/testing.md](../../testing.md#known-problems) を参照してください。 - -## コントリビュートと GPU テスト - -- GPU テストの手順(ゲームファイル不要): [docs/testing.md](../../testing.md)。結果は - [#166](https://github.com/ItsNotRexed/Leonida/issues/166) に、GPU とドライバーごとに 1 コメントで投稿します。 -- コントリビュートのルール、ゲームデータを持ち込まない方針、作業の調整: - [`CONTRIBUTING.md`](../../../CONTRIBUTING.md)。 diff --git a/docs/i18n/pl-PL/quickstart.md b/docs/i18n/pl-PL/quickstart.md deleted file mode 100644 index 29cfb6a08..000000000 --- a/docs/i18n/pl-PL/quickstart.md +++ /dev/null @@ -1,174 +0,0 @@ -# Leonida — Szybki start (`pl-PL`) - -> [!NOTE] -> Dokumentacja w języku angielskim ([`README.md`](../../../README.md), [`CONTRIBUTING.md`](../../../CONTRIBUTING.md) i -> [`docs/README.md`](../../README.md)) jest **wersją obowiązującą**. Ten przewodnik zawiera tylko stabilne instrukcje -> konfiguracji i budowania (zsynchronizowany z commitem `f847748c`). Aktualny stan projektu znajdziesz w -> [`README.md`](../../../README.md). - -## Czym jest Leonida - -Leonida to projekt statycznej rekompilacji Grand Theft Auto VI (Xbox Series), który uruchamia grę natywnie na -Windowsie. Port jest budowany **na Twoim komputerze z Twojej własnej kopii gry**. Procesor Xbox Series jest x86-64 -tak jak w komputerze PC, więc kod gry jest ładowany i wykonywany natywnie, a oprogramowanie systemowe konsoli jest -implementowane od nowa w postaci tzw. shimów. Skompilowane wcześniej programy GPU konsoli (RDNA2) są tłumaczone na -SPIR-V (Vulkan), a modele, tekstury i audio są odczytywane bezpośrednio z Twojej paczki. - -> [!IMPORTANT] -> To repozytorium **nie zawiera gry, kluczy ani pliku wykonywalnego** i nie wyjaśnia, jak je zdobyć. Nic tutaj nie -> odszyfrowuje danych ani nie obchodzi zabezpieczeń. Wszystko, co tworzy build (przetłumaczone shadery, wyodrębnione -> zasoby, folder roboczy i zapisy gry), pochodzi z Twojej kopii i **musi zostać wyłącznie na Twoim komputerze** — -> nigdy nie załączaj ani nie udostępniaj tych plików w issues ani pull requestach (zobacz -> [`CONTRIBUTING.md`](../../../CONTRIBUTING.md)). - -Projekt jest na wczesnym etapie: **gra jeszcze się nie uruchamia**. - -## Wymagania - -- **Twoja własna kopia** paczki Xbox Series w wersji `1.0.2.1` (folder z plikiem `MicrosoftGame.Config` i archiwami `.rpf` czytelnymi na dysku jako zwykłe pliki). -- **Windows 10/11 x64** z około **400 GB wolnego miejsca** na pliki robocze (mogą trafić na inny dysk dzięki `--work`). -- [Python 3.12+](https://www.python.org/downloads/) (zaznacz *„Add python.exe to PATH”*). -- [.NET 8 SDK](https://dotnet.microsoft.com/download/dotnet/8.0). -- [Vulkan SDK](https://vulkan.lunarg.com/) (`spirv-as`, `spirv-val` i `vulkaninfo`). -- [LLVM 21+](https://github.com/llvm/llvm-project/releases) z **targetem AMDGPU** (`llvm-mc`): - - Oficjalna wersja LLVM dla Windowsa **nie** zawiera targetu AMDGPU. - - Aby zbudować natywny `llvm-mc.exe` z AMDGPU, uruchom `.\scripts\build_llvm_mc.ps1` w PowerShellu w głównym - folderze repozytorium (WSL nie jest potrzebny). Skrypt wymaga `git` i narzędzi C++ z Visual Studio, ustawia - zmienną `LLVM_MC` dla Twojego użytkownika i prosi o otwarcie nowego terminala, żeby zmienna była widoczna. - - Jeśli używasz WSL, zainstaluj `llvm-21` w Ubuntu i ustaw zmienną w tej samej sesji PowerShella, w której - uruchamiasz `make_game.py`: - - ```powershell - $env:LLVM_MC = 'wsl -d Ubuntu -e /usr/lib/llvm-21/bin/llvm-mc' - ``` - - Więcej szczegółów w [`docs/design.md`](../../design.md#disassembling-shaders). - - Na Linuksie wystarczy `llvm-mc` w `PATH`. -- **Visual Studio 2022** z pakietem *Programowanie aplikacji klasycznych w języku C++* i **Windows SDK `10.0.26100` - lub nowszym** (potrzebne do etapu `runtime`, który używa root signatures w wersji 1.2; starsze SDK ich nie - deklarują). -- [ffmpeg](https://ffmpeg.org/download.html) w `PATH` *(opcjonalnie: dekoduje strumienie XMA2 i jest wymagany przy - `--wav`)*. - -**Mało miejsca na dysku:** około 400 GB dotyczy pełnego builda. Do *uruchomienia* portu etapy -`--stages check,shaders,runtime` potrzebują około 30 GB; etap `assets` (~370 GB) służy tylko narzędziom do zasobów, -a `--wav` dodaje kilkakrotność rozmiaru Ogg Opus. `--work` i `--out` mogą leżeć na innym dysku; paczka na dysku -tylko do odczytu wymaga `--overlay` (opcja `gta6rt`) na dysku zapisywalnym. Nie usuwaj plików `.s` z -`work/shaders/dxbc/disasm`: skasowanie ich z pozostawieniem folderu sprawia, że etap wygląda na ukończony z zerem -shaderów, a `disasm` będący dowiązaniem symbolicznym jest odrzucany. - -## Jak zbudować - -Portu nie pobiera się gotowego. Buduje się go na Twoim komputerze z Twojej kopii. - -**Prosty sposób:** - -1. Zainstaluj wymagania powyżej. -2. Pobierz projekt **razem z submodułem**: - ```powershell - git clone --recursive https://github.com/ItsNotRexed/Leonida - ``` - „Download ZIP” z GitHuba pomija `third_party/rpf9-explorer`. Build pobierze go sam, jeśli masz `git`, a w - przeciwnym razie powie, co zrobić. -3. Kliknij dwukrotnie **`Build.bat`**. - -Skrypt sam znajdzie Twoją kopię gry: szuka w Pobranych, na Pulpicie, w Dokumentach (także tam, gdzie Windows je -trzyma, np. w OneDrive), w Games, w folderze użytkownika i na początku każdego dysku, do dwóch poziomów w głąb. -Rozpoznaje wersję po rozmiarach kilku plików, bez czytania dużych danych. Jeśli znajdzie kilka kopii, zapyta, której -użyć, a jeśli żadnej — poprosi o wklejenie ścieżki do folderu. Przed startem sprawdza, czy wszystko jest zainstalowane -i czy jest dość wolnego miejsca, i wymienia wszystkie braki naraz. Wynik zapisuje w `Documents\Leonida`. Przerwany -build można uruchomić ponownie — będzie kontynuowany od miejsca, w którym się zatrzymał. - -### Z terminala (`make_game.py`) - -To samo zachowanie i więcej kontroli: - -```powershell -python -I make_game.py --find # lista kopii gry znalezionych na tym komputerze -python -I make_game.py --pick # wybór folderu gry w oknie dialogowym -python -I make_game.py --check # sprawdza Twoją kopię, niczego nie buduje -python -I make_game.py --check --full-check # dodatkowo porównuje SHA-256 każdego pliku (wolno) -python -I make_game.py --game "D:\sciezka\do\paczki" --out "D:\Games\Leonida" --work "E:\leonida-work" -python -I make_game.py --stages shaders,assets # tylko wybrane etapy -python -I make_game.py --game "D:\sciezka\do\paczki" --wav # dodatkowo dekoduje Ogg Opus do PCM WAV (duże pliki) -python -I make_game.py --wave64-emulate off # auto (domyślnie), on lub off -``` - -Etap `check` zawsze wykonuje się pierwszy; następnie, jeśli zostały wybrane, `shaders`, `assets` i `runtime` wykonują się równocześnie (nie zależą od siebie). Etap `pipelines` startuje, gdy przetłumaczone shadery są gotowe. Ten etap -tworzy każdy przetłumaczony shader na sterowniku Twojej karty graficznej i zapisuje cache potoków, żeby pierwsze -uruchomienie nie musiało ich kompilować. Tłumaczenie shaderów trwa najdłużej i domyślnie używa połowy wątków -procesora (można to zmienić przez `--jobs`). - -- **`--wave64-emulate`**: decyduje, czy shadery compute i mesh wave64 są tłumaczone tak, by były dokładne przy - dowolnym rozmiarze podgrupy (zobacz „Wave64 emulation” w [`docs/design.md`](../../design.md)). Karty NVIDIA i - Intel mają podgrupy 32-wątkowe i potrzebują tej emulacji. Domyślny tryb `auto` pyta `vulkaninfo` (część Vulkan SDK) - i włącza emulację, jeśli którejś karcie brakuje podgrup 64-wątkowych albo nie da się ustalić ich rozmiaru. Sprawdza - też, czy karta używana przez runtime potrafi uruchamiać shadery compute i mesh z podgrupami 64-wątkowymi; z - `--mesh-compute` wystarczy obsługa compute. W sterowniku AMD dla Windowsa `auto` używa natywnego wave64 na RDNA1 i - RDNA2, gdy karta runtime to obsługuje — nawet jeśli inna karta ma podgrupy 32-wątkowe albo `vulkaninfo` jest - niedostępne; ten sterownik potrafi się wysypać na emulowanym kodzie LDS (#857). Na kartach RDNA1 bez obsługi mesh - decyzja opiera się na etapie compute, który potrafi uruchomić wave64 bez natywnego mesh. Tryb jest zapisywany obok - przetłumaczonych shaderów, a jego zmiana tłumaczy je ponownie. `auto` zwykle może użyć ponownie wcześniej - emulowanych shaderów; obejście dla AMD na Windowsie przebudowuje je w trybie natywnym. Użyj `--wave64-emulate on`, - aby wymusić emulację, albo `--wave64-emulate off`, aby wymusić natywne wave64. -- **Cztery flagi awaryjne** są przekazywane do translatora w ten sam sposób, zapisywane obok przetłumaczonych - shaderów, a ich zmiana tłumaczy je ponownie: `--no-float-controls` (usuwa `SignedZeroInfNanPreserve` dla urządzeń, - których sprawdzanie potoku pomija shader bez `shaderSignedZeroInfNanPreserveFloat32`; wymaga flagi translatora z - PR #664), `--bary-fallback` (czyta surowe barycentryki z interpolowanego wejścia, dla urządzeń bez - `VK_KHR_fragment_shader_barycentric`), `--texel-offset-fallback` (wlicza przesunięcia `image_sample*_o` do - współrzędnej, dla urządzeń bez `VK_KHR_maintenance8`) i `--mesh-compute` (shadery mesh jako compute, dla urządzeń - bez `VK_EXT_mesh_shader`). Każda jest opisana w [`docs/design.md`](../../design.md). -- **`--work`**: najlepiej wskazać dysk z co najmniej 400 GB wolnego miejsca; do samego uruchomienia wystarczy około - 30 GB (zobacz „Mało miejsca na dysku” powyżej). -- **`--wav`**: domyślnie wyłączone, bo 16-bitowy PCM WAV jest kilkakrotnie większy od Ogg Opus. Dekoduje przepakowane - strumienie Ogg Opus do `work\assets\audio\wav` po etapie banków audio; istniejące pliki WAV są pomijane przy - wznawianiu builda. -- **Linux i Wine/Proton**: `make_game.py` działa też na Linuksie, a etap `pipelines` sam buduje tam - `vk_pipeline_check`, jeśli go brakuje. Aby wykonać etap `runtime` poza Windowsem, podaj `--runtime-build ` - z buildem dla Windowsa (`gta6rt.exe` i `gta6rt_tls_host.dll`, np. rozpakowany artefakt `runtime-windows` z CI). - Skrypt skopiuje te pliki do `--out` i utworzy `gta6rt.sh`, który uruchamia program przez `wine` (albo przez Wine - wskazane zmienną `WINE`, np. z Protona: `files/bin/wine`). Ta sama opcja pomija build na Windowsie. Alternatywnie - etap `runtime` może na Linuksie cross-kompilować loader przez clang-cl i lld-link (LLVM 19+, ale nie 22.1.7 ani - 22.1.8) przeciw CRT MSVC i Windows SDK przygotowanym przez [xwin](https://github.com/Jake-Shadle/xwin) w - `XWIN_DIR` lub `~/.local/share/xwin-sdk`; szczegóły w - [`docs/testing.md`](../../testing.md#the-windows-runtime-on-linux-under-wine-or-proton). - -Build zapisuje polecenie i wersję `llvm-mc`, które utworzyły pliki `.s`, oraz źródła translatora, które utworzyły -shadery. Zmiana któregokolwiek z nich, a także użycie starszego folderu roboczego, uruchamia ponownie deasemblację -albo tłumaczenie z zachowaniem wyodrębnionych wejść shaderów. -- **`--wave64-emulate`**: emuluje shadery compute/mesh wave64 na kartach z podgrupami 32-wątkowymi (NVIDIA i Intel). Domyślny tryb `auto` pyta `vulkaninfo` i sam włącza emulację, gdy jest potrzebna. -- **`--work`**: najlepiej wskazać dysk z co najmniej 400 GB wolnego miejsca. Etap `shaders` trwa najdłużej i domyślnie używa połowy wątków procesora (można to zmienić przez `--jobs`). -- **Linux i Wine/Proton**: `make_game.py` działa też na Linuksie. Aby wykonać etap `runtime` poza Windowsem, podaj `--runtime-build ` z buildem dla Windowsa (`gta6rt.exe` i `gta6rt_tls_host.dll`). Skrypt utworzy wtedy `gta6rt.sh`, który uruchamia program przez `wine` (albo przez Wine wskazane zmienną `WINE`, np. z Protona). - -## Częste problemy - -- **Pobrałeś repozytorium przyciskiem „Download ZIP” na GitHubie**: archiwum ZIP nie zawiera submodułu - `third_party/rpf9-explorer`. Użyj `git clone --recursive`; build pobierze submoduł sam, jeśli masz `git`, a jeśli - nie — powie, co zrobić. Możesz też uruchomić `git submodule update --init --recursive` w folderze repozytorium. -- **`llvm-mc` odrzuca `gfx1013` / AMDGPU**: najpewniej masz oficjalny instalator LLVM dla Windowsa. Użyj - `scripts\build_llvm_mc.ps1` albo ustaw `LLVM_MC` na `llvm-mc` z WSL (`llvm-21`). -- **Błąd `D3D12_ROOT_SIGNATURE_DESC2` przy budowaniu runtime**: zaktualizuj Windows SDK do `10.0.26100` lub nowszego - przez Visual Studio Installer albo `winget install Microsoft.WindowsSDK.10.0.26100`, usuń folder builda i - skonfiguruj go ponownie. -- **Brak miejsca na dysku `C:`**: podaj `--work "D:\leonida-work"`, aby przenieść pliki robocze na inną partycję. - Do samego uruchomienia wystarczą etapy `--stages check,shaders,runtime` (około 30 GB); `--out` też może leżeć na - innym dysku. - -## Jak pomóc i uruchomić testy GPU - -1. Przejrzyj otwarte PR-y i [issue koordynacyjne][coord], żeby nie dublować pracy, i zarezerwuj zadanie **przed** - otwarciem PR-a: wpisem `claiming: ` albo jednym zdaniem opisu, jeśli zadanie nie ma jeszcze ID. -2. Uruchom odpowiednie testy na syntetycznych danych wejściowych. Na przykład weryfikator manifestów testujesz - poleceniem `python -I tests/test_manifest_verifier.py` w głównym folderze repozytorium, a suite translatora — - `python -m unittest discover -s tests/semantic -v`. -3. W PR podaj ID zadania, opisz, co przetestowałeś, a jeśli uruchamiałeś testy GPU — podaj kartę i wersję - sterownika. Zaznacz, czy korzystałeś z pomocy AI, zgodnie z [`AGENTS.md`](../../../AGENTS.md). Zasady znajdziesz - w [`CONTRIBUTING.md`](../../../CONTRIBUTING.md). - -**Nigdy** nie załączaj do issues ani PR-ów plików gry, wyodrębnionych zasobów ani wygenerowanych shaderów: dziel się -tylko wynikami (liczby, wyniki testów, klasy błędów). - -[Przewodnik po testach GPU](../../testing.md) pokazuje, jak uruchomić testy bez plików gry. Wyniki testów GPU -publikuj w [issue #166](https://github.com/ItsNotRexed/Leonida/issues/166). - -[coord]: https://github.com/ItsNotRexed/Leonida/issues?q=is%3Aissue%20is%3Aopen%20in%3Atitle%20%22Coordinating%20who%20works%20on%20what%22 diff --git a/docs/i18n/pt-BR/quickstart.md b/docs/i18n/pt-BR/quickstart.md deleted file mode 100644 index 16f05be3a..000000000 --- a/docs/i18n/pt-BR/quickstart.md +++ /dev/null @@ -1,173 +0,0 @@ -# Leonida — Guia rápido (`pt-BR`) - -> [!NOTE] -> A documentação em inglês ([`README.md`](../../../README.md), [`CONTRIBUTING.md`](../../../CONTRIBUTING.md) e -> [`docs/README.md`](../../README.md)) é a **referência oficial**. Este guia reúne apenas instruções estáveis de -> configuração e compilação (sincronizado com o commit `f847748c`). Para o status diário do projeto, consulte o -> [`README.md`](../../../README.md). - -## O que é o Leonida - -O Leonida é um projeto de recompilação estática do Grand Theft Auto VI (Xbox Series) para rodar nativamente no -Windows, construído **no seu próprio PC a partir da sua própria cópia**. Os shaders RDNA2 do console são -traduzidos para SPIR-V (Vulkan), os assets são lidos diretamente do seu pacote e o software de sistema do -console é reimplementado em shims. - -> [!IMPORTANT] -> Este repositório **não contém o jogo, chaves nem executável**, e não explica como obtê-los. Nada aqui -> descriptografa ou contorna proteções. Tudo o que o build gera (shaders traduzidos, assets extraídos, pasta de -> trabalho e saves) vem da sua cópia e **deve ficar apenas na sua máquina** — nunca anexe nem compartilhe esses -> arquivos em issues ou pull requests (veja [`CONTRIBUTING.md`](../../../CONTRIBUTING.md)). - -O projeto está em fase inicial: **o jogo ainda não dá boot**. - -## Pré-requisitos - -- **Sua própria cópia** do pacote Xbox Series, versão `1.0.2.1` (pasta com `MicrosoftGame.Config` e os arquivos `.rpf` legíveis em disco). -- **Windows 10/11 x64** com cerca de **30 GB livres** para preparar só o runtime ou **400 GB** para o build completo. -- [Python 3.12+](https://www.python.org/downloads/) (marque *"Add python.exe to PATH"*). -- [.NET 8 SDK](https://dotnet.microsoft.com/download/dotnet/8.0). -- [Vulkan SDK](https://vulkan.lunarg.com/) (`spirv-as`, `spirv-val` e `vulkaninfo`). -- [LLVM 21+](https://github.com/llvm/llvm-project/releases) com o **target AMDGPU** (`llvm-mc`): - - O binário oficial do LLVM para Windows **não** inclui o target AMDGPU. - - Para compilar um `llvm-mc.exe` nativo com AMDGPU, rode este comando a partir da raiz do repositório. - - ```powershell - powershell -ExecutionPolicy Bypass -File scripts\build_llvm_mc.ps1 - ``` - - O script requer `git` e as ferramentas C++ do Visual Studio, configura `LLVM_MC` para o seu usuário - e pede que você abra um novo terminal para carregar a variável. - - Se usar o WSL, instale `llvm-21` no Ubuntu e defina a variável na mesma sessão do PowerShell em que vai - executar `make_game.py`. - - ```powershell - $env:LLVM_MC = 'wsl -d Ubuntu -e /usr/lib/llvm-21/bin/llvm-mc' - ``` - - Veja [`docs/design.md`](../../design.md#disassembling-shaders) para mais detalhes. - - No Linux, basta ter `llvm-mc` no `PATH`. -- **Visual Studio 2022** com *Desenvolvimento para desktop com C++* e **Windows SDK `10.0.26100` ou mais recente** (necessário para o estágio `runtime`, que usa root signatures 1.2). -- [ffmpeg](https://ffmpeg.org/download.html) no `PATH` *(opcional: decodifica streams XMA2 e é exigido ao usar `--wav`)*. - -**Pouco espaço em disco:** o valor de ~400 GB refere-se ao build completo. Para *executar* o port, -`--stages check,shaders,runtime` precisa de cerca de **30 GB**; o estágio `assets` (~370 GB) serve apenas para as -ferramentas de extração de assets, e `--wav` adiciona várias vezes o tamanho dos arquivos Ogg Opus. `--work` e `--out` -podem apontar para outro disco; se o pacote do jogo estiver em uma unidade somente leitura, use `--overlay` (no -`gta6rt`) em um disco gravável. Mantenha os arquivos `.s` em `work/shaders/dxbc/disasm`: apagá-los mantendo a pasta faz -o estágio parecer concluído com zero shaders, e um link simbólico em `disasm` é recusado. - -## Como compilar - -### Modo simples (Windows) - -1. Instale os pré-requisitos acima. -2. Clone o repositório **com o submódulo**: - ```powershell - git clone --recursive https://github.com/ItsNotRexed/Leonida - ``` -3. Abra a pasta `Leonida` e dê duplo clique em **`Build.bat`**. - -O script procura automaticamente sua cópia (Downloads, Desktop, Documentos, Games, pasta de usuário e raiz dos -discos até dois níveis), valida os pré-requisitos e o espaço livre e grava o resultado em `Documents\Leonida`. -Se o build for interrompido, basta rodar novamente para retomar de onde parou. - -**Espaço em disco baixo:** o valor de ~400 GB é para o build completo. Para *rodar* o port, `--stages check,shaders,runtime` -precisa de cerca de 30 GB; o estágio `assets` (~370 GB) é apenas para as ferramentas de assets, e `--wav` adiciona -várias vezes o tamanho do Ogg Opus. `--work` e `--out` podem ficar em outro disco; uma unidade de pacote somente leitura -precisa de `--overlay` em uma gravável. Mantenha os arquivos `.s` em `work/shaders/dxbc/disasm` no lugar: apagá-los -mantendo a pasta faz o estágio parecer concluído com zero shaders, e um `disasm` com symlink é recusado. - -### Pelo terminal (`make_game.py`) - -```powershell -python -I make_game.py --find # lista as cópias encontradas neste PC -python -I make_game.py --pick # escolhe a pasta do jogo em uma janela de diálogo -python -I make_game.py --check # verifica os arquivos do jogo sem compilar -python -I make_game.py --check --full-check # também compara o SHA-256 de cada arquivo (lento) -python -I make_game.py --game "D:\caminho\do\pacote" --out "D:\Games\Leonida" --work "E:\leonida-work" -python -I make_game.py --stages shaders,assets # roda apenas os estágios escolhidos -python -I make_game.py --game "D:\caminho\do\pacote" --wav # também decodifica Ogg Opus para PCM WAV (grande) -python -I make_game.py --wave64-emulate off # auto (padrão), on ou off; veja abaixo -``` - -O estágio `check` sempre roda primeiro; depois, quando selecionados, `shaders`, `assets` e `runtime` rodam juntos (não dependem uns dos outros). `pipelines` começa assim que os shaders traduzidos estiverem prontos. - -- **`--wave64-emulate`**: emula shaders compute/mesh wave64 em GPUs com subgrupos de 32 lanes (NVIDIA e Intel). O padrão `auto` consulta `vulkaninfo` e ativa a emulação se alguma GPU não tiver subgrupos de 64 lanes ou se o tamanho for desconhecido, verificando também se a GPU do runtime suporta compute e mesh em 64 lanes (com `--mesh-compute`, apenas o suporte em compute é necessário). No driver Windows da AMD, `auto` usa wave64 nativo em GPUs RDNA1 e RDNA2 quando a GPU do runtime suporta (para placas RDNA1 sem suporte a mesh shaders, a decisão usa o estágio compute), mesmo que outra GPU seja de 32 lanes ou que `vulkaninfo` não esteja disponível, pois o compilador desse driver pode falhar em código LDS emulado (#857). O modo escolhido fica salvo junto aos shaders traduzidos; use `--wave64-emulate on` para forçar a emulação ou `--wave64-emulate off` para forçar wave64 nativo. -- **Flags de fallback do tradutor**: `--no-float-controls` (omite `SignedZeroInfNanPreserve`), `--bary-fallback` (lê baricêntricas de um input interpolado sem `VK_KHR_fragment_shader_barycentric`), `--texel-offset-fallback` (incorpora offsets `image_sample*_o` na coordenada sem `VK_KHR_maintenance8`) e `--mesh-compute` (traduz mesh shaders como compute sem `VK_EXT_mesh_shader`) são repassadas ao tradutor e salvas junto aos shaders; alterá-las retraduz os shaders (veja [`docs/design.md`](../../design.md)). -- **`--work`**: recomenda-se apontar para um disco com pelo menos 400 GB livres para o build completo (ou ~30 GB com `--stages check,shaders,runtime`); o estágio `shaders` é o mais demorado e usa metade das threads da CPU por padrão (ajustável com `--jobs`). -- **`--wav`**: fica desativado por padrão porque WAV PCM de 16 bits é várias vezes maior que Ogg Opus; quando ativado, decodifica os streams Ogg Opus para `work\assets\audio\wav` e pula arquivos WAV já existentes ao retomar um build. - -### Build com pouco espaço em disco - -Para preparar o runtime e os shaders com cerca de **30 GB livres**, execute na raiz do repositório: - -```powershell -python -I make_game.py --stages check,shaders,runtime -``` - -O estágio `assets` serve às ferramentas de extração e ocupa cerca de 370 GB. A opção `--wav` aumenta ainda mais -o espaço usado pelos áudios. Você pode apontar `--work` e `--out` para outro disco. Se o disco do pacote for -somente leitura, passe `--overlay` ao iniciar o runtime e aponte para uma pasta em um disco gravável. -- **`--wave64-emulate`**: emula shaders compute/mesh wave64 em GPUs com subgrupos de 32 lanes (NVIDIA e Intel). O padrão `auto` consulta `vulkaninfo` e ativa a emulação se alguma GPU não tiver subgrupos de 64 lanes ou se o tamanho for desconhecido, verificando também se a GPU do runtime suporta compute e mesh em 64 lanes (com `--mesh-compute`, apenas o suporte em compute é necessário). No driver Windows da AMD, `auto` usa wave64 nativo em GPUs RDNA1 e RDNA2 quando a GPU do runtime suporta (para placas RDNA1 sem suporte a mesh shaders, a decisão usa o estágio compute), mesmo que outra GPU seja de 32 lanes ou que `vulkaninfo` não esteja disponível, pois o compilador desse driver pode falhar em código LDS emulado (#857). O modo escolhido fica salvo junto aos shaders traduzidos; use `--wave64-emulate on` para forçar a emulação ou `--wave64-emulate off` para forçar wave64 nativo. -- **Flags de fallback do tradutor**: `--no-float-controls` (omite `SignedZeroInfNanPreserve`), `--bary-fallback` (lê baricêntricas de um input interpolado sem `VK_KHR_fragment_shader_barycentric`), `--texel-offset-fallback` (incorpora offsets `image_sample*_o` na coordenada sem `VK_KHR_maintenance8`) e `--mesh-compute` (traduz mesh shaders como compute sem `VK_EXT_mesh_shader`) são repassadas ao tradutor e salvas junto aos shaders; alterá-las retraduz os shaders (veja [`docs/design.md`](../../design.md)). -- **`--work`**: recomenda-se apontar para um disco com pelo menos 400 GB livres para o build completo (ou ~30 GB com `--stages check,shaders,runtime`); o estágio `shaders` é o mais demorado e usa metade das threads da CPU por padrão (ajustável com `--jobs`). -- **`--wav`**: fica desativado por padrão porque WAV PCM de 16 bits é várias vezes maior que Ogg Opus; quando ativado, decodifica os streams Ogg Opus para `work\assets\audio\wav` e pula arquivos WAV já existentes ao retomar um build. - -### Diagnóstico do Vulkan no Linux - -Com CMake 3.24+, um compilador C++20, os cabeçalhos de desenvolvimento e o carregador do Vulkan instalados, -rode na raiz do repositório: - -```sh -cmake -S runtime -B runtime/build/linux -cmake --build runtime/build/linux --parallel -./runtime/build/linux/vk_pipeline_check /caminho/para/spirv -``` - -Passe a pasta que contém `index.json` e os shaders SPIR-V traduzidos. O estágio `pipelines` de `make_game.py` -usa esse verificador em `runtime/build/linux` ou `runtime/build`. Se ainda não existir, o script o compila -antes de iniciar os estágios. - -### Runtime no Linux com Wine ou Proton - -No Linux, `make_game.py` pode compilar o runtime Windows em `runtime/build/windows` com `clang-cl`, -`lld-link` e o SDK Windows com o CRT do MSVC instalado via [xwin](https://github.com/Jake-Shadle/xwin). -O script procura o SDK em `XWIN_DIR` ou `~/.local/share/xwin-sdk`. Consulte o -[guia de configuração](../../testing.md#the-windows-runtime-on-linux-under-wine-or-proton) para instalar -as ferramentas e conferir as versões do LLVM conhecidas por causar problemas. Sem essas dependências, -o estágio `runtime` fica fora da execução padrão no Linux. - -Você também pode reutilizar um build Windows já extraído, como o artefato `runtime-windows` do workflow -Runtime. Passe a pasta que contém `gta6rt.exe` e `gta6rt_tls_host.dll`: - -```sh -python3 -I make_game.py --runtime-build ~/Downloads/runtime-windows -``` - -Nos dois casos, o script copia os arquivos do runtime para o diretório indicado por `--out` e gera `gta6rt.sh` nessa pasta. -O script inicia o runtime com `wine` por padrão. Para usar o Proton, aponte `WINE` para o `files/bin/wine` -da instalação. No Windows, `--runtime-build` também permite reutilizar um build existente. - -## Problemas comuns - -- **Baixou pelo botão "Download ZIP" do GitHub**: o ZIP não inclui o submódulo `third_party/rpf9-explorer`. Use `git clone --recursive` ou execute `git submodule update --init --recursive` dentro da pasta do repositório. -- **`llvm-mc` recusa `gfx1013` / AMDGPU**: você provavelmente está com o instalador oficial do LLVM para Windows. Siga um dos passos de configuração do LLVM acima. -- **Erro de `D3D12_ROOT_SIGNATURE_DESC2` ao compilar o runtime**: atualize o Windows SDK para `10.0.26100` ou mais recente pelo Visual Studio Installer ou `winget install Microsoft.WindowsSDK.10.0.26100`, apague a pasta de build e reconfigure. -- **Falha por falta de espaço no drive `C:`**: passe `--work "D:\leonida-work"` para mover os arquivos - temporários ou siga o [build com pouco espaço em disco](#build-com-pouco-espaço-em-disco). - -## Como contribuir e rodar os testes de GPU - -1. Consulte os PRs abertos e a [issue de coordenação][coord] para evitar trabalho duplicado. Reserve a - tarefa com `claiming: ` ou com uma descrição de uma linha, se ainda não houver ID. -2. Rode os testes relevantes com entradas sintéticas. Por exemplo, para testar o verificador de manifestos, - execute `python -I tests/test_manifest_verifier.py` na raiz do repositório. -3. No PR, inclua o ID da tarefa, descreva o que testou e informe a GPU e o driver se rodou testes de GPU. - Confira as regras em [`CONTRIBUTING.md`](../../../CONTRIBUTING.md). Se usou assistência de IA, indique - isso no PR, conforme [`AGENTS.md`](../../../AGENTS.md). - -O [guia de testes em GPU](../../testing.md) mostra como executar os testes sem arquivos do jogo. -Publique os resultados de GPU na [issue #166](https://github.com/ItsNotRexed/Leonida/issues/166). - -[coord]: https://github.com/ItsNotRexed/Leonida/issues?q=is%3Aissue%20is%3Aopen%20in%3Atitle%20%22Coordinating%20who%20works%20on%20what%22 diff --git a/docs/i18n/pt-PT/quickstart.md b/docs/i18n/pt-PT/quickstart.md deleted file mode 100644 index db9549c86..000000000 --- a/docs/i18n/pt-PT/quickstart.md +++ /dev/null @@ -1,183 +0,0 @@ -# Leonida — Guia rápido (`pt-PT`) - -> [!NOTE] -> A documentação em inglês ([`README.md`](../../../README.md), [`CONTRIBUTING.md`](../../../CONTRIBUTING.md) e -> [`docs/README.md`](../../README.md)) é a **referência oficial**. Este guia reúne apenas instruções estáveis de -> configuração e compilação (sincronizado com o commit `867d922f`). Para o estado diário do projeto, consulte o -> [`README.md`](../../../README.md). - -## O que é o Leonida - -O Leonida é um projeto de recompilação estática do Grand Theft Auto VI (Xbox Series) para correr nativamente no -Windows, construído **no seu PC a partir da sua própria cópia**. Os programas RDNA2 da consola são traduzidos para -SPIR-V (Vulkan), os recursos são lidos diretamente do seu pacote e o software de sistema da consola é -reimplementado em *shims*. Tudo isto acontece **no seu PC, com a sua própria cópia do jogo**. - -> [!IMPORTANT] -> Este repositório **não contém o jogo, chaves nem executável**, e não explica como os obter. Não descriptografa -> nem contorna proteções. Tudo o que a compilação gera (shaders traduzidos, recursos extraídos, a pasta de -> execução e os seus saves) vem da sua cópia e **deve ficar apenas no seu PC**. Nunca anexe nem partilhe esses -> ficheiros em issues ou pull requests (veja [`CONTRIBUTING.md`](../../../CONTRIBUTING.md)). - -Ainda não é possível jogar o jogo em nenhuma plataforma; consulte a secção *Project status* do README inglês. - -## Pré-requisitos - -- **A sua própria cópia** do pacote Xbox Series, versão `1.0.2.1` (pasta com `MicrosoftGame.Config` e os ficheiros - `.rpf` legíveis em disco). -- **Windows 10/11 x64**, com cerca de **400 GB** livres para ficheiros de trabalho. Uma única exportação de - recursos ocupou cerca de 337 GB antes da etapa de áudio. `--work` permite colocá-los noutra unidade. -- [Python 3.12+](https://www.python.org/downloads/) (marque *“Add python.exe to PATH”*). -- [.NET 8 SDK](https://dotnet.microsoft.com/download/dotnet/8.0). -- [Vulkan SDK](https://vulkan.lunarg.com/) (`spirv-as` e `spirv-val`). -- [LLVM 21+](https://github.com/llvm/llvm-project/releases) com o **alvo AMDGPU** para `llvm-mc`. O instalador - oficial do LLVM para Windows não inclui esse alvo. No Windows, `scripts\build_llvm_mc.ps1` compila um - `llvm-mc.exe` nativo com o alvo e define `LLVM_MC` (demora cerca de 20–40 minutos e precisa do git e das - ferramentas C++ do Visual Studio). Outra opção é instalar `llvm-21` no WSL e definir - `LLVM_MC="wsl -d Ubuntu -e /usr/lib/llvm-21/bin/llvm-mc"`. No Linux, basta ter `llvm-mc` no `PATH`. - Consulte [`docs/design.md`](../../design.md#disassembling-shaders). -- **Visual Studio 2022** com *Desenvolvimento para desktop com C++* e **Windows SDK 10.0.26100 ou mais recente** - (a etapa `runtime` usa assinaturas de root 1.2). -- [ffmpeg](https://ffmpeg.org/download.html) no `PATH` *(opcional: descodifica streams XMA2; obrigatório com - `--wav`)*. - -**Este PC chega?** O [Can I Run Leonida](https://assttro.github.io/can-i-run-leonida/) é um verificador leve no -navegador que compara o teu PC com perfis de referência. É uma estimativa aproximada, não um benchmark. - -**Pouco espaço em disco:** os ~400 GB são para a compilação completa. Para *executar* o port, -`--stages check,shaders,runtime` precisa de cerca de 30 GB; a etapa `assets` (~370 GB) serve apenas para as -ferramentas de extração e `--wav` acrescenta várias vezes o tamanho do Ogg Opus. `--work` e `--out` podem ficar -noutra unidade. O runtime mapeia o pacote no local, pelo que uma unidade só de leitura exige -`gta6rt --overlay ` — `--overlay` é uma opção do `gta6rt`, não do `make_game.py`. Mantenha os -ficheiros `.s` em `work/shaders/dxbc/disasm`: a execução seguinte compara-os com `disasm.done` e refaz os que -faltam. Uma pasta `disasm` que seja uma ligação simbólica é recusada quando a etapa precisa de a limpar. - -## Como compilar - -### Modo simples (Windows) - -1. Instale os pré-requisitos acima. -2. Clone o repositório **com o submódulo**: - ```powershell - git clone --recursive https://github.com/ItsNotRexed/Leonida - ``` - Um *Download ZIP* do GitHub não inclui `third_party/rpf9-explorer`. -3. Abra a pasta `Leonida` e faça duplo clique em **`Build.bat`**. - -O script procura a sua cópia do jogo em Downloads, Ambiente de Trabalho, Documentos (incluindo OneDrive), Games, -pasta pessoal e raiz de cada unidade, até dois níveis. Reconhece a versão por alguns tamanhos de ficheiro, sem -ler nada de grande. Se encontrar mais do que uma cópia, pergunta qual usar; se não encontrar nenhuma, pede o -caminho. Antes de começar, verifica os pré-requisitos e o espaço livre e apresenta tudo o que falta de uma vez. -O resultado vai para `Documents\Leonida`. Uma compilação interrompida continua onde ficou. - -### Pelo terminal - -```powershell -python -I make_game.py --find # lista as cópias encontradas neste PC -python -I make_game.py --pick # escolhe a pasta do jogo numa janela de diálogo -python -I make_game.py --check # verifica a cópia sem compilar -python -I make_game.py --check --full-check # compara também o SHA-256 de cada ficheiro (lento) -python -I make_game.py --game "D:\caminho\do\pacote" --out "D:\Games\Leonida" --work "E:\leonida-work" -python -I make_game.py --stages shaders,assets # executa apenas as etapas escolhidas -python -I make_game.py --game "D:\caminho\do\pacote" --wav # descodifica também Opus para PCM WAV (grande) -python -I make_game.py --wave64-emulate off # auto (predefinição), on ou off; veja abaixo -``` - -As etapas executam-se nesta ordem: `check` primeiro; depois `shaders`, `assets` e `runtime` em conjunto quando -selecionadas; `pipelines` começa quando os shaders traduzidos estão prontos e cria cada um deles no controlador -GPU, guardando a cache em `pipeline_cache.bin` dentro de `--out` (o runtime ainda não a carrega). A tradução de -shaders é a etapa CPU mais longa e usa metade dos processadores por predefinição (`--jobs`). Num terminal -interativo, um ecrã de configuração permite ajustar o número de processos e a sobreposição de etapas, com uma -vista de logs por etapa (`1`–`4` / `Tab`); use `--no-tui` (ou redirecione a saída) para o console simples. -Os logs completos ficam em `work/logs/`. - -- **`--wave64-emulate`**: traduz shaders compute e mesh wave64 para serem exatos em qualquer tamanho de subgrupo. - NVIDIA e Intel têm subgrupos de 32 lanes e precisam disso. O modo `auto` consulta `vulkaninfo` e ativa a - emulação se alguma GPU não tiver subgrupos de 64 lanes ou o tamanho for desconhecido; verifica também se a GPU - do runtime suporta compute e mesh em 64 lanes (com `--mesh-compute`, basta compute). No controlador Windows da - AMD, `auto` usa wave64 nativo em RDNA1/RDNA2 quando a GPU do runtime o suporta, mesmo que outra GPU seja de - 32 lanes ou `vulkaninfo` não esteja disponível. O modo escolhido fica guardado junto dos shaders; alterá-lo - obriga a traduzir de novo. Veja *Wave64 emulation* em [`docs/design.md`](../../design.md). -- **Flags de fallback do tradutor**: `--no-float-controls` (remove `SignedZeroInfNanPreserve`), - `--bary-fallback` (lê baricêntricas de um input interpolado sem `VK_KHR_fragment_shader_barycentric`), - `--texel-offset-fallback` (incorpora offsets `image_sample*_o` na coordenada sem `VK_KHR_maintenance8`) e - `--mesh-compute` (mesh shaders como compute sem `VK_EXT_mesh_shader`). São repassadas ao tradutor, guardadas - com os shaders e alterá-las retraduz os shaders. Cada uma está documentada em - [`docs/design.md`](../../design.md). -- **`--wav`**: desativado por predefinição porque WAV PCM de 16 bits é várias vezes maior que Ogg Opus. Depois - da etapa de áudio, descodifica os streams para `work\assets\audio\wav`; ao retomar, os ficheiros já existentes - são ignorados. - -### Diagnóstico do Vulkan no Linux - -Com CMake 3.24+, um compilador C++20, cabeçalhos de desenvolvimento e o carregador Vulkan instalados: - -```sh -cmake -S runtime -B runtime/build/linux -cmake --build runtime/build/linux --parallel -./runtime/build/linux/vk_pipeline_check /caminho/para/spirv -``` - -Passe a pasta que contém `index.json` e os ficheiros SPIR-V traduzidos. No Linux, `make_game.py` também corre; -a etapa `pipelines` usa o `vk_pipeline_check` acima e compila-o se ainda não existir. - -### Runtime no Linux com Wine ou Proton - -O loader é um programa Windows e corre sob Wine ou Proton. No Linux, a etapa `runtime` compila-o de forma -cruzada para `runtime/build/windows` com clang-cl e lld-link contra o CRT do MSVC e o Windows SDK que o -[xwin](https://github.com/Jake-Shadle/xwin) organiza em `XWIN_DIR` ou `~/.local/share/xwin-sdk`. Sem isso, a -etapa fica fora da execução predefinida. Também pode reutilizar um build Windows existente: - -```sh -python3 -I make_game.py --runtime-build ~/Downloads/runtime-windows -``` - -Em ambos os casos, o script copia `gta6rt.exe` e `gta6rt_tls_host.dll` para `--out` e cria `gta6rt.sh`, que -inicia o runtime com `wine` (ou com o Wine indicado por `WINE`). Use `/gta6rt.sh --dry-run` para inspecionar -as importações, `--init` para verificar callbacks TLS e inicialização de DLL, e `--run` para o arranque. -Com `LEONIDA_D3D12=vulkan`, o runtime encontra os shaders em `/shaders/spirv` através de `shader_path.txt`; -`LEONIDA_SHADERS` permite escolher outra pasta. Consulte -[`docs/testing.md`](../../testing.md#the-windows-runtime-on-linux-under-wine-or-proton). - -## Como funciona - -| Parte | O que faz | Onde | -|---|---|---| -| Verificação de versão | Nome, tamanho e SHA-256 de cada ficheiro do pacote para cada versão suportada | `game/`, `make_game.py` | -| Pipeline de shaders | Extrai contentores DXBC sem a tabela de conteúdos encriptada; desempacota o programa RDNA2 `XBCH` → `FSSM`; desmonta com LLVM (`gfx1013`) e traduz para SPIR-V | `tools/shader_carve.py`, `fssm_unpack.py`, `shader_disasm.py`, `rdna2spirv.py` | -| Exportação de recursos | Encontra recursos validados em arquivos RPF9 e nos pools `.ttpf` soltos | `tools/rpf9dump` | -| Runtime | Mapeia a imagem PE, resolve importações para *shims* (GDK, XMem, `d3d12_xs`) | `runtime/` | -| Ferramentas de investigação | Inspeção PE/RTTI, extração, sondas de mosaicos, harnesses GPU | `tools/`, `runtime/test/` | -| Painel de progresso | Uma página offline com o que passa e o que bloqueia o próximo passo, gerada a partir de testes e das próprias tabelas da documentação | `tools/progress_dashboard.py` | - -O contrato do tradutor e todas as notas de formato estão em [`docs/design.md`](../../design.md); as notas de -formato, recursos, runtime e validação estão indexadas em [`docs/README.md`](../../README.md). O plano D3D12 -está em [`docs/d3d12_vulkan.md`](../../d3d12_vulkan.md), os formatos de áudio em -[`docs/audio.md`](../../audio.md) e as referências relacionadas em -[`docs/related_projects.md`](../../related_projects.md). - -## Problemas comuns - -- **Usou o botão “Download ZIP” do GitHub**: o ZIP não inclui o submódulo `third_party/rpf9-explorer`. Use - `git clone --recursive` ou `git submodule update --init --recursive`. -- **`llvm-mc` recusa `gfx1013` / AMDGPU**: está provavelmente a usar o instalador oficial do LLVM para Windows. - Siga uma das opções de `LLVM_MC` acima. -- **Erro `D3D12_ROOT_SIGNATURE_DESC2` ao compilar o runtime**: atualize o Windows SDK para `10.0.26100` ou - mais recente, apague a pasta de build e reconfigure. -- **Falta de espaço na unidade `C:`**: passe `--work "D:\leonida-work"` ou use as etapas reduzidas - `--stages check,shaders,runtime`. - -## Como contribuir e executar testes GPU - -1. Consulte os PRs abertos e a [issue de coordenação][coord] para evitar trabalho duplicado. Reserve a tarefa - com `claiming: ` (ou com uma descrição de uma linha, se ainda não houver ID). -2. Execute os testes relevantes com entradas sintéticas. Por exemplo, na raiz do repositório: - `python -I tests/test_manifest_verifier.py`. -3. No PR, indique o ID da tarefa, o que testou e a GPU/controlador se executou testes GPU. Siga as regras em - [`CONTRIBUTING.md`](../../../CONTRIBUTING.md) e indique o uso de IA conforme - [`AGENTS.md`](../../../AGENTS.md). - -O [guia de testes GPU](../../testing.md) explica como executar os testes sem ficheiros do jogo. Publique os -resultados na [issue #166](https://github.com/ItsNotRexed/Leonida/issues/166). - -[coord]: https://github.com/ItsNotRexed/Leonida/issues?q=is%3Aissue%20is%3Aopen%20in%3Atitle%20%22Coordinating%20who%20works%20on%20what%22 diff --git a/docs/i18n/ru/quickstart.md b/docs/i18n/ru/quickstart.md deleted file mode 100644 index 818e47fe4..000000000 --- a/docs/i18n/ru/quickstart.md +++ /dev/null @@ -1,198 +0,0 @@ -# Быстрый старт Leonida (`ru`) - -> [!NOTE] -> Главный источник: английская документация ([`README.md`](../../../README.md), [`CONTRIBUTING.md`](../../../CONTRIBUTING.md) -> и [`docs/README.md`](../../README.md)). Этот гайд покрывает только стабильные шаги установки и сборки -> (сверен с коммитом `aa2988cc`). Текущее состояние проекта меняется каждый день, его смотрите в -> [`README.md`](../../../README.md). - -## Что такое Leonida - -Leonida это проект статической рекомпиляции Grand Theft Auto VI (Xbox Series): игра запускается нативно на -Windows. Процессор консоли x86-64, как у ПК, поэтому код игры загружается и работает напрямую, а системное ПО -консоли реализовано заново. Готовые GPU-программы RDNA2 переводятся в SPIR-V для Vulkan. Модели, текстуры и звук -читаются из вашего пакета. Всё это происходит **на вашем ПК, из вашей копии игры**. - -> [!IMPORTANT] -> В репозитории **нет ни игры, ни ключей, ни исполняемого файла**, и он не объясняет, где их взять. Нужна своя -> копия, файлы которой уже читаются с диска. Ничто в проекте не расшифровывает данные и не обходит защиты. Всё, -> что создаёт сборка (переведённые шейдеры, извлечённые ресурсы, рабочая папка и ваши сохранения), берётся из -> вашей игры и **остаётся на вашем ПК**. Не выкладывайте эти файлы (см. [`CONTRIBUTING.md`](../../../CONTRIBUTING.md)). - -Проект на раннем этапе: **игра пока не запускается**. - -## Платформы - -Ни на одной платформе пока ничего не играбельно. Что где работает сегодня: - -- **Windows**: всё (`make_game.py`, инструменты и runtime `gta6rt` со слоем D3D12 → Vulkan и его тестами). -- **Linux**: переводчик, инструменты ресурсов и инструменты GPU-тестов Vulkan собираются и работают нативно - (проверено на RADV и NVIDIA). Runtime это код для Windows: он кросс-собирается через clang-cl и xwin, а его тесты - идут под Wine или Proton. Игра должна запускаться так же (#217). -- **macOS (Apple Silicon)**: инструменты на Python и инструменты тестов Vulkan работают нативно, на MoltenVK - (Homebrew) или KosmicKrisp. Runtime идёт под Wine, как на Linux. Известные ограничения: нет этапа geometry и - `VK_EXT_mesh_shader`, подгруппы шириной 32 (шейдеры wave64 эмулируются) и работа MoltenVK с числами с плавающей - точкой; все они перечислены в [`docs/testing.md`](../../testing.md). -- **AMD RDNA1 (RX 5000)**: поддерживаемая цель, близкая к RDNA2 консоли; её подгруппы шириной 64 выполняют - шейдеры wave64 нативно. - -Результаты GPU со всех платформ собираются в [issue #166](https://github.com/ItsNotRexed/Leonida/issues/166). - -## Что нужно - -- **Своя копия** пакета Xbox Series версии `1.0.2.1`: папка, где `MicrosoftGame.Config` и архивы `.rpf` лежат - обычными файлами. -- **Windows 10/11 x64** и примерно **350 ГБ** свободного места под рабочие файлы. Их можно перенести на другой - диск через `--work`. -- [Python 3.12+](https://www.python.org/downloads/) (при установке отметьте *«Add python.exe to PATH»*). -- [.NET 8 SDK](https://dotnet.microsoft.com/download/dotnet/8.0). -- [Vulkan SDK](https://vulkan.lunarg.com/) для `spirv-as` и `spirv-val`. -- [LLVM 21+](https://github.com/llvm/llvm-project/releases) с **целью AMDGPU** для `llvm-mc`: - - в официальной сборке LLVM для Windows цели AMDGPU нет; - - на Windows `scripts\build_llvm_mc.ps1` собирает свой `llvm-mc.exe` с этой целью (без WSL, нужны `git` и - инструменты C++ из Visual Studio ниже) и прописывает `LLVM_MC`; после этого откройте новый терминал, чтобы - переменная подхватилась. Сборка занимает 20-40 минут; - - быстрее, если вы пользуетесь [conda](https://docs.conda.io/): `conda install -c conda-forge llvm-tools` (в её - сборке для Windows цель AMDGPU есть), затем укажите в `LLVM_MC` полный путь к установленному `llvm-mc.exe` - (`where.exe llvm-mc` покажет его в активированном окружении; в PowerShell команда `where` без `.exe` — это - `Where-Object`); - - если ставите `llvm-21` в WSL, передайте `LLVM_MC` целой командой в той же сессии PowerShell, откуда - запускаете `make_game.py`: - - ```powershell - $env:LLVM_MC = 'wsl -d Ubuntu -e /usr/lib/llvm-21/bin/llvm-mc' - ``` - - Подробности в [`docs/design.md`](../../design.md#disassembling-shaders); - - на Linux достаточно `llvm-mc` в `PATH`. -- **Visual Studio 2022** с рабочей нагрузкой *«Разработка классических приложений на C++»* и **Windows SDK - `10.0.26100` или новее**: они нужны этапу `runtime`, который использует root signatures версии 1.2, а в старых - SDK их нет. -- [ffmpeg](https://ffmpeg.org/download.html) в `PATH` *(по желанию: декодирует потоки XMA2, обязателен для `--wav`)*. - -## Как собрать - -### Простой способ (Windows) - -1. Установите всё из списка выше. -2. Склонируйте проект **вместе с подмодулем**: - ```powershell - git clone --recursive https://github.com/ItsNotRexed/Leonida - ``` - Кнопка «Download ZIP» на GitHub оставляет за бортом `third_party/rpf9-explorer`. Сборка подтянет его сама, - если установлен `git`, иначе скажет, что сделать. -3. Запустите **`Build.bat`** двойным щелчком. - -Скрипт сам находит копию игры: смотрит папки «Загрузки», рабочий стол, «Документы» (в том числе когда их хранит -OneDrive), `Games`, домашнюю папку и корень каждого диска, на два уровня вглубь. Версию он определяет по -размерам нескольких файлов, не читая больших данных. Если копий несколько, спросит, какую брать; -если ни одной, попросит вставить путь к папке. Перед стартом он проверит, что всё из списка установлено и места -хватает, и покажет все недостающие пункты разом. Результат пишется в `Documents\Leonida`. Прерванная -сборка продолжается с того места, где встала. - -### Мало места на диске - -Объём, указанный выше, нужен для полной сборки. Чтобы *запустить* порт, `--stages check,shaders,runtime` хватает -примерно 30 ГБ; этап `assets`, на который приходится почти всё остальное, нужен только инструментам ресурсов, а -`--wav` добавляет ещё в несколько раз больше, чем занимает Ogg Opus. `--work` и `--out` можно вынести на другой диск. Runtime читает пакет на месте, поэтому для -диска только для чтения нужен `gta6rt --overlay <папка с правом записи>` (это флаг `gta6rt`, а не `make_game.py`). -Не удаляйте файлы `.s` в `work/shaders/dxbc/disasm`: без них и без `work/shaders/spirv/index.json` этап `shaders` -может выглядеть завершённым с нулём шейдеров. - -### Из терминала (`make_game.py`) - -```powershell -python -I make_game.py --find # какие копии нашлись на этом ПК -python -I make_game.py --pick # выбрать папку игры в диалоге -python -I make_game.py --check # проверить копию, ничего не собирать -python -I make_game.py --check --full-check # ещё и сравнить SHA-256 каждого файла (долго) -python -I make_game.py --game "D:\путь\к\пакету" --out "D:\Games\Leonida" --work "E:\leonida-work" -python -I make_game.py --stages shaders,assets # только часть этапов -python -I make_game.py --game "D:\путь\к\пакету" --wav # ещё и Opus в PCM WAV (много места) -python -I make_game.py --wave64-emulate off # auto (по умолчанию), on или off -``` - -Этапы идут в таком порядке: `check`, `shaders`, `assets`, `runtime`, `pipelines`. Последний создаёт все -переведённые шейдеры на драйвере вашей видеокарты, проверяет, что они компилируются, сообщает о пропущенных и -сохраняет кеш конвейеров в `pipeline_cache.bin` в `--out`. Runtime этот кеш пока не загружает, так что первую -загрузку он не ускоряет. Перевод шейдеров самый долгий: он выполняется в `--jobs` процессов (по умолчанию -половина потоков процессора). - -- **`--wave64-emulate`**: переводить ли compute- и mesh-шейдеры wave64 так, чтобы они работали точно при любом - размере подгруппы (раздел «Wave64 emulation» в [`docs/design.md`](../../design.md)). У NVIDIA и Intel подгруппы - шириной 32, им это нужно. Режим `auto` спрашивает `vulkaninfo` из Vulkan SDK и включает эмуляцию в трёх - случаях: не все видеокарты сообщают подгруппы шириной 64, ответ получить не удалось, или карта для runtime не - умеет выполнять compute- и mesh-шейдеры на 64 (с `--mesh-compute` нужна только поддержка compute). На драйвере - AMD для Windows `auto` берёт нативный wave64 на RDNA1 и RDNA2, если карта для runtime его поддерживает, даже - когда другая карта шириной 32 или `vulkaninfo` недоступен: этот драйвер может падать на эмулированном коде LDS - (#857). Режим сохраняется рядом с переведёнными шейдерами, и его смена запускает перевод заново. При `auto` - обычно можно переиспользовать уже эмулированные шейдеры; обход для драйвера AMD пересобирает их в нативном - режиме. -- **`--work`**: выберите диск, где свободно хотя бы 350 ГБ. -- **`--wav`**: по умолчанию выключен, потому что 16-битный PCM WAV в несколько раз больше Ogg Opus. Флаг - декодирует перепакованные потоки Ogg Opus в `work\assets\audio\wav` после этапа аудио; готовые WAV при - продолжении сборки пропускаются. - -Четыре запасных флага передаются переводчику так же, сохраняются рядом с шейдерами и запускают перевод заново -при изменении: `--no-float-controls` (убрать `SignedZeroInfNanPreserve` для устройств, чья проверка конвейеров -пропускает шейдер без `shaderSignedZeroInfNanPreserveFloat32`), `--bary-fallback` (читать сырые барицентрики из -интерполированного входа, для устройств без `VK_KHR_fragment_shader_barycentric`), `--texel-offset-fallback` -(вносить смещения `image_sample*_o` в координату, для устройств без `VK_KHR_maintenance8`) и `--mesh-compute` -(mesh-шейдеры как compute, для устройств без `VK_EXT_mesh_shader`). Каждый описан в -[`docs/design.md`](../../design.md). - -Сборка запоминает, чем сделаны результаты: команду и версию `llvm-mc`, исходники переводчика и декодер ресурсов -(коммит `third_party/rpf9-explorer` и исходники `tools/rpf9dump`). Если что-то из этого меняется, заново -выполняется только нужная часть: дизассемблирование, перевод или экспорт моделей и текстур архива. Старые рабочие -папки без такой записи один раз проходят эти шаги повторно после обновления. - -### Linux и Wine/Proton - -`make_game.py` работает и на Linux. Этап `pipelines` использует `vk_pipeline_check` (CMake 3.24+, компилятор -C++20 и заголовки Vulkan; собирается в `runtime/build/linux`, а если его нет, скрипт соберёт его сам до остальной -работы). Загрузчик (`gta6rt.exe`) это программа для Windows, поэтому на Linux она -идёт под Wine или Proton. Этап `runtime` на Linux кросс-собирается в `runtime/build/windows` через `clang-cl` и -`lld-link` -(LLVM 19+, но не 22.1.7 и не 22.1.8, см. [`docs/testing.md`](../../testing.md#known-problems)) против CRT от MSVC и -Windows SDK, которые раскладывает [xwin](https://github.com/Jake-Shadle/xwin) в `XWIN_DIR` или -`~/.local/share/xwin-sdk`. Разовый вызов `xwin` есть в -[`docs/testing.md`](../../testing.md#the-windows-runtime-on-linux-under-wine-or-proton). Если этих инструментов нет, -этап выпадает из списка по умолчанию, а при явном запросе скрипт сразу перечислит, чего не хватает. Готовая -сборка для Windows тоже подойдёт, например артефакт `runtime-windows` из CI: - -```sh -python3 -I make_game.py --runtime-build ~/Downloads/runtime-windows -``` - -В обоих случаях `gta6rt.exe` и `gta6rt_tls_host.dll` копируются в `--out`, а рядом пишется `gta6rt.sh`, который -запускает `gta6rt.exe` через `wine` или через Wine из переменной `WINE` (для Proton это его `files/bin/wine`). На -Windows этот же флаг пропускает сборку. - -## Частые проблемы - -- **Скачали ZIP с GitHub**: в архиве нет подмодуля `third_party/rpf9-explorer`. Используйте - `git clone --recursive` или выполните `git submodule update --init --recursive` в папке репозитория. -- **`llvm-mc` не знает `gfx1013` или цель AMDGPU**: скорее всего установлен официальный LLVM для Windows. - Соберите свой через `scripts\build_llvm_mc.ps1` или укажите в `LLVM_MC` путь к `llvm-mc` из WSL (`llvm-21`). -- **CMake пишет «needs the Windows SDK 10.0.26100 or newer»** или MSVC не находит `Desc_1_2` в - `D3D12_VERSIONED_ROOT_SIGNATURE_DESC`: поставьте Windows SDK `10.0.26100` или новее через Visual Studio - Installer либо `winget install Microsoft.WindowsSDK.10.0.26100`, удалите `runtime/build` и настройте заново. -- **Кончилось место на `C:`**: передайте `--work "D:\leonida-work"`, чтобы рабочие файлы легли на другой диск. -- **Windows не даёт запустить только что собранные тестовые программы** («An Application Control policy has - blocked this file»): так работает Smart App Control в Windows 11, подробности в - [`docs/testing.md`](../../testing.md#known-problems). - -## Как помочь и прогнать тесты на видеокарте - -1. Посмотрите открытые pull request и [issue координации][coord], чтобы не делать ту же работу дважды. Заявите - задачу строкой `claiming: ` или одним предложением описания, если ID ещё нет. -2. Прогоните нужные тесты на синтетических входных данных. Например, проверку манифеста: - `python -I tests/test_manifest_verifier.py` из корня репозитория. -3. В pull request укажите ID задачи и то, что вы проверили, а если запускали тесты на видеокарте, ещё её модель и - версию драйвера. Отметьте, помогал ли вам ИИ. Все правила в [`CONTRIBUTING.md`](../../../CONTRIBUTING.md). - -[Руководство по тестам на видеокарте](../../testing.md) объясняет, как обойтись без файлов игры. Результаты -складывают в [issue #166](https://github.com/ItsNotRexed/Leonida/issues/166), по одному комментарию на карту и -драйвер. - -[coord]: https://github.com/ItsNotRexed/Leonida/issues?q=is%3Aissue%20is%3Aopen%20in%3Atitle%20%22Coordinating%20who%20works%20on%20what%22 diff --git a/docs/i18n/tr/quickstart.md b/docs/i18n/tr/quickstart.md deleted file mode 100644 index ecdc45462..000000000 --- a/docs/i18n/tr/quickstart.md +++ /dev/null @@ -1,133 +0,0 @@ -# Leonida — Hızlı Başlangıç (`tr`) - -> [!NOTE] -> İngilizce dokümantasyon ([`README.md`](../../../README.md), [`CONTRIBUTING.md`](../../../CONTRIBUTING.md) ve -> [`docs/README.md`](../../README.md)) **yetkili kaynaktır**. Bu rehber yalnızca kararlı kurulum ve derleme -> yönergelerini kapsar (`561b65a` commit'ine göre eşitlenmiştir). Günlük değişen proje durumu için -> [`README.md`](../../../README.md) dosyasına bakın. - -## Leonida Nedir? - -Leonida, Grand Theft Auto VI'nın Xbox Series sürümünü Windows üzerinde yerel olarak çalıştırmayı hedefleyen statik -yeniden derleme (recompilation) projesidir. Port, **kendi bilgisayarınızda ve kendi oyun kopyanızdan** oluşturulur. -Konsolun önceden derlenmiş RDNA2 GPU shader'ları Vulkan için SPIR-V'ye çevrilir, oyun varlıkları doğrudan kendi -paketinizden okunur ve konsolun sistem yazılımları shim katmanlarıyla yeniden uygulanır. - -> [!IMPORTANT] -> Bu depo **oyunu, şifre çözme anahtarlarını veya çalıştırılabilir dosyayı içermez** ve bunların nasıl edinileceğini -> anlatmaz. Dosyaları diskte zaten okunabilir durumda olan kendi kopyanız gerekir. Buradaki hiçbir araç şifre çözmez -> veya herhangi bir korumayı aşmaz. Derlemenin ürettiği tüm dosyalar (çevrilmiş shader'lar, çıkarılan varlıklar, -> çalışma klasörü ve kayıtlar) kendi kopyanızdan gelir ve **yalnızca bilgisayarınızda kalmalıdır**; bunları asla issue -> veya pull request'lerde paylaşmayın (bkz. [`CONTRIBUTING.md`](../../../CONTRIBUTING.md)). - -Proje henüz erken aşamadadır: **oyun şu an açılmıyor**. - -## Gereksinimler - -- **Kendi Xbox Series paket kopyanız**, sürüm `1.0.2.1` (`MicrosoftGame.Config` dosyasını ve `.rpf` arşivlerini diskte - düz dosyalar olarak barındıran klasör). -- **Windows 10/11 x64** ve çalışma dosyaları için yaklaşık **400 GB boş disk alanı** (`--work` ile başka bir diske - yönlendirilebilir). Bu rakam tam derleme içindir: yalnızca çalıştırmak için `--stages check,shaders,runtime` - yaklaşık 30 GB ister, `assets` aşaması ise yaklaşık 370 GB. -- [Python 3.12+](https://www.python.org/downloads/) (kurulumda *"Add python.exe to PATH"* seçeneğini işaretleyin). -- [.NET 8 SDK](https://dotnet.microsoft.com/download/dotnet/8.0). -- [Vulkan SDK](https://vulkan.lunarg.com/) (`spirv-as`, `spirv-val` ve `vulkaninfo` için). -- **AMDGPU hedefli** [LLVM 21+](https://github.com/llvm/llvm-project/releases) (`llvm-mc`): - - Resmi Windows LLVM kurulumu AMDGPU hedefini **içermez**. - - AMDGPU destekli yerel `llvm-mc.exe` derlemek için depo kök dizininde PowerShell'den `.\scripts\build_llvm_mc.ps1` - betiğini çalıştırın (`git` ve aşağıdaki Visual Studio C++ araçları gerekir). Betik kullanıcınız için `LLVM_MC` - ortam değişkenini ayarlar; geçerli olması için yeni bir terminal açın. - - Daha hızlı bir yol: [conda](https://docs.conda.io/) kullanıyorsanız `conda install -c conda-forge llvm-tools` - (Windows derlemesi AMDGPU hedefini içerir; [`docs/testing.md`](../../testing.md) 23.1.6 sürümünü kullandı), ardından - `LLVM_MC` değişkenini kurduğu `llvm-mc.exe` dosyasının tam yoluna ayarlayın (ortam etkinleştirildikten sonra - `where.exe llvm-mc` yolunu gösterir; PowerShell'de çıplak `where` komutu `Where-Object` demektir). - - Alternatif olarak WSL (Ubuntu) içinde `llvm-21` kurup `make_game.py` çalıştıracağınız PowerShell oturumunda - `LLVM_MC` değişkenini tam komut olarak ayarlayın: - - ```powershell - $env:LLVM_MC = 'wsl -d Ubuntu -e /usr/lib/llvm-21/bin/llvm-mc' - ``` - - Ayrıntılar için [`docs/design.md`](../../design.md#disassembling-shaders) bölümüne bakın. - - Linux üzerinde `PATH` içinde `llvm-mc` bulunması yeterlidir. -- **Visual Studio 2022** (*C++ ile masaüstü geliştirme* iş yükü) ve **Windows SDK `10.0.26100` veya üzeri** (`runtime` - aşaması için; sürüm 1.2 root signature yapıları daha eski SDK'larda yoktur). -- `PATH` içinde [ffmpeg](https://ffmpeg.org/download.html) *(isteğe bağlı: XMA2 ses akışlarını çözer; `--wav` için - gereklidir)*. - -## Nasıl Derlenir? - -### Kolay yöntem (Windows) - -1. Yukarıdaki gereksinimleri kurun. -2. Depoyu **alt modülüyle birlikte** klonlayın: - ```powershell - git clone --recursive https://github.com/ItsNotRexed/Leonida - ``` -3. **`Build.bat`** dosyasına çift tıklayın. - -Betik oyun kopyanızı kendisi arar (İndirilenler, Masaüstü, Belgeler, Games, kullanıcı klasörünüz ve her sürücünün kök -dizininden iki seviye derine kadar). Büyük dosyaları okumadan yalnızca birkaç dosya boyutundan sürümü tanır. Birden -fazla kopya bulursa hangisini kullanacağınızı, hiç bulamazsa klasör yolunu yapıştırmanızı ister. Başlamadan önce -gereksinimleri ve boş disk alanını denetleyip eksikleri tek seferde listeler. Çıktı `Documents\Leonida` klasörüne -yazılır; yarım kalan bir derleme kaldığı yerden devam eder. - -### Terminalden (`make_game.py`) - -```powershell -python -I make_game.py --find # bilgisayarda bulunan kopyaları listele -python -I make_game.py --pick # oyun klasörünü bir klasör penceresinde seç -python -I make_game.py --check # kopyayı doğrula, derleme yapma -python -I make_game.py --check --full-check # ayrıca her dosyanın SHA-256 özetini karşılaştır (yavaş) -python -I make_game.py --game "D:\paket\yolu" --out "D:\Games\Leonida" --work "E:\leonida-work" -python -I make_game.py --stages shaders,assets # yalnızca seçili aşamaları çalıştır -python -I make_game.py --game "D:\paket\yolu" --wav # Opus akışlarını ayrıca PCM WAV'a çöz (büyük boyut) -python -I make_game.py --wave64-emulate off # auto (varsayılan), on veya off -``` - -`check` aşaması her zaman ilk çalışır; ardından seçildiklerinde `shaders`, `assets` ve `runtime` birlikte çalışır (birbirlerine bağlı değildir). `pipelines` ise çevrilmiş shader'lar hazır olduğunda başlar. - -- **`--wave64-emulate`**: Wave64 compute ve mesh shader'larını her subgroup genişliğinde birebir çalışacak şekilde - çevirir. NVIDIA ve Intel GPU'lar 32 şeritli subgroup kullandığı için buna ihtiyaç duyar. Varsayılan `auto` modu - `vulkaninfo` çıktısına bakar ve tüm GPU'lar yerel 64 şeritli subgroup bildirmediği sürece emülasyonu otomatik açar. -- **`--work`**: Tam derleme için en az 400 GB boş alana sahip bir sürücü seçin (yalnızca çalıştırmak için yaklaşık - 30 GB, `assets` aşaması için yaklaşık 370 GB yeterlidir). En uzun adım shader çevirisidir ve varsayılan olarak - CPU iş parçacıklarının yarısını kullanır (`--jobs` ile değiştirilebilir). -- **`--wav`**: Varsayılan olarak kapalıdır; 16-bit PCM WAV dosyaları Ogg Opus'tan birkaç kat daha büyüktür. -- **Linux ve Wine/Proton**: `make_game.py` Linux'ta da çalışır. Yükleyici (`gta6rt.exe`) bir Windows programıdır ve - Wine veya Proton altında çalışır. Linux'ta `runtime` aşaması, `clang-cl` + `lld-link` (LLVM 19+) ve - [xwin](https://github.com/Jake-Shadle/xwin) (`XWIN_DIR` veya `~/.local/share/xwin-sdk`; tek seferlik kurulum için - bkz. [`docs/testing.md`](../../testing.md#the-windows-runtime-on-linux-under-wine-or-proton)) ile `runtime/build/windows` - içine çapraz derleme yapabilir ya da `--runtime-build ` ile önceden derlenmiş bir Windows runtime'ını - (`gta6rt.exe` ve `gta6rt_tls_host.dll`, örn. CI'daki `runtime-windows` paketi) doğrudan kopyalayabilir. Her iki durumda - da çıkış klasörüne `gta6rt.sh` başlatıcısını yazar (`wine` veya `WINE` ortam değişkeni ile çalıştırılır). - -## Sık Karşılaşılan Sorunlar - -- **GitHub'dan "Download ZIP" ile indirdiniz**: ZIP arşivi `third_party/rpf9-explorer` alt modülünü içermez. - `git clone --recursive` kullanın veya depo klasöründe `git submodule update --init --recursive` çalıştırın. -- **`llvm-mc`, `gfx1013` veya AMDGPU hedefini reddediyor**: Büyük olasılıkla resmi Windows LLVM kurulumu kullanılıyor. - `scripts\build_llvm_mc.ps1` ile yerel derleyin veya `LLVM_MC` değişkenini WSL içindeki `llvm-21` `llvm-mc` yoluna - ayarlayın. -- **CMake "needs the Windows SDK 10.0.26100 or newer" hatası veriyor** (veya MSVC `Desc_1_2` üyesini bulamıyor): - Visual Studio Installer üzerinden ya da `winget install Microsoft.WindowsSDK.10.0.26100` komutuyla Windows SDK'yı - güncelleyin, `runtime/build` klasörünü silip yeniden yapılandırın. -- **`C:` sürücüsünde yer kalmadı**: Çalışma dosyalarını başka bir sürücüye taşımak için `--work "D:\leonida-work"` - parametresini verin. -- **Windows yeni derlenen test programlarını engelliyor** (*"An Application Control policy has blocked this file"*): - Windows 11 Akıllı Uygulama Denetimi kaynaklıdır; bkz. [`docs/testing.md`](../../testing.md#known-problems). - -## Katkıda Bulunma ve GPU Testleri - -1. Aynı işi iki kez yapmamak için açık PR'lara ve [koordinasyon issue'suna][coord] göz atın. Başlamadan önce - `claiming: ` yazarak (veya henüz ID yoksa tek satırlık açıklamayla) görevi sahiplenin. -2. Sentetik girdilerle ilgili testleri çalıştırın (örneğin depo kökünde `python -I tests/test_manifest_verifier.py`). -3. PR açıklamasında görev ID'sini, neleri test ettiğinizi ve GPU testi çalıştırdıysanız ekran kartı ile sürücü - sürümünü belirtin; yapay zekâ desteği kullandıysanız not düşün. Tüm kurallar için - [`CONTRIBUTING.md`](../../../CONTRIBUTING.md) dosyasına bakın. - -[GPU test rehberi](../../testing.md), oyun dosyası olmadan testlerin nasıl çalıştırılacağını açıklar. GPU test -sonuçlarını [issue #166](https://github.com/ItsNotRexed/Leonida/issues/166) altında (GPU ve sürücü başına bir yorum) -paylaşabilirsiniz. - -[coord]: https://github.com/ItsNotRexed/Leonida/issues?q=is%3Aissue%20is%3Aopen%20in%3Atitle%20%22Coordinating%20who%20works%20on%20what%22 diff --git a/docs/i18n/zh-CN/quickstart.md b/docs/i18n/zh-CN/quickstart.md deleted file mode 100644 index 6b609a6d8..000000000 --- a/docs/i18n/zh-CN/quickstart.md +++ /dev/null @@ -1,149 +0,0 @@ -# Leonida — 快速上手(`zh-CN`) - -> [!NOTE] -> 英文文档([`README.md`](../../../README.md)、[`CONTRIBUTING.md`](../../../CONTRIBUTING.md) 和 -> [`docs/README.md`](../../README.md))是**权威版本**。本文只汇总稳定的安装与构建说明(与 commit `aa2988cc` 同步)。 -> 项目每日进展请查看 [`README.md`](../../../README.md)。 - -## Leonida 是什么 - -Leonida 是一个把 Xbox Series 版 Grand Theft Auto VI **静态重编译**到 Windows 的项目:在**你自己的电脑上、 -用你自己的游戏拷贝**构建。主机的 RDNA2 着色器翻译为 SPIR-V(Vulkan),资源直接从你的包读取, -主机的系统软件用 shim 重新实现。 - -> [!IMPORTANT] -> 本仓库**不包含**游戏、密钥或可执行文件,也不说明如何获取。这里没有任何解密或绕过保护的内容。构建产生的一切 -> (翻译后的着色器、导出的资源、工作目录和存档)都来自你自己的拷贝,**只能留在本机**——不要在 issue 或 -> pull request 中附带或分享这些文件(见 [`CONTRIBUTING.md`](../../../CONTRIBUTING.md))。 - -项目处于早期:**目前还不能启动游戏**。 - -## 平台 - -目前在任何平台上都还不能游玩。各平台现在能运行的部分: - -- **Windows**:全部(`make_game.py`、各工具,以及带 D3D12 → Vulkan 层及其测试的 runtime `gta6rt`)。 -- **Linux**:翻译器、资源工具和 Vulkan GPU 测试工具可原生构建并运行(在 RADV 和 NVIDIA 上测试过)。runtime 是 - Windows 代码:用 clang-cl 和 xwin 交叉编译,测试在 Wine 或 Proton 下运行。游戏将来也打算这样运行(#217)。 -- **macOS(Apple Silicon)**:Python 工具和 Vulkan 测试工具可在 MoltenVK(Homebrew)或 KosmicKrisp 上原生运行。 - runtime 与 Linux 一样在 Wine 下运行。已知缺口:没有 geometry 阶段和 `VK_EXT_mesh_shader`、子组宽度为 32 - (wave64 着色器以模拟方式运行),以及 MoltenVK 的浮点处理;详见 [`docs/testing.md`](../../testing.md)。 -- **AMD RDNA1(RX 5000)**:受支持的目标,接近主机的 RDNA2;它的 64 宽子组可原生运行 wave64 着色器。 - -所有平台的 GPU 结果都汇总在 [issue #166](https://github.com/ItsNotRexed/Leonida/issues/166)。 - -## 前置条件 - -- **你自己的拷贝**:Xbox Series 包,版本 `1.0.2.1`(目录里有 `MicrosoftGame.Config` 和明文可读的 `.rpf` 文件)。 -- **Windows 10/11 x64**,约 **400 GB** 空闲空间给中间文件(可用 `--work` 放到另一块盘)。 -- [Python 3.12+](https://www.python.org/downloads/)(勾选 “Add python.exe to PATH”)。 -- [.NET 8 SDK](https://dotnet.microsoft.com/download/dotnet/8.0)。 -- [Vulkan SDK](https://vulkan.lunarg.com/)(`spirv-as`、`spirv-val`、`vulkaninfo`)。 -- [LLVM 21+](https://github.com/llvm/llvm-project/releases),需要 **AMDGPU target**(`llvm-mc`): - - Windows 官方 LLVM 发行版**不含** AMDGPU target。 - - Windows 上运行 `scripts\build_llvm_mc.ps1` 构建原生 `llvm-mc.exe`(需要 `git` 和 Visual Studio 的 C++ 工具) - 并设置 `LLVM_MC`;**或**在 WSL 里安装 `llvm-21` 并设置 - `LLVM_MC="wsl -d Ubuntu -e /usr/lib/llvm-21/bin/llvm-mc"`(见 [`docs/design.md`](../../design.md#disassembling-shaders))。 - 构建脚本大约需要 20-40 分钟。 - - 如果你用 [conda](https://docs.conda.io/),更快的办法是 `conda install -c conda-forge llvm-tools`(它的 Windows - 版本包含 AMDGPU target),然后把 `LLVM_MC` 设为安装好的 `llvm-mc.exe` 的完整路径(激活环境后用 - `where.exe llvm-mc` 查看;PowerShell 里单独的 `where` 是 `Where-Object`)。 - - Linux 上 `PATH` 里有 `llvm-mc` 即可。 -- **Visual Studio 2022**,勾选“使用 C++ 的桌面开发”和 **Windows SDK `10.0.26100` 或更新** - (`runtime` 阶段需要,它使用 root signature 1.2)。 -- [ffmpeg](https://ffmpeg.org/download.html) 在 `PATH` 中(可选:解码 XMA2 流;使用 `--wav` 时必需)。 - -## 如何构建 - -### 简单方式(Windows) - -1. 安装上面的前置条件。 -2. **带子模块**克隆仓库: - - ```powershell - git clone --recursive https://github.com/ItsNotRexed/Leonida - ``` - - 用 GitHub 的 “Download ZIP” 下载会缺少 `third_party/rpf9-explorer`:装了 `git` 时构建会自动获取,否则会告诉你该怎么做。 - -3. 双击 **`Build.bat`**。 - -脚本会自动查找你的拷贝(Downloads、Desktop、Documents(也包括 OneDrive 等 Windows 实际存放它的位置)、Games、 -用户目录以及每个盘的根目录往下两层),只根据几个文件的大小识别版本,不读取大文件。找到多份拷贝时会问你用哪一份, -一份都没找到时会让你粘贴目录路径。开始前它会检查前置条件和可用空间,并一次列出所有缺少的项目,结果写到 -`Documents\Leonida`。构建中断后重新运行即可从断点继续。 - -### 磁盘空间不足 - -上面的空间要求针对完整构建。只想*运行*移植版时,`--stages check,shaders,runtime` 约需 30 GB;占了其余绝大部分 -空间的 `assets` 阶段只供资源工具使用,`--wav` 还会再增加数倍于 Ogg Opus 的大小。`--work` 和 `--out` 都可以放在 -其他盘。runtime 原地映射游戏包,所以包所在盘为只读时需要 `gta6rt --overlay <可写目录>`(这是 `gta6rt` 的选项, -不是 `make_game.py` 的)。不要删除 `work/shaders/dxbc/disasm` 里的 `.s` 文件:连同 -`work/shaders/spirv/index.json` 一起删掉后,`shaders` 阶段可能看起来已完成,却没有任何着色器。 - -### 命令行(`make_game.py`) - -```powershell -python -I make_game.py --find # 列出本机找到的拷贝 -python -I make_game.py --pick # 在文件夹对话框里选择游戏目录 -python -I make_game.py --check # 校验游戏文件,不构建 -python -I make_game.py --check --full-check # 另外比对每个文件的 SHA-256(较慢) -python -I make_game.py --game "D:\path\to\package" --out "D:\Games\Leonida" --work "E:\leonida-work" -python -I make_game.py --stages shaders,assets # 只跑指定阶段 -python -I make_game.py --game "D:\path\to\package" --wav # 额外把 Ogg Opus 解码为 PCM WAV(很大) -python -I make_game.py --wave64-emulate auto # auto(默认)、on 或 off -``` - -`check` 阶段总是最先运行;选中后,`shaders`、`assets` 和 `runtime` 会一起运行(三者互不依赖)。`pipelines` 在翻译后的着色器就绪后开始。该阶段在你的 GPU 驱动上创建每个 -翻译后的着色器并检查能否编译,报告必须跳过的着色器,并把管线缓存保存到 `--out` 里的 `pipeline_cache.bin`; -runtime 目前还不加载这个缓存,所以它不会加快首次启动。 - -构建会记录产出结果所用的 `llvm-mc` 命令和版本、翻译器源码,以及资源解码器(`third_party/rpf9-explorer` 的 -commit 和 `tools/rpf9dump` 的源码)。其中任何一项改变时,只重做受影响的步骤(反汇编、翻译,或该归档的模型和 -纹理导出)。没有这些记录的旧工作目录在升级后会把这些步骤重做一次。 - -- **`--wave64-emulate`**:决定是否把 wave64 compute/mesh 着色器翻译成在任意子组宽度下都精确的版本 - (见 [`docs/design.md`](../../design.md) 中 Wave64 emulation 一行)。NVIDIA 和 Intel GPU 是 32 lane 子组, - 需要它。默认 `auto` 会询问 `vulkaninfo`(属于 Vulkan SDK),除非所有 GPU 都报告 64 宽子组、或无法判断, - 都会启用;运行时实际使用的 GPU 无法以 64 宽运行 compute/mesh 时也会启用。有一个例外会让它保持关闭:当运行时的 - GPU 是 RDNA2 独显或核显(RX 6000、Ryzen 6000/7000/9000 的核显)、使用 AMD Windows 驱动并原生运行 wave64 时 - ——该驱动的着色器编译器在模拟 LDS 代码上会崩溃(#857);否则 Intel 核显搭配 RX 6000 卡时也会被启用。 - 该模式会保存在翻译后的着色器旁边,切换它会重新翻译。使用 `auto` 时通常可以复用之前模拟翻译的着色器;上述 AMD - Windows 驱动的例外会把它们按原生方式重新翻译。要强制模拟用 `--wave64-emulate on`,强制原生 wave64 用 - `--wave64-emulate off`。 -- **四个 fallback 标志**:它们同样转发给翻译器、保存在翻译后的着色器旁边,切换会重新翻译: - `--no-float-controls`(去掉 `SignedZeroInfNanPreserve`,用于设备在缺少 - `shaderSignedZeroInfNanPreserveFloat32` 时会跳过着色器;需要 PR #664 的翻译器标志)、 - `--bary-fallback`(从插值输入读取原始重心坐标,用于没有 `VK_KHR_fragment_shader_barycentric` 的设备)、 - `--texel-offset-fallback`(把 `image_sample*_o` 的偏移折叠进坐标,用于没有 `VK_KHR_maintenance8` 的设备)和 - `--mesh-compute`(把 mesh 着色器当作 compute,用于没有 `VK_EXT_mesh_shader` 的设备)。每个标志的说明见 - [`docs/design.md`](../../design.md)。 -- **`--work`**:建议指向至少有 400 GB 空闲的磁盘;`shaders` 阶段最慢,默认使用一半 CPU 线程(`--jobs` 可调)。 -- **Linux 与 Wine/Proton**:`make_game.py` 也能在 Linux 上运行。`runtime` 阶段会在 Linux 上用 clang-cl 和 - lld-link(LLVM 19+,但 22.1.7 和 22.1.8 有已知问题,见 [docs/testing.md](../../testing.md#known-problems); - 命令名用不带版本后缀的,或五个 LLVM 工具都用同一版本后缀,例如 `clang-cl-21`)把 loader 交叉编译到 - `runtime/build/windows`,依赖 `XWIN_DIR` 或 - `~/.local/share/xwin-sdk` 里的 MSVC CRT 和 Windows SDK - ([docs/testing.md](../../testing.md#the-windows-runtime-on-linux-under-wine-or-proton) 有一次性 `xwin` 命令); - 缺少这些时该阶段不参与默认 stages,显式请求会先列出缺什么。 - 也可以使用别处构建好的 Windows 版本,例如 Runtime workflow 的 `runtime-windows` artifact: - `python3 -I make_game.py --runtime-build ~/Downloads/runtime-windows`。 - 两种方式都会把 `gta6rt.exe` 和 `gta6rt_tls_host.dll` 复制到 `--out`,并在旁边生成 `gta6rt.sh`, - 用 `wine`(或 `WINE` 指定的 Proton)启动。`pipelines` 阶段使用 `vk_pipeline_check`(需要 CMake 3.24+、C++20 - 编译器和 Vulkan 开发头文件,构建到 `runtime/build/linux`;缺少时脚本会在其他工作之前自行构建)。 - -## 常见问题 - -- **用 GitHub 的 “Download ZIP” 下载**:ZIP 不含 `third_party/rpf9-explorer` 子模块。请用 - `git clone --recursive`,或在仓库目录里执行 `git submodule update --init --recursive`。 -- **`llvm-mc` 拒绝 `gfx1013` / AMDGPU**:多半是用了 Windows 官方 LLVM 安装包。改用 - `scripts\build_llvm_mc.ps1`,或把 `LLVM_MC` 指向 WSL 里的 `llvm-mc`(`llvm-21`)。 -- **构建 runtime 时报 `D3D12_ROOT_SIGNATURE_DESC2` 错误**:把 Windows SDK 升级到 `10.0.26100` 或更新 - (可在 Visual Studio Installer 或 `winget install Microsoft.WindowsSDK.10.0.26100` 中安装), - 删除构建目录后重新配置。 -- **`C:` 盘空间不足**:用 `--work "D:\leonida-work"` 把中间文件放到其他分区。 - -## 参与贡献与运行 GPU 测试 - -- GPU 测试指南(不需要游戏文件):[`docs/testing.md`](../../testing.md)。 -- 贡献规则、零游戏数据政策与任务协调:[`CONTRIBUTING.md`](../../../CONTRIBUTING.md)。 diff --git a/docs/isa_coverage.md b/docs/isa_coverage.md deleted file mode 100644 index 999eeef82..000000000 --- a/docs/isa_coverage.md +++ /dev/null @@ -1,139 +0,0 @@ -# RDNA2 ISA coverage of the translator - -`tools/isa_coverage.py` compares the instructions of AMD's machine-readable RDNA2 ISA specification with what -`tools/rdna2spirv.py` has a rule for. It reads no game data and needs no GPU; it is a count over the public ISA and -the translator's source. - -## Getting the specification - -AMD publishes the XML files on GPUOpen, [AMD machine-readable GPU ISA documentation](https://gpuopen.com/machine-readable-isa). -The zip is not in this repository (the RDNA2 file alone is 11 MB): - -```sh -curl -L -o isa.zip https://gpuopen.com/download/machine-readable-isa/latest/ -unzip isa.zip amdgpu_isa_rdna2.xml -``` - -The numbers below come from the package `AMD_GPU_MR_ISA_XML_2026_08_06.zip` (SHA-256 -`82404f1126761b7877595b622afa7e1f311f2f41e89a3abe9aaf8ad045c082e2`), whose `amdgpu_isa_rdna2.xml` is "AMD RDNA 2", -schema 1.1.1, release date 2026-02-20, and carries `MIT`. AMD's reader for the same files is the -C++ [isa_spec_manager](https://github.com/GPUOpen-Tools/isa_spec_manager) (MIT); the schema is documented there in -`documentation/spec_documentation.md`. This tool parses the XML itself with `xml.etree`. - -## Running it - -```sh -python -I tools/isa_coverage.py --isa amdgpu_isa_rdna2.xml # markdown report -python -I tools/isa_coverage.py --isa amdgpu_isa_rdna2.xml --list # plus the unknown instructions per encoding -python -I tools/isa_coverage.py --isa amdgpu_isa_rdna2.xml --json -python -I tools/isa_coverage.py --isa amdgpu_isa_rdna2.xml --llvm-mc llvm-mc # classify non-RDNA2 names with llvm-mc -``` - -`--isa` defaults to `$LEONIDA_RDNA2_ISA_XML`. With that variable set, -`python -I tests/test_isa_coverage.py` also checks the real translator against the real XML; without it those tests -skip and the rest runs on a small hand-written fixture in the same schema. - -## What the classes mean - -The translator dispatches on the opcode string with one long if/elif chain (`Gen._insn`), so the tool reads the -source with `ast` instead of running it: - -| class | meaning | -|---|---| -| handled-exact | the name is compared with `op` (`==`, `in`) or is a key of a mnemonic table (`NOOPS`, `F2`, ...) | -| handled-family | no exact name, but it starts with a prefix `_insn` or a method it hands `op` to tests with `op.startswith`, or ends with a suffix one of their if/elif chains tests with `op.endswith` (alone, or beside a ` in self.TABLE` guard, which limits the family to that table's stems: `s_*_saveexec_b32/b64` and `EXEC_LOGIC`) | -| refused | the name sits in a test whose whole body is `raise Unsupported(...)` | -| unknown | none of these: the final `raise Unsupported(op)` is what it reaches | - -Limits. "Handled" means a rule exists, not that the rule is right; the GPU tests and `tests/semantic` do that. -A broad prefix such as `ds_` marks every `ds_*` instruction handled-family even where a sub-dispatch refuses one -form, so read handled-family as an upper bound; the instructions whose branch contains a `raise Unsupported` are -listed separately ("handled but with operand forms that raise"). Names built by string formatting are invisible. -Only the AMD XML defines the denominator: it omits a few gfx1013 instructions that LLVM accepts (below), and lists -some that a desktop part does not execute. - -## Result (translator at `41f44826`, AMD XML of 2026-08-06) - -Every new translator rule moves these numbers; rerun the tool for the current ones. - -1,153 RDNA2 instructions: 436 handled-exact, 408 handled-family, 2 refused (`s_denorm_mode`, `s_round_mode`), 307 -unknown. The unknown ones cluster in groups the corpus does not need or that are not written yet: the f64 -transcendentals and `v_div_*`, FLAT and SCRATCH memory, the global atomics, the `image_gather4*` variants outside the -four `_l`/`_lz` forms, packed image formats (`*_pck`, `*_by2`), the 16-bit `v_pk_*` integer forms, `v_dot*`, and the -`*_saveexec` / `s_nand`/`s_nor`/`s_xnor` scalar forms. `python -I tools/isa_coverage.py --list` has the full list per -encoding. - -Names the translator matches that are not in the RDNA2 XML (10), each checked with -`llvm-mc -arch=amdgcn -mcpu=gfx1013`: - -| name | llvm-mc for gfx1013 | verdict | -|---|---|---| -| `v_add_u16`, `v_sub_u16` | other GPU only | internal: `v_add_nc_u16` / `v_sub_nc_u16` are re-dispatched under these names | -| `s_delay_alu` | other GPU only (RDNA3) | deliberate, in `NOOPS` | -| `v_mac_f32`, `v_mac_legacy_f32`, `v_mad_f32`, `v_mad_legacy_f32`, `v_madak_f32`, `v_madmk_f32`, `s_get_waveid_in_workgroup` | valid | real gfx1013 instructions that AMD's XML omits | - -`tools/rdna2_decode.py` decodes raw words without LLVM from the opcode and operand tables in -`tools/rdna2_isa_tables.py`, which are derived from the same `amdgpu_isa_rdna2.xml`. The gfx1013 entries above -that the XML omits (`v_mac_f32`, `v_mad_f32`, `v_madak_f32`, `v_madmk_f32`, `s_get_waveid_in_workgroup`) are in -that table, and `v_mad_legacy_f32` is the name the decoder gives VOP3 opcode 0x140 on a gfx101* target. A name -added there belongs in the table above as well. - -None is a typo that breaks translation, so there is nothing to fix in the translator. No name ends in a suffix -`base_op()` strips (`_e32`, `_e64`, `_sdwa`, `_dpp`), and every `startswith` prefix matches at least one RDNA2 -instruction. - -## Which rules the game reaches that hardware has not checked - -Several rows of the translator contract in `docs/design.md` say part of a rule is not measured on hardware, or -not run on the shader corpus. `tools/op_reach.py` counts, over the disassembled corpus, the shaders and -instructions that use each instruction. It merges the `_e32`/`_e64`/`_sdwa`/`_dpp` encodings and counts only the -program up to a listing's last `s_endpgm`. The counts say whether 1.0.2.1 depends on the rule at all. They do -not settle the hardware question. - -```sh -python -I tools/op_reach.py /shaders/dxbc/disasm --index /shaders/dxbc/index.json v_cos_f16 v_log_f16 ... -``` - -Measured on the 26,503 1.0.2.1 listings (`shaders.rpf`, LLVM gfx1013; 12,101 PS, 9,282 MS, 2,689 CS, 2,236 VS, -195 GS). The 2,035 decoded instructions after a listing's last `s_endpgm` are left out: they are data words, and -the only place `s_cmov_b32` appears (4 listings). The embedded programs (the BVH builder's 52 FSSM programs, -[embedded_shaders.md](embedded_shaders.md), and the 29 FidelityFX programs, [fspx.md](fspx.md)) are not counted, -and a later game build may differ. - -**No 1.0.2.1 shader uses these instructions**, so on this build the unmeasured parts of their rows have no effect: - -| `docs/design.md` row | instructions with 0 shaders | -|---|---| -| Sub-dword MUBUF loads | `buffer_load_ubyte`, `_sbyte`, `_ushort`, `_sshort` | -| 8/16-bit global stores and d16 loads | `global_store_byte`, `_short` and their `_d16_hi` forms; `global_load_{u,s}byte_d16`, `global_load_short_d16` and their `_hi` forms | -| `v_rcp_f64`, `v_rsq_f64`, `v_sqrt_f64` | all three | -| `ds_cmpst_f32`/`_rtn_f32`, `global_atomic_fcmpswap`, `buffer_atomic_fcmpswap` | all four | -| `ds_add_f32`, `ds_add_rtn_f32` | both | -| `image_atomic_{swap,inc,dec,fmin,fmax,fcmpswap}` | all six | -| Scalar select and pack | `s_cmov_b32` (program code), `s_cmovk_i32`, `s_cmov_b64`, `s_pack_ll/lh/hh_b32_b16` | -| Vector integer additions | `v_mul_hi_u32_u24`, `v_mul_hi_i32_i24`, `v_lshrrev_b64`, `v_ashrrev_i64`, `v_qsad_pk_u16_u8`, `v_mqsad_pk_u16_u8` | -| `v_div_fixup_f16`, `v_div_fixup_f64` | both | -| `v_frexp_mant_f16`, `v_frexp_exp_i16_f16`, `v_ldexp_f16` | all three | -| `v_frexp_mant_f64`, `v_frexp_exp_i32_f64` | both | -| `v_cvt_pknorm_i16_f32`, `v_cvt_pknorm_u16_f32` | both | -| `v_cvt_pknorm_i16_f16`, `v_cvt_pknorm_u16_f16` ("not run on the shader corpus") | both | -| `v_cmp_class_f16`/`_f64` and the `v_cmpx` forms ("and the shader corpus") | all four | -| `buffer_atomic_{and,or,xor,swap}_x2` | all four | -| `v_dot2c_i32_i16`, `v_dot8c_i32_i4` | both | - -**These the game does reach**, so their unmeasured parts still matter. Shaders, then instructions in brackets: - -| `docs/design.md` row | instruction: shaders (instructions), by stage | -|---|---| -| 16-bit interpolation | `v_interp_p1ll_f16` and `v_interp_p2_f16`: 4,776 PS (59,367 each) | -| `v_interp_mov_f32` p10 / p20 | 3,673 PS (6,926) | -| `v_cvt_f16_f32` output modifiers | `v_cvt_f16_f32`: 6,306 (44,496): 4,490 MS, 926 CS, 580 PS, 310 VS; the count is the instruction, not its modifiers | -| Known approximations (`v_fma_mix*` rounding twice; `v_cos/exp/log_f16`) | `v_fma_mix_f32` 9,620 (487,658), `v_fma_mixlo_f16` 6,155 (33,900), `v_fma_mixhi_f16` 842 (2,135); `v_exp_f16` 3 CS (12), `v_cos_f16` 1 CS (2), `v_log_f16` 0 | -| `v_cndmask_b32` source modifiers | `v_cndmask_b32`: 22,553 (1,490,241); the count is the instruction, not its modifiers | -| Image atomics, size and LOD queries | `image_get_resinfo` 407 (1,148: 381 PS, 26 CS), `image_get_lod` 653 PS (718) | -| Ray tracing (gfx1013 not measured) | `image_bvh_intersect_ray` 40 CS (638), `image_bvh64_intersect_ray` 24 CS (78) | -| `s_bfe_u32` / `s_bfe_i32` past bit 31 | `s_bfe_u32` 15,398 (90,156), `s_bfe_i32` 2,847 (6,040); whether an operand passes bit 31 is not counted | - -A row's unmeasured part can be narrower than its instruction: a modifier, an operand range, an inactive lane or -a special value. Where the count is the instruction alone, the table says so, and the count is an upper bound for -that part. `tests/test_op_reach.py` checks the tool on hand-written listings. diff --git a/docs/linux.md b/docs/linux.md deleted file mode 100644 index e7ca27455..000000000 --- a/docs/linux.md +++ /dev/null @@ -1,114 +0,0 @@ -# Linux - -What a Linux user (x86-64, a Vulkan GPU) can do today, from one page: the build of the shaders and assets runs -natively, the Vulkan test tools build natively with GCC or Clang, and the loader (`gta6rt`) is a Windows program that -runs under Wine or Proton. Nothing is playable on any platform yet (README, *Project status*). - -The package names below were checked on Ubuntu 26.04 LTS. Other distributions have the same tools under their own -names; the build lists anything it can't find before it starts. - -## What runs where - -| Piece | On Linux | How it is checked | -|---|---|---| -| `make_game.py`: check, shaders, assets, pipelines | Native | CI (`stdlib-tests-linux`, `translator-tests`, `semantic-tests`) | -| `Build.sh`, `Mods.sh` | Native (`/bin/sh`) | `tests/test_shell_launchers.py`, in the standard-library loop of `stdlib-tests-linux` | -| Shader translator, its tests and the GPU test tools (`vk_harness`, `vk_pipeline_check`, ...) | Native, GCC or Clang | CI (`linux-gpu-tools`: GCC, tests on llvmpipe); Clang builds them too, but no CI job uses it yet | -| `rpf9dump` (asset export) | Native, .NET 8 or newer | CI builds it on Windows only (the `check` job) | -| `gta6rt`, its shims and their tests | Windows program, under Wine or Proton | Cross-built with clang-cl and xwin; CI runs the Windows build under Wine on pushes to `main` | - -## Build the port - -Install the prerequisites (Ubuntu 26.04; the comment says what each is for): - -```sh -sudo apt install git python3 \ - llvm-21 spirv-tools \ - dotnet-sdk-10.0 \ - cmake ninja-build g++ libvulkan-dev \ - ffmpeg zenity python3-tk -# git, python3 the clone and make_game.py (Python 3.12 or newer) -# llvm-21, spirv-tools the shaders stage: llvm-mc with the AMDGPU target, spirv-as and spirv-val -# dotnet-sdk-10.0 the assets stage builds rpf9dump; Ubuntu 26.04 packages no .NET 8 SDK, and 10 builds the -# net8.0 project through global.json's roll-forward -# cmake ... libvulkan-dev the pipelines stage builds vk_pipeline_check -# ffmpeg optional: XMA2 audio and --wav -# zenity, python3-tk optional: the --pick folder dialog and the mod manager window -``` - -Then, with your own copy of the game already readable on disk: - -```sh -git clone --recursive https://github.com/ubiquitarianism/leonida -cd leonida -./Build.sh --find # list the copies found: the home folder, Downloads, Documents, /mnt, /media/, ... -./Build.sh --check # check your copy, build nothing -./Build.sh # build into ~/Documents/Leonida -``` - -`./Build.sh` is `python3 -I make_game.py` with the newest Python 3.12+ it finds, so every `make_game.py` option in -the README works with it (`--game`, `--out`, `--work`, `--stages`, ...). Without the cross-build tools below, the -default stages leave `runtime` out (`check,shaders,assets,pipelines`). - -Notes: - -- **llvm-mc**: Debian and Ubuntu's `llvm-21` installs it only as `llvm-mc-21` and `/usr/lib/llvm-21/bin/llvm-mc`. - With `LLVM_MC` unset the tools use the plain `llvm-mc` when it is on `PATH` and otherwise the newest of those - versioned names (`tools/mc_command.py`). Set `LLVM_MC` to choose another one. -- **File names are case-sensitive.** The build opens the package's files by their exact names - (`MicrosoftGame.Config`, `Catalog000.bin`, ...). A copy whose names changed case on the way is reported with the - name it found and the one it needs; nothing is renamed for you. -- **Mods**: `./Mods.sh` opens the mod manager window ([modding.md](modding.md)); `python3 -I tools/leonida_mods.py` - is the same manager on the command line. - -## The runtime, under Wine or Proton - -`gta6rt` is a Windows program. To build it on Linux, add the LLVM cross tools and an MSVC CRT and Windows SDK laid -out by [xwin](https://github.com/Jake-Shadle/xwin) (running xwin downloads them from Microsoft and means accepting -Microsoft's licence): - -```sh -sudo apt install clang-21 lld-21 llvm-21 wine -xwin --accept-license --sdk-version 10.0.26100 splat --use-winsysroot-style --preserve-ms-arch-notation \ - --output ~/.local/share/xwin-sdk -./Build.sh --stages runtime -``` - -On Ubuntu 24.04, `clang-cl-` is in `clang-tools-` instead ([testing.md](testing.md#known-problems)). -`make_game.py` finds the five tools under one version suffix (`clang-cl-21`, `lld-link-21`, `llvm-lib-21`, -`llvm-rc-21`, `llvm-mt-21`) or their plain names. Without the SDK it lists what is missing before any work starts. -`--runtime-build ` takes a Windows build made elsewhere instead, such as the `runtime-windows` artifact of the -Runtime workflow. The stage writes `/gta6rt.sh`, which starts `gta6rt.exe` with `wine` or the Wine named by `WINE` -(for Proton, its `files/bin/wine`); README, *Running the loader on Linux*, has the commands. -[testing.md](testing.md#the-windows-runtime-on-linux-under-wine-or-proton) has the test runs under Wine and Proton -and what fails there. - -### Why there is no native Linux `gta6rt` - -A native (ELF) loader is not a matter of build flags: - -- The loader shims only the console's own modules and a few Win32 entry points it has to own (GDK, XMem, - `d3d12_xs`, the library loader, the process and file-system shims). Every other import binds to the host's Windows - DLLs unchanged (`runtime/src/pe_loader.cpp`; [runtime_imports.md](runtime_imports.md): `XboxBvhBuilder.dll` - alone binds 4 imports to shims and 53 to the host). On Linux, those host DLLs are what Wine provides. -- The mapped code uses the Windows x64 calling convention and the Windows thread and exception model: the loader - registers unwind tables with `RtlAddFunctionTable`, keeps a module TLS slot through `gta6rt_tls_host.dll`, and - `main.cpp` installs a vectored exception handler. The shims are written against `windows.h`. - -A Linux-native host would have to reimplement each of those Win32 APIs, which is the work Wine already does, so the -supported way is the Windows build under Wine or Proton with the D3D12 layer on native Vulkan. What does build -natively is everything that doesn't touch Win32: the Vulkan tools and the portable runtime pieces with their tests -(`ctest` on a Linux build runs them, including the root-signature model and the host CPU check). - -## Build and test without the game - -```sh -cmake -S runtime -B runtime/build/linux -G Ninja # CC=clang CXX=clang++ for Clang -cmake --build runtime/build/linux --parallel -ctest --test-dir runtime/build/linux --output-on-failure # Vulkan tests run on Mesa's lavapipe without a GPU -python3 -I scripts/run_semantic_tests.py tests/semantic # translator suite -python3 -I tests/test_.py # one standard-library test -``` - -[testing.md](testing.md) covers the GPU tests (`scripts/run_gpu_tests.py`), running them on llvmpipe, and choosing -the GPU. diff --git a/docs/material_pass_replay.md b/docs/material_pass_replay.md deleted file mode 100644 index 62afed933..000000000 --- a/docs/material_pass_replay.md +++ /dev/null @@ -1,32 +0,0 @@ -# Following a mesh from its material to a pixel shader - -A stored effect can offer several ways to draw the same mesh. On one Xbox 1.0.2.1 drawable, the first geometry selects material slot 0. Its effect has 45 techniques. One vertex/pixel pair writes a packed integer target. Two other techniques each pair a mesh shader with a pixel shader that declares textures. The first of those pixel shaders directly reads the drawable's stored material constants. The active technique for a particular frame remains unknown. - -## Identify the draw - -To locate the example in a local 1.0.2.1 copy, filter the decoded `data.rpf` drawables to three meshes and three material slots. The first mesh has 1,656 vertices and 809 triangles. Its slot declares five textures and 46 numeric members. Select stored technique 2, pass 0, then confirm the pixel stage declares one constant buffer, one structured SRV and one four-component unsigned output. These checks distinguish the input used here from the UV example in [first_light.md](first_light.md). - -Follow the geometry's material-slot index to the effect, then follow the technique and pass selectors to the original program records. Use their archive offsets to distinguish programs and verify the native shader hashes before replay. On the selected vertex shader's packed-index branch, the mesh's original buffers reproduced 2,427 triangle corners in order and 1,656 object-space positions bit for bit. Swapping the first and third corner changed 1,618 indices. Changing the position-axis field eliminated every exact position match. The replay ends before the object-to-clip transform. [Effect lookup and geometry check](https://github.com/ItsNotRexed/Leonida/pull/2519#issuecomment-7085667975) · [Effect and pass reader](https://github.com/ItsNotRexed/Leonida/pull/3036) - -## Follow the integer target through its reader - -For this pixel shader the first dword of `b501, space0` supplies a row index. The paired vertex shader uses that index to write three more incoming dwords into one 12-byte structured record. The pixel shader also reads a word at byte offset 20 in a separate structured SRV. Three other shader programs use that field to address records 48 bytes apart in a second table. - -Before its compressed export, the pixel shader forms the second component as `((word & 0xffff) << 16) | ((row + 1) & 0xffff)`. Six compute programs load a four-component image under the same resource key and interpret that layout. Each tests the second component for zero. Each subtracts one from the low half to index the 12-byte table and uses the high half to index the other table. The different stages identify the tables by matching resource keys even where the register numbers differ. Connecting this particular draw and dispatch still requires the actual image binding and execution order. - -To check the handoff, vary just the row and read back the **whole second component**. The following synthetic inputs were supplied to the selected translated pixel shader. A synthetic vertex shader supplied constant interpolants. Both pixel shaders used the same descriptor contents and `R32G32B32A32_UINT` target. [Tested translator revision](https://github.com/ItsNotRexed/Leonida/commit/4f0c41fb3241870230483c02918f99e901c3a5fe) - -| Buffer word | Row | Before the half conversion | Selected shader readback | Direct 32-bit control | -|---:|---:|---:|---:|---:| -| `0x3f80` | 6 | `0x3f800007` | `0x00003c00` | `0x3f800007` | -| `0x3f80` | 7 | `0x3f800008` | `0x00003c00` | `0x3f800008` | - -Two further cases varied the buffer word and crossed a half-precision quantization boundary. All four pixels of each of eight 2×2 draws matched their expected values on an NVIDIA GeForce RTX 5070, driver 621.01, Intel Core Ultra 7 265K, Windows 11 build 26200.9974. A typed output alone does not preserve these two indices through the selected translation. The Xbox frame's export configuration and render-target view remain open. - -## Find the surface inputs - -Compare pixel-stage declarations across the same material's passes. The packed pass has no texture or sampler declaration. The textured sibling declares a 272-byte material constant buffer. Of its 46 authored members, 45 match the program by hash and byte offset. For the last member, the effect's parameter record supplies both the authored and compiled name hashes at the same offset. A different material slot gave only 11 direct matches. The textured shader reads the stored values and uses the first texture handle for a 2-D RGB sample. The drawable supplies four texture references across five declarations. The live handle table, sampler, and the descriptor used for the empty declaration still need independent verification. - -The empty texture declaration has a narrower consequence on the first textured pass. Two stored material values satisfy a uniform branch condition. For an active wave reaching that branch, the taken path skips all four 2-D array sampling sites. Changing either value independently made those sites reachable in a control-flow check. The shader still loads the handle word. This result concerns that material and pass. - -Both tested color techniques' mesh and pixel programs translated and passed Vulkan 1.2 SPIR-V validation, including the translator's 32-lane emulation of the mesh stages' 64-lane waves. The stage-interface checker also found compatible mesh outputs and pixel inputs for each original pair in both modes. Reproducing final appearance still requires their draw constants, descriptors, transforms, and the frame's pass selection. diff --git a/docs/mission_logic.md b/docs/mission_logic.md deleted file mode 100644 index d1ee15e51..000000000 --- a/docs/mission_logic.md +++ /dev/null @@ -1,178 +0,0 @@ -# Mission state tables in the script archives - -`story000_script.rpf` and `script.rpf` are mostly not scripts in the sense of an instruction stream. The -containers that carry mission structure are **state machines**: arrays of 32-byte records keyed by a joaat -hash of a state name, each record pointing at a pool element that carries world transforms and an -archetype hash. This page records the layout, the vocabulary that resolved, and the shape of the flows. -Counts and offsets only — no payload, and only the small name excerpt needed to explain the key column. - -## Where they are - -| | | -|---|---| -| containers | `PSIN`-tagged, 2,309 of them across the two archives | -| record chunks | 8,986 | -| records | 40,804 | -| distinct record hashes | 6,065 | -| files with a record array | 2,035 | - -Note that `PSIN` here is the same chunk family the reader meets elsewhere; the mission arrays live in the -`LSNS`-style payload side of those containers, not in the `PSIN` descriptor side. - -## Record layout - -32 bytes: - -``` -u32 key │ u32 0 │ u32 colB │ u32 0 │ u32 (u16 kind, u16 offset BE) │ u32 band │ u32 (u16 n, u16 n) │ u32 0 -``` - -Two details cost a false start and are worth stating: - -- **`band` is not zero.** It is an ascending band counter (`0,0,1,2,2,…`). A validator that requires - `field[5] == 0` misclassifies the real tables as opaque blobs. -- **`offset` is a byte offset, big-endian in its half**, and it is **file-absolute for most records**: - 2,087 of 2,207 entity-bearing records resolve that way, 429 resolve through the "next even-tagged pool - chunk" rule, which only fits one table family. The proof of byte-ness: consecutive deltas equal - `count * 4`, and values pack back to back from 0. - -## The pool element - -64 bytes, 16 dwords: - -``` -u32 archetype hash │ 0 │ 0 │ 0 │ f32 pos.xyz │ f32 pos.xyz (dup) │ rot.a,b,c (dup) │ u32 hash │ u32 linkHash │ 0 │ 0 -``` - -The 16-dword stride is a histogram peak (319 windows against 25/25 for neighbours), and the duplicated -archetype hash plus the duplicated position components are what identify the shape. Positions are true -world coordinates in RAGE space, Z up. - -## The key column - -Keys are **joaat of the state name, lower-cased first**: joaat here folds case, which is not true of every -implementation of it. Measured on 340 ground-truth pairs: a folding implementation reproduces **340/340**, -a case-sensitive one only **91/340** (329 reference names contain an uppercase byte). Any name lookup must -fold before hashing, or it will invent phantom names. - -Resolved keys fall in four provenance tiers, kept separate because they are not equally strong: - -| tier | count | how it was resolved | -|---|---:|---| -| document-proven | 22 | the name appears literally in the package's own text metadata | -| register-measured | 178 | found by grammar search, in-register, discounting ≈3.6 expected chance collisions | -| earlier register | 114 | same, from a weaker pass | -| positional | 4 | still unnamed, but distinguishable by position in the machine | - -Coverage: 167 → 485 of 6,065 distinct hashes (2.75 % → 8.00 %); record keys 5,846 → 8,314 of 40,804 -(14.33 % → 20.38 %); real (non-structural) states named **53.5 %** (2,675 of 4,996). 26.1 % of real states -are still hex, and 65 % of records sit in structural states rather than gameplay states. - -## Shape of the flows - -The corpus is highly templated: **113 identical-state-set clusters cover 1,676 of 2,035 files (82.4 %)**. -Naming one cluster therefore names dozens of files. Repeated clusters seen so far include -`g1798–g1804`, `g2209–g2212`, `g0986–g0995`. - -Flows read as ordered states with an entity count per state. Representative shapes (names where resolved, -hex otherwise; `<…>` marks a positional label): - -``` -g0082/83 guardaggro → startRobbery → fleeRobbery → robberyCombat → disrupt → INTRO -g1599 stealvehicle → delivervehicle -g0554 fleestore → selfEscape -g1774–79 stealboat → dropoff → boatchase → deliver -g1096–1126 Approach → Leave → → HOPOUT → INTRO -``` - -**135 initiation→terminal shaped jobs** were listed; only 3 are fully bounded end to end. - -Phase tagging over the named states (primary match): setup 958, exit 400, action 344, cutscene 130, -aftermath 97, law reaction 29. Law reaction being the rarest phase is a property of the corpus, not of the -tagging. - -## What a flow does and does not say - -A flow gives **ordering, states and entities**. It carries no conditions, objectives, or durations: there -are no opcodes here, and no jump table. Two consequences for a runtime: - -1. State order in the file is not necessarily play order. -2. The remaining unnamed hashes still have positional meaning — e.g. one is the single looping beat - between two cutscenes, another is the "get the car into position" beat before a vehicle exit — so a - trace is interpretable even where the name is missing. - -## Mission identity - -The package's own text metadata carries a 145-entry mission table. Two of those ids now have a -reproducible binding to one of these tables, so most outlines are still unattributed. Joining ids to -tables is an open problem; a plain joaat of the ids does not appear in the program data (0 of 290 -variants in 170.9 MB), so the join is not by name hash. - -## Binding a mission id to its tables - -This binding does not join on the id. It uses a **character** as the bridge: the mission's own text names -a person, a name dictionary turns that name into a 32-bit hash, and the same hash appears as the -`linkHash` of pool elements in a state table. - -1. **Start from a name the mission text uses.** `COM_KBOS_NEIGHB` is the replay-table id for the mission - publicly catalogued as **Pipework** (Mandy's rent). The text table at `data.rpf` stream - `0x19957A0` contains the line "You brought the cops to Mandy's house" and the line "Bert died". - The stream carries no mission id; the id-to-text step rests on the public name and the cast, not an - archive key. -2. **Resolve the character and its schedule.** `common.rpf` stream `0x4C270` lists - `KeyLento/Perschars/Peds/Unique/Mandy` and `.../Bert` under the pack `PSP_KeyLento_perschars_peds`. - SixNG's name dictionary, which is lower-case joaat, resolves the pack to `0x865F0DA9`, Mandy to - `0x03A885E6` and Bert to `0xE34ACBC8`. -3. **Scan the PSINs for the link hash.** In the 64-byte element above, `linkHash` is the dword at byte - `+0x34`, not the archetype dword. Inflating the five `story000_script.rpf` streams at `0x3FE4000`, - `0x3FE8000`, `0x3FEB000`, `0x3FEE000` and `0x3FF0000` and searching for those two hashes finds 28 - elements: 15 Mandy and 13 Bert. A scan of all 2,309 PSIN streams finds those 28 hits in exactly these - five files. -4. **Read the element.** Its start is `linkHash - 52`. The first dword is the archetype/state hash - described above. It does not resolve in the name dictionary, and the same character takes three - values, so it is an archetype/state hash rather than a character model name. - -| stream | Mandy elements | Mandy archetype | Bert elements | Bert archetype | -|---|---:|---|---:|---| -| `0x3FE4000` | 5 | `0x18BB2550` | 5 | `0xA5A1E67D` | -| `0x3FE8000` | 3 | `0x73E83886` | 3 | `0x780A05A5` | -| `0x3FEB000` | 3 | `0x73E83886` | 4 | `0x780A05A5` | -| `0x3FEE000` | 3 | `0x73E83886` | 0 | - | -| `0x3FF0000` | 1 | `0x57DDFFC2` | 1 | `0xCBA48304` | - -Mandy has three distinct archetype values in this set and Bert three; none resolves in the name -dictionary. - -The five tables are bound to `COM_KBOS_NEIGHB` through two people the mission's own text names, both -present as link hashes in the same five streams. It is a binding by cast, not by id: the public -`Pipework` name is the outside link between the id and the text, and a mission whose cast is not in the -dictionary still has no bridge. - -It does **not** turn `0x18BB2550`, `0x73E83886`, `0x57DDFFC2`, `0xA5A1E67D`, `0x780A05A5` or -`0xCBA48304` into model names. None resolves in the same dictionary, and the first dword changes per -state; it is an archetype/state hash, not a Mandy or Bert drawable. The table that would name those -archetypes is not in the readable archives. - -This is **one more binding, not a general solution**. The other 143 ids in the mission table remain -unattributed unless a character, schedule or other stable name gives them a bridge; joining ids to -tables is still an open problem. - -## Reading these tables - -`tools/mission_tables.py` reads the 32-byte record tables and the 64-byte pool elements they point -at, from inflated PSIN streams or a directory of carved `.bin` streams: - -``` -python -I tools/mission_tables.py [--json] [--limit N] -``` - -A lone path is the PSIN file: a file without the `PSIN` magic is one `ERROR: : not a PSIN container` -line and exit 2, while a folder is the place for the bare carved streams and is scanned as before. A PSIN -file that holds no records is still a clean run. - -It prints per-file record, chunk, state and entity counts, plus each resolved entity's archetype -hash, link hash, position and rotation. Pointers are scored in three encodings: **file-absolute**, -**linked pool** (`pool_block_base + (offset >> 4)`), and **block-indexed** (`kind` is a 1-based -block number and the byte offset is `(band << 12) | (poolOffset >> 4)`). A slot that does not match -the 64-byte position/rotation layout is reported as unresolved or skipped, not guessed. The tests -are synthetic (`python -I tests/test_mission_tables.py`) and need no game files. diff --git a/docs/mobile.md b/docs/mobile.md deleted file mode 100644 index 5ea35ca04..000000000 --- a/docs/mobile.md +++ /dev/null @@ -1,73 +0,0 @@ -# Mobile / arm64 port notes - -The PC port works because the Xbox Series CPU is x86-64, the same ISA a PC runs; `runtime/` maps the -PE image and executes it natively. On Apple silicon that stops working for exactly one reason: the -guest is x86-64 and the host is arm64. Everything else (PE loading, import shims, D3D12→graphics, -assets) is a port of layers that already exist. This note records the design and the current state -of the x86-64 → arm64 groundwork. - -## Route - -- **Static/AOT recompilation** is the only clean iOS path: lift the exe's `.text` to arm64 ahead of - time and ship a plain arm64 binary — no JIT entitlement, no sandbox fights. `.pdata` gives exact - function boundaries (the same table `RtlAddFunctionTable` uses for SEH on the PC side), so the - recompiler can enumerate code without guessing; `.xdata` unwinding has to be re-emitted as arm64 - unwind info or handled in the translated prologue/epilogue, which is the genuinely hard part. -- **Dynamic translation (FEX/Box64-style)** is the fallback on Android, where JIT and Vulkan are - unrestricted; on iOS it needs `com.apple.developer.cs.jit` or workarounds and is not the plan. -- **arm64 macOS first, iOS second.** Same ISA, same Metal, same Mach kernel, but no entitlement - fights and debuggable. If "mobile" matters more than "iOS", Android is dramatically easier: - native Vulkan (the whole GPU layer ports) plus unrestricted JIT. -- Graphics on Apple: **MoltenVK** over the existing Vulkan backend for a first pixel (no - conservative raster / geometry shaders in Metal — needs fallbacks), or **SPIRV-Cross → MSL** - for a native Metal backend longer term. - -## What exists today - -| Piece | Where | State | -|---|---|---| -| x86-64 decoder | `tools/x64_recomp.py` `disasm`/`decode_one` | prefixes/REX, ModRM+SIB, RIP-relative and moffs addressing, hi8 regs (`ah`/`ch`/`dh`/`bh`), `Iv`/`Iz`/`J` immediates incl. imm64, groups 1–5/8/15/1A/11, VEX stubs | -| arm64 assembler | `tools/x64_recomp.py` `Asm` | integer/logical/bitfield/shift/multiply/load-store/branch/system encoders, label fixups, `li()` with `pad4` for self-referential constant materialization | -| Translator | `tools/x64_recomp.py` `FunctionTranslator` | linear-sweep over decoded insns; lazy flag analysis picks arm-NZCV when one producer covers a consumer, else materializes canonical x86 EFLAGS in the ctx block; unsupported insns emit `brk` and land in `stats["unhandled"]` | -| Dispatch runtime | `tools/x64_recomp.py` `emit_rt` | `rt_dispatch` (guest pc → host pc through a generated table), `rt_mkflags` (NZCV+operands → canonical x86 EFLAGS; preserves NZCV), `rt_print` (semihosting result output) | -| Verification | `tools/x64_recomp.py` `build_test_kernel`/`run_kernel` | flat kernel image → `qemu-system-aarch64 -M virt -cpu cortex-a53 -kernel -semihosting`; guest `ret` off the sentinel stack exits and prints `R=xxxxxxxx` (guest edi) | -| PE census | `tools/recomp_census.py` | walks every `.pdata` function, decodes + translates it, reports coverage %, hazard mnemonics, indirect control flow, unwind-info flags | -| Tests | `tests/test_x64_recomp.py`, `tests/test_recomp_census.py` | hand-built byte fixtures only; exec tests skip when qemu is absent | - -### Translator contract (as implemented) - -- Guest regs `rax`–`r15` → host `x19`–`x27`, `x9`–`x15` (`GMAP`); `x28` = guest ctx pointer, - `x16` = dispatch target, `x17`/`x30` scratch/link, `x0`–`x3` temps. -- Ctx block: `+0x00` canonical x86 EFLAGS dword, `+0x08` last result, `+0x10`/`+0x18` last - operands (for AF/PF reconstruction), `+0x38` the semihosting exit block in test images. -- Flag model: arithmetic runs on arm NZCV directly; a conditional reads arm NZCV only when one - flag-writing producer covers every flag it needs (`_flag_analysis`, `_producer_ok`); otherwise - producers materialize x86 EFLAGS through `rt_mkflags` and consumers read the ctx word. - Sub-kind producers carry inverted C (arm borrow ≠ x86 borrow); `popf`/`sahf` reconstruct - NZCV from the x86 word; `rt_mkflags` restores NZCV before returning so calls can't clobber it. -- Control flow: direct branches/calls become arm `b`; `ret`, `jmp/call reg` and unknown targets - load the guest pc into `x16` and go through `rt_dispatch`; guest pc 0 is the exit sentinel. - -## Status and honest limits - -- Hand-written fixtures run end-to-end under qemu: arithmetic, loops, taken/not-taken signed and - unsigned branches, `setcc`/`cmov`, `adc`/`sbb` carry chains, shifts with CF, `movsx`, high-byte - regs, `call`/`ret`/`leave`/`pushf`/`popf`, `rep movsb`, `repne scasb`, moffs/LEA memory - addressing, and indirect jumps through the pc table — all hand-assembled, no game bytes. -- Not covered yet (each is an `unhandled` entry at translate time, not silent wrongness): SIMD/SSE - beyond decode, x87, `rcl`/`rcr`, `std` (DF=1), system/privileged insns, `int`/`syscall`, far - transfers. Real binaries are x87/SIMD-heavy, so coverage on the engine image will be far below - the fixture suite until those lands — `recomp_census.py` is the tool that will measure it. -- The engine image itself is still not in the repository (the exe obtained so far is a packaging - probe — `docs/boot.md`), so nothing here has run against real code. First real milestone is the - census over a genuine PE, then a same-behaviour run of a real function under qemu against a - native x86-64 run. - -## Next steps - -1. `recomp_census.py` on the real image: instruction histogram, coverage %, hazard list. -2. SIMD/SSE emitters (the largest hazard class on any modern binary), then `std`/RCL-RCR. -3. SEH story: translate `.xdata` prologue ops or run translated code inside a frame the host - unwinder can walk — needed before C++ `throw` works. -4. arm64 userland runner (Mach-O + `mmap` JIT-free) to replace the qemu harness on Apple silicon. -5. Vulkan backend under MoltenVK on macOS as the first graphics target; Metal backend later. diff --git a/docs/modding.md b/docs/modding.md deleted file mode 100644 index 41ee5daed..000000000 --- a/docs/modding.md +++ /dev/null @@ -1,189 +0,0 @@ -# Mods - -**Status: the mod format, loader and hook are in place; only the lookup's address in the executable is missing.** `gta6rt` reads every -`mods//mod.json`, checks it and logs what it would change. A swap takes effect once the game's -archetype lookup is hooked, and that needs the executable (RT-5): its address differs per version. - -A mod never contains game data. It names models the game already has, by the names (or `joaat` hashes) -the game uses, and says what to swap. Everything stays on your own PC, like the rest of the build. - -## Where mods go - -`gta6rt` looks in a `mods` folder next to `gta6rt.exe` (the port's folder, `Documents\Leonida` by -default), or in the folder `--mods DIR` names. Each mod is a folder with a `mod.json`; a folder without -one is ignored. Folders load in name order, and a later one wins when two swap the same model. - -```text -Documents\Leonida\ - gta6rt.exe - mods\ - mandy_prison_intro\ - mod.json -``` - -At start the runtime prints what it loaded, for example: - -```text -[rt] mods: Mandy in the prison intro -[rt] mods: archetype player_story000_00 (0xE472B687) -> cs_mandy (0xD7C0CDFF) -[rt] mods: 1 archetype swap(s) loaded; not applied yet: the archetype lookup hook for this executable is not known -``` - -## Managing them (`tools/leonida_mods.py`) - -`tools/leonida_mods.py` is the small mod manager. It writes only in the port's `mods` folder: it can create, -install, list, check, enable, disable, pack and remove mods. A package is a normal ZIP file (the `.leonidamod` -extension is only a name) with `mod.json` at its top level or inside one top-level folder. The installer refuses -paths that climb out of the package, links and manifests the runtime would reject; it never goes online and never -copies game data. - -On Windows, double-click **`Mods.bat`** for the Tkinter window (on Linux and macOS, run **`./Mods.sh`**; it needs -Tkinter, `python3-tk` on Debian and Ubuntu): choose the port folder, install a ZIP or folder, -toggle a mod, create a swap, pack or remove one, and launch `gta6rt` normally or as a dry run. The GUI uses the same -standard-library code as the CLI below. - -Point `--port` at the built port (the folder with `gta6rt.exe` and `game_path.txt`), or `--dir` at a mods folder: - -```powershell -python -I tools/leonida_mods.py gui -python -I tools/leonida_mods.py --port "D:\Games\Leonida" list -python -I tools/leonida_mods.py --port "D:\Games\Leonida" install .\mandy.zip -python -I tools/leonida_mods.py --port "D:\Games\Leonida" new lucia_to_mandy ` - --name "Mandy" --game-version 1.0.2.1 --swap player_story000_00=cs_mandy -python -I tools/leonida_mods.py --port "D:\Games\Leonida" disable mandy_prison_intro -python -I tools/leonida_mods.py --dir "D:\Games\Leonida\mods" check -``` - -`pack` writes an installed folder back to a ZIP for sharing; `uninstall` removes it. `run` is a convenience -launcher for the same options `gta6rt` already takes: - -```powershell -python -I tools/leonida_mods.py --port "D:\Games\Leonida" run --archetype-lookup 1A2B3C0 -``` - -Without the measured `--archetype-lookup` RVA the runtime still loads and reports the manifests but the swaps are -not applied, as above. The game executable itself is still needed; the manager does not supply it. - -The repository's `mods/` folder has four manifest-only examples. `mandy_prison_intro` is enabled; the other three -are installed disabled so a copied folder cannot surprise anyone or silently fight it: - -| Folder | Swap | State | -|---|---|---| -| `mandy_prison_intro` | `player_story000_00` -> `cs_mandy` | enabled | -| `lucia_cutscene_model` | `player_story000_00` -> `cs_lucia` | disabled | -| `monalisa_player_model` | `player_story000_00` -> `cs_monalisa` | disabled | -| `mandy_to_monalisa` | `cs_mandy` -> `cs_monalisa` | disabled | - -## mod.json - -```json -{ - "name": "Mandy in the prison intro", - "enabled": true, - "game_version": "1.0.2.1", - "archetype_swaps": [ - { "from": "player_story000_00", "to": "cs_mandy", "when": "always" } - ] -} -``` - -| Key | Meaning | -|---|---| -| `name` | Shown in the log and the launcher. Defaults to the folder name. | -| `enabled` | `false` keeps the mod installed but off. | -| `game_version` | The package version the mod was made for. | -| `archetype_swaps` | Each entry: when the game asks for the model `from`, it gets `to`. | - -`from` and `to` are model names, hashed with `joaat` (lower case, as the game does), or 32-bit hashes -written `0x…`. A swap is one step: a model swapped to another that is itself swapped is not followed -again, so two mods cannot loop. `when` is `always`; a narrower condition (one mission, one cutscene) is -refused until a hook provides the game's mission state, so a mod never silently does more than it says. - -`mod.json` is UTF-8. A byte-order mark in front is accepted (Notepad's "UTF-8 with BOM", Windows -PowerShell 5.1's `-Encoding utf8`). A UTF-16 file, which PowerShell 5.1's `>` writes, is skipped with -`mod.json is UTF-16; save it as UTF-8`. - -The format is in `runtime/src/mods.h`; `runtime/test/mods_test.cpp` (ctest `mods`) covers it. - -## The Mandy mod (`mods/mandy_prison_intro`) - -Lucia's player model is `player_story000_00` (model id `0xE472B687`); Mandy is `cs_mandy` -(`0xD7C0CDFF`). Both ids are measured in the packs tables ([character_skeleton.md](character_skeleton.md), -"The Mandy search") and are the `joaat` of those names. Mandy has no drawable of her own: `cs_mandy` -uses the same shared female body as Lucia, and her look comes from her own nine-entry variation table. -Swapping the archetype therefore hands the game Mandy's model info, variation table included, rather -than pasting a mesh over Lucia; the game assembles her as it would in her own scenes. - -What is not known yet, and decides how far the swap reaches: - -- **The intro.** The prison intro's outfit is a component variation on `player_story000_00`. Which - mission or cutscene id the intro is, and whether its outfit components exist on `cs_mandy`, is not - measured; with `when: always` Mandy replaces Lucia everywhere the player model is asked for. -- **Mandy's components.** None of the 18 hashes in her variation table resolves to a name, so her - head, hair and outfit parts are only reachable through her own model info, not by name. - -## Day one: finding the hook - -The swap needs one function in the executable: the archetype lookup by name hash (RAGE's -`fwArchetypeManager::GetArchetypeFromHashKey`). `scripts/first_look.ps1` already ranks candidates with -`tools/find_hash_lookup.py` (report `hash_lookup.json`): it finds where the code loads `0xE472B687` and -`0xD7C0CDFF`, takes the functions called right after, and orders them by how many direct callers the -whole image has. Run it alone with `python -I tools/find_hash_lookup.py `. What it automates: - -1. **Constant search.** The player model id `0xE472B687` should appear as an immediate in the code that - sets up the story player. Its callers pass it to the lookup (or to a function that does). -2. **Shape.** The lookup takes a 32-bit hash (and an optional out-index), hashes into a bucket table - and walks a chain comparing a 32-bit key; it is called from hundreds of sites. -3. **Cross-check.** Called with `0xD7C0CDFF` it must return a valid archetype too (`cs_mandy` is a live - model id: a `story000.rpf` cutscene table uses it). - -Then pass it to the runtime: - -```powershell -gta6rt.exe --dry-run game_scarlett_master.exe --archetype-lookup 1A2B3C0 -``` - -`--archetype-lookup RVA[,ARG]` (hex RVA; `ARG` 0 when the hash is the first argument, 1 when it is the -second, as in a member function) hooks the function right after the image is mapped, before any of its -code runs (`runtime/src/code_hooks.h`). It does not patch the function: every direct `call` and `jmp` -to it in the image's code is pointed at a thunk that passes the hash through -`leonida::mods::active().remap()` and continues into the original with every other argument as it was. -The log line reports how many call sites were redirected, so a `--dry-run` with a candidate RVA shows at -once whether it is the lookup (hundreds of callers) or not (a handful, or none). ctest `code_hooks` runs -the thunk on small x64 functions in memory. - -That RVA is the only version-specific piece; it can go in `game/xbox-1.0.2.1.json` once confirmed, and -the manifests stay as they are. - -## First-person view (`mods/first_person`) - -```json -{ "camera": { "view_mode": "first_person", "first_person_value": 4, "contexts": [0] } } -``` - -`camera.view_mode` is `first_person` or `default` (leave the game's choice). The game picks a view mode per -camera context (on foot, in a vehicle, ...) with a getter that takes the context and returns an enum; the -mod answers `first_person_value` for the listed `contexts` (every context when the list is left out) and -the game's own answer otherwise. When several enabled mods have a `camera` section, the last folder wins. - -**Evidence that the engine has a first-person view.** The camera metadata classes GTA V uses -(`camFirstPersonShooterCameraMetadata`, `camFollowPedCameraMetadata`, ...) do not appear by `joaat` in the -carved `common`, `data` or `script` streams, but the game's own tuning data refers to a first-person view -in several systems: a ladder/mount tunable `FirstPersonDirectionDot`, a `UseFirstPersonCameraMatrix` flag on -every cloth-collision capsule (horse saddle and satchel capsules among them, so the code is RDR2's branch of -the engine, which shipped a first-person mode), a hit-reaction `RecoveryDirection` of `FIRST_PERSON_VIEW`, -and a `firstpersonshooter_hud` UI texture. So the mod switches on a mode the engine has rather than building -a camera. Whether the game exposes it to the player is not known. - -**ASSUMPTION:** three things to confirm in the executable: that the view mode is chosen through one getter of the form -`mode = get(context)`, that context 0 is on foot, and that first person is enum value 4 (GTA V's -`camViewModeSettings` order: third person near, medium, far, cinematic, first person). All three are -settings in `mod.json`, so a different answer changes the manifest, not the runtime. - -**Day one:** find the getter, then run `gta6rt --dry-run --view-mode-getter RVA` and check the log -line's count of redirected calls. Leads: the code that reads the view-mode input (GTA V's -`INPUT_NEXT_CAMERA`, an action hash), the switch over the five view-mode values that selects a camera -metadata per mode, and the callers of the `UseFirstPersonCameraMatrix` check in the cloth code (they ask -whether the active view is first person). The hook (`hook_image_results` in `runtime/src/code_hooks.h`) runs -the original and overrides its result; it is for getters with at most four register arguments and an -integer result. ctest `code_hooks` and `mods` cover the thunk and the override. diff --git a/docs/models.md b/docs/models.md deleted file mode 100644 index 85b805feb..000000000 --- a/docs/models.md +++ /dev/null @@ -1,873 +0,0 @@ -# Model recovery - -Measured state of `tools/rpf9dump models` on the Xbox Series 1.0.2.1 package, and the -upstream `rpf9-explorer` fixes that close it. The fixes are merged upstream and the submodule is -pinned at `e293917`, where a full ten-archive re-count recovers **382,781 models** (**0 decode -failures**), up from 350,251 at `917e9b9` and 190,792 at `c3708fb`. - -Before the fix, the exporter did not reject any vertex or index layout in the tested archives. It -dropped valid models in three validation paths, all in `third_party/rpf9-explorer` at commit -`48557ea`. - -## Upstream status - -[Leonida issue #29](https://github.com/ItsNotRexed/Leonida/issues/29) tracks this work. The decoder -fix in [rpf9-explorer PR #1](https://github.com/breadbbbb/rpf9-explorer/pull/1) is merged, and -`third_party/rpf9-explorer` is now pinned at upstream `e293917` (was `917e9b9`, originally -`48557ea`). Commits up to `917e9b9` added the `packs.rpf` drawable-dictionary roots (one drawable -per entry), the TTPF compact/array/cubemap/volume layouts, and the external drawable-skeleton -reader. Commits `917e9b9..e293917` add upstream `v1.2` model-discovery changes (PRs #8–#12: -optional fragment pointers, skipping texture dictionaries in drawable-dictionary scans, 16-bit -bone-palette indices, probe-count parity, and zero-radius drawables) plus BCPack BC1/BC3/BC4/BC5 -decoding (PR #7). A full ten-archive re-count at `e293917` recovers **382,781 models** (**+32,530** -over `917e9b9`'s 350,251) with **0 decode failures**, **55,417 fragments** and **2,636,248,990 -triangles** (the `levels.rpf` cells from a full export, see the table note), and the earlier -`917e9b9`, `c3708fb`, and `48557ea` measurements are kept below as controls. This page records the -measured state; it is not a competing patch. - -PR #1 reports 190,792 of 190,792 recognized candidates across the ten archives configured in -Leonida, including 169 previously rejected candidates (also verified after archive readback). A -later full-archive run at the same head independently reproduced the ten-archive total: 190,792 -candidates, 190,792 recovered, read back and decoded, 0 decode or readback failures, no duplicate -model names, and 2.22 billion triangles (the pre-fix export was 155,598 models / 1.95 billion -triangles). Issue #29's run uses its own recognized-candidate set and covers primary-LOD geometry; -the pre-fix counts below use `rpf9dump`'s page-scan candidates and export every recovered -drawable/LOD variant. The two sets are different scopes, not contradictory. - -### `packs.rpf` after the pin bump - -`packs.rpf`'s `.#dr` pages are drawable-dictionary roots, not drawables, so the old candidate -scan never saw them. The dictionary walk recovers **23,720 dictionary children** from that -archive at both `917e9b9` and `e293917`; the fragment count grew from **314** to **2,865** when -upstream `v1.2` began recovering zero-radius fragments. The archive total is therefore -**24,034 models at `917e9b9`** (23,720 children + 314 fragments) and **26,585 at `e293917`** -(23,720 + 2,865), against 314 at `c3708fb`. A full `rpf9dump models` export at `917e9b9` -reported **`ok=24,034 fail=0 skip=0` in 263 s** (0 embedded textures); the OBJs and manifest are -local. The 314 `48557ea`/`c3708fb` entries in the table below are the pre-pin control, not the -current `packs.rpf` result. - -### Full-archive re-count at `e293917` - -A fresh scan, recovery, and full `RageModelDecoder.Decode` readback across all ten archives in -`MODEL_ARCHIVES` (no index cache; `RpfPreview.Core` at `e293917`, .NET 8/10 Release) measures the -effect of upstream `v1.2` PRs #8–#12: - -| Archive | Candidates | Models at `e293917` | Dict children | Standalone | Fragments | Bone-bound | Triangles | Rejects | Delta vs `917e9b9` | -|---|---:|---:|---:|---:|---:|---:|---:|---:|---:| -| `data.rpf` | 2,921 | **3,175** | 268 | 2,907 | 1,758 | 2,891 | 3,387,016 | 0 | +594 | -| `pack/shared_minigame000/...` | 1,058 | **1,294** | 317 | 977 | 10 | 18 | 16,843,903 | 0 | +6 | -| `pack/core_restofworld/...` | 924 | **936** | 808 | 128 | 53 | 849 | 1,239,596 | 0 | +51 | -| `pack/story000_restofworld/...` | 1 | **3** | 3 | 0 | 0 | 0 | 2,620 | 0 | 0 | -| `pack/story000/story000.rpf` | 4,195 | **7,461** | 4,156 | 3,305 | 0 | 0 | 39,861,747 | 0 | +1 | -| `packs.rpf` | 26,389 | **26,585** | 23,720 | 2,865 | 2,865 | 26,585 | 64,966,572 | 0 | +2,551 | -| `levels.rpf` | 235,330 | **343,327** | 130,239 | 213,088 | 50,731 | 59,544 | 2,509,947,536 | 71 | +29,327 | -| `textures.rpf` | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | -| `common.rpf`, `core_restofworld001` | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | -| **Total** | **270,819** | **382,781** | **159,511** | **223,270** | **55,417** | **89,887** | **2,636,248,990** | **72** | **+32,530** | - -`levels.rpf` was first counted with `count.exe recover --verify`, which reports candidates, models, -dictionary children, standalone models, rejects and decode failures only, so its fragment, -bone-binding and triangle cells were open. A full `rpf9dump models ` export at -`e293917` (25 min, about 340 GB of OBJ, deleted afterwards) fills them from its manifest: 235,330 -candidates, 235,259 recovered, 71 not recovered, 343,327 entries, `fail=0`, the recovery count to -the row. Its `Drawable` field is set on 130,239 entries and null on 213,088, the dictionary-children -and standalone cells above (3,694 dictionaries have a single child, so counting shared offsets -instead gives 126,545 / 216,782). `IsFragment` is true on 50,731 entries and `HasBoneBindings` on -59,544; `Tris` sums to 2,509,947,536. The same counting on a fresh `data.rpf` export gives that -row's 268 / 2,907, 1,758, 2,891 and 3,387,016. The other archives measure 4,686 fragments, 30,343 -bone-bound and 126,301,454 triangles. - -Every recovered entry was read back from its archive segments and decoded through -`RageModelDecoder.Decode`: **382,781 / 382,781 decoded, 0 decode failures**. The other archives -measure **236,311 meshes**, **104,183,438 vertices**, **126,301,454 triangles** and **512 embedded -textures**; `levels.rpf` adds 3,854,587 meshes, 2,364,218,711 vertices, 2,509,947,536 triangles and -1,293 embedded textures (the export's own summary line), for **4,090,898 meshes**, **2,468,402,149 -vertices**, **2,636,248,990 triangles** and **1,805 embedded textures** over all ten archives. - -What moved between `917e9b9` and `e293917`: - -- **Standalone fragments (+32,505 standalone models total).** Upstream - [rpf9-explorer#8](https://github.com/breadbbbb/rpf9-explorer/pull/8) (optional fragment pointers) - accounts for the bulk of the gain across `levels.rpf` (+29,313 standalone), `packs.rpf` (+2,551 - fragments, all bone-bound), `data.rpf` (+594), `core_restofworld` (+40 standalone), and - `shared_minigame000` (+6). -- **Texture-dictionary false positives eliminated (1,242 → 1).** Upstream - [rpf9-explorer#9](https://github.com/breadbbbb/rpf9-explorer/pull/9) removes all 1,242 texture - dictionaries that were previously proposed as model candidates in `levels.rpf` (1,009 → 0), - `data.rpf` (75 → 0), `core_restofworld` (140 → 0), and `shared_minigame000` (18 → 0). Only one - texture-dictionary candidate remains across all ten archives (in `textures.rpf`; rejected cleanly, - and recovered by `Rpf9TextureRecovery`). -- **Probe caps and zero-radius drawables (+25 dictionary children plus capped standalones).** - Upstream [rpf9-explorer#11](https://github.com/breadbbbb/rpf9-explorer/pull/11) recovers the 29 - previously capped candidates (+1 in `story000.rpf`, and +14 dictionary children plus capped - standalones in `levels.rpf`). Upstream - [rpf9-explorer#12](https://github.com/breadbbbb/rpf9-explorer/pull/12) recovers all 11 zero-radius - dictionary children in `core_restofworld` (797 → 808); `story000_restofworld.rpf` already - recovered its 3 models at `917e9b9`, so its delta is 0. -- **Remaining 72 rejects (down from 1,282 at `917e9b9`).** Aside from the single texture-dictionary - candidate in `textures.rpf`, all 71 remaining rejects are in `levels.rpf` (0 texture dictionaries, - 0 zlib checksum errors). Sampled headers are fragment candidates (`LooksLikeFragment == true`) - whose `ProbeRequiredExtents` reports `MetadataComplete == false` on the first zlib block with - `RequiredSystemBytes` extending into subsequent 16-byte-aligned zlib continuation blocks. - -Method checks: sharded 4 MiB `FindCandidateOffsets` was verified exact-equal against the -single-threaded scan on `packs.rpf` (`26,389 == 26,389`), and `tools/rpf9dump models` end-to-end -OBJ + manifest export was spot-checked on `story000_restofworld.rpf` (`ok=3 fail=0 skip=0`) and -`data.rpf` (`ok=3175 fail=0 skip=0`). - -### Other archives at `917e9b9` - -A fresh scan/recover at the new pin (no cache; `models/3`) shows the same pattern in every -archive with drawable dictionaries: the `c3708fb` recovery is the non-child count, and the new -entries are dictionary children. - -| Archive | Candidates | Models at `917e9b9` | Dictionary children | `c3708fb` | -|---|---:|---:|---:|---:| -| `data.rpf` | 2,402 | **2,581** | 268 | 2,313 | -| `pack/shared_minigame000/...` | 1,070 | **1,288** | 317 | 971 | -| `pack/core_restofworld/...` | 1,024 | **885** | 797 | 88 | -| `pack/story000/story000.rpf` | 4,195 | **7,460** | 4,156 | 3,305 | -| `packs.rpf` | 23,838 | **24,034** | 23,720 | 314 | -| `levels.rpf` | 206,981 | **314,000** | 130,225 | 183,801 | -| `story000_restofworld` | 1 | **3** | 3 | 0 | -| `common`, `textures`, `story000_script`, `core_restofworld001` | 0 | 0 | 0 | 0 | -| **Total** | **239,511** | **350,251** | **159,486** | **190,792** | - -### Re-count at `e293917` - -A full `rpf9dump models` re-run over the same archives at the current pin (the manifests are -local; `levels.rpf` was exported separately, see the table note above): - -| Archive | Rows | Non-fragment | Fragments | Delta vs `917e9b9` | -|---|---:|---:|---:|---:| -| `packs.rpf` | **26,585** | 23,720 | 2,865 | +2,551 | -| `data.rpf` | **3,175** | 1,417 | 1,758 | +594 | -| `pack/shared_minigame000/...` | **1,294** | 1,284 | 10 | +6 | -| `pack/core_restofworld/...` | **936** | 883 | 53 | +51 | -| `pack/story000/story000.rpf` | **7,461** | 7,461 | 0 | +1 | -| `story000_restofworld` | **3** | 3 | 0 | 0 | -| `common`, `textures`, `story000_script`, `core_restofworld001` | 0 | 0 | 0 | 0 | -| **Total, excluding `levels.rpf`** | **39,454** | **34,768** | **4,686** | **+3,203** | -| `levels.rpf` | **343,327** | 292,596 | 50,731 | +29,327 | -| **Total** | **382,781** | **327,364** | **55,417** | **+32,530** | - -The gain outside `levels.rpf` is fragments: upstream `v1.2` PRs #8-#12 recover zero-radius -fragments that the earlier export skipped (2,551 in `packs.rpf`, 594 in `data.rpf`), plus one -drawable in `story000`. `story000_restofworld` has the same 3 models at both pins, so its delta -is 0. - -`levels.rpf` was re-counted at `e293917` (10 shards over 235,330 candidates): **343,327 models** -(130,239 dictionary children + 213,088 standalone), against 314,000 at `917e9b9` (206,981 -candidates; 130,225 children + 183,801). The +29,327 is a recovery count, not a row-for-row delta. -The full OBJ export at `e293917` (table note above) gives the same 343,327 rows. - -The last column is the `c3708fb` recovery for comparison. `story000`'s standalone count is -3,304 vs 3,305; the full new-pin standalone total is 190,765, 27 below the `c3708fb` 190,792. -Those 27 are not merged duplicates: they are the 27 models with more than 256 geometries that the -probe rejects at `917e9b9` (26 in `levels.rpf`, 1 in `story000`; see -[rejected candidates](#rejected-candidates-at-917e9b9)). The new entries are **159,486 -drawable-dictionary children**: one model per embedded drawable in a dictionary root, not new -pages. `core_restofworld` recovers 873 of its 1,024 candidates (885 models); the 151 rejects are -140 texture dictionaries and 11 drawable dictionaries whose drawable has radius 0. - -`levels.rpf` is the sum of ten parallel recovery shards over 206,981 candidates: **314,000 -models**, 130,225 dictionary children, 183,775 standalone. 1,037 candidates are rejected: the -1,009 in the last shard are texture dictionaries, not models, and 28 more in shards 1 to 7 are -models the probe caps reject (see [rejected candidates](#rejected-candidates-at-917e9b9)). The -`levels.rpf` full export was not re-run, so its triangle total is not re-run here. - -### Rejected candidates at `917e9b9` - -Every candidate of each model-bearing archive was run through `RecoverAtOffsets` on its own and, -for each reject, through a copy of `TryResource` that records which check drops it (it agrees -with the real code on all 206,981 `levels.rpf` candidates). Measured on the 1.0.2.1 package: - -| Archive | Rejects | Texture dictionaries | Geometry cap (`:351`) | List 4 cap (`:387`) | Radius 0 | -|---|---:|---:|---:|---:|---:| -| `levels.rpf` | 1,037 | 1,009 | 26 | 2 | 0 | -| `data.rpf` | 75 | 75 | 0 | 0 | 0 | -| `pack/core_restofworld/...` | 151 | 140 | 0 | 0 | 11 | -| `pack/shared_minigame000/...` | 18 | 18 | 0 | 0 | 0 | -| `pack/story000/story000.rpf` | 1 | 0 | 1 | 0 | 0 | -| `packs.rpf` | 0 | 0 | 0 | 0 | 0 | - -Line numbers are in `third_party/rpf9-explorer/Core/RageModelDecoder.cs`. - -- **Texture dictionaries (1,242).** `LooksLikeDrawableDictionary` (`:78`) checks only the - dictionary header, which texture dictionaries share, so they become model candidates and fail - at `:314` because their values are not drawables. `Rpf9TextureRecovery` recovers all 1,242. - In `levels.rpf` they are the archive's last 0.12 GiB, each a 256- to 880-byte system block - and a graphics block. None of them overlaps a recovered model. Upstream - [rpf9-explorer#9](https://github.com/breadbbbb/rpf9-explorer/pull/9) stops the scan from - proposing them. -- **Geometry cap (27).** The probe allows at most 256 geometries per model (`:351`), while - `Decode` allows `MaxMeshes`, 1,024 (`:535`). These models have 263 to 377 geometries. -- **List 4 cap (2).** The probe caps renderer list 4 at 4,096 entries (`:387`) but never uses - that count for sizing. These two dictionaries have 5,078 and 5,461. -- **Radius 0 (11).** Drawable dictionaries whose drawable has a zero radius and non-empty bounds, - rejected by `LooksLikeDrawableHeader` (`:124`) through `:314`. Whether they decode otherwise - has not been checked. - -[rpf9-explorer#11](https://github.com/breadbbbb/rpf9-explorer/pull/11) raises both probe caps. -With it, the 29 capped candidates recover (41 models, 3.25 million triangles), and every -candidate already recovered decodes exactly as before in all six archives above. - -One `levels.rpf` copy measured for this showed a 1,038th reject: a zlib block whose Adler-32 -fails because of a single flipped bit in that copy (flipping it back restores the stored -checksum). It is local corruption, not part of the package, and is left out of the table. - -## Independent validation - -Scoped validation at PR #1 head `c3708fb` with .NET 8.0.428 on the real package: - -| Scope | Candidates | Recovered | Rejects | Readback | -|---|---:|---:|---:|---:| -| `data.rpf` full | 2,313 | 2,313 | 0 | 2,313 / 2,313 | -| `common.rpf` | 0 | 0 | 0 | 0 / 0 | -| `levels.rpf` 0-8 GiB | 28,748 | 28,748 | 0 | 28,748 / 28,748 | -| `levels.rpf` 4-4.5 GiB | 4,010 | 4,010 | 0 | 4,010 / 4,010 | -| `levels.rpf` 12-16 GiB | 10,429 | 10,429 | 0 | 10,429 / 10,429 | - -The `data.rpf` export reported `ok=2,313 fail=0 skip=0`, 2,313 unique OBJ names, and 0 duplicate -stems. All 963 pre-PR misses were recovered, and all 1,350 pre-PR OBJs were byte-identical to their -pre-PR versions. The PR smoke test passes; v1/v2 cache round-trip and two raw-segment entries were -verified. - -Caveat: this scoped run did not scan the full `levels.rpf`; the full pass below covers it. The -`data.rpf` OBJ text is the only byte-identical file comparison; the full pass counted decoded -models, not OBJ bytes. No counterexample appeared in the tested scopes. - -### Full-archive run - -A full pass at the same head over `levels.rpf` (70.9 GiB) and the other model-bearing archives -reproduced the ten-archive total. The `48557ea` column is the pre-fix control: - -| Archive | Candidates | `48557ea` | `c3708fb` | -|---|---:|---:|---:| -| `levels.rpf` (full, 70.9 GiB) | 183,801 | 149,811 | **183,801** | -| `pack/story000/story000.rpf` | 3,305 | 3,303 | **3,305** | -| `data.rpf` | 2,313 | 1,350 | **2,313** | -| `pack/shared_minigame000/shared_minigame000.rpf` | 971 | 783 | **971** | -| `packs.rpf` | 314 | 314 | 314 | -| `pack/core_restofworld/core_restofworld.rpf` | 88 | 37 | **88** | -| `common`, `textures`, `story000_restofworld`, `core_restofworld001` | 0 | 0 | 0 | -| **Total** | **190,792** | **155,598** | **190,792** | - -The `packs.rpf` row is the pre-dictionary-root control: at `917e9b9` that archive recovers -24,034 models (26,585 at `e293917`), and the other archives' new-pin counts are in the table above. -The rows here are the `c3708fb` measurements (190,792 models); the `917e9b9` re-count is 350,251, -and the `e293917` re-count outside `levels.rpf` is 39,454. The `e293917` triangle totals of all ten -archives, `levels.rpf` included, are in the table above. - -At `c3708fb`, every candidate is recovered, read back and decoded: 0 decode failures, 0 readback -failures, no duplicate model names, and 2.22 billion triangles (1.95 billion before). The -169-candidate subset is a different scope and was not isolated here. - -## How the exporter works - -``` -rpf9dump models [--start BYTES] [--length BYTES] -``` - -`FindCandidateOffsets` scans 4 MiB blocks for a page-aligned 16-byte zero prefix followed by a zlib -stream at page offset +16. It inflates the first 176 bytes and keeps the offset when the result has -a drawable or fragment header (`RageModelDecoder.LooksLikeResource`). `RecoverAtOffsets` follows -the following zlib blocks, splits the inflated bytes into the system segment and the graphics -segment, probes the extents, and calls `RageModelDecoder.Decode`. - -`--start`/`--length` scan one window of the file instead of the whole archive. Neither `models` -nor `textures` needs the archive directory: the entry list comes from this run's scan or from the -index cache, and every resource is read from its own compression blocks -(`tools/rpf9dump/Segments.cs`). A window is therefore a raw slice - a copy of `levels.rpf` from an -offset, which has no `9FPR` header - and the scan covers exactly the slice. A sub-range is never -written to the index cache, which describes a whole file; the manifest records `Scan.Start` and -`Scan.Length` for it. One measured 1 GiB slice of `levels.rpf`: 1,228 models scanned, recovered, -decoded and exported in about 2 s (497 MB of OBJ and manifest). - -To locate a named drawable before decoding, `tools/rpf9_names.py` indexes the measured -`name.#dr`/`#ft`/`#dd` spellings in bounded zlib prefixes without the encrypted TOC; see -[resource_names.md](resource_names.md). - -For each returned entry, `tools/rpf9dump/Program.cs` reads the segments, splits at -`ResourceSystemBytes`, decodes the model, writes one OBJ, and writes the manifest. The manifest is -`//models/manifest.json` with `src`, `Count`, and `Items[]`. Each item records the -offset, OBJ name, model name, mesh/vertex/triangle counts, fragment and bone-binding flags, bounds, -per-mesh shader indices, embedded textures, and material texture references. - -Three arrays describe the geometries one by one, in the same order as the OBJ's `o` groups: -`MeshTris` (triangles), `MeshModels` (the position of the model in the drawable's primary-LOD model -list) and `MeshGeoms` (the position of the geometry in that model). That pair is the geometry index -a dehydrated BLAS leaf stores ([bvh.md](bvh.md) §4a), which is what `tools/bvh_match.py` matches on; -`MeshShaders` maps each geometry to its entry in `Materials`, and therefore to its shader name hash. - -The manifest has no failure, skip, or layout fields. `Program.cs` increments `fail` only when a -model entry returned by the carver fails `RageModelDecoder.Decode`; `skip` is not used in models -mode. A printed `fail=0 skip=0` therefore means "no decoded entry failed", not "nothing was -rejected". - -## Pre-fix measured counts - -Counts below are from submodule `48557ea` before the upstream fix: - -| Archive | Candidates | Recovered | Not recovered | -|---|---:|---:|---:| -| `common.rpf` | 0 | 0 | 0 | -| `textures.rpf` | 0 | 0 | 0 | -| `data.rpf` | 2,313 | 1,350 | 963 | -| `levels.rpf`, 0-8 GiB sample | 28,748 | 26,184 | 2,564 | -| `levels.rpf`, 4-4.5 GiB sample | 4,010 | 3,821 | 189 | - -`levels.rpf` was sampled, not scanned end to end. Its first 3.9 GiB held no model candidates. -All counts come from the same package and the same `48557ea` submodule. - -The 2,313 candidates in `data.rpf` decode to 2,313 unique model names once the checks below are -relaxed, so the 963 missing entries are valid models, not duplicate or false candidates. - -## Pre-fix rejection classes - -Observed in `data.rpf` with the unmodified carver: - -| Class | Count | Location | -|---|---:|---| -| Drawable bounds do not contain a geometry's bounds | 231 | `Core/RageModelDecoder.cs:377` | -| Graphics block has non-zero bytes after `RequiredGraphicsBytes` | 259 | `Core/Rpf9ModelRecovery.cs:140` | -| Fragment system block with trailing bytes; next block not requested | 388 | `Core/Rpf9ModelRecovery.cs:132-133` | -| A following block was found, but no split decoded | 67 | `Core/Rpf9ModelRecovery.cs:141-143` | -| No following block was found | 18 | `Core/Rpf9ModelRecovery.cs:112-113` | - -In the `levels.rpf` 0-8 GiB sample the same diagnostic classes were 978 bounds failures, 190 -graphics-trailing cases, 1,200 cases where a system block was not followed to the next block, and -196 cases where a block was found but no split decoded. - -The last two classes are symptoms of the splitter. The first three are the actionable causes. - -Cause isolation on `data.rpf`: - -| Change | Recovered | -|---|---:| -| Unmodified carver | 1,350 | -| Relax system trailing-byte check only | 1,408 | -| Relax graphics trailing-byte check only | 1,609 | -| Relax drawable bounds check only | 1,581 | -| Truncate both spans to the probed extents | 1,969 | -| Truncate both spans and relax drawable bounds | 2,313 / 2,313 | - -`RequiredSystemBytes` and `RequiredGraphicsBytes` are the ends of the last structures the probe -actually validated. Bytes after those ends are legal: system blocks can carry inline strings, and -a graphics zlib block can carry trailing data. Decoding the full spans and then requiring every -trailing byte to be zero rejects valid resources. - -## Measured diagnosis and the upstream fix - -This is our measured diagnosis, not a competing patch. The two hunks below record the minimum our -runs isolated; PR #1 implements this area more broadly, including cluster marker and palette -handling, packed-position bounds, and mixed raw/zlib block handling, and its exact code may differ. -The hunks are against `breadbbbb/rpf9-explorer` at `48557ea` and are not applied to this checkout. - -```diff ---- a/Core/Rpf9ModelRecovery.cs -+++ b/Core/Rpf9ModelRecovery.cs -@@ -132,3 +132,2 @@ -- if (extent.RequiredSystemBytes > prefixLength || -- system.AsSpan(extent.RequiredSystemBytes).IndexOfAnyExcept((byte)0) >= 0) continue; -+ if (extent.RequiredSystemBytes > prefixLength) continue; - int graphicsLength = total - prefixLength; -@@ -140,3 +139,4 @@ -- if (graphics.AsSpan(extent.RequiredGraphicsBytes).IndexOfAnyExcept((byte)0) >= 0) continue; -- RageModel? decoded = RageModelDecoder.Decode(system, graphics); -+ RageModel? decoded = RageModelDecoder.Decode( -+ system.AsSpan(0, extent.RequiredSystemBytes), -+ graphics.AsSpan(0, extent.RequiredGraphicsBytes)); - if (decoded is null) continue; -``` - -```diff ---- a/Core/RageModelDecoder.cs -+++ b/Core/RageModelDecoder.cs -@@ -373,8 +373,6 @@ - var mesh = ReadMesh(geometry, $"model_{mi}_geometry_{gi}", partMin, partMax, boneCount); - if (shaderMapping is int mapping) - mesh = mesh with { ShaderIndex = U16(sys, mapping + gi * 2) }; -- float tolerance = Tolerance(min, max); -- Require(Contains(min, max, partMin, tolerance) && Contains(min, max, partMax, tolerance)); - meshes.Add(mesh); - } - } -``` - -The bounds check is safe to remove because `ReadMesh` still validates every referenced index and -every decoded vertex against the geometry's own part bounds (`Core/RageModelDecoder.cs:643-646`). -The deleted check compared each geometry with the drawable-level bounds, which is not a valid -envelope for a drawable with multiple LOD models. - -The narrow two-hunk experiment in a temp copy recovered: - -- `data.rpf`: 2,313 / 2,313 entries. -- `levels.rpf` 4-4.5 GiB: 4,010 / 4,010 entries. -- `levels.rpf` 0-8 GiB: 28,746 / 28,748 entries. - -The two remaining 8 GiB cases are not tag rejections: one graphics extent is 48 bytes larger than -the assembled block and the next zlib stream starts 3,419 bytes past it; one model with 32 -geometries throws inside `ReadMesh`. PR #1's broader patch resolves both; at `c3708fb` the same -sample has 0 rejects. - -## Vertex and index tags - -The pre-fix tag survey (`data.rpf` plus the 0-8 GiB `levels.rpf` sample) contains 198,286 geometry -records. No unhandled layout tag appears: - -| Item | Observed | -|---|---| -| Position `(size, format)` | `(8, 16)` on 195,182 geometries; `(12, 6)` on 674; no other pair | -| Index buffer stride | 4 on every geometry | - -`(12, 6)` and `(8, 16)` are the only position encodings accepted by -`Core/RageModelDecoder.cs:244` and `:548-571`. The index stride must be 4 -(`Core/RageModelDecoder.cs:249` and `:576`). Other values would be rejected, but none occur in -`data.rpf` or the `levels.rpf` samples. `data.rpf` uses `(8, 16)` exclusively; the 674 -`(12, 6)` geometries are spread over 256 models in the levels sample. - -## Vehicle ratings and performance estimates - -`common.rpf` has one `CVehicleBaseRatingsAndEstimatesMap` XML document (see [gamedata.md](gamedata.md)): a -`Map` of 252 `Item key=""` entries, each with four blocks. Counts and ranges only; no model names. - -| Block | Fields | -|---|---| -| `estimatesRoad`, `estimatesOffroad` | `fTopSpeed`, `fCornerSpeed`, `fAccelerationTime`, `fBrakingTime`, `fStandingQuarterTime`, `fStandingQuarterSpeed`, `fAvgLatTraction` | -| `ratingsRoad`, `ratingsOffroad` | `fOverallRating`, `fSpeedRating`, `fHandlingRating`, `fAccelerationRating`, `fBrakesRating` | - -- **Keys are vehicle model names.** The 252 keys are distinct plain names (no hex hashes), and all 252 are the - base name of a `.yft` in the local archive catalog. 245 of them are also among the 319 models of the - distant-light recipes; 74 of those 319 have no rating entry. -- **Ratings are not fractions.** All ten rating fields have a minimum of exactly 10 and medians of 142 to 585, - with maxima up to 1,327 (`fAccelerationRating`). `fOverallRating` is not the mean of the other four: the two - differ by a median of 38 and agree within 0.01 in only 10 of 504 cases. -- **Estimates look like SI units.** Road `fTopSpeed` has a median of 44.3 and a maximum of 77.4 (m/s would make - that 160 and 279 km/h); `fStandingQuarterTime` has a median of 15.8, the right size for seconds over a - quarter mile; `fAvgLatTraction` has a median of 1.42 on road and 0.92 off road (lateral g would fit). Offroad - speeds are lower than road ones (median top speed 19.3). -- **Sentinels.** On each surface, 11 entries have every estimate 0 and 10 more have zero speeds with an - infinite time (`inf`). `inf` occurs in 38 road and 99 offroad blocks overall, so a parser must accept `inf` - in these fields (it reads as "never reaches the test speed or distance"). -- **`fOverallRating` is a weighted mean of the other four ratings** (measured, confirmed to float noise) on the - 345 of the 504 rating blocks whose four parts are all above 10: there `fOverallRating` = 0.21 - `fSpeedRating` + 0.38 `fHandlingRating` + 0.40 `fAccelerationRating` + 0.01 `fBrakesRating`, with a residual - of at most 7e-5. The four weights sum to 1, so handling and acceleration weigh about twice speed and brakes is 1%. - Differencing a key's road and offroad blocks gives the same 0.2100 / 0.3800 / 0.4000 / 0.0100 on the 139 keys - that are above 10 on both surfaces, so the weights do not depend on the surface. -- **The overall has the same observed minimum of 10.** The other 159 rating blocks each have at least one part - at exactly 10, and the formula does not hold for them: they sit up to 4.1 below the weighted mean, and 24 of - them carry an `fOverallRating` of exactly 10. No block without a part at 10 deviates. The exports show only - this minimum; they cannot tell where, or whether, the engine clamps. -- **Scale.** The ratings are continuous floats, not a 0-1 or 0-100 score: 342 to 451 distinct values per field - over the 504 blocks, a floor of exactly 10, and `fAccelerationRating` the only field past 1,000 (22 blocks, - maximum 1,327). - -Not measured here (hypothesis): whether the estimates are precomputed from handling data or measured by -simulation, and what fixes the top of the rating scale. -- **The estimates are a separate stored table, not the performance maps.** `common.rpf`'s data area at `0x9580` - also holds `CVehiclePerformanceMaps` (285 rows, 10 result fields) and `CTyreDataSet` (40 tyre types). 251 of the - 252 estimate keys join the performance rows, but no field reproduces an estimate exactly: the best OLS over - all ten gives R^2 0.872, and `fAccelerationTime` against `accelZeroSixty` is R^2 0.811 with a median |residual| - of 0.54 s. The clearest relation is internal to the estimates: over the 231 rows with a finite top speed, - `fStandingQuarterTime = 6.73 + 401.0 / fTopSpeed` (R^2 0.99998, median |residual| 1.01 s; R^2 0.82 over the - 209 rows under 30 s). For the seven top-speed-limited rows, `fTopSpeed * fStandingQuarterTime` is - 402.339 +/- 0.0003 m, a quarter mile; the residual tracks the 0-60 time. -- **The ratings are deterministic functions of the estimates.** Each of the 223 distinct road top speeds gives - one `fSpeedRating`; handling/corner has 221 levels, acceleration/acceleration time 204, brakes two collisions, - and `fOverallRating` uses more than one field. The rating scale and the overall weighting are still not fitted. -- **The handling inputs are not in the readable archives.** No `CHandlingData`/`handling.meta`, `fMass`, - `fInitialDriveForce`, `fInitialDragCoeff`, `nInitialDriveGears`, `fTractionCurve*`, `fBrakeForce` or - `fSuspensionForce` occurs in `common.rpf`, `data.rpf`, `packs.rpf` or `script.rpf`; the executable is absent. - `levels.rpf` is map data and was not fully scanned. The table is therefore consistent with an offline - estimator fed by handling-derived scalars, but whether it was fitted to handling or copied from a simulation - cannot be verified from this package. - -## Character skeletons - -World drawables do not carry the shared 597-name humanoid skeleton. Character `.#ft` fragments -store that name/hash table, and each character `#dr` model points at a local bone-hash array that -maps into it. The measured name table, the following 597-record hierarchy/reference-TRS table, -the model mapping and the texture-parameter split are in -[character_skeleton.md](character_skeleton.md). The character inverse bind matrices are at -skeleton header `+0x30` and agree with the default bone transforms (see that page); -`tools/anim_glb.py` exports a skinned part with them. - -The character-part inventory (Lucia's named records and decoded parts, the `player_story000_00` -drawable set, slot-name counts and texture coverage) is in -[character_models.md](character_models.md). - -### Character census - -`tools/character_census.py` totals a decoded model tree or an `rpf9dump models` manifest: - -```powershell -python -I tools/character_census.py [--json FILE] [--csv FILE] -``` - -It reads every nested `model.json` (the decoded-pack layout: `type`, `vertex_count`, -`triangle_count`, `materials[].shader_name_hash`, `materials[].textures[].hash64`, -`drawable.skeleton`/`drawable.models[].bone_palette` and `meshes[].skin_influences`), or the -`Items[]` of a manifest (`Verts`, `Tris`, `IsFragment`, `HasBoneBindings`, `Materials[]`). The -local exporter does not write an index count, so the index column and total normally stay unknown; -an input that supplies `index_count` is counted, but the field is optional and not part of the -decoded layout. It prints one row per model with kind, vertex/triangle counts, bones, 8-influence -skin, shader hashes and texture keys, then totals by kind and by shader hash. A missing or wrongly typed field -is reported on that row instead of ending the run. An `rpf9dump models` manifest records only -`HasBoneBindings`, not a bone count or influence width, so those cells stay `?`. Report paths that -alias an input are refused. The tests are synthetic: `python -I tests/test_character_census.py`. - -## Shader render buckets - -`rpf9dump` writes two raw shader fields per material, `RenderBucket` (byte at shader +0x39) and -`RenderBucketMask` (u32 at +0x3C; `RageModelDecoder.cs:651`). Measured on a random sample of 3,000 `.ydr`/`.yft` -models (27,435 shaders): - -- `RenderBucketMask == 0xFF00 | (1 << (RenderBucket & 0x7F))` in all 27,435. Bit 7 of `RenderBucket` is a - separate flag (set in 438) that does not change the mask. -- `RenderBucket & 0x7F` takes the values 0-6, the GTA V drawable bucket list. Model-name tokens (counted per - shader, from the model's name) line up with it: - -| Bucket | GTA V meaning | Shaders | Name evidence (share of shaders whose model name matches) | -|---:|---|---:|---| -| 0 | opaque | 17,826 | baseline: water 0.6%, vegetation 0.5%, glass/window 0.2%, decal 0.1% | -| 1 | alpha | 725 | glass/window 7.6% (38x baseline) | -| 2 | decal | 7,282 | decal/graffiti/dirt 3.1% (31x) | -| 3 | cutout | 1,311 | vegetation 2.8% (5.6x) | -| 4 | no splash | 6 | one program (`fc34f08b`) | -| 5 | no water | 6 | the same program | -| 6 | water | 343 | water/river/pool/canal 80.2% | - -Names are per model and a building holds glass, decal and opaque shaders alike, so the token shares are low -in absolute terms; the enrichment against bucket 0 is the signal. For export: bucket 1 needs blending, 2 is -a projected decal, 3 needs alpha testing, 6 is a water surface. - -`common.rpf` carries the matching preset-to-effect table (`SPS1`, decoded by `tools/gamedata_sps1.py`, -[`gamedata.md`](gamedata.md#sps1-shader-preset-table)): `858` `.sps` presets map onto `539` `SGD5` Database 0 effects -with a default `u8` render bucket (`0..7`), `63` effects accept multiple buckets, and the single bucket-`4` -and bucket-`5` presets both resolve to effect `fc34f08b`. - -## Material shader hashes and the carved programs - -`rpf9dump` also writes each material's shader hash (`manifest.json` → `Materials[].Shader`, u32 as 8 hex digits). -It is the joaat (lower-cased) of the material's **effect** name. The carve index (`/shaders/dxbc/index.json`) -names compute programs `:_<8 hex>_Wrapped` after a one-byte length prefix (the `:` becomes `_` in -file names), so the effect is recoverable from them. Measured on a 1.0.2.1 copy, `data.rpf` models and the full -26,503-program carve: - -| | Count | -|---|---:| -| Materials (3,175 models) | 3,340 | -| Distinct material shader hashes | 18 | -| Compute programs named `:` | 2,689 (every CS), 564 effects | -| Effects with `RaytracingResolve` CS programs | 341 (1,004 programs; 3 each for 324) | -| Materials whose hash is the joaat of a carved effect name | 3,211 (96%), 8 of the 18 hashes | -| Materials whose hash is the joaat of a native effect record's name (both SGD5 databases, below) | 3,340 (100%), 18 of the 18 hashes, one record each | - -So a material leads to its effect. Through the carved compute names it reaches only 8 of the 18 hashes; the -effect records' own names reach all 18 (@jeremygold02, `tools/sgd5_effects.py` in #3036). The draw (VS/PS/MS) -programs are not reachable through the carved programs' names, order or suffixes: - -- None of the 23,619 graphics programs (2,236 VS, 12,101 PS, 9,282 MS; the 195 GS are left out here) carries an - effect name; they are named `__<8 hex>`. -- `shaders.rpf` stores programs grouped by kind, not by effect (the 1,004 `RaytracingResolve` programs sit next - to each other), so position doesn't group an effect's programs either. -- Every one of the 23,619 has an 8-hex suffix. The suffixes group them: there are 1,228 distinct ones, the largest - shared by 1,806 programs and 53 used once. The suffix is not the joaat of the program name, and only 1 of the - 896 suffixes on the effect-named CS programs appears on any graphics program. - -They are reachable through the **effect records** in `shaders.rpf` (found by @jeremygold02, #2519). All fields -are little-endian: - -1. **The effect record.** It starts with a one-byte name length and the name, including its terminator, then a - u32 (below). Six stage lists follow, each a u32 count and that many u32 ordinals. - - The u32 is a size computed from the record's own counted fields (@jeremygold02). Let G be the ordinals in the - six lists, T the techniques, P the passes, and W the post-pass word count. Let A and B be the two block - lengths after them, E the post-pass entry count, I the payload bytes of the entries whose tag is a length - (not `0x80000000`), and S the string-pool length. Lengths don't count their own prefixes. Then, with - `x = 4W + A + B`: - - ```text - word = 48 + 8(G + T + E) + 32P + I + S + (round_up(x, 8) if E else x) - ``` - - This holds for all 932 records of this build (910 + 22, recomputed here). The value never equals the record's - serialized length (0 of 932), so the next record is found by the sequential walk, not by this word. What the - runtime uses it for is unknown. Groups 3 and 4 are empty here, so their share of it is unmeasured. - - `shaders.rpf` holds **two shader databases** (SGD5), and an ordinal counts within one of them (found by - @jeremygold02). Each database stores six program groups, each a u32 count followed by its programs. A program - is a u8-length label including its NUL, one tag byte, a u32-length payload, 152 fixed bytes and a u32-length - trailer. The u32 after group 5 is the database's effect count. An ordinal is the zero-based position in the - group of the effect's own database, so a lookup needs the database, the group and the ordinal. - - | Database (group walk starts at) | 0: VS + MS | 1: PS | 2: GS | 3 | 4 | 5: CS | Effects declared | - |---|---:|---:|---:|---:|---:|---:|---:| - | `0x10E39` | 11,018 | 10,944 | 195 | 0 | 0 | 2,647 | 910 | - | `0x10289C81` | 500 | 1,157 | 0 | 0 | 0 | 42 | 22 | - - The two databases add up to the whole carve: 11,518 VS + MS, 12,101 PS, 195 GS and 2,689 CS. Groups 3 and 4 are - empty and their stages are not identified. The first database's programs come first in the archive, so for its - effects the ordinal also equals the program's position among the carve index's programs of that group, sorted - by `offset`. The three records here are all in the first database: the wiper's 11017 is the last entry of its - group 0. - - On the rim and the tire, list 5's three entries are exactly the effect's own `:RaytracingResolve` - programs, the ones the material hash leads to in the table above. In the second database all 42 group-5 - references resolve to programs that carry their effect's name; resolved against the archive-wide CS list - instead, none of them do (@jeremygold02). -2. **The technique table.** A u32 count, then one 4-byte entry per technique: the low 15 bits of its first u16 are - the name's offset in a string block, and byte 3 is the pass count. A u32 pass total follows, then 24-byte pass - records. Where the table and its string block sit relative to the record is not derived yet: the three - tables were located by offset. -3. **The pass records.** The first six bytes of each pass select an entry of each stage list: 0 is unused, - otherwise `stage_list[selector - 1]`. - -The group walk and its counts above were reproduced on a 1.0.2.1 copy (the same `shaders.rpf`, SHA-256 -`0bc16345…`). So was @jeremygold02's census of both databases' effects with `tools/sgd5_effects.py ---list-effects` (#3036, `0029eba7`): 932 effect records with 932 distinct name hashes, 913 of them with a -technique table, 25,037 techniques and 28,798 passes. Since `c0439966` the tool also **walks** the records -forward from each database's effect count, using only stored lengths: every record's string pool, the next -record, and at the end the terminal word and zero padding. Its tests, run against this package -(`LEONIDA_GAME_DIR` set, `tests/test_sgd5_effects.py`), pass: the walk and the earlier search agree on every -record, technique and pass. The record and pass format below was also checked by hand on three records: - -| Record | Stage list sizes | Techniques | Passes (total = sum of counts) | First pass list 0 / list 1 ordinal | -|---|---|---:|---:|---| -| windshield wiper mask | 1, 1, 0, 0, 0, 0 | 1 | 1 | 11017 / 10943 | -| stock rim | 41, 53, 0, 0, 0, 3 | 106 | 108 | 9143 / 8925 | -| stock tire | 41, 53, 0, 0, 0, 3 | 106 | 108 | 9089 / 8835 | - -Two things are still open: - -- **The u32 after an effect's name.** It is reproduced from the record's fields; how the runtime uses it is - still unknown. -- **Which technique and pass the game draws with.** That is a run-time choice; it is presumably made in the - executable (RT-5). - -Until both are settled, a real model is drawn with a chosen pair ([first_light.md](first_light.md)). The effect -records already give that choice a pair that can be checked independently. - -So a material leads to its effect. Through the carved compute names it reaches only 8 of the 18 hashes; the -effect records' own names reach all 18 (@jeremygold02, `tools/sgd5_effects.py` in #3036). The draw (VS/PS/MS) -programs are not reachable through the carved programs' names, order or suffixes: - -- None of the 23,619 graphics programs (2,236 VS, 12,101 PS, 9,282 MS; the 195 GS are left out here) carries an - effect name; they are named `__<8 hex>`. -- `shaders.rpf` stores programs grouped by kind, not by effect (the 1,004 `RaytracingResolve` programs sit next - to each other), so position doesn't group an effect's programs either. -- Every one of the 23,619 has an 8-hex suffix. The suffixes group them: there are 1,228 distinct ones, the largest - shared by 1,806 programs and 53 used once. The suffix is not the joaat of the program name, and only 1 of the - 896 suffixes on the effect-named CS programs appears on any graphics program. - -They are reachable through the **effect records** in `shaders.rpf` (found by @jeremygold02, #2519). All fields -are little-endian: - -1. **The effect record.** It starts with a one-byte name length and the name, including its terminator, then a - u32 (below). Six stage lists follow, each a u32 count and that many u32 ordinals. - - The u32 is a size computed from the record's own counted fields (@jeremygold02). Let G be the ordinals in the - six lists, T the techniques, P the passes, and W the post-pass word count. Let A and B be the two block - lengths after them, E the post-pass entry count, I the payload bytes of the entries whose tag is a length - (not `0x80000000`), and S the string-pool length. Lengths don't count their own prefixes. Then, with - `x = 4W + A + B`: - - ```text - word = 48 + 8(G + T + E) + 32P + I + S + (round_up(x, 8) if E else x) - ``` - - This holds for all 932 records of this build (910 + 22, recomputed here). The value never equals the record's - serialized length (0 of 932), so the next record is found by the sequential walk, not by this word. What the - runtime uses it for is unknown. Groups 3 and 4 are empty here, so their share of it is unmeasured. - - `shaders.rpf` holds **two shader databases** (SGD5), and an ordinal counts within one of them (found by - @jeremygold02). Each database stores six program groups, each a u32 count followed by its programs. A program - is a u8-length label including its NUL, one tag byte, a u32-length payload, 152 fixed bytes and a u32-length - trailer. The u32 after group 5 is the database's effect count. An ordinal is the zero-based position in the - group of the effect's own database, so a lookup needs the database, the group and the ordinal. - - | Database (group walk starts at) | 0: VS + MS | 1: PS | 2: GS | 3 | 4 | 5: CS | Effects declared | - |---|---:|---:|---:|---:|---:|---:|---:| - | `0x10E39` | 11,018 | 10,944 | 195 | 0 | 0 | 2,647 | 910 | - | `0x10289C81` | 500 | 1,157 | 0 | 0 | 0 | 42 | 22 | - - The two databases add up to the whole carve: 11,518 VS + MS, 12,101 PS, 195 GS and 2,689 CS. Groups 3 and 4 are - empty and their stages are not identified. The first database's programs come first in the archive, so for its - effects the ordinal also equals the program's position among the carve index's programs of that group, sorted - by `offset`. The three records here are all in the first database: the wiper's 11017 is the last entry of its - group 0. - - On the rim and the tire, list 5's three entries are exactly the effect's own `:RaytracingResolve` - programs, the ones the material hash leads to in the table above. In the second database all 42 group-5 - references resolve to programs that carry their effect's name; resolved against the archive-wide CS list - instead, none of them do (@jeremygold02). -2. **The technique table.** A u32 count, then one 4-byte entry per technique: the low 15 bits of its first u16 are - the name's offset in a string block, and byte 3 is the pass count. A u32 pass total follows, then 24-byte pass - records. Where the table and its string block sit relative to the record is not derived yet: the three - tables were located by offset. -3. **The pass records.** The first six bytes of each pass select an entry of each stage list: 0 is unused, - otherwise `stage_list[selector - 1]`. - -The group walk and its counts above were reproduced on a 1.0.2.1 copy (the same `shaders.rpf`, SHA-256 -`0bc16345…`). So was @jeremygold02's census of both databases' effects with `tools/sgd5_effects.py ---list-effects` (#3036, `0029eba7`): 932 effect records with 932 distinct name hashes, 913 of them with a -technique table, 25,037 techniques and 28,798 passes. Since `c0439966` the tool also **walks** the records -forward from each database's effect count, using only stored lengths: every record's string pool, the next -record, and at the end the terminal word and zero padding. Its tests, run against this package -(`LEONIDA_GAME_DIR` set, `tests/test_sgd5_effects.py`), pass: the walk and the earlier search agree on every -record, technique and pass. The record and pass format below was also checked by hand on three records: - -| Record | Stage list sizes | Techniques | Passes (total = sum of counts) | First pass list 0 / list 1 ordinal | -|---|---|---:|---:|---| -| windshield wiper mask | 1, 1, 0, 0, 0, 0 | 1 | 1 | 11017 / 10943 | -| stock rim | 41, 53, 0, 0, 0, 3 | 106 | 108 | 9143 / 8925 | -| stock tire | 41, 53, 0, 0, 0, 3 | 106 | 108 | 9089 / 8835 | - -Two things are still open: - -- **The u32 after an effect's name.** It is reproduced from the record's fields; how the runtime uses it is - still unknown. -- **Which technique and pass the game draws with.** That is a run-time choice; it is presumably made in the - executable (RT-5). - -Until both are settled, a real model is drawn with a chosen pair ([first_light.md](first_light.md)). The effect -records already give that choice a pair that can be checked independently. - -## Vehicle distant-light recipes - -`common.rpf` has one `CVehicleDistantLightData` XML document (see [gamedata.md](gamedata.md)) that ties -vehicle models to far-away light recipes. Counts only; no model names. - -| Path | Count | Content | -|---|---:|---| -| `distantLights`, `presetLights` | 1 each | empty | -| `recipeLights/Item` | 1,980 | `vehicleModelName`, `secondaryRecipes`, `lights` | -| `recipeLights/Item/secondaryRecipes/Item` | 2,383 | one token each; 0 to 3 per recipe (0: 312, 1: 1,029, 2: 563, 3: 76) | -| `recipeLights/Item/lights` | 1,980 | empty in all | - -- **Every `vehicleModelName` is a real fragment model.** The 1,980 recipes name 319 distinct models, and all - 319 exist as `.yft` entries in the local archive catalog, each also with a `_hi.yft` high-detail - variant. None is a `.ydr`. A loader can therefore key the recipes by the vehicle's `.yft` base name. -- A model has 1 to 45 recipes (93 models have one); in 304 of the 319 models every recipe has a different set - of secondary tokens, so a recipe is selected by its secondaries, not by the model alone. -- The 780 distinct secondary tokens are not catalog entries (2 coincide with an entry name) and not texture - dictionary items, and are never another recipe's model name. 1,242 of the 2,383 contain the recipe's own - model name. -- **No light data is stored**: `lights` is empty in all 1,980 recipes and both top-level lists are empty. In - this build the document is an index from model and variant to recipe with the light positions absent, - so distant vehicle lights cannot be reconstructed from it. - -To reproduce the joins, locate the XML roots in the [common carve catalog](gamedata.md) with -`python -I tools/gamedata_xml.py --json xml.json`. Trim and lowercase the field -text, then match each nonempty `CVehicleDistantLightData/recipeLights/Item` by `vehicleModelName` -and its sorted list of `secondaryRecipes/Item` values against `vehicleName` and the same list on -`CPaletteIndexedRecipeTintsArray` rows at `.//recipeCombinations/Item`. For the carriage check, -expand the light lists to distinct pairs and compare with `CTrainConfigs` rows at `.//carriages/Item`. - -The sampled `CPaletteIndexedRecipeTintsArray` document reuses 746 of the 780 distinct distant-light -secondary tokens in its own `secondaryRecipes` field. Of the 1,668 distant-light rows with at least one -token, 1,339 match a palette recipe on both vehicle name and the complete token list, ignoring case and -token order. Replacing each vehicle name with the next of the 319 distinct names from all light rows in sorted order -(wrapping at the end) and keeping its tokens fixed gives 56 matches among the same 1,668 rows. - -For a single-token comparison, the distant-light rows give 1,547 distinct (vehicle, secondary token) -pairs. Four match the `modelName` and `modelSetName` fields on the same `CTrainConfigs` carriage row, -after trimming whitespace and ignoring case. These four pairs cover two vehicle models and four model -sets. Rotating the 319 vehicle names as above gives zero matching pairs. Keeping the vehicle fixed and -rotating the 780 distinct tokens in sorted order, with wraparound, gives two matching pairs. - -In the 34-row `CVehicleBoneOffsetsArray` document, 0 of the 780 distinct tokens match a whole text or -attribute value case-insensitively. In the 2,447-row document of the same type, 178 of the 780 match -`boneOffsets/Item/name`. All 2,447 rows have empty `vehicleName` fields, so those name matches provide -no same-row vehicle association. -Which physical parts or liveries a token selects, and where the runtime obtains light positions, remain open. - -## Skinned GLB export - -`tools/skinned_glb.py` writes a skinned GLB from decoded pack components and the shared ped -skeleton: - -``` -python -I tools/skinned_glb.py out.glb --skeleton
--component [--component ...] -``` - -It reads the 8-influence `JOINTS_0/1` and `WEIGHTS_0/1` streams from the graphics buffer, resolves -the drawable's local joint palette through the drawable and ped tables, and emits `skins` and -`inverseBindMatrices` with the ped bind pose. The measured stream offsets and joint mapping are -in [character_skeleton.md](character_skeleton.md#skinned-glb-export). On the 1.0.2.1 package, the -head (8,983 v) and biker jacket (9,818 v) produce one skin with 596 ped joints (703 with the -jacket's `GM_U01_*` helpers); every weight sums to 255 and the rest-pose reconstruction error is -6e-8 m. `python -I tests/test_skinned_glb.py` runs 24 synthetic tests and needs no game files. - -`tools/glb_inspect.py` reads such a GLB back without a library, so an export can be checked -before it is opened in a viewer: - -``` -python -I tools/glb_inspect.py out.glb [--json report.json] -``` - -It prints the chunk layout and padding, the `counts` of scenes, nodes, meshes, materials, images, -skins and animations, each mesh's primitive, vertex and triangle counts, each material's -`baseColorTexture`, each skin's joint count, each animation's channels and duration, and the -POSITION bounding box (marked `partial` when a POSITION accessor has no `min`/`max`). It reports -what the JSON chunk says — a field the exporter dropped reads `(missing)` — and never infers -geometry from the BIN chunk. Standard library only; no game files. - -## What to do next - -1. **Done:** [rpf9-explorer PR #1](https://github.com/breadbbbb/rpf9-explorer/pull/1) is merged upstream. -2. **Done:** the pin is `e293917` (was `917e9b9`, originally `48557ea`). -3. **Done:** all ten `MODEL_ARCHIVES` were re-counted and read-back decoded at `e293917` (**382,781 - models**, **0 decode failures**; table above, `levels.rpf` geometry from a full export). -4. Investigate the 71 remaining unrecovered fragment candidates in `levels.rpf` (and the 1 - texture-dictionary candidate in `textures.rpf`) if further upstream recovery is wanted. -5. Keep issue #29 in sync with the `e293917` counts. -3. **Done:** `tools/rpf9dump models` was re-run over the model-bearing archives at `e293917`; - the six non-`levels.rpf` archives total 39,454 rows (+3,203, almost all recovered fragments). - `levels.rpf` has the same 343,327 rows in a full export (50,731 fragments, 2,509,947,536 - triangles). -4. Keep the README and issue #29 in sync with the new counts. - -### Predict model offsets for placements - -Run `python -I tools/world_drawable_lookup.py entities.jsonl archetypes.json names.json` -with the placement rows from `world_index.py --entities-out`, the definitions from -`world_archetypes.py`, and a bounded `rpf9_names.py --types dr,ft` report. The command -prints local scratch JSON. Supply `--manifest path/to/models/manifest.json` for each -existing export whose listed identities should be excluded. - -The lookup requires agreement between the placement archetype, the definition's name and -assetName, the resource stem's joaat and its 64-bit placement key. It considers type 1 -fragments and type 2 drawables at page offset +16. Multiple offsets for an identity in -the indexed window are marked ambiguous. Even a single hit is a prediction: a stream -can mention another model. Export a window around the predicted offset with -`rpf9dump models --start BYTES --length BYTES`, compare the manifest offset and -model identity and run `world_build.py --placements` with the exported geometry. - -Save the lookup JSON and run -`python -I tools/world_drawable_verify.py lookup.json first/models/manifest.json second/models/manifest.json` -to verify single-offset predictions. Supply completed normal model manifests from the -same source archive. The verifier reads cached JSON only. It uses the world builder's -name hashes and counts each identity and its placements once. A matching offset and both -hashes confirm an observation, including dictionary children sharing an offset. The local -report counts repeat exact observations and lists other offsets for the same identity. -Without an exact match, a different name at the offset takes precedence over a matching -identity elsewhere. The coverage flag independently records whether the predicted offset -falls in a supplied scan (start inclusive, end exclusive). A full scan covers all offsets. -A covered prediction with no named evidence remains missing. Geometry loadability is -checked separately by running the normal world builder on confirmed placement rows. - -Add `--window-bytes BYTES` to recommend one scan in the name index's archive. -The optional `export_window` field gives the decimal `start` and `length` for -`rpf9dump models`. It maximizes the sum of unmatched placement rows with a -single predicted offset in that index. Each identity contributes its placement -count once. Ambiguous identities contribute zero. For a tie it takes the earliest -last offset, then trims the interval to its first and last included bytes. -An empty selection yields JSON null. Run the lookup separately for each archive. - -The budget bounds the half-open range of candidate **starts**. The exporter can -inspect prefix bytes and read model segments beyond the range. The report -predicts coverage. Confirm identities and offsets in the exported manifest and -check the resulting placement count with `world_build.py`. diff --git a/docs/movies.md b/docs/movies.md deleted file mode 100644 index a338069bd..000000000 --- a/docs/movies.md +++ /dev/null @@ -1,475 +0,0 @@ -# Movies (`movies.rpf`) - -**Status: indexed. All 515 Bink 2 streams have been enumerated and their fixed headers read; the first two frames -of every stream, and the start of every audio track, decode with the package's own Bink 2 library. The RPF9 table -of contents is encrypted, but the streams can be named from the game's mount lists -([section 8](#8-names-from-the-mount-lists)). Nothing here is a playback path yet.** -**Status: indexed and decode-checked. All 515 Bink 2 streams have been enumerated, their fixed headers read, and -frame 0 of every stream decoded with the package's own Bink 2 library (515/515). The RPF9 table of contents is -encrypted, but the streams can be named from the game's mount lists ([section 8](#8-names-from-the-mount-lists)). -Nothing here is a playback path yet.** - -Every number below was measured on the Xbox Series 1.0.2.1 package on 2026-11-21. The archive is read-only. No -game video, audio, frames, carved streams or reports that quote them are in this repository; the tools write only -offsets and header facts. Commands are at the end. - -## 1. What the package ships - -| Fact | Measured | -|---|---| -| `movies.rpf` size | 8,832,481,776 bytes | -| Bink 2 streams (`KB2[a-z]`) | **515** | -| Bytes occupied by those streams | **8,831,336,892** (99.99% of the archive) | -| Data start in the RPF header (word at +4) | 27,328 (0x6AC0) | -| First stream offset | 28,672 (0x7000) | -| Zero padding between streams | 1,094,744 bytes (includes 1,344 bytes before the first stream) | -| Bytes after the last stream | 22,812: 3,884 zero bytes to the next 4 KiB boundary, then the 18,928-byte RPF trailer (the header's `u32 +12`; [rpf.md](rpf.md#the-trailer-at-eof)) | -| Other carved file types | none; the whole data area is Bink 2 | -| Revisions | 505 `KB2n`, 10 `KB2j` | -| Frame rate | 30/1 in all 515 headers | -| Frame counts | 15 to 16,015; **425,440** frames total | -| Total duration at 30 fps | 14,181.3 s (3 h 56 min) | -| Audio tracks (header field) | 319 streams with 0, 165 with 1, 30 with 2, 1 with 4; 229 tracks total | -| Decoded samples | 9 streams, 14 frames, both revisions, 512x512 to 3840x2160 | -| Decode test over the archive | 515 of 515 streams: frames 0 and 1; 229 of 229 audio tracks: `RESULT PASS`, and PCM bytes reported for the first 60 frames ([below](#decode-coverage-over-the-whole-archive)) | -| Decoded streams (frame 0, `Bink2Scarlett.dll`) | **515 of 515** (0 failed), both revisions, all 19 resolutions | -| ffprobe decode result | 0 of 515 (`decodes=no` with a forced `-f bink` probe) | - -`8,831,336,892 + 1,094,744 + 22,812 = 8,832,454,448`, the span from the RPF header's data start to EOF. Readable -coverage is 100.0%; the 27,328-byte RPF header (before the data start) and the 18,928-byte trailer are the only -unindexed ranges, and both are part of the RPF container, not of a stream. - -`KB2n` is the newer of the two revisions. One DLL string mentions Bink 2.2, but the revision-to-version mapping is -not independently established. - -### Resolution distribution (header width x height) - -| Resolution | Streams | | Resolution | Streams | -|---|---:|---|---|---:| -| 1280x720 | 246 | | 2048x468 | 1 | -| 1920x1080 | 130 | | 2048x1024 | 1 | -| 720x1280 | 67 | | 512x384 | 1 | -| 512x512 | 23 | | 1407x1600 | 1 | -| 1024x1024 | 19 | | 1635x720 | 1 | -| 2560x1440 | 14 | | 1920x850 | 1 | -| 512x256 | 2 | | 1024x768 | 1 | -| 2048x558 | 2 | | 3840x2160 | 1 | -| 2048x512 | 2 | | 1080x1080 | 1 | -| 1024x512 | 1 | | | | - -There are 19 distinct sizes. Square and small streams (512x512, 1024x1024, 512x256) may be animated textures or -UI footage rather than cutscenes; that is a guess, not verified. The 10 `KB2j` streams are nine 512x512, 15-frame -(0.5 s) files of three slightly different sizes, plus one 1920x1080, 60-frame (2 s) file. Their similarity suggests -splash/logo variants, but nothing confirms it. - -## 2. Bink 2 container facts that were verified - -All 515 headers use the same fixed layout for the first 44 bytes (0x00-0x2B). The names in the table follow the -FFmpeg Bink demuxer's reading order; values in the last column are what this archive contains. The tool reads only -these fields plus the audio descriptors and never trusts a size past the stored stream length. - -| Offset | Size | Meaning | Observed | -|---:|---:|---|---| -| 0x00 | 4 | `KB2` + revision letter | `KB2n` (505), `KB2j` (10) | -| 0x04 | u32 | stored stream size minus 8 | `stored = field + 8`; matches the carve exactly for all 515 | -| 0x08 | u32 | frame count | 15 to 16,015 | -| 0x0C | u32 | largest frame size | at most `stored - 8` | -| 0x10 | u32 | frame count again | equals 0x08 in all 515 | -| 0x14 | u32 | width | 512 to 3840 | -| 0x18 | u32 | height | 256 to 2160 | -| 0x1C | u32 | fps numerator | 30 in all 515 | -| 0x20 | u32 | fps denominator | 1 in all 515 | -| 0x24 | u32 | opaque; FFmpeg reads it as codec extradata | 0x00040013 common; 0x00100012 on the 512x512 `KB2j` files, 0x00000012 on the 1920x1080 `KB2j` | -| 0x28 | u32 | audio track count | 0, 1, 2, 4 | -| 0x2C | u32 | opaque; present on revisions i/j/k/n | not interpreted (`0x87E9xxxx` variants on `KB2n`, `0x02070D00` on `KB2j`) | - -Only the first 0x2C bytes are fixed. When the audio count is non-zero, the next region is: - -- `count` u32 values: maximum decoded size per audio track (0x23A00 = 145,920 across all 229 tracks; `BinkGetTrackMaxSize` adds 512 bytes and returns 0x23C00 = 146,432). -- `count` pairs of u16: sample rate and flags. Every readable track in this archive is 48,000 Hz. -- `count` u32 values: track IDs (0 and 1 in the two-track files). -- then the frame index: `frame_count` u32 offsets. FFmpeg treats the low bit of each offset as the keyframe flag. - -The audio flag bits verified against FFmpeg's demuxer are `0x4000` (prefer 16-bit), `0x2000` (stereo) and `0x1000` -(DCT). 227 tracks have `0x7000` (16-bit, stereo, DCT); 2 tracks have `0x3000` (stereo, DCT, no 16-bit preference). -All 229 are therefore Bink Audio DCT, stereo, 48 kHz by the header's own description. That does not prove the -decoder output format or that every track is used by the game. - -The frame index is not read by `bink_index.py`: its length depends on the frame count, and the index is not needed -to inventory the stream. `rpf9_carve.py` advances by the stored size instead, which is why it can carve without -parsing the index. - -## 3. How the streams are found - -`tools/rpf9_carve.py` treats the data area as zlib streams or Bink 2 streams laid end to end. It: - -1. Starts at the u32 at archive offset +4 (27,328 here; the first stream begins 1,344 bytes later). -2. Searches for the zlib header bytes or `KB2[a-z]`. -3. For a Bink candidate, reads the size at +4 (`stored = size + 8`), the frame count at +8 and width/height at - +0x14, and rejects anything outside 64 bytes..EOF or 16..8192 pixels. Those checks keep random `KB2` bytes in a - payload from becoming a stream. -4. On a valid stream, records the offset and advances by the stored size. Gaps that are all zero are counted as - padding; any other gap is counted as unread. -5. `--index-only` performs steps 1-4 without writing the streams. - -`tools/bink_index.py` is the stdlib-only indexer added with this document. It scans an RPF, a single `.bk2`, or a -directory, applies the same signature and size checks plus header sanity (duplicate frame count, fps, audio count), -reads the 44-byte header and audio descriptors, and writes CSV or JSON. It never extracts unless `--probe` is used, -and then only to a temporary file that is deleted. - -On this archive both tools find the same 515 streams, the same 8,831,336,892 bytes, 1,094,744 bytes of zero -padding and 22,812 bytes after the last stream. Those 22,812 are 3,884 zero bytes and the 18,928-byte RPF trailer -(counted by reading the tail directly); `bink_index.py` now counts them as zero padding and `rpf_trailer`, which for -this archive gives `unread_bytes` 0 and zero padding 1,098,628 (derived from the measured tail, not a rerun). Running `bink_index.py` on the 515 carved -`.bk2` files finds 515 streams with zero unread bytes, which confirms the stored sizes cover each file exactly. - -## 4. Decoding - -### FFmpeg is not a Bink 2 decoder here - -Three FFmpeg builds on the test machine were checked: `N-127054-g9d3f0f2c58` (2026-10-01), `n8.0`, and `7.0`. -The two that include Bink support expose `binkvideo` (Bink 1) and the two Bink Audio decoders; the 7.0 build -includes neither. None exposes a Bink 2 video decoder. FFmpeg's Bink demuxer explicitly sets the codec to none for -a `KB2` tag ("Bink 2 video is not implemented"). Measured results: - -- `ffmpeg -i .bk2` fails with "Invalid data found when processing input" for `KB2n`; for `KB2j` the - demuxer may parse the header but there is no decoder, so no frame is produced. -- `ffprobe -f bink` parses the fixed header even for `KB2n` (forced demuxing skips the probe's revision list) and - reports a duration for 206 of 515 streams, but `codec_name` is empty and `decodes` is `no` for all 515. -- Without `-f bink`, generic probing misidentified one 168,505,620-byte stream as MPEG-4 (the cause was not - investigated). `bink_index.py --probe` therefore forces `-f bink`; the `decodes` column means "ffprobe found a - video codec", not "the stream was visually checked". - -So the task's working assumption that the installed FFmpeg can decode Bink 2 does not hold on this machine. The -decode evidence below comes from the package's own library, not FFmpeg. - -### The package's Bink 2 library - -`Bink2Scarlett.dll` is 255,488 bytes, x86-64, GUI subsystem, with 74 named exports at ordinals 0-73 (ordinal -equals index). It has no separate `BinkOpenAudio`; audio is track-based (`BinkOpenTrack`, `BinkGetTrackType`, -`BinkGetTrackData`, `BinkSetSoundTrack`, `BinkSetSoundSystem`). The full export list is in Appendix A. - -Facts from the PE and strings: - -- Imports include `xmem.dll!XMemAlloc` and `xmem.dll!XMemFree`, `XAudio2_9.dll` ordinal 1, VCRUNTIME140 and - Windows API sets. There is no `xmem.dll` on Windows, so `LoadLibrary` on the DLL as shipped fails with a missing - dependency. -- Build string: `_xbld_edition_sdktype=GXDK,220604` (GDK build dated 2022-06-04). PE timestamp 2023-02-08 - 06:36:22 UTC. PDB path `C:\devel\projects\bink\build\Bink2Scarlett.pdb`. No semantic version string such as - "2.7" was found. -- Strings include "BinkGPU is only supported for Bink 2.2 and later files.", "Not a Bink file.", "Error reading - Bink header." and the async-decompression and subtitle messages. -- Exports include `BinkOpen`, `BinkOpenWithOptions`, `BinkClose`, `BinkDoFrame`, `BinkDoFrameAsync`, - `BinkDoFrameAsyncWait`, `BinkNextFrame`, `BinkCopyToBuffer`, `BinkCopyToBufferRect`, `BinkWait`, `BinkGoto`, - `BinkGetSummary`, `BinkGetRects`, `BinkGetTrackType`, `BinkGetTrackData`, `BinkOpenTrack`, `BinkCloseTrack`, - `BinkSetSoundSystem`, `BinkSetSoundSystem2`, `BinkOpenXAudio2`, the subtitle calls and the async/thread calls. - -### Decode evidence - -For evidence only, a copy of the DLL was made in temp and its `xmem.dll` import was redirected to -`msvcrt.dll!malloc`/`free` (x64 ignores the extra Xbox attribute argument). The copy is not committed and is not a -build dependency. With that copy: - -- `BinkOpen(path, 0)` returned a non-null handle for every tested stream. -- `BinkDoFrame` followed by `BinkCopyToBuffer(..., BINKSURFACE32)` wrote a non-empty BGRA buffer for every test. - Nine streams and fourteen frames were decoded, covering both revisions: `KB2j` at 512x512 (3 frames) and - 1920x1080 (1 frame), and `KB2n` at 1280x720 (3 frames), 2560x1440, 2048x558, 1920x1080, 1407x1600, 720x1280 - and 3840x2160 (2 frames: 0 and 200). Four of the resulting images (512x512, 1280x720, 2048x558 and the 4K - frame 200) were viewed and are coherent pictures; the others were not viewed, so their content is not claimed. - Everything stayed in temp; none is in the repository or PR. -- `BinkGoto(handle, 200, 0)` followed by `BinkDoFrame` produced the 4K frame above, so absolute frame seeking - works at least in this path. The `BinkGoto` flag meaning was not otherwise tested. -- `BinkDoFrame` and `BinkCopyToBuffer` returned 0 even when they produced a correct frame. Over the whole archive - they return 0 on every call ([ABI over the archive](#abi-over-the-archive)); a caller must not treat 0 as failure - without checking the pixels. -- `BinkGetSummary` with a guessed `BINKSUMMARY` layout crashed with an access violation. With a 1,024-byte buffer it - writes bytes +0x00..+0x8F on every stream; the fields found in it are in [ABI over the archive](#abi-over-the-archive). - -### Decode coverage over the whole archive - -The two package-gated runtime tests were run on every stream of `movies.rpf`, one at a time: each stream is copied -from its `bink_index.py` offset and size to one temp file, the test runs on it, and the file is overwritten by the -next. Both tests map the package's `Bink2Scarlett.dll` with `rt::Loader` and bind its two `xmem.dll` imports to the -runtime's shim, so no patched copy of the DLL is involved. - -| Test | Scope | Result | -|---|---|---| -| `bink_decode_test` | all 515 streams | 515 exit 0: `BinkOpen` returns a handle, and frames 0 and 1 each replace the sentinel buffer with more than one byte value | -| `bink_audio_test`, `LEONIDA_AUDIO_FRAMES=60` | all 229 tracks of the 196 streams that have audio (`LEONIDA_AUDIO_TRACK` 0..n-1) | 229 `RESULT PASS`, 0 `FAIL` lines: track id and type match the header, the maximum size covers the header's, and `BinkOpenTrack` returns a track. Separately, the test's per-track `track N: ... bytes=` line is non-zero for 229 of 229 runs; the test itself checks for whole 16-bit samples only when a track returned some, and does not fail on a track that returns none | - -Measured at `main` `16282101` and again at `f847748c`, with the same counts, on Windows 11 (MSVC 14.44, -RelWithDebInfo). This is a decode check of the start of -each stream. It does not decode every frame, compare pixels with a reference, or look at the frames (none was -viewed), so it says the library accepts all 515 streams and all 229 tracks, not that every frame is correct. - -The nine sampled streams (all at 30 fps): - -| Revision | Resolution | Frames | Duration | Audio tracks | -|---|---|---:|---:|---:| -| `KB2j` | 512x512 | 15 | 0.5 s | 0 | -| `KB2j` | 1920x1080 | 60 | 2.0 s | 0 | -| `KB2n` | 1280x720 | 40 | 1.333 s | 0 | -| `KB2n` | 2560x1440 | 115 | 3.833 s | 0 | -| `KB2n` | 2048x558 | 360 | 12.0 s | 1 | -| `KB2n` | 1920x1080 | 150 | 5.0 s | 0 | -| `KB2n` | 1407x1600 | 2395 | 79.833 s | 1 | -| `KB2n` | 720x1280 | 150 | 5.0 s | 1 | -| `KB2n` | 3840x2160 | 450 | 15.0 s | 1 | - -### Full 515-stream decode check (ASSET-328) - -Using the same temporary `xmem.dll` → `msvcrt.dll` (`malloc`/`free`) copy of `Bink2Scarlett.dll` on Windows 11, -every one of the 515 indexed streams in `movies.rpf` was opened directly from the archive with -`BinkSetFileOffset(offset)` + `BinkOpen(archive, BINKFILEOFFSET)` (`0x20`), decoded (`BinkDoFrame`), and copied -into a pre-filled sentinel BGRA buffer (`BinkCopyToBuffer(..., BINKSURFACE32)`). No frames, pixels, audio, or -carved `.bk2` files were saved. - -- **Result:** **515 / 515 decoded, 0 failed** (2.9 s total). Every stream returned a non-null `HBINK` handle, - overwrote the sentinel buffer with non-zero BGRA bytes on frame 0, and returned `0` from both `BinkDoFrame` and - `BinkCopyToBuffer` (confirming the earlier 9-stream observation across the full corpus). -- **By revision:** `KB2j` **10 / 10** decoded (`0` failed); `KB2n` **505 / 505** decoded (`0` failed). -- **By stored stream size:** - -| Stream size bucket | Decoded | Failed | -|---|---:|---:| -| `< 1 MB` | 50 | 0 | -| `1–10 MB` | 352 | 0 | -| `10–50 MB` | 74 | 0 | -| `>= 50 MB` | 39 | 0 | -| **Total** | **515** | **0** | - -- **By resolution:** all 19 distinct header resolutions (`512x256` through `3840x2160`, matching the resolution - table in [section 1](#resolution-distribution-header-width-x-height)) decoded 100% (`0` failed). - -This establishes that every indexed stream in `movies.rpf` opens and decodes frame 0 with `Bink2Scarlett.dll`; -only the four frames from the earlier sample were visually inspected, and decoding all 425,440 frames or audio -tracks remains untested. - -To turn a decoded BGRA buffer into a viewable image without a Bink 2 decoder: - -```sh -ffmpeg -f rawvideo -pix_fmt bgra -s 1280x720 -i frame.raw -frames:v 1 frame.png -``` - -The raw buffer and PNG stay in temp. FFmpeg is only the raw-to-PNG step here; it never sees the `.bk2`. - -### ABI over the archive - -[`runtime/test/bink_abi_test.cpp`](../runtime/test/bink_abi_test.cpp) ([notes](../runtime/test/bink_abi_test.md)) maps `Bink2Scarlett.dll` with `rt::Loader` and -opens each of the 515 streams inside `movies.rpf` (`BinkSetFileOffset`, then `BinkOpen` with flag `0x20`), so nothing -is extracted. For each stream, it reads the first 256 bytes of the `HBINK` and the `BINKSUMMARY` that `BinkGetSummary` -writes, and keeps the 32-bit word offsets that hold the stream header's value. An offset is listed only if it -matched on all 515 streams. - -Every stream of 1.0.2.1 runs at 30/1 fps, so the header alone can't separate the rate fields. The test therefore -reopens one stream after `BinkSetFrameRate(24000, 1001)`. Of the 32 single-bit `BinkOpen` flags, only `0x1000` makes -that rate take effect. RAD's Bink 1 value, `0x00080000`, changes nothing. - -| Field | `HBINK` | `BINKSUMMARY` | How it was told apart | -|---|---|---|---| -| width | `+0x00` | `+0x28` | 11 distinct widths | -| height | `+0x04` | `+0x2c` | 14 distinct heights | -| frame count | `+0x08` | `+0x48` | 278 distinct counts | -| current frame (1-based) | `+0x0c` | | 1 after `BinkOpen`, 2 after `BinkNextFrame`, N after `BinkGoto(N)` | -| playback frame rate | `+0x14` / `+0x18` | `+0x3c` / `+0x40` | the forced 24000/1001 lands here | -| file frame rate | | `+0x34` / `+0x38` | keeps 30/1 under the forced rate | -| audio track count | `+0x38` | | values 0, 1, 2 and 4 | - -- `BinkGetSummary` writes every byte from +0x00 to +0x8F and none after, on all 515 streams. The test fills a - 1,024-byte buffer with `0xCD`, then again with `0x5A`. A written byte differs from at least one of the two, so a - byte that kept the sentinel both times was not written. This bounds what the call writes, not the declared size of - the structure, which may have padding past +0x8F. -- `BinkDoFrame` and `BinkCopyToBuffer` return 0 on every call. That covers 515 x 3 decodes: frame 1, frame 2, and - the frame after `BinkGoto` to the middle of the stream. `BinkCopyToBuffer` replaced the sentinel buffer on every - stream. -- `BinkWait` returns 0 before the first frame. It returns 1 when it is called straight after a decode, that is, - before the next frame is due at the stream's rate. -- The `HBINK` is readable for at least 256 bytes. Fields that matched no header value are not named here; the - `BINKTRACK` prefix is in [`bink_audio_test.md`](../runtime/test/bink_audio_test.md). -### Audio track decoding (`BinkOpenTrack` / `BinkGetTrackData`, ASSET-323) - -Using the same temporary `xmem.dll` → `msvcrt.dll` (`malloc`/`free`) copy of `Bink2Scarlett.dll` on Windows 11, -all **196** audio-bearing streams (**229** tracks total) in `movies.rpf` were opened directly via -`BinkSetFileOffset` + `BinkOpen(archive, BINKFILEOFFSET)` (`0x20`) and queried through the track API (both with -default open state and after `BinkSetSoundTrack(0, NULL)`, which behaved identically). No audio bytes were saved. - -- **All 229 / 229 tracks opened and decoded (0 failed, 0.98 s total):** `BinkOpenTrack(handle, i)` takes the - 0-based positional index `i` (`0..audio_tracks - 1`), not the logical track ID, and returned a non-null - `HBINKTRACK` for every track (including streams with non-consecutive IDs such as `(3, 1)`, `(1, 3)`, and `(0, 2)`). -- **Header-to-DLL mapping (229 / 229 exact matches):** - - `BinkGetTrackID(handle, i)` equals the header's `track_ids[i]` in **229 / 229** tracks. Header track-ID tuples - across the 196 audio-bearing streams: `(0,)` in 165 streams, `(0, 1)` in 21, `(3, 1)` in 6, `(1, 3)` in 2, - `(0, 2)` in 1, and `(0, 1, 2, 3)` in 1. - - `BinkGetTrackType(handle, i)` packs `(header_flags[i] << 16) | header_rate[i]` in **229 / 229** tracks: - `0x7000bb80` (`0x7000`, 48,000 Hz) in 227 tracks and `0x3000bb80` (`0x3000`, 48,000 Hz) in 2 tracks. - - `BinkGetTrackMaxSize(handle, i)` returns `146,432` (`0x23C00` = `header_max_size + 512`) for all 229 tracks. -- **Decoded packet sizes (`BinkGetTrackData` after `BinkDoFrame`):** every track overwrote the sentinel buffer with - decoded bytes — **145,920 bytes** on frame 0 (initial pre-roll, matching `header_max_size` in 229/229) and - **7,680 bytes** on frame 1 (229/229; confirmed through frame 2 on 1-, 2-, and 4-track samples). -The loader-side runs behind these numbers are recorded in [`runtime/test/bink_decode_test.md`](../runtime/test/bink_decode_test.md), -[`runtime/test/bink_audio_test.md`](../runtime/test/bink_audio_test.md) and -[`runtime/test/bink_play.md`](../runtime/test/bink_play.md). - -## 5. What is still unknown - -- **Roles.** The RPF9 table of contents is encrypted, but `tools/bink_names.py` recovers each stream's path from - the mount lists ([section 8](#8-names-from-the-mount-lists)), and the folder names group the streams by use. What - the game does with each folder at run time is not established. -- **Audio association.** The header gives a track count, sample rate, flags and track IDs, but not which audio - belongs to which video frame beyond the interleaving described by the Bink format. `BinkOpenTrack`, - `BinkGetTrackID`, `BinkGetTrackType`, `BinkGetTrackMaxSize`, and `BinkGetTrackData` succeed on all 229 tracks - across the 196 audio-bearing streams - ([section 4](#audio-track-decoding-binkopentrack--binkgettrackdata-asset-323)) and return 16-bit PCM for every - one of them (the byte count each run prints; `runtime/test/bink_audio_test.md`, - [coverage above](#decode-coverage-over-the-whole-archive)): positional track index `i` maps 1:1 to header - `track_ids[i]` (`0..3`), `BinkGetTrackType` returns `(flags << 16) | sample_rate`, and `BinkGetTrackData` - returned 145,920 bytes on frame 0 and 7,680 bytes on frame 1 across all 229 tracks (with frame 2 also checked on - 1-, 2-, and 4-track samples; later frames were not swept and may return 7,680 or 0 bytes). Which language or mix - role the game assigns to track IDs `0, 1, 2, 3` at run time remains unknown. -- **Playback integration.** The executable is not in the package. Where the game calls `BinkOpen`, which flags it - passes, whether it uses `BinkDoFrameAsync`, `BinkGoto`, subtitles or the GPU path, and how it schedules movies - against streaming are all unknown. -- **Bink2Scarlett ABI.** [ABI over the archive](#abi-over-the-archive) gives the `HBINK` and `BINKSUMMARY` fields - that match the stream header, the bytes `BinkGetSummary` writes (+0x00..+0x8F), and the return values of `BinkWait`, `BinkDoFrame` and - `BinkCopyToBuffer`. The rest of both structures, the async API, the GPU API and the XAudio2 setup are not - established. The DLL loads on - Windows only after the missing `xmem.dll` imports are supplied; a proper port needs an allocator shim with the - Xbox semantics, not necessarily `malloc`. -- **What the RPF trailer holds.** The 22,812 bytes after the last stream are no longer unexplained (ASSET-318): - 3,884 zeros pad to a 4 KiB boundary, and the remaining 18,928 bytes, to EOF, are exactly the header's `u32 +12`, - the RPF9 trailer ([rpf.md](rpf.md#the-trailer-at-eof); confirmed in 14 of the package's 22 archives, 8 - undecided, none against). Its contents are high-entropy (7.99 bits per byte) with no zlib or `KB2` header, like the TOC; this - project does not decode them. -- **Whether every frame of all 515 streams decodes correctly.** All 515 open and decode their first two frames - through the package's DLL ([coverage above](#decode-coverage-over-the-whole-archive)); nine were decoded as a - sample with frames viewed. No stream was decoded from its first frame to its last, and nothing compares the - output with a reference. -- **Why 22,812 bytes at the end are unread.** They are not a `KB2` stream and not zero. They may be an RPF footer - or leftover table data; the encrypted TOC prevents a name-level answer. -- **Full-stream playback beyond frame 0.** All 515 streams open and decode frame 0 with `Bink2Scarlett.dll` - (0 failed; see [Full 515-stream decode check](#full-515-stream-decode-check-asset-328)), settling stream-level - decodability. Decoding every one of the 425,440 frames and playing back the 229 audio tracks remain untested. - -## 6. No-sharing rule - -The repository and every PR contain **no** `.bk2`, no decoded frame, no audio, no extracted movie, and no log or -report that quotes frame pixels. The index files contain offsets, sizes, revisions, dimensions, frame counts, fps -and audio header flags only. Keep carved streams and decoded frames in your own temp/work folder. The project's -[CONTRIBUTING.md](../CONTRIBUTING.md) rule applies unchanged. - -## 7. Reproduce - -```sh -# 1. Index-only carve of the archive (no stream written) -python -I tools/rpf9_carve.py /movies.rpf /movies-index --index-only - -# 2. Stdlib index: CSV from the archive, or JSON from a carved directory -python -I tools/bink_index.py /movies.rpf --out /movies.csv -python -I tools/bink_index.py /movies --out /movies.json --format json - -# 3. Optional ffprobe columns (forced Bink demuxer; expects "no" for Bink 2 today) -python -I tools/bink_index.py /movies --out /movies-probe.csv --probe -``` - -The measured run produced 515 rows, 8,831,336,892 stream bytes, 1,094,744 zero bytes and 22,812 unread bytes from -the archive (before `bink_index.py` split off the RPF trailer; see section 3), and the same 515 rows with zero -unread from the carved directory. `--probe` produced 515 `no` values. - -## Appendix A: `Bink2Scarlett.dll` exports - -All 74 are named; the ordinal equals the index. This is the complete export table, read without loading the DLL. - -``` - 0 BinkAllocateFrameBuffers 37 BinkRegisterGPUDataBuffers - 1 BinkClose 38 BinkRequestStopAsyncThread - 2 BinkCloseTrack 39 BinkRequestStopAsyncThreadsMulti - 3 BinkControlBackgroundIO 40 BinkService - 4 BinkCopyToBuffer 41 BinkSetError - 5 BinkCopyToBufferRect 42 BinkSetFileOffset - 6 BinkCurrentSubtitle 43 BinkSetFrameRate - 7 BinkDoFrame 44 BinkSetIO - 8 BinkDoFrameAsync 45 BinkSetIOSize - 9 BinkDoFrameAsyncMulti 46 BinkSetMemory -10 BinkDoFrameAsyncWait 47 BinkSetOSFileCallbacks -11 BinkDoFramePlane 48 BinkSetPan -12 BinkFindXAudio2WinDevice 49 BinkSetSimulate -13 BinkFreeGlobals 50 BinkSetSoundOnOff -14 BinkGetError 51 BinkSetSoundSystem -15 BinkGetFrameBuffersInfo 52 BinkSetSoundSystem2 -16 BinkGetGPUDataBuffersInfo 53 BinkSetSoundTrack -17 BinkGetKeyFrame 54 BinkSetSpeakerVolumes -18 BinkGetPlatformInfo 55 BinkSetVideoOnOff -19 BinkGetRealtime 56 BinkSetVolume -20 BinkGetRects 57 BinkSetWillLoop -21 BinkGetSubtitleByIndex 58 BinkShouldSkip -22 BinkGetSummary 59 BinkStartAsyncThread -23 BinkGetTrackData 60 BinkUtilCPUs -24 BinkGetTrackID 61 BinkUtilFree -25 BinkGetTrackMaxSize 62 BinkUtilMalloc -26 BinkGetTrackType 63 BinkUtilMutexCreate -27 BinkGoto 64 BinkUtilMutexDestroy -28 BinkLoadSubtitles 65 BinkUtilMutexLock -29 BinkLogoAddress 66 BinkUtilMutexLockTimeOut -30 BinkNextFrame 67 BinkUtilMutexUnlock -31 BinkOpen 68 BinkUtilSoundGlobalLock -32 BinkOpenTrack 69 BinkUtilSoundGlobalUnlock -33 BinkOpenWithOptions 70 BinkWait -34 BinkOpenXAudio2 71 BinkWaitStopAsyncThread -35 BinkPause 72 BinkWaitStopAsyncThreadsMulti -36 BinkRegisterFrameBuffers 73 RADTimerRead -``` - -## 8. Names from the mount lists - -The table of contents is encrypted, but every pack registers its videos in a `CDataFileMgr__ContentChangeSetDef` -mount list as `$(common)/movies//.bk2`. For `movies.rpf` these are the -`core_binks` and `core_stinger_binks` lists in `common.rpf`; each other pack carries its own `_binks` list. -The archive stores a pack's streams in the order of its list sorted by lowercase path: folder first, then file name -without the extension, compared as bytes (so `x_final_y` sorts before `x_finale`). A list can name more files than -the archive holds, because some entries are stored in other packs, so `tools/bink_names.py` aligns the two rather -than zipping them. The longest list (`core_binks`, 74,268 bytes) spans two zlib streams with an entry cut at the -boundary, so `--mount` rebuilds whole XML payloads with `gamedata_index.py` when it is given an archive or an -`rpf9_carve.py` directory. - -The alignment is a monotone dynamic programme over (list entry, stream in offset order) that may skip list entries, -never streams. Scores come from header facts only: `_720`/`_1080`/`_1440`/`_4k` in a name against the height, -`snapmatic/` against a portrait frame, `tv/sprt/` against 1280x720, and neighbours of one family (the name without -trailing digits or side/size words) sharing width, height and frame count. An optional pins CSV (`offset,path`, -alternatives separated by `|`) adds paths confirmed by watching the stream. Each row gets a confidence: - -| Confidence | Meaning | -|---|---| -| `verified` | a pin names exactly this path | -| `anchored` | a family neighbour agrees on the header, a name hint matched, or a pin allows this path | -| `bracketed` | between the nearest anchored rows (or the ends) the names and streams have equal counts, so no skipped entry can hide there | -| `positional` | only the order supports it | - -Measured on the 1.0.2.1 package (2026-11-22), without pins: - -| Archive | List entries | Streams | Anchored | Bracketed | Positional | Entries in other packs | -|---|---:|---:|---:|---:|---:|---:| -| `movies.rpf` | 537 | 515 | 361 | 129 | 25 | 22 | -| `story000.rpf` | 271 | 264 | 78 | 37 | 149 | 7 | -| `story000_restofworld.rpf` | 7 | 7 | 5 | 2 | 0 | 0 | -| `core_restofworld.rpf` | 11 | 11 | 0 | 11 | 0 | 0 | - -All 797 streams in the four archives get a path. A local pins file of 53 streams (42 exact, 11 narrowed to two or -three names), made by watching them, moved 32 rows in `movies.rpf` and 32 in `story000.rpf`. In `story000.rpf` all -32 had been `positional`. In `movies.rpf` 21 were `positional`, 1 `bracketed` and 10 `anchored`: runs of same-shape -siblings (`..._01`, `_02`, `_03`) anchor each other even when the whole run is shifted by one entry, so `anchored` -does not rule out an off-by-one inside such a run. With the pins, `movies.rpf` has 2 positional rows left and -`story000.rpf` 7. - -The collation was checked by eye on `story000.rpf`, where one list's own order disagrees with the archive. Comparing -names with the extension instead gives the same paths in all four archives of this package. - -The output names game files. Like the index, it is a local work product: do not commit it or attach it to an issue. - -```sh -# Lists read straight from common.rpf (a list split over several zlib streams is rebuilt whole) -python -I tools/bink_names.py /movies.rpf --mount /common.rpf --out /movies-names.csv - -# Reuse an index or an rpf9_carve.py directory, add pins, or name another pack's streams with its own list -python -I tools/bink_names.py /movies.csv --mount /common --pins /pins.csv --out /names.json -python -I tools/bink_names.py /pack/story000/story000.rpf --mount /pack/story000/story000.rpf --out /story000-names.csv -``` diff --git a/docs/multi_gpu_validation.md b/docs/multi_gpu_validation.md deleted file mode 100644 index dbea4da09..000000000 --- a/docs/multi_gpu_validation.md +++ /dev/null @@ -1,79 +0,0 @@ -# Multi-GPU validation on identical cards - -A small box with several identical GPUs is useful for **parallel sharding**, not for inventing several independent -hardware results. This page records the setup used for the eight-card RDNA1/RADV farm and the rules that kept its -numbers meaningful. Counts and pass/fail lines only: no shader corpus, game files, keys or private paths belong -here or in any report generated from it. - -## Hardware used - -Eight AMD Radeon Pro V540 cards, Navi 12 / gfx1011 (RDNA1, PCI `1002:7360`, subsystem `1002:1a34`, VBIOS -`113-D3020100-103`), on bare metal (no VM passthrough), each bound to `amdgpu` and reachable through a render node. -RADV Mesa 25.2.8, Vulkan device 1.4.318, loader 1.3.275, subgroup range 32..64. Ubuntu 24.04.4, kernel -7.0.0-31-generic, GCC 13.3.0, Python 3.12.3, CMake 3.28.3, llvm-mc 21.1.8 with the AMDGPU target, SPIRV-Tools -2026.1 (2025.1 is too old for the `FMAKHR` capability used by `LEONIDA_FMA=khr`). - -| PCI BDF | Render node | Shard label | -|---|---|---| -| `0000:1c:00.0` | `renderD128` | gpu0 | -| `0000:1f:00.0` | `renderD129` | gpu1 | -| `0000:55:00.0` | `renderD130` | gpu2 | -| `0000:58:00.0` | `renderD131` | gpu3 | -| `0000:8e:00.0` | `renderD132` | gpu4 | -| `0000:91:00.0` | `renderD133` | gpu5 | -| `0000:c7:00.0` | `renderD134` | gpu6 | -| `0000:ca:00.0` | `renderD135` | gpu7 | - -## Pinning one device per process - -Use the PCI BDF, never an index, and exclude software drivers explicitly: - -```sh -lspci -Dn -d 1002:7360 -DRI_PRIME='pci-0000_1c:00.0!' VK_LOADER_DRIVERS_SELECT='*radeon*' vulkaninfo --summary -``` - -For every BDF in the table, that check must show **exactly one** RADV NAVI12 device. If it shows none or several, -stop and report the blocker; do not substitute llvmpipe. The ICD file on this box is `radeon_icd.json`, so -`VK_LOADER_DRIVERS_SELECT='*radv*'` matches nothing and makes `vkCreateInstance` fail with `-9`. - -## Shard discipline - -- Split work into **disjoint** units: different seeds for the fuzzers, different `--start`/`--count` ranges for a - translated index, or different test names. Eight processes running the same full suite are eight copies of one - result, not a validation farm. -- Run one process per card, keep logs per card, and aggregate counts afterwards. -- Each PR verification used a clean worktree at the PR head and, where a base was named, a second worktree at that - base with its own freshly built programs. Mixing a script from one commit with binaries from another produces - false failures (see "Known problems" in [testing.md](testing.md)). -- When a shard fails, rerun the *same* shard on two or three other cards. Failing everywhere points to a driver or - corpus issue; failing on one card points to that card. Re-run single failing tests in isolation before calling a - result reproducible. -- A transient single-card anomaly must be reported as such. On this box `0000:ca:00.0` intermittently produced a - few mismatching pixels in different fragment tests on different full-suite runs, while each failing test passed - 3/3 in isolation and the other seven cards were clean. It was never counted as a PR regression. - -## Results already collected - -These are aggregate results from this box; the full per-command counts are in the linked #166 entries, not in this -page. No game-derived data was used for any of them. - -- Single-card RDNA1/RADV baseline suite and TEST-71 fuzz matrix: [#166 entry](https://github.com/ItsNotRexed/Leonida/issues/166#issuecomment-7078373329). -- Eight-card fallback matrix and extended fuzz campaign (seeds 4–11, 200 programs, both waves): [#166 entry](https://github.com/ItsNotRexed/Leonida/issues/166#issuecomment-7079130604). -- Native MUBUF `OOB_SELECT` measurement on gfx1011 with `tools/hw_oracle` and `tools/buffer_bounds_probe.py`: 12 cases - at wave32 and wave64 (24 groups), all following the measured RDNA2/GFX11 column, 8 disagreements with Mesa's - GFX10 column, 0 wave32/wave64 differences (SHADER-341; results in [buffer_bounds.md](buffer_bounds.md)). - -Two failures recur on these cards at the tested commits and were confirmed on clean base worktrees, so they are -driver-version limitations rather than regressions from the PRs tested here: `cs_w32_salu64` (wrong high word of -an `s_bfe_i64` field) and `cs_signed_zero_nan`. The latter is the signed-zero class tracked in #1203. A real -regression was found on PR #2715: two wave64 pixel fixtures returned the clear value on all three cards tested while -the PR's base passed them. - -## Using a translated corpus - -If a private translated shader directory containing `index.json` and `stubs/` is available, shard the *sorted* index -with `vk_pipeline_check --start`/`--count` and one pipeline cache per shard. Record ok/skipped/failed by stage and -generic error category only: never post shader names, contents or private paths. RDNA1 legitimately skips mesh, -barycentric and maintenance8 shaders; report those separately from passes. If no such directory exists, do not run -this phase and do not report pipeline counts as if you had. diff --git a/docs/navmesh.md b/docs/navmesh.md deleted file mode 100644 index 9027ea2c7..000000000 --- a/docs/navmesh.md +++ /dev/null @@ -1,651 +0,0 @@ -# Navmesh archive (`navmeshes.rpf`) - -**Status: decoded at container, header, schema and spatial-table level; stdlib decoder in `tools/navmesh_decode.py`.** -All 90,295 carved streams in `navmeshes.rpf` are classified with **0 unclassified streams** into four top-level -resource classes (`0DRP` cover-point resources, `0x00010015` navmesh tiles, Band-3 `grid` sparse-table resources and -`PSIN` metadata containers) plus their single continuation streams. Every number below is aggregate metadata from a -full read-only scan of one Xbox Series 1.0.2.1 package (`6,707,512,496` bytes). No payload, key, name or carved file -is in this document or the repository. - -## Method - -- The package archive is **6,707,512,496 bytes**; its RPF9 data area starts at `0x780`, leaving a span of - `6,707,510,576` bytes. -- Walked sequentially with the fixed zlib carver rule (`ZHDR = \x78[\x01\x5e\x9c\xda]`, advance by bytes actually - consumed). The encrypted RPF9 table of contents and encrypted sub-RPF headers were never touched. -- Stream totals match the carver threshold (`inflated >= 64` bytes) for exact parity with `tools/navmesh_index.py`. - `tools/navmesh_decode.py` also accepts `< 64`-byte zlib streams strictly as continuations when a resource's block - map declares a second stream, recovering **10** tiny continuations (`3` `0DRP`, `7` `0x00010015`) that the carver's - 64-byte cutoff skipped. -- Full-archive `--deep` verification (`tools/navmesh_decode.py navmeshes.rpf --deep`) ran in 236 s on Windows x64 - (Python 3.13, stdlib only) with **0 check failures** across all `64,729` `pgBase` resources (`9,603` `0DRP`, - `27,644` `0x00010015` navmesh tiles, `27,482` Band-3 `grid` resources). - -## Composition and 3-band layout - -| Metric | Value | -|---|---:| -| File bytes | 6,707,512,496 | -| Scanned span (file minus `0x780`) | 6,707,510,576 | -| Carved zlib streams (`>= 64` B) | 90,295 | -| Stored (compressed) bytes | 6,540,238,392 (97.51% of span) | -| Inflated bytes | 20,551,068,624 (3.14x stored) | -| Zero padding | 161,191,191 (2.40%) | -| Unread (non-zero, non-stream) | 6,080,993 (0.09%) | -| Tiny continuations recovered (`16–48` B) | 10 (`3` `0DRP`, `7` `0x00010015`) | -| Bink 2 streams | 0 | - -Every stream in the earlier 53,026 "other" bucket is now classified into continuations or the Band-3 `grid` class -(**0 unclassified streams**): - -| Stream class | Role | Streams (`>= 64` B) | Stored bytes | Inflated bytes | Median inflated | -|---|---|---:|---:|---:|---:| -| `0DRP` | `0x7a` cover-point resource (`0DRP` at `+0x10`) | 9,603 | 745,601,504 | 2,764,382,624 | 196,608 | -| `0DRP` continuation *(was "other")* | 2nd stream of a `0DRP` (+3 tiny `< 64` B) | 2,478 | 19,473,516 | 37,778,384 | 10,944 | -| `0x00010015` | Navmesh tile (`u32 0x00010015` at `+0x14`) | 27,644 | 5,346,712,784 | 15,281,523,008 | 131,072 | -| `0x00010015` continuation *(was "other")* | 2nd stream of a navmesh tile (+7 tiny `< 64` B) | 23,039 | 51,000,438 | 139,234,640 | 1,840 | -| `grid` *(was "other")* | Band-3 sparse-grid SwissTable resource (`0x60` header) | 27,482 | 375,870,578 | 2,325,442,800 | 41,912 | -| `grid` continuation *(was "other")* | 2nd stream of a `grid` resource | 6 | 19,805 | 339,456 | 55,968 | -| `PSIN` | `PSIN` metadata container (`PSIN` at `+0x00`) | 22 | 628,344 | 1,413,376 | 65,536 | -| `PSIN` continuation *(was "other")* | 2nd stream of a `PSIN` container | 21 | 931,423 | 954,336 | 44,440 | -| **Total** | **0 unclassified streams** | **90,295** | **6,540,238,392** | **20,551,068,624** | | - -The archive is strictly partitioned into three contiguous, non-overlapping offset bands separated by 29 encrypted -sub-RPF header/TOC gaps (`5,947,550` bytes total) plus `117,745` non-zero bytes at EOF: - -| Band | Archive offset range | Contents | -|---|---|---| -| **Band 1** (`0DRP`) | `0x0000037010` – `0x002ed51619` | All `9,603` `0DRP` cover-point resources (`7,122` 1-stream, `2,481` 2-stream) | -| **Band 2** (`0x00010015`) | `0x002ed87000` – `0x0174b93f8f` | All `27,644` navmesh tiles (`4,598` 1-stream, `23,046` 2-stream) + `11` `PSIN` (`10` regional + `1` non-grid) | -| **Band 3** (`grid`) | `0x0174bbc000` – `0x018fcab8bf` | All `27,482` `grid` resources (`27,476` 1-stream, `6` 2-stream) + `11` `PSIN` (`10` identical regional pairs + `1` EOF v79) | - -Within Bands 2 and 3, static tiles are packed into 10 regional sub-RPF partitions (`2,448` unique tiles each, headed by -10 byte-for-byte identical `PSIN` version-256 pairs), plus an overlay partition of `3,002` variant tiles (`940` unique -sector IDs, subset of the base grid) and (in Band 2 only) a non-grid partition of `161` dynamic local-space navmeshes -plus `1` whole-world coarse navmesh. - -## Shared `pgBase` prefix and block map (`+0x00..+0x0F`) - -All three resource classes (`0DRP`, `0x00010015`, `grid`) share the same 16-byte prefix and `0x50000000` virtual -pointer base (`offset = u64_ptr - 0x50000000` when the upper 32 bits are zero and `0x50000000 <= ptr < 0x60000000`): - -- `+0x00` (`u64`): always `0` (`64,729 / 64,729`). -- `+0x08` (`u64`): pointer to a block-map descriptor (`24` bytes on `0DRP`, `32` bytes on `0x00010015` and `grid`): - - `+0x00` (`u64`): `0` - - `+0x08` (`u64`): **exact logical zlib stream count (`1` or `2`)** — matches actual stream membership on - `9,603 / 9,603` `0DRP`, `27,644 / 27,644` `0x00010015`, and `27,482 / 27,482` `grid` resources (`0` resources span - more than 2 streams). - - `+0x10` (`u64`): `0` (and `+0x18` `u64` is `0` on `100%` of `0x00010015` and `grid`; on `105` `0DRP` pages the next - object begins at `+0x18`, confirming the `0DRP` block map is 24 bytes). - -## `0DRP` directory pages (`9,603` pages — `0x7a` cover-point resources) - -`0DRP` pages in `navmeshes.rpf` are **self-describing `0x7a` resources** (the same container format documented in -[world.md](world.md) and [page_directory.md](page_directory.md)). Reconciling the full `9,603`-page corpus settles the -fields previously marked "not decoded" (`+0x48` eight `u16` values, `+0x60` "key" and `+0x70` repeating records). - -### Fixed header (`0x60` bytes, measured on all `9,603` pages) - -| Offset | Size | Observed | Verified meaning | -|---:|---:|---|---| -| `+0x00` | 8 | zero (`9,603 / 9,603`) | `pgBase` vtable slot | -| `+0x08` | 8 | `0x50xxxxxx`, 16-byte aligned | pointer to 24-byte block map (`u64@+8 == stream_count` on `9,603 / 9,603`) | -| `+0x10` | 4 | `30 44 52 50` (`0DRP`) | `0x7a` container magic | -| `+0x14` | 4 | `122` (`0x7A`, `9,603 / 9,603`) | format version | -| `+0x18` | 8 | zero (`9,603 / 9,603`) | reserved | -| `+0x20` | 4 | `1–6` (`3`: 7,650, `4`: 932, `2`: 779, `6`: 219, `5`: 22, `1`: 1) | **1-based index into `q38` naming the root object block** (`1 <= u20 <= n_blocks` and `blocks[u20-1].hash` is in `q28` on `9,603 / 9,603`) | -| `+0x24` | 4 | zero (`9,603 / 9,603`) | high half of `+0x20` | -| `+0x28` | 8 | `0x50xxxxxx`, 8-byte aligned | pointer to `q28` struct schema table (`32` B/record) | -| `+0x30` | 8 | `0x50xxxxxx` (`9,600`) or `0` (`3`) | pointer to `q30` enum schema table (`24` B/record) | -| `+0x38` | 8 | `0x50xxxxxx`, 16-byte aligned | pointer to `q38` instance block table (`16` B/record) | -| `+0x40` | 8 | `0x50xxxxxx`, 8-byte aligned | pointer to `q40` auxiliary table (`{u32 count, count x {u32 tag, u32 size}, payloads}`) | -| `+0x48` | 2 | `2–12` | `n_structs`: number of `q28` struct definitions | -| `+0x4a` | 2 | `0–4` | `n_enums`: number of `q30` enum definitions | -| `+0x4c` | 2 | `2–6` | `n_blocks`: number of `q38` instance blocks | -| `+0x4e` | 2 | `0` (`2,578`) or `1..602` (`7,025`) | **`pages_4k`:** `0` or `ceil(data_end / 4096)` (`9,603 / 9,603`; see rule below) | -| `+0x50` | 16 | zero (`9,603 / 9,603`) | reserved (covers the trailing four `u16`s of `+0x48..+0x57` plus `+0x58..+0x5f`) | -| `+0x60` | — | first `q38` instance block (`9,603 / 9,603`) | **payload, not a header field** | - -#### Decoding `u16@0x4e` (`pages_4k`) - -Define the runtime data end before schema tables as -`data_end = max(max(block.target + block.size), q38 + 16 * n_blocks, p08 + 24)` and `pg = ceil(data_end / 4096)`. -Across all **9,603 / 9,603** pages (`0` exceptions), `u16@0x4e` is either `0` or `pg`: - -- When `pg * 4096 < stream_end` (`stream_end = len(stream0)` if `data_end <= len(stream0)` else `len(joined)`): - `u16@0x4e == pg` on **100%** of pages. -- When `pg * 4096 > stream_end` (Stream 1 holds `data_end` without reaching the next 4 KiB multiple) or on single-stream - pages where `pg * 4096 == len(stream0)`: `u16@0x4e == 0` on **100%** of pages. -- On the **307** two-stream pages where `data_end <= len(stream0)` and `pg * 4096 == len(stream0)` (runtime data ends - in the last 4 KiB of Stream 0 while `q28`/`q30`/`q40` spill into Stream 1): `93` have `u16@0x4e == pg` and `214` have - `u16@0x4e == 0`. What breaks the tie on that exact 4 KiB boundary is **open** (likely the virtual page split in the - encrypted TOC). - -### Schema tables (`q28`, `q30`, `q38`, `q40`) - -- **`q28` struct table (`32` B/record):** `{u32 name_hash, u32 signature, u64 flags, ptr64 members, u32 size, u16 0, u16 member_count}`. Each member is `16` bytes: `{u32 name_hash, u32 offset, u8 type, u8 subtype, u16 ref, u32 extra}`. -- **`q30` enum table (`24` B/record):** `{u32 name_hash, u32 signature, ptr64 values, u64 count}`. Each enum value is `16` bytes: `{i64 value, u32 name_hash, u32 0}`. Values are dense `0 .. count - 1` on `9,603 / 9,603` pages. -- **`q38` instance blocks (`16` B/record):** `{u32 struct_or_type_hash, u32 byte_size, ptr64 target}`. Disjoint with **0 overlaps** across all `9,603` pages (`54,898` total records, including `18` on the 3 tiny-continuation pages); every page has a block starting at `+0x60`. -- **`q40` auxiliary table:** `{u32 count, count x {u32 tag, u32 size}, payload bytes}`. Fits cleanly in-bounds on `9,603 / 9,603` pages. On `8,275` world-grid `CCoverPointRegion` pages it holds a single tag `0x101` (`32/48/64/80` B = `2..5` 16-byte entries); on all `137` non-grid `CCoverPointRegion` pages and all `1,187` `0x4712787b` pages `count == 0`; the 4 singleton pages carry larger `0x101`, `0x207` or `0x211` tables. - -Only **10 distinct schemas** (6 root structs) occur across all `9,603` `0DRP` pages — **all cover-point data, not -navmesh polygons**. Struct/enum/member hashes match standard RAGE cover names under **case-sensitive joaat32** -(verified from hand-typed clean-room candidates in `tools/navmesh_decode.py`): - -| Root struct (joaat32) | Pages | Schemas | Summary | -|---|---:|---:|---| -| `CCoverPointRegion` (`0x2283b2cb`, `304` B) | 8,412 | 2 (`11–12` structs) | `8,275` 128 m × 128 m world-grid cover tiles + `137` smaller local/interior tiles; `15,474,729` `CCoverPointNode` (`0x0bcb00e4`, `160` B) instances (`+0xA0` `u16` array count `== block_count` on `8,412 / 8,412`; `+0x04` `i32` point count matches on `8,411 / 8,412`, with 1 local tile at `0x2e329010` having `23` vs `8` serialized nodes); world bounds (`+0x10`/`+0x20`) `X ∈ [-10,368, +10,411.9]`, `Y ∈ [-8,448, +9,472]`, `Z ∈ [-500, +1,350]` m; `256` sub-regions (`0xde5f1345`, `4,096` B) + `CCoverSpatialTreeNode` (`0xbb5a70d8`, `64` B) | -| `0x4712787b` (`48` B, name open) | 1,187 | 4 (`3–9` structs) | Local-space dynamic/entity cover sets (`155,250` `CCoverPointNode` instances on `1,173` pages, `0` nodes on `14` pages; node `+0x38` `f32[3]` positions in `[-63.1, +67.0] × [-36.0, +35.4] × [-72.1, +6.9]` m; `q40` always empty) | -| `CCoverPointRegionManifest` (`0xe842b0d6`, `48` B) | 1 | 1 (`4` structs) | Singleton at `0xca9d010`: `6,446` `CCoverPointRegionDef` (`0xbea9889e`, `64` B) entries | -| `0xb6dbe11b` (`16` B, name open) | 1 | 1 (`2` structs) | Singleton at `0x24c9a010`: `1,829` `0x0904902e` (`24` B) entries mapping hashes/strings to `RegionIndex` | -| `0x339accda` / `0x2bf76252` (`24` B, names open) | 2 | 2 (`2` structs each) | Two singleton map tables (`0x2e43e010`, `0x2ed47010`) | - -Verified case-sensitive joaat32 matches (`22` total): `CCoverPointRegion` (`0x2283b2cb`), `CCoverPointNode` -(`0x0bcb00e4`), `CCoverNodeId` (`0xa33600ff`), `CCoverPointUsageInfo` (`0x7f072f43`), `CCoverSpatialTree` -(`0x9b39705a`), `CCoverSpatialTreeNode` (`0xbb5a70d8`), `CCoverPointRegionManifest` (`0xe842b0d6`), -`CCoverPointRegionDef` (`0xbea9889e`), `rage__spdAABB` (`0xf377e8c8`), `eCoverFlags` (`0x42338022`, 54 values), -`eCoverHeight` (`0x5c3b2e01`, 4 values), `eCoverUsage` (`0x7245ba24`, 6 values), `eCoverRegionFlags` (`0xb1cf92b0`, 3 -values), `Uid` (`0x1863ce8e`), `SpatialTreeNodes` (`0xabe9944f`), `Entries` (`0xd566f590`), `RegionIndex` -(`0xd0a257d2`), `COVHEIGHT_PRONE` (`0x4d20005e`), `COVUSE_WALLTOLEFT` (`0xfdd96e08`), `COVUSE_WALLTORIGHT` -(`0xb00bfdf7`), `COVUSE_WALLTOBOTH` (`0xeae2591d`), `COVUSE_WALLTONEITHER` (`0x399bbf46`). - -### Explaining the `+0x60` "key" and `+0x70` repeating records - -The earlier report observed an opaque `u64` at `+0x60` (`9,409` nonzero, `194` zero), `u32_68` (`1,381` zeros), zero at -`+0x6c`, and repeating `key / u32 / 0xffffffff` patterns at `+0x70`. Every one of those counts comes directly from the -first `q38` payload block starting at `+0x60`: - -| Block placed at `+0x60` | Pages | `+0x60..+0x8f` byte layout | -|---|---:|---| -| `CCoverPointNode[]` (`0x0bcb00e4`, `160` B/node) | **9,378** (`8,205` region + `1,173` dynamic) | Node 0 starts with **three 16-byte `CCoverNodeId` (`0xa33600ff`) structs** at `+0x60`, `+0x70`, `+0x80`, each `{u64 id_key, u32 field_08, u32 local_index}`. `+0x60..+0x67` is `Uid.id_key` (always nonzero); `+0x68..+0x6b` is `0` on all `1,173` local/dynamic `0x4712787b` pages; `+0x6c..+0x6f` is `Uid.local_index` (`0` on all `9,378` pages because it is node 0). **`+0x70..+0x7f`** is the second `CCoverNodeId` (repeating `Uid.id_key` on `1,186` pages and holding sentinel `0xffffffff` at `+0x7c` on `3,966` pages and at `+0x78` on `1,912` pages — the `+0x70` pattern). **`+0x80..+0x8f`** is the third `CCoverNodeId` (repeating `id_key` on `2,237` pages, `local_index == 1` on `9,105` pages, `0xffffffff` on `203` pages). | -| `0xde5f1345[]` (`256 × 16` B sub-regions) | **207** (all `CCoverPointRegion`) | First `atArray` descriptor. On **`194`** pages the first sub-region is empty (`{0, 0, 0}` -> exact match for all **194** zero `+0x60` values and `194` of the `u32_68 == 0` pages); on `13` pages it is non-empty. | -| `0x00000100` (map-pair array) | **16** (`14` empty `0x4712787b` + `2` singletons) | Map entry array; contributes the remaining `14` `u32_68 == 0` pages (`1,173 + 194 + 14 = 1,381` exact). | -| `CCoverPointRegionDef[]` / `0x0904902e[]` | **2** (`2` singletons) | First manifest/index record (accounts for 2 of the 3 nonzero `+0x6c` words; `0x339accda` accounts for the 3rd). | - -## Typed data pages (`27,644` pages — `0x00010015` navmesh tiles) - -The 27,644 pages with `u32 0x00010015` at `+0x14` are the actual **navmesh geometry tiles** (RAGE `CNavMesh`-family -layout, fixed `0xF0`-byte header, `14.36 GiB` / `15,420,757,856` bytes inflated including continuations). - -### Fixed header (`0x000..0x0EF`, 240 bytes, verified on all `27,644` pages) - -| Offset | Size | Type | Verified meaning | Full-corpus check (`27,644` pages) | -|---:|---:|---|---|---| -| `+0x00` | 8 | `u64` | `pgBase` vtable slot | `0` on `27,644 / 27,644` | -| `+0x08` | 8 | `ptr64` | Pointer to 32-byte block map | `bm[1] == stream_count` (`4,598` × 1, `23,046` × 2) on `27,644 / 27,644` | -| `+0x10` | 4 | `u32` | Navmesh flags bitmask | `{9: 18791, 11: 5507, 3: 3149, 7: 161, 1: 35, 69: 1}` | -| `+0x14` | 4 | `u32` | Format word (`0x00010015`, low16 = `21`) | `0x00010015` on `27,644 / 27,644` | -| `+0x20` | 64 | `f32[16]` | Transform matrix (padded 3×4) | Identity `(1,0,0,0 / 0,1,0,0 / 0,0,1,0 / 0,0,0,0)` on `27,644 / 27,644` | -| `+0x60` | 12 | `f32[3]` | 3D tile extents `(dx, dy, dz)` | Matches `quadtree_root.vMax - vMin` (`< 0.02` m) on `27,644 / 27,644`; `(128, 128)` on all `27,482` static tiles | -| `+0x70` | 8 | `ptr64` | `aiSplitArray` of compressed vertices (`6` B: `u16[3]`) | Valid & total `== u32@0xC0` (`138,041,746` verts, max `52,608`) on `27,644 / 27,644` | -| `+0x78` | 8 | `ptr64` | Uncompressed vertex array (unused; bit 0 always set) | `0` on `27,644 / 27,644` | -| `+0x80` | 8 | `ptr64` | `aiSplitArray` of vertex indices (`2` B: `u16`) | Valid, total `== u32@0x90`, all `< u32@0xC0` on `27,644 / 27,644` | -| `+0x88` | 8 | `ptr64` | `aiSplitArray` of adjacent-poly edges (`12` B) | Valid & total `== u32@0x90` on `27,644 / 27,644` | -| `+0x90` | 4 | `u32` | Index / adjacency pool size | Sum `493,024,188`, max `235,411`; equals `sum(poly.num_verts)` on `27,644 / 27,644` | -| `+0x98` | 8 | `ptr64` | `aiSplitArray` of polygons (`44` B) | Valid, total `== u32@0xC4` (`124,768,148` polys, max `71,803`), contiguous chain, `poly+0 == u32@0xC8` and `poly+4 == (index start << 4) \| count` on `27,644 / 27,644` | -| `+0xA0` | 8 | `ptr64` | Spatial quadtree root (`96` B nodes, `32` B leaves) | Full tree (`2,337,904` nodes, `1,760,339` leaves, max depth `9`) valid & all leaf indices `< u32@0xC4` on `27,644 / 27,644` | -| `+0xA8` | 8 | `ptr64` | Nullable special-link array (`32` B, count `u32@0xD4`) | Non-null iff `flags & 2` (`8,817` pages); in-bounds `27,644 / 27,644` | -| `+0xB0` | 8 | `ptr64` | Nullable special-link index table (`u16`, count `u32@0xD8`) | Non-null iff `flags & 2`; in-bounds & all entries `< u32@0xD4` on `27,644 / 27,644` (`2` tiles have `d8 < d4`) | -| `+0xB8` | 8 | `ptr64` | Nullable 96-byte obstacle footprint array (count `u32@0xDC`) | Present on `9,425` pages (`6,246,890` records = `3,123,445` outer/inner contour pairs); in-bounds & valid `27,644 / 27,644` | -| `+0xC0` | 4 | `u32` | Vertex count | Min `4`, max `52,608`, sum `138,041,746` | -| `+0xC4` | 4 | `u32` | Polygon count | Min `1`, max `71,803`, sum `124,768,148` | -| `+0xC8` | 4 | `u32` | 512 × 512 sector ID (`0` if `flags & 4`) | `0` iff `flags & 4` (`162` pages); exact `136 × 180 = 24,480` static grid | -| `+0xCC` | 4 | `u32` | Core mesh data byte size | `6*c0 + 14*pool + 44*c4 + 32*d4 == u32@0xCC` with **0 residual** on `27,644 / 27,644` | -| `+0xD4` / `+0xD8` / `+0xDC` | 12 | `u32[3]` | Special-link, link-index, and `+0xB8` record counts | Sums `26,679,246` / `26,903,247` / `6,246,890` | -| `+0xE8` | 4 | `u8[4]` | Build stamp (`0` if `flags & 4`): second, minute, hour, day of month | `7` distinct values (`0` on `162`, `0x09090516` on `24,474`, `0x160e3132` on `3,003`, 4 rare on `5`); see [Build stamp](#build-stamp-0xe8) | - -Reserved slots `+0x18..+0x1f`, `+0x6c..+0x6f`, `+0x78..+0x7f`, `+0x94..+0x97`, `+0xd0..+0xd3`, `+0xe0..+0xe7`, and -`+0xec..+0xef` are zero on `27,644 / 27,644` pages. - -### Build stamp (`+0xE8`) - -Read as four bytes from the lowest address, every nonzero value is a second, a minute, an hour and a day of month, -the first four fields of C's `struct tm` in their order. No month or year is stored. The numbers are for the -1.0.2.1 package (ASSET-282): - -| `u32@0xE8` | Bytes | Reads as | Tiles | Grid positions | -|---|---|---|---:|---| -| `0x09090516` | 22, 5, 9, 9 | day 9, 09:05:22 | 24,474 | 24,474 of 24,480: 23,536 alone, 938 shared | -| `0x160e3132` | 50, 49, 14, 22 | day 22, 14:49:50 | 3,003 | 940, never alone | -| `0x0f0e1b37` | 55, 27, 14, 15 | day 15, 14:27:55 | 2 | 2 adjacent, alone | -| `0x1d07151c` | 28, 21, 7, 29 | day 29, 07:21:28 | 1 | alone | -| `0x18101739` | 57, 23, 16, 24 | day 24, 16:23:57 | 1 | shared with 2 day-22 tiles | -| `0x0b0a2f1a` | 26, 47, 10, 11 | day 11, 10:47:26 | 1 | alone | -| `0` | | not a grid tile | 162 | the `flags & 4` meshes | - -- **Only the date and time reading fits all six nonzero values.** In each one, the low two bytes are below 60, the - third is below 24 and the top byte is 1 to 31. Six independent random words land in those ranges with a - probability of about 6 × 10⁻²⁰. The low two bytes could in principle be the other way round (minute first). The - `struct tm` order is the natural reading, but the data can't tell them apart. -- **The day-22 stamp marks tiles added on top of the base grid.** The 27,482 static tiles sit on 24,480 grid - positions (the `u32@0xC8` sector, above). The 3,002 extra tiles are all on 940 positions that hold 2 to 40 tiles, - and every one of those positions has day-22 tiles. 2,984 of the 3,003 day-22 tiles share their position with a - day-9 tile, and on all 938 positions with both, the day-22 tiles come later in the archive. The other 19 are on two - positions without a day-9 tile: 17 at sector (255, 248), and 2 with the day-24 tile at (248, 246). On 450 of the - 938, the first day-22 tile has the same vertex and polygon counts as the day-9 tile. What the stacked tiles are for - is not measured. -- **Neighbouring tiles share a stamp.** Taking the last tile in the archive at each position (the day-22 one where a - position has both), 98.12% of the 48,644 pairs of grid neighbours have the same stamp, against 92.58% for stamps - placed at random with the same frequencies. Taking the first tile instead gives 99.95% against 99.95%, which says - nothing, because almost every first tile is day 9. - -Method: `tools/navmesh_decode.py`'s own scan of `navmeshes.rpf`, with each tile's `u32@0xE8`, `u32@0xC8`, flags, -counts and archive offset recorded per tile. No geometry was kept. - -The `+4` word of a polygon packs `(index start << 4) | count`; the runs tile the index pool in order -(`tools/navmesh_decode.py --deep` checks it on all `124,768,148` polygons, 0 failures), which caps a polygon at 15 -vertices. 6stars independently reads the same packing. Its polygon `+0x28` bit 17 and `+0x18` bit 27 -road/pavement labels were not adopted: a 1,027,984-polygon sample over 238 tiles sets both bits on 258 polygons, so -they are not a partition, and in the lane-graph count [below](#polygon-flags-under-the-lane-graph) neither is under -most lane nodes; `+0x18` bits 8 and 13 are. No 6stars code was copied; the repository has no licence. - -### Flags (`u32@0x10`) and 512 × 512 world grid - -- **Bit 0 (`0x01`)**: set on `27,644 / 27,644` (compressed 6-byte vertices at `+0x70`, `+0x78 == 0`). -- **Bit 1 (`0x02`)**: exact bijection (`27,644 / 27,644`) with special links (`+0xA8/+0xB0` non-null, `u32@0xD4/0xD8 > 0`; `8,817` tiles). -- **Bit 2 (`0x04`)**: exact bijection (`27,644 / 27,644`) with non-grid meshes (`u32@0xC8 == 0`, `u32@0xE8 == 0`: `161` local-space dynamic meshes with `flags = 7` + `1` whole-world coarse mesh with `flags = 69`). -- **Bit 3 (`0x08`)**: set on `24,298` tiles (`9` or `11`), clear on `3,346`. `0 / 3,346` bit-3-clear tiles contain any polygon with `poly+0x18 & 0x80000` (water candidate), whereas `24,009 / 24,298` (`98.81%`) bit-3-set tiles do; the remaining `289` bit-3-set tiles have an unresolved secondary trigger. -- **Bit 6 (`0x40`)**: set on `1 / 27,644` (`flags = 69`, the single global coarse mesh). - -For all `27,482` static tiles (`(flags & 4) == 0`), `u32@0xC8` encodes the tile origin bit-for-bit against the quadtree -root AABB (`27,482 / 27,482`): - -```text -sector_x = u32@0xC8 & 0x1FF # 160 .. 295 (136 columns) -sector_y = u32@0xC8 >> 9 # 179 .. 358 (180 rows) -world_min_x = (sector_x - 256) * 128.0 # -12,288 .. +4,992 m (max +5,120 m) -world_min_y = (sector_y - 256) * 128.0 # -9,856 .. +13,056 m (max +13,184 m) -``` - -The `24,480` unique static sector IDs form a complete, gap-free `136 × 180` rectangle (`Z ∈ [-78.55, +403.84]` m). - -### Adjacent-polygon edges (`+0x88`, `493,024,188` records) and special links (`+0xA8`/`+0xB0`, `26,679,246` records) - -- **12-byte adjacent-polygon edges (`+0x88`, count `u32@0x90`, `493,024,188` records across `27,644` tiles):** - Each record is `{u32 adj_sector, u16 adj_poly, u16 edge_meta, u32 edge_flags}`. Across all `493,024,188 / 493,024,188` - records (`0` exceptions): - - **`458,728,869`** (`93.04%`) are intra-tile neighbors with `adj_sector == u32@0xC8` and `adj_poly < u32@0xC4` - (`0` out-of-bounds polygon indices); - - **`34,295,319`** (`6.96%`) are open or tile-border edges with `adj_sector == 0xFFFFFFFF` and `adj_poly == 0xFFFF` - (cross-tile border stitching is performed at runtime rather than serialized in `+0x88`). -- **Polygon `+0x20` special-link prefix-sum chain (`124,768,148` polygons across `27,644` tiles):** - In every 44-byte polygon at `+0x98`, `u32@0x20` packs `link_count = w20 & 0x3F` (bits `0..5`, range `0..63`), - `link_start = (w20 >> 6) & 0x1FFFF` (bits `6..22`, up to `17,459`), and a 9-bit polygon flag field `w20 >> 23` - (bits `23..31`). Across all `27,644 / 27,644` tiles (including polygons with `link_count == 0` and linkless tiles - with `u32@0xD8 == 0`), `link_start` equals the exact running prefix sum of `link_count` across preceding polygons, - and the tile total after polygon `u32@0xC4 - 1` equals `u32@0xD8` (`0` failures). -- **32-byte special links (`+0xA8`, count `u32@0xD4`, `26,679,246` records across `8,817` tiles) and `+0xB0` index table - (`u16[u32@0xD8]`, `26,903,247` entries):** - Each 32-byte record at `+0xA8` is `{u16[3] pos0, u16[3] pos1, u16 poly0, u16 poly1, u32 sector0, u32 sector1, - u16 flags0, u16 flags1, u16 heading, u16 pad}`: - - `+0x00..+0x05` (`u16[3]`) and `+0x06..+0x0B` (`u16[3]`): quantized 3D link endpoints `pos0` and `pos1`. - - `+0x0C..+0x0F` (`u16 poly0, u16 poly1`) and `+0x10..+0x17` (`u32 sector0, u32 sector1`): endpoint polygon indices - and sector IDs. Across all `26,679,246 / 26,679,246` links, at least one endpoint sector equals the owning tile's - `u32@0xC8` (`26,398,281` intra-tile with `sector0 == sector1 == u32@0xC8`; `143,913` cross-tile with - `sector0 == u32@0xC8`; `137,052` cross-tile with `sector1 == u32@0xC8`; `0` with neither). Whenever - `sector0 == u32@0xC8`, `poly0 < u32@0xC4` (`26,542,194 / 26,542,194`); whenever `sector1 == u32@0xC8`, - `poly1 < u32@0xC4` (`26,535,333 / 26,535,333`). - - `+0x18..+0x1B` (`u16 flags0, u16 flags1`): link attribute and traversal type words (`flags1` top values: `0x0050` - on `11,492,614`, `0x0040` on `9,705,698`, `0x0030` on `4,281,168`, `0x0060` on `425,369`). - - `+0x1C..+0x1D` (`u16 heading`): 8-bit quantized heading angle (`< 256` on `26,679,246 / 26,679,246`; `u8@0x1C` - in `0..254`, `u8@0x1D == 0`). - - `+0x1E..+0x1F` (`u16 pad`): zero padding (`0` on `26,679,246 / 26,679,246`). - - Across all `26,903,247 / 26,903,247` entries of `+0xB0`, every entry `li = u16@(b0 + 2*k)` in polygon `pi`'s slice - `[link_start .. link_start + link_count)` indexes a 32-byte link at `+0xA8` satisfying - `(poly0 == pi or poly1 == pi) and (sector0 == u32@0xC8 or sector1 == u32@0xC8)`, and every referenced link is - listed by all of its local-tile endpoints (`poly0` when `sector0 == u32@0xC8`, and `poly1` when - `sector1 == u32@0xC8`; on cross-tile links where the foreign endpoint polygon index is `< u32@0xC4`, the offline - builder also indexed the link under that polygon index because it matched `poly0/poly1 == pi` without filtering - by `sector0/sector1 == u32@0xC8`). - -### Split arrays and quadtree layout - -- Each `aiSplitArray` descriptor (`48` B: `{u64 vtable, u64 total, ptr64 blocks, ptr64 starts, u64 nblocks, u64 0}`) - chunks elements into `floor(16384 / stride)` per non-final block (`6` B vertices: max `2,730`; `2` B vertex indices: - max `8,192`; `12` B adjacent edges: max `1,365`; `44` B polygons: max `372`). The header checksum - `6*c0 + 14*pool + 44*c4 + 32*d4 == u32@0xCC` independently proves all five core record strides on `27,644 / 27,644`. -- Each `96`-byte quadtree node stores min bounds (`+0x00` `f32[3]`), max bounds (`+0x10` `f32[3]`), `i16[6]` bounds (`+0x20`), a 4-byte-aligned - nullable leaf pointer (`+0x2C`), four 4-byte-aligned child pointers (`+0x34..+0x53`), and 12 trailing zero - bytes (`+0x54..+0x5F`). Each `32`-byte leaf holds `{u64 0, ptr64 poly_indices, u64 0, u64 num_polys}`. - -### Paired 96-byte obstacle footprint records (`+0xB8`, `6,246,890` records) - -On all `9,425` tiles where `u32@0xDC > 0`, `u32@0xDC` is even (`9,425 / 9,425`) and the array at `+0xB8` holds -`3,123,445` consecutive `(outer, inner)` pairs (`6,246,890` 96-byte records). Every pair `(rec[2*p], rec[2*p + 1])` -shares the identical 20-byte prefix `+0x00..+0x13` (`3,123,445 / 3,123,445`): - -| Offset | Size | Type | Verified meaning (`6,246,890 / 6,246,890` records) | -|---:|---:|---|---| -| `+0x00` | 8 | `u64` | 64-bit obstacle/object UID (identical across `rec[2*p]` and `rec[2*p + 1]` on `3,123,445 / 3,123,445` pairs; repeated across adjacent tiles when a footprint crosses a 128 m tile border) | -| `+0x08` | 12 | `f32[3]` | Finite 3D world-space anchor `(x, y, z)` (`6,246,890 / 6,246,890`, identical across each pair) | -| `+0x14` | 1 | `u8` | Contour role/flags: `0x00` (`2,750,542`) or `0x04` (`372,903`) on `rec[2*p]` (expanded outer contour), and `0x08` (`3,123,445`) on `rec[2*p + 1]` (inner core contour) on `3,123,445 / 3,123,445` pairs | -| `+0x15` | 1 | `u8` | 2D polygon vertex count `N` (`4` on `3,123,878` records, `8` on `3,123,012` records). `(rec[2*p].N, rec[2*p + 1].N)` is `(8, 4)` on `3,123,012` pairs (chamfered octagon around an inner quad, typically expanded by `128` fixed-point units) and `(4, 4)` on `433` pairs | -| `+0x16` | 64 | `i16[32]` | Up to 16 relative 2D `(dx, dy)` footprint vertices in signed 16-bit fixed point around `(x, y)`; trailing unused slots `+0x16 + 4*N .. +0x55` are zero on `6,246,890 / 6,246,890` | -| `+0x56` / `+0x58` | 4 | `i16`, `u16` | Vertical/extent words (`u16@0x56` range `0..65,535`, high bit set on `1,846,885`; `u16@0x58` range `3..65,534`, high bit set on `13,629`) | -| `+0x5A` | 6 | `u8[6]` | Trailing zero padding (`0` on `6,246,890 / 6,246,890`) | -### Polygon flags under the lane graph - -`tools/navmesh_nodes.py` puts the lane graph of `levels.rpf` ([world_lights_paths.md](world_lights_paths.md)) on -the navmesh: for each node it takes the polygon of the node's tile that contains the node in plan view and is -closest in height, and counts that polygon's flag bits. A polygon's height is the mean of its vertex heights, not -the surface height under the node, so on a slope the two differ (the 3 m cutoff below absorbs that). For comparison -it sums the plan area of the polygons that carry each bit over the same tiles; surfaces above one another, such as a -bridge over a road or the stacked tiles that share one sector id, each add their own area. A bit that most road -nodes stand on while it covers little of the area marks where the roads are. - -A vertex is `tile minimum + u16 / 65535 * tile extent` (the minimum is the quadtree root's, the extent `+0x60`). -The node heights confirm it: of the 63,806 nodes with a finite position (63,808 read), -63,802 lie over a polygon and 63,793 have one within 3 m above or below; the height -difference is 0.032 m at the median, 0.095 m at the 90th percentile and 0.28 m at the 99th. - -Measured over the 6,970 static tiles that hold a node (77,880,896 polygons with three -or more vertices, 120.2 km2 of plan area; 0 tiles unreadable). "Nodes" is how many of the 63,793 -nodes stand on a polygon with the bit; "area" is the share of the plan area such polygons cover: - -| Word | Bit | Nodes | Polygons | Area | Reading | -|---|---|---:|---:|---:|---| -| `+0x18` | 13 (`0x2000`) | 57,559 (90.2%) | 3,357,132 | 12.0% | under nine in ten nodes; SixNG's "road surface" | -| `+0x18` | 8 (`0x100`) | 58,528 (91.7%) | 251,917 | 2.6% | under nine in ten nodes, on a fifth of bit 13's area; not named | -| `+0x18` | 12 (`0x1000`) | 787 (1.2%) | 18,746,182 | 33.6% | not road: a third of the area, almost no node | -| `+0x18` | 19 (`0x80000`) | 3,980 (6.2%) | 3,263,052 | 23.6% | the water candidate above | -| `+0x18` | 27 (`0x8000000`) | 5,526 (8.7%) | 2,489,161 | 3.2% | 6stars's label; under few nodes | -| `+0x28` | 17 (`0x20000`) | 21,246 (33.3%) | 1,083,157 | 4.7% | 6stars's label; seven times its area share, but only a third of the nodes | - -No other bit of either word has more than 5% of the nodes, except `+0x28` bit 18 (4,520 nodes, 7.1%, on 1.6% of -the area). - -Bits 8 and 13 are mostly set together. The tool counts the four combinations: - -| `+0x18` bits 8 and 13 | Nodes | Polygons | Area | -|---|---:|---:|---:| -| both | 57,181 (89.6%) | 236,753 | 2.5% | -| bit 8 only | 1,347 (2.1%) | 15,164 | 0.1% | -| bit 13 only | 378 (0.6%) | 3,120,379 | 9.5% | -| neither | 4,887 (7.7%) | 74,508,600 | 87.8% | - -So nine in ten lane nodes stand on polygons that carry both bits, which cover 2.5% of the area. Bit 13 -alone covers almost four times that area (9.5%) with almost no node on it, and bit 8 alone is rare. -[SixNG](https://github.com/holdmysocks/SixNG) labels bit 13 "road surface" after a visual check -(`crates/sixng-core/src/navmesh.rs`, commit `0619601`, GPL-3.0; see [related_projects.md](related_projects.md)). -The count is consistent with that if road surface is wider than the driven lanes. It does not settle which bit, -or which combination, means road surface. That stays open, as do bit 8's meaning and the other bits. The vertex -formula above is stated in the same file and is confirmed by the heights. - -## Band-3 `grid` resources (`27,482` resources) - -The final 433 MiB of `navmeshes.rpf` holds `27,482` `pgBase` resources (`+6` continuations) paired **1-to-1** with all -`27,482` static navmesh tiles (`24,480` unique sectors, **0 symmetric difference** against Band 2). - -| Offset | Size | Type | Verified meaning (`27,482 / 27,482`) | -|---:|---:|---|---| -| `+0x00` / `+0x08` | 16 | `u64`, `ptr64` | `0`, pointer to 32-byte block map (`bm[1] == stream_count`: `27,476` × 1, `6` × 2) | -| `+0x10` / `+0x14` | 8 | `u32`, `u32` | Power-of-2 group count (`8..2048`), active entry count `N` (`85..14,903`; sum `53,835,068`) | -| `+0x18` / `+0x20` | 16 | `ptr64`, `ptr64` | Hash-table pointer (always `+0x60`, `groups × 272` B), payload pointer (`u32[N]`) | -| `+0x28` / `+0x34` | 16 | `u32[3]`, `u32` | Cubic volume extent (`128³ / 256³ / 512³ / 1024³ / 4096³` m), 512 × 512 sector ID | -| `+0x40` | 12 | `f32[3]` | World origin `(ox, oy, oz)` (`ox, oy` match sector ID on `27,482 / 27,482`; `oz ∈ {-2048..+256}`) | -| `+0x50` | 4 | `u32` | Mirror of entry count (`u32@0x50 == u32@0x14` on `27,482 / 27,482`) | - -Reserved slots `+0x38..+0x3f`, `+0x4c..+0x4f`, and `+0x54..+0x5f` are zero on `27,482 / 27,482`. Each 272-byte group at -`+0x60` is a 16-way SwissTable block (`16` control bytes where `0x80` = empty and `< 0x80` = occupied tag, followed by -`16 × {u64 key, u64 value}`). Across all `27,482 / 27,482` resources, occupied slots equal `N` and their `value` fields -form an exact bijection onto `[0 .. N - 1]`: `value` indexes the `u32[N]` payload. - -**Keys (ASSET-287).** The `u64` keys are sentinel-bit linear octree keys over the cubic volume: `1` is the root and a -child is `(parent << 3) | octant`, so the highest set bit sits at bit `3 × depth`. Measured on `27,482 / 27,482` -resources: the root is present, no key appears in two slots, every key's highest set bit is a multiple of 3, and every non-root key's parent (`key >> -3`) is in the same table. Octant bit 2 is the vertical axis (cells stack on it); which of bits 0/1 is x and where the -cube sits against the sector are **open**. Depths run `0..10` (`53,835,068` keys). The cell size at a resource's deepest -level (`extent >> depth`) is 16 m on `12,694` resources (`12,693` 128 m tiles at depth 3, one 256 m tile), 8 m on `859` -and 4 m on `13,929`. - -**`u32[N]` words.** `51` distinct values over the whole package. Every inner node (a key with at least one child: -`8,617,353`) holds `0x0000ff00`. Leaves (`45,217,715`) hold `0x0000ff00` (`1,791,096`, never at a resource's deepest -level), a word with low byte `0x01` (`26,659,574`; bits `8-11` take `0, 5, 7, 9, B, D, F`; bits `17-18` are a 2-bit -field), or a word with low byte `0x03` (`16,767,045`; bit 8 is a flag, bits `11-14` a 4-bit value `0..15`). What the two -leaf kinds and their fields mean, and the engine subsystem name, are **open**. `navmesh_decode.py --deep` checks the key -and inner-word rules (`keys_octree`, `inner_payload_ff00`) and reports `key_depth`, `inner_nodes` and `leaf_payload` -counts. - -## Remaining unknowns - -1. **RPF9 TOC and sub-RPF headers.** The outer TOC and the 29 internal sub-RPF boundary gaps are encrypted and were not - touched; asset paths and official resource type IDs require the TOC or executable. -2. **`0DRP` `u16@0x4e` boundary tie-breaker.** On the `307` two-stream pages where `data_end <= len(stream0)` and - `ceil(data_end / 4096) * 4096 == len(stream0)`, `93` store `pg` and `214` store `0`; what selects between them is - open. -3. **`0DRP` unnamed structs and fields.** Several `0x7a` struct/member hashes (including `0x4712787b`, `0x57ad0b12`, - `0xdd53676a`, `0xf2dd6348`, `0xde5f1345`, and 3 of the 4 singletons) are not yet matched to engine names. -4. **Per-record bitfields inside `0x00010015` tiles.** `u32@0x10` bit 3's secondary trigger on `289` tiles and bit 6's - name, `u32@0xE8` build-stamp encoding, the polygon flag bits (`+0x18` bits 8 and 13 lie under nine in ten lane - nodes; which of them is road surface is open; see above), the adjacent-edge and special-link flag bitfields, and - the exact C++ class name and `+0x56/+0x58` vertical unit of the paired 96-byte `+0xB8` footprint records remain - open. -5. **Band-3 `grid` subsystem and EOF `PSIN` v79.** The Band-3 subsystem identity, the x/y order of the octree key's - octant bits 0/1, the cube's placement against its sector and the meaning of the `u32[N]` leaf fields are open - (the key encoding and the inner-node word are decoded above), as is why the final `PSIN` (version `79`) - terminates before `LSNS` ends. - -## Vehicle navmesh settings (`CVehiclePoints`, `common.rpf`) - -The settings for navmeshes on vehicles that peds walk around on are outside this archive, in 32 `CVehiclePoints` -XML documents in `common.rpf` (see [gamedata.md](gamedata.md)); the meshes themselves are stored here (below). -One document per vehicle; counts only, no names. - -| Field | Documents | Values | -|---|---:|---| -| `DefinitionName`, `ModelName` | 32 | equal in all 32; 31 distinct (one model has two different documents) | -| `Flags`, `iNumBoardingPoints` | 32 | one value each across all 32; `iNumBoardingPoints` is 0 | -| `Points`, `Props`, `AuthoredMeshName` | 32 | empty in all 32 | -| `fNavOverrideRecastCellSize` | 31 | 4 distinct values: 0, 0.03125, 0.0325, 0.0625 | -| `fNavOverrideRecastCellHeight` | 26 | 2 distinct values, 0 or 0.04 | -| `fNavOverrideAgentRadius` | 30 | 4 distinct values, 0 to 0.15 | -| `fNavOverrideAgentHeight` | 30 | 0 or 1.2 | -| `fNavMaxHeightChange`, `fNavMinZDist` | 30 | constant (0.35 and 0.5) | -| `fMinPatchAreaBeforeCulling` | 31 | 6 distinct values, 0.1 to 4 | -| `ModDefs/Item` | 6 documents, 49 items | `ChassisModName`, `UtilityModName`, `PropsetExteriorModName`, `InteriorModName`, `CargoModName` (always empty), `RoofModName` (on 17) | - -The field names are Recast's (cell size and height, agent radius and height, a minimum patch area), so a vehicle -navmesh is built with Recast-style parameters per model, where 0 reads as "no override". The cell sizes are -fine (at most 0.0625 world units) compared with a world navmesh, as a deck or wagon bed would need. - -Cross-checks against the local archive catalog: 25 of the 31 model names are `.yft` base names (6 are not in -the catalog), and all 25 are also among the 319 models of the vehicle distant-light recipes; 4 are among the 252 -rated vehicles. Of the mod part names, only the 5 `RoofModName` values that are set resolve to a `.yft`; the -49 chassis, 32 utility, 35 exterior-propset and 4 interior names match no archive entry, so they are probably -fragment-part or kit names rather than models. - -### Stored vehicle navmeshes (ASSET-332) - -The vehicle navmeshes are **stored**, not left to a runtime generator: the 161 local-space non-grid meshes in this -archive (`flags = 7`, the non-grid partition above) were built on cell grids, and 9 of them on the one cell size -only these documents set. Measured over all 161 on 1.0.2.1 with `tools/navmesh_cell_fit.py`: - -- **Cell grid.** A mesh's `u16` vertices are dequantised over its `+0x60` extents (step `extent / 65535`, at most - 0.0011 m on these meshes) and an x or y coordinate counts as on a grid of cell size `c` when it is within 1.5 steps - of a multiple of `c`. Every mesh fits one of the three nonzero `fNavOverrideRecastCellSize` values: at - least 90.9% of its x and y coordinates sit on that grid (20,100 vertices in all). The quantisation step alone - cannot put them there: over all 65,536 levels of a mesh's own step, at most 5.1% land on its grid (mean 1.0% at - 0.0625, 1.7% at 0.03125, 0.7% at 0.0325). Taking the coarsest of the three that fits: - - | Cell size | Meshes | Distinct x × y extents | Documents with that value | - |---:|---:|---:|---:| - | 0.0625 | 87 | 42 | 1 | - | 0.03125 | 65 | 20 | 23 | - | 0.0325 | 9 | 1 | 3 | - - No mesh fits both 0.03125 and 0.0325. Of six other values tried (0.1, 0.125, 0.15, 0.2, 0.25, 0.5), only 0.125 - fits any mesh: 2 at the 90.9% cut (4 at 90%), all among the 87 at 0.0625, whose coordinates a coarser grid can - also hold. Every mesh's x and y extents are a whole number of its cells. -- **The static tiles are on a grid too.** Every 200th static 128 m tile (137 tiles) fits 0.0625 and 0.03125 (chance - baselines 9.4% and 18.8% at their step of 128/65535 m), and none fits 0.0325. So the world navmesh is built on a - 0.0625 grid as well, and a fit at 0.0625 or 0.03125 alone does not show that a mesh used a vehicle override. -- **The 0.0325 meshes.** 0.0325 is the one value that is not a power of two and that no static tile fits, so it - is the test that ties meshes to these documents. All 9 - meshes on it share one footprint, 1.755 × 5.1675 m, which is exactly 54 × 159 cells of 0.0325. They are flat - (z extent 0) and have 47 vertices (6) or 55 (3). The 3 documents with that value name 3 different models. -- **No name hash.** None of the 161 meshes (nor the whole-world coarse mesh) contains the `joaat` of any of - the 31 model names, as written, lower-cased, or with `.yft` appended, at any byte offset. So a mesh is not tied - to its model by a stored name hash. Where the link is is not measured; the encrypted table of contents is one - candidate (see [rpf.md](rpf.md)). - -Not measured (hypothesis): which mesh belongs to which model, and so which vehicles they are. 161 meshes for 31 -models means either several meshes per model (states or variants) or meshes for vehicles without a -`CVehiclePoints` document. The 87 meshes at 0.0625 against 1 document with that value, and the static tiles on the -same grid, would fit 0.0625 being the default cell size when the override is 0 or absent (5 documents: 4 with 0, -1 without the field). -**Stored vs runtime-generated and vehicle classes (ASSET-332).** Cross-checking the 31 distinct `CVehiclePoints` -models (and 55 `ModDefs/Item` part names) against `navmeshes.rpf`, `common.rpf` metadata, and other package -archives resolves the earlier hypothesis: **vehicle navmeshes are pre-baked and stored in `navmeshes.rpf` Band 2**, -so the port does not need a runtime Recast navmesh generator for these vehicles. The `CVehiclePoints` Recast fields -are authoring/build-time inputs to that partition: - -- **Stored in `navmeshes.rpf` Band 2 (`flags = 7` dynamic partition):** the non-grid `PSIN` container at - `0x1749fe000` (`37,120` B, version `256`, `493` `LSNS` records) heading the `161` local-space dynamic navmeshes - (`0x174a02010..0x174b91010`) contains the lowercase `joaat` hash of **25 of the 31** `CVehiclePoints` model names - (100% of the 25 present in the `.yft` catalog) and **20 of the 55** `ModDefs/Item` part names. The remaining 6 - models appear in neither the `.yft` catalog, `CVehiclePerformanceMaps`, `CTrainConfigs`, nor `PSIN 0x1749fe000`. -- **Absent from other archives:** scanning `packs.rpf`, `data.rpf`, `common.rpf`, and `story000.rpf` finds **0** - `0x00010015` navmesh streams outside `navmeshes.rpf`. -- **Dynamic partition dimensions (`161` `flags = 7` meshes):** extents `dx` `1.31..63.0` m, `dy` `2.94..69.38` m, - `dz` `0.0..13.2` m (`max(dx, dy)`: `81` `<= 10` m, `67` `10..25` m, `11` `25..60` m, `2` `> 60` m); `4..1,058` - vertices, `1..631` polygons, `2..1,694` special links, and `0` `+0xB8` volume records on all `161`. -- **Vehicle class breakdown of the 31 `CVehiclePoints` models** (via `CVehiclePerformanceMaps` and `CTrainConfigs` - in `common.rpf`): - -| Class (`common.rpf` metadata) | `CVehiclePoints` models | Matched in `PSIN 0x1749fe000` | Broader `common.rpf` set in `PSIN 0x1749fe000` | -|---|---:|---:|---:| -| Watercraft (`CVehiclePerformanceMaps` Doc 1, `buoyancyOffsetZ != 0`) | 20 | 20 / 20 | 31 / 34 | -| Ground/land (`CVehiclePerformanceMaps` Doc 0, `takeOffSpeed == 0`) | 4 | 4 / 4 | 12 / 251 | -| Air (`CVehiclePerformanceMaps` Doc 0, `takeOffSpeed > 0`) | 0 | 0 | — | -| Train (`CTrainConfigs`) | 1 | 1 / 1 | — | -| Absent from `CVehiclePerformanceMaps`, `CTrainConfigs`, and `.yft` catalog | 6 | 0 / 6 | — | -| **Total** | **31** | **25 / 31** | | - -## Tools - -- `tools/navmesh_cell_fit.py` (stdlib-only) measures the cell grid of the local-space meshes and, with `--common`, - counts the `CVehiclePoints` cell sizes and searches the meshes for the models' name hashes; `--static-every N` - adds a static-tile control. It prints aggregates only (ASSET-332). -- `tools/navmesh_index.py` (stdlib-only) performs the quick `0DRP` header inventory (`offset`, sizes, version, `+0x20`, - raw `+0x60`/`+0x68`). For a carve directory, `--pattern` selects paths recursively. Each matching pathname - counts once, including when the pattern itself contains `**`. -- `tools/navmesh_decode.py` (stdlib-only) decodes all four resource classes (`0DRP`, `0x00010015`, `grid`, `PSIN`), - joins continuations (including tiny `< 64`-byte continuations), validates structural invariants, and writes aggregate - JSON and optional numeric CSV metadata. It never writes payload bytes and never touches the TOC. -- `tools/navmesh_links.py` (stdlib-only) decodes and verifies the 12-byte `+0x88` adjacent-polygon edges, the polygon - `+0x20` special-link prefix-sum chain, and the 32-byte `+0xA8` special links and `+0xB0` index table. - Pass `--reciprocity` to include a `reciprocity` object. `tiles_counted` covers tiles with verified pool bounds - and contiguous polygon spans. Within each tile, `excess_directed` sums the positive differences between the - counts of A to B and B to A for each ordered polygon pair. Self edges contribute zero excess. The report counts - valid same-tile records, all-ones open targets and invalid targets separately. This measures polygon references - without testing geometric edge alignment. - Pass `--endpoint-agreement` to compare two ways to associate slot *j* of the adjacency span with its - polygon boundary. Under `outgoing` it runs from vertex *j* to the next vertex. Under `incoming` it runs - from the previous vertex to *j*. Both wrap within the polygon and compare all three stored u16 coordinates - at `+0x70` through the `+0x80` indices. The unit is a directed slot. With one occurrence on each polygon, - matching endpoints count as `reversed`, `same_direction`, or `degenerate` (identical endpoints). - If a return exists and either polygon repeats the same unordered endpoints for this neighbor, all affected - slots count as `repeated`. A slot with no return to its source at those exact coordinates counts as - `no_exact_return`. Open, invalid and self targets have separate totals. - - Across all 27,644 Xbox 1.0.2.1 tiles, each convention accounts for 458,728,869 directed same-tile slots. - The endpoint agreement supports slot *j* describing the outgoing boundary edge. A unique return can run - in either direction. Another 34,295,319 slots were open. None had invalid or self targets. - - | Boundary tested | Reversed | Same direction | Degenerate | Repeated | No exact return | - |---|---:|---:|---:|---:|---:| - | Outgoing | 449,013,586 | 9,676,624 | 42 | 94 | 38,523 | - | Incoming | 702 | 102,408 | 2 | 3 | 458,625,754 | - - Pass `--relative-winding` to subdivide uniquely matched outgoing slots by the winding of the two - polygon rings. The first two words of each vertex at `+0x70` are its tile-space X and Y coordinates - (see [the lane-graph height check](#polygon-flags-under-the-lane-graph)). Translation and positive - per-axis scaling by the tile extents at `+0x60` preserve the sign of the shoelace area, so the test uses - exact integer arithmetic. Dynamic meshes use their local XY plane. Endpoint matching still uses XYZ. - Either ring makes the pair ambiguous if it has fewer than three projected vertices, zero signed area, - a repeated point, or a boundary that crosses, touches itself or doubles back. Nonpositive or nonfinite - horizontal extents also make the pair ambiguous. - - | Unique outgoing match (directed slots) | Same winding | Opposite winding | Ambiguous | - |---|---:|---:|---:| - | Same direction | 61,128 | 592 | 9,614,904 | - | Reversed | 448,891,156 | 11,896 | 110,534 | - - Across the whole archive, only 592 same-direction slots have demonstrably opposite XY winding. Of the - 61,720 same-direction slots with classifiable rings, 61,128 have the same winding. The remaining - 9,614,904 slots admit no conclusion from this projection. Reversed slots overwhelmingly join rings - of the same winding. - - Pass `--coplanar-winding` to examine the 9,614,904 XY-ambiguous same-direction directed slots. - The three unsigned words per vertex at `+0x70` give tile-space XYZ. Positive per-axis scaling and - translation preserve coplanarity and the relative orientation of rings in a common plane. A zero - extent collapses that axis. The test requires finite, nonnegative extents. It finds a plane from - three noncollinear ring points and verifies all remaining points against it with integer arithmetic. - Dropping an axis with a nonzero normal component maps that plane one-to-one onto a coordinate plane, - where the existing simple-ring and signed-area tests apply. Two parallel planes containing the same - edge coincide, so both rings use the same projection. For different planes the relative sign can - depend on the viewing direction. - - A private census over all 27,644 tiles classified each ring separately. For planar rings with - distinct vertices, the segment checks stop at the first boundary defect in vertex order. When the - two rings have different conditions, the first listed below takes precedence. Each reciprocal - pair contributes two directed slots. - - | First applicable 3D condition | Directed slots | - |---|---:| - | Fewer than three vertices | 6,375,984 | - | Repeated XYZ vertex in a ring | 84 | - | All vertices collinear | 1,100,732 | - | Adjacent segments double back in a planar ring | 89,984 | - | Nonadjacent segments intersect or touch in a planar ring | 738,318 | - | Nonplanar ring | 596,656 | - | Both rings simple and planar | 713,146 | - - Among the 713,146 slots with two simple planar rings, 713,102 join different planes. The coplanar - group contains 20 slots of equal winding, 20 of opposite winding and 4 with coincident boundaries. - The coincidence test ignores extra vertices along straight sides. The remaining 8,901,758 slots - have at least one undefined ring. These counts describe polygon geometry only. - -- `tools/navmesh_nodes.py` (stdlib-only) counts the polygon flag bits under the lane-graph nodes - ([above](#polygon-flags-under-the-lane-graph)). It reads `navmeshes.rpf` and `levels.rpf` and writes counts only. - An `--out` this run cannot write (a folder that cannot be created or written, a read-only existing summary, or - one of the two archives) is one `ERROR` line and exit 2 before either archive is read. - -```powershell -python -I tools/navmesh_decode.py \navmeshes.rpf --out /navmesh-decode.json --csv /navmesh-decode.csv -python -I tools/navmesh_decode.py \navmeshes.rpf --deep --out /navmesh-decode-deep.json -python -I tools/navmesh_decode.py --out /carved-decode.json -python -I tools/navmesh_links.py \navmeshes.rpf --out /navmesh-links.json -python -I -W error::ResourceWarning tests/test_navmesh_decode.py -v -python -I tests/test_navmesh_links.py -v -python -I tools/navmesh_nodes.py \navmeshes.rpf \levels.rpf --jobs 8 --out /navmesh-nodes.json -python -I -W error::ResourceWarning tests/test_navmesh_decode.py -v -python -I tests/test_navmesh_nodes.py -python -I tests/test_navmesh_index.py -``` - -For both tools, `--start` must be 0 or more and `--limit` at least 1; anything else is refused with exit code 2 before the scan. - -Validation on the full real archive (`navmeshes.rpf`, `6,707,512,496` bytes) with `--deep`: `90,295` carver streams + -`10` tiny continuations; `9,603` `0DRP` (`15,629,979` cover nodes), `27,644` `0x00010015` navmesh tiles (`138,041,746` -vertices, `124,768,148` polygons, `2,337,904` quadtree nodes), `27,482` `grid` resources (`53,835,068` entries, `0` -sector mismatches, `keys_octree` and `inner_payload_ff00` pass on all), `22` `PSIN` (`21` complete), **0 check -failures**, in 236 s. Both test suites build synthetic archives in memory/tempdir and need no game files. - -## No-sharing rule - -The package is read-only. Do not commit, upload or share the archive, any carved page, a key, an extracted name, -or a report that quotes payload bytes. Only aggregate counts, offsets, verified layouts and four-byte magics belong in -this repository. - -## Inspect one tile locally - -Run `python -I tools/navmesh_tile_obj.py navmeshes.rpf --tile 0 --out /tile.obj` -with a zero-based tile ordinal. The reader walks complete navmesh resources in archive order and stops at the -selection. Dynamic tiles count toward the ordinal and lack the static world-space placement required for export. - -Each `polygon_N` group corresponds to record N in the selected tile. A single slot becomes a point, two slots -become a line, and three or more become a polyline closed back to the first slot. Empty records keep their group. -Repeated or collinear slots remain in order, including zero-length edges. OBJ vertex numbers are local to this -export. The boundary drawing makes no claim about surface triangulation, connections or navigability. -Keep generated OBJ files in your private work folder. diff --git a/docs/page_directory.md b/docs/page_directory.md deleted file mode 100644 index d28c78d8e..000000000 --- a/docs/page_directory.md +++ /dev/null @@ -1,517 +0,0 @@ -# RPF9 `0DRP` page directories - -**Status: measured layout and a stdlib indexer.** This note decodes the RPF9 directory page that carries `0DRP` -at +0x10, version 122. It is present and measured in `data.rpf`, `levels.rpf`, `navmeshes.rpf` and `anim.rpf`; -the sampled `*_bvh4.rpf` windows contain no such page. It does not decrypt the table of contents, search for keys -or name a game asset. The numbers come from a read-only scan of one Xbox Series 1.0.2.1 package. No archive, -payload, carved stream or name list is in this document or the repository. - -## Bottom line - -| Question | Measured answer | -|---|---| -| Where is the header? | `0DRP` at +0x10, version 122 at +0x14, fixed header length **0x60**. | -| Is there a 64-bit key at +0x60? | **No.** The first resource payload starts at +0x60 on 29,297 of 29,298 measured pages, and on 48,193 of the 48,194 pages of the three archives read whole. The bytes called a key are payload. | -| What does +0x38 point to? | A table of **16-byte `{u32 hash, u32 size, u64 self-pointer}` records**, one per resource segment. The count is `u16@0x4c`. | -| What does a record map? | A virtual offset and exact byte size inside the logical resource. The offset is `pointer - 0x50000000`, not an archive offset. | -| Do the records cover the page? | Yes on 15,767 of 15,768 `data.rpf` pages and on every navmesh and animation page (all 9,603 and all 22,823, see *Whole-archive pass*): sorted by target they tile from +0x60 with **zero overlaps**. The 14.8 MB, 89-count page starts with the +0x40 table at +0x60; its `q38` records still tile with zero overlaps. | -| Can a resource span zlib streams? | **Yes.** When a table or target crosses the inflated stream end, the next zlib stream in archive order continues the same resource. All 29,298 core pages resolved with at most **one** continuation stream; the 107 sampled `levels.rpf` pages did the same, and so did all 48,194 pages of `data.rpf`, `navmeshes.rpf` and `anim.rpf` read whole. | -| Are resource boundaries available without the TOC? | **Yes for offsets, sizes and stream membership; no for names or asset identity.** The TOC is still required for paths and the hash-to-name mapping. | - -## Method and coverage - -The walk is the fixed `tools/rpf9_carve.py` zlib walk from PR #90: find a zlib header, inflate to `eof`, advance by -the bytes actually consumed, and never read the encrypted TOC. A page is counted when the inflated stream has -`30 44 52 50` at +0x10. - -| Archive | Scope | Streams | `0DRP` pages | Version | -|---|---:|---:|---:|---:| -| `data.rpf` | full, 481,544,304 bytes | 28,509 | 15,768 | 122 | -| `levels.rpf` | first 64 MiB | 142 | 107 | 122 | -| `navmeshes.rpf` | first 64 MiB | 1,378 | 1,132 | 122 | -| `anim.rpf` | first 256 MiB | 24,232 | 12,398 | 122 | -| `navmeshes.rpf` | 64 MiB at +1 GiB | 956 | 0 | - | -| `core_bvh4.rpf` | first 64 MiB | 5,816 | 0 | - | -| `core_bvh4.rpf` | 64 MiB at +4 GiB | 14,823 | 0 | - | -| `core_bvh4.rpf` | 32 MiB near EOF | 654 | 0 | - | - -The +1 GiB navmesh slice is a control: 527 of its 956 streams are typed `0x00010015` data pages, not directory -pages. It confirms that the directory pages cluster in the first part of that archive, as `docs/navmesh.md` (PR -#97) already reported. The `levels.rpf` row is the cross-archive check: the same header, version, table counts and -continuations are present there. - -The BVH samples are a negative control. `core_bvh4.rpf` is RPF9, but none of the three sampled windows contains a -`0DRP` stream. This work therefore does **not** establish that the `*_bvh4.rpf` packs use the page-directory -format; their streams are BVH payloads and descriptors (see `docs/bvh.md`, PR #109), not directory pages. The -"generic" claim in this note covers `data.rpf`, `levels.rpf`, `navmeshes.rpf` and `anim.rpf`. - -## Whole-archive pass - -The `navmeshes.rpf` and `anim.rpf` rows above stop at 64 MiB and 256 MiB. `tools/page_index.py pages.json` -without `--limit`, on the same 1.0.2.1 package, reads both archives to the end (counts only; every row is taken from -the report's `summary` or counted over its `pages`): - -| | `data.rpf` | `navmeshes.rpf` | `anim.rpf` | -|---|---:|---:|---:| -| zlib streams | 28,509 | 90,295 | 130,470 | -| `0DRP` pages, all version 122, all complete | 15,768 | 9,603 | 22,823 | -| `q38` records | 60,880 | 54,898 | 527,439 | -| a `q38` record targets +0x60 | 15,767 | 9,603 | 22,823 | -| pages with overlapping `q38` records | 0 | 0 | 0 | -| gap runs / gap bytes between sorted records | 27,377 / 8,411,848 | 11,461 / 5,058,136 | 136,013 / 10,259,744 | -| pages with one continuation stream (none has more) | 158 | 2,170 | 11,760 | -| `q38` table wholly in the continuation (none is split) | 2 | 270 | 10,218 | -| span (target + size): minimum / median / maximum | 296 / 21,760 / 14,848,448 | 360 / 186,208 / 2,985,724 | 2,732 / 189,072 / 5,634,144 | -| `+0x20` | 1-3, 89 | 1-6 | 1-5, 13-41 | -| `n28` / `n30` / `n38` / `u16@0x4e` | 2-182 / 0-38 / 2-186 / 0-1,077 | 2-12 / 0-4 / 2-6 / 0-602 | 25-103 / 11-57 / 7-79 / 0-1,382 | -| `q28` records declared (`sum n28`) | 60,901 | 108,890 | 1,015,222 | -| `q28` records read | 60,897 | 106,202 | 952,850 | -| `q28` records with a null pointer | 0 | 0 | 3,672 (on 3,511 pages) | -| pages whose `q28` table ends past the streams read | 1 | 225 | 1,355 | - -The stream and page totals agree with the other whole-archive readers: 90,295 streams and 9,603 directory pages in -`docs/navmesh.md`, 130,470 streams in `docs/animation.md`. What the samples said about the layout holds on all -48,194 pages: version 122, the first payload at +0x60 (one `data.rpf` exception), `q38` tables 16-byte aligned, -`q28` tables 8-byte aligned, no overlap between `q38` records, at most one continuation stream, and a `q28` -`hash_a` that matches a `q38` hash on every page where both tables were read (15,767, 9,378 and 21,468 pages). - -What the samples did not show: - -- **Header ranges are wider.** `+0x20` reaches 6 in `navmeshes.rpf` (1: 1 page, 2: 779, 3: 7,650, 4: 932, 5: 22, - 6: 219) and 41 in `anim.rpf` (1: 1,883, 2: 7,571, 3: 9,241, 4: 2,022, 5: 70, 13-41: 2,036); `n30` reaches 57 and - `u16@0x4e` 1,382, both in `anim.rpf`. -- **A `q28` pointer can be null.** 3,672 `anim.rpf` records on 3,511 pages have a zero pointer with `hash_a`, - `count_or_size` and the flags set; 116,277 ordinary records follow them in the same tables. The tool used to stop - a table at the first one. It now keeps the record with `target` null and reads on; a pointer with any other - non-`0x50000000` value still ends the table with `q28_error`. `data.rpf` and `navmeshes.rpf` have none. -- **A `q28` table can lie past the resource's `q38` boundary.** The tool reads only the continuation streams the - `q38` table and its records need. On 1,355 `anim.rpf`, 225 `navmeshes.rpf` and 1 `data.rpf` pages the `q28` - table ends beyond those streams. Such a page reports no `q28` records and names the reason in `q28_error` - (`q28_tables_unread` in the summary) instead of looking like a page without the table. Whether the next stream - holds the table was not followed up. -- **The navmesh type hashes are not on every page.** `0xde5f1345` is in 8,412 of the 9,603 pages (every page of the - first 64 MiB has it); the most common hash, `0x0bcb00e4`, is in 9,585 records. - -The per-archive tables further down (common sizes, common hashes, payload classes) are still the 64 MiB and 256 MiB -slices where they say navmesh or animation; the `data.rpf` columns were complete from the start. - -### `levels.rpf` in full - -`levels.rpf` was counted whole with a temp-only streaming runner that calls the same `scan_rpf`, `parse_page` and -`resource_of` functions and accumulates the summary one page at a time (the stock tool keeps every page; this -archive reached 17.4 GB RSS and had to be stopped). The runner reproduces the stock `data.rpf` row exactly -(28,509 / 15,768 / 60,880 / 158), so the counts are the same fields: - -| | `levels.rpf` | -|---|---:| -| zlib streams | 1,116,073 | -| `0DRP` pages, all version 122, all complete | 188,449 | -| `q38` records | 465,611 | -| pages with one continuation stream (none has more) | 3,281 | -| `+0x20` | 1-44 | -| first `q38` payload at +0x60 | **52,776 of 188,449** | - -The page total agrees with the existing levels census (188,449). The +0x60 rule is the one place where this -archive differs from the other three: only 52,776 of its pages put the first `q38` payload at +0x60. The rest are -counted and parsed, but this check does not establish the +0x60 key claim for them; their first target or table -sits elsewhere. This was a count run (17.7 min), so it does not fill the payload-class, span or q28-declared -tables below; those keep their labelled sample scopes. - -## Fixed header (0x60 bytes) - -The core sample is 15,768 `data.rpf` pages plus 1,132 navmesh and 12,398 animation pages = **29,298 pages**. -The `levels.rpf` and BVH windows are cross-checks and are not included in that total. - -Offsets are from the start of the inflated stream. The "Observed" column is the measured range over the core -sample; the meaning column separates decoded fields from unresolved ones. - -| Offset | Size | Observed | Meaning | -|---:|---:|---|---| -| +0x00 | 8 | zero in all pages | page prefix | -| +0x08 | 8 | `0x0000000050xxxxxx`, inside the resource or exactly at its end | self-pointer/end pointer; role unresolved (4 animation pages point at the end) | -| +0x10 | 4 | `30 44 52 50` | `0DRP` | -| +0x14 | 4 | 122 in all 29,298 | version | -| +0x18 | 8 | zero in all pages | unused | -| +0x20 | 4 | 1-89 in `data.rpf`, 2-3 in navmesh, 1-38 in anim (whole archives: 1-6, 1-41; 1-44 in `levels.rpf`) | presumed page count; **unit unresolved** | -| +0x24 | 4 | zero in all pages | high half of the +0x20 qword | -| +0x28 | 8 | `0x5000xxxx`, 8-byte aligned | pointer to the `q28` table | -| +0x30 | 8 | zero or `0x5000xxxx` | pointer to the `q30` table | -| +0x38 | 8 | `0x5000xxxx`, 16-byte aligned in all pages | pointer to the `q38` resource table | -| +0x40 | 8 | `0x5000xxxx` | pointer to the `q40` table; layout unresolved | -| +0x48 | 2 | 0-182 | `n28`: number of +0x28 records | -| +0x4a | 2 | 0-38 (0-57 over whole `anim.rpf`) | `n30`: number of +0x30 records | -| +0x4c | 2 | 2-186 | `n38`: number of +0x38 records | -| +0x4e | 2 | 0-1,382, varying | **unresolved**; not a dense count | -| +0x50 | 16 | zero in all pages | unused | -| +0x60 | ... | first payload, or the `q40` table on one page | not header | - -The header read for the worked example below (`data.rpf`, archive offset `0x11f4010`, inflated 131,072 bytes): - -```text -00 00 00 00 00 00 00 00 10 87 01 50 00 00 00 00 -30 44 52 50 7a 00 00 00 00 00 00 00 00 00 00 00 -02 00 00 00 00 00 00 00 40 87 01 50 00 00 00 00 -00 00 00 00 00 00 00 00 d0 86 01 50 00 00 00 00 -60 88 01 50 00 00 00 00 04 00 00 00 04 00 00 00 -00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 -``` - -That is: `0DRP`, version 122, page count 2, `q28=0x18740`, `q30=0`, `q38=0x186d0`, `q40=0x18860`, counts -`4,0,4,0`, then 16 zero bytes. The first payload starts at +0x60. - -### The +0x60 "key" is payload - -`docs/navmesh.md` (PR #97) reports a 64-bit key at +0x60 and a `u32` at +0x68. The bytes are real but they are not -header fields on these pages. The `q38` table gives the counter-example: - -- On the navmesh page at archive offset `0x11ca630`, the first `q38` entry is - `{hash 0xd7e9c53b, size 0x140, target 0x60}`. It covers +0x60 through +0x19f. The reported key `49` is the - first byte of that payload, the ASCII character `1`; the reported `u68=0` is the next four payload bytes. -- On `data.rpf` page `0x11f4010`, the first `q38` entry targets +0x60 with size `0x11000`. -- The same holds for 15,767 of 15,768 `data.rpf` pages, all 107 sampled `levels.rpf` pages, all 1,132 sampled - navmesh pages and all 12,398 sampled animation pages. - -The one exception is the 14.8 MB, 89-count directory page at `data.rpf` offset `0x1c396010`: its `q40` table starts -at +0x60, and the first `q38` payload is elsewhere. Even there, +0x60 is a table, not a key. - -So the navmesh report's 9,603-page key census (9,409 nonzero) is a census of payload prefixes, not a header field. They cannot be -used as a name or asset id. Names still require the TOC. - -## Pointer arithmetic - -Every measured `q38` pointer, and every `q28` pointer that is not null (3,672 `anim.rpf` records have a zero -pointer, see *Whole-archive pass*), is a zero-extended 32-bit value in a 64-bit field: - -```text -d0 86 01 50 00 00 00 00 -> 0x000000005000186d0 -> 0x186d0 -``` - -The rule is: - -```text -target = pointer - 0x50000000 if the high 32 bits are zero and 0x50000000 <= pointer < 0x60000000 -``` - -No other base was observed in a directory table. The subtraction is **not** an archive offset. It is a virtual -offset into the logical resource: - -- `target < inflated_size`: the byte is in this inflated stream. -- `target >= inflated_size`: the byte is in the next stream in archive order, at - `target - inflated_size` into that stream's inflated bytes. -- A `q38` table can lie wholly in a continuation stream (2 `data.rpf` pages, 32 navmesh pages, 6,978 animation - pages). No partially split table was observed. The tool concatenates the continuation before reading it. - -`q38` tables are 16-byte aligned in all 29,298 pages; `q28` tables are 8-byte aligned. `q38` targets are 16- or -8-byte aligned; `q38` sizes are arbitrary. - -## The `q38` resource table (solid) - -`n = u16@0x4c`. The table is at `q38 = u64@0x38 - 0x50000000`, and each record is 16 bytes: - -| Offset | Size | Meaning | -|---:|---:|---| -| +0x00 | 4 | 32-bit type hash | -| +0x04 | 4 | exact payload byte size | -| +0x08 | 8 | self-pointer: `0x50000000 + virtual target` | - -Worked table from `data.rpf` page `0x11f4010`, table at `0x186d0`: - -```text -89 88 47 a8 70 76 00 00 60 10 01 50 00 00 00 00 -89 10 33 99 10 00 00 00 30 87 01 50 00 00 00 00 -01 01 00 00 00 10 01 00 60 00 00 50 00 00 00 00 -10 00 00 00 8b fa 00 00 00 00 02 50 00 00 00 00 -``` - -| Hash | Size | Pointer | Target | -|---|---:|---|---:| -| `0xa8478889` | `0x7670` | `0x50011060` | `0x11060` | -| `0x99331089` | `0x10` | `0x50018730` | `0x18730` | -| `0x00000101` | `0x11000` | `0x50000060` | `0x60` | -| `0x00000010` | `0xfa8b` | `0x50020000` | `0x20000` | - -The records are stored in hash-table order, not target order. Sorted by target, the segments are disjoint. On this -page: - -| Virtual range | Contents | -|---|---| -| `0x000060`-`0x01105f` | `q38` hash `0x00000101`, size `0x11000` | -| `0x011060`-`0x0186cf` | `q38` hash `0xa8478889`, size `0x7670` | -| `0x0186d0`-`0x01870f` | `q38` table, 4 x 16 bytes | -| `0x018710`-`0x01872f` | 32-byte gap, not decoded | -| `0x018730`-`0x01873f` | `q38` hash `0x99331089`, size `0x10` | -| `0x018740`-`0x0187bf` | `q28` table, 4 x 32 bytes | -| `0x0187c0`-`0x01885f` | `q28` target records | -| `0x018860`-`...` | `q40` table | -| `0x020000`-`0x02fa8a` | `q38` hash `0x00000010`, size `0xfa8b` | - -The last segment starts exactly at the inflated stream end (`0x20000`) and is continued by the next zlib stream, -at archive offset `0x11f9620`, inflated size **64,144** (`0xfa90`). The declared `q38` size is **64,139** -(`0xfa8b`); the continuation has five trailing bytes outside the declared payload. This is the direct -page-to-payload correlation: target `0x20000`, size `0xfa8b`, and the next stream's bytes line up exactly. The -continuation starts with printable ASCII, so that segment is text, not a model, texture or nested page. - -### Coverage and tiling - -| Archive | Pages | `q38` records | First target +0x60 | Overlap pages | Gap runs | Gap bytes | -|---|---:|---:|---:|---:|---:|---:| -| `data.rpf` | 15,768 | 60,880 | 15,767 | 0 | 27,377 | 8,411,848 | -| `navmeshes.rpf` (64 MiB) | 1,132 | 6,645 | 1,132 | 0 | 1,318 | 270,520 | -| `anim.rpf` (256 MiB) | 12,398 | 269,320 | 12,398 | 0 | 64,356 | 5,088,441 | - -"Gap runs" count individual gaps between sorted records, not pages. The gaps are the metadata tables and padding. -Classifying the gap bytes: most fall inside the `q38` table or the `q28`/`q30`/`q40` ranges; the rest are -`0x00`/`0x80` fill and short 16-40 byte alignment runs. No record overlaps another record in any sampled page. -On 2 `data.rpf`, 32 navmesh and 6,978 animation pages the `q38` table itself is in the continuation stream; each -was parsed after concatenation. - -Largest/smallest declared span (target + size): - -| Archive | Minimum | Median | Maximum | -|---|---:|---:|---:| -| `data.rpf` | 296 | 21,768 | 14,848,448 | -| `navmeshes.rpf` | 5,186 | 144,960 | 2,422,688 | -| `anim.rpf` | 2,732 | 206,064 | 2,319,504 | - -### Most common `q38` sizes - -| `data.rpf` | Count | `navmeshes.rpf` | Count | `anim.rpf` | Count | -|---:|---:|---:|---:|---:|---:| -| `0x10` | 15,320 | `0x130` | 1,148 | `0x10` | 11,750 | -| `0x2200` | 5,616 | `0x1000` | 1,136 | `0x2e00` | 9,522 | -| `0x220` | 4,658 | `0x20` | 125 | `0x120` | 5,436 | -| `0x4400` | 2,172 | `0x40` | 111 | `0x140` | 4,444 | -| `0x28` | 1,270 | `0x80` | 82 | `0x240` | 4,251 | -| `0x440` | 858 | `0x60` | 76 | `0x40` | 3,567 | -| `0x880` | 768 | `0xc0` | 66 | `0x80` | 3,459 | -| `0x20` | 552 | `0x100` | 65 | `0xc0` | 3,458 | - -### Most common `q38` hashes - -These are 32-bit hashes; whether they are type ids is open. Repeated values are stable across pages. - -| `data.rpf` hash | Count | `navmeshes.rpf` hash | Count | `anim.rpf` hash | Count | -|---:|---:|---:|---:|---:|---:| -| `0x00000010` | 14,520 | `0xde5f1345` | 1,132 | `0x00000007` | 12,398 | -| `0xa8478889` | 14,482 | `0x2283b2cb` | 1,132 | `0xa90b7f7e` | 12,398 | -| `0x99331089` | 14,482 | `0x00000013` | 1,132 | `0x0000004a` | 12,398 | -| `0x00000101` | 14,482 | `0xbb5a70d8` | 1,132 | `0x64e8ac67` | 12,398 | -| `0xc90d1c34` | 1,247 | `0x0bcb00e4` | 1,132 | `0xad5dfe3c` | 12,366 | -| `0xfc3dbc38` | 1,247 | `0x00000100` | 985 | `0x64d97283` | 11,686 | -| `0xd7e9c53b` | 38 | | | `0x00000100` | 11,686 | -| `0x8731ec16` | 38 | | | `0x29f72aea` | 11,670 | - -No name or type string is present in the page; these hashes remain opaque until the TOC or the executable supplies a mapping. - -### One page lacks the recurring `0x00000007` tag - -The Xbox Series 1.0.2.1 export identifies `story000.rpf` as its source and contains 16,977 complete -directory pages. A bounded source check used 17 evenly spaced rows (including the first and last) and -the six-record exception described below. At the recorded compressed spans, the inflated length, page -signature and both record lists (`q38` and `q28`) matched for 18/18 rows in `story000.rpf` and 0/18 in -`data.rpf`. The counts below apply only to this export. Each selected tag occurred once per page that contained it. - -| Selected `q38` tag | Pages containing it | -|---|---:| -| `0xa90b7f7e`, `0x0000004a`, `0x64e8ac67` | 16,977 each | -| `0x00000007` | 16,976 | -| `0x00000100` | 16,519 | -| `0x00000101` | 593 | -| `0x00000010` | 19 | -| `0xde5f1345` | 0 | - -The one complete page without tag 7 had six `q38` records. The six nearest pages by record count had 10–12 -records and carried tag 7 in positions 2–7 (counting from one). Four shared five of the exceptional page's tags -and two shared all six. Across the export, all 81 other pages containing all six tags also contained tag 7. -None preserved the relative order of all six. Tag 7 is therefore optional in this sample. There is no second -six-record table for a comparison that could distinguish omission from substitution. - -Of the 15,775 pages with exported `q28` records, all had at least one `hash_a` equal to a same-page `q38` -tag. None had a matching `hash_b`. The export also reported 131 pages with `q28_error`. On the exceptional -page, five of the 26 readable `q28` records each matched a different local tag through `hash_a`. Neither -field equalled 7. On the six nearest pages, `hash_a` also never equalled 7 even though `q38` contained it. -These comparisons establish equality of field values. Their role at runtime and the meaning of the tags remain open. - -## The `q28` table (layout measured, semantics partial) - -`n = u16@0x48`; table at `q28 = u64@0x28 - 0x50000000`; each record is 32 bytes: - -| Offset | Size | Confidence | Meaning | -|---:|---:|---|---| -| +0x00 | 4 | measured | `hash_a`; at least one record on every page matches a `q38` hash | -| +0x04 | 4 | unresolved | `hash_b`; no match to a `q38` hash observed | -| +0x08 | 8 | unresolved | `field_08`; observed `0`, `0x100`, `0x200`, `0x300`, `0x30c`, `0x400`, `0x424`, ...; not a measured byte range | -| +0x10 | 8 | measured | self-pointer, or zero on 3,672 `anim.rpf` records; 60,862 of 60,897 `data.rpf` targets resolve in the first stream | -| +0x18 | 4 | unresolved | `count_or_size`; small values, not consistently the linked `q38` size | -| +0x1c | 4 | measured | flags; only high 16 bits are set, observed `0x10000`-`0x6b0000` | - -Worked first `q28` record from the same page (`data.rpf` `0x11f4010`, table `0x18740`): - -```text -89 10 33 99 a4 68 55 bf 00 03 00 00 00 00 00 00 -00 88 01 50 00 00 00 00 10 00 00 00 00 00 03 00 -``` - -That is `hash_a=0x99331089` (the `q38` entry of size 0x10), `hash_b=0xbf5568a4`, `field_08=0x300`, -`target=0x18800`, `count_or_size=0x10`, `flags=0x00030000`. - -The table points at hash-table-like records of 16 bytes, `{u32 hash, u32 0, u32 index, u32 0}`, plus small -dictionaries. The exact meaning of `field_08`, `count_or_size` and `hash_b` is not decoded, so the tool exports -them under those names and does not use them for boundaries. - -Counts: 60,897 records in `data.rpf`, 13,090 in the navmesh slice, 511,435 in the animation slice (106,202 and -952,850 over the whole archives). `hash_a` -matched a `q38` hash on 15,767/15,767 `data.rpf` pages, 1,103/1,103 navmesh pages and 11,558/11,558 animation -pages where both tables were present. - -## `q30`, `q40` and `+0x4e` - -- `q30` is present when `u16@0x4a` is nonzero. Its target begins with a 16-byte hash-like header; in 980 of 1,132 - navmesh pages the first eight bytes are `01 2e 3b 5c 3e b2 ee 6e`. The internal layout is not decoded. -- `q40` points at a table whose common prefix is `01 00 00 00 01 01 00 00 20 00 00 00 ...` (1, 0x101, 32, then - hash words). The 89-count page starts `05 00 00 00 01 01 00 00 40 46 4e 00 0f 01 ...`. It is not used for - resource boundaries and its fields are unresolved. -- `u16@0x4e` ranges 0-1,382 (0-1,077 in `data.rpf`) and does not match any table count. It is left raw in the tool JSON as `counts[3]`. - -## What a page maps - -A `0DRP` stream starts a **logical resource**. The fixed header is followed by payload segments described by -`q38`; the first segment normally starts at +0x60. The page does not map to a zlib block (the zlib framing is -outside it), to another page, or to a named RBF0/PSIN/model/texture resource: - -- Every `q38` target's first 0x18 bytes were classed. In `data.rpf`: 46,184 "other" and 14,696 zero-prefix; in - navmesh: 6,194 "other" and 451 zero-prefix; in anim: 80,697 "other", 188,617 zero-prefix and 6 too short. - None started with `PSIN`, `RBF0`, `0DRP`, `RSC7` or `RSC8`. -- Continuation streams were classed as zero-prefix or other payload in every case; none was a `0DRP` page. A - resource therefore extends forward by payload, not by nesting another directory. -- `PSIN` (2,281) and `RBF0` (1,263) are separate top-level stream classes in `data.rpf`, not `q38` payloads. - -### Cross-check: `0x00010015` data pages - -A typed data page has a different prefix: eight zero bytes, a `0x5000xxxx` pointer at +0x08, a small `u32` at -+0x10 (9 in 355, 11 in 121, 3 in 46, 1 in 5 of the sampled pages), and `15 00 01 00` at +0x14. The same -subtraction applies: 99 of 527 sampled typed pages point inside their own inflated stream; 428 point beyond it, -consistent with a continuation stream. The typed page has **no `q38` table**, so it supplies no resource -boundaries by itself. - -This is the cross-check the navmesh report asked for: the `0x50000000` base is shared by directory pages and typed -data pages, but only the directory page carries the offset/size table. The typed prefix is not a `q38` payload -magic; 0 of 60,880 `data.rpf` records and 0 of the 6,645 navmesh and 269,320 animation records in their sampled -windows started with `0x00010015` at +0x14. - -## Distribution of the +0x20 count - -| Value | `data.rpf` | `navmeshes.rpf` (64 MiB) | `anim.rpf` (256 MiB) | -|---:|---:|---:|---:| -| 1 | 1,247 | 0 | 480 | -| 2 | 14,485 | 147 | 5,240 | -| 3 | 35 | 985 | 5,144 | -| 4 | 0 | 0 | 1,407 | -| 5 | 0 | 0 | 45 | -| 18-38 | 0 | 0 | 82 | -| 89 | 1 | 0 | 0 | - -The count does not equal the `q38` record count or the stream count. A `data.rpf` page with count 2 can have four -records; a navmesh page with count 3 has six; an animation page with count 3 can have 22. The unit is **unresolved**. -The earlier label "presumed page count" is kept only as a name for `u32@0x20`. - -### The `+0x20` count does not mark stream boundaries - -`story000.rpf` was measured to decide whether the field can group a resource's streams. In a 256 MiB carve -(33,315 streams, 16,977 `0DRP` directories) a directory is followed by **exactly one** non-directory stream in -16,128 cases, and that is the same for counts 2, 3 and 4 (9,616 / 5,663 / 633), so the field is not a stream count. -Compared against the 64 KiB units the resource group actually occupies (directory plus the continuations needed to -reach the `q38` table and its last record), the declared count matches on **9,010 of 16,977 pages (53.1%)**. Growing -the group until the `q28`/`q30`/`q38`/`q40` tables also fit raises that only to 9,622 (56.7%). Against -the directory stream alone the best unit is 32 KiB, at 7,660 pages (45.1%). Against counts derived from the `q28` -table (`n28`, `sum(flags >> 16)`, `max(flags >> 16)`, `sum(field_08)`) the match is **0%** on all 16,977 pages, and -the `q38` records tile the resource with zero overlaps and 138,583 gaps in the 1 GiB slice, so they are entries, not -pages either. - -The boundary is therefore taken from the tables, not from `+0x20`: a resource is the directory stream plus the -following streams needed to reach the `q38` table and its last record. `tools/page_index.py` reports that group per -page as `resource` (`streams`, `bytes`, `page_units`, `declared_pages`, `declared_matches_units`), and the summary -counts how often the declared count agrees, so the disagreement is recorded rather than used. - -## Readable versus opaque - -**Readable from bytes:** the `0DRP` magic, version 122, header length and pointers, the four `u16` counts, the -`q38` hash/size/target table, the raw `q28` fields, the first payload offset, continuation stream boundaries, and -the payload's coarse class (zero-prefix or other). - -**Opaque:** the hash-to-name mapping (TOC or executable), the meaning of each type hash, `q28` `hash_b`, -`field_08` and `count_or_size`, the `q30` and `q40` layouts, `u16@0x4e`, and the unit of `u32@0x20`. No name, -path or resource type is present in a `0DRP` page. - -## Remaining unknowns - -1. **Names and types.** Join a `q38` hash to the TOC or the executable's resource registry. Do not guess from a - four-byte value. -2. **`+0x20` unit.** Tested and rejected as a boundary on `story000.rpf`: no page-size reading fits (best 56.7% at - 64 KiB, 45.1% at 32 KiB over the directory stream, 0% against the `q28`-derived counts). The measured `data.rpf` - page `0x11f4010` has span 195,211 bytes and count 2 (1.49 x 128 KiB), while a navmesh page with span below 8 KiB - has count 3. A loader or a decoded dictionary is needed before the field itself is named. -3. **`q28` fields.** `hash_b`, `field_08` and `count_or_size` need a loader or a decoded dictionary. The hash - tables it points at look like `{hash, 0, index, 0}` records, but the index semantics are not proven. -4. **`q30`/`q40`.** Both contain hash-like tables and are not needed for boundaries. Decode them only with a - consumer. -5. **Type-hash semantics.** The same hashes recur across pages (`0xde5f1345` in every sampled navmesh page and 8,412 of all 9,603, - `0x00000101` in 14,482 `data.rpf` records). Whether they are class ids, schema hashes or builder tags is - **open**. -6. **Full-corpus runs.** The tool is bounded by `--limit`; run it on a whole archive before quoting a count for - that archive. `data.rpf`, `navmeshes.rpf` and `anim.rpf` are read whole in *Whole-archive pass*; `levels.rpf` - is read whole in *`levels.rpf` in full*, and its map contents are in `docs/world_census.md`. The common-size, - common-hash and payload-class tables are still slices for navmesh and animation. -7. **`q28` tables past the `q38` boundary.** 1,581 pages declare a `q28` table that ends beyond the streams the - `q38` records need. Reading the following stream for it would settle whether a resource can be longer than its - `q38` records say. - -## Tool - -`tools/page_index.py` is stdlib-only and reads the same data area as the carver. It never writes payloads and -never touches the TOC. - -```powershell -python -I tools/page_index.py pages.json --limit 268435456 -python -I tools/page_index.py pages.csv -python -I tools/page_index.py pages.json -python -I tests/test_page_index.py -``` - -`--start` must be 0 or more and `--limit` at least 1; both take decimal or `0x` hex. A value outside that, an output -that does not end in `.json` or `.csv`, or a `--start` past the end of the archive stops the tool with a one-line -error and exit code 2, before anything is scanned or written. An empty archive, or one shorter than its 8-byte -header, gives an index with no pages. - -JSON has a `summary` and one object per page: offset, stored/inflated size, version, `page_count` (`u32@0x20`), -the four counts, table offsets, `q38_records`, raw `q28_records` (`target` is null for a null pointer; `q28_error` -names a table that was cut short or not read), continuation streams, `span`, -`payload_at_0x60`, `complete`, and a `resource` group (its `streams` with offsets and inflated sizes, `bytes`, -`page_units` at 64 KiB, `declared_pages` and `declared_matches_units`). CSV is one row per `q38` record: -`page_offset,stored,inflated,version,page_count,q28_count,q30_count,q38_count,span,complete,record_index,hash,size,target,target_stream`. -`target_stream` is 0 for the directory stream and 1..N for a continuation. - -Validation on the package used here: - -| Run | Streams | Pages | `q38` records | Complete | Continuations | Time | -|---|---:|---:|---:|---:|---:|---:| -| `data.rpf` full | 28,509 | 15,768 | 60,880 | 15,768 | 158 | 21 s | -| `levels.rpf` first 64 MiB | 142 | 107 | 871 | 107 | 14 | 1.1 s | -| `navmeshes.rpf` first 64 MiB | 1,378 | 1,132 | 6,645 | 1,132 | 210 | 1.6 s | -| `anim.rpf` first 256 MiB | 24,232 | 12,398 | 269,320 | 12,398 | 7,865 | 25 s | -| `navmeshes.rpf` full | 90,295 | 9,603 | 54,898 | 9,603 | 2,170 | 2.8 min | -| `anim.rpf` full | 130,470 | 22,823 | 527,439 | 22,823 | 11,760 | 2.5 min | -| `levels.rpf` full (streaming runner) | 1,116,073 | 188,449 | 465,611 | 188,449 | 3,281 | 17.7 min | - -The summary also counts the `q28` side: `q28_declared` (the sum of `n28`), `q28_records` (read), `q28_null_targets` -and `q28_tables_unread`. - -The synthetic test builds its own RPF9 header and pages. It covers an in-page resource, a payload in the next -stream, a `q38` table that itself straddles the stream boundary, the carved-directory mode, the CSV shape, a -`q28` record with a null pointer in the middle of a table, and a `q28` table past the streams read. - -## No-sharing rule - -The package is read-only. Do not commit, upload or share the archive, a carved page, a payload excerpt, a name -list or a report that quotes payload bytes. Header bytes, table records and aggregate counts belong in this -repository; the bytes a table points at do not. diff --git a/docs/ped_catalogues.md b/docs/ped_catalogues.md deleted file mode 100644 index 9264152a2..000000000 --- a/docs/ped_catalogues.md +++ /dev/null @@ -1,172 +0,0 @@ -# Ped Appearance Catalogues (`0x8dcb4cf5`) - -Compiled ped and wardrobe appearance catalogues share one schema rooted at struct `0x8dcb4cf5`, stored in two container framings: - -1. **Resource-packed `0DRP` v122 containers** inside `packs.rpf` (per-archetype ped catalogues). -2. **Standalone `PSIN` containers** (e.g. the player/wardrobe catalogue, whose multi-megabyte body mixes deflate and raw 64 KiB chunks inside the archive and is read once extracted as a `.pso` file). - -Both framings expose a 1-based block table and use the same internal 64-bit pointer encoding: - -```text -block_1based = ptr & 0xfffff -byte_offset = ptr >> 20 -``` - -Parser and CLI: `tools/ped_catalogues.py` (stdlib only, `python -I`). Synthetic test suite: `tests/test_ped_catalogues.py`. - ---- - -## Container framings - -### Resource-packed `0DRP` v122 (`0x7a`) - -Uses the standard `0x60`-byte standalone `0DRP`/`0x7a` header validated by `tools/odrp_7a.py` (see [page_directory.md](page_directory.md)): - -| Offset | Type | Field | Notes | -|---:|---|---|---| -| `+0x00` | `u64` | zero prefix | Always `0` | -| `+0x08` | `u64` | page-map pointer | `0x50000000`-based virtual pointer | -| `+0x10` | `char[4]` | magic | `b"0DRP"` (`0x50524430`) | -| `+0x14` | `u32` | version | `122` (`0x7a`) | -| `+0x18` | `u64` | reserved | Always `0` | -| `+0x20` | `u32` | `root_block` | 1-based index into block directory (`+0x24` is `0`) | -| `+0x28` | `u64` | struct table ptr | `0x50000000`-based virtual pointer (`ns` x 32 B) | -| `+0x30` | `u64` | enum table ptr | `0` or `0x50000000`-based virtual pointer (`ne` x 24 B) | -| `+0x38` | `u64` | block directory ptr | `0x50000000`-based virtual pointer (`nb` x 16 B) | -| `+0x40` | `u64` | optional table ptr | `0` or `0x50000000`-based virtual pointer | -| `+0x48` | `4 x u16` | `(ns, ne, nb, u4e)` | Struct, enum, and block counts | -| `+0x50` | `u64` | optional ptr | `0` or `0x50000000`-based virtual pointer | -| `+0x58` | `u64` | reserved | Always `0` | - -Each 16-byte block directory row at `+0x38` is `(u32 type_hash, u32 byte_size, u64 virtual_ptr)`. Virtual pointers resolve to `virtual_ptr - 0x50000000` within the inflated resource buffer. When a resource spans two contiguous deflate streams, the block directory or a block payload extends past the first stream's end; continuation streams must only be joined while the resource is truncated and must stop before a new `0DRP`/`PSIN` header (a complete resource whose size happens to be a multiple of 64 KiB can sit immediately before another `0DRP` catalogue). - -### Standalone `PSIN` - -Uses the standard `PSIN` header, `0xaa`-filled 16-byte block table, `0x70` table terminator, `LSCH`/`LENM` schema sections, and `LRSC` `0DRP` v122 summary record (`u32@+0x10` = 1-based root block index), decoded via `tools/psin_data.py` (see [psin.md](psin.md)). - ---- - -## Schema and record layouts - -All offsets below were read directly from `LSCH` and verified across every `0x8dcb4cf5` catalogue in `packs.rpf`. - -### Root catalogue — `0x8dcb4cf5` (192 bytes) - -| Offset | Size | Field hash | Type | Meaning | -|---:|---:|---|---|---| -| `+0x00` | 96 B | `0x05269a03` | `0x50` (`0x60bcb6f3[2]`) | Two 48-byte preset buckets; each holds a `0x5c` array (`0x593bc9c3` at `+0x08`) of `0xf795e8ba` presets | -| `+0x60` | 96 B | `0x9bcf5f90` | `0x50` (`0x4c70a132[2]`) | Two 48-byte secondary buckets; each holds a `0x5c` array (`0x593bc9c3` at `+0x08`) of `0xa9d57751` records | - -### Preset record — `0xf795e8ba` (88 bytes) - -| Offset | Size | Field hash | Type | Meaning | -|---:|---:|---|---|---| -| `+0x00` | 4 B | `0x65121749` | `0x4a` (`u32`) | `preset_id` (unique within a catalogue) | -| `+0x04` | 4 B | `0x080eec39` | `0x4a` (`u32`) | `parent_id` (`0` = root preset, else parent `preset_id` in the same catalogue) | -| `+0x08` | 16 B | `0xebacf18c` | `0x5c` (`{u32 count, u32 cap, u64 ptr}`) | Array of 184-byte `0x37e52277` drawable/texture state records | -| `+0x18` | 4 B | `0xb53667be` | `0x4a` (`u32`) | Category hash (e.g. `0x378ad10c` head; `0x3817131d`, `0x44925bfd`, `0x9d283797` body skin) | -| `+0x1c` | 4 B | `0x5ecf9331` | `0x4a` (`u32`) | Secondary hash | -| `+0x20` | 4 B | `0xc4d75d79`..`0xa41d353b` | `3 x u8` + `0x60` enum | Preset flags and `0x25529dba` enum byte | -| `+0x24` | 4 B | `0xe13ebaf8` | `0x4a` (`u32`) | Auxiliary hash | -| `+0x28` | 24 B | `0x12f85293` | `0x71` sorted map | Preset tag map: `u64 flag` (`+0x28`), `u64 ptr` (`+0x30`), `u16 count` (`+0x38`), `u16 cap` (`+0x3a`) | -| `+0x40` | 24 B | `0x9a289423` | `0x71` sorted map | `u32` hash -> `array` map | - -Each slot in the `0x12f85293` tag map is **24 bytes** inside a synthetic anonymous map-slot block (`0x100..0x1ff`): - -```text -+0x00 u32 key (tag key hash, e.g. 0x4bfd27dd or 0x1c114e61 for drawable joaat32) -+0x04 u32 pad -+0x08 u32 count (number of u32 values) -+0x0c u32 capacity -+0x10 u64 value_ptr (internal pointer into a type-0x4a block of u32 hashes) -``` - -Synthetic block IDs (`0x100..0x1ff`) depend on per-file schema emission order. Across `packs.rpf`, `0x12f85293` uses `0x100` in 1,685 `0DRP` catalogues and `0x101` in 1,030 catalogues; hardcoding `0x100` drops 37.9% of catalogues. - -### Drawable / texture state record — `0x37e52277` (184 bytes) - -| Offset | Size | Field hash | Type | Meaning | -|---:|---:|---|---|---| -| `+0x00` | 4 B | `0x3eaddcd7` | `0x4a` (`u32`) | State ID / slot hash | -| `+0x04` | 4 B | `0x46d26d93` | `0x15` (`u32`) | State flags | -| `+0x08` | 56 B | `0xe7cb9e1b` | `0x05` (`0x147fdab5`) | Embedded drawable/texture + extension-map record (see below) | -| `+0x40` | 4 B | `0x1d52bc91` | `0x4a` (`u32`) | Auxiliary hash | -| `+0x48` | 16 B | `0x83698d93` | `0x5c` (`array<0x4a>`) | Auxiliary hash list | -| `+0x58` | 72 B | `0x35ff19d7`, `0x3b7601de`, `0x7e43b9a9` | `3 x 0x71` maps | Bitset/mask maps | -| `+0xa0` | 24 B | `0x12f85293` | `0x71` sorted map | State-level tag map (`u64 ptr` at `+0xa8`, `u16 count` at `+0xb0`) | - -### Embedded state body (`0x147fdab5`, 56 bytes at `0x37e52277 + 0x08`) - -| Local offset | `0x37e52277` offset | Field hash | Type | Meaning | -|---:|---:|---|---|---| -| `+0x00` | `+0x08` | `0x41acf8eb` | `0x4f` (`u64`) | Primary drawable `murmur64` (`h0`, MurmurHash3 x64_128 low word, seed 0) | -| `+0x08` | `+0x10` | `0xead733fc` | `0x4f` (`u64`) | Albedo texture `murmur64` | -| `+0x10` | `+0x18` | `0xd689b17f` | `0x4f` (`u64`) | Normal texture `murmur64` | -| `+0x18` | `+0x20` | `0x9d1000d8` | `0x4f` (`u64`) | Fourth 64-bit asset hash (`extra_hash`) | -| `+0x20` | `+0x28` | `0xb70a22c1` | `0x71` sorted map | Extension map: `u64 flag` (`+0x28`), `u64 ptr` (`+0x30`), `u16 count` (`+0x38`), `u16 cap` (`+0x3a`) | - -### `cull_drawable` chain (`0x147fdab5` -> `0xb70a22c1` -> `0x46e1a048` -> `0x3d780b74`) - -Each slot in the `0xb70a22c1` extension map is **16 bytes** inside a synthetic anonymous block (`0x100..0x1ff` — measured across `0x100`, `0x101`, `0x102`, `0x103` in `packs.rpf`): - -```text -+0x00 u32 key (extension key hash; 0x46e1a048 == joaat("cull_drawable")) -+0x04 u32 pad -+0x08 u64 target_ptr (0x07 polymorphic struct pointer: block = p & 0xfffff, off = p >> 20) -``` - -When `key == 0x46e1a048`, `target_ptr` resolves into a block of type `0x3d780b74` (**16-byte** records): - -| Offset | Size | Field hash | Type | Meaning | -|---:|---:|---|---|---| -| `+0x00` | 8 B | — | `u64` | Zero header (always `0` in all 43,626 measured records) | -| `+0x08` | 8 B | `0x7deba6f8` | `0x4f` (`u64`) | Alternate culled drawable `murmur64` | - ---- - -## Preset inheritance and resolution algorithm - -Within a single catalogue, `0xf795e8ba` presets form a forest keyed by `preset_id` via `parent_id`. Child presets commonly carry texture overrides (e.g. face albedo and normal) while placing the drawable tag (`0x4bfd27dd` or `0x1c114e61`, `joaat32` of the lowercased drawable name) on a parent or grandparent preset with zero texture hashes. - -`tools/ped_catalogues.py` resolves each state in deterministic precedence order: - -1. **Direct preset drawable tag** (`0x4bfd27dd` / `0x1c114e61` on the preset's `+0x28` tag map, `joaat32`). -2. **Direct state drawable tag** (`0x4bfd27dd` / `0x1c114e61` on the state's `+0xa0` tag map, `joaat32`). -3. **Inherited ancestor drawable tag**: walk `parent_id` within `presets_by_id`, maintaining a `visited` set (cycle guard) and depth cap (`MAX_PARENT_DEPTH = 16`; corpus maximum is 3), stopping at the nearest ancestor defining a drawable tag. -4. **State drawable hash**: direct `murmur64` `drawable_hash` (`h0` at `0x37e52277 + 0x08`). -5. **`cull_drawable` target**: resolved through `0x147fdab5` -> `0xb70a22c1` (`0x46e1a048`) -> `0x3d780b74 + 0x08` (`murmur64`), attached to every resolved state binding and searchable directly. - ---- - -## Verified corpus counts (Xbox package `1.0.2.1`, `packs.rpf`) - -Measured read-only with `tools/ped_catalogues.py` (0 parse errors, 0 warnings): - -| Metric | Resource-packed `0DRP` (`packs.rpf`) | Standalone `PSIN` (`00011ccb2000.pso`) | Combined | -|---|---:|---:|---:| -| `0x8dcb4cf5` catalogues | 2,715 | 1 | 2,716 | -| `0xf795e8ba` presets | 612,950 | 19,828 | 632,778 | -| Root-bucket (`0x60bcb6f3`) presets | 612,950 (100%) | 19,828 (100%) | 632,778 (100%) | -| Duplicate `preset_id`s within a catalogue | 0 | 0 | 0 | -| Presets with `parent_id != 0` | 334,146 | 11,634 | 345,780 | -| Maximum `parent_id` chain depth | 3 | 3 | 3 | -| Parent cycles / unresolved parents | 0 / 0 | 0 / 0 | 0 / 0 | -| `0x37e52277` states (reached / in blocks) | 878,374 / 878,374 | 17,741 / 17,741 | 896,115 / 896,115 | -| States with non-zero drawable `h0` | 559,139 | 7,227 | 566,366 | -| States with non-zero albedo | 623,350 | 7,642 | 630,992 | -| States with non-zero normal | 598,104 | 7,248 | 605,352 | -| Catalogues with `cull_drawable` | 2,206 (81.25%) | 1 | 2,207 | -| Resolved `0x46e1a048` -> `0x3d780b74` links | 42,882 | 744 | 43,626 | -| `0x3d780b74` block records (all non-zero `murmur64`) | 42,882 (100%) | 744 (100%) | 43,626 (100%) | -| Observed `0x12f85293` tag-map block IDs | `0x100` (1,685), `0x101` (1,030) | `0x100` (1) | `0x100`, `0x101` | -| Observed `0xb70a22c1` ext-map block IDs | `0x100` (1,030), `0x101` (1,411), `0x102` (3), `0x103` (1) | `0x101` (1) | `0x100`..`0x103` | - ---- - -## CLI usage - -```powershell -python -I tools/ped_catalogues.py census --json -python -I tools/ped_catalogues.py inspect --limit 10 -python -I tools/ped_catalogues.py resolve --name --cull-only --json -``` diff --git a/docs/pipeline_check.md b/docs/pipeline_check.md deleted file mode 100644 index 5e8872cad..000000000 --- a/docs/pipeline_check.md +++ /dev/null @@ -1,501 +0,0 @@ -# GPU pipeline corpus check - -`runtime/test/vk_pipeline_check.cpp` creates a `VkShaderModule` for every entry in the translator's -`index.json` and, for compute shaders, a real compute pipeline with the runtime's descriptor and push -constant contract. It is a driver-level check: it proves the modules and pipelines are accepted by -the Vulkan implementation, not that the shader results are correct. Value-level checks are in -`docs/shader_validation.md`. - -Timing and memory figures in this page were measured with `MESA_SHADER_CACHE_DISABLE=true`. Without it, RADV's -on-disk shader cache (`~/.cache/mesa_shader_cache`, about 1.1 GB after a full corpus run) turns a repeated module -into a cache hit: 0.1 s and ~114 MB instead of a real compilation. That is what a resume run wants, but not what a -measurement should report. - -The checker exits nonzero if a module fails to load, a pipeline fails to compile, or the requested final -cache save fails. It still finishes checking the other entries and attempts the final save so the next run -can reuse successful pipelines. Before creating a Vulkan shader module, it checks that the file has a -complete SPIR-V header, the SPIR-V magic word, and a whole number of 32-bit words. A rejected input -module counts as a failure. A rejected partner stub is unavailable, so the affected pipeline is skipped. -It also exits 2, before loading Vulkan, if `index.json` is missing, unreadable, empty or malformed, so a wrong -directory can't pass as an empty corpus. A valid `{}` is an intentionally empty index. - -For an index entry with `lds_bytes`, the checker compares the reported workgroup memory with the selected GPU's -`maxComputeSharedMemorySize` for compute or `maxMeshSharedMemorySize` for supported mesh shaders. An entry above its -limit counts as a module failure before Vulkan receives the shader. Older indexes without this field still use the -normal driver check. Mesh pipelines on devices without mesh shader support still use the existing feature skip. - -## Options - -`vk_pipeline_check [cache.bin] [options]` - -| Option | Meaning | -|---|---| -| `cache.bin` | Optional positional pipeline cache. Loaded first if it exists, saved every 10 minutes and at the end, so a stopped run resumes. | -| `--jobs N` | Compile on N threads (default: half the hardware threads). | -| `--start I`, `--count N` | Check only the sorted index entries `[I, I+N)`. | -| `--stage all\|cs\|graphics` | Which stages to check. `--compute-only` and `--graphics-only` are aliases. | -| `--slow SEC` | Print pipelines slower than SEC (default 30); compiles past 60 s are named while running. | -| `--max-bytes N` | Skip `.spv` files larger than N bytes (0 = no limit); every skip is named. | -| `--large-module-bytes N` | Compile modules larger than N bytes alone (default 4 MiB; 0 disables isolation). | -| `--stats FILE` | Write the driver's per-shader statistics as CSV rows `name,stage,statistic,value`. Needs `VK_KHR_pipeline_executable_properties`; use it without `cache.bin`, because a cached pipeline may come without statistics. | -| `--cache-feedback` | Group successful pipeline creations by `VkPipelineCreationFeedback`: cache hits, no hit reported, and unavailable. | -| `--isolate` | POSIX only: check in child processes, `--isolate-batch N` modules at a time (default 256), so a crashing module is recorded as `MODULE CRASH` and the pass continues. Not compatible with `--stats`. | -| `--inflight-file F` | Keep the modules currently in the driver in F as `namephase` lines. It is rewritten by the watchdog and when a large module enters or leaves, and emptied at the end; `make_game.py`'s pipelines stage reads it. | -| `--skip-file F` | Do not compile modules named one per line in F; each is reported as `MODULE CRASH` and counted as a failed pipeline. `make_game.py` writes F after a crash so the next run checks the rest. | - -`--isolate-child` is internal to the parent/child protocol and is not meant to be passed directly. A module with a missing partner stub is skipped; without `--isolate`, a driver crash ends the run. - -## Check user-defined interfaces between stages - -`tools/shader_link_check.py` compares the binary SPIR-V declarations of the shaders you plan to put in the -same pipeline. Use it before driver compilation to locate missing varyings, overlapping components, type -mismatches and per-primitive mesh declarations. It reads local modules and needs only Python. - -The declarations come from `tools/spirv_interface.py`, a standard-library reader of one module's interface -(the normalized `Location`/`Component` model, one array level and literal specialization defaults) with its -tests in `tests/test_spirv_interface.py`. It reflects declarations only, not instructions, device features or -resource bindings, so it does not replace `spirv-val`. - -```powershell -python -I tools/shader_link_check.py check --vs --ps -python -I tools/shader_link_check.py check --vs --gs --ps -python -I tools/shader_link_check.py check --ms --ps -python -I tools/shader_link_check.py inspect -``` - -Direct checks use `main` for every stage unless `--entry` sets another shared default. -Use a stage-specific override for modules with different entry names, for example -`check --vs vertex.spv --vs-entry Vertex --ps pixel.spv --ps-entry Fragment`. - -To audit a batch, give it the shader names from your local translation directory in a JSON file. A stage can -use a string or a `shader` and `entry` object. Names refer to `.spv` in `--shader-dir`. The manifest is read as -UTF-8 with or without the byte order mark, so a copy saved by Notepad or `Out-File -Encoding utf8` is taken as is. - -```json -{ - "version": 1, - "pipelines": [ - {"name": "two-stage", "vs": "vs_example", "ps": "ps_example"}, - {"name": "with-geometry", "vs": "vs_example", "gs": "gs_example", - "ps": {"shader": "ps_other", "entry": "main"}} - ] -} -``` - -```powershell -python -I tools/shader_link_check.py batch pairs.json --shader-dir --quiet --report link-report.json -``` - -The report records per-pipeline results. It uses the Vulkan Location and Component model, including one -outer array level for geometry inputs, mesh outputs and fragment `PerVertexKHR` inputs. Add `--maintenance4` -when the actual device enables that feature and the pipeline relies on matching a wider output vector to a -narrower input vector. See [Vulkan interface matching][interfaces]. - -Exit codes are `0` for compatible interfaces, `1` for a mismatch and `2` for a bad input or an interface -the reader cannot interpret. Continue with the driver checker for shader instruction validation, resource -bindings, device limits and pipeline state. Shader pairs must come from the caller. Share aggregate counts -and error classes, keeping the local shader files and reports that identify them on your PC. - -[interfaces]: https://docs.vulkan.org/spec/latest/chapters/interfaces.html#interfaces-iointerfaces-matching - -## Audit wave fidelity for the target GPU - -The subgroup audit combines the translator's wave-width and partition-invariance metadata with -the target device's Vulkan stage capabilities. A device can require 64 lanes for a fragment -shader without being able to require 64 for a vertex or geometry shader. Audit the whole graphics -index or use the same manifest as the interface check. - -```powershell -python -I tools/wave64_pipeline_audit.py /index.json -python -I tools/wave64_pipeline_audit.py /index.json --manifest pairs.json --strict --report wave64-summary.json -``` - -The audit checks the Vulkan device selected on this PC and respects `LEONIDA_VK_DEVICE`. To assess -another device, save `python -I tools/vk_subgroup_info.py --stage-caps` as UTF-8 JSON on that system and pass the file -with `--device-info`. The report counts each shader once and each pipeline by its worst stage. It -contains aggregate counts, capability masks and reason categories. Shader and pipeline names are -excluded from the report. - -| Result | Meaning | -| --- | --- | -| `exact` | Fixed or explicitly requestable translated width, or workgroup exchange in compute/mesh | -| `partition-invariant` | A 32-wide graphics subgroup can run a tier A/B wave64 shader. Tier B atomic slot order can differ. | -| `default-width` | The reported device default matches, with no per-stage width guarantee | -| `approximate` | A tier C wave64 VS, PS or GS depends on cross-half behaviour on the 32-wide device | -| `unknown` | The index or device lacks the information for a decision | -| `unsupported` | The translated width, stage support or execution model does not fit the target | - -In strict mode, exit 1 means at least one result other than `exact` or `partition-invariant`. -Invalid inputs or an unavailable Vulkan probe exit 2. This checks width fidelity from metadata. -Vulkan pipeline creation and drawing still need their own tests. See [Wave64 graphics in the -translator contract](design.md) for how the tiers are assigned. -## Test Mesa pipeline compilation without a physical GPU - -On Linux, Mesa's DRM shims expose GPU profiles to its Vulkan drivers. This lets `vk_pipeline_check` -measure shader compile time and reproduce compiler failures on a machine without that hardware. -Readback and dispatch correctness still require a Vulkan device that executes commands. -See the [Mesa DRM shim guide](https://docs.mesa3d.org/ci/drm-shim.html). - -From the Leonida root, build the checker and translate a synthetic fixture. The fixture build needs -`spirv-as`, `spirv-val` and LLVM 21 or later with the AMDGPU target. Set `LLVM_MC` if the assembler -has a versioned name. - -```sh -cmake -S runtime -B runtime/build -G Ninja -DCMAKE_BUILD_TYPE=Release -cmake --build runtime/build --target vk_pipeline_check -fixtures=$(mktemp -d) -python3 -I runtime/test/shaders/build.py "$fixtures" cs_buf_fmt8 -``` - -### AMD RADV - -Build Mesa with `-Dvulkan-drivers=amd -Dtools=drm-shim`. Set `mesa_build` to that build directory -and `radv_icd` to the absolute path of the matching RADV Vulkan ICD manifest. - -```sh -AMDGPU_GPU_ID=gfx1201 \ -LD_PRELOAD="$mesa_build/src/amd/drm-shim/libamdgpu_noop_drm_shim.so" \ -VK_DRIVER_FILES="$radv_icd" MESA_SHADER_CACHE_DISABLE=true \ - runtime/build/vk_pipeline_check "$fixtures/spirv" --jobs 1 --slow 0 -``` - -The checker should select a device whose name includes `RADV GFX1201` and report one compute pipeline -compiled. For comparisons, use the same Mesa version, GPU profile and translation flags each time. -Run each comparison in a fresh process and leave the pipeline cache filename out. - -Mesa 25.0.7 also supports a null device directly through the installed RADV ICD. On Debian 13 -this runs the same compile check with the distro driver. - -```sh -RADV_FORCE_FAMILY=GFX1201 VK_DRIVER_FILES=/usr/share/vulkan/icd.d/radeon_icd.json \ -MESA_SHADER_CACHE_DISABLE=true runtime/build/vk_pipeline_check "$fixtures/spirv" --jobs 1 --slow 0 -``` - -### Intel ANV - -Build the Intel shim with `-Dtools=drm-shim,intel` and use an ANV ICD from the same Mesa version. -When using a prebuilt driver, the shim can be built with `-Dvulkan-drivers= -Dgallium-drivers=`. -Set `intel_icd` to the absolute path of its ANV manifest and `intel_shim_build` to the shim's -Mesa build directory. - -```sh -INTEL_STUB_GPU_PLATFORM=bmg \ -LD_PRELOAD="$intel_shim_build/src/intel/tools/libintel_noop_drm_shim.so" \ -VK_DRIVER_FILES="$intel_icd" MESA_SHADER_CACHE_DISABLE=true \ - runtime/build/vk_pipeline_check "$fixtures/spirv" --jobs 1 --slow 0 -``` - -The example selects a Battlemage profile. Use `dg2` for an Alchemist profile or `adl` for Alder Lake. -On Mesa 26.1.6 all three compiled the example, including when it was rebuilt with -`LEONIDA_PC_TAIL_UBO=1` to move the push-constant tail to a uniform buffer. - -## Corpus - -The translated corpus is 26,503 entries: 2,236 vertex, 12,101 pixel, 2,689 compute, 9,282 mesh and -195 geometry shaders. A run was split into 12 contiguous index shards of about 2,209 entries each. -The shards were run with a per-shard pipeline cache; each saves a cache of roughly 190-203 MB. - -| Shard | Modules | CS pipelines | Result | Cache | Wall | -|---|---:|---:|---|---:|---:| -| s2 | 2,207 | 208 | pass | 196,869,933 B | 2h21m35s | -| s3 | 2,209 | 200 | pass | 190,022,273 B | 1h50m54s | -| s4 | 2,210 | 213 | pass | 198,941,511 B | 2h01m55s | -| s5 | 2,209 | 248 | pass | 201,997,254 B | 2h01m09s | -| s6 | 2,209 | 213 | pass | 190,939,966 B | 2h00m05s | -| s7 | 2,209 | 229 | pass | 202,013,032 B | 1h59m27s | -| s8 | 2,210 | 227 | pass | 199,121,775 B | 2h00m11s | -| s9 | 2,210 | 240 | pass | 198,407,685 B | 2h00m27s | -| s10 | 2,210 | 218 | pass | 202,890,354 B | 2h01m58s | -| s11 | 2,209 | 221 | pass | 200,378,101 B | 2h01m42s | -| **total (10/12)** | **22,092** | **2,217** | **0 module / 0 pipeline failures** | **1,981,581,884 B** | | - -Stage split over the ten shards: 2,217 compute, 163 geometry, 7,767 mesh, 10,088 pixel and 1,857 -vertex modules. The ten shards cover **22,092 of 26,503 entries (83.4%)** and **2,217 of 2,689 -compute pipelines (82.4%)**. - -Two shards did not complete: - -- **s0** was stopped after 1 h 57 m at 81% of its bytes, with no read progress for 27 minutes on a - 3.61 MB compute shader. -- **s1** was stopped at the same time at 83% of its bytes on a 2.52 MB pixel shader. - -They account for the missing 4,411 modules (472 compute, 32 geometry, 1,515 mesh, 2,013 pixel, 379 -vertex) and 472 compute pipelines. No summary was printed for either shard. This is a driver -compile-time limit, not a module or pipeline rejection: no `MODULE FAIL` or `PIPELINE FAIL` line -exists in any completed shard. - -A later full-corpus build on different hardware (RTX 4060 Ti, driver 595) completed **26,503 of 26,503** -modules and pipelines with **0 failures** and a 3.81 GB cache; see the "Full-corpus pipeline build" row in -[`docs/design.md`](design.md). The two stalled shards above therefore record a hardware/driver-specific -compile-time stall, not a project-wide limit. - -The recurring slow family at every shard tail was a set of 6.7-7.2 MB ray-tracing resolve compute -shaders. One observed single-module stall exceeded 27 minutes, read from the run's progress output. -The tool times each pipeline: `--slow SEC` prints `SLOW (w, s)` for a pipeline -that takes longer than SEC, and each stage's summary ends with -`compile time: s total, s mean, slowest (s)`. A run with `--slow 0` therefore -reports such a stall with its duration, not as a lower bound. - -## Bounded guaranteed-finish sample - -A separate bounded run covers eight 30-entry bins plus 12 large compute shaders: **252/252 modules -accepted** and **172/172 compute pipelines accepted**, 0 failures. Stage split: 172 compute, 20 each -geometry/mesh/pixel/vertex. Wave split: 97 wave64 / 75 wave32. The nine processes finished in about -5 minutes; their caches total 42,098,592 bytes. This is a sanity check on the same device, descriptor -layout and subgroup path, not a substitute for the 26,503-entry corpus. - -A validation-layer run of the same 252 shaders (temporary instrumented copy, not committed) produced -**zero shader/module/pipeline messages**. The 9 errors and 36 warnings were loader noise from -overlay layers (a missing Epic JSON, three non-conforming layer names, one duplicate OBS hook). The -22,092 full-shard modules were not re-run through the validation layer; their result is driver -acceptance only. - -## Limiting concurrent compilation of large modules - -A SPIR-V module larger than 4 MiB is "large". [#884](https://github.com/ItsNotRexed/Leonida/issues/884) -showed why that matters: several compiles that each needed gigabytes of host RAM ran at the same time. Large -modules now share a memory budget (`runtime/test/large_module_gate.h`): each one reserves 512 bytes of RAM per -SPIR-V byte, and they enter the driver while their reservations fit three quarters of the memory available when -the run starts, up to `--jobs` of them. One large module always gets in when none is compiling, so a module -bigger than the whole budget still compiles, alone among the large ones. Small modules are never held back. On -Linux the budget is the smaller of `MemAvailable` and the room under the cgroup v2 `memory.max` of the process and -every cgroup above it (a container, or `systemd-run -p MemoryMax=...`); on Windows it is `ullAvailPhys`. Where -neither can be read, every large module compiles alone, as before. After each large module, glibc builds call -`malloc_trim(0)`: the driver's compiler frees its memory into the arena of the thread it ran on, and glibc kept it -there. - -Measured on an RX 9070 XT (RADV GFX1201, Mesa 25.3.6, Mesa shader cache off), on 40 consecutive translated -compute modules of which 27 are over 4 MiB: - -| Large modules | Threads | Wall time | Peak RAM | -|---|---|---|---| -| one at a time (`--large-parallel 1`, the old default) | 6 | 297 s | 7.1 GB | -| memory budget (default) | 6 | 83 s | 8.3 GB | -| memory budget (default) | 12 | 56 s | 15.1 GB | - -One 5.7 MB ray-tracing compute module alone: 12.4 s and 1.96 GB peak (about 330 bytes per SPIR-V byte, hence the -512 estimate); a 0.36 MB one: 0.13 s and 94 MB. The process grew past one module's peak even one at a time because -of the arenas (16 modules, 6 threads: 6.2 GB; with `MALLOC_ARENA_MAX=1`: 2.1 GB). - -- `--large-module-bytes N` changes the cutoff in bytes. `0` disables the gate. -- `--large-parallel N` caps how many large modules compile at once: `0` (default) by the budget, `1` alone with - the other threads waiting (the behaviour before), `N` at most N without a budget. -- `--inflight-file` names every module in flight when a large one enters or leaves the driver, so with several - large modules in flight it names all of them; the `pipelines` stage of `make_game.py` checks each alone. - -## Skipping huge modules - -`vk_pipeline_check` now accepts `--max-bytes N`: - -```powershell -vk_pipeline_check [cache.bin] --max-bytes 2000000 --count 100 -``` - -Every `.spv` larger than `N` is reported as `BIG SKIP (, limit )`, counted by stage, -and excluded from the module/pipeline totals; the summary prints how many entries were checked. On a -30-entry smoke test with `--max-bytes 20000`, 24 modules were skipped and the remaining 6 pixel -modules passed. - -The report above therefore states the limit and the skip count; a later run on an RTX 4060 Ti / 595 -completed the full 26,503-entry set without them (`docs/design.md`). `--max-bytes` remains a visibility -tool, not a pass: a skipped module has not been validated. - -## Stack reserve (BUILD-1457) - -A driver compiles on the thread that creates the shader module or the pipeline, and its compiler can recurse with -the shader's control-flow nesting. On Windows a thread that asks for no stack size gets the reserve written in the -executable's PE header, 1 MB by default. That is the checker's main thread and every `std::thread` worker. - -`vk_pipeline_check` is linked with an **8 MB** reserve: `/STACK:8388608` in `runtime/cmake/vulkan_tools.cmake` and on -the checker's `cl` line in `scripts/build_runtime.ps1`. The CTest `vk_pipeline_check_stack` reads `SizeOfStackReserve` -back from the built file (`runtime/test/check_stack_reserve.cmake`; the program is not run), and -`tests/test_build_runtime_fallback.py` keeps the two numbers the same. - -Measured on an AMD Radeon RX 9070 XT, AMD 26.11.2 (LLPC, Windows driver 32.0.32029.2010), each module alone with -no cache file (`--jobs 1 --start N --count 1`), on a 1.0.2.1 corpus translated at `aa2988cc` with native wave64. -The reserve was changed with `editbin /STACK` on copies of one binary. Counts only. - -| Reserve | The 26 mesh modules that overflow at 1 MB | 28 structured compute modules that overflow at 1 MB | -|---|---|---| -| 1 MB | 26 exit 0xC00000FD (stack overflow) | 28 exit 0xC00000FD | -| 2 MB | 26 create their pipeline | 18 create theirs, 10 exit 0xC00000FD | -| 4 MB | 26 create their pipeline | 28 create their pipeline | -| 8 MB | 26 create their pipeline | 28 create their pipeline | - -The 26 are what a corpus translated on `main` hits: 2.42 to 2.79 MB of SPIR-V each, among 846 mesh and vertex -modules of 1 MiB or more that were tried one by one at 1 MB (the other 820 pass). The 28 come from a sample of 60 -compute modules, picked evenly by size, of the 781 that take the structured form once the structured depth bound -is 64 instead of 16 (SHADER-427): every sampled module from 4.76 MB up overflows 1 MB. So 2 MB is enough today and -not for the deeper trees. With the linked 8 MB, the same 26 and 28 create their pipelines, and with that binary's -reserve put back to 1 MB all 54 overflow again. - -Not measured: other AMD GPU families, other vendors' Windows drivers, and a corpus translated with -`--wave64-emulate`. - -**The runtime.** The D3D12 shim creates a pipeline on the thread that asks for it -(`runtime/shims/d3d12_vulkan_device.cpp`), so there the compiler runs on a game thread. The entry thread has 8 MB -from `run_entry` (`runtime/shims/process_shim.h`). A thread the game starts with `dwStackSize` 0, a thread-pool -thread and a `std::thread` of the shims get the reserve in `gta6rt.exe`'s header, because the game's `CreateThread` -is Windows' own. `gta6rt` is therefore linked with the same 8 MB (`GTA6RT_STACK` in -`runtime/cmake/windows_runtime.cmake`, and the loader's `cl` line in `scripts/build_runtime.ps1`). The CTest -`gta6rt_stack` reads the header, and -`run_tiny_game_stack` asks Windows from inside a program the loader runs: the entry thread and a thread created -with `dwStackSize` 0 both report 8 MB. Not covered: a thread the title creates with an explicit smaller size keeps -that size. Which threads the game creates pipelines on is not known without its executable. - -## Build-stage batches (BUILD-1030) - -`make_game.py` runs the pipelines stage in fresh checker processes over at most **500 index entries** each, on -Windows and POSIX. The ranges partition the same name-sorted index as `--start` / `--count`, including the final -short range. Each finished process saves to the same `pipeline_cache.bin`, and the next loads that checkpoint. -This bounds each invocation to a range that can be split further if concurrent heavy compiles exceed available -memory. A work folder with at most 500 entries keeps the single invocation. An older checker without the range -options keeps the older invocation; rebuild the runtime to get batching. - -If a batch crashes, its in-flight modules are checked alone in fresh processes. A module that reproducibly crashes -is recorded as failed, and the rest is checked. If none crashes alone, the entire failed range is retried in -smaller processes, down to one entry; healthy modules are not added to the crash list. An unrecoverable crash, -an interrupted check or a setup error stops the stage. A validation failure in one batch remains a failure even -when subsequent batches succeed; it does not prevent those later batches from being checked. - -The native checker returns 1 for initialization failures as well as validation failures. A completed shader pass -writes/clears its in-flight report even when validation fails. Exit 1 without a new report stops the stage instead -of repeating failed setup for the remaining batches; diagnostic probes use the same distinction. Each process -starts with a cleared report path, so an earlier process's report cannot hide an initialization failure. - -An abnormal diagnostic-probe exit confirms a module crash only when that probe's fresh in-flight report names -the selected module. A missing, empty or unrelated report makes the result inconclusive and stops the stage -without blaming that module. The native report is periodic for small modules, so even a real fast crash can -leave no evidence; this conservative fallback does not guess its cause or add an unconfirmed crash-list entry. - -The batch size limits the index range, **not total memory usage**. Concurrent heavy modules, loading a large -saved cache or compiling one large shader can still exceed a process's available memory; a range that -cannot complete even alone fails with a diagnostic rather than being counted as checked. - -`tests/test_make_game_pipeline_batches.py` runs the real build-stage orchestration against scripted child processes: -bounded coverage and cache checkpoints, collective memory-crash recovery, a genuinely crashing module, validation -failures, interruptions, setup failures, inconclusive probes and compatibility with older checkers. It needs no -game files or GPU. - -## Crash isolation (`--isolate`) - -A driver that dies while compiling one module (for example the RADV `SIGFPE` in -[#1721](https://github.com/ItsNotRexed/Leonida/issues/1721)) ends the whole process, so the rest of the corpus -used to need that module excluded by hand with `--start/--count`. With `--isolate` the tool runs the check in -child processes on native Windows and POSIX: - -```sh -vk_pipeline_check cache.bin --isolate [--isolate-batch 256] [--jobs N ...] -``` - -- The parent opens no Vulkan device. It runs this executable, one child at a time, over `--isolate-batch` - modules (default 256) of the same sorted, stage-filtered list, with the other options passed on (`--jobs` is - the thread count inside each child). `--stats` is refused: children would overwrite one file. -- A child that is killed by a signal, or exits without finishing the pass after it started work, has its output - discarded and its batch is bisected (re-run in halves) down to the module that kills it. That module is printed as - `MODULE CRASH (, driver crashed: SIGFPE)`, counted as a failed pipeline and listed at the end; - the other modules are checked as usual and counted once. If both halves of a crashed batch run clean (a crash - that needs several threads at once), the batch is reported as `MODULE CRASH [a, b) not reproduced ...` and - counts as a failure. A child that fails before it starts work (no device, bad arguments) stops the run - with exit status 1. -- Windows reports exception exit codes in hexadecimal, for example `driver exited with status 0xc0000005`. -- The pipeline cache: children run one after another and each seeds from and saves to the same `cache.bin`, - like the chunked runs above; the save is atomic, a crashed child saves nothing, so the file stays valid and - holds everything the finished children compiled. The parent prints its size at the end. -- Exit status: 0 only if no module failed or crashed and the cache saved; 1 otherwise. The summary is - aggregated by the parent (modules, pipelines, skips, `--cache-feedback`); the per-stage wave and compile-time lines - of a normal run are not repeated. Output of a batch appears when its child finishes. -- Each child loads the cache again, so a very large cache makes small batches slow; raise `--isolate-batch`. - There is no timeout: a hung compile still hangs. - -Test hook, not for normal use: `VK_PIPELINE_CHECK_SIMULATE_CRASH=[:SIGNAL]` makes the -process simulate a crash just before creating a matching module's pipeline. The default is `SIGFPE`. -On Windows, `SIGFPE` and `SIGSEGV` use the corresponding exception exit codes. -`tests/test_vk_pipeline_check_isolate.py` uses it with five hand-written compute -shaders to check `--isolate` without a crashing driver; it skips when the tool isn't built or there is no -Vulkan device. - -## Application pipeline-cache feedback - -With `--cache-feedback`, the checker groups successful pipeline creations by translated shader stage -and reports three counts. A **hit** means the driver set both the valid-feedback bit and the -application-cache-hit bit. **No hit reported** means feedback was valid and the hit bit was clear. -**Unavailable** means the driver returned no valid feedback, or feedback was unsupported. -The three counts sum to the successful pipelines for the stage. Skips and failures are counted separately. - -A driver can also use its own caches. A clear hit bit does not establish a fresh compile, and a -reported hit may reuse data populated earlier in the same process. The seed-file byte count alone -cannot identify which pipelines benefited. - -To compare runs, start with a new cache path and keep the device, index and flags identical, including -`--stats` if used. For example, from a scratch directory that contains no `sample.cache`, run the same -command twice, replacing `path/to/spirv` with the local translated-shader directory. - -```sh -vk_pipeline_check path/to/spirv sample.cache --cache-feedback -vk_pipeline_check path/to/spirv sample.cache --cache-feedback -``` - -On Windows with an RTX 5090 (driver 621.14), a synthetic three-compute, one-vertex and one-pixel -sample reported zero application-cache hits on its first run and five on the seeded run. On Mesa -llvmpipe the same five pipelines succeeded both times and neither run reported a hit. - -## Wave64-emulated corpus (`--wave64-emulate`) - -A GPU that only runs 32-wide subgroups (NVIDIA, Intel) needs the corpus translated with -`--wave64-emulate`. Its cross-lane operations go through workgroup memory instead of subgroup operations. -Its modules are larger, and they behave differently under the driver. All runs below are on an -RTX 4060 Ti (NVIDIA 595 driver, 32 GB RAM). - -**Translation.** All 26,503 shaders translate and pass `spirv-val` at 43d4703. The run used eight -`--shard` processes and took 80 minutes. The modules total 13.68 GB: median 3.3% larger than the -previous emulated translation (spirv4), 90th percentile 16% larger, with exact-semantics rules added -in between. - -**One process per chunk.** A single `vk_pipeline_check --jobs 4` run over the emulated corpus reached -21,000 of 26,503 pipelines with no failures. Then the driver's compiler ran out of memory -(`LLVM ERROR: out of memory`). With 2 jobs, one process later grew past 100 GB of committed memory. -In those earlier runs, compiler allocations were reported to persist between pipelines; the original workaround -used one checker process per 300–500 entries. The build stage now uses at most 500 per process, with smaller -retries when needed (above). -Each process seeds from and saves to the same cache file, so the chunks resume. Since #903 the checker also -compiles modules over 4 MiB alone. - -For BUILD-1030, [the reporter's later measurements](https://github.com/ItsNotRexed/Leonida/pull/3623#issuecomment-7085912874) -found no accumulation over a 1,500-entry range and cheap loading of the full cache; the large peaks came from -individual heavy modules. The recovery therefore splits the failed range until fewer such modules compile at -once, without treating the initial cache-growth hypothesis as established. - -**The ScreenProbes shaders.** `indirect_diffuse_lighting`'s ScreenProbes_ActivateProbes, -ActivateProbesTarget and ActivateRays compute shaders were 60, 60 and 32 MB of SPIR-V. Their 3,281 -typed-buffer loads each decoded every supported format inline. The exact UNORM/SNORM conversion added in -#755 made that about 900 instructions per load, which pushed the two largest past SPIR-V's id bound of -4,194,303 (#881). They were also the modules compiling when the driver ran out of memory. Since -dcd8ecf the run-time format decode is one function per module (`%fmt_decode_fn`): -ActivateProbes went from 6.16 M to 2.20 M instructions (41.7 MB), and all three now validate. - -**Results.** With the pre-dcd8ecf translation (spirv4), entries 0–24,200 compiled with 0 module and -0 pipeline failures; two modules over 16 MiB were skipped in the chunked part. The spirv5 cache (all -26,503 entries, nothing skipped by size) is being built. - -## Device - -The reported runs used an NVIDIA GeForce RTX 5070 Ti (discrete, subgroup size 32 only), driver -621.24 / Windows 32.0.16.2124, Vulkan 1.4.357, loader 1.4.363, with 28 logical CPUs and 34 GB RAM. -The executable used the Vulkan SDK at `C:\VulkanSDK\1.4.363.0`; no source change was needed to build -or run it. - -## What this does and does not prove - -It proves, for the ten completed shards, that every translated module is accepted and every compute -pipeline is created with the runtime's resource contract. It does not prove: - -- that any shader computes the right values (see `docs/shader_validation.md`); -- that the two incomplete shards are valid or invalid; -- that the graphics pipelines (vertex/pixel/geometry/mesh) execute or draw the right pixels: the tool - creates them with `vkCreateGraphicsPipelines` (dynamic rendering) but never draws with them; -- that the game's descriptors, root signatures and push constants match the contract at run time - (the missing executable still owns that). - -No shader data, names or caches are committed. The caches live in the work directory and are inputs -to a later run, not part of the repository. diff --git a/docs/progress_dashboard.md b/docs/progress_dashboard.md deleted file mode 100644 index b36e938c8..000000000 --- a/docs/progress_dashboard.md +++ /dev/null @@ -1,66 +0,0 @@ -# Progress dashboard - -`tools/progress_dashboard.py` turns outcomes the project already produces into one page that answers three questions: -what works, what changed since it last passed, and what blocks next. It runs locally, reads only, and writes nothing -into the repository. - -```powershell -python -I tools/progress_dashboard.py --out ..\leonida_progress --run-tests --github -start ..\leonida_progress\progress.html -``` - -`--out` must be outside the repository; the tool refuses a folder inside it, so its output can't be committed by accident. -The page is one self-contained HTML file: no network, no packages, it opens from disk. The project logo -(`assets/logo.png`) is embedded in it, and the page follows the system theme until you pick one with its theme button. - -## Sources - -Each source is optional. A missing one is listed under "Sources" on the page; it is never counted as zero or as a failure. -For `--junit`, keep the original XML encoding. UTF-16 reports and reports with a supported encoding declaration -are read directly; there is no need to re-save them as UTF-8. - -| Panel | Source | Unit | -|---|---|---| -| Unit tests | `--run-tests` runs `tests/test_*.py` with the selection `ci.yml` uses (standard-library files with a `__main__` block), one process each; the outcome and the commit it ran on are kept in `/unit_results.json`. That is CI's standard-library loop only: `tests/semantic` (the translator suite) and files that need pytest or numpy are not run, so the panel is not the whole test suite; feed those through `--junit` (`python -m pytest tests/semantic --junitxml `) to see them in the runtime-tests panel | test file | -| Runtime tests | `runtime/build/Testing/Temporary/LastTest.log` and any `--junit` file (CTest `--output-junit` or pytest `--junitxml`). CTest logs and XML reports are age-checked by file modification time | test | -| GPU tests | `--gpu-log [=]`: the saved output of `runtime/test/shaders/check.py`, one group per GPU; a log older than the last commit touching `runtime/test/shaders` or `tools/rdna2spirv.py` counts as needing a re-run | test program | -| Translator contract | the contract table in [design.md](design.md#translator-status-and-runtime-contract), each row classified by how it says it was confirmed | contract row | -| Runtime imports | the measured tables in [runtime_imports.md](runtime_imports.md) | import | -| Shader corpus | `--work `: counts per stage from `/shaders/dxbc/index.json` and `/shaders/spirv/index.json` | shaders, aggregated per stage | -| Pull requests into main | `--github`: every pull request into `main` of the main repository (`--repo`, default `ubiquitarianism/leonida`), grouped by the item ID its title names (`D3D-86: …`, `… (SHADER-339)`) | pull request | -| D3D12 layer | `--github`: the `D3D-` table of the D3D12 tracking issue, read through `gh` and checked against the merged and open pull requests. The issue is the open one whose title starts with "D3D12 → Vulkan layer", or the one `--d3d-issue N` names; when the repository has neither, the sources list says so and the panel stays empty (the number is not fixed: it was #313 in the original repository) | item | -| CI on main | `--github`: the latest completed run of each workflow on `main` | workflow | - -Every run with `--github` reads the pull requests again, so a merge into `main` shows up on the next run as -IMPLEMENTED, even before a tracking table (such as the D3D12 tracking issue's PR column) is edited. A pull request closed without merging is -left out. The page also lists the 30 latest merges, and the trend chart follows the share of pull requests merged and -of item IDs with a merged pull request. `gh pr list` reads at most 5000 per state; the Sources table says when that -limit is reached. - -With `--github --login ` the page also lists that account's claims in the coordination issue (and the issue -it continues) and its pull requests. Nothing is posted: every `gh` call is a read. - -## How a status is decided - -| Status | Unit tests and CTest | Contract row | Import | Pull request | D3D- item | -|---|---|---|---|---|---| -| VERIFIED | passed, and nothing it depends on changed since | names a GPU check and leaves nothing open | image with 0 unimplemented imports | — | — | -| IMPLEMENTED | — | confirmed by an LLVM/Mesa reference, a corpus count or a CPU test, not a GPU | bound to a shim, the host or a module | merged into `main` | a PR merged into `main` and none open | -| PARTIAL | passed before a change to the test, `make_game.py`, or a Python file under `tools/`, `scripts/` or `runtime/test/shaders/` (CTest: before the last commit touching `runtime/`) | waits for a GPU measurement, or names a GPU check with an item still open | — | open | pull request open | -| FAILED | failed on its last run | — | — | — | — | -| MISSING | — | — | unimplemented | — | unclaimed | -| UNKNOWN | skipped, or git can't tell what changed | states no confirmation method | — | — | claimed, no code yet | - -The contract classification reads the row's own words; the matched words are shown in each cell's details, so a -wrong class is visible and the rule list in the tool (`CONFIRMATION`) can be corrected. - -Each metric is a ratio with its numerator, denominator and formula on the page. There is no overall percentage: the -panels count different things. The trend chart breaks a line where a metric's formula changed between snapshots. - -## No game data - -The page and the JSON carry counts, pass/fail, error classes and the project's own document text. The corpus panel -stores per-stage numbers only: no shader name, carved file name or path into the game copy. One-line failure details -are kept with each absolute path replaced: a path inside the repository becomes its relative path, any other path -(work folder, home folder, temp folder) becomes ``, file name included, since a file name outside the -repository can be a carved shader's name. diff --git a/docs/psin.md b/docs/psin.md deleted file mode 100644 index 49945614e..000000000 --- a/docs/psin.md +++ /dev/null @@ -1,599 +0,0 @@ -# PSIN metadata containers - -PSIN is a small metadata container used by the game's data and script archives. It appears at the -start of carved zlib streams in `data.rpf` and `script.rpf`; it is not a compiled script program and -it is not a model, texture or audio resource. The archive table of contents is still encrypted, so -the original names are unavailable; PSIN is identified by its own magic. - -## Where it appears - -- `script.rpf` carve: **671 streams** start with `PSIN`. **670 are complete**; one is - the first 64 KiB of a larger record (its first-section offset points past the carved block). -- `data.rpf` carve: **2,281 streams** start with `PSIN` (the same project's carve also reports 1,263 - `RBF0` and 3,132 resource pages). The project's existing `ArchiveReader`/`PsinMetadata` path - validates **1,045 complete PSIN records** in `data.rpf` and **1,012** in `script.rpf` after joining - adjacent 64 KiB blocks. -- `common.rpf` has no PSIN. `anim.rpf`, `navmeshes.rpf` and the BVH archives have no PSIN at stream - starts in the measured samples. - -## Header - -Every measured file begins with the same 16-byte header: - -| Offset | Size | Field | -|---:|---:|---| -| +0 | 4 | `50 53 49 4e` (`PSIN`) | -| +4 | 4 | big-endian absolute offset of the first section (`LSCH`) | -| +8 | 4 | type of the first block-table row (see *Instance data*) | -| +12 | 4 | size of the first block | - -`psin_index.py` reports +8 as `version` and +12 as `table_bytes`. They are the first row of the block table that -starts at +8. The value 22 (`0x16`, a block of 64-bit integers) appears on 1,010 of the 18,640 PSIN streams, nearly -all of them in `script.rpf`. On the other 17,630 the field holds a struct name hash or another type code. - -## Sections - -Sections start at the offset in the header and run to the end of the file. Each section is: - -| Offset | Size | Field | -|---:|---:|---| -| +0 | 4 | ASCII tag | -| +4 | 4 | big-endian **total** size, including this 8-byte header | - -The next section starts at `offset + size`; the last section ends at EOF. A section with size 8 is -empty. The measured tag counts over the 670 complete `script.rpf` records are: - -| Tag | Count | Measured payload | -|---|---:|---| -| `LSCH` | 670 | 464-544 bytes; the type schema (structs and members), decoded below | -| `LENM` | 670 | the schema's enums and their values, decoded below | -| `LSNS` | 670 | block table and 16-byte records; layout decoded below, record contents opaque | -| `LGID` | 670 | empty (8-byte section) | -| `LRSC` | 670 | starts with `0DRP` + version 122; resource page directory link | -| `CHKS` | 670 | file size and a 32-bit checksum | - -The `LSCH` sizes on the measured set are 472-552 bytes including the 8-byte header. `LRSC` is the -link to the resource-page world: its payload begins `30 44 52 50` (`0DRP`), then a little-endian 122, -then the page fields used by the generic RPF pager. `CHKS` carries the file size in big-endian and a -32-bit hash; the tool reports the section, not a verified checksum. - -## `LSCH` and `LENM`: the type schema - -`LSCH` describes the structures of the container's data and `LENM` the enums those structures use. It is a -reflection schema of the kind RAGE's PSO format keeps in `PSCH`, with names reduced to 32-bit hashes. Neither -section carries strings. - -### Corpus - -Measured over **every PSIN stream in every archive** of package 1.0.2.1. Each `.rpf` except `audio.rpf` (raw -AWC, not zlib) was walked whole with the `rpf9_carve.py` stream walker; on `script.rpf` the PSIN-only walk gives -byte-for-byte the same 1,012 streams as `rpf9_carve.py`. Archives with no PSIN stream: `common`, `shaders`, -`textures`, `movies`, `appdata0`, `core_bvh4`, `core_licenses_data`, `core_restofworld001`, -`shared_minigame000_bvh4`, `story000_bvh4`. - -| Archive | PSIN | complete | whole `LSCH` | `LSCH` decoded | whole `LENM` | `LENM` decoded | structs | members | enums | values | -|---|---:|---:|---:|---:|---:|---:|---:|---:|---:|---:| -| `levels` | 6,982 | 6,650 | 6,680 | 6,680 | 6,671 | 6,671 | 51,414 | 296,370 | 13,913 | 178,110 | -| `story000` | 5,348 | 5,075 | 5,101 | 5,101 | 5,097 | 5,097 | 30,684 | 161,449 | 6,840 | 125,837 | -| `data` | 2,281 | 2,135 | 2,108 | 2,108 | 2,104 | 2,104 | 45,896 | 298,356 | 13,814 | 156,999 | -| `story000_script` | 2,309 | 2,118 | 2,160 | 2,160 | 2,156 | 2,156 | 54,683 | 465,992 | 8,587 | 83,740 | -| `script` | 1,012 | 1,009 | 1,009 | 1,009 | 1,009 | 1,009 | 3,879 | 25,763 | 1,009 | 6,054 | -| `packs` | 586 | 489 | 517 | 517 | 515 | 515 | 5,432 | 52,253 | 1,438 | 48,950 | -| `shared_minigame000` | 73 | 70 | 70 | 70 | 70 | 70 | 277 | 1,430 | 56 | 624 | -| `navmeshes` | 22 | 1 | 1 | 1 | 1 | 1 | 3 | 15 | 0 | 0 | -| `anim` | 18 | 10 | 10 | 10 | 10 | 10 | 43 | 200 | 5 | 20 | -| `core_restofworld` | 6 | 5 | 6 | 6 | 6 | 6 | 51 | 323 | 3 | 28 | -| `story000_restofworld` | 3 | 2 | 2 | 2 | 2 | 2 | 9 | 33 | 0 | 0 | -| **all** | **18,640** | **17,564** | **17,664** | **17,664** | **17,641** | **17,641** | **192,371** | **1,302,184** | **45,665** | **600,362** | - -- 157 truncated streams still hold a whole `LSCH`; they are counted. 919 streams are cut off before their first - section and hold neither. -- 57 complete streams (54 in `data`, 2 in `packs`, 1 in `anim`) use the PSO-style `PMAP`/`PSCH`/`PSIG` - sections instead and have no `LSCH`. -- 6,421 `LENM` sections are empty (8 bytes): those schemas use no enum. -- `LSCH` sizes, header included: 472-552 bytes on `script`, 2,440-7,464 on `story000_script`, 56-17,496 - on `data`. -- `psin_index.py` reports no schema error on any of them (see the checks under *Tool*). -- Distinct name hashes: 3,175 structs, 10,943 members, 664 enums, 13,946 enum values. - -### Shape of both sections - -Each section stores **all headers first, then all elements**, in header order. The header count is not stored: -it is the one count *k* for which *k* headers plus the elements they announce fill the payload exactly. That -count exists and is unique on 17,664 of 17,664 `LSCH` and 17,641 of 17,641 `LENM` sections. - -### `LSCH` struct header (32 bytes) - -| Offset | Size | Field | Confidence | -|---:|---:|---|---| -| +0 | 4 | name hash (case-sensitive joaat) | high: see *Hashes* | -| +4 | 4 | layout signature | high: see below | -| +8 | 1 | flags: 0, 0x0c, 0x1c or 0x24 on 150,352 / 34,361 / 89 / 7,569 structs | field: high; meaning: unknown | -| +9 | 1 | log2 of the alignment, 0-4 | medium: the size is a multiple of 2^n on 192,371 of 192,371 | -| +10 | 2 | 0 on every struct | high | -| +12 | 4 | 0 on every struct | high | -| +16 | 8 | fill, `aa` × 8 on every struct | high | -| +24 | 4 | byte size of the struct | high: every member offset is below it | -| +28 | 2 | 0 on every struct | high | -| +30 | 2 | member count | high: the counts fill the section exactly | - -The **layout signature** depends on the layout, not the name. A struct name hash that appears with two -signatures always has two layouts, and the other way round (3,175 of 3,175 names; 49 names have two layouts). -The 199 signatures that occur under more than one name give the same layout (size, offsets, types, sub-codes -and indices) under every name. Its hash function is not known. - -### `LSCH` member (16 bytes) - -The members follow the struct headers, each struct's members in a row. - -| Offset | Size | Field | Confidence | -|---:|---:|---|---| -| +0 | 4 | name hash (case-sensitive joaat), or `0x100` for an array element descriptor | high | -| +4 | 4 | byte offset in the struct (0 for an element descriptor) | high: below the size on 1,302,184 of 1,302,184 | -| +8 | 1 | type code | field: high; per-type meaning: see below | -| +9 | 1 | sub-code: non-zero on every member of types 0x4d and 0x4f, 0 on all others | field: high; meaning: unknown | -| +10 | 2 | element index: for an array (type 0x5c), the position in this struct's member list of its `0x100` element descriptor | high: 49,375 of 49,375 arrays point at a descriptor | -| +12 | 4 | reference hash: a struct or enum name for the types below, else 0 | high for 0x05 and the enum types | - -Type codes, with the measured references and the *gap*: the distance to the next member or to the end of the -struct, most common value first. The gap is an upper bound on the member's size, so every reading below is a -hypothesis until a struct is matched against its instance data. - -| Type | Members | Reference | Gap | Reading | -|---:|---:|---|---|---| -| 0x05 | 192,944 | a struct name: 155,495 in the same file, 36,277 in another file, 1,172 not found | varies | embedded struct (high) | -| 0x40 | 2,311 | the length in bytes (256, 128 or 16; equal to the gap on every member measured) | 256, 128 | `char[ref]` (high) | -| 0x5c | 49,375 | none; element index instead | 16 | array `{u32 count, u32 capacity, pointer}` (high) | -| 0x60 | 3,887 | an enum (3,866 same file, 21 other file) | 1 | 8-bit enum (medium) | -| 0x62 | 40,024 | an enum (39,758 / 253; 13 not found) | 4 | 32-bit enum (medium) | -| 0x63, 0x64 | 47, 85 | an enum | 1, 2 | 8/16-bit enum variants (low) | -| 0x65 | 16,217 | an enum (16,099 / 115; 1 not found) | 8, 4 | enum-indexed bit set (low) | -| 0x68 | 98 | an enum | 8 | 64-bit enum (medium) | -| 0x50, 0x53 | 20,777, 367 | the element count in the low 16 bits | varies | fixed array in place (high) | -| 0x71, 0x73, 0x75 | 114,700, 111, 12,888 | the key and value element indices (`ref & 0xffff`, `ref >> 16`) | 24, 16, 16 | maps (high), see *Instance data* | -| 0x76, 0x77, 0x54, 0x5a | 4, 2, 1, 3 | varies | varies | 0x54: inline array; the others are not decoded | -| 0x01, 0x11 | 93,811, 14,761 | - | 1 | 1-byte scalars (medium) | -| 0x13, 0x20 | 7,372, 7,356 | - | 2 | 2-byte scalars (medium) | -| 0x14, 0x15, 0x21, 0x4a | 35,088, 41,144, 110,948, 194,191 | - | 4 | 4-byte scalars (medium) | -| 0x07, 0x08, 0x30, 0x42 | 52,656, 2,232, 1,112, 1,084 | - | 8 | struct pointer, 64-bit int, 2×f32, string pointer (high) | -| 0x4d, 0x4f | 152,193, 15,076 | - (sub-code set) | 8, 4, 16 | 4- and 8-byte values, read as u32/u64 hashes (medium: size measured, meaning not) | -| 0x0d, 0x31, 0x33, 0x34, 0x52 | 582, 7,750, 50,665, 6,072, 50,156 | - | 16 | 16-byte vectors; 0x52 is the list `{pointer, u16 count, u16 capacity}` (high) | -| 0x36 | 402 | - | 64 | 64-byte value (medium) | - -The rest (0x0c, 0x10, 0x12, 0x16, 0x17, 0x32, 0x44, 0x4b) occur 3-1,551 times each. `psin_index.py --schema` -lists every member. The "(high)" readings were checked against the instance data in the next section. The gap -alone is only an upper bound. - -### `LENM` enum header (24 bytes) and value (16 bytes) - -| Offset | Size | Field | Confidence | -|---:|---:|---|---| -| +0 | 4 | name hash; a member of the same file's `LSCH` refers to every enum (45,665 of 45,665) | high | -| +4 | 4 | layout signature: it changes exactly when the value list changes (664 of 664 names; 9 have two lists) | high | -| +8 | 8 | fill, `ee` × 8 on every enum | high | -| +16 | 4 | value count | high: the counts fill the section exactly | -| +20 | 4 | 0 on every enum | high | - -The values follow the enum headers, each enum's values in a row: - -| Offset | Size | Field | Confidence | -|---:|---:|---|---| -| +0 | 8 | signed value: 0, 1, 2, ... in 38,870 of 45,665 enums; 1,270 enums have a negative value | high | -| +8 | 8 | name hash (case-sensitive joaat) in the low half; the high half is 0 on every value | high; unique within each enum (45,665 of 45,665) | - -### Hashes - -Names are the **case-sensitive joaat** (`world_names.joaat(text, case_sensitive=True)`), as for the engine -member hashes in [world_names.md](world_names.md). Candidates: every identifier-like string in the inflated -`data.rpf` and `script.rpf` streams (3,386,171 strings), against the 32,313 distinct hash values above: - -| Function | struct names | member names | enum names | enum value names | signatures | -|---|---:|---:|---:|---:|---:| -| joaat, case-sensitive | 26 / 3,175 | 733 / 10,943 | 0 / 664 | 1,023 / 13,946 | 1 / 3,750 | -| joaat of the lower-cased string only | 0 | 8 | 2 | 4 | 0 | -| control: CRC-32; CRC-32 xor a constant | | | | | 28; 30 over all | - -1,782 name hits against a chance level of about 30 confirm the function. The low coverage only means that the -engine's type and field names are mostly not in the data files. The one signature hit is at chance level: the -signatures are not joaat of a name. No name or hash from the game is committed here. - -### Links to the rest of the container - -- Struct references (type 0x05) resolve in the same `LSCH` for 155,495 of 192,944 members and in another - file's `LSCH` for 36,277 more. Enum references (types 0x60, 0x62-0x65, 0x68) resolve in the same file's - `LENM` for 59,945 of 60,354 and in another file for 395 more. -- The region between the 8-byte header and `LSCH` is the instance data these structs describe: a block table - and its data blocks, read from the root block that `LRSC` names. See *Instance data*. -- `LSNS` values occur nowhere else in the container (see *`LSNS`*). - -## `LSNS` - -`LSNS` is a block table followed by the blocks it lists: - -| Offset | Size | Field | -|---|---|---| -| +0 | 4 | little-endian block count n | -| +4 | 8 × n | per block: u32 kind, u32 byte count | -| +4 + 8n | | the n blocks back to back | - -The byte counts fill the section exactly, and every block is a whole number of 16-byte records. A section with -n = 0 is 12 bytes long (tag, size, count) and is followed directly by `LGID`. The kind's high byte is 1 or 2 and -reads like the word width (4- or 8-byte words), but the 16-byte rule holds for both. The low byte varies. - -Measured with `psin_index.py` over every complete container in five carved archives: - -| Archive | `LSNS` sections | Empty | 16-byte records | Errors | -|---|---:|---:|---:|---:| -| `data.rpf` | 2,083 | 886 | 164,512 | 0 | -| `script.rpf` | 1,009 | 0 | 56,382 | 0 | -| `story000_script.rpf` | 2,118 | 0 | 285,674 | 0 | -| `core_restofworld.rpf` | 5 | 0 | 605 | 0 | -| `story000_restofworld.rpf` | 2 | 0 | 1,975 | 0 | -| **Total** | **5,217** | **886** | **509,148** | **0** | - -Blocks by kind across these sections: `0x101` 4,200, `0x11c` 2,118, `0x207` 1,235, `0x10f` 26, `0x204` 14, -`0x113` 7, and 1-2 each of `0x102`, `0x205`, `0x208`, `0x109`, `0x11e` and `0x211`. Section sizes run from 12 to -36,756 bytes (median 836). - -### The records - -The record contents are opaque. A wider pass over 16,169 containers that have an `LSNS` block (the archives -above plus `levels.rpf`, `story000.rpf`, `packs.rpf` and `anim.rpf`; 22,101 blocks, 1,957,739 records) measured: - -- **Uniform bytes.** 8.0 bits/byte over the pooled records, and no record byte position favours any value. - (The per-section 5.2-8.0 bits/byte in [restofworld.md](restofworld.md) is the small-sample limit of short - sections.) Records are not version-4 GUIDs: no fixed version or variant nibble. -- **No references.** No 32-bit or 64-bit record word occurs anywhere else in its container, `LSCH` included (a - 300-container sample, 107,594 words). Instance data stores its own hashes directly (member types `0x4a`-`0x4f`). -- **No name hash.** Against up to 3.3 million harvested identifiers and model names, each as is, lower-cased and - upper-cased, the records match none of these functions. Each search was checked against a planted known value. - - 32-bit words: joaat, FNV-1, FNV-1a, CRC-32, MurmurHash3-32 and xxHash32 all stay at the level of a salted - control (about 1,350 chance hits each; this test used a third of the dictionary, 1.0 million words, - against 5.8 million distinct 32-bit words). - - 64-bit words: MurmurHash3 x64 (either half; the function behind the 64-bit map keys in - [world_names.md](world_names.md)), xxHash64, XXH3-64, FNV-1 and FNV-1a 64 have 0 matches. - - Whole records: MD5, XXH3-128, BLAKE2b-128, truncated SHA-1 and SHA-256, and full MurmurHash3 x64 128 have - 0 matches. -- **Repeats.** 18,692 of the 22,101 blocks are distinct. Beyond repeated whole blocks, 99,071 records still repeat - across different blocks. - -Uniform bytes in exact 16-byte units that repeat record by record fit a deterministic 128-bit block cipher. They -also fit 128-bit hashes of inputs outside the tested dictionary and functions. Which one it is has not been -established. Per the project rules, no decryption is attempted. - -## `PMAP`, `PSCH`, `PSIG` and `STNS`: the PSO-style variant - -The 57 complete `PSIN` streams without `LSCH` (54 in `data.rpf`, 2 in `packs.rpf`, 1 in `anim.rpf`) replace -`LSCH`/`LENM`/`LSNS`/`LRSC` with a big-endian PSO schema chain: `PMAP`, `PSCH`, `PSIG`, optional `STFN`/`STDN`, `STNS` -and `CHKS`. Measured with `tools/psin_psch.py` over all **54** containers in `data.rpf` (`54/54` valid): - -- **Header and instance region:** bytes `+0x08..+0x0F` hold `pppppppp` (`0x70` x 8) and instance data blocks sit at - `+0x10..first_section` (in contrast to `LSCH` containers, which place the block table at `+8`). -- **`PMAP` (287 blocks across 54 files):** starts with a 16-byte big-endian header (`u32 root_block_id`, `u16 flags`, - `u16 0`, `u16 block_count`, 6-byte `pppppp` fill), followed by `block_count` x 16-byte rows `{u32 name_hash, u32 offset, - u32 0, u32 length}`. On **54 of 54**, blocks begin at `0x10` and end at exact `first_section`; 237 blocks reference a - struct in `PSCH` (`237/237` have `length % struct_size == 0`) and 50 are anonymous (`0x1`: 41, `0xc`: 7, `0x8`: 1, - `0x6`: 1). -- **`PSCH` (`689` structs / `69` distinct, `3,250` members / `500` distinct, `146` enums / `17` distinct, `662` values):** - `u32be entry_count` followed by `entry_count` directory pairs `(u32be name_hash, u32be section_offset)`. Kind `0` - entries are structs (`u8 0`, `u8 flags`, `u16be member_count`, `u32be byte_size`, `u32be 0`, then `12`-byte big-endian - members `{u32 hash, u8 type, u8 sub, u16 offset, u32 ref}`); kind `1` entries are enums (`u8 1`, `u8 flags`, `u16be - value_count`, then `16`-byte values `{u32 hash, u32 0, i64be value}`). Every array member (`0x0d`, 226/226) and map - member (`0x10`, 3/3 key/value pairs) points at `0x100` element descriptors inside its struct; all 185 enum members - (`0x0e`) resolve locally, and 718 struct members (`0x0c`) hold `671` local hashes, `11` zero references, `33` - cross-file `data.rpf` references and `3` external references. -- **`PSIG` and `STNS`/`STDN`/`STFN`:** `PSIG` stores `entry_count` big-endian `u32` layout signatures (`83` distinct). - `STNS` mirrors `LSNS` as a little-endian `u32 block_count` table of `(u32 kind, u32 bytes)` pairs and 16-byte-aligned - records (`867` total across `54` blocks) padded with zeros to a 16-byte payload boundary - (`align16(4 + 8 * block_count + data_bytes)` on all 54 containers: 4 zero bytes for `1`-block sections and 12 zero - bytes for `0`- and `2`-block sections). Where present, `STDN` (`2/2`) matches the prefix of `STNS`'s block data - byte-for-byte. - -```text -python -I tools/psin_psch.py [--carve-dir DIR] [--json FILE] -``` - -`tests/test_psin_psch.py` builds synthetic `PMAP`/`PSCH`/`PSIG`/`STDN`/`STNS` containers and tests block validation, -member descriptor checks, carve-directory filtering and `--json` collision refusal. - -## Instance data - -The region between the 8-byte header and `LSCH` is a block table followed by its data blocks. The schema in -`LSCH`/`LENM` describes the blocks, and `LRSC` names the root. `tools/psin_data.py` reads it. - -### Block table and blocks - -| Offset | Size | Field | -|---:|---:|---| -| +0 | 4 | block type: a struct name hash from `LSCH`, a member type code below 0x100 (for example `0x10` for string bytes, `0x16` for 64-bit integers) or `0x100 + n` for an anonymous block | -| +4 | 4 | data size in bytes | -| +8 | 8 | fill, `aa` × 8 | - -The rows start at +8. The table therefore ends 8 bytes short of a 16-byte boundary, and those 8 bytes are `70` × 8 -(`pppppppp`) on 17,507 of 17,507 files. The blocks follow in table order, each padded to 16 bytes, and the last one -ends exactly at the first section (17,507 of 17,507). Blocks are numbered from 1. - -The root is the u32 at +0x10 of the `0DRP` header in `LRSC`. It is a struct block on 17,507 of 17,507 files. - -A **pointer** is a u64. Its low 20 bits are the block number, with 0 meaning null, and the bits above are the byte -offset into that block. - -### Layouts - -The tables below give the layouts the instance data confirms. Arrays name their element with the member's element -index, as in `LSCH`. Maps name a key element at `ref & 0xffff` and a value element at `ref >> 16`. - -| Type | Bytes | Layout | -|---:|---:|---| -| 0x07 | 8 | pointer to a struct block; the block's type is the struct | -| 0x42 | 8 | pointer to a NUL-terminated string in a type-`0x10` block | -| 0x44 | 16 | string with an in-place form: when bit 7 of byte 15 is set, its low 7 bits are the length of the string in bytes 0..14; otherwise bytes 0..7 are a string pointer as for 0x42 | -| 0x40 | ref | `char[ref]`, NUL-padded | -| 0x50, 0x53 | ref × element | `ref & 0xffff` elements in place | -| 0x54 | 8 + capacity × element | `{u32 capacity, u32 count}`, then the elements in place | -| 0x5c | 16 | `{u32 count, u32 capacity, u64 pointer}` | -| 0x52 | 16 | `{u64 pointer, u16 count, u16 capacity, u32 0}` | -| 0x71 | 24 | `{u64 1, u64 pointer, u16 count, u16 capacity, u32 0}`: `count` (key, value) pairs sorted by key | -| 0x75 | 16 | `{u32 groups, u32 count, u64 pointer}`: `groups` groups of 16 control bytes followed by 16 (key, value) slots. A control byte with bit 7 set marks an empty slot. | -| 0x73 | 16 | `{u32 capacity, u32 count, u64 pointer}`: `capacity` (key, value) slots, where key 0 marks an empty slot | -| 0x60, 0x63 / 0x64 / 0x62, 0x65 / 0x68 | 1 / 2 / 4 / 8 | enum value or enum bit set | - -**Alignment.** In a (key, value) slot the value starts at the key size rounded up to the value's alignment, and the -slot size is rounded up to the larger of the two alignments. A struct aligns to 2^(+9 of its header). The 16-byte -vectors (0x0c, 0x0d, 0x31, 0x33, 0x34, 0x35) and 0x36 align to 16, and 0x32 aligns to 4. Every other type aligns to -its size, capped at 8. With these rules the 24-byte 0x71 value sits at +8 after a u32 key, in a 32-byte pair. - -### Measured coverage - -The measurement walks every value reachable from the root, through embedded structs, pointers, arrays and maps, -and marks each byte it reads. - -| Archive | PSIN | with `LSCH`+`LRSC` | tables fill the region | fully reached | block bytes | reached | -|---|---:|---:|---:|---:|---:|---:| -| `levels` | 6,982 | 6,650 | 6,650 | 6,650 | 43,591,021 | 43,591,021 | -| `story000` | 5,348 | 5,075 | 5,075 | 5,075 | 36,404,701 | 36,404,701 | -| `data` | 2,281 | 2,081 | 2,081 | 2,079 | 14,773,021 | 14,772,189 | -| `story000_script` | 2,309 | 2,118 | 2,118 | 2,118 | 30,677,748 | 30,677,748 | -| `script` | 1,012 | 1,009 | 1,009 | 1,009 | 1,323,348 | 1,323,348 | -| `packs` | 586 | 487 | 487 | 486 | 1,924,622 | 1,923,342 | -| `shared_minigame000` | 73 | 70 | 70 | 70 | 227,855 | 227,855 | -| `navmeshes` | 22 | 1 | 1 | 1 | 28,688 | 28,688 | -| `anim` | 18 | 9 | 9 | 6 | 102,040 | 86,344 | -| `core_restofworld` | 6 | 5 | 5 | 5 | 59,136 | 59,136 | -| `story000_restofworld` | 3 | 2 | 2 | 2 | 5,632 | 5,632 | -| **all** | **18,640** | **17,507** | **17,507** | **17,501** | **129,117,812** | **129,100,004** (99.986%) | - -The other 1,133 streams are not counted. 1,076 are cut off (see *Corpus*), and 57 use the `PMAP`/`PSCH` form, which -has no `LSCH`. - -Checks over the 17,507 containers: - -- **Pointers.** 238,681 struct pointers (0x07) and 81,680 string pointers resolve; none points outside its block - table or past the end of its block. 4,305 more 0x44 strings are stored in place, and every one has a NUL at its - stated length. -- **Arrays.** 0x5c and 0x52 arrays resolve 177,675 and 628,888 times. Count ≤ capacity holds on all 1,352,211 arrays - and maps that store both. The target block's type is the element type (or struct) on 806,520 of them. The other - 43 are arrays of enums stored in anonymous `0x100+n` blocks. 24,949 more arrays name an element struct that is - not in their own file's `LSCH`, and all 24,949 are empty. -- **Maps.** 0x71: the first word is 1 on 159,409 of 159,409. The 69,954 non-empty maps hold 267,161 pairs, and - 69,951 of those maps have ascending keys. 0x75: on all 16,035 non-empty tables the group count is a power of two - and the used control bytes equal `count` (92,903 slots). In `data`, `levels` and `story000_script`, the control byte of every - used slot with a u32/u64 hash key (0x4a, 0x4d, 0x4f) is the key's low 7 bits. It is not for other key types. When the target block is larger than `groups` groups, the rest holds further tables. 0x73: on 167 of 167 - the non-zero keys equal `count`, and the capacity is a power of two. -- **Enums.** 533,100 of 533,927 enum values are listed in their `LENM` enum, and 827 are not. A 0x62 value is a - 32-bit field, and `LENM` lists values on both sides of the sign bit for it: of the 33,564 that are negative as `s32`, 2,767 - are listed only as negative numbers and 30,797 only as values of 2^31 or more, so a value counts as listed under either - reading. Reading it only as `s32`, as the first version of this tool did, leaves 31,624 unlisted. 235,486 of 235,489 bit sets (0x65) use only bits their enum defines. 1,431 - values name an enum that is not in their file's `LENM`. -- **Not decoded.** 0x5a (81 members), 0x76 (12) and 0x77 (1) are counted and skipped. They are the only reason the - 6 partly reached containers are partial: the 0x5a and 0x76 members point at `f32` and u32-hash blocks that - nothing else reaches. - -These numbers cover layout only. What each struct means is not decoded here. The engine names behind the schema -hashes are covered under *Hashes*, and the resource names behind hash values under *Name hashes in the data*. - -### Tool - -```text -python -I tools/psin_data.py [--json] [--limit N] -python -I tools/psin_data.py --dump -``` - -The default output is the counts above, for one file or every `.bin` in a carve directory. A single file that does -not start with the `PSIN` magic is one `ERROR:` line and exit 2; inside a directory such a file is skipped, since a -carve folder holds other streams too. `--dump` prints one container's decoded tree (hashes as hex) on stdout, for -local inspection only. It writes no file and must not be pasted into an issue or a pull request. -`tests/test_psin_data.py` builds containers from invented names and covers every layout above, the end padding, a -bad fill, pointers out of range, an unlisted enum value, a skipped type and the CLI. - -### Name hashes in the data - -Members of type `0x4a`, `0x4d` and `0x4b` hold a u32 hash and type `0x4f` a u64 hash. Many of these values name other -resources: drawables, fragments and maps. They use the two rules that [world_names.md](world_names.md) found for -placement maps: - -| Member type | Value | -|---|---| -| `0x4a`, `0x4d`, `0x4b` (u32) | joaat of the lower-cased name | -| `0x4f` (u64) | low 64 bits of MurmurHash3 x64 128, seed 0, over the name's bytes | - -`tools/psin_names.py` walks every container with `psin_data.py`, collects each hash value with the struct and member -that hold it, and looks it up in a dictionary of names you already have: `rpf9_names.py` JSON (the `.#dr`/`.#ft`/`.#dd` -suffix dropped) or plain name lists. Each run also hashes every name with `#zq` appended, through the same rules. Those -names cannot be right, so their matches show how many real matches chance alone would give. - -Measured on the 1.0.2.1 package (2026-11-22). The data was 18,640 `PSIN` streams carved whole from 11 archives, so the -container counts differ slightly from those above. The dictionary was 341,954 distinct names from `rpf9_names.py` over -the same archives with default options; 317,257 of them come from `levels.rpf`. - -| Archive | Containers | With a resolved name | u32 resolved | u32 control | u64 resolved | u64 control | -|---|---:|---:|---:|---:|---:|---:| -| `data.rpf` | 2,200 | 116 | 9,939 | 52 | 28,905 | 0 | -| `levels.rpf` | 6,951 | 957 | 7,310 | 51 | 34,309 | 0 | -| `packs.rpf` | 543 | 335 | 2,755 | 2 | 10,190 | 0 | -| `script.rpf` | 1,012 | 31 | 189 | 0 | 0 | 0 | -| `navmeshes.rpf` | 21 | 1 | 95 | 0 | 209 | 0 | -| `anim.rpf` | 10 | 1 | 3 | 0 | 0 | 0 | -| `story000.rpf` | 5,316 | 2,648 | 403 | 25 | 90,612 | 0 | -| `story000_script.rpf` | 2,270 | 1,264 | 19,894 | 169 | 23,612 | 0 | -| `shared_minigame000.rpf` | 73 | 2 | 2 | 0 | 0 | 0 | -| `core_restofworld.rpf`, `story000_restofworld.rpf` | 8 | 0 | 0 | 0 | 0 | 0 | -| **Total** | **18,404** | **5,355** | **40,590** | **299** | **187,837** | **0** | - -- **The u64 rule is general.** 187,837 of the 443,968 non-zero u64 hash values resolve, with no control match. - They are spread over 119 of the 223 u64 fields, so the MurmurHash3 keys are not specific to placement maps. The - other u64 fields match nothing in this dictionary. -- **The u32 rule is precise in name fields.** 40,590 matches against 299 for the control, about 0.7% expected false. - 122 of the 306 fields with a match have at least 20 resolved values and a control under 1% of them. Those fields - hold 227,504 of the 228,427 resolved values (u32 and u64 together), with no control match. The other 184 fields - mix a few real names with chance hits on non-name hashes. -- **Coverage.** 5,355 of 18,404 containers (29%) reference at least one known resource, and 23,049 distinct names - occur. Only 5,495 of the matches are in the placement fields that `world_names.py` already resolves. -- The remaining values are not names in the dictionary. They may be names of other kinds (sounds, animations, - scenarios), or resources whose own name string `rpf9_names.py` does not find. - -```text -python -I tools/psin_names.py --names [--names ...] - [--json] [--fields N] [--refs OUT.tsv] [--limit N] -``` - -The text output gives the totals and the fields with the most resolved values, as hashes. `--json` adds the whole -field table. `--refs` writes one row per resolved value: file, struct, field, type, value and name. These are game names, -so keep them in your local work folder; only the counts belong in git, issues or pull requests. On the data above the -run takes about 50 s. `tests/test_psin_names.py` builds containers from invented names. - -#### Vehicle names in the navmesh PSIN map - -The version 256 PSIN at `navmeshes.rpf` offset `0x1749fe000` has a root map of type `0x73`. Its pointer -resolves to an anonymous `0x100` block of 28,672 bytes. The schema gives a `0x4a` key at slot offset -`+0x00` and a 48-byte struct value at `+0x08`, for a stride of 56 bytes. The map declares 512 slots and -209 entries. Counting distinct nonzero keys gives 209. - -On the 1.0.2.1 package, compare the lower-case joaat hashes of `ModelName` and the nonempty -`ModDefs/Item` names in the 32 `CVehiclePoints` documents in `common.rpf` with every occupied slot. -Of 31 distinct model names, 25 match the map key. Of 55 distinct part names, 20 match `0x4a` members -in the value: 6 at slot `+0x18`, 2 at `+0x1c`, 4 at `+0x28`, and 8 at `+0x34`. Appending `#zq` -to the model names gives zero key matches. All the original matches lie in the instance block before -the first section. The container's 493 `LSNS` records have zero matches for either set of hashes. -The map identifies vehicles and parts in the container. Which entry refers to each of the 161 -local-space navmeshes remains open. - -## What it does not give - -- No plaintext script code, function names or string table. `LSNS` has a decoded block layout, but its - 16-byte records are uniformly random and match no tested name hash (see *`LSNS`*). -- No station/track names or file paths. Model names occur only as hashes; a name list from elsewhere resolves - them (see *Name hashes in the data*). The archive TOC is still the only source for original paths. -- No names. `LSCH` and `LENM` give the schema as 32-bit name hashes only; resolving them needs a name - list from elsewhere (see *Hashes*). - -## Tool - -```text -python -I tools/psin_index.py [--json] [--schema] [--limit N] -``` - -`--limit N` stops after N PSIN containers and must be at least 1 (0 or a negative value is refused with exit -code 2). Leave it out to index every container. - -- `parse(blob)` returns the magic, version, table size, the ordered section list - (`tag`, `offset`, `size`, `payload`) and a `complete` flag with the first structural error. When the - `LRSC` payload starts with `0DRP`, the `0DRP` version is reported; `CHKS` contributes the file size - and a 32-bit checksum. Text output and the summary include those fields. -- `decode_lsch(payload)` and `decode_lenm(payload)` return the structs (with members) and the enums (with - values) laid out above, and raise `ValueError` when no header count fills the payload. `parse()` adds - `structs`, `members`, `enums`, `enum_values` and `schema_error` (an undecodable section, a member past its - struct's size, or an array whose element index is not an element descriptor) to every record; with - `--schema` (or `parse(blob, schema=True)`) the decoded schema is included, hashes as hex. Every record - then has the same `schema` entry, `{structs, enums, lsch, lenm, reason}`, also when the walk stopped before - reaching the sections (a truncated stream): `lsch`/`lenm` say whether each was decoded and `reason` why - not ("" when both were); text mode prints the reason as a `schema:` line. -- `collect(src)` scans a single file or every `.bin` in a carve directory; non-PSIN files are - skipped. -- Text output prints one line per container and a tag summary; `--json` writes `{files, summary}`. -- The parser validates the first-section offset, each tag's printable range, each section size and - the exact EOF; a 64 KiB split is reported as incomplete rather than guessed. - -`tests/test_psin_index.py` covers complete records, an empty section, a bad first offset, a zero-size -section, truncated data, trailing bytes and the JSON CLI, and the `LSCH`/`LENM` layouts, empty sections, -a count that fits nothing and both schema checks. It uses synthetic headers and joaat hashes of invented names -only. - -### Viewing a container in ImHex - -[tools/imhex/psin.hexpat](../tools/imhex/psin.hexpat) is a pattern for the [ImHex](https://imhex.werwolv.net/) hex -editor that lays out one container as this page describes it: -- the header, the instance-data block table with its `pppppppp` end, and the blocks, as raw bytes; -- the section chain; -- the `LSCH` struct headers and members, and the `LENM` enums and values, with the header count found by the same - fill-exact rule as `psin_index.py`; -- the `LSNS` block table and its opaque 16-byte records; -- the `LRSC` `0DRP` version and root block, and the `CHKS` file size. - -A section that runs past the end of a truncated stream is shown as raw bytes. `tests/test_imhex_patterns.py` builds a -synthetic container, checks it with `psin_index.py` and `psin_data.block_table`, and when ImHex is installed compares -the pattern's output with both. - -## Non-PSIN object-tree table in `script.rpf` - -Besides its 1,012 `PSIN` containers (1,015 streams, 3,477,872 inflated bytes), `script.rpf` contains one large non-`PSIN` -binary container carved at offset `0x53000` (`42` contiguous deflate streams: 41 x 65,536 + 15,408 = **2,702,384** -inflated bytes / `0x293C30`, 461,333 stored bytes, 43.7% of `script.rpf`'s inflated output). It is not `PSIN`, `RBF0` -or `0DRP`, and carries no strings: it is a dense 483-tree forest serialized in preorder with `0x71717171` (`'qqqq'`) -relocatable pointers, measured with `tools/script_qtable.py` on package 1.0.2.1. - -### Layout and header (`0x000000..0x293C2F`) - -| Region | Offset | Size | Layout | -|---|---:|---:|---| -| Header | `0x000000` | 40 B | ten `u32` words: `record_count = 30,683` (`0x000077DB`) at `+0x14`; all other nine words `0` | -| Offset table | `0x000028` | 245,464 B | `30,683` strictly ascending, 16-byte-aligned `u64` offsets (`0x03BF00` to `0x293C00`) | -| Record pool | `0x03BF00` | 2,456,880 B | `30,683` 16-byte-aligned records (`32` to `6,704` bytes), ending at exact EOF (`0x293C30`) | - -Each record `i` begins with an 8-byte prefix before its body at `offsets[i] + 8`: - -- **`+0x00` `u32 root_key_hash`**: non-zero on **483** records (`483` distinct values) and `0` on the other **30,200** - records. -- **`+0x04` `u32 root_flags`**: `0` on all 30,200 non-root records; on the 483 roots, `0xFFFF0000` (385), `0` (86) or - `(1..8) << 16` (12). - -### Relocatable pointers and tree bijection - -Every 8-byte-aligned `u64` word from `+0x08` onward whose high 32 bits equal `0x71717171` (`'qqqq'`) is an internal -pointer whose low 32 bits equal `offsets[target] + 8` (the start of record `target`'s body): - -- **30,200 of 30,200** `0x71717171` pointers resolve to a valid record (`0` unresolved, `0` outside the pool). -- **Exact root bijection:** the **483** records with `root_key_hash != 0` are the exact **483** records with - in-degree `0`; all **30,200** records with `root_key_hash == 0` have in-degree `1`. -- **Contiguous preorder forest:** all **30,200** edges point strictly forward (`target > source`, `0` back-edges or - cycles), remain inside their root's contiguous index slice `[root_k, root_{k+1})` (`0` cross-tree edges), and match - strict depth-first preorder in stored pointer-field sibling order across all **30,683** positions. Tree sizes range - from `1` to `1,131` nodes (median `53`, depths `0..9`). - -### Array and struct records - -| Kind | Count | Header at `+0x08` | Notes | -|---|---:|---|---| -| Array records | 10,294 | `+0x08 = 0x14`, `+0x0C = 0`, `+0x10 = +0x14 = count` (`0..220`), `+0x18 = stride`, `+0x1C = flags`, `+0x20 = 0` (`u64`), `+0x28 = element_type_hash` (35 distinct, none 0), `+0x2C = 0` | Elements start at `+0x30`; `align16(48 + count * stride) == len(rec)` holds on **10,294 of 10,294**. `flags = 0` (8,211 value/struct arrays, strides `4, 8, 12, 16, 20, 24, 32, 48, 64, 128`) and `flags = 0x10000` (2,083 pointer arrays, all stride `8`, holding 7,297 `0x71717171` pointers). | -| Typed struct records | 20,389 | `+0x08 = struct_type_hash` (66 distinct hashes), `+0x0C = 0` on all 20,389 | Sizes `32` B (17,106: 12,332 wrapper nodes pointing at `+0x10` to `i + 1` with `+0x18 = 0`, 3,540 single-pointer at `+0x18`, 3 two-pointer, 1,231 leaves), `48` B (1,642: 1,641 two-pointer, 1 leaf) and `64` B (1,641 leaves). | - -```text -python -I tools/script_qtable.py [--root-hash HEX] [--type-hash HEX] [--json FILE] -``` - -Accepts an `rpf9_carve.py` carve directory (`script`), a `script.rpf` archive or a joined `.bin` payload. -Default stdout and `--json` output emit aggregate counts, histograms and structural invariant checks only; `--root-hash` -and `--type-hash` report local tree/type counts in hex. `tests/test_script_qtable.py` covers synthetic multi-tree parsing, -64 KiB stream reassembly across a carve folder, pointer validation and output collision guards. A target that does not -exist, or that cannot be read, stops the tool with one `ERROR:` line and exit 2 before anything is parsed; a readable -file that is not an object-tree payload is exit 1, the scan's verdict, and a `--json` file that cannot be written is -exit 2 as well. - -## Limits - -- The 64 KiB split is not joined automatically. A caller that has the archive order can join adjacent - blocks first; the tool then parses the complete container. -- `LSNS` record contents and the `CHKS` payload are opaque to this tool; only the `LSNS` block layout is read. `LSCH` and `LENM` are decoded as above, and the instance - data by `tools/psin_data.py`. Struct, member and enum names stay 32-bit hashes, and most of them have no known - name. -- No game data, names, hashes or payloads are committed. The carve directories are local. diff --git a/docs/pso_cache.md b/docs/pso_cache.md deleted file mode 100644 index 1d3d448c5..000000000 --- a/docs/pso_cache.md +++ /dev/null @@ -1,242 +0,0 @@ -# PSO/shader cache - -One cache blob was found in the package data, stored as a single resource in the data area of a top-level RPF9 -archive. It is a chain of 4,205 adjacent zlib streams: 4,204 full 64 KiB streams and a 27,436-byte last one, with -31,437 bytes of zero padding between the streams. Concatenating the inflated bytes in archive order gives -**275,540,780 bytes** (0x106C6B2C); the first stream starts at archive offset 0x10579000 and the chain is the last -resource in the archive. This page describes that file; `tools/psocache_inspect.py` checks a carved copy of it. - -The blob is little-endian. In the tables, *measured* means the field's value and the region arithmetic were checked -on this file. *Unproven* means the field is only located and described, not decoded. - -## Header - -The header is 0x80 bytes; the first 0x70 record of the next region starts exactly at 0x80. - -| Offset | Size | Value measured | Status | -|---:|---:|---:|---| -| 0x00 | 4 | `50 53 00 09` | magic `PS\0\x09`, measured | -| 0x04 | 10 | NUL-terminated ASCII string | meaning unproven | -| 0x24 | 11 | NUL-terminated ASCII string | meaning unproven | -| 0x48 | 8 | 8 bytes | 8-byte value, meaning unproven | -| 0x50 | 4 | 25,471 | count of the 0x70-byte records, measured; the "graphics PSO" role is inferred from the record shape, unproven | -| 0x54 | 4 | 2,693 | count of the 0x18-byte records, measured; the "compute PSO" role is likewise inferred, unproven | -| 0x58 | 4 | 54,576 | meta-index entries, measured (54,576 × 8 ends where the next region starts) | -| 0x5c | 4 | 21,522 | shader-index entries, measured | -| 0x60 | 4 | 31,120,020 | meta blob size, measured (the meta index covers exactly this) | -| 0x64 | 4 | 240,894,464 | code blob size, measured (the last shader entry ends 24 bytes before it) | -| 0x68 | 0x18 | zero | unused in this file | - -Two cross-checks tie the counts to the records. The u32 fields at +0x08, +0x0C and +0x50..+0x5C of the 0x70 records -are 0xFFFFFFFF or below 54,576 (50,942 values that are not 0xFFFFFFFF, maximum 54,441). All 10,772 fields at -+0x08..+0x14 of the 0x18 records are below 54,576 (maximum 54,575, the last meta-index entry). A wrong count or -stride breaks both. - -## Regions - -| Region | Offset | Size | End | -|---|---:|---:|---:| -| header | 0x0 | 0x80 | 0x80 | -| 0x70 records, 25,471 | 0x80 | 2,852,752 | 0x2B8810 | -| 0x18 records, 2,693 | 0x2B8810 | 64,632 | 0x2C8488 | -| meta index, 54,576 × 8 | 0x2C8488 | 436,608 | 0x332E08 | -| shader index, 21,522 × 8 | 0x332E08 | 172,176 | 0x35CE98 | -| meta blob | 0x35CE98 | 31,120,020 | 0x210A92C | -| code blob | 0x210A92C | 240,894,464 | 0x106C6B2C | - -The regions are laid end to end and add up to the file size exactly: - -``` -0x80 + 25,471 * 0x70 + 2,693 * 0x18 + 54,576 * 8 + 21,522 * 8 + 31,120,020 + 240,894,464 - = 128 + 2,852,752 + 64,632 + 436,608 + 172,176 + 31,120,020 + 240,894,464 - = 275,540,780 = 0x106C6B2C -``` - -## Indexes - -Both tables are arrays of `(u32 offset, u32 size)` pairs, 8 bytes per entry, relative to their blob. - -- Meta index: 54,576 entries over the meta blob. The first offset is 0 and each entry starts where the previous one - ends; the last ends at 31,120,020, so there is no gap, overlap or entry past the blob. -- Shader index: 21,522 entries over the code blob, offsets strictly ascending and all distinct. The largest - `offset + size` is 0xE5BC1E8, 24 bytes before the declared code size 0xE5BC200. - -A shader-index entry is not one program. Counting `s_endpgm` inside each entry's range gives 16,992 entries with one, -4,508 with two, 21 with three or more, and one with none. The code blob holds 26,092 `s_endpgm` (0xBF810000) and -1,070,769 `s_code_end` (0xBF9F0000), and 21,463 of the 21,522 entries end on an `s_code_end` dword (58 end on a zero -dword and one on another word). The run after the last `s_endpgm` is filler, so `s_code_end` is not a program -terminator and the `s_endpgm` count does not equal the shader count. A whole-file marker scan also finds two -`s_endpgm` words outside the code blob (one in the meta blob) and no `s_code_end`, so the marker count has to be -bounded to the code region. - -## Meta blob - -The blob spans [0x35CE98, 0x210A92C) and is 31,120,020 bytes. A meta-index entry starts with a short header and, in -20,318 of the 54,576 entries, continues with 32-byte chunks. The header length is the first multiple of 4 from 0 to -0x40 for which `(size - header) % 32 == 0` and every chunk's first dword is 0x41, 0x42 or 0x43. Measured headers: -0x10 on 17,634 entries, 0x14 on 2,684, 0x18 on 2,684 and 0x1c on 665. Another 3,349 entries fit that shape with zero -chunks. The remaining 30,909 entries do not parse as chunk lists at all; their layout is not decoded here. - -| Chunk | Count | 32-byte body | -|---|---:|---| -| 0x41 | 402,328 | first dword 0x41, then seven dwords | -| 0x42 | 371,387 | first dword 0x42, then seven dwords | -| 0x43 | 20,318 | first dword 0x43, a 16-byte value, then 12 zero bytes (all 20,318) | - -The second dword of a 0x41 chunk takes six measured values. An external layout note names the first four; that -mapping is not proven here. - -| Value | Count | Meaning | -|---:|---:|---| -| 0x300 | 289,590 | named SRV by the external note, unproven | -| 0x302 | 46,186 | named CBV by the external note, unproven | -| 0x303 | 11,328 | named UAV by the external note, unproven | -| 0x002 | 13,897 | named sampler by the external note, unproven | -| 0x401 | 33,596 | no name | -| 0x100 | 7,731 | no name | - -The third dword of a 0x42 chunk takes 26 distinct values shaped like 0x000SSIIRR (0x00070001, 0x000D0201 and so on), -which is consistent with space/index/register slots, but the fields are not decoded. - -## Meta records: what the chunks decode to - -The chunk lists have a fixed order: all 0x41 chunks, then all 0x42 chunks, then exactly one 0x43. That holds for -20,318 of 20,318 records, so one record belongs to one stage. The decode below is measured shape plus an -inference per field. - -### 0x41: user-data entries - -| Word | Role measured | Confidence | -|---:|---|---| -| +0 | 0x41 kind | high | -| +4 | offset, always a multiple of 8, 0..0x820; zero for 0x2, 0x100 and 0x401 | high that it is 8-byte-granular; the table it points into is not identified | -| +8 | key 0..0x1fd; repeats, 0 is common | low, it is not a unique binding id | -| +0xc | count 0..0x800, 73 distinct for 0x300 | low | -| +0x10 | three bytes: `a` (bits 16..31), `b` (bits 8..15), size (bits 0..7) | high on the split, meaning below | -| +0x14 | 0xffffffff | measured | -| +0x18 | 0 | measured | - -Per kind: 0x401 has offset 0, `b`=0, size 4 and `a`=1..24, consistent with a number of 32-bit constants -(medium); 0x2 has offset 0, `b`=5..13 and size 4 (sampler-like, medium); 0x100 has offset 0, `b`=6..11 and -size 2 (low); 0x300/0x302/0x303 carry the nonzero offsets, `b`=4..13, and size 4 or 8 (0x300, 0x303) or 4 -(0x302). Reading `b` as a register space and `a` as a base register for descriptors, or as a count for 0x401, -fits the values but has no independent check (medium/low). - -### 0x42: register slots - -The slot splits as 0x00SS_IIRR: SS 1..16, II 0..3, RR 1..2. The slots follow the 0x41 descriptors in order. In -the 5,230 records where their counts are equal, positional pairing gives II=0 for 23,047 of 23,049 0x300 -entries, II=1 for 4,144 of 4,146 0x303 entries and II=2 for all 6,100 0x302 entries. That is the order -SRV=0, UAV=1, CBV=2 of D3D12_DESCRIPTOR_RANGE_TYPE, so II is probably the range type (medium-high). SS is -probably a register space or table index (medium) and RR (1 or 2) a width (low). - -The 0x2 samplers and the 0x401 constants take no slot at all (0 of 13,897 and 0 of 33,596). Static samplers -taking no user-data dwords matches the layer's contract in [d3d12_vulkan.md](d3d12_vulkan.md) 3.5 (medium-high). -Another 15,068 records have more slots than descriptors, usually one or two; those extras all have RR=2, a -zero key and w4=0, with (SS,II) mostly (14,3), (2,0) or (10,0). They are not decoded (low). - -### Relation to the 32 user-data dwords - -Within one record the cost is small: a graphics chunk record carries 11 constant dwords and one or two tables, -15 dwords under two dwords per table. The 32-dword block is therefore the union of the tables and constants, -not one dword per 0x41 entry (medium). The 0x41 offsets also exceed 128 bytes for half the entries (range -0..0x820, 49.5% at or below 0x78), which fits a per-table descriptor index better than a dword offset. The -records that do not fit are elsewhere: 4,519 of the 20,318 chunk records exceed 32 dwords under two dwords per -table (4,202 under one), and none of them is on the graphics path. Of those 4,519, 1,017 are named by a compute -PSO and the other 3,502 are not named by the graphics or compute records measured here. The extreme record has -231 constant dwords; the largest slot count is 281. No mapping from a slot to a user-SGPR index was confirmed. - -### Which PSOs reference which records - -- A graphics PSO's u32 at +8 names a stage record (sizes 380..520) and +0xC an input-layout record; +0x50..+0x5C - are 0xFFFFFFFF in this corpus. -- The stage record names chunk records at +4 (entry 4 on 13,409 PSOs, entry 6 on 12,062), at +0x2C (entry 2 on - 25,469) and further at +0x78, +0x90, +0x150 and +0x1A4. Graphics PSOs share eight chunk records in total, not - one per PSO. -- A compute PSO's +8 and +0xC name 20- and 28-byte hash records, +0x10 a mixed record and +0x14 a chunk record - (2,693 references, 2,684 distinct records). - -## Graphics user signature - -`tools/psocache_usersig.py` resolves a graphics PSO to its user data and prints, per chunk, the kind, register -space, base register, count, element size and the slot bytes. A PSO uses 3 to 5 distinct chunk records after -duplicates are removed (four on 23,625 of 25,471 PSOs); the eight layouts are shared across the corpus. - -| Chunk or field | Reading | Confidence | -|---|---|---| -| 0x300 / 0x302 / 0x303 | descriptor entries | high that they are descriptors, medium for the SRV/CBV/UAV names | -| 0x002 | sampler entry, no slot | medium-high; none of the eight graphics records carries one | -| 0x401 | 32-bit constants, `a` = count | medium | -| 0x100 | unknown, not consumed | low | -| 0x41 offset (w2) | descriptor index inside the table, 8-byte granular | medium | -| 0x41 `b` | register space | medium | -| 0x41 `a` | base register for descriptors | medium | -| 0x41 size | element size 2, 4 or 8 | high | -| 0x41 key (w3) | unknown | low | -| 0x41 count (w4) | descriptor count | low | -| 0x42 SS | descriptor-table / root-parameter index | medium-high | -| 0x42 II | range type: 0 SRV, 1 UAV, 2 CBV, 3 sampler | medium-high | -| 0x42 RR | width, 1 normally and 2 on extra slots | low | - -The kind-to-range-type correspondence is exact in the positional pairing: 23,047 of 23,049 0x300 entries sit on -II=0, 4,144 of 4,146 0x303 on II=1 and all 6,100 0x302 on II=2. One distinct SS is read as one -`D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE`, each (SS, II) pair as one `D3D12_DESCRIPTOR_RANGE`, and each 0x401 -as one `D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS`. That mapping is one-to-one for the measured graphics -records, but it is an inference: SS could be a register space and `b` the table index instead, and the cache -does not say whether a table costs one or two user-data dwords. - -Under both table models all 25,471 graphics PSOs fit 32 dwords (15 dwords with two per table). A later -`CreateGraphicsPipelineState` path would group the slots by SS into tables, take II as the range type and the -0x41 entries as the range contents, take each 0x401 as a constants parameter, and pack them in root-parameter -order. The record does not carry that order, so it would have to come from SS or from the shader's reads, which -is not measured. - -## What remains unknown - -- The meaning of the two header strings, the 0x48 value and the six 0x41 second-dword values. The SRV/CBV/UAV/sampler - names are the external note's, not this file's. -- The `a` and `b` bytes of 0x41 w5 and the SS/II/RR meanings of the 0x42 slot word: the readings above are - inferences from value ranges and order, not confirmed by the shader code. -- The encoding of the w3 key and w4 count, and the 15,068 records with extra slots. -- The 0x43 16-byte value was not matched against any hash in the package. -- The 30,909 meta entries that are not chunk lists. -- Whether the code blob is raw RDNA2. The evidence is the two marker words and the `s_code_end` filler; no - disassembly or translation was run on this blob. - -## Checking and carving a copy - -`tools/psocache_extract.py` finds the cache in an RPF9 archive without the TOC: it walks the archive's stream -table in order, inflates each stream to learn its extent, keeps only the first 4 bytes, and stops at the first -stream whose output starts with the magic. It then appends the following contiguous streams (up to 1 MiB of zero -padding) until the header's declared total is reached, writes the file under the temporary directory and runs -the checks below. `--budget` bounds the compressed bytes examined and `--max-streams` the number of streams; a -source folder is scanned in sorted order and the report names the archive index and the stream offset, never the -path. - -``` -python -I tools/psocache_extract.py -``` - -`tools/psocache_inspect.py` reads the cache file only: - -``` -python -I tools/psocache_inspect.py --meta -``` - -It checks the magic, reads the four counts and two sizes above, bounds all six regions against the file, checks that -the meta index is contiguous over the meta blob and that every shader entry stays inside the code blob, parses the -chunk lists and counts `s_endpgm` and `s_code_end` in the code blob. `--meta` adds the aggregate 0x41/0x42 decode -described above, `--entry N` lists one meta index entry and `--limit N` bounds how many records `--meta` reads. It -prints offsets, sizes and counts, names every field that does not fit instead of stopping, and exits 0 when the -regions add up to the file size, 1 on a disagreement and 2 when the file is not a cache. `--json` prints the same -report as JSON. It does not decode a chunk payload, disassemble the code or verify a hash. - -`tools/psocache_usersig.py` turns one or more graphics PSOs into the per-record user signature and the 32-dword -fit described above: - -``` -python -I tools/psocache_usersig.py [--entry N] [--limit N] [--json] -``` - -It reuses the parser from `tools/psocache_inspect.py`, prints the aggregate over the first `--limit` graphics PSOs -(all by default) or one PSO with `--entry N`, and never prints a hash. diff --git a/docs/radio_stations.md b/docs/radio_stations.md deleted file mode 100644 index ecf8a769a..000000000 --- a/docs/radio_stations.md +++ /dev/null @@ -1,324 +0,0 @@ -# Radio station records and content-id lists - -**Status: layout measured, station ownership partly inferred.** This page is the companion to -[audio_config.md](audio_config.md), which covers the 1,589 music/radio records. Here are the station -descriptors and the content-id groups that reference those records. - -Both structures live in the same inflated audio config at the start of `audio.rpf`: 837 zlib streams, -54,143,493 bytes. They are plain config, not scripts and not AWC audio. The companion record table -groups 1,589 music/radio records into contiguous station runs, with shared ad/DJ/jingle libraries -interleaved. Offsets below are relative to one inflated 64 KiB stream. The stream is named by its -`audio.rpf` stream offset, so `0x762160` means "the stream whose zlib record starts at archive offset -`0x762160`", not a position in the concatenated config. On this package's concatenation the same -streams begin at `0x160B419` (`0x762160`) and `0x3C55D5` (`0xDAEB0`); those concatenation offsets -change with the carve order. - -Only the record side has a committed reader (`tools/audio_config.py`, described in the companion -page). Station identification needs a local hash dictionary, so this page records the measured -offsets and counts instead of adding a scanner that would have to guess station names. - -## Station descriptors in stream `0x762160` - -The stream holds 19 eight-byte pairs: - -```text -offset +0 +4 -0x524C [u32 station hash] e8 03 00 00 end = 0x03E8 -0x3B94 [u32 station hash] 38 4a 00 00 end = 0x4A38 -``` - -The second u32 is a **byte end offset in the same 64 KiB stream**, not a count, a duration or a start -time. `0x4A38` is 19,000 bytes, not 19 seconds and not 19,000 tracks. The 19 end values are exactly: - -```text -0x03E8 0x07D0 0x0BB8 0x0FA0 0x1388 0x1770 0x1B58 0x1F40 0x2328 0x2710 -0x32C8 0x36B0 0x3A98 0x3E80 0x4268 0x4A38 0x4E20 0x5208 0x55F0 -``` - -They partition `0x0000`-`0x55F0` (22,000 bytes) into 19 spans. Every value is a multiple of 1,000, -so the first 22,000 bytes behave like a slot arena of 1,000-byte units: 17 spans are one unit, -one is two (`0x4268`-`0x4A38`) and one is three (`0x2710`-`0x32C8`). That slot reading is inferred; -the end offset itself is measured. - -The 19 record starts run from `0x2F4C` to `0x6230`. Each record begins with the 8-byte pair and -continues with a variable-length graph of config nodes; only the next known station pair gives a clean -upper bound. The pairs are therefore not a fixed-stride array. The graph mixes content ids, -`FFFFFFFF` separators, floats and nested nodes; ids from the station's local range appear next to -shared ids. It is not a clean ordered playlist. The u32 field is not the length of this graph: it is -an end offset into the 22,000-byte span area described below, which is logically separate from the -graph after the pair. - -### The hash is not `joaat("Core.RadioStation.*")` - -Each station hash matches Jenkins one-at-a-time over a **bare identifier** of the form `radio_`. -The plaintext debug list at stream `0xB01000` contains `Core.RadioStation.` strings, but -`joaat("Core.RadioStation.vcrr")` is not the descriptor hash; `joaat("radio_vcrr")` is. On this -package all 19 descriptors resolve to a bare `radio_*` identifier with a candidate list. Fourteen of -the 19 bare suffixes also occur in the debug list; the other five use a different suffix, so the debug -list is a vocabulary, not a lookup table. A station-name dictionary is still required. - -A second table is easy to confuse with this one. At `0x202C`-`0x20DC` there are 22 contiguous -`[u32 station hash][u32 ident]` pairs with ident values `0x2634`-`0x27CC`. Those idents are content -references, not byte offsets. Only 17 hashes occur in both tables; two descriptor hashes are absent -from the ident table and five ident hashes are absent from the descriptor table. The two tables do -not enumerate the same station set, and the 19 descriptors do not cover every station group in the -record table. - -## The 19 spans - -The counts below are u32 values in the `0x2000`-`0x2FFF` band, the band the local content references -use on this package. They are **reference counts, not track counts**. Each descriptor's u32 picks the -span that ends at that value; the record's own offset does not select the span. "Descriptor at" is -where the 8-byte pair is stored, not the start of the span; the pair for S01 is stored at `0x524C`, -inside the S19 range. The last column counts station-table pairs stored inside the span: 22 ident -pairs for S09, boundary descriptors for the others. That shows the spans are not exclusive station -payloads. - -| Span | Bytes | Descriptor at | Size | `0x2xxx` refs | Unique | Station-table pairs inside | -|---|---:|---:|---:|---:|---:|---:| -| S01 | `0x0000`-`0x03E8` | `0x524C` | 1,000 | 8 | 8 | 0 | -| S02 | `0x03E8`-`0x07D0` | `0x3D80` | 1,000 | 4 | 4 | 0 | -| S03 | `0x07D0`-`0x0BB8` | `0x358C` | 1,000 | 9 | 9 | 0 | -| S04 | `0x0BB8`-`0x0FA0` | `0x6230` | 1,000 | 4 | 4 | 0 | -| S05 | `0x0FA0`-`0x1388` | `0x3E60` | 1,000 | 17 | 17 | 0 | -| S06 | `0x1388`-`0x1770` | `0x2F4C` | 1,000 | 19 | 19 | 0 | -| S07 | `0x1770`-`0x1B58` | `0x3F44` | 1,000 | 4 | 4 | 0 | -| S08 | `0x1B58`-`0x1F40` | `0x3664` | 1,000 | 86 | 86 | 0 | -| S09 | `0x1F40`-`0x2328` | `0x5860` | 1,000 | 112 | 89 | 22 (ident) | -| S10 | `0x2328`-`0x2710` | `0x304C` | 1,000 | 53 | 18 | 0 | -| S11 | `0x2710`-`0x32C8` | `0x4130` | 3,000 | 210 | 95 | 2 | -| S12 | `0x32C8`-`0x36B0` | `0x5784` | 1,000 | 95 | 68 | 3 | -| S13 | `0x36B0`-`0x3A98` | `0x60C0` | 1,000 | 89 | 63 | 1 | -| S14 | `0x3A98`-`0x3E80` | `0x41FC` | 1,000 | 99 | 76 | 3 | -| S15 | `0x3E80`-`0x4268` | `0x5B24` | 1,000 | 115 | 80 | 3 | -| S16 | `0x4268`-`0x4A38` | `0x3B94` | 2,000 | 121 | 79 | 0 | -| S17 | `0x4A38`-`0x4E20` | `0x37EC` | 1,000 | 41 | 16 | 0 | -| S18 | `0x4E20`-`0x5208` | `0x33E4` | 1,000 | 60 | 41 | 0 | -| S19 | `0x5208`-`0x55F0` | `0x547C` | 1,000 | 110 | 71 | 2 | - -S01-S08 and S10 contain no station table. S09 contains the 22-entry ident table at -`0x202C`-`0x20DC`; that table contributes 29 of its 112 `0x2xxx` occurrences. S11-S15 and S19 -contain boundary descriptors. The counts for S09, S11-S15 and S19 are therefore upper bounds, not -list lengths. The other spans are not upper-bounded by a station table, but they are still not -playlists. S16-S18 contain no station table yet remain mixed node graphs; a span being -station-table-free does not make it a playlist. - -S06 shows a clean pattern: repeated `3f 80 00 00` (float 1.0) followed by a content id: - -```text -0x1388 3f 80 00 00 22 27 00 00 3f 80 00 00 23 27 00 00 -0x1398 3f 80 00 00 24 27 00 00 3f 80 00 00 25 27 00 00 -``` - -That is 19 references for S06: 15 ids from its local run plus four shared ids. The rest of the stream -mixes floats, `FFFFFFFF` separators, zeros and small integers with the ids. The spans preserve local -order where a list is present, but they are not station-wide playlists. - -The spans are logically separate from the record payloads. The u32 field points into the first -22,000 bytes; the graph after a pair starts at the next bytes in the stream. A span can contain other -stations' descriptors, so its content-id count is not a playlist length. The clean 80-id VCRR list -is not in this stream; it is in `0xDAEB0`. - -## Content-id groups in stream `0xDAEB0` - -The actual count-prefixed groups are in a second 64 KiB stream. A group is: - -```text -[u32 count][count x u32 content id] -``` - -The start of the VCRR range is a clean example: - -```text -0x668C 08 00 00 00 f2 28 00 00 f3 28 00 00 f4 28 00 00 f5 28 00 00 -0x669C f6 28 00 00 f7 28 00 00 f8 28 00 00 f9 28 00 00 -0x66B0 03 00 00 00 fa 28 00 00 fb 28 00 00 fc 28 00 00 -0x66C0 da 00 00 00 93 15 00 00 2b 00 00 00 10 00 01 aa -``` - -The count is a count of ids: `0x28F2` is stored as `f2 28 00 00`, so the ids are u32, not u16. - -There are 33 count-prefixed groups in the stream, with counts 1-9 and ids in the `0x2822`-`0x29A5` -band. `0xDA` and `0x1593` appear together after 20 of the 33 groups; the exact -`0xDA, 0x1593, 0x2B` tail appears in 19, one uses `0x31`, and the other 13 have different tails. It is -a common template, not a universal constant. `0xDA` and `0x1593` do not vary with a record's duration -or with its position in the group. - -The other node family links one content id to the next: - -```text -[1][0x1594 or 0x15A8][0][0][0][0x2A][0xAAAA2609][u32 hash][next content id] -``` - -The hash on a link is not the record's `+8` hash, not its `+12` name hash and not the stream id. It -is another unresolved 32-bit value. The nodes form a graph of content references, not a table of -times. - -### Why this is not a start table - -No field in either family is a per-track start offset: - -- The count is the number of ids that follow; it is not a byte length or a duration. -- The tail values `0xDA`, `0x1593`, `0x2B`/`0x31`, `0xAA010010`, `0x20`, `0x28` are template - values. The same values follow groups with different ids and different total durations. -- The per-link hash is a new hash per node; it does not grow with time. -- None of the 80 prefix sums of the VCRR record durations in milliseconds occurs as a u32 anywhere - in stream `0xDAEB0` or `0x762160`. The two non-zero known VCRR cue times (86.24 s and 647.12 s, - stored in milliseconds) also do not occur anywhere in the 54 MiB config. -- The values that do vary are floats and small parameters around the nodes, not monotonic - millisecond counts. - -The groups may preserve a local order, and the VCRR ids are listed in ascending order, but order is -not a start time. A runtime still has to get the starts from the audio or from the missing -executable. - -## VCRR: exact mapping at one base - -The VCRR content range is `0x28F2`-`0x2941`: 80 consecutive ids. All 80 occur in stream `0xDAEB0` -(83 aligned occurrences; two ids repeat, one twice and one once). Six count-prefixed groups hold 33 of -them (8 + 3 + 8 + 4 + 2 + 8 ids); the other 47 occur in other node types, including 21 as linked-node -`next` values. - -At base `0x9481`: - -```text -0x28F2 + 0x9481 = 0xBD73 -0x2941 + 0x9481 = 0xBDC2 -``` - -Every one of the 80 ids maps to a record in `0xBD73`-`0xBDC2`, and every record in that range is -covered: **80/80, measured**. The first group maps `0x28F2`-`0x28F9` to `0xBD73`-`0xBD7A`; the -second maps `0x28FA`-`0x28FC` to `0xBD7B`-`0xBD7D`; the linked chain continues `0x28FD` to `0xBD7E`. -The base is constant across this local range. - -The uncertainty is in the anchor, not the arithmetic: - -- The base is chosen because `0x28F2` is the first content id and `0xBD73` is the first record of the - presumed VCRR block. That block is contiguous, 80 records long, and its 70 longest durations fit the - mix, but the config does not label it. -- A pure "all 80 ids resolve" search is **not unique**: many 80-record runs exist in the 1,589-record - table, and shifting the base by one count also resolves all 80 into a neighbouring run. The - arithmetic alone does not identify VCRR; the station-context anchor does. -- Therefore "80/80 at base `0x9481`" is measured, and "this block is VCRR's track set" is inferred. - -The 80 records sum to **13,013.088 s**. The 70 longest sum to **12,043.287 s**, 39.7 s more than the -measured 12,003.6 s VCRR mix, while the 10 shortest sum to 969.8 s. That is consistent with the mix -using about 70 of the 80 records, but the config does not say which ten are omitted or trimmed. The -80-record total is 1,009.5 s longer than the mix, so no cumulative table over all 80 can be the mix. - -## Shared and best-fit clusters - -Six content ranges are best read as shared libraries or shared blocks rather than station-local track -blocks. All bases in this table are best-fit, not decoded: - -| Content range | Record range at that base | Records present/span | Base | Evidence | -|---|---|---|---:|---| -| `0x27D1`-`0x289C` | `0xBA05`-`0xBAD0` | 204/204 | `0x9234` | best-fit shared library | -| `0x27DA`-`0x280D` | `0xB82E`-`0xB861` | 51/52 | `0x9054` | best-fit shared library | -| `0x27D6`-`0x2804` | `0xB8EC`-`0xB91A` | 47/47 | `0x9116` | best-fit shared library | -| `0x281E`-`0x283D` | `0xBD2C`-`0xBD4B` | 28/32 | `0x950E` | arithmetic exact; use inferred | -| `0x28AE`-`0x28D6` | `0xBDBC`-`0xBDE4` | 41/41 | `0x950E` | arithmetic exact; use inferred | -| `0x27D7`-`0x27F0` | `0xBF8C`-`0xBFA5` | 25/26 | `0x97B5` | best-fit shared library | - -The two `0x950E` rows are the strongest: the ids map onto contiguous record runs, with four absent -ids in the first row (`0xBD3E`-`0xBD41`) and none in the second. The four large rows are best-fit -because content ids are reused across spans; the mapped ranges are compact, but another base can -produce another compact range. - -The same local id range can therefore mean different records in different contexts. `0x281E`, for -example, occurs in the VCRR span, but at base `0x950E` it lands in the shared block, not in the VCRR -block at base `0x9481`. This is consistent with a station graph mixing its own local range with -shared ranges, each range keeping its own base; that reading is inferred from the ranges, not decoded -from a per-range base field. - -## Title-keyed stream ids - -The low 29 bits of `hash B` are the AWC stream id, and `hash B` is `joaat(normalized title)`. That -turns the record table into a title-keyed lookup even when the config's display-name field is blank. -On the current 800 resolved rows, the unmodified normalized title matches the stream id exactly for -**702 (87.75%)**; trying case, punctuation, bracket, dash and feature-credit variants raises this to -**746 (93.25%)**. The 54 misses are not evidence of absence: the stored title can differ from the -in-game name, the hash can cover a different mix or edition, and a few records are duplicate-title or -placeholder collisions. - -This rule resolved four previously untitled CircoLoco records whose config names were empty; one of -the four is assigned to CircoLoco by record-id and AWC-bank adjacency rather than by a station field. -The title hash identifies a bank, not a station, not a play order and not a start offset. Keep the -station assignment and cue times as separate, evidence-labelled steps. - -## What a runtime needs - -| Need | Source | Status | -|---|---|---| -| Record id, duration, name hash, stream id | record table, `docs/audio_config.md` | measured, 1,589 records | -| AWC bank for a stream id | AWC manifest; `stream_id = hash B & 0x1FFFFFFF` | measured | -| Station set and span ends | 19 descriptors in `0x762160` | measured | -| Local content ids | count-prefixed groups in `0xDAEB0` | measured for VCRR; group-to-station ownership inferred elsewhere | -| Content id -> record id | base per range | VCRR base measured only at its anchor; shared bases best-fit | -| Display names | hash dictionary for `joaat` | missing; the `0xB01000` list does not hash-match | -| Play order and start offsets | not stored | missing | - -To build a station, a runtime can read the descriptors, take the content-id groups once the -group-to-station mapping is known, resolve each local range with its own base, and use -`hash B & 0x1FFFFFFF` to find the AWC bank. It cannot get the mix order or the cue times from this -config. It also cannot assume that every station in the record table has a descriptor: the 19 -descriptors and the 22-entry ident table are different sets. - -The graph after each station pair is not a substitute for the groups: it mixes local and shared ids and -has no count or order guarantee. The groups are the only place where the VCRR range is complete. - -The u32 hash at `+8` (hash A) remains unresolved. It is not the normalized-name hash at `+12`, not -the stream id, and it did not match any content id checked. The name hash at `+12` is only useful -with a name dictionary; no such dictionary is committed here. - -## Measured vs inferred - -Measured: - -- 19 station records in `0x762160`, each starting with an eight-byte `[station hash][byte end]` pair; - the end values are the 19 multiples of 1,000 from `0x03E8` to `0x55F0`. -- The spans and `0x2xxx` reference counts in the table, including the boundary-descriptor and - S09 ident-table overlaps. -- 80 unique VCRR content ids, 83 aligned occurrences; 80/80 map to `0xBD73`-`0xBDC2` at base - `0x9481`; 13,013.088 s total, 12,043.287 s for the 70 longest. -- 33 count-prefixed groups; `0xDA` and `0x1593` together in 20, the exact three-field tail in 19, - 25 groups with `0x2B` somewhere and 2 with `0x31`. -- No VCRR prefix sum appears as a u32 in the two streams; the known cue times do not occur in the - 54 MiB config. -- The six cluster ranges and their present/span counts. -- The title-keyed stream-id check: 702/800 exact `joaat(normalized title)` matches and 746/800 - with the tested case/punctuation/feature variants; 54 remain unmatched. - -Inferred: - -- The 1,000-byte slot arena, and that a span is an allocation range rather than an exclusive - station payload. -- That the 80-record block at `0xBD73` is VCRR's track set, and that about 70 of the 80 are used. -- The station ownership of every non-VCRR group and every shared cluster base. -- That the `0x202C` ident table is a station-ident map rather than another content table. -- That the four title-resolved CircoLoco records belong to that station; one assignment is by - record-id/AWC-bank adjacency, not by a station field. - -## Reproduce - -```powershell -python -I tools/rpf9_carve.py audio.rpf --until-adat -``` - -(`--until-adat` stops at the first AWC bank, `0x129B000` on the measured package; `--limit 0x129B000` gives the -same window there.) - -The carve writes `000000762160.bin` and `0000000daeb0.bin`, both 65,536 bytes. The record table is -`python -I tools/audio_config.py --join --json`. The station scan is a u32 read of the two -streams; no station scanner is committed, because the station hash set needs a local dictionary. - -## No-sharing rule - -The package is read-only. Keep carved streams, the name list and any extracted names or hashes in a -local temp folder. This page and its PR contain offsets, counts, numeric ranges and the hash formula -only: no station-name list, no track title, no hash value, no carved bytes, no audio. - -The same rule applies to resolution: a content id is not a global record id, and a base is not -portable. Do not publish a table that gives one global meaning to a content id, and do not reuse one -station's base for another station or for a shared block. Resolve per range and keep the station -context. diff --git a/docs/rbf0.md b/docs/rbf0.md deleted file mode 100644 index 2a8629083..000000000 --- a/docs/rbf0.md +++ /dev/null @@ -1,539 +0,0 @@ -# RBF0 resources in `data.rpf` - -`RBF0` is RAGE's binary form of an XML data file. It is a single record stream with an inline descriptor table, not -a section container. This note measures the 1,263 `RBF0` resources carved from `data.rpf` of the Xbox Series -1.0.2.1 package, using the fixed zlib walk from PR #90. It records format facts and aggregate counts only: no -payload, carved stream, path list or string dump is committed here. - -## Bottom line - -| Question | Result | -|---|---| -| How many `RBF0` streams? | **1,263 logical resources**: 1,243 single-stream and 20 split over 2-37 zlib chunks. The magic is exactly `RBF0` at offset 0 in all 1,263. | -| Is the header stable? | **Yes.** A 4-byte prologue `FB FF 01 00` in 1,260 streams; absent in 3. The record grammar is identical in both. | -| Is there a section directory? | **No.** No section count, offset table or size table exists. All 1,263 resources parse to their exact last byte; the only structure is the record sequence. | -| Is there a name or hash table? | **No.** Schema names are inline UTF-8 with a u16 length. There is no hash table and no readable hash string. The 64-bit integers are mostly small codes; none is identified as a name hash. | -| What do the streams carry? | UI framework and UI data schemas, movie-subtitle containers, and three tuning/config schemas. No animation, mesh or audio payload. | -| Is it the same format as the `anim.rpf` rig blob? | **Yes, same container and grammar.** That blob is one `rage__crRigSetManager` resource; its 9 descriptors and 28,962 elements parse with the same rules. | -| Can it be decoded to a tree? | **Yes.** `tools/rbf0_tree.py` decodes all 1,263 resources to element/value/text trees. Unknown descriptors and record types fail closed. | -| Compression inside `RBF0`? | **None observed.** The only compression is the outer RPF9 zlib framing. | - -## 1. Method and coverage - -The corrected `rpf9_carve.py` walks the 481,544,304-byte `data.rpf` data area and inflates 28,509 zlib streams: -423,279,355 stored bytes and 1,403,250,069 inflated bytes. Of those streams, **1,263 start with `RBF0`** and 96 -more are 64 KiB continuations of the 20 chunked resources, so 1,359 streams belong to `RBF0` resources. - -The 1,263 starts are 0.48% of the carved stored bytes (2,040,469) and 1.03% of the inflated bytes (14,476,545). -The RBF0 count is the same as the earlier scan; the carve fix changes trailing streams, not this class. - -Each start was inflated, joined to its continuations by archive order, and parsed with the grammar in section 3. -**1,263 of 1,263 resources parse exactly to the last byte** after joining. The parser is `tools/rbf0_index.py`; -the unit test builds only synthetic headers. - -## 2. Sizes and chunking - -| Measure | Value | -|---|---:| -| Logical resources | 1,263 | -| Inflated bytes | 14,476,545 | -| Stored bytes | 2,040,469 | -| Minimum | 98 | -| First quartile | 1,287 | -| Median | 3,429 | -| Third quartile | 7,433 | -| Maximum | 2,372,401 | -| Mean | 11,462 | - -| Inflated size | Resources | -|---|---:| -| < 1 KiB | 259 | -| 1-4 KiB | 456 | -| 4-16 KiB | 419 | -| 16-64 KiB | 109 | -| 64 KiB-1 MiB | 18 | -| >= 1 MiB | 2 | - -A single RPF9 zlib stream in this package tops out at 65,536 inflated bytes. When a resource is larger, the -archive stores another zlib stream whose first bytes continue the previous record, not a new `RBF0` magic or a -continuation header. The split can fall inside any field: the 20 multi-chunk resources use 2, 3, 4, 8, 10, 17 and -37 chunks, with 96 continuation streams in total. The record stream carries no length field and no self-size, so a decoder -must append by archive order and stop when the root close leaves the buffer exactly consumed (or at the next -known signature). All 20 multi-chunk resources are in the 299.6-302.7 MB archive range. All 20 are wide; the three -narrow resources are single-stream. - -## 3. Header and record grammar - -There is no established version field and no section count. The only header is: - -``` -0x00 4 bytes "RBF0" all 1,263 -0x04 4 bytes FB FF 01 00 1,260; the other 3 start the records here -0x08 ... first record (0x04 in the three streams without the prologue) -``` - -Measured first bytes of the 98-byte stream at archive offset `0x12035690`: - -``` -52 42 46 30 fb ff 01 00 00 00 11 00 75 69 50 72 6f 67 72 65 73 73 ... -"R B F 0" prologue idx 0, elem name length 17 "uiProgressDataset" ... -``` - -The prologue's meaning is not established from the bytes. It is perfectly correlated with value width: the 1,260 -streams with it use 8-byte integers and floats, and the 3 without it use 4-byte integers and floats. Whether it is -a version, a build mode or a width flag is not proven. The three narrow resources are at archive offsets -472,271,120 (271 bytes, `CTuningFile`), 472,498,176 (15,432 bytes, `InputContextStyleStore`) and 473,161,728 -(18,317 bytes, `rage__SafeframeConfig`). - -Every record is a 1-byte descriptor index and a 1-byte type: - -| Index / type | Meaning | Payload | -|---|---|---| -| `idx < descriptor_count` | use an existing descriptor | none | -| `idx == descriptor_count` | new descriptor | u16 name length, then UTF-8 name | -| `idx > descriptor_count` | invalid | none | -| `0xFF 0xFF` | close the open element | none | -| `0xFD 0xFF` | text for the open element | u32 length, then that many bytes (NUL-terminated in this corpus) | -| type `0x00` | open an element | three u16 words | -| type `0x10` | integer | 8 bytes (wide) or 4 bytes (narrow) | -| type `0x20` / `0x30` | true / false | none | -| type `0x40` | float | 8 bytes (wide) or 4 bytes (narrow) | -| type `0x50` | three floats | 3 x width (not present in this corpus) | -| type `0x60` | string | u16 length, then UTF-8 bytes | - -The three u16 element words are `0, 0, attribute_count` in every stream. Across **475,461 elements**, word 0 and -word 1 are always zero and word 2 is 0 (389,525), 1 (84,541) or 2 (1,395). The declared attribute count matches -the number of leading value records after the open in **475,461 of 475,461** elements, with zero mismatches. This -is the same rule the public `rage_engine_formats` RBF reader describes for the GTA V form; the measurements here -are independent. - -One difference from the GTA V reader matters: this corpus **reuses a descriptor with more than one value type**. -The GTA V reader rejects a record whose type differs from the descriptor's first type; this corpus does that in -**6,131 of 591,064 reused-descriptor records (1.0%), spread over 536 of the 1,263 resources**. The descriptor is a -name index, not a type declaration, and the index tool does not enforce the GTA V rule. - -### Aggregate record counts - -| Record | Count | -|---|---:| -| Descriptors (names) | 44,887 | -| Distinct descriptor names | 698 | -| Elements | 475,461 | -| Scalar values | 160,490 | -| Text records | 254,935 | -| String values (`0x60`) | 85,924 | -| Integers (`0x10`) | 29,400 | -| Floats (`0x40`) | 38,304 | -| True / false (`0x20` / `0x30`) | 3,410 / 3,452 | -| Vectors (`0x50`) | 0 | -| Maximum element depth | 36 | - -Per resource: descriptors 4 (minimum), 29 (median), 204 (maximum); elements 1 (minimum), 106 (median), 68,398 -(maximum). The integer values are mostly small codes: 337 distinct, 29,221 fit in 32 bits, 13 are -`0xFFFFFFFFFFFFFFFF`, and the most common value is 1 (7,979 occurrences). The 38,304 floats have 7,814 distinct -values and range from -3,840.0 to 65,536.0. The index tool reports counts and samples; mapping these numbers to -fields needs the schema, which the format does not carry. - -### What is absent - -- **No section table.** A complete parse consumes every byte; there is no region left for a directory. The - element words are not offsets. -- **No hash table.** Descriptor names are literal. There are no 8- or 16-hex-digit strings in the corpus, and no - hash field adjacent to a name. -- **No nested compression.** No byte-blob value type exists and every record payload is consumed by the parser. -- **No file name or path.** A resource does not store its own archive path; that would come from the RPF9 TOC. - -## 4. Readable and opaque - -The 1,263 resources contain **340,859 string occurrences** and **29,986 distinct strings**: - -| Category | Count | -|---|---:| -| Strings with `/` | 4,087 occurrences, 1,057 distinct | -| Identifier-shaped (letters, digits, `_.:@+-`) | 333,176 occurrences | -| Empty | 22 | -| Longest path-like string | 126 bytes | - -The identifiers are UI field names, control names and enum values. The path-like strings are UI resource -references (control and panel paths), not archive paths: they are relative, with no `pack:/` prefix. A keyword -scan over all strings gives: - -| Term | Occurrences | Distinct | Reading | -|---|---:|---:|---| -| `anim/` | 0 | 0 | no animation paths | -| `pack:/` | 0 | 0 | no pack-root paths | -| `SKEL_` | 0 | 0 | no bone names | -| `RBF0` | 0 | 0 | magic is not repeated in strings | -| `xml` | 0 | 0 | no XML text | -| `nav` | 2,019 | 247 | substring of UI identifiers, not nav data | -| `map` | 919 | 203 | substring of UI identifiers | -| `ipl` | 207 | 36 | substring of UI identifiers | -| `handling` | 1,054 | 3 | enum/control names | -| `meta` | 20 | 16 | substring | -| `hud` | 3,836 | 532 | UI names | -| `vehicle` | 9,429 | 2,102 | UI names | -| `weapon` | 5,492 | 859 | UI names | -| `credits` | 965 | 211 | UI names | -| `phone` | 2,788 | 693 | UI names | -| `rage__` | 35,287 | 173 | engine schema names | -| `fwui` | 26,783 | 155 | engine UI schema names | - -The counts for `nav`, `map`, `ipl`, `handling` and `meta` are substring matches in identifiers, not evidence of -navigation, map, IPL or handling files. No `RBF0` stream in `data.rpf` carries archive paths, animation paths, -bone names or XML text. There is no readable hash string; whether any integer value is a hash is not established. - -## 5. Composition by root schema - -| Group | Resources | Elements | Strings | Root schemas (count) | -|---|---:|---:|---:|---| -| `rage__fwui*` UI framework | 895 | 210,513 | 146,339 | `rage__fwuiPrefab` 603, `rage__fwuiAnimationNodeGraph` 190, `rage__fwuiFlowBlock` 61, `rage__fwuiSubscreenPrefab` 14, `rage__fwuiCoreControlPrefab` 11, `rage__fwuiPanel` 8, `rage__fwuiGrid` 6, `rage__fwuiCanvas` 1, `rage__fwuiGpsDefs` 1 | -| Screens | 201 | 170,029 | 119,953 | `UIScreen` 136, `UIMovieView` 65 | -| Movie subtitles | 125 | 18,359 | 14,517 | `CMovieSubtitleContainer` 125 | -| UI data and settings | 39 | 76,420 | 59,813 | `uiFeedbackContext` 28, `uiProgressDataset` 5, `uiSafezone` 4, `uiSettingsGamepadControlsData` 1, `InputContextStyleStore` 1 | -| Tuning and config | 3 | 140 | 237 | `CTuningFile` 1, `CCombatMeleeGroup__Tunables__Tuning` 1, `rage__SafeframeConfig` 1 | -| **Total** | **1,263** | **475,461** | **340,859** | 20 root schemas | - -The four largest resources are `uiProgressDataset` at 2,372,401 bytes, `UIMovieView` at 1,094,224 and 653,738 -bytes, and `rage__fwuiSubscreenPrefab` at 480,604 bytes. Together they are 4,600,967 bytes (31.8% of the inflated -total), and all four are multi-chunk. The 20 multi-chunk resources are not a separate kind; they are the same -schemas at the large end of the size range. - -The most frequent descriptor names are `type`, `Item`, `Name`, `Children`, `Path`, `LayoutParams`, `Style`, -`Id` and `key`. These are schema vocabulary, not asset names. - -## 6. Cross-check with the `anim.rpf` rig blob - -`anim.rpf` ends in one large `RBF0` resource. The 21 zlib chunks (58,391 stored, 1,348,436 inflated) join to a -1,348,436-byte blob that parses to the exact last byte with the same grammar: - -``` -52 42 46 30 fb ff 01 00 00 00 15 00 "rage__crRigSetManager" ... -``` - -| Measure | `data.rpf` (1,263 resources) | `anim.rpf` tail (1 resource) | -|---|---:|---:| -| Inflated bytes | 14,476,545 | 1,348,436 | -| Stored bytes | 2,040,469 | 58,391 | -| Chunks | 1,243 x 1; 20 x 2-37 | 21 | -| Layout | 1,260 wide, 3 narrow | wide | -| Descriptors | 44,887 (698 distinct) | 9 | -| Elements | 475,461 | 28,962 | -| Text records | 254,935 | 20,031 | -| Strings | 340,859 | 21,157 | -| Integers / floats | 29,400 / 38,304 | 6,677 / 0 | -| Maximum depth | 36 | 6 | -| Root schema | 20 classes | `rage__crRigSetManager` | -| Exact parse | 1,263 / 1,263 | 1 / 1 | - -The rig blob's nine descriptors are `rage__crRigSetManager`, `RigSet`, `Item`, `key`, `Entries`, `Dictionary`, -`Rig`, `Group` and `Priority`. It has 1,126 `anim/rigset/` keys, 6,677 `anim/rig/` keys and 4,815 distinct -strings. The element words are again `0, 0, attrs` (27,836 with 0, 1,126 with 1) and there are no attribute -mismatches. - -The grammar-driven tree decoder in section 9 reproduces those counts and resolves the nesting. The root contains -one `RigSet`, whose 1,126 `Item` elements each carry one `key` string attribute and one `Entries` element. Under -`Entries`, the 6,677 entry `Item` elements contain a `Dictionary` text, a `Rig` text, a `Group` text and a -`Priority` integer after the three child elements. Maximum element depth is 6. The decoder does not resolve the -rig-to-skeleton link. - -So the container, prologue, record grammar and element header are shared. The difference is the root schema: -`anim.rpf` carries a rig-set manager, while `data.rpf` carries UI and config schemas. No `data.rpf` resource has -the rig-set root, an `anim/` string or a `SKEL_` string. The `data.rpf` RBF0s are not animation data. - -## 7. Relationship to PSIN and the model set - -- **PSIN.** `data.rpf` also contains 1,045 complete PSIN metadata records. PSIN is a different container with its - own section tags; an `RBF0` stream is not a PSIN section. The two classes are disjoint at stream start. -- **Models.** The package's model recovery found 2,313 model entries. `RBF0` carries no mesh, vertex, index or - texture payload: it has zero vector records and no binary blob value type, and every byte belongs to the record - grammar. The two sets do not overlap in content. -- **Animation.** See section 6: same format, different root schema. The `RBF0` in `anim.rpf` is the rig-set - manager; the `data.rpf` set is UI/config. - -## 8. What a future decoder needs - -1. **Join chunks before parsing.** A logical resource can span 2-37 zlib streams. Append in archive order; a - continuation starts mid-record. Stop when the root close consumes the buffer exactly, or at the next known - signature. There is no length field to trust. -2. **Parse the descriptor table and the type byte together.** A new descriptor is introduced when the index - equals the current descriptor count. Do not enforce the GTA V "type must match the declaration" rule; this - corpus reuses names with different value types. -3. **Select the value width from the prologue.** `FB FF 01 00` means 8-byte integers and floats; its absence means - 4-byte. Do not guess from the root schema. -4. **Use the attribute count.** The third u16 of an element header is the number of leading value records that - are attributes; the rest are children. The measured range is 0-2, and the rule holds for every element. -5. **Build the element tree, then map to XML.** Text records attach to the open element. The public - `rage_engine_formats` RBF reader documents the same mapping for the GTA V form; the `data.rpf` corpus follows - its record grammar with the wider scalar values. -6. **Do not look for a section directory or a hash table.** There is none. Names are literal; integers are - values. Mapping a value to a field requires a schema, not a hash lookup. -7. **Keep the compression boundary explicit.** The RBF0 bytes are uncompressed after the outer RPF9 zlib inflate. - There is no byte-blob value type and the parse consumes every byte, so there is no place for a nested frame. - -The chunk join, descriptor/type pairing, width selection, attribute count and tree build are implemented in -`tools/rbf0_tree.py`; section 9 records what that decoder measured and what it still cannot name. - -## 9. Tree decoder - -`tools/rbf0_tree.py` turns the record stream into a tree. It reads a carve directory or one complete resource, -joins the 64 KiB continuations, and writes one JSON file with one object per resource, plus optional per-resource -generic XML files. It is stdlib-only and uses no schema file. - -The full `data.rpf` carve decodes **1,263 of 1,263 resources with status `ok`**, and the totals are identical to the -index counts in section 3: 475,461 elements, 254,935 text records, 85,924 string values, 160,490 value records, -44,887 descriptors (698 distinct names) and maximum element depth 36. No unknown record type occurs in the corpus. - -### 9.1 Grammar used by the decoder - -| Bytes | Meaning | -|---|---| -| `RBF0` + `FB FF 01 00` | magic and the wide (64-bit integer/float) prologue; without the prologue values are 32-bit | -| `idx type` | one record; `idx < descriptor_count` reuses a descriptor, `idx == descriptor_count` adds one | -| `u16 len` + UTF-8 | descriptor name, present only when the record adds a descriptor | -| `0x00` | element open; three u16 words follow, words 0 and 1 are zero and word 2 is the attribute count | -| `0x10` | unsigned integer, 8 bytes wide or 4 bytes narrow | -| `0x20` / `0x30` | true / false, no payload | -| `0x40` | float, 8 bytes wide or 4 bytes narrow | -| `0x50` | three floats, 3 x width (not present in this corpus) | -| `0x60` | string; u16 length followed by that many UTF-8 bytes | -| `FD FF` | text for the open element; u32 length followed by that many bytes (NUL-terminated in this corpus) | -| `FF FF` | close the open element | - -A descriptor is a name index, not a type declaration. The decoder records the type that introduced the descriptor -and all later types used with the same index. - -In every one of the 1,263 resources, the declared attributes are the first value records of their element: no child -element or text record precedes them (0 violations). Values after the attribute prefix are content in stream order, -and a value can follow a child element. A text record attaches to the open element. - -### 9.2 Measured tree facts - -| Measure | Value | -|---|---:| -| Resources decoded | 1,263 / 1,263 `ok` | -| Elements | 475,461 | -| Elements with 0 / 1 / 2 declared attributes | 389,525 / 84,541 / 1,395 | -| Two-attribute type pairs | float/float 128, string/int 1,111, string/float 40, string/string 116 | -| Text records | 254,935, all NUL-terminated | -| String values | 85,924; all are attributes and none is NUL-terminated | -| Text / string length | 2-1,006 / 1-126 bytes (the text length includes its trailing NUL) | -| Descriptor instances reused with more than one type | 564 | -| Root with an attribute | 1: `rage__SafeframeConfig` | -| Descriptor names not usable as XML element names | 1: `xmlns:xi` | -| Unknown record types | 0 | - -The single root attribute is `xmlns:xi` on the narrow `rage__SafeframeConfig` resource at archive offset -`0x1c33e000` (18,317 inflated bytes). The same name is declared as descriptor 1 at offset `0x23` and is used 14 times -in that resource. It is also the only descriptor name that cannot be used as an XML element name (the `xmlns` -prefix is reserved), which is why the XML writer uses fixed tags and puts the exact name in a `name` attribute. - -Of the 26 text payloads that are not valid UTF-8, all are text records; no string value or descriptor name failed -a strict UTF-8 decode. The decoder replaces invalid bytes with U+FFFD and sets `utf8_valid: false`; the original -encoding is not established. - -### 9.3 Measured tree shape - -Every resource has one root. The corpus has **1,263 roots**, **474,198 parent-child edges** and **890,886 tree -nodes** in total: 475,461 elements, 160,490 values and 254,935 texts. The depth distribution is: - -| Depth | Elements | Depth | Elements | -|---:|---:|---:|---:| -| 1 | 1,263 | 19 | 24,523 | -| 2 | 3,722 | 20 | 31,186 | -| 3 | 15,537 | 21 | 21,989 | -| 4 | 19,248 | 22 | 11,765 | -| 5 | 18,377 | 23 | 10,702 | -| 6 | 24,965 | 24 | 10,247 | -| 7 | 22,295 | 25 | 15,399 | -| 8 | 19,530 | 26 | 8,563 | -| 9 | 18,599 | 27 | 7,918 | -| 10 | 17,738 | 28 | 13,470 | -| 11 | 16,822 | 29 | 5,721 | -| 12 | 14,247 | 30 | 4,177 | -| 13 | 14,740 | 31 | 3,433 | -| 14 | 12,670 | 32 | 1,612 | -| 15 | 14,584 | 33 | 1,139 | -| 16 | 28,395 | 34 | 363 | -| 17 | 18,917 | 35 | 38 | -| 18 | 21,559 | 36 | 8 | - -The child-count distribution is concentrated at the leaves: 280,469 elements have no child element, while the -largest element has 156. The mean is 0.9973 child elements per element. - -| Child elements | Elements | -|---:|---:| -| 0 | 280,469 | -| 1 | 76,379 | -| 2 | 54,236 | -| 3 | 20,118 | -| 4 | 27,568 | -| 5 | 7,731 | -| 6 | 2,594 | -| 7 | 2,277 | -| 8 | 1,615 | -| 9 | 968 | -| 10 | 191 | -| 11 | 661 | -| 12-19 | 407 | -| 20-29 | 69 | -| 30-39 | 71 | -| 40-49 | 25 | -| 50-59 | 17 | -| 60-69 | 8 | -| 70-79 | 18 | -| 80-89 | 10 | -| 90-99 | 9 | -| 100-109 | 14 | -| 124-127 | 5 | -| 156 | 1 | - -The tree also separates attribute values from content values. 87,331 values are attributes (85,924 string, 1,111 -integer, 296 float); 73,159 are content (38,008 float, 28,289 integer, 6,862 boolean). 22,977 content values follow -a child element rather than preceding it. 14,423 elements have an empty content list (attributes do not count), -and 254,935 have text as their only content. - -A synthetic four-element tree shows the stored fields without using game names: - -``` -Root depth 1 attrs 0/0 children 2 content 2 - Item depth 2 attrs 1/1 children 1 content 2 - value "id" (string, attribute) - Child depth 3 attrs 0/0 children 0 content 1 - text "example" - Empty depth 2 attrs 0/0 children 0 content 0 -``` - -`attrs` is `declared/actual`; `children` counts child elements only, while `content` counts every ordered content -record (child element, value or text). The root's `end` is the byte after its close; a complete resource consumes -the buffer exactly. - -### 9.4 Output and failure behavior - -JSON carries one object per resource: `offset`, `size`, `chunks`, `layout`, `root_name`, `status`, `error`, -`descriptors`, `counts` and `tree`. Every node has a `kind` and a byte `offset`. Elements carry `descriptor`, -`attrs_declared`, `attrs_actual`, `children`, `content_count`, `attributes`, ordered `content` and `end`; values -carry `descriptor`, `type`, `payload_offset`, `size` and `value`; text nodes carry `length`, `nul_terminated`, -`text` and `utf8_valid`. The full-corpus JSON is about 0.6 GB because every node keeps its offset and child counts; -`--root`, `--offset` and `--limit` select samples. The JSON summary adds the aggregate tree shape: `nodes`, -`elements_by_depth`, `children_histogram`, `content_length_histogram`, `attribute_count_histogram`, -`leaf_elements`, `empty_elements`, `text_only_elements`, `parent_child_edges`, `max_children` and `mean_children`. - -`--csv PATH` writes one flat row per node. The `parent` column is the parent element's byte offset, `slot` is -`attribute` or `content`, `sibling` is the index in that list, and `child_index` is the index among child elements; -`attrs`, `children`, `content_count`, `type`, `length`, `nul`, `utf8` and `value` describe the node. The CSV is a -convenience view of the same structural tree, not a second parse. Use `source` (the starting filename) with -`resource` (the archive offset) to group rows: two files in a carve directory can specify the same offset. - -XML is a rendering, not a round-trip; the JSON tree is the form that encodes back to bytes (9.6). Fixed tags avoid descriptor names that cannot be used as XML element names: -``, ``, `` and ``. A string containing XML markup is escaped by the writer. The -`` root carries `status` and, on failure, `error`. JSON, CSV and XML all contain names or payloads and are -game data. - -The decoder fails closed. An index beyond the current descriptor table, an unknown record type, a non-zero element -header word, a close or text with no open element, and a truncated payload stop that resource with `status` `bad` -or `truncated`; the partial tree is kept and no value is invented. `status` `trailing` means the root closed before -the last byte. The corpus has 0 bad, 0 truncated and 0 trailing resources. - -### 9.5 Remaining unknowns - -- There is no schema: descriptor names are fields, but value meaning, enum spelling and units are not stored. -- The prologue's meaning is still not established; the decoder uses it only to select 4- or 8-byte values. -- Element header words 0 and 1 are zero in all 475,461 elements. Their intended meaning is unknown; the decoder - rejects a non-zero value instead of guessing. -- The attribute rule is measured, not proven universal: every corpus attribute leads its element and every text - element is a text-only leaf. The decoder marks `attribute_order_violation`, `multiple_text` and - `text_after_child` if a future resource departs from it; the corpus has none of these. -- The 26 invalid UTF-8 text payloads have no established encoding. The JSON, CSV and XML writers replace bad bytes, - so they are lossy for those records, and `rbf0_encode.py` refuses the 23 resources that contain them (9.6). -- `xmlns:xi` is a literal field name. Its namespace meaning is not decoded. -- `0x50` (three floats) is accepted by the grammar but never occurs in this corpus. -- No external schema or XSD validates the tree; JSON, CSV and XML output are structural renderings only. -- A resource does not store its archive path. The source label is the carve offset or file name, not a game path. - -### 9.6 Encoder and round trip - -`tools/rbf0_encode.py` writes a tree document back to bytes with the grammar of section 3. It emits each descriptor -name at its first use, then the element header words `0, 0, attribute count`, the attributes, and the content in tree -order. Text and strings keep their recorded bytes and terminating NUL. `--check` decodes every resource of a carve, -joining continuations as `rbf0_tree.py` does, encodes it, and compares the result with the original bytes. It exits 0 -only when every resource is byte-identical: a resource that encodes to different bytes or is refused makes it exit 1, -as `rbf0_tree.py` does for a resource that is not `ok`. - -The encoder fails closed: it refuses a tree that cannot hold the original bytes instead of writing other bytes. A -refusal is one of these: an incomplete parse, invalid UTF-8 that the decoder replaced, a NaN float (infinities are -exact), an attribute after content, a descriptor out of order, a string or text whose byte length changed, or a -value the record cannot hold: an integer out of range for the layout, a float that overflows it, an unknown type, or -an element with more attribute records than its attribute count. An element short of its attribute count with a -value in its content is refused as an attribute after content, because that value would decode as an attribute. - -Measured on the same 1,263 `data.rpf` resources: - -| Result | Resources | -|---|---:| -| Byte-identical after decode and encode | **1,240** | -| Encoded to different bytes | 0 | -| Refused: invalid UTF-8 | 23 | -| Wide layout, exact | 1,237 of 1,260 | -| Narrow layout, exact | 3 of 3 | - -The 23 refused resources are exactly those that hold the 26 invalid UTF-8 text payloads in 9.5. No other reason -occurs, and with them `--check` exits 1 on this corpus. So the tree loses no byte anywhere else: element words, attribute counts, descriptor order, value widths, -float bits and NUL terminators all survive. The encoder also writes an edited tree, for example a JSON report -changed by hand. It then checks each string and text against the recorded byte length when one is present, so a -change that alters a length needs that field dropped or updated. Report-to-folder export also exits 1 if any resource is refused, -even when it writes the valid resources; on the measured corpus it writes 1,240 resources and refuses 23. -An export with no refusals exits 0. - -## 10. Reproduction - -```powershell -# Index the archive: CSV or JSON, root/counts/strings; no payload is written -python -I tools/rbf0_index.py \data.rpf \rbf0.json -python -I tools/rbf0_index.py \data.rpf \rbf0.csv --quiet - -# Index a directory of already-carved streams (offsets from leading hex file names) -python -I tools/rbf0_index.py \data-carve \rbf0.json - -# Decode trees from the same carve; JSON plus optional CSV node table and per-resource XML -python -I tools/rbf0_tree.py \data-carve \rbf0-tree.json -python -I tools/rbf0_tree.py \data-carve \rbf0-tree.json --csv \rbf0-nodes.csv -python -I tools/rbf0_tree.py \data-carve \rbf0-tree.json --xml \rbf0-xml -python -I tools/rbf0_tree.py \data-carve \subtitle.json --root CMovieSubtitleContainer --limit 1 - -# Round trip: decode and re-encode every resource and compare with the original bytes (counts only) -python -I tools/rbf0_encode.py --check \data-carve -# Write the resources of a (possibly edited) tree report back as .rbf files into a new folder -python -I tools/rbf0_encode.py \rbf0-tree.json \rbf0-encoded - -# Unit tests: synthetic headers and trees only -python -I tests/test_rbf0_index.py -python -I tests/test_rbf0_tree.py -python -I tests/test_rbf0_encode.py -python -I tests/test_imhex_patterns.py -``` - -To look at one resource in a hex editor, open the inflated and joined resource (not the archive) in -[ImHex](https://imhex.werwolv.net/) with [tools/imhex/rbf0.hexpat](../tools/imhex/rbf0.hexpat). The pattern follows -the grammar in section 3, picks the 8- or 4-byte value width from the prologue, and stops where the root element -closes. `tests/test_imhex_patterns.py` builds wide and narrow streams with every record type, checks them with -`rbf0_index.parse_rbf0`, and when ImHex is installed (on `PATH`, in its default Windows folder, or named by -`LEONIDA_IMHEX`) compares the pattern's output with the parser's. - -`--start` must be 0 or more and `--limit` at least 1 (decimal or `0x` hex); an out-of-range value stops with a -one-line error and exit code 2 before an index is written. - -The JSON summary carries the corpus totals used above (`streams`, `compressed_bytes`, `inflated_bytes`, -`rbf0.resources`, `rbf0.multi_chunk`, `rbf0.by_root`, `rbf0.size_buckets`, record counts, string categories and -keyword occurrences), so the numbers can be re-measured without committing an index. `--all-strings` writes the -full readable string list to JSON; that file is game data and must stay out of git. The tree summary adds the -structural counts `elements_by_depth`, `children_histogram`, `content_length_histogram`, -`attribute_count_histogram`, `leaf_elements`, `empty_elements`, `text_only_elements`, `parent_child_edges`, -`max_children` and `mean_children`, so the tree shape can be re-measured without keeping the trees. The tree JSON, -CSV and XML outputs contain names and payloads and are game data too. - -## 11. No-sharing rule - -Game files, carved streams, inflated RBF0 blobs, readable string lists, parsed trees and reports that quote them -stay on the machine that owns the package. Do not commit them, attach them to an issue or pull request, or paste -them into a chat. Short header excerpts (a few bytes) and aggregate counts are allowed, as in `CONTRIBUTING.md`. -This document contains no archive data, no asset path and no string dump. diff --git a/docs/related_projects.md b/docs/related_projects.md deleted file mode 100644 index df0c28c18..000000000 --- a/docs/related_projects.md +++ /dev/null @@ -1,213 +0,0 @@ -# Related projects and prior art - -Leonida is **GPL-3.0-or-later**. Some useful reverse-engineering work lives under other licences, and some of it -cannot be mixed with this repository. This page records what we may learn from each project and where the line is. - -The rule is the same for every entry: **facts are fine; code is not.** A format layout, an ABI observation or a -measured behaviour can be reimplemented independently. The source that expressed it cannot be copied. - -## ivall/xcl - - - -An Xbox Series compatibility layer for Windows. It runs a title's x64 code natively and reimplements the console -system libraries, in the spirit of Wine. It recompiles RDNA2 shaders to HLSL/DXIL instead of SPIR-V. Its README -reports several retail titles as playable, and its design notes record measured facts relevant here: root-argument -placement in user SGPRs, thread-group lane layout on PC drivers and GFX10 texture tiling. - -**Licence:** **GPL-2.0-only**, which is **incompatible with GPL-3.0-or-later**, as for americas-recomp below. **No -code, tables or comments may be copied.** - -**What we use it for:** its measured facts only. Verify each one with Leonida's own census, a synthetic test or a -public specification before relying on it. This repository never contains game data, so a fact XCL measured on a retail package is checked here with synthetic inputs or a contributor's own copy. - -## rpatty-dev/PercyStar - - - -A source-available Rust explorer for RPF9/TTPF, with an RDNA2 disassembler, texture decoders and an `ADAT` Opus audio -decoder. Its format observations are relevant to the archive, texture and audio work here. - -**Licence:** the "PercyStar Non-Commercial Attribution & Copyleft License (v1.2)". It is source-available, says -"All rights reserved", and adds non-commercial, attribution, naming and share-alike conditions. It is not -GPL-compatible, so **no PercyStar code, comments or tables may be copied into Leonida**. - -**What we use it for:** reading about format facts, then implementing them independently. If a fact is useful, -record the observation in our own words, cite the project and verify it against the package or a public -specification. Do not paste even a small function "to save time". - -## realdody/americas-recomp - - - -A **GPL-2.0-only** fork of [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5), on its `xbox-series` branch. It -recompiles the same Xbox Series shaders and has run the package's DLLs against a PC D3D12 device behind an Xbox-ABI -proxy. Since 2026-11-22 its pull requests are limited to collaborators and its README points contributors here. - -**Licence:** the repository is **GPL-2.0-only** (`LICENSE`), which is **incompatible with GPL-3.0-or-later**: GPLv2-only -code cannot be combined into a GPLv3 work, so none of it may be copied, and there is no "just this one file" exception. -Since 2026-11-22 its `REUSE.toml` on `xbox-series` (commit `f1c25d72`) lists **88 files under MIT**, each relicensed with -the agreement of everyone who wrote lines in it ([realdody/americas-recomp#179](https://github.com/realdody/americas-recomp/issues/179), -still open, so the list can change): 35 files at the top of its tools/xbox directory, 30 in tools/xbox/platform (for -example `xbox_dxil_lower.py`, `d3d12_xs.cpp`, `xmem.cpp`, `xbox_device_proxy.h`), one each under tools/xbox/msvc and -tools/xbox/platform/xgr, its 20 tools/tests/test_xbox_*.py tests and its docs/xbox/BVH_CONTAINER.md. Everything else, -including the recompiler in its core directory and the `xgameruntime` stand-in sources, stays GPL-2.0-only. - -**Rule until the maintainer decides:** **no americas-recomp code is copied into Leonida**, MIT-listed or not. MIT is -compatible with GPL-3.0-or-later, so the listed files could be used the way `third_party/xtaskqueue` is (per file, only -paths listed in `REUSE.toml` at the commit used, the MIT notice kept); whether Leonida does that is the maintainer's -decision, not a contributor's. - -**What we use it for:** the measured ABI facts only. The useful findings are summarised in -[d3d12_vulkan.md §7](d3d12_vulkan.md#7-prior-art-and-measured-xbox-abi): the Xbox device entry point, the slot -deviations, the descriptor-heap start-handle return convention, the root-signature flag word and the BVH builder's -compute-pipeline path. Those are observations to verify, not code to port. The document paraphrases them; no code or -long passages are copied. - -## breadbbbb/rpf9-explorer - - - -A Windows viewer for RPF archives, and the source of the Core library behind `tools/rpf9dump` (models, textures, -TTPF pools and AWC audio). It is a `third_party` **submodule**, not code copied into this repository. - -**Licence:** the repository has **no licence file** (GitHub reports no licence), so all rights are reserved by -default. A submodule is an external dependency; it is not a grant to copy its code. Do not paste its functions, -tables or comments into Leonida. If a format fact learned from it is useful, verify it against the package and -write our own implementation. The model-recovery gap measured in [models.md](models.md) is in that submodule; the -fix should go upstream, not into a copy. - -## meetox80/6stars - - — a macOS Swift/Metal engine that renders the world out of RPF9, -with a Swift `RPFKit` format library and 44 Python research scripts. Independent work: it likewise -does not decode the TOC. - -**Licence: none.** The repository has no `LICENSE` file (GitHub reports `license: null`); only the -vendored cimgui/imgui carry MIT. With no grant, default copyright applies and the project is -**all rights reserved** — stricter than PercyStar. **No 6stars code, comment, identifier or table may -be copied into Leonida.** - -**What we use it for:** corroboration and a small number of hypotheses. As an independent reading of -the same formats it matches our `CEntityDef` member hashes (9/9), the PRD0 header, the navmesh tile -header, the meshlet group header and the PSIN/LSCH field layout. Its stream-role predicates and -navmesh surface bits are recorded as hypotheses and tested from our own package, never copied. -Where it disagrees with us (ETPF format and tile mode, the RDS5 codec field, `atArray` type `0x5C`, -PSO member hashing) our measurements are the validated ones. - - -A macOS Swift/Metal engine that reads the world from RPF9, with its own archive index and format readers. - -**Licence: none.** There is no `LICENSE` file and GitHub reports no licence, so all rights are reserved. -**No 6stars code, comments, identifiers or tables may be copied into Leonida.** - -**What we use it for:** corroboration. Its RPF9 stream-boundary predicate and PRD0 member type codes were -re-measured against this package before entering [rpf.md](rpf.md) and [world.md](world.md); its navmesh -road/pavement bit labels did not reproduce and are not used. The navmesh polygon `+4` packing it reads is the one -our decoder already validates ([navmesh.md](navmesh.md)). - -## p-portela/SCARAB - - - -A GPL-3.0 "Scarlett Compatibility And Runtime API Bridge" that forwards the console D3D12 runtime to PC D3D12 (and -to vkd3d-proton on Linux). It carries a measured catalogue of the console `d3d12_xs.dll` export surface, standard -and console-only IIDs, extension interfaces, command-list interception and presentation entry points. - -**Licence:** GPL-3.0. That is compatible with this project's GPL-3.0-or-later for study, and adapted code can be -used with attribution and the original licence notice, unlike the two projects above. Even so, **facts first**: -verify a claim against SCARAB's code and, where possible, this package; write the implementation in our style; and -say in the pull request which file a borrowed fact came from. Do not copy a whole component just because the -licence allows it. - -**What we use it for:** the measured console runtime surface (see `docs/d3d12_xs_surface.md` when that study -lands), the IID/extension tables, and the call-sequence observations that Leonida's own -[d3d12_vulkan.md §7](d3d12_vulkan.md#7-prior-art-and-measured-xbox-abi) still lists as unknown. SCARAB forwards to -D3D12; Leonida translates to Vulkan. The ABI facts carry over, the forwarding architecture does not. - -## holdmysocks/SixNG - - - -A Rust extractor for the same package: models, textures, map placements, collision, navmesh, the lane graph and -audio, with format notes in its module headers. - -**Licence:** GPL-3.0, compatible with this project's GPL-3.0-or-later. As with SCARAB, **facts first**: nothing of -it is copied here. - -**What we use it for:** two navmesh facts, read in `crates/sixng-core/src/navmesh.rs` at commit `0619601` and -re-measured on this package by `tools/navmesh_nodes.py` -([navmesh.md](navmesh.md#polygon-flags-under-the-lane-graph)): its label "road surface" for polygon `+0x18` bit -13, which it bases on a visual check, and the vertex formula `tile minimum + u16 / 65535 * extent`. The formula is -confirmed by the lane-graph heights. The label is consistent with the count, but not settled by it: nine in ten -lane nodes stand on polygons with both bit 8 and bit 13, and which bit or combination means road surface is open. - -## microsoft/libHttpClient - - - -Microsoft's HTTP/WebSocket library for GDK titles. Its `Source/Task` folder is the implementation of the GDK's -`XTaskQueue` and `XAsync`. - -**Licence:** MIT, which is compatible with GPL-3.0-or-later. - -**What we use:** the task queue's headers and Win32 sources, copied unmodified into `third_party/xtaskqueue` (commit -and file list in its README) with the licence file. `runtime/shims/xgameruntime.cpp` registers those functions as -`xgameruntime.dll` imports. The HTTP and WebSocket stack is not included. Unlike the projects above, this is code -use under a compatible licence, so the MIT notice must stay with the files. - -## AMD machine-readable GPU ISA specification - - (reader: ) - -AMD's XML description of the RDNA and CDNA instruction sets: instructions, encodings, operands, data formats. - -**Licence:** MIT (`MIT` in each XML file; `isa_spec_manager` is MIT too), compatible with -GPL-3.0-or-later. - -**What we use it for:** `tools/isa_coverage.py` reads `amdgpu_isa_rdna2.xml` from a path the user supplies and counts -which instructions the translator has a rule for ([isa_coverage.md](isa_coverage.md)). The XML is not vendored (11 MB); -tests use a small fixture of our own in the same schema. - -## Mesa (AMD register database and format tables) and LLVM's AMDGPU backend - - (`src/amd/registers/*.json`, `src/amd/common/ac_descriptors.c`), - (`llvm/lib/Target/AMDGPU/SIDefines.h`) - -**Licence:** Mesa's AMD code is MIT, LLVM is Apache-2.0 with LLVM exceptions. Both are GPL-3.0-or-later compatible, -but nothing is copied. - -**What we use:** field positions and enum values, written into this repository's own code. `tools/hw_oracle/tsharp.py` -builds the T# for the hardware oracle of `tools/image_fuzz.py` from Mesa's SQ_IMG_RSRC_WORD1..4 bit ranges -(`gfx10-rsrc.json`, `gfx11-rsrc.json`), the way `ac_build_gfx10_texture_descriptor` and `ac_set_mutable_tex_desc_fields` -fill them (linear images carry their pitch in WORD4), and the GFX10 and GFX11 format numbers (Mesa's `GFX10_FORMAT`, -and for GFX11 the order of LLVM's `UfmtGFX11::UnifiedFormat`). The GFX11 numbers were confirmed on a gfx1150 by the -hardware oracle itself (a wrong FORMAT changes the fetched words); the GFX10 numbers and layout are Mesa's and not yet -run on RDNA2 hardware. - -## The line - -| Fine | Not fine | -|---|---| -| A format layout, field offset or enum value | Copying the function that parses it | -| An ABI measurement (slot number, return register, flag word) | Copying the proxy, thunk or struct definitions | -| A behaviour observed by running a tool | Copying comments, identifiers or test code | -| A public specification or vendor documentation | A line-by-line port, a translated port, or a "cleaned up" copy | -| A table of facts you rebuilt from your own observations | A table copied from the source, even with renamed columns | - -A table of constants is still expression. Rebuild it from your own measurements or a public specification. A -struct definition is still expression even if the field names are changed. If the only way to use a fact is to -copy the surrounding code, stop and find the fact another way. - -When in doubt: - -1. Write down the fact, not the code. -2. Cite the project and the section or file where you read it. -3. Verify the fact against the game package, a public specification or a test of your own. -4. Implement it independently, in this repository's style. - -Never paste code from either project into a pull request, an issue, a commit message or a chat log that becomes -part of the repository history. If a contribution was written while looking at incompatible source, say so in the -pull request so the provenance can be checked. - -Other dependencies keep their own licences; see the Credits and License sections of [README.md](../README.md). diff --git a/docs/resource_names.md b/docs/resource_names.md deleted file mode 100644 index d9272cb79..000000000 --- a/docs/resource_names.md +++ /dev/null @@ -1,69 +0,0 @@ -# Named RPF9 resources - -RPF9's table of contents is encrypted, so resource names cannot be read from the directory. They -are still present in the inflated stream data: a drawable is spelled `name.#dr`, a fragment -`name.#ft`, a drawable dictionary `name.#dd`, and so on. `tools/rpf9_names.py` walks the data area -like `rpf9_carve.py`, inflates a bounded prefix of each zlib stream, and indexes those names with -their archive offsets. - -This is a lookup pass, not a decoder. It does not need the TOC, does not decode models or -animations, and does not write any game data into the repository. The JSON index is local scratch. - -## Usage - -```text -python -I tools/rpf9_names.py [--start N] [--limit BYTES] - [--max-inflate BYTES] [--types dr,ft,dd] [--quiet] -``` - -- `--start` defaults to the data start in the RPF9 header. -- `--limit` bounds the pass; no limit scans to the end of the archive. -- `--max-inflate` is the prefix inspected per stream (default 1 MiB). -- `--types` selects the resource suffixes; the default is `dr,ft,dd`. - -The output has a `summary` and one `files` row per stream that contains a matching name: - -| Field | Meaning | -|---|---| -| `offset` | archive offset of the zlib stream | -| `stored` | compressed stream length | -| `size` | inflated stream length | -| `names` | matching full names in that stream | -| `streams` | every zlib stream accepted by the walk | -| `streams_with_names` | streams with at least one matching name | -| `name_hits` | total matching name occurrences | -| `unique_names` | distinct names across the pass | -| `by_type` | distinct names per suffix | -| `zero_padding`, `unread_bytes` | gap accounting, as in the carve tool | -| `bink2_files` | Bink 2 videos skipped whole | -| `bink2_bytes` | total bytes of those Bink 2 videos | - -## Measured pass - -Bounded runs against the 1.0.2.1 package validate the lookup: - -| Scope | Streams | Streams with names | Unique names | -|---|---:|---:|---:| -| `packs.rpf`, full | 144,364 | 27,292 | 12,338 (9,470 `#dr`, 2,865 `#ft`, 3 `#dd`) | -| `data.rpf`, first 256 MiB | 17,717 | 24 | 274 (`#dr`) | -| `packs.rpf`, player head window (2 MB) | 44 | 21 | 15 (`#dr`) | -| `packs.rpf`, brabikini window (2 MB) | 33 | 14 | 6 (`#dr`) | -| `packs.rpf`, Lucia head window (2 MB) | 36 | 16 | 6 (`#dr`) | -| `packs.rpf`, hand window (2 MB) | 21 | 9 | 4 (`#dr`) | -| `packs.rpf`, feet window (2 MB) | 62 | 28 | 11 (`#dr`) | -| `packs.rpf`, undies window (2 MB) | 74 | 33 | 12 (`#dr`) | - -The character windows contain the same head/eyes/eyecap, hand, feet, brabikini and undies drawable -records found by the earlier manual scan, which is the validation that matters for targeted -extraction. The generated index is local scratch because it contains game names. - -## Limits - -- Only the first `--max-inflate` bytes of each stream are inspected; a name after that prefix is - not found. The default is deliberately larger than the measured name tables. -- The scan is a zlib-stream walk, not a TOC read. Streams that are not clean zlib (raw blocks) - are skipped and counted in the gap accounting. Bink 2 videos are skipped whole and counted in - `bink2_files` / `bink2_bytes`. -- Names are data, not proof that a resource is usable: a matching stream still has to be decoded by - `rpf9dump` or `RageModelDecoder`. -- Counts are package/version-specific. The output index is local and must not be committed. diff --git a/docs/restofworld.md b/docs/restofworld.md deleted file mode 100644 index ae2bb90c3..000000000 --- a/docs/restofworld.md +++ /dev/null @@ -1,979 +0,0 @@ -# Rest-of-world and script archives - -This page measures the six rest-of-world/script archives in the Xbox 1.0.2.1 package: -`core_restofworld.rpf`, `story000_restofworld.rpf`, `story000_script.rpf`, -`core_restofworld001.rpf`, `appdata0.rpf` and `core_licenses_data.rpf`. The two story archives also -appear in the story report; this page re-measures them with the same corrected carver and adds the -1.21 GiB `core_restofworld`, the three small archives, and the cross-checks. It is a container survey, -not a resource decoder. The RPF9 tables of contents are still encrypted, so every count comes from the -data area or from a fixed header, never from a path or file name. - -All six archives were scanned end to end with the corrected carver from PR #90 (`--index-only`, which -advances by the actual stream length). The largest is 1.21 GiB, so no archive needed a bounded window. -Everything below is aggregate; no game payload, asset name or path is stored in this repository. - -## Archives and full index - -Sizes are exact bytes from the package. `data offset` is the little-endian u32 at file offset 4. The -readable fraction is the carver's `stored / span`; Bink 2 streams count as readable. - -| Archive | File size | Data offset | Streams | Stored | Inflated | Zero padding | Unread | Readable | Elapsed | -|---|---:|---:|---:|---:|---:|---:|---:|---:|---:| -| `core_restofworld.rpf` | 1,295,760,752 (1.21 GiB) | 0xAA0 | 2,381 | 1,293,131,069 | 1,355,861,220 | 2,410,297 | 216,666 | 99.8% | 1.9 s | -| `story000_restofworld.rpf` | 198,354,992 (189.17 MiB) | 0xA40 | 631 | 188,163,116 | 255,343,231 | 862,330 | 9,326,922 | 94.9% | 1.3 s | -| `story000_script.rpf` | 78,023,728 (74.41 MiB) | 0x2B0 | 2,632 | 20,408,094 | 74,729,504 | 4,585,959 | 53,028,987 | 26.2% | 3.9 s | -| `core_restofworld001.rpf` | 791,984 | 0x3B0 | 33 | 734,650 | 1,575,059 | 47,232 | 9,158 | 92.9% | 0.1 s | -| `appdata0.rpf` | 8,880 | 0x360 | 0 | 0 | 0 | 0 | 8,016 | 0.0% | 0.1 s | -| `core_licenses_data.rpf` | 13,536 | 0x330 | 3 | 1,074 | 2,004 | 19 | 11,627 | 8.4% | 0.1 s | - -The six archives total 1,572,953,872 bytes. The three larger scans are all full-file; the three small -archives are also full, including the 8,016-byte data area of `appdata0`. "Unread" is the non-zero gaps -between streams that did not inflate, not empty space. - -## What each archive is - -| Archive | Byte-dominant payload | Models | Maps | Scripts | -|---|---|---|---:|---:|---:| -| `core_restofworld` | Bink 2 video, 95.8% of the data span; 958 streams start with a graphics block, 13 more contain one later, and 924 system pages carry model names | 37 decoded in the existing manifest; 433 unique name strings measured here | 0 | 0 | -| `story000_restofworld` | Bink 2 video 60.6% of the data span, then system pages and 101 `0DRP` metadata resources | 1 page with 3 `.#dr` strings; no decoded model | 0 | 0 | -| `story000_script` | `PSIN` metadata, 79.2% of inflated bytes | 0 | 0 | 0 validated container | -| `core_restofworld001` | 23 zero-prefix system pages plus 4 XML content manifests | 0 | 0 | 0 | -| `core_licenses_data` | 3 XML content manifests | 0 | 0 | 0 | -| `appdata0` | no readable stream; 100% unread | 0 | 0 | 0 | - -"Models" and "maps" are counts of validated resources, not guesses from a magic. The 37 -`core_restofworld` models are the existing model-manifest count in `docs/design.md`; the 924 name-bearing -pages are a larger upper bound on the page population, not 924 decoded models. - -## Payload composition - -### `core_restofworld.rpf` - -| Class | Streams | Stored | Inflated | Share of inflated | -|---|---:|---:|---:|---:| -| Bink 2 (`KB2n`) | 11 | 1,241,514,796 | 1,241,514,796 | 91.6% | -| Streams starting with a `42 40 00 00` block | 958 | 37,556,463 | 77,862,128 | 5.7% | -| zero-prefix system pages | 1,230 | 12,920,541 | 34,278,992 | 2.5% | -| other raw/page starts | 162 | 1,045,600 | 1,960,826 | 0.1% | -| `PSIN` | 6 | 50,402 | 142,056 | <0.1% | -| `0DRP` metadata | 1 | 35,489 | 65,536 | <0.1% | -| `RBF0` | 3 | 3,380 | 23,364 | <0.1% | -| XML | 10 | 4,398 | 13,522 | <0.1% | - -- **Video.** The 11 `KB2n` streams are all 1920x1080, with 450 to 9,776 frames; together they are - 1,241,514,796 bytes, or 95.8% of the archive's data span. They are the largest payload by far. - No Bink 2 stream from this archive is byte-identical to one in `story000_restofworld` (0 common - SHA-256 over the 11 + 7 stored bodies). -- **Models and pages.** 924 zero-prefix system pages carry 936 model-name strings (883 `.#dr`, 53 - `.#ft`; 433 unique strings), which is the same name-bearing system-page pattern used by the model - exporter. There are no `.#dd`, `.#td` or `.#txd` strings. The 958 streams starting with a - `42 40 00 00` block range from 256 bytes to 9.4 MiB each and total 37.6 MB stored / 77.9 MB inflated. The existing - model manifest reports 37 decoded `core_restofworld` models; the 924 name pages are not all complete - resources, so this page does not raise that count. -- **Metadata.** One standalone `0DRP` resource at offset 53,899,280 has version 122 and 16 at +0x20. - `world_index.py` classifies it as `meta`, not a map: 1 resource, 0 maps, 0 entities. Six `PSIN` streams - follow: five complete six-section chains and one partial `LSCH`+`LENM` stream before an unread gap. - Joining the standalone resource's continuation stream completes its `0x7a` tables (18 structs, 2 enums, - 18 blocks), while the five `LRSC` payloads are 80-byte `0DRP` + 122 summary records with zero at - `+0x08..+0x0f`, `0xbb`-filled pointer slots and 1-based `root_block` indices 7, 5, 7, 2 and 2 at `+0x10` - (within block counts 7, 5, 8, 3 and 2). The `u32` at `PSIN+8` is 257 on four of the six; it is not called - a version because it varies and the story report already found it unstable. -- **Schemas and text.** The three `RBF0` records name `CMovieSubtitleContainer` (2) and - `VfxTextureAtlasMetadataInfoMgr` (1). The 10 XML streams have the roots - `CDataFileMgr__ContentChangeSetDef` (8), `CDataFileMgr__ContentDef` (1) and `SSetupData` (1). They are - content definitions, not UI layout. -- **Containers.** The file has 11 `9FPR` headers that pass the measured check: the outer archive plus - 10 embedded header candidates; one sits at the data start (2,720), eight are 4 KiB-aligned, and one - is at 54,154,944. There is no `RSC8` or `RSC7` header anywhere in it. The 216,666 unread bytes include - the non-zero gaps around those headers. - -### `story000_restofworld.rpf` - -| Class | Streams | Stored | Inflated | Share of inflated | -|---|---:|---:|---:|---:| -| Bink 2 (`KB2n`) | 7 | 120,187,756 | 120,187,756 | 47.1% | -| zero-prefix system pages | 400 | 57,694,475 | 92,678,320 | 36.3% | -| `0DRP` metadata | 101 | 8,152,633 | 38,632,912 | 15.1% | -| other raw/page starts | 99 | 1,903,036 | 3,436,561 | 1.3% | -| clip streams | 3 | 94,250 | 137,024 | 0.1% | -| `PSIN` | 3 | 40,679 | 104,080 | <0.1% | -| text | 3 | 28,330 | 60,064 | <0.1% | -| `42 40 00 00` resource page | 1 | 44,718 | 58,880 | <0.1% | -| type-hash page | 1 | 11,532 | 31,760 | <0.1% | -| XML | 13 | 5,707 | 15,874 | <0.1% | - -- The seven Bink 2 streams are 120,187,756 bytes, 60.6% of the data span: five 720x1280 and two - 1920x1080, with 425 to 3,192 frames. This is a vertical-video/extra-content archive as much as a - resource archive. -- The 101 `0DRP` streams are all version 122. Their +0x20 counts range from 1 to 37 and sum to 1,662 - pages. `world_index.py` classifies all 101 as `meta`, not maps: 101 resources, 0 maps, 0 entities. - The 400 zero-prefix system pages account for 92.7 MB inflated. Only one page has model-name strings - (3 `.#dr` names), so this is not a model archive. -- The three `PSIN` stream starts are 2 single-stream chains and 1 multi-stream container that completes - across four contiguous continuation streams (321,992 inflated bytes total), giving 3 complete `LRSC` - payloads alongside the 101 standalone `meta` resources (36 single-stream, 65 joined with one continuation - stream). The 13 XML streams are again content definitions (11 change-set, 1 content-def, 1 `SSetupData`); - the three text streams are 59,848, 146 and 70 bytes; the three clip streams have the measured - `u32 2/3 + 01 01 00 00` header. -- The 19 `9FPR` headers are the outer archive plus 18 nested headers on 4 KiB boundaries. The 9.33 MB - unread region holds nine `RSC8` headers (version 8001, flags 1, declared size 4,852-13,764, sum - 71,380) between offsets 70,697,336 and 70,877,704, but no `RSC7`. In these nine headers the bytes at - +0x30 are zero and the first `0x50xxxxxx` pointer is at +0x48; this page does not claim a name field - at +0x30. - -### `story000_script.rpf` - -| Class | Streams | Stored | Inflated | Share of inflated | -|---|---:|---:|---:|---:| -| `PSIN` | 2,309 | 14,484,253 | 59,151,216 | 79.2% | -| other raw/page starts | 258 | 4,704,587 | 11,970,376 | 16.0% | -| zero-prefix system pages | 65 | 1,219,254 | 3,607,912 | 4.8% | - -`PSIN` dominates; no compiled-script container was found. The measured header and chain are: - -``` -+0 "PSIN" -+4 big-endian first-section offset (points at LSCH) -+8 u32, 261 on 1,771 streams; 77/265/264 on the next 517; 21 other values -+12 u32, the hash-table byte count -... -record: 4-byte tag + big-endian u32 total size (includes the 8-byte record header) -``` - -| Tag | Sections | Size range | Median | -|---|---:|---:|---:| -| `LSCH` | 2,160 | 2,440-7,464 | 4,200 | -| `LENM` | 2,156 | 376-5,968 | 728 | -| `LSNS` | 2,118 | 68-17,204 | 1,804 | -| `LGID` | 2,118 | 8 | 8 | -| `LRSC` | 2,118 | 88 | 88 | -| `CHKS` | 2,118 | 20 | 20 | - -Of the 2,309 containers, 2,118 have all six sections in a single stream, 38 have `LSCH`+`LENM`, 4 have -`LSCH` only and 149 cross a stream boundary before their first section. An all-offset scan finds 2,275 -`0DRP` occurrences in the inflated set, and all 2,275 are `PSIN` `LRSC` records (0 standalone `0x7a` -resources): 2,118 in single-stream containers, 152 in contiguous multi-stream `PSIN` continuations and 5 -in `LRSC`+`CHKS` stream tails after an unread gap. The tag/length chain is contiguous and ends at `CHKS`, -which is the same layout measured for `script.rpf`. The `LSNS` payload is high-entropy (5.228-7.990 -bits/byte, median 7.888) and none of the 2,118 payloads decompresses with zlib; its block layout (a block table -and 16-byte records) is decoded in [psin.md](psin.md#lsns), the record contents are not. No `SCRP`, `YSC`, -`RSCC`, `RSC8`, `RBF0`, `FSSM` or Bink magic occurs anywhere in the inflated set. One of the 258 raw -streams begins with `LSCH` but has no `PSIN` header; it is a fragment, not a container. - -The 65 zero-prefix streams are 3.6 MB inflated. The remaining 258 raw streams are 226 distinct -first-eight-byte classes, 4.7 MB stored / 12.0 MB inflated; no recognised container starts them. -The archive has 5 `9FPR` headers: the outer archive plus four nested headers at 4,096; 98,304; -51,539,968 and 77,819,904. The 53,028,987 unread bytes (68.0% of the data span) contain those nested -archives and their high-entropy payloads. They are not decoded and are not guessed to be bytecode. - -### `core_restofworld001.rpf`, `appdata0.rpf` and `core_licenses_data.rpf` - -- `core_restofworld001.rpf` has 33 streams: 23 zero-prefix system pages (686,469 stored / 1,507,952 - inflated), 6 other raw streams (46,599 / 63,872) and 4 XML streams (1,582 / 3,235). The XML roots are - 2 `CDataFileMgr__ContentChangeSetDef`, 1 `CDataFileMgr__ContentDef` and 1 `SSetupData`. There is one - nested `9FPR` at 4,096. There is no `PSIN`, `0DRP`, Bink, model-name string or map. It is a small - content-manifest/page supplement. -- `appdata0.rpf` has the outer `9FPR` header and an 8,016-byte data area with no complete zlib stream, - no Bink and no nested `9FPR`. The data area is 2,751 zero bytes and 2,036 printable bytes with an - entropy of 6.155 bits/byte; no ` \odrp.json -python -I tests/test_odrp_7a.py -``` - -## Readable versus opaque - -Readable: the RPF9 header and data offset, zlib streams, Bink 2 headers, XML content definitions, -`PSIN` tag/length chains, `0DRP` version and count fields, `RBF0` schema strings, and model-name -strings in system pages. - -**Vertex blocks on graphics pages (ASSET-57).** In core rest-of-world, 958 inflated streams -start with the target header and another 13 reach it after earlier chunks. In all 971, the -first 23 little-endian words contain tagged stream locations: for a populated slot, -the low byte is the tag and twice the upper 24 bits gives the byte offset from the block -start. Slot 0 starts at +0x80. Sorting the populated slots by offset gives positive spans. - -The independent check is the meshlet group following the streams. To locate a candidate -group, take the greatest common divisor of the adjacent stream spans, try one through four -times that unit for the final span, then round up to 16 bytes across zero padding. -In 553 blocks the following group fits and validates: meshlet base offsets match the running -vertex-reference and triangle counts, and every packed triangle identifies its meshlet and -uses local indices within range. In 535 of these blocks the referenced indices cover -every integer from zero through the maximum, and each adjacent span divides exactly by -the size of that range. For all 535 the measured span per referenced vertex is **8 bytes -for tag 0x42** and **4 bytes for tags 0x21, 0x25, 0x26, 0x27 and 0x28** wherever -present with a measured successor. This supports separate vertex streams. It leaves the -component types, final stream width and blocks without an independent count unresolved. - -Across all 22 accessible RPF9 archives, a full data-area scan using the four zlib -headers from #752 accepted 2,241,411 streams at checksum-validated EOF. There were -309,007 target page starts and 41,342 streams in which a chunk walk reached the -target later. Each stream contributes at most its first target block. Of these -350,349 blocks, 350,348 passed the slot bounds and positive-span checks, 108,342 -had a validated following meshlet group, and 62,207 also had dense references and -integral span quotients. The recurring widths below account for 61,896 of those -blocks. Each row counts blocks with a measured successor for that tag. - -| Slot tag | Bytes per referenced vertex | Supporting blocks | -|---|---:|---:| -| 0x42 | 8 | 61,896 | -| 0x21 | 4 | 59,308 | -| 0x25 | 4 | 21,837 | -| 0x26 | 4 | 60,480 | -| 0x27 | 4 | 18,030 | -| 0x28 | 4 | 31,164 | -| 0x8c | 16 | 3,391 | - -Of the 61,896, core rest-of-world contributes 535, minigame 263, full story 110, -story rest-of-world 1 and the other archives 60,987. Full story alone has 5,589 -target starts and 1,523 continuations. The 311 other integral cases give different -quotients. A dense range measures the vertices used by the following group and can -miss vertices used elsewhere. The outlier analysis below checks those counts. The survey counts -stream occurrences, including duplicates, and excludes opaque data and encrypted -directory contents. - -**Integral outliers.** Comparing each measured adjacent span with the following -group's dense reference count times the recurring width for its tag gives a -single ratio per block: all measured tags in that block scale together. The -61,896 controls have ratio 1. Among the 311 outliers (62 distinct sets of -tag/quotient pairs), 193 have ratio 1/4, 59 have 1/2, eight have 3/4 and -51 have a ratio above 1. These counts include every integral case once. - -For the 260 ratios below 1, the first stream alone cannot hold all vertices -referenced by the following group at eight bytes each. Missing references or -positive padding cannot explain that shortfall. For the 51 above 1, a group -using only part of a block is possible. In both directions, a common scale -across tags also fits a different vertex count. It does not establish a new -encoding for any tag. The final stream has no measured successor and is -excluded from this comparison. - -Dividing each adjacent span by its tag's recurring width gives the same -positive integer count within each of the 311 blocks. A scan of every other -16-byte-aligned group header in the same inflated page, using the meshlet -checks above, found a second group whose references cover exactly that count -in **230 blocks** (222 of the 260 short cases and eight of the 51 long cases). -This independently corroborates the proposed count on those pages. It leaves -**81 blocks** without a second count match: 48 have another validated group -but no match, and 33 have no other validated group on the page. Even an exact -match does not identify which block a group draws from. - -For each of those 81, scan the immediately preceding and following -checksum-validated zlib streams in the same archive, in stored order, without -skipping intervening stream types. Use the same aligned group validation and -require dense references from zero through the proposed count minus one. -All 81 have an exact match on one side only: 66 in the preceding stream and -15 in the following stream. As a distance check, repeating the test two streams -away on either side yields matches for four of the same 81. - -Together, 230 same-stream and 81 adjacent-stream matches corroborate the -recurring-width count for **all 311 outliers**. The 61,896 original controls -remain a separate count because their immediately following group supplies -the matching range. No outlier had a control with the same header and bytes -through the last measured span. Applying the recurring widths to the final -slot as a separate check lets a chunk walk consume the whole stream in 219 -outlier cases. Only six of those walks have a one-to-one count match between -all blocks and dense groups, with a unique match for the target block. -Count agreement therefore supports the widths across the outlier set while -leaving the draw-to-block mapping unresolved. - -Rounding each measured stream's size up to 16 bytes using the following -group's count and the recurring widths fits zero of the 311 blocks. Padding -after the final stream cannot change the earlier spans. In three blocks, the -four candidate final lengths lead to more than one distinct validated group -offset. The original first-match rule is retained for the counts above. -The page-only survey supplies no reason to introduce an alternate per-tag format. - -**Draw ownership from system metadata.** A geometry record supplies two independent -resource-relative addresses. Following the pinned `RageModelDecoder.ReadMesh` layout, -geometry +8 points to the vertex buffer and geometry +64 points to the meshlet -descriptor, whose first pointer selects the index buffer. Each buffer's +24 pointer -addresses the complete inflated graphics segment, including when its target is in -another compressed stream. The vertex layout supplies the count separately. The -descriptor supplies meshlet, triangle and reference counts that must agree with the -pointed-to group's header. This check also validates the packed triangles, vertex -reference bounds and padded index-buffer length. - -The original check found one distinct validated group address for each of the -311 target blocks. The regular drawable LOD lists reached 303. For the other -eight, a search of aligned system records found the same pointer layout and a -geometry list containing the record. The layout count and the group's dense range -agreed in all 311. This includes the six uniquely paired page walks and seven -walks with a repeated target block count. - -**The eight auxiliary root paths (ASSET-273).** An independent scan of all 22 -archives reproduced 311 outliers and verified all 311 draw bindings. The regular -drawable lists reached 264 blocks through LOD 0 and another 39 through LODs 1–3. -The eight records reached through auxiliary paths each have a verified geometry -record and graphics-group address: - -- **Seven standalone drawables:** follow the root drawable's pointer at `+0xD0`. - In the auxiliary header, `+0x30` points to a table of system pointers and - `+0x38` holds its 16-bit count, which matched capacity in these cases. Each - relevant table entry points to a record whose `+0x68` field leads to the - structure with the geometry list at `+0x50`. -- **One fragment:** start with the fragment root's pointer at `+0x90`, then - follow pointer fields at `+0x130`, `+0x20` and `+0x70`. In that table, entry 1 - (zero-based) reaches the record whose `+0x68` pointer leads to the structure - with the geometry list at `+0x50`. These offsets are one measured route. - -One regular LOD 0 binding needs a compressed final system page that inflates to -48 bytes. The diagnostic scan's 64-byte minimum excluded that page. When the -first page's map declares the final system continuation, the archive diagnostic -accepts a nonempty short page at the next 16-byte boundary with zero padding -and a valid zlib checksum. That restores the normal draw binding. Both the -diagnostic and the pinned model reader recover the containing dictionary's 11 -children. - -`rpf9_carve.py` and the carved-folder model join use the same short final-system-page -exception, so a carve retains that page and can reproduce the archive join. Unrelated -streams still need at least 64 inflated bytes. When a carve has an `index.json`, the folder join uses its file list, offsets, -compressed sizes and preceding bytes to check root alignment and zero padding just -as the archive join does. An omitted stream between pages therefore interrupts the -join. Extra files are ignored, and missing indexed files or size mismatches are errors. -The index describes the original archive and cannot authenticate a same-size replacement -payload. Without an index, folder mode still uses file order and inflated file sizes -and can join across bytes the carver omitted. -The folder reader follows the carver's file types: `.bin` contains an inflated zlib -payload and `.bk2` contains raw video. A `KB2` prefix inside a `.bin` remains resource -data, while a raw `.bk2` interrupts the model's continuation run. - -| Pointed-to group start relative to the target stream (original survey) | Blocks | -|---|---:| -| Preceding stream | 68 | -| Same stream | 228 | -| Following stream | 15 | - -Two of the 230 same-stream count matches have their descriptor-selected group -in the preceding stream. A count-only association would therefore choose a -different group even with an exact match in hand. - -For an already separated system/graphics resource pair, the following command -walks the primary LOD from the drawable offset reported by the model manifest. -Use `--lod 1`, `--lod 2` or `--lod 3` with the same drawable offset to select a -lower LOD, or use `--geometry-offset` for a known individual geometry record. -Both offsets are relative to the start of the system segment. Unsupported or -inconsistent bindings are reported as unresolved. - -```powershell -python -I tools/meshlet_page.py --draw-system --drawable-offset -``` - -**System-to-graphics model-page join (ASSET-157).** `tools/restofworld_model_join.py` joins model system pages to -their owning graphics pages directly from an RPF9 archive or a carved stream directory without the encrypted TOC. -The earlier 37-model figure came from `rpf9dump` at `48557ea`, before `pgDictionary`, optional-pointer -fragment and zero-radius drawable support (`e293917`; see [models.md](models.md)). Four in-band structural rules -pair every model resource unambiguously: - -1. **Top-level framing and root header.** In an RPF9 data area, every top-level resource starts on a 4,096-byte - boundary plus `0x10` (`(offset & 0xFFF) == 0x10`) preceded by 16 zero bytes, with `u64@+0x00 == 0` and a - `0x50000000`-based system pointer at `+0x08` (`+0x10..+0x13 != "0DRP"`). Root headers separate into standalone - `rmcDrawable`, `fragType` (`fragment`), `pgDictionary` (`drawable_dict`), standalone - `pgDictionary` (`140` in `core_restofworld.rpf`: `115` `1+1`, `25` `1+2`), and `44` other non-model - system resources. -2. **In-band `datResourceMap` page counts.** At `page_map = u64@+0x08 - 0x50000000`, `u32@+0x00 == 0`, - `u32@+0x04 == 0`, `u8@+0x08 = system_pages`, `u8@+0x09 = graphics_pages`, `u16@+0x0A == 0`, and `u32@+0x0C == 0`, - followed at `+0x10` by `system_pages + graphics_pages` zero-initialised `u64` runtime page-base slots (`924 / 924` - in `core_restofworld.rpf`, `1 / 1` in `story000_restofworld.rpf`). When `system_pages > 1`, `page_map` lies in the - final system stream after concatenating preceding 64 KiB system streams. -3. **Contiguous 16-byte-padded runs and 64 KiB blocking.** Each resource owns `system_pages` contiguous zlib streams - followed immediately by `graphics_pages` contiguous zlib streams, with `0..15` zero padding bytes at every - internal boundary (`924 / 924`). Every non-final system stream (`2 / 2`) and every non-final graphics stream - (`96 / 96`) inflates to an exact multiple of 64 KiB (`(size & 0xFFFF) == 0`); the trailing `graphics_pages == 2` - continuation stream ranges from `656` to `63,520` bytes. -4. **Cross-page LOD, vertex-block and meshlet validation.** Across all four LOD slots (`+0x50..+0x68`) of every - drawable (`583` 1-LOD, `287` 2-LOD, `25` 3-LOD, `41` 4-LOD), `vb+0x18` (`0x60000000`-based) lands on a `0x42` - (`(8, 16)`) or `0x63` (`(12, 6)`) vertex block whose byte span covers `u32@(fvf+0x138) >> 10` vertices, and - `geo+0x40` lands on a meshlet index buffer whose cluster count (`countFlags & 0xFFFF` when bone-palette bit - `0x40000000` is set, else `countFlags & 0x7FFFFFFF`), 8-bit per-cluster triangle counts (`((packed >> 7) & 0xFF) + 1`), - running offsets, packed triangle indices and vertex references all match the system descriptor and reach into the - final declared graphics page (`924 / 924`). - -| `core_restofworld.rpf` model class | Resources | `1+1` | `1+2` | `2+2` | System streams | Graphics streams | Drawables | Primary-LOD tris | All-LOD tris | -|---|---:|---:|---:|---:|---:|---:|---:|---:|---:| -| `drawable_dict` (`795` x 1 child, `1` x 13) | 796 | 740 | 56 | 0 | 796 | 852 | 808 | 743,663 | 1,158,313 | -| Standalone `drawable` | 75 | 58 | 16 | 1 | 76 | 93 | 75 | 312,068 | 369,031 | -| `fragment` | 53 | 30 | 22 | 1 | 54 | 75 | 53 | 183,865 | 301,456 | -| **Total joined (`0` unjoined)** | **924** | **828** | **94** | **2** | **926** | **1,020** | **936** | **1,239,596** | **1,828,800** | - -The join accounts for both page populations in full: - -- **System pages (`926` streams, `924` name-bearing):** all `922` single-system-page resources carry their `.#dr`/`.#ft` - name strings in `sys_page0`, while the two `2+2` resources (`1` standalone drawable `[131,072, 3,728]` and `1` - fragment `[65,536, 9,680]`) hold root and geometry structures in a nameless 64 KiB-multiple `sys_page0` and place - their name strings and `datResourceMap` tails in `sys_page1` (`922 + 2 = 924` name-bearing zero-prefix pages; - `936` drawables = `883` `.#dr` + `53` `.#ft`, `849` bone-bound, `75` with an empty embedded texture dictionary). -- **Graphics pages (`1,020` streams):** all `924` `gfx_page0` streams start with `42 40 00 00`, and the `96` - `gfx_page1` continuation streams split into `34` `42 40 00 00` starts plus `62` meshlet-led starts (`924 + 34 = 958`, - claiming **958 / 958** `42 40 00 00`-start streams in the archive). All **13 / 13** streams that reach a - `42 40 00 00` vertex block after earlier meshlet groups (`8` standalone drawables, `5` fragments) sit inside those - `62` meshlet-led `gfx_page1` continuations (`47` `gfx_page1` streams carry a pointed-to `42 40 00 00` block; `49` - hold meshlet groups only). Primary-LOD geometry totals (`1,177` geometries, `1,001,667` vertices, `1,239,596` - triangles) match [models.md](models.md) to the triangle; all LODs total `2,021` geometries and `1,598,782` vertices. -- **Other rest-of-world archives:** `story000_restofworld.rpf` joins **1 / 1** model resource (`drawable_dict`, `1+1`, - `3` child drawables, `3` geometries, `1,808` vertices, `2,620` triangles, claiming **1 / 1** `42 40 00 00`-start - stream); `core_restofworld001.rpf` has `0` model candidates and `0` `42 40 00 00` streams. - -```powershell -python -I tools/restofworld_model_join.py \model_join.json -python -I tools/restofworld_model_join.py \carve\ \model_join.csv -python -I tests/test_restofworld_model_join.py -v -``` - -**Component types (full corpus).** `tools/vertex_types.py` (at `1aef69e`, with the running-sum fix to -`group_edges`) was run over the seven archives that hold target blocks: `data`, `packs`, `levels`, `story000`, -`core_restofworld`, `shared_minigame000` and `story000_restofworld`. It measures a block only when the -following meshlet group covers it densely, so it uses **60,442 blocks** (138,929,728 vertices, -282,704,362 triangle edges) out of the 309,007 target streams; the rest are skipped as "no group" (225,795) -or "not dense" (22,769), plus one single-stream block. The run before that fix gave the same block and vertex counts and 3,300 fewer -edges, so none of the conclusions below depend on it. - -| Measure | Result | -|---|---| -| `+0x5C` flags word | `0x200` in all 60,442 | -| `+0x7C` float | 4.0 in all 60,442 | -| `+0x6C` axis word | 2: 30,017, 1: 16,718, 0: 13,707 | -| Position header (bias, scale) finite, scale >= 0 | 60,442 / 60,442 | -| Every triangle edge no longer than the block extent | 48,150 / 60,442 | - -**Slots 6/7 (tag `0x26`) and 8/9 (tag `0x25`) are skin weights and joint indices.** Where slot 8 holds tag -`0x25`, each `0x25` slot comes with a `0x26` slot two below it (slot 6 with 8, slot 7 with 9), and no block in -the sample has one without the other. Read as four unorm8 weights per `0x26` slot and four joint indices per -`0x25` slot, `skin_checks` in `tools/vertex_types.py` counts, per vertex over all weight slots -(core_restofworld, first 500 streams: 612 blocks, 212,564 vertices; 454 blocks with two pairs, 158 with one): - -| Check | Vertices | -| --- | --- | -| Weights sum to 255 | 203,243 (95.6%) | -| Weights sum to 247-255 | 204,758 (96.3%) | -| Weights in descending order | 211,902 (99.7%) | -| No joint repeated among the non-zero weights | 212,564 (100%) | -| Every zero weight has joint index 0 | 156,808 (73.8%) | -| Control: slot 1 colour bytes sum to 255 | 0 | - -The `0x25` bytes are small: the highest joint used by a non-zero weight is below 16 in 488 blocks, 16-31 in -117 and 48-63 in 7. So the indices point into a short per-block (or per-mesh) joint list, not a whole -skeleton; which list was not traced here. - -Of the 9,321 core_restofworld vertices whose weights do not sum to 255, the twelve most common sums (254 -down to 233) all come from one-pair blocks: a four-influence vertex whose weights fall short, as -`tools/skin_streams.py` also finds for one packed four-influence population of the drawable skin streams. -levels (first 400 streams) has 9 skinned blocks (3,910 vertices), all one pair, and every vertex there -passes: one weight of 255 on joint 0. The colour control never sums to 255 in either sample. - -Slot usage (block counts): slot 0 tag `0x42` in all 60,442; slot 2 `0x21` in 57,925; slot 1 `0x26` in -57,873; slot 3 `0x28` in 49,294 and slot 4 `0x28` in 29,379; then slot 12 `0x26` (25,239), slot 6 `0x26` -(24,876), slot 8 `0x25` (21,519), slot 13 `0x26` (17,928), slot 11 `0x27` (11,120) and 21 rarer slot/tag -pairs, including `0x84` and `0x4b` in slot 17 (5,452 and 3,714). - -**What the skinned mesh shaders read from slots 6, 8 and 17 (shader reading; slot 17 is only partly -checked on the data).** The 363 mesh shaders that contain a `BUF_FMT_16_16_16_16_UINT` load take each -stream's type from the low four bits of a per-slot descriptor word in a constant buffer (one dword per -slot: `+0x18` is slot 6, `+0x20` slot 8, `+0x44` slot 17; stride `((w >> 3) & 60)` bytes). They choose -the load from that type: - -| Slot | Type | Load | -| --- | --- | --- | -| 6 | 6 (tag `0x26`) | `tbuffer_load_format_xyzw ... BUF_FMT_8_8_8_8_UNORM` | -| 6 | other | `buffer_load_dwordx4` (four raw dwords) | -| 8 | 5 (tag `0x25`) | `tbuffer_load_format_xyzw ... BUF_FMT_8_8_8_8_UINT` | -| 8 | other (type 11 is tag `0x4b`) | `tbuffer_load_format_xyzw ... BUF_FMT_16_16_16_16_UINT` | - -198 of the 363 also read slot 17 with `buffer_load_dwordx2` (the first 8 bytes): - -- u16 0 bit 15 set: that vertex skips the step. -- Otherwise u16 0 is an element index, checked against a count from a table. -- That element's entry holds eight u16 point indices. -- u16 1-3 are three coordinates, each `v / 65535` (`v_mul_f32 0x37800080`). -- The shader fetches the eight points and blends them with the trilinear weights `(1-a)(1-b)(1-c)` ... `abc`. - -That is a deformation-lattice binding. - -On the data (core_restofworld, first 500 streams), slot 17's width follows the skin influence count: - -- All 338 blocks with tag `0x84` (16 bytes) have two weight/index pairs (slots 6-9, eight influences). -- All 121 blocks with `0x4b` (8 bytes) have one (slots 6 and 8, four influences). -- Bit 15 of u16 0 is set on 20,898 of 186,727 `0x84` vertices (11.2%) and 5,973 of 12,336 `0x4b` vertices - (48.4%). -- For `0x84`, bit 15 of the second 8 bytes' first u16 is set on 117,067 (62.7%). Those 8 bytes may be a - second binding, but no shader read of them was traced. - -Element indices are mostly unique per vertex (115,101 distinct non-flagged values over the 186,727 `0x84` -vertices), so few elements are shared by enough vertices to test the coordinates. In the 39 elements with -8 or more vertices, positions are an affine function of the three coordinates: the median rms residual is -1.6% of the block extent, against 25% with the coordinates shuffled within the element. That is consistent -with the reading, but too few elements to confirm it. In these samples no block puts tag `0x4b` in -slot 8. - -**Tag `0x28` is two signed 16-bit values.** Over the triangle edges of the slot 3 stream, a difference of more -than 0x8000 between neighbouring vertices occurs 1,597,530 times when the values are read as unsigned and -18,791 times when they are read as signed (85 times fewer); slot 4 gives 1,680,055 against 5,570. Read as -half floats, 1,391,311 slot 3 values are NaN or infinite. So the stream is a pair of `int16`s, continuous across -the surface, which fits the `x / 32767 * f32@0x7C` texture-coordinate reading. - -**Tag `0x27` is a second tangent frame: a unit tangent along `u` of another `0x28` stream, with a sign.** -The mesh shaders fetch it with `tbuffer_load_format_xyzw ... BUF_FMT_2_10_10_10_UNORM` (one of the -four typed vertex formats they use, in 2,162 of the 9,282 mesh shaders) and map every component by -`v * 2 - 1`. They transform xyz by the same matrix as the normal and cross it with the normal, scaled by -w. `tangent_0x27` in `tools/vertex_types.py` is that read: xyz = bits 0-9, 10-19, 20-29 over 1023, and -w = bits 30-31 over 3. Per `0x27` slot, `tangent27_checks` counts unit length over all vertices; over -the sampled triangles it counts vectors perpendicular to the face normal (`|cos| < 0.2`) and, for each -`0x28` stream, vectors within `cos > 0.8` of `dP/du` and the w side: - -| Sample | Slot | Vertices | Unit | w = 3 / 0 | Perpendicular to face | Best `0x28` stream: along u | w > 0 exactly when `cross(face normal, xyz)` runs along `-v` | -| --- | --- | --- | --- | --- | --- | --- | --- | -| levels (400 streams) | 11 | 637,604 | 100% | 634,431 / 3,173 | 86.1% | slot 4: 96.7% (slot 3: 69.5%) | 99.8% | -| core_restofworld (500 streams) | 18 | 182,208 | 100% | 180,282 / 1,926 | 40.3% | slot 14: 79.3% (slot 4: 73.6%, slot 3: 21.0%) | 99.2% | -| core_restofworld | 19 | 12,679 | 100% | 12,445 / 234 | 61.7% | slot 14: 69.0% (slot 3: 54.1%) | 98.5% | - -The w side is counted among the along-u vertices of that stream. The w field only ever holds 0 or 3 in -these samples. Against the vertex normal of tag `0x21` (read as the mesh shaders read it) instead of the -face normal, the slot-18 vectors are perpendicular (`|cos| < 0.1`) for 174,942 of 182,208 (96.0%) and the -slot-19 and levels slot-11 vectors for all of them. Where the face-normal column is low, the face normals -disagree with the vertex normals, as for tag `0x21`. The tangent matches the `0x21` tangent (`cos > 0.99`) -for only 10-17% of vertices, so it is a different frame, the one for a second texture-coordinate stream. - -**Tag `0x26` (slot 1) is four bytes with an alpha-like byte 3.** Byte 3 is 255 on 62.4% of the 137.9 million -vertices and 0 on 17.2%; each of bytes 0-2 is constant within a block in 36,544 to 38,854 blocks. The bytes -change smoothly over edges (block-weighted median edge/random difference ratio 0.18 to 0.27), as a colour or -blend weight would. As a packed normal it scores no better than random directions (below). - -**Tag `0x21` (slot 2) is an octahedral normal whose width depends on bit 31.** The face-normal check: for each -block the tool reads 256 sampled triangles and counts the vertices whose decoded vector is within `|cos| > 0.8` -of the face normal; random directions score 0.2. None of the 19 fixed decodings scores well over the whole -corpus (best block-weighted medians: unorm10 xyz 0.479, octahedral unorm8 bytes 0-1 0.331, the rest 0.13 to -0.31), because the stream mixes two encodings. The mesh shaders show which one each vertex uses (6,285 of the -9,282 mesh shaders contain the octahedral `v_sub_f32 ..., 1.0, |x|`): after -`buffer_load_dword` of the vertex word they branch on its sign. With bit 31 set they take x = bits 0-9 and -y = bits 10-19 (`v_and_b32 0x3ff`, `v_bfe_u32 ..., 10, 10`), map each by `v * 2/1023 - 1`, and unfold the -octahedron (`z = 1 - |x| - |y|`, the `-z` clamp added back with each sign, then `v_rsq_f32`). With bit 31 -clear they take bytes 0 and 1 (`v_cvt_f32_ubyte0/1`), map each by `v / 127.5 - 1`, and unfold the same way. -`normal_0x21` in `tools/vertex_types.py` is that decode (candidate `oct_bit31_10_or_8`). - -Scored separately on the first streams of two archives (core_restofworld: 120 streams, 143 blocks; -levels: 200 streams, 187 blocks), each class matches the face normals only under its own branch: - -| Vertices | Decode | core_restofworld p25 / median / p90 | levels p25 / median / p90 | -| --- | --- | --- | --- | -| bit 31 set | 10-bit octahedral | 0.53 / 0.73 / 0.98 | 0.89 / 1.00 / 1.00 | -| bit 31 set | 8-bit octahedral | 0.19 / 0.20 / 0.30 | 0.12 / 0.23 / 0.57 | -| bit 31 clear | 8-bit octahedral | 0.44 / 0.61 / 1.00 | 0.67 / 1.00 / 1.00 | -| bit 31 clear | 10-bit octahedral | 0.00 / 0.16 / 0.26 | 0.00 / 0.00 / 0.75 | -| all | both, by bit 31 | 0.53 / 0.63 / 0.96 | 0.89 / 1.00 / 1.00 | - -Bit 31 is set on 48,046 of the 60,600 sampled core_restofworld vertices (79.3%). Model axis order is the one -`+0x6C` gives for positions; the other five axis orders and sign flips of the decoded vector score 0.27 to -0.36 there. Some core_restofworld blocks score lower under the matching decode than levels blocks do; this -check does not say why. - -**The rest of the `0x21` word is the tangent frame.** The same mesh shaders go on to build a tangent. -With bit 31 set, bits 20-29 are an angle, `v * 2pi/1023 - pi` (`v_fma_f32` by 2pi/1023 and -pi, then -`v_sin_f32`/`v_cos_f32`), that turns a basis made from the normal alone (`s` = sign of z, -`a = 1/(s + z)`, `b1 = (s x^2 a - 1, s x y a, s x)`, `b2 = (x y a, y^2 a - s, y)`), giving -`tangent = b1 cos - b2 sin`. With bit 31 clear, bits 16-22 and 23-29 are a 7-bit octahedral tangent -(`v_bfe_u32 ..., 16, 7` and `23, 7`, each `v / 63.5 - 1`). Bit 30 (`v_lshrrev_b32 30` then `& 1`) is the -bitangent sign. Of the 6,254 mesh shaders with the bit-31 branch, 5,196 read bits 20-29, 5,191 read the -two 7-bit fields and 528 read bit 30. `tangent_0x21` in `tools/vertex_types.py` is that decode. - -The tool checks it against the first `0x28` stream (texture coordinates): per sampled triangle it projects -`dP/du` into each vertex's tangent plane and counts tangents within `cos > 0.8` of it ("along u"), the same -tangent turned by a random angle about the normal (chance level), and, of the along-u vertices, how often -bit 30 matches the side of `dP/dv` that `cross(normal, tangent)` points to: - -| Archive sample | Form | Vertices checked | Along u | Random angle | Bit 30 = bitangent side | -| --- | --- | --- | --- | --- | --- | -| levels (187 blocks) | 10-bit | 59,448 | 98.0% | 23.2% | 99.4% | -| levels | 8-bit | 411 | 83.2% | 22.6% | 98.8% | -| core_restofworld (143 blocks) | 10-bit | 52,153 | 86.3% | 22.3% | 97.8% | -| core_restofworld | 8-bit | 6,992 | 56.4% | 15.8% | 92.6% | - -Bit 30 set means `cross(normal, tangent)` runs along `+v`. The shaders turn a set bit 30 into the factor -`-1.0` (`v_cndmask_b32 ..., 1.0, -1.0`), so their bitangent is that factor times their own cross product; -which operand order they use was not traced here. The 8-bit form in core_restofworld fits least; -this check does not say why. - -An independent `data.rpf` sample says the tangent decode itself is not the weak part. On one mesh with all -809 triangles usable, the decoded 8-bit vector pointed toward increasing UV0 U on **1,992 of 1,992** eligible -corner uses; its median |dot| with the U tangent was **0.999598** (0.000025 with V and 0.027633 with the face -normal), and permuting the candidate vectors within the same mesh lowers the U median to 0.697877. Four -bit-31-clear resources from the first 12 qualifying ones in archive order gave **114 of 114** positive U -comparisons (median +0.987002). Bit 30 agreed with the side of `dP/dv` that `cross(normal, tangent)` points -to on **101 of 104** corner uses. All three exceptions are one indexed vertex whose five adjoining triangles -have three negative and two positive UV determinants while its stored bit stays set; a single per-vertex bit -cannot represent that vertex, so a consumer reconstructing a tangent frame should take handedness per -triangle or accept that documented exception. This does not by itself explain the lower core_restofworld -8-bit score above, whose per-block UV coverage was not measured here; the mixed-determinant vertex is one -candidate. - -Opaque: the encrypted RPF9 tables of contents, the Bink 2 bodies, the `LSNS` record contents, the bodies of the -`RSC8` headers, the nested RPF9 payloads, and the whole `appdata0` data area. Across the 971 -core graphics blocks, final-slot widths remain unresolved (`0x21`, the last unread component type, -is decoded above). The stride check -Opaque: the encrypted RPF9 tables of contents, the Bink 2 bodies, the `LSNS` record contents, the nested RPF9 -payloads, and the whole `appdata0` data area. The bodies of the nine `RSC8` headers are decoded in -[rsc8_audio.md](rsc8_audio.md): facial/lip-sync clips. Across the 971 -core graphics blocks, final-slot widths remain unresolved, and of the component types the non-normal -bits of `0x21` (see above). The stride check -also leaves 436 blocks unclassified, including 18 with a validated following meshlet group. -"Unread" in the tables above is not a claim that those bytes are empty: in -`story000_restofworld` the 9.33 MB unread gap contains 15 `ADAT` (AWC) banks (8,908,216 bytes), which hold the -nine `RSC8` headers as tag `0x5c` clips, and nested RPF9 headers, and -in `story000_script` the 53 MB unread region contains four nested RPF9 headers. - -## Likely format family - -The bytes support the existing **RPF9/RAGE family**, not a new container: - -- RPF9 data areas are zlib streams with embedded RPF9 sub-archives (10 nested in core, 18 in - story-rest, 4 in script; most sit on 4 KiB boundaries). -- Bink 2 video is `KB2n` and is separate from the resource pages; core is video-first, story-rest is - video plus metadata/pages. -- `0DRP` version 122 reuses one 80-byte header frame across two distinct placements: in a standalone - stream (`+0x10` after the 16-byte system prefix) it is a `0x7a` metadata resource with `0x50000000` - table pointers, while in a `PSIN` `LRSC` section it is an 80-byte root/count summary record with - `0xbb`-filled pointer slots. Neither form carries map-placement structs in these six archives. -- `PSIN` is a sectioned metadata container, not a compiled-script container. The six tags and the - big-endian length chain are measured; the `LSNS` block layout is decoded, its record contents are not. -- `RBF0` records carry schema names (movie subtitles, VFX texture-atlas metadata); XML records carry - content definitions. -- `RSC8` appears only in the story-rest unread gap, as the tag `0x5c` facial/lip-sync clips of its 15 - `ADAT` (AWC) banks ([rsc8_audio.md](rsc8_audio.md)). No `RSC7` was found. - -Models are present (37 decoded in core, plus 924 name-bearing pages), but the measured bytes do not -support a claim that these archives hold map placement, compiled scripts or UI layout. Their only audio banks -are those 15 in story-rest, with 76 streams: 13 carry a streamed-music `0x48` tag and 9 are dialogue lines with -a clip. A raw `tools/rsc8_audio.py` scan of the other five archives finds no `ADAT` bank. -The only UI-adjacent evidence is content-manifest XML and text; there is no UI container signature. - -## Content-definition reader (ASSET-149) - -`tools/content_definitions.py` reads the three measured XML roots: -`CDataFileMgr__ContentChangeSetDef`, `CDataFileMgr__ContentDef` and `SSetupData`. -It accepts local XML files or an existing `rpf9_carve.py` directory and prints only aggregate counts: - -```powershell -python -I tools/content_definitions.py /carve/story000_restofworld -python -I tools/content_definitions.py -python -I tests/test_content_definitions.py -``` - -The Python API `parse_content(byte_chunks)` returns a `ContentDocument` only after the entire document -parses successfully. Its `kind` is `change_set`, `content` or `setup`; its immutable `root` record preserves -ordered children, attributes, text and tails, including unknown fields, after normal XML normalization. -Comments and processing instructions are not configuration fields. The convenience views are: - -- `files`: ordered `fileList/Item` entries with `filename`, `file_type` and the original record. `contents`, - flags and future fields remain accessible through that record. -- `included_changesets`: ordered `includedChangesets/Item` records, including `loadPath` and include flags. -- `included_sets`: ordered `includedSets/Item` records. -- `change_set_groups`: setup `contentChangeSetGroups/Item` records, preserving `NameHash` and the ordered - `ContentChangeSets/Item` children. - -`record.select("field", "Item")` selects direct-child paths without collapsing repeated fields; -`record.scalar("field")` reads a single text or `value`-attribute field. Missing fields return `None`, empty -fields return `""`, and ambiguous repeated/nested scalars raise `ContentError`. Text scalar access strips -surrounding whitespace; the underlying record retains it. Values stay strings: hashes, bit flags, phases, -macros, paths and references are not converted or resolved. No include is opened and no mount is performed. -The reader does not infer runtime execution order, resource boundaries or a relationship between an XML -filename and a carved resource. Those still require independent evidence. - -`carve_documents(directory)` uses the existing game-data grouper and yields `(offset, stored_bytes, document)`; -the first two values are the first recovered block offset and sum of compressed block sizes, **not** a named -RPF entry or a contiguous span including padding. Non-content XML yields `None`. Missing carved blocks raise -an error instead of substituting the index's header bytes. This path inherits the grouper's recovery limits. -The parser retains one complete XML document, limited to 64 MiB and 128 nested elements by default (`max_bytes` -can change the byte limit); the grouping step itself is not subject to that parser limit. DTDs are refused. -The CLI reports failed input counts and returns nonzero on failure; successful documents earlier in a failed -carve remain in the counts. It emits no input values, paths or exception text. API records contain game data -and must stay local, as must the carve and its index. - -Full scans of the four archives in this note recovered **30 content XML documents**, all accepted, with -no record differences against an independent ElementTree parse of each reassembled payload: - -| Archive | Change sets | Content definitions | Setup documents | File entries | Included change sets | Setup groups | -|---|---:|---:|---:|---:|---:|---:| -| `core_restofworld` | 8 | 1 | 1 | 33 | 8 | 4 | -| `story000_restofworld` | 11 | 1 | 1 | 28 | 11 | 2 | -| `core_restofworld001` | 2 | 1 | 1 | 3 | 2 | 1 | -| `core_licenses_data` | 1 | 1 | 1 | 1 | 1 | 1 | -| **Total** | **22** | **4** | **4** | **65** | **22** | **8** | - -There are zero `includedSets/Item` entries in these documents. Counts cover the four complete archives, -not a sample of the separate 20 GB `story000.rpf`. The check compares tags, attributes, text, tails and -child order; it establishes parsing fidelity, not the game's interpretation of flags or references. -Synthetic tests cover the three schemas, unknown fields, symbolic references, duplicate/ambiguous fields, -chunk boundaries, UTF-16, malformed/DTD input, limits, split carve payloads, missing blocks and the CLI. - -## Textures (`ASSET-148`) - -The stream-start scan above found zero `DDS`, `TXTR`, `DXT` or `BC` signatures because rest-of-world textures are -not raw stream-start images. Measured on the 1.0.2.1 package, they live in two places: - -1. **Embedded RAGE9 `0x980` texture descriptors inside `zero-prefix` CPU-segment streams** (the same `grcTexture` - layout `tools/tex_headers.py` reads in the main archives: `q[k-1] == 0x980`, 256-byte-aligned GPU pointer - `0x60000000 + offset` at `q[k]`, `(width, height, depth, byte6, dxgi_format)` at `q[k+4]`, `flags | (mips << 16)` - at `q[k+5]`), paired with the following GPU-segment stream chain. `tools/restofworld_index.py` now detects these - descriptors inside `zero-prefix` streams (`tex980=`, `dict=`, and summary fields `texture_streams`, - `texture_dictionaries`, `texture_headers`): - - | Archive | Texture streams | Standalone `pgDictionary` | Total `0x980` headers | GPU chain fit | Formats and tiling | - |---|---:|---:|---:|---:|---| - | `core_restofworld.rpf` | 145 | 144 (72×1, 72×2) | 278 | 278 / 278 | 216 tiled (`flags & 0xffff = 0x5`, 1–10 mips: `BC1_UNORM` 146, `BC1_UNORM_SRGB` 31, `BC7_UNORM` 26, `BC5_UNORM` 9, `BC7_UNORM_SRGB` 4) in the 144 dictionaries; 62 linear (`0x0`, 1 mip, `R16G16B16A16_FLOAT`, e.g. `16x4`–`16x10`) in one 576 KiB resource page | - | `story000_restofworld.rpf` | 1 | 0 | 51 | 51 / 51 | 51 linear (`0x0`, 1 mip, `R16G16B16A16_FLOAT`, `16x4`–`16x10`) in one 320 KiB resource page | - | `core_restofworld001.rpf` | 0 | 0 | 0 | — | textures are in the companion TTPF pool below | - | `story000_script.rpf` | 0 | 0 | 0 | — | none | - - All 329 embedded descriptors across these archives have `dtype = 0x980`, `depth = 1`, `byte6 = 1`, and 100% fit - within their following GPU-segment stream chain (`data_off + mip0_bytes <= gpu_chain_bytes`). - -2. **Companion RDS5/TTPF texture pools** alongside the archives under `pack/core_restofworld*/data/ttdb/` (6 pools, - 88,795,904 bytes total, **635** 2D textures, already walked and exported by `make_game.py`'s `assets` stage - under `ttpf_pack/core_restofworld/` and `ttpf_pack/core_restofworld001/`): - - | Pool | Bytes | Textures | Formats | - |---|---:|---:|---| - | `pack/core_restofworld/data/ttdb/props/ttdb_props.ttpf` | 35,286,784 | 211 | `BC1_UNORM` 110, `BC1_UNORM_SRGB` 72, `BC7_UNORM_SRGB` 11, `BC7_UNORM` 9, `BC3_UNORM_SRGB` 8, `BC6H_UF16` 1 | - | `pack/core_restofworld/data/ttdb/textures_loose.ttpf` | 21,081,856 | 194 | `BC1_UNORM` 89, `BC4_UNORM` 67, `BC7_UNORM` 17, `BC7_UNORM_SRGB` 13, `BC5_UNORM` 5, `BC6H_UF16` 2, `BC3_UNORM_SRGB` 1 | - | `pack/core_restofworld/data/ttdb/peds/ttdb_peds.ttpf` | 24,529,408 | 165 | `BC1_UNORM` 67, `BC1_UNORM_SRGB` 46, `BC7_UNORM` 35, `BC5_UNORM` 9, `BC7_UNORM_SRGB` 5, `BC3_UNORM_SRGB` 1, other 2 | - | `pack/core_restofworld/data/ttdb/ui/ttdb_ui.ttpf` | 4,729,600 | 43 | `BC1_UNORM` 37, `BC7_UNORM` 6 | - | `pack/core_restofworld/data/ttdb/vfx/ttdb_vfx.ttpf` | 3,129,600 | 17 | `BC7_UNORM_SRGB` 5, `BC1_UNORM` 5, `BC5_UNORM` 5, `BC4_UNORM` 1, `BC3_UNORM_SRGB` 1 | - | `pack/core_restofworld001/data/ttdb/ui/ttdb_ui.ttpf` | 38,656 | 5 | `BC7_UNORM` 3, `BC3_UNORM` 2 | - -### Which source the drawables' texture references reach - -The drawables name textures by the 64-bit texture IDs in their shader parameter records -([textures.md](textures.md)). Measured over the 1,732 `.ydr`/`.yft`/`.ydd` entries of the two core archives in -a local RPF9 index (all decoded; 17,208 texture references to 675 distinct IDs), against the ID tables of all 57 -`.ttpf` pools in the package and against the two sources above: - -| Where the ID is | Distinct IDs | References | -|---|---:|---:| -| a pool under `pack/core_restofworld*/data/ttdb/` | 285 | | -| a shared pool under `data/ttdb/` | 258 | | -| subtotal: in a pool | 543 | 6,403 | -| a key of an embedded `pgDictionary`, or any u64 inside the 145 embedded-texture streams | 0 | 0 | -| nowhere | 132 | 10,805 | - -The 144 embedded dictionaries hold 166 keys; 119 of them have a zero high half, and none equals a referenced ID -or either 32-bit half of one. So these 64-bit IDs reach the pools only; how a drawable binds the embedded -`0x980` textures was not traced here. - -The unresolved share is not spread over the materials. By shader texture slot (slots named by role where the -material's own textures show it; the others are unnamed and listed by size): - -| Slot | References in a pool / nowhere | Distinct IDs in a pool / nowhere | -|---|---:|---:| -| colour | 1,818 / 136 | 166 / 15 | -| normal | 1,758 / 223 | 145 / 14 | -| specular | 1,675 / 306 | 149 / 19 | -| a fourth material slot | 1,049 / 931 | 52 / 24 | -| five slots with one fixed ID each | 0 / 1,463 to 1,568 each | 0 / 1 each | -| a sixth such slot | 6 / 1,517 | 1 / 2 | -| one slot that never resolves | 0 / 184 | 0 / 57 | - -The per-asset material textures resolve for about nine references in ten (colour 93%, normal 89%, specular 85%). -Most unresolved references come from six slots that each use one fixed ID on 1,463 to 1,568 shaders: textures -shared by the whole engine and bound at run time rather than stored with an asset (hypothesis: lookup tables, -noise or environment maps). - -Pool entry formats of the 543 resolved IDs (DXGI numbers): 71/72 (BC1) 391, 98/99 (BC7) 120, 83 (BC5) 14, -78 (BC3) 14, 80 (BC4) 3, 65 (A8) 1; 22 are 4 x 4 placeholders. - -Method: drawables decoded with a local RPF9 model decoder (the shader parameter layout of textures.md); pool ID -tables read from each pool's `ETPF` section (count at +8, 16-byte records, then the sorted u64 IDs); embedded -streams found with `tools/restofworld_index.py`'s `find_rage_textures` / `is_pg_tex_dictionary` (keys at the -`+0x20` pointer, count at `+0x28`). Counts only; no IDs, names or texture data. - -## What a future decoder needs - -1. The RPF9 table-of-contents key/schema for names, paths and exact entry boundaries. This project - does not search for or distribute keys. -2. A recursive RPF9 walker. The flat carve crosses 10/18/4 embedded archives; a decoder needs their - spans and TOCs to group pages into resources. -3. A Bink 2 decoder for the 11 core and 7 story-rest videos (`KB2n`; see `docs/movies.md`). -4. An `0DRP`/`0x7a` parser (`tools/odrp_7a.py`, ASSET-156) now distinguishes and validates standalone - `0x7a` metadata/map resources (`0x50000000` table pointers at stream `+0x10`) against `PSIN` `LRSC` - root/count summary records (`0xbb`-filled pointer slots at `LRSC+0x08`) across single and - continuation-joined streams (see [world.md](world.md) and [psin.md](psin.md)); decoding resource payload - fields beyond schema/block layout still needs per-type definitions. -5. A `PSIN` section walker for `LSCH`, `LENM`, `LSNS`, `LGID`, `LRSC` and `CHKS`. The chain is - measured; `LSNS` is a block table and 16-byte records ([psin.md](psin.md#lsns)), not zlib. Do not call it - bytecode without evidence. -6. Model-page joining is implemented in `tools/restofworld_model_join.py` (and `rpf9dump` at `e293917`): - the `+0x08` `datResourceMap` page counts, 64 KiB stream blocking and `0x60000000` buffer validation join - all 924 `core_restofworld` model resources (936 drawables across 926 system and 1,020 graphics streams) - and the single `story000_restofworld` drawable dictionary (3 drawables) without the TOC. Archive path - names and external texture-dictionary links still need the TOC or hash matching. -7. A vertex decoder for `42 40 00 00` blocks. ASSET-57 measured recurring stream widths; - decoding vertex values still requires component types, final-stream widths and a way to - locate the owning geometry when only a graphics page is available. (Texture identification is - resolved above under **Textures (`ASSET-148`)**: embedded `0x980` descriptors in `zero-prefix` - CPU-segment streams plus the companion `ttdb/*.ttpf` pools.) -8. Runtime consumers for the XML content-definition records read by `tools/content_definitions.py` - (see above). Their roots describe configuration, not UI layout; reference resolution and mapping - to resources remain unimplemented. -9. A false-positive-aware magic scanner. `ADAT` inside `METADATA`, `AWC` inside names and `ATI2` inside - a page are measured examples; only validated stream starts and fixed headers count. - -## No-sharing rule - -Do not commit archives, carved streams, inflated payloads, asset names, path strings, hashes of assets -or name dumps. This page and its test contain aggregate counts and synthetic bytes only. Keep carves in -a local work directory, never in the repository or a PR. `tools/restofworld_index.py` writes offsets, -sizes, signatures and header fields; it does not write resource payloads or carved bytes. - -## Reproduce - -```powershell -python -I tools/rpf9_carve.py \carve\ --index-only -python -I tools/restofworld_index.py \index.csv -python -I tools/restofworld_index.py \index.json -python -I tests/test_restofworld_index.py -``` - -`--start` must be 0 or more, and `--limit` and `--max-inflate` at least 1 (decimal or `0x` hex). An out-of-range -value stops with a one-line error and exit code 2 before an index is written. - -For the map/meta split, run the `world_index.py` from `docs/world.md` over the same archive; it reports -`maps`, `meta`, `entities` and the `0x7a` version without decoding geometry. The index tool walks readable -streams; the nine `RSC8` headers in the story-rest unread gap come from a raw-file scan, not from the -tool. The cross-check hashes in this report came from a local SHA-256 pass over the inflated streams and -are not committed. The carver and index tool are stdlib-only and read the archive in place; neither -decrypts the TOC. - -## See also - -- [docs/rpf.md](rpf.md) - RPF9 carving and recovery tools. -- [docs/design.md](design.md) - the model manifest and the archive-stage table. -- `docs/story.md` - the `story000`/`shared_minigame000` archive family (pending story PR). -- `docs/world.md` - map placement and the `0x7a` metadata resource (PR #117). -- `docs/psin.md` - the `PSIN` container measured on `script.rpf` and `data.rpf` (PR #110). diff --git a/docs/retail_boot_chain.md b/docs/retail_boot_chain.md deleted file mode 100644 index fc2e9fcdb..000000000 --- a/docs/retail_boot_chain.md +++ /dev/null @@ -1,107 +0,0 @@ -# The retail boot chain: what stops `gta6rt --run`, in order - -**Status: measured on one machine, 2026-11-23. A measurement for RT-5, not a claim; RT-5 stays with its owners -on the coordination issue.** Each row is the first failure with every fix above it in place. Nothing here quotes -the executable: no addresses, offsets, IID values or bytes; only export names, public SDK types, vtable slot -numbers, call shapes and counts. [boot.md](boot.md) has the runbook that produced the traces; #6715 maps the same -executable under `--dry-run`. - -Setup: `main` `1cc6e3c12` with #6709, #4531, #6582, #4313, #4348 and #2490 merged locally, plus the local -stand-ins named below (not pull requests yet). Own 1.0.2.1 copy, Windows 11, RTX 4090 (driver 617.42), -`LEONIDA_D3D12=vulkan`, MSVC 2022 `RelWithDebInfo` build. - -## 1. The chain - -| # | Stop | What clears it | -|---|---|---| -| 1 | The first `XMemVirtualAlloc` calls: two 64 KiB reserve forms, then 2 MiB pages | #6709, #4531 | -| 2 | The 2 MiB reserve+commit calls carry attribute words the shim refuses, and `PAGE_GRAPHICS_*` bits (0x800..0x40000) on top of `PAGE_READWRITE` | Local: accept the attribute word, drop the graphics bits and keep the CPU protection. All seven startup allocations then succeed. #6843 measures the attribute words; no PR changes the check yet | -| 3 | `xgameruntime.lib`'s thunk treats a missing `XErrorReport` as fatal | #6582 | -| 4 | Access violation in the title's allocator: its `/GA` code reads its TLS from module index 0 | #4313 | -| 5 | Fatal assert when `DStorageGetFactory` returns null | #4348 | -| 6 | `XMemAllocatePhysicalPages` unimplemented; the title asserts on FALSE | Local stand-in, §2 | -| 7 | `D3D12XboxCreateDevice` succeeds; device slot 26 is called with its arguments swapped | Local, §3.1 | -| 8 | Device slot 48 is forwarded to the PC slot 48 and fails | Local, §3.2 | -| 9 | Device slot 73 is forwarded to the PC slot 73; the title then reads through a null list | #2490's list proxy plus local routing, §3.3 | -| 10 | An `XMemVirtualAlloc` reserve of about 185 MiB with type `0x42000`, attribute 7 and `PAGE_NOACCESS` is refused with `ERROR_INVALID_PARAMETER`. `0x40000` is `MEM_RESERVE_PLACEHOLDER` on the PC, which `VirtualAlloc` refuses and only `VirtualAlloc2` accepts; stop 11 supports the same reading on the console | Local: reserve it with `VirtualAlloc2(MEM_RESERVE \| MEM_RESERVE_PLACEHOLDER)` | -| 11 | The title carves five sub-ranges out of that placeholder with `MEM_RESERVE \| MEM_REPLACE_PLACEHOLDER \| MEM_PHYSICAL \| MEM_LARGE_PAGES` (`0x20406000`) at addresses inside it, then allocates a second batch of physical pages | Local: a physical reserve inside a known placeholder stays a placeholder (the page maps split it); other `MEM_REPLACE_PLACEHOLDER` calls split the range and allocate it in place | -| 12 | Device slot 133 is called; the proxy table had 128 slots, so the call went through a null pointer | Local: a 192-slot table, and a slot 133 stand-in, §3.4 | -| 13 | **Current stop**: right after the first `CreateDescriptorHeap`, the title calls the heap's slot 9 (`GetCPUDescriptorHandleForHeapStart` on the PC), takes the handle from `rax` and asserts that it equals a value it already holds. Hypothesis: a console descriptor heap starts at an address the title chose or can predict, which the PC handle doesn't match | Open: a question for the descriptor model ([boot.md](boot.md) Q4) | - -At stop 13 the D3D12 trace holds 1,185 calls: the device, 5 command queues, 5 fences, 7 command allocators, -581 command lists created and closed, a shader cache session, `XboxIDXGIDevice::GetAdapter`, one failed -`ID3D12Device10::CreateReservedResource2`, the first `CreateSampler2`, one committed resource (the slot 133 -stand-in) and the first descriptor heap. - -Without a debugger, the unhandled `int3` of a fatal assert ends the process with `C0000374` (heap corruption) or -`C0000005` during teardown, not `80000003`. An exit code of `C0000374` from `--run` can be such an assert, not a -heap bug. - -## 2. Physical pages (`xmem.dll`) - -The shapes, from the call sites and the checks that follow them: - -| Export | Shape | -|---|---| -| `XMemAllocatePhysicalPages` | `BOOL (ULONG64 attributes, ULONG_PTR* page_count /*in/out, 64 KiB pages*/, ULONG_PTR* page_array)`; the title checks both TRUE and the count written back. Attributes seen: `0x280`, `0x380` | -| `XMemVirtualAlloc` | the range for those pages is reserved with `MEM_RESERVE \| MEM_PHYSICAL \| MEM_LARGE_PAGES` (`0x20402000`) and no `MEM_COMMIT` | -| `XMemMapPhysicalPages` | `(va, page_count, page_array)`; a null `page_array` unmaps; non-null return on success | -| `XMemMapPhysicalPagesScatter` | `(va_array, page_count, page_array)`, the same with one VA per page | -| `XMemFreePhysicalPages` | `(page_count, page_array)` | - -The local stand-in that gets past stop 6 is CPU-only: one pagefile section per 64 KiB page -(`CreateFileMappingW(INVALID_HANDLE_VALUE, …, SEC_COMMIT)`), page numbers handed out as indexes into that table, -the physical reserve made with `VirtualAlloc2(MEM_RESERVE | MEM_RESERVE_PLACEHOLDER)`, each map a -`VirtualFree(MEM_RELEASE | MEM_PRESERVE_PLACEHOLDER)` split followed by `MapViewOfFile3(MEM_REPLACE_PLACEHOLDER)`, -and each unmap `UnmapViewOfFile2(MEM_PRESERVE_PLACEHOLDER)`. #5381 has the CPU half of physical pages with dirty -tracking and #5378 a Vulkan sparse-binding mapper; neither is wired to these exports. - -## 3. Device calls whose Xbox shape differs from the PC - -### 3.1 Struct-returning methods take the return buffer first - -Device slot 26 (`GetCustomHeapProperties`, which returns a `D3D12_HEAP_PROPERTIES`) is called as -`(return buffer, this, node_mask, heap_type)`: the first register holds the return buffer, the second the device -proxy. The PC MSVC method expects `(this, return buffer, …)`. A proxy thunk can tell the two apart: in the swapped -call the `this` register does not point at the proxy, and the second argument does. Calling the real method with -the two exchanged and returning the buffer pointer gets past it. Other struct-returning slots probably follow the -same rule; only slot 26 was reached. - -### 3.2 Device slot 48 creates a command queue - -Xbox device slot 48 is `(desc, riid, out)` with `riid = IID_ID3D12CommandQueue`. `desc` starts with a PC -`D3D12_COMMAND_QUEUE_DESC` (Type, Priority, Flags, NodeMask) followed by Xbox words. On the PC, slot 48 is -`OpenExistingHeapFromAddress`, so forwarding by number fails. Creating the queue from the 16-byte PC prefix, with -`Flags` limited to `D3D12_COMMAND_QUEUE_FLAG_DISABLE_GPU_TIMEOUT`, through the existing queue proxy works: four -queues come from this slot, the first of them a compute queue. The first queue comes from slot 8, as on the PC. - -### 3.3 Device slot 73 creates a command list - -Xbox device slot 73 is `(desc, allocator, pso, riid, out)`. `desc` is 16 bytes and its first word reads as the -`D3D12_COMMAND_LIST_TYPE`. `riid` is a console command-list IID that is not in the PC SDK (#3520 records that the -package doesn't export it). The shim's unknown-IID log names it on the player's machine. Creating an -`ID3D12GraphicsCommandList` of that type and handing out #2490's console list -proxy gets all 581 lists created and closed. - -### 3.4 Device slot 133 places a resource at a virtual address - -Xbox device slot 133 is `(va, const D3D12_RESOURCE_DESC*, state, clear, riid, out)` with `riid = IID_ID3D12Resource` -and `state = 0xFFFFFFFF`, which isn't a valid PC state. At the first call, `va` is the start of a physical-page -range the title had just reserved, and `desc` is a buffer of that range's size with Xbox bits in `Flags` above -the PC flags. The shape matches the console `CreatePlacedResourceX`. A buffer on those pages is imported with -`VK_EXT_external_memory_host` where the driver allows it, so the title's writes are the GPU's reads; a driver that -refuses falls back to a committed buffer. So does a buffer placed inside a page at an offset the driver cannot bind -it at: NVIDIA 582.66 on a GTX 1070 Ti binds such a buffer only at a multiple of 256 bytes, so one placed 64 bytes -into a page is not imported there (`d3d12_existing_heap_test`). -A texture gets a committed texture whose `GetGPUVirtualAddress` is the -title's address (the console behavior: a title clears a texture through that pointer), but its pixels do not alias -the title's pages yet. Both paths limit `Flags` to the PC bits; the buffer path also makes the Xbox layout word -`ROW_MAJOR`. - -The proxy's slot table must also be longer than the title's highest slot. A shorter table leaves a null pointer, -not an `E_NOTIMPL`. - -## 4. What this does not show - -These are one run's first failures, not a list of what is missing. Every stand-in above is local and untested -beyond "the title goes on to the next call". Nothing has reached a draw or a present yet. diff --git a/docs/retail_boot_intel_host.md b/docs/retail_boot_intel_host.md deleted file mode 100644 index c6220bf8e..000000000 --- a/docs/retail_boot_intel_host.md +++ /dev/null @@ -1,62 +0,0 @@ -# The retail boot on an Intel host: which stops hold, and what stops it there - -**Status: measured on one machine, 2026-11-23. A measurement for RT-5, not a claim on any code item; claimed as a docs item on the coordination issue.** It continues -[retail_boot_chain.md](retail_boot_chain.md) (stops 1-13) and the frame-loop notes of #8554 -(stops 13-28, not merged yet) on a host those pages do not cover: an Intel CPU, which needs #7111 for the four Zen 2 instructions -the executable uses, and 16 GB of RAM. Nothing here quotes the executable: no addresses, offsets or bytes; only slot -numbers, call shapes, counts and the runtime's own log classes. - -Setup: Intel Core i7-8700 (no SSE4a, CLZERO, MONITORX or CLWB), 16 GB, NVIDIA RTX 4070 SUPER (driver 616.92), -Windows 11 26200, MSVC 14.44 `RelWithDebInfo`, Vulkan SDK 1.4.363, `LEONIDA_D3D12=vulkan`, own 1.0.2.1 copy, outbound -network blocked, `--overlay` outside the package. Tree: `tibzejoker:rt5-integration` at `5fef1f1b` (31 open pull -requests on `main` `867d922f`; it contains #7111, #7417, #7240 and 18 of the 26 PRs #8554 used) plus #7078, #7009, #7755, -#7290 and a queue slot 35 routing that unwraps the list proxies (the #7286 with #7076 pairing #8554 names), merged -locally; #7755 and #7290 resolved by hand against the branch, their test files not taken. - -## 1. What holds - -| Tree | Switches | Result | -|---|---|---| -| `main` `867d922f` | none | 20 unimplemented imports (chad 5, xapu 5, AcpHal 9, `DStorageGetFactory`); `--init` clean; `--run` ends in CRT startup after 16 s with an access violation and 0 D3D12 calls: the stop-4 shape (TLS from module index 0) | -| rt5-integration | none | stop 18 (C++ throw in `XboxBvhBuilder.dll` at its first compute pipeline) after 20 s and 1,640 D3D12 calls. `[rt] cpu:` names the four emulated instructions; the run never faults on one. Stops 1-17 hold on Intel; #7240 covers stop 17, so #7235 was not needed | -| rt5-integration | `LEONIDA_STUB_PIPELINES=1` | stop 26 (the int3 after the title's window) after 18 s and 13,091 calls (2,746 ok; 10,241 refused on the device slot the PC maps to `CreateLifetimeTracker`; 1 failed `Close` on a stubbed list, #7007 not in the tree) | -| rt5-integration | + `LEONIDA_SKIP_INT3=1` | stop 27 (fence slot 12's `E_NOTIMPL` read as a pointer) after 47 s and 62,594 calls, in the runs that get past the early assert of section 2 | -| the stack above | + `LEONIDA_SKIP_INT3=1` | stops 27 and 28 cleared (fence slot 12 serves the completed value's address; the AcpHal, chad and xapu shims are reached). After 89,964 calls in 46 s the GPU address arena fills (section 3) | - -## 2. The commit limit: the stop that is specific to a 16 GB host - -Right after stop 17 the title's second `XMemAllocatePhysicalPages` asks for 99,776 pages (6.1 GiB, attributes 0x380). On -`main` (#6919) the shim backs the request with one `SEC_COMMIT` section, so the whole 6.1 GiB must be chargeable at once. -With 16 GB of RAM, a 5 GB page file and about 7 GB held by other programs, this machine's free commit sat near that line: -the request succeeded in 3 of 8 runs early in the evening and in 0 of 5 once the shader translation had grown; when it -fails, the title's int3 follows 0.3 ms later, at the 1,657th D3D12 call every time, on a title worker thread, and a -step-over only moves the failure to a null read a few milliseconds on. It is not load (0 of 5 on an idle CPU), not the -step-over (the int3 is unhandled without it), not the desktop session, not the overlay (fresh overlay: same), not the -tree (the unmodified branch fails the same way once commit is short). The event log carries a Resource-Exhaustion-Detector -2004 from the hour the translation peaked. - -#7556 (physical pages committed on first touch) clears it: 3 of 3 runs go on to stop 26 with the same free commit. With -#7556, `LEONIDA_STUB_PIPELINES=1`, `LEONIDA_SKIP_INT3=1` and `LEONIDA_ARENA_MB=4095`, one run went past every documented -stop and ran the title's frame loop until the 900 s timeout: 100,457 D3D12 calls (59,430 ok; 1,028 failed `Close` on -stubbed lists, #7007 not in the tree; 10,241 refusals on slot 57), one int3 stepped over (stop 26), the AcpHal, chad and -xapu shims reached. Machine-side mitigation: a fixed 16 GB page file (commit ceiling 32 GB instead of 21 GB). - -## 3. What the layer itself refuses at that depth - -In the run that first reached stop 28 (46 s, 89,964 calls, the 256 MiB default arena): `CreatePipelineState` 53,967 ok, -250 failed, 1,938 unsupported; 430 of the unsupported ones carry a stream subobject the PC parser reads as an amplification -shader (payloads 2.2-22.5 KB). All 430 payload sizes equal a mesh-shader container size in this copy's carve index (0 misses; -280 of them equal no vertex-shader size), so that subobject is the console's mesh shader: the console enum has no gap at 23 -where the PC has `AS` 24 and `MS` 25 (data posted on #8815, which maps it to the VS instead). Also 25,451 refusals on device -slot 57 (the PC `CreateLifetimeTracker`), 6 `ExecuteCommandLists`, 4 `DrawInstanced`, 3 `Dispatch`, and once each: a -depth-bounds stream subobject, a full bindless image array, a `GetResourceAllocationInfo` format, a UAV dimension, a storage -view on a depth-stencil format, a depth-stencil format and a multisample typed colour view. That run ended on "GPU address -arena full" (`LEONIDA_ARENA_MB`, 256 MiB default) on a 24,495 KiB buffer, after which `CreateCommittedResource` and slot 133 -failed and the title asserted; at the 4095 MiB cap the arena was not exhausted in 900 s. - -## 4. What this does not show - -One machine, one driver, nothing drawn: every pipeline was a stub, so the frame loop shows the submission path, not -rendering. No translated shaders were loaded in these runs; the full translation of this copy (26,503 of 26,503, one shard -redone after a `MemoryError` at the same commit limit) is the next step, with the subobject-24 reading of section 3 tested -both ways. The commit-limit section is what this host adds; the rest confirms #8554 on a second machine and CPU vendor. diff --git a/docs/rpf.md b/docs/rpf.md deleted file mode 100644 index 7bc656845..000000000 --- a/docs/rpf.md +++ /dev/null @@ -1,206 +0,0 @@ -# RPF9 archives and the carve tools - -GTA VI ships its assets in RPF9 archives. The **table of contents** (names, sizes, offsets and flags) is -encrypted/packed; this project does not decode it and does not search for keys. The **data area** is mostly -zlib streams laid end to end, so it can be measured and carved without the TOC. Names in the recovery view -are offset-based (`recovered/...`), not the original paths. - -## What is readable - -- The header: magic `RPF9` (stored as `9FPR` little-endian), sizes/counts, and the data start at `u32 +4`. - The TOC area immediately after the header is high-entropy and opaque. -- The data area: zlib streams, Bink 2 video (`KB2[a-z]`) in `movies.rpf`, and raw AWC banks in `audio.rpf`. -- From the existing survey in [docs/design.md](design.md): most archives are 93-99% plain zlib - (`levels.rpf` 98.3%, about 1.1M files); `audio.rpf` is 99.9% raw AWC, not zlib; about half of - `story000.rpf` and `shared_minigame000.rpf` is non-zlib. Unread bytes are recorded as ranges (the `unread` - list in `rpf9_carve.py`'s `index.json`), never guessed. - -## Whole-package name coverage (reported in #1790) - -The recovery view names streams by offset, but some original paths can be read from the payload itself: -mount XMLs and similar text in the data area list them in plain text, directory form included. #1790 ran one -name-recovery walker over all 22 archives of a retail package (150.2 GiB) and reports how far that gets. These -counts are as reported there; they were not re-run for this page. - -| | Count | -|---|---:| -| Streams | 1,489,677 | -| Streams with a name | 177,087 (11.89%) | -| Unique paths | 155,214 | -| Unique identifiers | 200,184 | -| Path mentions | 526,581 | - -| Stream type (walker's classes) | Named / streams | Share | -|---|---:|---:| -| `sgd5_shader_dxbc` | 25,043 / 25,043 | 100.00% | -| `xml` | 191 / 332 | 57.53% | -| `rsc50` | 123,889 / 531,370 | 23.32% | -| `xml_chunk` | 109 / 504 | 21.63% | -| raw | 26,766 / 690,003 | 3.88% | -| `PSIN` | 465 / 15,380 | 3.02% | -| `0DRP` | 624 / 227,045 | 0.27% | - -Three findings from the same run: - -- The paths come from the payload, not the TOC. One 8 KB stream in `common.head.bin` declares 473 `.bk2` paths on its - own. -- Stream alignment is not universal. Inflated streams sit on 4 KiB boundaries in `data.rpf` (295 of 301 checked) - but not in `levels.rpf` (8 of 26), `packs.rpf` (0 of 301) or `textures.rpf` (0 of 3), so a walker that assumes - 4 KiB steps misses most streams in three of those four. `tools/rpf9_carve.py` does not assume an alignment: it - continues after the bytes each stream consumed. -- `anim.rpf` is the richest archive for names (64,785 named streams, 367,190 path mentions, almost all `.clip`). - `movies.rpf` produced no zlib streams, and `script.rpf` and `story000_script.rpf` no names. - -The 11.89% is the ceiling of this method, not a progress figure: the rest of the names are in the encrypted TOC, -which this project does not decode. #1790 also confirms the TOC is not ECB (no duplicate 16-byte blocks in 62,487). -The full name index is not published; the issue offers salted hashes of the paths and identifiers so that another -run can be compared without publishing a name. - -## Stream roles - -In the measured carve indexes, a resource's system prefix can be separated from its graphics pages without -decoding the resource: the prefix ends at the first stream whose inflated size is a multiple of `0x10000`, plus at -most one following non-multiple stream (a spill reached by a `0x5…` pointer). This reproduces the first -`42 40 00 00` graphics page on all 36,911 resources with one in `packs.rpf` and the 20–21, 40–41 and 70–70.8 GiB -`levels.rpf` windows, and on all 2,478 two-stream `0DRP` navmesh pages. It is a boundary, not a page test: only -17,994 of the 40,038 graphics pages measured (44.9%) are multiples of `0x10000`, so the stream at the boundary is -often the last system page. `42 40 00 00` stays the direct graphics-page marker. - -An inflated size of exactly `0x800000` is a chunk head, not a continuation. All 43 in `core_bvh4.rpf` follow a -208–544-byte header stream and are followed by a separate continuation stream; the eight in the other measured -indexes are resource or graphics pages. [bvh.md](bvh.md) records the same 8 MiB-first relationship from the payload -side. - -The boundary rule is independently read by meetox80/6stars. No 6stars code, prose or table was used; the -repository has **no licence** (all rights reserved), and every count above was re-measured from this package. See -[related_projects.md](related_projects.md). - -## Carving - -```powershell -python -I tools/rpf9_carve.py [--start N] [--limit BYTES] [--index-only] -``` - -The walker starts at `--start` or the header's data offset, finds a zlib header (`78 01/5e/9c/da`) or a Bink 2 -magic, inflates the stream, and continues after the bytes it actually consumed. `--index-only` records the -streams without writing the inflated files; `--limit` bounds a sample; `--start` starts at a known offset. - -`--start` must be 0 or more and `--limit` at least 1 (decimal or `0x` hex). An out-of-range value stops with a -one-line error and exit code 2 before any output is written, rather than silently scanning everything or nothing. - -`/index.json` contains: - -- `summary`: archive, files, compressed/inflated bytes, Bink 2 bytes/files, zero padding, unread bytes, the number of - unread ranges (`unread_ranges`), span; -- `files`: `off`, `stored`, `size`, `pre` (bytes before the stream), `head` (first 16 inflated bytes), and for - Bink 2 the `w`/`h`/`frames` fields; -- `unread`: one row per gap that is not all zero bytes, between two streams, before the first or after the last: - `off`, `size`, and `entropy`, the Shannon entropy in bits/byte of its first `sampled` bytes (at most 1 MiB). A - gap is the whole region between two streams, so a mostly-zero gap with a few other bytes is one unread range. An - all-zero gap counts toward `zero_padding` only. The sizes add up to `unread_bytes`. - -Measured on `data.rpf` (481,544,304 bytes; span 481,474,576), the 20,268,240 unread bytes (4.2%) are **377 -ranges**: median 7,452 bytes, largest 1,149,226; 7 below 1 KiB, 297 from 1 KiB to 64 KiB, 73 of 64 KiB or more -(16,565,898 bytes). By entropy: - -| Bits/byte | Ranges | Bytes | -|---|---:|---:| -| 7.5 or more | 278 | 18,257,882 | -| 6 to 7.5 | 32 | 1,350,501 | -| 4 to 6 | 37 | 460,464 | -| below 4 | 30 | 199,393 | - -So 90% of the unread bytes look like compressed or encrypted data, with no zlib or Bink 2 header the walker accepts. -The rest is lower-entropy structure worth a look with a hex editor at the listed offsets. The list holds offsets -and sizes only; keep the index in your work folder like the carved files. - -The walker advances by `len(chunk)`, not by the 1 MiB read request. A short final slice used to make `p` -overshoot EOF, so `used` exceeded the real stream size and every trailing stream was skipped; the regression -test `tests/test_rpf9_carve.py` builds a two-stream archive to keep that fixed. - -A gap between streams counts as zero padding when every byte in it is zero, otherwise as unread. -`rpf9_carve.py` checks a gap in 1 MiB pieces. The other scanners that keep these counts (`rpf9_names`, -`bvh_index`, `navmesh_index`, `navmesh_decode`, `rbf0_index`, `anim_index`, `restofworld_index`, `story_index`) -use `tools/zero_span.py`, which compares the gap with zeros 4 MiB at a time and stops at the first window with a -non-zero byte. They used to slice the gap out of the mapped archive, which copies all of it at once. The largest -gap in `story000.rpf` is 8.9 GiB, so that needed 8.9 GiB of memory. `tests/test_zero_span.py` runs all nine -scanners on a 48 MiB gap and checks that each one's Python heap peak stays under 24 MiB. - -The carve is read-only and works on any `.rpf`, `.ttpf` or archive-like file. It does not decrypt the TOC, use -keys, or write anything outside the output directory. - -## Recovery tools - -`tools/rpf9dump` is a bulk exporter built on the Core library from -[breadbbbb/rpf9-explorer](https://github.com/breadbbbb/rpf9-explorer) (a `third_party` submodule; the -related-projects page records the licence boundary). It carves validated resources; it does -not decrypt the TOC either. - -```powershell -dotnet build tools/rpf9dump/rpf9dump.csproj -c Release -rpf9dump ttpf -rpf9dump models -rpf9dump textures -rpf9dump audio -rpf9dump xma -``` - -`audio` writes the AWC banks plus `audio_manifest.json` (stream ids, codec, channels, rate, duration); `xma` -writes RIFF XMA2 WAVs that ffmpeg decodes. `models`/`textures` write OBJ/DDS plus a manifest. The tool's -`ArchiveReader` recovery names are offset-based, and its structured path validates XML/PSIN, models and -textures; the original RPF paths still require the missing executable/key. - -`tools/manifest.py` is independent of RPF: it hashes a directory tree and verifies it later, with `--jobs` on -both paths. It is used to check exported assets without keeping a second copy. - -`tools/rpf9_names.py` is the lightweight lookup pass: it walks the same data area, inflates a bounded prefix -of each zlib stream and indexes the measured `name.#dr`/`#ft`/`#dd` spellings with their archive offsets. It -does not decode a resource or need the TOC; see [resource_names.md](resource_names.md). - -### The trailer at EOF - -The header's `u32 +12` is the size of a block that ends the file: the last `+12` bytes of an RPF9 are not part of -any stored file (ASSET-318, measured on the 22 RPF9 archives of the 1.0.2.1 package, offsets and counts only). -`+12` is a multiple of 16 in all 22 (64 to 119,520 bytes); `+8` is always larger than `+12` except in `levels.rpf` -and `core_bvh4.rpf`, and its role is not established. - -| Evidence | Archives | -|---|---| -| The data before it ends in zeros up to a 4 KiB boundary, and exactly `+12` non-zero bytes follow to EOF | 10: `anim`, `audio`, `common`, `data`, `levels`, `movies`, `packs`, `shared_minigame000`, `story000`, `core_bvh4` | -| Files are packed at 16-byte alignment; walking the zlib streams to the end leaves exactly `+12` bytes after the last one | 4: `core_licenses_data`, `core_restofworld`, `shared_minigame000_bvh4`, `story000_bvh4` | -| Undecided: the last stored file is not zlib (or the walk stops at a non-zlib file), so its end is not known without the TOC | 8: `appdata0`, `navmeshes`, `script`, `shaders`, `textures`, `core_restofworld001`, `story000_script`, `story000_restofworld` | - -No archive contradicts the rule, but 8 don't test it. In the 14, the trailer starts with no zlib or Bink 2 header and is -high-entropy like the TOC after the header: 7.95 to 8.00 bits per byte in the nine of 3 KiB or more, and 6.6 to 7.9 -in the five smaller ones (random 144-byte blocks average about 6.7); what they hold is not -decoded here. `tools/bink_index.py` counts it as `rpf_trailer` instead of unread bytes, only for an `RPF9` header -whose `+12` is a multiple of 16 and fits in the tail after the last stream; in `movies.rpf` it is the -18,928 bytes after 3,884 zeros that [movies.md](movies.md) listed as unread. - -### Viewing a header in ImHex - -[tools/imhex/rpf9.hexpat](../tools/imhex/rpf9.hexpat) is a pattern for the [ImHex](https://imhex.werwolv.net/) hex -editor. It names the magic, the data offset at `+4` and the trailer size at `+12`, shows the u32 at `+8` unnamed, -and shows the range from `+0x10` to the data offset (the rest of the header and the TOC) as one opaque byte array. -It decodes nothing in that range. `python -I tests/test_imhex_patterns.py` runs it on a synthetic header when ImHex is installed. - -## Limits - -- The TOC is the hard boundary. File names, original paths and the exact file boundaries come from the TOC, - so they are unavailable until the executable (or a documented key/schema) is part of the project. This - repository does not search for or distribute keys. -- Some archives are not plain zlib (`audio.rpf`, parts of `story000.rpf`/`shared_minigame000.rpf`); the - recovery tools handle the formats they know and report the rest as unread. -- Bink 2 video is carved as whole `.bk2` streams. FFmpeg builds generally expose only Bink 1; the package's - `Bink2Scarlett.dll` decodes Bink 2 (see the movie notes). -- Extracted assets are for local use with your own copy. Never commit or share them. - -## See also - -- [docs/design.md](design.md) - the asset-stage table, coverage numbers and the recovery approach. -- [docs/page_directory.md](page_directory.md) - the `0DRP` page directory layout, `q38` resource boundaries and - `tools/page_index.py`. -- [docs/story.md](story.md) - measured `story000`/`shared_minigame000` composition, nested RPF9 sub-archives and the `PSIN`/`RSC8` headers. -- [docs/restofworld.md](restofworld.md) - measured composition of the rest-of-world and script archives. -- `docs/audio.md` - AWC layout and the audio exporters, once the audio guide is merged. -- the related-projects page - the rpf9-explorer/PercyStar/SCARAB licence boundaries. diff --git a/docs/rsc8_audio.md b/docs/rsc8_audio.md deleted file mode 100644 index 2a5766207..000000000 --- a/docs/rsc8_audio.md +++ /dev/null @@ -1,441 +0,0 @@ -# `RSC8` audio-bank resources (AWC tag `0x5c`) - -**Status: decoded at container, object-graph, property, animation-block, track-directory and keyframe level; stdlib decoder in [`tools/rsc8_audio.py`](../tools/rsc8_audio.py).** - -[story.md](story.md) measured 225,281 raw `RSC8` (version `8001` / `0x1F41`) headers in `story000.rpf` -(plus 1,957 in `shared_minigame000.rpf` and 9 in `story000_restofworld.rpf`), and the mission-music -search recorded in [audio.md](audio.md#mission-music-home-sweet-home) (#716) left `RSC8` as the only -undecoded mission-side container. - -Full-package scanning resolves what `RSC8` is: - -- **`RSC8` v8001 is not an audio codec or standalone audio container.** -- **641,428 of 641,428** `RSC8` resources across the package (`8,183,359,968` bytes total) sit inside - standard little-endian **`ADAT` (AWC)** banks as **chunk tag `0x5c`**. Zero `RSC8` headers occur - outside `ADAT` anywhere, zero `0x5c` chunks hold non-`RSC8` data, and zero `RSC8` resources appear - under any other AWC chunk tag. -- **641,428 of 641,428** `0x5c` entries belong to an AWC stream that also carries a sibling **`0x55`** - audio payload and **`0x76`** format chunk declaring **48 kHz mono Opus** (`codec = 0x0B`, `channels = 1`, - `sample_rate = 48000`). -- Inside tag `0x5c`, the payload is an unencrypted RAGE **`crClipDictionary` + `crClipAnimation` + - `crAnimationDictionary` + `crAnimation`** facial / lip-sync animation resource whose clip duration - tracks the companion Opus dialogue line (typically with a short lip-sync blend margin). Zero `RSC8` - resources contain an embedded audio container (`ADAT`, `OggS`/`OpusHead`, or `RIFF WAVE`). -- Consequently, `RSC8` cannot hold undecoded mission music, closing that residual item from #716. - -Every figure below is an aggregate measurement from one local Xbox Series 1.0.2.1 package. No game -strings, asset names, dialogue lines, audio streams or raw payloads are committed here or emitted by -`tools/rsc8_audio.py`. - -## Corpus counts - -| Archive | `ADAT` banks | `ADAT` streams | Bytes in `ADAT` | `RSC8` (`0x5c`) | `RSC8` outside `ADAT` | `RSC8` tag bytes | `u32@+0x08` sum | Paired `0x55` Opus (48 kHz mono) | -|---|---:|---:|---:|---:|---:|---:|---:|---:| -| `audio.rpf` | 7,162 | 1,606,241 | 28,505,691,532 | 414,181 | 0 | 5,470,286,400 | 5,465,316,228 | 414,181 / 414,181 | -| `story000.rpf` | 63,861 | 234,458 | 9,423,830,212 | 225,281 | 0 | 2,680,074,288 | 2,677,370,916 | 225,281 / 225,281 | -| `shared_minigame000.rpf` | 638 | 4,334 | 359,078,504 | 1,957 | 0 | 32,927,792 | 32,904,308 | 1,957 / 1,957 | -| `story000_restofworld.rpf` | 15 | 76 | 8,908,216 | 9 | 0 | 71,488 | 71,380 | 9 / 9 | -| **Total (4 archives)** | **71,676** | **1,845,109** | **38,297,508,464** | **641,428** | **0** | **8,183,359,968** | **8,175,662,832** | **641,428 / 641,428** | - -Eight additional archives were scanned in full and contain **0** `RSC8` headers: `anim.rpf`, -`packs.rpf`, `core_restofworld.rpf`, `data.rpf`, `textures.rpf`, `story000_script.rpf`, `common.rpf`, -and `script.rpf`. - -Two of `audio.rpf`'s 7,162 banks are **zero-stream banks**: a complete 20-byte header with stream -count `0`, flags `0xff210001` (the `0x200000` table's `(count + 1) * 4` bytes fill the header exactly) -and no tags. The encrypted TOC lists both as `.awc` entries, and rpf9-explorer's -`AwcRecovery.ReadValidated` accepts them, which is why [design.md](design.md)'s audio row has 7,162 -banks. Until the parser learned them, this table said 7,160: `parse_adat_header_bytes` rejected any -`count == 0` header as malformed. A zero-stream bank is now accepted when the flag-selected tables -end exactly at the declared header size (no stream ids or tag rows can follow, so any leftover bytes -mean the header is not what the flags say); header slop, truncation and out-of-bounds sizes are still -rejected, covered by synthetic tests in `tests/test_rsc8_audio.py`. The other three archives have no -zero-stream bank, so only `audio.rpf`'s bank and byte counts changed (banks 7,160 → 7,162, +40 bytes). - -## The undocumented `0x5a`/`0xd9` companion tags - -`audio.rpf` carries two tag types no other archive has, mostly on streams that hold no `0x5c` clip: -**1,185 streams** with a `0x5a` tag (804 of them also with `0xd9`; shapes `{0x36,0x55,0x5a,0x76,0xa3,0xd9}` × 803, -`{0x36,0x55,0x5a,0x76,0xa3}` × 381, and one `{0x36,0x55,0x5a,0x76,0xa3,0xbd,0xd9}`), all declaring **32,000 Hz** -(one 32,007). - -`tools/rsc8_audio.py` decodes both structurally (`decode_grid20_table`, `decode_index_runs`) and validates -them per stream in its scan tallies (`grid20_*`, `indexrun_*` summary keys): over the whole archive -**387,233 `0x5a` entries / 0 invalid** and **4,853 `0xd9` groups / 0 invalid / 0 index overruns**. Every -invariant below was measured on that full population; the field names describe structure, and the meaning of -`p`, `z`, `s`, `t` and the trailer stays a labelled hypothesis. - -`0x5a` — `{u32 12345678; N × 20-byte entries; f32 trailer}` (`(size − 8) % 20 == 0` always). The framing is -@kotorvr's ([finding](https://github.com/ItsNotRexed/Leonida/issues/3232#issuecomment-7084750136)), recounted -for ASSET-256; read 4 bytes later, as before, each entry paired one entry's fields with the next one's -position, and the trailer became the last "counter": - -``` -0 u32 position (a sample position at the stream's rate, see below) -4 f32 value (3.658 .. 146.789 measured; spans up to 133 within one stream) -8 u16 p (a multiple of 512 on every measured entry) -10 u16 z (0 .. 16) -12 u16 index_lo -14 u16 index_hi (index pairs tile 0..129 / 1..130 measured) -16 u16 s -18 u16 t -trailer: f32 (2/3 = 0x3f2aaaab on 1,182 streams, 0.666812 on 1, 0.725624 on 2) -``` - -The position is a sample position in the stream (ASSET-256, all 1,185 streams and 387,233 entries; -`tools/rsc8_audio.py`'s `grid20_position_past_samples` = 0). It ascends strictly and stays below the `0x76` -sample count: the largest is 0.9986 of the stream's samples, and the last one ends p10/p50/p90 0.8/1.85/5.4 -mean entry steps before the stream's end. One entry lasts one period of its `value` read as a frequency: -`(position[k+1] − position[k]) × value[k] / rate` is within 1% of 1 on 365,803 of the 386,048 entry pairs -(within 5%: 383,993), so `value` reads as a pitch in Hz. Read as a u32, the trailer is about 1.06 × 10⁹, -2^9.9–2^15.2 times the sample count, which made the old "counter" look finer than a sample. Every one of these -streams is mono XMA2 (`0x76` codec 5) at 32,000 Hz (one at 32,007 Hz). - -`0xd9` — `{u32 K; K × {u32 2; u32 len; u32 hash; len × u32}}`: the run values ascend strictly inside each -group, exactly one distinct `hash` appears per stream, the group count always equals `K`, and **every run -value is smaller than the sibling `0x5a` table's entry count** (804/804), so the runs index `0x5a` entries. - -### Resolution of the `docs/story.md` raw gaps - -The uninflatable raw regions noted in [story.md](story.md) are unencrypted `ADAT` (AWC) audio banks: - -- **`story000.rpf` GiB 5–13**: `63,861` `ADAT` banks spanning `9,423,830,212` bytes (`8.78 GiB`), - containing `753` streamed-music (`0x48`) banks (matching #716) and `225,281` spoken dialogue streams - with `0x5c` facial clips. The `u32@+0x08` sum (`2,677,370,916` bytes = `2.49 GiB`) matches - [story.md](story.md) to the exact byte; the remainder of the `8.78 GiB` region is the sibling Opus - speech audio (`0x55`), streamed-music chunks (`0x48`), and per-stream audio metadata tags. -- **`shared_minigame000.rpf` 360 MB unread gap**: `638` `ADAT` banks spanning `359,078,504` bytes - (`99.2%` of the `362.1 MB` unread span), containing `7` streamed-music (`0x48`) banks and `1,957` - `0x5c` facial clips (`u32@+0x08` sum `32,904,308` bytes, matching [story.md](story.md)). -- **`story000_restofworld.rpf` 8.96 MB unread gap**: `15` `ADAT` banks spanning `8,908,216` bytes - (`99.4%` of the gap), containing `13` streamed-music (`0x48`) tags and `9` `0x5c` facial clips. - -## Companion AWC speech tags - -Beyond the three tags documented in [audio.md](audio.md) (`0x55` stream data, `0x76` format, `0x48` -streamed-music descriptor), speech streams carrying `0x5c` consistently carry these sibling tags: - -| Tag | Role | Measured layout | -|---:|---|---| -| `0x55` | Audio stream payload | 2048-byte Opus packet blocks (`codec = 0x0B`, mono, 48 kHz) | -| `0x76` | Audio format | 32 bytes (`+0x00 u32` samples, `+0x08 u16` sample rate, `+0x1C u8` codec, `+0x1D u8` channels) | -| `0x5c` | Facial / lip-sync clip | Unencrypted `RSC8` resource (`crClipDictionary` + `crAnimation`) | -| `0x36` | Peak envelope | Array of `u16` amplitude peaks | -| `0xa3` | Opus seek table | `u32` cumulative sample offsets per 2048-byte Opus block (step `0x2D00 = 11,520` = `12 × 960` samples) | -| `0xb2` | Loudness curve | `(u32 sample_index, f32 dB)` pairs sampled every `4,800` samples (`100 ms` at 48 kHz) | -| `0xbd` | Cue list (`markers`) | 16-byte records `{u32 name hash, u32 value, u32 sample offset, u32 extra}`, no header; see [below](#the-0xbd-cue-records) | - -### The `0xbd` cue records - -An earlier version of this table called `0xbd` "a 16-byte header starting with magic `0xE5C74063`". It is a list -of 16-byte records with no header, and `0xE5C74063` is one cue name among 167. `tools/rsc8_audio.py` decodes the -list (`decode_marker_records`) and counts it in every scan (`marker_*` summary keys: 420,168 streams, 781,350 -records, 0 invalid on `audio.rpf`). Over all of `audio.rpf`: - -| Check | Result | -|---|---:| -| `0xbd` tags, records | 420,168 / 781,350 | -| tag size a multiple of 16 | 420,168 / 420,168 | -| sample offsets never decrease inside a tag | 420,168 / 420,168 | -| offset at most the stream's `0x76` sample count (the 419,223 tags whose stream has a `0x76` tag) | 750,020 / 750,020 records | -| records per tag | 1 on 88,542, 2 on 330,777, 3 or more on 849 | -| distinct name hashes | 167 | -| first record's name | `0xdbedd43c` on 330,756 tags, `0xE5C74063` on 88,082, 150 other values on 1,330 | - -``` -+0 u32 name joaat of the cue name -+4 u32 value an f32 for most names; a second name hash for region cues -+8 u32 offset sample position in the stream -+12 u32 extra 0 on 363,166 records, 1..6 on the rest -``` - -The name word is 0 on 96 records (78 tags start with one); what a nameless record means is unknown. - -- **The name is a joaat of a lowercase word.** Four of the stored values are the hashes of `beat` (`0xe89ae78c`, - 17,770 records), `trackid` (`0xa6d93246`, 1,042), `intro` (`0xda8f5f53`, 835) and `outro` (`0x5d40b28d`, 825), - as the [GTA6-Asset-Info](https://github.com/TrinitronClient/GTA6-Asset-Info) byte reference reports - (`structure/03-audio-awc.md`, commit `029e4c3`); the hashes were computed here, not copied. The names behind - `0xE5C74063` (418,838 records, 402,357 of them on speech streams with a `0x5c` clip) and `0xdbedd43c` (330,756, - all on such streams and all with `extra = 0`) are not known. -- **`value`** is a whole number stored as `f32` on every record of those six names. On five of the other names it - is `joaat("start")` (`0x84dc271f`) or `joaat("end")` (`0xb0c485d7`). Matched record by record, 418 of the 420 - `start` records are followed by their `end`; see [Region cues](#region-cues-start-and-end-records). -- The same reference states that an AWC tag id is the low byte of the joaat of the chunk name. That holds for - `markers` (`0xbd`), `data` (`0x55`), `peak` (`0x36`), `seektable` (`0xa3`) and `streamformat` (`0x48`), which - `tests/test_rsc8_audio.py` checks, and by the same rule `0x5a` and `0xd9` are `granulargrains` and - `granularloops`. Those spellings are this document's: the reference prints the last two as `seek_table` and - `stream_format`, and with the underscore the rule fails (`0xb8` and `0xf9`). It does not hold for `0x5c`, - `0x76` and `0xb2` under the names `animation`, `format` and `metadata` either, so those three names stay open. - -#### Region cues: `start` and `end` records - -The five names whose `value` is the hash of `start` or `end` have 841 records in 22 tags of `audio.rpf`: 420 -`start`, 420 `end` and one with a third value. An earlier version of this page read the near-equal counts per name -(196/197, 101/101, 54/54, 49/49, 20/19) as region pairs without matching them. `tools/rsc8_audio.py` now matches -them (`pair_marker_regions`, the `marker_regions` block of every scan summary): inside one tag it takes the -records of one name in stored order, and a pair is a `start` whose next record of the same name is an `end` at the -same or a later offset. Every other record of such a name is counted as an exception. - -| Name | Tags | `start` | `end` | Pairs | Not paired | Pair length in samples (min / median / max) | -|---|---:|---:|---:|---:|---|---:| -| `0xda559149` | 22 | 196 | 197 | 196 | 1 `end` | 172,602 / 857,823 / 3,899,077 | -| `0x1df219ec` | 1 | 101 | 101 | 101 | none | 25,289 / 95,237 / 497,606 | -| `0x77edd3a2` | 1 | 54 | 54 | 53 | 1 `start`, 1 `end`, the record with the third value | 44,984 / 90,546 / 209,958 | -| `0x994ee645` | 1 | 49 | 49 | 49 | none | 22,233 / 93,644 / 212,156 | -| `0xccb465d1` | 1 | 20 | 19 | 19 | 1 `start` | 36,146 / 92,928 / 186,375 | -| **Total** | **22** | **420** | **420** | **418** | **5 records** | | - -So the reading holds for 418 pairs, and equal counts did not prove it: the 54/54 name has two unpaired records. -20 of the 22 tags pair completely (a tag holds 1 to 181 pairs, median 3). The five exceptions sit in two tags: - -- `0xda559149` has a second `end` 16,717 samples after the `end` that closes the region before it (record 744 of - its tag's 1,435). Nothing opens it. -- A `0x77edd3a2` `start` (record 40 of 834) is followed, 118,171 samples later, by a record of the same name whose - value is `0xdaa2d5ec`, the only value on these names that is neither word. Hypothesis: that record closes the - region under another word; the distance is inside the name's pair lengths. -- A `0xccb465d1` `start` (record 773 of the same tag, the last record of its name) is directly followed by a - `0x77edd3a2` `end` that no `start` opens (record 774), 114,697 samples later. Hypothesis: one region whose two - records carry different names; the distance is inside the pair lengths of both. - -If both hypotheses hold, every one of the 420 `start` records has a closing record and only the second `end` -is left over. None of the five is a region left open at an edge of its tag: none is the tag's first or last -record, the nearest to an edge is 40 records in, and the unclosed `0xccb465d1` `start` is 18,219,408 samples -before its tag's last offset. - -Also measured on the 418 pairs: - -- No pair has a zero length, and `extra` is the same on a pair's two records (418 / 418). -- Regions of one name cannot overlap under this matching; an overlap would show as an unpaired `start` followed - by a `start`, and there is none. Regions of different names do overlap: 54 pairs of regions share samples, 43 - with one region inside the other and 11 crossing (each starts or ends inside the other). All 54 are between - `0xda559149` and one of the other four names (`0x1df219ec` 13 inside / 7 crossing, `0x77edd3a2` 19 / 4, - `0x994ee645` 2 / 0, `0xccb465d1` 9 / 0); the other four never overlap each other. So a sample can lie in - regions of two names at once. -- None of the 22 streams has a `0x76` tag (`tags_with_sample_count` is 0), so this parser has no sample count to - compare a region's end with. - -The other three archives with `ADAT` banks have `0xbd` tags as well (226,788 in `story000.rpf`, 1,959 in -`shared_minigame000.rpf`, 22 in `story000_restofworld.rpf`) and not one record with either value. - -Not known: the words behind the five names and behind `0xdaa2d5ec`, what a region does in the game, and whether -the two hypotheses above are right. The lengths are in the unit of `offset`; they were not converted to seconds, -because the rate of these 22 streams is not read here. - -## Binary format of `RSC8` (version `8001`) - -All integers and IEEE-754 floats are little-endian. Every `RSC8` tag payload is 16-byte aligned. - -### 1. Outer 16-byte wrapper (`+0x00..+0x0F`) - -``` -+0x00 4s "RSC8" -+0x04 u32 version 0x00001F41 (8001) on 641,227 clips; 0x01001F41 on 201 audio.rpf clips -+0x08 u32 body_size exact byte length after +0x0C: tag_size == body_size + 12 (641,428 / 641,428) -+0x0C u32 flags always 1 (641,428 / 641,428) -+0x10 ... virtual segment (`virtual_size == tag_size - 0x10 == body_size - 4`) -``` - -Every internal 64-bit pointer uses virtual base **`0x50000000`** relative to **`+0x10`**: - -``` -file_offset = 0x10 + (u64_ptr - 0x50000000) -``` - -The `201` `audio.rpf` clips with `version = 0x01001F41` (`version & 0xFFFF == 8001`, flag bit 24 set) -use the identical binary structure, pointer base, animation block format, and sorted track directory -as `0x00001F41`. - -### 2. Root `crClipDictionary` (`virt+0x00..virt+0xAF`) - -| Virtual offset | Size | Type | Meaning | -|---:|---:|---|---| -| `+0x00` | 8 | `u64` | `0` (vtable placeholder) | -| `+0x08` | 8 | `vptr` | Block-map node pointer (`+0x08 u32 = 1`) | -| `+0x38` | 16 | `atString` | 16-byte SSO dictionary name (see §3) | -| `+0x48` | 8 | `vptr` | Clip `atMap` bucket array (`+0x50 u32 = 11` buckets, `+0x58 u32 = 1` entry) | -| `+0x68` | 4 | `u32` | `stream_hash` (`stream_hash & 0x1FFFFFFF == AWC stream_id` on 100% of `story000` / `minigame` / `restofworld` and ~99% of `audio.rpf`) | -| `+0x6C` | 4 | `u32` | Dictionary flags (`2`) | -| `+0x70` | 12 | `atArray` | `vptr` (`+0x70`), `u16 count`, `u16 capacity` (`+0x78`) of 16-byte `(vptr anim_dict, u32 hash, u32 1)` entries | -| `+0x80` | 8 | `vptr` | Secondary hash `atMap` (`+0x88 u32 = 11` buckets, `+0x90 u32 = 1` entry) | -| `+0xA0` | 8 | `vptr` | Pointer to `crProperties` table | -| `+0xA8` | 4 | `u32` | Exact byte size of the `crProperties` table | - -### 3. 16-byte SSO `atString` (`virt+0x38` and `crClipAnimation+0x28`) - -The same 16-byte short-string-optimized layout appears for both the dictionary name and the clip name: - -- **Inline mode (`raw[15] & 0x80 != 0`)**: `length = raw[15] & 0x7F` (`<= 14`), NUL-terminated ASCII - stored directly in `raw[0 : length + 1]`. -- **Heap mode (`raw[15] & 0x80 == 0`)**: `+0x00 vptr` to NUL-terminated ASCII string in the virtual - segment, `+0x08 u16 length`, `+0x0A u16 capacity` (`>= length + 1`), `+0x0C u32 flags = 1`. - -### 4. `crProperties` (`props_ptr`, length `props_size`) - -| Relative offset | Size | Type | Meaning | -|---:|---:|---|---| -| `+0x10` | 8 | `vptr` | Pointer to the `crClipAnimation` object | -| `+0x18` | 4 | `u32` | `prop_count` (measured range `3..7`, predominantly `4` or `5`) | -| `+0x1C` | 4 | `u32` | `prop_capacity` | -| `+0x70` | `prop_count * 0x48` | descriptors | Fixed `0x48`-byte property descriptors | -| tail | variable | attributes | Contiguous typed attribute records tiling cleanly to `props_size` | - -Typed attribute records begin with `(u32 key_hash, u32 type_id)`: - -| `type_id` | Record size | Payload | Common key hashes | -|---:|---:|---|---| -| `0xFFFF0004` | `0x40` | String attribute (`+0x18 u64` string length) | | -| `0xFFFF000E` | `0x20` | 16-byte GUID attribute | | -| `0xFFFF0003` | `0x0C` | Boolean (`+0x08 u32`) | | -| `0xFFFF0002` | `0x0C` | Integer (`+0x08 u32`) | `0x10BF2F94` = frame rate (`60` Hz) | -| `0xFFFF0001` | `0x0C` | Float (`+0x08 f32`) | `0xAAA6AF06` = lead-in / blend (`0.166667` = `1/6` s) | - -### 5. `crClipAnimation` (`clip_ptr`, `0xA0` bytes) and `crAnimation` descriptor (`anim_desc_ptr`, `0x70` bytes) - -`crClipAnimation`: - -| Relative offset | Size | Type | Meaning | -|---:|---:|---|---| -| `+0x28` | 16 | `atString` | 16-byte SSO clip name | -| `+0x48` | 8 | `vptr` | Back-pointer to `crProperties` | -| `+0x58` | 4 | `u32` | `clip_hash` (matches root `stream_hash`) | -| `+0x68` | 8 | `vptr` | Pointer to `crAnimation` descriptor | -| `+0x94` | 4 | `f32` | Clip duration in seconds (`== (total_frames - 1) / fps`) | -| `+0x98` | 4 | `f32` | Playback rate (`1.0`) | - -`crAnimation` descriptor: - -| Relative offset | Size | Type | Meaning | -|---:|---:|---|---| -| `+0x18` | 8 | `vptr` | Pointer to `crAnimationDictionary` | -| `+0x30` | 8 | `vptr` | Pointer to NUL-terminated animation name string | -| `+0x48` | 4 | `u32` | `max_block_size`: maximum `anim_size` across all packed animation blocks | -| `+0x50` | 12 | `atArray` | `vptr` (`+0x50`), `u16 block_count`, `u16 block_capacity` (`+0x58`) of `vptr` to packed `crAnimation` blocks | -| `+0x60` | 12 | `atArray` | `vptr` (`+0x60`), `u16 track_count`, `u16 track_capacity` (`+0x68`) of 12-byte track directory entries | - -### 6. Packed `crAnimation` blocks and sorted track directory - -Each pointer in `anim_desc+0x50` targets a packed `crAnimation` block (typically at `virt+0xB0`, -though the resource allocator occasionally places the track directory at `virt+0xB0` and the first -block after it, or splits long dialogue animations across `2` or `3` blocks): - -``` -+0x00 u32 signature -+0x04 u32 payload_size always anim_size - 32 -+0x08 u32 reserved 0 -+0x0C u32 chunk_data_offset <= payload_size; where the channel definitions end and the frame data starts -+0x10 u32 anim_size total packed block size in bytes (>= 32) -+0x14 u16 format_version always 2 -+0x16 u16 frame_count frames in this block -+0x18 u32 extra_flags low u16: bytes per frame; high u16 not decoded -+0x1C u16 sub_count sum of the type-4 channel bit widths -+0x1E u16 track_format_tag always 11: a u8 11 (the number of channel types) and a zero byte -+0x20 ... one keyframe sequence (`payload_size` bytes), see section 7 -``` - -The field names are the ones `tools/rsc8_audio.py` reports; the notes on the right are what section 7 measured. - -Multi-block animations share their boundary frame between consecutive blocks, so across `N` blocks: - -``` -total_frames = sum(block.frame_count) - (N - 1) -clip_duration = (total_frames - 1) / fps -max_block_size = max(block.anim_size) -``` - -The sorted track directory (`anim_desc+0x60`) holds `track_count` (`90` on all `story000`, `minigame`, -and `restofworld` clips; `90`, `88`, or `87` on `audio.rpf`) × 12-byte records in ascending -(non-decreasing) unsigned `track_id_hash` order: - -``` -+0x00 u32 track_id_hash sorted ascending (non-decreasing) across the directory -+0x04 u32 schema_hash constant 0x364D3BDB = joaat("facialtranslation"), a track type -+0x08 u32 track_type the value format: 4 = one value per frame, 3 = two values per frame -``` - -This is the 12-byte track entry of the clip dictionaries in `anim.rpf` (`{id, track-type hash, value format}`, -[animation.md](animation.md#objects)); `facialtranslation` is one of the track types `tools/anim_clips.py` names. - -### 7. Keyframes - -A packed block is one **sequence** as [animation.md](animation.md#sequences) describes it for `anim.rpf`: the -0x20-byte header, the channel definitions grouped by type, `frames x bytes per frame` of frame data, `u16 -count[11]` and the per-type `(track << 2 | component)` lists. Nothing new had to be decoded: `rsc8_audio.py ---curves` hands every block to `anim_clips`' sequence decoder and counts the outcome. It writes counts only. - -| Archive | Clips | Decoded | Type-10 chunk boundaries closed | -|---|---:|---:|---:| -| `story000_restofworld.rpf` | 9 | 9 | 593 / 593 | -| `shared_minigame000.rpf` | 1,957 | 1,957 | 439,313 / 439,313 | -| `story000.rpf` | 225,281 | 225,281 | 29,144,718 / 29,144,718 | -| `audio.rpf` | 414,181 | 414,181 | 58,428,044 / 58,428,044 | -| **Total** | **641,428** | **641,428** | **88,012,668 / 88,012,668** | - -Over those 641,428 clips: - -- The decoded frame count equals the clip's on 641,428, and the header's bit sum equals the - type-4 widths on 641,428. -- Channels by type: type 2 (constant) 21,683,337, type 4 (quantised) 9,171,169, type 5 (table) 162,508 and - type 10 (second-order delta) 33,239,783. No other type occurs, so a facial clip has no quaternion channel. -- All 57,706,322 directory entries get values, and the component count follows the entry's format on every one: - format 4 decodes to one value per frame (51,159,853 tracks) and format 3 to two (6,546,469 tracks). - -`decode_facial_curves` returns the per-frame values to a caller; the tool itself never prints or stores them. - -## Full-corpus validation results - -`tools/rsc8_audio.py` validates every resource against 24 structural integrity checks (wrapper size, -version, flags, 16-byte alignment, SSO strings, `crProperties`, `crClipAnimation`, `crAnimation` -descriptor, all packed `crAnimation` blocks, `max_block_size`, exact frame-to-duration agreement, -sorted track directory, and absence of embedded audio containers). - -| Archive | Valid `RSC8` | Invalid `RSC8` | Version `0x00001F41` / `0x01001F41` | `stream_id` match / mismatch | Blocks `1` / `2` / `3` | Dict name heap / inline | Frame range | -|---|---:|---:|---:|---:|---:|---:|---:| -| `story000_restofworld.rpf` | 9 | 0 | 9 / 0 | 9 / 0 | 9 / 0 / 0 | 9 / 0 | 50–246 | -| `shared_minigame000.rpf` | 1,957 | 0 | 1,957 / 0 | 1,957 / 0 | 1,957 / 0 / 0 | 1,638 / 319 | 46–937 | -| `story000.rpf` | 225,281 | 0 | 225,281 / 0 | 225,281 / 0 | 225,273 / 8 / 0 | 216,814 / 8,467 | 17–1,706 | -| `audio.rpf` | 414,181 | 0 | 413,980 / 201 | 409,881 / 4,300 | 414,151 / 28 / 2 | 377,008 / 37,173 | 11–1,399 | -| **Total** | **641,428** | **0** | **641,227 / 201** | **637,128 / 4,300** | **641,390 / 36 / 2** | **595,469 / 45,959** | **11–1,706** | - -*(Note: in `audio.rpf`, 4,300 structurally valid speech clips — 1.04% of `audio.rpf` — assign an -internal `RSC8` clip-name hash whose low 29 bits differ from the enclosing AWC `stream_id`; -`tools/rsc8_audio.py` reports `stream_id_matches` separately from structural validity. On the full -641,428-clip corpus, all 24 structural checks pass with **0** failures.)* - -## What remains undecoded - -- What the curves drive. The keyframes decode (section 7), but which facial control each `track_id_hash` names, - the unit of a value and how the rig evaluates them are not established here; that belongs to the animation - runtime, not audio extraction. -- The high u16 of a block's `+0x18` word. -- The semantic difference (if any) of version flag bit 24 (`0x01001F41`) on the 201 `audio.rpf` clips; - structurally all 201 parse identically to `0x00001F41`. - -## Reproduce - -```powershell -# Run synthetic unit tests (stdlib only, no game files needed) -python -I tests/test_rsc8_audio.py - -# Validate RSC8 resources in an archive (summary only, zero game strings emitted) -python -I tools/rsc8_audio.py \pack\story000_restofworld\story000_restofworld.rpf --summary-only -python -I tools/rsc8_audio.py \pack\shared_minigame000\shared_minigame000.rpf --summary-only -python -I tools/rsc8_audio.py \pack\story000\story000.rpf --summary-only -python -I tools/rsc8_audio.py \audio.rpf --summary-only - -# Every summary also has the cue counts (marker_* keys) and the region pairing (marker_regions): pairs and -# exceptions per name hash, pair lengths, overlaps between names and where each exception sits in its tag. -# The numbers of "Region cues" above are the audio.rpf summary's (57 to 87 s over three runs of the 28.5 GB archive). - -# Also decode every clip's keyframes and count the outcome (slower: about 40 clips per second per process; -# split a large archive with --start/--limit and add the summaries) -python -I tools/rsc8_audio.py \pack\shared_minigame000\shared_minigame000.rpf --summary-only --curves - -# Optional per-clip structural JSON/CSV export to a local work directory -python -I tools/rsc8_audio.py \pack\shared_minigame000\shared_minigame000.rpf \rsc8.csv -``` - -## No-sharing rule - -Do not commit archives, extracted `.awc` banks, `.rsc8` blobs, Ogg Opus streams, or asset-name dumps. -`tools/rsc8_audio.py` never writes game strings or raw payloads; `tests/test_rsc8_audio.py` uses -synthesized bytes only. diff --git a/docs/runtime_imports.md b/docs/runtime_imports.md deleted file mode 100644 index 7b9f62d5a..000000000 --- a/docs/runtime_imports.md +++ /dev/null @@ -1,666 +0,0 @@ -# Runtime: measured imports of the shipped modules - -`gta6rt --dry-run` maps an x86-64 image, applies base relocations, binds every import through the shim -registry or the host, and prints a report. It does **not** call `DllMain`, TLS callbacks or the entry point, so -this page measures mapping and binding only; it does not claim the modules work. - -The game executable is not in the package. Every other PE that the package ships is present, and all of them are -Xbox Series builds. Running the dry-run over those images is the closest thing to a loader test that does not need -the executable; [The retail executable](#the-retail-executable-rt-5) below is the dry-run over the executable -itself, supplied separately. - -## Reproduce - -Build the runtime, then point it at the package: - -```powershell -powershell -File scripts/build_runtime.ps1 - -$game = "D:\path\to\your\package" -runtime\build\gta6rt.exe --dry-run "$game\XboxBvhBuilder.dll" --game-dir $game -``` - -Each run prints one line per mapped module: - -``` -XboxBvhBuilder.dll base=0000000180000000 size=909312 entry=+0x227cc shim=4 host=53 module=0 unimplemented=0 - shim d3d12_xs.dll!D3D12SerializeVersionedRootSignature - shim xmem.dll!XMemVirtualQuery - shim api-ms-win-crt-runtime-l1-1-0.dll!_configure_narrow_argv - shim api-ms-win-core-libraryloader-l1-2-0.dll!DisableThreadLibraryCalls -1 module(s) mapped, 0 unimplemented import(s) -unimplemented by return policy: hresult=0 other=0 -``` - -`shim` counts imports served by the clean-room tables, `host` counts imports served by the desktop DLLs, -`module` counts imports served by another bundled image, and `unimplemented` counts imports with no binding. - -## Measured result - -All 16 DLLs in the package map at their preferred base `0x180000000` with no relocation, and every import binds. `gta6rt --init` on each one also runs its TLS callbacks and `DllMain` and exits 0 (counts re-measured with `--dry-run` and `--init` on `main` `aa2988cc`, Windows 11): - -| Image | Size of image | Entry RVA | Shim | Host | Module | Unimplemented | `--init` | -|---|---:|---:|---:|---:|---:|---:|---| -| `Bink2Scarlett.dll` | 278,528 | `0x2ac1c` | 4 | 56 | 0 | 0 | exit 0 | -| `XboxBvhBuilder.dll` | 909,312 | `0x227cc` | 4 | 53 | 0 | 0 | exit 0 | -| `amd_fidelityfx_upscaler_xbox.dll` | 802,816 | `0x26780` | 6 | 80 | 0 | 0 | exit 0 | -| `amd_fidelityfx_loader_xbox.dll` | 32,768 | `0x18d0` | 5 | 17 | 0 | 0 | exit 0 | -| `libHttpClient.GDK.dll` | 999,424 | `0x11f0` | 26 | 172 | 0 | 0 | exit 0 | -| `XCurl.dll` | 188,416 | `0x17b0` | 24 | 116 | 0 | 0 | exit 0 | -| `concrt140.dll` | 303,104 | `0x29160` | 2 | 101 | 0 | 0 | exit 0 | -| `msvcp140.dll` | 577,536 | `0x525a0` | 13 | 174 | 0 | 0 | exit 0 | -| `msvcp140_1.dll` | 36,864 | `0x15c0` | 2 | 31 | 0 | 0 | exit 0 | -| `msvcp140_2.dll` | 192,512 | `0x1efa0` | 2 | 94 | 0 | 0 | exit 0 | -| `msvcp140_atomic_wait.dll` | 81,920 | `0x3c80` | 4 | 60 | 0 | 0 | exit 0 | -| `msvcp140_codecvt_ids.dll` | 28,672 | `0x1340` | 2 | 22 | 0 | 0 | exit 0 | -| `vccorlib140.dll` | 344,064 | `0x27e50` | 7 | 107 | 0 | 0 | exit 0 | -| `vcomp140.dll` | 86,016 | `0x6580` | 7 | 71 | 0 | 0 | exit 0 | -| `vcruntime140.dll` | 110,592 | `0xf890` | 3 | 38 | 0 | 0 | exit 0 | -| `vcruntime140_1.dll` | 49,152 | `0x3e90` | 1 | 33 | 0 | 0 | exit 0 | - -The 12 Microsoft-signed DLLs in this table (the 10 VC++ runtime DLLs, `XCurl.dll` and `libHttpClient.GDK.dll`) report an Authenticode hash mismatch as shipped, because the Xbox packaging fills the load-config `CodeIntegrity` field of all 16 DLLs after signing; this is expected in every copy of the package and is not a sign of tampering ([jasontheminions's finding](https://github.com/ItsNotRexed/Leonida/issues/8504#issuecomment-7110985774)). - -Since the library-loader shims (`runtime/shims/library_loader.cpp`), a module's `LoadLibrary*`, `GetModuleHandle*`, `GetProcAddress` and `FreeLibrary` imports count as shim, through `kernel32`, `kernelbase` or the `api-ms-win-core-libraryloader-*` set it names. That is why every image above has a few more shim and fewer host imports than before; the Xbox-specific imports below are unchanged. `DisableThreadLibraryCalls` is served the same way: a mapped module gets `TRUE` (the real function refuses a module the Windows loader did not map, which failed the `DllMain` of the four `msvcp140_*` satellite DLLs), and any other handle goes to the real function. - -The process shim (`runtime/shims/process.cpp`) serves `ExitProcess` and `GetCommandLineA/W` the same way: through `kernel32`, `kernelbase`, and `api-ms-win-core-processthreads-l1-1-0` and `api-ms-win-core-processenvironment-l1-1-0`, the sets the API-set umbrella libraries (`OneCore_apiset.lib`, `mincore.lib`) bind them to. `vcomp140.dll` imports `ExitProcess` from the first of these. The UCRT's `_get_narrow_winmain_command_line` and `_get_wide_winmain_command_line` are served too, so a `WinMain` executable gets the game's command line as `lpCmdLine`. `abort()` raises `SIGABRT` when the guest installed a handler (the guest's `signal()` import binds to the host CRT, so its table is the one raised here); with the default or ignore disposition, or a handler that returns, the run still ends with code 3. `run_tiny_game_abort_exit_codes` compares that with a native run of the stand-in image. The table above is `gta6rt --dry-run` on each DLL at the commit that added this paragraph. - -The shims added since account for the rest of the difference from the first version of the table. The UCRT's `_configure_narrow_argv`, `_configure_wide_argv`, `__p___argc`, `__p___wargv` and `abort` are served by `runtime/shims/process.cpp`, which is why almost every DLL gained one or two. The file-system calls listed in *Console paths and the write overlay* below (`CreateFile2`, `CopyFile2`, `CreateDirectoryW`, `FindFirstFileExW`, `SetFileAttributesW` and the rest) account for `msvcp140.dll`, `vcomp140.dll`, `Bink2Scarlett.dll`'s `CreateFile2` and part of the two HTTP clients. `winhttp.dll` is a module the shims own (*WinHTTP offline* below), so every `WinHttp*` import binds to it: 15 in `libHttpClient.GDK.dll` (all 16 but `WinHttpCrackUrl`) and 15 in `XCurl.dll` (all but `WinHttpQueryOption`). That is why the two HTTP clients moved the most: 11 to 26 and 9 to 24 shim imports. - -The UCRT argv configuration imports honor the executable's startup mode. Each run starts with `argc == 0` and -null narrow/wide argument tables, while `GetCommandLineA/W` is already available to TLS and process-attach -callbacks. Default startup publishes unexpanded arguments for its chosen width. `setargv.obj` / `wsetargv.obj` -startup expands wildcard arguments against the host working directory, including quoted patterns; an unmatched -pattern stays literal. Narrow expansion searches the ACP-converted pattern and converts matching names back to -ACP, so its matches can differ from wide startup. The two widths retain independent tables, and the most recently -configured width sets the shared `argc`. `noarg.obj` leaves the initial tables null; later no-argument -configuration is a no-op that preserves existing pointers and counts. These are guest-owned tables, without -changing the host CRT's argument globals. This does not add console-path wildcard routing or change the legacy -`msvcrt!__getmainargs` wildcard policy. `run_argv_modes` compares the same six linker-selected MSVC fixtures -natively and through the loader; `run_startup_cmdline` also checks native preconfiguration and command-line -identity through attach and entry. - -The six unique Xbox-specific imports (eight consumer/import pairs) are exactly the set recorded in -[`d3d12_vulkan.md` §7](d3d12_vulkan.md#7-prior-art-and-measured-xbox-abi): - -| Consumer | Import | Binding | -|---|---|---| -| `Bink2Scarlett.dll` | `xmem.dll!XMemAlloc` | shim | -| `Bink2Scarlett.dll` | `xmem.dll!XMemFree` | shim | -| `XboxBvhBuilder.dll` | `xmem.dll!XMemVirtualQuery` | shim | -| `XboxBvhBuilder.dll` | `d3d12_xs.dll!D3D12SerializeVersionedRootSignature` | shim | -| `amd_fidelityfx_upscaler_xbox.dll` | `xmem.dll!XMemAlloc` | shim | -| `amd_fidelityfx_upscaler_xbox.dll` | `xmem.dll!XMemFree` | shim | -| `amd_fidelityfx_upscaler_xbox.dll` | `xmem.dll!XMemGetWorkingSetStatistics` | shim | -| `amd_fidelityfx_upscaler_xbox.dll` | `d3d12_xs.dll!D3D12CreateRootSignatureDeserializer` | shim | - -The video path (`Bink2Scarlett.dll`), the BVH builder and the FidelityFX upscaler therefore all go through the -two shim DLLs that already exist. `libHttpClient.GDK.dll` and `XCurl.dll` import only desktop APIs. - -`xmem.dll!XMemTransferMemory` is not imported by any of these DLLs, but a Series executable calls it during startup -(reported in [#5934](https://github.com/ItsNotRexed/Leonida/issues/5934#issuecomment-7101779516)). Its GDK reference -page is an NDA topic, but Microsoft's public [NetRumble](https://github.com/microsoft/XBOX-MonoGame-NetRumble/blob/203255e785f2ab2671a9d83b724eaa14d5b07414/console/NetRumble.Bootstrap/Main.cpp#L135-L145) -sample and FNA's [NativeAOT-Xbox](https://github.com/FNA-XNA/NativeAOT-Xbox/blob/b9dc547afd0e05f45764d670ec49e0ac7997a301/Bootstrap/Main.cpp#L117-L124) -bootstrap call it as `if (!XMemTransferMemory(XMemTransferTitleToSystem, size))` with a `size_t` in multiples of -2 MiB, to move budget from the title's memory partition to the system's. A PC has no such partition, so the shim -returns `TRUE` for every direction and size and allocates nothing; with `--trace` it records each distinct direction -and size as an `xmem_transfer` event, because the enum values are not public. `xmem_test` covers it. - -Seven more `xmem.dll` imports follow argument shapes measured locally at a title's call sites (the comments in -`runtime/shims/xmem.cpp` give each shape): - -- `XMemAllocDefault` and `XMemFreeDefault` take `XMemAlloc`'s and `XMemFree`'s arguments and share their heap. -- `XMemAllocatePhysicalPages(attributes, UINT64* count, UINT64* pages)` returns a `BOOL` and the count it allocated. - Each call is one pagefile-backed section of `count` 64 KiB pages. A page number is a 4 KiB frame number: a - non-zero multiple of 16 below 2^25, which is what the measured title assumes when it packs them. `0` means "unmap". -- `XMemMapPhysicalPages(address, UINT64 count, pages)` returns the address. A null page array unmaps. - `XMemMapPhysicalPagesScatter(addresses, UINT32 count, pages)` returns a `BOOL`, and a `0` entry unmaps. - `XMemFreePhysicalPages(UINT64 count, pages)` returns a `BOOL`. Every page is its own view, mapped with - `MapViewOfFile3` into a 64 KiB placeholder, so a page keeps its contents across remaps and can be mapped twice. -- The windows are reserve-only 64 KiB-page `XMemVirtualAlloc` regions. The shim reserves them as placeholders and - keeps their protection, which mapped pages get (AWE's rule). The measured title also reserves a placeholder with - `MEM_RESERVE_PLACEHOLDER` and carves windows out of it with `MEM_REPLACE_PLACEHOLDER`, and the shim passes both - through. **ASSUMPTION:** nothing commits into a window with `kernel32!VirtualAlloc`, which a placeholder refuses. -- `XMemVirtualAlloc` used to refuse 2 MiB pages, and five of the 23 measured calls commit them. They are now - committed 2 MiB-aligned through `VirtualAlloc2`. The attribute word is recorded (`xmem_attributes`) and the - console's `PAGE_GRAPHICS_*` bits are dropped from the protection, as before. -- `XMemIsToolsMemAvailable()` is `FALSE`: a PC has no development-kit tools memory. The measured title asks only - on an out-of-memory path, after an allocation has already failed. - -## The retail executable (RT-5) - -`game_scarlett_master.exe` (120,181,760 bytes on disk, SHA-256 -`e95020b2fa4a721db3df59fdecf75621730ac559d8835252f6c3b658d5a08993`) is a PE32+ x86-64 image with no resource -section. `gta6rt --dry-run` maps it at its preferred base together with the four package DLLs it imports, and -exits 0 with nothing on stderr: - -```powershell -$game = "D:\path\to\your\package" -$scratch = Join-Path $env:TEMP 'leonida-overlay' -runtime\build\gta6rt.exe --dry-run "D:\path\to\game_scarlett_master.exe" --game-dir $game --overlay $scratch -``` - -`--overlay` points the write overlay away from `\overlay`, so a dry run writes nothing into the package. -Measured at `1cc6e3c1`, Windows 11, MSVC 14.44: - -| Image | Base | Size of image | Entry RVA | Shim | Host | Module | Unimplemented | -|---|---|---:|---:|---:|---:|---:|---:| -| `game_scarlett_master.exe` | `0x140000000` | 184,995,840 | `0x56a1ec8` | 53 | 432 | 72 | **30** | -| `XboxBvhBuilder.dll` | `0x180000000` | 909,312 | `0x227cc` | 5 | 52 | 0 | 0 | -| `amd_fidelityfx_loader_xbox.dll` | relocated | 32,768 | `0x18d0` | 6 | 16 | 0 | 0 | -| `libHttpClient.GDK.dll` | relocated | 999,424 | `0x11f0` | 28 | 170 | 0 | 0 | -| `Bink2Scarlett.dll` | relocated | 278,528 | `0x2ac1c` | 5 | 55 | 0 | 0 | - -The 72 module imports are served by those four DLLs. The 30 unimplemented imports all fall under the dry-run's -policy "other" (none is counted as returning an `HRESULT`), and they come from seven Xbox-only DLLs: - -| DLL | Unimplemented imports | What the names suggest (not measured) | -|---|---:|---| -| `xmem.dll` | 7: `XMemAllocDefault`, `XMemAllocatePhysicalPages`, `XMemFreeDefault`, `XMemFreePhysicalPages`, `XMemIsToolsMemAvailable`, `XMemMapPhysicalPages`, `XMemMapPhysicalPagesScatter` | the console's physical page and default allocation routines; `XMemAlloc`, `XMemFree`, `XMemVirtualQuery`, `XMemGetWorkingSetStatistics` and `XMemTransferMemory` already bind | -| `d3d12_xs.dll` | 1: `D3D12ConfigureVirtualMemoryX` | GPU virtual memory setup | -| `xg_xs.dll` | 2: `XGCreateTextureComputer`, `XGSuggestSwizzleMode` | texture layout computation | -| `XCRDAPI.dll` | 1: `DStorageGetFactory` | DirectStorage | -| `chad.dll` | 5: `XDspActivate`, `XDspConnectWithMaximumStreamLimit`, `XDspDeactivate`, `XDspDisconnect`, `XDspSubmitCommand` | the audio DSP | -| `xapu.dll` | 5: `XApuConnect`, `XApuDequeueResult`, `XApuDisconnect`, `XApuEnqueueCommand`, `XApuGetResultCount` | the audio processing unit | -| `AcpHal.dll` | 9: `AcpHalAllocateShapeContexts`, `AcpHalCreate`, `AcpHalReleaseShapeContexts`, `ApuAlloc`, `ApuCreateHeap`, `ApuFree`, `ApuIsVirtualAddressValid`, `ApuMapApuAddress`, `ApuMapVirtualAddress` | the audio hardware layer | - -The game executable imports two functions from `xg_xs.dll`, the console's texture layout library: -`XGSuggestSwizzleMode` (2 call sites, in the helper that fills a texture description) and `XGCreateTextureComputer` -(4 call sites, which use slots 1, 2, 8 and 10 of the returned object's vtable). The runtime has no model of the console -resource layout, so `runtime/shims/xg_xs.cpp` computes none: both return `E_NOTIMPL` and write no layout. Two of the -four `XGCreateTextureComputer` callers ignore the HRESULT and call through the object at once, so the shim still stores -a static object in the out pointer; its slot 1 (read as `Release`) does nothing, and every other slot up to 31 logs its -index and caller once and returns `E_NOTIMPL` without writing its arguments. The call shapes and the reasoning are at -the top of the file; `xg_xs_test` covers them. Textures whose layout the game asks for are therefore not laid out yet. -The table above was measured before this shim and still lists these two as unimplemented; they are served now. - -Only two of these DLLs have a shim in the repository (`xmem.dll` and `d3d12_xs.dll`), and they are not complete: -they hold 8 of the 30 unimplemented imports. The other 22 are in five DLLs (`xg_xs.dll`, `XCRDAPI.dll`, `chad.dll`, -`xapu.dll`, `AcpHal.dll`) with no shim at all. - -The seven `xmem.dll` imports are served now (see the `xmem.dll` notes above), so the same dry run lists 23. - -`--init` on the same files also exits 0 with nothing on stderr. Its `--trace` file has 15 lines: the four package DLLs' -`DllMain(DLL_PROCESS_ATTACH)` each return 1, the executable's two TLS callbacks run at process attach (reason 1) and -again at detach (reason 0), and there is no `exception`, `error` or `unimplemented_call` event. So none of the 30 -unimplemented imports is reached by the TLS callbacks or the `DllMain`s. - -What this does not show: `--run` has not been run, so the entry point has not been called and no import is known to be -reached on the way to the first frame. A bound import is not a working one (the binding only says a function with -that name exists), and an unimplemented import stops the run only if the title calls it -([When an unimplemented import is called](#when-an-unimplemented-import-is-called)). The executable imports 25 -functions from `ws2_32.dll` (23 by ordinal, plus `getaddrinfo` and `freeaddrinfo`) and the loader binds them to the -host's, so a `--run` can open real sockets: run it with the network off. `winhttp.dll` is served by the offline shim, -which opens none. - -## Console paths and the write overlay - -A title's file calls name the console's drives, so `GAME:\data\x.sps` is a file inside the installed game folder. -[ivall/xcl](https://github.com/ivall/xcl) (GPL-2.0-only; facts only, no code) documents for Xbox Series GDK titles that -`GAME:` maps to the game folder and that writes go to a writable overlay instead of the package, which stays read-only. -`gta6rt` therefore shims `CreateFileA/W`, `FindFirstFileA/W`/`FindNextFileA/W`/`FindClose`, `GetFileAttributesA/W`, -`GetFileAttributesExA/W` and `DeleteFileA/W` (`runtime/shims/file_system.cpp`), under `kernel32.dll`, `kernelbase.dll` -and the `api-ms-win-core-file-*` sets a GDK title links against. - -- A `GAME:` path (any case, `\` or `/`) maps under `--game-dir`. A path without the prefix is a host path and is - passed to the host unchanged. `--game-dir` defaults to the image's folder. `gta6rt` makes it and `--overlay` - absolute at startup, so a bare image name (`gta6rt --run game.exe` from the game folder) and a relative folder - both keep naming the same place after the title changes its current directory (CTest `run_tiny_game_dir`). - `G:\` is the same folder as `GAME:`, and `T:\` is a scratch folder, `\.gta6rt-temp`, that `GAME:` does - not see (RT-218; the other console layers map those two drives this way, and only the executable can say which - spelling GTA VI uses). A path under `--game-dir` or the overlay is always a host path, so a package that sits on - a host drive `G:` keeps working, and with no folders configured `G:` and `T:` stay host drives. - `T:\` is a drive root like `GAME:\`: its folder is made on the first `T:` call, so it is a folder before anything - is written there, and removing or moving it fails with `ERROR_ACCESS_DENIED`. -- An open that can write, and `DeleteFile`, use the overlay: `--overlay DIR`, default `\overlay`. A - write-open of a package file copies it into the overlay first, so `OPEN_EXISTING` keeps its bytes. The copy is - written under `\.gta6rt-copy` and renamed into place, one copy-up at a time, so a process killed mid-copy - or two threads opening the same file never leave a truncated copy under its name; a delete of a - package file leaves an empty marker under `\.gta6rt-deleted`, which reads and listings treat as gone. The - package is never written. -- `DeleteFileA/W` checks the visible file's `FILE_ATTRIBUTE_READONLY`: a read-only package file with no overlay is - refused with `ERROR_ACCESS_DENIED` before writing a deletion marker. An overlay copy supplies its own attributes, - so a writable overlay can still be deleted when the package file underneath is read-only. The native A/W controls - in `file_system_test` cover these cases and mixed hidden, system and archive attributes. -- Console file shims support resolved Windows paths beyond `MAX_PATH`. A short `GAME:`, `G:` or `T:` name can - reach a file under a deep package or overlay root, with the same overlay and listing rules. -- Reads prefer the overlay copy and then the package. `FindFirstFile` merges the two folders, the overlay winning on a - name, and hides deleted names, the marker folder and the copy folder. -- A path that climbs above `GAME:` with `..`, or names another drive, fails with `ERROR_INVALID_NAME`, so a title - cannot reach outside the package and the overlay. - -- `CreateDirectory*` makes the folder in the overlay. A name the title can already see, including a folder only the - package has, fails with `ERROR_ALREADY_EXISTS`; a missing parent with `ERROR_PATH_NOT_FOUND`. -- `RemoveDirectory*` needs the folder empty in the title's view (`ERROR_DIR_NOT_EMPTY` otherwise). An overlay folder is - removed; a package folder is hidden by a `.gta6rt-dir` marker inside its marker folder, and stays on disk. A marker - folder on its own (left by a file deleted below it) does not hide anything. -- `MoveFile*` writes the destination in the overlay. A package file is copied there and its old name deleted by a - marker; an overlay file or an overlay-only folder is renamed. An existing destination needs - `MOVEFILE_REPLACE_EXISTING` even when only the package has it. Moving a package folder fails with - `ERROR_ACCESS_DENIED` (as deleting one does), a move between `GAME:` and a host path with `ERROR_NOT_SAME_DEVICE`, and - `MOVEFILE_DELAY_UNTIL_REBOOT` with `ERROR_INVALID_PARAMETER`. -- `CopyFile`, `CopyFileEx` and `CopyFile2` read the source the way a read does and write a `GAME:` destination in the - overlay; fail-if-exists counts a name only the package has. Either side can be a host path. `CopyFile2` checks its - parameter block before preparing the destination: one shorter than `COPYFILE2_EXTENDED_PARAMETERS` is - `E_INVALIDARG` and writes nothing, as Windows answers. Where the host has no `CopyFile2` (Wine 9, whose loader binds - the import to a stub that aborts the process), the shim copies with `CopyFileExW` instead: the flags both calls - define and the cancel flag are passed on (a flag already set cancels before anything is written), CopyFile2-only - requests that leave the contents as `CopyFileExW` writes them (no offload, compressed traffic, sparse copy, ...) - are dropped, and a `COPYFILE2` progress routine is not called. A call it can't run as asked (`SKIP_ALTERNATE_STREAMS`, - `DIRECTORY`, `OPEN_AND_COPY_REPARSE_POINT`, `IGNORE_SOURCE_ENCRYPTION`, an unknown flag, or a longer V2 block) is - `ERROR_NOT_SUPPORTED` and writes nothing. `rt::fs::force_copy_file2_fallback` makes the test take this path on - Windows too. A cancel flag that is already set is answered before the host's `CopyFile2` is called as well, since - Wine 10 and 11 export `CopyFile2` but ignore the flag; clearing it lets the same call be retried. -- `SetFileAttributes*` sets the attributes on the overlay copy, copying a package file up (or mirroring a package - folder) first, so the package keeps its own. -- A folder has to exist in the title's view before it is used. An open that writes fails with `ERROR_PATH_NOT_FOUND` - when its folder is missing, was removed, or is a file, and creates nothing (`T:` is the exception: a create there - makes its parent folders); `FindFirstFile` fails the same way for a - listing inside such a folder (a pattern that matches nothing in a folder that exists is still - `ERROR_FILE_NOT_FOUND`, and a listing directly below a file is `ERROR_DIRECTORY`, as on the host). -- `MoveFile*` onto the same name succeeds and changes nothing. A rename that changes only the case renames the overlay - entry; a package file gets an overlay copy under the new spelling, and a package folder is refused like any other - move of one. - -`runtime/test/file_system_test.cpp` (ctest `file_system`) covers this over folders it makes in `%TEMP%`. - -## When an unimplemented import is called - -The table above has no unimplemented imports, but the game executable will. A call to one used to return 0 -silently, which for an `HRESULT` function is `S_OK` with its out parameters never written; the caller then carries on -with stale pointers and fails somewhere unrelated. `LEONIDA_UNIMPLEMENTED` chooses what the thunk does instead -(details in `runtime/README.md`): - -- `log` (default): print the name once, return 0. Unchanged. -- `fail`: return `E_NOTIMPL` for imports known to return `HRESULT`, 0 otherwise. -- `stop`: print the import, the caller as `module+RVA` and rcx/rdx/r8/r9, then break (debugger) or exit with code 3. - -The `--dry-run` report ends with `unimplemented by return policy: hresult=N other=N`, so the first run against the -executable shows how many of its missing imports `fail` would turn into errors. - -The `HRESULT` list is by DLL and name: `D3D12Create*` and `D3D12Serialize*` (`d3d12.dll`, `d3d12_xs.dll`), -`D3D12GetDebugInterface`, `D3D12EnableExperimentalFeatures`, `CreateDXGIFactory*`, `DXGIGetDebugInterface1`, -`DXGIDeclareAdapterRemovalSupport` (`dxgi.dll`), and in `xgameruntime.dll` `XGameRuntimeInitialize`, `XGameEventWrite` -and the families `XAsync*`, `XTaskQueue*`, `XUser*`, `XStore*`, `XGameSave*`, `XPackage*`, `XGameUi*` except the 33 -functions their public reference pages show returning `void`, `bool` or `int` (for example `XTaskQueueDispatch`, -`XUserCloseHandle`, `XStoreIsLicenseValid`). The mixed `XSystem*`, `XGameStreaming*`, `XThread*` and `XDisplay*` -families are not listed. The sources are the Microsoft Learn pages for the D3D12/DXGI functions and the GDK reference -(`gaming/gdk/docs/reference/system//functions/`); `D3D12XboxCreateDevice` is matched by name from the -measurement in `d3d12_vulkan.md`, because its page could not be found. - -## Run-time loaded modules - -Not every console module is reached through an import table. `libHttpClient.GDK.dll` and `XCurl.dll` both use the -GDK runtime, but `dumpbin /imports` shows **no import of `xgameruntime.dll`** in either. Both carry the wide string -`xgameruntime.dll` and the ASCII names `InitializeApiImpl`, `InitializeApiImplEx`, `InitializeApiImplEx2`, -`QueryApiImpl` and `UninitializeApiImpl`, next to a statically linked `XGameRuntimeInitialize`. So `xgameruntime.lib`'s -thunks `LoadLibraryW` the runtime and `GetProcAddress` those five names at run time. xodus-gaming/xgameruntime-docs -(GPL-3.0) documents the same mechanism for PC GDK titles: `InitializeApiImplEx2` is what -`XGameRuntimeInitialize[WithOptions]` calls, and `QueryApiImpl` hands out the runtime's COM classes, whose methods -mostly correspond one to one to the `xgameruntime.lib` functions. The executable is very likely linked the same way. - -Bound to the host, those calls would load the PC's Gaming Services runtime, or fail, and never reach the offline -shims. `runtime/shims/library_loader.cpp` therefore answers `LoadLibrary*` and `GetModuleHandle*` for a module the -shim registry owns (`rt::shims::owns_dll`: `xgameruntime.dll`, `d3d12_xs.dll`, `xmem.dll`, `xg_xs.dll`, `gameinput.dll`) -with a pseudo-handle, and `GetProcAddress` on it resolves through the registry. A name the registry doesn't serve is `NULL` -with `ERROR_PROC_NOT_FOUND` and is logged once. Every other module goes to the host unchanged. - -`runtime/shims/xgameruntime.cpp` serves the five entry points. The initializers succeed offline and log the GDK -version and mode once. `QueryApiImpl` serves `XThreadingImpl`, `XErrorImpl`, `XNetworkingImpl`, `XSystemImpl`, -`XPersistentLocalStorageImpl`, `XPackageImpl`, `XGameImpl`, `XGameRuntimeFeatureImpl` and `XSystemAnalyticsImpl` -(below), and `XUserImpl`, `XGameSaveImpl`, `XStoreImpl`, `XGameEventImpl`, `XGameUiImpl`, `XGameStreamingImpl`, -`XDisplayImpl`, `XUserDeviceImpl`, `XAccessibilityImpl` and `XLauncherImpl` from xgameruntime-docs' layout (below); for any other class it logs -the class and interface id and returns `0x80070032`, the documented error for a class the runtime doesn't provide, so -the first boot with the executable lists the classes to implement next. `xgameruntime_test` drives this path through -the api-set binding `XCurl.dll` uses, and calls the classes `xgameruntime.cpp` serves slot by slot. - -`XCurl.dll` has a second way in. One of its functions reads `HKLM\Microsoft\GamingServices` value -`ServiceRetryTimeout`, then `LoadLibraryExW(L"gameplatformservices.dll", nullptr, LOAD_LIBRARY_SEARCH_SYSTEM32)` and -`GetProcAddress`es `GetApiVersionImpl` and `QueryApiImpl`. It calls the first through the CFG dispatch with two -pointers to 64-bit locals (the result is not read), compares the pair with the one it saw last and keeps it. On the -host that load would find a PC's Gaming Services runtime, which bypasses the offline classes, or nothing, in which -case XCurl returns `0x87E00196`. The shims own `gameplatformservices.dll` too: its `QueryApiImpl` is the offline -one, and `GetApiVersionImpl(uint64_t*, uint64_t*)` writes the same two values every time. - -### Class layouts, measured - -Each `xgameruntime.lib` function the package's DLLs link is a thunk of the same shape: it calls a helper with the -class id (passed as both the class and the interface id), which initializes the runtime once and calls -`QueryApiImpl`; then it calls one vtable slot with `this` followed by the function's own arguments, and calls -`Release` (slot 2). The helper treats `0x80040154` (class not registered) from `QueryApiImpl` specially: it turns it -into `0x89240107` and calls an error hook; any other failure is returned as is. - -The slots below were read from the thunks statically linked into `libHttpClient.GDK.dll` and `XCurl.dll` -(disassembled with `llvm-objdump`; no code was run, nothing else read). Every slot called matches, in argument -count and width, the function at that position of xgameruntime-docs' "Layout" list after IUnknown's three slots: - -| Class | Slots called | Checked against the documented order | -|---|---|---| -| `XThreadingImpl` (`IXThreadingImpl`, 28 methods, slots 3-30) | 3-7 and 9-30 (`libHttpClient.GDK.dll`), 3, 5, 12, 16-18, 22, 29 (`XCurl.dll`) | e.g. 7 `XAsyncBegin` (5 args), 9 `XAsyncSchedule` (pointer, 32-bit), 10 `XAsyncComplete` (pointer, HRESULT, size), 12 `XTaskQueueCreate` (two 32-bit modes, pointer), 16 `XTaskQueueDispatch` (returns a byte), 19 `XTaskQueueSubmitDelayedCallback` (5 args), 22 `XTaskQueueTerminate` (pointer, bool, two pointers), 27 `XThreadSetTimeSensitive` (bool), 30 `XThreadIsTimeSensitive` (returns a byte). Slot 8 (`XAsyncBeginAlloc`, private) is never called; slot 28 (`XTaskQueueIsEmpty`, private) takes no arguments | -| `XErrorImpl` (`IXErrorImpl`, slots 3-5) | 3 (`XCurl.dll`) | slot 3, the docs' `_unknown_`, takes an HRESULT and a pointer: `XErrorReport(HRESULT, const char*)` | -| `XNetworkingImpl` (`IXNetworkingImpl2`, slots 3-20) | 11-17 (`XCurl.dll`), 3-20 (`libHttpClient.GDK.dll`, each in its documented argument shape, e.g. 18-20 (enum, u64 pointer / u64 / pointer)) | the Utf16 `XNetworkingQuerySecurityInformationForUrl*` trio, `XNetworkingVerifyServerCertificate`, `XNetworkingGetConnectivityHint`, `XNetworkingRegister/UnregisterConnectivityHintChanged` (pointer, bool). Served offline, asked for with `IXNetworkingImpl2`'s id | -| `XSystemImpl` (`IXSystemImpl5`, slots 3-8 known) | 3-8 (`libHttpClient.GDK.dll`) | 3-5 `XSystemGetConsoleId` / `GetXboxLiveSandboxId` / `GetAppSpecificDeviceId` (size, pointer, pointer each), 6 `XSystemHandleTrack` (two pointers, IXSystemImpl3), 7 `XSystemIsHandleValid` (pointer), 8 `XSystemAllowFullDownloadBandwidth` (bool, IXSystemImpl4); IXSystemImpl2 and 5 add no known method. Served offline | -| `XPersistentLocalStorageImpl` (`IXPersistentLocalStorageImpl3`, slots 3-8) | none called (the table of ids only) | slots 3-7 are `XPersistentLocalStorageGetPathSize` / `GetPath` / `GetSpaceInfo` / `PromptUserForSpaceAsync` / `PromptUserForSpaceResult`, slot 8 `XPersistentLocalStorageMountForPackage` (IXPersistentLocalStorageImpl3). Slots from the public xgameruntime-docs and Wine IDL, not measured in a caller. Served offline: the folder is `\.gta6rt-persistent`, which `GAME:` does not see, the quota is the 2048 MB of `MicrosoftGame.Config`, a prompt for space the quota holds succeeds, and `MountForPackage` is `E_NOTIMPL` | -| `XPackageImpl` (`IXPackageImpl3`) | 3-19, 22, 24-27, 30, 32-34, 37-40 (`libHttpClient.GDK.dll`) | slots 3-34 are IXPackageImpl's 32 entries, 35-38 IXPackageImpl2's 4, 39-40 IXPackageImpl3's 2. Served offline: 3 identifier, 4 packaged process, 11 user locale, 24-26 mount path size / path / close; the rest log once and return `E_NOTIMPL` | -| `XGameImpl` (`IXGameImpl3`, slots 3-5) | none in the package's DLLs (`libHttpClient.GDK.dll` holds its id only in the linked id table); the executable's requests are unmeasured | from the xgameruntime IDL: 3 `XGameGetXboxTitleId` (pointer), 4 `XLaunchNewGame` (two strings and a user handle, `void`), 5 `XLaunchRestartOnCrash` (string, u32). Served offline: the title id is `MicrosoftGame.Config`'s `` (`E_FAIL` without one), a new game launch is logged and ignored, a crash restart succeeds with nothing registered | - -**Two layout sources, and where they differ.** Besides xgameruntime-docs (GPL; facts only), the LGPL -`include/*.idl` of xodus-gaming/xgameruntime (from the Wine project) declares each interface with its methods in -order. Compared class by class, the two agree exactly wherever the docs list no `_unknown_` slot: `XGameSaveImpl`'s 30 -methods, `XGameImpl`'s 3, `XStoreImpl`'s 81 (to `IXStoreImpl6`). Where the docs list one, the IDL is not consistent: -for `XErrorImpl` it keeps the slot as `HRESULT __PADDING__()`, so the two still line up, but for `XUserImpl` (the -docs' slot 15) and `XDisplayImpl` (slot 3) it has no entry at all, and every later method sits one slot earlier than -the docs put it. Take a layout from the IDL only where it matches the docs' slot count, and read an IDL interface that -skips one of the docs' unknown slots as missing it, not as proof the slot doesn't exist. The measured slots in the -table above all follow the docs. - -`XThreadingImpl` forwards each slot to `third_party/xtaskqueue`, the same implementation the named exports use; -`XThreadSetTimeSensitive`/`XThreadIsTimeSensitive` keep a per-thread flag and the two private slots log once and -answer 0. `XErrorImpl` logs each report and hands it to the callback `XErrorSetCallback` set. -`XNetworkingImpl` answers as a console without a network would: the connectivity hint is initialized with no -connectivity (level None), the port and URL security-information queries fail with -`HRESULT_FROM_WIN32(ERROR_NETWORK_UNREACHABLE)` (the `*Async` ones complete with it through XAsync), the -certificate check fails the same way, the two change registrations send the one initial notification Microsoft -documents (on the queue's completion port, the process queue when none is given: the hint above, or port 0) and -none after, and the three `IXNetworkingImpl2` additions are `E_NOTIMPL`. - -`XUserImpl` (`runtime/shims/xgameruntime_user.cpp`) is served from xgameruntime-docs' layout alone. No package DLL -calls an `XUser*` slot (`libHttpClient.GDK.dll` only holds the GUID table). The executable links thunks for -`IXUserImpl` slots 3-5, 7-14, 19-25 and 33-34 and `IXUserGamertagImpl` slot 3 (`tools/gdk_runtime_calls.py`, from the -file alone): none of the slots logged on first use below, and of the offline failures only the token-and-signature -trio (23-25). What the slots must answer is still **not measured**; that is the executable's first boot. -- **Interfaces:** the class id doubles as `IXUserImpl`'s; `IXUserImpl2`-`6` answer with the same 50-slot vtable; - `IXUserGamertagImpl` (`XUserGetGamertag`) is a second interface. -- **The user:** one offline local user, always signed in. `XUserAddAsync` adds it with or without - `AddDefaultUserSilently` (with `AllowGuests` as well, it's `E_INVALIDARG`, as documented). It has fixed non-zero user - and local ids, is not a guest, is an adult, and has every privilege. Its gamertag comes from `LEONIDA_GAMERTAG` (15 - printable ASCII characters at most), `Player` otherwise. -- **Handles:** each one is its own allocation, closed once by `XUserCloseHandle`. `XUserCompare` is 0 for any two - handles, since they all name the one user. -- **Not available offline:** token, gamer-picture, MSA-token and resolve-issue requests fail synchronously before - starting (`E_GAMEUSER_FAILED_TO_GET_TOKEN`, `E_FAIL`, `E_GAMEUSER_FAILED_TO_RESOLVE`), so no `XAsyncBlock` waits. - `XUserGetSignOutDeferral` is `E_GAMEUSER_DEFERRAL_NOT_AVAILABLE`, and change callbacks are only tracked as tokens, - because the user never changes. -- **Logged on first use:** the docs' unknown slot 15 (answers `E_NOTIMPL`, so nothing reads outputs it didn't - write), the PC-only `IXUserImpl5` slots and `IXUserImpl6`'s undocumented sign-out trio (`XUserIsSignOutPresent`, a - bool, answers false). -- **Validity:** handles are looked up in a live set, never read, so a closed or foreign pointer is refused without - touching its memory, and a double close does nothing. Unregistering a change callback is never pending, so it - returns true for any token. `XUserIsStoreUser` is true, as documented for console. - -`xgameruntime_user_test` calls every served slot with the documented arguments. - -`XGameSaveImpl` (`runtime/shims/xgameruntime_gamesave.cpp`) is served from the same layout, also **not measured**: -- **Interfaces:** the class id doubles as `IXGameSaveImpl`'s; `IXGameSaveImpl2` (adds the three `XGameSaveFiles` - slots, 30-32) and `IXGameSaveImpl3` (no methods of its own) answer with the same 33-slot vtable. -- **Storage:** `LEONIDA_SAVE_DIR\local-user\\`, defaulting to `%LOCALAPPDATA%\Leonida\saves`, - names %-encoded: the layout `tools/saves.py import` writes ([saves.md](saves.md#importing-into-the-runtime)). - `XGameSaveFilesGetFolderWithUi*` gives `\files\`. -- **Updates:** writes and deletes are buffered; `XGameSaveSubmitUpdate` writes each new blob beside its final name, - then renames it over, so a failed write leaves the container as it was. One write or delete per blob per update; - an update past 16 MB (`GS_MAX_BLOB_SIZE`) is `E_GS_UPDATE_TOO_BIG`. -- **Names:** container names follow `XGameSaveCreateContainer`'s documented rule (`E_GS_INVALID_CONTAINER_NAME` - otherwise). -- **Reads:** `XGameSaveReadBlobData` fills the title's buffer with the `XGameSaveBlob` array, then each blob's bytes - and name, which the array points into; a buffer too small is `E_GS_PROVIDED_BUFFER_TOO_SMALL`, a missing blob - `E_GS_BLOB_NOT_FOUND`. The async read's result size (`XAsyncGetResultSize`) is the buffer it needs. -- **ASSUMPTION:** a fixed 1 GiB quota, blob names of at most 256 bytes, `blobNames = nullptr` reads every blob, - and `XGameSaveGetContainerInfo` of a missing container returns `S_OK` without a callback. `syncOnDemand` is - ignored: nothing syncs offline. - -`xgameruntime_gamesave_test` drives every slot against a temporary `LEONIDA_SAVE_DIR`. - -`XStoreImpl` (`runtime/shims/xgameruntime_store.cpp`), from the same layout; the game-license struct is measured -on the executable, the rest is not: -- **Interfaces:** the class id doubles as `IXStoreImpl`'s; `IXStoreImpl2`-`6` answer with the same 84-slot vtable. -- **Offline answers:** the game license is active and not a trial; a package's license is acquirable and valid; - there are no add-on licenses, no products in any query and no package updates. License-changed and license-lost - registrations hand out tokens; the callbacks never run. -- **Not available offline:** purchases, consumables, license tokens, collections and purchase ids, downloads and - every store UI fail before starting (`E_FAIL`, logged once). The docs' three unnamed slots and - `XStoreIsAvailabilityPurchasable` (no documented signature) answer `E_NOTIMPL`. -- **Measured on the executable:** `XStoreGameLicense` is 104 bytes. The title's `XStoreQueryGameLicenseResult` - call passes a 104-byte stack buffer and reads the SKU id as a C string at +0x00, the three booleans at - +0x13..+0x15, the trial id as a C string at +0x1C and the expiration time at +0x60. That fixes - `STORE_SKU_ID_SIZE` = 18 and the 104-byte total. -- **UNVERIFIED:** `SKU_ID_SIZE` = 5 and the exact `TRIAL_UNIQUE_ID_MAX_SIZE` = 64. The executable bounds the - trial id to at most 68 bytes (the expiration time is at +0x60) but reads it as a C string, so it does not name - the bound; 64 is the public source's value. It does not call either can-acquire slot (24-27), so - `XStoreCanAcquireLicenseResult` (12 bytes) is unmeasured. - -`xgameruntime_store_test` drives the license check, add-ons, updates, package licenses and product queries. - -`XGameEventImpl`, `XGameUiImpl`, `XGameStreamingImpl`, `XDisplayImpl`, `XUserDeviceImpl`, `XAccessibilityImpl` and -`XLauncherImpl` (`runtime/shims/xgameruntime_offline.cpp`), from the same layout, also **not measured**: -- **`XGameEventWrite`** succeeds; the events are dropped. The first one's name is logged, and - `LEONIDA_LOG_GAME_EVENTS=1` logs each with its dimensions and measurements. -- **Dialogs:** a message dialog's title, text and buttons go to the log (`[rt] game dialog:`), and it completes at - once with its default button; an error dialog's HRESULT and context are logged and it is dismissed. So an error - the game would show on screen at boot is readable in the log. Every other UI (profile cards, pickers, text entry, - web authentication, invites, state share) fails before starting (`E_FAIL`); the docs' unnamed slots and the - PC-hosted UI callbacks of `IXGameUiImpl4` answer `E_NOTIMPL`. -- **Streaming:** never streamed. `XGameStreamingInitialize` succeeds, `XGameStreamingIsStreaming` is false, there - are no clients, and the connection-state registration hands out a token that never fires. Every per-client slot - answers `E_GAMESTREAMING_NOT_INITIALIZED` (0x89245400), which a caller reading a bool sees as false (low byte - 0). -- **Not reached by the executable:** the parameter lists of `XGameUiShowMessageDialogAsync` and - `XGameStreamingRegisterConnectionStateChanged` are the GDK reference's, and the executable has no caller to check - them against. `tools/gdk_runtime_calls.py` finds no thunk for the message dialog and none for any - `XGameStreamingImpl` or `XUserDeviceImpl` slot. Of `XGameUiImpl` it links slots 7-8 and 17-19 only: the profile - card and text entry, which fail before starting. - -- **Accessibility and speech** (`IXAccessibilityImpl2`, slots 3-21): `XHighContrastGetMode` (5) answers Off and - `XClosedCaptionSetEnabled` (4) is accepted. No voice is installed: `XSpeechSynthesizerEnumerateInstalledVoices` - (8) calls back zero times and returns `S_OK`, `XSpeechSynthesizerCreate` (9) fails (`E_FAIL`) with a null handle, - and the handle calls (10-16, 21: close, default and custom voice, streams from text and SSML, stream size and - data) refuse the handle they were never given (`E_INVALIDARG`, outputs zeroed). The closed-caption properties (3) - and the speech-to-text display calls (6, 7, 17-20) fail with `E_FAIL`, writing nothing: their parameter lists - are not in the docs' layout. -- **`XLauncherImpl`** (`IXLauncherImpl`, slots 3-5): `XLaunchUri`, `XDisplayAcquireTimeoutDeferral` (null handle) - and `XDisplayCloseTimeoutDeferralHandle` fail with `E_FAIL`; nothing is launched. -- **ASSUMPTION:** the parameter lists of the speech calls and `XHighContrastGetMode` (Off is 0), from the GDK - reference; only the argument counts were measured, from `tools/gdk_runtime_calls.py` on the executable. -- **HDR:** `XDisplayTryEnableHdrMode` answers Disabled, because the host output is SDR. With `LEONIDA_HDR=1` it - answers Enabled with the documented default tone-map luminances (0.01, 1000, 1000 nits). -- **Devices:** every device belongs to the offline user (`XUserFindForDevice` hands out an `XUserHandle` the title - closes). `XUserRegisterForDeviceAssociationChanged` (slot 4) and - `XUserRegisterForDefaultAudioEndpointUtf16Changed` (7) keep each registration (its queue, duplicated, its context - and callback) under a token unique across both kinds and never 0; a null callback or token is `E_INVALIDARG`, and - queue and context are optional. The matching unregister (5, 8) removes it at once, with or without `wait`, and - returns true for every token, as `XUserUnregisterForChangeEvent` does: a token already removed, never handed out or - of the other kind changes nothing. Offline the device association and the default audio endpoint never change, so - no event is raised and no callback is ever queued or called. The user has no audio endpoint of its own - (`ERROR_NOT_FOUND`). Finding a controller shows no UI and gives an all-zero device id, as - documented for desktop. `APP_LOCAL_DEVICE_ID` is taken to be 32 bytes; no caller in the executable confirms it. - -`xgameruntime_offline_test` drives the five classes; `xgameruntime_offline_hdr` runs it again with -`LEONIDA_HDR=1`. - -Two more classes are served from `tools/gdk_runtime_calls.py`'s measurement of `libHttpClient.GDK.dll` (it finds the -thunks in the code without running it and prints, per class, the interface id asked for, the slots called and the -argument count each passes after `this`). Their thunks are in the DLL but nothing in it calls them; a title linked with -the same `xgameruntime.lib` gets the same thunks. Every slot is the function at that position of xgameruntime-docs' -layout with the documented argument count, and each behaves as Microsoft's reference page for that function says -(`runtime/shims/xgameruntime.cpp` cites both): - -| Class | Interface asked for | Slots (args after `this`) | Offline behaviour | -|---|---|---|---| -| `XGameRuntimeFeatureImpl` | its class id | 3 `XGameRuntimeIsFeatureAvailable` (1, returns `bool`) | True when `QueryApiImpl` serves the class the feature's functions go through (whichever `xgameruntime*.cpp` serves it) and the feature is documented for Windows: today XAccessibility, XSpeechSynthesizer, XLauncher, XAsync, XAsyncProvider, XTaskQueue, XThread, XError, XGame, XGameSave, XGameUI, XNetworking, XPackage, XPersistentLocalStorage, XStore, XSystem, XUser, XGameEvent, XGameStreaming. False for XDisplay (served, but documented for the consoles only), for the classes not served (XAppCapture, XGameInvite) and for values past the enum | -| `XSystemAnalyticsImpl` | its class id | 3 `XSystemGetAnalyticsInfo` (1: the result's address, as MSVC passes a returned struct to a member function) | The named export's `XSystemAnalyticsInfo` | - -Not served yet, though `libHttpClient.GDK.dll` has thunks for them: `XAppCaptureImpl` and `XGameInviteImpl`, -among others. - -Which classes the package's GDK modules reference, from a byte search for the class and interface GUIDs that -xgameruntime-docs lists (16-byte in-memory form, every `.dll` of the package; counts only, nothing else read): - -| Module | Runtime classes referenced (highest interface id present) | -|---|---| -| `XCurl.dll` | `XThreadingImpl`, `XErrorImpl`, `XNetworkingImpl` (`IXNetworkingImpl2`) | -| `libHttpClient.GDK.dll` | 23 of the 24 documented classes (not `XGameActivationImpl`), each GUID once: the ids of the `xgameruntime.lib` thunks the incremental link kept, 404 of them. `XThreadingImpl` (27 thunks), `XPackageImpl` (30), `XNetworkingImpl` (18) and `XSystemImpl` (6) are the ones read by hand above; `XErrorImpl` (3) and 18 more classes have thunks too. Only `XThreadingImpl`'s and `XErrorImpl`'s are called ([below](#measuring-which-runtime-classes-a-binary-calls)). Highest interfaces: `IXSystemImpl5`, `IXUserImpl5` (not 6), `IXGameImpl3`, `IXStoreImpl6`, `IXPackageImpl3` (not 4), `IXGameUiImpl4`, `IXGameSaveImpl3`, `IXGameStreamingImpl3`, `IXPersistentLocalStorageImpl3`, `IXUserDeviceImpl2`, `IXNetworkingImpl2` | -| every other `.dll` | none | - -So `XCurl.dll` needs threading, error reporting and networking from the runtime, and the interface versions in -`libHttpClient.GDK.dll` date the GDK the package was built with: newer than the first `IXUserImpl5`, older than -`IXUserImpl6`. - -### The retail executable's runtime classes (RT-5) - -`python -I tools/gdk_runtime_calls.py game_scarlett_master.exe` (from the file alone, nothing executed; `main` -`1cc6e3c1`) finds one `QueryApiImpl` helper at RVA `0x55de048` and **161** `xgameruntime.lib` thunks that reach **17** -runtime classes. 158 of the thunks are referenced from the image; three are present and unreferenced (one each in -`XPackageImpl`, `XThreadingImpl` and `XAccessibilityImpl`). - -The executable does not import `xgameruntime.dll`. Its import table has no such module, so the thunks are linked into -the image like `libHttpClient.GDK.dll`'s. The name occurs in the image as a UTF-16 string, which -`tools/pe_inspect.py` lists among the run-time load candidates (a string is where to look, not proof of a -`LoadLibrary`). The registry -therefore needs no module name beyond the `xgameruntime.dll` it already has, which settles the assumption at the top of -`runtime/shims/xgameruntime.cpp`. - -| Class | Thunks | Referenced | Served | -|---|---:|---:|---| -| `XAccessibilityImpl` | 10 | 9 | no | -| `XAppCaptureImpl` | 1 | 1 | no | -| `XLauncherImpl` | 3 | 3 | no | -| `XDisplayImpl` | 1 | 1 | yes | -| `XGameEventImpl` | 1 | 1 | yes | -| `XGameImpl` | 2 | 2 | yes | -| `XGameRuntimeFeatureImpl` | 1 | 1 | yes | -| `XGameSaveImpl` | 20 | 20 | yes | -| `XGameUiImpl` | 5 | 5 | yes | -| `XNetworkingImpl` | 10 | 10 | yes | -| `XPackageImpl` | 18 | 17 | yes | -| `XPersistentLocalStorageImpl` | 2 | 2 | yes | -| `XStoreImpl` | 44 | 44 | yes | -| `XSystemAnalyticsImpl` | 1 | 1 | yes | -| `XSystemImpl` | 3 | 3 | yes | -| `XThreadingImpl` | 18 | 17 | yes | -| `XUserImpl` | 21 | 21 | yes | - -"Served" is the tool's answer for the runtime sources at that commit. The three that are not: `XAccessibilityImpl` -(the speech-synthesizer slots 8-13, 15, 16 and 21 are referenced; slot 14 is not), `XAppCaptureImpl` (slot 5, -`XAppCaptureTakeScreenshot`) and `XLauncherImpl` (slots 3-5: `XLaunchUri` and the two display timeout-deferral calls). -Open pull requests serve them: #4235, #4307 and #4248. The slots of `XUserImpl`, `XStoreImpl` and `XGameSaveImpl` the -executable calls, and the argument counts the tool estimates from the registers, are in the report the tool writes. -`XErrorImpl`, which `XCurl.dll` and `libHttpClient.GDK.dll` call, is not among the executable's classes. - -### Measuring which runtime classes a binary calls - -`tools/gdk_runtime_calls.py` lists, from the file alone, the runtime classes, interface ids and vtable slots an image -calls through `xgameruntime.lib`'s thunks, so the executable's list is known before it first runs. -`scripts/first_look.ps1` runs it on the executable. - -```powershell -python -I tools/gdk_runtime_calls.py "$game\XCurl.dll" "$game\libHttpClient.GDK.dll" # text; --json for JSON -python -I tools/gdk_runtime_calls.py --out # writes .gdk_calls.txt and .json, prints a summary -``` - -It finds the helper the thunks share (the call a known id's `lea` feeds, after which a vtable slot past IUnknown is -called), takes every call to it as a thunk, reads the class and interface ids loaded into `rcx` and `rdx` (an id the -table doesn't know is listed as unknown) and records each slot called up to `Release`, within the thunk's -`.pdata` function or a byte window without one. The slots are named from `tools/gdk_runtime_classes.json`: the ids, -inheritance and method order of xodus-gaming/xgameruntime-docs (GPL-3.0; facts only), made with -`python -I tools/gen_gdk_runtime_classes.py `. An interface's slot table is its chain's methods, base -first, from slot 3. For each class the report says whether `runtime/shims/xgameruntime.cpp` has its class id (a -`constexpr GUID k...Class`), and for each thunk whether anything in the image reaches it: a call, tail jump, address -load or pointer in data, directly or through an incremental-link `jmp` stub, a call from another thunk counting only -when that thunk is reached. The argument count it prints is an estimate from the registers and stack slots written -before the call. - -Measured on the package's DLLs (counts and slots only): - -| Image | Thunks (referenced) | Classes and slots | -|---|---:|---| -| `XCurl.dll` | 16 (16) | `XThreadingImpl` 3, 5, 12, 16-18, 22, 29; `XErrorImpl` 3; `XNetworkingImpl` as `IXNetworkingImpl2` 11-17, as in the table above. The estimated argument counts match the documented signatures for all 16 | -| `libHttpClient.GDK.dll` | 404 (15) | 23 classes through one helper. `XThreadingImpl` 3-7, 9-30, `XNetworkingImpl` as `IXNetworkingImpl2` 3-20, `XSystemImpl` as `IXSystemImpl5` 3-8 and `XPackageImpl` as `IXPackageImpl3` 3-19, 22, 24-27, 30, 32-34, 37-40 match the slots read by hand; the other 19 classes have thunks too. Referenced: `XThreadingImpl` 3, 5, 7, 9-15, 17, 19, 22, 29 and `XErrorImpl` 3 only | -| the other 14 DLLs | 0 | none | - -`libHttpClient.GDK.dll` is incrementally linked (its entry point is a `jmp rel32` stub), and an incremental link -doesn't remove unreferenced functions (`/INCREMENTAL` turns `/OPT:REF` off): it carries 404 thunks and calls 15. Two -interface ids its thunks ask for are not in xgameruntime-docs: one of `XGameSaveImpl` (slots 33-49, after the 30 of -`IXGameSaveImpl3`'s chain) and one of `XGameStreamingImpl` (slots 3-6). The report prints them. - -Limits: - -- x86-64 only, and the thunk shape measured here: the class id loaded with a RIP-relative `lea` into `rcx` and the - interface id into `rdx` (or the class id copied there), the vtable read with `mov r,[r]` and the slot with - `mov r,[r+disp]` and a call (the CFG dispatch, or `call r`) or `call [r+disp]`, register copies followed. A - `QueryApiImpl` call outside the library's thunks is found only when it has that shape; helper calls it can't - follow to a slot are listed. -- Static: a referenced thunk may never run, and a reference through a computed address or from another module is - not seen. -- "Served" means the shim has the class id. It doesn't say that each slot does more than log, nor that - `QueryApiImpl` accepts the interface id the thunk passes; the report marks each request whose interface id is not - the class id. -- Names are as complete as xgameruntime-docs: an *unknown* entry keeps its slot unnamed, and a slot past an interface - without a documented layout is unknown. - -A title that calls `LoadLibrary*`, `GetModuleHandle*`, `GetProcAddress` or `FreeLibrary` on one of the package's -bundled DLLs (`Bink2Scarlett.dll`, `XboxBvhBuilder.dll`, the FidelityFX DLLs) is routed through `rt::Loader` instead of -the host Windows loader (excluding data-file loads and host-preferred CRTs). The loader maps the DLL from `--game-dir`, -binds its console imports (`xmem.dll`, `d3d12_xs.dll`) through the shim registry, runs its `DllMain` and TLS callbacks, -and resolves direct, ordinal and forwarded exports from the mapped image. `run_tiny_bundled_load` exercises this path -end to end with a synthetic bundled DLL importing `xmem.dll!XMemAlloc` and `XMemFree`. - -## WinHTTP offline - -`XCurl.dll` and `libHttpClient.GDK.dll` do their HTTP through WinHTTP: between them they import 16 functions from -`winhttp.dll` (`WinHttpOpen`, `Connect`, `OpenRequest`, `SendRequest`, `ReceiveResponse`, `QueryHeaders`, -`QueryDataAvailable`, `ReadData`, `WriteData`, `AddRequestHeaders`, `SetOption`, `QueryOption`, `SetTimeouts`, -`SetStatusCallback`, `CloseHandle`, `CrackUrl`) and nothing from Winsock. Nothing here goes online, so `gta6rt` owns -`winhttp.dll` (`runtime/shims/winhttp_offline.cpp`) and answers all 16 in-process: - -- Sessions, connections and requests are local handles: no name is resolved and no socket is opened. -- `WinHttpSendRequest` fails with `ERROR_WINHTTP_CANNOT_CONNECT`. On a `WINHTTP_FLAG_ASYNC` session it returns `TRUE` - and the failure arrives as WinHTTP delivers one: `WINHTTP_CALLBACK_STATUS_REQUEST_ERROR` with `{API_SEND_REQUEST, - ERROR_WINHTTP_CANNOT_CONNECT}`, on a thread-pool thread, with the request's context. A `dwContext` of 0 keeps the - context set with `WINHTTP_OPTION_CONTEXT_VALUE`, as the host's `winhttp.dll` does. A request closed first gets no - error callback. -- Reading a response and `WinHttpWriteData` fail with `ERROR_WINHTTP_INCORRECT_HANDLE_STATE`. Options, timeouts and - headers are accepted; `WINHTTP_OPTION_CONTEXT_VALUE` and `WINHTTP_OPTION_HANDLE_TYPE` can be queried. -- A status callback is inherited by child handles, and so is the parent's `WINHTTP_OPTION_CONTEXT_VALUE` as it is - when the child is made (measured on the host's `winhttp.dll`). Child handles report `HANDLE_CREATED`; every - handle reports `HANDLE_CLOSING` once, last. `WinHttpCrackUrl` only parses, so it is the host's. -- Because the shims own the module, a title's `LoadLibrary("winhttp.dll")` gets a pseudo-handle too, and a WinHTTP - function outside these 16 resolves to `NULL` (logged), never to the host. - -Each refused server is logged once (`[rt] winhttp: offline, refused :`), which records what a title -tried to reach. `runtime/test/winhttp_offline_test.cpp` (ctest `winhttp_offline`) covers the synchronous and -asynchronous paths with `.invalid` names; it opens no connection. - -## What this proves and what it does not - -- It proves the loader parses real Xbox Series PE files, maps their sections, applies no unnecessary relocation, - walks their import tables, and classifies every thunk. -- The loader also registers each image's unwind table. `pe_loader_test` checks, for every DLL present in - `LEONIDA_GAME_DIR`, that the whole exception directory is registered, that `RtlLookupFunctionEntry` returns - each entry for its first byte, and that the entry point is covered (directly, or through the `jmp rel32` thunks - an incrementally linked entry point goes through: a thunk touches no stack, so it has no entry of its own). - Measured on all 16 DLLs: every table passes the loader's checks and every entry resolves to itself. - - | Image | Unwind entries | Entry point | - |---|---:|---| - | `Bink2Scarlett.dll` | 527 | covered | - | `XboxBvhBuilder.dll` | 449 | covered | - | `amd_fidelityfx_upscaler_xbox.dll` | 477 | covered | - | `amd_fidelityfx_loader_xbox.dll` | 46 | covered | - | `libHttpClient.GDK.dll` | 2,452 | `jmp rel32` thunk to a covered function | - | `XCurl.dll` | 446 | covered | - | `concrt140.dll` | 1,121 | covered | - | `msvcp140.dll` | 1,228 | covered | - | `msvcp140_1.dll` | 45 | covered | - | `msvcp140_2.dll` | 469 | covered | - | `msvcp140_atomic_wait.dll` | 86 | covered | - | `msvcp140_codecvt_ids.dll` | 32 | covered | - | `vccorlib140.dll` | 697 | covered | - | `vcomp140.dll` | 195 | covered | - | `vcruntime140.dll` | 236 | covered | - | `vcruntime140_1.dll` | 79 | covered | -- It does **not** prove any imported function behaves correctly when called. That needs the executable, or a - harness that calls a known entry point. -- The executable's own imports are unknown. `MicrosoftGame.Config` names `game_scarlett_master.exe`; the package - here does not contain it, so its import table cannot be measured yet. -- The CRT images are present in the package, but `pe_loader.cpp` prefers the host copies for the `vcruntime`/ - `msvcp`/`concrt`/`vccorlib`/`vcomp` families. The table above maps the packaged images only to test the - parser; a real run binds the host copies. -- No game data is stored in this repository. The counts are output of a local run against the user's package. diff --git a/docs/sandbox.md b/docs/sandbox.md deleted file mode 100644 index 701c4e515..000000000 --- a/docs/sandbox.md +++ /dev/null @@ -1,86 +0,0 @@ -# Real-shader sandbox: placed props through the game's own translated shaders - -Follows [first_light.md](first_light.md) §5: a real camera through a vertex shader's constants, a TTPF albedo -through the bindless set with the game's sampler, and many placed world props instead of one model. Measured on -2026-11-22 from one retail Xbox Series install (1.0.2.1), on an NVIDIA GeForce RTX 4070 Ti SUPER (driver 621.24). -Nothing below reproduces game data; every number is a count. - -## 1. What runs - -`tools/sandbox.py` packs the props around a point (`tools/sandbox_scene.py`), picks one translated VS/PS pair from -the work folder and runs `vk_sandbox` (`runtime/test/vk_sandbox.cpp`), which draws every prop with that pair: vertex buffers at -locations 0–2 (position, normal, UV), a D32 depth buffer, one indexed draw per mesh and one descriptor table per -draw. `--window` opens a window to fly, walk or drive through the scene; `--check` renders one frame headless and -prints only counts. - -The shaders are not stand-ins: the VS transforms each vertex with the world rows and view-projection it loads from -the heap and lights it with its own `max(0.25, n·l)`; the PS samples the albedo through the T# it loads and the -S# literal in its code, and multiplies by the VS colour. Lighting beyond that, shadows and the G-buffer passes are -not part of this pair. - -## 2. How the pair is chosen - -The material → program table is in the executable (#2519), so the pair is chosen by what the shaders read, from -`/shaders/spirv/index.json` and the listings in `/shaders/dxbc/disasm`: - -| | Vertex shader | Pixel shader | -|---|---|---| -| inputs | POSITION (xyz), NORMAL (xyz), TEXCOORD (xy) | SV_Position, TEXCOORD, COLOR | -| user data | user SGPR 8 only (`ptr32_lo`) | user SGPR 8 (`ptr32_lo`) | -| bindings | none | 0, 1, 2 (images, samplers, hash table) | -| listing | three `s_load_dwordx4` from `s[8:9]` at 0x0, 0x40, 0x60; a 4-dword buffer load at 0x30 and a 16-dword one at 0x160 | one `s_load_dwordx8` from `s[8:9]` + 0x20; one `image_sample`; `exp mrt0` | - -On the 1.0.2.1 corpus 3 VS and 231 PS match the signatures, and 2 VS and 4 PS also match the listing patterns; -they share one table layout. `tests/test_sandbox_pick.py` checks the picker on hand-written listings. - -## 3. The table the pair reads - -User SGPR 8 is a 32-bit pointer (the shaders force the high dword to 0) to one table in the heap: - -| Offset | Descriptor | Contents (byte offsets in the buffer) | -|---|---|---| -| 0x00 | V# | world rows 0–2 at 0x00, 0x10, 0x20 (xyz each), translation at 0x30; world = x·row0 + y·row1 + z·row2 + row3 | -| 0x20 | T# | the albedo image (8 dwords) | -| 0x40 | V# | light direction at 0xa0; view-projection at 0x160, clip = wx·r0 + wy·r1 + wz·r2 + r3 (D3D clip, y up, z 0..1) | -| 0x60 | V# | colour at 0x00 (rgb × the lighting term, alpha as is) | - -`vk_sandbox` writes raw V#s (stride 0, NUM_RECORDS = the buffer's bytes, OOB_SELECT 3), registers each texture's -T# words and the PS's S# literal in the descriptor hash table, builds the sampler from those S# words -(`gfx10::decode`), and draws through a negative-height viewport so the D3D-convention matrices stay unchanged. - -## 4. Reproduce it - -```sh -python -I tools/world_index.py ... --entities-out /entities.jsonl # placements (docs/world.md) -rpf9dump models "/levels.rpf" /assets -rpf9dump ttpf "/data/ttdb/maps/ttdb_maps__7.ttpf" /ttpf_maps # n = 0..7 -rpf9dump ttpf "/data/ttdb/terrain/ttdb_terrain__7.ttpf" /ttpf_terrain # n = 0..7 -cmake --build runtime/build --target vk_sandbox -python -I tools/sandbox.py --work --entities /entities.jsonl --models /assets \ - --textures /ttpf_maps --textures /ttpf_terrain [--center X Y] --window -``` - -Window keys: WASD move, right mouse button held to look, Q/E down/up (fly), Shift faster, 1 fly, 2 walk (eye 1.7 m -over the highest scene triangle under the camera), 3 drive (eye 1.2 m, accelerates and steers), P screenshot, -Esc quit. `--center` is in RAGE world metres; without it the densest 50 m cell of resolved props is used. - -## 5. Measured - -| | | -|---|---| -| map pools (8) | 133,697 textures exported, 0 failed, 7,030 skipped | -| terrain pools (8) | 46,115 exported, 0 failed, 26,903 skipped (`rpf9dump`'s limits in [textures.md](textures.md)) | -| test scene (one `levels.rpf` window) | 600 entities within 120 m, 150 placed (402 have no exported model in that window), 446 draws, 178 meshes, 345,782 triangles | -| albedo | the material's DiffuseTex reference (`Param` = `joaat("DiffuseTex")` = `C8E8C282`): 422 of 446 draws textured with 93 textures from the map and terrain pools (69 with the map pools alone). Two-layer blend materials have no DiffuseTex: 11 references each, two albedos, two normal maps, packed maps and a blend mask; the first layer's albedo (`Param` `346394EA`, name unknown) brings it to 442 of 446 draws and 107 textures | -| `--check` (640×360) | 114,503 pixels covered, 4,736 distinct colours (147 with the textures left out) | -| window | about 90 frames per second with a `vkQueueWaitIdle` per frame; a 60-frame windowed run ends on the same pixels as the headless render | -| walk / drive | eye at 1.70 m / 1.20 m over the roof the camera starts above | - -## 6. Limits and next - -* One pair, one forward pass. The world's own material shaders pull vertices (`SV_VertexID` only) and write the - G-buffer; drawing those needs their vertex fetch tables and the lighting passes that read the G-buffer. -* The scene stores mip 0 box-scaled to 256 px (`--tex-size`), so the sampler's LOD range is clamped to 0. -* Ground following uses the scene's own triangles; there is no collision against walls. -* Draws are not culled or sorted, and every frame waits for the GPU; a large `--max-props` gets slow (each prop is - one draw per mesh: 150 props gave 446 draws). diff --git a/docs/saves.md b/docs/saves.md deleted file mode 100644 index e710029a1..000000000 --- a/docs/saves.md +++ /dev/null @@ -1,185 +0,0 @@ -# Save files - -The game's save containers, measured from one save set (two story saves, a profile record and settings) taken from a -retail copy, with every file already plain on disk. `tools/saves.py` reads, rebuilds and imports them using only -the standard library. Nothing here decrypts anything. The one high-entropy layer (`SLAYER1`, below) is described -and left alone. - -Confidence: **confirmed** means it holds on every sample or is proven by a byte-identical rebuild. **likely** means -it's consistent with the data. **hypothesis** means it's a guess. - -Never commit or attach real saves, extracted blocks or `save.pretty.json`. They're the player's data, and the block -contents are game data. - -## Overview - -| Container | Holds | Where it's seen | -|---|---|---| -| `JSAV` v3 | The story save: an index plus one JSON document | One file per story slot (manual and autosave) | -| `ASAV` v1 | Generic header + payload | Profile record (kind 3), settings (kind 2) | -| `SLAYER1` | A named wrapper around a packed `ASAV` (kind 1) | Next to each story save: the same save packed, with its slot name and title | - -## JSAV: story save (confirmed) - -``` -0x00 char[4] "JSAV" -0x04 u32 version = 3 -0x08 u32 n_code_blocks -0x0C u32 n_script_blocks -0x10 entry[n_code + n_script], 20 bytes each: - u32 hash block id, also the block's inner key - u32 flags 1 on every sample - u32 reserved 0 - u32 offset absolute file offset of the block's JSON text - u32 size byte length of the block's JSON text - zero padding to a 16-byte boundary -body UTF-8 JSON, CRLF between blocks: - {"CodeSaveBlocks":[\r\n b0,\r\n b1 ... bN],\r\n"ScriptSaveBlocks":[\r\n ... bM]\r\n} - zero padding to a 16-byte boundary -``` - -Both samples have 38 code and 44 script blocks. `tools/saves.py verify` rebuilds them byte for byte from the parsed -blocks, which confirms the framing, padding and offsets. The JSAV carries no checksum of its own. - -A body or a block nested deeper than 512 JSON levels is rejected as malformed (`JSON_NESTING_LIMIT` in -`tools/saves.py`, one error line and exit 2). The limit is the tool's, not the interpreter's: Python 3.14's JSON -decoder is iterative and no longer raises `RecursionError` on a deeply nested document, while real saves nest a few -levels. - -Block conventions: -- Each block is `{"$0x":{"$0x":{...}}}`, with one group hash for code blocks and one for script blocks. The inner hash equals the index entry's hash. **confirmed** -- Keys are 32-bit hashes written as `"$0x%08x"`: the **case-sensitive** joaat (seed 0, no lower-casing) of the engine or script name, the same rule as the member hashes in [world_names.md](world_names.md). **confirmed**, see [Key names](#key-names). -- Reserved, unhashed keys **(confirmed)**: - - `$x $y $z $w` vectors and quaternions - - `$content` + `$data` typed arrays (`int_array`, `int64_array`, `char_array`, `float_array`, `short_array`) - - `$data:"0x…"` a hash value stored as a string - - `$key`/`$value` map entries - - `$type`, `$bits` - - `$v` version (settings) -- Floats are printed `%f` (six decimals) and ints in decimal. A JSON library re-serialises them differently, so `pack` copies block text verbatim. **confirmed** -- Diffing an autosave against a manual save taken about a minute later shows 62 of 82 blocks identical. The other 20 are positions, counters and stats, so blocks are independent units. **confirmed** - -## ASAV: header + payload - -``` -0x000 char[4] "ASAV" -0x004 u32 version = 1 -0x008 u32 kind: 1 story (packed), 2 settings, 3 profile likely -0x00C u32 1 plain, 3 packed hypothesis: storage mode -0x010 u32 0 plain, 0x180 packed hypothesis -0x014 u32 payload offset = 0x170 confirmed -0x018 u32 0 plain, stored size packed likely -0x01C u32 file size (plain), unpacked size (packed) confirmed plain / likely packed -0x020 u64 unix time, seconds, UTC confirmed -0x028 u16[128] display title, UTF-16LE confirmed -0x128 char[56] slot name, ASCII confirmed -0x160 u32 checksum: algorithm unknown -0x164 u32 0 -0x168 u64 file size again (plain) -0x170 payload -``` - -The checksum at 0x160 matched none of these: -- CRC-32, CRC-32C, Adler-32, FNV-1/1a, joaat (seeds 0, `0x3fac7125`, `0xffffffff`), byte sum, MD5, SHA-1 or SHA-256 (truncated to 32 bits) -- tried over every 4-aligned sub-range, with the field zeroed and raw, in both byte orders - -It's left as **open**. Copy the header verbatim whenever the payload is unchanged. - -Payloads: settings (kind 2) are hash-keyed JSON text with tabs and CRLF **(confirmed)**. The profile record (kind 3) -is 1,644 bytes (first 112 bytes non-zero, starting `u32 10, u32 3`, followed by 1,532 bytes of zero padding) **(confirmed)**. - -## Profile record (kind 3, confirmed) - -``` -0x000 u32 version = 10 confirmed -0x004 u32 kind = 3 confirmed -0x008 u32 subversion / format tag likely -0x00C u32 flags likely -0x010 u64 account / profile identifier likely -0x018 u32[22] profile settings & attributes (first 112 bytes non-zero) -0x070 byte[1532] zero padding (reserved area) confirmed -``` - -The profile record (kind 3) has a fixed 1,644-byte payload. Only the first 112 bytes (0x70) contain active profile -fields, starting with format version 10 and kind 3; the remaining 1,532 bytes (0x5FC) are zero padding reserved for -future profile expansion and cloud sync. - -`tools/saves.py info` reports the profile version, active bytes and verifies the zero-padding boundary; -`tools/saves.py extract` writes `profile.json`. - -## SLAYER1: packed copy (not decoded) - -``` -0x00 char[8] "SLAYER1\0" -0x08 u32 version = 1 -0x0C u32 name length n -0x10 char[n] name, no terminator (so the rest may be unaligned) -... u64 payload size -... ASAV, kind 1: header as above (title, slot name, time), then 16 high-entropy bytes at +0x170 - and a high-entropy body at +0x180 (~30% of the JSAV's size) -``` - -The body is compressed and/or encrypted. Following AGENTS.md, it's recorded here and not decoded. The plain JSAV next -to it holds the same save. The wrapper's header is the only place the autosave's slot name and title appear, so -`saves.py` reads it for those. - -## Importing into the runtime - -The runtime's offline `XGameSaveImpl` (`runtime/shims/xgameruntime_gamesave.cpp`, -[runtime_imports.md](runtime_imports.md)) keeps `XGameSave` data in -`LEONIDA_SAVE_DIR\local-user\\`, defaulting to `%LOCALAPPDATA%\Leonida\saves`, with names -%-encoded. `python -I tools/saves.py import ... [--out DIR] [--map OLD=CONTAINER/BLOB] [--with-packed]` -writes payloads in that layout with the same encoding, plus `import-manifest.json` (source, size, SHA-256). -`--with-packed` also imports `chives.dat`, the packed `SLAYER1` copy of the same save (below), as a blob of its own; -without it only the plain payload is imported. - -Checked earlier with the shim of the open #279, which used the same layout: four imported blobs (2 KB to 1.2 MB) -read back byte-identical through its `XGameSaveReadBlobData`. - -**VERIFY:** the title's real container and blob names. The default is container = slot name and blob = payload file -name, and `--map` overrides it. Confirm or fix them from the executable's `XGameSaveCreateContainer` and -`XGameSaveSubmitBlobWrite` calls. - -## Key names - -The hash was found from structure, before trying a dictionary: the code and script group keys are the joaat of names -derived from the clear-text JSON wrappers around them, with case kept. Measured on the sample set (two story saves -plus settings, **1,059 distinct keys**), with a dictionary of 1.14 million identifier-like strings harvested by -`tools/save_keys.py` from the raw bytes and zlib streams of four of the game's own data archives (`common`, `script`, -`data`, `appdata0`): - -| Method | Keys resolved | Expected by chance | -|---|---|---| -| joaat, case-sensitive, strings as found | 128 | 0.3 | -| joaat, lower-cased | 45 (1 not found case-sensitively) | 0.3 | -| FNV-1, FNV-1a, MurmurHash3-32 | 0 | 0.3 | -| CRC-32, MurmurHash3-64 low or high half | 1 each | 0.3 | -| + one- and two-word Pascal/camel/snake names from the 3,000 most frequent words (`--compose 3000`) | +134 | about 7 | -| + block ids only (82 targets): one or two PascalCase words; script blocks share a fixed name prefix | 33 of 82 (14 code, 19 script) | 0.6 | -| **Total** | **278 of 1,059 (26%)**, 1 ambiguous | at most about 8 | - -Every family except case-sensitive joaat stays at chance level. Code block ids are bare PascalCase nouns, script block -ids add a common prefix, code fields are PascalCase and many settings fields are camelCase **(likely)**. The other ~780 -names aren't in the data archives: they're code-only or script-local names, so the executable's strings should -resolve most of them. The resolved names are game data and stay local; only counts belong here. - -`save_keys.py resolve` prints these counts for any dictionary. `--out` writes the hash -> name table for local use. - -## Tool - -`verify` reports on every supplied file. Its exit status is 2 if any file could not be read or parsed, -otherwise 1 if any rebuild differed, otherwise 0. - -```powershell -python -I tools/saves.py info ... -python -I tools/saves.py verify ... # parse every block, rebuild, compare byte for byte -python -I tools/saves.py extract # blocks/*.json, index.json, save.pretty.json -python -I tools/saves.py pack # after editing blocks/*.json -python -I tools/saves.py diff -python -I tools/saves.py import ... [--out DIR] [--map OLD=CONTAINER/BLOB] [--with-packed] [--dry-run] [--force] -python -I tools/save_keys.py collect ... # distinct $0x… keys -python -I tools/save_keys.py resolve ... --dict ... [--compose N] [--out FILE] -``` - -`tests/test_saves.py` and `tests/test_save_keys.py` cover all of it on synthetic containers and names built in the -tests. diff --git a/docs/sgd5_render_states.md b/docs/sgd5_render_states.md deleted file mode 100644 index 6aa6f0f86..000000000 --- a/docs/sgd5_render_states.md +++ /dev/null @@ -1,25 +0,0 @@ -# SGD5 pass render-state indices - -In the Xbox 1.0.2.1 shader archive, bytes 6, 7 and 8 of a 24-byte pass select rows in the effect's rasterizer, depth/stencil and blend tables. These byte positions and state indices are zero-based. The six bytes immediately before them use one-based shader program selectors, with zero meaning unused. A renderer looking up a stored pass can therefore identify the three explicit state records alongside its shader programs. [Program lookup and effect boundaries](https://github.com/ItsNotRexed/Leonida/pull/2519) - -| Pass byte | Effect-local table | Bytes per row | Stored rows across both databases | Effects with passes and at least two rows | Effects in which the pass byte selects every row | -|---:|---|---:|---:|---:|---:| -| 6 | Rasterizer | 16 | 64 | 4 | 4 | -| 7 | Depth/stencil | 24 | 124 | 33 | 33 | -| 8 | Blend | 68 | 398 | 7 | 7 | - -All **28,798 passes** in the two databases satisfy the same rule. For a nonempty table, the byte is strictly less than the table's row count. If the count is zero, the byte is zero and there is no stored row to read. The state the runtime supplies in that case is unknown. An explicit row at index zero and an empty table can be distinguished by retaining the table count. - -## Reproduce on a local package - -Use the `shaders.rpf` listed in the [Xbox 1.0.2.1 manifest](../game/xbox-1.0.2.1.json). The two SGD5 databases start at `0x9000` and `0x10287000`. They contain 910 and 22 effects. Use each effect's own six program lists and its own state tables. [Named-pass reader and package test](https://github.com/ItsNotRexed/Leonida/pull/3036) - -1. From the end of the six program ordinal arrays, skip 80 bytes. For each row width in `(16, 24, 68, 36)`, read one little-endian u32 count, record the offset of the first row, and advance by `count * width`. The fourth table is needed to locate the techniques. -2. Read the u32 technique count and skip four bytes per technique. The next u32 is the pass count. For every 24-byte pass, check offsets 6, 7 and 8 against counts 0, 1 and 2 respectively. For a nonempty table the selected row starts at `first_row + pass_byte * width`. -3. For an independent check of the byte positions, repeat the test for **each whole byte** at offsets 6 through 23. For each table, require every pass to satisfy the bounds above. Within each effect with passes and at least two rows, also require the set of byte values across its passes to equal the set of row indices. Exactly one whole-byte position per table satisfies both conditions across the archive. The table above gives those positions and the number of effects that distinguish them. - -## Interpretation of the rows - -The state names are supported by comparison with the public SGD2 reader and measurements of the Xbox rows. The 16-byte rows have fill mode 3, cull mode in `1..3` and a one-byte front-face flag. In all 124 depth/stencil rows the enable flags and write mask are in `0..1`, and the comparison function is in `1..8`. All 398 blend rows have a four-byte prefix and eight eight-byte render-target entries. Their enable flag is in `0..1` and their write mask is in `0..15`. Individual enum values do not establish the rest of the Xbox state layout. [SGD2 format comparison](https://github.com/Kalmarv/rage-engine-formats/blob/91e5abb68476709fac80f256bc64f928c6fc2d19/src/sgd2_effect.rs) - -The measurements identify the indices stored in the package. Runtime selection of a technique, application of overrides, and the resulting image still require execution evidence. diff --git a/docs/shader_inputs.md b/docs/shader_inputs.md deleted file mode 100644 index 72d5404f9..000000000 --- a/docs/shader_inputs.md +++ /dev/null @@ -1,304 +0,0 @@ -# What game shaders expect from their inputs - -Some game shaders give a black, speckled or hung result when one input value is wrong, and that looks like a translator -or layer bug when it isn't. This page lists those inputs per shader, so a wrong picture or a device-lost has a -documented first check. Each section says what was reported, by whom, and what was measured in the shader to confirm -it. - -Measured on the local package's disassembly (`work/shaders/dxbc/disasm`) at `16282101`. Offsets, bit positions and -counts only; no shader text. - -## Bloom and exposure - -Reported by @Silliana in [#3235](https://github.com/ItsNotRexed/Leonida/issues/3235). The observations below were -checked against the local disassembly. Offsets are bytes into the constant buffer read by the named shader. - -### A black bloom chain (`PS_DownSampleBloomFilterKaris`) - -- Check the RGB tint at `+0x00`, `+0x04` and `+0x08` first. The shader multiplies the filtered colour by these - values before export. An all-zero tint makes bloom black even with a valid source. The fourth value at `+0x0C` - feeds the exported alpha. -- The sample loop has a limit of 13. Its luminance-dependent weight has the form `1 / (1 + k × luminance)`, - with scale `k` at `+0x1C`. Setting it to zero removes that dependence for finite inputs. The spatial filter - and output tint still apply. - -### Flat, wrong or slowly changing exposure (`PS_CalculateExposure`) - -- The mode dword at `+0x410` selects the exposure calculation. A nonzero value takes the path that computes - logarithmic exposure from the measured luminance. Check this before diagnosing the automatic exposure path. -- On the compensation path, a nonzero dword at `+0x40C` selects the fixed value at `+0x408`. Zero selects a - sample from a 1D compensation curve. Check that the curve is bound when using the texture path. -- Check the previous-exposure texture when the pass changes slowly. The adaptation code subtracts its sample - from the target exposure and can blend back toward the target. It tests `+0x3B0` against zero and compares - a value derived from the exposure delta against the threshold at `+0x3B4`. For a single-frame comparison, - the issue report suggests seeding the previous exposure with the target. - -### Luminance downsample and bloom upsample - -All five sampling sites in `PS_LuminanceSourceDownsample` contribute to the export. All nine in -`PS_UpSampleBloomFilterBlend` do too. Check the source resolution, sampling and reduction before comparing -the luminance pyramid with a whole-frame average. -When inspecting the upsample in isolation, check in the pipeline state how its output blends with the previous level. - -## Studio-shot lighting (`PS_STUDIOSHOT_PBR_MATERIAL_STANDARD_LIGHTING`) - -Reported by @Silliana in [#1892](https://github.com/ItsNotRexed/Leonida/issues/1892). The corpus has one program -with this name. It shades with up to eight lights, read from a buffer of 512-byte light records. Colour and -intensity come from a separate table of light profiles. - -### First check for a device-lost or a dark frame - -1. **The dword at record +0x4C.** Its top byte is a loop count, so it must hold an integer and never a float (see - [Light-shaping planes](#light-shaping-planes)). #1892 reports a GPU hang when a float sits here. That report gives - the dword as +0x40; the count is measured at +0x4C (+0x40 is a different field, described below). -2. **The profile intensity.** A light whose profile intensity is 0 or less is skipped entirely. So an all-black light - doesn't mean the light maths is broken. -3. **The shadow-strength byte at record +0x73.** At 0 the shadow map is still sampled, but the result does nothing. - -### Light loop - -- The loop always runs eight times (light 0 to 7); the light count doesn't come from a constant. An unused slot is - switched off through its profile: point it at a profile with intensity 0. -- Light *i*'s record starts at byte *i* × 512 (0x200) of the light buffer. -- All 61 image samples and all 27 cube-coordinate sequences in the program are inside this loop. That matches #1892: - the shader has no ambient term, and its 2D and cube samples are per-light cookies and shadows. Indirect light comes - from the separate probe system (`indirect_light_probes` / `CS_ApplyProbeIrradiance`), not from this shader. - -### Light record (512 bytes) - -The fields below are the ones confirmed. The rest of the record is read but not decoded here. - -| Offset | Type | Use | -|---|---|---| -| +0x10 | 3 × f32 | Light position; the shader subtracts the world position of the pixel from it. | -| +0x20 | u32 | Bits 0–8: profile index (9 bits) into the profile table. Bits 9–17 and 18–21 are two more fields, not decoded. | -| +0x28 | u32 | Flags. Bit 24 enables the light-shaping planes; bit 16 takes part in the shadow-map gate; bits 30–31 are the light type (0–3), which selects how +0x3C is used; bits 17, 20, 21, 26 and 27 are tested, not decoded. | -| +0x3C | 2 × f16 | Light shape size: the light's dimensions, used differently per light type. See [Light shape size](#light-shape-size). | -| +0x40 | u32 | Low 24 bits non-zero turns on one per-light factor; at zero that factor is 1.0, so the light still shades. The top byte isn't read on the paths checked. | -| +0x4C | u32 | Top byte: number of light-shaping planes (0–255). See below. | -| +0x5F | u8 | Read as byte / 255; at 0 one block of the light's shading is skipped. | -| +0x73 | u8 | Shadow strength, read as byte / 255 right before the shadow-map block. | -| +0xB0 | planes | Light-shaping planes, 32 bytes apart. | - -#### Light-shaping planes - -When flag bit 24 at +0x28 is set and the dword at +0x4C is at least `0x01000000`, the shader loops over *n* planes, -where *n* is that dword's top byte. Plane *k* is four f32 (normal xyz, then w) at record +0xB0 + 0x20 × *k*. For each -plane it computes `saturate(dot(normal, pixel − light) + w)`, squares it and multiplies it into a per-light factor that starts at 1.0. - -Only 11 planes fit in the record (the last at +0x1F0). A larger count reads on into the next light's record, and past the -end of the buffer after the last light. A float in this dword has its exponent in the top byte: 1.0f (`0x3F800000`) -gives 63 planes. The loop itself ends after at most 255 iterations. If a device-lost still shows up there, check this -dword and the buffer's bounds first. - -#### Light shape size - -+0x3C holds two f16. How they are used depends on the light type (bits 30–31 at +0x28): - -| Type | Low half | High half | Source | -|---|---|---|---| -| 0 | Sphere radius: clamped against the reflection ray to pick the closest point on the light. Brightness grows with radius², since intensity is radiance. | No effect. | Tested by @Silliana [on the pull request](https://github.com/ItsNotRexed/Leonida/pull/3157): radius 60 → 5 dimmed the light about 134× (radius² predicts 144×). | -| not decoded | Half-size along one axis of a rectangle. | Half-size along the other axis. | Shader: the light's position is moved by ± each half along its axis, and points are clamped to those bounds. | -| not decoded | — | A length along the light's axis (clamped to ± half of it), also squared and compared against a distance. Probably a tube light's length (@Silliana's hypothesis, not tested). | Shader. | - -The low half also sets one blend factor. No range-style falloff was found: neither half divides a distance, and the -early reading of the high half as a range is dropped. - -A value that's too big makes the light too large. On a sphere light, the brightness grows with the square of the -radius. That gives scattered single-pixel specular blowups that look like a translator bug, for example when a range -is written into both halves (reported by @Silliana). - -#### Correction to #1892 - -#1892 puts two checks on one dword at +0x40: a top-byte loop count, and low 24 bits that must be non-zero or the light -is skipped. The shader splits these across two dwords: - -- The count is the top byte of the dword at **+0x4C**, gated by flag bit 24 at +0x28. On that path the low 24 bits - aren't tested. -- The low-24-bit test is on the dword at **+0x40**, and at zero it disables one factor, not the whole light. - -The light is skipped only through a profile intensity of 0 or less. - -### Profile table - -- It is a separate buffer from the light records, made of 16-byte entries. -- The light record's profile index (bits 0–8 of +0x20) selects the entry. -- The entry's fourth dword (+12) is the intensity, as f32. When it's 0 or less the light is skipped before the rest of - its record is read. #1892 gives the first three dwords as the RGB colour; the shader loads the whole entry later in the - light's shading. - -## ACES LUT bakes (`postfx_aces`) - -Reported by @Silliana in [#1896](https://github.com/ItsNotRexed/Leonida/issues/1896). The corpus has ten bake -programs: `CS_BakeACESLUT`, `CS_BakeACESWithGamutCompressLUT`, and the `TonemapOnly` versions of both, each with a -choice of shaper (Linear, Log, PQ or QuasiLog; the `TonemapOnly` bakes exist only with QuasiLog). Each one writes -an RGBA 3D LUT through a storage image (`image_store`, 3D). In the corpus the program names have lost the `A` of -`ACES` (`CS_BakeCESLUT_…`) everywhere except the gamut-compress bakes. - -### First check for an identity-looking or flat LUT - -1. **Which spline you filled.** The bakes read their tone curve from a spline in the constant buffer. In the - `TonemapOnly` bakes, the dword at **+0x118** chooses between two of them (see [Two splines](#two-splines)): - non-zero uses the one at +0x70, zero uses the one at +0x00. Filling one and pointing the switch at the other - gives a flat or meaningless curve. -2. **The dword at +0x13C.** It is the switch #1896 describes, but it doesn't turn the curve off: every path - evaluates the spline. At zero the spline is applied to R, G and B separately (three evaluations). When it is - non-zero, the shader also evaluates it on AP1 luminance (0.2722, 0.6741, 0.0537), for four evaluations. In the - non-`TonemapOnly` bakes the dword at +0x11C then blends the luminance result with the per-channel one. -3. **The quasi-log addressing**, below, if you read the LUT back. - -### Quasi-log addressing - -The four QuasiLog bakes turn each LUT index *i* into a linear value as #1896 gives it: - -`linear = 0.18 · 2^(14 · (i · s − 0.41838)) − 0.0031` - -The shader's constants are −0.418377, 14.0, 0.18 and −0.0031050. The scale *s* is the first dword of a second -constant buffer and multiplies the thread index; #1896's formula makes it 1/(N − 1) for an N-entry axis. Mid grey -(linear 0.18) falls at *i* · *s* ≈ 0.4201, which is index 13.0 on a 32-entry axis. #1896 reports that mid grey comes -out at about 0.103. That needs the bake to run and isn't measured here. The Linear, Log and PQ bakes don't contain -these constants. - -### Two splines - -The RRT's own spline (the reference `SegmentedSplineParams_c5`) isn't an input: its coefficients are a constant -table inside the program, read relative to the code (`s_getpc_b64`), with the thresholds log10 0.18 = −0.7447 and -log10(0.18 · 2^18) = 4.673 as literals. The constant buffer holds the output tone curve, packed at 4 bytes per value -(not the 16-byte stride an HLSL array would get). - -**At +0x00, all ten bakes: reference order** (`SegmentedSplineParams_c9`, 8 knots per half): - -| Offset | Values | Use | -|---|---|---| -| +0x00 | 10 × f32 | Low coefficients | -| +0x28 | 10 × f32 | High coefficients | -| +0x50 | 2 × f32 | Min point (x, y) | -| +0x58 | 2 × f32 | Mid point (x, y) | -| +0x60 | 2 × f32 | Max point (x, y) | -| +0x68 | f32 | Low slope | -| +0x6C | f32 | High slope | - -**At +0x70, the two `TonemapOnly` bakes only: points first.** This is the layout #1896 describes: three (x, y, -slope) points come first, and the coefficient blocks follow them. - -| Offset | Values | Use | -|---|---|---| -| +0x70 | 3 × f32 | Min point (x, y, slope) | -| +0x7C | 3 × f32 | Mid point (x, y, slope) | -| +0x88 | 3 × f32 | Max point (x, y, slope) | -| +0x94 | 6 × f32 | Low coefficients | -| +0xAC | 6 × f32 | High coefficients | - -The x of each point is the value the shader compares log10(input) against, so the 12-byte stride is measured. The -role of the other two values in each triplet is #1896's reading. The non-`TonemapOnly` bakes don't read +0x70 to -+0xC3; their next values start at +0xC4. - -#### Correction to #1896 - -#1896 says the bakes use a non-reference order. That is true only of the `TonemapOnly` bakes' second spline at -+0x70. The spline at +0x00, which every bake reads (the only one outside the `TonemapOnly` bakes), is in the reference -CTL order. The RRT spline isn't in the constant buffer at all. The +0x13C switch picks between a per-channel curve and -one that also uses luminance; it doesn't decide whether the curve applies. - -## Sky passes (`sky_scattering`, `scattering_transmittance_system`) - -Reported by @Silliana in [#1897](https://github.com/ItsNotRexed/Leonida/issues/1897). This is a physically based -atmosphere: two lookup tables are built at runtime and the sky passes sample them. Neither table is a texture on -disk. - -### Order - -| Pass | Samples | Writes | -|---|---|---| -| `sky_scattering:CS_Transmittance` | nothing | one 2D storage image | -| `sky_scattering:CS_MultipleScattering` | one 2D texture | one 2D storage image (of two, see below) | -| `scattering_transmittance_system:CS_SkyAtmosphereLUT` | two 2D textures | three 2D storage images | -| `sky_scattering:CS_SkyView` | two 2D textures | two 2D storage images (of four, see below) | - -`CS_Transmittance` reads no texture, so it goes first. `CS_MultipleScattering` samples one texture, the -transmittance table #1897 names, so it runs second and not side by side with `CS_Transmittance`. `CS_SkyView` and -`CS_SkyAtmosphereLUT` each sample two textures, the two tables, and run after both. Every sample is `image_sample_lz` -(mip 0). Which texture is bound to which table comes from #1897, not from the program. If a sky pass runs before the -tables are built, it reads whatever is in them, and the black or noisy sky looks like a translator bug. - -### Transmittance addresses texel corners - -`CS_Transmittance` turns its integer texel index into table coordinates as x × 1/256 and y × 1/64, with no +0.5, -so each texel holds the value at its corner, not its centre (pointed out by @Silliana in -[#3217](https://github.com/ItsNotRexed/Leonida/pull/3217#issuecomment-7084678180)). A reference table built at texel -centres differs from it slightly, most visibly near the ground. That difference is expected and isn't a translator bug. - -### The dword at +0xD0: output format, not an enable - -#1897 reports a SkyView dword that skips the stores when it is zero. In `CS_SkyView` and `CS_MultipleScattering` -the dword at **+0xD0** of the pass's constant buffer is compared as a float with 0.0. Both outcomes store, but to -different descriptors: - -| +0xD0 | `CS_SkyView` writes | `CS_MultipleScattering` writes | -|---|---|---| -| non-zero | RGB9E5 bits to the images at table +0x40 and +0x80 | RGB9E5 bits to the image at table +0x40 | -| zero | float RGB (alpha 0) to the images at table +0x60 and +0xA0 | float RGB (alpha 1.0) to the image at table +0x60 | - -So a zero dword gives a black sky without an error if only the RGB9E5 images are bound: the stores go to the other -pair of descriptors. Because the test is a float compare, write a float such as 1.0f there. An integer 1 is a -denormal and compares equal to 0.0 if denormals are flushed. This is a hypothesis that depends on the program's float -mode, which isn't checked here. - -### RGB9E5 output - -On the non-zero path both programs pack RGB9E5 themselves: they clamp each channel to [0, 65408], take the shared -exponent from the largest, put R, G and B in bits 0–8, 9–17 and 18–26 and the exponent in 27–31. They then write the -same 32-bit word to all four components of the storage image. The data is useless read back as floats, as #1897 -says. The layer's UAV path for `R9G9B9E5_SHAREDEXP` already covers this: on a GPU without native RGB9E5 storage it -binds an `R32_UINT` storage view ([`d3d12_vulkan.md`](d3d12_vulkan.md), from #1375 and #1388). -`CS_Transmittance` and `CS_SkyAtmosphereLUT` contain no RGB9E5 packing. - -### The shared atmosphere constant buffer - -Reported by @Silliana in [#3990](https://github.com/ItsNotRexed/Leonida/issues/3990): the four passes read one -atmosphere struct, each through its own buffer descriptor fetched from the resource table. Confirmed in the -disassembly of the 1.0.2.1 package (llvm-mc 23.1.5, gfx1013): the 26,503-program corpus has exactly one program for -each of the four names, and each reads the offsets below through a single descriptor. The three `sky_scattering` -passes fetch that descriptor from table offset **+0x220**; `CS_SkyAtmosphereLUT` fetches it from **+0xC60**. So when -one pass looks right and another looks wrong, check the slot binding before the layout. The +0xD0 output-format -dword above sits in this same buffer. - -Everything is in km (#3990). Field names are #3990's reading; the offsets and the "consumed by" column are measured. -A pass can load a dword as part of a wider load without using it, so "consumed" means an instruction reads the -register before it is overwritten. - -| Offset | Type | Field (#3990) | Consumed by | -|---|---|---|---| -| +0x20 | f32 | Planet radius | all four | -| +0x30 | f32 | Rayleigh scale height | none (loaded, see below) | -| +0x34 | 3 × f32 | Rayleigh scattering RGB | all four | -| +0x40 | f32 | Mie scale height | none (loaded, see below) | -| +0x44 | 3 × f32 | Mie scattering RGB | all four | -| +0x50 | f32 | Top of the atmosphere | all four | -| +0x60 | 3 × f32 | Mie absorption RGB | all four | -| +0x6C | f32 | Mie g (phase asymmetry) | `CS_SkyView` only | -| +0x70 | f32 | Ozone layer width | all four | -| +0x74 | 2 × f32 | Ozone below the layer: constant, slope | all four | -| +0x7C | 2 × f32 | Ozone above the layer: constant, slope | all four | -| +0x84 | 3 × f32 | Ozone absorption RGB | all four | -| +0x90 | 3 × f32 | Sun direction | `CS_SkyView` only | -| +0xA0 | 3 × f32 | Moon direction | `CS_SkyView` only | - -The two scale-height dwords are where the disassembly adds to #3990: every pass loads them inside a wide scalar -load, but in all four programs the registers holding +0x30 and +0x40 are overwritten or never touched again before -any instruction reads them. Only the RGB coefficients next to them are consumed. A wrong value in those two dwords -cannot by itself explain a bad sky from these passes. - -The ozone block matches #3990's two-layer linear reading: the dword at +0x70 is compared per lane with a float -(`v_cmp_gt_f32`) in the ozone block, the constant/slope pairs feed `v_fma_f32`, and the absorption RGB feeds the -per-channel accumulate. `CS_SkyView` reads the sun direction at +0x90 and a second direction at +0xA0, -which #3990 reads as the moon; its second output is the sky lit by that direction. The fourth dword of each -direction (+0x9C, +0xAC) is not consumed. - -Some neighbouring dwords are read but not decoded here: +0x24 to +0x2C (next to the planet radius), +0x54 to +0x5C -(`CS_SkyView`), and +0x04 to +0x13 (`CS_SkyView` and `CS_SkyAtmosphereLUT`). - -Sanity checks from #3990 (GPU experiments, not repeated here): zeroing the Rayleigh RGB makes the zenith go basically -white, zeroing the ozone absorption mostly bumps green, and raising Mie g brightens the sky toward the sun. With -Earth-like values `CS_Transmittance` lands within about 0.01 of a reference transmittance table, which makes it the -cheapest pass to sanity-check a translation. diff --git a/docs/shader_library.md b/docs/shader_library.md deleted file mode 100644 index 09a1997a9..000000000 --- a/docs/shader_library.md +++ /dev/null @@ -1,193 +0,0 @@ -# The pipeline library in `shaders.rpf` - -**Status: measured** on the 1.0.2.1 package. `shaders.rpf` holds one more file behind its 26,503 shader entries: -a library of precompiled pipelines, with 25,471 graphics and 2,693 compute pipeline records and the 21,522 native -RDNA2 programs they run. `tools/shader_carve.py` reads only the raw-deflate shader entries, so until now nothing -read this file. No program, blob or record is reproduced here; the tables hold counts, sizes and offsets. - -## 1. Where it is - -The archive's data area has two parts. The first 274 MB are the shader entries `shader_carve.py` reads (name, -kind, sizes, raw deflate). The rest, from file offset `0x10579000`, is 4,205 zlib streams: 4,204 inflate to -65,536 bytes and the last to 27,436. Concatenated, they form one 275,540,780-byte file. That is the 33.4% -stream coverage [world_census.md](world_census.md) measured for `shaders.rpf`. The gaps between the streams are 0 -to 12 bytes. - -`tools/shader_library.py` finds the first stream that inflates to the header below and appends streams until it -has the size the header gives. It fails if the sizes don't match exactly. - -**No shaders elsewhere.** The other 74 RPF9 and TTPF archives of the package (214 GB: the root archives except -`movies.rpf`, and everything under `pack/` and `data/`) were scanned raw and through every zlib stream (about 420 GB -inflated) for `DXBC`, `XBCH`, `FSSM`, `FSPX` and the shader entries' `_Wrapped` names. There are no shader entries, -and none of the 148 `XBCH`/`FSSM` hits is a record: no `XBCH` inflates to an `FSSM` blob, and no `FSSM` has a code -offset with an `s_endpgm` after it. The same checks accept the 52 records of `XboxBvhBuilder.dll` and 200 of 200 -carved FSSM blobs. No `DXBC` hit has a valid header. So the game's shader programs are the shader entries, this -library and the two DLLs' containers ([embedded_shaders.md](embedded_shaders.md)), as far as raw and zlib data go. - -## 2. Layout - -All values little-endian. - -| offset | size | field | -|---|---:|---| -| 0x00 | 4 | `'P' 'S' 00 09` | -| 0x04 | 32 | name, NUL-padded: `0x65F41EDD` | -| 0x24 | 36 | version string, NUL-padded: `930.048.020` | -| 0x48 | 8 | hash | -| 0x50 | 4 × 4 | graphics pipelines G = 25,471, compute pipelines C = 2,693, blobs B = 54,576, programs P = 21,522 | -| 0x60 | 4 | blob section size, 31,120,020 | -| 0x64 | 4 | code section size, 240,894,464 | -| 0x80 | G × 0x70 | graphics pipeline records | -| | C × 24 | compute pipeline records | -| | B × 8 | blob table: (offset, size) into the blob section | -| | P × 8 | program table: (offset, size) into the code section; every offset is 256-byte aligned | -| | | blob section, then code section | - -The sections add up to the file size exactly: 0x80 + 25,471 × 0x70 + 2,693 × 24 + 54,576 × 8 + 21,522 × 8 + -31,120,020 + 240,894,464 = 275,540,780. Every blob and program entry lies inside its section. The blob entries -are contiguous; the program entries are in increasing offset order. - -**Graphics record** (0x70 bytes): u64 hash, u32 state blob, u32 pipeline blob, 40 bytes not decoded, then seven -(u32 program, u32 stage blob) pairs. 0xFFFFFFFF means no program. The slot gives the stage. Slot 0 is the pixel -shader, slot 1 the vertex shader and slot 2 the mesh shader. The source containers named in §3 have those stages -in every use §3 links: 24,090 of the 24,111 slot-0 uses, 13,388 of 13,409 slot-1 and all 12,062 slot-2. No linked -use names a source of another stage. Slot 6 is used by 2 records with one program and no stage blob; it is not -identified. Slots 3 to 5 are never used. - -| stages | pipelines | -|---|---:| -| VS + PS | 13,383 | -| MS + PS | 10,726 | -| MS only | 1,336 | -| VS only | 24 | -| VS + PS + slot 6 | 2 | - -The state blob is 388 to 472 bytes (5,680 distinct). The pipeline blob holds the input layout, with element -names such as `POSITION`, `COLOR`, `TEXCOORD`, `NORMAL`, `TANGENT`, `BLENDWEIGHT` and `BLENDINDICES` for vertex -pipelines (80 bytes, with no elements, for mesh pipelines). - -**Compute record** (24 bytes): u64 hash, u32 state blob, u32 blob, u32 program, u32 layout blob. The four parts -have the sizes and shapes of the four [FSPX](fspx.md) kinds: - -| record field | size | FSPX kind | -|---|---|---| -| state blob | 28 bytes in all 2,693 | kind 0, dispatch state: thread-group size in words 3-4, wave32 flag (word 4 bit 20), RSRC1, RSRC2 | -| blob | 20 bytes in all 2,693 | kind 1 | -| program | | kind 6 | -| layout blob | 56 to 10,552 bytes | kind 7 | - -1,529 of the 2,684 compute programs set the wave32 flag. 90 set RSRC2 `TG_SIZE_EN` (bit 10), which none of the -2,689 carved compute shaders do. - -**Programs.** 52 to 239,464 bytes (median 3,968; 238,829,764 in total), padded to 256 bytes with `s_code_end`. -21,463 of them start with the 36-byte prologue FSPX programs have, three 12-byte VOP3 opcode-0x180 words with -literals (`fspx_unpack.code_range` finds it); 59 have none. The code runs from there to the last 4-byte-aligned -`s_endpgm`, as for FSSM blobs. 579 of the first 3,000 pixel programs have more than one. Ending at the first one, -as for FSPX, cut off code their branches reach: 2,281 "branch target outside code" and 1,662 "branch into data" over -all stages. -Each program belongs to exactly one stage: 9,996 PS, 7,498 MS, 2,684 CS, 1,343 VS and the one slot-6 program. - -## 3. Where the programs come from - -A graphics stage blob and a compute layout blob share one layout. Word 0 is the kind (2 for a graphics stage, 3 -for compute). Then comes a head of 16 bytes (kind 2) or 24 bytes (kind 3), whose last word is tagged `0x40`. Then -come 32-byte records tagged `0x41` or `0x42`, then a word `0x43`, a 16-byte digest and 12 zero bytes. All 20,318 -distinct stage and layout blobs follow this. In FSPX, the 16 bytes after kind 7's `0x43` word are the container's -`HASH` digest ([fspx.md](fspx.md)). Here they are too: **21,509 of the 21,522 programs** have the `HASH` digest of -one of the carved containers, and every linked program has its container's stage (2,680 CS, 9,991 PS, 7,498 MS, -1,340 VS; the carve index's stage comes from the container's `DXIL` program header). They come from 6,522 -distinct carved shaders, and a source has 1 to 257 programs. - -None of the programs is byte-identical to its source's FSSM code. Only 47 distinct code bodies, from -`s_inst_prefetch` to the first `s_endpgm`, occur in both. So the library holds **pipeline builds**: the same -shaders compiled again with their pipeline's state. The 13 programs whose digest names no carved container (4 CS, -5 PS, 3 VS, the slot-6 program) are the only ones with no source in the shader entries. - -For a VS or PS program without native wave-size metadata, a 32-bit EXEC operation and an agreeing wave32 -flag in every FSSM payload of its matching DXBC source distinguish a wave32 program that uses `s_bfm_b64` -as scalar data. The translator keeps its existing behavior when the source is absent, the payloads disagree, -or the library code has another strict wave64 marker. Synthetic cases are in -`tests/semantic/test_fspx_wave_size.py`. - -## 4. Tool - -```sh -python -I tools/shader_library.py /shaders.rpf --out /library --disasm --carve /shaders/dxbc -python -I tools/rdna2spirv.py /library/disasm --out /library/spirv -``` - -* It writes `fspx/.code` and `fspx/.json`, the layout `fspx_unpack.py` writes and `rdna2spirv.py` - reads (`native_blob`, `cs_dispatch_state`). A compute program also gets `fspx/.state`, its record's state - blob (FSPX kind 0) as it is, whose SHA-256 is the index's `fspx_state_sha256`; in the 1.0.2.1 `shaders.rpf` library, - every compute program has one distinct state-blob index across `library.json`'s `compute` table (2,684 programs, - 2,693 records). It also writes `index.json` with each program's stage, and - `library.json` with the header and both pipeline tables, stage to program name. Programs are named - `lib__`. -* `--disasm` writes `disasm/.s` for the code after the prologue, as `fspx_unpack.py --disasm` does. -* `--carve` names each program's source shaders. It copies the first source container to `.dxbc`, because - the translator reads the stage's signatures and `PSV0` from there. Pipeline compilation keeps the D3D12 stage - interface. -* `--save` writes the reassembled library. A saved file is also accepted as input. -* `--stages` limits the output to some stages. - -The output is game data and must stay in your work folder. `tests/test_shader_library.py` builds libraries and -archives by hand and covers the header, both tables, the size checks, the search in an archive and the digest -walk. It also checks the `--carve` copy, the translator's reads of the compute sidecar and the compute `.state`. - -**In the build.** `make_game.py`'s `shaders` stage runs this for the compute stage after the BVH step -(`library_shaders`): `--stages cs --disasm --carve` into `/shaders/library`, then `translate()` shards -`rdna2spirv.py` across `--jobs` and merges into `/shaders/spirv/library` with the stage's `--wave64-emulate` -and fallback flags. The runtime's shader library -reads that index next to `fspx/` and finds its entries by `fspx_code_sha256` and `fspx_state_sha256` -([fspx.md](fspx.md), "Build and run-time lookup"). That is how the executable creates these pipelines: it reads the -library through DirectStorage zlib requests and passes each compute record's four parts to Xbox device slot 67, -`DeserializeComputePipelineStateX`, as kinds 0, 1, 6 and 7, so the code key is the program's bytes as the table gives -them and the state key is the record's state blob. The step is redone as a whole when `shaders.rpf`, the tools, -`llvm-mc`, the wave64 mode or the flags change (`library_build.json`, written last), and a clash of both keys between -different modules fails it, as for the FSPX step. Graphics pipelines are not translated by the build. - -## 5. Translation - -With `--carve` and `rdna2spirv.py` at `main` `aa2988cc` (llvm-mc 23, `gfx1013`), **17,955 of the 21,522 programs -translate and pass `spirv-val`**: - -| stage | programs | pass `spirv-val` | -|---|---:|---:| -| VS | 1,343 | 1,333 (99.3%) | -| MS | 7,498 | 7,059 (94.1%) | -| PS | 9,996 | 7,719 (77.2%) | -| CS | 2,684 | 1,844 (68.7%) | -| slot 6 | 1 | 0 (stage not identified) | - -What stops the rest, by the translator's message: - -* **2,533 programs: "reachable instruction with normalized encoding".** llvm-mc rejects scalar register tuples that - run into `vcc` (SGPRs 106 and 107): `s_load_dwordx8`/`x4`/`x16` writing `s[100:107]`, `s[104:107]` or - `s[92:107]`, and image instructions whose resource is `s[100:107]`. In the compute programs alone that is 37,952 - SMEM, 22,248 MIMG and 2,298 MUBUF words. The same words with the register field one tuple lower decode; with - `gfx1030` they don't either. The FSSM shaders don't use these tuples; the pipeline builds use them often. A decoder - fallback for these encodings would cover most of the remaining programs. The translator already reads - `[s100,...,vcc_lo,vcc_hi]` lists (design.md *Scalar/buffer memory*). -* **443: an instruction llvm-mc prints with another encoding than the blob's** (`v_fma_mix*`, `v_interp_p2_f16`): - the existing `check_printed_encodings` refusal. -* **90 CS: "CS thread-group-size SGPR"**: RSRC2 `TG_SIZE_EN`, which no FSSM compute shader sets. -* **68 translate but fail `spirv-val`**, mostly "requires a previous definition". -* Fewer than 30 each: `ds_append`, `s_bitreplicate_b64_b32` and `s_flbit_i32_b64` on a lane mask, `v_cmp` and mask - destinations, 25 branches into data, 10 undecodable words that can't be re-anchored, and a few `vcc`/`ttmp` - operands. -* Programs with no source container: a PS or MS one has no signatures and is `Unsupported` (the reads now raise - that instead of `FileNotFoundError`, which stopped the whole run). A VS that fetches no inputs translates without - one. - -None of the programs has been run on a GPU. - -## 6. What this changes - -* **Pipeline pairing is in the package.** [d3d12_vulkan.md](d3d12_vulkan.md) question 14 asks whether a PSO pairs - two code-base stages, and says the pairing is in the executable. The graphics records give it for 25,471 - pipelines: each names its VS or MS and its PS. Each source can be found through §3. -* **A second compiled form of 6,522 shaders.** The pipeline builds differ from the FSSM code. Which form the game - runs for a pipeline is not measured here (that needs the executable). Either way, a translated pipeline build can - be compared with the translated FSSM shader of the same pipeline. -* **Not decoded.** The graphics state blob, the 40 bytes in each graphics record, the compute kind-1 blob, the - records inside the stage blobs, and slot 6. diff --git a/docs/shader_validation.md b/docs/shader_validation.md deleted file mode 100644 index 381b11642..000000000 --- a/docs/shader_validation.md +++ /dev/null @@ -1,2427 +0,0 @@ -# Differential shader validation - -This note describes a value-level check for the RDNA2 → SPIR-V translator; it is not a claim that -the corpus is correct. The CPU differential oracle in `tools/shader_diff.py` is implemented and -tested (`tests/test_shader_diff.py`): it compares the ISA model in `tools/cpu_ref.py` against -translated SPIR-V run in `tests/semantic/spirv_mini_interp.py` over seeded straight-line programs. -Run it with `python -I tools/shader_diff.py --programs 200 --seed 7` (`--self-test` checks the -harness itself). The GPU-side runners are described below: `tools/valu_fuzz.py` (16-bit and memory ops), `tools/lds_fuzz.py`, `tools/crosslane_fuzz.py`, `tools/cf_diff.py` and `tools/ab_control_flow.py` (corpus pixel shaders in both control-flow forms). - -## Why `spirv-val` is not enough - -`spirv-val` checks that a module is structurally valid SPIR-V for a target environment. It does not -check that the module computes what the RDNA2 program computes. Those are different questions, and -this repository already has cases where only the second question had a useful answer: - -- All 26,503 shaders translate and pass `spirv-val` (Vulkan 1.2) at `43d4703`, after `dcd8ecf` fixed - the ID-bound regression (#881); the intervening `dedd75c` run was 26,501, and `793b06f` before - #223's LLVM 23 source-field fix was 25,032. Yet the SDWA source/destination selects were silently - ignored until 2026-11-20: validation passed for 3,826 of the 13,926 shaders translated at the time - and produced wrong values (`docs/design.md`, "SDWA"). -- The compressed-export bug was found by a GPU test, not by validation: LLVM prints `v4, v4, v5, v5` - for a compressed pair, and the translated shader exported `(r, g, r, g)`. -- `v_cvt_pkrtz_f16_f32` with round-to-nearest overflowed a finite value to infinity; the GPU smoke - test found it, `spirv-val` could not. -- The other project's execution harness found a read-after-store coherence bug: a shader that stored - a texel and loaded it back got stale data because the read and write used different bindings. That - is a well-formed, validator-clean pair of instructions with the wrong observable result. - -A validator answers "is this a legal module?" A differential test answers "does this module produce -the same bits as the original program for the same inputs?" Only the second one can find a wrong -instruction, a wrong operand order, a missing modifier, or a wrong rounding mode. - -## What "differential" means here - -Two independent computations start from the same architectural state: - -1. **Reference.** A CPU interpreter executes the original RDNA2 instructions and records the - registers (and, later, memory) the program writes. -2. **System under test.** The translator turns the same listing into SPIR-V; the existing Vulkan test - tools dispatch it on a real GPU and read back the same registers, buffers or images. - -The comparison is bit-for-bit on every value the test declares observable. A mismatch is reported -with the first differing lane/register, both bit patterns, the random seed, and (in the future -runner) the RDNA2 instruction that last wrote the value. The translator is the path under test; the -CPU model and the SPIR-V interpreter are the two independent oracles in the shipped CPU runner. The -translator → `spirv-as`/`spirv-val` → Vulkan tools path is what the future GPU oracle will run, not -a reference to be trusted. A hand-written SPIR-V twin of a test program is a useful third control: it -checks the harness and driver without involving the translator, so a harness failure is not blamed on -translation. - -Assembling needs no external `spirv-as` binary: `tools/spirv_asm.py` encodes SPIR-V assembly text into binary -words in process, as a module (`assemble(text, target_env="vulkan1.2")`) or from the command line -(`python -I tools/spirv_asm.py in.spvasm -o out.spv`, with `--target-env` choosing the environment and -`vulkan1.2` the default), using the Khronos SPIRV-Headers grammar kept in `tools/spirv_asm_tables.py`. -`tools/rdna2spirv.py --assembler python` takes that path instead of the `spirv-as` subprocess and its -temporary `.spvasm` file; `spirv-val` stays the external validator. `tests/test_spirv_asm.py` and -`tests/test_spirv_asm_tables.py` cover the assembler and the tables. - -The CPU model is deliberately not a second translator. It interprets the listing's mnemonics and -operands; it never consumes SPIR-V. That independence is what makes a disagreement meaningful. - -## The two sides - -### CPU interpreter (`tools/cpu_ref.py`, prototype) - -- Input is a `.s` listing in the format produced by `tools/shader_disasm.py` and by - `runtime/test/shaders/build.py`: a header line, then tab-indented instructions with an optional - `; encoding: [...]` comment per line. `tools/shader_ir.py` parses the listing and treats line 1 as - the header, so a raw `llvm-mc` dump has to be given the same header `build.py` writes. -- State is an SGPR file (32-bit values), a VGPR file (one 32-bit value per lane), VCC, EXEC, SCC and - a program counter. Float registers keep raw bits; only float instructions reinterpret them. - Uninitialized registers read as zero, matching the translator's deterministic register arrays. -- One lane or 64 lanes. Scalar instructions execute once; vector instructions execute for lanes whose - EXEC bit is set, and inactive lanes keep their old value. EXEC and VCC are 64-bit masks even in - one-lane mode, so scalar reads of `exec_lo`/`exec_hi` stay meaningful. -- The implemented subset is intentionally small: `s_mov_b32`, `v_mov_b32`, `v_add_f32`, `v_sub_f32`, - `v_mul_f32`, `v_fma_f32`, `v_cndmask_b32`, `v_and_b32`, `v_or_b32`, `v_xor_b32`, - `v_lshlrev_b32`, `v_lshrrev_b32`, `v_ashrrev_i32`, `s_add_u32`, `s_lshl_b32`, `s_lshr_b32`, - `s_endpgm`. Anything else raises `Unsupported` with the mnemonic and PC. It never guesses an - instruction's meaning. -- f32 add/sub/mul produce correctly rounded binary32 results. FMA is evaluated exactly with rational - arithmetic and rounded once to binary32, so it cannot inherit a double-rounding error from a host - `float`. -- NaNs are canonicalized to `0x7fc00000`; the comparison layer should treat all NaNs as equal by - default because Vulkan does not promise a NaN payload. -- Denormals are preserved. A GPU that flushes f32 denormals will disagree on the denormal cases, and - the harness must report that as an environment mismatch, not a translator bug. - -### GPU side (existing tools, future driver) - -The repository already has the pieces: `runtime/test/shaders/build.py` assembles `.asm` with -`llvm-mc`, `tools/rdna2spirv.py` translates the resulting `.s`, and the `runtime/test/vk_*_test.cpp` -programs dispatch SPIR-V on Vulkan and read buffers/images back. A GPU-side differential runner would: - -1. assemble the `.asm` to a `.s` listing with `llvm-mc -show-encoding`; -2. run the CPU model on that listing with the test's inputs; -3. translate the same listing, `spirv-as` + `spirv-val`, then dispatch; -4. read back the declared outputs and compare raw bits; -5. print the first mismatch and the seed; exit nonzero on any mismatch. - -Keeping one listing for both sides matters: if the CPU model and the translator parse different text, -the test measures the parser, not the translation. - -## Building test programs - -Hand-written RDNA2 assembly is the source of truth. Each test is an `.asm` file whose header comment -states the inputs, the observable outputs and the expected bits, matching the existing convention in -`runtime/test/shaders/*.asm`. The CPU expected values are computed by the interpreter and pinned in -the test table; the GPU must produce the same bits. Pinning the values catches a regression in the -CPU model as well as in the translator. - -`llvm-mc` is already a prerequisite for the shader pipeline. The test build is the same one -`build.py` uses: - -``` -llvm-mc -triple=amdgcn--amdpal -mcpu=gfx1013 -show-encoding test.asm -``` - -A minimal case, with the expected value in the header comment like the existing GPU samples: - -``` -; f32_add_nan hand-written test; expected v2 = 0x7fc00000 -v_mov_b32 v0, 0x7f800000 ; +inf -v_mov_b32 v1, 0xff800000 ; -inf -v_add_f32 v2, v0, v1 -s_endpgm -``` - -The prototype can check the CPU side of that case directly: - -``` -python -I tools/cpu_ref.py --parse-only -python -I tools/cpu_ref.py --json -python -I tests/test_cpu_ref.py -``` - -The scalar ALU has its own differential fuzzer (FUZZ-4), `tools/salu_diff.py`. It has a separate reference for -117 SOP1/SOP2/SOPC/SOPK opcodes in `OPS`, all listed by `--list-ops`. The default translator comparison selects -from 104 opcodes, excluding the 13 wave-mask operations in `LANE_MASK_OPS`. The fuzzer keeps SCC explicit, -generates seeded programs, runs translated SPIR-V in `tests/semantic/spirv_mini_interp.py`, and shrinks failing -programs to the instructions that matter. `s_bfe_*` control words stay inside offset + width <= 32 unless -`--bfe-any`. Its docstring lists the known divergences. - -`--branches` puts SCC into control flow, one lane: after an SCC producer comes either a chain of 1..3 consumers -(`s_cselect_b32`, `s_addc_u32`, `s_subb_u32`) or `s_cbranch_scc0`/`scc1` forward over the next 1..3 scalar -instructions (no loops or nesting), and half the instructions are SCC producers. The listing carries -`; encoding:` placeholders of each instruction's size, which places the branch targets. It is a flag so that the -default seeds keep their programs; translator oracle only. - -``` -python -I tools/salu_diff.py --programs 2000 --seed 1 -python -I tools/salu_diff.py --branches --programs 2000 --seed 1 -python -I tests/test_salu_diff.py -``` - -The `_sdwa` VALU forms have one too, `tools/sdwa_diff.py`: a separate reference for 92 VOP1/VOP2/VOPC opcodes in an -integer and an f16 family (source selects, `sext()`, `dst_sel` with `dst_unused` PAD/SEXT/PRESERVE, SGPR and -inline-constant sources, `clamp`, f16 neg/abs), seeded one-lane programs that chain through v1..v7 and VCC, the same -interpreter, shrinking and exit codes as `salu_diff.py`. Forms where the translator is known to differ -(`KNOWN_DIVERGENCES` in its docstring, which also lists what is modelled and skipped) are left out unless `--known`. -`--oracle hw` runs the programs on an RDNA1/RDNA2 GPU only (GFX11 has no SDWA); every rule of the reference was -checked that way on an RDNA2 iGPU (gfx1036), including two that differ from the non-SDWA forms: a 16-bit result -with `dst_sel:DWORD` zeroes the high half, and a float inline constant in an f16 op is narrowed by `src_sel` as the -f16 value. - -``` -python -I tools/sdwa_diff.py --programs 2000 --seed 1 -python -I tools/sdwa_diff.py --oracle hw --programs 500 --seed 1 -python -I tests/test_sdwa_diff.py -``` - -### Hardware oracle (optional) - -`--oracle hw` also runs the same programs natively on an AMD GPU and compares the hardware's three SGPRs and SCC -with the reference (`--oracle translator,hw` does both; `hw` alone leaves the translator out and then also -runs the 64-bit mask ops, which the hardware reads as plain integers). It tests the reference model, not the -translator. No tool is needed unless you pass `--oracle hw`; when one is missing the run prints -`hardware oracle unavailable: ` and exits 77, so CI is unaffected. - -``` -python -I tools/salu_diff.py --oracle hw --programs 5000 --seed 1 -python -I tools/hw_oracle/runner.py # checks the setup: prints the device, or what is missing (exit 77) -``` - -Setup on Windows, about 800 MB and no admin rights: - -- **Driver.** The AMD Windows driver ships the HIP runtime as `amdhip64_7.dll` in System32; nothing else is - loaded from the SDK. `LEONIDA_HIP_DLL` overrides the path. Drivers from 2024 ship `amdhip64_6.dll` instead and - refuse code object v6 (LLVM 23's default) with error 209 (`hipErrorNoBinaryForGpu`) or 303 (`hipErrorSharedObjectInitFailed`); - the oracle then assembles as v5 (seen with driver 32.0.11020.1002 on gfx1103 and 31.0.24002.92 on gfx1036). -- **true16.** LLVM 23 wants `v8.l`, not `v8`, for 16-bit operands on GFX11. The oracle asks the assembler once and - uses the spelling it takes, for the ops its tools run: the two f16/f32 conversions and `f16_trans_sweep.py`'s - seven. Another f16 op needs adding to `asm.true16_spelling`. -- **Compiler.** AMD clang with the amdgcn backend and `ld.lld`. The stock LLVM from winget has no amdgcn - target. The ROCm wheel has one: - `py -m venv .venv` then `.venv\Scripts\python -m pip install --index-url https://stable.repo.amd.com/rocm/whl-next/ "rocm-sdk-core==10.0.0"`; - `clang.exe` ends up in `.venv\Lib\site-packages\_rocm_sdk_core\lib\llvm\bin`. A `.venv` in the working - directory or repository is found by itself, and so is the wheels' `amdclang` on PATH: that launcher has no - `ld.lld` beside it, so the oracle uses the `clang.exe` in the folder it reports as `InstalledDir`. Otherwise set - `LEONIDA_AMD_CLANG` to that `clang.exe`. -- **Linux** has a launcher of its own, without ROCm: see the next list. `hw_oracle.c` is the Windows one (it loads - the driver's DLL). -- **Host C compiler.** `tools/hw_oracle/hw_oracle.c` is built once into the temp folder by MinGW gcc (on PATH or in - `C:\msys64`), else by MSVC: a `cl` on PATH (a Developer shell), else the Visual Studio that `vswhere` finds, through - its `vcvars64.bat`. The Visual Studio the runtime needs is therefore enough. `LEONIDA_HOST_CC` overrides the choice - (gcc or `cl.exe`). By hand: `gcc -O1 tools/hw_oracle/hw_oracle.c -o hw_oracle.exe` or `cl /O1 tools\hw_oracle\hw_oracle.c`. -- `LEONIDA_HW_ARCH` overrides the detected architecture (`amdgpu-arch`, else `gfx1150`). GFX10 spellings - (`s_load_dwordx2`, `global_store_dwordx4`) are used for `gfx10xx`, so the same kernels assemble for an RDNA2 card - (checked by assembling for gfx1030 with clang and gfx1013 with `llvm-mc`, and run on gfx1036 on Linux). - `gfx12xx` (RDNA4) uses the GFX11 spellings. An architecture outside gfx10, gfx11 and gfx12 is `unavailable` - (exit 77), like a missing tool. - -Setup on Linux, without ROCm. `tools/hw_oracle/hw_oracle_drm.c` submits each kernel as a raw compute dispatch -through the kernel driver (`libdrm_amdgpu`), so nothing sits between the instructions and the GPU: - -- **GPU.** GFX10 only, which is RDNA1 and RDNA2 (compute engine version 10); the launcher answers anything else - with exit 77. Name the render node, for example `LEONIDA_HW_DRM_NODE=/dev/dri/renderD129` - (`ls -l /dev/dri/by-path` shows which node is which PCI device). There is no default device, so a raw command - stream never goes to a GPU by accident. -- **Not the GPU you are looking at.** A raw stream bypasses the Vulkan driver, and a kernel that hangs makes the - kernel driver reset that GPU. A node with a display connected is refused unless - `LEONIDA_HW_DRM_ALLOW_DISPLAY=1`. An integrated GPU next to a discrete card is the convenient case. -- **Tools.** `clang` with the amdgcn target (the distribution's LLVM has it; `LEONIDA_AMD_CLANG` overrides), `gcc` - and the libdrm headers. The launcher is built once into the temp folder. By hand: - `gcc -O1 tools/hw_oracle/hw_oracle_drm.c -o hw_oracle_drm $(pkg-config --cflags --libs libdrm_amdgpu)`. -- **Access.** Your user must be able to open the render node (the `render` or `video` group on most - distributions). -- **The command stream** is libdrm's own compute dispatch test for GFX10 (`amdgpu_test_dispatch_memset`), with what - belongs to the kernel put in: its entry point, its group size, and what its kernel descriptor says. - - `COMPUTE_PGM_RSRC1`, `COMPUTE_PGM_RSRC2` and the wave size are read out of the descriptor in the assembled - object, so the `.amdhsa_*` directives take effect as they do under the HIP runtime: register counts, float - rounding and denormal modes, IEEE mode, DX10 clamp. A test checks that an f32 rounding mode set there changes - a sum on the hardware. - - The descriptor's group segment becomes `COMPUTE_PGM_RSRC2.LDS_SIZE` (bits 15..23, 512-byte units). The - assembler leaves that field 0, so the launcher programs it from the group segment, as the HIP runtime does; - a kernel with LDS reads back what it wrote there (`tests/test_hw_oracle.py`, measured on gfx1036). - - A descriptor that asks for something the launcher does not provide (scratch memory, more than the kernarg - pointer in the user SGPRs, more than 65,536 bytes of LDS) is refused instead of being run differently. - - The output buffer takes up to 16,384 words, as the Windows launcher does, so a 64x64 `image_fuzz` case (16,384 - words) runs here too. - - Every submission gets command memory of its own. While one buffer was rewritten in place, the second kernel of - a process ran the first one's commands, every time; `tests/test_hw_oracle.py` runs 300 distinct kernels to - catch that. - -How it works: each program becomes one kernel (`tools/hw_oracle/asm.py`: load the output pointer, run the program, -store `v[8:11]`), 500 kernels per code object. The code object needs an `.amdgpu_metadata` block; without it the HIP -runtime fails the load with error 209 (`hipErrorNoBinaryForGpu`), which looks like a wrong GPU. The launcher starts -one workgroup of one thread per kernel and pre-fills the buffer with `0xDEAD0000`, so a kernel that did not write -shows up as a mismatch. A program the assembler rejects is counted as a skip, not a pass. - -What it can and cannot say: - -- It says what **that GPU** does. A Radeon 880M is gfx1150 (RDNA3.5), not RDNA2: a match supports the reference, and - a difference is first checked against the RDNA2 ISA text before it is called a reference bug. Only an RDNA2 - card settles RDNA2. -- Skipped on gfx11, and listed in the run's skip counts: `s_ff0_i32_b32` and `s_ff0_i32_b64` (GFX11 has no - find-first-zero), and programs with two different 32-bit literals in one instruction (not encodable). Renamed - opcodes (`s_andn2_*` to `s_and_not1_*`, `s_ff1_*` to `s_ctz_*`, `s_flbit_i32_b32` to `s_clz_i32_u32`, ...) are - accepted by LLVM under their old names with the same behaviour and are run. -- Skipped on gfx12 as well: the twelve SOPK compares `s_cmpk_{eq,lg,gt,ge,lt,le}_{i32,u32}`, which AMD clang - assembles for gfx1150 and rejects for gfx1201. They are about a third of the programs there (seed 1: 870 of 2000 - skipped in all, 1130 run). -- Only the scalar unit is observed, on one lane with EXEC = 1; nothing about wave64 or the other stages. - -Result of the first runs (Radeon 880M, driver 26.11.2, AMD clang 23.0.0git): about 40,000 seeded programs -(1 to 10 instructions each, all opcodes in the table, seeds 1 to 3, 11, 21, 31, 41, 100, 200, with and without -`--bfe-any` and `--inline64`) gave 0 mismatches apart from one finding. `s_bfe_i32` with `offset + width > 32`: -the pseudocode taken literally (the old reference) sign-extends from bit `width - 1` of a zero-filled value, but -the hardware stops the field at bit 31 (`width = min(width, 32 - offset)`) and sign-extends from there. 4,000 random -control words, including bits 23 to 31 of the control word (ignored), fit that rule exactly. The translator already -did this (0 of 600 differ), so the reference was the one that was wrong, and it now follows the measured rule. The -rule rests on that gfx1150 measurement (4000 control words). LLVM's `constantFoldBFE` does the same for the VOP3 -`v_bfe` nodes, but with a 5-bit width, so it is only analogous. - -Result on RDNA2 (the integrated GPU of a Ryzen 9 7950X3D, Raphael, gfx1036; the Linux launcher, Linux 7.3.5, -libdrm 2.4.134, clang 23.1.5 from the distribution): 70,000 seeded programs, 0 mismatches. - -| Run | Programs | Match | Mismatch | Skipped (two literals) | -|---|---|---|---|---| -| seeds 1 to 8 | 40,000 | 39,439 | 0 | 561 | -| seeds 1 to 4, `--bfe-any` | 20,000 | 19,727 | 0 | 273 | -| seeds 1 and 2, `--inline64` | 10,000 | 9,855 | 0 | 145 | - -So the reference, the `s_bfe_i32` rule above included, holds on RDNA2 as measured, and GFX10's `s_ff0_i32_b32` and -`s_ff0_i32_b64`, which gfx1150 cannot run, are covered. As a control, a reference whose `s_min_i32` sets SCC for -equal operands too (`<=` for `<`) gave 2 mismatches in 5,000 programs, minimized to that instruction. - -RDNA4 (Radeon RX 9070, gfx1201, driver 26.11.2, `rocm-sdk-core` 10.0.0 clang): 10,000 programs (seeds 1, 2, 3 and -500, 2000 each, and seed 500 with `--bfe-any`) gave 0 mismatches, so gfx1201 follows the same `s_bfe` rule. With -`--oracle translator,hw`, 200 of 200 programs matched (seed 1). - -#### RDNA2 integer rows (`tools/int_hw_probe.py`, SHADER-137) - -`tools/int_hw_probe.py` runs 87 hand-written cases across 19 integer groups (both wave32 and wave64) natively on -an AMD GPU through `tools/hw_oracle` and compares every output word against `tools/rdna2spirv.py` + -`tests/semantic/spirv_mini_interp.py` (with scalar ops run twice, SCC preset to 0 and 1, so SCC written vs kept is -observed directly). - -Measured on an **AMD Radeon 680M (gfx1035, RDNA2)**, Windows 11 (`10.0.26300`), AMD driver `26.5.1` -(`32.0.21043.7012`, `amdhip64_6.dll`), conda-forge `clang 22.1.8` + `lld 23.1.6` (`--oracle both --wave both`): -**87 cases: 82 bit-exact matches, 5 known live translator divergences, 0 unexpected mismatches, 0 wave32/wave64 -differences** (plus `tools/salu_diff.py --oracle hw,translator --bfe-any --programs 500 --seed 1`: 500/500 match). - -- **Matched RDNA2 silicon in both wave32 and wave64 (82/87):** `s_absdiff_i32`, `s_mul_hi_i32/u32`, `s_lshl1..4_add_u32` - (64-bit shift-out and add carry into SCC), `s_sext_i32_i8/i16`, `s_flbit_i32`, `s_cmov_b32`, `s_cmovk_i32`, - `s_pack_ll/lh/hh_b32_b16`, `s_bfe_u32/i32` past bit 31, `s_brev_b64`, `s_bfe_u64/i64`, `s_bitset0/1_b64`, - `s_flbit_i32_b64/i64`, `s_quadmask_b32/b64`, `s_bitreplicate_b64_b32`, all nine 64-bit scalar bitwise ops on scalar - data, `s_movrels_b32/b64`, `v_add/sub/subrev_nc_u32` / `v_add/sub_nc_i32` / `v_add/sub_nc_u16` with `clamp` and - `op_sel`, `v_mad_u64_u32` / `v_mad_i64_i32` (`sdst` bit 64 sign of exact 65-bit sum and inactive-EXEC masking), - `v_sad_u8`/`hi_u8`/`u16`/`u32`, `v_msad_u8`, `v_lerp_u8`, `v_qsad_pk_u16_u8`, `v_mqsad_pk_u16_u8`, `v_mqsad_u32_u8`, - `v_mul_hi_u32_u24`/`i32_i24`, `v_lshrrev_b64`/`v_ashrrev_i64`, `v_mad_u16`/`i16` (`clamp`, `op_sel`, untouched half - kept), `v_cvt_f16_u16/i16` and `v_cvt_u16/i16_f16` (`_e64` keeps high half; NaN → 0, ±inf saturates; note GFX10 - does not accept `op_sel` on these opcodes), `v_cvt_i32_f32` (control: all ±qNaN/±sNaN → 0), and - `v_cvt_pknorm_i16/u16_f32` (±qNaN → 0, ±inf saturation, RNE ties at ±0.5). -- **Translator divergences found on gfx1035:** five (VOP3 `clamp` on the six carry-out add/sub ops ignored; - `v_cvt_rpi_i32_f32` rounding `x + 0.5` in binary32; `v_cvt_flr/rpi_i32_f32` returning `0` for NaN instead of - saturating by its sign). All are fixed (#1831, #1856), so `KNOWN_DIVERGENCES` is empty and all 87 cases - match. - -#### RDNA2 swizzled buffer addressing (`tools/buffer_swizzle_probe.py`, SHADER-343) - -`tools/buffer_swizzle_probe.py` runs 22 hand-written MUBUF/MTBUF buffer-swizzle cases across 8 groups (both wave32 -and wave64) natively on an AMD GPU through `tools/hw_oracle` and compares every output word against -`tools/rdna2spirv.py` + `tests/semantic/spirv_mini_interp.py`. - -Measured on an **AMD Radeon(TM) Graphics (gfx1036, RDNA2)**, Windows AMD driver `32.0.21042.62`, ROCm clang -(`--oracle both --wave both`): **22 cases: 22 bit-exact matches, 0 known divergences, 0 unexpected mismatches, -0 unexpected wave32/wave64 diffs** (and the 64-thread `add_tid_wave_lane` case matches wave32 and wave64 -individually, confirming wave-lane wrap at 32 vs 64). - -Six silicon divergences from the earlier ISA-only implementation were found and fixed in `tools/rdna2spirv.py`: - -- `idxen = 1` ignores `ADD_TID_ENABLE` completely (both address and bounds, linear and swizzled). -- `SWIZZLE_ENABLE = 1` with `idxen = 0` and `ADD_TID_ENABLE = 0` has no effect (linear address, mode 3 stays RAW). -- Multi-dword raw accesses step by `+4 * IS` only in scratch-swizzle mode (`SWIZZLE_ENABLE = 1`, `idxen = 0`, - `ADD_TID_ENABLE = 1`), whereas indexed swizzle (`idxen = 1`) steps linearly by `+4` bytes even across `IS` - boundaries. -- Scratch-swizzle mode suppresses typed formats > 4 bytes (MUBUF and MTBUF loads/stores) and 8-byte - `buffer_atomic_*_x2` even in `OOB_SELECT 2` (while formats <= 4 bytes succeed); indexed swizzle executes them - linearly. -- `OOB_SELECT 3` with active swizzle and `stride != 0` checks `(index + soffset) >= num_records` or - `off + payload > stride`. -- `uint32(voff + inst_offset)` wraps at 32 bits before bounds checking, whereas RAW mode 3 - `uint64(off) + uint64(soffset)` does not wrap at 32 bits. - -Two assembler facts matter when writing edge cases: - -- An integer token in a float-operand position uses AMD's inline-constant encoding for values 0..64 - and -16..-1. `v_add_f32 v0, v1, 2` therefore means `v1 + 2.0`, not `v1 + bits(2)`. To feed a - specific bit pattern, put it in a VGPR with `v_mov_b32` first. -- A literal outside the inline range is emitted as a 32-bit literal and printed as hex (for example - `0x100`), so denormal patterns above the inline range can be written directly. The smallest - denormal (`0x00000001`) cannot: load it with `v_mov_b32`. - -The first test matrix should cover: - -| Case | Program shape | What it pins | -|---|---|---| -| Inline constants | `v_mov_b32` with `1.0`, `-1`, `0x3f800000` | bit patterns, not just numeric equality | -| NaN | `inf + -inf`, `0 * inf`, NaN input through add/mul | canonical quiet NaN and propagation policy | -| Signed zero | `-0 + +0`, `0 - 0`, `-1 * 0` | sign of zero results | -| Denormals | smallest denormal + itself, `* 0.5`, `* 1.5`, max denormal + min denormal | gradual underflow and rounding | -| FMA | exact midpoint case (see below) | fused, single rounding | -| 16-bit | packed `0x3c003c00`, `v_and_b32 0xffff`, `v_lshrrev_b32 16` | packed halves survive moves and masks | -| `cndmask` | VCC lane mask 0b1010, both source values distinct | select direction and per-lane masking | -| Shifts | amount 0, 31, 32, 33; negative arithmetic shift | 5-bit amount mask and sign extension | -| EXEC low half | write only `exec_lo`, then a vector op | the high half of a wave64 mask is untouched | -| EXEC both halves | `exec_lo = 0xffff0000`, `exec_hi = 0` | inactive lanes unchanged | - -The FMA case is the one a naive host implementation gets wrong. A product of two binary32 values can -land exactly on a binary32 midpoint, and a tiny third addend decides the rounding direction. Evaluating -`a * b + c` in host double and then rounding to binary32 can lose that addend. The prototype uses exact -rational arithmetic for FMA; a test pins the result so the implementation cannot regress to the -double-rounded answer. - -#### `v_interp` ALU ops (`tools/interp_hw_probe.py`, SHADER-430) - -`v_interp_*` also run in a compute wave: they read the attribute words from LDS at M0. On gfx1036 with M0 = 0, -attribute N takes 12 dwords from byte 48·N; channel c's P0 and P10 words are dwords 2c and 2c+1, and its P20 word is -dword 8+c (found by filling LDS with markers and reading them back with `v_interp_mov_f32`). So the tool writes -random parameter words there itself, packed f16 pairs and plain f32 values, runs every interp op through -`tools/hw_oracle` and checks each result against exact rational models. It also runs 30 hand-built f16 rounding ties -that tell one rounding of `p2_f16` from two. - -Measured on the **Radeon iGPU of a Ryzen 7 9800X3D (gfx1036, RDNA2)**, AMD driver 32.0.13036.4, Windows 10 22H2, -`rocm-sdk-core` clang, seeds 1–8 × 4 kernels × 32 lanes. Every model matched, under both `--denorm32 3` (MODE keeps -f32 denormals) and `--denorm32 0` (MODE flushes them). That is 292,474 checks per mode plus the 30 ties. - -| Op | Result on gfx1036 | -| --- | --- | -| `v_interp_mov_f32 p0` | the raw P0 word | -| `v_interp_p1_f32` | fma(P10, I, P0) with one rounding to f32. A product rounded first and then added differed in 723 of 4,096 f32 cases (seeds 1–4). A packed channel's words are read as raw f32 bits | -| `v_interp_p2_f32` | fma(P20, J, p1), one rounding | -| `v_interp_p1ll_f16` (`high`) | the chosen f16 halves widened exactly, then fma(h10, I, h0) with one rounding to **f32** | -| `v_interp_p2_f16` (`high`) | fma(h20, J, p1ll) rounded **once, to f16** (all 30 ties gave the single-rounding result, none the f32-then-f16 one). The high 16 bits of vdst are **kept** | -| f32 denormals | follow MODE: with `denorm_mode_32 = 0` a denormal P0, P10 or P20 word reads as 0 | - -The translator wrote `p2_f16` as a full-register result with a zero high half. It now keeps the high half -(`tests/semantic/test_interp_f16_high.py`). This compute route does not reach the other half of SHADER-430: what the -SPI writes into LDS for a real draw, in particular whether a packed channel's P10/P20 are f32 differences of the raw -words or per-half f16 differences under `FP16_INTERP_MODE`. That needs a pixel-shader harness on AMD hardware. Not -covered either: `v_interp_p1lv_f16`, and f16 inf/NaN halves. - -```powershell -python -I tools/interp_hw_probe.py # exit 0: all match; 77: no hardware oracle here -python -I tools/interp_hw_probe.py --denorm32 0 --seeds 1,2,3,4,5,6,7,8 -``` - -## Harness design - -`tools/shader_diff.py` owns the test table, the seed and the comparison, leaving -`cpu_ref.py` a pure interpreter (it is never modified by the runner). Per case: - -- **Inputs.** Initial SGPRs/VGPRs (per lane), VCC, EXEC, and later buffer/image contents. Inputs are - generated from a named seed (SplitMix64 or `random.Random(seed)`), so a failure is reproducible - from the seed alone. Hand-pinned cases should also accept explicit values. -- **Outputs.** A declared list of observable registers, buffer ranges or image texels. Compare raw - bits. For NaN, compare "both NaN" by default and record the payloads; for finite values, require - exact equality. -- **First mismatch.** Report case name, seed, lane, register/buffer offset, expected bits, actual - bits, and the RDNA2 instruction at the PC that last wrote the value. Stop at the first mismatch; - the full diff is noise once one lane diverges. -- **Environment checks.** Query the device for f32 denormal preservation, f16 support and subgroup - size before running cases that need them. A missing feature is a skip with a reason, never a pass. -- **Harness canaries.** Hand-written SPIR-V twins for a few cases, plus an intentionally wrong - expected value, must fail. A harness that cannot fail is not a harness. -- **No silent skips.** Count `pass`, `mismatch`, `skip(reason)` and `harness-error`. A run whose - mismatch count is zero but whose skip count is 90% is not evidence of broad correctness. - -The existing `runtime/test` tools already expose the hard parts (device selection, push constants, -descriptor setup, readback). The differential runner should call them rather than grow a second -Vulkan stack. - -### Integer VALU across the whole wave (`tools/wint_diff.py`) - -The one-lane fuzzers cannot see which lanes an instruction writes or the lane masks it reads and makes. -`tools/wint_diff.py` runs seeded integer VALU programs on every lane of a wave32 or wave64 wave (`--wave 32|64|both`) -with EXEC rewritten between instructions: compares into SGPR masks and VCC (e64 and e32), `v_cmpx` into EXEC, -`v_cndmask_b32` on those masks, the carry-out and carry-in forms (`v_add/sub/subrev_co_u32`, `_co_ci_u32`, e64 -and e32), `v_mad_u64_u32`/`v_mad_i64_i32` with a mask carry-out, 16-bit e64/VOP3 ops with `op_sel` writing one half, -data moved into an SGPR mask, and a set of 32-bit ops. The reference is a per-lane ISA model in the tool; the -translated side runs in `tests/semantic/spirv_wave_interp.py`. Shrinking, skips and exit codes are those of -`salu_diff.py`. Forms the translator is known to get wrong (VCC holding data read as a mask, #2206 for wave32 and -open for wave64; a mask read as VALU data, #293) are left out unless `--known`. `--oracle hw` runs each program as -one wave on an AMD GPU and compares every lane; on an RDNA2 iGPU (gfx1036) 1,000 programs in both wave sizes, -the known forms included, matched the reference. - -``` -python -I tools/wint_diff.py --programs 2000 --seed 1 --wave both -python -I tools/wint_diff.py --oracle hw --programs 500 --seed 1 --wave both -python -I tests/test_wint_diff.py -``` - -### LDS and `ds_*` on the GPU (`tools/lds_fuzz.py`, FUZZ-6) - -LDS ops are workgroup-wide, so `tools/lds_fuzz.py` runs on the GPU rather than one lane in the -interpreter. Each seeded program is one 64-thread group (wave64, or two wave32s) with 4 KiB of LDS -that starts from a known pattern. It runs 4 to 12 random `ds_*` instructions, each followed by -`s_waitcnt` and `s_barrier`, then stores all 16 result VGPRs of every thread and the whole LDS. -`vk_compute_test` reads them back with `VKC_OUT_WORDS` / `VKC_DUMP`. - -For the translator oracle, `lds_fuzz.py` and `valu_fuzz.py` create and retain a unique output folder per run. With -`--work DIR`, that folder is a new child of `DIR` (the printed work directory), rather than `DIR` itself; files from -older runs and other contents of `DIR` are left alone. Without `--work`, it is created in the system temporary folder. - -- **Instructions.** Every read width (`b32` to `b128`, `u8`/`i8`/`u16`/`i16`, `u16_d16[_hi]`, `u8_d16[_hi]`, `i8_d16[_hi]`), the - byte and short writes (also `d16_hi`), `read2`/`write2` with and without `st64`, the add, sub, - min, max, and, or and xor atomics with and without return, `wrxchg`, `cmpst`, `ds_swizzle_b32` - and `ds_bpermute_b32`. -- **Reference.** A model in the same file, written from the ISA and not from the translator. -- **Determinism.** Programs stay deterministic. Writes, returning atomics, `wrxchg` and `cmpst` use - addresses no other lane touches in the same op. Only order-independent atomics without return - share addresses. Every access is in bounds, because the translator wraps out-of-range indices - where hardware returns 0. -- **Swizzle.** Offsets are the two forms the LLVM `swizzle()` macros encode, checked with - `llvm-mc 23 -mcpu=gfx1013`: bit 15 = quad permute; otherwise and = bits 4:0, or = 9:5, - xor = 14:10, within each 32-lane group. -- **EXEC.** Random EXEC masks are used on every op except `ds_swizzle`. -- **Reports.** A mismatch names the thread, the register or LDS word, and the op that last wrote it. - `--no-exec KIND` drops one op kind's masks without changing the rest of the program, to separate - a known finding from new ones. -- **Subgroup size.** Wave32 programs, and wave64 ones built with `--emulate`, ask `vk_compute_test` for - 32-lane subgroups (`VKC_SUBGROUP_SIZE=32`). Where the device can't require it but 32 is its default - (MoltenVK), a probe shader checks the lanes first and the programs are compared (see `docs/testing.md`, - "GPUs with 32-wide subgroups"). Where the device can't pin that size at all, `vk_compute_test` - prints `compute subgroup size: 32 not available` and runs at the driver's choice, and the wave32 - program is a skip, not a mismatch: its words come from another wave size. Mesa llvmpipe (8 lanes) - is such a device. Emulated wave64 uses no subgroup operations, so it is still compared there. - `valu_fuzz.py` and `crosslane_fuzz.py` follow the same rule. - -First results on an RX 6700 XT (RADV, Mesa 26.3.1), native wave64/wave32 and with -`--wave64-emulate` at subgroup 32: - -- **One finding, already fixed by #253.** With wave32 `ds_bpermute` under EXEC, a source lane that - is off returned its value instead of 0: 12 of 240 programs (seeds 1 to 3) failed, each time - under a masked wave32 `ds_bpermute`, and with #253's translator all 480 programs (seeds 1 to 3, - native and emulated) match. -- **Everything else matches.** With `--no-exec bpermute`, 1,040 programs match (seeds 1 to 8). -- **Not in the default mix.** `ds_permute_b32` is generated with `--permute` (below). The 8-bit d16 reads - (`ds_read_u8_d16[_hi]`, `ds_read_i8_d16[_hi]`) are translated since SHADER-85 (`cs_w32_lds_u8_d16`) and the - fuzzer generates them. - -#### Hardware oracle for the LDS programs (`--oracle hw`) - -`--oracle hw` runs each program natively on an AMD GPU through `tools/hw_oracle/` (setup: "Hardware oracle" under -FUZZ-4) and compares every stored word, 16 result registers per thread and all 1,024 LDS dwords, with the model; -`--oracle translator,hw` does both and prints what the translator did with each program the hardware disagrees -with. It tests the **model**, not the translator. Without the tools it prints `hardware oracle unavailable: ...` and -exits 77. - -``` -python -I tools/lds_fuzz.py --oracle hw --programs 2000 --seed 1 -python -I tools/lds_fuzz.py --oracle hw --extended --programs 2000 --seed 1 --negative-control -python -I tools/lds_fuzz.py --oracle hw --programs 50 --seed 1 --wave 32 --only 1,18,20,24 --minimize -``` - -- **What runs.** The program's real group size (`--threads 32|64|128|256|mix`: one partial wave, one wave, or several - waves joined by `s_barrier`), wave32 and native wave64 (`.amdhsa_wavefront_size32 0`), its EXEC masks (the entry - EXEC is saved in `s10` and restored, so a partial wave keeps its missing lanes off), and the LDS size in the - kernel descriptor and metadata (`.amdhsa_group_segment_fixed_size`; without it the group gets no LDS). Results go - out with `global_store_b32` through the output pointer. -- **GFX11 spellings** (`hw_oracle/asm.py`, checked by assembling every mnemonic with AMD clang for gfx1030 and - gfx1150): `ds_read_*` is `ds_load_*`, `ds_write_*` is `ds_store_*`, `ds_read2[st64]_b32` is - `ds_load_2addr[_stride64]_b32`, `ds_write2[st64]_b32` is `ds_store_2addr[_stride64]_b32`, `ds_wrxchg_rtn_b32` is - `ds_storexchg_rtn_b32`. The assembler still takes the old names on gfx1150 except `ds_cmpst_rtn_b32`. - **`ds_cmpstore_rtn_b32` takes the value to store before the compare value**, the reverse of GFX10's - `ds_cmpst_rtn_b32 vdst, vaddr, cmp, store`; llvm-mc encodes both spellings of the same text identically, so only - the operand order says which. Unswapped, every program with a `cmpst` failed on gfx1150 (each minimized to that one - op); swapped, none does. GFX12 takes the same order (measured on an RX 9070 XT, gfx1201: with 7 in the dword and - data `v1 = 9`, `v2 = 7` it becomes 9, with `v1 = 7`, `v2 = 9` it stays 7, for `ds_cmpstore_rtn_b32` and - `ds_cmpstore_b32`; gfx1036's `ds_cmpst` does the opposite), and with `--perturb cmpst_swap` 275 of 1,000 wave32 - programs mismatch there. The model keeps the GFX10 order. Nothing else the generator emits is missing on GFX11, so - no other program is skipped for its semantics; an assembler rejection is counted as `rejected`, never as a pass. -- **GFX12** (`hw_oracle/asm.py` `sync_lines`): there is no `s_barrier` (a workgroup barrier is - `s_barrier_signal -1` then `s_barrier_wait -1`), and the LDS wait is `s_wait_dscnt 0` instead of the legacy - `s_waitcnt lgkmcnt(0)`. **A wave64 `ds_bpermute_b32` and `ds_permute_b32` reach all 64 lanes on GFX12**, while - RDNA2 (and gfx1150) keep each 32-lane half separate: with every lane asking for lane `(l + 32) mod 64`, the - RX 9070 XT returns lane `l ^ 32` and a gfx1036 iGPU returns lane `l`; and with every lane *sending* to lane - `(l + 32) mod 64`, the RX 9070 (gfx1201, same as the XT measurement) delivers the sender's value to lane - `l ^ 32`, all 64 lanes, with lane-`l`-to-lane-`l` sending as the control. A masked wave64 `ds_swizzle` keeps - its halves (0 mismatches in a 40-program `--swizzle-exec` run there). The model describes RDNA2, so on gfx12xx - a wave64 program with either op is skipped with that reason; under `--perturb bpermute_wave64_cross` / - `--perturb permute_wave64_cross` the programs that run match there (the `--extended` 40 programs of seed 1: - 23 of 40 wave64 match, 0 mismatch, the rest skipped for the bpermute reason). RX 9070 XT, AMD 26.11.2, - `--programs 1000`, seeds 1 and 2: wave32 1,000/1,000 match; wave64 537 and 506 match, 0 mismatch, the rest - skipped for that reason; on the RX 9070, `--programs 500`, seed 1: wave32 500/500 match, wave64 250 match and - 250 skipped, 0 mismatch, 0 rejected. The gfx1036 iGPU gives 1,000/1,000 in both. -- **Wider op mix**, opt-in so that a seed keeps its programs: `--permute` (`ds_permute_b32`), `--swizzle-exec` - (`ds_swizzle_b32` under EXEC masks), `--threads`, `--extended` (all three). `ds_permute_b32` and a masked - `ds_swizzle_b32` carry a hypothesis (the model's reading of the ISA text); on the hardware a failing one is a - mismatch like any other and counted in `hyp_only`, on the translator it is reported apart as `HYPOTHESIS MISMATCH`. - The swizzle hypothesis was falsified at first ("an active lane reads its source lane's register whether or not - that lane is on"): gfx1150 returns 0 when the source lane is off in EXEC, as `ds_bpermute` does. The model now - says that. -- **Negative controls.** `--perturb NAME` judges the hardware against a deliberately wrong model (mismatches must - appear); `--negative-control` re-judges the words of the run with all 16 (`max_i32` unsigned, `min_u32` signed, - swapped `cmpst`, zero-extended `i8`/`i16`, d16 reads clearing the other half, `b16_d16_hi` shift, swapped - `write2`, `st64` unit, bpermute reading off lanes or crossing the wave64 halves, reversed quad permute, swapped - swizzle or/xor, permute writing no zero, permute lowest source winning a collision) and exits 1 if one goes - unnoticed. `--minimize` drops ops while a program still differs, `--keep DIR` writes the native kernel of each - mismatch, `--only I,J` runs chosen indices. - -RDNA2 `ds_permute_b32` verification (`FUZZ-10`, `SHADER-133`): raw kernels on an AMD Radeon RX 6800 (`gfx1030`, wave32 -and wave64) confirm that only active lanes send, the highest active source lane wins a collision, active destination -lanes nobody targets read `0`, inactive destinations keep their old values, and the two 32-lane halves stay separate -in wave64. On an AMD Radeon RX 6700 XT (`gfx1031`, RADV Mesa 26.3.1), 3,600 translator runs with colliding -`ds_permute_b32` multipliers (`mul` in `0..63`, seeds 1–3, 300 programs × wave32/wave64 native and `--emulate`) -matched the model bit for bit (`0` mismatches), and inverting the collision winner or zero-fill rules produced -mismatches in `39` and `56` of `200` seed-1 programs. - -Results on a Radeon 880M (gfx1150, RDNA3.5, driver 26.11.2, AMD clang 23.0.0git), `--oracle hw`: - -| Programs | Count (wave32 + wave64) | Mismatches | -| --- | --- | --- | -| default mix, seeds 1, 2, 3, 11, 21, 31, 41, 100, 200, 2,000 each | 36,000 | 0 | -| `--extended`, seeds 1, 2, 3, 11, 21, 31, 2,000 each (permute, masked swizzle, groups of 32 to 256) | 24,000 | 0 | -| seed 1, `--only` the twelve wave32 programs SHADER-105 names (1 18 20 23 24 26 29 30 32 33 34 38) | 12 | 0 | - -Negative control (1,000 extended programs): each of the 15 wrong models mismatches on 126 to 547 programs, none goes -unnoticed. gfx1150 is RDNA3.5, not RDNA2; the RDNA2 runs follow. - -Results on the integrated Radeon of a Ryzen 7 9800X3D (gfx1036, RDNA2, AMD driver 32.0.13036.4, Windows HIP launcher, -AMD clang 23.0.0git), `--oracle hw` on `main` `003e7812`: - -| Programs | Count (wave32 + wave64) | Mismatches | -| --- | --- | --- | -| default mix, seeds 1, 2, 3, 2,000 each | 12,000 | 0 | -| `--extended`, seeds 1, 2, 3, 2,000 each (permute, masked swizzle, groups of 32 to 256) | 12,000 | 0 | - -`hyp_confirmed` (programs with a hypothesis op that matched) in the extended runs: 1158/1185, 1183/1177 and 1151/1189 -(wave32/wave64, seeds 1 to 3). So on RDNA2 too a masked `ds_swizzle_b32` whose source lane is off in EXEC reads 0, -and `ds_permute_b32` follows the model. Negative control (extended, seed 1): each of the 15 wrong models mismatches, -from 417 programs (`bpermute_inactive_reads`) to 1,123 (`write2_swapped`); none goes unnoticed. - -With `--oracle translator,hw` on the same Radeon 880M (Vulkan, subgroup 64), seed 1, 100 programs per run: the -default mix matches the model on the translator, native and emulated (200/200 each). With `--extended` the -translator differs from the hardware in 22 of 177 programs (native and emulated alike), all in a `ds_swizzle_b32` -under an EXEC mask whose source lane is off: the translator hands the active lane the source lane's register, the -hardware gives 0 (the swizzle hypothesis above). So the translator differs from gfx1150 for a masked -`ds_swizzle_b32` with an off source lane; the gfx1036 hardware runs above show RDNA2 gives 0 as well (SHADER-207). Not -fixed here. Partial-wave programs (`--threads` 32 -in wave64) are skipped for the translator, which cannot launch them. NVIDIA was not run. - -**Other backends.** The Linux libdrm launcher of #1265 (`tools/hw_oracle/drm.py`) now runs these programs too. It -programs `COMPUTE_PGM_RSRC2.LDS_SIZE` from the descriptor's group segment (the assembler leaves that field 0, so the -4,096 bytes of LDS `lds_fuzz` asks for reach the hardware) and its output buffer takes 16,384 words like the Windows -launcher's, so a 64x64 `image_fuzz` case fits. On the integrated Radeon of a Ryzen 7 7700X (gfx1036, RDNA2, Linux -7.3.5-zen1-1-zen, libdrm 2.4.134, AMD clang 23.1.5): - -| Run | Programs / cases | Mismatches | -| --- | --- | --- | -| `lds_fuzz.py --oracle hw --programs 500 --seed 1` (wave32 and wave64) | 1,000 | 0 | -| `image_fuzz.py --oracle hw --programs 120 --seed 1` (60 cases per wave; 8 to 64 per side, four 64x64 cases) | 120 | 0 | - -`lds_fuzz --oracle hw` no longer exits 77 on Linux for LDS or the word count. The gfx1036 numbers earlier in this -section are still from the Windows HIP launcher; these two runs put the same model on the same architecture through -libdrm. - -**Overlap with #789.** #789 adds `ds_permute_b32` to the default op mix of `lds_fuzz.py`; here it is opt-in -(`--permute`) so that existing seeds keep their programs. Whichever lands second reconciles the two. - -**SHADER-105** (Intel `lds_fuzz` mismatches in DS atomics `max_i32`/`max_u32`, `ds_cmpst`, small reads, and -registers that kept their initial value): the model matches gfx1150 for every one of those families, under EXEC -masks, in wave32 and wave64, and in multi-wave groups. The Intel mismatches went away with #820's constant-EXEC fix -(50/50 native and 100/100 emulated for seeds 1 to 3). `ds_bpermute` (SHADER-31, #253) matches the model on gfx1150 -too, including "an off source lane reads 0" in both wave sizes. - -### Memory instructions (`tools/mem_diff.py`, FUZZ-5) - -`cpu_ref.py` has no memory model, so memory instructions get their own runner. `tools/mem_diff.py` -carries a small reference model written from the RDNA2 addressing rules (V# base and stride, MUBUF -`soffset + offset + voffset + vindex * stride`, SMEM pointer/V# plus offsets, signed 12-bit `global_*` -offsets, 32-bit buffer atomics) and compares it with the translation run in `spirv_mini_interp`. Both -the exported words and the whole final memory are compared, so stores and atomics are checked too. - -```powershell -python -I tools/mem_diff.py --programs 3000 --seed 1 [--family buffer_load] [--max-ops 4] -python -I tools/mem_diff.py --self-test -python -I tests/test_mem_diff.py -``` - -Families: `s_load`, `s_buffer_load`, `buffer_load`, `buffer_store`, `buffer_atomic`, `global` -(dword loads/stores, `ubyte`/`sbyte`/`ushort`/`sshort`). Every access is generated in bounds and -dword aligned (sub-dword loads at their natural alignment), with no format in word3: out-of-bounds -results, `OOB_SELECT`, swizzling and the `s_buffer_load` alignment truncation depend on descriptor -fields the translator does not model yet, so they need a GPU-confirmed rule before they are fuzzed. -`spirv_mini_interp` gained `OpSConvert` and the 32-bit atomics on PhysicalStorageBuffer memory for -this. Images have their own fuzzer (`tools/image_fuzz.py`, below). - -The `buffer_format` family covers `buffer_load_format_*` on every format the translator decodes, with a -random DST_SEL of 0/1/X/Y/Z/W, and `tbuffer_load_format_*` on the five formats the 1.0.2.1 corpus uses -(`16_16_SNORM`, `8_8_8_8_UNORM`, `8_8_8_8_UINT`, `2_10_10_10_UNORM`, `16_16_16_16_UINT`, about 53,000 -instructions). Generated MTBUF cases use a bound 32_UINT V# and take their data format from the -instruction. The reference decodes elements from the GFX10 format *name* in `tools/gfx10_formats.json` -(channel widths listed from the top bit). UNORM/SNORM values use correctly rounded division. -MUBUF repeats missing channels (*c* mod *n*) and DST_SEL 1 gives integer 1 for UINT/SINT and 1.0f -otherwise (SHADER-86, RX 6700). MTBUF loads return instruction-format channels in order, zero-fill -missing channels and return zero for an INVALID V# format (native gfx1036, wave32 and wave64). -Elements are naturally aligned. A half NaN widens to f32 with its payload shifted into the f32 mantissa -and its sign and quiet bit unchanged (`f16_to_f32`, bit-level so the Python version cannot change it); -the translator used to canonicalise it, which is the one class this fuzzer found -(`docs/shader_validation.md`, "Widening a 16-bit float NaN in a typed buffer load"). - -Over 5,000 programs the reference and translator match bit for bit; breaking the `16_16_SNORM` kind, the -`8_8_8_8_UINT` widths or the DST_SEL order in the translator makes 33, 37 and 191 of 300 programs fail. - -A mutation check (inst offset dropped, V# stride narrowed, the SMEM pointer's high word dropped) makes -76, 45 and 42 of 150 programs fail, so the runner does catch address errors. - -### Sum-of-absolute-differences family (`tools/sad_diff.py`) - -The subset interpreter `cpu_ref.py` has no SAD ops, so the family gets its own runner, like the memory -instructions above. The family is seven opcodes — `v_sad_u8`, `v_sad_hi_u8`, `v_sad_u16`, `v_sad_u32`, -`v_msad_u8` and the packed quad forms `v_qsad_pk_u16_u8`, `v_mqsad_pk_u16_u8`. `tools/sad_diff.py` -carries a small reference written from the ISA pseudocode recorded in `docs/design.md`'s contract rows -(the "Sum of absolute differences" row hardware-verified on gfx1035 through SHADER-137's `int_hw_probe` -run; the `v_qsad` row bit-exact on an RTX 3060 in #623) and compares it with the translation run in -`spirv_mini_interp`, the four exported mrt0 words, bit for bit (everything here is integer, so a -mismatch can never be a rounding convention). - -Programs are straight-line: seeds in v8..v15 and s4..s7, then family ops whose destinations stay inside -v8..v11 (the quad ops write pairs inside that), then `exp mrt0 v8, v9, v10, v11`, so every result is -observed and later ops chain on earlier ones. Every operand position takes every source kind the -encoding allows: VGPR, SGPR, a hex literal, an inline constant and `null` for the 32-bit sources; the -quad ops' 64-bit S0/S2 take VGPR/SGPR pairs, a hex literal (zero high word) or an inline constant -(sign-extended) — the 64-bit constant rule of the contract table, pinned both ways: a hex literal reads -the same as the register pair holding its word and a zero high word, while a negative inline constant -sign-extends, so the two constant forms differ in the high word. - -Two modes run one after the other: a sweep over the whole source-kind space (every (S0, S1, S2) kind -combination, 125 per plain op, 80 per quad op, 785 programs) with values drawn from byte/half edge -words, and random seeded programs that widen the value coverage over the same kind space. Not -generated, on purpose: `clamp` (the contract rows say the translator rejects it; pinned as expected -rejections in `--self-test`), `op_sel`/`neg`/`abs` (the ISA does not define them for these opcodes), -`v_mqsad_u32_u8` (open PRs #1926/#2163 are on that op) and `null` as a 64-bit quad source (PR #2650's -subject). - -```powershell -python -I tools/sad_diff.py --programs 2000 --seed 7 -python -I tools/sad_diff.py --self-test -python -I tests/test_sad_diff.py -``` - -Across seeds 1, 2, 3, 7, 11 and 12 (the last pair with `--max-ops 12`) 12,810 programs match bit for -bit, zero mismatches and zero skips; the seed-7 headline run alone is 785 + 2,000 programs with about -1,050 to 1,175 cases per op. Two mutations of the translator's SAD rule — the per-byte `UMax`/`UMin` -pair replaced by a wrapped subtraction, and the `v_sad_hi_u8` shift dropped — make 36 and 17 of 60 -programs fail (`--programs 60 --seed 2 --max-ops 5 --no-sweep`), so the runner does catch arithmetic -errors. - -### Images on the GPU (`tools/image_fuzz.py`) - -`tools/image_fuzz.py` starts on the image path, where the T# format, the view type and the binding layout -meet the driver. Each case assembles a pixel shader that reads one texel with `image_load` (a nonzero `dmask`, the -T# in `s[8:15]`), runs it through `runtime/test/vk_image_fuzz.cpp` against a synthetic texture of a chosen -format, and compares every RGBA32F pixel with an oracle that models the RDNA2 texel fetch for that format: a -fetch is a memory read, so there is no filter, border or LOD to model. - -The comparison is bit exact (any NaN matches any NaN) with one exception. The translated shader fetches a UNORM -texel through a float view, so the 8-bit to float conversion is the driver's. RDNA2 returns the correctly rounded -c / 255. llvmpipe multiplies by an f32 1/255, which is one ulp above that for 126 of the 256 byte values (27 gives -0x3dd8d8da, not 0x3dd8d8d9), and a run stops at its first mismatch, so on llvmpipe no case after the first -`R8G8B8A8_UNORM` one ran. The translator oracle therefore accepts one ulp on a UNORM8 texel component, never on -another format or on a sentinel, and the summary says how many components needed it. `--oracle hw` stays bit exact. - -Each run keeps its generated files in a unique output folder. With `--work DIR`, it is a new child of `DIR` and its -path is printed; existing contents and other runs are left alone. Without `--work`, it is in the system temporary folder. - -```sh -cmake --build runtime/build --target vk_image_fuzz -python -I tools/image_fuzz.py --programs 8 --seed 1 [--show] -python -I tools/image_fuzz.py --self-test -python -m pytest tests/test_image_fuzz.py -``` - -Covered: 2D `image_load`, `R8G8B8A8_UNORM`, `R16G16B16A16_SFLOAT`, `R32G32B32A32_SFLOAT`, `R32_SFLOAT`, -and `R8G8B8A8_UINT`/`SINT`, all as sampled images, as the runtime binds a read-only texture (integer formats are -read through the translator's uint/sint aliases of the sampled array). The shader converts the loaded 8-bit integer values to float for -readback; every such value is exactly representable, including signed negatives. Wider integers are not covered. -Texture sizes divide the 64x64 draw (8/16/32/64), so every texel is read at least once. The mask cycle starts with -`0xf` and `0x5`, so the default eight programs already exercise packing across a gap. With 90 programs, each of the -six default formats exercises all 15 nonzero masks. Selected channels are packed into consecutive destination -registers, while unwritten registers keep initialized sentinel values. -The packing model follows the image VGPR usage description in AMD's -[RDNA 1.0 ISA guide](https://www.amd.com/content/dam/amd/en/documents/radeon-tech-docs/instruction-set-architectures/rdna-shader-instruction-set-architecture.pdf); -the Vulkan test compares translated shaders on the host GPU, not native RDNA2 execution. - -Devices: the harness needs `fragmentStoresAndAtomics`, and no without-format storage-image feature: a translated -`image_load` fetches every format from the sampled arrays, UINT/SINT ones through integer aliases (SHADER-151, the -"Typed image loads" row of `docs/design.md`). Until then it declared the uint/sint storage path even when the case -read a float format, so an Intel UHD 770 (Xe-LP), which lacks `shaderStorageImageReadWithoutFormat`, skipped every -case. Not covered yet: wider UINT/SINT formats, mips, 1D/2D-array/3D/cube, -`image_sample`/`gather` with filters and borders, and texel offsets with `VK_KHR_maintenance8`. - -#### Hardware oracle for the image fetches (`--oracle hw`) - -`--oracle hw` runs the same fetches natively on an AMD GPU through `tools/hw_oracle/` (setup: "Hardware oracle" under -FUZZ-4) and compares every result register of every texel, bit for bit, with the CPU model above; -`--oracle translator,hw` does both on the same textures and says, for each case the hardware disagrees with, what the -translator did. It tests the **model**: whether `image_load` on real hardware returns what the oracle says. Without the -tools it prints `hardware oracle unavailable: ...` and exits 77. - -``` -python -I tools/image_fuzz.py --oracle hw --programs 2400 --seed 1 -python -I tools/image_fuzz.py --oracle hw --programs 180 --seed 1 --negative-control -python -I tools/image_fuzz.py --oracle translator,hw --programs 90 --seed 1 -python -m pytest tests/test_image_fuzz_hw.py -``` - -- **What runs.** One raw compute kernel per case, wave32 and native wave64 alternating. The texture is linear - (`SW_MODE` 0) device memory the kernel carries behind its own code, 256-byte aligned and found with `s_getpc_b64`, so - the launchers need no input buffer; rows are padded to a 256-byte pitch and the padding is a pattern that is wrong to - read (`0xCD`). The kernel builds the T# in `s[8:15]` (the base address from the PC, the other words are literals), - runs `image_load v[8:..], v[2:3], s[8:15] dmask:.. dim:SQ_RSRC_IMG_2D unorm` for one texel per lane (1,024 lanes - and a short loop for 64x64) and stores `v[8:11]` for each texel, so the sentinels of the registers `dmask` does not - write are compared too. A texture that was not 256-byte aligned would make every word `0xBAADF00D`; the run reports - that as an error instead of reading from a wrong base. The same texels, sizes (8 to 64 per side) and 15 masks as the - translator run; a seed names the same textures for both. -- **The T# per family** (`hw_oracle/tsharp.py`, exact words in `tests/test_image_fuzz_hw.py`). Facts from Mesa's AMD - register database and `ac_descriptors.c` and LLVM's `SIDefines.h` (MIT / Apache-2.0; own code, see - [related_projects.md](related_projects.md)). GFX10 and GFX11 differ here, and GFX12 is a third layout that is not - built (`--oracle hw` on gfx12xx exits 77 with that reason): - - | | GFX10 (gfx10xx, RDNA1/2) | GFX11 (gfx11xx, RDNA3 and RDNA3.5) | - | --- | --- | --- | - | WORD1 `FORMAT` | `[28:20]`, 9 bits | `[27:20]`, 8 bits | - | `R8G8B8A8_UNORM`, `_UINT`, `_SINT` | 56, 60, 61 | 42, 46, 47 | - | `R16G16B16A16_SFLOAT`, `R32G32B32A32_SFLOAT`, `R32_SFLOAT` | 71, 77, 22 | 57, 63, 22 | - | WORD2 `RESOURCE_LEVEL` (bit 31) | 1 ("must be 1") | not there (0) | - | `MAX_MIP` | WORD5 `[7:4]` on GFX10.3 | WORD1 `[19:16]` | - | linear pitch | WORD4: `DEPTH` `[12:0]` and `PITCH_MSB` bit 13, GFX10.3 only | same | - - The pitch is always written explicitly (the row size rounded up to 256 bytes); GFX10.1 (gfx1010) has no such field - and the builder leaves it zero. DST_SEL is X, Y, Z, W, except `R32_SFLOAT`, which reads (X, 0, 0, 1) as the model - says. `WORD5` carries Mesa's `PERF_MOD` 4, the rest is zero. -- **Negative control.** `--negative-control` runs the cases and then re-judges the same hardware words with seven - deliberately wrong models (UNORM8 `/256`, red and blue swapped, SINT8 read unsigned, `R32_SFLOAT` alpha 0, dmask - components not packed, unwritten registers read as 0, texel coordinates transposed) and runs the kernels again with - the T# `FORMAT` of the next format in the table. It exits 1 unless every one of them mismatches. - -Results on a Radeon 880M (gfx1150, RDNA3.5, driver 26.11.2, AMD clang 23.0.0git): - -| Run | Cases | Mismatches | -| --- | --- | --- | -| `--oracle hw`, seeds 1, 2, 3, 2,400 cases each (wave32 and wave64, all six formats, all 15 masks, 8 to 64 per side) | 7,200 | 0 | -| `--oracle translator,hw`, seed 1 (Vulkan on the same GPU, subgroup 64) | 12 | 0 (translator and hardware) | - -Negative control (`--oracle hw --programs 180 --seed 1 --negative-control`): the unperturbed model mismatches on 0 of -180 cases; the seven wrong models are caught by 16 to 168 of them (`unorm_256` 30, `swap_rb` 144, `sint_unsigned` 30, -`alpha_zero` 16, `dmask_in_place` 132, `no_sentinels` 168, `transpose` 166), and a kernel built with the next format's -`FORMAT` code is caught on every format (24 to 30 of 30 cases each). So a mismatch would have shown. - -Finding: none. The CPU model and the hardware agree word for word on all 7,200 cases, including NaN, infinity, signed -zero and denormal inputs (NaN payloads are compared as "any NaN", as in the translator run), the sentinel registers -`dmask` leaves alone, and the `R32_SFLOAT` (r, 0, 0, 1) fill. The translator run on 12 of the same cases agrees too; a -longer `translator,hw` run was not done (the Vulkan side takes about half a minute per case on this machine). - -**RDNA3.5 is not RDNA2.** The gfx1150 T# and image unit are GFX11's; a match shows that the model is right for the -texel fetch of these formats on that hardware, which is not the console's. The GFX10 words have since run on RDNA2: - -Results on the integrated Radeon of a Ryzen 7 9800X3D (gfx1036, RDNA2, GFX10 T# layout, AMD driver 32.0.13036.4, -Windows HIP launcher, AMD clang 23.0.0git), on `main` `003e7812`: - -| Run | Cases | Mismatches | -| --- | --- | --- | -| `--oracle hw`, seeds 1, 2, 3, 2,400 cases each (wave32 and wave64, all six formats, all 15 masks, 8 to 64 per side) | 7,200 | 0 | - -Negative control (`--oracle hw --programs 180 --seed 1 --negative-control`): the unperturbed model mismatches on 0 of -180 cases; the seven wrong models are caught by the same counts as on gfx1150 (`unorm_256` 30, `swap_rb` 144, -`sint_unsigned` 30, `alpha_zero` 16, `dmask_in_place` 132, `no_sentinels` 168, `transpose` 166), and a kernel built -with the next format's `FORMAT` code is caught on every format (24 to 30 of 30 cases each). So the GFX10 T# words of -`hw_oracle/tsharp.py` and the texel-fetch model hold on RDNA2 for these formats; `--oracle translator,hw` was not run -there. The Linux libdrm backend of #1265 (`tools/hw_oracle/drm.py`) now runs these cases too: `--oracle hw ---programs 120 --seed 1` on the same gfx1036 iGPU matched on 120 of 120 cases (60 per wave), four of them 64x64 and -therefore 16,384 words, with no rejections (Linux 7.3.5-zen1-1-zen, libdrm 2.4.134, AMD clang 23.1.5). It copies -only `.text`, which is where the texture lives, and the loaded code is 256-byte aligned. - -### 32-bit integer VALU in every encoding (`tools/vint_diff.py`) - -`tools/shader_diff.py` checks the common integer opcodes with VGPR sources in their e32 form. `tools/vint_diff.py` -adds the rest of the 32-bit integer VALU a compiler emits: the VOP1/VOP2 opcodes as e32 and e64, the VOP3-only ones -(`v_add3_u32`, `v_lshl_add_u32`, `v_alignbit/alignbyte/perm_b32`, `v_min3/max3/med3`, the 24- and 16-bit -multiplies with `op_sel`, `v_bcnt`, `v_bfm`, `v_ffbh/ffbl`, `v_cvt_pk_*16_*32`, ...) and VOPC e64 into a mask with -`v_cndmask_b32_e64`, with VGPR, SGPR, integer and float inline-constant and literal sources in every position the -encoding allows (one literal and two scalar values per VOP3). It runs one lane through -`tests/semantic/spirv_mini_interp.py` against its own ISA model, with the shrinking, skips and exit codes of -`salu_diff.py`; a compare's mask read as VALU data (#293) is left out unless `--known`. `--oracle hw` runs the same -programs on an AMD GPU; on an RDNA2 iGPU (gfx1036) 1,500 programs, the known form included, matched the reference. A 32-bit literal in a 16-bit source of `v_mad_u32_u16`/`v_mad_i32_i16` does not assemble, so literals there have 16 bits (zero-extended, measured). - -``` -python -I tools/vint_diff.py --programs 2000 --seed 1 -python -I tools/vint_diff.py --oracle hw --programs 500 --seed 1 -python -I tests/test_vint_diff.py -``` - -### 16-bit and memory ops on the GPU (`tools/valu_fuzz.py`, FUZZ-2, FUZZ-5) - -`tools/valu_fuzz.py --family f16|mem` uses the same runner shape as `lds_fuzz.py`. It generates seeded -64-thread compute programs, translates them, runs them with `vk_compute_test`'s `VKC_DUMP`, and compares every -thread's 16 result VGPRs (plus the scratch memory for `mem`) bit for bit with a model of the instructions written in -the same file. The model doesn't import the translator. `tests/test_valu_fuzz.py` checks the models on the CPU: -the f16/f32 rounding against Python's IEEE packers, signed zeros, the partial-write rules and out-of-range -buffer accesses. If llvm-mc is present, it also checks that every family's -programs assemble for gfx1013. - -- **`f16`**: f16 add/sub/mul/min/max/fma/fmac/med3, `v_cvt_f16_f32`/`v_cvt_f32_f16`/`v_cvt_pkrtz_f16_f32`, - `v_pk_*` (f16 and shifts) with `op_sel`/`op_sel_hi`, 16-bit integer ops and `v_pack_b32_f16`. It only uses - encodings `llvm-mc -mcpu=gfx1013` accepts: on GFX10 the VOP3 forms of the f16 VOP2 ops take no `op_sel`, and the - 16-bit integer ops exist only as `op_sel` VOP3. Which form keeps the other half follows the 16-bit row of - `docs/design.md`. Results whose exact value is NaN, infinite or denormal, denormal inputs, and min/max of +0 - against -0 are marked uncertain and not compared. -- **`mem`**: `buffer_load/store_dword` to `dwordx4` with `offen`, `idxen`, `idxen offen` and offset-only addressing - (offset-only loads use an SGPR `soffset` that is the slot of the wave's first thread), through V#s built in SGPRs. - Each run draws a random OOB_SELECT, stride and `num_records` for them (any dword-aligned byte count, so accesses end - mid-slot and straddle the end), and the model applies the per-mode rule of "Buffer bounds checking" in design.md per - dword (modes 1 and 2 check once). `s_load_dword/x2/x4` and `s_buffer_load_dword/x2/x4` read what the stores wrote - from the slot of the wave's first thread (a wave-uniform `soffset`, so no other wave races with the store); the - `s_buffer_load` V# has its own stride and `num_records` and the model keeps design.md's bound - (`num_records` bytes, or `num_records * stride`) and ignores OOB_SELECT. Byte/short buffer loads are still not - generated (the translator rejects them). - -`--skip-op OP` (an op name) sets a known finding aside without changing the rest of the program. -`--show SEED:INDEX:WAVE` prints a program and its model. - -#### Hardware oracle (`--oracle hw`, `translator,hw`) - -`--oracle hw` runs the same programs natively on the AMD GPU through `tools/hw_oracle/` (setup: "Hardware oracle" -above; exit 77 without it) and compares the 16 result VGPRs per thread (and the scratch memory for `mem`) with the -model, in wave32 and in native wave64, 64 threads, so it tests the **model** and not the translator. With -`translator,hw` both run on the same programs. `--negative-control` runs deliberately wrong models (six for `f16`, -eight for `mem`) and fails unless each one is caught. - -``` -python -I tools/valu_fuzz.py --family mem --oracle hw --programs 2000 --seed 1 -python -I tools/valu_fuzz.py --family f16 --oracle hw --negative-control --programs 300 -``` - -*What differs on GFX11 (gfx1150) and how it is handled.* The programs are the same ones the translator gets, so -every form has to mean the same on gfx1013 and gfx1150. Checked against Mesa ACO (`aco_ir.cpp`: `instr_is_16bit`, -`can_use_opsel`, `get_gfx11_true16_mask`), the `gfx11-rsrc.json` register description and by running them: - -| Form | GFX10 (gfx1013) | GFX11 (gfx1150) | Handling | -|---|---|---|---| -| f16 VOP2 `_e32`/`_e64` (add, sub, mul, min, max, fmac), `v_cvt_f16_f32`, `v_cvt_f32_f16`, `v_cvt_pkrtz_f16_f32` | low half written, high half kept | same (ACO treats both generations alike; true16 bit 7 of a VGPR selects the half only for v128 and up, which the programs never use) | run | -| `v_fma_f16`, `v_med3_f16`, `v_add_nc_u16`, `v_sub_nc_u16` VOP3 with `op_sel` | `op_sel` source bits, destination bit = high half, other half kept | same | run | -| `v_mul_lo_u16`, `v_lshlrev/lshrrev/ashrrev_b16`, `v_max/min_u16/i16` VOP3 with `op_sel` | same fields | same fields and meaning, but LLVM's gfx11 assembler has no `op_sel` operand for these, and GFX11 renumbered the three shifts (`0x314..0x316` to `0x338..0x33a`) | run: with `op_sel` nonzero the instruction words are written out (`GFX11_VOP3_OPCODE`, checked against llvm-mc in the tests); all-zero `op_sel` uses the plain mnemonic | -| `v_pk_add/mul/max/min/fma_f16`, `v_pk_lshlrev/lshrrev_b16`, `v_pk_ashrrev_i16` with `op_sel`/`op_sel_hi` | per-half selection | same | run | -| `v_pack_b32_f16` | halves moved under IEEE mode 0; under IEEE mode 1 a **signaling NaN** half is quieted (`0x7c96` becomes `0x7e96`; measured on gfx1036, see the RDNA2 results below) | same, gfx1150 quiets it too (measured under IEEE mode 1 only) | run; a signaling-NaN half is "uncertain" in the model (the kernels run with IEEE mode 1) | -| f16 transcendentals (`v_exp/log/rcp/rsq/sqrt/sin/cos_f16`) | write the low half | same | not generated: covered by FUZZ-29 (#1310), which sweeps all 65,536 inputs on the hardware oracle | -| 16-bit integer VOP2 `_e32` forms (`v_add_u16_e32`, ...) | exist, define the whole register (design.md) | **do not exist** (only VOP3, with `op_sel`) | not generated, nothing to compare | -| `v_pk_fmac_f16`, `v_mad_f16`/`v_mac_f16`, `v_subrev_f16` | various | removed or not in this fuzzer | not generated | -| f16 VOP1/VOP2 with VGPR operands v128 and up | whole VGPR | bit 7 selects the high half of v(n-128) (true16) | not generated (the programs use v20..v35, `v0..v127` is what LLVM's fake16 encoding allows too) | -| V# word 1 / word 3 | STRIDE `[29:16]`, SWIZZLE_ENABLE bit 31; FORMAT 7 bits `[18:12]`, RESOURCE_LEVEL bit 24, OOB_SELECT `[29:28]` | STRIDE `[29:16]`, SWIZZLE_ENABLE `[31:30]`; FORMAT 6 bits `[17:12]`, no RESOURCE_LEVEL, OOB_SELECT `[29:28]`, TYPE `[31:30]` = 0 | the hardware kernels build the GFX11 word 3 (`word3()`), the translator programs the GFX10 one; same logical semantics (`--gfx10-word3` runs the old word on gfx1150: it still works, bit 24 is ignored) | -| `buffer_load_dword`, `s_load_dword`, ... | `dword` names | `b32` names | the hardware kernels use the family's spelling (LLVM accepts both) | - -*Memory ordering the kernel needs on GFX11 (the model has none).* Measured with `--hw-sync` on 600 to 1,500 -programs each: with no wait before an `s_load`/`s_buffer_load` that follows a store, 18 of 300 wave32 programs read stale -data; `s_waitcnt_vscnt null, 0` alone leaves 7 of 300, because an earlier scalar load can have left the line in the -scalar cache, which is not coherent with vector stores; `s_dcache_inv` alone leaves 69 of 1,500 (the store had not -left the pipe); both together give 0 mismatches over 20,000 programs, and adding `buffer_gl0_inv` and `buffer_gl1_inv` -changes nothing (a vector load after a store of the same thread needs neither). The default (`--hw-sync scalar`) is -vscnt wait plus `s_dcache_inv`; vector accesses only need `s_waitcnt vmcnt(0)`. - -*Results (Radeon 880M, gfx1150, driver 26.11.2, AMD clang 23.0.0git).* Hardware, 5 seeds (101 to 105) x 2,000 programs x wave32 and native wave64 per family: **`mem` 20,000 of 20,000 match, `f16` 20,000 of 20,000 match, 0 mismatches, 0 assembler rejections** (plus earlier development runs of a further 15,000 `mem` and 12,000 `f16` programs; the one mismatch they produced, the `v_pack_b32_f16` NaN quieting above, is now modelled as uncertain). Negative controls (`--negative-control --programs 500`, 1,000 programs per row, unperturbed model: 0 mismatches): `f16` hi half zeroed 994, `op_sel` destination ignored 863, packed halves swapped 864, `v_min` as `v_max` 424, `v_pack_b32_f16` halves swapped 254, `op_sel` of the encoded 16-bit integer ops ignored 862; `mem` OOB_SELECT ignored 506, mode 0 without the stride check 54, index unchecked 364, soffset left out of the check 69, whole-access instead of per-dword 45, out-of-range loads keeping the old value 590, `s_buffer_load` unbounded 209, its stride ignored 81. Every perturbation is caught. Not run here: `translator,hw` for `mem` (see below); RDNA2 is in the next paragraph. - -*Results on RDNA2 (gfx1036 integrated GPU, AMD Windows driver 32.0.21044.64, HIP backend, AMD clang 23.0.0git, `main` bb2e1842).* -- **Hardware, same protocol** (seeds 101 to 105 x 2,000 programs x wave32 and native wave64 per family): **`f16` 20,000 of 20,000 and `mem` 20,000 of 20,000 match, 0 mismatches, 0 assembler rejections.** On a gfx1030, ROCm 6.2's clang 19 rejected 3,768 of 4,000 `f16` programs (#1365); clang 23 rejects none. -- **Negative controls**, in the order above: `f16` 992, 865, 826, 430, 280 and 879 caught; `mem` 514, 57, 354, 60, 37, 580, 214 and 89 caught. The unperturbed model gives 0 mismatches. -- **`translator,hw` at seed 3** (100 programs, the same GPU through the AMD Vulkan driver): `mem` 200 of 200 match, `f16` 199 of 200. The one difference, `s3_22_w64`, is a driver mismatch of the #1506 kind. The hardware and `tests/semantic/spirv_mini_interp.py` both give the model's value for it, and the same emulated SPIR-V matches on NVIDIA. -- **`v_pack_b32_f16` with modifiers (`neg`, `abs`, `-|x|`) and signaling NaNs**, measured with 1,088 hand-written raw kernels in both wave sizes (wave32 and wave64, 100% parity) and both IEEE modes on gfx1036 (driver 32.0.21045.29003). The inputs covered normal floats (±1.0), zeros (±0.0), infinities (±inf), subnormals (±min_sub), quiet NaNs, and signaling-NaN halves, in either half with `op_sel`. - - IEEE mode 1, the assembler's default: a signaling-NaN half is quieted (bit 9 set; sign bit cleared by `abs` and flipped by `neg`, e.g. `0xfc01` → `0x7e01` under `abs`, `0xfe01` under `-|x|`). - - IEEE mode 0: the half is moved as pure bit operations (`& 0x7FFF` for `abs`, `^ 0x8000` for `neg`, `(x & 0x7FFF) ^ 0x8000` for `-|x|`), with `sNaN` payload and quiet bit preserved untouched. - - Wave32 and wave64 produce identical results across all 1,088 kernels (0 differences). - - The translator implements the IEEE mode 0 bit moves, which is exact on hardware. - -*Results on RDNA4 (RX 9070, gfx1201, RADV/Mesa 26.2.6, the Linux DRM launcher, AMD clang 23.1.5, `main` + this -change).* The hardware gate is per family now: `f16` also runs on gfx1170 and gfx12xx (its kernels assemble clean -for gfx1150, gfx1170 and gfx1201 — 300 programs per wave size each, 0 rejected; the generator's op_sel lines are -respelled by `asm.opsel16_spelling` there, as the runner always has), and `mem` runs on gfx1150 and gfx1170 -(300 programs per wave size, every op kind, 0 rejected) and, in GFX12 spelling, on gfx12xx (below). -`f16` numbers: `--programs 500` (1,000 kernels, wave32 and native wave64) 1,000/1,000 match, 0 mismatches, -0 assembler rejections; the negative control caught every perturbation (100/87/85/42/31/90 of 100 programs for -hi_zero, opsel_dst_ignored, pk_swapped, min_is_max, pack_swapped, i16_opsel_ignored). gfx1201 is not RDNA2: the -match supports the model and settles nothing about the console. - -*`mem` on RDNA4 (RX 9060 XT, gfx1200, AMD Windows driver 26.11.2, the HIP launcher, AMD clang from rocm-sdk-core -10.0.0).* The generator's GFX10/GFX11 text is respelled for gfx12 (`gfx12_lines`): a MUBUF soffset is `null`, not the -literal `0`, which is what "operands are not valid for this GPU or mode" rejected on every `buffer_load/store_b*`; -`s_waitcnt_vscnt` becomes `s_wait_storecnt`, and the legacy `s_waitcnt vmcnt(0)` / `lgkmcnt(0)`, which still -assemble but to the old encoding, become `s_wait_loadcnt` / `s_wait_kmcnt`; `buffer_gl0_inv` and `buffer_gl1_inv` -become `global_inv scope:SCOPE_DEV`. The V#s are unchanged: Mesa's `gfx12-rsrc.json` keeps word 1 -(BASE_ADDRESS_HI, STRIDE) and word 3's DST_SEL, FORMAT (the GFX11 table, 32_FLOAT = 22) and OOB_SELECT bits, adding -STRIDE_SCALE and compression fields that stay 0. The gfx10, gfx11 and translator text is byte-identical to before. -Seeds 2, 3 and 4 × 2,000 programs × wave32 and native wave64: **12,000 of 12,000 match, 0 mismatches, 0 assembler -rejections**, so the four OOB_SELECT bounds rules of "Buffer bounds checking" hold on gfx1200 as measured on RDNA2 -and gfx1150. Negative control (`--programs 300`): unperturbed 0 of 600; caught 312, 33, 211, 39, 19, 353, 129 and 53 -(oob_ignore_mode, mode0_no_stride, idx_unchecked, soffset_unchecked, whole_access, oob_load_keeps, sbuf_no_bound, -sbuf_stride_ignored). `--hw-sync` at seed 5 (500 programs, both wave sizes): `scalar` (the default) and `full` -1,000 of 1,000, `sinv` 964, `min` 955, `none` 935. With the scalar loads left out (`--skip-op sload --skip-op sbuf`) -`none` gives 1,000 of 1,000, and with `s_load` alone 979: on gfx1200, as on GFX11 above, a vector load after a store -of the same thread needs no wait, and a scalar load after vector stores needs both the store wait and the -scalar-cache invalidation. - -*Findings.* The OOB_SELECT per-mode rules, the per-dword straddle rule and the `s_buffer_load` bound of design.md hold -on gfx1150 (they were measured on RDNA2 and, for the vector part, on this GPU before; the `s_buffer_load` bound and the -`idxen offen` and offset-only soffset forms are new on gfx1150). The one difference is `v_pack_b32_f16` quieting -signaling NaNs (only signaling NaN halves are not judged; a quiet NaN is compared). The default translator path of `mem` ran on the Radeon 880M (`VK_LOADER_DRIVERS_SELECT=*amd*`, `vk_compute_test` built with g++ as in the lab script): `--family mem --programs 200 --seed 1` gave 400 of 400 programs (native wave64 and wave32) matching the model, 0 not translated, 0 harness errors, so the translator agrees with the model on the OOB_SELECT, straddle, `s_load` and `s_buffer_load` rules there. On the RTX 5070 `vk_compute_test` loses the device (-4) for this and for the unchanged generator of `main`, so use the AMD device. - -### Packed and 16-bit integer VALU (`tools/pk16_diff.py`) - -`valu_fuzz.py --family f16` runs the 16-bit shifts, `v_add/sub_nc_u16`, `v_mul_lo_u16` and the 16-bit min/max on -the GPU with VGPR sources. `tools/pk16_diff.py` adds the packed integer ops (`v_pk_add/sub_u16/i16`, -`v_pk_mul_lo_u16`, `v_pk_min/max_u16/i16`, `v_pk_mad_u16/i16` and the packed shifts) with `op_sel`, `op_sel_hi` and -`clamp`, and the 16-bit VOP3 ops (`v_add/sub_nc_i16`, `v_min3/max3/med3_u16/i16`, `v_mad_u16/i16` next to the ones -above) with `op_sel` on every source and on the destination half and `clamp`. Sources are VGPRs, SGPRs, integer and -float inline constants and literals within the constant-bus limits. It runs one lane through -`tests/semantic/spirv_mini_interp.py` against its own ISA model, with the shrinking, skips and exit codes of -`salu_diff.py`. A constant whose high half a packed add/sub/mul/min/max/mad reads is left out unless `--known` (the -translator rejects it; #2224 changes that). - -Measured on an RDNA2 iGPU (gfx1036) with `--oracle hw`: 2,300 programs, the `--known` forms included, match the -model. A 16-bit VOP3 op keeps the other half of its destination. A constant source is its 32-bit value split like a -register: `-16` is `0xfff0`/`0xffff`, `1.0` is `0x0000`/`0x3f80` (f32 bits, unlike the f16 ops), and a literal of a -16-bit VOP3 op has 16 bits (`0xffff` with `op_sel` reads 0). The VOP2-named 16-bit ops (`v_mul_lo_u16`, -`v_min/max_*16`, the shifts) only have a VOP3 encoding on GFX10, and the generator writes them with `_e64`, because -without encoding bytes the translator reads a bare mnemonic as the VOP2 write that zeroes the high half. For the same -reason, rules that depend on the encoding bytes, such as a literal's 12-byte VOP3 encoding (SHADER-208), are out of -its reach. - -``` -python -I tools/pk16_diff.py --programs 3000 --seed 11 --max-ops 8 -python -I tools/pk16_diff.py --oracle hw --programs 500 --seed 1 -python -I tests/test_pk16_diff.py -``` - -### Wave and cross-lane ops on the GPU (`tools/crosslane_fuzz.py`, FUZZ-7) - -Cross-lane ops read other lanes, so like FUZZ-6 this runs on the GPU and not in the one-lane interpreter. -Each seeded program is one compute group of a wave32 or wave64 program. Group sizes cover one full wave, two or -three waves, and a partial last wave (20, 50, 40 or 100 threads). The program runs 24 to 28 random ops, then -every thread stores its six data VGPRs and eight data SGPRs, so each half of a wave reports its own copy of -every scalar. `vk_compute_test` reads them back with `VKC_OUT_WORDS` / `VKC_DUMP`. - -- **Instructions.** `v_readlane_b32` and `v_writelane_b32` (constant and SGPR lane selects; in wave32 also - selects of 32 and up), `v_readfirstlane_b32`, `v_cmp` into VCC or an SGPR mask, `v_cmpx`, `s_and_saveexec` - and its restore, nested up to three deep, constant EXEC halves, `s_bcnt1`/`s_bcnt0`/`s_ff1` of a mask or - EXEC, `v_mbcnt_lo/hi` on a mask, EXEC or plain data, `v_cndmask` on a mask, `s_and/or/xor/andn2` of masks, - `v_permlane16_b32` / `v_permlanex16_b32`, and forward `s_cbranch_execz/vccz/vccnz` over one to four of these. - With `--dpp`: a DPP16 or DPP8 src0 on `v_mov`/`v_not`/`v_add_nc_u32`/`v_xor`, with every DPP16 control, - `row_mask`, `bank_mask`, `bound_ctrl` and `fi`. Masks read as plain data (`v_mov_b32 v, s_mask`) belong to - #293 and are left out with `--no-maskdata`. -- **`--ext` (wave64 programs only).** Adds the ops the list above leaves out: carries (`v_add_co`, `v_sub_co`, - `v_subrev_co_u32` and the `_ci` forms) through SGPR pairs and VCC; `ds_bpermute_b32`, `ds_permute_b32` (address - permutations and colliding addresses) and `ds_swizzle_b32` (`QUAD_PERM`, `BITMASK_PERM`, `SWAP`, `REVERSE`, - `BROADCAST`); `v_readlane`/`v_writelane` with an SGPR lane select of 64 and up; `s_bcnt0/1` and `s_ff0/1` of a - mask, `s_and/or/xor/andn2_b64`, the ten `s_*_saveexec_b64` forms and `s_andn1/andn2_wrexec_b64`, `s_wqm_b64`, - `s_cmp_eq/lg_u64` and `s_bitcmp0/1_b64`, each followed by an `s_cselect_b32` so that its SCC is stored; - `s_cselect_b64` between masks, `s_mov_b64 exec, mask`, `s_bfm_b64` into a mask or EXEC; and a loop in LLVM's - SI_LOOP shape (per-lane trip counts of 1 to 8, a break mask, `s_andn2_b64 exec`, `s_cbranch_execnz` back to the - head) around one to four of the other ops. Without the flag, and for wave32 programs with it, a seed gives the - same program as before. The model of every op was checked on an AMD Radeon RDNA2 iGPU (gfx1036, Ryzen 9 - 9950X3D, raw wave64 kernels): `--ext --dpp --wave 64 --oracle hw --programs 100 --seed 21` matches 100/100, - with groups of one to three waves and partial waves. What that run settled where the ISA guide is terse: the - three DS ops need `s_waitcnt lgkmcnt(0)` before their result is used (without it a later VALU write to the same - VGPR is overwritten when the result arrives; the generator emits the wait); `ds_bpermute_b32` and - `ds_permute_b32` stay inside the lane's 32-lane half; with several senders `ds_permute_b32` keeps the highest - lane's value; an EXEC-off source reads 0 in `ds_bpermute_b32` and in `ds_swizzle_b32`. The translator matches - the same 100 programs on that GPU both natively (64-wide subgroup, `--w64-native`) and with - `--wave64-emulate`, apart from 15 that reach a known open case and are filed `hyp_only`: an EXEC-off - `v_permlane` source (#580) or `ds_swizzle_b32` source (#2780, tagged like the permlane case until it lands). An - RTX 5080 (driver 616.92) gives 46 matches and 14 `hyp_only` of 60 emulated programs (`--seed 23`). Not - generated: 32-bit ops on one half of a mask or of EXEC (#663, #3225) and carries with a DPP source (#3553). -- **Reference.** A 64-lane model in the same file, written from the ISA (rules in its docstring). Its unit - test, `tests/test_crosslane_fuzz.py`, needs no GPU. -- **Defined behaviour only.** Lane selects, permlane and DPP never read a lane missing from a partial wave. - EXEC constants only enable lanes that exist. Every mask register is zero-initialised, as compiled code does, - so a branch that skips the `v_cmp` writing a mask leaves a defined mask after the join. -- **Hypotheses are reported apart.** `v_permlane16/x16` with op_sel FI = 0 reading a lane that is off in - EXEC is modelled as the DPP "invalid source" case (vD kept). That is now measured, with the same result on both: - @aslan2142 on RDNA2 and @AlxcBTW on RDNA3.5 (#374). FI = 1 returns the source lane's value, FI = 0 leaves the - destination unwritten and FI = 0 with BOUND_CTRL gives 0; #580 (SHADER-74) makes the translator do that. The - fuzzer's docstring (`tools/crosslane_fuzz.py`, since #750) already says it was measured, but `op_permlane` still - tags the case `hyp` because the translator models it only with #580, so a program that hits it and mismatches - is filed as `hyp_only` instead of `mismatch` (one that matches still counts as `match`). The model (vD kept) - already matches the measurement; dropping the tag once #580 lands is a follow-up. - `--permlane-fetch-inactive` models FI = 1 instead. -- **Modes.** Wave32 runs natively. Wave64 runs with `--wave64-emulate`; `--w64-native` adds the plain build, - which on a 32-wide subgroup is the documented cross-half approximation and is expected to mismatch. -- **Hardware oracle (optional).** `--oracle hw` (or `translator,hw`) also runs every program natively on the AMD - GPU through `tools/hw_oracle/` (setup: see the FUZZ-4 section above) and compares all stored words with the model; - without the tools it prints `hardware oracle unavailable: ...` and exits 77. It tests the **model**, in wave32 - and in native wave64 (`.amdhsa_wavefront_size32 0`, wave64 code objects are assembled with - `-mwavefrontsize64`), with the program's real group size (partial waves, two or more waves) and its EXEC setup, - one thread per lane, each storing its 14 words with `global_store_b32`. Branch placeholders become labels. After - every instruction the native kernel has `s_nop 7`, because the model has no hazards and the real unit wants wait - states after some VALU writes of SGPRs, VCC and EXEC; `--no-hw-guard` leaves them out (a 4,000-program run - without them matched too, so the generator does not reach a hazard on this GPU). With `translator,hw`, a program - where the hardware differs from the model also prints what the translator did with it. - `hyp_confirmed` counts programs with a hypothesis op that matched on the hardware, split into `hyp_permlane` - (FI = 0 source lane off in EXEC keeps vD; the claim comes from the oracle measurements in #374 on RDNA2 and - RDNA3.5, and #580 models it in the translator) and `hyp_dpp` (DPP8 source lane off in EXEC with fi = 0 reads 0; - the claim is #238's, and nothing measured it before this oracle). On the hardware path a hypothesis that fails - is a falsified claim: it counts as a mismatch (exit 1) and in `hyp_only`, and `--minimize` marks the - hypothesis ops that remain. A startup probe checks that a wave64 kernel runs as wave64 (lane 32 reads 32) and a - wave32 kernel as wave32, so a runtime that ignored the wave size would fail loudly. `--keep` writes the kernel - body that ran. - GFX11 differences looked at, none of which changes a result for what the generator emits: the assembler takes - the same `row_share`/`row_xmask`/`dpp8`/`fi`/`bound_ctrl:1` and `v_permlane16/x16` spellings for gfx1030 and - gfx1150; `row_newbcast`, `row_bcast` and `wave_shl` exist on neither (not generated); `v_cmpx_*_e32` writes EXEC - only on both (the generator never uses the `_e64` form, whose GFX10 SDST the assembler no longer takes either); - `v_mbcnt_*` is VOP3-only on both; `s_ff1_i32_*` is the GFX10 name of GFX11's `s_ctz_i32_*` (an accepted alias); - `v_readlane_b32` with a lane select of 32 and up in wave32 uses select bits [4:0] on gfx1150 too. Nothing - needed a skip, so `hw_skip_reason` returns none and the only skips are assembler rejections (none seen). That - was gfx1150. - On RDNA2 (gfx1036, through the Linux launcher of the FUZZ-4 section): 24,000 programs (seeds 1 to 6) match in - both wave sizes, 12,000 each, 6,586 of them `hyp_permlane`; with `--dpp` (seeds 1 and 2) 8,000 more match, - 972 of them `hyp_dpp`. As a control, `--permlane-fetch-inactive` there mismatches in 239 of 1,000 programs. A - GFX10 assembler has no `global_store_b32`, so `asm.raw_kernel_text` puts the GFX10 name (`global_store_dword`) - back for `gfx10xx`; nothing else the generator emits needed a change. - On a discrete RDNA2 card (RX 6700 XT, gfx1031, Windows, Adrenalin 26.8.1, through the HIP DLL of the driver; - BUILD-162): with `--dpp`, seeds 1 to 8, 1,000 programs each (500 per wave size), all 8,000 match, 984 of them - `hyp_dpp` and 1,964 `hyp_permlane`. - On RDNA4 (RX 9070 XT, gfx1201, Windows, Adrenalin 26.11.2, `amdhip64_7.dll`, AMD clang 23.0.0git from the - `rocm-sdk` wheels): the same eight runs, all 8,000 match, with the same 984 `hyp_dpp` and 1,964 `hyp_permlane` - programs. gfx1201 is not RDNA2: the match supports the model and settles nothing about the console. -- **DPP sweep (`--dpp-sweep`, BUILD-162).** The random `--dpp` programs run full waves, four ops and mostly - `row_mask`/`bank_mask` 0xF, so a rare control or mask pair can go untested for many seeds. `--dpp-sweep` replaces - the random programs with one short program per case: an EXEC write, then one DPP op. It covers every DPP16 control - (335: 256 `quad_perm`, `row_shl/shr/ror` 1 to 15, both mirrors, `row_share` and `row_xmask` 0 to 15) × `bound_ctrl` - × `fi` × three EXEC patterns (all lanes; every other lane, so each source is invalid in some lanes; and bank 0 off - in some rows, so whole 4-lane groups read inactive sources). It also covers all 256 `row_mask`/`bank_mask` pairs on - `row_shr:1`, `quad_perm:[1,0,3,2]` and `row_share:5`, × `bound_ctrl`, under two EXEC patterns. And it covers 19 - DPP8 select sets (identity, reverse, swaps, the 8 broadcasts and the 7 rotations) × `fi` × the three EXEC patterns. - That makes 7,206 cases per wave size. The op rotates through `v_mov`/`v_not`/`v_add_nc_u32`/`v_xor`, and every - other group of four writes vD in place (`vD = src0`, as reductions do), so the model has to read every source - before it writes. Each case carries its family label, and failures print it. The run ends with a table of cases - and failures per family. The random draws of `--dpp` are unchanged: a test pins the program text of seed 77, and - 800 programs from before and after the change are identical. - On the RX 6700 XT (gfx1031), `--dpp-sweep --oracle hw --wave both`: 14,412 cases, match 14,412, mismatch 0 in - every family, 40 of them `hyp_dpp` (DPP8 with an inactive source and fi = 0 reads 0). This is the first measured - check of every DPP16 control and mask pair on RDNA2 hardware, and it confirms the rules in the model's docstring - (and `docs/design.md`): `bound_ctrl` with an invalid source, `fi` on DPP16 and DPP8 inactive sources, an - unwritten lane keeping the old vD for non-mov ops, and `row_mask`/`bank_mask` in both wave sizes. In the same - run (`--oracle translator,hw`), the translator matches all of them as well: 7,206 wave32 native and 7,206 wave64 - `--wave64-emulate`, with 0 rejected and 0 harness errors. One `vk_compute_test` runs per case, so the translator - side takes about 90 minutes there; the hardware side takes about one. - On the RX 9070 XT (gfx1201, the setup above), `--dpp-sweep --oracle hw --wave both`: 14,412 cases, match 14,412, - mismatch 0 in every family, 40 of them `hyp_dpp`, in half a minute. The same DPP rules hold on RDNA4; the - translator side was not run there. - First results (Radeon 880M, driver 26.11.2): 24,000 programs on the hardware, half wave32 and half native - wave64, seeds 11 to 16 (4,000 programs each), with and without `--dpp`, 12 to 60 ops, with and without - `--no-maskdata` and `--no-hw-guard`: match 24,000, mismatch 0, hyp_only 0, rejected 0. 7,652 of them contained - a permlane with an inactive source lane or a DPP8 with an inactive source lane (`hyp_confirmed`: 3,567 in - wave32, 4,085 in wave64) and every one matched, so both hypotheses hold on gfx1150 in both wave sizes. RDNA2 - itself is not measured by this run. - Against the translator (`translator,hw`, 200 programs, seed 7): every translator mismatch of this build had - masks read as plain data (#293); with `--no-maskdata` it has 0 mismatches and only the known permlane - `hyp_only` cases (#580). The hardware agrees with the model on both, so those are translator gaps, not model - errors. -- **Reports.** The thread, wave, lane and register of the first differences. `--minimize` drops ops while the - mismatch persists, and `--keep DIR` saves the programs. `--translator PATH` tests another checkout's - translator (for example an open pull request). - -First results on an RTX 4090 (subgroup 32, driver 621.14): - -- **SHADER-52 (#407).** In wave32, `v_readlane`/`v_writelane` masked the lane select with 63, not 31. 23 of - 100 wave32 programs failed, each one minimized to a `v_writelane` with a lane select of 32 or more. -- **Two DPP bugs in #238** (SHADER-23, posted there). Non-mov DPP ops wrote `op(old vD, src1)` in lanes that - should be left unwritten (invalid source without `bound_ctrl`, or a lane off in `row_mask`/`bank_mask`), and - DPP16 ignored `fi:1`. Each was confirmed with a hand-written program. -- **Everything else matches.** On `main`, 1,000 programs (`--seed 8 --ops 28 --no-maskdata --no-w32-hi-lanes`, 500 wave32 native and 500 wave64 emulated) give 0 mismatches. 297 of them are `hyp_only` (permlane with FI = 0 and an inactive source), and with `--permlane-fetch-inactive` all 1,000 match. Native wave64 on the 32-wide card mismatches as documented: `s_bcnt1` of EXEC counts one half, and a `v_readlane` from the other half wraps. -- **Native wave64 on a 64-wide device: one driver fault (SHADER-705).** With `--wave 64 --w64-native --dpp --no-maskdata - --seed 82001 --programs 600`, AMD's Windows driver on a gfx1036 integrated GPU (`32.0.21045.16010` and - `32.0.21042.62`, two machines; found by @Vonsek, reduced by @zzEmmazz) gives one native mismatch: - `cs_xl64_8200346406` (index 403) differs in 96 words, lanes 32-63 of each wave on the first driver and lanes 0-15 - and 32-47 on the second. The emulated build matches there. - - **The same run under RADV** (Mesa 26.3.1, Linux) on another gfx1036 (a Ryzen 9 7950X3D's) and on an RX 7900 XTX: - 454 match, 0 mismatch, 146 `hyp_only`, natively and emulated. The program alone, and the 12 instructions it was - reduced to, are exact natively on both devices: as 192 threads and as one 64-thread group, with the driver's - default subgroup size and with `vk_compute_test --require-wave64`. - - **Hardware:** `--oracle hw` on that gfx1036 matches the model in all 600 programs. - - **So the native wave64 SPIR-V is right and that driver is not.** The wrong instruction is a `v_permlanex16_b32` - that reads a register a DPP op with a partial `row_mask` has just written; equivalent rewrites of the shuffle - index only move the wrong lanes (@zzEmmazz). - - **In the game's shaders that shape does not occur.** Of 26,503, 2,293 use `v_permlanex16_b32` and 27 a DPP op with - a partial `row_mask`. 6 have both, all wave32 compute, and in none does the shuffle read a register that such a - DPP op wrote last (program order, branches ignored). - - **Not checked:** the driver's generated code, so the fault is not located and other shapes may trigger it; the - Windows driver with `--require-wave64` (the fuzzer's native run does not request a subgroup size); AMD's - Windows driver on RDNA3 or newer. - - `--wave64-emulate auto` stays native on that driver, because it can crash on emulated LDS code (#857). -- **Closed question (#374):** what hardware does for permlane with FI = 0 was measured on RDNA2 and RDNA3.5 (see above). - -### Wave and cross-lane ops on the CPU (`tools/wave_diff.py`) - -The same family as `crosslane_fuzz.py`, without a GPU or llvm-mc, so it can run wherever the translator tests run. -The reference is `cf_ref.WaveMachine` (FUZZ-8) extended in `wave_diff.WaveRef` with the instructions it leaves out: -`v_readlane`, `v_readfirstlane`, `v_writelane`, `ds_bpermute_b32` (per 32-lane half, an inactive source reads 0), -`v_permlane16/x16` (FI = 0 with an inactive source leaves vD, as measured above), `s_bcnt0/1` and `s_ff0/1` -(`_b32`/`_b64`, constants sign-extended to the operand width) and `s_not`. Each rule is written next to its instruction. -The translated side is `spirv_mini_interp.run_workgroup`, every lane of the wave in one subgroup of the wave's size, and -all 12 dwords every lane stores are compared (four VGPRs, two masks, VCC and the final EXEC as each lane's bit, four -scalars). Programs are straight-line wave32 and wave64 compute under random EXEC (`v_cmpx`, saveexec, constants). - -By default the generator keeps lane masks and 64-bit data in separate registers and only issues `v_permlane` with every -lane on, so a default run is a regression check. Two known gaps on `main` are opt-in: `--masks-as-data` (#210, #293) and -`--permlane-partial` (SHADER-74, #580). - -Results (`--max-ops 16`, half wave32, half wave64, nothing skipped): it found `s_and_b32 exec_lo, exec_lo, K` in -wave32 and `s_ff0_i32_b64` of a negative constant (#1409), both fixed on `main` since; on `main` 7b7d73f8, 600 of -600 match (seeds 401 to 403). - -For one case from a default wave32 run, `tools/wave_trace.py` writes a self-contained HTML report. Use the seed, -zero-based case index, and `--max-ops` from `wave_diff.py --wave 32`. The report compares all 32 lanes after -initialization and after each subsequent instruction. Select a register or jump to the first observed mismatch. - -```powershell -python -I tools/wave_trace.py --seed 1 --case 0 --max-ops 12 --out wave.html -``` - -Each checkpoint re-translates a shorter program with the same observation epilogue, so liveness and lowering can -change between checkpoints. The first mismatch identifies an observed prefix. The final checkpoint runs the full -original case. The tool uses synthetic programs and the CPU interpreters above. It writes a report for mismatches -and unavailable checkpoints as well. Exit 1 means a mismatch was observed, 2 means the comparison was incomplete -or the command failed, and 0 means all checkpoints matched. - -### 32-bit float VALU on the GPU (`tools/f32_fuzz.py`, FUZZ-3) - -`--oracle hw` (or `translator,hw`) runs the same seeded VOP1/VOP2/VOP3 f32 programs natively on the AMD GPU and judges -the hardware's `v8` and VCC against `F32Model` bit for bit (NaN matches any NaN; an f16 NaN in a `v_cvt_f16_f32` / -`v_cvt_pkrtz_f16_f32` half too). Setup is the one in "Hardware oracle" above; without it the run prints -`hardware oracle unavailable: ...` and exits 77. It tests the **model**, on wave32 with one lane; with `translator,hw` -a hardware mismatch also prints what the translated SPIR-V did. - -``` -python -I tools/f32_fuzz.py --oracle hw --programs 5000 --seed 1 # table + informational hardware tables -python -I tools/f32_fuzz.py --oracle hw --negative-control # wrong models must be caught -python -I tools/f32_fuzz.py --oracle hw --perturb mul_rtz --programs 500 # one wrong model, mismatches must appear -``` - -- **Float MODE.** An assembled kernel's descriptor starts with IEEE 1, DX10_CLAMP 1, f32 denormals flushed - (`.amdhsa_float_denorm_mode_32 0`), f16/f64 denormals kept (3), round to nearest (MODE `0x3c0`, read back with - `s_getreg_b32`). The primary mode, `flush`, is the state inferred for the game's shaders (IEEE off, f32 denormals - flushed, DX10_CLAMP on: MODE `0x1c0`). Three more are run for what the model does not judge: `keep` (f32 denormals - kept, `0x1f0`), `no_dx10` (`0x0c0`), `ieee` (`0x3c0`). The run reads MODE back in a kernel for each and fails if a - directive did not take. Rounding is always to nearest even. On gfx1170+ (GFX11.7, GFX12) IEEE and DX10_CLAMP are - fixed and AMD clang rejects `.amdhsa_ieee_mode` / `.amdhsa_dx10_clamp` ("directive unsupported on gfx1170+"), so - `asm.mode_skip_reason` reports a kernel that sets either as not runnable there and the runner never assembles it; - the MODE probe then fails naming that reason instead of a whole chunk failing to assemble (FUZZ-43). -- **GFX11 against GFX10, handled explicitly** (`tools/hw_oracle/asm.py`, checked by assembling every opcode for gfx1013, - gfx1010, gfx1030, gfx1100, gfx1150 and gfx1200): - - *Skipped, never substituted:* `v_mad_f32`, `v_mac_f32`, `v_madak_f32` and `v_mad_legacy_f32` exist on GFX10.1 only - (gfx1010/1011/1013, the console's family); gfx1030 and every GFX11 part reject them. The fused replacements - (`v_fma_f32`, `v_fmac_f32`, `v_fmaak_f32`, `v_fma_dx9_zero_f32`) round once, so they are different instructions. The - unfused mad semantics (and SHADER-118's flush) therefore stay unmeasured: no RDNA2 desktop part and no GFX11 part has - them. Also not generated: `v_madmk_f32` (GFX10.1 only, like the mad opcodes), `v_min_legacy_f32` (in no GFX10 or GFX11 - part: llvm-mc rejects it for gfx1010, gfx1013, gfx1030 and gfx1150), `v_fma_legacy_f32`/`v_fmac_legacy_f32` (new in - GFX10.3, not in gfx1013). - - *Renamed, run:* `v_mul_legacy_f32` is `v_mul_dx9_zero_f32` in GFX11 (the DX9 rule `0 * x = 0`, inf and NaN included, - held in every program) and `v_cvt_pkrtz_f16_f32` is `v_cvt_pk_rtz_f16_f32`; the assembler takes the old spelling. - - *Same, with a syntax change:* GFX11's assembler wants `clamp` before `mul:N`/`div:2`; the native kernels print them in - that order (the same bits). Opcode numbers differ between the families (`v_cmp_class_f32_e32` is `7d10` on gfx1013 and - `7cfc` on gfx1150); only mnemonics are shared. omod and clamp exist in VOP3 on both; no op_sel is used for f32. - The transcendental unit is separate on GFX11, so a `s_nop 7` follows the instruction in the native kernel - (`--no-hw-guard` leaves it out). - - *Not covered:* wave64 (the f32 ALU does not depend on it), `v_fma_mix*` and f16 arithmetic. The translated f64 VALU - forms have a separate CPU differential harness in `tools/f64_diff.py` (below). -- **Programs.** The seeded random ones, plus `--probes N` (default 12) per op and kind: denormal operand, denormal - result, NaN payloads, clamp of NaN/-0, invalid operations (inf - inf, 0 * inf, ...), and `cancel` (`z = -round(x * y)`, - which separates fused from unfused). `v_min/max/min3/max3/med3_f32` are in the table for the hardware only, with the - RDNA2 rules measured in #634. -- **Judged / not judged.** A program is *match* or *mismatch* where the model has an answer. Where it declines (denormal - operand or result, clamp of NaN or -0, cube of NaN) the hardware still runs and is recorded in the informational tables, - also under the other three modes. A *known deviation* is hardware behaviour already analysed and written down as a model - alternative (`KNOWN_DEVIATIONS`); the hardware words must equal the alternative exactly, anything else is a mismatch. - -Results (Radeon 880M, gfx1150, driver 26.11.2, AMD clang 23.0.0git), seeds 1 to 6, 5,000 random programs + 24 probes per -op and kind each, 46,967 programs in all: **30,577 match, 0 mismatch, 57 known deviation**, 5,417 skipped for GFX11, -5,903 denormal, 5,013 other not judged (clamp of NaN or -0, cube of NaN). "Match" accepts any NaN for any NaN: payload, sign and quiet bit are in the informational tables, not judged. Seed 1 by family: - -| Family | Programs | Match | Mismatch | Known dev | GFX11 skip | Denormal | Other | -|---|---|---|---|---|---|---|---| -| add / sub / mul | 921 | 631 | 0 | 0 | 0 | 176 | 114 | -| DX9 legacy mul / mad | 453 | 133 | 0 | 0 | 239 | 51 | 30 | -| mad / mac / madak | 698 | 0 | 0 | 0 | 698 | 0 | 0 | -| fma / fmac / fmaak | 700 | 509 | 0 | 0 | 0 | 132 | 59 | -| int to f32 convert | 708 | 708 | 0 | 0 | 0 | 0 | 0 | -| f16 convert | 478 | 383 | 0 | 0 | 0 | 90 | 5 | -| `v_cvt_pk_u8_f32` | 183 | 130 | 0 | 0 | 0 | 53 | 0 | -| floor / ceil / trunc / rndne | 795 | 582 | 0 | 5 | 0 | 96 | 112 | -| rcp / rsq / sqrt / exp / log | 956 | 704 | 0 | 0 | 0 | 119 | 133 | -| cube | 786 | 435 | 0 | 1 | 0 | 104 | 246 | -| `v_cmp_class_f32` | 171 | 147 | 0 | 0 | 0 | 24 | 0 | -| min / max / med3 (hardware only) | 989 | 732 | 0 | 1 | 0 | 128 | 128 | - -Negative control: `--negative-control` re-judges the same hardware words with a deliberately wrong model for six ops -(`v_add_f32` low bit flipped, `v_mul_f32` rounding toward zero, `v_fma_f32` unfused, `v_mul_legacy_f32` as IEEE multiply, -`v_rndne_f32` as floor, `v_min_f32` NaN rule changed); every one produced mismatches (1 to 112 per run; the `v_fma_f32` one only after the `cancel` probes were added, a plain random sweep missed it in seed 2; -the legacy multiply is the weakest, 1 to 4 in seeds 1 to 6, because `0 * inf` is rare in random programs; the `zero_inf` probes (a zero against inf, NaN or a normal number, DX9 multiply) were added afterwards and catch it at small sizes). The `cancel` probes (seeds 2, 7, 8) give 72 of 72 fused-FMA matches. Seeds 1 to 6 ran without them. - -On RDNA2 (gfx1036, through the Linux launcher of the FUZZ-4 section, the same seeds 1 to 6): 38,858 programs, -**28,671 match, 0 mismatch, 56 known deviation**, 4,224 skipped (the four mad opcodes are GFX10.1-only), 3,097 -denormal, 2,810 other not judged. The four MODE settings read back in the kernels as `0x1c0`, `0x1f0`, `0xc0` and -`0x3c0`, so the float mode of the kernel descriptor reaches the hardware through that launcher as well. -`--negative-control` catches all six wrong models there (3 to 25 mismatches each). - -The same seeds through the Windows HIP launcher (`hw_oracle.c`) on the integrated GPU of a Ryzen 7 9800X3D (gfx1036; -Windows 10 22H2, AMD driver 32.0.13036.4, `amdhip64_6.dll`, AMD clang 23.0.0git from rocm-sdk-core 10.0.0, main at -41f44826) give the same counts in every column: 38,858 programs, **28,671 match, 0 mismatch, 56 known deviation** -(all `omod_neg_zero`), 4,224 skipped, 3,097 denormal, 2,810 other. `--negative-control` again catches all six (3 to -25 mismatches). Two launchers on two machines and two operating systems agree on the hardware words. - -`v_rcp_iflag_f32` (SHADER-136; added to the rcp / rsq / sqrt / exp / log family after the run above, so it is not in -its counts) on the same gfx1036 through the Windows launcher, `--ops v_rcp_iflag_f32 --programs 1000 --probes 24`, -seeds 1 to 6: 6,552 programs, **5,971 match, 0 mismatch, 35 known deviation** (`omod_neg_zero`), 279 denormal, 267 -other. It shares `v_rcp_f32`'s model, and the clamp and omod bits behave as on the other ops (summed over the six -seeds, per MODE setting flush / keep / no_dx10 / ieee): clamp makes a -0 result +0 in every mode (98 each) and a NaN -result +0 except with DX10_CLAMP off, where the NaN passes (169); omod is applied with IEEE off, including with f32 -denormals kept (461 each; like the other transcendental ops), and ignored with IEEE on (461); a -0 result becomes +0 -under omod (35 each, none with IEEE on); a signalling NaN passes unchanged with IEEE off and is quieted with IEEE on -(59); denormal operands read as zero and denormal results flush in every mode. - -A discrete RDNA2 part (SHADER-353): an RX 6700 XT (gfx1031; AMD Windows driver 26.11.2, Vulkan 1.4.315, Windows 11 -10.0.26200, `amdhip64_6.dll`, AMD clang 24.0.0git from rocm-sdk-core 10.2.0, MinGW gcc as the host compiler, main at -4eb6155d with this change), `--oracle hw --programs 5000`, seeds 1 to 6: 39,101 programs, **28,856 match, 0 mismatch, 66 known -deviation** (all `omod_neg_zero`), 4,056 skipped (the four GFX10.1-only mad opcodes), 3,201 denormal, 2,922 other. More -programs than on gfx1036, probably because `v_rcp_iflag_f32` and its probes are in the table now. MODE read back as `0x1c0`, `0x1f0`, `0xc0` and -`0x3c0`; `--negative-control` catches all six wrong models (5 to 23 mismatches). The omod table, summed over the six -seeds (flush / keep / no_dx10 / ieee), answers what the gfx1150 row of `docs/design.md` left open for RDNA2: - -| omod, where it changes the result | flush | keep | no_dx10 | ieee | -|---|---|---|---|---| -| applied | 2,680 | 869 | 2,680 | 0 | -| applied, but a -0 result becomes +0 | 66 | 22 | 66 | 0 | -| ignored | 0 | 1,811 | 0 | 2,650 | -| -0 result kept (applied or ignored, same word) | 0 | 44 | 0 | 65 | -| other | 0 | 0 | 0 | 31 | - -With denormals kept, the 869 + 22 applied are all `v_rcp/rcp_iflag/rsq/sqrt/exp/log_f32` and the four cube ops -(`OMOD_IGNORES_DENORM_MODE`), and the 1,811 ignored are all ALU ops. The 31 "other" with IEEE on are `v_min/max/min3/ -max3/med3_f32` programs with a signalling NaN source, where the IEEE-off min/max rules of #634 do not apply; the omod -is not what differs there. Before SHADER-353, `omod_label` counted a -0 result that the omod cannot change as "applied", -which put 65 "applied" in the ieee column although no unambiguous program applied it there. - -What the hardware answered where the model does not judge (gfx1150; the RDNA2 run above agrees where it is cited): - -- **No model error found.** The model was right wherever it had an answer, in 30,577 programs; the min/max/med3 - rules measured on RDNA2 in #634 (one NaN gives the other operand, both NaN give src0, -0 < +0, med3 with a NaN is min3) - also hold on gfx1150 for quiet and signalling NaNs with IEEE off. -- **On gfx1150 output modifiers turn a -0 result into +0** (`mul:2`, `mul:4`, `div:2`; 57 programs, every seed; a flushed - denormal result, which is a -0, too). RDNA2 does the same: 56 programs in the same seeds on gfx1036. LLVM notes that omod mishandles signed zeros - (`SIFoldOperands.cpp`) and D30209 describes -0 being forced to +0 before the modifier, which points the same way. The - model and the translator both keep -0, so on that evidence the translator likely differs from the hardware - (`translator,hw`: all 6 deviations of 2,000 programs are "matches the model, so it shares the model's answer"). Not - fixed in this change; the finding is posted in the coordination issue (see #1006). A deviation is only accepted where - the omod was active (not with IEEE on, not for ALU ops with f32 denormals kept). -- **omod only acts with MODE.IEEE = 0**, and for the ALU ops only with f32 denormals flushed: with `keep` the omod of - add/mul/fma/min/max/cvt/rounding ops is ignored; the transcendental ops and the cube ops still apply it. LLVM says the - same for both conditions (`SIFoldOperands.cpp`: "omod is ignored by hardware if IEEE bit is enabled"; "If output - denormals are enabled, omod is ignored"). This supports - the corpus inference (omod on 102,365 float instructions, so IEEE off and f32 denormals flushed in the game's shaders). -- **f32 denormals (SHADER-35's MODE question).** With `denorm_mode_32 = 0` a denormal operand is read as a zero of its sign - and a denormal result is written as a zero of its sign, for add/sub/mul/fma/fmac/fmaak, min/max/med3, rounding ops and - DX9 mul; with `3` they are exact. `v_rcp/rsq/sqrt/exp/log_f32` flush in both modes (as #634 measured on RDNA2). - `v_cmp_class_f32` classifies a denormal as a denormal in both. `v_cubesc/cubetc` pass a denormal operand through. -- **clamp.** With DX10_CLAMP 1, clamp of a NaN gives +0; with 0 the NaN passes through. clamp of -0 gives +0 in every mode. - The model still declines both. -- **NaN payloads.** With IEEE off a signalling NaN passes through add/mul/fma/rounding/transcendental ops unchanged - (payload and sign); with IEEE on it is quieted (bit 22 set). With several NaN operands the first (lowest source) wins - in add/mul/fma/fmaak/fmac; for min/max the rule above applies. `v_sub_f32` returns the NaN of src1 with its sign flipped - (it computes src0 + -src1). Invalid operations (inf - inf, 0 * inf, sqrt/rsq/log of a negative) give `0xffc00000` in every - mode and op, never `0x7fc00000`. `v_cvt_f16_f32` and `v_cvt_pkrtz_f16_f32` turn a NaN into an f16 NaN with the top 10 - payload bits and the quiet bit set (not the canonical `0x7e00` the model writes; payload not judged, quietness is). - `v_cvt_f32_f16` keeps the f16 payload shifted left by 13 and does not quiet it (the model agrees). - -### f32 misc ops and float compares (`tools/fmisc_diff.py`) - -`tools/f32_fuzz.py` generates the f32 arithmetic. `tools/fmisc_diff.py` covers the f32 ops it leaves out: -`v_fract_f32`, `v_frexp_mant_f32`, `v_frexp_exp_i32_f32`, `v_ldexp_f32`, `v_cvt_u32_f32`, `v_cvt_i32_f32`, -`v_cvt_off_f32_i4` and `v_fmamk_f32`. It also covers the 16 `v_cmp_*_f32` conditions (e32 into VCC, e64 into an SGPR -mask or VCC) and `v_cmp_class_f32` e64, each read back with `v_cndmask_b32_e64`. Programs use VOP3 `neg`/`abs`, -`mul:2`/`mul:4`/`div:2` and `clamp`, with VGPR, SGPR, inline-constant and literal sources within the constant-bus -limits. It runs one lane through `tests/semantic/spirv_mini_interp.py` against its own exact-rational ISA model, with -the shrinking, skips and exit codes of `salu_diff.py`. Any NaN matches any NaN. It does not judge denormal operands -or results, a computed NaN read as an integer, the clamp of a NaN or an output modifier that gives a zero: those -programs are counted as skips with the reason. - -`--oracle hw` runs the kernels under the MODE inferred for the game's shaders (IEEE off, f32 denormals flushed). With -the assembler's compute default (IEEE on) the hardware ignores `omod`: `v_fract_f32_e64 v4, -v16 mul:2` with v16 = 0.5 -gives 0.5. On an RDNA2 iGPU (gfx1036), 1,800 programs gave 1,563 judged and 0 mismatches, so the model's rules hold -there. Those rules cover the `0x3f7fffff` cap of `v_fract_f32`, `fract(-0) = +0`, `frexp` of ±inf/NaN/±0, `ldexp` -overflow and underflow, saturating conversions, one rounding in `v_fmamk_f32`, unordered compares and the class bits. -Modifiers do not change whether a signalling NaN is signalling: `v_cmp_class_f32` with `-v`, `|v|` or `-|v|` on -`0x7f800001` still sets bit 0. The translator applies those modifiers with `OpFNegate`/`FAbs`, and in the -interpreter that quiets the NaN. That form is left out unless `--known` (`class-snan-mods`, posted as a finding). -`v_cmp_class_f32` without modifiers and `v_cvt_f32_ubyteN` are in `f32_fuzz.py`. - -``` -python -I tools/fmisc_diff.py --programs 3000 --seed 11 --max-ops 8 -python -I tools/fmisc_diff.py --oracle hw --programs 500 --seed 1 -python -I tools/fmisc_diff.py --oracle hw,vk --programs 600 --seed 11 --max-ops 8 [--wave 64] -python -I tests/test_fmisc_diff.py -``` - -`--oracle hw,vk` also runs the translated programs on a real Vulkan GPU (`tools/vk_fuzz_run.py`: llvm-mc for gfx1013, -`rdna2spirv.py`, `runtime/build/vk_compute_test`, `LEONIDA_VK_DEVICE`, `--build DIR`) as one wave of 32 or, with -`--wave 64`, 64 identical lanes (the lane masks as 64-bit pairs; the hardware kernels run in the same wave size), and -judges lane 0's four words against the hardware's, not the reference's: the interpreter cannot see a driver's denormal, -NaN and rounding rules. The seeds are computed from the buffer fill at run time (`--vk-constants` keeps them as -literals), because the AMD Windows driver (26.10.1) folds an ordered compare of a literal NaN to true in a wave32 -pipeline (`v_cmp_lt_f32 vcc_lo, -10.0, NaN`, fine in wave64 and on the RTX 5080; with run-time operands it is right). -Differences are `denormal` (the reference declines the program for a denormal: f32 denormals are left to the driver), -`omod_neg_zero` (an output modifier made the hardware's -0 a +0, the translated -0 stayed; #1281) and `mismatch`, -which fails the run. Seeds 11 to 13, 600 programs each, up to 8 ops: Radeon gfx1036 wave32 597 match, 3 omod_neg_zero; -wave64 593 match, 3 denormal, 4 omod_neg_zero; RTX 5080 wave32 595 match, 3 omod_neg_zero, 2 denormal; no mismatch. - -### Translated programs on a Vulkan GPU: `--oracle hw,vk` of `pk16_diff`, `vint_diff`, `wint_diff`, `sdwa_diff` and `fmisc_diff` - -These fuzzers judge the translator in `spirv_mini_interp`, which cannot see what a driver does with the SPIR-V. `f32_fuzz` -has no Vulkan path (its GPU oracle is `--oracle hw`, above). With -`--oracle hw,vk` each program also runs through llvm-mc (gfx1013), `rdna2spirv.py` and `runtime/build/vk_compute_test` -(`tools/vk_fuzz_run.py`; `--build DIR`, `--work DIR`, `LEONIDA_VK_DEVICE`) as one wave, and its words are judged against -the hardware's words from a kernel run in the same wave size (`--wave 32` or `--wave 64`; wave64 needs native 64-wide -subgroups, so the Radeon and not the RTX 5080). `pk16_diff`, `vint_diff` and `fmisc_diff` run identical lanes and judge -lane 0, `sdwa_diff` too (its VCC seed differs per lane), `wint_diff` runs its per-lane programs in the wave size they were -generated for and judges every lane. The `v_mov_b32 vN, K` seeds of the lane-identical tools become `K ^ 0xEEEEEEEE` -xor the buffer fill vk_compute_test leaves in the output (`--vk-constants` keeps literals): the AMD Windows driver -(26.10.1) folds an ordered compare of a literal NaN to true in a wave32 pipeline, which says nothing about a shader given -a NaN at run time. - -``` -python -I tools/pk16_diff.py --oracle hw,vk --programs 500 --seed 201 --max-ops 8 [--wave 64] -python -I tools/vint_diff.py --oracle hw,vk --programs 500 --seed 203 -python -I tools/sdwa_diff.py --oracle hw,vk --family f16 --programs 500 --seed 211 -python -I tools/wint_diff.py --oracle hw,vk --wave both --programs 400 --seed 221 -``` - -Fresh seeds, 400 to 500 programs each (AMD Radeon iGPU gfx1036, driver 26.10.1, and NVIDIA GeForce RTX 5080, driver -616.92; the f16 SDWA programs also count `nan`: the reference declines an f16 NaN, the hardware kernels run with IEEE on): - -| tool | Radeon wave32 | Radeon wave64 | RTX 5080 wave32 | -|---|---|---|---| -| `pk16_diff` | 492 match, 8 mismatch | 492 match, 8 mismatch | 500 match | -| `vint_diff` | 500 match | 500 match | 500 match | -| `sdwa_diff --family int` | 500 match | 498 match, 2 mismatch | 500 match | -| `sdwa_diff --family f16` | 499 match, 1 nan | 498 match, 2 mismatch | 490 match, 10 nan | -| `wint_diff` | 398 match, 2 mismatch (wave32 and wave64 programs together) | | 400 match | - -The pk16 mismatches were `v_med3_i16` with a constant operand (seven of eight on wave64, five of eight on wave32; the -rest `v_pk_*` or `v_min_i16`): the AMD driver returned a bound instead of the middle value for the translated -min/max/clamp median (fixed by the sum-minus-min-and-max form, GPU test `cs_med3_i16`). The others are Radeon-only and -not fixable in the translator as far as measured: `v_not_b32_sdwa v4, v3 dst_sel:WORD_0 dst_unused:UNUSED_PAD -src0_sel:BYTE_0` with v3 = 0xffff gives 0xffffff00 where the hardware gives 0x0000ff00 in a wave64 pipeline (the same -with the field extracts written as shifts and a mask), and `v_cvt_f32_f16_sdwa ... dst_sel:WORD_1` of an f16 denormal -differs in the low bits of the result. - -### binary64 VALU on the CPU and Vulkan (`tools/f64_diff.py`, FUZZ-55) - -`tools/f64_diff.py` covers the 47 binary64 instruction forms `tools/rdna2spirv.py` translates on main: four rounding -ops, add, f64-to-f32 conversion, reciprocal/reciprocal-square-root/square-root, division fixup and scaled FMA, both -frexp results, all 16 `v_cmp_*_f64` and 16 `v_cmpx_*_f64` predicates, and both class compares. It generates one-lane -programs with VGPR and SGPR pairs, float immediates, inline constants, 32-bit literals where the translator marks -them as upper-half f64 literals, and full-width literals in other instruction forms; it compares the four exported -dwords. Compare predicates are read through a mask-to-word operation, and `v_cmpx` cases also export the resulting -`EXEC` mask. Its reference decodes IEEE binary64 words and uses exact -`Fraction` arithmetic for finite addition and fused multiply-add; it does not import code from the translator or the -other fuzzer references. It models all four `MODE.FP_ROUND[3:2]` encodings for addition; the translator currently -rejects directed rounding (+infinity and -infinity), so those generated cases are counted skips. Any NaN matches any -NaN. Binary64 subnormal operands or results for `v_rcp_f64`, `v_rsq_f64` and `v_sqrt_f64`, and subnormal f32 results -from `v_cvt_f32_f64`, are counted skips because shader drivers may flush them to zero (FTZ). - -`--sweep` (the default) tries each translated form, followed by `--programs N` seeded programs (`--seed S` and -`--max-ops N` control the campaign). `--no-sweep`, `--ops`, `--no-literals`, `--known`, `--all-failures`, -`--list-ops` and `--self-test` are available. The translator oracle executes generated SPIR-V with the local semantic -interpreter. The current CPU interpreters do not implement binary64 `OpFConvert` or `OpFDiv`; these are reported as -counted skips. Negative-input `Sqrt` and -`InverseSqrt` cases are also skipped because GLSL.std.450 leaves them undefined. `s_round_mode` encodings for directed -rounding that the translator rejects are counted as skips. The reference uses IEEE binary64 for reciprocal and square -root; native RDNA2 `v_rcp_f64`, `v_rsq_f64` and `v_sqrt_f64` have about 26 bits of precision (PROC-216), so this -oracle checks the translated SPIR-V contract, not the native instruction's approximation. Other unsupported interpreter -instructions are counted as skips with their reason. Vulkan's [SPIR-V environment](https://docs.vulkan.org/spec/latest/appendices/spirvenv.html) -leaves the precision of these GLSL [extended instructions](https://registry.khronos.org/SPIR-V/specs/unified1/GLSL.std.450.html) -implementation-defined for binary64; the GPU oracle therefore counts `v_rsq_f64` and -`v_sqrt_f64` as unjudged skips instead of requiring bit-exact results. This was confirmed on an NVIDIA RTX 4070 with -`shaderFloat64`: `v_rsq_f64 3.25` produced matching high 32 bits but zero low 32 bits, unlike the exact reference. - -Known divergence probes are excluded and counted by default, then reinserted with `--known`: binary64 output modifiers -(SHADER-721), binary64 `OpFNegate`/`FAbs` that the CPU interpreter rounds through binary32 (TEST-912, #4172), -driver-dependent NaN or signed-zero clamp results, and `v_div_fixup_f64` with a NaN `S0` and an ordinary finite -division. The latter follows the RDNA2 ISA reference (`NaN(S0) -> signed infinity`), while the current translator -preserves the NaN payload. Therefore `--known` can intentionally return 1 when this known mismatch is reproduced; -the minimized case is printed. `--oracle gpu` translates the same -fragment shader and runs it through `runtime/build/vk_harness`, comparing the raw RGBA32F output words. It assembles -the fragment module with `spirv-as` and the full-screen vertex shader with the Vulkan SDK's `glslc`; use `--exe PATH` -to select another `vk_harness`. It exits 77 if the executable, SDK tools, Vulkan device or required `shaderFloat64` -feature is unavailable. `--oracle hw` runs the same programs natively on an AMD GPU through `tools/hw_oracle` (one lane -of a wave32 compute kernel, as `tools/fmisc_diff.py` does) and compares the four words with the reference only, not with -the translator; `--hw-arch` picks the architecture to assemble for (default: detected). The campaign is one launch, and a -failing program is re-run alone while it is shrunk. The hardware runs every form, so the known-divergence exclusions -(translator limits) do not apply: output modifiers, clamp, negated/absolute operands and directed rounding are compared -too, and the kernels start in the game's inferred float MODE (IEEE off, DX10_CLAMP on). `v_rcp_f64`, `v_rsq_f64` and -`v_sqrt_f64` are counted skips there, because the native results are approximations (PROC-216) and the reference is exact; -an architecture that cannot set that MODE (gfx1170 and later) or a program the assembler rejects is a counted skip with the -runner's reason. It exits 77 only when the `tools/hw_oracle` tools or device are missing. The path is covered by -`tests/test_f64_diff.py` with a fake oracle (routing, `--hw-arch`, exit 77, skips, shrinking); **no AMD hardware run has -been done for it yet**. -Exit codes are 0 for no unexpected -mismatch, 1 for a mismatch (with instruction-removal shrinking), 2 for CLI/harness errors and 77 for unavailable -oracles. Skips always include a reason. - -``` -python -I tools/f64_diff.py --programs 300 --seed 1 -python -I tools/f64_diff.py --known --programs 300 --seed 1 -python -I tools/f64_diff.py --oracle gpu --programs 300 --seed 1 -python -I tools/f64_diff.py --oracle hw --programs 300 --seed 1 -python -I tools/f64_diff.py --self-test -python -I tests/test_f64_diff.py -``` - -**Vulkan check on an NVIDIA GeForce RTX 4070** (Windows 11, driver 621.01, Vulkan `shaderFloat64` enabled): - -| Command | Match | Mismatch | Total | Skips | -|---|---:|---:|---:|---:| -| `--oracle gpu --programs 300 --seed 1` | 331 | 0 | 347 | 16 | -| `--oracle gpu --programs 200 --seed 2 --max-ops 4` | 218 | 0 | 247 | 29 | -| `--oracle gpu --ops v_cvt_f32_f64,v_rcp_f64,v_rsq_f64,v_sqrt_f64 --programs 80 --seed 1` | 39 | 0 | 84 | 45 | -| `--oracle gpu --ops v_cmpx_lt_f64,v_cmpx_eq_f64,v_cmpx_class_f64 --programs 40 --seed 1` | 43 | 0 | 43 | 0 | - -The skips are counted by reason: subnormal FTZ, implementation-defined binary64 `InverseSqrt`/`Sqrt` precision, -non-finite scaled FMA, and translator-rejected directed rounding. The compared cases had no mismatches. - -### Output modifiers of the binary64 and f16 division ops (`tools/f64_omod_probe.py`) - -`tools/f64_omod_probe.py` measures what `mul:2`, `mul:4`, `div:2` and `clamp` do to six VOP3 results: the binary64 -conversions `v_cvt_f64_i32` and `v_cvt_f64_u32`, `v_cvt_f32_f64` (an f32 destination), `v_frexp_mant_f64`, -`v_div_fixup_f64` and `v_div_fixup_f16`. Each case is measured plain and with each modifier in the same kernel launch, -so the probe compares the modifier's effect and not the semantics of the op. A hand-written kernel writes the whole -destination (both words for binary64, the low half only for the 16-bit form, as the ISA defines) and runs once in -wave32 and once in wave64, which must agree word for word. It needs `tools/hw_oracle` on a GFX10 AMD GPU: the kernels -set their own MODE from the descriptor, and a device of another family is reported as unavailable, since the gate was -measured on RDNA2. It reads no game files. - -The five MODEs are `game_i0_d3` (the game's, and the translator's: IEEE 0, `denorm_mode_16_64 = 3`, -`denorm_mode_32 = 0`, DX10_CLAMP 1), `i0_d0`, `i1_d3`, `i1_d0` and `i0_d3_f32keep` (`denorm_mode_32 = 3`). The gate -turns out to be **per result precision, not per instruction family**: the f32 result of `v_cvt_f32_f64` follows -`denorm_mode_32` and scales whenever it is 0, while the f16 and binary64 results scale only with IEEE 0 and -`denorm_mode_16_64 = 0` and ignore the modifiers in the game's MODE. `clamp` applies in every MODE. That is why -`tools/rdna2spirv.py` keeps only `clamp` for these destinations, and the rows for these ops in `docs/design.md` carry -the measurement. - -`--modes` takes a comma-separated subset of the five (all by default), `--waves` the wave sizes (`32,64` by default), -`--hw-arch` the architecture handed to `tools/hw_oracle`, and `--json` a path for the report: the device, the -architecture, the modes, the wave sizes, the modifier forms, the ops and the counts `scaling_gated_on`, -`scaling_gated_off`, `scaling_changed_value`, `clamp_changed_value`, `mismatches` and `wave_diffs`, with the first -cases of each. `--self-test` checks the model's own cases without a GPU. Exit 0 when every word matches the model and -the wave sizes agree, 1 on a mismatch or a wave difference (the first cases are printed), 2 on a CLI or harness error -and 77 when the oracle or a GFX10 device is missing. `tests/test_f64_omod_probe.py` covers the gate and the CLI with a -fake oracle. - -``` -python -I tools/f64_omod_probe.py # all five MODEs, wave32 and wave64 -python -I tools/f64_omod_probe.py --waves 64 --json f64_omod.json -python -I tools/f64_omod_probe.py --self-test -python -I tests/test_f64_omod_probe.py -``` - -**Default-mode DX9 multiply regression.** `v_mul_legacy_f32` now explicitly flushes each f32 operand before the -DX9 `0 * anything => +0` override, and flushes the nonzero product before its VOP3 output modifier. The output is -flushed again before the active omod's `-0 => +0` rule. Previously it emitted an unguarded `OpFMul`, so on a Vulkan -driver that keeps f32 denormals, a subnormal input times a large number or an underflowing normal product yielded -nonzero results even though the inferred RDNA2 `MODE.denorm_mode_32 = 0` requires zero. The standalone semantic -test `test_valu_mul_legacy_denorm.py` checks the exact bit patterns and the two GPU fixtures -`ps_mul_legacy_denorm` / `ps_mul_legacy_denorm_mods` exercise signed input/output FTZ, legacy zero override, and -output scaling. This is a translation for the **inferred game MODE**, not a claim of correctly handling dynamic -denormal-preserving or IEEE modes; native gfx1013 measurements of these new fixtures were not available. - - -### f16 transcendentals on the hardware (`tools/f16_trans_sweep.py`, FUZZ-29) - -The `16-bit results` row of `docs/design.md` listed `v_exp_f16`/`v_log_f16` and the NaN and denormal operands as -unverified. f16 has only 65,536 bit patterns, so instead of sampling, this tool runs every one of them through -`v_exp_f16`, `v_log_f16`, `v_rcp_f16`, `v_rsq_f16`, `v_sqrt_f16`, `v_sin_f16` and `v_cos_f16` on the hardware -oracle (setup above; exit 77 without it). Each op is 8 raw kernels of 1,024 threads. Each thread computes 8 inputs -and stores them packed two to a dword, which is 4,096 words per kernel; 8 kernels cover every input. The op runs in -wave32 and wave64 and under five MODEs, and MODE is read back with `s_getreg_b32` first: - -| Mode | IEEE | f16 denormals | f16 rounding | -|---|---|---|---| -| `keep16` | 0 | kept (3) | nearest | -| `flush16` | 0 | flushed (0) | nearest | -| `ieee_keep16` | 1 | kept | nearest | -| `ieee_flush16` | 1 | flushed | nearest | -| `keep16_rtz` | 0 | kept | toward zero | - -All modes have DX10_CLAMP 1 and f32 denormals flushed. - -``` -python -I tools/f16_trans_sweep.py # all ops and modes, about 5 minutes -python -I tools/f16_trans_sweep.py --ops v_exp_f16 --modes keep16 --json out.json -python -I tools/f16_trans_sweep.py --self-test # the reference, no GPU -``` - -The reference is the exact result correctly rounded to f16, computed with `decimal` at 60 digits: for sin/cos that is -sin/cos(2πx), reduced in turns. That reference is the translator's rule (widen, the GLSL.std.450 function in f32, -round to nearest even) with an exact f32 function, the best a driver can do. Inputs where the translated SPIR-V is -undefined are tabulated, not judged. For each mode the tool counts: -- bit-exact results, 1 ulp and more than 1 ulp; -- denormal operands that give the hardware's own word for a zero of the same sign, and denormal results written as zero; -- NaN results, with signalling NaNs kept, quieted or changed. - -It also counts the inputs on which each mode differs from `keep16`, and lists the word for 23 special inputs. For -sin/cos a second table compares the hardware with Sin/Cos of the f32 product 6.2831855 · x, by |x| band. - -Result on an RX 6700 XT (gfx1031, Navi 22; the Linux launcher from #1265, Linux 7.3.5, amdgpu, clang 23.1.5). -wave32 and wave64 gave the same word for every input of every op in every mode. There was no GPU fault, timeout or -reset in the kernel log. - -| Op (`keep16`) | Inputs that are not NaN | Bit-exact | 1 ulp | Undefined in SPIR-V | -|---|---|---|---|---| -| `v_exp_f16` | 63,490 | 63,490 | 0 | 0 | -| `v_log_f16` | 63,490 | 31,744 | 0 | 31,746 (≤ 0) | -| `v_rcp_f16` | 63,490 | 63,488 | 0 | 2 (±0) | -| `v_rsq_f16` | 63,490 | 31,744 | 0 | 31,746 (≤ 0) | -| `v_sqrt_f16` | 63,490 | 31,746 | 0 | 31,744 (< 0, -0 excluded) | -| `v_sin_f16` | 63,490 | 63,474 | 14 | 2 (±inf) | -| `v_cos_f16` | 63,490 | 63,484 | 4 | 2 (±inf) | - -- **Correctly rounded.** The five non-trigonometric ops never differ from the correctly rounded result. sin/cos differ - by 1 ulp on 14 and 4 inputs, all with |x| ≤ 1. For |x| > 1 every result is bit-exact, up to 65,504 turns: the f16 - ops have no ±256 domain limit. -- **The f32 product loses the turn.** Against Sin/Cos(f32 6.2831855 · x), which is what the translator computes before - #594 is fixed, 16,366 sin and 2,036 cos inputs are more than 1 ulp off, up to 9,944 ulp. Nearly all of them have - |x| > 1 (sin: 1,010 inputs at 1 < |x| ≤ 256 and 15,354 above 256). Reducing in turns first, as #1283 and #616 - propose, is what the hardware does; for f16 the reduction must not stop at ±256. -- **f16 denormals follow `denorm_mode_16_64`, for operands and results alike.** With 0, a denormal operand gives the - word of a zero of its sign (`v_log_f16` -inf, `v_rcp_f16` and `v_rsq_f16` ±inf, `v_sqrt_f16` and `v_sin_f16` ±0). - Denormal results become ±0 (831 for `v_exp_f16`, 4,094 for `v_rcp_f16`). With 3, both are kept. The f32 - transcendentals behave differently: they flush in both modes. -- **The f16 field of FP_ROUND is ignored.** Under round toward zero every op gives the same word as under round to - nearest, on all 65,536 inputs. -- **IEEE only changes signalling NaNs.** With IEEE 0, all 1,022 f16 signalling NaNs pass through unchanged. With IEEE 1 - they are quieted (bit 9 set) with payload and sign kept. Quiet NaNs pass through unchanged in every mode. This is the - f32 behaviour of the previous section. -- **Undefined in SPIR-V, defined on the hardware.** log(±0) = -inf; rcp(±0) = ±inf; rsq(+0) = +inf; rsq(-0) = -inf; - sqrt(-0) = -0. log, rsq and sqrt of a negative (-inf included), and sin/cos(±inf), give `0xfe00`, the negative quiet - NaN (`0xffc00000` in f32). -- **Controls.** `keep16_rtz` also judges against a round-toward-zero reference, so it shows what a wrong rounding - model produces: about half the results 1 ulp off. The kernel layout is checked without a GPU: each of the 65,536 - inputs is computed once and stored in its own half (`tests/test_f16_trans_sweep.py`). On a GPU the test checks - exp2 of integers and wave32 = wave64. - -### d16 rounding of UNORM/SNORM buffer loads (`tools/d16_format_probe.py`, BUILD-161) - -`docs/design.md` ("d16 and f16 format narrowing") narrows the f16 of a typed d16 buffer load the way it narrows an -image result: the exact binary32 decode, then integer round to nearest even (`Gen.f16_bits`). For buffer loads that -rounding was inferred, not measured. The probe measures it on a GFX10 GPU (RDNA1/RDNA2) through the hardware -oracle. Every value of UNORM8, SNORM8, UNORM10 (the x channel of format 50), UNORM16 and SNORM16 is loaded with -`buffer_load_format_d16_x`, `tbuffer_load_format_d16_x` and, for the f32 stage alone, `buffer_load_format_x`. Each -runs in wave32 and wave64. - -``` -python -I tools/d16_format_probe.py --json d16.json # about 1,040 kernels of 1,024 threads; exit 77 without the oracle -python -I tools/d16_format_probe.py --self-test # the rules against docs/design.md's #489 counts, no GPU -``` - -- **The kernels stage their own inputs.** Thread t stores the format bits of one value at dword t of the output - buffer and waits for the store (`s_waitcnt_vscnt`). It then builds a GFX10 V# over the buffer: DST_SEL XYZW, the - format, RESOURCE_LEVEL 1, OOB_SELECT 3, NUM_RECORDS the 4 KiB staged. It loads its element with `glc dlc` (past - L0 and GL1) and stores the VGPR at dword 1024 + t. The host checks that every staged word reads back as written. -- **Rules compared**, each also with f16 denormal results flushed: - - `f32_rte`, the translator's rule; - - `f32_rtz`, which is `v_cvt_pkrtz_f16_f32` of the f32 decode, the #489 bug; - - `rte` and `rtz`, which round the exact quotient once; - - `mul_rte`, the f32 product v · f32(1/(2^n − 1)) rounded to nearest even. -- **What the formats can separate.** The 8- and 10-bit formats only separate nearest from toward zero: every other rule - gives the same bits there. That covers 123 of the 256 UNORM8 values and 110 of the 256 SNORM8 values, the #489 - counts. Only four 16-bit values separate one rounding from two (`f32_rte` against `rte`): UNORM16 0xffaf and - 0xffef, SNORM16 0x7ff7 and 0x8009. The smallest UNORM16/SNORM16 values have quotients under 2^-14, so they show - a flush of f16 denormals. -- **Controls:** - - a 16_FLOAT d16 load must return its own bits (NaNs may be quieted); - - `d16_x` must leave the high half of its VGPR as it was (`docs/design.md` measured this on gfx1036); - - wave32 must equal wave64, and MUBUF must equal MTBUF. - - A failed control is exit 2; a wave or MUBUF/MTBUF difference is exit 1. Which rule the hardware follows is - reported, not judged. - -Measured on an RX 6700 (gfx1031, AMD Windows driver 32.0.21045.29003, ROCm wheel clang), the whole sweep in 36 s: - -| Format | Values | d16 `rte` | d16 `f32_rte` | d16 `f32_rtz` | f32 `f32_rte` | -| --- | --- | --- | --- | --- | --- | -| UNORM8 | 256 | 256 | 256 | 133 | 256 | -| SNORM8 | 256 | 256 | 256 | 146 | 256 | -| UNORM10 | 1,024 | 1,024 | 1,024 | 514 | 1,024 | -| UNORM16 | 65,536 | 65,536 | 65,534 | 33,796 | 65,536 | -| SNORM16 | 65,536 | 65,536 | 65,534 | 34,820 | 65,536 | - -- The d16 result is the exact quotient rounded once to f16, to nearest even, with f16 denormals kept. The two - UNORM16 and two SNORM16 values that separate one rounding from two all came out 1 ulp below the f32-first result: - 0xffaf gave 0x3bfd (not 0x3bfe), 0xffef gave 0x3bff (not 0x3c00), 0x7ff7 gave 0x3bff, and 0x8009 gave 0xbbff. - The translator now follows this (`Gen.d16_norm_f16`, `docs/design.md` "d16 and f16 format narrowing"). -- The f32 result (`buffer_load_format_x`) is the correctly rounded quotient for every value. The reciprocal multiply - matched only 130 of 256 UNORM8 values and 65,024 of 65,536 UNORM16 values. -- 16_FLOAT came back with its own bits for all 65,536 encodings, NaNs included. The high half of the d16_x VGPR was - kept. MUBUF matched MTBUF, and wave32 matched wave64, for every value. - -`tests/test_d16_format_probe.py` checks the rules against the #489 counts and the descriptor bits. It checks that -each value is staged once, and that the kernels assemble for gfx1031. A fake oracle plays the GPU to check the exit -codes. On a GFX10 GPU the test runs UNORM8 and checks the controls. - -### Widening a 16-bit float NaN in a typed buffer load (`tools/f16_widen_probe.py`) - -A typed buffer load of a half NaN had never been measured: `tools/mem_diff.py` decoded 16_FLOAT with -`struct`'s `'> (BASE_LEVEL + - level)): 100 layers at level 3 gave 12. -- Past the last level, width, height and depth are 0, while the level count stays. -- Raw LOD = computed LOD + LOD_BIAS. The clamped LOD is the level that would be read: 0 with no mip filter, the - clamp rounded half up with point, the clamp itself with linear. - -`tests/test_image_query_probe.py` checks the rules against the measured values, the descriptor bits and the -kernels. A fake oracle plays the GPU to check the comparison and the exit codes; with a 2D depth of 1 it fails. On -a GFX10 GPU the test runs the whole probe. -### d16 image loads of 32-bit integer texels (`tools/image_d16_probe.py`, SHADER-387) - -`docs/design.md` ("Typed image loads") saturates a 32-bit UINT or SINT texel to the 16-bit range of its signedness -when a d16 `image_load` packs it (Mesa sets `integer_dest_saturates` for AMD). Native gfx1036 had shown that on 2D -images; the probe measures it on every dimension the translator handles, through the hardware oracle on a GFX10 GPU. - -``` -python -I tools/image_d16_probe.py --json d16_image.json # 16 kernels, one lane per texel; exit 77 without the oracle -python -I tools/image_d16_probe.py --self-test # the rules, T# words and kernels, no GPU -``` - -- **Cases.** `SQ_RSRC_IMG_1D`, `2D`, `2D_ARRAY` (3 layers) and `3D` (depth 3), each with 32_UINT and 32_SINT - (`dmask:0x1`) and 32_32_UINT and 32_32_SINT (`dmask:0x3`, both results in one VGPR), read with `image_load` and - `image_load_mip` at mip 0. The texture sits in the kernel's code after `s_endpgm`, linear, with 256-byte rows (64 - R32 or 32 R32G32 texels), so the layout does not depend on how the T# states the pitch. The staged words start with the values that separate the rules (0x7fff, 0x8000, 0xffff, 0x10000, - 0x7fffffff, 0x80000000, -32769, -32768 and their neighbours), then a fixed mixing sequence. -- **Rules compared:** `trunc` (the low 16 bits), `sat_u` (min(w, 0xffff)) and `sat_s` (w clamped to - [-32768, 32767]). Every pair differs on some staged value. A one-channel result also reports its high half, which - starts as 0x5a5a. -- **Controls.** The same texel read without d16 must return the staged word, for x and, on two-channel formats, y: - a wrong extent, layer or slice offset fails it (exit 2). On gfx1036, a T# with one layer fewer than a 2D - array's three, a 3D depth of 1, or a 1D width of 32 failed 246 of 384, 246 of 384 and 31 of 64 controls. - `image_load` and `image_load_mip` must agree (exit 1). - -Measured on the integrated GPU of a Ryzen 7 7800X3D (gfx1036, AMD Windows driver 32.0.21045.29003, ROCm wheel -clang), wave32, every control read back: - -| Dimension | Texels per format (one / two channels) | UINT | SINT | High half (one channel) | -| --- | --- | --- | --- | --- | -| 1D | 64 / 32 | `sat_u` on all | `sat_s` on all | kept | -| 2D | 128 / 64 | `sat_u` on all | `sat_s` on all | kept | -| 2D-array | 384 / 192 | `sat_u` on all | `sat_s` on all | kept | -| 3D | 384 / 192 | `sat_u` on all | `sat_s` on all | kept | - -`image_load` and `image_load_mip` gave the same words on every texel. No result followed `trunc` where it differs -from saturation. The translator's `saturate_int16` follows this on every dimension; the translated 1D, 2D-array and -3D d16 loads have not been run on a GPU yet. - -`tests/test_image_d16_probe.py` checks the rules, the T# fields and the kernels without a GPU, assembles them for -gfx1036 when AMD clang is there, and checks the exit codes with a fake oracle. On a GFX10 GPU it runs the probe. - -### `v_fma_mix*` f16 rounding in nearest mode (`tools/fma_mix_probe.py`) - -`docs/design.md` leaves one f16 question open. In round-to-nearest mode, does `v_fma_mixlo_f16` / `v_fma_mixhi_f16` -round the exact x · y + z once, straight to f16? Or does it round to f32 first and then narrow, which is what the -translator does (f32 `Fma`, then `f16_res`)? The RX 6800 word behind the toward-zero rule can't answer this. For -1 · 2 - 2^-30 both readings give 0x4000 in nearest mode, and toward zero two truncations equal one. - -The two readings only differ when the f32 rounding lands exactly on an f16 tie, or moves a value off one. The probe has -seven such inputs, each one f16 ulp apart under the two rules, plus one control: -- a tie just above and just below, for both signs; -- the subnormal tie at 2^-25; -- the overflow tie at 65520 (inf against 65504); -- a tie made by the product rather than by z; -- the same with f16 operands (`op_sel_hi:[1,1,1]`). - -Every side reports which rule its words follow: - -``` -python -I tools/fma_mix_probe.py # the translator, on the CPU interpreter -python -I tools/fma_mix_probe.py --oracle hw # also the native instruction on an AMD GPU (hardware oracle) -python -I tools/fma_mix_probe.py --oracle vulkan --build runtime/build # also the translated shader on this GPU -``` - -The `hw` side is the measurement. It runs one wave32 lane per input, under the MODE inferred for the game: IEEE 0, -DX10_CLAMP 1, f32 denormals flushed, f16 denormals kept, nearest. The `vulkan` side only shows that a driver runs the -translator's sequence as written. Its operands come in user SGPRs, so the driver can't fold them. Exit 0 means every -side follows the same rule. Exit 1 means they differ, or a side follows neither rule. Exit 77 means a requested side -is unavailable. - -`tests/test_fma_mix_probe.py` checks the expected words against a derivation written out by hand. It also checks that -the translator follows the single rounding rule, and that the compute shader gives the pixel shader's words on the -interpreter. Hardware measurement on AMD RDNA2 confirmed that the hardware rounds once, straight to f16, so the translator -uses `Gen.fma_mix_odd` in nearest mode as well. Round-to-odd at f32 then narrows exactly, giving the single-rounded word on -all seven discriminating inputs. - -Results: - -| GPU | Driver | `translator` | `vulkan` | `hw` | -|---|---|---|---|---| -| NVIDIA GeForce RTX 5060 (Blackwell), Windows 11 | 621.24 | single | single, 8 of 8 words | not AMD | -| AMD Radeon iGPU (RDNA2, gfx1036), Windows 11, HIP backend | 32.0.21044.64 | single | single, 8 of 8 words | **single**, 7 of 7 ties; control `0x4100` | - -RDNA2 rounds once. Every tie input gives the single-rounded word (A `0x3c01`, B `0x3c01`, C `0xbc01`, D `0x0001`, -E `0x7bff`, F `0x3c01`, G `0x3c01`), so the translator is one f16 ulp off on exactly these inputs (SHADER-135; the -translator is not changed here). On the RTX 5060, a translator copy changed to use -`fma_mix_odd` in nearest mode gave the single-rounded word for all seven inputs on the `vulkan` side as well. - -Measurement on AMD RDNA2 (gfx1036) confirmed single rounding across all 7 discriminating cases (finding 7079901079). -Using `fma_mix_odd` produces the exact hardware single-rounded words in both nearest-even and toward-zero modes. -E `0x7bff`, F `0x3c01`, G `0x3c01`), which the translator produces across all 7 discriminating cases via -`fma_mix_odd` in both nearest-even and toward-zero modes (SHADER-297). On Vulkan, using `fma_mix_odd` matches the -exact single-rounded hardware words for all inputs. - -### `v_cvt_pknorm_*` NaN and rounding on RDNA2 (`tools/pknorm_probe.py`, SHADER-339) - -`docs/design.md` said `v_cvt_pknorm_i16_f32` / `v_cvt_pknorm_u16_f32` give 0 for a NaN, as `v_cvt_i32_f32` does, -without a hardware measurement. The probe puts each NaN pattern in S0 and in S1 next to a finite value: quiet -(`0x7fc00000`, `0xffc00000`), quiet with a payload (`0x7fc00001`, `0x7fffffff`, `0xffffffff`), signalling -(`0x7f800001`, `0xff800001`, `0x7fa00000`). Finite values are the semantic test's (±0, ±1, ±0.5, ±2, ±inf, -subnormals, steps of 1/32767 and 1/65535). It also has near-tie inputs: f32 values whose product with 32767 (or 65535) -rounds to exactly k + 0.5 in f32, while the exact product is just below or just above it. There the translator's -`OpFMul` then `RoundEven` and a single rounding of the exact product differ by one, in either direction. - -``` -python -I tools/pknorm_probe.py # the translator, on the CPU interpreter -python -I tools/pknorm_probe.py --oracle hw # also the native instruction on an AMD GPU (hardware oracle) -``` - -The `hw` side runs one lane per case in wave32 and wave64, under five MODEs: -- the one inferred for the game (IEEE 0, DX10_CLAMP 1, f32 denormals flushed, f16/f64 kept, nearest); -- the same with IEEE 1; -- the same with DX10_CLAMP 0; -- the same with both IEEE 1 and DX10_CLAMP 0; -- the same with f32 denormals kept. - -It reports the NaN halves that give 0, the words equal to the translator's, and the near-tie words equal to a single -rounding of the exact product. Exit 0 means every hardware word equals the translator's, 1 means one differs, 77 -means the oracle is unavailable. `tests/test_pknorm_probe.py` checks four near-tie words against a derivation written -out by hand, and checks that the translator side rounds once there (since SHADER-363) and gives 0 for a NaN half. - -Results (134 cases per run): - -| GPU | Driver | NaN halves giving 0 | near ties: single / translator | other words equal | -|---|---|---|---|---| -| AMD Radeon iGPU (Ryzen 5 7600X, RDNA2, gfx1036), Windows 11, HIP backend, AMD clang (rocm-sdk-core 10.0.0) | 32.0.21045.29003 | 74 of 74 | 28 of 28 / 0 of 28 | 34 of 34 | - -The ten runs (two wave sizes, five MODEs) give the same words. A NaN gives 0 on RDNA2, as the translator assumes, -whatever the IEEE, DX10_CLAMP and f32 denormal fields. The rounding does not match. The hardware rounds the exact -product once, to nearest even. Examples: -- `0x38400180` (exact 1.5 - 1.4e-9) gives 1, where the translator gives 2; -- `0x3c004101` (exact 256.5 + 1.5e-5) gives 257, where the translator gives 256. - -SHADER-363 fixes the translator. It keeps the f32 product p and its exact error `Fma(x, s, -p)`. When p lies exactly -on k + 0.5, the error's sign gives floor(p) + 1 or floor(p), and a zero error keeps `RoundEven` (an exact tie). The -probe then exits 0 on the same iGPU: all 134 words equal the translator's in all ten runs (wave32 and wave64, five -MODEs), including the 28 near ties. - -### Division fixup (`tools/div_fixup_diff.py`) - -No other fuzzer generates `v_div_fixup_f16`, `v_div_fixup_f32` or `v_div_fixup_f64`. `tools/div_fixup_diff.py` -runs them through the translator and `tests/semantic/spirv_mini_interp.py`, against a model of the `docs/design.md` -rows that works on the operand bits and shares no code with the translator, and compares the four exported words bit -for bit. The model: - -- `abs` then `neg` act on the sign bit of S0, S1 and S2, NaNs included. -- f32 reads an S1 or S2 denormal as a zero of its sign and keeps an S0 denormal. f16 and f64 keep every denormal. -- The first rule that holds gives the result: NaN(S2), NaN(S1), 0/0 or inf/inf (the negative quiet NaN), a zero - numerator or an inf denominator (zero), a zero denominator or an inf numerator (inf), the exponent cutoff - (`exp(S2) - exp(S1)` at most -151 on f32 and -1076 on f64, none on f16; zero), NaN(S0) (inf), S0's magnitude. - The sign is sign(S1) ^ sign(S2). -- On f32, `mul:2`/`mul:4`/`div:2` scale the result, then `clamp` takes a NaN or any negative value to +0. -- On f16 and f64, `mul:2`/`mul:4`/`div:2` change nothing: the `docs/design.md` row (#6314, measured on gfx1036 with - `tools/f64_omod_probe.py`) drops the scaling under `denorm_mode_16_64 = 3`, the game's `MODE`, while an f16 `clamp` - still saturates. The measured inputs are normal values; the reference applies the row to every result. - -`tests/test_div_fixup_diff.py` pins the model to the 73 gfx1036 rows of `tests/semantic/test_alu_div_fixup_f32.py` -and to the f16 and f64 rows of `test_alu_div_fixup.py`, the measured exponent cutoffs among them. - -Sources are VGPRs, SGPRs, a literal (not on f64) and integer and float inline constants, within the GFX10 literal and -constant-bus limits. An f64 source is a VGPR pair (odd first registers too), an SGPR pair or an inline constant, and -`0.15915494309189532` is the binary64 1/(2 pi). Modifiers are `neg`/`abs`, `op_sel` on the f16 register sources and -the destination, `clamp` on f16 and f32, and the output multipliers on all three. Not generated: a literal on f64 -(#3791 moves it to bits 63:32) and `clamp` on f64 (the translation needs Float64, which the interpreter does not run). - -An f32 NaN that went through an output multiplier matches any NaN. Some programs are counted as not judged, with the -reason: -- an f64 exponent cutoff that depends on how a denormal's exponent counts (only normal operands were measured); -- an output multiplier on -0 without `clamp` (the hardware gives +0, not modelled), or on an f32 denormal; -- `clamp` of a positive f32 denormal, of an f16 -0 or of an f16 NaN (`FClamp` of a NaN is undefined); -- reading part of an f32 NaN whose payload is not modelled. - -Stages: -1. A sweep of every encodable source-kind combination of each op. -2. An edge grid: special values as S1 and S2 under five S0 values, the exponent cutoff one below, at and one above - (also against a NaN or inf S0, and on f64 with a denormal numerator), `abs`/`neg` on every kind of value, and - the output modifiers on each rule's result (f16 multipliers in both destination halves, with and without `clamp`). -3. Random seeded programs, which read earlier results, f64 halves as f32 or f16 values included. - -A translator skip exits 1, as a mismatch does. - -``` -python -I tools/div_fixup_diff.py --programs 3000 --seed 11 --max-ops 8 -python -I tools/div_fixup_diff.py --ops v_div_fixup_f64 --programs 1000 -python -I tests/test_div_fixup_diff.py -``` - -### `v_mad_f32`, `v_mac_f32`, `v_mad_legacy_f32` denormal flush on RDNA1 (`tools/mad_denorm_probe.py`, SHADER-340) - -`docs/design.md` ("Denormal flush in `v_mad_f32`, `v_mac_f32`, `v_mad_legacy_f32`") had no hardware measurement: GFX10.3+ -dropped these opcodes, and flushing only after `omod` (`div:2`/`mul:2`/`mul:4`) was an unverified assumption. The probe -covers 48 cases across six groups: subnormal operands in each source slot (`input`, 15), normal operands with a subnormal -product (`product`, 7), normal operands/products with a subnormal sum (`result`, 6), `omod`/`clamp` crossing the -subnormal threshold (`omod`, 8), `v_mad_legacy_f32`'s `0 * anything -> +0` with subnormals (`legacy`, 5), and controls -(`control`, 7). A `v_mul_f32(FLT_MIN, 0.5)` sanity kernel checks that `MODE.denorm32=3` actually keeps f32 denormals on -the device (`0x00000000` with `denorm32=0`, `0x00400000` with `denorm32=3`). - -``` -python -I tools/mad_denorm_probe.py # the translator, on the CPU interpreter -python -I tools/mad_denorm_probe.py --oracle hw # also the native instruction on an AMD GPU -``` - -Results (48 cases per run, wave32 and wave64 across 5 MODEs; `tests/test_mad_denorm_probe.py` checks the translator side): - -| GPU | Driver | `game` / `dx10clamp0` / `denorm32_kept` | `ieee1` / `ieee1_dx10clamp0` (non-`omod` + `omod` ignored) | -|---|---|---|---| -| AMD Radeon RX 5600 XT (`gfx1010`, RDNA1), Windows, HIP backend (`amdhip64_6.dll`), AMD clang (`rocm-sdk-core 10.0.0`) | 32.0.21045.29003 | 48 of 48 (wave32 and wave64) | 48 of 48 (wave32 and wave64) | - -Two findings from the RDNA1 measurement: -- **Subnormal inputs, products, sums, and legacy rules flush regardless of `MODE.denorm32`** (40 of 40 non-`omod` cases match bit-for-bit across all 5 MODEs, including `denorm32=3`). Under `MODE.IEEE=1`, hardware ignores `mul:2`/`mul:4`/`div:2` (`FLT_MIN div:2` gives `FLT_MIN`, as for other f32 VALU ops). -- **Hardware flushes both before and after `omod`.** Before SHADER-340, the translator flushed only after `clamp_mods`, so `(1.5*2^-126 - 2^-126) mul:2` gave `0x00800000` (`FLT_MIN`) and `mul:4` gave `0x01000000`, whereas the RX 5600 XT returns `+0` (`0x00000000`) in `game`, `dx10clamp0`, and `denorm32_kept`. `Gen.flush_f32_mods` now flushes the sum before `clamp_mods` and flushes again after it (`FLT_MIN div:2` → `+0`, `-FLT_MIN div:2` → `-0`), leaving non-modified `v_mad*`/`v_mac*` instructions byte-identical. - -### f16 output modifiers, clamp and `v_fma_mix*` operands on RDNA2 (SHADER-135) - -*Measured on an RDNA2 iGPU (gfx1036), AMD Windows driver 32.0.21044.64, HIP backend, AMD clang 23.0.0git, `main` -a0acd33d.* Raw kernels written by hand, one lane each. The MODE comes from the kernel descriptor (`ieee`, -`dx10_clamp`, `denorm_mode_32`, `denorm_mode_16_64`). Every program writes one word, starting from a destination of -`0x5a5a5a5a`, so a half the op must not write shows up. 1,385 programs assembled, each run in wave32 and wave64, and -the two wave sizes agree on every word. `tools/fma_mix_probe.py --oracle hw` (the section above) and -`tools/f16_trans_sweep.py --ops v_exp_f16,v_log_f16` ran on the same GPU. - -- **An omod on an f16 result acts only with IEEE 0 and f16 denormals flushed (`denorm_mode_16_64 = 0`).** In that - MODE `mul:2`, `mul:4` and `div:2` scale the results of `v_add_f16`, `v_mul_f16`, `v_fma_f16`, `v_fmac_f16_e64`, - `v_cvt_f16_f32_e64`, `v_exp_f16_e64` and `v_rcp_f16_e64` (`v_fmac_f16_e64` 0.75 · 1 + -0 `mul:4` gives `0x4200`). - With `denorm_mode_16_64 = 3` or IEEE 1 they leave the result as it is (`0x3a00`), and `denorm_mode_32` makes no - difference. The f32 control (`v_add_f32_e64 mul:2`) follows `denorm_mode_32` instead, as on gfx1150 above. Unlike - the f32 transcendentals there, `v_exp_f16` and `v_rcp_f16` obey the same rule as the ALU ops. When the omod acts, a - -0 result becomes +0 (`v_fmac_f16` -0 · 1 + -0 `mul:2` gives `0x0000`), and it comes before the clamp - (`v_cvt_f16_f32_e64` 0.75 `clamp mul:2` gives `0x3c00`, not `0x3e00`). -- **clamp** on `v_cvt_f16_f32_e64`, `v_fmac_f16_e64`, `v_fma_mixlo_f16` and `v_fma_mix_f32` clamps to [0, 1] in every - MODE: -0.5 and -0 give +0, 3.0 and an overflow (1e5, 65504 · 2) give 1.0. A NaN gives +0 with DX10_CLAMP 1. With - DX10_CLAMP 0 it stays the NaN the op gives without clamp. This is SHADER-186's f32 rule, here for the f16 results and - the mix ops. -- **Constants in `v_fma_mix*` operands.** A float inline constant is the f32 constant where `op_sel_hi` makes the - operand f32, and the f16 constant with a zero high half where it makes it f16. `1.0`, `-1.0`, `0.5`, `2.0` and - `-4.0` give their value either way. `0.15915494` gives `0x3e22f983` as f32 and `0x3118` as f16 (`0x3e230000` once - widened). With `op_sel_hi = 1` and `op_sel = 1`, every float constant reads +0.0. An integer inline constant is its - 32-bit integer. As an f32 operand, `1` and `64` are f32 denormals (+0 with `denorm_mode_32 = 0`) and `-1` is the NaN - `0xffffffff`. As an f16 operand, `op_sel` picks a half: `1` gives `0x0001` low and +0 high, and `-1` gives `0xffff` - in both. `op_sel` is ignored for an f32 operand. For gfx10, llvm-mc rejects a 32-bit literal in these ops ("invalid - operand"). It encodes a literal equal to an f16 inline constant, such as `0x3c00`, as that constant (`0xf2`). -- **Mix-op denormals follow the mode of their own width.** An f16 operand (`op_sel_hi = 1`) and an f16 result - (`mixlo`/`mixhi`) become a zero of their sign with `denorm_mode_16_64 = 0`, and are kept with 3, whatever - `denorm_mode_32` says. An f32 denormal is flushed with `denorm_mode_32 = 0` and kept with 3. -- **Mix-op NaNs.** An f16 NaN operand widens with its payload (`0x7c01` → `0x7f802000`, `0xfe01` → `0xffc02000`). - `v_fma_mix_f32` keeps a signalling NaN, f16 or f32, with IEEE 0, and quiets it with IEEE 1, payload kept - (`0x7f800001` → `0x7fc00001`). `v_fma_mixlo_f16` quiets every NaN in every MODE and keeps the top payload bits - (`0x7c01` → `0x7e01`, `0x7d55` → `0x7f55`, f32 `0x7fa00000` → `0x7f00`, f32 `0x7f800001` → `0x7e00`). -- **`v_exp_f16` and `v_log_f16` give gfx1031's counts exactly**, on all 65,536 inputs in the five MODEs of the f16 - transcendentals section: 0 ulp on every input that is not a NaN, with f16 denormals kept. With them flushed, 831 - `v_exp_f16` results and 1,023 `v_log_f16` operands become zero. Signalling NaNs are quieted only with IEEE 1, and - wave32 = wave64. - -**The translator against these words.** Each program was translated as a pixel shader and run on -`tests/semantic/spirv_mini_interp.py`, then compared with the hardware under the MODE the translator assumes for the -game (IEEE 0, DX10_CLAMP 1, f32 denormals flushed, f16 denormals kept). It gives the same word for the float -constants in every `op_sel`/`op_sel_hi` combination, for the integer constants as f16 halves, for clamp on values that -are not NaN, and for the f16 denormals. It differs in five ways, none fixed here: - -1. **f16 omod.** The translator applies `mul:2`/`mul:4`/`div:2` to every f16 result. The hardware ignores them in this - MODE (24 words: `v_add/mul/fma/fmac/exp/rcp_f16`). `v_cvt_f16_f32` drops its omod and clamp today, so its omod - matches by accident; #718 would make it apply. The two assumptions can't both hold for the game. Either its shaders - run with f16 denormals flushed, and keeping them is wrong, or every f16 omod in them does nothing. A corpus count - of omod on f16 instructions would decide, since a compiler that emits one expects it to act (LLVM folds an omod only - when "output denormals" are off, the `SIFoldOperands.cpp` comment quoted above). That count needs the game files. -2. **clamp of a NaN.** The interpreter refuses `FClamp` with a NaN operand, which GLSL.std.450 leaves undefined. The - hardware gives +0 with DX10_CLAMP 1, for `v_fmac_f16`, `v_fma_mixlo_f16` and `v_fma_mix_f32` alike (SHADER-186). -3. **Mix-op rounding.** The hardware rounds once (the section above). -4. **f32 denormal operands of the mix ops.** They are not flushed with `denorm_mode_32 = 0`: `0x00000001`, `0x807fffff` - and the integer constants `1` and `64` used as f32 give the denormal, where the hardware gives a zero of its sign - (compare SHADER-118 for the mad ops). -5. **NaN payloads.** Where the hardware keeps the payload and, with IEEE 0, the signalling bit, the translator writes - the canonical quiet NaN (`0x7fc00000`, `0x7e00`). For example, `v_fmac_f16` keeps `0x7c01`. This is the "not - modelled yet" note of the f16 transcendentals row in `docs/design.md`, here for these ops too. - -### Integer operations and scalar ALU verification (`tools/salu_diff.py`, gfx1036 follow-up to #1746) - -As a follow-up to #1746 (SHADER-137), `tools/salu_diff.py` and `tests/test_salu_diff.py` were expanded to include 12 integer SALU operations (`s_absdiff_i32`, `s_mul_hi_i32`, `s_lshl1..4_add_u32`, `s_sext_i32_i8`, `s_sext_i32_i16`, `s_flbit_i32`, and `s_pack_ll/lh/hh_b32_b16`) and tested on native desktop RDNA2 silicon (`gfx1036`), complementing #1746's laptop `gfx1035` probe. - -Hardware validation was executed via `tools/hw_oracle` and `tools/salu_diff.py` on native AMD RDNA2 silicon: - -- **GPU**: AMD Radeon(TM) Graphics (`gfx1036`), AMD Windows driver `32.0.21045.29003`, Windows 11, `amdhip64_6.dll`, AMD clang 23.0.0git (`rocm-sdk-core 10.0.0`). -- **Second-silicon verification of #1746 (`tools/int_hw_probe.py`)**: - - `python -I tools/int_hw_probe.py --oracle both --wave both`: **87 cases: 87 match, 0 known divergence, 0 unexpected mismatch, 0 wave32/64 diff** on native `gfx1036` (corroborating that the 5 divergences originally reported by #1746 are now fully resolved on `main`). -- **SALU operations (`s_absdiff_i32`, `s_mul_hi_i32`, `s_lshl1..4_add_u32`)**: - - `python -I tools/salu_diff.py --ops s_absdiff_i32,s_mul_hi_i32,s_lshl1_add_u32,s_lshl2_add_u32,s_lshl3_add_u32,s_lshl4_add_u32 --programs 500 --oracle translator,hw`: **500 passed, 0 mismatches**. - - Confirmed SCC preserved across operations with prior SCC=0 and SCC=1. -- **Sign-extension and pack (`s_sext_i32_i8`, `s_sext_i32_i16`, `s_flbit_i32`, `s_pack_ll/lh/hh_b32_b16`)**: - - `python -I tools/salu_diff.py --ops s_sext_i32_i8,s_sext_i32_i16,s_flbit_i32,s_pack_ll_b32_b16,s_pack_lh_b32_b16,s_pack_hh_b32_b16 --programs 500 --oracle translator,hw`: **500 passed, 0 mismatches**. - - `s_cmov_b32` verified on hardware under SCC=0 (destination preserved) and SCC=1 (destination loaded). -- **VALU product-sum (`v_mad_u64_u32`, `v_mad_i64_i32`)**: - - 292 programs in wave32 across special and random 32/64-bit inputs: **292 passed, 0 mismatches**. - - 192 programs in wave64 across special inputs: **192 passed, 0 mismatches**. - - Carry-out and sign bits in sdst matched the 65-bit ISA reference bit-for-bit. -- **Integer saturation (`clamp`)**: - - 567 programs tested across `v_add_nc_u32_e64`, `v_sub_nc_u32_e64`, `v_subrev_nc_u32_e64`, `v_add_nc_i32_e64`, `v_sub_nc_i32_e64`, `v_add_nc_u16_e64`, and `v_sub_nc_u16_e64`: **567 passed, 0 mismatches**. - - 16-bit clamp confirmed preserving the high 16 bits of the destination VGPR. -- **EXEC lane masking**: - - Multi-threaded kernel under alternating lane masks (`0xAAAAAAAA`, `0x55555555`) confirmed that inactive lanes write 0 in sdst mask words for `v_add_co_u32` and `v_mad_u64_u32`. -- **SAD family and lerp (`v_sad_u8`, `v_sad_hi_u8`, `v_sad_u16`, `v_sad_u32`, `v_msad_u8`, `v_mqsad_u32_u8`, `v_qsad_pk_u16_u8`, `v_mqsad_pk_u16_u8`, `v_lerp_u8`)**: - - Verified across edge byte patterns, 64-bit sliding windows, and zero masks: **0 mismatches** against ISA reference. -- **24-bit products and 64-bit shifts (`v_mul_hi_*24`, `v_lshrrev_b64`, `v_ashrrev_i64`)**: - - Verified across signed/unsigned products, edge signs, and 0..63 shift counts: **0 mismatches**. - -### Packed 16-bit integer operations on RDNA2 (SHADER-302) - -*Measured on an RDNA2 iGPU (gfx1036), Windows 11, AMD Windows driver 32.0.21045.29003, HIP backend (`amdhip64_6.dll`), AMD clang 23.0.0git (`rocm-sdk-core 10.0.0`).* - -380 raw compute kernels covering all 11 packed 16-bit integer instructions (`v_pk_add_u16`, `v_pk_sub_u16`, `v_pk_add_i16`, `v_pk_sub_i16`, `v_pk_mul_lo_u16`, `v_pk_mad_u16`, `v_pk_mad_i16`, `v_pk_max_u16`, `v_pk_min_u16`, `v_pk_max_i16`, `v_pk_min_i16`), tested in both wave32 and wave64: - -- **Constant operands under `op_sel` / `op_sel_hi`:** Integer constants under VOP3P are uniformly treated as 32-bit dwords `C`. When `op_sel[i] == 0`, bits `[15:0]` are selected; when `op_sel[i] == 1`, bits `[31:16]` are selected. Positive inline constants zero-extend (`5` → `0x00000005`: lo=`0x0005`, hi=`0x0000`; `64` → `0x00000040`: lo=`0x0040`, hi=`0x0000`). Negative inline constants sign-extend (`-1` → `0xFFFFFFFF`: lo=`0xFFFF`, hi=`0xFFFF`; `-16` → `0xFFFFFFF0`: lo=`0xFFF0`, hi=`0xFFFF`). 32-bit literals preserve their full dword (`0x12345678`: lo=`0x5678`, hi=`0x1234`; `0x80017fff`: lo=`0x7fff`, hi=`0x8001`). Float inline tokens (`0.5`, `1.0`, `-2.0`, `4.0`) assemble as their 32-bit IEEE 754 bit patterns (`1.0` → `0x3f800000`: lo=`0x0000`, hi=`0x3f80`). -- **`clamp` saturation:** Unsigned add/mad saturate to `0xFFFF`; unsigned sub saturates underflow to `0x0000`; signed add/sub/mad saturate to `[-32768, 32767]`. -- **Silicon vs Translator parity:** 380 of 380 kernels match bit-for-bit between native hardware and `tools/rdna2spirv.py` lowered to SPIR-V (0 mismatches, 0 wave32/wave64 differences). -### Pixel-shader ISA on the hardware (`tools/ps_oracle.py`, EGEN-TOOL-PS-ORACLE) - -`tools/hw_oracle` only launches compute kernels, so what only a pixel shader has (`v_interp_*` and the parameter -words the SPI writes into LDS, the barycentric VGPRs, exports and their formats, helper lanes) could not be -measured there. `tools/ps_oracle.py` runs hand-written RDNA2 pixel-shader ISA in a real draw on an AMD GPU, through -Vulkan's `VK_KHR_pipeline_binary`: - -1. `vk_harness` builds a pipeline from a template vertex + pixel shader and writes its binary (`VKH_BINARY_OUT`). - On the AMD Windows driver that is one PAL ELF: `.text` with `_amdgpu_gs_main` (the vertex stage) and - `_amdgpu_ps_main`, and a `.note` with the PAL metadata in msgpack, from which the driver programs the register - counts and the SPI setup (`spi_ps_input_ena/addr`, `spi_ps_input_cntl` per parameter, `spi_shader_col_format`). -2. The code under test is assembled with AMD clang (`LEONIDA_AMD_CLANG`, as for hw_oracle) and replaces - `_amdgpu_ps_main`; `.text` grows if needed and the pixel stage's VGPR/SGPR counts are raised to the registers - the code names. `--set PATH=JSON` changes a metadata entry as well, e.g. - `.graphics_registers/.spi_ps_input_cntl/0/.fp16_interp_mode=true`. -3. `vk_harness` builds the pipeline from the patched binary (`VKH_BINARY_IN`), draws one full-screen triangle into - an RGBA32F target and reads every pixel's four mrt0 dwords back bit for bit. - -The template sets what the code finds when it starts, so `--show-template` prints the template's own ISA and SPI -metadata to copy the conventions from. With the built-in `interp2` template on gfx1036 the pixel stage is wave64, -the perspective I/J barycentrics are in v0/v1, M0 comes from s2 (`s_mov_b32 m0, s2`), and parameters 0 and 1 are -the vertex shader's locations 0 = (u, v, 0, 1) and 1 = (u, v, 0, 0), u and v going 0..2 across the screen. - -```powershell -$env:LEONIDA_VK_DEVICE = "radeon" -python -I tools/ps_oracle.py --build --template interp2 --show-template -python -I tools/ps_oracle.py --build --template interp2 --asm body.s --size 4 1 [--json out.json] -``` - -Checked on an AMD Radeon iGPU (gfx1036, Windows driver 26.10.1): the driver accepts a patched binary (there is no -check over the code), the patched code runs as the pixel shader, and `v_interp_p1/p2_f32` of `attr0.x` at the four -pixel centres of a 4 x 1 target gives u = 0.125, 0.375, 0.625, 0.875, with `v_interp_mov_f32` reading the -parameter words P0 = 0 and P10 = 2.0 (`tests/test_ps_oracle.py`, which runs it on hardware when -`LEONIDA_PS_ORACLE_BUILD` names a runtime build). On other drivers the binary is not a single PAL ELF (the NVIDIA -driver returns two blobs) and the tool exits 77. - -`--format` picks the color target (rgba32f by default; rgba16f/unorm/snorm/u/i, rg32f, r32f, rgba8*, rgb10a2unorm, -...), and the driver picks the export format for it as for a game pipeline; the readback is the target's texels as -stored. Measured on gfx1036 with the `const` template (EGEN-TOOL-PS-ORACLE-FORMATS): - -| Target | `col_0_export_format` | What reaches the target | -|---|---|---| -| RGBA32F, RGBA32_UINT | 9 (32_ABGR) | the four exported dwords as they are; a channel exported as `off` is 0 | -| RG32F | 2 (32_GR) | R = the last enabled of x, z; G = the last enabled of y, w (all four enabled: z, w) | -| R32F | 1 (32_R) | the last enabled channel (all four enabled: w) | -| RGBA16F, RG16F, RGBA8_UNORM/SNORM, RGB10A2 | 4 (FP16_ABGR) | a `compr` export's halves as f16, converted by the CB; an f16 NaN half becomes `0xfe00` in an f16 target, 0 in a normalized one | -| RGBA16 UNORM/SNORM/UINT/SINT, RG16_UNORM | 5 / 6 / 7 / 8 | a `compr` export's 16-bit halves bit for bit (unorm16/snorm16/integer values, not f16) | -| RGBA8_UINT | 7 (UINT16_ABGR) | the 16-bit halves clamped to 255 | - -A 16-bit export format takes a `compr` export; an uncompressed one into it is not meaningful (the target got the z -and w dwords). Limits: one draw of one triangle, mrt0 only; the vertex -stage is the template's, compiled by the driver; the SPI behaviour comes from the driver's metadata, so a `--set` -the hardware does not support is not refused here. - -### Packed 16-bit integer operations on RDNA2 (SHADER-302) - -*Measured on an RDNA2 iGPU (gfx1036), Windows 11, AMD Windows driver 32.0.21045.29003, HIP backend (`amdhip64_6.dll`), AMD clang 23.0.0git (`rocm-sdk-core 10.0.0`).* - -380 raw compute kernels covering all 11 packed 16-bit integer instructions (`v_pk_add_u16`, `v_pk_sub_u16`, `v_pk_add_i16`, `v_pk_sub_i16`, `v_pk_mul_lo_u16`, `v_pk_mad_u16`, `v_pk_mad_i16`, `v_pk_max_u16`, `v_pk_min_u16`, `v_pk_max_i16`, `v_pk_min_i16`), tested in both wave32 and wave64: - -- **Constant operands under `op_sel` / `op_sel_hi`:** Integer constants under VOP3P are uniformly treated as 32-bit dwords `C`. When `op_sel[i] == 0`, bits `[15:0]` are selected; when `op_sel[i] == 1`, bits `[31:16]` are selected. Positive inline constants zero-extend (`5` → `0x00000005`: lo=`0x0005`, hi=`0x0000`; `64` → `0x00000040`: lo=`0x0040`, hi=`0x0000`). Negative inline constants sign-extend (`-1` → `0xFFFFFFFF`: lo=`0xFFFF`, hi=`0xFFFF`; `-16` → `0xFFFFFFF0`: lo=`0xFFF0`, hi=`0xFFFF`). 32-bit literals preserve their full dword (`0x12345678`: lo=`0x5678`, hi=`0x1234`; `0x80017fff`: lo=`0x7fff`, hi=`0x8001`). Float inline tokens (`0.5`, `1.0`, `-2.0`, `4.0`) assemble as their 32-bit IEEE 754 bit patterns (`1.0` → `0x3f800000`: lo=`0x0000`, hi=`0x3f80`). -- **`clamp` saturation:** Unsigned add/mad saturate to `0xFFFF`; unsigned sub saturates underflow to `0x0000`; signed add/sub/mad saturate to `[-32768, 32767]`. -- **Silicon vs Translator parity:** 380 of 380 kernels match bit-for-bit between native hardware and `tools/rdna2spirv.py` lowered to SPIR-V (0 mismatches, 0 wave32/wave64 differences). -### Pixel-shader ISA on the hardware (`tools/ps_oracle.py`, EGEN-TOOL-PS-ORACLE) - -`tools/hw_oracle` only launches compute kernels, so what only a pixel shader has (`v_interp_*` and the parameter -words the SPI writes into LDS, the barycentric VGPRs, exports and their formats, helper lanes) could not be -measured there. `tools/ps_oracle.py` runs hand-written RDNA2 pixel-shader ISA in a real draw on an AMD GPU, through -Vulkan's `VK_KHR_pipeline_binary`: - -1. `vk_harness` builds a pipeline from a template vertex + pixel shader and writes its binary (`VKH_BINARY_OUT`). - On the AMD Windows driver that is one PAL ELF: `.text` with `_amdgpu_gs_main` (the vertex stage) and - `_amdgpu_ps_main`, and a `.note` with the PAL metadata in msgpack, from which the driver programs the register - counts and the SPI setup (`spi_ps_input_ena/addr`, `spi_ps_input_cntl` per parameter, `spi_shader_col_format`). -2. The code under test is assembled with AMD clang (`LEONIDA_AMD_CLANG`, as for hw_oracle) and replaces - `_amdgpu_ps_main`; `.text` grows if needed and the pixel stage's VGPR/SGPR counts are raised to the registers - the code names. `--set PATH=JSON` changes a metadata entry as well, e.g. - `.graphics_registers/.spi_ps_input_cntl/0/.fp16_interp_mode=true`. -3. `vk_harness` builds the pipeline from the patched binary (`VKH_BINARY_IN`), draws one full-screen triangle into - an RGBA32F target and reads every pixel's four mrt0 dwords back bit for bit. - -The template sets what the code finds when it starts, so `--show-template` prints the template's own ISA and SPI -metadata to copy the conventions from. With the built-in `interp2` template on gfx1036 the pixel stage is wave64, -the perspective I/J barycentrics are in v0/v1, M0 comes from s2 (`s_mov_b32 m0, s2`), and parameters 0 and 1 are -the vertex shader's locations 0 = (u, v, 0, 1) and 1 = (u, v, 0, 0), u and v going 0..2 across the screen. - -```powershell -$env:LEONIDA_VK_DEVICE = "radeon" -python -I tools/ps_oracle.py --build --template interp2 --show-template -python -I tools/ps_oracle.py --build --template interp2 --asm body.s --size 4 1 [--json out.json] -``` - -Checked on an AMD Radeon iGPU (gfx1036, Windows driver 26.10.1): the driver accepts a patched binary (there is no -check over the code), the patched code runs as the pixel shader, and `v_interp_p1/p2_f32` of `attr0.x` at the four -pixel centres of a 4 x 1 target gives u = 0.125, 0.375, 0.625, 0.875, with `v_interp_mov_f32` reading the -parameter words P0 = 0 and P10 = 2.0 (`tests/test_ps_oracle.py`, which runs it on hardware when -`LEONIDA_PS_ORACLE_BUILD` names a runtime build). On other drivers the binary is not a single PAL ELF (the NVIDIA -driver returns two blobs) and the tool exits 77. Limits: one draw of one triangle, mrt0 as RGBA32F only; the vertex -stage is the template's, compiled by the driver; the SPI behaviour comes from the driver's metadata, so a `--set` -the hardware does not support is not refused here. - -**On Linux (RADV).** Mesa's RADV returns the pipeline as one binary per stage, as `radv_shader_serialize` writes it -(Mesa 26.3 `radv_pipeline_cache.c`, structs in `radv_shader.h`): a type word, `struct ac_shader_config` (`num_sgprs`, -`num_vgprs`, ..., `rsrc1`), `struct radv_shader_info`, `total_size`, then `code_size`, `exec_size` and the other -sizes, then stats, code, IR and disassembly. The info struct's size changes between Mesa versions, so the tool finds -the fields from their values: the size block whose sizes add up to `total_size`, the pixel stage from the -`wave_size, ., stage = 4 (fragment), next_stage = none` bytes in the info, and `rsrc1` as the config word whose -VGPRS field is `(num_vgprs - 1) / (wave32 ? 8 : 4)` (`radv_postprocess_binary_config`) and whose FLOAT_MODE equals -`float_mode`. A layout where these do not agree is refused (exit 77), not guessed. The code is replaced, the sizes -are fixed, and `num_vgprs`/`num_sgprs` and rsrc1's VGPRS are raised; RADV builds an imported binary with -`radv_shader_create_uncached` (no cache lookup by key) and programs `SPI_SHADER_PGM_RSRC1_PS` from `rsrc1`. Two -limits: `--set` is refused (RADV keeps the SPI setup in its own structs, so a template has to ask for what it -needs), and only GFX10 (RDNA1/RDNA2) devices are taken, from the chip name RADV puts in the device name; GFX11 and -later interpolate with `lds_param_load` instead of `v_interp_*`, so e.g. an RX 9070 XT (`RADV GFX1201`) gets -`unsupported architecture` and exit 77. -### Packed 16-bit integer operations on RDNA2 (SHADER-302) - -Mesa optimises varyings across stages, so a template's parameter layout can differ from the Windows driver's: -RADV moves `interp2`'s `in0 + in1` into the vertex shader and the pixel shader reads one parameter, attr0 = -(2u, 2v, 0, 1); `--show-template` shows the layout a run gets. - -```sh -LEONIDA_VK_DEVICE=raphael python -I tools/ps_oracle.py --build --template interp2 --show-template -``` - -Checked on the Ryzen 7 9800X3D iGPU (`RADV RAPHAEL_MENDOCINO`, gfx1036, wave64 pixel stage, Mesa 26.3.1, CachyOS): -the Windows check's `attr0.x` code (with `v40`, past the template's 8 VGPRs) gives u = 0.25, 0.75, 1.25, 1.75, -P0 = 0 and P10 = 4.0 for the single parameter, and a second patch with another constant changes the result (nothing -is cached). - -- **Constant operands under `op_sel` / `op_sel_hi`:** Integer constants under VOP3P are uniformly treated as 32-bit dwords `C`. When `op_sel[i] == 0`, bits `[15:0]` are selected; when `op_sel[i] == 1`, bits `[31:16]` are selected. Positive inline constants zero-extend (`5` → `0x00000005`: lo=`0x0005`, hi=`0x0000`; `64` → `0x00000040`: lo=`0x0040`, hi=`0x0000`). Negative inline constants sign-extend (`-1` → `0xFFFFFFFF`: lo=`0xFFFF`, hi=`0xFFFF`; `-16` → `0xFFFFFFF0`: lo=`0xFFF0`, hi=`0xFFFF`). 32-bit literals preserve their full dword (`0x12345678`: lo=`0x5678`, hi=`0x1234`; `0x80017fff`: lo=`0x7fff`, hi=`0x8001`). Float inline tokens (`0.5`, `1.0`, `-2.0`, `4.0`) assemble as their 32-bit IEEE 754 bit patterns (`1.0` → `0x3f800000`: lo=`0x0000`, hi=`0x3f80`). -- **`clamp` saturation:** Unsigned add/mad saturate to `0xFFFF`; unsigned sub saturates underflow to `0x0000`; signed add/sub/mad saturate to `[-32768, 32767]`. -- **Silicon vs Translator parity:** 380 of 380 kernels match bit-for-bit between native hardware and `tools/rdna2spirv.py` lowered to SPIR-V (0 mismatches, 0 wave32/wave64 differences). -#### Helper lanes at a triangle edge (`tools/ps_helper_probe.py`, SHADER-681) - -What a pixel wave does with the helper lanes of a partly covered 2x2 quad, which the translator's EXEC model and -`s_wqm` lowering depend on (`docs/design.md` row "Whole-quad mode"). The probe draws one triangle, (-1, -1), (1.3, -1), -(-1, 0.9), into a 16 x 16 target, so its edge cuts quads; the varying is the vertex position, so each lane's -interpolated value is its own pixel centre. The template pixel shader takes a derivative, so the driver builds it as -a shader that needs quads. Seven wave64 programs replace the pixel shader. A helper is never written to the target, -so a covered lane of the same quad reads the helper's registers through DPP `quad_perm` and exports them. - -```sh -LEONIDA_VK_DEVICE=raphael python -I tools/ps_helper_probe.py --build [--json out.json] -``` - -On the Ryzen 7 9800X3D iGPU (`RADV RAPHAEL_MENDOCINO`, gfx1036, Mesa 26.3.1): 137 covered pixels in three waves, -25 (covered lane, helper neighbour) pairs, and all 10 checks hold in three runs, with identical words except an -unwritten helper register: - -| check | gfx1036 | -|---|---| -| entry EXEC | exactly the covered pixels: helpers start off | -| `s_wqm_b64 exec, exec` | turns on exactly the quads with a covered pixel | -| wave layout | quads packed from lane 0; a quad with no covered pixel is not in the wave | -| lane order in a quad | lane % 4 = (x & 1) + 2 (y & 1): top-left, top-right, bottom-left, bottom-right | -| a helper's `v_interp_p1/p2_f32` after `s_wqm` | its own pixel centre, extrapolated (error 1.64e-4, as covered) | -| a helper's v0/v1 without `s_wqm` | already its own pixel's I/J (to 7e-5; I + J > 1, outside the triangle) | -| a helper's VGPR without `s_wqm` | not written (an unwritten register, different in every run) | -| EXEC without `s_wqm` | stays the entry mask | -| DPP without `fi` from an inactive lane | leaves the destination unchanged | -| `exp mrt0 ... done vm` with helpers on in EXEC | writes no pixel outside the triangle | - -The last row is what the driver's own code relies on: RADV compiles the template as `s_wqm_b64 exec, exec` at entry, -then the interpolation and an `exp mrt0 ... done vm` with the helpers still on. The programs are wave64; a wave32 -pixel stage (`RADV_PERFTEST=pswave32`) and GFX11+ exit 77. Not measured: wave32, RDNA1/gfx1013 and the Windows driver. - -### Packed 16-bit integer operations on RDNA2 (SHADER-302) - -*Measured on an RDNA2 iGPU (gfx1036), Windows 11, AMD Windows driver 32.0.21045.29003, HIP backend (`amdhip64_6.dll`), AMD clang 23.0.0git (`rocm-sdk-core 10.0.0`).* - -380 raw compute kernels covering all 11 packed 16-bit integer instructions (`v_pk_add_u16`, `v_pk_sub_u16`, `v_pk_add_i16`, `v_pk_sub_i16`, `v_pk_mul_lo_u16`, `v_pk_mad_u16`, `v_pk_mad_i16`, `v_pk_max_u16`, `v_pk_min_u16`, `v_pk_max_i16`, `v_pk_min_i16`), tested in both wave32 and wave64: - -- **Constant operands under `op_sel` / `op_sel_hi`:** Integer constants under VOP3P are uniformly treated as 32-bit dwords `C`. When `op_sel[i] == 0`, bits `[15:0]` are selected; when `op_sel[i] == 1`, bits `[31:16]` are selected. Positive inline constants zero-extend (`5` → `0x00000005`: lo=`0x0005`, hi=`0x0000`; `64` → `0x00000040`: lo=`0x0040`, hi=`0x0000`). Negative inline constants sign-extend (`-1` → `0xFFFFFFFF`: lo=`0xFFFF`, hi=`0xFFFF`; `-16` → `0xFFFFFFF0`: lo=`0xFFF0`, hi=`0xFFFF`). 32-bit literals preserve their full dword (`0x12345678`: lo=`0x5678`, hi=`0x1234`; `0x80017fff`: lo=`0x7fff`, hi=`0x8001`). Float inline tokens (`0.5`, `1.0`, `-2.0`, `4.0`) assemble as their 32-bit IEEE 754 bit patterns (`1.0` → `0x3f800000`: lo=`0x0000`, hi=`0x3f80`). -- **`clamp` saturation:** Unsigned add/mad saturate to `0xFFFF`; unsigned sub saturates underflow to `0x0000`; signed add/sub/mad saturate to `[-32768, 32767]`. -- **Silicon vs Translator parity:** 380 of 380 kernels match bit-for-bit between native hardware and `tools/rdna2spirv.py` lowered to SPIR-V (0 mismatches, 0 wave32/wave64 differences). - - -### Real pixel shaders on two GPUs (`tools/ps_sweep.py`, `runtime/test/vk_ps_sweep.cpp`) - -The oracles above run hand-written programs. This one draws translated corpus pixel shaders, to find what only real -shaders trigger. `ps_sweep.py sample` takes a fixed-seed stratified sample of the translated pixel shaders (strata: -needs barycentrics, descriptor bindings none / 0-3 only / any above 3, control-flow style; at least 10 per stratum, -the rest in proportion). `vk_ps_sweep` draws one of them with a generated vertex shader (a viewport-covering triangle -and a vec4 at every input location), the runtime's bindless set 0 with only its fallbacks, a zeroed 1 MiB heap, the -push-constant block and 32x32 `RGBA32F` targets cleared to -1. Everything is identical on every GPU, so the same -sample can be run on each and compared; `ps_sweep.py compare` classifies each shader: OK on both, differs beyond -tolerance (1e-3 absolute plus relative), NaN or all-zero on one GPU only, fails on one GPU, fails on both, timeout. -When both workers exit successfully, `compare` requires matching target counts (1–8) and exactly 16,384 bytes per -target in each raw file (32 × 32 pixels × 16 bytes). A missing file, a wrong byte length or an invalid or mismatched -count is reported as `invalid readback`, not as a GPU result. Failed and timed-out draws are classified by exit -code without reading either file. The size check establishes completeness; this command still compares float values -with tolerance, not byte-for-byte equality. -Variant `t` (`VKS_TEX=1`) replaces the fallback images with an 8x8 gradient (2D, 2D array, 1D, 3D) and a linear -sampler so sampled values are not all zero. - -Warning: a few sampled shaders hang NVIDIA GPUs with the zeroed heap (see "Fails on one GPU, NVIDIA" below). The -`--timeout` of `ps_sweep.py run` only bounds the wait on the host side; the driver resets the GPU (TDR). On a GPU that -also drives the display the desktop freezes until each reset (a tester saw five in six minutes on an RTX 3060 around -shaders 120 to 310 of the 480). Run it on a GPU with no display attached, or expect a freeze of a few seconds per hang; -`--lo`/`--hi`/`--only` run part of the sample. - -RTX 4080 SUPER and Intel UHD 770 (32.0.101.6129), Windows 11, 480 of 12,101 pixel shaders (seed 20261122): - -| class | variant z (fallback images) | variant t (gradient textures) | -|---|---|---| -| OK on both | 262 | 260 | -| differs beyond tolerance | 0 | 1 | -| NaN or zero on one GPU only | 0 | 0 | -| fails on one GPU | 214 | 215 | -| fails on both | 0 | 0 | -| timeout (both) | 4 | 4 | - -- **Fails on one GPU, Intel (210 in both variants):** the module needs `fragmentShaderBarycentric` (206) or - `shaderResourceMinLod` (3) or both (1), and the UHD 770 has neither feature. The runtime's barycentric fallback is not - part of this sweep. 5,298 of the 12,101 pixel shaders need barycentrics and 29 need MinLod. -- **Fails on one GPU, NVIDIA (4 in z, 5 in t):** `VK_ERROR_DEVICE_LOST` after a few seconds while the Intel GPU - returns at once with every pixel unwritten. All are tier C shaders; in the one disassembled, a scalar loop reads a - list from a buffer until an entry's low 16 bits are `0xffff`, and the zeroed heap has no terminator, so the loop - never ends. A 10-line GLSL - fragment shader with the same loop (`while ((heap[i] & 0xffff) != 0xffff) i++;` on a zeroed buffer reached through - its device address) hangs the same way. The synthetic input, not the translation, is the cause; a real heap holds the - terminator. -- **Timeout (4, both GPUs, 40 s):** large `dispatch loop` shaders; not root-caused. -- **Differs beyond tolerance (1, variant t):** a tier C shader (`wave64_graphics` C), 92 of 4,096 values of one target - (about 2 % of the pixels), differences up to 0.06. It is identical with a constant texture and with a NEAREST sampler, - so the cause is the two GPUs' linear-filter weights, not the translation. -- The 262 / 260 shaders that run on both agree to 4.9e-4 at most; 239 of the 260 in variant t are bit-identical. - Of those, 107 write non-zero values and 153 write only zeros or nothing (a shader whose descriptors come from a - zeroed heap mostly samples zero or discards). That is the limit of the synthetic inputs: a - seeded heap was tried and abandoned, because a pointer read from float data is a wild address and takes NVIDIA's - device down. - -**With the fallbacks (`--bary-fallback` plus the MinLod fallback of #4642, same 480 shaders, variant z).** The same sample was -retranslated with both flags and drawn through `.bary_gs.spv` where a shader reads raw barycentrics (`VKS_GS`, -`tools/bary_fallback_gs.py`). The Intel UHD 770 creates 440 of the 480 (265 before; the 207 that needed -`fragmentShaderBarycentric` or `shaderResourceMinLod` are gone), 32 time out (zeroed-heap loops, which the same -translation also hits on the RTX 4080 SUPER), and 8 are not translated (`computed I/J pair under --bary-fallback`, -#3898). Intel against NVIDIA on the same fallback translation: 434 OK on both, 0 differ, 4 NVIDIA device losses -(the unterminated loop above), 8 not translated, 34 timeouts on both. Intel with the fallbacks against NVIDIA with -the default translation: 373 OK, 53 differ by more than 0.1 and 8 are NaN on one side. The same 61 differ between the -two translations on NVIDIA alone, so it is the translation, not the GPU. **Cause (counted on the same 480 translated -again, `--bary-fallback` alone, without the MinLod flag of #4642, against the default):** 199 modules differ between the two translations, 190 that read a -16-bit interpolant (`v_interp_p1ll/p1lv/p2_f16`) and the 9 that read raw barycentrics; the other 273 translated under -both are byte-identical, so ordinary `v_interp_p1/p2/mov_f32` is not translated differently (the remaining 8 are not -translated under the fallback). `--bary-fallback` has no `PerVertexKHR` inputs, so a 16-bit interpolant is read as the -smooth f32 of its packed word (design.md, "16-bit interpolation"); `--f16-interp-fallback` is its companion, and -`make_game.py` turns it on with it wherever the device has no per-vertex inputs, as an Intel UHD has none. The sweep -used the first flag without the second, and its generated vertex shader wrote the decoded halves nowhere. The synthetic -`ps_interp_f16_high` drawn with `vs_f16_pack` agrees: with `--bary-fallback` alone its f16 halves are off by 0.984 on -both GPUs, with both flags and by default they are within 2e-3 on both, and `ps_interp_f32_mods` / `ps_interp_mov_mods` -(plain f32 and mov reads) are exact with `--bary-fallback`. `ps_sweep.py` now builds the vertex shader of a pixel -shader with `f16_halves` in its index entry so that the halves are decoded from the same words a default translation -reads per vertex. An exhaustive follow-up on all `480` sampled shaders (`--seed 20261122`, `main` at `dde82f27e`) -and all `12,101` PS confirmed this on an AMD Radeon RX 6650 XT (RDNA2, Windows 11 driver `32.0.21045.29003`, -`vk_ps_sweep` variant `z`, `--timeout 30`): `29` of `12,101` PS use `MinLod` (`image_sample_d_cl`, `273` occurrences; -`10` also have `v_interp_*_f16`, `0` read raw barycentrics), and `0` of the `480` sampled PS declare `MinLod`, so -the MinLod fallback plays no part in this `480`-shader difference. Across the `480` shaders, `272` modules are -byte-identical across all three translations, `10` are refused (`computed I/J pair under --bary-fallback`), and -`198` differ (`186` reading `v_interp_*_f16` — all `186` using `high` — `12` reading raw barycentrics with -`.bary_gs.spv`, `0` combining both in the sample; across all `12,101` PS, `5` combine both, of which `3` translate -under `--bary-fallback --f16-interp-fallback` + `.bary_gs.spv` and `2` hit `computed I/J pair under --bary-fallback`). -On the `198` differing shaders on the RX 6650 XT, `default` vs `--bary-fallback` alone gave `90` OK on both (all `12` -raw-bary GS draws plus `78` `v_interp_*_f16`), `54` differing beyond tolerance (`53` gross `>0.1`, `1` moderate -`>1e-2`), `9` NaN or zero on one side (`8` NaN on `default` only with `371`/`507`/`960` NaNs, `1` zero on `default` -only), `12` driver crashes on both (`0xC0000005`, unchanged with an 8 MiB stack), and `33` timeouts; all `63` -differing/NaN/zero draws are `v_interp_*_f16` shaders where the default sweep vertex shader without `f16_halves` wrote -smooth `[0, 1]` `f32` bits that `PerVertexKHR` `UnpackHalf2x16` interpreted as negative or large `f16` values (feeding -`sqrt`/`log`/`pow`), whereas `--bary-fallback` alone read the positive smooth `f32` values directly. Re-running the -same `198` shaders with `--bary-fallback --f16-interp-fallback` gave `153` OK on both (`141` `v_interp_*_f16` + all -`12` raw-bary GS), `0` differing, `0` NaN/zero mismatch, `12` failures on both, and `33` timeouts, with `153/153` -completing draws (`89` non-clear exact + `64` clear-only exact across `573/573` targets) bit-for-bit identical under -`ps_sweep.py compare --exact`. All `3` whole-corpus shaders combining raw barycentrics and `v_interp_*_f16` also draw -bit-for-bit identically (`3/3` draws, `11/11` targets) against `default` on the RX 6650 XT. - -## Coverage plan and cost - -Start with straight-line scalar/vector ALU because it is deterministic, needs no descriptors and -covers the operations most shaders use. Then add, in order: - -1. **EXEC/VCC and `cndmask`.** Per-lane masking and scalar state are where a one-lane-per-invocation - translator differs most from hardware. -2. **16-bit arithmetic and partial writes.** `v_add/sub/mul/fma_f16`, `op_sel`, destination-half - preservation, packed ops. The translator's contract calls out which forms keep the high half; - those rules need value tests. -3. **Branches and loops.** Modelled control flow, then irreducible graphs and the dispatch-loop form. - The existing control-flow unit tests check graph structure; differential tests check the values. - `tools/cf_diff.py` (FUZZ-8) does this for whole waves: seeded programs built from the shapes - compilers emit (saveexec if/else, `v_cmpx`, VCC- and SCC-voted branches, uniform and per-lane - loops, two-entry cycles), run by `tools/cf_ref.py` (cpu_ref plus branches, compares and saveexec) - and by `tests/semantic/spirv_wave_interp.py` (every invocation of a subgroup, with structured - reconvergence), compared lane by lane in both the structured and the dispatch-loop form. - The corpus-side counterpart is `tools/ab_control_flow.py`: it renders branchy pixel shaders - translated both ways (real loops and conditionals, and `--dispatch-loop`) and compares the two - images byte for byte. It needs a finished shaders stage and `runtime/build/vk_texture_test`, and - writes the outcome of each shader to `outcomes.tsv`. -4. **LDS, global memory, buffers and images.** These need a memory model and descriptor setup; the - existing `vk_compute_test`/`vk_store_test`/`vk_texture_test` programs show the shape. -5. **Wave operations.** Ballot, shuffles, DPP, `readlane`/`writelane`, `permlane`, `mbcnt`, and the - wave64 split on 32-wide subgroups. These are the largest semantic gap and need a 64-lane model - plus a subgroup-size-aware host. `tools/crosslane_fuzz.py` (FUZZ-7, above) is that model, run on - the GPU. -6. **Pixel interpolation and exports.** Barycentrics, per-vertex inputs, compressed exports, MRT and - depth. The existing GPU tests already pin several of these; a CPU model makes them differential. - -Cost is dominated by the GPU dispatch and pipeline creation, not by the Python interpreter. A small -case is one `llvm-mc` run, one translation, one `spirv-as` + `spirv-val`, one pipeline and one -dispatch: seconds per case on a desktop GPU. The interpreter is milliseconds for the programs in this -subset. A suite of a few hundred cases is practical locally; running every corpus shader is not the -goal, because many need descriptors and data the harness cannot invent. The useful target is a -hand-picked suite that covers each instruction family and each known semantic trap, plus seeded -fuzzing over operand values and lane masks within that suite. - -## What this cannot model - -The prototype and the first harness stage deliberately do not cover: - -- **Descriptors.** T#/V#, S# and `s_load`/`image_*`/`buffer_*` need realistic descriptor memory and - binding setup. A wrong descriptor is indistinguishable from a wrong translation. -- **Interpolation.** `v_interp_p1/p2/mov` depend on rasterization state, barycentric conventions and - the pixel center. The CPU model would need the same triangle and sample positions as the GPU. -- **Wave operations.** Ballot, shuffles, DPP, permlane and cross-half wave64 behaviour need a full - 64-lane model and a GPU whose subgroup size matches the wave. On a 32-wide subgroup host, a wave64 - program is not the same execution. The one-lane interpreter still can't run them; the GPU fuzzer - `tools/crosslane_fuzz.py` covers them instead, with wave64 checked through `--wave64-emulate`. -- **Memory and LDS.** Address spaces, out-of-bounds rules, atomics, ordering and barriers. These are - modelled later, with the same "unsupported, never guessed" rule. -- **Transcendentals and approximation.** `v_rcp_f32`, `v_rsq_f32`, `v_exp_f32`, `v_log_f32` and the - trig instructions have implementation-defined accuracy. The other project handled a 5–14 ulp - reciprocal difference by computing an envelope, not by demanding a bit match. A differential test - should either use exact instructions or compare within a documented tolerance/envelope. -- **The MODE register and rounding modes.** The translator skips `s_setreg`; the CPU model assumes - round-to-nearest and gradual underflow. Tests that depend on flush-to-zero or round-toward-zero are - out of scope until the harness sets and checks those modes. -- **NaN payloads and signed-zero corner cases in min/max/clamp.** Vulkan leaves some of this - implementation-defined. Compare NaNs by class, and pin only the cases the ISA defines. -- **Wave-size-dependent operand forms.** `v_cndmask_b32` takes a 32-bit SGPR mask in wave32 and an - `s[lo:hi]` pair in wave64. The model follows the form printed in the listing; a listing assembled - for the wrong wave size is a test bug, not a translator result. -- **Scheduling and hazards.** The model is sequential. It does not test wait counts, dependency - stalls, or whether two instructions can overlap. Those are hardware timing properties, not - arithmetic results. - -Growing the model means adding one instruction family at a time, with a hand-written test and a -pinned expected value, and removing the `Unsupported` path for that family. A family that cannot be -modelled faithfully stays a reported skip; it is never approximated silently. - -## Prior art - -The technique is described in another project's write-ups; no code from them is copied. - -- [Xbox Series shaders](https://github.com/realdody/americas-recomp/blob/xbox-series/docs/xbox/XBOX_SHADERS.md), - sections "Execution harness" and "A CPU reference for small real shaders". -- [tools/xbox README](https://github.com/realdody/americas-recomp/blob/xbox-series/tools/xbox/README.md), - which describes `exec` and the check against a Python reference. - -Their reported numbers, as a scale reference only: 183 of 872 compute shaders of 3,000 bytes or less -gave byte-identical CPU/GPU results, with none differing and 687 skipped; for shaders up to 1,500 -bytes the later run reported 242 matches, 1 mismatch (reciprocal precision), 2 harness failures and -435 skips; the pixel-shader run reported 157 bit-identical, 0 differing and 581 skips. The numbers -are context for the scale of the approach, not a result of this change. - -The other project is GPL-2.0-only and this one is GPL-3.0-or-later. The design above is an -independent implementation from the ISA and from LLVM's disassembly; the links are for the technique -and the reported results, not for code. - -## Deliberate limits of this change - -This change adds the design, the CPU prototype and its unit tests. It does not modify -`tools/rdna2spirv.py`, does not add a GPU runner, and does not use game data. The prototype is useful -now because it pins the semantics of the first instruction families and gives the future harness a -reference that fails loudly on anything it does not understand. diff --git a/docs/story.md b/docs/story.md deleted file mode 100644 index a0a0e1770..000000000 --- a/docs/story.md +++ /dev/null @@ -1,614 +0,0 @@ -# Story and minigame archives - -This page measures the `story000` and `shared_minigame000` archive family in the Xbox 1.0.2.1 -package. It is a container survey, not a resource decoder: the RPF9 table of contents is still -encrypted, so counts come from the data area and from fixed headers, never from names or paths. -Everything below is aggregate. No game payload, path or name is stored in this repository. - -## Archives and index - -Sizes are exact bytes from the package; `data offset` is the little-endian u32 at file offset 4. -A full index of `story000.rpf` was not completed (see the layout section); its headline row is the -first 1 GiB of the data area, and the full-file non-inflating signature scan is reported separately. - -| Archive | File size | Data offset | Scope | Streams | Stored | Inflated | Zero padding | Unread | Readable | Elapsed | -|---|---:|---:|---|---:|---:|---:|---:|---:|---:|---:| -| `story000.rpf` | 20,022,508,672 (18.65 GiB) | 0xA120 | first 1 GiB of data area | 55,284 | 1,002,413,457 | 3,963,061,696 | 67,544,007 | 3,803,929 | 93.4% | 44.0 s | -| `shared_minigame000.rpf` | 810,581,008 (773.03 MiB) | 0xFB0 | full | 5,073 | 443,771,951 | 928,713,043 | 4,723,814 | 362,081,227 | 54.7% | 24.5 s | -| `story000_script.rpf` | 78,023,728 (74.41 MiB) | 0x2B0 | full | 2,632 | 20,408,094 | 74,729,504 | 4,585,959 | 53,028,987 | 26.2% | 4.5 s | -| `story000_restofworld.rpf` | 198,354,992 (189.17 MiB) | 0xA40 | full | 631 | 188,163,116 | 255,343,231 | 862,330 | 9,326,922 | 94.9% | 1.0 s | -| `story000_bvh4.rpf` | 5,632 | 0x340 | full | 4 | 1,795 | 16,677 | 2,849 | 156 | 37.4% | 0.004 s | -| `shared_minigame000_bvh4.rpf` | 61,987,040 (59.12 MiB) | 0x4F0 | full | 2,560 | 59,142,787 | 970,044,012 | 2,672,073 | 170,916 | 95.4% | 2.65 s | - -Readable is the carver's `stored / span`; Bink 2 streams count as readable. The first `story000` -row scans file offsets `0xA120`-`0x4000A11F`. - -A first full 20 GB walk was stopped at 72% (about 14.4 billion bytes, 106,000 streams) with one process at -8.5 GB in memory. A later full walk with `tools/story_index.py` (after #2726 stopped the scanners copying the -gaps between streams) completes in about 10 minutes and is the full index below; no zlib candidate in the -archive inflates past 512 MiB. - -**Full index.** `python -I tools/story_index.py story000.rpf out.json` over all 20,022,508,672 bytes: -**141,385 streams**, 10,231,531,520 bytes stored (51.1% of the span) and 17,094,635,373 inflated, 182,253,050 -bytes of zero padding and 9,608,682,854 unread (the raw `RSC8` region). By class: zero-prefix 56,228, `0DRP` -48,084, `42 40 00 00` 5,589, `PSIN` 5,348, type-hash 1,393, clip-stream 875, Bink 2 264, MoVE 119, XML 32, and -23,327 streams in 12,463 other first-word classes. By 1 GiB bucket (a stream counts where it starts, so a bucket -whose streams run into the next one is shown as 100%): - -| GiB | Streams | Stored | Inflated | Readable | Main classes | -|---:|---:|---:|---:|---:|---| -| 0 | 55,282 | 1,002,378,056 | 3,963,018,176 | 93.4% | zero-prefix 22,679, `0DRP` 21,980 | -| 1 | 18,210 | 1,045,208,660 | 1,484,948,432 | 97.3% | zero-prefix 15,640 | -| 2 | 13,901 | 1,055,312,755 | 1,880,941,536 | 98.3% | zero-prefix 7,464, `0DRP` 3,067, type-hash 459 | -| 3 | 2,020 | 1,068,996,430 | 1,487,761,024 | 99.6% | zero-prefix 1,302 | -| 4 | 2,340 | 463,305,742 | 617,702,940 | 43.1% | `PSIN` 735, zero-prefix 732, MoVE 119 | -| 5 | 0 | 0 | 0 | 0.0% | — | -| 6 | 0 | 0 | 0 | 0.0% | — | -| 7 | 0 | 0 | 0 | 0.0% | — | -| 8 | 0 | 0 | 0 | 0.0% | — | -| 9 | 0 | 0 | 0 | 0.0% | — | -| 10 | 0 | 0 | 0 | 0.0% | — | -| 11 | 0 | 0 | 0 | 0.0% | — | -| 12 | 0 | 0 | 0 | 0.0% | — | -| 13 | 31,714 | 638,135,783 | 1,356,633,857 | 59.4% | `0DRP` 17,584, `PSIN` 4,537, zero-prefix 3,658 | -| 14 | 13,803 | 1,055,814,600 | 1,879,292,779 | 98.3% | zero-prefix 4,725, `42 40 00 00` 3,282, `0DRP` 1,751 | -| 15 | 3,928 | 1,060,254,688 | 1,582,210,186 | 98.7% | `0DRP` 3,702, Bink 2 78, XML 31 | -| 16 | 169 | 1,155,442,136 | 1,155,442,136 | 100.0% | Bink 2 169 | -| 17 | 10 | 1,107,140,984 | 1,107,140,984 | 100.0% | Bink 2 10 | -| 18 | 8 | 579,541,686 | 579,543,323 | 83.4% | Bink 2 7, XML 1 | - -The bounded windows below were the measurements before the full index; they agree with it where they overlap. - -## `story000.rpf` layout - -The archive is not uniform. A 64 MiB magic-count scan of the whole 20 GB file and the full index above separate -these regions: - -| Region | zlib carver result | Full-file signature result | -|---|---|---| -| GiB 0-4 | 91,753 streams (full index); GiB 0-3 93.4-99.6% readable, GiB 4 43.1%; `0DRP` pages, `zero-prefix` pages, type-hash and clip headers, `PSIN` from GiB 4 | no RSC8 | -| GiB 5-12 | 0 streams in every 1 GiB bucket (full index) | 225,281 `RSC8` headers (in GiB 6-13), all version 8001, u32@8 sum 2,677,370,916 | -| GiB 13 | 31,714 streams, 59.4% readable (full index): `0DRP` 17,584, `PSIN` 4,537, zero-prefix 3,658 | the last 6,736 `RSC8` headers | -| GiB 14 | 13,803 streams, 98.3% readable (full index); 3,282 `42 40 00 00` pages (780 in the first 256 MiB) | no RSC8 | -| GiB 15 | 3,928 streams (full index): `0DRP` 3,702, Bink 2 78, XML 31 | first Bink 2 bucket | -| GiB 16-18 | Bink 2 only: 169, 10 and 7 streams (plus one XML at 18 GiB) | 264 valid Bink 2 streams in all, 3,327,650,728 bytes | - -Window samples (each starts at the stated file offset and scans 256 MiB unless noted): - -| Start | Streams | Stored | Inflated | Readable | Dominant class | -|---:|---:|---:|---:|---:|---| -| 0 (1 GiB) | 55,284 | 1,002,413,457 | 3,963,061,696 | 93.4% | `0DRP` 21,980; zero-prefix 22,681 | -| 2 GiB | 8,837 | 255,734,022 | 744,610,656 | 95.3% | `0DRP` 3,067 | -| 3 GiB | 476 | 268,264,094 | 341,274,256 | 99.9% | large zero-prefix pages | -| 4 GiB | 502 | 273,507,830 | 342,088,096 | 100% (crosses window) | large zero-prefix pages | -| 5 GiB | 0 | 0 | 0 | 0% | raw, no zlib | -| 6 GiB | 0 | 0 | 0 | 0% | raw, no zlib | -| 8 GiB | 0 | 0 | 0 | 0% | raw `RSC8` | -| 10 GiB (1 GiB) | 0 | 0 | 0 | 0% | raw `RSC8`; 25,685 headers in that GiB | -| 12 GiB | 0 | 0 | 0 | 0% | raw `RSC8` | -| 14 GiB | 2,547 | 268,670,234 | 472,245,792 | ~100% (crosses window) | `42 40 00 00` 780; zero-prefix 1,100 | -| 16 GiB | 42 | 277,746,976 | 277,746,976 | 100% | Bink 2 | -| 18 GiB | 2 | 208,322,272 | 208,322,272 | 77.6% | Bink 2 | - -`RSC8` headers by 1 GiB bucket: 6 GiB 33,846; 7 GiB 41,391; 8 GiB 33,334; 9 GiB 29,687; -10 GiB 25,685; 11 GiB 25,983; 12 GiB 28,619; 13 GiB 6,736. The u32 at +8 sums to 2.49 GiB; the raw -region itself is about 7 GiB, so that field is not the total stored size of each resource. Every one -of the 225,281 headers has version 8001 (`0x1F41`); no `RSC7` header was found anywhere in the file. - -Bink 2 by 1 GiB bucket: 15 GiB 78; 16 GiB 169; 17 GiB 10; 18 GiB 7. The 264 streams carry valid -`KB2[a-z]` headers and dimensions from 540x960 to 2560x1440. They account for 3.10 GiB of the -archive and are the only video class measured here. - -## Readable payload classes - -### `story000.rpf`, first 1 GiB - -| Class | Streams | Stored | Inflated | Measured field | -|---|---:|---:|---:|---| -| `0DRP` page directory at +16 | 21,980 | 124,984,888 | 2,336,795,552 | version 122; page count u64 at +0x20 (top: 2 = 10,603, 3 = 5,996, 1 = 1,231, 4 = 646) | -| zero-prefix page | 22,681 | 737,279,203 | 1,234,168,960 | first 8 bytes zero | -| `80 80 80 80` buffer page | 3,594 | 43,479,838 | 203,792,288 | 16 bytes `0x80`, then zeros | -| type-hash header | 934 | 2,247,133 | 5,946,240 | u32 type, u32 8, u32 count, u32 0 | -| clip stream | 804 | 7,326,470 | 13,957,328 | u32 2 or 3, `01 01 00 00` | -| other raw starts | 5,291 (3,137 classes) | 87,095,925 | 168,401,328 | 3,036 classes occur once | - -No `PSIN`, `RBF0`, `RSC7`, `RSC8`, `AWC`, `FSSM`, `SCRP`, `YSC` or valid `KB2` stream starts in -this 1 GiB. A prefix scan of all 55,284 inflated streams found no `RSC7`/`RSC8`, `DDS `, `DXT1`, -`DXT3`, `DXT5`, `ATI2`, `BC5`, `BC7` or `TXTR` magic in the first 4 KiB; the only `0DRP` matches -were the 21,980 page directories. - -### `shared_minigame000.rpf`, full - -| Class | Streams | Stored | Inflated | Measured field | -|---|---:|---:|---:|---| -| `42 40 00 00` resource page | 1,255 | 304,089,245 | 656,802,672 | 0x4042 marker; four u32s then float records | -| zero-prefix page | 1,782 | 104,870,151 | 188,050,712 | first 8 bytes zero | -| `0DRP` page directory at +16 | 787 | 6,251,535 | 19,538,880 | version 122; page counts 1 = 578, 2 = 192, 4 = 4, 6 = 3 | -| `PSIN` | 73 | 164,290 | 556,280 | 70 full six-section chains; 3 without a chain | -| `63 30 00 00` mesh page | 45 | 4,470,231 | 14,894,128 | vertex blocks and meshlet groups; see [the section below](#63-30-00-00-mesh-pages) | -| XML text | 16 | 11,500 | 57,317 | UTF-8 BOM + ` 0.9) | Opposed (dot < −0.9) | -|---:|---:|---:|---:|---:|---:| -| 15,956,983 | 15,956,983 | 15,945,428 | 17,335,198 | 14,501,371 (83.7%) | 44,414 (0.26%) | - -Deliberately wrong reads of the first 300 streams don't hold up: -- **The three u16 at bytes 0-5 as a position:** 40.9% within 25° and 20.0% opposed. The rule gives 79.3% and 0.09%. -- **The low bytes swapped between `a` and `b`:** the same at 25°, but fewer neighbours within 0.1° than with no low - bytes at all. Within 0.1° the counts are 7.56% swapped, 8.59% with the high 16 bits only, and 9.19% with the rule. - -The 4-byte attribute streams (tags 0x21, 0x26, 0x27, 0x28) are still not decoded. - -With these blocks sized, the archive walk accepts 1,569 streams and leaves 0 unparsed: - -| Scope | Streams | `63 30` blocks | `42 40` blocks | Vertices | Groups | Meshlets | Triangles | -|---|---:|---:|---:|---:|---:|---:|---:| -| before | 335 | 142 | not sized | 302,524 | 855 | 9,134 | 996,321 | -| now | 1,569 | 145 | 13,545 | 302,584 + 15,956,983 | 12,697 | 159,387 | 16,868,805 | - -1,234 streams start with a `42 40` block. 7,759 groups have the vertex count of a `42 40` block in the same -stream. 520 streams end inside a group that continues in the next one; 5 stop at a `42 40` word whose header -doesn't fit. The `63 30` checks are unchanged on the 3 extra blocks: all positions finite and all normals of unit -length. - -**Slot 2 is the vertex normal.** With tag 0x21 (type 1) it is octahedral: u = bits 0-9 and v = bits 10-19, each -read as unorm `x / 511.5 − 1`, unfolded as usual (z = 1 − |u| − |v|, and where z < 0, x and y become -(1 − |v|)·sign(u) and (1 − |u|)·sign(v)). Bits 20-31 are not decoded; their top two bits are mostly 2 or 3, which -would fit a tangent angle and sign. With tag 0x27 (type 7, 363 blocks) it is x, y, z in bits 0-9, 10-19 and 20-29, -in the same unorm. The normals are in world order whatever the +0x6C axis word says, which also confirms the -position reorder above. `tools/meshlet_page.py --normals` compares each stored normal with the sum of its vertex's -face normals: - -| Archive | Vertices | Within 8° | Within 25° | Opposed | -|---|---:|---:|---:|---:| -| `shared_minigame000.rpf` | 14,411,107 | 12,394,835 (86.0%) | 13,271,947 (92.1%) | 210,301 (1.5%) | -| `core_restofworld.rpf` | 451,593 | 299,356 (66.3%) | 331,910 (73.5%) | 51,184 (11.3%) | - -On a sample of 79,157 minigame vertices, the readings tried before this one stay well below it, at a mean dot of -0.56-0.8: plain 10:10:10, a smallest-three quaternion, and 15- or 16-bit octahedral. In `core_restofworld`, 70% -of the 347 groups with a type-1 normal have fewer than 5% opposed, and 2% are mostly opposed (more than half), -which fits mirrored parts. The rest may be groups that the span rule binds to the wrong block. - -**Meshlet record words +8/+12 hold the meshlet's centre.** Three 12-bit fields give x, y and z: w2 bits 0-11, -w2 bits 12-23 and w3 bits 0-11. Each counts steps around 2047: the centre is `(field − 2047) × step`, with a step of -2^e / 16 m, where e is w2 bits 28-31: 1/16 m (±128 m) for most meshlets, coarser for larger ones further out (below). The default `0x007FF7FF / 0x7FF` is the origin. -`tools/meshlet_page.py --centres` compares each stored -centre with the centre of its meshlet's vertex box, using the `42 40` positions above. Over all 1,569 streams: - -| Meshlets | Default words | Axes | Same step | Within one step | -|---:|---:|---:|---:|---:| -| 142,613 | 68 | 427,839 | 214,263 (50.1%) | 307,248 (71.8%) | - -The rest are further off. The stored centre may be a bounding-sphere centre rather than the box centre: the mean -of the vertices fits worse (about 30% in the same step on the first 400 streams, against 51.8% for the box). -Within a block of 40 or more meshlets, the fields are almost perfectly ordered by the box centre: median rank -correlation 0.997 (x), 0.997 (y) and 0.983 (z) over 387 blocks. Readings that are deliberately wrong fit far worse on the first 400 streams: - -| Reading | Same step | -|---|---:| -| the rule | 51.8% | -| offset 2048 | 11.3% | -| 1/8 m steps | 0.9% | -| x and y swapped | 17.0% | - -The earlier test on `63 30` blocks found no correlation, and the reason is that their records hardly vary: the -groups matched to a `63 30` block keep the default words in 2,417 of 2,452 meshlets. - -**Word 0 bits 16-31 hold the meshlet's bounding-sphere radius, as an f16**, measured around the stored centre. Bits -14-15 are clear in all 61,170 records of the first 400 streams. Against the radius from the box centre, the -correlation is 0.999 on those streams. `--centres` checks the radius against the farthest vertex from the stored -centre, three ways: it covers that vertex; it covers it once the centre's rounding of up to √3/32 m is allowed for; -and it is tight, at most 1.25 × that distance plus the rounding: - -| Archive | Meshlets | Covers | Covers within rounding | Tight | -|---|---:|---:|---:|---:| -| `shared_minigame000.rpf` | 142,613 | 137,777 (96.6%) | 140,881 (98.8%) | 142,518 (99.9%) | -| `core_restofworld.rpf` | 4,899 | 4,771 (97.4%) | 4,895 (99.9%) | 4,883 (99.7%) | - -So the record carries a culling sphere (centre plus radius) for each meshlet. - -**Word +12 bits 14-30 hold the meshlet's normal cone.** The axis is octahedral, 6 + 6 bits: u = bits 14-19 and -v = bits 20-25, each read as unorm `x / 31.5 − 1`, unfolded like the normals above. Bits 26-30 give the spread: -sin(half-angle) = (31 − f) / 31. All-zero bits 12-31 (76% of records) is no cone. Bits 12-13 and bit 31 are always -clear. On the first 400 streams, the median smallest dot between a face normal and the stored axis follows -√(1 − ((31 − f)/31)²) within 0.033 on average; linear, square-root, squared and sine readings of the field miss by -0.14-0.32. `--cones` counts: - -| Archive | Cones | Axis within 25° of the mean normal | Every face inside | … within 0.05 | -|---|---:|---:|---:|---:| -| `shared_minigame000.rpf` | 43,415 | 35,615 (82.0%) | 18,483 (42.6%) | 42,454 (97.8%) | -| `core_restofworld.rpf` | 1,221 | 914 (74.9%) | 463 (37.9%) | 1,217 (99.7%) | - -So the cone is rounded to the nearest step, not widened to be conservative. With the centre and radius it completes -a meshlet's culling data. - -**w2 bits 28-31 are an exponent for the centre's step.** The step is 2^e / 16 m; bits 24-27 are always clear. -@zzEmmazz's count over the minigame archive and `story000` found e = 0 to 4 (review on #2991; the first version of -this section saw only e = 0 and 1 in the first 400 streams). In the minigame archive, e = 1 is set on 1,732 -meshlets and e = 2 on 157; `core_restofworld` has none. These meshlets are large (median radius 33 m), face upward, -and sit 100 m or more from the origin. Within the centre's rounding, the radius around the stored centre covers -the farthest vertex as follows: - -| e | Meshlets | Step 2^e/16 | 1/16 m | 1/8 m | -|---:|---:|---:|---:|---:| -| 1 | 1,732 | 1,730 | 0 | 1,730 | -| 2 | 157 | 157 | 0 | 0 | - -A least-squares fit of box centre against field on the e = 1 meshlets gives slopes of 1/8.07, 1/8.05 and 1/8.08 -per axis. `--centres` counts the meshlets with e > 0 as `coarse_steps`. The centre and radius tables above use each -meshlet's own step. - -**Slots 11 and 18 are tangents.** Their type-7 words are unit vectors in the same 10:10:10 unorm, perpendicular to -the vertex's stored normal. Bits 30-31 are always 3 or 0, which fits the bitangent sign +1 or −1. Over the minigame -archive (`--normals`, counts only): -- 7,520,441 tangent words, 7,435,001 (98.9%) of them within |dot| < 0.05 of perpendicular; -- sign bits 6,457,714 × 3 and 1,062,727 × 0, and never 1 or 2. - -`core_restofworld.rpf` has no tangent slots. - -**The rules hold in a second archive.** `core_restofworld.rpf` with `--faces --centres --normals`: -- all 151 mesh streams parse, with 502 `42 40` blocks, 488,265 positions (all finite, all within 300 m) and - 6,564 meshlets; -- 69.4% of 699,618 shared edges have neighbouring faces within ~25°, and 0.37% are opposed; -- 10,555 of 14,697 centre axes (71.8%) are in the same 1/16 m step, and 87.6% within one. - -**And in `story000.rpf`, the main story archive.** All 7,577 mesh streams parse with every check on (`--faces ---centres --normals --cones`, counts only). Six of them are 256 KiB pages where texture-like data follows the mesh -chunks on a 256-byte boundary behind zero padding; the walk stops there (`stopped_at_other_data`). They hold: - -| `42 40` blocks | Positions | Meshlets | Triangles | -|---:|---:|---:|---:| -| 173,877 | 29,602,924 | 405,418 | 38,626,760 | - -| Check | Count | -|---|---:| -| positions finite | all | -| positions within 300 m | 29,572,450 (99.9%) | -| shared edges with neighbouring faces within ~25° | 33,342,470 of 36,707,506 (90.8%); 1.4% opposed | -| normals within 8° / 25° of their faces | 76.5% / 94.6% of 20,801,089; 2.1% opposed | -| normals within 8° / 25° of their faces | 76.5% / 94.5% of 20,801,089; 2.1% opposed | -| tangents perpendicular to the normal | 30,473,135 of 30,569,246 (99.7%) | -| radius covers the farthest vertex from the stored centre | 257,091 of 275,832 meshlets (93.2%); 94.8% within rounding | -| cones: axis within 25° / every face inside within 0.05 | 89.5% / 94.2% of 228,244 | - -The stored centres match the box centre less often here: 25.7% of axes in the same step, 41.5% within one, -against 50.1% / 71.8% in the minigame archive. 625 meshlets use the 1/8 m step. Since the radius still covers the farthest vertex from the stored -centre in 93.2%, the decoding holds. These assets seem to store a centre other than the box midpoint; a sphere -centre would fit. The centre and radius counts in this table were taken before the step exponent was read in -full: they read only w2 bit 28. `story000` also has e = 2 to 4 on about 456 meshlets (@zzEmmazz's count), so those -few rows will move slightly when recounted. Most of the remaining misses come from the group-to-block binding: -several blocks in a page share a vertex count (@Pipodi's count on #2991). - -**Which `42 40` block a group is checked against (ASSET-294).** `--faces` and `--centres` decode a group with -a `42 40` block of its vertex count in the same page. When several blocks have that count, the order in the -page doesn't decide it. In `Q0 Q1 G0 G1` pages, G0 is built on Q0 in some pages and on Q1 in others, and taking -the k-th block for the k-th group fits only 9,295 of the 15,997 `story000` groups that have several blocks and a -fitting one. The link is in the drawable's pointers, outside the page. So the walker takes the block whose vertex -boxes are closest to the group's stored centres (`centre_distance`, summed over its meshlets), keeping the nearest -block before the group on a tie. Over all of `story000.rpf` (all 7,577 mesh pages parsed), before and after: - -| Pairing | Groups with several blocks | Block changed | Shared edges | Faces within ~25° | Opposed | -|---|---:|---:|---:|---:|---:| -| nearest block before | 16,059 | — | 36,707,506 | 33,342,470 (90.8%) | 518,120 (1.41%) | -| closest centres | 16,059 | 8,668 | 36,719,379 | 34,037,683 (92.7%) | 16,415 (0.045%) | - -The face check doesn't use the centres, so it is the independent evidence. The centre counts rise too (same step -212,479 → 222,572 of 827,496 axes), but for those 8,668 groups they no longer measure the centres on their own. -The tables above were counted with the old pairing; the first row is the story000 face count above. - -Still open: the +0x5C word, the type-1 normal's -bits 20-31, and what the `42 40` colour and UV slots hold beyond rpf9-explorer's reading. - -### `story000_script.rpf`, full - -`PSIN` dominates: 2,309 of 2,632 streams, 14,484,253 stored / 59,151,216 inflated. The 16-byte -header is: - -| Offset | Field | Measurement | -|---:|---|---| -| +0 | `PSIN` | magic | -| +4 | big-endian first-section offset | points at `LSCH` in 2,173 of 2,309 script streams and 70 of 73 minigame streams | -| +8 | little-endian u32 | 261 on 1,771 script streams, but 77/265/264 and larger values elsewhere; not stable in minigame, so this page does not label it a version | -| +12 | little-endian u32 | 1,568 on 1,227 script streams; not interpreted here | - -The section chain follows the measured layout: - -``` -+0 "PSIN" -... section records: 4-byte tag, big-endian u32 length (includes the 8-byte record header) -``` - -The chain is contiguous. In one 22,952-byte stream it runs from +0x2EE0 to +0x59A8: - -| Section | Length | Next section | -|---|---:|---:| -| `LSCH` | 0x14C8 | +0x43A8 | -| `LENM` | 0x358 | +0x4700 | -| `LSNS` | 0x1234 | +0x5934 | -| `LGID` | 8 | +0x593C | -| `LRSC` | 0x58 | +0x5994 | -| `CHKS` | 0x14 | end | - -Chain completeness: 2,118 streams have all six sections; 38 have `LSCH` and `LENM`; 4 have -`LSCH` only; 149 have no parseable chain. The other 323 streams are pages and raw starts. -No `SCRP` or `YSC` container appears, so the script archive's metadata is `PSIN`, not a named -script container. - -The 53 MB unread region contains four nested `RPF9` headers (three in a 51.7 MB gap). Their data -is high-entropy and shows no `PSIN`, `RSC8`, `0DRP` or `SCRP`/`YSC` header. That payload is opaque -to this pass; it is not guessed to be bytecode. - -### `story000_restofworld.rpf`, full - -631 streams, 94.9% readable. Bink 2 is the bulk: 7 streams, 120,187,756 bytes, dimensions -720x1280 (5) and 1920x1080 (2). The rest is 101 `0DRP` pages (version 122), 400 zero-prefix pages, -3 `PSIN`, 13 XML, 3 text and 3 clip streams. Nine `RSC8` headers (version 8001) sit in an 8.96 MB -unread gap; the archive has 18 nested `RPF9` headers. This is the video/extra-content companion to -the story archive. - -## `_bvh4` cross-check - -| Archive | Streams | Inflated | Content | Overlap with main | -|---|---:|---:|---|---:| -| `story000_bvh4.rpf` | 4 | 16,677 | 4 XML streams (2 ids); no binary BVH payload | 0 of 4 SHA-256 | -| `shared_minigame000_bvh4.rpf` | 2,560 | 970,044,012 | 2,555 binary zero-prefix pages + 5 XML streams (3 ids) | 0 of 2,560 SHA-256 | - -The XML streams identify themselves as environment-BVH change sets and carry 61 file-like entries -in `story000_bvh4` and 9 in `shared_minigame000_bvh4`. One filename string is common to both, but -the inflated stream sets have **no common SHA-256**. The binary pages start with zeroes, `0x50xxxxxx` pointers and identity matrices, -consistent with BVH node pages. -These are independent BVH archives, not empty indexes and not shared page sets. `story000_bvh4` is -metadata-only; `shared_minigame000_bvh4` has the payload. - -The main-archive comparison scope was the first 1 GiB of `story000.rpf` and all of -`shared_minigame000.rpf`; zero overlaps at those scopes do not prove zero overlap with the -remaining 19 GB. - -## Signatures actually observed - -| Magic | Offset | Measured fields | Where | -|---|---|---|---| -| `9FPR` (RPF9 little-endian) | +0 | data offset u32 +4; next u32 +8; third u32 +12 | 442 headers in `story000`, 50 in minigame, 5 in script, 19 in restofworld, including the outer archive | -| zlib `78 01/5e/9c/da` | +0 | inflates cleanly to stream end | 93.4% of the first `story000` GiB; 54.7% of minigame | -| `PSIN` | +0 | section chain with big-endian lengths | 2,309 in script; 73 in minigame; 3 in restofworld | -| `0DRP` | +16 | version 122 at +0x14; page count u64 at +0x20 | 21,980 first `story000` GiB; 787 minigame; 101 restofworld | -| `RSC8` | +0 | version 8001 at +4; u32 at +8; flags u32 at +12; name at +0x30 | 225,281 in `story000`; 1,957 minigame; 9 restofworld | -| `RSC7` | +0 | - | 0 in every full-file scan | -| `KB2[a-z]` | +0 | size u32 +4; width +0x14; height +0x18 | 264 in `story000`; 7 in restofworld | -| `42 40 00 00` | +0 | 0x4042 marker; u32s and float records | 1,255 minigame; 780 in the 14 GiB `story000` window | -| `RBF0` | +0 | schema string | 0 at stream starts; 2 raw occurrences in 20 GB (not container starts) | -| `SCRP`, `YSC` | +0 | - | 0 validated | -| `AWC\0`, `FSSM` | +0 | - | 0 validated | -| XML | +0 | UTF-8 BOM + ` [--start N] [--limit BYTES] -python -I tools/rpf9_carve.py --index-only [--start N] [--limit BYTES] -python -I tests/test_story_index.py -python -I tools/meshlet_page.py [...] [--json out.json] [--quiet] -python -I tests/test_meshlet_page.py -``` - -`meshlet_page.py` writes counts and layout checks only (chunk kinds, vertex, meshlet and triangle counts, and -how many values pass each check), never vertex or index values. It exits 1 if a page fails to parse and 2 if an -input does not exist. - -`--start` must be 0 or more and `--limit` at least 1 (decimal or `0x` hex). A value outside that, or a `--start` -past the end of the archive, stops `story_index.py` with a one-line error and exit code 2 and writes nothing. -An empty archive gives an index with no files. - -`story_index.py` is stdlib-only. It classifies the same zlib/Bink walk as `rpf9_carve.py`, parses -the `PSIN` section chain, and reports `0DRP`/`RSC8`/`9FPR` headers when they start a stream or a -carved file. It does not recurse into the raw embedded archives. A `clip-stream` row is the tagged -auxiliary table of a `0DRP` second system page, checked by the same `aux_table` as `anim_index.py` -(#2496): u32 count 2 or 3, count {u32 tag, u32 payloadBytes} pairs with first tag `0x101`, and every -payload inside the stream. Its `count` is the entry count and its detail lists the tags and payload end; -there is no version and no fixed 24-byte header. The "clip stream" row in the 1 GiB table above was -counted with the older eight-byte prefix check (u32 2 or 3, then `01 01 00 00`). diff --git a/docs/strand_grooms.md b/docs/strand_grooms.md deleted file mode 100644 index 02d59bea7..000000000 --- a/docs/strand_grooms.md +++ /dev/null @@ -1,320 +0,0 @@ -# GPU Strand Grooms (`smh`) - -Hair, beards, brows, lashes, body hair, and animal fur in the Xbox Series build are not authored as static -triangle drawables. Each such item's `.#dr` drawable is a one-triangle stub, while the hair geometry is stored -separately as a **groom LOD resource** consumed by the `smh_*` compute and strand-rendering shaders. - -This document specifies the measured binary layout of `smh` groom LOD resources, the shader-verified compute -pipeline (`smh_pose_0_CS_PreSkinSimGuides` and `smh_gen_1_CS_InterpolateStrands`), the exact Class 0 strand -scattering RNG, barycentric strand interpolation, and aggregate corpus measurements verified with the pure -standard-library decoder in `tools/smh_groom.py`. No game data or shader disassembly is included. - -## Pipeline overview - -Rendered strands are **not stored** in the archive. Each groom LOD stores a scalp triangle mesh whose vertices -are **guides** (polylines of rest-pose nodes, skin weights, arc lengths, root UVs, and per-guide attributes) -plus per-triangle strand density counts and optional region IDs. At runtime the `smh_*` GPU pipeline generates -and shades strands in stages: - -1. **Guide pose & simulation (`smh_pose_*`, `smh_sim_*`)**: `smh_pose_0_CS_PreSkinSimGuides` reads guide rest - positions (`+0x44`), bone indices (`+0x10`), and bone weights (`+0x14`) from the GPU asset buffer and skins - guide curves into posed runtime buffers (21/21/22-bit packed positions). `smh_sim_0_CS_LodBlend` cross-fades - simulated guides across LOD transitions. -2. **Strand scattering & interpolation (`smh_gen_*_CS_InterpolateStrands`)**: dispatches one thread per strand - for each active strand class, picks a scalp triangle and uniform barycentric coordinates deterministically - from the thread ID and asset seed, tests the triangle's region ID against a per-instance 256-bit style mask, - blends the three corner guides' posed nodes, lengths, and UVs, trims each strand to its randomized target - length, and writes 16 bytes per strand point (with the last dword of a strand's block zeroed when culled). -3. **Style modification & visibility (`smh_modify_*`, `smh_draw_64`/`smh_draw_128` `CS_VisHair`, - `VS_HairStrandGeometry`, `PS_HairStrandVBuffer`, `hair_resolve_*`)**: applies runtime clump, curl, frizz, - and width parameters from per-instance style records and rasterizes all strands in one batch. - -### What the two strand classes are (`smh_gen_*` and `smh_draw_*`) - -Shader inspection of `smh_gen_*`, `smh_draw_64`, `smh_draw_128`, `VS_HairStrandGeometry`, and -`PS_HairStrandVBuffer` confirms that **neither class 0 nor class 1 is "the detailed one"**. They are two -placement sets of one groom, generated alike and drawn together: - -- **Same strand shape and style inputs**: every `smh_gen_*` variant reads points-per-strand from per-instance - record `+0x54` bits 16–23, writes 16 bytes per point, and reads the same shared style/texture fields - (`+0x11c` texture value range, `+0x128` texture heap index, `+0x58` style record index into SRV `t72`). -- **Drawn together as one batch**: both the software strand rasterizer (`smh_draw_64`, `smh_draw_128` / - `CS_VisHair`) and the hardware visibility-buffer path (`VS_HairStrandGeometry` + `PS_HairStrandVBuffer`) load - both counts and draw `(count0 + count1) * (points - 1)` segments together. A secondary point count at - `+0x54` bits 24–31 replaces the primary count in cheaper/shadow passes. -- **Per-instance record (`t71`, `0x150` bytes)**: - -| Instance offset | Meaning | -|---|---| -| `+0x50` | Feature bit `128` parameter | -| `+0x54` | Bits 16–23 = points per strand; bits 24–31 = secondary point count (shadow / cheaper passes) | -| `+0x58` | Style index into SRV `t72` (`0xb0`-byte style records; `+0x10` = 256-bit region mask) | -| `+0x6c` | Class 1 output buffer offset (read by `smh_gen_2`, `_4`, `_8`, `_16`) | -| `+0xa0`, `+0x148` | Feature bit `32` parameters | -| `+0xc8..+0xd0` | Feature bit `128` parameters | -| `+0xe0`, `+0xe4`, `+0xe8` | Skin matrix buffer handles | -| `+0xf0` | Feature bit `256` parameter | -| `+0x100`, `+0x104` | Class 1 start index and strand count (`smh_gen_2`, `_4`, `_8`, `_16`) | -| `+0x108`, `+0x10c`, `+0x110` | Class 0 start index, strand count, and output buffer offset (`smh_gen_1`) | -| `+0x11c` | Two `float16` values: texture value range (shared by both classes) | -| `+0x120` | Descriptor-heap index of the GPU asset buffer | -| `+0x124`, `+0x12c` | Feature bit `64` parameters (accompanied by two additional textures) | -| `+0x128` | Shared texture heap index (length/attribute lookup) | - -- **`smh_gen_N` variant bitmask**: - - **Low 5 bits (placement mode)**: bit `1` generates **class 0** (`+0x108`/`+0x10c`/`+0x110`, per-triangle - count byte 0, asset header seed `+0x7c`); bits `2`, `4`, `8`, and `16` select four placement modes of - **class 1** (`+0x100`/`+0x104`/`+0x6c`, additionally reading asset header `+0x64`, `+0x70`, seed `+0x80`, - and the `+0x90..+0x9f` lookup curve; `smh_gen_2` reads `tri_count` byte 3 and `smh_gen_4` reads bytes 1 - and 3). - - **Higher feature bits (`32..480`)**: bit `32` reads `+0x148` and `+0xa0`; bit `64` reads `+0x124`, - `+0x12c`, and two additional textures; bit `128` reads `+0x50` and `+0xc8..+0xd0`; bit `256` reads `+0xf0`. - -## Binary container and system page layout - -On disk inside RPF9 archives (see [rpf.md](rpf.md)), each groom LOD is stored as a native RAGE resource: a -16-byte all-zero prefix on a 16-byte boundary followed by one zlib-compressed **system page** (464 to 672 bytes -inflated), padded to a 16-byte boundary, followed by one or more 16-byte-aligned zlib-compressed chunks that -concatenate to the **GPU asset buffer**. - -System pointers use base `0x50000000` (`SYS_BASE`); GPU buffer pointers use base `0x60000000` (`GPU_BASE`). - -| System offset | Type | Meaning | -|---|---|---| -| `+0x00` | `u8[8]` | Zero vtable placeholder before resource fixup | -| `+0x1c` | `u32` | Constant type ID `0x7d8f3db3` in every groom LOD resource | -| `+0x30` | `float4` | Primary bounding box minimum `(x, y, z, w)` in metres (skeleton-root space, Z-up) | -| `+0x40` | `float4` | Primary bounding box maximum `(x, y, z, w)` in metres (skeleton-root space, Z-up) | -| `+0x50..+0x6f` | `float4[2]` | Secondary bounds floats (within the `+0x48..+0x70` float block); left unset at `+FLT_MAX` (`0x7f7fffff`, LE `ff ff 7f 7f`) / `-FLT_MAX` (`0xff7fffff`) on child rigs | -| `+0x70` | `u64` | System pointer (`- 0x50000000`) to the GPU buffer descriptor (`+0x08`: `u32` dword count, `+0x0c`: `u16` stride = `4`, `+0x0e`: `u16` flags = `8`, `+0x18`: `u64` GPU pointer = `0x60000000`) | -| `+0x98` / `+0xa0` | `u32`, `u64` | Count and system pointer to `u32` skinning bone name hashes (`joaat32`, see [character_skeleton.md](character_skeleton.md)) | -| `+0xa8` / `+0xb0` | `u32`, `u64` | Region record count (`0..64`) and system pointer to 12-byte region records (`> 16` sequence. - - Candidate triangle index: `pick = (v8 >> 16) % triangles`. - - Look up `rid = tri_region[pick]`. If `rid != 0` and bit `rid` is set in the 256-bit style mask, mark the - strand culled for this attempt and continue to the next attempt. - - Otherwise record `v20 = v5 >> 8` and test `(v6 & 0xFFFFFF) * 2^-24 < clamp_f32(tri_count[pick][0] * density_scale, 0, 1)`. - If accepted, stop searching. -3. If all four attempts fail to accept, the final attempt's `tri`, `culled`, and last live `v20` remain. - -`density_scale` is supplied per instance at runtime; offline export defaults to `1 / max(tri_count[:, 0])` so -the densest scalp triangle is always accepted. - -### 2. Barycentric coordinates (`v_mad_u32_u24` cascade) - -Using `mul24(a, b) = ((a & 0xFFFFFF) * (b & 0xFFFFFF)) & 0xFFFFFFFF` and constant `k = 0xC083C5`: - -- `seed = (0x3C1 * (tri & 0xFFFF) + seed_0 * 0x8A30D + v20 * 31) & 0xFFFFFFFF` -- Six `mul24` + add steps with `0x3C6EF35F` and `x ^= x >> 12` folding yield two 24-bit integers `a` and `b`. -- `u1 = a * 2^-24`, `u2 = b * 2^-24`, `r = sqrt(u1)`. -- Uniform barycentric weights on the scalp triangle: `bary = (1 - r, (1 - u2) * r, u2 * r)`. - -### 3. Rest-pose blending and length trimming - -For each unculled strand on triangle `(g0, g1, g2)` with weights `(b0, b1, b2)`: - -- Blend each node `k` of the three guides: `P[k] = b0 * pos[g0][k] + b1 * pos[g1][k] + b2 * pos[g2][k]`. -- Blend stored guide arc length: `L_guide = b0 * len[g0] + b1 * len[g1] + b2 * len[g2]`. -- Compute per-strand PCG hash of `seed`: - `v = seed * 0x2C9277B5 + 0xAC564B05`, `w = (((v >> ((v >> 28) + 4)) ^ v) * 0x108EF2D9)`, - `u_len = ((w >> 22) ^ (w & 0xFFFFFF)) * 2^-24`. -- Target length from header `+0x60` `(amount, low)`: - `factor = low + u_len * (1 - low)`, `L_target = max(L_guide * (1 + (factor - 1) * amount), 0)`. -- Walk segments `k = 1 .. nodes_per_guide - 1`, clamping each segment to the remaining length (using a minimum - segment length floor of `2^-23` m and zeroing steps below `1e-9` m). Trailing nodes past the trimmed tip repeat - the tip coordinate. - -## Measured corpus census - -Aggregate counts measured with `python -I tools/smh_groom.py census` across the two package archives that hold -groom resources (other archives such as `data.rpf`, `story000`, and `shared_minigame000` hold none): - -| Archive | Groom assets | LOD resources | Decode errors | GPU buffer bytes | Class 0 strands | Class 1 strands | -|---|---:|---:|---:|---:|---:|---:| -| `packs.rpf` | 5,741 | 20,010 | 0 | 902,231,288 | 77,123,314 | 35,359,612 | -| `core_restofworld.rpf` | 10 | 36 | 0 | 225,568 | 3,099 | 5,596 | -| **Total** | **5,751** | **20,046** | **0** | **902,456,856** | **77,126,413** | **35,365,208** | - -Additional corpus-wide properties across all 20,046 decoded LODs and 5,751 LOD 0 assets: - -- **Decode coverage**: 20,046 / 20,046 LOD resources decode cleanly (0 failures). -- **Geometry ranges**: 3 to 5,185 guides per LOD; 2 to 80 nodes per guide. -- **LOD depths**: 4,534 assets have 4 LODs, 341 have 3 LODs, 11 have 2 LODs, and 865 have 1 LOD (82% of the - `braids_ties` class and 91% of `lashes` are single-LOD). -- **Per-triangle strand sums**: summing `tri_count[:, 0]` equals system page `+0xd0` in 5,716 / 5,751 LOD 0 - assets; summing `tri_count[:, 1]` equals `+0xd4` in 3,158 / 5,751 LOD 0 assets (confirming class 1 placement - uses the four additional shader placement modes `smh_gen_2`, `_4`, `_8`, and `_16`). -- **System page metadata**: `425` distinct `+0xc8` style preset hashes (`0x74792000` in 968 grooms), `30` - distinct `+0xcc` part class hashes, and `2,457` / `5,741` `packs.rpf` assets (including child-rig hair - grooms) with unset `+0x50..+0x6f` secondary bounds floats (`0x7f7fffff` / `0xff7fffff`). -- **Split chains**: `396` split assets enclosing `413` inner assets in `packs.rpf`. -- **Optional arrays**: `node_4` / `node_2` appear together in 12,101 LODs; `ext_18` / `ext_1c` appear together - in 10,684 LODs; `ext_24` / `direction` appear together in 5,718 LODs; `+0x3c` is non-zero in 10,756 LODs; - header `+0x2c` is `0x0001ffff` in 39 LODs (`0xffffffff` in all other 20,007 LODs). -- **Heuristic bounding-box placement classes** (5,751 assets): 1,462 Facial hair, 1,371 Body hair, 1,119 Scalp - hair, 1,076 Fur and other, 723 Brows and lashes. - -## What is exact vs. modelled or open - -| Component | Status | Notes | -|---|---|---| -| Binary layout (system page, `+0xb8` hashes, `+0x50..+0x6f` child-rig float sentinels, `+0xe8` half-float style params, GPU header, guides, nodes, triangles, skin, lengths, UVs, counts, regions) | Exact | Verified across all 20,046 LODs (0 decode failures) against `smh_pose_0_CS_PreSkinSimGuides` and `smh_gen_*_CS_InterpolateStrands` | -| Strand class relationship (class 0 vs. class 1) | Exact (shader-verified) | Neither class is more detailed; both are placement sets of one groom generated with the same points-per-strand (`+0x54` bits 16–23, 16 B/pt) and drawn together as `(count0 + count1) * (points - 1)` segments in one batch | -| Class 0 root triangle selection & barycentric RNG | Exact | Bit-exact 32-bit unsigned integer port of `smh_gen_1_CS_InterpolateStrands`; `density_scale` defaults to `1 / max(tri_count)` | -| Rest-pose strand shape and length trimming | Modelled | Barycentric blend of three guides trimmed via `+0x60` PCG length variation; omits runtime style record (clump/curl/frizz/region mask), length texture, skinning, and simulation | -| Class 1 strand scattering | Approximate | Class 1 total is exact; the four placement modes (`smh_gen_2`, `_4`, `_8`, `_16`) are not yet ported | -| Optional arrays `ext_18`, `ext_1c`, `ext_24`, `node_4`, `node_2`, `+0x3c`, `tail` | Undecoded | Spans are parsed and reported; per-field semantics remain open | -| Groom-to-item name linking | Partial / encrypted TOC | Groom resources store no per-item marker or name hash, and the nested RPF9 file table is encrypted (see [rpf.md](rpf.md) and [character_models.md](character_models.md)) | - -## CLI usage (`tools/smh_groom.py`) - -`tools/smh_groom.py` uses only the Python standard library (`python -I`) and reuses the binary glTF 2.0 container -primitives from `tools/glb_writer.py`. Synthetic unit tests live in `tests/test_smh_groom.py`. - -```powershell -# Inspect a carved .smh file or an archive member at a byte offset -python -I tools/smh_groom.py inspect --json -python -I tools/smh_groom.py inspect --offset 0x1000 - -# Run an aggregate census over one or more archives, carved .smh files, or directories -python -I tools/smh_groom.py census --json - -# Export a groom to glTF 2.0 binary (.glb) as 3-sided tubes, flat ribbons, LINES, or LINE_STRIP -python -I tools/smh_groom.py export-glb out_tubes.glb --geometry tubes --strands 6000 -python -I tools/smh_groom.py export-glb out_ribbons.glb --geometry ribbons --strands 4000 -python -I tools/smh_groom.py export-glb out_curves.glb --curves --strands 12000 -python -I tools/smh_groom.py export-glb out_strips.glb --geometry line-strip --no-scalp --no-guides -``` diff --git a/docs/testing.md b/docs/testing.md deleted file mode 100644 index 0137c1a07..000000000 --- a/docs/testing.md +++ /dev/null @@ -1,726 +0,0 @@ -# Running the GPU tests - -The GPU tests are small hand-written RDNA2 programs in `runtime/test/shaders`. They are translated to SPIR-V and run -on your GPU, and the results are compared with what the RDNA2 hardware gives. They need no game files, and every -result helps: post it in [#166](https://github.com/ItsNotRexed/Leonida/issues/166), one comment per GPU and driver. -If your GPU is already covered there, testing an open pull request from the review queue in the [coordination -issue][claims] helps more. - -This page collects the setup steps and the problems testers have run into so far. - -[claims]: https://github.com/ItsNotRexed/Leonida/issues?q=is%3Aissue%20is%3Aopen%20in%3Atitle%20%22Coordinating%20who%20works%20on%20what%22 - -## What you need - -- **Python 3.11+.** `scripts/run_gpu_tests.py` needs at least 3.10. -- **`llvm-mc` with the AMDGPU target** (LLVM 21+). The official LLVM Windows release has no AMDGPU target. On - Windows, use one of: - - `scripts\build_llvm_mc.ps1`, which builds a native `llvm-mc.exe` (needs git and the Visual Studio C++ tools); - - conda-forge's `llvm-tools` package, whose Windows build includes the AMDGPU target; - - `llvm-21` in WSL, with `LLVM_MC` set to the whole command: - `LLVM_MC="wsl -d Ubuntu -e /usr/lib/llvm-21/bin/llvm-mc"`. - - On Linux, the distribution's `llvm-mc` on `PATH` is enough, if it is 21 or newer. Debian and Ubuntu's `llvm-21` - installs it only as `llvm-mc-21` and `/usr/lib/llvm-21/bin/llvm-mc`; with `LLVM_MC` unset, the tools take the newest - such versioned install when there is no plain `llvm-mc` (`tools/mc_command.py`). On macOS, Homebrew's `llvm` is - keg-only, so `brew install llvm` doesn't put `llvm-mc` on `PATH`: the pytest suites find it in - `/opt/homebrew/opt/llvm*/bin` (or `/usr/local/opt/llvm*/bin` on Intel), and the other tools need - `LLVM_MC="$(brew --prefix llvm)/bin/llvm-mc"`. - - An older `llvm-mc` is not enough for everything. Ubuntu 24.04's default `llvm-18` (18.1.3) works for - `valu_fuzz.py --family mem` and `lds_fuzz.py`, but rejects `ps_sdwa_f16_const`. LLVM 19+ assembles the stock CI - test fixtures. However, full f16 fuzzing with `valu_fuzz.py --family f16` requires LLVM 21+, as LLVM 19 still - rejects `op_sel` on the 16-bit integer VOP3 forms that the fuzzer generates - (`v_ashrrev_i16_e64 ... op_sel:[0,0,0]`: "not a valid operand"). - - On Windows, ROCm 7.2's bundled `llvm-mc.exe` reports LLVM 21.0.0git. It assembled the TEST-71 memory and - LDS programs but rejected the 16-bit shift used by the f16 generator. To check an assembler directly in - PowerShell, set `$env:LLVM_MC` to the path of its executable and run: - - ```powershell - 'v_lshlrev_b16_e64 v34, v27, v27 op_sel:[0,1,1]' | & $env:LLVM_MC -triple=amdgcn--amdpal -mcpu=gfx1013 -show-encoding - ``` - - If it reports `not a valid operand`, point `LLVM_MC` at a build that accepts this instruction. The Windows - conda-forge `llvm-tools` 23.1.6 package assembled the same f16 programs. -- **SPIRV-Tools** (`spirv-as`, `spirv-val`): part of the Vulkan SDK, or a distribution package. -- **A C++20 compiler, CMake and the Vulkan headers** to build the test programs: - - Windows: the full runtime needs Visual Studio 2022 with "Desktop development with C++" and Windows SDK - 10.0.26100 or newer. Install the Vulkan SDK for the backend headers. The standalone tools also compile with llvm-mingw and the Vulkan headers alone. - Running the GPU tests needs a Vulkan loader and a compatible driver. - - Linux: CMake 3.24+, GCC or Clang, and the Vulkan headers and loader. The headers should be recent enough - for `VK_KHR_maintenance8`; older ones still build, but skip what needs it. - - macOS: `brew install llvm molten-vk vulkan-headers vulkan-loader spirv-tools vulkan-tools`. The test programs - load MoltenVK directly; set `LEONIDA_VULKAN_LOADER` to use the Vulkan loader instead. - -## Build the test programs - -On a Windows runtime build with Vulkan enabled, CMake only registers `d3d12_translated_draw`, `d3d12_m2_textured`, -`d3d12_m2_formats`, `d3d12_m3_frame`, `d3d12_m4_compute` and `d3d12_buffer_uav` when it finds `llvm-mc`, -`spirv-as` and `spirv-val`. It registers `d3d12_subgroup` only when it finds `llvm-mc` and `glslangValidator`. -Without `glslangValidator`, other tests are also omitted, including `d3d12_compute`, `d3d12_draw`, -`d3d12_set0_compute` and `d3d12_mesh`; some registered tests run only part of their checks. These tests can be -**absent**, not reported as skipped, when their build prerequisites are missing, so a passing `ctest` percentage -alone does not establish that they ran. Check the CMake configure messages and list the -configured tests with `ctest --test-dir runtime/build -C RelWithDebInfo -N` before comparing test counts. After -installing missing tools, rerun CMake in an environment where they are visible and rebuild. - - -Windows, from a "Developer PowerShell for VS 2022" or a plain shell: - -```powershell -scripts\build_runtime.ps1 # CMake + Ninja into runtime\build -``` - -For the standalone Vulkan tools, put llvm-mingw on `PATH` and point CMake at the directory containing `vulkan/vulkan.h`: - -```powershell -cmake -S runtime -B runtime/build/vulkan -G Ninja -DCMAKE_CXX_COMPILER=clang++ -DLEONIDA_BUILD_WINDOWS_RUNTIME=OFF -DVulkan_INCLUDE_DIR=C:/Vulkan-Headers/include -cmake --build runtime/build/vulkan --parallel --target vk_harness vk_texture_test vk_sampler_test vk_compute_test vk_store_test vk_bindless_test -``` - -Pass `--build runtime/build/vulkan` to `scripts/run_gpu_tests.py`. - -If you configure with CMake's Visual Studio generator instead, the programs end up in `runtime\build\Release` (or -`RelWithDebInfo`); pass that folder to `--build` below. - -Linux and macOS: - -```sh -cmake -S runtime -B runtime/build/linux -cmake --build runtime/build/linux --parallel -``` - -On macOS, add `-DVulkan_INCLUDE_DIR=/opt/homebrew/include` to the first command. - -The test programs and `scripts/run_gpu_tests.py` should come from the same commit. Some checks tolerate an older -binary (`unpinned_subgroup_skip`), but mixing them can report false failures in the compute tests: 28 `cs_*` -failures on both an RTX 5070 Ti Laptop and a Radeon 610M with the `426023a` script and `48ad23f` binaries, where -either matching pair is clean. If you cannot build locally, the `runtime-windows` artifact of the Runtime workflow -belongs to the commit that built it; check that commit out as well. - -### Without a compiler: a CI-built runtime - -If you cannot build the test programs locally, the Runtime workflow publishes them as the `runtime-windows` -artifact of its own commit. It holds Windows executables, so use them on Windows or under Wine as in the -section below; GitHub expires the artifact after 7 days. Not every commit on `main` has one: the workflow runs -only when a commit touches what it builds or reads (the `paths` list in `.github/workflows/runtime.yml`), so a -commit that changes only docs, tests or other tools has no Runtime run. Take the most recent run under -Actions -> Runtime, and check out the commit it built, or start a run of the commit you want on your own fork with -"Run workflow" (`workflow_dispatch`). Download and unzip `runtime-windows`, and pass the unzipped folder to `--build`: - -```sh -python -I scripts/run_gpu_tests.py --build -``` - -If you also have neither `llvm-mc` nor SPIRV-Tools (`spirv-as` / `spirv-val`) installed, `--disasm-dir` runs the -pre-disassembled subset in `tests/semantic/fixtures/disasm` and `--assembler python` (the default under `auto` when -`spirv-as` is absent) assembles SPIR-V with `tools/spirv_asm.py`: - -```sh -python -I scripts/run_gpu_tests.py --build --disasm-dir tests/semantic/fixtures/disasm --assembler python -``` - -`build.py` and `check.py` take the same folder as their second argument: - -```sh -python -I runtime/test/shaders/build.py -python -I runtime/test/shaders/check.py -``` - -The artifact belongs to the commit that built it, so run the scripts from that commit as well (see the note above). - -#### Run one test from the Windows artifact - -For a focused GPU check without building locally, extract the artifact and open -PowerShell in the directory containing the test executable. Keep the extracted -files together so the test can find any fixtures relative to that directory. -For example, to run the synthetic depth/stencil resolve test without game files: - -```powershell -.\d3d12_depth_resolve_test.exe -Write-Output "Test exit code: $LASTEXITCODE" -``` - -Report the executable name, the workflow run and its commit, your GPU and driver, -the exit code, and the test summary in [#166](https://github.com/ItsNotRexed/Leonida/issues/166). -Label it as a single-test run so the result is easy to distinguish from a full suite run. - -## Run them - -The whole suite, assembled, translated and run in one go: - -```sh -python -I scripts/run_gpu_tests.py --build runtime/build/linux # Windows: the default runtime\build -``` - -`--filter ` runs only matching tests, and `--work ` keeps the intermediate files. -Add `--require-pass` when verifying a specific path: an all-skipped run exits 1 instead of 0. -Skips still appear as `SKIP`, and individual skips are allowed if at least one test passes and none fail. - -A GPU test program that runs longer than 120 seconds is killed and counted as a failure, so a hung driver does -not stall the suite. `LEONIDA_GPU_TEST_TIMEOUT` sets the limit in seconds for `check.py`, `run_gpu_tests.py` and -the `valu_fuzz.py` translator oracle; `0` turns the limit off. -**Rebuild the test programs after pulling.** The programs carry the V# and push-constant layout the translator expects. An executable from an older commit still loads and runs every shader, so a stale `vk_compute_test` does not fail loudly: when a newer translator starts enforcing a descriptor rule the old program does not set up (the raw V# in `pc[2..3]`, for one), every compute test reports the untouched `0xEEEEEEEE` fill pattern and the run looks like a translator regression. If all the compute tests in a run return that pattern, rebuild first (`cmake --build runtime/build/linux`, or `cmake --build runtime\build` on Windows) and run again before reading anything into the words. - -The two-step form, which `CONTRIBUTING.md` describes: - -```sh -python -I runtime/test/shaders/build.py -python -I runtime/test/shaders/check.py -``` - -For the standalone `v_mullit_f32` readback, build the full-screen triangle and the -hand-written semantic fixture, then run 120 draws with runtime SGPR inputs. -The driver checks every pixel against an integer product rounded to 24 bits. -It reports the input words, pixel and channel on the first mismatch. - -```sh -python -I runtime/test/shaders/build.py vs_ids ps_mullit -python -I runtime/test/shaders/mullit_readback.py -``` - -For D3D12/runtime tests, `LEONIDA_VK_VALIDATION=1` enables `VK_LAYER_KHRONOS_validation`. When running with validation, set `DISABLE_RTSS_LAYER=1` and `DISABLE_VULKAN_OBS_CAPTURE=1` if MSI Afterburner (RivaTuner) or OBS is installed: their overlay layers can add unsupported swapchain usage, and in an elevated (administrator) terminal the loader ignores `VK_LOADER_LAYERS_DISABLE=~implicit~` (see "Known problems"). - -`vk_compute_test`, `vk_bindless_test` and `vk_image_fuzz` read `LEONIDA_VK_VALIDATION` too (`vk_compute_test` -through `runtime/test/vk_validation.h`): each validation message goes to stderr and a validation error makes the -program exit 1, so `LEONIDA_VK_VALIDATION=1 VK_KHRONOS_VALIDATION_GPUAV_ENABLE=1 python scripts/run_gpu_tests.py` fails -every compute test the layer objects to; the program's output ends with "N validation errors". The other shader test -programs (`vk_harness`, `vk_store_test`, `vk_texture_test`, `vk_sampler_test`) don't read it. -To check one, load the layer through the loader and run it by hand, for example -`VK_INSTANCE_LAYERS=VK_LAYER_KHRONOS_validation VK_KHRONOS_VALIDATION_GPUAV_ENABLE=1 vk_harness vs.spv ps.spv out.raw`. -The layer prints its messages to stdout and the program's exit status doesn't change, and `run_gpu_tests.py` shows -only each test's last line, so read the program's own output. GPU-assisted validation (`..._GPUAV_ENABLE=1`) -instruments the translated shaders and reports what they actually do at run time: out-of-bounds buffer accesses, and -an image read through a view whose numeric type doesn't match the shader's (a T# FORMAT that disagrees with the -bound view). It runs on llvmpipe. `VK_KHRONOS_VALIDATION_VALIDATE_SYNC=1` adds synchronization validation. - -## The Windows runtime on Linux, under Wine or Proton - -The Linux build above makes only the Vulkan programs. The loader (`gta6rt`), its shims and their tests are Windows -programs; `runtime/cmake/clang-cl-xwin.cmake` cross-compiles them on Linux with clang-cl and lld-link (LLVM 19+, but not 22.1.7 or 22.1.8 (see Known problems): the -MSVC STL that xwin lays out rejects older Clang; versioned names go in with `-DCMAKE_CXX_COMPILER=clang-cl-19` etc.) -against an MSVC CRT and Windows SDK that [xwin](https://github.com/Jake-Shadle/xwin) downloads from Microsoft -(running it means accepting Microsoft's licence), and `ctest` runs them through Wine: - -```sh -xwin --accept-license --sdk-version 10.0.26100 splat --use-winsysroot-style --preserve-ms-arch-notation \ - --output ~/.local/share/xwin-sdk -cmake -S runtime -B runtime/build/windows --toolchain "$PWD/runtime/cmake/clang-cl-xwin.cmake" \ - -DXWIN_DIR="$HOME/.local/share/xwin-sdk" -cmake --build runtime/build/windows --parallel -WINEPREFIX="$HOME/.local/share/leonida-wine" ctest --test-dir runtime/build/windows -``` - -Use a recent xwin: 0.10.0 lays out SDK 10.0.26100 with the command above, while 0.6.5 stops with "unable to find -x86_64 headers for Win11SDK_10.0.26100". - -On a machine without a display (a server, a container, WSL without WSLg), Wine has no graphics driver to create a -Vulkan instance with, so every Vulkan test fails with `vkCreateInstance failed (VkResult -3)` and, with -`WINEDEBUG=+vulkan`, "Failed to load Wine graphics driver supporting Vulkan". Run the tests under a virtual X server, -as CI does: `WINEPREFIX="$HOME/.local/share/leonida-wine" xvfb-run -a ctest --test-dir runtime/build/windows` -(packages `xvfb` and `xauth`, which `xvfb-run` needs). With Mesa installed, the tests then run on llvmpipe. - -A virtual X server has no presentable surface, so presentation cannot be judged under it. With a real display (here -Wine 11.22 on a Wayland session, through XWayland) the same 123-test list gives 92 passed, 6 failed and 25 skipped, -and `vk_presenter_sync`, `xbox_present` and `dxgi_swapchain` pass, while they fail under `xvfb-run`. Use a real -compositor for those three. Six still failed with a real display: `device_proxy`, `d3d12_xs_root_signature`, -`xdxr_build`, `d3d12_xdxr_rt`, `d3d12_present` and `d3d12_compute`. - -The build type defaults to `RelWithDebInfo`: xwin leaves out the debug CRT, so `Debug` needs `--include-debug-libs`. -`make_game.py`'s `runtime` stage makes this same build on Linux when the tools and the SDK are there (`--runtime-build -runtime/build/windows` takes a folder made by hand like a Windows build). CMake packages are -looked up only inside the SDK folder, so a Windows SDL3 for the GameInput shim is passed as `-DSDL3_DIR=` (`CMAKE_PREFIX_PATH` is not searched here). - -### Proton's wine - -Proton's wine runs the suite against the D3D12 a Proton game gets: the prefix's vkd3d-proton and DXVK. Start any -program once with `proton run` so that it lays down the prefix libraries; the `STEAM_COMPAT_DATA_PATH` folder has to -exist first, because Proton opens `/pfx.lock` in it: - -```sh -mkdir -p ~/.local/share/leonida-proton -STEAM_COMPAT_DATA_PATH="$HOME/.local/share/leonida-proton" \ -STEAM_COMPAT_CLIENT_INSTALL_PATH="$HOME/.local/share/Steam" \ - "$HOME/.local/share/Steam/steamapps/common/Proton 11.0/proton" run cmd /c exit 0 -cmake -S runtime -B runtime/build/proton --toolchain "$PWD/runtime/cmake/clang-cl-xwin.cmake" \ - -DXWIN_DIR="$HOME/.local/share/xwin-sdk" \ - -DCMAKE_CROSSCOMPILING_EMULATOR="$HOME/.local/share/Steam/steamapps/common/Proton 11.0/files/bin/wine" -cmake --build runtime/build/proton --parallel 2 -WINEPREFIX="$HOME/.local/share/leonida-proton/pfx" WINEDLLOVERRIDES="d3d12=n;d3d12core=n;dxgi=n" \ - WINEDEBUG=-all ctest --test-dir runtime/build/proton -``` - -`proton run` itself doesn't pass the program's output on, so the tests can't run through it. `WINEPREFIX` must be -the prefix the emulator made: a prefix from another wine version fails every test with "wine client error: version -mismatch". The tests need a real display here as well. - -Measured on 2026-11-23 with Proton 11.0 (wine-11.0, vkd3d-proton 3.0) on an RX 7600 XT (radv): 155 tests -registered, 154 run, 127 passed, 20 skipped, one disabled and seven failed. The skips are the usual ones (game data, -`LEONIDA_FIRST_LIGHT_DIR`, no independent Vulkan queue for `d3d12_queue_wait`, and so on). All seven failures are in -the comparisons with the host D3D12, which is vkd3d-proton here: - -- `d3d12_fence_timing`, `d3d12_private_data`, `d3d12_sampler2` and `d3d12_subresource_copy` disagree with - vkd3d-proton on a return value or a field it writes (`GetCustomHeapProperties` of a custom heap type, - `SetName(nullptr)`, unknown sampler flags, CPU-copy boxes). -- `d3d12_r9g9b9e5_uav` compares a clear with WARP, and Proton's dxgi answers `EnumWarpAdapter` with the first - hardware adapter ("WARP not supported"), so the compared value is the hardware's. -- `d3d12_compute` and `d3d12_method_variants` crash with an access violation inside `d3d12core.dll` on their - null-argument checks, not on device creation: `GetCachedBlob(nullptr)` and `CreateCommandQueue1(nullptr, ...)` - are not validated by vkd3d-proton (filed upstream as vkd3d-proton issues 3512 and 3513; Wine's builtin d3d12 - crashes on the queue one too). `d3d12_compute` passes with only `WINEDLLOVERRIDES="dxgi=n"`, where the host is - Wine's own d3d12 and the comparison skips. - -The host's D3D12 here is Wine's vkd3d or vkd3d-proton, not Microsoft's runtime, and Proton's `EnumWarpAdapter` -returns the hardware adapter, so "WARP" is vkd3d-proton on the GPU. Most tests that compare with the host or WARP -skip that comparison under Wine and Proton (`runtime/test/host_wine.h`), and most of them still check the layer -against Microsoft's answers recorded in the test (`d3d12_subresource_copy` and `d3d12_private_data` keep theirs in -`d3d12_subresource_copy_answers.h` and `d3d12_private_data_answers.h`). -A few still compare with the host (`root_sig`, `device_proxy`, and some of `d3d12_vulkan_device`'s cases), so some -of those fail for that reason. - -### Run a Windows CI artifact under Wine - -The `Runtime` workflow uploads `runtime-windows` for seven days. It contains the Windows executables, DLLs, -synthetic test shaders, CTest inventory and the path of the Windows checkout. From a clean checkout of the commit -used by the Windows job, set `run_id` to the Actions run ID and download the artifact to `runtime/build`: - -```sh -gh run download "$run_id" --repo ItsNotRexed/Leonida --name runtime-windows --dir runtime/build - -WINE=wine WINEPREFIX="$(mktemp -d)" WINEDLLOVERRIDES="mscoree,mshtml=" WINEDEBUG=-all \ - bash scripts/run_wine_session.sh python3 -I scripts/run_wine_tests.py \ - --tests runtime/build/ctest.json \ - --windows-root "$(cat runtime/build/windows-root.txt)" \ - --require loader --require pe_loader --require loader_tls --require unimplemented_policy \ - --require run_tiny_game --require run_tiny_game_exit_code -``` - -The session script initializes a dedicated prefix and stops its Wine processes at exit. On a headless host, -put `xvfb-run -a` before `bash` so prefix initialization and the tests share one virtual display. The test runner -maps the recorded Windows drive to the Linux checkout for shaders referenced by absolute Windows paths. It prints -every verdict and returns a failure status if any required test fails, skips or is missing. Check the printed -verdicts for failures outside the required set. - -Under GitHub Actions the runner also writes its verdicts as annotations, which anyone can read on the run's page -without a login (the job log and the step summary need one): notices that name every failed test and every skipped -test, a warning with the last output of each test that ran into its time limit, and an end notice with the counts -and the slowest tests. A failed test's entry gives its exit code or time-out, the first lines it printed that name a -failed check (`FAIL ...`, `line N: ...`, `... MISMATCH`) and the last line it printed that is not the runtime's -`[rt]` log; a skipped test's entry gives its exit code and last line. GitHub cuts a notice at 4096 characters and -shows ten per step, so a long list is split over numbered notices (`1 of 3`): up to four for the failed tests and -two for the skipped ones. - -## GPUs with 32-wide subgroups (NVIDIA, Intel, Apple) - -The game's shaders are mostly wave64. A GPU that can't run 64-wide compute subgroups skips the wave64 tests -(`cs_wavemask`, `cs_wave64_ballot`, `cs_wm_*`, `cs_w64x_*`, `ms_w64x_ballot`); that's expected, not a failure. - -To test the wave64 emulation that makes them exact on these GPUs, set `LEONIDA_W64_EMULATE=1`, **for both -`build.py` and `check.py`**: `build.py` translates with emulation only when it's set. If you set it only for -`check.py`, the shaders are checked against the emulated expectations without being emulated, and every wave64 test -fails. - -`scripts/bench_wave64.py` normally compares emulation on AMD and NVIDIA with a native-wave64 AMD reference. On a -machine without that reference, use `--emulated-only` to time the current Vulkan device instead: - -```sh -export LLVM_MC="$(brew --prefix llvm)/bin/llvm-mc" # bench_wave64.py reads --llvm-mc from LLVM_MC -python3 -I scripts/bench_wave64.py --build runtime/build/linux --emulated-only -``` - -This mode builds only the emulated shader, requires every benchmark process to finish the shader's `0 mismatches` -self-check and requires the output hash to stay identical between processes. It says `no native reference` in the -result: the run establishes deterministic self-consistency on that device, not equality with native Wave64. The mode -leaves `LEONIDA_VK_DEVICE`, `VK_DRIVER_FILES` and `VK_LOADER_DRIVERS_SELECT` untouched; on macOS the test tools use -MoltenVK directly by default. - -`ps_bitmask_perm` is a wave32 pixel shader, and a pixel shader's width can't be requested on every device. Intel -drivers report subgroups of 8..32 and may run it 8 or 16 wide; its second pattern reads lanes 16-31, which then -don't run. The test skips when the frame shows that (#1318), and the translation gives 0 for a source lane that -isn't running instead of an undefined value (#618). At 16 wide the first pattern stays inside the running lanes, so -it is still checked before the skip. -The wave32 tests whose words depend on 32 lanes (`cs_dpp*`, `cs_bpermute32`, `cs_exec_const`, `cs_wqm_w32`, -`cs_w32_*`, and in `check.py` every compute test the index records at 32) ask `vk_compute_test` for 32 lanes -(`VKC_SUBGROUP_SIZE=32`). MoltenVK can't require a subgroup size (`requiredSubgroupSizeStages` is 0, sizes 4..32), -but its default is 32 and the translator's SPIR-V 1.5 doesn't allow varying sizes, so Vulkan fixes the size at 32. -`vk_compute_test` checks that with a probe shader before the test (where the device has compute ballots): same -local size and flags as the test's `main`, every subgroup 32 lanes wide by its own lane numbers and ballot, and the -lanes in invocation order, which the translator assumes. It prints `compute subgroup size: 32 (observed: ...)` and -the test is judged. A wrong width fails the test with `observed wrong` and the first wrong invocation; 32-lane -subgroups in another order print `not available`, a skip. Measured -on an Apple M3 Max (MoltenVK 1.4.2 and 1.4.3): 17 workgroup shapes from 1 to 1024 invocations, partial last -subgroups, with and without full subgroups and register pressure, all 32 lanes in order. A device whose default -isn't the requested size still prints `not available`, and those tests skip. - -## Wave64 pixel, vertex and geometry shaders (`w64_graphics.py`) - -Graphics stages have no emulation: on a 32-wide subgroup a wave64 VS, PS or GS runs as two 32-lane halves, and the -translator marks each one tier A, B or C by whether that can change its results (`docs/design.md`, "Wave64 graphics: -partition invariance"). `runtime/test/shaders/w64_graphics.py` checks those tiers on a GPU by running each `ps_w64_*`, -`vs_w64_*` and `gs_w64_*` fixture at wave64 and at wave32: tier A and B must give the same words both ways, tier C -must differ. CI has no GPU, and the CPU wave interpreter (`tests/semantic/test_wave64_halves.py`) runs vertex shaders -only, so this comparison needs real hardware. - -Vulkan can require a subgroup size for pixel shaders (`VKH_SUBGROUP_SIZE`) where the driver lists the fragment stage in -`requiredSubgroupSizeStages`, but not for vertex or geometry shaders, so those two use a RADV switch instead: on GFX10 -and newer, RADV runs them as wave64 by default and as wave32 with `RADV_PERFTEST=gewave32`. The runner sets it itself -and checks the result with a probe fixture per stage (`vs_w64_c_lane_id`, `gs_w64_c_lane_id`): the largest lane id -must reach 32 at wave64 and stay below 32 at wave32. On other drivers (AMD Windows, NVIDIA, Intel) the probe sees no -change, and only the default-size checks run; tier C is then a `SKIP`, not a failure. Not every driver lists the -fragment stage either: on an RX 6800 (RDNA2) with AMD's Windows driver 26.11.2 the list is compute only, no size can -be requested for pixel shaders (they run at the 64-wide default), and the tier C pixel fixtures are a `SKIP` too -(2026-11-22, [d3d12_vulkan.md](d3d12_vulkan.md), "Subgroup size"). - -Build and run it on Linux with RADV, pinned to one GPU (`LEONIDA_VK_DEVICE`, see "Choosing the GPU"): - -```sh -cmake -S runtime -B runtime/build/linux -G Ninja && cmake --build runtime/build/linux --target vk_harness -python3 -I runtime/test/shaders/build.py /tmp/w64g -LEONIDA_VK_DEVICE=9070 python3 -I runtime/test/shaders/w64_graphics.py /tmp/w64g runtime/build/linux -LEONIDA_VK_DEVICE=9070 python3 -I runtime/test/shaders/w64_graphics.py /tmp/w64g runtime/build/linux gs_w64_a_ring -``` - -Each line prints `ok`, a `SKIP` with its reason, or what differed. To add a fixture: - -1. Write `runtime/test/shaders/{ps,vs,gs}_w64__.asm` with `; mattr: +wavefrontsize64,-wavefrontsize32` - and a header that says what every result word is. Vertex and geometry fixtures store four words per vertex or - per triangle to the heap record at `0x1000 + 16 * i`, and every word of a tier A or B fixture is a function of - `i` alone, never of the lane (copy the store from `vs_w64_a_skip` or `gs_w64_a_ring`). -2. Add it to `FIXTURES` in `w64_graphics.py` with its tier and a function that gives the expected words for record - `i` (`None` for a word that may depend on the wave size). -3. Add it to `EXPECT` in `tests/test_wave64_halves_fixtures.py` with the tier, reasons and idioms the translator - should give it, and run `python -m pytest tests/test_wave64_halves_fixtures.py`. -4. Run `w64_graphics.py` on a RADV GPU and say which GPU and Mesa version in the pull request. -## GPUs with 128 bytes of push constants (AMD RDNA2 iGPUs on Windows, some Intel Arc drivers) - -The translated shaders take 144 bytes of push constants: s0..s31, then the heap base and the code base. A device whose -`maxPushConstantsSize` is 128, Vulkan's minimum, can't take that, so the texture tests and every test drawn through -`vk_harness` skip there (`unsupported: need 144 push constant bytes, device has 128`); `vulkaninfo` shows the limit. -AMD's older Windows drivers report 128 on RDNA2 iGPUs (Radeon 680M on 22.40.84.06, 610M on 24.10.16.14, the Ryzen 5 -7600's iGPU on 24.10.24); 26.11.2 reports 256 on a Radeon 610M, where these tests run without the variable below. -RADV reports more on the same chips. - -To run them anyway, set `LEONIDA_PC_TAIL_UBO=1` **for both `build.py` and `check.py`** (or for -`run_gpu_tests.py`). The shaders are then translated with `--pc-tail-ubo`: s0..s31 stay in 128 push-constant bytes, -and the heap base and code base move to a uniform block at set 1 (`docs/design.md`, "Push-constant tail as a uniform -block"), which `vk_compute_test`, `vk_store_test`, `vk_harness`, `vk_texture_test`, `vk_sampler_test` and -`vk_bindless_test` bind (`runtime/test/vk_pc_tail.h`). If you set it -only for `check.py`, the shaders read the tail from push constants the programs no longer declare. `--mesh-compute` -(`LEONIDA_MESH_COMPUTE=1`) isn't combined with it yet: its vertex shader still reads the output address from push -constants, so those tests skip. - -## GPUs with 128 bytes of push constants (AMD RDNA2 iGPUs on Windows, some Intel Arc drivers) - -The translated shaders take 144 bytes of push constants: s0..s31, then the heap base and the code base. A device whose -`maxPushConstantsSize` is 128, Vulkan's minimum, can't take that, so the texture tests and every test drawn through -`vk_harness` skip there (`unsupported: need 144 push constant bytes, device has 128`); `vulkaninfo` shows the limit. -AMD's older Windows drivers report 128 on RDNA2 iGPUs (Radeon 680M on 22.40.84.06, 610M on 24.10.16.14, the Ryzen 5 -7600's iGPU on 24.10.24); 26.11.2 reports 256 on a Radeon 610M, where these tests run without the variable below. -RADV reports more on the same chips. - -To run them anyway, set `LEONIDA_PC_TAIL_UBO=1` **for both `build.py` and `check.py`** (or for -`run_gpu_tests.py`). The shaders are then translated with `--pc-tail-ubo`: s0..s31 stay in 128 push-constant bytes, -and the heap base and code base move to a uniform block at set 1 (`docs/design.md`, "Push-constant tail as a uniform -block"), which `vk_compute_test`, `vk_store_test`, `vk_harness`, `vk_texture_test`, `vk_sampler_test` and -`vk_bindless_test` bind (`runtime/test/vk_pc_tail.h`). If you set it -only for `check.py`, the shaders read the tail from push constants the programs no longer declare. `--mesh-compute` -(`LEONIDA_MESH_COMPUTE=1`) isn't combined with it yet: its vertex shader still reads the output address from push -constants, so those tests skip. - -## GPUs without mesh shaders (NVIDIA Pascal and older) - -Without `VK_EXT_mesh_shader`, the `ms_*` tests are skipped; that's expected, not a failure. To test the path that -runs them anyway, set `LEONIDA_MESH_COMPUTE=1` for `run_gpu_tests.py`, together with `LEONIDA_W64_EMULATE=1` on a -32-wide GPU (every mesh shader is wave64). The mesh shaders are then translated with `--mesh-compute`, dispatched as -compute and drawn by a generated vertex shader (`docs/design.md`, "Mesh shaders as compute"), so the device needs -`bufferDeviceAddress` instead, and `shaderInt64` for a module that declares `Int64`. The standalone tools -(`vk_harness`, `vk_compute_test`, `vk_texture_test`, `vk_store_test`, `vk_bindless_test`) read the modules' -capabilities first: they enable `shaderInt64` only for one that declares `Int64` (or `Int64Atomics`), and report 77 -(SKIP, with the reason) when the device lacks it. - -## Without a GPU: Mesa llvmpipe - -Mesa's llvmpipe is a software Vulkan driver (`mesa-vulkan-drivers` on Debian and Ubuntu). CI runs the suite on it -for every pull request that touches the runtime, the scripts or a tool the jobs read (`.github/workflows/runtime.yml` -lists them), and you can do the same on Linux without a GPU: - -```sh -sudo apt-get install -y libvulkan-dev mesa-vulkan-drivers vulkan-tools spirv-tools llvm-19 -cmake -S runtime -B runtime/build/linux && cmake --build runtime/build/linux --parallel -python -I scripts/run_gpu_tests.py --build runtime/build/linux --llvm-mc /usr/lib/llvm-19/bin/llvm-mc -LEONIDA_W64_EMULATE=1 python -I scripts/run_gpu_tests.py --build runtime/build/linux \ - --llvm-mc /usr/lib/llvm-19/bin/llvm-mc --filter cs_ -LEONIDA_BARY_FALLBACK=1 python -I scripts/run_gpu_tests.py --build runtime/build/linux \ - --llvm-mc /usr/lib/llvm-19/bin/llvm-mc -``` - -With Mesa 25.2 (llvmpipe, LLVM 20) the first run passes 52 of 88 and skips 36, the second passes 37 of 39 and -skips 2. The skips are expected: llvmpipe has 8-wide subgroups (so every wave64 test skips without emulation, and -the 32-lane tests `ps_bitmask_perm`, `cs_wqm_w32` and `cs_w32_lane_wrap` skip in both runs), no -`VK_KHR_fragment_shader_barycentric` (`ps_bary`, `ps_persp_bary`, `ps_uniform_branch`, `ps_scc_mask32`) and no -`VK_KHR_maintenance8` (`ps_texoff`). The third run draws those four barycentric tests through the fallback below -(with Mesa 26.0.8 it passes 123 of 189, the first run 120), and CI fails it unless every shader that got a fallback -geometry shader passes. With -`LEONIDA_W64_EMULATE=1` the mesh tests fail on llvmpipe, which is why the second run is limited to compute. This is -an llvmpipe bug, not the translator's (TEST-782, #3127): llvmpipe stores a mesh shader's per-primitive -`CullPrimitiveEXT` by bitcasting the boolean (``) to a float vector, an invalid LLVM cast -(`emit_store_mesh_chan` in `lp_bld_nir_soa.c`, Mesa 26.3.1 and `main`). A constant cull flag is folded away before -that, so the native mesh tests pass; the emulated ones carry it through memory, so it reaches the cast. What the -cast becomes depends on the backend: on x86_64 at 256 bits, LLVM aborts ("LLVM ERROR: Cannot emit physreg copy -instruction"); at 128 bits (`LP_NATIVE_VECTOR_WIDTH=128`) some draw correctly and some draw nothing (with Mesa -26.0.3, `ms_tri`, `ms_w64x_ballot`, `ms_clip` and `ms_f16_pack` pass, while `ms_wave_info_s3` and `ms_v5_workgroup` -stay at the clear color); on arm64 (128 bits) `ms_tri`'s primitive comes out culled, so nothing is drawn. Storing a -constant `false` there instead makes the emulated `ms_tri` draw a frame byte-identical to RADV's (Mesa 26.3.1), and -`ms_tri`, `ms_wave_info_s3`, `ms_w64x_ballot` and `ms_v5_workgroup` byte-identical to NVIDIA's at both widths (Mesa -26.0.3, [measured by @TreXito](https://github.com/ItsNotRexed/Leonida/pull/3838#issuecomment-7086696759), with a 42-line reduced -reproducer). llvmpipe is not a substitute for a result from a -real GPU in [#166](https://github.com/ItsNotRexed/Leonida/issues/166): it catches regressions, not hardware -differences. - -## Macs in CI - -The `macos` job in `.github/workflows/runtime.yml` builds the runtime on GitHub's `macos-26` arm64 runner and runs -`ctest` and `run_gpu_tests.py` on MoltenVK; `macos-python` in `ci.yml` runs the Python suites. The runner is a VM -whose Metal device is "Apple Paravirtual device" (Metal family Mac2, not Apple7): MoltenVK runs on it with 32-wide -subgroups, so the wave64 and "32 lanes on request" tests skip there (about 75 of 190 in November 2026), and Mesa's -KosmicKrisp finds no device. `macos-15` can't build the runtime: Xcode 16's libc++ has no floating-point -`std::from_chars`. A test known to fail on MoltenVK is listed in the step's `EXPECTED_FAILURES` with the pull -request or coordination-issue finding that tracks it; it still runs, and `scripts/ci_expected_failures.py` fails the step -on any other failure. It takes `FAILED_LIST EXIT_STATUS [EXPECTED ...]`, answers `--help`, and reports a list it cannot -read or a non-numeric status as one line with exit code 2. - -## GPUs without fragment barycentrics (NVIDIA Volta, Pascal and older) - -`ps_bary`, `ps_persp_bary`, `ps_uniform_branch` and `ps_scc_mask32` read raw barycentrics, which need -`VK_KHR_fragment_shader_barycentric`. NVIDIA has it from Turing on; Volta (V100, Titan V) and older lack it, as do -llvmpipe and some other drivers. Where the device lacks it those four are skipped; that's expected, not a failure. -To test the fallback that runs them anyway, set `LEONIDA_BARY_FALLBACK=1`, **for both `build.py` and `check.py`** -(or for `run_gpu_tests.py`; CI does this on llvmpipe). The shaders are then translated with `--bary-fallback` and -drawn through a pass-through geometry shader that supplies the barycentrics (`docs/design.md`, "Barycentric -fallback"), so the device needs geometry shaders instead. - -`ps_interp_f16_high` and `ms_f16_pack` read 16-bit interpolants as `PerVertexKHR` inputs, which need the extension -too and which `--bary-fallback` can't express. With `LEONIDA_F16_INTERP_FALLBACK=1` they read halves the producer -exports decoded instead (see Macs, below) and run with or without the bary fallback; `run_gpu_tests.py` turns that -on by itself where the device lacks the extension. Under the bary fallback without it they skip. - -Intel Arc with Mesa ANV currently advertises the native barycentric feature but has a driver bug where translated -pixel shaders can read `BaryCoordKHR.i` as zero (SHADER-925). `make_game.py` detects ANV and automatically translates -with `--bary-fallback`; both entry points accept `LEONIDA_BARY_FALLBACK=1` to force it and -`LEONIDA_BARY_FALLBACK=0` to force native barycentrics. The CLI `--bary-fallback` flag also remains available for -game builds and other manually built fixtures. - -AMD's Windows driver on gfx90c iGPUs (Renoir, Lucienne, Cezanne, Barcelo: Ryzen 4000/5000 mobile and 5000G, GCN 5) -also advertises the feature but returns a wrong third `BaryCoordKHR` component, about 0.99 where a small value is -expected (#5933: Vega 8, PCI 1002:15E7, driver 31.0.21921.13001). `ps_bary`, `ps_persp_bary` and `ps_ij_computed` -fail natively; through the fallback `ps_bary` and `ps_persp_bary` pass. `tools/vk_subgroup_info.py` reports -`barycentric_fallback` for these PCI IDs under `VK_DRIVER_ID_AMD_PROPRIETARY`, so `make_game.py` and -`run_gpu_tests.py` turn the fallback on by themselves there, with the same `LEONIDA_BARY_FALLBACK` override. RADV and -other GCN 5 GPUs are not covered: none has been measured. - -## Macs: 16-bit interpolation without PerVertexKHR - -`ps_interp_f16_high` (and `ms_f16_pack`) normally read 16-bit interpolants through `PerVertexKHR` inputs, which -MoltenVK can't convert to Metal ("PerVertexKHR decoration is not supported in MSL"). `run_gpu_tests.py` asks -`tools/vk_subgroup_info.py` whether the device can take them and, on MoltenVK, translates with -`--f16-interp-fallback` by itself: the vertex or mesh shader then also exports the decoded f16 halves -(`docs/design.md`, "16-bit interpolation without `PerVertexKHR`"). `LEONIDA_F16_INTERP_FALLBACK=1` or `0` forces it -on or off; `build.py` (for `check.py`) translates with the flag only when that variable is `1`. `ms_f16_pack` also runs -on a Mac with `LEONIDA_MESH_COMPUTE=1 LEONIDA_W64_EMULATE=1`. - -## GPUs without VK_KHR_maintenance8 (NVIDIA Pascal and older) - -`ps_texoff` and `ps_texoff_implicit` sample with a run-time texel offset, which needs `VK_KHR_maintenance8`; -without it they're skipped, which is expected, not a failure. To test the fallback, set `LEONIDA_TEXOFF_FALLBACK=1` -**for both `build.py` and `check.py`** (or for `run_gpu_tests.py`): the offset is then folded into the coordinate -(`docs/design.md`, "Texel offsets"), and the +16/-32 sample is judged on every device. - -## Fused multiply-add: GLSL Fma or OpFmaKHR - -`cs_fma_fused` checks that `v_fma_f32`, `v_fmac_f32`, `v_fmaak_f32`, `v_fmamk_f32` (and one `v_fma_f16`) round once, on -operands taken from user SGPRs so the driver cannot fold them. Run it with default `--fma glsl` (GLSL.std.450 `Fma`) or -with `LEONIDA_FMA=khr` **for `build.py`** (or for `run_gpu_tests.py`), which emits `OpFmaKHR`. -That needs `VK_KHR_shader_fma` with `shaderFmaFloat32`; the test programs enable it when the device has it and exit -77 (a SKIP) for a module that needs it on a device without it. The Vulkan specification allows a driver to split GLSL -`Fma` into two roundings, which is why `khr` exists: on AMD Windows (26.11.2) and NVIDIA (617.42) GLSL `Fma` stayed -fused, whereas **Mesa RADV (26.2.6-arch3.1, AMD Radeon RX 6800, Linux)** splits 5 of the 7 f32 ops under `--fma glsl` -(reusing the live `a * a` product in `v3`) and returns 8/8 fused exact under `LEONIDA_FMA=khr`. Under default -`--fma glsl`, `check.py` and `run_gpu_tests.py` therefore accept either the fused or the exact split word for each of -fused, whereas **Mesa RADV (Linux)** splits several of the 7 f32 ops under `--fma glsl` — the exact split count varies -by GPU, Mesa/ACO version, and execution modes (4 of 7 on RX 6800 / Mesa 26.2.6-arch3.1 and RX 7600 / Mesa 27.0.0-devel -with `SignedZeroInfNanPreserve 32`, 5 of 7 on RX 6800 before float controls, 7 of 7 on Radeon Pro V540 RDNA1 / Mesa -25.2.8) — while returning 8/8 fused exact under `LEONIDA_FMA=khr` where supported. Under default `--fma glsl`, -`check.py` and `run_gpu_tests.py` therefore accept either the fused or the exact split word independently for each of -the 7 f32 outputs while still requiring exact f16 round-to-odd (`0x00007351`); under `LEONIDA_FMA=khr`, all 8 words -must be strictly fused. -operands taken from user SGPRs so the driver cannot fold them. It passes with the default translation (`--fma glsl`, -GLSL.std.450 `Fma`) on a driver that keeps `Fma` fused, and with `LEONIDA_FMA=khr` **for `build.py`** (or for -`run_gpu_tests.py`), which emits `OpFmaKHR`. That needs `VK_KHR_shader_fma` with `shaderFmaFloat32`; the test programs -enable it when the device has it and exit 77 (a SKIP) for a module that needs it on a device without it. The Vulkan -specification allows a driver to split GLSL `Fma` into two roundings, which is why `khr` exists. The AMD Windows -(26.11.2) and NVIDIA (617.42) drivers we tried don't. Two do, failing `cs_fma_fused` with `glsl` in words 0, 2, 3 and 5 -(`v_fma_f32`, `v_fmaak_f32`, `v_fmac_f32`), which get the split value: - -- RADV (Mesa 26.3.1, RX 6700 XT, measured in #3004's review). It has `VK_KHR_shader_fma` since Mesa 26.2 (#1364), so - `khr` fixes it, and so does `exact`. -- The Intel UHD Graphics driver (Xe-LP, Windows 101.7088). It has no `VK_KHR_shader_fma`, so only `exact` fixes it. - -`LEONIDA_FMA=exact` (`--fma exact`) builds the single rounding from plain f32 operations and needs no extension; with -it `cs_fma_fused` passes on both of those, on an RTX 3050 Laptop (617.42), an RTX 5060 Laptop (621.01), an RTX 5070 Ti -(621.24) and a Radeon 780M (26.11.2). -Intel UHD Graphics (Xe-LP, Windows 101.7088) splits it too, words 0, 2, 3 and 5 (`v_fma_f32`, `v_fmaak_f32`, -`v_fmac_f32`), and has no `VK_KHR_shader_fma`, so `khr` can't be used there. For such a device, -`LEONIDA_FMA=exact` (`--fma exact`) builds the single rounding from plain f32 operations and needs no extension; -under it, as under `khr`, all 8 words must be strictly fused, and they are on that Intel UHD and on an RTX 3050 -Laptop (617.42). - -## Hardware oracle (optional, AMD) - -`valu_fuzz.py`, `lds_fuzz.py`, `f32_fuzz.py` and `image_fuzz.py` take `--oracle hw`: the same programs run as native -compute kernels on an AMD GPU (`tools/hw_oracle/`; setup in [shader_validation.md](shader_validation.md), "Hardware -oracle"). It needs AMD clang with the amdgcn target (`LEONIDA_AMD_CLANG`), the AMD driver's HIP runtime and a host C -compiler on Windows, or the libdrm launcher on Linux. Without them a run prints `hardware oracle unavailable: ...` and -exits 77, so CI skips it. `image_fuzz.py --oracle hw` loads a linear texture through a T# built for the GPU's family -(GFX11 on gfx11xx, GFX10 on gfx103x; `tests/test_image_fuzz_hw.py` has the exact words) and compares every texel with -its CPU model; add `--negative-control` to check that wrong models are caught. A gfx1150 (RDNA3.5) is not RDNA2: a -match supports the model and does not prove RDNA2. Run these one at a time: a second job on the same GPU can hang it. - -## Choosing the GPU - -With more than one GPU, pick one through the Vulkan loader, for example -`VK_LOADER_DRIVERS_SELECT=*amd*` or `VK_LOADER_DRIVERS_SELECT=nv-vk*` (or `VK_DRIVER_FILES=`). -`vulkaninfo --summary` shows which devices the loader then sees. - -Two GPUs of one vendor share one driver, so the loader cannot tell them apart (an RTX 5070 Ti next to an RTX 3060, -say; without a choice the runtime and every test take the same one: a native driver over Microsoft's Dozen, discrete -over integrated, the first on a tie, `vulkan_device_rank` in `runtime/src/vulkan_device_filter.h`). -`LEONIDA_VK_DEVICE` names the GPU by part of its name, without case: `LEONIDA_VK_DEVICE=5070` or -`LEONIDA_VK_DEVICE=radeon`. The D3D12 tests (`vk_test_device.h`) and the layer's standalone device read it, -and a value that matches no device fails the run instead of testing -another GPU. For the host side of the comparison tests, `LEONIDA_HOST_ADAPTER` picks the D3D12 adapter the same way. -Unset, the host side is the adapter behind the layer's Vulkan device (`runtime/test/host_adapter.h`; `d3d12_buffer_tiles` -by the layer's `GetAdapterLuid()`), so on a PC with two GPUs the layer is compared with its own GPU's driver. -The GPU tools of `runtime/test/shaders` (`vk_compute_test`, `vk_harness`, ...) read it the same way through -`vk_device_pick.h`, and fail with a message naming the filter when it matches no device. - -Two test settings make the layer's standalone device look like a GPU with fewer Vulkan queues, so D3D12 queues share -them (`docs/d3d12_vulkan.md` section 4.4) on any GPU: `LEONIDA_VK_MAX_QUEUES_PER_FAMILY=N` (1 to 16) creates at most -N Vulkan queues per queue family, and `LEONIDA_VK_GRAPHICS_FAMILY_ONLY=1` puts COMPUTE and COPY queues in the -graphics family, as on a GPU without async compute or transfer families. Both together give the shape of the Intel -UHD 770 on Windows and of lavapipe, one family with one queue; the `d3d12_queue_share_one_queue` and -`d3d12_queue_wait_one_queue` tests run that way, and any other test can be run so by hand. The device logs what it -applied; a queue count outside 1 to 16 is ignored, with a message. Only tests apply them: the device that -`gta6rt --run` creates for a game (`LEONIDA_D3D12=vulkan`) ignores both and prints `... is a test setting; the -game's device ignores it`, so leaving them set cannot slow a game down (`run_tiny_frame_queue_test_settings`). - -## Known problems - -| What you see | Cause | What to do | -|---|---|---| -| Under Wine 9.0 (Ubuntu 24.04's `wine`), a test or the runtime waits out every `std::condition_variable` timeout: `wait_registration_admission` ("native drainage complete"), `vk_presenter_sync` (`unblocked_during_present`), `frame_pacer`, `vk_fence_dispatcher_sync`, `context_concurrent_detach` | The STL's timed wait (`_Cnd_timedwait_for_unchecked`) is linked statically from `msvcprt.lib` and reads Windows' `_Mtx_t` layout, while `_Mtx_lock`/`_Mtx_unlock` come from Wine's builtin msvcp140, which used another layout until wine-10.1 (757bd7909fda); the wait never released the mutex (#3796) | Fixed in the build: `runtime/src/crt_timed_wait.cpp` routes the wait through msvcp140's own `_Cnd_timedwait` in every `/MD` binary, and `crt_timed_wait_test` checks it. A binary built before that fix still needs Wine 10.1 or newer (or Proton) | -| `ctest` passes but runs far fewer tests than expected (about 45 instead of 125 on Windows), no `d3d12_*` GPU tests, and `LEONIDA_D3D12=vulkan` does nothing | CMake found no Vulkan headers: `VULKAN_SDK` was not set in the environment that ran CMake (for example a user variable set after the terminal opened), and `CMakeCache.txt` keeps that failed lookup. The configure prints a `CMake Warning` "Vulkan headers not found" | Set `VULKAN_SDK` in that environment (or pass `-DLEONIDA_VULKAN_HEADERS_FETCH=ON`), delete `CMakeCache.txt` and configure again. `-DLEONIDA_REQUIRE_VULKAN=ON` makes this a configure error; CI and `scripts/build_runtime.ps1` (with `VULKAN_SDK` set) pass it | -| Windows refuses to start freshly built test programs ("An Application Control policy has blocked this file"), and the runner stops with a traceback | Smart App Control on Windows 11 | Turn Smart App Control off for the run | -| `tools/hw_oracle` works once, then stops with "hardware oracle unavailable: Windows Defender blocked the launcher ... (WinError 225)" (older runs: an `OSError: [WinError 225] ... contains a virus or potentially unwanted software` traceback) | Defender's machine-learning check flags the small unsigned `leonida_hw_oracle_.exe` that the runner builds in `%TEMP%` (seen as `Trojan:Win32/Bearfoos.A!ml`) and quarantines it; every later run rebuilds and loses it again | Add an exclusion for the build folder (`%TEMP%`) in Windows Security, Virus & threat protection, Manage settings, Exclusions, restore the file from Protection history if you want it back, and rerun. The program is built from `tools/hw_oracle/hw_oracle.c` and is a false positive | -| Validation errors without a VUID, or messages from a layer you didn't ask for | An implicit Vulkan layer from other software (Rockstar Social Club, ReShade, MangoHud, an overlay) | Set `VK_LOADER_LAYERS_DISABLE=~implicit~`. Overlays that hook the swapchain (RivaTuner `VK_LAYER_RTSS`, OBS `VK_LAYER_OBS_HOOK`) can stay loaded: see the next row | -| Validation errors that only your machine shows (e.g. `xbox_present`'s sRGB swapchain `STORAGE` message), with MSI Afterburner/RivaTuner or OBS installed | An overlay layer that hooks the swapchain: while RivaTuner Statistics Server is running, its `VK_LAYER_RTSS` adds `STORAGE` usage to it (OBS's `VK_LAYER_OBS_HOOK` injects `VK_IMAGE_USAGE_STORAGE_BIT` too). In an elevated (administrator) terminal the loader ignores `VK_LOADER_LAYERS_DISABLE` (`VK_LOADER_DEBUG=all` says so), so `~implicit~` leaves the layer in | Run the tests from a normal terminal, close the overlay application, or set the layer's own switch, which works elevated too: `DISABLE_RTSS_LAYER=1`, `DISABLE_VULKAN_OBS_CAPTURE=1` (OBS). Any other layer's switch is the `disable_environment` entry in its manifest (the JSON listed under `HKLM\SOFTWARE\Khronos\Vulkan\ImplicitLayers` or `HKCU\...`). `VK_LOADER_DEBUG=layer` prints the layers that were actually inserted | -| GPU tests crash with an access violation (`0xC0000005`, exit `-1073741819`) right after device creation, with no layer message and validation off (e.g. `d3d12_method_variants` 9 of 10 runs, `xbox_present` 10 of 10, on `main` 561b65a83, RTX 4070 Ti, NVIDIA 616.56) | An implicit layer from an overlay or game tool you did not install for these tests. FPS Monitor's `fpsmonvk64.json` (listed under `HKLM\SOFTWARE\Khronos\Vulkan\ImplicitLayers`) names itself `VK_LAYER_RENDERDOC_Capture`, so `DISABLE_VULKAN_OBS_CAPTURE=1` does not disable it | `VK_LOADER_DEBUG=layer` prints the layers that were actually inserted. That manifest's `disable_environment` is `DISABLE_LAYER=1`; `DISABLE_LAYER=1` or `VK_LOADER_LAYERS_DISABLE=~implicit~` gave 20 of 20 clean runs (a layer's own switch is its `disable_environment` entry, as the row above says) | -| `vk_sync_validation` fails with `LEONIDA_VK_VALIDATION=1` ("the write-after-write hazard was not reported") | Synchronization validation is off although the tests ask for it: an older layer, or a layer setting such as `VK_KHRONOS_VALIDATION_VALIDATE_SYNC=false` or a `vk_layer_settings.txt` that overrides it. Every other GPU test then reports "0 validation errors" without having been checked | Remove the override or update the Vulkan SDK, then rerun `ctest -R vk_sync_validation` until it passes | -| On RADV with Mesa 25.2 (Ubuntu 24.04's default; 25.2.8 measured) or 25.3 (from the source, not run), `cs_w32_salu64` fails with word 2 = `0` (want `0xFFFFFFFF`) and `cs_signed_zero_nan` fails with word 5 = `0` (want `1`). The `cs_signed_zero_nan` failure alone is also measured on RADV 25.0.7 (RX 7800 XT, Debian 13; @mrbean56, #4421) and on ANV 25.2.8 (Intel UHD 630; @theswiss24, #4571); llvmpipe on Mesa 26.0.8 (Ubuntu 26.04) still gives word 5 = `0`, which `check.py` does not judge there (`UNJUDGED_WORDS`) | Two Mesa bugs, not translator bugs (#166). `cs_w32_salu64`: ACO's `combine_add_sub_b2i` reads a temporary without counting the use, so dead-code elimination removes it (`ACO ERROR: ... never defined` with `MESA_SHADER_CACHE_DISABLE=true`); `RADV_DEBUG=llvm` passes. `cs_signed_zero_nan`: NIR's range analysis (`fmul_is_a_number`) calls `0 * x` a number when `x` may be infinite, so the `x != x` check folds to false despite `SignedZeroInfNanPreserve`. The same NIR code is behind llvmpipe's word 5 (#664) and ANV's, since both drivers run NIR; `cs_w32_salu64` is ACO's, so only RADV has it | Expected with these Mesa versions. From the source, the ACO function is gone from Mesa 26.0 and the NIR code was replaced in 26.1 (neither run); RADV from Mesa 26.3.1 passes both on an 8060S (gfx1151) | -| Every test crashes inside `libnvidia-eglcore.so` | NVIDIA's 535 server driver (Ubuntu 24.04's default) | Use driver 615 or newer | -| `build.py`: 0 translated, reason `.text` | An old `build.py` with LLVM 19 | Update to current `main` | -| `vk_harness` doesn't compile: `VK_KHR_maintenance8` names unknown | Vulkan headers older than the SDK the code was written against | Update to current `main` (the code now builds without it), or use current Khronos Vulkan-Headers; conda-forge's package is too old | -| `ps_bary` and `ps_uniform_branch` fail by about 0.9 | The GPU runs pixel shaders wave64 without fragment barycentrics (GCN3 and RDNA1 on RADV), or an old AMD Windows driver (22.40) | Current `main` skips them on such devices; on Windows, update the driver | -| `ps_bary`, `ps_persp_bary` and `ps_ij_computed` read the third barycentric as about 0.99 on a gfx90c iGPU (Vega 8, AMD Windows driver 31.0.21921.13001; #5933) | The driver's native `BaryCoordKHR` is wrong there: the same tests pass through `--bary-fallback`, and natively on RADV (Radeon 8060S) | `tools/vk_subgroup_info.py` turns the fallback on by itself for gfx90c under AMD's driver, and `make_game.py`, `run_gpu_tests.py`, `build.py` and `check.py` follow it when `LEONIDA_BARY_FALLBACK` is unset; `=1` forces the fallback and `=0` forces native barycentrics, where they still fail | -| `cs_w32_salu64` gives eight wrong words on RDNA1 under RADV Mesa 25.2.8 (`0x1E6A2C48 0x1234 0 0x100 47 48 0xFFFF8000 0xFFFFFFFE`, where word 2 should be `0xFFFFFFFF`) | Only the high word of the `s_bfe_i64` result is wrong. The same words appear on four pinned V540s (Navi 12, PCI `1002:7360`) and on a clean upstream/main worktree, and three different valid SPIR-V sign-extension formulations give the same result while the CPU interpreter matches, so this is the driver version rather than the translator (SHADER-276) | Expected with Mesa 25.2.8; the fixture passes on NVIDIA and on AMD's Windows driver. Try a newer Mesa before treating it as a translator bug; do not weaken the fixture's expectation | -| `d3d12_typeless_rtv` fails its WARP comparison on an AMD desktop iGPU (TEST-591) | [Reported on the Ryzen 5 7600X iGPU with Windows 10 build 19045 and AMD 23.40.02](https://github.com/ItsNotRexed/Leonida/issues/166#issuecomment-7083403389). The exact cause is still open. | Retest on a newer Windows and AMD driver combination. Passing results were reported on the [Ryzen 9 7900 iGPU with AMD 25.10.30.02](https://github.com/ItsNotRexed/Leonida/issues/3232#issuecomment-7085263408), a [gfx1036 iGPU with AMD 26.5.2](https://github.com/ItsNotRexed/Leonida/issues/2891#issuecomment-7084023801), and the [Ryzen 7 9800X3D iGPU with driver 32.0.21045.29003](https://github.com/ItsNotRexed/Leonida/pull/3440). | -| `ps_interp_f16_high` fails on a Mac: `PerVertexKHR decoration is not supported in MSL`, then `vkCreateGraphicsPipelines` -3 | MoltenVK can't convert `PerVertexKHR` inputs to Metal | Current `main` translates it with `--f16-interp-fallback` on MoltenVK (see "Macs: 16-bit interpolation") | -| `ps_vcmpx_forms` fails on a Mac: word 1 reads `0xf05e8e16`, want `0xf05e8a12` | MoltenVK's fast-math makes a compare of a NaN with itself true (SHADER-234) | Current `main`'s test programs turn it off (`MVK_CONFIG_FAST_MATH_ENABLED=0`, unless you set the variable yourself); rebuild them | -| On a Mac, a translated shader's GPU time is 1.5 to 16 times what it would be without the precise-arithmetic overhead | MoltenVK's SPIRV-Cross turns every `NoContraction` float add, subtract and multiply into a call to an `[[clang::optnone]]` helper that Metal does not inline. MoltenVK 1.4.2 and `main` up to at least `5189f8de` are affected (SHADER-234, [design notes](design.md#translator-status-and-runtime-contract)) | Expected with these MoltenVK versions, and the output is still exact. Before you time shaders on a Mac, build MoltenVK with SPIRV-Cross `98cbb7c0` or newer in `ExternalRevisions/SPIRV-Cross_repo_revision` (KhronosGroup/MoltenVK#2917 moves it to `57e4efcc`), and point `LEONIDA_VULKAN_LOADER` at its `libMoltenVK.dylib` | -| `d3d12_descriptor_test` reports that the set had room for fewer than 5001 2D views and 2100 samplers, and the device logs that the bindless set holds fewer samplers than a full shader-visible sampler heap | The device's descriptor limits, or its `vkGetDescriptorSetLayoutSupport`, allow no bigger bindless set ([d3d12_vulkan.md](d3d12_vulkan.md) section 5). MoltenVK's answer is ignored, since it rejects every layout of `maxPerSetDescriptors` (1212) or more although it runs the full set | Expected where the limits are low. The test still checks the last index of each array and that the next view and sampler are refused | -| `cs_dpp_ops` fails on a Mac with MoltenVK 1.4.2: `out[0..7] = 100 100 11 ...`, want `100 10 11 ...` | MoltenVK 1.4.2's SPIRV-Cross moves the DPP lowering's subgroup ballot and shuffle into a short-circuiting `&&` and `?:`, so only some lanes run them and lane 1 sees its source lane 0 as inactive. SPIRV-Cross `5c372ffb` (in MoltenVK `main`) keeps them out of `?:`; a ballot on the right of `&&` is still moved there in SPIRV-Cross `57e4efcc` | Expected with MoltenVK 1.4.2; it passes with MoltenVK `main` (point `LEONIDA_VULKAN_LOADER` at its `libMoltenVK.dylib`) and on KosmicKrisp | -| `check.py`'s `cs_fma_fused` fails on a Mac with MoltenVK 1.4.2: word 7 reads `15360` (`0x3c00`), want `29521` (`0x7351`) | The f16 multiply-add (round to odd). The MSL of 1.4.2 and of MoltenVK `main` differ only in SPIRV-Cross's precise-arithmetic helpers (`[[clang::optnone]]` and `fma(l, r, 0)` against `math_mode(safe)` and `fma(l, r, -0.0)`, the SHADER-182 / SHADER-234 change) | Expected with MoltenVK 1.4.2; it passes with MoltenVK `main` | -| `gs_tri` and `ms_tri` fail on a Mac | MoltenVK has no geometry stage and no `VK_EXT_mesh_shader` | Current `main` reports them as skipped | -| With `LEONIDA_W64_EMULATE=1` on llvmpipe, the `ms_*` tests fail. Measured with Mesa 26.3.1: on x86_64 at 256-bit vectors (the default there) all six abort with "LLVM ERROR: Cannot emit physreg copy instruction"; on arm64 (128-bit) `ms_tri` draws nothing (the frame stays at the clear color); on x86_64 at 128 bits (`LP_NATIVE_VECTOR_WIDTH=128`) `ms_tri` happened to draw correctly, but with Mesa 26.0.3 `ms_wave_info_s3` and `ms_v5_workgroup` draw nothing there (4 of 6 pass, [measured by @TreXito](https://github.com/ItsNotRexed/Leonida/pull/3838#issuecomment-7086696759)) ([measured runs](https://github.com/ItsNotRexed/Leonida/issues/3127#issuecomment-7086469679)) | An llvmpipe bug: a mesh shader's runtime `CullPrimitiveEXT` is stored through an invalid `bitcast to ` (TEST-782, #3127; see "Without a GPU: Mesa llvmpipe") | Run the mesh tests on llvmpipe without `LEONIDA_W64_EMULATE`, or add `LEONIDA_MESH_COMPUTE=1` (the compute fallback): with it all 6 `ms_*` pass emulated on llvmpipe (x86_64, 256-bit) | -| On a Mac, `valu_fuzz.py --family f16` reads `+0` where the model wants `-0`, from a multiply whose exact product is -0 (`v_mul_f16`, `v_pk_mul_f16`) or from an FMA whose product and addend are both -0 (`v_fma_f16`, `v_fmac_f16`, `v_pk_fma_f16`) | MoltenVK computes a `NoContraction` multiply as `fma(l, r, +0)`, which drops the sign. MoltenVK 1.4.2 and `main` up to at least `5189f8de` are affected (SHADER-182, [design notes](design.md#translator-status-and-runtime-contract)) | Expected with these MoltenVK versions. To run the rest of the fuzzer clean, add `--skip-op` for each of the five ops. To see them match, install Homebrew's `mesa` and use its KosmicKrisp driver: `LEONIDA_VULKAN_LOADER=/opt/homebrew/opt/vulkan-loader/lib/libvulkan.1.dylib VK_DRIVER_FILES=/opt/homebrew/share/vulkan/icd.d/kosmickrisp_mesa_icd.aarch64.json python3 -I tools/valu_fuzz.py --family f16 --build runtime/build/linux`. Or build MoltenVK with SPIRV-Cross `300681bb` or newer in `ExternalRevisions/SPIRV-Cross_repo_revision`, and point `LEONIDA_VULKAN_LOADER` at its `libMoltenVK.dylib` | -| A pixel shader exporting non-canonical f32 NaNs reads back `0x7fc00000` from an RGBA32F color attachment | KosmicKrisp (Mesa 26.3.1), reproduced on Apple M3 Max, M2 Ultra and M1 Pro ([#3125](https://github.com/ItsNotRexed/Leonida/issues/3125)): `nir_to_msl` emits `(NAN)` for `float`-typed NaN constants (`MESA_KK_DEBUG=msl`); MoltenVK 1.4.2 preserved both tested payloads on the same hardware | `ps_nan_payload` allows the measured canonical word only for the NaN channels and only when `vk_harness` reports `driver: KosmicKrisp`. Finite channels and other drivers still require exact words. Integer or storage-buffer readback still canonicalizes constants that NIR infers as `float` (see the `cs_bvh` row below). | -| `cs_bvh` and `cs_bvh32` fail on a Mac with KosmicKrisp: `out[3]` reads `0x7fc00000`, want `0xffffffff` | KosmicKrisp's `nir_to_msl` compiler (Mesa 26.3.1, measured on Apple M2 Ultra, macOS 27.3), not the translator or the buffer format. The triangle branch writes bitcast `float` words and the box branch writes `OpSelect %uint` with `0xffffffff` (`-1`) into the same VGPRs; NIR erases `OpBitcast`, type inference marks the shared register and `bcsel` as `float`, and `nir_to_msl` prints any `float`-typed 32-bit constant in the IEEE-754 NaN range (`0x7f800001..0x7fffffff`, `0xff800001..0xffffffff`) as `(NAN)` (`0x7fc00000`) | Expected with KosmicKrisp in Mesa 26.3.1; MoltenVK 1.4.2 and llvmpipe (Mesa 26.3.1) return `0xffffffff` on the same machine. Do not weaken `vk_compute_test`'s expected BVH words | -| CMake stops with "needs the Windows SDK 10.0.26100 or newer", or MSVC reports `'Desc_1_2': is not a member of 'D3D12_VERSIONED_ROOT_SIGNATURE_DESC'` | A Windows SDK older than 10.0.26100 (10.0.22621 is the common one), which has no version 1.2 root signatures | `winget install Microsoft.WindowsSDK.10.0.26100`, or add it in the Visual Studio Installer, then delete `runtime/build` and configure again | -| `ctest` lists `fsr_dispatch` and `bvh_builder` as failed (`Not Run`) after clang-cl hits an internal compiler error in `fsr_dispatch_test.cpp` and `bvh_builder_test.cpp` | clang-cl 22.1.8 on Fedora (Linux cross-build) and Windows, plus 22.1.7 on Windows | Use clang-cl 23.1.6 (both files compile on Windows) | -| `d3d12_compute`, `d3d12_draw` or another test that writes a shader library under the temp directory fails now and then (a PSO creation `line N: SUCCEEDED(...)`, or exit 3 with no message) but passes when run alone | Two copies running at once (`ctest -j`, or two suites sharing one Wine prefix or `TMPDIR`) used the same `leonida_` folder under the temp directory, and one copy deleted the shader modules the other was loading: 6 of 40 runs failed with four copies of `d3d12_compute` at once on a Mac under Wine | Current `main` gives each process its own folder (`/leonida__`) | -| A Windows CI artifact run under Wine by hand: `d3d12_compute` and the other tests that read `LEONIDA_TEST_*_SPV` end with exit 3 and no message | The `.spv` paths are compiled in as `D:/a/Leonida/Leonida/runtime/build/generated/...`; the prefix has no `D:` drive and the test isn't run from the artifact folder | Run it from the artifact folder (the tests then find `generated/.spv` there) or through `scripts/run_wine_tests.py`, which maps that drive for the run; current `main` names the file it couldn't copy (`cannot copy ...: File not found`) | -| Under Ubuntu's Wine 9.0 a test stops with `wine: Call from ... to unimplemented function KERNEL32.dll.CopyFile2, aborting` | MSVC's `std::filesystem::copy_file` calls `CopyFile2`, which that Wine doesn't implement. In the `wine (ubuntu)` job of 24 November 2026 it stopped `module_names`, `d3d12_depth_resolve`, `d3d12_compute`, `d3d12_fspx_compute`, `d3d12_draw` and `d3d12_pso_validation` before the job reached its time limit; WineHQ stable 11.0 ran the same tests without it | Current `main` copies with `CopyFileW`: a test uses `testfiles::copy_file` (`runtime/test/test_temp_dir.h`), not `std::filesystem::copy_file` | -| A test that crashes under Wine runs until its time limit instead of failing at once; its output ends with `starting debugger...` | Wine starts `winedbg` for a crashed program, and without a terminal it waits: 120 s for each crashed test in CI, under Wine 9.0 and 11.0 (`dxgi_host_parity`, `dxgi_waitable_latency`, the deliberate crash in `queue_proxy`'s child, and every `CopyFile2` abort above) | `scripts/run_wine_tests.py` adds `winedbg.exe=d` to each test's `WINEDLLOVERRIDES` unless the value already names `winedbg`; when running a test by hand, add it yourself | -| Linux cross-build: CMake can't find `clang-cl-19` (or another versioned `clang-cl-`) although `clang-19` and `lld-19` are installed | On Debian and Ubuntu, the versioned `clang-cl-` link is in the `clang-tools-` package, not in `clang-` (`/usr/lib/llvm-/bin/clang-cl` comes from it too); `lld-link-`, `llvm-lib`, `llvm-rc` and `llvm-mt` come from `lld-` and `llvm-` | `sudo apt-get install clang-tools-19 lld-19 llvm-19` (Ubuntu 24.04 has 19 and 20), then pass the versioned names as in [the cross-build](#the-windows-runtime-on-linux-under-wine-or-proton) | -| Under Ubuntu's Wine 9.0, `wineboot --init` (and every Wine program after it) stops at once with `free(): invalid pointer` or a segmentation fault, before printing anything else; the prefix holds only a `wineserver` file | That Wine opens `/run/user/` for its server directory, whether `XDG_RUNTIME_DIR` is set or not, and aborts when the folder doesn't exist. The login manager makes it for a desktop session; a container or a shell started without a login session (a root shell in Docker, a CI runner image) has none | Create it before starting Wine: `mkdir -p /run/user/$(id -u) && chmod 700 /run/user/$(id -u)` (setting `XDG_RUNTIME_DIR` alone doesn't help), delete the half-made prefix, and run `wineboot --init` again | -| `run_gpu_tests.py` fails on a `dict \| None` annotation | Python older than 3.10 | Use Python 3.11+ | -| `vulkaninfo` lists `Microsoft Direct3D12 ()` next to the real GPU and the tests run on it | The Windows "OpenCL™, OpenGL® and Vulkan® Compatibility Pack" installs Mesa's Dozen, a Vulkan-on-D3D12 layer that reports `DISCRETE_GPU` like the native card | Current `main` prefers a native ICD over Microsoft's vendor (`0x1414`) in the runtime and every harness; set `LEONIDA_VK_DEVICE=` to select explicitly. See #915. | -| A GPU test that uses `image_load` (or lighting built from real shaders) reads zeros from its image; @Silliana saw every texel except pixel (0,0) come back zero in their own layer (#603, not reproduced here) | In this runtime the shader turns the T# words into an index through the descriptor hash table (`runtime/src/descriptor_table.h`: a miss gives index 0), and index 0 is a 1×1 image of zeros (`runtime/src/vulkan_bindless.h`), so a hand-built or zeroed T# that was never registered reads zeros even at (0,0). The translator does not compare coordinates with the T# size, and `cs_imgload.asm` only uses its T# words as a hash key | Register the descriptor through the runtime (for D3D12, create it with `CreateShaderResourceView`) so its T# hits the table, with the image's real width and height (stored as size − 1, see `runtime/src/gfx10_descriptors.h`) | -| `cs_sample_lz_int_d16`, `ps_sample_implicit_sint`, `ps_ssharp`, `ps_tex`, `ps_texture_mip0`, `ps_texture_sample` and `ps_texture_sample_d16` crash (exit -11 or 139) on an Intel GPU on Linux, while NVIDIA and llvmpipe pass them (TEST-399) | A bug in Mesa ANV's shader compiler: compiling these texture-sampling shaders, `nir_opt_gcm` (`nir_opt_gcm.c:430`, `gcm_schedule_early_src`) dereferences a phi source an earlier pass has freed. The SPIR-V passes `spirv-val`. Seen with Mesa 26.1.6 (Arrow Lake) and 26.2.7 (Iris Xe, ADL GT2); Mesa 26.3.1 and `main` (bb98606) pass the whole suite on the same Iris Xe | Use Mesa 26.3.1 or newer. To check a newer Mesa without installing it, build its Intel Vulkan driver and point `VK_DRIVER_FILES` at its `src/intel/vulkan/intel_devenv_icd.x86_64.json` | -| A test exits with `3221225477` (`0xC0000005`, an access violation) on AMD, only when `VK_INSTANCE_LAYERS=VK_LAYER_LUNARG_api_dump` is set (`d3d12_sparse_queue_family_contract` sets it itself) | The Vulkan SDK's API dump layer (1.4.363.0) crashes the test process now and then: on an RX 9060 XT (RDNA4, Windows driver 32.0.32029.2010) `d3d12_buffer_tiles` and `d3d12_queue_wait` crashed in 1 and 4 of 8 runs in one session and in 3 and 1 of 30 in another; the layer's `detailed` and `pre_dump` settings make no difference. Not seen in 24 runs of those tests without the layer, nor in 8 runs each of the SDK's `vkcube` and `vulkaninfo` with it, so it is not simply the layer on that driver | Run the test again. Do not read a crash under the layer as a failure of the test: run the same program without the layer to check its result, and use `LEONIDA_VK_VALIDATION=1` (the Khronos layer) for validation messages | -| On an AMD integrated GPU (gfx1036) with AMD's Windows driver (`32.0.21042.62` and `32.0.21045.16010` measured), `crosslane_fuzz.py --wave 64 --w64-native --dpp --no-maskdata --seed 82001 --programs 600` reports one native mismatch: `cs_xl64_8200346406` differs in 96 words (32 lanes of each of its three waves), while `--wave64-emulate` and the hardware oracle match | AMD's Windows driver, not the translator (SHADER-705; the driver's generated code was not inspected). The same native wave64 SPIR-V is exact under RADV (Mesa 26.3.1) on another gfx1036 and on an RX 7900 XTX, and in the CPU interpreter. The wrong instruction is a `v_permlanex16_b32` that reads a register a DPP op with a partial `row_mask` has just written ([shader_validation.md](shader_validation.md), FUZZ-7) | Nothing to change in a build: no shader of the game has that shape (0 of 26,503; the two instructions meet in 6 shaders, all wave32 compute). `--wave64-emulate auto` stays native on this driver because of #857, and the emulated translation of the program matches there | -| With `--wave64-emulate` (or `LEONIDA_W64_EMULATE=1`) on an NVIDIA RTX 5080 with Windows driver 32.0.16.1692 (616.92), `crosslane_fuzz.py --seed 91001 --dpp --no-maskdata` reports a hard mismatch for `cs_xl64_9100373886`: after `s_xor_b64 s[16:17], vcc, vcc` (0 in every lane), the second of two nested `v_cndmask_b32_e64 … s[16:17]` returns the old register instead of the lane id | An NVIDIA driver miscompile, not the translator (SHADER-720). The same SPIR-V (spirv-val clean) matches the model on an RTX 3060 with 616.64, an RTX 5060 Ti (Blackwell) with 621.14, an RTX 5070 Ti with 621.24 and an RTX 5080 with the Linux 580.65.06 driver. Hand edits narrow it to a value selected through the `%active` gate of a store; on the Linux 580 driver a similar pattern, a subgroup shuffle selected by an `%active` that is false, still fails in three wave32 `v_permlane16`/`v_permlanex16` programs of the same seed (#3796, #3918) | Update the NVIDIA driver to 621.14 or newer on Windows. If a crosslane mismatch only shows on one driver, check another driver or GPU before changing the translator | -| `lds_fuzz.py --wave 64` (native, not `--emulate`) reports a `ds_bpermute_b32` mismatch on an AMD GPU on Windows, e.g. `cs_ldsfuzz_s7031_496_w64` (seed 7031): small values like `0x14` where the model wants another lane's data, while `--oracle hw` and `--emulate` on another GPU agree with the model | The AMD Windows driver (32.0.21042.62, gfx1036) miscompiles a native wave64 compute shader with two subgroup shuffles; a reduced SPIR-V module is in #4613 | Not a translator regression: check the same seed with `--oracle hw` and with `--emulate`. Native wave64 results on that driver need that cross-check | -| On AMD's Windows driver a compute pipeline creation takes tens of minutes: `vk_pipeline_check` prints `still compiling after ...s` with one busy thread, or a compute PSO creation through the D3D12 layer seems never to return | The driver's compiler on one module in the dispatch-loop form (`"control_flow": "dispatch loop"` in the translated `index.json`). Measured on a Radeon gfx1036 iGPU, driver 32.0.21042.62 (SHADER-995): `XboxBvhBuilder.dll`'s `LeafRehydration` in that form (a 581-case switch in a loop) was created after 34 minutes of one busy thread (XXTESTING), while its structured module is created in 2.9 s and an RTX 3070 (NVIDIA 610.74) created the dispatch-loop one in 11 s. It is not every such module: ten other programs of that DLL compile in that form on the Radeon in 0.4 to 40 s ([embedded_shaders.md](embedded_shaders.md), section 7). Not tried on another AMD GPU or driver branch | Translate with current `main`. Since SHADER-427 only a tree nested deeper than 64, a graph that cannot be made reducible or `--dispatch-loop` gives that form, and none of that DLL's programs has it; the shaders stage translates again by itself when the translator changed. A wave64 compute shader that still has it comes out in another form with `--wave64-emulate on` (12.4 s for this program on that driver), which that driver can crash on for other programs (#857) | - -### Signed zero in a float storage image (SHADER-605) - -Build `vk_store_test` as above and put `spirv-as` and `spirv-val` on PATH. Run this standalone -probe from the repository root, passing the path to the executable you built: - -```powershell -python -I runtime/test/shaders/probe_signed_zero.py runtime/build/vulkan/vk_store_test.exe -``` - -The probe assembles and validates two hand-written Vulkan 1.2 compute modules. Each requests -`SignedZeroInfNanPreserve 32` and executes three constant `OpImageWrite` instructions into -a `VK_FORMAT_R32G32B32A32_SFLOAT` image. Only the SPIR-V image format changes (`Unknown` or -`Rgba32f`). The harness copies the images back, issues a transfer-write to host-read barrier, -waits for completion, and compares all 768 words, including 756 prefilled guard words. -A bit mismatch prints the word index and returns exit code 1. Both variants run even if the -first comparison fails. - -On a GeForce RTX 5070 with Windows driver 616.56, both formats matched 765/768 words. -In the first texel, `(-0, +0, +0, +0)`, word 0 read back as positive zero. The second texel, -`(-0, 1, +0, +0)`, retained every bit. In the third, `(-0, -0, +0, +0)`, words 8 and 9 both -read back as positive zero. All guards matched. This reproduces the discrepancy independently -of RDNA translation. Independent runs of the same probe reproduced those three mismatches on -a Linux RTX 5090 (595.99.02). On Windows, a Ryzen 7 9800X3D Radeon iGPU (25.10.30.02), -an RTX 3080 (616.64) and an RTX 3060 (621.14) preserved all 768 words in both formats. -The device reports are in [PR #3260](https://github.com/ItsNotRexed/Leonida/pull/3260). - -### Which known problems the game's shaders reach - -Several rows of the table above are tied to particular instructions. A GPU test or fuzzer that hits one does -not by itself mean the game does. The counts below say how many of the 26,503 1.0.2.1 shaders (`shaders.rpf`, -LLVM gfx1013) contain those instructions, by stage and by the wave size their FSSM header gives. They are -counts of instructions over the program up to each listing's last `s_endpgm`. They are not reproductions: a -shader that contains an instruction does not have to take the exact path a row describes. - -```sh -python -I tools/op_reach.py /shaders/dxbc/disasm --index /shaders/dxbc/index.json \ - --fssm /shaders/dxbc/fssm s_bfe_i64 '*_dpp' v_permlanex16_b32 ds_bpermute_b32 v_mul_f16 ... -``` - -The corpus has 2,662 wave32 shaders (1,535 CS, 1,127 PS) and 23,841 wave64 shaders (every VS, GS and MS, 1,154 -CS, 10,974 PS). - -| Row | What the game's shaders contain (1.0.2.1) | -|---|---| -| `cs_w32_salu64` on RDNA1 / RADV 25.2.8 (the high word of `s_bfe_i64`) | **No shader uses `s_bfe_i64`** (nor `s_bfe_u64`). The fixture's failure does not reach a game shader. | -| `lds_fuzz.py --wave 64` `ds_bpermute_b32` on AMD's Windows driver | **No wave64 shader uses `ds_bpermute_b32`**: it occurs in 5 wave32 CS (74 instructions), and `ds_permute_b32` in none. | -| `crosslane_fuzz.py --wave 64` on an AMD iGPU (a `v_permlanex16_b32` after a partial-`row_mask` DPP) | DPP in 4,313 shaders, 2,496 of them wave64 (2,364 PS, 113 CS, 17 MS, 2 VS). `v_permlanex16_b32` in 2,293 shaders, 561 of them wave64. Whether any of them pairs the two with a partial `row_mask` is not counted, so these are upper bounds. | -| `cs_dpp_ops` on MoltenVK 1.4.2 | DPP (any `*_dpp`) in 4,313 shaders (66,354 instructions): 1,817 wave32, 2,496 wave64. | -| `valu_fuzz.py --family f16` signed zero on MoltenVK | `v_mul_f16` 124 shaders, `v_fma_f16` 124, `v_fmac_f16` 130, `v_pk_mul_f16` 55, `v_pk_fma_f16` 47, mostly PS (113–115 for the scalar forms). | -| `ps_interp_f16_high` on MoltenVK (16-bit interpolation) | `v_interp_p1ll_f16` / `v_interp_p2_f16` in 4,776 PS (679 wave32, 4,097 wave64), 59,367 instructions each. The count is the instruction, not the `high` operand. | -| `gs_tri` and `ms_tri` on a Mac | 195 GS and 9,282 MS, all wave64. | - -## Posting your result - -Use the template at the top of [#166](https://github.com/ItsNotRexed/Leonida/issues/166): GPU, driver, subgroup -range, OS, the commit you built, the tool versions and the counts each script printed. Post counts and pass/fail -lines only, never shaders or logs from the game. A failure that isn't in the table above gets its own issue, linked -from your entry. - -Use your system's detected CPU, GPU, VRAM and RAM model names in the #166 entry, not benchmark scores. For a rough browser-based check against reference profiles, you can use [Can I Run Leonida](https://assttro.github.io/can-i-run-leonida/). diff --git a/docs/text.md b/docs/text.md deleted file mode 100644 index ce293518f..000000000 --- a/docs/text.md +++ /dev/null @@ -1,212 +0,0 @@ -# Text: string tables and dialogue subtitles - -**Status: decoded.** Every string table the descriptor search finds in `data.rpf`, `story000.rpf` and -`shared_minigame000.rpf` is read, and every dialogue line is joined to its subtitles. Labels are stored only as -hashes. Dialogue labels are named by the conversation data; other labels are named only when a dictionary holds them. -The tables have no language field, so the language is a guess (below). - -Measured on the Xbox Series 1.0.2.1 package on 2026-11-22. The outputs quote game text, so they are local work -products: do not commit them or attach them to an issue. The test fixtures are synthetic. - -## String tables - -A string table is a `0DRP` logical resource ([page_directory.md](page_directory.md)): the `0DRP` stream joined with -the 64 KiB streams that continue it. Its payload holds a hash table, an index array and a string blob. A descriptor -in the resource locates the three. All pointers are `0x5xxxxxxx` resource pointers; the low 28 bits are offsets -into the logical resource. - -``` -descriptor ptr index | u32 | u32 0x10 | ptr | 01 01 00 00 | u32 hash_bytes | ptr hash - | u32 0x10 | u32 blob_bytes | ptr blob | ... more entries (u32 tag, u32 bytes, ptr) -ptr u32 0x5xxxxxxx, u32 0 -hash entry 16 bytes: u32 joaat(lowercase label), u32 0, u8 1, u8[2], u24 index (at +11), u8 -index entry 16 bytes: u64, u64 (offset in its blob chunk << 20 | flags); the chunk is flags & 3 -blob NUL-terminated UTF-8 strings, in one or more chunks -``` - -A hash entry whose first word is 0, whose second word is not 0, or whose byte at +8 is not 1 is an empty slot. Text -keeps the game's inline markup (`~o~`, `~s~`, `~n~`, `~sl:0.05:0.9~`, `~COLOR_SUBTITLE_FOREIGN_DIALOGUE~`, ...). - -### Blob chunks - -From the blob on, the descriptor is a run of 16-byte entries: u32 tag, u32 bytes, pointer. The run ends at the first -16 bytes whose pointer word is not a `0x5xxxxxxx` pointer. A table with more than 1 MiB of text has several tag -`0x10` entries instead of one. Each is a blob chunk of at most 1 MiB, and the chunks need not be contiguous. An -index entry's second word names its chunk: its low 20 bits are always `0b1cc`, where `cc` is the chunk, and the bits -above them are the offset inside that chunk. - -Measured on `data.rpf` (counts only): - -| | | -|---|---:| -| Tables with more than one chunk | 23 (3 of them contiguous) | -| Chunks per such table | 2-4 | -| Index entries in them | 649,246 | -| Low 20 bits `0b100` / `0b101` / `0b110` / `0b111`, all tables | 3,914,583 / 220,161 / 66,416 / 6,721 | -| Index entries pointing at the start of a string, chunk = `flags & 3` | 4,207,881 of 4,207,881 | - -Before this rule, `text_tables.py` read every offset from the first chunk, which is a full 1 MiB. The offset then -landed inside some other string, so 293,292 strings in those 23 tables came out with the wrong text and no error. -The other 14,459 `data.rpf` tables read the same as before. So do all 15,951 tables of `story000.rpf` and all 78 -of `shared_minigame000.rpf`. - -| Archive | Tables | -|---|---:| -| `data.rpf` | 14,482 | -| `story000.rpf` | 15,951 | -| `shared_minigame000.rpf` | 78 | -| **Total** | **30,511** tables, 7,530,381 strings | - -The same 14,482 `data.rpf` tables come out of a directory carved by `rpf9_carve.py`, the archive read directly, and -an older carve that wrote each resource as one file. - -### Language - -The tables carry no language field. Each table's language is guessed from the first 400 strings: - -1. **Script.** Kana is `ja`, hangul is `ko`, CJK is Chinese and Cyrillic is `ru`. -2. **Latin script.** Common words and distinctive letters (`ąćęłńśźż`, `äöüß`, `ãõ`, `ñ¿¡`, ...) score each of `en`, - `de`, `es`, `fr`, `it`, `pl` and `pt`. No score, or a tie, gives `xx`. -3. **Variants.** Spanish and Chinese ship two variants each: - - Chinese splits by characters that differ between Traditional and Simplified script (`這`/`这`). - - Spanish splits by Spain's second-person plural (`vosotros`, `habéis`) and vocabulary against Latin America's - (`ustedes`, `celular`, `ahorita`). - - A table without a marker keeps the plain `es` or `zh` code. - -The table below counts these per-table guesses. Since the nested-archive rule (next section), they are the `guess` -column of `--tables`. - -| Language | Tables | Distinct label hashes | Hashes with a second, different text | -|---|---:|---:|---:| -| `en` | 2,190 | 545,145 | 337 | -| `de` | 2,236 | 552,563 | 127 | -| `es-ES` | 1,649 | 525,316 | 4,542 | -| `es-419` | 1,568 | 509,876 | 5,220 | -| `es` (no marker) | 1,214 | 37,802 | 18,852 | -| `fr` | 2,031 | 535,263 | 210 | -| `it` | 2,063 | 544,165 | 56 | -| `ja` | 2,326 | 552,111 | 35 | -| `ko` | 2,334 | 554,576 | 35 | -| `pl` | 2,280 | 547,423 | 58 | -| `pt` | 2,395 | 548,445 | 5,392 | -| `ru` | 2,327 | 545,820 | 33 | -| `zh-Hans` | 2,221 | 553,483 | 81 | -| `zh-Hant` | 2,206 | 554,441 | 34 | -| `zh` (no marker) | 250 | 839 | 252 | -| `xx` (undecided) | 1,059 | 3,652 | 2,246 | - -The last column counts label hashes whose text differs between two tables of the same language. A clean split -leaves a few dozen of them (about 35 for `ja`, `ko`, `ru` and `zh-Hant`). Above that there are two causes: - -- **Variants mixed.** The plain `es`, `zh` and `xx` rows hold small UI tables without enough text to decide. In the - marked Spanish rows about 1% of hashes still disagree. The `pt` row holds some tables of another language. -- **Labels with two texts.** Some labels exist in two tables of one language with different text. For example, a - line spoken in Spanish has a plain subtitle in one table and an `In Spanish: …` subtitle under - `~COLOR_SUBTITLE_FOREIGN_DIALOGUE~` in another. This accounts for most of the `en` and `fr` counts. - -The dialogue table keeps one text per label and language: the last table read wins. `--strings` writes every table -separately, so nothing is lost. - -### Language from the nested archive - -In `data.rpf`, `story000.rpf` and `shared_minigame000.rpf` every string table sits in one of 13 nested RPF9 archives: -`9FPR` headers at 4 KiB-aligned offsets, whose data offset at +4 stays inside the file. Each of those archives holds a -single language. `text_tables.py` therefore gives every table in a nested archive the guess that most of that archive's -tables share (`xx` left out), when that guess covers more than half of them. A table outside a nested archive, or in an -archive with no majority, keeps its own guess. The tool finds the archive in an `.rpf` source, or in the archive that an -`rpf9_carve.py` directory's `index.json` names. Without it, every table keeps its own guess. -`story000_restofworld.rpf` has 18 nested archives, but the descriptor search finds no string table in it: none of its -101 `0DRP` resources matches the table descriptor. - -Measured with the per-table guess (counts only): - -| | `data.rpf` | `story000.rpf` | `shared_minigame000.rpf` | `story000_restofworld.rpf` | -|---|---:|---:|---:|---:| -| Nested archives (all) | 41 | 436 | 48 | 18 | -| Nested archives holding string tables | 13 | 13 | 13 | 0 | -| Tables in them / all tables | 14,482 / 14,482 | 15,831 / 15,831 | 78 / 78 | 0 / 0 | -| Tables per archive | 1,109-1,113 | 1,214-1,220 | 6 | - | -| Per-table guess equal to its archive's language | 57.7%-99.9% | 72.2%-100% | 66.7%-100% | - | -| Tables whose language changes | 2,075 | 849 | 5 | 0 | -| `xx` before / after | 869 / 0 | 188 / 0 | 2 / 0 | 0 / 0 | -| Plain `es` before / after | 659 / 0 | 553 / 0 | 2 / 0 | 0 / 0 | -| Plain `zh` before / after | 203 / 0 | 47 / 0 | 0 / 0 | 0 / 0 | - -The three archives that hold tables share the 13 languages in the same order: `en`, `pt`, `zh-Hans`, `zh-Hant`, `fr`, -`de`, `it`, `ja`, `ko`, `es-419`, `pl`, `ru`, `es-ES`. The lowest agreement is in the Spanish archives: in `data.rpf` and -`story000.rpf` 208 to 314 tables per archive had no variant marker, and in `shared_minigame000.rpf` the `es-ES` archive -agrees on 4 of its 6 tables. - -Reading `story000.rpf` this way needs the `rpf9_carve.py` that checks a gap in chunks (#2117): one unread gap there is -9.56 GB, and slicing it whole ran out of memory. - -## Dialogue - -Conversation data (PSO streams) pairs a dialogue key with its line labels as `AU_\0] -``` - -`--overlay` is where a mapped title's writes go (default `\overlay`); `GAME:` paths read from -`--game-dir`. See [Console paths and the write overlay](../docs/runtime_imports.md#console-paths-and-the-write-overlay). - -The dry run maps the image and the bundled modules it imports, applies base relocations, binds every -import through the shim registry, a host DLL, or another bundled module, parses exports, installs static -TLS for the calling thread, applies section protections, and -prints a per-module report. It does **not** call `DllMain`, TLS callbacks, or the entry point, so no -code from the mapped images runs. TLS reserves its module index through the runtime's own -`gta6rt_tls_host.dll`, and host imports load system DLLs, as they did before. - -`gta6rt --init ` runs the same mapping and then `Loader::initialise()`: each module's TLS -callbacks and each DLL's `DllMain(DLL_PROCESS_ATTACH)`, dependencies first. An EXE's entry point is not -run. When the loader is destroyed, initialised modules receive TLS callbacks and DLL entry-point calls with -`DLL_PROCESS_DETACH`, in reverse initialisation order. All mapped images, unwind tables and static TLS stay -available until these notifications finish, so DLLs can release resources such as FLS callbacks safely. The reserved -argument is null (explicit unload). A map-only load receives no detach notifications. - -`--dry-run`, `--init` and `--run` are separate modes: give exactly one. Two together (`--dry-run --run`) -print the usage and exit 2 before anything is mapped. - -`--init` and `--run` first check that the host can run the game's AVX code (CPUID.1 AVX and OSXSAVE, XCR0 YMM -state; `src/host_cpu.h`). Without it they print one line naming what is missing and exit 4 before anything is -mapped. In a virtual machine, pass the host CPU through (QEMU `-cpu host`); under Rosetta on macOS, set -`ROSETTA_ADVERTISE_AVX=1`. `LEONIDA_SKIP_CPU_CHECK=1` skips the check; `--dry-run` never runs it. - -The report line is: - -``` - base= size= entry=+ shim=N host=N module=N unimplemented=N -``` - -Shim and unimplemented imports are listed by name. A non-zero `unimplemented` count is the useful -signal: it names the next shim that is missing. The measured result for the 16 DLLs shipped in the -package is recorded in the runtime-imports documentation. - -After the totals the report counts the unimplemented imports by return class, and marks the HRESULT ones in the list: - -``` - UNIMPLEMENTED xgameruntime.dll!XUserAddAsync [returns HRESULT] -1 module(s) mapped, 1 unimplemented import(s) -unimplemented by return policy: hresult=1 other=0 -``` - -### Unimplemented imports at run time: `LEONIDA_UNIMPLEMENTED` - -An import with no shim, host function or bundled module is bound to a thunk. What a call to it does is set by the -environment variable `LEONIDA_UNIMPLEMENTED`, read once per process: - -| value | a call to the thunk | -|---|---| -| `log` (default) | prints `[rt] unimplemented: dll!name` once and returns 0 in rax and xmm0. This is what the runtime always did. | -| `fail` | the same, but returns `E_NOTIMPL` (`0x80004001`) for imports known to return an `HRESULT`, and 0 for all others. | -| `stop` | on the first call prints the import, the caller's return address as `module+RVA`, and rcx, rdx, r8 and r9 as the game passed them; then breaks if a debugger is attached (continuing returns the `fail` value), else ends the process with exit code 3. | - -No mode writes to an out parameter: a function that fills one in on success leaves it as the caller had it. Under -`log` an `HRESULT` function therefore returns `S_OK` with its outputs unset, which is why `fail` exists; with `fail` -the caller sees an error and can take its own failure path. Any other value is reported and treated as `log`. - -Whether an import returns an `HRESULT` is decided by DLL and name alone (`classify_import` in -`shims/registry.cpp`, where each entry names its source). The list is short on purpose and every entry was checked -against the public Microsoft documentation: `D3D12Create*`/`D3D12Serialize*` and the D3D12 debug/experimental -entries, `CreateDXGIFactory*` and two DXGI functions, `XGameRuntimeInitialize`, and the GDK families `XAsync*`, -`XTaskQueue*`, `XUser*`, `XStore*`, `XGameSave*`, `XPackage*`, `XGameUi*` minus the functions the same pages document -as `void`/`bool`/`int`. A function that is not on the list gets 0 under `fail`, exactly as under `log`. - -The thunk keeps the Win64 argument registers and the return address intact (it is entered by the game's `call`), and -reaches a shared stub that saves them, so a floating-point caller still reads 0.0 from xmm0 and a debugger can unwind -through it. - -### Compat modules: `LEONIDA_COMPAT_DIR` - -Opt-in. When `LEONIDA_COMPAT_DIR` names a folder, an import whose DLL is a file in that folder (matched by file name, -any case) is served by that DLL: Windows loads it from the full path with `LoadLibraryExW` -(`LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR | LOAD_LIBRARY_SEARCH_SYSTEM32`, never the game folder), so its CRT, TLS and SEH -work as for any host DLL and it takes no slot of the mapper's static TLS. This step comes before the shims, the -bundled package DLLs and the host, and the DLL owns all of its module's imports: a symbol it does not export binds to -the unimplemented thunk, not to a shim, so one console DLL is never served by two implementations that do not share -state. The binding is reported as `host`, and `[rt] compat: -> ` is printed once per DLL. A file in the -folder that Windows refuses to load stops the run with the error code. Unset or empty: no change. The DLLs stay -loaded for the process lifetime. Only static imports go through this step; a run-time `LoadLibrary` of the same name -does not yet. - -It exists for drop-in implementations of console DLLs that have no shim here, such as the `AcpHal`, `chad`, `xapu` -and `XCRDAPI` crates of [omonkeyz/xbox-emulator](https://github.com/omonkeyz/xbox-emulator) (GPL-3.0-or-later). -Measured on the 1.0.2.1 executable at `867d922`: without the folder, `--dry-run` leaves 20 imports unimplemented -(AcpHal 9, chad 5, xapu 5, XCRDAPI 1); with those four DLLs built from `f89e410`, it leaves 0, with the four -package DLLs still mapped (`module=72`). Those DLLs run static initializers when Windows loads them, and with the -defaults one of them hooks the process: the package DLLs mapped after it then fail to map. With -`TOMBOX_GDK_EARLY=0 TOMBOX_GDK_RUNTIME=0 TOMBOX_OSHOST=0 TOMBOX_PAD=0 TOMBOX_TIMER_1MS=0` they map; their network -guard stays on and denies all traffic. `loader_test` covers the step with a synthetic DLL (no game data). - -### Repeatable random bytes: `LEONIDA_RNG_SEED` - -With `LEONIDA_RNG_SEED=` (decimal, or hexadecimal with `0x`; read once when the `bcrypt` shim starts), -`BCryptGenRandom` on the RNG algorithms answers from a seeded splitmix64 generator instead of the host's, so two -runs with the same seed get the same bytes. The shim prints `[rt] bcrypt: deterministic LEONIDA_RNG_SEED enabled` -with the seed on stderr; a seed of 0 uses a fixed non-zero state. Unset, the host's generator answers as before. - -## Settings: `leonida.toml` and `gta6rt config` - -Every setting of the runtime is a row of one table, `kSettings` in `runtime/core/config.h`: a name in the settings -file (`section.name`), an environment variable and a default. A value is taken from the first of these that has one: - -1. the environment variable, when it is set and not empty; -2. the settings file; -3. the default. - -The settings file is the one `LEONIDA_CONFIG` names, else `leonida.toml` in the folder of `gta6rt.exe`, if there is -one. `runtime/leonida.example.toml` lists every setting with its default and its variable; copy it and remove the -`# ` in front of what you change. The file is read once, when `gta6rt` starts. A section or name that is not in the -table, a name set twice, or a `LEONIDA_CONFIG` that names no file ends the run with exit code 2 and a line such as -`leonida.toml:12: there is no setting vulkan.validaton`, so a misspelt setting cannot pass as one that does nothing. - -The format is the part of TOML the file needs: `[section]` lines, `name = value` lines and `#` comments. A value is -text in single quotes (taken as written, so a Windows path needs no doubled backslashes), text in double quotes -(only `\\` and `\"` are escapes), a number, or `true`/`false`. `''` leaves a setting unset. - -`gta6rt config` prints the file in use and one line per setting: its name, where its value comes from (`default`, -`file` or `environment`), its variable and the value. - -```text -settings file: C:\leonida\runtime\build\leonida.toml -system.gamertag environment LEONIDA_GAMERTAG Tester -vulkan.validation file LEONIDA_VK_VALIDATION 1 -vulkan.arena_mb default LEONIDA_ARENA_MB 256 -``` - -Only `gta6rt` loads a settings file. The test programs and tools load none, so for them a setting comes from its -environment variable or is the default. - -## Log levels: `LEONIDA_LOG` - -The runtime's diagnostics are the `[rt] : ...` lines on stderr. Each has a level: `error`, `warn`, `info` -or `debug`. `LEONIDA_LOG` (`log.level` in `leonida.toml`) names the highest level that is printed: `off`, `error`, -`warn`, `info`, `debug` or `trace`, in any case. A level prints its own lines and those of the levels before it; -`off` prints none. The default is `debug`, which prints what the runtime printed before it had levels; no line has -the level `trace` yet. There is one level for all modules. - -A value that is not a level prints one warning that lists the levels, and `debug` is used: - -```text -[rt] log: LEONIDA_LOG=loud unknown (off, error, warn, info, debug or trace), using debug -``` - -Not filtered, because they are answers of the program and not log lines: the usage text and the `error: ...` lines -of the command line, the binding report, the `gta6rt config` table and the `[d3d12-trace]` lines of -`--trace-d3d12`. `gta6rt` reads the setting once, at startup. The test programs do not read it and log at the -default. - -In the code a log line is one of the macros of `runtime/core/log.h`, such as `RT_LOG_WARN("module: text\n", ...)`; -the macro adds the `[rt] ` prefix. The header needs no library, so a header-only part of the runtime can log. - -## PE loader - -`src/pe_loader.cpp` maps x86-64 images at their preferred base, or elsewhere (with relocations) when -that base is taken, copies headers and sections, applies `IMAGE_REL_BASED_DIR64` relocations, binds -imports by name or ordinal, parses the export table, sets section protections, and registers the -image's x64 unwind table (`.pdata`) with `RtlAddFunctionTable`, so exceptions raised in or passing -through a mapped image are dispatched and stack walks can step over its frames. The table is validated -first (entries in bounds, sorted and non-overlapping) and removed when the loader is destroyed. Modules -are deduped by basename, so an import graph that reaches the same DLL twice maps it once. The identity -key uses the filesystem's native path representation with ASCII case folded; it does not require a -Windows filename to fit the ANSI code page. A lossless legacy narrow filename alias retains the existing -bytewise case behavior for narrow API and import-name lookups. `Module::name`, mapped address labels, -and path diagnostics use UTF-8. The `LoadLibrary*`/`GetModuleHandle*` shims look a wide name up by its native -basename when it has a character outside ASCII (`Loader::find_loaded_module_w`, `load_runtime_module_w`), and -module names compare case-insensitively with the system's own table (`CompareStringOrdinal`), as Windows -compares them; a narrow name outside ASCII compares the same way through the ANSI code page. - -`module_names` checks native and mapped renamed DLLs, distinct Unicode identities, basename cache -reuse, existing ACP aliases, the wide and case-insensitive lookups, export execution, and path errors. On native Windows with Python available, -`run_module_names` compares original renamed EXEs through native execution and `--dry-run`, `--init`, -and `--run`, including a Unicode parent directory and an ACP-named imported DLL. It checks strict UTF-8 -trace names and unchanged fixture bytes. Both tests use only locally built synthetic images. - -MSVC C++ exceptions need one more piece. `_CxxThrowException` stores the throwing image's base in the -exception record, from `RtlPcToFileHeader`, and the catch side adds the throw's RVAs to it; Windows' own -`RtlPcToFileHeader` only knows images its loader mapped, so for a mapped image the base is 0 and no -`catch` matches. When the loader binds a host copy of the MSVC runtime (`vcruntime140.dll`, -`msvcp140.dll` and the rest of that list), it points that DLL's import of `RtlPcToFileHeader` at a -version that asks Windows first and then the modules a live `Loader` maps. The redirect stays for the -process lifetime and answers as Windows does when no `Loader` is alive. - -`load()` also installs static TLS for the calling thread. `__declspec(thread)` reads `TEB->ThreadLocalStoragePointer[_tls_index]`, which is a -different index space from the `TlsAlloc` slots, and only the OS loader can allocate a module index. -The runtime therefore ships a minimal `gta6rt_tls_host.dll`; the loader reuses the index the OS assigns -it, writes that index into the image's `AddressOfIndex`, and copies the image's TLS template into the -slot. This reserves one index; every additional simultaneous TLS module gets its own by mapping a fresh -clone of the helper from `%TEMP%\leonida_tls_host__.dll`, so up to 16 modules can be live at -once and a further one is rejected with an error instead of sharing a slot. Images without a TLS -directory (or with an all-zero one) load normally. - -A `/GA` executable's code reaches its static TLS directly at index 0 (`mov r64, gs:[58h]`), but the -loader can only get that image an index from the OS, and it need not be 0. Before the image's sections -are protected and before any of its code runs, TLS callbacks included, the loader rewrites each such -slot-0 read in an executable section to the same instruction reading `TEB->TlsSlots[slot]` instead -(`patch_ga_tls_reads`), with one `TlsAlloc` slot per image; the rewrite is the same length, so nothing -else in the image moves. It applies only to an EXE whose own TLS index is not 0 and that has a TLS -directory; the loader's log names the image, the number of rewritten reads and the slot. Set -`LEONIDA_TLS_GA_PATCH=0` to turn the rewrite off, for measuring what the image does without it; any other -value, or leaving it unset, keeps it on. - -Current limits, by design: - -- `load()` runs no image code. Static TLS is data, not code. The TLS index helper is the runtime's own - `gta6rt_tls_host.dll`; host imports still load system DLLs as before. -- `--dry-run` never runs image code. `initialise()` runs TLS callbacks and a DLL's `DllMain`; - `run_tls_callbacks()` is the seam for callers that do not use `initialise()`. An EXE's entry point is - the caller's to run. -- Every thread started after `load()` gets its own copy of the TLS template, from - `gta6rt_tls_host.dll`'s `DLL_THREAD_ATTACH`, and gives it back at `DLL_THREAD_DETACH`, also when the - thread outlives its `Loader`. From `initialise()` until `~Loader` starts the process detach, those - events also run the module's TLS callbacks, with the thread's copy already in place. A thread that - was already running when `load()` ran, such as a worker of the process thread pool that the task queue later runs a - title's callback on, gets its copy from `load()` itself, the way Windows gives one to running threads for a DLL it - loads: a block, no `DLL_THREAD_ATTACH`, `DLL_THREAD_DETACH` when it ends, and `~Loader` takes the block back. - `install_tls_for_thread()` and `uninstall_tls_for_thread()` are no-ops on such a thread. Mapped DLLs' `DllMain` is not called with thread events. Destroy the `Loader` on the thread that - called `load()`. -- The TOC of the game's RPF archives is encrypted and is not read here. The loader works on the PE - files and on any images the caller passes it. - -## Shims - -`shims/registry.cpp` holds the static tables. The current shims are: - -- `xmem.dll` — `XMemAlloc`, `XMemFree`, the measured two-argument `XMemGetWorkingSetStatistics(kind, out)`, and the - measured three-argument - `XMemVirtualQuery(process, address, out)`. Allocations are 64-byte aligned; the working-set and - virtual-query outputs fill the observed 64-byte structures and return `FALSE`/`0` on a null or bad - address. `XMemAllocDefault`/`XMemFreeDefault` share that heap. `XMemVirtualAlloc` accepts the attribute word, - drops the console's `PAGE_GRAPHICS_*` protection bits, commits 2 MiB guest pages 2 MiB-aligned, - and passes `MEM_RESERVE_PLACEHOLDER`/`MEM_REPLACE_PLACEHOLDER` through. Physical pages - (`XMemAllocatePhysicalPages`, `XMemFreePhysicalPages`, `XMemMapPhysicalPages`, `XMemMapPhysicalPagesScatter`) are - 64 KiB pages of pagefile-backed sections, mapped one view per page into the placeholder that a reserve-only - 64 KiB-page `XMemVirtualAlloc` becomes, with that reservation's protection. `XMemIsToolsMemAvailable` is `FALSE`. -- The `kernel32.dll` file API — `CreateFileA/W`, `FindFirstFileA/W`/`FindNextFileA/W`/`FindClose`, - `GetFileAttributesA/W`, `GetFileAttributesExA/W` and `DeleteFileA/W`: a `GAME:` path maps under `--game-dir`, an - open that can write and a delete go to `--overlay DIR` (default `\overlay`), which reads prefer, and a path - that climbs above `GAME:` is refused. The package is never modified. See - [docs/runtime_imports.md](../docs/runtime_imports.md#console-paths-and-the-write-overlay). -- `d3d12_xs.dll` — `D3D12SerializeVersionedRootSignature` and - `D3D12CreateRootSignatureDeserializer`, with the console root-signature high byte (`0x03000000`) - cleared on a copy before forwarding to the PC `d3d12.dll`. `D3D12XboxCreateDevice` wraps a device in - the measured-slot Xbox-ABI proxy: the host PC `ID3D12Device` by default, or the Vulkan-backed device - (`shims/d3d12_vulkan_device.cpp`) when `LEONIDA_D3D12=vulkan` is set and the runtime was built with the - Vulkan SDK and Python 3. The Vulkan device covers command submission, descriptor heaps, render-target and - depth views, committed resources and copies (uploads, readbacks, BC textures), root signatures, graphics and - compute pipeline states, draws, dispatches and `ExecuteIndirect`; see `docs/d3d12_vulkan.md` for what is - missing. - -- `gameinput.dll` / `xgameruntime.dll` — `GameInputCreate`: the v0 GameInput API for gamepads on SDL3 - (`shims/gameinput.cpp`), so any controller SDL supports works, with rumble, Xbox trigger rumble, force feedback - and trigger haptics where SDL opens the pad as a haptic device, and on a DualSense adaptive-trigger effects and the - lightbar. Optional and CMake-only: built when an installed SDL3 is found, - or with `-DLEONIDA_SDL3_FETCH=ON` to download the pinned release; nothing is downloaded otherwise, and the - `scripts/build_runtime.ps1` cl.exe fallback never builds it. See [docs/gameinput.md](../docs/gameinput.md) for the mapping, the `LEONIDA_DS_*` settings and what is - unverified. - -### What `xgameruntime.dll` reports: environment overrides - -The `xgameruntime` shim (`shims/xgameruntime.cpp`) answers the title's questions about the console and its package -with fixed values. Five environment variables change an answer, for trying another of the title's code paths. Each -is read on every call, and a value that is empty or too long for its buffer is ignored. -`tests/test_docs_env_vars.py` fails when the runtime or `make_game.py` reads a `LEONIDA_*` variable that no -document names. - -| variable | default | what it changes | -|---|---|---| -| `LEONIDA_DEVICE_TYPE` | `7` | The `XSystemDeviceType` that `XSystemGetDeviceType` returns: `0` Unknown, `1` Pc, `2` XboxOne, `3` XboxOneS, `4` XboxOneX, `5` XboxOneXDevkit, `6` XboxScarlettLockhart (Series S), `7` XboxScarlettAnaconda (Series X), `8` XboxScarlettDevkit. A number outside 0..8 is ignored; text that is not a number counts as `0`. `6` also makes `XSystemGetAnalyticsInfo` report the form `Xbox Series S` instead of `Xbox Series X`. | -| `LEONIDA_ANALYTICS_FORM` | unset | The `form` string of `XSystemGetAnalyticsInfo`, in place of the one the device type gives (up to 63 characters). | -| `LEONIDA_PACKAGE_ID` | `LeonidaPackageIdentifier00000000` | The identifier `XPackageGetCurrentProcessPackageIdentifier` returns (up to 32 characters). It is also the one identifier `XPackageMount` refuses with `E_ACCESSDENIED`, as the game's own package. | -| `LEONIDA_CONTENT_PACKAGES` | unset | The content packages `XPackageMount` can mount: `id1=path1;id2=path2` (up to 1,023 characters). The mount path of a listed identifier is its path, as written; any other identifier is `ERROR_NOT_FOUND`, and a path longer than 259 characters is `ERROR_INSUFFICIENT_BUFFER`. | -| `LEONIDA_PACKAGED` | `1` | `0`, or text that is not a number, makes `XPackageIsPackagedProcess` return false. Any other number keeps it true. | - -The two serializer functions and `D3D12XboxCreateDevice` are the only `d3d12_xs` imports used by the -shipped DLLs (measured; see `docs/design.md` and `docs/d3d12_vulkan.md`). The game executable's own -imports are unknown until it is available. - -## Tests - -For a Visual Studio build, pass CTest the same configuration you built above. - -```powershell -ctest --test-dir runtime/build -C RelWithDebInfo --output-on-failure -``` - -On Windows the build configures the CPU tests that do not need a GPU or game files, including the -root-signature forwarding test (`root_sig_test`) and the clear-command test. The Vulkan tools and -D3D12-over-Vulkan COM targets are built when Vulkan headers are found (via `VULKAN_SDK`, an installed -SDK, or `-DLEONIDA_VULKAN_HEADERS_FETCH=ON` to download the pinned Khronos Vulkan-Headers release): - -- `vk_harness` — hand-written RDNA2 shader programs on a real Vulkan device. -- `vk_texture_test`, `vk_compute_test`, `vk_store_test` — texture, LDS/compute, and buffer-store paths. -- `vk_command_replay_test`, `d3d12_com_test`, `d3d12_vulkan_device_test` — the D3D12 command path on - Vulkan: replay, the COM command objects, and the Vulkan device behind the Xbox-ABI proxy. -- GPU tests count only validation-type errors. Loader and layer messages, such as a third-party implicit layer - that fails to load, are printed but don't fail the run; to silence one, set - `VK_LOADER_LAYERS_DISABLE=`. -- `d3d12_draw_test` — milestone M1: a VS+PS pipeline found by FSSM hash, the input layout matched by semantic, - and five draws plus a culled triangle, compared pixel by pixel. They also cover an unbound render target and - DSV, a rebound root signature, instance step rate 0, an unbound vertex slot, and PSOs, buffers and heaps that - must be refused. A second pass draws a full-screen triangle with no vertex input and an XOR logic op. -- `d3d12_translated_draw_test` — milestone M1.5: the same with translator output. `test/shaders/vs_m15.asm` (vertex - fetch through a V#) and `ps_m15.asm` (constants read through the code base) are built by `test/shaders/build.py` - and found by FSSM hash; three draws into a float target, compared bit for bit. Needs `llvm-mc` (`LLVM_MC`) and the - Vulkan SDK's `spirv-as` and `spirv-val` at build time. -- `d3d12_compute_test` — the compute path: root signature, a compute PSO found by its FSSM hash in a - translator-style index, root arguments through the GPU address arena, and two dispatches. A second program is - found the same way in `/bvh/index.json`, where the BVH builder's programs go (`docs/embedded_shaders.md`). -- `d3d12_fspx_compute_test` — compute PSOs from synthetic FSPX programs (`docs/fspx.md`): an `ACCC` container - through slot 62 and a bare kind-6 program, found by `fspx_code_sha256` in `/fspx/index.json`, one - dispatch each that reads its kind-6 program as the code base; malformed directories and untranslated programs - are refused with `E_INVALIDARG`. Also slot 67 with all four pairs (picked by kind 0), refused pairs, and the - pipeline's console slot 11. -- `d3d12_set0_compute_test` — set 0 from the compute bind point: a compute PSO whose index entry lists set-0 - bindings, and four dispatches that sample two SRVs, bytes no view was made for and a clamping sampler through - the bindless set the layer binds. -- `d3d12_present_test` — milestone M0: opens a window and presents 60 cleared frames through the proxy on - Vulkan, resizes it and presents 10 more, and checks the colour in the presented images (the presenter's - capture) and on screen where GDI can read it. A driver double then injects an - out-of-date and a suboptimal present, a failed semaphore during a swapchain recreation and a failed blit - submission, which the presenter must survive. Set - `LEONIDA_VK_VALIDATION=1` to run them under the Khronos validation layer. -- `vk_pipeline_check [cache.bin] [--jobs N] [--start I] [--count N] [--max-bytes N]` - - creates a shader module and, for compute shaders, a pipeline for every entry in the translator's - `index.json`; reports `MODULE FAIL` / `PIPELINE FAIL` per shader and a summary. `--max-bytes` - names and skips modules larger than the limit, which is how the corpus run works around the - driver's compile time on multi-megabyte ray-tracing shaders. The measured partial pass is in - [docs/pipeline_check.md](../docs/pipeline_check.md). - -`gameinput_test` (only with SDL3; otherwise CTest lists `gameinput` as not run) drives the GameInput shim on SDL virtual joysticks (no controller needed): enumeration, readings -and the button/axis mapping, rumble and trigger rumble, DualSense effect bytes, a dispatcher, and hot-plug. -`gameinput_probe [--seconds N] [--rumble] [--force-feedback]` is the manual check on a real pad: it prints live -readings, plays each motor and trigger, and holds a constant force on a pad that reports a force-feedback motor. - -`unimplemented_policy_test` builds a small image whose two imports bind to nothing and checks `log`, `fail` and -`stop` on it: return values, untouched out parameter, xmm0 = 0, environment parsing, and (in a child process) the -`stop` message with the caller's module+RVA and the argument registers. It also checks that the stub keeps the stack -16-byte aligned at the call into the runtime, that rbx/rbp/rdi/rsi/r12-r15 and xmm6-xmm15 survive a call -(`test/fixtures/abi_probe.asm`, MASM; skipped without `ml64`), and that `RtlVirtualUnwind` from inside the call walks -back to the caller. - -### PE-loader fuzzer: `pe_loader_fuzz` - -`pe_loader_fuzz` (RT-388) is a deterministic mutation fuzzer for `Loader::load`. Each case builds three small -synthetic DLLs in the test itself (headers and four sections, base relocations, import and delay-import tables, exports -with forwarders and ordinal-only entries, a TLS directory with template, index and callbacks, and an exception -directory with `UNWIND_INFO`), mutates their fields and bytes, writes them to a scratch folder and loads the first one. -A case passes when `load()` returns or throws a `std::exception`, the `Loader` is destroyed again, and after a -successful load every export and unwind table lies inside its image. It fails on a crash, an AddressSanitizer report, -a non-`std::exception` throw, or a case that runs past `--timeout-ms` (30 s). No image code runs (it never calls -`initialise()`), and nothing is read from the game. - -CTest runs the first 120 cases of the fixed seed. Case `N` of a seed is the same everywhere, so a failure reproduces -with `--case N` and shrinks with `--minimize N`, which retries in child processes with each mutation left out and -prints the ones the failure needs. `--dump N DIR` writes the case's images for a closer look. A process memory limit -(`--mem-mb`, 1024 by default) turns a mutated size of several gigabytes into a failed allocation. On a machine -with many threads, most of each case is the loader's snapshot of every thread in the system for a TLS module -(`install_on_existing_threads`); expect a few cases per second. - -```powershell -pe_loader_fuzz --iters 20000 # or --seconds 3600; LEONIDA_LOADER_FUZZ_ITERS/_SECONDS/_SEED -pe_loader_fuzz --seed 0x4C454F4E49444131 --case 1234 --verbose -pe_loader_fuzz --minimize 1234 -pe_loader_fuzz --start 10000000 --seconds 3600 # a second process on another range of cases -``` - -For AddressSanitizer, configure a separate build with `-DLEONIDA_LOADER_FUZZ_ASAN=ON` and `RelWithDebInfo` -(`/fsanitize=address` does not combine with Debug's `/RTC1`). That instruments the fuzzer and the loader sources -compiled into it, and copies `clang_rt.asan_dynamic-x86_64.dll` beside the test. MSVC needs the Visual Studio -component "C++ AddressSanitizer". clang-cl from an official LLVM release works with the MSVC headers and libraries -(LLVM 23.1.5 with MSVC 14.44 was tested). Run it from an x64 Developer prompt: - -```powershell -cmake -S runtime -B build-asan -G Ninja -DCMAKE_BUILD_TYPE=RelWithDebInfo -DLEONIDA_LOADER_FUZZ_ASAN=ON ` - -DCMAKE_C_COMPILER=/bin/clang-cl.exe -DCMAKE_CXX_COMPILER=/bin/clang-cl.exe ` - -DCMAKE_LINKER=/bin/lld-link.exe -DCMAKE_AR=/bin/llvm-lib.exe -DCMAKE_RC_COMPILER=/bin/llvm-rc.exe ` - -DCMAKE_MT=/bin/llvm-mt.exe -cmake --build build-asan --target pe_loader_fuzz -build-asan/pe_loader_fuzz --seconds 3600 -``` - -With clang-cl the target is built with `-fsanitize-address-use-after-return=never`: clang-cl 23's -stack-use-after-return frames make MSVC C++ exception dispatch fault in `_C_specific_handler_noexcept` at `/O2`, and -every rejected image is a thrown exception. STL container annotations are off (`_DISABLE_STRING_ANNOTATION`, -`_DISABLE_VECTOR_ANNOTATION`), because they need the component's `stl_asan.lib` and the libraries linked in are -built without ASan. - -The PE-loader and Bink-decode tests that need the retail package are optional: when -`LEONIDA_GAME_DIR` (and, for Bink, `LEONIDA_MOVIE`) is unset they print `SKIP` and exit 0. They read -the files in place and never copy or commit game data. - -`shader_library_corpus_test` runs the D3D12 layer's shader lookup (`src/shader_library.h`) over a work folder -that `make_game.py --stages shaders` built from your copy. With `LEONIDA_SHADERS=/shaders/spirv` it takes -every container in `/shaders/dxbc` (or `LEONIDA_SHADER_DXBC`), inflates its FSSM program and looks it up -under the stage its DXIL program header names. Each container has to find its own `index.json` entry and a -readable `.spv`, every entry has to be reached, and in containers with more than one 0x0D payload no earlier -payload may be the indexed program. Without `LEONIDA_SHADERS` it prints `SKIP` (CTest reports it as skipped). -It prints counts only; on the 1.0.2.1 corpus all 26,503 containers resolve. - -## Current limits - -`gta6rt --run [-- args]` runs an executable's entry point inside the runtime (`shims/process.cpp` gives it its -own command line and turns its `exit` into the end of the run); CTest's `run_tiny_game` does that with a stand-in game. -The game's `atexit` handlers and static destructors go to a table of the run's own (the CRT's process-wide one is -shared with gta6rt): `exit` and a return from `main` run them newest first before the run ends, `_cexit` runs them and -returns, and `_exit`, `quick_exit`, `ExitProcess` and `abort` skip them, as natively. `run_tiny_atexit` runs a stand-in -program natively and through `--run` for each of those paths (and for `_exit` from a second thread during `exit`) and -holds both to the Windows sequence (under Wine, whose CRT differs, a native difference is only reported). Not covered -yet: `at_quick_exit` handlers (`quick_exit` runs none) and the thread-local destructor callback -(`_register_thread_local_exe_atexit_callback`); both still reach the host CRT. -`run_tiny_frame` does it with a stand-in that imports `d3d12_xs.dll!D3D12XboxCreateDevice` and, with -`LEONIDA_D3D12=vulkan`, clears a render target and reads it back on the Vulkan device: the loader, the game thread, -the Xbox-ABI proxies and the device in one process (`test/fixtures/tiny_frame.cpp`; `test/check_tiny_frame.py` checks -the verdict, the `shim` binding and the call order in the `--trace-d3d12` output, and skips without a Vulkan GPU). -The game does not boot yet. The missing executable blocks the import-driven work: the real device -entry point, command-list/queue/fence extensions, `PresentX`, and most of the `xgameruntime` surface (an offline -shim covers `XGameRuntimeInitialize`, device/console queries, `XTaskQueue` and `XAsync`; see `xgameruntime_test`). The -D3D12-to-Vulkan design and the measured console ABI are in -The game does not boot yet, and none of this has been measured against the real executable. The missing executable -blocks the import-driven work: - -- The device entry point: `D3D12XboxCreateDevice` exists and wraps the PC or the Vulkan-backed device in the - measured-slot proxy, but its parameter and flag layout is unmeasured, and the Xbox device vtable is only partly - measured: the FSR DLL's calls confirm device slots 14, 15, 16, 18, 19, 27, 38, 62 and 76, slot 67 is a - console-only pipeline call, and the rest is open (`docs/d3d12_vulkan.md`, question 2). -- The command-queue and fence extensions: the proxies forward the public slots, and the console's own methods past - them (`PresentX`, `SuspendX`, `ResumeX`) have unknown slots, so they are refused with a log. - `PresentX` and the frame events themselves are implemented (`shims/xbox_present.*`, `xbox_present_test`), and the - proxies have a place to hang them: a frame-event sink on device slots 78/79/80 and a present sink on the queue - (`shims/d3d12_xs_device.h`). `gta6rt` sets neither sink yet, so the frame calls still get the proxy's own answers - and a `PresentX` is still refused. The `PresentX` slot is not measured for this title (public code gives 30 for - an older runtime layout and 32 for a newer one), so no slot is taken for it by default: - `LEONIDA_XS_PRESENT_X_SLOT` (`d3d12.present_x_slot` in `leonida.toml`) names it, a queue slot from 19 to 127. A - value outside that range is logged once and ignored. The setting is read once per run. -- Most of the `xgameruntime` surface: an offline shim covers `XGameRuntimeInitialize`, device/console queries, - `XTaskQueue` and `XAsync`, and `QueryApiImpl` serves `XThreadingImpl`, `XErrorImpl`, `XNetworkingImpl`, - `XPersistentLocalStorageImpl` and `XSystemImpl` (see `xgameruntime_test`); any other class is refused with a log. - -The D3D12-to-Vulkan design and the measured console ABI are in -[docs/d3d12_vulkan.md](../docs/d3d12_vulkan.md); the shader translator and its GPU checks are described -in [docs/design.md](../docs/design.md), and the differential-validation design is in the shader-validation -work. - -No game data, keys, or extracted assets belong in this directory or in the repository. - -### First-boot D3D12 trace - -On a Vulkan-enabled build, select the Vulkan backend to trace device, command-list and queue calls handled -by Leonida. Put `--trace-d3d12` before the separator for game arguments. - -```powershell -$env:LEONIDA_D3D12 = 'vulkan' -.\runtime\build\gta6rt.exe --run $gameExe --trace-d3d12 2>&1 | - Select-String '^\[d3d12-trace\]' -``` - -Each trace line contains a sequence number, a fixed API name and an outcome. `called` marks a void API call -whose validation may be deferred. `ok`, `failed` and `unsupported` report known results. `ignored` marks a no-op. -Share only the lines prefixed with `[d3d12-trace]`. Other runtime diagnostics are separate. - -### Startup trace: `--trace FILE` - -`--trace FILE` (with `--dry-run`, `--init` or `--run`, before the `--` separator) writes one JSON object per line -to FILE, flushed per event so the file survives a crash ([shims/startup_trace.h](shims/startup_trace.h)). FILE must -not exist yet: the trace is created before the loader reads anything, so gta6rt refuses an existing path (exit code 2) -rather than risk truncating an input such as the image. The file is UTF-8; `OutputDebugStringA` text is converted -from the ANSI code page. - -| `kind` | When | Fields | -|---|---|---| -| `trace_open` | first line | `pid` | -| `map` | a module is mapped, bound and protected | `module`, `base`, `size`, `relocated` | -| `tls_callback` | before each TLS callback the Loader runs (process attach and detach; thread events run under the Windows loader lock and are not traced) | `module`, `at` (module+RVA), `reason` | -| `dllmain` | after `DllMain(DLL_PROCESS_ATTACH)` returns | `module`, `result` | -| `unimplemented_call` | first call of each unimplemented import | `import` (`dll!name`), `caller` (module+RVA) | -| `xmem_attributes` | the first `XMemAlloc`, `XMemFree`, `XMemAllocDefault`, `XMemFreeDefault` and `XMemVirtualAlloc` for each distinct raw attribute word (not every allocation) | `api`, `attributes`, `size` (not for the frees), `caller` (module+RVA) | -| `xmem_physical_pages` | the first `XMemAllocatePhysicalPages` for each distinct attribute word | `api`, `attributes`, `pages`, `caller` | -| `file_open_failed` | a guest `CreateFileW`/`CreateFile2` that fails (at most 256 events) | `api`, `path` (as the title passed it), `error` (Win32), `caller` (module+RVA) | -| `int3_skipped` | with `LEONIDA_SKIP_INT3` set: first int3 at each address, which is then stepped over | `at` (module+RVA) | -| `debug_string` | `OutputDebugStringA/W` with no debugger attached | `text` | -| `exception` | any exception, before handlers run | `code`, `at`, `access`/`address` for access violations, `cpp` for C++ throws, `stack` (up to 16 frames) | -| `exit` / `error` | `--run` returns, or the loader throws | `code` / `what` | - -Every line also has `seq` and `t` (seconds since the trace opened). Addresses are `module+0xRVA` for mapped images, -`host:name.dll+0xRVA` for host modules. The exception handler only records: it returns `EXCEPTION_CONTINUE_SEARCH`, -so the process behaves the same with or without the trace (except under the diagnostic `LEONIDA_SKIP_INT3`, which -steps over int3). It works with any `LEONIDA_UNIMPLEMENTED` policy. - -The file can quote what the game prints, so it stays on your machine. In issues and pull requests, share counts or -lines from synthetic fixtures only. - -```powershell -.\runtime\build\gta6rt.exe --run $gameExe --trace startup.jsonl -Get-Content startup.jsonl | ConvertFrom-Json | Group-Object kind | Select-Object Count, Name -``` - -[tools/boot_trace.py](../tools/boot_trace.py) prints the first-boot summary of this file and of the -`--trace-d3d12` log (modules, unimplemented calls with their callers, DllMain/TLS results, exceptions with their -stack, the exit, and the D3D12 calls by outcome and first call per method): - -```powershell -python -I tools\boot_trace.py startup.jsonl --d3d12 d3d12.log -``` - -[docs/boot.md](../docs/boot.md) is the runbook around it: the commands, the triage order and the open questions' -trace signals. - -### Typed clear regression - -`clear_color_test` checks numeric UINT conversion and unchanged float clears without a GPU. -`d3d12_clear_test` compares full/rectangle readbacks with Windows WARP across UNORM, SNORM, FLOAT, UINT and SINT -render-target formats, plus depth and stencil clears. Fixtures are synthetic; no shaders or game data are needed. -The GPU test runs explicitly, while the CPU test is registered in CTest. - -```powershell -ctest --test-dir runtime/build -C RelWithDebInfo -R '^clear_color$' --output-on-failure -$env:LEONIDA_VK_VALIDATION = '1' -$env:VK_VALIDATION_VALIDATE_SYNC = '1' -.\runtime\build\RelWithDebInfo\d3d12_clear_test.exe -``` - -### RGBA8 typeless RTV clear regression (phase 1) - -`typeless_rtv_test` checks typed-view recording and replay without a GPU. It is registered in CTest. -`d3d12_typeless_rtv_test` compares synthetic full and rectangular clears with Windows WARP through explicit -UNORM/SRGB/UINT RTVs on 2D RGBA8 typeless resources, including mip slices, array-layer ranges and 4x MSAA. -SINT/SNORM clears are compared where both Vulkan and WARP report render-target support. It checks descriptor -snapshots, alternating view formats, SRGB with UAV resource usage, and invalid view rejection. - -```powershell -ctest --test-dir runtime/build -C RelWithDebInfo -R '^typeless_rtv$' --output-on-failure -$env:LEONIDA_VK_VALIDATION = '1' -$env:VK_VALIDATION_VALIDATE_SYNC = '1' -.\runtime\build\RelWithDebInfo\d3d12_typeless_rtv_test.exe -``` - -### 96-bit R32G32B32 textures (D3D-62) - -`d3d12_rgb96_test` compares footprints, uploads, readbacks, boxes, texture-to-texture copies and CPU copies of -`R32G32B32_FLOAT/UINT/SINT/TYPELESS` textures (2D arrays with mips, and volumes) with Windows WARP, bit for bit, -checks that WARP and the hardware adapter report no resource tiling for all four formats, and prints how long an -upload and a readback take. `d3d12_descriptor_test` samples them (alpha reads as one). It -is registered in CTest (`d3d12_rgb96`). - -```powershell -$env:LEONIDA_VK_VALIDATION = '1' -$env:VK_VALIDATION_VALIDATE_SYNC = '1' -.\runtime\build\RelWithDebInfo\d3d12_rgb96_test.exe -``` - -RGBA8 typeless RTV clears support explicit UNORM/SRGB/UINT/SINT/SNORM views of 2D mip slices and contiguous -array-layer ranges, and MSAA. Other typeless color families also accept same-family typed RTVs, subject to Vulkan -color-attachment support. Typed-resource RTV casts are limited to R8G8B8A8_UNORM resources whose castable-format -list allows the view. A 1D texture cannot be created as a render target or depth buffer (`CreateCommittedResource` -refuses `ALLOW_RENDER_TARGET`/`ALLOW_DEPTH_STENCIL` on it), and 3D typeless view reinterpretation remains refused. - -### Resource descriptions - -`d3d12_resource_desc_test` creates the same committed and reserved resources on the Vulkan-backed device and on -Windows D3D12 (the default adapter and WARP, whichever exist) and compares every field of `ID3D12Resource::GetDesc`: -the `Alignment` and `MipLevels` a description left at 0 must read back as the host fills them in. A description the -host refuses is skipped, and one only the layer refuses is listed and not compared. It needs a -Vulkan GPU and runs explicitly. - -```powershell -$env:LEONIDA_VK_VALIDATION = '1' -.\runtime\build\RelWithDebInfo\d3d12_resource_desc_test.exe -``` - -`d3d12_placed_dimensions_test` places 1D and 3D textures (arrays, mips, BC1, UAV and render targets, plus a 2D -control) in heaps big enough for both sides' `GetResourceAllocationInfo`, at offset 0 and at 64 KiB, on the -Vulkan-backed device and on Windows D3D12 (the default adapter and WARP), and compares the answers and `GetDesc`. A -dimension outside the enum must be refused alike. It also copies a pattern through a buffer into every subresource of a placed -3D texture and a placed 1D array and back, and checks the bytes. It needs a Vulkan GPU. - -```powershell -$env:LEONIDA_VK_VALIDATION = '1' -.\runtime\build\RelWithDebInfo\d3d12_placed_dimensions_test.exe -``` - -### 1D render targets and depth buffers - -`d3d12_texture1d_target_test` creates `TEXTURE1D` textures with `ALLOW_RENDER_TARGET` (10 color formats) or -`ALLOW_DEPTH_STENCIL` (4 depth formats), one texture and a 6-layer array each, on the Vulkan-backed device, the -hardware adapter and WARP. Where every reference creates one and the Vulkan device can make that 1D attachment image, -the layer must create it and `GetResourceAllocationInfo` must answer a size. It then clears through `TEXTURE1D` and -`TEXTURE1DARRAY` RTVs and DSVs (whole and with rectangles, on mips and slice ranges) and through a 1D UAV with a -rectangle, and compares every subresource's bytes with WARP. It is registered in CTest (`d3d12_texture1d_target`). - -```powershell -$env:LEONIDA_VK_VALIDATION = '1' -.\runtime\build\RelWithDebInfo\d3d12_texture1d_target_test.exe -``` - -### Depth and stencil resolves - -`d3d12_depth_resolve_test` resolves one plane of a 4x D32 or D24S8 target into a 1x one with -`ResolveSubresourceRegion` (MIN and MAX of depth or stencil, AVERAGE of depth by its own format; whole and by -rectangle) on the Vulkan-backed device and on Windows D3D12 (the default adapter and WARP), and compares the -destinations read back. Calls the layer refuses must fail `Close` and leave the destination as cleared. Clears give -every sample of a pixel one value, so the modes over differing samples are not checked. It needs a Vulkan GPU. - -```powershell -$env:LEONIDA_VK_VALIDATION = '1' -.\runtime\build\RelWithDebInfo\d3d12_depth_resolve_test.exe -``` - -### Predicate capture lifetime - -`vk_predicate_capture_test` checks full-width predicate snapshots, offset rebinding and reset with 32 gated submissions, then reuses completed command-buffer slots. Run explicitly on a Vulkan GPU with conditional rendering; it uses only synthetic data. - -### A synthetic guest draws its first offscreen frame - -On a Windows Vulkan build, configure CMake with `-DLEONIDA_TEST_GUEST_DRAW=ON` and build the -`tiny_guest_draw` and `gta6rt` targets. With llvm-mc, spirv-as and spirv-val available at configure -time, run `ctest --test-dir runtime/build -C Release -R "^d3d12_translated_draw_guest$" -V`. -The loader maps the test executable. It imports the Xbox device factory, submits three draws using two -handwritten shaders, reads back a 64×64 offscreen texture and checks every pixel. - -The guest also builds independently of the shader tools. To produce the same synthetic fixture on -another machine, run `python -I runtime/test/shaders/build.py m15_shaders vs_m15 ps_m15` from the -checkout with llvm-mc, spirv-as and spirv-val available. Copy the whole resulting folder to the test -machine. For Wine, make the runtime executable, its runtime DLLs, the guest executable and the fixture -accessible in the same Wine prefix. For example, from their containing directory with the guest and -fixture beside the loader: - -```sh -fixture=$(winepath -w "$PWD/m15_shaders") -shaders=$(winepath -w "$PWD/m15_shaders/spirv") -guest=$(winepath -w "$PWD/tiny_guest_draw.exe") -LEONIDA_D3D12=vulkan LEONIDA_SHADERS="$shaders" wine ./gta6rt.exe --run "$guest" -- "$fixture" -``` - -A passing run exits zero and prints `M1.5 guest: PASS, 4064 of 4096 pixels exact, 32 edge pixels the clear colour`. -The 32 diagonal pixels must all match the clear colour exactly. The fixture does not create a window. - -### A 600-frame headless guest scene - -Configure a Windows Vulkan build with `-DLEONIDA_GUEST_SCENE=ON` and static SDL3 -(`SDL3_DIR` or `-DLEONIDA_SDL3_FETCH=ON`). Build `gta6rt` and `tiny_guest_draw`. -With the shader tools and Python available at configure time, CTest runs the existing -one-frame test and the scene with `ctest -R "^(d3d12_translated_draw_guest|d3d12_guest_scene)$" -V`. -For an externally generated M1.5 shader fixture, use the runner directly: - -```sh -python -I scripts/run_guest_scene.py --loader path/to/gta6rt.exe --guest path/to/tiny_guest_draw.exe \ - --shaders path/to/m15_shaders --out new-scene-run --negative-controls -``` - -For Wine, add `--wine path/to/wine`. With a Linux cross-build, CTest also registers -`d3d12_guest_scene` when CMake finds the shader tools and has a Wine command in -`CMAKE_CROSSCOMPILING_EMULATOR`. Build the `tiny_guest_draw` target, then run -`ctest --test-dir -R '^d3d12_guest_scene$' --output-on-failure`. -On a headless host, prefix that CTest command with `xvfb-run -a` so the scene runner -keeps guest stdout and stderr separate while checking the frame-count marker. -The runner launches the mapped guest for an -uninterrupted 600-frame run, a 300-frame save, and a fresh process that restores the -checkpoint. This opt-in build links a fixture input source into the loader. Scripted keyboard changes feed the SDL virtual pad. GameInput readings -drive the position of one quad. The guest streams ten 16-byte synthetic palette pages from -`GAME:\scene.bin` and changes its shader constants. A software reference independently -predicts the GPU pixel digest for each frame and checks six captured images. - -Each run writes frame records, a state file, selected PPM readbacks, and a checkpoint -where applicable. At the first A-button edge the guest generates a quarter-second PCM -WAV. Playback is off by default. `--play-audio` requests playback through host WinMM -and records its result. The runner uses a fresh output directory, or a temporary one -when `--out` is omitted. The negative controls independently corrupt a scene byte and -a saved-state byte and require the expected guest errors. This fixture renders offscreen. diff --git a/runtime/cmake/clang-cl-xwin.cmake b/runtime/cmake/clang-cl-xwin.cmake deleted file mode 100644 index 2848e5dca..000000000 --- a/runtime/cmake/clang-cl-xwin.cmake +++ /dev/null @@ -1,117 +0,0 @@ -# Cross-compile the Windows runtime from Linux with clang-cl and lld-link against an MSVC CRT and Windows SDK laid -# out by xwin (https://github.com/Jake-Shadle/xwin) in the /winsysroot style: -# -# xwin --accept-license --sdk-version 10.0.26100 splat --use-winsysroot-style --preserve-ms-arch-notation \ -# --output ~/.local/share/xwin-sdk -# cmake -S runtime -B runtime/build/windows --toolchain "$PWD/runtime/cmake/clang-cl-xwin.cmake" \ -# -DXWIN_DIR="$HOME/.local/share/xwin-sdk" -# cmake --build runtime/build/windows --parallel -# ctest --test-dir runtime/build/windows # through Wine; see docs/testing.md for Proton -# -# The result is the same set of PE files the Windows build makes. A relative --toolchain path is resolved against -# the build folder, hence $PWD. -DCMAKE_CXX_FLAGS=... replaces the flags set here (--target, /winsysroot), so add -# flags with CMAKE_CXX_FLAGS_RELWITHDEBINFO or target options instead. -set(CMAKE_SYSTEM_NAME Windows) -set(CMAKE_SYSTEM_PROCESSOR AMD64) - -if(NOT XWIN_DIR) - set(XWIN_DIR "$ENV{XWIN_DIR}") - if(XWIN_DIR AND NOT IS_ABSOLUTE "${XWIN_DIR}") - # Match a relative -DXWIN_DIR= path by resolving it from CMake's working directory. - execute_process(COMMAND pwd -P OUTPUT_VARIABLE _xwin_cwd COMMAND_ERROR_IS_FATAL ANY) - string(REGEX REPLACE "\n$" "" _xwin_cwd "${_xwin_cwd}") - cmake_path(ABSOLUTE_PATH XWIN_DIR BASE_DIRECTORY "${_xwin_cwd}") - endif() -endif() -if(NOT XWIN_DIR OR NOT EXISTS "${XWIN_DIR}/VC/Tools/MSVC") - message(FATAL_ERROR "Set XWIN_DIR (or -DXWIN_DIR=) to an xwin splat made with --use-winsysroot-style") -endif() -set(XWIN_DIR "${XWIN_DIR}" CACHE PATH "xwin /winsysroot directory (VC/ and Windows Kits/)") -list(APPEND CMAKE_TRY_COMPILE_PLATFORM_VARIABLES XWIN_DIR) - -# The LLVM tools, by their unversioned names unless given (-DCMAKE_CXX_COMPILER=clang-cl-19 -DCMAKE_LINKER=lld-link-19 -# ...). The MSVC STL that xwin lays out needs Clang 19 or newer. -foreach(_tool C_COMPILER:clang-cl CXX_COMPILER:clang-cl LINKER:lld-link AR:llvm-lib RC_COMPILER:llvm-rc MT:llvm-mt) - string(REPLACE ":" ";" _tool "${_tool}") - list(GET _tool 0 _var) - list(GET _tool 1 _name) - if(NOT CMAKE_${_var}) - set(CMAKE_${_var} ${_name}) - endif() -endforeach() - -set(_xwin_compile "--target=x86_64-pc-windows-msvc /winsysroot \"${XWIN_DIR}\"") -set(CMAKE_C_FLAGS_INIT "${_xwin_compile}") -set(CMAKE_CXX_FLAGS_INIT "${_xwin_compile}") -foreach(_kind EXE SHARED MODULE) - set(CMAKE_${_kind}_LINKER_FLAGS_INIT "/winsysroot:\"${XWIN_DIR}\"") -endforeach() - -# xwin leaves out the debug CRT (msvcrtd, ucrtd: not redistributable), so only Release and RelWithDebInfo link. CMake's -# MSVC platform file defaults the build type to Debug, so default it here, and CMake's own checks build in Release. -if(NOT DEFINED CACHE{CMAKE_BUILD_TYPE}) - set(CMAKE_BUILD_TYPE RelWithDebInfo CACHE STRING "Release or RelWithDebInfo (xwin has no debug CRT)") -endif() -file(GLOB _xwin_debug_crt "${XWIN_DIR}/VC/Tools/MSVC/*/lib/x64/msvcrtd.lib") -if(CMAKE_BUILD_TYPE STREQUAL "Debug" AND NOT _xwin_debug_crt) - message(FATAL_ERROR "CMAKE_BUILD_TYPE=Debug needs the debug CRT: splat again with xwin's --include-debug-libs, " - "or use RelWithDebInfo") -endif() -set(CMAKE_TRY_COMPILE_CONFIGURATION Release) - -# The Vulkan headers are the same on every platform, but /usr/include also holds glibc's, which must not shadow the -# MSVC CRT. Point Vulkan_INCLUDE_DIR at a folder that holds only vulkan/ and vk_video/ (links to the host copies), -# unless another folder was given (-DVulkan_INCLUDE_DIR=/include). The links are (re)made on every -# configure, so deleting the folder doesn't silently drop the Vulkan targets. -if(CMAKE_BINARY_DIR) - set(_xwin_vulkan "${CMAKE_BINARY_DIR}/xwin-vulkan-include") - if(NOT Vulkan_INCLUDE_DIR OR Vulkan_INCLUDE_DIR STREQUAL _xwin_vulkan) - foreach(_host_include /usr/include /usr/local/include) - if(EXISTS "${_host_include}/vulkan/vulkan.h") - file(MAKE_DIRECTORY "${_xwin_vulkan}") - foreach(_sub vulkan vk_video) - if(EXISTS "${_host_include}/${_sub}" AND NOT EXISTS "${_xwin_vulkan}/${_sub}") - file(CREATE_LINK "${_host_include}/${_sub}" "${_xwin_vulkan}/${_sub}" SYMBOLIC) - endif() - endforeach() - set(Vulkan_INCLUDE_DIR "${_xwin_vulkan}" CACHE PATH "Vulkan headers without the host's libc headers") - break() - endif() - endforeach() - endif() -endif() - -# find_library and find_path look in the newest SDK's um folders: d3d12.lib and dxgi.lib for the host-comparison -# tests, d3d12.h for tools/gen_d3d12_stubs.py. -file(GLOB _xwin_um_libs LIST_DIRECTORIES true "${XWIN_DIR}/Windows Kits/10/Lib/*/um/x64") -if(NOT _xwin_um_libs) - message(FATAL_ERROR "No \"Windows Kits/10/Lib//um/x64\" under ${XWIN_DIR}: make the splat with " - "--use-winsysroot-style --preserve-ms-arch-notation and an SDK (--sdk-version 10.0.26100)") -endif() -list(SORT _xwin_um_libs COMPARE NATURAL ORDER DESCENDING) -list(GET _xwin_um_libs 0 _xwin_um_lib) -list(APPEND CMAKE_LIBRARY_PATH "${_xwin_um_lib}") -get_filename_component(_xwin_sdk_version "${_xwin_um_lib}/../.." ABSOLUTE) -get_filename_component(_xwin_sdk_version "${_xwin_sdk_version}" NAME) -list(APPEND CMAKE_INCLUDE_PATH "${XWIN_DIR}/Windows Kits/10/Include/${_xwin_sdk_version}/um") -# Programs (Python, glslangValidator, Wine) come from the host; libraries and headers from the SDK or the paths above; -# CMake packages only from the SDK root, so a host package (an ELF SDL3, say) never ends up in a Windows link. -set(CMAKE_FIND_ROOT_PATH "${XWIN_DIR}") -set(CMAKE_FIND_ROOT_PATH_MODE_PROGRAM NEVER) -set(CMAKE_FIND_ROOT_PATH_MODE_LIBRARY BOTH) -set(CMAKE_FIND_ROOT_PATH_MODE_INCLUDE BOTH) -set(CMAKE_FIND_ROOT_PATH_MODE_PACKAGE ONLY) - -# LLVM's MASM stands in for ml64, so unimplemented_policy_test keeps its register-preservation check (abi_probe.asm). -# runtime/cmake/runtime_tests.cmake keeps a LEONIDA_ML64 that is already set. -find_program(LEONIDA_ML64 NAMES ml64 llvm-ml64) - -# ctest runs the PE tests through Wine, or Proton's wine (-DCMAKE_CROSSCOMPILING_EMULATOR=/files/bin/wine). -if(NOT CMAKE_CROSSCOMPILING_EMULATOR) - find_program(XWIN_WINE NAMES wine wine64) - if(XWIN_WINE) - set(CMAKE_CROSSCOMPILING_EMULATOR "${XWIN_WINE}") - elseif(CMAKE_BINARY_DIR) - message(STATUS "Wine not found: ctest can't run the Windows tests (set CMAKE_CROSSCOMPILING_EMULATOR)") - endif() -endif() diff --git a/runtime/cmake/d3d12_vulkan.cmake b/runtime/cmake/d3d12_vulkan.cmake deleted file mode 100644 index a0f0219ae..000000000 --- a/runtime/cmake/d3d12_vulkan.cmake +++ /dev/null @@ -1,1538 +0,0 @@ -# The D3D12 COM objects over the Vulkan backend (gta6rt_d3d12_com), their generated method stubs and their tests. -# Included by runtime/CMakeLists.txt inside if(TARGET Vulkan::Headers). - -# D3D12 COM objects over the Vulkan backend. Their method stubs are generated from the SDK's d3d12.h at build -# time (tools/gen_d3d12_stubs.py), so nothing derived from the SDK header is checked in. -find_package(Python3 COMPONENTS Interpreter QUIET) -# The generator finds d3d12.h through INCLUDE, which a Developer Prompt sets. A cross build (for example -# runtime/cmake/clang-cl-xwin.cmake) has no such prompt, so it is handed the header CMake finds. -set(_stubs_header) -set(_stubs_header_ok TRUE) -if(TARGET gta6rt AND CMAKE_CROSSCOMPILING) - find_file(LEONIDA_D3D12_HEADER d3d12.h) - if(LEONIDA_D3D12_HEADER) - set(_stubs_header --header "${LEONIDA_D3D12_HEADER}") - else() - set(_stubs_header_ok FALSE) - message(STATUS "d3d12.h not found (set CMAKE_INCLUDE_PATH): the D3D12 COM objects are not built") - endif() -endif() -if(TARGET gta6rt AND Python3_FOUND AND _stubs_header_ok) - set(LEONIDA_STUBS ${CMAKE_CURRENT_BINARY_DIR}/generated/d3d12_stubs.h) - add_custom_command( - OUTPUT ${LEONIDA_STUBS} - COMMAND "${Python3_EXECUTABLE}" -I ${CMAKE_CURRENT_SOURCE_DIR}/../tools/gen_d3d12_stubs.py --out ${LEONIDA_STUBS} - ${_stubs_header} - ID3D12GraphicsCommandList8 ID3D12CommandQueue ID3D12CommandAllocator ID3D12Fence1 - ID3D12Device11 ID3D12DescriptorHeap ID3D12Heap ID3D12Resource ID3D12QueryHeap ID3D12RootSignature - ID3D12PipelineState ID3D12CommandSignature ID3D12PipelineLibrary1 ID3D12ShaderCacheSession - DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/../tools/gen_d3d12_stubs.py ${LEONIDA_D3D12_HEADER} - COMMENT "Generating D3D12 COM stubs" - VERBATIM) - add_library(gta6rt_d3d12_com STATIC shims/d3d12_com.cpp shims/d3d12_vulkan_device.cpp shims/d3d12_xs_device.cpp shims/xbox_present.cpp - shims/dxgi_com.cpp ${LEONIDA_STUBS}) # d3d12_vulkan_device.cpp reads the PC device behind the proxy (#224) - target_include_directories(gta6rt_d3d12_com PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/generated) - target_link_libraries(gta6rt_d3d12_com PUBLIC Vulkan::Headers gta6rt_root_signature) - target_compile_definitions(gta6rt_d3d12_com PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) - # /bigobj: a Debug build of d3d12_vulkan_device.cpp has more sections than a COFF object holds by default - # (fatal error C1128), because without optimisation every inline function keeps its own COMDAT. - target_compile_options(gta6rt_d3d12_com PRIVATE /W4 /permissive- /utf-8 /bigobj) - - add_executable(d3d12_com_test test/d3d12_com_test.cpp) - target_link_libraries(d3d12_com_test PRIVATE gta6rt_d3d12_com) - target_compile_definitions(d3d12_com_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) - target_compile_options(d3d12_com_test PRIVATE /W4 /permissive- /utf-8) - add_test(NAME d3d12_com COMMAND d3d12_com_test) - set_tests_properties(d3d12_com PROPERTIES SKIP_RETURN_CODE 77) - - # Where the device finds its translated shaders (shader_path.txt, a path that is not UTF-8). No GPU. - add_executable(d3d12_shader_path_test test/d3d12_shader_path_test.cpp) - target_link_libraries(d3d12_shader_path_test PRIVATE gta6rt_d3d12_com) - target_compile_definitions(d3d12_shader_path_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) - target_compile_options(d3d12_shader_path_test PRIVATE /W4 /permissive- /utf-8) - add_test(NAME d3d12_shader_path COMMAND d3d12_shader_path_test) - - # Multi-threaded concurrent submissions across two D3D12 queues + resource creation/destruction churn. - add_executable(d3d12_multithread_test test/d3d12_multithread_test.cpp) - target_link_libraries(d3d12_multithread_test PRIVATE gta6rt_d3d12_com) - target_compile_definitions(d3d12_multithread_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) - target_compile_options(d3d12_multithread_test PRIVATE /W4 /permissive- /utf-8) - add_test(NAME d3d12_multithread COMMAND d3d12_multithread_test) - # 300 s, not 120: the test's 60 s fence waits need headroom when other GPU tests share the device - # (two concurrent `ctest -j 6` suites pushed it to 91-120 s; TEST-514 follow-up). - set_tests_properties(d3d12_multithread PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 300) - # Several threads make the first CheckFeatureSupport(D3D12_OPTIONS1) call of a new device at the same time. - add_executable(d3d12_options1_first_use_test test/d3d12_options1_first_use_test.cpp) - target_link_libraries(d3d12_options1_first_use_test PRIVATE gta6rt_d3d12_com) - target_compile_definitions(d3d12_options1_first_use_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) - target_compile_options(d3d12_options1_first_use_test PRIVATE /W4 /permissive- /utf-8) - add_test(NAME d3d12_options1_first_use COMMAND d3d12_options1_first_use_test) - set_tests_properties(d3d12_options1_first_use PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 120) - # A queued Wait must not block a Signal submitted by another D3D12 queue. - add_executable(d3d12_queue_wait_test test/d3d12_queue_wait_test.cpp) - target_link_libraries(d3d12_queue_wait_test PRIVATE gta6rt_d3d12_com) - target_compile_definitions(d3d12_queue_wait_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) - target_compile_options(d3d12_queue_wait_test PRIVATE /W4 /permissive- /utf-8) - add_test(NAME d3d12_queue_wait COMMAND d3d12_queue_wait_test) - add_executable(d3d12_noop_copy_test test/d3d12_noop_copy_test.cpp) - target_link_libraries(d3d12_noop_copy_test PRIVATE gta6rt_d3d12_com d3d12 dxgi) - target_compile_definitions(d3d12_noop_copy_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) - target_compile_options(d3d12_noop_copy_test PRIVATE /W4 /permissive- /utf-8) - add_test(NAME d3d12_noop_copy COMMAND d3d12_noop_copy_test) - set_tests_properties(d3d12_noop_copy PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 45) - set_tests_properties(d3d12_queue_wait PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 60) - add_test(NAME d3d12_queue_wait_timeout COMMAND d3d12_queue_wait_test --timeout-control) - # Under Ubuntu's Wine 9.0 this test runs into the 10 s without printing anything. With 60 s (9002b42) it no longer - # did, but the tests after it stayed slow and the wine (ubuntu) job was cancelled at 30 minutes (run 45428701383); - # with 10 s the same job passed in 694 s (run 45410688081). Why is not known yet, so the limit stays. - set_tests_properties(d3d12_queue_wait_timeout PROPERTIES SKIP_RETURN_CODE 77 WILL_FAIL TRUE TIMEOUT 10) - # ExecuteCommandLists refuses a list whose type isn't the queue's (debug-layer message 836). - add_executable(d3d12_queue_list_type_test test/d3d12_queue_list_type_test.cpp) - target_link_libraries(d3d12_queue_list_type_test PRIVATE gta6rt_d3d12_com) - target_compile_definitions(d3d12_queue_list_type_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) - target_compile_options(d3d12_queue_list_type_test PRIVATE /W4 /permissive- /utf-8) - add_test(NAME d3d12_queue_list_type COMMAND d3d12_queue_list_type_test) - set_tests_properties(d3d12_queue_list_type PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 30) - # Cross-device ownership validation: Signal, Wait, SetEventOnMultipleFenceCompletion, ExecuteCommandLists, ExecuteBundle. - add_executable(d3d12_cross_device_validation_test test/d3d12_cross_device_validation_test.cpp) - target_link_libraries(d3d12_cross_device_validation_test PRIVATE gta6rt_d3d12_com d3d12 dxgi) - target_compile_definitions(d3d12_cross_device_validation_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) - target_compile_options(d3d12_cross_device_validation_test PRIVATE /W4 /permissive- /utf-8) - add_test(NAME d3d12_cross_device_validation COMMAND d3d12_cross_device_validation_test) - set_tests_properties(d3d12_cross_device_validation PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 60 - FAIL_REGULAR_EXPRESSION "Validation Error;VUID-") - # Wait-before-Signal with a texture and a buffer handed over between the COPY, COMPUTE and DIRECT queues, in every - # submission order, on the layer and on the host runtime (docs/d3d12_vulkan.md section 4.4). - add_executable(d3d12_queue_handover_test test/d3d12_queue_handover_test.cpp) - target_link_libraries(d3d12_queue_handover_test PRIVATE gta6rt_d3d12_com d3d12 dxgi) - target_compile_definitions(d3d12_queue_handover_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) - target_compile_options(d3d12_queue_handover_test PRIVATE /W4 /permissive- /utf-8) - add_test(NAME d3d12_queue_handover COMMAND d3d12_queue_handover_test) - set_tests_properties(d3d12_queue_handover PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 400 - FAIL_REGULAR_EXPRESSION "Validation Error;VUID-") - # The same on a caller-owned device: two VkQueues handed to the layer (the D3D12 queues share them), and one - # (every D3D12 queue shares it, where a Wait ahead of its Signal would never progress on the GPU). - add_test(NAME d3d12_queue_handover_two_queues COMMAND d3d12_queue_handover_test --two-queues) - add_test(NAME d3d12_queue_handover_shared_queue COMMAND d3d12_queue_handover_test --shared-queue) - set_tests_properties(d3d12_queue_handover_two_queues d3d12_queue_handover_shared_queue PROPERTIES - SKIP_RETURN_CODE 77 TIMEOUT 400 FAIL_REGULAR_EXPRESSION "Validation Error;VUID-") - # More D3D12 queues than Vulkan queues: they share VkQueues, keeping fences and Wait-before-Signal (section 4.4). - # The _one_queue runs make every GPU look like the Intel UHD 770 (one family, one VkQueue): every queue shares it. - add_executable(d3d12_queue_share_test test/d3d12_queue_share_test.cpp) - target_link_libraries(d3d12_queue_share_test PRIVATE gta6rt_d3d12_com) - target_compile_definitions(d3d12_queue_share_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) - target_compile_options(d3d12_queue_share_test PRIVATE /W4 /permissive- /utf-8) - add_test(NAME d3d12_queue_share COMMAND d3d12_queue_share_test) - add_test(NAME d3d12_queue_share_one_queue COMMAND d3d12_queue_share_test) - set_tests_properties(d3d12_queue_share d3d12_queue_share_one_queue PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 300 - FAIL_REGULAR_EXPRESSION "Validation Error;VUID-") - add_test(NAME d3d12_queue_wait_one_queue COMMAND d3d12_queue_wait_test) - set_tests_properties(d3d12_queue_wait_one_queue PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 60) - set_tests_properties(d3d12_queue_share_one_queue d3d12_queue_wait_one_queue PROPERTIES - ENVIRONMENT "LEONIDA_VK_MAX_QUEUES_PER_FAMILY=1;LEONIDA_VK_GRAPHICS_FAMILY_ONLY=1") - # A misspelt case or count is refused with the usage line (exit code 2) before a device exists, instead of - # passing with nothing run. No GPU needed. - set(_share_bad_arguments "case_typo|--case|typo" "iterations_zero|--iterations|0" - "iterations_word|--iterations|banana" "iterations_too_many|--iterations|99999999999") - foreach(_bad IN LISTS _share_bad_arguments) - string(REPLACE "|" ";" _bad "${_bad}") - list(POP_FRONT _bad _bad_name) - add_test(NAME d3d12_queue_share_rejects_${_bad_name} COMMAND d3d12_queue_share_test ${_bad}) - set_tests_properties(d3d12_queue_share_rejects_${_bad_name} PROPERTIES TIMEOUT 60 - PASS_REGULAR_EXPRESSION "\nusage: d3d12_queue_share_test ") - endforeach() - - # XDXR acceleration structures through BuildRaytracingAccelerationStructure (docs/d3d12_vulkan.md 4.8): the - # device builds them, tools/xdxr_bvh.py checks them. - add_executable(d3d12_xdxr_rt_test test/d3d12_xdxr_rt_test.cpp) - target_link_libraries(d3d12_xdxr_rt_test PRIVATE gta6rt_d3d12_com) - target_compile_definitions(d3d12_xdxr_rt_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) - target_compile_options(d3d12_xdxr_rt_test PRIVATE /W4 /permissive- /utf-8) - set(LEONIDA_D3D12_XDXR_OUT "${CMAKE_CURRENT_BINARY_DIR}/d3d12_xdxr_cases") - file(MAKE_DIRECTORY "${LEONIDA_D3D12_XDXR_OUT}") - add_test(NAME d3d12_xdxr_rt COMMAND d3d12_xdxr_rt_test "${LEONIDA_D3D12_XDXR_OUT}") - set_tests_properties(d3d12_xdxr_rt PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 60 FIXTURES_SETUP d3d12_xdxr_cases) - find_package(Python3 COMPONENTS Interpreter QUIET) - if(Python3_FOUND) - add_test(NAME d3d12_xdxr_rt_check COMMAND "${Python3_EXECUTABLE}" -I - "${CMAKE_CURRENT_SOURCE_DIR}/../tools/xdxr_bvh.py" check-build "${LEONIDA_D3D12_XDXR_OUT}" --rays 1000) - set_tests_properties(d3d12_xdxr_rt_check PROPERTIES FIXTURES_REQUIRED d3d12_xdxr_cases SKIP_RETURN_CODE 77) - endif() - - # GCL8's QueryInterface and its one method need an allocator and a list, not a Vulkan device. - add_executable(d3d12_gcl8_test test/d3d12_gcl8_test.cpp) - target_link_libraries(d3d12_gcl8_test PRIVATE gta6rt_d3d12_com) - target_compile_definitions(d3d12_gcl8_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) - target_compile_options(d3d12_gcl8_test PRIVATE /W4 /permissive- /utf-8) - add_test(NAME d3d12_gcl8 COMMAND d3d12_gcl8_test) - # Python runs on the host; a cross-compiled fixture runs through the emulator (Wine), which the script prepends. - # The interpreter is named by path, because ctest would put the emulator in front of an executable target. - set(_trace_runner) - foreach(_part IN LISTS CMAKE_CROSSCOMPILING_EMULATOR) - list(APPEND _trace_runner "--runner=${_part}") # one word each, even one that starts with "-" (xvfb-run -a) - endforeach() - add_test(NAME d3d12_trace COMMAND "${Python3_EXECUTABLE}" -I - "${CMAKE_CURRENT_SOURCE_DIR}/test/check_d3d12_trace.py" "$" ${_trace_runner}) - - # The Vulkan device behind the Xbox-ABI proxy, end to end. - add_executable(d3d12_vulkan_device_test test/d3d12_vulkan_device_test.cpp) - target_link_libraries(d3d12_vulkan_device_test PRIVATE gta6rt_d3d12_com dxguid) # IID_ID3D12MetaCommand (#1440) - target_compile_definitions(d3d12_vulkan_device_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) - target_compile_options(d3d12_vulkan_device_test PRIVATE /W4 /permissive- /utf-8) - add_test(NAME d3d12_vulkan_device COMMAND d3d12_vulkan_device_test) - - add_executable(d3d12_buffer_tiles_test test/d3d12_buffer_tiles_test.cpp) - target_link_libraries(d3d12_buffer_tiles_test PRIVATE gta6rt_d3d12_com d3d12 dxgi) - target_compile_definitions(d3d12_buffer_tiles_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) - target_compile_options(d3d12_buffer_tiles_test PRIVATE /W4 /permissive- /utf-8) - add_test(NAME d3d12_buffer_tiles COMMAND d3d12_buffer_tiles_test) - set_tests_properties(d3d12_buffer_tiles PROPERTIES SKIP_RETURN_CODE 77 - FAIL_REGULAR_EXPRESSION "Validation Error;VUID-") - add_executable(d3d12_texture_tiles_test test/d3d12_texture_tiles_test.cpp) - target_link_libraries(d3d12_texture_tiles_test PRIVATE gta6rt_d3d12_com d3d12 dxgi) - target_compile_definitions(d3d12_texture_tiles_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) - target_compile_options(d3d12_texture_tiles_test PRIVATE /W4 /permissive- /utf-8) - add_test(NAME d3d12_texture_tiles COMMAND d3d12_texture_tiles_test) - set_tests_properties(d3d12_texture_tiles PROPERTIES SKIP_RETURN_CODE 77 - FAIL_REGULAR_EXPRESSION "Validation Error;VUID-") - - # DXR acceleration-structure prebuild and command-list recording validation parity test. - add_executable(d3d12_dxr_validation_test test/d3d12_dxr_validation_test.cpp) - target_link_libraries(d3d12_dxr_validation_test PRIVATE gta6rt_d3d12_com d3d12 dxgi) - target_compile_definitions(d3d12_dxr_validation_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) - target_compile_options(d3d12_dxr_validation_test PRIVATE /W4 /permissive- /utf-8) - add_test(NAME d3d12_dxr_validation COMMAND d3d12_dxr_validation_test) - add_test(NAME d3d12_dxr_validation_khr COMMAND d3d12_dxr_validation_test) - set_tests_properties(d3d12_dxr_validation d3d12_dxr_validation_khr PROPERTIES SKIP_RETURN_CODE 77 - FAIL_REGULAR_EXPRESSION "Validation Error;VUID-") - set_tests_properties(d3d12_dxr_validation_khr PROPERTIES ENVIRONMENT "LEONIDA_RT_AS=khr") - - # D3D12 permits UpdateTileMappings on DIRECT/COPY/COMPUTE and a sparse buffer must remain - # accessible across their selected Vulkan families. The optional API-dump check catches an - # EXCLUSIVE VkBuffer even on drivers that happen to return correct bytes without ownership barriers. - add_executable(d3d12_sparse_queue_family_test test/d3d12_sparse_queue_family_test.cpp) - target_link_libraries(d3d12_sparse_queue_family_test PRIVATE gta6rt_d3d12_com d3d12 dxgi) - target_compile_definitions(d3d12_sparse_queue_family_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) - target_compile_options(d3d12_sparse_queue_family_test PRIVATE /W4 /permissive- /utf-8) - add_test(NAME d3d12_sparse_queue_family COMMAND d3d12_sparse_queue_family_test) - set_tests_properties(d3d12_sparse_queue_family PROPERTIES SKIP_RETURN_CODE 77 - FAIL_REGULAR_EXPRESSION "Validation Error;VUID-") - if(Python3_FOUND AND NOT CMAKE_CROSSCOMPILING) - add_test(NAME d3d12_sparse_queue_family_contract COMMAND "${Python3_EXECUTABLE}" -I - "${CMAKE_CURRENT_SOURCE_DIR}/test/check_sparse_queue_family.py" - "$") - set_tests_properties(d3d12_sparse_queue_family_contract PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 65) - endif() - set_tests_properties(d3d12_vulkan_device PROPERTIES SKIP_RETURN_CODE 77) - - add_executable(d3d12_texture1d_test test/d3d12_texture1d_test.cpp) - target_link_libraries(d3d12_texture1d_test PRIVATE gta6rt_d3d12_com dxguid) - target_compile_definitions(d3d12_texture1d_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) - target_compile_options(d3d12_texture1d_test PRIVATE /W4 /permissive- /utf-8) - add_test(NAME d3d12_texture1d COMMAND d3d12_texture1d_test) - set_tests_properties(d3d12_texture1d PROPERTIES SKIP_RETURN_CODE 77) - - # Placed 1D and 3D textures against the host runtime and WARP, and a copy round trip through them. - add_executable(d3d12_placed_dimensions_test test/d3d12_placed_dimensions_test.cpp) - target_link_libraries(d3d12_placed_dimensions_test PRIVATE gta6rt_d3d12_com d3d12 dxgi) - target_compile_definitions(d3d12_placed_dimensions_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) - target_compile_options(d3d12_placed_dimensions_test PRIVATE /W4 /permissive- /utf-8) - add_test(NAME d3d12_placed_dimensions COMMAND d3d12_placed_dimensions_test) - set_tests_properties(d3d12_placed_dimensions PROPERTIES SKIP_RETURN_CODE 77 - FAIL_REGULAR_EXPRESSION "Validation Error;VUID-") - - # FORMAT_SUPPORT of the depth- and stencil-plane view formats and comparison sampling, against the host runtime. - add_executable(d3d12_depth_view_format_support_test test/d3d12_depth_view_format_support_test.cpp) - target_link_libraries(d3d12_depth_view_format_support_test PRIVATE gta6rt_d3d12_com d3d12 dxgi) - target_compile_definitions(d3d12_depth_view_format_support_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) - target_compile_options(d3d12_depth_view_format_support_test PRIVATE /W4 /permissive- /utf-8) - add_test(NAME d3d12_depth_view_format_support COMMAND d3d12_depth_view_format_support_test) - set_tests_properties(d3d12_depth_view_format_support PROPERTIES SKIP_RETURN_CODE 77) - - # A placed buffer keeps its heap's arena range after the application releases the heap. - add_executable(d3d12_placed_heap_lifetime_test test/d3d12_placed_heap_lifetime_test.cpp) - target_link_libraries(d3d12_placed_heap_lifetime_test PRIVATE gta6rt_d3d12_com d3d12 dxgi) - target_compile_definitions(d3d12_placed_heap_lifetime_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) - target_compile_options(d3d12_placed_heap_lifetime_test PRIVATE /W4 /permissive- /utf-8) - add_test(NAME d3d12_placed_heap_lifetime COMMAND d3d12_placed_heap_lifetime_test) - set_tests_properties(d3d12_placed_heap_lifetime PROPERTIES SKIP_RETURN_CODE 77 - FAIL_REGULAR_EXPRESSION "Validation Error;VUID-") - - # ClearUnorderedAccessViewUint/Float on buffers and textures, read back through D3D12. - add_executable(d3d12_uav_clear_test test/d3d12_uav_clear_test.cpp) - target_link_libraries(d3d12_uav_clear_test PRIVATE gta6rt_d3d12_com) - target_compile_definitions(d3d12_uav_clear_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) - target_compile_options(d3d12_uav_clear_test PRIVATE /W4 /permissive- /utf-8) - add_test(NAME d3d12_uav_clear COMMAND d3d12_uav_clear_test) - set_tests_properties(d3d12_uav_clear PROPERTIES SKIP_RETURN_CODE 77) - - add_executable(d3d12_short_uav_clear_test test/d3d12_short_uav_clear_test.cpp) - target_link_libraries(d3d12_short_uav_clear_test PRIVATE gta6rt_d3d12_com d3d12 dxgi) - target_compile_definitions(d3d12_short_uav_clear_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) - target_compile_options(d3d12_short_uav_clear_test PRIVATE /W4 /permissive- /utf-8) - add_test(NAME d3d12_short_uav_clear COMMAND d3d12_short_uav_clear_test) - set_tests_properties(d3d12_short_uav_clear PROPERTIES SKIP_RETURN_CODE 77 - ENVIRONMENT "LEONIDA_HOST_ADAPTER=warp") - - # Emulation of R9G9B9E5_SHAREDEXP UAV textures as mutable R32_UINT on GPUs without E5B9G9R9 storage: - # format support, 1D/2D/3D/reserved creation, SRV/UAV T#s, WARP differential UAV clears, cross-backing copies, - # and set-0 storage write -> E5B9G9R9 sampled HDR round-trip. - add_executable(d3d12_d24_support_test test/d3d12_d24_support_test.cpp) - target_link_libraries(d3d12_d24_support_test PRIVATE gta6rt_d3d12_com d3d12 dxgi) - target_compile_definitions(d3d12_d24_support_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) - target_compile_options(d3d12_d24_support_test PRIVATE /W4 /permissive- /utf-8) - add_test(NAME d3d12_d24_support COMMAND d3d12_d24_support_test) - set_tests_properties(d3d12_d24_support PROPERTIES SKIP_RETURN_CODE 77) - add_executable(d3d12_b5g5r5a1_uav_test test/d3d12_b5g5r5a1_uav_test.cpp) - target_link_libraries(d3d12_b5g5r5a1_uav_test PRIVATE gta6rt_d3d12_com d3d12 dxgi) - target_compile_definitions(d3d12_b5g5r5a1_uav_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) - target_compile_options(d3d12_b5g5r5a1_uav_test PRIVATE /W4 /permissive- /utf-8) - add_test(NAME d3d12_b5g5r5a1_uav COMMAND d3d12_b5g5r5a1_uav_test) - set_tests_properties(d3d12_b5g5r5a1_uav PROPERTIES SKIP_RETURN_CODE 77) - add_executable(d3d12_srgb_uav_test test/d3d12_srgb_uav_test.cpp) - target_link_libraries(d3d12_srgb_uav_test PRIVATE gta6rt_d3d12_com d3d12 dxgi) - target_compile_definitions(d3d12_srgb_uav_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) - target_compile_options(d3d12_srgb_uav_test PRIVATE /W4 /permissive- /utf-8) - add_test(NAME d3d12_srgb_uav COMMAND d3d12_srgb_uav_test) - set_tests_properties(d3d12_srgb_uav PROPERTIES SKIP_RETURN_CODE 77) # native sRGB storage, no Vulkan GPU, or Wine - add_executable(d3d12_r9g9b9e5_uav_test test/d3d12_r9g9b9e5_uav_test.cpp) - target_link_libraries(d3d12_r9g9b9e5_uav_test PRIVATE gta6rt_d3d12_com d3d12 dxgi) - target_compile_definitions(d3d12_r9g9b9e5_uav_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) - target_compile_options(d3d12_r9g9b9e5_uav_test PRIVATE /W4 /permissive- /utf-8) - add_test(NAME d3d12_r9g9b9e5_uav COMMAND d3d12_r9g9b9e5_uav_test) - set_tests_properties(d3d12_r9g9b9e5_uav PROPERTIES SKIP_RETURN_CODE 77) - if(Vulkan_GLSLANG_VALIDATOR_EXECUTABLE) - set(LEONIDA_TEST_CS_R9G9B9E5_UAV ${CMAKE_CURRENT_BINARY_DIR}/generated/cs_r9g9b9e5_uav.spv) - add_custom_command( - OUTPUT ${LEONIDA_TEST_CS_R9G9B9E5_UAV} - COMMAND ${Vulkan_GLSLANG_VALIDATOR_EXECUTABLE} -V --target-env vulkan1.3 -o ${LEONIDA_TEST_CS_R9G9B9E5_UAV} - ${CMAKE_CURRENT_SOURCE_DIR}/test/glsl/cs_r9g9b9e5_uav.comp - DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/test/glsl/cs_r9g9b9e5_uav.comp - COMMENT "Compiling cs_r9g9b9e5_uav.comp" - VERBATIM) - target_sources(d3d12_r9g9b9e5_uav_test PRIVATE ${LEONIDA_TEST_CS_R9G9B9E5_UAV}) - target_compile_definitions(d3d12_r9g9b9e5_uav_test PRIVATE - LEONIDA_TEST_CS_R9G9B9E5_UAV_SPV="${LEONIDA_TEST_CS_R9G9B9E5_UAV}") - endif() - - # Debug markers as VK_EXT_debug_utils labels, and private data on every object (D3D-24). - add_executable(d3d12_debug_markers_test test/d3d12_debug_markers_test.cpp) - target_link_libraries(d3d12_debug_markers_test PRIVATE gta6rt_d3d12_com) - target_compile_definitions(d3d12_debug_markers_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) - target_compile_options(d3d12_debug_markers_test PRIVATE /W4 /permissive- /utf-8) - add_test(NAME d3d12_debug_markers COMMAND d3d12_debug_markers_test) - set_tests_properties(d3d12_debug_markers PROPERTIES SKIP_RETURN_CODE 77) - - # Existing-memory heaps and lifetime trackers: the arguments the host refuses (OpenExistingHeapFromAddress, - # OpenExistingHeapFromFileMapping, CreateLifetimeTracker). - add_executable(d3d12_existing_heap_test test/d3d12_existing_heap_test.cpp) - target_link_libraries(d3d12_existing_heap_test PRIVATE gta6rt_d3d12_com d3d12 dxgi) - target_compile_definitions(d3d12_existing_heap_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) - target_compile_options(d3d12_existing_heap_test PRIVATE /W4 /permissive- /utf-8) - add_test(NAME d3d12_existing_heap COMMAND d3d12_existing_heap_test) - set_tests_properties(d3d12_existing_heap PROPERTIES SKIP_RETURN_CODE 77) - # Slot 133 on untouched xmem physical pages: committed through the pages hook, then imported. xmem.cpp and - # registry.cpp are compiled in, as xmem_test does, to reach the registered XMem* exports. - add_executable(d3d12_xmem_placed_test test/d3d12_xmem_placed_test.cpp shims/xmem.cpp shims/registry.cpp) - target_link_libraries(d3d12_xmem_placed_test PRIVATE gta6rt_d3d12_com d3d12 dxgi psapi) - target_compile_definitions(d3d12_xmem_placed_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) - target_compile_options(d3d12_xmem_placed_test PRIVATE /W4 /permissive- /utf-8) - target_link_options(d3d12_xmem_placed_test PRIVATE /OPT:NOREF) - add_test(NAME d3d12_xmem_placed COMMAND d3d12_xmem_placed_test) - set_tests_properties(d3d12_xmem_placed PROPERTIES SKIP_RETURN_CODE 77) - - # Fences and timing (D3D-30): multiple-fence waits, clock calibration, adapter LUID, custom heap properties. - add_executable(d3d12_fence_timing_test test/d3d12_fence_timing_test.cpp) - target_link_libraries(d3d12_fence_timing_test PRIVATE gta6rt_d3d12_com d3d12 dxgi) - target_compile_definitions(d3d12_fence_timing_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) - target_compile_options(d3d12_fence_timing_test PRIVATE /W4 /permissive- /utf-8) - add_test(NAME d3d12_fence_timing COMMAND d3d12_fence_timing_test) - set_tests_properties(d3d12_fence_timing PROPERTIES SKIP_RETURN_CODE 77) - # Fence events the host runtime sets or refuses (released fences, no fences), compared with the host devices. - add_executable(d3d12_fence_events_test test/d3d12_fence_events_test.cpp) - target_link_libraries(d3d12_fence_events_test PRIVATE gta6rt_d3d12_com d3d12 dxgi) - target_compile_definitions(d3d12_fence_events_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) - target_compile_options(d3d12_fence_events_test PRIVATE /W4 /permissive- /utf-8) - add_test(NAME d3d12_fence_events COMMAND d3d12_fence_events_test) - set_tests_properties(d3d12_fence_events PROPERTIES SKIP_RETURN_CODE 77) - add_executable(d3d12_fence_device_lost_counter_test test/d3d12_fence_device_lost_counter_test.cpp) - target_link_libraries(d3d12_fence_device_lost_counter_test PRIVATE gta6rt_d3d12_com d3d12 dxgi) - target_compile_definitions(d3d12_fence_device_lost_counter_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) - target_compile_options(d3d12_fence_device_lost_counter_test PRIVATE /W4 /permissive- /utf-8) - add_test(NAME d3d12_fence_device_lost_counter COMMAND d3d12_fence_device_lost_counter_test) - set_tests_properties(d3d12_fence_device_lost_counter PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 60) - # Xbox-ABI queue and fence proxies behind the device proxy, on the host runtime (WARP, a hardware adapter) and - # on the Vulkan device: forwarding, refusal past the public chain, fence unwrapping. 77: no device at all. - add_executable(queue_proxy_test test/queue_proxy_test.cpp) - target_link_libraries(queue_proxy_test PRIVATE gta6rt_d3d12_com d3d12 dxgi) - target_compile_definitions(queue_proxy_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) - target_compile_options(queue_proxy_test PRIVATE /W4 /permissive- /utf-8 /EHsc) - add_test(NAME queue_proxy COMMAND queue_proxy_test) - set_tests_properties(queue_proxy PROPERTIES SKIP_RETURN_CODE 77) - # Xbox-ABI command allocator proxies (device slot 9) on the Vulkan device, and the unwrapped PC allocator on the - # host runtime: forwarding, refused tail, guard region, lists and GPU copies on the proxy. 77: no device at all. - add_executable(allocator_proxy_test test/allocator_proxy_test.cpp) - target_link_libraries(allocator_proxy_test PRIVATE gta6rt_d3d12_com d3d12 dxgi) - target_compile_definitions(allocator_proxy_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) - target_compile_options(allocator_proxy_test PRIVATE /W4 /permissive- /utf-8) - add_test(NAME allocator_proxy COMMAND allocator_proxy_test) - set_tests_properties(allocator_proxy PROPERTIES SKIP_RETURN_CODE 77) - # IDXGIDevice1 on the device proxy (the GDKX boot step: QueryInterface, GetAdapter, EnumOutputs), on the host - # runtime and on the Vulkan device: COM identity with the device, the adapter's LUID. 77: no device at all. - add_executable(dxgi_device_test test/dxgi_device_test.cpp) - target_link_libraries(dxgi_device_test PRIVATE gta6rt_d3d12_com d3d12 dxgi) - target_compile_definitions(dxgi_device_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) - target_compile_options(dxgi_device_test PRIVATE /W4 /permissive- /utf-8) - add_test(NAME dxgi_device COMMAND dxgi_device_test) - set_tests_properties(dxgi_device PROPERTIES SKIP_RETURN_CODE 77) - add_executable(dxgi_host_answers_test test/dxgi_host_answers_test.cpp) - target_link_libraries(dxgi_host_answers_test PRIVATE gta6rt_d3d12_com d3d12 dxgi) - target_compile_definitions(dxgi_host_answers_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) - target_compile_options(dxgi_host_answers_test PRIVATE /W4 /permissive- /utf-8) - add_test(NAME dxgi_host_answers COMMAND dxgi_host_answers_test) - set_tests_properties(dxgi_host_answers PROPERTIES SKIP_RETURN_CODE 77) - # The countdown behind those event-backed waits, with no GPU: the full unsigned count, no wrap past zero. - add_executable(d3d12_fence_waiter_test test/d3d12_fence_waiter_test.cpp) - target_compile_definitions(d3d12_fence_waiter_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) - target_compile_options(d3d12_fence_waiter_test PRIVATE /W4 /permissive- /utf-8) - add_test(NAME d3d12_fence_waiter COMMAND d3d12_fence_waiter_test) - # The 1/2/3 method variants (D3D-28) against the methods they wrap, on the Vulkan device directly. - add_executable(d3d12_method_variants_test test/d3d12_method_variants_test.cpp) - target_link_libraries(d3d12_method_variants_test PRIVATE gta6rt_d3d12_com) - target_compile_definitions(d3d12_method_variants_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) - target_compile_options(d3d12_method_variants_test PRIVATE /W4 /permissive- /utf-8) - add_test(NAME d3d12_method_variants COMMAND d3d12_method_variants_test) - # ID3D12Device9::CreateShaderCacheSession, ID3D12ShaderCacheSession and ShaderCacheControl (D3D-34). - add_executable(d3d12_shader_cache_test test/d3d12_shader_cache_test.cpp) - target_link_libraries(d3d12_shader_cache_test PRIVATE gta6rt_d3d12_com) - target_compile_definitions(d3d12_shader_cache_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) - target_compile_options(d3d12_shader_cache_test PRIVATE /W4 /permissive- /utf-8) - add_test(NAME d3d12_shader_cache COMMAND d3d12_shader_cache_test) - set_tests_properties(d3d12_shader_cache PROPERTIES SKIP_RETURN_CODE 77) - set_tests_properties(d3d12_method_variants PROPERTIES SKIP_RETURN_CODE 77) - # ID3D12Object private data (GetPrivateData, SetPrivateData, SetPrivateDataInterface, SetName) compared with - # the host runtime's answers on the device and four child objects. - add_executable(d3d12_private_data_test test/d3d12_private_data_test.cpp) - target_link_libraries(d3d12_private_data_test PRIVATE gta6rt_d3d12_com) - target_compile_definitions(d3d12_private_data_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) - target_compile_options(d3d12_private_data_test PRIVATE /W4 /permissive- /utf-8) - add_test(NAME d3d12_private_data COMMAND d3d12_private_data_test) - set_tests_properties(d3d12_private_data PROPERTIES SKIP_RETURN_CODE 77) - - # CreateSampler2 (D3D-28) against CreateSampler, and its refusals against the host's PC runtime. - add_executable(d3d12_sampler2_test test/d3d12_sampler2_test.cpp) - target_link_libraries(d3d12_sampler2_test PRIVATE gta6rt_d3d12_com) - target_compile_definitions(d3d12_sampler2_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) - target_compile_options(d3d12_sampler2_test PRIVATE /W4 /permissive- /utf-8) - add_test(NAME d3d12_sampler2 COMMAND d3d12_sampler2_test) - set_tests_properties(d3d12_sampler2 PROPERTIES SKIP_RETURN_CODE 77) - - # Descriptors through the proxy: copies between heaps, what texture views and samplers write into their slots, - # and (where glslangValidator is found) a compute shader the test runs on the device's bindless set, which - # finds a T# and an S# through the hash table and samples. The shader is GLSL, compiled here. - add_executable(d3d12_descriptor_test test/d3d12_descriptor_test.cpp) - target_link_libraries(d3d12_descriptor_test PRIVATE gta6rt_d3d12_com) - target_compile_definitions(d3d12_descriptor_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) - target_compile_options(d3d12_descriptor_test PRIVATE /W4 /permissive- /utf-8) - add_test(NAME d3d12_descriptor COMMAND d3d12_descriptor_test) - set_tests_properties(d3d12_descriptor PROPERTIES SKIP_RETURN_CODE 77) - if(Vulkan_GLSLANG_VALIDATOR_EXECUTABLE) - function(descriptor_test_shader shader definition) - set(source ${CMAKE_CURRENT_SOURCE_DIR}/test/glsl/${shader}) - set(binary ${CMAKE_CURRENT_BINARY_DIR}/generated/${definition}.spv) - add_custom_command(OUTPUT ${binary} - COMMAND ${Vulkan_GLSLANG_VALIDATOR_EXECUTABLE} -V --target-env vulkan1.3 ${ARGN} -o ${binary} ${source} - DEPENDS ${source} COMMENT "Compiling descriptor test shader ${shader}" VERBATIM) - target_sources(d3d12_descriptor_test PRIVATE ${binary}) - target_compile_definitions(d3d12_descriptor_test PRIVATE ${definition}="${binary}") - endfunction() - descriptor_test_shader(cs_sample.comp LEONIDA_TEST_CS_SAMPLE_SPV) - descriptor_test_shader(cs_sample.comp LEONIDA_TEST_GATHER_ALPHA_SPV -DTEST_GATHER_ALPHA=1) - descriptor_test_shader(cs_sample.comp LEONIDA_TEST_MS_FLOAT_SPV -DTEST_MS_FLOAT=1) - descriptor_test_shader(cs_sample.comp LEONIDA_TEST_MS_UINT_SPV -DTEST_MS_UINT=1) - descriptor_test_shader(cs_sample.comp LEONIDA_TEST_MS_SINT_SPV -DTEST_MS_SINT=1) - descriptor_test_shader(msaa_seed.vert LEONIDA_TEST_MSAA_VERT_SPV) - descriptor_test_shader(msaa_seed.frag LEONIDA_TEST_MSAA_FRAG_SPV) - else() - message(STATUS "glslangValidator not found: d3d12_descriptor_test skips its shader") - endif() - - add_executable(d3d12_predicated_copy_test test/d3d12_predicated_copy_test.cpp) - target_link_libraries(d3d12_predicated_copy_test PRIVATE gta6rt_d3d12_com d3d12 dxgi) - target_compile_definitions(d3d12_predicated_copy_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) - target_compile_options(d3d12_predicated_copy_test PRIVATE /W4 /permissive- /utf-8) - add_test(NAME d3d12_predicated_copy COMMAND d3d12_predicated_copy_test) - set_tests_properties(d3d12_predicated_copy PROPERTIES SKIP_RETURN_CODE 77) - # A DISPATCH-only ExecuteIndirect signature with a GPU count buffer: native Windows WARP versus Vulkan GPU, - # including a GPU-written count that changes between two calls in the same command list. - if(Vulkan_GLSLANG_VALIDATOR_EXECUTABLE) - set(_indirect_count_spv ${CMAKE_CURRENT_BINARY_DIR}/generated/cs_indirect_dispatch_count.spv) - add_custom_command(OUTPUT ${_indirect_count_spv} - COMMAND ${Vulkan_GLSLANG_VALIDATOR_EXECUTABLE} -V --target-env vulkan1.2 - -o ${_indirect_count_spv} ${CMAKE_CURRENT_SOURCE_DIR}/test/glsl/cs_indirect_dispatch_count.comp - DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/test/glsl/cs_indirect_dispatch_count.comp - COMMENT "Compiling the counted indirect dispatch test shader" VERBATIM) - add_executable(d3d12_indirect_dispatch_count_test test/d3d12_indirect_dispatch_count_test.cpp - ${_indirect_count_spv}) - target_link_libraries(d3d12_indirect_dispatch_count_test PRIVATE gta6rt_d3d12_com d3d12 dxgi version) - target_compile_definitions(d3d12_indirect_dispatch_count_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX - LEONIDA_TEST_INDIRECT_COUNT_SPV="${_indirect_count_spv}") - target_compile_options(d3d12_indirect_dispatch_count_test PRIVATE /W4 /permissive- /utf-8) - add_test(NAME d3d12_indirect_dispatch_count COMMAND d3d12_indirect_dispatch_count_test) - set_tests_properties(d3d12_indirect_dispatch_count PROPERTIES SKIP_RETURN_CODE 77) - endif() - - # What Close returns after one recorded call, against WARP; today's differences are listed in the test. - add_executable(d3d12_close_parity_test test/d3d12_close_parity_test.cpp) - target_link_libraries(d3d12_close_parity_test PRIVATE gta6rt_d3d12_com d3d12 dxgi) - target_compile_definitions(d3d12_close_parity_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) - target_compile_options(d3d12_close_parity_test PRIVATE /W4 /permissive- /utf-8) - add_test(NAME d3d12_close_parity COMMAND d3d12_close_parity_test) - set_tests_properties(d3d12_close_parity PROPERTIES SKIP_RETURN_CODE 77) - - # ExecuteIndirect recording-time Close() parity against live WARP and hardware D3D12, plus GPU dispatch sanity. - add_executable(d3d12_execute_indirect_validation_test test/d3d12_execute_indirect_validation_test.cpp) - target_link_libraries(d3d12_execute_indirect_validation_test PRIVATE gta6rt_d3d12_com d3d12 dxgi) - target_compile_definitions(d3d12_execute_indirect_validation_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) - target_compile_options(d3d12_execute_indirect_validation_test PRIVATE /W4 /permissive- /utf-8) - add_test(NAME d3d12_execute_indirect_validation COMMAND d3d12_execute_indirect_validation_test) - set_tests_properties(d3d12_execute_indirect_validation PROPERTIES - SKIP_RETURN_CODE 77 - FAIL_REGULAR_EXPRESSION "Validation Error;VUID-") - - # Set{Compute,Graphics}Root* closed-list, zero-count null, CBV alignment, and foreign root signature parity. - add_executable(d3d12_root_args_validation_test test/d3d12_root_args_validation_test.cpp) - target_link_libraries(d3d12_root_args_validation_test PRIVATE gta6rt_d3d12_com d3d12 dxgi) - target_compile_definitions(d3d12_root_args_validation_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) - target_compile_options(d3d12_root_args_validation_test PRIVATE /W4 /permissive- /utf-8) - add_test(NAME d3d12_root_args_validation COMMAND d3d12_root_args_validation_test) - set_tests_properties(d3d12_root_args_validation PROPERTIES - SKIP_RETURN_CODE 77 - FAIL_REGULAR_EXPRESSION "Validation Error;VUID-") - - # ClearState predication reset (GPU readback) + SetPredication / AtomicCopyBuffer Close() parity against WARP & HW. - add_executable(d3d12_predication_atomic_copy_test test/d3d12_predication_atomic_copy_test.cpp) - target_link_libraries(d3d12_predication_atomic_copy_test PRIVATE gta6rt_d3d12_com d3d12 dxgi) - target_compile_definitions(d3d12_predication_atomic_copy_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) - target_compile_options(d3d12_predication_atomic_copy_test PRIVATE /W4 /permissive- /utf-8) - add_test(NAME d3d12_predication_atomic_copy COMMAND d3d12_predication_atomic_copy_test) - set_tests_properties(d3d12_predication_atomic_copy PROPERTIES - SKIP_RETURN_CODE 77 - FAIL_REGULAR_EXPRESSION "Validation Error;VUID-" - ) - - # Differential regression: run explicitly (requires Vulkan hardware and Windows WARP). - add_executable(d3d12_clear_test test/d3d12_clear_test.cpp) - target_link_libraries(d3d12_clear_test PRIVATE gta6rt_d3d12_com d3d12 dxgi) - target_compile_definitions(d3d12_clear_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) - target_compile_options(d3d12_clear_test PRIVATE /W4 /permissive- /utf-8) - add_test(NAME d3d12_rgb9e5_rtv COMMAND d3d12_clear_test --rgb9e5) - set_tests_properties(d3d12_rgb9e5_rtv PROPERTIES SKIP_RETURN_CODE 77) - add_test(NAME d3d12_clear COMMAND d3d12_clear_test) - set_tests_properties(d3d12_clear PROPERTIES SKIP_RETURN_CODE 77) - - # Synthetic typed-view readbacks against Windows WARP; run explicitly on a Vulkan GPU. - add_executable(d3d12_typeless_rtv_test test/d3d12_typeless_rtv_test.cpp) - target_link_libraries(d3d12_typeless_rtv_test PRIVATE gta6rt_d3d12_com d3d12 dxgi) - target_compile_definitions(d3d12_typeless_rtv_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) - target_compile_options(d3d12_typeless_rtv_test PRIVATE /W4 /permissive- /utf-8) - add_test(NAME d3d12_typeless_rtv COMMAND d3d12_typeless_rtv_test) - # 1D render targets and depth buffers: creation against the host and WARP, clears read back against WARP. - add_executable(d3d12_texture1d_target_test test/d3d12_texture1d_target_test.cpp) - target_link_libraries(d3d12_texture1d_target_test PRIVATE gta6rt_d3d12_com d3d12 dxgi) - target_compile_definitions(d3d12_texture1d_target_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) - target_compile_options(d3d12_texture1d_target_test PRIVATE /W4 /permissive- /utf-8) - add_test(NAME d3d12_texture1d_target COMMAND d3d12_texture1d_target_test) - set_tests_properties(d3d12_texture1d_target PROPERTIES SKIP_RETURN_CODE 77) # no Vulkan GPU, or Wine - - # ArraySize -1 in array RTVs and DSVs (every slice from the first on), against the host on the same adapter - # and WARP. - add_executable(d3d12_view_slices_test test/d3d12_view_slices_test.cpp) - target_link_libraries(d3d12_view_slices_test PRIVATE gta6rt_d3d12_com d3d12 dxgi) - target_compile_definitions(d3d12_view_slices_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) - target_compile_options(d3d12_view_slices_test PRIVATE /W4 /permissive- /utf-8) - add_test(NAME d3d12_view_slices COMMAND d3d12_view_slices_test) - set_tests_properties(d3d12_view_slices PROPERTIES SKIP_RETURN_CODE 77) - - # Typed RTV clears and draws of every TYPELESS color family against the host on the same adapter and WARP - # (D3D-275). The draws need glslangValidator for their GLSL stand-ins of translated shaders. - add_executable(d3d12_typeless_families_test test/d3d12_typeless_families_test.cpp) - target_link_libraries(d3d12_typeless_families_test PRIVATE gta6rt_d3d12_com d3d12 dxgi) - target_compile_definitions(d3d12_typeless_families_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) - target_compile_options(d3d12_typeless_families_test PRIVATE /W4 /permissive- /utf-8) - add_test(NAME d3d12_typeless_families COMMAND d3d12_typeless_families_test) - set_tests_properties(d3d12_typeless_families PROPERTIES SKIP_RETURN_CODE 77) - if(Vulkan_GLSLANG_VALIDATOR_EXECUTABLE) - foreach(pair "vs_fullscreen.vert;LEONIDA_TYPELESS_VS_SPV;typeless_vs.spv" - "ps_typeless_float.frag;LEONIDA_TYPELESS_PS_FLOAT_SPV;typeless_ps_float.spv" - "ps_typeless_uint.frag;LEONIDA_TYPELESS_PS_UINT_SPV;typeless_ps_uint.spv") - list(GET pair 0 shader) - list(GET pair 1 definition) - list(GET pair 2 name) - set(binary ${CMAKE_CURRENT_BINARY_DIR}/generated/${name}) - add_custom_command(OUTPUT ${binary} - COMMAND ${Vulkan_GLSLANG_VALIDATOR_EXECUTABLE} -V --target-env vulkan1.3 -o ${binary} - ${CMAKE_CURRENT_SOURCE_DIR}/test/glsl/${shader} - DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/test/glsl/${shader} - COMMENT "Compiling the typeless draw test shader ${shader}" VERBATIM) - target_sources(d3d12_typeless_families_test PRIVATE ${binary}) - target_compile_definitions(d3d12_typeless_families_test PRIVATE ${definition}="${binary}") - endforeach() - else() - message(STATUS "glslangValidator not found: d3d12_typeless_families_test runs its clears only") - endif() - - # Fixed-function state (blend, depth, stencil) swept against the host D3D12 device on the same adapter. Needs - # glslangValidator for the GLSL stand-ins of translated shaders. - if(Vulkan_GLSLANG_VALIDATOR_EXECUTABLE) - add_executable(d3d12_state_sweep_test test/d3d12_state_sweep_test.cpp) - target_link_libraries(d3d12_state_sweep_test PRIVATE gta6rt_d3d12_com d3d12 dxgi) - target_compile_definitions(d3d12_state_sweep_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) - target_compile_options(d3d12_state_sweep_test PRIVATE /W4 /permissive- /utf-8) - foreach(pair "vs_fullscreen.vert;LEONIDA_SWEEP_VS_SPV;sweep_vs.spv" - "ps_sweep.frag;LEONIDA_SWEEP_PS_SPV;sweep_ps.spv") - list(GET pair 0 shader) - list(GET pair 1 definition) - list(GET pair 2 name) - set(binary ${CMAKE_CURRENT_BINARY_DIR}/generated/${name}) - add_custom_command(OUTPUT ${binary} - COMMAND ${Vulkan_GLSLANG_VALIDATOR_EXECUTABLE} -V --target-env vulkan1.3 -o ${binary} - ${CMAKE_CURRENT_SOURCE_DIR}/test/glsl/${shader} - DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/test/glsl/${shader} - COMMENT "Compiling the state sweep test shader ${shader}" VERBATIM) - target_sources(d3d12_state_sweep_test PRIVATE ${binary}) - target_compile_definitions(d3d12_state_sweep_test PRIVATE ${definition}="${binary}") - endforeach() - add_test(NAME d3d12_state_sweep COMMAND d3d12_state_sweep_test) - set_tests_properties(d3d12_state_sweep PROPERTIES SKIP_RETURN_CODE 77) - endif() - - # 96-bit R32G32B32 textures (D3D-62): footprints and every copy path against Windows WARP. - add_executable(d3d12_rgb96_test test/d3d12_rgb96_test.cpp) - target_link_libraries(d3d12_rgb96_test PRIVATE gta6rt_d3d12_com d3d12 dxgi) - target_compile_definitions(d3d12_rgb96_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) - target_compile_options(d3d12_rgb96_test PRIVATE /W4 /permissive- /utf-8) - add_test(NAME d3d12_rgb96 COMMAND d3d12_rgb96_test) - set_tests_properties(d3d12_rgb96 PROPERTIES SKIP_RETURN_CODE 77) # no Vulkan GPU or no WARP adapter - set_tests_properties(d3d12_typeless_rtv PROPERTIES SKIP_RETURN_CODE 77) - - # Depth/stencil ResolveSubresourceRegion against the host runtime and WARP; run explicitly on a Vulkan GPU. - add_executable(d3d12_depth_resolve_test test/d3d12_depth_resolve_test.cpp) - target_link_libraries(d3d12_depth_resolve_test PRIVATE gta6rt_d3d12_com d3d12 dxgi) - target_compile_definitions(d3d12_depth_resolve_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) - target_compile_options(d3d12_depth_resolve_test PRIVATE /W4 /permissive- /utf-8) - add_test(NAME d3d12_depth_resolve COMMAND d3d12_depth_resolve_test) - set_tests_properties(d3d12_depth_resolve PROPERTIES SKIP_RETURN_CODE 77) - # The edge cases (TEST-848) draw with a GLSL stand-in for a translated vertex shader; without glslangValidator - # only the clear cases run. - if(Vulkan_GLSLANG_VALIDATOR_EXECUTABLE) - set(binary ${CMAKE_CURRENT_BINARY_DIR}/generated/depth_edge_vs.spv) - add_custom_command(OUTPUT ${binary} - COMMAND ${Vulkan_GLSLANG_VALIDATOR_EXECUTABLE} -V --target-env vulkan1.3 -o ${binary} - ${CMAKE_CURRENT_SOURCE_DIR}/test/glsl/vs_depth_edge.vert - DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/test/glsl/vs_depth_edge.vert - COMMENT "Compiling the depth resolve test shader vs_depth_edge.vert" VERBATIM) - target_sources(d3d12_depth_resolve_test PRIVATE ${binary}) - target_compile_definitions(d3d12_depth_resolve_test PRIVATE LEONIDA_DEPTH_EDGE_VS_SPV="${binary}") - endif() - - # ID3D12Resource::GetDesc against the host runtime and WARP; run explicitly on a Vulkan GPU. - add_executable(d3d12_resource_desc_test test/d3d12_resource_desc_test.cpp) - target_link_libraries(d3d12_resource_desc_test PRIVATE gta6rt_d3d12_com d3d12 dxgi) - target_compile_definitions(d3d12_resource_desc_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) - target_compile_options(d3d12_resource_desc_test PRIVATE /W4 /permissive- /utf-8) - add_test(NAME d3d12_resource_desc COMMAND d3d12_resource_desc_test) - set_tests_properties(d3d12_resource_desc PROPERTIES SKIP_RETURN_CODE 77) - - # Typeless depth-stencil textures without ALLOW_DEPTH_STENCIL, copied from a depth buffer, against WARP. - add_executable(d3d12_typeless_depth_test test/d3d12_typeless_depth_test.cpp) - target_link_libraries(d3d12_typeless_depth_test PRIVATE gta6rt_d3d12_com d3d12 dxgi) - target_compile_definitions(d3d12_typeless_depth_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) - target_compile_options(d3d12_typeless_depth_test PRIVATE /W4 /permissive- /utf-8) - add_test(NAME d3d12_typeless_depth COMMAND d3d12_typeless_depth_test) - set_tests_properties(d3d12_typeless_depth PROPERTIES SKIP_RETURN_CODE 77) - - # WriteToSubresource/ReadFromSubresource arguments and bytes, compared with the host runtime. - add_executable(d3d12_subresource_copy_test test/d3d12_subresource_copy_test.cpp) - target_link_libraries(d3d12_subresource_copy_test PRIVATE gta6rt_d3d12_com d3d12 dxgi) - target_compile_definitions(d3d12_subresource_copy_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) - target_compile_options(d3d12_subresource_copy_test PRIVATE /W4 /permissive- /utf-8) - add_test(NAME d3d12_subresource_copy COMMAND d3d12_subresource_copy_test) - set_tests_properties(d3d12_subresource_copy PROPERTIES SKIP_RETURN_CODE 77) - - # MakeResident, Evict, SetResidencyPriority and EnqueueMakeResident, compared with the host runtime. - add_executable(d3d12_residency_test test/d3d12_residency_test.cpp) - target_link_libraries(d3d12_residency_test PRIVATE gta6rt_d3d12_com d3d12 dxgi) - target_compile_definitions(d3d12_residency_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) - target_compile_options(d3d12_residency_test PRIVATE /W4 /permissive- /utf-8) - add_test(NAME d3d12_residency COMMAND d3d12_residency_test) - set_tests_properties(d3d12_residency PROPERTIES SKIP_RETURN_CODE 77) - - # ID3D12Resource::GetHeapProperties for committed, placed and reserved resources, compared with the host runtime. - add_executable(d3d12_heap_properties_test test/d3d12_heap_properties_test.cpp) - target_link_libraries(d3d12_heap_properties_test PRIVATE gta6rt_d3d12_com d3d12 dxgi) - target_compile_definitions(d3d12_heap_properties_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) - target_compile_options(d3d12_heap_properties_test PRIVATE /W4 /permissive- /utf-8) - add_test(NAME d3d12_heap_properties COMMAND d3d12_heap_properties_test) - set_tests_properties(d3d12_heap_properties PROPERTIES SKIP_RETURN_CODE 77) - - # CreatePipelineLibrary and ID3D12PipelineLibrary1 arguments, compared with the host runtime. - add_executable(d3d12_pipeline_library_host_test test/d3d12_pipeline_library_host_test.cpp) - target_link_libraries(d3d12_pipeline_library_host_test PRIVATE gta6rt_d3d12_com d3d12 dxgi) - target_compile_definitions(d3d12_pipeline_library_host_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) - target_compile_options(d3d12_pipeline_library_host_test PRIVATE /W4 /permissive- /utf-8) - add_test(NAME d3d12_pipeline_library_host COMMAND d3d12_pipeline_library_host_test) - set_tests_properties(d3d12_pipeline_library_host PROPERTIES SKIP_RETURN_CODE 77) - - # Milestone M0: a window, 60 cleared frames presented through the proxy on Vulkan. - add_executable(d3d12_present_test test/d3d12_present_test.cpp) - target_link_libraries(d3d12_present_test PRIVATE gta6rt_d3d12_com user32 gdi32 dxgi) - target_compile_definitions(d3d12_present_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) - target_compile_options(d3d12_present_test PRIVATE /W4 /permissive- /utf-8) - add_test(NAME d3d12_present COMMAND d3d12_present_test) - set_tests_properties(d3d12_present PROPERTIES SKIP_RETURN_CODE 77) - - # Per-pipeline --f16-interp-fallback linking (SHADER-378): 16-param VS + colliding PS rendered on Vulkan. - add_executable(d3d12_f16_halves_test test/d3d12_f16_halves_test.cpp shims/d3d12_xs_device.cpp) - target_link_libraries(d3d12_f16_halves_test PRIVATE gta6rt_d3d12_com d3d12 dxgi) - target_compile_definitions(d3d12_f16_halves_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) - target_compile_options(d3d12_f16_halves_test PRIVATE /W4 /permissive- /utf-8) - add_test(NAME d3d12_f16_halves COMMAND d3d12_f16_halves_test) - set_tests_properties(d3d12_f16_halves PROPERTIES SKIP_RETURN_CODE 77) - - # PresentX and the frame events on the Vulkan device (shims/xbox_present.h), checked on swapchain pixels. - add_executable(xbox_present_test test/xbox_present_test.cpp) - target_link_libraries(xbox_present_test PRIVATE gta6rt_d3d12_com user32) - target_compile_definitions(xbox_present_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) - target_compile_options(xbox_present_test PRIVATE /W4 /permissive- /utf-8) - # Needs a Vulkan GPU and a window; exits 77 (skipped) without a Vulkan device. - add_test(NAME xbox_present COMMAND xbox_present_test) - set_tests_properties(xbox_present PROPERTIES SKIP_RETURN_CODE 77) - - # TEST-528: a real boot-movie frame (the package's Bink2Scarlett.dll) uploaded through the Xbox-ABI proxy and - # presented with PresentX, checked against the decoded BGRA. Package-gated like bink_decode_test: skips (77) - # unless LEONIDA_GAME_DIR and LEONIDA_MOVIE are set; no game data is written into the repo. - add_executable(d3d12_boot_movie_test - test/d3d12_boot_movie_test.cpp - src/pe_loader.cpp - shims/registry.cpp - shims/xmem.cpp - ) - target_link_libraries(d3d12_boot_movie_test PRIVATE gta6rt_d3d12_com user32 psapi) - target_compile_definitions(d3d12_boot_movie_test PRIVATE - WIN32_LEAN_AND_MEAN NOMINMAX UNICODE _UNICODE _CRT_SECURE_NO_WARNINGS) - target_compile_options(d3d12_boot_movie_test PRIVATE /W4 /permissive- /utf-8 /EHsc) - target_link_options(d3d12_boot_movie_test PRIVATE /OPT:NOREF) - add_dependencies(d3d12_boot_movie_test gta6rt_tls_host) - add_test(NAME d3d12_boot_movie COMMAND d3d12_boot_movie_test) - set_tests_properties(d3d12_boot_movie PROPERTIES SKIP_RETURN_CODE 77) - - # First light through D3D12 (docs/first_light.md): the real model and translated VS/PS that tools/first_light.py - # wrote to LEONIDA_FIRST_LIGHT_DIR, drawn through the device proxy. Skips (77) unless that variable is set. - add_executable(d3d12_first_light_test test/d3d12_first_light_test.cpp shims/d3d12_xs_device.cpp) - target_link_libraries(d3d12_first_light_test PRIVATE gta6rt_d3d12_com) - target_compile_definitions(d3d12_first_light_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX _CRT_SECURE_NO_WARNINGS) - target_compile_options(d3d12_first_light_test PRIVATE /W4 /permissive- /utf-8) - add_test(NAME d3d12_first_light COMMAND d3d12_first_light_test) - set_tests_properties(d3d12_first_light PROPERTIES SKIP_RETURN_CODE 77) - - # M1.5 (D3D-53): a draw whose VS and PS are translator output. test/shaders/vs_m15.asm and ps_m15.asm are assembled - # with llvm-mc and translated by tools/rdna2spirv.py through test/shaders/build.py, which also writes the FSSM - # programs their index entries are keyed by. Needs llvm-mc with the AMDGPU target (LLVM_MC in the environment, as - # for the other shader tests, or llvm-mc on PATH or in C:/msys64/ucrt64/bin) and the Vulkan SDK's spirv-as and - # spirv-val; without them the test is not built. - if(NOT LEONIDA_LLVM_MC) - if(DEFINED ENV{LLVM_MC}) - set(LEONIDA_LLVM_MC "$ENV{LLVM_MC}") - else() - find_program(LEONIDA_LLVM_MC llvm-mc HINTS "C:/msys64/ucrt64/bin") - endif() - endif() - find_program(LEONIDA_SPIRV_AS spirv-as HINTS "$ENV{VULKAN_SDK}/Bin" "$ENV{VULKAN_SDK}/bin") - find_program(LEONIDA_SPIRV_VAL spirv-val HINTS "$ENV{VULKAN_SDK}/Bin" "$ENV{VULKAN_SDK}/bin") - if(LEONIDA_LLVM_MC AND LEONIDA_SPIRV_AS AND LEONIDA_SPIRV_VAL) - set(LEONIDA_M15_DIR ${CMAKE_CURRENT_BINARY_DIR}/generated/m15_shaders) - get_filename_component(LEONIDA_SPIRV_TOOLS_DIR ${LEONIDA_SPIRV_AS} DIRECTORY) - file(TO_NATIVE_PATH "${LEONIDA_SPIRV_TOOLS_DIR}" LEONIDA_SPIRV_TOOLS_NATIVE) - set(LEONIDA_M15_FILES ${LEONIDA_M15_DIR}/spirv/index.json ${LEONIDA_M15_DIR}/fssm/vs_m15.fssm - ${LEONIDA_M15_DIR}/fssm/ps_m15.fssm) - add_custom_command( - OUTPUT ${LEONIDA_M15_FILES} - COMMAND ${CMAKE_COMMAND} -E remove_directory ${LEONIDA_M15_DIR} - COMMAND ${CMAKE_COMMAND} -E env "LLVM_MC=${LEONIDA_LLVM_MC}" "LEONIDA_SPIRV_TOOLS=${LEONIDA_SPIRV_TOOLS_NATIVE}" - $ -I ${CMAKE_CURRENT_SOURCE_DIR}/test/shaders/build.py - ${LEONIDA_M15_DIR} vs_m15 ps_m15 - DEPENDS ${LEONIDA_TRANSLATOR_DEPS} - ${CMAKE_CURRENT_SOURCE_DIR}/test/shaders/vs_m15.asm - ${CMAKE_CURRENT_SOURCE_DIR}/test/shaders/ps_m15.asm - COMMENT "Translating vs_m15 and ps_m15 for the translated draw test" - VERBATIM) - add_executable(d3d12_translated_draw_test test/d3d12_translated_draw_test.cpp shims/d3d12_xs_device.cpp - ${LEONIDA_M15_FILES}) - target_link_libraries(d3d12_translated_draw_test PRIVATE gta6rt_d3d12_com) - target_compile_definitions(d3d12_translated_draw_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX - LEONIDA_TEST_M15_DIR="${LEONIDA_M15_DIR}") - target_compile_options(d3d12_translated_draw_test PRIVATE /W4 /permissive- /utf-8) - add_test(NAME d3d12_translated_draw COMMAND d3d12_translated_draw_test) - set_tests_properties(d3d12_translated_draw PROPERTIES SKIP_RETURN_CODE 77) - - # vk_bindless_test (the bindless set and its table at the Vulkan level, no D3D12) takes the translated vs_ids, - # ps_tex and ps_imgatomic; it was only run by scripts/run_gpu_tests.py and check.py until D3D-314 needed it. - set(LEONIDA_BINDLESS_DIR ${CMAKE_CURRENT_BINARY_DIR}/generated/bindless_shaders) - set(LEONIDA_BINDLESS_FILES ${LEONIDA_BINDLESS_DIR}/spirv/vs_ids.spv ${LEONIDA_BINDLESS_DIR}/spirv/ps_tex.spv - ${LEONIDA_BINDLESS_DIR}/spirv/ps_imgatomic.spv) - add_custom_command( - OUTPUT ${LEONIDA_BINDLESS_FILES} - COMMAND ${CMAKE_COMMAND} -E remove_directory ${LEONIDA_BINDLESS_DIR} - COMMAND ${CMAKE_COMMAND} -E env "LLVM_MC=${LEONIDA_LLVM_MC}" "LEONIDA_SPIRV_TOOLS=${LEONIDA_SPIRV_TOOLS_NATIVE}" - $ -I ${CMAKE_CURRENT_SOURCE_DIR}/test/shaders/build.py - ${LEONIDA_BINDLESS_DIR} vs_ids ps_tex ps_imgatomic - DEPENDS ${LEONIDA_TRANSLATOR_DEPS} - ${CMAKE_CURRENT_SOURCE_DIR}/test/shaders/vs_ids.asm - ${CMAKE_CURRENT_SOURCE_DIR}/test/shaders/ps_tex.asm - ${CMAKE_CURRENT_SOURCE_DIR}/test/shaders/ps_imgatomic.asm - COMMENT "Translating vs_ids, ps_tex and ps_imgatomic for vk_bindless_test" - VERBATIM) - add_custom_target(vk_bindless_shaders ALL DEPENDS ${LEONIDA_BINDLESS_FILES}) - add_dependencies(vk_bindless_test vk_bindless_shaders) - add_test(NAME vk_bindless_ps_tex COMMAND vk_bindless_test ${LEONIDA_BINDLESS_DIR}/spirv/vs_ids.spv - ${LEONIDA_BINDLESS_DIR}/spirv/ps_tex.spv) - add_test(NAME vk_bindless_ps_imgatomic COMMAND vk_bindless_test ${LEONIDA_BINDLESS_DIR}/spirv/vs_ids.spv - ${LEONIDA_BINDLESS_DIR}/spirv/ps_imgatomic.spv) - set_tests_properties(vk_bindless_ps_tex vk_bindless_ps_imgatomic PROPERTIES SKIP_RETURN_CODE 77) - - # M2: a textured quad. vs_m2.asm and ps_m2.asm (the PS samples a T#/S# it loads from two descriptor tables) go - # through the same build; the test creates the heaps, the SRV, the sampler and the root signature through the - # D3D12 API only. - set(LEONIDA_M2_DIR ${CMAKE_CURRENT_BINARY_DIR}/generated/m2_shaders) - set(LEONIDA_M2_FILES ${LEONIDA_M2_DIR}/spirv/index.json ${LEONIDA_M2_DIR}/fssm/vs_m2.fssm - ${LEONIDA_M2_DIR}/fssm/ps_m2.fssm ${LEONIDA_M2_DIR}/fssm/ps_m2_uoff.fssm - ${LEONIDA_M2_DIR}/fssm/ps_m2_literal.fssm) - add_custom_command( - OUTPUT ${LEONIDA_M2_FILES} - COMMAND ${CMAKE_COMMAND} -E remove_directory ${LEONIDA_M2_DIR} - COMMAND ${CMAKE_COMMAND} -E env "LLVM_MC=${LEONIDA_LLVM_MC}" "LEONIDA_SPIRV_TOOLS=${LEONIDA_SPIRV_TOOLS_NATIVE}" - $ -I ${CMAKE_CURRENT_SOURCE_DIR}/test/shaders/build.py - ${LEONIDA_M2_DIR} vs_m2 ps_m2 ps_m2_uoff ps_m2_literal - DEPENDS ${LEONIDA_TRANSLATOR_DEPS} - ${CMAKE_CURRENT_SOURCE_DIR}/test/shaders/vs_m2.asm - ${CMAKE_CURRENT_SOURCE_DIR}/test/shaders/ps_m2.asm - ${CMAKE_CURRENT_SOURCE_DIR}/test/shaders/ps_m2_uoff.asm - ${CMAKE_CURRENT_SOURCE_DIR}/test/shaders/ps_m2_literal.asm - COMMENT "Translating vs_m2 and ps_m2 for the textured draw test" - VERBATIM) - add_executable(d3d12_m2_textured_test test/d3d12_m2_textured_test.cpp shims/d3d12_xs_device.cpp - ${LEONIDA_M2_FILES}) - target_link_libraries(d3d12_m2_textured_test PRIVATE gta6rt_d3d12_com) - target_compile_definitions(d3d12_m2_textured_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX - LEONIDA_TEST_M2_DIR="${LEONIDA_M2_DIR}") - target_compile_options(d3d12_m2_textured_test PRIVATE /W4 /permissive- /utf-8) - add_test(NAME d3d12_m2_textured COMMAND d3d12_m2_textured_test) - set_tests_properties(d3d12_m2_textured PROPERTIES SKIP_RETURN_CODE 77) - - # M2, formats: BC1 and BC7 textures with mip chains and an R8G8B8A8 2D array through the same descriptor path. - # vs_m2.asm with ps_m2.asm (2D) and ps_m2_array.asm (2D array, slice 1.0 of the view). - set(LEONIDA_M2F_DIR ${CMAKE_CURRENT_BINARY_DIR}/generated/m2f_shaders) - set(LEONIDA_M2F_FILES ${LEONIDA_M2F_DIR}/spirv/index.json ${LEONIDA_M2F_DIR}/fssm/vs_m2.fssm - ${LEONIDA_M2F_DIR}/fssm/ps_m2.fssm ${LEONIDA_M2F_DIR}/fssm/ps_m2_array.fssm) - add_custom_command( - OUTPUT ${LEONIDA_M2F_FILES} - COMMAND ${CMAKE_COMMAND} -E remove_directory ${LEONIDA_M2F_DIR} - COMMAND ${CMAKE_COMMAND} -E env "LLVM_MC=${LEONIDA_LLVM_MC}" "LEONIDA_SPIRV_TOOLS=${LEONIDA_SPIRV_TOOLS_NATIVE}" - $ -I ${CMAKE_CURRENT_SOURCE_DIR}/test/shaders/build.py - ${LEONIDA_M2F_DIR} vs_m2 ps_m2 ps_m2_array - DEPENDS ${LEONIDA_TRANSLATOR_DEPS} - ${CMAKE_CURRENT_SOURCE_DIR}/test/shaders/vs_m2.asm - ${CMAKE_CURRENT_SOURCE_DIR}/test/shaders/ps_m2.asm - ${CMAKE_CURRENT_SOURCE_DIR}/test/shaders/ps_m2_array.asm - COMMENT "Translating vs_m2, ps_m2 and ps_m2_array for the M2 formats test" - VERBATIM) - add_executable(d3d12_m2_formats_test test/d3d12_m2_formats_test.cpp shims/d3d12_xs_device.cpp - ${LEONIDA_M2F_FILES}) - target_link_libraries(d3d12_m2_formats_test PRIVATE gta6rt_d3d12_com) - target_compile_definitions(d3d12_m2_formats_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX - LEONIDA_TEST_M2F_DIR="${LEONIDA_M2F_DIR}") - target_compile_options(d3d12_m2_formats_test PRIVATE /W4 /permissive- /utf-8) - add_test(NAME d3d12_m2_formats COMMAND d3d12_m2_formats_test) - set_tests_properties(d3d12_m2_formats PROPERTIES SKIP_RETURN_CODE 77) - - # M3 (synthetic part): frames with two render targets and a depth/stencil buffer, an occlusion query, resource - # barriers and a second pass that samples the first one's target, three frames in flight with a fence each. - # Pass 1's two-output PS and its single-output occlusion probe go through the same translator build. - set(LEONIDA_M3_DIR ${CMAKE_CURRENT_BINARY_DIR}/generated/m3_shaders) - set(LEONIDA_M3_FILES ${LEONIDA_M3_DIR}/spirv/index.json ${LEONIDA_M3_DIR}/fssm/vs_m3.fssm - ${LEONIDA_M3_DIR}/fssm/ps_m3.fssm ${LEONIDA_M3_DIR}/fssm/vs_m2.fssm - ${LEONIDA_M3_DIR}/fssm/ps_m3_post.fssm ${LEONIDA_M3_DIR}/fssm/ps_m3_query.fssm) - add_custom_command( - OUTPUT ${LEONIDA_M3_FILES} - COMMAND ${CMAKE_COMMAND} -E remove_directory ${LEONIDA_M3_DIR} - COMMAND ${CMAKE_COMMAND} -E env "LLVM_MC=${LEONIDA_LLVM_MC}" "LEONIDA_SPIRV_TOOLS=${LEONIDA_SPIRV_TOOLS_NATIVE}" - $ -I ${CMAKE_CURRENT_SOURCE_DIR}/test/shaders/build.py - ${LEONIDA_M3_DIR} vs_m3 ps_m3 vs_m2 ps_m3_post ps_m3_query - DEPENDS ${LEONIDA_TRANSLATOR_DEPS} - ${CMAKE_CURRENT_SOURCE_DIR}/test/shaders/vs_m3.asm - ${CMAKE_CURRENT_SOURCE_DIR}/test/shaders/ps_m3.asm - ${CMAKE_CURRENT_SOURCE_DIR}/test/shaders/vs_m2.asm - ${CMAKE_CURRENT_SOURCE_DIR}/test/shaders/ps_m3_post.asm - ${CMAKE_CURRENT_SOURCE_DIR}/test/shaders/ps_m3_query.asm - COMMENT "Translating M3 frame and single-output occlusion-probe shaders" - VERBATIM) - add_executable(d3d12_m3_frame_test test/d3d12_m3_frame_test.cpp shims/d3d12_xs_device.cpp ${LEONIDA_M3_FILES}) - target_link_libraries(d3d12_m3_frame_test PRIVATE gta6rt_d3d12_com) - target_compile_definitions(d3d12_m3_frame_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX - LEONIDA_TEST_M3_DIR="${LEONIDA_M3_DIR}") - target_compile_options(d3d12_m3_frame_test PRIVATE /W4 /permissive- /utf-8) - add_test(NAME d3d12_m3_frame COMMAND d3d12_m3_frame_test) - add_test(NAME d3d12_m3_first_pass COMMAND d3d12_m3_frame_test --first-pass-only) - set_tests_properties(d3d12_m3_frame d3d12_m3_first_pass PROPERTIES SKIP_RETURN_CODE 77) - - # M4 (synthetic part): compute PSOs, a UAV table (structured and raw buffers, an R32_UINT storage image), an indirect - # dispatch from arguments a first dispatch wrote, and a copy queue that streams the input in and reads the results - # back across queue fences. cs_m4_fill.asm and cs_m4_indirect.asm go through the same build; build.py publishes - # their synthetic FSSM programs (the compute header and the words their "fssm-data" comments give), which the - # test wraps in shader containers. - set(LEONIDA_M4_DIR ${CMAKE_CURRENT_BINARY_DIR}/generated/m4_shaders) - set(LEONIDA_M4_FILES ${LEONIDA_M4_DIR}/spirv/index.json ${LEONIDA_M4_DIR}/fssm/cs_m4_fill.fssm - ${LEONIDA_M4_DIR}/fssm/cs_m4_indirect.fssm) - add_custom_command( - OUTPUT ${LEONIDA_M4_FILES} - COMMAND ${CMAKE_COMMAND} -E remove_directory ${LEONIDA_M4_DIR} - # LEONIDA_USER_DATA_SHIFT=4: the fixtures read their user data from s0; a D3D12 compute PSO gets its root - # arguments from s4 (rt::rootsig::pack_stage, D3D-448), so they are built with every SGPR 4 higher. - COMMAND ${CMAKE_COMMAND} -E env "LLVM_MC=${LEONIDA_LLVM_MC}" "LEONIDA_SPIRV_TOOLS=${LEONIDA_SPIRV_TOOLS_NATIVE}" - LEONIDA_USER_DATA_SHIFT=4 - $ -I ${CMAKE_CURRENT_SOURCE_DIR}/test/shaders/build.py - ${LEONIDA_M4_DIR} cs_m4_fill cs_m4_indirect - DEPENDS ${LEONIDA_TRANSLATOR_DEPS} - ${CMAKE_CURRENT_SOURCE_DIR}/test/shaders/cs_m4_fill.asm - ${CMAKE_CURRENT_SOURCE_DIR}/test/shaders/cs_m4_indirect.asm - COMMENT "Translating cs_m4_fill and cs_m4_indirect for the compute test" - VERBATIM) - add_executable(d3d12_m4_compute_test test/d3d12_m4_compute_test.cpp shims/d3d12_xs_device.cpp ${LEONIDA_M4_FILES}) - target_link_libraries(d3d12_m4_compute_test PRIVATE gta6rt_d3d12_com) - target_compile_definitions(d3d12_m4_compute_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX - LEONIDA_TEST_M4_DIR="${LEONIDA_M4_DIR}") - target_compile_options(d3d12_m4_compute_test PRIVATE /W4 /permissive- /utf-8) - add_test(NAME d3d12_m4_compute COMMAND d3d12_m4_compute_test) - set_tests_properties(d3d12_m4_compute PROPERTIES SKIP_RETURN_CODE 77) - - # Typed buffer UAVs and UAV counters: cs_buf_typed.asm writes typed views through V#s with a FORMAT, and - # cs_buf_counter.asm appends to and consumes from a structured view whose counter is the second V# of its slot; - # the test also compares typed-buffer and counter clears with the host runtime on the layer's adapter. - set(LEONIDA_BUFFER_UAV_DIR ${CMAKE_CURRENT_BINARY_DIR}/generated/buffer_uav_shaders) - set(LEONIDA_BUFFER_UAV_FILES ${LEONIDA_BUFFER_UAV_DIR}/spirv/index.json - ${LEONIDA_BUFFER_UAV_DIR}/fssm/cs_buf_typed.fssm - ${LEONIDA_BUFFER_UAV_DIR}/fssm/cs_buf_counter.fssm) - add_custom_command( - OUTPUT ${LEONIDA_BUFFER_UAV_FILES} - COMMAND ${CMAKE_COMMAND} -E remove_directory ${LEONIDA_BUFFER_UAV_DIR} - # LEONIDA_USER_DATA_SHIFT=4: root arguments from s4 in a D3D12 compute PSO (see the M4 shaders above). - COMMAND ${CMAKE_COMMAND} -E env "LLVM_MC=${LEONIDA_LLVM_MC}" "LEONIDA_SPIRV_TOOLS=${LEONIDA_SPIRV_TOOLS_NATIVE}" - LEONIDA_USER_DATA_SHIFT=4 - $ -I ${CMAKE_CURRENT_SOURCE_DIR}/test/shaders/build.py - ${LEONIDA_BUFFER_UAV_DIR} cs_buf_typed cs_buf_counter - DEPENDS ${LEONIDA_TRANSLATOR_DEPS} - ${CMAKE_CURRENT_SOURCE_DIR}/test/shaders/cs_buf_typed.asm - ${CMAKE_CURRENT_SOURCE_DIR}/test/shaders/cs_buf_counter.asm - COMMENT "Translating cs_buf_typed and cs_buf_counter for the buffer UAV test" - VERBATIM) - add_executable(d3d12_buffer_uav_test test/d3d12_buffer_uav_test.cpp shims/d3d12_xs_device.cpp ${LEONIDA_BUFFER_UAV_FILES}) - target_link_libraries(d3d12_buffer_uav_test PRIVATE gta6rt_d3d12_com) - target_compile_definitions(d3d12_buffer_uav_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX - LEONIDA_TEST_BUFFER_UAV_DIR="${LEONIDA_BUFFER_UAV_DIR}") - target_compile_options(d3d12_buffer_uav_test PRIVATE /W4 /permissive- /utf-8) - add_test(NAME d3d12_buffer_uav COMMAND d3d12_buffer_uav_test) - set_tests_properties(d3d12_buffer_uav PROPERTIES SKIP_RETURN_CODE 77) - else() - message(STATUS "llvm-mc (set LLVM_MC) or the SDK's spirv-as/spirv-val not found: d3d12_translated_draw_test, d3d12_m2_textured_test, d3d12_m2_formats_test, d3d12_m3_frame_test, d3d12_m4_compute_test and d3d12_buffer_uav_test are not built") - endif() - # ID3D12Resource::GetHeapProperties and ID3D12DescriptorHeap::GetDesc (node masks, resolved heap flags) against the - # host runtime and WARP; run explicitly on a Vulkan GPU. - add_executable(d3d12_node_mask_test test/d3d12_node_mask_test.cpp) - target_link_libraries(d3d12_node_mask_test PRIVATE gta6rt_d3d12_com d3d12 dxgi) - target_compile_definitions(d3d12_node_mask_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) - target_compile_options(d3d12_node_mask_test PRIVATE /W4 /permissive- /utf-8) - add_test(NAME d3d12_node_mask COMMAND d3d12_node_mask_test) - - # Console Xbox CreateDescriptorHeap extended ABI (issue #313 comment 7107265058): the title passes address/size - # after the PC desc and expects GetCPU/GPUDescriptorHandleForHeapStart() == address. Synthetic test; no title-memory - # aliasing / §3.3 backing coverage. - add_executable(d3d12_console_descriptor_heap_test test/d3d12_console_descriptor_heap_test.cpp shims/d3d12_xs_device.cpp) - target_link_libraries(d3d12_console_descriptor_heap_test PRIVATE gta6rt_d3d12_com d3d12 dxgi) - target_compile_definitions(d3d12_console_descriptor_heap_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) - target_compile_options(d3d12_console_descriptor_heap_test PRIVATE /W4 /permissive- /utf-8) - add_test(NAME d3d12_console_descriptor_heap COMMAND d3d12_console_descriptor_heap_test) - set_tests_properties(d3d12_console_descriptor_heap PROPERTIES SKIP_RETURN_CODE 77) - add_executable(d3d12_indirect_zero_test test/d3d12_indirect_zero_test.cpp) - target_link_libraries(d3d12_indirect_zero_test PRIVATE gta6rt_d3d12_com d3d12 dxgi) - target_compile_definitions(d3d12_indirect_zero_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) - target_compile_options(d3d12_indirect_zero_test PRIVATE /W4 /permissive- /utf-8) - add_test(NAME d3d12_indirect_zero COMMAND d3d12_indirect_zero_test) - set_tests_properties(d3d12_indirect_zero PROPERTIES SKIP_RETURN_CODE 77) - set_tests_properties(d3d12_node_mask PROPERTIES SKIP_RETURN_CODE 77) - set_tests_properties(d3d12_indirect_zero PROPERTIES SKIP_RETURN_CODE 77) - - # CopyResource / CopyTextureRegion between BC and its uncompressed equivalent (and depth <-> colour) against the - # host runtime and WARP; run explicitly on a Vulkan GPU. - add_executable(d3d12_copy_xfmt_test test/d3d12_copy_xfmt_test.cpp) - target_link_libraries(d3d12_copy_xfmt_test PRIVATE gta6rt_d3d12_com d3d12 dxgi) - target_compile_definitions(d3d12_copy_xfmt_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) - target_compile_options(d3d12_copy_xfmt_test PRIVATE /W4 /permissive- /utf-8) - add_test(NAME d3d12_copy_xfmt COMMAND d3d12_copy_xfmt_test) - set_tests_properties(d3d12_copy_xfmt PROPERTIES SKIP_RETURN_CODE 77) - - add_executable(d3d12_stencil_copy_test test/d3d12_stencil_copy_test.cpp) - target_link_libraries(d3d12_stencil_copy_test PRIVATE gta6rt_d3d12_com d3d12 dxgi) - target_compile_definitions(d3d12_stencil_copy_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) - target_compile_options(d3d12_stencil_copy_test PRIVATE /W4 /permissive- /utf-8) - add_test(NAME d3d12_stencil_copy COMMAND d3d12_stencil_copy_test) - set_tests_properties(d3d12_stencil_copy PROPERTIES SKIP_RETURN_CODE 77 - ENVIRONMENT "LEONIDA_HOST_ADAPTER=warp") - - # Query heaps and query calls by list type (Close results, CreateQueryHeap node masks, timestamp heap kinds) - # against the host runtime and WARP; run explicitly on a Vulkan GPU. - add_executable(d3d12_query_rules_test test/d3d12_query_rules_test.cpp) - target_link_libraries(d3d12_query_rules_test PRIVATE gta6rt_d3d12_com d3d12 dxgi) - target_compile_definitions(d3d12_query_rules_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) - target_compile_options(d3d12_query_rules_test PRIVATE /W4 /permissive- /utf-8) - add_test(NAME d3d12_query_rules COMMAND d3d12_query_rules_test) - set_tests_properties(d3d12_query_rules PROPERTIES SKIP_RETURN_CODE 77) - - # Vulkan-backed IDXGIFactory4 / IDXGISwapChain3 presentation over a Win32 HWND. - add_executable(dxgi_swapchain_test test/dxgi_swapchain_test.cpp) - target_link_libraries(dxgi_swapchain_test PRIVATE gta6rt_d3d12_com) - target_compile_definitions(dxgi_swapchain_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) - target_compile_options(dxgi_swapchain_test PRIVATE /W4 /permissive- /utf-8) - add_test(NAME dxgi_swapchain COMMAND dxgi_swapchain_test) - set_tests_properties(dxgi_swapchain PROPERTIES SKIP_RETURN_CODE 77) - - # The layer's DXGI against the host runtime's (hardware adapter, or WARP with PROBE_WARP=1): IDXGIAdapter4, - # GetRestrictToOutput without an output, ResizeBuffers flag bits and null out-pointers. - add_executable(dxgi_host_parity_test test/dxgi_host_parity_test.cpp) - target_link_libraries(dxgi_host_parity_test PRIVATE gta6rt_d3d12_com d3d12 dxgi) - target_compile_definitions(dxgi_host_parity_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) - target_compile_options(dxgi_host_parity_test PRIVATE /W4 /permissive- /utf-8) - add_test(NAME dxgi_host_parity COMMAND dxgi_host_parity_test) - set_tests_properties(dxgi_host_parity PROPERTIES SKIP_RETURN_CODE 77) - - # Host-parity test for DXGI waitable swap chain frame-latency semaphore behavior. - add_executable(dxgi_waitable_latency_test test/dxgi_waitable_latency_test.cpp) - target_link_libraries(dxgi_waitable_latency_test PRIVATE gta6rt_d3d12_com) - target_compile_definitions(dxgi_waitable_latency_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) - target_compile_options(dxgi_waitable_latency_test PRIVATE /W4 /permissive- /utf-8) - add_test(NAME dxgi_waitable_latency COMMAND dxgi_waitable_latency_test) - set_tests_properties(dxgi_waitable_latency PROPERTIES - SKIP_RETURN_CODE 77 - FAIL_REGULAR_EXPRESSION "Validation Error;VUID-") - - # Synthetic (no GPU): VulkanSwapchain's DXGI BufferCount contract when Vulkan returns more images than the - # app asked for, or the surface minimum exceeds the request (D3D-389). - add_executable(dxgi_swapchain_count_test test/dxgi_swapchain_count_test.cpp) - target_link_libraries(dxgi_swapchain_count_test PRIVATE Vulkan::Headers) - target_compile_definitions(dxgi_swapchain_count_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) - target_compile_options(dxgi_swapchain_count_test PRIVATE /W4 /permissive- /utf-8) - add_test(NAME dxgi_swapchain_count COMMAND dxgi_swapchain_count_test) - - # ExecuteIndirect with CountBuffer (vkCmdDrawIndirectCount) + optional BLAS/TLAS/RayQueryKHR GPU test. - add_executable(d3d12_indirect_rt_test test/d3d12_indirect_rt_test.cpp) - target_link_libraries(d3d12_indirect_rt_test PRIVATE gta6rt_d3d12_com) - target_compile_definitions(d3d12_indirect_rt_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) - target_compile_options(d3d12_indirect_rt_test PRIVATE /W4 /permissive- /utf-8) - if(Vulkan_GLSLANG_VALIDATOR_EXECUTABLE) - set(LEONIDA_TEST_VS_TRI ${CMAKE_CURRENT_BINARY_DIR}/generated/vs_tri.spv) - set(LEONIDA_TEST_FS_SOLID ${CMAKE_CURRENT_BINARY_DIR}/generated/fs_solid.spv) - set(LEONIDA_TEST_CS_RAYQUERY ${CMAKE_CURRENT_BINARY_DIR}/generated/cs_rayquery.spv) - add_custom_command( - OUTPUT ${LEONIDA_TEST_VS_TRI} - COMMAND ${Vulkan_GLSLANG_VALIDATOR_EXECUTABLE} -V --target-env vulkan1.3 -o ${LEONIDA_TEST_VS_TRI} - ${CMAKE_CURRENT_SOURCE_DIR}/test/glsl/vs_tri.vert - DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/test/glsl/vs_tri.vert - COMMENT "Compiling vs_tri.vert" - VERBATIM) - add_custom_command( - OUTPUT ${LEONIDA_TEST_FS_SOLID} - COMMAND ${Vulkan_GLSLANG_VALIDATOR_EXECUTABLE} -V --target-env vulkan1.3 -o ${LEONIDA_TEST_FS_SOLID} - ${CMAKE_CURRENT_SOURCE_DIR}/test/glsl/fs_solid.frag - DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/test/glsl/fs_solid.frag - COMMENT "Compiling fs_solid.frag" - VERBATIM) - add_custom_command( - OUTPUT ${LEONIDA_TEST_CS_RAYQUERY} - COMMAND ${Vulkan_GLSLANG_VALIDATOR_EXECUTABLE} -V --target-env vulkan1.3 -o ${LEONIDA_TEST_CS_RAYQUERY} - ${CMAKE_CURRENT_SOURCE_DIR}/test/glsl/cs_rayquery.comp - DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/test/glsl/cs_rayquery.comp - COMMENT "Compiling cs_rayquery.comp" - VERBATIM) - target_sources(d3d12_indirect_rt_test PRIVATE - ${LEONIDA_TEST_VS_TRI} ${LEONIDA_TEST_FS_SOLID} ${LEONIDA_TEST_CS_RAYQUERY}) - target_compile_definitions(d3d12_indirect_rt_test PRIVATE - LEONIDA_TEST_VS_TRI_SPV="${LEONIDA_TEST_VS_TRI}" - LEONIDA_TEST_FS_SOLID_SPV="${LEONIDA_TEST_FS_SOLID}" - LEONIDA_TEST_CS_RAYQUERY_SPV="${LEONIDA_TEST_CS_RAYQUERY}") - endif() - add_test(NAME d3d12_indirect_rt COMMAND d3d12_indirect_rt_test) - set_tests_properties(d3d12_indirect_rt PROPERTIES SKIP_RETURN_CODE 77) - # Upload heaps in system memory, as on a GPU without Resizable BAR: their VAs can lie below the arena and wrap. - add_test(NAME d3d12_indirect_rt_upload_sysmem COMMAND d3d12_indirect_rt_test) - set_tests_properties(d3d12_indirect_rt_upload_sysmem PROPERTIES SKIP_RETURN_CODE 77 - ENVIRONMENT "LEONIDA_UPLOAD_SYSMEM=1") - - # The compute path: root signature, compute PSO from a translator-style index, root arguments, dispatch. Its - # shader is GLSL written to the translator's push-constant/address contract, compiled here. - if(NOT Vulkan_GLSLANG_VALIDATOR_EXECUTABLE) - find_program(Vulkan_GLSLANG_VALIDATOR_EXECUTABLE glslangValidator HINTS "$ENV{VULKAN_SDK}/Bin" "$ENV{VULKAN_SDK}/bin") - endif() - if(Vulkan_GLSLANG_VALIDATOR_EXECUTABLE) - set(LEONIDA_TEST_CS ${CMAKE_CURRENT_BINARY_DIR}/generated/cs_user_data.spv) - add_custom_command( - OUTPUT ${LEONIDA_TEST_CS} - COMMAND ${Vulkan_GLSLANG_VALIDATOR_EXECUTABLE} -V --target-env vulkan1.3 -o ${LEONIDA_TEST_CS} - ${CMAKE_CURRENT_SOURCE_DIR}/test/glsl/cs_user_data.comp - DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/test/glsl/cs_user_data.comp - COMMENT "Compiling the compute test shader" - VERBATIM) - add_executable(d3d12_compute_test test/d3d12_compute_test.cpp shims/d3d12_xs_device.cpp ${LEONIDA_TEST_CS}) - target_link_libraries(d3d12_compute_test PRIVATE gta6rt_d3d12_com) - target_compile_definitions(d3d12_compute_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX - LEONIDA_TEST_CS_SPV="${LEONIDA_TEST_CS}") - target_compile_options(d3d12_compute_test PRIVATE /W4 /permissive- /utf-8) - add_test(NAME d3d12_compute COMMAND d3d12_compute_test) - set_tests_properties(d3d12_compute PROPERTIES SKIP_RETURN_CODE 77) - # Compute PSOs from FSPX programs (docs/fspx.md): an ACCC container at slot 62 and a bare kind-6 program. - add_executable(d3d12_fspx_compute_test test/d3d12_fspx_compute_test.cpp shims/d3d12_xs_device.cpp ${LEONIDA_TEST_CS}) - target_link_libraries(d3d12_fspx_compute_test PRIVATE gta6rt_d3d12_com) - target_compile_definitions(d3d12_fspx_compute_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX - LEONIDA_TEST_CS_SPV="${LEONIDA_TEST_CS}") - target_compile_options(d3d12_fspx_compute_test PRIVATE /W4 /permissive- /utf-8) - add_test(NAME d3d12_fspx_compute COMMAND d3d12_fspx_compute_test) - set_tests_properties(d3d12_fspx_compute PROPERTIES SKIP_RETURN_CODE 77) - # Milestone M1: a VS+PS pipeline and indexed draws, shaders written to the same contract. - set(LEONIDA_TEST_VS ${CMAKE_CURRENT_BINARY_DIR}/generated/vs_draw.spv) - set(LEONIDA_TEST_PS ${CMAKE_CURRENT_BINARY_DIR}/generated/ps_draw.spv) - set(LEONIDA_TEST_PS_UINT ${CMAKE_CURRENT_BINARY_DIR}/generated/ps_draw_uint.spv) - set(LEONIDA_TEST_VS_FULLSCREEN ${CMAKE_CURRENT_BINARY_DIR}/generated/vs_fullscreen.spv) - set(LEONIDA_TEST_VS_INT ${CMAKE_CURRENT_BINARY_DIR}/generated/vs_draw_int.spv) - set(LEONIDA_TEST_GS_DOUBLE ${CMAKE_CURRENT_BINARY_DIR}/generated/gs_double.spv) - foreach(pair "vs_draw.vert;${LEONIDA_TEST_VS}" "ps_draw.frag;${LEONIDA_TEST_PS}" - "ps_draw_uint.frag;${LEONIDA_TEST_PS_UINT}" "vs_fullscreen.vert;${LEONIDA_TEST_VS_FULLSCREEN}" "vs_draw_int.vert;${LEONIDA_TEST_VS_INT}" - "gs_double.geom;${LEONIDA_TEST_GS_DOUBLE}") - list(GET pair 0 source) - list(GET pair 1 output) - add_custom_command( - OUTPUT ${output} - COMMAND ${Vulkan_GLSLANG_VALIDATOR_EXECUTABLE} -V --target-env vulkan1.3 -o ${output} - ${CMAKE_CURRENT_SOURCE_DIR}/test/glsl/${source} - DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/test/glsl/${source} - COMMENT "Compiling the draw test shader ${source}" - VERBATIM) - endforeach() - add_executable(d3d12_draw_test test/d3d12_draw_test.cpp shims/d3d12_xs_device.cpp ${LEONIDA_TEST_VS} - ${LEONIDA_TEST_PS} ${LEONIDA_TEST_PS_UINT} ${LEONIDA_TEST_VS_FULLSCREEN} ${LEONIDA_TEST_VS_INT}) - target_link_libraries(d3d12_draw_test PRIVATE gta6rt_d3d12_com) - target_compile_definitions(d3d12_draw_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX - LEONIDA_TEST_VS_SPV="${LEONIDA_TEST_VS}" LEONIDA_TEST_PS_SPV="${LEONIDA_TEST_PS}" - LEONIDA_TEST_PS_UINT_SPV="${LEONIDA_TEST_PS_UINT}" - LEONIDA_TEST_VS_FULLSCREEN_SPV="${LEONIDA_TEST_VS_FULLSCREEN}" - LEONIDA_TEST_VS_INT_SPV="${LEONIDA_TEST_VS_INT}") - target_compile_options(d3d12_draw_test PRIVATE /W4 /permissive- /utf-8) - add_test(NAME d3d12_draw COMMAND d3d12_draw_test) - set_tests_properties(d3d12_draw PROPERTIES SKIP_RETURN_CODE 77) - # Graphics & compute PSO descriptor validation parity against live Windows D3D12 (WARP and HW). - add_executable(d3d12_pso_validation_test test/d3d12_pso_validation_test.cpp ${LEONIDA_TEST_VS} - ${LEONIDA_TEST_PS} ${LEONIDA_TEST_PS_UINT} ${LEONIDA_TEST_VS_FULLSCREEN} ${LEONIDA_TEST_CS}) - target_link_libraries(d3d12_pso_validation_test PRIVATE gta6rt_d3d12_com d3d12 dxgi) - target_compile_definitions(d3d12_pso_validation_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX - LEONIDA_TEST_VS_SPV="${LEONIDA_TEST_VS}" LEONIDA_TEST_PS_SPV="${LEONIDA_TEST_PS}" - LEONIDA_TEST_PS_UINT_SPV="${LEONIDA_TEST_PS_UINT}" - LEONIDA_TEST_VS_FULLSCREEN_SPV="${LEONIDA_TEST_VS_FULLSCREEN}" - LEONIDA_TEST_CS_SPV="${LEONIDA_TEST_CS}") - target_compile_options(d3d12_pso_validation_test PRIVATE /W4 /permissive- /utf-8) - add_test(NAME d3d12_pso_validation COMMAND d3d12_pso_validation_test) - set_tests_properties(d3d12_pso_validation PROPERTIES SKIP_RETURN_CODE 77 - FAIL_REGULAR_EXPRESSION "Validation Error;VUID-") - # Conservative raster Tier 1, with geometric coverage bounds and host D3D12 references. - set(LEONIDA_CONSERVATIVE_VS ${CMAKE_CURRENT_BINARY_DIR}/generated/vs_conservative.spv) - set(LEONIDA_CONSERVATIVE_PS ${CMAKE_CURRENT_BINARY_DIR}/generated/ps_conservative.spv) - foreach(pair "vs_conservative.vert;${LEONIDA_CONSERVATIVE_VS}" "ps_conservative.frag;${LEONIDA_CONSERVATIVE_PS}") - list(GET pair 0 source) - list(GET pair 1 output) - add_custom_command(OUTPUT ${output} - COMMAND ${Vulkan_GLSLANG_VALIDATOR_EXECUTABLE} -V --target-env vulkan1.3 -o ${output} - ${CMAKE_CURRENT_SOURCE_DIR}/test/glsl/${source} - DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/test/glsl/${source} VERBATIM) - endforeach() - add_executable(d3d12_conservative_raster_test test/d3d12_conservative_raster_test.cpp - ${LEONIDA_CONSERVATIVE_VS} ${LEONIDA_CONSERVATIVE_PS}) - target_link_libraries(d3d12_conservative_raster_test PRIVATE gta6rt_d3d12_com d3d12 dxgi) - target_compile_definitions(d3d12_conservative_raster_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX - LEONIDA_CONSERVATIVE_VS="${LEONIDA_CONSERVATIVE_VS}" LEONIDA_CONSERVATIVE_PS="${LEONIDA_CONSERVATIVE_PS}") - target_compile_options(d3d12_conservative_raster_test PRIVATE /W4 /permissive- /utf-8) - add_test(NAME d3d12_conservative_raster COMMAND d3d12_conservative_raster_test) - set_tests_properties(d3d12_conservative_raster PROPERTIES SKIP_RETURN_CODE 77 - ENVIRONMENT "LEONIDA_HOST_ADAPTER=warp") - set(LEONIDA_CONSERVATIVE_TIER2_VS ${CMAKE_CURRENT_BINARY_DIR}/generated/vs_conservative_tier2.spv) - set(LEONIDA_CONSERVATIVE_TIER2_PS ${CMAKE_CURRENT_BINARY_DIR}/generated/ps_conservative_tier2.spv) - foreach(pair "vs_conservative_tier2.vert;${LEONIDA_CONSERVATIVE_TIER2_VS}" "ps_conservative_tier2.frag;${LEONIDA_CONSERVATIVE_TIER2_PS}") - list(GET pair 0 source) - list(GET pair 1 output) - add_custom_command(OUTPUT ${output} - COMMAND ${Vulkan_GLSLANG_VALIDATOR_EXECUTABLE} -V --target-env vulkan1.3 -o ${output} - ${CMAKE_CURRENT_SOURCE_DIR}/test/glsl/${source} - DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/test/glsl/${source} VERBATIM) - endforeach() - add_executable(d3d12_conservative_tier2_test test/d3d12_conservative_tier2_test.cpp - ${LEONIDA_CONSERVATIVE_TIER2_VS} ${LEONIDA_CONSERVATIVE_TIER2_PS}) - target_link_libraries(d3d12_conservative_tier2_test PRIVATE gta6rt_d3d12_com d3d12 dxgi) - target_compile_definitions(d3d12_conservative_tier2_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX - LEONIDA_CONSERVATIVE_TIER2_VS="${LEONIDA_CONSERVATIVE_TIER2_VS}" LEONIDA_CONSERVATIVE_TIER2_PS="${LEONIDA_CONSERVATIVE_TIER2_PS}") - target_compile_options(d3d12_conservative_tier2_test PRIVATE /W4 /permissive- /utf-8) - add_test(NAME d3d12_conservative_tier2 COMMAND d3d12_conservative_tier2_test) - set_tests_properties(d3d12_conservative_tier2 PROPERTIES SKIP_RETURN_CODE 77 ENVIRONMENT "LEONIDA_HOST_ADAPTER=warp") - set(LEONIDA_CONSERVATIVE_TIER3_PS ${CMAKE_CURRENT_BINARY_DIR}/generated/ps_conservative_tier3.spv) - add_custom_command(OUTPUT ${LEONIDA_CONSERVATIVE_TIER3_PS} - COMMAND ${Vulkan_GLSLANG_VALIDATOR_EXECUTABLE} -V --target-env vulkan1.3 -o ${LEONIDA_CONSERVATIVE_TIER3_PS} - ${CMAKE_CURRENT_SOURCE_DIR}/test/glsl/ps_conservative_tier3.frag - DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/test/glsl/ps_conservative_tier3.frag VERBATIM) - add_executable(d3d12_conservative_tier3_test test/d3d12_conservative_tier3_test.cpp - ${LEONIDA_CONSERVATIVE_VS} ${LEONIDA_CONSERVATIVE_TIER3_PS}) - target_link_libraries(d3d12_conservative_tier3_test PRIVATE gta6rt_d3d12_com d3d12 dxgi) - target_compile_definitions(d3d12_conservative_tier3_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX - LEONIDA_CONSERVATIVE_VS="${LEONIDA_CONSERVATIVE_VS}" - LEONIDA_CONSERVATIVE_TIER3_PS="${LEONIDA_CONSERVATIVE_TIER3_PS}") - target_compile_options(d3d12_conservative_tier3_test PRIVATE /W4 /permissive- /utf-8) - add_test(NAME inner_coverage_oracle COMMAND d3d12_conservative_tier3_test --oracle-only) - add_test(NAME d3d12_inner_coverage_guards COMMAND d3d12_conservative_tier3_test --guards-only) - add_test(NAME d3d12_inner_coverage_native COMMAND d3d12_conservative_tier3_test --native-only) - add_test(NAME d3d12_conservative_tier3 COMMAND d3d12_conservative_tier3_test) - set_tests_properties(d3d12_inner_coverage_guards d3d12_inner_coverage_native d3d12_conservative_tier3 - PROPERTIES SKIP_RETURN_CODE 77) - add_executable(d3d12_msaa_draw_test test/d3d12_msaa_draw_test.cpp shims/d3d12_xs_device.cpp - ${LEONIDA_TEST_VS} ${LEONIDA_TEST_PS}) - target_link_libraries(d3d12_msaa_draw_test PRIVATE gta6rt_d3d12_com) - target_compile_definitions(d3d12_msaa_draw_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX - LEONIDA_TEST_VS_SPV="${LEONIDA_TEST_VS}" LEONIDA_TEST_PS_SPV="${LEONIDA_TEST_PS}") - target_compile_options(d3d12_msaa_draw_test PRIVATE /W4 /permissive- /utf-8) - add_test(NAME d3d12_msaa_draw COMMAND d3d12_msaa_draw_test) - set_tests_properties(d3d12_msaa_draw PROPERTIES SKIP_RETURN_CODE 77) - # Geometry shaders: a VS+GS+PS pipeline whose GS emits each triangle twice. - add_executable(d3d12_geometry_test test/d3d12_geometry_test.cpp shims/d3d12_xs_device.cpp - ${LEONIDA_TEST_VS} ${LEONIDA_TEST_GS_DOUBLE} ${LEONIDA_TEST_PS}) - target_link_libraries(d3d12_geometry_test PRIVATE gta6rt_d3d12_com) - target_compile_definitions(d3d12_geometry_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX - LEONIDA_TEST_VS_SPV="${LEONIDA_TEST_VS}" LEONIDA_TEST_GS_SPV="${LEONIDA_TEST_GS_DOUBLE}" - LEONIDA_TEST_PS_SPV="${LEONIDA_TEST_PS}") - target_compile_options(d3d12_geometry_test PRIVATE /W4 /permissive- /utf-8) - add_test(NAME d3d12_geometry COMMAND d3d12_geometry_test) - set_tests_properties(d3d12_geometry PROPERTIES SKIP_RETURN_CODE 77) - # D3D-309: D24 depth bias and 24-bit depth in draws, with and without a pixel shader and with a geometry shader - # (src/depth24_fragment.h). - set(LEONIDA_TEST_VS_DEPTH ${CMAKE_CURRENT_BINARY_DIR}/generated/vs_depth.spv) - set(LEONIDA_TEST_PS_DEPTH_EMPTY ${CMAKE_CURRENT_BINARY_DIR}/generated/ps_depth_empty.spv) - set(LEONIDA_TEST_PS_DEPTH_WRITE ${CMAKE_CURRENT_BINARY_DIR}/generated/ps_depth_write.spv) - set(LEONIDA_TEST_GS_DEPTH ${CMAKE_CURRENT_BINARY_DIR}/generated/gs_depth.spv) - foreach(pair "vs_depth.vert;${LEONIDA_TEST_VS_DEPTH}" "ps_depth_empty.frag;${LEONIDA_TEST_PS_DEPTH_EMPTY}" - "ps_depth_write.frag;${LEONIDA_TEST_PS_DEPTH_WRITE}" "gs_depth.geom;${LEONIDA_TEST_GS_DEPTH}") - list(GET pair 0 source) - list(GET pair 1 output) - add_custom_command( - OUTPUT ${output} - COMMAND ${Vulkan_GLSLANG_VALIDATOR_EXECUTABLE} -V --target-env vulkan1.3 -o ${output} - ${CMAKE_CURRENT_SOURCE_DIR}/test/glsl/${source} - DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/test/glsl/${source} - COMMENT "Compiling the D24 draw test shader ${source}" - VERBATIM) - endforeach() - add_executable(d3d12_depth24_draw_test test/d3d12_depth24_draw_test.cpp shims/d3d12_xs_device.cpp - ${LEONIDA_TEST_VS_DEPTH} ${LEONIDA_TEST_PS_DEPTH_EMPTY} ${LEONIDA_TEST_PS_DEPTH_WRITE} - ${LEONIDA_TEST_GS_DEPTH}) - target_link_libraries(d3d12_depth24_draw_test PRIVATE gta6rt_d3d12_com) - target_compile_definitions(d3d12_depth24_draw_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX - LEONIDA_TEST_VS_DEPTH_SPV="${LEONIDA_TEST_VS_DEPTH}" - LEONIDA_TEST_PS_DEPTH_EMPTY_SPV="${LEONIDA_TEST_PS_DEPTH_EMPTY}" - LEONIDA_TEST_PS_DEPTH_WRITE_SPV="${LEONIDA_TEST_PS_DEPTH_WRITE}" - LEONIDA_TEST_GS_DEPTH_SPV="${LEONIDA_TEST_GS_DEPTH}") - target_compile_options(d3d12_depth24_draw_test PRIVATE /W4 /permissive- /utf-8) - add_test(NAME d3d12_depth24_draw COMMAND d3d12_depth24_draw_test) - set_tests_properties(d3d12_depth24_draw PROPERTIES SKIP_RETURN_CODE 77) - # Set 0 from the compute bind point: a compute PSO whose shader declares set-0 bindings samples through the - # device's bindless set, which nothing but the layer binds. - set(LEONIDA_TEST_CS_SET0_SAMPLE ${CMAKE_CURRENT_BINARY_DIR}/generated/cs_set0_sample.spv) - add_custom_command( - OUTPUT ${LEONIDA_TEST_CS_SET0_SAMPLE} - COMMAND ${Vulkan_GLSLANG_VALIDATOR_EXECUTABLE} -V --target-env vulkan1.3 -o ${LEONIDA_TEST_CS_SET0_SAMPLE} - ${CMAKE_CURRENT_SOURCE_DIR}/test/glsl/cs_set0_sample.comp - DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/test/glsl/cs_set0_sample.comp - COMMENT "Compiling the set-0 compute test shader" - VERBATIM) - add_executable(d3d12_set0_compute_test test/d3d12_set0_compute_test.cpp shims/d3d12_xs_device.cpp - ${LEONIDA_TEST_CS_SET0_SAMPLE}) - target_link_libraries(d3d12_set0_compute_test PRIVATE gta6rt_d3d12_com) - target_compile_definitions(d3d12_set0_compute_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX - LEONIDA_TEST_CS_SET0_SAMPLE_SPV="${LEONIDA_TEST_CS_SET0_SAMPLE}") - target_compile_options(d3d12_set0_compute_test PRIVATE /W4 /permissive- /utf-8) - add_test(NAME d3d12_set0_compute COMMAND d3d12_set0_compute_test) - set_tests_properties(d3d12_set0_compute PROPERTIES SKIP_RETURN_CODE 77) - # Bindless table churn on a direct and a compute queue: the table grows and live keys move without a - # device-idle wait (D3D-314); the same shader, run twice (deferred retirement, and the old wait for timing). - add_executable(d3d12_bindless_churn_test test/d3d12_bindless_churn_test.cpp shims/d3d12_xs_device.cpp - ${LEONIDA_TEST_CS_SET0_SAMPLE}) - target_link_libraries(d3d12_bindless_churn_test PRIVATE gta6rt_d3d12_com) - target_compile_definitions(d3d12_bindless_churn_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX - LEONIDA_TEST_CS_SET0_SAMPLE_SPV="${LEONIDA_TEST_CS_SET0_SAMPLE}") - target_compile_options(d3d12_bindless_churn_test PRIVATE /W4 /permissive- /utf-8) - add_test(NAME d3d12_bindless_churn COMMAND d3d12_bindless_churn_test) - set_tests_properties(d3d12_bindless_churn PROPERTIES SKIP_RETURN_CODE 77) - add_test(NAME d3d12_bindless_churn_validated COMMAND d3d12_bindless_churn_test --validated) - set_tests_properties(d3d12_bindless_churn_validated PROPERTIES SKIP_RETURN_CODE 77) - add_executable(d3d12_pipeline_library_test test/d3d12_pipeline_library_test.cpp - ${LEONIDA_TEST_CS} ${LEONIDA_TEST_VS} ${LEONIDA_TEST_PS}) - target_link_libraries(d3d12_pipeline_library_test PRIVATE gta6rt_d3d12_com) - target_compile_definitions(d3d12_pipeline_library_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX - LEONIDA_TEST_CS_SPV="${LEONIDA_TEST_CS}" - LEONIDA_TEST_VS_SPV="${LEONIDA_TEST_VS}" - LEONIDA_TEST_PS_SPV="${LEONIDA_TEST_PS}") - target_compile_options(d3d12_pipeline_library_test PRIVATE /W4 /permissive- /utf-8) - add_test(NAME d3d12_pipeline_library COMMAND d3d12_pipeline_library_test) - set_tests_properties(d3d12_pipeline_library PROPERTIES SKIP_RETURN_CODE 77) - # ExecuteBundle: what a bundle's draws inherit and hand back, against the host runtime and WARP. - add_executable(d3d12_bundle_test test/d3d12_bundle_test.cpp ${LEONIDA_TEST_VS} ${LEONIDA_TEST_PS}) - target_link_libraries(d3d12_bundle_test PRIVATE gta6rt_d3d12_com d3d12 dxgi) - target_compile_definitions(d3d12_bundle_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX _CRT_SECURE_NO_WARNINGS - LEONIDA_TEST_VS_SPV="${LEONIDA_TEST_VS}" LEONIDA_TEST_PS_SPV="${LEONIDA_TEST_PS}") - target_compile_options(d3d12_bundle_test PRIVATE /W4 /permissive- /utf-8) - add_test(NAME d3d12_bundle COMMAND d3d12_bundle_test) - set_tests_properties(d3d12_bundle PROPERTIES SKIP_RETURN_CODE 77) - # Calls a bundle may not make, Close of the bundle and of its parent, against the host runtime and WARP. - add_executable(d3d12_bundle_forbidden_test test/d3d12_bundle_forbidden_test.cpp) - target_link_libraries(d3d12_bundle_forbidden_test PRIVATE gta6rt_d3d12_com d3d12 dxgi) - target_compile_definitions(d3d12_bundle_forbidden_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) - target_compile_options(d3d12_bundle_forbidden_test PRIVATE /W4 /permissive- /utf-8) - add_test(NAME d3d12_bundle_forbidden COMMAND d3d12_bundle_forbidden_test) - set_tests_properties(d3d12_bundle_forbidden PROPERTIES SKIP_RETURN_CODE 77) - # A pixel shader with a writable storage image (an image atomic) needs fragmentStoresAndAtomics: refused on a - # device without it, created on the runtime's own device, under the validation layer where it is installed. - set(LEONIDA_TEST_PS_ATOMIC ${CMAKE_CURRENT_BINARY_DIR}/generated/ps_image_atomic.spv) - add_custom_command( - OUTPUT ${LEONIDA_TEST_PS_ATOMIC} - COMMAND ${Vulkan_GLSLANG_VALIDATOR_EXECUTABLE} -V --target-env vulkan1.3 -o ${LEONIDA_TEST_PS_ATOMIC} - ${CMAKE_CURRENT_SOURCE_DIR}/test/glsl/ps_image_atomic.frag - DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/test/glsl/ps_image_atomic.frag - COMMENT "Compiling the stores-and-atomics test shader ps_image_atomic.frag" - VERBATIM) - add_executable(d3d12_stores_atomics_test test/d3d12_stores_atomics_test.cpp ${LEONIDA_TEST_VS_FULLSCREEN} - ${LEONIDA_TEST_PS} ${LEONIDA_TEST_PS_ATOMIC}) - target_link_libraries(d3d12_stores_atomics_test PRIVATE gta6rt_d3d12_com) - target_compile_definitions(d3d12_stores_atomics_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX - LEONIDA_TEST_VS_FULLSCREEN_SPV="${LEONIDA_TEST_VS_FULLSCREEN}" - LEONIDA_TEST_PS_SPV="${LEONIDA_TEST_PS}" - LEONIDA_TEST_PS_ATOMIC_SPV="${LEONIDA_TEST_PS_ATOMIC}") - target_compile_options(d3d12_stores_atomics_test PRIVATE /W4 /permissive- /utf-8) - add_test(NAME d3d12_stores_atomics COMMAND d3d12_stores_atomics_test) - set_tests_properties(d3d12_stores_atomics PROPERTIES SKIP_RETURN_CODE 77) - - # D3D-29: mesh-shader PSOs from pipeline state streams and DispatchMesh (skips without VK_EXT_mesh_shader). - set(LEONIDA_TEST_MS ${CMAKE_CURRENT_BINARY_DIR}/generated/ms_draw.spv) - add_custom_command( - OUTPUT ${LEONIDA_TEST_MS} - # Vulkan 1.2 (SPIR-V 1.5), the translator's target: 1.3 would emit LocalSizeId, which needs maintenance4. - COMMAND ${Vulkan_GLSLANG_VALIDATOR_EXECUTABLE} -V --target-env vulkan1.2 -o ${LEONIDA_TEST_MS} - ${CMAKE_CURRENT_SOURCE_DIR}/test/glsl/ms_draw.mesh - DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/test/glsl/ms_draw.mesh - COMMENT "Compiling the mesh test shader ms_draw.mesh" - VERBATIM) - add_executable(d3d12_mesh_test test/d3d12_mesh_test.cpp shims/d3d12_xs_device.cpp ${LEONIDA_TEST_MS} - ${LEONIDA_TEST_PS} ${LEONIDA_TEST_VS_FULLSCREEN}) - target_link_libraries(d3d12_mesh_test PRIVATE gta6rt_d3d12_com) - target_compile_definitions(d3d12_mesh_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX - LEONIDA_TEST_MS_SPV="${LEONIDA_TEST_MS}" LEONIDA_TEST_PS_SPV="${LEONIDA_TEST_PS}" - LEONIDA_TEST_VS_FULLSCREEN_SPV="${LEONIDA_TEST_VS_FULLSCREEN}") - target_compile_options(d3d12_mesh_test PRIVATE /W4 /permissive- /utf-8) - add_test(NAME d3d12_mesh COMMAND d3d12_mesh_test) - set_tests_properties(d3d12_mesh PROPERTIES SKIP_RETURN_CODE 77) - else() - message(STATUS "glslangValidator not found: d3d12_compute_test, d3d12_draw_test, d3d12_set0_compute_test and d3d12_mesh_test are not built") - endif() - - # Native D3D12 SV_InnerCoverage reference; its HLSL is compiled at runtime, so glslang is not needed. - add_executable(d3d12_conservative_tier3_reference_test test/d3d12_conservative_tier3_reference_test.cpp) - target_link_libraries(d3d12_conservative_tier3_reference_test PRIVATE gta6rt_d3d12_com d3d12 dxgi) - target_compile_definitions(d3d12_conservative_tier3_reference_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) - target_compile_options(d3d12_conservative_tier3_reference_test PRIVATE /W4 /permissive- /utf-8) - add_test(NAME d3d12_conservative_tier3_reference COMMAND d3d12_conservative_tier3_reference_test) - set_tests_properties(d3d12_conservative_tier3_reference PROPERTIES SKIP_RETURN_CODE 77) - - # Subgroup size control in PSOs, end to end: runtime/test/shaders/cs_w64x_readlane.asm translated natively and with - # --wave64-emulate, and cs_wqm_w32.asm, built here with tools/rdna2spirv.py through test/shaders/build.py. Needs - # llvm-mc with the AMDGPU target (LLVM_MC in the environment, as for the other shader tests, or llvm-mc on PATH) - # and the Vulkan SDK's spirv tools; without them the test is not built. - if(DEFINED ENV{LLVM_MC}) - set(LEONIDA_LLVM_MC "$ENV{LLVM_MC}") - else() - find_program(LEONIDA_LLVM_MC llvm-mc HINTS "C:/msys64/ucrt64/bin") - endif() - if(LEONIDA_LLVM_MC AND Vulkan_GLSLANG_VALIDATOR_EXECUTABLE) - set(LEONIDA_SG_DIR ${CMAKE_CURRENT_BINARY_DIR}/generated/subgroup_shaders) - set(LEONIDA_SG_INDEXES "") - foreach(case "w64_native;cs_w64x_readlane;0" "w64_emulated;cs_w64x_readlane;1" "w32_native;cs_wqm_w32;0" - "ps_w64_native;ps_w64x_readlane;0") - list(GET case 0 folder) - list(GET case 1 shader) - list(GET case 2 emulate) - set(index ${LEONIDA_SG_DIR}/${folder}/spirv/index.json) - add_custom_command( - OUTPUT ${index} - # The standalone harness runs these with the V# at s[0:3]; d3d12_subgroup_test passes it as four root - # constants, which the D3D12 compute layout puts at s[4:7] (LEONIDA_USER_DATA_SHIFT=4, D3D-448). - COMMAND ${CMAKE_COMMAND} -E env LLVM_MC=${LEONIDA_LLVM_MC} LEONIDA_W64_EMULATE=${emulate} - LEONIDA_USER_DATA_SHIFT=4 - $ -I ${CMAKE_CURRENT_SOURCE_DIR}/test/shaders/build.py - ${LEONIDA_SG_DIR}/${folder} ${shader} - DEPENDS ${LEONIDA_TRANSLATOR_DEPS} - ${CMAKE_CURRENT_SOURCE_DIR}/test/shaders/${shader}.asm - COMMENT "Translating ${shader} for the subgroup size test (${folder})" - VERBATIM) - list(APPEND LEONIDA_SG_INDEXES ${index}) - endforeach() - # The probe shaders that store the subgroup size the driver ran them with, and a one-triangle vertex shader. - foreach(source cs_sg_probe.comp ps_sg_probe.frag vs_sg_fullscreen.vert) - set(output ${LEONIDA_SG_DIR}/glsl/${source}.spv) - add_custom_command( - OUTPUT ${output} - COMMAND ${CMAKE_COMMAND} -E make_directory ${LEONIDA_SG_DIR}/glsl - COMMAND ${Vulkan_GLSLANG_VALIDATOR_EXECUTABLE} -V --target-env vulkan1.3 -o ${output} - ${CMAKE_CURRENT_SOURCE_DIR}/test/glsl/${source} - DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/test/glsl/${source} - COMMENT "Compiling ${source}" - VERBATIM) - list(APPEND LEONIDA_SG_INDEXES ${output}) - endforeach() - add_executable(d3d12_subgroup_test test/d3d12_subgroup_test.cpp shims/d3d12_xs_device.cpp ${LEONIDA_SG_INDEXES}) - target_link_libraries(d3d12_subgroup_test PRIVATE gta6rt_d3d12_com) - target_compile_definitions(d3d12_subgroup_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX - LEONIDA_TEST_SUBGROUP_SHADERS="${LEONIDA_SG_DIR}") - target_compile_options(d3d12_subgroup_test PRIVATE /W4 /permissive- /utf-8) - add_test(NAME d3d12_subgroup COMMAND d3d12_subgroup_test) - set_tests_properties(d3d12_subgroup PROPERTIES SKIP_RETURN_CODE 77) - else() - message(STATUS "llvm-mc (set LLVM_MC) or glslangValidator not found: d3d12_subgroup_test is not built") - endif() - - # Clears on every format class against WARP (needs a Vulkan GPU; exit 77 without one). - add_executable(d3d12_clear_formats_test test/d3d12_clear_formats_test.cpp) - target_link_libraries(d3d12_clear_formats_test PRIVATE gta6rt_d3d12_com d3d12 dxgi) - target_compile_definitions(d3d12_clear_formats_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) - target_compile_options(d3d12_clear_formats_test PRIVATE /W4 /permissive- /utf-8) - add_test(NAME d3d12_clear_formats COMMAND d3d12_clear_formats_test) - set_tests_properties(d3d12_clear_formats PROPERTIES SKIP_RETURN_CODE 77) - - # SetDescriptorHeaps validation, Reset/ClearState/bundle parity, lifetime pinning, direct-index flags. - add_executable(d3d12_set_descriptor_heaps_test test/d3d12_set_descriptor_heaps_test.cpp) - target_link_libraries(d3d12_set_descriptor_heaps_test PRIVATE gta6rt_d3d12_com d3d12 dxgi) - target_compile_definitions(d3d12_set_descriptor_heaps_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) - target_compile_options(d3d12_set_descriptor_heaps_test PRIVATE /W4 /permissive- /utf-8) - add_test(NAME d3d12_set_descriptor_heaps COMMAND d3d12_set_descriptor_heaps_test) - set_tests_properties(d3d12_set_descriptor_heaps PROPERTIES SKIP_RETURN_CODE 77 - FAIL_REGULAR_EXPRESSION "Validation Error;VUID-") - - # The loader can create this device instead of the host's (D3D12XboxCreateDevice, LEONIDA_D3D12=vulkan). - if(TARGET gta6rt) - target_link_libraries(gta6rt PRIVATE gta6rt_d3d12_com) - target_compile_definitions(gta6rt PRIVATE LEONIDA_VULKAN_DEVICE) - - # A stand-in title that imports d3d12_xs.dll!D3D12XboxCreateDevice and runs a clear and a readback on the - # device it gets, mapped and run by `gta6rt --run` with LEONIDA_D3D12=vulkan: the loader, the game thread, the - # proxies and the Vulkan device in one process. check_tiny_frame.py reads the verdict, the binding and the - # call order from outside; d3d12_com_test is its probe for "no usable Vulkan device" (exit code 77). - leonida_add_d3d12_xs_stub() - add_executable(tiny_frame test/fixtures/tiny_frame.cpp) - target_link_libraries(tiny_frame PRIVATE d3d12_xs_stub) - target_compile_definitions(tiny_frame PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) - target_compile_options(tiny_frame PRIVATE /W4 /permissive- /utf-8) - set_target_properties(tiny_frame PROPERTIES - RUNTIME_OUTPUT_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/fixtures/game/$" - ) - if(Python3_FOUND) - add_test(NAME run_tiny_frame COMMAND "${Python3_EXECUTABLE}" -I - "${CMAKE_CURRENT_SOURCE_DIR}/test/check_tiny_frame.py" "$" - "$" "--probe=$" ${_trace_runner}) - set_tests_properties(run_tiny_frame PROPERTIES SKIP_RETURN_CODE 77) - # The queue test settings are for the tests only: left set, they must not shrink the game's device. - add_test(NAME run_tiny_frame_queue_test_settings COMMAND "${Python3_EXECUTABLE}" -I - "${CMAKE_CURRENT_SOURCE_DIR}/test/check_tiny_frame.py" "$" - "$" "--probe=$" --queue-test-settings - ${_trace_runner}) - set_tests_properties(run_tiny_frame_queue_test_settings PROPERTIES SKIP_RETURN_CODE 77) - endif() - endif() - - # M1.5 as a `gta6rt --run` guest: test/d3d12_translated_draw_test.cpp built again with LEONIDA_M15_GUEST as - # tiny_guest_draw.exe, whose only device is the D3D12XboxCreateDevice it imports from d3d12_xs.dll. The import - # library comes from a failing stub built into fixtures/stubs, away from the guest, so only gta6rt's shim registry - # can answer it. The guest links nothing from src/ or shims/ and can be - # copied with its ordinary CRT dependencies, given the m15 folder as its argument. test/run_guest_draw.cmake checks the exit code and the marker line. - # Opt-in: it needs a Vulkan GPU and the guest cannot tell a missing one from a bug, so default runs are unchanged. - option(LEONIDA_TEST_GUEST_DRAW - "Build tiny_guest_draw.exe and run the M1.5 draw through gta6rt --run (needs a Vulkan GPU)" OFF) - option(LEONIDA_GUEST_SCENE "Build the headless 600-frame synthetic guest test (requires static SDL3)" OFF) - if(LEONIDA_TEST_GUEST_DRAW OR LEONIDA_GUEST_SCENE) - # The import stub is shared with the tiny_frame clear/readback guest. - leonida_add_d3d12_xs_stub() - add_executable(tiny_guest_draw test/d3d12_translated_draw_test.cpp) - target_link_libraries(tiny_guest_draw PRIVATE d3d12_xs_stub Vulkan::Headers) - target_compile_definitions(tiny_guest_draw PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX LEONIDA_M15_GUEST) - target_compile_options(tiny_guest_draw PRIVATE /W4 /permissive- /utf-8) - set_target_properties(tiny_guest_draw PROPERTIES - OUTPUT_NAME tiny_guest_draw - RUNTIME_OUTPUT_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/fixtures/guest_draw/$" - ) - if(LEONIDA_GUEST_SCENE) - if(NOT TARGET gta6rt OR NOT TARGET SDL3::SDL3-static OR NOT LEONIDA_SDL3) - message(FATAL_ERROR "LEONIDA_GUEST_SCENE requires static SDL3; configure SDL3_DIR or LEONIDA_SDL3_FETCH") - endif() - target_compile_definitions(tiny_guest_draw PRIVATE LEONIDA_GUEST_SCENE) - target_sources(gta6rt PRIVATE test/scene_input_driver.cpp) - endif() - # This guest can use a synthetic fixture produced on another machine. Register the automated test - # if the tools to generate the fixture are available locally. - if(CMAKE_HOST_WIN32 AND NOT CMAKE_CROSSCOMPILING AND TARGET d3d12_translated_draw_test AND TARGET gta6rt) - add_dependencies(tiny_guest_draw d3d12_translated_draw_test gta6rt) - add_test(NAME d3d12_translated_draw_guest - COMMAND ${CMAKE_COMMAND} -DGTA6RT=$ -DGUEST=$ - -DFIXTURE=${LEONIDA_M15_DIR} -P ${CMAKE_CURRENT_SOURCE_DIR}/test/run_guest_draw.cmake) - set_tests_properties(d3d12_translated_draw_guest PROPERTIES TIMEOUT 180) - else() - message(STATUS "tiny_guest_draw will build. For an external synthetic M1.5 fixture or Wine run see runtime/README.md.") - endif() - if(LEONIDA_GUEST_SCENE AND Python3_Interpreter_FOUND AND TARGET d3d12_translated_draw_test) - set(_scene_wine_args) - if(CMAKE_CROSSCOMPILING AND CMAKE_CROSSCOMPILING_EMULATOR) - set(_scene_emulator ${CMAKE_CROSSCOMPILING_EMULATOR}) - list(POP_FRONT _scene_emulator _scene_launcher) - list(APPEND _scene_wine_args "--wine=${_scene_launcher}") - foreach(_arg IN LISTS _scene_emulator) - list(APPEND _scene_wine_args "--wine-arg=${_arg}") - endforeach() - add_dependencies(tiny_guest_draw d3d12_translated_draw_test gta6rt) - endif() - if((CMAKE_HOST_WIN32 AND NOT CMAKE_CROSSCOMPILING) OR _scene_wine_args) - add_test(NAME d3d12_guest_scene - COMMAND "${Python3_EXECUTABLE}" -I "${CMAKE_CURRENT_SOURCE_DIR}/../scripts/run_guest_scene.py" - --loader $ --guest $ - --shaders "${LEONIDA_M15_DIR}" --negative-controls ${_scene_wine_args}) - set_tests_properties(d3d12_guest_scene PROPERTIES TIMEOUT 900) - endif() - endif() - endif() - # bvh_builder_test can put the package's XboxBvhBuilder on this device too (LEONIDA_BVH_DEVICE=vulkan). - if(TARGET bvh_builder_test) - target_link_libraries(bvh_builder_test PRIVATE gta6rt_d3d12_com) - target_compile_definitions(bvh_builder_test PRIVATE LEONIDA_VULKAN_DEVICE) - endif() - # fsr_dispatch_test can put the package's FidelityFX DLL on this device too (LEONIDA_FSR_DEVICE=vulkan). - if(TARGET fsr_dispatch_test) - target_link_libraries(fsr_dispatch_test PRIVATE gta6rt_d3d12_com) - target_compile_definitions(fsr_dispatch_test PRIVATE LEONIDA_VULKAN_DEVICE) - endif() -elseif(TARGET gta6rt) - message(STATUS "Python 3 or d3d12.h missing: the D3D12 COM objects and d3d12_com_test are not built") -endif() diff --git a/runtime/cmake/fixtures.cmake b/runtime/cmake/fixtures.cmake deleted file mode 100644 index 9ac19f476..000000000 --- a/runtime/cmake/fixtures.cmake +++ /dev/null @@ -1,23 +0,0 @@ -# Test fixtures that more than one part of the build needs. - -# d3d12_xs_stub: d3d12_xs.dll with an import library, for the stand-in titles that import -# d3d12_xs.dll!D3D12XboxCreateDevice (tiny_frame, tiny_guest_draw). It is built into fixtures/stubs, away from the -# guests, so at run time only gta6rt's shim registry can answer the import. Callable from any directory; the target -# is created by the first call. -function(leonida_add_d3d12_xs_stub) - if(TARGET d3d12_xs_stub) - return() - endif() - add_library(d3d12_xs_stub SHARED - "${PROJECT_SOURCE_DIR}/test/fixtures/d3d12_xs_stub.cpp" - "${PROJECT_SOURCE_DIR}/test/fixtures/d3d12_xs_stub.def" - ) - target_compile_definitions(d3d12_xs_stub PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) - target_compile_options(d3d12_xs_stub PRIVATE /W4 /permissive- /utf-8) - set_target_properties(d3d12_xs_stub PROPERTIES - OUTPUT_NAME d3d12_xs - PREFIX "" - RUNTIME_OUTPUT_DIRECTORY "${PROJECT_BINARY_DIR}/fixtures/stubs/$" - ARCHIVE_OUTPUT_DIRECTORY "${PROJECT_BINARY_DIR}/fixtures/stubs/$" - ) -endfunction() diff --git a/runtime/cmake/runtime_tests.cmake b/runtime/cmake/runtime_tests.cmake deleted file mode 100644 index 85c0738ea..000000000 --- a/runtime/cmake/runtime_tests.cmake +++ /dev/null @@ -1,834 +0,0 @@ -# Tests that need no Vulkan headers: the CPU-only test programs, the stand-in titles and DLLs (tiny_*) that gta6rt -# maps, and the add_test() calls for the shim test programs of windows_runtime.cmake. -# Included by runtime/CMakeLists.txt inside if(BUILD_TESTING). - -add_executable(gfx10_tiling_test test/gfx10_tiling_test.cpp) -add_test(NAME gfx10_tiling COMMAND gfx10_tiling_test) - -add_executable(retire_tickets_test test/retire_tickets_test.cpp) -add_test(NAME retire_tickets COMMAND retire_tickets_test) -# VulkanContext::buffer_at's VA index (runtime/src/buffer_va_index.h): pure stdlib, no Vulkan instance. -add_executable(buffer_va_index_test test/buffer_va_index_test.cpp) -add_test(NAME buffer_va_index COMMAND buffer_va_index_test) - -add_executable(xbox_present_readback_size_test test/xbox_present_readback_size_test.cpp) -add_test(NAME xbox_present_readback_size COMMAND xbox_present_readback_size_test) - -add_executable(pipeline_cache_file_test test/pipeline_cache_file_test.cpp) -add_test(NAME pipeline_cache_file COMMAND pipeline_cache_file_test) - -add_executable(xdxr_build_output_test test/xdxr_build_output_test.cpp) -add_test(NAME xdxr_build_output COMMAND xdxr_build_output_test) - -# vk_pipeline_check's memory budget for large modules: pure stdlib, no Vulkan device. -add_executable(large_module_gate_test test/large_module_gate_test.cpp) -find_package(Threads REQUIRED) -target_link_libraries(large_module_gate_test PRIVATE Threads::Threads) -add_test(NAME large_module_gate COMMAND large_module_gate_test) -# vk_pipeline_check's isolate summary stage set: pure stdlib, no Vulkan device. -add_executable(pipeline_summary_test test/pipeline_summary_test.cpp) -add_test(NAME pipeline_summary COMMAND pipeline_summary_test) -# XDXR build descriptions (docs/xdxr.md); compared with d3d12.h where the Windows SDK provides it. -add_executable(xdxr_descs_test test/xdxr_descs_test.cpp) -add_test(NAME xdxr_descs COMMAND xdxr_descs_test) -# LEONIDA_VK_DEVICE name matching (runtime/src/vulkan_device_filter.h): pure stdlib, no Vulkan instance. -add_executable(vulkan_device_filter_test test/vulkan_device_filter_test.cpp) -target_include_directories(vulkan_device_filter_test PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/src) -add_test(NAME vulkan_device_filter COMMAND vulkan_device_filter_test) -add_executable(vk_presenter_capture_colour_test test/vk_presenter_capture_colour_test.cpp) -add_test(NAME vk_presenter_capture_colour COMMAND vk_presenter_capture_colour_test) -if(TARGET gta6rt) - if(CMAKE_CXX_COMPILER_ID STREQUAL "MSVC") - add_executable(cpp_unwind_test test/cpp_unwind_test.cpp) - add_test(NAME cpp_unwind COMMAND cpp_unwind_test) - endif() - - # Compile-time ABI checks (D3D12/XMem structure sizes, alignments and member offsets against the Windows SDK). - # The file existed but no target built it, so none of its static_asserts ever ran. - add_executable(runtime_types_test test/test_runtime_types.cpp) - target_include_directories(runtime_types_test PRIVATE - ${CMAKE_CURRENT_SOURCE_DIR}/src ${CMAKE_CURRENT_SOURCE_DIR}/shims) - add_test(NAME runtime_types COMMAND runtime_types_test) - - # Loader tests. They build their own PE images, so they need neither the game nor any other input. - add_executable(loader_test - test/loader_test.cpp - src/pe_loader.cpp - shims/registry.cpp - ) - target_compile_definitions(loader_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX UNICODE _UNICODE) - target_compile_options(loader_test PRIVATE /W4 /permissive- /utf-8 /EHsc) - target_link_options(loader_test PRIVATE /OPT:NOREF ${GTA6RT_HOST_BASE}) - add_dependencies(loader_test gta6rt_tls_host) - add_test(NAME loader COMMAND loader_test) - # PE loader tests use two locally built fixtures: a DLL with exports, imports and relocations, and an EXE that - # imports it so Loader::load exercises recursive module loading. They contain no game data. - set(TINY_FIXTURE_DIR "${CMAKE_CURRENT_BINARY_DIR}/fixtures/$") - - add_library(tiny_dll SHARED test/fixtures/tiny_dll.cpp) - target_compile_definitions(tiny_dll PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) - target_compile_options(tiny_dll PRIVATE /W4 /permissive- /utf-8 /GS-) - # tiny_fault_caught faults inside its own __try. MSVC always catches that; clang-cl only with asynchronous - # exceptions, otherwise the access violation escapes and the unwind-registration check fails. - target_compile_options(tiny_dll PRIVATE $<$:/EHa>) - set_target_properties(tiny_dll PROPERTIES - OUTPUT_NAME tiny_dll - PREFIX "" - RUNTIME_OUTPUT_DIRECTORY "${TINY_FIXTURE_DIR}" - ARCHIVE_OUTPUT_DIRECTORY "${TINY_FIXTURE_DIR}" - MSVC_RUNTIME_LIBRARY "MultiThreaded$<$:Debug>" - ) - - add_executable(tiny_exe test/fixtures/tiny_exe.cpp) - target_link_libraries(tiny_exe PRIVATE tiny_dll) - target_compile_definitions(tiny_exe PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) - target_compile_options(tiny_exe PRIVATE /W4 /permissive- /utf-8 /GS-) - set_target_properties(tiny_exe PROPERTIES - OUTPUT_NAME tiny_exe - RUNTIME_OUTPUT_DIRECTORY "${TINY_FIXTURE_DIR}" - MSVC_RUNTIME_LIBRARY "MultiThreaded$<$:Debug>" - ) - - # An EXE built with /GA reads its TLS at index 0 without _tls_index; loader_tls_test maps it and reads it from - # threads that existed before load() and from ones that did not. - add_executable(tiny_ga_tls test/fixtures/tiny_ga_tls.cpp) - target_compile_definitions(tiny_ga_tls PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) - target_compile_options(tiny_ga_tls PRIVATE /W4 /permissive- /utf-8 /GS- /GA) - set_target_properties(tiny_ga_tls PROPERTIES - OUTPUT_NAME tiny_ga_tls - RUNTIME_OUTPUT_DIRECTORY "${TINY_FIXTURE_DIR}" - MSVC_RUNTIME_LIBRARY "MultiThreaded$<$:Debug>" - ) - - add_executable(module_names_test test/module_names_test.cpp src/pe_loader.cpp shims/registry.cpp) - target_include_directories(module_names_test PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/src) - target_compile_definitions(module_names_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) - target_compile_options(module_names_test PRIVATE /W4 /permissive- /utf-8 /EHsc) - target_link_options(module_names_test PRIVATE /OPT:NOREF) - add_dependencies(module_names_test gta6rt_tls_host tiny_dll) - add_test(NAME module_names COMMAND module_names_test "$") - - add_executable(tiny_module_names test/fixtures/tiny_module_names.cpp) - target_compile_definitions(tiny_module_names PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) - target_compile_options(tiny_module_names PRIVATE /W4 /permissive- /utf-8 /EHsc) - set_target_properties(tiny_module_names PROPERTIES RUNTIME_OUTPUT_DIRECTORY "${TINY_FIXTURE_DIR}") - - # Native Windows and --dry-run/--init/--run share original renamed fixtures, including an ACP-named import. - if(NOT CMAKE_CROSSCOMPILING) - find_package(Python3 COMPONENTS Interpreter QUIET) - if(Python3_FOUND) - add_test(NAME run_module_names COMMAND "${Python3_EXECUTABLE}" -I - "${CMAKE_CURRENT_SOURCE_DIR}/test/check_module_names.py" - "--loader=$" "--guest=$" - "--importer=$" "--dependency=$" - "--work-dir=${CMAKE_CURRENT_BINARY_DIR}" - "--report=${CMAKE_CURRENT_BINARY_DIR}/module-names-results.json") - set_tests_properties(run_module_names PROPERTIES TIMEOUT 90) - endif() - endif() - - # pe_loader.cpp needs the shim registry for shims::find/make_unimplemented_thunk. The xmem and d3d12_xs tables - # are linked too so the optional LEONIDA_GAME_DIR run classifies the shipped modules' imports exactly like - # gta6rt does (no d3d12.lib is needed: d3d12_xs resolves its host entry points at run time). - add_executable(pe_loader_test - test/pe_loader_test.cpp - src/pe_loader.cpp - shims/registry.cpp - shims/xmem.cpp - shims/d3d12_xs.cpp - shims/d3d12_xs_device.cpp - ) - target_include_directories(pe_loader_test PRIVATE - ${CMAKE_CURRENT_SOURCE_DIR}/src - ${CMAKE_CURRENT_SOURCE_DIR}/shims - ) - target_compile_definitions(pe_loader_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) - target_compile_options(pe_loader_test PRIVATE /W4 /permissive- /utf-8 /EHsc) - target_link_options(pe_loader_test PRIVATE /OPT:NOREF) - target_link_libraries(pe_loader_test PRIVATE gta6rt_d3d12_xs_rootsig psapi) - add_dependencies(pe_loader_test tiny_dll tiny_exe gta6rt_tls_host) - - # `gta6rt --run` rehearsal: a stand-in game EXE (CRT startup, statics, heap, files, threads) that imports - # xgameruntime.dll from a link-time stub; under --run the shim registry answers those imports instead. - add_library(xgameruntime_stub SHARED test/fixtures/xgameruntime_stub.cpp test/fixtures/xgameruntime_stub.def) - target_include_directories(xgameruntime_stub PUBLIC ${XTASKQUEUE_DIR}/Include) - target_compile_definitions(xgameruntime_stub PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) - set_target_properties(xgameruntime_stub PROPERTIES - OUTPUT_NAME xgameruntime - PREFIX "" - RUNTIME_OUTPUT_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/fixtures/game/$" - ARCHIVE_OUTPUT_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/fixtures/game/$" - ) - add_executable(tiny_async test/fixtures/tiny_async.cpp) - target_link_libraries(tiny_async PRIVATE xgameruntime_stub) - set_target_properties(tiny_async PROPERTIES - RUNTIME_OUTPUT_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/fixtures/game/$" - ) - # Reaches xgameruntime.dll through LoadLibraryW/GetProcAddress, as xgameruntime.lib's thunks do (no import). - add_executable(tiny_gdk_load test/fixtures/tiny_gdk_load.cpp) - target_compile_definitions(tiny_gdk_load PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) - target_compile_options(tiny_gdk_load PRIVATE /W4 /permissive- /utf-8) - set_target_properties(tiny_gdk_load PROPERTIES - RUNTIME_OUTPUT_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/fixtures/game/$" - ) - # Run-time LoadLibrary of a bundled Xbox DLL (importing xmem.dll) through rt::Loader. - add_library(xmem_stub SHARED test/fixtures/xmem_stub.cpp test/fixtures/xmem_stub.def) - target_compile_definitions(xmem_stub PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) - target_compile_options(xmem_stub PRIVATE /W4 /permissive- /utf-8) - set_target_properties(xmem_stub PROPERTIES - OUTPUT_NAME xmem - PREFIX "" - RUNTIME_OUTPUT_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/fixtures/stubs/$" - ARCHIVE_OUTPUT_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/fixtures/stubs/$" - ) - add_library(tiny_bundled_dll SHARED test/fixtures/tiny_bundled_dll.cpp test/fixtures/tiny_bundled_dll.def) - target_link_libraries(tiny_bundled_dll PRIVATE xmem_stub) - target_compile_definitions(tiny_bundled_dll PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) - target_compile_options(tiny_bundled_dll PRIVATE /W4 /permissive- /utf-8) - set_target_properties(tiny_bundled_dll PROPERTIES - OUTPUT_NAME tiny_bundled_dll - PREFIX "" - RUNTIME_OUTPUT_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/fixtures/game/$" - ARCHIVE_OUTPUT_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/fixtures/stubs/$" - ) - add_executable(tiny_bundled_load test/fixtures/tiny_bundled_load.cpp) - target_compile_definitions(tiny_bundled_load PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) - target_compile_options(tiny_bundled_load PRIVATE /W4 /permissive- /utf-8) - add_dependencies(tiny_bundled_load tiny_bundled_dll) - set_target_properties(tiny_bundled_load PROPERTIES - RUNTIME_OUTPUT_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/fixtures/game/$" - ) - add_library(tiny_startup_cmdline_dll SHARED test/fixtures/tiny_startup_cmdline.cpp) - target_compile_definitions(tiny_startup_cmdline_dll PRIVATE STARTUP_CMDLINE_DLL) - add_executable(tiny_startup_cmdline test/fixtures/tiny_startup_cmdline.cpp) - target_link_libraries(tiny_startup_cmdline PRIVATE tiny_startup_cmdline_dll) - foreach(target tiny_startup_cmdline_dll tiny_startup_cmdline) - target_compile_definitions(${target} PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) - target_compile_options(${target} PRIVATE /W4 /permissive- /utf-8) - set_target_properties(${target} PROPERTIES - PREFIX "" - RUNTIME_OUTPUT_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/fixtures/game/$" - ) - endforeach() - # These linker-selected startup modes are specific to the MSVC CRT. - if(MSVC) - foreach(width a w) - foreach(mode default expand noargs) - set(target tiny_argv_${mode}_${width}) - add_executable(${target} test/fixtures/tiny_argv_modes.cpp) - target_compile_definitions(${target} PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) - target_compile_options(${target} PRIVATE /W4 /permissive- /utf-8) - if(width STREQUAL "w") - target_compile_definitions(${target} PRIVATE APP_WIDE) - endif() - if(mode STREQUAL "expand") - if(width STREQUAL "w") - target_link_options(${target} PRIVATE wsetargv.obj) - else() - target_link_options(${target} PRIVATE setargv.obj) - endif() - elseif(mode STREQUAL "noargs") - target_link_options(${target} PRIVATE noarg.obj) - endif() - set_target_properties(${target} PROPERTIES - RUNTIME_OUTPUT_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/fixtures/game/$") - endforeach() - endforeach() - endif() - add_executable(tiny_atexit test/fixtures/tiny_atexit.cpp) - target_compile_definitions(tiny_atexit PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) - target_compile_options(tiny_atexit PRIVATE /W4 /permissive- /utf-8) - set_target_properties(tiny_atexit PROPERTIES - RUNTIME_OUTPUT_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/fixtures/game/$" - ) - add_executable(tiny_game test/fixtures/tiny_game.cpp) - target_link_libraries(tiny_game PRIVATE xgameruntime_stub) - target_compile_definitions(tiny_game PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX _CRT_SECURE_NO_WARNINGS) # plain fopen, as games use - target_compile_options(tiny_game PRIVATE /W4 /permissive- /utf-8 /EHsc) - set_target_properties(tiny_game PROPERTIES - RUNTIME_OUTPUT_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/fixtures/game/$" - ) - # The same game with no .reloc, at the default EXE base, as RT-22 asks about the real one: it can only run at - # 0x140000000, which arm64 Wine on macOS uses for itself (src/base_reservation.h). - add_executable(tiny_game_fixed test/fixtures/tiny_game.cpp) - target_link_libraries(tiny_game_fixed PRIVATE xgameruntime_stub) - target_compile_definitions(tiny_game_fixed PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX _CRT_SECURE_NO_WARNINGS) - target_compile_options(tiny_game_fixed PRIVATE /W4 /permissive- /utf-8 /EHsc) - target_link_options(tiny_game_fixed PRIVATE /FIXED /DYNAMICBASE:NO /BASE:0x140000000) - set_target_properties(tiny_game_fixed PROPERTIES - RUNTIME_OUTPUT_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/fixtures/game/$" - ) - add_executable(tiny_game_exit_code_test test/tiny_game_exit_code_test.cpp) - target_compile_definitions(tiny_game_exit_code_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) - target_compile_options(tiny_game_exit_code_test PRIVATE /W4 /permissive- /utf-8) - add_dependencies(tiny_game_exit_code_test gta6rt tiny_game tiny_game_fixed) - # abort() must reach the guest's SIGABRT handler before the run ends with the CRT's abort code (3). - add_executable(tiny_game_abort_test test/tiny_game_abort_test.cpp) - target_compile_definitions(tiny_game_abort_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) - target_compile_options(tiny_game_abort_test PRIVATE /W4 /permissive- /utf-8) - add_dependencies(tiny_game_abort_test gta6rt tiny_game) - add_test(NAME pe_loader COMMAND pe_loader_test "$" "$") - - # Synthetic, hand-built images through Loader::load: range checks, wrapping RVAs, import-table termination and - # base relocations (HIGHLOW included). No fixture DLL is needed; the images are written to a temporary folder. - add_executable(test_pe_loader_bounds - test/test_pe_loader_bounds.cpp - src/pe_loader.cpp - shims/registry.cpp - shims/xmem.cpp - shims/d3d12_xs.cpp - shims/d3d12_xs_device.cpp - ) - target_include_directories(test_pe_loader_bounds PRIVATE - ${CMAKE_CURRENT_SOURCE_DIR}/src - ${CMAKE_CURRENT_SOURCE_DIR}/shims - ) - target_compile_definitions(test_pe_loader_bounds PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) - target_compile_options(test_pe_loader_bounds PRIVATE /W4 /permissive- /utf-8 /EHsc) - target_link_options(test_pe_loader_bounds PRIVATE /OPT:NOREF ${GTA6RT_HOST_BASE}) - target_link_libraries(test_pe_loader_bounds PRIVATE gta6rt_d3d12_xs_rootsig psapi) - add_dependencies(test_pe_loader_bounds gta6rt_tls_host) - add_test(NAME pe_loader_bounds COMMAND test_pe_loader_bounds) - - # RT-388: a deterministic mutation fuzzer over synthetic images through Loader::load (test/pe_loader_fuzz.cpp). - # ctest runs a fixed seed and case count; docs/testing.md has the long runs. With LEONIDA_LOADER_FUZZ_ASAN the - # fuzzer and the loader sources it compiles are built with AddressSanitizer (use RelWithDebInfo or Release: - # /fsanitize=address does not combine with the /RTC1 of a Debug build). - option(LEONIDA_LOADER_FUZZ_ASAN "Build pe_loader_fuzz with AddressSanitizer" OFF) - add_executable(pe_loader_fuzz - test/pe_loader_fuzz.cpp - src/pe_loader.cpp - shims/registry.cpp - shims/xmem.cpp - shims/d3d12_xs.cpp - shims/d3d12_xs_device.cpp - ) - target_include_directories(pe_loader_fuzz PRIVATE - ${CMAKE_CURRENT_SOURCE_DIR}/src - ${CMAKE_CURRENT_SOURCE_DIR}/shims - ) - target_compile_definitions(pe_loader_fuzz PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) - target_compile_options(pe_loader_fuzz PRIVATE /W4 /permissive- /utf-8 /EHsc) - target_link_options(pe_loader_fuzz PRIVATE /OPT:NOREF ${GTA6RT_HOST_BASE}) - target_link_libraries(pe_loader_fuzz PRIVATE gta6rt_d3d12_xs_rootsig psapi) - add_dependencies(pe_loader_fuzz gta6rt_tls_host) - if(LEONIDA_LOADER_FUZZ_ASAN) - target_compile_options(pe_loader_fuzz PRIVATE /fsanitize=address /Zi) - target_link_options(pe_loader_fuzz PRIVATE /INCREMENTAL:NO /DEBUG) - # No STL container annotations: they need stl_asan.lib from the VS component, and the libraries linked here - # are built without ASan, so the annotate_string/annotate_vector /FAILIFMISMATCH keys must stay as theirs. - target_compile_definitions(pe_loader_fuzz PRIVATE _DISABLE_STRING_ANNOTATION _DISABLE_VECTOR_ANNOTATION) - # The ASan runtime: next to cl.exe for MSVC (the VS "C++ AddressSanitizer" component), under the resource - # directory for clang-cl. Its objects name the runtime libraries; the folder goes on the library path, and the - # DLL is copied beside the test so it runs without a Developer prompt or a PATH change. - get_filename_component(_leonida_cc_dir "${CMAKE_CXX_COMPILER}" DIRECTORY) - file(GLOB _leonida_asan_dll - "${_leonida_cc_dir}/clang_rt.asan_dynamic-x86_64.dll" - "${_leonida_cc_dir}/../lib/clang/*/lib/windows/clang_rt.asan_dynamic-x86_64.dll") - if(_leonida_asan_dll) - list(GET _leonida_asan_dll 0 _leonida_asan_dll) - get_filename_component(_leonida_asan_dir "${_leonida_asan_dll}" DIRECTORY) - target_link_directories(pe_loader_fuzz PRIVATE "${_leonida_asan_dir}") - if(CMAKE_CXX_COMPILER_ID STREQUAL "Clang") - # clang-cl 23's stack-use-after-return frames break MSVC C++ exception dispatch at /O2: a rethrow faults - # in vcruntime's _C_specific_handler_noexcept (a five-line try/throw/catch does it). Without them it works. - target_compile_options(pe_loader_fuzz PRIVATE -fsanitize-address-use-after-return=never) - # clang-cl names these only when it runs the link itself; CMake calls the linker directly. - target_link_options(pe_loader_fuzz PRIVATE clang_rt.asan_dynamic-x86_64.lib - /wholearchive:clang_rt.asan_dynamic_runtime_thunk-x86_64.lib) - endif() - add_custom_command(TARGET pe_loader_fuzz POST_BUILD - COMMAND ${CMAKE_COMMAND} -E copy_if_different "${_leonida_asan_dll}" "$") - else() - message(WARNING "LEONIDA_LOADER_FUZZ_ASAN: no clang_rt.asan_dynamic-x86_64.dll beside ${CMAKE_CXX_COMPILER}") - endif() - endif() - add_test(NAME pe_loader_fuzz COMMAND pe_loader_fuzz --quiet) - - # Static TLS fixture: a DLL with __declspec(thread) and a TLS callback. It is ordinary test code; no game data - # is involved. loader_tls_test needs gta6rt_tls_host.dll next to its own EXE, because that is where - # Loader::initialize_tls looks for the reserved module TLS index. - add_library(tiny_tls SHARED test/fixtures/tiny_tls.cpp) - target_compile_definitions(tiny_tls PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) - target_compile_options(tiny_tls PRIVATE /W4 /permissive- /utf-8 /GS-) - set_target_properties(tiny_tls PROPERTIES - OUTPUT_NAME tiny_tls - PREFIX "" - RUNTIME_OUTPUT_DIRECTORY "${TINY_FIXTURE_DIR}" - ARCHIVE_OUTPUT_DIRECTORY "${TINY_FIXTURE_DIR}" - ) - - add_library(tiny_tls_cb_only SHARED test/fixtures/tiny_tls_cb_only.cpp) - target_compile_definitions(tiny_tls_cb_only PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) - target_compile_options(tiny_tls_cb_only PRIVATE /W4 /permissive- /utf-8 /GS-) - target_link_options(tiny_tls_cb_only PRIVATE /NODEFAULTLIB /ENTRY:DllMainCRTStartup) - target_link_libraries(tiny_tls_cb_only PRIVATE kernel32) - set_target_properties(tiny_tls_cb_only PROPERTIES - OUTPUT_NAME tiny_tls_cb_only - PREFIX "" - RUNTIME_OUTPUT_DIRECTORY "${TINY_FIXTURE_DIR}" - ARCHIVE_OUTPUT_DIRECTORY "${TINY_FIXTURE_DIR}" - ) - - # pe_loader.cpp needs the shim registry for shims::find/make_unimplemented_thunk. The fixtures import only host - # DLLs, so no shim tables are linked. - add_executable(loader_tls_test - test/loader_tls_test.cpp - src/pe_loader.cpp - shims/registry.cpp - ) - target_include_directories(loader_tls_test PRIVATE - ${CMAKE_CURRENT_SOURCE_DIR}/src - ) - target_compile_definitions(loader_tls_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) - target_compile_options(loader_tls_test PRIVATE /W4 /permissive- /utf-8 /EHsc) - add_dependencies(loader_tls_test tiny_tls tiny_tls_cb_only tiny_ga_tls gta6rt_tls_host) - add_test(NAME loader_tls - COMMAND loader_tls_test "$" - ) - - # DisableThreadLibraryCalls from a mapped DllMain (shims/library_loader.cpp). The fixture is built without the CRT, so - # DllMain's only work is that one call. No game files. - add_library(dll_thread_calls SHARED test/fixtures/dll_thread_calls.cpp) - target_compile_options(dll_thread_calls PRIVATE /W4 /permissive- /utf-8 /GS-) - target_link_options(dll_thread_calls PRIVATE /NODEFAULTLIB /ENTRY:dll_thread_calls_main) - target_link_libraries(dll_thread_calls PRIVATE kernel32) - set_target_properties(dll_thread_calls PROPERTIES - OUTPUT_NAME dll_thread_calls - PREFIX "" - RUNTIME_OUTPUT_DIRECTORY "${TINY_FIXTURE_DIR}" - ARCHIVE_OUTPUT_DIRECTORY "${TINY_FIXTURE_DIR}" - ) - add_executable(dll_thread_calls_test - test/dll_thread_calls_test.cpp - src/pe_loader.cpp - shims/library_loader.cpp - shims/registry.cpp - shims/xmem.cpp - ) - target_include_directories(dll_thread_calls_test PRIVATE - ${CMAKE_CURRENT_SOURCE_DIR}/src - ${CMAKE_CURRENT_SOURCE_DIR}/shims - ) - target_compile_definitions(dll_thread_calls_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) - target_compile_options(dll_thread_calls_test PRIVATE /W4 /permissive- /utf-8 /EHsc) - target_link_options(dll_thread_calls_test PRIVATE /OPT:NOREF) - target_link_libraries(dll_thread_calls_test PRIVATE psapi) - add_dependencies(dll_thread_calls_test dll_thread_calls) - add_test(NAME dll_thread_calls - COMMAND dll_thread_calls_test "$" - ) - - # The host GameInput path (docs/gameinput.md): mapped code that imports GameInputCreate from GameInput.dll, with no - # GameInput shim linked. Needs the SDK's gameinput.lib and GameInput.h to build the fixture, and a GameInput.dll on - # the machine to run (the test skips with 77 only when Windows cannot load GameInput.dll). No game files. - find_library(GAMEINPUT_LIBRARY NAMES gameinput HINTS ${_sdk_lib_hints}) - if(GAMEINPUT_LIBRARY) - add_library(gameinput_host SHARED test/fixtures/gameinput_host.cpp) - target_compile_options(gameinput_host PRIVATE /W4 /permissive- /utf-8 /GS-) - target_link_options(gameinput_host PRIVATE /NODEFAULTLIB /ENTRY:gameinput_host_main) - target_link_libraries(gameinput_host PRIVATE kernel32 ${GAMEINPUT_LIBRARY}) - set_target_properties(gameinput_host PROPERTIES - OUTPUT_NAME gameinput_host - PREFIX "" - RUNTIME_OUTPUT_DIRECTORY "${TINY_FIXTURE_DIR}" - ARCHIVE_OUTPUT_DIRECTORY "${TINY_FIXTURE_DIR}" - ) - add_executable(gameinput_host_test - test/gameinput_host_test.cpp - src/pe_loader.cpp - shims/registry.cpp - ) - target_include_directories(gameinput_host_test PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/src) - target_compile_definitions(gameinput_host_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) - target_compile_options(gameinput_host_test PRIVATE /W4 /permissive- /utf-8 /EHsc) - add_dependencies(gameinput_host_test gameinput_host) - add_test(NAME gameinput_host COMMAND gameinput_host_test "$") - set_tests_properties(gameinput_host PROPERTIES SKIP_RETURN_CODE 77) # Windows cannot load GameInput.dll - endif() - - # LEONIDA_UNIMPLEMENTED=log|fail|stop: builds its own image with two imports that bind to nothing, calls them in - # process (log, fail) and in child processes (default/env parsing, stop). No game files, no GPU. - add_executable(unimplemented_policy_test - test/unimplemented_policy_test.cpp - src/pe_loader.cpp - shims/registry.cpp - ) - # The register-preservation check needs a caller that sets rbx/rbp/rdi/rsi/r12-r15 and xmm6-15, which MSVC x64 - # cannot do inline: test/fixtures/abi_probe.asm (MASM). Without ml64 the rest of the test still runs. - # Visual Studio locates cl.exe without adding its directory to PATH. - # Keep looking for ml64 specifically so Ninja cannot select the 32-bit assembler. - get_filename_component(_gta6rt_compiler_bin "${CMAKE_CXX_COMPILER}" DIRECTORY) - find_program(LEONIDA_ML64 NAMES ml64 HINTS "${_gta6rt_compiler_bin}") - if(LEONIDA_ML64) - set(CMAKE_ASM_MASM_COMPILER "${LEONIDA_ML64}") - enable_language(ASM_MASM) - target_sources(unimplemented_policy_test PRIVATE test/fixtures/abi_probe.asm) - target_compile_definitions(unimplemented_policy_test PRIVATE LEONIDA_HAVE_ABI_PROBE=1) - else() - message(STATUS "ml64 not found: unimplemented_policy_test skips the register-preservation check") - endif() - target_include_directories(unimplemented_policy_test PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/src) - target_compile_definitions(unimplemented_policy_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX UNICODE _UNICODE _CRT_SECURE_NO_WARNINGS) - target_compile_options(unimplemented_policy_test PRIVATE $<$:/W4 /permissive- /utf-8 /EHsc>) - target_link_options(unimplemented_policy_test PRIVATE /OPT:NOREF) - add_dependencies(unimplemented_policy_test gta6rt_tls_host) - add_test(NAME unimplemented_policy COMMAND unimplemented_policy_test) - - # gta6rt --trace FILE (shims/startup_trace.h): a synthetic image with an unimplemented import, an - # OutputDebugStringA call and a read of address 0; checks the JSON lines. No game files, no GPU. - add_executable(startup_trace_test - test/startup_trace_test.cpp - src/pe_loader.cpp - shims/registry.cpp - ) - target_include_directories(startup_trace_test PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/src) - target_compile_definitions(startup_trace_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX UNICODE _UNICODE _CRT_SECURE_NO_WARNINGS) - target_compile_options(startup_trace_test PRIVATE /W4 /permissive- /utf-8 /EHsc) - target_link_options(startup_trace_test PRIVATE /OPT:NOREF) - add_dependencies(startup_trace_test gta6rt_tls_host) - add_test(NAME startup_trace COMMAND startup_trace_test) -endif() - -if(TARGET device_proxy_test) - add_test(NAME device_proxy COMMAND device_proxy_test) - set_tests_properties(device_proxy PROPERTIES SKIP_RETURN_CODE 77) # no WARP adapter (Wine) - # With --trace-d3d12 the 24 D3D12XboxCreateDevice parameter words still print (docs/boot.md, question 1), - # and the line with run-specific pointers does not. - add_test(NAME device_proxy_trace COMMAND device_proxy_test --trace-d3d12) - set_tests_properties(device_proxy_trace PROPERTIES SKIP_RETURN_CODE 77 - PASS_REGULAR_EXPRESSION "D3D12XboxCreateDevice params\\[24\\] =1234abcd" - FAIL_REGULAR_EXPRESSION "FAIL;D3D12XboxCreateDevice adapter=") -endif() -if(TARGET xs_proxy_mock_test) - add_test(NAME xs_proxy_mock COMMAND xs_proxy_mock_test) - # The guard region's setup failing (one process each: the tables are built once per process). - add_test(NAME xs_proxy_mock_no_reserve COMMAND xs_proxy_mock_test --fail-virtualalloc) - add_test(NAME xs_proxy_mock_no_protect COMMAND xs_proxy_mock_test --fail-virtualprotect) - add_test(NAME xs_proxy_mock_no_handler COMMAND xs_proxy_mock_test --fail-veh) - # The routes are read once per process, so each override case is its own test. - add_test(NAME xs_proxy_mock_env_slots COMMAND xs_proxy_mock_test --env-slots) - add_test(NAME xs_proxy_mock_env_slots_invalid COMMAND xs_proxy_mock_test --env-slots-invalid) - # PresentX on the queue: the slot is read once per process, so the named slot and the ignored value are two tests. - add_test(NAME xs_proxy_mock_present_slot COMMAND xs_proxy_mock_test --present-slot) - add_test(NAME xs_proxy_mock_present_slot_invalid COMMAND xs_proxy_mock_test --present-slot-invalid) -endif() -if(TARGET root_sig_test) - add_test(NAME root_sig COMMAND root_sig_test) -endif() -add_executable(command_list_test test/command_list_test.cpp) -add_test(NAME command_list COMMAND command_list_test) -# Which SPIR-V modules declare a storage image or buffer they may write (src/spirv_stores.h), on hand-built words. -add_executable(spirv_stores_test test/spirv_stores_test.cpp) -add_test(NAME spirv_stores COMMAND spirv_stores_test) -add_executable(shader_fixture_path_test test/shader_fixture_path_test.cpp) -add_test(NAME shader_fixture_path COMMAND shader_fixture_path_test) -add_executable(resource_tiling_test test/resource_tiling_test.cpp) -add_test(NAME resource_tiling COMMAND resource_tiling_test) -add_executable(resource_detile_test test/resource_detile_test.cpp) -add_test(NAME resource_detile COMMAND resource_detile_test) -add_executable(descriptor_table_test test/descriptor_table_test.cpp) -add_test(NAME descriptor_table COMMAND descriptor_table_test) -add_executable(shader_library_test test/shader_library_test.cpp) -add_test(NAME shader_library COMMAND shader_library_test) -add_executable(spirv_f16_halves_test test/spirv_f16_halves_test.cpp) -add_test(NAME spirv_f16_halves COMMAND spirv_f16_halves_test) -# Optional: skips unless LEONIDA_SHADERS names a translated work folder (/shaders/spirv). -add_executable(shader_library_corpus_test test/shader_library_corpus_test.cpp) -add_test(NAME shader_library_corpus COMMAND shader_library_corpus_test) -# Reads all 26,503 containers and modules: about 9 minutes from a hard disk. -set_tests_properties(shader_library_corpus PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 3600) -if(TARGET gta6rt) - # Optional: skips unless LEONIDA_GAME_DIR and LEONIDA_MOVIE are set. - add_executable(bink_decode_test - test/bink_decode_test.cpp - src/pe_loader.cpp - shims/registry.cpp - shims/xmem.cpp - ) - target_compile_definitions(bink_decode_test PRIVATE - WIN32_LEAN_AND_MEAN NOMINMAX UNICODE _UNICODE _CRT_SECURE_NO_WARNINGS) - target_compile_options(bink_decode_test PRIVATE /W4 /permissive- /EHsc /utf-8) - target_link_options(bink_decode_test PRIVATE /OPT:NOREF) - target_link_libraries(bink_decode_test PRIVATE psapi) - add_dependencies(bink_decode_test gta6rt_tls_host) - add_test(NAME bink_decode COMMAND bink_decode_test) - set_tests_properties(bink_decode PROPERTIES SKIP_RETURN_CODE 77) - - # Optional: skips unless LEONIDA_GAME_DIR and LEONIDA_BINK_INDEX are set. Measures the HBINK/BINKSUMMARY - # offsets and the decode return values over every stream of movies.rpf (docs/movies.md section 5). - add_executable(bink_abi_test - test/bink_abi_test.cpp - src/pe_loader.cpp - shims/registry.cpp - shims/xmem.cpp - ) - target_compile_definitions(bink_abi_test PRIVATE - WIN32_LEAN_AND_MEAN NOMINMAX UNICODE _UNICODE _CRT_SECURE_NO_WARNINGS) - target_compile_options(bink_abi_test PRIVATE /W4 /permissive- /EHsc /utf-8) - target_link_options(bink_abi_test PRIVATE /OPT:NOREF) - target_link_libraries(bink_abi_test PRIVATE psapi) - add_dependencies(bink_abi_test gta6rt_tls_host) - add_test(NAME bink_abi COMMAND bink_abi_test) - set_tests_properties(bink_abi PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 3600) - - # Optional local viewer: plays a .bk2 in a window through the package's Bink2Scarlett.dll (test/bink_play.cpp). - # The CTest entry is the headless smoke run; it skips unless LEONIDA_GAME_DIR and LEONIDA_MOVIE are set. - add_executable(bink_play - test/bink_play.cpp - src/pe_loader.cpp - shims/registry.cpp - shims/xmem.cpp - ) - target_compile_definitions(bink_play PRIVATE - WIN32_LEAN_AND_MEAN NOMINMAX UNICODE _UNICODE _CRT_SECURE_NO_WARNINGS) - target_compile_options(bink_play PRIVATE /W4 /permissive- /EHsc /utf-8) - target_link_options(bink_play PRIVATE /OPT:NOREF) - target_link_libraries(bink_play PRIVATE psapi user32 gdi32) - add_dependencies(bink_play gta6rt_tls_host) - add_test(NAME bink_play_headless COMMAND bink_play --headless --frames 30) - set_tests_properties(bink_play_headless PROPERTIES SKIP_RETURN_CODE 77) - - # Optional: skips unless LEONIDA_GAME_DIR is set. Drives the package's FSR DLL on the Xbox-ABI device proxy. - if(D3D12_LIBRARY AND DXGI_LIBRARY) - add_executable(fsr_dispatch_test - test/fsr_dispatch_test.cpp - src/pe_loader.cpp - shims/registry.cpp - shims/xmem.cpp - shims/d3d12_xs.cpp - shims/d3d12_xs_device.cpp - ) - target_compile_definitions(fsr_dispatch_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX _CRT_SECURE_NO_WARNINGS) - target_compile_options(fsr_dispatch_test PRIVATE /W4 /permissive- /EHsc /utf-8) - target_link_options(fsr_dispatch_test PRIVATE /OPT:NOREF) - target_link_libraries(fsr_dispatch_test PRIVATE gta6rt_d3d12_xs_rootsig ${D3D12_LIBRARY} ${DXGI_LIBRARY} psapi) - add_dependencies(fsr_dispatch_test gta6rt_tls_host) - add_test(NAME fsr_dispatch COMMAND fsr_dispatch_test) - set_tests_properties(fsr_dispatch PROPERTIES SKIP_RETURN_CODE 77) - - # Optional: skips unless LEONIDA_GAME_DIR is set. Constructs the package's XboxBvhBuilder on the device proxy. - add_executable(bvh_builder_test - test/bvh_builder_test.cpp - src/pe_loader.cpp - shims/registry.cpp - shims/xmem.cpp - shims/d3d12_xs.cpp - shims/d3d12_xs_device.cpp - ) - target_compile_definitions(bvh_builder_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX _CRT_SECURE_NO_WARNINGS) - target_compile_options(bvh_builder_test PRIVATE /W4 /permissive- /EHsc /utf-8) - target_link_options(bvh_builder_test PRIVATE /OPT:NOREF) - target_link_libraries(bvh_builder_test PRIVATE gta6rt_d3d12_xs_rootsig ${D3D12_LIBRARY} ${DXGI_LIBRARY} psapi) - add_dependencies(bvh_builder_test gta6rt_tls_host) - add_test(NAME bvh_builder COMMAND bvh_builder_test) - set_tests_properties(bvh_builder PROPERTIES SKIP_RETURN_CODE 77) - endif() - - # Optional: skips unless LEONIDA_GAME_DIR and LEONIDA_MOVIE_AUDIO are set. - add_executable(bink_audio_test - test/bink_audio_test.cpp - src/pe_loader.cpp - shims/registry.cpp - shims/xmem.cpp - ) - target_compile_definitions(bink_audio_test PRIVATE - WIN32_LEAN_AND_MEAN NOMINMAX UNICODE _UNICODE _CRT_SECURE_NO_WARNINGS) - target_compile_options(bink_audio_test PRIVATE /W4 /permissive- /EHsc /utf-8) - target_link_options(bink_audio_test PRIVATE /OPT:NOREF) - target_link_libraries(bink_audio_test PRIVATE psapi) - add_dependencies(bink_audio_test gta6rt_tls_host) - add_test(NAME bink_audio COMMAND bink_audio_test) - set_tests_properties(bink_audio PROPERTIES SKIP_RETURN_CODE 77) -endif() -if(WIN32 AND TARGET xmem_test) - add_test(NAME xmem COMMAND xmem_test) -endif() -if(WIN32 AND TARGET xg_xs_test) - add_test(NAME xg_xs COMMAND xg_xs_test) -endif() -if(WIN32 AND TARGET acphal_test) - add_test(NAME acphal COMMAND acphal_test) -endif() -if(WIN32 AND TARGET cpu_emulation_test) - add_test(NAME cpu_emulation COMMAND cpu_emulation_test) -endif() -if(WIN32 AND TARGET xapu_chad_test) - add_test(NAME xapu_chad COMMAND xapu_chad_test) -endif() -if(WIN32 AND TARGET process_cmdline_test) - add_test(NAME process_cmdline COMMAND process_cmdline_test) -endif() -if(WIN32 AND TARGET file_system_test) - add_test(NAME file_system COMMAND file_system_test) -endif() -if(WIN32 AND TARGET int3_skip_test) - add_test(NAME int3_skip COMMAND int3_skip_test) -endif() -if(WIN32 AND TARGET winhttp_offline_test) - add_test(NAME winhttp_offline COMMAND winhttp_offline_test) -endif() -if(WIN32 AND TARGET com_shim_test) - add_test(NAME com_shim COMMAND com_shim_test) -endif() -if(WIN32 AND TARGET bcrypt_rng_test) - add_test(NAME bcrypt_rng COMMAND bcrypt_rng_test) - add_test(NAME bcrypt_rng_seeded COMMAND bcrypt_rng_test --seeded) - set_tests_properties(bcrypt_rng_seeded PROPERTIES ENVIRONMENT "LEONIDA_RNG_SEED=0x123456789abcdef0") -endif() -if(WIN32 AND TARGET api_ref_state_test) - add_test(NAME api_ref_state COMMAND api_ref_state_test) - set_tests_properties(api_ref_state PROPERTIES TIMEOUT 30) -endif() -if(WIN32 AND TARGET api_global_refs_test) - add_test(NAME api_global_refs COMMAND api_global_refs_test) - set_tests_properties(api_global_refs PROPERTIES TIMEOUT 30) -endif() -# Internal XTaskQueue context pinning and rundown regression tests. -if(WIN32 AND TARGET gta6rt_xtaskqueue) - foreach(_context_test context_pinning context_rundown context_reentrant context_concurrent_detach context_attach_detach_stress) - add_executable(${_context_test}_test - test/${_context_test}_test.cpp - ) - target_include_directories(${_context_test}_test PRIVATE - ${CMAKE_CURRENT_SOURCE_DIR}/shims/xtaskqueue - ${XTASKQUEUE_DIR}/Source/Task - ${XTASKQUEUE_DIR}/Source/Common - ) - target_compile_definitions(${_context_test}_test PRIVATE - WIN32_LEAN_AND_MEAN NOMINMAX - ) - target_compile_options(${_context_test}_test PRIVATE - /W4 /permissive- /utf-8 /EHsc - ) - target_link_libraries(${_context_test}_test PRIVATE - gta6rt_xtaskqueue - ) - add_test(NAME ${_context_test} - COMMAND ${_context_test}_test - ) - set_tests_properties(${_context_test} PROPERTIES TIMEOUT 15) - endforeach() - - add_executable(wait_registration_test test/wait_registration_test.cpp) - target_include_directories(wait_registration_test PRIVATE - ${CMAKE_CURRENT_SOURCE_DIR}/shims/xtaskqueue ${XTASKQUEUE_DIR}/Source/Task ${XTASKQUEUE_DIR}/Source/Common) - target_link_libraries(wait_registration_test PRIVATE gta6rt_xtaskqueue) - foreach(_case unregister undispatched terminate parked self presignaled monitor close composite snapshot - cross concurrent held_snapshot admission cancel_unregister reentrant_admission - reentrant_vs_external_unregister multi_dispatcher_terminate multi_dispatcher_unregister_replace) - add_test(NAME wait_registration_${_case} COMMAND wait_registration_test ${_case}) - set_tests_properties(wait_registration_${_case} PROPERTIES TIMEOUT 15) - endforeach() -endif() -if(WIN32 AND TARGET dstorage_test) - add_test(NAME dstorage COMMAND dstorage_test) -endif() -if(WIN32 AND TARGET xgameruntime_test) - add_test(NAME xgameruntime COMMAND xgameruntime_test) - add_test(NAME xgameruntime_user COMMAND xgameruntime_user_test) - add_test(NAME xgameruntime_gamesave COMMAND xgameruntime_gamesave_test) - add_test(NAME xgameruntime_store COMMAND xgameruntime_store_test) - add_test(NAME xgameruntime_offline COMMAND xgameruntime_offline_test) - add_test(NAME xgameruntime_offline_hdr COMMAND xgameruntime_offline_test) - set_tests_properties(xgameruntime_offline_hdr PROPERTIES ENVIRONMENT "LEONIDA_HDR=1") - add_test(NAME xgameruntime_user_gamertag COMMAND xgameruntime_user_test --expect-gamertag Tester42) - set_tests_properties(xgameruntime_user_gamertag PROPERTIES ENVIRONMENT "LEONIDA_GAMERTAG=Tester42") - # Longer than getenv_s's old 64-byte buffer: still the "Player" fallback (and its message), not a silent one. - add_test(NAME xgameruntime_user_gamertag_long COMMAND xgameruntime_user_test --expect-gamertag Player) - set_tests_properties(xgameruntime_user_gamertag_long PROPERTIES ENVIRONMENT "LEONIDA_GAMERTAG=GGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGG") -endif() -# The active-input tracker the GameInput shim feeds (src/active_input.h), on synthetic samples: no SDL, no -# controller, no GPU, so it builds and runs everywhere, with or without SDL3. -add_executable(active_input_test test/active_input_test.cpp) -if(MSVC) - target_compile_options(active_input_test PRIVATE /W4 /permissive- /utf-8) -endif() -add_test(NAME active_input COMMAND active_input_test) -if(WIN32 AND TARGET gameinput_test) - add_test(NAME gameinput COMMAND gameinput_test) -elseif(TARGET gta6rt) - # Built without SDL3: listed as "Not Run (Disabled)" so it is visible that the shim was not tested. - add_test(NAME gameinput COMMAND ${CMAKE_COMMAND} -E echo "built without SDL3") - set_tests_properties(gameinput PROPERTIES DISABLED TRUE) -endif() -if(WIN32 AND TARGET gta6rt AND TARGET tiny_game) - if(TARGET tiny_argv_default_a AND NOT CMAKE_CROSSCOMPILING) - find_package(Python3 COMPONENTS Interpreter QUIET) - if(Python3_FOUND) - add_test(NAME run_argv_modes COMMAND "${Python3_EXECUTABLE}" -I - "${CMAKE_CURRENT_SOURCE_DIR}/test/check_argv_modes.py" - --loader "$" --fixtures "$" - --work-dir "${CMAKE_CURRENT_BINARY_DIR}") - set_tests_properties(run_argv_modes PROPERTIES TIMEOUT 90) - endif() - endif() - add_test(NAME run_startup_cmdline COMMAND ${CMAKE_COMMAND} - "-DLOADER=$" "-DGUEST=$" - "-DRUNNER=${CMAKE_CROSSCOMPILING_EMULATOR}" -P "${CMAKE_CURRENT_SOURCE_DIR}/test/check_startup_cmdline.cmake") - add_test(NAME run_tiny_async COMMAND ${CMAKE_COMMAND} - "-DLOADER=$" "-DGUEST=$" - "-DRUNNER=${CMAKE_CROSSCOMPILING_EMULATOR}" -P "${CMAKE_CURRENT_SOURCE_DIR}/test/check_loaded_async.cmake") - add_test(NAME run_tiny_gdk_load COMMAND ${CMAKE_COMMAND} - "-DLOADER=$" "-DGUEST=$" - "-DRUNNER=${CMAKE_CROSSCOMPILING_EMULATOR}" -P "${CMAKE_CURRENT_SOURCE_DIR}/test/check_loaded_gdk.cmake") - add_test(NAME run_tiny_bundled_load COMMAND ${CMAKE_COMMAND} - "-DLOADER=$" "-DGUEST=$" - "-DRUNNER=${CMAKE_CROSSCOMPILING_EMULATOR}" -P "${CMAKE_CURRENT_SOURCE_DIR}/test/check_loaded_bundled.cmake") - # atexit handlers, static destructors and the ways out, compared with the same program run natively. - add_test(NAME run_tiny_atexit COMMAND ${CMAKE_COMMAND} - "-DLOADER=$" "-DGUEST=$" - "-DRUNNER=${CMAKE_CROSSCOMPILING_EMULATOR}" -P "${CMAKE_CURRENT_SOURCE_DIR}/test/check_atexit.cmake") - add_test(NAME run_tiny_game COMMAND gta6rt --run $ -- hello 42) - add_test(NAME run_tiny_game_console_paths COMMAND ${CMAKE_COMMAND} - "-DLOADER=$" "-DGUEST=$" - "-DRUNNER=${CMAKE_CROSSCOMPILING_EMULATOR}" -P "${CMAKE_CURRENT_SOURCE_DIR}/test/check_console_paths.cmake") - add_test(NAME run_tiny_game_exit_code COMMAND tiny_game_exit_code_test - "$" "$") - add_test(NAME run_tiny_game_abort_exit_codes COMMAND tiny_game_abort_test - "$" "$") - # Without relocations it can only run at 0x140000000 (base_reservation.h), so passing means it got there; the - # game's exact exit code comes back through the relaunch. - add_test(NAME run_tiny_game_fixed COMMAND gta6rt --run $ -- hello 42) - add_test(NAME run_tiny_game_fixed_exit_code COMMAND tiny_game_exit_code_test - "$" "$") - # Two modes at once are refused before anything is mapped (#886). The stand-in game's own arguments are passed, - # so a gta6rt that ignored the conflict would run it, print "running" and exit 0. - foreach(modes "dry-run;run" "dry-run;init" "init;run") - string(REPLACE ";" "_" name "${modes}") - list(TRANSFORM modes PREPEND "--") - add_test(NAME gta6rt_rejects_${name} COMMAND gta6rt ${modes} $ -- hello 42) - set_tests_properties(gta6rt_rejects_${name} PROPERTIES - PASS_REGULAR_EXPRESSION "usage: gta6rt" - FAIL_REGULAR_EXPRESSION "running |module\\(s\\) mapped") - endforeach() - # The opt-in checks, one test each: thread_local on the game's threads, a C++ exception caught inside the image. - add_test(NAME run_tiny_game_tls COMMAND gta6rt --run $ -- hello 42 tls) - add_test(NAME run_tiny_game_eh COMMAND gta6rt --run $ -- hello 42 eh) - # BUILD-1457: the stack a game thread gets. gta6rt_stack reads SizeOfStackReserve from the built loader (nothing - # is run); run_tiny_game_stack asks Windows, on the entry thread and on a thread created with dwStackSize 0. - add_test(NAME gta6rt_stack COMMAND "${CMAKE_COMMAND}" - "-DTOOL=$" "-DWANT=${GTA6RT_STACK}" - -P "${CMAKE_CURRENT_SOURCE_DIR}/test/check_stack_reserve.cmake") - add_test(NAME run_tiny_game_stack COMMAND gta6rt --run $ -- hello 42 stack) - # GAME: is the game folder, absolute, when gta6rt is given a bare image name or `--game-dir .`. - add_test(NAME run_tiny_game_dir COMMAND ${CMAKE_COMMAND} - "-DLOADER=$" "-DGUEST=$" - "-DRUNNER=${CMAKE_CROSSCOMPILING_EMULATOR}" -P "${CMAKE_CURRENT_SOURCE_DIR}/test/check_game_dir.cmake") -endif() -if(TARGET root_signature_test) - add_test(NAME root_signature COMMAND root_signature_test) -endif() -if(TARGET host_cpu_test) - add_test(NAME host_cpu COMMAND host_cpu_test) -endif() -if(TARGET core_config_test) - # The example file is an argument, so the test reads the tracked file and not a copy made at configure time. - add_test(NAME core_config COMMAND core_config_test "${CMAKE_CURRENT_SOURCE_DIR}/leonida.example.toml") -endif() -if(TARGET core_log_test) - add_test(NAME core_log COMMAND core_log_test) -endif() -if(WIN32 AND TARGET root_signature_oracle_test) - add_test(NAME root_signature_oracle COMMAND root_signature_oracle_test) -endif() diff --git a/runtime/cmake/translator_deps.cmake b/runtime/cmake/translator_deps.cmake deleted file mode 100644 index 559333bc9..000000000 --- a/runtime/cmake/translator_deps.cmake +++ /dev/null @@ -1,31 +0,0 @@ -# What the SPIR-V that test/shaders/build.py writes comes from, besides the .asm files: build.py and the modules it -# imports, the scripts it runs (tools/rdna2spirv.py, and tools/vk_subgroup_info.py, whose answer picks -# --bary-fallback), and every module rdna2spirv.py imports or file it reads (make_game.py's TRANSLATION_SOURCES). -# Every add_custom_command that runs build.py DEPENDS on this list, so an edit to a helper such as tools/spirv_asm.py -# rebuilds the test shaders instead of leaving the last build's SPIR-V in place (BUILD-1064). -# tests/test_cmake_translator_deps.py fails when an import is missing here or a build.py rule doesn't use the list. -get_filename_component(_leonida_repo "${CMAKE_CURRENT_LIST_DIR}/../.." ABSOLUTE) -set(LEONIDA_TRANSLATOR_DEPS - ${_leonida_repo}/runtime/test/shaders/build.py - ${_leonida_repo}/runtime/test/shaders/compute_fixture.py - ${_leonida_repo}/tools/bary_fallback_gs.py - ${_leonida_repo}/tools/cfg_structure.py - ${_leonida_repo}/tools/fssm_header.py - ${_leonida_repo}/tools/fssm_unpack.py - ${_leonida_repo}/tools/gfx10_formats.json - ${_leonida_repo}/tools/lane_masks.py - ${_leonida_repo}/tools/mc_command.py - ${_leonida_repo}/tools/rdna2spirv.py - ${_leonida_repo}/tools/replace_retry.py - ${_leonida_repo}/tools/report_paths.py - ${_leonida_repo}/tools/shader_ir.py - ${_leonida_repo}/tools/shader_meta.py - ${_leonida_repo}/tools/shader_stage_manifest.py - ${_leonida_repo}/tools/spirv_asm.py - ${_leonida_repo}/tools/spirv_asm_tables.py - ${_leonida_repo}/tools/spirv_opt.py - ${_leonida_repo}/tools/spirv_stubs.py - ${_leonida_repo}/tools/vk_subgroup_info.py - ${_leonida_repo}/tools/wave64_emulate_opt.py - ${_leonida_repo}/tools/wave64_halves.py) -unset(_leonida_repo) diff --git a/runtime/cmake/vulkan_cpu_tests.cmake b/runtime/cmake/vulkan_cpu_tests.cmake deleted file mode 100644 index e5ca3cbbe..000000000 --- a/runtime/cmake/vulkan_cpu_tests.cmake +++ /dev/null @@ -1,155 +0,0 @@ -# CPU-only tests of the Vulkan layer: they need the Vulkan headers, not a GPU. -# Included by runtime/CMakeLists.txt inside if(TARGET Vulkan::Headers). - -# Needs only the Vulkan headers, not a GPU. -if(BUILD_TESTING) - add_executable(typeless_rtv_test test/typeless_rtv_test.cpp) - target_link_libraries(typeless_rtv_test PRIVATE Vulkan::Headers) - if(WIN32) - target_compile_definitions(typeless_rtv_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) - endif() - add_test(NAME typeless_rtv COMMAND typeless_rtv_test) - add_executable(pipeline_cache_snapshot_test test/pipeline_cache_snapshot_test.cpp) - target_link_libraries(pipeline_cache_snapshot_test PRIVATE Vulkan::Headers) - add_test(NAME pipeline_cache_snapshot COMMAND pipeline_cache_snapshot_test) - add_executable(predicated_copy_test test/predicated_copy_test.cpp) - target_link_libraries(predicated_copy_test PRIVATE Vulkan::Headers) - if(WIN32) - target_compile_definitions(predicated_copy_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) - endif() - add_test(NAME predicated_copy COMMAND predicated_copy_test) - # CopyResource (buffer-to-buffer) and CopyTexture (including depth24_as_float) apply ResourceBinding::buffer_offset (no GPU). - add_executable(replay_copy_offset_test test/replay_copy_offset_test.cpp) - target_link_libraries(replay_copy_offset_test PRIVATE Vulkan::Headers) - if(WIN32) - target_compile_definitions(replay_copy_offset_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) - endif() - add_test(NAME replay_copy_offset COMMAND replay_copy_offset_test) - # KHR CopyRaytracingAccelerationStructure (CLONE, COMPACT) and COMPACTED_SIZE postbuild (no GPU). - add_executable(replay_khr_as_copy_postbuild_test test/replay_khr_as_copy_postbuild_test.cpp) - target_link_libraries(replay_khr_as_copy_postbuild_test PRIVATE Vulkan::Headers) - if(WIN32) - target_compile_definitions(replay_khr_as_copy_postbuild_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) - endif() - if(MSVC) - target_compile_options(replay_khr_as_copy_postbuild_test PRIVATE /W4 /permissive- /utf-8) - endif() - add_test(NAME replay_khr_as_copy_postbuild COMMAND replay_khr_as_copy_postbuild_test) - # PreparedList::wrote_readback and readback_src_stages match the actual producer stage (depth24, rgb96, UAV clear; no GPU). - add_executable(replay_readback_stages_test test/replay_readback_stages_test.cpp) - target_link_libraries(replay_readback_stages_test PRIVATE Vulkan::Headers) - if(WIN32) - target_compile_definitions(replay_readback_stages_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) - endif() - add_test(NAME replay_readback_stages COMMAND replay_readback_stages_test) - # emit of an enhanced texture barrier: no heap allocation for one layout piece, one barrier for each piece (no GPU). - add_executable(replay_texture_barrier_test test/replay_texture_barrier_test.cpp) - target_link_libraries(replay_texture_barrier_test PRIVATE Vulkan::Headers) - if(WIN32) - target_compile_definitions(replay_texture_barrier_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) - endif() - add_test(NAME replay_texture_barrier COMMAND replay_texture_barrier_test) - add_executable(clear_color_test test/clear_color_test.cpp) - target_link_libraries(clear_color_test PRIVATE Vulkan::Headers) - if(WIN32) - target_compile_definitions(clear_color_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) - endif() - add_test(NAME clear_color COMMAND clear_color_test) - # FramePacer of the Xbox presentation path on a fake clock (src/frame_pacer.h); no GPU, no Vulkan. - add_executable(frame_pacer_test test/frame_pacer_test.cpp) - find_package(Threads REQUIRED) - target_link_libraries(frame_pacer_test PRIVATE Threads::Threads) - if(MSVC) - target_compile_options(frame_pacer_test PRIVATE /W4 /permissive- /utf-8) - endif() - add_test(NAME frame_pacer COMMAND frame_pacer_test) - - # Replay refuses a list whose whole-view or implicit zero-clear needs an unset vkCmdClear*Image (no GPU). - add_executable(replay_clear_gate_test test/replay_clear_gate_test.cpp) - target_link_libraries(replay_clear_gate_test PRIVATE Vulkan::Headers) - if(WIN32) - target_compile_definitions(replay_clear_gate_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) - endif() - add_test(NAME replay_clear_gate COMMAND replay_clear_gate_test) - # WriteBufferImmediate suspends conditional rendering around vkCmdUpdateBuffer so Intel drivers do not drop it. - add_executable(replay_write_immediate_predication_test test/replay_write_immediate_predication_test.cpp) - target_link_libraries(replay_write_immediate_predication_test PRIVATE Vulkan::Headers) - if(WIN32) - target_compile_definitions(replay_write_immediate_predication_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) - endif() - add_test(NAME replay_write_immediate_predication COMMAND replay_write_immediate_predication_test) - add_executable(d3d12_state_map_test test/d3d12_state_map_test.cpp) - target_link_libraries(d3d12_state_map_test PRIVATE Vulkan::Headers) - if(WIN32) - target_compile_definitions(d3d12_state_map_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) - endif() - add_test(NAME d3d12_state_map COMMAND d3d12_state_map_test) - add_executable(indirect_dispatch_count_alloc_test test/indirect_dispatch_count_alloc_test.cpp) - target_link_libraries(indirect_dispatch_count_alloc_test PRIVATE Vulkan::Headers) - if(WIN32) - target_compile_definitions(indirect_dispatch_count_alloc_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) - endif() - add_test(NAME indirect_dispatch_count_alloc COMMAND indirect_dispatch_count_alloc_test) - # A buffer UAV clear writes where its resource starts in a shared VkBuffer (no GPU). - add_executable(replay_uav_clear_offset_test test/replay_uav_clear_offset_test.cpp) - target_link_libraries(replay_uav_clear_offset_test PRIVATE Vulkan::Headers) - add_test(NAME replay_uav_clear_offset COMMAND replay_uav_clear_offset_test) - # ResolveQueryData suspends conditional rendering around un-ended vkCmdFillBuffer runs as well as dispatches (D3D-148). - add_executable(replay_query_predication_test test/replay_query_predication_test.cpp) - target_link_libraries(replay_query_predication_test PRIVATE Vulkan::Headers) - if(WIN32) - target_compile_definitions(replay_query_predication_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) - endif() - add_test(NAME replay_query_predication COMMAND replay_query_predication_test) - # Query edge cases and queue ownership, with CPU mocks (no GPU or game data). - add_executable(replay_query_edges_test test/replay_query_edges_test.cpp) - target_link_libraries(replay_query_edges_test PRIVATE Vulkan::Headers) - if(WIN32) - target_compile_definitions(replay_query_edges_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) - endif() - add_test(NAME replay_query_edges COMMAND replay_query_edges_test) - # GFX10 T#/S#/V# descriptor encoding and its Vulkan mappings (src/gfx10_descriptors.h). - add_executable(gfx10_descriptors_test test/gfx10_descriptors_test.cpp) - target_link_libraries(gfx10_descriptors_test PRIVATE Vulkan::Headers) - add_test(NAME gfx10_descriptors COMMAND gfx10_descriptors_test) - # CPU cost of the D3D12 -> Vulkan replay per command (record, prepare, emit) with no-op Vulkan entry points: - # no GPU or driver. ctest runs its quick self-test; run it without arguments for the numbers. - add_executable(replay_cpu_bench test/replay_cpu_bench.cpp) - target_link_libraries(replay_cpu_bench PRIVATE Vulkan::Headers) - if(WIN32) - target_compile_definitions(replay_cpu_bench PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) - endif() - add_test(NAME replay_cpu_bench_selftest COMMAND replay_cpu_bench --self-test) - add_test(NAME vk_descriptor_bench_selftest COMMAND vk_descriptor_bench --self-test) - # mods.h: mod.json manifests and archetype swaps (docs/modding.md) - add_executable(mods_test test/mods_test.cpp) - target_link_libraries(mods_test PRIVATE Vulkan::Headers) - add_test(NAME mods COMMAND mods_test) - if(WIN32) - # code_hooks.h: the remapping thunk and direct-call redirection the archetype hook uses (x64 Windows) - add_executable(code_hooks_test test/code_hooks_test.cpp) - target_link_libraries(code_hooks_test PRIVATE Vulkan::Headers) - target_compile_definitions(code_hooks_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) - add_test(NAME code_hooks COMMAND code_hooks_test) - endif() - # The subgroup size a pipeline stage asks for, from synthetic index entries and device properties. - add_executable(subgroup_size_test test/subgroup_size_test.cpp) - target_link_libraries(subgroup_size_test PRIVATE Vulkan::Headers) - add_test(NAME subgroup_size COMMAND subgroup_size_test) - add_executable(conservative_raster_test test/conservative_raster_test.cpp) - add_test(NAME conservative_raster COMMAND conservative_raster_test) - # The GPU address arena's size from LEONIDA_ARENA_MB and synthetic device buffer limits. - add_executable(arena_size_test test/arena_size_test.cpp) - target_link_libraries(arena_size_test PRIVATE Vulkan::Headers) - add_test(NAME arena_size COMMAND arena_size_test) - # Queue construction cleans its Vulkan handles if holder registration runs out of host memory. - add_executable(vk_queue_constructor_oom_test test/vk_queue_constructor_oom_test.cpp) - target_link_libraries(vk_queue_constructor_oom_test PRIVATE Vulkan::Headers ${CMAKE_DL_LIBS}) - if(WIN32) - target_compile_definitions(vk_queue_constructor_oom_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) - if(MSVC) - target_compile_options(vk_queue_constructor_oom_test PRIVATE /W4 /permissive- /EHsc /utf-8) - endif() - endif() - add_test(NAME vk_queue_constructor_oom COMMAND vk_queue_constructor_oom_test) -endif() diff --git a/runtime/cmake/vulkan_headers_missing.cmake b/runtime/cmake/vulkan_headers_missing.cmake deleted file mode 100644 index 8b4c94dfd..000000000 --- a/runtime/cmake/vulkan_headers_missing.cmake +++ /dev/null @@ -1,21 +0,0 @@ -# Reports a configure without Vulkan headers. Everything under if(TARGET Vulkan::Headers) in runtime/CMakeLists.txt -# is then left out: not only the GPU test tools but the D3D12 COM objects and the Vulkan D3D12 device in gta6rt -# (LEONIDA_D3D12=vulkan), and with them most of ctest. A STATUS line was easy to miss: ctest then reports -# "100% tests passed" on a fraction of the suite. -DLEONIDA_REQUIRE_VULKAN=ON makes it a configure error (CI sets it). -# Kept in its own file so tests/test_cmake_vulkan_missing.py can run it with `cmake -P`. -function(leonida_vulkan_headers_missing) - set(text - "Vulkan headers not found, so this build leaves out the Vulkan D3D12 device in gta6rt (LEONIDA_D3D12=vulkan " - "is unavailable), the D3D12 COM objects and their tests, the D3D12 layer and GPU tests, the GPU test tools " - "(run_gpu_tests.py needs them), vk_pipeline_check, d3d12_state_map_test and gfx10_descriptors_test. ctest " - "then runs only the CPU tests and can still report 100% passed. Set VULKAN_SDK in the environment that runs " - "CMake (then delete CMakeCache.txt, which keeps the failed lookup), install the Vulkan headers, or pass " - "-DLEONIDA_VULKAN_HEADERS_FETCH=ON to download the pinned Khronos Vulkan-Headers release. " - "-DLEONIDA_REQUIRE_VULKAN=ON turns this warning into an error.") - string(CONCAT text ${text}) - if(LEONIDA_REQUIRE_VULKAN) - message(FATAL_ERROR "${text}") - else() - message(WARNING "${text}") - endif() -endfunction() diff --git a/runtime/cmake/vulkan_tools.cmake b/runtime/cmake/vulkan_tools.cmake deleted file mode 100644 index fbd142d3f..000000000 --- a/runtime/cmake/vulkan_tools.cmake +++ /dev/null @@ -1,262 +0,0 @@ -# The standalone Vulkan tools (vk_harness, vk_pipeline_check, vk_sandbox and the others of the loop below) and the -# Vulkan tests that do not use the D3D12 COM objects. -# Included by runtime/CMakeLists.txt inside if(TARGET Vulkan::Headers). - -foreach(tool vk_harness vk_ps_sweep vk_texture_test vk_sampler_test vk_compute_test vk_store_test vk_pipeline_check vk_command_replay_test - vk_bindless_test vk_image_fuzz vk_descriptor_bench depth24_convert_test vk_predicate_capture_test vk_predicated_copy_test - vk_xdxr_build_test vk_queue_test vk_sandbox) - add_executable(${tool} test/${tool}.cpp) - target_link_libraries(${tool} PRIVATE Vulkan::Headers ${CMAKE_DL_LIBS}) - if(WIN32) - target_compile_definitions(${tool} PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) - endif() -endforeach() -# OpFmaKHR width gate of vk_shader_fma.h (shaderFmaFloat32 / shaderFmaFloat64): no Vulkan instance, no GPU. -add_executable(vk_shader_fma_test test/vk_shader_fma_test.cpp) -target_link_libraries(vk_shader_fma_test PRIVATE Vulkan::Headers) -add_test(NAME vk_shader_fma COMMAND vk_shader_fma_test) -# LEONIDA_VK_DEVICE names the GPU in every harness (docs/testing.md, "Choosing the GPU"): a filter that matches no -# device fails the run in vk_descriptor_bench and vk_sandbox too, instead of testing another GPU (TEST-1141). -find_package(Python3 COMPONENTS Interpreter QUIET) -if(Python3_FOUND) - add_test(NAME vk_device_filter_tools COMMAND "${Python3_EXECUTABLE}" -I - "${CMAKE_CURRENT_SOURCE_DIR}/test/check_device_filter_tools.py" "$" - "$" "${CMAKE_CURRENT_BINARY_DIR}/vk_device_filter_tools") - set_tests_properties(vk_device_filter_tools PROPERTIES SKIP_RETURN_CODE 77) -endif() -if(MSVC) - # Keep the checker and its worker threads on the toolchain's C++ runtime under Wine. - set_property(TARGET vk_pipeline_check PROPERTY - MSVC_RUNTIME_LIBRARY "MultiThreaded$<$:Debug>") -endif() -# BUILD-1457: a driver compiles on the thread that creates the pipeline, and its compiler can recurse with the -# shader's nesting. On Windows a thread that asks for no size gets the reserve in the PE header, 1 MB by default: -# the main thread and every std::thread worker of the checker. AMD's Windows compiler (26.11.2) overflows that -# on 26 of the corpus's mesh shaders, and 2 MB is still too little for compute shaders nested deeper than 16 -# (docs/pipeline_check.md, "Stack reserve"). Keep the number in step with scripts/build_runtime.ps1. -set(LEONIDA_PIPELINE_CHECK_STACK 8388608) -if(WIN32) - if(MSVC) - target_link_options(vk_pipeline_check PRIVATE /STACK:${LEONIDA_PIPELINE_CHECK_STACK}) - else() - target_link_options(vk_pipeline_check PRIVATE -Wl,--stack,${LEONIDA_PIPELINE_CHECK_STACK}) - endif() -endif() -if(BUILD_TESTING) - if(WIN32 AND LEONIDA_BUILD_WINDOWS_RUNTIME) - # Real Win32 environment and DXGI names, with D3D12 device creation stubbed: no GPU commands or game files. - # It includes the runtime's D3D12 shim headers, so it needs the same Windows SDK as the runtime. - add_executable(host_adapter_test test/host_adapter_test.cpp) - target_link_libraries(host_adapter_test PRIVATE Vulkan::Headers dxgi) - target_compile_definitions(host_adapter_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) - if(MSVC) - target_compile_options(host_adapter_test PRIVATE /W4 /permissive- /EHsc /utf-8) - endif() - add_test(NAME host_adapter COMMAND host_adapter_test) - endif() - add_test(NAME vk_pipeline_check_cli COMMAND "${CMAKE_COMMAND}" - "-DTOOL=$" - "-DTEST_DIR=${CMAKE_CURRENT_BINARY_DIR}/vk_pipeline_check_cli_input" - "-DRUNNER=${CMAKE_CROSSCOMPILING_EMULATOR}" - -P "${CMAKE_CURRENT_SOURCE_DIR}/test/check_vk_pipeline_cli.cmake") - add_test(NAME vk_texture_cube_alpha COMMAND vk_texture_test --self-test-cube-alpha) - if(WIN32) - # Reads SizeOfStackReserve from the built file; the program is not run, so it needs no emulator. - add_test(NAME vk_pipeline_check_stack COMMAND "${CMAKE_COMMAND}" - "-DTOOL=$" - "-DWANT=${LEONIDA_PIPELINE_CHECK_STACK}" - -P "${CMAKE_CURRENT_SOURCE_DIR}/test/check_stack_reserve.cmake") - endif() - add_test(NAME depth24_convert COMMAND depth24_convert_test) - set_tests_properties(depth24_convert PROPERTIES SKIP_RETURN_CODE 77) - # Self-checking Vulkan tests with no shaders or game data; each exits 77 without a Vulkan device (TEST-514). - foreach(test vk_command_replay vk_predicated_copy vk_predicate_capture vk_queue) - add_test(NAME ${test} COMMAND ${test}_test) - set_tests_properties(${test} PROPERTIES SKIP_RETURN_CODE 77) - endforeach() - # The XDXR BVH builder: the GPU writes every case, then tools/xdxr_bvh.py validates and traces them. - set(LEONIDA_XDXR_OUT "${CMAKE_CURRENT_BINARY_DIR}/xdxr_build_cases") - file(MAKE_DIRECTORY "${LEONIDA_XDXR_OUT}") - add_test(NAME xdxr_build COMMAND vk_xdxr_build_test "${LEONIDA_XDXR_OUT}") - set_tests_properties(xdxr_build PROPERTIES SKIP_RETURN_CODE 77 FIXTURES_SETUP xdxr_build_cases) - find_package(Python3 COMPONENTS Interpreter QUIET) - if(Python3_FOUND) - add_test(NAME xdxr_build_check COMMAND "${Python3_EXECUTABLE}" -I - "${CMAKE_CURRENT_SOURCE_DIR}/../tools/xdxr_bvh.py" check-build "${LEONIDA_XDXR_OUT}" --rays 1000) - set_tests_properties(xdxr_build_check PROPERTIES FIXTURES_REQUIRED xdxr_build_cases SKIP_RETURN_CODE 77) - endif() -endif() -# VulkanQueue/VulkanContext query-state synchronization (remove_query_pool vs commit, cross-queue plan/commit) -# and pending Wait() preservation across transient vkQueueSubmit failures. -add_executable(vk_queue_query_sync_test test/vk_queue_query_sync_test.cpp) -target_link_libraries(vk_queue_query_sync_test PRIVATE Vulkan::Headers ${CMAKE_DL_LIBS}) -if(WIN32) - target_compile_definitions(vk_queue_query_sync_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) -else() - find_package(Threads REQUIRED) - target_link_libraries(vk_queue_query_sync_test PRIVATE Threads::Threads) -endif() -if(MSVC) - target_compile_options(vk_queue_query_sync_test PRIVATE /W4 /permissive- /utf-8) -endif() -if(BUILD_TESTING) - add_test(NAME vk_queue_query_sync COMMAND vk_queue_query_sync_test) - set_tests_properties(vk_queue_query_sync PROPERTIES SKIP_RETURN_CODE 77) -endif() -# With LEONIDA_VK_VALIDATION=1: synchronization validation reports a missing barrier (and not a present one), so -# the other GPU tests' "0 validation errors" was checked by an active layer. 77 without validation or a device. -add_executable(vk_sync_validation_selftest test/vk_sync_validation_selftest.cpp) -target_link_libraries(vk_sync_validation_selftest PRIVATE Vulkan::Headers ${CMAKE_DL_LIBS}) -if(WIN32) - target_compile_definitions(vk_sync_validation_selftest PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) -endif() -if(MSVC) - target_compile_options(vk_sync_validation_selftest PRIVATE /W4 /permissive- /utf-8) -endif() -if(BUILD_TESTING) - add_test(NAME vk_sync_validation COMMAND vk_sync_validation_selftest) - set_tests_properties(vk_sync_validation PROPERTIES SKIP_RETURN_CODE 77) -endif() -if(NOT Vulkan_GLSLANG_VALIDATOR_EXECUTABLE) - find_program(Vulkan_GLSLANG_VALIDATOR_EXECUTABLE glslangValidator HINTS "$ENV{VULKAN_SDK}/Bin" "$ENV{VULKAN_SDK}/bin") -endif() -if(Vulkan_GLSLANG_VALIDATOR_EXECUTABLE) - add_executable(vk_overlapping_occlusion_test test/vk_overlapping_occlusion_test.cpp) - target_link_libraries(vk_overlapping_occlusion_test PRIVATE Vulkan::Headers ${CMAKE_DL_LIBS}) - if(WIN32) - target_compile_definitions(vk_overlapping_occlusion_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) - endif() - foreach(stage vert frag) - set(source "${CMAKE_CURRENT_SOURCE_DIR}/test/glsl/overlapping_occlusion.${stage}") - set(output "${CMAKE_CURRENT_BINARY_DIR}/overlapping_occlusion.${stage}.spv") - add_custom_command(OUTPUT "${output}" - COMMAND "${Vulkan_GLSLANG_VALIDATOR_EXECUTABLE}" -V --target-env vulkan1.0 - -o "${output}" "${source}" - DEPENDS "${source}" VERBATIM) - target_sources(vk_overlapping_occlusion_test PRIVATE "${output}") - endforeach() - if(BUILD_TESTING) - add_test(NAME vk_overlapping_occlusion COMMAND vk_overlapping_occlusion_test - "${CMAKE_CURRENT_BINARY_DIR}/overlapping_occlusion.vert.spv" - "${CMAKE_CURRENT_BINARY_DIR}/overlapping_occlusion.frag.spv") - # The same test as a device without pipelineStatisticsQuery runs it (MoltenVK), on whatever device is here. - add_test(NAME vk_overlapping_occlusion_no_statistics COMMAND vk_overlapping_occlusion_test - "${CMAKE_CURRENT_BINARY_DIR}/overlapping_occlusion.vert.spv" - "${CMAKE_CURRENT_BINARY_DIR}/overlapping_occlusion.frag.spv" --no-statistics) - set_tests_properties(vk_overlapping_occlusion vk_overlapping_occlusion_no_statistics - PROPERTIES SKIP_RETURN_CODE 77) - endif() -endif() -# CPU-only: the ranking that makes these harnesses prefer a native ICD over Mesa's Dozen (#915). No GPU needed. -add_executable(vk_device_pick_test test/vk_device_pick_test.cpp) -target_link_libraries(vk_device_pick_test PRIVATE Vulkan::Headers) -if(BUILD_TESTING) - add_test(NAME vk_device_pick COMMAND vk_device_pick_test) -endif() -# Committed BC* texture zero-initialization via vk.zero_buffer or vk.copy_scratch (D3D-220). -add_executable(vk_bc_zero_init_test test/vk_bc_zero_init_test.cpp) -target_link_libraries(vk_bc_zero_init_test PRIVATE Vulkan::Headers ${CMAKE_DL_LIBS}) -if(WIN32) - target_compile_definitions(vk_bc_zero_init_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) -endif() -if(MSVC) - target_compile_options(vk_bc_zero_init_test PRIVATE /W4 /permissive- /utf-8) -endif() -if(BUILD_TESTING) - add_test(NAME vk_bc_zero_init COMMAND vk_bc_zero_init_test) - set_tests_properties(vk_bc_zero_init PROPERTIES SKIP_RETURN_CODE 77) -endif() -# FenceWaitDispatcher concurrency and device-lost regressions (re-entrant callbacks, wakeup on device lost, counter error drain). -add_executable(vk_fence_dispatcher_sync_test test/vk_fence_dispatcher_sync_test.cpp) -target_link_libraries(vk_fence_dispatcher_sync_test PRIVATE Vulkan::Headers ${CMAKE_DL_LIBS}) -if(WIN32) - target_compile_definitions(vk_fence_dispatcher_sync_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) -else() - find_package(Threads REQUIRED) - target_link_libraries(vk_fence_dispatcher_sync_test PRIVATE Threads::Threads) -endif() -if(MSVC) - target_compile_options(vk_fence_dispatcher_sync_test PRIVATE /W4 /permissive- /utf-8) -endif() -if(BUILD_TESTING) - add_test(NAME vk_fence_dispatcher_sync COMMAND vk_fence_dispatcher_sync_test) - set_tests_properties(vk_fence_dispatcher_sync PROPERTIES SKIP_RETURN_CODE 77) -endif() -# CPU-only: the bindless set's array sizes from synthetic device limits. -add_executable(bindless_sizing_test test/bindless_sizing_test.cpp) -target_link_libraries(bindless_sizing_test PRIVATE Vulkan::Headers) -if(BUILD_TESTING) - add_test(NAME bindless_sizing COMMAND bindless_sizing_test) -endif() -# CPU-only: a mesh PSO's output, workgroup and shared-memory needs against synthetic device limits (vulkan_mesh_limits.h). -add_executable(vulkan_mesh_limits_test test/vulkan_mesh_limits_test.cpp) -target_link_libraries(vulkan_mesh_limits_test PRIVATE Vulkan::Headers) -if(BUILD_TESTING) - add_test(NAME vulkan_mesh_limits COMMAND vulkan_mesh_limits_test) -endif() -# CPU-only: Vulkan 1.3 core vs 1.2 KHR/EXT feature probing and proc fallback (runtime/src/vulkan13_features.h). -add_executable(vulkan13_features_test test/vulkan13_features_test.cpp) -target_link_libraries(vulkan13_features_test PRIVATE Vulkan::Headers) -if(MSVC) - target_compile_options(vulkan13_features_test PRIVATE /W4 /permissive- /utf-8) -endif() -if(BUILD_TESTING) - add_test(NAME vulkan13_features COMMAND vulkan13_features_test) -endif() -# Buffer registrations keep their binding, VA lookup, and sparse owner in step on host allocation failure. -add_executable(vk_buffer_registration_oom_test test/vk_buffer_registration_oom_test.cpp) -target_link_libraries(vk_buffer_registration_oom_test PRIVATE Vulkan::Headers ${CMAKE_DL_LIBS}) -if(WIN32) - target_compile_definitions(vk_buffer_registration_oom_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) - if(MSVC) - target_compile_options(vk_buffer_registration_oom_test PRIVATE /W4 /permissive- /EHsc /utf-8) - endif() -endif() -if(BUILD_TESTING) - add_test(NAME vk_buffer_registration_oom COMMAND vk_buffer_registration_oom_test) -endif() -# CPU-only: ScratchBuffers chunk alignment, retire/collect/forget, and spare cap (runtime/src/vulkan_scratch.h). -add_executable(vulkan_scratch_test test/vulkan_scratch_test.cpp) -target_link_libraries(vulkan_scratch_test PRIVATE Vulkan::Headers) -if(MSVC) - target_compile_options(vulkan_scratch_test PRIVATE /W4 /permissive- /utf-8) -endif() -if(BUILD_TESTING) - add_test(NAME vulkan_scratch COMMAND vulkan_scratch_test) -endif() -if(WIN32 AND BUILD_TESTING) - # VulkanPresenter tracker lock / failed-submit rollback and capture-buffer WAW synchronization. - add_executable(vk_presenter_sync_test test/vk_presenter_sync_test.cpp) - target_link_libraries(vk_presenter_sync_test PRIVATE Vulkan::Headers user32) - target_compile_definitions(vk_presenter_sync_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) - if(MSVC) - target_compile_options(vk_presenter_sync_test PRIVATE /W4 /permissive- /utf-8) - endif() - add_test(NAME vk_presenter_sync COMMAND vk_presenter_sync_test) - set_tests_properties(vk_presenter_sync PROPERTIES SKIP_RETURN_CODE 77) -endif() -if(NOT Vulkan_GLSLANG_VALIDATOR_EXECUTABLE) - find_program(Vulkan_GLSLANG_VALIDATOR_EXECUTABLE glslangValidator HINTS "$ENV{VULKAN_SDK}/Bin" "$ENV{VULKAN_SDK}/bin") -endif() -if(Vulkan_GLSLANG_VALIDATOR_EXECUTABLE) - add_executable(vk_binary_occlusion_test test/vk_binary_occlusion_test.cpp) - target_link_libraries(vk_binary_occlusion_test PRIVATE Vulkan::Headers ${CMAKE_DL_LIBS}) - if(WIN32) - target_compile_definitions(vk_binary_occlusion_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) - endif() - foreach(stage vert frag) - set(source "${CMAKE_CURRENT_SOURCE_DIR}/test/glsl/binary_occlusion.${stage}") - set(output "${CMAKE_CURRENT_BINARY_DIR}/binary_occlusion.${stage}.spv") - add_custom_command(OUTPUT "${output}" - COMMAND "${Vulkan_GLSLANG_VALIDATOR_EXECUTABLE}" -V --target-env vulkan1.0 - -o "${output}" "${source}" - DEPENDS "${source}" VERBATIM) - target_sources(vk_binary_occlusion_test PRIVATE "${output}") - endforeach() - if(BUILD_TESTING) - add_test(NAME vk_binary_occlusion COMMAND vk_binary_occlusion_test - "${CMAKE_CURRENT_BINARY_DIR}/binary_occlusion.vert.spv" - "${CMAKE_CURRENT_BINARY_DIR}/binary_occlusion.frag.spv") - set_tests_properties(vk_binary_occlusion PROPERTIES SKIP_RETURN_CODE 77) - endif() -endif() diff --git a/runtime/cmake/windows_runtime.cmake b/runtime/cmake/windows_runtime.cmake deleted file mode 100644 index e5fd04c3f..000000000 --- a/runtime/cmake/windows_runtime.cmake +++ /dev/null @@ -1,472 +0,0 @@ -# The Windows runtime: gta6rt.exe, the libraries its shims link (the root-signature fix, XTaskQueue, the TLS host -# DLL, GameInput on SDL3) and the shim test programs. Their add_test() calls are in runtime_tests.cmake. -# Included by runtime/CMakeLists.txt inside if(WIN32 AND LEONIDA_BUILD_WINDOWS_RUNTIME). - -# Custom CMAKE_CXX_FLAGS can replace MSVC's default /EHsc. Require C++ stack unwinding so error -# paths in the runtime and its libraries still destroy automatic objects when an exception leaves a frame. -if(CMAKE_CXX_COMPILER_ID STREQUAL "MSVC") - add_compile_options($<$:/EHsc>) -endif() - -# The d3d12_xs shim and its tests use version 1.2 root signatures (D3D12_ROOT_SIGNATURE_DESC2), which the Windows -# SDK declares from 10.0.26100 on. Stop here with the fix instead of failing halfway through the build. -include(CheckCXXSourceCompiles) -check_cxx_source_compiles([=[ - #include - int main() { D3D12_VERSIONED_ROOT_SIGNATURE_DESC d{}; d.Version = D3D_ROOT_SIGNATURE_VERSION_1_2; - return static_cast(sizeof(d.Desc_1_2)); } -]=] GTA6RT_SDK_HAS_ROOT_SIGNATURE_1_2) -if(NOT GTA6RT_SDK_HAS_ROOT_SIGNATURE_1_2) - if(CMAKE_VS_WINDOWS_TARGET_PLATFORM_VERSION) - set(_gta6rt_sdk "${CMAKE_VS_WINDOWS_TARGET_PLATFORM_VERSION}") - elseif(DEFINED ENV{WindowsSDKVersion}) - string(REGEX REPLACE "[\\/]+$" "" _gta6rt_sdk "$ENV{WindowsSDKVersion}") - else() - set(_gta6rt_sdk "an older one") - endif() - message(FATAL_ERROR - "gta6rt needs the Windows SDK 10.0.26100 or newer (version 1.2 root signatures); " - "this build uses ${_gta6rt_sdk}. Install it with " - "`winget install Microsoft.WindowsSDK.10.0.26100` or the Visual Studio Installer, then delete the build " - "folder and configure again.") -endif() - -# Root-signature flag fix, shared by the d3d12_xs shim and its tests. -add_library(gta6rt_d3d12_xs_rootsig STATIC - shims/d3d12_xs_rootsig.cpp -) -target_include_directories(gta6rt_d3d12_xs_rootsig PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/shims) -target_compile_definitions(gta6rt_d3d12_xs_rootsig PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) -target_compile_options(gta6rt_d3d12_xs_rootsig PRIVATE /W4 /permissive- /utf-8) - -# XTaskQueue/XAsync from microsoft/libHttpClient (MIT), vendored in third_party/xtaskqueue; shims/xtaskqueue/pch.h -# stands in for libHttpClient's pch.h so only the task queue builds. Used by the xgameruntime shim. -set(XTASKQUEUE_DIR ${CMAKE_CURRENT_SOURCE_DIR}/../third_party/xtaskqueue) -add_library(gta6rt_xtaskqueue STATIC - ${XTASKQUEUE_DIR}/Source/Task/TaskQueue.cpp - ${XTASKQUEUE_DIR}/Source/Task/AsyncLib.cpp - ${XTASKQUEUE_DIR}/Source/Task/ThreadPool_win32.cpp - ${XTASKQUEUE_DIR}/Source/Task/WaitTimer_win32.cpp -) -target_include_directories(gta6rt_xtaskqueue - PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/shims/xtaskqueue ${XTASKQUEUE_DIR}/Source/Task ${XTASKQUEUE_DIR}/Source/Common - PUBLIC ${XTASKQUEUE_DIR}/Include) -target_compile_definitions(gta6rt_xtaskqueue PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) -target_compile_options(gta6rt_xtaskqueue PRIVATE /utf-8) # third-party code: its own warning level -target_link_libraries(gta6rt_xtaskqueue PUBLIC ole32) - -# Reserves one loader-assigned module TLS index for mapped images. Loaded from the executable's directory by -# Loader::initialize_tls; its trivial DllMain only keeps the TLS anchor in the image. Built in the same directory as -# the executables that map images, because the loader looks for it next to the running EXE. -add_library(gta6rt_tls_host SHARED src/tls_host.cpp) -target_compile_options(gta6rt_tls_host PRIVATE /W4 /permissive- /utf-8 /GS-) -target_compile_definitions(gta6rt_tls_host PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) -set_target_properties(gta6rt_tls_host PROPERTIES - OUTPUT_NAME gta6rt_tls_host - PREFIX "" - MSVC_RUNTIME_LIBRARY "MultiThreaded$<$:Debug>" -) - -add_executable(gta6rt - src/main.cpp - src/host_cpu.cpp - src/pe_loader.cpp - shims/registry.cpp - shims/file_system.cpp - shims/winhttp_offline.cpp - shims/xmem.cpp - shims/xg_xs.cpp - shims/acphal.cpp - shims/d3d12_xs.cpp - shims/d3d12_xs_device.cpp - shims/xgameruntime.cpp - shims/xgameruntime_user.cpp - shims/xgameruntime_gamesave.cpp - shims/xgameruntime_store.cpp - shims/xgameruntime_offline.cpp - shims/library_loader.cpp - shims/process.cpp - shims/com_shim.cpp - shims/bcrypt_rng.cpp - shims/xapu_chad.cpp - shims/dstorage.cpp -) -# dstorage.cpp's guarded_move turns an access violation in a title's buffer into E_DSTORAGE_ACCESS_VIOLATION with -# __try. MSVC always catches it; clang-cl only with asynchronous exceptions (as for tiny_dll below). A source file -# property, so gta6rt and dstorage_test both get it. -set_source_files_properties(shims/dstorage.cpp PROPERTIES COMPILE_OPTIONS "$<$:/EHa>") -add_dependencies(gta6rt gta6rt_tls_host) -target_compile_definitions(gta6rt PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX UNICODE _UNICODE) -target_compile_options(gta6rt PRIVATE /W4 /permissive- /utf-8) -# Static shim tables register themselves at startup; keep the linker from dropping their objects. -# GTA6RT_HOST_BASE keeps the loader's own image off the default x64 EXE base (0x140000000), where a mapped EXE -# without relocations wants to go. Windows moves the EXE with ASLR anyway; Wine loads it at its preferred base. -set(GTA6RT_HOST_BASE /BASE:0x10000000000) -# BUILD-1457: a thread that asks for no stack size gets the reserve in this program's PE header, 1 MB by default: -# a thread the game starts with dwStackSize 0, a thread-pool thread, a std::thread of the shims. The D3D12 shim -# creates Vulkan pipelines on the calling thread, the driver compiles there, and AMD's Windows compiler (26.11.2) -# overflows 1 MB on some of the game's shaders (docs/pipeline_check.md, "Stack reserve"). run_entry already gives -# the entry thread 8 MB (shims/process_shim.h); this is the same number for the others. Keep it in step with -# scripts/build_runtime.ps1. -set(GTA6RT_STACK 8388608) -target_link_options(gta6rt PRIVATE /OPT:NOREF ${GTA6RT_HOST_BASE} /STACK:${GTA6RT_STACK}) -target_link_libraries(gta6rt PRIVATE gta6rt_core gta6rt_d3d12_xs_rootsig gta6rt_xtaskqueue psapi) - -# Root-signature forwarding test: needs a real PC d3d12.lib to serialize the synthetic descriptors. -# find_library searches %LIB% (a Developer Prompt), not the Windows SDK the Visual Studio generator links -# against, so also look in that SDK's um/x64 folder. -set(_sdk_lib_hints) -if(DEFINED ENV{WindowsSdkDir} AND DEFINED ENV{WindowsSDKLibVersion}) - list(APPEND _sdk_lib_hints "$ENV{WindowsSdkDir}Lib/$ENV{WindowsSDKLibVersion}um/x64") -endif() -get_filename_component(_kits_root - "[HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Windows Kits\\Installed Roots;KitsRoot10]" ABSOLUTE) -if(CMAKE_VS_WINDOWS_TARGET_PLATFORM_VERSION AND EXISTS "${_kits_root}") - list(APPEND _sdk_lib_hints "${_kits_root}/Lib/${CMAKE_VS_WINDOWS_TARGET_PLATFORM_VERSION}/um/x64") -endif() -find_library(D3D12_LIBRARY NAMES d3d12 HINTS ${_sdk_lib_hints}) -find_library(DXGI_LIBRARY NAMES dxgi HINTS ${_sdk_lib_hints}) -if(D3D12_LIBRARY) - add_executable(root_sig_test - test/root_sig_test.cpp - shims/registry.cpp - shims/d3d12_xs.cpp - shims/d3d12_xs_device.cpp - ) - target_link_libraries(root_sig_test PRIVATE gta6rt_d3d12_xs_rootsig ${D3D12_LIBRARY}) - target_compile_definitions(root_sig_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) - target_compile_options(root_sig_test PRIVATE /W4 /permissive- /utf-8) - target_link_options(root_sig_test PRIVATE /OPT:NOREF) - - # RTS0 parser oracle: synthetic descriptors only, serialized by the real PC - # d3d12.dll and parsed back by rt::rootsig::parse_rts0. A layout mismatch - # fails here with the blob bytes, never silently in a draw. - add_executable(root_signature_oracle_test - test/root_signature_oracle_test.cpp - ) - target_link_libraries(root_signature_oracle_test PRIVATE gta6rt_root_signature ${D3D12_LIBRARY}) - target_compile_definitions(root_signature_oracle_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) - target_compile_options(root_signature_oracle_test PRIVATE /W4 /permissive- /utf-8) - target_link_options(root_signature_oracle_test PRIVATE /OPT:NOREF) - - # Xbox-ABI device proxy test: WARP PC device, no game executable. Needs DXGI for the WARP adapter. - if(DXGI_LIBRARY) - add_executable(device_proxy_test - test/device_proxy_test.cpp - shims/registry.cpp - shims/d3d12_xs.cpp - shims/d3d12_xs_device.cpp - ) - target_link_libraries(device_proxy_test PRIVATE gta6rt_d3d12_xs_rootsig ${D3D12_LIBRARY} ${DXGI_LIBRARY}) - target_compile_definitions(device_proxy_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) - target_compile_options(device_proxy_test PRIVATE /W4 /permissive- /utf-8) - target_link_options(device_proxy_test PRIVATE /OPT:NOREF) - else() - message(STATUS "dxgi.lib not found: device_proxy_test is not built") - endif() - # The queue and fence proxies over synthetic COM objects: no D3D12 runtime, no GPU. Replaces operator new and - # patches its own import table to inject failures, so the proxy source is compiled into it alone. - add_executable(xs_proxy_mock_test - test/xs_proxy_mock_test.cpp - shims/d3d12_xs_device.cpp - ) - target_compile_definitions(xs_proxy_mock_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) - target_compile_options(xs_proxy_mock_test PRIVATE /W4 /permissive- /utf-8 /EHsc) -else() - message(STATUS "d3d12.lib not found: root_sig_test and device_proxy_test are not built") -endif() - -# xmem shim ABI test: resolves the registered xmem.dll exports itself, so xmem.cpp and registry.cpp are compiled -# into this executable instead of reusing gta6rt's objects (which would duplicate their symbols). -add_executable(xmem_test - test/xmem_test.cpp - shims/xmem.cpp - shims/registry.cpp -) -target_include_directories(xmem_test PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/shims) -target_compile_definitions(xmem_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) -target_compile_options(xmem_test PRIVATE /W4 /permissive- /utf-8 $<$:/EHa>) -target_link_options(xmem_test PRIVATE /OPT:NOREF) -target_link_libraries(xmem_test PRIVATE psapi) - -# xg_xs shim: the two exports and the texture computer's slots against the measured call shapes. -add_executable(xg_xs_test - test/xg_xs_test.cpp - shims/xg_xs.cpp - shims/registry.cpp -) -target_include_directories(xg_xs_test PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/shims) -target_compile_definitions(xg_xs_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) -target_compile_options(xg_xs_test PRIVATE /W4 /permissive- /utf-8) -target_link_options(xg_xs_test PRIVATE /OPT:NOREF) - -# acphal shim ABI test: resolves the registered acphal.dll exports through the registry. -add_executable(acphal_test - test/acphal_test.cpp - shims/acphal.cpp - shims/registry.cpp -) -target_include_directories(acphal_test PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/shims) -target_compile_definitions(acphal_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) -target_compile_options(acphal_test PRIVATE /W4 /permissive- /utf-8) -target_link_options(acphal_test PRIVATE /OPT:NOREF) - -# The Zen 2 instructions a desktop CPU may lack (src/cpu_emulation.h): decoded, emulated on a CONTEXT, and run for -# real with the #UD handler installed, so an Intel host takes the emulated path and an AMD one the native path. -add_executable(cpu_emulation_test test/cpu_emulation_test.cpp) -target_include_directories(cpu_emulation_test PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/src) -target_compile_definitions(cpu_emulation_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) -target_compile_options(cpu_emulation_test PRIVATE /W4 /permissive- /utf-8) - -# Xbox DirectStorage (DStorageGetFactory under dstorage_xs.dll, xcrdapi.dll and dstorage.dll) over synthetic files: -# GAME: paths through the file shims, queues, status arrays, fences and errors. No GPU, no game data. -add_executable(dstorage_test - test/dstorage_test.cpp - shims/dstorage.cpp - shims/file_system.cpp - shims/registry.cpp -) -target_include_directories(dstorage_test PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/shims) -target_compile_definitions(dstorage_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) -target_compile_options(dstorage_test PRIVATE /W4 /permissive- /utf-8) -target_link_options(dstorage_test PRIVATE /OPT:NOREF) - -# xapu.dll and chad.dll, the APU and audio DSP command queues, resolved through the registry like xmem_test. -add_executable(xapu_chad_test - test/xapu_chad_test.cpp - shims/xapu_chad.cpp - shims/registry.cpp -) -target_include_directories(xapu_chad_test PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/shims) -target_compile_definitions(xapu_chad_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) -target_compile_options(xapu_chad_test PRIVATE /W4 /permissive- /utf-8) -target_link_options(xapu_chad_test PRIVATE /OPT:NOREF) - -# The process shim's command line: GetCommandLineW must parse (CommandLineToArgvW) back to its __wargv. -add_executable(process_cmdline_test - test/process_cmdline_test.cpp - shims/process.cpp - shims/registry.cpp -) -target_include_directories(process_cmdline_test PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/shims) -target_compile_definitions(process_cmdline_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) -target_compile_options(process_cmdline_test PRIVATE /W4 /permissive- /utf-8) -target_link_options(process_cmdline_test PRIVATE /OPT:NOREF) -target_link_libraries(process_cmdline_test PRIVATE shell32) - -# Console paths (GAME:) and the write overlay: the file shims resolved through the registry, over temporary folders. -add_executable(file_system_test - test/file_system_test.cpp - shims/file_system.cpp - shims/registry.cpp -) -target_include_directories(file_system_test PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/shims) -target_compile_definitions(file_system_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) -target_compile_options(file_system_test PRIVATE /W4 /permissive- /utf-8) -target_link_options(file_system_test PRIVATE /OPT:NOREF) -target_link_libraries(file_system_test PRIVATE advapi32) # the ACL calls of the unlistable-marker-folder check - -# loader.skip_int3 (LEONIDA_SKIP_INT3; shims/startup_trace.h): its own executable, the switch is for the whole process. -add_executable(int3_skip_test - test/int3_skip_test.cpp - shims/registry.cpp -) -target_include_directories(int3_skip_test PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/shims) -target_compile_definitions(int3_skip_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) -target_compile_options(int3_skip_test PRIVATE /W4 /permissive- /utf-8) -target_link_options(int3_skip_test PRIVATE /OPT:NOREF) - -# Offline WinHTTP for mapped images (the package's XCurl.dll and libHttpClient.GDK.dll); no network is touched. -add_executable(winhttp_offline_test - test/winhttp_offline_test.cpp - shims/winhttp_offline.cpp - shims/registry.cpp -) -target_include_directories(winhttp_offline_test PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/shims) -target_compile_definitions(winhttp_offline_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) -target_compile_options(winhttp_offline_test PRIVATE /W4 /permissive- /utf-8) -target_link_options(winhttp_offline_test PRIVATE /OPT:NOREF) - -# COM lifecycle and helper shims for api-ms-win-core-com-l1-1-*.dll. -add_executable(com_shim_test - test/com_shim_test.cpp - shims/com_shim.cpp - shims/registry.cpp -) -target_include_directories(com_shim_test PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/shims) -target_compile_definitions(com_shim_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) -target_compile_options(com_shim_test PRIVATE /W4 /permissive- /utf-8) -target_link_options(com_shim_test PRIVATE /OPT:NOREF) - -# BCrypt RNG and algorithm provider shims. -add_executable(bcrypt_rng_test - test/bcrypt_rng_test.cpp - shims/bcrypt_rng.cpp - shims/registry.cpp -) -target_include_directories(bcrypt_rng_test PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/shims) -target_compile_definitions(bcrypt_rng_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) -target_compile_options(bcrypt_rng_test PRIVATE /W4 /permissive- /utf-8) -target_link_options(bcrypt_rng_test PRIVATE /OPT:NOREF) - -# Synthetic tests for the atomic API reference lifecycle. -add_executable(api_ref_state_test test/api_ref_state_test.cpp) -target_include_directories(api_ref_state_test PRIVATE - ${XTASKQUEUE_DIR}/Source/Task) -target_compile_definitions(api_ref_state_test PRIVATE - WIN32_LEAN_AND_MEAN NOMINMAX) -target_compile_options(api_ref_state_test PRIVATE - /W4 /permissive- /utf-8) -# Verify global reference accounting during task queue teardown. -add_executable(api_global_refs_test test/api_global_refs_test.cpp) -target_compile_definitions(api_global_refs_test PRIVATE - WIN32_LEAN_AND_MEAN NOMINMAX) -target_compile_options(api_global_refs_test PRIVATE - /W4 /permissive- /utf-8) -target_link_libraries(api_global_refs_test PRIVATE - gta6rt_xtaskqueue) -# Offline GDK runtime shim (XGameRuntime, XSystem, XTaskQueue, XAsync), driven through the shim registry the way -# a title calls it at boot. Like xmem_test it compiles its own registry.cpp. -add_executable(xgameruntime_test - test/xgameruntime_test.cpp - shims/xgameruntime.cpp - shims/xgameruntime_user.cpp - shims/xgameruntime_gamesave.cpp - shims/xgameruntime_store.cpp - shims/xgameruntime_offline.cpp - shims/library_loader.cpp - shims/registry.cpp - shims/file_system.cpp -) -target_include_directories(xgameruntime_test PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/shims) -target_compile_definitions(xgameruntime_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) -target_compile_options(xgameruntime_test PRIVATE /W4 /permissive- /utf-8) -target_link_options(xgameruntime_test PRIVATE /OPT:NOREF) -target_link_libraries(xgameruntime_test PRIVATE gta6rt_xtaskqueue) - -# XUserImpl (offline local user) through QueryApiImpl, slot by slot as xgameruntime.lib's thunks call it. -add_executable(xgameruntime_user_test - test/xgameruntime_user_test.cpp - shims/xgameruntime.cpp - shims/xgameruntime_user.cpp - shims/xgameruntime_gamesave.cpp - shims/xgameruntime_store.cpp - shims/xgameruntime_offline.cpp - shims/library_loader.cpp - shims/registry.cpp - shims/file_system.cpp -) -target_include_directories(xgameruntime_user_test PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/shims) -target_compile_definitions(xgameruntime_user_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) -target_compile_options(xgameruntime_user_test PRIVATE /W4 /permissive- /utf-8) -target_link_options(xgameruntime_user_test PRIVATE /OPT:NOREF) -target_link_libraries(xgameruntime_user_test PRIVATE gta6rt_xtaskqueue) - -# XGameSaveImpl (offline saves in LEONIDA_SAVE_DIR) through QueryApiImpl, slot by slot. -add_executable(xgameruntime_gamesave_test - test/xgameruntime_gamesave_test.cpp - shims/xgameruntime.cpp - shims/xgameruntime_user.cpp - shims/xgameruntime_gamesave.cpp - shims/xgameruntime_store.cpp - shims/xgameruntime_offline.cpp - shims/library_loader.cpp - shims/registry.cpp - shims/file_system.cpp -) -target_include_directories(xgameruntime_gamesave_test PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/shims) -target_compile_definitions(xgameruntime_gamesave_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) -target_compile_options(xgameruntime_gamesave_test PRIVATE /W4 /permissive- /utf-8) -target_link_options(xgameruntime_gamesave_test PRIVATE /OPT:NOREF) -target_link_libraries(xgameruntime_gamesave_test PRIVATE gta6rt_xtaskqueue) - -# XStoreImpl (offline: the game is owned, no add-ons, no updates) through QueryApiImpl, slot by slot. -add_executable(xgameruntime_store_test - test/xgameruntime_store_test.cpp - shims/xgameruntime.cpp - shims/xgameruntime_user.cpp - shims/xgameruntime_gamesave.cpp - shims/xgameruntime_store.cpp - shims/xgameruntime_offline.cpp - shims/library_loader.cpp - shims/registry.cpp - shims/file_system.cpp -) -target_include_directories(xgameruntime_store_test PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/shims) -target_compile_definitions(xgameruntime_store_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) -target_compile_options(xgameruntime_store_test PRIVATE /W4 /permissive- /utf-8) -target_link_options(xgameruntime_store_test PRIVATE /OPT:NOREF) -target_link_libraries(xgameruntime_store_test PRIVATE gta6rt_xtaskqueue) - -# XGameEventImpl, XGameUiImpl, XGameStreamingImpl (offline) through QueryApiImpl. -add_executable(xgameruntime_offline_test - test/xgameruntime_offline_test.cpp - shims/xgameruntime.cpp - shims/xgameruntime_user.cpp - shims/xgameruntime_gamesave.cpp - shims/xgameruntime_store.cpp - shims/xgameruntime_offline.cpp - shims/library_loader.cpp - shims/registry.cpp - shims/file_system.cpp -) -target_include_directories(xgameruntime_offline_test PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/shims) -target_compile_definitions(xgameruntime_offline_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) -target_compile_options(xgameruntime_offline_test PRIVATE /W4 /permissive- /utf-8) -target_link_options(xgameruntime_offline_test PRIVATE /OPT:NOREF) -target_link_libraries(xgameruntime_offline_test PRIVATE gta6rt_xtaskqueue) - -# GameInput shim on SDL3 (zlib licence): any controller SDL supports, DualSense trigger effects and lightbar. -# Nothing is downloaded unless asked. The shim is built when SDL3 is available: -# - an installed SDL3 3.2+ that find_package finds (SDL3_DIR / CMAKE_PREFIX_PATH), or -# - -DLEONIDA_SDL3_FETCH=ON: download the pinned release below once at configure time (hash-checked) and build it -# static, or -DFETCHCONTENT_SOURCE_DIR_SDL3= to build that copy without downloading. -# Otherwise, or with -DLEONIDA_SDL3=OFF, gta6rt is built without the shim and the loader binds GameInputCreate to the -# host's GameInput.dll or the unimplemented thunk as before. docs/gameinput.md has the details. -option(LEONIDA_SDL3 "Build the GameInput shim when SDL3 is available" ON) -option(LEONIDA_SDL3_FETCH "Download the pinned SDL3 release if no installed SDL3 is found" OFF) -if(LEONIDA_SDL3) - find_package(SDL3 3.2 CONFIG QUIET COMPONENTS SDL3-static NO_SYSTEM_ENVIRONMENT_PATH) - if(NOT TARGET SDL3::SDL3-static AND (LEONIDA_SDL3_FETCH OR FETCHCONTENT_SOURCE_DIR_SDL3)) - include(FetchContent) - FetchContent_Declare(SDL3 - URL https://github.com/libsdl-org/SDL/releases/download/release-3.4.20/SDL3-3.4.20.tar.gz - URL_HASH SHA256=f3bb06f55bed9557227a700af2ea62e49497ebdf58037732a731a5fb3ef8581f - DOWNLOAD_EXTRACT_TIMESTAMP TRUE) - # Only what gamepads need: the joystick, HIDAPI, haptic, sensor and power code, in a static library. - set(SDL_SHARED OFF CACHE BOOL "" FORCE) - set(SDL_STATIC ON CACHE BOOL "" FORCE) - set(SDL_TEST_LIBRARY OFF CACHE BOOL "" FORCE) - set(SDL_TESTS OFF CACHE BOOL "" FORCE) - set(SDL_EXAMPLES OFF CACHE BOOL "" FORCE) - set(SDL_INSTALL OFF CACHE BOOL "" FORCE) - set(SDL_DISABLE_INSTALL ON CACHE BOOL "" FORCE) - foreach(_sdl_off SDL_AUDIO SDL_VIDEO SDL_GPU SDL_RENDER SDL_CAMERA SDL_DIALOG SDL_TRAY) - set(${_sdl_off} OFF CACHE BOOL "" FORCE) - endforeach() - FetchContent_MakeAvailable(SDL3) - endif() -endif() -if(LEONIDA_SDL3 AND TARGET SDL3::SDL3-static) - target_sources(gta6rt PRIVATE shims/gameinput.cpp) - target_link_libraries(gta6rt PRIVATE SDL3::SDL3-static) - - # GameInput through the shim registry on SDL virtual joysticks: no controller, no game data. - add_executable(gameinput_test test/gameinput_test.cpp shims/gameinput.cpp shims/registry.cpp) - # gameinput_probe: the same shim on a real controller, run by hand (not a CTest). - add_executable(gameinput_probe test/gameinput_probe.cpp shims/gameinput.cpp shims/registry.cpp) - foreach(_gi gameinput_test gameinput_probe) - target_include_directories(${_gi} PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/shims) - target_compile_definitions(${_gi} PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) - target_compile_options(${_gi} PRIVATE /W4 /permissive- /utf-8) - target_link_options(${_gi} PRIVATE /OPT:NOREF) - target_link_libraries(${_gi} PRIVATE SDL3::SDL3-static) - endforeach() -else() - if(LEONIDA_SDL3) - message(STATUS "GameInput shim not built: no installed SDL3 found. Set SDL3_DIR, or pass -DLEONIDA_SDL3_FETCH=ON " - "to download the pinned SDL3 release (see docs/gameinput.md)") - else() - message(STATUS "GameInput shim not built (LEONIDA_SDL3=OFF)") - endif() -endif() diff --git a/runtime/core/config.cpp b/runtime/core/config.cpp deleted file mode 100644 index ed046b75a..000000000 --- a/runtime/core/config.cpp +++ /dev/null @@ -1,353 +0,0 @@ -#include "config.h" - -#include -#include -#include -#include -#include -#include - -#if defined(_WIN32) -#include -#else -#include -#endif - -namespace rt::config { - -namespace { - -// ---- text, paths and the environment ---- - -#if defined(_WIN32) -// Flags 0 in both directions: a character that cannot be converted is replaced, so neither conversion fails. -std::string narrow(std::wstring_view wide) { - if (wide.empty()) return {}; - const int size = WideCharToMultiByte(CP_UTF8, 0, wide.data(), static_cast(wide.size()), nullptr, 0, nullptr, - nullptr); - if (size <= 0) return {}; - std::string text(static_cast(size), '\0'); - WideCharToMultiByte(CP_UTF8, 0, wide.data(), static_cast(wide.size()), text.data(), size, nullptr, nullptr); - return text; -} - -std::wstring widen(std::string_view text) { - if (text.empty()) return {}; - const int size = MultiByteToWideChar(CP_UTF8, 0, text.data(), static_cast(text.size()), nullptr, 0); - if (size <= 0) return {}; - std::wstring wide(static_cast(size), L'\0'); - MultiByteToWideChar(CP_UTF8, 0, text.data(), static_cast(text.size()), wide.data(), size); - return wide; -} - -std::string to_utf8(const std::filesystem::path& p) { return narrow(p.native()); } -std::filesystem::path to_path(std::string_view text) { return std::filesystem::path(widen(text)); } -#else -std::string to_utf8(const std::filesystem::path& p) { return p.string(); } -std::filesystem::path to_path(std::string_view text) { return std::filesystem::path(std::string(text)); } -#endif - -// The variable's value in UTF-8; nullopt when it is unset or empty, which get() treats alike. -std::optional environment(const char* variable) { -#if defined(_WIN32) - // GetEnvironmentVariableW and not getenv: the CRT's copy of the environment does not follow - // SetEnvironmentVariable, which the tests use to set a variable in their own process. The thread's last error - // is put back, because shims read settings in the middle of a call from the title. - const DWORD last_error = GetLastError(); - std::wstring name; - for (const char* c = variable; *c; ++c) name.push_back(static_cast(static_cast(*c))); - std::wstring wide(260, L'\0'); - DWORD length = 0; - for (;;) { - length = GetEnvironmentVariableW(name.c_str(), wide.data(), static_cast(wide.size())); - if (length < wide.size()) break; // 0: unset or empty; else the length without the terminator - wide.resize(static_cast(length) + 1); // too small: `length` is the size the value needs - } - SetLastError(last_error); - if (length == 0) return std::nullopt; - wide.resize(length); - return narrow(wide); -#else - const char* value = std::getenv(variable); - if (!value || !*value) return std::nullopt; - return std::string(value); -#endif -} - -// ---- the loaded file ---- - -struct Loaded { - std::mutex mutex; - FileValues values; - std::filesystem::path file; -}; - -// Never destroyed: a thread of the title may still read a setting while the process exits. -Loaded& loaded() { - static Loaded* const state = new Loaded; - return *state; -} - -// ---- the file format ---- - -constexpr bool is_blank(char c) { return c == ' ' || c == '\t' || c == '\r'; } -constexpr bool is_digit(char c) { return c >= '0' && c <= '9'; } - -std::string_view trim(std::string_view s) { - while (!s.empty() && is_blank(s.front())) s.remove_prefix(1); - while (!s.empty() && is_blank(s.back())) s.remove_suffix(1); - return s; -} - -// A section or setting name as TOML allows it without quotes: letters, digits, _ and -. -bool is_name(std::string_view s) { - if (s.empty()) return false; - for (const char c : s) - if (!(is_digit(c) || (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || c == '_' || c == '-')) return false; - return true; -} - -// A number in the forms a setting uses: 30, -1, 1.5, 0x1f. -bool is_number(std::string_view s) { - const bool has_sign = !s.empty() && (s.front() == '+' || s.front() == '-'); - if (has_sign) s.remove_prefix(1); - if (!has_sign && s.size() > 2 && s[0] == '0' && s[1] == 'x') { - for (const char c : s.substr(2)) - if (!(is_digit(c) || (c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F'))) return false; - return true; - } - std::size_t i = 0; - while (i < s.size() && is_digit(s[i])) ++i; - if (i == 0) return false; - if (i == s.size()) return true; - if (s[i] != '.') return false; - const std::size_t fraction = ++i; - while (i < s.size() && is_digit(s[i])) ++i; - return i > fraction && i == s.size(); -} - -bool has_section(std::string_view section) { - for (const Setting& setting : kSettings) { - const std::string_view key = setting.key; - if (key.size() > section.size() && key[section.size()] == '.' && key.substr(0, section.size()) == section) - return true; - } - return false; -} - -// True when nothing but a comment follows. -bool ends_here(std::string_view rest) { - rest = trim(rest); - return rest.empty() || rest.front() == '#'; -} - -// The value `rest` starts with, as the text get() returns. False with the reason in *what when it is not a value -// this reader takes or something other than a comment follows it. -bool read_value(std::string_view rest, std::string* value, std::string* what) { - value->clear(); - std::size_t end = 0; - if (rest.empty() || rest.front() == '#') { - *what = "the value after = is missing"; - return false; - } - if (rest.front() == '\'') { - const std::size_t close = rest.find('\'', 1); - if (close == std::string_view::npos) { - *what = "the closing ' is missing"; - return false; - } - value->assign(rest.substr(1, close - 1)); - end = close + 1; - } else if (rest.front() == '"') { - std::size_t i = 1; - for (;; ++i) { - if (i == rest.size()) { - *what = "the closing \" is missing"; - return false; - } - if (rest[i] == '"') break; - if (rest[i] == '\\') { - if (i + 1 == rest.size() || (rest[i + 1] != '\\' && rest[i + 1] != '"')) { - *what = "in double quotes a backslash starts an escape, and only \\\\ and \\\" are read here; " - "write a Windows path in single quotes"; - return false; - } - ++i; - } - value->push_back(rest[i]); - } - end = i + 1; - } else { - while (end < rest.size() && !is_blank(rest[end]) && rest[end] != '#') ++end; - const std::string_view word = rest.substr(0, end); - if (word == "true") *value = "1"; - else if (word == "false") *value = "0"; - else if (is_number(word)) value->assign(word); - else { - *what = "the value must be text in quotes, a number, true or false"; - return false; - } - } - if (!ends_here(rest.substr(end))) { - *what = "only a # comment may follow the value"; - return false; - } - return true; -} - -std::string padded(std::string_view text, std::size_t width) { - std::string out(text); - if (out.size() < width) out.append(width - out.size(), ' '); - return out; -} - -} // namespace - -std::optional Name::find(std::string_view key_or_variable) { - for (std::size_t i = 0; i < kSettingCount; ++i) - if (key_or_variable == kSettings[i].key || key_or_variable == kSettings[i].variable) return at(i); - return std::nullopt; -} - -const char* source_name(Source source) { - switch (source) { - case Source::Environment: return "environment"; - case Source::File: return "file"; - default: return "default"; - } -} - -Value get(Name name) { - const Setting& setting = name.setting(); - if (auto value = environment(setting.variable)) return Value{std::move(*value), Source::Environment}; - { - Loaded& state = loaded(); - const std::lock_guard lock(state.mutex); - if (const auto& value = state.values[name.index()]) return Value{*value, Source::File}; - } - return Value{setting.fallback, Source::Default}; -} - -std::filesystem::path path(Name name) { return to_path(get(name).text); } - -bool parse(std::string_view text, std::string_view file_name, FileValues* values, std::string* error) { - FileValues found; - std::array seen{}; // apart from `found`: a setting set to '' is seen and stays unset - std::vector sections; - std::string_view section; - std::size_t line_number = 0; - const auto fail = [&](const std::string& what) { - if (error) *error = std::string(file_name) + ":" + std::to_string(line_number) + ": " + what; - return false; - }; - - if (text.starts_with("\xEF\xBB\xBF")) text.remove_prefix(3); // a UTF-8 byte order mark, as Notepad writes it - while (!text.empty()) { - ++line_number; - const std::size_t newline = text.find('\n'); - const std::string_view line = trim(text.substr(0, newline)); - text.remove_prefix(newline == std::string_view::npos ? text.size() : newline + 1); - if (line.empty() || line.front() == '#') continue; - - if (line.front() == '[') { - const std::size_t close = line.find(']'); - if (close == std::string_view::npos) return fail("the closing ] is missing"); - const std::string_view name = trim(line.substr(1, close - 1)); - if (!is_name(name) || !has_section(name)) - return fail("there is no section [" + std::string(name) + "]"); - if (!ends_here(line.substr(close + 1))) return fail("only a # comment may follow a [section]"); - for (const std::string_view earlier : sections) - if (earlier == name) return fail("[" + std::string(name) + "] is in the file twice"); - sections.push_back(name); - section = name; - continue; - } - - const std::size_t equals = line.find('='); - const std::string_view name = trim(line.substr(0, equals)); - if (equals == std::string_view::npos || !is_name(name)) return fail("expected [section] or name = value"); - if (section.empty()) return fail("a setting needs its [section] line above it"); - const std::string key = std::string(section) + "." + std::string(name); - const std::size_t index = index_of_key(key); - if (index == kSettingCount) - return fail("there is no setting " + key + "; `gta6rt config` lists the settings"); - if (seen[index]) return fail(key + " is set twice"); - seen[index] = true; - std::string value, what; - if (!read_value(trim(line.substr(equals + 1)), &value, &what)) return fail(key + ": " + what); - if (!value.empty()) found[index] = std::move(value); - } - *values = std::move(found); - return true; -} - -bool load_file(const std::filesystem::path& file, std::string* error) { - const std::string name = to_utf8(file); - std::ifstream in(file, std::ios::binary); - const std::string text{std::istreambuf_iterator(in), std::istreambuf_iterator()}; - if (!in.is_open() || in.bad()) { - if (error) *error = name + ": cannot be read"; - return false; - } - FileValues values; - if (!parse(text, name, &values, error)) return false; - // Absolute, so that the report still names the file after the title has changed the current directory. - std::error_code failed; - std::filesystem::path absolute = std::filesystem::absolute(file, failed); - Loaded& state = loaded(); - const std::lock_guard lock(state.mutex); - state.values = std::move(values); - state.file = failed ? file : std::move(absolute); - return true; -} - -bool load(const std::filesystem::path& program_dir, std::string* error) { - std::error_code ignored; - if (const auto named = environment(kFileVariable)) { - const std::filesystem::path file = to_path(*named); - if (!std::filesystem::is_regular_file(file, ignored)) { - if (error) *error = std::string(kFileVariable) + " names " + *named + ", which is not a file"; - return false; - } - return load_file(file, error); - } - if (program_dir.empty()) return true; - const std::filesystem::path file = program_dir / kFileName; - if (!std::filesystem::is_regular_file(file, ignored)) return true; - return load_file(file, error); -} - -void unload() { - Loaded& state = loaded(); - const std::lock_guard lock(state.mutex); - state.values = {}; - state.file.clear(); -} - -std::filesystem::path loaded_file() { - Loaded& state = loaded(); - const std::lock_guard lock(state.mutex); - return state.file; -} - -std::string report() { - const std::filesystem::path file = loaded_file(); - std::string out = "settings file: "; - out += file.empty() ? std::string("none (") + kFileVariable + ", or " + kFileName + " next to the program)" - : to_utf8(file); - out += '\n'; - std::size_t key_width = 0, variable_width = 0; - for (const Setting& setting : kSettings) { - if (const std::size_t n = std::string_view(setting.key).size(); n > key_width) key_width = n; - if (const std::size_t n = std::string_view(setting.variable).size(); n > variable_width) variable_width = n; - } - for (std::size_t i = 0; i < kSettingCount; ++i) { - const Setting& setting = kSettings[i]; - const Value value = get(Name::at(i)); - out += padded(setting.key, key_width + 2) + padded(source_name(value.source), 13) + - padded(setting.variable, variable_width + 2) + (value.text.empty() ? "(not set)" : value.text) + '\n'; - } - return out; -} - -} // namespace rt::config diff --git a/runtime/core/config.h b/runtime/core/config.h deleted file mode 100644 index c63dbad38..000000000 --- a/runtime/core/config.h +++ /dev/null @@ -1,188 +0,0 @@ -// The runtime's settings: one table, looked up one way. -// -// Every setting has a name in leonida.toml ("section.name"), an environment variable and a default. A value is taken -// from the first of these that has one: the environment variable, the file, the default. The environment is read at -// each call and not cached, so a variable that a test or a launcher sets is seen by the next read. The file is read -// once, by load(). -// -// A reader names its setting with a string literal, and the name is checked when the code is compiled: -// -// if (rt::config::get("vulkan.validation").text != "0") ... -// -// A name that is not in kSettings does not build. A new setting gets a row in kSettings, a line in -// leonida.example.toml (test/core_config_test.cpp compares the two) and a line in a document -// (tests/test_docs_env_vars.py). -// -// Nothing here needs windows.h, so it is built and tested on every OS. -#pragma once - -#include -#include -#include -#include -#include -#include -#include - -namespace rt::config { - -struct Setting { - const char* key; // "section.name": [section] and name in leonida.toml - const char* variable; // the environment variable; when set, it wins over the file - const char* fallback; // the default as text; "" when the default is "not set" -}; - -// The defaults repeat what each reader does when nothing is set. What the values mean is in leonida.example.toml, -// runtime/README.md, docs/gameinput.md and docs/d3d12_vulkan.md. -inline constexpr Setting kSettings[] = { - {"paths.game_dir", "LEONIDA_GAME_DIR", ""}, - {"paths.save_dir", "LEONIDA_SAVE_DIR", ""}, - {"paths.shaders", "LEONIDA_SHADERS", ""}, - {"paths.compat_dir", "LEONIDA_COMPAT_DIR", ""}, - - {"loader.unimplemented", "LEONIDA_UNIMPLEMENTED", "log"}, - {"loader.tls_ga_patch", "LEONIDA_TLS_GA_PATCH", "1"}, - {"loader.skip_cpu_check", "LEONIDA_SKIP_CPU_CHECK", "0"}, - {"loader.skip_int3", "LEONIDA_SKIP_INT3", "0"}, - {"loader.rng_seed", "LEONIDA_RNG_SEED", ""}, - - {"log.level", "LEONIDA_LOG", "debug"}, // core/log.h - - {"system.device_type", "LEONIDA_DEVICE_TYPE", "7"}, - {"system.analytics_form", "LEONIDA_ANALYTICS_FORM", ""}, - {"system.package_id", "LEONIDA_PACKAGE_ID", "LeonidaPackageIdentifier00000000"}, - {"system.content_packages", "LEONIDA_CONTENT_PACKAGES", ""}, - {"system.packaged", "LEONIDA_PACKAGED", "1"}, - {"system.gamertag", "LEONIDA_GAMERTAG", "Player"}, - {"system.hdr", "LEONIDA_HDR", "0"}, - {"system.log_game_events", "LEONIDA_LOG_GAME_EVENTS", "0"}, - - {"d3d12.backend", "LEONIDA_D3D12", "host"}, - {"d3d12.xs_trace", "XS_TRACE", "0"}, - {"d3d12.frame_interval_slot", "LEONIDA_XS_FRAME_INTERVAL_SLOT", "78"}, - {"d3d12.schedule_event_slot", "LEONIDA_XS_SCHEDULE_EVENT_SLOT", "79"}, - {"d3d12.wait_event_slot", "LEONIDA_XS_WAIT_EVENT_SLOT", "80"}, - {"d3d12.queue_x_slot", "LEONIDA_XS_QUEUE_X_SLOT", "48"}, - {"d3d12.list_x_slot", "LEONIDA_XS_LIST_X_SLOT", "73"}, - {"d3d12.present_x_slot", "LEONIDA_XS_PRESENT_X_SLOT", ""}, - - {"vulkan.device", "LEONIDA_VK_DEVICE", ""}, - {"vulkan.validation", "LEONIDA_VK_VALIDATION", "0"}, - {"vulkan.max_queues_per_family", "LEONIDA_VK_MAX_QUEUES_PER_FAMILY", "16"}, - {"vulkan.graphics_family_only", "LEONIDA_VK_GRAPHICS_FAMILY_ONLY", "0"}, - {"vulkan.arena_mb", "LEONIDA_ARENA_MB", "256"}, - {"vulkan.arena_log", "LEONIDA_ARENA_LOG", "0"}, - {"vulkan.upload_sysmem", "LEONIDA_UPLOAD_SYSMEM", "0"}, - {"vulkan.bindless_idle_wait", "LEONIDA_BINDLESS_IDLE_WAIT", "0"}, - {"vulkan.rt_as", "LEONIDA_RT_AS", "xdxr"}, - - {"present.sdr_eotf", "LEONIDA_SDR_EOTF", "srgb"}, - {"present.uncap", "LEONIDA_PRESENT_UNCAP", "0"}, - {"present.no_tear", "LEONIDA_PRESENT_NO_TEAR", "0"}, - {"present.capture_dir", "LEONIDA_CAPTURE", ""}, - {"present.capture_every", "LEONIDA_CAPTURE_EVERY", "30"}, - {"present.capture_limit", "LEONIDA_CAPTURE_LIMIT", "24"}, - - {"input.prompts", "LEONIDA_PROMPTS", "auto"}, - {"input.prompts_switch_ms", "LEONIDA_PROMPTS_SWITCH_MS", "300"}, - {"input.ds_triggers", "LEONIDA_DS_TRIGGERS", "rumble"}, - {"input.ds_trigger_gain", "LEONIDA_DS_TRIGGER_GAIN", "1"}, - {"input.ds_trigger_freq", "LEONIDA_DS_TRIGGER_FREQ", "30"}, - {"input.ds_lightbar", "LEONIDA_DS_LIGHTBAR", ""}, - {"input.rumble", "LEONIDA_RUMBLE", "1"}, - {"input.thread", "LEONIDA_GAMEINPUT_THREAD", "1"}, - {"input.keyboard_pad", "LEONIDA_KEYBOARD_PAD", "off"}, - {"input.mouse_sensitivity", "LEONIDA_MOUSE_SENSITIVITY", "1"}, -}; -inline constexpr std::size_t kSettingCount = std::size(kSettings); - -// The settings file: the one this variable names, else kFileName in the folder of the program (load()). -inline constexpr char kFileVariable[] = "LEONIDA_CONFIG"; -inline constexpr char kFileName[] = "leonida.toml"; - -// The row of kSettings with this key; kSettingCount when there is none. -constexpr std::size_t index_of_key(std::string_view key) { - for (std::size_t i = 0; i < kSettingCount; ++i) - if (key == kSettings[i].key) return i; - return kSettingCount; -} - -namespace detail { -// Declared, never defined and not constexpr: Name's constructor reaches it only for a name that is not in kSettings, -// and the compiler reports that as an error at the place that wrote the name. -void this_setting_name_is_not_in_kSettings(); -} // namespace detail - -// A setting, by its key. Made from a string literal at compile time, so a misspelt key is a build error and a read -// costs no search. -class Name { -public: - consteval Name(const char* key) : index_(index_of_key(key)) { - if (index_ == kSettingCount) detail::this_setting_name_is_not_in_kSettings(); - } - - // For a name that is only known at run time (the file reader, a test): by key or by variable. - static std::optional find(std::string_view key_or_variable); - // The setting in row `index` of kSettings; `index` must be below kSettingCount. - static constexpr Name at(std::size_t index) { return Name(index, Row{}); } - - constexpr std::size_t index() const { return index_; } - constexpr const Setting& setting() const { return kSettings[index_]; } - -private: - struct Row {}; - constexpr Name(std::size_t index, Row) : index_(index) {} - - std::size_t index_; -}; - -enum class Source { Default, File, Environment }; - -// "default", "file" or "environment". -const char* source_name(Source source); - -struct Value { - std::string text; // UTF-8 - Source source = Source::Default; // where `text` comes from - - // True when the environment or the file gave the value, false when it is the default. - bool is_set() const { return source != Source::Default; } -}; - -// The setting's value: the environment variable if it is set and not empty, else what the loaded file says, else the -// default. Safe to call from any thread. -Value get(Name name); - -// The same value as a path; empty when the setting is not set. -std::filesystem::path path(Name name); - -// What a settings file sets, one entry per row of kSettings. -using FileValues = std::array, kSettingCount>; - -// Reads `text` as a settings file. The format is the part of TOML the file needs: [section] lines, `name = value` -// lines and # comments, where a value is text in single quotes (taken as written) or double quotes (\\ and \" only), -// a number, or true/false (stored as 1/0). A value of '' leaves the setting unset. -// -// A section or name that is not in kSettings, a name set twice and anything else this reader does not take make it -// return false with ":: " in *error; *values is then unchanged. A misspelt setting is -// therefore an error and not a setting that silently does nothing. -bool parse(std::string_view text, std::string_view file_name, FileValues* values, std::string* error); - -// Reads `file` and makes its values the ones get() falls back on. On failure the values loaded before stay. -bool load_file(const std::filesystem::path& file, std::string* error); - -// What gta6rt does at startup: reads the file kFileVariable names (an error if it does not exist), else -// /leonida.toml if there is one. True when there is no file to read. -bool load(const std::filesystem::path& program_dir, std::string* error); - -// Forgets the loaded file (tests). -void unload(); - -// The file whose values are loaded; empty when none is. -std::filesystem::path loaded_file(); - -// What `gta6rt config` prints: the loaded file, then one line per setting with its key, where its value comes from, -// its variable and the value. -std::string report(); - -} // namespace rt::config diff --git a/runtime/core/log.cpp b/runtime/core/log.cpp deleted file mode 100644 index 8e4d09c5c..000000000 --- a/runtime/core/log.cpp +++ /dev/null @@ -1,27 +0,0 @@ -// rt::log (core/log.h): the level the setting log.level asks for. -#include "log.h" - -#include "config.h" - -namespace rt::log { - -Level level_from_settings(std::string* warning) { - if (warning) warning->clear(); - constexpr rt::config::Name setting("log.level"); - const std::string text = rt::config::get(setting).text; - if (const std::optional named = parse_level(text)) return *named; - // The variable is named also when the value came from the file, as the other readers do. - if (warning) - *warning = std::string("log: ") + setting.setting().variable + "=" + text + " unknown (" + kLevelList + - "), using " + level_name(kDefaultLevel); - return kDefaultLevel; -} - -void apply_settings(bool print_warning) { - std::string warning; - set_level(level_from_settings(&warning)); - // With a warning the level in use is the default, which lets warnings through. - if (print_warning && !warning.empty()) RT_LOG_WARN("%s\n", warning.c_str()); -} - -} // namespace rt::log diff --git a/runtime/core/log.h b/runtime/core/log.h deleted file mode 100644 index abdd3f336..000000000 --- a/runtime/core/log.h +++ /dev/null @@ -1,100 +0,0 @@ -// The runtime's log: the "[rt] ..." lines on stderr, each with a level. -// -// RT_LOG_WARN("gameinput: LEONIDA_PROMPTS=%s unknown\n", text.c_str()); -// -// prints "[rt] gameinput: LEONIDA_PROMPTS=... unknown" when the level in use lets warnings through. The first -// argument is a string literal, ": \n" by convention. The macro puts "[rt] " in front of it and hands -// the rest to std::fprintf as written, so the compiler still checks the arguments against the format, a line is one -// fprintf call as it was before the levels, and a line that is held back evaluates none of its arguments. -// -// The levels, in order: off, error, warn, info, debug, trace. A line is printed when its level is at or below the -// level in use. The default is debug: it prints every line the runtime printed before it had levels, and holds -// back only trace lines. There is one level for all modules; a form such as "warn,gameinput=debug" is not read. -// -// The level in use is one value per program. It starts at the default. gta6rt sets it once at startup from the -// setting log.level (LEONIDA_LOG) with apply_settings(). That function and level_from_settings() are in -// core/log.cpp and need gta6rt_core. Everything else is in this header and needs neither gta6rt_core nor windows.h, -// so a header that logs and a test that links no library can include it. A program that does not call -// apply_settings() logs at the default. -#pragma once - -#include -#include -#include -#include -#include -#include - -namespace rt::log { - -enum class Level : int { Off, Error, Warn, Info, Debug, Trace }; - -inline constexpr Level kDefaultLevel = Level::Debug; -// The values log.level takes, as a warning lists them. -inline constexpr char kLevelList[] = "off, error, warn, info, debug or trace"; - -constexpr const char* level_name(Level level) { - switch (level) { - case Level::Off: return "off"; - case Level::Error: return "error"; - case Level::Warn: return "warn"; - case Level::Info: return "info"; - case Level::Debug: return "debug"; - case Level::Trace: return "trace"; - } - return "?"; -} - -// The level `text` names, in any case; nullopt for anything else, also for an empty text. -constexpr std::optional parse_level(std::string_view text) { - constexpr Level all[] = {Level::Off, Level::Error, Level::Warn, Level::Info, Level::Debug, Level::Trace}; - for (const Level level : all) { - const std::string_view name = level_name(level); - if (name.size() != text.size()) continue; - bool same = true; - for (std::size_t i = 0; i < name.size(); ++i) { - const char c = text[i]; - if ((c >= 'A' && c <= 'Z' ? static_cast(c - 'A' + 'a') : c) != name[i]) same = false; - } - if (same) return level; - } - return std::nullopt; -} - -namespace detail { -inline std::atomic g_level{static_cast(kDefaultLevel)}; -} // namespace detail - -// The level in use. Safe to call from any thread. -inline Level level() { return static_cast(detail::g_level.load(std::memory_order_relaxed)); } -inline void set_level(Level level) { detail::g_level.store(static_cast(level), std::memory_order_relaxed); } - -// True when a line of `line_level` is printed at the level in use. Off is not a level a line has: nothing is -// printed for it. -inline bool enabled(Level line_level) { - return line_level != Level::Off && - static_cast(line_level) <= detail::g_level.load(std::memory_order_relaxed); -} - -// ---- in core/log.cpp (gta6rt_core) ---- - -// The level the setting log.level asks for (core/config.h: its variable if set and not empty, else leonida.toml, -// else the default). A value that is not a level gives the default; *warning is then the line that says so, without -// "[rt] " and without a line break, and is empty otherwise. -Level level_from_settings(std::string* warning = nullptr); - -// Makes that level the level in use. A value that is not a level is reported once, as the line -// "[rt] log: ..."; print_warning false leaves that line out, for a program whose parent already printed it. -void apply_settings(bool print_warning = true); - -} // namespace rt::log - -// The first of the variable arguments is the format, a string literal. -#define RT_LOG_AT(level, ...) \ - (::rt::log::enabled(level) ? static_cast(std::fprintf(stderr, "[rt] " __VA_ARGS__)) \ - : static_cast(0)) -#define RT_LOG_ERROR(...) RT_LOG_AT(::rt::log::Level::Error, __VA_ARGS__) -#define RT_LOG_WARN(...) RT_LOG_AT(::rt::log::Level::Warn, __VA_ARGS__) -#define RT_LOG_INFO(...) RT_LOG_AT(::rt::log::Level::Info, __VA_ARGS__) -#define RT_LOG_DEBUG(...) RT_LOG_AT(::rt::log::Level::Debug, __VA_ARGS__) -#define RT_LOG_TRACE(...) RT_LOG_AT(::rt::log::Level::Trace, __VA_ARGS__) diff --git a/runtime/leonida.example.toml b/runtime/leonida.example.toml deleted file mode 100644 index 93ea0005c..000000000 --- a/runtime/leonida.example.toml +++ /dev/null @@ -1,190 +0,0 @@ -# Settings of gta6rt. Copy this file to `leonida.toml` next to gta6rt.exe and change what you need. -# -# A value is taken from the first place that has one: the environment variable named with each setting, then this -# file, then the default. LEONIDA_CONFIG names another file to read in place of the one next to the program. -# `gta6rt config` prints every setting with its value and where the value comes from. -# -# Every setting is listed below with its default, switched off by the "# " in front of it; remove the "# " to set -# it. Text goes in single quotes, which take a Windows path as written ('D:\games\gta6'). Numbers, true and false -# need no quotes. A value of '' means "not set". A name this file format does not know is an error, so a misspelt -# setting cannot go unnoticed. - -[paths] -# LEONIDA_GAME_DIR: the game folder the package's MicrosoftGame.Config is read from. -# Not set: the folder --game-dir names, else the folder of the image. -# game_dir = '' - -# LEONIDA_SAVE_DIR: where saved games go. Not set: %LOCALAPPDATA%\Leonida\saves. -# save_dir = '' - -# LEONIDA_SHADERS: the folder of translated shaders (\shaders\spirv of make_game.py). -# Not set: the folder that shader_path.txt next to the program names. -# shaders = '' - -# LEONIDA_COMPAT_DIR: a folder of compat modules (runtime/README.md, "Compat modules"). Not set: none are used. -# compat_dir = '' - -[loader] -# LEONIDA_UNIMPLEMENTED: what a call to an import without a shim does: 'log', 'fail' or 'stop' (runtime/README.md). -# unimplemented = 'log' - -# LEONIDA_TLS_GA_PATCH: false turns off the loader's TLS rewrite of the image, to measure what the image does -# without it (runtime/README.md, "PE loader"). -# tls_ga_patch = true - -# LEONIDA_SKIP_CPU_CHECK: true skips the AVX check that --init and --run make before any code of the game runs. -# skip_cpu_check = false - -# LEONIDA_SKIP_INT3: a diagnostic for --trace. true logs an int3 in the game's code once per address and steps -# over it. -# skip_int3 = false - -# LEONIDA_RNG_SEED: a number, decimal or hexadecimal with 0x. With it the bcrypt shim returns the same bytes in -# every run. Not set: random bytes from the host. -# rng_seed = '' - -[log] -# LEONIDA_LOG: which of the runtime's "[rt]" lines are printed on stderr: 'off', 'error', 'warn', 'info', 'debug' -# or 'trace'. A level prints its own lines and those of the levels before it. 'debug' prints every line the -# runtime printed before it had levels. -# level = 'debug' - -[system] -# What xgameruntime.dll reports to the title (runtime/README.md, "environment overrides"). - -# LEONIDA_DEVICE_TYPE: the XSystemDeviceType, 0 to 8; 7 is Xbox Series X. -# device_type = 7 - -# LEONIDA_ANALYTICS_FORM: the form string of XSystemGetAnalyticsInfo. Not set: the one the device type gives. -# analytics_form = '' - -# LEONIDA_PACKAGE_ID: the identifier of the running package, up to 32 characters. -# package_id = 'LeonidaPackageIdentifier00000000' - -# LEONIDA_CONTENT_PACKAGES: the content packages XPackageMount can mount, as 'id1=path1;id2=path2'. Not set: none. -# content_packages = '' - -# LEONIDA_PACKAGED: false makes XPackageIsPackagedProcess answer false. -# packaged = true - -# LEONIDA_GAMERTAG: the offline user's gamertag, up to 15 characters of printable ASCII. -# gamertag = 'Player' - -# LEONIDA_HDR: what the title is told when it asks for HDR output (docs/runtime_imports.md, "HDR"). -# false: HDR is reported as disabled. -# hdr = false - -# LEONIDA_LOG_GAME_EVENTS: true logs every event the title writes, with its dimensions and measurements. -# log_game_events = false - -[d3d12] -# LEONIDA_D3D12: the device behind D3D12XboxCreateDevice: 'host' is the D3D12 of this PC, 'vulkan' the runtime's -# D3D12 over Vulkan. -# backend = 'host' - -# XS_TRACE: true logs the first call of each slot of the Xbox device. -# xs_trace = false - -# The slots of the Xbox device's own methods, each 3 to 127 (docs/d3d12_vulkan.md). Change them only for a trace -# that disagrees with the defaults. -# LEONIDA_XS_FRAME_INTERVAL_SLOT: SetFrameIntervalX. -# frame_interval_slot = 78 -# LEONIDA_XS_SCHEDULE_EVENT_SLOT: ScheduleFrameEventX. -# schedule_event_slot = 79 -# LEONIDA_XS_WAIT_EVENT_SLOT: WaitFrameEventX. -# wait_event_slot = 80 -# LEONIDA_XS_QUEUE_X_SLOT: CreateCommandQueueX. -# queue_x_slot = 48 -# LEONIDA_XS_LIST_X_SLOT: CreateCommandListX. -# list_x_slot = 73 - -# LEONIDA_XS_PRESENT_X_SLOT: the slot of PresentX on the Xbox command queue, 19 to 127 (runtime/README.md). Not set: -# no slot is taken for it, and the call is refused with a log line that names the slot the title called. -# present_x_slot = '' - -[vulkan] -# The Vulkan backend (docs/d3d12_vulkan.md). - -# LEONIDA_VK_DEVICE: picks the GPU by its name (runtime/src/vulkan_device_filter.h). Not set: the runtime's choice. -# device = '' - -# LEONIDA_VK_VALIDATION: true runs the device under the Khronos validation layer. -# validation = false - -# LEONIDA_VK_MAX_QUEUES_PER_FAMILY: a test setting, 1 to 16: at most this many Vulkan queues per queue family. -# The game's device ignores it. -# max_queues_per_family = 16 - -# LEONIDA_VK_GRAPHICS_FAMILY_ONLY: a test setting: true puts every D3D12 queue in the graphics family. -# The game's device ignores it. -# graphics_family_only = false - -# LEONIDA_ARENA_MB: the size of the device's memory arena in MiB, at most 4095. -# arena_mb = 256 - -# LEONIDA_ARENA_LOG: true logs every address the arena hands out and every allocation it refuses. -# arena_log = false - -# LEONIDA_UPLOAD_SYSMEM: true keeps upload heaps in system memory on a GPU with Resizable BAR. -# upload_sysmem = false - -# LEONIDA_BINDLESS_IDLE_WAIT: true brings back the old wait before the bindless descriptor set is replaced. -# bindless_idle_wait = false - -# LEONIDA_RT_AS: how acceleration structures are built: 'xdxr' writes the records the game's shaders read, 'khr' -# builds Vulkan's own (docs/bvh.md). -# rt_as = 'xdxr' - -[present] -# LEONIDA_SDR_EOTF: how SDR output is decoded: 'srgb' is piecewise sRGB, 'gamma22' (or '2.2') a pure power of 2.2. -# sdr_eotf = 'srgb' - -# LEONIDA_PRESENT_UNCAP: true takes the frame-rate cap off: frame events return at once and presents do not wait -# for vblank. -# uncap = false - -# LEONIDA_PRESENT_NO_TEAR: true never lets a late frame tear. -# no_tear = false - -# LEONIDA_CAPTURE: a folder. With it, presented frames are also written there as PPM files. Not set: no capture. -# capture_dir = '' - -# LEONIDA_CAPTURE_EVERY: with a capture folder, every how many presented frames one is written. -# capture_every = 30 - -# LEONIDA_CAPTURE_LIMIT: with a capture folder, how many frames are written at most. -# capture_limit = 24 - -[input] -# Controllers, keyboard and mouse (docs/gameinput.md). - -# LEONIDA_PROMPTS: the input family the title is told is in use: 'auto' follows the devices; or 'xbox', -# 'playstation' (or 'ps5'), 'ps4', 'ps3', 'nintendo', 'keyboard'. -# prompts = 'auto' - -# LEONIDA_PROMPTS_SWITCH_MS: the shortest time between two changes of that family, 0 to 2000 ms. -# prompts_switch_ms = 300 - -# LEONIDA_DS_TRIGGERS: DualSense trigger effects: 'off', 'rumble' or 'resistance'. -# ds_triggers = 'rumble' - -# LEONIDA_DS_TRIGGER_GAIN: scales the trigger level before it becomes an effect, 0 to 4. -# ds_trigger_gain = 1 - -# LEONIDA_DS_TRIGGER_FREQ: the vibration frequency of the 'rumble' trigger mode, 1 to 255. -# ds_trigger_freq = 30 - -# LEONIDA_DS_LIGHTBAR: the lightbar colour as 'RRGGBB' (hexadecimal), or 'off'. Not set: SDL's player colour. -# ds_lightbar = '' - -# LEONIDA_RUMBLE: false turns all rumble, trigger and force-feedback output off. -# rumble = true - -# LEONIDA_GAMEINPUT_THREAD: false stops the background poll thread (tests). -# thread = true - -# LEONIDA_KEYBOARD_PAD: the keyboard as a gamepad: 'off'; 'focus' while this program has the focus; 'always'. -# keyboard_pad = 'off' - -# LEONIDA_MOUSE_SENSITIVITY: scales how far the mouse moves the keyboard pad's right stick, 0.1 to 10. -# mouse_sensitivity = 1 diff --git a/runtime/shims/acphal.cpp b/runtime/shims/acphal.cpp deleted file mode 100644 index 6350422d9..000000000 --- a/runtime/shims/acphal.cpp +++ /dev/null @@ -1,568 +0,0 @@ -// acphal.dll: Audio Control Processor HAL. Scalable Hardware Audio Processing Engine -// (SHAPE) and APU (Audio Processing Unit) physical memory management for Xbox Series. -// -// On a PC there is no SHAPE/ACP hardware and APU physical memory does not exist. -// This shim creates the APU heap from process memory and manages allocations within it. -// The SHAPE context arrays are allocated on the process heap; the ACP interface -// accepts and acknowledges commands to allow audio bring-up to proceed cleanly. -// -// Signatures from the public GDK reference (devdocs.xbox.com): -// AcpHal, APU reference, SHAPE_CONTEXTS, APU_ADDRESS. -// Measured call-site shapes and findings from the retail executable (1.0.2.1): -// - docs/retail_boot_chain.md, docs/retail_boot_frame_loop.md (Stop 28) -// - PR #6885 (call sites and parameter analysis), PR #7009 (audio/HAL bring-up). - -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include "../core/log.h" -#include "shims.h" -#include "startup_trace.h" - -namespace { - -// ---- APU_ADDRESS (from the GDK) ---- - -// The console APU uses a 40-bit physical address space. -// On PC we translate to a 32-bit APU address offset. -struct APU_ADDRESS { - uint64_t value; // 40-bit physical address -}; - -// ---- SHAPE context structures (from the public GDK documentation at devdocs.xbox.com) ---- -// -// These structures are defined here with their documented GDK field layouts so that -// sizeof() returns the correct per-context byte count. Without the real layouts the -// empty structs would be 1 byte each, and the title's writes (e.g. memset with the -// real stride) would overflow the allocation. - -// UINT32 bitfields packed into 32-bit words -struct SHAPE_SRC_CONTEXT { - uint32_t timestamp : 21; - uint32_t blocksToSkip : 2; - uint32_t internalSaturate : 1; - uint32_t mixBufPeakMag : 4; - uint32_t peakMag : 4; - uint32_t samplingIncrement : 21; - uint32_t reserved0 : 1; - uint32_t cmd : 2; - uint32_t mixBufPeakMag2 : 4; - uint32_t peakMag2 : 4; - uint32_t sampleCount; - uint32_t samplePointer : 25; - uint32_t reserved1 : 7; - uint32_t samplingIncrementTarget : 21; - uint32_t reserved2 : 11; - uint32_t reserved[3]; -}; -static_assert(sizeof(SHAPE_SRC_CONTEXT) == 32, "SHAPE_SRC_CONTEXT is 32 bytes per GDK"); - -// The EQ/Comp context: 88 UINT32s = 352 bytes per GDK definition. -#pragma pack(push, 1) -struct alignas(4) SHAPE_EQCOMP_CONTEXT { - uint8_t data[352]; -}; -#pragma pack(pop) -static_assert(sizeof(SHAPE_EQCOMP_CONTEXT) == 352, "SHAPE_EQCOMP_CONTEXT is 352 bytes per GDK"); - -struct SHAPE_FILTVOL_CONTEXT { - uint32_t timestamp : 21; - uint32_t reserved0 : 2; - uint32_t internalSaturate : 1; - uint32_t mixBufPeakMag : 4; - uint32_t peakMag : 4; - uint32_t delay1 : 30; - uint32_t headroom : 2; - uint32_t delay2 : 30; - uint32_t svfMode : 2; - uint32_t gainTarget : 16; - uint32_t gain : 16; - uint32_t qRecip : 24; - uint32_t reserved1 : 8; - uint32_t qRecipTarget : 24; - uint32_t reserved2 : 8; - uint32_t fc : 24; - uint32_t reserved3 : 8; - uint32_t fcTarget : 24; - uint32_t reserved4 : 8; -}; -static_assert(sizeof(SHAPE_FILTVOL_CONTEXT) == 32, "SHAPE_FILTVOL_CONTEXT is 32 bytes per GDK"); - -struct SHAPE_DMA_CONTEXT { - uint32_t timestamp : 21; - uint32_t reserved0 : 3; - uint32_t mixBufPeakMag : 4; - uint32_t peakMag : 4; - uint32_t readPointer : 5; - uint32_t reserved1 : 3; - uint32_t writePointer : 5; - uint32_t reserved2 : 3; - uint32_t full : 1; - uint32_t reserved3 : 15; - uint32_t reserved4 : 9; - uint32_t address : 23; - uint32_t numFrames : 5; - uint32_t reserved5 : 3; - uint32_t floatConvert : 1; - uint32_t reserved6 : 7; - uint32_t numChannels : 3; - uint32_t reserved7 : 5; - uint32_t channel : 3; - uint32_t reserved8 : 5; -}; -static_assert(sizeof(SHAPE_DMA_CONTEXT) == 16, "SHAPE_DMA_CONTEXT is 16 bytes per GDK"); - -struct SHAPE_XMA_CONTEXT { - uint32_t sizeRead0 : 12; - uint32_t numLoops : 8; - uint32_t validBuffer : 2; - uint32_t sizeWrite : 5; - uint32_t offsetWrite : 5; - uint32_t sizeRead1 : 12; - uint32_t sequenceNumber : 12; - uint32_t stopSampleAddress : 8; - uint32_t subframeOffset : 4; - uint32_t reserved0 : 1; - uint32_t isLooping : 1; - uint32_t subframeSkip : 2; - uint32_t packetMetadata : 16; - uint32_t currentByteOffset : 26; - uint32_t reserved1 : 6; - uint32_t loopStartOffset : 26; - uint32_t loopEndOffset : 6; - uint32_t reserved[11]; // the GDK's 64-byte context: the published field list leaves one trailing word -}; -static_assert(sizeof(SHAPE_XMA_CONTEXT) == 64, "SHAPE_XMA_CONTEXT is 64 bytes per GDK"); - -struct SHAPE_PCM_CONTEXT { - uint32_t timestamp : 21; - uint32_t reserved0 : 11; - uint32_t loopCount : 8; - uint32_t reserved1 : 8; - uint32_t full : 1; - uint32_t reserved2 : 15; - uint32_t readPointer : 21; - uint32_t reserved3 : 11; - uint32_t loopStartWritePointer : 21; - uint32_t reserved4 : 11; - uint32_t loopEnd : 21; - uint32_t reserved5 : 11; - uint32_t mode : 1; - uint32_t reserved6 : 15; - uint32_t format : 2; - uint32_t reserved7 : 14; - uint32_t reserved[2]; // the GDK's 32-byte context: the published field list leaves one trailing word -}; -static_assert(sizeof(SHAPE_PCM_CONTEXT) == 32, "SHAPE_PCM_CONTEXT is 32 bytes per GDK"); - -// The SHAPE_CONTEXTS structure (from the GDK) -struct SHAPE_CONTEXTS { - uint32_t numSrcContexts; - uint32_t numEqCompContexts; - uint32_t numFiltVolContexts; - uint32_t numDmaContexts; - uint32_t numXmaContexts; - uint32_t numPcmContexts; - SHAPE_SRC_CONTEXT* srcContextArray; - SHAPE_EQCOMP_CONTEXT* eqCompContextArray; - SHAPE_FILTVOL_CONTEXT* filtVolContextArray; - SHAPE_DMA_CONTEXT* dmaContextArray; - SHAPE_XMA_CONTEXT* xmaContextArray; - SHAPE_PCM_CONTEXT* pcmContextArray; - APU_ADDRESS apuSrcContextArray; - APU_ADDRESS apuEqCompContextArray; - APU_ADDRESS apuFiltVolContextArray; - APU_ADDRESS apuDmaContextArray; - APU_ADDRESS apuXmaContextArray; - APU_ADDRESS apuPcmContextArray; -}; - -static_assert(sizeof(SHAPE_CONTEXTS) == 120, "SHAPE_CONTEXTS is 120 bytes per GDK"); -static_assert(offsetof(SHAPE_CONTEXTS, xmaContextArray) == 0x38, - "xmaContextArray is at offset +0x38 per retail binary measurement"); - -// ---- Startup trace helper ---- - -void trace_call(const char* api, const std::string& detail) { - if (!rt::startup_trace::enabled()) return; - static std::mutex mutex; - static std::set seen; - { - const std::lock_guard lock(mutex); - if (!seen.insert(std::string(api) + detail).second) return; - } - rt::startup_trace::event("acphal", - std::string("\"api\":\"") + api + "\"" + detail); -} - -// ---- Genuine APU Heap Implementation ---- - -constexpr uint32_t kApuBaseAddress = 0x40000000u; - -struct ApuRegion { - void* base = nullptr; - uint64_t size = 0; - std::map blocks; // offset -> size of active allocations - - bool contains(const void* ptr) const { - if (!base || !ptr) return false; - const uintptr_t p = reinterpret_cast(ptr); - const uintptr_t b = reinterpret_cast(base); - return p >= b && p < b + size; - } - - bool is_valid_address(const void* ptr, uint32_t alignment) const { - if (!base || !ptr) return false; - const uintptr_t p = reinterpret_cast(ptr); - const uintptr_t b = reinterpret_cast(base); - if (p < b || p >= b + size) return false; - if (alignment == 0) alignment = 1; - return ((p - b) & (static_cast(alignment) - 1)) == 0; - } - - uint32_t to_offset(const void* ptr) const { - return static_cast(reinterpret_cast(ptr) - - reinterpret_cast(base)); - } - - void* from_offset(uint32_t offset) const { - if (offset >= size) return nullptr; - return static_cast(base) + offset; - } - - void* allocate(uint32_t alloc_size, uint32_t alignment, uint32_t* out_offset) { - if (alloc_size == 0 || alignment == 0) return nullptr; - uint64_t at = 0; - for (auto it = blocks.begin();; ++it) { - at = (at + alignment - 1) & ~static_cast(alignment - 1); - const uint64_t limit = (it == blocks.end()) ? size : it->first; - if (at + alloc_size <= limit) break; - if (it == blocks.end()) return nullptr; // out of memory - at = static_cast(it->first) + it->second; - } - const uint32_t offset = static_cast(at); - blocks.emplace(offset, alloc_size); - uint8_t* ptr = static_cast(base) + offset; - std::memset(ptr, 0, alloc_size); - if (out_offset) *out_offset = offset; - return ptr; - } - - bool free_block(void* ptr) { - if (!contains(ptr)) return false; - const uint32_t offset = to_offset(ptr); - return blocks.erase(offset) > 0; - } - - void release() { - if (base) { - VirtualFree(base, 0, MEM_RELEASE); - base = nullptr; - } - size = 0; - blocks.clear(); - } -}; - -std::mutex g_apu_mutex; -bool g_apu_heap_created = false; -ApuRegion g_cached_heap; -ApuRegion g_noncached_heap; - -// Tracked SHAPE context arrays -std::vector g_active_shape_arrays; - -// ---- IAcpHal Interface Implementation ---- - -struct AcpHalImpl { - // Slot 0: Connect (called at boot with (0x1000, 0x1000), result checked) - virtual HRESULT __stdcall connect(uint32_t, uint32_t) { - trace_call("AcpHal::Connect", ""); - return S_OK; - } - - // Slot 1: Disconnect (called at shutdown) - virtual HRESULT __stdcall disconnect() { - trace_call("AcpHal::Disconnect", ""); - return S_OK; - } - - // Slot 2: SubmitCommand - // Critical: The title calls slot 2 as (2, 0xf0f0f0f0, -1, config, 0) and - // a negative result triggers a fatal int3 kernel panic (+0x43ad94e). - virtual HRESULT __stdcall submit_command(uint32_t cmd, uint32_t d1, uint32_t d2, - const void* config, uint32_t d3) { - (void)cmd; - (void)d1; - (void)d2; - (void)config; - (void)d3; - static std::atomic warned{false}; - if (!warned.exchange(true, std::memory_order_relaxed)) { - RT_LOG_WARN("acphal: command accepted and dropped: no audio DSP hardware on PC\n"); - } - trace_call("AcpHal::SubmitCommand", ""); - return S_OK; - } - - // Slots 3 and 4: PopMessage and GetNumMessages (message polling, not called by title) - virtual uint32_t __stdcall pop_message() { return 0; } - virtual uint32_t __stdcall get_num_messages() { return 0; } - - // Slot 5: Release - virtual HRESULT __stdcall release() { - trace_call("AcpHal::Release", ""); - delete this; - return S_OK; - } -}; - -// ---- AcpHalCreate ---- - -HRESULT __stdcall AcpHalCreate(void** ppAcpHal) { - if (!ppAcpHal) return E_POINTER; - *ppAcpHal = new AcpHalImpl(); - trace_call("AcpHalCreate", ""); - return S_OK; -} - -// ---- AcpHalAllocateShapeContexts ---- - -HRESULT __stdcall AcpHalAllocateShapeContexts(SHAPE_CONTEXTS* ctx) { - if (!ctx) return E_POINTER; - - std::lock_guard lock(g_apu_mutex); - - auto alloc_array = [](uint32_t count, size_t elem_size) -> void* { - if (count == 0) return nullptr; - void* ptr = std::calloc(count, elem_size); - if (ptr) g_active_shape_arrays.push_back(ptr); - return ptr; - }; - - ctx->srcContextArray = static_cast( - alloc_array(ctx->numSrcContexts, sizeof(SHAPE_SRC_CONTEXT))); - ctx->eqCompContextArray = static_cast( - alloc_array(ctx->numEqCompContexts, sizeof(SHAPE_EQCOMP_CONTEXT))); - ctx->filtVolContextArray = static_cast( - alloc_array(ctx->numFiltVolContexts, sizeof(SHAPE_FILTVOL_CONTEXT))); - ctx->dmaContextArray = static_cast( - alloc_array(ctx->numDmaContexts, sizeof(SHAPE_DMA_CONTEXT))); - ctx->xmaContextArray = static_cast( - alloc_array(ctx->numXmaContexts, sizeof(SHAPE_XMA_CONTEXT))); - ctx->pcmContextArray = static_cast( - alloc_array(ctx->numPcmContexts, sizeof(SHAPE_PCM_CONTEXT))); - - // On PC there is no physical APU address translation for host context arrays; - // assign unique synthetic addresses from the APU base. - ctx->apuSrcContextArray = {ctx->srcContextArray ? kApuBaseAddress : 0}; - ctx->apuEqCompContextArray = {ctx->eqCompContextArray ? kApuBaseAddress + 0x1000 : 0}; - ctx->apuFiltVolContextArray = {ctx->filtVolContextArray ? kApuBaseAddress + 0x2000 : 0}; - ctx->apuDmaContextArray = {ctx->dmaContextArray ? kApuBaseAddress + 0x3000 : 0}; - ctx->apuXmaContextArray = {ctx->xmaContextArray ? kApuBaseAddress + 0x4000 : 0}; - ctx->apuPcmContextArray = {ctx->pcmContextArray ? kApuBaseAddress + 0x5000 : 0}; - - trace_call("AcpHalAllocateShapeContexts", - ",\"src\":" + std::to_string(ctx->numSrcContexts) + - ",\"xma\":" + std::to_string(ctx->numXmaContexts) + - ",\"pcm\":" + std::to_string(ctx->numPcmContexts)); - return S_OK; -} - -// ---- AcpHalReleaseShapeContexts ---- - -HRESULT __stdcall AcpHalReleaseShapeContexts(SHAPE_CONTEXTS* ctx = nullptr) { - std::lock_guard lock(g_apu_mutex); - - // Free all recorded context allocations - for (void* p : g_active_shape_arrays) { - if (p) std::free(p); - } - g_active_shape_arrays.clear(); - - if (ctx) { - ctx->srcContextArray = nullptr; - ctx->eqCompContextArray = nullptr; - ctx->filtVolContextArray = nullptr; - ctx->dmaContextArray = nullptr; - ctx->xmaContextArray = nullptr; - ctx->pcmContextArray = nullptr; - } - - trace_call("AcpHalReleaseShapeContexts", ""); - return S_OK; -} - -// ---- ApuCreateHeap ---- - -HRESULT __stdcall ApuCreateHeap(uint32_t cachedSizeInBytes, - uint32_t nonCachedSizeInBytes) { - std::lock_guard lock(g_apu_mutex); - if (g_apu_heap_created) return E_FAIL; - - if (cachedSizeInBytes > 0) { - g_cached_heap.base = VirtualAlloc( - nullptr, cachedSizeInBytes, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE); - if (!g_cached_heap.base) return E_OUTOFMEMORY; - g_cached_heap.size = cachedSizeInBytes; - } - - if (nonCachedSizeInBytes > 0) { - g_noncached_heap.base = VirtualAlloc( - nullptr, nonCachedSizeInBytes, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE); - if (!g_noncached_heap.base) { - g_cached_heap.release(); - return E_OUTOFMEMORY; - } - g_noncached_heap.size = nonCachedSizeInBytes; - } - - g_apu_heap_created = true; - trace_call("ApuCreateHeap", - ",\"cachedSize\":" + std::to_string(cachedSizeInBytes) + - ",\"nonCachedSize\":" + std::to_string(nonCachedSizeInBytes)); - return S_OK; -} - -// ---- ApuAlloc ---- - -HRESULT __stdcall ApuAlloc(void** virtualAddress, uint32_t* physicalAddress, - uint32_t sizeInBytes, uint32_t alignmentInBytes, - uint32_t flags) { - if (!virtualAddress) return E_POINTER; - *virtualAddress = nullptr; - if (physicalAddress) *physicalAddress = 0; - - if (sizeInBytes == 0) return E_INVALIDARG; - if (alignmentInBytes == 0) alignmentInBytes = 1; - if ((alignmentInBytes & (alignmentInBytes - 1)) != 0) return E_INVALIDARG; - - std::lock_guard lock(g_apu_mutex); - - // Routing: flags=2 routes to non-cached heap; flags=0 or 1 routes to cached heap. - // If non-cached heap wasn't created or has no room, fall back to cached heap - // because PC memory is unified and cache-coherent. - const bool prefer_noncached = (flags == 2); - ApuRegion* target = prefer_noncached ? &g_noncached_heap : &g_cached_heap; - - if (!target->base) { - if (!prefer_noncached) { - // Lazy default cached heap if ApuCreateHeap wasn't called yet - constexpr uint32_t kDefaultHeapSize = 64 * 1024 * 1024; - target->base = VirtualAlloc(nullptr, kDefaultHeapSize, - MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE); - if (!target->base) return E_OUTOFMEMORY; - target->size = kDefaultHeapSize; - g_apu_heap_created = true; - } else { - // Fall back to cached heap - target = &g_cached_heap; - if (!target->base) return E_OUTOFMEMORY; - } - } - - uint32_t offset = 0; - void* ptr = target->allocate(sizeInBytes, alignmentInBytes, &offset); - if (!ptr && prefer_noncached && g_cached_heap.base) { - // Fall back to cached heap if non-cached heap is full - target = &g_cached_heap; - ptr = target->allocate(sizeInBytes, alignmentInBytes, &offset); - } - - if (!ptr) return E_OUTOFMEMORY; - - *virtualAddress = ptr; - if (physicalAddress) { - // Disjoint APU address ranges: - // cached: 0x40000000 .. 0x40000000 + cached_size - 1 - // non-cached: 0x40000000 + cached_size .. 0x40000000 + cached_size + noncached_size - 1 - uint32_t apu = kApuBaseAddress + offset; - if (target == &g_noncached_heap) { - apu += static_cast(g_cached_heap.size); - } - *physicalAddress = apu; - } - - return S_OK; -} - -// ---- ApuFree ---- - -void __stdcall ApuFree(void* virtualAddress) { - if (!virtualAddress) return; - std::lock_guard lock(g_apu_mutex); - if (!g_cached_heap.free_block(virtualAddress)) { - g_noncached_heap.free_block(virtualAddress); - } - trace_call("ApuFree", ""); -} - -// ---- ApuIsVirtualAddressValid ---- - -BOOL __stdcall ApuIsVirtualAddressValid(void* virtualAddress, uint32_t alignment) { - if (!virtualAddress) return FALSE; - if (alignment == 0) alignment = 1; - std::lock_guard lock(g_apu_mutex); - if (g_cached_heap.is_valid_address(virtualAddress, alignment)) return TRUE; - if (g_noncached_heap.is_valid_address(virtualAddress, alignment)) return TRUE; - return FALSE; -} - -// ---- ApuMapApuAddress ---- - -void* __stdcall ApuMapApuAddress(uint32_t apu) { - if (apu == 0 || apu < kApuBaseAddress) return nullptr; - std::lock_guard lock(g_apu_mutex); - const uint32_t offset = apu - kApuBaseAddress; - if (g_cached_heap.base && offset < g_cached_heap.size) { - return g_cached_heap.from_offset(offset); - } - if (g_noncached_heap.base) { - const uint32_t cached_span = static_cast(g_cached_heap.size); - if (offset >= cached_span && offset - cached_span < g_noncached_heap.size) { - return g_noncached_heap.from_offset(offset - cached_span); - } - } - return nullptr; -} - -// ---- ApuMapVirtualAddress ---- - -uint32_t __stdcall ApuMapVirtualAddress(void* virtualAddress) { - if (!virtualAddress) return 0; - std::lock_guard lock(g_apu_mutex); - if (g_cached_heap.contains(virtualAddress)) { - return kApuBaseAddress + g_cached_heap.to_offset(virtualAddress); - } - if (g_noncached_heap.contains(virtualAddress)) { - return kApuBaseAddress + static_cast(g_cached_heap.size) + - g_noncached_heap.to_offset(virtualAddress); - } - return 0; -} - -} // namespace - -SHIM_TABLE(acphal, - {"acphal.dll", "AcpHalAllocateShapeContexts", reinterpret_cast(&AcpHalAllocateShapeContexts)}, - {"acphal.dll", "AcpHalCreate", reinterpret_cast(&AcpHalCreate)}, - {"acphal.dll", "AcpHalReleaseShapeContexts", reinterpret_cast(&AcpHalReleaseShapeContexts)}, - {"acphal.dll", "ApuAlloc", reinterpret_cast(&ApuAlloc)}, - {"acphal.dll", "ApuCreateHeap", reinterpret_cast(&ApuCreateHeap)}, - {"acphal.dll", "ApuFree", reinterpret_cast(&ApuFree)}, - {"acphal.dll", "ApuIsVirtualAddressValid", reinterpret_cast(&ApuIsVirtualAddressValid)}, - {"acphal.dll", "ApuMapApuAddress", reinterpret_cast(&ApuMapApuAddress)}, - {"acphal.dll", "ApuMapVirtualAddress", reinterpret_cast(&ApuMapVirtualAddress)}, -); diff --git a/runtime/shims/bcrypt_rng.cpp b/runtime/shims/bcrypt_rng.cpp deleted file mode 100644 index 2fb346208..000000000 --- a/runtime/shims/bcrypt_rng.cpp +++ /dev/null @@ -1,238 +0,0 @@ -// BCrypt RNG and algorithm provider shims (bcrypt.dll). -// -// game_scarlett_master.exe directly imports BCryptOpenAlgorithmProvider, BCryptGenRandom, and -// BCryptCloseAlgorithmProvider (all 3 imports of bcrypt.dll). This shim: -// - tracks live BCRYPT_ALG_HANDLEs so double-close, null, or foreign handles fail safely with -// STATUS_INVALID_HANDLE (0xC0000008) instead of corrupting or faulting in host bcryptprimitives.dll; -// - delegates hardware CSPRNG generation to dynamically loaded host bcrypt.dll (with SystemFunction036 fallback); -// - supports an optional deterministic LEONIDA_RNG_SEED= mode (decimal or 0x hex) for reproducible -// testing/debugging runs. -#include - -#ifndef _NTDEF_ -using NTSTATUS = LONG; -#endif -#include - -#include -#include -#include -#include -#include -#include -#include -#include - -#include "../core/config.h" -#include "../core/log.h" -#include "shims.h" - -namespace rt::bcrypt_rng { -namespace { - -constexpr NTSTATUS kStatusSuccess = 0x00000000L; -constexpr NTSTATUS kStatusUnsuccessful = static_cast(0xC0000001L); -constexpr NTSTATUS kStatusNotImplemented = static_cast(0xC0000002L); -constexpr NTSTATUS kStatusInvalidHandle = static_cast(0xC0000008L); -constexpr NTSTATUS kStatusInvalidParameter = static_cast(0xC000000DL); -constexpr NTSTATUS kStatusNoMemory = static_cast(0xC0000017L); -constexpr NTSTATUS kStatusNotFound = static_cast(0xC0000225L); - -using OpenAlgFn = NTSTATUS(WINAPI*)(BCRYPT_ALG_HANDLE*, LPCWSTR, LPCWSTR, ULONG); -using CloseAlgFn = NTSTATUS(WINAPI*)(BCRYPT_ALG_HANDLE, ULONG); -using GenRandomFn = NTSTATUS(WINAPI*)(BCRYPT_ALG_HANDLE, PUCHAR, ULONG, ULONG); -using RtlGenRandomFn = BOOLEAN(WINAPI*)(PVOID, ULONG); - -struct AlgHandle { - BCRYPT_ALG_HANDLE host_handle; - bool is_rng; - AlgHandle* next; -}; - -INIT_ONCE g_init_once = INIT_ONCE_STATIC_INIT; -OpenAlgFn g_host_open = nullptr; -CloseAlgFn g_host_close = nullptr; -GenRandomFn g_host_gen = nullptr; -RtlGenRandomFn g_rtl_gen_random = nullptr; -bool g_seeded_mode = false; -uint64_t g_prng_state = 0; -std::atomic g_disable_host_rng_for_test{false}; - -SRWLOCK g_lock = SRWLOCK_INIT; -AlgHandle* g_live_handles = nullptr; - -bool parse_u64(const char* text, uint64_t& out) { - if (!text || !*text) return false; - char* end = nullptr; - const unsigned long long val = std::strtoull(text, &end, 0); - if (!end || *end != '\0') return false; - out = static_cast(val); - return true; -} - -BOOL CALLBACK init_bcrypt_once(PINIT_ONCE, PVOID, PVOID*) { - if (const HMODULE m = LoadLibraryExW(L"bcrypt.dll", nullptr, LOAD_LIBRARY_SEARCH_SYSTEM32)) { - g_host_open = reinterpret_cast(GetProcAddress(m, "BCryptOpenAlgorithmProvider")); - g_host_close = reinterpret_cast(GetProcAddress(m, "BCryptCloseAlgorithmProvider")); - g_host_gen = reinterpret_cast(GetProcAddress(m, "BCryptGenRandom")); - } - if (const HMODULE adv = LoadLibraryExW(L"advapi32.dll", nullptr, LOAD_LIBRARY_SEARCH_SYSTEM32)) { - g_rtl_gen_random = reinterpret_cast(GetProcAddress(adv, "SystemFunction036")); - } - - // A value of 64 characters or more is not taken as a seed, as before the setting moved to the table. - const std::string seed_text = rt::config::get("loader.rng_seed").text; - uint64_t seed = 0; - if (seed_text.size() < 64 && parse_u64(seed_text.c_str(), seed)) { - g_seeded_mode = true; - g_prng_state = seed ? seed : 0x9E3779B97F4A7C15ULL; - RT_LOG_INFO("bcrypt: deterministic LEONIDA_RNG_SEED enabled (0x%llx)\n", - static_cast(seed)); - } - return TRUE; -} - -void ensure_initialized() { InitOnceExecuteOnce(&g_init_once, init_bcrypt_once, nullptr, nullptr); } - -uint64_t next_splitmix64() { - uint64_t z = (g_prng_state += 0x9E3779B97F4A7C15ULL); - z = (z ^ (z >> 30)) * 0xBF58476D1CE4E5B9ULL; - z = (z ^ (z >> 27)) * 0x94D049BB133111EBULL; - return z ^ (z >> 31); -} - -void fill_seeded(PUCHAR buffer, ULONG count) { - AcquireSRWLockExclusive(&g_lock); - ULONG offset = 0; - while (offset < count) { - const uint64_t word = next_splitmix64(); - const ULONG chunk = (count - offset) < sizeof(word) ? (count - offset) : static_cast(sizeof(word)); - std::memcpy(buffer + offset, &word, chunk); - offset += chunk; - } - ReleaseSRWLockExclusive(&g_lock); -} - -bool is_rng_algorithm(LPCWSTR alg_id) { - return alg_id && _wcsicmp(alg_id, BCRYPT_RNG_ALGORITHM) == 0; -} - -bool lookup_live_handle(BCRYPT_ALG_HANDLE h, BCRYPT_ALG_HANDLE& out_host, bool& out_is_rng) { - AcquireSRWLockShared(&g_lock); - for (const AlgHandle* cur = g_live_handles; cur; cur = cur->next) { - if (cur == h) { - out_host = cur->host_handle; - out_is_rng = cur->is_rng; - ReleaseSRWLockShared(&g_lock); - return true; - } - } - ReleaseSRWLockShared(&g_lock); - return false; -} - -NTSTATUS WINAPI open_algorithm_provider(BCRYPT_ALG_HANDLE* phAlgorithm, LPCWSTR pszAlgId, LPCWSTR pszImplementation, - ULONG dwFlags) { - ensure_initialized(); - if (!phAlgorithm || !pszAlgId) return kStatusInvalidParameter; - *phAlgorithm = nullptr; - - const bool is_rng = is_rng_algorithm(pszAlgId); - BCRYPT_ALG_HANDLE host_alg = nullptr; - if (!(g_seeded_mode && is_rng)) { - if (!g_host_open) { - if (!is_rng) return kStatusNotFound; - } else { - const NTSTATUS st = g_host_open(&host_alg, pszAlgId, pszImplementation, dwFlags); - // Windows answers STATUS_NOT_FOUND for an algorithm name it does not know, Wine's bcrypt.dll - // STATUS_NOT_IMPLEMENTED; the caller gets the Windows answer on both. - if (st == kStatusNotImplemented) return kStatusNotFound; - if (st < 0) return st; - } - } - - auto* wrapper = new (std::nothrow) AlgHandle{host_alg, is_rng, nullptr}; - if (!wrapper) { - if (host_alg && g_host_close) g_host_close(host_alg, 0); - return kStatusNoMemory; - } - - AcquireSRWLockExclusive(&g_lock); - wrapper->next = g_live_handles; - g_live_handles = wrapper; - ReleaseSRWLockExclusive(&g_lock); - - *phAlgorithm = wrapper; - return kStatusSuccess; -} - -NTSTATUS WINAPI close_algorithm_provider(BCRYPT_ALG_HANDLE hAlgorithm, ULONG dwFlags) { - ensure_initialized(); - if (!hAlgorithm) return kStatusInvalidHandle; - - AlgHandle* removed = nullptr; - AcquireSRWLockExclusive(&g_lock); - AlgHandle** cur = &g_live_handles; - while (*cur) { - if (*cur == hAlgorithm) { - removed = *cur; - *cur = removed->next; - break; - } - cur = &((*cur)->next); - } - ReleaseSRWLockExclusive(&g_lock); - if (!removed) return kStatusInvalidHandle; - - NTSTATUS st = kStatusSuccess; - if (removed->host_handle && g_host_close) st = g_host_close(removed->host_handle, dwFlags); - delete removed; - return st; -} - -NTSTATUS WINAPI gen_random(BCRYPT_ALG_HANDLE hAlgorithm, PUCHAR pbBuffer, ULONG cbBuffer, ULONG dwFlags) { - ensure_initialized(); - if (!pbBuffer) return kStatusInvalidParameter; - - const bool use_system = (dwFlags & BCRYPT_USE_SYSTEM_PREFERRED_RNG) != 0; - BCRYPT_ALG_HANDLE host_handle = nullptr; - bool is_rng = use_system; - if (use_system) { - if (hAlgorithm != nullptr) return kStatusInvalidParameter; - } else { - if (!hAlgorithm || !lookup_live_handle(hAlgorithm, host_handle, is_rng)) return kStatusInvalidHandle; - if (!is_rng) return kStatusInvalidHandle; - } - - if (cbBuffer == 0) return kStatusSuccess; - - if (g_seeded_mode) { - fill_seeded(pbBuffer, cbBuffer); - return kStatusSuccess; - } - if (!g_disable_host_rng_for_test.load(std::memory_order_acquire)) { - if (g_host_gen) { - const NTSTATUS st = g_host_gen(use_system ? nullptr : host_handle, pbBuffer, cbBuffer, dwFlags); - if (st >= 0) return st; - } - if (g_rtl_gen_random && g_rtl_gen_random(pbBuffer, cbBuffer)) return kStatusSuccess; - } - return kStatusUnsuccessful; -} - -} // namespace - -void set_host_rng_enabled_for_test(bool enabled) { - g_disable_host_rng_for_test.store(!enabled, std::memory_order_release); -} -} // namespace rt::bcrypt_rng - -namespace { -using namespace rt::bcrypt_rng; -} // namespace - -SHIM_TABLE(bcrypt_rng, - {"bcrypt.dll", "BCryptOpenAlgorithmProvider", reinterpret_cast(&open_algorithm_provider)}, - {"bcrypt.dll", "BCryptGenRandom", reinterpret_cast(&gen_random)}, - {"bcrypt.dll", "BCryptCloseAlgorithmProvider", reinterpret_cast(&close_algorithm_provider)}, -); diff --git a/runtime/shims/com_shim.cpp b/runtime/shims/com_shim.cpp deleted file mode 100644 index 55962e215..000000000 --- a/runtime/shims/com_shim.cpp +++ /dev/null @@ -1,173 +0,0 @@ -// COM lifecycle and helper shims for api-ms-win-core-com-l1-1-0..3.dll. -// -// game_scarlett_master.exe imports CoInitializeEx, CoUninitialize, CoCreateInstance, CoCreateGuid, CoTaskMemFree, -// PropVariantClear, and StringFromGUID2 through api-ms-win-core-com-l1-1-0.dll. When the host (or a host library) has -// already initialized a thread as STA, a guest call to CoInitializeEx(nullptr, COINIT_MULTITHREADED) fails with -// RPC_E_CHANGED_MODE (0x80010106) and an unbalanced CoUninitialize can tear down host COM early. -// -// Per-thread guest COM depth and host init ownership are tracked via a TlsAlloc slot (constant-initialized via -// InitOnceExecuteOnce with zero _Init_thread_header TLS guards or C++ thread_local destructors). -#include -#include -#include - -#include -#include - -#include "shims.h" - -namespace rt::com_shim { -namespace { - -struct ThreadComState { - uint32_t guest_depth = 0; - uint32_t host_inits_owned = 0; - DWORD requested_coinit = COINIT_MULTITHREADED; - DWORD host_coinit = COINIT_MULTITHREADED; - bool mismatch_absorbed = false; -}; - -INIT_ONCE g_tls_once = INIT_ONCE_STATIC_INIT; -DWORD g_tls_index = TLS_OUT_OF_INDEXES; - -BOOL CALLBACK init_tls_once(PINIT_ONCE, PVOID, PVOID*) { - g_tls_index = TlsAlloc(); - return TRUE; -} - -DWORD tls_slot() { - InitOnceExecuteOnce(&g_tls_once, init_tls_once, nullptr, nullptr); - return g_tls_index; -} - -bool apartment_differs(DWORD a, DWORD b) { - return (a & COINIT_APARTMENTTHREADED) != (b & COINIT_APARTMENTTHREADED); -} - -DWORD detect_existing_host_coinit(DWORD attempted_coinit) { - APTTYPE apt = APTTYPE_CURRENT; - APTTYPEQUALIFIER qual = APTTYPEQUALIFIER_NONE; - DWORD base = (attempted_coinit & COINIT_APARTMENTTHREADED) ? COINIT_MULTITHREADED : COINIT_APARTMENTTHREADED; - if (SUCCEEDED(::CoGetApartmentType(&apt, &qual))) { - if (apt == APTTYPE_STA || apt == APTTYPE_MAINSTA) base = COINIT_APARTMENTTHREADED; - else if (apt == APTTYPE_MTA) base = COINIT_MULTITHREADED; - } - return base | (attempted_coinit & (COINIT_DISABLE_OLE1DDE | COINIT_SPEED_OVER_MEMORY)); -} - -HRESULT WINAPI co_initialize_ex(LPVOID reserved, DWORD coinit) { - if (reserved != nullptr) return E_INVALIDARG; - - const DWORD slot = tls_slot(); - if (slot == TLS_OUT_OF_INDEXES) return ::CoInitializeEx(nullptr, coinit); - - auto* state = static_cast(TlsGetValue(slot)); - if (!state) { - const HRESULT hr = ::CoInitializeEx(nullptr, coinit); - if (FAILED(hr) && hr != RPC_E_CHANGED_MODE) return hr; - - DWORD owned_mode = coinit; - bool absorbed = false; - uint32_t owned_count = 1; - if (hr == RPC_E_CHANGED_MODE) { - // Retain an actual host COM reference in the thread's existing apartment so guest COM stays alive even if - // the host calls CoUninitialize() while the guest still holds an active initialization. - owned_mode = detect_existing_host_coinit(coinit); - const HRESULT hold_hr = ::CoInitializeEx(nullptr, owned_mode); - if (FAILED(hold_hr)) return hold_hr; - absorbed = true; - } - - auto* created = new (std::nothrow) ThreadComState{}; - if (!created) { - if (owned_count) ::CoUninitialize(); - return E_OUTOFMEMORY; - } - created->guest_depth = 1; - created->host_inits_owned = owned_count; - created->requested_coinit = coinit; - created->host_coinit = owned_mode; - created->mismatch_absorbed = absorbed; - TlsSetValue(slot, created); - return S_OK; - } - - const bool matches_host = !apartment_differs(state->host_coinit, coinit); - const bool matches_absorbed_guest = state->mismatch_absorbed && !apartment_differs(state->requested_coinit, coinit); - if (!matches_host && !matches_absorbed_guest) return RPC_E_CHANGED_MODE; - - const DWORD forward_mode = - matches_host ? coinit : (state->host_coinit | (coinit & (COINIT_DISABLE_OLE1DDE | COINIT_SPEED_OVER_MEMORY))); - const HRESULT hr = ::CoInitializeEx(nullptr, forward_mode); - if (FAILED(hr)) return hr; - - ++state->host_inits_owned; - ++state->guest_depth; - return S_FALSE; -} - -void WINAPI co_uninitialize() { - const DWORD slot = tls_slot(); - if (slot == TLS_OUT_OF_INDEXES) { - ::CoUninitialize(); - return; - } - auto* state = static_cast(TlsGetValue(slot)); - if (!state || state->guest_depth == 0) return; - - --state->guest_depth; - if (state->guest_depth == 0) { - for (uint32_t i = 0; i < state->host_inits_owned; ++i) { - ::CoUninitialize(); - } - TlsSetValue(slot, nullptr); - delete state; - } -} - -HRESULT WINAPI co_create_instance(REFCLSID rclsid, LPUNKNOWN outer, DWORD cls_context, REFIID riid, LPVOID* ppv) { - if (!ppv) return E_POINTER; - *ppv = nullptr; - return ::CoCreateInstance(rclsid, outer, cls_context, riid, ppv); -} - -HRESULT WINAPI co_create_guid(GUID* guid) { - if (!guid) return E_INVALIDARG; - return ::CoCreateGuid(guid); -} - -void WINAPI co_task_mem_free(LPVOID pv) { ::CoTaskMemFree(pv); } - -HRESULT WINAPI prop_variant_clear(PROPVARIANT* pvar) { return ::PropVariantClear(pvar); } - -int WINAPI string_from_guid2(REFGUID rguid, LPOLESTR lpsz, int cch_max) { - if (!lpsz || cch_max <= 0) return 0; - return ::StringFromGUID2(rguid, lpsz, cch_max); -} - -} // namespace -} // namespace rt::com_shim - -namespace { - -using namespace rt::com_shim; - -#define COM_L1_API(dll) \ - {dll, "CoInitializeEx", reinterpret_cast(&co_initialize_ex)}, \ - {dll, "CoUninitialize", reinterpret_cast(&co_uninitialize)}, \ - {dll, "CoCreateInstance", reinterpret_cast(&co_create_instance)}, \ - {dll, "CoCreateGuid", reinterpret_cast(&co_create_guid)}, \ - {dll, "CoTaskMemFree", reinterpret_cast(&co_task_mem_free)}, \ - {dll, "PropVariantClear", reinterpret_cast(&prop_variant_clear)}, \ - {dll, "StringFromGUID2", reinterpret_cast(&string_from_guid2)} - -} // namespace - -// Registered strictly on the api-ms-win-core-com API sets (not ole32.dll/combase.dll) so rt::shims::owns_dll keeps -// host COM DLLs unbound to pseudo-handles while answering all mapped api-ms-win-core-com-* imports. -SHIM_TABLE(com_shim, - COM_L1_API("api-ms-win-core-com-l1-1-0.dll"), - COM_L1_API("api-ms-win-core-com-l1-1-1.dll"), - COM_L1_API("api-ms-win-core-com-l1-1-2.dll"), - COM_L1_API("api-ms-win-core-com-l1-1-3.dll"), -); diff --git a/runtime/shims/d3d12_com.cpp b/runtime/shims/d3d12_com.cpp deleted file mode 100644 index bd8cd5b75..000000000 --- a/runtime/shims/d3d12_com.cpp +++ /dev/null @@ -1,2091 +0,0 @@ -#include "d3d12_com.h" - -#include "d3d12_stubs.h" // generated -#include "d3d12_com_object.h" -#include "d3d12_fence_waiter.h" -#include "d3d12_trace.h" -#include "d3d12_xs_device.h" -#include "../core/log.h" -#include "../src/gfx10_descriptors.h" - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace rt::d3d12 { - -struct TileGrid { - std::uint64_t columns = 0; - std::uint64_t rows = 0; -}; - -static TileGrid tile_grid(ID3D12Resource* resource) { - if (!resource) return {}; - const auto desc = resource->GetDesc(); - if (desc.Dimension == D3D12_RESOURCE_DIMENSION_BUFFER && desc.Width) - return {1 + (desc.Width - 1) / leonida::tile_size_in_bytes, 1}; - if (!is_sparse_image(resource)) return {}; - constexpr auto shape = leonida::element_tile_shape(false, 4); - return {1 + (desc.Width - 1) / shape.width, 1 + (desc.Height - 1) / shape.height}; -} - -static bool append_tile_regions(const D3D12_TILED_RESOURCE_COORDINATE* start, const D3D12_TILE_REGION_SIZE* size, - TileGrid grid, std::vector& regions) { - const auto x = start ? start->X : 0; - const auto y = start ? start->Y : 0; - if ((start && (start->Z || start->Subresource)) || x >= grid.columns || y >= grid.rows) return false; - const auto first = y * grid.columns + x; - if (size && size->UseBox) { - if (size->Depth != 1 || !size->Width || !size->Height || - size->Width > grid.columns - x || size->Height > grid.rows - y) return false; - for (UINT row = 0; row < size->Height; ++row) - regions.push_back({first + row * grid.columns, size->Width}); - return true; - } - const auto tiles = grid.columns * grid.rows; - const auto count = size ? size->NumTiles : (start ? 1 : tiles); - if (!count || count > tiles - first) return false; - regions.push_back({first, count}); - return true; -} - -void stub(const char* method) { - // Generated API stubs pass a bare method name; explanatory diagnostics are not separate calls. - if (!std::strchr(method, '(')) d3d12_trace::record(method, "unsupported"); - static std::mutex mutex; - static std::set seen; - std::lock_guard lock(mutex); - if (seen.insert(method).second) RT_LOG_WARN("d3d12: unimplemented %s\n", method); -} - -namespace { - -// Reports a deliberate simplification once (unlike stub, which reports a method not implemented). -void note_once(const char* what) { - static std::mutex mutex; - static std::set seen; - std::lock_guard lock(mutex); - if (seen.insert(what).second) RT_LOG_WARN("d3d12: %s\n", what); -} - -const char* name(leonida::ReplayResult result) { - switch (result) { - case leonida::ReplayResult::success: return "success"; - case leonida::ReplayResult::list_open: return "a list is not closed"; - case leonida::ReplayResult::unresolved_resource: return "unknown resource"; - case leonida::ReplayResult::invalid_subresource: return "invalid subresource"; - case leonida::ReplayResult::invalid_clear: return "invalid clear"; - case leonida::ReplayResult::invalid_copy: return "invalid copy or resolve"; - case leonida::ReplayResult::invalid_query: return "invalid query"; - case leonida::ReplayResult::invalid_indirect_arguments: return "invalid indirect argument or count buffer range"; - case leonida::ReplayResult::invalid_draw: return "draw kind does not match the pipeline (mesh or vertex)"; - case leonida::ReplayResult::unsupported: return "unsupported"; - } - return "?"; -} - -// The label of a SetMarker/BeginEvent call, as UTF-8. Metadata says what the data is (WinPixEventRuntime's -// pix3_win.h: PIX_EVENT_UNICODE_VERSION 0, a UTF-16 string; PIX_EVENT_ANSI_VERSION 1, an ANSI string; -// PIX_EVENT_PIX3BLOB_VERSION 2, PIX's own encoded event). Strings end at their terminator or at `size` bytes. The -// PIX3 blob is not decoded (its console form is unmeasured, docs/d3d12_vulkan.md section 4.10); it gets a fixed -// label, so the event still nests. -std::string event_label(UINT metadata, const void* data, UINT size) { - if (!data || !size) return {}; - std::wstring wide; - if (metadata == 0) { - const auto* text = static_cast(data); - const std::size_t limit = size / sizeof(wchar_t); - std::size_t n = 0; - while (n < limit && text[n]) ++n; - wide.assign(text, n); - } else if (metadata == 1) { - const auto* text = static_cast(data); - std::size_t n = 0; - while (n < size && text[n]) ++n; - if (!n) return {}; - const int count = MultiByteToWideChar(CP_ACP, 0, text, int(n), nullptr, 0); - wide.resize(std::size_t(std::max(count, 0))); - if (count > 0) MultiByteToWideChar(CP_ACP, 0, text, int(n), wide.data(), count); - } else { - if (metadata != 2) stub("SetMarker/BeginEvent with unknown metadata"); - return "PIX event"; - } - if (wide.empty()) return {}; - const int count = WideCharToMultiByte(CP_UTF8, 0, wide.data(), int(wide.size()), nullptr, 0, nullptr, nullptr); - std::string out(std::size_t(std::max(count, 0)), '\0'); - if (count > 0) WideCharToMultiByte(CP_UTF8, 0, wide.data(), int(wide.size()), out.data(), count, nullptr, nullptr); - return out; -} - -class CommandSignature final - : public Child { -public: - // {9a4e1c2b-55d8-4f7a-b012-3c8e7a1f6d90} - static constexpr GUID kTag{0x9a4e1c2b, 0x55d8, 0x4f7a, {0xb0, 0x12, 0x3c, 0x8e, 0x7a, 0x1f, 0x6d, 0x90}}; - - CommandSignature(leonida::IndirectKind kind, UINT byte_stride) : kind_(kind), stride_(byte_stride) {} - - leonida::IndirectKind kind() const { return kind_; } - UINT stride() const { return stride_; } - static CommandSignature* from(IUnknown* object) { return Child::from(object); } - -private: - leonida::IndirectKind kind_; - UINT stride_; -}; - -class CommandAllocator final - : public Child { -public: - // {7d0e6b51-34a2-4f0c-9a61-0c5b2e8f4a10}, public in d3d12_xs_device.h: the device proxy's slot 9 wraps an allocator - // in an Xbox-ABI allocator proxy only when it answers this tag, because from() below resolves such a proxy. - static constexpr GUID kTag = d3d12_xs::kLeonidaCommandAllocatorTag; - explicit CommandAllocator(D3D12_COMMAND_LIST_TYPE type) : type_(type) {} - // Lists own their recorded commands, so there is nothing to free. As on the PC runtime (D3D-51, measured by - // d3d12_vulkan_device_test): E_FAIL while a list is recording into this allocator, and S_OK while its lists are - // still executing on the GPU (keeping that safe is the application's job on D3D12 too). - HRESULT STDMETHODCALLTYPE Reset() override { return recording_ ? E_FAIL : S_OK; } - D3D12_COMMAND_LIST_TYPE type() const { return type_; } - // The one list that is recording into this allocator, or null. D3D12 allows one at a time. - const void* recording() const { return recording_; } - void set_recording(const void* list) { recording_ = list; } - // An allocator proxy (the title's allocator from device slot 9) stands for the allocator behind it, so every - // list method that takes an allocator (CreateCommandList, Reset) resolves it here. - static CommandAllocator* from(IUnknown* object) { - if (ID3D12CommandAllocator* real = d3d12_xs::allocator_proxy_real_allocator(object)) object = real; - return Child::from(object); - } - -private: - D3D12_COMMAND_LIST_TYPE type_; - const void* recording_ = nullptr; -}; - -class GraphicsCommandList final - : public Child { -public: - // {2f8a7c33-91d4-4b6e-8e05-6d3f1a9b2c47} - static constexpr GUID kTag{0x2f8a7c33, 0x91d4, 0x4b6e, {0x8e, 0x05, 0x6d, 0x3f, 0x1a, 0x9b, 0x2c, 0x47}}; - explicit GraphicsCommandList(D3D12_COMMAND_LIST_TYPE type) : type_(type) {} - ~GraphicsCommandList() override { - stop_recording(); - release_held(); - } - - // While open, the list holds a reference to the allocator it records into and marks it busy. - void record_into(CommandAllocator* allocator) { - allocator->AddRef(); - allocator->set_recording(this); - allocator_ = allocator; - } - - const leonida::CommandList& commands() const { return list_; } - // The pipeline states and root signatures the recording names (it holds a reference to each until Reset). - const std::vector& pinned() const { return held_; } - UINT front_stencil_ref() const { return front_stencil_ref_; } - UINT back_stencil_ref() const { return back_stencil_ref_; } - D3D12_GPU_VIRTUAL_ADDRESS cbv_srv_uav_base() const { return cbv_srv_uav_base_; } - D3D12_GPU_VIRTUAL_ADDRESS sampler_base() const { return sampler_base_; } - - D3D12_COMMAND_LIST_TYPE STDMETHODCALLTYPE GetType() override { - d3d12_trace::record("ID3D12CommandList::GetType"); - return type_; - } - D3D12_COMMAND_LIST_TYPE type() const { return type_; } - bool invalid() const { return invalid_; } - - // E_INVALIDARG when a call during recording was invalid, or a query was begun and not ended, as D3D12's Close - // reports it. - HRESULT STDMETHODCALLTYPE Close() override { - constexpr auto method = "ID3D12GraphicsCommandList::Close"; - if (list_.queries_open()) invalid_ = true; - if (!list_.close()) return d3d12_trace::result(method, E_FAIL); - stop_recording(); - return d3d12_trace::result(method, invalid_ ? E_INVALIDARG : S_OK); - } - - HRESULT STDMETHODCALLTYPE Reset(ID3D12CommandAllocator* allocator, ID3D12PipelineState* state) override { - constexpr auto method = "ID3D12GraphicsCommandList::Reset"; - CommandAllocator* command_allocator = CommandAllocator::from(allocator); - if (!command_allocator || command_allocator->type() != type_) - return d3d12_trace::result(method, E_INVALIDARG); - // Another list recording into the allocator: E_INVALIDARG, as on the PC runtime (D3D-51). - if (command_allocator->recording() && command_allocator->recording() != this) - return d3d12_trace::result(method, E_INVALIDARG); - if (!list_.reset()) return d3d12_trace::result(method, E_FAIL); // D3D12 resets only closed lists - record_into(command_allocator); - invalid_ = false; - calls_.clear(); - release_held(); // what the old recording used: it was replayed at ExecuteCommandLists - reset_state(state); // Reset returns every list state to its default - if (type_ == D3D12_COMMAND_LIST_TYPE_BUNDLE) set_initial_pipeline(state); // reset_state holds it - return d3d12_trace::result(method, S_OK); - } - - // CreateCommandList's pipeline state. As SetPipelineState on a direct list; on a bundle it is the first deferred - // call, which the application did not make, so it is not traced. - void set_initial_pipeline(ID3D12PipelineState* state) { - if (!state) return; - if (type_ != D3D12_COMMAND_LIST_TYPE_BUNDLE) return SetPipelineState(state); - defer([=](GraphicsCommandList& l) { l.set_pipeline(state); }); - hold(state); - } - - void STDMETHODCALLTYPE ExecuteBundle(ID3D12GraphicsCommandList* command_list) override { - d3d12_trace::record("ID3D12GraphicsCommandList::ExecuteBundle"); - if (list_.closed()) return; - if (type_ != D3D12_COMMAND_LIST_TYPE_DIRECT) return check(false); - GraphicsCommandList* bundle = from(command_list); - if (!bundle || bundle->attached_device() != attached_device() || - bundle->type_ != D3D12_COMMAND_LIST_TYPE_BUNDLE || bundle->invalid_ || !bundle->list_.closed()) - return check(false); - // The bundle's state calls and draws play on this list through the members the application would have - // called, so a draw sees this list's state plus what the bundle set, and what the bundle set stays here - // afterwards (measured on the PC runtime, docs/d3d12_vulkan.md section 3.2). Commands that need no state - // were recorded in the bundle's own list and are copied between them, in order. - std::size_t copied = 0; - for (const BundleCall& call : bundle->calls_) { - if (!list_.execute_bundle(bundle->list_, copied, call.commands)) return check(false); - copied = call.commands; - call.run(*this); - } - check(list_.execute_bundle(bundle->list_, copied)); - } - - // Root signatures, pipeline state and root arguments. The arguments are packed into the 32 user-data dwords - // the translated shaders read (root_signature.h; docs section 3.5); a draw or dispatch records a copy. - void STDMETHODCALLTYPE SetComputeRootSignature(ID3D12RootSignature* signature) override { - d3d12_trace::record("ID3D12GraphicsCommandList::SetComputeRootSignature"); - bind_root(compute_, signature); - } - void STDMETHODCALLTYPE SetGraphicsRootSignature(ID3D12RootSignature* signature) override { - d3d12_trace::record("ID3D12GraphicsCommandList::SetGraphicsRootSignature"); - bind_root(graphics_, signature); - } - - void STDMETHODCALLTYPE SetPipelineState(ID3D12PipelineState* state) override { - d3d12_trace::record("ID3D12GraphicsCommandList::SetPipelineState"); - if (list_.closed()) return; - if (defer([=](GraphicsCommandList& l) { l.set_pipeline(state); })) return hold(state); - set_pipeline(state); - } - - // Validates shader-visible descriptor heaps and tracks bound heap identities/bases (docs/d3d12_vulkan.md §3.2/§3.4). - void STDMETHODCALLTYPE SetDescriptorHeaps(UINT num, ID3D12DescriptorHeap* const* heaps) override { - d3d12_trace::record("ID3D12GraphicsCommandList::SetDescriptorHeaps"); - if (type_ == D3D12_COMMAND_LIST_TYPE_COPY) return check(false); - if (num > 2 || (num && !heaps)) return check(false); - - ID3D12DescriptorHeap* cbv = nullptr; - ID3D12DescriptorHeap* smp = nullptr; - D3D12_GPU_VIRTUAL_ADDRESS cbv_base = 0; - D3D12_GPU_VIRTUAL_ADDRESS smp_base = 0; - IUnknown* const owner = this->attached_device(); - for (UINT i = 0; i < num; ++i) { - ID3D12DescriptorHeap* raw = heaps[i]; - if (!raw) return check(false); - if (ID3D12DescriptorHeap* real = d3d12_xs::heap_proxy_real_heap(raw)) raw = real; - D3D12_DESCRIPTOR_HEAP_DESC desc{}; - D3D12_GPU_VIRTUAL_ADDRESS base = 0; - IUnknown* const heap_owner = descriptor_heap_info(raw, desc, base); - if (!heap_owner || (owner && heap_owner != owner)) return check(false); - if (!(desc.Flags & D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE)) return check(false); - if (desc.Type == D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV) { - if (cbv) return check(false); - cbv = raw; - cbv_base = base; - } else if (desc.Type == D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER) { - if (smp) return check(false); - smp = raw; - smp_base = base; - } else { - return check(false); - } - } - hold(cbv); - hold(smp); - if (defer([=](GraphicsCommandList& l) { l.verify_bundle_descriptor_heaps(cbv, smp); })) return; - set_descriptor_heaps(cbv, cbv_base, smp, smp_base); - } - - void STDMETHODCALLTYPE SetComputeRoot32BitConstant(UINT index, UINT value, UINT offset) override { - constants(compute_, index, 1, &value, offset); - } - void STDMETHODCALLTYPE SetComputeRoot32BitConstants(UINT index, UINT count, const void* data, UINT offset) override { - constants(compute_, index, count, data, offset); - } - void STDMETHODCALLTYPE SetComputeRootConstantBufferView(UINT index, D3D12_GPU_VIRTUAL_ADDRESS va) override { - address(compute_, index, va, rt::rootsig::ParamType::Descriptor); - } - void STDMETHODCALLTYPE SetComputeRootShaderResourceView(UINT index, D3D12_GPU_VIRTUAL_ADDRESS va) override { - address(compute_, index, va, rt::rootsig::ParamType::Descriptor); - } - void STDMETHODCALLTYPE SetComputeRootUnorderedAccessView(UINT index, D3D12_GPU_VIRTUAL_ADDRESS va) override { - address(compute_, index, va, rt::rootsig::ParamType::Descriptor); - } - void STDMETHODCALLTYPE SetComputeRootDescriptorTable(UINT index, D3D12_GPU_DESCRIPTOR_HANDLE table) override { - address(compute_, index, table.ptr, rt::rootsig::ParamType::Table); - } - void STDMETHODCALLTYPE SetGraphicsRoot32BitConstant(UINT index, UINT value, UINT offset) override { - constants(graphics_, index, 1, &value, offset); - } - void STDMETHODCALLTYPE SetGraphicsRoot32BitConstants(UINT index, UINT count, const void* data, UINT offset) override { - constants(graphics_, index, count, data, offset); - } - void STDMETHODCALLTYPE SetGraphicsRootConstantBufferView(UINT index, D3D12_GPU_VIRTUAL_ADDRESS va) override { - address(graphics_, index, va, rt::rootsig::ParamType::Descriptor); - } - void STDMETHODCALLTYPE SetGraphicsRootShaderResourceView(UINT index, D3D12_GPU_VIRTUAL_ADDRESS va) override { - address(graphics_, index, va, rt::rootsig::ParamType::Descriptor); - } - void STDMETHODCALLTYPE SetGraphicsRootUnorderedAccessView(UINT index, D3D12_GPU_VIRTUAL_ADDRESS va) override { - address(graphics_, index, va, rt::rootsig::ParamType::Descriptor); - } - void STDMETHODCALLTYPE SetGraphicsRootDescriptorTable(UINT index, D3D12_GPU_DESCRIPTOR_HANDLE table) override { - d3d12_trace::record("ID3D12GraphicsCommandList::SetGraphicsRootDescriptorTable"); - address(graphics_, index, table.ptr, rt::rootsig::ParamType::Table); - } - - void STDMETHODCALLTYPE Dispatch(UINT x, UINT y, UINT z) override { - d3d12_trace::record("ID3D12GraphicsCommandList::Dispatch"); - if (defer([=](GraphicsCommandList& l) { l.record_dispatch(x, y, z); }, true)) return; - record_dispatch(x, y, z); - } - - // ClearState returns every piece of list state to its default, as Reset does (stencil references and predication - // included). - void STDMETHODCALLTYPE ClearState(ID3D12PipelineState* state) override { - if (list_.closed()) return; - if (type_ == D3D12_COMMAND_LIST_TYPE_BUNDLE) return check(false); - if (!list_.closed()) check(list_.set_predication({0, 0, 0})); - reset_state(state); - } - - // Graphics state. Draws record a copy of it (command_list.h, Draw). - void STDMETHODCALLTYPE IASetPrimitiveTopology(D3D12_PRIMITIVE_TOPOLOGY topology) override { - if (list_.closed()) return; - if (defer([=](GraphicsCommandList& l) { l.topology_ = u(topology); })) return; - topology_ = u(topology); - } - - void STDMETHODCALLTYPE IASetVertexBuffers(UINT start, UINT count, const D3D12_VERTEX_BUFFER_VIEW* views) override { - if (std::uint64_t(start) + count > vertex_buffers_.size()) return check(false); - if (type_ == D3D12_COMMAND_LIST_TYPE_BUNDLE) { - std::vector copy; - if (views) copy.assign(views, views + count); - defer([=, copy = std::move(copy), bound = views != nullptr](GraphicsCommandList& l) { - l.set_vertex_buffers(start, count, bound ? copy.data() : nullptr); - }); - return; - } - set_vertex_buffers(start, count, views); - } - - void STDMETHODCALLTYPE IASetIndexBuffer(const D3D12_INDEX_BUFFER_VIEW* view) override { - if (list_.closed()) return; - const std::optional copy = view ? std::optional(*view) : std::nullopt; - if (defer([=](GraphicsCommandList& l) { l.set_index_buffer(copy ? &*copy : nullptr); })) return; - set_index_buffer(view); - } - - // A count of 0 unbinds the viewports; draws then rasterize nothing (record_draw). - void STDMETHODCALLTYPE RSSetViewports(UINT count, const D3D12_VIEWPORT* viewports) override { - if (type_ == D3D12_COMMAND_LIST_TYPE_BUNDLE) return check(false); - if (!count) { - viewport_ = {}; - return; - } - if (!viewports || count > D3D12_VIEWPORT_AND_SCISSORRECT_OBJECT_COUNT_PER_PIPELINE) return check(false); - if (count > 1) stub("ID3D12GraphicsCommandList::RSSetViewports (more than one viewport; the first is used)"); - const D3D12_VIEWPORT& v = viewports[0]; - viewport_ = {v.TopLeftX, v.TopLeftY, v.Width, v.Height, v.MinDepth, v.MaxDepth}; - } - - void STDMETHODCALLTYPE RSSetScissorRects(UINT count, const D3D12_RECT* rects) override { - if (type_ == D3D12_COMMAND_LIST_TYPE_BUNDLE) return check(false); - // A zero-count call disables all previously bound rectangles; it is not a no-op. - // With no scissor bound, the rasterizer clips every fragment, as on native D3D12. - if (!count) { - scissor_ = {}; - return; - } - if (!rects) return; - if (count > 1) stub("ID3D12GraphicsCommandList::RSSetScissorRects (more than one rectangle; the first is used)"); - scissor_ = {rects[0].left, rects[0].top, rects[0].right, rects[0].bottom}; - } - - // D3D12 reads render-target and depth descriptors here, so their views are copied now. - void STDMETHODCALLTYPE OMSetRenderTargets(UINT count, const D3D12_CPU_DESCRIPTOR_HANDLE* targets, BOOL single_range, - const D3D12_CPU_DESCRIPTOR_HANDLE* depth) override { - if (type_ == D3D12_COMMAND_LIST_TYPE_BUNDLE) return check(false); - if (count > D3D12_SIMULTANEOUS_RENDER_TARGET_COUNT) return check(false); - render_targets_.fill({}); - render_target_count_ = count; - draw_views_stale_ = true; - for (UINT i = 0; i < count && targets; ++i) { - const SIZE_T handle = single_range ? targets[0].ptr + SIZE_T(i) * descriptor_size : targets[i].ptr; - if (handle) render_targets_[i] = *reinterpret_cast(handle); - } - depth_ = depth && depth->ptr ? *reinterpret_cast(depth->ptr) : leonida::TargetView{}; - } - - void STDMETHODCALLTYPE OMSetBlendFactor(const FLOAT factor[4]) override { - if (list_.closed()) return; - const std::array value = factor ? std::array{factor[0], factor[1], factor[2], factor[3]} - : std::array{1, 1, 1, 1}; // null means { 1, 1, 1, 1 } - if (defer([=](GraphicsCommandList& l) { l.blend_factor_ = value; })) return; - blend_factor_ = value; - } - - void STDMETHODCALLTYPE OMSetStencilRef(UINT reference) override { - if (list_.closed()) return; - if (defer([=](GraphicsCommandList& l) { l.front_stencil_ref_ = l.back_stencil_ref_ = reference; })) return; - front_stencil_ref_ = back_stencil_ref_ = reference; - } - - void STDMETHODCALLTYPE DrawInstanced(UINT vertices, UINT instances, UINT first_vertex, UINT first_instance) override { - d3d12_trace::record("ID3D12GraphicsCommandList::DrawInstanced"); - if (defer([=](GraphicsCommandList& l) { l.record_draw(false, vertices, instances, first_vertex, 0, first_instance); }, - true)) - return; - record_draw(false, vertices, instances, first_vertex, 0, first_instance); - } - - void STDMETHODCALLTYPE DrawIndexedInstanced(UINT indices, UINT instances, UINT first_index, INT base_vertex, - UINT first_instance) override { - d3d12_trace::record("ID3D12GraphicsCommandList::DrawIndexedInstanced"); - if (defer([=](GraphicsCommandList& l) { - l.record_draw(true, indices, instances, first_index, base_vertex, first_instance); - }, true)) - return; - record_draw(true, indices, instances, first_index, base_vertex, first_instance); - } - - // ID3D12GraphicsCommandList6: a mesh draw. The bound graphics pipeline must have a mesh shader (checked at - // execution, where the pipeline is resolved). D3D12 caps each count at 65535 and their product at 2^22 - // (D3D12_MS_DISPATCH_MAX_THREAD_GROUPS_PER_GRID); a larger grid is a recording error. - void STDMETHODCALLTYPE DispatchMesh(UINT x, UINT y, UINT z) override { - d3d12_trace::record("ID3D12GraphicsCommandList6::DispatchMesh"); - if (x > 65535 || y > 65535 || z > 65535 || std::uint64_t(x) * y * z > (1u << 22)) return check(false); - if (!graphics_pipeline_ || !graphics_.layout) return check(false); - if (!(viewport_.width > 0) || !(viewport_.height > 0)) return; // as record_draw: nothing is rasterized - leonida::Draw draw{graphics_pipeline_, graphics_.data, draw_views(), depth_, {}, 0, viewport_, - scissor_, blend_factor_, front_stencil_ref_, back_stencil_ref_, false, x, y, z, 0, 0}; - draw.mesh = true; - check(list_.draw(std::move(draw))); - } - - void STDMETHODCALLTYPE ResourceBarrier(UINT count, const D3D12_RESOURCE_BARRIER* barriers) override { - d3d12_trace::record("ID3D12GraphicsCommandList::ResourceBarrier"); - if (type_ == D3D12_COMMAND_LIST_TYPE_BUNDLE) return check(false); - for (UINT i = 0; i < count; ++i) { - const auto& b = barriers[i]; - switch (b.Type) { - case D3D12_RESOURCE_BARRIER_TYPE_TRANSITION: - check(list_.transition({resource_id(b.Transition.pResource), b.Transition.Subresource, - static_cast(b.Transition.StateBefore), - static_cast(b.Transition.StateAfter)}, - static_cast(b.Flags))); - break; - case D3D12_RESOURCE_BARRIER_TYPE_ALIASING: - check(!b.Flags && list_.aliasing_barrier({resource_id(b.Aliasing.pResourceBefore), - resource_id(b.Aliasing.pResourceAfter)})); - break; - case D3D12_RESOURCE_BARRIER_TYPE_UAV: - check(!b.Flags && list_.uav_barrier({resource_id(b.UAV.pResource)})); - break; - default: - check(false); - } - } - } - - void STDMETHODCALLTYPE Barrier(UINT32 groups, const D3D12_BARRIER_GROUP* group) override { - d3d12_trace::record("ID3D12GraphicsCommandList7::Barrier"); - if (type_ == D3D12_COMMAND_LIST_TYPE_BUNDLE) return check(false); - for (UINT32 g = 0; g < groups; ++g) { - for (UINT32 i = 0; i < group[g].NumBarriers; ++i) { - switch (group[g].Type) { - case D3D12_BARRIER_TYPE_GLOBAL: { - const auto& b = group[g].pGlobalBarriers[i]; - check(list_.barrier(leonida::GlobalBarrier{u(b.SyncBefore), u(b.SyncAfter), u(b.AccessBefore), - u(b.AccessAfter)})); - break; - } - case D3D12_BARRIER_TYPE_BUFFER: { - const auto& b = group[g].pBufferBarriers[i]; - check(list_.barrier(leonida::BufferBarrier{u(b.SyncBefore), u(b.SyncAfter), u(b.AccessBefore), - u(b.AccessAfter), resource_id(b.pResource)})); - break; - } - case D3D12_BARRIER_TYPE_TEXTURE: { - const auto& b = group[g].pTextureBarriers[i]; - const auto& r = b.Subresources; - check(list_.barrier(leonida::TextureBarrier{ - u(b.SyncBefore), u(b.SyncAfter), u(b.AccessBefore), u(b.AccessAfter), u(b.LayoutBefore), - u(b.LayoutAfter), resource_id(b.pResource), - {r.IndexOrFirstMipLevel, r.NumMipLevels, r.FirstArraySlice, r.NumArraySlices, r.FirstPlane, - r.NumPlanes}, - u(b.Flags)})); - break; - } - default: - check(false); - } - } - } - } - - void STDMETHODCALLTYPE CopyBufferRegion(ID3D12Resource* dst, UINT64 dst_offset, ID3D12Resource* src, - UINT64 src_offset, UINT64 bytes) override { - d3d12_trace::record("ID3D12GraphicsCommandList::CopyBufferRegion"); - if (type_ == D3D12_COMMAND_LIST_TYPE_BUNDLE) return check(false); - check(list_.copy_buffer({resource_id(dst), dst_offset, resource_id(src), src_offset, bytes})); - } - - void STDMETHODCALLTYPE CopyTiles(ID3D12Resource* tiled, const D3D12_TILED_RESOURCE_COORDINATE* start, - const D3D12_TILE_REGION_SIZE* size, ID3D12Resource* linear, - UINT64 linear_offset, D3D12_TILE_COPY_FLAGS flags) override { - d3d12_trace::record("ID3D12GraphicsCommandList::CopyTiles"); - const auto direction = flags & ~D3D12_TILE_COPY_FLAG_NO_HAZARD; - const bool to_linear = direction == D3D12_TILE_COPY_FLAG_SWIZZLED_TILED_RESOURCE_TO_LINEAR_BUFFER; - const auto grid = tile_grid(tiled); - std::vector regions; - if (!start || !size || !linear || linear == tiled || - !append_tile_regions(start, size, grid, regions) || - (!to_linear && direction != D3D12_TILE_COPY_FLAG_LINEAR_BUFFER_TO_SWIZZLED_TILED_RESOURCE)) - return check(false); - const auto tiled_id = resource_id(tiled), linear_id = resource_id(linear); - if (is_sparse_image(tiled)) { - const auto buffer = linear->GetDesc(); - const auto desc = tiled->GetDesc(); - const auto count = size->UseBox ? std::uint64_t(size->Width) * size->Height : size->NumTiles; - if (type_ == D3D12_COMMAND_LIST_TYPE_BUNDLE || buffer.Dimension != D3D12_RESOURCE_DIMENSION_BUFFER || - linear_offset > buffer.Width || count > (buffer.Width - linear_offset) / leonida::tile_size_in_bytes) - return check(false); - constexpr auto shape = leonida::element_tile_shape(false, 4); - const leonida::CopyLocation image{tiled_id, false, 0, 0, 0, 0, 0, 0}; - for (const auto& region : regions) { - for (std::uint64_t tile = region.first; tile < region.first + region.count; ++tile) { - const auto x = std::uint32_t(tile % grid.columns) * shape.width; - const auto y = std::uint32_t(tile / grid.columns) * shape.height; - const auto width = std::min(shape.width, std::uint32_t(desc.Width) - x); - const auto height = std::min(shape.height, desc.Height - y); - const leonida::CopyLocation footprint{ - linear_id, true, 0, linear_offset, shape.width, shape.height, 1, shape.width * 4}; - auto copy = to_linear - ? leonida::CopyTexture{footprint, 0, 0, 0, image, true, {x, y, 0, x + width, y + height, 1}} - : leonida::CopyTexture{image, x, y, 0, footprint, true, {0, 0, 0, width, height, 1}}; - copy.tile_footprint = true; - check(list_.copy_texture(copy)); - linear_offset += leonida::tile_size_in_bytes; - } - } - return; - } - const auto& region = regions.front(); - const auto tiled_offset = region.first * leonida::tile_size_in_bytes; - const auto bytes = region.count * leonida::tile_size_in_bytes; - check(list_.copy_buffer(to_linear - ? leonida::CopyBuffer{linear_id, linear_offset, tiled_id, tiled_offset, bytes, tiled_id} - : leonida::CopyBuffer{tiled_id, tiled_offset, linear_id, linear_offset, bytes, tiled_id})); - } - - void STDMETHODCALLTYPE CopyTextureRegion(const D3D12_TEXTURE_COPY_LOCATION* dst, UINT x, UINT y, UINT z, - const D3D12_TEXTURE_COPY_LOCATION* src, const D3D12_BOX* box) override { - d3d12_trace::record("ID3D12GraphicsCommandList::CopyTextureRegion"); - if (type_ == D3D12_COMMAND_LIST_TYPE_BUNDLE) return check(false); - if (!dst || !src) return check(false); - leonida::CopyTexture copy{location(*dst), x, y, z, location(*src), box != nullptr, {}}; - if (box) copy.box = {box->left, box->top, box->front, box->right, box->bottom, box->back}; - check(list_.copy_texture(copy)); - } - - void STDMETHODCALLTYPE CopyResource(ID3D12Resource* dst, ID3D12Resource* src) override { - d3d12_trace::record("ID3D12GraphicsCommandList::CopyResource"); - if (type_ == D3D12_COMMAND_LIST_TYPE_BUNDLE) return check(false); - if (dst && dst == src) { - // A self-copy on a DEFAULT heap is a no-op, but an UPLOAD/READBACK resource still cannot - // be both source and destination: native D3D12 rejects it at Close. Check this before - // the no-op is omitted from the recorded command list. - D3D12_HEAP_PROPERTIES properties{}; - if (FAILED(dst->GetHeapProperties(&properties, nullptr)) || - properties.Type != D3D12_HEAP_TYPE_DEFAULT) return check(false); - } - check(list_.copy_resource({resource_id(dst), resource_id(src)})); - } - - // The format picks the member of a typeless family to resolve as; the textures' own format is used. - void STDMETHODCALLTYPE ResolveSubresource(ID3D12Resource* dst, UINT dst_subresource, ID3D12Resource* src, - UINT src_subresource, DXGI_FORMAT format) override { - d3d12_trace::record("ID3D12GraphicsCommandList::ResolveSubresource"); - if (type_ == D3D12_COMMAND_LIST_TYPE_BUNDLE) return check(false); - const auto integer_color = [](ID3D12Resource* resource) { - if (!resource) return false; - const auto desc = resource->GetDesc(); - return !(desc.Flags & D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL) && - color_resolve_format_is_integer(desc.Format); - }; - if (color_resolve_format_is_integer(format) || integer_color(dst) || integer_color(src)) { - note_once("ResolveSubresource refused: integer colour formats cannot be resolved"); - return check(false); - } - check(list_.resolve_subresource({resource_id(dst), dst_subresource, resource_id(src), src_subresource})); - } - - void STDMETHODCALLTYPE ResolveSubresourceRegion(ID3D12Resource* dst, UINT dst_subresource, UINT x, UINT y, - ID3D12Resource* src, UINT src_subresource, D3D12_RECT* rect, - DXGI_FORMAT format, D3D12_RESOLVE_MODE mode) override { - d3d12_trace::record("ID3D12GraphicsCommandList1::ResolveSubresourceRegion"); - if (type_ != D3D12_COMMAND_LIST_TYPE_DIRECT) return check(false); - leonida::ResolveRegion region{x, y, std::nullopt}; - if (mode != D3D12_RESOLVE_MODE_AVERAGE || !color_resolve_format_matches(format, dst, src)) { - if (!depth_stencil_resolve_supported(format, dst, dst_subresource, x, y, src, src_subresource, rect, - mode)) { - note_once("ResolveSubresourceRegion refused: neither an average colour resolve nor a depth or " - "stencil one the device can replay"); - return check(false); - } - region.mode = mode == D3D12_RESOLVE_MODE_MIN ? leonida::d3d12_resolve_mode::minimum - : mode == D3D12_RESOLVE_MODE_MAX ? leonida::d3d12_resolve_mode::maximum - : leonida::d3d12_resolve_mode::average; - } - if (rect) region.src_rect = leonida::Rect{rect->left, rect->top, rect->right, rect->bottom}; - check(list_.resolve_subresource({resource_id(dst), dst_subresource, resource_id(src), src_subresource, region})); - } - - // A null buffer turns predication off (docs/d3d12_vulkan.md section 4.7). Bundles and copy lists may not set it. - // Recording-time checks match live Windows 11 WARP and RTX 5090 D3D12: null buffer requires offset 0 and - // EQUAL_ZERO; a non-null resource must be a non-READBACK buffer with an 8-byte aligned in-bounds range. - void STDMETHODCALLTYPE SetPredication(ID3D12Resource* buffer, UINT64 offset, D3D12_PREDICATION_OP op) override { - d3d12_trace::record("ID3D12GraphicsCommandList::SetPredication"); - if (type_ == D3D12_COMMAND_LIST_TYPE_BUNDLE || type_ == D3D12_COMMAND_LIST_TYPE_COPY) return check(false); - if (!buffer) { - if (offset != 0 || op != D3D12_PREDICATION_OP_EQUAL_ZERO) return check(false); - return check(list_.set_predication({0, 0, 0})); - } - const auto desc = buffer->GetDesc(); - if (desc.Dimension != D3D12_RESOURCE_DIMENSION_BUFFER) return check(false); - if (offset % leonida::predication_alignment != 0 || offset > desc.Width || - desc.Width - offset < leonida::predication_alignment) - return check(false); - D3D12_HEAP_PROPERTIES heap{}; - if (SUCCEEDED(buffer->GetHeapProperties(&heap, nullptr)) && heap.Type == D3D12_HEAP_TYPE_READBACK) - return check(false); - check(list_.set_predication({resource_id(buffer), offset, u(op)})); - } - - void STDMETHODCALLTYPE ClearRenderTargetView(D3D12_CPU_DESCRIPTOR_HANDLE view, const FLOAT color[4], UINT count, - const D3D12_RECT* rects) override { - d3d12_trace::record("ID3D12GraphicsCommandList::ClearRenderTargetView"); - if (type_ == D3D12_COMMAND_LIST_TYPE_BUNDLE) return check(false); - if (!view.ptr || !color) return check(false); - check(list_.clear_render_target(*reinterpret_cast(view.ptr), - {color[0], color[1], color[2], color[3]}, to_rects(count, rects))); - } - - void STDMETHODCALLTYPE ClearDepthStencilView(D3D12_CPU_DESCRIPTOR_HANDLE view, D3D12_CLEAR_FLAGS flags, - FLOAT depth, UINT8 stencil, UINT count, - const D3D12_RECT* rects) override { - d3d12_trace::record("ID3D12GraphicsCommandList::ClearDepthStencilView"); - if (type_ == D3D12_COMMAND_LIST_TYPE_BUNDLE) return check(false); - if (!view.ptr) return check(false); - check(list_.clear_depth_stencil(*reinterpret_cast(view.ptr), u(flags), depth, - stencil, to_rects(count, rects))); - } - - // A null region discards the whole resource. Not allowed in a bundle. - void STDMETHODCALLTYPE DiscardResource(ID3D12Resource* resource, const D3D12_DISCARD_REGION* region) override { - if (type_ == D3D12_COMMAND_LIST_TYPE_BUNDLE) return check(false); - if (!region) return check(list_.discard({resource_id(resource), 0, 0, false, true})); - if (region->NumRects && !region->pRects) return check(false); - check(list_.discard({resource_id(resource), region->FirstSubresource, region->NumSubresources, - region->NumRects != 0})); - } - - // GCL2. A null pModes means DEFAULT for every write. The address is resolved when the list is executed. - // Allowed in a bundle (the API restrictions table of "Recording command lists and bundles"). - void STDMETHODCALLTYPE WriteBufferImmediate(UINT count, const D3D12_WRITEBUFFERIMMEDIATE_PARAMETER* params, - const D3D12_WRITEBUFFERIMMEDIATE_MODE* modes) override { - if (count && !params) return check(false); - for (UINT i = 0; i < count; ++i) - check(list_.write_immediate({params[i].Dest, params[i].Value, modes ? u(modes[i]) : 0})); - } - - // GCL1. Not allowed in a bundle, as no copy is. - void STDMETHODCALLTYPE AtomicCopyBufferUINT(ID3D12Resource* dst, UINT64 dst_offset, ID3D12Resource* src, - UINT64 src_offset, UINT count, ID3D12Resource* const* resources, - const D3D12_SUBRESOURCE_RANGE_UINT64* ranges) override { - atomic_copy(4, dst, dst_offset, src, src_offset, count, resources, ranges); - } - void STDMETHODCALLTYPE AtomicCopyBufferUINT64(ID3D12Resource* dst, UINT64 dst_offset, ID3D12Resource* src, - UINT64 src_offset, UINT count, ID3D12Resource* const* resources, - const D3D12_SUBRESOURCE_RANGE_UINT64* ranges) override { - atomic_copy(8, dst, dst_offset, src, src_offset, count, resources, ranges); - } - - // The CPU handle's slot holds the view as the GFX10 descriptor a shader would load (docs/d3d12_vulkan.md - // section 3.4): a T# for a texture, a V# for a buffer. It is read now, because the slot may be rewritten before - // the list runs. The GPU handle names the same view in a shader-visible heap and is not needed. - void STDMETHODCALLTYPE ClearUnorderedAccessViewUint(D3D12_GPU_DESCRIPTOR_HANDLE, D3D12_CPU_DESCRIPTOR_HANDLE view, - ID3D12Resource* resource, const UINT values[4], UINT count, - const D3D12_RECT* rects) override { - if (!values) return check(false); - clear_unordered_access(view, resource, false, {values[0], values[1], values[2], values[3]}, count, rects); - } - - void STDMETHODCALLTYPE ClearUnorderedAccessViewFloat(D3D12_GPU_DESCRIPTOR_HANDLE, D3D12_CPU_DESCRIPTOR_HANDLE view, - ID3D12Resource* resource, const FLOAT values[4], UINT count, - const D3D12_RECT* rects) override { - if (!values) return check(false); - clear_unordered_access(view, resource, true, - {std::bit_cast(values[0]), std::bit_cast(values[1]), - std::bit_cast(values[2]), std::bit_cast(values[3])}, - count, rects); - } - - // As the host's Close reports it: compute and copy lists hold timestamps only (not even pipeline statistics on - // compute), and bundles no queries at all. - bool query_allowed(D3D12_QUERY_TYPE type) const { - if (type_ == D3D12_COMMAND_LIST_TYPE_DIRECT) return true; - return type_ != D3D12_COMMAND_LIST_TYPE_BUNDLE && type == D3D12_QUERY_TYPE_TIMESTAMP; - } - - // Queries (docs/d3d12_vulkan.md section 4.6). Heap types, index ranges and the destination buffer are checked - // at ExecuteCommandLists, when the heap and the buffer are known. - void STDMETHODCALLTYPE BeginQuery(ID3D12QueryHeap* heap, D3D12_QUERY_TYPE type, UINT index) override { - if (!query_allowed(type)) return check(false); - check(list_.begin_query({query_heap_id(heap), u(type), index})); - } - - void STDMETHODCALLTYPE EndQuery(ID3D12QueryHeap* heap, D3D12_QUERY_TYPE type, UINT index) override { - if (!query_allowed(type)) return check(false); - check(list_.end_query({query_heap_id(heap), u(type), index})); - } - - void STDMETHODCALLTYPE ResolveQueryData(ID3D12QueryHeap* heap, D3D12_QUERY_TYPE type, UINT first, UINT count, - ID3D12Resource* dst, UINT64 offset) override { - if (!query_allowed(type)) return check(false); - check(list_.resolve_queries({query_heap_id(heap), u(type), first, count, resource_id(dst), offset})); - } - - // GCL8. Each draw applies the two faces with vkCmdSetStencilReference(VK_STENCIL_FACE_FRONT_BIT / BACK_BIT). - void STDMETHODCALLTYPE OMSetFrontAndBackStencilRef(UINT front, UINT back) override { - d3d12_trace::record("ID3D12GraphicsCommandList8::OMSetFrontAndBackStencilRef"); - if (list_.closed()) return check(false); - if (defer([=](GraphicsCommandList& l) { - l.front_stencil_ref_ = front; - l.back_stencil_ref_ = back; - })) - return; - front_stencil_ref_ = front; - back_stencil_ref_ = back; - } - - // Debug markers, recorded in order with the other commands and replayed as VK_EXT_debug_utils labels. The trace - // names the call only, never the label. - void STDMETHODCALLTYPE SetMarker(UINT metadata, const void* data, UINT size) override { - d3d12_trace::record("ID3D12GraphicsCommandList::SetMarker"); - check(list_.marker(leonida::DebugMarker::Kind::set, event_label(metadata, data, size))); - } - void STDMETHODCALLTYPE BeginEvent(UINT metadata, const void* data, UINT size) override { - d3d12_trace::record("ID3D12GraphicsCommandList::BeginEvent"); - check(list_.marker(leonida::DebugMarker::Kind::begin, event_label(metadata, data, size))); - } - void STDMETHODCALLTYPE EndEvent() override { - d3d12_trace::record("ID3D12GraphicsCommandList::EndEvent"); - check(list_.marker(leonida::DebugMarker::Kind::end)); - } - - void STDMETHODCALLTYPE ExecuteIndirect(ID3D12CommandSignature* signature, UINT max_command_count, - ID3D12Resource* argument_buffer, UINT64 argument_buffer_offset, - ID3D12Resource* count_buffer, UINT64 count_buffer_offset) override { - if (type_ == D3D12_COMMAND_LIST_TYPE_BUNDLE) return check(false); - leonida::IndirectKind kind = leonida::IndirectKind::draw; - UINT stride = 0; - if (!command_signature_info(signature, kind, stride) || !argument_buffer) - return check(false); - const auto arg_desc = argument_buffer->GetDesc(); - if (arg_desc.Dimension != D3D12_RESOURCE_DIMENSION_BUFFER || argument_buffer_offset % 4 != 0) - return check(false); - if (count_buffer) { - const auto count_desc = count_buffer->GetDesc(); - if (count_desc.Dimension != D3D12_RESOURCE_DIMENSION_BUFFER || count_buffer_offset % 4 != 0 || - count_desc.Width < sizeof(UINT) || count_buffer_offset > count_desc.Width - sizeof(UINT)) - return check(false); - } else if (count_buffer_offset != 0) { - return check(false); - } - // The record size is checked for every call: D3D12 rejects a signature whose stride cannot hold a record - // even when no command runs. The argument span is what the signature can walk, max_command_count * stride: - // the host refuses a range that ends past the buffer (`240` with stride `20` in a `256`-byte buffer), and - // it checks the offset itself when max_command_count is 0, where the required bytes are none. - const UINT64 record_size = - kind == leonida::IndirectKind::draw ? sizeof(D3D12_DRAW_ARGUMENTS) - : kind == leonida::IndirectKind::draw_indexed ? sizeof(D3D12_DRAW_INDEXED_ARGUMENTS) - : kind == leonida::IndirectKind::dispatch ? sizeof(D3D12_DISPATCH_ARGUMENTS) - : 0; - if (!record_size || stride < record_size || stride % 4 != 0) return check(false); - if (argument_buffer_offset > arg_desc.Width || - UINT64(max_command_count) > (arg_desc.Width - argument_buffer_offset) / stride) - return check(false); - leonida::ExecuteIndirect cmd{}; - cmd.kind = kind; - cmd.stride = stride; - cmd.max_count = max_command_count; - cmd.argument_buffer = resource_id(argument_buffer); - cmd.argument_offset = argument_buffer_offset; - cmd.count_buffer = count_buffer ? resource_id(count_buffer) : 0; - cmd.count_offset = count_buffer ? count_buffer_offset : 0; - if (kind == leonida::IndirectKind::dispatch && max_command_count) { // the pipeline and root arguments a Dispatch would record - if (!compute_pipeline_ || !compute_.layout) return check(false); - cmd.pipeline = compute_pipeline_; - cmd.user_data = compute_.data; - } - check(list_.execute_indirect(cmd)); - } - - void STDMETHODCALLTYPE BuildRaytracingAccelerationStructure( - const D3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_DESC* desc, UINT postbuild_count, - const D3D12_RAYTRACING_ACCELERATION_STRUCTURE_POSTBUILD_INFO_DESC* postbuild) override { - if (type_ == D3D12_COMMAND_LIST_TYPE_BUNDLE || !desc) return check(false); - if (postbuild_count && !postbuild) return check(false); - for (UINT i = 0; i < postbuild_count; ++i) { - if (!valid_postbuild_info_type(postbuild[i].InfoType)) return check(false); - } - const auto& in = desc->Inputs; - if (in.Type != D3D12_RAYTRACING_ACCELERATION_STRUCTURE_TYPE_TOP_LEVEL && - in.Type != D3D12_RAYTRACING_ACCELERATION_STRUCTURE_TYPE_BOTTOM_LEVEL) - return check(false); - if (in.DescsLayout != D3D12_ELEMENTS_LAYOUT_ARRAY && - in.DescsLayout != D3D12_ELEMENTS_LAYOUT_ARRAY_OF_POINTERS) - return check(false); - leonida::BuildAccelerationStructure cmd{}; - cmd.is_tlas = (in.Type == D3D12_RAYTRACING_ACCELERATION_STRUCTURE_TYPE_TOP_LEVEL); - cmd.update = (in.Flags & D3D12_RAYTRACING_ACCELERATION_STRUCTURE_BUILD_FLAG_PERFORM_UPDATE) != 0; - if (in.Flags & D3D12_RAYTRACING_ACCELERATION_STRUCTURE_BUILD_FLAG_ALLOW_UPDATE) - cmd.build_flags |= VK_BUILD_ACCELERATION_STRUCTURE_ALLOW_UPDATE_BIT_KHR; - if (in.Flags & D3D12_RAYTRACING_ACCELERATION_STRUCTURE_BUILD_FLAG_ALLOW_COMPACTION) - cmd.build_flags |= VK_BUILD_ACCELERATION_STRUCTURE_ALLOW_COMPACTION_BIT_KHR; - if (in.Flags & D3D12_RAYTRACING_ACCELERATION_STRUCTURE_BUILD_FLAG_PREFER_FAST_TRACE) - cmd.build_flags |= VK_BUILD_ACCELERATION_STRUCTURE_PREFER_FAST_TRACE_BIT_KHR; - if (in.Flags & D3D12_RAYTRACING_ACCELERATION_STRUCTURE_BUILD_FLAG_PREFER_FAST_BUILD) - cmd.build_flags |= VK_BUILD_ACCELERATION_STRUCTURE_PREFER_FAST_BUILD_BIT_KHR; - if (in.Flags & D3D12_RAYTRACING_ACCELERATION_STRUCTURE_BUILD_FLAG_MINIMIZE_MEMORY) - cmd.build_flags |= VK_BUILD_ACCELERATION_STRUCTURE_LOW_MEMORY_BIT_KHR; // XDXR: BOX16 nodes (BLAS) - cmd.dst_va = desc->DestAccelerationStructureData; - cmd.src_va = desc->SourceAccelerationStructureData; - cmd.scratch_va = desc->ScratchAccelerationStructureData; - if (cmd.is_tlas) { - cmd.instances_va = in.InstanceDescs; - cmd.instance_count = in.NumDescs; - cmd.instance_pointers = in.DescsLayout == D3D12_ELEMENTS_LAYOUT_ARRAY_OF_POINTERS; - } else { - for (UINT i = 0; i < in.NumDescs; ++i) { - const D3D12_RAYTRACING_GEOMETRY_DESC* gd = - (in.DescsLayout == D3D12_ELEMENTS_LAYOUT_ARRAY_OF_POINTERS) - ? (in.ppGeometryDescs ? in.ppGeometryDescs[i] : nullptr) - : (in.pGeometryDescs ? &in.pGeometryDescs[i] : nullptr); - if (!gd || gd->Type != D3D12_RAYTRACING_GEOMETRY_TYPE_TRIANGLES) return check(false); - leonida::RtTriangleGeometry t{}; - t.vertex_va = gd->Triangles.VertexBuffer.StartAddress; - t.vertex_count = gd->Triangles.VertexCount; - t.vertex_stride = static_cast(gd->Triangles.VertexBuffer.StrideInBytes); - // The vertex formats D3D12 allows for BLAS builds; any other stays VK_FORMAT_UNDEFINED and the - // build is refused at replay instead of reading the wrong layout. - switch (gd->Triangles.VertexFormat) { - case DXGI_FORMAT_R32G32B32_FLOAT: t.vertex_format = VK_FORMAT_R32G32B32_SFLOAT; break; - case DXGI_FORMAT_R32G32_FLOAT: t.vertex_format = VK_FORMAT_R32G32_SFLOAT; break; - case DXGI_FORMAT_R16G16B16A16_FLOAT: t.vertex_format = VK_FORMAT_R16G16B16A16_SFLOAT; break; - case DXGI_FORMAT_R16G16_FLOAT: t.vertex_format = VK_FORMAT_R16G16_SFLOAT; break; - case DXGI_FORMAT_R16G16B16A16_SNORM: t.vertex_format = VK_FORMAT_R16G16B16A16_SNORM; break; - case DXGI_FORMAT_R16G16_SNORM: t.vertex_format = VK_FORMAT_R16G16_SNORM; break; - default: t.vertex_format = VK_FORMAT_UNDEFINED; break; - } - t.index_va = gd->Triangles.IndexBuffer; - t.index_count = gd->Triangles.IndexCount; - if (gd->Triangles.IndexFormat == DXGI_FORMAT_R16_UINT) - t.index_type = 1; - else if (gd->Triangles.IndexFormat == DXGI_FORMAT_R32_UINT) - t.index_type = 2; - t.transform_va = gd->Triangles.Transform3x4; - t.opaque = (gd->Flags & D3D12_RAYTRACING_GEOMETRY_FLAG_OPAQUE) != 0; - t.flags = static_cast(gd->Flags); - cmd.triangles.push_back(t); - } - } - const std::uint64_t built = cmd.dst_va; - const bool recorded = list_.build_acceleration_structure(std::move(cmd)); - check(recorded); - if (!recorded) return; - // The postbuild values of the structure just built, after it (D3D12 orders them after the build). - for (UINT i = 0; postbuild && i < postbuild_count; ++i) { - leonida::AccelerationStructurePostbuild info{}; - info.dest_va = postbuild[i].DestBuffer; - info.type = static_cast(postbuild[i].InfoType); - info.sources = {built}; - const bool ok = list_.acceleration_structure_postbuild(std::move(info)); - check(ok); - if (!ok) return; - } - } - - void STDMETHODCALLTYPE EmitRaytracingAccelerationStructurePostbuildInfo( - const D3D12_RAYTRACING_ACCELERATION_STRUCTURE_POSTBUILD_INFO_DESC* desc, UINT count, - const D3D12_GPU_VIRTUAL_ADDRESS* sources) override { - if (type_ == D3D12_COMMAND_LIST_TYPE_BUNDLE || !desc || !count || !sources) return check(false); - if (!valid_postbuild_info_type(desc->InfoType)) return check(false); - leonida::AccelerationStructurePostbuild info{}; - info.dest_va = desc->DestBuffer; - info.type = static_cast(desc->InfoType); - info.sources.assign(sources, sources + count); - check(list_.acceleration_structure_postbuild(std::move(info))); - } - - void STDMETHODCALLTYPE CopyRaytracingAccelerationStructure(D3D12_GPU_VIRTUAL_ADDRESS dest, - D3D12_GPU_VIRTUAL_ADDRESS source, - D3D12_RAYTRACING_ACCELERATION_STRUCTURE_COPY_MODE mode) override { - if (type_ == D3D12_COMMAND_LIST_TYPE_BUNDLE) return check(false); - if (!valid_copy_mode(mode)) return check(false); - check(list_.copy_acceleration_structure({dest, source, static_cast(mode)})); - } - - static GraphicsCommandList* from(IUnknown* object) { return Child::from(object); } - -private: - static bool valid_postbuild_info_type(D3D12_RAYTRACING_ACCELERATION_STRUCTURE_POSTBUILD_INFO_TYPE type) { - switch (type) { - case D3D12_RAYTRACING_ACCELERATION_STRUCTURE_POSTBUILD_INFO_COMPACTED_SIZE: - case D3D12_RAYTRACING_ACCELERATION_STRUCTURE_POSTBUILD_INFO_TOOLS_VISUALIZATION: - case D3D12_RAYTRACING_ACCELERATION_STRUCTURE_POSTBUILD_INFO_SERIALIZATION: - case D3D12_RAYTRACING_ACCELERATION_STRUCTURE_POSTBUILD_INFO_CURRENT_SIZE: - return true; - default: - return false; - } - } - - static bool valid_copy_mode(D3D12_RAYTRACING_ACCELERATION_STRUCTURE_COPY_MODE mode) { - switch (mode) { - case D3D12_RAYTRACING_ACCELERATION_STRUCTURE_COPY_MODE_CLONE: - case D3D12_RAYTRACING_ACCELERATION_STRUCTURE_COPY_MODE_COMPACT: - case D3D12_RAYTRACING_ACCELERATION_STRUCTURE_COPY_MODE_VISUALIZATION_DECODE_FOR_TOOLS: - case D3D12_RAYTRACING_ACCELERATION_STRUCTURE_COPY_MODE_SERIALIZE: - case D3D12_RAYTRACING_ACCELERATION_STRUCTURE_COPY_MODE_DESERIALIZE: - return true; - default: - return false; - } - } - template - static std::uint32_t u(E value) { - return static_cast(value); - } - - static leonida::CopyLocation location(const D3D12_TEXTURE_COPY_LOCATION& l) { - if (l.Type == D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT) { - const auto& f = l.PlacedFootprint; - return {resource_id(l.pResource), true, 0, f.Offset, f.Footprint.Width, f.Footprint.Height, - f.Footprint.Depth, f.Footprint.RowPitch}; - } - return {resource_id(l.pResource), false, l.SubresourceIndex, 0, 0, 0, 0, 0}; - } - - static std::vector to_rects(UINT count, const D3D12_RECT* rects) { - std::vector out; - for (UINT i = 0; rects && i < count; ++i) - out.push_back({rects[i].left, rects[i].top, rects[i].right, rects[i].bottom}); - return out; - } - - void check(bool ok) { - if (!ok) invalid_ = true; - } - - void stop_recording() { - if (!allocator_) return; - if (allocator_->recording() == this) allocator_->set_recording(nullptr); - allocator_->Release(); - allocator_ = nullptr; - } - - static UINT subresource_count(const D3D12_RESOURCE_DESC& desc) { - if (desc.Dimension == D3D12_RESOURCE_DIMENSION_BUFFER) return 1; - const UINT mips = desc.MipLevels ? desc.MipLevels : 1u; - const UINT layers = desc.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE3D - ? 1u - : (desc.DepthOrArraySize ? desc.DepthOrArraySize : 1u); - UINT planes = 1; - switch (desc.Format) { - case DXGI_FORMAT_D24_UNORM_S8_UINT: - case DXGI_FORMAT_D32_FLOAT_S8X24_UINT: - case DXGI_FORMAT_R24G8_TYPELESS: - case DXGI_FORMAT_R32G8X24_TYPELESS: - case DXGI_FORMAT_R24_UNORM_X8_TYPELESS: - case DXGI_FORMAT_X24_TYPELESS_G8_UINT: - case DXGI_FORMAT_R32_FLOAT_X8X24_TYPELESS: - case DXGI_FORMAT_X32_TYPELESS_G8X24_UINT: - case DXGI_FORMAT_NV12: - case DXGI_FORMAT_P010: - case DXGI_FORMAT_P016: - planes = 2; - break; - default: - break; - } - return mips * layers * planes; - } - - void atomic_copy(std::uint32_t bytes, ID3D12Resource* dst, UINT64 dst_offset, ID3D12Resource* src, - UINT64 src_offset, UINT count, ID3D12Resource* const* resources, - const D3D12_SUBRESOURCE_RANGE_UINT64* ranges) { - if (type_ == D3D12_COMMAND_LIST_TYPE_BUNDLE || !dst || !src || (count && (!resources || !ranges))) - return check(false); - const auto dst_desc = dst->GetDesc(); - const auto src_desc = src->GetDesc(); - if (dst_desc.Dimension != D3D12_RESOURCE_DIMENSION_BUFFER || - src_desc.Dimension != D3D12_RESOURCE_DIMENSION_BUFFER) - return check(false); - if (dst_offset % bytes != 0 || src_offset % bytes != 0 || dst_offset > dst_desc.Width || - dst_desc.Width - dst_offset < bytes || src_offset > src_desc.Width || src_desc.Width - src_offset < bytes) - return check(false); - leonida::AtomicCopyBuffer copy{resource_id(dst), dst_offset, resource_id(src), src_offset, bytes, {}}; - copy.dependencies.reserve(count); - for (UINT i = 0; i < count; ++i) { - ID3D12Resource* dep = resources[i]; - if (!dep) return check(false); - const auto dep_desc = dep->GetDesc(); - const auto& r = ranges[i]; - UINT64 begin = r.Range.Begin; - UINT64 end = r.Range.End; - if (dep_desc.Dimension == D3D12_RESOURCE_DIMENSION_BUFFER) { - if (r.Subresource != 0) return check(false); - if (begin >= end || (end != UINT64_MAX && end > dep_desc.Width)) - return check(false); - } else { - const UINT total_subresources = subresource_count(dep_desc); - if (r.Subresource != D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES && r.Subresource >= total_subresources) - return check(false); - if (begin != 0 || end != UINT64_MAX) return check(false); - } - copy.dependencies.push_back({resource_id(dep), r.Subresource, begin, end}); - } - check(list_.atomic_copy(copy)); - } - - void clear_unordered_access(D3D12_CPU_DESCRIPTOR_HANDLE view, ID3D12Resource* resource, bool is_float, - const std::array& values, UINT count, const D3D12_RECT* rects) { - if (type_ == D3D12_COMMAND_LIST_TYPE_BUNDLE) return check(false); // no clear is allowed in a bundle - leonida::UavView target{}; - if (!view.ptr || !resource || !unordered_access_view(view, resource, target)) return check(false); - check(list_.clear_unordered_access(target, is_float, values, to_rects(count, rects))); - } - - // The Vulkan format a descriptor's FORMAT and DST_SEL name: a UAV has no component mapping of its own, so its - // DST_SEL is the one its format reads R, G, B, A with (gfx10::format_swizzle), which tells B8G8R8A8 from - // R8G8B8A8. VK_FORMAT_UNDEFINED: not a format the table has. - static VkFormat descriptor_format(std::uint32_t code, const leonida::gfx10::Swizzle& swizzle) { - for (const auto& row : leonida::gfx10::format_table) - if (row.gfx10 == code && row.channels == swizzle) return row.vulkan; - return leonida::gfx10::vulkan_format(code); - } - - // A V#: stride 0 and no format is a raw buffer of NUM_RECORDS bytes, a stride without a format a structured one - // of NUM_RECORDS records, and a format a typed one of NUM_RECORDS elements. Its address is a GPU VA, so the - // view starts at that minus the resource's own. - static bool unordered_access_view(D3D12_CPU_DESCRIPTOR_HANDLE handle, ID3D12Resource* resource, - leonida::UavView& out) { - namespace g = leonida::gfx10; - g::ImageWords words{}; - std::memcpy(words.data(), reinterpret_cast(handle.ptr), sizeof(words)); - out.resource = resource_id(resource); - if (g::is_image(words)) { - g::Image image{}; - if (!g::decode(words, image)) return false; - const bool volume = image.type == g::ImageType::image_3d; - out.buffer = false; - out.format = std::uint32_t(descriptor_format(image.format, image.swizzle)); - out.mip = image.first_mip; - out.first_layer = volume ? 0 : image.first_layer; // a 3D view clears every slice of its mip - out.layer_count = volume ? 1 : image.layer_count; - return out.format != VK_FORMAT_UNDEFINED; - } - g::BufferWords buffer_words{}; - std::memcpy(buffer_words.data(), words.data(), sizeof(buffer_words)); - g::Buffer buffer{}; - if (!g::decode(buffer_words, buffer)) return false; - const UINT64 base = resource->GetGPUVirtualAddress(); - if (buffer.address < base) return false; - out.buffer = true; - out.offset = buffer.address - base; - if (buffer.format) { - const VkFormat format = descriptor_format(buffer.format, buffer.swizzle); - const auto* layout = leonida::uav_clear::layout(format); - if (!layout) return false; // not a typed-UAV format - out.format = std::uint32_t(format); - out.element_size = layout->bytes; - out.size = std::uint64_t(buffer.num_records) * layout->bytes; - } else if (buffer.stride) { - out.element_size = buffer.stride; - out.size = std::uint64_t(buffer.num_records) * buffer.stride; - } else { - out.element_size = 4; - out.size = buffer.num_records; - } - return true; - } - - struct RootState { - const RootArgumentLayout* layout = nullptr; - std::array data{}; - }; - - // D3D12 leaves root arguments undefined after a root-signature change; they start at zero here. Setting the - // signature that is already bound changes nothing: "existing root signature bindings do not become stale" - // (D3D12, "Using a Root Signature"), and engines rebind routinely. - void bind_root(RootState& state, ID3D12RootSignature* signature) { - if (list_.closed()) return; - const RootArgumentLayout* layout = root_signature_layout(signature); - if (signature && !layout) { - stub("ID3D12GraphicsCommandList::Set*RootSignature(foreign root signature)"); - return check(false); - } - if (defer([=, compute = &state == &compute_](GraphicsCommandList& l) { - l.bind_root(compute ? l.compute_ : l.graphics_, signature); - })) - return hold(signature); // the bundle keeps it for as long as it can be executed - if (layout && layout == state.layout) return; - hold(signature); // state.layout points into it - state.layout = layout; - state.data = {}; - // CreateRootSignature accepted it for the other bind point only (its log line says why). - if (layout && !(is_compute(state) ? layout->compute_ok : layout->graphics_ok)) { - stub(is_compute(state) ? "SetComputeRootSignature(signature that does not fit the compute layout)" - : "SetGraphicsRootSignature(signature that does not fit the graphics layout)"); - check(false); - } - } - - bool is_compute(const RootState& state) const { return &state == &compute_; } - - // The parameter's first user-data dword at this bind point (RootArgumentLayout). - std::uint32_t first_dword(const RootState& state, const RootArgumentLayout::Parameter& p) const { - return is_compute(state) ? p.compute_offset : p.user_offset; - } - - // The parameter, if it exists and has the expected type; null after recording an invalid call. - const RootArgumentLayout::Parameter* parameter(RootState& state, UINT index, rt::rootsig::ParamType type) { - if (!state.layout || index >= state.layout->parameters.size() || - state.layout->parameters[index].type != type) { - check(false); - return nullptr; - } - return &state.layout->parameters[index]; - } - - // Dwords beyond the 32 user registers are what the console spills to memory; that layout is still open. - void write(RootState& state, std::uint32_t dword, std::uint32_t value) { - if (dword < rt::rootsig::kMaxUserSgprs) - state.data[dword] = value; - else - stub("root arguments beyond 32 user-data dwords (spill not modelled)"); - } - - void constants(RootState& state, UINT index, UINT count, const void* data, UINT offset) { - if (list_.closed()) return; - if (type_ == D3D12_COMMAND_LIST_TYPE_BUNDLE) { - // The layout is the executing list's, so the range is checked when it runs; no signature takes more - // than D3D12_MAX_ROOT_COST dwords, which bounds what is copied from the caller's memory. - if (count > D3D12_MAX_ROOT_COST || (count && !data)) return check(false); - const auto* words = static_cast(data); - std::vector copy; - if (count) copy.assign(words, words + count); - defer([=, compute = &state == &compute_, copy = std::move(copy)](GraphicsCommandList& l) { - l.constants(compute ? l.compute_ : l.graphics_, index, count, - copy.empty() ? nullptr : copy.data(), offset); - }); - return; - } - const RootArgumentLayout::Parameter* p = parameter(state, index, rt::rootsig::ParamType::Constants); - if (!p) return; - if ((count && !data) || std::uint64_t(offset) + count > p->constant_count) return check(false); - const auto* values = static_cast(data); - const std::uint32_t first = first_dword(state, *p); - for (UINT i = 0; i < count; ++i) write(state, first + offset + i, values[i]); - } - - void address(RootState& state, UINT index, std::uint64_t va, rt::rootsig::ParamType type) { - if (list_.closed()) return; - if (defer([=, compute = &state == &compute_](GraphicsCommandList& l) { - l.address(compute ? l.compute_ : l.graphics_, index, va, type); - })) - return; - const RootArgumentLayout::Parameter* p = parameter(state, index, type); - if (!p) return; - const std::uint32_t first = first_dword(state, *p); - write(state, first, std::uint32_t(va)); - // In the compute layout a descriptor table is one dword, the 32-bit VA of its first descriptor (the heaps - // live below 4 GiB); a root view keeps both halves. The graphics layout gives every address two dwords. - if (!(is_compute(state) && type == rt::rootsig::ParamType::Table)) write(state, first + 1, std::uint32_t(va >> 32)); - } - - D3D12_COMMAND_LIST_TYPE type_; - CommandAllocator* allocator_ = nullptr; // referenced while the list is open - leonida::CommandList list_; - bool invalid_ = false; - UINT front_stencil_ref_ = 0; - UINT back_stencil_ref_ = 0; - RootState compute_; - RootState graphics_; - std::uintptr_t compute_pipeline_ = 0; - std::uintptr_t graphics_pipeline_ = 0; - ID3D12DescriptorHeap* cbv_srv_uav_heap_ = nullptr; - ID3D12DescriptorHeap* sampler_heap_ = nullptr; - D3D12_GPU_VIRTUAL_ADDRESS cbv_srv_uav_base_ = 0; - D3D12_GPU_VIRTUAL_ADDRESS sampler_base_ = 0; - std::uint32_t topology_ = 0; // D3D_PRIMITIVE_TOPOLOGY_UNDEFINED - std::array vertex_buffers_{}; - leonida::IndexBufferView index_{}; - leonida::Viewport viewport_{}; - leonida::Rect scissor_{}; - std::array render_targets_{}; - UINT render_target_count_ = 0; - // One block shared by every draw that keeps the same targets and buffers, rebuilt when either changes, so a - // run of draws does not allocate per draw. - std::shared_ptr draw_views_; - bool draw_views_stale_ = true; - leonida::TargetView depth_{}; - std::array blend_factor_{1, 1, 1, 1}; - - // The root signatures and pipeline states this recording uses. D3D12 lets an application release them right - // after Set*RootSignature / SetPipelineState; the list keeps them until Reset or its own release, so the root - // layout it reads and the pipeline ExecuteCommandLists looks up still exist. (Keeping them alive while the GPU - // runs the submission stays the application's job, as in D3D12.) - std::vector held_; - - // A bundle keeps its state calls and draws instead of applying them: it has no render targets, viewport or root - // signature of its own to resolve them against, and what it sets belongs to the list that executes it. - // `commands` is how much of the bundle's own list was recorded before the call, so ExecuteBundle can replay the - // calls and copy the state-free commands (markers, immediate writes) in their original order. Returns whether the - // call was kept; on any other list it is false and the caller does the work. - struct BundleCall { - std::size_t commands; - std::function run; - }; - std::vector calls_; - - // Every deferred call replays through a private member that does not trace: the trace line is written once, when - // the application makes the call, and not again at each ExecuteBundle. After Close nothing is appended, since - // another list may be executing the bundle: a state call is ignored, and a draw or dispatch (`command`) makes - // the list invalid. - bool defer(std::function run, bool command = false) { - if (type_ != D3D12_COMMAND_LIST_TYPE_BUNDLE) return false; - if (list_.closed()) { - if (command) check(false); - return true; - } - calls_.push_back({list_.commands().size(), std::move(run)}); - return true; - } - - void hold(IUnknown* object) { - if (!object || std::find(held_.begin(), held_.end(), object) != held_.end()) return; - object->AddRef(); - held_.push_back(object); - } - - void release_held() { - for (IUnknown* object : held_) object->Release(); - held_.clear(); - } - - void set_pipeline(ID3D12PipelineState* state) { - hold(state); - compute_pipeline_ = compute_pipeline_id(state); - graphics_pipeline_ = graphics_pipeline_id(state); - if (state && !compute_pipeline_ && !graphics_pipeline_) - stub("ID3D12GraphicsCommandList::SetPipelineState(pipeline from another device)"); - } - - void set_descriptor_heaps(ID3D12DescriptorHeap* cbv, D3D12_GPU_VIRTUAL_ADDRESS cbv_base, - ID3D12DescriptorHeap* smp, D3D12_GPU_VIRTUAL_ADDRESS smp_base) { - cbv_srv_uav_heap_ = cbv; - cbv_srv_uav_base_ = cbv_base; - sampler_heap_ = smp; - sampler_base_ = smp_base; - } - - // D3D12 bundle rule: every non-null heap bound by a bundle's SetDescriptorHeaps must match the parent list's - // currently bound heap of that type, without clearing any omitted heap slot on the parent. - void verify_bundle_descriptor_heaps(ID3D12DescriptorHeap* cbv, ID3D12DescriptorHeap* smp) { - if ((cbv && cbv != cbv_srv_uav_heap_) || (smp && smp != sampler_heap_)) check(false); - } - - void note_direct_heap_indexing(const RootArgumentLayout* layout) const { - if (!layout) return; - if (layout->flags & D3D12_ROOT_SIGNATURE_FLAG_CBV_SRV_UAV_HEAP_DIRECTLY_INDEXED) { - if (!cbv_srv_uav_heap_) - note_once("draw/dispatch uses CBV_SRV_UAV_HEAP_DIRECTLY_INDEXED with no CBV/SRV/UAV heap bound"); - else - note_once("CBV_SRV_UAV_HEAP_DIRECTLY_INDEXED heap base tracked on list (SGPR slot open, section 3.4)"); - } - if (layout->flags & D3D12_ROOT_SIGNATURE_FLAG_SAMPLER_HEAP_DIRECTLY_INDEXED) { - if (!sampler_heap_) - note_once("draw/dispatch uses SAMPLER_HEAP_DIRECTLY_INDEXED with no sampler heap bound"); - else - note_once("SAMPLER_HEAP_DIRECTLY_INDEXED heap base tracked on list (SGPR slot open, section 3.4)"); - } - } - - void reset_state(ID3D12PipelineState* state) { - front_stencil_ref_ = back_stencil_ref_ = 0; - compute_ = {}; - graphics_ = {}; - cbv_srv_uav_heap_ = nullptr; - sampler_heap_ = nullptr; - cbv_srv_uav_base_ = 0; - sampler_base_ = 0; - topology_ = 0; - vertex_buffers_ = {}; - index_ = {}; - viewport_ = {}; - scissor_ = {}; - render_targets_.fill({}); - render_target_count_ = 0; - draw_views_stale_ = true; - depth_ = {}; - blend_factor_ = {1, 1, 1, 1}; - set_pipeline(state); - } - - void set_vertex_buffers(UINT start, UINT count, const D3D12_VERTEX_BUFFER_VIEW* views) { - if (count) draw_views_stale_ = true; - for (UINT i = 0; i < count; ++i) - vertex_buffers_[start + i] = views ? leonida::VertexBufferView{views[i].BufferLocation, views[i].SizeInBytes, - views[i].StrideInBytes} - : leonida::VertexBufferView{}; - } - - void set_index_buffer(const D3D12_INDEX_BUFFER_VIEW* view) { - index_ = view ? leonida::IndexBufferView{view->BufferLocation, view->SizeInBytes, u(view->Format)} - : leonida::IndexBufferView{}; - } - - void record_dispatch(UINT x, UINT y, UINT z) { - if (!compute_pipeline_ || !compute_.layout) return check(false); - note_direct_heap_indexing(compute_.layout); - check(list_.dispatch({compute_pipeline_, compute_.data, x, y, z})); - } - - // The views block a draw records. Rebuilt only when the render targets or the bound vertex buffers change. - const std::shared_ptr& draw_views() { - if (draw_views_stale_ || !draw_views_) { - auto views = std::make_shared(); - views->render_targets = render_targets_; - views->vertex_buffers = vertex_buffers_; - views->render_target_count = render_target_count_; - draw_views_ = std::move(views); - draw_views_stale_ = false; - } - return draw_views_; - } - - // A draw needs a graphics pipeline, a graphics root signature and a topology. - void record_draw(bool indexed, UINT count, UINT instances, UINT first, INT base_vertex, UINT first_instance) { - if (!graphics_pipeline_ || !graphics_.layout || !topology_) return check(false); - note_direct_heap_indexing(graphics_.layout); - // No viewport (never set, or unbound with RSSetViewports(0)) or an empty one: D3D12 rasterizes nothing, - // and Vulkan forbids a 0x0 viewport, so the draw is not recorded. - if (!(viewport_.width > 0) || !(viewport_.height > 0)) return; - leonida::Draw draw{graphics_pipeline_, graphics_.data, draw_views(), depth_, index_, topology_, viewport_, - scissor_, blend_factor_, front_stencil_ref_, back_stencil_ref_, indexed, count, instances, - first, base_vertex, first_instance}; - check(list_.draw(std::move(draw))); - } -}; - -class Fence final - : public Child { -public: - // {b4c39e02-6f71-4d8a-b25e-3e9d0f6c1a88} - static constexpr GUID kTag{0xb4c39e02, 0x6f71, 0x4d8a, {0xb2, 0x5e, 0x3e, 0x9d, 0x0f, 0x6c, 0x1a, 0x88}}; - - Fence(leonida::VulkanContext& context, UINT64 initial, D3D12_FENCE_FLAGS flags) - : context_(context), fence_(context, initial), flags_(flags), highest_(initial) {} - - // As in D3D12, releasing the fence completes the waits still pending on it (ALL counts it as one fence). - ~Fence() override { context_.cancel_fence_waits(fence_.semaphore()); } - - bool ok() const { return fence_.semaphore() != VK_NULL_HANDLE; } - VkSemaphore semaphore() const { return fence_.semaphore(); } - const leonida::VulkanContext* context() const { return &context_; } - - // A Vulkan timeline only increases; D3D12 allows setting a fence lower. Such a signal is reported and dropped. - // A queue's claim also records the value as one the GPU will signal, which a later CPU signal must not overtake. - bool claim(UINT64 value, bool queue = false) { - std::lock_guard lock(claim_mutex_); - return claim_locked(value, queue); - } - - UINT64 STDMETHODCALLTYPE GetCompletedValue() override { - return context_.is_device_lost() ? UINT64_MAX : fence_.completed(); - } - D3D12_FENCE_FLAGS STDMETHODCALLTYPE GetCreationFlags() override { return flags_; } - - // vkSignalSemaphore must stay below every signal still pending on the GPU - // (VUID-VkSemaphoreSignalInfo-value-03259). A CPU signal above a queue signal the GPU has not reached yet, or - // made while an earlier one is held, is held: the fence dispatcher applies it once the GPU passes that queue - // value, in the order the signals were made. Until then GetCompletedValue reads the GPU's progress, where D3D12 - // would already read `value`. - HRESULT STDMETHODCALLTYPE Signal(UINT64 value) override { - std::lock_guard lock(claim_mutex_); - if (!claim_locked(value, false)) return S_OK; - const UINT64 queued = queued_; - if (held_->load() == 0 && fence_.completed() >= queued) return fence_.signal(value) ? S_OK : E_FAIL; - held_->fetch_add(1); - // The callback must not touch the fence, which may be released first. Released (cancel) or device lost, - // the queue value may not be reached, and signalling then would break the same rule: the signal is dropped. - leonida::VulkanContext* context = &context_; - const VkSemaphore semaphore = fence_.semaphore(); - context_.enqueue_fence_callback(semaphore, queued, [context, semaphore, queued, value, held = held_] { - std::uint64_t now = 0; - bool signaled = false; - if (context->vk.vkGetSemaphoreCounterValue(context->device(), semaphore, &now) == VK_SUCCESS && - now >= queued && now < value) { - VkSemaphoreSignalInfo info{VK_STRUCTURE_TYPE_SEMAPHORE_SIGNAL_INFO}; - info.semaphore = semaphore; - info.value = value; - signaled = context->vk.vkSignalSemaphore(context->device(), &info) == VK_SUCCESS; - } - held->fetch_sub(1); - if (signaled) { - context->holds().signaled(semaphore, value); - context->holds().pump_ready(); - } - }); - return S_OK; - } - - // A null event blocks until the value is reached, as D3D12 does. - HRESULT STDMETHODCALLTYPE SetEventOnCompletion(UINT64 value, HANDLE event) override { - if (context_.is_device_lost() || fence_.completed() >= value) { - if (event) SetEvent(event); - return S_OK; - } - if (!event) return fence_.wait(value, UINT64_MAX) ? S_OK : E_FAIL; - context_.enqueue_fence_wait(fence_.semaphore(), value, event); - return S_OK; - } - - // Counts `waiter` down once this fence reaches `value`: now if it has, else via the centralized dispatcher. - void notify(UINT64 value, std::shared_ptr waiter) { - if (context_.is_device_lost() || fence_.completed() >= value) { - waiter->hit(); - return; - } - context_.enqueue_fence_callback(fence_.semaphore(), value, [w = std::move(waiter)] { w->hit(); }); - } - - static Fence* from(IUnknown* object) { return Child::from(object); } - -private: - bool claim_locked(UINT64 value, bool queue) { - if (value <= highest_) { - RT_LOG_ERROR("d3d12: fence signal %llu is not above %llu; Vulkan timelines cannot go back\n", - static_cast(value), static_cast(highest_)); - return false; - } - highest_ = value; - if (queue) queued_ = value; - return true; - } - - leonida::VulkanContext& context_; - leonida::VulkanFence fence_; - D3D12_FENCE_FLAGS flags_; - std::mutex claim_mutex_; - UINT64 highest_; // the highest value claimed, from either side - UINT64 queued_ = 0; // the highest value a queue will signal - std::shared_ptr> held_ = std::make_shared>(0); // CPU signals not applied yet -}; - -class CommandQueue final - : public Child { -public: - // {e1a85d76-0b3f-4c29-a7d4-58f2c6e0b913} - static constexpr GUID kTag{0xe1a85d76, 0x0b3f, 0x4c29, {0xa7, 0xd4, 0x58, 0xf2, 0xc6, 0xe0, 0xb9, 0x13}}; - - // What a held batch (queue_holds.h) keeps alive until it has run: the pipeline states and root signatures its - // lists name, which the application may release and Reset away as soon as ExecuteCommandLists returns. Resources - // are not held (a D3D12 application keeps them until the fence it signals; the docs, section 4.4, list this). - static std::shared_ptr pin_lists(const std::vector& lists) { - auto objects = std::shared_ptr>(new std::vector, [](auto* held) { - for (IUnknown* object : *held) object->Release(); - delete held; - }); - for (const GraphicsCommandList* list : lists) - for (IUnknown* object : list->pinned()) { - object->AddRef(); - objects->push_back(object); - } - return objects; - } - - // A D3D12 queue holds the fences it waits on and signals until the work has been submitted. - static leonida::VulkanQueue::PinFn fence_pin(ID3D12Fence* fence) { - return [fence]() -> std::shared_ptr { - fence->AddRef(); - return std::shared_ptr(fence, [](void* held) { static_cast(held)->Release(); }); - }; - } - - static leonida::VulkanQueue::QueueKind queue_kind_for(D3D12_COMMAND_LIST_TYPE type) { - if (type == D3D12_COMMAND_LIST_TYPE_COPY) return leonida::VulkanQueue::QueueKind::copy; - if (type == D3D12_COMMAND_LIST_TYPE_COMPUTE) return leonida::VulkanQueue::QueueKind::compute; - return leonida::VulkanQueue::QueueKind::direct; - } - - CommandQueue(leonida::VulkanContext& context, VkQueue queue, std::uint32_t family, - const D3D12_COMMAND_QUEUE_DESC& desc, const QueueClock& clock, std::shared_ptr queue_lease) - : desc_(desc), context_(context), queue_lease_(std::move(queue_lease)), - queue_(context, queue, family, queue_kind_for(desc.Type)), - vk_queue_(queue), family_(family), clock_(clock) {} - - ~CommandQueue() override { - if (!stamp_.pool) return; - const VkDevice device = context_.device(); - stamp_.destroy_query_pool(device, stamp_.queries, nullptr); - context_.vk.vkDestroyCommandPool(device, stamp_.pool, nullptr); - } - - bool ok() const { return queue_.ok(); } - leonida::ReplayResult last_result() { - // A batch the queue held fails when it is released, after the call returned: the failure is the result. - if (const auto held = queue_.take_held_failure(); held != leonida::ReplayResult::success) last_result_ = held; - return last_result_; - } - - D3D12_COMMAND_QUEUE_DESC STDMETHODCALLTYPE GetDesc() override { - d3d12_trace::record("ID3D12CommandQueue::GetDesc"); - D3D12_COMMAND_QUEUE_DESC desc = desc_; - if (!desc.NodeMask) desc.NodeMask = 1; // node mask 0 reads back as the one node, as on the host - return desc; - } - - void STDMETHODCALLTYPE ExecuteCommandLists(UINT count, ID3D12CommandList* const* lists) override { - constexpr auto method = "ID3D12CommandQueue::ExecuteCommandLists"; - std::lock_guard lock(mutex_); - if (count > 0 && !lists) { - note_once("ExecuteCommandLists: null command list array with non-zero count"); - last_result_ = leonida::ReplayResult::unsupported; - d3d12_trace::record(method, "failed"); - return; - } - std::vector recorded; - std::vector graphics; - for (UINT i = 0; i < count; ++i) { - const GraphicsCommandList* list = GraphicsCommandList::from(lists[i]); - if (!list || list->type() == D3D12_COMMAND_LIST_TYPE_BUNDLE) { - RT_LOG_ERROR("d3d12: ExecuteCommandLists: list %u is not a direct command list\n", i); - last_result_ = leonida::ReplayResult::unsupported; - d3d12_trace::record(method, "failed"); - return; - } - if (list->attached_device() != attached_device()) { - RT_LOG_ERROR("d3d12: ExecuteCommandLists: list %u belongs to a different device; refusing batch\n", i); - last_result_ = leonida::ReplayResult::unsupported; - d3d12_trace::record(method, "failed"); - return; - } - // A list runs only on a queue of its own type (the debug layer's EXECUTECOMMANDLISTS_COMMANDLISTMISMATCH, - // message 836): a DIRECT list's draws would otherwise be recorded for a COPY queue's transfer-only - // Vulkan family. The whole batch is refused, as for the other checks here. - if (list->type() != desc_.Type) { - RT_LOG_ERROR("d3d12: ExecuteCommandLists: list %u has type %d, the queue type %d\n", i, - int(list->type()), int(desc_.Type)); - last_result_ = leonida::ReplayResult::unsupported; - d3d12_trace::record(method, "failed"); - return; - } - // A list whose recording failed (Close returned E_INVALIDARG) must not replay its earlier commands. - if (list->invalid()) { - RT_LOG_ERROR("d3d12: ExecuteCommandLists: list %u is invalid; refusing batch\n", i); - last_result_ = leonida::ReplayResult::unsupported; - d3d12_trace::record(method, "failed"); - return; - } - if (!timestamps_fit(*list)) { - last_result_ = leonida::ReplayResult::invalid_query; - d3d12_trace::record(method, "failed"); - return; - } - recorded.push_back(&list->commands()); - graphics.push_back(list); - } - last_result_ = queue_.execute(recorded, [&graphics] { return pin_lists(graphics); }); - d3d12_trace::record(method, last_result_ == leonida::ReplayResult::success ? "ok" : "failed"); - if (last_result_ != leonida::ReplayResult::success) - RT_LOG_ERROR("d3d12: ExecuteCommandLists failed: %s; nothing was submitted\n", name(last_result_)); - } - - // A copy list's timestamps go to COPY_QUEUE_TIMESTAMP heaps and every other list's to TIMESTAMP heaps. - bool timestamps_fit(const GraphicsCommandList& list) { - namespace h = leonida::d3d12_query_heap; - const auto other = list.type() == D3D12_COMMAND_LIST_TYPE_COPY ? h::timestamp : h::copy_queue_timestamp; - for (const auto& command : list.commands().commands()) { - const auto range = leonida::query_range(command); - if (range.count && range.type == leonida::d3d12_query::timestamp && - context_.query_heap_type(range.heap) == other) - return false; - } - return true; - } - - void STDMETHODCALLTYPE UpdateTileMappings(ID3D12Resource* resource, UINT region_count, - const D3D12_TILED_RESOURCE_COORDINATE* starts, - const D3D12_TILE_REGION_SIZE* sizes, ID3D12Heap* heap, UINT range_count, - const D3D12_TILE_RANGE_FLAGS* flags, const UINT* offsets, - const UINT* counts, D3D12_TILE_MAPPING_FLAGS mapping_flags) override { - constexpr auto method = "ID3D12CommandQueue::UpdateTileMappings"; - if (!update_tiles(resource, region_count, starts, sizes, heap, range_count, flags, offsets, counts, - mapping_flags)) { - d3d12_trace::record(method, "refused"); - note_once("ID3D12CommandQueue::UpdateTileMappings: invalid mapping or sparse residency unavailable"); - } else { - d3d12_trace::record(method, "ok"); - } - } - - void STDMETHODCALLTYPE CopyTileMappings(ID3D12Resource* dst, const D3D12_TILED_RESOURCE_COORDINATE* dst_start, - ID3D12Resource* src, const D3D12_TILED_RESOURCE_COORDINATE* src_start, - const D3D12_TILE_REGION_SIZE* size, D3D12_TILE_MAPPING_FLAGS flags) override { - constexpr auto method = "ID3D12CommandQueue::CopyTileMappings"; - std::lock_guard lock(mutex_); - std::vector from, to; - if ((flags & ~D3D12_TILE_MAPPING_FLAG_NO_HAZARD) || !dst_start || !src_start || !size || - !append_tile_regions(src_start, size, tile_grid(src), from) || - !append_tile_regions(dst_start, size, tile_grid(dst), to) || - !queue_.copy_tile_mappings(resource_id(dst), to, resource_id(src), from)) { - d3d12_trace::record(method, "refused"); - note_once("ID3D12CommandQueue::CopyTileMappings: invalid mapping or sparse residency unavailable"); - } else { - d3d12_trace::record(method, "ok"); - } - } - - HRESULT STDMETHODCALLTYPE Signal(ID3D12Fence* fence, UINT64 value) override { - constexpr auto method = "ID3D12CommandQueue::Signal"; - Fence* f = Fence::from(fence); - if (!f || f->context() != &context_ || f->attached_device() != attached_device()) - return d3d12_trace::result(method, E_INVALIDARG); - std::lock_guard lock(mutex_); - if (!f->claim(value, true)) return d3d12_trace::result(method, S_OK); - return d3d12_trace::result(method, queue_.signal(f->semaphore(), value, fence_pin(fence)) ? S_OK : E_FAIL); - } - - HRESULT STDMETHODCALLTYPE Wait(ID3D12Fence* fence, UINT64 value) override { - constexpr auto method = "ID3D12CommandQueue::Wait"; - Fence* f = Fence::from(fence); - if (!f || f->context() != &context_ || f->attached_device() != attached_device()) - return d3d12_trace::result(method, E_INVALIDARG); - std::lock_guard lock(mutex_); - queue_.wait(f->semaphore(), value, fence_pin(fence)); - return d3d12_trace::result(method, S_OK); - } - - // Ticks per second of the timestamps EndQuery writes: one tick is timestampPeriod nanoseconds. Every D3D12 - // queue of the device shares one VkQueue, so they share one frequency. E_FAIL when that queue has no - // timestamps (timestampValidBits 0), as D3D12 reports for a queue that does not support them. - HRESULT STDMETHODCALLTYPE GetTimestampFrequency(UINT64* frequency) override { - if (!frequency) return E_INVALIDARG; - const double period = context_.timestamp_period(); - if (!(period > 0)) return E_FAIL; - *frequency = static_cast(1e9 / period + 0.5); - return S_OK; - } - - // Queue labels, in order with the submissions around them. - void STDMETHODCALLTYPE SetMarker(UINT metadata, const void* data, UINT size) override { - d3d12_trace::record("ID3D12CommandQueue::SetMarker"); - marker(leonida::DebugMarker::Kind::set, metadata, data, size); - } - void STDMETHODCALLTYPE BeginEvent(UINT metadata, const void* data, UINT size) override { - d3d12_trace::record("ID3D12CommandQueue::BeginEvent"); - marker(leonida::DebugMarker::Kind::begin, metadata, data, size); - } - void STDMETHODCALLTYPE EndEvent() override { - d3d12_trace::record("ID3D12CommandQueue::EndEvent"); - marker(leonida::DebugMarker::Kind::end, 0, nullptr, 0); - } - - // The GPU timestamp is in device ticks (what GetTimestampFrequency counts: 1e9 / timestampPeriod per second) - // and the CPU one is QueryPerformanceCounter's, both read at about the same moment. - HRESULT STDMETHODCALLTYPE GetClockCalibration(UINT64* gpu, UINT64* cpu) override { - if (!gpu || !cpu) return E_INVALIDARG; - if (clock_.calibrated) { - VkCalibratedTimestampInfoKHR domains[2]{{VK_STRUCTURE_TYPE_CALIBRATED_TIMESTAMP_INFO_KHR}, - {VK_STRUCTURE_TYPE_CALIBRATED_TIMESTAMP_INFO_KHR}}; - domains[0].timeDomain = VK_TIME_DOMAIN_DEVICE_KHR; - domains[1].timeDomain = VK_TIME_DOMAIN_QUERY_PERFORMANCE_COUNTER_KHR; - std::uint64_t stamps[2]{}, deviation = 0; - LARGE_INTEGER before{}, after{}; - QueryPerformanceCounter(&before); - if (clock_.calibrated(context_.device(), 2, domains, stamps, &deviation) == VK_SUCCESS) { - QueryPerformanceCounter(&after); - // Wine can expose a host monotonic clock that differs from its Win32 QPC clock. - // Keep the GPU and CPU samples paired by taking a fresh GPU sample on fallback. - if (stamps[1] >= UINT64(before.QuadPart) && stamps[1] <= UINT64(after.QuadPart)) { - *gpu = stamps[0]; - *cpu = stamps[1]; - return S_OK; - } - } - } - return submitted_calibration(*gpu, *cpu); - } - - bool uses_calibrated_timestamps() const { return clock_.calibrated != nullptr; } - - static CommandQueue* from(IUnknown* object) { return Child::from(object); } - -private: - // The fallback without calibrated timestamps: wait for the queue to go idle, then submit a timestamp write and - // wait for it, with QueryPerformanceCounter read just before the submission and just after it completes. The - // GPU timestamp falls between the two; the midpoint is the answer, off by at most half the round trip (tens of - // microseconds). It stalls the queue, which is acceptable for a call profilers make once per capture. - HRESULT submitted_calibration(UINT64& gpu, UINT64& cpu) { - std::lock_guard lock(mutex_); - if (!clock_.timestamp_valid_bits || !clock_.get_device_proc || !create_stamp()) return E_FAIL; - auto& vk = context_.vk; - VkCommandBufferBeginInfo begin{VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO}; - begin.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT; - if (vk.vkBeginCommandBuffer(stamp_.commands, &begin) != VK_SUCCESS) return E_FAIL; - stamp_.reset_query_pool(stamp_.commands, stamp_.queries, 0, 1); - stamp_.write_timestamp(stamp_.commands, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, stamp_.queries, 0); - if (vk.vkEndCommandBuffer(stamp_.commands) != VK_SUCCESS) return E_FAIL; - VkSubmitInfo submit{VK_STRUCTURE_TYPE_SUBMIT_INFO}; - submit.commandBufferCount = 1; - submit.pCommandBuffers = &stamp_.commands; - LARGE_INTEGER before{}, after{}; - { - std::lock_guard submit_lock(context_.submit_mutex()); - if (vk.vkQueueWaitIdle(vk_queue_) != VK_SUCCESS) return E_FAIL; - QueryPerformanceCounter(&before); - if (vk.vkQueueSubmit(vk_queue_, 1, &submit, VK_NULL_HANDLE) != VK_SUCCESS || - vk.vkQueueWaitIdle(vk_queue_) != VK_SUCCESS) - return E_FAIL; - QueryPerformanceCounter(&after); - } - std::uint64_t stamp = 0; - if (stamp_.get_query_pool_results(context_.device(), stamp_.queries, 0, 1, sizeof(stamp), &stamp, - sizeof(stamp), VK_QUERY_RESULT_64_BIT) != VK_SUCCESS) - return E_FAIL; - if (clock_.timestamp_valid_bits < 64) stamp &= (std::uint64_t(1) << clock_.timestamp_valid_bits) - 1; - gpu = stamp; - cpu = UINT64(before.QuadPart) + UINT64(after.QuadPart - before.QuadPart) / 2; - return S_OK; - } - - // The fallback's command buffer and one-query timestamp pool, made on first use. Called with mutex_ held. - bool create_stamp() { - if (stamp_.pool) return true; - const VkDevice device = context_.device(); - const auto get = clock_.get_device_proc; - stamp_.create_query_pool = reinterpret_cast(get(device, "vkCreateQueryPool")); - stamp_.destroy_query_pool = reinterpret_cast(get(device, "vkDestroyQueryPool")); - stamp_.reset_query_pool = reinterpret_cast(get(device, "vkCmdResetQueryPool")); - stamp_.write_timestamp = reinterpret_cast(get(device, "vkCmdWriteTimestamp")); - stamp_.get_query_pool_results = - reinterpret_cast(get(device, "vkGetQueryPoolResults")); - if (!stamp_.create_query_pool || !stamp_.destroy_query_pool || !stamp_.reset_query_pool || - !stamp_.write_timestamp || !stamp_.get_query_pool_results) - return false; - auto& vk = context_.vk; - VkQueryPoolCreateInfo queries{VK_STRUCTURE_TYPE_QUERY_POOL_CREATE_INFO}; - queries.queryType = VK_QUERY_TYPE_TIMESTAMP; - queries.queryCount = 1; - if (stamp_.create_query_pool(device, &queries, nullptr, &stamp_.queries) != VK_SUCCESS) return false; - VkCommandPoolCreateInfo pool{VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO}; - pool.flags = VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT; - pool.queueFamilyIndex = family_; - VkCommandBufferAllocateInfo allocate{VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO}; - allocate.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY; - allocate.commandBufferCount = 1; - if (vk.vkCreateCommandPool(device, &pool, nullptr, &stamp_.pool) == VK_SUCCESS) { - allocate.commandPool = stamp_.pool; - if (vk.vkAllocateCommandBuffers(device, &allocate, &stamp_.commands) == VK_SUCCESS) return true; - vk.vkDestroyCommandPool(device, stamp_.pool, nullptr); - stamp_.pool = VK_NULL_HANDLE; - } - stamp_.destroy_query_pool(device, stamp_.queries, nullptr); - stamp_.queries = VK_NULL_HANDLE; - return false; - } - - void marker(leonida::DebugMarker::Kind kind, UINT metadata, const void* data, UINT size) { - const std::string label = event_label(metadata, data, size); - std::lock_guard lock(mutex_); - queue_.marker(kind, label.c_str()); - } - - bool update_tiles(ID3D12Resource* resource, UINT region_count, const D3D12_TILED_RESOURCE_COORDINATE* starts, - const D3D12_TILE_REGION_SIZE* sizes, ID3D12Heap* heap, UINT range_count, - const D3D12_TILE_RANGE_FLAGS* flags, const UINT* offsets, const UINT* counts, - D3D12_TILE_MAPPING_FLAGS mapping_flags) { - if (!region_count || !range_count || (!starts && region_count != 1) || - (mapping_flags & ~D3D12_TILE_MAPPING_FLAG_NO_HAZARD)) return false; - const auto grid = tile_grid(resource); - std::vector regions; - regions.reserve(region_count); - for (UINT i = 0; i < region_count; ++i) { - if (!append_tile_regions(starts ? starts + i : nullptr, sizes ? sizes + i : nullptr, grid, regions)) - return false; - } - std::uint64_t total = 0; - for (const auto& region : regions) { - if (region.count > UINT64_MAX - total) return false; - total += region.count; - } - - std::vector ranges; - ranges.reserve(range_count); - std::uint64_t remaining = total, heap_tiles_required = 0; - for (UINT i = 0; i < range_count; ++i) { - const auto count = counts ? counts[i] : (range_count == 1 ? total : 1); - if (!count) continue; - if (count > remaining) return false; - remaining -= count; - using leonida::TileRangeMode; - const auto flag = flags ? flags[i] : D3D12_TILE_RANGE_FLAG_NONE; - switch (flag) { - case D3D12_TILE_RANGE_FLAG_NONE: - case D3D12_TILE_RANGE_FLAG_REUSE_SINGLE_TILE: { - if (!offsets) return false; - const auto used = flag == D3D12_TILE_RANGE_FLAG_NONE ? count : 1; - if (used > UINT64_MAX - offsets[i]) return false; - heap_tiles_required = std::max(heap_tiles_required, offsets[i] + used); - ranges.push_back({flag == D3D12_TILE_RANGE_FLAG_NONE ? TileRangeMode::sequential : TileRangeMode::reuse, - offsets[i], count}); - break; - } - case D3D12_TILE_RANGE_FLAG_NULL: - ranges.push_back({TileRangeMode::unmap, 0, count}); - break; - case D3D12_TILE_RANGE_FLAG_SKIP: - ranges.push_back({TileRangeMode::skip, 0, count}); - break; - default: - return false; - } - } - if (remaining || (heap_tiles_required && - (!heap || heap_tiles_required > heap->GetDesc().SizeInBytes / leonida::tile_size_in_bytes))) return false; - std::lock_guard lock(mutex_); - return queue_.update_tiles(resource_id(resource), regions, ranges, - [&](bool image, std::uint32_t types) { - return heap_tiles_required ? tile_heap(heap, context_, image, types) : nullptr; - }); - } - - D3D12_COMMAND_QUEUE_DESC desc_; - leonida::VulkanContext& context_; - std::mutex mutex_; - // Destroyed after queue_ has waited idle, so the handle cannot be reused prematurely. - std::shared_ptr queue_lease_; - leonida::VulkanQueue queue_; - leonida::ReplayResult last_result_ = leonida::ReplayResult::success; - VkQueue vk_queue_; - std::uint32_t family_; - QueueClock clock_; - struct { - PFN_vkCreateQueryPool create_query_pool = nullptr; - PFN_vkDestroyQueryPool destroy_query_pool = nullptr; - PFN_vkCmdResetQueryPool reset_query_pool = nullptr; - PFN_vkCmdWriteTimestamp write_timestamp = nullptr; - PFN_vkGetQueryPoolResults get_query_pool_results = nullptr; - VkQueryPool queries = VK_NULL_HANDLE; - VkCommandPool pool = VK_NULL_HANDLE; - VkCommandBuffer commands = VK_NULL_HANDLE; - } stamp_; -}; - -} // namespace - -HRESULT create_command_queue(leonida::VulkanContext& context, VkQueue queue, std::uint32_t queue_family, - const D3D12_COMMAND_QUEUE_DESC& desc, REFIID riid, void** out, IUnknown* device, - const QueueClock& clock, std::shared_ptr queue_lease) { - if (!out) return E_POINTER; - *out = nullptr; - auto* object = new CommandQueue(context, queue, queue_family, desc, clock, std::move(queue_lease)); - if (!object->ok()) { - object->Release(); - return E_FAIL; - } - object->attach_device(device); - return hand_out(object, riid, out); -} - -HRESULT create_command_allocator(D3D12_COMMAND_LIST_TYPE type, REFIID riid, void** out, IUnknown* device) { - // The host runtime's order (d3d12_vulkan_device_test, compare_invalid_arguments "command allocator:"): a type - // past VIDEO_ENCODE is E_INVALIDARG, then a null output is E_UNEXPECTED. - if (out) *out = nullptr; - if (UINT(type) > UINT(D3D12_COMMAND_LIST_TYPE_VIDEO_ENCODE)) return E_INVALIDARG; - if (!out) return E_UNEXPECTED; - auto* object = new CommandAllocator(type); - object->attach_device(device); - return hand_out(object, riid, out); -} - -HRESULT create_command_list(D3D12_COMMAND_LIST_TYPE type, ID3D12CommandAllocator* allocator, REFIID riid, - void** out, IUnknown* device, ID3D12PipelineState* initial_state) { - if (out) *out = nullptr; - CommandAllocator* command_allocator = CommandAllocator::from(allocator); - if (!command_allocator || command_allocator->type() != type) return E_INVALIDARG; - // A list is created open, so the allocator must be free: E_INVALIDARG as on the PC runtime (D3D-51). - if (command_allocator->recording()) return E_INVALIDARG; - // A null output only after the arguments, as the host runtime answers ("command list:" cases). - if (!out) return E_UNEXPECTED; - if (type != D3D12_COMMAND_LIST_TYPE_DIRECT && type != D3D12_COMMAND_LIST_TYPE_BUNDLE && - type != D3D12_COMMAND_LIST_TYPE_COMPUTE && type != D3D12_COMMAND_LIST_TYPE_COPY) - stub("create_command_list(non-direct type)"); - auto* object = new GraphicsCommandList(type); // created open, as D3D12 does - object->record_into(command_allocator); - object->attach_device(device); - const HRESULT hr = hand_out(object, riid, out); // releases the creation reference, so a failure frees the list - // The initial pipeline state only once the list exists for the caller, as SetPipelineState on it would be. - if (SUCCEEDED(hr) && initial_state) - if (GraphicsCommandList* list = GraphicsCommandList::from(static_cast(*out))) - list->set_initial_pipeline(initial_state); - return hr; -} - -HRESULT create_fence(leonida::VulkanContext& context, UINT64 initial_value, D3D12_FENCE_FLAGS flags, REFIID riid, - void** out, IUnknown* device) { - if (!out) return E_POINTER; - *out = nullptr; - context.set_signal_event_fn([](void* h) { SetEvent(static_cast(h)); }); - auto* object = new Fence(context, initial_value, flags); - if (!object->ok()) { - object->Release(); - return E_FAIL; - } - object->attach_device(device); - return hand_out(object, riid, out); -} - -HRESULT set_event_on_multiple_fence_completion(leonida::VulkanContext& context, ID3D12Fence* const* fences, - const UINT64* values, UINT count, - D3D12_MULTIPLE_FENCE_WAIT_FLAGS flags, HANDLE event, - IUnknown* device) { - if (flags != D3D12_MULTIPLE_FENCE_WAIT_FLAG_ALL && flags != D3D12_MULTIPLE_FENCE_WAIT_FLAG_ANY) - return E_INVALIDARG; - if (!count || !fences || !values) return E_INVALIDARG; // no fences is refused, as on the host runtime - std::vector objects(count); - for (UINT i = 0; i < count; ++i) { - Fence* const f = Fence::from(fences[i]); - if (!f || f->context() != &context || (device && f->attached_device() != device)) - return E_INVALIDARG; - objects[i] = f; - } - const bool any = flags == D3D12_MULTIPLE_FENCE_WAIT_FLAG_ANY; - if (!event) { - if (context.is_device_lost()) return DXGI_ERROR_DEVICE_REMOVED; - // One vkWaitSemaphores call: VK_SEMAPHORE_WAIT_ANY_BIT is the ANY flag, no flag is ALL. - std::vector semaphores(count); - for (UINT i = 0; i < count; ++i) semaphores[i] = objects[i]->semaphore(); - VkSemaphoreWaitInfo wait{VK_STRUCTURE_TYPE_SEMAPHORE_WAIT_INFO}; - wait.flags = any ? VK_SEMAPHORE_WAIT_ANY_BIT : 0; - wait.semaphoreCount = count; - wait.pSemaphores = semaphores.data(); - wait.pValues = values; - const VkResult result = context.vk.vkWaitSemaphores(context.device(), &wait, UINT64_MAX); - // Unlike a single fence's blocking SetEventOnCompletion, this path invokes Vulkan directly. - // A lost device must wake its other registered fence waiters and reject later submissions. - if (result == VK_ERROR_DEVICE_LOST) { - context.mark_device_lost(); - return DXGI_ERROR_DEVICE_REMOVED; - } - return result == VK_SUCCESS ? S_OK : E_FAIL; - } - // Each fence's own waiter thread counts the shared waiter down; no thread of its own. - const auto waiter = std::make_shared(event, any ? 1u : count); - for (UINT i = 0; i < count && !waiter->done(); ++i) objects[i]->notify(values[i], waiter); - return S_OK; -} - -bool queue_uses_calibrated_timestamps(ID3D12CommandQueue* queue) { - if (ID3D12CommandQueue* real = d3d12_xs::queue_proxy_real_queue(queue)) queue = real; // the Xbox-ABI proxy - const CommandQueue* q = CommandQueue::from(queue); - return q && q->uses_calibrated_timestamps(); -} - -HRESULT create_command_signature(leonida::IndirectKind kind, UINT byte_stride, REFIID riid, void** out, - IUnknown* device) { - if (!out) return E_POINTER; - *out = nullptr; - auto* sig = new CommandSignature(kind, byte_stride); - sig->attach_device(device); - return hand_out(sig, riid, out); -} - -bool command_signature_info(ID3D12CommandSignature* signature, leonida::IndirectKind& kind, UINT& byte_stride) { - const CommandSignature* s = CommandSignature::from(signature); - if (!s) return false; - kind = s->kind(); - byte_stride = s->stride(); - return true; -} - -leonida::ReplayResult last_execute_result(ID3D12CommandQueue* queue) { - if (ID3D12CommandQueue* real = d3d12_xs::queue_proxy_real_queue(queue)) queue = real; // the Xbox-ABI proxy - CommandQueue* q = CommandQueue::from(queue); - return q ? q->last_result() : leonida::ReplayResult::unsupported; -} - -bool front_back_stencil_ref(ID3D12GraphicsCommandList8* list, UINT& front, UINT& back) { - const GraphicsCommandList* l = GraphicsCommandList::from(list); - if (!l) return false; - front = l->front_stencil_ref(); - back = l->back_stencil_ref(); - return true; -} - -bool recorded_commands(ID3D12GraphicsCommandList* list, std::vector& commands) { - const GraphicsCommandList* l = GraphicsCommandList::from(list); - if (!l) return false; - const auto recorded = l->commands().commands(); - commands.assign(recorded.begin(), recorded.end()); - return true; -} - -bool bound_descriptor_heap_bases(ID3D12GraphicsCommandList* list, D3D12_GPU_VIRTUAL_ADDRESS& cbv_srv_uav, - D3D12_GPU_VIRTUAL_ADDRESS& sampler) { - const GraphicsCommandList* l = GraphicsCommandList::from(list); - if (!l) return false; - cbv_srv_uav = l->cbv_srv_uav_base(); - sampler = l->sampler_base(); - return true; -} - -} // namespace rt::d3d12 diff --git a/runtime/shims/d3d12_com.h b/runtime/shims/d3d12_com.h deleted file mode 100644 index d0f3b528a..000000000 --- a/runtime/shims/d3d12_com.h +++ /dev/null @@ -1,447 +0,0 @@ -// D3D12 COM objects over the Vulkan backend (src/vulkan_backend.h): command allocator, graphics command list, -// command queue and fence. Their vtables are the Windows SDK's (ID3D12GraphicsCommandList8, ID3D12CommandQueue, -// ID3D12CommandAllocator, ID3D12Fence1); every method not implemented here is a generated stub that reports its -// name once (tools/gen_d3d12_stubs.py). The Xbox-specific slots measured for the device do not apply to these -// interfaces as far as is known; docs/d3d12_vulkan.md section 3.1 lists what is still unverified. -// -// Contracts with the rest of the layer (the device proxy that will hand these objects out): -// - an ID3D12Resource's leonida::ResourceId is its pointer value; the device registers it with the VulkanContext; -// - so is an ID3D12QueryHeap's leonida::QueryHeapId, registered with its VkQueryPool; -// - the CPU handle of an RTV or DSV points at a leonida::TargetView in the device's descriptor heap. -#pragma once - -#include -#include -#include -#include - -#include "../src/gfx10_descriptors.h" -#include "../src/vulkan_backend.h" - -#include -#include -#include -#include -#include -#include - -#include "../src/root_signature.h" -#include "../src/subgroup_size.h" - -namespace leonida { -class VulkanPresenter; -struct PresentPlanes; -} - -namespace rt::d3d12 { - -// How a queue answers GetClockCalibration. With `calibrated` (vkGetCalibratedTimestampsKHR or its EXT alias, on a -// device whose time domains include DEVICE and QUERY_PERFORMANCE_COUNTER) both clocks are read in one call. Without -// it, the queue writes a timestamp query and reads QueryPerformanceCounter around it; that needs `get_device_proc` -// and a queue family with timestamp_valid_bits > 0. With neither, GetClockCalibration fails. -struct QueueClock { - PFN_vkGetCalibratedTimestampsKHR calibrated = nullptr; - PFN_vkGetDeviceProcAddr get_device_proc = nullptr; - std::uint32_t timestamp_valid_bits = 0; -}; - -// `device` (optional) is what the object's GetDevice returns; the object holds a reference to it. -HRESULT create_command_queue(leonida::VulkanContext& context, VkQueue queue, std::uint32_t queue_family, - const D3D12_COMMAND_QUEUE_DESC& desc, REFIID riid, void** out, - IUnknown* device = nullptr, const QueueClock& clock = {}, - std::shared_ptr queue_lease = {}); -HRESULT create_command_allocator(D3D12_COMMAND_LIST_TYPE type, REFIID riid, void** out, IUnknown* device = nullptr); -HRESULT create_command_list(D3D12_COMMAND_LIST_TYPE type, ID3D12CommandAllocator* allocator, REFIID riid, - void** out, IUnknown* device = nullptr, ID3D12PipelineState* initial_state = nullptr); -HRESULT create_fence(leonida::VulkanContext& context, UINT64 initial_value, D3D12_FENCE_FLAGS flags, REFIID riid, - void** out, IUnknown* device = nullptr); -HRESULT create_command_signature(leonida::IndirectKind kind, UINT byte_stride, REFIID riid, void** out, - IUnknown* device = nullptr); -bool command_signature_info(ID3D12CommandSignature* signature, leonida::IndirectKind& kind, UINT& byte_stride); - -// ID3D12Device1::SetEventOnMultipleFenceCompletion on fences from create_fence: sets `event` once every fence -// (D3D12_MULTIPLE_FENCE_WAIT_FLAG_ALL) or any fence (_ANY) has reached its value; a null event blocks until then. -HRESULT set_event_on_multiple_fence_completion(leonida::VulkanContext& context, ID3D12Fence* const* fences, - const UINT64* values, UINT count, - D3D12_MULTIPLE_FENCE_WAIT_FLAGS flags, HANDLE event, - IUnknown* device = nullptr); - -std::shared_ptr tile_heap(ID3D12Heap* heap, const leonida::VulkanContext& context, - bool image, std::uint32_t memory_types); -bool is_sparse_image(ID3D12Resource* resource); - -// The Vulkan objects a D3D12 device runs on. Vulkan 1.3 with dynamicRendering, synchronization2, timelineSemaphore -// and (when separate_depth_stencil_layouts is set) separateDepthStencilLayouts enabled. -struct VulkanDeviceInfo { - PFN_vkGetInstanceProcAddr get_instance_proc = nullptr; - VkInstance instance = VK_NULL_HANDLE; - VkPhysicalDevice physical = VK_NULL_HANDLE; - VkDevice device = VK_NULL_HANDLE; - VkQueue queue = VK_NULL_HANDLE; // graphics queue used by staging and legacy single-queue callers - std::uint32_t queue_family = 0; - // Distinct handles from queue_family, when the creator requested more than one queue. - // Empty for caller-owned devices that only supplied queue above. - std::vector command_queues; - std::uint32_t compute_family = UINT32_MAX; - std::uint32_t copy_family = UINT32_MAX; - std::vector compute_queues; - std::vector copy_queues; - bool separate_depth_stencil_layouts = true; - std::uint32_t max_push_constants_size = 0; - bool push_constants_need_fallback = false; - // maxBufferSize and maxMemoryAllocationSize, which cap the GPU address arena (src/arena_size.h). 0: read from - // the physical device when the D3D12 device is created; a test sets smaller ones to simulate a device. - VkDeviceSize max_buffer_size = 0; - VkDeviceSize max_memory_allocation_size = 0; - // The subgroup sizes the device offers and whether subgroupSizeControl / computeFullSubgroups are enabled on it - // (src/subgroup_size.h). Default: nothing, so pipelines request no size. - leonida::SubgroupSizeCaps subgroup; - // Enabled: runtimeDescriptorArray, the dynamic indexing of sampled- and storage-image arrays, and update after - // bind for sampled images, storage images and storage buffers. The device then keeps the bindless set 0 of - // the translated shaders (docs section 3.4), and texture views and samplers are put in it as they are - // created. bindless_partially_bound: descriptorBindingPartiallyBound is enabled as well. - bool bindless = false; - bool bindless_partially_bound = false; - // samplerAnisotropy, samplerMirrorClampToEdge and samplerFilterMinmax enabled; without them such samplers are - // approximated. - bool sampler_anisotropy = false; - bool sampler_mirror_clamp_to_edge = false; - bool sampler_filter_minmax = false; - // VK_KHR_calibrated_timestamps or VK_EXT_calibrated_timestamps is enabled on `device` (QueueClock). - bool calibrated_timestamps = false; - // VK_EXT_conditional_rendering (with its conditionalRendering feature) is enabled: SetPredication works, and - // buffers are created with VK_BUFFER_USAGE_CONDITIONAL_RENDERING_BIT_EXT. Without it a predicated list is - // rejected at ExecuteCommandLists. - bool conditional_rendering = false; - bool storage_buffer_8bit = false; // storageBuffer8BitAccess enabled: byte-granular predicated buffer copies. - // VK_EXT_conservative_rasterization is enabled on the logical device. Tier 1/2 depend on the physical - // precision/overestimation properties; Tier 2 also requires post-snap degenerate triangles. - bool conservative_rasterization = false; - // Opt in only for shader libraries whose InnerCoverage input contract uses FullyCoveredEXT. The device - // still checks physical Tier 2 and fullyCoveredFragmentShaderInputVariable properties. The standalone - // device leaves this false until the Xbox PS input mapping is confirmed (synthetic GLSL is not that ABI). - bool inner_coverage_abi = false; - // VK_EXT_host_image_copy and its hostImageCopy feature are enabled on `device`: WriteToSubresource and - // ReadFromSubresource on textures in CPU-visible heaps copy on the CPU instead of through a staging submit. - bool host_image_copy = false; - // VK_KHR_shader_fma and its shaderFmaFloat32 feature are enabled on `device`: translated shaders built with - // `rdna2spirv.py --fma khr` (OpFmaKHR, capability FMAKHR in the index) can be created. Without it only the - // default `--fma glsl` shaders can. - bool shader_fma = false; - bool shader_subgroup_clock = false; - bool shader_device_clock = false; - // The caller enabled textureCompressionBC on this logical device. - bool texture_compression_bc = false; - // Optional device features the caller enabled. Without occlusionQueryPrecise, D3D12_QUERY_TYPE_OCCLUSION counts - // are only zero or non-zero; without pipelineStatisticsQuery, pipeline-statistics query heaps are refused. - bool occlusion_query_precise = false; - bool pipeline_statistics_query = false; - bool presentation = false; // VK_KHR_surface + VK_KHR_win32_surface on the instance, VK_KHR_swapchain on the device - // VK_KHR_swapchain_maintenance1 (or VK_EXT_swapchain_maintenance1) and its swapchainMaintenance1 feature are - // enabled on the device, with VK_KHR_get_surface_capabilities2 and the matching *_surface_maintenance1 on the - // instance (only meaningful with `presentation`): a vsync swapchain can switch to IMMEDIATE or FIFO_RELAXED per - // present, which PresentX's ImmediateThresholdPercent uses. - bool swapchain_maintenance1 = false; - // VK_EXT_swapchain_colorspace is enabled on the instance (with `presentation`): the surface can list its HDR10 - // (ST.2084) formats, which a PresentX plane in HDR10 uses. Without it HDR10 planes are tone mapped to SDR. - bool swapchain_colorspace = false; - // VK_EXT_image_view_min_lod and its minLod feature are enabled on the logical device. - bool image_view_min_lod = false; - // VK_KHR_vertex_attribute_divisor or VK_EXT_vertex_attribute_divisor with vertexAttributeInstanceRateDivisor. - bool vertex_attribute_divisor = false; - // Pixel-shader extensions translated shaders can declare, each enabled with its feature where the GPU has it: - // VK_KHR_fragment_shader_barycentric (BaryCoordKHR / PerVertexKHR reads), VK_EXT_fragment_shader_interlock - // (fragmentShaderPixelInterlock: POPS shaders run in PixelInterlockOrderedEXT) and VK_KHR_maintenance8 (texel - // offsets outside gathers: the index's needs_maintenance8). - bool fragment_shader_barycentric = false; - bool fragment_shader_interlock = false; - bool maintenance8 = false; - // The instance enabled VK_EXT_debug_utils: SetMarker/BeginEvent/EndEvent become debug labels. Otherwise they - // do nothing. - bool debug_utils = false; - // Vulkan 1.2 bufferDeviceAddress is enabled: buffers and shader-visible heaps then live in the GPU address - // arena and have console VAs (docs section 3.3), and GetGPUVirtualAddress returns those addresses; ray tracing - // needs it too. Without it, GetGPUVirtualAddress returns 0 and pipelines cannot be created. - bool buffer_device_address = false; - // Optional VK_KHR_acceleration_structure + VK_KHR_deferred_host_operations + VK_KHR_ray_query are enabled: - // GetRaytracingAccelerationStructurePrebuildInfo and BuildRaytracingAccelerationStructure (BLAS + TLAS) work. - bool ray_tracing = false; - // BuildRaytracingAccelerationStructure writes the console's XDXR BVH4 records into the destination buffer - // (src/xdxr_build.h), the layout the game's translated traversal shaders read, instead of building a - // VkAccelerationStructureKHR; needs buffer_device_address and the GPU address arena. The standalone device sets it - // unless LEONIDA_RT_AS=khr (docs/d3d12_vulkan.md 4.8); with it set, ray_tracing is not enabled. - bool xdxr_acceleration_structures = false; - // VK_EXT_mesh_shader with its meshShader feature is enabled on `device` (taskShader is not needed: the game's - // shaders have no amplification stage). Mesh-shader PSOs and DispatchMesh work, and CheckFeatureSupport reports - // D3D12_MESH_SHADER_TIER_1; without it mesh PSOs are refused and the tier is NOT_SUPPORTED. - bool mesh_shader = false; - // The core features enabled on `device`. Graphics PSOs that need independentBlend, fillModeNonSolid, - // depthBiasClamp or dualSrcBlend are refused unless it is set here. - VkPhysicalDeviceFeatures features{}; - // Vulkan 1.2 shaderOutputLayer / shaderOutputViewportIndex enabled on `device`: a translated vertex shader that - // writes the layer or viewport declares ShaderLayer / ShaderViewportIndex (the index's `features`). - bool shader_output_layer = false; - bool shader_output_viewport_index = false; - // The translator's output folder for pipeline creation. An empty value uses LEONIDA_SHADERS or the packaged path. - std::string shader_dir; - // VK_EXT_custom_border_color (with customBorderColors and customBorderColorWithoutFormat) is enabled on - // `device`: samplers with custom border colours pass them through to Vulkan. Without it, custom border - // colours fall back to transparent black. - bool custom_border_color = false; - bool custom_border_color_without_format = false; - // VK_EXT_external_memory_host is enabled on `device` when this is non-zero (its - // minImportedHostPointerAlignment): OpenExistingHeapFromAddress backs a heap with the caller's own committed - // memory. Zero: existing heaps stay unsupported. - VkDeviceSize host_pointer_alignment = 0; -}; - -// A Vulkan-backed ID3D12Device (PC ABI, up to ID3D12Device11) on caller-owned Vulkan objects, which must outlive -// the device and every object it created. Wrap it in rt::d3d12_xs::create_device_proxy for the Xbox ABI. -HRESULT create_vulkan_device(const VulkanDeviceInfo& info, REFIID riid, void** out); - -// The folder of translated shaders a device loads when VulkanDeviceInfo::shader_dir is empty: LEONIDA_SHADERS, else -// the path make_game recorded in shader_path.txt next to the executable (`config` names another file, for tests). -// Empty when neither names one, or when the path cannot be converted (a shader_path.txt that is not UTF-8); the reason -// is in `*error` then. Never throws. -std::filesystem::path configured_shader_directory(std::string* error, const std::filesystem::path& config = {}); - -// The same, on a Vulkan instance and device of its own (destroyed with the D3D12 device). Picks the first discrete -// GPU with the features above. LEONIDA_VK_VALIDATION=1 enables VK_LAYER_KHRONOS_validation. -// -// The queue test settings (LEONIDA_VK_MAX_QUEUES_PER_FAMILY, LEONIDA_VK_GRAPHICS_FAMILY_ONLY; docs/testing.md) give -// the device fewer Vulkan queues than the GPU has, so the tests run the path where D3D12 queues share one. Only the -// tests apply them: the game's device (d3d12_xs, LEONIDA_D3D12=vulkan) passes `ignore`, so a variable left set does -// not serialize the game's queues; it says once that it ignores them. -enum class QueueTestSettings { apply, ignore }; -HRESULT create_vulkan_device_standalone(REFIID riid, void** out, - QueueTestSettings queue_test_settings = QueueTestSettings::apply); - -// Tells a device from create_vulkan_device* that `outer` (the Xbox-ABI proxy that owns it) is what its children's -// GetDevice must return. No reference is taken: the outer object owns the device. `outer` may be the proxy's -// IDXGIDevice1 pointer (what create_device_proxy returns for that IID); the proxy itself becomes the outer. For a -// proxy it also makes the proxy's IDXGIDevice1::GetAdapter return this layer's adapter (d3d12_xs_device.h). -void set_device_outer(ID3D12Device* device, IUnknown* outer); - -// Console Xbox CreateDescriptorHeap takes a 16-byte PC D3D12_DESCRIPTOR_HEAP_DESC followed by address/size at -// +0x10/+0x18 (issue #313 comment 7107265058). This helper creates a heap with that console ABI contract on a -// device from create_vulkan_device*; it is intended for the Xbox device-proxy slot 14 path, not normal PC callers. -HRESULT create_console_descriptor_heap(ID3D12Device* device, const D3D12_DESCRIPTOR_HEAP_DESC* desc, - D3D12_GPU_VIRTUAL_ADDRESS console_address, std::uint64_t console_size, - REFIID riid, void** out); - -// The VkImage behind a texture created by such a device, or VK_NULL_HANDLE. For tests and the swapchain. -VkImage vulkan_image(ID3D12Resource* resource); -// The VkBuffer behind a buffer created by such a device, or VK_NULL_HANDLE. For tests. -VkBuffer vulkan_buffer(ID3D12Resource* resource); -// What a device from create_vulkan_device* was created with (enabled features included), or null. For tests. -const VulkanDeviceInfo* vulkan_device_info(ID3D12Device* device); -// True when `device` has VK_KHR_acceleration_structure + VK_KHR_ray_query enabled. -bool device_supports_ray_tracing(ID3D12Device* device); - -// Xbox device slot 133 (the console's CreatePlacedResourceX): a buffer on the caller's own pages at `address`, which -// becomes its console VA. The pages are imported with VK_EXT_external_memory_host, so what the CPU writes there is -// what the GPU reads. A buffer description only; E_NOTIMPL on a device that is not the Vulkan layer, without the -// extension, or for a texture. -HRESULT create_buffer_at_host_address(ID3D12Device* device, void* address, const D3D12_RESOURCE_DESC& desc, - std::uint32_t layout, REFIID riid, void** out); -// The VkAccelerationStructureKHR registered for `va` on `device`, or VK_NULL_HANDLE. For tests. -VkAccelerationStructureKHR vulkan_acceleration_structure(ID3D12Device* device, D3D12_GPU_VIRTUAL_ADDRESS va); - -// The property flags of the Vulkan memory type behind a resource created by such a device, or 0. For tests. -VkMemoryPropertyFlags vulkan_memory_flags(ID3D12Resource* resource); - -// Whether the requested colour format has an integer numeric class. -bool color_resolve_format_is_integer(DXGI_FORMAT format); - -// Whether both resources use the requested typed, non-integer colour format for a regional average resolve. -bool color_resolve_format_matches(DXGI_FORMAT format, ID3D12Resource* dst, ID3D12Resource* src); - -// Whether a resolve of one depth or stencil plane can be replayed: both resources are depth-stencil textures of -// `format` (a depth format, or a plane's shader-resource format such as R24_UNORM_X8_TYPELESS), the source -// multisampled and the destination not, the same plane on both sides, MIN or MAX (or AVERAGE of the depth plane by -// its own format), the destination offset the source rectangle's corner (or 0, 0 without one), and the Vulkan device -// has the mode. -bool depth_stencil_resolve_supported(DXGI_FORMAT format, ID3D12Resource* dst, UINT dst_subresource, UINT x, UINT y, - ID3D12Resource* src, UINT src_subresource, const D3D12_RECT* rect, - D3D12_RESOLVE_MODE mode); - -// The maxPushConstantsSize in bytes of the Vulkan physical device behind `device`, or 0 if not a Vulkan device. -std::uint32_t device_max_push_constants_size(ID3D12Device* device); - -// True when `device`'s Vulkan physical device has maxPushConstantsSize < 144 bytes, requiring -// the uniform-buffer fallback for the 16-byte tail (heap/code base). -bool device_push_constants_need_fallback(ID3D12Device* device); - -// True when `device` puts upload-heap buffers in DEVICE_LOCAL | HOST_VISIBLE memory: its GPU has Resizable BAR and -// LEONIDA_UPLOAD_SYSMEM is not set (D3D-96). -bool device_upload_in_vram(ID3D12Device* device); - -// True when the device can map reserved buffers onto its D3D12 heaps. -bool device_sparse_buffer_tiles(ID3D12Device* device); - -// The size in bytes of the device's GPU address arena, or 0 without one. For tests. -std::uint64_t device_arena_size(ID3D12Device* device); - -// The bindless set 0 a device with VulkanDeviceInfo::bindless keeps (vulkan_bindless.h), and its layout: what a -// pipeline whose shader declares set-0 bindings is created with and binds. Null without such a set. The set is -// brought up to date at every ExecuteCommandLists. -VkDescriptorSet bindless_set(ID3D12Device* device); -// What the bindless set did without waiting (D3D-314): table generations made because a flush grew the table or -// changed live entries, the retired ones not freed yet, and vkDeviceWaitIdle calls made for it (always 0 unless -// LEONIDA_BINDLESS_IDLE_WAIT=1 restores the old wait, to compare frame times). All 0 without a bindless set. -struct BindlessStats { - std::uint64_t generations_made = 0; - std::uint64_t retired_pending = 0; - std::uint64_t device_idle_waits = 0; -}; -BindlessStats bindless_stats(ID3D12Device* device); -VkDescriptorSetLayout bindless_set_layout(ID3D12Device* device); -// The bindless index the descriptor hash table holds for the 8 key dwords of a T# (or the 4 of an S# followed by -// 0xFFFFFFFF x4), 0 (the fallback) when it has none or `device` has no such set. For tests. -std::uint32_t bindless_hash_lookup(ID3D12Device* device, const std::uint32_t (&key)[8]); -// The free indices of that set's 2D image and sampler arrays: how many more distinct 2D T#s and S#s -// CreateShaderResourceView and CreateSampler can register before they log that the array is full. Zeros when -// `device` has no such set. For tests. -struct BindlessRoom { - std::uint32_t images_2d = 0; - std::uint32_t samplers = 0; -}; -BindlessRoom bindless_room(ID3D12Device* device); -// Gives each S# a sampler in that set and a key in its hash table, as CreateSampler does, without a heap slot: for -// the literal S#s a shader builds from immediates (`literal_samplers` in the shader index). An S# that has them -// already is left as it is. E_INVALIDARG when `device` is not such a device; E_FAIL when one of them could not be -// registered (no bindless set, or its sampler array is full), the others are registered all the same. -HRESULT register_samplers(ID3D12Device* device, std::span samplers); -// True when GetClockCalibration on `queue` reads calibrated timestamps, false when it submits a timestamp query -// (or `queue` is not one of this module's queues). For tests. -bool queue_uses_calibrated_timestamps(ID3D12CommandQueue* queue); - -// Creates a Vulkan-backed IDXGIFactory4 bound to `device`'s VulkanContext, instance, physical device, and queue. -// Its CreateSwapChainForHwnd registers swapchain backbuffers directly with the device's VulkanContext. -HRESULT create_dxgi_factory(ID3D12Device* device, REFIID riid, void** out); - -// SDRWhiteLevel of DISPLAYCONFIG_SDR_WHITE_LEVEL (1000 = 80 nits) to nits. -float sdr_white_nits_from_level(unsigned long level); - -// Puts back buffers of a device from create_vulkan_device* into a window (leonida::VulkanPresenter), for the -// presentation front end the game uses (DXGI or PresentX, still open). Holds a reference to the device. -class WindowPresenter { -public: - WindowPresenter(IUnknown* device, std::unique_ptr presenter); - ~WindowPresenter(); - WindowPresenter(const WindowPresenter&) = delete; - WindowPresenter& operator=(const WindowPresenter&) = delete; - - // `back_buffer` is a colour texture in D3D12's PRESENT state. sync_interval 0 presents without vsync. - // S_OK also covers a skipped present while the window is minimised. - // `src_rect` (when not null) limits the blit to that part of the texture, which is stretched to the window. - // `tear` (with sync_interval > 0): present in the tearing mode when the swapchain has one (tear_supported()), so a - // frame that missed its vblank is shown at once; last_present_tore() tells whether that happened. - HRESULT present(ID3D12Resource* back_buffer, UINT sync_interval, const D3D12_RECT* src_rect = nullptr, - bool tear = false); - // A black frame, nothing read (PresentX with no planes). - HRESULT present_blank(UINT sync_interval); - // One or two planes composed (VulkanPresenter::present_planes); `planes` names the textures by ResourceId, so the - // caller fills it with resource_id(). DXGI_ERROR_UNSUPPORTED for a source the compose pass cannot read. - HRESULT present_planes(const leonida::PresentPlanes& planes, UINT sync_interval, bool tear = false); - // The swapchain holds HDR10 (ST.2084) values; and a test hook (VulkanPresenter::force_hdr_encoding). - bool hdr_active() const; - void force_hdr_encoding(bool on); - std::uint64_t composed_presents() const; // presents that went through the compose pass - // Nits of SDR white the user set in Windows for the output the window is on (DISPLAYCONFIG_SDR_WHITE_LEVEL), or 0 when - // it cannot be read (no window, no display config, not Windows). Only meaningful while hdr_active(). - float display_sdr_white_nits() const; - void set_window(HWND window) { window_ = window; } - bool tear_supported() const; - bool last_present_tore() const; - std::uint64_t tear_presents() const; - // Screenshot support for tests: every presented frame is also copied to host memory (call before presenting). - bool enable_capture(); - // See VulkanPresenter::set_abort: polled while a present waits for a swapchain image. - void set_abort(std::function abort); - // See VulkanPresenter::read_back: false after a present skipped while the window is minimised, too. - bool read_back(std::vector& pixels, VkExtent2D* extent, VkFormat* format); - VkExtent2D extent() const; - std::uint64_t presented() const; - -private: - IUnknown* device_; - HWND window_ = nullptr; - std::unique_ptr presenter_; -}; - -// Whether `device` (from create_vulkan_device*) was created with VK_EXT_swapchain_colorspace on its instance. -bool device_has_swapchain_colorspace(ID3D12Device* device); - -// Null when `device` is not a Vulkan device created with presentation, or the window cannot be presented to. -std::unique_ptr create_window_presenter(ID3D12Device* device, HWND window); - -// Where each root parameter's arguments go in the 32 user-data dwords the translated shaders read (docs section -// 3.5). Built when a Vulkan device creates the root signature. A signature can be bound at either bind point, so it -// carries both layouts: -// - graphics: rt::rootsig::pack() (from s0, two dwords per table; D3D-448 keeps it until per-stage user-data windows -// exist, because a mesh shader (s16) and a pixel shader (s8) share one push-constant block); -// - compute: rt::rootsig::pack_stage(Stage::Compute), the measured console layout (from s4, one dword per table). -// A layout that refuses the signature is marked unusable; binding the signature there invalidates the list. -struct RootArgumentLayout { - struct Parameter { - rt::rootsig::ParamType type; - std::uint32_t user_offset; // graphics: first dword; unused for a parameter with no dwords - std::uint32_t constant_count; // constants only - std::uint32_t compute_offset = rt::rootsig::kNoSgpr; // compute: first user SGPR - }; - std::vector parameters; - std::uint32_t flags = 0; // D3D12_ROOT_SIGNATURE_FLAGS from the serialized blob - bool graphics_ok = true; - bool compute_ok = true; -}; - -// For the command list: the argument layout of a root signature from a Vulkan device, and the id it records for a -// compute pipeline state (0: not a compute PSO of a Vulkan device). -const RootArgumentLayout* root_signature_layout(ID3D12RootSignature* signature); -std::uintptr_t compute_pipeline_id(ID3D12PipelineState* pipeline); -std::uintptr_t graphics_pipeline_id(ID3D12PipelineState* pipeline); -// What each stage of a Vulkan device's PSO asked for (src/subgroup_size.h), in creation order; null for another PSO. -const std::vector* pipeline_subgroup_requests(ID3D12PipelineState* pipeline); - -// Unwraps an Xbox-ABI heap proxy if needed and inspects one of this module's descriptor heaps; returns its owning -// device identity pointer, or nullptr when `heap` is null or belongs to another implementation. -IUnknown* descriptor_heap_info(ID3D12DescriptorHeap* heap, D3D12_DESCRIPTOR_HEAP_DESC& desc, - D3D12_GPU_VIRTUAL_ADDRESS& gpu_base); - -// Reads the shader-visible descriptor heap GPU base addresses currently bound on `list` (0 when unbound). -// Returns false when `list` is not one of this module's command lists. -bool bound_descriptor_heap_bases(ID3D12GraphicsCommandList* list, D3D12_GPU_VIRTUAL_ADDRESS& cbv_srv_uav, - D3D12_GPU_VIRTUAL_ADDRESS& sampler); - -// The size of every descriptor slot (GetDescriptorHandleIncrementSize), for handle ranges. -inline constexpr UINT descriptor_size = 32; - -// ExecuteCommandLists returns void; this is what the last call on the queue did. -leonida::ReplayResult last_execute_result(ID3D12CommandQueue* queue); - -// True when the current thread or process token has SeIncreaseBasePriorityPrivilege enabled (or the test override -// forces it), which D3D12 requires for D3D12_COMMAND_QUEUE_PRIORITY_GLOBAL_REALTIME. -bool has_global_realtime_privilege(); -// Test override for has_global_realtime_privilege(): -1 queries the token (default), 0 forces denied, 1 forces granted. -void set_global_realtime_privilege_override_for_test(int state); - -// The front/back stencil references last recorded by ID3D12GraphicsCommandList8::OMSetFrontAndBackStencilRef on -// `list`. The values are kept for the future pipeline path, which is what would apply them. False when `list` is -// not one of this module's command lists. -bool front_back_stencil_ref(ID3D12GraphicsCommandList8* list, UINT& front, UINT& back); - -// A copy of the commands `list` has recorded so far, for tests of what a bundle puts into its parent. False when -// `list` is not one of this module's command lists. -bool recorded_commands(ID3D12GraphicsCommandList* list, std::vector& commands); - -inline leonida::ResourceId resource_id(const ID3D12Resource* resource) { - return reinterpret_cast(resource); -} - -// A query heap's ID in the command-list IR and the VulkanContext: its pointer value, as for resources. -inline leonida::QueryHeapId query_heap_id(const ID3D12QueryHeap* heap) { - return reinterpret_cast(heap); -} - -} // namespace rt::d3d12 diff --git a/runtime/shims/d3d12_com_object.h b/runtime/shims/d3d12_com_object.h deleted file mode 100644 index f16cb9a04..000000000 --- a/runtime/shims/d3d12_com_object.h +++ /dev/null @@ -1,202 +0,0 @@ -// Shared IUnknown/ID3D12Object/ID3D12DeviceChild implementation for the Vulkan-backed D3D12 COM objects -// (d3d12_com.cpp, d3d12_vulkan_device.cpp). Private to the runtime; include after the generated d3d12_stubs.h. -#pragma once - -#include -#include - -#include -#include -#include -#include -#include -#include -#include -#include - -#include "../core/log.h" - -namespace rt::d3d12 { - -void stub(const char* method); - -// IUnknown and ID3D12Object for one implementation class. QueryInterface answers the listed public interfaces -// and the class's private Derived::kTag (which returns the implementation itself); anything else is logged with -// its IID and refused, as docs/d3d12_vulkan.md section 3.1 asks. -template -class Object : public Stubs { -public: - ULONG STDMETHODCALLTYPE AddRef() override { return ++refs_; } - ULONG STDMETHODCALLTYPE Release() override { - const ULONG left = --refs_; - if (!left) delete static_cast(this); - return left; - } - - HRESULT STDMETHODCALLTYPE QueryInterface(REFIID riid, void** out) override { - if (!out) return E_POINTER; - *out = nullptr; - if (riid == Derived::kTag) { - *out = static_cast(this); - } else if (riid == __uuidof(IUnknown) || ((riid == __uuidof(Interfaces)) || ...)) { - *out = static_cast(this); // one inheritance chain: every interface shares this pointer - } else { - RT_LOG_WARN("d3d12: QueryInterface: unknown IID {%08lx-%04x-%04x-%02x%02x-%02x%02x%02x%02x%02x%02x}\n", - static_cast(riid.Data1), riid.Data2, riid.Data3, riid.Data4[0], riid.Data4[1], - riid.Data4[2], riid.Data4[3], riid.Data4[4], riid.Data4[5], riid.Data4[6], riid.Data4[7]); - return E_NOINTERFACE; - } - AddRef(); - return S_OK; - } - - // Private data (ID3D12Object): bytes, or with SetPrivateDataInterface an interface the object holds a reference - // to until the entry is replaced, removed or the object dies. GetPrivateData hands such an interface back with a - // reference added, as D3D12 does. The answers are the host runtime's (d3d12_private_data_test, RTX 3060 / - // 610.88, on the device and four child objects): a buffer too small for the entry gets DXGI_ERROR_MORE_DATA and - // the size it needs; SetPrivateData with null data removes the entry whatever the size, S_OK when there was one - // and S_FALSE when there wasn't; zero bytes with data keep an empty entry; SetPrivateDataInterface with null - // keeps a pointer-sized entry that reads back as null. - HRESULT STDMETHODCALLTYPE GetPrivateData(REFGUID guid, UINT* size, void* data) override { - if (!size) return E_INVALIDARG; - std::lock_guard lock(data_mutex_); - for (const auto& entry : data_) { - if (entry.key != guid) continue; - const UINT bytes = entry.is_interface ? UINT(sizeof(IUnknown*)) : UINT(entry.bytes.size()); - if (data && *size < bytes) { - *size = bytes; // the size to retry with - return DXGI_ERROR_MORE_DATA; - } - if (data) { - if (entry.is_interface) { - if (entry.object) entry.object->AddRef(); - std::memcpy(data, &entry.object, sizeof(IUnknown*)); - } else if (bytes) { - std::memcpy(data, entry.bytes.data(), bytes); - } - } - *size = bytes; - return S_OK; - } - *size = 0; - return DXGI_ERROR_NOT_FOUND; - } - - HRESULT STDMETHODCALLTYPE SetPrivateData(REFGUID guid, UINT size, const void* data) override { - if (!data) return remove(guid) ? S_OK : S_FALSE; - PrivateData entry{guid, {}, nullptr, false}; - const auto* bytes = static_cast(data); - entry.bytes.assign(bytes, bytes + size); - store(std::move(entry)); - return S_OK; - } - - HRESULT STDMETHODCALLTYPE SetPrivateDataInterface(REFGUID guid, const IUnknown* object) override { - IUnknown* held = const_cast(object); - if (held) held->AddRef(); - store(PrivateData{guid, {}, held, true}); - return S_OK; - } - - // SetName is SetPrivateData with WKPDID_D3DDebugObjectNameW and the name with its terminator, as D3D12 documents - // and the host runtime does: GetPrivateData reads it back (an empty name is a 2-byte entry), and the narrow - // WKPDID_D3DDebugObjectName is not touched. A null name, which the host runtime faults on, changes nothing. - HRESULT STDMETHODCALLTYPE SetName(LPCWSTR name) override { - if (!name) return E_INVALIDARG; - return SetPrivateData(kDebugObjectNameW, UINT((std::wcslen(name) + 1) * sizeof(wchar_t)), name); - } - - // WKPDID_D3DDebugObjectNameW (d3dcommon.h), spelled out so nothing needs dxguid.lib. - static constexpr GUID kDebugObjectNameW{0x4cca5fd8, 0x921f, 0x42c8, - {0x85, 0x66, 0x70, 0xca, 0xf2, 0xa9, 0xb7, 0x41}}; - - // The implementation behind a public interface pointer, or null when it is not a T. No reference is added. - template - static T* from(IUnknown* object) { - if (!object) return nullptr; - void* implementation = nullptr; - if (FAILED(object->QueryInterface(T::kTag, &implementation))) return nullptr; - static_cast(implementation)->Release(); // the caller holds its own reference - return static_cast(implementation); - } - -protected: - virtual ~Object() { - for (auto& entry : data_) - if (entry.object) entry.object->Release(); - } - -private: - struct PrivateData { - GUID key; - std::vector bytes; - IUnknown* object; // SetPrivateDataInterface: one reference held (null for a null interface) - bool is_interface; // set by SetPrivateDataInterface, even with null: reads back as a pointer - }; - - // Takes the entry for `key` out; true when there was one. The interface it held is released after the lock is - // dropped, since its Release may run arbitrary code. - bool remove(REFGUID key) { return replace(key, nullptr); } - void store(PrivateData entry) { - const GUID key = entry.key; - replace(key, &entry); - } - bool replace(REFGUID key, PrivateData* entry) { - IUnknown* released = nullptr; - bool found = false; - { - std::lock_guard lock(data_mutex_); - for (auto it = data_.begin(); it != data_.end(); ++it) { - if (it->key != key) continue; - released = it->object; - data_.erase(it); - found = true; - break; - } - if (entry) data_.push_back(std::move(*entry)); - } - if (released) released->Release(); - return found; - } - - std::atomic refs_{1}; - std::mutex data_mutex_; - std::vector data_; -}; - -// An ID3D12DeviceChild: holds a reference to its device, as D3D12 children do, and GetDevice returns it. When the -// device sits behind the Xbox-ABI proxy, the reference is to the proxy, so the game never sees the inner device. -template -class Child : public Object { -public: - void attach_device(IUnknown* device) { - if (device) device->AddRef(); - if (device_) device_->Release(); - device_ = device; - } - - IUnknown* attached_device() const { return device_; } - - HRESULT STDMETHODCALLTYPE GetDevice(REFIID riid, void** out) override { - if (!out) return E_POINTER; - *out = nullptr; - return device_ ? device_->QueryInterface(riid, out) : E_NOINTERFACE; - } - -protected: - ~Child() override { - if (device_) device_->Release(); - } - -private: - IUnknown* device_ = nullptr; -}; - -template -HRESULT hand_out(T* object, REFIID riid, void** out) { - const HRESULT hr = object->QueryInterface(riid, out); - object->Release(); - return hr; -} - -} // namespace rt::d3d12 diff --git a/runtime/shims/d3d12_feature_compat.h b/runtime/shims/d3d12_feature_compat.h deleted file mode 100644 index efba257a7..000000000 --- a/runtime/shims/d3d12_feature_compat.h +++ /dev/null @@ -1,83 +0,0 @@ -#pragma once - -#include - -#include - -// D3D12 values newer than some Windows SDK 10.0.26100 releases. The README asks for "Windows SDK 10.0.26100 or newer", -// but the SDK's d3d12.h moved within 10.0.26100 (D3D12_SDK_VERSION 612 in 10.0.26100.6584, 616 later), so anything the -// runtime uses from a newer header is declared here with its ABI value and payload, and checked against the header -// where the header has it. That keeps the runtime and its tests building on every 10.0.26100 SDK. -namespace rt::d3d12::compat { - -// Feature values introduced after Windows SDK 10.0.26100.0. -inline constexpr D3D12_FEATURE kFeatureApplicationSpecificDriverState = static_cast(56); -inline constexpr D3D12_FEATURE kFeatureBytecodeBypassHashSupported = static_cast(57); - -struct FeatureSupportFlag { - BOOL Supported; -}; - -static_assert(sizeof(FeatureSupportFlag) == sizeof(BOOL)); - -// D3D12_FEATURE_D3D12_OPTIONS20 and D3D12_FEATURE_PREDICATION: D3D12_SDK_VERSION 611 (DirectX-Headers v1.611.0); not -// in 610. PREDICATION's payload is one BOOL, FeatureSupportFlag above. -inline constexpr D3D12_FEATURE kFeatureOptions20 = static_cast(49); -inline constexpr D3D12_FEATURE kFeaturePredication = static_cast(50); -inline constexpr UINT kRecreateAtTierNotSupported = 0; // D3D12_RECREATE_AT_TIER_NOT_SUPPORTED - -struct FeatureDataOptions20 { - BOOL ComputeOnlyWriteWatchSupported; - UINT RecreateAtTier; // D3D12_RECREATE_AT_TIER -}; - -static_assert(sizeof(FeatureDataOptions20) == 8); - -#if defined(D3D12_SDK_VERSION) && D3D12_SDK_VERSION >= 611 -static_assert(kFeatureOptions20 == D3D12_FEATURE_D3D12_OPTIONS20); -static_assert(kFeaturePredication == D3D12_FEATURE_PREDICATION); -static_assert(kRecreateAtTierNotSupported == UINT(D3D12_RECREATE_AT_TIER_NOT_SUPPORTED)); -static_assert(sizeof(FeatureDataOptions20) == sizeof(D3D12_FEATURE_DATA_D3D12_OPTIONS20)); -static_assert(sizeof(D3D12_RECREATE_AT_TIER) == sizeof(UINT)); -static_assert(offsetof(FeatureDataOptions20, RecreateAtTier) == - offsetof(D3D12_FEATURE_DATA_D3D12_OPTIONS20, RecreateAtTier)); -static_assert(sizeof(FeatureSupportFlag) == sizeof(D3D12_FEATURE_DATA_PREDICATION)); -#endif - -// D3D12_FEATURE_D3D12_OPTIONS21 (work graphs and the ExecuteIndirect tier): D3D12_SDK_VERSION 613 (DirectX-Headers -// v1.613.0); not in 611. The enums are UINT-sized in d3d12.h, as here. -inline constexpr D3D12_FEATURE kFeatureOptions21 = static_cast(53); -inline constexpr UINT kWorkGraphsTierNotSupported = 0; // D3D12_WORK_GRAPHS_TIER_NOT_SUPPORTED -inline constexpr UINT kExecuteIndirectTier1_0 = 10; // D3D12_EXECUTE_INDIRECT_TIER_1_0 - -struct FeatureDataOptions21 { - UINT WorkGraphsTier; // D3D12_WORK_GRAPHS_TIER - UINT ExecuteIndirectTier; // D3D12_EXECUTE_INDIRECT_TIER - BOOL SampleCmpGradientAndBiasSupported; - BOOL ExtendedCommandInfoSupported; -}; - -static_assert(sizeof(FeatureDataOptions21) == 16); - -// D3D12_INDIRECT_ARGUMENT_TYPE_INCREMENTING_CONSTANT (ExecuteIndirect tier 1.1): the value after DISPATCH_MESH, from -// the same header version as OPTIONS21. -inline constexpr D3D12_INDIRECT_ARGUMENT_TYPE kIndirectArgumentIncrementingConstant = - static_cast(D3D12_INDIRECT_ARGUMENT_TYPE_DISPATCH_MESH + 1); - -#if defined(D3D12_SDK_VERSION) && D3D12_SDK_VERSION >= 613 -// A header that declares these must agree with the values above. -static_assert(kFeatureOptions21 == D3D12_FEATURE_D3D12_OPTIONS21); -static_assert(kWorkGraphsTierNotSupported == UINT(D3D12_WORK_GRAPHS_TIER_NOT_SUPPORTED)); -static_assert(kExecuteIndirectTier1_0 == UINT(D3D12_EXECUTE_INDIRECT_TIER_1_0)); -static_assert(kIndirectArgumentIncrementingConstant == D3D12_INDIRECT_ARGUMENT_TYPE_INCREMENTING_CONSTANT); -static_assert(sizeof(FeatureDataOptions21) == sizeof(D3D12_FEATURE_DATA_D3D12_OPTIONS21)); -static_assert(sizeof(D3D12_WORK_GRAPHS_TIER) == sizeof(UINT) && sizeof(D3D12_EXECUTE_INDIRECT_TIER) == sizeof(UINT)); -static_assert(offsetof(FeatureDataOptions21, ExecuteIndirectTier) == - offsetof(D3D12_FEATURE_DATA_D3D12_OPTIONS21, ExecuteIndirectTier)); -static_assert(offsetof(FeatureDataOptions21, SampleCmpGradientAndBiasSupported) == - offsetof(D3D12_FEATURE_DATA_D3D12_OPTIONS21, SampleCmpGradientAndBiasSupported)); -static_assert(offsetof(FeatureDataOptions21, ExtendedCommandInfoSupported) == - offsetof(D3D12_FEATURE_DATA_D3D12_OPTIONS21, ExtendedCommandInfoSupported)); -#endif - -} // namespace rt::d3d12::compat diff --git a/runtime/shims/d3d12_fence_waiter.h b/runtime/shims/d3d12_fence_waiter.h deleted file mode 100644 index 154bc2988..000000000 --- a/runtime/shims/d3d12_fence_waiter.h +++ /dev/null @@ -1,28 +0,0 @@ -// The event behind SetEventOnCompletion and SetEventOnMultipleFenceCompletion (d3d12_com.cpp), on its own so a test -// can check the countdown without a GPU (test/d3d12_fence_waiter_test.cpp). -#pragma once - -#include - -#include - -namespace rt::d3d12 { - -// An event waiting for `remaining` fence values: 1 for SetEventOnCompletion and for the ANY flag of -// SetEventOnMultipleFenceCompletion, the fence count for ALL. The count is the API's UINT, kept unsigned so every -// count the caller can pass is waited for. Each fence that reaches its value counts down once; the hit that takes it -// from 1 to 0 sets the event, and later hits (ANY) leave it at 0 instead of wrapping. -struct FenceWaiter { - FenceWaiter(HANDLE e, UINT n) : event(e), remaining(n) {} - void hit() { - UINT left = remaining.load(); - while (left && !remaining.compare_exchange_weak(left, left - 1)) { - } - if (left == 1) SetEvent(event); - } - bool done() const { return remaining.load() == 0; } - HANDLE event; - std::atomic remaining; -}; - -} // namespace rt::d3d12 diff --git a/runtime/shims/d3d12_trace.h b/runtime/shims/d3d12_trace.h deleted file mode 100644 index 82432eb18..000000000 --- a/runtime/shims/d3d12_trace.h +++ /dev/null @@ -1,36 +0,0 @@ -#pragma once - -#include - -#include -#include -#include - -namespace rt::d3d12_trace { - -inline std::atomic tracing{false}; - -inline void set_enabled(bool enable) noexcept { - tracing.store(enable, std::memory_order_relaxed); -} - -inline bool enabled() noexcept { - return tracing.load(std::memory_order_relaxed); -} - -// Callers supply fixed method names and outcomes only. Keep one ordered record per call across threads. -inline void record(const char* method, const char* outcome = "called") noexcept { - if (!enabled()) return; - static std::mutex mutex; - static unsigned long long sequence = 0; - const std::lock_guard lock(mutex); - std::fprintf(stderr, "[d3d12-trace] #%llu %s %s\n", ++sequence, method, outcome); - std::fflush(stderr); -} - -inline HRESULT result(const char* method, HRESULT code) noexcept { - record(method, code == E_NOTIMPL ? "unsupported" : FAILED(code) ? "failed" : "ok"); - return code; -} - -} // namespace rt::d3d12_trace diff --git a/runtime/shims/d3d12_vulkan_device.cpp b/runtime/shims/d3d12_vulkan_device.cpp deleted file mode 100644 index 008be5023..000000000 --- a/runtime/shims/d3d12_vulkan_device.cpp +++ /dev/null @@ -1,10066 +0,0 @@ -// A Vulkan-backed ID3D12Device (PC ABI) for the Xbox-ABI device proxy (d3d12_xs_device.cpp) to forward to. -// Implemented: queues, allocators, command lists, fences, descriptor heaps, render-target and depth-stencil views, -// committed buffers and textures (1D, 1D arrays, 2D, multisampled 2D, 3D) and their 1/2/3 variants, allocation -// info, CPU texture copies (WriteToSubresource/ReadFromSubresource), query heaps, a few feature queries. Everything else is a -// generated stub that reports itself once. See docs/d3d12_vulkan.md section 4.1/4.2 for what each answer means and -// what is still open. -#ifndef VK_USE_PLATFORM_WIN32_KHR -#define VK_USE_PLATFORM_WIN32_KHR -#endif -#include "d3d12_com.h" -#include "d3d12_feature_compat.h" - -#include "d3d12_stubs.h" // generated -#include "d3d12_com_object.h" -#include "d3d12_trace.h" -#include "d3d12_xs_device.h" -#include "dxgi_com.h" -#include "../core/config.h" -#include "../core/log.h" -#include "../src/arena_size.h" -#include "../src/gfx10_descriptors.h" -#include "../src/depth24_fragment.h" -#include "../src/uav_clear.h" -#include "../src/vulkan_bindless.h" -#include "../src/vulkan_memory.h" -#include "../src/vulkan_mesh_limits.h" -#include "../src/resource_tiling.h" -#include "../src/cached_pso.h" -#include "../src/conservative_raster.h" -#include "../src/resource_detile.h" -#include "../src/shader_library.h" -#include "../src/spirv_f16_halves.h" -#include "../src/spirv_stores.h" -#include "../src/vulkan_present.h" -#include "../src/vulkan_device_filter.h" -#include "../src/vulkan13_features.h" - -#include -#ifdef _MSC_VER -#pragma comment(lib, "advapi32.lib") -#endif - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace rt::d3d12 { -namespace { - -// Every descriptor slot is this many bytes; an RTV or DSV slot holds a leonida::TargetView. The console's own -// increments are open question 4 in docs/d3d12_vulkan.md; the application reads them from the device, as it must. -constexpr UINT kDescriptorSize = descriptor_size; -// The first 64 KiB of the GPU address arena are never handed out: VA 0 stays invalid, and the page is kept zero -// for unbound vertex and index buffers to read (D3D12 reads zeros there). -constexpr VkDeviceSize kArenaReserved = 64 * 1024; -static_assert(sizeof(leonida::TargetView) <= kDescriptorSize); - -// The shader model and root signature version this layer can honour. Nothing in the runtime compiles DXIL: the -// game's shaders arrive as SPIR-V from the offline translator, and the only DXIL path (the BVH builder) is lowered -// to standard DXIL, whose baseline is 6.0. Answering the driver's own maximum would tell the game it can hand this -// layer shaders it has no front end for, which section 4.1 of docs/d3d12_vulkan.md calls worse than a false -// "unsupported" at boot. Raise these when a front end for the higher version lands. -constexpr D3D_SHADER_MODEL kHighestShaderModel = D3D_SHADER_MODEL_6_0; -constexpr D3D_ROOT_SIGNATURE_VERSION kHighestRootSignatureVersion = D3D_ROOT_SIGNATURE_VERSION_1_1; - -std::atomic g_global_realtime_privilege_override{-1}; - -void log_once(const char* what, int value) { - static std::mutex mutex; - static std::set> seen; - std::lock_guard lock(mutex); - if (seen.insert({what, value}).second) RT_LOG_WARN("d3d12: %s %d\n", what, value); -} - -// Two test settings that make the standalone device look like a GPU with fewer Vulkan queues, so the path where D3D12 -// queues share a VkQueue runs on any GPU; both together give the Intel UHD 770 on Windows and lavapipe (one family, -// one queue). LEONIDA_VK_MAX_QUEUES_PER_FAMILY=N (1 to 16): at most N VkQueues per queue family (unset, or not a -// number from 1 to 16: 16). LEONIDA_VK_GRAPHICS_FAMILY_ONLY=1: COMPUTE and COPY queues use the graphics family, as on -// a GPU without async compute or transfer families. The game's device ignores both (QueueTestSettings::ignore). - -// The setting's value in *text, or false when nothing sets it (its variable, else leonida.toml); set but ignored, it -// says so, naming the variable also when the value came from the file. `size` is the size of the buffer the variable -// was read into before the settings moved to the table: a value of that many characters or more counts as unset. -bool queue_test_setting(rt::config::Name setting, std::string* text, size_t size, - rt::d3d12::QueueTestSettings settings) { - const rt::config::Value value = rt::config::get(setting); - if (!value.is_set() || value.text.size() >= size) return false; - if (settings == rt::d3d12::QueueTestSettings::apply) { - *text = value.text; - return true; - } - RT_LOG_WARN("d3d12: %s is a test setting; the game's device ignores it (all its Vulkan queues)\n", - setting.setting().variable); - return false; -} - -bool graphics_family_only(rt::d3d12::QueueTestSettings settings) { - std::string text; - const bool on = queue_test_setting("vulkan.graphics_family_only", &text, 8, settings) && text[0] != '0'; - if (on) RT_LOG_INFO("d3d12: LEONIDA_VK_GRAPHICS_FAMILY_ONLY: every D3D12 queue in the graphics family\n"); - return on; -} - -std::uint32_t max_queues_per_family(rt::d3d12::QueueTestSettings settings) { - constexpr std::uint32_t most = 16; - std::string text; - if (!queue_test_setting("vulkan.max_queues_per_family", &text, 16, settings)) return most; - char* end = nullptr; - const unsigned long value = std::strtoul(text.c_str(), &end, 10); - if (end == text.c_str() || *end || value < 1 || value > most) { - RT_LOG_WARN("d3d12: LEONIDA_VK_MAX_QUEUES_PER_FAMILY=%s is not a number from 1 to %u: ignored\n", - text.c_str(), most); - return most; - } - RT_LOG_INFO("d3d12: LEONIDA_VK_MAX_QUEUES_PER_FAMILY: at most %lu Vulkan queue(s) per family\n", - value); - return std::uint32_t(value); -} - -// The pipelines build stage writes its cache beside gta6rt.exe, independently of the working directory. -std::filesystem::path pipeline_cache_path() { - std::wstring path(32768, L'\0'); - const DWORD length = GetModuleFileNameW(nullptr, path.data(), static_cast(path.size())); - if (!length || length >= path.size()) return {}; - path.resize(length); - return std::filesystem::path(path).parent_path() / L"pipeline_cache.bin"; -} - -// A corpus cache may be several GiB. Keep the read-only view alive through vkCreatePipelineCache -// and deny writers while the view is in use. -class PipelineCacheSeed { -public: - explicit PipelineCacheSeed(const std::filesystem::path& path) { - if (path.empty()) return; - file_ = CreateFileW(path.c_str(), GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_DELETE, nullptr, - OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr); - if (file_ == INVALID_HANDLE_VALUE) return; - LARGE_INTEGER length{}; - constexpr auto header_size = static_cast(sizeof(VkPipelineCacheHeaderVersionOne)); - if (!GetFileSizeEx(file_, &length) || length.QuadPart < header_size) - return; - const HANDLE mapping = CreateFileMappingW(file_, nullptr, PAGE_READONLY, 0, 0, nullptr); - if (!mapping) return; - data_ = MapViewOfFile(mapping, FILE_MAP_READ, 0, 0, 0); - CloseHandle(mapping); - if (data_) size_ = static_cast(length.QuadPart); - } - - ~PipelineCacheSeed() { - if (data_) UnmapViewOfFile(data_); - if (file_ != INVALID_HANDLE_VALUE) CloseHandle(file_); - } - - PipelineCacheSeed(const PipelineCacheSeed&) = delete; - PipelineCacheSeed& operator=(const PipelineCacheSeed&) = delete; - - const void* data() const { return data_; } - std::size_t size() const { return size_; } - - bool compatible(const leonida::cached_pso::Identity& identity) const { - static_assert(sizeof(VkPipelineCacheHeaderVersionOne) == 32); - VkPipelineCacheHeaderVersionOne header{}; - // The header is little-endian, like the host. The driver interprets the opaque payload. - std::memcpy(&header, data_, sizeof(header)); - return header.headerSize == sizeof(header) && header.headerVersion == VK_PIPELINE_CACHE_HEADER_VERSION_ONE && - header.vendorID == identity.vendor && header.deviceID == identity.device && - std::memcmp(header.pipelineCacheUUID, identity.cache_uuid, VK_UUID_SIZE) == 0; - } - -private: - HANDLE file_ = INVALID_HANDLE_VALUE; - const void* data_ = nullptr; - std::size_t size_ = 0; -}; - -VkPipelineCache create_seeded_pipeline_cache(PFN_vkCreatePipelineCache create_cache, VkDevice device, - const leonida::cached_pso::Identity& identity) { - const PipelineCacheSeed seed(pipeline_cache_path()); - if (!seed.data()) return VK_NULL_HANDLE; - if (!seed.compatible(identity)) { - RT_LOG_WARN("d3d12: pipeline_cache.bin does not match this Vulkan device\n"); - return VK_NULL_HANDLE; - } - const VkPipelineCacheCreateInfo create{VK_STRUCTURE_TYPE_PIPELINE_CACHE_CREATE_INFO, - nullptr, 0, seed.size(), seed.data()}; - VkPipelineCache cache = VK_NULL_HANDLE; - if (create_cache(device, &create, nullptr, &cache) != VK_SUCCESS) { - RT_LOG_WARN("d3d12: Vulkan declined the pipeline cache seed\n"); - return VK_NULL_HANDLE; - } - RT_LOG_INFO("d3d12: loaded %zu bytes from pipeline_cache.bin\n", seed.size()); - return cache; -} - -// A shader whose subgroup size cannot be had runs at the device's: inexact if it crosses the halves of a wave64 (or, -// for a wave32 shader on a 64-wide default, reads lanes that are not its own). Logged once per stage with the first -// shader's name, then again at 10, 100, 1000... of that stage so a whole corpus stays readable. -void report_subgroup_unavailable(const leonida::ShaderEntry& entry, const leonida::SubgroupRequest& request, - const leonida::SubgroupSizeCaps& caps) { - static std::mutex mutex; - static std::map, unsigned>> seen; // stage -> names, next report - std::lock_guard lock(mutex); - auto& [names, next_report] = seen[entry.stage]; - if (!names.insert(entry.name).second) return; - if (names.size() == 1) next_report = 10; - else if (names.size() != next_report) return; - else next_report *= 10; - const bool emulable = entry.stage == "cs" || entry.stage == "ms"; - const std::string so_far = - names.size() > 1 ? " (shaders of this stage so far: " + std::to_string(names.size()) + ")" : ""; - RT_LOG_WARN("d3d12: %s (%s) is a %u-wide shader but this device cannot require that subgroup size for the " - "stage (device sizes %u..%u, default %u, subgroupSizeControl %s); it runs at the device's size and " - "is inexact where lanes of the other half matter%s\n", - entry.name.c_str(), entry.stage.c_str(), request.wanted, caps.min_size, caps.max_size, - caps.default_size, caps.subgroup_size_control ? "on" : "off", - so_far.c_str()); - if (emulable && request.wanted == 64) - RT_LOG_WARN("d3d12: translate wave64 %s shaders with --wave64-emulate for this GPU " - "(make_game.py --wave64-emulate auto does)\n", entry.stage.c_str()); - else if (request.wanted == 64) - RT_LOG_WARN("d3d12: no emulation exists for wave64 %s shaders yet (docs/d3d12_vulkan.md, " - "subgroup size)\n", entry.stage.c_str()); -} - -struct Format { - VkFormat format = VK_FORMAT_UNDEFINED; - VkImageAspectFlags aspects = 0; - bool typeless = false; // created with MUTABLE_FORMAT so typed views can reinterpret it - bool d24_as_float = false; // D24_UNORM_S8_UINT stored as D32_SFLOAT_S8_UINT (no D24 on the GPU) - bool d24 = false; // a D24_UNORM_S8_UINT family format, native or stored as D32 - // A UAV texture whose format has no storage support, stored as the mutable unsigned image `format` names (R32_UINT - // for R9G9B9E5_SHAREDEXP, R16_UINT for B5G5R5A1_UNORM): the format its SRVs, RTVs and T#s use. Its storage view is - // `format`, in the uint class; shaders write the packed bits. UNDEFINED for every other texture. - VkFormat uint_backed = VK_FORMAT_UNDEFINED; - // A 96-bit R32G32B32 format, held in the R32G32B32A32 image `format` names (ResourceBinding::rgb96). - bool rgb96 = false; -}; - -// 96-bit textures are always RGBA32 images, even where the GPU has an RGB32 one (most have none with optimal -// tiling): D3D12 places subresources at multiples of 512 bytes, Vulkan wants a copy's buffer offset to be a -// multiple of the 12-byte texel (VUID-vkCmdCopyBufferToImage-dstImage-07975), so copies need the repack either -// way (docs section 4.2). -constexpr Format rgb96_format(VkFormat wide, bool typeless = false) { - Format format{wide, VK_IMAGE_ASPECT_COLOR_BIT, typeless}; - format.rgb96 = true; - return format; -} - -// DXGI -> Vulkan for the formats render targets, depth buffers and common textures use. R32 and R16 typeless become -// depth formats when the resource allows depth-stencil; R32G8X24 and R24G8 always do, as Vulkan has no colour format -// with their layout. -Format vulkan_format(DXGI_FORMAT format, bool depth) { - constexpr VkImageAspectFlags color = VK_IMAGE_ASPECT_COLOR_BIT, d = VK_IMAGE_ASPECT_DEPTH_BIT, - ds = VK_IMAGE_ASPECT_DEPTH_BIT | VK_IMAGE_ASPECT_STENCIL_BIT; - switch (format) { - case DXGI_FORMAT_R32G32B32A32_TYPELESS: return {VK_FORMAT_R32G32B32A32_SFLOAT, color, true}; - case DXGI_FORMAT_R32G32B32A32_FLOAT: return {VK_FORMAT_R32G32B32A32_SFLOAT, color}; - case DXGI_FORMAT_R32G32B32A32_UINT: return {VK_FORMAT_R32G32B32A32_UINT, color}; - case DXGI_FORMAT_R32G32B32A32_SINT: return {VK_FORMAT_R32G32B32A32_SINT, color}; - case DXGI_FORMAT_R32G32B32_TYPELESS: return rgb96_format(VK_FORMAT_R32G32B32A32_SFLOAT, true); - case DXGI_FORMAT_R32G32B32_FLOAT: return rgb96_format(VK_FORMAT_R32G32B32A32_SFLOAT); - case DXGI_FORMAT_R32G32B32_UINT: return rgb96_format(VK_FORMAT_R32G32B32A32_UINT); - case DXGI_FORMAT_R32G32B32_SINT: return rgb96_format(VK_FORMAT_R32G32B32A32_SINT); - case DXGI_FORMAT_R16G16B16A16_TYPELESS: return {VK_FORMAT_R16G16B16A16_SFLOAT, color, true}; - case DXGI_FORMAT_R16G16B16A16_FLOAT: return {VK_FORMAT_R16G16B16A16_SFLOAT, color}; - case DXGI_FORMAT_R16G16B16A16_UNORM: return {VK_FORMAT_R16G16B16A16_UNORM, color}; - case DXGI_FORMAT_R16G16B16A16_SNORM: return {VK_FORMAT_R16G16B16A16_SNORM, color}; - case DXGI_FORMAT_R16G16B16A16_UINT: return {VK_FORMAT_R16G16B16A16_UINT, color}; - case DXGI_FORMAT_R16G16B16A16_SINT: return {VK_FORMAT_R16G16B16A16_SINT, color}; - case DXGI_FORMAT_R32G32_TYPELESS: return {VK_FORMAT_R32G32_SFLOAT, color, true}; - case DXGI_FORMAT_R32G32_FLOAT: return {VK_FORMAT_R32G32_SFLOAT, color}; - case DXGI_FORMAT_R32G32_UINT: return {VK_FORMAT_R32G32_UINT, color}; - case DXGI_FORMAT_R32G32_SINT: return {VK_FORMAT_R32G32_SINT, color}; - case DXGI_FORMAT_R10G10B10A2_TYPELESS: return {VK_FORMAT_A2B10G10R10_UNORM_PACK32, color, true}; - case DXGI_FORMAT_R10G10B10A2_UNORM: return {VK_FORMAT_A2B10G10R10_UNORM_PACK32, color}; - case DXGI_FORMAT_R10G10B10A2_UINT: return {VK_FORMAT_A2B10G10R10_UINT_PACK32, color}; - // XR_BIAS is the same packed 10:10:10:2 bit layout as R10G10B10A2_UNORM. Vulkan has no XR_BIAS format: - // the application biases and scales the channels in its shader, so the resource itself is an ordinary UNORM. - case DXGI_FORMAT_R10G10B10_XR_BIAS_A2_UNORM: return {VK_FORMAT_A2B10G10R10_UNORM_PACK32, color}; - case DXGI_FORMAT_R9G9B9E5_SHAREDEXP: return {VK_FORMAT_E5B9G9R9_UFLOAT_PACK32, color}; - case DXGI_FORMAT_R11G11B10_FLOAT: return {VK_FORMAT_B10G11R11_UFLOAT_PACK32, color}; - case DXGI_FORMAT_R8G8B8A8_TYPELESS: return {VK_FORMAT_R8G8B8A8_UNORM, color, true}; - case DXGI_FORMAT_R8G8B8A8_UNORM: return {VK_FORMAT_R8G8B8A8_UNORM, color}; - case DXGI_FORMAT_R8G8B8A8_UNORM_SRGB: return {VK_FORMAT_R8G8B8A8_SRGB, color}; - case DXGI_FORMAT_R8G8B8A8_SNORM: return {VK_FORMAT_R8G8B8A8_SNORM, color}; - case DXGI_FORMAT_R8G8B8A8_UINT: return {VK_FORMAT_R8G8B8A8_UINT, color}; - case DXGI_FORMAT_R8G8B8A8_SINT: return {VK_FORMAT_R8G8B8A8_SINT, color}; - case DXGI_FORMAT_B8G8R8A8_TYPELESS: return {VK_FORMAT_B8G8R8A8_UNORM, color, true}; - case DXGI_FORMAT_B8G8R8A8_UNORM: return {VK_FORMAT_B8G8R8A8_UNORM, color}; - // DXGI names channels from the low bits up, Vulkan from the high bits down: B in bits 0-3, A in 12-15 in both. - // Vulkan 1.3 requires sampling it (formerly VK_EXT_4444_formats). - case DXGI_FORMAT_B4G4R4A4_UNORM: return {VK_FORMAT_A4R4G4B4_UNORM_PACK16, color}; - // A in bits 0-3 and R in 12-15 (cleared and read back on native D3D12, AMD and WARP): Vulkan's R4G4B4A4_PACK16. - case DXGI_FORMAT_A4B4G4R4_UNORM: return {VK_FORMAT_R4G4B4A4_UNORM_PACK16, color}; - case DXGI_FORMAT_B8G8R8A8_UNORM_SRGB: return {VK_FORMAT_B8G8R8A8_SRGB, color}; - // The X byte has no channel of its own: the BGRA8 images hold it, and shader views read alpha as 1. - case DXGI_FORMAT_B8G8R8X8_TYPELESS: return {VK_FORMAT_B8G8R8A8_UNORM, color, true}; - case DXGI_FORMAT_B8G8R8X8_UNORM: return {VK_FORMAT_B8G8R8A8_UNORM, color}; - case DXGI_FORMAT_B8G8R8X8_UNORM_SRGB: return {VK_FORMAT_B8G8R8A8_SRGB, color}; - case DXGI_FORMAT_R16G16_TYPELESS: return {VK_FORMAT_R16G16_SFLOAT, color, true}; - case DXGI_FORMAT_R16G16_FLOAT: return {VK_FORMAT_R16G16_SFLOAT, color}; - case DXGI_FORMAT_R16G16_UNORM: return {VK_FORMAT_R16G16_UNORM, color}; - case DXGI_FORMAT_R16G16_SNORM: return {VK_FORMAT_R16G16_SNORM, color}; - case DXGI_FORMAT_R16G16_UINT: return {VK_FORMAT_R16G16_UINT, color}; - case DXGI_FORMAT_R16G16_SINT: return {VK_FORMAT_R16G16_SINT, color}; - case DXGI_FORMAT_R8G8_TYPELESS: return {VK_FORMAT_R8G8_UNORM, color, true}; - case DXGI_FORMAT_R8G8_UNORM: return {VK_FORMAT_R8G8_UNORM, color}; - case DXGI_FORMAT_R8G8_SNORM: return {VK_FORMAT_R8G8_SNORM, color}; - case DXGI_FORMAT_R16_UNORM: return {VK_FORMAT_R16_UNORM, color}; - case DXGI_FORMAT_R16_SNORM: return {VK_FORMAT_R16_SNORM, color}; - case DXGI_FORMAT_R16_UINT: return {VK_FORMAT_R16_UINT, color}; - case DXGI_FORMAT_R16_SINT: return {VK_FORMAT_R16_SINT, color}; - // DXGI names packed channels from the high bits down, Vulkan's PACK formats the same way but spelled the other - // way round: B5G6R5 (blue in bits 0-4) is R5G6B5_PACK16 and B5G5R5A1 (alpha in bit 15) is A1R5G5B5_PACK16. - case DXGI_FORMAT_B5G6R5_UNORM: return {VK_FORMAT_R5G6B5_UNORM_PACK16, color}; - case DXGI_FORMAT_B5G5R5A1_UNORM: return {VK_FORMAT_A1R5G5B5_UNORM_PACK16, color}; - case DXGI_FORMAT_R8G8_UINT: return {VK_FORMAT_R8G8_UINT, color}; - case DXGI_FORMAT_R8G8_SINT: return {VK_FORMAT_R8G8_SINT, color}; - case DXGI_FORMAT_R16_FLOAT: return {VK_FORMAT_R16_SFLOAT, color}; - case DXGI_FORMAT_R8_UNORM: return {VK_FORMAT_R8_UNORM, color}; - case DXGI_FORMAT_R8_TYPELESS: return {VK_FORMAT_R8_UNORM, color, true}; - case DXGI_FORMAT_R8_SNORM: return {VK_FORMAT_R8_SNORM, color}; - case DXGI_FORMAT_R8_UINT: return {VK_FORMAT_R8_UINT, color}; - case DXGI_FORMAT_R8_SINT: return {VK_FORMAT_R8_SINT, color}; - case DXGI_FORMAT_R32_FLOAT: return {VK_FORMAT_R32_SFLOAT, color}; - case DXGI_FORMAT_R32_UINT: return {VK_FORMAT_R32_UINT, color}; - case DXGI_FORMAT_R32_SINT: return {VK_FORMAT_R32_SINT, color}; - case DXGI_FORMAT_BC1_TYPELESS: return {VK_FORMAT_BC1_RGBA_UNORM_BLOCK, color, true}; - case DXGI_FORMAT_BC1_UNORM: return {VK_FORMAT_BC1_RGBA_UNORM_BLOCK, color}; - case DXGI_FORMAT_BC1_UNORM_SRGB: return {VK_FORMAT_BC1_RGBA_SRGB_BLOCK, color}; - case DXGI_FORMAT_BC2_TYPELESS: return {VK_FORMAT_BC2_UNORM_BLOCK, color, true}; - case DXGI_FORMAT_BC2_UNORM: return {VK_FORMAT_BC2_UNORM_BLOCK, color}; - case DXGI_FORMAT_BC2_UNORM_SRGB: return {VK_FORMAT_BC2_SRGB_BLOCK, color}; - case DXGI_FORMAT_BC3_TYPELESS: return {VK_FORMAT_BC3_UNORM_BLOCK, color, true}; - case DXGI_FORMAT_BC3_UNORM: return {VK_FORMAT_BC3_UNORM_BLOCK, color}; - case DXGI_FORMAT_BC3_UNORM_SRGB: return {VK_FORMAT_BC3_SRGB_BLOCK, color}; - case DXGI_FORMAT_BC4_TYPELESS: return {VK_FORMAT_BC4_UNORM_BLOCK, color, true}; - case DXGI_FORMAT_BC4_UNORM: return {VK_FORMAT_BC4_UNORM_BLOCK, color}; - case DXGI_FORMAT_BC4_SNORM: return {VK_FORMAT_BC4_SNORM_BLOCK, color}; - case DXGI_FORMAT_BC5_TYPELESS: return {VK_FORMAT_BC5_UNORM_BLOCK, color, true}; - case DXGI_FORMAT_BC5_UNORM: return {VK_FORMAT_BC5_UNORM_BLOCK, color}; - case DXGI_FORMAT_BC5_SNORM: return {VK_FORMAT_BC5_SNORM_BLOCK, color}; - case DXGI_FORMAT_BC6H_TYPELESS: return {VK_FORMAT_BC6H_UFLOAT_BLOCK, color, true}; - case DXGI_FORMAT_BC6H_UF16: return {VK_FORMAT_BC6H_UFLOAT_BLOCK, color}; - case DXGI_FORMAT_BC6H_SF16: return {VK_FORMAT_BC6H_SFLOAT_BLOCK, color}; - case DXGI_FORMAT_BC7_TYPELESS: return {VK_FORMAT_BC7_UNORM_BLOCK, color, true}; - case DXGI_FORMAT_BC7_UNORM: return {VK_FORMAT_BC7_UNORM_BLOCK, color}; - case DXGI_FORMAT_BC7_UNORM_SRGB: return {VK_FORMAT_BC7_SRGB_BLOCK, color}; - case DXGI_FORMAT_D32_FLOAT: return {VK_FORMAT_D32_SFLOAT, d}; - case DXGI_FORMAT_D16_UNORM: return {VK_FORMAT_D16_UNORM, d}; - case DXGI_FORMAT_D32_FLOAT_S8X24_UINT: return {VK_FORMAT_D32_SFLOAT_S8_UINT, ds}; - case DXGI_FORMAT_D24_UNORM_S8_UINT: return {VK_FORMAT_D24_UNORM_S8_UINT, ds}; - case DXGI_FORMAT_R32_TYPELESS: - return depth ? Format{VK_FORMAT_D32_SFLOAT, d, true} : Format{VK_FORMAT_R32_SFLOAT, color, true}; - case DXGI_FORMAT_R16_TYPELESS: - return depth ? Format{VK_FORMAT_D16_UNORM, d, true} : Format{VK_FORMAT_R16_UNORM, color, true}; - case DXGI_FORMAT_R32G8X24_TYPELESS: return {VK_FORMAT_D32_SFLOAT_S8_UINT, ds, true}; - case DXGI_FORMAT_R24G8_TYPELESS: return {VK_FORMAT_D24_UNORM_S8_UINT, ds, true}; - default: return {}; - } -} - -Format texture_storage_format(DXGI_FORMAT format, bool depth) { - return vulkan_format(format == DXGI_FORMAT_A8_UNORM ? DXGI_FORMAT_R8_UNORM : format, depth); -} - -// The three-channel format a view of a 96-bit texture names in its T# (GFX10_FORMAT_32_32_32_*): the format -// whose channels the view's swizzle is taken from, so alpha reads as one whatever the image's fourth channel holds. -VkFormat rgb96_named_format(VkFormat image_view_format) { - switch (image_view_format) { - case VK_FORMAT_R32G32B32A32_SFLOAT: return VK_FORMAT_R32G32B32_SFLOAT; - case VK_FORMAT_R32G32B32A32_UINT: return VK_FORMAT_R32G32B32_UINT; - case VK_FORMAT_R32G32B32A32_SINT: return VK_FORMAT_R32G32B32_SINT; - default: return VK_FORMAT_UNDEFINED; - } -} -// And back: the format of the view of the RGBA32 image that shows such a T#. -VkFormat rgb96_view_format(VkFormat image_format, std::uint32_t gfx10_format) { - for (const VkFormat wide : {VK_FORMAT_R32G32B32A32_SFLOAT, VK_FORMAT_R32G32B32A32_UINT, VK_FORMAT_R32G32B32A32_SINT}) - if (leonida::gfx10::format_from_vulkan(rgb96_named_format(wide)) == gfx10_format) - return rgb96_named_format(image_format) != VK_FORMAT_UNDEFINED ? wide : VK_FORMAT_UNDEFINED; - return VK_FORMAT_UNDEFINED; -} - -// Bytes per texel or block as D3D12 lays the format out in a footprint. -leonida::BlockFormat footprint_block(const Format& format, VkImageAspectFlags aspect) { - leonida::BlockFormat block = leonida::block_format(format.format, aspect); - if (format.rgb96 && block.bytes) block.bytes = leonida::rgb96_bytes; - return block; -} - -// 96-bit textures are sampled and copied, nothing else yet: the flags creation refuses, and -// GetResourceAllocationInfo with it. The PC runtime (WARP) refuses unordered access and depth too; it does make -// 96-bit render targets (d3d12_rgb96_test prints both devices' answers). -bool rgb96_refused(const D3D12_RESOURCE_DESC& desc) { - return vulkan_format(desc.Format, false).rgb96 && - (desc.Flags & (D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS | D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET | - D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL)); -} - -// B8G8R8X8: the BGRA8 Vulkan formats with the alpha byte unused. Its typeless family is a family of its own, so -// only a castable-format list lets a view cross between it and B8G8R8A8, although both land on the same VkFormat. -bool alpha_unused(DXGI_FORMAT format) { - return format == DXGI_FORMAT_B8G8R8X8_TYPELESS || format == DXGI_FORMAT_B8G8R8X8_UNORM || - format == DXGI_FORMAT_B8G8R8X8_UNORM_SRGB; -} - -// The 8-bit four-channel UNORM and SRGB formats in either channel order, B8G8R8X8 included. A texture in one of them -// takes an RTV in another when its castable-format list names it: WARP and AMD's D3D12 driver store the clear or the -// draw in the view's channel order and encoding. -bool rgba8_any_order(DXGI_FORMAT format) { - switch (format) { - case DXGI_FORMAT_R8G8B8A8_UNORM: case DXGI_FORMAT_R8G8B8A8_UNORM_SRGB: - case DXGI_FORMAT_B8G8R8A8_UNORM: case DXGI_FORMAT_B8G8R8A8_UNORM_SRGB: - case DXGI_FORMAT_B8G8R8X8_UNORM: case DXGI_FORMAT_B8G8R8X8_UNORM_SRGB: return true; - default: return false; - } -} - -// The full mip chain's length for a texture this size. -UINT16 full_mips(UINT64 width, UINT height, UINT depth) { - UINT16 mips = 0; - for (UINT64 size = std::max({width, height, depth}); size; size >>= 1) ++mips; - return mips; -} - -// XR_BIAS is a display format: the PC runtime accepts it only as a single-mip, single-sample 2D texture, and -// refuses 3D, extra mips and multisampling in creation, allocation and footprints alike. -bool xr_bias_compatible(const D3D12_RESOURCE_DESC& desc) { - if (desc.Format != DXGI_FORMAT_R10G10B10_XR_BIAS_A2_UNORM) return true; - if (desc.Dimension != D3D12_RESOURCE_DIMENSION_TEXTURE2D || desc.SampleDesc.Count != 1) return false; - const UINT mips = desc.MipLevels ? desc.MipLevels : full_mips(desc.Width, desc.Height, 1); - return mips == 1; -} - -// The Xbox tiled layout word (slot 76, docs/d3d12_vulkan.md section 4.2) is outside D3D12_TEXTURE_LAYOUT's -// enumerators, so compare as an integer. -constexpr UINT kXboxTiledLayout = 0x101; - -bool is_tiled_layout(D3D12_TEXTURE_LAYOUT layout) { - return layout == D3D12_TEXTURE_LAYOUT_64KB_UNDEFINED_SWIZZLE || static_cast(layout) == kXboxTiledLayout; -} - -// A volume RTV covers W slices of one mip. UINT_MAX extends through the last slice of that mip. -leonida::TargetView volume_rtv(leonida::ResourceId id, const D3D12_RESOURCE_DESC& resource, - const D3D12_RENDER_TARGET_VIEW_DESC* view) { - if (!(resource.Flags & D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET) || vulkan_format(resource.Format, false).typeless) - return {}; - if (view && (view->ViewDimension != D3D12_RTV_DIMENSION_TEXTURE3D || - (view->Format != DXGI_FORMAT_UNKNOWN && view->Format != resource.Format))) return {}; - const D3D12_TEX3D_RTV slices = view ? view->Texture3D : D3D12_TEX3D_RTV{0, 0, UINT_MAX}; - if (slices.MipSlice >= resource.MipLevels) return {}; - const UINT depth = std::max(1u, UINT(resource.DepthOrArraySize) >> slices.MipSlice); - if (slices.FirstWSlice >= depth) return {}; - const UINT remaining = depth - slices.FirstWSlice; - const UINT count = slices.WSize == UINT_MAX ? remaining : slices.WSize; - if (!count || count > remaining) return {}; - return {id, slices.MipSlice, slices.FirstWSlice, count}; -} - -leonida::TargetView line_target_view(leonida::ResourceId id, const D3D12_RESOURCE_DESC& resource, - UINT mip, UINT first_layer, UINT layer_count) { - if (resource.Dimension != D3D12_RESOURCE_DIMENSION_TEXTURE1D || mip >= resource.MipLevels || - first_layer >= resource.DepthOrArraySize) - return {}; - const UINT remaining = UINT(resource.DepthOrArraySize) - first_layer; - const UINT count = layer_count == UINT_MAX ? remaining : layer_count; - if (!count || count > remaining) return {}; - return {id, mip, first_layer, count}; -} - -// ArraySize of a 2D-array RTV or DSV: UINT_MAX is every slice from the first on, as on the host. Any other count -// is kept, and UINT_MAX with a first slice past the array too, so an out-of-range view is refused as before. -UINT view_slices(const D3D12_RESOURCE_DESC& resource, UINT first_layer, UINT layer_count) { - const bool remaining = layer_count == UINT_MAX && first_layer < resource.DepthOrArraySize; - return remaining ? resource.DepthOrArraySize - first_layer : layer_count; -} - -// The VkImage a texture description becomes, with its mip count already resolved (MipLevels != 0). Shared by -// texture creation and GetResourceAllocationInfo, so the sizes reported are the sizes later allocated. -// Keeps the optional VkImageFormatListCreateInfo alongside VkImageCreateInfo so info.pNext stays valid. -// attachment_usable: the GPU can render to `format`. A UAV texture then also gets COLOR_ATTACHMENT usage, because -// ClearUnorderedAccessView* with rectangles clears through an attachment (vkCmdClearAttachments). -struct TextureCreateInfo { - VkImageCreateInfo info{VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO}; - VkImageFormatListCreateInfo format_list{VK_STRUCTURE_TYPE_IMAGE_FORMAT_LIST_CREATE_INFO}; - std::array view_formats{}; - - TextureCreateInfo(const D3D12_RESOURCE_DESC& desc, const Format& format, bool attachment_usable) { - const bool volume = desc.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE3D; - const bool one_d = desc.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE1D; - info.flags = format.typeless ? VK_IMAGE_CREATE_MUTABLE_FORMAT_BIT : 0; - if (volume && (desc.Flags & D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET)) - info.flags |= VK_IMAGE_CREATE_2D_ARRAY_COMPATIBLE_BIT; - info.imageType = volume ? VK_IMAGE_TYPE_3D : one_d ? VK_IMAGE_TYPE_1D : VK_IMAGE_TYPE_2D; - info.format = format.format; - info.extent = {std::uint32_t(desc.Width), one_d ? 1u : desc.Height, - volume ? UINT(desc.DepthOrArraySize) : 1u}; - info.mipLevels = desc.MipLevels; - info.arrayLayers = volume ? 1 : desc.DepthOrArraySize; - info.samples = VkSampleCountFlagBits(std::max(1u, desc.SampleDesc.Count)); - info.usage = VK_IMAGE_USAGE_TRANSFER_SRC_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT; - if (desc.Flags & D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET) info.usage |= VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT; - if (desc.Flags & D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL) info.usage |= VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT; - // No B8G8R8X8 view is ever a UAV, so its typeless family needs no storage usage (not every GPU has it for BGRA8). - if ((desc.Flags & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS) && !alpha_unused(desc.Format)) { - info.usage |= VK_IMAGE_USAGE_STORAGE_BIT; - if (!volume && info.samples == VK_SAMPLE_COUNT_1_BIT && attachment_usable) - info.usage |= VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT; - } - if (!(desc.Flags & D3D12_RESOURCE_FLAG_DENY_SHADER_RESOURCE)) info.usage |= VK_IMAGE_USAGE_SAMPLED_BIT; - if (format.uint_backed) { - // The unsigned format owns the storage usage; views in the logical format restrict their usage (SAMPLED_BIT - // for SRVs, COLOR_ATTACHMENT_BIT for RTVs). - info.flags |= VK_IMAGE_CREATE_MUTABLE_FORMAT_BIT | VK_IMAGE_CREATE_EXTENDED_USAGE_BIT; - view_formats = {format.format, format.uint_backed}; - format_list.viewFormatCount = 2; - format_list.pViewFormats = view_formats.data(); - info.pNext = &format_list; - } - } - - TextureCreateInfo(const TextureCreateInfo&) = delete; - TextureCreateInfo& operator=(const TextureCreateInfo&) = delete; -}; - -// The folder make_game recorded in shader_path.txt at `config`, or empty without one. Throws when the path cannot be -// converted: MSVC's STL reports a Windows path that is not UTF-8 as std::system_error, libstdc++ as filesystem_error. -std::filesystem::path shader_directory_from_file(const std::filesystem::path& config) { - std::ifstream file(config, std::ios::binary); - if (!file) return {}; - const std::string text{std::istreambuf_iterator(file), std::istreambuf_iterator()}; - if (text.empty() || text.find('\0') != std::string::npos) return {}; - - // make_game records an absolute Unix path on Linux. Resolve it inside the running Wine prefix. - if (text.front() == '/') { - using WineDosPath = wchar_t* (CDECL*)(const char*); - const auto to_dos = std::bit_cast( - ::GetProcAddress(::GetModuleHandleW(L"kernel32.dll"), "wine_get_dos_file_name")); - if (!to_dos) return {}; - const auto release = [](wchar_t* path) { ::HeapFree(::GetProcessHeap(), 0, path); }; - const std::unique_ptr path(to_dos(text.c_str()), release); - if (path) return std::filesystem::path(path.get()); - return {}; - } - return std::filesystem::path(std::u8string(text.begin(), text.end())); -} - -// What a device's children need from it, kept apart from the COM class so children can hold a plain pointer. -struct DeviceState { - VulkanDeviceInfo info; - std::vector families; - - template - void share(CreateInfo& create) const { - if (families.size() < 2) return; - create.sharingMode = VK_SHARING_MODE_CONCURRENT; - create.queueFamilyIndexCount = std::uint32_t(families.size()); - create.pQueueFamilyIndices = families.data(); - } - std::unique_ptr context; - VkPhysicalDeviceMemoryProperties memory{}; - // D3D-96: upload-heap buffers prefer DEVICE_LOCAL | HOST_VISIBLE memory, so the GPU reads them from VRAM. Only - // with Resizable BAR (leonida::resizable_bar); LEONIDA_UPLOAD_SYSMEM=1 keeps them in system memory to compare. - bool upload_in_vram = false; - // D3D-299: the first texture or default-heap buffer that lands outside device-local memory is logged, once. - mutable std::once_flag spill_logged; - - // What D3D12_OPTIONS1 answers with: the physical device's own subgroup facts, read on first use. - struct SubgroupFacts { - UINT lane_min = 0; - UINT lane_max = 0; - bool wave_ops = false; - }; - SubgroupFacts subgroups; - std::once_flag subgroups_once; - // VkPhysicalDeviceMeshShaderPropertiesEXT, read on first use by a mesh PSO; zeros when it cannot be asked. - VkPhysicalDeviceMeshShaderPropertiesEXT mesh_properties{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MESH_SHADER_PROPERTIES_EXT}; - bool mesh_properties_read = false; - std::mutex mesh_properties_mutex; - PFN_vkGetPhysicalDeviceFormatProperties format_properties = nullptr; - PFN_vkGetPhysicalDeviceImageFormatProperties image_format_properties = nullptr; - PFN_vkGetPhysicalDeviceImageFormatProperties2 image_format_properties2 = nullptr; - PFN_vkGetDeviceImageMemoryRequirements image_requirements = nullptr; // Vulkan 1.3 or VK_KHR_maintenance4 - LUID luid{}; // VkPhysicalDeviceIDProperties::deviceLUID; zero when the driver reports none - // An integrated GPU (VK_PHYSICAL_DEVICE_TYPE_INTEGRATED_GPU): D3D12_FEATURE_ARCHITECTURE answers UMA, the custom - // heap equivalents are in MEMORY_POOL_L0 and custom heaps in L1 are refused, as the host runtime does there. - bool uma = false; - leonida::cached_pso::Identity pso_identity; // what GetCachedBlob records and CachedPSO is checked against - std::once_flag pipeline_cache_once; - VkPipelineCache pipeline_cache_handle = VK_NULL_HANDLE; - - VkPipelineCache pipeline_cache() { - std::call_once(pipeline_cache_once, [this] { - const auto& vk = context->vk; - if (!vk.vkCreatePipelineCache || !vk.vkDestroyPipelineCache) return; - pipeline_cache_handle = create_seeded_pipeline_cache(vk.vkCreatePipelineCache, info.device, pso_identity); - if (pipeline_cache_handle) return; - const VkPipelineCacheCreateInfo create{VK_STRUCTURE_TYPE_PIPELINE_CACHE_CREATE_INFO}; - if (vk.vkCreatePipelineCache(info.device, &create, nullptr, &pipeline_cache_handle) != VK_SUCCESS) - pipeline_cache_handle = VK_NULL_HANDLE; - }); - // Without EXTERNALLY_SYNCHRONIZED_BIT the driver synchronizes concurrent pipeline creation using this cache. - return pipeline_cache_handle; - } - - QueueClock clock; // what every queue's GetClockCalibration uses - PFN_vkGetPhysicalDeviceFormatProperties2 format_properties2 = nullptr; - // True when VK_FORMAT_E5B9G9R9_UFLOAT_PACK32 lacks native STORAGE_IMAGE but mutable R32_UINT+{R32_UINT,E5B9G9R9} - // is supported, so R9G9B9E5_SHAREDEXP UAV textures are backed by R32_UINT with separate storage/sampled views. - bool r9g9b9e5_uav_emulated = false; - // The same for B5G5R5A1_UNORM: VK_FORMAT_A1R5G5B5_UNORM_PACK16 without STORAGE_IMAGE, backed by mutable R16_UINT. - bool b5g5r5a1_uav_emulated = false; - // The same for the 8-bit sRGB formats: VK_FORMAT_R8G8B8A8_SRGB / B8G8R8A8_SRGB without STORAGE_IMAGE (as on most - // GPUs), backed by a mutable image of the UNORM format of the same order. The host runtime makes such textures. - bool rgba8_srgb_uav_emulated = false; - bool bgra8_srgb_uav_emulated = false; - - // Cached physical-device no-attachment sample counts for D3D12_OPTIONS19. - UINT no_output_sample_counts = 0; - std::uint32_t f16_half_top_location = 29; - float max_sampler_lod_bias = 0; - D3D12_CONSERVATIVE_RASTERIZATION_TIER conservative_raster_tier = D3D12_CONSERVATIVE_RASTERIZATION_TIER_NOT_SUPPORTED; - bool conservative_post_depth_coverage = false; - // VkPhysicalDeviceDepthStencilResolveProperties: the modes a depth or stencil ResolveSubresourceRegion can use. - VkResolveModeFlags depth_resolve_modes = 0; - VkResolveModeFlags stencil_resolve_modes = 0; - - // VK_EXT_host_image_copy; null unless the device enabled it and its copies accept GENERAL. - PFN_vkCopyMemoryToImageEXT copy_memory_to_image = nullptr; - PFN_vkCopyImageToMemoryEXT copy_image_to_memory = nullptr; - PFN_vkTransitionImageLayoutEXT transition_image_layout = nullptr; - // VK_EXT_external_memory_host; null unless info.host_pointer_alignment is set and the entry point loaded. - PFN_vkGetMemoryHostPointerPropertiesEXT get_host_pointer_properties = nullptr; - - // WriteToSubresource/ReadFromSubresource without host image copy: one staging copy at a time, submitted to - // the device's VkQueue and waited for. Created on first use. - std::mutex staging_mutex; - std::unique_ptr staging_queue; - - // The GPU address arena (docs/d3d12_vulkan.md section 3.3): one host-visible, device-addressable VkBuffer that - // stands in for the console's GPU address space. A console VA is an offset in it, and heap_base (push-constant - // dwords 32-33) is its device address. It is at most 4 GiB, so every VA fits the 32-bit descriptor-table - // pointers some shaders use, and no larger than the device's maxBufferSize and maxMemoryAllocationSize - // (src/arena_size.h). The first 64 KiB are never handed out, so no resource has VA 0. - struct Arena { - VkBuffer buffer = VK_NULL_HANDLE; - VkDeviceMemory memory = VK_NULL_HANDLE; - std::uint8_t* mapped = nullptr; - VkDeviceAddress address = 0; - VkDeviceSize size = 0; - std::uint32_t memory_type = 0; - std::mutex mutex; - std::map free; // offset -> size - - // The high-water mark (D3D-55, open question 5): the arena's size is a guess until a run measures it. - // `peak_end` is the highest end offset ever handed out, the size the arena must have; `peak_in_use` is the - // most bytes live at once, which differs from it by fragmentation. - bool log = false; // LEONIDA_ARENA_LOG=1: one line per VA handed out - VkDeviceSize in_use = 0, peak_in_use = 0, peak_end = 0; - VkDeviceSize use_in_use[4] = {}, use_peak[4] = {}; - std::uint64_t allocations = 0, failures = 0; - } arena; - - std::uint32_t sparse_buffer_memory_types = 0; - bool sparse_image_tiles = false; - - bool tiles_share_arena() const { return (sparse_buffer_memory_types & (1u << arena.memory_type)) != 0; } - - VkBufferCreateInfo sparse_buffer_info(VkDeviceSize bytes) const { - VkBufferCreateInfo result{VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO}; - result.size = bytes; - result.flags = VK_BUFFER_CREATE_SPARSE_BINDING_BIT | VK_BUFFER_CREATE_SPARSE_RESIDENCY_BIT | - VK_BUFFER_CREATE_SPARSE_ALIASED_BIT; - result.usage = VK_BUFFER_USAGE_TRANSFER_SRC_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT | - VK_BUFFER_USAGE_VERTEX_BUFFER_BIT | VK_BUFFER_USAGE_INDEX_BUFFER_BIT | - VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT | VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | - VK_BUFFER_USAGE_INDIRECT_BUFFER_BIT | VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT; - if (info.conditional_rendering) result.usage |= VK_BUFFER_USAGE_CONDITIONAL_RENDERING_BIT_EXT; - // D3D12 reserved buffers are visible to DIRECT, COPY and COMPUTE queues without exposing Vulkan - // queue-family ownership. Their tile bindings and accesses may use distinct families, so match the - // CONCURRENT sharing policy used for ordinary buffers and the GPU address arena. - share(result); - return result; - } - - // What an arena range holds, for the high-water report (D3D-55). - enum ArenaUse { arena_buffer, arena_descriptor_heap, arena_shader, arena_heap }; - static constexpr const char* kArenaUseNames[4] = {"buffer", "descriptor heap", "shader", "heap"}; - - // A zero-size range is refused: it would share its offset with the next range, and its release would collide - // with that range's free entry. The fit test cannot wrap: free blocks lie inside the arena (below 4 GiB). - bool arena_allocate(VkDeviceSize bytes, VkDeviceSize alignment, VkDeviceSize& out, ArenaUse use) { - if (!bytes || bytes > arena.size) return false; - std::lock_guard lock(arena.mutex); - for (auto it = arena.free.begin(); it != arena.free.end(); ++it) { - const VkDeviceSize start = (it->first + alignment - 1) / alignment * alignment; - const VkDeviceSize end = it->first + it->second; - if (start >= end || bytes > end - start) continue; - const VkDeviceSize block = it->first; - arena.free.erase(it); - if (start > block) arena.free[block] = start - block; - if (start + bytes < end) arena.free[start + bytes] = end - (start + bytes); - out = start; - ++arena.allocations; - arena.in_use += bytes; - arena.peak_in_use = std::max(arena.peak_in_use, arena.in_use); - arena.peak_end = std::max(arena.peak_end, start + bytes); - arena.use_in_use[use] += bytes; - arena.use_peak[use] = std::max(arena.use_peak[use], arena.use_in_use[use]); - if (arena.log) - RT_LOG_DEBUG("d3d12: arena %s VA 0x%llx + 0x%llx\n", kArenaUseNames[use], - (unsigned long long)start, (unsigned long long)bytes); - return true; - } - ++arena.failures; - if (arena.log) - RT_LOG_DEBUG("d3d12: arena %s: no room for 0x%llx bytes\n", kArenaUseNames[use], - (unsigned long long)bytes); - return false; - } - - // A console VA outside the arena (an upload or readback buffer: its device address minus heap_base). - void log_va(const char* what, std::uint64_t va, VkDeviceSize bytes) { - if (arena.log) - RT_LOG_DEBUG("d3d12: %s VA 0x%llx + 0x%llx (outside the arena)\n", what, - (unsigned long long)va, (unsigned long long)bytes); - } - - // Printed once at device release, so a run reports the size the arena needs. - void report_arena() { - std::lock_guard lock(arena.mutex); - if (!arena.size) return; - const double mib = 1.0 / (1 << 20); - RT_LOG_INFO("d3d12: GPU address arena: peak end %.1f of %.1f MiB (%.1f%%), peak live %.1f MiB " - "(buffers %.1f, descriptor heaps %.1f, shaders %.1f, heaps %.1f), %llu allocations, %llu refused\n", - arena.peak_end * mib, arena.size * mib, 100.0 * double(arena.peak_end) / double(arena.size), - arena.peak_in_use * mib, arena.use_peak[arena_buffer] * mib, - arena.use_peak[arena_descriptor_heap] * mib, arena.use_peak[arena_shader] * mib, - arena.use_peak[arena_heap] * mib, - (unsigned long long)arena.allocations, (unsigned long long)arena.failures); - } - - void arena_release(VkDeviceSize offset, VkDeviceSize bytes, ArenaUse use) { - if (!bytes) return; - std::lock_guard lock(arena.mutex); - arena.in_use -= bytes; - arena.use_in_use[use] -= bytes; - auto it = arena.free.emplace(offset, bytes).first; - if (auto next = std::next(it); next != arena.free.end() && it->first + it->second == next->first) { - it->second += next->second; - arena.free.erase(next); - } - if (it != arena.free.begin()) { - if (auto previous = std::prev(it); previous->first + previous->second == it->first) { - previous->second += it->second; - arena.free.erase(it); - } - } - } - - // The translator's output, loaded on first use. - std::mutex library_mutex; - bool library_tried = false; - leonida::ShaderLibrary shader_library; - - const leonida::ShaderLibrary* library() { - std::lock_guard lock(library_mutex); - if (!library_tried) { - library_tried = true; - // Nothing may leave here into Create*PipelineState: a path the STL cannot convert throws std::system_error - // under MSVC, which is not a filesystem_error, so every std::exception gives the message. - try { - std::string error; - const std::filesystem::path dir = info.shader_dir.empty() ? configured_shader_directory(&error) - : std::filesystem::path(info.shader_dir); - if (!error.empty()) - RT_LOG_ERROR("d3d12: invalid translated shader path: %s\n", error.c_str()); - else if (dir.empty()) - RT_LOG_WARN("d3d12: no translated shaders: set LEONIDA_SHADERS to /shaders/spirv\n"); - else if (!shader_library.load(dir, &error)) - RT_LOG_ERROR("d3d12: %s\n", error.c_str()); - else { - const auto path = shader_library.directory().u8string(); - RT_LOG_INFO("d3d12: %zu translated shaders from %s\n", - shader_library.size(), reinterpret_cast(path.c_str())); - } - } catch (const std::exception& e) { - RT_LOG_ERROR("d3d12: invalid translated shader path: %s\n", e.what()); - } - } - return shader_library.loaded() ? &shader_library : nullptr; - } - - bool depth_usable(VkFormat format) const { - VkFormatProperties properties{}; - format_properties(info.physical, format, &properties); - return properties.optimalTilingFeatures & VK_FORMAT_FEATURE_DEPTH_STENCIL_ATTACHMENT_BIT; - } - - bool color_attachment_usable(VkFormat format) const { - VkFormatProperties properties{}; - format_properties(info.physical, format, &properties); - return (properties.optimalTilingFeatures & VK_FORMAT_FEATURE_COLOR_ATTACHMENT_BIT) != 0; - } - - bool storage_usable(VkFormat format) const { - VkFormatProperties properties{}; - format_properties(info.physical, format, &properties); - return (properties.optimalTilingFeatures & VK_FORMAT_FEATURE_STORAGE_IMAGE_BIT) != 0; - } - - bool sampled_usable(VkFormat format) const { - VkFormatProperties properties{}; - format_properties(info.physical, format, &properties); - return (properties.optimalTilingFeatures & VK_FORMAT_FEATURE_SAMPLED_IMAGE_BIT) != 0; - } - - // Whether the GPU needs and supports backing UAV textures of `logical` (no storage support) with a mutable image of - // the unsigned format `backing` of the same size. - bool probe_uint_backed_uav(VkFormat logical, VkFormat backing) const { - if (storage_usable(logical)) return false; - if (!image_format_properties2 || !storage_usable(backing) || !sampled_usable(logical)) return false; - const VkFormat view_formats[2] = {backing, logical}; - VkImageFormatListCreateInfo list{VK_STRUCTURE_TYPE_IMAGE_FORMAT_LIST_CREATE_INFO}; - list.viewFormatCount = 2; - list.pViewFormats = view_formats; - VkPhysicalDeviceImageFormatInfo2 query{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_IMAGE_FORMAT_INFO_2, &list}; - query.format = backing; - query.type = VK_IMAGE_TYPE_2D; - query.tiling = VK_IMAGE_TILING_OPTIMAL; - query.usage = VK_IMAGE_USAGE_TRANSFER_SRC_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT | - VK_IMAGE_USAGE_STORAGE_BIT | VK_IMAGE_USAGE_SAMPLED_BIT; - query.flags = VK_IMAGE_CREATE_MUTABLE_FORMAT_BIT | VK_IMAGE_CREATE_EXTENDED_USAGE_BIT; - VkImageFormatProperties2 props{VK_STRUCTURE_TYPE_IMAGE_FORMAT_PROPERTIES_2}; - return image_format_properties2(info.physical, &query, &props) == VK_SUCCESS; - } - - // The limits apply to this exact combination of format, type, tiling, usage, create flags and pNext format list. - HRESULT check_image_support(const VkImageCreateInfo& create) const { - VkImageFormatProperties limits{}; - VkResult result = VK_ERROR_FORMAT_NOT_SUPPORTED; - if (image_format_properties2) { - VkPhysicalDeviceImageFormatInfo2 query{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_IMAGE_FORMAT_INFO_2}; - query.pNext = create.pNext; - query.format = create.format; - query.type = create.imageType; - query.tiling = create.tiling; - query.usage = create.usage; - query.flags = create.flags; - VkImageFormatProperties2 props{VK_STRUCTURE_TYPE_IMAGE_FORMAT_PROPERTIES_2}; - result = image_format_properties2(info.physical, &query, &props); - limits = props.imageFormatProperties; - } else { - result = image_format_properties(info.physical, create.format, create.imageType, create.tiling, - create.usage, create.flags, &limits); - } - if (result == VK_ERROR_FORMAT_NOT_SUPPORTED) return E_INVALIDARG; - if (result == VK_ERROR_OUT_OF_HOST_MEMORY || result == VK_ERROR_OUT_OF_DEVICE_MEMORY) return E_OUTOFMEMORY; - if (result != VK_SUCCESS) return E_FAIL; - if (create.extent.width > limits.maxExtent.width || create.extent.height > limits.maxExtent.height || - create.extent.depth > limits.maxExtent.depth || create.mipLevels > limits.maxMipLevels || - create.arrayLayers > limits.maxArrayLayers || !(limits.sampleCounts & create.samples)) - return E_INVALIDARG; - return S_OK; - } - - // D3D12_OPTIONS1's wave facts, from the physical device: which subgroup operations exist and what wave sizes it - // can run. Zeros and false when the device cannot be asked, which the query then reports as unsupported. - // Read once: std::call_once makes a concurrent first caller wait until the facts are complete. - const SubgroupFacts& subgroup_facts() { - std::call_once(subgroups_once, [this] { read_subgroup_facts(); }); - return subgroups; - } - void read_subgroup_facts() { - const auto properties2 = reinterpret_cast( - info.get_instance_proc - ? info.get_instance_proc(info.instance, "vkGetPhysicalDeviceProperties2") - : nullptr); - if (!properties2 || !info.physical) return; - VkPhysicalDeviceSubgroupSizeControlProperties size_control{ - VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SUBGROUP_SIZE_CONTROL_PROPERTIES}; - VkPhysicalDeviceSubgroupProperties subgroup{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SUBGROUP_PROPERTIES, - &size_control}; - VkPhysicalDeviceProperties2 properties{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROPERTIES_2, &subgroup}; - properties2(info.physical, &properties); - // Every group the wave intrinsics map to, because D3D12 promises them all behind the one bool. - constexpr VkSubgroupFeatureFlags kD3D12WaveOps = - VK_SUBGROUP_FEATURE_BASIC_BIT | VK_SUBGROUP_FEATURE_VOTE_BIT | VK_SUBGROUP_FEATURE_BALLOT_BIT | - VK_SUBGROUP_FEATURE_SHUFFLE_BIT | VK_SUBGROUP_FEATURE_ARITHMETIC_BIT; - subgroups.wave_ops = (subgroup.supportedOperations & kD3D12WaveOps) == kD3D12WaveOps; - subgroups.lane_min = size_control.minSubgroupSize ? size_control.minSubgroupSize : subgroup.subgroupSize; - subgroups.lane_max = size_control.maxSubgroupSize ? size_control.maxSubgroupSize : subgroups.lane_min; - if (subgroups.lane_max < subgroups.lane_min) subgroups.lane_max = subgroups.lane_min; - // D3D-121: Intel's D3D12 driver answers a fixed 16..16 on its older integrated GPUs, where Vulkan reports - // the compiler's whole 8..32 choice. Measured on Xe-LP: UHD 770 (32.0.101.6129), Raptor Lake-S Mobile - // (101.7092) and Tiger Lake 0x9a78 (101.7088). Discrete Arc is not measured yet (TEST-57), so it keeps the - // Vulkan range. D3D-280: from Xe-LPG on the driver answers what Vulkan reports (Meteor Lake 0x7d55, - // 32.0.101.6127: 8..32 on both sides), so there is no fixed answer to mirror and those lines keep the - // Vulkan range too. - constexpr uint32_t kIntelVendorId = 0x8086; - constexpr UINT kIntelD3D12Lanes = 16; - const uint32_t intel_device_id = properties.properties.deviceID; - // The Xe-core integrated lines from Xe-LPG on. Device IDs are not generation-ordered (Tiger Lake's 0x9a78 - // sorts above Meteor Lake's), so the ranges are listed out, not compared as a cutoff. - const bool intel_xe_lpg_or_later = - (intel_device_id >= 0x7d40 && intel_device_id <= 0x7dc5) || // Meteor Lake, Arrow Lake - (intel_device_id >= 0x64a0 && intel_device_id <= 0x64b6); // Lunar Lake - if (properties.properties.vendorID == kIntelVendorId && - properties.properties.deviceType == VK_PHYSICAL_DEVICE_TYPE_INTEGRATED_GPU && !intel_xe_lpg_or_later && - subgroups.lane_min <= kIntelD3D12Lanes && kIntelD3D12Lanes <= subgroups.lane_max) - subgroups.lane_min = subgroups.lane_max = kIntelD3D12Lanes; - } - - // The device's mesh-shader limits (output vertices and primitives, workgroup size), for mesh PSO creation. - const VkPhysicalDeviceMeshShaderPropertiesEXT& mesh_limits() { - std::lock_guard lock(mesh_properties_mutex); - if (mesh_properties_read) return mesh_properties; - mesh_properties_read = true; - const auto properties2 = reinterpret_cast( - info.get_instance_proc ? info.get_instance_proc(info.instance, "vkGetPhysicalDeviceProperties2") : nullptr); - if (!properties2 || !info.physical || !info.mesh_shader) return mesh_properties; - VkPhysicalDeviceProperties2 properties{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROPERTIES_2, &mesh_properties}; - properties2(info.physical, &properties); - mesh_properties.pNext = nullptr; - return mesh_properties; - } - - // Integer sampled images need not support multisampling. Pick a supported count for the - // zero image in the corresponding set-0 bindings; one means that class is unavailable. - VkSampleCountFlagBits ms_fallback_samples(VkFormat format) const { - VkImageFormatProperties props{}; - constexpr VkImageUsageFlags usage = VK_IMAGE_USAGE_SAMPLED_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT; - if (image_format_properties(info.physical, format, VK_IMAGE_TYPE_2D, VK_IMAGE_TILING_OPTIMAL, - usage, 0, &props) == VK_SUCCESS) { - for (UINT count = D3D12_MAX_MULTISAMPLE_SAMPLE_COUNT; count > 1; count >>= 1) - if (props.sampleCounts & count) return VkSampleCountFlagBits(count); - } - return VK_SAMPLE_COUNT_1_BIT; - } - - // The format a texture description is created with, D24S8 and R9G9B9E5 UAV fallbacks included. - Format texture_format(const D3D12_RESOURCE_DESC& desc) const { - if (!xr_bias_compatible(desc)) return {}; - if (desc.Format == DXGI_FORMAT_A8_UNORM && - (desc.Dimension != D3D12_RESOURCE_DIMENSION_TEXTURE2D || desc.SampleDesc.Count != 1 || - (desc.Flags & (D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET | D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL | - D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS)))) - return {}; - if (desc.Format == DXGI_FORMAT_R9G9B9E5_SHAREDEXP) { - if ((desc.SampleDesc.Count != 1 && (!(desc.Flags & D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET) || - (desc.Flags & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS))) || - (desc.Flags & (D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL | D3D12_RESOURCE_FLAG_DENY_SHADER_RESOURCE))) - return {}; - if ((desc.Flags & D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET) && - (!color_attachment_usable(VK_FORMAT_E5B9G9R9_UFLOAT_PACK32) || - ((desc.Flags & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS) && - !storage_usable(VK_FORMAT_E5B9G9R9_UFLOAT_PACK32)))) - return {}; - if ((desc.Flags & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS) && r9g9b9e5_uav_emulated) { - log_once("R9G9B9E5_SHAREDEXP UAV unavailable natively, using mutable R32_UINT; format", desc.Format); - Format backed{VK_FORMAT_R32_UINT, VK_IMAGE_ASPECT_COLOR_BIT}; - backed.uint_backed = VK_FORMAT_E5B9G9R9_UFLOAT_PACK32; - return backed; - } - } - if (rgb96_refused(desc)) { - if (desc.Flags & D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET) - log_once("96-bit (R32G32B32) render targets not supported; format", desc.Format); - return {}; - } - // The host runtime refuses typed B8G8R8X8 with unordered access (its typeless family is accepted): the - // BGRA8 image could take storage writes, but D3D12 has no typed UAV for these formats. - if (alpha_unused(desc.Format) && desc.Format != DXGI_FORMAT_B8G8R8X8_TYPELESS && - (desc.Flags & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS)) { - log_once("B8G8R8X8 textures cannot allow unordered access; format", desc.Format); - return {}; - } - // A B5G5R5A1 UAV texture where VK_FORMAT_A1R5G5B5_UNORM_PACK16 has no storage support: a mutable R16_UINT image - // (Format::uint_backed). Its RTVs and SRVs view it as A1R5G5B5; shaders store the packed 16 bits. - if (desc.Format == DXGI_FORMAT_B5G5R5A1_UNORM && (desc.Flags & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS) && - !storage_usable(VK_FORMAT_A1R5G5B5_UNORM_PACK16)) { - if (!b5g5r5a1_uav_emulated || desc.SampleDesc.Count > 1 || - ((desc.Flags & D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET) && - !color_attachment_usable(VK_FORMAT_A1R5G5B5_UNORM_PACK16))) - return {}; - log_once("B5G5R5A1_UNORM UAV unavailable natively, using mutable R16_UINT; format", desc.Format); - Format backed{VK_FORMAT_R16_UINT, VK_IMAGE_ASPECT_COLOR_BIT}; - backed.uint_backed = VK_FORMAT_A1R5G5B5_UNORM_PACK16; - return backed; - } - // An 8-bit sRGB UAV texture where the sRGB format has no storage support: the host runtime makes it (RTX 4090 - // and WARP; a retail title sizes a 2048x2048 R8G8B8A8_UNORM_SRGB render target with unordered access), but no - // typed UAV is sRGB in D3D12, so shaders write the raw bytes. A mutable image of the UNORM format of the same - // channel order (Format::uint_backed): its storage view is UNORM, its SRVs and RTVs are sRGB, so sampling - // decodes and rendering encodes as on the host. - if ((desc.Format == DXGI_FORMAT_R8G8B8A8_UNORM_SRGB || desc.Format == DXGI_FORMAT_B8G8R8A8_UNORM_SRGB) && - (desc.Flags & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS)) { - const bool rgba = desc.Format == DXGI_FORMAT_R8G8B8A8_UNORM_SRGB; - const VkFormat srgb = rgba ? VK_FORMAT_R8G8B8A8_SRGB : VK_FORMAT_B8G8R8A8_SRGB; - if (!storage_usable(srgb)) { - if (!(rgba ? rgba8_srgb_uav_emulated : bgra8_srgb_uav_emulated) || desc.SampleDesc.Count > 1 || - ((desc.Flags & D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET) && !color_attachment_usable(srgb))) - return {}; - log_once("8-bit sRGB UAV unavailable natively, using a mutable UNORM image; format", desc.Format); - Format backed{rgba ? VK_FORMAT_R8G8B8A8_UNORM : VK_FORMAT_B8G8R8A8_UNORM, VK_IMAGE_ASPECT_COLOR_BIT}; - backed.uint_backed = srgb; - return backed; - } - } - Format format = texture_storage_format(desc.Format, desc.Flags & D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL); - if (desc.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE3D && (format.aspects & VK_IMAGE_ASPECT_DEPTH_BIT)) - return {}; - format.d24 = format.format == VK_FORMAT_D24_UNORM_S8_UINT; // native or not: clears are quantised - if (format.format == VK_FORMAT_D24_UNORM_S8_UINT && !depth_usable(format.format)) { - log_once("D24_UNORM_S8_UINT unavailable, using D32_SFLOAT_S8_UINT; format", desc.Format); - format.format = VK_FORMAT_D32_SFLOAT_S8_UINT; - format.d24_as_float = true; - } - return format; - } - - // The memory an image made from `create` needs, or false if the device can't make that image. - bool memory_requirements(const VkImageCreateInfo& create, VkMemoryRequirements& out) const { - if (FAILED(check_image_support(create))) return false; - if (image_requirements) { - VkDeviceImageMemoryRequirements query{VK_STRUCTURE_TYPE_DEVICE_IMAGE_MEMORY_REQUIREMENTS}; - query.pCreateInfo = &create; - VkMemoryRequirements2 result{VK_STRUCTURE_TYPE_MEMORY_REQUIREMENTS_2}; - image_requirements(info.device, &query, &result); - out = result.memoryRequirements; - return true; - } - auto& vk = context->vk; // without the query, a throwaway image - VkImage image = VK_NULL_HANDLE; - VkImageCreateInfo shared = create; - share(shared); - if (vk.vkCreateImage(info.device, &shared, nullptr, &image) != VK_SUCCESS) return false; - vk.vkGetImageMemoryRequirements(info.device, image, &out); - vk.vkDestroyImage(info.device, image, nullptr); - return true; - } - - // Set 0 of the translated shaders (vulkan_bindless.h, docs section 3.4) and what has been put in it. A shader - // finds a T# or S# by its bytes (the descriptor hash table), so one entry serves every heap slot that holds - // those bytes: a copied descriptor needs nothing more. An image's entries live until its texture is - // destroyed, samplers until the device is. - struct ImageEntry { - leonida::ImageDimension dimension; - std::uint32_t index; - VkImageView sampled; - VkImageView storage; // the same range without a component mapping, for the storage bindings; or null - std::uint64_t address; - }; - std::unique_ptr bindless; - std::mutex descriptor_mutex; // the set and the containers below - // vkDeviceWaitIdle calls made for the bindless set (none, unless LEONIDA_BINDLESS_IDLE_WAIT restores the old wait). - std::atomic bindless_idle_waits{0}; - bool bindless_legacy_idle = false; - std::atomic bindless_cap_logged{false}; - std::map image_entries; - std::multimap image_keys; // by the texture's address - std::vector replaced_images; // kept until their texture goes: work in flight may still use them - std::map sampler_entries; - struct CustomBorderColor { - bool is_int = false; - VkClearColorValue value{}; - bool operator==(const CustomBorderColor& o) const { - return is_int == o.is_int && std::memcmp(&value, &o.value, sizeof(value)) == 0; - } - }; - std::vector border_color_table; - - std::uint32_t register_border_color(bool is_int, const void* components) { - std::lock_guard lock(descriptor_mutex); - CustomBorderColor entry{}; - entry.is_int = is_int; - std::memcpy(&entry.value, components, sizeof(entry.value)); - for (std::size_t i = 0; i < border_color_table.size(); ++i) { - if (border_color_table[i] == entry) return std::uint32_t(i); - } - if (border_color_table.size() >= 4000) { - log_once("custom sampler border colour table is full (4000 entries); clamping index", - int(border_color_table.size())); - return 3999; - } - const std::uint32_t idx = std::uint32_t(border_color_table.size()); - border_color_table.push_back(entry); - return idx; - } - // A T# names a texture by an address of its own: above 4 GiB, which the GPU address arena for buffers (docs - // section 3.3) stays below, and 256 bytes apart (the T# keeps addresses in 256-byte units). Nothing - // dereferences it. - std::atomic next_image_address{std::uint64_t(1) << 32}; - - // 0 float, 1 unsigned integer, 2 signed integer: which of the three storage-image arrays a view belongs in. - static int numeric_class(VkFormat format) { - switch (format) { - case VK_FORMAT_R8_UINT: - case VK_FORMAT_R8G8_UINT: - case VK_FORMAT_R8G8B8A8_UINT: - case VK_FORMAT_R16_UINT: - case VK_FORMAT_R16G16_UINT: - case VK_FORMAT_R16G16B16A16_UINT: - case VK_FORMAT_R32_UINT: - case VK_FORMAT_R32G32_UINT: - case VK_FORMAT_R32G32B32A32_UINT: - case VK_FORMAT_A2B10G10R10_UINT_PACK32: return 1; - case VK_FORMAT_R8_SINT: - case VK_FORMAT_R8G8_SINT: - case VK_FORMAT_R8G8B8A8_SINT: - case VK_FORMAT_R16_SINT: - case VK_FORMAT_R16G16_SINT: - case VK_FORMAT_R16G16B16A16_SINT: - case VK_FORMAT_R32_SINT: - case VK_FORMAT_R32G32_SINT: - case VK_FORMAT_R32G32B32A32_SINT: return 2; - default: return 0; - } - } - - void release(const ImageEntry& entry) { // descriptor_mutex held - const std::uint64_t slot_handle = - (static_cast(entry.dimension) << 32) | static_cast(entry.index); - context->defer_destroy(leonida::DeferredDeletionQueue::Kind::bindless_slot, slot_handle); - context->defer_destroy(leonida::DeferredDeletionQueue::Kind::image_view, entry.sampled); - if (entry.storage) context->defer_destroy(leonida::DeferredDeletionQueue::Kind::image_view, entry.storage); - } - - // Gives the T# `words` a view in set 0 and an entry in the hash table, unless it has them. `storage`: shaders - // write through it too (an unordered-access view), so it also goes into the storage arrays, which are - // shorter. False when set 0 cannot show the image; the descriptor then finds the fallback at index 0. - bool bind_image(const leonida::gfx10::ImageWords& words, const leonida::gfx10::Image& image, VkImage vk_image, - VkFormat image_format, VkImageAspectFlags aspects, bool storage, - bool allow_channel_cast = false, VkFormat uint_backed = VK_FORMAT_UNDEFINED) { - namespace g = leonida::gfx10; - std::lock_guard lock(descriptor_mutex); - if (!bindless) return false; - const auto existing = image_entries.find(words); - if (existing != image_entries.end() && (existing->second.storage || !storage)) return true; - - leonida::ImageDimension dimension; - switch (image.type) { - case g::ImageType::image_2d: dimension = leonida::ImageDimension::dim_2d; break; - case g::ImageType::image_2d_array: - case g::ImageType::cube: dimension = leonida::ImageDimension::dim_2d_array; break; - case g::ImageType::image_3d: dimension = leonida::ImageDimension::dim_3d; break; - case g::ImageType::image_1d: dimension = leonida::ImageDimension::dim_1d; break; - case g::ImageType::image_2d_msaa: dimension = leonida::ImageDimension::dim_2d_ms; break; - case g::ImageType::image_2d_msaa_array: dimension = leonida::ImageDimension::dim_2d_ms_array; break; - default: - log_once("set 0 has no array for this image type:", int(image.type)); - return false; - } - const bool depth_or_stencil = (aspects & (VK_IMAGE_ASPECT_DEPTH_BIT | VK_IMAGE_ASPECT_STENCIL_BIT)) != 0; - if (storage && depth_or_stencil) { - log_once("storage view not supported for depth-stencil image format:", int(image_format)); - return false; - } - // A T# of 8_UINT on a depth-stencil image is a view of its stencil plane (image_descriptor, D3D-75). Vulkan - // views it in the image's own format with the stencil aspect, and returns the value in R, as a T# whose - // format is 8_UINT reads it from X. - const bool stencil = (aspects & VK_IMAGE_ASPECT_STENCIL_BIT) && image.format == g::stencil_format; - const VkFormat logical_format = uint_backed ? uint_backed : image_format; - VkFormat view_format = - stencil ? image_format : g::vulkan_view_format(logical_format, image.format, allow_channel_cast); - VkFormat channels_format = view_format; // whose channels the T#'s swizzle selects from - if (view_format == VK_FORMAT_UNDEFINED) { // a 96-bit texture's T# names RGB32; its image is RGBA32 - view_format = rgb96_view_format(image_format, image.format); - channels_format = rgb96_named_format(view_format); - } - if (view_format == VK_FORMAT_UNDEFINED || - (depth_or_stencil && !g::is_depth_stencil_format(view_format))) { - log_once("no Vulkan view format for the GFX10 format of a view:", int(image.format)); - return false; - } - const unsigned sampled_class = g::multisampled(image.type) ? numeric_class(view_format) : 0; - if (g::multisampled(image.type) && !bindless->supports_ms_class(sampled_class)) { - log_once("set 0 has no multisample binding for this numeric class:", int(sampled_class)); - return false; - } - auto& vk = context->vk; - VkImageViewCreateInfo view_info{VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO}; - view_info.image = vk_image; - view_info.viewType = g::vulkan_view_type(image.type); - view_info.format = view_format; - VkImageViewUsageCreateInfo sampled_usage{VK_STRUCTURE_TYPE_IMAGE_VIEW_USAGE_CREATE_INFO}; - if (uint_backed) { - sampled_usage.usage = VK_IMAGE_USAGE_SAMPLED_BIT; - view_info.pNext = &sampled_usage; - } - auto swizzle = image.swizzle; - VkImageViewMinLodCreateInfoEXT clamp{VK_STRUCTURE_TYPE_IMAGE_VIEW_MIN_LOD_CREATE_INFO_EXT}; - const bool supports_lod_clamp = image.type == g::ImageType::image_1d || image.type == g::ImageType::image_2d || - image.type == g::ImageType::image_2d_array || image.type == g::ImageType::cube || - image.type == g::ImageType::image_3d; - if (!storage && supports_lod_clamp && (aspects & VK_IMAGE_ASPECT_COLOR_BIT)) { - // Use the clamp in the T# itself: views with identical keys must sample identically. - clamp.minLod = g::image_min_lod(words); - if (clamp.minLod > float(image.first_mip + image.mip_count - 1)) { - // The accessible mip set is empty. Keep the dimensions and constant/missing channels. - for (auto& channel : swizzle) - if (channel != g::select_one) channel = g::select_zero; - } else if (clamp.minLod > float(image.first_mip)) { - if (!info.image_view_min_lod) { - log_once("SRV requires VK_EXT_image_view_min_lod; first mip", int(image.first_mip)); - return false; - } - clamp.pNext = view_info.pNext; - view_info.pNext = &clamp; - } - } - view_info.components = g::vulkan_swizzle(swizzle, channels_format); - // The cast: MSVC's enums are ints, and it rejects int to VkImageAspectFlags in braces as narrowing. - view_info.subresourceRange = { - VkImageAspectFlags(stencil ? VK_IMAGE_ASPECT_STENCIL_BIT - : (aspects & VK_IMAGE_ASPECT_DEPTH_BIT) ? VK_IMAGE_ASPECT_DEPTH_BIT - : VK_IMAGE_ASPECT_COLOR_BIT), - image.first_mip, image.mip_count, image.first_layer, image.layer_count}; - ImageEntry entry{dimension, 0, VK_NULL_HANDLE, VK_NULL_HANDLE, image.address}; - if (vk.vkCreateImageView(info.device, &view_info, nullptr, &entry.sampled) != VK_SUCCESS) return false; - leonida::StorageViews views{}; - if (storage) { - VkImageViewCreateInfo storage_info = view_info; - storage_info.components = {}; - VkImageViewUsageCreateInfo storage_usage{VK_STRUCTURE_TYPE_IMAGE_VIEW_USAGE_CREATE_INFO}; - const VkFormat storage_format = uint_backed ? image_format : view_format; - if (uint_backed) { - storage_info.format = storage_format; - storage_usage.usage = VK_IMAGE_USAGE_STORAGE_BIT; - storage_info.pNext = &storage_usage; - } - if (vk.vkCreateImageView(info.device, &storage_info, nullptr, &entry.storage) != VK_SUCCESS) { - vk.vkDestroyImageView(info.device, entry.sampled, nullptr); - return false; - } - const int numeric = numeric_class(storage_format); - (numeric == 1 ? views.as_uint : numeric == 2 ? views.as_sint : views.as_float) = entry.storage; - if (storage_format == VK_FORMAT_R32_UINT) views.r32ui = entry.storage; - } - // Every state a shader can read or write the texture in is GENERAL (ResourceBinding::sampled_in_general). - entry.index = bindless->add_image(dimension, entry.sampled, VK_IMAGE_LAYOUT_GENERAL, views, sampled_class); - if (!entry.index) { - log_once("a bindless image array is full; dimension", int(dimension)); - vk.vkDestroyImageView(info.device, entry.sampled, nullptr); - if (entry.storage) vk.vkDestroyImageView(info.device, entry.storage, nullptr); - return false; - } - if (existing != image_entries.end()) { - replaced_images.push_back(existing->second); // the read-only entry of the same bytes - existing->second = entry; - } else { - image_entries.emplace(words, entry); - image_keys.emplace(image.address, words); - } - bindless->insert_key(words, entry.index); - return true; - } - - // The texture at `address` is gone: its views leave set 0 and its T#s the hash table. - void forget_image(std::uint64_t address) { - std::lock_guard lock(descriptor_mutex); - if (!bindless) return; - const auto [first, last] = image_keys.equal_range(address); - for (auto it = first; it != last; ++it) { - const auto entry = image_entries.find(it->second); - bindless->erase_key(it->second); - release(entry->second); - image_entries.erase(entry); - } - image_keys.erase(first, last); - std::erase_if(replaced_images, [&](const ImageEntry& entry) { - if (entry.address != address) return false; - release(entry); - return true; - }); - } - - // Gives the S# `words` a sampler in set 0 and an entry in the hash table, unless it has them. - bool bind_sampler(const leonida::gfx10::SamplerWords& words) { - namespace g = leonida::gfx10; - std::lock_guard lock(descriptor_mutex); - if (!bindless) return false; - const leonida::DescriptorKey key = leonida::make_ssharp_key(words.data()); - if (sampler_entries.count(key)) return true; - const g::Sampler sampler = g::decode(words); - VkSamplerCreateInfo sampler_info = g::vulkan_sampler(sampler, max_sampler_lod_bias); - // What vulkan_sampler leaves to its caller, and features this device may not have enabled. - if (sampler_info.anisotropyEnable && !info.sampler_anisotropy) { - log_once("anisotropic sampler without samplerAnisotropy; anisotropy", int(sampler.max_anisotropy)); - sampler_info.anisotropyEnable = VK_FALSE; - } - for (VkSamplerAddressMode* mode : - {&sampler_info.addressModeU, &sampler_info.addressModeV, &sampler_info.addressModeW}) { - if (*mode != VK_SAMPLER_ADDRESS_MODE_MIRROR_CLAMP_TO_EDGE || info.sampler_mirror_clamp_to_edge) continue; - log_once("mirror-once sampler without samplerMirrorClampToEdge; clamped instead, mode", int(*mode)); - *mode = VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE; - } - VkSamplerReductionModeCreateInfo reduction{VK_STRUCTURE_TYPE_SAMPLER_REDUCTION_MODE_CREATE_INFO}; - if (sampler.filter_mode != g::FilterMode::blend) { - if (info.sampler_filter_minmax && !sampler_info.compareEnable) { - reduction.reductionMode = g::vulkan_reduction_mode(sampler.filter_mode); - reduction.pNext = sampler_info.pNext; - sampler_info.pNext = &reduction; - } else { - log_once("minimum/maximum filter sampler without samplerFilterMinmax; blended instead, mode", - int(sampler.filter_mode)); - } - } - VkSamplerCustomBorderColorCreateInfoEXT custom_border{ - VK_STRUCTURE_TYPE_SAMPLER_CUSTOM_BORDER_COLOR_CREATE_INFO_EXT}; - if (sampler.border_color == g::BorderColor::table) { - const bool is_int = sampler.border_color_index < border_color_table.size() && - border_color_table[sampler.border_color_index].is_int; - if (info.custom_border_color && info.custom_border_color_without_format && - sampler.border_color_index < border_color_table.size()) { - const auto& entry = border_color_table[sampler.border_color_index]; - custom_border.customBorderColor = entry.value; - custom_border.format = VK_FORMAT_UNDEFINED; - sampler_info.borderColor = - entry.is_int ? VK_BORDER_COLOR_INT_CUSTOM_EXT : VK_BORDER_COLOR_FLOAT_CUSTOM_EXT; - custom_border.pNext = sampler_info.pNext; - sampler_info.pNext = &custom_border; - } else { - sampler_info.borderColor = - is_int ? VK_BORDER_COLOR_INT_TRANSPARENT_BLACK : VK_BORDER_COLOR_FLOAT_TRANSPARENT_BLACK; - log_once("custom sampler border colours without VK_EXT_custom_border_color; transparent black instead, index", - int(sampler.border_color_index)); - } - } - VkSampler vk_sampler = VK_NULL_HANDLE; - if (!context->vk.vkCreateSampler || - context->vk.vkCreateSampler(info.device, &sampler_info, nullptr, &vk_sampler) != VK_SUCCESS) - return false; - const std::uint32_t index = bindless->add_sampler(vk_sampler); - if (!index) { - log_once("the bindless sampler array is full; samplers", int(sampler_entries.size())); - context->vk.vkDestroySampler(info.device, vk_sampler, nullptr); - return false; - } - sampler_entries.emplace(key, vk_sampler); - bindless->insert_key(key, index); - return true; - } - - // An optimal-tiling image of this format can take VK_IMAGE_USAGE_HOST_TRANSFER_BIT_EXT. - bool host_transfer_format(VkFormat format) const { - if (!copy_memory_to_image || !format_properties2) return false; - VkFormatProperties3 properties3{VK_STRUCTURE_TYPE_FORMAT_PROPERTIES_3}; - VkFormatProperties2 properties{VK_STRUCTURE_TYPE_FORMAT_PROPERTIES_2, &properties3}; - format_properties2(info.physical, format, &properties); - return properties3.optimalTilingFeatures & VK_FORMAT_FEATURE_2_HOST_IMAGE_TRANSFER_BIT_EXT; - } - - // A memory type with `required`, preferring one that also has `preferred`, in a heap large enough for the - // allocation (leonida::memory_type_order). `chosen`, when given, receives the property flags of the type the - // memory came from. - VkDeviceMemory allocate(const VkMemoryRequirements& requirements, VkMemoryPropertyFlags required, - VkMemoryPropertyFlags preferred, VkMemoryPropertyFlags* chosen = nullptr, - bool device_address = false, std::uint32_t* chosen_type = nullptr) const { - VkMemoryAllocateFlagsInfo flags_info{VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_FLAGS_INFO}; - flags_info.flags = VK_MEMORY_ALLOCATE_DEVICE_ADDRESS_BIT; - for (const std::uint32_t i : - leonida::memory_type_order(memory, requirements.memoryTypeBits, required, preferred, requirements.size)) { - VkMemoryAllocateInfo allocate{VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO}; - if (device_address) allocate.pNext = &flags_info; - allocate.allocationSize = requirements.size; - allocate.memoryTypeIndex = i; - VkDeviceMemory out = VK_NULL_HANDLE; - if (context->vk.vkAllocateMemory(info.device, &allocate, nullptr, &out) == VK_SUCCESS) { - if (chosen) *chosen = memory.memoryTypes[i].propertyFlags; - if (chosen_type) *chosen_type = i; - if (leonida::spilled_to_host(required, preferred, memory.memoryTypes[i].propertyFlags)) - std::call_once(spill_logged, [&] { - const std::uint32_t heap = memory.memoryTypes[i].heapIndex; - RT_LOG_WARN("d3d12: a %llu-byte allocation did not fit in device-local memory and went " - "to memory type %u (heap %u, %llu MiB); later ones are not logged\n", - static_cast(requirements.size), i, heap, - static_cast(memory.memoryHeaps[heap].size >> 20)); - }); - return out; - } - } - return VK_NULL_HANDLE; - } -}; - -// The Vulkan format for a texture this layer can create, with the D24 fallback; VK_FORMAT_UNDEFINED, after a log -// line, when it cannot. Committed and placed textures share it so both refuse the same formats for the same reason. -Format texture_format(const DeviceState& device, const D3D12_RESOURCE_DESC& desc) { - Format format = vulkan_format(desc.Format, desc.Flags & D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL); - if (format.format == VK_FORMAT_D24_UNORM_S8_UINT && !device.depth_usable(format.format)) { - log_once("D24_UNORM_S8_UINT unavailable, using D32_SFLOAT_S8_UINT; format", desc.Format); - format.format = VK_FORMAT_D32_SFLOAT_S8_UINT; - } - if (format.format == VK_FORMAT_UNDEFINED) log_once("texture format not supported yet:", desc.Format); - return format; -} - -// The castable-format list a committed or placed texture was created with, mapped to Vulkan (D3D-85's committed -// path, D3D-90's placed one). Each format must map and be the same texel size as the resource's: the host PC -// runtime refuses other sizes, and a size-mismatched VkImageFormatListCreateInfo is a Vulkan validation error -// (VUID-VkImageCreateInfo-pNext-06722). A nonzero count with a null list is no list. E_INVALIDARG on a bad format. -HRESULT castable_view_formats(const Format& format, UINT32 count, const DXGI_FORMAT* castable, - std::vector& out) { - if (!count || !castable) return S_OK; - const bool depth = (format.aspects & (VK_IMAGE_ASPECT_DEPTH_BIT | VK_IMAGE_ASPECT_STENCIL_BIT)) != 0; - const leonida::BlockFormat own = leonida::block_format(format.format, format.aspects); - for (UINT32 i = 0; i < count; ++i) { - const Format cast = vulkan_format(castable[i], depth); - if (cast.format == VK_FORMAT_UNDEFINED) { - log_once("castable format not supported yet:", castable[i]); - return E_INVALIDARG; - } - const leonida::BlockFormat block = leonida::block_format(cast.format, cast.aspects); - if (own.bytes && block.bytes && (block.bytes != own.bytes || block.block != own.block)) { - log_once("castable format is a different texel size than the resource:", castable[i]); - return E_INVALIDARG; - } - if (std::find(out.begin(), out.end(), cast.format) == out.end()) out.push_back(cast.format); - } - return S_OK; -} - -// Argument checks the host PC runtime makes (without the debug layer) before it creates anything, so the layer -// returns the same HRESULTs. Each rule was measured against the host runtime by d3d12_vulkan_device_test -// (compare_invalid_arguments, D3D-49); the texture size, mip, sample-count and alignment rules are in -// GetResourceAllocationInfo's allocation(), which CreateCommittedResource also applies. - -// The typeless format a DXGI format can be cast within, or the format itself when it has no such family. -DXGI_FORMAT format_family(DXGI_FORMAT format) { - const int f = int(format); - const auto in = [f](int first, int last) { return f >= first && f <= last; }; - if (in(1, 4)) return DXGI_FORMAT_R32G32B32A32_TYPELESS; - if (in(5, 8)) return DXGI_FORMAT_R32G32B32_TYPELESS; - if (in(9, 14)) return DXGI_FORMAT_R16G16B16A16_TYPELESS; - if (in(15, 18)) return DXGI_FORMAT_R32G32_TYPELESS; - if (in(19, 22)) return DXGI_FORMAT_R32G8X24_TYPELESS; - if (in(23, 25)) return DXGI_FORMAT_R10G10B10A2_TYPELESS; - if (in(27, 32)) return DXGI_FORMAT_R8G8B8A8_TYPELESS; - if (in(33, 38)) return DXGI_FORMAT_R16G16_TYPELESS; - if (in(39, 43)) return DXGI_FORMAT_R32_TYPELESS; - if (in(44, 47)) return DXGI_FORMAT_R24G8_TYPELESS; - if (in(48, 52)) return DXGI_FORMAT_R8G8_TYPELESS; - if (in(53, 59)) return DXGI_FORMAT_R16_TYPELESS; - if (in(60, 64)) return DXGI_FORMAT_R8_TYPELESS; - if (in(70, 72)) return DXGI_FORMAT_BC1_TYPELESS; - if (in(73, 75)) return DXGI_FORMAT_BC2_TYPELESS; - if (in(76, 78)) return DXGI_FORMAT_BC3_TYPELESS; - if (in(79, 81)) return DXGI_FORMAT_BC4_TYPELESS; - if (in(82, 84)) return DXGI_FORMAT_BC5_TYPELESS; - if (f == 87 || in(90, 91)) return DXGI_FORMAT_B8G8R8A8_TYPELESS; - if (f == 88 || in(92, 93)) return DXGI_FORMAT_B8G8R8X8_TYPELESS; - if (in(94, 96)) return DXGI_FORMAT_BC6H_TYPELESS; - if (in(97, 99)) return DXGI_FORMAT_BC7_TYPELESS; - return format; -} - -// ALLOW_DEPTH_STENCIL: the host accepts every format of a family with a depth member (R32_FLOAT and R16_FLOAT -// included) and nothing else. -bool depth_stencil_family(DXGI_FORMAT format) { - const DXGI_FORMAT family = format_family(format); - return family == DXGI_FORMAT_R32_TYPELESS || family == DXGI_FORMAT_R16_TYPELESS || - family == DXGI_FORMAT_R24G8_TYPELESS || family == DXGI_FORMAT_R32G8X24_TYPELESS; -} - -// ALLOW_RENDER_TARGET: the host refuses the families below and accepts the rest, D32_FLOAT, D16_UNORM, -// R9G9B9E5_SHAREDEXP and NV12 among them. R32G32B32 is the driver's answer (refused by both AMD drivers measured, -// accepted by WARP); it is refused here, since Vulkan drivers rarely render to it. -bool render_target_family(DXGI_FORMAT format) { - switch (format_family(format)) { - case DXGI_FORMAT_R32G32B32_TYPELESS: - case DXGI_FORMAT_R32G8X24_TYPELESS: - case DXGI_FORMAT_R24G8_TYPELESS: - case DXGI_FORMAT_R1_UNORM: - case DXGI_FORMAT_R8G8_B8G8_UNORM: - case DXGI_FORMAT_G8R8_G8B8_UNORM: - case DXGI_FORMAT_BC1_TYPELESS: - case DXGI_FORMAT_BC2_TYPELESS: - case DXGI_FORMAT_BC3_TYPELESS: - case DXGI_FORMAT_BC4_TYPELESS: - case DXGI_FORMAT_BC5_TYPELESS: - case DXGI_FORMAT_BC6H_TYPELESS: - case DXGI_FORMAT_BC7_TYPELESS: - return false; - default: - return true; - } -} - -// Why the host would refuse these heap properties, or null if it accepts them. `uma` is the device's -// D3D12_FEATURE_ARCHITECTURE answer: a UMA adapter has no MEMORY_POOL_L1, and the host refuses a custom heap in it -// (measured on a Radeon 780M, AMD 32.0.13030.13001, and on WARP: E_INVALIDARG from CreateHeap and -// CreateCommittedResource for every CPU page property). -const char* heap_properties_refusal(const D3D12_HEAP_PROPERTIES& heap, bool uma) { - if (heap.Type < D3D12_HEAP_TYPE_DEFAULT || heap.Type > D3D12_HEAP_TYPE_GPU_UPLOAD) return "heap type"; - // CheckFeatureSupport reports OPTIONS16.GPUUploadHeapSupported FALSE, and a host runtime without GPU upload heaps - // (Resizable BAR off) refuses the type. - if (heap.Type == D3D12_HEAP_TYPE_GPU_UPLOAD) return "GPU upload heap, which OPTIONS16 reports unsupported"; - const bool custom = heap.Type == D3D12_HEAP_TYPE_CUSTOM; - const bool page_given = heap.CPUPageProperty != D3D12_CPU_PAGE_PROPERTY_UNKNOWN; - const bool pool_given = heap.MemoryPoolPreference != D3D12_MEMORY_POOL_UNKNOWN; - if (custom ? !(page_given && pool_given) : (page_given || pool_given)) - return "CPU page property or memory pool (given only, and both, on custom heaps)"; - if (heap.CreationNodeMask > 1 || heap.VisibleNodeMask > 1) return "node mask (one node)"; - if (uma && custom && heap.MemoryPoolPreference == D3D12_MEMORY_POOL_L1) return "MEMORY_POOL_L1 on a UMA adapter"; - return nullptr; -} - -// Why the host would refuse this CreateHeap description, or null if these checks pass (D3D-238). A probe on an -// RX 5700 and WARP refuses an alignment other than 0, 64 KiB and 4 MiB, the heap properties above (a type of 0, a -// custom heap without a CPU page property), and a heap that denies buffers and both kinds of texture. ALLOW_DISPLAY -// (CreateCommittedResource on a default heap only, per the D3D12_HEAP_FLAGS documentation) is refused too, confirmed -// on an RTX 4070 SUPER and a UHD 770 host by @CowBoYdu76. Those hosts accept HARDWARE_PROTECTED, so it is not refused. -const char* heap_desc_refusal(const D3D12_HEAP_DESC& desc, bool uma) { - if (!desc.SizeInBytes) return "zero size"; - if (desc.Alignment && desc.Alignment != D3D12_DEFAULT_RESOURCE_PLACEMENT_ALIGNMENT && - desc.Alignment != D3D12_DEFAULT_MSAA_RESOURCE_PLACEMENT_ALIGNMENT) - return "alignment (0, 64 KiB or 4 MiB)"; - if (const char* why = heap_properties_refusal(desc.Properties, uma)) return why; - constexpr UINT deny_all = D3D12_HEAP_FLAG_DENY_BUFFERS | D3D12_HEAP_FLAG_DENY_RT_DS_TEXTURES | - D3D12_HEAP_FLAG_DENY_NON_RT_DS_TEXTURES; - if ((UINT(desc.Flags) & deny_all) == deny_all) return "heap flags denying every resource kind"; - if (UINT(desc.Flags) & D3D12_HEAP_FLAG_ALLOW_DISPLAY) return "ALLOW_DISPLAY (committed resources only)"; - return nullptr; -} - -// Why the host would refuse this committed resource, or null if these checks pass. The flag and format tables were -// measured on an RX 9070 XT, an integrated Radeon and WARP, which agree on all of them. Cross-adapter resources -// (valid there only as a row-major texture on a SHARED | SHARED_CROSS_ADAPTER heap) are refused: this layer has no -// cross-adapter sharing. -// The initial state a committed, placed or reserved resource may start in, as the host runtime answers it -// (d3d12_vulkan_device_test's compare_placed_reserved and its "committed: ... state" cases, RTX 3060 / 610.88). -// A buffer takes any bits, unknown ones too, except RAYTRACING_ACCELERATION_STRUCTURE without UAV access, or at all -// on a device without acceleration structures (the host refuses it where OPTIONS5 reports no ray tracing: an -// integrated Radeon, measured by @aguedou-34 on #2462; here, a device with neither the KHR acceleration structures -// nor the XDXR builds). A texture -// takes exactly GENERIC_READ, or one write state alone (RENDER_TARGET, UNORDERED_ACCESS and DEPTH_WRITE need the -// matching resource flag), or any mix of read states (DEPTH_READ needs ALLOW_DEPTH_STENCIL; the shader-resource -// states are refused with DENY_SHADER_RESOURCE). The buffer-only bits (vertex/constant, index, indirect, stream -// output, acceleration structure) and undefined bits are refused on a texture, also inside a mix. -const char* initial_state_refusal(bool buffer, UINT flags, D3D12_RESOURCE_STATES state, - bool acceleration_structures) { - const UINT s = UINT(state); - if (buffer) { - if ((s & D3D12_RESOURCE_STATE_RAYTRACING_ACCELERATION_STRUCTURE) && !acceleration_structures) - return "acceleration-structure state on a device without acceleration structures"; - if ((s & D3D12_RESOURCE_STATE_RAYTRACING_ACCELERATION_STRUCTURE) && - !(flags & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS)) - return "acceleration-structure state on a buffer without UAV access"; - return nullptr; - } - if (s == D3D12_RESOURCE_STATE_GENERIC_READ) return nullptr; - constexpr UINT writes = D3D12_RESOURCE_STATE_RENDER_TARGET | D3D12_RESOURCE_STATE_UNORDERED_ACCESS | - D3D12_RESOURCE_STATE_DEPTH_WRITE | D3D12_RESOURCE_STATE_COPY_DEST | - D3D12_RESOURCE_STATE_RESOLVE_DEST | D3D12_RESOURCE_STATE_VIDEO_DECODE_WRITE | - D3D12_RESOURCE_STATE_VIDEO_PROCESS_WRITE | D3D12_RESOURCE_STATE_VIDEO_ENCODE_WRITE; - constexpr UINT shader_reads = - D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE | D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE; - constexpr UINT reads = D3D12_RESOURCE_STATE_DEPTH_READ | shader_reads | D3D12_RESOURCE_STATE_COPY_SOURCE | - D3D12_RESOURCE_STATE_RESOLVE_SOURCE | D3D12_RESOURCE_STATE_SHADING_RATE_SOURCE | - D3D12_RESOURCE_STATE_VIDEO_DECODE_READ | D3D12_RESOURCE_STATE_VIDEO_PROCESS_READ | - D3D12_RESOURCE_STATE_VIDEO_ENCODE_READ; - if (s & ~(writes | reads)) return "initial state of a texture (buffer-only or undefined bits)"; - if (s & writes) { - if (s & (s - 1)) return "initial state of a texture (a write state with another state)"; - if (s == D3D12_RESOURCE_STATE_RENDER_TARGET && !(flags & D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET)) - return "RENDER_TARGET state without ALLOW_RENDER_TARGET"; - if (s == D3D12_RESOURCE_STATE_UNORDERED_ACCESS && !(flags & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS)) - return "UNORDERED_ACCESS state without ALLOW_UNORDERED_ACCESS"; - if (s == D3D12_RESOURCE_STATE_DEPTH_WRITE && !(flags & D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL)) - return "DEPTH_WRITE state without ALLOW_DEPTH_STENCIL"; - return nullptr; - } - if ((s & D3D12_RESOURCE_STATE_DEPTH_READ) && !(flags & D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL)) - return "DEPTH_READ state without ALLOW_DEPTH_STENCIL"; - if ((s & shader_reads) && (flags & D3D12_RESOURCE_FLAG_DENY_SHADER_RESOURCE)) - return "shader-resource state with DENY_SHADER_RESOURCE"; - return nullptr; -} - -const char* committed_resource_refusal(const D3D12_HEAP_PROPERTIES& heap, D3D12_HEAP_FLAGS heap_flags, - const D3D12_RESOURCE_DESC& desc, D3D12_RESOURCE_STATES state, - const D3D12_CLEAR_VALUE* clear, bool acceleration_structures, bool uma) { - if (const char* why = heap_properties_refusal(heap, uma)) return why; - // The DENY flags of a committed resource's heap are the runtime's to choose; most other bits are refused too. - constexpr UINT committed_heap_flags = D3D12_HEAP_FLAG_SHARED | D3D12_HEAP_FLAG_ALLOW_DISPLAY | - D3D12_HEAP_FLAG_HARDWARE_PROTECTED | D3D12_HEAP_FLAG_CREATE_NOT_RESIDENT | - D3D12_HEAP_FLAG_CREATE_NOT_ZEROED | D3D12_HEAP_FLAG_ALLOW_SHADER_ATOMICS; - if (UINT(heap_flags) & ~committed_heap_flags) return "heap flags of a committed resource"; - - const bool buffer = desc.Dimension == D3D12_RESOURCE_DIMENSION_BUFFER; - // 0x400 is not in this SDK's d3d12.h (10.0.26100), but the host accepts it on buffers and textures; 0x200 and - // 0x800 it refuses. RAYTRACING_ACCELERATION_STRUCTURE is accepted on a texture too. - constexpr UINT buffer_flags = D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET | D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS | - D3D12_RESOURCE_FLAG_DENY_SHADER_RESOURCE | - D3D12_RESOURCE_FLAG_RAYTRACING_ACCELERATION_STRUCTURE | 0x400; - constexpr UINT texture_flags = - buffer_flags | D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL | D3D12_RESOURCE_FLAG_ALLOW_SIMULTANEOUS_ACCESS; - const UINT flags = UINT(desc.Flags); - if (flags & ~(buffer ? buffer_flags : texture_flags)) return "resource flags"; - const bool rt = flags & D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET; - const bool ds = flags & D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL; - const bool uav = flags & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS; - // ALLOW_SHADER_ATOMICS is for a resource shaders can write: RTX 4070 Laptop (621.24) and WARP refuse it without - // ALLOW_UNORDERED_ACCESS, on buffers and textures alike. It changes nothing on one adapter; GetHeapProperties keeps it. - if ((UINT(heap_flags) & D3D12_HEAP_FLAG_ALLOW_SHADER_ATOMICS) && !uav) - return "ALLOW_SHADER_ATOMICS without ALLOW_UNORDERED_ACCESS"; - // Upload heaps start in (a part of) GENERIC_READ, readback heaps in COPY_DEST; COMMON on both; no UAVs. - if (heap.Type == D3D12_HEAP_TYPE_UPLOAD && (uav || (UINT(state) & ~UINT(D3D12_RESOURCE_STATE_GENERIC_READ)))) - return "upload heap state or UAV"; - if (heap.Type == D3D12_HEAP_TYPE_READBACK && (uav || (UINT(state) & ~UINT(D3D12_RESOURCE_STATE_COPY_DEST)))) - return "readback heap state or UAV"; - - if (const char* why = initial_state_refusal(buffer, flags, state, acceleration_structures)) return why; - - if (buffer) { - if (!desc.Width || desc.Height != 1 || desc.DepthOrArraySize != 1 || desc.MipLevels != 1 || - desc.Format != DXGI_FORMAT_UNKNOWN || desc.SampleDesc.Count != 1 || desc.SampleDesc.Quality != 0 || - desc.Layout != D3D12_TEXTURE_LAYOUT_ROW_MAJOR) - return "buffer description"; - if (desc.Alignment && desc.Alignment != D3D12_DEFAULT_RESOURCE_PLACEMENT_ALIGNMENT) return "buffer alignment"; - if (clear) return "clear value on a buffer"; - if (heap_flags & D3D12_HEAP_FLAG_ALLOW_DISPLAY) return "display heap for a buffer"; - return nullptr; - } - if (desc.Dimension < D3D12_RESOURCE_DIMENSION_TEXTURE1D || desc.Dimension > D3D12_RESOURCE_DIMENSION_TEXTURE3D) - return "resource dimension"; - if ((rt && ds) || (ds && uav) || ((flags & D3D12_RESOURCE_FLAG_DENY_SHADER_RESOURCE) && !ds)) - return "resource flag combination"; - if (ds && !depth_stencil_family(desc.Format)) return "depth-stencil format"; - if (rt && !render_target_family(desc.Format)) return "render-target format"; - const UINT samples = desc.SampleDesc.Count; - if (samples > 1 && !rt && !ds) return "multisampled texture that is not a render target or depth buffer"; - // Every adapter measured reports one quality level; the two standard patterns are accepted too. They are spelled - // with the DXGI names: D3D12_STANDARD/CENTER_MULTISAMPLE_PATTERN, the same values, are only in d3d12.h from - // DirectX-Headers 1.613 on, and older Windows SDK 10.0.26100 headers lack them. - if (samples > 1 && desc.SampleDesc.Quality && - desc.SampleDesc.Quality != DXGI_STANDARD_MULTISAMPLE_QUALITY_PATTERN && - desc.SampleDesc.Quality != DXGI_CENTER_MULTISAMPLE_QUALITY_PATTERN) - return "sample quality"; - // A clear value is only for render targets and depth buffers, in the resource's format family. - if (clear && (!(rt || ds) || clear->Format == DXGI_FORMAT_UNKNOWN || - format_family(clear->Format) != format_family(desc.Format))) - return "clear value"; - return nullptr; -} - -// Why the host refuses this enhanced-barrier initial layout for `desc`, or null when valid (measured on Windows D3D12). -const char* barrier_layout_refusal(const D3D12_RESOURCE_DESC& desc, D3D12_BARRIER_LAYOUT layout) { - if (desc.Dimension == D3D12_RESOURCE_DIMENSION_BUFFER) - return layout == D3D12_BARRIER_LAYOUT_UNDEFINED ? nullptr : "buffer barrier layout"; - const UINT flags = UINT(desc.Flags); - switch (layout) { - case D3D12_BARRIER_LAYOUT_RENDER_TARGET: - return (flags & D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET) ? nullptr : "RENDER_TARGET barrier layout"; - case D3D12_BARRIER_LAYOUT_UNORDERED_ACCESS: - case D3D12_BARRIER_LAYOUT_DIRECT_QUEUE_UNORDERED_ACCESS: - case D3D12_BARRIER_LAYOUT_COMPUTE_QUEUE_UNORDERED_ACCESS: - return (flags & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS) ? nullptr : "UNORDERED_ACCESS barrier layout"; - case D3D12_BARRIER_LAYOUT_DEPTH_STENCIL_WRITE: - case D3D12_BARRIER_LAYOUT_DEPTH_STENCIL_READ: - return (flags & D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL) ? nullptr : "DEPTH_STENCIL barrier layout"; - case D3D12_BARRIER_LAYOUT_SHADER_RESOURCE: - case D3D12_BARRIER_LAYOUT_DIRECT_QUEUE_SHADER_RESOURCE: - case D3D12_BARRIER_LAYOUT_COMPUTE_QUEUE_SHADER_RESOURCE: - return (flags & D3D12_RESOURCE_FLAG_DENY_SHADER_RESOURCE) ? "SHADER_RESOURCE barrier layout" : nullptr; - default: - return nullptr; - } -} - -// Console Xbox D3D12 CreateDescriptorHeap (device slot 14) passes the PC description followed by the heap address -// and size, as measured in the retail boot (issue #313 comment 7107265058): a 16-byte PC D3D12_DESCRIPTOR_HEAP_DESC, -// then address at +0x10 and size at +0x18. The title asserts GetCPUDescriptorHandleForHeapStart() == address. -// Backing this range with title memory / section 3.3 aliasing is tracked separately; this path only satisfies the -// observed ABI contract and must not be inferred from normal PC 16-byte CreateDescriptorHeap calls. -struct ConsoleDescriptorHeapDesc { - D3D12_DESCRIPTOR_HEAP_DESC desc{}; - std::uint64_t address = 0; - std::uint64_t size = 0; -}; - -class DescriptorHeap final - : public Child { -public: - // {4a7d2c90-5e1b-4f63-8c0a-91d3b6e2f417} - static constexpr GUID kTag{0x4a7d2c90, 0x5e1b, 0x4f63, {0x8c, 0x0a, 0x91, 0xd3, 0xb6, 0xe2, 0xf4, 0x17}}; - - // A shader-visible heap lives in the GPU address arena: its CPU handles point at the arena's host mapping and - // its GPU handle is the console VA, so the bytes the game or Create*View writes are what shaders load. Other - // heaps (RTV, DSV, non-visible staging heaps) stay in host memory. - // A shader-visible heap that the arena cannot hold is not created (ok() is false, E_OUTOFMEMORY), as a - // default-heap buffer is not: in host memory its GPU handle would be 0, and every table would read VA 0. - DescriptorHeap(DeviceState& device, const D3D12_DESCRIPTOR_HEAP_DESC& desc, std::uint64_t console_address = 0, - std::uint64_t console_size = 0) - : device_(device), desc_(desc), console_address_(console_address), console_size_(console_size), - console_addressed_(console_address != 0) { - const VkDeviceSize bytes = VkDeviceSize(desc_.NumDescriptors) * kDescriptorSize; - if (console_addressed_) { - // The retail boot checks GetCPUDescriptorHandleForHeapStart() == address. Report the requested title VA - // now; backing this range with title memory / §3.3 aliasing is tracked separately. - log_once("descriptor heap uses console address/size (not backed by title memory)", int(desc_.Type)); - cpu_ = reinterpret_cast(static_cast(console_address_)); - in_arena_ = false; - return; - } - if ((desc_.Flags & D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE) && device.arena.mapped) { - if (!device.arena_allocate(bytes, 256, arena_offset_, DeviceState::arena_descriptor_heap)) { - log_once("GPU address arena full (raise LEONIDA_ARENA_MB); shader-visible heap size in KiB:", - int(std::min(bytes / 1024, INT_MAX))); - return; - } - in_arena_ = true; - cpu_ = device.arena.mapped + arena_offset_; - std::memset(cpu_, 0, std::size_t(bytes)); - } else { - storage_.reset(new std::byte[std::size_t(bytes)]()); - cpu_ = reinterpret_cast(storage_.get()); - } - } - - ~DescriptorHeap() override { - if (in_arena_) device_.arena_release(arena_offset_, VkDeviceSize(desc_.NumDescriptors) * kDescriptorSize, - DeviceState::arena_descriptor_heap); - } - - bool ok() const { return cpu_ != nullptr; } - - // A node mask of 0 reads back as the one node of a single adapter, as on the PC runtime (d3d12_node_mask_test). - D3D12_DESCRIPTOR_HEAP_DESC STDMETHODCALLTYPE GetDesc() override { - D3D12_DESCRIPTOR_HEAP_DESC desc = desc_; - if (!desc.NodeMask) desc.NodeMask = 1; - return desc; - } - D3D12_CPU_DESCRIPTOR_HANDLE STDMETHODCALLTYPE GetCPUDescriptorHandleForHeapStart() override { - return {reinterpret_cast(cpu_)}; - } - D3D12_GPU_DESCRIPTOR_HANDLE STDMETHODCALLTYPE GetGPUDescriptorHandleForHeapStart() override { - if (!(desc_.Flags & D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE)) return {0}; - if (console_addressed_) return {static_cast(console_address_)}; - if (!in_arena_) log_once("shader-visible heap without a GPU address arena; flags", int(desc_.Flags)); - return {in_arena_ ? UINT64(arena_offset_) : 0}; - } - - const D3D12_DESCRIPTOR_HEAP_DESC& raw_desc() const { return desc_; } - D3D12_GPU_VIRTUAL_ADDRESS gpu_base() const { - if (console_addressed_) return static_cast(console_address_); - return in_arena_ ? UINT64(arena_offset_) : 0; - } - -private: - DeviceState& device_; - D3D12_DESCRIPTOR_HEAP_DESC desc_; - std::unique_ptr storage_; - std::uint8_t* cpu_ = nullptr; - VkDeviceSize arena_offset_ = 0; - bool in_arena_ = false; - std::uint64_t console_address_ = 0; - std::uint64_t console_size_ = 0; - bool console_addressed_ = false; -}; - -class Resource final - : public Child { -public: - // {9b3e5f12-7c48-4d0e-a6b1-2f8d4c7e9a35} - static constexpr GUID kTag{0x9b3e5f12, 0x7c48, 0x4d0e, {0xa6, 0xb1, 0x2f, 0x8d, 0x4c, 0x7e, 0x9a, 0x35}}; - - Resource(DeviceState& device, const D3D12_RESOURCE_DESC& desc, const D3D12_HEAP_PROPERTIES& heap, - D3D12_HEAP_FLAGS heap_flags) - : device_(device), desc_(desc), heap_(heap), heap_flags_(heap_flags) {} - - // A placed resource lives inside a heap's arena range: the heap owns the range, so only the console VA is kept - // here and nothing goes back to the arena when this object dies. - Resource(DeviceState& device, const D3D12_RESOURCE_DESC& desc, const D3D12_HEAP_PROPERTIES& heap, - D3D12_HEAP_FLAGS heap_flags, VkDeviceSize placed_va) - : device_(device), desc_(desc), heap_(heap), heap_flags_(heap_flags), placed_(true), va_(placed_va) {} - - ~Resource() override { - if (accel_) { - device_.context->unregister_acceleration_structure(gpu_va_); - if (buffer_va_ && buffer_va_ != gpu_va_) device_.context->unregister_acceleration_structure(buffer_va_); - device_.context->defer_destroy(leonida::DeferredDeletionQueue::Kind::acceleration_structure, accel_); - } - if (image_address_) device_.forget_image(image_address_); - device_.context->remove_resource(id()); - if (host_import_) { - // VK_EXT_external_memory_host needs the caller's pages to stay valid for the imported memory's whole - // lifetime, and a title may free them right after releasing the resource. So the memory is not left to - // the deferred queue (freed after the *next* submission retires): wait for what was submitted, then - // free it now (found in review). - device_.context->wait_retire_ticket(device_.context->submitted_retire_ticket()); - auto& vk = device_.context->vk; - if (buffer_) vk.vkDestroyBuffer(device_.info.device, buffer_, nullptr); - if (memory_) vk.vkFreeMemory(device_.info.device, memory_, nullptr); - buffer_ = VK_NULL_HANDLE; - memory_ = VK_NULL_HANDLE; - } - if (in_arena_) device_.arena_release(arena_offset_, desc_.Width, DeviceState::arena_buffer); - if (image_ && !sparse_image_) - device_.context->defer_destroy(leonida::DeferredDeletionQueue::Kind::image, image_); - if (buffer_) device_.context->defer_destroy(leonida::DeferredDeletionQueue::Kind::buffer, buffer_); - if (memory_) device_.context->defer_destroy(leonida::DeferredDeletionQueue::Kind::device_memory, memory_); - } - - leonida::ResourceId id() const { return resource_id(this); } - VkImage image() const { return image_; } - bool sparse_image() const { return sparse_image_; } - VkBuffer buffer() const { return buffer_; } - const D3D12_RESOURCE_DESC& desc() const { return desc_; } - VkFormat format() const { return format_; } // of the image - bool has_view_format_list() const { return !view_formats_.empty(); } - bool allows_view_format(VkFormat format) const { - return view_formats_.empty() || format == format_ || - std::find(view_formats_.begin(), view_formats_.end(), format) != view_formats_.end(); - } - // The castable-format list in DXGI formats, which the Vulkan list can't tell apart where two families share a - // VkFormat: B8G8R8X8 and B8G8R8A8 are both BGRA8 images. - void keep_castable_formats(UINT32 count, const DXGI_FORMAT* formats) { - if (count && formats) castable_formats_.assign(formats, formats + count); - } - bool lists_castable_format(DXGI_FORMAT format) const { - return std::find(castable_formats_.begin(), castable_formats_.end(), format) != castable_formats_.end(); - } - bool has_castable_formats() const { return !castable_formats_.empty(); } - VkFormat uint_backed() const { return uint_backed_; } // Format::uint_backed - VkImageAspectFlags aspects() const { return aspects_; } - bool rgb96() const { return rgb96_; } // a 96-bit texture in an RGBA32 image - std::uint64_t image_address() const { return image_address_; } // what a T# names the texture by - VkMemoryPropertyFlags memory_flags() const { return memory_flags_; } // of the memory type behind it - const DeviceState& device_state() const { return device_; } - - // Default-heap buffers are ranges of the GPU address arena: console VA = offset, zeroed through the arena's host - // mapping. Upload and readback buffers keep their own host memory; with buffer device addresses their console - // VA is their device address minus heap_base, so a shader's heap_base + VA still lands on them (section 3.3). - HRESULT create_buffer(D3D12_RESOURCE_STATES initial_state = D3D12_RESOURCE_STATE_COMMON) { - auto& vk = device_.context->vk; - // A buffer has at least one byte, and its size must survive alignment to 64 KiB without wrapping. - if (!desc_.Width || desc_.Width > ~UINT64(0) - D3D12_DEFAULT_RESOURCE_PLACEMENT_ALIGNMENT) return E_INVALIDARG; - const bool host = cpu_visible(); - leonida::ResourceBinding binding{}; // a buffer: no image - binding.size = desc_.Width; - if (!host && device_.arena.mapped) { - if (!device_.arena_allocate(desc_.Width, D3D12_DEFAULT_RESOURCE_PLACEMENT_ALIGNMENT, arena_offset_, - DeviceState::arena_buffer)) { - log_once("GPU address arena full (raise LEONIDA_ARENA_MB); buffer size in KiB:", - int(desc_.Width / 1024)); - return E_OUTOFMEMORY; - } - in_arena_ = true; - std::memset(device_.arena.mapped + arena_offset_, 0, std::size_t(desc_.Width)); - va_ = arena_offset_; - binding.va = va_; - binding.buffer = device_.arena.buffer; - binding.buffer_offset = arena_offset_; - // No host pointer: this is DEFAULT-heap arena memory the GPU may write, so its mapped bytes can be - // stale. host_at() must not treat it as a CPU-written instance pointer list. - // A default-heap AS resource is one of these ranges: a GENERIC acceleration structure covers it where - // it sits. It is named by its real device address (heap base + offset), as instance descriptors and - // BuildRaytracingAccelerationStructure hand that address to the driver, not a console VA. - if (device_.info.ray_tracing && - initial_state == D3D12_RESOURCE_STATE_RAYTRACING_ACCELERATION_STRUCTURE && - vk.vkCreateAccelerationStructureKHR) { - VkAccelerationStructureCreateInfoKHR asci{VK_STRUCTURE_TYPE_ACCELERATION_STRUCTURE_CREATE_INFO_KHR}; - asci.buffer = device_.arena.buffer; - asci.offset = arena_offset_; - asci.size = desc_.Width; - asci.type = VK_ACCELERATION_STRUCTURE_TYPE_GENERIC_KHR; - if (vk.vkCreateAccelerationStructureKHR(device_.info.device, &asci, nullptr, &accel_) == VK_SUCCESS) { - gpu_va_ = device_.arena.address + va_; - device_.context->register_acceleration_structure(gpu_va_, accel_); - } - } - device_.context->add_resource(id(), binding); - return S_OK; - } - const bool addressable = device_.arena.buffer != VK_NULL_HANDLE; - const bool need_bda = device_.info.buffer_device_address || device_.info.ray_tracing; - VkBufferCreateInfo info{VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO}; - info.size = desc_.Width; - info.usage = VK_BUFFER_USAGE_TRANSFER_SRC_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT | - VK_BUFFER_USAGE_VERTEX_BUFFER_BIT | VK_BUFFER_USAGE_INDEX_BUFFER_BIT | - VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT | VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | - VK_BUFFER_USAGE_INDIRECT_BUFFER_BIT; - if (device_.info.conditional_rendering) info.usage |= VK_BUFFER_USAGE_CONDITIONAL_RENDERING_BIT_EXT; - if (addressable || need_bda) info.usage |= VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT; - if (device_.info.ray_tracing) { - info.usage |= VK_BUFFER_USAGE_ACCELERATION_STRUCTURE_STORAGE_BIT_KHR | - VK_BUFFER_USAGE_ACCELERATION_STRUCTURE_BUILD_INPUT_READ_ONLY_BIT_KHR; - } - device_.share(info); - if (vk.vkCreateBuffer(device_.info.device, &info, nullptr, &buffer_) != VK_SUCCESS) return E_OUTOFMEMORY; - VkMemoryRequirements requirements{}; - vk.vkGetBufferMemoryRequirements(device_.info.device, buffer_, &requirements); - // Readback buffers prefer cached memory, which the CPU reads quickly. Upload buffers prefer VRAM the CPU - // writes through Resizable BAR, where the GPU reads them quickly (D3D-96); without it, system memory. - VkMemoryPropertyFlags host_preferred = 0; - if (heap_.Type == D3D12_HEAP_TYPE_READBACK) host_preferred = VK_MEMORY_PROPERTY_HOST_CACHED_BIT; - if (heap_.Type == D3D12_HEAP_TYPE_UPLOAD && device_.upload_in_vram) - host_preferred = VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT; - memory_ = host ? device_.allocate(requirements, - VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT, - host_preferred, &memory_flags_, addressable || need_bda) - : device_.allocate(requirements, 0, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, &memory_flags_, - addressable || need_bda); - if (!memory_ || vk.vkBindBufferMemory(device_.info.device, buffer_, memory_, 0) != VK_SUCCESS) - return E_OUTOFMEMORY; - if (addressable) { - VkBufferDeviceAddressInfo address{VK_STRUCTURE_TYPE_BUFFER_DEVICE_ADDRESS_INFO}; - address.buffer = buffer_; - va_ = vk.vkGetBufferDeviceAddress(device_.info.device, &address) - device_.arena.address; - device_.log_va(heap_.Type == D3D12_HEAP_TYPE_READBACK ? "readback buffer" : "upload buffer", va_, - desc_.Width); - } - if (host) { - if (vk.vkMapMemory(device_.info.device, memory_, 0, VK_WHOLE_SIZE, 0, &mapped_) != VK_SUCCESS) - return E_OUTOFMEMORY; - std::memset(mapped_, 0, std::size_t(desc_.Width)); // committed resources start zeroed - } - if (need_bda && vk.vkGetBufferDeviceAddress) { - VkBufferDeviceAddressInfo bda{VK_STRUCTURE_TYPE_BUFFER_DEVICE_ADDRESS_INFO}; - bda.buffer = buffer_; - buffer_va_ = vk.vkGetBufferDeviceAddress(device_.info.device, &bda); - gpu_va_ = buffer_va_; - } - if (device_.info.ray_tracing && initial_state == D3D12_RESOURCE_STATE_RAYTRACING_ACCELERATION_STRUCTURE && - vk.vkCreateAccelerationStructureKHR && vk.vkGetAccelerationStructureDeviceAddressKHR) { - VkAccelerationStructureCreateInfoKHR asci{VK_STRUCTURE_TYPE_ACCELERATION_STRUCTURE_CREATE_INFO_KHR}; - asci.buffer = buffer_; - asci.offset = 0; - asci.size = desc_.Width; - asci.type = VK_ACCELERATION_STRUCTURE_TYPE_GENERIC_KHR; - if (vk.vkCreateAccelerationStructureKHR(device_.info.device, &asci, nullptr, &accel_) == VK_SUCCESS) { - VkAccelerationStructureDeviceAddressInfoKHR dai{ - VK_STRUCTURE_TYPE_ACCELERATION_STRUCTURE_DEVICE_ADDRESS_INFO_KHR}; - dai.accelerationStructure = accel_; - const std::uint64_t as_va = vk.vkGetAccelerationStructureDeviceAddressKHR(device_.info.device, &dai); - if (as_va) gpu_va_ = as_va; - device_.context->register_acceleration_structure(gpu_va_, accel_); - if (buffer_va_ && buffer_va_ != gpu_va_) - device_.context->register_acceleration_structure(buffer_va_, accel_); - } - } - binding.buffer = buffer_; - binding.size = desc_.Width; - binding.host = cpu_writable() ? static_cast(mapped_) : nullptr; - binding.host_readable = (heap_.Type == D3D12_HEAP_TYPE_READBACK || - (heap_.Type == D3D12_HEAP_TYPE_CUSTOM && - heap_.CPUPageProperty == D3D12_CPU_PAGE_PROPERTY_WRITE_BACK)); - binding.va = va_; - device_.context->add_resource(id(), binding); - // Committed resources start zeroed unless the heap says otherwise; the host cannot reach device-local memory, - // so the next submission fills it (D3D-71). - if (!host && !(heap_flags_ & D3D12_HEAP_FLAG_CREATE_NOT_ZEROED)) - device_.context->zero_on_next_submit(id(), buffer_); - return S_OK; - } - - // A buffer on the caller's own pages (Xbox device slot 133, create_buffer_at_host_address): `address` is imported - // with VK_EXT_external_memory_host and the buffer bound to it at offset 0, so the CPU's writes there are the GPU's - // reads with no copy. Its console VA is `address` itself, the VA the title chose, so vertex, index and immediate - // writes the title names by that VA find this buffer (VulkanContext::buffer_at). A shader that adds heap_base to - // that VA does not reach it: the title's own V#s into these pages need the single address space of - // docs/d3d12_vulkan.md section 3.3, which this does not decide. The pages stay the caller's: nothing is zeroed. - HRESULT create_host_buffer(void* address) { - auto& vk = device_.context->vk; - const VkDeviceSize alignment = device_.info.host_pointer_alignment; - if (!device_.get_host_pointer_properties || !alignment) return E_NOTIMPL; - const auto start = reinterpret_cast(address); - if (!address || !desc_.Width || desc_.Width > UINT64_MAX - 2 * alignment) return E_INVALIDARG; - // The import starts at the page that holds `address`, and the buffer is bound at the offset inside it: the - // title places small buffers inside a page too (a 16-byte UAV at a 64-byte-aligned address on an RTX 5090, - // found in review), which an import of `address` itself would refuse. - const std::uintptr_t base = start & ~static_cast(alignment - 1); - void* const base_address = reinterpret_cast(base); - const VkDeviceSize offset = start - base; - const VkDeviceSize bytes = (offset + desc_.Width + alignment - 1) & ~(alignment - 1); - // An imported buffer's VA is its host address, and it joins the same BufferVaIndex as default-heap buffers, - // whose VAs are offsets in [0, arena size). A host range that reaches into that window (low host addresses, - // as under Wine) would shadow arena buffers in the index's nearest-start lookup, so it takes the fallback - // (found in review). - if (start < device_.arena.size) { - log_once("a title-placed buffer's host address overlaps the arena's VA window; not imported, size", - int(desc_.Width > INT_MAX ? INT_MAX : desc_.Width)); - return E_NOTIMPL; - } - // The whole imported range must be committed, possibly across several allocations (the retail buffer spans - // three mapped windows); a page not committed yet (xmem commits on first touch) or a write-combined one (on - // an RTX 5090 such an import succeeded but GPU reads returned wrong bytes, found in review) is not imported, - // and the ordinary-buffer fallback answers instead. - bool importable = true; - for (VkDeviceSize at = 0; at < bytes;) { - MEMORY_BASIC_INFORMATION region{}; - if (!VirtualQuery(static_cast(base_address) + at, ®ion, sizeof(region)) || - region.State != MEM_COMMIT || (region.Protect & (PAGE_WRITECOMBINE | PAGE_NOCACHE))) { - importable = false; - break; - } - const auto region_end = reinterpret_cast(region.BaseAddress) + region.RegionSize; - at = region_end - base; - } - if (!importable) return E_NOTIMPL; - const bool need_bda = device_.info.buffer_device_address || device_.arena.buffer != VK_NULL_HANDLE; - VkExternalMemoryBufferCreateInfo external{VK_STRUCTURE_TYPE_EXTERNAL_MEMORY_BUFFER_CREATE_INFO}; - external.handleTypes = VK_EXTERNAL_MEMORY_HANDLE_TYPE_HOST_ALLOCATION_BIT_EXT; - VkBufferCreateInfo info{VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO, &external}; - info.size = desc_.Width; - info.usage = VK_BUFFER_USAGE_TRANSFER_SRC_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT | - VK_BUFFER_USAGE_VERTEX_BUFFER_BIT | VK_BUFFER_USAGE_INDEX_BUFFER_BIT | - VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT | VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | - VK_BUFFER_USAGE_INDIRECT_BUFFER_BIT; - if (device_.info.conditional_rendering) info.usage |= VK_BUFFER_USAGE_CONDITIONAL_RENDERING_BIT_EXT; - if (need_bda) info.usage |= VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT; - device_.share(info); - if (vk.vkCreateBuffer(device_.info.device, &info, nullptr, &buffer_) != VK_SUCCESS) return E_OUTOFMEMORY; - VkMemoryRequirements requirements{}; - vk.vkGetBufferMemoryRequirements(device_.info.device, buffer_, &requirements); - VkMemoryHostPointerPropertiesEXT host{VK_STRUCTURE_TYPE_MEMORY_HOST_POINTER_PROPERTIES_EXT}; - if (device_.get_host_pointer_properties(device_.info.device, - VK_EXTERNAL_MEMORY_HANDLE_TYPE_HOST_ALLOCATION_BIT_EXT, base_address, - &host) != VK_SUCCESS) - return E_NOTIMPL; - const std::uint32_t types = host.memoryTypeBits & requirements.memoryTypeBits; - // An offset off the buffer's own alignment cannot be bound: the fallback answers. - if (!types || (offset % requirements.alignment) || bytes < offset + requirements.size) return E_NOTIMPL; - VkImportMemoryHostPointerInfoEXT import{VK_STRUCTURE_TYPE_IMPORT_MEMORY_HOST_POINTER_INFO_EXT}; - import.handleType = VK_EXTERNAL_MEMORY_HANDLE_TYPE_HOST_ALLOCATION_BIT_EXT; - import.pHostPointer = base_address; - VkMemoryAllocateFlagsInfo flags{VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_FLAGS_INFO, &import}; - flags.flags = VK_MEMORY_ALLOCATE_DEVICE_ADDRESS_BIT; - // Host-visible and coherent first, as the caller's pages are; then any type both the import and the - // buffer take. - for (const VkMemoryPropertyFlags want : - {VkMemoryPropertyFlags(VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT), - VkMemoryPropertyFlags(0)}) { - for (std::uint32_t i = 0; i < device_.memory.memoryTypeCount && !memory_; ++i) { - if (!(types & (1u << i)) || (device_.memory.memoryTypes[i].propertyFlags & want) != want) continue; - VkMemoryAllocateInfo allocate{VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO, - need_bda ? static_cast(&flags) : &import}; - allocate.allocationSize = bytes; - allocate.memoryTypeIndex = i; - if (vk.vkAllocateMemory(device_.info.device, &allocate, nullptr, &memory_) == VK_SUCCESS) - memory_flags_ = device_.memory.memoryTypes[i].propertyFlags; - else - memory_ = VK_NULL_HANDLE; - } - if (memory_) break; - } - if (!memory_) return E_OUTOFMEMORY; - if (vk.vkBindBufferMemory(device_.info.device, buffer_, memory_, offset) != VK_SUCCESS) return E_OUTOFMEMORY; - mapped_ = address; - host_import_ = true; - va_ = start; - if (need_bda && vk.vkGetBufferDeviceAddress) { - VkBufferDeviceAddressInfo bda{VK_STRUCTURE_TYPE_BUFFER_DEVICE_ADDRESS_INFO}; - bda.buffer = buffer_; - buffer_va_ = vk.vkGetBufferDeviceAddress(device_.info.device, &bda); - gpu_va_ = buffer_va_; - } - device_.log_va("title-placed buffer", va_, desc_.Width); - leonida::ResourceBinding binding{}; - binding.buffer = buffer_; - binding.size = desc_.Width; - binding.host = static_cast(address); - binding.host_readable = true; - binding.va = va_; - device_.context->add_resource(id(), binding); - return S_OK; - } - - HRESULT create_sparse_buffer() { - constexpr std::uint64_t tile_bytes = leonida::tile_size_in_bytes; - if (!desc_.Width || desc_.Width > UINT64_MAX - tile_bytes || - desc_.SampleDesc.Count != 1 || desc_.SampleDesc.Quality != 0) return E_INVALIDARG; - auto& vk = device_.context->vk; - auto sparse = std::make_shared(device_.info.device, vk); - sparse->tile_count = (desc_.Width + tile_bytes - 1) / tile_bytes; - const auto info = device_.sparse_buffer_info(sparse->tile_count * tile_bytes); - if (vk.vkCreateBuffer(device_.info.device, &info, nullptr, &sparse->buffer) != VK_SUCCESS) - return E_OUTOFMEMORY; - VkMemoryRequirements requirements{}; - vk.vkGetBufferMemoryRequirements(device_.info.device, sparse->buffer, &requirements); - sparse->memory_types = requirements.memoryTypeBits; - if (tile_bytes % requirements.alignment || - !(sparse->memory_types & device_.sparse_buffer_memory_types)) return E_NOTIMPL; - VkBufferDeviceAddressInfo address{VK_STRUCTURE_TYPE_BUFFER_DEVICE_ADDRESS_INFO}; - address.buffer = sparse->buffer; - va_ = vk.vkGetBufferDeviceAddress(device_.info.device, &address) - device_.arena.address; - leonida::ResourceBinding binding{}; - binding.buffer = sparse->buffer; - binding.size = desc_.Width; - binding.va = va_; - binding.sparse_buffer = true; - device_.context->add_sparse_resource(id(), binding, std::move(sparse)); - return S_OK; - } - - HRESULT create_sparse_image() { - auto& vk = device_.context->vk; - const auto format = device_.texture_format(desc_); - TextureCreateInfo create(desc_, format, false); - create.info.flags |= VK_IMAGE_CREATE_SPARSE_BINDING_BIT | VK_IMAGE_CREATE_SPARSE_RESIDENCY_BIT | - VK_IMAGE_CREATE_SPARSE_ALIASED_BIT; - HRESULT support = device_.check_image_support(create.info); - if (FAILED(support)) return support == E_INVALIDARG ? E_NOTIMPL : support; - device_.share(create.info); - auto sparse = std::make_shared(device_.info.device, vk); - const auto result = vk.vkCreateImage(device_.info.device, &create.info, nullptr, &sparse->image); - if (result == VK_ERROR_FORMAT_NOT_SUPPORTED) return E_NOTIMPL; - if (result != VK_SUCCESS) return E_OUTOFMEMORY; - - VkMemoryRequirements requirements{}; - vk.vkGetImageMemoryRequirements(device_.info.device, sparse->image, &requirements); - if (requirements.alignment != leonida::tile_size_in_bytes || - leonida::memory_type_order(device_.memory, requirements.memoryTypeBits, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, - 0, leonida::tile_size_in_bytes).empty()) - return E_NOTIMPL; - std::uint32_t count = 0; - vk.vkGetImageSparseMemoryRequirements(device_.info.device, sparse->image, &count, nullptr); - if (count != 1) return E_NOTIMPL; // exactly one color aspect, with no separately bound metadata - VkSparseImageMemoryRequirements image_requirements{}; - vk.vkGetImageSparseMemoryRequirements(device_.info.device, sparse->image, &count, &image_requirements); - constexpr auto shape = leonida::element_tile_shape(false, 4); - const auto& properties = image_requirements.formatProperties; - const auto granularity = properties.imageGranularity; - if (properties.aspectMask != VK_IMAGE_ASPECT_COLOR_BIT || granularity.width != shape.width || - granularity.height != shape.height || granularity.depth != 1 || - !image_requirements.imageMipTailFirstLod || image_requirements.imageMipTailSize) - return E_NOTIMPL; - - sparse->image_extent = {create.info.extent.width, create.info.extent.height}; - sparse->tile_count = (1 + (sparse->image_extent.width - 1) / shape.width) * - std::uint64_t(1 + (sparse->image_extent.height - 1) / shape.height); - sparse->memory_types = requirements.memoryTypeBits; - image_ = sparse->image; - sparse_image_ = true; - format_ = format.format; - aspects_ = format.aspects; - image_address_ = device_.next_image_address.fetch_add(256); - binding_.image = image_; - binding_.format = format_; - binding_.aspects = aspects_; - binding_.width = sparse->image_extent.width; - binding_.height = sparse->image_extent.height; - // An unbound tile reads as zero. Keep the layout stable once the image can share memory with an alias. - binding_.not_zeroed = true; - binding_.simultaneous_access = true; - binding_.sampled_in_general = true; - device_.context->add_sparse_resource(id(), binding_, std::move(sparse)); - return S_OK; - } - - // A placed buffer is a range of the heap's arena memory: it has no VkBuffer of its own and its console VA is - // where it sits in the arena. The arena is host-visible, so an upload or readback place maps that same range. - HRESULT create_placed_buffer(std::shared_ptr heap_range) { - if (!device_.arena.mapped) return E_OUTOFMEMORY; - heap_range_ = std::move(heap_range); - if (cpu_visible()) mapped_ = device_.arena.mapped + va_; - std::memset(device_.arena.mapped + va_, 0, std::size_t(desc_.Width)); // a fresh place reads as zeroed - leonida::ResourceBinding binding{}; - binding.size = desc_.Width; - binding.buffer = device_.arena.buffer; - binding.buffer_offset = va_; - binding.va = va_; - binding.host = cpu_writable() ? device_.arena.mapped + va_ : nullptr; - binding.host_readable = (heap_.Type == D3D12_HEAP_TYPE_READBACK || - (heap_.Type == D3D12_HEAP_TYPE_CUSTOM && - heap_.CPUPageProperty == D3D12_CPU_PAGE_PROPERTY_WRITE_BACK)); - device_.context->add_resource(id(), binding); - return S_OK; - } - - HRESULT create_texture(const Format& format, const std::vector& castable = {}) { - auto& vk = device_.context->vk; - const bool volume = desc_.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE3D; - const UINT depth = volume ? desc_.DepthOrArraySize : 1; - const bool one_d = desc_.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE1D; - if (desc_.MipLevels == 0) desc_.MipLevels = full_mips(desc_.Width, desc_.Height, depth); - TextureCreateInfo create(desc_, format, device_.color_attachment_usable(format.format)); - VkImageCreateInfo& info = create.info; - if (!castable.empty()) { - // D3D12 always allows a view in the resource's own format, whether or not the castable list names - // it. Vulkan requires every view format to be in the image's format list, so add it when missing. - view_formats_ = castable; - if (std::find(view_formats_.begin(), view_formats_.end(), format.format) == view_formats_.end()) - view_formats_.push_back(format.format); - if (format.uint_backed) { - // An unsigned-backed UAV texture needs both its formats whatever the list names (TextureCreateInfo). - for (VkFormat pair : {format.format, format.uint_backed}) - if (std::find(view_formats_.begin(), view_formats_.end(), pair) == view_formats_.end()) - view_formats_.push_back(pair); - } - info.flags |= VK_IMAGE_CREATE_MUTABLE_FORMAT_BIT; - create.format_list.viewFormatCount = std::uint32_t(view_formats_.size()); - create.format_list.pViewFormats = view_formats_.data(); - create.format_list.pNext = info.pNext; - info.pNext = &create.format_list; - } - const std::uint32_t samples = info.samples; - // Textures the CPU reads and writes (WriteToSubresource/ReadFromSubresource) copy on the host when they can. - // (A D24 texture stored as D32 goes through the staged copy: the host copy would not convert. Nor would it - // repack a 96-bit texture's 12-byte texels.) - host_transfer_ = cpu_visible() && samples == 1 && !format.d24_as_float && !format.rgb96 && - device_.host_transfer_format(format.format); - rgb96_ = format.rgb96; - if (host_transfer_) info.usage |= VK_IMAGE_USAGE_HOST_TRANSFER_BIT_EXT; - HRESULT support = device_.check_image_support(info); - if (support == E_INVALIDARG && host_transfer_) { - host_transfer_ = false; // staging copies do not require host-transfer usage - info.usage &= ~VK_IMAGE_USAGE_HOST_TRANSFER_BIT_EXT; - support = device_.check_image_support(info); - } - if (FAILED(support)) return support; - device_.share(info); - const VkResult created = vk.vkCreateImage(device_.info.device, &info, nullptr, &image_); - if (created != VK_SUCCESS) { - if (created == VK_ERROR_OUT_OF_HOST_MEMORY || created == VK_ERROR_OUT_OF_DEVICE_MEMORY) - return E_OUTOFMEMORY; - if (!view_formats_.empty()) { - log_once("castable format list refused by Vulkan; count", int(view_formats_.size())); - return E_INVALIDARG; - } - return E_OUTOFMEMORY; - } - VkMemoryRequirements requirements{}; - vk.vkGetImageMemoryRequirements(device_.info.device, image_, &requirements); - if (host_transfer_ && !requirements.memoryTypeBits) { - // A driver can accept the host-transfer usage and then name no memory type for the image: NVIDIA 582.66 on - // a GTX 1070 Ti answers memoryTypeBits 0 with the usage and 0x82 without it. Make the image again without - // the usage, so its CPU copies take the staging path. - log_once("no memory type for a host-transfer image, using staging copies; format", int(info.format)); - vk.vkDestroyImage(device_.info.device, image_, nullptr); - image_ = VK_NULL_HANDLE; - host_transfer_ = false; - info.usage &= ~VK_IMAGE_USAGE_HOST_TRANSFER_BIT_EXT; - support = device_.check_image_support(info); - if (FAILED(support)) return support; - if (vk.vkCreateImage(device_.info.device, &info, nullptr, &image_) != VK_SUCCESS) return E_OUTOFMEMORY; - vk.vkGetImageMemoryRequirements(device_.info.device, image_, &requirements); - } - memory_ = device_.allocate(requirements, 0, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, &memory_flags_); - if (!memory_ || vk.vkBindImageMemory(device_.info.device, image_, memory_, 0) != VK_SUCCESS) - return E_OUTOFMEMORY; - - leonida::ResourceBinding binding{}; - binding.image = image_; - binding.typeless = format.typeless && format.aspects == VK_IMAGE_ASPECT_COLOR_BIT; // views name their format - binding.castable_view_formats = !view_formats_.empty(); // a castable list made the image mutable - binding.uint_backed = format.uint_backed; - binding.rgb96 = format.rgb96; - binding.depth24_as_float = format.d24_as_float; - binding.depth24 = format.d24; - binding.format = format.format; - binding.aspects = format.aspects; - binding.width = std::uint32_t(desc_.Width); - binding.height = one_d ? 1u : desc_.Height; - binding.mip_levels = desc_.MipLevels; - binding.array_layers = info.arrayLayers; - binding.depth = depth; - binding.volume = volume; - binding.line = one_d; - binding.samples = samples; - binding.color_attachment = (info.usage & VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT) != 0; - binding.sampled = (info.usage & VK_IMAGE_USAGE_SAMPLED_BIT) != 0; - binding.simultaneous_access = (desc_.Flags & D3D12_RESOURCE_FLAG_ALLOW_SIMULTANEOUS_ACCESS) != 0; - binding.not_zeroed = (heap_flags_ & D3D12_HEAP_FLAG_CREATE_NOT_ZEROED) != 0; - // With the bindless set, a view's descriptor has one layout for as long as it lives (bind_image). - binding.sampled_in_general = device_.bindless != nullptr; - format_ = format.format; - uint_backed_ = format.uint_backed; - aspects_ = format.aspects; - image_address_ = device_.next_image_address.fetch_add(256); - binding_ = binding; - if (host_transfer_) { - // Moved to GENERAL and zero-filled on the host now, so the CPU can copy into it before any command - // list has touched it (a first GPU use would otherwise zero-fill over what the CPU wrote). - if (!host_initialize()) return E_OUTOFMEMORY; - device_.context->add_resource(id(), binding, VK_IMAGE_LAYOUT_GENERAL); - return S_OK; - } - // Never used yet: the first command that touches a part zero-fills it and moves it to the layout of the - // state that command expects (vulkan_replay.h, initialize), so no submission is needed here. - device_.context->add_resource(id(), binding, VK_IMAGE_LAYOUT_UNDEFINED); - return S_OK; - } - - // D3D12 reports the placement alignment of a description that left it 0: 64 KiB, or 4 MiB for a multisampled - // texture. One the description asked for is kept. Measured on the PC runtime and WARP (d3d12_resource_desc_test). - D3D12_RESOURCE_DESC STDMETHODCALLTYPE GetDesc() override { - D3D12_RESOURCE_DESC desc = desc_; - if (!desc.Alignment) { - desc.Alignment = (desc.SampleDesc.Count > 1 && !is_tiled_layout(desc.Layout)) - ? D3D12_DEFAULT_MSAA_RESOURCE_PLACEMENT_ALIGNMENT - : D3D12_DEFAULT_RESOURCE_PLACEMENT_ALIGNMENT; - } - return desc; - } - - // Both sparse resources and the committed fallback report the reserved layout and have no heap of their own. - void make_reserved(D3D12_TEXTURE_LAYOUT layout) { - reserved_ = true; - desc_.Layout = layout; - } - bool reserved() const { return reserved_; } - // A committed resource: neither placed in a heap nor reserved. It owns its memory, like a heap does. - bool committed() const { return !placed_ && !reserved_; } - - // D3D12 answers only for committed and placed resources (E_INVALIDARG for reserved ones, measured on the PC - // runtime). - // Buffers report their console VA into the GPU address arena; an acceleration structure reports its real device - // address (instance descriptors and builds hand it to the driver). A texture the title placed at its own address - // through Xbox slot 133 reports that title address, as the console does: a title uses it as the CPU pointer it - // clears the texture through (docs/d3d12_vulkan.md 3.3). Any other texture answers 0, as on D3D12. - D3D12_GPU_VIRTUAL_ADDRESS STDMETHODCALLTYPE GetGPUVirtualAddress() override { return accel_ ? gpu_va_ : va_; } - // The title's own address for a texture Xbox slot 133 placed. The image is still the committed fallback, so its - // pixels do not alias the title's pages yet; the address is what GetGPUVirtualAddress answers (XCL PR #168's - // behavior, measured on a retail title). - void set_title_address(D3D12_GPU_VIRTUAL_ADDRESS address) { va_ = address; } - - // - // The node masks read back as the one node of a single adapter (0 becomes 1), and the heap flags as the runtime - // resolves them: the caller's, without the two creation-only bits (CREATE_NOT_RESIDENT, CREATE_NOT_ZEROED), plus - // the DENY bits of the resource classes this resource is not (buffers 0xC0, textures without render-target or - // depth use 0x44, the others 0x84). Measured on the PC runtime and WARP (d3d12_node_mask_test). - HRESULT STDMETHODCALLTYPE GetHeapProperties(D3D12_HEAP_PROPERTIES* properties, D3D12_HEAP_FLAGS* flags) override { - if (reserved_) return E_INVALIDARG; - if (properties) { - *properties = heap_; - if (!properties->CreationNodeMask) properties->CreationNodeMask = 1; - if (!properties->VisibleNodeMask) properties->VisibleNodeMask = 1; - } - if (flags) *flags = resolved_heap_flags(); - return S_OK; - } - - D3D12_HEAP_FLAGS resolved_heap_flags() const { - const UINT deny_buffers = D3D12_HEAP_FLAG_DENY_BUFFERS, deny_rt_ds = D3D12_HEAP_FLAG_DENY_RT_DS_TEXTURES, - deny_non_rt_ds = D3D12_HEAP_FLAG_DENY_NON_RT_DS_TEXTURES; - UINT deny = deny_buffers | deny_rt_ds; // a texture without render-target or depth use - if (desc_.Dimension == D3D12_RESOURCE_DIMENSION_BUFFER) - deny = deny_rt_ds | deny_non_rt_ds; - else if (desc_.Flags & (D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET | D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL)) - deny = deny_buffers | deny_non_rt_ds; - const UINT creation_only = D3D12_HEAP_FLAG_CREATE_NOT_RESIDENT | D3D12_HEAP_FLAG_CREATE_NOT_ZEROED; - // A placed resource reports its heap's flags as they are (an ALLOW_ALL heap reads back 0): the DENY bits - // are the runtime's choice only for the implicit heap of a committed resource (d3d12_heap_properties_test). - if (placed_) return D3D12_HEAP_FLAGS(UINT(heap_flags_) & ~creation_only); - return D3D12_HEAP_FLAGS((UINT(heap_flags_) & ~creation_only) | deny); - } - - // Buffers on upload and readback heaps are mapped persistently; the ranges are hints, as on D3D12, except that - // the host runtime refuses a non-empty read range that ends past the buffer. A texture in a CPU-visible heap has - // no pointer to give (its layout is the driver's), so D3D12 only lets it be mapped with a null pointer, before - // WriteToSubresource/ReadFromSubresource. - HRESULT STDMETHODCALLTYPE Map(UINT subresource, const D3D12_RANGE* read, void** data) override { - if (image_) { - VkImageSubresourceRange range{}; - return !data && cpu_visible() && subresource != leonida::all_subresources && - leonida::image_range(binding_, subresource, range) - ? S_OK - : E_INVALIDARG; - } - if (!mapped_ || subresource != 0) return E_INVALIDARG; - if (read && read->Begin < read->End && read->End > desc_.Width) return E_INVALIDARG; - if (data) *data = mapped_; - return S_OK; - } - void STDMETHODCALLTYPE Unmap(UINT, const D3D12_RANGE*) override {} - - // CPU copies into and out of a texture subresource. D3D12 completes them before returning and leaves it to - // the application to keep the GPU off the subresource meanwhile, so a blocking copy is the whole contract. - HRESULT STDMETHODCALLTYPE WriteToSubresource(UINT subresource, const D3D12_BOX* box, const void* data, - UINT row_pitch, UINT depth_pitch) override { - return cpu_copy(true, subresource, box, const_cast(data), row_pitch, depth_pitch); - } - HRESULT STDMETHODCALLTYPE ReadFromSubresource(void* data, UINT row_pitch, UINT depth_pitch, UINT subresource, - const D3D12_BOX* box) override { - return cpu_copy(false, subresource, box, data, row_pitch, depth_pitch); - } - -private: - // One subresource region in copy units: rows of texels, or of 4x4 blocks for block-compressed formats. - struct Region { - VkImageSubresourceLayers layers; - D3D12_BOX box; - leonida::BlockFormat block; - std::uint32_t rows; - std::uint64_t row_bytes; - std::uint32_t slices; - }; - - // The region a copy names, or false when D3D12 would reject it: an unknown subresource, a box whose right, - // bottom or back edge lies past the mip's, or one that cuts a compressed block anywhere but at the mip edge. - // An empty or inverted box that passes those checks is no copy at all: `rows` and `slices` are 0, and the host - // runtime answers S_OK without touching a byte (d3d12_subresource_copy_test, RTX 3060 / 610.88). - bool region(UINT subresource, const D3D12_BOX* box, Region& out) const { - VkImageSubresourceRange range{}; - if (subresource == leonida::all_subresources || !leonida::image_range(binding_, subresource, range)) return false; - if (binding_.samples > 1) return false; // D3D12 has no CPU copies of multisampled textures; Vulkan neither - const std::uint32_t mip = range.baseMipLevel; - const std::uint32_t width = std::max(1u, binding_.width >> mip), height = std::max(1u, binding_.height >> mip); - const std::uint32_t depth = binding_.volume ? std::max(1u, binding_.depth >> mip) : 1; - out.box = box ? *box : D3D12_BOX{0, 0, 0, width, height, depth}; - const D3D12_BOX& b = out.box; - if (b.right > width || b.bottom > height || b.back > depth) return false; - out.block = leonida::copy_block_format(binding_, range.aspectMask); - if (!out.block.bytes) return false; - const std::uint32_t k = out.block.block; - if (b.left % k || b.top % k || (b.right % k && b.right != width) || (b.bottom % k && b.bottom != height)) - return false; - out.layers = {range.aspectMask, mip, range.baseArrayLayer, 1}; - if (b.left >= b.right || b.top >= b.bottom || b.front >= b.back) { - out.rows = 0; - out.row_bytes = 0; - out.slices = 0; - return true; - } - out.rows = (b.bottom - b.top + k - 1) / k; - out.row_bytes = std::uint64_t((b.right - b.left + k - 1) / k) * out.block.bytes; - out.slices = b.back - b.front; - return true; - } - - HRESULT cpu_copy(bool write, UINT subresource, const D3D12_BOX* box, void* data, UINT row_pitch, - UINT depth_pitch) { - if (!image_ || !data) return E_INVALIDARG; - Region r{}; - if (!region(subresource, box, r)) return E_INVALIDARG; - if (!r.rows || !r.slices) return S_OK; // an empty box: nothing to copy - // The pitches are not checked, as on the host runtime: rows or slices that overlap (a pitch smaller than a - // row, or 0) are copied in order, row by row and slice by slice, so on a read the last one wins. - if (!cpu_visible()) - log_once(write ? "WriteToSubresource on a texture outside a CPU-visible heap; heap type" - : "ReadFromSubresource on a texture outside a CPU-visible heap; heap type", - heap_.Type); - auto* bytes = static_cast(data); - // Between the application's pitches and `pitch`, the one a copy reads or writes. - const auto pack = [&](std::byte* to, std::uint64_t pitch) { - for (std::uint32_t z = 0; z < r.slices; ++z) - for (std::uint32_t y = 0; y < r.rows; ++y) - std::memcpy(to + (std::uint64_t(z) * r.rows + y) * pitch, - bytes + std::uint64_t(z) * depth_pitch + std::uint64_t(y) * row_pitch, r.row_bytes); - }; - const auto unpack = [&](const std::byte* from, std::uint64_t pitch) { - for (std::uint32_t z = 0; z < r.slices; ++z) - for (std::uint32_t y = 0; y < r.rows; ++y) - std::memcpy(bytes + std::uint64_t(z) * depth_pitch + std::uint64_t(y) * row_pitch, - from + (std::uint64_t(z) * r.rows + y) * pitch, r.row_bytes); - }; - // On the host only while the subresource is in GENERAL: it is from creation, and stays there until a - // barrier moves it (D3D12's COMMON is GENERAL). Any other layout goes through the staging copy, which - // moves it as a CopyTextureRegion would. - if (host_transfer_ && device_.context->layout(id(), subresource) == VK_IMAGE_LAYOUT_GENERAL) { - std::vector packed(r.row_bytes * r.rows * r.slices); - if (write) pack(packed.data(), r.row_bytes); - if (!host_copy(write, r, packed.data())) return E_FAIL; - if (!write) unpack(packed.data(), r.row_bytes); - return S_OK; - } - return staged_copy(write, subresource, r, pack, unpack); - } - - // Tightly packed `memory` to or from the region, with VK_EXT_host_image_copy. - bool host_copy(bool write, const Region& r, void* memory) { - const VkOffset3D offset{std::int32_t(r.box.left), std::int32_t(r.box.top), std::int32_t(r.box.front)}; - const VkExtent3D extent{r.box.right - r.box.left, r.box.bottom - r.box.top, r.slices}; - const VkDevice dev = device_.info.device; - if (write) { - VkMemoryToImageCopyEXT copy{VK_STRUCTURE_TYPE_MEMORY_TO_IMAGE_COPY_EXT}; - copy.pHostPointer = memory; - copy.imageSubresource = r.layers; - copy.imageOffset = offset; - copy.imageExtent = extent; - VkCopyMemoryToImageInfoEXT info{VK_STRUCTURE_TYPE_COPY_MEMORY_TO_IMAGE_INFO_EXT}; - info.dstImage = image_; - info.dstImageLayout = VK_IMAGE_LAYOUT_GENERAL; - info.regionCount = 1; - info.pRegions = © - return device_.copy_memory_to_image(dev, &info) == VK_SUCCESS; - } - VkImageToMemoryCopyEXT copy{VK_STRUCTURE_TYPE_IMAGE_TO_MEMORY_COPY_EXT}; - copy.pHostPointer = memory; - copy.imageSubresource = r.layers; - copy.imageOffset = offset; - copy.imageExtent = extent; - VkCopyImageToMemoryInfoEXT info{VK_STRUCTURE_TYPE_COPY_IMAGE_TO_MEMORY_INFO_EXT}; - info.srcImage = image_; - info.srcImageLayout = VK_IMAGE_LAYOUT_GENERAL; - info.regionCount = 1; - info.pRegions = © - return device_.copy_image_to_memory(dev, &info) == VK_SUCCESS; - } - - // Every subresource of a new host-transfer image to GENERAL, zero-filled unless the heap said not to. - bool host_initialize() { - const VkDevice dev = device_.info.device; - VkHostImageLayoutTransitionInfoEXT transition{VK_STRUCTURE_TYPE_HOST_IMAGE_LAYOUT_TRANSITION_INFO_EXT}; - transition.image = image_; - transition.oldLayout = VK_IMAGE_LAYOUT_UNDEFINED; - transition.newLayout = VK_IMAGE_LAYOUT_GENERAL; - transition.subresourceRange = {binding_.aspects, 0, binding_.mip_levels, 0, - binding_.volume ? VK_REMAINING_ARRAY_LAYERS : binding_.array_layers}; - if (device_.transition_image_layout(dev, 1, &transition) != VK_SUCCESS) return false; - if (binding_.not_zeroed) return true; - const std::uint32_t planes = leonida::two_planes(binding_) ? 2 : 1; - const std::uint32_t per_plane = binding_.mip_levels * binding_.array_layers; - std::vector zero; - for (UINT subresource = 0; subresource < planes * per_plane; ++subresource) { - Region r{}; - if (!region(subresource, nullptr, r)) return false; - zero.assign(r.row_bytes * r.rows * r.slices, std::byte{0}); - if (!host_copy(true, r, zero.data())) return false; - } - return true; - } - - // A host-visible buffer at D3D12's footprint pitch, copied to or from the subresource by a CopyTextureRegion - // replayed on the device's queue, then waited for. The replay handles the layout (and a first use's zero fill) - // exactly as it does for the application's own copies. - template - HRESULT staged_copy(bool write, UINT subresource, const Region& r, const Pack& pack, const Unpack& unpack) { - auto& vk = device_.context->vk; - const VkDevice dev = device_.info.device; - const std::uint64_t pitch = (r.row_bytes + D3D12_TEXTURE_DATA_PITCH_ALIGNMENT - 1) / - D3D12_TEXTURE_DATA_PITCH_ALIGNMENT * D3D12_TEXTURE_DATA_PITCH_ALIGNMENT; - leonida::ResourceBinding staging{}; - staging.size = pitch * r.rows * r.slices; - VkBufferCreateInfo info{VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO}; - info.size = staging.size; - info.usage = VK_BUFFER_USAGE_TRANSFER_SRC_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT | VK_BUFFER_USAGE_STORAGE_BUFFER_BIT; // storage: D24 depth conversion - device_.share(info); - if (vk.vkCreateBuffer(dev, &info, nullptr, &staging.buffer) != VK_SUCCESS) return E_OUTOFMEMORY; - VkDeviceMemory memory = VK_NULL_HANDLE; - void* mapped = nullptr; - const auto release = [&](HRESULT hr) { - if (memory) vk.vkFreeMemory(dev, memory, nullptr); // unmaps it - vk.vkDestroyBuffer(dev, staging.buffer, nullptr); - return hr; - }; - VkMemoryRequirements requirements{}; - vk.vkGetBufferMemoryRequirements(dev, staging.buffer, &requirements); - memory = device_.allocate(requirements, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT, - write ? 0 : VK_MEMORY_PROPERTY_HOST_CACHED_BIT); - if (!memory || vk.vkBindBufferMemory(dev, staging.buffer, memory, 0) != VK_SUCCESS || - vk.vkMapMemory(dev, memory, 0, VK_WHOLE_SIZE, 0, &mapped) != VK_SUCCESS) - return release(E_OUTOFMEMORY); - if (write) pack(static_cast(mapped), pitch); - - // The staging buffer is a resource only for the length of this call; its ID is its binding's address, - // which no COM resource can share. - const auto staging_id = reinterpret_cast(&staging); - const std::uint32_t k = r.block.block; - const leonida::CopyLocation texture{id(), false, subresource, 0, 0, 0, 0, 0}; - const leonida::CopyLocation placed{staging_id, true, 0, 0, std::uint32_t(r.row_bytes / r.block.bytes) * k, - r.rows * k, r.slices, std::uint32_t(pitch)}; - leonida::CopyTexture copy{}; - if (write) { - copy = {texture, r.box.left, r.box.top, r.box.front, placed, false, {}}; - } else { - copy = {placed, 0, 0, 0, texture, true, - {r.box.left, r.box.top, r.box.front, r.box.right, r.box.bottom, r.box.back}}; - } - leonida::CommandList list; - if (!list.copy_texture(copy) || !list.close()) return release(E_INVALIDARG); - device_.context->add_resource(staging_id, staging); - leonida::ReplayResult result = leonida::ReplayResult::unsupported; - { - std::lock_guard lock(device_.staging_mutex); - if (!device_.staging_queue) { - device_.staging_queue = std::make_unique(*device_.context, device_.info.queue, - device_.info.queue_family); - } - if (device_.staging_queue->ok()) { - const leonida::CommandList* lists[] = {&list}; - result = device_.staging_queue->execute(lists); - if (result == leonida::ReplayResult::success && !device_.staging_queue->idle()) - result = leonida::ReplayResult::unsupported; - } - } - device_.context->remove_resource(staging_id); - if (result != leonida::ReplayResult::success) { - log_once("WriteToSubresource/ReadFromSubresource staging copy failed; replay result", int(result)); - return release(E_FAIL); - } - if (!write) unpack(static_cast(mapped), pitch); - return release(S_OK); - } - - bool cpu_visible() const { - if (heap_.Type == D3D12_HEAP_TYPE_UPLOAD || heap_.Type == D3D12_HEAP_TYPE_READBACK) return true; - return heap_.Type == D3D12_HEAP_TYPE_CUSTOM && heap_.CPUPageProperty != D3D12_CPU_PAGE_PROPERTY_NOT_AVAILABLE && - heap_.CPUPageProperty != D3D12_CPU_PAGE_PROPERTY_UNKNOWN; - } - - // Only these heaps hold bytes the CPU writes. READBACK is CPU-visible but GPU-written, and DEFAULT arena memory - // is also GPU-written; both can hold stale bytes at replay time, so host_at() must not read them as inputs. - bool cpu_writable() const { - if (heap_.Type == D3D12_HEAP_TYPE_UPLOAD) return true; - return heap_.Type == D3D12_HEAP_TYPE_CUSTOM && - (heap_.CPUPageProperty == D3D12_CPU_PAGE_PROPERTY_WRITE_BACK || - heap_.CPUPageProperty == D3D12_CPU_PAGE_PROPERTY_WRITE_COMBINE); - } - - DeviceState& device_; - D3D12_RESOURCE_DESC desc_; - D3D12_HEAP_PROPERTIES heap_; - D3D12_HEAP_FLAGS heap_flags_; - VkImage image_ = VK_NULL_HANDLE; - VkBuffer buffer_ = VK_NULL_HANDLE; - VkDeviceMemory memory_ = VK_NULL_HANDLE; - VkMemoryPropertyFlags memory_flags_ = 0; - VkAccelerationStructureKHR accel_ = VK_NULL_HANDLE; - void* mapped_ = nullptr; - VkFormat format_ = VK_FORMAT_UNDEFINED; - std::vector view_formats_; // creation-time castable list; empty means no restriction - std::vector castable_formats_; // the same list as the application gave it - VkFormat uint_backed_ = VK_FORMAT_UNDEFINED; - std::uint64_t image_address_ = 0; // what a T# names the texture by - bool rgb96_ = false; - VkImageAspectFlags aspects_ = 0; - std::uint64_t buffer_va_ = 0; - std::uint64_t gpu_va_ = 0; - bool host_import_ = false; // memory_ is the caller's pages (create_host_buffer): freed at once, not deferred - bool reserved_ = false; - bool sparse_image_ = false; - bool placed_ = false; - leonida::ResourceBinding binding_{}; // a texture's, as registered with the context - bool host_transfer_ = false; // created with VK_IMAGE_USAGE_HOST_TRANSFER_BIT_EXT - D3D12_GPU_VIRTUAL_ADDRESS va_ = 0; // a buffer's console VA, or a slot-133 texture's title address - VkDeviceSize arena_offset_ = 0; - bool in_arena_ = false; - // A placed buffer's heap range, held as a D3D12 placed resource holds its heap: the app may release the heap - // first, and the range must not go to another allocation while this buffer lives. - std::shared_ptr heap_range_; -}; - -// DXGI -> Vulkan for vertex attributes, with each element's size for D3D12_APPEND_ALIGNED_ELEMENT. -bool vertex_format(DXGI_FORMAT format, VkFormat& out, UINT& bytes) { - struct Row { - DXGI_FORMAT dxgi; - VkFormat vk; - UINT bytes; - }; - static constexpr Row rows[] = { - {DXGI_FORMAT_R32G32B32A32_FLOAT, VK_FORMAT_R32G32B32A32_SFLOAT, 16}, - {DXGI_FORMAT_R32G32B32A32_UINT, VK_FORMAT_R32G32B32A32_UINT, 16}, - {DXGI_FORMAT_R32G32B32A32_SINT, VK_FORMAT_R32G32B32A32_SINT, 16}, - {DXGI_FORMAT_R32G32B32_FLOAT, VK_FORMAT_R32G32B32_SFLOAT, 12}, - {DXGI_FORMAT_R32G32B32_UINT, VK_FORMAT_R32G32B32_UINT, 12}, - {DXGI_FORMAT_R32G32B32_SINT, VK_FORMAT_R32G32B32_SINT, 12}, - {DXGI_FORMAT_R32G32_FLOAT, VK_FORMAT_R32G32_SFLOAT, 8}, - {DXGI_FORMAT_R32G32_UINT, VK_FORMAT_R32G32_UINT, 8}, - {DXGI_FORMAT_R32G32_SINT, VK_FORMAT_R32G32_SINT, 8}, - {DXGI_FORMAT_R32_FLOAT, VK_FORMAT_R32_SFLOAT, 4}, - {DXGI_FORMAT_R32_UINT, VK_FORMAT_R32_UINT, 4}, - {DXGI_FORMAT_R32_SINT, VK_FORMAT_R32_SINT, 4}, - {DXGI_FORMAT_R16G16B16A16_FLOAT, VK_FORMAT_R16G16B16A16_SFLOAT, 8}, - {DXGI_FORMAT_R16G16B16A16_UNORM, VK_FORMAT_R16G16B16A16_UNORM, 8}, - {DXGI_FORMAT_R16G16B16A16_SNORM, VK_FORMAT_R16G16B16A16_SNORM, 8}, - {DXGI_FORMAT_R16G16B16A16_UINT, VK_FORMAT_R16G16B16A16_UINT, 8}, - {DXGI_FORMAT_R16G16B16A16_SINT, VK_FORMAT_R16G16B16A16_SINT, 8}, - {DXGI_FORMAT_R16G16_FLOAT, VK_FORMAT_R16G16_SFLOAT, 4}, - {DXGI_FORMAT_R16G16_UNORM, VK_FORMAT_R16G16_UNORM, 4}, - {DXGI_FORMAT_R16G16_SNORM, VK_FORMAT_R16G16_SNORM, 4}, - {DXGI_FORMAT_R16G16_UINT, VK_FORMAT_R16G16_UINT, 4}, - {DXGI_FORMAT_R16G16_SINT, VK_FORMAT_R16G16_SINT, 4}, - {DXGI_FORMAT_R16_FLOAT, VK_FORMAT_R16_SFLOAT, 2}, - {DXGI_FORMAT_R16_UNORM, VK_FORMAT_R16_UNORM, 2}, - {DXGI_FORMAT_R16_SNORM, VK_FORMAT_R16_SNORM, 2}, - {DXGI_FORMAT_R16_UINT, VK_FORMAT_R16_UINT, 2}, - {DXGI_FORMAT_R16_SINT, VK_FORMAT_R16_SINT, 2}, - {DXGI_FORMAT_R8G8B8A8_UNORM, VK_FORMAT_R8G8B8A8_UNORM, 4}, - {DXGI_FORMAT_R8G8B8A8_SNORM, VK_FORMAT_R8G8B8A8_SNORM, 4}, - {DXGI_FORMAT_R8G8B8A8_UINT, VK_FORMAT_R8G8B8A8_UINT, 4}, - {DXGI_FORMAT_R8G8B8A8_SINT, VK_FORMAT_R8G8B8A8_SINT, 4}, - {DXGI_FORMAT_B8G8R8A8_UNORM, VK_FORMAT_B8G8R8A8_UNORM, 4}, - {DXGI_FORMAT_R8G8_UNORM, VK_FORMAT_R8G8_UNORM, 2}, - {DXGI_FORMAT_R8G8_SNORM, VK_FORMAT_R8G8_SNORM, 2}, - {DXGI_FORMAT_R8G8_UINT, VK_FORMAT_R8G8_UINT, 2}, - {DXGI_FORMAT_R8G8_SINT, VK_FORMAT_R8G8_SINT, 2}, - {DXGI_FORMAT_R8_UNORM, VK_FORMAT_R8_UNORM, 1}, - {DXGI_FORMAT_R8_SNORM, VK_FORMAT_R8_SNORM, 1}, - {DXGI_FORMAT_R8_UINT, VK_FORMAT_R8_UINT, 1}, - {DXGI_FORMAT_R8_SINT, VK_FORMAT_R8_SINT, 1}, - {DXGI_FORMAT_R10G10B10A2_UNORM, VK_FORMAT_A2B10G10R10_UNORM_PACK32, 4}, - {DXGI_FORMAT_R10G10B10A2_UINT, VK_FORMAT_A2B10G10R10_UINT_PACK32, 4}, - {DXGI_FORMAT_R11G11B10_FLOAT, VK_FORMAT_B10G11R11_UFLOAT_PACK32, 4}, - }; - for (const Row& row : rows) - if (row.dxgi == format) { - out = row.vk; - bytes = row.bytes; - return true; - } - return false; -} - -VkBlendFactor blend_factor(D3D12_BLEND blend) { - switch (blend) { - case D3D12_BLEND_ZERO: return VK_BLEND_FACTOR_ZERO; - case D3D12_BLEND_ONE: return VK_BLEND_FACTOR_ONE; - case D3D12_BLEND_SRC_COLOR: return VK_BLEND_FACTOR_SRC_COLOR; - case D3D12_BLEND_INV_SRC_COLOR: return VK_BLEND_FACTOR_ONE_MINUS_SRC_COLOR; - case D3D12_BLEND_SRC_ALPHA: return VK_BLEND_FACTOR_SRC_ALPHA; - case D3D12_BLEND_INV_SRC_ALPHA: return VK_BLEND_FACTOR_ONE_MINUS_SRC_ALPHA; - case D3D12_BLEND_DEST_ALPHA: return VK_BLEND_FACTOR_DST_ALPHA; - case D3D12_BLEND_INV_DEST_ALPHA: return VK_BLEND_FACTOR_ONE_MINUS_DST_ALPHA; - case D3D12_BLEND_DEST_COLOR: return VK_BLEND_FACTOR_DST_COLOR; - case D3D12_BLEND_INV_DEST_COLOR: return VK_BLEND_FACTOR_ONE_MINUS_DST_COLOR; - case D3D12_BLEND_SRC_ALPHA_SAT: return VK_BLEND_FACTOR_SRC_ALPHA_SATURATE; - case D3D12_BLEND_BLEND_FACTOR: return VK_BLEND_FACTOR_CONSTANT_COLOR; - case D3D12_BLEND_INV_BLEND_FACTOR: return VK_BLEND_FACTOR_ONE_MINUS_CONSTANT_COLOR; - case D3D12_BLEND_SRC1_COLOR: return VK_BLEND_FACTOR_SRC1_COLOR; - case D3D12_BLEND_INV_SRC1_COLOR: return VK_BLEND_FACTOR_ONE_MINUS_SRC1_COLOR; - case D3D12_BLEND_SRC1_ALPHA: return VK_BLEND_FACTOR_SRC1_ALPHA; - case D3D12_BLEND_INV_SRC1_ALPHA: return VK_BLEND_FACTOR_ONE_MINUS_SRC1_ALPHA; - case D3D12_BLEND_ALPHA_FACTOR: return VK_BLEND_FACTOR_CONSTANT_ALPHA; - case D3D12_BLEND_INV_ALPHA_FACTOR: return VK_BLEND_FACTOR_ONE_MINUS_CONSTANT_ALPHA; - default: return VK_BLEND_FACTOR_ONE; - } -} - -VkBlendOp blend_op(D3D12_BLEND_OP op) { - switch (op) { - case D3D12_BLEND_OP_SUBTRACT: return VK_BLEND_OP_SUBTRACT; - case D3D12_BLEND_OP_REV_SUBTRACT: return VK_BLEND_OP_REVERSE_SUBTRACT; - case D3D12_BLEND_OP_MIN: return VK_BLEND_OP_MIN; - case D3D12_BLEND_OP_MAX: return VK_BLEND_OP_MAX; - default: return VK_BLEND_OP_ADD; - } -} - -// D3D12 and Vulkan list the logic ops in different orders, so each is named. -VkLogicOp logic_op(D3D12_LOGIC_OP op) { - switch (op) { - case D3D12_LOGIC_OP_CLEAR: return VK_LOGIC_OP_CLEAR; - case D3D12_LOGIC_OP_SET: return VK_LOGIC_OP_SET; - case D3D12_LOGIC_OP_COPY: return VK_LOGIC_OP_COPY; - case D3D12_LOGIC_OP_COPY_INVERTED: return VK_LOGIC_OP_COPY_INVERTED; - case D3D12_LOGIC_OP_NOOP: return VK_LOGIC_OP_NO_OP; - case D3D12_LOGIC_OP_INVERT: return VK_LOGIC_OP_INVERT; - case D3D12_LOGIC_OP_AND: return VK_LOGIC_OP_AND; - case D3D12_LOGIC_OP_NAND: return VK_LOGIC_OP_NAND; - case D3D12_LOGIC_OP_OR: return VK_LOGIC_OP_OR; - case D3D12_LOGIC_OP_NOR: return VK_LOGIC_OP_NOR; - case D3D12_LOGIC_OP_XOR: return VK_LOGIC_OP_XOR; - case D3D12_LOGIC_OP_EQUIV: return VK_LOGIC_OP_EQUIVALENT; - case D3D12_LOGIC_OP_AND_REVERSE: return VK_LOGIC_OP_AND_REVERSE; - case D3D12_LOGIC_OP_AND_INVERTED: return VK_LOGIC_OP_AND_INVERTED; - case D3D12_LOGIC_OP_OR_REVERSE: return VK_LOGIC_OP_OR_REVERSE; - case D3D12_LOGIC_OP_OR_INVERTED: return VK_LOGIC_OP_OR_INVERTED; - default: return VK_LOGIC_OP_COPY; - } -} - -// D3D12_COMPARISON_FUNC (NEVER = 1 .. ALWAYS = 8) and D3D12_STENCIL_OP (KEEP = 1 .. DECR = 8) list their values -// in Vulkan's order, starting at 1 instead of 0. -VkCompareOp compare_op(D3D12_COMPARISON_FUNC func) { - const int value = int(func); - return value >= 1 && value <= 8 ? VkCompareOp(value - 1) : VK_COMPARE_OP_ALWAYS; -} -VkStencilOp stencil_op(D3D12_STENCIL_OP op) { - const int value = int(op); - return value >= 1 && value <= 8 ? VkStencilOp(value - 1) : VK_STENCIL_OP_KEEP; -} - -VkStencilOpState stencil_face(const D3D12_DEPTH_STENCILOP_DESC& face, UINT8 read_mask, UINT8 write_mask) { - VkStencilOpState state{}; - state.failOp = stencil_op(face.StencilFailOp); - state.passOp = stencil_op(face.StencilPassOp); - state.depthFailOp = stencil_op(face.StencilDepthFailOp); - state.compareOp = compare_op(face.StencilFunc); - state.compareMask = read_mask; - state.writeMask = write_mask; - return state; -} - -bool equal_semantic(const std::string& a, const char* b) { - if (!b || a.size() != std::strlen(b)) return false; - for (std::size_t i = 0; i < a.size(); ++i) - if (std::tolower(static_cast(a[i])) != std::tolower(static_cast(b[i]))) return false; - return true; -} -// A heap (section 3.3): a range of the GPU address arena, as large as the game asked for, so a placed buffer can -// name any 64 KiB-aligned offset in it. Textures placed in it still get their own VkDeviceMemory; the offset is only -// their key, which keeps optimal-tiling images out of the arena's memory type. -class Heap final - : public Child { -public: - // {5d20c7a4-8e13-4b6d-9f27-3a1c94e0b7d8} - static constexpr GUID kTag{0x5d20c7a4, 0x8e13, 0x4b6d, {0x9f, 0x27, 0x3a, 0x1c, 0x94, 0xe0, 0xb7, 0xd8}}; - - Heap(DeviceState& device, const D3D12_HEAP_DESC& desc) : device_(device), desc_(desc) { - VkDeviceSize offset = 0; - if (device_.arena.mapped && - device_.arena_allocate(desc_.SizeInBytes, D3D12_DEFAULT_RESOURCE_PLACEMENT_ALIGNMENT, offset, - DeviceState::arena_heap)) { - allocation_ = std::shared_ptr( - new leonida::TileHeapAllocation{device_.arena.memory, offset, desc_.SizeInBytes, - device_.arena.memory_type}, - [&device](const leonida::TileHeapAllocation* allocation) { - device.arena_release(allocation->offset, allocation->size, DeviceState::arena_heap); - delete allocation; - }); - } - } - - // An existing heap (OpenExistingHeapFromAddress): `memory` is the caller's committed range imported with - // VK_EXT_external_memory_host, and the heap owns that VkDeviceMemory, not the range. Not in the arena. - Heap(DeviceState& device, const D3D12_HEAP_DESC& desc, VkDeviceMemory memory, std::uint32_t memory_type, - const void* address) - : device_(device), desc_(desc), host_address_(address) { - allocation_ = std::shared_ptr( - new leonida::TileHeapAllocation{memory, 0, desc_.SizeInBytes, memory_type}, - [device = device_.info.device, free = device_.context->vk.vkFreeMemory] - (const leonida::TileHeapAllocation* allocation) { - free(device, allocation->memory, nullptr); - delete allocation; - }); - } - - // As the host reports it (measured against the PC runtime, d3d12_vulkan_device_test compare_heap_descs): the - // alignment the heap was placed with (64 KiB for an Alignment of 0) and the one node for a node mask of 0, as the - // layer's resources, descriptor heaps and queues already answer. - D3D12_HEAP_DESC STDMETHODCALLTYPE GetDesc() override { - D3D12_HEAP_DESC desc = desc_; - desc.Alignment = alignment(); - desc.Properties.CreationNodeMask = 1; - desc.Properties.VisibleNodeMask = 1; - return desc; - } - - bool reserved() const { return bool(allocation_); } - // An existing heap: the caller's memory, not an arena range, so offset() is not a place in the arena. - const void* host_address() const { return host_address_; } - const std::shared_ptr& arena_range() const { return allocation_; } - VkDeviceSize offset() const { return allocation_->offset; } - UINT64 bytes() const { return desc_.SizeInBytes; } - UINT64 alignment() const { return desc_.Alignment ? desc_.Alignment : D3D12_DEFAULT_RESOURCE_PLACEMENT_ALIGNMENT; } - const D3D12_HEAP_PROPERTIES& properties() const { return desc_.Properties; } - D3D12_HEAP_FLAGS flags() const { return desc_.Flags; } - std::shared_ptr tiles(const leonida::VulkanContext& context, bool image, - std::uint32_t memory_types) { - const auto denied = image ? D3D12_HEAP_FLAG_DENY_NON_RT_DS_TEXTURES : D3D12_HEAP_FLAG_DENY_BUFFERS; - if (device_.context.get() != &context || desc_.Properties.Type != D3D12_HEAP_TYPE_DEFAULT || - (desc_.Flags & denied) || host_address_) return {}; - std::lock_guard lock(backing_mutex_); - if (!image && device_.tiles_share_arena()) { - if (tile_allocation_) return {}; - arena_tiles_ = true; - return allocation_; - } - // Vulkan only guarantees sparse aliasing between compatible images. A texture tile heap has its own - // backing, so a heap already used for buffer tiles or placed buffers cannot also map texture tiles. - if (arena_tiles_ || (tile_allocation_ && image_tiles_ != image)) return {}; - if (placed_buffer_ || (image && placed_image_)) return {}; - if (!tile_allocation_) { - std::uint32_t memory_type = 0; - if (!image) memory_types = device_.sparse_buffer_memory_types; - const VkMemoryRequirements requirements{desc_.SizeInBytes, leonida::tile_size_in_bytes, - memory_types}; - const auto memory = device_.allocate(requirements, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, 0, - nullptr, !image, &memory_type); - if (!memory) return {}; - image_tiles_ = image; - tile_allocation_ = std::shared_ptr( - new leonida::TileHeapAllocation{memory, 0, desc_.SizeInBytes, memory_type}, - [device = device_.info.device, free = device_.context->vk.vkFreeMemory] - (const leonida::TileHeapAllocation* allocation) { - free(device, allocation->memory, nullptr); - delete allocation; - }); - } - return tile_allocation_; - } - - bool use_as_placed_resource(bool buffer) { - std::lock_guard lock(backing_mutex_); - // A placed resource cannot alias the separate sparse memory allocation. - if (tile_allocation_ && (buffer || image_tiles_)) return false; - (buffer ? placed_buffer_ : placed_image_) = true; - return true; - } - -private: - DeviceState& device_; - D3D12_HEAP_DESC desc_; - const void* host_address_ = nullptr; - std::shared_ptr allocation_; - std::mutex backing_mutex_; - std::shared_ptr tile_allocation_; - bool placed_buffer_ = false; - bool placed_image_ = false; - bool arena_tiles_ = false; - bool image_tiles_ = false; -}; - -// The S#s a shader builds from immediates (literal_samplers in its index entry) are named by no heap slot, so -// nothing else gives them a sampler and a hash-table key: without this their lookup finds the fallback sampler -// (index 0) and the shader samples with the wrong filter and address modes (docs/design.md, Literal samplers). -// Registering is idempotent and also runs when the pipeline is created again. -void register_literal_samplers(DeviceState& device, const leonida::ShaderEntry& entry) { - for (const leonida::gfx10::SamplerWords& words : entry.literal_samplers) - if (!device.bind_sampler(words)) - log_once("a shader's literal S# got no sampler (no bindless set, or its sampler array is full); " - "literal S#s in that shader:", - int(entry.literal_samplers.size())); -} - -// Among index entries for one program (containers with the same FSSM program; 789 groups in the 26,503-shader -// corpus), the one to build: the first that `fits` and declares no set-0 bindings (the cheaper pipeline); else the -// first that fits; else the first without bindings; else the first. Null when there is none. -template -const leonida::ShaderEntry* pick_entry(const std::vector& candidates, Fits&& fits) { - const leonida::ShaderEntry* fitting = nullptr; - const leonida::ShaderEntry* unbound = nullptr; - for (const leonida::ShaderEntry* e : candidates) { - const bool fit = fits(*e); - if (fit && !e->binding_count) return e; - if (fit && !fitting) fitting = e; - if (!e->binding_count && !unbound) unbound = e; - } - if (fitting) return fitting; - if (unbound) return unbound; - return candidates.empty() ? nullptr : candidates.front(); -} - -// Whether the input layout has an element for every ordinary (non-system-value) input of the vertex shader. -bool layout_feeds(const leonida::ShaderEntry& vs, const D3D12_INPUT_LAYOUT_DESC& layout) { - const UINT count = layout.pInputElementDescs ? layout.NumElements : 0; - for (const auto& input : vs.input_signature) { - if (input.system_value) continue; - bool fed = false; - for (UINT i = 0; i < count && !fed; ++i) - fed = layout.pInputElementDescs[i].SemanticIndex == input.semantic_index && - equal_semantic(input.semantic, layout.pInputElementDescs[i].SemanticName); - if (!fed) return false; - } - return true; -} - -// Known D3D12_PIPELINE_STATE_FLAGS bits: TOOL_DEBUG (0x1, kept for cached-PSO parity), bit 0x2, -// DYNAMIC_DEPTH_BIAS (0x4), and DYNAMIC_INDEX_BUFFER_STRIP_CUT (0x8). Higher bits fail with E_INVALIDARG -// on both Windows hardware D3D12 and WARP. -constexpr UINT kKnownPipelineStateFlags = 0xFu; - -class RootSignature final - : public Child { -public: - // {3e9b4a61-2d7c-4f18-b5a0-c71e8d92f036} - static constexpr GUID kTag{0x3e9b4a61, 0x2d7c, 0x4f18, {0xb5, 0xa0, 0xc7, 0x1e, 0x8d, 0x92, 0xf0, 0x36}}; - RootSignature(RootArgumentLayout layout, std::string content) - : layout_(std::move(layout)), content_(std::move(content)) {} - const RootArgumentLayout& layout() const { return layout_; } - // SHA-256 of the serialized root signature: a cached PSO matches root signatures with the same content. - const std::string& content() const { return content_; } - -private: - RootArgumentLayout layout_; - std::string content_; -}; - -// The ID3DBlob GetCachedBlob returns. -class CachedBlob final : public ID3DBlob { -public: - explicit CachedBlob(std::vector bytes) : bytes_(std::move(bytes)) {} - HRESULT STDMETHODCALLTYPE QueryInterface(REFIID riid, void** out) override { - if (!out) return E_POINTER; - if (riid == __uuidof(IUnknown) || riid == __uuidof(ID3D10Blob)) { - AddRef(); - *out = static_cast(this); - return S_OK; - } - *out = nullptr; - return E_NOINTERFACE; - } - ULONG STDMETHODCALLTYPE AddRef() override { return ++refs_; } - ULONG STDMETHODCALLTYPE Release() override { - const ULONG left = --refs_; - if (!left) delete this; - return left; - } - LPVOID STDMETHODCALLTYPE GetBufferPointer() override { return bytes_.data(); } - SIZE_T STDMETHODCALLTYPE GetBufferSize() override { return bytes_.size(); } - -private: - std::vector bytes_; - std::atomic refs_{1}; -}; - -// A shader as the key sees it, without reading the whole program on every PSO: a DXBC container already carries a -// checksum of its contents (bytes 4..19), so that and the size stand for it. A container without one (all zero, as -// hand-built test containers have) or other bytecode is hashed with FNV-1a. -void key_shader(leonida::cached_pso::KeyBuilder& key, const char* stage, const D3D12_SHADER_BYTECODE& code) { - const auto* bytes = static_cast(code.pShaderBytecode); - const std::size_t size = bytes ? code.BytecodeLength : 0; - key.tag(stage).u32(std::uint32_t(size)).u32(std::uint32_t(std::uint64_t(size) >> 32)); - if (size >= 20 && std::memcmp(bytes, "DXBC", 4) == 0 && - std::any_of(bytes + 4, bytes + 20, [](std::uint8_t b) { return b != 0; })) { - key.bytes(bytes + 4, 16); - return; - } - std::uint64_t h = 0xcbf29ce484222325ull; - for (std::size_t i = 0; i < size; ++i) h = (h ^ bytes[i]) * 0x100000001b3ull; - key.u32(std::uint32_t(h)).u32(std::uint32_t(h >> 32)); -} - -void key_root_signature(leonida::cached_pso::KeyBuilder& key, ID3D12RootSignature* signature); - -// The parts of a compute description the PC runtime matches a cached PSO against (not Flags, measured). -leonida::cached_pso::Key pipeline_key(const D3D12_COMPUTE_PIPELINE_STATE_DESC& desc) { - leonida::cached_pso::KeyBuilder key; - key.tag("compute"); - key_root_signature(key, desc.pRootSignature); - key_shader(key, "cs", desc.CS); - key.u32(desc.NodeMask); - return leonida::sha256_hex(key.data()); -} - -leonida::cached_pso::Key pipeline_key(const D3D12_GRAPHICS_PIPELINE_STATE_DESC& desc) { - leonida::cached_pso::KeyBuilder key; - key.tag("graphics"); - key_root_signature(key, desc.pRootSignature); - key_shader(key, "vs", desc.VS); - key_shader(key, "ps", desc.PS); - key_shader(key, "ds", desc.DS); - key_shader(key, "hs", desc.HS); - key_shader(key, "gs", desc.GS); - const D3D12_STREAM_OUTPUT_DESC& so = desc.StreamOutput; - key.u32(so.pSODeclaration ? so.NumEntries : 0); - for (UINT i = 0; so.pSODeclaration && i < so.NumEntries; ++i) { - const D3D12_SO_DECLARATION_ENTRY& e = so.pSODeclaration[i]; - key.u32(e.Stream).text(e.SemanticName).u32(e.SemanticIndex).u32(e.StartComponent).u32(e.ComponentCount); - key.u32(e.OutputSlot); - } - key.u32(so.pBufferStrides ? so.NumStrides : 0); - for (UINT i = 0; so.pBufferStrides && i < so.NumStrides; ++i) key.u32(so.pBufferStrides[i]); - key.u32(so.RasterizedStream); - const D3D12_BLEND_DESC& blend = desc.BlendState; - key.u32(blend.AlphaToCoverageEnable).u32(blend.IndependentBlendEnable); - for (const D3D12_RENDER_TARGET_BLEND_DESC& t : blend.RenderTarget) - key.u32(t.BlendEnable).u32(t.LogicOpEnable).u32(t.SrcBlend).u32(t.DestBlend).u32(t.BlendOp).u32(t.SrcBlendAlpha) - .u32(t.DestBlendAlpha).u32(t.BlendOpAlpha).u32(t.LogicOp).u32(t.RenderTargetWriteMask); - key.u32(desc.SampleMask); - const D3D12_RASTERIZER_DESC& r = desc.RasterizerState; - std::uint32_t bias_clamp = 0, slope = 0; - std::memcpy(&bias_clamp, &r.DepthBiasClamp, 4); - std::memcpy(&slope, &r.SlopeScaledDepthBias, 4); - key.u32(r.FillMode).u32(r.CullMode).u32(r.FrontCounterClockwise).u32(std::uint32_t(r.DepthBias)).u32(bias_clamp); - key.u32(slope).u32(r.DepthClipEnable).u32(r.MultisampleEnable).u32(r.AntialiasedLineEnable); - key.u32(r.ForcedSampleCount).u32(r.ConservativeRaster); - const D3D12_DEPTH_STENCIL_DESC& d = desc.DepthStencilState; - key.u32(d.DepthEnable).u32(d.DepthWriteMask).u32(d.DepthFunc).u32(d.StencilEnable).u32(d.StencilReadMask); - key.u32(d.StencilWriteMask); - for (const D3D12_DEPTH_STENCILOP_DESC& face : {d.FrontFace, d.BackFace}) - key.u32(face.StencilFailOp).u32(face.StencilDepthFailOp).u32(face.StencilPassOp).u32(face.StencilFunc); - const D3D12_INPUT_LAYOUT_DESC& input = desc.InputLayout; - const UINT input_count = - input.pInputElementDescs ? std::min(input.NumElements, D3D12_IA_VERTEX_INPUT_STRUCTURE_ELEMENT_COUNT) : 0; - key.u32(input_count); - for (UINT i = 0; i < input_count; ++i) { - const D3D12_INPUT_ELEMENT_DESC& e = input.pInputElementDescs[i]; - key.text(e.SemanticName).u32(e.SemanticIndex).u32(e.Format).u32(e.InputSlot).u32(e.AlignedByteOffset); - key.u32(e.InputSlotClass).u32(e.InstanceDataStepRate); - } - key.u32(desc.IBStripCutValue).u32(desc.PrimitiveTopologyType).u32(desc.NumRenderTargets); - for (const DXGI_FORMAT format : desc.RTVFormats) key.u32(format); - key.u32(desc.DSVFormat).u32(desc.SampleDesc.Count).u32(desc.SampleDesc.Quality).u32(desc.NodeMask); - return leonida::sha256_hex(key.data()); -} - -// CachedPSO as the PC runtime checks it before creating the PSO (src/cached_pso.h has the measured answers). -HRESULT check_cached_pso(const leonida::cached_pso::Identity& identity, const leonida::cached_pso::Key& key, - const D3D12_CACHED_PIPELINE_STATE& cached) { - if (!cached.pCachedBlob) return S_OK; - if (!cached.CachedBlobSizeInBytes) return E_INVALIDARG; - using leonida::cached_pso::Check; - switch (leonida::cached_pso::check(identity, key, - {static_cast(cached.pCachedBlob), cached.CachedBlobSizeInBytes})) { - case Check::accepted: return S_OK; - case Check::other_adapter: return D3D12_ERROR_ADAPTER_NOT_FOUND; - case Check::other_driver: return D3D12_ERROR_DRIVER_VERSION_MISMATCH; - default: return E_INVALIDARG; - } -} - -// The console's ID3D12PipelineState goes past the public interface, which ends at slot 8 (GetCachedBlob). The -// FidelityFX DLL calls slot 11 on every compute pipeline it creates (docs/d3d12_command_objects.md, "Pipeline slot 11 -// sizes the compute scratch"). These three are declared here, ahead of Object's virtual destructor, so they are vtable -// slots 9, 10 and 11 under MSVC and GCC alike; declared in PipelineState itself they would come after the destructor, -// which takes one slot under MSVC and two under GCC. d3d12_fspx_compute_test calls slot 11 through the vtable. -class XboxPipelineStateStubs : public ID3D12PipelineStateStubs { -public: - virtual HRESULT STDMETHODCALLTYPE xbox_slot9(UINT64, UINT64, UINT64) = 0; - virtual HRESULT STDMETHODCALLTYPE xbox_slot10(UINT64, UINT64, UINT64) = 0; - virtual HRESULT STDMETHODCALLTYPE xbox_slot11(UINT64, UINT64, void** out) = 0; -}; - -// A pipeline state. Compute only for now: the shader is found by the SHA-256 of its FSSM program in the -// translator's index, and the FSSM blob is copied into the arena as the shader's code base. -// A D3D12_PIPELINE_STATE_STREAM_DESC (ID3D12Device2::CreatePipelineState) as the descriptions the PSO creators take. -// The stream is a run of subobjects, each a D3D12_PIPELINE_STATE_SUBOBJECT_TYPE followed by its description at that -// description's alignment, each subobject starting at pointer alignment (the d3dx12.h layout, `alignas(void*)`). A -// subobject that is absent takes the runtime's default (the CD3DX12 defaults: depth test on with LESS, back-face -// culling, no blending, sample mask 0xFFFFFFFF, one sample). A type given twice, a truncated stream or an unknown -// type is E_INVALIDARG, as on the PC runtime; state this layer cannot honour yet is E_NOTIMPL with a log. -struct PipelineStream { - D3D12_GRAPHICS_PIPELINE_STATE_DESC graphics{}; - D3D12_COMPUTE_PIPELINE_STATE_DESC compute{}; - D3D12_SHADER_BYTECODE ms{}; - D3D12_SHADER_BYTECODE as{}; - bool has_cs = false; - bool has_graphics_stage = false; // VS, PS, DS, HS, GS, AS or MS -}; - -HRESULT parse_pipeline_stream(const D3D12_PIPELINE_STATE_STREAM_DESC& desc, PipelineStream& out) { - if (!desc.pPipelineStateSubobjectStream || !desc.SizeInBytes) return E_INVALIDARG; - D3D12_GRAPHICS_PIPELINE_STATE_DESC& g = out.graphics; - for (auto& target : g.BlendState.RenderTarget) { - target.SrcBlend = target.SrcBlendAlpha = D3D12_BLEND_ONE; - target.DestBlend = target.DestBlendAlpha = D3D12_BLEND_ZERO; - target.BlendOp = target.BlendOpAlpha = D3D12_BLEND_OP_ADD; - target.LogicOp = D3D12_LOGIC_OP_NOOP; - target.RenderTargetWriteMask = D3D12_COLOR_WRITE_ENABLE_ALL; - } - g.RasterizerState.FillMode = D3D12_FILL_MODE_SOLID; - g.RasterizerState.CullMode = D3D12_CULL_MODE_BACK; - g.RasterizerState.DepthClipEnable = TRUE; - g.DepthStencilState.DepthEnable = TRUE; - g.DepthStencilState.DepthWriteMask = D3D12_DEPTH_WRITE_MASK_ALL; - g.DepthStencilState.DepthFunc = D3D12_COMPARISON_FUNC_LESS; - g.DepthStencilState.StencilReadMask = D3D12_DEFAULT_STENCIL_READ_MASK; - g.DepthStencilState.StencilWriteMask = D3D12_DEFAULT_STENCIL_WRITE_MASK; - g.DepthStencilState.FrontFace = g.DepthStencilState.BackFace = { - D3D12_STENCIL_OP_KEEP, D3D12_STENCIL_OP_KEEP, D3D12_STENCIL_OP_KEEP, D3D12_COMPARISON_FUNC_ALWAYS}; - g.SampleMask = UINT_MAX; - g.SampleDesc = {1, 0}; - - const auto* base = static_cast(desc.pPipelineStateSubobjectStream); - const std::size_t size = desc.SizeInBytes; - const auto round_up = [](std::size_t v, std::size_t a) { return (v + a - 1) / a * a; }; - std::uint64_t seen = 0; - std::size_t at = 0; - while (at < size) { - D3D12_PIPELINE_STATE_SUBOBJECT_TYPE type; - if (size - at < sizeof(type)) return E_INVALIDARG; - std::memcpy(&type, base + at, sizeof(type)); - // The versioned depth-stencil and rasterizer subobjects describe the same state as their base type, so the - // stream contract counts any two of one family as duplicates; the payload below still follows `type`. - D3D12_PIPELINE_STATE_SUBOBJECT_TYPE family = type; - if (type == D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DEPTH_STENCIL1 || - type == D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DEPTH_STENCIL2) - family = D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DEPTH_STENCIL; - else if (type == D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_RASTERIZER1 || - type == D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_RASTERIZER2) - family = D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_RASTERIZER; - if (unsigned(type) >= 64 || (seen >> unsigned(family) & 1)) return E_INVALIDARG; - seen |= std::uint64_t(1) << unsigned(family); - bool ok = true; - const auto take = [&](auto& value) { - using T = std::remove_reference_t; - const std::size_t payload = round_up(at + sizeof(type), alignof(T)); - if (payload > size || size - payload < sizeof(T)) { - ok = false; - return; - } - std::memcpy(&value, base + payload, sizeof(T)); - at = round_up(payload + sizeof(T), sizeof(void*)); - }; - const auto stage = [&](D3D12_SHADER_BYTECODE& code) { - take(code); - out.has_graphics_stage = true; - }; - switch (type) { - case D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_ROOT_SIGNATURE: - take(g.pRootSignature); - out.compute.pRootSignature = g.pRootSignature; - break; - case D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_VS: stage(g.VS); break; - case D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_PS: stage(g.PS); break; - case D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DS: stage(g.DS); break; - case D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_HS: stage(g.HS); break; - case D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_GS: stage(g.GS); break; - case D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_AS: stage(out.as); break; - case D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_MS: stage(out.ms); break; - case D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_CS: - take(out.compute.CS); - out.has_cs = true; - break; - case D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_STREAM_OUTPUT: take(g.StreamOutput); break; - case D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_BLEND: take(g.BlendState); break; - case D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_SAMPLE_MASK: take(g.SampleMask); break; - case D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_RASTERIZER: take(g.RasterizerState); break; - case D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DEPTH_STENCIL: take(g.DepthStencilState); break; - case D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_INPUT_LAYOUT: take(g.InputLayout); break; - case D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_IB_STRIP_CUT_VALUE: take(g.IBStripCutValue); break; - case D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_PRIMITIVE_TOPOLOGY: take(g.PrimitiveTopologyType); break; - case D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_RENDER_TARGET_FORMATS: { - D3D12_RT_FORMAT_ARRAY formats{}; - take(formats); - if (formats.NumRenderTargets > D3D12_SIMULTANEOUS_RENDER_TARGET_COUNT) return E_INVALIDARG; - g.NumRenderTargets = formats.NumRenderTargets; - std::copy(std::begin(formats.RTFormats), std::end(formats.RTFormats), std::begin(g.RTVFormats)); - break; - } - case D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DEPTH_STENCIL_FORMAT: take(g.DSVFormat); break; - case D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_SAMPLE_DESC: take(g.SampleDesc); break; - case D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_NODE_MASK: - take(g.NodeMask); - out.compute.NodeMask = g.NodeMask; - break; - case D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_CACHED_PSO: - take(g.CachedPSO); - out.compute.CachedPSO = g.CachedPSO; - break; - case D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_FLAGS: - take(g.Flags); - out.compute.Flags = g.Flags; - break; - case D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DEPTH_STENCIL1: { - D3D12_DEPTH_STENCIL_DESC1 d{}; - take(d); - if (ok && d.DepthBoundsTestEnable) { - log_once("depth-bounds tests are not supported yet; stream subobject", int(type)); - return E_NOTIMPL; - } - g.DepthStencilState = {d.DepthEnable, d.DepthWriteMask, d.DepthFunc, d.StencilEnable, d.StencilReadMask, - d.StencilWriteMask, d.FrontFace, d.BackFace}; - break; - } - case D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DEPTH_STENCIL2: { - D3D12_DEPTH_STENCIL_DESC2 d{}; - take(d); - if (!ok) break; - if (d.DepthBoundsTestEnable) { - log_once("depth-bounds tests are not supported yet; stream subobject", int(type)); - return E_NOTIMPL; - } - // Separate front and back stencil masks are not modelled (one read and one write mask per PSO). - if (d.StencilEnable && (d.FrontFace.StencilReadMask != d.BackFace.StencilReadMask || - d.FrontFace.StencilWriteMask != d.BackFace.StencilWriteMask)) { - log_once("separate front and back stencil masks are not supported yet; stream subobject", int(type)); - return E_NOTIMPL; - } - const auto face = [](const D3D12_DEPTH_STENCILOP_DESC1& f) { - return D3D12_DEPTH_STENCILOP_DESC{f.StencilFailOp, f.StencilDepthFailOp, f.StencilPassOp, f.StencilFunc}; - }; - g.DepthStencilState = {d.DepthEnable, d.DepthWriteMask, d.DepthFunc, d.StencilEnable, - UINT8(d.FrontFace.StencilReadMask), UINT8(d.FrontFace.StencilWriteMask), - face(d.FrontFace), face(d.BackFace)}; - break; - } - case D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_RASTERIZER1: - case D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_RASTERIZER2: { - // Their DepthBias is a float; the PSO path takes D3D12_RASTERIZER_DESC's integer one. - FLOAT bias = 0; - D3D12_RASTERIZER_DESC& r = g.RasterizerState; - if (type == D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_RASTERIZER1) { - D3D12_RASTERIZER_DESC1 d{}; - take(d); - r = {d.FillMode, d.CullMode, d.FrontCounterClockwise, 0, d.DepthBiasClamp, d.SlopeScaledDepthBias, - d.DepthClipEnable, d.MultisampleEnable, d.AntialiasedLineEnable, d.ForcedSampleCount, - d.ConservativeRaster}; - bias = d.DepthBias; - } else { - D3D12_RASTERIZER_DESC2 d{}; - take(d); - r = {d.FillMode, d.CullMode, d.FrontCounterClockwise, 0, d.DepthBiasClamp, d.SlopeScaledDepthBias, - d.DepthClipEnable, FALSE, FALSE, d.ForcedSampleCount, d.ConservativeRaster}; - bias = d.DepthBias; - } - r.DepthBias = INT(bias); - if (ok && FLOAT(r.DepthBias) != bias) log_once("a fractional depth bias is truncated; bias x1000", int(bias * 1000)); - break; - } - case D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_VIEW_INSTANCING: { - D3D12_VIEW_INSTANCING_DESC d{}; - take(d); - if (ok && d.ViewInstanceCount) { - log_once("view instancing is not supported yet; views", int(d.ViewInstanceCount)); - return E_NOTIMPL; - } - break; - } - default: - log_once("unknown pipeline state stream subobject type:", int(type)); - return E_INVALIDARG; - } - if (!ok) return E_INVALIDARG; - } - if (out.has_cs && out.has_graphics_stage) return E_INVALIDARG; // a compute stage with graphics stages - if (!out.has_cs && !out.has_graphics_stage) return E_INVALIDARG; - return S_OK; -} - -class PipelineState final - : public Child { -public: - // {8d2f6c14-b0e7-4a93-9c58-1f4a7e3b6d20} - static constexpr GUID kTag{0x8d2f6c14, 0xb0e7, 0x4a93, {0x9c, 0x58, 0x1f, 0x4a, 0x7e, 0x3b, 0x6d, 0x20}}; - explicit PipelineState(DeviceState& device) : device_(device) {} - - ~PipelineState() override { - auto& vk = device_.context->vk; - const VkDevice dev = device_.info.device; - if (registered_) device_.context->remove_pipeline(id()); - if (pipeline_.pipeline) vk.vkDestroyPipeline(dev, pipeline_.pipeline, nullptr); - if (pipeline_.layout) vk.vkDestroyPipelineLayout(dev, pipeline_.layout, nullptr); - if (module_) vk.vkDestroyShaderModule(dev, module_, nullptr); - if (graphics_.pipeline) vk.vkDestroyPipeline(dev, graphics_.pipeline, nullptr); - for (const auto& [unbound, built] : variants_) vk.vkDestroyPipeline(dev, built, nullptr); - if (graphics_.layout) vk.vkDestroyPipelineLayout(dev, graphics_.layout, nullptr); - for (VkShaderModule module : modules_) vk.vkDestroyShaderModule(dev, module, nullptr); - if (code_bytes_) device_.arena_release(code_base_, code_bytes_, DeviceState::arena_shader); - } - - // Pipeline layouts declare the whole 144-byte block as one push-constant range. A device whose - // maxPushConstantsSize is smaller (128 bytes is the Vulkan minimum, which some Intel and mobile drivers - // report) needs the uniform-buffer tail #224 flags with push_constants_need_fallback, which is not built yet, - // so pipelines are refused there with the limit named instead of breaking VUID-VkPushConstantRange-size-00298. - bool push_constants_fit() const { - const std::uint32_t limit = device_.info.max_push_constants_size; - if (limit == 0 || limit >= sizeof(leonida::ShaderUserData)) return true; // 0: not queried - log_once("pipelines need 144 bytes of push constants (uniform-buffer fallback not built yet); " - "maxPushConstantsSize", - int(limit)); - return false; - } - - // Asks for the subgroup size the shader was translated for, where the device allows (src/subgroup_size.h): the - // stage gets VkPipelineShaderStageRequiredSubgroupSizeCreateInfo in `storage` (which must outlive pipeline - // creation) and, for compute, REQUIRE_FULL_SUBGROUPS. A size the device cannot give is reported, not hidden. - void subgroup_size_for(const leonida::ShaderEntry& entry, VkPipelineShaderStageRequiredSubgroupSizeCreateInfo& storage, - VkPipelineShaderStageCreateInfo& stage) { - const leonida::SubgroupRequest request = leonida::decide_subgroup_size(entry, device_.info.subgroup); - if (request.outcome == leonida::SubgroupOutcome::unavailable) - report_subgroup_unavailable(entry, request, device_.info.subgroup); - leonida::apply_subgroup_request(request, storage, stage); - subgroup_requests_.push_back(request); - } - - std::uintptr_t id() const { return reinterpret_cast(static_cast(this)); } - void set_cache_key(leonida::cached_pso::Key key) { cache_key_ = std::move(key); } - - // A null pointer is accepted with S_OK, as by the PC runtime (measured on an RTX 3060 and WARP). - HRESULT STDMETHODCALLTYPE GetCachedBlob(ID3DBlob** blob) override { - if (!blob) return S_OK; - *blob = new CachedBlob(leonida::cached_pso::encode(device_.pso_identity, cache_key_)); - return S_OK; - } - - // Slots 9 and 10: console methods no caller is known to use; refused, and named once in the log. - HRESULT STDMETHODCALLTYPE xbox_slot9(UINT64, UINT64, UINT64) override { - log_once("console pipeline slot called (not implemented); slot", 9); - return E_NOTIMPL; - } - HRESULT STDMETHODCALLTYPE xbox_slot10(UINT64, UINT64, UINT64) override { - log_once("console pipeline slot called (not implemented); slot", 10); - return E_NOTIMPL; - } - - // Slot 11, called by the FidelityFX DLL as (0, 0, &obj) after it creates a pipeline. It reads one dword through - // obj's slot 3 (the shape of ID3DBlob::GetBufferPointer), multiplies it by 1024, releases obj through slot 2, and - // creates and binds a compute scratch buffer before a dispatch only when that value is non-zero (measured in the - // DLL's code, docs/d3d12_command_objects.md). The answer is a blob holding 0: none of the 1.0.2.1 DLL's 29 programs - // enables scratch (COMPUTE_PGM_RSRC2.SCRATCH_EN clear in all 29) or has a scratch instruction (measured), and a - // translated module keeps its private data in SPIR-V, not in a console scratch buffer. With 0 the DLL creates no - // scratch buffer and skips list slot 141. The arguments are logged once when they are not the measured zeros. - HRESULT STDMETHODCALLTYPE xbox_slot11(UINT64 a, UINT64 b, void** out) override { - if (a || b) log_once("console pipeline slot 11 with unexpected arguments; first", int(a ? a : b)); - if (!out) return E_POINTER; - *out = static_cast(new CachedBlob(std::vector(4, 0))); - return S_OK; - } - - bool compute() const { return registered_ && !is_graphics_; } - bool graphics() const { return registered_ && is_graphics_; } - const std::vector& subgroup_requests() const { return subgroup_requests_; } - - // A VS (+ GS) (+ PS) pipeline for dynamic rendering. Vertex input comes from the input layout matched to the - // VS's input signature by semantic name and index: location = the element's register, the translator's rule - // (docs/design.md, "Vertex fetch"). Refused with a log: hull and domain stages, stream output, the centre - // multisample pattern, two stages that both read their code base, and state that needs a Vulkan feature the - // device lacks (including the geometryShader feature a GS needs). A GS takes triangles; the sample count may - // be above one. Viewport, scissor, topology, vertex strides, stencil reference and blend factor are dynamic, - // set from the list's state at each draw. - // With `ms` (a pipeline state stream's MS subobject) it is an MS (+ PS) pipeline on VK_EXT_mesh_shader instead: - // no VS, no vertex input or input assembly (the input layout, topology type and strip cut are ignored, as D3D12 - // does for mesh PSOs), drawn by DispatchMesh. An AS (amplification shader) is refused: the game has none. - HRESULT create_graphics(const D3D12_GRAPHICS_PIPELINE_STATE_DESC& desc, const D3D12_SHADER_BYTECODE* ms = nullptr, - const D3D12_SHADER_BYTECODE* as = nullptr) { - auto& vk = device_.context->vk; - const VkDevice dev = device_.info.device; - const bool mesh = ms && ms->pShaderBytecode && ms->BytecodeLength; - if (as && as->pShaderBytecode && as->BytecodeLength) { - log_once("amplification shaders are not supported (the game has none); bytes", int(as->BytecodeLength)); - return E_NOTIMPL; - } - if (mesh && (desc.VS.BytecodeLength || desc.HS.BytecodeLength || desc.DS.BytecodeLength || - desc.GS.BytecodeLength || desc.StreamOutput.NumEntries)) - return E_INVALIDARG; // D3D12: a mesh PSO has no vertex, tessellation or geometry stage - if (!mesh && (!desc.VS.pShaderBytecode || !desc.VS.BytecodeLength)) return E_INVALIDARG; - if (mesh && (!device_.info.mesh_shader || !vk.vkCmdDrawMeshTasksEXT)) { - log_once("mesh-shader PSOs need VK_EXT_mesh_shader, which the device has not enabled; stage", 1); - return E_NOTIMPL; - } - if (desc.NodeMask & ~1u) return E_INVALIDARG; - if (static_cast(desc.Flags) & ~kKnownPipelineStateFlags) return E_INVALIDARG; - if (!device_.arena.mapped) { - log_once("pipelines need the GPU address arena (bufferDeviceAddress); stage", 1); - return E_NOTIMPL; - } - if (!push_constants_fit()) return E_NOTIMPL; - if (!vk.graphics_complete()) { - log_once("graphics pipelines need Vulkan 1.3 dynamic rendering and extended dynamic state; stage", 1); - return E_NOTIMPL; - } - if (desc.NumRenderTargets > D3D12_SIMULTANEOUS_RENDER_TARGET_COUNT) return E_INVALIDARG; - for (UINT i = desc.NumRenderTargets; i < D3D12_SIMULTANEOUS_RENDER_TARGET_COUNT; ++i) - if (desc.RTVFormats[i] != DXGI_FORMAT_UNKNOWN) return E_INVALIDARG; - if (desc.DSVFormat != DXGI_FORMAT_UNKNOWN) { - const Format dsv_fmt = vulkan_format(desc.DSVFormat, true); - if (dsv_fmt.format == VK_FORMAT_UNDEFINED || dsv_fmt.typeless || - !(dsv_fmt.aspects & (VK_IMAGE_ASPECT_DEPTH_BIT | VK_IMAGE_ASPECT_STENCIL_BIT))) { - log_once("depth-stencil format not supported:", desc.DSVFormat); - return E_INVALIDARG; - } - } - if (desc.InputLayout.NumElements > D3D12_IA_VERTEX_INPUT_STRUCTURE_ELEMENT_COUNT) return E_INVALIDARG; - if (desc.InputLayout.NumElements > 0 && !desc.InputLayout.pInputElementDescs) return E_INVALIDARG; - for (UINT i = 0; i < desc.InputLayout.NumElements; ++i) { - const D3D12_INPUT_ELEMENT_DESC& element = desc.InputLayout.pInputElementDescs[i]; - if (!element.SemanticName) return E_INVALIDARG; - if (element.InputSlot >= D3D12_IA_VERTEX_INPUT_RESOURCE_SLOT_COUNT) return E_INVALIDARG; - if (element.InputSlotClass != D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA && - element.InputSlotClass != D3D12_INPUT_CLASSIFICATION_PER_INSTANCE_DATA) - return E_INVALIDARG; - if (element.InputSlotClass == D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA && - element.InstanceDataStepRate != 0) - return E_INVALIDARG; - } - if (desc.BlendState.IndependentBlendEnable) { - for (const D3D12_RENDER_TARGET_BLEND_DESC& rt : desc.BlendState.RenderTarget) - if (rt.LogicOpEnable) return E_INVALIDARG; - } else { - const D3D12_RENDER_TARGET_BLEND_DESC& rt0 = desc.BlendState.RenderTarget[0]; - if (rt0.BlendEnable && rt0.LogicOpEnable) return E_INVALIDARG; - if (rt0.LogicOpEnable && unsigned(rt0.LogicOp) > D3D12_LOGIC_OP_OR_INVERTED) return E_INVALIDARG; - } - if (desc.HS.BytecodeLength || desc.DS.BytecodeLength || desc.StreamOutput.NumEntries) { - log_once("graphics pipeline stage not supported yet (hull/domain/stream output):", 0); - return E_NOTIMPL; - } - // A geometry shader is the translator's Vulkan geometry stage (docs/design.md, "Geometry shaders"): it takes - // triangles and emits a triangle strip. It needs the geometryShader feature, and the PSO's topology type must - // be its input primitive, as D3D12 requires. - const bool geometry = desc.GS.pShaderBytecode && desc.GS.BytecodeLength; - if (geometry && !device_.info.features.geometryShader) { - log_once("geometry shaders need the Vulkan geometryShader feature; stage", 0); - return E_NOTIMPL; - } - if (geometry && desc.PrimitiveTopologyType != D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE) { - log_once("a translated geometry shader takes triangles; topology type", desc.PrimitiveTopologyType); - return E_INVALIDARG; - } - const UINT samples = desc.SampleDesc.Count; - if (!samples || samples > D3D12_MAX_MULTISAMPLE_SAMPLE_COUNT || (samples & (samples - 1))) { - log_once("invalid graphics pipeline sample count:", int(samples)); - return E_INVALIDARG; - } - // D3D12 takes quality 0 and the two pattern values (measured natively on an RX 7800 XT, a Radeon iGPU and - // WARP: 0, D3D12_STANDARD_MULTISAMPLE_PATTERN and D3D12_CENTER_MULTISAMPLE_PATTERN succeed, 1 is - // E_INVALIDARG, as NumQualityLevels is 1). The standard pattern is Vulkan's standard sample positions, so it - // is quality 0 here. The centre pattern puts every sample at the pixel centre, which needs custom sample - // locations: refused with a log until those are set. - if (desc.SampleDesc.Quality == DXGI_CENTER_MULTISAMPLE_QUALITY_PATTERN) { - log_once("D3D12_CENTER_MULTISAMPLE_PATTERN needs custom sample locations (not set yet); samples", - int(samples)); - return E_NOTIMPL; - } - if (desc.SampleDesc.Quality != 0 && desc.SampleDesc.Quality != DXGI_STANDARD_MULTISAMPLE_QUALITY_PATTERN) { - log_once("invalid graphics pipeline sample quality:", int(desc.SampleDesc.Quality)); - return E_INVALIDARG; - } - const leonida::ShaderLibrary* library = device_.library(); - if (!library) return E_FAIL; - - struct Stage { - const char* name; - VkShaderStageFlagBits bit; - const D3D12_SHADER_BYTECODE& code; - const leonida::ShaderEntry* entry = nullptr; - std::vector fssm; - std::vector words; - }; - Stage stages[3] = {mesh ? Stage{"ms", VK_SHADER_STAGE_MESH_BIT_EXT, *ms} - : Stage{"vs", VK_SHADER_STAGE_VERTEX_BIT, desc.VS}, - {"gs", VK_SHADER_STAGE_GEOMETRY_BIT, desc.GS}, - {"ps", VK_SHADER_STAGE_FRAGMENT_BIT, desc.PS}}; - // stage_infos.size() indexes the recipe's per-stage required-size structs: one for every table entry. - static_assert(std::size(stages) <= std::size(decltype(recipe_.required_sizes){}), - "Recipe::required_sizes needs an entry per graphics stage"); - bool uses_bindless = false; // a stage declares set-0 bindings: the layout holds the device's set 0 - std::vector stage_infos; - // Chained from stage_infos, which the recipe keeps for variants built at draw time: so they live in the recipe. - auto& required_sizes = recipe_.required_sizes; - const Stage* code_stage = nullptr; - // D24_UNORM_S8_UINT stored as D32_SFLOAT_S8_UINT (no D24 on the GPU): the pixel stage writes the depth D24 - // would hold, biased in D24 units and quantised (src/depth24_fragment.h, D3D-309), and the rasterizer's own - // bias is turned off. Multisampled targets keep the old path: a FragDepth write is per pixel. - const bool d24_as_float = desc.DSVFormat != DXGI_FORMAT_UNKNOWN && - vulkan_format(desc.DSVFormat, true).format == VK_FORMAT_D24_UNORM_S8_UINT && - !device_.depth_usable(VK_FORMAT_D24_UNORM_S8_UINT); - bool depth24_fragment = d24_as_float && desc.DepthStencilState.DepthEnable; - if (depth24_fragment && samples > 1) { - log_once("D24 depth stored as D32 keeps float depth bias and precision on multisampled targets; samples", - int(samples)); - depth24_fragment = false; - } - const leonida::Depth24Bias depth24_bias{desc.RasterizerState.DepthBias, - desc.RasterizerState.SlopeScaledDepthBias, - desc.RasterizerState.DepthBiasClamp}; - for (Stage& stage : stages) { - if (!stage.code.pShaderBytecode || !stage.code.BytecodeLength) continue; // no PS: depth only - stage.fssm = leonida::fssm_program( - {static_cast(stage.code.pShaderBytecode), stage.code.BytecodeLength}); - if (stage.fssm.empty()) { - log_once("shader bytecode holds no FSSM program; bytes", int(stage.code.BytecodeLength)); - return E_INVALIDARG; - } - const std::string hash = leonida::sha256_hex(stage.fssm); - // Containers with the same program can differ in their input signature or bindings: a VS must have its - // inputs fed by this input layout (else the layout check below reports it). - const bool vertex = stage.bit == VK_SHADER_STAGE_VERTEX_BIT; - stage.entry = pick_entry(library->candidates(stage.name, hash), [&](const leonida::ShaderEntry& e) { - return !vertex || layout_feeds(e, desc.InputLayout); - }); - if (!stage.entry) { - RT_LOG_ERROR("d3d12: no translated %s for FSSM sha256 %s\n", stage.name, hash.c_str()); - return E_INVALIDARG; - } - if (stage.entry->binding_count) { - if (!device_.bindless) { - RT_LOG_ERROR("d3d12: %s uses set-0 bindings; the device has no bindless set 0\n", - stage.entry->name.c_str()); - return E_NOTIMPL; - } - uses_bindless = true; - register_literal_samplers(device_, *stage.entry); - } - if (stage.bit == VK_SHADER_STAGE_MESH_BIT_EXT) { - // The SPIR-V's output arrays are sized from PSV0 (the index's max_vertices / max_primitives); Vulkan - // has no per-pipeline limit to set, so a mesh shader beyond the device's is refused here - // (docs/d3d12_vulkan.md, "Pipelines"). - if (const std::string refusal = leonida::mesh_limit_refusal(*stage.entry, device_.mesh_limits()); - !refusal.empty()) { - RT_LOG_ERROR("d3d12: %s\n", refusal.c_str()); - return E_NOTIMPL; - } - } - if (stage.entry->uses_code_base) { - if (code_stage) { - log_once("two stages read their code base; one push-constant slot holds one (question 14)", 0); - return E_NOTIMPL; - } - code_stage = &stage; - } - stage.words = library->spirv(*stage.entry); - if (stage.words.empty()) return E_FAIL; - const auto inner = leonida::conservative_raster::inner_coverage_requirements(stage.words); - if (!inner.valid) return E_INVALIDARG; - if (inner.fully_covered && - (stage.bit != VK_SHADER_STAGE_FRAGMENT_BIT || - device_.conservative_raster_tier != D3D12_CONSERVATIVE_RASTERIZATION_TIER_3 || - (inner.post_depth && !device_.conservative_post_depth_coverage))) { - log_once("FullyCoveredEXT needs an enabled Tier 3 shader ABI and device properties; stage", int(stage.bit)); - return E_NOTIMPL; - } - } - // --f16-interp-fallback (SHADER-378): align/synthesize VS decoded f16 halves for this (VS, PS) pair before - // creating the shader modules so colliding PS and high-param producers link within MoltenVK's 30 locations. - // stages[] is {vs, gs, ps} since geometry shaders joined graphics PSOs (#2109): the PS is stages[2], and with a - // GS the PS reads the GS's outputs, not the VS's, so the VS/PS halves link only applies without one. - Stage& vs_stage = stages[0]; - Stage& gs_stage = stages[1]; - Stage& ps_stage = stages[2]; - if (vs_stage.entry && ps_stage.entry && !ps_stage.entry->f16_halves.empty() && gs_stage.entry) { - log_once("--f16-interp-fallback halves are linked VS->PS only; this PSO has a geometry shader", 0); - } - if (vs_stage.entry && ps_stage.entry && !gs_stage.entry && - (!ps_stage.entry->f16_halves.empty() || !vs_stage.entry->f16_halves.empty())) { - std::string link_error; - if (!leonida::link_f16_halves(vs_stage.words, *vs_stage.entry, ps_stage.words, *ps_stage.entry, - &link_error, device_.f16_half_top_location)) { - RT_LOG_ERROR("d3d12: %s\n", link_error.c_str()); - return E_FAIL; - } - } - // A stage that declares a storage image or buffer it may write needs a device feature outside compute - // (src/spirv_stores.h). Without it the pipeline would be created all the same and break - // VUID-RuntimeSpirv-NonWritable-06340 / -06341, so the PSO is refused here with the stage named. - for (const Stage& stage : stages) { - if (!stage.entry) continue; - const bool pixel = stage.bit == VK_SHADER_STAGE_FRAGMENT_BIT; - const VkBool32 allowed = pixel ? device_.info.features.fragmentStoresAndAtomics - : device_.info.features.vertexPipelineStoresAndAtomics; - if (allowed || !leonida::spirv_declares_writable_storage(stage.words)) continue; - RT_LOG_ERROR("d3d12: %s (%s) writes a storage image or buffer, which needs the Vulkan feature %s; " - "the device does not have it enabled, so the pipeline is refused\n", - stage.entry->name.c_str(), stage.name, - pixel ? "fragmentStoresAndAtomics" : "vertexPipelineStoresAndAtomics"); - return E_NOTIMPL; - } - for (Stage& stage : stages) { - if (!stage.entry) continue; - // After the f16 link above, which can also edit the pixel shader's words. - if (depth24_fragment && stage.bit == VK_SHADER_STAGE_FRAGMENT_BIT) { - std::string why; - std::vector patched = leonida::depth24_patch_fragment(stage.words, depth24_bias, why); - if (patched.empty()) { - RT_LOG_WARN("d3d12: %s keeps float depth on a D24 target stored as D32: %s\n", - stage.entry->name.c_str(), why.c_str()); - depth24_fragment = false; - } else { - stage.words = std::move(patched); - } - } - VkShaderModuleCreateInfo module_info{VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO}; - module_info.codeSize = stage.words.size() * 4; - module_info.pCode = stage.words.data(); - VkShaderModule module = VK_NULL_HANDLE; - if (vk.vkCreateShaderModule(dev, &module_info, nullptr, &module) != VK_SUCCESS) return E_FAIL; - modules_.push_back(module); - VkPipelineShaderStageCreateInfo info{VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO}; - info.stage = stage.bit; - info.module = module; - info.pName = "main"; - subgroup_size_for(*stage.entry, required_sizes[stage_infos.size()], info); - stage_infos.push_back(info); - } - if (depth24_fragment && !ps_stage.entry) { // no pixel shader: a built-in one writes the depth - const std::vector words = leonida::depth24_depth_only_fragment(depth24_bias); - VkShaderModuleCreateInfo module_info{VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO}; - module_info.codeSize = words.size() * 4; - module_info.pCode = words.data(); - VkShaderModule module = VK_NULL_HANDLE; - if (words.empty() || vk.vkCreateShaderModule(dev, &module_info, nullptr, &module) != VK_SUCCESS) - return E_FAIL; - modules_.push_back(module); - VkPipelineShaderStageCreateInfo info{VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO}; - info.stage = VK_SHADER_STAGE_FRAGMENT_BIT; - info.module = module; - info.pName = "main"; - stage_infos.push_back(info); - } - - // Input layout -> vertex input, by semantic. A mesh pipeline has none. - std::vector attributes; - std::vector bindings; - std::vector divisors; - std::uint32_t divisor_slots = 0; - UINT slot_end[D3D12_IA_VERTEX_INPUT_RESOURCE_SLOT_COUNT] = {}; - for (UINT i = 0; !mesh && i < desc.InputLayout.NumElements; ++i) { - const D3D12_INPUT_ELEMENT_DESC& element = desc.InputLayout.pInputElementDescs[i]; - if (element.InputSlot >= D3D12_IA_VERTEX_INPUT_RESOURCE_SLOT_COUNT) return E_INVALIDARG; - VkFormat format; - UINT bytes; - if (!vertex_format(element.Format, format, bytes)) { - log_once("vertex attribute format not supported yet:", element.Format); - return E_INVALIDARG; - } - const UINT alignment = std::min(bytes, 4u); - const UINT offset = element.AlignedByteOffset == D3D12_APPEND_ALIGNED_ELEMENT - ? (slot_end[element.InputSlot] + alignment - 1) / alignment * alignment - : element.AlignedByteOffset; - slot_end[element.InputSlot] = offset + bytes; - const leonida::SignatureElement* input = nullptr; - for (const auto& e : stages[0].entry->input_signature) - if (e.system_value == 0 && e.semantic_index == element.SemanticIndex && - equal_semantic(e.semantic, element.SemanticName)) - input = &e; - if (!input) continue; // the shader does not read this element - attributes.push_back({input->register_index, element.InputSlot, format, offset}); - const bool instance = element.InputSlotClass == D3D12_INPUT_CLASSIFICATION_PER_INSTANCE_DATA; - // Step rate 0: every instance reads element 0, which a stride of 0 gives (set at each draw). - if (instance && element.InstanceDataStepRate == 0) graphics_.zero_step_slots |= 1u << element.InputSlot; - if (instance && element.InstanceDataStepRate > 1) { - if (!device_.info.vertex_attribute_divisor) { - log_once("instance step rates above 1 need vertexAttributeInstanceRateDivisor; rate", - int(element.InstanceDataStepRate)); - return E_NOTIMPL; - } - if (!(divisor_slots & (1u << element.InputSlot))) { - divisor_slots |= 1u << element.InputSlot; - divisors.push_back({element.InputSlot, element.InstanceDataStepRate}); - } - } - if (!(graphics_.vertex_slots & (1u << element.InputSlot))) { - graphics_.vertex_slots |= 1u << element.InputSlot; - bindings.push_back({element.InputSlot, 0, // stride: dynamic, from IASetVertexBuffers - instance ? VK_VERTEX_INPUT_RATE_INSTANCE : VK_VERTEX_INPUT_RATE_VERTEX}); - } - } - for (const auto& e : stages[0].entry->input_signature) { - if (e.system_value) continue; - const bool fed = std::any_of(attributes.begin(), attributes.end(), - [&](const auto& a) { return a.location == e.register_index; }); - if (!fed) { // D3D12 rejects an input layout that leaves a shader input unfed - RT_LOG_ERROR("d3d12: the input layout does not feed %s%u (register %u)\n", - e.semantic.c_str(), e.semantic_index, e.register_index); - return E_INVALIDARG; - } - } - VkPipelineInputAssemblyStateCreateInfo assembly{VK_STRUCTURE_TYPE_PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO}; - switch (mesh ? D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE : desc.PrimitiveTopologyType) { // mesh: not used - case D3D12_PRIMITIVE_TOPOLOGY_TYPE_POINT: assembly.topology = VK_PRIMITIVE_TOPOLOGY_POINT_LIST; break; - case D3D12_PRIMITIVE_TOPOLOGY_TYPE_LINE: assembly.topology = VK_PRIMITIVE_TOPOLOGY_LINE_LIST; break; - case D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE: assembly.topology = VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST; break; - default: - log_once("primitive topology type not supported:", desc.PrimitiveTopologyType); - return E_INVALIDARG; - } - if (!mesh) { // a mesh PSO has no index buffer: its strip cut is ignored - if (desc.IBStripCutValue != D3D12_INDEX_BUFFER_STRIP_CUT_VALUE_DISABLED && - desc.IBStripCutValue != D3D12_INDEX_BUFFER_STRIP_CUT_VALUE_0xFFFF && - desc.IBStripCutValue != D3D12_INDEX_BUFFER_STRIP_CUT_VALUE_0xFFFFFFFF) { - log_once("index-buffer strip cut value not supported:", desc.IBStripCutValue); - return E_INVALIDARG; - } - graphics_.strip_cut = desc.IBStripCutValue; - } - - const D3D12_RASTERIZER_DESC& r = desc.RasterizerState; - if (r.ConservativeRaster != D3D12_CONSERVATIVE_RASTERIZATION_MODE_OFF && - r.ConservativeRaster != D3D12_CONSERVATIVE_RASTERIZATION_MODE_ON) return E_INVALIDARG; - if (r.ConservativeRaster == D3D12_CONSERVATIVE_RASTERIZATION_MODE_ON) { - if (device_.conservative_raster_tier == D3D12_CONSERVATIVE_RASTERIZATION_TIER_NOT_SUPPORTED) { - log_once("conservative rasterization needs enabled VK_EXT_conservative_rasterization and Tier 1 precision", 1); - return E_INVALIDARG; - } - if (r.FillMode != D3D12_FILL_MODE_SOLID || - desc.PrimitiveTopologyType != D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE) return E_INVALIDARG; - // Target-independent rasterization is a separate pipeline path; do not silently ignore its count. - if (r.ForcedSampleCount) return E_NOTIMPL; - } - VkPipelineRasterizationStateCreateInfo raster{VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_STATE_CREATE_INFO}; - raster.polygonMode = r.FillMode == D3D12_FILL_MODE_WIREFRAME ? VK_POLYGON_MODE_LINE : VK_POLYGON_MODE_FILL; - raster.cullMode = r.CullMode == D3D12_CULL_MODE_FRONT ? VK_CULL_MODE_FRONT_BIT - : r.CullMode == D3D12_CULL_MODE_BACK ? VK_CULL_MODE_BACK_BIT - : VK_CULL_MODE_NONE; - // With the negative-height viewport, framebuffer winding matches D3D12's screen-space winding. - raster.frontFace = r.FrontCounterClockwise ? VK_FRONT_FACE_COUNTER_CLOCKWISE : VK_FRONT_FACE_CLOCKWISE; - // The D24-as-D32 pixel stage applies the bias itself, in D24 units (depth24_fragment above): the - // rasterizer's bias stays off and zero, so its clamp needs no depthBiasClamp feature either. - raster.depthBiasEnable = !depth24_fragment && (r.DepthBias || r.SlopeScaledDepthBias != 0.0f); - if (raster.depthBiasEnable) { - raster.depthBiasConstantFactor = float(r.DepthBias); - raster.depthBiasClamp = r.DepthBiasClamp; - raster.depthBiasSlopeFactor = r.SlopeScaledDepthBias; - } - raster.lineWidth = 1.0f; - // No depth clipping: fragments outside the viewport's depth range are kept and their depth clamped to it, as - // D3D12 clamps output depth to MinDepth..MaxDepth anyway (needs depthClamp, checked below). - raster.depthClampEnable = r.DepthClipEnable ? VK_FALSE : VK_TRUE; - - VkPipelineMultisampleStateCreateInfo multisample{VK_STRUCTURE_TYPE_PIPELINE_MULTISAMPLE_STATE_CREATE_INFO}; - multisample.rasterizationSamples = VkSampleCountFlagBits(samples); - const VkSampleMask sample_mask = desc.SampleMask; - multisample.pSampleMask = &sample_mask; - multisample.alphaToCoverageEnable = desc.BlendState.AlphaToCoverageEnable; - - const D3D12_DEPTH_STENCIL_DESC& ds = desc.DepthStencilState; - VkPipelineDepthStencilStateCreateInfo depth{VK_STRUCTURE_TYPE_PIPELINE_DEPTH_STENCIL_STATE_CREATE_INFO}; - depth.depthTestEnable = ds.DepthEnable; - depth.depthWriteEnable = ds.DepthEnable && ds.DepthWriteMask == D3D12_DEPTH_WRITE_MASK_ALL; - depth.depthCompareOp = compare_op(ds.DepthFunc); - depth.stencilTestEnable = ds.StencilEnable; - depth.front = stencil_face(ds.FrontFace, ds.StencilReadMask, ds.StencilWriteMask); - depth.back = stencil_face(ds.BackFace, ds.StencilReadMask, ds.StencilWriteMask); - - std::vector blends(desc.NumRenderTargets); - for (UINT i = 0; i < desc.NumRenderTargets; ++i) { - const D3D12_RENDER_TARGET_BLEND_DESC& b = - desc.BlendState.RenderTarget[desc.BlendState.IndependentBlendEnable ? i : 0]; - blends[i].blendEnable = b.BlendEnable; - blends[i].srcColorBlendFactor = blend_factor(b.SrcBlend); - blends[i].dstColorBlendFactor = blend_factor(b.DestBlend); - blends[i].colorBlendOp = blend_op(b.BlendOp); - blends[i].srcAlphaBlendFactor = blend_factor(b.SrcBlendAlpha); - blends[i].dstAlphaBlendFactor = blend_factor(b.DestBlendAlpha); - blends[i].alphaBlendOp = blend_op(b.BlendOpAlpha); - blends[i].colorWriteMask = b.RenderTargetWriteMask & 0xf; // R, G, B, A in both APIs - // B8G8R8X8 has no alpha, so blending reads destination alpha as 1 there (WARP and AMD's D3D12 driver), - // where its BGRA8 Vulkan image would read the X byte. For colour SRC_ALPHA_SAT is min(As, 1 - Ad), so 0; - // for alpha it is 1 in both APIs already. - if (alpha_unused(desc.RTVFormats[i])) { - const auto dest_alpha_one = [](VkBlendFactor& factor, bool colour) { - if (factor == VK_BLEND_FACTOR_DST_ALPHA) factor = VK_BLEND_FACTOR_ONE; - else if (factor == VK_BLEND_FACTOR_ONE_MINUS_DST_ALPHA) factor = VK_BLEND_FACTOR_ZERO; - else if (colour && factor == VK_BLEND_FACTOR_SRC_ALPHA_SATURATE) factor = VK_BLEND_FACTOR_ZERO; - }; - dest_alpha_one(blends[i].srcColorBlendFactor, true); - dest_alpha_one(blends[i].dstColorBlendFactor, true); - dest_alpha_one(blends[i].srcAlphaBlendFactor, false); - dest_alpha_one(blends[i].dstAlphaBlendFactor, false); - } - } - VkPipelineColorBlendStateCreateInfo blend{VK_STRUCTURE_TYPE_PIPELINE_COLOR_BLEND_STATE_CREATE_INFO}; - blend.attachmentCount = std::uint32_t(blends.size()); - blend.pAttachments = blends.data(); - // A logic op replaces blending for every target in Vulkan (one per pipeline), and D3D12 takes it from - // RenderTarget[0]. Vulkan applies it to integer and normalized formats and skips float ones. - const D3D12_RENDER_TARGET_BLEND_DESC& first = desc.BlendState.RenderTarget[0]; - if (desc.NumRenderTargets && first.LogicOpEnable) { - if (unsigned(first.LogicOp) > D3D12_LOGIC_OP_OR_INVERTED) return E_INVALIDARG; - blend.logicOpEnable = VK_TRUE; - blend.logicOp = logic_op(first.LogicOp); - } - - // State that needs a Vulkan feature the device did not enable (VulkanDeviceInfo::features) is refused, rather - // than handed to the driver against the spec. - const VkPhysicalDeviceFeatures& features = device_.info.features; - const auto refuse = [&](const char* what, int value) { - log_once(what, value); - return E_NOTIMPL; - }; - if (raster.polygonMode != VK_POLYGON_MODE_FILL && !features.fillModeNonSolid) - return refuse("wireframe fill needs fillModeNonSolid, which the device lacks; fill mode", r.FillMode); - if (raster.depthBiasEnable && raster.depthBiasClamp != 0.0f && !features.depthBiasClamp) - return refuse("a depth-bias clamp needs depthBiasClamp, which the device lacks; clamp x1000", - int(raster.depthBiasClamp * 1000)); - for (std::size_t i = 1; i < blends.size(); ++i) - if (std::memcmp(&blends[i], &blends[0], sizeof(blends[0])) != 0 && !features.independentBlend) - return refuse("per-render-target blend state needs independentBlend, which the device lacks; target", - int(i)); - const auto src1 = [](VkBlendFactor f) { - return f == VK_BLEND_FACTOR_SRC1_COLOR || f == VK_BLEND_FACTOR_ONE_MINUS_SRC1_COLOR || - f == VK_BLEND_FACTOR_SRC1_ALPHA || f == VK_BLEND_FACTOR_ONE_MINUS_SRC1_ALPHA; - }; - for (const auto& b : blends) - if (b.blendEnable && !features.dualSrcBlend && - (src1(b.srcColorBlendFactor) || src1(b.dstColorBlendFactor) || src1(b.srcAlphaBlendFactor) || - src1(b.dstAlphaBlendFactor))) - return refuse("SRC1 blend factors need dualSrcBlend, which the device lacks; factor", - int(b.srcColorBlendFactor)); - if (blend.logicOpEnable && !features.logicOp) - return refuse("logic ops need logicOp, which the device lacks; op", int(first.LogicOp)); - if (raster.depthClampEnable && !features.depthClamp) - return refuse("DepthClipEnable = FALSE needs depthClamp, which the device lacks; flag", 0); - - graphics_.color_formats.assign(desc.NumRenderTargets, VK_FORMAT_UNDEFINED); - for (UINT i = 0; i < desc.NumRenderTargets; ++i) { - if (desc.RTVFormats[i] == DXGI_FORMAT_UNKNOWN) continue; - graphics_.color_formats[i] = vulkan_format(desc.RTVFormats[i], false).format; - if (graphics_.color_formats[i] == VK_FORMAT_UNDEFINED) { - log_once("render-target format not supported yet:", desc.RTVFormats[i]); - return E_INVALIDARG; - } - } - if (desc.DSVFormat != DXGI_FORMAT_UNKNOWN) { - Format f = vulkan_format(desc.DSVFormat, true); - if (f.format == VK_FORMAT_D24_UNORM_S8_UINT && !device_.depth_usable(f.format)) - f.format = VK_FORMAT_D32_SFLOAT_S8_UINT; // as CreateCommittedResource does - graphics_.depth_format = f.format; - graphics_.depth_aspects = f.aspects; - } - if (samples > 1) { - const auto& dinfo = device_.info; - const bool has_color = std::any_of(graphics_.color_formats.begin(), graphics_.color_formats.end(), - [](VkFormat f) { return f != VK_FORMAT_UNDEFINED; }); - const bool has_depth = graphics_.depth_format != VK_FORMAT_UNDEFINED; - if (const auto get_props = reinterpret_cast( - dinfo.get_instance_proc ? dinfo.get_instance_proc(dinfo.instance, "vkGetPhysicalDeviceProperties") - : nullptr)) { - VkPhysicalDeviceProperties props{}; - get_props(dinfo.physical, &props); - VkSampleCountFlags supported = ~VkSampleCountFlags(0); - if (has_color) supported &= props.limits.framebufferColorSampleCounts; - if (has_depth && (graphics_.depth_aspects & VK_IMAGE_ASPECT_DEPTH_BIT)) - supported &= props.limits.framebufferDepthSampleCounts; - if (has_depth && (graphics_.depth_aspects & VK_IMAGE_ASPECT_STENCIL_BIT)) - supported &= props.limits.framebufferStencilSampleCounts; - if (!has_color && !has_depth) supported &= props.limits.framebufferNoAttachmentsSampleCounts; - if (!(supported & samples)) { - log_once("multisample count not supported by framebuffer limits; samples", int(samples)); - return E_INVALIDARG; - } - } - if ((has_color || has_depth) && !device_.image_format_properties) { - log_once("cannot query per-format multisample support; samples", int(samples)); - return E_INVALIDARG; - } - for (const VkFormat fmt : graphics_.color_formats) { - if (fmt == VK_FORMAT_UNDEFINED) continue; - VkImageFormatProperties img_props{}; - if (device_.image_format_properties(dinfo.physical, fmt, VK_IMAGE_TYPE_2D, VK_IMAGE_TILING_OPTIMAL, - VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT, 0, &img_props) != VK_SUCCESS || - !(img_props.sampleCounts & samples)) { - log_once("multisample count not supported by color attachment format; samples", int(samples)); - return E_INVALIDARG; - } - } - if (has_depth) { - VkImageFormatProperties img_props{}; - if (device_.image_format_properties(dinfo.physical, graphics_.depth_format, VK_IMAGE_TYPE_2D, - VK_IMAGE_TILING_OPTIMAL, - VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT, 0, - &img_props) != VK_SUCCESS || - !(img_props.sampleCounts & samples)) { - log_once("multisample count not supported by depth/stencil attachment format; samples", - int(samples)); - return E_INVALIDARG; - } - } - } - // Every stage this path accepts reads the user SGPRs, so the range covers the whole stage table, not only the - // stages present. A stage added to the table (geometry, mesh) is covered without touching this. - // (The geometry bit only where the device has the stage: a range may not name a stage it cannot run.) - for (const Stage& stage : stages) - if (stage.bit != VK_SHADER_STAGE_GEOMETRY_BIT || device_.info.features.geometryShader) - graphics_.push_stages |= stage.bit; - const VkPushConstantRange push{graphics_.push_stages, 0, sizeof(leonida::ShaderUserData)}; - VkPipelineLayoutCreateInfo layout_info{VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO}; - layout_info.pushConstantRangeCount = 1; - layout_info.pPushConstantRanges = &push; - VkDescriptorSetLayout set0_layout = VK_NULL_HANDLE; - if (uses_bindless) { - set0_layout = device_.bindless->layout(); - layout_info.setLayoutCount = 1; - layout_info.pSetLayouts = &set0_layout; - graphics_.bindless_set = device_.bindless->set(); - } - if (vk.vkCreatePipelineLayout(dev, &layout_info, nullptr, &graphics_.layout) != VK_SUCCESS) return E_FAIL; - - // Kept for variants: a draw that leaves a slot unbound needs this pipeline with that format undefined. - graphics_.mesh = mesh; - recipe_.mesh = mesh; - recipe_.stages = std::move(stage_infos); - recipe_.attributes = std::move(attributes); - recipe_.bindings = std::move(bindings); - recipe_.divisors = std::move(divisors); - recipe_.assembly = assembly; - recipe_.raster = raster; - recipe_.conservative = r.ConservativeRaster == D3D12_CONSERVATIVE_RASTERIZATION_MODE_ON; - recipe_.multisample = multisample; - graphics_.samples = samples; - recipe_.sample_mask = sample_mask; - recipe_.depth = depth; - recipe_.blends = std::move(blends); - recipe_.blend = blend; - graphics_.pipeline = build(0); - if (!graphics_.pipeline) return E_FAIL; - graphics_.variant = [this](std::uint32_t unbound) { return variant(unbound); }; - - if (code_stage) { - VkDeviceSize offset = 0; - if (!device_.arena_allocate(code_stage->fssm.size(), 256, offset, DeviceState::arena_shader)) return E_OUTOFMEMORY; - std::memcpy(device_.arena.mapped + offset, code_stage->fssm.data(), code_stage->fssm.size()); - code_bytes_ = code_stage->fssm.size(); - code_base_ = offset; - graphics_.code_base = offset; - } - device_.context->add_graphics_pipeline(id(), graphics_); - registered_ = true; - is_graphics_ = true; - return S_OK; - } - - HRESULT create_compute(const D3D12_COMPUTE_PIPELINE_STATE_DESC& desc) { - auto& vk = device_.context->vk; - const VkDevice dev = device_.info.device; - if (!desc.CS.pShaderBytecode || !desc.CS.BytecodeLength) return E_INVALIDARG; - if (desc.NodeMask & ~1u) return E_INVALIDARG; - if (static_cast(desc.Flags) & ~kKnownPipelineStateFlags) return E_INVALIDARG; - if (!device_.arena.mapped) { - log_once("pipelines need the GPU address arena (bufferDeviceAddress); stage", 0); - return E_NOTIMPL; - } - if (!push_constants_fit()) return E_NOTIMPL; - // The game's FSSM program, or the FidelityFX DLL's FSPX kind-6 program: in a DXBC container's ACCC part at - // slot 62, bare from a slot-67 description (docs/fspx.md, "Run-time lookup"). - const leonida::ComputeProgram program = leonida::compute_program( - {static_cast(desc.CS.pShaderBytecode), desc.CS.BytecodeLength}); - if (program.kind == leonida::ComputeProgram::Kind::none) { - log_once("compute shader bytecode holds no FSSM or FSPX program; bytes", int(desc.CS.BytecodeLength)); - return E_INVALIDARG; - } - const leonida::ShaderLibrary* library = device_.library(); - if (!library) return E_FAIL; - // A binding-free entry wins over one with bindings for the same program (pick_entry). - // An FSPX program from a container is matched on its kind-0 state too; a bare kind-6 program whose - // translations differ is ambiguous without that state and is refused (program_candidates). - bool ambiguous = false; - const leonida::ShaderEntry* entry = pick_entry(library->program_candidates("cs", program, &ambiguous), - [](const leonida::ShaderEntry&) { return true; }); - if (!entry) { - const bool fspx = program.kind == leonida::ComputeProgram::Kind::fspx; - if (ambiguous) - RT_LOG_ERROR("d3d12: FSPX kind-6 program sha256 %s is ambiguous without its kind-0 " - "state: its translations differ\n", leonida::sha256_hex(program.bytes).c_str()); - else - RT_LOG_ERROR("d3d12: no translated compute shader for %s sha256 %s\n", - fspx ? (program.state.empty() ? "FSPX kind-6" : "FSPX kind-6 and kind-0") : "FSSM", - leonida::sha256_hex(program.bytes).c_str()); - return E_INVALIDARG; - } - // Set 0 (bindless images, samplers, the descriptor hash table): the device keeps it, and a pipeline whose - // shader declares bindings has it in its layout and has it bound at every dispatch. - if (entry->binding_count && !device_.bindless) { - RT_LOG_ERROR("d3d12: %s uses set-0 bindings; the device has no bindless set 0\n", - entry->name.c_str()); - return E_NOTIMPL; - } - if (entry->binding_count) register_literal_samplers(device_, *entry); - // SHADER-309: a module over the device's maxComputeSharedMemorySize is invalid usage that spirv-val accepts - // and RADV dies on (#1721); some drivers report 32768. Refuse it here instead of creating the pipeline. - if (entry->lds_bytes) { - const auto& dinfo = device_.info; - if (const auto get_props = reinterpret_cast( - dinfo.get_instance_proc ? dinfo.get_instance_proc(dinfo.instance, "vkGetPhysicalDeviceProperties") - : nullptr)) { - VkPhysicalDeviceProperties props{}; - get_props(dinfo.physical, &props); - if (entry->lds_bytes > props.limits.maxComputeSharedMemorySize) { - RT_LOG_ERROR("d3d12: %s declares %u bytes of workgroup memory, over the device's " - "maxComputeSharedMemorySize %u\n", - entry->name.c_str(), unsigned(entry->lds_bytes), - unsigned(props.limits.maxComputeSharedMemorySize)); - return E_NOTIMPL; - } - } - } - const std::vector words = library->spirv(*entry); - if (words.empty()) { - RT_LOG_ERROR("d3d12: %s.spv is missing or not SPIR-V\n", entry->name.c_str()); - return E_FAIL; - } - - VkShaderModuleCreateInfo module_info{VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO}; - module_info.codeSize = words.size() * 4; - module_info.pCode = words.data(); - if (vk.vkCreateShaderModule(dev, &module_info, nullptr, &module_) != VK_SUCCESS) return E_FAIL; - const VkPushConstantRange push{VK_SHADER_STAGE_COMPUTE_BIT, 0, sizeof(leonida::ShaderUserData)}; - VkPipelineLayoutCreateInfo layout_info{VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO}; - layout_info.pushConstantRangeCount = 1; - layout_info.pPushConstantRanges = &push; - VkDescriptorSetLayout set0_layout = VK_NULL_HANDLE; - if (entry->binding_count) { - set0_layout = device_.bindless->layout(); - layout_info.setLayoutCount = 1; - layout_info.pSetLayouts = &set0_layout; - pipeline_.bindless_set = device_.bindless->set(); - } - if (vk.vkCreatePipelineLayout(dev, &layout_info, nullptr, &pipeline_.layout) != VK_SUCCESS) return E_FAIL; - VkComputePipelineCreateInfo pipeline_info{VK_STRUCTURE_TYPE_COMPUTE_PIPELINE_CREATE_INFO}; - pipeline_info.stage = {VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO}; - pipeline_info.stage.stage = VK_SHADER_STAGE_COMPUTE_BIT; - pipeline_info.stage.module = module_; - pipeline_info.stage.pName = "main"; - VkPipelineShaderStageRequiredSubgroupSizeCreateInfo required_size{}; - subgroup_size_for(*entry, required_size, pipeline_info.stage); - pipeline_info.layout = pipeline_.layout; - if (vk.vkCreateComputePipelines(dev, device_.pipeline_cache(), 1, &pipeline_info, nullptr, &pipeline_.pipeline) != - VK_SUCCESS) - return E_FAIL; - - // The code base: shaders read constant tables embedded in their own program through s_getpc_b64. The - // translator's code offsets are into the bytes the key hashes (the FSSM blob, or the kind-6 program). - const std::vector& code = program.bytes; - VkDeviceSize offset = 0; - if (!device_.arena_allocate(code.size(), 256, offset, DeviceState::arena_shader)) return E_OUTOFMEMORY; - std::memcpy(device_.arena.mapped + offset, code.data(), code.size()); - code_bytes_ = code.size(); - code_base_ = offset; - pipeline_.code_base = offset; - device_.context->add_pipeline(id(), pipeline_); - registered_ = true; - return S_OK; - } - -private: - // What a graphics pipeline is made from, so variants can be built at draw time. - struct Recipe { - bool mesh = false; // no vertex input or input assembly state, and no dynamic topology or strides - std::vector stages; - // One per entry of create_graphics's stage table (VS, GS, PS), static_assert there; what `stages` chain. - VkPipelineShaderStageRequiredSubgroupSizeCreateInfo required_sizes[3]{}; - std::vector attributes; - std::vector bindings; - std::vector divisors; - VkPipelineInputAssemblyStateCreateInfo assembly{}; - VkPipelineRasterizationStateCreateInfo raster{}; - bool conservative = false; - VkPipelineMultisampleStateCreateInfo multisample{}; - VkSampleMask sample_mask = ~0u; - VkPipelineDepthStencilStateCreateInfo depth{}; - std::vector blends; - VkPipelineColorBlendStateCreateInfo blend{}; - }; - - // The graphics pipeline with the formats of the `unbound` slots (leonida::GraphicsPipeline::variant) undefined. - VkPipeline build(std::uint32_t unbound) const { - // The stride state is last: a pipeline without vertex bindings (a full-screen pass that builds its vertices - // from SV_VertexID) leaves it out, since no vkCmdBindVertexBuffers2 would ever set it - // (VUID-vkCmdDraw-pStrides-04913). - static constexpr VkDynamicState dynamic_states[] = { - VK_DYNAMIC_STATE_VIEWPORT, VK_DYNAMIC_STATE_SCISSOR, - VK_DYNAMIC_STATE_PRIMITIVE_TOPOLOGY, VK_DYNAMIC_STATE_PRIMITIVE_RESTART_ENABLE, - VK_DYNAMIC_STATE_STENCIL_REFERENCE, VK_DYNAMIC_STATE_BLEND_CONSTANTS, - VK_DYNAMIC_STATE_VERTEX_INPUT_BINDING_STRIDE}; - const Recipe& r = recipe_; - std::vector colors = graphics_.color_formats; - for (std::size_t slot = 0; slot < colors.size(); ++slot) - if (unbound & (1u << slot)) colors[slot] = VK_FORMAT_UNDEFINED; - const bool depth_bound = !(unbound & leonida::GraphicsPipeline::unbound_depth); - VkPipelineRenderingCreateInfo rendering{VK_STRUCTURE_TYPE_PIPELINE_RENDERING_CREATE_INFO}; - rendering.colorAttachmentCount = std::uint32_t(colors.size()); - rendering.pColorAttachmentFormats = colors.data(); - if (depth_bound && (graphics_.depth_aspects & VK_IMAGE_ASPECT_DEPTH_BIT)) - rendering.depthAttachmentFormat = graphics_.depth_format; - if (depth_bound && (graphics_.depth_aspects & VK_IMAGE_ASPECT_STENCIL_BIT)) - rendering.stencilAttachmentFormat = graphics_.depth_format; - - VkPipelineVertexInputStateCreateInfo vertex_input{VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO}; - VkPipelineVertexInputDivisorStateCreateInfoEXT divisor_state{ - VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_DIVISOR_STATE_CREATE_INFO_EXT}; - if (!r.divisors.empty()) { - divisor_state.vertexBindingDivisorCount = std::uint32_t(r.divisors.size()); - divisor_state.pVertexBindingDivisors = r.divisors.data(); - vertex_input.pNext = &divisor_state; - } - vertex_input.vertexBindingDescriptionCount = std::uint32_t(r.bindings.size()); - vertex_input.pVertexBindingDescriptions = r.bindings.data(); - vertex_input.vertexAttributeDescriptionCount = std::uint32_t(r.attributes.size()); - vertex_input.pVertexAttributeDescriptions = r.attributes.data(); - VkPipelineViewportStateCreateInfo viewport{VK_STRUCTURE_TYPE_PIPELINE_VIEWPORT_STATE_CREATE_INFO}; - viewport.viewportCount = 1; - viewport.scissorCount = 1; - VkPipelineMultisampleStateCreateInfo multisample = r.multisample; - VkPipelineRasterizationStateCreateInfo raster = r.raster; - VkPipelineRasterizationConservativeStateCreateInfoEXT conservative{ - VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_CONSERVATIVE_STATE_CREATE_INFO_EXT}; - if (r.conservative) { - conservative.conservativeRasterizationMode = VK_CONSERVATIVE_RASTERIZATION_MODE_OVERESTIMATE_EXT; - conservative.extraPrimitiveOverestimationSize = 0.0f; - conservative.pNext = raster.pNext; - raster.pNext = &conservative; - } - multisample.pSampleMask = &r.sample_mask; - VkPipelineColorBlendStateCreateInfo blend = r.blend; - blend.attachmentCount = std::uint32_t(r.blends.size()); - blend.pAttachments = r.blends.data(); - // A mesh pipeline takes neither the topology nor the strides as dynamic state - // (VUID-VkGraphicsPipelineCreateInfo-pDynamicStates-07065 and -07066). - static constexpr VkDynamicState mesh_dynamic_states[] = {VK_DYNAMIC_STATE_VIEWPORT, VK_DYNAMIC_STATE_SCISSOR, - VK_DYNAMIC_STATE_STENCIL_REFERENCE, - VK_DYNAMIC_STATE_BLEND_CONSTANTS}; - VkPipelineDynamicStateCreateInfo dynamic{VK_STRUCTURE_TYPE_PIPELINE_DYNAMIC_STATE_CREATE_INFO}; - if (r.mesh) { - dynamic.dynamicStateCount = std::uint32_t(std::size(mesh_dynamic_states)); - dynamic.pDynamicStates = mesh_dynamic_states; - } else { - dynamic.dynamicStateCount = std::uint32_t(std::size(dynamic_states)) - (r.bindings.empty() ? 1 : 0); - dynamic.pDynamicStates = dynamic_states; - } - - VkGraphicsPipelineCreateInfo info{VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO, &rendering}; - info.stageCount = std::uint32_t(r.stages.size()); - info.pStages = r.stages.data(); - info.pVertexInputState = r.mesh ? nullptr : &vertex_input; // ignored with a mesh stage; null for clarity - info.pInputAssemblyState = r.mesh ? nullptr : &r.assembly; - info.pViewportState = &viewport; - info.pRasterizationState = &raster; - info.pMultisampleState = &multisample; - info.pDepthStencilState = &r.depth; - info.pColorBlendState = &blend; - info.pDynamicState = &dynamic; - info.layout = graphics_.layout; - VkPipeline pipeline = VK_NULL_HANDLE; - if (device_.context->vk.vkCreateGraphicsPipelines(device_.info.device, device_.pipeline_cache(), 1, - &info, nullptr, &pipeline) != VK_SUCCESS) - return VK_NULL_HANDLE; - return pipeline; - } - - // Built on first use and kept until the PSO is released (replay may call this from any queue). - VkPipeline variant(std::uint32_t unbound) { - std::lock_guard lock(variants_mutex_); - if (const auto it = variants_.find(unbound); it != variants_.end()) return it->second; - const VkPipeline pipeline = build(unbound); - if (!pipeline) { - log_once("a pipeline variant for unbound attachment slots could not be built; slots", int(unbound)); - return VK_NULL_HANDLE; - } - variants_.emplace(unbound, pipeline); - return pipeline; - } - - DeviceState& device_; - leonida::ComputePipeline pipeline_; - leonida::GraphicsPipeline graphics_; - Recipe recipe_; - std::mutex variants_mutex_; - std::map variants_; - VkShaderModule module_ = VK_NULL_HANDLE; - std::vector modules_; - VkDeviceSize code_base_ = 0; - VkDeviceSize code_bytes_ = 0; - bool registered_ = false; - bool is_graphics_ = false; - std::vector subgroup_requests_; // one per stage, in creation order - leonida::cached_pso::Key cache_key_; -}; - -void key_root_signature(leonida::cached_pso::KeyBuilder& key, ID3D12RootSignature* signature) { - if (!signature) { - key.tag("no root signature"); - } else if (const RootSignature* own = RootSignature::from(signature)) { - key.tag("root signature").text(own->content().c_str()); - } else { - const auto address = reinterpret_cast(signature); - key.tag("foreign root signature").bytes(&address, sizeof(address)); - } -} - -// A view of a texture as Create*View describes it, before the resource's own shape is applied. -struct TextureView { - DXGI_FORMAT format = DXGI_FORMAT_UNKNOWN; // UNKNOWN: the resource's - leonida::gfx10::ImageType type = leonida::gfx10::ImageType::image_2d; - UINT first_mip = 0; - UINT mip_count = ~0u; // ~0: to the last - UINT first_layer = 0; - UINT layer_count = ~0u; - UINT mapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; - UINT plane = 0; - float min_lod = 0.0f; -}; - -// In-memory pipeline library (docs/d3d12_vulkan.md sections 3.6 and 4). D3D12 cached blobs are driver-specific -// and ignored across runs; Serialize writes a versioned header so CreatePipelineLibrary recognizes our own blobs. -// As on the host runtime (d3d12_pipeline_library_host_test), a foreign, truncated or corrupt blob is E_INVALIDARG; -// one of ours from another version is D3D12_ERROR_DRIVER_VERSION_MISMATCH. A pipeline library is a device child, -// not a pageable object: the host answers E_NOINTERFACE for ID3D12Pageable. -class PipelineLibrary final - : public Child { -public: - // {6e2a9d41-7b5f-4c83-8e14-2a9d6f3c5b10} - static constexpr GUID kTag{0x6e2a9d41, 0x7b5f, 0x4c83, {0x8e, 0x14, 0x2a, 0x9d, 0x6f, 0x3c, 0x5b, 0x10}}; - - struct Header { - std::uint32_t magic; - std::uint32_t version; - std::uint32_t count; - std::uint32_t reserved; - }; - static constexpr std::uint32_t kMagic = 0x314C504Cu; // "LPL1" - static constexpr std::uint32_t kVersion = 1; - - ~PipelineLibrary() override { - std::lock_guard lock(mutex_); - for (auto& [name, pso] : entries_) - if (pso) pso->Release(); - entries_.clear(); - } - - // S_OK for a blob of ours, D3D12_ERROR_DRIVER_VERSION_MISMATCH for one of ours from another version, - // E_INVALIDARG for anything else (foreign, truncated or corrupt). - static HRESULT check_blob(const void* data, SIZE_T size) { - if (!data || size < sizeof(Header)) return E_INVALIDARG; - Header h{}; - std::memcpy(&h, data, sizeof(h)); - if (h.magic != kMagic || h.reserved != 0) return E_INVALIDARG; - return h.version == kVersion ? S_OK : D3D12_ERROR_DRIVER_VERSION_MISMATCH; - } - - HRESULT STDMETHODCALLTYPE StorePipeline(LPCWSTR name, ID3D12PipelineState* pipeline) override { - if (!name || !*name || !pipeline) return E_INVALIDARG; - if (!PipelineState::from(pipeline)) return E_INVALIDARG; - std::lock_guard lock(mutex_); - auto [it, inserted] = entries_.emplace(name, pipeline); - if (!inserted) return E_INVALIDARG; - pipeline->AddRef(); - return S_OK; - } - - HRESULT STDMETHODCALLTYPE LoadGraphicsPipeline(LPCWSTR name, const D3D12_GRAPHICS_PIPELINE_STATE_DESC* desc, - REFIID riid, void** out) override { - if (!out) return E_INVALIDARG; // the host runtime's answer (not E_POINTER) - *out = nullptr; - if (!name || !*name || !desc) return E_INVALIDARG; - return load_entry(name, false, true, riid, out); - } - - HRESULT STDMETHODCALLTYPE LoadComputePipeline(LPCWSTR name, const D3D12_COMPUTE_PIPELINE_STATE_DESC* desc, - REFIID riid, void** out) override { - if (!out) return E_INVALIDARG; // the host runtime's answer (not E_POINTER) - *out = nullptr; - if (!name || !*name || !desc) return E_INVALIDARG; - return load_entry(name, true, false, riid, out); - } - - HRESULT STDMETHODCALLTYPE LoadPipeline(LPCWSTR name, const D3D12_PIPELINE_STATE_STREAM_DESC* desc, - REFIID riid, void** out) override { - if (!out) return E_INVALIDARG; // the host runtime's answer (not E_POINTER) - *out = nullptr; - if (!name || !*name || !desc || !desc->SizeInBytes || !desc->pPipelineStateSubobjectStream) return E_INVALIDARG; - return load_entry(name, false, false, riid, out); - } - - SIZE_T STDMETHODCALLTYPE GetSerializedSize() override { return sizeof(Header); } - - HRESULT STDMETHODCALLTYPE Serialize(void* data, SIZE_T size) override { - if (!data || size < sizeof(Header)) return E_INVALIDARG; - std::lock_guard lock(mutex_); - const Header h{kMagic, kVersion, static_cast(entries_.size()), 0}; - std::memcpy(data, &h, sizeof(h)); - return S_OK; - } - -private: - HRESULT load_entry(LPCWSTR name, bool require_compute, bool require_graphics, REFIID riid, void** out) { - std::lock_guard lock(mutex_); - const auto it = entries_.find(name); - if (it == entries_.end()) return E_INVALIDARG; - PipelineState* ps = PipelineState::from(it->second); - if (!ps) return E_INVALIDARG; - if (require_compute && !ps->compute()) return E_INVALIDARG; - if (require_graphics && !ps->graphics()) return E_INVALIDARG; - return it->second->QueryInterface(riid, out); - } - - std::mutex mutex_; - std::unordered_map entries_; -}; - -// Process-wide backing for ID3D12Device9::CreateShaderCacheSession and ID3D12ShaderCacheSession (D3D-34). -// Sessions in the same process sharing (Identifier, Mode, disk_path) share their entries; a live session with a -// different Version returns DXGI_ERROR_ALREADY_EXISTS, while reopening after all sessions close clears and recreates -// the cache. MODE_MEMORY discards its entries when the final session is released; MODE_DISK persists entries to a -// versioned binary file via unique per-writer temp files and atomic replacement. -struct ShaderCacheKey { - GUID identifier{}; - D3D12_SHADER_CACHE_MODE mode = D3D12_SHADER_CACHE_MODE_MEMORY; - std::wstring disk_path; // empty for MODE_MEMORY - - bool operator<(const ShaderCacheKey& other) const { - const int cmp = std::memcmp(&identifier, &other.identifier, sizeof(GUID)); - if (cmp != 0) return cmp < 0; - if (mode != other.mode) return mode < other.mode; - return disk_path < other.disk_path; - } -}; - -struct ShaderCacheStore { - static constexpr std::uint32_t kDiskMagic = 0x3143534Cu; // "LSC1" - static constexpr std::uint32_t kDiskFormatVersion = 2; - static constexpr UINT kDefaultMaxMemoryBytes = 1024u; - static constexpr UINT kDefaultMaxMemoryEntries = 128u; - static constexpr UINT kDefaultMaxValueFileBytes = 128u * 1024u * 1024u; - - struct DiskHeader { - std::uint32_t magic; - std::uint32_t format_version; - std::uint32_t entry_count; - std::uint32_t reserved; - std::uint64_t cache_version; - }; - - std::mutex mutex; - std::map> entries; - std::size_t total_bytes = 0; - std::uint32_t live_sessions = 0; - UINT64 version = 0; - bool delete_on_destroy = false; - std::filesystem::path disk_path; - - void load_from_disk_locked(UINT64 expected_version, UINT max_file_bytes) { - if (disk_path.empty()) return; - std::error_code ec; - const std::uintmax_t file_size = std::filesystem::file_size(disk_path, ec); - if (ec || file_size < sizeof(DiskHeader)) return; - std::ifstream in(disk_path, std::ios::binary); - if (!in) return; - DiskHeader header{}; - if (!in.read(reinterpret_cast(&header), sizeof(header))) return; - if (header.magic != kDiskMagic || header.format_version != kDiskFormatVersion || header.reserved != 0) return; - if (header.cache_version != expected_version) { - in.close(); - std::filesystem::remove(disk_path, ec); - return; - } - std::uint64_t remaining = static_cast(file_size) - sizeof(DiskHeader); - if (header.entry_count > remaining / 8u) return; - std::map> loaded; - std::size_t bytes = 0; - for (std::uint32_t i = 0; i < header.entry_count; ++i) { - if (remaining < 8u) return; - std::uint32_t lens[2]{}; - if (!in.read(reinterpret_cast(lens), sizeof(lens))) return; - remaining -= 8u; - const std::uint64_t key_len = lens[0]; - const std::uint64_t val_len = lens[1]; - if (!key_len || !val_len || key_len > remaining || val_len > remaining - key_len) return; - if (val_len > max_file_bytes || bytes > max_file_bytes - val_len) return; - std::string k(static_cast(key_len), '\0'); - std::vector v(static_cast(val_len)); - if (!in.read(k.data(), static_cast(key_len)) || - !in.read(reinterpret_cast(v.data()), static_cast(val_len))) - return; - remaining -= key_len + val_len; - loaded.emplace(std::move(k), std::move(v)); - bytes += static_cast(val_len); - } - entries = std::move(loaded); - total_bytes = bytes; - } - - bool save_to_disk_locked() const { - if (disk_path.empty()) return true; - std::error_code ec; - std::filesystem::create_directories(disk_path.parent_path(), ec); - static std::atomic write_seq{0}; - const std::uint64_t seq = write_seq.fetch_add(1, std::memory_order_relaxed); - wchar_t suffix[64]{}; - std::swprintf(suffix, std::size(suffix), L".%lu.%lu.%llu.tmp", - static_cast(GetCurrentProcessId()), - static_cast(GetCurrentThreadId()), static_cast(seq)); - std::filesystem::path tmp = disk_path; - tmp += suffix; - { - std::ofstream out(tmp, std::ios::binary | std::ios::trunc); - if (!out) return false; - const DiskHeader header{kDiskMagic, kDiskFormatVersion, static_cast(entries.size()), 0, - version}; - out.write(reinterpret_cast(&header), sizeof(header)); - for (const auto& [k, v] : entries) { - const std::uint32_t lens[2] = {static_cast(k.size()), - static_cast(v.size())}; - out.write(reinterpret_cast(lens), sizeof(lens)); - out.write(k.data(), static_cast(k.size())); - out.write(reinterpret_cast(v.data()), static_cast(v.size())); - } - if (!out.good()) return false; - } - if (!MoveFileExW(tmp.c_str(), disk_path.c_str(), MOVEFILE_REPLACE_EXISTING)) { - std::filesystem::remove(tmp, ec); - return false; - } - return true; - } - - void clear() { - std::lock_guard lock(mutex); - entries.clear(); - total_bytes = 0; - if (!disk_path.empty()) { - std::error_code ec; - std::filesystem::remove(disk_path, ec); - } - } -}; - -std::filesystem::path default_shader_cache_dir() { - std::error_code ec; - const auto tmp = std::filesystem::temp_directory_path(ec); - if (ec || tmp.empty()) return {}; - return tmp / L"leonida_shader_cache"; -} - -struct ShaderCacheRegistry { - std::mutex mutex; - std::map> stores; - std::atomic disabled{false}; - - HRESULT acquire(const ShaderCacheKey& key, UINT64 version, UINT max_file_bytes, - std::shared_ptr& out) { - if (disabled.load(std::memory_order_relaxed)) return DXGI_ERROR_NOT_CURRENTLY_AVAILABLE; - std::lock_guard lock(mutex); - if (disabled.load(std::memory_order_relaxed)) return DXGI_ERROR_NOT_CURRENTLY_AVAILABLE; - auto it = stores.find(key); - if (it != stores.end()) { - if (it->second->version != version) return DXGI_ERROR_ALREADY_EXISTS; - ++it->second->live_sessions; - out = it->second; - return S_OK; - } - auto store = std::make_shared(); - store->version = version; - if (key.mode == D3D12_SHADER_CACHE_MODE_DISK && !key.disk_path.empty()) { - store->disk_path = key.disk_path; - std::lock_guard store_lock(store->mutex); - store->load_from_disk_locked(version, max_file_bytes); - } - store->live_sessions = 1; - stores.emplace(key, store); - out = std::move(store); - return S_OK; - } - - void mark_delete_on_destroy(const std::shared_ptr& store) { - std::lock_guard lock(mutex); - if (store) store->delete_on_destroy = true; - } - - void release(const ShaderCacheKey& key, const std::shared_ptr& store) { - std::lock_guard lock(mutex); - if (!store) return; - if (store->live_sessions > 0) --store->live_sessions; - if (store->live_sessions == 0) { - if (store->delete_on_destroy && !store->disk_path.empty()) { - std::error_code ec; - std::filesystem::remove(store->disk_path, ec); - } - // Discard both idle MEMORY stores (per D3D12 spec) and idle DISK stores (so reopening reloads from disk). - const auto it = stores.find(key); - if (it != stores.end() && it->second == store) stores.erase(it); - } - } - - void clear_all() { - std::vector> snapshot; - { - std::lock_guard lock(mutex); - snapshot.reserve(stores.size()); - for (const auto& [k, v] : stores) snapshot.push_back(v); - } - for (const auto& store : snapshot) store->clear(); - // Also remove inactive and prior-run disk caches stored in the default cache directory (non-USE_WORKING_DIR). - const auto default_dir = default_shader_cache_dir(); - if (!default_dir.empty()) { - std::error_code ec; - if (std::filesystem::exists(default_dir, ec)) { - for (const auto& entry : std::filesystem::directory_iterator(default_dir, ec)) { - if (ec) break; - if (!entry.is_regular_file(ec)) continue; - const auto fname = entry.path().filename().wstring(); - if (fname.rfind(L"leonida_sc_", 0) == 0) std::filesystem::remove(entry.path(), ec); - } - } - } - } -}; - -ShaderCacheRegistry& process_shader_cache_registry() { - static auto* registry = new ShaderCacheRegistry(); - return *registry; -} - -std::filesystem::path shader_cache_disk_path(const D3D12_SHADER_CACHE_SESSION_DESC& desc, - const VkPhysicalDeviceProperties& gpu_props) { - std::error_code ec; - std::filesystem::path dir = (desc.Flags & D3D12_SHADER_CACHE_FLAG_USE_WORKING_DIR) - ? std::filesystem::current_path(ec) - : default_shader_cache_dir(); - if (ec || dir.empty()) return {}; - wchar_t name[160]{}; - const auto& g = desc.Identifier; - if (desc.Flags & D3D12_SHADER_CACHE_FLAG_DRIVER_VERSIONED) { - std::swprintf(name, std::size(name), - L"leonida_sc_%08lx%04x%04x%02x%02x%02x%02x%02x%02x%02x%02x_d%04x_%04x_%08x.bin", - static_cast(g.Data1), g.Data2, g.Data3, g.Data4[0], g.Data4[1], g.Data4[2], - g.Data4[3], g.Data4[4], g.Data4[5], g.Data4[6], g.Data4[7], gpu_props.vendorID, - gpu_props.deviceID, gpu_props.driverVersion); - } else { - std::swprintf(name, std::size(name), L"leonida_sc_%08lx%04x%04x%02x%02x%02x%02x%02x%02x%02x%02x.bin", - static_cast(g.Data1), g.Data2, g.Data3, g.Data4[0], g.Data4[1], g.Data4[2], - g.Data4[3], g.Data4[4], g.Data4[5], g.Data4[6], g.Data4[7]); - } - return dir / name; -} - -class ShaderCacheSession final - : public Child { -public: - // {9a4f1b2c-8d6e-43a7-b152-7e3c9f0d4a81} - static constexpr GUID kTag{0x9a4f1b2c, 0x8d6e, 0x43a7, {0xb1, 0x52, 0x7e, 0x3c, 0x9f, 0x0d, 0x4a, 0x81}}; - - ShaderCacheSession(const D3D12_SHADER_CACHE_SESSION_DESC& desc, const ShaderCacheKey& key, - ShaderCacheRegistry& registry, std::shared_ptr store) - : desc_(desc), key_(key), registry_(®istry), store_(std::move(store)) {} - - ~ShaderCacheSession() override { - if (registry_) registry_->release(key_, store_); - } - - HRESULT STDMETHODCALLTYPE FindValue(const void* key, UINT key_size, void* value, UINT* value_size) override { - if (!key || !key_size || !value_size) return E_INVALIDARG; - if (registry_ && registry_->disabled.load(std::memory_order_relaxed)) - return DXGI_ERROR_NOT_CURRENTLY_AVAILABLE; - std::lock_guard lock(store_->mutex); - const std::string k(static_cast(key), key_size); - const auto it = store_->entries.find(k); - if (it == store_->entries.end()) return DXGI_ERROR_NOT_FOUND; - const UINT stored_size = static_cast(it->second.size()); - if (!value) { - *value_size = stored_size; - return S_OK; - } - if (*value_size < stored_size) { - *value_size = stored_size; - return DXGI_ERROR_MORE_DATA; - } - std::memcpy(value, it->second.data(), stored_size); - *value_size = stored_size; - return S_OK; - } - - HRESULT STDMETHODCALLTYPE StoreValue(const void* key, UINT key_size, const void* value, UINT value_size) override { - if (!key || !key_size || !value || !value_size) return E_INVALIDARG; - if (registry_ && registry_->disabled.load(std::memory_order_relaxed)) - return DXGI_ERROR_NOT_CURRENTLY_AVAILABLE; - std::lock_guard lock(store_->mutex); - const std::string k(static_cast(key), key_size); - if (store_->entries.find(k) != store_->entries.end()) return DXGI_ERROR_ALREADY_EXISTS; - if (desc_.Mode == D3D12_SHADER_CACHE_MODE_MEMORY) { - const UINT max_entries = desc_.MaximumInMemoryCacheEntries ? desc_.MaximumInMemoryCacheEntries - : ShaderCacheStore::kDefaultMaxMemoryEntries; - const UINT max_bytes = desc_.MaximumInMemoryCacheSizeBytes ? desc_.MaximumInMemoryCacheSizeBytes - : ShaderCacheStore::kDefaultMaxMemoryBytes; - if (store_->entries.size() >= max_entries || value_size > max_bytes || - store_->total_bytes > max_bytes - value_size) - return DXGI_ERROR_CACHE_FULL; - } else { - const UINT max_file_bytes = desc_.MaximumValueFileSizeBytes ? desc_.MaximumValueFileSizeBytes - : ShaderCacheStore::kDefaultMaxValueFileBytes; - if (value_size > max_file_bytes || store_->total_bytes > max_file_bytes - value_size) - return DXGI_ERROR_CACHE_FULL; - } - const auto* bytes = static_cast(value); - auto [it, inserted] = store_->entries.emplace(k, std::vector(bytes, bytes + value_size)); - store_->total_bytes += value_size; - if (desc_.Mode == D3D12_SHADER_CACHE_MODE_DISK && !store_->save_to_disk_locked()) { - store_->total_bytes -= value_size; - store_->entries.erase(it); - return E_FAIL; - } - return S_OK; - } - - void STDMETHODCALLTYPE SetDeleteOnDestroy() override { - if (registry_) registry_->mark_delete_on_destroy(store_); - } - -#if defined(_MSC_VER) || !defined(_WIN32) - D3D12_SHADER_CACHE_SESSION_DESC STDMETHODCALLTYPE GetDesc() override { return desc_; } -#else - D3D12_SHADER_CACHE_SESSION_DESC* STDMETHODCALLTYPE GetDesc(D3D12_SHADER_CACHE_SESSION_DESC* out) override { - *out = desc_; - return out; - } -#endif - -private: - D3D12_SHADER_CACHE_SESSION_DESC desc_{}; - ShaderCacheKey key_{}; - ShaderCacheRegistry* registry_ = nullptr; - std::shared_ptr store_; -}; - -// The T# of a view: what the shader gets to know about it, in the structure the console's shaders read. -// False (with a log) for a view set 0 cannot show yet. -bool image_descriptor(const Resource& resource, const TextureView& view, leonida::gfx10::Image& out) { - namespace g = leonida::gfx10; - const D3D12_RESOURCE_DESC& desc = resource.desc(); - // Plane 1 of a depth-stencil texture is its stencil, viewed as X24_TYPELESS_G8_UINT (D24S8) or - // X32_TYPELESS_G8X24_UINT (D32S8): eight unsigned bits in G, as D3D12 returns them. The T# is 8_UINT, the - // format of the console's separate stencil surface, and bind_image views the stencil aspect for it. - const bool stencil = view.plane == 1; - if (view.plane > 1 || (stencil && !(resource.aspects() & VK_IMAGE_ASPECT_STENCIL_BIT))) { - log_once("no such plane in this texture; plane", int(view.plane)); - return false; - } - // Each stencil view format belongs to its own DXGI family only, as in D3D12: the family is the texture's DXGI - // format, not the Vulkan format behind it (a D24 texture may be D32_SFLOAT_S8_UINT underneath). - const bool stencil_format_fits = - (view.format == DXGI_FORMAT_X24_TYPELESS_G8_UINT && - (desc.Format == DXGI_FORMAT_R24G8_TYPELESS || desc.Format == DXGI_FORMAT_D24_UNORM_S8_UINT)) || - (view.format == DXGI_FORMAT_X32_TYPELESS_G8X24_UINT && - (desc.Format == DXGI_FORMAT_R32G8X24_TYPELESS || desc.Format == DXGI_FORMAT_D32_FLOAT_S8X24_UINT)); - if (stencil && !stencil_format_fits) { - log_once("a stencil-plane view needs its texture family's stencil view format; format", int(view.format)); - return false; - } - const bool volume = desc.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE3D; - const bool msaa = g::multisampled(view.type); - const bool line = view.type == g::ImageType::image_1d; - const auto dimension = line ? D3D12_RESOURCE_DIMENSION_TEXTURE1D : - view.type == g::ImageType::image_3d ? D3D12_RESOURCE_DIMENSION_TEXTURE3D : - D3D12_RESOURCE_DIMENSION_TEXTURE2D; - if (desc.Dimension != dimension || (line && view.layer_count != 1) || msaa != (desc.SampleDesc.Count > 1)) { - log_once("view type incompatible with texture dimension or sample count; view type", int(view.type)); - return false; - } - if (msaa) { - // The MS bindings expose typed colour SRVs. An MS view has one mip and can name an array slice range. - const Format format = texture_storage_format(desc.Format, false); - if (resource.aspects() != VK_IMAGE_ASPECT_COLOR_BIT || format.typeless || - (view.format != DXGI_FORMAT_UNKNOWN && view.format != desc.Format)) { - log_once("multisample shader view requires a matching typed colour format:", int(desc.Format)); - return false; - } - // Four 3-bit selectors followed by D3D12's always-set bit. - if ((view.mapping >> 12) != 1) { - log_once("invalid multisample shader view component mapping:", int(view.mapping)); - return false; - } - } - const VkFormat resource_format = resource.uint_backed() ? resource.uint_backed() : resource.format(); - VkFormat named = resource_format; - if (volume) { - const bool compatible = vulkan_format(desc.Format, false).typeless - ? desc.Format == DXGI_FORMAT_R8G8B8A8_TYPELESS && - (view.format == DXGI_FORMAT_R8G8B8A8_UNORM || view.format == DXGI_FORMAT_R8G8B8A8_UNORM_SRGB) - : view.format == DXGI_FORMAT_UNKNOWN || view.format == desc.Format; - if (!compatible) { - log_once("unsupported volume SRV format for this resource:", int(view.format)); - return false; - } - } - // Depth and depth-stencil textures can only be viewed through their own family's depth-plane SRV format (or - // UNKNOWN on typed depth textures): in Vulkan a depth image's view format must equal the image's own depth - // format (VUID-VkImageViewCreateInfo-image-01762 / 09594), so colour view formats such as R16_FLOAT on D16 or - // R32_UINT on D32 must be rejected. Each view format belongs to its own DXGI family only, whatever format - // backs the texture (a D24 texture may be D32_SFLOAT_S8_UINT underneath). - const bool depth_plane = (resource.aspects() & VK_IMAGE_ASPECT_DEPTH_BIT) && !stencil; - if (depth_plane) { - const bool depth_format_fits = - (desc.Format == DXGI_FORMAT_D16_UNORM && - (view.format == DXGI_FORMAT_UNKNOWN || view.format == DXGI_FORMAT_R16_UNORM)) || - (desc.Format == DXGI_FORMAT_R16_TYPELESS && view.format == DXGI_FORMAT_R16_UNORM) || - (desc.Format == DXGI_FORMAT_D32_FLOAT && - (view.format == DXGI_FORMAT_UNKNOWN || view.format == DXGI_FORMAT_R32_FLOAT)) || - (desc.Format == DXGI_FORMAT_R32_TYPELESS && view.format == DXGI_FORMAT_R32_FLOAT) || - (desc.Format == DXGI_FORMAT_D24_UNORM_S8_UINT && - (view.format == DXGI_FORMAT_UNKNOWN || view.format == DXGI_FORMAT_R24_UNORM_X8_TYPELESS)) || - (desc.Format == DXGI_FORMAT_R24G8_TYPELESS && view.format == DXGI_FORMAT_R24_UNORM_X8_TYPELESS) || - (desc.Format == DXGI_FORMAT_D32_FLOAT_S8X24_UINT && - (view.format == DXGI_FORMAT_UNKNOWN || view.format == DXGI_FORMAT_R32_FLOAT_X8X24_TYPELESS)) || - (desc.Format == DXGI_FORMAT_R32G8X24_TYPELESS && view.format == DXGI_FORMAT_R32_FLOAT_X8X24_TYPELESS); - if (!depth_format_fits) { - log_once("incompatible depth shader-resource view format:", int(view.format)); - return false; - } - } - if (view.format != DXGI_FORMAT_UNKNOWN && !stencil && !depth_plane) { - if ((view.format == DXGI_FORMAT_A8_UNORM) != (desc.Format == DXGI_FORMAT_A8_UNORM)) { - log_once("incompatible typed A8 view format:", int(view.format)); - return false; - } - // Only a castable-format list that names the view's format lets a view cross the two families, as WARP and - // AMD's D3D12 driver accept (relaxed casting). - if (alpha_unused(view.format) != alpha_unused(desc.Format) && !resource.lists_castable_format(view.format)) { - log_once("view format from another typeless family (B8G8R8X8 and B8G8R8A8):", int(view.format)); - return false; - } - if ((view.format == DXGI_FORMAT_R9G9B9E5_SHAREDEXP) != (desc.Format == DXGI_FORMAT_R9G9B9E5_SHAREDEXP)) { - log_once("incompatible R9G9B9E5 view format:", int(view.format)); - return false; - } - named = texture_storage_format(view.format, false).format; - if (g::is_depth_stencil_format(named)) { - log_once("depth-stencil view format on a colour texture:", int(view.format)); - return false; - } - } - // A 96-bit texture takes views of its own family only (and a four-channel texture none of it), and only the - // TYPELESS one is cast between FLOAT, UINT and SINT. Its T# names the three-channel format: the swizzle below - // then reads alpha as one, and bind_image views the RGBA32 image accordingly. - const bool rgb96 = resource.rgb96(); - if (!stencil && !depth_plane) { - const bool view_rgb96 = view.format != DXGI_FORMAT_UNKNOWN ? vulkan_format(view.format, false).rgb96 : rgb96; - if (view_rgb96 != rgb96 || - (rgb96 && desc.Format != DXGI_FORMAT_R32G32B32_TYPELESS && named != resource.format())) { - log_once("view format outside the texture's 96-bit family:", int(view.format)); - return false; - } - if (rgb96) named = rgb96_named_format(named); - } - if (named == VK_FORMAT_UNDEFINED || !resource.allows_view_format(named)) { - log_once("view format not in the resource's castable list:", int(view.format)); - return false; - } - const std::uint32_t code = stencil ? g::stencil_format : g::format_from_vulkan(named); - VkFormat view_format = VK_FORMAT_UNDEFINED; - if (stencil) { - view_format = resource.format(); - } else if (code && rgb96) { - view_format = named; - } else if (code) { - view_format = g::vulkan_view_format(resource_format, code, resource.has_view_format_list()); - } - if (view_format == VK_FORMAT_UNDEFINED) { - log_once("view format not supported for this texture:", int(view.format)); - return false; - } - const UINT layers = volume ? 1 : desc.DepthOrArraySize; - if (view.first_mip >= desc.MipLevels || view.first_layer >= layers) { - log_once("view starts past the texture's mips or layers; first mip", int(view.first_mip)); - return false; - } - if (msaa && view.layer_count != UINT_MAX && view.layer_count > UINT(desc.DepthOrArraySize) - view.first_layer) { - log_once("multisample shader view ends past the texture array; layers", int(view.layer_count)); - return false; - } - out = {}; - out.address = resource.image_address(); - out.format = code; - out.type = view.type; - out.width = std::uint32_t(desc.Width); - out.height = desc.Height; - out.depth = volume ? desc.DepthOrArraySize : 1; - out.samples = desc.SampleDesc.Count; - out.first_mip = view.first_mip; - out.mip_count = std::min(view.mip_count, desc.MipLevels - view.first_mip); - out.first_layer = view.first_layer; - out.layer_count = std::min(view.layer_count, layers - view.first_layer); - if (view.type == g::ImageType::cube) out.layer_count -= out.layer_count % 6; // whole cubes - out.resource_mips = desc.MipLevels; - out.min_lod = view.min_lod; - if (!out.mip_count || !out.layer_count) { - log_once("view of no mips or no layers; type", int(view.type)); - return false; - } - // D3D12's component mapping picks, for each of R, G, B, A, a channel of the format or a constant; the T# - // says the same about the hardware's channels, which the format places. - // A stencil view's format has its eight bits in G and no R, B or A of its own (0, 0, 1 when read). - // B8G8R8X8 has no alpha: a view in its family reads 1, and a B8G8R8A8 view of a B8G8R8X8 texture (through a - // castable-format list) the stored byte. The view's format decides, as on WARP and AMD's D3D12 driver. - // The T#'s format code is the same for both channel orders of a colour format (R8G8B8A8 and B8G8R8A8 are one - // 8_8_8_8 code), and the image view keeps the image's format; a castable-format list may still ask for the other - // order, so then the view's own format places the channels. Depth images keep their own format's channels. - const bool other_order = view.format != DXGI_FORMAT_UNKNOWN && !stencil && !depth_plane && !rgb96 && - named != view_format && !g::is_depth_stencil_format(view_format); - g::Swizzle channels = g::format_swizzle(other_order ? named : view_format); - if (stencil) channels = {g::select_zero, g::select_x, g::select_zero, g::select_one}; - else if (desc.Format == DXGI_FORMAT_A8_UNORM) channels = {g::select_zero, g::select_zero, g::select_zero, g::select_x}; - else if (alpha_unused(view.format != DXGI_FORMAT_UNKNOWN ? view.format : desc.Format)) channels[3] = g::select_one; - for (UINT i = 0; i < 4; ++i) { - const UINT from = D3D12_DECODE_SHADER_4_COMPONENT_MAPPING(i, view.mapping); - if (msaa && from > D3D12_SHADER_COMPONENT_MAPPING_FORCE_VALUE_1) { - log_once("invalid multisample shader view component selector:", from); - return false; - } - out.swizzle[i] = from < 4 ? channels[from] - : from == D3D12_SHADER_COMPONENT_MAPPING_FORCE_VALUE_0 ? g::select_zero : g::select_one; - } - return true; -} - -// The S# of a D3D12 sampler. -leonida::gfx10::Sampler sampler_descriptor(const D3D12_SAMPLER_DESC& desc, DeviceState* state = nullptr) { - namespace g = leonida::gfx10; - const auto address = [](D3D12_TEXTURE_ADDRESS_MODE mode) { - switch (mode) { - case D3D12_TEXTURE_ADDRESS_MODE_MIRROR: return g::AddressMode::mirror; - case D3D12_TEXTURE_ADDRESS_MODE_CLAMP: return g::AddressMode::clamp_last_texel; - case D3D12_TEXTURE_ADDRESS_MODE_BORDER: return g::AddressMode::clamp_border; - case D3D12_TEXTURE_ADDRESS_MODE_MIRROR_ONCE: return g::AddressMode::mirror_once_last_texel; - default: return g::AddressMode::wrap; - } - }; - const bool anisotropic = D3D12_DECODE_IS_ANISOTROPIC_FILTER(desc.Filter); - const auto filter = [&](D3D12_FILTER_TYPE type) { - if (anisotropic) return type == D3D12_FILTER_TYPE_LINEAR ? g::Filter::aniso_bilinear : g::Filter::aniso_point; - return type == D3D12_FILTER_TYPE_LINEAR ? g::Filter::bilinear : g::Filter::point; - }; - g::Sampler out{}; - out.address_u = address(desc.AddressU); - out.address_v = address(desc.AddressV); - out.address_w = address(desc.AddressW); - out.mag_filter = filter(D3D12_DECODE_MAG_FILTER(desc.Filter)); - out.min_filter = filter(D3D12_DECODE_MIN_FILTER(desc.Filter)); - out.mip_filter = D3D12_DECODE_MIP_FILTER(desc.Filter) == D3D12_FILTER_TYPE_LINEAR ? g::MipFilter::linear - : g::MipFilter::point; - out.max_anisotropy = anisotropic ? std::clamp(desc.MaxAnisotropy, 1, 16) : 1; - const D3D12_FILTER_REDUCTION_TYPE reduction = D3D12_DECODE_FILTER_REDUCTION(desc.Filter); - // D3D12's comparison functions are 1 (NEVER) to 8 (ALWAYS); the S#'s are 0 to 7 in the same order. - if (reduction == D3D12_FILTER_REDUCTION_TYPE_COMPARISON && desc.ComparisonFunc >= D3D12_COMPARISON_FUNC_NEVER) - out.compare = g::CompareFunction(desc.ComparisonFunc - D3D12_COMPARISON_FUNC_NEVER); - out.compare_never = reduction == D3D12_FILTER_REDUCTION_TYPE_COMPARISON && - desc.ComparisonFunc == D3D12_COMPARISON_FUNC_NEVER; - if (reduction == D3D12_FILTER_REDUCTION_TYPE_MINIMUM) out.filter_mode = g::FilterMode::minimum; - if (reduction == D3D12_FILTER_REDUCTION_TYPE_MAXIMUM) out.filter_mode = g::FilterMode::maximum; - out.min_lod = desc.MinLOD; - out.max_lod = desc.MaxLOD; - out.lod_bias = desc.MipLODBias; - const FLOAT* border = desc.BorderColor; - const bool black = border[0] == 0 && border[1] == 0 && border[2] == 0; - if (black && border[3] == 0) { - out.border_color = g::BorderColor::transparent_black; - } else if (black && border[3] == 1) { - out.border_color = g::BorderColor::opaque_black; - } else if (border[0] == 1 && border[1] == 1 && border[2] == 1 && border[3] == 1) { - out.border_color = g::BorderColor::opaque_white; - } else { - out.border_color = g::BorderColor::table; - if (state) out.border_color_index = state->register_border_color(false, border); - } - return out; -} - -// A query heap: one VkQueryPool, registered with the context so that lists can resolve it by ID -// (docs/d3d12_vulkan.md section 4.6). Occlusion heaps hold both OCCLUSION and BINARY_OCCLUSION queries; timestamp -// and copy-queue timestamp heaps are timestamp pools; pipeline-statistics heaps count all eleven Vulkan -// statistics, whose result order is the field order of D3D12_QUERY_DATA_PIPELINE_STATISTICS. Stream-output -// statistics heaps have no pool: without stream output every such query is zero. -class QueryHeap final - : public Child { -public: - // {6e2b9a41-d83c-4f17-b5e9-0a7c3d1f8b62} - static constexpr GUID kTag{0x6e2b9a41, 0xd83c, 0x4f17, {0xb5, 0xe9, 0x0a, 0x7c, 0x3d, 0x1f, 0x8b, 0x62}}; - - explicit QueryHeap(DeviceState& device) : device_(device) {} - - ~QueryHeap() override { - if (!registered_) return; - device_.context->remove_query_pool(id()); - if (pool_) device_.context->vk.vkDestroyQueryPool(device_.info.device, pool_, nullptr); - } - - leonida::QueryHeapId id() const { return query_heap_id(this); } - - HRESULT create(const D3D12_QUERY_HEAP_DESC& desc) { - namespace h = leonida::d3d12_query_heap; - auto& vk = device_.context->vk; - if (!vk.vkCreateQueryPool || !vk.vkDestroyQueryPool) return E_NOTIMPL; - VkQueryPoolCreateInfo info{VK_STRUCTURE_TYPE_QUERY_POOL_CREATE_INFO}; - info.queryCount = desc.Count; - switch (desc.Type) { - case h::occlusion: info.queryType = VK_QUERY_TYPE_OCCLUSION; break; - case h::timestamp: - case h::copy_queue_timestamp: - if (!(device_.context->timestamp_period() > 0)) { - log_once("timestamp query heap: the queue writes no timestamps; type", desc.Type); - return E_NOTIMPL; - } - info.queryType = VK_QUERY_TYPE_TIMESTAMP; - break; - case h::so_statistics: - // The layer has no stream output: a graphics PSO with StreamOutput entries is refused (E_NOTIMPL) and - // SOSetTargets is not implemented, so no primitive ever reaches a stream and every query of this heap - // counts 0 written and 0 needed. That needs no Vulkan pool: Begin/EndQuery run nothing and a resolve fills zeros. When stream - // output lands, this becomes a VK_QUERY_TYPE_TRANSFORM_FEEDBACK_STREAM_EXT pool (D3D-302). - return register_pool(desc); - case h::pipeline_statistics: - if (!device_.info.pipeline_statistics_query) { - log_once("pipeline-statistics query heap: pipelineStatisticsQuery not enabled; type", desc.Type); - return E_NOTIMPL; - } - info.queryType = VK_QUERY_TYPE_PIPELINE_STATISTICS; - info.pipelineStatistics = kPipelineStatistics; - break; - default: - // Video decode and mesh-shader statistics (PIPELINE_STATISTICS1) have no path yet. - log_once("query heap type not supported:", desc.Type); - return E_NOTIMPL; - } - if (vk.vkCreateQueryPool(device_.info.device, &info, nullptr, &pool_) != VK_SUCCESS) { - pool_ = VK_NULL_HANDLE; - return E_OUTOFMEMORY; - } - return register_pool(desc); - } - -private: - HRESULT register_pool(const D3D12_QUERY_HEAP_DESC& desc) { - leonida::QueryPool pool{}; - pool.pool = pool_; - pool.heap_type = desc.Type; - pool.count = desc.Count; - pool.precise = device_.info.occlusion_query_precise; - pool.ended.assign(desc.Count, false); - device_.context->add_query_pool(id(), pool); - registered_ = true; - return S_OK; - } - - // VK_QUERY_PIPELINE_STATISTIC_INPUT_ASSEMBLY_VERTICES_BIT through COMPUTE_SHADER_INVOCATIONS_BIT (0x1-0x400): - // IAVertices, IAPrimitives, VSInvocations, GSInvocations, GSPrimitives, CInvocations, CPrimitives, - // PSInvocations, HSInvocations (patches), DSInvocations, CSInvocations. - static constexpr VkQueryPipelineStatisticFlags kPipelineStatistics = 0x7ff; - static_assert(sizeof(D3D12_QUERY_DATA_PIPELINE_STATISTICS) == 11 * sizeof(UINT64)); - - DeviceState& device_; - VkQueryPool pool_ = VK_NULL_HANDLE; // null for a stream-output heap (no Vulkan query behind it) - bool registered_ = false; // added to the context, so removed from it on destruction -}; - -// The Vulkan objects create_vulkan_device_standalone made, destroyed with the device. -struct OwnedRuntime { - PFN_vkDestroyDevice destroy_device = nullptr; - PFN_vkDestroyInstance destroy_instance = nullptr; - VkDevice device = VK_NULL_HANDLE; - VkInstance instance = VK_NULL_HANDLE; -}; - -class Device final - : public Object { -public: - // {c58e1d27-3a96-4b4f-9e72-6d0a8b5f3c61} - static constexpr GUID kTag{0xc58e1d27, 0x3a96, 0x4b4f, {0x9e, 0x72, 0x6d, 0x0a, 0x8b, 0x5f, 0x3c, 0x61}}; - - explicit Device(const VulkanDeviceInfo& info) { - // Every Vulkan device serves Xbox device slot 133, whichever entry made it: create_vulkan_device and the - // standalone device gta6rt --run uses both come through here (found in review: registering only in - // create_vulkan_device left the retail path without it). - rt::d3d12_xs::set_placed_at_va_handler(&create_buffer_at_host_address); - rt::d3d12_xs::set_console_descriptor_heap_handler(&rt::d3d12::create_console_descriptor_heap); - state_.info = info; - queue_users_.resize(info.command_queues.size(), 0); - compute_users_.resize(info.compute_queues.size(), 0); - copy_users_.resize(info.copy_queues.size(), 0); - for (std::uint32_t f : {info.queue_family, info.compute_family, info.copy_family}) - if (f != UINT32_MAX && std::find(state_.families.begin(), state_.families.end(), f) == state_.families.end()) - state_.families.push_back(f); - const auto get_device = reinterpret_cast( - info.get_instance_proc(info.instance, "vkGetDeviceProcAddr")); - state_.format_properties = reinterpret_cast( - info.get_instance_proc(info.instance, "vkGetPhysicalDeviceFormatProperties")); - state_.image_format_properties = reinterpret_cast( - info.get_instance_proc(info.instance, "vkGetPhysicalDeviceImageFormatProperties")); - state_.image_format_properties2 = reinterpret_cast( - info.get_instance_proc(info.instance, "vkGetPhysicalDeviceImageFormatProperties2")); - if (!state_.image_format_properties2) { - state_.image_format_properties2 = reinterpret_cast( - info.get_instance_proc(info.instance, "vkGetPhysicalDeviceImageFormatProperties2KHR")); - } - const auto memory_properties = reinterpret_cast( - info.get_instance_proc(info.instance, "vkGetPhysicalDeviceMemoryProperties")); - const auto device_properties = reinterpret_cast( - info.get_instance_proc(info.instance, "vkGetPhysicalDeviceProperties")); - const auto queue_families = reinterpret_cast( - info.get_instance_proc(info.instance, "vkGetPhysicalDeviceQueueFamilyProperties")); - if (!get_device || !state_.format_properties || !state_.image_format_properties || !memory_properties || - !device_properties || !queue_families) - return; - state_.r9g9b9e5_uav_emulated = - state_.probe_uint_backed_uav(VK_FORMAT_E5B9G9R9_UFLOAT_PACK32, VK_FORMAT_R32_UINT); - state_.b5g5r5a1_uav_emulated = - state_.probe_uint_backed_uav(VK_FORMAT_A1R5G5B5_UNORM_PACK16, VK_FORMAT_R16_UINT); - state_.rgba8_srgb_uav_emulated = - state_.probe_uint_backed_uav(VK_FORMAT_R8G8B8A8_SRGB, VK_FORMAT_R8G8B8A8_UNORM); - state_.bgra8_srgb_uav_emulated = - state_.probe_uint_backed_uav(VK_FORMAT_B8G8R8A8_SRGB, VK_FORMAT_B8G8R8A8_UNORM); - memory_properties(info.physical, &state_.memory); - { - // vulkan.upload_sysmem (LEONIDA_UPLOAD_SYSMEM): on for a value that does not start with 0. A value of 4 - // characters or more is ignored, as before the setting moved to the table. - const std::string text = rt::config::get("vulkan.upload_sysmem").text; - const bool sysmem = !text.empty() && text.size() < 4 && text[0] != '0'; - state_.upload_in_vram = leonida::resizable_bar(state_.memory) && !sysmem; - RT_LOG_INFO("d3d12: upload heaps in %s\n", - state_.upload_in_vram ? "VRAM (DEVICE_LOCAL | HOST_VISIBLE, Resizable BAR)" - : sysmem ? "system memory (LEONIDA_UPLOAD_SYSMEM)" - : "system memory (no Resizable BAR)"); - } - for (const char* name : {"vkGetDeviceImageMemoryRequirements", "vkGetDeviceImageMemoryRequirementsKHR"}) - if (!state_.image_requirements) - state_.image_requirements = - reinterpret_cast(get_device(info.device, name)); - - if (info.physical && info.get_instance_proc) { - const auto get_props = reinterpret_cast( - info.get_instance_proc(info.instance, "vkGetPhysicalDeviceProperties")); - if (get_props) { - VkPhysicalDeviceProperties props{}; - get_props(info.physical, &props); - state_.pso_identity.vendor = props.vendorID; - state_.pso_identity.device = props.deviceID; - state_.pso_identity.driver = props.driverVersion; - std::memcpy(state_.pso_identity.cache_uuid, props.pipelineCacheUUID, VK_UUID_SIZE); - if (state_.info.max_push_constants_size == 0) { - state_.info.max_push_constants_size = props.limits.maxPushConstantsSize; - state_.info.push_constants_need_fallback = (state_.info.max_push_constants_size < 144); - } - // The counts D3D12 offers with no outputs are the target-independent-rasterization ones: 1, 4, 8 - // and 16 (ForcedSampleCount is 0, 1, 4, 8 or 16; DirectX-Specs VulkanOn12.md "Sample-frequency MSAA - // with no render targets bound": a driver reports at least 0b11101). 2x is not one of them, though - // framebufferNoAttachmentsSampleCounts has it on every GPU here; reporting it would offer a count the - // PC runtime refuses (its hosts report 0x1d). - constexpr VkSampleCountFlags kD3D12SampleCounts = - VK_SAMPLE_COUNT_1_BIT | VK_SAMPLE_COUNT_4_BIT | VK_SAMPLE_COUNT_8_BIT | VK_SAMPLE_COUNT_16_BIT; - state_.no_output_sample_counts = - static_cast(props.limits.framebufferNoAttachmentsSampleCounts & kD3D12SampleCounts); - state_.f16_half_top_location = leonida::f16_half_top_location( - props.limits.maxVertexOutputComponents, props.limits.maxFragmentInputComponents); - } - if (const auto get_props2 = reinterpret_cast( - info.get_instance_proc(info.instance, "vkGetPhysicalDeviceProperties2"))) { - VkPhysicalDeviceDepthStencilResolveProperties resolve{ - VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_DEPTH_STENCIL_RESOLVE_PROPERTIES}; - VkPhysicalDeviceConservativeRasterizationPropertiesEXT conservative{ - VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_CONSERVATIVE_RASTERIZATION_PROPERTIES_EXT}; - if (info.conservative_rasterization) resolve.pNext = &conservative; - VkPhysicalDeviceProperties2 props{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROPERTIES_2, &resolve}; - get_props2(info.physical, &props); - state_.conservative_raster_tier = D3D12_CONSERVATIVE_RASTERIZATION_TIER(leonida::conservative_raster::tier( - info.conservative_rasterization, props.properties.limits.subPixelPrecisionBits, - conservative.primitiveOverestimationSize, conservative.degenerateTrianglesRasterized == VK_TRUE, - conservative.fullyCoveredFragmentShaderInputVariable == VK_TRUE, info.inner_coverage_abi)); - state_.conservative_post_depth_coverage = conservative.conservativeRasterizationPostDepthCoverage == VK_TRUE; - state_.depth_resolve_modes = resolve.supportedDepthResolveModes; - state_.stencil_resolve_modes = resolve.supportedStencilResolveModes; - const leonida::ArenaLimits limits = leonida::query_arena_limits(get_props2, info.physical); - if (!state_.info.max_buffer_size) state_.info.max_buffer_size = limits.max_buffer_size; - if (!state_.info.max_memory_allocation_size) - state_.info.max_memory_allocation_size = limits.max_allocation_size; - } - } - - state_.context = std::make_unique(get_device, info.device, - info.separate_depth_stencil_layouts, - info.conditional_rendering, info.ray_tracing, - info.xdxr_acceleration_structures && - info.buffer_device_address); - if (info.physical && state_.format_properties) { - state_.context->set_color_attachment_format( - [physical = info.physical, get_props = state_.format_properties](VkFormat format) { - VkFormatProperties properties{}; - get_props(physical, format, &properties); - return (properties.optimalTilingFeatures & VK_FORMAT_FEATURE_COLOR_ATTACHMENT_BIT) != 0; - }); - } - if (info.buffer_device_address && state_.context->loaded() && !create_arena()) - RT_LOG_ERROR("d3d12: the GPU address arena could not be created\n"); - if (info.conditional_rendering) { - const auto properties = reinterpret_cast( - info.get_instance_proc(info.instance, "vkGetPhysicalDeviceProperties")); - const auto families = reinterpret_cast( - info.get_instance_proc(info.instance, "vkGetPhysicalDeviceQueueFamilyProperties")); - if (properties && families) { - VkPhysicalDeviceProperties limits{}; - properties(info.physical, &limits); - std::uint32_t count = 0; - families(info.physical, &count, nullptr); - std::vector queues(count); - families(info.physical, &count, queues.data()); - if (info.copy_family < count && !(queues[info.copy_family].queueFlags & VK_QUEUE_COMPUTE_BIT)) - state_.context->set_transfer_only_family(info.copy_family); - if (info.queue_family < count && (queues[info.queue_family].queueFlags & VK_QUEUE_COMPUTE_BIT)) { - state_.context->configure_predication(get_device, state_.memory, limits.limits.maxStorageBufferRange, info.queue_family); - if (info.storage_buffer_8bit) state_.context->configure_predicated_copy(get_device, limits.limits); - } - } - } - if (info.host_image_copy) load_host_image_copy(get_device); - if (info.host_pointer_alignment) - state_.get_host_pointer_properties = reinterpret_cast( - get_device(info.device, "vkGetMemoryHostPointerPropertiesEXT")); - // Depth <-> colour copies are staged through scratch buffers (vulkan_scratch.h), on every GPU. - state_.context->enable_copy_scratch(get_device, [this](const VkMemoryRequirements& requirements) { - return state_.allocate(requirements, 0, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT); - }); - if (info.buffer_device_address && info.physical && info.get_instance_proc) { - if (const auto get_props = reinterpret_cast( - info.get_instance_proc(info.instance, "vkGetPhysicalDeviceProperties"))) { - VkPhysicalDeviceProperties props{}; - get_props(info.physical, &props); - state_.context->configure_counted_dispatch(get_device, state_.memory, props.limits); - } - } - // The copies of a D24 texture stored as D32 convert on the GPU (vulkan_depth24.h), and so do the copies of - // a 96-bit texture, which every GPU stores as RGBA32 (D3D-62): the converter is there whether or not the - // GPU has a native D24_UNORM_S8_UINT. It costs nothing until a copy needs it (its pipeline is made on the - // first job, and a queue takes the tracker lock for it only when a list has such a copy). - { - std::uint64_t max_storage_range = 1u << 27; // the least Vulkan allows, if the limit cannot be read - if (info.physical && info.get_instance_proc) { - if (const auto get_props = reinterpret_cast( - info.get_instance_proc(info.instance, "vkGetPhysicalDeviceProperties"))) { - VkPhysicalDeviceProperties props{}; - get_props(info.physical, &props); - max_storage_range = props.limits.maxStorageBufferRange; - } - } - state_.context->enable_depth24(get_device, [this](const VkMemoryRequirements& requirements) { - return state_.allocate(requirements, 0, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT); - }, max_storage_range); - } - if (info.bindless && state_.context->loaded() && !create_bindless(get_device)) - RT_LOG_ERROR("d3d12: the bindless set 0 could not be created\n"); - query_luid_and_clock(get_device); - // Timestamps: what the one VkQueue every D3D12 queue submits to can write. - VkPhysicalDeviceProperties properties{}; - device_properties(info.physical, &properties); - state_.max_sampler_lod_bias = properties.limits.maxSamplerLodBias; - std::uint32_t family_count = 0; - queue_families(info.physical, &family_count, nullptr); - std::vector families(family_count); - queue_families(info.physical, &family_count, families.data()); - if (info.queue_family < family_count) { - const auto& family = families[info.queue_family]; - if (family.timestampValidBits) - state_.context->set_timestamp_period(properties.limits.timestampPeriod); - // MoltenVK (1.4.2 and 1.4.3 measured) resolves a timestamp before the write that precedes it lands, unless - // something orders the two (docs/d3d12_vulkan.md section 4.6). - const auto get_props2 = reinterpret_cast( - info.get_instance_proc ? info.get_instance_proc(info.instance, "vkGetPhysicalDeviceProperties2") - : nullptr); - if (family.timestampValidBits && get_props2) { - VkPhysicalDeviceDriverProperties driver{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_DRIVER_PROPERTIES}; - VkPhysicalDeviceProperties2 props{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROPERTIES_2, &driver}; - get_props2(info.physical, &props); - if (driver.driverID == VK_DRIVER_ID_MOLTENVK) { - state_.context->set_order_timestamp_copies(true); - log_once("timestamp resolves wait for the timestamps before them (MoltenVK); driver", - int(driver.driverID)); - } - } - if (family.queueFlags & VK_QUEUE_COMPUTE_BIT) - state_.context->set_occlusion_resolve_memory(state_.memory); - } - - if (info.debug_utils) { - leonida::DebugLabelFunctions labels; - const auto load = [&](auto& f, const char* name) { - f = reinterpret_cast>(info.get_instance_proc(info.instance, name)); - }; - load(labels.cmd_insert, "vkCmdInsertDebugUtilsLabelEXT"); - load(labels.cmd_begin, "vkCmdBeginDebugUtilsLabelEXT"); - load(labels.cmd_end, "vkCmdEndDebugUtilsLabelEXT"); - load(labels.queue_insert, "vkQueueInsertDebugUtilsLabelEXT"); - load(labels.queue_begin, "vkQueueBeginDebugUtilsLabelEXT"); - load(labels.queue_end, "vkQueueEndDebugUtilsLabelEXT"); - state_.context->enable_debug_labels(labels); - if (!state_.context->debug_labels()) - RT_LOG_WARN("d3d12: VK_EXT_debug_utils entry points missing; debug markers are off\n"); - } - - const bool sparse_aliasing = state_.context->vk.vkQueueBindSparse && info.features.sparseBinding && - info.features.sparseResidencyAliased && properties.sparseProperties.residencyNonResidentStrict && - info.queue_family < family_count && (families[info.queue_family].queueFlags & VK_QUEUE_SPARSE_BINDING_BIT); - state_.sparse_image_tiles = sparse_aliasing && info.features.sparseResidencyImage2D && - state_.context->vk.vkGetImageSparseMemoryRequirements; - if (sparse_aliasing && state_.arena.memory && info.features.sparseResidencyBuffer) { - auto& vk = state_.context->vk; - const auto sparse_info = state_.sparse_buffer_info(leonida::tile_size_in_bytes); - VkBuffer sample = VK_NULL_HANDLE; - if (vk.vkCreateBuffer(info.device, &sparse_info, nullptr, &sample) == VK_SUCCESS) { - VkMemoryRequirements requirements{}; - vk.vkGetBufferMemoryRequirements(info.device, sample, &requirements); - vk.vkDestroyBuffer(info.device, sample, nullptr); - if (!(leonida::tile_size_in_bytes % requirements.alignment)) - state_.sparse_buffer_memory_types = requirements.memoryTypeBits; - } - } - } - - // Set 0 of every translated shader that declares bindings: images, samplers and the descriptor hash table - // (docs section 3.4). Each ExecuteCommandLists brings it up to date before its commands are written. - bool create_bindless(PFN_vkGetDeviceProcAddr get_device) { - leonida::BindlessFeatures features{}; - features.update_after_bind = true; // VulkanDeviceInfo::bindless promises it - features.partially_bound = state_.info.bindless_partially_bound; - const auto get_properties = reinterpret_cast( - state_.info.get_instance_proc(state_.info.instance, "vkGetPhysicalDeviceProperties2")); - if (get_properties) { - VkPhysicalDeviceVulkan12Properties indexed{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_2_PROPERTIES}; - VkPhysicalDeviceVulkan11Properties v11{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_1_PROPERTIES, &indexed}; - VkPhysicalDeviceProperties2 properties{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROPERTIES_2, &v11}; - get_properties(state_.info.physical, &properties); - features.ms_samples = {VK_SAMPLE_COUNT_4_BIT, state_.ms_fallback_samples(VK_FORMAT_R32_UINT), - state_.ms_fallback_samples(VK_FORMAT_R32_SINT)}; - // Past maxPerSetDescriptors, ask the driver about the grown layout (D3D-219: Intel's Xe-LP reports 6159). - const auto layout_support = reinterpret_cast( - get_device(state_.info.device, "vkGetDescriptorSetLayoutSupport")); - std::function layout_supported; - // MoltenVK's vkGetDescriptorSetLayoutSupport compares every layout with maxPerSetDescriptors (1212, the - // limit without argument buffers) and rejects even 1212 itself, while it creates and samples a 65536-image, - // 4096-sampler update-after-bind set correctly (docs/d3d12_vulkan.md section 5). There size_bindings' - // per-type update-after-bind limits, which MoltenVK takes from Metal's argument-buffer limits, decide. - VkPhysicalDeviceDriverProperties driver{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_DRIVER_PROPERTIES}; - VkPhysicalDeviceProperties2 driver_properties{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROPERTIES_2, &driver}; - get_properties(state_.info.physical, &driver_properties); - if (driver.driverID == VK_DRIVER_ID_MOLTENVK) - layout_supported = [](const leonida::BindlessFeatures&) { return true; }; - else if (layout_support) - layout_supported = [&](const leonida::BindlessFeatures& candidate) { - const leonida::bindless::SetLayout layout(candidate); - VkDescriptorSetLayoutSupport support{VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_SUPPORT}; - layout_support(state_.info.device, &layout.info, &support); - return support.supported == VK_TRUE; - }; - if (!leonida::bindless::size_bindings(features, properties.properties.limits, v11, indexed, - layout_supported)) - RT_LOG_WARN("d3d12: the device's descriptor limits are below the bindless set's default " - "sizes; it holds less\n"); - } - namespace b = leonida::bindless; - RT_LOG_INFO("d3d12: bindless set: %u 2D images, %u samplers, %u 2D-array, %u 3D, %u 1D, " - "%u storage indices in 2D\n", - features.counts[b::sampled_binding(leonida::ImageDimension::dim_2d)], - features.counts[b::sampler_binding], - features.counts[b::sampled_binding(leonida::ImageDimension::dim_2d_array)], - features.counts[b::sampled_binding(leonida::ImageDimension::dim_3d)], - features.counts[b::sampled_binding(leonida::ImageDimension::dim_1d)], - features.counts[b::storage_binding(leonida::ImageDimension::dim_2d, 0)]); - // D3D12 promises a shader holds a full shader-visible sampler heap. Past this many distinct S#s, CreateSampler - // logs that the array is full and a shader reads the fallback (clamping) sampler. - if (features.counts[b::sampler_binding] < D3D12_MAX_SHADER_VISIBLE_SAMPLER_HEAP_SIZE + 1) - RT_LOG_WARN("d3d12: the bindless set holds fewer samplers than a full shader-visible " - "sampler heap (%u of %u besides the fallback): its limits or " - "vkGetDescriptorSetLayoutSupport allow no more\n", - features.counts[b::sampler_binding] - 1, unsigned(D3D12_MAX_SHADER_VISIBLE_SAMPLER_HEAP_SIZE)); - state_.bindless = std::make_unique(get_device, state_.info.device, state_.memory, features); - if (!state_.bindless->ok() || !state_.context->vk.vkCreateSampler) { - state_.bindless.reset(); - return false; - } - state_.context->set_bindless_release( - [](void* user, std::uint32_t dim, std::uint32_t idx) { - auto* st = static_cast(user); - std::lock_guard lock(st->descriptor_mutex); - if (st->bindless) st->bindless->remove_image(static_cast(dim), idx); - }, - &state_); - state_.context->set_bindless_prepare([this](VkCommandBuffer command_buffer) { - std::unique_lock lock(state_.descriptor_mutex); - if (!state_.bindless->fallbacks_ready()) state_.bindless->record_fallback_init(command_buffer); - auto& context = *state_.context; - if (state_.bindless_legacy_idle && state_.bindless->flush_replaces_table()) { - // The wait of before D3D-314, kept for comparing frame times: nothing that uses the set still runs - // after it, so the generations flush() retires are free at once. - { - std::lock_guard submit(context.submit_mutex()); - context.vk.vkDeviceWaitIdle(state_.info.device); - } - state_.bindless_idle_waits.fetch_add(1, std::memory_order_relaxed); - state_.bindless->release_retired(); - } else if (state_.bindless->has_retired()) { - // Generations of the table that an earlier flush replaced: free those whose submissions are done. - // Nothing waits; the rest stay for a later submit. completed_retire_ticket() takes submit_mutex_, - // which comes after the resource, tracker and descriptor locks held here. - state_.bindless->release_retired(context.completed_retire_ticket()); - // A queue whose work is stalled (a fence only the CPU signals, long async work) keeps its ticket from - // completing, and each replacing flush adds a generation. Past the cap wait, once the oldest is in the - // way, for the submissions up to its ticket (the queues' timelines, not the device), with the - // descriptor lock released: the thread that signals such a fence may need it. - constexpr std::size_t max_retired = 8; - if (state_.bindless->retired_count() > max_retired) { - if (!state_.bindless_cap_logged.exchange(true)) - RT_LOG_WARN("d3d12: more than %zu retired bindless table generations: waiting " - "for the queues that still use the oldest\n", max_retired); - const std::uint64_t oldest = state_.bindless->oldest_retired_ticket(); - lock.unlock(); - const std::uint64_t completed = context.wait_retire_ticket(oldest); - lock.lock(); - state_.bindless->release_retired(completed); - } - } - // Under tracker_mutex_ (held from here to the submit) no other ExecuteCommandLists has recorded work that - // is not yet submitted, so every submission that can have bound the set being replaced has a ticket up to - // the one read here. - const bool flushed = state_.bindless->flush(command_buffer, context.submitted_retire_ticket()); - if (flushed && state_.bindless->last_flush_replaced()) context.note_bindless_upload(); - return flushed; - }); - state_.context->set_bindless_current([this]() { - std::lock_guard lock(state_.descriptor_mutex); - return state_.bindless ? state_.bindless->set() : VK_NULL_HANDLE; - }); - { - // vulkan.bindless_idle_wait (LEONIDA_BINDLESS_IDLE_WAIT): on for a value that does not start with 0. A - // value of 8 characters or more is ignored, as before the setting moved to the table. - const std::string text = rt::config::get("vulkan.bindless_idle_wait").text; - state_.bindless_legacy_idle = !text.empty() && text.size() < 8 && text[0] != '0'; - } - state_.context->set_bindless_commit([this](bool submitted) { - std::lock_guard lock(state_.descriptor_mutex); - if (state_.bindless) state_.bindless->table_upload_result(submitted); - }); - return true; - } - - // LEONIDA_ARENA_MB sets its size (default 256, at most 4095, and no more than the device's maxBufferSize and - // maxMemoryAllocationSize allow: src/arena_size.h): it holds every default-heap buffer, shader-visible - // descriptor heap and shader program. M0-M3 keep it host-visible (section 3.3, memory type policy). - bool create_arena() { - auto& vk = state_.context->vk; - if (!vk.vkGetBufferDeviceAddress) return false; - // vulkan.arena_mb (LEONIDA_ARENA_MB): the text goes to decide_arena_size as written. Nothing set, or a value - // of 16 characters or more (ignored, as before the setting moved to the table), gives the default size. - const rt::config::Value arena_mb = rt::config::get("vulkan.arena_mb"); - const bool set = arena_mb.is_set() && arena_mb.text.size() < 16; - const char* text = arena_mb.text.c_str(); - const leonida::ArenaLimits limits{state_.info.max_buffer_size, state_.info.max_memory_allocation_size}; - leonida::ArenaSize size = leonida::decide_arena_size(set ? text : nullptr, limits); - auto& arena = state_.arena; - VkBufferCreateInfo info{VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO}; - info.size = size.bytes; - info.usage = VK_BUFFER_USAGE_TRANSFER_SRC_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT | - VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT | VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | - VK_BUFFER_USAGE_VERTEX_BUFFER_BIT | VK_BUFFER_USAGE_INDEX_BUFFER_BIT | - VK_BUFFER_USAGE_INDIRECT_BUFFER_BIT | VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT; - // Default-heap buffers live here, and any of them can be a SetPredication buffer. - if (state_.info.conditional_rendering) info.usage |= VK_BUFFER_USAGE_CONDITIONAL_RENDERING_BIT_EXT; - // With ray tracing, AS result, scratch and build-input buffers are default-heap ranges of the arena. - if (state_.info.ray_tracing) - info.usage |= VK_BUFFER_USAGE_ACCELERATION_STRUCTURE_STORAGE_BIT_KHR | - VK_BUFFER_USAGE_ACCELERATION_STRUCTURE_BUILD_INPUT_READ_ONLY_BIT_KHR; - state_.share(info); - VkMemoryRequirements requirements{}; - const auto create_buffer = [&] { - if (info.size <= kArenaReserved || - vk.vkCreateBuffer(state_.info.device, &info, nullptr, &arena.buffer) != VK_SUCCESS) { - arena.buffer = VK_NULL_HANDLE; - return false; - } - vk.vkGetBufferMemoryRequirements(state_.info.device, arena.buffer, &requirements); - return true; - }; - if (!create_buffer()) return false; - // The allocation is requirements.size, which alignment can make larger than the buffer: past - // maxMemoryAllocationSize, make the buffer smaller by that much once. - if (limits.max_allocation_size && requirements.size > limits.max_allocation_size) { - vk.vkDestroyBuffer(state_.info.device, arena.buffer, nullptr); - size = leonida::decide_arena_size(set ? text : nullptr, limits, requirements.size - info.size); - info.size = size.bytes; - if (!create_buffer()) return false; - if (requirements.size > limits.max_allocation_size) { - vk.vkDestroyBuffer(state_.info.device, arena.buffer, nullptr); - arena.buffer = VK_NULL_HANDLE; - return false; - } - } - if (size.capped) - RT_LOG_WARN("d3d12: GPU address arena: %llu MiB of the %llu MiB asked for, capped by the " - "device's %s\n", - static_cast(size.bytes >> 20), - static_cast(size.requested >> 20), leonida::arena_cap_name(size.capped)); - arena.memory = state_.allocate(requirements, - VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT, - VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, nullptr, true, &arena.memory_type); - void* mapped = nullptr; - if (!arena.memory || vk.vkBindBufferMemory(state_.info.device, arena.buffer, arena.memory, 0) != VK_SUCCESS || - vk.vkMapMemory(state_.info.device, arena.memory, 0, VK_WHOLE_SIZE, 0, &mapped) != VK_SUCCESS) { - // Without an arena every buffer keeps its own memory; a leftover handle would make them addressable - // with heap base 0, so their VAs would be raw device addresses above 4 GiB. - vk.vkDestroyBuffer(state_.info.device, arena.buffer, nullptr); - if (arena.memory) vk.vkFreeMemory(state_.info.device, arena.memory, nullptr); - arena.buffer = VK_NULL_HANDLE; - arena.memory = VK_NULL_HANDLE; - return false; - } - arena.mapped = static_cast(mapped); - std::memset(arena.mapped, 0, kArenaReserved); // the zero page unbound vertex and index buffers read - VkBufferDeviceAddressInfo address{VK_STRUCTURE_TYPE_BUFFER_DEVICE_ADDRESS_INFO}; - address.buffer = arena.buffer; - arena.address = vk.vkGetBufferDeviceAddress(state_.info.device, &address); - arena.size = info.size; - arena.free[kArenaReserved] = arena.size - kArenaReserved; - arena.peak_end = kArenaReserved; - // vulkan.arena_log (LEONIDA_ARENA_LOG): on for a value that does not start with 0. A value of 4 - // characters or more is ignored, as before the setting moved to the table. - const std::string log = rt::config::get("vulkan.arena_log").text; - arena.log = !log.empty() && log.size() < 4 && log[0] != '0'; - state_.context->set_heap_base(arena.address); - state_.context->set_zero_page(arena.buffer, 0, kArenaReserved); - return true; - } - - ~Device() override { - if (state_.context) { - { - std::lock_guard lock(state_.context->submit_mutex()); - state_.context->vk.vkDeviceWaitIdle(state_.info.device); - } - state_.context->drain_deleted_resources(UINT64_MAX); - state_.context->set_bindless_release(nullptr, nullptr); - state_.context->set_bindless_current(nullptr); // the retired generations go with state_.bindless below - } - state_.staging_queue.reset(); // it uses the context - if (state_.context && state_.bindless) { - // Every texture is gone by now (each held this device), and its views with it; samplers remain. - std::lock_guard lock(state_.descriptor_mutex); - for (const auto& [key, sampler] : state_.sampler_entries) - state_.context->vk.vkDestroySampler(state_.info.device, sampler, nullptr); - state_.sampler_entries.clear(); - state_.bindless.reset(); - } - state_.report_arena(); - if (state_.context && state_.arena.buffer) { - auto& vk = state_.context->vk; - vk.vkDestroyBuffer(state_.info.device, state_.arena.buffer, nullptr); - if (state_.arena.memory) vk.vkFreeMemory(state_.info.device, state_.arena.memory, nullptr); - } - if (state_.pipeline_cache_handle) - state_.context->vk.vkDestroyPipelineCache(state_.info.device, state_.pipeline_cache_handle, nullptr); - state_.context.reset(); - if (owned_.device) owned_.destroy_device(owned_.device, nullptr); - if (owned_.instance) owned_.destroy_instance(owned_.instance, nullptr); - } - - bool ok() const { return state_.context && state_.context->loaded(); } - const VulkanDeviceInfo& info() const { return state_.info; } - // Acceleration-structure resources work: KHR builds, or the XDXR records (which need the GPU address arena). - bool acceleration_structures() const { - return state_.info.ray_tracing || (state_.info.xdxr_acceleration_structures && state_.info.buffer_device_address); - } - bool upload_in_vram() const { return state_.upload_in_vram; } - leonida::VulkanContext& context() { return *state_.context; } - const leonida::BindlessSet* bindless() const { return state_.bindless.get(); } - const DeviceState& state() const { return state_; } - IUnknown* holder() { return identity(); } - // Console-extended CreateDescriptorHeap (Xbox slot 14): a heap at the title's console address. The proxy's - // handler (set_console_descriptor_heap_handler) calls this; a normal PC create never does. - HRESULT create_console_descriptor_heap(const D3D12_DESCRIPTOR_HEAP_DESC* desc, - D3D12_GPU_VIRTUAL_ADDRESS console_address, std::uint64_t console_size, - REFIID riid, void** out) { - auto* heap = new DescriptorHeap(state_, *desc, console_address, console_size); - heap->attach_device(identity()); - if (!heap->ok()) { - heap->Release(); - return E_OUTOFMEMORY; - } - return hand_out(heap, riid, out); - } - bool bind_sampler(const leonida::gfx10::SamplerWords& words) { return state_.bind_sampler(words); } - void own(const OwnedRuntime& owned) { owned_ = owned; } - void set_outer(IUnknown* outer) { outer_ = outer; } - - UINT STDMETHODCALLTYPE GetNodeCount() override { return 1; } - - // The Vulkan physical device's LUID, which is the DXGI adapter's on Windows. Zero (logged) when the driver has - // none to report (deviceLUIDValid false). - LUID STDMETHODCALLTYPE GetAdapterLuid() override { return state_.luid; } - - // The CUSTOM equivalent of a standard heap type, from the D3D12 documentation's table for the architecture - // D3D12_FEATURE_ARCHITECTURE reports. NUMA (a discrete GPU): DEFAULT is GPU-only memory in L1, UPLOAD - // write-combined and READBACK write-back system memory in L0, GPU_UPLOAD write-combined L1. UMA (an integrated - // GPU, CacheCoherentUMA FALSE): the same pages, all in L0, as the host runtime answers on a Radeon 780M (AMD - // 32.0.13030.13001). The pool only names the answer; memory is chosen by the CPU page property either way. CUSTOM - // and unknown types have - // no equivalent and get an all-zero answer (D3D12 reports them through the debug layer), with node 0 in both node - // masks as the host runtime gives it (d3d12_fence_timing_test compares CUSTOM, an unknown type and node mask 2). - D3D12_HEAP_PROPERTIES STDMETHODCALLTYPE GetCustomHeapProperties(UINT node_mask, D3D12_HEAP_TYPE type) override { - D3D12_HEAP_PROPERTIES properties{}; - properties.CreationNodeMask = properties.VisibleNodeMask = 1; - if (node_mask > 1) { - log_once("GetCustomHeapProperties node mask", int(node_mask)); - return properties; - } - switch (type) { - case D3D12_HEAP_TYPE_DEFAULT: - properties.CPUPageProperty = D3D12_CPU_PAGE_PROPERTY_NOT_AVAILABLE; - properties.MemoryPoolPreference = D3D12_MEMORY_POOL_L1; - break; - case D3D12_HEAP_TYPE_UPLOAD: - properties.CPUPageProperty = D3D12_CPU_PAGE_PROPERTY_WRITE_COMBINE; - properties.MemoryPoolPreference = D3D12_MEMORY_POOL_L0; - break; - case D3D12_HEAP_TYPE_READBACK: - properties.CPUPageProperty = D3D12_CPU_PAGE_PROPERTY_WRITE_BACK; - properties.MemoryPoolPreference = D3D12_MEMORY_POOL_L0; - break; - case D3D12_HEAP_TYPE_GPU_UPLOAD: - properties.CPUPageProperty = D3D12_CPU_PAGE_PROPERTY_WRITE_COMBINE; - properties.MemoryPoolPreference = D3D12_MEMORY_POOL_L1; - break; - default: - log_once("GetCustomHeapProperties heap type without a custom equivalent:", int(type)); - return properties; - } - if (state_.uma) properties.MemoryPoolPreference = D3D12_MEMORY_POOL_L0; - properties.Type = D3D12_HEAP_TYPE_CUSTOM; - return properties; - } - - HRESULT STDMETHODCALLTYPE SetEventOnMultipleFenceCompletion(ID3D12Fence* const* fences, const UINT64* values, - UINT count, D3D12_MULTIPLE_FENCE_WAIT_FLAGS flags, - HANDLE event) override { - return set_event_on_multiple_fence_completion(*state_.context, fences, values, count, flags, event, identity()); - } - HRESULT STDMETHODCALLTYPE GetDeviceRemovedReason() override { - if (removed_.load(std::memory_order_acquire)) return DXGI_ERROR_DEVICE_REMOVED; - return (state_.context && state_.context->is_device_lost()) ? DXGI_ERROR_DEVICE_REMOVED : S_OK; - } - - // Residency and power (D3D-33, docs/d3d12_vulkan.md section 4.1). Vulkan has no residency API: memory from - // vkAllocateMemory stays usable by the device until vkFreeMemory, and paging under pressure is the kernel - // driver's job (WDDM on Windows), invisible to the application. So every pageable object of this device is - // always resident, MakeResident has nothing to do and Evict, which D3D12 documents as a hint the runtime may - // defer, can be dropped. Only the arguments are checked; the objects themselves are not touched. - HRESULT STDMETHODCALLTYPE MakeResident(UINT count, ID3D12Pageable* const* objects) override { - return count && !objects ? E_INVALIDARG : S_OK; - } - - HRESULT STDMETHODCALLTYPE Evict(UINT count, ID3D12Pageable* const* objects) override { - return count && !objects ? E_INVALIDARG : S_OK; - } - - // Device1: priorities only order what the OS evicts first under memory pressure. VK_EXT_pageable_device_local_memory - // could pass them on, but it is optional and changes no result, so they are accepted and dropped. Any UINT is a - // valid priority (the D3D12_RESIDENCY_PRIORITY values are named points, the low 24 bits a refinement). As on the - // host runtime (d3d12_residency_test, RTX 3060 / 610.88), only objects that own their memory take one: committed - // resources and heaps. A placed resource (a reserved one too, by the same rule; not measured), a descriptor heap, a query heap or a fence is E_INVALIDARG. - // The host also removes its device then (DXGI_ERROR_INVALID_CALL); the layer doesn't, since a console title that - // sets priorities on its placed resources would lose its device over a hint. - HRESULT STDMETHODCALLTYPE SetResidencyPriority(UINT count, ID3D12Pageable* const* objects, - const D3D12_RESIDENCY_PRIORITY* priorities) override { - if (count && (!objects || !priorities)) return E_INVALIDARG; - for (UINT i = 0; i < count; ++i) { - if (from(objects[i])) continue; - const Resource* resource = from(objects[i]); - if (!resource || !resource->committed()) return E_INVALIDARG; - } - return S_OK; - } - - // Device3: the asynchronous MakeResident. The objects are already resident, so the work is complete at once - // and the fence is signalled from the CPU now. The caller's queue Wait on it must not hang, which is why the - // signal is kept although the residency part is a no-op. DENY_OVERBUDGET cannot fail: nothing is paged in. A - // null fence is accepted, as the host runtime does: there is nothing to signal. - HRESULT STDMETHODCALLTYPE EnqueueMakeResident(D3D12_RESIDENCY_FLAGS flags, UINT count, - ID3D12Pageable* const* objects, ID3D12Fence* fence, - UINT64 value) override { - if ((count && !objects) || (flags & ~D3D12_RESIDENCY_FLAG_DENY_OVERBUDGET)) return E_INVALIDARG; - return fence ? fence->Signal(value) : S_OK; - } - - // Stable power state pins GPU clocks for profiling, a developer-mode feature on Windows. Vulkan has no clock - // control (vendor tools do it outside the API), and the game's frame does not depend on the clocks, so the - // request is accepted. Success is what D3D12 returns on a machine where the call is allowed. - HRESULT STDMETHODCALLTYPE SetStablePowerState(BOOL) override { return S_OK; } - - // Device6: lets the driver run background shader recompilation and profiling-guided optimisation. Vulkan - // drivers do that, if at all, without an API to steer it, so there is nothing to start or stop. The completion - // event is set at once, since no measurement is running, and no further measurements are wanted. - HRESULT STDMETHODCALLTYPE SetBackgroundProcessingMode(D3D12_BACKGROUND_PROCESSING_MODE mode, - D3D12_MEASUREMENTS_ACTION action, HANDLE event, - BOOL* further_measurements) override { - if (unsigned(mode) > unsigned(D3D12_BACKGROUND_PROCESSING_MODE_DISABLE_PROFILING_BY_SYSTEM) || - unsigned(action) > unsigned(D3D12_MEASUREMENTS_ACTION_DISCARD_PREVIOUS)) - return E_INVALIDARG; - if (further_measurements) *further_measurements = FALSE; - if (event) SetEvent(event); - return S_OK; - } - - // STUB - HRESULT STDMETHODCALLTYPE EnumerateMetaCommands(UINT* count, D3D12_META_COMMAND_DESC*) override { - if (!count) return E_INVALIDARG; - *count = 0; - return S_OK; - } - - HRESULT STDMETHODCALLTYPE EnumerateMetaCommandParameters(REFGUID, D3D12_META_COMMAND_PARAMETER_STAGE, UINT*, - UINT*, D3D12_META_COMMAND_PARAMETER_DESC*) override { - return E_INVALIDARG; - } - - HRESULT STDMETHODCALLTYPE CreateMetaCommand(REFGUID, UINT, const void*, SIZE_T, REFIID, void** out) override { - if (out) *out = nullptr; - return E_INVALIDARG; - } - - // STUB - D3D12_DRIVER_MATCHING_IDENTIFIER_STATUS STDMETHODCALLTYPE CheckDriverMatchingIdentifier( - D3D12_SERIALIZED_DATA_TYPE type, const D3D12_SERIALIZED_DATA_DRIVER_MATCHING_IDENTIFIER*) override { - return type == D3D12_SERIALIZED_DATA_RAYTRACING_ACCELERATION_STRUCTURE - ? D3D12_DRIVER_MATCHING_IDENTIFIER_UNRECOGNIZED - : D3D12_DRIVER_MATCHING_IDENTIFIER_UNSUPPORTED_TYPE; - } - - // STUB - void STDMETHODCALLTYPE RemoveDevice() override { removed_.store(true, std::memory_order_release); } - - HRESULT STDMETHODCALLTYPE CreateCommandQueue(const D3D12_COMMAND_QUEUE_DESC* desc, REFIID riid, - void** out) override { - constexpr auto method = "ID3D12Device::CreateCommandQueue"; - if (!desc) return d3d12_trace::result(method, E_INVALIDARG); - // As the host runtime: no bundle queues, the three D3D12 priorities (realtime refused, below), one flag and - // one node. A valid description without an output is E_UNEXPECTED there, not a capability check. - if (desc->Type == D3D12_COMMAND_LIST_TYPE_BUNDLE || UINT(desc->Type) > D3D12_COMMAND_LIST_TYPE_VIDEO_ENCODE || - (desc->Priority != D3D12_COMMAND_QUEUE_PRIORITY_NORMAL && - desc->Priority != D3D12_COMMAND_QUEUE_PRIORITY_HIGH && - desc->Priority != D3D12_COMMAND_QUEUE_PRIORITY_GLOBAL_REALTIME) || - (desc->Flags & ~D3D12_COMMAND_QUEUE_FLAG_DISABLE_GPU_TIMEOUT) || desc->NodeMask > 1) { - log_once("CreateCommandQueue refused (type, priority, flags or node mask), type", desc->Type); - return d3d12_trace::result(method, E_INVALIDARG); - } - // Global realtime priority needs SeIncreaseBasePriorityPrivilege enabled in the effective token, as on the - // Windows D3D12 runtime; without it, this answer. Vulkan queue priorities (and VK_KHR_global_priority) are - // fixed at vkCreateDevice time before CreateCommandQueue is called, so a privileged request leases from the - // device's pre-created VkQueue pool like D3D12_COMMAND_QUEUE_PRIORITY_HIGH and logs the approximation once. - if (desc->Priority == D3D12_COMMAND_QUEUE_PRIORITY_GLOBAL_REALTIME && !has_global_realtime_privilege()) { - log_once("CreateCommandQueue refused (global realtime priority), type", desc->Type); - return d3d12_trace::result(method, DXGI_ERROR_ACCESS_DENIED); - } - if (!out) return d3d12_trace::result(method, E_UNEXPECTED); - *out = nullptr; - if (desc->Type != D3D12_COMMAND_LIST_TYPE_DIRECT && desc->Type != D3D12_COMMAND_LIST_TYPE_COMPUTE && - desc->Type != D3D12_COMMAND_LIST_TYPE_COPY) return d3d12_trace::result(method, E_INVALIDARG); - if (desc->Priority == D3D12_COMMAND_QUEUE_PRIORITY_GLOBAL_REALTIME) - log_once("CreateCommandQueue: global realtime priority runs on a standard-priority Vulkan queue, type", - desc->Type); - // Caller-owned devices that only provide the legacy queue cannot acquire more handles from their VkDevice. - if (state_.info.command_queues.empty()) - return d3d12_trace::result(method, create_command_queue(*state_.context, state_.info.queue, - state_.info.queue_family, *desc, riid, out, - identity(), state_.clock)); - // A VkQueue of the type's own family first, then the graphics family; shared when every one is in use. - const bool compute = desc->Type == D3D12_COMMAND_LIST_TYPE_COMPUTE; - const bool copy = desc->Type == D3D12_COMMAND_LIST_TYPE_COPY; - auto& own_users = compute ? compute_users_ : copy_users_; - const auto& own_queues = compute ? state_.info.compute_queues : state_.info.copy_queues; - const std::uint32_t own_family = compute ? state_.info.compute_family : state_.info.copy_family; - const std::span own = - compute || copy ? std::span(own_users) : std::span(); - std::vector* users = nullptr; - std::size_t slot = 0; - std::uint32_t sharing = 0; // other D3D12 queues already on the chosen VkQueue - { - std::lock_guard lock(queue_mutex_); - const auto chosen = leonida::pick_queue_slot({own, queue_users_}); - if (chosen.pool == SIZE_MAX) return d3d12_trace::result(method, E_OUTOFMEMORY); // no VkQueue at all - users = chosen.pool == 0 ? &own_users : &queue_users_; - slot = chosen.index; - sharing = (*users)[slot]++; - } - const bool own_pool = users != &queue_users_; - if (sharing) - log_once("CreateCommandQueue: every Vulkan queue of the family is in use; this D3D12 queue shares one with " - "the others on it (their batches run in submission order), type", desc->Type); - // Child holds a device reference until after the lease has been released. - std::shared_ptr lease(nullptr, [this, users, slot](void*) { - std::lock_guard lock(queue_mutex_); - --(*users)[slot]; - }); - const VkQueue queue = own_pool ? own_queues[slot] : state_.info.command_queues[slot]; - const std::uint32_t family = own_pool ? own_family : state_.info.queue_family; - return d3d12_trace::result(method, create_command_queue(*state_.context, queue, family, *desc, riid, out, - identity(), state_.clock, std::move(lease))); - } - - HRESULT STDMETHODCALLTYPE CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE type, REFIID riid, void** out) override { - constexpr auto method = "ID3D12Device::CreateCommandAllocator"; - return d3d12_trace::result(method, create_command_allocator(type, riid, out, identity())); - } - - HRESULT STDMETHODCALLTYPE CreateCommandList(UINT node_mask, D3D12_COMMAND_LIST_TYPE type, - ID3D12CommandAllocator* allocator, ID3D12PipelineState* state, - REFIID riid, void** out) override { - constexpr auto method = "ID3D12Device::CreateCommandList"; - if (out) *out = nullptr; - if (node_mask & ~1u) return d3d12_trace::result(method, E_INVALIDARG); // one node, as the host answers - // The initial pipeline state is set as SetPipelineState would set it (a bundle's is its first deferred call). - HRESULT hr = create_command_list(type, allocator, riid, out, identity(), state); - return d3d12_trace::result(method, hr); - } - - // Device4: a list created closed, without an allocator. - HRESULT STDMETHODCALLTYPE CreateCommandList1(UINT node_mask, D3D12_COMMAND_LIST_TYPE type, - D3D12_COMMAND_LIST_FLAGS, REFIID riid, void** out) override { - constexpr auto method = "ID3D12Device4::CreateCommandList1"; - // The host runtime's order ("command list1:" cases): one node and a type up to VIDEO_ENCODE (non-zero - // D3D12_COMMAND_LIST_FLAGS are ignored by the host runtime), then a null output is E_UNEXPECTED. - if (out) *out = nullptr; - if ((node_mask & ~1u) || UINT(type) > UINT(D3D12_COMMAND_LIST_TYPE_VIDEO_ENCODE)) - return d3d12_trace::result(method, E_INVALIDARG); - if (!out) return d3d12_trace::result(method, E_UNEXPECTED); - ID3D12CommandAllocator* allocator = nullptr; - HRESULT hr = create_command_allocator(type, IID_PPV_ARGS(&allocator), identity()); - if (FAILED(hr)) return d3d12_trace::result(method, hr); - ID3D12GraphicsCommandList* list = nullptr; - hr = create_command_list(type, allocator, IID_PPV_ARGS(&list), identity()); - allocator->Release(); - if (FAILED(hr)) return d3d12_trace::result(method, hr); - list->Close(); - hr = list->QueryInterface(riid, out); - list->Release(); - return d3d12_trace::result(method, hr); - } - - HRESULT STDMETHODCALLTYPE CreateFence(UINT64 initial, D3D12_FENCE_FLAGS flags, REFIID riid, void** out) override { - constexpr auto method = "ID3D12Device::CreateFence"; - // As the host runtime: known flags only, cross-adapter only when shared, and no non-monitored fences - // (refused there even with both sharing flags). A null output is a capability check. - constexpr UINT known = D3D12_FENCE_FLAG_SHARED | D3D12_FENCE_FLAG_SHARED_CROSS_ADAPTER | - D3D12_FENCE_FLAG_NON_MONITORED; - if ((UINT(flags) & ~known) || (flags & D3D12_FENCE_FLAG_NON_MONITORED) || - ((flags & D3D12_FENCE_FLAG_SHARED_CROSS_ADAPTER) && !(flags & D3D12_FENCE_FLAG_SHARED))) { - log_once("CreateFence refused, flags", int(flags)); - return d3d12_trace::result(method, E_INVALIDARG); - } - if (!out) return d3d12_trace::result(method, S_FALSE); - return d3d12_trace::result(method, create_fence(*state_.context, initial, flags, riid, out, - identity())); - } - - HRESULT STDMETHODCALLTYPE CreateCommandSignature(const D3D12_COMMAND_SIGNATURE_DESC* desc, - ID3D12RootSignature* root_signature, REFIID riid, - void** out) override { - if (out) *out = nullptr; - // The host refuses these with E_INVALIDARG (compare_invalid_arguments, "command signature:"): one node, a - // known type per argument, exactly one draw or dispatch and it comes last, a root signature for root - // arguments, and a stride that is a multiple of 4 and holds every argument. - if (!desc || desc->NumArgumentDescs == 0 || !desc->pArgumentDescs || (desc->NodeMask & ~1u)) - return E_INVALIDARG; - UINT64 size = 0; // 64-bit: a large Num32BitValuesToSet must not wrap past ByteStride - for (UINT i = 0; i < desc->NumArgumentDescs; ++i) { - const D3D12_INDIRECT_ARGUMENT_DESC& arg = desc->pArgumentDescs[i]; - switch (arg.Type) { - case D3D12_INDIRECT_ARGUMENT_TYPE_DRAW: size += sizeof(D3D12_DRAW_ARGUMENTS); break; - case D3D12_INDIRECT_ARGUMENT_TYPE_DRAW_INDEXED: size += sizeof(D3D12_DRAW_INDEXED_ARGUMENTS); break; - case D3D12_INDIRECT_ARGUMENT_TYPE_DISPATCH: size += sizeof(D3D12_DISPATCH_ARGUMENTS); break; - case D3D12_INDIRECT_ARGUMENT_TYPE_DISPATCH_RAYS: size += sizeof(D3D12_DISPATCH_RAYS_DESC); break; - case D3D12_INDIRECT_ARGUMENT_TYPE_DISPATCH_MESH: size += sizeof(D3D12_DISPATCH_MESH_ARGUMENTS); break; - case D3D12_INDIRECT_ARGUMENT_TYPE_VERTEX_BUFFER_VIEW: size += sizeof(D3D12_VERTEX_BUFFER_VIEW); break; - case D3D12_INDIRECT_ARGUMENT_TYPE_INDEX_BUFFER_VIEW: size += sizeof(D3D12_INDEX_BUFFER_VIEW); break; - case D3D12_INDIRECT_ARGUMENT_TYPE_CONSTANT: size += UINT64{4} * arg.Constant.Num32BitValuesToSet; break; - case compat::kIndirectArgumentIncrementingConstant: size += 4; break; - case D3D12_INDIRECT_ARGUMENT_TYPE_CONSTANT_BUFFER_VIEW: - case D3D12_INDIRECT_ARGUMENT_TYPE_SHADER_RESOURCE_VIEW: - case D3D12_INDIRECT_ARGUMENT_TYPE_UNORDERED_ACCESS_VIEW: size += sizeof(D3D12_GPU_VIRTUAL_ADDRESS); break; - default: return E_INVALIDARG; - } - const bool draw = arg.Type <= D3D12_INDIRECT_ARGUMENT_TYPE_DISPATCH || - arg.Type == D3D12_INDIRECT_ARGUMENT_TYPE_DISPATCH_RAYS || - arg.Type == D3D12_INDIRECT_ARGUMENT_TYPE_DISPATCH_MESH; - const bool root_argument = !draw && arg.Type != D3D12_INDIRECT_ARGUMENT_TYPE_VERTEX_BUFFER_VIEW && - arg.Type != D3D12_INDIRECT_ARGUMENT_TYPE_INDEX_BUFFER_VIEW; - if (draw != (i + 1 == desc->NumArgumentDescs) || (root_argument && !root_signature)) return E_INVALIDARG; - } - if (desc->ByteStride % 4 || desc->ByteStride < size) return E_INVALIDARG; - if (!out) return E_UNEXPECTED; // the host's answer for a valid description and no output - leonida::IndirectKind kind; - switch (desc->pArgumentDescs[desc->NumArgumentDescs - 1].Type) { - case D3D12_INDIRECT_ARGUMENT_TYPE_DRAW: kind = leonida::IndirectKind::draw; break; - case D3D12_INDIRECT_ARGUMENT_TYPE_DRAW_INDEXED: kind = leonida::IndirectKind::draw_indexed; break; - case D3D12_INDIRECT_ARGUMENT_TYPE_DISPATCH: kind = leonida::IndirectKind::dispatch; break; - default: return E_NOTIMPL; - } - return create_command_signature(kind, desc->ByteStride, riid, out, identity()); - } - - void STDMETHODCALLTYPE GetRaytracingAccelerationStructurePrebuildInfo( - const D3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_INPUTS* desc, - D3D12_RAYTRACING_ACCELERATION_STRUCTURE_PREBUILD_INFO* out) override { - if (!out) return; - *out = {}; - if (!desc) return; - if (desc->Type != D3D12_RAYTRACING_ACCELERATION_STRUCTURE_TYPE_TOP_LEVEL && - desc->Type != D3D12_RAYTRACING_ACCELERATION_STRUCTURE_TYPE_BOTTOM_LEVEL) - return; - if (desc->DescsLayout != D3D12_ELEMENTS_LAYOUT_ARRAY && - desc->DescsLayout != D3D12_ELEMENTS_LAYOUT_ARRAY_OF_POINTERS) - return; - const bool is_tlas = (desc->Type == D3D12_RAYTRACING_ACCELERATION_STRUCTURE_TYPE_TOP_LEVEL); - if (!is_tlas && desc->NumDescs > 0) { - if (desc->DescsLayout == D3D12_ELEMENTS_LAYOUT_ARRAY) { - if (!desc->pGeometryDescs) return; - } else { - if (!desc->ppGeometryDescs) return; - for (UINT i = 0; i < desc->NumDescs; ++i) - if (!desc->ppGeometryDescs[i]) return; - } - } - auto& vk = state_.context->vk; - if (state_.context->xdxr_acceleration_structures()) { - // XDXR records: the layout depends only on the triangle or instance count and on whether the nodes are - // BOX16 (MINIMIZE_MEMORY, bottom level; xdxr_build.h). Its size has room for the most nodes a tree of - // that many elements can have; a build's own size, in its header, is what COMPACTED_SIZE reports. An - // update refits (no sort); the build's scratch size covers it. - leonida::BuildAccelerationStructure build{}; - build.is_tlas = is_tlas; - if (desc->Flags & D3D12_RAYTRACING_ACCELERATION_STRUCTURE_BUILD_FLAG_MINIMIZE_MEMORY) - build.build_flags |= VK_BUILD_ACCELERATION_STRUCTURE_LOW_MEMORY_BIT_KHR; - if (build.is_tlas) { - build.instance_count = desc->NumDescs; - } else { - for (UINT i = 0; i < desc->NumDescs; ++i) { - const D3D12_RAYTRACING_GEOMETRY_DESC* gd = - (desc->DescsLayout == D3D12_ELEMENTS_LAYOUT_ARRAY_OF_POINTERS) - ? desc->ppGeometryDescs[i] - : &desc->pGeometryDescs[i]; - if (gd->Type != D3D12_RAYTRACING_GEOMETRY_TYPE_TRIANGLES) continue; - leonida::RtTriangleGeometry t{}; - t.vertex_count = gd->Triangles.VertexCount; - t.index_count = gd->Triangles.IndexCount; - t.index_type = gd->Triangles.IndexFormat == DXGI_FORMAT_UNKNOWN ? 0u : 1u; - build.triangles.push_back(t); - } - } - leonida::XdxrLayout layout; - if (!layout.compute(leonida::VulkanContext::xdxr_elements(build), build.is_tlas, - leonida::VulkanContext::xdxr_box16(build))) - return; - out->ResultDataMaxSizeInBytes = layout.size; - out->ScratchDataSizeInBytes = layout.scratch; - out->UpdateScratchDataSizeInBytes = layout.scratch; - return; - } - if (!state_.info.ray_tracing || !vk.vkGetAccelerationStructureBuildSizesKHR) return; - - std::vector geoms; - std::vector max_prims; - if (is_tlas) { - VkAccelerationStructureGeometryKHR g{VK_STRUCTURE_TYPE_ACCELERATION_STRUCTURE_GEOMETRY_KHR}; - g.geometryType = VK_GEOMETRY_TYPE_INSTANCES_KHR; - g.geometry.instances.sType = VK_STRUCTURE_TYPE_ACCELERATION_STRUCTURE_GEOMETRY_INSTANCES_DATA_KHR; - g.geometry.instances.arrayOfPointers = - desc->DescsLayout == D3D12_ELEMENTS_LAYOUT_ARRAY_OF_POINTERS ? VK_TRUE : VK_FALSE; - geoms.push_back(g); - max_prims.push_back(desc->NumDescs); - } else { - for (UINT i = 0; i < desc->NumDescs; ++i) { - const D3D12_RAYTRACING_GEOMETRY_DESC* gd = - (desc->DescsLayout == D3D12_ELEMENTS_LAYOUT_ARRAY_OF_POINTERS) - ? (desc->ppGeometryDescs ? desc->ppGeometryDescs[i] : nullptr) - : (desc->pGeometryDescs ? &desc->pGeometryDescs[i] : nullptr); - if (!gd || gd->Type != D3D12_RAYTRACING_GEOMETRY_TYPE_TRIANGLES) continue; - VkAccelerationStructureGeometryKHR g{VK_STRUCTURE_TYPE_ACCELERATION_STRUCTURE_GEOMETRY_KHR}; - g.geometryType = VK_GEOMETRY_TYPE_TRIANGLES_KHR; - g.flags = (gd->Flags & D3D12_RAYTRACING_GEOMETRY_FLAG_OPAQUE) ? VK_GEOMETRY_OPAQUE_BIT_KHR : 0u; - auto& tr = g.geometry.triangles; - tr.sType = VK_STRUCTURE_TYPE_ACCELERATION_STRUCTURE_GEOMETRY_TRIANGLES_DATA_KHR; - tr.vertexFormat = (gd->Triangles.VertexFormat == DXGI_FORMAT_R32G32_FLOAT) ? VK_FORMAT_R32G32_SFLOAT - : VK_FORMAT_R32G32B32_SFLOAT; - tr.vertexStride = gd->Triangles.VertexBuffer.StrideInBytes; - tr.maxVertex = gd->Triangles.VertexCount ? (gd->Triangles.VertexCount - 1u) : 0u; - tr.indexType = (gd->Triangles.IndexFormat == DXGI_FORMAT_R16_UINT) - ? VK_INDEX_TYPE_UINT16 - : ((gd->Triangles.IndexFormat == DXGI_FORMAT_R32_UINT) ? VK_INDEX_TYPE_UINT32 - : VK_INDEX_TYPE_NONE_KHR); - geoms.push_back(g); - const std::uint32_t prims = - (gd->Triangles.IndexFormat != DXGI_FORMAT_UNKNOWN && gd->Triangles.IndexCount >= 3) - ? (gd->Triangles.IndexCount / 3u) - : (gd->Triangles.VertexCount / 3u); - max_prims.push_back(prims); - } - } - if (geoms.empty()) return; - - VkAccelerationStructureBuildGeometryInfoKHR bgi{ - VK_STRUCTURE_TYPE_ACCELERATION_STRUCTURE_BUILD_GEOMETRY_INFO_KHR}; - bgi.type = is_tlas ? VK_ACCELERATION_STRUCTURE_TYPE_TOP_LEVEL_KHR - : VK_ACCELERATION_STRUCTURE_TYPE_BOTTOM_LEVEL_KHR; - if (desc->Flags & D3D12_RAYTRACING_ACCELERATION_STRUCTURE_BUILD_FLAG_ALLOW_UPDATE) - bgi.flags |= VK_BUILD_ACCELERATION_STRUCTURE_ALLOW_UPDATE_BIT_KHR; - if (desc->Flags & D3D12_RAYTRACING_ACCELERATION_STRUCTURE_BUILD_FLAG_PREFER_FAST_TRACE) - bgi.flags |= VK_BUILD_ACCELERATION_STRUCTURE_PREFER_FAST_TRACE_BIT_KHR; - if (desc->Flags & D3D12_RAYTRACING_ACCELERATION_STRUCTURE_BUILD_FLAG_PREFER_FAST_BUILD) - bgi.flags |= VK_BUILD_ACCELERATION_STRUCTURE_PREFER_FAST_BUILD_BIT_KHR; - if (desc->Flags & D3D12_RAYTRACING_ACCELERATION_STRUCTURE_BUILD_FLAG_MINIMIZE_MEMORY) // as the build gets it - bgi.flags |= VK_BUILD_ACCELERATION_STRUCTURE_LOW_MEMORY_BIT_KHR; - bgi.geometryCount = static_cast(geoms.size()); - bgi.pGeometries = geoms.data(); - - VkAccelerationStructureBuildSizesInfoKHR sizes{VK_STRUCTURE_TYPE_ACCELERATION_STRUCTURE_BUILD_SIZES_INFO_KHR}; - vk.vkGetAccelerationStructureBuildSizesKHR(state_.info.device, VK_ACCELERATION_STRUCTURE_BUILD_TYPE_DEVICE_KHR, - &bgi, max_prims.data(), &sizes); - out->ResultDataMaxSizeInBytes = sizes.accelerationStructureSize; - out->ScratchDataSizeInBytes = sizes.buildScratchSize; - out->UpdateScratchDataSizeInBytes = sizes.updateScratchSize; - } - - HRESULT STDMETHODCALLTYPE CreateDescriptorHeap(const D3D12_DESCRIPTOR_HEAP_DESC* desc, REFIID riid, - void** out) override { - constexpr auto method = "ID3D12Device::CreateDescriptorHeap"; - if (out) *out = nullptr; - if (!desc) return d3d12_trace::result(method, E_INVALIDARG); - // As the host runtime: a null output is a capability check, answered before the rules below (S_FALSE even - // for a shader-visible RTV heap). Zero descriptors are allowed, RTV and DSV heaps are never shader-visible, - // one flag and one node. - if (!out) return d3d12_trace::result(method, S_FALSE); - if ((desc->Flags & ~D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE) || desc->NodeMask > 1 || - ((desc->Flags & D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE) && - (desc->Type == D3D12_DESCRIPTOR_HEAP_TYPE_RTV || desc->Type == D3D12_DESCRIPTOR_HEAP_TYPE_DSV))) { - log_once("CreateDescriptorHeap refused (flags or node mask), type", desc->Type); - return d3d12_trace::result(method, E_INVALIDARG); - } - auto* heap = new DescriptorHeap(state_, *desc); - heap->attach_device(identity()); - if (!heap->ok()) { - heap->Release(); - return d3d12_trace::result(method, E_OUTOFMEMORY); - } - return d3d12_trace::result(method, hand_out(heap, riid, out)); - } - - HRESULT STDMETHODCALLTYPE CreateQueryHeap(const D3D12_QUERY_HEAP_DESC* desc, REFIID riid, void** out) override { - if (out) *out = nullptr; - // The host runtime's order (compare_invalid_arguments, "query heap:"): the description first, refused with - // E_INVALIDARG for no queries, a node other than node 0 or a type past PIPELINE_STATISTICS1 (7; 6 has no - // name in the SDK but the host takes it), then E_UNEXPECTED for a null output. A known type this layer - // can't create stays E_NOTIMPL. - if (!desc || !desc->Count || desc->NodeMask > 1 || - UINT(desc->Type) > UINT(D3D12_QUERY_HEAP_TYPE_PIPELINE_STATISTICS1)) - return E_INVALIDARG; - if (!out) return E_UNEXPECTED; - auto* heap = new QueryHeap(state_); - heap->attach_device(identity()); - if (const HRESULT hr = heap->create(*desc); FAILED(hr)) { - heap->Release(); - return hr; - } - return hand_out(heap, riid, out); - } - - HRESULT STDMETHODCALLTYPE CreateRootSignature(UINT node_mask, const void* blob, SIZE_T size, REFIID riid, - void** out) override { - // The host runtime answers a null output with S_FALSE before it looks at the blob or the node mask - // (compare_invalid_arguments, "root signature:"). Otherwise it refuses a node other than node 0, and a DXBC - // container whose own size (the dword at +24) is not the size passed. - if (!out) return S_FALSE; - *out = nullptr; - if (!blob || !size || (node_mask & ~1u)) return E_INVALIDARG; - const auto* bytes = static_cast(blob); - if (size >= 28 && std::memcmp(bytes, "DXBC", 4) == 0) { - std::uint32_t container_size = 0; - std::memcpy(&container_size, bytes + 24, sizeof(container_size)); - if (container_size != size) return E_INVALIDARG; - } - // The repository's root-signature model (runtime/src/root_signature.h): parse the RTS0 blob, then pack - // the parameters into the 32 user-data dwords. pack() refuses what it cannot place (more than 32 dwords: - // the console spills those to memory, in a layout that is still open), and so does this. - const rt::rootsig::DecodeResult parsed = rt::rootsig::parse_rts0(bytes, size); - if (!parsed.ok) { - RT_LOG_ERROR("d3d12: root signature not understood: %s\n", parsed.error.c_str()); - return E_INVALIDARG; - } - // Two layouts, one per bind point (RootArgumentLayout): graphics keeps pack(), compute takes the console - // layout pack_stage() measured (D3D-448). The signature is refused only when neither can place it. - const rt::rootsig::PackResult packed = rt::rootsig::pack(parsed.sig); - const rt::rootsig::StagePackResult compute = rt::rootsig::pack_stage(parsed.sig, rt::rootsig::Stage::Compute); - if (!packed.ok && !compute.ok) { - RT_LOG_ERROR("d3d12: root signature refused: %s (compute: %s)\n", packed.error.c_str(), - compute.error.c_str()); - return E_INVALIDARG; - } - if (!packed.ok) - RT_LOG_WARN("d3d12: root signature usable for compute only: %s\n", packed.error.c_str()); - if (!compute.ok) - RT_LOG_WARN("d3d12: root signature usable for graphics only: %s\n", compute.error.c_str()); - RootArgumentLayout layout; - layout.flags = parsed.sig.flags; - layout.graphics_ok = packed.ok; - layout.compute_ok = compute.ok; - for (std::size_t i = 0; i < parsed.sig.params.size(); ++i) { - std::uint32_t first = UINT32_MAX; - for (std::uint32_t d = 0; packed.ok && d < packed.dword_count; ++d) - if (packed.provenance[d].param_index == i) { - first = d; - break; - } - layout.parameters.push_back({parsed.sig.params[i].type, first, parsed.sig.params[i].num_values, - compute.ok ? compute.first_sgpr[i] : rt::rootsig::kNoSgpr}); - } - register_static_samplers(parsed.sig); - auto* signature = new RootSignature( - std::move(layout), leonida::sha256_hex({static_cast(blob), size})); - signature->attach_device(identity()); - return hand_out(signature, riid, out); - } - - // PC slot 11; the Xbox ABI reaches it through device slots 62 and 67 (the proxy forwards). - HRESULT STDMETHODCALLTYPE CreateComputePipelineState(const D3D12_COMPUTE_PIPELINE_STATE_DESC* desc, REFIID riid, - void** out) override { - if (!out) return E_POINTER; - *out = nullptr; - if (!desc) return E_INVALIDARG; - leonida::cached_pso::Key key = pipeline_key(*desc); - if (const HRESULT hr = check_cached_pso(state_.pso_identity, key, desc->CachedPSO); FAILED(hr)) return hr; - auto* pipeline = new PipelineState(state_); - pipeline->attach_device(identity()); - if (const HRESULT hr = pipeline->create_compute(*desc); FAILED(hr)) { - pipeline->Release(); - return hr; - } - pipeline->set_cache_key(std::move(key)); - return hand_out(pipeline, riid, out); - } - - HRESULT STDMETHODCALLTYPE CreateGraphicsPipelineState(const D3D12_GRAPHICS_PIPELINE_STATE_DESC* desc, REFIID riid, - void** out) override { - if (!out) return E_POINTER; - *out = nullptr; - if (!desc) return E_INVALIDARG; - leonida::cached_pso::Key key = pipeline_key(*desc); - if (const HRESULT hr = check_cached_pso(state_.pso_identity, key, desc->CachedPSO); FAILED(hr)) return hr; - auto* pipeline = new PipelineState(state_); - pipeline->attach_device(identity()); - if (const HRESULT hr = pipeline->create_graphics(*desc); FAILED(hr)) { - pipeline->Release(); - return hr; - } - pipeline->set_cache_key(std::move(key)); - return hand_out(pipeline, riid, out); - } - - // Device1: in-memory pipeline library (docs/d3d12_vulkan.md sections 3.6 and 4). - HRESULT STDMETHODCALLTYPE CreatePipelineLibrary(const void* blob, SIZE_T size, REFIID riid, void** out) override { - constexpr auto method = "ID3D12Device1::CreatePipelineLibrary"; - // A refused blob leaves *out as it was, as the host runtime does; a wrong interface nulls it (hand_out). - if (size > 0) { - const HRESULT checked = PipelineLibrary::check_blob(blob, size); - if (FAILED(checked)) return d3d12_trace::result(method, checked); - } - if (!out) return d3d12_trace::result(method, S_FALSE); - *out = nullptr; - auto* lib = new PipelineLibrary(); - lib->attach_device(identity()); - return d3d12_trace::result(method, hand_out(lib, riid, out)); - } - - // Device9: process-wide shader cache sessions (in-memory and disk-backed) and control (D3D-34). - HRESULT STDMETHODCALLTYPE CreateShaderCacheSession(const D3D12_SHADER_CACHE_SESSION_DESC* desc, REFIID riid, - void** out) override { - constexpr auto method = "ID3D12Device9::CreateShaderCacheSession"; - if (out) *out = nullptr; - if (!desc) return d3d12_trace::result(method, E_INVALIDARG); - const GUID zero_guid{}; - if (std::memcmp(&desc->Identifier, &zero_guid, sizeof(GUID)) == 0) - return d3d12_trace::result(method, E_INVALIDARG); - if (desc->Mode != D3D12_SHADER_CACHE_MODE_MEMORY && desc->Mode != D3D12_SHADER_CACHE_MODE_DISK) - return d3d12_trace::result(method, E_INVALIDARG); - constexpr UINT kKnownFlags = D3D12_SHADER_CACHE_FLAG_DRIVER_VERSIONED | D3D12_SHADER_CACHE_FLAG_USE_WORKING_DIR; - if (UINT(desc->Flags) & ~kKnownFlags) return d3d12_trace::result(method, E_INVALIDARG); - if (!out) return d3d12_trace::result(method, S_FALSE); - std::wstring disk_path; - if (desc->Mode == D3D12_SHADER_CACHE_MODE_DISK) { - VkPhysicalDeviceProperties props{}; - if (state_.info.get_instance_proc && state_.info.instance && state_.info.physical) { - if (const auto get_props = reinterpret_cast( - state_.info.get_instance_proc(state_.info.instance, "vkGetPhysicalDeviceProperties"))) - get_props(state_.info.physical, &props); - } - const auto path = shader_cache_disk_path(*desc, props); - if (path.empty()) return d3d12_trace::result(method, E_FAIL); - disk_path = path.wstring(); - } - const ShaderCacheKey key{desc->Identifier, desc->Mode, std::move(disk_path)}; - auto& registry = process_shader_cache_registry(); - const UINT max_file_bytes = desc->MaximumValueFileSizeBytes ? desc->MaximumValueFileSizeBytes - : ShaderCacheStore::kDefaultMaxValueFileBytes; - std::shared_ptr store; - if (const HRESULT hr = registry.acquire(key, desc->Version, max_file_bytes, store); FAILED(hr)) - return d3d12_trace::result(method, hr); - auto* session = new ShaderCacheSession(*desc, key, registry, std::move(store)); - session->attach_device(identity()); - return d3d12_trace::result(method, hand_out(session, riid, out)); - } - - HRESULT STDMETHODCALLTYPE ShaderCacheControl(D3D12_SHADER_CACHE_KIND_FLAGS kinds, - D3D12_SHADER_CACHE_CONTROL_FLAGS control) override { - constexpr auto method = "ID3D12Device9::ShaderCacheControl"; - constexpr UINT kKnownKinds = D3D12_SHADER_CACHE_KIND_FLAG_IMPLICIT_D3D_CACHE_FOR_DRIVER | - D3D12_SHADER_CACHE_KIND_FLAG_IMPLICIT_D3D_CONVERSIONS | - D3D12_SHADER_CACHE_KIND_FLAG_IMPLICIT_DRIVER_MANAGED | - D3D12_SHADER_CACHE_KIND_FLAG_APPLICATION_MANAGED; - constexpr UINT kKnownControls = D3D12_SHADER_CACHE_CONTROL_FLAG_DISABLE | - D3D12_SHADER_CACHE_CONTROL_FLAG_ENABLE | D3D12_SHADER_CACHE_CONTROL_FLAG_CLEAR; - if (!kinds || (UINT(kinds) & ~kKnownKinds) || !control || (UINT(control) & ~kKnownControls)) - return d3d12_trace::result(method, E_INVALIDARG); - if ((control & D3D12_SHADER_CACHE_CONTROL_FLAG_ENABLE) && (control & D3D12_SHADER_CACHE_CONTROL_FLAG_DISABLE)) - return d3d12_trace::result(method, E_INVALIDARG); - auto& registry = process_shader_cache_registry(); - if (kinds & D3D12_SHADER_CACHE_KIND_FLAG_APPLICATION_MANAGED) { - if (control & D3D12_SHADER_CACHE_CONTROL_FLAG_CLEAR) registry.clear_all(); - if (control & D3D12_SHADER_CACHE_CONTROL_FLAG_DISABLE) - registry.disabled.store(true, std::memory_order_relaxed); - if (control & D3D12_SHADER_CACHE_CONTROL_FLAG_ENABLE) - registry.disabled.store(false, std::memory_order_relaxed); - } - return d3d12_trace::result(method, S_OK); - } - - // ID3D12Device2: a PSO from a pipeline state stream. A CS makes a compute PSO, an MS a mesh PSO, a VS the same - // graphics PSO CreateGraphicsPipelineState makes (parse_pipeline_stream). - HRESULT STDMETHODCALLTYPE CreatePipelineState(const D3D12_PIPELINE_STATE_STREAM_DESC* desc, REFIID riid, - void** out) override { - constexpr const char* method = "ID3D12Device2::CreatePipelineState"; - if (!out) return d3d12_trace::result(method, E_POINTER); - *out = nullptr; - if (!desc) return d3d12_trace::result(method, E_INVALIDARG); - PipelineStream stream; - if (const HRESULT hr = parse_pipeline_stream(*desc, stream); FAILED(hr)) return d3d12_trace::result(method, hr); - auto* pipeline = new PipelineState(state_); - pipeline->attach_device(identity()); - const HRESULT hr = stream.has_cs ? pipeline->create_compute(stream.compute) - : pipeline->create_graphics(stream.graphics, &stream.ms, &stream.as); - if (FAILED(hr)) { - pipeline->Release(); - return d3d12_trace::result(method, hr); - } - return d3d12_trace::result(method, hand_out(pipeline, riid, out)); - } - - UINT STDMETHODCALLTYPE GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE) override { - return kDescriptorSize; - } - - void STDMETHODCALLTYPE CreateRenderTargetView(ID3D12Resource* resource, const D3D12_RENDER_TARGET_VIEW_DESC* desc, - D3D12_CPU_DESCRIPTOR_HANDLE destination) override { - d3d12_trace::record("ID3D12Device::CreateRenderTargetView"); - if (!destination.ptr) return; - leonida::TargetView view{}; - leonida::ResourceId rid = 0; - D3D12_RESOURCE_DESC rd{}; - const Resource* r = Resource::from(resource); - if (r) { - rid = r->id(); - rd = const_cast(r)->GetDesc(); - } else if (resource && state_.context->has_resource(resource_id(resource))) { - rid = resource_id(resource); - rd = resource->GetDesc(); - } - if (rid) { - view = {rid, 0, 0, rd.DepthOrArraySize}; - if (rd.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE3D) { - view = volume_rtv(rid, rd, desc); - } else if (desc && desc->ViewDimension == D3D12_RTV_DIMENSION_TEXTURE1D) { - view = line_target_view(rid, rd, desc->Texture1D.MipSlice, 0, 1); - } else if (desc && desc->ViewDimension == D3D12_RTV_DIMENSION_TEXTURE1DARRAY) { - view = line_target_view(rid, rd, desc->Texture1DArray.MipSlice, - desc->Texture1DArray.FirstArraySlice, desc->Texture1DArray.ArraySize); - } else if (desc && desc->ViewDimension == D3D12_RTV_DIMENSION_TEXTURE2D) { - view = {rid, desc->Texture2D.MipSlice, 0, 1}; - } else if (desc && desc->ViewDimension == D3D12_RTV_DIMENSION_TEXTURE2DMS) { - view = {rid, 0, 0, 1}; - } else if (desc && desc->ViewDimension == D3D12_RTV_DIMENSION_TEXTURE2DARRAY) { - view = {rid, desc->Texture2DArray.MipSlice, desc->Texture2DArray.FirstArraySlice, - view_slices(rd, desc->Texture2DArray.FirstArraySlice, desc->Texture2DArray.ArraySize)}; - } else if (desc && desc->ViewDimension == D3D12_RTV_DIMENSION_TEXTURE2DMSARRAY) { - // Multisample textures have one mip, so only the slice range is chosen (as for the DSV). - view = {rid, 0, desc->Texture2DMSArray.FirstArraySlice, - view_slices(rd, desc->Texture2DMSArray.FirstArraySlice, desc->Texture2DMSArray.ArraySize)}; - } else if (desc) { - log_once("render-target view dimension not supported:", desc->ViewDimension); - view = {}; - } - // A TYPELESS color texture of any family takes RTVs in its family's formats (D3D-275; RGBA8 only before). - const bool typeless_color = vulkan_format(rd.Format, false).typeless && - !(rd.Flags & D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL); - const bool typed_rgba8 = rd.Format == DXGI_FORMAT_R8G8B8A8_UNORM || - rd.Format == DXGI_FORMAT_R8G8B8A8_UNORM_SRGB || rd.Format == DXGI_FORMAT_R8G8B8A8_UINT; - // An RGBA8 or BGRA8 texture whose castable list names the RTV's format in the other channel order, or - // across B8G8R8X8 and B8G8R8A8, gets an RTV in that format. - const DXGI_FORMAT asked = desc && desc->Format != DXGI_FORMAT_UNKNOWN ? desc->Format : rd.Format; - const bool cast_listed = r && asked != rd.Format && rgba8_any_order(rd.Format) && rgba8_any_order(asked) && - r->lists_castable_format(asked); - // A typed BGRA8 or B8G8R8X8 texture with a castable list refuses an RTV in another format the list - // doesn't name, as a typed RGBA8 texture does. Without a list it keeps the image's format, as before. - const bool typed_bgra8_listed = r && !typed_rgba8 && rgba8_any_order(rd.Format) && - r->has_castable_formats(); - if (rd.Format == DXGI_FORMAT_A8_UNORM || (desc && desc->Format == DXGI_FORMAT_A8_UNORM)) { - view = {}; - } else if (r && r->uint_backed() == VK_FORMAT_A1R5G5B5_UNORM_PACK16) { - // An R16_UINT-backed B5G5R5A1 UAV texture (Format::uint_backed) renders through an A1R5G5B5 view, in - // its own format only. - if (desc && desc->Format != DXGI_FORMAT_UNKNOWN && desc->Format != rd.Format) - view = {}; - else - view.format = static_cast(VK_FORMAT_A1R5G5B5_UNORM_PACK16); - } else if (r && (r->uint_backed() == VK_FORMAT_R8G8B8A8_SRGB || r->uint_backed() == VK_FORMAT_B8G8R8A8_SRGB)) { - // A UNORM-backed 8-bit sRGB UAV texture renders through an sRGB view (encoding as the host does), in its - // own format only. - if (desc && desc->Format != DXGI_FORMAT_UNKNOWN && desc->Format != rd.Format) - view = {}; - else - view.format = static_cast(r->uint_backed()); - } else if (rd.Format == DXGI_FORMAT_R9G9B9E5_SHAREDEXP || - (desc && desc->Format == DXGI_FORMAT_R9G9B9E5_SHAREDEXP)) { - if (rd.Format != DXGI_FORMAT_R9G9B9E5_SHAREDEXP || !(rd.Flags & D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET) || - (desc && desc->Format != DXGI_FORMAT_UNKNOWN && desc->Format != rd.Format)) - view = {}; - } else if (typeless_color || typed_rgba8 || cast_listed || typed_bgra8_listed) { - const DXGI_FORMAT requested = asked; - // A typed UNORM RGBA8 resource with a castable list may be viewed in a listed family format - // (D3D-85's committed path, D3D-90's placed one): its image is mutable and lists the view - // format, so the reinterpretation is the typeless path's. Only a UNORM image is advertised, - // as that is what the clear path reinterprets. - const bool listed = requested == rd.Format || - (r && r->has_view_format_list() && - r->allows_view_format(vulkan_format(requested, false).format)); - if (typeless_color || cast_listed || - (requested != rd.Format && listed && rd.Format == DXGI_FORMAT_R8G8B8A8_UNORM)) { - const bool msaa = rd.SampleDesc.Count > 1; - const bool plain_1d = !msaa && desc && desc->ViewDimension == D3D12_RTV_DIMENSION_TEXTURE1D; - const bool array_1d = !msaa && desc && desc->ViewDimension == D3D12_RTV_DIMENSION_TEXTURE1DARRAY; - const bool plain_2d = !msaa && desc && desc->ViewDimension == D3D12_RTV_DIMENSION_TEXTURE2D; - const bool array_2d = !msaa && desc && desc->ViewDimension == D3D12_RTV_DIMENSION_TEXTURE2DARRAY; - const bool ms = msaa && desc && desc->ViewDimension == D3D12_RTV_DIMENSION_TEXTURE2DMS; - const bool ms_array = msaa && desc && desc->ViewDimension == D3D12_RTV_DIMENSION_TEXTURE2DMSARRAY; - const UINT plane = plain_2d ? desc->Texture2D.PlaneSlice : - array_2d ? desc->Texture2DArray.PlaneSlice : 0; - const bool dim_ok = ((plain_1d || array_1d) && rd.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE1D) || - ((plain_2d || array_2d || ms || ms_array) && - rd.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE2D); - // Subtraction keeps malformed layer ranges from overflowing during validation. - if (!dim_ok || plane || !view.resource || view.mip >= rd.MipLevels || - !view.layer_count || view.first_layer >= rd.DepthOrArraySize || - view.layer_count > rd.DepthOrArraySize - view.first_layer || - !(rd.Flags & D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET)) { - view = {}; - } else { - // The view's own format, of the resource's family (B8G8R8X8 and B8G8R8A8 are two families - // that share Vulkan formats) or named by its castable list; the clear and the attachment - // view reinterpret the image in it. - const Format named = vulkan_format(requested, false); - const int family = leonida::detail::typeless_view_family(named.format); - const bool same_family = - alpha_unused(requested) == alpha_unused(rd.Format) && - family == leonida::detail::typeless_view_family(vulkan_format(rd.Format, false).format); - if (named.typeless || named.rgb96 || !family || !(same_family || cast_listed)) - view = {}; - else - view.format = static_cast(named.format); - if (view.resource) { - const auto format = vulkan_format(requested, false); - VkFormatProperties properties{}; - state_.format_properties(state_.info.physical, format.format, &properties); - if (!(properties.optimalTilingFeatures & VK_FORMAT_FEATURE_COLOR_ATTACHMENT_BIT)) view = {}; - } - } - } else if (requested != rd.Format) { - view = {}; // No typed-resource format casting is advertised by this backend. - } - if (!view.resource) log_once("unsupported typeless or RGBA8 RTV format/subresource:", int(requested)); - } - } else if (resource) { - stub("ID3D12Device::CreateRenderTargetView(resource from another device)"); - } - std::memcpy(reinterpret_cast(destination.ptr), &view, sizeof(view)); - } - - void STDMETHODCALLTYPE CreateDepthStencilView(ID3D12Resource* resource, const D3D12_DEPTH_STENCIL_VIEW_DESC* desc, - D3D12_CPU_DESCRIPTOR_HANDLE destination) override { - d3d12_trace::record("ID3D12Device::CreateDepthStencilView"); - if (!destination.ptr) return; - leonida::TargetView view{}; - if (const Resource* r = Resource::from(resource)) { - const D3D12_RESOURCE_DESC rd = const_cast(r)->GetDesc(); - view = {r->id(), 0, 0, rd.DepthOrArraySize}; - if (desc && desc->ViewDimension == D3D12_DSV_DIMENSION_TEXTURE1D) { - view = line_target_view(r->id(), rd, desc->Texture1D.MipSlice, 0, 1); - } else if (desc && desc->ViewDimension == D3D12_DSV_DIMENSION_TEXTURE1DARRAY) { - view = line_target_view(r->id(), rd, desc->Texture1DArray.MipSlice, - desc->Texture1DArray.FirstArraySlice, desc->Texture1DArray.ArraySize); - } else if (desc && desc->ViewDimension == D3D12_DSV_DIMENSION_TEXTURE2D) { - view = {r->id(), desc->Texture2D.MipSlice, 0, 1}; - } else if (desc && desc->ViewDimension == D3D12_DSV_DIMENSION_TEXTURE2DMS) { - view = {r->id(), 0, 0, 1}; - } else if (desc && desc->ViewDimension == D3D12_DSV_DIMENSION_TEXTURE2DARRAY) { - view = {r->id(), desc->Texture2DArray.MipSlice, desc->Texture2DArray.FirstArraySlice, - view_slices(rd, desc->Texture2DArray.FirstArraySlice, desc->Texture2DArray.ArraySize)}; - } else if (desc && desc->ViewDimension == D3D12_DSV_DIMENSION_TEXTURE2DMSARRAY) { - // Multisample textures have one mip, so only the slice range is chosen. - view = {r->id(), 0, desc->Texture2DMSArray.FirstArraySlice, - view_slices(rd, desc->Texture2DMSArray.FirstArraySlice, desc->Texture2DMSArray.ArraySize)}; - } else if (desc) { - log_once("depth-stencil view dimension not supported:", desc->ViewDimension); - view = {}; - } - if (r->desc().Format == DXGI_FORMAT_A8_UNORM || (desc && desc->Format == DXGI_FORMAT_A8_UNORM)) view = {}; - } else if (resource) { - stub("ID3D12Device::CreateDepthStencilView(resource from another device)"); - } - std::memcpy(reinterpret_cast(destination.ptr), &view, sizeof(view)); - } - - // A descriptor is its slot's bytes (a TargetView in RTV and DSV heaps, otherwise what the shader loads), so a - // copy is a byte copy. D3D12 walks the destination and source ranges together, one descriptor at a time; a - // null size array means every range holds one descriptor. Whichever side runs out first ends the copy. - void STDMETHODCALLTYPE CopyDescriptors(UINT destination_ranges, const D3D12_CPU_DESCRIPTOR_HANDLE* destinations, - const UINT* destination_sizes, UINT source_ranges, - const D3D12_CPU_DESCRIPTOR_HANDLE* sources, const UINT* source_sizes, - D3D12_DESCRIPTOR_HEAP_TYPE) override { - if (!destinations || !sources) return; - UINT d = 0, s = 0, d_at = 0, s_at = 0; // the range on each side, and the position in it - while (d < destination_ranges && s < source_ranges) { - if (d_at >= (destination_sizes ? destination_sizes[d] : 1) || !destinations[d].ptr) { - ++d; - d_at = 0; - } else if (s_at >= (source_sizes ? source_sizes[s] : 1) || !sources[s].ptr) { - ++s; - s_at = 0; - } else { - std::memmove(reinterpret_cast(destinations[d].ptr) + std::size_t(d_at++) * kDescriptorSize, - reinterpret_cast(sources[s].ptr) + std::size_t(s_at++) * kDescriptorSize, - kDescriptorSize); - } - } - } - - void STDMETHODCALLTYPE CopyDescriptorsSimple(UINT count, D3D12_CPU_DESCRIPTOR_HANDLE destination, - D3D12_CPU_DESCRIPTOR_HANDLE source, - D3D12_DESCRIPTOR_HEAP_TYPE) override { - if (!destination.ptr || !source.ptr) return; - std::memmove(reinterpret_cast(destination.ptr), reinterpret_cast(source.ptr), - std::size_t(count) * kDescriptorSize); - } - - // A constant-buffer view is a 16-byte GFX10 raw buffer V# in the first half of the slot (zeros in the rest). - // A null description, zero address, or zero size leaves the whole slot zeroed (null V#: reads return 0). - void STDMETHODCALLTYPE CreateConstantBufferView(const D3D12_CONSTANT_BUFFER_VIEW_DESC* desc, - D3D12_CPU_DESCRIPTOR_HANDLE destination) override { - d3d12_trace::record("ID3D12Device::CreateConstantBufferView"); - if (!destination.ptr) return; - std::memset(reinterpret_cast(destination.ptr), 0, kDescriptorSize); - if (!desc || !desc->BufferLocation || !desc->SizeInBytes) return; - leonida::gfx10::Buffer buffer{}; - buffer.address = desc->BufferLocation; - buffer.stride = 0; - buffer.num_records = desc->SizeInBytes; - buffer.format = leonida::gfx10::format_from_vulkan(VK_FORMAT_R32_UINT); - buffer.oob_select = leonida::gfx10::OobSelect::raw; - const leonida::gfx10::BufferWords words = leonida::gfx10::encode(buffer); - std::memcpy(reinterpret_cast(destination.ptr), words.data(), sizeof(words)); - } - - // A shader-resource view of a texture is a T# in the slot (docs section 3.4): the shader loads those eight - // dwords through its descriptor table and finds the image by them. A buffer SRV writes a 16-byte GFX10 V# in the - // first half of the slot (raw, structured, or typed). A slot left as zeros is a null descriptor. - void STDMETHODCALLTYPE CreateShaderResourceView(ID3D12Resource* resource, - const D3D12_SHADER_RESOURCE_VIEW_DESC* desc, - D3D12_CPU_DESCRIPTOR_HANDLE destination) override { - d3d12_trace::record("ID3D12Device::CreateShaderResourceView"); - using leonida::gfx10::ImageType; - if (!destination.ptr) return; - std::memset(reinterpret_cast(destination.ptr), 0, kDescriptorSize); - const Resource* r = Resource::from(resource); - if (!r) { - if (resource) stub("ID3D12Device::CreateShaderResourceView(resource from another device)"); - return; - } - if (r->desc().Flags & D3D12_RESOURCE_FLAG_DENY_SHADER_RESOURCE) { - log_once("shader-resource view denied by resource flags; format", int(r->desc().Format)); - return; - } - if (!r->image()) { - if (!desc) { - log_once("buffer SRV requires a description; width", int(r->desc().Width)); - return; - } - if (desc->ViewDimension != D3D12_SRV_DIMENSION_BUFFER) { - log_once("shader-resource view dimension not supported for buffer:", desc->ViewDimension); - return; - } - const UINT64 base_va = const_cast(r)->GetGPUVirtualAddress(); - const UINT64 width = r->desc().Width; - if (!base_va || !desc->Buffer.NumElements || (desc->Buffer.Flags & ~D3D12_BUFFER_SRV_FLAG_RAW)) return; - leonida::gfx10::Buffer buffer{}; - if (desc->Buffer.Flags & D3D12_BUFFER_SRV_FLAG_RAW) { - if (desc->Format != DXGI_FORMAT_R32_TYPELESS || desc->Buffer.StructureByteStride != 0) return; - if (desc->Buffer.FirstElement > width / 4) return; - const UINT64 byte_off = desc->Buffer.FirstElement * 4; - const UINT64 byte_size = UINT64(desc->Buffer.NumElements) * 4; - if (byte_size > width - byte_off || byte_size > UINT32_MAX) return; - buffer.address = base_va + byte_off; - buffer.stride = 0; - buffer.num_records = std::uint32_t(byte_size); - buffer.format = leonida::gfx10::format_from_vulkan(VK_FORMAT_R32_UINT); - buffer.oob_select = leonida::gfx10::OobSelect::raw; - } else if (desc->Buffer.StructureByteStride != 0) { - if (desc->Format != DXGI_FORMAT_UNKNOWN || desc->Buffer.StructureByteStride > 16383) return; - const UINT64 stride = desc->Buffer.StructureByteStride; - if (desc->Buffer.FirstElement > width / stride) return; - const UINT64 byte_off = desc->Buffer.FirstElement * stride; - const UINT64 byte_size = UINT64(desc->Buffer.NumElements) * stride; - if (byte_size > width - byte_off) return; - buffer.address = base_va + byte_off; - buffer.stride = std::uint32_t(stride); - buffer.num_records = desc->Buffer.NumElements; - buffer.format = leonida::gfx10::format_from_vulkan(VK_FORMAT_R32_UINT); - buffer.oob_select = leonida::gfx10::OobSelect::structured; - } else { - const Format fmt = vulkan_format(desc->Format, false); - if (fmt.format == VK_FORMAT_UNDEFINED || fmt.typeless || !(fmt.aspects & VK_IMAGE_ASPECT_COLOR_BIT)) { - log_once("buffer SRV format not supported:", int(desc->Format)); - return; - } - const VkFormat named = fmt.rgb96 ? rgb96_named_format(fmt.format) : fmt.format; - const std::uint32_t code = leonida::gfx10::format_from_vulkan(named); - const leonida::BlockFormat bf = footprint_block(fmt, VK_IMAGE_ASPECT_COLOR_BIT); - if (!code || bf.block != 1 || !bf.bytes || bf.bytes > 16383) { - log_once("buffer SRV format not supported:", int(desc->Format)); - return; - } - const UINT64 stride = bf.bytes; - if (desc->Buffer.FirstElement > width / stride) return; - const UINT64 byte_off = desc->Buffer.FirstElement * stride; - const UINT64 byte_size = UINT64(desc->Buffer.NumElements) * stride; - if (byte_size > width - byte_off) return; - buffer.address = base_va + byte_off; - buffer.stride = std::uint32_t(stride); - buffer.num_records = desc->Buffer.NumElements; - buffer.format = code; - const leonida::gfx10::Swizzle channels = leonida::gfx10::format_swizzle(named); - for (unsigned i = 0; i < 4; ++i) { - const UINT from = D3D12_DECODE_SHADER_4_COMPONENT_MAPPING(i, desc->Shader4ComponentMapping); - buffer.swizzle[i] = from < 4 ? channels[from] - : from == D3D12_SHADER_COMPONENT_MAPPING_FORCE_VALUE_0 - ? leonida::gfx10::select_zero - : leonida::gfx10::select_one; - } - buffer.oob_select = leonida::gfx10::OobSelect::structured; - } - const leonida::gfx10::BufferWords words = leonida::gfx10::encode(buffer); - std::memcpy(reinterpret_cast(destination.ptr), words.data(), sizeof(words)); - return; - } - TextureView view{}; - if (!desc) { - const bool array = r->desc().DepthOrArraySize > 1; - if (r->desc().Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE1D && !array) { - view.type = ImageType::image_1d; - view.layer_count = 1; - } else if (r->desc().Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE3D) - view.type = ImageType::image_3d; - else if (r->desc().SampleDesc.Count > 1) - view.type = array ? ImageType::image_2d_msaa_array : ImageType::image_2d_msaa; - else if (array) - view.type = ImageType::image_2d_array; - } else { - view.format = desc->Format; - view.mapping = desc->Shader4ComponentMapping; - switch (desc->ViewDimension) { - case D3D12_SRV_DIMENSION_TEXTURE1D: - view.type = ImageType::image_1d; - view.first_mip = desc->Texture1D.MostDetailedMip; - view.mip_count = desc->Texture1D.MipLevels; - view.layer_count = 1; - view.min_lod = desc->Texture1D.ResourceMinLODClamp; - break; - case D3D12_SRV_DIMENSION_TEXTURE3D: - view.type = leonida::gfx10::ImageType::image_3d; - view.first_mip = desc->Texture3D.MostDetailedMip; - view.mip_count = desc->Texture3D.MipLevels; - view.min_lod = desc->Texture3D.ResourceMinLODClamp; - break; - case D3D12_SRV_DIMENSION_TEXTURE2DMS: - view.type = ImageType::image_2d_msaa; - view.layer_count = 1; - break; - case D3D12_SRV_DIMENSION_TEXTURE2DMSARRAY: - view.type = ImageType::image_2d_msaa_array; - view.first_layer = desc->Texture2DMSArray.FirstArraySlice; - view.layer_count = desc->Texture2DMSArray.ArraySize; - break; - case D3D12_SRV_DIMENSION_TEXTURE2D: - view.first_mip = desc->Texture2D.MostDetailedMip; - view.mip_count = desc->Texture2D.MipLevels; - view.layer_count = 1; - view.plane = desc->Texture2D.PlaneSlice; - view.min_lod = desc->Texture2D.ResourceMinLODClamp; - break; - case D3D12_SRV_DIMENSION_TEXTURE2DARRAY: - view.type = ImageType::image_2d_array; - view.first_mip = desc->Texture2DArray.MostDetailedMip; - view.mip_count = desc->Texture2DArray.MipLevels; - view.first_layer = desc->Texture2DArray.FirstArraySlice; - view.layer_count = desc->Texture2DArray.ArraySize; - view.plane = desc->Texture2DArray.PlaneSlice; - view.min_lod = desc->Texture2DArray.ResourceMinLODClamp; - break; - case D3D12_SRV_DIMENSION_TEXTURECUBE: - view.type = ImageType::cube; - view.first_mip = desc->TextureCube.MostDetailedMip; - view.mip_count = desc->TextureCube.MipLevels; - view.layer_count = 6; - view.min_lod = desc->TextureCube.ResourceMinLODClamp; - break; - case D3D12_SRV_DIMENSION_TEXTURECUBEARRAY: - view.type = ImageType::cube; - view.first_mip = desc->TextureCubeArray.MostDetailedMip; - view.mip_count = desc->TextureCubeArray.MipLevels; - view.first_layer = desc->TextureCubeArray.First2DArrayFace; - view.layer_count = desc->TextureCubeArray.NumCubes < ~0u / 6 ? desc->TextureCubeArray.NumCubes * 6 : ~0u; - view.min_lod = desc->TextureCubeArray.ResourceMinLODClamp; - break; - default: - log_once("shader-resource view dimension not supported:", desc->ViewDimension); - return; - } - } - write_image_descriptor(*r, view, destination, false); - } - - // An unordered-access view of a buffer is a V# in the slot (docs section 3.4): the shader loads those four dwords - // through its descriptor table and reaches the bytes by the console VA in them. A structured view (format - // UNKNOWN and a stride) is `stride` and a record count, a raw one (R32_TYPELESS with the RAW flag) is a byte count, - // a typed one (any other format) is the format's GFX10_FORMAT code with the element size as the stride and an - // element count: the V# a buffer_load_format / buffer_store_format / buffer_atomic reads (OOB_SELECT 1, so the - // index is checked against NUM_RECORDS, docs/buffer_bounds.md). A slot left as zeros is a null descriptor. - // A UAV counter (docs section 3.4, "UAV counters") is a second, raw V# of 4 bytes in the slot's upper 16 bytes: the - // counter resource's address plus CounterOffsetInBytes. Append and consume are atomics a shader does on it. - void write_buffer_uav(ID3D12Resource* resource, ID3D12Resource* counter, const D3D12_UNORDERED_ACCESS_VIEW_DESC* desc, - D3D12_CPU_DESCRIPTOR_HANDLE destination) { - namespace g = leonida::gfx10; - const D3D12_RESOURCE_DESC& rd = Resource::from(resource)->desc(); - if (!(rd.Flags & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS)) { - log_once("unordered-access view of a buffer created without ALLOW_UNORDERED_ACCESS; flags", int(rd.Flags)); - return; - } - if (!desc || desc->ViewDimension != D3D12_UAV_DIMENSION_BUFFER) { - log_once("unordered-access view of a buffer needs a buffer view description; dimension", - desc ? int(desc->ViewDimension) : -1); - return; - } - const D3D12_BUFFER_UAV& view = desc->Buffer; - const bool structured = desc->Format == DXGI_FORMAT_UNKNOWN; - const bool raw = desc->Format == DXGI_FORMAT_R32_TYPELESS && (view.Flags & D3D12_BUFFER_UAV_FLAG_RAW); - const bool typed = !structured && !raw; - std::uint32_t format_code = 0, element_bytes = 0; - g::Swizzle channels = g::identity_swizzle; - if (typed) { - // D3D12: a typed view has no RAW flag; its format is one of the typed-UAV formats the layer can name. - const Format mapped = vulkan_format(desc->Format, false); - const auto* layout = mapped.format != VK_FORMAT_UNDEFINED && !mapped.typeless && !mapped.rgb96 && - !(view.Flags & D3D12_BUFFER_UAV_FLAG_RAW) - ? leonida::uav_clear::layout(mapped.format) - : nullptr; - format_code = layout ? g::format_from_vulkan(mapped.format) : 0; - if (!format_code || format_code >= 128) { // the V#'s FORMAT is 7 bits - log_once("typed buffer unordered-access view format not supported; format", int(desc->Format)); - return; - } - element_bytes = layout->bytes; - channels = g::format_swizzle(mapped.format); - } - const UINT64 unit = structured ? view.StructureByteStride : typed ? element_bytes : 4; - if (!unit || unit > 0x3fff || view.FirstElement > rd.Width / unit || - (UINT64(view.FirstElement) + view.NumElements) > rd.Width / unit || - UINT64(view.NumElements) * (structured || typed ? 1 : 4) > ~0u) { - log_once("unordered-access view of a buffer outside the resource or with a bad stride; elements", - int(view.NumElements)); - return; - } - // D3D12: a counter belongs to a structured view and sits in a buffer that allows unordered access, 4096-byte - // aligned with room for its 4 bytes; with no counter resource the offset is 0. - if (counter || view.CounterOffsetInBytes) { - const Resource* c = counter ? Resource::from(counter) : nullptr; - const bool valid = c && !c->image() && structured && - (c->desc().Flags & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS) && - !(view.CounterOffsetInBytes % D3D12_UAV_COUNTER_PLACEMENT_ALIGNMENT) && - UINT64(view.CounterOffsetInBytes) + 4 <= c->desc().Width; - if (!valid) { - log_once("unordered-access view counter refused (a structured view, a buffer that allows unordered " - "access, a 4096-aligned offset inside it); offset", - int(view.CounterOffsetInBytes)); - return; - } - } - const UINT64 va = resource->GetGPUVirtualAddress(); - const UINT64 counter_va = counter ? counter->GetGPUVirtualAddress() : 0; - if (!va || (counter && !counter_va)) return; - g::Buffer buffer{}; - buffer.address = va + view.FirstElement * unit; - buffer.stride = structured || typed ? std::uint32_t(unit) : 0; - buffer.num_records = std::uint32_t(structured || typed ? view.NumElements : UINT64(view.NumElements) * 4); - buffer.format = format_code; - buffer.swizzle = channels; - buffer.oob_select = typed ? g::OobSelect::structured - : structured ? g::OobSelect::structured_with_offset : g::OobSelect::raw; - const g::BufferWords words = g::encode(buffer); - std::memcpy(reinterpret_cast(destination.ptr), words.data(), sizeof(words)); - if (counter) { - g::Buffer counter_buffer{}; - counter_buffer.address = counter_va + view.CounterOffsetInBytes; - counter_buffer.num_records = 4; - counter_buffer.oob_select = g::OobSelect::raw; - const g::BufferWords counter_words = g::encode(counter_buffer); - std::memcpy(reinterpret_cast(destination.ptr) + sizeof(words), counter_words.data(), - sizeof(counter_words)); - } - } - - // An unordered-access view of a texture is a T# too, of one mip; set 0 also holds it as a storage image. - void STDMETHODCALLTYPE CreateUnorderedAccessView(ID3D12Resource* resource, ID3D12Resource* counter, - const D3D12_UNORDERED_ACCESS_VIEW_DESC* desc, - D3D12_CPU_DESCRIPTOR_HANDLE destination) override { - d3d12_trace::record("ID3D12Device::CreateUnorderedAccessView"); - if (!destination.ptr) return; - std::memset(reinterpret_cast(destination.ptr), 0, kDescriptorSize); - const Resource* r = Resource::from(resource); - if (!r) { - if (resource) stub("ID3D12Device::CreateUnorderedAccessView(resource from another device)"); - return; - } - if (!r->image()) return write_buffer_uav(resource, counter, desc, destination); - if (counter) { - log_once("unordered-access view of a texture with a counter resource; dimension", int(r->desc().Dimension)); - return; - } - if (!(r->desc().Flags & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS)) { - log_once("unordered-access view of a texture created without ALLOW_UNORDERED_ACCESS; flags", - int(r->desc().Flags)); - return; - } - TextureView view{}; - view.mip_count = 1; - if (!desc) { - const bool array = r->desc().DepthOrArraySize > 1; - if (r->desc().Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE1D && !array) { - view.type = leonida::gfx10::ImageType::image_1d; - view.layer_count = 1; - } else if (array) - view.type = leonida::gfx10::ImageType::image_2d_array; - } else { - view.format = desc->Format; - switch (desc->ViewDimension) { - case D3D12_UAV_DIMENSION_TEXTURE1D: - view.type = leonida::gfx10::ImageType::image_1d; - view.first_mip = desc->Texture1D.MipSlice; - view.layer_count = 1; - break; - case D3D12_UAV_DIMENSION_TEXTURE2D: - view.first_mip = desc->Texture2D.MipSlice; - view.layer_count = 1; - view.plane = desc->Texture2D.PlaneSlice; - break; - case D3D12_UAV_DIMENSION_TEXTURE2DARRAY: - view.type = leonida::gfx10::ImageType::image_2d_array; - view.first_mip = desc->Texture2DArray.MipSlice; - view.first_layer = desc->Texture2DArray.FirstArraySlice; - view.layer_count = desc->Texture2DArray.ArraySize; - view.plane = desc->Texture2DArray.PlaneSlice; - break; - default: - log_once("unordered-access view dimension not supported:", desc->ViewDimension); - return; - } - } - // B8G8R8X8 has no typed UAV, so no format of its family gives an unordered-access view. - if (alpha_unused(r->desc().Format) || alpha_unused(view.format)) { - log_once("unordered-access view of a B8G8R8X8 format; format", int(view.format)); - return; - } - write_image_descriptor(*r, view, destination, true); - state_.context->note_shader_image(r->id()); - } - - // A sampler is an S# in the first 16 bytes of the slot; the shader finds the sampler by those four dwords. - void STDMETHODCALLTYPE CreateSampler(const D3D12_SAMPLER_DESC* desc, - D3D12_CPU_DESCRIPTOR_HANDLE destination) override { - d3d12_trace::record("ID3D12Device::CreateSampler"); - if (!destination.ptr) return; - std::memset(reinterpret_cast(destination.ptr), 0, kDescriptorSize); - if (!desc) return; - const leonida::gfx10::SamplerWords words = leonida::gfx10::encode(sampler_descriptor(*desc, &state_)); - std::memcpy(reinterpret_cast(destination.ptr), words.data(), sizeof(words)); - state_.bind_sampler(words); - } - - // CreateSampler with a UINT border colour and non-normalized coordinates (D3D-28). A description the PC runtime - // refuses leaves the slot as it was, as the runtime itself does (without the debug layer) on an RTX 4090 and - // on WARP: docs/d3d12_vulkan.md section 3.2. - void STDMETHODCALLTYPE CreateSampler2(const D3D12_SAMPLER_DESC2* desc, - D3D12_CPU_DESCRIPTOR_HANDLE destination) override { - d3d12_trace::record("ID3D12Device11::CreateSampler2"); - if (!destination.ptr || !desc) return; - const char* refusal = sampler2_refusal(*desc); - if (refusal) { - log_once(refusal, desc->Flags); - return; - } - const leonida::gfx10::SamplerWords words = sampler2_words(*desc); - std::memset(reinterpret_cast(destination.ptr), 0, kDescriptorSize); - std::memcpy(reinterpret_cast(destination.ptr), words.data(), sizeof(words)); - state_.bind_sampler(words); - } - - // The S# of a D3D12_SAMPLER_DESC2 that sampler2_refusal accepts. - leonida::gfx10::SamplerWords sampler2_words(const D3D12_SAMPLER_DESC2& desc) { - const bool uint_border = desc.Flags & D3D12_SAMPLER_FLAG_UINT_BORDER_COLOR; - D3D12_SAMPLER_DESC base{desc.Filter, desc.AddressU, desc.AddressV, desc.AddressW, - desc.MipLODBias, desc.MaxAnisotropy, desc.ComparisonFunc, {}, - desc.MinLOD, desc.MaxLOD}; - if (!uint_border) std::memcpy(base.BorderColor, desc.FloatBorderColor, sizeof(base.BorderColor)); - leonida::gfx10::Sampler sampler = sampler_descriptor(base, uint_border ? nullptr : &state_); - if (uint_border) { - // The S#'s border types are the float ones', plus the layer's integer mark (kIntegerBorderPtr), which - // gives the integer border its own key and VK_BORDER_COLOR_INT_* in Vulkan. - namespace g = leonida::gfx10; - const UINT* c = desc.UintBorderColor; - const bool black = c[0] == 0 && c[1] == 0 && c[2] == 0; - if (black && c[3] == 0) { - sampler.border_color = g::BorderColor::transparent_black; - } else if (black && c[3] == 1) { - sampler.border_color = g::BorderColor::opaque_black; - } else if (c[0] == 1 && c[1] == 1 && c[2] == 1 && c[3] == 1) { - sampler.border_color = g::BorderColor::opaque_white; - } else { - sampler.border_color = g::BorderColor::table; - sampler.border_color_index = state_.register_border_color(true, c); - } - sampler.integer_border = true; - } - sampler.unnormalized = desc.Flags & D3D12_SAMPLER_FLAG_NON_NORMALIZED_COORDINATES; - return leonida::gfx10::encode(sampler); - } - - // A root signature's static samplers take no root argument: a shader that uses one holds its S# by value - // (docs/d3d12_vulkan.md section 3.5). So each gets a sampler in set 0 and a key in the hash table here, as - // CreateSampler gives a heap slot's S#; without them the shader's lookup misses and it samples through the - // fallback sampler. A static sampler is a D3D12_SAMPLER_DESC2 whose border colour is one of five named ones - // (D3D12_STATIC_BORDER_COLOR; the two UINT ones can be in a blob of any version, the flags only in 1.2), or - // transparent black with the UINT flag. - void register_static_samplers(const rt::rootsig::RootSignature& signature) { - for (const rt::rootsig::StaticSampler& s : signature.static_samplers) { - D3D12_SAMPLER_DESC2 desc{}; - desc.Filter = D3D12_FILTER(s.filter); - desc.AddressU = D3D12_TEXTURE_ADDRESS_MODE(s.address_u); - desc.AddressV = D3D12_TEXTURE_ADDRESS_MODE(s.address_v); - desc.AddressW = D3D12_TEXTURE_ADDRESS_MODE(s.address_w); - desc.MipLODBias = s.mip_lod_bias; - desc.MaxAnisotropy = s.max_anisotropy; - desc.ComparisonFunc = D3D12_COMPARISON_FUNC(s.comparison_func); - desc.MinLOD = s.min_lod; - desc.MaxLOD = s.max_lod; - desc.Flags = D3D12_SAMPLER_FLAGS(s.flags); - const bool white = s.border_color == D3D12_STATIC_BORDER_COLOR_OPAQUE_WHITE || - s.border_color == D3D12_STATIC_BORDER_COLOR_OPAQUE_WHITE_UINT; - if (s.border_color == D3D12_STATIC_BORDER_COLOR_OPAQUE_BLACK_UINT || - s.border_color == D3D12_STATIC_BORDER_COLOR_OPAQUE_WHITE_UINT) { - desc.Flags |= D3D12_SAMPLER_FLAG_UINT_BORDER_COLOR; - desc.UintBorderColor[0] = desc.UintBorderColor[1] = desc.UintBorderColor[2] = white ? 1u : 0u; - desc.UintBorderColor[3] = 1; - } else if (s.border_color == D3D12_STATIC_BORDER_COLOR_TRANSPARENT_BLACK && - (desc.Flags & D3D12_SAMPLER_FLAG_UINT_BORDER_COLOR)) { - // The integer border the enum has no value for: the 1.2 flag on transparent black is UINT (0,0,0,0), - // which D3D12 serializes and creates. UintBorderColor is already zero. - } else if (s.border_color > D3D12_STATIC_BORDER_COLOR_OPAQUE_WHITE_UINT || - (desc.Flags & D3D12_SAMPLER_FLAG_UINT_BORDER_COLOR)) { - // A value past the enum, or the UINT flag with the float opaque black or white (D3D12 refuses to - // serialize that pair): not a sampler D3D12 defines. - log_once("static sampler not registered: border colour and flags do not go together; border colour", - int(s.border_color)); - continue; - } else { - desc.FloatBorderColor[0] = desc.FloatBorderColor[1] = desc.FloatBorderColor[2] = white ? 1.0f : 0.0f; - desc.FloatBorderColor[3] = - s.border_color == D3D12_STATIC_BORDER_COLOR_TRANSPARENT_BLACK ? 0.0f : 1.0f; - } - if (sampler2_refusal(desc)) { - log_once("static sampler not registered: a sampler CreateSampler2 refuses; flags", int(desc.Flags)); - continue; - } - if (!state_.bind_sampler(sampler2_words(desc))) - log_once("static sampler not registered: no room in the bindless set; register", - int(s.shader_register)); - } - } - - // Why the PC runtime refuses a D3D12_SAMPLER_DESC2, or null. The non-normalized rules are its debug layer's - // messages, which match Vulkan's for unnormalizedCoordinates; AddressW is free in both. - static const char* sampler2_refusal(const D3D12_SAMPLER_DESC2& desc) { - if (desc.Flags & ~UINT(D3D12_SAMPLER_FLAG_UINT_BORDER_COLOR | D3D12_SAMPLER_FLAG_NON_NORMALIZED_COORDINATES)) - return "CreateSampler2 refused: unknown sampler flags; flags"; - if (!(desc.Flags & D3D12_SAMPLER_FLAG_NON_NORMALIZED_COORDINATES)) return nullptr; - if (D3D12_DECODE_MIN_FILTER(desc.Filter) != D3D12_DECODE_MAG_FILTER(desc.Filter) || - D3D12_DECODE_MIP_FILTER(desc.Filter) != D3D12_FILTER_TYPE_POINT || - D3D12_DECODE_IS_ANISOTROPIC_FILTER(desc.Filter) || - D3D12_DECODE_FILTER_REDUCTION(desc.Filter) == D3D12_FILTER_REDUCTION_TYPE_COMPARISON) - return "CreateSampler2 refused: non-normalized sampler filter; flags"; - const auto clamps = [](D3D12_TEXTURE_ADDRESS_MODE m) { - return m == D3D12_TEXTURE_ADDRESS_MODE_CLAMP || m == D3D12_TEXTURE_ADDRESS_MODE_BORDER; - }; - if (!clamps(desc.AddressU) || !clamps(desc.AddressV)) - return "CreateSampler2 refused: non-normalized sampler address mode; flags"; - if (desc.MinLOD != 0 || desc.MaxLOD != 0 || desc.MipLODBias != 0) - return "CreateSampler2 refused: non-normalized sampler LOD; flags"; - return nullptr; - } - - HRESULT STDMETHODCALLTYPE CreateCommittedResource(const D3D12_HEAP_PROPERTIES* heap, D3D12_HEAP_FLAGS heap_flags, - const D3D12_RESOURCE_DESC* desc, D3D12_RESOURCE_STATES state, - const D3D12_CLEAR_VALUE* clear, REFIID riid, - void** out) override { - return create_committed_validated("ID3D12Device::CreateCommittedResource", heap, heap_flags, desc, state, clear, - 0, nullptr, riid, out); - } - - // Reserved buffers use sparse binding where available. Textures and fallback buffers are fully backed. - // The description rules are D3D12's: buffers are ROW_MAJOR, textures 64KB_UNDEFINED_SWIZZLE with a tile shape - // (64KB_STANDARD_SWIZZLE needs StandardSwizzle64KBSupported, which CheckFeatureSupport reports as FALSE). The - // Xbox tiled layout word 0x101 (slot 76, section 4.2) is accepted as 64KB_UNDEFINED_SWIZZLE; that the console - // uses it for reserved resources too is an assumption. - HRESULT STDMETHODCALLTYPE CreateReservedResource(const D3D12_RESOURCE_DESC* desc, D3D12_RESOURCE_STATES state, - const D3D12_CLEAR_VALUE* clear, REFIID riid, - void** out) override { - return create_reserved("ID3D12Device::CreateReservedResource", desc, state, clear, 0, nullptr, riid, out); - } - - // Device4. Protected sessions are not supported. - HRESULT STDMETHODCALLTYPE CreateReservedResource1(const D3D12_RESOURCE_DESC* desc, D3D12_RESOURCE_STATES state, - const D3D12_CLEAR_VALUE* clear, - ID3D12ProtectedResourceSession* session, REFIID riid, - void** out) override { - constexpr auto method = "ID3D12Device4::CreateReservedResource1"; - if (out) *out = nullptr; - if (!desc) return d3d12_trace::result(method, E_INVALIDARG); - if (session) return d3d12_trace::result(method, refuse_protected_session("CreateReservedResource1")); - return create_reserved(method, desc, state, clear, 0, nullptr, riid, out); - } - - // Device10: an initial layout instead of a state (resources start in their first use's layout here anyway), and a - // castable-format list forwarded to the backing texture. - HRESULT STDMETHODCALLTYPE CreateReservedResource2(const D3D12_RESOURCE_DESC* desc, D3D12_BARRIER_LAYOUT layout, - const D3D12_CLEAR_VALUE* clear, - ID3D12ProtectedResourceSession* session, - UINT32 castable_formats, const DXGI_FORMAT* castable, REFIID riid, - void** out) override { - constexpr auto method = "ID3D12Device10::CreateReservedResource2"; - if (out) *out = nullptr; - if (!desc) return d3d12_trace::result(method, E_INVALIDARG); - if (session) return d3d12_trace::result(method, refuse_protected_session("CreateReservedResource2")); - if (const char* why = barrier_layout_refusal(*desc, layout)) { - log_once((std::string(method) + " refused (" + why + "), layout").c_str(), int(layout)); - return d3d12_trace::result(method, E_INVALIDARG); - } - return create_reserved(method, desc, D3D12_RESOURCE_STATE_COMMON, clear, castable_formats, castable, riid, out); - } - - // Tiling of a reserved resource or a tiled (64KB_UNDEFINED_SWIZZLE) texture (src/resource_tiling.h). Anything - // else, as on the PC runtime, has no tiles: every output is zero and no subresource tiling is written. - void STDMETHODCALLTYPE GetResourceTiling(ID3D12Resource* resource, UINT* total, D3D12_PACKED_MIP_INFO* packed, - D3D12_TILE_SHAPE* shape, UINT* count, UINT first, - D3D12_SUBRESOURCE_TILING* tilings) override { - leonida::ResourceTiling tiling; - Resource* r = Resource::from(resource); - const bool ok = r && (r->reserved() || is_tiled_layout(r->GetDesc().Layout)) && - resource_tiling(r->GetDesc(), tiling); - if (total) *total = ok ? tiling.total_tiles : 0; - if (packed) - *packed = ok ? D3D12_PACKED_MIP_INFO{UINT8(tiling.standard_mips), UINT8(tiling.packed_mips), - tiling.packed_tiles, tiling.packed_start} - : D3D12_PACKED_MIP_INFO{}; - if (shape) - *shape = ok ? D3D12_TILE_SHAPE{tiling.shape.width, tiling.shape.height, tiling.shape.depth} - : D3D12_TILE_SHAPE{}; - if (!count) return; - const UINT available = ok && first < tiling.subresources.size() ? UINT(tiling.subresources.size() - first) : 0; - const UINT n = tilings ? std::min(*count, available) : 0; - for (UINT i = 0; i < n; ++i) { - const leonida::SubresourceTiling& s = tiling.subresources[first + i]; - tilings[i] = {s.width, UINT16(s.height), UINT16(s.depth), s.start}; - } - *count = n; - } - - // The 1/2/3 variants (D3D-28) are the same calls with newer arguments, answered as the PC runtime answers them - // (probed on an RTX 4090; docs/d3d12_vulkan.md section 3.2 has the table). The initial state or layout is not - // used: new textures are tracked as UNDEFINED and moved on first use, and buffers have no layout. - HRESULT STDMETHODCALLTYPE CreateCommittedResource1(const D3D12_HEAP_PROPERTIES* heap, D3D12_HEAP_FLAGS heap_flags, - const D3D12_RESOURCE_DESC* desc, D3D12_RESOURCE_STATES state, - const D3D12_CLEAR_VALUE* clear, - ID3D12ProtectedResourceSession* session, REFIID riid, - void** out) override { - if (out) *out = nullptr; - if (session) return refuse_protected_session("CreateCommittedResource1"); - return CreateCommittedResource(heap, heap_flags, desc, state, clear, riid, out); - } - - HRESULT STDMETHODCALLTYPE CreateCommittedResource2(const D3D12_HEAP_PROPERTIES* heap, D3D12_HEAP_FLAGS heap_flags, - const D3D12_RESOURCE_DESC1* desc, D3D12_RESOURCE_STATES state, - const D3D12_CLEAR_VALUE* clear, - ID3D12ProtectedResourceSession* session, REFIID riid, - void** out) override { - if (out) *out = nullptr; - if (!desc) return E_INVALIDARG; - if (session) return refuse_protected_session("CreateCommittedResource2"); - if (texture_mip_region(*desc)) return E_INVALIDARG; - const D3D12_RESOURCE_DESC base = resource_desc(*desc); - return CreateCommittedResource(heap, heap_flags, &base, state, clear, riid, out); - } - - HRESULT STDMETHODCALLTYPE CreateCommittedResource3(const D3D12_HEAP_PROPERTIES* heap, D3D12_HEAP_FLAGS heap_flags, - const D3D12_RESOURCE_DESC1* desc, D3D12_BARRIER_LAYOUT layout, - const D3D12_CLEAR_VALUE* clear, - ID3D12ProtectedResourceSession* session, UINT32 castable_count, - const DXGI_FORMAT* castable, REFIID riid, void** out) override { - constexpr auto method = "ID3D12Device10::CreateCommittedResource3"; - if (out) *out = nullptr; - if (!desc) return d3d12_trace::result(method, E_INVALIDARG); - if (session) return d3d12_trace::result(method, refuse_protected_session("CreateCommittedResource3")); - if (texture_mip_region(*desc)) return d3d12_trace::result(method, E_INVALIDARG); - // A count with a null array is no list (as on the PC runtime). The layer reports relaxed format casting, so - // a real list is passed through; only buffers are refused. - const D3D12_RESOURCE_DESC base = resource_desc(*desc); - if (const char* why = barrier_layout_refusal(base, layout)) { - log_once((std::string(method) + " refused (" + why + "), layout").c_str(), int(layout)); - return d3d12_trace::result(method, E_INVALIDARG); - } - // D3D12_BARRIER_LAYOUT has no acceleration-structure value; an AS buffer's state comes through the - // legacy CreateCommittedResource path. Buffers here start COMMON, as before. - return create_committed_validated(method, heap, heap_flags, &base, D3D12_RESOURCE_STATE_COMMON, clear, - castable_count, castable, riid, out); - } - - // Device9. The creator ID only groups queues for tools; one creator is as good as another here. - HRESULT STDMETHODCALLTYPE CreateCommandQueue1(const D3D12_COMMAND_QUEUE_DESC* desc, REFIID, REFIID riid, - void** out) override { - return CreateCommandQueue(desc, riid, out); - } - - // Device8. A texture with a mip region gets the failure answer (every output all ones), as on the PC runtime; - // a buffer's mip region is ignored. - void STDMETHODCALLTYPE GetCopyableFootprints1(const D3D12_RESOURCE_DESC1* desc, UINT first, UINT count, - UINT64 base, D3D12_PLACED_SUBRESOURCE_FOOTPRINT* layouts, UINT* rows, - UINT64* row_sizes, UINT64* total) override { - const D3D12_RESOURCE_DESC base_desc = desc ? resource_desc(*desc) : D3D12_RESOURCE_DESC{}; - const bool usable = desc && !texture_mip_region(*desc); - GetCopyableFootprints(usable ? &base_desc : nullptr, first, count, base, layouts, rows, row_sizes, total); - } - - // Heaps and placed resources (section 3.3). A heap reserves its size in the arena, so a buffer placed at a - // 64 KiB-aligned offset is simply that offset into the arena, and its console VA is the heap's place plus it. - // Existing-memory heaps and lifetime trackers. The host refuses a null address, a file mapping that is not a - // handle and a null lifetime owner with E_INVALIDARG on WARP, NVIDIA and Intel (d3d12_existing_heap_test). Docs: - // https://learn.microsoft.com/en-us/windows/win32/api/d3d12/nf-d3d12-id3d12device3-openexistingheapfromaddress - // - // OpenExistingHeapFromAddress answers as the host runtime does on an RTX 4090 and WARP (d3d12_existing_heap_test - // open_cases): the address must be the base of a VirtualAlloc allocation that is committed read-write over its - // whole size; an address inside it, a partly committed or reserved-only allocation, a read-only one and an - // uncached one are E_INVALIDARG. The heap is the allocation's size, 64 KiB aligned, CUSTOM / L0 with WRITE_BACK - // (WRITE_COMBINE for a PAGE_WRITECOMBINE range), flags SHARED | - // SHARED_CROSS_ADAPTER | ALLOW_SHADER_ATOMICS. Its backing is that memory itself, imported with - // VK_EXT_external_memory_host, so the GPU sees the caller's writes. Without the extension, or when the range is - // not aligned to minImportedHostPointerAlignment or no memory type takes it, the call stays E_NOTIMPL, and - // CheckFeatureSupport(EXISTING_HEAPS) reports the extension's absence. The console title opens the 64 KiB - // graphics region it has just committed with XMemVirtualAlloc this way, right after its first queue and fence. - HRESULT STDMETHODCALLTYPE OpenExistingHeapFromAddress(const void* address, REFIID riid, void** out) override { - constexpr auto method = "ID3D12Device3::OpenExistingHeapFromAddress"; - if (out) *out = nullptr; - if (!address || !out) return d3d12_trace::result(method, E_INVALIDARG); - SIZE_T size = 0; - DWORD protect = 0; - if (!existing_allocation_size(address, size, protect)) return d3d12_trace::result(method, E_INVALIDARG); - if (!state_.get_host_pointer_properties) { - log_once("OpenExistingHeapFromAddress (no VK_EXT_external_memory_host; existing heaps are not supported)", 0); - return d3d12_trace::result(method, E_NOTIMPL); - } - const VkDeviceSize alignment = state_.info.host_pointer_alignment; - if ((reinterpret_cast(address) | size) & (alignment - 1)) { - log_once("OpenExistingHeapFromAddress: range not aligned to minImportedHostPointerAlignment; alignment", - int(alignment)); - return d3d12_trace::result(method, E_NOTIMPL); - } - VkMemoryHostPointerPropertiesEXT host{VK_STRUCTURE_TYPE_MEMORY_HOST_POINTER_PROPERTIES_EXT}; - if (state_.get_host_pointer_properties(state_.info.device, - VK_EXTERNAL_MEMORY_HANDLE_TYPE_HOST_ALLOCATION_BIT_EXT, address, - &host) != VK_SUCCESS || - !host.memoryTypeBits) { - log_once("OpenExistingHeapFromAddress: no memory type imports this host range", 0); - return d3d12_trace::result(method, E_NOTIMPL); - } - VkImportMemoryHostPointerInfoEXT import{VK_STRUCTURE_TYPE_IMPORT_MEMORY_HOST_POINTER_INFO_EXT}; - import.handleType = VK_EXTERNAL_MEMORY_HANDLE_TYPE_HOST_ALLOCATION_BIT_EXT; - import.pHostPointer = const_cast(address); - VkMemoryAllocateFlagsInfo flags{VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_FLAGS_INFO, &import}; - flags.flags = VK_MEMORY_ALLOCATE_DEVICE_ADDRESS_BIT; - VkDeviceMemory memory = VK_NULL_HANDLE; - std::uint32_t memory_type = 0; - // Host-visible and coherent first, as the caller's pages are; then any type the driver offers. - for (const VkMemoryPropertyFlags want : - {VkMemoryPropertyFlags(VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT), - VkMemoryPropertyFlags(0)}) { - for (std::uint32_t i = 0; i < state_.memory.memoryTypeCount && !memory; ++i) { - if (!(host.memoryTypeBits & (1u << i)) || - (state_.memory.memoryTypes[i].propertyFlags & want) != want) - continue; - VkMemoryAllocateInfo allocate{VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO, &flags}; - allocate.allocationSize = size; - allocate.memoryTypeIndex = i; - if (state_.context->vk.vkAllocateMemory(state_.info.device, &allocate, nullptr, &memory) == - VK_SUCCESS) - memory_type = i; - else - memory = VK_NULL_HANDLE; - } - if (memory) break; - } - if (!memory) { - log_once("OpenExistingHeapFromAddress: importing the host range failed; size in KiB", int(size / 1024)); - return d3d12_trace::result(method, E_OUTOFMEMORY); - } - D3D12_HEAP_DESC desc{}; - desc.SizeInBytes = size; - desc.Properties.Type = D3D12_HEAP_TYPE_CUSTOM; - desc.Properties.CPUPageProperty = (protect & PAGE_WRITECOMBINE) ? D3D12_CPU_PAGE_PROPERTY_WRITE_COMBINE - : D3D12_CPU_PAGE_PROPERTY_WRITE_BACK; - desc.Properties.MemoryPoolPreference = D3D12_MEMORY_POOL_L0; - desc.Alignment = D3D12_DEFAULT_RESOURCE_PLACEMENT_ALIGNMENT; - desc.Flags = D3D12_HEAP_FLAG_SHARED | D3D12_HEAP_FLAG_SHARED_CROSS_ADAPTER | - D3D12_HEAP_FLAG_ALLOW_SHADER_ATOMICS; - auto* heap = new Heap(state_, desc, memory, memory_type, address); - heap->attach_device(identity()); - return d3d12_trace::result(method, hand_out(heap, riid, out)); - } - - // The size of the VirtualAlloc allocation `address` starts, and its protection, when the whole of it is committed - // PAGE_READWRITE, or PAGE_READWRITE | PAGE_WRITECOMBINE: what the host runtime accepts (a write-combined range - // opens as a WRITE_COMBINE heap). False for an address inside an allocation, a reserved or free page, another - // protection (read-only, PAGE_NOCACHE), or two protections in one allocation. - static bool existing_allocation_size(const void* address, SIZE_T& size, DWORD& protect) { - MEMORY_BASIC_INFORMATION region{}; - if (!VirtualQuery(address, ®ion, sizeof(region)) || region.AllocationBase != address) return false; - protect = region.Protect; - if (protect != PAGE_READWRITE && protect != (PAGE_READWRITE | PAGE_WRITECOMBINE)) return false; - size = 0; - const char* at = static_cast(address); - while (VirtualQuery(at + size, ®ion, sizeof(region)) && region.AllocationBase == address) { - if (region.State != MEM_COMMIT || region.Protect != protect) return false; - size += region.RegionSize; - } - return size != 0; - } - - // create_buffer_at_host_address (Xbox device slot 133). The heap the resource reports is CUSTOM / WRITE_BACK / L0, - // what OpenExistingHeapFromAddress gives the same pages, since the CPU keeps writing them. - // A D3D12_BARRIER_LAYOUT (what Xbox slot 133 passes, as PC CreatePlacedResource2 does) as the legacy initial state - // of an equivalent committed resource. UNDEFINED (0xFFFFFFFF) and anything unlisted give COMMON. - static D3D12_RESOURCE_STATES state_for_barrier_layout(std::uint32_t layout) { - switch (layout) { - case 1: return D3D12_RESOURCE_STATE_GENERIC_READ; - case 2: return D3D12_RESOURCE_STATE_RENDER_TARGET; - case 3: return D3D12_RESOURCE_STATE_UNORDERED_ACCESS; - case 4: return D3D12_RESOURCE_STATE_DEPTH_WRITE; - case 5: return D3D12_RESOURCE_STATE_DEPTH_READ; - case 6: return D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE | D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE; - case 7: return D3D12_RESOURCE_STATE_COPY_SOURCE; - case 8: return D3D12_RESOURCE_STATE_COPY_DEST; - case 9: return D3D12_RESOURCE_STATE_RESOLVE_SOURCE; - case 10: return D3D12_RESOURCE_STATE_RESOLVE_DEST; - default: return D3D12_RESOURCE_STATE_COMMON; - } - } - - HRESULT create_at_host_address(void* address, const D3D12_RESOURCE_DESC& desc, std::uint32_t layout, REFIID riid, - void** out) { - constexpr auto method = "Xbox CreatePlacedResourceX (device slot 133)"; - if (desc.Dimension != D3D12_RESOURCE_DIMENSION_BUFFER) { - // A texture is not placed on the title's pages yet: it gets an ordinary committed DEFAULT texture of the - // same description, as slot 76 gives one, so the title has its resource instead of asserting (found in - // review). Its GPU VA is still the title's address: the console answers a placed texture's - // GetGPUVirtualAddress with the address the title placed it at, and a title turns that into the CPU - // pointer it clears the texture through (docs/d3d12_vulkan.md 3.3). What the title writes at `address` - // does not reach the image yet. - log_once("a title-placed texture (device slot 133) is a committed texture whose GPU VA is the title " - "address; its pixels do not alias the title's pages yet; dimension", - int(desc.Dimension)); - // The title's barrier layout (slot 133's third argument, measured by @dracbat) is checked against the - // description as CreateCommittedResource checks a state; one it refuses (or UNDEFINED) gives COMMON, so - // the title still gets its texture. The image itself starts undefined either way: the first command that - // uses it moves it to that command's layout (vulkan_replay.h, initialize), as for every texture here. - const D3D12_HEAP_PROPERTIES fallback{D3D12_HEAP_TYPE_DEFAULT}; - const D3D12_RESOURCE_STATES initial = state_for_barrier_layout(layout); - HRESULT hr = create_committed_validated(nullptr, &fallback, D3D12_HEAP_FLAG_NONE, &desc, initial, nullptr, - 0, nullptr, riid, out); - if (FAILED(hr) && initial != D3D12_RESOURCE_STATE_COMMON) - hr = create_committed_validated(nullptr, &fallback, D3D12_HEAP_FLAG_NONE, &desc, - D3D12_RESOURCE_STATE_COMMON, nullptr, 0, nullptr, riid, out); - if (SUCCEEDED(hr) && out && *out) { - // The console answers the texture's GetGPUVirtualAddress with the title's address; without it a - // title that clears the texture through that pointer writes at address 0 (XCL measured this on a - // retail title). The image stays the committed fallback above, so only the address is folded in. - if (auto* texture = Resource::from(static_cast(*out))) - texture->set_title_address(reinterpret_cast(address)); - } - return d3d12_trace::result(method, hr); - } - D3D12_HEAP_PROPERTIES heap{}; - heap.Type = D3D12_HEAP_TYPE_CUSTOM; - heap.CPUPageProperty = D3D12_CPU_PAGE_PROPERTY_WRITE_BACK; - heap.MemoryPoolPreference = D3D12_MEMORY_POOL_L0; - auto* resource = new Resource(state_, desc, heap, D3D12_HEAP_FLAG_NONE); - resource->attach_device(identity()); - const HRESULT hr = resource->create_host_buffer(address); - if (hr == E_INVALIDARG) { - resource->Release(); - return d3d12_trace::result(method, hr); - } - if (FAILED(hr)) { - // The driver would not import these pages: RADV refuses a view of a pagefile-backed section, the form - // xmem's physical pages take (found in review on an RX 9070 XT under Wine), and a device without - // VK_EXT_external_memory_host has no import at all. The boot goes on with an ordinary DEFAULT buffer - // of the same description, as #6915's stand-in did: the title gets a resource, but its writes at - // `address` do not reach it. - resource->Release(); - log_once("a title-placed buffer (device slot 133) could not import its pages, so it is an ordinary buffer " - "the title's writes do not reach; HRESULT", - int(hr)); - const D3D12_HEAP_PROPERTIES fallback{D3D12_HEAP_TYPE_DEFAULT}; - return d3d12_trace::result(method, create_committed(&fallback, D3D12_HEAP_FLAG_NONE, &desc, - D3D12_RESOURCE_STATE_COMMON, 0, nullptr, riid, out)); - } - return d3d12_trace::result(method, hand_out(resource, riid, out)); - } - - HRESULT STDMETHODCALLTYPE OpenExistingHeapFromFileMapping(HANDLE file_mapping, REFIID, void** out) override { - constexpr auto method = "ID3D12Device3::OpenExistingHeapFromFileMapping"; - if (out) *out = nullptr; - DWORD flags = 0; - if (!file_mapping || !out || !GetHandleInformation(file_mapping, &flags)) - return d3d12_trace::result(method, E_INVALIDARG); - log_once("OpenExistingHeapFromFileMapping (existing heaps are not supported)", 0); - return d3d12_trace::result(method, E_NOTIMPL); - } - - HRESULT STDMETHODCALLTYPE CreateLifetimeTracker(ID3D12LifetimeOwner* owner, REFIID, void** out) override { - constexpr auto method = "ID3D12Device5::CreateLifetimeTracker"; - if (out) *out = nullptr; - if (!owner || !out) return d3d12_trace::result(method, E_INVALIDARG); - log_once("CreateLifetimeTracker (not supported)", 0); - return d3d12_trace::result(method, E_NOTIMPL); - } - - HRESULT STDMETHODCALLTYPE CreateHeap(const D3D12_HEAP_DESC* desc, REFIID riid, void** out) override { - if (out) *out = nullptr; - if (!desc) return E_INVALIDARG; - if (const char* why = heap_desc_refusal(*desc, state_.uma)) { - log_once((std::string("CreateHeap refused (") + why + "), heap type").c_str(), int(desc->Properties.Type)); - return E_INVALIDARG; - } - if (!state_.arena.mapped) { - log_once("heaps need the GPU address arena (bufferDeviceAddress); heap size in KiB:", - int(desc->SizeInBytes / 1024)); - return E_NOTIMPL; - } - auto* heap = new Heap(state_, *desc); - heap->attach_device(identity()); - if (!heap->reserved()) { - log_once("GPU address arena full (raise LEONIDA_ARENA_MB); heap size in KiB:", int(desc->SizeInBytes / 1024)); - heap->Release(); - return E_OUTOFMEMORY; - } - if (!out) { - heap->Release(); - return S_FALSE; - } - return hand_out(heap, riid, out); - } - - HRESULT STDMETHODCALLTYPE CreatePlacedResource(ID3D12Heap* heap_interface, UINT64 heap_offset, - const D3D12_RESOURCE_DESC* desc, D3D12_RESOURCE_STATES state, - const D3D12_CLEAR_VALUE* clear, REFIID riid, void** out) override { - return create_placed("ID3D12Device::CreatePlacedResource", heap_interface, heap_offset, desc, state, clear, 0, - nullptr, riid, out); - } - - // Device8: the DESC1 placed variant without a castable list. A texture with a mip region gets the failure - // answer, as on the PC runtime; a buffer's mip region is ignored. - HRESULT STDMETHODCALLTYPE CreatePlacedResource1(ID3D12Heap* heap_interface, UINT64 heap_offset, - const D3D12_RESOURCE_DESC1* desc, D3D12_RESOURCE_STATES state, - const D3D12_CLEAR_VALUE* clear, REFIID riid, void** out) override { - constexpr auto method = "ID3D12Device8::CreatePlacedResource1"; - if (out) *out = nullptr; - if (!desc) return d3d12_trace::result(method, E_INVALIDARG); - if (texture_mip_region(*desc)) return d3d12_trace::result(method, E_INVALIDARG); - const D3D12_RESOURCE_DESC base = resource_desc(*desc); - return create_placed(method, heap_interface, heap_offset, &base, state, clear, 0, nullptr, riid, out); - } - - // Device10: an initial layout instead of a state, and the castable-format list, which the placed texture's - // Vulkan image takes exactly as the committed path's does. A count with a null array is no list (as on the - // PC runtime); the layer reports RelaxedFormatCastingSupported, so a real list is passed through. - HRESULT STDMETHODCALLTYPE CreatePlacedResource2(ID3D12Heap* heap_interface, UINT64 heap_offset, - const D3D12_RESOURCE_DESC1* desc, D3D12_BARRIER_LAYOUT layout, - const D3D12_CLEAR_VALUE* clear, UINT32 castable_count, - const DXGI_FORMAT* castable, REFIID riid, void** out) override { - constexpr auto method = "ID3D12Device10::CreatePlacedResource2"; - if (out) *out = nullptr; - if (!desc) return d3d12_trace::result(method, E_INVALIDARG); - if (texture_mip_region(*desc)) return d3d12_trace::result(method, E_INVALIDARG); - const D3D12_RESOURCE_DESC base = resource_desc(*desc); - if (const char* why = barrier_layout_refusal(base, layout)) { - log_once((std::string(method) + " refused (" + why + "), layout").c_str(), int(layout)); - return d3d12_trace::result(method, E_INVALIDARG); - } - // An initial layout replaces the state, so the state rules are not this call's. - return create_placed(method, heap_interface, heap_offset, &base, D3D12_RESOURCE_STATE_COMMON, clear, - castable_count, castable, riid, out); - } - - // The placed path every CreatePlacedResource variant shares. A castable-format list reaches the placed - // texture's Vulkan image as the committed path's does (create_committed): a buffer with a list is - // E_INVALIDARG, and so is a format with no Vulkan mapping. - // The arguments are answered as the host runtime answers them (d3d12_vulkan_device_test's - // compare_placed_reserved, RTX 3060 / 610.88): the description, initial state and clear value rules - // CreateCommittedResource has, then the placement: a buffer at a 64 KiB-aligned offset, a texture at a - // multiple of its GetResourceAllocationInfo alignment (4 KiB for a small texture), in a heap aligned at least - // as much, and the whole resource inside the heap. Only then is a null output E_UNEXPECTED, with nothing made. - HRESULT create_placed(const char* method, ID3D12Heap* heap_interface, UINT64 heap_offset, - const D3D12_RESOURCE_DESC* desc, D3D12_RESOURCE_STATES state, const D3D12_CLEAR_VALUE* clear, - UINT32 castable_count, const DXGI_FORMAT* castable, REFIID riid, void** out) { - if (out) *out = nullptr; - auto* heap = Heap::from(heap_interface); - if (!heap || !desc) return d3d12_trace::result(method, E_INVALIDARG); - if (heap->host_address()) { - // An existing heap is not an arena range, and the placed path addresses resources by arena offset. - log_once("a placed resource in an existing heap (OpenExistingHeapFromAddress) is not supported yet; " - "dimension", - int(desc->Dimension)); - return d3d12_trace::result(method, E_NOTIMPL); - } - if (castable_count && castable && desc->Dimension == D3D12_RESOURCE_DIMENSION_BUFFER) { - log_once("castable formats on a placed buffer are invalid; count", int(castable_count)); - return d3d12_trace::result(method, E_INVALIDARG); - } - // The description, state and clear value rules of a committed resource, but on a default heap: the heap's - // DENY flags are checked against the resource below, and the host takes any initial state for a buffer in - // an upload or readback heap (COPY_DEST in an upload heap, GENERIC_READ in a readback heap), where a - // committed buffer must start in GENERIC_READ or COPY_DEST. UAV access is refused there all the same. - const D3D12_HEAP_PROPERTIES default_heap{D3D12_HEAP_TYPE_DEFAULT}; - const char* why = committed_resource_refusal(default_heap, D3D12_HEAP_FLAG_NONE, *desc, state, clear, - acceleration_structures(), state_.uma); - const D3D12_HEAP_TYPE heap_type = heap->properties().Type; - if (!why && (heap_type == D3D12_HEAP_TYPE_UPLOAD || heap_type == D3D12_HEAP_TYPE_READBACK) && - (desc->Flags & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS)) - why = "UAV access in an upload or readback heap"; - if (why) { - log_once((std::string(method) + " refused (" + why + "), dimension").c_str(), int(desc->Dimension)); - return d3d12_trace::result(method, E_INVALIDARG); - } - const bool tiled = is_tiled_layout(desc->Layout); - const bool msaa = desc->SampleDesc.Count > 1; - if (desc->Dimension == D3D12_RESOURCE_DIMENSION_BUFFER) { - if (heap->flags() & D3D12_HEAP_FLAG_DENY_BUFFERS) return d3d12_trace::result(method, E_INVALIDARG); - if (heap_offset % D3D12_DEFAULT_RESOURCE_PLACEMENT_ALIGNMENT) { - log_once("placed buffer offset not 64 KiB aligned:", int(heap_offset)); - return d3d12_trace::result(method, E_INVALIDARG); - } - if (desc->Width > heap->bytes() || heap_offset > heap->bytes() - desc->Width) - return d3d12_trace::result(method, E_INVALIDARG); - } else { - if (heap->properties().Type == D3D12_HEAP_TYPE_UPLOAD || - heap->properties().Type == D3D12_HEAP_TYPE_READBACK) - return d3d12_trace::result(method, E_INVALIDARG); - const bool rt_ds = (desc->Flags & (D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET | - D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL)) != 0; - if (rt_ds && (heap->flags() & D3D12_HEAP_FLAG_DENY_RT_DS_TEXTURES)) - return d3d12_trace::result(method, E_INVALIDARG); - if (!rt_ds && (heap->flags() & D3D12_HEAP_FLAG_DENY_NON_RT_DS_TEXTURES)) - return d3d12_trace::result(method, E_INVALIDARG); - if (tiled && desc->Dimension != D3D12_RESOURCE_DIMENSION_TEXTURE2D && - desc->Dimension != D3D12_RESOURCE_DIMENSION_TEXTURE3D) - return d3d12_trace::result(method, E_INVALIDARG); - if (msaa && desc->Dimension != D3D12_RESOURCE_DIMENSION_TEXTURE2D) - return d3d12_trace::result(method, E_INVALIDARG); - // Extents, mips, samples, layout and alignment, as GetResourceAllocationInfo answers them (the sample - // quality is the description rules' above, as in CreateCommittedResource). - D3D12_RESOURCE_DESC checked = *desc; - checked.SampleDesc.Quality = 0; - const D3D12_RESOURCE_ALLOCATION_INFO alloc = allocation(checked); - if (alloc.SizeInBytes == UINT64_MAX || heap->alignment() < alloc.Alignment || - heap_offset % alloc.Alignment) { - log_once("placed texture refused (size, alignment or room in the heap), dimension", - int(desc->Dimension)); - return d3d12_trace::result(method, E_INVALIDARG); - } - const UINT64 fit_bytes = - (tiled || msaa) - ? alloc.SizeInBytes - : min_placed_texture_bytes(checked, state_.texture_format(checked), alloc.Alignment, - alloc.SizeInBytes); - if (fit_bytes > heap->bytes() || heap_offset > heap->bytes() - fit_bytes) { - log_once("placed texture refused (size, alignment or room in the heap), dimension", - int(desc->Dimension)); - return d3d12_trace::result(method, E_INVALIDARG); - } - if (tiled && static_cast(desc->Layout) == kXboxTiledLayout) { - log_once("placed resource with the Xbox tiled layout, as 64KB_UNDEFINED_SWIZZLE; dimension", - int(desc->Dimension)); - } - } - if (!out) return d3d12_trace::result(method, E_UNEXPECTED); - const bool buffer = desc->Dimension == D3D12_RESOURCE_DIMENSION_BUFFER; - if (buffer && !heap->use_as_placed_resource(true)) { - log_once("placed buffer refused: heap uses a separate allocation for sparse tiles", 1); - return d3d12_trace::result(method, E_NOTIMPL); - } - // Only buffers are addressable, as in D3D12: a placed texture keeps a null VA and its own Vulkan image, which - // create_texture makes for 1D, 2D and 3D alike (arrays and mips included), as for a committed texture. - const VkDeviceSize placed_va = desc->Dimension == D3D12_RESOURCE_DIMENSION_BUFFER ? heap->offset() + heap_offset : 0; - auto* resource = new Resource(state_, *desc, heap->properties(), heap->flags(), placed_va); - resource->attach_device(identity()); - HRESULT hr = E_NOTIMPL; - if (buffer) { - hr = resource->create_placed_buffer(heap->arena_range()); - } else { - hr = S_OK; - const Format format = state_.texture_format(*desc); - if (format.format == VK_FORMAT_UNDEFINED) { - hr = E_INVALIDARG; - } else { - std::vector cast_formats; - hr = castable_view_formats(format, castable_count, castable, cast_formats); - if (SUCCEEDED(hr)) hr = resource->create_texture(format, cast_formats); - if (SUCCEEDED(hr)) resource->keep_castable_formats(castable_count, castable); - } - } - if (SUCCEEDED(hr) && !buffer && !heap->use_as_placed_resource(false)) { - log_once("placed resource refused: heap uses a separate allocation for sparse tiles", 1); - hr = E_NOTIMPL; - } - if (FAILED(hr)) { - resource->Release(); - return d3d12_trace::result(method, hr); - } - return d3d12_trace::result(method, hand_out(resource, riid, out)); - } - - // Footprints for copies through a buffer: rows padded to D3D12_TEXTURE_DATA_PITCH_ALIGNMENT (512 for planar - // depth-stencil), subresources placed at D3D12_TEXTURE_DATA_PLACEMENT_ALIGNMENT, block-compressed sizes rounded up to whole blocks, depth-stencil - // formats as two planes. d3d12_vulkan_device_test compares every output with the PC runtime's. - void STDMETHODCALLTYPE GetCopyableFootprints(const D3D12_RESOURCE_DESC* desc, UINT first, UINT count, UINT64 base, - D3D12_PLACED_SUBRESOURCE_FOOTPRINT* layouts, UINT* rows, - UINT64* row_sizes, UINT64* total) override { - const auto fail = [&] { - for (UINT i = 0; i < count; ++i) { - if (layouts) std::memset(&layouts[i], 0xff, sizeof(layouts[i])); - if (rows) rows[i] = ~0u; - if (row_sizes) row_sizes[i] = ~0ull; - } - if (total) *total = ~0ull; - }; - if (!desc || !xr_bias_compatible(*desc) || rgb96_refused(*desc)) return fail(); - const auto align = [](UINT64 value, UINT64 to) { return (value + to - 1) / to * to; }; - if (desc->Dimension == D3D12_RESOURCE_DIMENSION_BUFFER) { - // The PC runtime refuses any buffer field that isn't its one valid value (all measured on WARP, Width, - // Height, Format, MipLevels 0, Layout and Count 0 also on an NVIDIA GPU). It doesn't look at Flags, so a - // buffer with the render-target flag still gets its footprint (D3D-122). - if (first != 0 || count != 1 || !desc->Width || desc->Height != 1 || desc->DepthOrArraySize != 1 || - desc->MipLevels != 1 || desc->Format != DXGI_FORMAT_UNKNOWN || - desc->Layout != D3D12_TEXTURE_LAYOUT_ROW_MAJOR || desc->SampleDesc.Count != 1 || - desc->SampleDesc.Quality != 0 || - (desc->Alignment && desc->Alignment != D3D12_DEFAULT_RESOURCE_PLACEMENT_ALIGNMENT)) - return fail(); - if (layouts) layouts[0] = {base, {DXGI_FORMAT_UNKNOWN, UINT(desc->Width), 1, 1, - UINT(align(desc->Width, D3D12_TEXTURE_DATA_PITCH_ALIGNMENT))}}; - if (rows) rows[0] = 1; - if (row_sizes) row_sizes[0] = desc->Width; - if (total) *total = desc->Width; - return; - } - const bool volume = desc->Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE3D; - const bool one_d = desc->Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE1D; - if (!volume && !one_d && desc->Dimension != D3D12_RESOURCE_DIMENSION_TEXTURE2D) { - log_once("GetCopyableFootprints dimension not supported:", desc->Dimension); - return fail(); - } - if (one_d && desc->Height != 1) return fail(); - // Structural checks only, as measured on the PC runtime (D3D-122). Not allocation()'s: the footprint path - // accepts extra mips, 2D ROW_MAJOR and Quality > 0 at one sample, and extent limits, alignment and - // multisample quality differ between adapters, so those stay unchecked. - const UINT samples = desc->SampleDesc.Count; - const bool multisample_ok = desc->Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE2D && desc->MipLevels == 1 && - desc->Layout != D3D12_TEXTURE_LAYOUT_ROW_MAJOR && !(samples & (samples - 1)) && - (desc->Flags & (D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET | - D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL)); - if (!desc->Width || !desc->Height || !desc->DepthOrArraySize || !samples || (samples > 1 && !multisample_ok)) - return fail(); - const Format format = texture_storage_format(desc->Format, true); // typeless depth families are planar either way - UINT mips = desc->MipLevels; - const UINT depth = volume ? desc->DepthOrArraySize : 1; - if (!mips) - for (UINT64 size = std::max({desc->Width, desc->Height, depth}); size; size >>= 1) ++mips; - const UINT planes = (format.aspects & VK_IMAGE_ASPECT_STENCIL_BIT) ? 2 : 1; - const UINT per_plane = mips * (volume ? 1 : desc->DepthOrArraySize); - if (!format.format || UINT64(first) + count > UINT64(per_plane) * planes) return fail(); - - // Subresources are aligned to D3D12_TEXTURE_DATA_PLACEMENT_ALIGNMENT counting from BaseOffset, not from 0: the - // PC runtime moves the whole layout by BaseOffset, so an unaligned base (513) keeps the same relative offsets - // and the same total. Measured by compare_footprints in d3d12_vulkan_device_test. - UINT64 offset = 0, end = 0; - for (UINT i = 0; i < count; ++i) { - const UINT index = first + i, plane = index / per_plane, mip = index % mips; - const VkImageAspectFlags aspect = - planes == 2 ? (plane ? VK_IMAGE_ASPECT_STENCIL_BIT : VK_IMAGE_ASPECT_DEPTH_BIT) : format.aspects; - const leonida::BlockFormat block = footprint_block(format, aspect); - if (!block.bytes) return fail(); - // D3D12 takes any MipLevels, and the PC runtime's own shifts wrap past the type's width: a 16x16 texture - // with 40 mips reports subresource 32 as 1x16 and 33 as 1x8, a volume's depth likewise (measured on an - // RTX 5060 Ti, compare_footprints). The masks give the same answers without shifting a 32-bit (or the - // 64-bit Width) value by its width or more, which C++ leaves undefined. - const UINT width = std::max(1, UINT(desc->Width >> (mip & 63))); - const UINT height = one_d ? 1 : std::max(1, desc->Height >> (mip & 31)); - const UINT blocks_wide = (width + block.block - 1) / block.block; - const UINT blocks_high = (height + block.block - 1) / block.block; - const UINT64 row_size = UINT64(blocks_wide) * block.bytes; - // Measured against the PC runtime (d3d12_vulkan_device_test): planar depth-stencil rows are padded to - // 512 bytes, every other format's to D3D12_TEXTURE_DATA_PITCH_ALIGNMENT (256). - const UINT pitch = UINT(align(row_size, planes == 2 ? 2 * D3D12_TEXTURE_DATA_PITCH_ALIGNMENT - : D3D12_TEXTURE_DATA_PITCH_ALIGNMENT)); - offset = align(offset, D3D12_TEXTURE_DATA_PLACEMENT_ALIGNMENT); - DXGI_FORMAT footprint_format = desc->Format; - if (planes == 2) footprint_format = plane ? DXGI_FORMAT_R8_TYPELESS : DXGI_FORMAT_R32_TYPELESS; - const UINT slices = std::max(1u, depth >> (mip & 31)); - if (layouts) - layouts[i] = {base + offset, - {footprint_format, blocks_wide * block.block, blocks_high * block.block, slices, pitch}}; - if (rows) rows[i] = blocks_high; - if (row_sizes) row_sizes[i] = row_size; - const UINT64 total_rows = UINT64(blocks_high) * slices; - end = offset + (total_rows - 1) * pitch + row_size; - offset += total_rows * pitch; - } - if (total) *total = end; - } - - // How much heap memory resources need and how to align them, for applications that suballocate heaps (section - // 4.1). Buffers follow D3D12's fixed rule. A texture's size is what the Vulkan image it becomes needs, rounded up - // to D3D12's alignment for it; the alignment itself is D3D12's, since placed textures bind their own memory - // (section 4.2). Several resources are laid out one after another, each at its own alignment. An invalid - // description gives SizeInBytes = UINT64_MAX, as on D3D12. d3d12_vulkan_device_test compares with the PC runtime. - // A visible mask above 1 names a node the single-node adapter lacks: the same invalid answer, also for no - // resources at all, and the per-resource array is left untouched (host runtime and WARP, measured). - D3D12_RESOURCE_ALLOCATION_INFO STDMETHODCALLTYPE GetResourceAllocationInfo( - UINT visible_mask, UINT count, const D3D12_RESOURCE_DESC* descs) override { - if (visible_mask > 1) return kInvalidAllocation; - return place(count, descs, [&](UINT i) { return descs[i]; }, nullptr); - } - D3D12_RESOURCE_ALLOCATION_INFO STDMETHODCALLTYPE GetResourceAllocationInfo1( - UINT visible_mask, UINT count, const D3D12_RESOURCE_DESC* descs, - D3D12_RESOURCE_ALLOCATION_INFO1* each) override { - if (visible_mask > 1) return kInvalidAllocation; - return place(count, descs, [&](UINT i) { return descs[i]; }, each); - } - D3D12_RESOURCE_ALLOCATION_INFO STDMETHODCALLTYPE GetResourceAllocationInfo2( - UINT visible_mask, UINT count, const D3D12_RESOURCE_DESC1* descs, - D3D12_RESOURCE_ALLOCATION_INFO1* each) override { - if (visible_mask > 1) return kInvalidAllocation; - return place(count, descs, [&](UINT i) { - const D3D12_RESOURCE_DESC1& d = descs[i]; - if (d.SamplerFeedbackMipRegion.Width || d.SamplerFeedbackMipRegion.Height || - d.SamplerFeedbackMipRegion.Depth) { - log_once("GetResourceAllocationInfo2 sampler feedback not supported, format", d.Format); - return D3D12_RESOURCE_DESC{}; // an unknown dimension: invalid - } - return D3D12_RESOURCE_DESC{d.Dimension, d.Alignment, d.Width, d.Height, d.DepthOrArraySize, - d.MipLevels, d.Format, d.SampleDesc, d.Layout, d.Flags}; - }, each); - } - - template - static HRESULT write_supported_feature(const char* method, void* data, UINT size, BOOL supported) { - if (size != sizeof(FeatureData)) return d3d12_trace::result(method, E_INVALIDARG); - static_cast(data)->Supported = supported; - return d3d12_trace::result(method, S_OK); - } - - HRESULT STDMETHODCALLTYPE CheckFeatureSupport(D3D12_FEATURE feature, void* data, UINT size) override { - constexpr auto method = "ID3D12Device::CheckFeatureSupport"; - log_once("CheckFeatureSupport feature", feature); - if (!data) return d3d12_trace::result(method, E_INVALIDARG); - constexpr VkSampleCountFlags d3d12_multisample_sample_counts = - VK_SAMPLE_COUNT_2_BIT | VK_SAMPLE_COUNT_4_BIT | VK_SAMPLE_COUNT_8_BIT | - VK_SAMPLE_COUNT_16_BIT | VK_SAMPLE_COUNT_32_BIT; - switch (feature) { - case D3D12_FEATURE_FEATURE_LEVELS: { - if (size != sizeof(D3D12_FEATURE_DATA_FEATURE_LEVELS)) return d3d12_trace::result(method, E_INVALIDARG); - auto* levels = static_cast(data); - // The host (hardware and WARP) refuses an empty or missing list before reading it. - if (!levels->NumFeatureLevels || !levels->pFeatureLevelsRequested) - return d3d12_trace::result(method, E_INVALIDARG); - D3D_FEATURE_LEVEL best = D3D_FEATURE_LEVEL(0); - for (UINT i = 0; i < levels->NumFeatureLevels; ++i) - if (levels->pFeatureLevelsRequested[i] <= D3D_FEATURE_LEVEL_12_1) - best = std::max(best, levels->pFeatureLevelsRequested[i]); - levels->MaxSupportedFeatureLevel = best; // 0 with DXGI_ERROR_UNSUPPORTED, as the host writes it - if (!best) return d3d12_trace::result(method, DXGI_ERROR_UNSUPPORTED); - return d3d12_trace::result(method, S_OK); - } - case D3D12_FEATURE_ARCHITECTURE: - case D3D12_FEATURE_ARCHITECTURE1: { - const bool v1 = feature == D3D12_FEATURE_ARCHITECTURE1; - if (size != (v1 ? sizeof(D3D12_FEATURE_DATA_ARCHITECTURE1) : sizeof(D3D12_FEATURE_DATA_ARCHITECTURE))) - return d3d12_trace::result(method, E_INVALIDARG); - auto* arch = static_cast(data); - const UINT node = arch->NodeIndex; - if (node != 0) return d3d12_trace::result(method, E_INVALIDARG); - // The host GPU's architecture (question 11): not tile-based; UMA on an integrated GPU, as the host runtime - // answers there (Radeon 780M, AMD 32.0.13030.13001: UMA 1, CacheCoherentUMA 0), else a discrete one. The - // console is UMA; the layer keeps upload heaps host-visible either way, so the game's upload path works. - // CacheCoherentUMA stays FALSE: the AMD iGPU measured reports it so, and FALSE only steers an application - // to write-combined uploads, which every UMA adapter accepts. - arch->TileBasedRenderer = FALSE; - arch->UMA = state_.uma ? TRUE : FALSE; - arch->CacheCoherentUMA = FALSE; - if (v1) arch->IsolatedMMU = TRUE; - return d3d12_trace::result(method, S_OK); - } - case D3D12_FEATURE_D3D12_OPTIONS: { - if (size != sizeof(D3D12_FEATURE_DATA_D3D12_OPTIONS)) return d3d12_trace::result(method, E_INVALIDARG); - auto* opts = static_cast(data); - *opts = {}; - // Answer what the layer will actually honour, not what the GPU offers: docs/d3d12_vulkan.md 4.1 says a - // false "supported" is worse than a false "unsupported" at boot, and the PSO paths refuse these same - // features when they are missing (logic ops, per the mapping vkd3d-proton's - // d3d12_device_caps_init_feature_options uses). - opts->DoublePrecisionFloatShaderOps = state_.info.features.shaderFloat64; - opts->OutputMergerLogicOp = state_.info.features.logicOp; - opts->MinPrecisionSupport = D3D12_SHADER_MIN_PRECISION_SUPPORT_NONE; - opts->TiledResourcesTier = D3D12_TILED_RESOURCES_TIER_NOT_SUPPORTED; - opts->ResourceBindingTier = D3D12_RESOURCE_BINDING_TIER_3; // Bindless descriptor indexing supported - // No VK_EXT_shader_stencil_export is enabled and the translator emits no stencil-ref write, so a pixel - // shader that writes the stencil ref would be refused: answer unsupported, the direction 4.1 prefers. - opts->PSSpecifiedStencilRefSupported = FALSE; - opts->TypedUAVLoadAdditionalFormats = TRUE; - // POPS: the translator only declares PixelInterlockOrderedEXT, enabled exactly when the GPU offers - // VK_EXT_fragment_shader_interlock and its fragmentShaderPixelInterlock feature. - opts->ROVsSupported = state_.info.fragment_shader_interlock; - opts->ConservativeRasterizationTier = state_.conservative_raster_tier; - opts->MaxGPUVirtualAddressBitsPerResource = 40; - opts->StandardSwizzle64KBSupported = FALSE; - opts->CrossNodeSharingTier = D3D12_CROSS_NODE_SHARING_TIER_NOT_SUPPORTED; - opts->CrossAdapterRowMajorTextureSupported = FALSE; - // A translated vertex shader writing a layer or viewport index needs both Vulkan 1.2 features enabled - // (vkCreateShaderModule refuses the module without them, VUID-...-pCode-08740). - opts->VPAndRTArrayIndexFromAnyShaderFeedingRasterizerSupportedWithoutGSEmulation = - state_.info.shader_output_layer && state_.info.shader_output_viewport_index; - opts->ResourceHeapTier = D3D12_RESOURCE_HEAP_TIER_1; - return d3d12_trace::result(method, S_OK); - } - case D3D12_FEATURE_D3D12_OPTIONS1: { - if (size != sizeof(D3D12_FEATURE_DATA_D3D12_OPTIONS1)) return d3d12_trace::result(method, E_INVALIDARG); - auto* opts = static_cast(data); - const DeviceState::SubgroupFacts& facts = state_.subgroup_facts(); - *opts = {}; - opts->WaveOps = facts.wave_ops; - opts->WaveLaneCountMin = facts.lane_min; - opts->WaveLaneCountMax = facts.lane_max; - // D3D12 counts every lane of the device here, and Vulkan has no such number. This is one full wave - // (section 4.1): a game that sizes work from it plans for less parallelism than the GPU has, not more. - opts->TotalLaneCount = facts.lane_max; - opts->ExpandedComputeResourceStates = TRUE; // Vulkan has no resource states to expand - return d3d12_trace::result(method, S_OK); - } - case D3D12_FEATURE_D3D12_OPTIONS8: { - if (size != sizeof(D3D12_FEATURE_DATA_D3D12_OPTIONS8)) return d3d12_trace::result(method, E_INVALIDARG); - // Vulkan BC image extents are in texels; only the transfer footprints round up to blocks. - auto* opts = static_cast(data); - opts->UnalignedBlockTexturesSupported = state_.info.texture_compression_bc; - return d3d12_trace::result(method, S_OK); - } - case D3D12_FEATURE_D3D12_OPTIONS2: { - if (size != sizeof(D3D12_FEATURE_DATA_D3D12_OPTIONS2)) return d3d12_trace::result(method, E_INVALIDARG); - auto* opts = static_cast(data); - *opts = {}; - opts->DepthBoundsTestSupported = FALSE; - opts->ProgrammableSamplePositionsTier = D3D12_PROGRAMMABLE_SAMPLE_POSITIONS_TIER_NOT_SUPPORTED; - return d3d12_trace::result(method, S_OK); - } - case D3D12_FEATURE_D3D12_OPTIONS3: { - if (size != sizeof(D3D12_FEATURE_DATA_D3D12_OPTIONS3)) return d3d12_trace::result(method, E_INVALIDARG); - auto* opts = static_cast(data); - *opts = {}; - opts->CopyQueueTimestampQueriesSupported = FALSE; - // Only typeless resources set VK_IMAGE_CREATE_MUTABLE_FORMAT_BIT. - opts->CastingFullyTypedFormatSupported = FALSE; - opts->WriteBufferImmediateSupportFlags = D3D12_COMMAND_LIST_SUPPORT_FLAG_NONE; - opts->ViewInstancingTier = D3D12_VIEW_INSTANCING_TIER_NOT_SUPPORTED; - opts->BarycentricsSupported = FALSE; - return d3d12_trace::result(method, S_OK); - } - case D3D12_FEATURE_D3D12_OPTIONS4: { - if (size != sizeof(D3D12_FEATURE_DATA_D3D12_OPTIONS4)) return d3d12_trace::result(method, E_INVALIDARG); - auto* opts = static_cast(data); - *opts = {}; - // GetResourceAllocationInfo implements D3D12_SMALL_MSAA_RESOURCE_PLACEMENT_ALIGNMENT (64 KiB). - opts->MSAA64KBAlignedTextureSupported = TRUE; - opts->SharedResourceCompatibilityTier = D3D12_SHARED_RESOURCE_COMPATIBILITY_TIER_0; - opts->Native16BitShaderOpsSupported = FALSE; - return d3d12_trace::result(method, S_OK); - } - case D3D12_FEATURE_D3D12_OPTIONS5: { - if (size != sizeof(D3D12_FEATURE_DATA_D3D12_OPTIONS5)) return d3d12_trace::result(method, E_INVALIDARG); - auto* opts = static_cast(data); - *opts = {}; - opts->SRVOnlyTiledResourceTier3 = FALSE; - opts->RenderPassesTier = D3D12_RENDER_PASS_TIER_0; - opts->RaytracingTier = D3D12_RAYTRACING_TIER_NOT_SUPPORTED; - return d3d12_trace::result(method, S_OK); - } - case D3D12_FEATURE_D3D12_OPTIONS7: { - if (size != sizeof(D3D12_FEATURE_DATA_D3D12_OPTIONS7)) return d3d12_trace::result(method, E_INVALIDARG); - auto* opts = static_cast(data); - *opts = {}; - // Tier 1 is mesh PSOs and DispatchMesh, on VK_EXT_mesh_shader. Amplification shaders are part of the tier - // but refused at PSO creation (the game has none); OPTIONS9's mesh statistics and full-range render - // target array index stay FALSE. - opts->MeshShaderTier = - state_.info.mesh_shader ? D3D12_MESH_SHADER_TIER_1 : D3D12_MESH_SHADER_TIER_NOT_SUPPORTED; - opts->SamplerFeedbackTier = D3D12_SAMPLER_FEEDBACK_TIER_NOT_SUPPORTED; - return d3d12_trace::result(method, S_OK); - } - case D3D12_FEATURE_D3D12_OPTIONS9: { - if (size != sizeof(D3D12_FEATURE_DATA_D3D12_OPTIONS9)) return d3d12_trace::result(method, E_INVALIDARG); - auto* opts = static_cast(data); - *opts = {}; - opts->MeshShaderPipelineStatsSupported = FALSE; - opts->MeshShaderSupportsFullRangeRenderTargetArrayIndex = FALSE; - opts->AtomicInt64OnTypedResourceSupported = FALSE; - opts->AtomicInt64OnGroupSharedSupported = FALSE; - opts->DerivativesInMeshAndAmplificationShadersSupported = FALSE; - opts->WaveMMATier = D3D12_WAVE_MMA_TIER_NOT_SUPPORTED; - return d3d12_trace::result(method, S_OK); - } - case D3D12_FEATURE_D3D12_OPTIONS11: { - if (size != sizeof(D3D12_FEATURE_DATA_D3D12_OPTIONS11)) return d3d12_trace::result(method, E_INVALIDARG); - auto* opts = static_cast(data); - *opts = {}; - opts->AtomicInt64OnDescriptorHeapResourceSupported = FALSE; - return d3d12_trace::result(method, S_OK); - } - case D3D12_FEATURE_D3D12_OPTIONS13: { - if (size != sizeof(D3D12_FEATURE_DATA_D3D12_OPTIONS13)) return d3d12_trace::result(method, E_INVALIDARG); - auto* opts = static_cast(data); - *opts = {}; - opts->UnrestrictedBufferTextureCopyPitchSupported = FALSE; - opts->UnrestrictedVertexElementAlignmentSupported = FALSE; - opts->InvertedViewportHeightFlipsYSupported = FALSE; - opts->InvertedViewportDepthFlipsZSupported = FALSE; - opts->TextureCopyBetweenDimensionsSupported = FALSE; - opts->AlphaBlendFactorSupported = FALSE; - return d3d12_trace::result(method, S_OK); - } - case D3D12_FEATURE_D3D12_OPTIONS14: { - if (size != sizeof(D3D12_FEATURE_DATA_D3D12_OPTIONS14)) return d3d12_trace::result(method, E_INVALIDARG); - auto* opts = static_cast(data); - *opts = {}; - opts->AdvancedTextureOpsSupported = FALSE; - opts->WriteableMSAATexturesSupported = FALSE; - opts->IndependentFrontAndBackStencilRefMaskSupported = FALSE; - return d3d12_trace::result(method, S_OK); - } - case D3D12_FEATURE_D3D12_OPTIONS15: { - if (size != sizeof(D3D12_FEATURE_DATA_D3D12_OPTIONS15)) return d3d12_trace::result(method, E_INVALIDARG); - auto* opts = static_cast(data); - *opts = {}; - opts->TriangleFanSupported = FALSE; - opts->DynamicIndexBufferStripCutSupported = FALSE; - return d3d12_trace::result(method, S_OK); - } - case D3D12_FEATURE_D3D12_OPTIONS16: { - if (size != sizeof(D3D12_FEATURE_DATA_D3D12_OPTIONS16)) return d3d12_trace::result(method, E_INVALIDARG); - auto* opts = static_cast(data); - *opts = {}; - opts->DynamicDepthBiasSupported = FALSE; - opts->GPUUploadHeapSupported = FALSE; - return d3d12_trace::result(method, S_OK); - } - case D3D12_FEATURE_D3D12_OPTIONS12: { - // Vulkan 1.3's VkImageFormatListCreateInfo gives a mutable image the same relaxed format casting that - // D3D12's castable-format lists describe. The layer also implements enhanced barriers (Barrier). - if (size != sizeof(D3D12_FEATURE_DATA_D3D12_OPTIONS12)) return E_INVALIDARG; - auto* opts = static_cast(data); - *opts = {}; - opts->MSPrimitivesPipelineStatisticIncludesCulledPrimitives = D3D12_TRI_STATE_UNKNOWN; - opts->EnhancedBarriersSupported = TRUE; - opts->RelaxedFormatCastingSupported = TRUE; - return S_OK; - } - case D3D12_FEATURE_D3D12_OPTIONS17: { - // Non-normalized samplers are core Vulkan (unnormalizedCoordinates), with the restrictions - // CreateSampler2 checks. No manual write tracking, as the RTX 4090 answers too. - if (size != sizeof(D3D12_FEATURE_DATA_D3D12_OPTIONS17)) return d3d12_trace::result(method, E_INVALIDARG); - auto* opts = static_cast(data); - *opts = {}; - opts->NonNormalizedCoordinateSamplersSupported = TRUE; - return d3d12_trace::result(method, S_OK); - } - case D3D12_FEATURE_D3D12_OPTIONS18: { - if (size != sizeof(D3D12_FEATURE_DATA_D3D12_OPTIONS18)) return d3d12_trace::result(method, E_INVALIDARG); - auto* opts = static_cast(data); - *opts = {}; - opts->RenderPassesValid = FALSE; - return d3d12_trace::result(method, S_OK); - } - case D3D12_FEATURE_D3D12_OPTIONS19: { - if (size != sizeof(D3D12_FEATURE_DATA_D3D12_OPTIONS19)) return d3d12_trace::result(method, E_INVALIDARG); - auto* opts = static_cast(data); - *opts = {}; - opts->MismatchingOutputDimensionsSupported = FALSE; - opts->SupportedSampleCountsWithNoOutputs = state_.no_output_sample_counts; - opts->PointSamplingAddressesNeverRoundUp = FALSE; - opts->RasterizerDesc2Supported = FALSE; - opts->NarrowQuadrilateralLinesSupported = FALSE; - opts->AnisoFilterWithPointMipSupported = state_.info.sampler_anisotropy ? TRUE : FALSE; - opts->MaxSamplerDescriptorHeapSize = D3D12_MAX_SHADER_VISIBLE_SAMPLER_HEAP_SIZE; - opts->MaxSamplerDescriptorHeapSizeWithStaticSamplers = D3D12_MAX_SHADER_VISIBLE_SAMPLER_HEAP_SIZE; - opts->MaxViewDescriptorHeapSize = D3D12_MAX_SHADER_VISIBLE_DESCRIPTOR_HEAP_SIZE_TIER_2; - opts->ComputeOnlyCustomHeapSupported = FALSE; - return d3d12_trace::result(method, S_OK); - } - case compat::kFeatureOptions20: { - if (size != sizeof(compat::FeatureDataOptions20)) return d3d12_trace::result(method, E_INVALIDARG); - auto* opts = static_cast(data); - *opts = {}; - opts->ComputeOnlyWriteWatchSupported = FALSE; - opts->RecreateAtTier = compat::kRecreateAtTierNotSupported; - return d3d12_trace::result(method, S_OK); - } - case compat::kFeatureOptions21: { - if (size != sizeof(compat::FeatureDataOptions21)) return d3d12_trace::result(method, E_INVALIDARG); - auto* opts = static_cast(data); - *opts = {}; - opts->WorkGraphsTier = compat::kWorkGraphsTierNotSupported; - opts->ExecuteIndirectTier = compat::kExecuteIndirectTier1_0; - opts->SampleCmpGradientAndBiasSupported = FALSE; - opts->ExtendedCommandInfoSupported = FALSE; - return d3d12_trace::result(method, S_OK); - } - case D3D12_FEATURE_GPU_VIRTUAL_ADDRESS_SUPPORT: { - if (size != sizeof(D3D12_FEATURE_DATA_GPU_VIRTUAL_ADDRESS_SUPPORT)) return d3d12_trace::result(method, E_INVALIDARG); - auto* va = static_cast(data); - // The console and PC BDA support 48-bit GPU virtual addresses (section 4.1). - va->MaxGPUVirtualAddressBitsPerResource = 40; - va->MaxGPUVirtualAddressBitsPerProcess = 48; - return d3d12_trace::result(method, S_OK); - } - case D3D12_FEATURE_FORMAT_INFO: { - if (size != sizeof(D3D12_FEATURE_DATA_FORMAT_INFO)) return E_INVALIDARG; - auto* info = static_cast(data); - // Plane count describes the DXGI layout even when the backend cannot create the texture. - switch (info->Format) { - case DXGI_FORMAT_R32G8X24_TYPELESS: - case DXGI_FORMAT_D32_FLOAT_S8X24_UINT: - case DXGI_FORMAT_R32_FLOAT_X8X24_TYPELESS: - case DXGI_FORMAT_X32_TYPELESS_G8X24_UINT: - case DXGI_FORMAT_R24G8_TYPELESS: - case DXGI_FORMAT_D24_UNORM_S8_UINT: - case DXGI_FORMAT_R24_UNORM_X8_TYPELESS: - case DXGI_FORMAT_X24_TYPELESS_G8_UINT: - case DXGI_FORMAT_NV12: - case DXGI_FORMAT_P010: - case DXGI_FORMAT_P016: - case DXGI_FORMAT_NV11: - info->PlaneCount = 2; - break; - case DXGI_FORMAT_SAMPLER_FEEDBACK_MIN_MIP_OPAQUE: - case DXGI_FORMAT_SAMPLER_FEEDBACK_MIP_REGION_USED_OPAQUE: - case DXGI_FORMAT_A4B4G4R4_UNORM: - info->PlaneCount = 1; - break; - default: - // Native D3D12 accepts UNKNOWN but rejects R1_UNORM and the gaps in the enum. - if (UINT(info->Format) > DXGI_FORMAT_B4G4R4A4_UNORM || info->Format == DXGI_FORMAT_R1_UNORM) - return E_INVALIDARG; - info->PlaneCount = 1; - } - return S_OK; - } - case D3D12_FEATURE_FORMAT_SUPPORT: { - if (size != sizeof(D3D12_FEATURE_DATA_FORMAT_SUPPORT)) return d3d12_trace::result(method, E_INVALIDARG); - auto* fs = static_cast(data); - fs->Support1 = D3D12_FORMAT_SUPPORT1_NONE; - fs->Support2 = D3D12_FORMAT_SUPPORT2_NONE; - // The host runtime's format table (compare_invalid_arguments, "format support:"): a value it has no entry - // for is E_FAIL, not unsupported: past B4G4R4A4_UNORM (115) up to 188, which includes the planar video - // formats P208/V208/V408 (130-132), and from 192 up; 189-191 are the sampler-feedback formats and - // A4B4G4R4. UNKNOWN is a buffer format (raw and structured buffers). - const UINT format_value = static_cast(fs->Format); - if (format_value > static_cast(DXGI_FORMAT_B4G4R4A4_UNORM) && - (format_value < 189 || format_value > 191)) - return d3d12_trace::result(method, E_FAIL); - if (fs->Format == DXGI_FORMAT_UNKNOWN) { - fs->Support1 = D3D12_FORMAT_SUPPORT1_BUFFER; - return d3d12_trace::result(method, S_OK); - } - // The plane formats a shader reads a depth-stencil texture through (CreateShaderResourceView takes them on - // R24G8/R32G8X24 and D24S8/D32S8 textures) have no image of their own, so the lookups below find nothing. - // The host reports them as sampled 2D and cube textures with mips, the depth plane also filtered and - // compared. Left out, as for the depth formats themselves: 1D, and multisample loads. - const bool depth_plane = fs->Format == DXGI_FORMAT_R24_UNORM_X8_TYPELESS || - fs->Format == DXGI_FORMAT_R32_FLOAT_X8X24_TYPELESS; - if (depth_plane || fs->Format == DXGI_FORMAT_X24_TYPELESS_G8_UINT || - fs->Format == DXGI_FORMAT_X32_TYPELESS_G8X24_UINT) { - const bool d24 = fs->Format == DXGI_FORMAT_R24_UNORM_X8_TYPELESS || - fs->Format == DXGI_FORMAT_X24_TYPELESS_G8_UINT; - VkFormat family = vulkan_format(d24 ? DXGI_FORMAT_D24_UNORM_S8_UINT : DXGI_FORMAT_D32_FLOAT_S8X24_UINT, - true).format; - if (family == VK_FORMAT_D24_UNORM_S8_UINT && !state_.depth_usable(family)) - family = VK_FORMAT_D32_SFLOAT_S8_UINT; - VkFormatProperties props{}; - if (state_.format_properties) state_.format_properties(state_.info.physical, family, &props); - if (!(props.optimalTilingFeatures & VK_FORMAT_FEATURE_SAMPLED_IMAGE_BIT)) - return d3d12_trace::result(method, DXGI_ERROR_UNSUPPORTED); - fs->Support1 = D3D12_FORMAT_SUPPORT1_TEXTURE2D | D3D12_FORMAT_SUPPORT1_TEXTURECUBE | - D3D12_FORMAT_SUPPORT1_SHADER_LOAD | D3D12_FORMAT_SUPPORT1_MIP; - if (depth_plane && (props.optimalTilingFeatures & VK_FORMAT_FEATURE_SAMPLED_IMAGE_FILTER_LINEAR_BIT)) - fs->Support1 |= D3D12_FORMAT_SUPPORT1_SHADER_SAMPLE | D3D12_FORMAT_SUPPORT1_SHADER_GATHER | - D3D12_FORMAT_SUPPORT1_SHADER_SAMPLE_COMPARISON | - D3D12_FORMAT_SUPPORT1_SHADER_GATHER_COMPARISON; - return d3d12_trace::result(method, S_OK); - } - const Format fmt = texture_storage_format(fs->Format, false); - const Format depth_fmt = vulkan_format(fs->Format, true); - VkFormat vk_fmt = fmt.format != VK_FORMAT_UNDEFINED ? fmt.format : depth_fmt.format; - // Report what creation makes: a D24 texture on a GPU without Vulkan D24 (AMD) is a D32_SFLOAT_S8_UINT - // image (texture_format), so its features are D32S8's. Asking D24 itself gave Support1 = 0 there, - // although CreateCommittedResource(ALLOW_DEPTH_STENCIL) succeeds. - if (vk_fmt == VK_FORMAT_D24_UNORM_S8_UINT && !state_.depth_usable(vk_fmt)) - vk_fmt = VK_FORMAT_D32_SFLOAT_S8_UINT; - if (vk_fmt == VK_FORMAT_UNDEFINED || !state_.format_properties) { - return d3d12_trace::result(method, DXGI_ERROR_UNSUPPORTED); - } - if (fs->Format == DXGI_FORMAT_R10G10B10_XR_BIAS_A2_UNORM) { - // The host reports this display format as 2D, display, cast-within-bit-layout, back-buffer-cast and - // video-processor output, and no shader reads. The layer has the 2D resource and the bit-compatible - // view cast; it has no display scan-out or video processor, so it reports only what it provides. - fs->Support1 = D3D12_FORMAT_SUPPORT1_TEXTURE2D | D3D12_FORMAT_SUPPORT1_CAST_WITHIN_BIT_LAYOUT; - return S_OK; - } - VkFormatProperties props{}; - state_.format_properties(state_.info.physical, vk_fmt, &props); - VkFormatFeatureFlags optimal = props.optimalTilingFeatures; - VkFormatFeatureFlags buffer = props.bufferFeatures; - if (fmt.rgb96) { - // Textures are RGBA32 images that are sampled and copied, nothing else yet (no render target, - // no unordered access: creation refuses them). Buffers hold the real 12-byte format; the PC - // runtime (WARP) has no typed unordered access of these formats, in buffers either. - optimal &= VK_FORMAT_FEATURE_SAMPLED_IMAGE_BIT | VK_FORMAT_FEATURE_SAMPLED_IMAGE_FILTER_LINEAR_BIT; - VkFormatProperties narrow{}; - state_.format_properties(state_.info.physical, rgb96_named_format(vk_fmt), &narrow); - buffer = narrow.bufferFeatures & - ~VkFormatFeatureFlags(VK_FORMAT_FEATURE_STORAGE_TEXEL_BUFFER_BIT | - VK_FORMAT_FEATURE_STORAGE_TEXEL_BUFFER_ATOMIC_BIT); - } - - D3D12_FORMAT_SUPPORT1 s1 = D3D12_FORMAT_SUPPORT1_NONE; - D3D12_FORMAT_SUPPORT2 s2 = D3D12_FORMAT_SUPPORT2_NONE; - - if (fs->Format == DXGI_FORMAT_A8_UNORM) { - if (optimal & VK_FORMAT_FEATURE_SAMPLED_IMAGE_BIT) { - fs->Support1 = D3D12_FORMAT_SUPPORT1_TEXTURE2D | D3D12_FORMAT_SUPPORT1_TEXTURECUBE | - D3D12_FORMAT_SUPPORT1_SHADER_LOAD; - if (optimal & VK_FORMAT_FEATURE_SAMPLED_IMAGE_FILTER_LINEAR_BIT) - fs->Support1 |= D3D12_FORMAT_SUPPORT1_SHADER_SAMPLE | D3D12_FORMAT_SUPPORT1_SHADER_GATHER; - VkImageFormatProperties limits{}; - const VkImageUsageFlags usage = VK_IMAGE_USAGE_SAMPLED_BIT | VK_IMAGE_USAGE_TRANSFER_SRC_BIT | - VK_IMAGE_USAGE_TRANSFER_DST_BIT; - if (state_.image_format_properties && - state_.image_format_properties(state_.info.physical, vk_fmt, VK_IMAGE_TYPE_2D, - VK_IMAGE_TILING_OPTIMAL, usage, 0, &limits) == VK_SUCCESS && - limits.maxMipLevels > 1) - fs->Support1 |= D3D12_FORMAT_SUPPORT1_MIP; - } - return d3d12_trace::result(method, S_OK); - } - - // D3D12 disallows typed buffer views for the RGBA8 and BGRA8 sRGB formats (including BGRX8). - // Vulkan can still advertise buffer features for their backing formats. - if (buffer != 0 && vk_fmt != VK_FORMAT_R8G8B8A8_SRGB && vk_fmt != VK_FORMAT_B8G8R8A8_SRGB) - s1 |= D3D12_FORMAT_SUPPORT1_BUFFER; - // Only what CreateGraphicsPipelineState's input layouts accept (vertex_format): R8/R16 SNORM and SINT - // have Vulkan vertex support but no input-layout mapping yet. - VkFormat vertex_vk = VK_FORMAT_UNDEFINED; - UINT vertex_bytes = 0; - if ((buffer & VK_FORMAT_FEATURE_VERTEX_BUFFER_BIT) && vertex_format(fs->Format, vertex_vk, vertex_bytes)) - s1 |= D3D12_FORMAT_SUPPORT1_IA_VERTEX_BUFFER; - if (fs->Format == DXGI_FORMAT_R16_UINT || fs->Format == DXGI_FORMAT_R32_UINT) - s1 |= D3D12_FORMAT_SUPPORT1_IA_INDEX_BUFFER; - - if (optimal & VK_FORMAT_FEATURE_SAMPLED_IMAGE_BIT) { - s1 |= D3D12_FORMAT_SUPPORT1_TEXTURE1D | D3D12_FORMAT_SUPPORT1_TEXTURE2D | - D3D12_FORMAT_SUPPORT1_TEXTURE3D | D3D12_FORMAT_SUPPORT1_TEXTURECUBE | - D3D12_FORMAT_SUPPORT1_SHADER_LOAD; - } - if (buffer & VK_FORMAT_FEATURE_UNIFORM_TEXEL_BUFFER_BIT) { - s1 |= D3D12_FORMAT_SUPPORT1_SHADER_LOAD; - } - if (optimal & VK_FORMAT_FEATURE_SAMPLED_IMAGE_FILTER_LINEAR_BIT) { - s1 |= D3D12_FORMAT_SUPPORT1_SHADER_SAMPLE; - } - if (optimal & VK_FORMAT_FEATURE_COLOR_ATTACHMENT_BIT) { - s1 |= D3D12_FORMAT_SUPPORT1_RENDER_TARGET; - // A D3D12 multisample resolve needs the same image usages as texture_create_info(): colour - // attachment plus transfer source/destination (and the ordinary sampled usage). - VkImageFormatProperties image_properties{}; - const VkImageUsageFlags usage = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | VK_IMAGE_USAGE_TRANSFER_SRC_BIT | - VK_IMAGE_USAGE_TRANSFER_DST_BIT | VK_IMAGE_USAGE_SAMPLED_BIT; - const VkImageCreateFlags flags = fmt.typeless ? VK_IMAGE_CREATE_MUTABLE_FORMAT_BIT : 0; - if (state_.image_format_properties && - state_.image_format_properties(state_.info.physical, vk_fmt, VK_IMAGE_TYPE_2D, - VK_IMAGE_TILING_OPTIMAL, usage, flags, &image_properties) == VK_SUCCESS && - (image_properties.sampleCounts & d3d12_multisample_sample_counts)) { - s1 |= D3D12_FORMAT_SUPPORT1_MULTISAMPLE_RENDERTARGET | - D3D12_FORMAT_SUPPORT1_MULTISAMPLE_RESOLVE; - if ((optimal & VK_FORMAT_FEATURE_SAMPLED_IMAGE_BIT) && !fmt.typeless && - fmt.aspects == VK_IMAGE_ASPECT_COLOR_BIT && leonida::gfx10::format_from_vulkan(vk_fmt) && - state_.bindless && state_.bindless->supports_ms_class(DeviceState::numeric_class(vk_fmt))) - s1 |= D3D12_FORMAT_SUPPORT1_MULTISAMPLE_LOAD; - } - } - if (optimal & VK_FORMAT_FEATURE_COLOR_ATTACHMENT_BLEND_BIT) { - s1 |= D3D12_FORMAT_SUPPORT1_BLENDABLE; - } - if (optimal & VK_FORMAT_FEATURE_DEPTH_STENCIL_ATTACHMENT_BIT) { - s1 |= D3D12_FORMAT_SUPPORT1_DEPTH_STENCIL; - } - // B8G8R8X8 has no typed UAV in D3D12 (texture_format refuses it), whatever the BGRA8 image could do. - if (!alpha_unused(fs->Format) && ((optimal & VK_FORMAT_FEATURE_STORAGE_IMAGE_BIT) || - (buffer & VK_FORMAT_FEATURE_STORAGE_TEXEL_BUFFER_BIT))) { - s1 |= D3D12_FORMAT_SUPPORT1_TYPED_UNORDERED_ACCESS_VIEW; - // A typed UAV texture read is not a storage-image read: the translator reads it through the - // texture's sampled binding with the T#'s numeric type (rdna2spirv.py image_read_typed), so a - // format that can be stored can be read. Typed buffer UAVs share the store side's limits: the layer - // creates no buffer UAV views yet, and rdna2spirv.py FORMATS decodes only some buffer formats. - s2 |= D3D12_FORMAT_SUPPORT2_UAV_TYPED_STORE | D3D12_FORMAT_SUPPORT2_UAV_TYPED_LOAD; - // Image atomics go through the r32ui storage view, which an R32_UINT UAV view gets - // (StorageViews::r32ui). Today that is 2D UAVs only: the translator's image atomics cover 2D and 3D, - // the bindless set has r32ui slots for those two, and the layer creates no 3D UAV views yet. There - // is no image_atomic_swap, so no exchange. - if (vk_fmt == VK_FORMAT_R32_UINT && (optimal & VK_FORMAT_FEATURE_STORAGE_IMAGE_ATOMIC_BIT)) { - s2 |= D3D12_FORMAT_SUPPORT2_UAV_ATOMIC_ADD | D3D12_FORMAT_SUPPORT2_UAV_ATOMIC_BITWISE_OPS | - D3D12_FORMAT_SUPPORT2_UAV_ATOMIC_COMPARE_STORE_OR_COMPARE_EXCHANGE | - D3D12_FORMAT_SUPPORT2_UAV_ATOMIC_SIGNED_MIN_OR_MAX | - D3D12_FORMAT_SUPPORT2_UAV_ATOMIC_UNSIGNED_MIN_OR_MAX; - } - } - { - // D3D12's per-format rules, as native D3D12 reports them (RX 9070 XT, AMD 26.11.2, and WARP): - // the Vulkan feature bits above say what the image can do, not what D3D12 lets the format do. - const Format& chosen = fmt.format != VK_FORMAT_UNDEFINED ? fmt : depth_fmt; - const bool depth = (chosen.aspects & (VK_IMAGE_ASPECT_DEPTH_BIT | VK_IMAGE_ASPECT_STENCIL_BIT)) != 0; - const bool block_compressed = vk_fmt >= VK_FORMAT_BC1_RGB_UNORM_BLOCK && vk_fmt <= VK_FORMAT_BC7_SRGB_BLOCK; - // Gathers read the sampled view like a sample does (OpImageGather); the host reports one with the other. - if (s1 & D3D12_FORMAT_SUPPORT1_SHADER_SAMPLE) s1 |= D3D12_FORMAT_SUPPORT1_SHADER_GATHER; - // Comparison sampling and gathers (SampleCmp, GatherCmp with a comparison sampler) are D3D12's for the - // depth-plane view formats only; R32_FLOAT and R16_UNORM are the views of D32 and D16 textures. - if ((s1 & D3D12_FORMAT_SUPPORT1_SHADER_SAMPLE) && - (fs->Format == DXGI_FORMAT_R32_FLOAT || fs->Format == DXGI_FORMAT_R16_UNORM)) - s1 |= D3D12_FORMAT_SUPPORT1_SHADER_SAMPLE_COMPARISON | D3D12_FORMAT_SUPPORT1_SHADER_GATHER_COMPARISON; - // A mip chain where the image can have one (asked with its sampled or depth-stencil usage). - if (s1 & (D3D12_FORMAT_SUPPORT1_TEXTURE1D | D3D12_FORMAT_SUPPORT1_TEXTURE2D | - D3D12_FORMAT_SUPPORT1_TEXTURE3D | D3D12_FORMAT_SUPPORT1_TEXTURECUBE | - D3D12_FORMAT_SUPPORT1_DEPTH_STENCIL)) { - const VkImageUsageFlags usage = depth ? VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT - : VK_IMAGE_USAGE_SAMPLED_BIT; - VkImageFormatProperties limits{}; - if (state_.image_format_properties && - state_.image_format_properties(state_.info.physical, vk_fmt, VK_IMAGE_TYPE_2D, - VK_IMAGE_TILING_OPTIMAL, usage, - chosen.typeless ? VK_IMAGE_CREATE_MUTABLE_FORMAT_BIT : 0, - &limits) == VK_SUCCESS && - limits.maxMipLevels > 1) - s1 |= D3D12_FORMAT_SUPPORT1_MIP; - // Depth formats multisample as depth-stencil targets; the colour-attachment check above never - // sees them. Same usages as MULTISAMPLE_QUALITY_LEVELS and resource creation ask for. - if (depth && !chosen.typeless && (s1 & D3D12_FORMAT_SUPPORT1_DEPTH_STENCIL) && - state_.image_format_properties && - state_.image_format_properties(state_.info.physical, vk_fmt, VK_IMAGE_TYPE_2D, - VK_IMAGE_TILING_OPTIMAL, - VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT | - VK_IMAGE_USAGE_TRANSFER_SRC_BIT | - VK_IMAGE_USAGE_TRANSFER_DST_BIT | VK_IMAGE_USAGE_SAMPLED_BIT, - 0, &limits) == VK_SUCCESS && - (limits.sampleCounts & d3d12_multisample_sample_counts)) - s1 |= D3D12_FORMAT_SUPPORT1_MULTISAMPLE_RENDERTARGET; - } - // No resolve of integer formats (ResolveSubresource takes float, UNORM and SNORM only). - if (DeviceState::numeric_class(vk_fmt) != 0) s1 &= ~D3D12_FORMAT_SUPPORT1_MULTISAMPLE_RESOLVE; - // Block-compressed textures are 2D, 3D or cubes: 1D has no 4x4 blocks. - if (block_compressed) s1 &= ~D3D12_FORMAT_SUPPORT1_TEXTURE1D; - // Depth formats are 2D and cube resources whose shaders read and write them through a colour view - // (R32_FLOAT, R24_UNORM_X8_TYPELESS, ...): not 3D, not shader resources or UAVs themselves (NVIDIA - // gives D32_SFLOAT and D16_UNORM STORAGE_IMAGE). Native D3D12 also allows 1D, but the layer refuses - // 1D depth-stencil resources (CreateCommittedResource). - if (depth) { - s1 &= ~(D3D12_FORMAT_SUPPORT1_TEXTURE1D | D3D12_FORMAT_SUPPORT1_TEXTURE3D | D3D12_FORMAT_SUPPORT1_SHADER_LOAD | - D3D12_FORMAT_SUPPORT1_SHADER_SAMPLE | D3D12_FORMAT_SUPPORT1_SHADER_GATHER | - D3D12_FORMAT_SUPPORT1_BUFFER | D3D12_FORMAT_SUPPORT1_IA_VERTEX_BUFFER | - D3D12_FORMAT_SUPPORT1_TYPED_UNORDERED_ACCESS_VIEW); - s2 = D3D12_FORMAT_SUPPORT2_NONE; - } - // A TYPELESS format is only storage: views give it a type, so it is a texture with mips and - // nothing a view would do (no buffer, shader, render-target or UAV use of its own). - if (chosen.typeless) { - s1 &= D3D12_FORMAT_SUPPORT1_TEXTURE1D | D3D12_FORMAT_SUPPORT1_TEXTURE2D | - D3D12_FORMAT_SUPPORT1_TEXTURE3D | D3D12_FORMAT_SUPPORT1_TEXTURECUBE | - D3D12_FORMAT_SUPPORT1_MIP; - s2 = D3D12_FORMAT_SUPPORT2_NONE; - } - } - if (fs->Format == DXGI_FORMAT_R9G9B9E5_SHAREDEXP && state_.r9g9b9e5_uav_emulated) { - s1 |= D3D12_FORMAT_SUPPORT1_TYPED_UNORDERED_ACCESS_VIEW; - // Reads go through the sampled E5B9G9R9 view, like every typed UAV read (see above). - s2 |= D3D12_FORMAT_SUPPORT2_UAV_TYPED_STORE | D3D12_FORMAT_SUPPORT2_UAV_TYPED_LOAD; - } - if (fs->Format == DXGI_FORMAT_R9G9B9E5_SHAREDEXP) { - // Keep the native attachment and resolve bits. Blending and shader multisample loads remain masked. - s1 &= ~(D3D12_FORMAT_SUPPORT1_BLENDABLE | D3D12_FORMAT_SUPPORT1_DEPTH_STENCIL | - D3D12_FORMAT_SUPPORT1_MULTISAMPLE_LOAD); - } - fs->Support1 = s1; - fs->Support2 = s2; - return d3d12_trace::result(method, S_OK); - } - case D3D12_FEATURE_MULTISAMPLE_QUALITY_LEVELS: { - if (size != sizeof(D3D12_FEATURE_DATA_MULTISAMPLE_QUALITY_LEVELS)) return d3d12_trace::result(method, E_INVALIDARG); - auto* levels = static_cast(data); - // RTX 5070 / 621.14/621.24: a format outside the runtime's table (and R1_UNORM) fails with the caller's - // output untouched; a known format clears it before the sample count is checked. - const UINT format_id = UINT(levels->Format); - if (levels->Format == DXGI_FORMAT_R1_UNORM || - !(format_id <= DXGI_FORMAT_B4G4R4A4_UNORM || - (format_id >= DXGI_FORMAT_SAMPLER_FEEDBACK_MIN_MIP_OPAQUE && - format_id <= DXGI_FORMAT_A4B4G4R4_UNORM))) - return d3d12_trace::result(method, E_FAIL); - levels->NumQualityLevels = 0; - // TILED_RESOURCE asks about tiled (reserved, 64KB_UNDEFINED_SWIZZLE) textures. Measured natively on an - // RX 7800 XT, a Radeon iGPU and WARP: 1x and 4x keep the plain answer, every other count has none, and a - // format without a tile shape (96-bit) has none at any count. That is GetResourceAllocationInfo's rule - // here (tiled MSAA is 4x only). 128-bit formats at 4x: the AMD drivers answer 0, WARP and the RTX 5070 Ti - // allocate them; this follows the latter, as the allocation path does. - // RTX 5070 / 621.14: undefined flag bits are ignored; bad counts fail, known formats have 1x. - const bool tiled = (levels->Flags & D3D12_MULTISAMPLE_QUALITY_LEVELS_FLAG_TILED_RESOURCE) != 0; - if (levels->SampleCount == 0 || levels->SampleCount > D3D12_MAX_MULTISAMPLE_SAMPLE_COUNT) - return d3d12_trace::result(method, E_FAIL); - Format format = texture_storage_format(levels->Format, false); - if (levels->SampleCount == 1) { - levels->NumQualityLevels = tiled && format.rgb96 ? 0 : 1; - return d3d12_trace::result(method, S_OK); - } - if ((levels->SampleCount & (levels->SampleCount - 1)) != 0) - return d3d12_trace::result(method, S_OK); - const bool alpha_only = levels->Format == DXGI_FORMAT_A8_UNORM; - if (alpha_only && levels->SampleCount != 1) return d3d12_trace::result(method, S_OK); - if (levels->Format == DXGI_FORMAT_R10G10B10_XR_BIAS_A2_UNORM && levels->SampleCount != 1) - return d3d12_trace::result(method, S_OK); // single-sample 2D only; no quality levels - if (format.aspects & VK_IMAGE_ASPECT_DEPTH_BIT) { - D3D12_RESOURCE_DESC depth_desc{}; - depth_desc.Format = levels->Format; - depth_desc.Flags = D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL; - format = state_.texture_format(depth_desc); // includes the D24-to-D32 fallback used by creation - } - if (format.format == VK_FORMAT_UNDEFINED || !state_.image_format_properties) - return d3d12_trace::result(method, S_OK); - if (format.rgb96) return d3d12_trace::result(method, S_OK); // no 96-bit render targets yet - - // Vulkan exposes one standard sample pattern per supported count, so each supported count maps to - // one D3D12 quality level (quality index 0). Query the matching colour or depth/stencil attachment - // usage, plus the transfer and sampled usages used by the resource implementation. - VkImageUsageFlags usage = VK_IMAGE_USAGE_TRANSFER_SRC_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT | - VK_IMAGE_USAGE_SAMPLED_BIT; - if (format.aspects & VK_IMAGE_ASPECT_COLOR_BIT) { - if (!alpha_only) usage |= VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT; - } else if (format.aspects & VK_IMAGE_ASPECT_DEPTH_BIT) - usage |= VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT; - else - return d3d12_trace::result(method, DXGI_ERROR_UNSUPPORTED); - const VkImageCreateFlags flags = format.typeless ? VK_IMAGE_CREATE_MUTABLE_FORMAT_BIT : 0; - VkImageFormatProperties image_properties{}; - const VkResult result = state_.image_format_properties(state_.info.physical, format.format, - VK_IMAGE_TYPE_2D, VK_IMAGE_TILING_OPTIMAL, - usage, flags, &image_properties); - const VkSampleCountFlagBits samples = VkSampleCountFlagBits(levels->SampleCount); - if (result == VK_SUCCESS && (image_properties.sampleCounts & samples)) - levels->NumQualityLevels = 1; - if (tiled && levels->SampleCount != 1 && levels->SampleCount != 4) levels->NumQualityLevels = 0; - return d3d12_trace::result(method, S_OK); - } - case D3D12_FEATURE_SHADER_MODEL: { - if (size != sizeof(D3D12_FEATURE_DATA_SHADER_MODEL)) return E_INVALIDARG; - auto* model = static_cast(data); - // Measured against the host PC runtime: a request above the supported model is clamped down to it, 5.1 - // is echoed because it is D3D12's own baseline (WARP and the RTX 5070 both answer it with S_OK), and a - // value below it is refused with E_INVALIDARG (0x5f crashed the host, so the test does not probe it). - // Refuse the same way instead of echoing an unrepresentable value back: below 5.1, and between 5.1 and - // 6.0, where no runtime defines a model (0x52-0x5f; E_INVALIDARG on the host runtime of an RTX 5070). - const UINT requested = static_cast(model->HighestShaderModel); - if (requested < D3D_SHADER_MODEL_5_1 || - (requested > D3D_SHADER_MODEL_5_1 && requested < D3D_SHADER_MODEL_6_0)) - return E_INVALIDARG; - if (model->HighestShaderModel > kHighestShaderModel) model->HighestShaderModel = kHighestShaderModel; - return S_OK; - } - case D3D12_FEATURE_ROOT_SIGNATURE: { - if (size != sizeof(D3D12_FEATURE_DATA_ROOT_SIGNATURE)) return E_INVALIDARG; - auto* root = static_cast(data); - // 1.0 to 1.2 are defined (1.2 by number: not every SDK names it). The host refuses anything else and leaves - // the value alone (RTX 4070 Laptop 621.24 and WARP), so only 1.2 is clamped. - const UINT requested = static_cast(root->HighestVersion); - if (requested < static_cast(D3D_ROOT_SIGNATURE_VERSION_1_0) || requested > 0x3) return E_INVALIDARG; - if (root->HighestVersion > kHighestRootSignatureVersion) - root->HighestVersion = kHighestRootSignatureVersion; - return S_OK; - } - case D3D12_FEATURE_PROTECTED_RESOURCE_SESSION_SUPPORT: { - if (size != sizeof(D3D12_FEATURE_DATA_PROTECTED_RESOURCE_SESSION_SUPPORT)) - return d3d12_trace::result(method, E_INVALIDARG); - auto* prot = static_cast(data); - prot->Support = D3D12_PROTECTED_RESOURCE_SESSION_SUPPORT_FLAG_NONE; - if (prot->NodeIndex != 0) return d3d12_trace::result(method, E_INVALIDARG); - return d3d12_trace::result(method, S_OK); - } - case D3D12_FEATURE_PROTECTED_RESOURCE_SESSION_TYPE_COUNT: { - if (size != sizeof(D3D12_FEATURE_DATA_PROTECTED_RESOURCE_SESSION_TYPE_COUNT)) - return d3d12_trace::result(method, E_INVALIDARG); - auto* prot_count = static_cast(data); - if (prot_count->NodeIndex != 0) return d3d12_trace::result(method, E_INVALIDARG); - prot_count->Count = 0; - return d3d12_trace::result(method, S_OK); - } - case D3D12_FEATURE_PROTECTED_RESOURCE_SESSION_TYPES: { - if (size != sizeof(D3D12_FEATURE_DATA_PROTECTED_RESOURCE_SESSION_TYPES)) - return d3d12_trace::result(method, E_INVALIDARG); - const auto* prot_types = static_cast(data); - // Zero protected resource session types exist, so only Count == 0 on node 0 matches TYPE_COUNT. - if (prot_types->NodeIndex != 0 || prot_types->Count != 0) - return d3d12_trace::result(method, E_INVALIDARG); - return d3d12_trace::result(method, S_OK); - } - case D3D12_FEATURE_SHADER_CACHE: { - if (size != sizeof(D3D12_FEATURE_DATA_SHADER_CACHE)) return d3d12_trace::result(method, E_INVALIDARG); - static_cast(data)->SupportFlags = D3D12_SHADER_CACHE_SUPPORT_NONE; - return d3d12_trace::result(method, S_OK); - } - case D3D12_FEATURE_COMMAND_QUEUE_PRIORITY: { - if (size != sizeof(D3D12_FEATURE_DATA_COMMAND_QUEUE_PRIORITY)) - return d3d12_trace::result(method, E_INVALIDARG); - auto* prio = static_cast(data); - prio->PriorityForTypeIsSupported = FALSE; - if (UINT(prio->CommandListType) > D3D12_COMMAND_LIST_TYPE_VIDEO_ENCODE || - (prio->Priority != D3D12_COMMAND_QUEUE_PRIORITY_NORMAL && - prio->Priority != D3D12_COMMAND_QUEUE_PRIORITY_HIGH && - prio->Priority != D3D12_COMMAND_QUEUE_PRIORITY_GLOBAL_REALTIME)) - return d3d12_trace::result(method, E_INVALIDARG); - // DIRECT/COMPUTE/COPY report NORMAL only: all VkQueues share priority 1.0f (HIGH has no distinct scheduling) - // and GLOBAL_REALTIME is refused in CreateCommandQueue. - const bool supported_type = prio->CommandListType == D3D12_COMMAND_LIST_TYPE_DIRECT || - prio->CommandListType == D3D12_COMMAND_LIST_TYPE_COMPUTE || - prio->CommandListType == D3D12_COMMAND_LIST_TYPE_COPY; - const bool supported_priority = prio->Priority == D3D12_COMMAND_QUEUE_PRIORITY_NORMAL; - prio->PriorityForTypeIsSupported = (supported_type && supported_priority) ? TRUE : FALSE; - return d3d12_trace::result(method, S_OK); - } - case D3D12_FEATURE_EXISTING_HEAPS: - return write_supported_feature( - method, data, size, state_.get_host_pointer_properties ? TRUE : FALSE); - case D3D12_FEATURE_SERIALIZATION: { - if (size != sizeof(D3D12_FEATURE_DATA_SERIALIZATION)) return d3d12_trace::result(method, E_INVALIDARG); - auto* ser = static_cast(data); - ser->HeapSerializationTier = D3D12_HEAP_SERIALIZATION_TIER_0; - if (ser->NodeIndex != 0) return d3d12_trace::result(method, E_INVALIDARG); - return d3d12_trace::result(method, S_OK); - } - case D3D12_FEATURE_CROSS_NODE: { - if (size != sizeof(D3D12_FEATURE_DATA_CROSS_NODE)) return d3d12_trace::result(method, E_INVALIDARG); - auto* cross = static_cast(data); - cross->SharingTier = D3D12_CROSS_NODE_SHARING_TIER_NOT_SUPPORTED; - cross->AtomicShaderInstructions = FALSE; - return d3d12_trace::result(method, S_OK); - } - case D3D12_FEATURE_DISPLAYABLE: { - if (size != sizeof(D3D12_FEATURE_DATA_DISPLAYABLE)) return d3d12_trace::result(method, E_INVALIDARG); - auto* disp = static_cast(data); - disp->DisplayableTexture = FALSE; - disp->SharedResourceCompatibilityTier = D3D12_SHARED_RESOURCE_COMPATIBILITY_TIER_0; - return d3d12_trace::result(method, S_OK); - } - case D3D12_FEATURE_QUERY_META_COMMAND: - // EnumerateMetaCommands reports 0 meta-commands, so any query is rejected (as on host D3D12). - return d3d12_trace::result(method, E_INVALIDARG); - case compat::kFeaturePredication: - return write_supported_feature( - method, data, size, state_.info.conditional_rendering ? TRUE : FALSE); - case compat::kFeatureApplicationSpecificDriverState: - return write_supported_feature(method, data, size, FALSE); - case compat::kFeatureBytecodeBypassHashSupported: - return write_supported_feature(method, data, size, FALSE); - default: - // Not answered yet. The log above lists every query; answers are added as the trace asks for them. - return d3d12_trace::result(method, E_INVALIDARG); - } - } - -private: - IUnknown* identity() { return outer_ ? outer_ : static_cast(this); } - - static constexpr D3D12_RESOURCE_ALLOCATION_INFO kInvalidAllocation{UINT64_MAX, - D3D12_DEFAULT_RESOURCE_PLACEMENT_ALIGNMENT}; - // Saturates at the last multiple of `to` instead of wrapping, as the PC runtime's totals do. - static UINT64 align_up(UINT64 value, UINT64 to) { - return value > UINT64_MAX - (to - 1) ? UINT64_MAX / to * to : (value + to - 1) / to * to; - } - - // Lays `count` resources out one after another; `each` (optional) gets every resource's offset, size and - // alignment. As on the PC runtime, the total is rounded up to the largest alignment (1 for no resources) and - // saturates near 2^64 rather than wrapping. - template - D3D12_RESOURCE_ALLOCATION_INFO place(UINT count, const Desc* descs, Get get, - D3D12_RESOURCE_ALLOCATION_INFO1* each) { - D3D12_RESOURCE_ALLOCATION_INFO total{0, 1}; - bool failed = count && !descs; - for (UINT i = 0; i < count; ++i) { - const D3D12_RESOURCE_ALLOCATION_INFO one = failed ? kInvalidAllocation : allocation(get(i)); - failed = failed || one.SizeInBytes == UINT64_MAX; - if (failed) { - if (each) each[i] = {UINT64_MAX, one.Alignment, UINT64_MAX}; - continue; - } - const UINT64 offset = align_up(total.SizeInBytes, one.Alignment); - if (each) each[i] = {offset, one.Alignment, one.SizeInBytes}; - total = {one.SizeInBytes > UINT64_MAX - offset ? UINT64_MAX : offset + one.SizeInBytes, - std::max(total.Alignment, one.Alignment)}; - } - return failed ? kInvalidAllocation - : D3D12_RESOURCE_ALLOCATION_INFO{align_up(total.SizeInBytes, total.Alignment), total.Alignment}; - } - - // One resource's size and alignment, or kInvalidAllocation for a description D3D12 (or this device) rejects. - D3D12_RESOURCE_ALLOCATION_INFO allocation(const D3D12_RESOURCE_DESC& desc) const { - constexpr UINT64 align_4k = D3D12_SMALL_RESOURCE_PLACEMENT_ALIGNMENT, - align_64k = D3D12_DEFAULT_RESOURCE_PLACEMENT_ALIGNMENT, - align_msaa_64k = D3D12_SMALL_MSAA_RESOURCE_PLACEMENT_ALIGNMENT, - align_msaa_4m = D3D12_DEFAULT_MSAA_RESOURCE_PLACEMENT_ALIGNMENT; - constexpr D3D12_RESOURCE_FLAGS attachment = - D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET | D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL; - if (desc.Dimension == D3D12_RESOURCE_DIMENSION_BUFFER) { - // Host D3D12 accepts ALLOW_RENDER_TARGET, ALLOW_CROSS_ADAPTER, UAV, DENY_SHADER_RESOURCE, - // RAYTRACING_ACCELERATION_STRUCTURE and 0x400 on buffers; refuses ALLOW_DEPTH_STENCIL, - // ALLOW_SIMULTANEOUS_ACCESS, VIDEO_DECODE_REFERENCE_ONLY and other flags (D3D-467). - constexpr UINT buffer_flags = D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET | - D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS | - D3D12_RESOURCE_FLAG_DENY_SHADER_RESOURCE | - D3D12_RESOURCE_FLAG_ALLOW_CROSS_ADAPTER | - D3D12_RESOURCE_FLAG_RAYTRACING_ACCELERATION_STRUCTURE | 0x400; - if (!desc.Width || desc.Width > UINT64_MAX - align_64k || desc.Height != 1 || desc.DepthOrArraySize != 1 || - desc.MipLevels != 1 || desc.Format != DXGI_FORMAT_UNKNOWN || desc.SampleDesc.Count != 1 || - desc.SampleDesc.Quality != 0 || desc.Layout != D3D12_TEXTURE_LAYOUT_ROW_MAJOR || - (desc.Alignment && desc.Alignment != align_64k) || (UINT(desc.Flags) & ~buffer_flags)) - return kInvalidAllocation; - return {align_up(desc.Width, align_64k), align_64k}; - } - const bool volume = desc.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE3D; - const bool one_d = desc.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE1D; - if (!volume && !one_d && desc.Dimension != D3D12_RESOURCE_DIMENSION_TEXTURE2D) { - if (desc.Dimension != D3D12_RESOURCE_DIMENSION_UNKNOWN) - log_once("GetResourceAllocationInfo dimension not supported:", desc.Dimension); - return kInvalidAllocation; - } - if (one_d && desc.Height != 1) return kInvalidAllocation; - const UINT samples = desc.SampleDesc.Count, depth = volume ? desc.DepthOrArraySize : 1; - const UINT64 max_extent = - volume ? D3D12_REQ_TEXTURE3D_U_V_OR_W_DIMENSION : D3D12_REQ_TEXTURE2D_U_OR_V_DIMENSION; - const UINT max_layers = - volume ? D3D12_REQ_TEXTURE3D_U_V_OR_W_DIMENSION : D3D12_REQ_TEXTURE2D_ARRAY_AXIS_DIMENSION; - if (!desc.Width || !desc.Height || !desc.DepthOrArraySize || desc.Width > max_extent || - desc.Height > max_extent || desc.DepthOrArraySize > max_layers || !samples || samples > D3D12_MAX_MULTISAMPLE_SAMPLE_COUNT || - (samples & (samples - 1)) || (samples > 1 && desc.SampleDesc.Quality != 0) || - desc.Layout == D3D12_TEXTURE_LAYOUT_ROW_MAJOR) - return kInvalidAllocation; - const UINT16 full = full_mips(desc.Width, desc.Height, depth); - D3D12_RESOURCE_DESC resolved = desc; - if (!resolved.MipLevels) resolved.MipLevels = full; - if (resolved.MipLevels > full) return kInvalidAllocation; - const bool depth_stencil = desc.Flags & D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL; - if ((desc.Flags & D3D12_RESOURCE_FLAG_DENY_SHADER_RESOURCE) && !depth_stencil) - return kInvalidAllocation; - if (samples > 1 && (volume || one_d || resolved.MipLevels != 1 || !(desc.Flags & attachment) || - (desc.Flags & attachment) == attachment || - (desc.Flags & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS))) - return kInvalidAllocation; - // The PC runtime: simultaneous access only single-sampled and without depth-stencil, and no volume depth. - if (((desc.Flags & D3D12_RESOURCE_FLAG_ALLOW_SIMULTANEOUS_ACCESS) && (depth_stencil || samples > 1)) || - (volume && depth_stencil)) - return kInvalidAllocation; - const bool tiled = is_tiled_layout(desc.Layout); - if (tiled) { - if (one_d || (samples > 1 && samples != 4)) return kInvalidAllocation; - if (desc.Alignment && desc.Alignment != align_64k) return kInvalidAllocation; - } else if (desc.Layout != D3D12_TEXTURE_LAYOUT_UNKNOWN) { - log_once("GetResourceAllocationInfo layout as UNKNOWN:", desc.Layout); - } - - const Format format = state_.texture_format(desc); - if (!format.format) { - log_once("GetResourceAllocationInfo format not supported yet:", desc.Format); - return kInvalidAllocation; - } - VkMemoryRequirements need{}; - const TextureCreateInfo create(resolved, format, state_.color_attachment_usable(format.format)); - if (!state_.memory_requirements(create.info, need)) return kInvalidAllocation; - if (tiled) { - leonida::ResourceTiling tiling; - if (!resource_tiling(resolved, tiling)) return kInvalidAllocation; - return {UINT64(tiling.total_tiles) * leonida::tile_size_in_bytes, align_64k}; - } - - // D3D12's alignment: 64 KiB, or 4 MiB with MSAA, unless the description asks for a small one (4 KiB, 64 KiB - // with MSAA). 4 KiB needs the top mip of one array slice to fit in 16 tiles of 4 KiB and the resource not to - // be a render target or depth buffer; mips and array slices don't count. If it doesn't qualify, the PC - // runtime calls the description invalid rather than answering with 64 KiB. The MSAA 64 KiB alignment has no - // size limit there. Both measured in d3d12_vulkan_device_test. - UINT64 alignment = 0; - if (samples > 1) { - if (desc.Alignment && desc.Alignment != align_msaa_64k && desc.Alignment != align_msaa_4m) - return kInvalidAllocation; - alignment = desc.Alignment ? desc.Alignment : align_msaa_4m; - } else { - if (desc.Alignment && desc.Alignment != align_4k && desc.Alignment != align_64k) return kInvalidAllocation; - if (desc.Alignment == align_4k && ((desc.Flags & attachment) || !small_tiles_fit(desc, format, need.size))) - return kInvalidAllocation; - alignment = desc.Alignment ? desc.Alignment : align_64k; - } - return {align_up(need.size, alignment), alignment}; - } - - // Whether 16 tiles of 4 KiB (leonida::small_tile_shape; 4096 bytes of a row for 1D) cover the top mip of one - // array slice, the PC runtime's test for D3D12_SMALL_RESOURCE_PLACEMENT_ALIGNMENT. - static bool small_tiles_fit(const D3D12_RESOURCE_DESC& desc, const Format& format, VkDeviceSize vulkan_size) { - const leonida::BlockFormat block = leonida::block_format(format.format, VK_IMAGE_ASPECT_COLOR_BIT); - const bool volume = desc.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE3D; - leonida::TileShape shape = leonida::small_tile_shape(volume, block.bytes); - if (desc.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE1D && shape.width) shape = {4096 / block.bytes, 1, 1}; - // shortcut: untileable element sizes (3- and 12-byte formats) keep the whole-resource 64 KiB test; measure - // them on the PC runtime if a game asks for one. - if (!shape.width) return vulkan_size <= D3D12_DEFAULT_RESOURCE_PLACEMENT_ALIGNMENT; - const auto tiles = [](UINT64 texels, UINT64 per_block, UINT64 per_tile) { - return ((texels + per_block - 1) / per_block + per_tile - 1) / per_tile; - }; - return tiles(desc.Width, block.block, shape.width) * tiles(desc.Height, block.block, shape.height) * - tiles(volume ? desc.DepthOrArraySize : 1, 1, shape.depth) <= 16; - } - - // Strict lower bound on the heap bytes a non-tiled single-sample texture needs: sums uncompressed texel/block - // payload across subresources and rounds to `alignment`, capped at `fallback` (Vulkan allocation size). Avoids - // rejecting host-valid placed textures when Vulkan driver padding exceeds D3D12's GetResourceAllocationInfo. - static UINT64 min_placed_texture_bytes(const D3D12_RESOURCE_DESC& desc, const Format& format, UINT64 alignment, - UINT64 fallback) { - const VkImageAspectFlags aspect = - (format.aspects & VK_IMAGE_ASPECT_DEPTH_BIT) ? VK_IMAGE_ASPECT_DEPTH_BIT : format.aspects; - const leonida::BlockFormat block = footprint_block(format, aspect); - if (!block.bytes || !alignment) return fallback; - const bool volume = desc.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE3D; - const bool one_d = desc.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE1D; - const UINT depth = volume ? desc.DepthOrArraySize : 1; - const UINT slices = volume ? 1 : desc.DepthOrArraySize; - const UINT mips = desc.MipLevels ? desc.MipLevels : full_mips(desc.Width, desc.Height, depth); - UINT64 per_slice = 0; - for (UINT m = 0; m < mips; ++m) { - const UINT64 w = std::max(1, desc.Width >> m); - const UINT64 h = one_d ? 1 : std::max(1, desc.Height >> m); - const UINT64 d = volume ? std::max(1, depth >> m) : 1; - const UINT64 bw = (w + block.block - 1) / block.block; - const UINT64 bh = (h + block.block - 1) / block.block; - if (bw > UINT64_MAX / bh) return fallback; - const UINT64 blocks = bw * bh; - if (blocks > UINT64_MAX / d) return fallback; - const UINT64 count = blocks * d; - if (count > UINT64_MAX / block.bytes) return fallback; - const UINT64 mip_bytes = count * block.bytes; - if (per_slice > UINT64_MAX - mip_bytes) return fallback; - per_slice += mip_bytes; - } - if (slices && per_slice > UINT64_MAX / slices) return fallback; - const UINT64 total = per_slice * slices; - if (total > UINT64_MAX - (alignment - 1)) return fallback; - return std::min(fallback, align_up(total, alignment)); - } - - // Writes the view's T# into the slot and makes sure set 0 and the hash table know it. A view that cannot be - // shown leaves the slot a null descriptor. - void write_image_descriptor(const Resource& resource, const TextureView& view, - D3D12_CPU_DESCRIPTOR_HANDLE destination, bool storage) { - leonida::gfx10::Image image{}; - if (!image_descriptor(resource, view, image)) return; - const leonida::gfx10::ImageWords words = leonida::gfx10::encode(image); - const bool registered = state_.bind_image(words, image, resource.image(), resource.format(), - resource.aspects(), storage, resource.has_view_format_list(), - resource.uint_backed()); - if (registered && resource.sparse_image()) state_.context->note_shader_image(resource.id()); - if (leonida::gfx10::multisampled(image.type) && !registered) return; - std::memcpy(reinterpret_cast(destination.ptr), words.data(), sizeof(words)); - } - - // Validation shared by CreateCommittedResource and CreateCommittedResource3; internal callers pass null `method` - // to skip trace recording. - HRESULT create_committed_validated(const char* method, const D3D12_HEAP_PROPERTIES* heap, - D3D12_HEAP_FLAGS heap_flags, const D3D12_RESOURCE_DESC* desc, - D3D12_RESOURCE_STATES state, const D3D12_CLEAR_VALUE* clear, - UINT32 castable_count, const DXGI_FORMAT* castable, REFIID riid, void** out) { - const auto finish = [&](HRESULT hr) { return method ? d3d12_trace::result(method, hr) : hr; }; - if (out) *out = nullptr; - if (!heap || !desc) return finish(E_INVALIDARG); - if (const char* why = committed_resource_refusal(*heap, heap_flags, *desc, state, clear, - acceleration_structures(), state_.uma)) { - log_once((std::string(method ? method : "CreateCommittedResource") + " refused (" + why + "), dimension") - .c_str(), - int(desc->Dimension)); - return finish(E_INVALIDARG); - } - // The sample quality is checked above as the host does it here: CreateCommittedResource accepts a quality on a - // 1x texture while GetResourceAllocationInfo requires 0; the other texture checks stay shared with allocation. - D3D12_RESOURCE_DESC checked = *desc; - if (checked.Dimension != D3D12_RESOURCE_DIMENSION_BUFFER) checked.SampleDesc.Quality = 0; - if (desc->Dimension != D3D12_RESOURCE_DIMENSION_BUFFER && allocation(checked).SizeInBytes == UINT64_MAX) { - log_once((std::string(method ? method : "CreateCommittedResource") + - " refused (texture size, mips, samples or alignment), dimension") - .c_str(), - int(desc->Dimension)); - return finish(E_INVALIDARG); - } - return finish(create_committed(heap, heap_flags, desc, state, castable_count, castable, riid, out)); - } - - // Shared by CreateCommittedResource, CreateCommittedResource3 and CreateReservedResource*. A castable-format list - // is only meaningful on textures; the layer reports RelaxedFormatCastingSupported, so each format is mapped and - // handed to Vulkan as a VkImageFormatListCreateInfo. A nonzero count with a null list is no list, as on the PC - // runtime. - HRESULT create_committed(const D3D12_HEAP_PROPERTIES* heap, D3D12_HEAP_FLAGS heap_flags, - const D3D12_RESOURCE_DESC* desc, D3D12_RESOURCE_STATES initial_state, - UINT32 castable_count, const DXGI_FORMAT* castable, REFIID riid, void** out) { - if (out) *out = nullptr; - if (!heap || !desc) return E_INVALIDARG; - if (castable_count && castable && desc->Dimension == D3D12_RESOURCE_DIMENSION_BUFFER) { - log_once("castable formats on a buffer are invalid; count", int(castable_count)); - return E_INVALIDARG; - } - auto* resource = new Resource(state_, *desc, *heap, heap_flags); - resource->attach_device(identity()); - HRESULT hr = E_NOTIMPL; - if (desc->Dimension == D3D12_RESOURCE_DIMENSION_BUFFER) { - hr = desc->SampleDesc.Count == 1 && desc->SampleDesc.Quality == 0 - ? resource->create_buffer(initial_state) - : E_INVALIDARG; - } else if (desc->Dimension != D3D12_RESOURCE_DIMENSION_TEXTURE1D && - desc->Dimension != D3D12_RESOURCE_DIMENSION_TEXTURE2D && - desc->Dimension != D3D12_RESOURCE_DIMENSION_TEXTURE3D) { - log_once("committed resource dimension not supported:", desc->Dimension); - } else if (desc->Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE1D && desc->Height != 1) { - log_once("1D texture height must be 1:", int(desc->Height)); - hr = E_INVALIDARG; - } else if (desc->Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE3D && - (desc->Flags & D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL)) { - log_once("volume depth-stencil resources not supported, flags:", int(desc->Flags)); - } else if (heap->Type == D3D12_HEAP_TYPE_UPLOAD || heap->Type == D3D12_HEAP_TYPE_READBACK) { - hr = E_INVALIDARG; // D3D12 places textures on default heaps unless they are row-major - } else if (const UINT samples = desc->SampleDesc.Count; - !samples || samples > D3D12_MAX_MULTISAMPLE_SAMPLE_COUNT || - (samples > 1 && desc->SampleDesc.Quality && - desc->SampleDesc.Quality != DXGI_STANDARD_MULTISAMPLE_QUALITY_PATTERN && - desc->SampleDesc.Quality != DXGI_CENTER_MULTISAMPLE_QUALITY_PATTERN) || - (samples > 1 && ((samples & (samples - 1)) || desc->MipLevels != 1 || - desc->Dimension != D3D12_RESOURCE_DIMENSION_TEXTURE2D || - !(desc->Flags & (D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET | - D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL))))) { - hr = E_INVALIDARG; // D3D12: nonzero power-of-two sample count up to 32; MSAA needs a single-mip 2D attachment - } else { - hr = S_OK; - const Format format = state_.texture_format(*desc); - if (format.format == VK_FORMAT_UNDEFINED) { - log_once("texture format not supported yet:", desc->Format); - hr = E_INVALIDARG; - } else { - std::vector cast_formats; - hr = castable_view_formats(format, castable_count, castable, cast_formats); - if (SUCCEEDED(hr)) hr = resource->create_texture(format, cast_formats); - if (SUCCEEDED(hr)) resource->keep_castable_formats(castable_count, castable); - } - } - if (FAILED(hr)) { - resource->Release(); - return hr; - } - if (!out) { // a capability check: D3D12 allows a null output - resource->Release(); - return S_FALSE; - } - return hand_out(resource, riid, out); - } - - // GetAdapterLuid's answer, and how queues read the clocks: calibrated timestamps when the caller enabled the - // extension and the GPU calibrates its DEVICE domain against QueryPerformanceCounter, else the queue family's - // timestamp queries. - void query_luid_and_clock(PFN_vkGetDeviceProcAddr get_device) { - const VulkanDeviceInfo& info = state_.info; - const auto properties2 = reinterpret_cast( - info.get_instance_proc(info.instance, "vkGetPhysicalDeviceProperties2")); - if (properties2) { - VkPhysicalDeviceIDProperties id{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_ID_PROPERTIES}; - VkPhysicalDeviceProperties2 properties{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROPERTIES_2, &id}; - properties2(info.physical, &properties); - static_assert(sizeof(LUID) == VK_LUID_SIZE); - if (id.deviceLUIDValid) std::memcpy(&state_.luid, id.deviceLUID, sizeof(LUID)); - state_.uma = properties.properties.deviceType == VK_PHYSICAL_DEVICE_TYPE_INTEGRATED_GPU; - } - if (!state_.luid.LowPart && !state_.luid.HighPart) log_once("the Vulkan driver reports no device LUID;", 0); - - state_.clock.get_device_proc = get_device; - const auto families_of = reinterpret_cast( - info.get_instance_proc(info.instance, "vkGetPhysicalDeviceQueueFamilyProperties")); - if (families_of) { - std::uint32_t count = 0; - families_of(info.physical, &count, nullptr); - std::vector families(count); - families_of(info.physical, &count, families.data()); - if (info.queue_family < count) - state_.clock.timestamp_valid_bits = families[info.queue_family].timestampValidBits; - } - if (!info.calibrated_timestamps) return; - // The KHR names first; the EXT ones are aliases with the same signatures. - auto domains_of = reinterpret_cast( - info.get_instance_proc(info.instance, "vkGetPhysicalDeviceCalibrateableTimeDomainsKHR")); - auto calibrated = reinterpret_cast( - get_device(info.device, "vkGetCalibratedTimestampsKHR")); - if (!domains_of || !calibrated) { - domains_of = reinterpret_cast( - info.get_instance_proc(info.instance, "vkGetPhysicalDeviceCalibrateableTimeDomainsEXT")); - calibrated = reinterpret_cast( - get_device(info.device, "vkGetCalibratedTimestampsEXT")); - } - if (!domains_of || !calibrated) return; - std::uint32_t count = 0; - domains_of(info.physical, &count, nullptr); - std::vector domains(count); - domains_of(info.physical, &count, domains.data()); - const auto has = [&](VkTimeDomainKHR domain) { - return std::find(domains.begin(), domains.end(), domain) != domains.end(); - }; - if (has(VK_TIME_DOMAIN_DEVICE_KHR) && has(VK_TIME_DOMAIN_QUERY_PERFORMANCE_COUNTER_KHR)) - state_.clock.calibrated = calibrated; - else - log_once("calibrated timestamps lack the DEVICE or QueryPerformanceCounter domain; domains:", int(count)); - } - - // D3D12's layout rules for reserved resources. Use sparse backing for buffers and compatible color textures. - // The arguments are answered as the host runtime answers them (d3d12_vulkan_device_test's - // compare_placed_reserved, RTX 3060 / 610.88): the description, initial state and clear value rules of a - // committed resource on a default heap, the reserved layouts below, and only then E_UNEXPECTED for a null - // output, with nothing made. - HRESULT create_reserved(const char* method, const D3D12_RESOURCE_DESC* desc, D3D12_RESOURCE_STATES state, - const D3D12_CLEAR_VALUE* clear, UINT32 castable_count, const DXGI_FORMAT* castable, - REFIID riid, void** out) { - if (out) *out = nullptr; - if (!desc) return d3d12_trace::result(method, E_INVALIDARG); - if (castable_count && castable && desc->Dimension == D3D12_RESOURCE_DIMENSION_BUFFER) { - log_once("castable formats on a reserved buffer are invalid; count", int(castable_count)); - return d3d12_trace::result(method, E_INVALIDARG); - } - D3D12_RESOURCE_DESC backing = *desc; - const D3D12_HEAP_PROPERTIES heap{D3D12_HEAP_TYPE_DEFAULT}; - if (desc->Dimension == D3D12_RESOURCE_DIMENSION_BUFFER) { - if (desc->Layout != D3D12_TEXTURE_LAYOUT_ROW_MAJOR) return d3d12_trace::result(method, E_INVALIDARG); - } else { - if (static_cast(desc->Layout) == kXboxTiledLayout) { - log_once("reserved resource with the Xbox tiled layout, as 64KB_UNDEFINED_SWIZZLE; dimension", - desc->Dimension); - } else if (desc->Layout != D3D12_TEXTURE_LAYOUT_64KB_UNDEFINED_SWIZZLE) { - return d3d12_trace::result(method, E_INVALIDARG); // 64KB_STANDARD_SWIZZLE too: CheckFeatureSupport reports it unsupported - } - backing.Layout = D3D12_TEXTURE_LAYOUT_UNKNOWN; - leonida::ResourceTiling tiling; - backing.MipLevels = std::max(desc->MipLevels, 1); // any count: only the format is checked here - if (!resource_tiling(backing, tiling)) { - log_once("reserved texture format has no tile shape:", desc->Format); - return d3d12_trace::result(method, E_INVALIDARG); - } - backing.MipLevels = desc->MipLevels; - } - if (const char* why = committed_resource_refusal(heap, D3D12_HEAP_FLAG_NONE, backing, state, clear, - acceleration_structures(), state_.uma)) { - log_once((std::string(method) + " refused (" + why + "), dimension").c_str(), int(desc->Dimension)); - return d3d12_trace::result(method, E_INVALIDARG); - } - if (desc->Dimension != D3D12_RESOURCE_DIMENSION_BUFFER) { - // Extents, mips and samples, as the committed backing below checks them (GetResourceAllocationInfo). - D3D12_RESOURCE_DESC checked = backing; - checked.SampleDesc.Quality = 0; - if (allocation(checked).SizeInBytes == UINT64_MAX) return d3d12_trace::result(method, E_INVALIDARG); - } - if (!out) return d3d12_trace::result(method, E_UNEXPECTED); - ID3D12Resource* resource = nullptr; - HRESULT hr = S_OK; - if (desc->Dimension == D3D12_RESOURCE_DIMENSION_BUFFER && state_.sparse_buffer_memory_types) { - auto* sparse = new Resource(state_, backing, heap, D3D12_HEAP_FLAG_NONE); - sparse->attach_device(identity()); - hr = sparse->create_sparse_buffer(); - if (FAILED(hr)) { - sparse->Release(); - return d3d12_trace::result(method, hr); - } - resource = sparse; - } else if (state_.sparse_image_tiles && backing.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE2D && - backing.Format == DXGI_FORMAT_R8G8B8A8_UNORM && backing.Width && backing.Width <= UINT32_MAX && - backing.Height && backing.DepthOrArraySize == 1 && backing.MipLevels == 1 && - backing.SampleDesc.Count == 1 && !backing.SampleDesc.Quality && - backing.Flags == D3D12_RESOURCE_FLAG_NONE && !clear && !castable_count) { - auto* sparse = new Resource(state_, backing, heap, D3D12_HEAP_FLAG_NONE); - sparse->attach_device(identity()); - hr = sparse->create_sparse_image(); - if (SUCCEEDED(hr)) resource = sparse; - else { - sparse->Release(); - if (hr != E_NOTIMPL) return d3d12_trace::result(method, hr); - } - } - if (!resource) { - hr = create_committed_validated(nullptr, &heap, D3D12_HEAP_FLAG_NONE, &backing, D3D12_RESOURCE_STATE_COMMON, - clear, castable_count, castable, IID_PPV_ARGS(&resource)); - } - if (FAILED(hr)) return d3d12_trace::result(method, hr); - Resource::from(resource)->make_reserved(desc->Layout); - hr = resource->QueryInterface(riid, out); - resource->Release(); - return d3d12_trace::result(method, hr); - } - - // The tiling of a reserved resource's description; false for formats without a tile shape (three- and - // twelve-byte texels, two-plane depth-stencil). - static bool resource_tiling(const D3D12_RESOURCE_DESC& desc, leonida::ResourceTiling& out) { - leonida::TilingDesc tiling{}; - tiling.width = desc.Width; - tiling.height = desc.Height; - tiling.depth_or_layers = desc.DepthOrArraySize; - tiling.mips = desc.MipLevels; - if (desc.Dimension == D3D12_RESOURCE_DIMENSION_BUFFER) { - tiling.kind = leonida::TiledKind::buffer; - return leonida::resource_tiling(tiling, out); - } - if (desc.Dimension != D3D12_RESOURCE_DIMENSION_TEXTURE2D && desc.Dimension != D3D12_RESOURCE_DIMENSION_TEXTURE3D) - return false; - tiling.kind = desc.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE3D ? leonida::TiledKind::texture3d - : leonida::TiledKind::texture2d; - const Format format = vulkan_format(desc.Format, false); - if (!format.format || (format.aspects & VK_IMAGE_ASPECT_STENCIL_BIT)) return false; - if (format.rgb96) return false; // the tile shape of a 12-byte texel is not measured - const leonida::BlockFormat block = leonida::block_format(format.format, format.aspects); - tiling.element_bytes = block.bytes; - tiling.block = block.block; - tiling.samples = desc.SampleDesc.Count; - return leonida::resource_tiling(tiling, out); - } - - // Host image copies are used only on images in GENERAL (D3D12's COMMON), so GENERAL must be a layout the - // device copies from and to on the host. Vulkan requires it to be; check rather than assume. - void load_host_image_copy(PFN_vkGetDeviceProcAddr get_device) { - const VkDevice dev = state_.info.device; - const auto properties2 = reinterpret_cast( - state_.info.get_instance_proc(state_.info.instance, "vkGetPhysicalDeviceProperties2")); - state_.format_properties2 = reinterpret_cast( - state_.info.get_instance_proc(state_.info.instance, "vkGetPhysicalDeviceFormatProperties2")); - const auto to_image = reinterpret_cast(get_device(dev, "vkCopyMemoryToImageEXT")); - const auto to_memory = reinterpret_cast(get_device(dev, "vkCopyImageToMemoryEXT")); - const auto transition = - reinterpret_cast(get_device(dev, "vkTransitionImageLayoutEXT")); - if (!properties2 || !state_.format_properties2 || !to_image || !to_memory || !transition) { - RT_LOG_WARN("d3d12: VK_EXT_host_image_copy entry points missing; using staging copies\n"); - return; - } - VkPhysicalDeviceHostImageCopyPropertiesEXT host{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_HOST_IMAGE_COPY_PROPERTIES_EXT}; - VkPhysicalDeviceProperties2 properties{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROPERTIES_2, &host}; - properties2(state_.info.physical, &properties); - std::vector src(host.copySrcLayoutCount), dst(host.copyDstLayoutCount); - host.pCopySrcLayouts = src.data(); - host.pCopyDstLayouts = dst.data(); - properties2(state_.info.physical, &properties); - const auto general = [](const std::vector& layouts) { - return std::find(layouts.begin(), layouts.end(), VK_IMAGE_LAYOUT_GENERAL) != layouts.end(); - }; - if (!general(src) || !general(dst)) { - RT_LOG_WARN("d3d12: host image copies do not accept GENERAL; using staging copies\n"); - return; - } - state_.copy_memory_to_image = to_image; - state_.copy_image_to_memory = to_memory; - state_.transition_image_layout = transition; - } - - // The layer reports no protected-session support, so a session is refused, as D3D12 refuses one on a device - // without D3D12_FEATURE_PROTECTED_RESOURCE_SESSION_SUPPORT. - static HRESULT refuse_protected_session(const char* method) { - log_once((std::string("protected resource session refused (not supported) by ") + method + ':').c_str(), 1); - return E_INVALIDARG; - } - - // D3D12_RESOURCE_DESC1 is D3D12_RESOURCE_DESC plus SamplerFeedbackMipRegion. - static D3D12_RESOURCE_DESC resource_desc(const D3D12_RESOURCE_DESC1& desc) { - return {desc.Dimension, desc.Alignment, desc.Width, desc.Height, desc.DepthOrArraySize, - desc.MipLevels, desc.Format, desc.SampleDesc, desc.Layout, desc.Flags}; - } - - // A sampler-feedback mip region on a texture, which needs a DXGI_FORMAT_SAMPLER_FEEDBACK_* resource the layer - // does not have. The PC runtime ignores the region on a buffer. - static bool texture_mip_region(const D3D12_RESOURCE_DESC1& desc) { - const D3D12_MIP_REGION& region = desc.SamplerFeedbackMipRegion; - return desc.Dimension != D3D12_RESOURCE_DIMENSION_BUFFER && (region.Width || region.Height || region.Depth); - } - - std::mutex queue_mutex_; - // Live D3D12 queues per VkQueue of info.command_queues, compute_queues and copy_queues (pick_queue_slot). - std::vector queue_users_; - std::vector compute_users_; - std::vector copy_users_; - DeviceState state_; - std::atomic removed_{false}; - OwnedRuntime owned_; - IUnknown* outer_ = nullptr; // the Xbox-ABI proxy, which owns a reference to this device -}; - -} // namespace - -HRESULT create_vulkan_device(const VulkanDeviceInfo& info, REFIID riid, void** out) { - if (!out) return E_POINTER; - *out = nullptr; - auto* device = new Device(info); - if (!device->ok()) { - device->Release(); - return E_FAIL; - } - return hand_out(device, riid, out); -} - -std::shared_ptr tile_heap(ID3D12Heap* heap, const leonida::VulkanContext& context, - bool image, std::uint32_t memory_types) { - auto* object = Heap::from(heap); - return object ? object->tiles(context, image, memory_types) : nullptr; -} - -bool is_sparse_image(ID3D12Resource* resource) { - const auto* object = Resource::from(resource); - return object && object->sparse_image(); -} - -void set_device_outer(ID3D12Device* device, IUnknown* outer) { - Device* d = Device::from(device); - if (!d) return; - // A caller passes what create_device_proxy returned, which is the proxy's DXGI pointer when the title asked - // for IDXGIDevice1: the device's outer identity is the proxy itself either way. - if (void* proxy = rt::d3d12_xs::device_proxy_primary(outer)) outer = static_cast(proxy); - d->set_outer(outer); - // Second job, for an outer that is the Xbox-ABI proxy: its IDXGIDevice1::GetAdapter (d3d12_xs_device.h) hands - // out this layer's adapter, the one create_dxgi_factory enumerates, so a title on the Vulkan device never gets - // a host DXGI object from it. - if (!rt::d3d12_xs::is_device_proxy(outer)) return; - rt::d3d12_xs::set_device_adapter_provider(outer, [](ID3D12Device* real, REFIID riid, void** out) { - IDXGIFactory1* factory = nullptr; - HRESULT hr = create_dxgi_factory(real, __uuidof(IDXGIFactory1), reinterpret_cast(&factory)); - if (FAILED(hr)) return hr; - IDXGIAdapter* adapter = nullptr; - hr = factory->EnumAdapters(0, &adapter); - factory->Release(); - if (FAILED(hr)) return hr; - hr = adapter->QueryInterface(riid, out); - adapter->Release(); - return hr; - }); -} - -const RootArgumentLayout* root_signature_layout(ID3D12RootSignature* signature) { - const RootSignature* s = RootSignature::from(signature); - return s ? &s->layout() : nullptr; -} - -std::uintptr_t compute_pipeline_id(ID3D12PipelineState* pipeline) { - const PipelineState* p = PipelineState::from(pipeline); - return p && p->compute() ? p->id() : 0; -} - -std::uintptr_t graphics_pipeline_id(ID3D12PipelineState* pipeline) { - const PipelineState* p = PipelineState::from(pipeline); - return p && p->graphics() ? p->id() : 0; -} - -const std::vector* pipeline_subgroup_requests(ID3D12PipelineState* pipeline) { - const PipelineState* p = PipelineState::from(pipeline); - return p && (p->compute() || p->graphics()) ? &p->subgroup_requests() : nullptr; -} - -IUnknown* descriptor_heap_info(ID3D12DescriptorHeap* heap, D3D12_DESCRIPTOR_HEAP_DESC& desc, - D3D12_GPU_VIRTUAL_ADDRESS& gpu_base) { - if (!heap) return nullptr; - if (ID3D12DescriptorHeap* real = rt::d3d12_xs::heap_proxy_real_heap(heap)) heap = real; - const DescriptorHeap* d = DescriptorHeap::from(heap); - if (!d) return nullptr; - desc = d->raw_desc(); - gpu_base = d->gpu_base(); - return d->attached_device(); -} - -VkImage vulkan_image(ID3D12Resource* resource) { - const Resource* r = Resource::from(resource); - return r ? r->image() : VK_NULL_HANDLE; -} - -VkMemoryPropertyFlags vulkan_memory_flags(ID3D12Resource* resource) { - const Resource* r = Resource::from(resource); - return r ? r->memory_flags() : 0; -} - -VkBuffer vulkan_buffer(ID3D12Resource* resource) { - const Resource* r = Resource::from(resource); - return r ? r->buffer() : VK_NULL_HANDLE; -} - -const VulkanDeviceInfo* vulkan_device_info(ID3D12Device* device) { - if (!device) return nullptr; - ID3D12Device* real = rt::d3d12_xs::device_proxy_real_device(device); - if (auto* d = Device::from(real ? real : device)) return &d->state().info; - return nullptr; -} - -HRESULT create_buffer_at_host_address(ID3D12Device* device, void* address, const D3D12_RESOURCE_DESC& desc, - std::uint32_t layout, REFIID riid, void** out) { - if (out) *out = nullptr; - if (!device || !out) return E_POINTER; - ID3D12Device* real = rt::d3d12_xs::device_proxy_real_device(device); - auto* d = Device::from(real ? real : device); - if (!d) return E_NOTIMPL; - return d->create_at_host_address(address, desc, layout, riid, out); -} - -bool device_supports_ray_tracing(ID3D12Device* device) { - if (!device) return false; - ID3D12Device* real = rt::d3d12_xs::device_proxy_real_device(device); - if (auto* d = Device::from(real ? real : device)) return d->context().ray_tracing_supported(); - return false; -} - -VkAccelerationStructureKHR vulkan_acceleration_structure(ID3D12Device* device, D3D12_GPU_VIRTUAL_ADDRESS va) { - if (!device || !va) return VK_NULL_HANDLE; - ID3D12Device* real = rt::d3d12_xs::device_proxy_real_device(device); - if (auto* d = Device::from(real ? real : device)) - return d->context().resolve_acceleration_structure(va); - return VK_NULL_HANDLE; -} - -bool color_resolve_format_is_integer(DXGI_FORMAT format) { - return DeviceState::numeric_class(vulkan_format(format, false).format) != 0; -} - -bool color_resolve_format_matches(DXGI_FORMAT format, ID3D12Resource* dst, ID3D12Resource* src) { - if (!dst || !src) return false; - const Format requested = vulkan_format(format, false); - if (requested.typeless || requested.rgb96 || requested.aspects != VK_IMAGE_ASPECT_COLOR_BIT) return false; - if (DeviceState::numeric_class(requested.format) != 0) return false; // D3D12 resolves no integer format - const auto matches = [&](ID3D12Resource* resource) { - const D3D12_RESOURCE_DESC desc = resource->GetDesc(); - return vulkan_format(desc.Format, desc.Flags & D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL).format == - requested.format; - }; - return matches(dst) && matches(src); -} - -bool depth_stencil_resolve_supported(DXGI_FORMAT format, ID3D12Resource* dst, UINT dst_subresource, UINT x, UINT y, - ID3D12Resource* src, UINT src_subresource, const D3D12_RECT* rect, - D3D12_RESOLVE_MODE mode) { - const Resource* d = Resource::from(dst); - const Resource* s = Resource::from(src); - if (!d || !s) return false; - // The format names the depth format, or one plane by its shader-resource format. Measured on the PC runtime - // (RTX 5070 and WARP): Close fails for AVERAGE with the depth format or a stencil plane; the depth plane's - // own format (R32_FLOAT, R24_UNORM_X8_TYPELESS) takes AVERAGE as well as MIN and MAX. - DXGI_FORMAT family = format; - int named_plane = -1; // -1: any plane of the depth format - switch (format) { - case DXGI_FORMAT_R32_FLOAT: family = DXGI_FORMAT_D32_FLOAT, named_plane = 0; break; - case DXGI_FORMAT_R24_UNORM_X8_TYPELESS: family = DXGI_FORMAT_D24_UNORM_S8_UINT, named_plane = 0; break; - case DXGI_FORMAT_X24_TYPELESS_G8_UINT: family = DXGI_FORMAT_D24_UNORM_S8_UINT, named_plane = 1; break; - case DXGI_FORMAT_R32_FLOAT_X8X24_TYPELESS: family = DXGI_FORMAT_D32_FLOAT_S8X24_UINT, named_plane = 0; break; - case DXGI_FORMAT_X32_TYPELESS_G8X24_UINT: family = DXGI_FORMAT_D32_FLOAT_S8X24_UINT, named_plane = 1; break; - default: break; - } - const Format requested = vulkan_format(family, true); - if (requested.typeless || !(requested.aspects & VK_IMAGE_ASPECT_DEPTH_BIT)) return false; - // The plane a subresource index names (0 depth, 1 stencil), or -1. - const auto plane = [&](const Resource* r, UINT subresource) { - const D3D12_RESOURCE_DESC& desc = r->desc(); - if (!(desc.Flags & D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL) || - vulkan_format(desc.Format, true).format != requested.format) - return -1; - const UINT planes = (requested.aspects & VK_IMAGE_ASPECT_STENCIL_BIT) ? 2 : 1; - const UINT per_plane = UINT(desc.MipLevels) * desc.DepthOrArraySize; - return per_plane && subresource / per_plane < planes ? int(subresource / per_plane) : -1; - }; - const int resolved = plane(d, dst_subresource); - if (resolved < 0 || resolved != plane(s, src_subresource) || (named_plane >= 0 && resolved != named_plane) || - s->desc().SampleDesc.Count <= 1 || d->desc().SampleDesc.Count != 1) - return false; - VkResolveModeFlagBits wanted = VK_RESOLVE_MODE_MIN_BIT; - if (mode == D3D12_RESOLVE_MODE_MAX) wanted = VK_RESOLVE_MODE_MAX_BIT; - else if (mode == D3D12_RESOLVE_MODE_AVERAGE && named_plane == 0) wanted = VK_RESOLVE_MODE_AVERAGE_BIT; - else if (mode != D3D12_RESOLVE_MODE_MIN) return false; - // The rendering scope that replays it resolves pixels in place (vulkan_replay.h). - if (rect ? (LONG(x) != rect->left || LONG(y) != rect->top) : (x || y)) return false; - const DeviceState& state = d->device_state(); - return (resolved ? state.stencil_resolve_modes : state.depth_resolve_modes) & wanted; -} - -std::uint32_t device_max_push_constants_size(ID3D12Device* device) { - if (!device) return 0; - ID3D12Device* real = rt::d3d12_xs::device_proxy_real_device(device); - if (!real) real = device; - if (auto* d = Device::from(real)) return d->info().max_push_constants_size; - return 0; -} - -bool device_push_constants_need_fallback(ID3D12Device* device) { - if (!device) return false; - ID3D12Device* real = rt::d3d12_xs::device_proxy_real_device(device); - if (!real) real = device; - if (auto* d = Device::from(real)) return d->info().push_constants_need_fallback; - return false; -} - -bool device_upload_in_vram(ID3D12Device* device) { - if (!device) return false; - ID3D12Device* real = rt::d3d12_xs::device_proxy_real_device(device); - if (!real) real = device; - if (auto* d = Device::from(real)) return d->upload_in_vram(); - return false; -} - -bool device_sparse_buffer_tiles(ID3D12Device* device) { - const Device* d = Device::from(device); - return d && d->state().sparse_buffer_memory_types != 0; -} - -std::uint64_t device_arena_size(ID3D12Device* device) { - if (!device) return 0; - ID3D12Device* real = rt::d3d12_xs::device_proxy_real_device(device); - if (!real) real = device; - const Device* d = Device::from(real); - return d ? d->state().arena.size : 0; -} - -namespace { -const leonida::BindlessSet* bindless_of(ID3D12Device* device) { - if (!device) return nullptr; - ID3D12Device* real = rt::d3d12_xs::device_proxy_real_device(device); - const Device* d = Device::from(real ? real : device); - return d ? d->bindless() : nullptr; -} -} // namespace - -VkDescriptorSet bindless_set(ID3D12Device* device) { - const leonida::BindlessSet* set = bindless_of(device); - return set ? set->set() : VK_NULL_HANDLE; -} - -BindlessStats bindless_stats(ID3D12Device* device) { - BindlessStats stats; - if (!device) return stats; - ID3D12Device* real = rt::d3d12_xs::device_proxy_real_device(device); - const Device* d = Device::from(real ? real : device); - if (!d || !d->bindless()) return stats; - stats.generations_made = d->bindless()->generations_made(); - stats.retired_pending = d->bindless()->retired_count(); - stats.device_idle_waits = d->state().bindless_idle_waits.load(std::memory_order_relaxed); - return stats; -} - -VkDescriptorSetLayout bindless_set_layout(ID3D12Device* device) { - const leonida::BindlessSet* set = bindless_of(device); - return set ? set->layout() : VK_NULL_HANDLE; -} - -std::uint32_t bindless_hash_lookup(ID3D12Device* device, const std::uint32_t (&key)[8]) { - const leonida::BindlessSet* set = bindless_of(device); - return set ? set->table().lookup(key) : 0; -} - -BindlessRoom bindless_room(ID3D12Device* device) { - const leonida::BindlessSet* set = bindless_of(device); - if (!set) return {}; - return {set->free_images(leonida::ImageDimension::dim_2d), set->free_samplers()}; -} - -WindowPresenter::WindowPresenter(IUnknown* device, std::unique_ptr presenter) - : device_(device), presenter_(std::move(presenter)) { - device_->AddRef(); -} - -WindowPresenter::~WindowPresenter() { - presenter_.reset(); // before the device it runs on - device_->Release(); -} - -namespace { -HRESULT present_result(VkResult result) { - if (result == VK_SUCCESS) return S_OK; - RT_LOG_ERROR("d3d12: present failed (VkResult %d)\n", int(result)); - if (result == VK_ERROR_DEVICE_LOST) return DXGI_ERROR_DEVICE_REMOVED; - if (result == VK_ERROR_FORMAT_NOT_SUPPORTED) return DXGI_ERROR_UNSUPPORTED; - return E_FAIL; -} -} // namespace - -HRESULT WindowPresenter::present(ID3D12Resource* back_buffer, UINT sync_interval, const D3D12_RECT* src_rect, - bool tear) { - if (!back_buffer) return E_INVALIDARG; - const leonida::PresentRect rect = src_rect ? leonida::PresentRect{src_rect->left, src_rect->top, src_rect->right, - src_rect->bottom} - : leonida::PresentRect{}; - return present_result(presenter_->present(resource_id(back_buffer), sync_interval > 0, src_rect ? &rect : nullptr, - tear)); -} - -bool WindowPresenter::tear_supported() const { return presenter_->tear_supported(); } -bool WindowPresenter::last_present_tore() const { return presenter_->last_present_tore(); } -std::uint64_t WindowPresenter::tear_presents() const { return presenter_->tear_presents(); } - -HRESULT WindowPresenter::present_blank(UINT sync_interval) { - return present_result(presenter_->present_blank(sync_interval > 0)); -} - -HRESULT WindowPresenter::present_planes(const leonida::PresentPlanes& planes, UINT sync_interval, bool tear) { - return present_result(presenter_->present_planes(planes, sync_interval > 0, tear)); -} - -bool WindowPresenter::hdr_active() const { return presenter_->hdr_active(); } -void WindowPresenter::force_hdr_encoding(bool on) { presenter_->force_hdr_encoding(on); } -std::uint64_t WindowPresenter::composed_presents() const { return presenter_->composed_presents(); } - -// DISPLAYCONFIG_SDR_WHITE_LEVEL.SDRWhiteLevel is the white level in units of 80/1000 nits: 1000 is 80 nits (the scRGB 1.0), -// 2500 is 200 nits (MS Learn, DISPLAYCONFIG_SDR_WHITE_LEVEL). Zero is not a level. -float sdr_white_nits_from_level(unsigned long level) { return float(level) / 1000.0f * 80.0f; } - -float WindowPresenter::display_sdr_white_nits() const { - if (!window_) return 0.0f; - // The GDI name of the monitor the window is on, matched to a display path's source, whose target has the setting. - MONITORINFOEXW monitor{}; - monitor.cbSize = sizeof(monitor); - if (!GetMonitorInfoW(MonitorFromWindow(window_, MONITOR_DEFAULTTONEAREST), &monitor)) return 0.0f; - // The active configuration can change between the size query and the read (a hot-plug): ERROR_INSUFFICIENT_BUFFER asks - // for the sizes again (the pattern Microsoft documents for QueryDisplayConfig). - UINT32 path_count = 0, mode_count = 0; - std::vector paths; - std::vector modes; - LONG status = ERROR_INSUFFICIENT_BUFFER; - for (int attempt = 0; attempt < 8 && status == ERROR_INSUFFICIENT_BUFFER; ++attempt) { - if (GetDisplayConfigBufferSizes(QDC_ONLY_ACTIVE_PATHS, &path_count, &mode_count) != ERROR_SUCCESS) return 0.0f; - paths.assign(path_count, {}); - modes.assign(mode_count, {}); - status = QueryDisplayConfig(QDC_ONLY_ACTIVE_PATHS, &path_count, paths.data(), &mode_count, modes.data(), nullptr); - } - if (status != ERROR_SUCCESS) return 0.0f; // the caller keeps the last good value - for (UINT32 i = 0; i < path_count; ++i) { - DISPLAYCONFIG_SOURCE_DEVICE_NAME source{}; - source.header = {DISPLAYCONFIG_DEVICE_INFO_GET_SOURCE_NAME, sizeof(source), paths[i].sourceInfo.adapterId, - paths[i].sourceInfo.id}; - if (DisplayConfigGetDeviceInfo(&source.header) != ERROR_SUCCESS || - std::wcscmp(source.viewGdiDeviceName, monitor.szDevice) != 0) - continue; - DISPLAYCONFIG_SDR_WHITE_LEVEL level{}; - level.header = {DISPLAYCONFIG_DEVICE_INFO_GET_SDR_WHITE_LEVEL, sizeof(level), paths[i].targetInfo.adapterId, - paths[i].targetInfo.id}; - if (DisplayConfigGetDeviceInfo(&level.header) != ERROR_SUCCESS || level.SDRWhiteLevel == 0) return 0.0f; - return sdr_white_nits_from_level(level.SDRWhiteLevel); - } - return 0.0f; -} - -bool WindowPresenter::enable_capture() { return presenter_->enable_capture(); } - -void WindowPresenter::set_abort(std::function abort) { presenter_->set_abort(std::move(abort)); } - -bool WindowPresenter::read_back(std::vector& pixels, VkExtent2D* extent, VkFormat* format) { - return presenter_->read_back(pixels, extent, format); -} - -VkExtent2D WindowPresenter::extent() const { return presenter_->extent(); } -std::uint64_t WindowPresenter::presented() const { return presenter_->presented(); } - -bool device_has_swapchain_colorspace(ID3D12Device* device) { - ID3D12Device* real = rt::d3d12_xs::device_proxy_real_device(device); - Device* d = Device::from(real ? real : device); - return d && d->state().info.swapchain_colorspace; -} - -std::unique_ptr create_window_presenter(ID3D12Device* device, HWND window) { - // A title holds the Xbox-ABI proxy, not the layer's device: look behind it, as the helpers above do. - ID3D12Device* real = rt::d3d12_xs::device_proxy_real_device(device); - Device* d = Device::from(real ? real : device); - if (device && !d) - RT_LOG_ERROR("d3d12: create_window_presenter: %p is neither the Xbox device proxy nor a device of " - "this layer; no presenter\n", - static_cast(device)); - if (!d || !window) return nullptr; - const VulkanDeviceInfo& info = d->state().info; - if (!info.presentation) { - RT_LOG_ERROR("d3d12: the Vulkan device was created without presentation support\n"); - return nullptr; - } - const auto create_surface = reinterpret_cast( - info.get_instance_proc(info.instance, "vkCreateWin32SurfaceKHR")); - if (!create_surface) return nullptr; - VkWin32SurfaceCreateInfoKHR surface_info{VK_STRUCTURE_TYPE_WIN32_SURFACE_CREATE_INFO_KHR}; - surface_info.hinstance = GetModuleHandleW(nullptr); - surface_info.hwnd = window; - VkSurfaceKHR surface = VK_NULL_HANDLE; - if (create_surface(info.instance, &surface_info, nullptr, &surface) != VK_SUCCESS) return nullptr; - // LEONIDA_PRESENT_NO_TEAR=1 keeps the swapchain FIFO-only (ImmediateThresholdPercent then does nothing). - // Any non-empty value other than "0" turns it off. - const std::string no_tear = rt::config::get("present.no_tear").text; - const bool tear_allowed = no_tear.empty() || no_tear == "0"; - // present.capture_dir, present.capture_every and present.capture_limit (LEONIDA_CAPTURE, LEONIDA_CAPTURE_EVERY, - // LEONIDA_CAPTURE_LIMIT): the presenter writes presented frames to that folder (src/vulkan_present.h). The two - // numbers are read with atoi and raised to 1 by the presenter, as before the settings moved to the table. - leonida::PresentCapture capture; - capture.dir = rt::config::path("present.capture_dir"); - capture.every = std::atoi(rt::config::get("present.capture_every").text.c_str()); - capture.limit = std::atoi(rt::config::get("present.capture_limit").text.c_str()); - auto presenter = std::make_unique(*d->state().context, info.get_instance_proc, - info.instance, info.physical, info.queue, - info.queue_family, surface, // owns the surface - info.swapchain_maintenance1 && tear_allowed, - [window]() -> VkExtent2D { - RECT r{}; - if (GetClientRect(window, &r)) { - return {static_cast(r.right - r.left), - static_cast(r.bottom - r.top)}; - } - return {0, 0}; - }, - [create_surface, hinstance = GetModuleHandleW(nullptr), - hwnd = window, instance = info.instance]() -> VkSurfaceKHR { - // A lost surface (display gone) is remade for the - // same window; VulkanSwapchain never retained the - // hwnd, this callback does. - VkWin32SurfaceCreateInfoKHR surface_info{ - VK_STRUCTURE_TYPE_WIN32_SURFACE_CREATE_INFO_KHR}; - surface_info.hinstance = hinstance; - surface_info.hwnd = hwnd; - VkSurfaceKHR made = VK_NULL_HANDLE; - if (create_surface(instance, &surface_info, nullptr, - &made) != VK_SUCCESS) - return VK_NULL_HANDLE; - return made; - }, - std::move(capture)); - if (!presenter->ok()) { - RT_LOG_ERROR("d3d12: cannot present to this window from the device's queue family\n"); - return nullptr; - } - auto window_presenter = std::make_unique(d->holder(), std::move(presenter)); - window_presenter->set_window(window); - return window_presenter; -} - -HRESULT register_samplers(ID3D12Device* device, std::span samplers) { - if (!device) return E_INVALIDARG; - ID3D12Device* real = rt::d3d12_xs::device_proxy_real_device(device); - Device* d = Device::from(real ? real : device); - if (!d) return E_INVALIDARG; - bool all = true; - for (const leonida::gfx10::SamplerWords& words : samplers) all = d->bind_sampler(words) && all; - return all ? S_OK : E_FAIL; -} - -HRESULT create_dxgi_factory(ID3D12Device* device, REFIID riid, void** out) { - if (!out) return E_POINTER; - *out = nullptr; - if (!device) return E_INVALIDARG; - ID3D12Device* real = rt::d3d12_xs::device_proxy_real_device(device); - Device* d = Device::from(real ? real : device); - if (!d) return E_INVALIDARG; - const auto& i = d->info(); - const auto gdpa = reinterpret_cast(i.get_instance_proc(i.instance, "vkGetDeviceProcAddr")); - if (!gdpa) return E_FAIL; - return rt::dxgi::create_factory(d->context(), i.get_instance_proc, i.instance, i.physical, gdpa, i.queue, - i.queue_family, riid, out); -} - -// Creates its own Vulkan instance and a Vulkan 1.3 device, or a 1.2 device with VK_KHR_dynamic_rendering and -// VK_KHR_synchronization2 (vulkan13_features.h). LEONIDA_VK_VALIDATION=1 adds VK_LAYER_KHRONOS_validation. -HRESULT create_vulkan_device_standalone(REFIID riid, void** out, QueueTestSettings queue_test_settings) { - if (!out) return E_POINTER; - *out = nullptr; - static const HMODULE library = LoadLibraryA("vulkan-1.dll"); - const auto get = library ? reinterpret_cast( - reinterpret_cast(GetProcAddress(library, "vkGetInstanceProcAddr"))) - : nullptr; - if (!get) { - RT_LOG_ERROR("d3d12: vulkan-1.dll not found\n"); - return E_FAIL; - } - const auto create_instance = reinterpret_cast(get(nullptr, "vkCreateInstance")); - const auto enum_inst_exts = reinterpret_cast( - get(nullptr, "vkEnumerateInstanceExtensionProperties")); - std::vector inst_exts; - bool surface_maintenance1_khr = false, surface_maintenance1_ext = false; // enabled on the instance - bool swapchain_colorspace_enabled = false; // VK_EXT_swapchain_colorspace on the instance - if (enum_inst_exts) { - std::uint32_t ext_cnt = 0; - enum_inst_exts(nullptr, &ext_cnt, nullptr); - std::vector available(ext_cnt); - enum_inst_exts(nullptr, &ext_cnt, available.data()); - bool has_surface = false, has_win32 = false, has_caps2 = false; - for (const auto& e : available) { - if (!std::strcmp(e.extensionName, VK_KHR_SURFACE_EXTENSION_NAME)) has_surface = true; - if (!std::strcmp(e.extensionName, VK_KHR_WIN32_SURFACE_EXTENSION_NAME)) has_win32 = true; - if (!std::strcmp(e.extensionName, VK_KHR_GET_SURFACE_CAPABILITIES_2_EXTENSION_NAME)) has_caps2 = true; - if (!std::strcmp(e.extensionName, "VK_KHR_surface_maintenance1")) surface_maintenance1_khr = true; - if (!std::strcmp(e.extensionName, "VK_EXT_surface_maintenance1")) surface_maintenance1_ext = true; - } - if (has_surface && has_win32) { - inst_exts.push_back(VK_KHR_SURFACE_EXTENSION_NAME); - inst_exts.push_back(VK_KHR_WIN32_SURFACE_EXTENSION_NAME); - // Lists the HDR10 (ST.2084) surface formats, which a PresentX plane in HDR10 can use (xbox_present.h); without it - // the surface only offers sRGB-nonlinear ones. - for (const auto& e : available) - if (!std::strcmp(e.extensionName, VK_EXT_SWAPCHAIN_COLOR_SPACE_EXTENSION_NAME)) { - inst_exts.push_back(VK_EXT_SWAPCHAIN_COLOR_SPACE_EXTENSION_NAME); - swapchain_colorspace_enabled = true; - break; - } - // The surface half of VK_*_swapchain_maintenance1 (the present modes a swapchain can switch between). - if (has_caps2 && (surface_maintenance1_khr || surface_maintenance1_ext)) { - inst_exts.push_back(VK_KHR_GET_SURFACE_CAPABILITIES_2_EXTENSION_NAME); - if (surface_maintenance1_khr) inst_exts.push_back("VK_KHR_surface_maintenance1"); - if (surface_maintenance1_ext) inst_exts.push_back("VK_EXT_surface_maintenance1"); - } else { - surface_maintenance1_khr = surface_maintenance1_ext = false; - } - } else { - surface_maintenance1_khr = surface_maintenance1_ext = false; - } - } - VkApplicationInfo app{VK_STRUCTURE_TYPE_APPLICATION_INFO}; - app.pApplicationName = "gta6rt"; - app.apiVersion = VK_API_VERSION_1_3; - VkInstanceCreateInfo instance_info{VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO}; - instance_info.pApplicationInfo = &app; - const char* layer = "VK_LAYER_KHRONOS_validation"; - const VkValidationFeatureEnableEXT sync_validation = VK_VALIDATION_FEATURE_ENABLE_SYNCHRONIZATION_VALIDATION_EXT; - VkValidationFeaturesEXT validation_features{VK_STRUCTURE_TYPE_VALIDATION_FEATURES_EXT}; - validation_features.enabledValidationFeatureCount = 1; - validation_features.pEnabledValidationFeatures = &sync_validation; - // vulkan.validation (LEONIDA_VK_VALIDATION): on for a value that does not start with 0. A value of 8 characters - // or more is ignored, as before the setting moved to the table. - const std::string validation = rt::config::get("vulkan.validation").text; - if (!validation.empty() && validation.size() < 8 && validation[0] != '0') { - // Ask for the layer only when the loader lists it, and say so when it does not: an instance that cannot be - // made because of a missing layer left the caller with "Vulkan unavailable" and no hint that validation was - // the cause. Wine does not list the Linux loader's layers to the program and refuses an explicit request for - // one, so there only VK_INSTANCE_LAYERS (which Wine keeps out of the program's environment) loads it. - bool layer_listed = false; - if (const auto enumerate_layers = reinterpret_cast( - get(nullptr, "vkEnumerateInstanceLayerProperties"))) { - std::uint32_t layer_count = 0; - enumerate_layers(&layer_count, nullptr); - std::vector layers(layer_count); - if (layer_count && enumerate_layers(&layer_count, layers.data()) >= VK_SUCCESS) - for (std::uint32_t i = 0; i < layer_count; ++i) - layer_listed = layer_listed || std::strcmp(layers[i].layerName, layer) == 0; - } - if (layer_listed) { - instance_info.pNext = &validation_features; - instance_info.enabledLayerCount = 1; - instance_info.ppEnabledLayerNames = &layer; - } else { - RT_LOG_ERROR("d3d12: LEONIDA_VK_VALIDATION is set but %s is not listed by the Vulkan loader " - "(install the Vulkan SDK; under Wine set VK_INSTANCE_LAYERS=%s instead)\n", - layer, layer); - return E_FAIL; - } - } - // VK_EXT_debug_utils when the loader has it, for the game's debug markers (PIX events) in RenderDoc and the like. - const char* debug_utils = VK_EXT_DEBUG_UTILS_EXTENSION_NAME; - bool has_debug_utils = false; - if (const auto enumerate = reinterpret_cast( - get(nullptr, "vkEnumerateInstanceExtensionProperties"))) { - std::uint32_t extension_count = 0; - enumerate(nullptr, &extension_count, nullptr); - std::vector extensions(extension_count); - enumerate(nullptr, &extension_count, extensions.data()); - for (const auto& e : extensions) has_debug_utils = has_debug_utils || std::strcmp(e.extensionName, debug_utils) == 0; - } - // One list: the surface extensions above (for DXGI presentation) and debug utils both go on the instance. - const bool instance_has_surface = !inst_exts.empty(); - if (has_debug_utils) inst_exts.push_back(debug_utils); - instance_info.enabledExtensionCount = static_cast(inst_exts.size()); - instance_info.ppEnabledExtensionNames = inst_exts.empty() ? nullptr : inst_exts.data(); - OwnedRuntime owned{}; - if (create_instance(&instance_info, nullptr, &owned.instance) != VK_SUCCESS) { - RT_LOG_ERROR("d3d12: vkCreateInstance (Vulkan 1.3) failed\n"); - return E_FAIL; - } - owned.destroy_instance = reinterpret_cast(get(owned.instance, "vkDestroyInstance")); - const auto fail = [&](const char* why) { - RT_LOG_ERROR("d3d12: %s\n", why); - owned.destroy_instance(owned.instance, nullptr); - return E_FAIL; - }; - -#define LEONIDA_INSTANCE(name) const auto name = reinterpret_cast(get(owned.instance, #name)) - LEONIDA_INSTANCE(vkEnumeratePhysicalDevices); - LEONIDA_INSTANCE(vkGetPhysicalDeviceProperties); - LEONIDA_INSTANCE(vkGetPhysicalDeviceQueueFamilyProperties); - LEONIDA_INSTANCE(vkGetPhysicalDeviceFeatures2); - LEONIDA_INSTANCE(vkGetPhysicalDeviceProperties2); - LEONIDA_INSTANCE(vkEnumerateDeviceExtensionProperties); - LEONIDA_INSTANCE(vkCreateDevice); - LEONIDA_INSTANCE(vkGetDeviceProcAddr); -#undef LEONIDA_INSTANCE - std::uint32_t count = 0; - vkEnumeratePhysicalDevices(owned.instance, &count, nullptr); - std::vector physicals(count); - vkEnumeratePhysicalDevices(owned.instance, &count, physicals.data()); - VulkanDeviceInfo info{}; - info.get_instance_proc = get; - info.instance = owned.instance; - info.separate_depth_stencil_layouts = true; - info.debug_utils = has_debug_utils; - VkPhysicalDeviceProperties chosen{}; - bool chosen_bc = false; - VkPhysicalDeviceFeatures chosen_features{}; - VkPhysicalDeviceVulkan12Features chosen12{}; - bool chosen_draw_params = false; - leonida::Vulkan13Features v13, candidate13; - // The first usable device of the highest vulkan_device_rank: a native driver over Microsoft's Dozen (which says - // it is a discrete GPU, #915), then discrete over integrated; the test harnesses (vk_device_pick.h) pick the same. - int chosen_rank = -1; - // vulkan.device (LEONIDA_VK_DEVICE, else leonida.toml): part of the device's name, compared without case - // (src/vulkan_device_filter.h). Nothing set takes every device. - const std::string device_filter = leonida::vulkan_device_filter_of(rt::config::get("vulkan.device").text); - for (VkPhysicalDevice candidate : physicals) { - VkPhysicalDeviceProperties props{}; - vkGetPhysicalDeviceProperties(candidate, &props); - if (!leonida::vulkan_device_wanted(props.deviceName, device_filter)) continue; - candidate13.query(candidate, props.apiVersion, vkGetPhysicalDeviceFeatures2, vkEnumerateDeviceExtensionProperties); - if (!candidate13.usable()) continue; - VkPhysicalDeviceVulkan11Features f11{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_1_FEATURES}; - VkPhysicalDeviceVulkan12Features f12{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_2_FEATURES, &f11}; - VkPhysicalDeviceFeatures2 features{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2, &f12}; - vkGetPhysicalDeviceFeatures2(candidate, &features); - const bool bc = features.features.textureCompressionBC; - const bool draw_params = f11.shaderDrawParameters; - if (!f12.timelineSemaphore || !f12.separateDepthStencilLayouts || !f12.bufferDeviceAddress) continue; - std::uint32_t family_count = 0; - vkGetPhysicalDeviceQueueFamilyProperties(candidate, &family_count, nullptr); - std::vector families(family_count); - vkGetPhysicalDeviceQueueFamilyProperties(candidate, &family_count, families.data()); - for (std::uint32_t i = 0; i < family_count; ++i) { - if (!(families[i].queueFlags & VK_QUEUE_GRAPHICS_BIT)) continue; - if (const int rank = leonida::vulkan_device_rank(static_cast(props.deviceType), props.vendorID); - rank > chosen_rank) { - chosen_rank = rank; - info.physical = candidate; - info.queue_family = i; - chosen = props; - chosen_bc = bc; - chosen_features = features.features; - chosen12 = f12; - chosen_draw_params = draw_params; - v13.choose(candidate13); - } - break; - } - } - if (!info.physical) - return fail(device_filter.empty() - ? "no Vulkan 1.3 GPU (or 1.2 with VK_KHR_dynamic_rendering and VK_KHR_synchronization2) with " - "dynamicRendering, synchronization2, timelineSemaphore and separateDepthStencilLayouts" - : "no GPU named by LEONIDA_VK_DEVICE has Vulkan 1.3 (or 1.2 with VK_KHR_dynamic_rendering and " - "VK_KHR_synchronization2) with dynamicRendering, synchronization2, timelineSemaphore and " - "separateDepthStencilLayouts"); - if (!v13.core) - RT_LOG_INFO("d3d12: Vulkan 1.2 device: dynamicRendering and synchronization2 through their KHR " - "extensions; %s\n", - v13.extended_dynamic_state ? "extended dynamic state through VK_EXT_extended_dynamic_state(2)" - : "no extended dynamic state, so no graphics pipelines"); - - // VK_EXT_conditional_rendering for SetPredication, VK_KHR_swapchain for DXGI presentation, and optional - // VK_KHR_acceleration_structure + VK_KHR_ray_query for hardware BVH builds (BLAS + TLAS). - VkPhysicalDeviceConditionalRenderingFeaturesEXT conditional{ - VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_CONDITIONAL_RENDERING_FEATURES_EXT}; - bool has_swapchain = false; - VkPhysicalDeviceAccelerationStructureFeaturesKHR as_features{ - VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_ACCELERATION_STRUCTURE_FEATURES_KHR}; - VkPhysicalDeviceRayQueryFeaturesKHR rq_features{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_RAY_QUERY_FEATURES_KHR}; - VkPhysicalDeviceMeshShaderFeaturesEXT mesh_features{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MESH_SHADER_FEATURES_EXT}; - { - std::uint32_t extension_count = 0; - vkEnumerateDeviceExtensionProperties(info.physical, nullptr, &extension_count, nullptr); - std::vector extensions(extension_count); - vkEnumerateDeviceExtensionProperties(info.physical, nullptr, &extension_count, extensions.data()); - bool has_as = false, has_dho = false, has_rq = false; - for (const auto& e : extensions) { - if (!std::strcmp(e.extensionName, VK_EXT_CONDITIONAL_RENDERING_EXTENSION_NAME)) { - VkPhysicalDeviceFeatures2 features{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2, &conditional}; - vkGetPhysicalDeviceFeatures2(info.physical, &features); - info.conditional_rendering = conditional.conditionalRendering == VK_TRUE; - } else if (!std::strcmp(e.extensionName, VK_KHR_SWAPCHAIN_EXTENSION_NAME)) { - has_swapchain = true; - } else if (!std::strcmp(e.extensionName, VK_KHR_ACCELERATION_STRUCTURE_EXTENSION_NAME)) { - has_as = true; - } else if (!std::strcmp(e.extensionName, VK_KHR_DEFERRED_HOST_OPERATIONS_EXTENSION_NAME)) { - has_dho = true; - } else if (!std::strcmp(e.extensionName, VK_KHR_RAY_QUERY_EXTENSION_NAME)) { - has_rq = true; - } else if (!std::strcmp(e.extensionName, VK_EXT_MESH_SHADER_EXTENSION_NAME)) { - VkPhysicalDeviceFeatures2 features{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2, &mesh_features}; - vkGetPhysicalDeviceFeatures2(info.physical, &features); - info.mesh_shader = mesh_features.meshShader == VK_TRUE; - } - } - if (!info.mesh_shader) - RT_LOG_WARN("d3d12: the GPU has no VK_EXT_mesh_shader: mesh-shader PSOs are unsupported\n"); - if (has_as && has_dho && has_rq && chosen12.bufferDeviceAddress) { - as_features.pNext = &rq_features; - VkPhysicalDeviceFeatures2 features{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2, &as_features}; - vkGetPhysicalDeviceFeatures2(info.physical, &features); - info.ray_tracing = as_features.accelerationStructure == VK_TRUE && rq_features.rayQuery == VK_TRUE; - } - // The game's translated RT shaders read XDXR BVH4 records, which a VkAccelerationStructureKHR is not - // (docs/d3d12_vulkan.md 4.8): build those, unless LEONIDA_RT_AS=khr asks for #743's KHR builds instead. - const bool khr = rt::config::get("vulkan.rt_as").text == "khr"; - if (!khr && chosen12.bufferDeviceAddress) { - info.xdxr_acceleration_structures = true; - info.ray_tracing = false; // no KHR extensions: AS resources keep their console VAs - } - if (!info.conditional_rendering) - RT_LOG_WARN("d3d12: the GPU has no VK_EXT_conditional_rendering: SetPredication is unsupported\n"); - } - VkPhysicalDeviceConditionalRenderingFeaturesEXT enable_conditional{ - VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_CONDITIONAL_RENDERING_FEATURES_EXT}; - enable_conditional.conditionalRendering = VK_TRUE; - VkPhysicalDeviceRayQueryFeaturesKHR enable_rq{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_RAY_QUERY_FEATURES_KHR}; - enable_rq.rayQuery = VK_TRUE; - VkPhysicalDeviceAccelerationStructureFeaturesKHR enable_as{ - VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_ACCELERATION_STRUCTURE_FEATURES_KHR}; - enable_as.accelerationStructure = VK_TRUE; - - // Only meshShader: the game has no amplification (task) shaders, and multiview and shading-rate mesh features - // are not used. - VkPhysicalDeviceMeshShaderFeaturesEXT enable_mesh{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MESH_SHADER_FEATURES_EXT}; - enable_mesh.meshShader = VK_TRUE; - - void* ext_chain = nullptr; - if (info.mesh_shader) { - enable_mesh.pNext = ext_chain; - ext_chain = &enable_mesh; - } - if (info.ray_tracing) { - enable_rq.pNext = ext_chain; - enable_as.pNext = &enable_rq; - ext_chain = &enable_as; - } - if (info.conditional_rendering) { - enable_conditional.pNext = ext_chain; - ext_chain = &enable_conditional; - } - - // Subgroup size control: a pipeline stage asks for the size its shader was translated for (src/subgroup_size.h). - leonida::query_subgroup_size_caps(vkGetPhysicalDeviceProperties2, info.physical, v13.subgroup_size_control, - v13.compute_full_subgroups, info.subgroup); - // Translated vertex shaders read BaseVertex / BaseInstance (SPIR-V DrawParameters) to give v0 / v3 the - // hardware's zero-based vertex and instance ids (docs/design.md, Inputs and outputs). - VkPhysicalDeviceVulkan11Features enable11{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_1_FEATURES, - v13.enable(ext_chain)}; - enable11.shaderDrawParameters = chosen_draw_params ? VK_TRUE : VK_FALSE; - if (!chosen_draw_params) RT_LOG_WARN("d3d12: the GPU has no shaderDrawParameters\n"); - VkPhysicalDeviceVulkan12Features enable12{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_2_FEATURES, &enable11}; - enable12.timelineSemaphore = VK_TRUE; - enable12.separateDepthStencilLayouts = VK_TRUE; - info.buffer_device_address = chosen12.bufferDeviceAddress == VK_TRUE; - enable12.bufferDeviceAddress = info.buffer_device_address ? VK_TRUE : VK_FALSE; - info.storage_buffer_8bit = chosen12.storageBuffer8BitAccess == VK_TRUE; - enable12.storageBuffer8BitAccess = info.storage_buffer_8bit; - // Where the GPU has them: what the bindless set 0 needs (VulkanDeviceInfo::bindless), and the sampler features - // D3D12 samplers can ask for. - info.bindless = chosen12.runtimeDescriptorArray && chosen_features.shaderSampledImageArrayDynamicIndexing && - chosen_features.shaderStorageImageArrayDynamicIndexing && - chosen12.descriptorBindingSampledImageUpdateAfterBind && - chosen12.descriptorBindingStorageImageUpdateAfterBind && - chosen12.descriptorBindingStorageBufferUpdateAfterBind; - info.bindless_partially_bound = info.bindless && chosen12.descriptorBindingPartiallyBound; - info.sampler_anisotropy = chosen_features.samplerAnisotropy; - info.sampler_mirror_clamp_to_edge = chosen12.samplerMirrorClampToEdge; - info.sampler_filter_minmax = chosen12.samplerFilterMinmax; - enable12.runtimeDescriptorArray = info.bindless; - enable12.descriptorBindingSampledImageUpdateAfterBind = info.bindless; - enable12.descriptorBindingStorageImageUpdateAfterBind = info.bindless; - enable12.descriptorBindingStorageBufferUpdateAfterBind = info.bindless; - enable12.descriptorBindingPartiallyBound = info.bindless_partially_bound; - enable12.samplerMirrorClampToEdge = info.sampler_mirror_clamp_to_edge; - enable12.samplerFilterMinmax = info.sampler_filter_minmax; - info.shader_output_layer = chosen12.shaderOutputLayer == VK_TRUE; - info.shader_output_viewport_index = chosen12.shaderOutputViewportIndex == VK_TRUE; - enable12.shaderOutputLayer = info.shader_output_layer; - enable12.shaderOutputViewportIndex = info.shader_output_viewport_index; - if (!info.bindless) - RT_LOG_WARN("d3d12: the GPU lacks a descriptor-indexing feature the bindless set needs\n"); - enable12.bufferDeviceAddress = VK_TRUE; - info.buffer_device_address = true; - std::uint32_t family_count = 0; - vkGetPhysicalDeviceQueueFamilyProperties(info.physical, &family_count, nullptr); - std::vector families(family_count); - vkGetPhysicalDeviceQueueFamilyProperties(info.physical, &family_count, families.data()); - const std::uint32_t queue_cap = max_queues_per_family(queue_test_settings); - const std::uint32_t command_queue_count = std::min(queue_cap, families[info.queue_family].queueCount); - std::vector priorities(16, 1.0f); - std::vector queue_infos; - { - VkDeviceQueueCreateInfo q{VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO}; - q.queueFamilyIndex = info.queue_family; - q.queueCount = command_queue_count; - q.pQueuePriorities = priorities.data(); - queue_infos.push_back(q); - } - const auto preferred = leonida::pick_queue_families(families, info.queue_family); - // D3D12 permits UpdateTileMappings on DIRECT, COMPUTE and COPY queues. Vulkan requires - // VK_QUEUE_SPARSE_BINDING_BIT on the VkQueue passed to vkQueueBindSparse. A dedicated - // async family without that capability cannot implement all D3D12 queue operations; - // fall back to the graphics family when sparse buffers are supported. QueueKind still - // enforces the D3D12 COPY/COMPUTE stage restrictions on the more capable family. - const bool sparse_buffers = chosen_features.sparseBinding && chosen_features.sparseResidencyBuffer && - chosen_features.sparseResidencyAliased; - auto picked = leonida::sparse_capable_queue_families(families, preferred, sparse_buffers); - if (graphics_family_only(queue_test_settings)) picked = {info.queue_family, info.queue_family, info.queue_family}; - std::uint32_t compute_count = 0, copy_count = 0; - if (picked.compute != info.queue_family) { - info.compute_family = picked.compute; - compute_count = std::min(queue_cap, families[picked.compute].queueCount); - VkDeviceQueueCreateInfo q{VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO}; - q.queueFamilyIndex = picked.compute; - q.queueCount = compute_count; - q.pQueuePriorities = priorities.data(); - queue_infos.push_back(q); - } - if (picked.copy != info.queue_family) { - info.copy_family = picked.copy; - if (picked.copy != picked.compute) { - copy_count = std::min(queue_cap, families[picked.copy].queueCount); - VkDeviceQueueCreateInfo q{VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO}; - q.queueFamilyIndex = picked.copy; - q.queueCount = copy_count; - q.pQueuePriorities = priorities.data(); - queue_infos.push_back(q); - } - } - VkPhysicalDeviceFeatures enable{}; - enable.sparseBinding = chosen_features.sparseBinding; - enable.sparseResidencyBuffer = chosen_features.sparseResidencyBuffer; - enable.sparseResidencyImage2D = chosen_features.sparseResidencyImage2D; - enable.sparseResidencyAliased = chosen_features.sparseResidencyAliased; - info.texture_compression_bc = chosen_bc; - enable.textureCompressionBC = chosen_bc ? VK_TRUE : VK_FALSE; // the game's textures are BC1-7 - enable.shaderSampledImageArrayDynamicIndexing = info.bindless; - enable.shaderStorageImageArrayDynamicIndexing = info.bindless; - if (!chosen_features.shaderInt64) - RT_LOG_WARN("d3d12: the GPU has no shaderInt64; translated shaders (all declare Int64) will not load\n"); - enable.samplerAnisotropy = info.sampler_anisotropy; - enable.occlusionQueryPrecise = chosen_features.occlusionQueryPrecise; // exact D3D12 occlusion counts - enable.pipelineStatisticsQuery = chosen_features.pipelineStatisticsQuery; - info.occlusion_query_precise = chosen_features.occlusionQueryPrecise == VK_TRUE; - info.pipeline_statistics_query = chosen_features.pipelineStatisticsQuery == VK_TRUE; - if (!chosen_bc) RT_LOG_WARN("d3d12: the GPU has no BC texture support\n"); - const char* conditional_extension = VK_EXT_CONDITIONAL_RENDERING_EXTENSION_NAME; - - // Optional: VK_EXT_host_image_copy lets WriteToSubresource/ReadFromSubresource copy on the CPU. - std::uint32_t extension_count = 0; - vkEnumerateDeviceExtensionProperties(info.physical, nullptr, &extension_count, nullptr); - std::vector extensions(extension_count); - vkEnumerateDeviceExtensionProperties(info.physical, nullptr, &extension_count, extensions.data()); - info.conservative_rasterization = std::any_of(extensions.begin(), extensions.end(), [](const auto& e) { - return std::strcmp(e.extensionName, VK_EXT_CONSERVATIVE_RASTERIZATION_EXTENSION_NAME) == 0; - }); - const bool has_host_image_copy = std::any_of(extensions.begin(), extensions.end(), [](const auto& e) { - return std::strcmp(e.extensionName, VK_EXT_HOST_IMAGE_COPY_EXTENSION_NAME) == 0; - }); - VkPhysicalDeviceImageViewMinLodFeaturesEXT min_lod{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_IMAGE_VIEW_MIN_LOD_FEATURES_EXT}; - if (std::any_of(extensions.begin(), extensions.end(), [](const auto& e) { - return std::strcmp(e.extensionName, VK_EXT_IMAGE_VIEW_MIN_LOD_EXTENSION_NAME) == 0; - })) { - VkPhysicalDeviceFeatures2 query{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2, &min_lod}; - vkGetPhysicalDeviceFeatures2(info.physical, &query); - info.image_view_min_lod = min_lod.minLod == VK_TRUE; - if (info.image_view_min_lod) { - min_lod.pNext = *v13.next(); - *v13.next() = &min_lod; - } - } - const char* divisor_extension = nullptr; - for (const char* name : - {VK_KHR_VERTEX_ATTRIBUTE_DIVISOR_EXTENSION_NAME, VK_EXT_VERTEX_ATTRIBUTE_DIVISOR_EXTENSION_NAME}) { - if (std::any_of(extensions.begin(), extensions.end(), - [&](const auto& e) { return std::strcmp(e.extensionName, name) == 0; })) { - divisor_extension = name; - break; - } - } - VkPhysicalDeviceVertexAttributeDivisorFeaturesKHR divisor_khr{ - VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VERTEX_ATTRIBUTE_DIVISOR_FEATURES_KHR}; - VkPhysicalDeviceVertexAttributeDivisorFeaturesEXT divisor_ext{ - VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VERTEX_ATTRIBUTE_DIVISOR_FEATURES_EXT}; - if (divisor_extension) { - const bool is_khr = std::strcmp(divisor_extension, VK_KHR_VERTEX_ATTRIBUTE_DIVISOR_EXTENSION_NAME) == 0; - VkPhysicalDeviceFeatures2 query{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2, - is_khr ? static_cast(&divisor_khr) : static_cast(&divisor_ext)}; - vkGetPhysicalDeviceFeatures2(info.physical, &query); - info.vertex_attribute_divisor = - (is_khr ? divisor_khr.vertexAttributeInstanceRateDivisor : divisor_ext.vertexAttributeInstanceRateDivisor) == - VK_TRUE; - if (info.vertex_attribute_divisor) { - if (is_khr) { - divisor_khr.pNext = *v13.next(); - *v13.next() = &divisor_khr; - } else { - divisor_ext.pNext = *v13.next(); - *v13.next() = &divisor_ext; - } - } - } - VkPhysicalDeviceHostImageCopyFeaturesEXT host_copy{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_HOST_IMAGE_COPY_FEATURES_EXT}; - if (has_host_image_copy) { - VkPhysicalDeviceFeatures2 query{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2, &host_copy}; - vkGetPhysicalDeviceFeatures2(info.physical, &query); - } - const char* host_image_copy_name = VK_EXT_HOST_IMAGE_COPY_EXTENSION_NAME; - info.host_image_copy = has_host_image_copy && host_copy.hostImageCopy; - if (info.host_image_copy) { - host_copy.pNext = *v13.next(); // after the conditional rendering features, if any - *v13.next() = &host_copy; - } else { - RT_LOG_WARN("d3d12: no VK_EXT_host_image_copy; CPU texture copies use a staging submit\n"); - } - - // The pixel-shader extensions translated shaders can declare (VulkanDeviceInfo::fragment_shader_barycentric and - // the two after it). Each is queried, and enabled with its feature where the GPU has it. - const auto has_device_extension = [&](const char* name) { - return std::any_of(extensions.begin(), extensions.end(), - [&](const auto& e) { return std::strcmp(e.extensionName, name) == 0; }); - }; - VkPhysicalDeviceFragmentShaderBarycentricFeaturesKHR barycentric{ - VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FRAGMENT_SHADER_BARYCENTRIC_FEATURES_KHR}; - if (has_device_extension(VK_KHR_FRAGMENT_SHADER_BARYCENTRIC_EXTENSION_NAME)) { - VkPhysicalDeviceFeatures2 query{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2, &barycentric}; - vkGetPhysicalDeviceFeatures2(info.physical, &query); - info.fragment_shader_barycentric = barycentric.fragmentShaderBarycentric == VK_TRUE; - if (info.fragment_shader_barycentric) { - barycentric.pNext = *v13.next(); - *v13.next() = &barycentric; - } - } - VkPhysicalDeviceFragmentShaderInterlockFeaturesEXT interlock{ - VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FRAGMENT_SHADER_INTERLOCK_FEATURES_EXT}; - if (has_device_extension(VK_EXT_FRAGMENT_SHADER_INTERLOCK_EXTENSION_NAME)) { - VkPhysicalDeviceFeatures2 query{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2, &interlock}; - vkGetPhysicalDeviceFeatures2(info.physical, &query); - info.fragment_shader_interlock = interlock.fragmentShaderPixelInterlock == VK_TRUE; - if (info.fragment_shader_interlock) { - interlock.fragmentShaderSampleInterlock = VK_FALSE; // the translator only declares the pixel interlock - interlock.fragmentShaderShadingRateInterlock = VK_FALSE; - interlock.pNext = *v13.next(); - *v13.next() = &interlock; - } - } -#ifdef VK_KHR_MAINTENANCE_8_EXTENSION_NAME - VkPhysicalDeviceMaintenance8FeaturesKHR maintenance8{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MAINTENANCE_8_FEATURES_KHR}; - if (has_device_extension(VK_KHR_MAINTENANCE_8_EXTENSION_NAME)) { - VkPhysicalDeviceFeatures2 query{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2, &maintenance8}; - vkGetPhysicalDeviceFeatures2(info.physical, &query); - info.maintenance8 = maintenance8.maintenance8 == VK_TRUE; - if (info.maintenance8) { - maintenance8.pNext = *v13.next(); - *v13.next() = &maintenance8; - } - } -#endif - -#ifdef VK_KHR_SHADER_FMA_EXTENSION_NAME - // VK_KHR_shader_fma: OpFmaKHR is a single-rounding multiply-add in SPIR-V (GLSL.std.450 Fma may round twice). - // Translated shaders built with `rdna2spirv.py --fma khr` need it (index capability FMAKHR, feature - // shaderFmaFloat32); when it is missing they must not be created, so use `--fma glsl` there. - VkPhysicalDeviceShaderFmaFeaturesKHR shader_fma{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADER_FMA_FEATURES_KHR}; - if (std::any_of(extensions.begin(), extensions.end(), [](const auto& e) { - return std::strcmp(e.extensionName, VK_KHR_SHADER_FMA_EXTENSION_NAME) == 0; - })) { - VkPhysicalDeviceFeatures2 query{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2, &shader_fma}; - vkGetPhysicalDeviceFeatures2(info.physical, &query); - info.shader_fma = shader_fma.shaderFmaFloat32 == VK_TRUE; - if (info.shader_fma) { - shader_fma.pNext = *v13.next(); - *v13.next() = &shader_fma; - } - } -#endif - VkPhysicalDeviceShaderClockFeaturesKHR shader_clock{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADER_CLOCK_FEATURES_KHR}; - if (has_device_extension(VK_KHR_SHADER_CLOCK_EXTENSION_NAME)) { - VkPhysicalDeviceFeatures2 query{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2, &shader_clock}; - vkGetPhysicalDeviceFeatures2(info.physical, &query); - info.shader_subgroup_clock = shader_clock.shaderSubgroupClock == VK_TRUE; - info.shader_device_clock = shader_clock.shaderDeviceClock == VK_TRUE; - if (info.shader_subgroup_clock || info.shader_device_clock) { - shader_clock.pNext = *v13.next(); - *v13.next() = &shader_clock; - } - } - // What graphics PSOs may ask for: different blend state per render target, wireframe, a depth-bias clamp and - // SRC1 blend factors. Enabled where the GPU has them; a PSO that needs a missing one is refused. - enable.independentBlend = chosen_features.independentBlend; - enable.fillModeNonSolid = chosen_features.fillModeNonSolid; - enable.depthBiasClamp = chosen_features.depthBiasClamp; - enable.dualSrcBlend = chosen_features.dualSrcBlend; - enable.logicOp = chosen_features.logicOp; - enable.depthClamp = chosen_features.depthClamp; - enable.geometryShader = chosen_features.geometryShader; // translated geometry shaders (195 in the corpus) - // What translated shaders declare (the index's `features`): 64-bit integers in most of the corpus (25,803 of - // 26,503 entries), doubles, 16-bit integers, clip and cull distances in a few vertex shaders, image stores - // without a format (StorageImageWriteWithoutFormat), gather offsets (ImageGatherExtended) and LOD-clamped samples - // (MinLod), and the layer or viewport a vertex shader writes (above, in Vulkan 1.2). Enabled where the GPU has - // them; without one, vkCreateShaderModule reports the capability (VUID-...-pCode-08740). - enable.shaderInt64 = chosen_features.shaderInt64; - enable.shaderFloat64 = chosen_features.shaderFloat64; - enable.shaderInt16 = chosen_features.shaderInt16; - enable.shaderClipDistance = chosen_features.shaderClipDistance; - enable.shaderCullDistance = chosen_features.shaderCullDistance; - enable.shaderStorageImageWriteWithoutFormat = chosen_features.shaderStorageImageWriteWithoutFormat; - enable.shaderStorageImageReadWithoutFormat = chosen_features.shaderStorageImageReadWithoutFormat; - enable.shaderImageGatherExtended = chosen_features.shaderImageGatherExtended; - enable.shaderResourceMinLod = chosen_features.shaderResourceMinLod; - // A translated pixel shader that stores to an image or does an image atomic declares that storage image without - // NonWritable (1,018 of the corpus's 1,038 image-atomic shaders are pixel shaders), and Vulkan allows that outside - // a compute shader only with these two features: fragmentStoresAndAtomics for the pixel stage, - // vertexPipelineStoresAndAtomics for vertex and geometry shaders. Enabled where the GPU has them; a graphics PSO - // whose shader needs a missing one is refused (PipelineState::create_graphics). - enable.fragmentStoresAndAtomics = chosen_features.fragmentStoresAndAtomics; - enable.vertexPipelineStoresAndAtomics = chosen_features.vertexPipelineStoresAndAtomics; - info.features = enable; - - // GetClockCalibration reads both clocks at once with calibrated timestamps (KHR, or the older EXT). - const char* calibrated = nullptr; - for (const char* name : - {VK_KHR_CALIBRATED_TIMESTAMPS_EXTENSION_NAME, VK_EXT_CALIBRATED_TIMESTAMPS_EXTENSION_NAME}) { - for (const auto& extension : extensions) - if (std::strcmp(extension.extensionName, name) == 0) calibrated = name; - if (calibrated) break; - } - info.calibrated_timestamps = calibrated != nullptr; - - // Switching a vsync swapchain to IMMEDIATE or FIFO_RELAXED per present (PresentX's ImmediateThresholdPercent): - // the KHR extension (promoted from the EXT one, same structures) with the surface extension of the same name - // on the instance, else the EXT one. Only enabled where the instance has the surface half and the GPU the feature. - const char* swapchain_m1_name = nullptr; -#ifdef LEONIDA_SWAPCHAIN_MAINTENANCE1 - VkPhysicalDeviceSwapchainMaintenance1FeaturesEXT swapchain_m1{ - VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SWAPCHAIN_MAINTENANCE_1_FEATURES_EXT}; - if (has_swapchain && instance_has_surface) { - const auto device_has = [&](const char* name) { - return std::any_of(extensions.begin(), extensions.end(), - [&](const auto& e) { return std::strcmp(e.extensionName, name) == 0; }); - }; - if (surface_maintenance1_khr && device_has("VK_KHR_swapchain_maintenance1")) - swapchain_m1_name = "VK_KHR_swapchain_maintenance1"; - else if (surface_maintenance1_ext && device_has("VK_EXT_swapchain_maintenance1")) - swapchain_m1_name = "VK_EXT_swapchain_maintenance1"; - if (swapchain_m1_name) { - VkPhysicalDeviceFeatures2 query{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2, &swapchain_m1}; - vkGetPhysicalDeviceFeatures2(info.physical, &query); - if (swapchain_m1.swapchainMaintenance1 == VK_TRUE) { - swapchain_m1.pNext = *v13.next(); - *v13.next() = &swapchain_m1; - } else { - swapchain_m1_name = nullptr; - } - } - } -#endif - info.swapchain_maintenance1 = swapchain_m1_name != nullptr; - - // Optional: VK_EXT_custom_border_color lets samplers use custom float and integer border colours. - const bool has_custom_border = std::any_of(extensions.begin(), extensions.end(), [](const auto& e) { - return std::strcmp(e.extensionName, VK_EXT_CUSTOM_BORDER_COLOR_EXTENSION_NAME) == 0; - }); - VkPhysicalDeviceCustomBorderColorFeaturesEXT custom_border{ - VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_CUSTOM_BORDER_COLOR_FEATURES_EXT}; - if (has_custom_border) { - VkPhysicalDeviceFeatures2 query{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2, &custom_border}; - vkGetPhysicalDeviceFeatures2(info.physical, &query); - } - const char* custom_border_name = VK_EXT_CUSTOM_BORDER_COLOR_EXTENSION_NAME; - info.custom_border_color = has_custom_border && custom_border.customBorderColors; - info.custom_border_color_without_format = has_custom_border && custom_border.customBorderColorWithoutFormat; - if (info.custom_border_color) { - custom_border.pNext = *v13.next(); // where later feature structs go since #1706 - *v13.next() = &custom_border; - } else { - RT_LOG_WARN( - "d3d12: no VK_EXT_custom_border_color; custom sampler border colours fall back to transparent black\n"); - } - - // Optional: VK_EXT_external_memory_host lets OpenExistingHeapFromAddress import the caller's committed memory as - // the heap's backing, so the GPU reads what the CPU writes there without a copy. - if (std::any_of(extensions.begin(), extensions.end(), [](const auto& e) { - return std::strcmp(e.extensionName, VK_EXT_EXTERNAL_MEMORY_HOST_EXTENSION_NAME) == 0; - })) { - VkPhysicalDeviceExternalMemoryHostPropertiesEXT host_memory{ - VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_EXTERNAL_MEMORY_HOST_PROPERTIES_EXT}; - VkPhysicalDeviceProperties2 properties{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROPERTIES_2, &host_memory}; - vkGetPhysicalDeviceProperties2(info.physical, &properties); - info.host_pointer_alignment = host_memory.minImportedHostPointerAlignment; - } - - VkDeviceCreateInfo device_info{VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO, &enable12}; - device_info.queueCreateInfoCount = std::uint32_t(queue_infos.size()); - device_info.pQueueCreateInfos = queue_infos.data(); - device_info.pEnabledFeatures = &enable; - std::vector device_extensions; - v13.add_extensions(device_extensions); - if (info.conservative_rasterization) device_extensions.push_back(VK_EXT_CONSERVATIVE_RASTERIZATION_EXTENSION_NAME); - if (info.image_view_min_lod) device_extensions.push_back(VK_EXT_IMAGE_VIEW_MIN_LOD_EXTENSION_NAME); - if (info.vertex_attribute_divisor) device_extensions.push_back(divisor_extension); - if (info.conditional_rendering) device_extensions.push_back(conditional_extension); - if (info.host_image_copy) device_extensions.push_back(host_image_copy_name); - if (info.fragment_shader_barycentric) - device_extensions.push_back(VK_KHR_FRAGMENT_SHADER_BARYCENTRIC_EXTENSION_NAME); - if (info.fragment_shader_interlock) device_extensions.push_back(VK_EXT_FRAGMENT_SHADER_INTERLOCK_EXTENSION_NAME); -#ifdef VK_KHR_MAINTENANCE_8_EXTENSION_NAME - if (info.maintenance8) device_extensions.push_back(VK_KHR_MAINTENANCE_8_EXTENSION_NAME); -#endif -#ifdef VK_KHR_SHADER_FMA_EXTENSION_NAME - if (info.shader_fma) device_extensions.push_back(VK_KHR_SHADER_FMA_EXTENSION_NAME); -#endif - if (info.shader_subgroup_clock || info.shader_device_clock) - device_extensions.push_back(VK_KHR_SHADER_CLOCK_EXTENSION_NAME); - if (calibrated) device_extensions.push_back(calibrated); - // VK_KHR_swapchain requires VK_KHR_surface on the instance (VUID-vkCreateDevice-ppEnabledExtensionNames-01387). - if (has_swapchain && instance_has_surface) device_extensions.push_back(VK_KHR_SWAPCHAIN_EXTENSION_NAME); - if (swapchain_m1_name) device_extensions.push_back(swapchain_m1_name); - if (info.mesh_shader) device_extensions.push_back(VK_EXT_MESH_SHADER_EXTENSION_NAME); - if (info.ray_tracing) { - device_extensions.push_back(VK_KHR_ACCELERATION_STRUCTURE_EXTENSION_NAME); - device_extensions.push_back(VK_KHR_DEFERRED_HOST_OPERATIONS_EXTENSION_NAME); - device_extensions.push_back(VK_KHR_RAY_QUERY_EXTENSION_NAME); - } - info.presentation = has_swapchain && instance_has_surface; - info.swapchain_colorspace = info.presentation && swapchain_colorspace_enabled; - if (info.custom_border_color) device_extensions.push_back(custom_border_name); - if (info.host_pointer_alignment) device_extensions.push_back(VK_EXT_EXTERNAL_MEMORY_HOST_EXTENSION_NAME); - device_info.enabledExtensionCount = std::uint32_t(device_extensions.size()); - device_info.ppEnabledExtensionNames = device_extensions.empty() ? nullptr : device_extensions.data(); - if (vkCreateDevice(info.physical, &device_info, nullptr, &owned.device) != VK_SUCCESS) - return fail("vkCreateDevice failed"); - info.device = owned.device; - owned.destroy_device = reinterpret_cast(vkGetDeviceProcAddr(owned.device, "vkDestroyDevice")); - info.command_queues.resize(command_queue_count); - const auto get_queue = reinterpret_cast(vkGetDeviceProcAddr(owned.device, "vkGetDeviceQueue")); - for (std::uint32_t i = 0; i < command_queue_count; ++i) - get_queue(owned.device, info.queue_family, i, &info.command_queues[i]); - if (compute_count) { - // Copies on the async-compute family split its queues with the compute queues: one VkQueue per live queue. - const bool split = info.copy_family == info.compute_family && compute_count > 1; - const std::uint32_t for_compute = split ? compute_count / 2 : compute_count; - for (std::uint32_t i = 0; i < compute_count; ++i) { - VkQueue q = VK_NULL_HANDLE; - get_queue(owned.device, info.compute_family, i, &q); - (i < for_compute ? info.compute_queues : info.copy_queues).push_back(q); - } - if (info.copy_family == info.compute_family && !split) info.copy_family = UINT32_MAX; - } - for (std::uint32_t i = 0; i < copy_count; ++i) { - VkQueue q = VK_NULL_HANDLE; - get_queue(owned.device, info.copy_family, i, &q); - info.copy_queues.push_back(q); - } - info.queue = info.command_queues[0]; - info.max_push_constants_size = chosen.limits.maxPushConstantsSize; - info.push_constants_need_fallback = (info.max_push_constants_size < 144); - RT_LOG_INFO("d3d12: Vulkan device: %s (maxPushConstantsSize: %u bytes)\n", chosen.deviceName, - chosen.limits.maxPushConstantsSize); - RT_LOG_INFO("d3d12: subgroup sizes %u..%u (default %u), requirable in stages 0x%x, subgroupSizeControl %s, " - "computeFullSubgroups %s\n", - info.subgroup.min_size, info.subgroup.max_size, info.subgroup.default_size, - unsigned(info.subgroup.required_stages), info.subgroup.subgroup_size_control ? "on" : "off", - info.subgroup.compute_full_subgroups ? "on" : "off"); - if (info.push_constants_need_fallback) { - RT_LOG_WARN("d3d12: WARNING: GPU maxPushConstantsSize (%u bytes) is below the 144 bytes required by " - "the shader contract; uniform-buffer fallback required for the 16-byte tail\n", - chosen.limits.maxPushConstantsSize); - } - - auto* device = new Device(info); - device->own(owned); // destroyed with the device from here on, even on failure - if (!device->ok()) { - device->Release(); - return E_FAIL; - } - return hand_out(device, riid, out); -} - -bool has_global_realtime_privilege() { - const int override_state = g_global_realtime_privilege_override.load(std::memory_order_relaxed); - if (override_state >= 0) return override_state != 0; - HANDLE token = nullptr; - if (!OpenThreadToken(GetCurrentThread(), TOKEN_QUERY, TRUE, &token)) { - // Fall back to the process token only when the thread is not impersonating (ERROR_NO_TOKEN); fail closed on - // ERROR_CANT_OPEN_ANONYMOUS or any other thread-token error so an impersonated caller cannot inherit the - // process token's privilege. - if (GetLastError() != ERROR_NO_TOKEN || !OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &token)) - return false; - } - LUID luid{}; - BOOL enabled = FALSE; - if (LookupPrivilegeValueW(nullptr, L"SeIncreaseBasePriorityPrivilege", &luid)) { - PRIVILEGE_SET set{}; - set.PrivilegeCount = 1; - set.Control = PRIVILEGE_SET_ALL_NECESSARY; - set.Privilege[0].Luid = luid; - set.Privilege[0].Attributes = SE_PRIVILEGE_ENABLED; - if (!PrivilegeCheck(token, &set, &enabled)) enabled = FALSE; - } - CloseHandle(token); - return enabled != FALSE; -} - -void set_global_realtime_privilege_override_for_test(int state) { - g_global_realtime_privilege_override.store(state, std::memory_order_relaxed); -} - -HRESULT create_console_descriptor_heap(ID3D12Device* device, const D3D12_DESCRIPTOR_HEAP_DESC* desc, - D3D12_GPU_VIRTUAL_ADDRESS console_address, std::uint64_t console_size, - REFIID riid, void** out) { - if (out) *out = nullptr; - if (!device || !desc) return E_INVALIDARG; - // No output: a capability check, as CreateDescriptorHeap does. - if (!out) return S_FALSE; - if ((desc->Flags & ~D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE) || desc->NodeMask > 1 || - ((desc->Flags & D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE) && - (desc->Type == D3D12_DESCRIPTOR_HEAP_TYPE_RTV || desc->Type == D3D12_DESCRIPTOR_HEAP_TYPE_DSV))) { - return E_INVALIDARG; - } - ID3D12Device* real = rt::d3d12_xs::device_proxy_real_device(device); - auto* d = Device::from(real ? real : device); - if (!d) return E_INVALIDARG; - return d->create_console_descriptor_heap(desc, console_address, console_size, riid, out); -} - -std::filesystem::path configured_shader_directory(std::string* error, const std::filesystem::path& config) { - try { - // paths.shaders (LEONIDA_SHADERS, else leonida.toml) wins over shader_path.txt. - if (std::filesystem::path shaders = rt::config::path("paths.shaders"); !shaders.empty()) return shaders; - if (!config.empty()) return shader_directory_from_file(config); - std::wstring exe(32768, L'\0'); - const DWORD length = ::GetModuleFileNameW(nullptr, exe.data(), static_cast(exe.size())); - if (!length || length >= exe.size()) return {}; - exe.resize(length); - return shader_directory_from_file(std::filesystem::path(exe).parent_path() / L"shader_path.txt"); - } catch (const std::exception& e) { - if (error) *error = e.what(); - return {}; - } -} - -} // namespace rt::d3d12 diff --git a/runtime/shims/d3d12_xs.cpp b/runtime/shims/d3d12_xs.cpp deleted file mode 100644 index fa65a6849..000000000 --- a/runtime/shims/d3d12_xs.cpp +++ /dev/null @@ -1,238 +0,0 @@ -// Xbox Series D3D12 imports forwarded to the Windows D3D12 exports. -// The SDK types describe the Windows side. The measured guest ABI differs in the root-signature flag word: Xbox -// sets bits in the high byte (observed 0x03000000) and the PC serializer rejects them, so descriptors are copied -// with that byte cleared before forwarding. On a host that serializes only up to 1.1 (Windows 10's built-in -// d3d12.dll), version 1.2 descriptions are rewritten as 1.1 when no static sampler uses 1.2's flags. -// D3D12XboxCreateDevice returns an Xbox-ABI proxy (d3d12_xs_device.h) over the PC device; only the measured slots -// are overridden, the rest follow the PC vtable. -#include -#include - -#include -#include -#include -#include -#include -#include - -#include "../core/config.h" -#include "../core/log.h" -#ifdef LEONIDA_VULKAN_DEVICE -#include "d3d12_com.h" -#endif -#include "d3d12_trace.h" -#include "d3d12_xs_device.h" -#include "d3d12_xs_rootsig.h" -#include "shims.h" - -namespace { - -FARPROC host(const char* name) { - static HMODULE d3d12 = LoadLibraryExA("d3d12.dll", nullptr, LOAD_LIBRARY_SEARCH_SYSTEM32); - FARPROC p = d3d12 ? GetProcAddress(d3d12, name) : nullptr; - if (!p) RT_LOG_ERROR("d3d12_xs: host d3d12.dll has no %s\n", name); - return p; -} - -using SerializeFn = decltype(&::D3D12SerializeVersionedRootSignature); -using DeserializerFn = decltype(&::D3D12CreateRootSignatureDeserializer); -using LegacySerializeFn = decltype(&::D3D12SerializeRootSignature); -using CreateDeviceFn = decltype(&::D3D12CreateDevice); - -// Asked once: does the host serializer take version 1.2 at all? An empty 1.2 description is valid everywhere 1.2 is -// supported; Windows 10's built-in d3d12.dll rejects it with E_INVALIDARG. -bool host_serializes_1_2(SerializeFn fn) { - static const bool supported = [fn] { - D3D12_VERSIONED_ROOT_SIGNATURE_DESC empty{}; - empty.Version = D3D_ROOT_SIGNATURE_VERSION_1_2; - ID3DBlob* blob = nullptr; - ID3DBlob* error = nullptr; - const HRESULT hr = fn(&empty, &blob, &error); - if (blob) blob->Release(); - if (error) error->Release(); - return SUCCEEDED(hr); - }(); - return supported; -} - -HRESULT WINAPI serialize_root_signature(const D3D12_VERSIONED_ROOT_SIGNATURE_DESC* desc, - ID3DBlob** blob, ID3DBlob** error) { - static auto fn = reinterpret_cast(host("D3D12SerializeVersionedRootSignature")); - if (!fn) return E_NOTIMPL; - if (!desc) return fn(desc, blob, error); - - D3D12_VERSIONED_ROOT_SIGNATURE_DESC cleared{}; - if (!rt::d3d12_xs::copy_versioned_root_signature_desc_clear_xbox_flags(*desc, cleared)) { - RT_LOG_WARN("d3d12_xs: D3D12SerializeVersionedRootSignature: unknown descriptor version %d; " - "forwarding unchanged (Xbox flags not cleared)\n", - static_cast(desc->Version)); - return fn(desc, blob, error); - } - if (cleared.Version == D3D_ROOT_SIGNATURE_VERSION_1_2 && !host_serializes_1_2(fn)) { - // Windows 10's d3d12.dll stops at 1.1 (d3d12_xs_rootsig.h). Rewrite as 1.1 when nothing is lost. - std::vector samplers; - D3D12_VERSIONED_ROOT_SIGNATURE_DESC v11{}; - if (!rt::d3d12_xs::downgrade_root_signature_1_2_to_1_1(cleared, samplers, v11)) { - RT_LOG_ERROR("d3d12_xs: D3D12SerializeVersionedRootSignature: version 1.2 with static sampler flags, " - "and the host d3d12.dll serializes only up to 1.1; refused\n"); - if (blob) *blob = nullptr; - if (error) *error = nullptr; - return E_INVALIDARG; - } - static std::atomic logged{false}; - if (!logged.exchange(true)) - RT_LOG_INFO("d3d12_xs: the host d3d12.dll serializes root signatures only up to 1.1; version 1.2 " - "descriptions without static sampler flags are serialized as 1.1\n"); - return fn(&v11, blob, error); - } - return fn(&cleared, blob, error); -} - -// The package DLLs import the versioned serializer; the legacy entry point is kept because it is trivial to forward -// with the same flag fix and the test uses it. -HRESULT WINAPI serialize_root_signature_legacy(const D3D12_ROOT_SIGNATURE_DESC* desc, - D3D_ROOT_SIGNATURE_VERSION version, ID3DBlob** blob, - ID3DBlob** error) { - static auto fn = reinterpret_cast(host("D3D12SerializeRootSignature")); - if (!fn) return E_NOTIMPL; - if (!desc) return fn(desc, version, blob, error); - - D3D12_ROOT_SIGNATURE_DESC cleared{}; - rt::d3d12_xs::copy_root_signature_desc_clear_xbox_flags(*desc, cleared); - return fn(&cleared, version, blob, error); -} - -HRESULT WINAPI create_root_signature_deserializer(const void* data, SIZE_T size, REFIID iid, void** out) { - static auto fn = reinterpret_cast(host("D3D12CreateRootSignatureDeserializer")); - if (!fn) return E_NOTIMPL; - - // The host deserializer rejects a blob whose RTS0 flags carry the Xbox high - // byte, so forward a copy with that byte cleared when present (the same fix - // the serializer applies to descriptors). - std::vector cleared; - if (rt::d3d12_xs::copy_rts0_blob_clear_xbox_flags(data, static_cast(size), cleared)) { - data = cleared.data(); - size = cleared.size(); - } - // Wine's deserializer refuses an all-zero container hash, which Microsoft's does not check; a matching hash - // suits both (d3d12_xs_rootsig.h). This also covers the copy above, which keeps a zero hash zero. - std::vector hashed; - if (rt::d3d12_xs::copy_dxbc_blob_fill_zero_checksum(data, static_cast(size), hashed)) { - data = hashed.data(); - size = hashed.size(); - } - return fn(data, size, iid, out); -} - -// Measured shape: D3D12XboxCreateDevice(adapter, params, riid, out), where params is a 24-word block that is only -// logged and not used to create the device. The struct's total size is unknown, so the log reads 24 x 32-bit words -// (96 bytes) and no more. The PC D3D12CreateDevice needs a minimum feature level instead, so 12_0 is used as the -// least restrictive floor; higher feature levels are still exposed by the created device. -HRESULT WINAPI D3D12XboxCreateDevice(IUnknown* adapter, const void* params, const IID* riid, void** out) { - constexpr auto method = "D3D12XboxCreateDevice"; - using rt::d3d12_trace::result; - if (!out) return result(method, E_POINTER); - *out = nullptr; - if (!riid) return result(method, E_POINTER); - - const bool tracing = rt::d3d12_trace::enabled(); - if (!tracing) - RT_LOG_DEBUG("d3d12_xs: D3D12XboxCreateDevice adapter=%p params=%p riid=%08lx-%04x-%04x\n", - adapter, params, static_cast(riid->Data1), riid->Data2, riid->Data3); - // The 24 words are the title's device parameters (docs/boot.md, question 1). Unlike the pointers above they are the - // same on every run, so they are printed with --trace-d3d12 as well, and one traced run shows them. - if (params) { - const uint32_t* words = static_cast(params); - char line[24 * 11 + 1]; - line[0] = '\0'; - size_t used = 0; - for (int i = 0; i < 24 && used < sizeof(line); ++i) { - int n = std::snprintf(line + used, sizeof(line) - used, "%s%08x", i ? " " : "", - static_cast(words[i])); - if (n < 0) break; - used += static_cast(n); - } - RT_LOG_DEBUG("d3d12_xs: D3D12XboxCreateDevice params[24] =%s\n", line); - } else { - RT_LOG_DEBUG("d3d12_xs: D3D12XboxCreateDevice params = null\n"); - } - - static std::atomic proxy_logged{false}; - if (!proxy_logged.exchange(true, std::memory_order_relaxed)) { - RT_LOG_DEBUG("d3d12_xs: D3D12XboxCreateDevice: wrapping the PC ID3D12Device in the Xbox-ABI proxy " - "(slot 62 -> CreateComputePipelineState, slot 76 -> CreateCommittedResource).\n"); - } - -#ifdef LEONIDA_VULKAN_DEVICE - // Opt-in until the Vulkan device covers the first frame: LEONIDA_D3D12=vulkan puts the Vulkan-backed device - // behind the same proxy instead of the host's D3D12 device. - if (rt::config::get("d3d12.backend").text == "vulkan") { - ID3D12Device* vulkan = nullptr; - HRESULT vhr = rt::d3d12::create_vulkan_device_standalone( - __uuidof(ID3D12Device), reinterpret_cast(&vulkan), rt::d3d12::QueueTestSettings::ignore); - if (FAILED(vhr)) { - RT_LOG_ERROR("d3d12_xs: D3D12XboxCreateDevice: Vulkan device failed (hr=0x%08lx)\n", - static_cast(vhr)); - return result(method, vhr); - } - vhr = rt::d3d12_xs::create_device_proxy(vulkan, *riid, out); - if (FAILED(vhr)) { - vulkan->Release(); - RT_LOG_ERROR("d3d12_xs: D3D12XboxCreateDevice: proxy over the Vulkan device failed " - "(hr=0x%08lx)\n", static_cast(vhr)); - return result(method, vhr); - } - rt::d3d12::set_device_outer(vulkan, static_cast(*out)); - if (!tracing) - RT_LOG_DEBUG("d3d12_xs: D3D12XboxCreateDevice -> proxy %p (Vulkan device %p)\n", *out, - static_cast(vulkan)); - return result(method, S_OK); - } -#endif - - static auto create = reinterpret_cast(host("D3D12CreateDevice")); - if (!create) return result(method, E_NOTIMPL); - - ID3D12Device* real = nullptr; - HRESULT hr = create(adapter, D3D_FEATURE_LEVEL_12_0, __uuidof(ID3D12Device), - reinterpret_cast(&real)); - if (FAILED(hr) || !real) { - if (real) real->Release(); - RT_LOG_ERROR("d3d12_xs: D3D12XboxCreateDevice: PC D3D12CreateDevice failed (hr=0x%08lx)\n", - static_cast(hr)); - return result(method, FAILED(hr) ? hr : E_FAIL); - } - - hr = rt::d3d12_xs::create_device_proxy(real, *riid, out); - if (FAILED(hr)) { - // create_device_proxy keeps the caller's reference on failure. - real->Release(); - RT_LOG_ERROR("d3d12_xs: D3D12XboxCreateDevice: proxy creation failed (hr=0x%08lx)\n", - static_cast(hr)); - return result(method, hr); - } - if (!tracing) - RT_LOG_DEBUG("d3d12_xs: D3D12XboxCreateDevice -> proxy %p (PC device %p)\n", *out, - static_cast(real)); - return result(method, S_OK); -} - -static_assert(std::is_same_v); -static_assert(std::is_same_v); -static_assert(std::is_same_v); - -// Measured call (RT-5, 1.0.2.1): the title calls it once at startup with one pointer to a zeroed 32-byte block whose -// dword at +4 it sets (a count), and only checks the result for failure. The PC/Vulkan side owns virtual memory, -// so the policy is accepted and ignored. -HRESULT WINAPI configure_virtual_memory(void* /*desc*/) { return S_OK; } - -} // namespace - -SHIM_TABLE(d3d12_xs, - {"d3d12_xs.dll", "D3D12SerializeVersionedRootSignature", reinterpret_cast(&serialize_root_signature)}, - {"d3d12_xs.dll", "D3D12SerializeRootSignature", reinterpret_cast(&serialize_root_signature_legacy)}, - {"d3d12_xs.dll", "D3D12CreateRootSignatureDeserializer", - reinterpret_cast(&create_root_signature_deserializer)}, - {"d3d12_xs.dll", "D3D12XboxCreateDevice", reinterpret_cast(&D3D12XboxCreateDevice)}, - {"d3d12_xs.dll", "D3D12ConfigureVirtualMemoryX", reinterpret_cast(&configure_virtual_memory)}, -); diff --git a/runtime/shims/d3d12_xs_device.cpp b/runtime/shims/d3d12_xs_device.cpp deleted file mode 100644 index 30b6707f2..000000000 --- a/runtime/shims/d3d12_xs_device.cpp +++ /dev/null @@ -1,2344 +0,0 @@ -// Xbox-ABI proxy around a PC ID3D12Device. See d3d12_xs_device.h for the measured slots and the limits. -// -// How forwarding works: the proxy object's first word is a vtable built once from one thunk per slot. A thunk -// receives the proxy in RCX, replaces it with the PC device pointer from offset 8, and tail-calls the PC method at -// the same index through a 15-argument integer prototype. Every PC D3D12 device method takes integer/pointer -// arguments only, so the x64 registers and stack words line up exactly; methods that return a struct keep their -// hidden return pointer in RDX, which is passed through as the first argument unchanged. The measured exceptions -// are IUnknown (0-2), slot 14 (which wraps the heap), 62 and 76, plus the heap proxy's 9/10 conversion from the -// PC hidden-pointer form to the Xbox RAX form. Slots 8/75 (command queues), 36 (fences) and 32 (a shared fence) wrap -// what they create in queue and fence proxies built the same way, and slots 31/34/35/45/46/50 hand the real objects -// behind heap, queue and fence proxies to the real device (see the command queue and fence section). -// -// A thunk declares 14 argument words, but the title passes only as many as the method takes, so the caller's frame -// may end right after the four register homes. The compiler owns a function's incoming stack-argument slots and may -// write them, a tail call included. Every function a thunk hands its words to therefore takes them in the same -// positions (slot 8: desc, riid, out as a1-a3; slot 50: a1-a5; and so on). A tail call then writes back only the -// values it read from those slots. A helper that moved a word to another stack position would overwrite the title's -// frame. xs_proxy_mock_test's mock hit this in an optimized build, and its thunks now pass their words by pointer. -// -// The public HLE Freminet/ScarlettX reports five more Xbox device slots (a third-party observation, not a Microsoft -// ABI); the generic thunk routes them before it forwards anything: 48 CreateCommandQueueX, 73 CreateCommandListX, -// 78 SetFrameIntervalX, 79 ScheduleFrameEventX and 80 WaitFrameEventX. The slots can be moved with LEONIDA_XS_*_SLOT -// for a trace that disagrees. The frame-event calls answer from a per-device token counter: there is no vblank source -// behind the device before a presenter exists, so WaitFrameEventX returns at once with a fresh non-zero token. -#include "d3d12_xs_device.h" -#include "d3d12_trace.h" -#include "../core/config.h" -#include "../core/log.h" -#include "../src/shader_library.h" // leonida::fspx_payload_from_parts for slot 67 - -#include -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace rt::d3d12_xs { -namespace { - -// The retail title calls device slots well past ID3D12Device14 (slot 133 at least); every slot past the PC device's -// vtable goes through the generic thunk and is refused with E_NOTIMPL, so the table must outlast the highest one. -constexpr unsigned kMaxSlots = 192; -static_assert(kMaxSlots > 133, "the proxy table must cover the slots the retail title calls (up to 133)"); - -// Set by the Vulkan device behind the proxy; slot 14 uses it for a console-extended CreateDescriptorHeap. -std::atomic g_console_descriptor_heap{nullptr}; -static_assert(kMaxSlots > 83, "the proxy table must cover ID3D12Device14 (83 slots)"); -static_assert(sizeof(void*) == 8, "the Xbox-ABI proxy is x64-only"); -static_assert(sizeof(D3D12_CPU_DESCRIPTOR_HANDLE) == 8, - "the Xbox handle ABI is an 8-byte value in RAX; the heap thunk converts the PC hidden-pointer form"); -static_assert(sizeof(D3D12_RESOURCE_DESC) == 56, "the measured Xbox description prefix is 56 bytes"); - -struct DeviceProxy { - void** vtable; // offset 0: the caller's ID3D12Device* points here - ID3D12Device* real; // offset 8: the PC device every thunk forwards to - void** real_vtable; - unsigned slot_count; // number of valid entries in real_vtable - std::atomic refs; - // The device's IDXGIDevice1 (see "IDXGIDevice1 on the device" below): a title's IDXGIDevice1* points here. - void** dxgi_vtable; - DxgiAdapterProvider adapter_provider; - std::atomic gpu_thread_priority; - std::atomic max_frame_latency; - // The first-frame subset of SetFrameIntervalX/ScheduleFrameEventX/WaitFrameEventX. Tokens were never measured; - // they start at 1 and only have to be fresh and non-zero for the boot sequence. Waiting returns at once: there is - // no vblank source until a presenter exists, and a bounded zero wait cannot stall the first frame. - std::atomic frame_interval_us{0}; - std::atomic frame_latency{1}; - std::atomic frame_event_scheduled{false}; - std::atomic frame_next_token{1}; - // Takes the three frame calls over when set (set_device_frame_event_sink); the fields above stay unused then. - std::atomic frame_sink{nullptr}; - // Where a PresentX on one of this device's queues goes (set_device_present_sink); null: the call is refused. - std::atomic present_sink{nullptr}; -}; - -constexpr unsigned kHeapSlots = 11; // IUnknown + ID3D12Object + DeviceChild + Pageable + GetDesc + 2 handles - -struct HeapProxy { - void** vtable; // offset 0: the caller's ID3D12DescriptorHeap* points here - ID3D12DescriptorHeap* real; - DeviceProxy* device; // keeps the Xbox-ABI device alive; GetDevice returns it - void** real_vtable; - std::atomic refs; -}; - -std::atomic g_hits[kMaxSlots]; -std::atomic g_first[kMaxSlots]; -std::atomic g_beyond_warned[kMaxSlots]; -std::atomic g_heap_hits[kHeapSlots]; -std::atomic g_heap_first[kHeapSlots]; -// The hit counters are for tests. They count from the first call of a *_slot_hits reader or of -// reset_device_proxy_stats, so the calls of a title, which reads no counter, write no shared counter. -std::atomic g_count_hits{false}; - -// For the readers and the reset. The flag is written one time only. -void start_hit_counts() { - if (!g_count_hits.load(std::memory_order_relaxed)) g_count_hits.store(true, std::memory_order_relaxed); -} - -void count_hit(std::atomic& hits) { - if (g_count_hits.load(std::memory_order_relaxed)) hits.fetch_add(1, std::memory_order_relaxed); -} - -// True for the first call of a slot only. The flag is read first: a compare-exchange takes the cache line for -// writing also when it fails, and the flags of all slots share one or two lines. -bool first_call(std::atomic& seen) { - if (seen.load(std::memory_order_relaxed)) return false; - bool expected = false; - return seen.compare_exchange_strong(expected, true, std::memory_order_relaxed); -} - -bool trace_enabled() { - // d3d12.xs_trace (XS_TRACE): on for a value that does not start with 0. A value of 8 characters or more is - // ignored, as before the setting moved to the table. - static const bool enabled = [] { - const std::string value = rt::config::get("d3d12.xs_trace").text; - return !value.empty() && value.size() < 8 && value[0] != '0'; - }(); - return enabled; -} - -const char* slot_name(unsigned slot) { - switch (slot) { - case 0: return "QueryInterface"; - case 1: return "AddRef"; - case 2: return "Release"; - case 8: return "CreateCommandQueue -> queue proxy"; - case 9: return "CreateCommandAllocator (PC slot 9)"; - case 10: return "CreateGraphicsPipelineState (PC slot 10)"; - case 11: return "CreateComputePipelineState (PC slot 11)"; - case 14: return "CreateDescriptorHeap"; - case 16: return "CreateRootSignature"; - case 25: return "GetResourceAllocationInfo"; - case 27: return "CreateCommittedResource (PC slot 27)"; - case 31: return "CreateSharedHandle (proxies unwrapped)"; - case 32: return "OpenSharedHandle (a fence comes back wrapped)"; - case 34: return "MakeResident (proxies unwrapped)"; - case 35: return "Evict (proxies unwrapped)"; - case 36: return "CreateFence -> fence proxy"; - case 43: return "GetAdapterLuid"; - case 45: return "SetEventOnMultipleFenceCompletion (fence proxies unwrapped)"; - case 46: return "SetResidencyPriority (proxies unwrapped)"; - case 48: return "Xbox CreateCommandQueueX -> queue proxy"; - case 50: return "EnqueueMakeResident (proxies unwrapped)"; - case 62: return "Xbox CreateComputePipelineState"; - case 67: return "Xbox DeserializeComputePipelineStateX"; - case 73: return "Xbox CreateCommandListX -> PC CreateCommandList"; - case 75: return "CreateCommandQueue1 -> queue proxy"; - case 76: return "Xbox resource creation"; - case 78: return "Xbox SetFrameIntervalX"; - case 79: return "Xbox ScheduleFrameEventX"; - case 80: return "Xbox WaitFrameEventX"; - case 133: return "Xbox CreatePlacedResourceX (a buffer on the title's pages)"; - default: return "forwarded"; - } -} - -void note_slot(unsigned slot) { - if (slot >= kMaxSlots) return; - count_hit(g_hits[slot]); - const bool first = first_call(g_first[slot]); - if (first) { - RT_LOG_DEBUG("d3d12_xs: device slot %u (%s) first call\n", slot, slot_name(slot)); - } else if (slot >= 3 && trace_enabled()) { - RT_LOG_DEBUG("d3d12_xs: device slot %u (%s) call\n", slot, slot_name(slot)); - } -} - -// Xbox device slots (public HLE Freminet/ScarlettX, an observation, not Microsoft documentation). The defaults are -// the HLE's; an environment variable that names another slot in 3..127 replaces one (a whole-table move for a trace -// that disagrees). A value outside that range is logged once and ignored. The table is read once, on the first -// generic slot call, so a test that wants other slots sets the variables before it creates a device. -struct XboxDeviceSlotRoutes { - unsigned frame_interval = 78; // SetFrameIntervalX(output, interval_us, latency, flags) - unsigned schedule_event = 79; // ScheduleFrameEventX(event, offset_us, reserved, flags) - unsigned wait_event = 80; // WaitFrameEventX(event, timeout_ms, reserved, flags, &token) - unsigned queue_x = 48; // CreateCommandQueueX(desc, riid, out) - unsigned list_x = 73; // CreateCommandListX(desc, allocator, initial_state, riid, out) -}; - -// The slot a setting of the table names (its variable, else leonida.toml); `fallback` when nothing sets it. The -// messages name the variable also when the value came from the file. -unsigned env_device_slot(rt::config::Name setting, unsigned fallback) { - const char* name = setting.setting().variable; - const rt::config::Value configured = rt::config::get(setting); - if (!configured.is_set()) return fallback; - const std::string& value = configured.text; - if (value.size() >= 32) { // the size of the buffer the variable was read into before it moved to the table - RT_LOG_WARN("d3d12_xs: %s is too long for a device slot; the default is kept\n", name); - return fallback; - } - errno = 0; - char* end = nullptr; - const unsigned long slot = std::strtoul(value.c_str(), &end, 0); - if (errno != 0 || end == value.c_str() || *end != '\0' || slot < 3 || slot > 127) { - RT_LOG_WARN("d3d12_xs: %s=%s is not a device slot in 3..127; the default is kept\n", name, - value.c_str()); - return fallback; - } - return static_cast(slot); -} - -const XboxDeviceSlotRoutes& xbox_device_slot_routes() { - static const XboxDeviceSlotRoutes routes = [] { - XboxDeviceSlotRoutes r; - const unsigned frame_interval = env_device_slot("d3d12.frame_interval_slot", r.frame_interval); - const unsigned schedule_event = env_device_slot("d3d12.schedule_event_slot", r.schedule_event); - const unsigned wait_event = env_device_slot("d3d12.wait_event_slot", r.wait_event); - const unsigned queue_x = env_device_slot("d3d12.queue_x_slot", r.queue_x); - const unsigned list_x = env_device_slot("d3d12.list_x_slot", r.list_x); - const bool moved = frame_interval != r.frame_interval || schedule_event != r.schedule_event || - wait_event != r.wait_event || queue_x != r.queue_x || list_x != r.list_x; - r.frame_interval = frame_interval; - r.schedule_event = schedule_event; - r.wait_event = wait_event; - r.queue_x = queue_x; - r.list_x = list_x; - if (moved) - RT_LOG_INFO("d3d12_xs: Xbox device slots: SetFrameIntervalX=%u ScheduleFrameEventX=%u " - "WaitFrameEventX=%u CreateCommandQueueX=%u CreateCommandListX=%u\n", - r.frame_interval, r.schedule_event, r.wait_event, r.queue_x, r.list_x); - return r; - }(); - return routes; -} - -// The public HLE call shapes. SetFrameIntervalX's output and flags are unused while there is no output or pacing; -// ScheduleFrameEventX's reserved event pointer is a3 in the console call and a4 is its flags. The logged words are the -// caller's, so a trace names the slot even when an override moved it. -void log_xbox_route_once(unsigned slot, const char* name, std::uint64_t a1, std::uint64_t a2, std::uint64_t a3, - std::uint64_t a4, std::uint64_t a5) { - static std::atomic logged[kMaxSlots]; - if (slot >= kMaxSlots) return; - bool expected = false; - if (!logged[slot].compare_exchange_strong(expected, true, std::memory_order_relaxed)) return; - RT_LOG_DEBUG("d3d12_xs: device slot %u routed to %s (args 0x%llx 0x%llx 0x%llx 0x%llx 0x%llx)\n", slot, - name, static_cast(a1), static_cast(a2), - static_cast(a3), static_cast(a4), - static_cast(a5)); -} - -const char* heap_slot_name(unsigned slot) { - switch (slot) { - case 0: return "QueryInterface"; - case 1: return "AddRef"; - case 2: return "Release"; - case 7: return "GetDevice"; - case 8: return "GetDesc"; - case 9: return "GetCPUDescriptorHandleForHeapStart"; - case 10: return "GetGPUDescriptorHandleForHeapStart"; - default: return "forwarded"; - } -} - -void note_heap_slot(unsigned slot) { - if (slot >= kHeapSlots) return; - count_hit(g_heap_hits[slot]); - const bool first = first_call(g_heap_first[slot]); - if (first) { - RT_LOG_DEBUG("d3d12_xs: heap slot %u (%s) first call\n", slot, heap_slot_name(slot)); - } else if (slot >= 3 && trace_enabled()) { - RT_LOG_DEBUG("d3d12_xs: heap slot %u (%s) call\n", slot, heap_slot_name(slot)); - } -} - -std::uint64_t hr_to_u64(HRESULT hr) { - return static_cast(static_cast(hr)); -} - -unsigned long proxy_add_ref(DeviceProxy* self) { - note_slot(1); - return self->refs.fetch_add(1, std::memory_order_relaxed) + 1; -} - -unsigned long proxy_release(DeviceProxy* self) { - note_slot(2); - const unsigned long refs = self->refs.fetch_sub(1, std::memory_order_acq_rel) - 1; - if (refs == 0) { - ID3D12Device* real = self->real; - delete self; - if (real) real->Release(); - } - return refs; -} - -bool is_device_iid(const IID& iid) { - if (IsEqualIID(iid, __uuidof(ID3D12Device))) return true; -#ifdef __ID3D12Device14_INTERFACE_DEFINED__ - if (IsEqualIID(iid, __uuidof(ID3D12Device14))) return true; -#endif -#ifdef __ID3D12Device13_INTERFACE_DEFINED__ - if (IsEqualIID(iid, __uuidof(ID3D12Device13))) return true; -#endif -#ifdef __ID3D12Device12_INTERFACE_DEFINED__ - if (IsEqualIID(iid, __uuidof(ID3D12Device12))) return true; -#endif -#ifdef __ID3D12Device11_INTERFACE_DEFINED__ - if (IsEqualIID(iid, __uuidof(ID3D12Device11))) return true; -#endif -#ifdef __ID3D12Device10_INTERFACE_DEFINED__ - if (IsEqualIID(iid, __uuidof(ID3D12Device10))) return true; -#endif -#ifdef __ID3D12Device9_INTERFACE_DEFINED__ - if (IsEqualIID(iid, __uuidof(ID3D12Device9))) return true; -#endif - if (IsEqualIID(iid, __uuidof(ID3D12Device8))) return true; - if (IsEqualIID(iid, __uuidof(ID3D12Device7))) return true; - if (IsEqualIID(iid, __uuidof(ID3D12Device6))) return true; - if (IsEqualIID(iid, __uuidof(ID3D12Device5))) return true; - if (IsEqualIID(iid, __uuidof(ID3D12Device4))) return true; - if (IsEqualIID(iid, __uuidof(ID3D12Device3))) return true; - if (IsEqualIID(iid, __uuidof(ID3D12Device2))) return true; - if (IsEqualIID(iid, __uuidof(ID3D12Device1))) return true; - return false; -} - -HRESULT proxy_query_interface(DeviceProxy* self, const IID* riid, void** out) { - note_slot(0); - if (!out) return E_POINTER; - *out = nullptr; - if (!riid) return E_POINTER; - if (IsEqualIID(*riid, __uuidof(IUnknown)) || IsEqualIID(*riid, __uuidof(ID3D12Object))) { - *out = self; - proxy_add_ref(self); - return S_OK; - } - if (IsEqualIID(*riid, __uuidof(IDXGIObject)) || IsEqualIID(*riid, __uuidof(IDXGIDevice)) || - IsEqualIID(*riid, __uuidof(IDXGIDevice1))) { - *out = &self->dxgi_vtable; - proxy_add_ref(self); - return S_OK; - } - if (!is_device_iid(*riid)) return E_NOINTERFACE; - - // Only claim an interface the PC device really implements; the proxy vtable covers its slots. - void* supported = nullptr; - HRESULT hr = self->real->QueryInterface(*riid, &supported); - if (FAILED(hr)) return hr; - if (!supported) return E_NOINTERFACE; - static_cast(supported)->Release(); - *out = self; - proxy_add_ref(self); - return S_OK; -} - -// ---- IDXGIDevice1 on the device --------------------------------------------------------------------------------- -// -// A GDKX title finds its output through the device: QueryInterface for IDXGIDevice1, GetAdapter, EnumOutputs(0), -// and hands that output to SetFrameIntervalX (docs/d3d12_vulkan.md section 4.5, from the public samples). A PC -// ID3D12Device has no IDXGIDevice, so the proxy answers it itself: a second vtable pointer inside the proxy object, -// with the proxy's reference count and QueryInterface, so the two pointers are one COM object. Only IDXGIDevice and -// IDXGIDevice1 are answered (what the samples ask for). The 14 slots are the public dxgi.h order; that the console -// keeps it is the same assumption as for the queue and the fence. -// -// GetAdapter and GetParent hand out the adapter of the device behind the proxy. The provider says how: the default -// asks the host's DXGI for the adapter with the device's LUID (the host backend); set_device_adapter_provider puts -// the Vulkan layer's own adapter there, so that backend never loads the host's dxgi.dll for it. -constexpr unsigned kDxgiDeviceSlots = 14; // IUnknown 3, IDXGIObject 4, IDXGIDevice 5, IDXGIDevice1 2 - -DeviceProxy* dxgi_owner(void* self) { - return reinterpret_cast(static_cast(self) - offsetof(DeviceProxy, dxgi_vtable)); -} - -HRESULT host_adapter(ID3D12Device* real, REFIID riid, void** out) { - using CreateFactoryFn = HRESULT(WINAPI*)(REFIID, void**); - static const CreateFactoryFn create_factory = [] { - const HMODULE dxgi = LoadLibraryExA("dxgi.dll", nullptr, LOAD_LIBRARY_SEARCH_SYSTEM32); - return dxgi ? reinterpret_cast( - reinterpret_cast(GetProcAddress(dxgi, "CreateDXGIFactory1"))) - : nullptr; - }(); - if (!create_factory) return DXGI_ERROR_NOT_FOUND; - IDXGIFactory4* factory = nullptr; - HRESULT hr = create_factory(__uuidof(IDXGIFactory4), reinterpret_cast(&factory)); - if (FAILED(hr) || !factory) return FAILED(hr) ? hr : DXGI_ERROR_NOT_FOUND; - hr = factory->EnumAdapterByLuid(real->GetAdapterLuid(), riid, out); - factory->Release(); - return hr; -} - -HRESULT dxgi_adapter(DeviceProxy* self, REFIID riid, void** out) { - if (!out) return E_POINTER; - *out = nullptr; - const DxgiAdapterProvider provider = self->adapter_provider ? self->adapter_provider : &host_adapter; - const HRESULT hr = provider(self->real, riid, out); - if (FAILED(hr)) *out = nullptr; - return hr; -} - -void note_dxgi(const char* method) { - d3d12_trace::record(method); -} - -HRESULT WINAPI dxgi_query_interface(void* self, const IID* riid, void** out) { - return proxy_query_interface(dxgi_owner(self), riid, out); -} -ULONG WINAPI dxgi_add_ref(void* self) { return proxy_add_ref(dxgi_owner(self)); } -ULONG WINAPI dxgi_release(void* self) { return proxy_release(dxgi_owner(self)); } - -// IDXGIObject's private data is the device's: ID3D12Object has the same three methods with the same arguments. -HRESULT WINAPI dxgi_set_private_data(void* self, const GUID* name, UINT size, const void* data) { - if (!name) return E_INVALIDARG; - return dxgi_owner(self)->real->SetPrivateData(*name, size, data); -} -HRESULT WINAPI dxgi_set_private_data_interface(void* self, const GUID* name, const IUnknown* object) { - if (!name) return E_INVALIDARG; - return dxgi_owner(self)->real->SetPrivateDataInterface(*name, object); -} -HRESULT WINAPI dxgi_get_private_data(void* self, const GUID* name, UINT* size, void* data) { - if (!name) return E_INVALIDARG; - return dxgi_owner(self)->real->GetPrivateData(*name, size, data); -} -HRESULT WINAPI dxgi_get_parent(void* self, const IID* riid, void** out) { - note_dxgi("XboxIDXGIDevice::GetParent"); - if (!riid) return E_POINTER; - return dxgi_adapter(dxgi_owner(self), *riid, out); -} -HRESULT WINAPI dxgi_get_adapter(void* self, IDXGIAdapter** out) { - note_dxgi("XboxIDXGIDevice::GetAdapter"); - return dxgi_adapter(dxgi_owner(self), __uuidof(IDXGIAdapter), reinterpret_cast(out)); -} -// CreateSurface and QueryResourceResidency are D3D10/11-era methods no D3D12 title has a use for; what the console -// answers is not measured, so they are refused and say so once. -HRESULT WINAPI dxgi_create_surface(void*, const DXGI_SURFACE_DESC*, UINT, DXGI_USAGE, const DXGI_SHARED_RESOURCE*, - IDXGISurface** out) { - static std::atomic logged{false}; - if (!logged.exchange(true, std::memory_order_relaxed)) - RT_LOG_WARN("d3d12_xs: IDXGIDevice::CreateSurface is not implemented; returning E_NOTIMPL\n"); - if (out) *out = nullptr; - return E_NOTIMPL; -} -HRESULT WINAPI dxgi_query_resource_residency(void*, IUnknown* const*, DXGI_RESIDENCY*, UINT) { - static std::atomic logged{false}; - if (!logged.exchange(true, std::memory_order_relaxed)) - RT_LOG_WARN("d3d12_xs: IDXGIDevice::QueryResourceResidency is not implemented; returning E_NOTIMPL\n"); - return E_NOTIMPL; -} -// The priority and the frame latency are kept and read back; nothing acts on them (the Xbox presenter's latency is -// SetFrameIntervalX's). The ranges are the documented ones: -7..7, and 1..16 with 0 for the default of 3. -HRESULT WINAPI dxgi_set_gpu_thread_priority(void* self, INT priority) { - if (priority < -7 || priority > 7) return E_INVALIDARG; - dxgi_owner(self)->gpu_thread_priority.store(priority, std::memory_order_relaxed); - return S_OK; -} -HRESULT WINAPI dxgi_get_gpu_thread_priority(void* self, INT* priority) { - if (!priority) return E_POINTER; - *priority = dxgi_owner(self)->gpu_thread_priority.load(std::memory_order_relaxed); - return S_OK; -} -HRESULT WINAPI dxgi_set_maximum_frame_latency(void* self, UINT latency) { - if (latency > 16) return DXGI_ERROR_INVALID_CALL; - dxgi_owner(self)->max_frame_latency.store(latency ? latency : 3, std::memory_order_relaxed); - return S_OK; -} -HRESULT WINAPI dxgi_get_maximum_frame_latency(void* self, UINT* latency) { - if (!latency) return E_POINTER; - *latency = dxgi_owner(self)->max_frame_latency.load(std::memory_order_relaxed); - return S_OK; -} - -void** get_dxgi_vtable() { - static void* table[kDxgiDeviceSlots] = { - reinterpret_cast(&dxgi_query_interface), // 0 - reinterpret_cast(&dxgi_add_ref), // 1 - reinterpret_cast(&dxgi_release), // 2 - reinterpret_cast(&dxgi_set_private_data), // 3 IDXGIObject - reinterpret_cast(&dxgi_set_private_data_interface), - reinterpret_cast(&dxgi_get_private_data), - reinterpret_cast(&dxgi_get_parent), - reinterpret_cast(&dxgi_get_adapter), // 7 IDXGIDevice - reinterpret_cast(&dxgi_create_surface), - reinterpret_cast(&dxgi_query_resource_residency), - reinterpret_cast(&dxgi_set_gpu_thread_priority), - reinterpret_cast(&dxgi_get_gpu_thread_priority), - reinterpret_cast(&dxgi_set_maximum_frame_latency), // 12 IDXGIDevice1 - reinterpret_cast(&dxgi_get_maximum_frame_latency), - }; - return table; -} - -unsigned long heap_add_ref(HeapProxy* self) { - note_heap_slot(1); - return self->refs.fetch_add(1, std::memory_order_relaxed) + 1; -} - -unsigned long heap_release(HeapProxy* self) { - note_heap_slot(2); - const unsigned long refs = self->refs.fetch_sub(1, std::memory_order_acq_rel) - 1; - if (refs == 0) { - ID3D12DescriptorHeap* real = self->real; - DeviceProxy* device = self->device; - delete self; - if (real) real->Release(); - if (device) proxy_release(device); - } - return refs; -} - -bool is_heap_iid(const IID& iid) { - return IsEqualIID(iid, __uuidof(ID3D12DescriptorHeap)) || IsEqualIID(iid, __uuidof(ID3D12Pageable)) || - IsEqualIID(iid, __uuidof(ID3D12DeviceChild)) || IsEqualIID(iid, __uuidof(ID3D12Object)) || - IsEqualIID(iid, __uuidof(IUnknown)); -} - -HRESULT heap_query_interface(HeapProxy* self, const IID* riid, void** out) { - note_heap_slot(0); - if (!out) return E_POINTER; - *out = nullptr; - if (!riid) return E_POINTER; - if (!is_heap_iid(*riid)) return E_NOINTERFACE; - *out = self; - heap_add_ref(self); - return S_OK; -} - -// ID3D12DeviceChild::GetDevice on the heap must hand back the Xbox-ABI device, not the raw PC device. -HRESULT heap_get_device(HeapProxy* self, const IID* riid, void** out) { - note_heap_slot(7); - if (!out) return E_POINTER; - *out = nullptr; - if (!riid) return E_POINTER; - if (!self->device) return E_NOINTERFACE; - return proxy_query_interface(self->device, riid, out); -} - -// The PC methods write through the hidden return pointer (RDX) on the measured runtime; the Xbox ABI wants the -// 8-byte value in RAX. Call with both conventions and keep whichever produced a value, so a runtime that really -// returns in RAX also works. The extra register is harmless when the callee ignores it. -D3D12_CPU_DESCRIPTOR_HANDLE heap_get_cpu_handle(HeapProxy* self) { - note_heap_slot(9); - constexpr SIZE_T kUnset = ~static_cast(0); - D3D12_CPU_DESCRIPTOR_HANDLE handle{}; - handle.ptr = kUnset; - using Fn = D3D12_CPU_DESCRIPTOR_HANDLE(WINAPI*)(ID3D12DescriptorHeap*, D3D12_CPU_DESCRIPTOR_HANDLE*); - const D3D12_CPU_DESCRIPTOR_HANDLE returned = - reinterpret_cast(self->real_vtable[9])(self->real, &handle); - return handle.ptr != kUnset ? handle : returned; -} - -D3D12_GPU_DESCRIPTOR_HANDLE heap_get_gpu_handle(HeapProxy* self) { - note_heap_slot(10); - constexpr UINT64 kUnset = ~static_cast(0); - D3D12_GPU_DESCRIPTOR_HANDLE handle{}; - handle.ptr = kUnset; - using Fn = D3D12_GPU_DESCRIPTOR_HANDLE(WINAPI*)(ID3D12DescriptorHeap*, D3D12_GPU_DESCRIPTOR_HANDLE*); - const D3D12_GPU_DESCRIPTOR_HANDLE returned = - reinterpret_cast(self->real_vtable[10])(self->real, &handle); - return handle.ptr != kUnset ? handle : returned; -} - -template -std::uint64_t WINAPI heap_slot(HeapProxy* self, std::uint64_t a1, std::uint64_t a2, std::uint64_t a3, - std::uint64_t a4, std::uint64_t a5, std::uint64_t a6, std::uint64_t a7, - std::uint64_t a8, std::uint64_t a9, std::uint64_t a10, std::uint64_t a11, - std::uint64_t a12, std::uint64_t a13, std::uint64_t a14) { - if constexpr (Slot == 0) { - return hr_to_u64(heap_query_interface(self, reinterpret_cast(a1), - reinterpret_cast(a2))); - } else if constexpr (Slot == 1) { - return heap_add_ref(self); - } else if constexpr (Slot == 2) { - return heap_release(self); - } else if constexpr (Slot == 7) { - return hr_to_u64(heap_get_device(self, reinterpret_cast(a1), - reinterpret_cast(a2))); - } else if constexpr (Slot == 9) { - return static_cast(heap_get_cpu_handle(self).ptr); - } else if constexpr (Slot == 10) { - return static_cast(heap_get_gpu_handle(self).ptr); - } else { - note_heap_slot(Slot); - using ForwardFn = std::uint64_t(WINAPI*)(void*, std::uint64_t, std::uint64_t, std::uint64_t, - std::uint64_t, std::uint64_t, std::uint64_t, std::uint64_t, - std::uint64_t, std::uint64_t, std::uint64_t, std::uint64_t, - std::uint64_t, std::uint64_t, std::uint64_t); - auto fn = reinterpret_cast(self->real_vtable[Slot]); - return fn(self->real, a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14); - } -} - -template -void fill_heap_vtable(void** vtable, std::index_sequence) { - ((vtable[I] = reinterpret_cast(&heap_slot(I)>) ), ...); -} - -void** get_heap_vtable() { - static void** vtable = [] { - static void* storage[kHeapSlots]; - fill_heap_vtable(storage, std::make_index_sequence{}); - return storage; - }(); - return vtable; -} - -HRESULT create_heap_proxy(ID3D12DescriptorHeap* real, DeviceProxy* device, REFIID riid, void** out) { - if (!real || !device) return E_POINTER; - if (!out) return E_POINTER; - *out = nullptr; - - HeapProxy* proxy = new (std::nothrow) HeapProxy; - if (!proxy) return E_OUTOFMEMORY; - proxy->vtable = get_heap_vtable(); - proxy->real = real; - proxy->device = device; - proxy->real_vtable = *reinterpret_cast(real); - proxy->refs.store(1, std::memory_order_relaxed); - proxy_add_ref(device); // the heap keeps its Xbox-ABI device alive for GetDevice - - const HRESULT hr = heap_query_interface(proxy, &riid, out); - if (FAILED(hr)) { - // No reference escaped, and the caller still owns its references to `real` and `device`. - delete proxy; - proxy_release(device); - return hr; - } - if (!d3d12_trace::enabled()) - RT_LOG_DEBUG("d3d12_xs: heap proxy %p wraps PC heap %p (device proxy %p)\n", - static_cast(proxy), static_cast(real), static_cast(device)); - heap_release(proxy); - return S_OK; -} - -// ---- Command queue and fence proxies -------------------------------------------------------------------------- -// -// Device slots 8 (CreateCommandQueue), 75 (CreateCommandQueue1), 36 (CreateFence) and 32 (OpenSharedHandle, for a -// fence) wrap what they create, so a title never holds a PC or Vulkan-layer queue or fence. The proxies forward -// the public chain in PC order, exactly like the device proxy, and a slot past the PC vtable is logged and refused -// with E_NOTIMPL. PresentX, SuspendX and ResumeX are queue methods past the public chain -// (docs/d3d12_command_objects.md §5.3). Their slots are not known and nothing is guessed: the first run of the -// executable names them in the log. PresentX alone has a route, at the slot a setting names (present_x_slot below). -// -// Slot numbers are those of the Windows SDK 10.0.26100 d3d12.h: ID3D12CommandQueue has 19, ID3D12Fence 11 and -// ID3D12Fence1 12. That the console keeps these public slots, and keeps device slots 8/32/36/75, is an assumption -// the shipped binaries cannot test (§3.5: the package has no queue or fence client). Every queue and fence method -// takes integer and pointer arguments only; GetDesc returns its struct through the hidden pointer in RDX, which is -// forwarded unchanged (no Xbox variant is measured, §6). -// -// The refused range is the proxy's own table: 128 queue slots and 64 fence slots, every one a thunk. The table sits -// at the end of the first page of a 64 KiB reservation whose other pages are never committed, so a slot index past -// the table makes the vtable read itself fault, at an address that names the slot (a vectored handler logs it and -// lets the fault continue), instead of jumping through whatever memory follows. A title whose vtable read lands -// further away than that reservation is not covered. -// -// Objects cross back into the real runtime wherever a device or queue method takes them, and the real object is -// passed there: queue Signal/Wait (14/15) take a fence; device CreateSharedHandle (31) a device child, -// MakeResident/Evict (34/35), SetResidencyPriority (46) and EnqueueMakeResident (50) pageables, and -// SetEventOnMultipleFenceCompletion (45) and EnqueueMakeResident fences. The heap proxies of slot 14 are pageables -// and device children too and are unwrapped in the same places. Command lists are not wrapped yet, so -// ExecuteCommandLists passes them through, and a heap proxy still reaches the real runtime through the list's -// SetDescriptorHeaps. A command-list proxy (docs/d3d12_command_objects.md §3.5a) adds its vtable to -// proxy_real_object, which every unwrap goes through, and a queue slot 10 branch in child_slot that unwraps the list -// array (UnwrappedArray) before forwarding, and unwraps heap proxies in its own SetDescriptorHeaps. -// -// QueryInterface answers only the interfaces the proxy models (the base chain and its own interface, Fence1 when -// the real fence has it), like the device and heap proxies, so the COM identity holds and no real object leaks to -// the title. Leonida's own code reaches the real object through queue_proxy_real_queue / fence_proxy_real_fence / -// allocator_proxy_real_allocator. -// -// Command allocators (device slot 9) are the third kind: their public chain is 9 slots (Reset at 8). Slot 9 wraps -// only an allocator that answers kLeonidaCommandAllocatorTag, because a list takes the title's allocator in -// CreateCommandList and Reset and only the Vulkan layer's lists resolve a proxy there (CommandAllocator::from); -// a PC runtime allocator is handed out unchanged until a command-list proxy unwraps it at Reset. - -enum class ChildKind { queue, fence, allocator }; - -constexpr unsigned kQueueSlots = 128; // the table: 19 public slots plus a refused tail -constexpr unsigned kFenceSlots = 64; // the table: 12 public slots plus a refused tail -constexpr unsigned kQueuePublicSlots = 19; // ID3D12CommandQueue -constexpr unsigned kFencePublicSlots = 11; // ID3D12Fence -constexpr unsigned kFence1PublicSlots = 12; // ID3D12Fence1 -constexpr unsigned kAllocatorSlots = 64; // the table: 9 public slots plus a refused tail -constexpr unsigned kAllocatorPublicSlots = 9; // ID3D12CommandAllocator: the base chain and Reset (slot 8) -constexpr SIZE_T kTableRegion = 64 * 1024; // one allocation granule: the table page plus 15 never-committed pages -static_assert(kQueueSlots > kQueuePublicSlots && kFenceSlots > kFence1PublicSlots && - kAllocatorSlots > kAllocatorPublicSlots, - "the tables need a tail"); -static_assert(kQueueSlots * sizeof(void*) <= 4096 && kFenceSlots * sizeof(void*) <= 4096 && - kAllocatorSlots * sizeof(void*) <= 4096, - "a table must fit in the first page of its reservation"); - -constexpr unsigned kQueueSignal = 14, kQueueWait = 15; // (ID3D12Fence*, UINT64) - -struct ChildProxy { - void** vtable; // offset 0: the caller's ID3D12CommandQueue* / ID3D12Fence* points here - IUnknown* real; // offset 8: the PC or Vulkan-layer object every thunk forwards to - DeviceProxy* device; // keeps the Xbox-ABI device alive; GetDevice returns it - void** real_vtable; - unsigned slot_count; // public slots the real object implements; the rest of the table is refused - std::atomic refs; -}; - -template -struct ChildStats { - static constexpr unsigned kSlots = K == ChildKind::queue ? kQueueSlots - : K == ChildKind::fence ? kFenceSlots - : kAllocatorSlots; - static inline std::atomic hits[kSlots]; - static inline std::atomic first[kSlots]; - static inline std::atomic beyond_warned[kSlots]; - static inline std::atomic overruns{0}; - // Where the table and its reservation are: written once, before the table is handed out. - static inline std::atomic table_begin{0}, table_end{0}, region_end{0}; -}; - -template -constexpr const char* child_kind_name() { - return K == ChildKind::queue ? "queue" : K == ChildKind::fence ? "fence" : "allocator"; -} - -template -const char* child_public_name(unsigned slot) { - static constexpr const char* object[] = {"QueryInterface", "AddRef", "Release", "GetPrivateData", - "SetPrivateData", "SetPrivateDataInterface", "SetName", "GetDevice"}; - static constexpr const char* queue[] = {"UpdateTileMappings", "CopyTileMappings", "ExecuteCommandLists", - "SetMarker", "BeginEvent", "EndEvent", "Signal", "Wait", - "GetTimestampFrequency", "GetClockCalibration", "GetDesc"}; - static constexpr const char* fence[] = {"GetCompletedValue", "SetEventOnCompletion", "Signal", - "GetCreationFlags"}; - if (slot < 8) return object[slot]; - if constexpr (K == ChildKind::queue) { - if (slot < kQueuePublicSlots) return queue[slot - 8]; - } else if constexpr (K == ChildKind::fence) { - if (slot < kFence1PublicSlots) return fence[slot - 8]; - } else { - if (slot == 8) return "Reset"; - } - return nullptr; -} - -// Fixed names for the trace channel (d3d12_trace::record takes fixed strings): one per table slot, built once, in -// the trace grammar of runtime/README.md and check_d3d12_trace.py (an identifier with `::`, no spaces): -// XboxID3D12CommandQueue::Signal, and XboxID3D12CommandQueue::Slot40 for a slot past the public chain. -template -const char* child_trace_name(unsigned slot) { - static const auto names = [] { - static char storage[ChildStats::kSlots][64]; - const char* iface = K == ChildKind::queue ? "XboxID3D12CommandQueue" - : K == ChildKind::fence ? "XboxID3D12Fence" - : "XboxID3D12CommandAllocator"; - for (unsigned s = 0; s < ChildStats::kSlots; ++s) { - const char* method = child_public_name(s); - if (method) - std::snprintf(storage[s], sizeof(storage[s]), "%s::%s", iface, method); - else - std::snprintf(storage[s], sizeof(storage[s]), "%s::Slot%u", iface, s); - } - return &storage; - }(); - return (*names)[slot < ChildStats::kSlots ? slot : 0]; -} - -template -void note_child_slot(unsigned slot) { - using S = ChildStats; - if (slot >= S::kSlots) return; - count_hit(S::hits[slot]); - const bool first = first_call(S::first[slot]); - const char* method = child_public_name(slot); - if (first) { - RT_LOG_DEBUG("d3d12_xs: %s slot %u (%s) first call\n", child_kind_name(), slot, - method ? method : "past the public chain"); - } else if (slot >= 3 && trace_enabled()) { - RT_LOG_DEBUG("d3d12_xs: %s slot %u (%s) call\n", child_kind_name(), slot, - method ? method : "past the public chain"); - } -} - -// The counters reset_device_proxy_stats clears for one kind: per-slot hits, first-call and beyond-table flags, and -// the faulted reads past the table. -template -void reset_child_stats() { - using S = ChildStats; - for (unsigned slot = 0; slot < S::kSlots; ++slot) { - S::hits[slot].store(0, std::memory_order_relaxed); - S::first[slot].store(false, std::memory_order_relaxed); - S::beyond_warned[slot].store(false, std::memory_order_relaxed); - } - S::overruns.store(0, std::memory_order_relaxed); -} - -// Frees a proxy whose last reference is gone, with the real object and the device reference it held. -void destroy_child(ChildProxy* self) { - IUnknown* real = self->real; - DeviceProxy* device = self->device; - delete self; - if (real) real->Release(); - if (device) proxy_release(device); -} - -template -unsigned long child_add_ref(ChildProxy* self) { - note_child_slot(1); - return self->refs.fetch_add(1, std::memory_order_relaxed) + 1; -} - -template -unsigned long child_release(ChildProxy* self) { - note_child_slot(2); - const unsigned long refs = self->refs.fetch_sub(1, std::memory_order_acq_rel) - 1; - if (refs == 0) destroy_child(self); - return refs; -} - -// The interfaces the proxy answers: the base chain and the object's own interface. -template -bool is_child_iid(const IID& iid) { - if (IsEqualIID(iid, __uuidof(IUnknown)) || IsEqualIID(iid, __uuidof(ID3D12Object)) || - IsEqualIID(iid, __uuidof(ID3D12DeviceChild)) || IsEqualIID(iid, __uuidof(ID3D12Pageable))) - return true; - if constexpr (K == ChildKind::queue) { - return IsEqualIID(iid, __uuidof(ID3D12CommandQueue)); - } else if constexpr (K == ChildKind::fence) { - return IsEqualIID(iid, __uuidof(ID3D12Fence)) || IsEqualIID(iid, __uuidof(ID3D12Fence1)); - } else { - return IsEqualIID(iid, __uuidof(ID3D12CommandAllocator)); - } -} - -bool supports_iid(IUnknown* real, REFIID iid) { - void* found = nullptr; - const HRESULT hr = real->QueryInterface(iid, &found); - if (FAILED(hr) || !found) return false; - static_cast(found)->Release(); - return true; -} - -// An interface the real object implements but the proxy does not model is refused where the PC runtime would answer: -// logged once per interface (the first 32 of them), so a title that stops after such a refusal shows what it asked -// for. Also reached from wrap_child, for the interface a title creates a queue or fence as. -void log_refused_iid(const char* kind, const IID& iid) { - static SRWLOCK lock = SRWLOCK_INIT; - static IID seen[32]; - static unsigned count = 0; - AcquireSRWLockExclusive(&lock); - bool known = false; - for (unsigned i = 0; i < count && !known; ++i) known = IsEqualIID(seen[i], iid) != 0; - const bool log = !known && count < std::size(seen); - if (log) seen[count++] = iid; - ReleaseSRWLockExclusive(&lock); - if (!log) return; - RT_LOG_WARN("d3d12_xs: %s proxy refuses {%08lX-%04X-%04X-%02X%02X-%02X%02X%02X%02X%02X%02X}, which the real " - "object implements; E_NOINTERFACE\n", - kind, iid.Data1, iid.Data2, iid.Data3, iid.Data4[0], iid.Data4[1], iid.Data4[2], iid.Data4[3], - iid.Data4[4], iid.Data4[5], iid.Data4[6], iid.Data4[7]); -} - -template -HRESULT child_query_interface(ChildProxy* self, const IID* riid, void** out) { - note_child_slot(0); - if (!out) return E_POINTER; - *out = nullptr; - if (!riid) return E_POINTER; - // Only what the proxy models, and of that only what the real object implements (ID3D12Fence1 is optional). - if (!is_child_iid(*riid)) { - if (supports_iid(self->real, *riid)) log_refused_iid(child_kind_name(), *riid); - return E_NOINTERFACE; - } - if (!supports_iid(self->real, *riid)) return E_NOINTERFACE; - *out = self; - child_add_ref(self); - return S_OK; -} - -// ID3D12DeviceChild::GetDevice hands back the Xbox-ABI device, not the real one. Without an output it is the real -// object's own answer (what the PC runtime returns for a null pointer). -template -HRESULT child_get_device(ChildProxy* self, const IID* riid, void** out) { - note_child_slot(7); - if (out) *out = nullptr; // _COM_Outptr_: NULL on every failure (bc59ef46) - if (!riid) return E_POINTER; - if (!out) { - using Fn = HRESULT(WINAPI*)(IUnknown*, const IID*, void**); - return reinterpret_cast(self->real_vtable[7])(self->real, riid, nullptr); - } - if (!self->device) return E_NOINTERFACE; - return proxy_query_interface(self->device, riid, out); -} - -void** get_heap_vtable(); -void** get_list_vtable(); - -template -void** get_child_vtable(); - -template -bool is_child_proxy(const void* object) { - return object && *reinterpret_cast(object) == reinterpret_cast(get_child_vtable()); -} - -constexpr unsigned kListSlots = 160; -constexpr unsigned kConsoleSetDescriptorHeaps = 32; -constexpr unsigned kConsoleExecuteBundle = 31; -constexpr unsigned kConsoleBarrier = 146; - -struct ListProxy { - void** vtable; // +0x00 - ID3D12GraphicsCommandList* real; // +0x08 - DeviceProxy* device; // +0x10: keeps the Xbox-ABI device alive; GetDevice returns it - // +0x18..: the console object body a title's inline writers read. +0x18 holds the write cursor, +0x28 and - // +0x30 the record limits; the rest is room for the measured flags, header table and pipeline record. - alignas(8) std::uint8_t console_fields[0x600]; - std::atomic refs; // past the console body - unsigned pc_slot_count; // slots the real list implements; mapped slots past it are refused - - void pin_cursor_at_limit() { - const std::uint64_t at_limit = static_cast( - reinterpret_cast(this) + 0x18 + 0x500); - for (const size_t offset : {0x18, 0x28, 0x30}) - std::memcpy(reinterpret_cast(this) + offset, &at_limit, sizeof(at_limit)); - } -}; -static_assert(offsetof(ListProxy, console_fields) == 0x18, "the console fields start at +0x18"); - -// The real object behind a heap, queue, fence or list proxy, or null when `object` is none of them. -IUnknown* proxy_real_object(const void* object) { - if (!object) return nullptr; - void* const vtable = *reinterpret_cast(object); - if (vtable == reinterpret_cast(get_heap_vtable())) return static_cast(object)->real; - if (vtable == reinterpret_cast(get_child_vtable()) || - vtable == reinterpret_cast(get_child_vtable()) || - vtable == reinterpret_cast(get_child_vtable())) - return static_cast(object)->real; - if (vtable == reinterpret_cast(get_list_vtable())) - return static_cast(object)->real; - return nullptr; -} - -// `object` with a proxy replaced by its real object; anything else (a real object, null) unchanged. -inline std::uint64_t unwrap_object(std::uint64_t object) { - IUnknown* real = proxy_real_object(reinterpret_cast(object)); - return real ? reinterpret_cast(real) : object; -} - -// A copy of an array of interface pointers with every proxy replaced by its real object. Nothing here throws, since -// an exception must not leave a thunk for the title's code: up to 16 entries are kept inline (no allocation, which -// also suits a per-frame ExecuteCommandLists), a longer array is allocated with new (std::nothrow). -class UnwrappedArray { -public: - // Copies `count` entries (a UINT in every PC prototype) of `objects`. False on allocation failure. - bool fill(std::uint64_t objects, std::uint64_t count) { - const auto n = static_cast(count); - if (!objects || !n) return true; - std::uint64_t* copy = inline_; - if (n > std::size(inline_)) { - heap_.reset(new (std::nothrow) std::uint64_t[n]); - if (!heap_) return false; - copy = heap_.get(); - } - const auto* in = reinterpret_cast(objects); - for (std::uint32_t i = 0; i < n; ++i) copy[i] = unwrap_object(in[i]); - data_ = copy; - return true; - } - // The copy to pass on, or 0 when there was no array (the caller's argument then goes on unchanged). - std::uint64_t data() const { return reinterpret_cast(data_); } - -private: - std::uint64_t inline_[16]; - std::unique_ptr heap_; - std::uint64_t* data_ = nullptr; -}; - -struct ListStats { - static inline std::atomic hits[kListSlots]; - static inline std::atomic first[kListSlots]; -}; - -inline void note_list_slot(unsigned slot, std::uint64_t a1 = 0, std::uint64_t a2 = 0, std::uint64_t a3 = 0, std::uint64_t a4 = 0) { - if (slot >= kListSlots) return; - ListStats::hits[slot].fetch_add(1, std::memory_order_relaxed); - bool expected = false; - if (ListStats::first[slot].compare_exchange_strong(expected, true, std::memory_order_relaxed)) - RT_LOG_DEBUG("d3d12_xs: list slot %u first call (args 0x%llx 0x%llx 0x%llx 0x%llx)\n", slot, - static_cast(a1), static_cast(a2), - static_cast(a3), static_cast(a4)); -} - -inline bool is_list_iid(const IID& iid) { - return IsEqualIID(iid, __uuidof(IUnknown)) || IsEqualIID(iid, __uuidof(ID3D12Object)) || - IsEqualIID(iid, __uuidof(ID3D12DeviceChild)) || IsEqualIID(iid, __uuidof(ID3D12CommandList)) || - IsEqualIID(iid, __uuidof(ID3D12GraphicsCommandList)) || - IsEqualIID(iid, __uuidof(ID3D12GraphicsCommandList1)) || - IsEqualIID(iid, __uuidof(ID3D12GraphicsCommandList2)) || - IsEqualIID(iid, __uuidof(ID3D12GraphicsCommandList3)) || - IsEqualIID(iid, __uuidof(ID3D12GraphicsCommandList4)) || - IsEqualIID(iid, __uuidof(ID3D12GraphicsCommandList5)) || - IsEqualIID(iid, __uuidof(ID3D12GraphicsCommandList6)) || - IsEqualIID(iid, __uuidof(ID3D12GraphicsCommandList7)) || - IsEqualIID(iid, __uuidof(ID3D12GraphicsCommandList8)); -} - -inline unsigned long list_add_ref(ListProxy* self) { return self->refs.fetch_add(1, std::memory_order_relaxed) + 1; } - -inline void destroy_list(ListProxy* self) { - IUnknown* real = self->real; - DeviceProxy* device = self->device; - delete self; - if (real) real->Release(); - if (device) proxy_release(device); -} - -inline unsigned long list_release(ListProxy* self) { - const unsigned long refs = self->refs.fetch_sub(1, std::memory_order_acq_rel) - 1; - if (refs == 0) destroy_list(self); - return refs; -} - -inline HRESULT list_query_interface(ListProxy* self, const IID* riid, void** out) { - note_list_slot(0, reinterpret_cast(riid), reinterpret_cast(out), 0, 0); - if (!out) return E_POINTER; - *out = nullptr; - if (!riid) return E_POINTER; - if (!is_list_iid(*riid)) { - if (supports_iid(self->real, *riid)) log_refused_iid("list", *riid); - return E_NOINTERFACE; - } - if (!supports_iid(self->real, *riid)) return E_NOINTERFACE; - *out = self; - list_add_ref(self); - return S_OK; -} - -inline unsigned detect_list_slot_count(IUnknown* real) { - if (supports_iid(real, __uuidof(ID3D12GraphicsCommandList8))) return 82; - if (supports_iid(real, __uuidof(ID3D12GraphicsCommandList7))) return 81; - if (supports_iid(real, __uuidof(ID3D12GraphicsCommandList6))) return 80; - if (supports_iid(real, __uuidof(ID3D12GraphicsCommandList5))) return 79; - if (supports_iid(real, __uuidof(ID3D12GraphicsCommandList4))) return 77; - if (supports_iid(real, __uuidof(ID3D12GraphicsCommandList3))) return 68; - if (supports_iid(real, __uuidof(ID3D12GraphicsCommandList2))) return 67; - if (supports_iid(real, __uuidof(ID3D12GraphicsCommandList1))) return 66; - if (supports_iid(real, __uuidof(ID3D12GraphicsCommandList))) return 60; - return 9; -} - -template -std::uint64_t WINAPI list_slot(ListProxy* self, std::uint64_t a1, std::uint64_t a2, std::uint64_t a3, - std::uint64_t a4, std::uint64_t a5, std::uint64_t a6, std::uint64_t a7, - std::uint64_t a8, std::uint64_t a9, std::uint64_t a10, std::uint64_t a11, - std::uint64_t a12, std::uint64_t a13, std::uint64_t a14) { - if constexpr (Slot == 0) { - return hr_to_u64(list_query_interface(self, reinterpret_cast(a1), - reinterpret_cast(a2))); - } else if constexpr (Slot == 1) { - return list_add_ref(self); - } else if constexpr (Slot == 2) { - return list_release(self); - } else if constexpr (Slot == 7) { // GetDevice - note_list_slot(7, a1, a2, 0, 0); - if (a2) *reinterpret_cast(a2) = nullptr; - if (!a1) return hr_to_u64(E_POINTER); - if (!a2) { - using Fn = HRESULT(WINAPI*)(IUnknown*, const IID*, void**); - return hr_to_u64(reinterpret_cast((*reinterpret_cast(self->real))[7])( - self->real, reinterpret_cast(a1), nullptr)); - } - return hr_to_u64(proxy_query_interface(self->device, reinterpret_cast(a1), - reinterpret_cast(a2))); - } else { - note_list_slot(Slot, a1, a2, a3, a4); - constexpr unsigned pc = console_to_pc_list_slot(Slot); - if constexpr (pc == kListNotForwarded) { - if constexpr (Slot == 148) { - static std::atomic logged{false}; - if (!logged.exchange(true, std::memory_order_relaxed)) - RT_LOG_WARN( - "d3d12_xs: console list slot 148 AllocateUploadMemory stub called (size %llu, align %llu)\n", - static_cast(a1), static_cast(a2)); - } - return 0; - } else { - if (pc >= self->pc_slot_count) { - static std::atomic beyond_warned[kListSlots]; - bool expected = false; - if (beyond_warned[Slot].compare_exchange_strong(expected, true, std::memory_order_relaxed)) - RT_LOG_WARN("d3d12_xs: list slot %u maps to PC slot %u, beyond the real list's %u " - "slots; returning E_NOTIMPL\n", - Slot, pc, self->pc_slot_count); - return hr_to_u64(E_NOTIMPL); - } - using ForwardFn = std::uint64_t(WINAPI*)(void*, std::uint64_t, std::uint64_t, std::uint64_t, - std::uint64_t, std::uint64_t, std::uint64_t, - std::uint64_t, std::uint64_t, std::uint64_t, - std::uint64_t, std::uint64_t, std::uint64_t, - std::uint64_t, std::uint64_t); - auto** const real_vtable = *reinterpret_cast(self->real); - UnwrappedArray heaps; - if constexpr (Slot == 10) { - a1 = unwrap_object(a1); - self->pin_cursor_at_limit(); - } else if constexpr (Slot == kConsoleExecuteBundle) { - a1 = unwrap_object(a1); - } else if constexpr (Slot == kConsoleSetDescriptorHeaps) { - if (!heaps.fill(a2, a1)) return 0; - if (heaps.data()) a2 = heaps.data(); - } - return reinterpret_cast(real_vtable[pc])(self->real, a1, a2, a3, a4, a5, a6, a7, a8, a9, - a10, a11, a12, a13, a14); - } - } -} - -template -void fill_list_vtable(void** vtable, std::index_sequence) { - ((vtable[I] = reinterpret_cast(&list_slot(I)>)), ...); -} - -void** get_list_vtable() { - static void** vtable = [] { - static void* storage[kListSlots]; - fill_list_vtable(storage, std::make_index_sequence{}); - return storage; - }(); - return vtable; -} - -HRESULT wrap_list(IUnknown* created, DeviceProxy* device, const IID* riid, void** out) { - if (out) *out = nullptr; - if (!created) return E_FAIL; - auto* proxy = new (std::nothrow) ListProxy(); - if (!proxy) { - created->Release(); - return E_OUTOFMEMORY; - } - proxy->vtable = get_list_vtable(); - proxy->real = static_cast(created); - proxy->device = device; - proxy->refs.store(1, std::memory_order_relaxed); - proxy->pc_slot_count = detect_list_slot_count(created); - proxy->pin_cursor_at_limit(); - proxy_add_ref(device); - - const HRESULT hr = list_query_interface(proxy, riid, out); - if (FAILED(hr)) { - destroy_list(proxy); - return hr; - } - static std::atomic logged{false}; - if (!d3d12_trace::enabled() && (!logged.exchange(true, std::memory_order_relaxed) || trace_enabled())) - RT_LOG_DEBUG("d3d12_xs: list proxy %p wraps %p (%u PC vtable slots)\n", - static_cast(proxy), static_cast(created), proxy->pc_slot_count); - proxy->refs.fetch_sub(1, std::memory_order_relaxed); - return S_OK; -} - -// The vtable read for a slot past a table faults in the reservation behind it; name the slot. Only reads the -// exception record and writes with WriteFile, so it is safe whatever the faulting thread holds. -template -void report_table_overrun(std::uintptr_t address) { - using S = ChildStats; - const std::uintptr_t begin = S::table_begin.load(std::memory_order_acquire); - const std::uintptr_t end = S::table_end.load(std::memory_order_acquire); - const std::uintptr_t limit = S::region_end.load(std::memory_order_acquire); - if (!end || address < end || address >= limit) return; - S::overruns.fetch_add(1, std::memory_order_relaxed); - // An error line of the log (core/log.h). It is put together and written by hand because this runs inside the - // fault handler; the level is one atomic read. - if (!::rt::log::enabled(::rt::log::Level::Error)) return; - char line[160]; - unsigned long long slot = (address - begin) / sizeof(void*); - char digits[24]; - int d = 0; - do { - digits[d++] = static_cast('0' + slot % 10); - slot /= 10; - } while (slot && d < 23); - int n = 0; - const auto put = [&](const char* text) { - while (*text && n < static_cast(sizeof(line)) - 1) line[n++] = *text++; - }; - put("[rt] d3d12_xs: "); - put(child_kind_name()); - put(" slot "); - while (d > 0 && n < static_cast(sizeof(line)) - 1) line[n++] = digits[--d]; - put(" is past the proxy table; the vtable read faults\n"); - DWORD written = 0; - WriteFile(GetStdHandle(STD_ERROR_HANDLE), line, static_cast(n), &written, nullptr); -} - -LONG CALLBACK table_overrun_handler(EXCEPTION_POINTERS* info) { - const EXCEPTION_RECORD* record = info ? info->ExceptionRecord : nullptr; - if (record && record->ExceptionCode == EXCEPTION_ACCESS_VIOLATION && record->NumberParameters >= 2) { - const auto address = static_cast(record->ExceptionInformation[1]); - report_table_overrun(address); - report_table_overrun(address); - report_table_overrun(address); - } - return EXCEPTION_CONTINUE_SEARCH; // diagnostics only: the fault goes on to the title's handlers or the crash -} - -// PresentX on the queue (PresentSink in d3d12_xs_device.h). Its slot is the one d3d12.present_x_slot -// (LEONIDA_XS_PRESENT_X_SLOT) names, read once: a slot of the refused tail, or 0 when the setting names none or its -// value is not such a slot (logged once). No default is taken from the public numbers: they are other titles'. -unsigned present_x_slot() { - static const unsigned slot = [] { - const rt::config::Name setting("d3d12.present_x_slot"); - const char* name = setting.setting().variable; - const rt::config::Value configured = rt::config::get(setting); - if (!configured.is_set()) return 0u; - const std::string& value = configured.text; - errno = 0; - char* end = nullptr; - const unsigned long parsed = value.size() < 32 ? std::strtoul(value.c_str(), &end, 0) : 0; - if (value.size() >= 32 || errno != 0 || end == value.c_str() || *end != '\0' || - parsed < kQueuePublicSlots || parsed >= kQueueSlots) { - RT_LOG_WARN("d3d12_xs: %s=%.40s is not a queue slot in %u..%u; no slot is taken for PresentX\n", name, - value.c_str(), kQueuePublicSlots, kQueueSlots - 1); - return 0u; - } - RT_LOG_INFO("d3d12_xs: Xbox queue slot: PresentX=%lu\n", parsed); - return static_cast(parsed); - }(); - return slot; -} - -// A call on the PresentX slot: PresentX(plane count, planes, parameters). It goes to the present sink of the queue's -// device with the real queue behind the proxy; without a sink it is refused like the rest of the tail, with a line -// that says why. -HRESULT queue_present_x(ChildProxy* self, unsigned slot, std::uint64_t plane_count, std::uint64_t planes, - std::uint64_t params) { - const PresentSink* sink = self->device ? self->device->present_sink.load(std::memory_order_acquire) : nullptr; - if (!sink || !sink->present_x) { - static std::atomic logged{false}; - if (first_call(logged)) - RT_LOG_WARN("d3d12_xs: queue slot %u is taken for PresentX and the device has no present sink; " - "returning E_NOTIMPL\n", slot); - d3d12_trace::record(child_trace_name(slot), "unsupported"); - return E_NOTIMPL; - } - d3d12_trace::record(child_trace_name(slot)); // "called": the sink's result is the title's - return sink->present_x(sink->context, reinterpret_cast(self->real), - static_cast(plane_count), reinterpret_cast(planes), - reinterpret_cast(params)); -} - -template -std::uint64_t WINAPI child_slot(ChildProxy* self, std::uint64_t a1, std::uint64_t a2, std::uint64_t a3, - std::uint64_t a4, std::uint64_t a5, std::uint64_t a6, std::uint64_t a7, - std::uint64_t a8, std::uint64_t a9, std::uint64_t a10, std::uint64_t a11, - std::uint64_t a12, std::uint64_t a13, std::uint64_t a14) { - if constexpr (Slot == 0) { - d3d12_trace::record(child_trace_name(Slot)); - return hr_to_u64(child_query_interface(self, reinterpret_cast(a1), - reinterpret_cast(a2))); - } else if constexpr (Slot == 1) { - return child_add_ref(self); - } else if constexpr (Slot == 2) { - return child_release(self); - } else if constexpr (Slot == 7) { - d3d12_trace::record(child_trace_name(Slot)); - return hr_to_u64(child_get_device(self, reinterpret_cast(a1), - reinterpret_cast(a2))); - } else { - note_child_slot(Slot); - // The slot a setting names for PresentX, before the tail is refused. Only a tail slot of the queue table can - // be that slot, so the public chain, the fences and the allocators never ask. - if constexpr (K == ChildKind::queue && Slot >= kQueuePublicSlots) { - if (Slot == present_x_slot()) return hr_to_u64(queue_present_x(self, Slot, a1, a2, a3)); - } - if (Slot >= self->slot_count) { - bool expected = false; - if (ChildStats::beyond_warned[Slot].compare_exchange_strong(expected, true, - std::memory_order_relaxed)) { - RT_LOG_WARN("d3d12_xs: %s slot %u is beyond the PC %s vtable (%u slots); returning E_NOTIMPL " - "(args 0x%llx 0x%llx 0x%llx 0x%llx)\n", - child_kind_name(), Slot, child_kind_name(), self->slot_count, - static_cast(a1), static_cast(a2), - static_cast(a3), static_cast(a4)); - } - d3d12_trace::record(child_trace_name(Slot), "unsupported"); - return hr_to_u64(E_NOTIMPL); - } - d3d12_trace::record(child_trace_name(Slot)); // "called": the real object's result is not inspected - if constexpr (K == ChildKind::queue && (Slot == kQueueSignal || Slot == kQueueWait)) a1 = unwrap_object(a1); - UnwrappedArray unwrapped_lists; - if constexpr (K == ChildKind::queue && Slot == 10) { - if (!unwrapped_lists.fill(a2, a1)) return hr_to_u64(E_OUTOFMEMORY); - if (unwrapped_lists.data()) a2 = unwrapped_lists.data(); - } - - // The PC vtable entry with the real object as `this`; integer/pointer arguments, the hidden struct-return - // pointer and stack arguments keep their positions, as in the device proxy. - using ForwardFn = std::uint64_t(WINAPI*)(void*, std::uint64_t, std::uint64_t, std::uint64_t, - std::uint64_t, std::uint64_t, std::uint64_t, std::uint64_t, - std::uint64_t, std::uint64_t, std::uint64_t, std::uint64_t, - std::uint64_t, std::uint64_t, std::uint64_t); - auto fn = reinterpret_cast(self->real_vtable[Slot]); - return fn(self->real, a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14); - } -} - -template -void fill_child_vtable(void** vtable, std::index_sequence) { - ((vtable[I] = reinterpret_cast(&child_slot(I)>)), ...); -} - -// True when the fault logger is installed (once per process; a failure is logged once). -bool install_table_overrun_handler() { - static const bool installed = [] { - if (AddVectoredExceptionHandler(0, &table_overrun_handler)) return true; - RT_LOG_ERROR("d3d12_xs: AddVectoredExceptionHandler failed (error %lu); a slot past a queue or " - "fence proxy table faults without being named\n", GetLastError()); - return false; - }(); - return installed; -} - -template -void** get_child_vtable() { - static void** vtable = [] { - using S = ChildStats; - constexpr std::size_t bytes = S::kSlots * sizeof(void*); - SYSTEM_INFO system{}; - GetSystemInfo(&system); - const SIZE_T page = system.dwPageSize; - if (void* base = page >= bytes ? VirtualAlloc(nullptr, kTableRegion, MEM_RESERVE, PAGE_NOACCESS) : nullptr) { - if (VirtualAlloc(base, page, MEM_COMMIT, PAGE_READWRITE)) { - auto* table = reinterpret_cast(static_cast(base) + page - bytes); - fill_child_vtable(table, std::make_index_sequence{}); - DWORD old = 0; - if (!VirtualProtect(base, page, PAGE_READONLY, &old)) // the table works, but stays writable - RT_LOG_WARN("d3d12_xs: %s proxy table stays writable (VirtualProtect error %lu)\n", - child_kind_name(), GetLastError()); - S::table_begin.store(reinterpret_cast(table), std::memory_order_release); - S::region_end.store(reinterpret_cast(base) + kTableRegion, std::memory_order_release); - // table_end is what "guarded" means (command_object_tables_guarded, the fault logger): set only when - // a fault past the table will be named. Without the logger the region still faults, unnamed. - if (install_table_overrun_handler()) - S::table_end.store(reinterpret_cast(base) + page, std::memory_order_release); - return table; - } - VirtualFree(base, 0, MEM_RELEASE); - } - // No reservation: the table still works, but a slot past it is not caught. - RT_LOG_WARN("d3d12_xs: %s proxy table without a guard region\n", child_kind_name()); - static void* storage[S::kSlots]; - fill_child_vtable(storage, std::make_index_sequence{}); - return storage; - }(); - return vtable; -} - -// Wraps `created` (one reference, owned by the proxy on success, released on failure) and returns `riid` from the -// proxy through `out`. -template -HRESULT wrap_child(IUnknown* created, DeviceProxy* device, const IID* riid, void** out) { - if (!created) return E_FAIL; - ChildProxy* proxy = new (std::nothrow) ChildProxy; - if (!proxy) { - created->Release(); - return E_OUTOFMEMORY; - } - proxy->vtable = get_child_vtable(); - proxy->real = created; - proxy->device = device; - proxy->real_vtable = *reinterpret_cast(created); - if constexpr (K == ChildKind::queue) { - proxy->slot_count = kQueuePublicSlots; - } else if constexpr (K == ChildKind::fence) { - proxy->slot_count = supports_iid(created, __uuidof(ID3D12Fence1)) ? kFence1PublicSlots : kFencePublicSlots; - } else { - proxy->slot_count = kAllocatorPublicSlots; - } - proxy->refs.store(1, std::memory_order_relaxed); - proxy_add_ref(device); // the object keeps its Xbox-ABI device alive for GetDevice - - const HRESULT hr = child_query_interface(proxy, riid, out); - if (FAILED(hr)) { - destroy_child(proxy); // no reference escaped - return hr; - } - // Titles create fences at run time: the first proxy of each kind is logged, every one only with XS_TRACE. - static std::atomic logged{false}; - if (!d3d12_trace::enabled() && (!logged.exchange(true, std::memory_order_relaxed) || trace_enabled())) - RT_LOG_DEBUG("d3d12_xs: %s proxy %p wraps %p (device proxy %p, %u public slots)\n", - child_kind_name(), static_cast(proxy), static_cast(created), - static_cast(device), proxy->slot_count); - proxy->refs.fetch_sub(1, std::memory_order_relaxed); // drop the creation reference; `out` holds the caller's - return S_OK; -} - -// Calls the real device's slot `Slot` with these five words in the positions the thunk received them (see "A thunk -// declares 14 argument words" at the top: no word may move to another stack position on the way). -template -std::uint64_t forward_device(DeviceProxy* self, std::uint64_t a1, std::uint64_t a2, std::uint64_t a3, - std::uint64_t a4, std::uint64_t a5) { - using Fn = std::uint64_t(WINAPI*)(void*, std::uint64_t, std::uint64_t, std::uint64_t, std::uint64_t, - std::uint64_t); - return reinterpret_cast(self->real_vtable[Slot])(self->real, a1, a2, a3, a4, a5); -} - -// A device slot past the PC device's vtable (the real device predates the interface): E_NOTIMPL, logged once per -// slot. The generic thunk and the slots the proxy handles itself (31/34/35/45/46/50, 75) log the same line. -HRESULT refuse_beyond_device(unsigned slot, unsigned slot_count) { - bool expected = false; - if (slot < kMaxSlots && g_beyond_warned[slot].compare_exchange_strong(expected, true, std::memory_order_relaxed)) - RT_LOG_WARN("d3d12_xs: device slot %u (%s) is beyond the PC device vtable (%u slots); returning " - "E_NOTIMPL\n", - slot, slot_name(slot), slot_count); - return E_NOTIMPL; -} - -// Device slot 8: CreateCommandQueue(desc, riid, out). Without an output it is the device's own capability answer -// (S_FALSE for a valid description on the PC), as #558 does for slot 14. -HRESULT proxy_create_command_queue(DeviceProxy* self, const D3D12_COMMAND_QUEUE_DESC* desc, const IID* riid, - void** out) { - note_slot(8); - if (out) *out = nullptr; // _COM_Outptr_: NULL on every failure, as slots 14/62/76 - if (!riid) return E_POINTER; - // The caller's null output goes to the real device on purpose: its answer (S_FALSE, E_UNEXPECTED, ...) is the - // one to give, although the SDK annotates the parameter as required. -#pragma warning(suppress : 6387) - if (!out) return self->real->CreateCommandQueue(desc, *riid, nullptr); - void* created = nullptr; - const HRESULT hr = self->real->CreateCommandQueue(desc, __uuidof(ID3D12CommandQueue), &created); - if (FAILED(hr)) return hr; - return wrap_child(static_cast(created), self, riid, out); -} - -// Xbox device slot 78 (public HLE): SetFrameIntervalX(output, interval_us, latency, flags). The output and flags are -// not used before a presenter exists. The period is a vblank period in microseconds in the public samples (16667 for -// 60 Hz), and latency is the allowed frames in flight. S_OK even for 0: a boot must not abort here, and nothing paces. -HRESULT proxy_set_frame_interval_x(DeviceProxy* self, std::uint64_t output, std::uint64_t interval_us, - std::uint64_t latency, std::uint64_t flags) { - // A sink (set_device_frame_event_sink) takes the call over, with the title's words and its own result. - if (const FrameEventSink* sink = self->frame_sink.load(std::memory_order_acquire); - sink && sink->set_frame_interval) - return sink->set_frame_interval(sink->context, reinterpret_cast(output), - static_cast(interval_us), - static_cast(latency), static_cast(flags)); - (void)output; - (void)flags; - self->frame_interval_us.store(static_cast(interval_us), std::memory_order_relaxed); - self->frame_latency.store(static_cast(latency ? latency : 1), std::memory_order_relaxed); - return S_OK; -} - -// Xbox device slot 79 (public HLE): ScheduleFrameEventX(event, offset_us, pEvent, flags); our pacer has only the origin. -HRESULT proxy_schedule_frame_event_x(DeviceProxy* self, std::uint64_t event, std::uint64_t offset_us, - std::uint64_t flags) { - if (const FrameEventSink* sink = self->frame_sink.load(std::memory_order_acquire); - sink && sink->schedule_frame_event) - return sink->schedule_frame_event(sink->context, static_cast(event), - static_cast(offset_us), static_cast(flags)); - (void)event; - (void)offset_us; - (void)flags; - self->frame_event_scheduled.store(true, std::memory_order_relaxed); - return S_OK; -} - -// Xbox device slot 80 (public HLE): WaitFrameEventX(event, timeout_ms, pEvent, flags, &token). It returns at once with -// a fresh non-zero token (the first-frame choice): there is no vblank source behind the device before a presenter, and -// a zero wait cannot stall the title. A null token pointer is E_POINTER, as a _Out_ parameter. -HRESULT proxy_wait_frame_event_x(DeviceProxy* self, std::uint64_t event, std::uint64_t timeout_ms, - std::uint64_t flags, std::uint64_t token_word) { - auto* token = reinterpret_cast(token_word); - if (!token) return E_POINTER; - // With a sink the wait is the sink's: it may block, and its result and token are the title's. - if (const FrameEventSink* sink = self->frame_sink.load(std::memory_order_acquire); - sink && sink->wait_frame_event) - return sink->wait_frame_event(sink->context, static_cast(event), - static_cast(timeout_ms), static_cast(flags), - token); - (void)event; - (void)timeout_ms; - (void)flags; - std::uint64_t value = self->frame_next_token.fetch_add(1, std::memory_order_relaxed); - if (value == 0) value = self->frame_next_token.fetch_add(1, std::memory_order_relaxed); // skip the null token - *token = value; - return S_OK; -} - -// Xbox device slot 73 (public HLE): CreateCommandListX(desc, allocator, initial_state, riid, out). The console call is -// not the PC six-argument form: the type is the first word of D3D12XBOX_COMMAND_LIST_DESC and there is no node mask -// (the HLE passes 0). The second desc word is logged, not interpreted: its public layout is not established. -HRESULT proxy_create_command_list_x(DeviceProxy* self, std::uint64_t desc_word, std::uint64_t allocator_word, - std::uint64_t initial_state_word, const IID* riid, void** out) { - if (out) *out = nullptr; - if (!desc_word || !allocator_word) return E_INVALIDARG; - if (!riid) return E_POINTER; - if (!out) return E_POINTER; - - std::uint32_t words[2] = {}; - std::memcpy(words, reinterpret_cast(desc_word), sizeof(words)); - auto type = static_cast(words[0]); - if (type != D3D12_COMMAND_LIST_TYPE_DIRECT && type != D3D12_COMMAND_LIST_TYPE_BUNDLE && - type != D3D12_COMMAND_LIST_TYPE_COMPUTE && type != D3D12_COMMAND_LIST_TYPE_COPY) - type = D3D12_COMMAND_LIST_TYPE_DIRECT; // as the public HLE does - - static std::atomic logged{false}; - if (first_call(logged)) - RT_LOG_DEBUG("d3d12_xs: slot 73 CreateCommandListX desc words 0x%08x 0x%08x -> node mask 0, type %d\n", - words[0], words[1], static_cast(type)); - - // Leonida wraps its Vulkan allocators; a PC allocator comes back unwrapped and is passed as it is. Pipeline states - // are not wrapped by this proxy, so initial_state is already the real object (a proxy there is passed through too). - auto* allocator = allocator_proxy_real_allocator(reinterpret_cast(allocator_word)); - if (!allocator) allocator = reinterpret_cast(allocator_word); - auto* initial_state = reinterpret_cast(initial_state_word); - void* created = nullptr; - const HRESULT hr = self->real->CreateCommandList(0, type, allocator, initial_state, - *riid, &created); - if (FAILED(hr)) return hr; - return wrap_list(static_cast(created), self, riid, out); -} - -// Device slot 75: ID3D12Device9::CreateCommandQueue1(desc, creator_id, riid, out), called by slot index. -HRESULT proxy_create_command_queue1(DeviceProxy* self, std::uint64_t desc, std::uint64_t creator_id, - const IID* riid, void** out) { - note_slot(75); - if (out) *out = nullptr; // as slot 8 - if (self->slot_count <= 75) return refuse_beyond_device(75, self->slot_count); // predates ID3D12Device9 - if (!riid) return E_POINTER; - using Fn = HRESULT(WINAPI*)(ID3D12Device*, std::uint64_t, std::uint64_t, const IID*, void**); - const auto create = reinterpret_cast(self->real_vtable[75]); - if (!out) return create(self->real, desc, creator_id, riid, nullptr); - void* created = nullptr; - const HRESULT hr = create(self->real, desc, creator_id, &__uuidof(ID3D12CommandQueue), &created); - if (FAILED(hr)) return hr; - return wrap_child(static_cast(created), self, riid, out); -} - -// Device slot 36: CreateFence(initial_value, flags, riid, out). -HRESULT proxy_create_fence(DeviceProxy* self, std::uint64_t initial_value, std::uint64_t flags, const IID* riid, - void** out) { - note_slot(36); - if (out) *out = nullptr; // as slot 8 - if (!riid) return E_POINTER; - const auto fence_flags = static_cast(static_cast(flags)); -#pragma warning(suppress : 6387) // the caller's null output, on purpose (see slot 8) - if (!out) return self->real->CreateFence(initial_value, fence_flags, *riid, nullptr); - void* created = nullptr; - const HRESULT hr = self->real->CreateFence(initial_value, fence_flags, __uuidof(ID3D12Fence), &created); - if (FAILED(hr)) return hr; - return wrap_child(static_cast(created), self, riid, out); -} - -// True when `allocator` is one whose consumers resolve allocator proxies: Leonida's own Vulkan-layer allocator, -// whose lists (CreateCommandList, Reset) find the real allocator through allocator_proxy_real_allocator. A PC -// runtime allocator does not answer the tag, and its lists would take a proxy for their own allocator. -bool resolves_allocator_proxies(IUnknown* allocator) { - void* found = nullptr; - if (FAILED(allocator->QueryInterface(kLeonidaCommandAllocatorTag, &found)) || !found) return false; - static_cast(found)->Release(); // the implementation pointer starts with its IUnknown chain - return true; -} - -// Device slot 9: CreateCommandAllocator(type, riid, out). An allocator proxy where the list side resolves it (see -// resolves_allocator_proxies); any other allocator goes back unchanged, logged once, so the host runtime's lists -// never see a proxy. Null output and null IID as slot 8. -HRESULT proxy_create_command_allocator(DeviceProxy* self, std::uint64_t type, const IID* riid, void** out) { - note_slot(9); - if (out) *out = nullptr; // as slot 8 - if (!riid) return E_POINTER; - const auto list_type = static_cast(static_cast(type)); -#pragma warning(suppress : 6387) // the caller's null output, on purpose (see slot 8) - if (!out) return self->real->CreateCommandAllocator(list_type, *riid, nullptr); - void* created = nullptr; - const HRESULT hr = self->real->CreateCommandAllocator(list_type, __uuidof(ID3D12CommandAllocator), &created); - if (FAILED(hr)) return hr; - if (!created) return E_FAIL; - auto* allocator = static_cast(created); - if (!resolves_allocator_proxies(allocator)) { - static std::atomic logged{false}; - if (!logged.exchange(true, std::memory_order_relaxed)) - RT_LOG_WARN("d3d12_xs: allocators of this device are not wrapped: its command lists " - "cannot resolve an allocator proxy\n"); - const HRESULT asked = allocator->QueryInterface(*riid, out); - allocator->Release(); - return asked; - } - return wrap_child(allocator, self, riid, out); -} - -// Device slot 32: OpenSharedHandle(handle, riid, out). The object is opened as asked; when it is a fence (whatever -// interface was asked for, IUnknown included) the title gets a fence proxy, anything else (heaps, resources) is -// returned unchanged. -HRESULT proxy_open_shared_handle(DeviceProxy* self, std::uint64_t handle, const IID* riid, void** out) { - note_slot(32); - if (out) *out = nullptr; // as slot 8 - if (!riid) return E_POINTER; - const auto shared = reinterpret_cast(handle); - if (!out) return self->real->OpenSharedHandle(shared, *riid, nullptr); - void* opened = nullptr; - HRESULT hr = self->real->OpenSharedHandle(shared, *riid, &opened); - if (FAILED(hr) || !opened) return FAILED(hr) ? hr : E_FAIL; - void* fence = nullptr; - if (FAILED(static_cast(opened)->QueryInterface(__uuidof(ID3D12Fence), &fence)) || !fence) { - *out = opened; // not a fence - return hr; - } - static_cast(opened)->Release(); - return wrap_child(static_cast(fence), self, riid, out); -} - -// Device slots that take heap, queue or fence objects: the real runtime gets the real objects. -// 31 CreateSharedHandle(object, attributes, access, name, handle) -// 34 MakeResident(count, objects) 35 Evict(count, objects) -// 45 SetEventOnMultipleFenceCompletion(fences, values, count, flags, event) (ID3D12Device1) -// 46 SetResidencyPriority(count, objects, priorities) (ID3D12Device1) -// 50 EnqueueMakeResident(flags, count, objects, fence, value) (ID3D12Device3) -template -HRESULT proxy_unwrapping_call(DeviceProxy* self, std::uint64_t a1, std::uint64_t a2, std::uint64_t a3, - std::uint64_t a4, std::uint64_t a5) { - note_slot(Slot); - if (Slot >= self->slot_count) return refuse_beyond_device(Slot, self->slot_count); // predates the interface - UnwrappedArray objects; - std::uint64_t r1 = a1, r2 = a2, r3 = a3, r4 = a4; - if constexpr (Slot == 31) { - r1 = unwrap_object(a1); - } else if constexpr (Slot == 34 || Slot == 35 || Slot == 46) { - if (!objects.fill(a2, a1)) return E_OUTOFMEMORY; - if (objects.data()) r2 = objects.data(); - } else if constexpr (Slot == 45) { - if (!objects.fill(a1, a3)) return E_OUTOFMEMORY; - if (objects.data()) r1 = objects.data(); - } else if constexpr (Slot == 50) { - if (!objects.fill(a3, a2)) return E_OUTOFMEMORY; - if (objects.data()) r3 = objects.data(); - r4 = unwrap_object(a4); - } - // r1-r4 differ from a1-a4 only in a position the method takes, so the title's frame has that word. - return static_cast(static_cast(forward_device(self, r1, r2, r3, r4, a5))); -} - -// A console descriptor heap carries a size as well as an address, and that size is 32 bytes per descriptor. A PC -// desc's trailing words are whatever the caller holds next; they do not encode NumDescriptors * 32, so this -// separates the two layouts without guessing anything about the address itself. -static bool console_heap_range_plausible(const D3D12_DESCRIPTOR_HEAP_DESC* desc, std::uint64_t address, - std::uint64_t size) { - constexpr std::uint64_t kConsoleDescriptorSize = 32; - if (address == 0 || size == 0) return false; - if (desc->NumDescriptors == 0 || desc->NumDescriptors > (0xFFFFFFFFull / kConsoleDescriptorSize)) return false; - if (size != static_cast(desc->NumDescriptors) * kConsoleDescriptorSize) return false; - return true; -} - -static bool readable_range(const void* ptr, std::size_t bytes) { - if (!ptr || !bytes) return false; - const auto* p = static_cast(ptr); - std::size_t remaining = bytes; - while (remaining) { - MEMORY_BASIC_INFORMATION mbi{}; - if (!VirtualQuery(p, &mbi, sizeof(mbi)) || mbi.State != MEM_COMMIT) return false; - const DWORD protect = mbi.Protect & 0xffu; - if (protect == PAGE_NOACCESS || protect == PAGE_GUARD || protect == PAGE_EXECUTE) return false; - const auto base = reinterpret_cast(mbi.BaseAddress); - const auto addr = reinterpret_cast(p); - const std::size_t avail = static_cast(base + mbi.RegionSize - addr); - if (avail >= remaining) return true; - remaining -= avail; - p += avail; - } - return true; -} - -HRESULT proxy_create_descriptor_heap(DeviceProxy* self, const D3D12_DESCRIPTOR_HEAP_DESC* desc, const IID* riid, - void** out) { - note_slot(14); - if (out) *out = nullptr; // _COM_Outptr_: NULL on every failure, as the PC device does - if (!riid) return E_POINTER; - // No output: a capability check, answered by the device (S_FALSE, as on the PC). - if (!out) return self->real->CreateDescriptorHeap(desc, *riid, nullptr); - - void* created = nullptr; - HRESULT hr = E_INVALIDARG; - bool console_extended = false; - if (desc && desc->Type <= D3D12_DESCRIPTOR_HEAP_TYPE_DSV && - (desc->Flags & ~D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE) == 0) { - const auto* bytes = reinterpret_cast(desc); - const void* tail = bytes + sizeof(D3D12_DESCRIPTOR_HEAP_DESC); - if (readable_range(tail, sizeof(std::uint64_t) * 2)) { - std::uint64_t address = 0; - std::uint64_t size = 0; - std::memcpy(&address, tail, sizeof(address)); - std::memcpy(&size, bytes + sizeof(D3D12_DESCRIPTOR_HEAP_DESC) + sizeof(address), sizeof(size)); - // Console-extended slot 14 (issue #313): address/size follow the PC desc. A non-zero word is not evidence - // of that layout - the bytes after a PC desc are whatever the caller holds next, and they are almost - // always readable and non-zero. The size has to agree with the descriptor count for the path to be taken. - if (console_heap_range_plausible(desc, address, size)) { - const ConsoleDescriptorHeapHandler handler = - g_console_descriptor_heap.load(std::memory_order_acquire); - if (handler) { - console_extended = true; - hr = handler(self->real, desc, static_cast(address), size, - __uuidof(ID3D12DescriptorHeap), &created); - } - } - } - } - if (!console_extended) - hr = self->real->CreateDescriptorHeap(desc, __uuidof(ID3D12DescriptorHeap), &created); - if (FAILED(hr) || !created) return FAILED(hr) ? hr : E_FAIL; - - ID3D12DescriptorHeap* heap = static_cast(created); - hr = create_heap_proxy(heap, self, *riid, out); - if (FAILED(hr)) heap->Release(); - return hr; -} - -// The Xbox slot 62 takes two more words between the description and the IID: (desc, w2, w3, riid, out). Measured -// on the package's XboxBvhBuilder.dll (its constructor passes w2 = w3 = 0 and IID_ID3D12PipelineState in the fourth -// argument), as the prior art had recorded. Their meaning is unknown; non-zero values are logged once. -HRESULT proxy_create_compute_pipeline_state(DeviceProxy* self, const D3D12_COMPUTE_PIPELINE_STATE_DESC* desc, - std::uint64_t w2, std::uint64_t w3, const IID* riid, void** out) { - note_slot(62); - if (w2 || w3) { - static std::atomic logged{false}; - if (!logged.exchange(true, std::memory_order_relaxed)) - RT_LOG_WARN("d3d12_xs: slot 62 extra words 0x%llx 0x%llx (ignored)\n", - static_cast(w2), static_cast(w3)); - } - if (!out) return E_POINTER; - *out = nullptr; - if (!riid) return E_POINTER; - return self->real->CreateComputePipelineState(desc, *riid, out); -} - -// The Xbox slot 67 creates a compute pipeline from native GPU code: (desc, riid, out), named -// DeserializeComputePipelineStateX in amd_fidelityfx_upscaler_xbox.dll's messages (call at RVA 0x56d9). The desc -// passes the root signature at +0x00, followed by pointer/size pairs for the shader's FSPX entries (docs/fspx.md): -// kind 0 (dispatch state) at +0x08/+0x10, kind 1 at +0x18/+0x20, kind 6 (the RDNA2 program) at +0x28/+0x30, and -// kind 7 (records) at +0x38/+0x40. Translates the console description to a standard D3D12_COMPUTE_PIPELINE_STATE_DESC -// with CS bytecode pointing at kind 6 and routes it to CreateComputePipelineState on the PC device (slot 11), which -// on the Vulkan device resolves through the translator. The PC slot 67 is CreateProtectedResourceSession1. -HRESULT proxy_create_compute_pipeline_from_native_code(DeviceProxy* self, const void* desc, - const IID* riid, void** out) { - note_slot(67); - if (!out) return E_POINTER; - *out = nullptr; - if (!desc) return E_INVALIDARG; - if (!riid) return E_POINTER; - - // FSPX description layout (docs/fspx.md §How the DLL reads it): - struct XboxNativeComputePipelineStateDesc { - ID3D12RootSignature* root_signature; // +0x00 - const void* kind0; // +0x08: dispatch state - std::uint64_t kind0_size; // +0x10: 28 bytes - const void* kind1; // +0x18: unknown - std::uint64_t kind1_size; // +0x20: 20 bytes - const void* kind6; // +0x28: RDNA2 program code - std::uint64_t kind6_size; // +0x30: program size in bytes - const void* kind7; // +0x38: resource/hash records - std::uint64_t kind7_size; // +0x40: records size in bytes - }; - const auto* xbox_desc = static_cast(desc); - - D3D12_COMPUTE_PIPELINE_STATE_DESC pc_desc{}; - pc_desc.pRootSignature = xbox_desc->root_signature; - pc_desc.CS.pShaderBytecode = xbox_desc->kind6; - pc_desc.CS.BytecodeLength = static_cast(xbox_desc->kind6_size); - // With kind 0 (the DLL always passes it: its reader refuses a payload without one), the four pairs go on as one - // FSPX payload, so the device matches the program by its kind-6 and kind-0 keys (docs/fspx.md, "Build and run-time - // lookup"): two programs with the same code and different dispatch state stay apart. Every pair is checked before - // it is read (leonida::fspx_payload_from_parts); an inconsistent one refuses the call. Without kind 0 the kind-6 - // bytes go on alone, as before. - std::vector payload; - if (xbox_desc->kind0 || xbox_desc->kind0_size) { - const leonida::FspxPart parts[] = {{0, xbox_desc->kind0, xbox_desc->kind0_size}, - {1, xbox_desc->kind1, xbox_desc->kind1_size}, - {6, xbox_desc->kind6, xbox_desc->kind6_size}, - {7, xbox_desc->kind7, xbox_desc->kind7_size}}; - payload = leonida::fspx_payload_from_parts(parts); - if (payload.empty()) { - static std::atomic logged{false}; - if (!logged.exchange(true, std::memory_order_relaxed)) - RT_LOG_ERROR("d3d12_xs: slot 67 refused: a pointer/size pair is inconsistent or too large " - "(kind0 %llu B, kind1 %llu B, kind6 %llu B, kind7 %llu B)\n", - static_cast(xbox_desc->kind0_size), - static_cast(xbox_desc->kind1_size), - static_cast(xbox_desc->kind6_size), - static_cast(xbox_desc->kind7_size)); - return E_INVALIDARG; - } - pc_desc.CS.pShaderBytecode = payload.data(); - pc_desc.CS.BytecodeLength = payload.size(); - } - - pc_desc.NodeMask = 0; - pc_desc.CachedPSO = {nullptr, 0}; - pc_desc.Flags = D3D12_PIPELINE_STATE_FLAG_NONE; - - // Every failed call is logged with its number: the DLL creates its pipelines one after the other, and only the - // first call of a slot is announced, so a miss on a later program would otherwise read as the first call's. - static std::atomic calls{0}; - const std::uint64_t call = calls.fetch_add(1, std::memory_order_relaxed) + 1; - const HRESULT hr = self->real->CreateComputePipelineState(&pc_desc, *riid, out); - if (FAILED(hr)) - RT_LOG_ERROR("d3d12_xs: slot 67 call %llu failed with 0x%08lx (kind 0 %llu B, kind 1 %llu B, kind 6 %llu B, " - "kind 7 %llu B)\n", - static_cast(call), static_cast(hr), - static_cast(xbox_desc->kind0_size), - static_cast(xbox_desc->kind1_size), - static_cast(xbox_desc->kind6_size), - static_cast(xbox_desc->kind7_size)); - return hr; -} - -HRESULT proxy_create_resource(DeviceProxy* self, const D3D12_HEAP_PROPERTIES* heap_properties, - D3D12_HEAP_FLAGS heap_flags, const D3D12_RESOURCE_DESC* xbox_desc, - D3D12_RESOURCE_STATES initial_state, const D3D12_CLEAR_VALUE* clear_value, - const IID* riid, void** out) { - note_slot(76); - if (!out) return E_POINTER; - *out = nullptr; - if (!xbox_desc) return E_POINTER; - if (!riid) return E_POINTER; - - // The measured description is 56 bytes plus Xbox extension words; D3D12_RESOURCE_DESC is exactly 56 bytes. - // The Xbox layout word is 0x101 (tiled) or 0x1 (row-major buffer), and is not a PC layout value. Committed - // resources take ROW_MAJOR for buffers and UNKNOWN for everything else, so the word is ignored and replaced. - D3D12_RESOURCE_DESC pc_desc = *xbox_desc; - const auto xbox_layout = static_cast(pc_desc.Layout); - pc_desc.Layout = pc_desc.Dimension == D3D12_RESOURCE_DIMENSION_BUFFER ? D3D12_TEXTURE_LAYOUT_ROW_MAJOR - : D3D12_TEXTURE_LAYOUT_UNKNOWN; - - static std::atomic logged{false}; - if (!logged.exchange(true, std::memory_order_relaxed)) { - RT_LOG_DEBUG("d3d12_xs: slot 76 resource: dimension=%d xbox layout=0x%x -> PC layout=0x%x\n", - static_cast(pc_desc.Dimension), xbox_layout, static_cast(pc_desc.Layout)); - } - return self->real->CreateCommittedResource(heap_properties, heap_flags, &pc_desc, initial_state, clear_value, - *riid, out); -} - -// Device slot 133 is the console's CreatePlacedResourceX: (va, desc, state, clear, riid, out), measured on the retail -// executable (docs/retail_boot_chain.md, section 3.4). `va` is the start of a physical-page range the title has just -// mapped, `desc` a 56-byte description with Xbox bits above the PC resource flags and an Xbox layout word, and -// `state` is 0xFFFFFFFF, which is no PC state. The resource is a buffer on those pages, made by the handler the -// device behind the proxy registered (set_placed_at_va_handler), with the PC flags kept and the layout made -// ROW_MAJOR, as slot 76 does. -std::atomic g_placed_at_va{nullptr}; -std::atomic g_placed_at_va_pages{nullptr}; - -HRESULT proxy_create_placed_resource_x(DeviceProxy* self, void* va, const D3D12_RESOURCE_DESC* xbox_desc, - std::uint32_t state, const IID* riid, void** out) { - note_slot(133); - if (out) *out = nullptr; - // Without a handler (a PC device behind the proxy, or none registered) the slot refuses like any slot past the - // PC vtable, whatever its arguments. - const PlacedAtVaHandler handler = g_placed_at_va.load(std::memory_order_acquire); - if (!handler) return E_NOTIMPL; - if (!out || !xbox_desc || !riid) return E_POINTER; - // An integer mask: a D3D12_RESOURCE_FLAGS constant past the SDK's last enumerator is not a constant expression - // for clang-cl with SDK 10.0.26100 (found in review). The cast is applied to the masked value at run time. - // The PC flags up to RAYTRACING_ACCELERATION_STRUCTURE (0x100) and USE_TIGHT_ALIGNMENT (0x400); 0x200 is - // dropped, as committed_resource_refusal says the host refuses it (found in review). - constexpr std::uint32_t kPcResourceFlags = 0x5ff; - D3D12_RESOURCE_DESC pc_desc = *xbox_desc; - const auto xbox_flags = static_cast(pc_desc.Flags); - pc_desc.Flags = static_cast(xbox_flags & kPcResourceFlags); - // The Xbox layout word (0x101 tiled, 0x1 row-major buffer) is no PC layout: ROW_MAJOR for a buffer and UNKNOWN - // for everything else, as slot 76 does. - pc_desc.Layout = pc_desc.Dimension == D3D12_RESOURCE_DIMENSION_BUFFER ? D3D12_TEXTURE_LAYOUT_ROW_MAJOR - : D3D12_TEXTURE_LAYOUT_UNKNOWN; - static std::atomic logged{false}; - if (!logged.exchange(true, std::memory_order_relaxed)) { - RT_LOG_DEBUG("d3d12_xs: slot 133 CreatePlacedResourceX: va=%p dimension=%d width=%llu xbox flags=0x%x " - "state=0x%x -> a buffer on the title's pages\n", - va, static_cast(pc_desc.Dimension), static_cast(pc_desc.Width), - xbox_flags, state); - } - // The buffer's pages are committed before the handler walks them (set_placed_at_va_pages_hook). - const PlacedAtVaPagesHook pages = g_placed_at_va_pages.load(std::memory_order_acquire); - if (pages && pc_desc.Dimension == D3D12_RESOURCE_DIMENSION_BUFFER && pc_desc.Width && - !pages(va, static_cast(pc_desc.Width))) { - static std::atomic refused{false}; - if (!refused.exchange(true, std::memory_order_relaxed)) { - RT_LOG_ERROR("d3d12_xs: slot 133: committing the pages of va=%p width=%llu failed (error %lu)\n", - va, static_cast(pc_desc.Width), GetLastError()); - } - } - return handler(self->real, va, pc_desc, state, *riid, out); -} - -template -std::uint64_t WINAPI proxy_slot(DeviceProxy* self, std::uint64_t a1, std::uint64_t a2, std::uint64_t a3, - std::uint64_t a4, std::uint64_t a5, std::uint64_t a6, std::uint64_t a7, - std::uint64_t a8, std::uint64_t a9, std::uint64_t a10, std::uint64_t a11, - std::uint64_t a12, std::uint64_t a13, std::uint64_t a14) { - if constexpr (Slot == 0) { - return hr_to_u64(proxy_query_interface(self, reinterpret_cast(a1), - reinterpret_cast(a2))); - } else if constexpr (Slot == 1) { - return proxy_add_ref(self); - } else if constexpr (Slot == 2) { - return proxy_release(self); - } else if constexpr (Slot == 8) { - return hr_to_u64(proxy_create_command_queue(self, reinterpret_cast(a1), - reinterpret_cast(a2), reinterpret_cast(a3))); - } else if constexpr (Slot == 9) { - return hr_to_u64(proxy_create_command_allocator(self, a1, reinterpret_cast(a2), - reinterpret_cast(a3))); - } else if constexpr (Slot == 12) { - note_slot(12); - a3 = unwrap_object(a3); - if (Slot >= self->slot_count) return hr_to_u64(refuse_beyond_device(12, self->slot_count)); - using CreateListFn = HRESULT(WINAPI*)(ID3D12Device*, UINT, D3D12_COMMAND_LIST_TYPE, ID3D12CommandAllocator*, - ID3D12PipelineState*, const IID*, void**); - auto fn = reinterpret_cast(self->real_vtable[12]); - return hr_to_u64(fn(self->real, static_cast(a1), static_cast(a2), - reinterpret_cast(a3), - reinterpret_cast(a4), - reinterpret_cast(a5), - reinterpret_cast(a6))); - } else if constexpr (Slot == 36) { - return hr_to_u64(proxy_create_fence(self, a1, a2, reinterpret_cast(a3), - reinterpret_cast(a4))); - } else if constexpr (Slot == 32) { - return hr_to_u64(proxy_open_shared_handle(self, a1, reinterpret_cast(a2), - reinterpret_cast(a3))); - } else if constexpr (Slot == 31 || Slot == 34 || Slot == 35 || Slot == 45 || Slot == 46 || Slot == 50) { - return hr_to_u64(proxy_unwrapping_call(self, a1, a2, a3, a4, a5)); - } else if constexpr (Slot == 75) { - return hr_to_u64(proxy_create_command_queue1(self, a1, a2, reinterpret_cast(a3), - reinterpret_cast(a4))); - } else if constexpr (Slot == 14) { - return hr_to_u64(proxy_create_descriptor_heap( - self, reinterpret_cast(a1), - reinterpret_cast(a2), reinterpret_cast(a3))); - } else if constexpr (Slot == 62) { - return hr_to_u64(proxy_create_compute_pipeline_state( - self, reinterpret_cast(a1), a2, a3, - reinterpret_cast(a4), reinterpret_cast(a5))); - } else if constexpr (Slot == 67) { - return hr_to_u64(proxy_create_compute_pipeline_from_native_code( - self, reinterpret_cast(a1), reinterpret_cast(a2), - reinterpret_cast(a3))); - } else if constexpr (Slot == 133) { - return hr_to_u64(proxy_create_placed_resource_x(self, reinterpret_cast(a1), - reinterpret_cast(a2), - static_cast(a3), reinterpret_cast(a5), - reinterpret_cast(a6))); - } else if constexpr (Slot == 76) { - return hr_to_u64(proxy_create_resource( - self, reinterpret_cast(a1), - static_cast(static_cast(a2)), - reinterpret_cast(a3), - static_cast(static_cast(a4)), - reinterpret_cast(a5), reinterpret_cast(a6), - reinterpret_cast(a7))); - } else { - note_slot(Slot); - // Xbox device slots, before the PC vtable is indexed: the public HLE's 78/79/80 would otherwise reach - // CreateReservedResource2/CreateSampler2 or fall past an 80-slot table, and 48/73 would reach unrelated PC - // methods. The check is before the slot-count refusal because slot 80 is outside a PC ID3D12Device11 table. - const XboxDeviceSlotRoutes& routes = xbox_device_slot_routes(); - if (Slot == routes.frame_interval) { - log_xbox_route_once(Slot, "SetFrameIntervalX", a1, a2, a3, a4, a5); - return hr_to_u64(proxy_set_frame_interval_x(self, a1, a2, a3, a4)); - } - if (Slot == routes.schedule_event) { - log_xbox_route_once(Slot, "ScheduleFrameEventX", a1, a2, a3, a4, a5); - return hr_to_u64(proxy_schedule_frame_event_x(self, a1, a2, a4)); - } - if (Slot == routes.wait_event) { - log_xbox_route_once(Slot, "WaitFrameEventX", a1, a2, a3, a4, a5); - return hr_to_u64(proxy_wait_frame_event_x(self, a1, a2, a4, a5)); - } - if (Slot == routes.queue_x) { - log_xbox_route_once(Slot, "CreateCommandQueueX", a1, a2, a3, a4, a5); - return hr_to_u64(proxy_create_command_queue(self, reinterpret_cast(a1), - reinterpret_cast(a2), - reinterpret_cast(a3))); - } - if (Slot == routes.list_x) { - log_xbox_route_once(Slot, "CreateCommandListX", a1, a2, a3, a4, a5); - return hr_to_u64(proxy_create_command_list_x(self, a1, a2, a3, reinterpret_cast(a4), - reinterpret_cast(a5))); - } - if (Slot >= self->slot_count) return hr_to_u64(refuse_beyond_device(Slot, self->slot_count)); - - // The PC vtable entry, called with the PC device as `this`. Integer/pointer arguments, the hidden - // struct-return pointer and any stack arguments keep their positions; XMM registers are untouched. - using ForwardFn = std::uint64_t(WINAPI*)(void*, std::uint64_t, std::uint64_t, std::uint64_t, - std::uint64_t, std::uint64_t, std::uint64_t, std::uint64_t, - std::uint64_t, std::uint64_t, std::uint64_t, std::uint64_t, - std::uint64_t, std::uint64_t, std::uint64_t); - auto fn = reinterpret_cast(self->real_vtable[Slot]); - return fn(self->real, a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14); - } -} - -template -void fill_vtable(void** vtable, std::index_sequence) { - ((vtable[I] = reinterpret_cast(&proxy_slot(I)>) ), ...); -} - -void** get_vtable() { - static void** vtable = [] { - static void* storage[kMaxSlots]; - fill_vtable(storage, std::make_index_sequence{}); - return storage; - }(); - return vtable; -} - -bool supports(ID3D12Device* real, REFIID iid) { - void* found = nullptr; - const HRESULT hr = real->QueryInterface(iid, &found); - if (FAILED(hr) || !found) return false; - static_cast(found)->Release(); - return true; -} - -// Highest device interface the PC runtime exposes; its cumulative slot count (from d3d12.h) bounds forwarding. -// Windows SDK 10.0.26100 defines ID3D12Device through ID3D12Device14 only; there is no Device15/Device16 header. -unsigned detect_slot_count(ID3D12Device* real) { -#ifdef __ID3D12Device14_INTERFACE_DEFINED__ - if (supports(real, __uuidof(ID3D12Device14))) return 83; -#endif -#ifdef __ID3D12Device13_INTERFACE_DEFINED__ - if (supports(real, __uuidof(ID3D12Device13))) return 82; -#endif -#ifdef __ID3D12Device12_INTERFACE_DEFINED__ - if (supports(real, __uuidof(ID3D12Device12))) return 81; -#endif -#ifdef __ID3D12Device11_INTERFACE_DEFINED__ - if (supports(real, __uuidof(ID3D12Device11))) return 80; -#endif -#ifdef __ID3D12Device10_INTERFACE_DEFINED__ - if (supports(real, __uuidof(ID3D12Device10))) return 79; -#endif -#ifdef __ID3D12Device9_INTERFACE_DEFINED__ - if (supports(real, __uuidof(ID3D12Device9))) return 76; -#endif - if (supports(real, __uuidof(ID3D12Device8))) return 73; - if (supports(real, __uuidof(ID3D12Device7))) return 68; - if (supports(real, __uuidof(ID3D12Device6))) return 66; - if (supports(real, __uuidof(ID3D12Device5))) return 65; - if (supports(real, __uuidof(ID3D12Device4))) return 57; - if (supports(real, __uuidof(ID3D12Device3))) return 51; - if (supports(real, __uuidof(ID3D12Device2))) return 48; - if (supports(real, __uuidof(ID3D12Device1))) return 47; - return 44; -} - -} // namespace - -HRESULT create_device_proxy(ID3D12Device* real, REFIID riid, void** out) { - if (!real) return E_POINTER; - if (!out) return E_POINTER; - *out = nullptr; - - DeviceProxy* proxy = new (std::nothrow) DeviceProxy; - if (!proxy) return E_OUTOFMEMORY; - proxy->vtable = get_vtable(); - proxy->real = real; - proxy->real_vtable = *reinterpret_cast(real); - proxy->slot_count = detect_slot_count(real); - proxy->refs.store(1, std::memory_order_relaxed); - proxy->dxgi_vtable = get_dxgi_vtable(); - proxy->adapter_provider = nullptr; - proxy->gpu_thread_priority.store(0, std::memory_order_relaxed); - proxy->max_frame_latency.store(3, std::memory_order_relaxed); - - const unsigned slot_count = proxy->slot_count; - HRESULT hr = proxy_query_interface(proxy, &riid, out); - if (FAILED(hr)) { - // No reference escaped, and the caller still owns its reference to `real`. - delete proxy; - return hr; - } - if (!d3d12_trace::enabled()) - RT_LOG_DEBUG("d3d12_xs: device proxy %p wraps PC device %p (%u PC vtable slots)\n", - static_cast(proxy), static_cast(real), slot_count); - proxy_release(proxy); // drop the creation reference; `out` holds the caller's reference - return S_OK; -} - -bool is_device_proxy(const void* device) { - return device && *reinterpret_cast(device) == reinterpret_cast(get_vtable()); -} - -void* device_proxy_from_dxgi_device(void* dxgi_device) { - if (!dxgi_device || *static_cast(dxgi_device) != get_dxgi_vtable()) return nullptr; - return dxgi_owner(dxgi_device); -} - -void* device_proxy_primary(void* device) { - if (is_device_proxy(device)) return device; - return device_proxy_from_dxgi_device(device); -} - -bool set_device_adapter_provider(void* device, DxgiAdapterProvider provider) { - auto* proxy = static_cast(device_proxy_primary(device)); - if (!proxy) { - // Not installing one silently would leave the host's adapter in its place. - RT_LOG_ERROR("d3d12_xs: set_device_adapter_provider: %p is not a device proxy; no provider set\n", - device); - return false; - } - proxy->adapter_provider = provider; - return true; -} - -bool set_device_frame_event_sink(void* device, const FrameEventSink* sink) { - auto* proxy = static_cast(device_proxy_primary(device)); - if (!proxy) { - // Not setting one silently would leave the frame calls with the proxy's own answers, unpaced. - RT_LOG_ERROR("d3d12_xs: set_device_frame_event_sink: %p is not a device proxy; no sink set\n", device); - return false; - } - proxy->frame_sink.store(sink, std::memory_order_release); - return true; -} - -const FrameEventSink* device_frame_event_sink(const void* device) { - if (!is_device_proxy(device)) return nullptr; - return static_cast(device)->frame_sink.load(std::memory_order_acquire); -} - -bool set_device_present_sink(void* device, const PresentSink* sink) { - auto* proxy = static_cast(device_proxy_primary(device)); - if (!proxy) { - // Not setting one silently would leave every PresentX of the device's queues refused. - RT_LOG_ERROR("d3d12_xs: set_device_present_sink: %p is not a device proxy; no sink set\n", device); - return false; - } - proxy->present_sink.store(sink, std::memory_order_release); - return true; -} - -const PresentSink* device_present_sink(const void* device) { - if (!is_device_proxy(device)) return nullptr; - return static_cast(device)->present_sink.load(std::memory_order_acquire); -} - -unsigned queue_present_x_slot() { return present_x_slot(); } - -bool is_heap_proxy(const void* heap) { - return heap && *reinterpret_cast(heap) == reinterpret_cast(get_heap_vtable()); -} - -ID3D12DescriptorHeap* heap_proxy_real_heap(const void* heap) { - if (!is_heap_proxy(heap)) return nullptr; - return static_cast(heap)->real; -} - -unsigned device_proxy_slot_count(const void* device) { - if (!is_device_proxy(device)) return 0; - return static_cast(device)->slot_count; -} - -void set_placed_at_va_handler(PlacedAtVaHandler handler) { - g_placed_at_va.store(handler, std::memory_order_release); -} - -void set_placed_at_va_pages_hook(PlacedAtVaPagesHook hook) { - g_placed_at_va_pages.store(hook, std::memory_order_release); -} - -void set_console_descriptor_heap_handler(ConsoleDescriptorHeapHandler handler) { - g_console_descriptor_heap.store(handler, std::memory_order_release); -} - -ID3D12Device* device_proxy_real_device(const void* device) { - if (!is_device_proxy(device)) return nullptr; - return static_cast(device)->real; -} - -bool device_slot_overridden(unsigned slot) { - if (slot <= 2 || slot == 8 || slot == 9 || slot == 14 || slot == 31 || slot == 32 || slot == 34 || slot == 35 || - slot == 36 || slot == 45 || slot == 46 || slot == 50 || slot == 62 || slot == 67 || - slot == 75 || slot == 76 || slot == 133) - return true; - const XboxDeviceSlotRoutes& routes = xbox_device_slot_routes(); - return slot == routes.frame_interval || slot == routes.schedule_event || slot == routes.wait_event || - slot == routes.queue_x || slot == routes.list_x; -} - -bool is_queue_proxy(const void* queue) { return is_child_proxy(queue); } -bool is_fence_proxy(const void* fence) { return is_child_proxy(fence); } -bool is_allocator_proxy(const void* allocator) { return is_child_proxy(allocator); } - -ID3D12CommandAllocator* allocator_proxy_real_allocator(const void* allocator) { - if (!is_allocator_proxy(allocator)) return nullptr; - return reinterpret_cast(static_cast(allocator)->real); -} - -ID3D12CommandQueue* queue_proxy_real_queue(const void* queue) { - if (!is_queue_proxy(queue)) return nullptr; - return reinterpret_cast(static_cast(queue)->real); -} - -ID3D12Fence* fence_proxy_real_fence(const void* fence) { - if (!is_fence_proxy(fence)) return nullptr; - return reinterpret_cast(static_cast(fence)->real); -} - -unsigned queue_proxy_slot_count(const void* queue) { - return is_queue_proxy(queue) ? static_cast(queue)->slot_count : 0; -} - -unsigned fence_proxy_slot_count(const void* fence) { - return is_fence_proxy(fence) ? static_cast(fence)->slot_count : 0; -} - -unsigned queue_proxy_table_size() { return kQueueSlots; } -unsigned fence_proxy_table_size() { return kFenceSlots; } -unsigned allocator_proxy_table_size() { return kAllocatorSlots; } -unsigned allocator_proxy_slot_count(const void* allocator) { - return is_allocator_proxy(allocator) ? static_cast(allocator)->slot_count : 0; -} - -unsigned long command_object_proxy_ref_count(const void* object) { - if (!is_queue_proxy(object) && !is_fence_proxy(object) && !is_allocator_proxy(object)) return 0; - return static_cast(object)->refs.load(std::memory_order_relaxed); -} - -std::uint64_t queue_slot_hits(unsigned slot) { - using S = ChildStats; - start_hit_counts(); - return slot < S::kSlots ? S::hits[slot].load(std::memory_order_relaxed) : 0; -} - -bool queue_slot_first_call_seen(unsigned slot) { - using S = ChildStats; - return slot < S::kSlots && S::first[slot].load(std::memory_order_relaxed); -} - -std::uint64_t fence_slot_hits(unsigned slot) { - using S = ChildStats; - start_hit_counts(); - return slot < S::kSlots ? S::hits[slot].load(std::memory_order_relaxed) : 0; -} - -bool fence_slot_first_call_seen(unsigned slot) { - using S = ChildStats; - return slot < S::kSlots && S::first[slot].load(std::memory_order_relaxed); -} - -std::uint64_t queue_table_overruns() { - return ChildStats::overruns.load(std::memory_order_relaxed); -} - -std::uint64_t fence_table_overruns() { - return ChildStats::overruns.load(std::memory_order_relaxed); -} - -bool command_object_tables_guarded() { - get_child_vtable(); - get_child_vtable(); - get_child_vtable(); - return ChildStats::table_end.load(std::memory_order_acquire) && - ChildStats::table_end.load(std::memory_order_acquire) && - ChildStats::table_end.load(std::memory_order_acquire); -} - -std::uint64_t allocator_slot_hits(unsigned slot) { - using S = ChildStats; - start_hit_counts(); - return slot < S::kSlots ? S::hits[slot].load(std::memory_order_relaxed) : 0; -} - -bool allocator_slot_first_call_seen(unsigned slot) { - using S = ChildStats; - return slot < S::kSlots && S::first[slot].load(std::memory_order_relaxed); -} - -std::uint64_t allocator_table_overruns() { - return ChildStats::overruns.load(std::memory_order_relaxed); -} - -bool heap_slot_overridden(unsigned slot) { - return slot <= 2 || slot == 7 || slot == 9 || slot == 10; -} - -std::uint64_t device_slot_hits(unsigned slot) { - start_hit_counts(); - return slot < kMaxSlots ? g_hits[slot].load(std::memory_order_relaxed) : 0; -} - -bool device_slot_first_call_seen(unsigned slot) { - return slot < kMaxSlots && g_first[slot].load(std::memory_order_relaxed); -} - -unsigned long device_proxy_ref_count(const void* device) { - if (!is_device_proxy(device)) return 0; - return static_cast(device)->refs.load(std::memory_order_relaxed); -} - -std::uint64_t heap_slot_hits(unsigned slot) { - start_hit_counts(); - return slot < kHeapSlots ? g_heap_hits[slot].load(std::memory_order_relaxed) : 0; -} - -bool heap_slot_first_call_seen(unsigned slot) { - return slot < kHeapSlots && g_heap_first[slot].load(std::memory_order_relaxed); -} - -bool is_command_list_proxy(const void* list) { - return list && *reinterpret_cast(list) == reinterpret_cast(get_list_vtable()); -} - -ID3D12GraphicsCommandList* command_list_proxy_real_list(const void* list) { - if (!is_command_list_proxy(list)) return nullptr; - return static_cast(list)->real; -} - -unsigned command_list_proxy_table_size() { return kListSlots; } - -std::uint64_t list_slot_hits(unsigned slot) { - start_hit_counts(); - return slot < kListSlots ? ListStats::hits[slot].load(std::memory_order_relaxed) : 0; -} - -bool list_slot_first_call_seen(unsigned slot) { - return slot < kListSlots && ListStats::first[slot].load(std::memory_order_relaxed); -} - -void reset_device_proxy_stats() { - start_hit_counts(); - for (unsigned slot = 0; slot < kMaxSlots; ++slot) { - g_hits[slot].store(0, std::memory_order_relaxed); - g_first[slot].store(false, std::memory_order_relaxed); - g_beyond_warned[slot].store(false, std::memory_order_relaxed); - } - for (unsigned slot = 0; slot < kHeapSlots; ++slot) { - g_heap_hits[slot].store(0, std::memory_order_relaxed); - g_heap_first[slot].store(false, std::memory_order_relaxed); - } - for (unsigned slot = 0; slot < kListSlots; ++slot) { - ListStats::hits[slot].store(0, std::memory_order_relaxed); - ListStats::first[slot].store(false, std::memory_order_relaxed); - } - reset_child_stats(); - reset_child_stats(); - reset_child_stats(); -} - -} // namespace rt::d3d12_xs diff --git a/runtime/shims/d3d12_xs_device.h b/runtime/shims/d3d12_xs_device.h deleted file mode 100644 index 6838ec54f..000000000 --- a/runtime/shims/d3d12_xs_device.h +++ /dev/null @@ -1,258 +0,0 @@ -// Xbox-ABI proxy around a PC ID3D12Device. -// -// Measured Xbox device deviations used here (vtable indices, x64): -// slot 62 CreateComputePipelineState(desc, w2, w3, iid, out): two words (0 from XboxBvhBuilder, meaning unknown) -// before the IID. The PC slot 62 is CreateStateObject. -// slot 67 CreateComputePipelineState from native code (desc, iid, out): converts the Xbox native-code desc -// (+0x00 root signature, +0x28 code, +0x30 size) to D3D12_COMPUTE_PIPELINE_STATE_DESC and forwards -// to PC CreateComputePipelineState (slot 11). The PC slot 67 is CreateProtectedResourceSession1. -// slot 76 resource creation -> PC CreateCommittedResource (PC slot 27), with the Xbox layout word ignored. -// slot 48 CreateCommandQueueX(desc, riid, out) -> the same queue proxy as slot 8. The Xbox desc's first fields are -// D3D12_COMMAND_QUEUE_DESC's (public HLE). -// slot 73 CreateCommandListX(desc, allocator, initialState, riid, out) -> PC CreateCommandList(0, type, allocator, -// initialState, riid, out). The type is the first word of the Xbox desc; there is no node-mask argument -// in the console call (public HLE; the PC six-argument form differs). -// slots 78/79/80 SetFrameIntervalX, ScheduleFrameEventX, WaitFrameEventX. A per-device token state machine answers -// them before the PC vtable is indexed; WaitFrameEventX returns at once with a fresh non-zero token. -// Slot 80 is outside a PC ID3D12Device11 table, so it is checked before the beyond-table refusal. -// A frame-event sink (set_device_frame_event_sink below) takes the three calls over when one is set. -// The slots 48/73/78/79/80 are the public HLE Freminet/ScarlettX's observation, not Microsoft documentation, and can -// be moved with LEONIDA_XS_QUEUE_X_SLOT, LEONIDA_XS_LIST_X_SLOT, LEONIDA_XS_FRAME_INTERVAL_SLOT, -// LEONIDA_XS_SCHEDULE_EVENT_SLOT and LEONIDA_XS_WAIT_EVENT_SLOT (3..127; anything else is logged once and ignored). -// The measured slots 9/10 (GetCPU/GPUDescriptorHandleForHeapStart) are ID3D12DescriptorHeap methods, not device -// methods: the PC device's 9/10 are CreateCommandAllocator/CreateGraphicsPipelineState and are forwarded unchanged. -// On the PC heap those getters use the hidden return pointer in RDX; the Xbox ABI returns the 8-byte handle in -// RAX. Device slot 14 therefore wraps the created heap in a heap proxy that performs that conversion. The heap -// proxy holds a reference to the device proxy, and its ID3D12DeviceChild::GetDevice returns that same proxy. -// The proxy's heap slots 9/10 expose only the Xbox shape: a PC C++ caller using the PC header's return convention -// would not receive the value, while GetDesc and the other heap slots forward the PC convention unchanged. A -// direct one-argument call against a real PC heap is invalid, so the device test exercises the conversion on the -// wrapper and compares it with a hidden-pointer call against the real heap. -// -// Every other PC device slot is forwarded by a generated thunk that swaps `this` to the PC device. The proxy's -// vtable therefore follows the PC device order, with slots 62 and 76 and the public HLE's 48/73/78/79/80 deliberately -// shadowed. The full Xbox vtable order is not known from the spec; slots beyond the PC device's own vtable return -// E_NOTIMPL and log once. -// -// Command queues and fences (device slots 8, 75, 36, and 32 for a shared fence) come back wrapped in queue and fence -// proxies of the same kind: the public chain (19 queue slots, 11 or 12 fence slots in SDK 10.0.26100) is forwarded -// in PC order, and a slot past it, up to the end of the proxy's table (128 queue, 64 fence slots), is logged with its -// first four argument words and refused with E_NOTIMPL. A slot past the table faults on the vtable read inside a -// reserved, never-committed region, and the fault is logged with the slot. That is where the console's queue methods -// (PresentX, SuspendX, ResumeX) will show up; their slots are not known and are not guessed (PresentX is routed only -// at a slot a setting names, see PresentSink below), and that the console keeps the public slots is an assumption -// (docs/d3d12_command_objects.md §5.2). Heap, queue and fence proxies are -// unwrapped wherever a device or queue method hands them to the real runtime: queue Signal/Wait (14/15), device -// CreateSharedHandle (31), MakeResident/Evict (34/35), SetEventOnMultipleFenceCompletion (45), SetResidencyPriority -// (46) and EnqueueMakeResident (50). Command lists are not wrapped, so ExecuteCommandLists passes them through and a -// heap proxy given to a list's SetDescriptorHeaps reaches the real list as it is. QueryInterface answers only the -// modelled interfaces; one the real object has but the proxy does not model is logged once and refused. -#pragma once - -#include - -#include -#include - -namespace rt::d3d12_xs { - -// Wraps `real` and returns the requested device interface through `out`. Takes ownership of one reference to -// `real` on success; on failure the caller keeps its reference. Returns E_NOINTERFACE if `riid` is not a D3D12 -// device interface the PC device implements. -HRESULT create_device_proxy(ID3D12Device* real, REFIID riid, void** out); - -// True when `device` points at a proxy created by create_device_proxy. Used by the tests. -bool is_device_proxy(const void* device); - -// IDXGIDevice1 on the device. A GDKX title asks its device for IDXGIDevice1, then GetAdapter and EnumOutputs(0), -// to find the output it gives SetFrameIntervalX (docs/d3d12_vulkan.md section 4.5). The proxy answers IDXGIObject, -// IDXGIDevice and IDXGIDevice1 itself, as one COM object with the device (same reference count, QueryInterface -// both ways). GetAdapter and GetParent return the adapter of the device behind the proxy: by default the host DXGI -// adapter with that device's LUID. A provider replaces that: `real` is the device behind the proxy, and it returns -// the adapter as `riid`. rt::d3d12::set_device_outer sets one for the Vulkan-backed device (the layer's own adapter). -// -// A title may ask D3D12XboxCreateDevice (so create_device_proxy) for IDXGIDevice1 directly. What comes back then is -// the proxy's DXGI pointer, not the proxy: is_device_proxy is false for it. Code that takes "the proxy" from a -// creation call goes through device_proxy_primary first. -using DxgiAdapterProvider = HRESULT (*)(ID3D12Device* real, REFIID riid, void** out); -// `device` is the proxy or its DXGI pointer. False, with a line on stderr, when it is neither: nothing is set then. -bool set_device_adapter_provider(void* device, DxgiAdapterProvider provider); -// The device proxy an IDXGIDevice pointer handed out by one belongs to, or null. -void* device_proxy_from_dxgi_device(void* dxgi_device); -// The device proxy itself, given the proxy or its DXGI pointer; null for anything else. -void* device_proxy_primary(void* device); - -// The frame calls of device slots 78/79/80 (at their configured indices). With no sink the proxy answers them -// itself, as described at the top: S_OK, and a fresh non-zero token at once. A sink takes them over: the proxy passes -// the title's words on and returns the sink's result. A sink is meant to stand in front of the presentation class -// (rt::d3d12::XboxPresentation, whose timing is src/frame_pacer.h); the proxy does not know that class, so this file -// needs neither a presenter nor Vulkan. A null function leaves that one call with the proxy's own answer. -// The reserved pointer of ScheduleFrameEventX and WaitFrameEventX (their third word) is not passed on: nothing models -// it. A null token pointer is refused with E_POINTER before the sink is called. -// The sink is not copied: it and what `context` points at must stay valid until another sink (or null) is set and -// every frame call that had already entered the sink has returned. A wait can block in the sink, so whoever takes a -// sink away makes its waits return first. -struct FrameEventSink { - void* context; - HRESULT (*set_frame_interval)(void* context, void* output, std::uint32_t interval_us, std::uint32_t latency, - std::uint32_t flags); - HRESULT (*schedule_frame_event)(void* context, std::uint32_t event, std::uint32_t offset_us, std::uint32_t flags); - HRESULT (*wait_frame_event)(void* context, std::uint32_t event, std::uint32_t timeout_ms, std::uint32_t flags, - std::uint64_t* token); -}; -// `device` is the proxy or its DXGI pointer; a null `sink` goes back to the proxy's own answers. False, with a line -// on stderr, when `device` is neither: nothing is set then. -bool set_device_frame_event_sink(void* device, const FrameEventSink* sink); -// The sink set on a device proxy, or null. Test helper. -const FrameEventSink* device_frame_event_sink(const void* device); - -// PresentX on the command queue. It is a queue method past the public chain and its slot is not measured for this -// title (public code gives 30 for an older runtime layout and 32 for a newer one, shims/xbox_present.h), so no slot -// is taken for it unless a setting names one: d3d12.present_x_slot (LEONIDA_XS_PRESENT_X_SLOT), a slot of the queue -// proxy's refused tail (19..127; anything else is logged once and ignored). The setting is read once, on the first -// queue call past the public chain or the first queue_present_x_slot(). -// A call on that slot goes to the present sink of the queue's device, also for a queue made before the sink was set: -// the sink gets the real queue behind the proxy and the title's three words (plane count, planes, parameters), and -// its result is the title's. The two structures are not read here; their layouts are in shims/xbox_present.h. With -// the slot set and no sink (or a sink with a null function) the call is refused with E_NOTIMPL and logged once. -// The sink is not copied; the lifetime rule is the frame-event sink's. -struct PresentSink { - void* context; - HRESULT (*present_x)(void* context, ID3D12CommandQueue* queue, std::uint32_t plane_count, const void* planes, - const void* params); -}; -// `device` is the proxy or its DXGI pointer; a null `sink` takes the sink away. False, with a line on stderr, when -// `device` is neither: nothing is set then. -bool set_device_present_sink(void* device, const PresentSink* sink); -// The present sink set on a device proxy, or null. Test helper. -const PresentSink* device_present_sink(const void* device); -// The queue slot taken for PresentX, or 0 when the setting names none. -unsigned queue_present_x_slot(); - -// True when `heap` is a descriptor-heap proxy created by device slot 14. -bool is_heap_proxy(const void* heap); -ID3D12DescriptorHeap* heap_proxy_real_heap(const void* heap); - -// Number of PC vtable slots the proxy forwards (detected from the interfaces the PC device supports). -unsigned device_proxy_slot_count(const void* device); - -// The PC device behind a proxy. Null when `device` is not a proxy. -ID3D12Device* device_proxy_real_device(const void* device); - -// Device slot 133 (the console's CreatePlacedResourceX) makes a buffer on the title's pages at `va`. The proxy does -// not create it itself: the device behind it does, through this handler, which the Vulkan layer registers -// (rt::d3d12::create_buffer_at_host_address). With none registered, or a PC device behind the proxy, the slot -// answers E_NOTIMPL. -// `layout` is the title's third argument, a D3D12_BARRIER_LAYOUT (0xFFFFFFFF = UNDEFINED), measured on a retail -// boot: 0x6 SHADER_RESOURCE, 0x3 UNORDERED_ACCESS, as PC CreatePlacedResource2 takes it. -using PlacedAtVaHandler = HRESULT (*)(ID3D12Device* real, void* va, const D3D12_RESOURCE_DESC& desc, - std::uint32_t layout, REFIID riid, void** out); -void set_placed_at_va_handler(PlacedAtVaHandler handler); - -// Called by slot 133 for a buffer, before the handler, with the buffer's range [va, va + width). gta6rt registers -// rt::xmem::commit_physical_range: xmem commits physical pages on first touch, so a range the title has mapped but -// not written yet is still reserved, and the handler's import refuses reserved pages (it would answer with its -// fallback buffer, which the title's writes never reach). A false return is logged once and the handler is still -// called. With none registered nothing is done. -using PlacedAtVaPagesHook = bool (*)(const void* va, std::size_t bytes); -void set_placed_at_va_pages_hook(PlacedAtVaPagesHook hook); - -// Device slot 14's console-extended CreateDescriptorHeap: the description is the PC 16-byte shape followed by a -// console VA and a size (issue #313). The proxy does not create the heap itself: the device behind it registers this -// handler, which the Vulkan layer implements (rt::d3d12::create_console_descriptor_heap). With none registered, or a -// 16-byte PC description (address 0), the slot uses the PC CreateDescriptorHeap. -using ConsoleDescriptorHeapHandler = HRESULT (*)(ID3D12Device* real, const D3D12_DESCRIPTOR_HEAP_DESC* desc, - D3D12_GPU_VIRTUAL_ADDRESS console_address, std::uint64_t console_size, - REFIID riid, void** out); -void set_console_descriptor_heap_handler(ConsoleDescriptorHeapHandler handler); - -// True for slots the proxy handles itself rather than forwarding verbatim: IUnknown (0-2), 8 and 75 (queue -// proxies), 9 (allocator proxies), 14, 31/34/35/45/46/50 (proxies unwrapped), 32 and 36 (fence proxies), 48/73 and -// 78/79/80 (the Xbox slots above, at their configured indices), 62, 67 and 76. Slot 10 is intentionally false: the -// measured 9/10 handle conversion is on the heap proxy, and device slot 9 is CreateCommandAllocator, which the proxy -// handles for the allocator proxy. -bool device_slot_overridden(unsigned slot); - -// Queue and fence proxies created by device slots 8/75 and 36. The real_* accessors return the wrapped object -// (no reference added), or null when the pointer is not such a proxy. -bool is_queue_proxy(const void* queue); -bool is_fence_proxy(const void* fence); -ID3D12CommandQueue* queue_proxy_real_queue(const void* queue); -ID3D12Fence* fence_proxy_real_fence(const void* fence); -// Public slots forwarded (19 for a queue; 11 or 12 for a fence), and the size of the proxy's vtable. -unsigned queue_proxy_slot_count(const void* queue); -unsigned fence_proxy_slot_count(const void* fence); -unsigned queue_proxy_table_size(); -unsigned fence_proxy_table_size(); -// Live references on a queue, fence or allocator proxy (0 for anything else). Test helper. -unsigned long command_object_proxy_ref_count(const void* object); -// Per-slot call counters and first-call flags, shared by all queue proxies and all fence proxies. -std::uint64_t queue_slot_hits(unsigned slot); -bool queue_slot_first_call_seen(unsigned slot); -std::uint64_t fence_slot_hits(unsigned slot); -bool fence_slot_first_call_seen(unsigned slot); -// Vtable reads past a queue or fence proxy table that faulted in its guard region (counted by the fault logger). -std::uint64_t queue_table_overruns(); -std::uint64_t fence_table_overruns(); -// True when the queue, fence and allocator tables sit in front of their guard regions (false only if a reservation -// or the fault logger failed). -bool command_object_tables_guarded(); - -// Command allocator proxies (device slot 9): the public chain (9 slots: the base chain and Reset) is forwarded, a -// slot past it up to the end of the table (64 slots) is logged and refused with E_NOTIMPL, and a read past the -// table faults in a guard region, as for queues and fences. The console allocator's extra methods are not -// measured and not guessed. Slot 9 wraps only an allocator that answers kLeonidaCommandAllocatorTag, Leonida's -// own Vulkan-layer allocator: its command lists resolve the proxy (CreateCommandList, Reset). A PC runtime -// allocator goes back unchanged, because the PC runtime's lists would take a proxy for their own allocator; a -// command-list proxy that unwraps at Reset is what lets the host backend wrap allocators too. -// {7d0e6b51-34a2-4f0c-9a61-0c5b2e8f4a10}: the Vulkan layer's CommandAllocator answers it with its implementation. -inline constexpr GUID kLeonidaCommandAllocatorTag{ - 0x7d0e6b51, 0x34a2, 0x4f0c, {0x9a, 0x61, 0x0c, 0x5b, 0x2e, 0x8f, 0x4a, 0x10}}; -bool is_allocator_proxy(const void* allocator); -// The wrapped allocator (no reference added), or null when `allocator` is not an allocator proxy. -ID3D12CommandAllocator* allocator_proxy_real_allocator(const void* allocator); -unsigned allocator_proxy_slot_count(const void* allocator); -unsigned allocator_proxy_table_size(); -std::uint64_t allocator_slot_hits(unsigned slot); -bool allocator_slot_first_call_seen(unsigned slot); -std::uint64_t allocator_table_overruns(); -// Command list proxies created by device slot 73 (CreateCommandListX): -bool is_command_list_proxy(const void* list); -ID3D12GraphicsCommandList* command_list_proxy_real_list(const void* list); -unsigned command_list_proxy_table_size(); -std::uint64_t list_slot_hits(unsigned slot); -bool list_slot_first_call_seen(unsigned slot); - -// Heap slots 0-2, 7 (GetDevice -> device proxy) and 9/10 (handle conversion). -bool heap_slot_overridden(unsigned slot); - -// Console list slot mapping: returns PC vtable slot or ~0u if console-only / unforwarded. -inline constexpr unsigned kListNotForwarded = ~0u; -inline constexpr unsigned console_to_pc_list_slot(unsigned slot) { - if (slot <= 26) return slot; // PC order, measured - if (slot <= 30) return kListNotForwarded; // console-only extras - if (slot <= 59) return slot - 4; // PC chain, shifted +4 - if (slot == 60) return 58; // EndEvent (no console SetMarker/BeginEvent) - if (slot == 61) return 59; // ExecuteIndirect (Package) - if (slot == 85) return 16; // CopyTextureRegionX -> CopyTextureRegion - if (slot == 146) return 80; // D3D12_BARRIER_GROUP (Package; PC GCL7) - return kListNotForwarded; -} - - -// Number of live references on a device proxy. Test helper for the heap's GetDevice/lifetime checks. -unsigned long device_proxy_ref_count(const void* device); - -// Per-slot call counters and first-call flags for the device and heap proxies. Slot 0 also counts the -// QueryInterface call made while a proxy is created, so tests reset the counters after creation. -// reset_device_proxy_stats also resets the queue and fence counters. -// The hit counters (device, heap, queue, fence and allocator) are for tests, and they are off at the start. -// A test must read a counter (any *_slot_hits function) or call reset_device_proxy_stats BEFORE the calls that it -// counts. Calls made before that are not counted (the counter stays 0); they set only the first-call flags. -std::uint64_t device_slot_hits(unsigned slot); -bool device_slot_first_call_seen(unsigned slot); -std::uint64_t heap_slot_hits(unsigned slot); -bool heap_slot_first_call_seen(unsigned slot); -void reset_device_proxy_stats(); - -} // namespace rt::d3d12_xs diff --git a/runtime/shims/d3d12_xs_rootsig.cpp b/runtime/shims/d3d12_xs_rootsig.cpp deleted file mode 100644 index f29d7e021..000000000 --- a/runtime/shims/d3d12_xs_rootsig.cpp +++ /dev/null @@ -1,222 +0,0 @@ -#include "d3d12_xs_rootsig.h" - -#include - -namespace rt::d3d12_xs { -namespace { - -D3D12_ROOT_SIGNATURE_FLAGS clear_high_byte(D3D12_ROOT_SIGNATURE_FLAGS flags) { - return static_cast(static_cast(flags) & ~kXboxRootSignatureFlagHighByte); -} - -uint32_t rotl(uint32_t x, int c) { return (x << c) | (x >> (32 - c)); } - -void md5_block(uint32_t state[4], const uint32_t m[16]) { - static const uint32_t k[64] = { - 0xd76aa478, 0xe8c7b756, 0x242070db, 0xc1bdceee, 0xf57c0faf, 0x4787c62a, 0xa8304613, 0xfd469501, - 0x698098d8, 0x8b44f7af, 0xffff5bb1, 0x895cd7be, 0x6b901122, 0xfd987193, 0xa679438e, 0x49b40821, - 0xf61e2562, 0xc040b340, 0x265e5a51, 0xe9b6c7aa, 0xd62f105d, 0x02441453, 0xd8a1e681, 0xe7d3fbc8, - 0x21e1cde6, 0xc33707d6, 0xf4d50d87, 0x455a14ed, 0xa9e3e905, 0xfcefa3f8, 0x676f02d9, 0x8d2a4c8a, - 0xfffa3942, 0x8771f681, 0x6d9d6122, 0xfde5380c, 0xa4beea44, 0x4bdecfa9, 0xf6bb4b60, 0xbebfbc70, - 0x289b7ec6, 0xeaa127fa, 0xd4ef3085, 0x04881d05, 0xd9d4d039, 0xe6db99e5, 0x1fa27cf8, 0xc4ac5665, - 0xf4292244, 0x432aff97, 0xab9423a7, 0xfc93a039, 0x655b59c3, 0x8f0ccc92, 0xffeff47d, 0x85845dd1, - 0x6fa87e4f, 0xfe2ce6e0, 0xa3014314, 0x4e0811a1, 0xf7537e82, 0xbd3af235, 0x2ad7d2bb, 0xeb86d391}; - static const int r[16] = {7, 12, 17, 22, 5, 9, 14, 20, 4, 11, 16, 23, 6, 10, 15, 21}; - uint32_t a = state[0], b = state[1], c = state[2], d = state[3]; - for (int i = 0; i < 64; ++i) { - uint32_t f; - int g; - if (i < 16) { f = (b & c) | (~b & d); g = i; } - else if (i < 32) { f = (d & b) | (~d & c); g = (5 * i + 1) % 16; } - else if (i < 48) { f = b ^ c ^ d; g = (3 * i + 5) % 16; } - else { f = c ^ (b | ~d); g = (7 * i) % 16; } - const uint32_t t = d; - d = c; - c = b; - b += rotl(a + f + k[i] + m[g], r[i / 16 * 4 + i % 4]); - a = t; - } - state[0] += a; state[1] += b; state[2] += c; state[3] += d; -} - -} // namespace - -void dxbc_checksum(const uint8_t* blob, size_t size, uint32_t out[4]) { - if (!out) return; - if (!blob || size < 20 || size - 20 > 0x1FFFFFFFu) { - std::memset(out, 0, 16); - return; - } - // MD5 with the DXBC tail: the bit count goes first in the last block and (bits >> 2) | 1 last, in place of - // MD5's 64-bit length (the d3dcompiler container hash; vkd3d-shader and Wine use the same). - const uint8_t* data = blob + 20; - const uint32_t n = static_cast(size - 20); - const uint32_t bits = n * 8; - uint32_t state[4] = {0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476}; - uint32_t m[16]; - const uint32_t full = n / 64 * 64; - for (uint32_t i = 0; i < full; i += 64) { - std::memcpy(m, data + i, 64); - md5_block(state, m); - } - const uint32_t left = n - full; - uint8_t block[64] = {}; - if (left >= 56) { - std::memcpy(block, data + full, left); - block[left] = 0x80; - std::memcpy(m, block, 64); - md5_block(state, m); - std::memset(m, 0, sizeof(m)); - } else { - std::memcpy(block + 4, data + full, left); - block[4 + left] = 0x80; - std::memcpy(m, block, 64); - } - m[0] = bits; - m[15] = (bits >> 2) | 1; - md5_block(state, m); - std::memcpy(out, state, 16); -} - -bool copy_versioned_root_signature_desc_clear_xbox_flags(const D3D12_VERSIONED_ROOT_SIGNATURE_DESC& in, - D3D12_VERSIONED_ROOT_SIGNATURE_DESC& out) { - out = in; - switch (in.Version) { - case D3D_ROOT_SIGNATURE_VERSION_1_0: - out.Desc_1_0.Flags = clear_high_byte(in.Desc_1_0.Flags); - return true; - case D3D_ROOT_SIGNATURE_VERSION_1_1: - out.Desc_1_1.Flags = clear_high_byte(in.Desc_1_1.Flags); - return true; - case D3D_ROOT_SIGNATURE_VERSION_1_2: - out.Desc_1_2.Flags = clear_high_byte(in.Desc_1_2.Flags); - return true; - default: - // Unknown version: forward unchanged. - return false; - } -} - -bool downgrade_root_signature_1_2_to_1_1(const D3D12_VERSIONED_ROOT_SIGNATURE_DESC& in, - std::vector& samplers, - D3D12_VERSIONED_ROOT_SIGNATURE_DESC& out) { - if (in.Version != D3D_ROOT_SIGNATURE_VERSION_1_2) return false; - const D3D12_ROOT_SIGNATURE_DESC2& desc = in.Desc_1_2; - if (desc.NumStaticSamplers != 0 && !desc.pStaticSamplers) return false; - for (UINT i = 0; i < desc.NumStaticSamplers; ++i) - if (desc.pStaticSamplers[i].Flags != D3D12_SAMPLER_FLAG_NONE) return false; - - samplers.resize(desc.NumStaticSamplers); - for (UINT i = 0; i < desc.NumStaticSamplers; ++i) { - const D3D12_STATIC_SAMPLER_DESC1& s = desc.pStaticSamplers[i]; - // D3D12_STATIC_SAMPLER_DESC is D3D12_STATIC_SAMPLER_DESC1 without the trailing Flags. - samplers[i] = {s.Filter, s.AddressU, s.AddressV, s.AddressW, s.MipLODBias, s.MaxAnisotropy, - s.ComparisonFunc, s.BorderColor, s.MinLOD, s.MaxLOD, s.ShaderRegister, s.RegisterSpace, - s.ShaderVisibility}; - } - out = {}; - out.Version = D3D_ROOT_SIGNATURE_VERSION_1_1; - out.Desc_1_1.NumParameters = desc.NumParameters; - out.Desc_1_1.pParameters = desc.pParameters; // D3D12_ROOT_PARAMETER1 in both versions - out.Desc_1_1.NumStaticSamplers = desc.NumStaticSamplers; - out.Desc_1_1.pStaticSamplers = samplers.empty() ? nullptr : samplers.data(); - out.Desc_1_1.Flags = desc.Flags; - return true; -} - -void copy_root_signature_desc_clear_xbox_flags(const D3D12_ROOT_SIGNATURE_DESC& in, D3D12_ROOT_SIGNATURE_DESC& out) { - out = in; - out.Flags = clear_high_byte(in.Flags); -} - -bool copy_rts0_blob_clear_xbox_flags(const void* data, size_t size, std::vector& out) { - out.clear(); - if (!data || size < 36 || size - 20 > 0x1FFFFFFFu) return false; - - const uint8_t* bytes = static_cast(data); - // The host deserializer only consumes the DXBC container the serializer - // produces, so a non-DXBC blob is forwarded unchanged (no rewrite). - if (std::memcmp(bytes, "DXBC", 4) != 0) return false; - - uint32_t total_size = 0; - std::memcpy(&total_size, bytes + 24, sizeof(total_size)); - if (total_size != size) return false; - - uint32_t chunk_count = 0; - std::memcpy(&chunk_count, bytes + 28, sizeof(chunk_count)); - if (chunk_count == 0 || chunk_count > 16 || static_cast(chunk_count) * 4 > size - 32) return false; - - // Verify the incoming container hash before rewriting: a corrupted blob must reach the host deserializer - // unchanged so it is rejected, rather than getting a freshly forged valid hash. Host d3d12.dll accepts a - // matching DXBC checksum or an all-zero one and rejects any other with E_INVALIDARG, so an all-zero checksum - // is accepted here too and stays zero in the rewritten blob. - constexpr uint8_t kZeroHash[16] = {}; - const bool zero_hash = std::memcmp(bytes + 4, kZeroHash, sizeof(kZeroHash)) == 0; - if (!zero_hash) { - uint32_t expected_hash[4]; - dxbc_checksum(bytes, size, expected_hash); - if (std::memcmp(expected_hash, bytes + 4, sizeof(expected_hash)) != 0) return false; - } - - // Fail closed on any malformed chunk-table entry (5c3487a94). - const size_t min_chunk_off = 32 + static_cast(chunk_count) * 4; - bool found_rts0 = false; - uint32_t rts0_off = 0; - for (uint32_t i = 0; i < chunk_count; ++i) { - uint32_t off = 0; - std::memcpy(&off, bytes + 32 + static_cast(i) * 4, sizeof(off)); - if (off < min_chunk_off || off > size || size - off < 8) return false; - uint32_t chunk_size = 0; - std::memcpy(&chunk_size, bytes + off + 4, sizeof(chunk_size)); - if (chunk_size > size - off - 8) return false; - if (!found_rts0 && std::memcmp(bytes + off, "RTS0", 4) == 0) { - if (chunk_size < 24) return false; - found_rts0 = true; - rts0_off = off; - } - } - if (!found_rts0) return false; - - const uint8_t* payload = bytes + rts0_off + 8; - uint32_t rts_version = 0; - std::memcpy(&rts_version, payload, sizeof(rts_version)); - if (rts_version < 1 || rts_version > 3) return false; - - uint32_t flags = 0; - std::memcpy(&flags, payload + 20, sizeof(flags)); - const uint32_t cleared = static_cast(clear_high_byte( - static_cast(flags))); - if (cleared == flags) return false; // no Xbox high byte - - out.assign(bytes, bytes + size); - std::memcpy(out.data() + rts0_off + 8 + 20, &cleared, sizeof(cleared)); - // The host deserializer checks the container hash (bytes 4..19), so a stale one is E_INVALIDARG; an all-zero - // checksum is not checked and is kept. - if (!zero_hash) { - uint32_t hash[4]; - dxbc_checksum(out.data(), out.size(), hash); - std::memcpy(out.data() + 4, hash, sizeof(hash)); - } - return true; -} - -bool copy_dxbc_blob_fill_zero_checksum(const void* data, size_t size, std::vector& out) { - out.clear(); - if (!data || size < 32 || size - 20 > 0x1FFFFFFFu) return false; - - const uint8_t* bytes = static_cast(data); - if (std::memcmp(bytes, "DXBC", 4) != 0) return false; - constexpr uint8_t kZeroHash[16] = {}; - if (std::memcmp(bytes + 4, kZeroHash, sizeof(kZeroHash)) != 0) return false; - uint32_t total_size = 0; - std::memcpy(&total_size, bytes + 24, sizeof(total_size)); - if (total_size != size) return false; - - out.assign(bytes, bytes + size); - uint32_t hash[4]; - dxbc_checksum(out.data(), out.size(), hash); - std::memcpy(out.data() + 4, hash, sizeof(hash)); - return true; -} - -} // namespace rt::d3d12_xs diff --git a/runtime/shims/d3d12_xs_rootsig.h b/runtime/shims/d3d12_xs_rootsig.h deleted file mode 100644 index 29fd01c2e..000000000 --- a/runtime/shims/d3d12_xs_rootsig.h +++ /dev/null @@ -1,55 +0,0 @@ -// Helpers for forwarding Xbox root-signature descriptions to the PC d3d12.dll. -// -// The measured Xbox descriptions carry type bits in the high byte of D3D12_ROOT_SIGNATURE_FLAGS (observed value -// 0x03000000). The PC serializer rejects those bits, so the shims pass a shallow copy with bits 24-31 cleared and -// every other flag bit preserved. The pointed-to parameter/sampler arrays are not modified. -#pragma once - -#include -#include -#include - -namespace rt::d3d12_xs { - -constexpr uint32_t kXboxRootSignatureFlagHighByte = 0xFF000000u; - -// Always copies `in` to `out`. Returns true for the known 1.0/1.1/1.2 descriptor versions and clears the high flag -// byte in the copy. Returns false for an unknown version, leaving the copy byte-for-byte identical to `in` so the -// caller can forward it unchanged and log the unsupported version. -bool copy_versioned_root_signature_desc_clear_xbox_flags(const D3D12_VERSIONED_ROOT_SIGNATURE_DESC& in, - D3D12_VERSIONED_ROOT_SIGNATURE_DESC& out); - -// Windows 10's built-in d3d12.dll serializes root signatures up to version 1.1: it rejects every 1.2 description, -// even an empty one, with E_INVALIDARG, and reports HighestVersion 1.1. Version 1.2 differs from 1.1 only in -// D3D12_STATIC_SAMPLER_DESC1::Flags, so a 1.2 description whose static samplers all have Flags == 0 is the same -// root signature written as 1.1. This rewrites it that way: `out` becomes a 1.1 description that shares `in`'s -// parameters and points its samplers at `samplers` (resized here; keep it alive while `out` is used). Returns false, -// with `out` and `samplers` untouched, when `in` is not version 1.2 or a static sampler has non-zero Flags (a UINT -// border colour or non-normalized coordinates, which 1.1 can't express). -bool downgrade_root_signature_1_2_to_1_1(const D3D12_VERSIONED_ROOT_SIGNATURE_DESC& in, - std::vector& samplers, - D3D12_VERSIONED_ROOT_SIGNATURE_DESC& out); - -// Legacy D3D12SerializeRootSignature descriptor (version 1.0): copies and clears the high flag byte. -void copy_root_signature_desc_clear_xbox_flags(const D3D12_ROOT_SIGNATURE_DESC& in, D3D12_ROOT_SIGNATURE_DESC& out); - -// D3D12CreateRootSignatureDeserializer path: the host deserializer accepts a correctly hashed blob whose RTS0 -// flags carry the Xbox high byte and hands the byte back, and CreateRootSignature then refuses it (E_FAIL on WARP -// and an RTX 5070). So copy the blob, clear bits 24-31 of the RTS0 flags, recompute the DXBC hash the host -// deserializer checks (a stale one is E_INVALIDARG; an all-zero hash is accepted as-is and kept zeroed), and return -// true with the copy in `out`. Returns false (and leaves `out` empty) when no rewrite is needed or the container is -// not valid to re-sign: no RTS0 chunk, no Xbox high byte, a malformed/truncated header, total_size != size, or a -// non-zero incoming DXBC hash that does not match the input bytes. -bool copy_rts0_blob_clear_xbox_flags(const void* data, size_t size, std::vector& out); - -// Microsoft's deserializer does not check an all-zero DXBC hash; Wine's refuses the blob (root_sig under Wine 9.0 and -// 11.0, run 45457013232). So for a DXBC container whose hash is all zero and whose total_size is `size`, copy it to -// `out` with the hash computed and return true: both hosts accept a matching hash. False, with `out` empty, for -// anything else. -bool copy_dxbc_blob_fill_zero_checksum(const void* data, size_t size, std::vector& out); - -// The DXBC container hash of `blob` (bytes 20..size), as stored at bytes 4..19. Zeroes `out` when `blob` is null, -// `size < 20`, or the hashed payload exceeds the 32-bit bit-count limit. -void dxbc_checksum(const uint8_t* blob, size_t size, uint32_t out[4]); - -} // namespace rt::d3d12_xs diff --git a/runtime/shims/dstorage.cpp b/runtime/shims/dstorage.cpp deleted file mode 100644 index 8ceb7e4a0..000000000 --- a/runtime/shims/dstorage.cpp +++ /dev/null @@ -1,1126 +0,0 @@ -// Xbox DirectStorage for a mapped title: DStorageGetFactory and the IDStorageFactoryX2 / IDStorageQueueX2 / -// IDStorageFileX / IDStorageStatusArrayX objects of the console API (dstorage_xs_abi.h). -// -// Served as dstorage_xs.dll, xcrdapi.dll and dstorage.dll!DStorageGetFactory; docs/directstorage.md has the evidence -// for those names, the console ABI and what each method does here. In short: -// - OpenFile resolves kernel32.dll!CreateFileW through the shim registry, so a GAME: path goes through the -// runtime's console path mapping and write overlay (file_system.cpp) exactly as the title's own CreateFileW. -// - Each queue has one worker thread that runs its submitted entries in order: a request reads a file range or -// copies a memory range into the destination, a status entry, fence signal or event runs when every entry before -// it has. Completion is therefore in queue order, as the API guarantees. -// - A zlib request (ZlibDecompress alone) reads its source into a staging buffer, inflates it on the worker with -// the runtime's RFC 1950 inflater (leonida::zlib_inflate, src/shader_library.h) and copies the result to the -// destination only when it is exactly DestinationSize bytes; a stream that fails leaves the destination as it was. -// - BCPack, swizzle and physical-page requests fail with E_NOTIMPL for now (later PRs: they become stages between -// the read and the destination write, BCPack after the inflate). -// Nothing here goes online or touches the GPU. -#include -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include "../src/shader_library.h" // leonida::zlib_inflate -#include "../core/log.h" -#include "dstorage_xs_abi.h" -#include "shims.h" - -using namespace dsx; - -namespace { - -// ---- Logging ------------------------------------------------------------------------------------------------------ - -// Process-lifetime state is allocated once and never freed: a worker thread may still run while statics are destroyed -// at exit. -std::mutex& log_mutex() { - static auto* m = new std::mutex; - return *m; -} - -void log_once(const std::string& key, const std::string& line) { - static auto* seen = new std::set; - std::lock_guard lock(log_mutex()); - if (!seen->insert(key).second) return; - RT_LOG_WARN("dstorage: %s\n", line.c_str()); -} - -std::string guid_text(const GUID& g) { - char b[48]; - std::snprintf(b, sizeof b, "{%08lx-%04x-%04x-%02x%02x-%02x%02x%02x%02x%02x%02x}", g.Data1, g.Data2, g.Data3, - g.Data4[0], g.Data4[1], g.Data4[2], g.Data4[3], g.Data4[4], g.Data4[5], g.Data4[6], g.Data4[7]); - return b; -} - -bool same_guid(const GUID& a, const GUID& b) { return std::memcmp(&a, &b, sizeof(GUID)) == 0; } - -std::string hr_text(HRESULT hr) { - char b[16]; - std::snprintf(b, sizeof b, "0x%08lx", static_cast(hr)); - return b; -} - -// ---- Interface ids ------------------------------------------------------------------------------------------------ -// -// The X interfaces' ids are not public. A creating call (DStorageGetFactory, CreateQueue*, OpenFile, -// CreateStatusArray) accepts an id it has not seen for the kind of object it hands out and logs it the first time, so -// the first boot records the console's ids. It refuses an id seen for another kind, a PC DirectStorage id of another -// shape, and the system COM interfaces (IMarshal, IAgileObject, ...), which a DirectStorage object never implements. -// QueryInterface is stricter (docs/d3d12_vulkan.md: an unknown id is E_NOINTERFACE): it accepts IUnknown, the -// declared ids (dstorage_xs_abi.h) and the ids a creating call accepted for that kind, and logs anything else. This is -// a policy, not a fact; it lives here so a measured id list can replace it. - -enum class Kind { Factory, Queue, File, StatusArray }; - -const char* kind_name(Kind k) { - switch (k) { - case Kind::Factory: return "factory"; - case Kind::Queue: return "queue"; - case Kind::File: return "file"; - case Kind::StatusArray: return "status array"; - } - return "?"; -} - -// System interfaces: the COM base range {xxxxxxxx-0000-0000-C000-000000000046} (IClassFactory, IMarshal, -// IStdMarshalInfo, IExternalConnection, IMultiQI, IClientSecurity, IServerSecurity, IRpcOptions, IMarshal2, -// IWeakReferenceSource, IDispatch, IPersist, ...) and these others. -constexpr GUID kSystemInterfaceIds[] = { - {0x94ea2b94, 0xe9cc, 0x49e0, {0xc0, 0xff, 0xee, 0x64, 0xca, 0x8f, 0x5b, 0x90}}, // IAgileObject - {0xecc8691b, 0xc1db, 0x4dc0, {0x85, 0x5e, 0x65, 0xf6, 0xc5, 0x51, 0xaf, 0x49}}, // INoMarshal - {0x1c733a30, 0x2a1c, 0x11ce, {0xad, 0xe5, 0x00, 0xaa, 0x00, 0x44, 0x77, 0x3d}}, // ICallFactory - {0xaf86e2e0, 0xb12d, 0x4c6a, {0x9c, 0x5a, 0xd7, 0xaa, 0x65, 0x10, 0x1e, 0x90}}, // IInspectable - {0xdf0b3d60, 0x548f, 0x101b, {0x8e, 0x65, 0x08, 0x00, 0x2b, 0x2b, 0xd1, 0x19}}, // ISupportErrorInfo - {0xb196b283, 0xbab4, 0x101a, {0xb6, 0x9c, 0x00, 0xaa, 0x00, 0x34, 0x1d, 0x07}}, // IProvideClassInfo - {0xb196b284, 0xbab4, 0x101a, {0xb6, 0x9c, 0x00, 0xaa, 0x00, 0x34, 0x1d, 0x07}}, // IConnectionPointContainer - {0xfc4801a3, 0x2ba9, 0x11cf, {0xa2, 0x29, 0x00, 0xaa, 0x00, 0x3d, 0x73, 0x52}}, // IObjectWithSite -}; - -bool system_interface(const GUID& g) { - static const uint8_t kComBase[8] = {0xc0, 0, 0, 0, 0, 0, 0, 0x46}; - if (g.Data2 == 0 && g.Data3 == 0 && std::memcmp(g.Data4, kComBase, 8) == 0) return true; - for (const GUID& s : kSystemInterfaceIds) - if (same_guid(g, s)) return true; - return false; -} - -// The ids declared for a kind: the PC IDStorageStatusArray id, whose interface has the console one's shape (console -// D3D12 binaries reuse the PC SDK's ids). No other X interface id is known. -bool declared(const GUID& g, Kind kind) { - for (const GUID& id : kStatusArrayIds) - if (same_guid(g, id)) return kind == Kind::StatusArray; - return false; -} - -bool declared_for_any(const GUID& g) { - for (const GUID& id : kStatusArrayIds) - if (same_guid(g, id)) return true; - return false; -} - -class IidPolicy { -public: - bool accept_creating(REFIID riid, Kind kind, const char* caller) { - if (same_guid(riid, __uuidof(IUnknown)) || declared(riid, kind)) return true; - if (system_interface(riid)) return refuse(riid, caller, "a system COM interface"); - if (declared_for_any(riid)) return refuse(riid, caller, "an id declared for another kind of object"); - for (const GUID& pc : kPcInterfaceIds) - if (same_guid(riid, pc)) - return refuse(riid, caller, "a PC DirectStorage interface; only the console ABI is served"); - std::lock_guard lock(mutex_); - for (const auto& [id, k] : learned_) - if (same_guid(id, riid)) { - if (k == kind) return true; - return refuse(riid, caller, std::string("seen before as a ") + kind_name(k) + " interface"); - } - learned_.push_back({riid, kind}); - log_once("learn" + guid_text(riid), std::string(caller) + " asked for " + guid_text(riid) + ": serving the " + - kind_name(kind) + " interface"); - return true; - } - - bool accept_query(REFIID riid, Kind kind, const char* caller) { - if (same_guid(riid, __uuidof(IUnknown)) || declared(riid, kind)) return true; - { - std::lock_guard lock(mutex_); - for (const auto& [id, k] : learned_) - if (same_guid(id, riid) && k == kind) return true; - } - return refuse(riid, caller, std::string("not an id a ") + kind_name(kind) + " was created with"); - } - -private: - static bool refuse(REFIID riid, const char* caller, const std::string& why) { - log_once(std::string("refuse") + caller + guid_text(riid), - std::string(caller) + " asked for " + guid_text(riid) + ": " + why + " (E_NOINTERFACE)"); - return false; - } - - std::mutex mutex_; - std::vector> learned_; -}; - -IidPolicy& iid_policy() { - static auto* p = new IidPolicy; - return *p; -} - -// A bad argument to a factory or queue method, logged once per method and kind: a wrong vtable guess for the console -// interfaces would show up here first, as arguments that make no sense for the method. -HRESULT bad_call(const char* method, HRESULT hr, const char* what) { - log_once(std::string("bad") + method + what, - std::string(method) + ": " + what + " (" + hr_text(hr) + - "; logged once; a wrong vtable slot guess would show up like this)"); - return hr; -} - -// ---- Statistics (IDStorageFactoryX1::GetStats) -------------------------------------------------------------------- - -struct Stats { - std::mutex mutex; - DSTORAGE_STATS s{}; - uint32_t live_queues = 0; // all priorities; SetStagingBufferSize is refused while queues or files exist -}; - -Stats& stats() { - static auto* s = new Stats; - return *s; -} - -DSTORAGE_PRIORITY_STATS& priority_stats(DSTORAGE_STATS& s, DSTORAGE_PRIORITY p) { - switch (p) { - case DSTORAGE_PRIORITY_LOW: return s.LowPriorityStats; - case DSTORAGE_PRIORITY_HIGH: return s.HighPriorityStats; - case DSTORAGE_PRIORITY_REALTIME: return s.RealtimePriorityStats; - default: return s.NormalPriorityStats; - } -} - -void count_error() { - std::lock_guard lock(stats().mutex); - ++stats().s.ErrorCount; -} - -// ---- Live objects --------------------------------------------------------------------------------------------------- -// -// A request names its file and a status entry its array by pointer. Only objects this shim made and that are still -// alive are used; anything else is an error in the request, never a call through a stranger's vtable. - -std::mutex& live_mutex() { - static auto* m = new std::mutex; - return *m; -} -// One set per kind, so a status array passed as a file (or the other way round) is not found. -std::unordered_set& live_files() { - static auto* s = new std::unordered_set; - return *s; -} -std::unordered_set& live_status_arrays() { - static auto* s = new std::unordered_set; - return *s; -} - -// AddRef only if the count has not reached zero (an object being released is not revived). -bool add_ref_if_live(std::atomic& refs) { - ULONG r = refs.load(); - while (r != 0) - if (refs.compare_exchange_weak(r, r + 1)) return true; - return false; -} - -// ---- Status arrays ------------------------------------------------------------------------------------------------ - -class StatusArray final : public IDStorageStatusArrayX { -public: - StatusArray(uint32_t capacity, std::unique_ptr[]> entries) - : capacity_(capacity), entries_(std::move(entries)) { - for (uint32_t i = 0; i < capacity_; ++i) entries_[i].store(S_OK, std::memory_order_relaxed); - std::lock_guard lock(live_mutex()); - live_status_arrays().insert(static_cast(this)); - } - - HRESULT STDMETHODCALLTYPE QueryInterface(REFIID riid, void** ppv) override { - if (!ppv) return E_POINTER; - *ppv = nullptr; - if (!iid_policy().accept_query(riid, Kind::StatusArray, "IDStorageStatusArrayX::QueryInterface")) - return E_NOINTERFACE; - AddRef(); - *ppv = static_cast(this); - return S_OK; - } - ULONG STDMETHODCALLTYPE AddRef() override { return ++refs_; } - ULONG STDMETHODCALLTYPE Release() override { - ULONG r; - { - std::lock_guard lock(live_mutex()); - r = --refs_; - if (r == 0) live_status_arrays().erase(static_cast(this)); - } - if (r == 0) delete this; - return r; - } - - // IsComplete is GetHResult(index) != E_PENDING (the reference says so); an index past the array is not pending. - bool STDMETHODCALLTYPE IsComplete(UINT32 index) override { return GetHResult(index) != E_PENDING; } - HRESULT STDMETHODCALLTYPE GetHResult(UINT32 index) override { - if (index >= capacity_) return E_DSTORAGE_INDEX_BOUND; - return entries_[index].load(std::memory_order_acquire); - } - - uint32_t capacity() const { return capacity_; } - void set_pending(uint32_t index) { entries_[index].store(E_PENDING, std::memory_order_release); } - void complete(uint32_t index, HRESULT hr) { entries_[index].store(hr, std::memory_order_release); } - std::atomic& refs() { return refs_; } - -private: - std::atomic refs_{1}; - const uint32_t capacity_; - std::unique_ptr[]> entries_; -}; - -// ---- Files -------------------------------------------------------------------------------------------------------- - -class File final : public IDStorageFileX { -public: - File(HANDLE handle, std::wstring path) : handle_(handle), path_(std::move(path)) { - { - std::lock_guard lock(live_mutex()); - live_files().insert(static_cast(this)); - } - std::lock_guard lock(stats().mutex); - auto& s = stats().s; - ++s.CurrentOpenFileCount; - ++s.CumulativeOpenFileCount; - s.MaxOpenFileCount = std::max(s.MaxOpenFileCount, s.CurrentOpenFileCount); - } - ~File() { - Close(); - std::lock_guard lock(stats().mutex); - --stats().s.CurrentOpenFileCount; - } - - HRESULT STDMETHODCALLTYPE QueryInterface(REFIID riid, void** ppv) override { - if (!ppv) return E_POINTER; - *ppv = nullptr; - if (!iid_policy().accept_query(riid, Kind::File, "IDStorageFileX::QueryInterface")) return E_NOINTERFACE; - AddRef(); - *ppv = static_cast(this); - return S_OK; - } - ULONG STDMETHODCALLTYPE AddRef() override { return ++refs_; } - ULONG STDMETHODCALLTYPE Release() override { - ULONG r; - { - std::lock_guard lock(live_mutex()); - r = --refs_; - if (r == 0) live_files().erase(static_cast(this)); - } - if (r == 0) delete this; - return r; - } - - // Waits for the submitted requests that read this file, then closes the handle. A request submitted later fails - // with E_DSTORAGE_FILE_NOT_OPEN. Waiting only for submitted requests keeps a Close from blocking forever on a - // request that sits unsubmitted in a queue with auto-submit disabled. - void STDMETHODCALLTYPE Close() override { - std::unique_lock lock(mutex_); - closed_ = true; - idle_.wait(lock, [&] { return pending_ == 0; }); - if (handle_ != INVALID_HANDLE_VALUE) { - CloseHandle(handle_); - handle_ = INVALID_HANDLE_VALUE; - } - } - - // A new handle the caller closes (GENERIC_READ, FILE_SHARE_READ, as the reference describes it). ReOpenFile, - // not DuplicateHandle: a duplicate shares the file position with the shim's own reads, so the title's ReadFile - // through it would start wherever the worker's last read ended. - HANDLE STDMETHODCALLTYPE GetHandle() override { - std::lock_guard lock(mutex_); - if (closed_ || handle_ == INVALID_HANDLE_VALUE) { - SetLastError(ERROR_INVALID_HANDLE); - return INVALID_HANDLE_VALUE; - } - return ReOpenFile(handle_, GENERIC_READ, FILE_SHARE_READ, 0); - } - - // Called when a request naming this file is submitted. False once the file is closed. - bool add_pending() { - std::lock_guard lock(mutex_); - if (closed_) return false; - ++pending_; - return true; - } - void finish_pending() { - std::lock_guard lock(mutex_); - if (--pending_ == 0) idle_.notify_all(); - } - // Valid while the caller holds a pending count: Close does not close the handle before it drops to zero. - HANDLE handle() const { return handle_; } - const std::wstring& path() const { return path_; } - std::atomic& refs() { return refs_; } - -private: - std::atomic refs_{1}; - std::mutex mutex_; - std::condition_variable idle_; - HANDLE handle_; - const std::wstring path_; - uint32_t pending_ = 0; - bool closed_ = false; -}; - -StatusArray* live_status_array(IDStorageStatusArrayX* p) { - std::lock_guard lock(live_mutex()); - if (!p || !live_status_arrays().count(p)) return nullptr; - auto* a = static_cast(p); - return add_ref_if_live(a->refs()) ? a : nullptr; -} - -File* live_file(IDStorageFileX* p) { - std::lock_guard lock(live_mutex()); - if (!p || !live_files().count(p)) return nullptr; - auto* f = static_cast(p); - return add_ref_if_live(f->refs()) ? f : nullptr; -} - -// ---- Reads -------------------------------------------------------------------------------------------------------- - -// memmove that turns an access violation into an error instead of ending the process. No C++ objects here: a -// function with __try cannot have any that need unwinding. -bool guarded_move(void* destination, const void* source, size_t size) { - __try { - std::memmove(destination, source, size); - return true; - } __except (GetExceptionCode() == EXCEPTION_ACCESS_VIOLATION ? EXCEPTION_EXECUTE_HANDLER - : EXCEPTION_CONTINUE_SEARCH) { - return false; - } -} - -HRESULT read_error(DWORD error) { - switch (error) { - case ERROR_NOACCESS: - case ERROR_INVALID_USER_BUFFER: return E_DSTORAGE_ACCESS_VIOLATION; - case ERROR_HANDLE_EOF: return E_DSTORAGE_END_OF_FILE; - default: return HRESULT_FROM_WIN32(error); - } -} - -// Reads exactly "size" bytes at "offset" of a synchronous handle into "destination". -HRESULT read_file_range(HANDLE handle, uint64_t offset, void* destination, uint32_t size) { - LARGE_INTEGER length{}; - if (!GetFileSizeEx(handle, &length)) return HRESULT_FROM_WIN32(GetLastError()); - const uint64_t file_size = static_cast(length.QuadPart); - if (offset > file_size || size > file_size - offset) return E_DSTORAGE_END_OF_FILE; - auto* out = static_cast(destination); - uint32_t done = 0; - while (done < size) { - OVERLAPPED at{}; - const uint64_t position = offset + done; - at.Offset = static_cast(position); - at.OffsetHigh = static_cast(position >> 32); - DWORD got = 0; - if (!ReadFile(handle, out + done, size - done, &got, &at)) return read_error(GetLastError()); - if (got == 0) return E_DSTORAGE_END_OF_FILE; // the file shrank since the size check - done += got; - } - return S_OK; -} - -// ---- Queues ------------------------------------------------------------------------------------------------------- - -struct Entry { - enum class Type { Request, Status, Signal, Event } type = Type::Request; - DSTORAGE_REQUEST request{}; - File* file = nullptr; // a reference, for a file request naming a live file - bool file_counted = false; // the file's pending count was raised at submit - bool cancelled = false; // CancelRequestsWithTag matched it before it started - bool counted = false; // a request the title passed: counted in the statistics when it is submitted - HRESULT enqueue_error = S_OK; // found at enqueue: reported when the entry is reached, in order - StatusArray* status = nullptr; // a reference - IDStorageStatusArrayX* status_as_given = nullptr; - uint32_t index = 0; - ID3D12Fence* fence = nullptr; // a reference - uint64_t value = 0; - HANDLE event = nullptr; // a duplicate the entry owns -}; - -class Queue final : public IDStorageQueueX2 { -public: - explicit Queue(const DSTORAGE_QUEUE_DESC1& desc) : desc_(desc) { - error_event_ = CreateEventW(nullptr, TRUE, FALSE, nullptr); - clear_record_locked(); - std::lock_guard lock(stats().mutex); - auto& p = priority_stats(stats().s, desc_.Priority); - ++p.CurrentQueueCount; - ++p.CumulativeQueueCount; - p.MaxQueueCount = std::max(p.MaxQueueCount, p.CurrentQueueCount); - ++stats().live_queues; - } - // Separate from the constructor so a failure to start the thread can be reported. - bool start() { - if (!error_event_) return false; - try { - worker_ = std::thread([this] { run(); }); - } catch (...) { - return false; - } - return true; - } - ~Queue() { - Close(); - if (error_event_) CloseHandle(error_event_); - std::lock_guard lock(stats().mutex); - --priority_stats(stats().s, desc_.Priority).CurrentQueueCount; - --stats().live_queues; - } - - HRESULT STDMETHODCALLTYPE QueryInterface(REFIID riid, void** ppv) override { - if (!ppv) return E_POINTER; - *ppv = nullptr; - if (!iid_policy().accept_query(riid, Kind::Queue, "IDStorageQueueX::QueryInterface")) return E_NOINTERFACE; - AddRef(); - *ppv = static_cast(this); - return S_OK; - } - ULONG STDMETHODCALLTYPE AddRef() override { return ++refs_; } - // The last Release closes the queue, which runs everything enqueued first. - ULONG STDMETHODCALLTYPE Release() override { - const ULONG r = --refs_; - if (r == 0) delete this; - return r; - } - - void STDMETHODCALLTYPE EnqueueRequest(const DSTORAGE_REQUEST* request) override { - Entry e; - e.type = Entry::Type::Request; - if (!request) { - e.enqueue_error = bad_call("IDStorageQueueX::EnqueueRequest", E_INVALIDARG, "null request"); - } else { - e.request = *request; // the title may reuse its structure as soon as this returns - const uint64_t o = e.request.Options.AsUINT64; - if (options::source_type(o) == DSTORAGE_REQUEST_SOURCE_FILE && - desc_.SourceType == DSTORAGE_REQUEST_SOURCE_FILE && e.request.File) { - e.file = live_file(e.request.File); - if (!e.file) e.enqueue_error = E_DSTORAGE_INVALID_FILE_HANDLE; - } - e.counted = true; // TotalRequestCount is "submitted requests" (DSTORAGE_PRIORITY_STATS): see submit_locked - } - enqueue(std::move(e)); - } - - void STDMETHODCALLTYPE EnqueueStatus(IDStorageStatusArrayX* status_array, UINT32 index) override { - Entry e; - e.type = Entry::Type::Status; - e.status_as_given = status_array; - e.index = index; - e.status = live_status_array(status_array); - if (!e.status) { - e.enqueue_error = E_DSTORAGE_INVALID_STATUS_ARRAY; - } else if (index >= e.status->capacity()) { - e.enqueue_error = E_DSTORAGE_INDEX_BOUND; - } else { - e.status->set_pending(index); // polling after this call sees E_PENDING until the entry is reached - } - { - std::lock_guard lock(stats().mutex); - ++priority_stats(stats().s, desc_.Priority).TotalStatusCount; - } - enqueue(std::move(e)); - } - - void STDMETHODCALLTYPE EnqueueSignal(ID3D12Fence* fence, UINT64 value) override { - Entry e; - e.type = Entry::Type::Signal; - e.fence = fence; - e.value = value; - if (fence) { - fence->AddRef(); - } else { - e.enqueue_error = E_DSTORAGE_INVALID_FENCE; - } - { - std::lock_guard lock(stats().mutex); - ++priority_stats(stats().s, desc_.Priority).TotalFenceCount; - } - enqueue(std::move(e)); - } - - // The handle is duplicated here and the duplicate closed once it has been set (or dropped), so an event the - // title closes, and whose handle value is then reused for another object, is never the one set. - void STDMETHODCALLTYPE EnqueueSetEvent(HANDLE handle) override { - Entry e; - e.type = Entry::Type::Event; - if (!handle) { - e.enqueue_error = bad_call("IDStorageQueueX1::EnqueueSetEvent", HRESULT_FROM_WIN32(ERROR_INVALID_HANDLE), - "null event handle"); - } else if (!DuplicateHandle(GetCurrentProcess(), handle, GetCurrentProcess(), &e.event, 0, FALSE, - DUPLICATE_SAME_ACCESS)) { - e.event = nullptr; - e.enqueue_error = HRESULT_FROM_WIN32(GetLastError()); - } - enqueue(std::move(e)); - } - - void STDMETHODCALLTYPE Submit() override { - std::lock_guard lock(mutex_); - submit_locked(); - } - - // Marks the requests enqueued before this call that have not started. A cancelled request completes as a success - // without being read (the overview: the title may no longer use its result). - void STDMETHODCALLTYPE CancelRequestsWithTag(UINT64 mask, UINT64 value) override { - std::lock_guard lock(mutex_); - for (Entry& e : entries_) - if (e.type == Entry::Type::Request && (e.request.CancellationTag & mask) == value) e.cancelled = true; - } - - // Submits what is enqueued, waits until the worker has run all of it and stops the worker. Later enqueues are - // dropped and recorded as E_DSTORAGE_QUEUE_CLOSED. - void STDMETHODCALLTYPE Close() override { - std::lock_guard close_lock(close_mutex_); - { - std::unique_lock lock(mutex_); - if (closed_) return; - closing_ = true; - submit_locked(); - space_.notify_all(); // an enqueue waiting for space gives up (the queue is closing) - idle_.wait(lock, [&] { return entries_.empty() && !in_flight_; }); - closed_ = true; - work_.notify_all(); - } - if (worker_.joinable()) worker_.join(); - } - - HANDLE STDMETHODCALLTYPE GetErrorEvent() override { - HANDLE dup = nullptr; - if (!error_event_ || !DuplicateHandle(GetCurrentProcess(), error_event_, GetCurrentProcess(), &dup, 0, FALSE, - DUPLICATE_SAME_ACCESS)) - return nullptr; - return dup; // the reference says the title closes it - } - - void STDMETHODCALLTYPE RetrieveErrorRecord(DSTORAGE_ERROR_RECORD* record) override { - if (!record) { - bad_call("IDStorageQueueX::RetrieveErrorRecord", E_POINTER, "null record"); - return; - } - std::lock_guard lock(error_mutex_); - *record = record_; - clear_record_locked(); - if (error_event_) ResetEvent(error_event_); - } - - void STDMETHODCALLTYPE Query(DSTORAGE_QUEUE_INFO* info) override { - if (!info) { - bad_call("IDStorageQueueX::Query", E_POINTER, "null info"); - return; - } - DSTORAGE_QUEUE_INFO1 full{}; - Query1(&full); - info->Desc.SourceType = full.Desc.SourceType; - info->Desc.Capacity = full.Desc.Capacity; - info->Desc.Priority = full.Desc.Priority; - info->Desc.Name = full.Desc.Name; - info->EmptySlotCount = full.EmptySlotCount; - info->RequestCountUntilAutoSubmit = full.RequestCountUntilAutoSubmit; - } - - // An empty queue has capacity - 1 empty slots (one slot tells empty from full). The automatic submit happens when - // the entries enqueued since the last submit reach half the capacity; with it disabled the count is 0. - void STDMETHODCALLTYPE Query1(DSTORAGE_QUEUE_INFO1* info) override { - if (!info) { - bad_call("IDStorageQueueX2::Query1", E_POINTER, "null info"); - return; - } - std::lock_guard lock(mutex_); - info->Desc = desc_; - info->EmptySlotCount = static_cast(usable() - used_locked()); - const size_t unsubmitted = entries_.size() - submitted_; - info->RequestCountUntilAutoSubmit = - auto_submit() ? static_cast(half() > unsubmitted ? half() - unsubmitted : 0) : 0; - } - -private: - size_t usable() const { return desc_.Capacity - 1u; } - size_t half() const { return desc_.Capacity / 2u; } - bool auto_submit() const { return !desc_.Options.AutoSubmitDisabled; } - size_t used_locked() const { return entries_.size() + (in_flight_ ? 1 : 0); } - - void enqueue(Entry&& e) { - { - std::unique_lock lock(mutex_); - // A full queue waits for the worker to free a slot. With auto-submit on, half the queue is always - // submitted by then; with it off, only a Submit from another thread frees one (as the reference warns). - space_.wait(lock, [&] { return closing_ || used_locked() < usable(); }); - if (!closing_) { - entries_.push_back(std::move(e)); - if (auto_submit() && entries_.size() - submitted_ >= half()) submit_locked(); - return; - } - } - DSTORAGE_ERROR_FIRST_FAILURE f{}; - f.HResult = E_DSTORAGE_QUEUE_CLOSED; - describe(e, f); - record_failure(f); - log_once("closed", "an entry was enqueued on a closed queue (E_DSTORAGE_QUEUE_CLOSED); it never completes"); - release_references(e); - } - - void submit_locked() { - uint32_t requests = 0; - uint64_t source_bytes = 0, destination_bytes = 0; - for (size_t i = submitted_; i < entries_.size(); ++i) { - Entry& e = entries_[i]; - if (e.file) e.file_counted = e.file->add_pending(); - if (e.counted) { - ++requests; - source_bytes += e.request.SourceSize; - destination_bytes += e.request.DestinationSize; - } - } - if (requests) { - std::lock_guard stats_lock(stats().mutex); - auto& p = priority_stats(stats().s, desc_.Priority); - p.TotalRequestCount += requests; - p.TotalRequestSourceByteCount += source_bytes; - p.TotalRequestDestinationByteCount += destination_bytes; - } - if (entries_.size() > submitted_) { - submitted_ = entries_.size(); - work_.notify_one(); - } - } - - void run() { - for (;;) { - Entry e; - { - std::unique_lock lock(mutex_); - work_.wait(lock, [&] { return submitted_ > 0 || closed_; }); - if (submitted_ == 0) return; // closed and drained - e = std::move(entries_.front()); - entries_.pop_front(); - --submitted_; - in_flight_ = true; - } - process(e); - release_references(e); - { - std::lock_guard lock(mutex_); - in_flight_ = false; - space_.notify_all(); - if (entries_.empty()) idle_.notify_all(); - } - } - } - - // Runs on the worker. since_notify_ is the first failure since the last status entry or fence signal: the - // HRESULT a status entry reports. - void process(Entry& e) { - HRESULT hr = e.enqueue_error; - switch (e.type) { - case Entry::Type::Request: - // A cancelled request is a success whatever else is wrong with it (the GDK: not counted as a failure). - if (e.cancelled) { - hr = S_OK; - } else if (SUCCEEDED(hr)) { - // Pending: processing has started and not completed (DSTORAGE_PRIORITY_STATS). - set_pending(+1); - hr = execute_request(e); - set_pending(-1); - } - if (e.file && e.file_counted) e.file->finish_pending(); - if (FAILED(hr) && SUCCEEDED(since_notify_)) since_notify_ = hr; - break; - case Entry::Type::Status: - if (SUCCEEDED(hr)) { - e.status->complete(e.index, since_notify_); - since_notify_ = S_OK; - } - break; - case Entry::Type::Signal: - if (SUCCEEDED(hr)) hr = e.fence->Signal(e.value); - since_notify_ = S_OK; - break; - case Entry::Type::Event: - if (SUCCEEDED(hr) && !SetEvent(e.event)) hr = HRESULT_FROM_WIN32(GetLastError()); - break; - } - if (FAILED(hr)) { - DSTORAGE_ERROR_FIRST_FAILURE f{}; - f.HResult = hr; - describe(e, f); - record_failure(f); - } - } - - HRESULT execute_request(const Entry& e) { - const DSTORAGE_REQUEST& r = e.request; - const uint64_t o = r.Options.AsUINT64; - if (o & options::kReservedMask) return E_DSTORAGE_RESERVED_FIELDS; - if (options::source_type(o) != desc_.SourceType) return E_DSTORAGE_INVALID_SOURCE_TYPE; - if (options::bcpack(o) > DSTORAGE_BCPACK_MODE_BC7) return E_DSTORAGE_INVALID_BCPACK_MODE; - if (options::swizzle(o) > DSTORAGE_SWIZZLE_MODE_4K_12K_4K_12K) return E_DSTORAGE_INVALID_SWIZZLE_MODE; - if (options::bcpack(o) != 0 || options::swizzle(o) != 0) { - log_once("decompress", "BCPack and swizzle requests are not implemented yet (E_NOTIMPL)"); - return E_NOTIMPL; - } - if (o & (options::kDestinationPages | options::kSourcePages)) { - log_once("pages", "physical-page requests are not implemented yet (E_NOTIMPL)"); - return E_NOTIMPL; - } - const bool zlib = options::zlib(o); - // IntermediateSize is the BCPack data's size between the inflate and the BCPack decode (DSTORAGE_REQUEST), so - // it is 0 for every request that gets here (BCPack is refused above). - if (r.IntermediateSize != 0) return E_DSTORAGE_INVALID_INTERMEDIATE_SIZE; - // E_DSTORAGE_INVALID_DESTINATION_SIZE: without decompression DestinationSize must equal the source's length, - // with it it must be larger (dstorageerr.h's description; DSTORAGE_REQUEST says the same of DestinationSize). - if (zlib ? r.DestinationSize <= r.SourceSize : r.DestinationSize != r.SourceSize) - return E_DSTORAGE_INVALID_DESTINATION_SIZE; - const bool memory = desc_.SourceType == DSTORAGE_REQUEST_SOURCE_MEMORY; - const uint64_t total = static_cast(r.DestinationSize) + (memory ? r.SourceSize : 0u); - if (total > kMaxRequestBytes) return E_DSTORAGE_REQUEST_TOO_LARGE; - // DSTORAGE_REQUEST: a buffer over 32 MiB is allowed only with 64 KiB or 2 MiB pages, which are not implemented - // yet (refused above). The source is never larger than the destination here (the same size without zlib, - // smaller with it), so this covers both buffers, and bounds the staging buffers of a zlib request too. - if (r.DestinationSize > kMax4kPageDestinationSize) return E_DSTORAGE_REQUEST_TOO_LARGE; - // DSTORAGE_REQUEST: with ZlibDecompress the file offset must be 16-byte aligned. - if (zlib && !memory && r.FileOffset % 16 != 0) return E_DSTORAGE_INVALID_FILE_OFFSET; - if (!r.Destination) return E_INVALIDARG; - if (memory) { - if (!r.Source) return E_INVALIDARG; - } else { - if (!r.File) return E_INVALIDARG; - if (!e.file_counted) return E_DSTORAGE_FILE_NOT_OPEN; - } - if (zlib) return inflate_request(e, memory); - if (r.SourceSize == 0) return S_OK; // nothing to move; the reference does not say this fails - if (memory) return guarded_move(r.Destination, r.Source, r.SourceSize) ? S_OK : E_DSTORAGE_ACCESS_VIOLATION; - return read_file_range(e.file->handle(), r.FileOffset, r.Destination, r.SourceSize); - } - - // A zlib request whose checks have passed: the source (SourceSize bytes of the file or of memory) goes into a - // staging buffer, inflates there, and only a result of exactly DestinationSize bytes is copied to the destination. - // So a failed stream leaves the destination as it was, and a memory source that overlaps its destination is safe. - // Both buffers are at most 32 MiB (execute_request). The stream is RFC 1950: the two header bytes, the deflate - // data, the Adler-32 of the result; bytes after the Adler-32 are not read. A failure is the matching - // dstorageerr.h code: a bad header (not deflate, a window over 32 KiB, a bad check value or a preset dictionary) - // E_DSTORAGE_ZLIB_BAD_HEADER, bad or truncated deflate data E_DSTORAGE_ZLIB_BAD_DATA, an Adler-32 mismatch - // E_DSTORAGE_ZLIB_PARITY_FAIL, and a stream that inflates to more or fewer bytes than DestinationSize - // E_DSTORAGE_DECOMPRESSION_ERROR (no code names a size mismatch; this is the header's generic one). - HRESULT inflate_request(const Entry& e, bool memory) { - const DSTORAGE_REQUEST& r = e.request; - std::vector source, result; - try { - source.resize(r.SourceSize); - result.reserve(r.DestinationSize); - } catch (const std::bad_alloc&) { - return E_OUTOFMEMORY; - } - if (r.SourceSize != 0) { - if (memory) { - if (!guarded_move(source.data(), r.Source, r.SourceSize)) return E_DSTORAGE_ACCESS_VIOLATION; - } else if (const HRESULT hr = read_file_range(e.file->handle(), r.FileOffset, source.data(), r.SourceSize); - FAILED(hr)) { - return hr; - } - } - log_once("zlib", "zlib requests are inflated on the CPU (RFC 1950, leonida::zlib_inflate)"); - set_decompression_pending(+1); - leonida::ZlibError why = leonida::ZlibError::none; - const bool inflated = leonida::zlib_inflate(source, result, r.DestinationSize, &why); - set_decompression_pending(-1); - HRESULT hr = S_OK; - if (!inflated) { - switch (why) { - case leonida::ZlibError::header: hr = E_DSTORAGE_ZLIB_BAD_HEADER; break; - case leonida::ZlibError::checksum: hr = E_DSTORAGE_ZLIB_PARITY_FAIL; break; - case leonida::ZlibError::limit: hr = E_DSTORAGE_DECOMPRESSION_ERROR; break; // longer than the destination - default: hr = E_DSTORAGE_ZLIB_BAD_DATA; break; - } - } else if (result.size() != r.DestinationSize) { - hr = E_DSTORAGE_DECOMPRESSION_ERROR; // shorter than the destination - } - if (FAILED(hr)) { - std::lock_guard lock(stats().mutex); - ++stats().s.DecompressionErrors; - return hr; - } - return guarded_move(r.Destination, result.data(), result.size()) ? S_OK : E_DSTORAGE_ACCESS_VIOLATION; - } - - void set_pending(int delta) { - std::lock_guard lock(stats().mutex); - priority_stats(stats().s, desc_.Priority).PendingRequestCount += static_cast(delta); - } - - // PendingDecompressionRequestCount is the zlib requests being inflated; TotalDecompressionRequestCount counts each - // one that reached its inflate (its source was read), DecompressionErrors those whose stream then failed. - static void set_decompression_pending(int delta) { - std::lock_guard lock(stats().mutex); - auto& s = stats().s; - s.PendingDecompressionRequestCount += static_cast(delta); - if (delta > 0) ++s.TotalDecompressionRequestCount; - } - - void describe(const Entry& e, DSTORAGE_ERROR_FIRST_FAILURE& f) const { - switch (e.type) { - case Entry::Type::Request: { - f.CommandType = DSTORAGE_COMMAND_TYPE_REQUEST; - auto& q = f.Request; - const DSTORAGE_REQUEST& r = e.request; - q.Options = r.Options; - q.Destination = r.Destination; - q.DestinationSize = r.DestinationSize; - q.SourceSize = r.SourceSize; - q.CancellationTag = r.CancellationTag; - if (options::source_type(r.Options.AsUINT64) == DSTORAGE_REQUEST_SOURCE_MEMORY) { - q.Source = r.Source; - } else { - q.FileOffset = r.FileOffset; - if (e.file) wcsncpy_s(q.Filename, e.file->path().c_str(), _TRUNCATE); - } - // The reference says the name stays readable until the request completes. - if (r.Name) - for (size_t i = 0; i + 1 < kRequestMaxName && r.Name[i]; ++i) q.Name[i] = r.Name[i]; - break; - } - case Entry::Type::Status: - f.CommandType = DSTORAGE_COMMAND_TYPE_STATUS; - f.Status.StatusArray = e.status_as_given; - f.Status.Index = e.index; - break; - case Entry::Type::Signal: - f.CommandType = DSTORAGE_COMMAND_TYPE_SIGNAL; - f.Signal.Fence = e.fence; - f.Signal.Value = e.value; - break; - case Entry::Type::Event: - f.CommandType = kCommandTypeEvent; - break; - } - } - - void record_failure(const DSTORAGE_ERROR_FIRST_FAILURE& f) { - count_error(); - { - std::lock_guard lock(error_mutex_); - if (record_.FailureCount++ == 0) record_.FirstFailure = f; - if (error_event_) SetEvent(error_event_); - } - log_once("fail" + hr_text(f.HResult) + std::to_string(f.CommandType), - "an entry failed with " + hr_text(f.HResult) + " (command type " + std::to_string(f.CommandType) + - "; logged once per code)"); - } - - void clear_record_locked() { - record_ = DSTORAGE_ERROR_RECORD{}; - record_.FirstFailure.CommandType = DSTORAGE_COMMAND_TYPE_NONE; - } - - static void release_references(Entry& e) { - if (e.file) e.file->Release(); - if (e.status) e.status->Release(); - if (e.fence) e.fence->Release(); - if (e.event) CloseHandle(e.event); - e.event = nullptr; - e.file = nullptr; - e.status = nullptr; - e.fence = nullptr; - } - - std::atomic refs_{1}; - const DSTORAGE_QUEUE_DESC1 desc_; - std::mutex close_mutex_; // one Close at a time - std::mutex mutex_; // entries_, submitted_, in_flight_, closing_, closed_ - std::condition_variable work_, space_, idle_; - std::deque entries_; - size_t submitted_ = 0; // the first submitted_ entries are submitted - bool in_flight_ = false; - bool closing_ = false; - bool closed_ = false; - std::thread worker_; - HRESULT since_notify_ = S_OK; // worker only - std::mutex error_mutex_; - DSTORAGE_ERROR_RECORD record_{}; - HANDLE error_event_ = nullptr; -}; - -// ---- The factory ---------------------------------------------------------------------------------------------------- - -HRESULT validate_queue_desc(const DSTORAGE_QUEUE_DESC1& d) { - if (d.SourceType != DSTORAGE_REQUEST_SOURCE_FILE && d.SourceType != DSTORAGE_REQUEST_SOURCE_MEMORY) - return E_DSTORAGE_INVALID_SOURCE_TYPE; - if (d.Capacity < kMinQueueCapacity || d.Capacity > kMaxQueueCapacity) return E_DSTORAGE_INVALID_QUEUE_CAPACITY; - if (d.Priority < DSTORAGE_PRIORITY_FIRST || d.Priority > DSTORAGE_PRIORITY_LAST) - return E_DSTORAGE_INVALID_QUEUE_PRIORITY; - if (d.SourceType == DSTORAGE_REQUEST_SOURCE_MEMORY && d.Priority != DSTORAGE_PRIORITY_REALTIME) - return E_DSTORAGE_INVALID_MEMORY_QUEUE_PRIORITY; - if (d.Options.Reserved) return E_DSTORAGE_RESERVED_FIELDS; - return S_OK; -} - -using CreateFileWFn = HANDLE(WINAPI*)(LPCWSTR, DWORD, DWORD, LPSECURITY_ATTRIBUTES, DWORD, DWORD, HANDLE); - -// The title's own CreateFileW: the GAME: mapping and overlay when file_system.cpp is linked, else the host's. -CreateFileWFn create_file_w() { - if (void* fn = rt::shims::find("kernel32.dll", "CreateFileW")) return reinterpret_cast(fn); - return &::CreateFileW; -} - -class Factory final : public IDStorageFactoryX2 { -public: - HRESULT STDMETHODCALLTYPE QueryInterface(REFIID riid, void** ppv) override { - if (!ppv) return E_POINTER; - *ppv = nullptr; - if (!iid_policy().accept_query(riid, Kind::Factory, "IDStorageFactoryX::QueryInterface")) return E_NOINTERFACE; - AddRef(); - *ppv = static_cast(this); - return S_OK; - } - ULONG STDMETHODCALLTYPE AddRef() override { return ++refs_; } - // One factory for the process; its count never drops below one, so it is never freed. - ULONG STDMETHODCALLTYPE Release() override { - ULONG r = refs_.load(); - while (r > 1 && !refs_.compare_exchange_weak(r, r - 1)) {} - return r > 1 ? r - 1 : 1; - } - - HRESULT STDMETHODCALLTYPE CreateQueue(const DSTORAGE_QUEUE_DESC* desc, REFIID riid, void** ppv) override { - if (!ppv) return bad_call("IDStorageFactoryX::CreateQueue", E_POINTER, "null ppv"); - *ppv = nullptr; - if (!desc) return bad_call("IDStorageFactoryX::CreateQueue", E_INVALIDARG, "null desc"); - DSTORAGE_QUEUE_DESC1 d{}; - d.SourceType = desc->SourceType; - d.Capacity = desc->Capacity; - d.Priority = desc->Priority; - d.Name = desc->Name; - return create_queue(d, riid, ppv, "IDStorageFactoryX::CreateQueue"); - } - - HRESULT STDMETHODCALLTYPE CreateQueue1(const DSTORAGE_QUEUE_DESC1* desc, REFIID riid, void** ppv) override { - if (!ppv) return bad_call("IDStorageFactoryX2::CreateQueue1", E_POINTER, "null ppv"); - *ppv = nullptr; - if (!desc) return bad_call("IDStorageFactoryX2::CreateQueue1", E_INVALIDARG, "null desc"); - return create_queue(*desc, riid, ppv, "IDStorageFactoryX2::CreateQueue1"); - } - - HRESULT STDMETHODCALLTYPE OpenFile(const WCHAR* path, REFIID riid, void** ppv) override { - if (!ppv) return bad_call("IDStorageFactoryX::OpenFile", E_POINTER, "null ppv"); - *ppv = nullptr; - if (!path || !*path) return bad_call("IDStorageFactoryX::OpenFile", E_INVALIDARG, "null or empty path"); - if (!iid_policy().accept_creating(riid, Kind::File, "IDStorageFactoryX::OpenFile")) return E_NOINTERFACE; - const HANDLE h = create_file_w()(path, GENERIC_READ, FILE_SHARE_READ, nullptr, OPEN_EXISTING, - FILE_ATTRIBUTE_NORMAL, nullptr); - if (h == INVALID_HANDLE_VALUE) { - const DWORD error = GetLastError(); - return HRESULT_FROM_WIN32(error ? error : ERROR_FILE_NOT_FOUND); - } - File* f = new (std::nothrow) File(h, path); - if (!f) { - CloseHandle(h); - return E_OUTOFMEMORY; - } - *ppv = static_cast(f); - return S_OK; - } - - HRESULT STDMETHODCALLTYPE CreateStatusArray(UINT32 capacity, PCSTR, REFIID riid, void** ppv) override { - if (!ppv) return bad_call("IDStorageFactoryX::CreateStatusArray", E_POINTER, "null ppv"); - *ppv = nullptr; - if (capacity == 0) return bad_call("IDStorageFactoryX::CreateStatusArray", E_INVALIDARG, "capacity 0"); - if (!iid_policy().accept_creating(riid, Kind::StatusArray, "IDStorageFactoryX::CreateStatusArray")) - return E_NOINTERFACE; - std::unique_ptr[]> entries(new (std::nothrow) std::atomic[capacity]); - if (!entries) return E_OUTOFMEMORY; - auto* a = new (std::nothrow) StatusArray(capacity, std::move(entries)); - if (!a) return E_OUTOFMEMORY; - *ppv = static_cast(a); - return S_OK; - } - - // DirectStorage's own worker work would be pinned to these cores on the console. The mask names console cores, - // so it is stored and not applied to the host's. - HRESULT STDMETHODCALLTYPE SetCpuAffinity(UINT64 affinity) override { - cpu_affinity_.store(affinity); - return S_OK; - } - void STDMETHODCALLTYPE SetDebugFlags(UINT32 flags) override { debug_flags_.store(flags); } - - HRESULT STDMETHODCALLTYPE SetStagingBufferSize(UINT32 size) override { - if (std::find(std::begin(kStagingBufferSizes), std::end(kStagingBufferSizes), size) == - std::end(kStagingBufferSizes)) - return bad_call("IDStorageFactoryX::SetStagingBufferSize", E_DSTORAGE_INVALID_STAGING_BUFFER_SIZE, - "not one of 0, 16, 20, 24, 28 or 32 MiB"); - std::lock_guard lock(stats().mutex); - if (stats().live_queues || stats().s.CurrentOpenFileCount) return E_DSTORAGE_STAGING_BUFFER_LOCKED; - staging_size_ = size; // there is no staging buffer here; the size is only kept - return S_OK; - } - - void STDMETHODCALLTYPE GetStats(DSTORAGE_STATS* out) override { - if (!out) { - bad_call("IDStorageFactoryX1::GetStats", E_POINTER, "null stats"); - return; - } - std::lock_guard lock(stats().mutex); - *out = stats().s; - } - -private: - HRESULT create_queue(const DSTORAGE_QUEUE_DESC1& desc, REFIID riid, void** ppv, const char* caller) { - if (const HRESULT hr = validate_queue_desc(desc); FAILED(hr)) return bad_call(caller, hr, "invalid queue desc"); - if (!iid_policy().accept_creating(riid, Kind::Queue, caller)) return E_NOINTERFACE; - auto* q = new (std::nothrow) Queue(desc); - if (!q) return E_OUTOFMEMORY; - if (!q->start()) { - q->Release(); - return E_OUTOFMEMORY; - } - *ppv = static_cast(q); - return S_OK; - } - - std::atomic refs_{1}; - std::atomic cpu_affinity_{~0ull}; - std::atomic debug_flags_{0}; - uint32_t staging_size_ = 32u << 20; // under stats().mutex -}; - -Factory& factory() { - static auto* f = new Factory; - return *f; -} - -HRESULT WINAPI dstorage_get_factory(REFIID riid, void** ppv) { - if (!ppv) return bad_call("DStorageGetFactory", E_POINTER, "null ppv"); - *ppv = nullptr; - if (!iid_policy().accept_creating(riid, Kind::Factory, "DStorageGetFactory")) return E_NOINTERFACE; - Factory& f = factory(); - f.AddRef(); - *ppv = static_cast(&f); - return S_OK; -} - -} // namespace - -// The console module names; docs/directstorage.md has the evidence and the confidence for each. -SHIM_TABLE(dstorage, - {"dstorage_xs.dll", "DStorageGetFactory", reinterpret_cast(&dstorage_get_factory)}, - {"xcrdapi.dll", "DStorageGetFactory", reinterpret_cast(&dstorage_get_factory)}, - {"dstorage.dll", "DStorageGetFactory", reinterpret_cast(&dstorage_get_factory)}, -); diff --git a/runtime/shims/dstorage_xs_abi.h b/runtime/shims/dstorage_xs_abi.h deleted file mode 100644 index aec6ac59d..000000000 --- a/runtime/shims/dstorage_xs_abi.h +++ /dev/null @@ -1,387 +0,0 @@ -// Xbox DirectStorage ABI: the console API (dstorage_xs.h on the console) a title calls through DStorageGetFactory. -// -// These are Leonida's own declarations. Names, member order and types follow the public GDK reference -// (learn.microsoft.com/gaming/gdk/docs/reference/system/dstorage); docs/directstorage.md has the evidence for which -// DLL serves it and how sure each part is. No Microsoft header is copied. -// -// VERIFY (docs/directstorage.md "What is not public"): -// - Vtable order. The reference lists methods alphabetically; the order below is the PC dstorage.h order for the -// methods both APIs share, with the console-only ones (SetCpuAffinity, GetStats, CreateQueue1, GetHandle, -// Query1) where the GDK overview lists them. Reorder a declaration here and every object follows. -// - Interface ids. The X interfaces' ids are not public. The one declared id is the PC IDStorageStatusArray's, whose -// interface has the same shape (console D3D12 binaries reuse PC SDK ids); dstorage.cpp's creating calls learn and -// log the others. The other PC ids are declared only so they can be refused. -// - The capacity bounds, DSTORAGE_REQUEST_MAX_NAME and the E_DSTORAGE_* values are the PC header's. -#pragma once -#include -#include - -#include -#include - -struct ID3D12Fence; // d3d12.h; the shim calls Signal through it - -namespace dsx { - -#pragma warning(push) -#pragma warning(disable : 4201) // nameless struct/union: the reference declares the members that way - -// ---- Constants and enumerations ----------------------------------------------------------------------------------- - -constexpr uint16_t kMinQueueCapacity = 0x80; // DSTORAGE_MIN_QUEUE_CAPACITY (PC value) -constexpr uint16_t kMaxQueueCapacity = 0x2000; // DSTORAGE_MAX_QUEUE_CAPACITY (PC value) -constexpr size_t kRequestMaxName = 64; // DSTORAGE_REQUEST_MAX_NAME (PC value) -constexpr uint64_t kMaxRequestBytes = 1ull << 30; // DSTORAGE_MAX_REQUEST_SIZE: source + destination -constexpr uint32_t kMax4kPageDestinationSize = 32u << 20; // DSTORAGE_MAX_4K_PAGE_DESTINATION_SIZE - -enum DSTORAGE_PRIORITY : int8_t { - DSTORAGE_PRIORITY_LOW = -1, - DSTORAGE_PRIORITY_NORMAL = 0, - DSTORAGE_PRIORITY_HIGH = 1, - DSTORAGE_PRIORITY_REALTIME = 2, - DSTORAGE_PRIORITY_FIRST = DSTORAGE_PRIORITY_LOW, - DSTORAGE_PRIORITY_LAST = DSTORAGE_PRIORITY_REALTIME, - DSTORAGE_PRIORITY_COUNT = 4, -}; - -enum DSTORAGE_REQUEST_SOURCE_TYPE : uint64_t { - DSTORAGE_REQUEST_SOURCE_FILE = 0, - DSTORAGE_REQUEST_SOURCE_MEMORY = 1, -}; - -enum DSTORAGE_BCPACK_MODE : uint64_t { - DSTORAGE_BCPACK_MODE_NONE = 0, - DSTORAGE_BCPACK_MODE_BC1 = 1, - DSTORAGE_BCPACK_MODE_BC2 = 2, - DSTORAGE_BCPACK_MODE_BC3 = 3, - DSTORAGE_BCPACK_MODE_BC4 = 4, - DSTORAGE_BCPACK_MODE_BC5 = 5, - DSTORAGE_BCPACK_MODE_BC6H = 6, - DSTORAGE_BCPACK_MODE_BC7 = 7, -}; - -enum DSTORAGE_SWIZZLE_MODE : uint64_t { - DSTORAGE_SWIZZLE_MODE_NONE = 0, - DSTORAGE_SWIZZLE_MODE_4K_4K_8K = 1, - DSTORAGE_SWIZZLE_MODE_4K_4K_24K = 2, - DSTORAGE_SWIZZLE_MODE_4K_12K_4K_4K_8K = 3, - DSTORAGE_SWIZZLE_MODE_4K_12K_4K_12K = 4, -}; - -enum DSTORAGE_COMMAND_TYPE : int32_t { - DSTORAGE_COMMAND_TYPE_NONE = -1, - DSTORAGE_COMMAND_TYPE_REQUEST = 0, - DSTORAGE_COMMAND_TYPE_STATUS = 1, - DSTORAGE_COMMAND_TYPE_SIGNAL = 2, -}; -// Not in the console enum: the PC API's DSTORAGE_COMMAND_TYPE_EVENT, used here for a failed EnqueueSetEvent. -constexpr DSTORAGE_COMMAND_TYPE kCommandTypeEvent = static_cast(3); - -enum DSTORAGE_DEBUG : uint32_t { - DSTORAGE_DEBUG_NONE = 0x00, - DSTORAGE_DEBUG_SHOW_ERRORS = 0x01, - DSTORAGE_DEBUG_BREAK_ON_ERROR = 0x02, - DSTORAGE_DEBUG_RECORD_OBJECT_NAMES = 0x04, -}; - -// The staging-buffer sizes the GDK overview lists as valid (its enumeration page is not public). -constexpr uint32_t kStagingBufferSizes[] = {0, 16u << 20, 20u << 20, 24u << 20, 28u << 20, 32u << 20}; - -// ---- Errors (FACILITY_GAME, the PC dstorageerr.h values) ---------------------------------------------------------- - -constexpr HRESULT E_DSTORAGE_INVALID_QUEUE_CAPACITY = static_cast(0x89240003L); -constexpr HRESULT E_DSTORAGE_END_OF_FILE = static_cast(0x89240007L); -constexpr HRESULT E_DSTORAGE_REQUEST_TOO_LARGE = static_cast(0x89240008L); -constexpr HRESULT E_DSTORAGE_ACCESS_VIOLATION = static_cast(0x89240009L); -constexpr HRESULT E_DSTORAGE_FILE_NOT_OPEN = static_cast(0x8924000BL); -constexpr HRESULT E_DSTORAGE_RESERVED_FIELDS = static_cast(0x8924000CL); -constexpr HRESULT E_DSTORAGE_INVALID_BCPACK_MODE = static_cast(0x8924000DL); -constexpr HRESULT E_DSTORAGE_INVALID_SWIZZLE_MODE = static_cast(0x8924000EL); -constexpr HRESULT E_DSTORAGE_INVALID_DESTINATION_SIZE = static_cast(0x8924000FL); -constexpr HRESULT E_DSTORAGE_QUEUE_CLOSED = static_cast(0x89240010L); -constexpr HRESULT E_DSTORAGE_INVALID_QUEUE_PRIORITY = static_cast(0x89240013L); -constexpr HRESULT E_DSTORAGE_INDEX_BOUND = static_cast(0x89240015L); -constexpr HRESULT E_DSTORAGE_INVALID_FILE_HANDLE = static_cast(0x89240017L); -constexpr HRESULT E_DSTORAGE_INVALID_FILE_OFFSET = static_cast(0x8924001AL); -constexpr HRESULT E_DSTORAGE_INVALID_SOURCE_TYPE = static_cast(0x8924001BL); -constexpr HRESULT E_DSTORAGE_INVALID_INTERMEDIATE_SIZE = static_cast(0x8924001CL); -constexpr HRESULT E_DSTORAGE_STAGING_BUFFER_LOCKED = static_cast(0x8924001FL); -constexpr HRESULT E_DSTORAGE_INVALID_STAGING_BUFFER_SIZE = static_cast(0x89240020L); -constexpr HRESULT E_DSTORAGE_INVALID_FENCE = static_cast(0x89240022L); -constexpr HRESULT E_DSTORAGE_INVALID_STATUS_ARRAY = static_cast(0x89240023L); -constexpr HRESULT E_DSTORAGE_INVALID_MEMORY_QUEUE_PRIORITY = static_cast(0x89240024L); -// The decompression failures. E_DSTORAGE_DECOMPRESSION_ERROR ("a generic error has happened during decompression") -// is on the public DirectStorage constants page; the three zlib codes are in the same header (dstorageerr.h) with no -// public description: the names and values here are those of the header-generated bindings of the `direct-storage` -// crate (docs/directstorage.md "Sources"). PARITY_FAIL is read as the Adler-32 check, the only check value a zlib -// stream has. -constexpr HRESULT E_DSTORAGE_DECOMPRESSION_ERROR = static_cast(0x89240030L); -constexpr HRESULT E_DSTORAGE_ZLIB_BAD_HEADER = static_cast(0x89240031L); -constexpr HRESULT E_DSTORAGE_ZLIB_BAD_DATA = static_cast(0x89240032L); -constexpr HRESULT E_DSTORAGE_ZLIB_PARITY_FAIL = static_cast(0x89240033L); - -// ---- Structures --------------------------------------------------------------------------------------------------- - -// DSTORAGE_REQUEST_OPTIONS as the reference declares it. The shim reads AsUINT64 through the bit positions below -// (MSVC allocates bit-fields from bit 0 up); dstorage_test checks that the two agree. -union DSTORAGE_REQUEST_OPTIONS { - struct { - uint64_t ZlibDecompress : 1; - DSTORAGE_BCPACK_MODE BcpackMode : 4; - DSTORAGE_SWIZZLE_MODE SwizzleMode : 16; - uint64_t DestinationIsPhysicalPages : 1; - DSTORAGE_REQUEST_SOURCE_TYPE SourceType : 1; - uint64_t SourceIsPhysicalPages : 1; - uint64_t Reserved : 40; - }; - uint64_t AsUINT64; -}; -static_assert(sizeof(DSTORAGE_REQUEST_OPTIONS) == 8); - -namespace options { -constexpr uint64_t kZlib = 1ull << 0; -constexpr unsigned kBcpackShift = 1; -constexpr uint64_t kBcpackMask = 0xFull << kBcpackShift; -constexpr unsigned kSwizzleShift = 5; -constexpr uint64_t kSwizzleMask = 0xFFFFull << kSwizzleShift; -constexpr uint64_t kDestinationPages = 1ull << 21; -constexpr uint64_t kSourceMemory = 1ull << 22; // SourceType == DSTORAGE_REQUEST_SOURCE_MEMORY -constexpr uint64_t kSourcePages = 1ull << 23; -constexpr uint64_t kReservedMask = ~((1ull << 24) - 1); - -constexpr bool zlib(uint64_t o) { return (o & kZlib) != 0; } -constexpr uint64_t bcpack(uint64_t o) { return (o & kBcpackMask) >> kBcpackShift; } -constexpr uint64_t swizzle(uint64_t o) { return (o & kSwizzleMask) >> kSwizzleShift; } -constexpr DSTORAGE_REQUEST_SOURCE_TYPE source_type(uint64_t o) { - return (o & kSourceMemory) ? DSTORAGE_REQUEST_SOURCE_MEMORY : DSTORAGE_REQUEST_SOURCE_FILE; -} -} // namespace options - -struct IDStorageFileX; -struct IDStorageStatusArrayX; - -struct DSTORAGE_REQUEST { - DSTORAGE_REQUEST_OPTIONS Options; - union { - void* Destination; - struct { - PULONG_PTR DestinationPageArray; - UINT16 DestinationPageOffset; - }; - }; - UINT32 DestinationSize; - union { - struct { - IDStorageFileX* File; - UINT64 FileOffset; - }; - const void* Source; - struct { - PULONG_PTR SourcePageArray; - UINT16 SourcePageOffset; - }; - }; - UINT32 SourceSize; - UINT32 IntermediateSize; - UINT64 CancellationTag; - const CHAR* Name; -}; -static_assert(offsetof(DSTORAGE_REQUEST, Destination) == 8 && offsetof(DSTORAGE_REQUEST, DestinationPageOffset) == 16); -static_assert(offsetof(DSTORAGE_REQUEST, DestinationSize) == 24 && offsetof(DSTORAGE_REQUEST, File) == 32); -static_assert(offsetof(DSTORAGE_REQUEST, FileOffset) == 40 && offsetof(DSTORAGE_REQUEST, Source) == 32); -static_assert(offsetof(DSTORAGE_REQUEST, SourcePageOffset) == 40 && offsetof(DSTORAGE_REQUEST, SourceSize) == 48); -static_assert(offsetof(DSTORAGE_REQUEST, IntermediateSize) == 52 && offsetof(DSTORAGE_REQUEST, CancellationTag) == 56); -static_assert(offsetof(DSTORAGE_REQUEST, Name) == 64 && sizeof(DSTORAGE_REQUEST) == 72); - -struct DSTORAGE_QUEUE_DESC { - DSTORAGE_REQUEST_SOURCE_TYPE SourceType; - UINT16 Capacity; - DSTORAGE_PRIORITY Priority; - const CHAR* Name; -}; -static_assert(offsetof(DSTORAGE_QUEUE_DESC, Capacity) == 8 && offsetof(DSTORAGE_QUEUE_DESC, Priority) == 10); -static_assert(offsetof(DSTORAGE_QUEUE_DESC, Name) == 16 && sizeof(DSTORAGE_QUEUE_DESC) == 24); - -union DSTORAGE_QUEUE_OPTIONS { - struct { - uint64_t AutoSubmitDisabled : 1; - uint64_t Reserved : 63; - }; - uint64_t AsUINT64; -}; -static_assert(sizeof(DSTORAGE_QUEUE_OPTIONS) == 8); - -struct DSTORAGE_QUEUE_DESC1 { - DSTORAGE_REQUEST_SOURCE_TYPE SourceType; - UINT16 Capacity; - DSTORAGE_PRIORITY Priority; - const CHAR* Name; - DSTORAGE_QUEUE_OPTIONS Options; -}; -static_assert(offsetof(DSTORAGE_QUEUE_DESC1, Options) == 24 && sizeof(DSTORAGE_QUEUE_DESC1) == 32); - -struct DSTORAGE_QUEUE_INFO { - DSTORAGE_QUEUE_DESC Desc; - UINT16 EmptySlotCount; - UINT16 RequestCountUntilAutoSubmit; -}; -static_assert(offsetof(DSTORAGE_QUEUE_INFO, EmptySlotCount) == 24 && sizeof(DSTORAGE_QUEUE_INFO) == 32); - -struct DSTORAGE_QUEUE_INFO1 { - DSTORAGE_QUEUE_DESC1 Desc; - UINT16 EmptySlotCount; - UINT16 RequestCountUntilAutoSubmit; -}; -static_assert(offsetof(DSTORAGE_QUEUE_INFO1, EmptySlotCount) == 32 && sizeof(DSTORAGE_QUEUE_INFO1) == 40); - -// The reference declares the three failure kinds as unnamed structs inside DSTORAGE_ERROR_RECORD; they are named -// here (Leonida's names) so the shim can fill them. The layout is the same. -struct DSTORAGE_ERROR_REQUEST { - DSTORAGE_REQUEST_OPTIONS Options; - void* Destination; - UINT32 DestinationSize; - WCHAR Filename[MAX_PATH]; - UINT64 FileOffset; - const void* Source; - UINT32 SourceSize; - UINT64 CancellationTag; - CHAR Name[kRequestMaxName]; -}; -struct DSTORAGE_ERROR_STATUS { - IDStorageStatusArrayX* StatusArray; - UINT32 Index; -}; -struct DSTORAGE_ERROR_SIGNAL { - ID3D12Fence* Fence; - UINT64 Value; -}; -struct DSTORAGE_ERROR_FIRST_FAILURE { - HRESULT HResult; - DSTORAGE_COMMAND_TYPE CommandType; - union { - DSTORAGE_ERROR_REQUEST Request; - DSTORAGE_ERROR_STATUS Status; - DSTORAGE_ERROR_SIGNAL Signal; - }; -}; -struct DSTORAGE_ERROR_RECORD { - UINT32 FailureCount; - DSTORAGE_ERROR_FIRST_FAILURE FirstFailure; -}; -static_assert(offsetof(DSTORAGE_ERROR_RECORD, FirstFailure) == 8); -static_assert(offsetof(DSTORAGE_ERROR_FIRST_FAILURE, Request) == 8); -static_assert(offsetof(DSTORAGE_ERROR_REQUEST, Filename) == 20 && offsetof(DSTORAGE_ERROR_REQUEST, FileOffset) == 544); -static_assert(offsetof(DSTORAGE_ERROR_REQUEST, Name) == 576 && sizeof(DSTORAGE_ERROR_REQUEST) == 640); -static_assert(sizeof(DSTORAGE_ERROR_RECORD) == 656); - -struct DSTORAGE_PRIORITY_STATS { - UINT32 CurrentQueueCount; - UINT32 MaxQueueCount; - UINT32 CumulativeQueueCount; - UINT32 TotalStatusCount; - UINT32 TotalFenceCount; - UINT32 PendingRequestCount; - UINT32 TotalRequestCount; - UINT64 TotalRequestSourceByteCount; - UINT64 TotalRequestDestinationByteCount; -}; -static_assert(sizeof(DSTORAGE_PRIORITY_STATS) == 48); - -struct DSTORAGE_STATS { - DSTORAGE_PRIORITY_STATS LowPriorityStats; - DSTORAGE_PRIORITY_STATS NormalPriorityStats; - DSTORAGE_PRIORITY_STATS HighPriorityStats; - DSTORAGE_PRIORITY_STATS RealtimePriorityStats; - UINT8 CurrentOpenVirtualDiskCount; - UINT8 MaxOpenVirtualDiskCount; - UINT32 CumulativeOpenVirtualDiskCount; - UINT32 PendingStorageRequestCount; - UINT32 TotalStorageRequestCount; - UINT32 StorageRetries; - UINT32 StorageErrors; - UINT32 PendingDecompressionRequestCount; - UINT32 TotalDecompressionRequestCount; - UINT32 DecompressionErrors; - UINT32 StagingBufferStallCount; - UINT32 CurrentOpenFileCount; - UINT32 MaxOpenFileCount; - UINT32 CumulativeOpenFileCount; - UINT32 CurrentTitleMemoryUsageBytes; - UINT32 MaxTitleMemoryUsageBytes; - UINT32 ErrorCount; -}; - -#pragma warning(pop) - -// ---- Interfaces, in the vtable order chosen above --------------------------------------------------------------- - -struct IDStorageStatusArrayX : IUnknown { - virtual bool STDMETHODCALLTYPE IsComplete(UINT32 index) = 0; - virtual HRESULT STDMETHODCALLTYPE GetHResult(UINT32 index) = 0; -}; - -struct IDStorageFileX : IUnknown { - virtual void STDMETHODCALLTYPE Close() = 0; - virtual HANDLE STDMETHODCALLTYPE GetHandle() = 0; -}; - -struct IDStorageQueueX : IUnknown { - virtual void STDMETHODCALLTYPE EnqueueRequest(const DSTORAGE_REQUEST* request) = 0; - virtual void STDMETHODCALLTYPE EnqueueStatus(IDStorageStatusArrayX* status_array, UINT32 index) = 0; - virtual void STDMETHODCALLTYPE EnqueueSignal(ID3D12Fence* fence, UINT64 value) = 0; - virtual void STDMETHODCALLTYPE Submit() = 0; - virtual void STDMETHODCALLTYPE CancelRequestsWithTag(UINT64 mask, UINT64 value) = 0; - virtual void STDMETHODCALLTYPE Close() = 0; - virtual HANDLE STDMETHODCALLTYPE GetErrorEvent() = 0; - virtual void STDMETHODCALLTYPE RetrieveErrorRecord(DSTORAGE_ERROR_RECORD* record) = 0; - virtual void STDMETHODCALLTYPE Query(DSTORAGE_QUEUE_INFO* info) = 0; -}; - -struct IDStorageQueueX1 : IDStorageQueueX { - virtual void STDMETHODCALLTYPE EnqueueSetEvent(HANDLE handle) = 0; -}; - -struct IDStorageQueueX2 : IDStorageQueueX1 { - virtual void STDMETHODCALLTYPE Query1(DSTORAGE_QUEUE_INFO1* info) = 0; -}; - -struct IDStorageFactoryX : IUnknown { - virtual HRESULT STDMETHODCALLTYPE CreateQueue(const DSTORAGE_QUEUE_DESC* desc, REFIID riid, void** ppv) = 0; - virtual HRESULT STDMETHODCALLTYPE OpenFile(const WCHAR* path, REFIID riid, void** ppv) = 0; - virtual HRESULT STDMETHODCALLTYPE CreateStatusArray(UINT32 capacity, PCSTR name, REFIID riid, void** ppv) = 0; - virtual HRESULT STDMETHODCALLTYPE SetCpuAffinity(UINT64 affinity) = 0; - virtual void STDMETHODCALLTYPE SetDebugFlags(UINT32 flags) = 0; - virtual HRESULT STDMETHODCALLTYPE SetStagingBufferSize(UINT32 size) = 0; -}; - -struct IDStorageFactoryX1 : IDStorageFactoryX { - virtual void STDMETHODCALLTYPE GetStats(DSTORAGE_STATS* stats) = 0; -}; - -struct IDStorageFactoryX2 : IDStorageFactoryX1 { - virtual HRESULT STDMETHODCALLTYPE CreateQueue1(const DSTORAGE_QUEUE_DESC1* desc, REFIID riid, void** ppv) = 0; -}; - -using DStorageGetFactoryFn = HRESULT(WINAPI*)(REFIID riid, void** ppv); - -// ---- Interface ids ------------------------------------------------------------------------------------------------- - -// Accepted for a status array: IDStorageStatusArray (PC dstorage.h 1.3.0), same methods in the same order. -constexpr GUID kStatusArrayIds[] = { - {0x82397587, 0x7cd5, 0x453b, {0xa0, 0x2e, 0x31, 0x37, 0x9b, 0xd6, 0x46, 0x56}}, -}; - -// The other PC DirectStorage ids (dstorage.h 1.3.0), refused: their objects have another shape. -constexpr GUID kPcInterfaceIds[] = { - {0x6924ea0c, 0xc3cd, 0x4826, {0xb1, 0x0a, 0xf6, 0x4f, 0x4e, 0xd9, 0x27, 0xc1}}, // IDStorageFactory - {0x5de95e7b, 0x955a, 0x4868, {0xa7, 0x3c, 0x24, 0x3b, 0x29, 0xf4, 0xb8, 0xda}}, // IDStorageFile - {0xcfdbd83f, 0x9e06, 0x4fda, {0x8e, 0xa5, 0x69, 0x04, 0x21, 0x37, 0xf4, 0x9b}}, // IDStorageQueue - {0xdd2f482c, 0x5eff, 0x41e8, {0x9c, 0x9e, 0xd2, 0x37, 0x4b, 0x27, 0x81, 0x28}}, // IDStorageQueue1 - {0xb1c9d643, 0x3a49, 0x44a2, {0xb4, 0x6f, 0x65, 0x36, 0x49, 0x47, 0x0d, 0x18}}, // IDStorageQueue2 - {0xdeb54c52, 0xeca8, 0x46b3, {0x82, 0xa7, 0x03, 0x1b, 0x72, 0x26, 0x26, 0x53}}, // IDStorageQueue3 - {0x97179b2f, 0x2c21, 0x49ca, {0x82, 0x91, 0x4e, 0x1b, 0xf4, 0xa1, 0x60, 0xdf}}, // ...CustomDecompressionQueue - {0x0d47c6c9, 0xe61a, 0x4706, {0x93, 0xb4, 0x68, 0xbf, 0xe3, 0xf4, 0xaa, 0x4a}}, // ...CustomDecompressionQueue1 - {0x84ef5121, 0x9b43, 0x4d03, {0xb5, 0xc1, 0xcc, 0x34, 0x60, 0x6b, 0x26, 0x2d}}, // IDStorageCompressionCodec -}; - -} // namespace dsx diff --git a/runtime/shims/dxgi_com.cpp b/runtime/shims/dxgi_com.cpp deleted file mode 100644 index 63c5990d4..000000000 --- a/runtime/shims/dxgi_com.cpp +++ /dev/null @@ -1,1742 +0,0 @@ -#include "dxgi_com.h" -#include "d3d12_stubs.h" -#include "../core/log.h" - -#include // NTSTATUS, which d3dkmthk.h needs and WIN32_LEAN_AND_MEAN leaves out -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace rt::dxgi { -namespace { - -// Native DXGI accepts up to 40 queued frames on a waitable swapchain. -constexpr UINT max_waitable_frame_latency = 40; - -void stub(const char* method) { - static std::mutex mutex; - static std::set seen; - std::lock_guard lock(mutex); - if (seen.insert(method).second) RT_LOG_WARN("dxgi: unimplemented %s\n", method); -} - -// IDXGIObject private data, shared by the factory, adapter and swapchain. SetPrivateData keeps a copy of the bytes; -// SetPrivateDataInterface holds one reference until the entry is replaced, removed or the owner dies (Microsoft: -// IDXGIObject::SetPrivateDataInterface). Zero bytes remove the entry. GetPrivateData gives an interface back with a -// reference added, and a buffer too small for the entry gets DXGI_ERROR_MORE_DATA and the size to retry with. -class PrivateDataStore { -public: - PrivateDataStore() = default; - PrivateDataStore(const PrivateDataStore&) = delete; - PrivateDataStore& operator=(const PrivateDataStore&) = delete; - ~PrivateDataStore() { - for (auto& entry : data_) - if (entry.object) entry.object->Release(); - } - - HRESULT get(REFGUID guid, UINT* size, void* data) { - if (!size) return E_INVALIDARG; - std::lock_guard lock(mutex_); - for (const auto& entry : data_) { - if (entry.key != guid) continue; - const UINT bytes = entry.object ? UINT(sizeof(IUnknown*)) : UINT(entry.bytes.size()); - if (data && *size < bytes) { - *size = bytes; - return DXGI_ERROR_MORE_DATA; - } - if (data) { - if (entry.object) { - entry.object->AddRef(); - std::memcpy(data, &entry.object, sizeof(IUnknown*)); - } else { - std::memcpy(data, entry.bytes.data(), bytes); - } - } - *size = bytes; - return S_OK; - } - *size = 0; - return DXGI_ERROR_NOT_FOUND; - } - - HRESULT set(REFGUID guid, UINT size, const void* data) { - if (size && !data) return E_INVALIDARG; - Entry entry{guid, {}, nullptr}; - if (size) { - const auto* bytes = static_cast(data); - entry.bytes.assign(bytes, bytes + size); - } - store(std::move(entry), size != 0); - return S_OK; - } - - HRESULT set_interface(REFGUID guid, const IUnknown* object) { - IUnknown* held = const_cast(object); - if (held) held->AddRef(); - store(Entry{guid, {}, held}, held != nullptr); - return S_OK; - } - -private: - struct Entry { - GUID key; - std::vector bytes; - IUnknown* object; - }; - - // The replaced interface is released after the lock is dropped, since its Release may run arbitrary code. - void store(Entry entry, bool keep) { - IUnknown* released = nullptr; - { - std::lock_guard lock(mutex_); - for (auto it = data_.begin(); it != data_.end(); ++it) { - if (it->key != entry.key) continue; - released = it->object; - data_.erase(it); - break; - } - if (keep) data_.push_back(std::move(entry)); - } - if (released) released->Release(); - } - - std::mutex mutex_; - std::vector data_; -}; - -bool valid_flip_buffer_count(UINT count) { - return count >= 2 && count <= DXGI_MAX_SWAP_CHAIN_BUFFERS; -} - -bool is_direct_present_queue(IUnknown* candidate) { - ID3D12CommandQueue* queue = nullptr; - if (!candidate || FAILED(candidate->QueryInterface(IID_PPV_ARGS(&queue))) || !queue) return false; - const bool direct = queue->GetDesc().Type == D3D12_COMMAND_LIST_TYPE_DIRECT; - queue->Release(); - return direct; -} - -VkFormat dxgi_to_vk_format(DXGI_FORMAT fmt) { - switch (fmt) { - case DXGI_FORMAT_B8G8R8A8_UNORM: return VK_FORMAT_B8G8R8A8_UNORM; - case DXGI_FORMAT_R8G8B8A8_UNORM: return VK_FORMAT_R8G8B8A8_UNORM; - case DXGI_FORMAT_R10G10B10A2_UNORM: return VK_FORMAT_A2B10G10R10_UNORM_PACK32; - case DXGI_FORMAT_R16G16B16A16_FLOAT: return VK_FORMAT_R16G16B16A16_SFLOAT; - default: return VK_FORMAT_UNDEFINED; - } -} - -DXGI_FORMAT vk_to_dxgi_format(VkFormat fmt) { - switch (fmt) { - case VK_FORMAT_B8G8R8A8_UNORM: return DXGI_FORMAT_B8G8R8A8_UNORM; - case VK_FORMAT_B8G8R8A8_SRGB: return DXGI_FORMAT_B8G8R8A8_UNORM_SRGB; - case VK_FORMAT_R8G8B8A8_UNORM: return DXGI_FORMAT_R8G8B8A8_UNORM; - case VK_FORMAT_R8G8B8A8_SRGB: return DXGI_FORMAT_R8G8B8A8_UNORM_SRGB; - case VK_FORMAT_A2B10G10R10_UNORM_PACK32: return DXGI_FORMAT_R10G10B10A2_UNORM; - case VK_FORMAT_R16G16B16A16_SFLOAT: return DXGI_FORMAT_R16G16B16A16_FLOAT; - default: return DXGI_FORMAT_UNKNOWN; - } -} - -// Real ID3D12Resource COM object representing a swapchain backbuffer. Its pointer value is the -// leonida::ResourceId registered in VulkanContext, matching d3d12_com.h's resource_id(ID3D12Resource*) contract. -class BackBufferResource final : public ID3D12ResourceStubs { -public: - explicit BackBufferResource(const D3D12_RESOURCE_DESC& desc) : desc_(desc) {} - - ULONG STDMETHODCALLTYPE AddRef() override { return ++refs_; } - ULONG STDMETHODCALLTYPE Release() override { - const ULONG left = --refs_; - if (!left) delete this; - return left; - } - HRESULT STDMETHODCALLTYPE QueryInterface(REFIID riid, void** out) override { - if (!out) return E_POINTER; - *out = nullptr; - if (riid == __uuidof(IUnknown) || riid == __uuidof(ID3D12Object) || riid == __uuidof(ID3D12DeviceChild) || - riid == __uuidof(ID3D12Pageable) || riid == __uuidof(ID3D12Resource)) { - *out = static_cast(this); - AddRef(); - return S_OK; - } - return E_NOINTERFACE; - } - - HRESULT STDMETHODCALLTYPE SetName(LPCWSTR) override { return S_OK; } - -#ifdef _MSC_VER - D3D12_RESOURCE_DESC STDMETHODCALLTYPE GetDesc(void) override { return desc_; } -#else - D3D12_RESOURCE_DESC* STDMETHODCALLTYPE GetDesc(D3D12_RESOURCE_DESC* ret) override { - if (ret) *ret = desc_; - return ret; - } -#endif - - D3D12_GPU_VIRTUAL_ADDRESS STDMETHODCALLTYPE GetGPUVirtualAddress(void) override { return 0; } - - HRESULT STDMETHODCALLTYPE GetHeapProperties(D3D12_HEAP_PROPERTIES* props, D3D12_HEAP_FLAGS* flags) override { - if (props) { - *props = {}; - props->Type = D3D12_HEAP_TYPE_DEFAULT; - props->CreationNodeMask = 1; - props->VisibleNodeMask = 1; - } - if (flags) *flags = D3D12_HEAP_FLAG_ALLOW_ONLY_RT_DS_TEXTURES; - return S_OK; - } - - leonida::ResourceId resource_id() const { return reinterpret_cast(this); } - bool held_by_app() const { return refs_ > 1; } - -private: - std::atomic refs_{1}; - D3D12_RESOURCE_DESC desc_{}; -}; - -class SwapChain final : public IDXGISwapChain3 { -public: - SwapChain(IDXGIFactory4* parent, IUnknown* device, leonida::VulkanContext& context, - PFN_vkGetInstanceProcAddr gipa, VkInstance instance, VkPhysicalDevice physical, - PFN_vkGetDeviceProcAddr gdpa, VkQueue queue, std::uint32_t queue_family) - : parent_(parent), - device_(device), - context_(context), - swapchain_(gipa, instance, physical, gdpa, context.device(), queue, queue_family, context.submit_mutex()) { - if (parent_) parent_->AddRef(); - if (device_) device_->AddRef(); - } - - ~SwapChain() { - unregister_buffers(); - if (restrict_to_output_) restrict_to_output_->Release(); - if (waitable_) CloseHandle(waitable_); - if (device_) device_->Release(); - if (parent_) parent_->Release(); - } - - bool init(HWND hwnd, const DXGI_SWAP_CHAIN_DESC1& desc, VkFormat vk_fmt) { - hwnd_ = hwnd; - flags_ = desc.Flags; - swap_effect_ = desc.SwapEffect; - buffer_usage_ = desc.BufferUsage; - const VkExtent2D size = size_or_client(desc.Width, desc.Height, {256u, 256u}); - const std::uint32_t w = size.width; - const std::uint32_t h = size.height; - const bool allow_tearing = (flags_ & DXGI_SWAP_CHAIN_FLAG_ALLOW_TEARING) != 0; - if (!swapchain_.create(hwnd, w, h, vk_fmt, desc.BufferCount, allow_tearing)) return false; - source_size_ = {w, h}; - if (flags_ & DXGI_SWAP_CHAIN_FLAG_FRAME_LATENCY_WAITABLE_OBJECT) { - // DXGI: waitable swapchains default to maximum frame latency 1. - max_frame_latency_.store(1, std::memory_order_relaxed); - waitable_ = CreateSemaphoreW(nullptr, 1, max_waitable_frame_latency, nullptr); - if (!waitable_) return false; - } - register_buffers(); - std::uint32_t idx = 0; - return swapchain_.acquire_next_image(idx); - } - - // IUnknown - ULONG STDMETHODCALLTYPE AddRef() override { return ++refs_; } - ULONG STDMETHODCALLTYPE Release() override { - const ULONG left = --refs_; - if (!left) delete this; - return left; - } - HRESULT STDMETHODCALLTYPE QueryInterface(REFIID riid, void** out) override { - if (!out) return E_POINTER; - *out = nullptr; - if (riid == __uuidof(IUnknown) || riid == __uuidof(IDXGIObject) || riid == __uuidof(IDXGIDeviceSubObject) || - riid == __uuidof(IDXGISwapChain) || riid == __uuidof(IDXGISwapChain1) || - riid == __uuidof(IDXGISwapChain2) || riid == __uuidof(IDXGISwapChain3)) { - *out = static_cast(this); - AddRef(); - return S_OK; - } - return E_NOINTERFACE; - } - - // IDXGIObject - HRESULT STDMETHODCALLTYPE SetPrivateData(REFGUID guid, UINT size, const void* data) override { - return private_data_.set(guid, size, data); - } - HRESULT STDMETHODCALLTYPE SetPrivateDataInterface(REFGUID guid, const IUnknown* object) override { - return private_data_.set_interface(guid, object); - } - HRESULT STDMETHODCALLTYPE GetPrivateData(REFGUID guid, UINT* size, void* data) override { - return private_data_.get(guid, size, data); - } - HRESULT STDMETHODCALLTYPE GetParent(REFIID riid, void** out) override { - if (!out) return E_POINTER; - *out = nullptr; - if (!parent_) return E_NOINTERFACE; - return parent_->QueryInterface(riid, out); - } - - // IDXGIDeviceSubObject - HRESULT STDMETHODCALLTYPE GetDevice(REFIID riid, void** out) override { - if (!out) return E_POINTER; - *out = nullptr; - if (!device_) return E_NOINTERFACE; - - ID3D12DeviceChild* device_child = nullptr; - if (SUCCEEDED(device_->QueryInterface(IID_PPV_ARGS(&device_child)))) { - const HRESULT hr = device_child->GetDevice(riid, out); - device_child->Release(); - return hr; - } - return device_->QueryInterface(riid, out); - } - - // IDXGISwapChain - HRESULT STDMETHODCALLTYPE Present(UINT sync, UINT flags) override { - if (sync > 4) return DXGI_ERROR_INVALID_CALL; - if ((flags & DXGI_PRESENT_ALLOW_TEARING) && - (sync != 0 || !(flags_ & DXGI_SWAP_CHAIN_FLAG_ALLOW_TEARING))) - return DXGI_ERROR_INVALID_CALL; - if (flags & DXGI_PRESENT_TEST) return S_OK; // only asks whether a present would succeed - const std::uint32_t cur = swapchain_.current_back_buffer_index(); - if (!swapchain_.present(cur)) return E_FAIL; - ++present_count_; - LARGE_INTEGER qpc{}; - if (QueryPerformanceCounter(&qpc)) last_present_qpc_.store(qpc.QuadPart, std::memory_order_relaxed); - std::uint32_t next = 0; - if (!swapchain_.acquire_next_image(next)) return E_FAIL; - if (waitable_) ReleaseSemaphore(waitable_, 1, nullptr); - return S_OK; - } - - HRESULT STDMETHODCALLTYPE GetBuffer(UINT buffer, REFIID riid, void** surface) override { - if (!surface) return DXGI_ERROR_INVALID_CALL; // host-measured, not E_POINTER - *surface = nullptr; - if (buffer >= buffers_.size()) return DXGI_ERROR_INVALID_CALL; - return buffers_[buffer]->QueryInterface(riid, surface); - } - - HRESULT STDMETHODCALLTYPE SetFullscreenState(BOOL, IDXGIOutput*) override { return S_OK; } - HRESULT STDMETHODCALLTYPE GetFullscreenState(BOOL* fs, IDXGIOutput** out) override { - if (fs) *fs = FALSE; - if (out) *out = nullptr; - return S_OK; - } - - HRESULT STDMETHODCALLTYPE GetDesc(DXGI_SWAP_CHAIN_DESC* desc) override { - if (!desc) return E_INVALIDARG; - std::memset(desc, 0, sizeof(*desc)); - desc->BufferDesc.Width = swapchain_.extent().width; - desc->BufferDesc.Height = swapchain_.extent().height; - desc->BufferDesc.Format = vk_to_dxgi_format(swapchain_.format()); - desc->SampleDesc.Count = 1; - desc->BufferUsage = buffer_usage_; - desc->BufferCount = swapchain_.image_count(); - desc->OutputWindow = hwnd_; - desc->Windowed = TRUE; - desc->SwapEffect = swap_effect_; - desc->Flags = flags_; - return S_OK; - } - - HRESULT STDMETHODCALLTYPE ResizeBuffers(UINT count, UINT width, UINT height, DXGI_FORMAT fmt, UINT flags) override { - return resize_buffers(count, width, height, fmt, flags, nullptr, nullptr); - } - - HRESULT resize_buffers(UINT count, UINT width, UINT height, DXGI_FORMAT fmt, UINT flags, - const UINT* node_masks, IUnknown* const* present_queues) { - if (count != 0 && !valid_flip_buffer_count(count)) return E_INVALIDARG; - VkFormat vk_fmt = VK_FORMAT_UNDEFINED; - if (fmt != DXGI_FORMAT_UNKNOWN) { - vk_fmt = dxgi_to_vk_format(fmt); - if (vk_fmt == VK_FORMAT_UNDEFINED) return E_INVALIDARG; - } - // DXGI first checks creation-dependent flags against the chain's original flags. If one is missing, this - // E_INVALIDARG wins even when the same call also includes flags that independently return INVALID_CALL. - constexpr UINT creation_only_flags = DXGI_SWAP_CHAIN_FLAG_FRAME_LATENCY_WAITABLE_OBJECT | - DXGI_SWAP_CHAIN_FLAG_ALLOW_TEARING | - DXGI_SWAP_CHAIN_FLAG_FOREGROUND_LAYER | DXGI_SWAP_CHAIN_FLAG_YUV_VIDEO | - 0x2000u; - if ((flags & creation_only_flags) != (flags_ & creation_only_flags)) return E_INVALIDARG; - // On a chain whose creation flags match, NONPREROTATED, FULLSCREEN_VIDEO and every bit from 0x4000 up are - // DXGI_ERROR_INVALID_CALL (host-measured on Windows 11 with the RTX 5070 Ti and WARP). - constexpr UINT refused_flags = ~0x3fffu | DXGI_SWAP_CHAIN_FLAG_NONPREROTATED | - DXGI_SWAP_CHAIN_FLAG_FULLSCREEN_VIDEO; - if (flags & refused_flags) return DXGI_ERROR_INVALID_CALL; - // DXGI refuses to resize while the app still holds a back buffer reference. - for (auto* bb : buffers_) - if (bb->held_by_app()) return DXGI_ERROR_INVALID_CALL; - const std::size_t target_count = count ? count : buffers_.size(); - if (node_masks && !std::all_of(node_masks, node_masks + target_count, [](UINT mask) { return mask <= 1; })) - return DXGI_ERROR_INVALID_CALL; - if (present_queues && !std::all_of(present_queues, present_queues + target_count, is_direct_present_queue)) - return DXGI_ERROR_INVALID_CALL; - unregister_buffers(); - const VkExtent2D size = size_or_client(width, height, swapchain_.extent()); - const std::uint32_t w = size.width; - const std::uint32_t h = size.height; - const UINT next_flags = flags ? flags : flags_; - const bool allow_tearing = (next_flags & DXGI_SWAP_CHAIN_FLAG_ALLOW_TEARING) != 0; - if (!swapchain_.resize(w, h, vk_fmt, count, allow_tearing)) return E_FAIL; - source_size_ = {w, h}; // host-measured: ResizeBuffers resets the source region to the new back buffers - statistics_disjoint_.store(true, std::memory_order_relaxed); - flags_ = next_flags; - register_buffers(); - std::uint32_t next = 0; - return swapchain_.acquire_next_image(next) ? S_OK : E_FAIL; - } - - HRESULT STDMETHODCALLTYPE ResizeTarget(const DXGI_MODE_DESC* mode) override { - if (!mode) return DXGI_ERROR_INVALID_CALL; // host-measured, not E_INVALIDARG - // Windowed: the target output's client area takes the mode's size, and the back buffers keep theirs until - // ResizeBuffers (where 0 means the client area). The window's own style gives the frame around it. A zero - // size is accepted, as on the host, and the window's minimum tracking size decides what is left of it. - RECT frame{0, 0, static_cast(mode->Width), static_cast(mode->Height)}; - const auto style = static_cast(GetWindowLongW(hwnd_, GWL_STYLE)); - const auto ex_style = static_cast(GetWindowLongW(hwnd_, GWL_EXSTYLE)); - if (!AdjustWindowRectEx(&frame, style, FALSE, ex_style)) return E_INVALIDARG; - if (!SetWindowPos(hwnd_, nullptr, 0, 0, frame.right - frame.left, frame.bottom - frame.top, - SWP_NOMOVE | SWP_NOZORDER | SWP_NOACTIVATE)) - return DXGI_ERROR_INVALID_CALL; - return S_OK; - } - HRESULT STDMETHODCALLTYPE GetContainingOutput(IDXGIOutput** out) override { - if (!out) return DXGI_ERROR_INVALID_CALL; - *out = nullptr; - if (!parent_) return DXGI_ERROR_NOT_CURRENTLY_AVAILABLE; - IDXGIAdapter* adapter = nullptr; - if (FAILED(parent_->EnumAdapters(0, &adapter)) || !adapter) return DXGI_ERROR_NOT_CURRENTLY_AVAILABLE; - - const HMONITOR target = hwnd_ ? MonitorFromWindow(hwnd_, MONITOR_DEFAULTTONEAREST) : nullptr; - IDXGIOutput* fallback = nullptr; - for (UINT i = 0;; ++i) { - IDXGIOutput* candidate = nullptr; - if (adapter->EnumOutputs(i, &candidate) == DXGI_ERROR_NOT_FOUND) break; - if (!candidate) continue; - DXGI_OUTPUT_DESC desc{}; - if (target && SUCCEEDED(candidate->GetDesc(&desc)) && desc.Monitor == target) { - if (fallback) fallback->Release(); - adapter->Release(); - *out = candidate; - return S_OK; - } - if (!fallback) { - fallback = candidate; - } else { - candidate->Release(); - } - } - adapter->Release(); - if (!fallback) return DXGI_ERROR_NOT_CURRENTLY_AVAILABLE; - *out = fallback; - return S_OK; - } - HRESULT STDMETHODCALLTYPE GetFrameStatistics(DXGI_FRAME_STATISTICS* stats) override { - if (!stats) return DXGI_ERROR_INVALID_CALL; - std::memset(stats, 0, sizeof(*stats)); - // Native DXGI reports the discontinuity once, on the first valid query after creation or resize. - if (statistics_disjoint_.exchange(false, std::memory_order_relaxed)) - return DXGI_ERROR_FRAME_STATISTICS_DISJOINT; - const UINT count = present_count_.load(std::memory_order_relaxed); - stats->PresentCount = count; - stats->PresentRefreshCount = count; - stats->SyncRefreshCount = count; - stats->SyncQPCTime.QuadPart = last_present_qpc_.load(std::memory_order_relaxed); - return S_OK; - } - HRESULT STDMETHODCALLTYPE GetLastPresentCount(UINT* p) override { - if (!p) return DXGI_ERROR_INVALID_CALL; // host-measured - *p = present_count_.load(std::memory_order_relaxed); - return S_OK; - } - - // IDXGISwapChain1 - HRESULT STDMETHODCALLTYPE GetDesc1(DXGI_SWAP_CHAIN_DESC1* desc) override { - if (!desc) return E_INVALIDARG; - std::memset(desc, 0, sizeof(*desc)); - desc->Width = swapchain_.extent().width; - desc->Height = swapchain_.extent().height; - desc->Format = vk_to_dxgi_format(swapchain_.format()); - desc->SampleDesc.Count = 1; - desc->BufferUsage = buffer_usage_; - desc->BufferCount = swapchain_.image_count(); - desc->Scaling = DXGI_SCALING_STRETCH; - desc->SwapEffect = swap_effect_; - desc->AlphaMode = DXGI_ALPHA_MODE_IGNORE; - desc->Flags = flags_; - return S_OK; - } - HRESULT STDMETHODCALLTYPE GetFullscreenDesc(DXGI_SWAP_CHAIN_FULLSCREEN_DESC* desc) override { - if (!desc) return E_INVALIDARG; - std::memset(desc, 0, sizeof(*desc)); - desc->Windowed = TRUE; - return S_OK; - } - HRESULT STDMETHODCALLTYPE GetHwnd(HWND* out) override { - if (!out) return DXGI_ERROR_INVALID_CALL; // host-measured - *out = hwnd_; - return S_OK; - } - HRESULT STDMETHODCALLTYPE GetCoreWindow(REFIID, void** out) override { - if (!out) return DXGI_ERROR_INVALID_CALL; - *out = nullptr; - return DXGI_ERROR_INVALID_CALL; - } - HRESULT STDMETHODCALLTYPE Present1(UINT sync, UINT flags, const DXGI_PRESENT_PARAMETERS*) override { - return Present(sync, flags); - } - BOOL STDMETHODCALLTYPE IsTemporaryMonoSupported() override { return FALSE; } - // Host-measured: a chain created without an output answers S_OK with a null output, and a null pointer is - // DXGI_ERROR_INVALID_CALL. - HRESULT STDMETHODCALLTYPE GetRestrictToOutput(IDXGIOutput** out) override { - if (!out) return DXGI_ERROR_INVALID_CALL; - *out = restrict_to_output_; - if (restrict_to_output_) restrict_to_output_->AddRef(); - return S_OK; - } - void set_restrict_to_output(IDXGIOutput* out) { - if (restrict_to_output_) restrict_to_output_->Release(); - restrict_to_output_ = out; - if (restrict_to_output_) restrict_to_output_->AddRef(); - } - HRESULT STDMETHODCALLTYPE SetBackgroundColor(const DXGI_RGBA* color) override { - if (!color) return E_INVALIDARG; - background_color_ = *color; - return S_OK; - } - HRESULT STDMETHODCALLTYPE GetBackgroundColor(DXGI_RGBA* color) override { - if (!color) return E_INVALIDARG; - *color = background_color_; - return S_OK; - } - HRESULT STDMETHODCALLTYPE SetRotation(DXGI_MODE_ROTATION rotation) override { - rotation_ = rotation; - return S_OK; - } - HRESULT STDMETHODCALLTYPE GetRotation(DXGI_MODE_ROTATION* rotation) override { - if (!rotation) return E_INVALIDARG; - *rotation = rotation_; - return S_OK; - } - - // IDXGISwapChain2 - HRESULT STDMETHODCALLTYPE SetSourceSize(UINT width, UINT height) override { - // Host-measured: a region larger than either back-buffer dimension is refused and keeps the stored one; - // zero is accepted. Present does not scale by it yet (documented difference). - const VkExtent2D extent = swapchain_.extent(); - if (width > extent.width || height > extent.height) return DXGI_ERROR_INVALID_CALL; - source_size_ = {width, height}; - return S_OK; - } - HRESULT STDMETHODCALLTYPE GetSourceSize(UINT* w, UINT* h) override { - if (!w || !h) return DXGI_ERROR_INVALID_CALL; // host-measured: both are required - *w = source_size_.width; - *h = source_size_.height; - return S_OK; - } - // Host-measured (Windows 11, RTX 5090 and WARP): the waitable object is a semaphore initialized to 1 with max 40. - // Increasing latency releases (max_latency - prev) tokens (if current + delta > 40, ReleaseSemaphore fails with - // ERROR_TOO_MANY_POSTS leaving count unchanged and SetMaximumFrameLatency still returns S_OK). Decreasing updates - // max_frame_latency_ without draining existing tokens. Present releases 1 token per non-test call up to max 40. - HRESULT STDMETHODCALLTYPE SetMaximumFrameLatency(UINT max_latency) override { - if (!waitable_ || max_latency == 0 || max_latency > max_waitable_frame_latency) - return DXGI_ERROR_INVALID_CALL; - const UINT prev = max_frame_latency_.exchange(max_latency, std::memory_order_relaxed); - if (max_latency > prev) - ReleaseSemaphore(waitable_, static_cast(max_latency - prev), nullptr); - return S_OK; - } - HRESULT STDMETHODCALLTYPE GetMaximumFrameLatency(UINT* n) override { - // Host-measured (Windows 11, RTX 5090 and WARP): null output returns DXGI_ERROR_INVALID_CALL on both - // waitable and non-waitable swapchains. - if (!n || !waitable_) return DXGI_ERROR_INVALID_CALL; - *n = max_frame_latency_.load(std::memory_order_relaxed); - return S_OK; - } - HANDLE STDMETHODCALLTYPE GetFrameLatencyWaitableObject() override { - if (!waitable_) return nullptr; - HANDLE dup = nullptr; - // Host-measured (Windows 11, RTX 5090 and WARP): the returned handle grants SYNCHRONIZE only, so callers can - // wait on it and CloseHandle it, while ReleaseSemaphore fails with ERROR_ACCESS_DENIED. - if (!DuplicateHandle(GetCurrentProcess(), waitable_, GetCurrentProcess(), &dup, SYNCHRONIZE, FALSE, 0)) - return nullptr; - return dup; - } - // A matrix transform belongs to composition swapchains only (CreateSwapChainForComposition, E_NOTIMPL here). - // Host DXGI answers DXGI_ERROR_INVALID_CALL to both methods on an HWND swapchain, with a matrix or with null - // (Windows 11, RTX 5060 Ti, driver 621.14); every swapchain the layer creates gets that answer. - HRESULT STDMETHODCALLTYPE SetMatrixTransform(const DXGI_MATRIX_3X2_F*) override { return DXGI_ERROR_INVALID_CALL; } - HRESULT STDMETHODCALLTYPE GetMatrixTransform(DXGI_MATRIX_3X2_F*) override { return DXGI_ERROR_INVALID_CALL; } - - // IDXGISwapChain3 - UINT STDMETHODCALLTYPE GetCurrentBackBufferIndex() override { return swapchain_.current_back_buffer_index(); } - HRESULT STDMETHODCALLTYPE CheckColorSpaceSupport(DXGI_COLOR_SPACE_TYPE, UINT* s) override { - if (s) *s = DXGI_SWAP_CHAIN_COLOR_SPACE_SUPPORT_FLAG_PRESENT; - return S_OK; - } - HRESULT STDMETHODCALLTYPE SetColorSpace1(DXGI_COLOR_SPACE_TYPE) override { return S_OK; } - HRESULT STDMETHODCALLTYPE ResizeBuffers1(UINT count, UINT w, UINT h, DXGI_FORMAT fmt, UINT flags, - const UINT* node_masks, IUnknown* const* present_queues) override { - return resize_buffers(count, w, h, fmt, flags, node_masks, present_queues); - } - -private: - // DXGI: a zero width or height takes the whole size from the window's client area (host-measured). - VkExtent2D size_or_client(UINT width, UINT height, VkExtent2D fallback) const { - if (width && height) return {width, height}; - RECT rc{}; - if (GetClientRect(hwnd_, &rc) && rc.right > 0 && rc.bottom > 0) - return {static_cast(rc.right), static_cast(rc.bottom)}; - return fallback; - } - - void register_buffers() { - const std::uint32_t count = swapchain_.image_count(); - D3D12_RESOURCE_DESC desc{}; - desc.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D; - desc.Width = swapchain_.extent().width; - desc.Height = swapchain_.extent().height; - desc.DepthOrArraySize = 1; - desc.MipLevels = 1; - desc.Format = vk_to_dxgi_format(swapchain_.format()); - desc.SampleDesc.Count = 1; - desc.Layout = D3D12_TEXTURE_LAYOUT_UNKNOWN; - desc.Flags = D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET; - const VkImageLayout initial_layout = - swapchain_.is_offscreen() ? VK_IMAGE_LAYOUT_GENERAL : VK_IMAGE_LAYOUT_PRESENT_SRC_KHR; - buffers_.reserve(count); - for (std::uint32_t i = 0; i < count; ++i) { - auto* bb = new BackBufferResource(desc); - context_.add_resource(bb->resource_id(), swapchain_.resource_binding(i), initial_layout); - buffers_.push_back(bb); - } - } - - void unregister_buffers() { - for (auto* bb : buffers_) { - context_.remove_resource(bb->resource_id()); - bb->Release(); - } - buffers_.clear(); - } - - std::atomic refs_{1}; - PrivateDataStore private_data_; - IDXGIFactory4* parent_ = nullptr; - IUnknown* device_ = nullptr; - leonida::VulkanContext& context_; - leonida::VulkanSwapchain swapchain_; - HWND hwnd_ = nullptr; - IDXGIOutput* restrict_to_output_ = nullptr; - UINT flags_ = 0; - // As created: the host reports the creation SwapEffect and BufferUsage (FLIP_SEQUENTIAL, SHADER_INPUT, or 0). - DXGI_SWAP_EFFECT swap_effect_ = DXGI_SWAP_EFFECT_FLIP_DISCARD; - DXGI_USAGE buffer_usage_ = DXGI_USAGE_RENDER_TARGET_OUTPUT; - HANDLE waitable_ = nullptr; - std::vector buffers_; - std::atomic present_count_{0}; - std::atomic statistics_disjoint_{true}; - std::atomic last_present_qpc_{0}; - std::atomic max_frame_latency_{2}; - DXGI_RGBA background_color_{0, 0, 0, 0}; - DXGI_MODE_ROTATION rotation_ = DXGI_MODE_ROTATION_IDENTITY; - VkExtent2D source_size_{0, 0}; -}; - -struct ReservationState { - std::atomic local{0}; - std::atomic non_local{0}; -}; - -// Video-memory reservations are scoped per physical adapter in the process (matching native DXGI, -// where separate IDXGIAdapter3 handles opened for the same LUID observe each other's reservations). -std::shared_ptr adapter_reservation_state(LUID luid, VkPhysicalDevice physical) { - static std::mutex mutex; - static std::map, std::shared_ptr> table; - const bool has_luid = (luid.LowPart != 0 || luid.HighPart != 0); - const auto key = - has_luid ? std::make_tuple(std::uint32_t(luid.LowPart), std::int32_t(luid.HighPart), std::uintptr_t(0)) - : std::make_tuple(std::uint32_t(0), std::int32_t(0), reinterpret_cast(physical)); - std::lock_guard lock(mutex); - auto& entry = table[key]; - if (!entry) entry = std::make_shared(); - return entry; -} - -// On discrete GPUs without Resizable BAR, Vulkan exposes a second smaller DEVICE_LOCAL heap for the -// CPU-visible BAR1 aperture (typically 256 MiB) that aliases the same physical VRAM as the primary heap. -// Pick the largest DEVICE_LOCAL heap so DedicatedVideoMemory and LOCAL budget/usage match Windows DXGI -// instead of double-counting BAR1. -std::uint32_t primary_device_local_heap(const VkPhysicalDeviceMemoryProperties& mem) { - std::uint32_t best = UINT32_MAX; - VkDeviceSize best_size = 0; - for (std::uint32_t i = 0; i < mem.memoryHeapCount; ++i) { - if ((mem.memoryHeaps[i].flags & VK_MEMORY_HEAP_DEVICE_LOCAL_BIT) == 0) continue; - if (best == UINT32_MAX || mem.memoryHeaps[i].size > best_size) { - best = i; - best_size = mem.memoryHeaps[i].size; - } - } - return best; -} - -// Snapshot of a Win32 monitor (or synthetic headless fallback) exposed through IDXGIOutput*. -// Defaults target a 1920x1080@60 Hz primary output; Win32 enumeration must also fill desktop_coords explicitly. -struct DisplayInfo { - HMONITOR monitor = nullptr; - WCHAR device_name[CCHDEVICENAME] = L"\\\\.\\DISPLAY1"; // matches DXGI_OUTPUT_DESC::DeviceName (32 WCHARs, NUL-terminated) - RECT desktop_coords{0, 0, 1920, 1080}; // Default desktop coordinates - DXGI_MODE_ROTATION rotation = DXGI_MODE_ROTATION_IDENTITY; - UINT current_width = 1920; - UINT current_height = 1080; - UINT current_refresh_hz = 60; - bool primary = true; -}; - -static_assert(sizeof(DisplayInfo{}.device_name) == sizeof(DXGI_OUTPUT_DESC{}.DeviceName)); - -// Maps Win32 DEVMODEW::dmDisplayOrientation (valid only when DM_DISPLAYORIENTATION is set in dmFields) -// to DXGI_MODE_ROTATION. -constexpr DXGI_MODE_ROTATION rotation_from_dm(const DEVMODEW& dm) noexcept { - if ((dm.dmFields & DM_DISPLAYORIENTATION) == 0) // dmDisplayOrientation is in a union and undefined without this flag - return DXGI_MODE_ROTATION_IDENTITY; - switch (dm.dmDisplayOrientation) { - case DMDO_90: return DXGI_MODE_ROTATION_ROTATE90; - case DMDO_180: return DXGI_MODE_ROTATION_ROTATE180; - case DMDO_270: return DXGI_MODE_ROTATION_ROTATE270; - default: return DXGI_MODE_ROTATION_IDENTITY; // covers DMDO_DEFAULT and unexpected values - } -} - -BOOL CALLBACK collect_monitor_cb(HMONITOR hmon, HDC, LPRECT, LPARAM lparam) { - auto* displays = reinterpret_cast*>(lparam); - MONITORINFOEXW mi{}; - mi.cbSize = sizeof(mi); - if (!GetMonitorInfoW(hmon, &mi)) return TRUE; - - DisplayInfo info{}; - info.monitor = hmon; - info.desktop_coords = mi.rcMonitor; - info.primary = (mi.dwFlags & MONITORINFOF_PRIMARY) != 0; - // szDevice is CCHDEVICENAME (32) WCHARs; _TRUNCATE guarantees a trailing NUL even on unexpected input. - wcsncpy_s(info.device_name, mi.szDevice, _TRUNCATE); - - DEVMODEW dm{}; - dm.dmSize = sizeof(dm); - if (EnumDisplaySettingsW(mi.szDevice, ENUM_CURRENT_SETTINGS, &dm)) { - if ((dm.dmFields & (DM_PELSWIDTH | DM_PELSHEIGHT)) == (DM_PELSWIDTH | DM_PELSHEIGHT) && - dm.dmPelsWidth > 0 && dm.dmPelsHeight > 0) { - info.current_width = dm.dmPelsWidth; - info.current_height = dm.dmPelsHeight; - } - // Win32 drivers may report 0 or 1 as "hardware default" rather than an actual Hz rate. - if ((dm.dmFields & DM_DISPLAYFREQUENCY) != 0 && dm.dmDisplayFrequency > 1) - info.current_refresh_hz = dm.dmDisplayFrequency; - info.rotation = rotation_from_dm(dm); - } - - displays->push_back(info); - return TRUE; -} - -// Enumerates attached Win32 displays with the primary monitor at index 0 (matching DXGI's EnumOutputs contract), -// falling back to a single 1920x1080@60 output in headless environments with no desktop monitors. -std::vector enumerate_displays() { - std::vector displays; - EnumDisplayMonitors(nullptr, nullptr, &collect_monitor_cb, reinterpret_cast(&displays)); - if (displays.empty()) { - displays.push_back(DisplayInfo{}); - return displays; - } - // Keep enumeration order among secondary monitors while ensuring primary is output 0. - for (std::size_t i = 1; i < displays.size(); ++i) { - if (displays[i].primary) { - DisplayInfo primary_info = displays[i]; - for (std::size_t j = i; j > 0; --j) displays[j] = displays[j - 1]; - displays[0] = primary_info; - break; - } - } - return displays; -} - -bool is_supported_display_format(DXGI_FORMAT fmt) noexcept { - switch (fmt) { - case DXGI_FORMAT_R8G8B8A8_UNORM: - case DXGI_FORMAT_R8G8B8A8_UNORM_SRGB: - case DXGI_FORMAT_B8G8R8A8_UNORM: - case DXGI_FORMAT_B8G8R8A8_UNORM_SRGB: - case DXGI_FORMAT_R10G10B10A2_UNORM: - case DXGI_FORMAT_R16G16B16A16_FLOAT: - return true; - default: - return false; - } -} - -std::vector collect_modes(const DisplayInfo& info, DXGI_FORMAT fmt) { - std::vector modes; - if (!is_supported_display_format(fmt)) return modes; - - std::set> seen; - auto push_mode = [&](UINT w, UINT h, UINT hz) { - if (!w || !h || !hz) return; - if (!seen.emplace(w, h, hz).second) return; - DXGI_MODE_DESC m{}; - m.Width = w; - m.Height = h; - m.RefreshRate = {hz, 1}; - m.Format = fmt; - m.ScanlineOrdering = DXGI_MODE_SCANLINE_ORDER_PROGRESSIVE; - m.Scaling = DXGI_MODE_SCALING_UNSPECIFIED; - modes.push_back(m); - }; - - if (info.monitor) { - // Bound the driver enumeration loop defensively in case a faulty driver never stops returning modes. - for (DWORD i = 0; i < 4096; ++i) { - DEVMODEW dm{}; - dm.dmSize = sizeof(dm); - if (!EnumDisplaySettingsW(info.device_name, i, &dm)) break; - if ((dm.dmFields & (DM_PELSWIDTH | DM_PELSHEIGHT)) != (DM_PELSWIDTH | DM_PELSHEIGHT) || - dm.dmPelsWidth == 0 || dm.dmPelsHeight == 0) - continue; - const UINT hz = - ((dm.dmFields & DM_DISPLAYFREQUENCY) != 0 && dm.dmDisplayFrequency > 1) ? dm.dmDisplayFrequency - : info.current_refresh_hz; - push_mode(dm.dmPelsWidth, dm.dmPelsHeight, hz); - } - } - push_mode(info.current_width, info.current_height, info.current_refresh_hz); - - std::sort(modes.begin(), modes.end(), [](const DXGI_MODE_DESC& a, const DXGI_MODE_DESC& b) { - return std::tie(a.Width, a.Height, a.RefreshRate.Numerator) < - std::tie(b.Width, b.Height, b.RefreshRate.Numerator); - }); - return modes; -} - -constexpr DXGI_MODE_DESC1 to_mode_desc1(const DXGI_MODE_DESC& m) noexcept { - return {m.Width, m.Height, m.RefreshRate, m.Format, m.ScanlineOrdering, m.Scaling, FALSE}; -} - -constexpr DXGI_MODE_DESC from_mode_desc1(const DXGI_MODE_DESC1& m) noexcept { - return {m.Width, m.Height, m.RefreshRate, m.Format, m.ScanlineOrdering, m.Scaling}; -} - -template -HRESULT fill_mode_list(const DisplayInfo& info, DXGI_FORMAT fmt, UINT* num_modes, DescT* out, ConvertFn convert) { - if (!num_modes) return DXGI_ERROR_INVALID_CALL; - const std::vector modes = collect_modes(info, fmt); - const UINT total = static_cast(modes.size()); - if (!out) { - *num_modes = total; - return S_OK; - } - const UINT to_copy = std::min(*num_modes, total); - for (UINT i = 0; i < to_copy; ++i) out[i] = convert(modes[i]); - // Host DXGI writes the number of copied entries back into *pNumModes when returning MORE_DATA. - *num_modes = to_copy; - return (to_copy < total) ? DXGI_ERROR_MORE_DATA : S_OK; -} - -HRESULT find_closest_mode(const DisplayInfo& info, const DXGI_MODE_DESC& req, IUnknown* concerned_device, - DXGI_MODE_DESC& out) { - out = {}; - if (req.Format == DXGI_FORMAT_UNKNOWN && !concerned_device) return DXGI_ERROR_INVALID_CALL; - const DXGI_FORMAT target_fmt = (req.Format == DXGI_FORMAT_UNKNOWN) ? DXGI_FORMAT_B8G8R8A8_UNORM : req.Format; - const std::vector modes = collect_modes(info, target_fmt); - if (modes.empty()) return DXGI_ERROR_NOT_FOUND; - - const UINT target_w = req.Width ? req.Width : info.current_width; - const UINT target_h = req.Height ? req.Height : info.current_height; - const bool has_refresh = (req.RefreshRate.Numerator > 0 && req.RefreshRate.Denominator > 0); - const std::uint64_t target_mhz = - has_refresh ? (std::uint64_t(req.RefreshRate.Numerator) * 1000ull) / req.RefreshRate.Denominator - : std::uint64_t(info.current_refresh_hz) * 1000ull; - - auto abs_diff = [](std::uint64_t a, std::uint64_t b) -> std::uint64_t { return a > b ? (a - b) : (b - a); }; - auto score = [&](const DXGI_MODE_DESC& m) { - const std::uint64_t area_diff = abs_diff(std::uint64_t(m.Width) * m.Height, std::uint64_t(target_w) * target_h); - const std::uint64_t dim_diff = abs_diff(m.Width, target_w) + abs_diff(m.Height, target_h); - const std::uint64_t m_mhz = - m.RefreshRate.Denominator ? (std::uint64_t(m.RefreshRate.Numerator) * 1000ull) / m.RefreshRate.Denominator : 0; - const std::uint64_t hz_diff = abs_diff(m_mhz, target_mhz); - return std::make_tuple(dim_diff, area_diff, hz_diff); - }; - - const DXGI_MODE_DESC* best = &modes[0]; - auto best_score = score(*best); - for (std::size_t i = 1; i < modes.size(); ++i) { - const auto s = score(modes[i]); - if (s < best_score) { - best = &modes[i]; - best_score = s; - } - } - out = *best; - return S_OK; -} - -void wait_for_vblank() { - using DwmFlushFn = HRESULT(WINAPI*)(); - static const DwmFlushFn dwm_flush = []() -> DwmFlushFn { - // Resolve dynamically so dxgi_com.cpp needs no extra dwmapi.lib link entry in CMakeLists.txt. - const HMODULE mod = LoadLibraryW(L"dwmapi.dll"); - return mod ? reinterpret_cast(GetProcAddress(mod, "DwmFlush")) : nullptr; - }(); - if (dwm_flush && SUCCEEDED(dwm_flush())) return; - Sleep(16); -} - -// Win32/DXGI-backed IDXGIOutput6 reporting desktop monitor descriptors and display modes. -class Output final : public IDXGIOutput6 { -public: - Output(IDXGIAdapter* parent, DisplayInfo info) : parent_(parent), info_(info) { - if (parent_) parent_->AddRef(); - } - - ~Output() { - if (parent_) parent_->Release(); - } - - // IUnknown - ULONG STDMETHODCALLTYPE AddRef() override { return ++refs_; } - ULONG STDMETHODCALLTYPE Release() override { - const ULONG left = --refs_; - if (!left) delete this; - return left; - } - HRESULT STDMETHODCALLTYPE QueryInterface(REFIID riid, void** out) override { - if (!out) return E_POINTER; - *out = nullptr; - if (riid == __uuidof(IUnknown) || riid == __uuidof(IDXGIObject) || riid == __uuidof(IDXGIOutput) || - riid == __uuidof(IDXGIOutput1) || riid == __uuidof(IDXGIOutput2) || riid == __uuidof(IDXGIOutput3) || - riid == __uuidof(IDXGIOutput4) || riid == __uuidof(IDXGIOutput5) || riid == __uuidof(IDXGIOutput6)) { - *out = static_cast(this); - AddRef(); - return S_OK; - } - return E_NOINTERFACE; - } - - // IDXGIObject - HRESULT STDMETHODCALLTYPE SetPrivateData(REFGUID, UINT, const void*) override { return S_OK; } - HRESULT STDMETHODCALLTYPE SetPrivateDataInterface(REFGUID, const IUnknown*) override { return S_OK; } - HRESULT STDMETHODCALLTYPE GetPrivateData(REFGUID, UINT*, void*) override { return DXGI_ERROR_NOT_FOUND; } - HRESULT STDMETHODCALLTYPE GetParent(REFIID riid, void** out) override { - if (!out) return E_POINTER; - *out = nullptr; - if (!parent_) return E_NOINTERFACE; - return parent_->QueryInterface(riid, out); - } - - // IDXGIOutput - HRESULT STDMETHODCALLTYPE GetDesc(DXGI_OUTPUT_DESC* desc) override { - if (!desc) return E_INVALIDARG; - fill_base_desc(*desc); - return S_OK; - } - HRESULT STDMETHODCALLTYPE GetDisplayModeList(DXGI_FORMAT fmt, UINT, UINT* num_modes, DXGI_MODE_DESC* desc) override { - return fill_mode_list(info_, fmt, num_modes, desc, [](const DXGI_MODE_DESC& m) { return m; }); - } - HRESULT STDMETHODCALLTYPE FindClosestMatchingMode(const DXGI_MODE_DESC* mode_to_match, DXGI_MODE_DESC* closest, - IUnknown* concerned_device) override { - if (!mode_to_match || !closest) return DXGI_ERROR_INVALID_CALL; - return find_closest_mode(info_, *mode_to_match, concerned_device, *closest); - } - HRESULT STDMETHODCALLTYPE WaitForVBlank() override { - wait_for_vblank(); - return S_OK; - } - HRESULT STDMETHODCALLTYPE TakeOwnership(IUnknown* device, BOOL) override { - return device ? S_OK : E_INVALIDARG; - } - void STDMETHODCALLTYPE ReleaseOwnership() override {} - HRESULT STDMETHODCALLTYPE GetGammaControlCapabilities(DXGI_GAMMA_CONTROL_CAPABILITIES* caps) override { - if (caps) std::memset(caps, 0, sizeof(*caps)); - return DXGI_ERROR_INVALID_CALL; - } - HRESULT STDMETHODCALLTYPE SetGammaControl(const DXGI_GAMMA_CONTROL*) override { return DXGI_ERROR_INVALID_CALL; } - HRESULT STDMETHODCALLTYPE GetGammaControl(DXGI_GAMMA_CONTROL*) override { return DXGI_ERROR_INVALID_CALL; } - HRESULT STDMETHODCALLTYPE SetDisplaySurface(IDXGISurface*) override { return S_OK; } - HRESULT STDMETHODCALLTYPE GetDisplaySurfaceData(IDXGISurface*) override { return DXGI_ERROR_INVALID_CALL; } - HRESULT STDMETHODCALLTYPE GetFrameStatistics(DXGI_FRAME_STATISTICS* stats) override { - if (!stats) return DXGI_ERROR_INVALID_CALL; - std::memset(stats, 0, sizeof(*stats)); - LARGE_INTEGER qpc{}; - if (QueryPerformanceCounter(&qpc)) stats->SyncQPCTime = qpc; - return S_OK; - } - - // IDXGIOutput1 - HRESULT STDMETHODCALLTYPE GetDisplayModeList1(DXGI_FORMAT fmt, UINT, UINT* num_modes, - DXGI_MODE_DESC1* desc) override { - return fill_mode_list(info_, fmt, num_modes, desc, to_mode_desc1); - } - HRESULT STDMETHODCALLTYPE FindClosestMatchingMode1(const DXGI_MODE_DESC1* mode_to_match, DXGI_MODE_DESC1* closest, - IUnknown* concerned_device) override { - if (!mode_to_match || !closest) return DXGI_ERROR_INVALID_CALL; - DXGI_MODE_DESC best{}; - const HRESULT hr = find_closest_mode(info_, from_mode_desc1(*mode_to_match), concerned_device, best); - *closest = SUCCEEDED(hr) ? to_mode_desc1(best) : DXGI_MODE_DESC1{}; - return hr; - } - HRESULT STDMETHODCALLTYPE GetDisplaySurfaceData1(IDXGIResource*) override { return DXGI_ERROR_INVALID_CALL; } - HRESULT STDMETHODCALLTYPE DuplicateOutput(IUnknown* device, IDXGIOutputDuplication** dup) override { - if (dup) *dup = nullptr; - if (!device || !dup) return E_INVALIDARG; - return DXGI_ERROR_UNSUPPORTED; - } - - // IDXGIOutput2 - BOOL STDMETHODCALLTYPE SupportsOverlays() override { return FALSE; } - - // IDXGIOutput3 - HRESULT STDMETHODCALLTYPE CheckOverlaySupport(DXGI_FORMAT, IUnknown* device, UINT* flags) override { - if (flags) *flags = 0; - return (device && flags) ? S_OK : E_INVALIDARG; - } - - // IDXGIOutput4 - HRESULT STDMETHODCALLTYPE CheckOverlayColorSpaceSupport(DXGI_FORMAT, DXGI_COLOR_SPACE_TYPE, IUnknown* device, - UINT* flags) override { - if (flags) *flags = 0; - return (device && flags) ? S_OK : E_INVALIDARG; - } - - // IDXGIOutput5 - HRESULT STDMETHODCALLTYPE DuplicateOutput1(IUnknown* device, UINT, UINT, const DXGI_FORMAT*, - IDXGIOutputDuplication** dup) override { - if (dup) *dup = nullptr; - if (!device || !dup) return E_INVALIDARG; - return DXGI_ERROR_UNSUPPORTED; - } - - // IDXGIOutput6 - HRESULT STDMETHODCALLTYPE GetDesc1(DXGI_OUTPUT_DESC1* desc) override { - if (!desc) return E_INVALIDARG; - std::memset(desc, 0, sizeof(*desc)); - DXGI_OUTPUT_DESC base{}; - fill_base_desc(base); - std::memcpy(desc->DeviceName, base.DeviceName, sizeof(desc->DeviceName)); - desc->DesktopCoordinates = base.DesktopCoordinates; - desc->AttachedToDesktop = base.AttachedToDesktop; - desc->Rotation = base.Rotation; - desc->Monitor = base.Monitor; - desc->BitsPerColor = 8; - desc->ColorSpace = DXGI_COLOR_SPACE_RGB_FULL_G22_NONE_P709; - // Standard sRGB / ITU-R BT.709 primaries and baseline SDR luminance. - desc->RedPrimary[0] = 0.64f; - desc->RedPrimary[1] = 0.33f; - desc->GreenPrimary[0] = 0.30f; - desc->GreenPrimary[1] = 0.60f; - desc->BluePrimary[0] = 0.15f; - desc->BluePrimary[1] = 0.06f; - desc->WhitePoint[0] = 0.3127f; - desc->WhitePoint[1] = 0.3290f; - desc->MinLuminance = 0.0f; - desc->MaxLuminance = 80.0f; - desc->MaxFullFrameLuminance = 80.0f; - return S_OK; - } - HRESULT STDMETHODCALLTYPE CheckHardwareCompositionSupport(UINT* flags) override { - if (!flags) return E_INVALIDARG; - *flags = 0; - return S_OK; - } - -private: - void fill_base_desc(DXGI_OUTPUT_DESC& desc) const noexcept { - std::memset(&desc, 0, sizeof(desc)); - std::memcpy(desc.DeviceName, info_.device_name, sizeof(desc.DeviceName)); - desc.DesktopCoordinates = info_.desktop_coords; - desc.AttachedToDesktop = TRUE; - desc.Rotation = info_.rotation; - desc.Monitor = info_.monitor; - } - - std::atomic refs_{1}; - IDXGIAdapter* parent_ = nullptr; - DisplayInfo info_{}; -}; - - -// Vulkan-backed IDXGIAdapter4 reporting the physical device's name, IDs, LUID (matching -// ID3D12Device::GetAdapterLuid), memory heap sizes, and video memory budget info. - -// The adapter's user-mode driver version, as DXGI's CheckInterfaceSupport(IDXGIDevice) reports it: what -// D3DKMTQueryAdapterInfo(KMTQAITYPE_UMD_DRIVER_VERSION) gives for the adapter's LUID (measured equal to host DXGI on -// an RTX 5060 Ti, 0x0020000000100842 for driver 621.14, and on WARP). gdi32's entry points are looked up at run -// time and the host dxgi.dll isn't used; 0 when they are missing (Wine) or the query fails. -LARGE_INTEGER umd_driver_version(LUID luid) { - LARGE_INTEGER version{}; - if (!luid.LowPart && !luid.HighPart) return version; - HMODULE gdi32 = GetModuleHandleW(L"gdi32.dll"); - if (!gdi32) gdi32 = LoadLibraryW(L"gdi32.dll"); - if (!gdi32) return version; - const auto open = reinterpret_cast( - GetProcAddress(gdi32, "D3DKMTOpenAdapterFromLuid")); - const auto query = reinterpret_cast( - GetProcAddress(gdi32, "D3DKMTQueryAdapterInfo")); - const auto close = reinterpret_cast(GetProcAddress(gdi32, "D3DKMTCloseAdapter")); - if (!open || !query || !close) return version; - D3DKMT_OPENADAPTERFROMLUID adapter{}; - adapter.AdapterLuid = luid; - if (open(&adapter) != 0) return version; - D3DKMT_UMD_DRIVER_VERSION umd{}; - D3DKMT_QUERYADAPTERINFO info{}; - info.hAdapter = adapter.hAdapter; - info.Type = KMTQAITYPE_UMD_DRIVER_VERSION; - info.pPrivateDriverData = &umd; - info.PrivateDriverDataSize = sizeof(umd); - if (query(&info) == 0) version = umd.DriverVersion; - D3DKMT_CLOSEADAPTER closing{adapter.hAdapter}; - close(&closing); - return version; -} - -class Adapter final : public IDXGIAdapter4 { -public: - Adapter(IDXGIFactory4* parent, PFN_vkGetInstanceProcAddr gipa, VkInstance instance, VkPhysicalDevice physical) - : parent_(parent), gipa_(gipa), instance_(instance), physical_(physical) { - if (parent_) parent_->AddRef(); - populate_desc(); - umd_version_ = umd_driver_version(desc_.AdapterLuid); - reservations_ = adapter_reservation_state(desc_.AdapterLuid, physical_); - } - - ~Adapter() { - if (parent_) parent_->Release(); - } - - LUID luid() const { return desc_.AdapterLuid; } - - // IUnknown - ULONG STDMETHODCALLTYPE AddRef() override { return ++refs_; } - ULONG STDMETHODCALLTYPE Release() override { - const ULONG left = --refs_; - if (!left) delete this; - return left; - } - HRESULT STDMETHODCALLTYPE QueryInterface(REFIID riid, void** out) override { - if (!out) return E_POINTER; - *out = nullptr; - if (riid == __uuidof(IUnknown) || riid == __uuidof(IDXGIObject) || riid == __uuidof(IDXGIAdapter) || - riid == __uuidof(IDXGIAdapter1) || riid == __uuidof(IDXGIAdapter2) || riid == __uuidof(IDXGIAdapter3) || - riid == __uuidof(IDXGIAdapter4)) { - *out = static_cast(this); - AddRef(); - return S_OK; - } - return E_NOINTERFACE; - } - - // IDXGIObject - HRESULT STDMETHODCALLTYPE SetPrivateData(REFGUID guid, UINT size, const void* data) override { - return private_data_.set(guid, size, data); - } - HRESULT STDMETHODCALLTYPE SetPrivateDataInterface(REFGUID guid, const IUnknown* object) override { - return private_data_.set_interface(guid, object); - } - HRESULT STDMETHODCALLTYPE GetPrivateData(REFGUID guid, UINT* size, void* data) override { - return private_data_.get(guid, size, data); - } - HRESULT STDMETHODCALLTYPE GetParent(REFIID riid, void** out) override { - if (!out) return E_POINTER; - *out = nullptr; - if (!parent_) return E_NOINTERFACE; - return parent_->QueryInterface(riid, out); - } - - // IDXGIAdapter - HRESULT STDMETHODCALLTYPE EnumOutputs(UINT index, IDXGIOutput** out) override { - if (!out) return E_INVALIDARG; - *out = nullptr; - const std::vector displays = enumerate_displays(); - if (index >= displays.size()) return DXGI_ERROR_NOT_FOUND; - *out = new Output(static_cast(this), displays[index]); - return S_OK; - } - HRESULT STDMETHODCALLTYPE GetDesc(DXGI_ADAPTER_DESC* desc) override { - if (!desc) return E_INVALIDARG; - std::memcpy(desc->Description, desc_.Description, sizeof(desc->Description)); - desc->VendorId = desc_.VendorId; - desc->DeviceId = desc_.DeviceId; - desc->SubSysId = desc_.SubSysId; - desc->Revision = desc_.Revision; - desc->DedicatedVideoMemory = desc_.DedicatedVideoMemory; - desc->DedicatedSystemMemory = desc_.DedicatedSystemMemory; - desc->SharedSystemMemory = desc_.SharedSystemMemory; - desc->AdapterLuid = desc_.AdapterLuid; - return S_OK; - } - HRESULT STDMETHODCALLTYPE CheckInterfaceSupport(REFGUID interface_name, LARGE_INTEGER* umd_version) override { - if (interface_name == __uuidof(IDXGIDevice)) { - if (umd_version) *umd_version = umd_version_; - return S_OK; - } - return DXGI_ERROR_UNSUPPORTED; - } - - // IDXGIAdapter1 - HRESULT STDMETHODCALLTYPE GetDesc1(DXGI_ADAPTER_DESC1* desc) override { - if (!desc) return E_INVALIDARG; - std::memcpy(desc->Description, desc_.Description, sizeof(desc->Description)); - desc->VendorId = desc_.VendorId; - desc->DeviceId = desc_.DeviceId; - desc->SubSysId = desc_.SubSysId; - desc->Revision = desc_.Revision; - desc->DedicatedVideoMemory = desc_.DedicatedVideoMemory; - desc->DedicatedSystemMemory = desc_.DedicatedSystemMemory; - desc->SharedSystemMemory = desc_.SharedSystemMemory; - desc->AdapterLuid = desc_.AdapterLuid; - desc->Flags = desc_.Flags; - return S_OK; - } - - // IDXGIAdapter2 - HRESULT STDMETHODCALLTYPE GetDesc2(DXGI_ADAPTER_DESC2* desc) override { - if (!desc) return E_INVALIDARG; - *desc = desc_; - return S_OK; - } - - // IDXGIAdapter3 - HRESULT STDMETHODCALLTYPE RegisterHardwareContentProtectionTeardownStatusEvent(HANDLE, DWORD* cookie) override { - if (cookie) *cookie = 0; - return E_NOTIMPL; - } - void STDMETHODCALLTYPE UnregisterHardwareContentProtectionTeardownStatus(DWORD) override {} - HRESULT STDMETHODCALLTYPE QueryVideoMemoryInfo(UINT node_index, DXGI_MEMORY_SEGMENT_GROUP group, - DXGI_QUERY_VIDEO_MEMORY_INFO* info) override { - if (node_index != 0 || !info) return E_INVALIDARG; - if (group != DXGI_MEMORY_SEGMENT_GROUP_LOCAL && group != DXGI_MEMORY_SEGMENT_GROUP_NON_LOCAL) - return E_INVALIDARG; - std::memset(info, 0, sizeof(*info)); - const bool want_local = (group == DXGI_MEMORY_SEGMENT_GROUP_LOCAL); - if (has_memory_budget_ && gipa_ && instance_ && physical_) { - if (const auto get_mem2 = reinterpret_cast( - gipa_(instance_, "vkGetPhysicalDeviceMemoryProperties2"))) { - VkPhysicalDeviceMemoryBudgetPropertiesEXT budget{ - VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MEMORY_BUDGET_PROPERTIES_EXT}; - VkPhysicalDeviceMemoryProperties2 mem2{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MEMORY_PROPERTIES_2, &budget}; - get_mem2(physical_, &mem2); - const auto& mem = mem2.memoryProperties; - if (want_local) { - const std::uint32_t local_heap = primary_device_local_heap(mem); - if (local_heap != UINT32_MAX) { - info->Budget = budget.heapBudget[local_heap]; - info->CurrentUsage = budget.heapUsage[local_heap]; - } - } else { - for (std::uint32_t i = 0; i < mem.memoryHeapCount; ++i) { - if ((mem.memoryHeaps[i].flags & VK_MEMORY_HEAP_DEVICE_LOCAL_BIT) == 0) { - info->Budget += budget.heapBudget[i]; - info->CurrentUsage += budget.heapUsage[i]; - } - } - } - } - } - if (info->Budget == 0) { - info->Budget = want_local ? desc_.DedicatedVideoMemory : desc_.SharedSystemMemory; - } - info->AvailableForReservation = info->Budget / 2; - info->CurrentReservation = want_local ? reservations_->local.load(std::memory_order_relaxed) - : reservations_->non_local.load(std::memory_order_relaxed); - return S_OK; - } - HRESULT STDMETHODCALLTYPE SetVideoMemoryReservation(UINT node_index, DXGI_MEMORY_SEGMENT_GROUP group, - UINT64 reservation) override { - if (node_index != 0) return E_INVALIDARG; - if (group == DXGI_MEMORY_SEGMENT_GROUP_LOCAL) { - reservations_->local.store(reservation, std::memory_order_relaxed); - return S_OK; - } - if (group == DXGI_MEMORY_SEGMENT_GROUP_NON_LOCAL) { - reservations_->non_local.store(reservation, std::memory_order_relaxed); - return S_OK; - } - return E_INVALIDARG; - } - // Microsoft documents only "an HRESULT success or error code" and a cookie for - // UnregisterVideoMemoryBudgetChangeNotification. The budget here is recomputed on every QueryVideoMemoryInfo and - // never changes by itself, so the event is registered and never signalled. - HRESULT STDMETHODCALLTYPE RegisterVideoMemoryBudgetChangeNotificationEvent(HANDLE event, DWORD* cookie) override { - if (!event || !cookie) return E_INVALIDARG; - *cookie = next_budget_cookie_.fetch_add(1, std::memory_order_relaxed); - return S_OK; - } - void STDMETHODCALLTYPE UnregisterVideoMemoryBudgetChangeNotification(DWORD) override {} - - // IDXGIAdapter4 (host DXGI answers it since Windows 10 1803). DXGI_ADAPTER_FLAG3_SOFTWARE is the same bit as - // DXGI_ADAPTER_FLAG_SOFTWARE; a null description is E_INVALIDARG, as on the host. - HRESULT STDMETHODCALLTYPE GetDesc3(DXGI_ADAPTER_DESC3* desc) override { - if (!desc) return E_INVALIDARG; - std::memset(desc, 0, sizeof(*desc)); - std::memcpy(desc->Description, desc_.Description, sizeof(desc->Description)); - desc->VendorId = desc_.VendorId; - desc->DeviceId = desc_.DeviceId; - desc->SubSysId = desc_.SubSysId; - desc->Revision = desc_.Revision; - desc->DedicatedVideoMemory = desc_.DedicatedVideoMemory; - desc->DedicatedSystemMemory = desc_.DedicatedSystemMemory; - desc->SharedSystemMemory = desc_.SharedSystemMemory; - desc->AdapterLuid = desc_.AdapterLuid; - desc->Flags = static_cast(desc_.Flags); - desc->GraphicsPreemptionGranularity = desc_.GraphicsPreemptionGranularity; - desc->ComputePreemptionGranularity = desc_.ComputePreemptionGranularity; - return S_OK; - } - -private: - void populate_desc() { - std::memset(&desc_, 0, sizeof(desc_)); - desc_.GraphicsPreemptionGranularity = DXGI_GRAPHICS_PREEMPTION_DMA_BUFFER_BOUNDARY; - desc_.ComputePreemptionGranularity = DXGI_COMPUTE_PREEMPTION_DMA_BUFFER_BOUNDARY; - if (!gipa_ || !instance_ || !physical_) return; - - VkPhysicalDeviceProperties props{}; - bool got_props = false; - if (const auto get_props2 = reinterpret_cast( - gipa_(instance_, "vkGetPhysicalDeviceProperties2"))) { - VkPhysicalDeviceIDProperties id{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_ID_PROPERTIES}; - VkPhysicalDeviceProperties2 props2{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROPERTIES_2, &id}; - get_props2(physical_, &props2); - props = props2.properties; - got_props = true; - static_assert(sizeof(LUID) == VK_LUID_SIZE); - if (id.deviceLUIDValid) std::memcpy(&desc_.AdapterLuid, id.deviceLUID, sizeof(LUID)); - } else if (const auto get_props = reinterpret_cast( - gipa_(instance_, "vkGetPhysicalDeviceProperties"))) { - get_props(physical_, &props); - got_props = true; - } - if (got_props) { - MultiByteToWideChar(CP_UTF8, 0, props.deviceName, -1, desc_.Description, - static_cast(std::size(desc_.Description) - 1)); - desc_.Description[std::size(desc_.Description) - 1] = L'\0'; - desc_.VendorId = props.vendorID; - desc_.DeviceId = props.deviceID; - desc_.Revision = props.driverVersion; - if (props.deviceType == VK_PHYSICAL_DEVICE_TYPE_CPU) desc_.Flags = DXGI_ADAPTER_FLAG_SOFTWARE; - } - - if (const auto get_mem = reinterpret_cast( - gipa_(instance_, "vkGetPhysicalDeviceMemoryProperties"))) { - VkPhysicalDeviceMemoryProperties mem{}; - get_mem(physical_, &mem); - const std::uint32_t local_heap = primary_device_local_heap(mem); - const std::uint64_t dedicated = (local_heap != UINT32_MAX) ? mem.memoryHeaps[local_heap].size : 0; - std::uint64_t shared = 0; - for (std::uint32_t i = 0; i < mem.memoryHeapCount; ++i) { - if ((mem.memoryHeaps[i].flags & VK_MEMORY_HEAP_DEVICE_LOCAL_BIT) == 0) - shared += mem.memoryHeaps[i].size; - } - desc_.DedicatedVideoMemory = static_cast(dedicated); - desc_.SharedSystemMemory = static_cast(shared); - } - - if (const auto enum_exts = reinterpret_cast( - gipa_(instance_, "vkEnumerateDeviceExtensionProperties"))) { - std::uint32_t count = 0; - if (enum_exts(physical_, nullptr, &count, nullptr) == VK_SUCCESS && count > 0) { - std::vector exts(count); - if (enum_exts(physical_, nullptr, &count, exts.data()) == VK_SUCCESS) { - for (const auto& e : exts) { - if (std::strcmp(e.extensionName, VK_EXT_MEMORY_BUDGET_EXTENSION_NAME) == 0) { - has_memory_budget_ = true; - break; - } - } - } - } - } - } - - std::atomic next_budget_cookie_{1}; - std::atomic refs_{1}; - PrivateDataStore private_data_; - IDXGIFactory4* parent_ = nullptr; - PFN_vkGetInstanceProcAddr gipa_ = nullptr; - VkInstance instance_ = VK_NULL_HANDLE; - VkPhysicalDevice physical_ = VK_NULL_HANDLE; - DXGI_ADAPTER_DESC2 desc_{}; - LARGE_INTEGER umd_version_{}; // CheckInterfaceSupport(IDXGIDevice): the adapter's user-mode driver version - bool has_memory_budget_ = false; - std::shared_ptr reservations_; -}; - -class Factory final : public IDXGIFactory7 { -public: - Factory(leonida::VulkanContext& context, PFN_vkGetInstanceProcAddr gipa, VkInstance instance, - VkPhysicalDevice physical, PFN_vkGetDeviceProcAddr gdpa, VkQueue queue, std::uint32_t queue_family) - : context_(context), gipa_(gipa), instance_(instance), physical_(physical), gdpa_(gdpa), - queue_(queue), queue_family_(queue_family) {} - - ULONG STDMETHODCALLTYPE AddRef() override { return ++refs_; } - ULONG STDMETHODCALLTYPE Release() override { - const ULONG left = --refs_; - if (!left) delete this; - return left; - } - HRESULT STDMETHODCALLTYPE QueryInterface(REFIID riid, void** out) override { - if (!out) return E_POINTER; - *out = nullptr; - if (riid == __uuidof(IUnknown) || riid == __uuidof(IDXGIObject) || riid == __uuidof(IDXGIFactory) || - riid == __uuidof(IDXGIFactory1) || riid == __uuidof(IDXGIFactory2) || - riid == __uuidof(IDXGIFactory3) || riid == __uuidof(IDXGIFactory4) || - riid == __uuidof(IDXGIFactory5) || riid == __uuidof(IDXGIFactory6) || - riid == __uuidof(IDXGIFactory7)) { - *out = static_cast(this); - AddRef(); - return S_OK; - } - return E_NOINTERFACE; - } - - // IDXGIObject - HRESULT STDMETHODCALLTYPE SetPrivateData(REFGUID guid, UINT size, const void* data) override { - return private_data_.set(guid, size, data); - } - HRESULT STDMETHODCALLTYPE SetPrivateDataInterface(REFGUID guid, const IUnknown* object) override { - return private_data_.set_interface(guid, object); - } - HRESULT STDMETHODCALLTYPE GetPrivateData(REFGUID guid, UINT* size, void* data) override { - return private_data_.get(guid, size, data); - } - HRESULT STDMETHODCALLTYPE GetParent(REFIID, void** out) override { - if (!out) return E_POINTER; - *out = nullptr; - return E_NOINTERFACE; - } - - // IDXGIFactory - HRESULT STDMETHODCALLTYPE EnumAdapters(UINT index, IDXGIAdapter** out) override { - if (!out) return E_POINTER; - *out = nullptr; - if (index != 0) return DXGI_ERROR_NOT_FOUND; - auto* adapter = new Adapter(this, gipa_, instance_, physical_); - *out = static_cast(adapter); - return S_OK; - } - HRESULT STDMETHODCALLTYPE MakeWindowAssociation(HWND hwnd, UINT flags) override { - // Host-measured: only the three documented bits are accepted; any other bit is DXGI_ERROR_INVALID_CALL. - constexpr UINT known = DXGI_MWA_NO_WINDOW_CHANGES | DXGI_MWA_NO_ALT_ENTER | DXGI_MWA_NO_PRINT_SCREEN; - if (flags & ~known) return DXGI_ERROR_INVALID_CALL; - assoc_hwnd_ = hwnd; - return S_OK; - } - HRESULT STDMETHODCALLTYPE GetWindowAssociation(HWND* hwnd) override { - if (!hwnd) return E_INVALIDARG; - *hwnd = assoc_hwnd_; - return S_OK; - } - HRESULT STDMETHODCALLTYPE CreateSwapChain(IUnknown* device, DXGI_SWAP_CHAIN_DESC* desc, IDXGISwapChain** out) override { - if (!out || !device || !desc) return DXGI_ERROR_INVALID_CALL; - *out = nullptr; - DXGI_SWAP_CHAIN_DESC1 desc1{}; - desc1.Width = desc->BufferDesc.Width; - desc1.Height = desc->BufferDesc.Height; - desc1.Format = desc->BufferDesc.Format; - desc1.SampleDesc = desc->SampleDesc; - desc1.BufferUsage = desc->BufferUsage; - desc1.BufferCount = desc->BufferCount; - desc1.Scaling = DXGI_SCALING_STRETCH; - desc1.SwapEffect = desc->SwapEffect; - desc1.Flags = desc->Flags; - DXGI_SWAP_CHAIN_FULLSCREEN_DESC fs_desc{}; - fs_desc.Windowed = desc->Windowed; - fs_desc.RefreshRate = desc->BufferDesc.RefreshRate; - fs_desc.Scaling = desc->BufferDesc.Scaling; - fs_desc.ScanlineOrdering = desc->BufferDesc.ScanlineOrdering; - IDXGISwapChain1* sc1 = nullptr; - const HRESULT hr = CreateSwapChainForHwnd(device, desc->OutputWindow, &desc1, &fs_desc, nullptr, &sc1); - if (SUCCEEDED(hr) && sc1) { - *out = static_cast(sc1); - if (!desc->Windowed) { - // When exclusive fullscreen is unavailable, native DXGI creates the - // windowed chain and returns DXGI_STATUS_OCCLUDED. - return DXGI_STATUS_OCCLUDED; - } - } - return hr; - } - HRESULT STDMETHODCALLTYPE CreateSoftwareAdapter(HMODULE, IDXGIAdapter**) override { return E_NOTIMPL; } - - // IDXGIFactory1 - HRESULT STDMETHODCALLTYPE EnumAdapters1(UINT index, IDXGIAdapter1** out) override { - if (!out) return E_POINTER; - *out = nullptr; - if (index != 0) return DXGI_ERROR_NOT_FOUND; - auto* adapter = new Adapter(this, gipa_, instance_, physical_); - *out = static_cast(adapter); - return S_OK; - } - BOOL STDMETHODCALLTYPE IsCurrent() override { return TRUE; } - - // IDXGIFactory2 - BOOL STDMETHODCALLTYPE IsWindowedStereoEnabled() override { return FALSE; } - HRESULT STDMETHODCALLTYPE CreateSwapChainForHwnd(IUnknown* device, HWND hwnd, const DXGI_SWAP_CHAIN_DESC1* desc, - const DXGI_SWAP_CHAIN_FULLSCREEN_DESC*, IDXGIOutput* restrict_to_output, - IDXGISwapChain1** out) override { - if (out) *out = nullptr; - if (const HRESULT hr = check_hwnd_swap_chain(device, hwnd, desc, out); FAILED(hr)) return hr; - return create_swap_chain(device, hwnd, desc, restrict_to_output, out); - } - - // What the host runtime's DXGI refuses for a D3D12 swap chain on a window (dxgi_swapchain_test compares these, - // RTX 5070 / 621.14): a null queue, window, description or output, an ID3D12Device in place of the queue, the - // bitblt effects, a scaling or alpha mode a window can't present, a flag outside the ones a D3D12 window swap chain - // takes (MODE_SWITCH, DISPLAY_ONLY, FRAME_LATENCY_WAITABLE_OBJECT, ALLOW_TEARING, the holographic restriction and - // 0x2000), a shared, read-only, discard-on-present or unordered-access buffer usage, MSAA, a buffer count outside - // 2..16 and a format the swap chain can't take are DXGI_ERROR_INVALID_CALL; a side above 16384 is E_INVALIDARG, - // only when nothing else is wrong. - static HRESULT check_hwnd_swap_chain(IUnknown* device, HWND hwnd, const DXGI_SWAP_CHAIN_DESC1* desc, - IDXGISwapChain1** out) { - if (!device || !hwnd || !desc || !out) return DXGI_ERROR_INVALID_CALL; - ID3D12CommandQueue* queue = nullptr; - if (FAILED(device->QueryInterface(IID_PPV_ARGS(&queue))) || !queue) return DXGI_ERROR_INVALID_CALL; - queue->Release(); - if (desc->SwapEffect != DXGI_SWAP_EFFECT_FLIP_SEQUENTIAL && desc->SwapEffect != DXGI_SWAP_EFFECT_FLIP_DISCARD) - return DXGI_ERROR_INVALID_CALL; - if (desc->Scaling != DXGI_SCALING_STRETCH && desc->Scaling != DXGI_SCALING_NONE) return DXGI_ERROR_INVALID_CALL; - if (desc->AlphaMode != DXGI_ALPHA_MODE_UNSPECIFIED && desc->AlphaMode != DXGI_ALPHA_MODE_IGNORE) - return DXGI_ERROR_INVALID_CALL; - constexpr UINT kWindowFlags = DXGI_SWAP_CHAIN_FLAG_ALLOW_MODE_SWITCH | DXGI_SWAP_CHAIN_FLAG_DISPLAY_ONLY | - DXGI_SWAP_CHAIN_FLAG_FRAME_LATENCY_WAITABLE_OBJECT | - DXGI_SWAP_CHAIN_FLAG_ALLOW_TEARING | 0x1000u | 0x2000u; - if (desc->Flags & ~kWindowFlags) return DXGI_ERROR_INVALID_CALL; - constexpr DXGI_USAGE kRefusedUsage = - DXGI_USAGE_SHARED | DXGI_USAGE_READ_ONLY | DXGI_USAGE_DISCARD_ON_PRESENT | DXGI_USAGE_UNORDERED_ACCESS; - if (desc->BufferUsage & kRefusedUsage) return DXGI_ERROR_INVALID_CALL; - // The host checks these before the size: MSAA 4 or one buffer at width 16385 is still INVALID_CALL. - if (desc->SampleDesc.Count != 1 || desc->SampleDesc.Quality != 0) return DXGI_ERROR_INVALID_CALL; - if (!valid_flip_buffer_count(desc->BufferCount)) return DXGI_ERROR_INVALID_CALL; - if (dxgi_to_vk_format(desc->Format) == VK_FORMAT_UNDEFINED) return DXGI_ERROR_INVALID_CALL; - if (desc->Width > D3D12_REQ_TEXTURE2D_U_OR_V_DIMENSION || desc->Height > D3D12_REQ_TEXTURE2D_U_OR_V_DIMENSION) - return E_INVALIDARG; - return S_OK; - } - - // The swap chain itself, for a window or (through its HWND) a CoreWindow. The CoreWindow path keeps only these - // checks: the host's rules for it (ASPECT_RATIO_STRETCH, for one) can't be compared without a real CoreWindow. - HRESULT create_swap_chain(IUnknown* device, HWND hwnd, const DXGI_SWAP_CHAIN_DESC1* desc, - IDXGIOutput* restrict_to_output, IDXGISwapChain1** out) { - if (!out) return E_POINTER; - *out = nullptr; - if (!hwnd || !desc) return E_INVALIDARG; - if (desc->SampleDesc.Count != 1 || desc->SampleDesc.Quality != 0) return DXGI_ERROR_INVALID_CALL; - if (!valid_flip_buffer_count(desc->BufferCount)) return DXGI_ERROR_INVALID_CALL; - const VkFormat vk_fmt = dxgi_to_vk_format(desc->Format); - if (vk_fmt == VK_FORMAT_UNDEFINED) return DXGI_ERROR_INVALID_CALL; - auto* sc = new SwapChain(this, device, context_, gipa_, instance_, physical_, gdpa_, queue_, queue_family_); - if (restrict_to_output) sc->set_restrict_to_output(restrict_to_output); - if (!sc->init(hwnd, *desc, vk_fmt)) { - sc->Release(); - return E_FAIL; - } - *out = static_cast(sc); - return S_OK; - } - HRESULT STDMETHODCALLTYPE CreateSwapChainForCoreWindow(IUnknown* device, IUnknown* window, - const DXGI_SWAP_CHAIN_DESC1* desc, - IDXGIOutput* restrict_to_output, - IDXGISwapChain1** out) override { - if (!out) return E_POINTER; - *out = nullptr; - if (!device || !window || !desc) return E_INVALIDARG; - // UWP / Game Core Scarlett titles present to an ICoreWindow. Extract the underlying - // Win32 HWND via ICoreWindowInterop. - static constexpr GUID kIID_ICoreWindowInterop = { - 0x45D64A29, 0xA63E, 0x4CB6, {0xB4, 0x98, 0x57, 0x81, 0xD2, 0x98, 0xCB, 0x4F}}; - struct ICoreWindowInterop : public IUnknown { - virtual HRESULT STDMETHODCALLTYPE get_WindowHandle(HWND* hwnd) = 0; - virtual HRESULT STDMETHODCALLTYPE put_MessageHandled(unsigned char value) = 0; - }; - ICoreWindowInterop* interop = nullptr; - if (FAILED(window->QueryInterface(kIID_ICoreWindowInterop, reinterpret_cast(&interop))) || !interop) { - return DXGI_ERROR_INVALID_CALL; - } - HWND hwnd = nullptr; - const HRESULT hr = interop->get_WindowHandle(&hwnd); - interop->Release(); - if (FAILED(hr) || !hwnd) return DXGI_ERROR_INVALID_CALL; - return create_swap_chain(device, hwnd, desc, restrict_to_output, out); - } - HRESULT STDMETHODCALLTYPE GetSharedResourceAdapterLuid(HANDLE, LUID*) override { return E_NOTIMPL; } - // Microsoft documents S_OK with a cookie for UnregisterStereoStatus (E_NOTIMPL is only the answer of the - // Windows 7 Platform Update). Stereo is never enabled here, so the window or event is never notified. - HRESULT STDMETHODCALLTYPE RegisterStereoStatusWindow(HWND hwnd, UINT msg, DWORD* cookie) override { - (void)msg; - if (!hwnd || !cookie) return DXGI_ERROR_INVALID_CALL; - *cookie = next_stereo_cookie_.fetch_add(1, std::memory_order_relaxed); - return S_OK; - } - HRESULT STDMETHODCALLTYPE RegisterStereoStatusEvent(HANDLE event, DWORD* cookie) override { - if (!event || !cookie) return DXGI_ERROR_INVALID_CALL; - *cookie = next_stereo_cookie_.fetch_add(1, std::memory_order_relaxed); - return S_OK; - } - void STDMETHODCALLTYPE UnregisterStereoStatus(DWORD) override {} - HRESULT STDMETHODCALLTYPE RegisterOcclusionStatusWindow(HWND hwnd, UINT msg, DWORD* cookie) override { - (void)msg; - if (!hwnd || !cookie) return DXGI_ERROR_INVALID_CALL; - *cookie = next_occlusion_cookie_.fetch_add(1, std::memory_order_relaxed); - return S_OK; - } - HRESULT STDMETHODCALLTYPE RegisterOcclusionStatusEvent(HANDLE event, DWORD* cookie) override { - if (!event || !cookie) return DXGI_ERROR_INVALID_CALL; - *cookie = next_occlusion_cookie_.fetch_add(1, std::memory_order_relaxed); - return S_OK; - } - void STDMETHODCALLTYPE UnregisterOcclusionStatus(DWORD) override {} - HRESULT STDMETHODCALLTYPE CreateSwapChainForComposition(IUnknown*, const DXGI_SWAP_CHAIN_DESC1*, IDXGIOutput*, - IDXGISwapChain1**) override { - return E_NOTIMPL; - } - - // IDXGIFactory3 - UINT STDMETHODCALLTYPE GetCreationFlags() override { return 0; } - - // IDXGIFactory4 - HRESULT STDMETHODCALLTYPE EnumAdapterByLuid(LUID luid, REFIID riid, void** out) override { - if (!out) return E_POINTER; - *out = nullptr; - auto* adapter = new Adapter(this, gipa_, instance_, physical_); - const LUID actual = adapter->luid(); - if (actual.LowPart != luid.LowPart || actual.HighPart != luid.HighPart) { - adapter->Release(); - return DXGI_ERROR_NOT_FOUND; - } - const HRESULT hr = adapter->QueryInterface(riid, out); - adapter->Release(); - return hr; - } - HRESULT STDMETHODCALLTYPE EnumWarpAdapter(REFIID, void**) override { return DXGI_ERROR_NOT_FOUND; } - - // IDXGIFactory5 - HRESULT STDMETHODCALLTYPE CheckFeatureSupport(DXGI_FEATURE feature, void* data, UINT size) override { - if (!data) return E_INVALIDARG; - if (feature == DXGI_FEATURE_PRESENT_ALLOW_TEARING) { - if (size != sizeof(BOOL)) return E_INVALIDARG; - std::call_once(tearing_once_, [this] { tearing_supported_ = probe_immediate_present_mode(); }); - *static_cast(data) = tearing_supported_ ? TRUE : FALSE; - return S_OK; - } - return E_INVALIDARG; - } - - // IDXGIFactory6. The factory has one adapter, so every preference orders the same list. Measured on the host's - // dxgi.dll (Windows 11, RTX 3070): a preference outside the enum is accepted, a null `out` is - // DXGI_ERROR_INVALID_CALL, and an index past the end is DXGI_ERROR_NOT_FOUND with *out cleared. - HRESULT STDMETHODCALLTYPE EnumAdapterByGpuPreference(UINT index, DXGI_GPU_PREFERENCE, REFIID riid, - void** out) override { - if (!out) return DXGI_ERROR_INVALID_CALL; - *out = nullptr; - if (index != 0) return DXGI_ERROR_NOT_FOUND; - auto* adapter = new Adapter(this, gipa_, instance_, physical_); - const HRESULT hr = adapter->QueryInterface(riid, out); - adapter->Release(); - return hr; - } - - // IDXGIFactory7. The adapter list never changes, so a registered event is never signalled; the registry only - // keeps the host's answers (same measurement): a null event or cookie and an event registered twice are - // DXGI_ERROR_INVALID_CALL, cookies start at 1 and are separate from the occlusion cookies, and an unknown - // cookie is DXGI_ERROR_NOT_FOUND. - HRESULT STDMETHODCALLTYPE RegisterAdaptersChangedEvent(HANDLE event, DWORD* cookie) override { - if (!event || !cookie) return DXGI_ERROR_INVALID_CALL; - std::lock_guard lock(adapters_changed_mutex_); - for (const auto& [registered_cookie, registered_event] : adapters_changed_events_) - if (registered_event == event) return DXGI_ERROR_INVALID_CALL; - const DWORD next = next_adapters_changed_cookie_++; - adapters_changed_events_.emplace(next, event); - *cookie = next; - return S_OK; - } - HRESULT STDMETHODCALLTYPE UnregisterAdaptersChangedEvent(DWORD cookie) override { - std::lock_guard lock(adapters_changed_mutex_); - return adapters_changed_events_.erase(cookie) ? S_OK : DXGI_ERROR_NOT_FOUND; - } - -private: - bool probe_immediate_present_mode() const { - if (!gipa_ || !instance_ || !physical_) return false; - const auto create_surface = - reinterpret_cast(gipa_(instance_, "vkCreateWin32SurfaceKHR")); - const auto destroy_surface = - reinterpret_cast(gipa_(instance_, "vkDestroySurfaceKHR")); - const auto present_modes = reinterpret_cast( - gipa_(instance_, "vkGetPhysicalDeviceSurfacePresentModesKHR")); - if (!create_surface || !destroy_surface || !present_modes) return false; - const HINSTANCE hinst = GetModuleHandleW(nullptr); - HWND probe_hwnd = CreateWindowExW(0, L"STATIC", L"", WS_POPUP, 0, 0, 1, 1, nullptr, nullptr, hinst, nullptr); - if (!probe_hwnd) return false; - VkWin32SurfaceCreateInfoKHR sci{VK_STRUCTURE_TYPE_WIN32_SURFACE_CREATE_INFO_KHR}; - sci.hinstance = hinst; - sci.hwnd = probe_hwnd; - VkSurfaceKHR surf = VK_NULL_HANDLE; - bool has_immediate = false; - if (create_surface(instance_, &sci, nullptr, &surf) == VK_SUCCESS && surf) { - std::uint32_t count = 0; - if (present_modes(physical_, surf, &count, nullptr) == VK_SUCCESS && count > 0) { - std::vector modes(count); - if (present_modes(physical_, surf, &count, modes.data()) == VK_SUCCESS) { - for (VkPresentModeKHR m : modes) { - if (m == VK_PRESENT_MODE_IMMEDIATE_KHR) { - has_immediate = true; - break; - } - } - } - } - destroy_surface(instance_, surf, nullptr); - } - DestroyWindow(probe_hwnd); - return has_immediate; - } - - std::atomic refs_{1}; - PrivateDataStore private_data_; - leonida::VulkanContext& context_; - PFN_vkGetInstanceProcAddr gipa_; - VkInstance instance_; - VkPhysicalDevice physical_; - PFN_vkGetDeviceProcAddr gdpa_; - VkQueue queue_; - std::uint32_t queue_family_; - HWND assoc_hwnd_ = nullptr; - mutable std::once_flag tearing_once_; - bool tearing_supported_ = false; - std::atomic next_occlusion_cookie_{1}; - std::mutex adapters_changed_mutex_; - std::map adapters_changed_events_; - DWORD next_adapters_changed_cookie_ = 1; - std::atomic next_stereo_cookie_{1}; -}; - -} // namespace - -HRESULT create_factory(leonida::VulkanContext& context, PFN_vkGetInstanceProcAddr gipa, VkInstance instance, - VkPhysicalDevice physical, PFN_vkGetDeviceProcAddr gdpa, VkQueue queue, - std::uint32_t queue_family, REFIID riid, void** out) { - if (!out) return E_POINTER; - *out = nullptr; - auto* factory = new Factory(context, gipa, instance, physical, gdpa, queue, queue_family); - const HRESULT hr = factory->QueryInterface(riid, out); - factory->Release(); - return hr; -} - -} // namespace rt::dxgi diff --git a/runtime/shims/dxgi_com.h b/runtime/shims/dxgi_com.h deleted file mode 100644 index 02ea2e084..000000000 --- a/runtime/shims/dxgi_com.h +++ /dev/null @@ -1,20 +0,0 @@ -#pragma once - -// COM wrappers for IDXGIFactory7, IDXGIAdapter3, IDXGIOutput6, and IDXGISwapChain3 backed by VulkanSwapchain (dxgi_swapchain.h). -// Keeps the host dxgi.dll out of the Vulkan presentation path (docs/d3d12_vulkan.md section 3.1 & 4). - -#include -#include -#include - -#include "dxgi_swapchain.h" - -namespace rt::dxgi { - -// Creates an IDXGIFactory4 COM object whose CreateSwapChainForHwnd creates a VulkanSwapchain -// and registers its back-buffer images with `context` (keyed by the returned ID3D12Resource* pointer). -HRESULT create_factory(leonida::VulkanContext& context, PFN_vkGetInstanceProcAddr gipa, VkInstance instance, - VkPhysicalDevice physical, PFN_vkGetDeviceProcAddr gdpa, VkQueue queue, - std::uint32_t queue_family, REFIID riid, void** out); - -} // namespace rt::dxgi diff --git a/runtime/shims/dxgi_swapchain.h b/runtime/shims/dxgi_swapchain.h deleted file mode 100644 index 3dadfcef5..000000000 --- a/runtime/shims/dxgi_swapchain.h +++ /dev/null @@ -1,603 +0,0 @@ -#pragma once - -// Vulkan swapchain backend for the dxgi.dll shim (docs/d3d12_vulkan.md section 3.1 & 4): -// Wraps VK_KHR_win32_surface + VkSwapchainKHR over a Win32 HWND, exposing acquire/present/resize -// and ResourceBindings for the swapchain images (with presentable = true so D3D12_RESOURCE_STATE_PRESENT -// maps to VK_IMAGE_LAYOUT_PRESENT_SRC_KHR). - -#ifndef VK_NO_PROTOTYPES -#define VK_NO_PROTOTYPES -#endif -#ifndef VK_USE_PLATFORM_WIN32_KHR -#define VK_USE_PLATFORM_WIN32_KHR -#endif - -#include -#include - -#include "../src/vulkan_backend.h" - -#include -#include -#include -#include - -namespace leonida { - -struct SwapchainFunctions { - PFN_vkCreateWin32SurfaceKHR create_win32_surface = nullptr; - PFN_vkDestroySurfaceKHR destroy_surface = nullptr; - PFN_vkGetPhysicalDeviceSurfaceSupportKHR surface_support = nullptr; - PFN_vkGetPhysicalDeviceSurfaceCapabilitiesKHR surface_caps = nullptr; - PFN_vkGetPhysicalDeviceSurfaceFormatsKHR surface_formats = nullptr; - PFN_vkGetPhysicalDeviceSurfacePresentModesKHR surface_present_modes = nullptr; - PFN_vkCreateSwapchainKHR create_swapchain = nullptr; - PFN_vkDestroySwapchainKHR destroy_swapchain = nullptr; - PFN_vkGetSwapchainImagesKHR get_images = nullptr; - PFN_vkAcquireNextImageKHR acquire_next_image = nullptr; - PFN_vkQueuePresentKHR queue_present = nullptr; - PFN_vkCreateFence create_fence = nullptr; - PFN_vkDestroyFence destroy_fence = nullptr; - PFN_vkWaitForFences wait_for_fences = nullptr; - PFN_vkResetFences reset_fences = nullptr; - PFN_vkDeviceWaitIdle device_wait_idle = nullptr; - PFN_vkGetPhysicalDeviceMemoryProperties mem_props = nullptr; - PFN_vkCreateImage create_image = nullptr; - PFN_vkDestroyImage destroy_image = nullptr; - PFN_vkGetImageMemoryRequirements image_mem_req = nullptr; - PFN_vkAllocateMemory alloc_mem = nullptr; - PFN_vkFreeMemory free_mem = nullptr; - PFN_vkBindImageMemory bind_image_mem = nullptr; - PFN_vkCreateCommandPool create_cmd_pool = nullptr; - PFN_vkDestroyCommandPool destroy_cmd_pool = nullptr; - PFN_vkAllocateCommandBuffers alloc_cmd_bufs = nullptr; - PFN_vkResetCommandBuffer reset_cmd_buf = nullptr; - PFN_vkBeginCommandBuffer begin_cmd_buf = nullptr; - PFN_vkEndCommandBuffer end_cmd_buf = nullptr; - PFN_vkCmdPipelineBarrier cmd_barrier = nullptr; - PFN_vkCmdBlitImage cmd_blit = nullptr; - PFN_vkQueueSubmit queue_submit = nullptr; - - bool load(PFN_vkGetInstanceProcAddr gipa, VkInstance instance, PFN_vkGetDeviceProcAddr gdpa, VkDevice device) { -#define LOAD_I(member, name) member = reinterpret_cast(gipa(instance, #name)) -#define LOAD_D(member, name) member = reinterpret_cast(gdpa(device, #name)) - LOAD_I(create_win32_surface, vkCreateWin32SurfaceKHR); - LOAD_I(destroy_surface, vkDestroySurfaceKHR); - LOAD_I(surface_support, vkGetPhysicalDeviceSurfaceSupportKHR); - LOAD_I(surface_caps, vkGetPhysicalDeviceSurfaceCapabilitiesKHR); - LOAD_I(surface_formats, vkGetPhysicalDeviceSurfaceFormatsKHR); - LOAD_I(surface_present_modes, vkGetPhysicalDeviceSurfacePresentModesKHR); - LOAD_I(mem_props, vkGetPhysicalDeviceMemoryProperties); - LOAD_D(create_swapchain, vkCreateSwapchainKHR); - LOAD_D(destroy_swapchain, vkDestroySwapchainKHR); - LOAD_D(get_images, vkGetSwapchainImagesKHR); - LOAD_D(acquire_next_image, vkAcquireNextImageKHR); - LOAD_D(queue_present, vkQueuePresentKHR); - LOAD_D(create_fence, vkCreateFence); - LOAD_D(destroy_fence, vkDestroyFence); - LOAD_D(wait_for_fences, vkWaitForFences); - LOAD_D(reset_fences, vkResetFences); - LOAD_D(device_wait_idle, vkDeviceWaitIdle); - LOAD_D(create_image, vkCreateImage); - LOAD_D(destroy_image, vkDestroyImage); - LOAD_D(image_mem_req, vkGetImageMemoryRequirements); - LOAD_D(alloc_mem, vkAllocateMemory); - LOAD_D(free_mem, vkFreeMemory); - LOAD_D(bind_image_mem, vkBindImageMemory); - LOAD_D(create_cmd_pool, vkCreateCommandPool); - LOAD_D(destroy_cmd_pool, vkDestroyCommandPool); - LOAD_D(alloc_cmd_bufs, vkAllocateCommandBuffers); - LOAD_D(reset_cmd_buf, vkResetCommandBuffer); - LOAD_D(begin_cmd_buf, vkBeginCommandBuffer); - LOAD_D(end_cmd_buf, vkEndCommandBuffer); - LOAD_D(cmd_barrier, vkCmdPipelineBarrier); - LOAD_D(cmd_blit, vkCmdBlitImage); - LOAD_D(queue_submit, vkQueueSubmit); -#undef LOAD_I -#undef LOAD_D - return create_win32_surface && destroy_surface && surface_support && surface_caps && surface_formats && - mem_props && create_swapchain && destroy_swapchain && get_images && acquire_next_image && - queue_present && create_fence && destroy_fence && wait_for_fences && reset_fences && device_wait_idle && - create_image && destroy_image && image_mem_req && alloc_mem && free_mem && bind_image_mem && - create_cmd_pool && destroy_cmd_pool && alloc_cmd_bufs && reset_cmd_buf && begin_cmd_buf && - end_cmd_buf && cmd_barrier && cmd_blit && queue_submit; - } -}; - -class VulkanSwapchain { -public: - VulkanSwapchain(PFN_vkGetInstanceProcAddr gipa, VkInstance instance, VkPhysicalDevice physical, - PFN_vkGetDeviceProcAddr gdpa, VkDevice device, VkQueue queue, std::uint32_t queue_family, - std::mutex& submit_mutex) - : instance_(instance), physical_(physical), device_(device), queue_(queue), queue_family_(queue_family), - submit_mutex_(submit_mutex) { - loaded_ = fn_.load(gipa, instance, gdpa, device); - if (loaded_) { - VkFenceCreateInfo fi{VK_STRUCTURE_TYPE_FENCE_CREATE_INFO}; - if (fn_.create_fence(device_, &fi, nullptr, &acquire_fence_) != VK_SUCCESS) acquire_fence_ = VK_NULL_HANDLE; - if (fn_.create_fence(device_, &fi, nullptr, &blit_fence_) != VK_SUCCESS) blit_fence_ = VK_NULL_HANDLE; - VkCommandPoolCreateInfo pi{VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO}; - pi.flags = VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT; - pi.queueFamilyIndex = queue_family_; - if (fn_.create_cmd_pool(device_, &pi, nullptr, &blit_pool_) == VK_SUCCESS) { - VkCommandBufferAllocateInfo ai{VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO}; - ai.commandPool = blit_pool_; - ai.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY; - ai.commandBufferCount = 1; - if (fn_.alloc_cmd_bufs(device_, &ai, &blit_cmd_) != VK_SUCCESS) blit_cmd_ = VK_NULL_HANDLE; - } - } - } - - ~VulkanSwapchain() { - destroy_swapchain(); - if (blit_pool_) fn_.destroy_cmd_pool(device_, blit_pool_, nullptr); - if (surface_) fn_.destroy_surface(instance_, surface_, nullptr); - if (acquire_fence_) fn_.destroy_fence(device_, acquire_fence_, nullptr); - if (blit_fence_) fn_.destroy_fence(device_, blit_fence_, nullptr); - } - - VulkanSwapchain(const VulkanSwapchain&) = delete; - VulkanSwapchain& operator=(const VulkanSwapchain&) = delete; - - bool create(HWND hwnd, std::uint32_t width, std::uint32_t height, - VkFormat preferred_format = VK_FORMAT_B8G8R8A8_UNORM, std::uint32_t buffer_count = 2, - bool allow_tearing = false) { - if (!loaded_ || !acquire_fence_ || !hwnd) return false; - if (!surface_) { - VkWin32SurfaceCreateInfoKHR sci{VK_STRUCTURE_TYPE_WIN32_SURFACE_CREATE_INFO_KHR}; - sci.hinstance = GetModuleHandleW(nullptr); - sci.hwnd = hwnd; - if (fn_.create_win32_surface(instance_, &sci, nullptr, &surface_) != VK_SUCCESS) return false; - VkBool32 supported = VK_FALSE; - if (fn_.surface_support(physical_, queue_family_, surface_, &supported) != VK_SUCCESS || !supported) - return false; - } - allow_tearing_ = allow_tearing; - return rebuild(width, height, preferred_format, buffer_count); - } - - bool resize(std::uint32_t width, std::uint32_t height, VkFormat preferred_format = VK_FORMAT_UNDEFINED, - std::uint32_t buffer_count = 0, bool allow_tearing = false) { - if (!loaded_ || !surface_) return false; - { - std::lock_guard lock(submit_mutex_); - fn_.device_wait_idle(device_); - } - allow_tearing_ = allow_tearing; - const VkFormat fmt = (preferred_format != VK_FORMAT_UNDEFINED) ? preferred_format : format_; - const std::uint32_t count = buffer_count ? buffer_count : exposed_count_; - return rebuild(width, height, fmt, count ? count : 2u); - } - - bool acquire_next_image(std::uint32_t& out_index, std::uint64_t timeout_ns = UINT64_MAX) { - if (!swapchain_ || !acquire_fence_) return false; - if (fn_.reset_fences(device_, 1, &acquire_fence_) != VK_SUCCESS) return false; - const VkResult r = fn_.acquire_next_image(device_, swapchain_, timeout_ns, VK_NULL_HANDLE, acquire_fence_, - &out_index); - if (r != VK_SUCCESS && r != VK_SUBOPTIMAL_KHR) return false; - if (fn_.wait_for_fences(device_, 1, &acquire_fence_, VK_TRUE, timeout_ns) != VK_SUCCESS) return false; - acquired_index_ = out_index; - if (is_offscreen()) { - // The native image count may differ from the DXGI BufferCount (Vulkan is free to return more - // images than minImageCount, and caps.minImageCount can exceed the app's request). The app's - // backbuffers are the stable offscreen ring; each present blits the current slot into whichever - // native image was acquired, so the exposed index never follows the native one. - current_index_ = next_back_buffer_; - next_back_buffer_ = (next_back_buffer_ + 1) % exposed_count_; - } else { - current_index_ = out_index; - } - // D3D12 swapchain backbuffers begin in D3D12_RESOURCE_STATE_PRESENT; transition each newly acquired - // native swapchain image once from UNDEFINED -> PRESENT_SRC_KHR so presenting an untouched backbuffer - // or transitioning from PRESENT matches the tracked layout. - if (!is_offscreen() && out_index < image_initialized_.size() && !image_initialized_[out_index]) { - if (!transition_image_layout(images_[out_index], VK_IMAGE_LAYOUT_UNDEFINED, - VK_IMAGE_LAYOUT_PRESENT_SRC_KHR)) - return false; - image_initialized_[out_index] = true; - } - return true; - } - - bool present(std::uint32_t back_buffer_index) { - if (!swapchain_ || back_buffer_index >= exposed_count_ || acquired_index_ >= images_.size()) return false; - std::uint32_t image_index = back_buffer_index; - if (is_offscreen()) { - if (!blit_to_swapchain(back_buffer_index)) return false; - image_index = acquired_index_; - } - VkPresentInfoKHR pi{VK_STRUCTURE_TYPE_PRESENT_INFO_KHR}; - pi.swapchainCount = 1; - pi.pSwapchains = &swapchain_; - pi.pImageIndices = &image_index; - std::lock_guard lock(submit_mutex_); - const VkResult r = fn_.queue_present(queue_, &pi); - return r == VK_SUCCESS || r == VK_SUBOPTIMAL_KHR; - } - - // DXGI exposes exactly the BufferCount the app asked for (GetDesc/GetDesc1 and GetCurrentBackBufferIndex - // stay inside it). When Vulkan supplies a different number of native images the extra ones are hidden - // behind a stable offscreen ring (is_offscreen()). - std::uint32_t image_count() const { return exposed_count_; } - std::uint32_t current_back_buffer_index() const { return current_index_; } - VkFormat format() const { return format_; } - VkExtent2D extent() const { return extent_; } - bool is_offscreen() const { return !offscreen_images_.empty(); } - VkPresentModeKHR present_mode() const { return present_mode_; } - VkImage image(std::uint32_t i) const { - if (i >= exposed_count_) return VK_NULL_HANDLE; - return is_offscreen() ? offscreen_images_[i] : images_[i]; - } - - ResourceBinding resource_binding(std::uint32_t i) const { - ResourceBinding b{}; - if (i >= exposed_count_) return b; - const bool offscreen = is_offscreen(); - b.image = offscreen ? offscreen_images_[i] : images_[i]; - b.format = format_; - b.aspects = VK_IMAGE_ASPECT_COLOR_BIT; - b.width = extent_.width; - b.height = extent_.height; - b.mip_levels = 1; - b.array_layers = 1; - b.presentable = !offscreen; - return b; - } - -private: - bool transition_image_layout(VkImage img, VkImageLayout old_layout, VkImageLayout new_layout) { - if (!blit_cmd_ || !blit_fence_ || !img) return false; - std::lock_guard lock(submit_mutex_); - if (fn_.reset_fences(device_, 1, &blit_fence_) != VK_SUCCESS || - fn_.reset_cmd_buf(blit_cmd_, 0) != VK_SUCCESS) - return false; - VkCommandBufferBeginInfo bi{VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO}; - bi.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT; - if (fn_.begin_cmd_buf(blit_cmd_, &bi) != VK_SUCCESS) return false; - VkImageMemoryBarrier barrier{VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER}; - barrier.srcAccessMask = 0; - barrier.dstAccessMask = - (new_layout == VK_IMAGE_LAYOUT_PRESENT_SRC_KHR) ? 0 : (VK_ACCESS_MEMORY_READ_BIT | VK_ACCESS_MEMORY_WRITE_BIT); - barrier.oldLayout = old_layout; - barrier.newLayout = new_layout; - barrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; - barrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; - barrier.image = img; - barrier.subresourceRange = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1}; - fn_.cmd_barrier(blit_cmd_, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, 0, 0, - nullptr, 0, nullptr, 1, &barrier); - if (fn_.end_cmd_buf(blit_cmd_) != VK_SUCCESS) return false; - VkSubmitInfo si{VK_STRUCTURE_TYPE_SUBMIT_INFO}; - si.commandBufferCount = 1; - si.pCommandBuffers = &blit_cmd_; - return fn_.queue_submit(queue_, 1, &si, blit_fence_) == VK_SUCCESS && - fn_.wait_for_fences(device_, 1, &blit_fence_, VK_TRUE, UINT64_MAX) == VK_SUCCESS; - } - - void destroy_offscreen() { - for (VkImage img : offscreen_images_) - if (img) fn_.destroy_image(device_, img, nullptr); - for (VkDeviceMemory mem : offscreen_memory_) - if (mem) fn_.free_mem(device_, mem, nullptr); - offscreen_images_.clear(); - offscreen_memory_.clear(); - } - - void destroy_swapchain() { - if (swapchain_ || !offscreen_images_.empty()) { - std::lock_guard lock(submit_mutex_); - fn_.device_wait_idle(device_); - destroy_offscreen(); - if (swapchain_) { - fn_.destroy_swapchain(device_, swapchain_, nullptr); - swapchain_ = VK_NULL_HANDLE; - } - } - images_.clear(); - exposed_count_ = 0; - } - - bool create_offscreen_backbuffers(std::uint32_t count) { - VkPhysicalDeviceMemoryProperties mp{}; - fn_.mem_props(physical_, &mp); - offscreen_images_.reserve(count); - offscreen_memory_.reserve(count); - for (std::uint32_t i = 0; i < count; ++i) { - VkImageCreateInfo ici{VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO}; - ici.imageType = VK_IMAGE_TYPE_2D; - ici.format = format_; - ici.extent = {extent_.width, extent_.height, 1}; - ici.mipLevels = 1; - ici.arrayLayers = 1; - ici.samples = VK_SAMPLE_COUNT_1_BIT; - ici.tiling = VK_IMAGE_TILING_OPTIMAL; - ici.usage = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | VK_IMAGE_USAGE_TRANSFER_SRC_BIT | - VK_IMAGE_USAGE_TRANSFER_DST_BIT | VK_IMAGE_USAGE_SAMPLED_BIT; - ici.sharingMode = VK_SHARING_MODE_EXCLUSIVE; - ici.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED; - VkImage img = VK_NULL_HANDLE; - if (fn_.create_image(device_, &ici, nullptr, &img) != VK_SUCCESS) { - destroy_offscreen(); - return false; - } - VkMemoryRequirements req{}; - fn_.image_mem_req(device_, img, &req); - std::uint32_t mem_idx = UINT32_MAX; - for (std::uint32_t m = 0; m < mp.memoryTypeCount; ++m) { - if ((req.memoryTypeBits & (1u << m)) && - (mp.memoryTypes[m].propertyFlags & VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT)) { - mem_idx = m; - break; - } - } - if (mem_idx == UINT32_MAX) { - for (std::uint32_t m = 0; m < mp.memoryTypeCount; ++m) { - if (req.memoryTypeBits & (1u << m)) { - mem_idx = m; - break; - } - } - } - VkMemoryAllocateInfo mai{VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO}; - mai.allocationSize = req.size; - mai.memoryTypeIndex = mem_idx; - VkDeviceMemory mem = VK_NULL_HANDLE; - if (mem_idx == UINT32_MAX || fn_.alloc_mem(device_, &mai, nullptr, &mem) != VK_SUCCESS || - fn_.bind_image_mem(device_, img, mem, 0) != VK_SUCCESS) { - if (mem) fn_.free_mem(device_, mem, nullptr); - fn_.destroy_image(device_, img, nullptr); - destroy_offscreen(); - return false; - } - offscreen_images_.push_back(img); - offscreen_memory_.push_back(mem); - } - // Transition newly created offscreen backbuffers to GENERAL so presenting an untouched buffer - // never violates blit_to_swapchain's GENERAL -> TRANSFER_SRC_OPTIMAL transition. - if (blit_cmd_ && blit_fence_ && !offscreen_images_.empty()) { - std::lock_guard lock(submit_mutex_); - if (fn_.reset_fences(device_, 1, &blit_fence_) != VK_SUCCESS || - fn_.reset_cmd_buf(blit_cmd_, 0) != VK_SUCCESS) { - destroy_offscreen(); - return false; - } - VkCommandBufferBeginInfo bi{VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO}; - bi.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT; - if (fn_.begin_cmd_buf(blit_cmd_, &bi) != VK_SUCCESS) { - destroy_offscreen(); - return false; - } - std::vector barriers(offscreen_images_.size()); - for (std::size_t i = 0; i < offscreen_images_.size(); ++i) { - barriers[i].sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER; - barriers[i].srcAccessMask = 0; - barriers[i].dstAccessMask = VK_ACCESS_MEMORY_READ_BIT | VK_ACCESS_MEMORY_WRITE_BIT; - barriers[i].oldLayout = VK_IMAGE_LAYOUT_UNDEFINED; - barriers[i].newLayout = VK_IMAGE_LAYOUT_GENERAL; - barriers[i].srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; - barriers[i].dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; - barriers[i].image = offscreen_images_[i]; - barriers[i].subresourceRange = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1}; - } - fn_.cmd_barrier(blit_cmd_, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, 0, 0, - nullptr, 0, nullptr, static_cast(barriers.size()), barriers.data()); - if (fn_.end_cmd_buf(blit_cmd_) != VK_SUCCESS) { - destroy_offscreen(); - return false; - } - VkSubmitInfo si{VK_STRUCTURE_TYPE_SUBMIT_INFO}; - si.commandBufferCount = 1; - si.pCommandBuffers = &blit_cmd_; - if (fn_.queue_submit(queue_, 1, &si, blit_fence_) != VK_SUCCESS || - fn_.wait_for_fences(device_, 1, &blit_fence_, VK_TRUE, UINT64_MAX) != VK_SUCCESS) { - destroy_offscreen(); - return false; - } - } - return true; - } - - bool blit_to_swapchain(std::uint32_t image_index) { - if (!blit_cmd_ || !blit_fence_ || image_index >= offscreen_images_.size() || - acquired_index_ >= images_.size()) - return false; - const VkImage dst_image = images_[acquired_index_]; - std::lock_guard lock(submit_mutex_); - if (fn_.reset_fences(device_, 1, &blit_fence_) != VK_SUCCESS) return false; - if (fn_.reset_cmd_buf(blit_cmd_, 0) != VK_SUCCESS) return false; - VkCommandBufferBeginInfo bi{VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO}; - bi.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT; - if (fn_.begin_cmd_buf(blit_cmd_, &bi) != VK_SUCCESS) return false; - - VkImageMemoryBarrier pre[2]{}; - pre[0].sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER; - pre[0].srcAccessMask = VK_ACCESS_MEMORY_WRITE_BIT; - pre[0].dstAccessMask = VK_ACCESS_TRANSFER_READ_BIT; - pre[0].oldLayout = VK_IMAGE_LAYOUT_GENERAL; - pre[0].newLayout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL; - pre[0].srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; - pre[0].dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; - pre[0].image = offscreen_images_[image_index]; - pre[0].subresourceRange = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1}; - - pre[1].sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER; - pre[1].srcAccessMask = 0; - pre[1].dstAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT; - pre[1].oldLayout = VK_IMAGE_LAYOUT_UNDEFINED; - pre[1].newLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL; - pre[1].srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; - pre[1].dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; - pre[1].image = dst_image; - pre[1].subresourceRange = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1}; - - fn_.cmd_barrier(blit_cmd_, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, 0, 0, nullptr, - 0, nullptr, 2, pre); - - VkImageBlit region{}; - region.srcSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1}; - region.srcOffsets[1] = {static_cast(extent_.width), static_cast(extent_.height), 1}; - region.dstSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1}; - region.dstOffsets[1] = {static_cast(surface_extent_.width), - static_cast(surface_extent_.height), 1}; - fn_.cmd_blit(blit_cmd_, offscreen_images_[image_index], VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, - dst_image, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, ®ion, VK_FILTER_LINEAR); - - VkImageMemoryBarrier post[2]{}; - post[0].sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER; - post[0].srcAccessMask = VK_ACCESS_TRANSFER_READ_BIT; - post[0].dstAccessMask = VK_ACCESS_MEMORY_READ_BIT | VK_ACCESS_MEMORY_WRITE_BIT; - post[0].oldLayout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL; - post[0].newLayout = VK_IMAGE_LAYOUT_GENERAL; - post[0].srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; - post[0].dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; - post[0].image = offscreen_images_[image_index]; - post[0].subresourceRange = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1}; - - post[1].sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER; - post[1].srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT; - post[1].dstAccessMask = 0; - post[1].oldLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL; - post[1].newLayout = VK_IMAGE_LAYOUT_PRESENT_SRC_KHR; - post[1].srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; - post[1].dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; - post[1].image = dst_image; - post[1].subresourceRange = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1}; - - fn_.cmd_barrier(blit_cmd_, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, 0, 0, nullptr, - 0, nullptr, 2, post); - - if (fn_.end_cmd_buf(blit_cmd_) != VK_SUCCESS) return false; - VkSubmitInfo si{VK_STRUCTURE_TYPE_SUBMIT_INFO}; - si.commandBufferCount = 1; - si.pCommandBuffers = &blit_cmd_; - if (fn_.queue_submit(queue_, 1, &si, blit_fence_) != VK_SUCCESS) return false; - return fn_.wait_for_fences(device_, 1, &blit_fence_, VK_TRUE, UINT64_MAX) == VK_SUCCESS; - } - - bool rebuild(std::uint32_t width, std::uint32_t height, VkFormat preferred_format, std::uint32_t buffer_count) { - VkSurfaceCapabilitiesKHR caps{}; - if (fn_.surface_caps(physical_, surface_, &caps) != VK_SUCCESS) return false; - - std::uint32_t fmt_count = 0; - fn_.surface_formats(physical_, surface_, &fmt_count, nullptr); - if (fmt_count == 0) return false; - std::vector formats(fmt_count); - fn_.surface_formats(physical_, surface_, &fmt_count, formats.data()); - - VkSurfaceFormatKHR chosen = formats[0]; - for (const auto& sf : formats) { - if (sf.format == preferred_format && sf.colorSpace == VK_COLOR_SPACE_SRGB_NONLINEAR_KHR) { - chosen = sf; - break; - } - } - - VkExtent2D ext{}; - if (caps.currentExtent.width != UINT32_MAX && caps.currentExtent.width > 0 && caps.currentExtent.height > 0) { - ext = caps.currentExtent; - } else { - ext.width = std::clamp(width, caps.minImageExtent.width, caps.maxImageExtent.width); - ext.height = std::clamp(height, caps.minImageExtent.height, caps.maxImageExtent.height); - } - - std::uint32_t count = std::max(buffer_count, caps.minImageCount); - if (caps.maxImageCount > 0) count = std::min(count, caps.maxImageCount); - - VkPresentModeKHR chosen_present_mode = VK_PRESENT_MODE_FIFO_KHR; - if (allow_tearing_ && fn_.surface_present_modes) { - std::uint32_t mode_count = 0; - if (fn_.surface_present_modes(physical_, surface_, &mode_count, nullptr) == VK_SUCCESS && mode_count > 0) { - std::vector modes(mode_count); - if (fn_.surface_present_modes(physical_, surface_, &mode_count, modes.data()) == VK_SUCCESS) { - bool has_immediate = false; - bool has_mailbox = false; - for (VkPresentModeKHR m : modes) { - if (m == VK_PRESENT_MODE_IMMEDIATE_KHR) has_immediate = true; - if (m == VK_PRESENT_MODE_MAILBOX_KHR) has_mailbox = true; - } - if (has_immediate) chosen_present_mode = VK_PRESENT_MODE_IMMEDIATE_KHR; - else if (has_mailbox) chosen_present_mode = VK_PRESENT_MODE_MAILBOX_KHR; - } - } - } - - VkSwapchainCreateInfoKHR ci{VK_STRUCTURE_TYPE_SWAPCHAIN_CREATE_INFO_KHR}; - ci.surface = surface_; - ci.minImageCount = count; - ci.imageFormat = chosen.format; - ci.imageColorSpace = chosen.colorSpace; - ci.imageExtent = ext; - ci.imageArrayLayers = 1; - ci.imageUsage = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT; - if (caps.supportedUsageFlags & VK_IMAGE_USAGE_TRANSFER_SRC_BIT) - ci.imageUsage |= VK_IMAGE_USAGE_TRANSFER_SRC_BIT; - ci.imageSharingMode = VK_SHARING_MODE_EXCLUSIVE; - ci.preTransform = caps.currentTransform; - ci.compositeAlpha = VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR; - ci.presentMode = chosen_present_mode; - ci.clipped = VK_TRUE; - ci.oldSwapchain = swapchain_; - - VkSwapchainKHR next = VK_NULL_HANDLE; - if (fn_.create_swapchain(device_, &ci, nullptr, &next) != VK_SUCCESS) return false; - if (swapchain_) fn_.destroy_swapchain(device_, swapchain_, nullptr); - destroy_offscreen(); - swapchain_ = next; - present_mode_ = chosen_present_mode; - format_ = (preferred_format != VK_FORMAT_UNDEFINED) ? preferred_format : chosen.format; - surface_extent_ = ext; - extent_ = (width > 0 && height > 0) ? VkExtent2D{width, height} : ext; - - std::uint32_t img_count = 0; - fn_.get_images(device_, swapchain_, &img_count, nullptr); - if (img_count == 0) return false; - images_.resize(img_count); - fn_.get_images(device_, swapchain_, &img_count, images_.data()); - image_initialized_.assign(img_count, false); - const std::uint32_t requested = buffer_count ? buffer_count : 2u; - // The native images are never the app's back buffers. A size, format or count that differs cannot be mapped - // one-to-one (Vulkan may return more images than minImageCount, and minImageCount may exceed the app's - // request), and even a matching set comes back from vkAcquireNextImageKHR in any order (0 1 0 2 1 0 2 on an - // RTX 5070 Ti with three FIFO images), where DXGI hands a flip-model chain's buffers out round-robin, 0, 1, - // ..., BufferCount-1 (host-measured on NVIDIA and WARP). The app owns one persistent resource per BufferCount - // index: expose the requested count as offscreen images and blit the presented slot into the acquired native - // image instead. - if (!create_offscreen_backbuffers(requested)) return false; - exposed_count_ = requested; - current_index_ = 0; - next_back_buffer_ = 0; - acquired_index_ = 0; - return true; - } - - SwapchainFunctions fn_{}; - bool loaded_ = false; - VkInstance instance_ = VK_NULL_HANDLE; - VkPhysicalDevice physical_ = VK_NULL_HANDLE; - VkDevice device_ = VK_NULL_HANDLE; - VkQueue queue_ = VK_NULL_HANDLE; - std::uint32_t queue_family_ = 0; - std::mutex& submit_mutex_; - VkSurfaceKHR surface_ = VK_NULL_HANDLE; - VkSwapchainKHR swapchain_ = VK_NULL_HANDLE; - VkFence acquire_fence_ = VK_NULL_HANDLE; - VkFence blit_fence_ = VK_NULL_HANDLE; - VkCommandPool blit_pool_ = VK_NULL_HANDLE; - VkCommandBuffer blit_cmd_ = VK_NULL_HANDLE; - VkFormat format_ = VK_FORMAT_UNDEFINED; - VkPresentModeKHR present_mode_ = VK_PRESENT_MODE_FIFO_KHR; - bool allow_tearing_ = false; - VkExtent2D surface_extent_{0, 0}; - VkExtent2D extent_{0, 0}; - std::vector images_; - std::vector image_initialized_; - std::vector offscreen_images_; - std::vector offscreen_memory_; - std::uint32_t exposed_count_ = 0; - std::uint32_t current_index_ = 0; - std::uint32_t acquired_index_ = 0; - std::uint32_t next_back_buffer_ = 0; -}; - -} // namespace leonida diff --git a/runtime/shims/file_system.cpp b/runtime/shims/file_system.cpp deleted file mode 100644 index 2df5d5566..000000000 --- a/runtime/shims/file_system.cpp +++ /dev/null @@ -1,1463 +0,0 @@ -// file_system: the file API of a mapped title, seen through the console's drives. -// -// A GDK title names its files on the console's drives, "GAME:\\data\\x.sps" being one in the installed game folder, so -// the imports it makes of CreateFile*, FindFirstFile*/FindNextFile*/FindClose, GetFileAttributes*/GetFileAttributesEx*, -// DeleteFile*, CreateDirectory*/RemoveDirectory*, MoveFile*, CopyFile*/CopyFile2 and SetFileAttributes* are answered -// here (docs/runtime_imports.md, "Console paths and the write overlay"; the prefixes come from ivall/xcl, -// GPL-2.0-only, as facts). The rules: -// - "GAME:" (any case, "\\" or "/") maps under --game-dir, "G:\\" is the same folder and "T:\\" a scratch folder in -// the overlay (RT-218); any other path is a host path and goes to the host; -// - an open that can write, and DeleteFile, go to the overlay (--overlay, default \\overlay), so the -// package stays exactly as installed. A write-open of a package file copies it into the overlay first, so -// OPEN_EXISTING keeps its bytes; a delete of a package file leaves an empty marker under -// \\.gta6rt-deleted, and reads and listings treat the name as gone. The marker is never removed and a -// deleted name is never copied up: a re-created file is its overlay copy, which reads and listings already -// prefer, while an open of a deleted name that fails leaves the name deleted; -// - reads prefer the overlay copy and then the package; -// - FindFirstFile merges the two folders, the overlay winning on a name, and hides deleted names and the marker -// folder; -// - folders are made in the overlay; a removed package folder is hidden by a marker, a moved package file is -// copied into the overlay and its old name deleted, and attributes are set on the overlay copy; -// - a path that climbs above the root with ".." or names another drive is refused with ERROR_INVALID_NAME, so a -// title cannot reach outside the package and the overlay. -// Only images mapped by the loader see these: they are bound through the registry, the runtime's own code calls the -// host directly. -#include -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include "file_system.h" -#include "shims.h" -#include "startup_trace.h" - -namespace rt::fs { -namespace { - -constexpr wchar_t kGamePrefix[] = L"game:"; -constexpr size_t kGamePrefixLength = 5; -constexpr wchar_t kDeletedDir[] = L".gta6rt-deleted"; -constexpr wchar_t kScratchDir[] = L".gta6rt-temp"; // what "T:\" names, inside the overlay -// A removed package folder is marked by this file inside its marker folder: the marker folder itself can already -// exist because files below it were deleted, and that alone does not hide the folder. -constexpr wchar_t kRemovedDirMarker[] = L".gta6rt-dir"; -// Copy-up writes here first and then renames into place, so a half-copied file never sits under the title's name. -constexpr wchar_t kCopyDir[] = L".gta6rt-copy"; - -// The overlay root's own folders, which a title never sees in a listing. -bool internal_dir(const wchar_t* name) { - return _wcsicmp(name, kDeletedDir) == 0 || _wcsicmp(name, kCopyDir) == 0 || _wcsicmp(name, kScratchDir) == 0 || - _wcsicmp(name, kPersistentStorageDir) == 0; -} - -std::mutex g_mutex; -std::filesystem::path g_game_dir; -std::filesystem::path g_overlay_dir; - -struct Roots { - std::filesystem::path game, overlay; -}; - -Roots roots() { - std::lock_guard lock(g_mutex); - return {g_game_dir, g_overlay_dir}; -} - -std::wstring lower(std::wstring s) { - for (auto& c : s) c = static_cast(std::towlower(c)); - return s; -} - -bool same_name(const wchar_t* a, const wchar_t* b) { return _wcsicmp(a, b) == 0; } - -// The narrow API (CreateFileA and friends) takes ANSI code page text, as the CRT does; the loader's own paths are -// handled as wide strings everywhere else. -std::wstring widen_ansi(const char* s) { - if (!s) return {}; - const int n = MultiByteToWideChar(CP_ACP, 0, s, -1, nullptr, 0); - if (n <= 1) return {}; - std::wstring w(static_cast(n - 1), L'\0'); - MultiByteToWideChar(CP_ACP, 0, s, -1, w.data(), n); - return w; -} - -void narrow_ansi(const std::wstring& wide, char* out, size_t capacity) { - if (capacity == 0) return; - const int n = WideCharToMultiByte(CP_ACP, 0, wide.c_str(), -1, nullptr, 0, nullptr, nullptr); - if (n <= 1 || static_cast(n) > capacity) { - out[0] = '\0'; - return; - } - WideCharToMultiByte(CP_ACP, 0, wide.c_str(), -1, out, static_cast(capacity), nullptr, nullptr); -} - -enum class Parsed { Host, Console, Refused }; - -// Splits a console path into the components below the root. A component that names a drive or a stream ("C:", "x:y") -// and a ".." that would leave the root are refused: the package and the overlay are the only folders a title may name. -bool is_separator(wchar_t c) { return c == L'\\' || c == L'/'; } - -// True when `path` is `root` or lies below it, compared by name (case-insensitive, either separator). -bool lies_under(const std::wstring& path, const std::filesystem::path& root) { - std::wstring base = lower(root.native()); - for (auto& c : base) if (c == L'/') c = L'\\'; - while (!base.empty() && base.back() == L'\\') base.pop_back(); - if (base.empty()) return false; - std::wstring p = lower(path); - for (auto& c : p) if (c == L'/') c = L'\\'; - return p.compare(0, base.size(), base) == 0 && (p.size() == base.size() || p[base.size()] == L'\\'); -} - -// The console shim may resolve even a short guest name to an extended-length host path. GetFullPathNameW -// applies the ordinary DOS path rules (including trailing dots and spaces) before the extended prefix disables -// that normalization. The headroom is for CreateDirectoryW's shorter limit on an unprefixed directory name. -std::filesystem::path win32_io_path(const std::filesystem::path& path) { - const auto& native = path.native(); - constexpr size_t kDirectoryPathLimit = MAX_PATH - 12; - if (native.size() < kDirectoryPathLimit || !path.is_absolute() || - native.starts_with(L"\\\\?\\") || native.starts_with(L"\\\\.\\")) - return path; - - const DWORD capacity = ::GetFullPathNameW(native.c_str(), 0, nullptr, nullptr); - if (capacity == 0) return path; - std::wstring full(capacity, L'\0'); - const DWORD size = ::GetFullPathNameW(native.c_str(), capacity, full.data(), nullptr); - if (size == 0 || size >= capacity) return path; - full.resize(size); - - // DOS device names such as NUL can normalize to a device path. Leave those to the native API as before. - if (full.starts_with(L"\\\\.\\")) return path; - if (full.starts_with(L"\\\\")) return std::filesystem::path(L"\\\\?\\UNC\\" + full.substr(2)); - return std::filesystem::path(L"\\\\?\\" + full); -} - -std::filesystem::path win32_find_path(const std::filesystem::path& path, const std::wstring& leaf) { - if (path.native().size() < MAX_PATH) return path; - const auto search = win32_io_path(path); - if (search == path || !leaf.ends_with(L'.') || leaf.find_first_of(L"*?") == std::wstring::npos) return search; - - // GetFullPathNameW strips a terminal dot, but that dot changes a native Win32 search (e.g. "mesh*."). - // Preserve the DOS wildcard expression for the extended path and let the filesystem match it, including - // short names. The DOS_STAR, DOS_QM and DOS_DOT tokens are defined by MS-FSA 2.1.4.3-4. - std::wstring mask = search.filename().native(); - if (mask.ends_with(L'*')) mask.back() = L'<'; - else mask.push_back(L'"'); - for (size_t i = 0; i + 1 < mask.size(); ++i) { - const wchar_t next = mask[i + 1]; - if (mask[i] == L'?') mask[i] = L'>'; - else if (mask[i] == L'*' && next == L'.') mask[i] = L'<'; - else if (mask[i] == L'.' && (next == L'*' || next == L'?' || next == L'<')) mask[i] = L'"'; - } - return search.parent_path() / mask; -} - -// "G:\x" is the installed package, like "GAME:\x", and "T:\x" a scratch folder the title may write to, the way the -// other console layers map those two drives (RT-218). Only the executable can say which spelling the title uses, so -// a host drive of the same letter must keep working: a path under --game-dir or the overlay (a package on drive G:, -// or a path GetModuleFileName handed back) stays a host path, and so does every G:/T: path while no roots are -// configured. The scratch folder lives in the overlay, as `.gta6rt-temp`. -enum class Drive { None, Game, Scratch }; - -Drive console_drive(const std::wstring& path, size_t& prefix_length) { - if (path.size() >= kGamePrefixLength && lower(path.substr(0, kGamePrefixLength)) == kGamePrefix) { - prefix_length = kGamePrefixLength; - return Drive::Game; - } - if (path.size() < 2 || path[1] != L':' || (path.size() > 2 && !is_separator(path[2]))) return Drive::None; - const wchar_t letter = static_cast(std::towlower(path[0])); - if (letter != L'g' && letter != L't') return Drive::None; - const Roots r = roots(); - if (r.game.empty() && r.overlay.empty()) return Drive::None; - if (lies_under(path, r.game) || lies_under(path, r.overlay)) return Drive::None; - prefix_length = 2; - return letter == L'g' ? Drive::Game : Drive::Scratch; -} - -Parsed parse_console(const std::wstring& path, std::vector& parts) { - size_t prefix_length = 0; - const Drive drive = console_drive(path, prefix_length); - if (drive == Drive::None) return Parsed::Host; - parts.clear(); - if (drive == Drive::Scratch) { - parts.push_back(kScratchDir); - const std::filesystem::path overlay = roots().overlay; - const DWORD last_error = ::GetLastError(); - std::error_code ec; - if (!overlay.empty()) std::filesystem::create_directories(win32_io_path(overlay / kScratchDir), ec); - ::SetLastError(last_error); - } - const size_t floor = parts.size(); // ".." may not climb out of the drive's own root - std::wstring part; - auto flush = [&]() -> bool { - if (part.empty() || part == L".") { - part.clear(); - return true; - } - if (part == L"..") { - if (parts.size() <= floor) return false; - parts.pop_back(); - } else if (part.find(L':') != std::wstring::npos) { - return false; - } else { - parts.push_back(part); - } - part.clear(); - return true; - }; - for (size_t i = prefix_length; i < path.size(); ++i) { - const wchar_t c = path[i]; - if (is_separator(c)) { - if (!flush()) return Parsed::Refused; - } else { - part.push_back(c); - } - } - if (!flush()) return Parsed::Refused; - // The overlay's own folders are not part of the title's GAME: tree: hidden from its listings (internal_dir) and - // refused as an explicit path too, in every spelling the loop above normalises (case, slashes, "." and ".."). - // T: still names the scratch folder: its first part is pushed above, not parsed from the title's path. - if (drive == Drive::Game && !parts.empty() && internal_dir(parts.front().c_str())) return Parsed::Refused; - return Parsed::Console; -} - -std::filesystem::path join(const std::filesystem::path& root, const std::vector& parts) { - std::filesystem::path p = root; - for (const auto& part : parts) p /= part; - return p; -} - -std::filesystem::path disk_path(const std::filesystem::path& root, const std::vector& parts) { - return win32_io_path(join(root, parts)); -} - -bool drive_root(const std::wstring& path, const std::vector& parts) { - size_t prefix_length = 0; - return parts.empty() || (parts.size() == 1 && console_drive(path, prefix_length) == Drive::Scratch); -} - -struct Target { - std::filesystem::path path; - DWORD error = 0; // non-zero: the caller fails with this error and does not touch the host -}; - -Target fail(DWORD error) { - Target t; - t.error = error; - return t; -} - -// The overlay keeps one empty marker per deleted package path, outside the mirrored tree so it cannot collide with a -// file the title creates. -std::filesystem::path marker(const std::filesystem::path& overlay, const std::vector& parts) { - return join(overlay / kDeletedDir, parts); -} - -// A deleted file leaves an empty file at its marker path and a removed folder leaves kRemovedDirMarker inside its -// marker folder. -bool deleted(const std::filesystem::path& overlay, const std::vector& parts) { - if (overlay.empty() || parts.empty()) return false; - std::error_code ec; - // Only regular files are deletion markers; parent directories inside .gta6rt-deleted/ exist only to hold markers - // for nested deleted files and must not hide the corresponding ancestor directories in the package. - const std::filesystem::path m = marker(overlay, parts); - return std::filesystem::is_regular_file(win32_io_path(m), ec) || - std::filesystem::is_regular_file(win32_io_path(m / kRemovedDirMarker), ec); -} - -// Writes an empty hidden marker file. On failure `error` holds the reason. -bool write_marker(const std::filesystem::path& path, DWORD& error) { - const std::filesystem::path mark = win32_io_path(path); - std::error_code ec; - std::filesystem::create_directories(mark.parent_path(), ec); - if (ec) { - error = static_cast(ec.value()); - return false; - } - const HANDLE h = ::CreateFileW(mark.c_str(), GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, - nullptr, CREATE_ALWAYS, FILE_ATTRIBUTE_HIDDEN, nullptr); - if (h == INVALID_HANDLE_VALUE) { - error = ::GetLastError(); - return false; - } - ::CloseHandle(h); - return true; -} - -// Flushes a file the shim wrote on the title's behalf, for MOVEFILE_WRITE_THROUGH. On failure `error` holds the reason. -bool flush_file(const std::filesystem::path& path, DWORD& error) { - const HANDLE h = ::CreateFileW(win32_io_path(path).c_str(), GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, - nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr); - if (h == INVALID_HANDLE_VALUE) { - error = ::GetLastError(); - return false; - } - const BOOL ok = ::FlushFileBuffers(h); - if (!ok) error = ::GetLastError(); - ::CloseHandle(h); - return ok != FALSE; -} - -// What a console path is in the title's view: the overlay copy if there is one, else the package's unless deleted. -enum class Kind { None, File, Directory }; -struct View { - Kind kind = Kind::None; - bool in_overlay = false; // the overlay holds the name - bool in_package = false; // the package holds the name and it is not deleted -}; - -View view(const Roots& r, const std::vector& parts) { - View v; - std::error_code ec; - if (parts.empty()) { // "GAME:" itself - v.kind = Kind::Directory; - v.in_package = !r.game.empty(); - return v; - } - if (!r.overlay.empty()) { - const std::filesystem::path p = disk_path(r.overlay, parts); - if (std::filesystem::exists(p, ec)) { - v.in_overlay = true; - v.kind = std::filesystem::is_directory(p, ec) ? Kind::Directory : Kind::File; - } - } - if (!r.game.empty() && !deleted(r.overlay, parts)) { - const std::filesystem::path p = disk_path(r.game, parts); - if (std::filesystem::exists(p, ec)) { - v.in_package = true; - if (v.kind == Kind::None) v.kind = std::filesystem::is_directory(p, ec) ? Kind::Directory : Kind::File; - } - } - return v; -} - -bool is_folder(const Roots& r, const std::vector& parts) { return view(r, parts).kind == Kind::Directory; } - -// Whether two console paths name the same entry: names compare without case, as the lookups do. -bool same_entry(const std::vector& a, const std::vector& b) { - if (a.size() != b.size()) return false; - for (size_t i = 0; i < a.size(); ++i) - if (!same_name(a[i].c_str(), b[i].c_str())) return false; - return true; -} - -std::vector parent_of(const std::vector& parts) { - return parts.empty() ? parts : std::vector(parts.begin(), parts.end() - 1); -} - -// Whether a folder has nothing in the title's view: no overlay entry and no package entry that is not deleted. -bool empty_in_view(const Roots& r, const std::vector& parts) { - std::error_code ec; - if (!r.overlay.empty()) { - const std::filesystem::path p = disk_path(r.overlay, parts); - for (auto it = std::filesystem::directory_iterator(p, ec); !ec && it != std::filesystem::directory_iterator(); - it.increment(ec)) { - if (parts.empty() && internal_dir(it->path().filename().c_str())) continue; - return false; - } - } - ec.clear(); - if (!r.game.empty()) { - const std::filesystem::path p = disk_path(r.game, parts); - for (auto it = std::filesystem::directory_iterator(p, ec); !ec && it != std::filesystem::directory_iterator(); - it.increment(ec)) { - std::vector child = parts; - child.push_back(it->path().filename().wstring()); - if (!deleted(r.overlay, child)) return false; - } - } - return true; -} - -BOOL fail_bool(DWORD error) { - SetLastError(error); - return FALSE; -} - -Target read_target(const std::wstring& path) { - std::vector parts; - const Parsed parsed = parse_console(path, parts); - if (parsed == Parsed::Host) { - Target t; - t.path = std::filesystem::path(path); - return t; - } - if (parsed == Parsed::Refused) return fail(ERROR_INVALID_NAME); - - const Roots r = roots(); - if (r.game.empty()) return fail(ERROR_PATH_NOT_FOUND); - - std::error_code ec; - if (!r.overlay.empty()) { - const std::filesystem::path overlay_path = disk_path(r.overlay, parts); - if (std::filesystem::exists(overlay_path, ec)) { - Target t; - t.path = overlay_path; - return t; - } - } - // A package file the title deleted is gone even though the package still holds it. - if (deleted(r.overlay, parts)) return fail(ERROR_FILE_NOT_FOUND); - - Target t; - t.path = disk_path(r.game, parts); - return t; -} - -Target write_target(const std::wstring& path, bool copy_up) { - std::vector parts; - const Parsed parsed = parse_console(path, parts); - if (parsed == Parsed::Host) { - Target t; - t.path = std::filesystem::path(path); - return t; - } - if (parsed == Parsed::Refused) return fail(ERROR_INVALID_NAME); - - const Roots r = roots(); - if (r.overlay.empty()) return fail(ERROR_PATH_NOT_FOUND); - if (parts.empty()) return fail(ERROR_INVALID_NAME); // "GAME:" is a folder, not a file - - // The folder has to exist in the title's view, as CreateDirectory, MoveFile and CopyFile require: without the - // check a failed open left the missing folders behind, and a create succeeded in a folder that was never made, - // below a package file (which then read as a folder) and inside a folder the title had removed. The overlay may - // still lack a folder only the package has, so it is mirrored here, which the title cannot see. - // T:'s scratch folder is the exception: it creates its parent folders, as merged with RT-218. - const bool scratch = !parts.empty() && same_name(parts.front().c_str(), kScratchDir); - if (!scratch && !is_folder(r, parent_of(parts))) return fail(ERROR_PATH_NOT_FOUND); - - Target t; - t.path = disk_path(r.overlay, parts); - - std::error_code ec; - std::filesystem::create_directories(t.path.parent_path(), ec); - if (ec) { - t.error = static_cast(ec.value()); - return t; - } - - // A deleted package file is not there to copy: copying it up would bring the name back, and an open that keeps - // the contents (OPEN_EXISTING, TRUNCATE_EXISTING) has to fail on it instead. CREATE_ALWAYS and CREATE_NEW still - // make a new overlay file, which reads prefer over the package and so over the marker. - const std::filesystem::path package_path = disk_path(r.game, parts); - // One copy-up at a time: a second thread writing the same file waits here and then finds the first one's copy, so - // it neither fails on the taken name nor collides with that file's open through a rename of its own. - static std::mutex s_copy_mutex; - std::unique_lock copy_lock(s_copy_mutex, std::defer_lock); - if (copy_up) copy_lock.lock(); - if (copy_up && !deleted(r.overlay, parts) && !std::filesystem::exists(t.path, ec) && - std::filesystem::is_regular_file(package_path, ec)) { - // Copied to a private name, then renamed into place: a process killed mid-copy leaves only a hidden leftover, - // not a truncated file that reads would prefer over the package. - static unsigned s_copies = 0; // under s_copy_mutex - const std::filesystem::path staging = r.overlay / kCopyDir; - std::filesystem::create_directories(win32_io_path(staging), ec); - const std::filesystem::path tmp = - win32_io_path(staging / (std::to_wstring(::GetCurrentProcessId()) + L"-" + std::to_wstring(++s_copies))); - // Use CopyFileW for staging because MSVC's std::filesystem::copy_file calls CopyFile2, which Wine 9 lacks. - if (ec) { - t.error = static_cast(ec.value()); - } else if (!::CopyFileW(package_path.c_str(), tmp.c_str(), FALSE)) { - t.error = ::GetLastError(); - } - if (t.error) { - std::filesystem::remove(tmp, ec); - return t; - } - if (!::MoveFileExW(tmp.c_str(), t.path.c_str(), 0)) { - // The name taken means the title created the file itself meanwhile (CREATE_NEW and CREATE_ALWAYS don't - // copy up, so they don't take the lock); that file is what it wrote, so keep it. - const DWORD error = ::GetLastError(); - std::filesystem::remove(tmp, ec); - if (!std::filesystem::exists(t.path, ec)) t.error = error; - } - } - return t; -} - -// MAXIMUM_ALLOWED names no right and grants every one the file allows, write included, so it is a write-open: opened -// as a read it handed out a handle to the package file itself, and a WriteFile through it changed the package. -bool writes(DWORD access, DWORD disposition) { - constexpr DWORD kWriteAccess = GENERIC_WRITE | GENERIC_ALL | MAXIMUM_ALLOWED | FILE_WRITE_DATA | FILE_APPEND_DATA | - FILE_WRITE_EA | FILE_WRITE_ATTRIBUTES | DELETE | WRITE_DAC | WRITE_OWNER; - if ((access & kWriteAccess) != 0) return true; - return disposition == CREATE_NEW || disposition == CREATE_ALWAYS || disposition == OPEN_ALWAYS || - disposition == TRUNCATE_EXISTING; -} - -Target open_target(const std::wstring& path, DWORD access, DWORD disposition) { - if (!writes(access, disposition)) return read_target(path); - // OPEN_ALWAYS and TRUNCATE_EXISTING read what is already there, and a write-open must not lose a package file's - // bytes; CREATE_ALWAYS and CREATE_NEW replace it. - const bool keeps_contents = - disposition == OPEN_EXISTING || disposition == OPEN_ALWAYS || disposition == TRUNCATE_EXISTING; - return write_target(path, keeps_contents); -} - -// MAXIMUM_ALLOWED grants read and write where the file allows them, but names neither. A host that picks how to open -// the file from the rights named hands out a handle that cannot write: under Wine 9.0 and 11.0 a WriteFile through a -// MAXIMUM_ALLOWED | GENERIC_READ handle failed (file_system, run 45457013232). Naming both next to it asks every host -// for the handle Windows gives. Where the file refuses one of them, the title's own access word is tried as it came. -template -HANDLE open_naming_maximum_allowed(DWORD access, Open open) { - if (access & MAXIMUM_ALLOWED) { - const HANDLE h = open(access | GENERIC_READ | GENERIC_WRITE); - if (h != INVALID_HANDLE_VALUE || GetLastError() != ERROR_ACCESS_DENIED) return h; - } - return open(access); -} - -// ---- FindFirstFile: the overlay and the package merged into one listing -// -// The host enumerates each folder; the results are merged here, overlay first, so a name that exists in both appears -// once with the overlay's times and size, a name the title deleted does not appear at all, and the overlay's marker -// folder never does. -struct Enumeration { - std::vector entries; - size_t next = 0; -}; - -std::mutex g_enum_mutex; -std::map> g_enumerations; // keyed by the pseudo-handle handed to the title - -HANDLE register_enumeration(std::unique_ptr e) { - std::lock_guard lock(g_enum_mutex); - const HANDLE h = reinterpret_cast(e.get()); - g_enumerations.emplace(h, std::move(e)); - return h; -} - -bool unregister_enumeration(HANDLE h) { - std::lock_guard lock(g_enum_mutex); - return g_enumerations.erase(h) != 0; -} - -bool collect(const std::wstring& pattern, const std::vector& parts, std::vector& out, - DWORD& error) { - // "GAME:" and "GAME:\\dir\\" name the folder itself: list everything in it. - std::vector dirs; - std::wstring leaf; - const bool trailing_separator = !pattern.empty() && (pattern.back() == L'\\' || pattern.back() == L'/'); - if (parts.empty() || trailing_separator) { - dirs = parts; - leaf = L"*"; - } else { - dirs.assign(parts.begin(), parts.end() - 1); - leaf = parts.back(); - } - - const Roots r = roots(); - if (r.game.empty()) { - error = ERROR_PATH_NOT_FOUND; - return false; - } - // The folder being listed has to exist in the title's view. The host would still enumerate a package folder the - // title removed (its "." and ".."), and a folder that is missing is a missing path, not a missing file. A listing - // below a file is a third answer on the host, ERROR_DIRECTORY. - const Kind listed = view(r, dirs).kind; - if (listed != Kind::Directory) { - error = listed == Kind::File ? ERROR_DIRECTORY : ERROR_PATH_NOT_FOUND; - return false; - } - - // Every deletion marker for an entry of this folder lives inside its marker folder, so that folder is read once - // instead of probing it twice per package entry (deleted()). An entry is deleted when its marker is a file, or a - // folder holding kRemovedDirMarker: the rule deleted() applies. The lookup folds ASCII letters only, which matches - // the file system's case-insensitive compare exactly when both names are ASCII. Any other name, a non-ASCII entry - // or a marker that is not plain ASCII or is a reparse point, goes through deleted() and the file system's rule. - auto ascii = [](const wchar_t* s) { - for (; *s; ++s) - if (*s > 0x7f) return false; - return true; - }; - auto ascii_key = [](const wchar_t* s) { - std::wstring k = s; - for (auto& c : k) - if (c >= L'A' && c <= L'Z') c = static_cast(c - L'A' + L'a'); - return k; - }; - bool has_markers = false; - bool markers_exact = true; - std::unordered_set deleted_here; - if (!r.overlay.empty()) { - const std::filesystem::path marks = marker(r.overlay, dirs); - WIN32_FIND_DATAW m{}; - const HANDLE mh = ::FindFirstFileW(win32_io_path(marks / L"*").c_str(), &m); - if (mh != INVALID_HANDLE_VALUE) { - has_markers = true; - do { - if (same_name(m.cFileName, L".") || same_name(m.cFileName, L"..")) continue; - if (!ascii(m.cFileName) || (m.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT)) { - markers_exact = false; - continue; - } - if (!(m.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)) { - deleted_here.insert(ascii_key(m.cFileName)); - continue; - } - // A marker folder is a removed folder only with kRemovedDirMarker in it; without one it just holds the - // markers of a nested delete. A missing sentinel is that ordinary answer (status() reports not_found - // with an error code set); any other error leaves the decision to deleted() per entry. - std::error_code ec; - const auto st = std::filesystem::status(win32_io_path(marks / m.cFileName / kRemovedDirMarker), ec); - if (st.type() == std::filesystem::file_type::regular) deleted_here.insert(ascii_key(m.cFileName)); - else if (st.type() != std::filesystem::file_type::not_found && ec) markers_exact = false; - } while (::FindNextFileW(mh, &m)); - if (::GetLastError() != ERROR_NO_MORE_FILES) markers_exact = false; // an incomplete scan - ::FindClose(mh); - } else { - // Only a missing marker folder means "nothing deleted here". Any other failure (a folder that cannot be - // listed although its markers can be queried by path, for one) leaves the decision to deleted(). - const DWORD e = ::GetLastError(); - if (e != ERROR_FILE_NOT_FOUND && e != ERROR_PATH_NOT_FOUND) { - has_markers = true; - markers_exact = false; - } - } - } - auto entry_deleted = [&](const wchar_t* name) { - if (!has_markers) return false; - if (markers_exact && ascii(name)) return deleted_here.count(ascii_key(name)) != 0; - std::vector entry_parts = dirs; - entry_parts.push_back(name); - return deleted(r.overlay, entry_parts); - }; - // Names already listed, ordered by _wcsicmp itself, so two names are one entry exactly when same_name says so, in - // whatever locale the title set (a lower-cased key is not: under .UTF-8 _wcslwr_s folds É and é, _wcsicmp not). - struct NoCase { - bool operator()(const std::wstring& a, const std::wstring& b) const { return _wcsicmp(a.c_str(), b.c_str()) < 0; } - }; - std::set seen; - for (const auto& e : out) seen.insert(e.cFileName); - - auto add_root = [&](const std::filesystem::path& root, bool overlay_root) { - if (root.empty()) return; - WIN32_FIND_DATAW found{}; - const HANDLE h = ::FindFirstFileW(win32_find_path(join(root, dirs) / leaf, leaf).c_str(), &found); - if (h == INVALID_HANDLE_VALUE) return; - do { - if (overlay_root && internal_dir(found.cFileName)) continue; - const bool dot = same_name(found.cFileName, L".") || same_name(found.cFileName, L".."); - if (!overlay_root && !dot && entry_deleted(found.cFileName)) continue; - if (seen.insert(found.cFileName).second) out.push_back(found); - } while (::FindNextFileW(h, &found)); - ::FindClose(h); - }; - add_root(r.overlay, true); - add_root(r.game, false); - - if (out.empty()) { - error = ERROR_FILE_NOT_FOUND; - return false; - } - return true; -} - -void to_ansi(const WIN32_FIND_DATAW& wide, WIN32_FIND_DATAA* ansi) { - *ansi = WIN32_FIND_DATAA{}; - ansi->dwFileAttributes = wide.dwFileAttributes; - ansi->ftCreationTime = wide.ftCreationTime; - ansi->ftLastAccessTime = wide.ftLastAccessTime; - ansi->ftLastWriteTime = wide.ftLastWriteTime; - ansi->nFileSizeHigh = wide.nFileSizeHigh; - ansi->nFileSizeLow = wide.nFileSizeLow; - ansi->dwReserved0 = wide.dwReserved0; - ansi->dwReserved1 = wide.dwReserved1; - narrow_ansi(wide.cFileName, ansi->cFileName, MAX_PATH); - narrow_ansi(wide.cAlternateFileName, ansi->cAlternateFileName, 14); -} - -} // namespace - -void configure(const std::filesystem::path& game_dir, const std::filesystem::path& overlay_dir) { - std::lock_guard lock(g_mutex); - g_game_dir = game_dir; - g_overlay_dir = overlay_dir; -} - -std::filesystem::path game_dir() { - std::lock_guard lock(g_mutex); - return g_game_dir; -} - -std::filesystem::path overlay_dir() { - std::lock_guard lock(g_mutex); - return g_overlay_dir; -} - -// gta6rt --trace FILE: a failed open of a guest path goes to the startup trace as a "file_open_failed" event (the -// path the title passed, the Win32 error, the caller as module+RVA), so a boot that stops on a missing or refused -// file names it. Failures only, and at most 256 of them, so a title probing many optional files can't fill the file. -void note_open_failure(const char* api, LPCWSTR name, DWORD error, const void* caller) { - if (!rt::startup_trace::enabled()) return; - static std::atomic left{256}; - if (left.fetch_sub(1, std::memory_order_relaxed) <= 0) return; - std::string utf8; - if (const int n = WideCharToMultiByte(CP_UTF8, 0, name, -1, nullptr, 0, nullptr, nullptr); n > 1) { - utf8.resize(static_cast(n) - 1); - WideCharToMultiByte(CP_UTF8, 0, name, -1, utf8.data(), n, nullptr, nullptr); - } - rt::startup_trace::event( - "file_open_failed", - std::string("\"api\":\"") + api + "\",\"path\":" + rt::startup_trace::quote(utf8) + - ",\"error\":" + std::to_string(error) + ",\"caller\":" + - rt::startup_trace::quote(rt::startup_trace::where(reinterpret_cast(caller)))); -} - -HANDLE WINAPI create_file_w(LPCWSTR name, DWORD access, DWORD share, LPSECURITY_ATTRIBUTES attributes, - DWORD disposition, DWORD flags, HANDLE template_file) { - if (!name) { - SetLastError(ERROR_INVALID_PARAMETER); - return INVALID_HANDLE_VALUE; - } - const Target t = open_target(name, access, disposition); - if (t.error) { - note_open_failure("CreateFileW", name, t.error, _ReturnAddress()); - SetLastError(t.error); - return INVALID_HANDLE_VALUE; - } - const HANDLE h = open_naming_maximum_allowed(access, [&](DWORD named) { - return ::CreateFileW(t.path.c_str(), named, share, attributes, disposition, flags, template_file); - }); - if (h == INVALID_HANDLE_VALUE) { - const DWORD error = GetLastError(); - note_open_failure("CreateFileW", name, error, _ReturnAddress()); - SetLastError(error); - } - return h; -} - -HANDLE WINAPI create_file_a(LPCSTR name, DWORD access, DWORD share, LPSECURITY_ATTRIBUTES attributes, - DWORD disposition, DWORD flags, HANDLE template_file) { - if (!name) { - SetLastError(ERROR_INVALID_PARAMETER); - return INVALID_HANDLE_VALUE; - } - const std::wstring wide = widen_ansi(name); - return create_file_w(wide.c_str(), access, share, attributes, disposition, flags, template_file); -} - -HANDLE WINAPI create_file2(LPCWSTR name, DWORD access, DWORD share, DWORD disposition, - LPCREATEFILE2_EXTENDED_PARAMETERS params) { - if (!name) { - SetLastError(ERROR_INVALID_PARAMETER); - return INVALID_HANDLE_VALUE; - } - const Target t = open_target(name, access, disposition); - if (t.error) { - note_open_failure("CreateFile2", name, t.error, _ReturnAddress()); - SetLastError(t.error); - return INVALID_HANDLE_VALUE; - } - const HANDLE h = open_naming_maximum_allowed(access, [&](DWORD named) { - return ::CreateFile2(t.path.c_str(), named, share, disposition, params); - }); - if (h == INVALID_HANDLE_VALUE) { - const DWORD error = GetLastError(); - note_open_failure("CreateFile2", name, error, _ReturnAddress()); - SetLastError(error); - } - return h; -} - -DWORD WINAPI get_file_attributes_w(LPCWSTR name) { - if (!name) { - SetLastError(ERROR_INVALID_PARAMETER); - return INVALID_FILE_ATTRIBUTES; - } - const Target t = read_target(name); - if (t.error) { - SetLastError(t.error); - return INVALID_FILE_ATTRIBUTES; - } - return ::GetFileAttributesW(t.path.c_str()); -} - -DWORD WINAPI get_file_attributes_a(LPCSTR name) { - if (!name) { - SetLastError(ERROR_INVALID_PARAMETER); - return INVALID_FILE_ATTRIBUTES; - } - const std::wstring wide = widen_ansi(name); - return get_file_attributes_w(wide.c_str()); -} - -BOOL WINAPI get_file_attributes_ex_w(LPCWSTR name, GET_FILEEX_INFO_LEVELS level, LPVOID info) { - if (!name || !info) { - SetLastError(ERROR_INVALID_PARAMETER); - return FALSE; - } - const Target t = read_target(name); - if (t.error) { - SetLastError(t.error); - return FALSE; - } - return ::GetFileAttributesExW(t.path.c_str(), level, info); -} - -BOOL WINAPI get_file_attributes_ex_a(LPCSTR name, GET_FILEEX_INFO_LEVELS level, LPVOID info) { - if (!name || !info) { - SetLastError(ERROR_INVALID_PARAMETER); - return FALSE; - } - const std::wstring wide = widen_ansi(name); - return get_file_attributes_ex_w(wide.c_str(), level, info); -} - -HANDLE WINAPI find_first_file_w(LPCWSTR pattern, LPWIN32_FIND_DATAW data) { - if (!pattern || !data) { - SetLastError(ERROR_INVALID_PARAMETER); - return INVALID_HANDLE_VALUE; - } - std::vector parts; - const Parsed parsed = parse_console(pattern, parts); - if (parsed == Parsed::Host) return ::FindFirstFileW(pattern, data); - if (parsed == Parsed::Refused) { - SetLastError(ERROR_INVALID_NAME); - return INVALID_HANDLE_VALUE; - } - - std::vector entries; - DWORD error = 0; - if (!collect(pattern, parts, entries, error)) { - SetLastError(error); - return INVALID_HANDLE_VALUE; - } - auto e = std::make_unique(); - e->entries = std::move(entries); - e->next = 1; - *data = e->entries[0]; - return register_enumeration(std::move(e)); -} - -HANDLE WINAPI find_first_file_ex_w(LPCWSTR pattern, FINDEX_INFO_LEVELS info_level, LPVOID data, - FINDEX_SEARCH_OPS search_op, LPVOID search_filter, DWORD additional_flags) { - if (!pattern || !data) { - SetLastError(ERROR_INVALID_PARAMETER); - return INVALID_HANDLE_VALUE; - } - std::vector parts; - const Parsed parsed = parse_console(pattern, parts); - if (parsed == Parsed::Host) - return ::FindFirstFileExW(pattern, info_level, data, search_op, search_filter, additional_flags); - if (parsed == Parsed::Refused) { - SetLastError(ERROR_INVALID_NAME); - return INVALID_HANDLE_VALUE; - } - if (info_level != FindExInfoStandard && info_level != FindExInfoBasic) { - SetLastError(ERROR_INVALID_PARAMETER); - return INVALID_HANDLE_VALUE; - } - if (search_op != FindExSearchNameMatch && search_op != FindExSearchLimitToDirectories) { - SetLastError(ERROR_INVALID_PARAMETER); - return INVALID_HANDLE_VALUE; - } - - std::vector entries; - DWORD error = 0; - if (!collect(pattern, parts, entries, error)) { - SetLastError(error); - return INVALID_HANDLE_VALUE; - } - if (search_op == FindExSearchLimitToDirectories) { - std::vector dirs_only; - for (auto& entry : entries) - if ((entry.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) != 0) dirs_only.push_back(entry); - entries = std::move(dirs_only); - if (entries.empty()) { - SetLastError(ERROR_FILE_NOT_FOUND); - return INVALID_HANDLE_VALUE; - } - } - if (info_level == FindExInfoBasic) { - for (auto& entry : entries) entry.cAlternateFileName[0] = L'\0'; - } - auto e = std::make_unique(); - e->entries = std::move(entries); - e->next = 1; - *static_cast(data) = e->entries[0]; - return register_enumeration(std::move(e)); -} - -HANDLE WINAPI find_first_file_ex_a(LPCSTR pattern, FINDEX_INFO_LEVELS info_level, LPVOID data, - FINDEX_SEARCH_OPS search_op, LPVOID search_filter, DWORD additional_flags) { - if (!pattern || !data) { - SetLastError(ERROR_INVALID_PARAMETER); - return INVALID_HANDLE_VALUE; - } - const std::wstring wide = widen_ansi(pattern); - std::vector parts; - const Parsed parsed = parse_console(wide, parts); - if (parsed == Parsed::Host) - return ::FindFirstFileExA(pattern, info_level, data, search_op, search_filter, additional_flags); - WIN32_FIND_DATAW wide_data{}; - const HANDLE h = find_first_file_ex_w(wide.c_str(), info_level, &wide_data, search_op, search_filter, additional_flags); - if (h != INVALID_HANDLE_VALUE) to_ansi(wide_data, static_cast(data)); - return h; -} - -HANDLE WINAPI find_first_file_a(LPCSTR pattern, LPWIN32_FIND_DATAA data) { - if (!pattern || !data) { - SetLastError(ERROR_INVALID_PARAMETER); - return INVALID_HANDLE_VALUE; - } - const std::wstring wide = widen_ansi(pattern); - WIN32_FIND_DATAW found{}; - const HANDLE h = find_first_file_w(wide.c_str(), &found); - if (h != INVALID_HANDLE_VALUE) to_ansi(found, data); - return h; -} - -BOOL WINAPI find_next_file_w(HANDLE find, LPWIN32_FIND_DATAW data) { - if (!find || !data) { - SetLastError(ERROR_INVALID_PARAMETER); - return FALSE; - } - { - std::lock_guard lock(g_enum_mutex); - const auto it = g_enumerations.find(find); - if (it != g_enumerations.end()) { - Enumeration& e = *it->second; - if (e.next >= e.entries.size()) { - SetLastError(ERROR_NO_MORE_FILES); - return FALSE; - } - *data = e.entries[e.next++]; - SetLastError(ERROR_SUCCESS); - return TRUE; - } - } - return ::FindNextFileW(find, data); // a host listing -} - -BOOL WINAPI find_next_file_a(HANDLE find, LPWIN32_FIND_DATAA data) { - if (!find || !data) { - SetLastError(ERROR_INVALID_PARAMETER); - return FALSE; - } - WIN32_FIND_DATAW found{}; - const BOOL ok = find_next_file_w(find, &found); - if (ok) to_ansi(found, data); - return ok; -} - -BOOL WINAPI find_close(HANDLE find) { - if (!find) { - SetLastError(ERROR_INVALID_HANDLE); - return FALSE; - } - if (unregister_enumeration(find)) return TRUE; - return ::FindClose(find); -} - -BOOL WINAPI delete_file_w(LPCWSTR name) { - if (!name) { - SetLastError(ERROR_INVALID_PARAMETER); - return FALSE; - } - std::vector parts; - const Parsed parsed = parse_console(name, parts); - if (parsed == Parsed::Host) return ::DeleteFileW(name); - if (parsed == Parsed::Refused) { - SetLastError(ERROR_INVALID_NAME); - return FALSE; - } - - const Roots r = roots(); - if (r.overlay.empty() || parts.empty()) { - SetLastError(ERROR_INVALID_NAME); - return FALSE; - } - - bool removed = false; - std::error_code ec; - const std::filesystem::path overlay_path = disk_path(r.overlay, parts); - if (std::filesystem::exists(overlay_path, ec)) { - if (!::DeleteFileW(overlay_path.c_str())) return FALSE; - removed = true; - } - if (!r.game.empty() && !deleted(r.overlay, parts)) { - const std::filesystem::path package_path = disk_path(r.game, parts); - if (std::filesystem::exists(package_path, ec)) { - if (std::filesystem::is_directory(package_path, ec)) { - SetLastError(ERROR_ACCESS_DENIED); - return FALSE; - } - // The overlay delete already checked its own attributes. Without an overlay, the package file's - // read-only bit still applies even though deletion only writes a marker instead of deleting that file. - if (!removed) { - const DWORD attributes = ::GetFileAttributesW(package_path.c_str()); - if (attributes != INVALID_FILE_ATTRIBUTES && (attributes & FILE_ATTRIBUTE_READONLY) != 0) - return fail_bool(ERROR_ACCESS_DENIED); - } - // The package file stays where it is; the marker is what hides it. - DWORD error = 0; - if (!write_marker(marker(r.overlay, parts), error)) return fail_bool(error); - removed = true; - } - } - if (!removed) { - SetLastError(ERROR_FILE_NOT_FOUND); - return FALSE; - } - return TRUE; -} - -BOOL WINAPI delete_file_a(LPCSTR name) { - if (!name) { - SetLastError(ERROR_INVALID_PARAMETER); - return FALSE; - } - const std::wstring wide = widen_ansi(name); - return delete_file_w(wide.c_str()); -} - -// ---- Folders: created in the overlay, removed by a marker when the package has them - -namespace { - -BOOL create_directory(LPCWSTR template_name, LPCWSTR name, LPSECURITY_ATTRIBUTES security) { - if (!name) return fail_bool(ERROR_INVALID_PARAMETER); - std::wstring template_path; - if (template_name) { - const Target t = read_target(template_name); - if (t.error) return fail_bool(t.error); - template_path = t.path.wstring(); - } - std::vector parts; - const Parsed parsed = parse_console(name, parts); - if (parsed == Parsed::Host) - return template_name ? ::CreateDirectoryExW(template_path.c_str(), name, security) - : ::CreateDirectoryW(name, security); - if (parsed == Parsed::Refused) return fail_bool(ERROR_INVALID_NAME); - - const Roots r = roots(); - if (r.game.empty() || r.overlay.empty()) return fail_bool(ERROR_PATH_NOT_FOUND); - if (view(r, parts).kind != Kind::None) return fail_bool(ERROR_ALREADY_EXISTS); // "GAME:" included - if (!is_folder(r, parent_of(parts))) return fail_bool(ERROR_PATH_NOT_FOUND); - - const std::filesystem::path target = disk_path(r.overlay, parts); - std::error_code ec; - std::filesystem::create_directories(target.parent_path(), ec); - if (ec) return fail_bool(static_cast(ec.value())); - const BOOL created = template_name ? ::CreateDirectoryExW(template_path.c_str(), target.c_str(), security) - : ::CreateDirectoryW(target.c_str(), security); - if (created) { - // Keep markers for deleted children, which must remain hidden after the folder is recreated. - std::filesystem::remove(marker(r.overlay, parts) / kRemovedDirMarker, ec); - if (ec) { - const DWORD error = static_cast(ec.value()); - ::RemoveDirectoryW(target.c_str()); - return fail_bool(error); - } - } - return created; -} - -} // namespace - -BOOL WINAPI create_directory_w(LPCWSTR name, LPSECURITY_ATTRIBUTES security) { - return create_directory(nullptr, name, security); -} - -BOOL WINAPI create_directory_a(LPCSTR name, LPSECURITY_ATTRIBUTES security) { - if (!name) return fail_bool(ERROR_INVALID_PARAMETER); - const std::wstring wide = widen_ansi(name); - return create_directory(nullptr, wide.c_str(), security); -} - -BOOL WINAPI create_directory_ex_w(LPCWSTR template_name, LPCWSTR name, LPSECURITY_ATTRIBUTES security) { - if (!template_name) return fail_bool(ERROR_INVALID_PARAMETER); - return create_directory(template_name, name, security); -} - -BOOL WINAPI create_directory_ex_a(LPCSTR template_name, LPCSTR name, LPSECURITY_ATTRIBUTES security) { - if (!template_name || !name) return fail_bool(ERROR_INVALID_PARAMETER); - const std::wstring wide_template = widen_ansi(template_name), wide = widen_ansi(name); - return create_directory(wide_template.c_str(), wide.c_str(), security); -} - -BOOL WINAPI remove_directory_w(LPCWSTR name) { - if (!name) return fail_bool(ERROR_INVALID_PARAMETER); - std::vector parts; - const Parsed parsed = parse_console(name, parts); - if (parsed == Parsed::Host) return ::RemoveDirectoryW(name); - if (parsed == Parsed::Refused) return fail_bool(ERROR_INVALID_NAME); - - const Roots r = roots(); - if (r.game.empty() || r.overlay.empty()) return fail_bool(ERROR_PATH_NOT_FOUND); - if (drive_root(name, parts)) return fail_bool(ERROR_ACCESS_DENIED); // "GAME:" and "T:" themselves stay - const View v = view(r, parts); - if (v.kind == Kind::None) return fail_bool(ERROR_FILE_NOT_FOUND); - if (v.kind == Kind::File) return fail_bool(ERROR_DIRECTORY); - if (!empty_in_view(r, parts)) return fail_bool(ERROR_DIR_NOT_EMPTY); - - if (v.in_overlay && !::RemoveDirectoryW(disk_path(r.overlay, parts).c_str())) return FALSE; // its error - if (v.in_package) { - // The package folder stays where it is; the marker hides it, and its files are already hidden one by one. - DWORD error = 0; - if (!write_marker(marker(r.overlay, parts) / kRemovedDirMarker, error)) return fail_bool(error); - } - return TRUE; -} - -BOOL WINAPI remove_directory_a(LPCSTR name) { - if (!name) return fail_bool(ERROR_INVALID_PARAMETER); - const std::wstring wide = widen_ansi(name); - return remove_directory_w(wide.c_str()); -} - -// ---- Move, copy and attributes: the result lands in the overlay, a moved package name is deleted by a marker - -BOOL WINAPI move_file_ex_w(LPCWSTR from, LPCWSTR to, DWORD flags) { - if (!from) return fail_bool(ERROR_INVALID_PARAMETER); - std::vector src, dst; - const Parsed from_kind = parse_console(from, src); - const Parsed to_kind = to ? parse_console(to, dst) : Parsed::Host; - if (from_kind == Parsed::Host && to_kind == Parsed::Host) return ::MoveFileExW(from, to, flags); - if (from_kind == Parsed::Refused || to_kind == Parsed::Refused) return fail_bool(ERROR_INVALID_NAME); - // A boot-time move or delete is a host feature a title cannot use on the console's drives. - if (!to || (flags & MOVEFILE_DELAY_UNTIL_REBOOT) != 0) return fail_bool(ERROR_INVALID_PARAMETER); - // GAME: is its own volume: a move between it and a host path is refused the way a cross-volume move is. - if (from_kind != to_kind) return fail_bool(ERROR_NOT_SAME_DEVICE); - - const Roots r = roots(); - if (r.game.empty() || r.overlay.empty()) return fail_bool(ERROR_PATH_NOT_FOUND); - if (drive_root(from, src) || drive_root(to, dst)) return fail_bool(ERROR_ACCESS_DENIED); - const View from_view = view(r, src); - if (from_view.kind == Kind::None) return fail_bool(ERROR_FILE_NOT_FOUND); - const std::filesystem::path overlay_from = disk_path(r.overlay, src), overlay_to = disk_path(r.overlay, dst); - if (same_entry(src, dst)) { - // The destination is the source, so it is not "already there". The host succeeds at a move onto the same - // name and changes nothing, and renames when only the case differs. Here the case of a name is the overlay's - // when the overlay holds it, so a package file gets an overlay copy under the new spelling (no marker: the - // listing takes the overlay's entry and skips the package's as the same name); a package folder is left - // where it is, as for any other move of one. - if (src == dst) return TRUE; - if (from_view.kind == Kind::Directory && from_view.in_package) return fail_bool(ERROR_ACCESS_DENIED); - if (from_view.in_overlay) - return ::MoveFileExW(overlay_from.c_str(), overlay_to.c_str(), flags & MOVEFILE_WRITE_THROUGH); - std::error_code same_ec; - std::filesystem::create_directories(overlay_to.parent_path(), same_ec); - if (same_ec) return fail_bool(static_cast(same_ec.value())); - if (!::CopyFileW(disk_path(r.game, src).c_str(), overlay_to.c_str(), TRUE)) return FALSE; - DWORD flush_error = 0; - if ((flags & MOVEFILE_WRITE_THROUGH) != 0 && !flush_file(overlay_to, flush_error)) return fail_bool(flush_error); - return TRUE; - } - - const View to_view = view(r, dst); - if (to_view.kind == Kind::Directory) return fail_bool(ERROR_ACCESS_DENIED); - if (to_view.kind == Kind::File && (flags & MOVEFILE_REPLACE_EXISTING) == 0) return fail_bool(ERROR_ALREADY_EXISTS); - if (!is_folder(r, parent_of(dst))) return fail_bool(ERROR_PATH_NOT_FOUND); - - std::error_code ec; - std::filesystem::create_directories(overlay_to.parent_path(), ec); - if (ec) return fail_bool(static_cast(ec.value())); - - if (from_view.kind == Kind::Directory) { - // A package folder is left where it is (as DeleteFile does); an overlay-only folder is renamed in place. - if (from_view.in_package) return fail_bool(ERROR_ACCESS_DENIED); - if (to_view.kind != Kind::None) return fail_bool(ERROR_ACCESS_DENIED); - return ::MoveFileExW(overlay_from.c_str(), overlay_to.c_str(), flags & MOVEFILE_WRITE_THROUGH); - } - - const bool write_through = (flags & MOVEFILE_WRITE_THROUGH) != 0; - const DWORD keep = flags & (MOVEFILE_REPLACE_EXISTING | MOVEFILE_WRITE_THROUGH); - DWORD error = 0; - if (from_view.in_overlay) { - if (!::MoveFileExW(overlay_from.c_str(), overlay_to.c_str(), keep | MOVEFILE_COPY_ALLOWED)) return FALSE; - } else { - // The host never sees a move here, only a copy and a marker, so MOVEFILE_WRITE_THROUGH is honoured by - // flushing both before returning, as MoveFileEx does for its own copy and delete. - const BOOL fail_if_exists = (flags & MOVEFILE_REPLACE_EXISTING) == 0; - if (!::CopyFileW(disk_path(r.game, src).c_str(), overlay_to.c_str(), fail_if_exists)) return FALSE; - if (write_through && !flush_file(overlay_to, error)) return fail_bool(error); - } - if (from_view.in_package) { - const std::filesystem::path mark = marker(r.overlay, src); - if (!write_marker(mark, error)) return fail_bool(error); - if (write_through && !flush_file(mark, error)) return fail_bool(error); - } - return TRUE; -} - -BOOL WINAPI move_file_w(LPCWSTR from, LPCWSTR to) { - if (!from || !to) return fail_bool(ERROR_INVALID_PARAMETER); - return move_file_ex_w(from, to, MOVEFILE_COPY_ALLOWED); // MoveFile moves files across volumes -} - -BOOL WINAPI move_file_ex_a(LPCSTR from, LPCSTR to, DWORD flags) { - if (!from) return fail_bool(ERROR_INVALID_PARAMETER); - const std::wstring wide_from = widen_ansi(from), wide_to = to ? widen_ansi(to) : std::wstring(); - return move_file_ex_w(wide_from.c_str(), to ? wide_to.c_str() : nullptr, flags); -} - -BOOL WINAPI move_file_a(LPCSTR from, LPCSTR to) { - if (!from || !to) return fail_bool(ERROR_INVALID_PARAMETER); - return move_file_ex_a(from, to, MOVEFILE_COPY_ALLOWED); -} - -namespace { - -// Where a copy writes: a host path as given; a GAME: path is checked against the title's view (an existing name -// counts even when only the package has it) and then means its overlay copy. -bool copy_destination(LPCWSTR to, bool fail_if_exists, std::filesystem::path& out, DWORD& error) { - std::vector parts; - const Parsed parsed = parse_console(to, parts); - if (parsed == Parsed::Host) { - out = std::filesystem::path(to); - return true; - } - error = ERROR_INVALID_NAME; - if (parsed == Parsed::Refused || parts.empty()) return false; - const Roots r = roots(); - error = ERROR_PATH_NOT_FOUND; - if (r.game.empty() || r.overlay.empty()) return false; - const View v = view(r, parts); - error = ERROR_ACCESS_DENIED; - if (v.kind == Kind::Directory) return false; - error = ERROR_FILE_EXISTS; - if (v.kind == Kind::File && fail_if_exists) return false; - error = ERROR_PATH_NOT_FOUND; - if (!is_folder(r, parent_of(parts))) return false; - out = disk_path(r.overlay, parts); - std::error_code ec; - std::filesystem::create_directories(out.parent_path(), ec); - if (ec) { - error = static_cast(ec.value()); - return false; - } - error = 0; - return true; -} - -// The source and destination a copy opens, or the error it fails with. -bool copy_paths(LPCWSTR from, LPCWSTR to, bool fail_if_exists, std::filesystem::path& source, - std::filesystem::path& destination, DWORD& error) { - if (!from || !to) { - error = ERROR_INVALID_PARAMETER; - return false; - } - const Target t = read_target(from); - if (t.error) { - error = t.error; - return false; - } - source = t.path; - return copy_destination(to, fail_if_exists, destination, error); -} - -} // namespace - -BOOL WINAPI copy_file_w(LPCWSTR from, LPCWSTR to, BOOL fail_if_exists) { - std::filesystem::path source, destination; - DWORD error = 0; - if (!copy_paths(from, to, fail_if_exists != FALSE, source, destination, error)) return fail_bool(error); - return ::CopyFileW(source.c_str(), destination.c_str(), fail_if_exists); -} - -BOOL WINAPI copy_file_a(LPCSTR from, LPCSTR to, BOOL fail_if_exists) { - if (!from || !to) return fail_bool(ERROR_INVALID_PARAMETER); - const std::wstring wide_from = widen_ansi(from), wide_to = widen_ansi(to); - return copy_file_w(wide_from.c_str(), wide_to.c_str(), fail_if_exists); -} - -BOOL WINAPI copy_file_ex_w(LPCWSTR from, LPCWSTR to, LPPROGRESS_ROUTINE progress, LPVOID data, LPBOOL cancel, - DWORD flags) { - std::filesystem::path source, destination; - DWORD error = 0; - if (!copy_paths(from, to, (flags & COPY_FILE_FAIL_IF_EXISTS) != 0, source, destination, error)) - return fail_bool(error); - return ::CopyFileExW(source.c_str(), destination.c_str(), progress, data, cancel, flags); -} - -BOOL WINAPI copy_file_ex_a(LPCSTR from, LPCSTR to, LPPROGRESS_ROUTINE progress, LPVOID data, LPBOOL cancel, - DWORD flags) { - if (!from || !to) return fail_bool(ERROR_INVALID_PARAMETER); - const std::wstring wide_from = widen_ansi(from), wide_to = widen_ansi(to); - return copy_file_ex_w(wide_from.c_str(), wide_to.c_str(), progress, data, cancel, flags); -} - -namespace { - -// The host's CopyFile2, or null where the host has none. Wine 9's kernel32 and kernelbase don't export it: Wine's -// loader binds a static import of it to a stub that aborts the process when called ("unimplemented function -// KERNEL32.dll.CopyFile2, aborting"), so a direct ::CopyFile2 call (or MSVC's std::filesystem::copy_file, which uses -// it) kills a title under Wine 9 or a Proton built on it; pe_loader.cpp and loader_tls_test.cpp avoid it for the same -// reason. GetProcAddress returns null there instead, and the fallback below runs. -using CopyFile2Fn = HRESULT(WINAPI*)(PCWSTR, PCWSTR, COPYFILE2_EXTENDED_PARAMETERS*); -std::atomic g_force_copy_file2_fallback{false}; - -CopyFile2Fn host_copy_file2() { - static const CopyFile2Fn fn = [] { - for (const wchar_t* dll : {L"kernelbase.dll", L"kernel32.dll"}) { - if (const HMODULE module = GetModuleHandleW(dll)) - if (const FARPROC p = GetProcAddress(module, "CopyFile2")) return reinterpret_cast(p); - } - return CopyFile2Fn{}; - }(); - return g_force_copy_file2_fallback.load(std::memory_order_relaxed) ? CopyFile2Fn{} : fn; -} - -// The fallback's flags, by what CopyFileExW can do with them (values from the SDK's WinBase.h, spelled out because -// some of the names are only declared for newer NTDDI_VERSION targets): -// - passed on: the flags both calls define, with the same meaning; -// - dropped: CopyFile2-only requests about how the copy runs (privileges, resuming a paused copy, no offload, EDP, -// destination DACL, compressed SMB traffic, pre-allocation, low-free-space mode, sparse copy) that leave the -// destination's contents as CopyFileExW writes them; -// - everything else changes what the copy produces (0x80 DIRECTORY, 0x8000 SKIP_ALTERNATE_STREAMS, 0x200000 -// OPEN_AND_COPY_REPARSE_POINT, 0x800000 IGNORE_SOURCE_ENCRYPTION) or isn't defined, so the fallback refuses the -// call with ERROR_NOT_SUPPORTED instead of copying something else. -constexpr DWORD kFallbackPassedFlags = COPY_FILE_FAIL_IF_EXISTS | COPY_FILE_RESTARTABLE | - COPY_FILE_OPEN_SOURCE_FOR_WRITE | COPY_FILE_ALLOW_DECRYPTED_DESTINATION | - COPY_FILE_COPY_SYMLINK | COPY_FILE_NO_BUFFERING; -constexpr DWORD kFallbackDroppedFlags = 0x00002000 /* REQUEST_SECURITY_PRIVILEGES */ | - 0x00004000 /* RESUME_FROM_PAUSE */ | 0x00040000 /* NO_OFFLOAD */ | - 0x00400000 /* IGNORE_EDP_BLOCK */ | - 0x02000000 /* DONT_REQUEST_DEST_WRITE_DAC */ | - 0x04000000 /* DISABLE_PRE_ALLOCATION */ | - 0x08000000 /* ENABLE_LOW_FREE_SPACE_MODE */ | - 0x10000000 /* REQUEST_COMPRESSED_TRAFFIC */ | - 0x20000000 /* ENABLE_SPARSE_COPY */ | 0x80000000 /* DISABLE_SPARSE_COPY */; - -// Whether the fallback can run this call as CopyFile2 would: a COPYFILE2_EXTENDED_PARAMETERS block (the V2 block's -// extra fields have no CopyFileExW equivalent) and no flag outside the two sets above. -bool fallback_supports(const COPYFILE2_EXTENDED_PARAMETERS* parameters) { - if (!parameters) return true; - if (parameters->dwSize != sizeof(COPYFILE2_EXTENDED_PARAMETERS)) return false; - return (parameters->dwCopyFlags & ~(kFallbackPassedFlags | kFallbackDroppedFlags)) == 0; -} - -// CopyFile2 through CopyFileExW, for hosts without it (only for calls fallback_supports). The cancel flag has the -// same type in both (one already set is answered by copy_file2 before this runs). A COPYFILE2 progress routine has -// another signature and message set, so it isn't called here. -HRESULT copy_file2_fallback(const wchar_t* source, const wchar_t* destination, - const COPYFILE2_EXTENDED_PARAMETERS* parameters) { - const DWORD flags = parameters ? parameters->dwCopyFlags & kFallbackPassedFlags : 0; - BOOL* const cancel = parameters ? parameters->pfCancel : nullptr; - if (::CopyFileExW(source, destination, nullptr, nullptr, cancel, flags)) return S_OK; - const DWORD error = GetLastError(); - return HRESULT_FROM_WIN32(error ? error : ERROR_GEN_FAILURE); -} - -} // namespace - -void force_copy_file2_fallback(bool force) { g_force_copy_file2_fallback.store(force, std::memory_order_relaxed); } - -// The parameter block is checked before the destination is prepared, so a refused call leaves nothing behind: a -// block shorter than COPYFILE2_EXTENDED_PARAMETERS is E_INVALIDARG, as the host's CopyFile2 answers (measured on -// Windows 11 for dwSize 0, 4 and 31, which also left no destination), and a call the fallback can't run as asked is -// ERROR_NOT_SUPPORTED. A longer block goes to the host's CopyFile2, which checks it itself. -HRESULT WINAPI copy_file2(PCWSTR from, PCWSTR to, COPYFILE2_EXTENDED_PARAMETERS* parameters) { - if (parameters && parameters->dwSize < sizeof(COPYFILE2_EXTENDED_PARAMETERS)) return E_INVALIDARG; - const CopyFile2Fn host = host_copy_file2(); - if (!host && !fallback_supports(parameters)) return HRESULT_FROM_WIN32(ERROR_NOT_SUPPORTED); - // A cancel flag already set is answered here, for the host's CopyFile2 as well as the fallback: Windows returns - // ERROR_REQUEST_ABORTED and writes nothing, while Wine reads the flag in neither call (Wine 11.20's CopyFile2 logs - // "pfCancel is not supported" and copies, dlls/kernelbase/file.c copy_file; Wine 9 has only CopyFileExW). - if (parameters && parameters->pfCancel && *parameters->pfCancel) return HRESULT_FROM_WIN32(ERROR_REQUEST_ABORTED); - const bool fail_if_exists = parameters && (parameters->dwCopyFlags & COPY_FILE_FAIL_IF_EXISTS) != 0; - std::filesystem::path source, destination; - DWORD error = 0; - if (!copy_paths(from, to, fail_if_exists, source, destination, error)) return HRESULT_FROM_WIN32(error); - if (host) return host(source.c_str(), destination.c_str(), parameters); - return copy_file2_fallback(source.c_str(), destination.c_str(), parameters); -} - -BOOL WINAPI set_file_attributes_w(LPCWSTR name, DWORD attributes) { - if (!name) return fail_bool(ERROR_INVALID_PARAMETER); - std::vector parts; - const Parsed parsed = parse_console(name, parts); - if (parsed == Parsed::Host) return ::SetFileAttributesW(name, attributes); - if (parsed == Parsed::Refused) return fail_bool(ERROR_INVALID_NAME); - - const Roots r = roots(); - if (r.game.empty() || r.overlay.empty()) return fail_bool(ERROR_PATH_NOT_FOUND); - if (parts.empty()) return fail_bool(ERROR_ACCESS_DENIED); - const View v = view(r, parts); - if (v.kind == Kind::None) return fail_bool(ERROR_FILE_NOT_FOUND); - - // The attributes belong to the overlay copy: a package file is copied up and a package folder mirrored first, - // so the package keeps its own attributes and reads, which prefer the overlay, see the new ones. - const std::filesystem::path target = disk_path(r.overlay, parts); - if (!v.in_overlay) { - std::error_code ec; - if (v.kind == Kind::Directory) { - std::filesystem::create_directories(target, ec); - if (ec) return fail_bool(static_cast(ec.value())); - } else { - const Target t = write_target(name, true); - if (t.error) return fail_bool(t.error); - } - } - return ::SetFileAttributesW(target.c_str(), attributes); -} - -BOOL WINAPI set_file_attributes_a(LPCSTR name, DWORD attributes) { - if (!name) return fail_bool(ERROR_INVALID_PARAMETER); - const std::wstring wide = widen_ansi(name); - return set_file_attributes_w(wide.c_str(), attributes); -} - -} // namespace rt::fs - -namespace { -using namespace rt::fs; - -// CreateFile, the FindFirstFile family, the attribute queries and DeleteFile arrive through kernel32/kernelbase -// imports and through the api sets a GDK title is linked against (file-l1-1-0 for the find and attribute calls, -// file-l1-2-0 and file-l2-1-0 for CreateFile). -#define FILE_API(dll) \ - {dll, "CreateFileA", reinterpret_cast(&create_file_a)}, \ - {dll, "CreateFileW", reinterpret_cast(&create_file_w)}, \ - {dll, "CreateFile2", reinterpret_cast(&create_file2)}, \ - {dll, "FindFirstFileA", reinterpret_cast(&find_first_file_a)}, \ - {dll, "FindFirstFileW", reinterpret_cast(&find_first_file_w)}, \ - {dll, "FindFirstFileExA", reinterpret_cast(&find_first_file_ex_a)}, \ - {dll, "FindFirstFileExW", reinterpret_cast(&find_first_file_ex_w)}, \ - {dll, "FindNextFileA", reinterpret_cast(&find_next_file_a)}, \ - {dll, "FindNextFileW", reinterpret_cast(&find_next_file_w)}, \ - {dll, "FindClose", reinterpret_cast(&find_close)}, \ - {dll, "GetFileAttributesA", reinterpret_cast(&get_file_attributes_a)}, \ - {dll, "GetFileAttributesW", reinterpret_cast(&get_file_attributes_w)}, \ - {dll, "GetFileAttributesExA", reinterpret_cast(&get_file_attributes_ex_a)}, \ - {dll, "GetFileAttributesExW", reinterpret_cast(&get_file_attributes_ex_w)}, \ - {dll, "DeleteFileA", reinterpret_cast(&delete_file_a)}, \ - {dll, "DeleteFileW", reinterpret_cast(&delete_file_w)}, \ - {dll, "CreateDirectoryA", reinterpret_cast(&create_directory_a)}, \ - {dll, "CreateDirectoryW", reinterpret_cast(&create_directory_w)}, \ - {dll, "CreateDirectoryExA", reinterpret_cast(&create_directory_ex_a)}, \ - {dll, "CreateDirectoryExW", reinterpret_cast(&create_directory_ex_w)}, \ - {dll, "RemoveDirectoryA", reinterpret_cast(&remove_directory_a)}, \ - {dll, "RemoveDirectoryW", reinterpret_cast(&remove_directory_w)}, \ - {dll, "MoveFileA", reinterpret_cast(&move_file_a)}, \ - {dll, "MoveFileW", reinterpret_cast(&move_file_w)}, \ - {dll, "MoveFileExA", reinterpret_cast(&move_file_ex_a)}, \ - {dll, "MoveFileExW", reinterpret_cast(&move_file_ex_w)}, \ - {dll, "CopyFileA", reinterpret_cast(©_file_a)}, \ - {dll, "CopyFileW", reinterpret_cast(©_file_w)}, \ - {dll, "CopyFileExA", reinterpret_cast(©_file_ex_a)}, \ - {dll, "CopyFileExW", reinterpret_cast(©_file_ex_w)}, \ - {dll, "CopyFile2", reinterpret_cast(©_file2)}, \ - {dll, "SetFileAttributesA", reinterpret_cast(&set_file_attributes_a)}, \ - {dll, "SetFileAttributesW", reinterpret_cast(&set_file_attributes_w)} -} // namespace - -SHIM_TABLE(file_system, - FILE_API("kernel32.dll"), - FILE_API("kernelbase.dll"), - FILE_API("api-ms-win-core-file-l1-1-0.dll"), - FILE_API("api-ms-win-core-file-l1-2-0.dll"), - FILE_API("api-ms-win-core-file-l2-1-0.dll"), -); diff --git a/runtime/shims/file_system.h b/runtime/shims/file_system.h deleted file mode 100644 index d252bb1ce..000000000 --- a/runtime/shims/file_system.h +++ /dev/null @@ -1,36 +0,0 @@ -// Console (GDK) file paths for a mapped title. -// -// A title's file API sees the console's drives: "GAME:\\data\\shaders\\x.sps" is a file inside the installed game -// folder. ivall/xcl (GPL-2.0-only; facts only here) documents for Xbox Series GDK titles that GAME: names the game -// folder and that writes go to a writable overlay rather than to the package, which is read-only. gta6rt does the -// same: -// GAME: a read opens the overlay copy when one exists, else \; -// an open that can write opens \, copying the package file there first when the -// disposition keeps its contents, so the package is never modified; -// a delete leaves a marker in the overlay instead of removing a package file. -// anything else is a host path and is passed through unchanged. -// A GAME: path that climbs above the root with ".." or names another drive is refused with ERROR_INVALID_NAME. -// -// The shims that use this live in file_system.cpp: CreateFile*, FindFirstFile*/FindNextFile*/FindClose, -// GetFileAttributes*/GetFileAttributesEx*, DeleteFile*, CreateDirectory*/RemoveDirectory*, MoveFile*/MoveFileEx*, -// CopyFile*/CopyFileEx*/CopyFile2 and SetFileAttributes* (the rules for each are in docs/runtime_imports.md). -#pragma once - -#include - -namespace rt::fs { - -inline constexpr wchar_t kPersistentStorageDir[] = L".gta6rt-persistent"; - -// Sets the roots. main.cpp calls this once, before anything is mapped; the test calls it per case. The overlay is -// created on the first write, not here. -void configure(const std::filesystem::path& game_dir, const std::filesystem::path& overlay_dir); - -std::filesystem::path game_dir(); -std::filesystem::path overlay_dir(); - -// For tests: true makes the CopyFile2 shim use its CopyFileExW fallback even where the host has CopyFile2, so the -// path Wine 9 takes can be checked on Windows. Off by default; main.cpp never sets it. -void force_copy_file2_fallback(bool force); - -} // namespace rt::fs diff --git a/runtime/shims/gameinput.cpp b/runtime/shims/gameinput.cpp deleted file mode 100644 index 8624b71b6..000000000 --- a/runtime/shims/gameinput.cpp +++ /dev/null @@ -1,2739 +0,0 @@ -// gameinput: Microsoft's GameInput API (v0) for gamepads, backed by SDL3, so any controller SDL knows works: -// DualSense, DualShock 4, Switch Pro, Xbox and the rest of SDL's gamepad database. -// -// The Xbox build reads controllers through GameInput. This shim answers GameInputCreate with a COM object whose -// vtables follow the public v0 API (gameinput_abi.h) and serves gamepads from SDL3: -// -// - device enumeration, connect/disconnect and device callbacks (blocking and async enumeration) -// - GetCurrentReading, and GetNextReading / GetPreviousReading over each pad's last half second of readings -// - GetGamepadState, GetUiNavigationState, controller axes and buttons -// - SetRumbleState: the two body motors through SDL_RumbleGamepad, the impulse-trigger motors through -// SDL_RumbleGamepadTriggers on pads that have them; on a DualSense the trigger signal becomes an adaptive-trigger -// effect (SDL_SendGamepadEffect), as set by LEONIDA_DS_TRIGGERS. That is an approximation of the Xbox impulse -// trigger signal, not the PS5 version's authored effects. -// - DualSense/DualShock 4 lightbar colour (LEONIDA_DS_LIGHTBAR) and the player LEDs by connection order -// - force-feedback motors, reported from the SDL haptic device SDL opens for the pad's joystick, and played through -// SDL_CreateHapticEffect/RunHapticEffect (IGameInputForceFeedbackEffect); haptic trigger motors, reported from the -// trigger motors the pad already has, played as an intensity through the same trigger output as SetRumbleState -// - the keyboard pad (LEONIDA_KEYBOARD_PAD): one SDL virtual gamepad driven by the keyboard and mouse -// - which kind of device the player used last (rt::gameinput::active_input, LEONIDA_PROMPTS), for the runtime's -// own use: the title is told every pad is an Xbox One pad -// -// One thread owns SDL: the background poll thread by default, or the caller of rt::gameinput::poll() when -// LEONIDA_GAMEINPUT_THREAD=0. Title calls never touch SDL: they read the latest snapshot and leave rumble requests -// that the next poll applies (2 ms at most with the thread). Callbacks run on the poll thread, as GameInput runs them -// on its own threads, unless the title created a dispatcher; then IGameInputDispatcher::Dispatch delivers them. -// -// Buttons are positional, as on an Xbox pad: A is the bottom face button (Cross on a DualSense, B on a Switch Pro), -// B the right one, X the left, Y the top. View is Back/Create/Share/Minus, Menu is Start/Options/Plus. -// -// Nothing here goes online. docs/gameinput.md has the mapping, the environment variables and the VERIFY list. -// -// ASSUMPTION: the console executable is not available, so the DLL it imports GameInputCreate from is unknown. The PC -// API lives in gameinput.dll; on console the GDK links it through xgameruntime. Both names are registered. -#include - -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include "../core/config.h" -#include "../core/log.h" -#include "gameinput.h" -#include "gameinput_abi.h" -#include "shims.h" - -using namespace gi; - -namespace { - -constexpr uint32_t kBaseKinds = - GameInputKindControllerAxis | GameInputKindControllerButton | GameInputKindGamepad | GameInputKindUiNavigation; -// Everything a reading may carry: motion on pads with sensors, raw reports on pads opened through HID (RT-175). -constexpr uint32_t kSupportedKinds = kBaseKinds | GameInputKindMotion | GameInputKindRawDeviceReport; -constexpr uint32_t kAxisCount = 6; // LX, LY, RX, RY, LT, RT -constexpr uint32_t kButtonCount = SDL_GAMEPAD_BUTTON_COUNT; -constexpr uint32_t kConnectedStatus = GameInputDeviceConnected | GameInputDeviceInputEnabled | GameInputDeviceOutputEnabled; -constexpr Uint32 kRumbleDurationMs = 0xFFFF; // SDL's maximum; refreshed well before it runs out -constexpr uint64_t kRumbleRefreshUs = 20'000'000; -constexpr uint64_t kBatteryRefreshUs = 1'000'000; -constexpr int kDsEffectSize = 47; // the DualSense effects block SDL_SendGamepadEffect forwards (SDL's DS5EffectsState_t) -constexpr uint32_t kForceFeedbackMotors = 1; // one per SDL haptic device: the wheel or stick it belongs to -constexpr uint32_t kHapticMotors = 2; // the left and right trigger, on a pad that backs them -constexpr uint32_t kHapticHoldMs = 60'000; // length of an effect GameInput gives no duration; re-run before it ends -constexpr uint64_t kHistoryUs = 500'000; // a reading stays in the history until the one after it is this old -constexpr size_t kHistoryCap = 512; // readings per pad, whatever the poll rate -// Motion. SDL gives accel in m/s^2 (gravity included) and gyro in rad/s; the state the ABI defines carries signed -// fractions of the maxima motionInfo reports, so a reading stays within -1..1 however hard the pad is shaken. The -// maxima are this shim's choice: SDL does not expose a sensor range, and 2 g / 2000 deg/s are the ranges a -// DualSense's accelerometer and gyro can express (VERIFY: against the game and a real pad, docs/gameinput.md). -constexpr float kMaxAcceleration = 19.6133f; // 2 g in m/s^2 -constexpr float kMaxAngularVelocity = 34.9066f; // 2000 deg/s in rad/s -constexpr float kMotionSensorRate = 250.0f; // requested sample rate; the device clamps to what it has -constexpr uint64_t kMotionReadingUs = 8'000; // a motion pad streams readings at ~125 Hz so the history stays sane - -uint64_t now_us() { - static const LARGE_INTEGER freq = [] { LARGE_INTEGER f; QueryPerformanceFrequency(&f); return f; }(); - LARGE_INTEGER c; - QueryPerformanceCounter(&c); - return static_cast(c.QuadPart / freq.QuadPart * 1'000'000 + c.QuadPart % freq.QuadPart * 1'000'000 / freq.QuadPart); -} - -// Release for objects the shim keeps for the process: the count never drops below one, so they are never freed. -ULONG release_floor(std::atomic& refs) { - ULONG r = refs.load(); - while (r > 1 && !refs.compare_exchange_weak(r, r - 1)) {} - return r > 1 ? r - 1 : 1; -} - -bool same_guid(const GUID& a, const GUID& b) { return std::memcmp(&a, &b, sizeof(GUID)) == 0; } - -// ---- SDL haptics ------------------------------------------------------------------------------------------------ -// -// Force feedback and the trigger haptic motors go through SDL's haptic API, opened from the pad's joystick: SDL's -// gamepad API has no force feedback at all, and a wheel or stick it models as a joystick exposes one only as a haptic -// device. Every call goes through one table so gameinput_test can stand in for it, because SDL's virtual joysticks -// report no haptics and a wheel is the only other way to reach this path. - -void* sdl_open_haptic(void* js) { return SDL_OpenHapticFromJoystick(static_cast(js)); } -void sdl_close_haptic(void* h) { SDL_CloseHaptic(static_cast(h)); } -uint32_t sdl_haptic_features(void* h) { return SDL_GetHapticFeatures(static_cast(h)); } -int sdl_haptic_max_effects(void* h) { return SDL_GetMaxHapticEffects(static_cast(h)); } -int sdl_haptic_create(void* h, const void* e) { - return SDL_CreateHapticEffect(static_cast(h), static_cast(e)); -} -bool sdl_haptic_update(void* h, int id, const void* e) { - return SDL_UpdateHapticEffect(static_cast(h), id, static_cast(e)); -} -bool sdl_haptic_run(void* h, int id, uint32_t iterations) { - return SDL_RunHapticEffect(static_cast(h), id, iterations); -} -bool sdl_haptic_stop(void* h, int id) { return SDL_StopHapticEffect(static_cast(h), id); } -void sdl_haptic_destroy(void* h, int id) { SDL_DestroyHapticEffect(static_cast(h), id); } -bool sdl_haptic_gain(void* h, int gain) { return SDL_SetHapticGain(static_cast(h), gain); } - -const rt::gameinput::HapticApi kSdlHaptic{sdl_open_haptic, sdl_close_haptic, sdl_haptic_features, - sdl_haptic_max_effects, sdl_haptic_create, sdl_haptic_update, - sdl_haptic_run, sdl_haptic_stop, sdl_haptic_destroy, - sdl_haptic_gain}; -std::atomic g_haptic_api{&kSdlHaptic}; -const rt::gameinput::HapticApi& haptics() { return *g_haptic_api.load(); } - -// ---- configuration ---------------------------------------------------------------------------------------------- - -// A setting of the table (its variable, else leonida.toml), lower-cased; empty when nothing sets it. A value of 64 -// characters or more is ignored, as before the settings moved to the table. The messages below name the variable -// also when the value came from the file. -std::string env(rt::config::Name setting) { - const rt::config::Value value = rt::config::get(setting); - if (!value.is_set() || value.text.size() >= 64) return {}; - std::string s = value.text; - for (auto& c : s) c = static_cast(std::tolower(static_cast(c))); - return s; -} - -rt::gameinput::Config read_config() { - rt::gameinput::Config c; - const std::string t = env("input.ds_triggers"); - if (t == "off" || t == "0") c.ds_triggers = rt::gameinput::DsTriggerMode::Off; - else if (t == "resistance") c.ds_triggers = rt::gameinput::DsTriggerMode::Resistance; - else if (!t.empty() && t != "rumble") - RT_LOG_WARN("gameinput: LEONIDA_DS_TRIGGERS=%s unknown, using rumble\n", t.c_str()); - if (const std::string g = env("input.ds_trigger_gain"); !g.empty()) - c.ds_trigger_gain = std::clamp(static_cast(std::atof(g.c_str())), 0.0f, 4.0f); - if (const std::string g = env("input.mouse_sensitivity"); !g.empty()) - c.mouse_sensitivity = std::clamp(static_cast(std::atof(g.c_str())), 0.1f, 10.0f); - if (const std::string f = env("input.ds_trigger_freq"); !f.empty()) - c.ds_trigger_frequency = static_cast(std::clamp(std::atoi(f.c_str()), 1, 255)); - if (const std::string l = env("input.ds_lightbar"); !l.empty()) { - if (l == "off") { - c.lightbar_set = true; - } else if (l.size() == 6 && l.find_first_not_of("0123456789abcdef") == std::string::npos) { - const unsigned long rgb = std::strtoul(l.c_str(), nullptr, 16); - c.lightbar_set = true; - c.lightbar[0] = static_cast(rgb >> 16); - c.lightbar[1] = static_cast(rgb >> 8); - c.lightbar[2] = static_cast(rgb); - } else { - RT_LOG_WARN("gameinput: LEONIDA_DS_LIGHTBAR=%s is not RRGGBB or off, ignored\n", l.c_str()); - } - } - if (env("input.rumble") == "0") c.rumble = false; - if (env("input.thread") == "0") c.background_thread = false; - const std::string k = env("input.keyboard_pad"); - if (k == "1" || k == "on" || k == "focus") c.keyboard_pad = rt::gameinput::KeyboardPadMode::Focused; - else if (k == "always") c.keyboard_pad = rt::gameinput::KeyboardPadMode::Always; - else if (!k.empty() && k != "0" && k != "off") - RT_LOG_WARN("gameinput: LEONIDA_KEYBOARD_PAD=%s unknown (1, always or off), keyboard pad off\n", - k.c_str()); - using leonida::InputFamily; - const std::string p = env("input.prompts"); - if (p == "xbox") c.prompts = InputFamily::Xbox; - else if (p == "playstation" || p == "ps5") c.prompts = InputFamily::PlayStation5; - else if (p == "ps4") c.prompts = InputFamily::PlayStation4; - else if (p == "ps3") c.prompts = InputFamily::PlayStation3; - else if (p == "nintendo" || p == "switch") c.prompts = InputFamily::Nintendo; - else if (p == "keyboard") c.prompts = InputFamily::Keyboard; - else if (!p.empty() && p != "auto") - RT_LOG_WARN("gameinput: LEONIDA_PROMPTS=%s unknown (auto, xbox, playstation, ps5, ps4, ps3, " - "nintendo or keyboard), following the devices\n", p.c_str()); - if (const std::string m = env("input.prompts_switch_ms"); !m.empty()) - c.prompts_switch_ms = static_cast(std::clamp(std::atoi(m.c_str()), 0, 2000)); - return c; -} - -// ---- objects ---------------------------------------------------------------------------------------------------- - -class Device; -class ForceFeedbackEffect; - -struct Snapshot { - GameInputGamepadState gamepad{}; - uint32_t ui = 0; - float axes[kAxisCount] = {}; - bool buttons[kButtonCount] = {}; - bool guide = false; - GameInputMotionState motion{}; // valid only when has_motion; does not take part in operator== - bool has_motion = false; - // The newest raw input report of a pad opened through HID (RT-175): its report id and payload, without the id - // byte. A new report with other bytes is a change, so it makes a reading of its own. - bool has_raw = false; - uint32_t raw_id = 0; - std::vector raw; - bool operator==(const Snapshot& o) const { // field by field: the padding is not initialised - const GameInputGamepadState &a = gamepad, &b = o.gamepad; - return a.buttons == b.buttons && a.leftTrigger == b.leftTrigger && a.rightTrigger == b.rightTrigger && - a.leftThumbstickX == b.leftThumbstickX && a.leftThumbstickY == b.leftThumbstickY && - a.rightThumbstickX == b.rightThumbstickX && a.rightThumbstickY == b.rightThumbstickY && ui == o.ui && - std::memcmp(buttons, o.buttons, sizeof buttons) == 0 && guide == o.guide && has_raw == o.has_raw && - raw_id == o.raw_id && raw == o.raw; - } -}; - -class Reading final : public IGameInputReading { -public: - Reading(Device* device, const Snapshot& s, uint64_t seq, uint64_t ts, uint64_t order); - ~Reading(); - - HRESULT STDMETHODCALLTYPE QueryInterface(REFIID riid, void** out) override { - if (!out) return E_POINTER; - if (same_guid(riid, IID_IUnknown) || same_guid(riid, IID_IGameInputReading)) { - AddRef(); - *out = static_cast(this); - return S_OK; - } - *out = nullptr; - return E_NOINTERFACE; - } - ULONG STDMETHODCALLTYPE AddRef() override { return ++refs_; } - ULONG STDMETHODCALLTYPE Release() override { - const ULONG r = --refs_; - if (r == 0) delete this; - return r; - } - - uint32_t STDMETHODCALLTYPE GetInputKind() override { - // A reading of a pad without sensors carries no motion, and one without a raw report no raw report. - return kBaseKinds | (s_.has_motion ? GameInputKindMotion : 0u) | (s_.has_raw ? GameInputKindRawDeviceReport : 0u); - } - uint64_t STDMETHODCALLTYPE GetSequenceNumber(uint32_t) override { return seq_; } - uint64_t STDMETHODCALLTYPE GetTimestamp() override { return ts_; } - void STDMETHODCALLTYPE GetDevice(IGameInputDevice** device) override; - bool STDMETHODCALLTYPE GetRawReport(void** report) override; - uint32_t STDMETHODCALLTYPE GetControllerAxisCount() override { return kAxisCount; } - uint32_t STDMETHODCALLTYPE GetControllerAxisState(uint32_t count, float* out) override { - const uint32_t n = out ? std::min(count, kAxisCount) : 0; - std::memcpy(out, s_.axes, n * sizeof(float)); - return n; - } - uint32_t STDMETHODCALLTYPE GetControllerButtonCount() override { return kButtonCount; } - uint32_t STDMETHODCALLTYPE GetControllerButtonState(uint32_t count, bool* out) override { - const uint32_t n = out ? std::min(count, kButtonCount) : 0; - std::memcpy(out, s_.buttons, n * sizeof(bool)); - return n; - } - uint32_t STDMETHODCALLTYPE GetControllerSwitchCount() override { return 0; } - uint32_t STDMETHODCALLTYPE GetControllerSwitchState(uint32_t, GameInputSwitchPosition*) override { return 0; } - uint32_t STDMETHODCALLTYPE GetKeyCount() override { return 0; } - uint32_t STDMETHODCALLTYPE GetKeyState(uint32_t, void*) override { return 0; } - bool STDMETHODCALLTYPE GetMouseState(void*) override { return false; } - uint32_t STDMETHODCALLTYPE GetTouchCount() override { return 0; } - uint32_t STDMETHODCALLTYPE GetTouchState(uint32_t, void*) override { return 0; } - bool STDMETHODCALLTYPE GetMotionState(void* state) override { - if (!state || !s_.has_motion) return false; - *static_cast(state) = s_.motion; - return true; - } - bool STDMETHODCALLTYPE GetArcadeStickState(void*) override { return false; } - bool STDMETHODCALLTYPE GetFlightStickState(void*) override { return false; } - bool STDMETHODCALLTYPE GetGamepadState(GameInputGamepadState* state) override { - if (!state) return false; - *state = s_.gamepad; - return true; - } - bool STDMETHODCALLTYPE GetRacingWheelState(void*) override { return false; } - bool STDMETHODCALLTYPE GetUiNavigationState(GameInputUiNavigationState* state) override { - if (!state) return false; - state->buttons = s_.ui; - return true; - } - - Device* device() const { return device_; } - uint64_t order() const { return order_; } - -private: - std::atomic refs_{1}; - Device* device_; - Snapshot s_; - uint64_t seq_, ts_; - uint64_t order_; // place among every pad's readings, the order GetNextReading/GetPreviousReading follow -}; - -struct Rumble { - float low = 0, high = 0, left = 0, right = 0; -}; - -// GameInput -1..1 magnitudes and 0..1 saturations against SDL's levels and saturations. -Sint16 hlevel(float v) { return static_cast(std::lround(std::clamp(v, -1.0f, 1.0f) * 32767.0f)); } -Uint16 hsat(float v) { return static_cast(std::lround(std::clamp(v, 0.0f, 1.0f) * 65535.0f)); } -uint16_t ms_from_us(uint64_t us) { return static_cast(std::min((us + 999) / 1000, 65535)); } - -// The SDL_HAPTIC_* bit an effect kind needs, for the motor flags and the create-time check. -uint32_t kind_feature(GameInputForceFeedbackEffectKind kind) { - switch (kind) { - case GameInputForceFeedbackConstant: return SDL_HAPTIC_CONSTANT; - case GameInputForceFeedbackRamp: return SDL_HAPTIC_RAMP; - case GameInputForceFeedbackSineWave: return SDL_HAPTIC_SINE; - case GameInputForceFeedbackSquareWave: return SDL_HAPTIC_SQUARE; - case GameInputForceFeedbackTriangleWave: return SDL_HAPTIC_TRIANGLE; - case GameInputForceFeedbackSawtoothUpWave: return SDL_HAPTIC_SAWTOOTHUP; - case GameInputForceFeedbackSawtoothDownWave: return SDL_HAPTIC_SAWTOOTHDOWN; - case GameInputForceFeedbackSpring: return SDL_HAPTIC_SPRING; - case GameInputForceFeedbackFriction: return SDL_HAPTIC_FRICTION; - case GameInputForceFeedbackDamper: return SDL_HAPTIC_DAMPER; - case GameInputForceFeedbackInertia: return SDL_HAPTIC_INERTIA; - } - return 0; -} - -bool valid_kind(GameInputForceFeedbackEffectKind kind) { - return kind >= GameInputForceFeedbackConstant && kind <= GameInputForceFeedbackInertia; -} - -// An all-zero envelope is how a title that only sets a magnitude leaves it: that means no envelope, not silence. -bool envelope_used(const GameInputForceFeedbackEnvelope& e) { - return e.attackDuration || e.sustainDuration || e.releaseDuration || e.attackGain != 0.0f || - e.sustainGain != 0.0f || e.releaseGain != 0.0f || e.playCount || e.repeatDelay; -} - -uint32_t play_count(const GameInputForceFeedbackParams& p) { - return p.kind <= GameInputForceFeedbackSawtoothDownWave ? p.data.constant.envelope.playCount : 0; -} - -// One GameInput effect as SDL's template. GameInput's eleven kinds are SDL's eleven force-feedback effects, so the -// kind picks the SDL type and the fields are magnitudes; conditions have no envelope in GameInput either. Returns -// false for a kind the shim does not map. `endless` says the effect has no duration of its own (GameInput left the -// envelope empty), which is what the poll thread re-runs before the SDL length runs out. -bool build_effect(const GameInputForceFeedbackParams& p, float gain, bool* endless, uint32_t* length_ms, - SDL_HapticEffect* out) { - std::memset(out, 0, sizeof *out); - if (!valid_kind(p.kind)) return false; - const bool envelope_kind = p.kind <= GameInputForceFeedbackSawtoothDownWave; - const GameInputForceFeedbackEnvelope env = envelope_kind ? p.data.constant.envelope : GameInputForceFeedbackEnvelope{}; - const bool used = envelope_kind && envelope_used(env); - const float level = gain * (used ? env.sustainGain : 1.0f); // GameInput's sustainGain is the effect's level - const uint64_t total_us = used ? env.attackDuration + env.sustainDuration + env.releaseDuration : 0; - *endless = total_us == 0; - *length_ms = total_us == 0 ? kHapticHoldMs - : static_cast(std::clamp((total_us + 999) / 1000, 1, 86'400'000)); - // The envelope's attack and release, when the title gave one. SDL only uses the envelope when attack_length or - // fade_level is set, so a zero-gain envelope is left alone rather than muting the effect. - auto envelope = [&](SDL_HapticConstant& e) { - if (!used || (!env.attackDuration && !env.releaseDuration)) return; - e.attack_length = ms_from_us(env.attackDuration); - e.attack_level = hsat(env.attackGain); - e.fade_length = ms_from_us(env.releaseDuration); - e.fade_level = hsat(env.releaseGain); - }; - // Force along +X: the axis a wheel's or a stick's motor acts on, which is the one the motor reports (LinearX). - auto direction = [](SDL_HapticDirection& d) { - d.type = SDL_HAPTIC_CARTESIAN; - d.dir[0] = 1; - }; - switch (p.kind) { - case GameInputForceFeedbackConstant: { - SDL_HapticConstant& e = out->constant; - e.type = SDL_HAPTIC_CONSTANT; - direction(e.direction); - e.length = *length_ms; - e.level = hlevel(p.data.constant.magnitude.linearX * level); - envelope(e); - break; - } - case GameInputForceFeedbackRamp: { - SDL_HapticRamp& e = out->ramp; - e.type = SDL_HAPTIC_RAMP; - direction(e.direction); - e.length = *length_ms; - e.start = hlevel(p.data.ramp.startMagnitude.linearX * level); - e.end = hlevel(p.data.ramp.endMagnitude.linearX * level); - if (used) { - e.attack_length = ms_from_us(env.attackDuration); - e.attack_level = hsat(env.attackGain); - e.fade_length = ms_from_us(env.releaseDuration); - e.fade_level = hsat(env.releaseGain); - } - break; - } - case GameInputForceFeedbackSineWave: - case GameInputForceFeedbackSquareWave: - case GameInputForceFeedbackTriangleWave: - case GameInputForceFeedbackSawtoothUpWave: - case GameInputForceFeedbackSawtoothDownWave: { - SDL_HapticPeriodic& e = out->periodic; - e.type = p.kind == GameInputForceFeedbackSineWave ? SDL_HAPTIC_SINE - : p.kind == GameInputForceFeedbackSquareWave ? SDL_HAPTIC_SQUARE - : p.kind == GameInputForceFeedbackTriangleWave ? SDL_HAPTIC_TRIANGLE - : p.kind == GameInputForceFeedbackSawtoothUpWave ? SDL_HAPTIC_SAWTOOTHUP - : SDL_HAPTIC_SAWTOOTHDOWN; - direction(e.direction); - e.length = *length_ms; - const GameInputForceFeedbackPeriodicParams& pp = p.data.sineWave; - // GameInput gives the wave's frequency in Hz and its phase in degrees; SDL wants a period in ms and a - // phase in hundredths of a degree. - e.period = pp.frequency > 0.0f ? static_cast(std::clamp(std::lround(1000.0f / pp.frequency), 1L, 65535L)) : 100; - e.magnitude = hlevel(pp.magnitude.linearX * level); - e.offset = hlevel(pp.bias * level); - e.phase = static_cast(std::clamp(std::lround(pp.phase * 100.0f), 0L, 35999L)); - if (used) { - e.attack_length = ms_from_us(env.attackDuration); - e.attack_level = hsat(env.attackGain); - e.fade_length = ms_from_us(env.releaseDuration); - e.fade_level = hsat(env.releaseGain); - } - break; - } - default: { // spring, friction, damper, inertia - SDL_HapticCondition& e = out->condition; - e.type = p.kind == GameInputForceFeedbackSpring ? SDL_HAPTIC_SPRING - : p.kind == GameInputForceFeedbackFriction ? SDL_HAPTIC_FRICTION - : p.kind == GameInputForceFeedbackDamper ? SDL_HAPTIC_DAMPER - : SDL_HAPTIC_INERTIA; - e.length = *length_ms; - const GameInputForceFeedbackConditionParams& cp = p.data.spring; - const float center[3] = {cp.magnitude.linearX, cp.magnitude.linearY, cp.magnitude.linearZ}; - for (int a = 0; a < 3; ++a) { - e.right_sat[a] = hsat(cp.maxPositiveMagnitude); - e.left_sat[a] = hsat(cp.maxNegativeMagnitude); - e.right_coeff[a] = hlevel(cp.positiveCoefficient * level); - e.left_coeff[a] = hlevel(-cp.negativeCoefficient * level); - e.deadband[a] = hsat(cp.deadZone); - e.center[a] = hlevel(center[a]); - } - break; - } - } - return true; -} - -struct TriggerWaveform { - float intensity = 0.0f; - uint64_t start = 0, end = 0; // microseconds, end == 0 holds until replaced - uint64_t duration = 0, delay = 0; - - float level_at(uint64_t now) const { - if (end && now >= end) return 0.0f; - if (!duration || !delay || now <= start) return intensity; - const uint64_t elapsed = now - start; - if (elapsed < duration) return intensity; - // A cycle longer than the clock's entire range can only reach its first quiet interval. - if (delay > UINT64_MAX - duration) return 0.0f; - return elapsed % (duration + delay) < duration ? intensity : 0.0f; - } -}; - -class Device final : public IGameInputDevice { -public: - HRESULT STDMETHODCALLTYPE QueryInterface(REFIID riid, void** out) override { - if (!out) return E_POINTER; - if (same_guid(riid, IID_IUnknown) || same_guid(riid, IID_IGameInputDevice)) { - AddRef(); - *out = static_cast(this); - return S_OK; - } - *out = nullptr; - return E_NOINTERFACE; - } - // Devices live for the process: the registry keeps every device it has seen, so that a title holding one across a - // disconnect gets the same object back when the pad returns. - ULONG STDMETHODCALLTYPE AddRef() override { return ++refs_; } - ULONG STDMETHODCALLTYPE Release() override { return release_floor(refs_); } - - const GameInputDeviceInfo* STDMETHODCALLTYPE GetDeviceInfo() override { return &info; } - uint32_t STDMETHODCALLTYPE GetDeviceStatus() override { return status.load(); } - void STDMETHODCALLTYPE GetBatteryState(GameInputBatteryState* state) override; - HRESULT STDMETHODCALLTYPE CreateForceFeedbackEffect(uint32_t motorIndex, const void* params, void** effect) override; - bool STDMETHODCALLTYPE IsForceFeedbackMotorPoweredOn(uint32_t motorIndex) override; - void STDMETHODCALLTYPE SetForceFeedbackMotorGain(uint32_t motorIndex, float masterGain) override; - HRESULT STDMETHODCALLTYPE SetHapticMotorState(uint32_t motorIndex, const void* params) override; - void STDMETHODCALLTYPE SetRumbleState(const GameInputRumbleParams* params) override; - void STDMETHODCALLTYPE SetInputSynchronizationState(bool) override {} - void STDMETHODCALLTYPE SendInputSynchronizationHint() override {} - void STDMETHODCALLTYPE PowerOff() override {} - // Raw HID (RT-175): reports of the pad's HID device through rt::gameinput::HidBackend (SDL_hid_* by default). - HRESULT STDMETHODCALLTYPE CreateRawDeviceReport(uint32_t reportId, int32_t reportKind, void** report) override; - HRESULT STDMETHODCALLTYPE GetRawDeviceFeature(uint32_t reportId, void** report) override; - HRESULT STDMETHODCALLTYPE SetRawDeviceFeature(void* report) override; - HRESULT STDMETHODCALLTYPE SendRawDeviceOutput(void* report) override; - HRESULT STDMETHODCALLTYPE SendRawDeviceOutputWithResponse(void*, void** response) override { - if (response) *response = nullptr; - return E_NOTIMPL; - } - HRESULT STDMETHODCALLTYPE ExecuteRawDeviceIoControl(uint32_t, size_t, const void*, size_t, void*, size_t* size) override { - if (size) *size = 0; - return E_NOTIMPL; - } - bool STDMETHODCALLTYPE AcquireExclusiveRawDeviceAccess(uint64_t) override { return false; } - void STDMETHODCALLTYPE ReleaseExclusiveRawDeviceAccess() override {} - - // Shared state, under g().mu unless noted. - GameInputDeviceInfo info{}; - std::string name; - GameInputString display_name{}; - GameInputControllerAxisInfo axis_info[kAxisCount]{}; - GameInputControllerButtonInfo button_info[kButtonCount]{}; - GameInputGamepadInfo gamepad_info{}; - GameInputUiNavigationInfo ui_info{}; - GameInputMotionInfo motion_info{}; // filled only when the pad has sensors; info.motionInfo points at it - GameInputForceFeedbackMotorInfo ff_motor_info{}; // filled when SDL opened the pad as a haptic device - GameInputHapticFeedbackMotorInfo haptic_motor_info[kHapticMotors]{}; // the trigger motors, when the pad has them - GameInputHapticWaveformInfo haptic_waveform_info[kHapticMotors]{}; // one waveform each, an intensity - std::atomic status{GameInputDeviceNoStatus}; - std::deque history; // one reference each, oldest first; the newest is the current reading - uint64_t evicted_order = 0; // order of the newest reading dropped from history - Reading* latest() const { return history.empty() ? nullptr : history.back(); } - uint64_t seq = 0; - Rumble wanted; - float motor_gain = 1.0f; // SetForceFeedbackMotorGain, 0..1 - std::vector effects; // every live effect, so the poll thread can drive them - std::vector retired; // SDL effect ids whose object is gone: destroyed on the poll thread - TriggerWaveform waveforms[kHapticMotors]{}; - GameInputBatteryState battery{0, 0, 0, 0, GameInputBatteryUnknown}; - AppLocalDeviceId base_id{}; // id_bytes of the identity alone: twins share it, info.deviceId tells them apart - - // Poll-thread state. - SDL_Gamepad* pad = nullptr; - SDL_JoystickID id = 0; - int player = -1; - bool is_dualsense = false, has_rumble = false, has_trigger_rumble = false, has_motion = false; - bool has_trigger_output = false; // the pad backs trigger motors: rumble, DualSense effects or haptic motors - void* haptic = nullptr; // SDL_Haptic behind the joystick, when SDL has one for this pad - uint32_t ff_features = 0; // the SDL_HAPTIC_* bits it reports: which effect kinds it can play - int sent_gain = -1; // device gain 0..100 last sent, so a steady gain costs one call - uint32_t haptic_motors = 0; // trigger haptic motors the pad reports (0 or 2) - rt::gameinput::OutputState sent{}; - leonida::InputFamily family = leonida::InputFamily::Xbox; // what kind of device it really is (active_input) - Snapshot last_snap{}; // what the latest reading holds - uint64_t last_reading_us = 0; // for the motion cadence: readings stream at ~125 Hz on pads with sensors - uint64_t motors_sent_at = 0, triggers_sent_at = 0, battery_at = 0; - bool ds_sent_once = false; - - // Raw HID (RT-175). hid is the backend's handle, null when the pad has no HID device the backend could open; - // hid_mu serialises every call on it, from the poll thread (reads) and the title's threads (output, features). - // The report tables come from the HID report descriptor; info.input/output/featureReportInfo point into them. - std::mutex hid_mu; - void* hid = nullptr; - const rt::gameinput::HidBackend* hid_backend = nullptr; // the backend hid was opened with - bool hid_ids = false; // the descriptor declares report ids, so an input report starts with its id byte - std::vector raw_in, raw_out, raw_feature; - const GameInputRawDeviceReportInfo* find_raw(int32_t kind, uint32_t report_id) const; - HRESULT send_raw(void* report, GameInputRawDeviceReportKind kind); - -private: - std::atomic refs_{1}; -}; - -Reading::Reading(Device* device, const Snapshot& s, uint64_t seq, uint64_t ts, uint64_t order) - : device_(device), s_(s), seq_(seq), ts_(ts), order_(order) { - device_->AddRef(); -} -Reading::~Reading() { device_->Release(); } -void Reading::GetDevice(IGameInputDevice** device) { - if (!device) return; - device_->AddRef(); - *device = device_; -} - -// ---- raw HID (RT-175) ------------------------------------------------------------------------------------------- - -// One raw report: its own copy of the report info (so it outlives a reconnect that rebuilds the device's tables) and -// payload. There are no item tables (itemCount 0), so the item calls answer false; see docs/gameinput.md "Raw HID". -class RawReport final : public IGameInputRawDeviceReport { -public: - RawReport(Device* device, const GameInputRawDeviceReportInfo& info, const uint8_t* data, size_t size) - : device_(device), info_(info), data_(info.size, 0) { - info_.itemCount = 0; - info_.items = nullptr; - if (data) std::memcpy(data_.data(), data, std::min(size, data_.size())); - device_->AddRef(); - } - ~RawReport() { device_->Release(); } - - HRESULT STDMETHODCALLTYPE QueryInterface(REFIID riid, void** out) override { - if (!out) return E_POINTER; - if (same_guid(riid, IID_IUnknown) || same_guid(riid, IID_IGameInputRawDeviceReport)) { - AddRef(); - *out = static_cast(this); - return S_OK; - } - *out = nullptr; - return E_NOINTERFACE; - } - ULONG STDMETHODCALLTYPE AddRef() override { return ++refs_; } - ULONG STDMETHODCALLTYPE Release() override { - const ULONG r = --refs_; - if (r == 0) delete this; - return r; - } - - void STDMETHODCALLTYPE GetDevice(IGameInputDevice** device) override; - const GameInputRawDeviceReportInfo* STDMETHODCALLTYPE GetReportInfo() override { return &info_; } - size_t STDMETHODCALLTYPE GetRawDataSize() override { return data_.size(); } - size_t STDMETHODCALLTYPE GetRawData(size_t bufferSize, void* buffer) override { - const size_t n = buffer ? std::min(bufferSize, data_.size()) : 0; - if (n) std::memcpy(buffer, data_.data(), n); - return n; - } - // The whole payload at once: a buffer of another size is refused, so a report is never half old, half new. - bool STDMETHODCALLTYPE SetRawData(size_t bufferSize, const void* buffer) override { - if (!buffer || bufferSize != data_.size()) return false; - std::memcpy(data_.data(), buffer, bufferSize); - return true; - } - bool STDMETHODCALLTYPE GetItemValue(uint32_t, int64_t* value) override { - if (value) *value = 0; - return false; - } - bool STDMETHODCALLTYPE SetItemValue(uint32_t, int64_t) override { return false; } - bool STDMETHODCALLTYPE ResetItemValue(uint32_t) override { return false; } - bool STDMETHODCALLTYPE ResetAllItems() override { return false; } - -private: - std::atomic refs_{1}; - Device* device_; - GameInputRawDeviceReportInfo info_; - std::vector data_; -}; - -void RawReport::GetDevice(IGameInputDevice** device) { - if (!device) return; - device_->AddRef(); - *device = device_; -} - -// The default backend: SDL's hidapi. A pad is opened by the path SDL reports for it; with no such HID path, by its -// vendor and product id when exactly one game-pad collection (usage page 1, usage 5) matches, so twins never mix. -// A pad without a path (SDL virtual joysticks, the keyboard pad) gets no HID device. -void* sdl_hid_open(const char* path, uint16_t vendor, uint16_t product) { - if (!path || !*path) return nullptr; - static const bool ok = SDL_hid_init() == 0; - if (!ok) return nullptr; - if (SDL_hid_device* h = SDL_hid_open_path(path)) return h; - SDL_hid_device_info* list = SDL_hid_enumerate(vendor, product); - const char* only = nullptr; - int matches = 0; - for (SDL_hid_device_info* i = list; i; i = i->next) - if (i->usage_page == 0x01 && i->usage == 0x05 && ++matches == 1) only = i->path; - SDL_hid_device* h = (matches == 1 && only) ? SDL_hid_open_path(only) : nullptr; - SDL_hid_free_enumeration(list); - return h; -} -void sdl_hid_close(void* h) { SDL_hid_close(static_cast(h)); } -int sdl_hid_descriptor(void* h, uint8_t* buf, size_t size) { - return SDL_hid_get_report_descriptor(static_cast(h), buf, size); -} -int sdl_hid_read(void* h, uint8_t* buf, size_t size) { - return SDL_hid_read_timeout(static_cast(h), buf, size, 0); -} -int sdl_hid_write(void* h, const uint8_t* buf, size_t size) { - return SDL_hid_write(static_cast(h), buf, size); -} -int sdl_hid_get_feature(void* h, uint8_t* buf, size_t size) { - return SDL_hid_get_feature_report(static_cast(h), buf, size); -} -int sdl_hid_send_feature(void* h, const uint8_t* buf, size_t size) { - return SDL_hid_send_feature_report(static_cast(h), buf, size); -} -const rt::gameinput::HidBackend kSdlHid = {sdl_hid_open, sdl_hid_close, sdl_hid_descriptor, sdl_hid_read, - sdl_hid_write, sdl_hid_get_feature, sdl_hid_send_feature}; -std::atomic g_hid{&kSdlHid}; - -bool Reading::GetRawReport(void** report) { - if (!report) return false; - *report = nullptr; - if (!s_.has_raw) return false; - std::lock_guard lock(device_->hid_mu); - const GameInputRawDeviceReportInfo* info = device_->find_raw(GameInputRawInputReport, s_.raw_id); - if (!info) return false; - *report = static_cast(new RawReport(device_, *info, s_.raw.data(), s_.raw.size())); - return true; -} - -const GameInputRawDeviceReportInfo* Device::find_raw(int32_t kind, uint32_t report_id) const { - const std::vector* list = kind == GameInputRawInputReport ? &raw_in - : kind == GameInputRawOutputReport ? &raw_out - : kind == GameInputRawFeatureReport ? &raw_feature - : nullptr; - if (!list) return nullptr; - for (const GameInputRawDeviceReportInfo& r : *list) - if (r.id == report_id) return &r; - return nullptr; -} - -HRESULT Device::CreateRawDeviceReport(uint32_t reportId, int32_t reportKind, void** report) { - if (!report) return E_POINTER; - *report = nullptr; - std::lock_guard lock(hid_mu); - if (!hid) return E_NOTIMPL; // no raw I/O on this pad (GameInputDeviceRawIoEnabled is not set) - const GameInputRawDeviceReportInfo* ri = find_raw(reportKind, reportId); - if (!ri) return E_INVALIDARG; - *report = static_cast(new RawReport(this, *ri, nullptr, 0)); - return S_OK; -} - -HRESULT Device::GetRawDeviceFeature(uint32_t reportId, void** report) { - if (!report) return E_POINTER; - *report = nullptr; - std::lock_guard lock(hid_mu); - if (!hid) return E_NOTIMPL; - const GameInputRawDeviceReportInfo* ri = find_raw(GameInputRawFeatureReport, reportId); - if (!ri) return E_INVALIDARG; - std::vector buf(ri->size + 1, 0); - buf[0] = static_cast(reportId); // hidapi: the id goes first, 0 for a device without ids - const int n = hid_backend->get_feature(hid, buf.data(), buf.size()); - if (n < 1) return E_FAIL; - *report = static_cast(new RawReport(this, *ri, buf.data() + 1, static_cast(n) - 1)); - return S_OK; -} - -// SetRawDeviceFeature and SendRawDeviceOutput: any IGameInputRawDeviceReport of the right kind whose id this pad -// declares; the payload is sent with the id byte in front, as hidapi takes it. -HRESULT Device::send_raw(void* report, GameInputRawDeviceReportKind kind) { - if (!report) return E_INVALIDARG; - auto* r = static_cast(report); - const GameInputRawDeviceReportInfo* given = r->GetReportInfo(); - std::lock_guard lock(hid_mu); - if (!hid) return E_NOTIMPL; - if (!given || given->kind != kind) return E_INVALIDARG; - const GameInputRawDeviceReportInfo* ri = find_raw(kind, given->id); - if (!ri) return E_INVALIDARG; - std::vector buf(ri->size + 1, 0); - buf[0] = static_cast(ri->id); - r->GetRawData(ri->size, buf.data() + 1); - const rt::gameinput::HidBackend* b = hid_backend; - const int n = kind == GameInputRawFeatureReport ? b->send_feature(hid, buf.data(), buf.size()) - : b->write(hid, buf.data(), buf.size()); - return n < 0 ? E_FAIL : S_OK; -} -HRESULT Device::SetRawDeviceFeature(void* report) { return send_raw(report, GameInputRawFeatureReport); } -HRESULT Device::SendRawDeviceOutput(void* report) { return send_raw(report, GameInputRawOutputReport); } - -// ---- callbacks -------------------------------------------------------------------------------------------------- - -enum class CbType { Device, Reading, Guide, KeyboardLayout }; - -struct Callback { - GameInputCallbackToken token; - CbType type; - Device* device; // filter, or null for all - uint32_t kind; - uint32_t status_filter; - void* context; - void* fn; - bool active; -}; - -struct Event { - CbType type; - Device* device; // referenced - Reading* reading; // referenced, Reading events only - uint64_t timestamp; - uint32_t current, previous; - bool pressed; - GameInputCallbackToken only; // enumeration: deliver to this callback only -}; - -// One effect a title created, on the device it belongs to. The object and its parameters belong to the title; SDL's -// effect is created, run and destroyed on the poll thread, so a title call only writes its state and bumps `version_`, -// which the poll thread compares before it touches SDL. A new effect is Running: CreateForceFeedbackEffect already -// carried the parameters, and the documented use (create once, SetParams per frame) never reaches SetState. -class ForceFeedbackEffect final : public IGameInputForceFeedbackEffect { -public: - ForceFeedbackEffect(Device* device, uint32_t motor, const GameInputForceFeedbackParams& params); - ~ForceFeedbackEffect(); - - HRESULT STDMETHODCALLTYPE QueryInterface(REFIID riid, void** out) override; - ULONG STDMETHODCALLTYPE AddRef() override; - ULONG STDMETHODCALLTYPE Release() override; - void STDMETHODCALLTYPE GetDevice(IGameInputDevice** device) override; - uint32_t STDMETHODCALLTYPE GetMotorIndex() override; - float STDMETHODCALLTYPE GetGain() override; - void STDMETHODCALLTYPE SetGain(float gain) override; - void STDMETHODCALLTYPE GetParams(GameInputForceFeedbackParams* params) override; - bool STDMETHODCALLTYPE SetParams(const GameInputForceFeedbackParams* params) override; - GameInputFeedbackEffectState STDMETHODCALLTYPE GetState() override; - void STDMETHODCALLTYPE SetState(GameInputFeedbackEffectState state) override; - - // Poll thread: make SDL match the effect's parameters, gain and state. `muted` says every output is off - // (LEONIDA_RUMBLE=0); the motor's master gain is SDL's device gain, set once by apply_effects. - void sync(Device* device, uint64_t now, bool muted); - // Poll thread, on unplug: the SDL device went with the pad, so forget its effect id without touching SDL. - void orphan(); - // Poll thread, under g().mu: a reference unless the title's last Release already ran (the destructor then waits - // for g().mu to unlink the effect, so it is still in the device's list but must not be used or revived). - bool add_ref_if_live() { return rt::gameinput::add_ref_if_live(refs_); } - -private: - std::atomic refs_{1}; - Device* device_; - uint32_t motor_; - // Written by title calls under g().mu and read by the poll thread. - GameInputForceFeedbackParams params_; - float gain_ = 1.0f; - GameInputFeedbackEffectState state_ = GameInputFeedbackRunning; - uint64_t version_ = 1; - // Poll thread only. - uint64_t applied_ = 0; // the version SDL has - int sdl_effect_ = -1; - bool sdl_running_ = false; - bool endless_ = true; // GameInput gave no duration: re-run before the SDL length runs out - uint64_t run_at_ = 0, run_for_ = 0; -}; - -class Dispatcher; - -struct State { - std::recursive_mutex mu; // everything below - std::mutex poll_mu; // one poller at a time - std::recursive_mutex deliver_mu; // held while callbacks run; UnregisterCallback waits on it - std::vector devices; // every device seen, for the process lifetime - std::vector connected; // open now, in connection order - std::vector callbacks; - std::vector queue; - GameInputCallbackToken next_token = 1; - uint64_t last_order = 0; // Reading::order of the newest reading - int dispatchers = 0; - HANDLE wait_event = nullptr; // auto-reset, signalled when a dispatcher has work - rt::gameinput::Config config; - bool config_read = false; - bool sdl_ready = false, sdl_failed = false; - bool thread_started = false; - std::atomic delivering_thread{0}; // written by the delivering thread, read unlocked by UnregisterCallback -}; - -// Never destroyed: the poll thread may still run while the process exits. -State& g() { - static State* s = new State; - return *s; -} - -void queue_event(const Event& e) { - if (e.device) e.device->AddRef(); - if (e.reading) e.reading->AddRef(); - g().queue.push_back(e); -} - -bool matches(const Callback& c, const Event& e) { - if (!c.active || c.type != e.type) return false; - if (e.only && e.only != c.token) return false; - if (c.device && c.device != e.device) return false; - switch (e.type) { - case CbType::Device: - if (!(c.kind & e.device->info.supportedInput) && c.kind != GameInputKindUnknown) return false; - return e.only || ((e.current ^ e.previous) & c.status_filter); - case CbType::Reading: - return c.kind == GameInputKindUnknown || (c.kind & e.device->info.supportedInput); - default: - return true; - } -} - -void call(const Callback& c, const Event& e) { - switch (c.type) { - case CbType::Device: - reinterpret_cast(c.fn)(c.token, c.context, e.device, e.timestamp, e.current, e.previous); - break; - case CbType::Reading: - reinterpret_cast(c.fn)(c.token, c.context, e.reading, false); - break; - case CbType::Guide: - reinterpret_cast(c.fn)(c.token, c.context, e.device, e.timestamp, e.pressed); - break; - case CbType::KeyboardLayout: - break; - } -} - -// Runs one queued event's callbacks on the calling thread, without holding the state lock. -void deliver_event(const Event& e) { - State& s = g(); - std::vector targets; - { - std::lock_guard lock(s.mu); - for (const Callback& c : s.callbacks) - if (matches(c, e)) targets.push_back(c); - } - for (const Callback& c : targets) { - bool still = false; - { - std::lock_guard lock(s.mu); - for (const Callback& now : s.callbacks) - if (now.token == c.token) still = now.active; - } - if (still) call(c, e); - } - if (e.device) e.device->Release(); - if (e.reading) e.reading->Release(); -} - -// Runs queued callbacks on the calling thread, without holding the state lock. Returns whether more events arrived -// meanwhile. -bool deliver() { - State& s = g(); - std::lock_guard dl(s.deliver_mu); - std::vector events; - { - std::lock_guard lock(s.mu); - events.swap(s.queue); - } - s.delivering_thread = GetCurrentThreadId(); - for (const Event& e : events) deliver_event(e); - s.delivering_thread = 0; - std::lock_guard lock(s.mu); - return !s.queue.empty(); -} - -// IGameInputDispatcher::Dispatch: runs the events queued when the call starts, oldest first: at least one even with a -// quota of 0, and no further event once quota_us microseconds have passed (an event already started runs to the end, -// so the quota is a target, as on Windows). Events queued during the call wait for the next one, so a busy poll thread -// cannot keep the title inside Dispatch even with an unlimited quota. Events left over go back to the front of the -// queue, ahead of newer ones, and the wait handle is signalled again while any remain. Returns whether events remain. -bool deliver_within(uint64_t quota_us) { - State& s = g(); - std::lock_guard dl(s.deliver_mu); - const auto start = std::chrono::steady_clock::now(); - std::vector batch; - { - std::lock_guard lock(s.mu); - batch.swap(s.queue); - } - s.delivering_thread = GetCurrentThreadId(); - size_t next = 0; - while (next < batch.size()) { - if (next > 0) { - const auto spent = std::chrono::duration_cast(std::chrono::steady_clock::now() - start); - if (static_cast(spent.count()) >= quota_us) break; - } - deliver_event(batch[next++]); - } - s.delivering_thread = 0; - std::lock_guard lock(s.mu); - if (next < batch.size()) s.queue.insert(s.queue.begin(), batch.begin() + static_cast(next), batch.end()); - const bool remaining = !s.queue.empty(); - if (remaining && s.wait_event) SetEvent(s.wait_event); - return remaining; -} - -// ---- SDL backend (poll thread only) ----------------------------------------------------------------------------- - -uint16_t to_u16(float v) { return static_cast(std::lround(std::clamp(v, 0.0f, 1.0f) * 65535.0f)); } - -float axis(SDL_Gamepad* p, SDL_GamepadAxis a) { return std::max(-1.0f, SDL_GetGamepadAxis(p, a) / 32767.0f); } - -float norm(float v, float max) { return std::clamp(v / max, -1.0f, 1.0f); } - -bool is_keyboard_pad(SDL_JoystickID jid); // with the keyboard pad below - -// What kind of device a pad really is, for active_input(): SDL's gamepad type, which it takes from the vendor and -// product id. Anything SDL does not place (a generic or unknown pad, a GameCube adapter) counts as Xbox, the layout -// GameInput itself describes. -leonida::InputFamily family_of(SDL_JoystickID jid, SDL_Gamepad* p) { - using leonida::InputFamily; - if (is_keyboard_pad(jid)) return InputFamily::Keyboard; - switch (SDL_GetGamepadType(p)) { - case SDL_GAMEPAD_TYPE_PS5: return InputFamily::PlayStation5; - case SDL_GAMEPAD_TYPE_PS4: return InputFamily::PlayStation4; - case SDL_GAMEPAD_TYPE_PS3: return InputFamily::PlayStation3; - case SDL_GAMEPAD_TYPE_NINTENDO_SWITCH_PRO: - case SDL_GAMEPAD_TYPE_NINTENDO_SWITCH_JOYCON_LEFT: - case SDL_GAMEPAD_TYPE_NINTENDO_SWITCH_JOYCON_RIGHT: - case SDL_GAMEPAD_TYPE_NINTENDO_SWITCH_JOYCON_PAIR: return InputFamily::Nintendo; - default: return InputFamily::Xbox; - } -} - -// ---- active input (src/active_input.h) ---- -// -// The tracker is poll-thread state, under poll_mu like the rest of the poll. What it answers is published in one word, -// so active_input() needs no lock and never sees a family from one change with the generation of another: the family -// in bits 0-7, forced in bit 8, the generation from bit 16. -leonida::ActiveInputTracker g_tracker; -std::atomic g_active{0}; - -void publish_active() { - g_active.store(static_cast(g_tracker.active()) | (g_tracker.forced() ? 1ull << 8 : 0) | - (g_tracker.generation() << 16), - std::memory_order_release); -} - -leonida::InputSample sample_of(const Snapshot& s) { - static_assert(kButtonCount <= 32, "every SDL gamepad button needs a bit"); - leonida::InputSample out; - for (uint32_t i = 0; i < kButtonCount; ++i) // all of SDL's buttons: guide, touchpad and paddles included - if (s.buttons[i]) out.buttons |= 1u << i; - out.left_trigger = s.gamepad.leftTrigger; - out.right_trigger = s.gamepad.rightTrigger; - out.left_x = s.gamepad.leftThumbstickX; - out.left_y = s.gamepad.leftThumbstickY; - out.right_x = s.gamepad.rightThumbstickX; - out.right_y = s.gamepad.rightThumbstickY; - return out; -} - -// LEONIDA_PROMPTS and LEONIDA_PROMPTS_SWITCH_MS, applied at each poll: reload_config can change them at any time. -void apply_prompt_config() { - std::optional want; - uint32_t switch_ms; - { - std::lock_guard lock(g().mu); - want = g().config.prompts; - switch_ms = g().config.prompts_switch_ms; - } - leonida::ActiveInputTracker::Thresholds t = g_tracker.thresholds(); - t.min_switch_us = uint64_t{switch_ms} * 1000; - g_tracker.set_thresholds(t); - const std::optional now = - g_tracker.forced() ? std::optional(g_tracker.active()) : std::nullopt; - if (want == now) return; - g_tracker.force(want); - publish_active(); - if (want) - RT_LOG_INFO("gameinput: LEONIDA_PROMPTS: input family set to %s\n", - leonida::input_family_name(*want)); - else - RT_LOG_INFO("gameinput: LEONIDA_PROMPTS cleared: input family follows the devices (%s now)\n", - leonida::input_family_name(g_tracker.active())); -} - -Snapshot read_pad(Device* d) { - SDL_Gamepad* p = d->pad; - Snapshot s; - auto down = [p](SDL_GamepadButton b) { return SDL_GetGamepadButton(p, b); }; - struct Map { SDL_GamepadButton sdl; uint32_t gi; }; - static const Map kMap[] = { - {SDL_GAMEPAD_BUTTON_START, GameInputGamepadMenu}, - {SDL_GAMEPAD_BUTTON_BACK, GameInputGamepadView}, - {SDL_GAMEPAD_BUTTON_SOUTH, GameInputGamepadA}, - {SDL_GAMEPAD_BUTTON_EAST, GameInputGamepadB}, - {SDL_GAMEPAD_BUTTON_WEST, GameInputGamepadX}, - {SDL_GAMEPAD_BUTTON_NORTH, GameInputGamepadY}, - {SDL_GAMEPAD_BUTTON_DPAD_UP, GameInputGamepadDPadUp}, - {SDL_GAMEPAD_BUTTON_DPAD_DOWN, GameInputGamepadDPadDown}, - {SDL_GAMEPAD_BUTTON_DPAD_LEFT, GameInputGamepadDPadLeft}, - {SDL_GAMEPAD_BUTTON_DPAD_RIGHT, GameInputGamepadDPadRight}, - {SDL_GAMEPAD_BUTTON_LEFT_SHOULDER, GameInputGamepadLeftShoulder}, - {SDL_GAMEPAD_BUTTON_RIGHT_SHOULDER, GameInputGamepadRightShoulder}, - {SDL_GAMEPAD_BUTTON_LEFT_STICK, GameInputGamepadLeftThumbstick}, - {SDL_GAMEPAD_BUTTON_RIGHT_STICK, GameInputGamepadRightThumbstick}, - }; - for (const Map& m : kMap) - if (down(m.sdl)) s.gamepad.buttons |= m.gi; - // GameInput: sticks in -1..1 with +Y up, triggers in 0..1. SDL: +Y down, -32768..32767, triggers 0..32767. - s.gamepad.leftThumbstickX = axis(p, SDL_GAMEPAD_AXIS_LEFTX); - s.gamepad.leftThumbstickY = -axis(p, SDL_GAMEPAD_AXIS_LEFTY); - s.gamepad.rightThumbstickX = axis(p, SDL_GAMEPAD_AXIS_RIGHTX); - s.gamepad.rightThumbstickY = -axis(p, SDL_GAMEPAD_AXIS_RIGHTY); - s.gamepad.leftTrigger = std::max(0.0f, axis(p, SDL_GAMEPAD_AXIS_LEFT_TRIGGER)); - s.gamepad.rightTrigger = std::max(0.0f, axis(p, SDL_GAMEPAD_AXIS_RIGHT_TRIGGER)); - - // Controller axes, 0..1 with 0.5 at rest for the sticks (VERIFY: the raw-axis convention of a GameInput gamepad). - s.axes[0] = (s.gamepad.leftThumbstickX + 1) * 0.5f; - s.axes[1] = (s.gamepad.leftThumbstickY + 1) * 0.5f; - s.axes[2] = (s.gamepad.rightThumbstickX + 1) * 0.5f; - s.axes[3] = (s.gamepad.rightThumbstickY + 1) * 0.5f; - s.axes[4] = s.gamepad.leftTrigger; - s.axes[5] = s.gamepad.rightTrigger; - for (uint32_t i = 0; i < kButtonCount; ++i) s.buttons[i] = down(static_cast(i)); - s.guide = down(SDL_GAMEPAD_BUTTON_GUIDE); - - // Motion, normalised against the maxima motionInfo reports (the ABI's fraction convention). Sensors were enabled - // when the pad was opened; a pad whose sensor read fails just reports no motion this poll. SDL answers reads - // with zeros before the device's first sample arrives, and gravity makes a real accelerometer never read - // exactly zero, so all-zero accel means "no sample yet" and the reading carries no motion at all. - if (d->has_motion) { - float accel[3], gyro[3]; - if (SDL_GetGamepadSensorData(p, SDL_SENSOR_ACCEL, accel, 3) && - SDL_GetGamepadSensorData(p, SDL_SENSOR_GYRO, gyro, 3) && - (accel[0] != 0.0f || accel[1] != 0.0f || accel[2] != 0.0f)) { - s.has_motion = true; - s.motion.accelerationX = norm(accel[0], kMaxAcceleration); - s.motion.accelerationY = norm(accel[1], kMaxAcceleration); - s.motion.accelerationZ = norm(accel[2], kMaxAcceleration); - s.motion.angularVelocityX = norm(gyro[0], kMaxAngularVelocity); - s.motion.angularVelocityY = norm(gyro[1], kMaxAngularVelocity); - s.motion.angularVelocityZ = norm(gyro[2], kMaxAngularVelocity); - // SDL's gamepad API has no compass and the shim synthesises no orientation, so those stay zero and - // unknown rather than a made-up value. - s.motion.accelerometerAccuracy = GameInputMotionAccuracyHigh; - s.motion.gyroscopeAccuracy = GameInputMotionAccuracyHigh; - s.motion.magnetometerAccuracy = GameInputMotionAccuracyUnknown; - s.motion.orientationAccuracy = GameInputMotionAccuracyUnknown; - } - } - - // UI navigation derived from the gamepad (VERIFY against the console's own mapping). - const uint32_t b = s.gamepad.buttons; - const float t = 0.5f; - uint32_t& u = s.ui; - if (b & GameInputGamepadMenu) u |= GameInputUiNavigationMenu; - if (b & GameInputGamepadView) u |= GameInputUiNavigationView; - if (b & GameInputGamepadA) u |= GameInputUiNavigationAccept; - if (b & GameInputGamepadB) u |= GameInputUiNavigationCancel; - if (b & GameInputGamepadX) u |= GameInputUiNavigationContext1; - if (b & GameInputGamepadY) u |= GameInputUiNavigationContext2; - if (b & GameInputGamepadLeftThumbstick) u |= GameInputUiNavigationContext3; - if (b & GameInputGamepadRightThumbstick) u |= GameInputUiNavigationContext4; - if ((b & GameInputGamepadDPadUp) || s.gamepad.leftThumbstickY > t) u |= GameInputUiNavigationUp; - if ((b & GameInputGamepadDPadDown) || s.gamepad.leftThumbstickY < -t) u |= GameInputUiNavigationDown; - if ((b & GameInputGamepadDPadLeft) || s.gamepad.leftThumbstickX < -t) u |= GameInputUiNavigationLeft; - if ((b & GameInputGamepadDPadRight) || s.gamepad.leftThumbstickX > t) u |= GameInputUiNavigationRight; - if (b & GameInputGamepadLeftShoulder) u |= GameInputUiNavigationPageLeft; - if (b & GameInputGamepadRightShoulder) u |= GameInputUiNavigationPageRight; - if (s.gamepad.leftTrigger > t) u |= GameInputUiNavigationPageUp; - if (s.gamepad.rightTrigger > t) u |= GameInputUiNavigationPageDown; - if (s.gamepad.rightThumbstickY > t) u |= GameInputUiNavigationScrollUp; - if (s.gamepad.rightThumbstickY < -t) u |= GameInputUiNavigationScrollDown; - if (s.gamepad.rightThumbstickX < -t) u |= GameInputUiNavigationScrollLeft; - if (s.gamepad.rightThumbstickX > t) u |= GameInputUiNavigationScrollRight; - return s; -} - -void id_bytes(const std::string& identity, const SDL_GUID& guid, AppLocalDeviceId* out) { - std::memcpy(out->value, guid.data, 16); - for (int half = 0; half < 2; ++half) { // FNV-1a, two seeds - uint64_t h = half ? 0x84222325cbf29ce4ull : 0xcbf29ce484222325ull; - for (unsigned char c : identity) h = (h ^ c) * 0x100000001b3ull; - std::memcpy(out->value + 16 + half * 8, &h, 8); - } -} - -// Twin n of an identity. Twin 0 is the plain id, so a pad without twins keeps the id it always had. Real identities -// start with "s:", "p:" or are empty, never "t:", so a twin id cannot be another pad's own id. -void id_bytes(const std::string& identity, const SDL_GUID& guid, uint32_t twin, AppLocalDeviceId* out) { - id_bytes(twin ? "t:" + std::to_string(twin) + ":" + identity : identity, guid, out); -} - -void fill_info(Device* d, SDL_Gamepad* p, const AppLocalDeviceId& id) { - GameInputDeviceInfo& i = d->info; - i = {}; - i.infoSize = sizeof(GameInputDeviceInfo); - i.vendorId = SDL_GetGamepadVendor(p); - i.productId = SDL_GetGamepadProduct(p); - i.revisionNumber = SDL_GetGamepadProductVersion(p); - i.usage = {0x01, 0x05}; // HID generic desktop / game pad - const uint16_t fw = SDL_GetGamepadFirmwareVersion(p); - i.firmwareVersion = {static_cast(fw >> 8), static_cast(fw & 0xFF), 0, 0}; - i.deviceId = id; - i.deviceRootId = id; - // Every pad is presented as an Xbox gamepad, which is all a console title expects (VERIFY: whether a title - // filters on the family). - i.deviceFamily = GameInputFamilyXboxOne; - if (SDL_GetGamepadConnectionState(p) == SDL_JOYSTICK_CONNECTION_WIRELESS) i.capabilities |= GameInputDeviceCapabilityWireless; - // The per-device kind set: the reading-kind searches take the global kSupportedKinds as the outer bound and this - // as the per-device one, so only pads with sensors answer a motion query. - i.supportedInput = kBaseKinds; - if (d->has_rumble) i.supportedRumbleMotors |= GameInputRumbleLowFrequency | GameInputRumbleHighFrequency; - if (d->has_trigger_output) i.supportedRumbleMotors |= GameInputRumbleLeftTrigger | GameInputRumbleRightTrigger; - if (d->has_motion) { - i.supportedInput |= GameInputKindMotion; - // The maxima GetMotionState's fractions divide by. The magnetometer is not available: SDL's gamepad API has - // no compass, and maxMagneticFieldStrength 0 says so (Microsoft's GameInputMotionInfo remarks). - d->motion_info = {kMaxAcceleration, kMaxAngularVelocity, 0.0f}; - i.motionInfo = &d->motion_info; - } - // The motors this pad can back. Force feedback is whatever SDL opened a haptic device for with effect kinds of its - // own; the haptic motors are the trigger motors the pad already has for rumble, which the shim can drive as an - // intensity. A pad with neither keeps the old answers: no motors at all. - if (d->haptic) { - i.forceFeedbackMotorCount = kForceFeedbackMotors; - i.forceFeedbackMotorInfo = &d->ff_motor_info; - } - if (d->haptic_motors) { - i.hapticFeedbackMotorCount = d->haptic_motors; - i.hapticFeedbackMotorInfo = d->haptic_motor_info; - } - i.controllerAxisCount = kAxisCount; - i.controllerButtonCount = kButtonCount; - for (uint32_t a = 0; a < kAxisCount; ++a) { - d->axis_info[a] = {}; - d->axis_info[a].mappedInputKinds = GameInputKindGamepad; - d->axis_info[a].isContinuous = true; - d->axis_info[a].hasRestValue = true; - d->axis_info[a].restValue = a < 4 ? 0.5f : 0.0f; - d->axis_info[a].resolution = 65536; - d->axis_info[a].legacyHidIndex = static_cast(a); - d->axis_info[a].legacyDInputIndex = static_cast(a); - } - for (uint32_t b = 0; b < kButtonCount; ++b) { - d->button_info[b] = {}; - d->button_info[b].mappedInputKinds = GameInputKindGamepad; - d->button_info[b].legacyHidIndex = static_cast(b); - d->button_info[b].legacyDInputIndex = static_cast(b); - d->button_info[b].label = GameInputLabelUnknown; // paddles, touchpad, misc: no gamepad meaning to name - } - // Labels. Every pad is presented as an Xbox One pad (docs/gameinput.md), so every control carries the Xbox label - // of its position, whatever is printed on the pad in the player's hands. A stick axis has no label in v0, so - // only the triggers are named. UI navigation names the controls read_pad reads it from; scrolling is the right - // stick, which has none. - const GameInputLabel face[4] = {GameInputLabelXboxA, GameInputLabelXboxB, GameInputLabelXboxX, - GameInputLabelXboxY}; - const GameInputLabel menu = GameInputLabelXboxMenu, view = GameInputLabelXboxView; - const GameInputLabel up = GameInputLabelXboxDPadUp, down = GameInputLabelXboxDPadDown; - const GameInputLabel left = GameInputLabelXboxDPadLeft, right = GameInputLabelXboxDPadRight; - const GameInputLabel lb = GameInputLabelXboxLeftShoulder, rb = GameInputLabelXboxRightShoulder; - const GameInputLabel ls = GameInputLabelXboxLeftStickButton, rs = GameInputLabelXboxRightStickButton; - const GameInputLabel lt = GameInputLabelXboxLeftTrigger, rt = GameInputLabelXboxRightTrigger; - const GameInputLabel none = GameInputLabelNone; - d->gamepad_info = {menu, view, face[0], face[1], face[2], face[3], up, down, left, right, lb, rb, ls, rs}; - d->ui_info = {menu, view, face[0], face[1], up, down, left, right, face[2], face[3], ls, rs, lt, rt, lb, rb, - none, none, none, none, GameInputLabelXboxGuide}; - d->axis_info[4].label = lt; - d->axis_info[5].label = rt; - const struct { - SDL_GamepadButton sdl; - GameInputLabel label; - } labelled[] = { - {SDL_GAMEPAD_BUTTON_SOUTH, face[0]}, {SDL_GAMEPAD_BUTTON_EAST, face[1]}, - {SDL_GAMEPAD_BUTTON_WEST, face[2]}, {SDL_GAMEPAD_BUTTON_NORTH, face[3]}, - {SDL_GAMEPAD_BUTTON_BACK, view}, {SDL_GAMEPAD_BUTTON_GUIDE, GameInputLabelXboxGuide}, - {SDL_GAMEPAD_BUTTON_START, menu}, {SDL_GAMEPAD_BUTTON_LEFT_STICK, ls}, - {SDL_GAMEPAD_BUTTON_RIGHT_STICK, rs}, {SDL_GAMEPAD_BUTTON_LEFT_SHOULDER, lb}, - {SDL_GAMEPAD_BUTTON_RIGHT_SHOULDER, rb}, {SDL_GAMEPAD_BUTTON_DPAD_UP, up}, - {SDL_GAMEPAD_BUTTON_DPAD_DOWN, down}, {SDL_GAMEPAD_BUTTON_DPAD_LEFT, left}, - {SDL_GAMEPAD_BUTTON_DPAD_RIGHT, right}, - }; - for (const auto& l : labelled) d->button_info[l.sdl].label = l.label; - i.controllerAxisInfo = d->axis_info; - i.controllerButtonInfo = d->button_info; - i.gamepadInfo = &d->gamepad_info; - i.uiNavigationInfo = &d->ui_info; - const char* n = SDL_GetGamepadName(p); - d->name = n ? n : "Gamepad"; - uint32_t points = 0; - for (unsigned char c : d->name) points += (c & 0xC0) != 0x80; - d->display_name = {static_cast(d->name.size()), points, d->name.c_str()}; - i.displayName = &d->display_name; -} - -// Makes snap the device's current reading. A reading leaves the history once the one after it is more than kHistoryUs -// old, so the last half second stays reachable however long the pad then idles; kHistoryCap bounds a flood. Readings -// the title holds outlive their place here (~Reading only releases the device, which takes no lock). Under g().mu. -Reading* push_reading(Device* d, const Snapshot& snap, uint64_t ts) { - std::deque& h = d->history; - d->last_reading_us = ts; - h.push_back(new Reading(d, snap, ++d->seq, ts, ++g().last_order)); - while (h.size() > kHistoryCap || (h.size() > 1 && h[1]->GetTimestamp() + kHistoryUs < ts)) { - d->evicted_order = h.front()->order(); - h.front()->Release(); - h.pop_front(); - } - return h.back(); -} - -// Raw HID (RT-175): opens the pad's HID device with the current backend and builds the report tables from its report -// descriptor. A pad the backend cannot open, or whose descriptor cannot be read or declares no report, gets no raw -// I/O: no GameInputKindRawDeviceReport, no report tables, and E_NOTIMPL from the raw device calls. Under g().mu. -void open_raw(Device* d, const char* path) { - std::lock_guard lock(d->hid_mu); - if (d->hid) d->hid_backend->close(d->hid); - d->hid = nullptr; - d->hid_ids = false; - d->raw_in.clear(); - d->raw_out.clear(); - d->raw_feature.clear(); - const rt::gameinput::HidBackend* b = g_hid.load(); - void* h = b->open(path, d->info.vendorId, d->info.productId); - if (!h) { - // SDL reads Xbox pads on Windows through XInput ("XInput#n"); SDL's hidapi skips their XInput HID interface - // (&IG_ in the path), which carries no full HID reports, so they have no raw I/O here. - const bool xinput = path && std::strncmp(path, "XInput#", 7) == 0; - RT_LOG_WARN("gameinput: %s: no raw HID (%s)\n", d->name.c_str(), - xinput ? "an XInput pad: SDL's hidapi does not open XInput HID interfaces" - : path && *path ? "its HID device could not be opened" - : "SDL reports no device path"); - return; - } - std::vector desc(4096); - const int n = b->descriptor(h, desc.data(), desc.size()); - std::vector reports; - const bool parsed = n > 0 && rt::gameinput::parse_report_descriptor(desc.data(), static_cast(n), &reports); - if (!parsed || reports.empty()) { - RT_LOG_WARN("gameinput: %s: no raw HID (%s)\n", d->name.c_str(), - n <= 0 ? "no report descriptor" : !parsed ? "malformed report descriptor" : "no reports declared"); - b->close(h); - return; - } - for (const rt::gameinput::RawReportSize& r : reports) { - const GameInputRawDeviceReportInfo info{static_cast(r.kind), r.id, r.bytes, 0, nullptr}; - (r.kind == GameInputRawInputReport ? d->raw_in : r.kind == GameInputRawOutputReport ? d->raw_out : d->raw_feature) - .push_back(info); - d->hid_ids |= r.id != 0; - } - d->hid = h; - d->hid_backend = b; - GameInputDeviceInfo& i = d->info; - i.supportedInput |= GameInputKindRawDeviceReport; - i.inputReportCount = static_cast(d->raw_in.size()); - i.inputReportInfo = d->raw_in.empty() ? nullptr : d->raw_in.data(); - i.outputReportCount = static_cast(d->raw_out.size()); - i.outputReportInfo = d->raw_out.empty() ? nullptr : d->raw_out.data(); - i.featureReportCount = static_cast(d->raw_feature.size()); - i.featureReportInfo = d->raw_feature.empty() ? nullptr : d->raw_feature.data(); -} - -void close_raw(Device* d) { - std::lock_guard lock(d->hid_mu); - if (d->hid) d->hid_backend->close(d->hid); - d->hid = nullptr; -} - -// Drains the input reports pending since the last poll; the newest one the pad declares goes into snap. With none -// pending, snap keeps the previous report, so a quiet pad makes no new reading. Poll thread. -void read_raw(Device* d, Snapshot* snap) { - snap->has_raw = d->last_snap.has_raw; - snap->raw_id = d->last_snap.raw_id; - snap->raw = d->last_snap.raw; - std::lock_guard lock(d->hid_mu); - if (!d->hid) return; - std::vector buf(4096); - for (int k = 0; k < 64; ++k) { // bounded: a pad that floods cannot hold up the poll - const int n = d->hid_backend->read(d->hid, buf.data(), buf.size()); - if (n <= 0) break; - uint32_t id = 0; - const uint8_t* p = buf.data(); - size_t len = static_cast(n); - if (d->hid_ids) { - id = buf[0]; - ++p; - --len; - } - const GameInputRawDeviceReportInfo* info = d->find_raw(GameInputRawInputReport, id); - if (!info) continue; - snap->has_raw = true; - snap->raw_id = id; - snap->raw.assign(p, p + std::min(len, static_cast(info->size))); - snap->raw.resize(info->size, 0); - } -} - -void open_pad(SDL_JoystickID jid, uint64_t ts) { - State& s = g(); - SDL_Gamepad* p = SDL_OpenGamepad(jid); - if (!p) { - RT_LOG_ERROR("gameinput: cannot open gamepad %u: %s\n", static_cast(jid), SDL_GetError()); - return; - } - const char* serial = SDL_GetGamepadSerial(p); - const char* path = SDL_GetGamepadPath(p); - const std::string identity = (serial && *serial) ? std::string("s:") + serial : (path && *path) ? std::string("p:") + path : ""; - const SDL_GUID guid = SDL_GetGamepadGUIDForID(jid); - AppLocalDeviceId base{}; - id_bytes(identity, guid, &base); - - const SDL_PropertiesID props = SDL_GetGamepadProperties(p); - std::lock_guard lock(s.mu); - // The same pad coming back gets its old object. Pads with the same GUID and serial or path (identical pads with - // neither, mostly) are twins sharing one base id, told apart by order alone: the lowest disconnected twin is - // reused, and a new one gets the next free twin id. Which physical pad was which cannot be recovered, so twins - // that return in a different order swap objects and ids (docs/gameinput.md). - Device* d = nullptr; - uint32_t twins = 0; - for (Device* old : s.devices) { // creation order, so twins in twin order - if (std::memcmp(&old->base_id, &base, sizeof base) != 0) continue; - ++twins; - if (!d && old->status == GameInputDeviceNoStatus) d = old; - } - AppLocalDeviceId id = d ? d->info.deviceId : base; // a copy: fill_info clears info before it writes the id - if (!d) { - const auto taken = [&s](const AppLocalDeviceId& v) { - for (Device* o : s.devices) - if (std::memcmp(&o->info.deviceId, &v, sizeof v) == 0) return true; - return false; - }; - id_bytes(identity, guid, twins, &id); - for (uint32_t n = twins + 1; taken(id); ++n) id_bytes(identity, guid, n, &id); - d = new Device; - d->base_id = base; - s.devices.push_back(d); - } - d->pad = p; - d->id = jid; - d->family = family_of(jid, p); - d->is_dualsense = SDL_GetGamepadType(p) == SDL_GAMEPAD_TYPE_PS5; - d->has_rumble = SDL_GetBooleanProperty(props, SDL_PROP_GAMEPAD_CAP_RUMBLE_BOOLEAN, false); - d->has_trigger_rumble = SDL_GetBooleanProperty(props, SDL_PROP_GAMEPAD_CAP_TRIGGER_RUMBLE_BOOLEAN, false); - // Motion needs both sensors; SDL's orientation quaternion is left alone (no title asks for it, and a synthesised - // one would lie). Enabling at open: SDL delivers samples only for enabled sensors. - d->has_motion = SDL_GamepadHasSensor(p, SDL_SENSOR_GYRO) && SDL_GamepadHasSensor(p, SDL_SENSOR_ACCEL); - if (d->has_motion) { - SDL_SetGamepadSensorEnabled(p, SDL_SENSOR_GYRO, kMotionSensorRate); - SDL_SetGamepadSensorEnabled(p, SDL_SENSOR_ACCEL, kMotionSensorRate); - } - d->has_trigger_output = d->has_trigger_rumble || - (d->is_dualsense && s.config.ds_triggers != rt::gameinput::DsTriggerMode::Off); - // Force feedback: SDL opens a wheel or a stick as a joystick with a haptic device behind it and never through the - // gamepad API, so it is opened from the joystick and closed with the pad. Only what the device really reports is - // passed on: no haptic device, no motor, and an effect kind SDL does not list is not offered to a title. - d->haptic = haptics().open_joystick(SDL_GetGamepadJoystick(p)); - d->ff_features = 0; - d->ff_motor_info = {}; - d->sent_gain = -1; - if (d->haptic) { - const uint32_t features = haptics().features(d->haptic); - if (features) { - GameInputForceFeedbackMotorInfo& m = d->ff_motor_info; - d->ff_features = features; - m.supportedAxes = GameInputFeedbackAxisLinearX; // the axis a wheel's or a stick's motor acts on - m.location = GameInputLocationChassis; - m.locationId = 0; - m.maxSimultaneousEffects = static_cast(std::max(1, haptics().max_effects(d->haptic))); - m.isConstantEffectSupported = (features & SDL_HAPTIC_CONSTANT) != 0; - m.isRampEffectSupported = (features & SDL_HAPTIC_RAMP) != 0; - m.isSineWaveEffectSupported = (features & SDL_HAPTIC_SINE) != 0; - m.isSquareWaveEffectSupported = (features & SDL_HAPTIC_SQUARE) != 0; - m.isTriangleWaveEffectSupported = (features & SDL_HAPTIC_TRIANGLE) != 0; - m.isSawtoothUpWaveEffectSupported = (features & SDL_HAPTIC_SAWTOOTHUP) != 0; - m.isSawtoothDownWaveEffectSupported = (features & SDL_HAPTIC_SAWTOOTHDOWN) != 0; - m.isSpringEffectSupported = (features & SDL_HAPTIC_SPRING) != 0; - m.isFrictionEffectSupported = (features & SDL_HAPTIC_FRICTION) != 0; - m.isDamperEffectSupported = (features & SDL_HAPTIC_DAMPER) != 0; - m.isInertiaEffectSupported = (features & SDL_HAPTIC_INERTIA) != 0; - } else { - haptics().close(d->haptic); - d->haptic = nullptr; - } - } - // Haptic motors: the trigger motors, one waveform each. The waveform identifier is this shim's choice, an - // intensity (HID physical-interface usage 0x0F/0x58), because an intensity is the one thing SDL lets it send. - d->haptic_motors = 0; - if (d->has_trigger_output) { - for (uint32_t m = 0; m < kHapticMotors; ++m) { - d->haptic_waveform_info[m] = {{0x0F, 0x58}, true, true, true, true, 0}; - d->haptic_motor_info[m] = {}; - d->haptic_motor_info[m].mappedRumbleMotors = m ? GameInputRumbleRightTrigger : GameInputRumbleLeftTrigger; - d->haptic_motor_info[m].location = GameInputLocationChassis; - d->haptic_motor_info[m].locationId = m; - d->haptic_motor_info[m].waveformCount = 1; - d->haptic_motor_info[m].waveformInfo = &d->haptic_waveform_info[m]; - } - d->haptic_motors = kHapticMotors; - } - d->sent = {}; - d->sent.is_dualsense = d->is_dualsense; - d->sent.trigger_rumble = d->has_trigger_rumble; - d->sent.force_feedback = d->haptic != nullptr; - d->sent.haptic_motors = d->haptic_motors; - d->ds_sent_once = false; - d->motors_sent_at = d->triggers_sent_at = d->battery_at = 0; - d->wanted = {}; - fill_info(d, p, id); - open_raw(d, path); - - // Player LEDs and SDL's default lightbar colour follow the slot: the lowest one not in use. - int player = 0; - for (bool used = true; used; ++player) { - used = false; - for (Device* c : s.connected) used |= c->player == player; - if (!used) break; - } - d->player = player; - SDL_SetGamepadPlayerIndex(p, player); - if (s.config.lightbar_set && SDL_GetBooleanProperty(props, SDL_PROP_GAMEPAD_CAP_RGB_LED_BOOLEAN, false)) - SDL_SetGamepadLED(p, s.config.lightbar[0], s.config.lightbar[1], s.config.lightbar[2]); - - uint32_t status = kConnectedStatus; - if (d->info.capabilities & GameInputDeviceCapabilityWireless) status |= GameInputDeviceWireless; - if (d->hid) status |= GameInputDeviceRawIoEnabled; - d->status = status; - s.connected.push_back(d); - - const Snapshot snap = read_pad(d); - d->last_snap = snap; - push_reading(d, snap, ts); - queue_event({CbType::Device, d, nullptr, ts, status, GameInputDeviceNoStatus, false, 0}); - RT_LOG_INFO("gameinput: connected %s (%04x:%04x, player %d%s%s%s%s)\n", d->name.c_str(), - d->info.vendorId, d->info.productId, player + 1, d->is_dualsense ? ", DualSense trigger effects" : "", - d->has_trigger_rumble ? ", trigger rumble" : "", d->has_motion ? ", gyro" : "", - d->haptic ? ", force feedback" : ""); -} - -void close_pad(Device* d, uint64_t ts) { - State& s = g(); - g_tracker.forget(d->id); // poll-thread state: a pad that comes back starts from a fresh baseline - std::lock_guard lock(s.mu); - const uint32_t old = d->status.exchange(GameInputDeviceNoStatus); - SDL_CloseGamepad(d->pad); - close_raw(d); - d->pad = nullptr; - d->player = -1; - // The haptic device belongs to the joystick, which goes with the gamepad. Effects a title still holds stay alive - // and pick up again when the pad comes back. - if (d->haptic) { - haptics().close(d->haptic); - d->haptic = nullptr; - } - d->retired.clear(); - d->ff_features = 0; - d->ff_motor_info = {}; - d->sent_gain = -1; - d->haptic_motors = 0; - for (ForceFeedbackEffect* e : d->effects) e->orphan(); - for (auto& waveform : d->waveforms) waveform = {}; - if (!d->history.empty()) d->evicted_order = d->history.back()->order(); // the history ends with the session - for (Reading* r : d->history) r->Release(); - d->history.clear(); - s.connected.erase(std::remove(s.connected.begin(), s.connected.end(), d), s.connected.end()); - queue_event({CbType::Device, d, nullptr, ts, GameInputDeviceNoStatus, old, false, 0}); - RT_LOG_INFO("gameinput: disconnected %s\n", d->name.c_str()); -} - -void ds_effect(float strength, uint8_t out[11]) { - const rt::gameinput::Config& c = g().config; - std::memset(out, 0, 11); - const uint8_t v = static_cast(std::lround(std::clamp(strength * c.ds_trigger_gain, 0.0f, 1.0f) * 255.0f)); - if (v == 0) { - out[0] = 0x05; // effect off - } else if (c.ds_triggers == rt::gameinput::DsTriggerMode::Resistance) { - out[0] = 0x01; // continuous resistance: start position, force - out[1] = 0; - out[2] = v; - } else { - out[0] = 0x06; // vibration: frequency, amplitude, start position - out[1] = c.ds_trigger_frequency; - out[2] = v; - out[3] = 0; - } -} - -// The force-feedback effects and the device gain, on the poll thread: SDL's effects are created, updated, run and -// destroyed here and nowhere else, so a title call costs a lock and a copy. -void apply_effects(Device* d, uint64_t now) { - State& s = g(); - std::vector live; - std::vector retire; - float motor_gain; - bool muted; - { - std::lock_guard lock(s.mu); - live.reserve(d->effects.size()); - // Referenced: the title may release one while this runs. An effect whose count already reached 0 is being - // destroyed (its destructor waits for this lock to unlink it); a plain AddRef revived it, and this loop's own - // Release below freed it a second time. - for (ForceFeedbackEffect* e : d->effects) - if (e->add_ref_if_live()) live.push_back(e); - retire.swap(d->retired); - motor_gain = d->motor_gain; - muted = !s.config.rumble; - } - if (d->haptic) { - for (int id : retire) haptics().destroy_effect(d->haptic, id); - const int gain = static_cast(std::lround(std::clamp(motor_gain, 0.0f, 1.0f) * 100.0f)); - if (gain != d->sent_gain) { - haptics().set_gain(d->haptic, gain); - d->sent_gain = gain; - } - } - for (ForceFeedbackEffect* e : live) { - e->sync(d, now, muted); - e->Release(); - } -} - -void apply_output(Device* d, uint64_t now) { - State& s = g(); - Rumble want; - float haptic[kHapticMotors] = {}; - { - std::lock_guard lock(s.mu); - want = d->wanted; - for (uint32_t m = 0; m < d->haptic_motors; ++m) - haptic[m] = d->waveforms[m].level_at(now); - } - const bool muted = !s.config.rumble; - if (muted) want = {}; - // The haptic motors sit on the trigger motors, so their intensity and SetRumbleState's trigger level go out on one - // output: the stronger of the two wins, and a request that has run out is dropped here. - want.left = std::max(want.left, muted ? 0.0f : haptic[0]); - want.right = std::max(want.right, muted ? 0.0f : haptic[1]); - rt::gameinput::OutputState& o = d->sent; - - if (d->has_rumble) { - const uint16_t lo = to_u16(want.low), hi = to_u16(want.high); - const bool stale = (lo || hi) && now - d->motors_sent_at > kRumbleRefreshUs; - if (lo != o.low || hi != o.high || stale) { - SDL_RumbleGamepad(d->pad, lo, hi, kRumbleDurationMs); - o.low = lo; - o.high = hi; - d->motors_sent_at = now; - } - } - if (d->is_dualsense) { - // LEONIDA_DS_TRIGGERS=off leaves the triggers alone. - if (s.config.ds_triggers != rt::gameinput::DsTriggerMode::Off) { - uint8_t right[11], left[11]; - ds_effect(want.right, right); - ds_effect(want.left, left); - if (!d->ds_sent_once || std::memcmp(right, o.ds_right, 11) || std::memcmp(left, o.ds_left, 11)) { - uint8_t block[kDsEffectSize] = {}; - block[0] = 0x04 | 0x08; // valid flags: right and left trigger effect - std::memcpy(block + 10, right, 11); - std::memcpy(block + 21, left, 11); - if (SDL_SendGamepadEffect(d->pad, block, sizeof block)) { - std::memcpy(o.ds_right, right, 11); - std::memcpy(o.ds_left, left, 11); - d->ds_sent_once = true; - } - } - } - } else if (d->has_trigger_rumble) { - const uint16_t l = to_u16(want.left), r = to_u16(want.right); - const bool stale = (l || r) && now - d->triggers_sent_at > kRumbleRefreshUs; - if (l != o.left || r != o.right || stale) { - SDL_RumbleGamepadTriggers(d->pad, l, r, kRumbleDurationMs); - o.left = l; - o.right = r; - d->triggers_sent_at = now; - } - } - apply_effects(d, now); -} - -void refresh_battery(Device* d, uint64_t now) { - if (now - d->battery_at < kBatteryRefreshUs && d->battery_at) return; - d->battery_at = now; - int percent = -1; - const SDL_PowerState ps = SDL_GetGamepadPowerInfo(d->pad, &percent); - GameInputBatteryState b{0, 0, 0, 0, GameInputBatteryUnknown}; - switch (ps) { - case SDL_POWERSTATE_ON_BATTERY: b.status = GameInputBatteryDischarging; break; - case SDL_POWERSTATE_CHARGING: b.status = GameInputBatteryCharging; break; - case SDL_POWERSTATE_CHARGED: b.status = GameInputBatteryIdle; break; - case SDL_POWERSTATE_NO_BATTERY: b.status = GameInputBatteryNotPresent; break; - default: break; - } - if (percent >= 0) { // relative capacity (VERIFY: GameInput reports the capacity in device units) - b.remainingCapacity = percent / 100.0f; - b.fullChargeCapacity = 1.0f; - } - std::lock_guard lock(g().mu); - d->battery = b; -} - -// ---- keyboard pad (poll thread only) ---------------------------------------------------------------------------- -// -// The title reads gamepads, not the keyboard, so keys reach it as one more pad: an SDL virtual gamepad that this -// code presses buttons on each poll. It then goes through open_pad and read_pad like any controller, so it gets a -// device object, a player slot, readings, callbacks and UI navigation the same way. It has no motors, so rumble sent -// to it is dropped. Keys are read with GetAsyncKeyState, which needs no window or message loop and works under Wine. -// WASD is the left stick, the mouse the right stick, and the right/left mouse buttons the left/right triggers. - -constexpr rt::gameinput::KeyBinding kKeyBindings[] = { - {VK_UP, SDL_GAMEPAD_BUTTON_DPAD_UP, "Up"}, - {VK_DOWN, SDL_GAMEPAD_BUTTON_DPAD_DOWN, "Down"}, - {VK_LEFT, SDL_GAMEPAD_BUTTON_DPAD_LEFT, "Left"}, - {VK_RIGHT, SDL_GAMEPAD_BUTTON_DPAD_RIGHT, "Right"}, - {VK_RETURN, SDL_GAMEPAD_BUTTON_SOUTH, "Enter"}, - {VK_BACK, SDL_GAMEPAD_BUTTON_EAST, "Backspace"}, - {'X', SDL_GAMEPAD_BUTTON_WEST, "X"}, - {'Y', SDL_GAMEPAD_BUTTON_NORTH, "Y"}, - {'Q', SDL_GAMEPAD_BUTTON_LEFT_SHOULDER, "Q"}, - {'E', SDL_GAMEPAD_BUTTON_RIGHT_SHOULDER, "E"}, - {VK_ESCAPE, SDL_GAMEPAD_BUTTON_START, "Esc"}, - {VK_TAB, SDL_GAMEPAD_BUTTON_BACK, "Tab"}, -}; - -// WASD on the left stick: a full press is the edge of the stick; a diagonal sits on the round gate, as a real stick -// reports it, so each axis is 1/sqrt(2) of full. -constexpr int kStickFull = 32767; -constexpr int kStickDiagonal = 23170; // 32767 / sqrt(2) - -// The mouse on the right stick, in SDL axis units per poll (2 ms with the background thread): each poll the stick -// keeps kMouseDecayNum/kMouseDecayDen of its value and adds kMouseAxisPerPixel for every pixel the cursor moved, then -// is clamped to full. Steady movement settles at 8 x 1024 units per pixel per poll, so 4 pixels per poll (2000 -// pixels a second) is full deflection; a stopped mouse falls back from full to exactly 0 in 67 polls (134 ms). -// Integer math rounds toward zero, so the stick always reaches center. -constexpr int kMouseAxisPerPixel = 1024; -constexpr int kMouseDecayNum = 7, kMouseDecayDen = 8; - -bool async_key_down(int vk) { return (GetAsyncKeyState(vk) & 0x8000) != 0; } - -// ---- raw mouse input (its own thread) ---- -// -// The cursor stops at the edge of the screen, so cursor deltas stop too. Raw input reports what the mouse itself -// moved, with no edge and no pointer acceleration. A message-only window (never shown) on its own thread receives -// WM_INPUT and adds each movement to a running total; system_cursor_pos then returns that total as an edgeless -// "cursor", and update_keyboard_pad takes the difference between polls exactly as it did with the real cursor. -std::atomic g_raw_x{0}, g_raw_y{0}; // total raw movement since the thread started, mouse counts -std::atomic g_raw_ready{false}; // registration worked; system_cursor_pos uses the totals -std::atomic g_raw_started{false}; // the thread is started once per process - -LRESULT CALLBACK raw_mouse_proc(HWND hwnd, UINT msg, WPARAM wp, LPARAM lp) { - if (msg == WM_INPUT) { - RAWINPUT raw{}; - UINT size = sizeof(raw); - if (GetRawInputData(reinterpret_cast(lp), RID_INPUT, &raw, &size, sizeof(RAWINPUTHEADER)) != - static_cast(-1) && - raw.header.dwType == RIM_TYPEMOUSE && !(raw.data.mouse.usFlags & MOUSE_MOVE_ABSOLUTE)) { - // Relative movement only: absolute reports (remote desktop, some VMs, tablets) are positions, not - // movement, and would make the stick jump. - g_raw_x += raw.data.mouse.lLastX; - g_raw_y += raw.data.mouse.lLastY; // +Y is down, as for the cursor - } - } - return DefWindowProcW(hwnd, msg, wp, lp); // also for WM_INPUT, which lets Windows clean up the input -} - -void raw_mouse_thread() { - const HINSTANCE inst = GetModuleHandleW(nullptr); - WNDCLASSEXW wc{}; - wc.cbSize = sizeof(wc); - wc.lpfnWndProc = raw_mouse_proc; - wc.hInstance = inst; - wc.lpszClassName = L"LeonidaRawMouse"; - RegisterClassExW(&wc); - // HWND_MESSAGE: a window that is never shown and only receives messages. It must be created on the thread that - // runs the message loop below, because a window's messages go to the thread that created it. - HWND hwnd = CreateWindowExW(0, L"LeonidaRawMouse", L"", 0, 0, 0, 0, 0, - HWND_MESSAGE, nullptr, inst, nullptr); - if (!hwnd) { - RT_LOG_WARN("gameinput: no raw mouse input (window: error %lu); using the cursor position\n", - GetLastError()); - return; - } - RAWINPUTDEVICE dev{}; - dev.usUsagePage = 0x01; // HID generic desktop - dev.usUsage = 0x02; // mouse - dev.dwFlags = RIDEV_INPUTSINK; // also while this (invisible) window has no focus; focus is checked per poll - dev.hwndTarget = hwnd; - if (!RegisterRawInputDevices(&dev, 1, sizeof(dev))) { - RT_LOG_WARN("gameinput: no raw mouse input (register: error %lu); using the cursor position\n", - GetLastError()); - DestroyWindow(hwnd); - return; - } - g_raw_ready = true; - RT_LOG_INFO("gameinput: raw mouse input on (the right stick does not stop at the screen edge)\n"); - MSG m; - while (GetMessageW(&m, nullptr, 0, 0) > 0) DispatchMessageW(&m); -} - -void start_raw_mouse() { - if (!g_raw_started.exchange(true)) std::thread(raw_mouse_thread).detach(); -} - -bool system_cursor_pos(int* x, int* y) { - if (g_raw_ready) { // the edgeless total; it wraps only after ±2^31 counts, and the poll uses differences - *x = static_cast(g_raw_x.load()); - *y = static_cast(g_raw_y.load()); - return true; - } - POINT p; - if (!GetCursorPos(&p)) return false; - *x = p.x; - *y = p.y; - return true; -} - -bool foreground_is_ours() { - const HWND w = GetForegroundWindow(); - DWORD pid = 0; - return w && GetWindowThreadProcessId(w, &pid) && pid == GetCurrentProcessId(); -} - -std::atomic g_key_down{async_key_down}; -std::atomic g_has_focus{foreground_is_ours}; -std::atomic g_cursor_pos{system_cursor_pos}; - -struct KeyboardPad { - SDL_JoystickID id = 0; - SDL_Joystick* js = nullptr; - bool failed = false; // attaching failed once; not retried every 2 ms - int right_x = 0, right_y = 0; // the mouse's right stick, SDL axis units (+Y down) - int cursor_x = 0, cursor_y = 0; // the cursor at the last poll - bool have_cursor = false; // cursor_x/y are valid; false after focus loss, so the first poll moves nothing -}; -KeyboardPad g_keyboard; - -bool is_keyboard_pad(SDL_JoystickID jid) { return jid != 0 && jid == g_keyboard.id; } - -void detach_keyboard_pad() { - if (g_keyboard.js) SDL_CloseJoystick(g_keyboard.js); - if (g_keyboard.id) SDL_DetachVirtualJoystick(g_keyboard.id); - if (g_keyboard.id) RT_LOG_INFO("gameinput: keyboard pad removed\n"); - g_keyboard = {}; -} - -// Keeps the cursor inside the game window while it has focus, so a click cannot land on another window, and releases -// it on focus loss. Only with raw input (a clipped plain cursor would stop the stick at the window edge) and only for -// a real foreground window of this process: not KeyboardPadMode::Always over a terminal, nor a test's fake focus. -// Re-applied every 100 ms, because Windows drops the clip on some focus and resize changes. -bool g_clipped = false; -uint64_t g_clip_at = 0; - -void clip_cursor(bool want) { - if (!want) { - if (g_clipped) ClipCursor(nullptr); - g_clipped = false; - return; - } - const uint64_t now = now_us(); - if (g_clipped && now - g_clip_at < 100'000) return; - const HWND w = GetForegroundWindow(); - RECT r; - if (!w || !GetClientRect(w, &r)) return; - POINT top_left{r.left, r.top}, bottom_right{r.right, r.bottom}; - if (!ClientToScreen(w, &top_left) || !ClientToScreen(w, &bottom_right)) return; - const RECT screen{top_left.x, top_left.y, bottom_right.x, bottom_right.y}; - if (screen.right > screen.left && screen.bottom > screen.top && ClipCursor(&screen)) { - g_clipped = true; - g_clip_at = now; - } -} - -bool attach_keyboard_pad() { - SDL_VirtualJoystickDesc d; - SDL_INIT_INTERFACE(&d); - d.type = SDL_JOYSTICK_TYPE_GAMEPAD; - d.naxes = SDL_GAMEPAD_AXIS_COUNT; - d.nbuttons = SDL_GAMEPAD_BUTTON_COUNT; - d.button_mask = (1u << SDL_GAMEPAD_BUTTON_COUNT) - 1; - d.axis_mask = (1u << SDL_GAMEPAD_AXIS_COUNT) - 1; - d.name = "Keyboard pad (Leonida)"; - g_keyboard.id = SDL_AttachVirtualJoystick(&d); - g_keyboard.js = g_keyboard.id ? SDL_OpenJoystick(g_keyboard.id) : nullptr; - if (!g_keyboard.js) { - RT_LOG_ERROR("gameinput: cannot attach the keyboard pad: %s\n", SDL_GetError()); - detach_keyboard_pad(); - g_keyboard.failed = true; - return false; - } - RT_LOG_INFO("gameinput: keyboard pad attached (arrows d-pad, Enter A, Backspace B, X X, Y Y, " - "Q/E shoulders, Esc Menu, Tab View, WASD left stick, mouse right stick, right/left " - "button LT/RT)\n"); - start_raw_mouse(); - return true; -} - -// Before SDL_UpdateGamepads, so the buttons set here are in this poll's reading. -void update_keyboard_pad() { - float sens; - rt::gameinput::KeyboardPadMode mode; - { - std::lock_guard lock(g().mu); - mode = g().config.keyboard_pad; - sens = g().config.mouse_sensitivity; - } - if (mode == rt::gameinput::KeyboardPadMode::Off) { - clip_cursor(false); - if (g_keyboard.id) detach_keyboard_pad(); - g_keyboard.failed = false; - return; - } - if (!g_keyboard.js && (g_keyboard.failed || !attach_keyboard_pad())) return; - - bool down[SDL_GAMEPAD_BUTTON_COUNT] = {}; - int lx = 0, ly = 0; - bool aim = false, fire = false; - // Out of focus every button, stick and trigger is released, so a key held while switching windows does not stay - // pressed, and the cursor is read afresh on return, so moving it in another window does not swing the stick. - const bool active = mode == rt::gameinput::KeyboardPadMode::Always || g_has_focus.load()(); - if (active) { - const rt::gameinput::KeyDownFn key_down = g_key_down.load(); - for (const auto& b : kKeyBindings) down[b.sdl_button] |= key_down(b.virtual_key); - lx = key_down('D') - key_down('A'); // opposite keys cancel - ly = key_down('S') - key_down('W'); // SDL's +Y is down - aim = key_down(VK_RBUTTON); - fire = key_down(VK_LBUTTON); - - int x = 0, y = 0; - const bool have = g_cursor_pos.load()(&x, &y); - const bool moved = have && g_keyboard.have_cursor; - auto step = [sens](int v, int pixels) { - const long long n = static_cast(v) * kMouseDecayNum / kMouseDecayDen + - std::lround(static_cast(pixels) * kMouseAxisPerPixel * sens); - return static_cast(std::clamp(n, -kStickFull, kStickFull)); - }; - g_keyboard.right_x = step(g_keyboard.right_x, moved ? x - g_keyboard.cursor_x : 0); - g_keyboard.right_y = step(g_keyboard.right_y, moved ? y - g_keyboard.cursor_y : 0); - if (have) g_keyboard.cursor_x = x, g_keyboard.cursor_y = y; - g_keyboard.have_cursor = have; - } else { - g_keyboard.right_x = g_keyboard.right_y = 0; - g_keyboard.have_cursor = false; - } - clip_cursor(active && g_raw_ready && g_cursor_pos.load() == system_cursor_pos && foreground_is_ours()); - for (const auto& b : kKeyBindings) SDL_SetJoystickVirtualButton(g_keyboard.js, b.sdl_button, down[b.sdl_button]); - const int reach = lx && ly ? kStickDiagonal : kStickFull; - SDL_SetJoystickVirtualAxis(g_keyboard.js, SDL_GAMEPAD_AXIS_LEFTX, static_cast(lx * reach)); - SDL_SetJoystickVirtualAxis(g_keyboard.js, SDL_GAMEPAD_AXIS_LEFTY, static_cast(ly * reach)); - SDL_SetJoystickVirtualAxis(g_keyboard.js, SDL_GAMEPAD_AXIS_RIGHTX, static_cast(g_keyboard.right_x)); - SDL_SetJoystickVirtualAxis(g_keyboard.js, SDL_GAMEPAD_AXIS_RIGHTY, static_cast(g_keyboard.right_y)); - // SDL maps a full-range virtual axis to the trigger, so -32768 is released, 0 half pulled, 32767 full. - SDL_SetJoystickVirtualAxis(g_keyboard.js, SDL_GAMEPAD_AXIS_LEFT_TRIGGER, aim ? 32767 : -32768); - SDL_SetJoystickVirtualAxis(g_keyboard.js, SDL_GAMEPAD_AXIS_RIGHT_TRIGGER, fire ? 32767 : -32768); -} - -bool init_sdl() { - State& s = g(); - if (s.sdl_ready) return true; - if (s.sdl_failed) return false; - // No window: keep reading pads when another application has focus. - SDL_SetHint(SDL_HINT_JOYSTICK_ALLOW_BACKGROUND_EVENTS, "1"); - // Never read pads through the host's GameInput underneath this GameInput shim (SDL's default is already off - // outside the GDK; this keeps it off if that default changes). -#ifdef SDL_HINT_JOYSTICK_GAMEINPUT - SDL_SetHint(SDL_HINT_JOYSTICK_GAMEINPUT, "0"); -#endif - SDL_SetGamepadEventsEnabled(false); // the shim reads state directly; nothing drains an event queue - if (!SDL_InitSubSystem(SDL_INIT_GAMEPAD)) { - RT_LOG_ERROR("gameinput: SDL gamepad init failed: %s; no controllers\n", SDL_GetError()); - s.sdl_failed = true; - return false; - } - SDL_SetGamepadEventsEnabled(false); - s.sdl_ready = true; - const int v = SDL_GetVersion(); - RT_LOG_INFO("gameinput: SDL %d.%d.%d gamepads\n", SDL_VERSIONNUM_MAJOR(v), SDL_VERSIONNUM_MINOR(v), - SDL_VERSIONNUM_MICRO(v)); - return true; -} - -void poll_once() { - State& s = g(); - std::lock_guard pl(s.poll_mu); - if (!init_sdl()) return; - apply_prompt_config(); - update_keyboard_pad(); - SDL_UpdateGamepads(); - const uint64_t now = now_us(); - - int count = 0; - SDL_JoystickID* ids = SDL_GetGamepads(&count); - std::vector present(ids, ids + (ids ? count : 0)); - SDL_free(ids); - - std::vector connected; - { - std::lock_guard lock(s.mu); - connected = s.connected; - } - for (Device* d : connected) - if (std::find(present.begin(), present.end(), d->id) == present.end() || !SDL_GamepadConnected(d->pad)) - close_pad(d, now); - for (SDL_JoystickID jid : present) { - bool known = false; - { - std::lock_guard lock(s.mu); - for (Device* d : s.connected) known |= d->id == jid; - } - if (!known) open_pad(jid, now); - } - - { - std::lock_guard lock(s.mu); - connected = s.connected; - } - for (Device* d : connected) { - Snapshot snap = read_pad(d); - read_raw(d, &snap); - const bool guide_changed = d->last_snap.guide != snap.guide; - const bool changed = !(d->last_snap == snap); - d->last_snap = snap; - // A newly opened pad's first sample here is its baseline (active_input.h), so connecting a pad with a button - // held changes nothing. - if (const leonida::InputEdge edge = g_tracker.observe(d->id, d->family, sample_of(snap), now); - edge != leonida::InputEdge::None) { - publish_active(); - if (!g_tracker.forced()) - RT_LOG_INFO("gameinput: input in use: %s (%s, %s)\n", - leonida::input_family_name(d->family), d->name.c_str(), leonida::input_edge_name(edge)); - } - // A pad with sensors streams readings at ~125 Hz even when nothing else changes, so motion the title reads - // between its frames is never stuck at the last button event; pads without sensors only read on change, as - // before. push_reading stamps last_reading_us, so the cadence follows the actual history. - const bool motion_tick = snap.has_motion && now - d->last_reading_us >= kMotionReadingUs; - if (changed || motion_tick) { - std::lock_guard lock(s.mu); - queue_event({CbType::Reading, d, push_reading(d, snap, now), now, 0, 0, false, 0}); - } - if (guide_changed) { - std::lock_guard lock(s.mu); - queue_event({CbType::Guide, d, nullptr, now, 0, 0, snap.guide, 0}); - } - refresh_battery(d, now); - apply_output(d, now); - } -} - -void poll_and_deliver() { - poll_once(); - State& s = g(); - bool dispatch; - bool pending; - { - std::lock_guard lock(s.mu); - dispatch = s.dispatchers > 0; - pending = !s.queue.empty(); - } - if (!pending) return; - if (dispatch) SetEvent(s.wait_event); - else deliver(); -} - -void poll_thread() { - HANDLE timer = CreateWaitableTimerExW(nullptr, nullptr, CREATE_WAITABLE_TIMER_HIGH_RESOLUTION, TIMER_ALL_ACCESS); - if (!timer) timer = CreateWaitableTimerW(nullptr, FALSE, nullptr); - LARGE_INTEGER due; - due.QuadPart = -20'000; // 2 ms, relative - for (;;) { - poll_and_deliver(); - if (timer && SetWaitableTimer(timer, &due, 0, nullptr, nullptr, FALSE)) WaitForSingleObject(timer, INFINITE); - else Sleep(1); - } -} - -void ensure_started() { - State& s = g(); - std::lock_guard lock(s.mu); - if (!s.config_read) { - s.config = read_config(); - s.config_read = true; - s.wait_event = CreateEventW(nullptr, FALSE, FALSE, nullptr); - } - if (s.config.background_thread && !s.thread_started) { - s.thread_started = true; - std::thread(poll_thread).detach(); - } -} - -// ---- IGameInputDevice methods that need State ---- - -void Device::GetBatteryState(GameInputBatteryState* state) { - if (!state) return; - std::lock_guard lock(g().mu); - *state = battery; -} - -void Device::SetRumbleState(const GameInputRumbleParams* params) { - std::lock_guard lock(g().mu); - wanted = params ? Rumble{params->lowFrequency, params->highFrequency, params->leftTrigger, params->rightTrigger} : Rumble{}; -} - -HRESULT Device::CreateForceFeedbackEffect(uint32_t motorIndex, const void* params, void** effect) { - if (!effect) return E_POINTER; - *effect = nullptr; - if (!params || motorIndex >= info.forceFeedbackMotorCount) return E_INVALIDARG; - const auto* p = static_cast(params); - // Only what the motor reported. SDL is not asked here: this is a title call, so the cached feature mask decides, - // and the poll thread is what finds out if SDL refuses the effect anyway. - if (!valid_kind(p->kind) || !(ff_features & kind_feature(p->kind))) return E_INVALIDARG; - *effect = new ForceFeedbackEffect(this, motorIndex, *p); - return S_OK; -} - -bool Device::IsForceFeedbackMotorPoweredOn(uint32_t motorIndex) { - return motorIndex < info.forceFeedbackMotorCount && haptic != nullptr && status.load() != GameInputDeviceNoStatus; -} - -void Device::SetForceFeedbackMotorGain(uint32_t motorIndex, float masterGain) { - std::lock_guard lock(g().mu); - if (motorIndex < info.forceFeedbackMotorCount) motor_gain = std::clamp(masterGain, 0.0f, 1.0f); -} - -HRESULT Device::SetHapticMotorState(uint32_t motorIndex, const void* params) { - std::lock_guard lock(g().mu); - if (motorIndex >= haptic_motors) return E_INVALIDARG; - auto& waveform = waveforms[motorIndex]; - if (!params) { // stop the motor - waveform = {}; - return S_OK; - } - const auto* p = static_cast(params); - if (p->waveformIndex >= haptic_motor_info[motorIndex].waveformCount) return E_INVALIDARG; - waveform.intensity = std::clamp(p->intensity, 0.0f, 1.0f); - waveform.start = now_us(); - waveform.duration = p->duration; - waveform.delay = p->repeatDelay; - // duration and repeatDelay are microseconds; playCount 0 plays until the state is set again. The poll thread sends - // the level and drops it when the deadline passes. The sums saturate: a request longer than a uint64 of - // microseconds (a duration of UINT64_MAX, say) ends at UINT64_MAX, which the poll thread never reaches, instead of - // wrapping to a deadline already past or only a moment away. - constexpr uint64_t kMax = UINT64_MAX; - const auto mul = [](uint64_t a, uint64_t b) { return b && a > kMax / b ? kMax : a * b; }; - const auto add = [](uint64_t a, uint64_t b) { return a > kMax - b ? kMax : a + b; }; - uint64_t total = p->playCount == 0 ? 0 : p->duration; - if (p->playCount > 1) total = add(mul(p->duration, p->playCount), mul(p->repeatDelay, p->playCount - 1)); - waveform.end = total ? add(waveform.start, total) : 0; - return S_OK; -} - -// ---- IGameInputForceFeedbackEffect ---------------------------------------------------------------- - -ForceFeedbackEffect::ForceFeedbackEffect(Device* device, uint32_t motor, const GameInputForceFeedbackParams& params) - : device_(device), motor_(motor), params_(params) { - device_->AddRef(); - std::lock_guard lock(g().mu); - device_->effects.push_back(this); -} - -ForceFeedbackEffect::~ForceFeedbackEffect() { - std::lock_guard lock(g().mu); - std::vector& list = device_->effects; - list.erase(std::remove(list.begin(), list.end(), this), list.end()); - if (sdl_effect_ >= 0) { // SDL's effect is destroyed by the poll thread, which is the only thread that may - device_->retired.push_back(sdl_effect_); - sdl_effect_ = -1; - } - device_->Release(); -} - -HRESULT STDMETHODCALLTYPE ForceFeedbackEffect::QueryInterface(REFIID riid, void** out) { - if (!out) return E_POINTER; - if (same_guid(riid, IID_IUnknown) || same_guid(riid, IID_IGameInputForceFeedbackEffect)) { - AddRef(); - *out = static_cast(this); - return S_OK; - } - *out = nullptr; - return E_NOINTERFACE; -} - -ULONG STDMETHODCALLTYPE ForceFeedbackEffect::AddRef() { return ++refs_; } - -ULONG STDMETHODCALLTYPE ForceFeedbackEffect::Release() { - const ULONG r = --refs_; - if (r == 0) delete this; - return r; -} - -void STDMETHODCALLTYPE ForceFeedbackEffect::GetDevice(IGameInputDevice** device) { - if (!device) return; - device_->AddRef(); - *device = device_; -} - -uint32_t STDMETHODCALLTYPE ForceFeedbackEffect::GetMotorIndex() { return motor_; } - -float STDMETHODCALLTYPE ForceFeedbackEffect::GetGain() { - std::lock_guard lock(g().mu); - return gain_; -} - -void STDMETHODCALLTYPE ForceFeedbackEffect::SetGain(float gain) { - std::lock_guard lock(g().mu); - gain_ = std::clamp(gain, 0.0f, 1.0f); - ++version_; -} - -void STDMETHODCALLTYPE ForceFeedbackEffect::GetParams(GameInputForceFeedbackParams* params) { - if (!params) return; - std::lock_guard lock(g().mu); - *params = params_; -} - -bool STDMETHODCALLTYPE ForceFeedbackEffect::SetParams(const GameInputForceFeedbackParams* params) { - if (!params || !valid_kind(params->kind)) return false; - std::lock_guard lock(g().mu); - params_ = *params; - ++version_; - return true; -} - -GameInputFeedbackEffectState STDMETHODCALLTYPE ForceFeedbackEffect::GetState() { - std::lock_guard lock(g().mu); - return state_; -} - -void STDMETHODCALLTYPE ForceFeedbackEffect::SetState(GameInputFeedbackEffectState state) { - std::lock_guard lock(g().mu); - state_ = state; - ++version_; -} - -void ForceFeedbackEffect::orphan() { - sdl_effect_ = -1; - sdl_running_ = false; - applied_ = 0; -} - -// What SDL said about the effect, for output_state (gameinput_probe and the tests): the id it returned, whether it is -// running, and its error text when it is not. SDL_GetError is read here, on the poll thread that made the call. -void note_effect(Device* d, int id, bool ran) { - const char* error = ran ? "" : SDL_GetError(); - std::lock_guard lock(g().mu); - d->sent.effect_id = id; - d->sent.effect_ran = ran; - std::snprintf(d->sent.effect_error, sizeof d->sent.effect_error, "%s", error ? error : ""); -} - -void ForceFeedbackEffect::sync(Device* d, uint64_t now, bool muted) { - GameInputForceFeedbackParams params; - float gain; - GameInputFeedbackEffectState state; - uint64_t version; - { - std::lock_guard lock(g().mu); - params = params_; - gain = gain_; - state = state_; - version = version_; - } - if (!d->haptic) return; - // A stopped or paused effect is stopped in SDL: GameInput pauses one effect where SDL pauses the device, so a - // pause here is a stop that keeps the parameters. LEONIDA_RUMBLE=0 silences this path like every other. - if (state != GameInputFeedbackRunning || muted) { - if (sdl_running_) { - haptics().stop_effect(d->haptic, sdl_effect_); - sdl_running_ = false; - } - return; - } - // An effect that played the length GameInput gave it is over, as the API says of a finished effect. The run is - // forgotten so that a second SetState(Running) starts it again instead of expiring at once. - if (!endless_ && run_for_ && now >= run_at_ + run_for_) { - if (sdl_running_) { - haptics().stop_effect(d->haptic, sdl_effect_); - sdl_running_ = false; - } - endless_ = true; - run_for_ = 0; - std::lock_guard lock(g().mu); - state_ = GameInputFeedbackStopped; - return; - } - const bool stale = sdl_running_ && endless_ && now - run_at_ > kRumbleRefreshUs; - if (sdl_running_ && version == applied_ && !stale) return; - - SDL_HapticEffect fx; - bool endless = true; - uint32_t length_ms = kHapticHoldMs; - if (!build_effect(params, gain, &endless, &length_ms, &fx)) { - if (sdl_running_) haptics().stop_effect(d->haptic, sdl_effect_); - sdl_running_ = false; - return; - } - if (sdl_effect_ < 0) { - sdl_effect_ = haptics().create_effect(d->haptic, &fx); // SDL refused: nothing to drive this effect - if (sdl_effect_ < 0) { - note_effect(d, -1, false); - return; - } - } else if (!haptics().update_effect(d->haptic, sdl_effect_, &fx)) { - note_effect(d, sdl_effect_, false); - return; - } - // GameInput's playCount 0 means "until stopped", which is what SDL's 0 iterations means. - const uint32_t iterations = endless ? 0 : play_count(params); - if (!haptics().run_effect(d->haptic, sdl_effect_, iterations)) { - note_effect(d, sdl_effect_, false); - return; - } - note_effect(d, sdl_effect_, true); - sdl_running_ = true; - applied_ = version; - endless_ = endless; - run_at_ = now; - run_for_ = endless || iterations == 0 ? 0 : static_cast(length_ms) * 1000ull * iterations; -} - -// ---- IGameInputDispatcher ---- - -class Dispatcher final : public IGameInputDispatcher { -public: - Dispatcher() { - std::lock_guard lock(g().mu); - ++g().dispatchers; - } - HRESULT STDMETHODCALLTYPE QueryInterface(REFIID riid, void** out) override { - if (!out) return E_POINTER; - if (same_guid(riid, IID_IUnknown) || same_guid(riid, IID_IGameInputDispatcher)) { - AddRef(); - *out = static_cast(this); - return S_OK; - } - *out = nullptr; - return E_NOINTERFACE; - } - ULONG STDMETHODCALLTYPE AddRef() override { return ++refs_; } - ULONG STDMETHODCALLTYPE Release() override { - const ULONG r = --refs_; - if (r == 0) { - { - std::lock_guard lock(g().mu); - --g().dispatchers; - } - delete this; - } - return r; - } - // Runs the queued callbacks on the caller's thread within the quota (see deliver_within). - bool STDMETHODCALLTYPE Dispatch(uint64_t quotaInMicroseconds) override { return deliver_within(quotaInMicroseconds); } - HRESULT STDMETHODCALLTYPE OpenWaitHandle(HANDLE* handle) override { - if (!handle) return E_POINTER; - *handle = nullptr; - if (!DuplicateHandle(GetCurrentProcess(), g().wait_event, GetCurrentProcess(), handle, 0, FALSE, DUPLICATE_SAME_ACCESS)) - return HRESULT_FROM_WIN32(GetLastError()); - return S_OK; - } - -private: - std::atomic refs_{1}; -}; - -// ---- IGameInput ---- - -Device* as_device(IGameInputDevice* d) { return static_cast(d); } - -// GetNextReading (forward) and GetPreviousReading: the reading right after or right before the reference in the order -// readings were taken, from the filter device's history or, with no filter, every connected pad's. Readings compare by -// Reading::order, not timestamp, since pads polled together share one. The horizon is the newest reading dropped from -// the histories searched (with no filter the reference's pad counts too, even unplugged): a step that would cross it -// is REFERENCE_READING_TOO_OLD rather than a silent skip. -HRESULT find_reading(IGameInputReading* ref, uint32_t kind, IGameInputDevice* device, IGameInputReading** out, - bool forward) { - if (!out) return E_POINTER; - *out = nullptr; - if (!ref) return E_INVALIDARG; - if (kind != GameInputKindUnknown && !(kind & kSupportedKinds)) return GAMEINPUT_E_READING_NOT_FOUND; - const Reading* r = static_cast(ref); - State& s = g(); - std::lock_guard lock(s.mu); - std::vector scope = s.connected; - uint64_t horizon = 0; - if (device) { - Device* dev = as_device(device); - if (dev->info.deviceFamily == GameInputFamilyAggregate) { - if (kind != GameInputKindUnknown && !(kind & dev->info.supportedInput)) - return GAMEINPUT_E_READING_NOT_FOUND; - const uint32_t effective_kind = (kind != GameInputKindUnknown) ? (kind & dev->info.supportedInput) : dev->info.supportedInput; - scope.clear(); - for (Device* cd : s.connected) { - if (effective_kind & cd->info.supportedInput) { - scope.push_back(cd); - } - } - } else { - if (dev->status == GameInputDeviceNoStatus) return GAMEINPUT_E_DEVICE_DISCONNECTED; - if (kind != GameInputKindUnknown && !(kind & dev->info.supportedInput)) - return GAMEINPUT_E_READING_NOT_FOUND; // the device does not do this kind (motion on a plain pad) - scope = {dev}; - } - } else { - horizon = r->device()->evicted_order; - } - for (Device* d : scope) horizon = std::max(horizon, d->evicted_order); - if (forward ? horizon > r->order() : horizon >= r->order()) return GAMEINPUT_E_REFERENCE_READING_TOO_OLD; - Reading* best = nullptr; - for (Device* d : scope) - for (Reading* c : d->history) { - const bool beyond = forward ? c->order() > r->order() : c->order() < r->order() && c->order() > horizon; - if (beyond && (!best || (c->order() < best->order()) == forward)) best = c; // the nearest one - } - if (!best) return GAMEINPUT_E_READING_NOT_FOUND; - best->AddRef(); - *out = best; - return S_OK; -} - -class GameInput final : public IGameInput { -public: - HRESULT STDMETHODCALLTYPE QueryInterface(REFIID riid, void** out) override { - if (!out) return E_POINTER; - if (same_guid(riid, IID_IUnknown) || same_guid(riid, IID_IGameInput)) { - AddRef(); - *out = static_cast(this); - return S_OK; - } - *out = nullptr; - return E_NOINTERFACE; - } - ULONG STDMETHODCALLTYPE AddRef() override { return ++refs_; } - ULONG STDMETHODCALLTYPE Release() override { return release_floor(refs_); } // a process-wide singleton - - uint64_t STDMETHODCALLTYPE GetCurrentTimestamp() override { return now_us(); } - - HRESULT STDMETHODCALLTYPE GetCurrentReading(uint32_t kind, IGameInputDevice* device, IGameInputReading** out) override { - if (!out) return E_POINTER; - *out = nullptr; - if (kind != GameInputKindUnknown && !(kind & kSupportedKinds)) return GAMEINPUT_E_READING_NOT_FOUND; - std::lock_guard lock(g().mu); - Reading* best = nullptr; - if (device) { - Device* d = as_device(device); - if (d->info.deviceFamily == GameInputFamilyAggregate) { - if (kind != GameInputKindUnknown && !(kind & d->info.supportedInput)) - return GAMEINPUT_E_READING_NOT_FOUND; - const uint32_t effective_kind = (kind != GameInputKindUnknown) ? (kind & d->info.supportedInput) : d->info.supportedInput; - for (Device* cd : g().connected) { - if (!(effective_kind & cd->info.supportedInput)) continue; - if (Reading* r = cd->latest(); r && (!best || r->GetTimestamp() >= best->GetTimestamp())) best = r; - } - } else { - if (d->status == GameInputDeviceNoStatus) return GAMEINPUT_E_DEVICE_DISCONNECTED; - if (kind != GameInputKindUnknown && !(kind & d->info.supportedInput)) - return GAMEINPUT_E_READING_NOT_FOUND; // the device does not do this kind (motion on a plain pad) - best = d->latest(); - } - } else { - for (Device* d : g().connected) // the most recent reading from any gamepad - if (Reading* r = d->latest(); r && (!best || r->GetTimestamp() >= best->GetTimestamp())) best = r; - } - if (!best) return GAMEINPUT_E_READING_NOT_FOUND; - best->AddRef(); - *out = best; - return S_OK; - } - - HRESULT STDMETHODCALLTYPE GetNextReading(IGameInputReading* ref, uint32_t kind, IGameInputDevice* device, - IGameInputReading** out) override { - return find_reading(ref, kind, device, out, true); - } - HRESULT STDMETHODCALLTYPE GetPreviousReading(IGameInputReading* ref, uint32_t kind, IGameInputDevice* device, - IGameInputReading** out) override { - return find_reading(ref, kind, device, out, false); - } - // E_NOTIMPL is GameInput v0's own answer: Microsoft's reference page says the method "was never implemented in - // v0" and returns E_NOTIMPL, and v1 removed it. A history lookup here would give a title what no GameInput does. - HRESULT STDMETHODCALLTYPE GetTemporalReading(uint64_t, IGameInputDevice*, IGameInputReading** out) override { - if (!out) return E_POINTER; - *out = nullptr; - return E_NOTIMPL; - } - - HRESULT STDMETHODCALLTYPE RegisterReadingCallback(IGameInputDevice* device, uint32_t kind, float, void* context, - GameInputReadingCallback fn, GameInputCallbackToken* token) override { - if (token) *token = kInvalidCallbackToken; - if (!fn) return E_INVALIDARG; - if (device && as_device(device)->info.deviceFamily == GameInputFamilyAggregate) return E_NOTIMPL; - return add({0, CbType::Reading, as_device(device), kind, 0, context, reinterpret_cast(fn), true}, token); - } - - HRESULT STDMETHODCALLTYPE RegisterDeviceCallback(IGameInputDevice* device, uint32_t kind, uint32_t status_filter, - GameInputEnumerationKind enumeration, void* context, - GameInputDeviceCallback fn, GameInputCallbackToken* token) override { - if (token) *token = kInvalidCallbackToken; - if (!fn) return E_INVALIDARG; - if (device && as_device(device)->info.deviceFamily == GameInputFamilyAggregate) return E_NOTIMPL; - State& s = g(); - GameInputCallbackToken t; - std::vector now; - { - std::lock_guard lock(s.mu); - t = s.next_token++; - s.callbacks.push_back({t, CbType::Device, as_device(device), kind, status_filter, context, - reinterpret_cast(fn), true}); - if (enumeration != GameInputNoEnumeration) { - const uint64_t ts = now_us(); - for (Device* d : s.connected) { - if (device && as_device(device) != d) continue; - if (kind != GameInputKindUnknown && !(kind & d->info.supportedInput)) continue; - const uint32_t st = d->status; - if (!(st & status_filter)) continue; - const Event e{CbType::Device, d, nullptr, ts, st, GameInputDeviceNoStatus, false, t}; - if (enumeration == GameInputBlockingEnumeration) { - d->AddRef(); - now.push_back(e); - } else { - queue_event(e); - } - } - } - } - if (token) *token = t; - // Blocking enumeration: every connected device is reported before this returns, on the caller's thread. - for (const Event& e : now) { - fn(t, context, e.device, e.timestamp, e.current, e.previous); - e.device->Release(); - } - return S_OK; - } - - HRESULT STDMETHODCALLTYPE RegisterGuideButtonCallback(IGameInputDevice* device, void* context, - GameInputGuideButtonCallback fn, GameInputCallbackToken* token) override { - return add({0, CbType::Guide, as_device(device), 0, 0, context, reinterpret_cast(fn), true}, token); - } - // Gamepads have no keyboard layout; the callback is accepted and never runs. - HRESULT STDMETHODCALLTYPE RegisterKeyboardLayoutCallback(IGameInputDevice* device, void* context, - GameInputKeyboardLayoutCallback fn, GameInputCallbackToken* token) override { - return add({0, CbType::KeyboardLayout, as_device(device), 0, 0, context, reinterpret_cast(fn), true}, token); - } - - void STDMETHODCALLTYPE StopCallback(GameInputCallbackToken token) override { - std::lock_guard lock(g().mu); - for (Callback& c : g().callbacks) - if (c.token == token) c.active = false; - } - - // Removes the callback and, unless called from inside a callback, waits for one that is running to return. - // VERIFY: the timeout is not honoured; the wait is for at most one callback. - bool STDMETHODCALLTYPE UnregisterCallback(GameInputCallbackToken token, uint64_t) override { - State& s = g(); - bool found = false; - { - std::lock_guard lock(s.mu); - auto it = std::find_if(s.callbacks.begin(), s.callbacks.end(), [token](const Callback& c) { return c.token == token; }); - if (it != s.callbacks.end()) { - s.callbacks.erase(it); - found = true; - } - } - if (found && s.delivering_thread != GetCurrentThreadId()) std::lock_guard wait(s.deliver_mu); - return found; - } - - HRESULT STDMETHODCALLTYPE CreateDispatcher(IGameInputDispatcher** out) override { - if (!out) return E_POINTER; - *out = new Dispatcher; - return S_OK; - } - HRESULT STDMETHODCALLTYPE CreateAggregateDevice(uint32_t kind, IGameInputDevice** out) override { - if (!out) return E_POINTER; - *out = nullptr; - if (kind == GameInputKindUnknown) return E_INVALIDARG; - // Combining multiple kinds into a single call is unsupported per Microsoft GDK spec - if ((kind & (kind - 1)) != 0) return E_INVALIDARG; - constexpr uint32_t kAllowedKinds = - GameInputKindKeyboard | GameInputKindMouse | GameInputKindGamepad | - GameInputKindArcadeStick | GameInputKindFlightStick | GameInputKindRacingWheel; - if (!(kind & kAllowedKinds)) return E_INVALIDARG; - - std::lock_guard lock(g().mu); - for (Device* d : g().devices) { - if (d->info.deviceFamily == GameInputFamilyAggregate && d->info.supportedInput == kind) { - d->AddRef(); - *out = d; - return S_OK; - } - } - - auto* agg = new Device(); - agg->info.deviceFamily = GameInputFamilyAggregate; - agg->info.supportedInput = kind; - agg->info.capabilities = GameInputDeviceCapabilityNone; - agg->status = GameInputDeviceConnected; - agg->name = "Aggregate GameInput Device"; - agg->display_name.data = agg->name.c_str(); - agg->display_name.sizeInBytes = static_cast(agg->name.size()); - agg->display_name.codePointCount = static_cast(agg->name.size()); - agg->info.displayName = &agg->display_name; - - std::memcpy(agg->info.deviceId.value, "LEONIDA_AGGREGATE_DEVICE_ID\0\0\0\0", 32); - agg->info.deviceId.value[28] = static_cast(kind & 0xff); - agg->info.deviceId.value[29] = static_cast((kind >> 8) & 0xff); - - g().devices.push_back(agg); - agg->AddRef(); - *out = agg; - return S_OK; - } - HRESULT STDMETHODCALLTYPE FindDeviceFromId(const AppLocalDeviceId* id, IGameInputDevice** out) override { - if (!out) return E_POINTER; - *out = nullptr; - if (!id) return E_INVALIDARG; - std::lock_guard lock(g().mu); - for (Device* d : g().devices) - if (std::memcmp(&d->info.deviceId, id, sizeof *id) == 0) { - d->AddRef(); - *out = d; - return S_OK; - } - return GAMEINPUT_E_DEVICE_NOT_FOUND; - } - HRESULT STDMETHODCALLTYPE FindDeviceFromObject(IUnknown*, IGameInputDevice** out) override { return not_found(out); } - HRESULT STDMETHODCALLTYPE FindDeviceFromPlatformHandle(HANDLE, IGameInputDevice** out) override { return not_found(out); } - HRESULT STDMETHODCALLTYPE FindDeviceFromPlatformString(LPCWSTR, IGameInputDevice** out) override { return not_found(out); } - HRESULT STDMETHODCALLTYPE EnableOemDeviceSupport(uint16_t, uint16_t, uint8_t, uint8_t) override { return S_OK; } - // Input keeps arriving in the background: the runtime has no focus model yet. - void STDMETHODCALLTYPE SetFocusPolicy(uint32_t) override {} - -private: - static HRESULT not_found(IGameInputDevice** out) { - if (out) *out = nullptr; - return GAMEINPUT_E_DEVICE_NOT_FOUND; - } - static HRESULT add(Callback c, GameInputCallbackToken* token) { - if (token) *token = kInvalidCallbackToken; - if (!c.fn) return E_INVALIDARG; - std::lock_guard lock(g().mu); - c.token = g().next_token++; - g().callbacks.push_back(c); - if (token) *token = c.token; - return S_OK; - } - std::atomic refs_{1}; -}; - -GameInput& instance() { - static GameInput* gi = new GameInput; - return *gi; -} - -// HRESULT GameInputCreate(IGameInput** gameInput). One instance per process; each call adds a reference. -HRESULT WINAPI GameInputCreate(IGameInput** out) { - if (!out) return E_POINTER; - ensure_started(); - GameInput& gi = instance(); - gi.AddRef(); - *out = &gi; - return S_OK; -} - -} // namespace - -namespace rt::gameinput { - -const Config& config() { - ensure_started(); - return g().config; -} - -void reload_config() { - std::lock_guard lock(g().mu); - g().config = read_config(); - g().config_read = true; -} - -void poll() { - ensure_started(); - poll_and_deliver(); -} - -int connected_count() { - std::lock_guard lock(g().mu); - return static_cast(g().connected.size()); -} - -ActiveInput active_input() { - const uint64_t v = g_active.load(std::memory_order_acquire); - return {static_cast(v & 0xFF), v >> 16, ((v >> 8) & 1) != 0}; -} - -bool output_state(int i, OutputState* out) { - std::lock_guard lock(g().mu); - if (i < 0 || i >= static_cast(g().connected.size()) || !out) return false; - *out = g().connected[static_cast(i)]->sent; - return true; -} - -void set_keyboard_source(KeyDownFn key_down, HasFocusFn has_focus) { - g_key_down = key_down ? key_down : async_key_down; - g_has_focus = has_focus ? has_focus : foreground_is_ours; -} - -void set_cursor_source(CursorPosFn cursor_pos) { g_cursor_pos = cursor_pos ? cursor_pos : system_cursor_pos; } - -void set_haptic_source(const HapticApi* api) { g_haptic_api = api ? api : &kSdlHaptic; } - -const KeyBinding* keyboard_bindings(int* count) { - if (count) *count = static_cast(std::size(kKeyBindings)); - return kKeyBindings; -} - -// HID 1.11 section 6.2.2: a short item is one prefix byte (bSize in bits 0-1, 3 meaning 4 bytes; bType in bits 2-3; -// bTag in bits 4-7) and up to four data bytes, little-endian. 0xFE starts a long item (data size, tag, data). -bool parse_report_descriptor(const uint8_t* data, size_t size, std::vector* out) { - if (!out || (!data && size)) return false; - out->clear(); - struct Globals { - uint32_t report_size = 0, report_count = 0, report_id = 0; - }; - Globals g; - std::vector stack; - struct Key { - int kind; - uint32_t id; - uint64_t bits; - }; - std::vector reports; // first-seen order; sorted at the end - size_t i = 0; - while (i < size) { - const uint8_t prefix = data[i++]; - if (prefix == 0xFE) { // long item: bDataSize, bLongItemTag, data - if (i + 2 > size) return false; - i += 2 + data[i]; - if (i > size) return false; - continue; - } - const size_t n = (prefix & 3) == 3 ? 4 : (prefix & 3); - if (i + n > size) return false; - uint32_t v = 0; - for (size_t k = 0; k < n; ++k) v |= static_cast(data[i + k]) << (8 * k); - i += n; - const int type = (prefix >> 2) & 3, tag = prefix >> 4; - if (type == 1) { // global - if (tag == 7) g.report_size = v; - else if (tag == 8) { - if (v == 0 || v > 255) return false; - g.report_id = v; - } else if (tag == 9) g.report_count = v; - else if (tag == 10) stack.push_back(g); - else if (tag == 11) { - if (stack.empty()) return false; - g = stack.back(); - stack.pop_back(); - } - } else if (type == 0) { // main: Input 8, Output 9, Feature 11 (Collection 10 and End Collection 12 add nothing) - const int kind = tag == 8 ? 0 : tag == 9 ? 1 : tag == 11 ? 2 : -1; - if (kind < 0) continue; - const uint64_t add = static_cast(g.report_size) * g.report_count; - Key* k = nullptr; - for (Key& r : reports) - if (r.kind == kind && r.id == g.report_id) k = &r; - if (!k) { - reports.push_back({kind, g.report_id, 0}); - k = &reports.back(); - } - k->bits += add; - if (k->bits > 65536ull * 8) return false; - } - } - for (const Key& k : reports) out->push_back({k.kind, k.id, static_cast((k.bits + 7) / 8)}); - std::sort(out->begin(), out->end(), - [](const RawReportSize& a, const RawReportSize& b) { return a.kind != b.kind ? a.kind < b.kind : a.id < b.id; }); - return true; -} - -void set_hid_backend(const HidBackend* backend) { g_hid = backend ? backend : &kSdlHid; } - -} // namespace rt::gameinput - -// GameInputCreate is GameInput.dll's export 1, and the retail executable imports it by that ordinal, which the loader -// looks up as "#1". Without the alias the import misses the shim and binds to the host's GameInput.dll; under Wine that -// is the builtin stub, which fails, and the title stops on the result. -SHIM_TABLE(gameinput, - {"gameinput.dll", "GameInputCreate", reinterpret_cast(&GameInputCreate)}, - {"gameinput.dll", "#1", reinterpret_cast(&GameInputCreate)}, - {"xgameruntime.dll", "GameInputCreate", reinterpret_cast(&GameInputCreate)}, -); diff --git a/runtime/shims/gameinput.h b/runtime/shims/gameinput.h deleted file mode 100644 index 79529d08f..000000000 --- a/runtime/shims/gameinput.h +++ /dev/null @@ -1,160 +0,0 @@ -// GameInput shim on SDL3: runtime-side controls and test seams. The GameInput API itself is reached the way a title -// reaches it, through GameInputCreate in the shim registry (gameinput.dll / xgameruntime.dll). See docs/gameinput.md. -#pragma once -#include -#include -#include -#include - -#include "../src/active_input.h" // leonida::InputFamily (and std::optional) for Config::prompts and active_input() - -namespace rt::gameinput { - -// Takes a reference on a reference-counted object only while it is alive, that is while its count isn't 0. A thread -// that finds the object in a shared list (the poll thread and a device's force-feedback effects) then can't revive one -// whose last Release has already run and whose destructor is waiting for the lock to unlink it. False: leave it be. -template -bool add_ref_if_live(std::atomic& refs) { - Count n = refs.load(); - while (n != 0 && !refs.compare_exchange_weak(n, n + 1)) {} - return n != 0; -} - -// How the impulse-trigger motors (GameInputRumbleParams::leftTrigger/rightTrigger) reach a DualSense. -enum class DsTriggerMode { Off, Rumble, Resistance }; - -// The keyboard pad: one extra virtual gamepad driven by the keyboard. Focused reads keys only while a window of this -// process is in the foreground; Always reads them whatever has focus (console tools such as gameinput_probe). -enum class KeyboardPadMode { Off, Focused, Always }; - -struct Config { - // LEONIDA_PROMPTS=auto|xbox|playstation|ps5|ps4|ps3|nintendo|keyboard: a family that active_input() reports - // whatever is in use; unset or auto follows the devices. - std::optional prompts; - uint32_t prompts_switch_ms = 300; // LEONIDA_PROMPTS_SWITCH_MS, 0..2000: shortest time between two changes - DsTriggerMode ds_triggers = DsTriggerMode::Rumble; // LEONIDA_DS_TRIGGERS=off|rumble|resistance - float ds_trigger_gain = 1.0f; // LEONIDA_DS_TRIGGER_GAIN, 0..4, scales the effect strength - float mouse_sensitivity = 1.0f; // LEONIDA_MOUSE_SENSITIVITY, 0.1..10, scales mouse movement - uint8_t ds_trigger_frequency = 30; // LEONIDA_DS_TRIGGER_FREQ, Hz for the rumble mode, 1..255 - bool lightbar_set = false; // LEONIDA_DS_LIGHTBAR=RRGGBB|off; unset keeps SDL's - uint8_t lightbar[3] = {0, 0, 0}; // player colour - bool rumble = true; // LEONIDA_RUMBLE=0 turns all rumble off - bool background_thread = true; // LEONIDA_GAMEINPUT_THREAD=0: poll only from poll() - KeyboardPadMode keyboard_pad = KeyboardPadMode::Off; // LEONIDA_KEYBOARD_PAD=1|focus|always|off -}; - -// The configuration in use. Read from the environment on the first GameInputCreate. -const Config& config(); -// Re-reads the environment (tests). Takes effect for the next rumble update. -void reload_config(); - -// One step of the backend, on the calling thread: initialise SDL if needed, open new gamepads, close removed ones, -// take a reading from each, apply pending rumble/trigger output, and deliver queued callbacks unless a dispatcher -// owns them. With the background thread on (the default) this runs every 2 ms by itself; with it off -// (LEONIDA_GAMEINPUT_THREAD=0) a test calls it, always from the same thread, because SDL's joystick calls must be. -void poll(); - -// Number of gamepads currently open by the backend (tests, gameinput_probe). -int connected_count(); - -// The kind of device the player used last (src/active_input.h has the rules), or the one LEONIDA_PROMPTS forces. -// The title is told every pad is an Xbox One pad; this is for the runtime's own use, such as button prompt glyphs. -// Safe from any thread. `generation` goes up by one with each change of `family`, so a reader can check it every -// frame and act only when it moved. Xbox, generation 0, until the first deliberate input. -struct ActiveInput { - leonida::InputFamily family = leonida::InputFamily::Xbox; - uint64_t generation = 0; - bool forced = false; // LEONIDA_PROMPTS set the family -}; -ActiveInput active_input(); - -// The SDL haptic calls the shim makes, one entry per call, so a test can stand in for them: SDL's virtual joysticks -// report no haptics, and a pad that does is the only other way to reach this path. `joystick` is the SDL_Joystick the -// gamepad was opened from, `haptic` what open_joystick returned, `effect` is an SDL_HapticEffect. Returning null from -// open_joystick says the pad has no force feedback, which is what a pad without it does. -struct HapticApi { - void* (*open_joystick)(void* joystick); // SDL_OpenHapticFromJoystick - void (*close)(void* haptic); // SDL_CloseHaptic - uint32_t (*features)(void* haptic); // SDL_GetHapticFeatures: the SDL_HAPTIC_* bits the device supports - int (*max_effects)(void* haptic); // SDL_GetMaxHapticEffects - int (*create_effect)(void* haptic, const void* effect); // SDL_CreateHapticEffect, -1 on failure - bool (*update_effect)(void* haptic, int effect, const void* data); // SDL_UpdateHapticEffect - bool (*run_effect)(void* haptic, int effect, uint32_t iterations); // SDL_RunHapticEffect - bool (*stop_effect)(void* haptic, int effect); // SDL_StopHapticEffect - void (*destroy_effect)(void* haptic, int effect); // SDL_DestroyHapticEffect - bool (*set_gain)(void* haptic, int gain); // SDL_SetHapticGain, 0..100 -}; -// Where the haptics come from (tests). nullptr restores SDL. Applies to pads opened after the call: a pad keeps the -// haptic device it was opened with. -void set_haptic_source(const HapticApi* api); - -// What the shim last sent to SDL for the device that is index `i` in connection order. Test seam. -struct OutputState { - uint16_t low = 0, high = 0; // SDL_RumbleGamepad - uint16_t left = 0, right = 0; // SDL_RumbleGamepadTriggers - uint8_t ds_right[11] = {}, ds_left[11] = {}; // last DualSense trigger effects sent - bool is_dualsense = false; - bool trigger_rumble = false; // the pad takes SDL_RumbleGamepadTriggers - bool force_feedback = false; // SDL opened the pad as a haptic device - uint32_t haptic_motors = 0; // haptic motors the pad reports (0 or 2) - // The last force-feedback effect the shim asked SDL for: SDL_CreateHapticEffect's id (-1 when SDL refused), - // whether SDL_RunHapticEffect then returned true, and SDL's error text when a call failed. `force_feedback` only - // says a haptic device was opened; an effect SDL creates but will not run, or refuses outright, shows up here. - int effect_id = -1; - bool effect_ran = false; - char effect_error[128] = {}; -}; -bool output_state(int i, OutputState* out); - -// Where the keyboard pad reads keys from. Test seam: key_down(virtual_key) replaces GetAsyncKeyState, has_focus -// replaces the foreground-window check of KeyboardPadMode::Focused. nullptr restores the default for either. -using KeyDownFn = bool (*)(int virtual_key); -using HasFocusFn = bool (*)(); -void set_keyboard_source(KeyDownFn key_down, HasFocusFn has_focus); - -// Where the keyboard pad reads the mouse cursor from (screen pixels; false when it cannot be read). Test seam: -// replaces GetCursorPos. nullptr restores the default. -using CursorPosFn = bool (*)(int* x, int* y); -void set_cursor_source(CursorPosFn cursor_pos); - -// Raw HID (RT-175, docs/gameinput.md "Raw HID"). One report a HID report descriptor declares: its kind -// (GameInputRawDeviceReportKind: 0 input, 1 output, 2 feature), its report id (0 when the descriptor declares none) -// and its payload size in bytes, without the id byte. -struct RawReportSize { - int kind; - uint32_t id; - uint32_t bytes; -}; -// Reads the reports out of a HID report descriptor, sorted by kind then id. Main items Input/Output/Feature add -// Report Size x Report Count bits to the current report id; Push and Pop save and restore the globals; long items are -// skipped. False on a truncated descriptor, a Report ID of 0 or above 255, a Pop without a Push, or a report over -// 64 KiB. -bool parse_report_descriptor(const uint8_t* data, size_t size, std::vector* out); - -// Where the shim does a pad's HID I/O. The default is SDL's hidapi (SDL_hid_*). Report buffers follow hidapi: they -// start with the report id byte (0 for a device without ids) for write, get_feature and send_feature, and read -// returns it first only when the device uses ids. read never blocks: it returns 0 when nothing is pending. Every -// call returns a byte count, or a negative value on error. -struct HidBackend { - void* (*open)(const char* path, uint16_t vendor, uint16_t product); // nullptr: no HID device for this pad - void (*close)(void* hid); - int (*descriptor)(void* hid, uint8_t* buf, size_t size); - int (*read)(void* hid, uint8_t* buf, size_t size); - int (*write)(void* hid, const uint8_t* buf, size_t size); - int (*get_feature)(void* hid, uint8_t* buf, size_t size); - int (*send_feature)(void* hid, const uint8_t* buf, size_t size); -}; -// Test seam: the backend for pads opened from now on (pads already open keep theirs until they reconnect). nullptr -// restores SDL's. -void set_hid_backend(const HidBackend* backend); - -// One row of the keyboard pad's key map: a Windows virtual-key code and the SDL gamepad button it presses. -struct KeyBinding { - int virtual_key; - int sdl_button; // SDL_GamepadButton - const char* key_name; -}; -// The fixed key map (docs/gameinput.md lists it). `count` receives the number of rows. -const KeyBinding* keyboard_bindings(int* count); - -} // namespace rt::gameinput diff --git a/runtime/shims/gameinput_abi.h b/runtime/shims/gameinput_abi.h deleted file mode 100644 index a1a17c8a1..000000000 --- a/runtime/shims/gameinput_abi.h +++ /dev/null @@ -1,813 +0,0 @@ -// GameInput v0 ABI: the part of Microsoft's GameInput API a title uses for gamepads. -// -// These are Leonida's own declarations, written to match the binary layout of the public v0 GameInput API (the -// in-box GDK version, also shipped as the Microsoft.GameInput 0.2303.x NuGet package). Only what the shim implements -// or must lay out is declared; interface methods are in vtable order and every struct is checked with static_asserts -// below. Names follow the public API so the docs at learn.microsoft.com/gaming/gdk/docs/reference/input/gameinput -// apply directly. -// -// VERIFY: GameInput v1 and later (the 1.x-4.x NuGet packages) changed the interfaces. Which version the console -// executable was built against is unknown until it is available; this file is v0. -#pragma once -#include -#include - -#include -#include - -namespace gi { - -enum GameInputKind : uint32_t { - GameInputKindUnknown = 0x00000000, - GameInputKindRawDeviceReport = 0x00000001, - GameInputKindControllerAxis = 0x00000002, - GameInputKindControllerButton = 0x00000004, - GameInputKindControllerSwitch = 0x00000008, - GameInputKindController = 0x0000000E, - GameInputKindKeyboard = 0x00000010, - GameInputKindMouse = 0x00000020, - GameInputKindTouch = 0x00000100, - GameInputKindMotion = 0x00001000, - GameInputKindArcadeStick = 0x00010000, - GameInputKindFlightStick = 0x00020000, - GameInputKindGamepad = 0x00040000, - GameInputKindRacingWheel = 0x00080000, - GameInputKindUiNavigation = 0x01000000, -}; - -enum GameInputEnumerationKind : int32_t { - GameInputNoEnumeration = 0, - GameInputAsyncEnumeration = 1, - GameInputBlockingEnumeration = 2, -}; - -enum GameInputGamepadButtons : uint32_t { - GameInputGamepadNone = 0x00000000, - GameInputGamepadMenu = 0x00000001, - GameInputGamepadView = 0x00000002, - GameInputGamepadA = 0x00000004, - GameInputGamepadB = 0x00000008, - GameInputGamepadX = 0x00000010, - GameInputGamepadY = 0x00000020, - GameInputGamepadDPadUp = 0x00000040, - GameInputGamepadDPadDown = 0x00000080, - GameInputGamepadDPadLeft = 0x00000100, - GameInputGamepadDPadRight = 0x00000200, - GameInputGamepadLeftShoulder = 0x00000400, - GameInputGamepadRightShoulder = 0x00000800, - GameInputGamepadLeftThumbstick = 0x00001000, - GameInputGamepadRightThumbstick = 0x00002000, -}; - -enum GameInputUiNavigationButtons : uint32_t { - GameInputUiNavigationNone = 0x00000000, - GameInputUiNavigationMenu = 0x00000001, - GameInputUiNavigationView = 0x00000002, - GameInputUiNavigationAccept = 0x00000004, - GameInputUiNavigationCancel = 0x00000008, - GameInputUiNavigationUp = 0x00000010, - GameInputUiNavigationDown = 0x00000020, - GameInputUiNavigationLeft = 0x00000040, - GameInputUiNavigationRight = 0x00000080, - GameInputUiNavigationContext1 = 0x00000100, - GameInputUiNavigationContext2 = 0x00000200, - GameInputUiNavigationContext3 = 0x00000400, - GameInputUiNavigationContext4 = 0x00000800, - GameInputUiNavigationPageUp = 0x00001000, - GameInputUiNavigationPageDown = 0x00002000, - GameInputUiNavigationPageLeft = 0x00004000, - GameInputUiNavigationPageRight = 0x00008000, - GameInputUiNavigationScrollUp = 0x00010000, - GameInputUiNavigationScrollDown = 0x00020000, - GameInputUiNavigationScrollLeft = 0x00040000, - GameInputUiNavigationScrollRight = 0x00080000, -}; - -enum GameInputDeviceStatus : uint32_t { - GameInputDeviceNoStatus = 0x00000000, - GameInputDeviceConnected = 0x00000001, - GameInputDeviceInputEnabled = 0x00000002, - GameInputDeviceOutputEnabled = 0x00000004, - GameInputDeviceRawIoEnabled = 0x00000008, - GameInputDeviceAudioCapture = 0x00000010, - GameInputDeviceAudioRender = 0x00000020, - GameInputDeviceSynchronized = 0x00000040, - GameInputDeviceWireless = 0x00000080, - GameInputDeviceUserIdle = 0x00100000, - GameInputDeviceAnyStatus = 0x00FFFFFF, -}; - -enum GameInputBatteryStatus : int32_t { - GameInputBatteryUnknown = -1, - GameInputBatteryNotPresent = 0, - GameInputBatteryDischarging = 1, - GameInputBatteryIdle = 2, - GameInputBatteryCharging = 3, -}; - -enum GameInputDeviceFamily : int32_t { - GameInputFamilyVirtual = -1, - GameInputFamilyAggregate = 0, - GameInputFamilyXboxOne = 1, - GameInputFamilyXbox360 = 2, - GameInputFamilyHid = 3, - GameInputFamilyI8042 = 4, -}; - -enum GameInputDeviceCapabilities : uint32_t { - GameInputDeviceCapabilityNone = 0x00000000, - GameInputDeviceCapabilityAudio = 0x00000001, - GameInputDeviceCapabilityPluginModule = 0x00000002, - GameInputDeviceCapabilityPowerOff = 0x00000004, - GameInputDeviceCapabilitySynchronization = 0x00000008, - GameInputDeviceCapabilityWireless = 0x00000010, -}; - -enum GameInputRumbleMotors : uint32_t { - GameInputRumbleNone = 0x00000000, - GameInputRumbleLowFrequency = 0x00000001, - GameInputRumbleHighFrequency = 0x00000002, - GameInputRumbleLeftTrigger = 0x00000004, - GameInputRumbleRightTrigger = 0x00000008, -}; - -// Where a motor sits on the device. v0 carries it in the motor infos below. -enum GameInputLocation : int32_t { - GameInputLocationUnknown = -1, - GameInputLocationChassis = 0, - GameInputLocationDisplay = 1, - GameInputLocationAxis = 2, - GameInputLocationButton = 3, - GameInputLocationSwitch = 4, - GameInputLocationKey = 5, - GameInputLocationTouchPad = 6, -}; - -// The axes a force-feedback motor can drive, and the kinds of effect it can play. -enum GameInputFeedbackAxes : uint32_t { - GameInputFeedbackAxisNone = 0x00000000, - GameInputFeedbackAxisLinearX = 0x00000001, - GameInputFeedbackAxisLinearY = 0x00000002, - GameInputFeedbackAxisLinearZ = 0x00000004, - GameInputFeedbackAxisAngularX = 0x00000008, - GameInputFeedbackAxisAngularY = 0x00000010, - GameInputFeedbackAxisAngularZ = 0x00000020, - GameInputFeedbackAxisNormal = 0x00000040, -}; - -enum GameInputFeedbackEffectState : int32_t { - GameInputFeedbackStopped = 0, - GameInputFeedbackRunning = 1, - GameInputFeedbackPaused = 2, -}; - -enum GameInputForceFeedbackEffectKind : int32_t { - GameInputForceFeedbackConstant = 0, - GameInputForceFeedbackRamp = 1, - GameInputForceFeedbackSineWave = 2, - GameInputForceFeedbackSquareWave = 3, - GameInputForceFeedbackTriangleWave = 4, - GameInputForceFeedbackSawtoothUpWave = 5, - GameInputForceFeedbackSawtoothDownWave = 6, - GameInputForceFeedbackSpring = 7, - GameInputForceFeedbackFriction = 8, - GameInputForceFeedbackDamper = 9, - GameInputForceFeedbackInertia = 10, -}; - -enum GameInputSwitchPosition : int32_t { GameInputSwitchCenter = 0 }; -enum GameInputFocusPolicy : uint32_t { GameInputDefaultFocusPolicy = 0 }; - -// What is printed on a control, in the device info below. Only the labels the shim reports are declared. The values -// are the ones Microsoft Learn's GameInputLabel page lists, unchanged since v0 by that page's version history. -enum GameInputLabel : int32_t { - GameInputLabelUnknown = -1, - GameInputLabelNone = 0, - GameInputLabelXboxGuide = 1, - GameInputLabelXboxMenu = 4, - GameInputLabelXboxView = 5, - GameInputLabelXboxA = 7, - GameInputLabelXboxB = 8, - GameInputLabelXboxX = 9, - GameInputLabelXboxY = 10, - GameInputLabelXboxDPadUp = 11, - GameInputLabelXboxDPadDown = 12, - GameInputLabelXboxDPadLeft = 13, - GameInputLabelXboxDPadRight = 14, - GameInputLabelXboxLeftShoulder = 15, - GameInputLabelXboxLeftTrigger = 16, - GameInputLabelXboxLeftStickButton = 17, - GameInputLabelXboxRightShoulder = 18, - GameInputLabelXboxRightTrigger = 19, - GameInputLabelXboxRightStickButton = 20, -}; - -using GameInputCallbackToken = uint64_t; -constexpr GameInputCallbackToken kInvalidCallbackToken = 0; - -// Error codes (facility 0x38A). -constexpr HRESULT GAMEINPUT_E_DEVICE_DISCONNECTED = static_cast(0x838A0001L); -constexpr HRESULT GAMEINPUT_E_DEVICE_NOT_FOUND = static_cast(0x838A0002L); -constexpr HRESULT GAMEINPUT_E_READING_NOT_FOUND = static_cast(0x838A0003L); -constexpr HRESULT GAMEINPUT_E_REFERENCE_READING_TOO_OLD = static_cast(0x838A0004L); -constexpr HRESULT GAMEINPUT_E_TIMESTAMP_OUT_OF_RANGE = static_cast(0x838A0005L); -constexpr HRESULT GAMEINPUT_E_INSUFFICIENT_FORCE_FEEDBACK_RESOURCES = static_cast(0x838A0006L); - -struct AppLocalDeviceId { // APP_LOCAL_DEVICE_ID - uint8_t value[32]; -}; - -struct GameInputGamepadState { - uint32_t buttons; // GameInputGamepadButtons - float leftTrigger; - float rightTrigger; - float leftThumbstickX; - float leftThumbstickY; - float rightThumbstickX; - float rightThumbstickY; -}; - -struct GameInputUiNavigationState { - uint32_t buttons; // GameInputUiNavigationButtons -}; - -struct GameInputBatteryState { - float chargeRate; - float maxChargeRate; - float remainingCapacity; - float fullChargeCapacity; - GameInputBatteryStatus status; -}; - -struct GameInputUsage { - uint16_t page; - uint16_t id; -}; - -struct GameInputRumbleParams { - float lowFrequency; - float highFrequency; - float leftTrigger; - float rightTrigger; -}; - -// ---- force feedback and haptic motors ------------------------------------------------------------ -// One entry of GameInputDeviceInfo::forceFeedbackMotorInfo per motor. -struct GameInputForceFeedbackMotorInfo { - GameInputFeedbackAxes supportedAxes; - GameInputLocation location; - uint32_t locationId; - uint32_t maxSimultaneousEffects; - bool isConstantEffectSupported; - bool isRampEffectSupported; - bool isSineWaveEffectSupported; - bool isSquareWaveEffectSupported; - bool isTriangleWaveEffectSupported; - bool isSawtoothUpWaveEffectSupported; - bool isSawtoothDownWaveEffectSupported; - bool isSpringEffectSupported; - bool isFrictionEffectSupported; - bool isDamperEffectSupported; - bool isInertiaEffectSupported; -}; - -// One entry of GameInputHapticFeedbackMotorInfo::waveformInfo per waveform the motor can play. -struct GameInputHapticWaveformInfo { - GameInputUsage usage; // the HID usage of the waveform - bool isDurationSupported; - bool isIntensitySupported; - bool isRepeatSupported; - bool isRepeatDelaySupported; - uint64_t defaultDuration; // microseconds -}; - -// One entry of GameInputDeviceInfo::hapticFeedbackMotorInfo per haptic motor. -struct GameInputHapticFeedbackMotorInfo { - GameInputRumbleMotors mappedRumbleMotors; // the rumble motors this haptic motor sits on - GameInputLocation location; - uint32_t locationId; - uint32_t waveformCount; - const GameInputHapticWaveformInfo* waveformInfo; -}; - -// An effect's duration and gain over time. The durations are microseconds; 0 everywhere means the effect has no -// envelope and lasts until it is stopped, and playCount 0 means the same. -struct GameInputForceFeedbackEnvelope { - uint64_t attackDuration; - uint64_t sustainDuration; - uint64_t releaseDuration; - float attackGain; - float sustainGain; - float releaseGain; - uint32_t playCount; - uint64_t repeatDelay; -}; - -// An effect's strength per axis, -1..1 (the axis is chosen by the motor's supportedAxes). -struct GameInputForceFeedbackMagnitude { - float linearX; - float linearY; - float linearZ; - float angularX; - float angularY; - float angularZ; - float normal; -}; - -struct GameInputForceFeedbackConditionParams { - GameInputForceFeedbackMagnitude magnitude; - float positiveCoefficient; - float negativeCoefficient; - float maxPositiveMagnitude; - float maxNegativeMagnitude; - float deadZone; - float bias; -}; - -struct GameInputForceFeedbackConstantParams { - GameInputForceFeedbackEnvelope envelope; - GameInputForceFeedbackMagnitude magnitude; -}; - -// Sine, square, triangle and both sawtooth waves. `frequency` is Hz and `phase` degrees (the shim's reading of the -// GDK remarks: 0 is no displacement); SDL takes a period in ms and a phase in hundredths of a degree. -struct GameInputForceFeedbackPeriodicParams { - GameInputForceFeedbackEnvelope envelope; - GameInputForceFeedbackMagnitude magnitude; - float frequency; - float phase; - float bias; -}; - -struct GameInputForceFeedbackRampParams { - GameInputForceFeedbackEnvelope envelope; - GameInputForceFeedbackMagnitude startMagnitude; - GameInputForceFeedbackMagnitude endMagnitude; -}; - -// What CreateForceFeedbackEffect and IGameInputForceFeedbackEffect::SetParams take: `kind` chooses the union member. -struct GameInputForceFeedbackParams { - GameInputForceFeedbackEffectKind kind; - union { - GameInputForceFeedbackConstantParams constant; - GameInputForceFeedbackRampParams ramp; - GameInputForceFeedbackPeriodicParams sineWave; - GameInputForceFeedbackPeriodicParams squareWave; - GameInputForceFeedbackPeriodicParams triangleWave; - GameInputForceFeedbackPeriodicParams sawtoothUpWave; - GameInputForceFeedbackPeriodicParams sawtoothDownWave; - GameInputForceFeedbackConditionParams spring; - GameInputForceFeedbackConditionParams friction; - GameInputForceFeedbackConditionParams damper; - GameInputForceFeedbackConditionParams inertia; - } data; -}; - -// What SetHapticMotorState takes: one waveform of the motor's waveformInfo, played `playCount` times. `duration` and -// `repeatDelay` are microseconds; playCount 0 plays until the state is set again. -struct GameInputHapticFeedbackParams { - uint32_t waveformIndex; - uint64_t duration; - float intensity; - uint32_t playCount; - uint64_t repeatDelay; -}; - -struct GameInputString { - uint32_t sizeInBytes; - uint32_t codePointCount; - const char* data; // UTF-8, zero-terminated -}; - -struct GameInputVersion { - uint16_t major, minor, build, revision; -}; - -// Raw HID reports (RT-175). Layouts and order match Microsoft's v0 header (NuGet Microsoft.GameInput -// 0.2303.22621.3038), checked with offsetof against it (docs/gameinput.md, "ABI"); the shim fills reportInfo with -// each report's kind, id and size and no items (itemCount 0, see docs/gameinput.md "Raw HID"). -enum GameInputRawDeviceReportKind : int32_t { - GameInputRawInputReport = 0, - GameInputRawOutputReport = 1, - GameInputRawFeatureReport = 2, -}; - -struct GameInputRawDeviceItemCollectionInfo { - int32_t kind; // GameInputRawDeviceItemCollectionKind - uint32_t childCount; - uint32_t siblingCount; - uint32_t usageCount; - const GameInputUsage* usages; - const GameInputRawDeviceItemCollectionInfo* parent; - const GameInputRawDeviceItemCollectionInfo* firstSibling; - const GameInputRawDeviceItemCollectionInfo* previousSibling; - const GameInputRawDeviceItemCollectionInfo* nextSibling; - const GameInputRawDeviceItemCollectionInfo* lastSibling; - const GameInputRawDeviceItemCollectionInfo* firstChild; - const GameInputRawDeviceItemCollectionInfo* lastChild; -}; - -struct GameInputRawDeviceReportItemInfo { - uint32_t bitOffset; - uint32_t bitSize; - int64_t logicalMin; - int64_t logicalMax; - double physicalMin; - double physicalMax; - int32_t physicalUnits; // GameInputRawDevicePhysicalUnitKind - uint32_t rawPhysicalUnits; - int32_t rawPhysicalUnitsExponent; - uint32_t flags; // GameInputRawDeviceReportItemFlags - uint32_t usageCount; - const GameInputUsage* usages; - const GameInputRawDeviceItemCollectionInfo* collection; - const GameInputString* itemString; -}; - -struct GameInputRawDeviceReportInfo { - GameInputRawDeviceReportKind kind; - uint32_t id; - uint32_t size; - uint32_t itemCount; - const GameInputRawDeviceReportItemInfo* items; -}; - -// One axis and one button of the controller-axis and controller-button arrays. In the public v0 header the label -// comes right after mappedInputKinds; it fills what would otherwise be padding, so the sizes do not show it. -struct GameInputControllerAxisInfo { - uint32_t mappedInputKinds; // GameInputKind - GameInputLabel label; - bool isContinuous; - bool isNonlinear; - bool isQuantized; - bool hasRestValue; - float restValue; - uint64_t resolution; - uint16_t legacyDInputIndex; - uint16_t legacyHidIndex; - uint32_t rawReportIndex; - const GameInputRawDeviceReportInfo* inputReport; - const GameInputRawDeviceReportItemInfo* inputReportItem; -}; - -struct GameInputControllerButtonInfo { - uint32_t mappedInputKinds; // GameInputKind - GameInputLabel label; - uint16_t legacyDInputIndex; - uint16_t legacyHidIndex; - uint32_t rawReportIndex; - const GameInputRawDeviceReportInfo* inputReport; - const GameInputRawDeviceReportItemInfo* inputReportItem; -}; - -// The label of each control behind the gamepad state and the UI navigation state: 14 and 21 labels and nothing else. -// The member order is the public v0 header's, and the host's GameInput 0.2309 fills both this way (docs/gameinput.md, -// "ABI"). Learn's pages of these two names describe later versions, which start with another member. -struct GameInputGamepadInfo { - GameInputLabel menuButtonLabel; - GameInputLabel viewButtonLabel; - GameInputLabel aButtonLabel; - GameInputLabel bButtonLabel; - GameInputLabel xButtonLabel; - GameInputLabel yButtonLabel; - GameInputLabel dpadUpLabel; - GameInputLabel dpadDownLabel; - GameInputLabel dpadLeftLabel; - GameInputLabel dpadRightLabel; - GameInputLabel leftShoulderButtonLabel; - GameInputLabel rightShoulderButtonLabel; - GameInputLabel leftThumbstickButtonLabel; - GameInputLabel rightThumbstickButtonLabel; -}; - -struct GameInputUiNavigationInfo { - GameInputLabel menuButtonLabel; - GameInputLabel viewButtonLabel; - GameInputLabel acceptButtonLabel; - GameInputLabel cancelButtonLabel; - GameInputLabel upButtonLabel; - GameInputLabel downButtonLabel; - GameInputLabel leftButtonLabel; - GameInputLabel rightButtonLabel; - GameInputLabel contextButton1Label; - GameInputLabel contextButton2Label; - GameInputLabel contextButton3Label; - GameInputLabel contextButton4Label; - GameInputLabel pageUpButtonLabel; - GameInputLabel pageDownButtonLabel; - GameInputLabel pageLeftButtonLabel; - GameInputLabel pageRightButtonLabel; - GameInputLabel scrollUpButtonLabel; - GameInputLabel scrollDownButtonLabel; - GameInputLabel scrollLeftButtonLabel; - GameInputLabel scrollRightButtonLabel; - GameInputLabel guideButtonLabel; -}; - -// Motion: layouts from Microsoft's v0 documentation (learn.microsoft.com GameInputMotionInfo / GameInputMotionState / -// GameInputMotionAccuracy; the GDK public header spells the same members). Accuracy is deprecated only in GameInput -// v1 and later; v0 still uses it in GameInputMotionState. -enum GameInputMotionAccuracy : int32_t { - GameInputMotionAccuracyUnknown = -1, - GameInputMotionAccuracyUnreliable = 0, - GameInputMotionAccuracyLow = 1, - GameInputMotionAccuracyMedium = 2, - GameInputMotionAccuracyHigh = 3, -}; - -struct GameInputMotionInfo { - float maxAcceleration; // m/s^2; 0 says acceleration input is not available - float maxAngularVelocity; // rad/s; 0 says angular-velocity input is not available - float maxMagneticFieldStrength; // teslas; 0 says magnetic-field input is not available -}; - -// The state GetMotionState writes. Each float is the signed fraction of the GameInputMotionInfo maximum for its -// sensor (1.0 = full magnitude); orientation is a quaternion. SDL delivers accel in m/s^2 (gravity included) and -// gyro in rad/s, so the shim divides by the maxima it reports in motionInfo. -struct GameInputMotionState { - float accelerationX; - float accelerationY; - float accelerationZ; - float angularVelocityX; - float angularVelocityY; - float angularVelocityZ; - float magneticFieldX; - float magneticFieldY; - float magneticFieldZ; - float orientationW; - float orientationX; - float orientationY; - float orientationZ; - GameInputMotionAccuracy accelerometerAccuracy; - GameInputMotionAccuracy gyroscopeAccuracy; - GameInputMotionAccuracy magnetometerAccuracy; - GameInputMotionAccuracy orientationAccuracy; -}; - -struct GameInputDeviceInfo { - uint32_t infoSize; - uint16_t vendorId; - uint16_t productId; - uint16_t revisionNumber; - uint8_t interfaceNumber; - uint8_t collectionNumber; - GameInputUsage usage; - GameInputVersion hardwareVersion; - GameInputVersion firmwareVersion; - AppLocalDeviceId deviceId; - AppLocalDeviceId deviceRootId; - GameInputDeviceFamily deviceFamily; - uint32_t capabilities; // GameInputDeviceCapabilities - uint32_t supportedInput; // GameInputKind - uint32_t supportedRumbleMotors; // GameInputRumbleMotors - uint32_t inputReportCount; - uint32_t outputReportCount; - uint32_t featureReportCount; - uint32_t controllerAxisCount; - uint32_t controllerButtonCount; - uint32_t controllerSwitchCount; - uint32_t touchPointCount; - uint32_t touchSensorCount; - uint32_t forceFeedbackMotorCount; - uint32_t hapticFeedbackMotorCount; - uint32_t deviceStringCount; - uint32_t deviceDescriptorSize; - const GameInputRawDeviceReportInfo* inputReportInfo; - const GameInputRawDeviceReportInfo* outputReportInfo; - const GameInputRawDeviceReportInfo* featureReportInfo; - const GameInputControllerAxisInfo* controllerAxisInfo; - const GameInputControllerButtonInfo* controllerButtonInfo; - const void* controllerSwitchInfo; - const void* keyboardInfo; - const void* mouseInfo; - const void* touchSensorInfo; - const void* motionInfo; - const void* arcadeStickInfo; - const void* flightStickInfo; - const GameInputGamepadInfo* gamepadInfo; - const void* racingWheelInfo; - const GameInputUiNavigationInfo* uiNavigationInfo; - const void* forceFeedbackMotorInfo; - const void* hapticFeedbackMotorInfo; - const GameInputString* displayName; - const GameInputString* deviceStrings; - const void* deviceDescriptorData; -}; - -// Layout checks. The offsets were compared with the public v0 header by compiling both side by side (see -// docs/gameinput.md); they hold for x64 MSVC. -static_assert(sizeof(GameInputGamepadState) == 28); -static_assert(sizeof(GameInputRumbleParams) == 16); -static_assert(sizeof(GameInputBatteryState) == 20); -static_assert(sizeof(GameInputString) == 16); -static_assert(sizeof(GameInputMotionInfo) == 12); -static_assert(sizeof(GameInputMotionState) == 68); -static_assert(sizeof(GameInputControllerAxisInfo) == 48); -static_assert(sizeof(GameInputControllerButtonInfo) == 32); -// The members behind a label, and the two label tables: a size of 48 or 32 holds with or without the label, so -// each offset it moves is pinned here. -static_assert(offsetof(GameInputControllerAxisInfo, label) == 4); -static_assert(offsetof(GameInputControllerAxisInfo, isContinuous) == 8); -static_assert(offsetof(GameInputControllerAxisInfo, isNonlinear) == 9); -static_assert(offsetof(GameInputControllerAxisInfo, isQuantized) == 10); -static_assert(offsetof(GameInputControllerAxisInfo, hasRestValue) == 11); -static_assert(offsetof(GameInputControllerAxisInfo, restValue) == 12); -static_assert(offsetof(GameInputControllerAxisInfo, resolution) == 16); -static_assert(offsetof(GameInputControllerButtonInfo, label) == 4); -static_assert(offsetof(GameInputControllerButtonInfo, legacyDInputIndex) == 8); -static_assert(offsetof(GameInputControllerButtonInfo, legacyHidIndex) == 10); -static_assert(offsetof(GameInputControllerButtonInfo, rawReportIndex) == 12); -static_assert(offsetof(GameInputControllerButtonInfo, inputReport) == 16); -static_assert(sizeof(GameInputGamepadInfo) == 56); -static_assert(offsetof(GameInputGamepadInfo, rightThumbstickButtonLabel) == 52); -static_assert(sizeof(GameInputUiNavigationInfo) == 84); -static_assert(offsetof(GameInputUiNavigationInfo, guideButtonLabel) == 80); -static_assert(offsetof(GameInputDeviceInfo, deviceId) == 32); -static_assert(offsetof(GameInputDeviceInfo, deviceFamily) == 96); -static_assert(offsetof(GameInputDeviceInfo, inputReportCount) == 112); -static_assert(offsetof(GameInputDeviceInfo, inputReportInfo) == 160); -static_assert(offsetof(GameInputDeviceInfo, gamepadInfo) == 256); -static_assert(offsetof(GameInputDeviceInfo, displayName) == 296); -static_assert(sizeof(GameInputDeviceInfo) == 320); -static_assert(sizeof(GameInputRawDeviceItemCollectionInfo) == 80); -static_assert(offsetof(GameInputRawDeviceItemCollectionInfo, usages) == 16); -static_assert(offsetof(GameInputRawDeviceReportItemInfo, physicalUnits) == 40); -static_assert(offsetof(GameInputRawDeviceReportItemInfo, usages) == 64); -static_assert(sizeof(GameInputRawDeviceReportItemInfo) == 88); -static_assert(offsetof(GameInputRawDeviceReportInfo, items) == 16); -static_assert(sizeof(GameInputRawDeviceReportInfo) == 24); - -// The force-feedback and haptic layouts, transcribed from the public v0 header (GameInput.h, the same GDK release -// as the rest of this file). They were not compiled against that header here — it is not in the repository — so -// the sizes and offsets below are the check: they are what x64 MSVC lays out for those declarations. -static_assert(sizeof(GameInputForceFeedbackMotorInfo) == 28); -static_assert(offsetof(GameInputForceFeedbackMotorInfo, location) == 4); -static_assert(offsetof(GameInputForceFeedbackMotorInfo, maxSimultaneousEffects) == 12); -static_assert(offsetof(GameInputForceFeedbackMotorInfo, isConstantEffectSupported) == 16); -static_assert(sizeof(GameInputHapticWaveformInfo) == 16); -static_assert(offsetof(GameInputHapticWaveformInfo, defaultDuration) == 8); -static_assert(sizeof(GameInputHapticFeedbackMotorInfo) == 24); -static_assert(offsetof(GameInputHapticFeedbackMotorInfo, waveformInfo) == 16); -static_assert(sizeof(GameInputForceFeedbackEnvelope) == 48); -static_assert(offsetof(GameInputForceFeedbackEnvelope, repeatDelay) == 40); -static_assert(sizeof(GameInputForceFeedbackMagnitude) == 28); -static_assert(sizeof(GameInputForceFeedbackConditionParams) == 52); -static_assert(sizeof(GameInputForceFeedbackConstantParams) == 80); // 76 rounded up to the envelope's 8-byte alignment -static_assert(offsetof(GameInputForceFeedbackConstantParams, magnitude) == 48); -static_assert(sizeof(GameInputForceFeedbackPeriodicParams) == 88); -static_assert(sizeof(GameInputForceFeedbackRampParams) == 104); -static_assert(sizeof(GameInputForceFeedbackParams) == 112); -static_assert(offsetof(GameInputForceFeedbackParams, data) == 8); -static_assert(sizeof(GameInputHapticFeedbackParams) == 32); -static_assert(offsetof(GameInputHapticFeedbackParams, repeatDelay) == 24); - -struct IGameInputDevice; -struct IGameInputReading; -struct IGameInputDispatcher; - -using GameInputReadingCallback = void(CALLBACK*)(GameInputCallbackToken, void* context, IGameInputReading* reading, - bool hasOverrunOccurred); -using GameInputDeviceCallback = void(CALLBACK*)(GameInputCallbackToken, void* context, IGameInputDevice* device, - uint64_t timestamp, uint32_t currentStatus, uint32_t previousStatus); -using GameInputGuideButtonCallback = void(CALLBACK*)(GameInputCallbackToken, void* context, IGameInputDevice* device, - uint64_t timestamp, bool isPressed); -using GameInputKeyboardLayoutCallback = void(CALLBACK*)(GameInputCallbackToken, void* context, - IGameInputDevice* device, uint64_t timestamp, - uint32_t currentLayout, uint32_t previousLayout); - -// {11BE2A7E-4254-445A-9C09-FFC40F006918} -constexpr GUID IID_IGameInput = {0x11BE2A7E, 0x4254, 0x445A, {0x9C, 0x09, 0xFF, 0xC4, 0x0F, 0x00, 0x69, 0x18}}; -// {2156947A-E1FA-4DE0-A30B-D812931DBD8D} -constexpr GUID IID_IGameInputReading = {0x2156947A, 0xE1FA, 0x4DE0, {0xA3, 0x0B, 0xD8, 0x12, 0x93, 0x1D, 0xBD, 0x8D}}; -// {31DD86FB-4C1B-408A-868F-439B3CD47125} -constexpr GUID IID_IGameInputDevice = {0x31DD86FB, 0x4C1B, 0x408A, {0x86, 0x8F, 0x43, 0x9B, 0x3C, 0xD4, 0x71, 0x25}}; -// {61F08CF1-1FFC-40CA-A2B8-E1AB8BC5B6DC} -constexpr GUID IID_IGameInputRawDeviceReport = {0x61F08CF1, 0x1FFC, 0x40CA, {0xA2, 0xB8, 0xE1, 0xAB, 0x8B, 0xC5, 0xB6, 0xDC}}; -// {415EED2E-98CB-42C2-8F28-B94601074E31} -constexpr GUID IID_IGameInputDispatcher = {0x415EED2E, 0x98CB, 0x42C2, {0x8F, 0x28, 0xB9, 0x46, 0x01, 0x07, 0x4E, 0x31}}; -// {51BDA05E-F742-45D9-B085-9444AE48381D} -constexpr GUID IID_IGameInputForceFeedbackEffect = {0x51BDA05E, 0xF742, 0x45D9, {0xB0, 0x85, 0x94, 0x44, 0xAE, 0x48, 0x38, 0x1D}}; - -// Interfaces, methods in vtable order. Pointer types the shim never implements are void*. -struct IGameInput : IUnknown { - virtual uint64_t STDMETHODCALLTYPE GetCurrentTimestamp() = 0; - virtual HRESULT STDMETHODCALLTYPE GetCurrentReading(uint32_t inputKind, IGameInputDevice* device, - IGameInputReading** reading) = 0; - virtual HRESULT STDMETHODCALLTYPE GetNextReading(IGameInputReading* referenceReading, uint32_t inputKind, - IGameInputDevice* device, IGameInputReading** reading) = 0; - virtual HRESULT STDMETHODCALLTYPE GetPreviousReading(IGameInputReading* referenceReading, uint32_t inputKind, - IGameInputDevice* device, IGameInputReading** reading) = 0; - virtual HRESULT STDMETHODCALLTYPE GetTemporalReading(uint64_t timestamp, IGameInputDevice* device, - IGameInputReading** reading) = 0; - virtual HRESULT STDMETHODCALLTYPE RegisterReadingCallback(IGameInputDevice* device, uint32_t inputKind, - float analogThreshold, void* context, - GameInputReadingCallback callbackFunc, - GameInputCallbackToken* callbackToken) = 0; - virtual HRESULT STDMETHODCALLTYPE RegisterDeviceCallback(IGameInputDevice* device, uint32_t inputKind, - uint32_t statusFilter, GameInputEnumerationKind enumerationKind, - void* context, GameInputDeviceCallback callbackFunc, - GameInputCallbackToken* callbackToken) = 0; - virtual HRESULT STDMETHODCALLTYPE RegisterGuideButtonCallback(IGameInputDevice* device, void* context, - GameInputGuideButtonCallback callbackFunc, - GameInputCallbackToken* callbackToken) = 0; - virtual HRESULT STDMETHODCALLTYPE RegisterKeyboardLayoutCallback(IGameInputDevice* device, void* context, - GameInputKeyboardLayoutCallback callbackFunc, - GameInputCallbackToken* callbackToken) = 0; - virtual void STDMETHODCALLTYPE StopCallback(GameInputCallbackToken callbackToken) = 0; - virtual bool STDMETHODCALLTYPE UnregisterCallback(GameInputCallbackToken callbackToken, - uint64_t timeoutInMicroseconds) = 0; - virtual HRESULT STDMETHODCALLTYPE CreateDispatcher(IGameInputDispatcher** dispatcher) = 0; - virtual HRESULT STDMETHODCALLTYPE CreateAggregateDevice(uint32_t inputKind, IGameInputDevice** device) = 0; - virtual HRESULT STDMETHODCALLTYPE FindDeviceFromId(const AppLocalDeviceId* value, IGameInputDevice** device) = 0; - virtual HRESULT STDMETHODCALLTYPE FindDeviceFromObject(IUnknown* value, IGameInputDevice** device) = 0; - virtual HRESULT STDMETHODCALLTYPE FindDeviceFromPlatformHandle(HANDLE value, IGameInputDevice** device) = 0; - virtual HRESULT STDMETHODCALLTYPE FindDeviceFromPlatformString(LPCWSTR value, IGameInputDevice** device) = 0; - virtual HRESULT STDMETHODCALLTYPE EnableOemDeviceSupport(uint16_t vendorId, uint16_t productId, - uint8_t interfaceNumber, uint8_t collectionNumber) = 0; - virtual void STDMETHODCALLTYPE SetFocusPolicy(uint32_t policy) = 0; -}; - -struct IGameInputReading : IUnknown { - virtual uint32_t STDMETHODCALLTYPE GetInputKind() = 0; - virtual uint64_t STDMETHODCALLTYPE GetSequenceNumber(uint32_t inputKind) = 0; - virtual uint64_t STDMETHODCALLTYPE GetTimestamp() = 0; - virtual void STDMETHODCALLTYPE GetDevice(IGameInputDevice** device) = 0; - virtual bool STDMETHODCALLTYPE GetRawReport(void** report) = 0; - virtual uint32_t STDMETHODCALLTYPE GetControllerAxisCount() = 0; - virtual uint32_t STDMETHODCALLTYPE GetControllerAxisState(uint32_t stateArrayCount, float* stateArray) = 0; - virtual uint32_t STDMETHODCALLTYPE GetControllerButtonCount() = 0; - virtual uint32_t STDMETHODCALLTYPE GetControllerButtonState(uint32_t stateArrayCount, bool* stateArray) = 0; - virtual uint32_t STDMETHODCALLTYPE GetControllerSwitchCount() = 0; - virtual uint32_t STDMETHODCALLTYPE GetControllerSwitchState(uint32_t stateArrayCount, - GameInputSwitchPosition* stateArray) = 0; - virtual uint32_t STDMETHODCALLTYPE GetKeyCount() = 0; - virtual uint32_t STDMETHODCALLTYPE GetKeyState(uint32_t stateArrayCount, void* stateArray) = 0; - virtual bool STDMETHODCALLTYPE GetMouseState(void* state) = 0; - virtual uint32_t STDMETHODCALLTYPE GetTouchCount() = 0; - virtual uint32_t STDMETHODCALLTYPE GetTouchState(uint32_t stateArrayCount, void* stateArray) = 0; - virtual bool STDMETHODCALLTYPE GetMotionState(void* state) = 0; - virtual bool STDMETHODCALLTYPE GetArcadeStickState(void* state) = 0; - virtual bool STDMETHODCALLTYPE GetFlightStickState(void* state) = 0; - virtual bool STDMETHODCALLTYPE GetGamepadState(GameInputGamepadState* state) = 0; - virtual bool STDMETHODCALLTYPE GetRacingWheelState(void* state) = 0; - virtual bool STDMETHODCALLTYPE GetUiNavigationState(GameInputUiNavigationState* state) = 0; -}; - -struct IGameInputDevice : IUnknown { - virtual const GameInputDeviceInfo* STDMETHODCALLTYPE GetDeviceInfo() = 0; - virtual uint32_t STDMETHODCALLTYPE GetDeviceStatus() = 0; - virtual void STDMETHODCALLTYPE GetBatteryState(GameInputBatteryState* state) = 0; - virtual HRESULT STDMETHODCALLTYPE CreateForceFeedbackEffect(uint32_t motorIndex, const void* params, - void** effect) = 0; - virtual bool STDMETHODCALLTYPE IsForceFeedbackMotorPoweredOn(uint32_t motorIndex) = 0; - virtual void STDMETHODCALLTYPE SetForceFeedbackMotorGain(uint32_t motorIndex, float masterGain) = 0; - virtual HRESULT STDMETHODCALLTYPE SetHapticMotorState(uint32_t motorIndex, const void* params) = 0; - virtual void STDMETHODCALLTYPE SetRumbleState(const GameInputRumbleParams* params) = 0; - virtual void STDMETHODCALLTYPE SetInputSynchronizationState(bool enabled) = 0; - virtual void STDMETHODCALLTYPE SendInputSynchronizationHint() = 0; - virtual void STDMETHODCALLTYPE PowerOff() = 0; - virtual HRESULT STDMETHODCALLTYPE CreateRawDeviceReport(uint32_t reportId, int32_t reportKind, void** report) = 0; - virtual HRESULT STDMETHODCALLTYPE GetRawDeviceFeature(uint32_t reportId, void** report) = 0; - virtual HRESULT STDMETHODCALLTYPE SetRawDeviceFeature(void* report) = 0; - virtual HRESULT STDMETHODCALLTYPE SendRawDeviceOutput(void* report) = 0; - virtual HRESULT STDMETHODCALLTYPE SendRawDeviceOutputWithResponse(void* requestReport, void** responseReport) = 0; - virtual HRESULT STDMETHODCALLTYPE ExecuteRawDeviceIoControl(uint32_t controlCode, size_t inputBufferSize, - const void* inputBuffer, size_t outputBufferSize, - void* outputBuffer, size_t* outputSize) = 0; - virtual bool STDMETHODCALLTYPE AcquireExclusiveRawDeviceAccess(uint64_t timeoutInMicroseconds) = 0; - virtual void STDMETHODCALLTYPE ReleaseExclusiveRawDeviceAccess() = 0; -}; - -struct IGameInputRawDeviceReport : IUnknown { - virtual void STDMETHODCALLTYPE GetDevice(IGameInputDevice** device) = 0; - virtual const GameInputRawDeviceReportInfo* STDMETHODCALLTYPE GetReportInfo() = 0; - virtual size_t STDMETHODCALLTYPE GetRawDataSize() = 0; - virtual size_t STDMETHODCALLTYPE GetRawData(size_t bufferSize, void* buffer) = 0; - virtual bool STDMETHODCALLTYPE SetRawData(size_t bufferSize, const void* buffer) = 0; - virtual bool STDMETHODCALLTYPE GetItemValue(uint32_t itemIndex, int64_t* value) = 0; - virtual bool STDMETHODCALLTYPE SetItemValue(uint32_t itemIndex, int64_t value) = 0; - virtual bool STDMETHODCALLTYPE ResetItemValue(uint32_t itemIndex) = 0; - virtual bool STDMETHODCALLTYPE ResetAllItems() = 0; -}; - -// What CreateForceFeedbackEffect returns: the effect's parameters, gain and run state, and one reference on the -// device it belongs to. -struct IGameInputForceFeedbackEffect : IUnknown { - virtual void STDMETHODCALLTYPE GetDevice(IGameInputDevice** device) = 0; - virtual uint32_t STDMETHODCALLTYPE GetMotorIndex() = 0; - virtual float STDMETHODCALLTYPE GetGain() = 0; - virtual void STDMETHODCALLTYPE SetGain(float gain) = 0; - virtual void STDMETHODCALLTYPE GetParams(GameInputForceFeedbackParams* params) = 0; - virtual bool STDMETHODCALLTYPE SetParams(const GameInputForceFeedbackParams* params) = 0; - virtual GameInputFeedbackEffectState STDMETHODCALLTYPE GetState() = 0; - virtual void STDMETHODCALLTYPE SetState(GameInputFeedbackEffectState state) = 0; -}; - -struct IGameInputDispatcher : IUnknown { - virtual bool STDMETHODCALLTYPE Dispatch(uint64_t quotaInMicroseconds) = 0; - virtual HRESULT STDMETHODCALLTYPE OpenWaitHandle(HANDLE* waitHandle) = 0; -}; - -using GameInputCreateFn = HRESULT(WINAPI*)(IGameInput** gameInput); - -} // namespace gi diff --git a/runtime/shims/library_loader.cpp b/runtime/shims/library_loader.cpp deleted file mode 100644 index a94709d94..000000000 --- a/runtime/shims/library_loader.cpp +++ /dev/null @@ -1,321 +0,0 @@ -// library_loader: LoadLibrary / GetModuleHandle / GetProcAddress for modules the shims own. -// -// GDK code does not always import the console runtime. The package's libHttpClient.GDK.dll and XCurl.dll have no -// import entry for xgameruntime.dll at all: their statically linked xgameruntime.lib thunks hold the wide string -// "xgameruntime.dll" and the names InitializeApiImpl, InitializeApiImplEx, InitializeApiImplEx2, QueryApiImpl and -// UninitializeApiImpl, and look them up at run time (docs/runtime_imports.md, "Run-time loaded modules"). Bound to the -// host, that LoadLibraryW would load the PC's Gaming Services runtime or fail, and never reach the offline shims. -// -// So for a module the shim registry owns (rt::shims::owns_dll: xgameruntime.dll, d3d12_xs.dll, xmem.dll, ...), these -// return a pseudo-handle, and GetProcAddress on it resolves names (and "#ordinal") through rt::shims::find. A name the -// registry doesn't serve returns NULL with ERROR_PROC_NOT_FOUND, as a real module would, and is logged once. Every -// other module uses the same named shims as static imports, falling back to the host. Only images mapped by the -// loader see these: they are bound through the registry, the runtime's own code calls the host directly. -#include - -#include -#include -#include -#include -#include -#include -#include - -#include "../core/log.h" -#include "shims.h" - -namespace rt::shims::library_loader { - -// A module the shims own, identified by a pointer to one of these. Host modules are image bases (64 KiB aligned); -// these live in the runtime's heap, and GetProcAddress tells them apart by lookup, not by address range. -struct Pseudo { - char tag[8] = {'L', 'E', 'O', 'S', 'H', 'I', 'M', 0}; - std::string dll; // lower case, with .dll -}; - -namespace { - -// Intentionally immortal: mapped-DLL DLL_PROCESS_DETACH and earlier atexit handlers can call GetProcAddress or -// FreeLibrary on pseudo-handles during process teardown, after normal statics would have been destroyed. -std::mutex& loader_mutex() { - static auto* m = new std::mutex; - return *m; -} - -std::deque& pseudos() { // a deque never moves its elements, so handed-out handles stay valid - static auto* d = new std::deque; - return *d; -} - -std::string lower_ascii(std::string s) { - for (auto& c : s) - if (c >= 'A' && c <= 'Z') c = static_cast(c + 32); - return s; -} - -std::string narrow(const wchar_t* w) { - std::string s; - for (; w && *w; ++w) s += (*w < 0x80) ? static_cast(*w) : '?'; - return s; -} - -bool is_ascii(const wchar_t* w) { - for (; w && *w; ++w) - if (*w >= 0x80) return false; - return true; -} - -// module_name for a name narrow() cannot spell: the last path component as given (the loader matches it -// case-insensitively, as Windows does), ".dll" added when there is no extension. -std::wstring module_name_w(std::wstring path) { - const size_t slash = path.find_last_of(L"\\/"); - if (slash != std::wstring::npos) path.erase(0, slash + 1); - if (!path.empty() && path.back() == L'.') path.pop_back(); - else if (path.find(L'.') == std::wstring::npos) path += L".dll"; - return path; -} - -// Whether the module a wide name refers to has an ASCII name. Only the last component decides: the directory may be -// outside ASCII (narrow() turns it into '?', which the basename-only lookups never see) while the module is a shim's. -bool ascii_basename(const wchar_t* name) { - return is_ascii(module_name_w(name).c_str()); -} - -// LoadLibrary's file-name rules for the module a path names: the last path component, lower case, and ".dll" added -// when there is no extension (a trailing '.' means "no extension, add nothing"). -std::string module_name(std::string path) { - const size_t slash = path.find_last_of("\\/"); - if (slash != std::string::npos) path.erase(0, slash + 1); - path = lower_ascii(path); - if (!path.empty() && path.back() == '.') path.pop_back(); - else if (path.find('.') == std::string::npos) path += ".dll"; - return path; -} - -std::string host_module_name(HMODULE module) { - std::lock_guard lock(loader_mutex()); - static auto* names = new std::map; - if (auto it = names->find(module); it != names->end()) return it->second; - - std::vector path(MAX_PATH); - for (;;) { - const DWORD length = GetModuleFileNameW(module, path.data(), static_cast(path.size())); - if (!length) return {}; - if (length < path.size()) { - const std::string name = module_name(narrow(path.data())); - names->emplace(module, name); - return name; - } - if (path.size() == 32768) return {}; - path.resize(path.size() > 16384 ? 32768 : path.size() * 2); - } -} - -} // namespace - -// The pseudo-handle for an owned module, or nullptr when the shims don't own `path`'s module. -HMODULE owned_handle(const std::string& path) { - const std::string dll = module_name(path); - if (dll.empty() || !owns_dll(dll)) return nullptr; - std::lock_guard lock(loader_mutex()); - for (auto& p : pseudos()) - if (p.dll == dll) return reinterpret_cast(&p); - pseudos().push_back(Pseudo{}); - pseudos().back().dll = dll; - RT_LOG_INFO("loader: %s is served by the shims (run-time load)\n", dll.c_str()); - return reinterpret_cast(&pseudos().back()); -} - -// The owned module a handle names, or nullptr for a host module. -const Pseudo* pseudo(HMODULE h) { - std::lock_guard lock(loader_mutex()); - for (auto& p : pseudos()) - if (reinterpret_cast(&p) == h) return &p; - return nullptr; -} - -namespace { - -constexpr DWORD kDataFileLoadFlags = - LOAD_LIBRARY_AS_DATAFILE | LOAD_LIBRARY_AS_DATAFILE_EXCLUSIVE | LOAD_LIBRARY_AS_IMAGE_RESOURCE; - -HMODULE load_shim_or_bundled(const std::string& path, DWORD flags, bool& handled) { - handled = false; - if (HMODULE h = owned_handle(path)) { - handled = true; - return h; - } - const std::string dll = module_name(path); - if (!dll.empty()) { - if (void* h = load_bundled_module(dll, static_cast(flags), handled); handled) - return reinterpret_cast(h); - } - return nullptr; -} - -HMODULE WINAPI load_library_a(LPCSTR name) { - if (name) { - bool handled = false; - HMODULE h = load_shim_or_bundled(name, 0, handled); - if (handled) return h; - } - return LoadLibraryA(name); -} - -// A name with a character outside ASCII names no shim (their names are ASCII) and narrow() would turn it into '?', -// so it goes to the bundled loader by its wide basename: an image already mapped under that name is returned, as -// Windows returns the loaded module for LoadLibraryW of its own file. -HMODULE load_bundled_w(LPCWSTR name, DWORD flags, bool& handled) { - handled = false; - const std::wstring dll = module_name_w(name); - if (dll.empty()) return nullptr; - return reinterpret_cast(load_bundled_module_w(dll, static_cast(flags), handled)); -} - -HMODULE WINAPI load_library_w(LPCWSTR name) { - if (name) { - bool handled = false; - HMODULE h = ascii_basename(name) ? load_shim_or_bundled(narrow(name), 0, handled) : load_bundled_w(name, 0, handled); - if (handled) return h; - } - return LoadLibraryW(name); -} - -HMODULE WINAPI load_library_ex_a(LPCSTR name, HANDLE file, DWORD flags) { - if (name && (flags & kDataFileLoadFlags) == 0) { - bool handled = false; - HMODULE h = load_shim_or_bundled(name, flags, handled); - if (handled) return h; - } - return LoadLibraryExA(name, file, flags); -} - -HMODULE WINAPI load_library_ex_w(LPCWSTR name, HANDLE file, DWORD flags) { - if (name && (flags & kDataFileLoadFlags) == 0) { - bool handled = false; - HMODULE h = ascii_basename(name) ? load_shim_or_bundled(narrow(name), flags, handled) - : load_bundled_w(name, flags, handled); - if (handled) return h; - } - return LoadLibraryExW(name, file, flags); -} - -// GetModuleHandle answers for an owned module as if it were loaded (the GDK may probe before it loads), and for any -// bundled package module already mapped by the native loader. -HMODULE WINAPI get_module_handle_a(LPCSTR name) { - if (name) { - if (HMODULE h = owned_handle(name)) return h; - const std::string dll = module_name(name); - if (!dll.empty()) - if (void* h = find_loaded_bundled_module(dll)) return reinterpret_cast(h); - } - return GetModuleHandleA(name); -} - -HMODULE WINAPI get_module_handle_w(LPCWSTR name) { - if (name) { - if (ascii_basename(name)) { - const std::string path = narrow(name); - if (HMODULE h = owned_handle(path)) return h; - const std::string dll = module_name(path); - if (!dll.empty()) - if (void* h = find_loaded_bundled_module(dll)) return reinterpret_cast(h); - } else { - // Outside ASCII: by the wide basename (narrow() would turn it into '?'), as for load_library_w. - const std::wstring dll = module_name_w(name); - if (!dll.empty()) - if (void* h = find_loaded_bundled_module_w(dll)) return reinterpret_cast(h); - } - } - return GetModuleHandleW(name); -} - -FARPROC WINAPI get_proc_address(HMODULE module, LPCSTR name) { - if (const Pseudo* p = pseudo(module)) { - if (!name) { - SetLastError(ERROR_PROC_NOT_FOUND); - return nullptr; - } - // A value below 0x10000 is an ordinal (IS_INTRESOURCE), as in the real GetProcAddress. - const std::string what = - IS_INTRESOURCE(name) ? "#" + std::to_string(reinterpret_cast(name)) : name; - if (void* fn = find(p->dll, what)) return reinterpret_cast(fn); - { - static auto* m = new std::mutex; - static auto* seen = new std::set; - std::lock_guard lock(*m); - if (seen->insert(p->dll + "!" + what).second) - RT_LOG_WARN("loader: GetProcAddress(%s, %s): not served\n", p->dll.c_str(), what.c_str()); - } - SetLastError(ERROR_PROC_NOT_FOUND); - return nullptr; - } - - if (!name) { - if (owns_bundled_module_handle(module)) { - SetLastError(ERROR_PROC_NOT_FOUND); - return nullptr; - } - return GetProcAddress(module, name); - } - - const std::string what = IS_INTRESOURCE(name) ? "#" + std::to_string(reinterpret_cast(name)) : name; - bool owns_handle = false; - void* fn = get_bundled_proc_address(module, what, owns_handle); - if (owns_handle) { - if (fn) return reinterpret_cast(fn); - SetLastError(ERROR_PROC_NOT_FOUND); - return nullptr; - } - if (module && !IS_INTRESOURCE(name)) { - const DWORD error = GetLastError(); - const std::string dll = host_module_name(module); - void* shim = dll.empty() ? nullptr : find(dll, what); - SetLastError(error); - if (shim) return reinterpret_cast(shim); - } - return GetProcAddress(module, name); -} - -BOOL WINAPI free_library(HMODULE module) { - if (pseudo(module)) return TRUE; // owned modules are never unloaded - if (owns_bundled_module_handle(module)) return TRUE; // mapped modules stay live until ~Loader detaches them - return FreeLibrary(module); -} - -// DisableThreadLibraryCalls(hinstance) from a mapped image's DllMain. The real function only accepts a module the -// Windows loader mapped, so for ours it fails, and a DllMain that returns its result (the MSVC runtime's satellite -// DLLs do) fails Loader::initialise() with "DllMain returned FALSE". Owned and mapped modules answer TRUE. The loader -// sends no thread events to a DllMain, so there is nothing further to switch off; every other handle goes to the -// real function. -BOOL WINAPI disable_thread_calls(HMODULE module) { - if (pseudo(module)) return TRUE; - if (owns_bundled_module_handle(module)) return TRUE; - return DisableThreadLibraryCalls(module); -} - -#define LOADER(dll) \ - {dll, "LoadLibraryA", reinterpret_cast(&rt::shims::library_loader::load_library_a)}, \ - {dll, "LoadLibraryW", reinterpret_cast(&rt::shims::library_loader::load_library_w)}, \ - {dll, "LoadLibraryExA", reinterpret_cast(&rt::shims::library_loader::load_library_ex_a)}, \ - {dll, "LoadLibraryExW", reinterpret_cast(&rt::shims::library_loader::load_library_ex_w)}, \ - {dll, "GetModuleHandleA", reinterpret_cast(&rt::shims::library_loader::get_module_handle_a)}, \ - {dll, "GetModuleHandleW", reinterpret_cast(&rt::shims::library_loader::get_module_handle_w)}, \ - {dll, "GetProcAddress", reinterpret_cast(&rt::shims::library_loader::get_proc_address)}, \ - {dll, "FreeLibrary", reinterpret_cast(&rt::shims::library_loader::free_library)}, \ - {dll, "DisableThreadLibraryCalls", reinterpret_cast(&rt::shims::library_loader::disable_thread_calls)} - -} // namespace -} // namespace rt::shims::library_loader - -// The package's DLLs import the loader functions through these api sets (XCurl.dll: libraryloader-l1-2-0 and -// -l1-2-1); kernel32 and kernelbase cover code linked against the classic libraries. -SHIM_TABLE(library_loader, - LOADER("kernel32.dll"), - LOADER("kernelbase.dll"), - LOADER("api-ms-win-core-libraryloader-l1-1-0.dll"), - LOADER("api-ms-win-core-libraryloader-l1-1-1.dll"), - LOADER("api-ms-win-core-libraryloader-l1-2-0.dll"), - LOADER("api-ms-win-core-libraryloader-l1-2-1.dll"), - LOADER("api-ms-win-core-libraryloader-l1-2-2.dll"), -); diff --git a/runtime/shims/process.cpp b/runtime/shims/process.cpp deleted file mode 100644 index 58c424fa3..000000000 --- a/runtime/shims/process.cpp +++ /dev/null @@ -1,548 +0,0 @@ -// Process-level imports of a mapped executable: its command line and its way out. -// -// `gta6rt --run` calls a mapped EXE's entry point inside the gta6rt process. The EXE's CRT startup asks for its -// arguments and finally calls exit(); both go through the EXE's own import table, so they can be answered here: -// - the command line is the game's, and its CRT configures its own argv/argc at startup; -// - exit(), _exit(), quick_exit(), ExitProcess() and abort() from the game end the game's run, not the host: -// the exit code is recorded, the run is signalled as finished and the calling thread waits for the host to -// exit; -// - the game's atexit registrations (_crt_atexit, which MSVC's atexit and static destructors reach; msvcrt's -// atexit and _onexit) go to a table of the run's own instead of the CRT's process-wide one, which the game -// shares with gta6rt. exit() runs it newest first, as the CRT does, before the run ends; _exit(), _Exit(), -// quick_exit(), ExitProcess() and abort() do not. _cexit() runs it and returns, _c_exit() returns. A second -// thread that calls exit(), _exit(), _Exit() or quick_exit() while the first is leaving waits, as with the -// CRT's exit lock. Not covered yet: at_quick_exit() handlers (quick_exit() runs none) and the thread-local -// destructor callback (_register_thread_local_exe_atexit_callback); both still reach the host CRT. -// Covered CRTs: the Universal CRT (api-ms-win-crt-runtime-l1-1-0.dll / ucrtbase.dll, what MSVC links; ucrtbased.dll in Debug) and -// msvcrt.dll (MinGW). Calls made inside host DLLs, not through the game's imports, are not seen here. -// The loader matches imports by exact DLL name, so GetCommandLineA/W and ExitProcess are served under every name a -// title can import them by: kernel32.dll (the classic import libraries), kernelbase.dll, and the API sets that the -// umbrella libraries a GDK title links (OneCore_apiset.lib, mincore.lib) bind them to. The retail package's own DLLs -// import ExitProcess from api-ms-win-core-processthreads-l1-1-0.dll. -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include "../core/log.h" -#include "process_shim.h" -#include "shims.h" - -namespace rt::process { -namespace { - -std::vector g_input_args; -std::vector g_input_wargs; -std::vector g_args; -std::vector g_wargs; -std::vector g_argv; -std::vector g_wargv; -std::string g_cmdline; -std::wstring g_wcmdline; -int g_argc = 0; -char** g_argv_ptr = nullptr; -wchar_t** g_wargv_ptr = nullptr; - -std::atomic g_running{false}; -std::atomic g_exited{false}; -std::atomic g_exit_code{0}; -HANDLE g_done = nullptr; - -std::wstring quote(const std::wstring& a) { - if (!a.empty() && a.find_first_of(L" \t\"") == std::wstring::npos) return a; - std::wstring out = L"\""; - size_t slashes = 0; // CommandLineToArgvW: backslashes are literal unless they precede a quote - for (wchar_t c : a) { - if (c == L'\\') { - ++slashes; - } else { - if (c == L'"') out.append(slashes + 1, L'\\'); - slashes = 0; - } - out += c; - } - return out.append(slashes, L'\\') + L"\""; // a trailing run is doubled before the closing quote -} - -// The narrow arguments are ANSI code page text, like the CRT's narrow argv; under a UTF-8 activeCodePage CP_ACP is -// UTF-8 anyway. A character the code page has no mapping for becomes the code page's default character (or a -// best-fit one), as in the CRT, instead of failing: std::filesystem::path::string() throws there (RT-84). -std::string narrow(const std::wstring& w) { - int n = WideCharToMultiByte(CP_ACP, 0, w.c_str(), -1, nullptr, 0, nullptr, nullptr); - std::string s(n > 0 ? n - 1 : 0, '\0'); - if (n > 1) WideCharToMultiByte(CP_ACP, 0, w.c_str(), -1, s.data(), n, nullptr, nullptr); - return s; -} - -[[noreturn]] void end_run(int code) { - // Read before signalling: once g_done is set, run_entry can return and clear g_running while the host is still - // finishing the run (main.cpp's "game exited" line and cleanup), which this thread must not cut short. - const bool running = g_running; - bool expected = false; - if (g_exited.compare_exchange_strong(expected, true)) { - g_exit_code = code; - if (g_done) SetEvent(g_done); - } - // Park until the host's ExitProcess, not ExitThread: Wine < 11.2 can exit 0 if the two race (4a9bc42a). - if (running) for (;;) Sleep(INFINITE); - // The run is already over: this is game code running during host shutdown (an atexit handler the game - // registered with the shared CRT calling exit again). Finish the process with the game's exit code; ending - // just this thread here would make the host's last thread, and so the process, exit with `code` instead. - ExitProcess(static_cast(g_exit_code.load())); -} - -// ---- the game's atexit table -using AtexitFn = void(__cdecl*)(); -using OnexitFn = int(__cdecl*)(); -std::mutex g_atexit_lock; -std::vector g_atexit; -std::atomic g_exiting_thread{0}; - -bool register_atexit(AtexitFn fn) { - std::lock_guard lock(g_atexit_lock); - try { - g_atexit.push_back(fn); - } catch (const std::bad_alloc&) { - return false; // the CRT reports a full table as a failed registration - } - return true; -} - -// Newest first. A handler registered while the handlers run goes on the end and so runs next, as in the UCRT. -void run_atexit_handlers() { - for (;;) { - AtexitFn fn; - { - std::lock_guard lock(g_atexit_lock); - if (g_atexit.empty()) return; - fn = g_atexit.back(); - g_atexit.pop_back(); - } - fn(); - } -} - -// UCRT: int _crt_atexit(_PVFV), 0 on success. MSVC's atexit() and the static destructors of an EXE reach it. -int __cdecl game_crt_atexit(AtexitFn fn) { - return fn && register_atexit(fn) ? 0 : -1; -} -// msvcrt.dll (MinGW): int atexit(void (*)(void)) and _onexit_t _onexit(_onexit_t). -int __cdecl game_msvcrt_atexit(AtexitFn fn) { return game_crt_atexit(fn); } -OnexitFn __cdecl game_onexit(OnexitFn fn) { - // its int result is ignored, as the CRT ignores it - return fn && register_atexit(reinterpret_cast(fn)) ? fn : nullptr; -} - -// ---- the way out -// The CRT's exit lock, which exit(), _exit(), _Exit() and quick_exit() all take: the first thread to leave owns it -// and ends the run; any other thread that tries to leave waits forever. The owner may leave again from a handler -// (undefined in C): that ends the run with the new code and skips the remaining handlers. -bool take_exit_lock() { - const DWORD self = GetCurrentThreadId(); - DWORD owner = 0; - if (g_exiting_thread.compare_exchange_strong(owner, self)) return true; - if (owner != self) { - for (;;) Sleep(INFINITE); - } - return false; -} -// exit(): the game's handlers and static destructors, then the end of the run. -void __cdecl game_exit(int code) { - if (take_exit_lock()) run_atexit_handlers(); - end_run(code); -} -// _exit(), _Exit(), quick_exit(): the end of the run without the atexit handlers. -void __cdecl game_quick_exit(int code) { - take_exit_lock(); - end_run(code); -} -// _cexit() runs the handlers and flushes the streams, then returns; _c_exit() only returns. -void __cdecl game_cexit() { - run_atexit_handlers(); - std::fflush(nullptr); -} -void __cdecl game_c_exit() {} -void __stdcall game_exit_process(UINT code) { end_run(static_cast(code)); } - -// ---- threads and processors -// The console has cores a PC may lack, and a title pins its threads to them with masks the host rejects: Windows -// answers a mask with no CPU of the process (or one outside it) with 0 and ERROR_INVALID_PARAMETER, and a title that -// checks the previous mask then aborts. The call succeeds on the console, so it does here: the thread stays where it -// is and the answer is the mask the thread had (the process mask for a thread never pinned). A bad handle and an empty -// mask still fail, as on Windows. The fact (answer instead of failing when the host call returns 0) is from sammwyy/xvalkyrie src/runtime/modules/kernel.cpp (commit -// 53af7df77c10, GPL-3.0), reimplemented here in our own words and checked against the Win32 behaviour. -DWORD_PTR __stdcall game_set_thread_affinity_mask(HANDLE thread, DWORD_PTR mask) { - DWORD_PTR previous = SetThreadAffinityMask(thread, mask); - if (previous != 0) return previous; - // An empty mask names no CPU on any machine: it fails as on Windows (the host's own answer, ERROR_INVALID_PARAMETER). - if (mask == 0) { - SetLastError(ERROR_INVALID_PARAMETER); - return 0; - } - DWORD_PTR process = 0, system = 0; - if (GetLastError() != ERROR_INVALID_PARAMETER || !GetProcessAffinityMask(GetCurrentProcess(), &process, &system)) - return 0; - // The caller expects the mask the thread had, which may be narrower than the process mask (it may restore it - // later). The host reports it only on a successful call, so widen the thread to the process mask, read the old - // mask from that call, and put the old mask back: the thread ends where it started. - const DWORD_PTR actual = SetThreadAffinityMask(thread, process); - if (actual == 0) return 0; // the host's error stands (a bad handle) - if (actual != process) SetThreadAffinityMask(thread, actual); - // The first boot shows which masks the title asks for: the first few are named, the rest only counted. - static std::atomic substituted{0}; - const int n = ++substituted; - if (n <= 8) - RT_LOG_WARN("process: SetThreadAffinityMask(0x%llx) names cores the host lacks; the thread stays, " - "answered its mask 0x%llx (call %d)\n", - static_cast(mask), static_cast(actual), n); - // The log may have failed (a closed stderr pipe leaves ERROR_NO_DATA); the call itself succeeded. - SetLastError(ERROR_SUCCESS); - return actual; -} -// The retail title imports the group form (processtopology API sets), not SetThreadAffinityMask. The same rule holds: a -// GROUP_AFFINITY naming cores or a processor group the PC lacks is answered, not failed. The thread stays where it is, -// the call returns TRUE and the out parameter gets the affinity the thread had. An empty mask names no CPU on any -// machine and a bad handle is the host's own error: both are passed to the host and fail as on Windows. -BOOL __stdcall game_set_thread_group_affinity(HANDLE thread, const GROUP_AFFINITY* requested, PGROUP_AFFINITY previous) { - // An empty mask names no CPU on any machine. Some Windows builds accept it and clear the affinity instead of - // failing, so answer the documented error before the host call rather than depending on the build. - if (!requested || requested->Mask == 0) { - SetLastError(ERROR_INVALID_PARAMETER); - return FALSE; - } - if (SetThreadGroupAffinity(thread, requested, previous)) return TRUE; - if (GetLastError() != ERROR_INVALID_PARAMETER) return FALSE; - GROUP_AFFINITY actual = {}; - if (!GetThreadGroupAffinity(thread, &actual)) return FALSE; // the host's error stands - if (previous) *previous = actual; - static std::atomic substituted{0}; - const int n = ++substituted; - if (n <= 8) - RT_LOG_WARN("process: SetThreadGroupAffinity(group %u, 0x%llx) names cores or a group the host lacks; " - "the thread stays, answered group %u mask 0x%llx (call %d)\n", - static_cast(requested->Group), static_cast(requested->Mask), - static_cast(actual.Group), static_cast(actual.Mask), n); - // The log may have failed (a closed stderr pipe leaves ERROR_NO_DATA); the call itself succeeded. - SetLastError(ERROR_SUCCESS); - return TRUE; -} -// A console-only kernel32 export that pins a thread pool to cores. The host has no such call, and a pool with the -// host's own affinity runs the same work, so it succeeds and changes nothing. -BOOL __stdcall game_set_threadpool_affinity_mask(PTP_POOL, DWORD_PTR) { return TRUE; } -void __cdecl game_abort() { - RT_LOG_ERROR("process: the game called abort()\n"); - // The game's signal() import is not shimmed: its handler goes into the host CRT's process-wide table, which - // std::signal here reads too. UCRT's abort() raises SIGABRT before it terminates; do the same only when a - // handler is installed, because raising it with the default action would terminate the host process. A handler - // that exits ends the run itself; one that returns falls through to the CRT's abort code below. - const auto previous = std::signal(SIGABRT, SIG_DFL); - if (previous != SIG_ERR) { - std::signal(SIGABRT, previous); - if (previous != SIG_DFL && previous != SIG_IGN) std::raise(SIGABRT); - } - end_run(3); // the CRT's abort exit code -} - -// ---- arguments -int* __cdecl game_p_argc() { return &g_argc; } -char*** __cdecl game_p_argv() { return &g_argv_ptr; } -wchar_t*** __cdecl game_p_wargv() { return &g_wargv_ptr; } - -std::wstring widen_argument(const std::string& text) { - const int size = MultiByteToWideChar(CP_ACP, 0, text.c_str(), -1, nullptr, 0); - std::wstring wide(size > 0 ? static_cast(size - 1) : 0, L'\0'); - if (size > 1) MultiByteToWideChar(CP_ACP, 0, text.c_str(), -1, wide.data(), size); - return wide; -} - -// UCRT startup expands each wildcard argument against the host working directory, even when the argument was -// quoted. A failed search retains the pattern; a successful search omits "." and ".." and keeps the path prefix. -// Narrow startup searches its ACP-converted text, which can have different wildcard matches from wide startup. -template -std::vector> expand_arguments(const std::vector>& input) { - std::vector> result; - for (const auto& argument : input) { - std::wstring pattern; - if constexpr (std::is_same_v) pattern = argument; - else pattern = widen_argument(argument); - const size_t wildcard = pattern.find_first_of(L"*?"); - if (wildcard == std::wstring::npos) { - result.push_back(argument); - continue; - } - const size_t separator = pattern.find_last_of(L"\\/:", wildcard); - if (separator != std::wstring::npos && pattern[separator] == L':' && separator != 1) { - result.push_back(argument); - continue; - } - WIN32_FIND_DATAW found{}; - const HANDLE handle = ::FindFirstFileExW(pattern.c_str(), FindExInfoStandard, &found, - FindExSearchNameMatch, nullptr, 0); - if (handle == INVALID_HANDLE_VALUE) { - result.push_back(argument); - continue; - } - struct Search { - HANDLE handle; - ~Search() { ::FindClose(handle); } - } search{handle}; - const std::wstring prefix = pattern.substr(0, separator == std::wstring::npos ? 0 : separator + 1); - do { - if (std::wcscmp(found.cFileName, L".") == 0 || std::wcscmp(found.cFileName, L"..") == 0) continue; - const std::wstring match = prefix + found.cFileName; - if constexpr (std::is_same_v) result.push_back(match); - else result.push_back(narrow(match)); - } while (::FindNextFileW(handle, &found)); - } - return result; -} - -template -int configure_argv(int mode, const std::vector>& input, - std::vector>& strings, std::vector& pointers, C**& published) { - // _crt_argv_no_arguments is a no-op, including after another width or mode has been configured. - if (mode == 0) return 0; - if (mode != 1 && mode != 2) return errno = EINVAL; - try { - auto next_strings = mode == 2 ? expand_arguments(input) : input; - std::vector next_pointers; - next_pointers.reserve(next_strings.size() + 1); - for (auto& argument : next_strings) next_pointers.push_back(argument.data()); - next_pointers.push_back(nullptr); - // Publish only after every allocation succeeds. The other width keeps its own strings and pointer table. - strings.swap(next_strings); - pointers.swap(next_pointers); - published = pointers.data(); - g_argc = static_cast(strings.size()); - return 0; - } catch (const std::bad_alloc&) { - return errno = ENOMEM; - } -} - -int __cdecl game_configure_narrow_argv(int mode) { - return configure_argv(mode, g_input_args, g_args, g_argv, g_argv_ptr); -} -int __cdecl game_configure_wide_argv(int mode) { - return configure_argv(mode, g_input_wargs, g_wargs, g_wargv, g_wargv_ptr); -} - -LPSTR __stdcall game_get_command_line_a() { return g_cmdline.data(); } -LPWSTR __stdcall game_get_command_line_w() { return g_wcmdline.data(); } -char** __cdecl game_p_acmdln_storage() { - static char* p = nullptr; - p = g_cmdline.data(); - return &p; -} -wchar_t** __cdecl game_p_wcmdln_storage() { - static wchar_t* p = nullptr; - p = g_wcmdline.data(); - return &p; -} - -// What the UCRT's _get_narrow/_get_wide_winmain_command_line return, and the CRT's WinMain startup passes as -// lpCmdLine: the command line after the program name and the blanks that follow it. The program name ends at the -// first character up to ' ' outside quotes, the UCRT's own scan. The comparison is unsigned, so a non-ASCII byte of -// the narrow line is part of the name; a DBCS trail byte is never '"' or a blank, so it needs no lead-byte step. -template -C* after_program_name(C* p) { - using U = std::make_unsigned_t; - bool quoted = false; - while (U(*p) > U(' ') || (*p && quoted)) { - if (*p == C('"')) quoted = !quoted; - ++p; - } - while (*p && U(*p) <= U(' ')) ++p; - return p; -} -char* __cdecl game_get_narrow_winmain_command_line() { return after_program_name(g_cmdline.data()); } -wchar_t* __cdecl game_get_wide_winmain_command_line() { return after_program_name(g_wcmdline.data()); } - -// The host CRT's environment tables, read when the game asks (RT-136). _environ and _wenviron are not stable: the host -// CRT builds the wide table only when a wide environment function first runs (a host started through main() has -// none until then), and _putenv/_wputenv reallocate both, so a pointer taken in set_command_line would be null or -// dangling by the time a wide-character startup calls __wgetmainargs. A lookup of a name no one sets makes the CRT -// create the table if it does not exist yet (from the other table or the OS block) without changing it. -// Like the msvcrt.dll original, the returned table is the CRT's own and is only valid until the next _putenv: a CRT -// startup reads it once, before the game has other threads, and a host that edits its environment concurrently with -// a game's startup is not covered. -char** current_environment() { - if (!_environ) { - size_t size = 0; - (void)getenv_s(&size, nullptr, 0, "LEONIDA_RT_ENV_INIT"); - } - return _environ; -} -wchar_t** current_wide_environment() { - if (!_wenviron) { - size_t size = 0; - (void)_wgetenv_s(&size, nullptr, 0, L"LEONIDA_RT_ENV_INIT"); - } - return _wenviron; -} - -// msvcrt.dll: int __getmainargs(int* argc, char*** argv, char*** env, int expand, void* startinfo) -int __cdecl game_getmainargs(int* argc, char*** argv, char*** env, int, void*) { - if (const int error = game_configure_narrow_argv(1)) return error; - *argc = g_argc; - *argv = g_argv_ptr; - if (env) *env = current_environment(); - return 0; -} -int __cdecl game_wgetmainargs(int* argc, wchar_t*** argv, wchar_t*** env, int, void*) { - if (const int error = game_configure_wide_argv(1)) return error; - *argc = g_argc; - *argv = g_wargv_ptr; - if (env) *env = current_wide_environment(); - return 0; -} - -struct EntryCall { - void* entry; -}; - -DWORD WINAPI game_thread(void* p) { - auto* call = static_cast(p); - // An EXE entry point (mainCRTStartup and friends) takes the PEB pointer and returns the process exit code. - auto entry = reinterpret_cast(call->entry); - const DWORD code = entry(nullptr); - end_run(static_cast(code)); // returning from the entry point is an exit too -} - -} // namespace - -void set_command_line(const std::wstring& program, const std::vector& args) { - g_input_wargs.clear(); - g_input_wargs.push_back(program); - g_input_wargs.insert(g_input_wargs.end(), args.begin(), args.end()); - g_input_args.clear(); - g_wcmdline.clear(); - for (const auto& a : g_input_wargs) { - g_input_args.push_back(narrow(a)); - if (!g_wcmdline.empty()) g_wcmdline += L' '; - g_wcmdline += quote(a); - } - g_cmdline = narrow(g_wcmdline); - // GetCommandLine is available before TLS/DllMain, but CRT argv starts unconfigured on every run. - g_args.clear(); - g_wargs.clear(); - g_argv.clear(); - g_wargv.clear(); - g_argc = 0; - g_argv_ptr = nullptr; - g_wargv_ptr = nullptr; -} - -int run_entry(void* entry, size_t stack_bytes) { - { - std::lock_guard lock(g_atexit_lock); - g_atexit.clear(); // a run never sees the handlers of an earlier one - } - g_exiting_thread = 0; - g_exited = false; - g_exit_code = 0; - g_done = CreateEventW(nullptr, TRUE, FALSE, nullptr); - if (!g_done) return -1; - g_running = true; - EntryCall call{entry}; - HANDLE thread = CreateThread(nullptr, stack_bytes, game_thread, &call, STACK_SIZE_PARAM_IS_A_RESERVATION, nullptr); - if (!thread) { - g_running = false; - CloseHandle(g_done); - g_done = nullptr; - return -1; - } - // The run ends when any game thread exits the process (exit/ExitProcess/abort) or the entry point returns. - HANDLE waits[] = {g_done, thread}; - WaitForMultipleObjects(2, waits, FALSE, INFINITE); - bool expected = false; - if (g_exited.compare_exchange_strong(expected, true)) { - // The entry thread exited without calling end_run (e.g. ExitThread); claim g_exited so no worker thread can - // touch g_done while we close it, and preserve the thread's exit code. - DWORD thread_code = 0; - if (GetExitCodeThread(thread, &thread_code)) g_exit_code = static_cast(thread_code); - } else { - // Another thread already won g_exited and is publishing g_exit_code + SetEvent(g_done); wait until it finishes - // so we never close g_done or return before g_exit_code is published. - WaitForSingleObject(g_done, INFINITE); - } - CloseHandle(thread); - CloseHandle(g_done); - g_done = nullptr; - g_running = false; - return g_exit_code.load(); -} - -} // namespace rt::process - -namespace { -using namespace rt::process; -#define UCRT(dll) \ - {dll, "exit", reinterpret_cast(&game_exit)}, {dll, "_exit", reinterpret_cast(&game_quick_exit)}, \ - {dll, "_Exit", reinterpret_cast(&game_quick_exit)}, \ - {dll, "quick_exit", reinterpret_cast(&game_quick_exit)}, \ - {dll, "_crt_atexit", reinterpret_cast(&game_crt_atexit)}, \ - {dll, "_cexit", reinterpret_cast(&game_cexit)}, {dll, "_c_exit", reinterpret_cast(&game_c_exit)}, \ - {dll, "abort", reinterpret_cast(&game_abort)}, {dll, "__p___argc", reinterpret_cast(&game_p_argc)}, \ - {dll, "__p___argv", reinterpret_cast(&game_p_argv)}, \ - {dll, "__p___wargv", reinterpret_cast(&game_p_wargv)}, \ - {dll, "_configure_narrow_argv", reinterpret_cast(&game_configure_narrow_argv)}, \ - {dll, "_configure_wide_argv", reinterpret_cast(&game_configure_wide_argv)}, \ - {dll, "__p__acmdln", reinterpret_cast(&game_p_acmdln_storage)}, \ - {dll, "__p__wcmdln", reinterpret_cast(&game_p_wcmdln_storage)}, \ - {dll, "_get_narrow_winmain_command_line", reinterpret_cast(&game_get_narrow_winmain_command_line)}, \ - {dll, "_get_wide_winmain_command_line", reinterpret_cast(&game_get_wide_winmain_command_line)} -#define EXIT_PROCESS(dll) {dll, "ExitProcess", reinterpret_cast(&game_exit_process)} -#define THREAD_AFFINITY(dll) {dll, "SetThreadAffinityMask", reinterpret_cast(&game_set_thread_affinity_mask)} -#define THREAD_GROUP_AFFINITY(dll) \ - {dll, "SetThreadGroupAffinity", reinterpret_cast(&game_set_thread_group_affinity)} -#define POOL_AFFINITY(dll) \ - {dll, "SetThreadpoolAffinityMask", reinterpret_cast(&game_set_threadpool_affinity_mask)} -#define COMMAND_LINE(dll) \ - {dll, "GetCommandLineA", reinterpret_cast(&game_get_command_line_a)}, \ - {dll, "GetCommandLineW", reinterpret_cast(&game_get_command_line_w)} -} // namespace - -SHIM_TABLE(process, - UCRT("api-ms-win-crt-runtime-l1-1-0.dll"), - UCRT("ucrtbase.dll"), - UCRT("ucrtbased.dll"), // the Debug UCRT: a Debug build of the stand-in game (run_tiny_game) links it - {"msvcrt.dll", "exit", reinterpret_cast(&game_exit)}, - {"msvcrt.dll", "_exit", reinterpret_cast(&game_quick_exit)}, - {"msvcrt.dll", "atexit", reinterpret_cast(&game_msvcrt_atexit)}, - {"msvcrt.dll", "_onexit", reinterpret_cast(&game_onexit)}, - {"msvcrt.dll", "_cexit", reinterpret_cast(&game_cexit)}, - {"msvcrt.dll", "_c_exit", reinterpret_cast(&game_c_exit)}, - {"msvcrt.dll", "abort", reinterpret_cast(&game_abort)}, - {"msvcrt.dll", "__getmainargs", reinterpret_cast(&game_getmainargs)}, - {"msvcrt.dll", "__wgetmainargs", reinterpret_cast(&game_wgetmainargs)}, - EXIT_PROCESS("kernel32.dll"), - EXIT_PROCESS("kernelbase.dll"), - EXIT_PROCESS("api-ms-win-core-processthreads-l1-1-0.dll"), - THREAD_AFFINITY("kernel32.dll"), - THREAD_AFFINITY("kernelbase.dll"), - THREAD_AFFINITY("api-ms-win-core-processthreads-l1-1-0.dll"), - THREAD_AFFINITY("api-ms-win-core-processthreads-l1-1-1.dll"), - THREAD_AFFINITY("api-ms-win-core-processthreads-l1-1-2.dll"), - THREAD_AFFINITY("api-ms-win-core-processthreads-l1-1-3.dll"), - THREAD_GROUP_AFFINITY("kernel32.dll"), - THREAD_GROUP_AFFINITY("kernelbase.dll"), - THREAD_GROUP_AFFINITY("api-ms-win-core-processtopology-l1-1-0.dll"), - THREAD_GROUP_AFFINITY("api-ms-win-core-processtopology-l1-1-1.dll"), - THREAD_GROUP_AFFINITY("api-ms-win-core-processtopology-l1-1-2.dll"), - POOL_AFFINITY("kernel32.dll"), - POOL_AFFINITY("kernelbase.dll"), - COMMAND_LINE("kernel32.dll"), - COMMAND_LINE("kernelbase.dll"), - COMMAND_LINE("api-ms-win-core-processenvironment-l1-1-0.dll"), -); diff --git a/runtime/shims/process_shim.h b/runtime/shims/process_shim.h deleted file mode 100644 index f6946719b..000000000 --- a/runtime/shims/process_shim.h +++ /dev/null @@ -1,19 +0,0 @@ -// The game's command line and exit, for `gta6rt --run` (shims/process.cpp). -#pragma once -#include -#include -#include - -namespace rt::process { - -// Set GetCommandLine to `program` then `args`, quoted where needed, before process-attach callbacks. The wide text -// holds the arguments exactly; the narrow text uses the ANSI code page (RT-84). Reset CRT argv to argc=0/null: -// its startup configuration selects no arguments, the original arguments, or wildcard expansion for each width. -void set_command_line(const std::wstring& program, const std::vector& args); - -// Runs a mapped EXE's entry point on a new thread with `stack_bytes` of reserved stack and returns the game's -// exit code: the entry point's return value, or what it passed to exit/ExitProcess (3 for abort). Returns when -// the first of those happens; other game threads are left running (the host process ends them when it exits). -int run_entry(void* entry, std::size_t stack_bytes = 8u << 20); - -} // namespace rt::process diff --git a/runtime/shims/registry.cpp b/runtime/shims/registry.cpp deleted file mode 100644 index be2ac8eda..000000000 --- a/runtime/shims/registry.cpp +++ /dev/null @@ -1,544 +0,0 @@ -#include -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include "../core/config.h" -#include "../core/log.h" -#include "shims.h" -#include "startup_trace.h" - -namespace rt::shims { -namespace { - -std::map& table() { - static std::map t; // "dll!name" - return t; -} - -std::string lower_ascii(std::string s) { - for (auto& c : s) - if (c >= 'A' && c <= 'Z') c = static_cast(c + 32); - return s; -} - -bool starts_with(const std::string& s, const char* prefix) { return s.rfind(prefix, 0) == 0; } - -std::mutex g_called_mutex; -std::set g_called; -std::map g_seen; // by the thunk's `what` pointer; both under g_called_mutex -std::atomic g_test_hook{nullptr}; - -// ---- Return-value policy ---------------------------------------------------------------------------------------- - -constexpr int kStopExitCode = 3; // what abort() exits with; documented, and checked by the tests - -std::atomic g_policy{-1}; // -1: not decided yet, LEONIDA_UNIMPLEMENTED is read on first use - -struct Lookup { - void* ctx; - ModuleLookup fn; -}; -std::mutex g_lookup_mutex; -std::vector g_lookups; - -// The imports known to return HRESULT. Everything else is "other" and keeps returning 0 under `fail`. -// Each family was checked against the public Microsoft documentation (learn.microsoft.com), one signature per -// function; no SDK headers were read. An HRESULT function that is not listed just returns 0, as before, so a missing -// entry is the safe direction; a wrong entry would hand E_NOTIMPL (nonzero, "true") to a bool or pointer caller. -// -// d3d12.dll, d3d12_xs.dll D3D12Create*: D3D12CreateDevice, D3D12CreateRootSignatureDeserializer, -// D3D12CreateVersionedRootSignatureDeserializer return HRESULT -// (learn.microsoft.com/windows/win32/api/d3d12/nf-d3d12-d3d12createdevice and siblings). -// D3D12Serialize*: D3D12SerializeRootSignature, D3D12SerializeVersionedRootSignature: HRESULT. -// D3D12GetDebugInterface, D3D12EnableExperimentalFeatures: HRESULT. -// D3D12XboxCreateDevice is matched by exact name: the console-only function has no public -// reference page that could be reached; it is the factory this repo measured (it returns -// an HRESULT with the device in an out parameter, docs/d3d12_vulkan.md), not a documented one. -// D3D12XboxCreateSyntheticDevice is the other console-only factory the sibling export -// inventories list (docs/d3d12_vulkan.md §7); same Create*Device HRESULT shape. -// D3D12XboxSetProcessDebugFlags is left out: nothing measured its return. -// dxgi.dll CreateDXGIFactory, CreateDXGIFactory1, CreateDXGIFactory2, DXGIGetDebugInterface1 and -// DXGIDeclareAdapterRemovalSupport return HRESULT (win32/api/dxgi/nf-dxgi-createdxgifactory, -// dxgi1_3 and dxgi1_6 pages). Not the whole DXGI* prefix: only these names were verified. -// xgameruntime.dll GDK reference, gaming/gdk/docs/reference/system//functions/. These families -// return HRESULT except the functions in kNotHResult, which the same pages show as -// void/bool/int: XAsync*, XTaskQueue*, XUser*, XStore*, XGameSave*, XPackage*, XGameUi*. -// XGameRuntimeInitialize and XGameEventWrite: HRESULT. -// Mixed families (XSystem*, XGameStreaming*, XThread*, XDisplay*, XGameRuntimeFeature*) are -// left out on purpose. -// gameinput.dll GameInputCreate: HRESULT (gaming/gdk/docs/reference/input/gameinput/functions/ -// gameinputcreate). The shim implements it (runtime/shims/gameinput.cpp); the class is -// listed anyway for a build or import it misses. -// xaudio2_9.dll XAudio2Create: HRESULT (learn.microsoft.com/windows/win32/api/xaudio2/ -// xaudio2_9redist.dll nf-xaudio2-xaudio2create). xaudio2_9.dll is the console name (docs/d3d12_vulkan.md §7). -// dstorage.dll DStorageGetFactory: HRESULT (learn.microsoft.com/windows/win32/api/dstorage/ -// dstorage_xs.dll nf-dstorage-dstoragegetfactory, and the GDK's gaming/gdk/docs/reference/system/dstorage/ -// xcrdapi.dll functions/dstoragegetfactory). dstorage_xs.dll is the console name; xcrdapi.dll is a -// console module the title may import it from (docs/directstorage.md). dstorage.cpp serves -// it; the class is kept for a build without that shim. -const char* const kNotHResult[] = { - "XAsyncCancel", "XAsyncComplete", - "XTaskQueueCloseHandle", "XTaskQueueDispatch", "XTaskQueueGetCurrentProcessTaskQueue", - "XTaskQueueSetCurrentProcessTaskQueue", "XTaskQueueUnregisterMonitor", "XTaskQueueUnregisterWaiter", - "XUserCloseHandle", "XUserCloseSignOutDeferralHandle", "XUserCompare", "XUserIsStoreUser", - "XUserUnregisterForChangeEvent", "XUserUnregisterForDefaultAudioEndpointUtf16Changed", - "XUserUnregisterForDeviceAssociationChanged", - "XStoreCloseContextHandle", "XStoreCloseLicenseHandle", "XStoreCloseProductsQueryHandle", "XStoreIsLicenseValid", - "XStoreProductsQueryHasMorePages", "XStoreUnregisterGameLicenseChanged", "XStoreUnregisterPackageLicenseLost", - "XGameSaveCloseContainer", "XGameSaveCloseProvider", "XGameSaveCloseUpdate", - "XPackageCloseInstallationMonitorHandle", "XPackageCloseMountHandle", "XPackageGetInstallationProgress", - "XPackageIsPackagedProcess", "XPackageUninstallPackage", "XPackageUnregisterInstallationProgressChanged", - "XPackageUnregisterPackageInstalled", "XPackageUpdateInstallationMonitor", -}; -const char* const kXFamilies[] = {"XAsync", "XTaskQueue", "XUser", "XStore", "XGameSave", "XPackage", "XGameUi"}; - -ReturnClass classify(const std::string& dll, const std::string& name) { - if (dll == "d3d12.dll" || dll == "d3d12_xs.dll") { - if (starts_with(name, "D3D12Create") || starts_with(name, "D3D12Serialize") || - name == "D3D12GetDebugInterface" || name == "D3D12EnableExperimentalFeatures" || - name == "D3D12XboxCreateDevice" || name == "D3D12XboxCreateSyntheticDevice") - return ReturnClass::HResult; - } else if (dll == "dxgi.dll") { - if (starts_with(name, "CreateDXGIFactory") || name == "DXGIGetDebugInterface1" || - name == "DXGIDeclareAdapterRemovalSupport") - return ReturnClass::HResult; - } else if (dll == "xaudio2_9.dll" || dll == "xaudio2_9redist.dll") { - if (name == "XAudio2Create") return ReturnClass::HResult; - } else if (dll == "gameinput.dll") { - if (name == "GameInputCreate") return ReturnClass::HResult; - } else if (dll == "dstorage.dll" || dll == "dstorage_xs.dll" || dll == "xcrdapi.dll") { - if (name == "DStorageGetFactory") return ReturnClass::HResult; - } else if (dll == "acphal.dll") { - if (name == "AcpHalAllocateShapeContexts" || name == "AcpHalCreate" || - name == "AcpHalReleaseShapeContexts" || name == "ApuAlloc" || - name == "ApuCreateHeap") - return ReturnClass::HResult; - } else if (dll == "xgameruntime.dll") { - if (name == "XGameRuntimeInitialize" || name == "XGameEventWrite") return ReturnClass::HResult; - for (const char* n : kNotHResult) - if (name == n) return ReturnClass::Other; - for (const char* f : kXFamilies) - if (starts_with(name, f)) return ReturnClass::HResult; - } - return ReturnClass::Other; -} - -struct CallInfo { // what the common stub saved, in this order - uint64_t rcx, rdx, r8, r9, ret; -}; - -// "0x00007ff6... = module+0x1234", resolved through the loaders' module lists, else through the host's modules. -std::string describe_address(uint64_t addr) { - char head[32], tail[64]; - std::snprintf(head, sizeof head, "0x%016llx", static_cast(addr)); - std::string module; - uint32_t rva = 0; - { - std::lock_guard lock(g_lookup_mutex); - for (auto& l : g_lookups) - if (l.fn(l.ctx, addr, module, rva)) { - std::snprintf(tail, sizeof tail, "+0x%x", rva); - return std::string(head) + " = " + module + tail; - } - } - HMODULE host = nullptr; - if (GetModuleHandleExA(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT, - reinterpret_cast(addr), &host) && host) { - char path[MAX_PATH] = {}; - GetModuleFileNameA(host, path, MAX_PATH); - const char* slash = std::strrchr(path, '\\'); - std::snprintf(tail, sizeof tail, "+0x%llx", - static_cast(addr - reinterpret_cast(host))); - return std::string(head) + " = host module " + (slash ? slash + 1 : path) + tail; - } - return std::string(head) + " = not inside any module"; -} - -// Called by the common stub with the import's "dll!name" string and the registers it saved. The return value goes -// back to the game's caller in rax; the stub zeroes xmm0. -extern "C" uint64_t rt_unimplemented(const char* what, const CallInfo* info) { - if (auto hook = g_test_hook.load()) hook(_AddressOfReturnAddress()); - const UnimplementedPolicy policy = unimplemented_policy(); - - // `what` is a string that lives for the process and is unique per import, so the pointer keys the per-import - // state. Strings are built only the first time an import is seen; a repeat call costs one map lookup. - ReturnClass cls; - bool first = false; - { - std::lock_guard lock(g_called_mutex); - auto it = g_seen.find(what); - if (it == g_seen.end()) { - const std::string full = what; - const auto bang = full.find('!'); - cls = classify(lower_ascii(bang == std::string::npos ? "" : full.substr(0, bang)), - bang == std::string::npos ? full : full.substr(bang + 1)); - g_seen.emplace(what, cls); - g_called.insert(full); - first = true; - } else { - cls = it->second; - } - } - const uint64_t fail_value = cls == ReturnClass::HResult ? kENotImpl : 0; - if (first && startup_trace::enabled()) - startup_trace::event("unimplemented_call", "\"import\":" + startup_trace::quote(what) + - ",\"caller\":" + startup_trace::quote(module_offset(info->ret))); - - if (policy == UnimplementedPolicy::Stop) { - RT_LOG_ERROR("STOP: unimplemented import %s called\n" - "[rt] caller %s\n" - "[rt] rcx=0x%llx rdx=0x%llx r8=0x%llx r9=0x%llx\n" - "[rt] return class: %s (LEONIDA_UNIMPLEMENTED=fail returns %s)\n", - what, describe_address(info->ret).c_str(), static_cast(info->rcx), - static_cast(info->rdx), static_cast(info->r8), - static_cast(info->r9), cls == ReturnClass::HResult ? "hresult" : "other", - cls == ReturnClass::HResult ? "E_NOTIMPL" : "0"); - if (IsDebuggerPresent()) { - RT_LOG_ERROR(" debugger attached: breaking; continuing returns the `fail` value\n"); - std::fflush(stderr); - __debugbreak(); - return fail_value; - } - RT_LOG_ERROR(" no debugger attached: terminating the process (exit code %d)\n", kStopExitCode); - std::fflush(stderr); - TerminateProcess(GetCurrentProcess(), kStopExitCode); - return 0; // not reached - } - if (first) - RT_LOG_WARN("unimplemented: %s%s\n", what, - policy == UnimplementedPolicy::Fail - ? (cls == ReturnClass::HResult ? " (returns E_NOTIMPL)" : " (returns 0)") - : ""); - return policy == UnimplementedPolicy::Fail ? fail_value : 0; -} - -// Thunk layout (x86-64), one per import: -// 49 BA mov r10, what ("dll!name"; r10 is volatile and carries no argument) -// 48 B8 mov rax, common_stub -// FF E0 jmp rax -// The game's `call` pushed the return address, so at thunk entry [rsp] is the caller. rcx/rdx/r8/r9 are untouched. -// -// The common stub (one copy, made on first use) saves those registers and the return address, calls -// rt_unimplemented(what, &saved), and returns its rax straight to the game's caller with xmm0 zeroed (so a caller -// that expects a float or double result sees 0.0): -// sub rsp, 0x48 ; 8 (return address) + 0x48 leaves rsp 16-byte aligned at the call -// mov [rsp+0x20..0x38], rcx, rdx, r8, r9 ; the CallInfo, above the 32-byte shadow space -// mov rax, [rsp+0x48]; mov [rsp+0x40], rax ; the return address -// mov rcx, r10; lea rdx, [rsp+0x20]; mov rax, rt_unimplemented; call rax -// add rsp, 0x48; xorps xmm0, xmm0; ret -// An UNWIND_INFO (UWOP_ALLOC_SMALL 0x48) is registered for the stub, so a debugger stopped inside rt_unimplemented -// can walk up into the game. -constexpr size_t kThunkSize = 32; - -uint8_t* g_pool = nullptr; -size_t g_pool_used = 0, g_pool_size = 0; -std::mutex g_pool_mutex; -void* g_stub = nullptr; // under g_pool_mutex - -void* make_common_stub() { - constexpr size_t kUnwindOffset = 0x80, kFunctionOffset = 0x90, kRegionSize = 0x1000; - auto* region = - static_cast(VirtualAlloc(nullptr, kRegionSize, MEM_RESERVE | MEM_COMMIT, PAGE_EXECUTE_READWRITE)); - if (!region) return nullptr; - static const uint8_t head[] = { - 0x48, 0x83, 0xEC, 0x48, // sub rsp, 0x48 - 0x48, 0x89, 0x4C, 0x24, 0x20, // mov [rsp+0x20], rcx - 0x48, 0x89, 0x54, 0x24, 0x28, // mov [rsp+0x28], rdx - 0x4C, 0x89, 0x44, 0x24, 0x30, // mov [rsp+0x30], r8 - 0x4C, 0x89, 0x4C, 0x24, 0x38, // mov [rsp+0x38], r9 - 0x48, 0x8B, 0x44, 0x24, 0x48, // mov rax, [rsp+0x48] - 0x48, 0x89, 0x44, 0x24, 0x40, // mov [rsp+0x40], rax - 0x4C, 0x89, 0xD1, // mov rcx, r10 - 0x48, 0x8D, 0x54, 0x24, 0x20, // lea rdx, [rsp+0x20] - 0x48, 0xB8, // mov rax, imm64 - }; - static const uint8_t tail[] = { - 0xFF, 0xD0, // call rax - 0x48, 0x83, 0xC4, 0x48, // add rsp, 0x48 - 0x0F, 0x57, 0xC0, // xorps xmm0, xmm0 - 0xC3, // ret - }; - static_assert(sizeof(head) + 8 + sizeof(tail) < kUnwindOffset); - const uint64_t fn = reinterpret_cast(&rt_unimplemented); - size_t n = 0; - std::memcpy(region + n, head, sizeof head); - n += sizeof head; - std::memcpy(region + n, &fn, 8); - n += 8; - std::memcpy(region + n, tail, sizeof tail); - n += sizeof tail; - - // UNWIND_INFO: version 1, no flags, prolog of 4 bytes, one code (offset 4, UWOP_ALLOC_SMALL, (0x48 - 8) / 8 = 8). - const uint8_t unwind[] = {0x01, 0x04, 0x01, 0x00, 0x04, 0x82, 0x00, 0x00}; - std::memcpy(region + kUnwindOffset, unwind, sizeof unwind); - auto* rf = reinterpret_cast(region + kFunctionOffset); - rf->BeginAddress = 0; - rf->EndAddress = static_cast(n); - rf->UnwindData = kUnwindOffset; - // Without the table the stub still works; only a stack walk through it (a debugger, an exception) stops there. - if (!RtlAddFunctionTable(rf, 1, reinterpret_cast(region))) - RT_LOG_ERROR("RtlAddFunctionTable failed for the unimplemented-import stub (error %lu): " - "stack walks cannot pass through it\n", GetLastError()); - FlushInstructionCache(GetCurrentProcess(), region, kRegionSize); - return region; -} - -} // namespace - -UnimplementedPolicy parse_unimplemented_policy(const char* text, bool* valid) { - if (valid) *valid = true; - if (!text || !*text) return UnimplementedPolicy::Log; - const std::string v = lower_ascii(text); - if (v == "log") return UnimplementedPolicy::Log; - if (v == "fail") return UnimplementedPolicy::Fail; - if (v == "stop") return UnimplementedPolicy::Stop; - if (valid) *valid = false; - return UnimplementedPolicy::Log; -} - -UnimplementedPolicy unimplemented_policy() { - int p = g_policy.load(); - if (p < 0) { - const std::string text = rt::config::get("loader.unimplemented").text; - bool valid = true; - const UnimplementedPolicy parsed = parse_unimplemented_policy(text.c_str(), &valid); - if (!valid) RT_LOG_WARN("LEONIDA_UNIMPLEMENTED: expected log, fail or stop; using log\n"); - int expected = -1; - g_policy.compare_exchange_strong(expected, static_cast(parsed)); - p = g_policy.load(); - } - return static_cast(p); -} - -void set_unimplemented_policy(UnimplementedPolicy p) { g_policy.store(static_cast(p)); } - -ReturnClass classify_import(const std::string& dll, const std::string& name) { return classify(lower_ascii(dll), name); } - -void set_unimplemented_test_hook(TestHook hook) { g_test_hook.store(hook); } - -void add_module_lookup(void* ctx, ModuleLookup fn) { - std::lock_guard lock(g_lookup_mutex); - g_lookups.push_back({ctx, fn}); -} - -bool mapped_image_base(uint64_t address, uint64_t& base) { - std::string module; - uint32_t rva = 0; - std::lock_guard lock(g_lookup_mutex); - for (auto& l : g_lookups) - if (l.fn(l.ctx, address, module, rva)) { - base = address - rva; - return true; - } - return false; -} - -std::string module_offset(uint64_t address) { - char b[48]; - std::string module; - uint32_t rva = 0; - { - std::lock_guard lock(g_lookup_mutex); - for (auto& l : g_lookups) - if (l.fn(l.ctx, address, module, rva)) { - std::snprintf(b, sizeof b, "+0x%x", rva); - return module + b; - } - } - HMODULE host = nullptr; - if (GetModuleHandleExW(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT, - reinterpret_cast(address), &host) && host) { - // Wide, then UTF-8: the ANSI form would put code-page bytes into the trace's JSON lines. - wchar_t path[MAX_PATH] = {}; - const DWORD len = GetModuleFileNameW(host, path, MAX_PATH); - const wchar_t* slash = std::wcsrchr(path, L'\\'); - const wchar_t* file = slash ? slash + 1 : path; - const int wlen = len ? static_cast(path + len - file) : 0; - const int bytes = wlen > 0 ? WideCharToMultiByte(CP_UTF8, 0, file, wlen, nullptr, 0, nullptr, nullptr) : 0; - std::string name(bytes > 0 ? bytes : 0, '\0'); - if (bytes > 0) WideCharToMultiByte(CP_UTF8, 0, file, wlen, name.data(), bytes, nullptr, nullptr); - std::snprintf(b, sizeof b, "+0x%llx", static_cast(address - reinterpret_cast(host))); - return "host:" + name + b; - } - std::snprintf(b, sizeof b, "0x%llx", static_cast(address)); - return b; -} - -void remove_module_lookup(void* ctx) { - std::lock_guard lock(g_lookup_mutex); - for (auto it = g_lookups.begin(); it != g_lookups.end(); ++it) - if (it->ctx == ctx) { - g_lookups.erase(it); - break; - } -} - -namespace { - -struct BundledLoaderEntry { - void* ctx; - const BundledModuleOps* ops; -}; - -// Immortal: late mapped-DLL detach or atexit handlers may call GetProcAddress/FreeLibrary during process teardown. -std::mutex& bundled_loader_mutex() { - static auto* m = new std::mutex; - return *m; -} - -std::vector& bundled_loaders() { - static auto* v = new std::vector; - return *v; -} - -std::vector snapshot_bundled_loaders() { - std::lock_guard lock(bundled_loader_mutex()); - return bundled_loaders(); -} - -} // namespace - -void add_bundled_loader(void* ctx, const BundledModuleOps* ops) { - if (!ctx || !ops) return; - std::lock_guard lock(bundled_loader_mutex()); - bundled_loaders().push_back({ctx, ops}); -} - -void remove_bundled_loader(void* ctx) { - std::lock_guard lock(bundled_loader_mutex()); - auto& list = bundled_loaders(); - for (auto it = list.begin(); it != list.end(); ++it) - if (it->ctx == ctx) { - list.erase(it); - break; - } -} - -void* find_loaded_bundled_module(const std::string& dll_lower) { - for (const auto& entry : snapshot_bundled_loaders()) - if (void* h = entry.ops->find_loaded(entry.ctx, dll_lower)) return h; - return nullptr; -} - -void* load_bundled_module(const std::string& dll_lower, uint32_t flags, bool& handled) { - handled = false; - for (const auto& entry : snapshot_bundled_loaders()) { - bool loader_handled = false; - void* h = entry.ops->load_bundled(entry.ctx, dll_lower, flags, loader_handled); - if (loader_handled) { - handled = true; - return h; - } - } - return nullptr; -} - -void* find_loaded_bundled_module_w(const std::wstring& basename) { - for (const auto& entry : snapshot_bundled_loaders()) - if (entry.ops->find_loaded_w) - if (void* h = entry.ops->find_loaded_w(entry.ctx, basename)) return h; - return nullptr; -} - -void* load_bundled_module_w(const std::wstring& basename, uint32_t flags, bool& handled) { - handled = false; - for (const auto& entry : snapshot_bundled_loaders()) { - if (!entry.ops->load_bundled_w) continue; - bool loader_handled = false; - void* h = entry.ops->load_bundled_w(entry.ctx, basename, flags, loader_handled); - if (loader_handled) { - handled = true; - return h; - } - } - return nullptr; -} - -void* get_bundled_proc_address(void* module, const std::string& sym, bool& owns_handle) { - owns_handle = false; - for (const auto& entry : snapshot_bundled_loaders()) { - bool loader_owns = false; - void* fn = entry.ops->get_proc(entry.ctx, module, sym, loader_owns); - if (loader_owns) { - owns_handle = true; - return fn; - } - } - return nullptr; -} - -bool owns_bundled_module_handle(void* module) { - for (const auto& entry : snapshot_bundled_loaders()) - if (entry.ops->owns_handle(entry.ctx, module)) return true; - return false; -} - -Table::Table(const Entry* entries, size_t count) { - for (size_t i = 0; i < count; ++i) table()[lower_ascii(entries[i].dll) + "!" + entries[i].name] = entries[i].fn; -} - -void* find(const std::string& dll_lower, const std::string& name) { - auto it = table().find(dll_lower + "!" + name); - return it == table().end() ? nullptr : it->second; -} - -bool owns_dll(const std::string& dll_lower) { - static const char* const host[] = {"kernel32.dll", "kernelbase.dll", "msvcrt.dll", "ucrtbase.dll", "ucrtbased.dll", - "vulkan-1.dll", "ntdll.dll", "user32.dll"}; - if (starts_with(dll_lower, "api-ms-") || starts_with(dll_lower, "ext-ms-")) return false; - for (const char* h : host) - if (dll_lower == h) return false; - const std::string prefix = dll_lower + "!"; - auto it = table().lower_bound(prefix); - return it != table().end() && it->first.compare(0, prefix.size(), prefix) == 0; -} - -void* make_unimplemented_thunk(const std::string& dll, const std::string& name) { - std::lock_guard lock(g_pool_mutex); - static std::map s_thunks; - const std::string key = lower_ascii(dll) + "!" + name; - auto it = s_thunks.find(key); - if (it != s_thunks.end()) return it->second; - - if (!g_stub) g_stub = make_common_stub(); - if (!g_stub) return nullptr; - if (!g_pool || g_pool_used + kThunkSize > g_pool_size) { - g_pool_size = 1 << 20; - g_pool = static_cast(VirtualAlloc(nullptr, g_pool_size, MEM_RESERVE | MEM_COMMIT, PAGE_EXECUTE_READWRITE)); - g_pool_used = 0; - if (!g_pool) return nullptr; - } - const char* what = _strdup(key.c_str()); // lives for the process - uint8_t* t = g_pool + g_pool_used; - g_pool_used += kThunkSize; - const uint64_t a = reinterpret_cast(what), f = reinterpret_cast(g_stub); - uint8_t code[kThunkSize] = {0x49, 0xBA}; - std::memcpy(code + 2, &a, 8); - code[10] = 0x48; - code[11] = 0xB8; - std::memcpy(code + 12, &f, 8); - code[20] = 0xFF; - code[21] = 0xE0; - std::memset(code + 22, 0xCC, kThunkSize - 22); - std::memcpy(t, code, kThunkSize); - FlushInstructionCache(GetCurrentProcess(), t, kThunkSize); - s_thunks.emplace(key, t); - return t; -} - -void report_called_unimplemented() { - std::lock_guard lock(g_called_mutex); - for (auto& s : g_called) std::fprintf(stderr, " called: %s\n", s.c_str()); -} - -} // namespace rt::shims diff --git a/runtime/shims/shims.h b/runtime/shims/shims.h deleted file mode 100644 index d157a582b..000000000 --- a/runtime/shims/shims.h +++ /dev/null @@ -1,99 +0,0 @@ -// Shim registry: reimplementations of console-only imports. -// Add a DLL by writing a shims/.cpp with a SHIM_TABLE and listing it in cmake/windows_runtime.cmake. -#pragma once -#include -#include - -namespace rt::shims { - -struct Entry { - const char* dll; // lower-case, with .dll - const char* name; // export name, or "#ordinal" - void* fn; -}; - -// Registers a static table at startup. -struct Table { - Table(const Entry* entries, size_t count); -}; - -void* find(const std::string& dll_lower, const std::string& name); - -// Whether the shims own a whole module: the registry serves names from it and it is not a host system DLL (kernel32, -// kernelbase, the CRTs, api-ms-* sets, vulkan-1) of which only a few functions are replaced. A title's -// LoadLibrary/GetModuleHandle of an owned module gets a pseudo-handle that GetProcAddress resolves through find() -// (library_loader.cpp). `dll_lower` is a lower-case file name with ".dll". -bool owns_dll(const std::string& dll_lower); - -// What a call to an import that has no binding does. Chosen by the environment variable LEONIDA_UNIMPLEMENTED -// (read once, on the first call): -// log (default) print the name once and return 0, in rax and xmm0 -// fail as log, but return E_NOTIMPL for imports classified as HRESULT-returning (classify_import) -// stop on the first call print the import, the caller's return address as module+RVA and rcx, rdx, r8, -// r9 as received; then break if a debugger is attached, else end the process with exit code 3 -// Out parameters are never written in any mode. -enum class UnimplementedPolicy { Log, Fail, Stop }; - -// Whether an import is known to return an HRESULT. Judged by DLL and name only; see registry.cpp for the list and -// where each entry comes from. Unknown imports are Other. -enum class ReturnClass { HResult, Other }; - -inline constexpr uint32_t kENotImpl = 0x80004001u; // E_NOTIMPL - -// "log", "fail" or "stop", any case. Empty or null is log without complaint; anything else is log with *valid = false. -UnimplementedPolicy parse_unimplemented_policy(const char* text, bool* valid = nullptr); -UnimplementedPolicy unimplemented_policy(); -void set_unimplemented_policy(UnimplementedPolicy policy); // overrides the environment (tests) -ReturnClass classify_import(const std::string& dll, const std::string& name); - -// Resolves an address to a mapped module for the `stop` message. A Loader registers itself; `fn` returns true and -// fills the module's file name and the address's RVA when the address is inside one of its modules. -using ModuleLookup = bool (*)(void* ctx, uint64_t address, std::string& module, uint32_t& rva); -void add_module_lookup(void* ctx, ModuleLookup fn); -// "a.dll+0x1234" for an address inside a mapped module, "host:ntdll.dll+0x1234" inside a host module, else the bare -// address in hex. Used by the startup trace (startup_trace.h). -std::string module_offset(uint64_t address); -void remove_module_lookup(void* ctx); - -// The base of the mapped module holding `address`, through the same lookups. False if no live Loader maps it. -bool mapped_image_base(uint64_t address, uint64_t& base); - -// Run-time LoadLibrary / GetModuleHandle / GetProcAddress / FreeLibrary for bundled package DLLs managed by a live -// Loader. Registered in Loader::Loader and removed in Loader::~Loader. -struct BundledModuleOps { - void* (*find_loaded)(void* ctx, const std::string& dll_lower); - void* (*load_bundled)(void* ctx, const std::string& dll_lower, uint32_t flags, bool& handled); - void* (*get_proc)(void* ctx, void* module, const std::string& sym, bool& owns_handle); - bool (*owns_handle)(void* ctx, void* module); - // The same two lookups by the module's native (wide) basename, for names the ANSI code page cannot spell - // (library_loader's W entries use them when a name has a character outside ASCII). Either may be null. - void* (*find_loaded_w)(void* ctx, const std::wstring& basename); - void* (*load_bundled_w)(void* ctx, const std::wstring& basename, uint32_t flags, bool& handled); -}; -void add_bundled_loader(void* ctx, const BundledModuleOps* ops); -void remove_bundled_loader(void* ctx); - -void* find_loaded_bundled_module(const std::string& dll_lower); -void* load_bundled_module(const std::string& dll_lower, uint32_t flags, bool& handled); -void* find_loaded_bundled_module_w(const std::wstring& basename); -void* load_bundled_module_w(const std::wstring& basename, uint32_t flags, bool& handled); -void* get_bundled_proc_address(void* module, const std::string& sym, bool& owns_handle); -bool owns_bundled_module_handle(void* module); - -// Test seam: called at the top of every unimplemented-import call with the address of rt_unimplemented's return -// address slot (so a test can check stack alignment) and from inside the call (so it can walk the stack). -using TestHook = void (*)(const void* return_address_slot); -void set_unimplemented_test_hook(TestHook hook); - -// Makes a small thunk for an import with no binding; calling it follows the policy above. It passes the caller's -// return address and the first four argument registers through unchanged. -void* make_unimplemented_thunk(const std::string& dll, const std::string& name); - -// Prints every unimplemented import that has been called. -void report_called_unimplemented(); - -} // namespace rt::shims - -#define SHIM_TABLE(id, ...) \ - static const ::rt::shims::Entry id##_entries[] = {__VA_ARGS__}; \ - static ::rt::shims::Table id##_table(id##_entries, sizeof(id##_entries) / sizeof(id##_entries[0])) diff --git a/runtime/shims/startup_trace.h b/runtime/shims/startup_trace.h deleted file mode 100644 index 4f14a715f..000000000 --- a/runtime/shims/startup_trace.h +++ /dev/null @@ -1,279 +0,0 @@ -// Opt-in startup trace: gta6rt --trace FILE. -// -// One JSON object per line, flushed per event so the file survives a crash. Off by default; every entry point is a -// single relaxed load when it is off. Events: -// {"seq":1,"t":0.000,"kind":"trace_open"} -// {"seq":2,"t":0.001,"kind":"map","module":"a.dll","base":"0x...","size":"0x2000","relocated":false} -// {"seq":3,"t":0.002,"kind":"tls_callback","module":"a.dll","at":"a.dll+0x1200","reason":1} -// {"seq":4,"t":0.002,"kind":"dllmain","module":"a.dll","result":1} -// {"seq":5,"t":0.010,"kind":"unimplemented_call","import":"x.dll!Foo","caller":"a.dll+0x3f10"} (first call only) -// {"seq":6,"t":0.011,"kind":"debug_string","text":"..."} -// {"seq":7,"t":0.020,"kind":"exception","code":"0xc0000005","at":"a.dll+0x4a00","access":"read","address":"0x0", -// "stack":["a.dll+0x4a00","a.dll+0x2210"]} -// {"seq":8,"t":0.030,"kind":"exit","code":0} -// -// The exception handler is vectored, logs and returns EXCEPTION_CONTINUE_SEARCH: it never changes what the process -// does (except LEONIDA_SKIP_INT3, below). -// OutputDebugStringA/W raise DBG_PRINTEXCEPTION_C / DBG_PRINTEXCEPTION_WIDE_C when no debugger is attached, so the -// same handler records their text without a shim. -// -// The file can quote whatever the game prints: it stays on the player's machine (AGENTS.md, "No game data"). -#pragma once - -#include -#include - -#include -#include -#include -#include -#include -#include -#include -#include - -#include "shims.h" - -namespace rt::startup_trace { - -namespace detail { -inline std::atomic on{false}; -// Intentionally immortal: vectored exception handlers or late teardown paths can still run after normal statics would -// have been destroyed. -inline std::mutex& mutex() { - static auto* m = new std::mutex; - return *m; -} -inline FILE* file = nullptr; -inline unsigned long long seq = 0; -inline std::chrono::steady_clock::time_point start; -inline void* veh = nullptr; -inline thread_local bool in_handler = false; -// set_skip_int3(): whether the handler steps over an int3 in guest code (skip_int3, below). -inline std::atomic skip_int3_on{false}; -// With nothing to handle it, OutputDebugStringW's DBG_PRINTEXCEPTION_WIDE_C falls back to OutputDebugStringA on its -// own ANSI copy (ExceptionInformation[3]), a second, lossy exception for the same text. Every debug string on the -// thread resets this, so only the exception right after the wide one, with that same pointer, is skipped. -inline thread_local ULONG_PTR wide_fallback = 0; - -inline void append_escaped(std::string& out, const char* s, size_t n) { - static const char hex[] = "0123456789abcdef"; - for (size_t i = 0; i < n; ++i) { - const unsigned char c = static_cast(s[i]); - switch (c) { - case '"': out += "\\\""; break; - case '\\': out += "\\\\"; break; - case '\n': out += "\\n"; break; - case '\r': out += "\\r"; break; - case '\t': out += "\\t"; break; - default: - if (c < 0x20) { - out += "\\u00"; - out += hex[c >> 4]; - out += hex[c & 15]; - } else { - out += static_cast(c); // UTF-8 passes through - } - } - } -} -} // namespace detail - -inline bool enabled() noexcept { return detail::on.load(std::memory_order_acquire); } - -// loader.skip_int3 (LEONIDA_SKIP_INT3): whether the handler steps over an int3 in guest code (skip_int3, below). -// Off until this is called; gta6rt calls it from the setting before it opens the trace. -inline void set_skip_int3(bool skip) noexcept { detail::skip_int3_on.store(skip, std::memory_order_release); } - -// A JSON string literal, quotes included. -inline std::string quote(const std::string& s) { - std::string out = "\""; - detail::append_escaped(out, s.data(), s.size()); - out += '"'; - return out; -} - -inline std::string hex(uint64_t v) { - char b[24]; - std::snprintf(b, sizeof b, "0x%llx", static_cast(v)); - return b; -} - -// "module+0xRVA" for a mapped image or a host module, else the bare address. -inline std::string where(uint64_t address) { return shims::module_offset(address); } - -// `fields` is the rest of the object, already JSON: `"module":"a.dll","result":1`. Empty is allowed. -inline void event(const char* kind, const std::string& fields = {}) { - if (!enabled()) return; - const std::lock_guard lock(detail::mutex()); - if (!detail::file) return; - const double t = std::chrono::duration(std::chrono::steady_clock::now() - detail::start).count(); - std::fprintf(detail::file, "{\"seq\":%llu,\"t\":%.6f,\"kind\":\"%s\"%s%s}\n", ++detail::seq, t, kind, - fields.empty() ? "" : ",", fields.c_str()); - std::fflush(detail::file); -} - -namespace detail { -constexpr DWORD kDbgPrint = 0x40010006; // DBG_PRINTEXCEPTION_C -constexpr DWORD kDbgPrintWide = 0x4001000A; // DBG_PRINTEXCEPTION_WIDE_C -constexpr DWORD kCppException = 0xE06D7363; // MSVC throw: logged with its address, never its payload -constexpr int kMaxFrames = 16; - -inline std::string stack_from(const CONTEXT& start_context) { - CONTEXT c = start_context; - std::string out = "["; - for (int i = 0; i < kMaxFrames && c.Rip; ++i) { - if (i) out += ','; - out += quote(where(c.Rip)); - DWORD64 image_base = 0; - PRUNTIME_FUNCTION fn = RtlLookupFunctionEntry(c.Rip, &image_base, nullptr); - if (!fn) { // a leaf function: the return address is at [rsp] - if (!c.Rsp || IsBadReadPtr(reinterpret_cast(c.Rsp), 8)) break; - c.Rip = *reinterpret_cast(c.Rsp); - c.Rsp += 8; - continue; - } - void* handler_data = nullptr; - DWORD64 frame = 0; - RtlVirtualUnwind(UNW_FLAG_NHANDLER, image_base, c.Rip, fn, &c, &handler_data, &frame, nullptr); - } - return out + "]"; -} - -inline std::string utf8_from_wide(const wchar_t* w, int len) { - const int bytes = len > 0 ? WideCharToMultiByte(CP_UTF8, 0, w, len, nullptr, 0, nullptr, nullptr) : 0; - std::string s(bytes > 0 ? bytes : 0, '\0'); - if (bytes > 0) WideCharToMultiByte(CP_UTF8, 0, w, len, s.data(), bytes, nullptr, nullptr); - return s; -} - -// OutputDebugStringA text is in the ANSI code page, not UTF-8: convert it, or a byte such as 0xE9 would land in the -// file as is and break the JSON lines for a strict UTF-8 reader. -inline std::string utf8_from_ansi(const char* a, int len) { - const int chars = len > 0 ? MultiByteToWideChar(CP_ACP, 0, a, len, nullptr, 0) : 0; - if (chars <= 0) return {}; - std::wstring w(static_cast(chars), L'\0'); - MultiByteToWideChar(CP_ACP, 0, a, len, w.data(), chars); - return utf8_from_wide(w.data(), chars); -} - -inline std::string debug_text(const EXCEPTION_RECORD& r) { - // Parameters: [0] length in characters including the terminator, [1] the string. - if (r.NumberParameters < 2 || !r.ExceptionInformation[1]) return {}; - const size_t n = static_cast(r.ExceptionInformation[0]); - if (r.ExceptionCode == kDbgPrintWide) { - const auto* w = reinterpret_cast(r.ExceptionInformation[1]); - return utf8_from_wide(w, static_cast(n ? n - 1 : wcslen(w))); - } - const auto* a = reinterpret_cast(r.ExceptionInformation[1]); - return utf8_from_ansi(a, static_cast(n ? n - 1 : strlen(a))); -} - -inline void log_exception(const EXCEPTION_POINTERS& info) { - const EXCEPTION_RECORD& r = *info.ExceptionRecord; - try { - if (r.ExceptionCode == kDbgPrint || r.ExceptionCode == kDbgPrintWide) { - const ULONG_PTR fallback = wide_fallback; - const bool wide = r.ExceptionCode == kDbgPrintWide; - wide_fallback = wide && r.NumberParameters >= 4 ? r.ExceptionInformation[3] : 0; - if (!wide && fallback && r.NumberParameters >= 2 && r.ExceptionInformation[1] == fallback) return; - std::string text = debug_text(r); - while (!text.empty() && (text.back() == '\n' || text.back() == '\r')) text.pop_back(); - event("debug_string", "\"text\":" + quote(text)); - } else { - std::string f = "\"code\":" + quote(hex(r.ExceptionCode)) + - ",\"at\":" + quote(where(reinterpret_cast(r.ExceptionAddress))); - if (r.ExceptionCode == EXCEPTION_ACCESS_VIOLATION && r.NumberParameters >= 2) { - const auto op = r.ExceptionInformation[0]; - f += ",\"access\":" + quote(op == 0 ? "read" : op == 1 ? "write" : "execute") + - ",\"address\":" + quote(hex(r.ExceptionInformation[1])); - } - if (r.ExceptionCode == kCppException) f += ",\"cpp\":true"; - if (info.ContextRecord) f += ",\"stack\":" + stack_from(*info.ContextRecord); - event("exception", f); - } - } catch (...) { - // Out of memory while formatting: drop the event rather than disturb the process. - } -} - -// loader.skip_int3 (LEONIDA_SKIP_INT3; diagnostic, with --trace): an int3 in guest code is logged once per address -// and stepped over, so a boot can be followed past the title's soft asserts (an int3 followed by code that carries -// on). Off by default: a console title never reaches one in a correct run, so each skipped address is a finding, not -// a fix. This header reads no setting itself: gta6rt turns it on with set_skip_int3() before it opens the trace. -inline bool skip_int3(EXCEPTION_POINTERS* info) { - if (!detail::skip_int3_on.load(std::memory_order_acquire)) return false; - if (info->ExceptionRecord->ExceptionCode != EXCEPTION_BREAKPOINT || !info->ContextRecord) return false; - const auto* at = static_cast(info->ExceptionRecord->ExceptionAddress); - if (!at || *at != 0xCC || info->ContextRecord->Rip != reinterpret_cast(at)) return false; - static std::mutex m; - static std::set seen; - bool first = false; - { - const std::lock_guard lock(m); - first = seen.insert(at).second; - } - if (first) event("int3_skipped", "\"at\":" + quote(where(reinterpret_cast(at)))); - info->ContextRecord->Rip += 1; - return true; -} - -inline LONG CALLBACK handler(EXCEPTION_POINTERS* info) { - if (!enabled() || in_handler || !info || !info->ExceptionRecord) return EXCEPTION_CONTINUE_SEARCH; - if (skip_int3(info)) return EXCEPTION_CONTINUE_EXECUTION; - in_handler = true; -#ifdef _MSC_VER - // Under /EHsc, catch(...) does not catch SEH faults (e.g. a bad DBG_PRINTEXCEPTION_C pointer or corrupt unwind). - // Keep the __try frame free of C++ destructors so in_handler is always reset and the exception still propagates. - __try { - log_exception(*info); - } __except (EXCEPTION_EXECUTE_HANDLER) { - } -#else - struct Reset { - ~Reset() { in_handler = false; } - } reset; - log_exception(*info); -#endif - in_handler = false; - return EXCEPTION_CONTINUE_SEARCH; -} -} // namespace detail - -inline void close(); - -// Creates the trace file and installs the exception handler. The file must not exist yet ("x" mode): the trace is -// opened before the loader reads anything, so overwriting would let `--trace` destroy an input, such as the image -// itself. Returns false if the file exists or cannot be created; `error`, when given, receives the errno. -inline bool open(const wchar_t* path, int* error = nullptr) { - { - const std::lock_guard lock(detail::mutex()); - if (detail::file) return true; - const errno_t e = _wfopen_s(&detail::file, path, L"wxb"); - if (e != 0 || !detail::file) { - detail::file = nullptr; - if (error) *error = e ? e : EINVAL; - return false; - } - detail::start = std::chrono::steady_clock::now(); - detail::seq = 0; - static const int atexit_registered = std::atexit(&close); - (void)atexit_registered; - } - detail::veh = AddVectoredExceptionHandler(1, &detail::handler); - detail::on.store(true, std::memory_order_release); - event("trace_open", "\"pid\":" + std::to_string(GetCurrentProcessId())); - return true; -} - -// Removes the handler and closes the file (tests and process exit via atexit). -inline void close() { - detail::on.store(false, std::memory_order_release); - if (detail::veh) RemoveVectoredExceptionHandler(detail::veh); - detail::veh = nullptr; - const std::lock_guard lock(detail::mutex()); - if (detail::file) std::fclose(detail::file); - detail::file = nullptr; -} - -} // namespace rt::startup_trace diff --git a/runtime/shims/winhttp_offline.cpp b/runtime/shims/winhttp_offline.cpp deleted file mode 100644 index 1321d9d72..000000000 --- a/runtime/shims/winhttp_offline.cpp +++ /dev/null @@ -1,459 +0,0 @@ -// winhttp_offline: WinHTTP for a mapped title, with no network. -// -// The package's XCurl.dll and libHttpClient.GDK.dll do their HTTP through WinHTTP: between them they import 16 -// functions from winhttp.dll and nothing from Winsock (docs/runtime_imports.md, "WinHTTP offline"). Bound to the host's -// winhttp.dll a mapped title could reach the network, and nothing here goes online. So winhttp.dll is a module the -// shims own (a LoadLibrary of it gets a pseudo-handle, library_loader.cpp) and every function a title can reach is -// answered in-process: -// - WinHttpOpen, WinHttpConnect and WinHttpOpenRequest return local handles. WinHttpConnect resolves no name and -// opens no socket. -// - WinHttpSendRequest fails with ERROR_WINHTTP_CANNOT_CONNECT. On a session opened with WINHTTP_FLAG_ASYNC it -// returns TRUE and reports the failure the way WinHTTP does, through the status callback: -// WINHTTP_CALLBACK_STATUS_REQUEST_ERROR with WINHTTP_ASYNC_RESULT { API_SEND_REQUEST, ERROR_WINHTTP_CANNOT_CONNECT }, -// from a thread-pool thread, with the context the request was sent with (a context of 0 keeps the one set with -// WINHTTP_OPTION_CONTEXT_VALUE). -// - Reading a response (WinHttpReceiveResponse, WinHttpQueryHeaders, WinHttpQueryDataAvailable, WinHttpReadData) and -// WinHttpWriteData fail with ERROR_WINHTTP_INCORRECT_HANDLE_STATE: no request ever got that far. -// - Options, timeouts and request headers are accepted. WINHTTP_OPTION_CONTEXT_VALUE is kept per handle and -// WINHTTP_OPTION_HANDLE_TYPE answered; WinHttpQueryOption reports ERROR_WINHTTP_INVALID_OPTION for the rest. -// - A status callback set on a handle is inherited by the handles created under it, as in WinHTTP, and so is -// the handle's WINHTTP_OPTION_CONTEXT_VALUE as it is when the child is made. -// WINHTTP_CALLBACK_STATUS_HANDLE_CREATED is reported when a child handle is made, and -// WINHTTP_CALLBACK_STATUS_HANDLE_CLOSING once per handle, last, after WinHttpCloseHandle and any callback still -// running for it. -// - WinHttpCrackUrl only parses a string, so it is the host's. -// Each refused server is logged once ("[rt] winhttp: offline, refused :"), which says what a title tried -// to reach. Only images mapped by the loader see these: they are bound through the registry, the runtime's own code -// calls the host directly. -#include -#include - -#include -#include -#include -#include -#include -#include -#include - -#include "../core/log.h" -#include "shims.h" - -namespace rt::winhttp { -namespace { - -enum class Kind { Session, Connect, Request }; - -struct Handle { - Kind kind = Kind::Session; - Handle* parent = nullptr; // holds one reference on the parent - bool async = false; - std::atomic refs{1}; // the handle's own reference, dropped by WinHttpCloseHandle - std::atomic closed{false}; - - std::mutex mutex; // guards the three below - WINHTTP_STATUS_CALLBACK callback = nullptr; - DWORD notifications = 0; - DWORD_PTR context = 0; - - std::wstring server; // Connect: for the log - INTERNET_PORT port = 0; -}; - -// Intentionally immortal: a mapped DLL can close handles from DLL_PROCESS_DETACH, after normal statics are gone. -std::mutex& live_mutex() { - static auto* m = new std::mutex; - return *m; -} -std::set& live() { - static auto* s = new std::set; - return *s; -} - -HINTERNET to_hinternet(Handle* h) { return reinterpret_cast(h); } - -// Takes a reference on a live handle of an accepted kind. On failure `error` says why: ERROR_INVALID_HANDLE for -// something that is not an open handle, ERROR_WINHTTP_INCORRECT_HANDLE_TYPE for the wrong kind. -Handle* acquire(HINTERNET handle, bool session, bool connect, bool request, DWORD& error) { - Handle* h = reinterpret_cast(handle); - std::lock_guard lock(live_mutex()); - if (!handle || live().count(h) == 0) { - error = ERROR_INVALID_HANDLE; - return nullptr; - } - const bool ok = (h->kind == Kind::Session && session) || (h->kind == Kind::Connect && connect) || - (h->kind == Kind::Request && request); - if (!ok) { - error = ERROR_WINHTTP_INCORRECT_HANDLE_TYPE; - return nullptr; - } - h->refs.fetch_add(1); - return h; -} - -void notify(Handle* h, DWORD status, void* info, DWORD length) { - WINHTTP_STATUS_CALLBACK callback; - DWORD notifications; - DWORD_PTR context; - { - std::lock_guard lock(h->mutex); - callback = h->callback; - notifications = h->notifications; - context = h->context; - } - // The WINHTTP_CALLBACK_FLAG_* bits are the status values they select. - if (callback && callback != WINHTTP_INVALID_STATUS_CALLBACK && (notifications & status) != 0) - callback(to_hinternet(h), context, status, info, length); -} - -void release(Handle* h) { - while (h && h->refs.fetch_sub(1) == 1) { - HINTERNET self = to_hinternet(h); - notify(h, WINHTTP_CALLBACK_STATUS_HANDLE_CLOSING, &self, sizeof(self)); - Handle* parent = h->parent; - delete h; - h = parent; // the child's reference on its parent - } -} - -HINTERNET make_handle(Kind kind, Handle* parent, bool async, LPCWSTR server = nullptr, INTERNET_PORT port = 0) { - std::wstring host = server ? server : L""; - auto* h = new (std::nothrow) Handle; - if (!h) { - if (parent) release(parent); - SetLastError(ERROR_NOT_ENOUGH_MEMORY); - return nullptr; - } - // Publish connection metadata before live() / HANDLE_CREATED: the callback can use or close the handle inline. - h->server = std::move(host); - h->port = port; - h->kind = kind; - h->parent = parent; - h->async = async; - if (parent) { - // A callback set on a handle is inherited by the handles created under it, and so is the context value - // (WINHTTP_OPTION_CONTEXT_VALUE), as the host's winhttp.dll does: what the parent has at this moment. - std::lock_guard lock(parent->mutex); - h->callback = parent->callback; - h->notifications = parent->notifications; - h->context = parent->context; - } - { - std::lock_guard lock(live_mutex()); - live().insert(h); - } - if (parent) { - h->refs.fetch_add(1); // held while HANDLE_CREATED runs, so HANDLE_CLOSING comes after it - HINTERNET self = to_hinternet(h); - notify(h, WINHTTP_CALLBACK_STATUS_HANDLE_CREATED, &self, sizeof(self)); - const bool closed = h->closed.load(); - release(h); - if (closed) { - SetLastError(ERROR_WINHTTP_OPERATION_CANCELLED); - return nullptr; - } - } - return to_hinternet(h); -} - -std::wstring server_of(const Handle* request) { - const Handle* connect = request ? request->parent : nullptr; - if (!connect) return L"?"; - return connect->server + L":" + std::to_wstring(connect->port); -} - -void log_refused(const Handle* request) { - static auto* logged = new std::set; - static auto* mutex = new std::mutex; - const std::wstring server = server_of(request); - std::lock_guard lock(*mutex); - if (logged->insert(server).second && rt::log::enabled(rt::log::Level::Warn)) { - std::fwprintf(stderr, L"[rt] winhttp: offline, refused %ls\n", server.c_str()); - } -} - -void CALLBACK send_failed(PTP_CALLBACK_INSTANCE, void* context) { - Handle* h = static_cast(context); - if (!h->closed.load()) { - WINHTTP_ASYNC_RESULT result{}; - result.dwResult = API_SEND_REQUEST; - result.dwError = ERROR_WINHTTP_CANNOT_CONNECT; - notify(h, WINHTTP_CALLBACK_STATUS_REQUEST_ERROR, &result, sizeof(result)); - } - release(h); // the reference WinHttpSendRequest took for this callback -} - -BOOL fail(DWORD error) { - SetLastError(error); - return FALSE; -} - -} // namespace - -HINTERNET WINAPI open_session(LPCWSTR, DWORD, LPCWSTR, LPCWSTR, DWORD flags) { - static std::once_flag once; - std::call_once(once, [] { - RT_LOG_INFO("winhttp: offline; requests fail with ERROR_WINHTTP_CANNOT_CONNECT\n"); - }); - return make_handle(Kind::Session, nullptr, (flags & WINHTTP_FLAG_ASYNC) != 0); -} - -HINTERNET WINAPI open_connection(HINTERNET session, LPCWSTR server, INTERNET_PORT port, DWORD) { - DWORD error = 0; - Handle* s = acquire(session, true, false, false, error); - if (!s) { - SetLastError(error); - return nullptr; - } - if (!server || !*server) { - release(s); - SetLastError(ERROR_INVALID_PARAMETER); - return nullptr; - } - return make_handle(Kind::Connect, s, s->async, server, port); // keeps the reference on the session -} - -HINTERNET WINAPI open_request(HINTERNET connection, LPCWSTR, LPCWSTR, LPCWSTR, LPCWSTR, LPCWSTR*, DWORD) { - DWORD error = 0; - Handle* c = acquire(connection, false, true, false, error); - if (!c) { - SetLastError(error); - return nullptr; - } - return make_handle(Kind::Request, c, c->async); // keeps the reference on the connection -} - -BOOL WINAPI send_request(HINTERNET request, LPCWSTR, DWORD, LPVOID, DWORD, DWORD, DWORD_PTR context) { - DWORD error = 0; - Handle* r = acquire(request, false, false, true, error); - if (!r) return fail(error); - if (context) { - // The context this request's callbacks carry. 0 keeps the one set with WINHTTP_OPTION_CONTEXT_VALUE, as the - // host's winhttp.dll does (measured on Windows 11: WinHttpQueryOption and every callback still give it). - std::lock_guard lock(r->mutex); - r->context = context; - } - log_refused(r); - if (!r->async) { - release(r); - return fail(ERROR_WINHTTP_CANNOT_CONNECT); - } - // Asynchronous: the failure arrives through the callback, never on the calling thread, as with WinHTTP. The - // reference taken above is the callback's and is dropped there. - if (!TrySubmitThreadpoolCallback(&send_failed, r, nullptr)) { - const DWORD submit_error = GetLastError(); - release(r); - return fail(submit_error ? submit_error : ERROR_NOT_ENOUGH_MEMORY); - } - SetLastError(ERROR_SUCCESS); - return TRUE; -} - -// No request was ever sent, so there is no response to read and nothing to write to. -BOOL WINAPI receive_response(HINTERNET request, LPVOID) { - DWORD error = 0; - Handle* r = acquire(request, false, false, true, error); - if (!r) return fail(error); - release(r); - return fail(ERROR_WINHTTP_INCORRECT_HANDLE_STATE); -} - -BOOL WINAPI query_data_available(HINTERNET request, LPDWORD) { return receive_response(request, nullptr); } -BOOL WINAPI read_data(HINTERNET request, LPVOID, DWORD, LPDWORD) { return receive_response(request, nullptr); } -BOOL WINAPI write_data(HINTERNET request, LPCVOID, DWORD, LPDWORD) { return receive_response(request, nullptr); } -BOOL WINAPI query_headers(HINTERNET request, DWORD, LPCWSTR, LPVOID, LPDWORD, LPDWORD) { - return receive_response(request, nullptr); -} - -// RFC 7230 tchar grammar for HTTP header field-names (matches native WinHttpAddRequestHeaders): -// printable ASCII 0x21..0x7E excluding HTTP token separators ()<>@,;:\"/[]?={}. -bool is_header_name_char(wchar_t ch) { - if (ch <= 0x20 || ch >= 0x7F) return false; - switch (ch) { - case L'(': case L')': case L'<': case L'>': case L'@': - case L',': case L';': case L':': case L'\\': case L'"': - case L'/': case L'[': case L']': case L'?': case L'=': - case L'{': case L'}': - return false; - default: - return true; - } -} - -// Headers WinHTTP would reject. Measured against the host's winhttp.dll (Windows 10 19045 / Windows 11 26100): -// a null or empty block (count == 0), embedded NULs, a non-empty line with no ':', an empty header name (": v"), -// or any non-token character (whitespace, control, separator, or non-ASCII) in a header name fail with -// ERROR_INVALID_PARAMETER; a non-empty block containing only blank lines ("\r\n") is accepted by the host. -// A length of (DWORD)-1 means the text is NUL-terminated. Nothing is stored: no request is ever sent. -bool header_block_valid(LPCWSTR headers, DWORD length) { - if (!headers) return false; - const size_t count = length == static_cast(-1) ? wcslen(headers) : static_cast(length); - if (count == 0) return false; - size_t i = 0; - while (i < count) { - if (headers[i] == L'\0') return false; - const size_t line_start = i; - while (i < count && headers[i] != L'\r' && headers[i] != L'\n') { - if (headers[i] == L'\0') return false; - ++i; - } - const size_t line_end = i; - if (i < count && headers[i] == L'\r') ++i; - if (i < count && headers[i] == L'\n') ++i; - if (line_end == line_start) continue; - size_t colon = line_start; - while (colon < line_end && headers[colon] != L':') ++colon; - if (colon == line_start || colon == line_end) return false; - for (size_t k = line_start; k < colon; ++k) { - if (!is_header_name_char(headers[k])) return false; - } - } - return true; -} - -BOOL WINAPI add_request_headers(HINTERNET request, LPCWSTR headers, DWORD length, DWORD) { - DWORD error = 0; - Handle* r = acquire(request, false, false, true, error); - if (!r) return fail(error); - release(r); - if (!header_block_valid(headers, length)) return fail(ERROR_INVALID_PARAMETER); - return TRUE; -} - -// Measured the same way: valid on session and request handles (connect handles fail with -// ERROR_WINHTTP_INCORRECT_HANDLE_TYPE); 0 and -1 (infinite) are accepted; any other negative value, in any of the -// four, fails with ERROR_INVALID_PARAMETER. -BOOL WINAPI set_timeouts(HINTERNET handle, int resolve, int connect, int send, int receive) { - DWORD error = 0; - Handle* h = acquire(handle, true, false, true, error); - if (!h) return fail(error); - release(h); - if (resolve < -1 || connect < -1 || send < -1 || receive < -1) return fail(ERROR_INVALID_PARAMETER); - return TRUE; -} - -BOOL WINAPI set_option(HINTERNET handle, DWORD option, LPVOID buffer, DWORD length) { - if (!handle) { - if (option == WINHTTP_OPTION_CONTEXT_VALUE) return fail(ERROR_WINHTTP_INCORRECT_HANDLE_TYPE); - return TRUE; // process-wide options: accepted, nothing to apply - } - DWORD error = 0; - Handle* h = acquire(handle, true, true, true, error); - if (!h) return fail(error); - if (option == WINHTTP_OPTION_CONTEXT_VALUE) { - if (!buffer) { - release(h); - return fail(ERROR_INVALID_PARAMETER); - } - if (length < sizeof(DWORD_PTR)) { - release(h); - return fail(ERROR_INSUFFICIENT_BUFFER); - } - std::lock_guard lock(h->mutex); - h->context = *static_cast(buffer); - } - release(h); - return TRUE; -} - -BOOL WINAPI query_option(HINTERNET handle, DWORD option, LPVOID buffer, LPDWORD length) { - if (!length) return fail(ERROR_INVALID_PARAMETER); - DWORD error = 0; - Handle* h = acquire(handle, true, true, true, error); - if (!h) return fail(error); - DWORD_PTR value_ptr = 0; - DWORD value_dword = 0; - const void* value = nullptr; - DWORD size = 0; - if (option == WINHTTP_OPTION_CONTEXT_VALUE) { - std::lock_guard lock(h->mutex); - value_ptr = h->context; - value = &value_ptr; - size = sizeof(value_ptr); - } else if (option == WINHTTP_OPTION_HANDLE_TYPE) { - value_dword = h->kind == Kind::Session ? WINHTTP_HANDLE_TYPE_SESSION - : h->kind == Kind::Connect ? WINHTTP_HANDLE_TYPE_CONNECT - : WINHTTP_HANDLE_TYPE_REQUEST; - value = &value_dword; - size = sizeof(value_dword); - } - release(h); - if (!value) return fail(ERROR_WINHTTP_INVALID_OPTION); - if (!buffer || *length < size) { - *length = size; - return fail(ERROR_INSUFFICIENT_BUFFER); - } - std::memcpy(buffer, value, size); - *length = size; - return TRUE; -} - -WINHTTP_STATUS_CALLBACK WINAPI set_status_callback(HINTERNET handle, WINHTTP_STATUS_CALLBACK callback, - DWORD notifications, DWORD_PTR) { - if (!handle) { - SetLastError(ERROR_WINHTTP_INCORRECT_HANDLE_TYPE); - return WINHTTP_INVALID_STATUS_CALLBACK; - } - DWORD error = 0; - Handle* h = acquire(handle, true, true, true, error); - if (!h) { - SetLastError(error); - return WINHTTP_INVALID_STATUS_CALLBACK; - } - WINHTTP_STATUS_CALLBACK previous; - { - std::lock_guard lock(h->mutex); - previous = h->callback; - h->callback = callback; - h->notifications = callback ? notifications : 0; - } - release(h); - return previous; -} - -BOOL WINAPI close_handle(HINTERNET handle) { - Handle* h = reinterpret_cast(handle); - { - std::lock_guard lock(live_mutex()); - if (!handle || live().erase(h) == 0) return fail(ERROR_INVALID_HANDLE); - } - h->closed.store(true); - release(h); // the handle's own reference; HANDLE_CLOSING follows when nothing else holds it - return TRUE; -} - -BOOL WINAPI crack_url(LPCWSTR url, DWORD length, DWORD flags, LPURL_COMPONENTS components) { - // Parsing only: the host's, loaded on first use so the runtime does not depend on winhttp.dll otherwise. - using CrackUrlFn = BOOL(WINAPI*)(LPCWSTR, DWORD, DWORD, LPURL_COMPONENTS); - static CrackUrlFn host = [] { - const HMODULE m = LoadLibraryExW(L"winhttp.dll", nullptr, LOAD_LIBRARY_SEARCH_SYSTEM32); - return m ? reinterpret_cast(GetProcAddress(m, "WinHttpCrackUrl")) : nullptr; - }(); - if (!host) return fail(ERROR_PROC_NOT_FOUND); - return host(url, length, flags, components); -} - -} // namespace rt::winhttp - -namespace { -using namespace rt::winhttp; -} // namespace - -SHIM_TABLE(winhttp_offline, - {"winhttp.dll", "WinHttpOpen", reinterpret_cast(&open_session)}, - {"winhttp.dll", "WinHttpConnect", reinterpret_cast(&open_connection)}, - {"winhttp.dll", "WinHttpOpenRequest", reinterpret_cast(&open_request)}, - {"winhttp.dll", "WinHttpSendRequest", reinterpret_cast(&send_request)}, - {"winhttp.dll", "WinHttpReceiveResponse", reinterpret_cast(&receive_response)}, - {"winhttp.dll", "WinHttpQueryDataAvailable", reinterpret_cast(&query_data_available)}, - {"winhttp.dll", "WinHttpReadData", reinterpret_cast(&read_data)}, - {"winhttp.dll", "WinHttpWriteData", reinterpret_cast(&write_data)}, - {"winhttp.dll", "WinHttpQueryHeaders", reinterpret_cast(&query_headers)}, - {"winhttp.dll", "WinHttpAddRequestHeaders", reinterpret_cast(&add_request_headers)}, - {"winhttp.dll", "WinHttpSetTimeouts", reinterpret_cast(&set_timeouts)}, - {"winhttp.dll", "WinHttpSetOption", reinterpret_cast(&set_option)}, - {"winhttp.dll", "WinHttpQueryOption", reinterpret_cast(&query_option)}, - {"winhttp.dll", "WinHttpSetStatusCallback", reinterpret_cast(&set_status_callback)}, - {"winhttp.dll", "WinHttpCloseHandle", reinterpret_cast(&close_handle)}, - {"winhttp.dll", "WinHttpCrackUrl", reinterpret_cast(&crack_url)}, -); diff --git a/runtime/shims/xapu_chad.cpp b/runtime/shims/xapu_chad.cpp deleted file mode 100644 index 35bda2b72..000000000 --- a/runtime/shims/xapu_chad.cpp +++ /dev/null @@ -1,216 +0,0 @@ -// xapu.dll and chad.dll: the console's audio processing unit (APU) and audio DSP command queues. No PC has either, -// so these give the title connections whose calls succeed, a zeroed shared buffer, a result for each stream open and -// close, and zeroed DSP status: the audio the APU would render stays silent, and nothing the title submits is processed. -// -// Read from the executable's call sites (counts in docs/runtime_imports.md), statically, never run: -// XApuConnect(block24*, out16*, handle*) 1 site; success is SUCCEEDED(hr). The first qword of the 16-byte -// output is read later as the base of a CPU-visible buffer: per-stream -// input at base + slot * 0x280 and output at base + 0x14000 + -// slot * 0x1E00. The first argument is a 24-byte global of the title -// that other title code also addresses; whether it is an input or an -// output is not known, so it is left untouched. -// XApuEnqueueCommand(handle, cmd*, 0) 4 sites; the return value is never read. cmd's first dword is a type -// (1, 2 and 3 seen), the second a stream slot. -// XApuGetResultCount(handle, 0) 1 site; 0 skips the loop that dequeues. -// XApuDequeueResult(handle, out*) 1 site, called count times into a zeroed 0x50-byte local; a negative -// HRESULT skips that result. The loop reads a type at +0, a stream slot -// at +4 and a dword at +0x34. Its per-slot state machine takes a type 1 -// result as "opened" and returns the slot to the title's free list only -// on a type 2 result, after the title enqueued a type 2 command. -// XApuDisconnect(handle, 0x20) 1 site; the return value is never read. The constant second -// argument is not declared here: nothing reads it. -// XDspConnectWithMaximumStreamLimit(buffer, u32, u32, 0x80, 1, handle*) 1 site; success is a return of 0. The -// buffer comes from the title's XMemAlloc and stays the title's. -// XDspActivate(handle, desc*, out*, out*) 1 site; success is a return of 0, else the caller returns -1. The two -// outputs are fields of the caller's object. The title later reads -// dwords at +4 and +0xc through one of them with no null check, and -// passes the other to XDspSubmitCommand. -// XDspSubmitCommand(stream, cmd*, id*) 1 site; success is a return of 0. The title zeroes *id before the call -// and afterwards waits until the status dword at +0xc is 0 and the one -// at +4 equals *id. -// XDspDeactivate, XDspDisconnect 1 site each, tail calls: the caller returns what they return. -// -// HYPOTHESIS: the shared buffer is 0x14000 + 128 * 0x1E00 bytes. 128 slots is what fits 0x14000 at the 0x280 input -// stride, and the DSP connect passes 0x80 as its stream limit; no call site shows a bound. The 16-byte output is -// written as {base, size}; only the base is measured. -// HYPOTHESIS: a type 1 (open) or type 2 (close) command produces one result of the same type for the same slot; the -// title's state machine fits that, the console is not measured. Without the close result the title's 256 stream ids -// run out. Only the two dwords are written; other command types are accepted with S_OK and produce no result. -// HYPOTHESIS: XDspActivate's outputs point at zeroed memory owned by the connection. XDspSubmitCommand leaves *id at -// the title's 0, so the zeroed status reads as "command 0 done, no error" and the title does not wait. -#include -#include - -#include -#include -#include -#include -#include -#include -#include - -#include "shims.h" -#include "startup_trace.h" - -namespace { - -constexpr size_t kApuBufferSize = 0x14000 + 128 * 0x1E00; - -// shortcut: results past this cap are dropped (each leaks one stream id); raise it if a title that never dequeues -// must still work. -constexpr size_t kMaxResults = 4096; - -struct ApuResult { - uint32_t type; - uint32_t slot; -}; - -struct ApuConnection { - void* buffer; - std::mutex mutex; - std::deque results; -}; - -struct DspConnection { - uint8_t status[256]; - uint8_t stream[256]; -}; - -// gta6rt --trace FILE: the first call of each function and the first XApuEnqueueCommand of each command type, with -// the caller, so the first boot shows what the title sends without a line per call. -void note(const char* api, uint64_t value, const void* caller) { - if (!rt::startup_trace::enabled()) return; - static std::mutex mutex; - static std::set> seen; - { - const std::lock_guard lock(mutex); - if (!seen.insert({api, value}).second) return; - } - rt::startup_trace::event( - "audio_queue", std::string("\"api\":") + rt::startup_trace::quote(api) + - ",\"value\":" + rt::startup_trace::quote(rt::startup_trace::hex(value)) + ",\"caller\":" + - rt::startup_trace::quote(rt::startup_trace::where(reinterpret_cast(caller)))); -} - -HRESULT __stdcall XApuConnect(void* block24, void* out16, void** handle) { - note("XApuConnect", 0, _ReturnAddress()); - if (!handle) return E_INVALIDARG; - *handle = nullptr; - void* buffer = VirtualAlloc(nullptr, kApuBufferSize, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE); // zeroed - if (!buffer) return E_OUTOFMEMORY; - auto* c = new (std::nothrow) ApuConnection; // a throwing new would unwind into the title - if (!c) { - VirtualFree(buffer, 0, MEM_RELEASE); - return E_OUTOFMEMORY; - } - c->buffer = buffer; - *handle = c; - (void)block24; - if (out16) { - const uint64_t info[2] = {reinterpret_cast(buffer), kApuBufferSize}; - std::memcpy(out16, info, sizeof info); - } - return S_OK; -} - -HRESULT __stdcall XApuDisconnect(void* handle) { - note("XApuDisconnect", 0, _ReturnAddress()); - auto* c = static_cast(handle); - if (!c) return E_INVALIDARG; - VirtualFree(c->buffer, 0, MEM_RELEASE); - delete c; - return S_OK; -} - -HRESULT __stdcall XApuEnqueueCommand(void* handle, const uint32_t* command, uint64_t flags) { - note("XApuEnqueueCommand", command ? command[0] : ~0ull, _ReturnAddress()); - (void)flags; - auto* c = static_cast(handle); - if (!c || !command) return E_INVALIDARG; - if (command[0] == 1 || command[0] == 2) { - try { - const std::lock_guard lock(c->mutex); - if (c->results.size() < kMaxResults) c->results.push_back({command[0], command[1]}); - } catch (...) { // out of memory: the result is lost, nothing may unwind into the title - } - } - return S_OK; -} - -uint32_t __stdcall XApuGetResultCount(void* handle, uint64_t flags) { - note("XApuGetResultCount", 0, _ReturnAddress()); - (void)flags; - auto* c = static_cast(handle); - if (!c) return 0; - const std::lock_guard lock(c->mutex); - return static_cast(c->results.size()); -} - -HRESULT __stdcall XApuDequeueResult(void* handle, void* result) { - note("XApuDequeueResult", 0, _ReturnAddress()); - auto* c = static_cast(handle); - if (!c || !result) return E_INVALIDARG; - const std::lock_guard lock(c->mutex); - if (c->results.empty()) return E_FAIL; - std::memcpy(result, &c->results.front(), sizeof(ApuResult)); // the rest stays as the caller zeroed it - c->results.pop_front(); - return S_OK; -} - -HRESULT __stdcall XDspConnectWithMaximumStreamLimit(void* buffer, uint32_t a, uint32_t b, uint32_t max_streams, - uint32_t flags, void** handle) { - note("XDspConnectWithMaximumStreamLimit", max_streams, _ReturnAddress()); - (void)buffer; - (void)a; - (void)b; - (void)flags; - if (!handle) return E_INVALIDARG; - *handle = new (std::nothrow) DspConnection{}; - return *handle ? S_OK : E_OUTOFMEMORY; -} - -HRESULT __stdcall XDspDisconnect(void* handle) { - note("XDspDisconnect", 0, _ReturnAddress()); - delete static_cast(handle); - return S_OK; -} - -HRESULT __stdcall XDspActivate(void* handle, const void* description, void** status, void** stream) { - note("XDspActivate", 0, _ReturnAddress()); - (void)description; - auto* c = static_cast(handle); - if (!c) return E_INVALIDARG; - if (status) *status = c->status; - if (stream) *stream = c->stream; - return S_OK; -} - -HRESULT __stdcall XDspDeactivate(void* handle, uint64_t, uint64_t, uint64_t) { - note("XDspDeactivate", 0, _ReturnAddress()); - (void)handle; - return S_OK; -} - -// *id stays the 0 the title wrote, which the zeroed status block already reports as done. -HRESULT __stdcall XDspSubmitCommand(void*, void*, uint32_t*) { - note("XDspSubmitCommand", 0, _ReturnAddress()); - return S_OK; -} - -} // namespace - -SHIM_TABLE(xapu, - {"xapu.dll", "XApuConnect", reinterpret_cast(&XApuConnect)}, - {"xapu.dll", "XApuDequeueResult", reinterpret_cast(&XApuDequeueResult)}, - {"xapu.dll", "XApuDisconnect", reinterpret_cast(&XApuDisconnect)}, - {"xapu.dll", "XApuEnqueueCommand", reinterpret_cast(&XApuEnqueueCommand)}, - {"xapu.dll", "XApuGetResultCount", reinterpret_cast(&XApuGetResultCount)}, -); - -SHIM_TABLE(chad, - {"chad.dll", "XDspActivate", reinterpret_cast(&XDspActivate)}, - {"chad.dll", "XDspConnectWithMaximumStreamLimit", reinterpret_cast(&XDspConnectWithMaximumStreamLimit)}, - {"chad.dll", "XDspDeactivate", reinterpret_cast(&XDspDeactivate)}, - {"chad.dll", "XDspDisconnect", reinterpret_cast(&XDspDisconnect)}, - {"chad.dll", "XDspSubmitCommand", reinterpret_cast(&XDspSubmitCommand)}, -); diff --git a/runtime/shims/xbox_present.cpp b/runtime/shims/xbox_present.cpp deleted file mode 100644 index c3653cdb5..000000000 --- a/runtime/shims/xbox_present.cpp +++ /dev/null @@ -1,314 +0,0 @@ -#include "xbox_present.h" - -#include "d3d12_trace.h" - -#include "../core/config.h" -#include "../core/log.h" -#include "../src/vulkan_present.h" - -#include -#include -#include -#include -#include -#include - -namespace rt::d3d12 { - -namespace { - -using leonida::FramePacer; -namespace hr = leonida::pacer_hr; - -HRESULT from_pacer(std::int32_t value) { return HRESULT(value); } - -// The fixed text of a log line is printed once per object. -void log_once(bool& done, const char* text) { - if (done) return; - done = true; - RT_LOG_WARN("present: %s\n", text); -} - -} // namespace - -XboxPresentation::XboxPresentation(std::unique_ptr presenter, leonida::FrameClock* clock) - : presenter_(std::move(presenter)), - own_clock_(clock ? nullptr : std::make_unique()), - pacer_(clock ? *clock : *own_clock_) { - // A present waiting for a swapchain image gives up once SuspendX has been called. - presenter_->set_abort([this] { return pacer_.suspended(); }); - // present.sdr_eotf (LEONIDA_SDR_EOTF): gamma22 (or 2.2, any case) decodes SDR with a pure power of 2.2 instead - // of piecewise sRGB; "srgb" or unset keeps the default; anything else (also a value of 32 characters or more, - // the size of the buffer the variable was read into before it moved to the table) is logged once and ignored. - const std::string eotf = rt::config::get("present.sdr_eotf").text; - if (eotf.size() >= 32) { - RT_LOG_WARN("present: LEONIDA_SDR_EOTF is too long to be srgb, gamma22 or 2.2: piecewise sRGB " - "used\n"); - } else if (!_stricmp(eotf.c_str(), "gamma22") || !_stricmp(eotf.c_str(), "2.2")) { - sdr_eotf_ = leonida::PresentPlanes::SdrEotf::gamma22; - } else if (_stricmp(eotf.c_str(), "srgb") != 0) { - RT_LOG_WARN("present: LEONIDA_SDR_EOTF=%s is not srgb, gamma22 or 2.2: piecewise sRGB used\n", - eotf.c_str()); - } - // LEONIDA_PRESENT_UNCAP (any non-empty value other than "0") takes the frame-rate cap off: a WaitFrameEventX - // hands a token out at once instead of at the next interval origin, and presents go unsynced (MAILBOX or - // IMMEDIATE, not FIFO), so the frame rate is whatever the title renders. Registration and suspension still - // apply, so the title keeps its call sequence. - if (const std::string uncap = rt::config::get("present.uncap").text; !uncap.empty() && uncap != "0") { - pacer_.set_uncapped(true); - RT_LOG_INFO("present: LEONIDA_PRESENT_UNCAP is set: frame events return at once and " - "presents do not wait for vblank\n"); - } - display_white_thread_ = std::thread([this] { display_white_worker(); }); -} - -XboxPresentation::~XboxPresentation() { - { - std::lock_guard lock(worker_mutex_); - worker_stop_ = true; - } - worker_wake_.notify_all(); - display_white_thread_.join(); - presenter_->set_abort(nullptr); -} - -// Windows' SDR white level costs a QueryDisplayConfig and two DisplayConfigGetDeviceInfo calls (measured in -// xbox_present_test, docs section 4.5): too much for the present path, which would hitch once a second and feed the pacer. -// So it is read here, about once a second while an HDR10 swapchain is in use, and PresentX reads the cached value. -void XboxPresentation::display_white_worker() { - std::unique_lock lock(worker_mutex_); - while (!worker_stop_) { - if (white_wanted_.load()) { - lock.unlock(); - const float nits = presenter_->display_sdr_white_nits(); - if (nits > 0.0f) display_white_ = nits; // a failed query keeps the last good value - lock.lock(); - } - worker_wake_.wait_for(lock, std::chrono::seconds(1), [this] { return worker_stop_; }); - } -} - -float XboxPresentation::effective_sdr_white_nits() { - if (sdr_white_override_ > 0.0f) return sdr_white_override_; - if (!presenter_->hdr_active()) return 203.0f; // the Windows setting belongs to HDR mode - if (!white_wanted_.exchange(true)) { // first HDR10 present: have it read now - std::lock_guard lock(worker_mutex_); - worker_wake_.notify_all(); - } - const float cached = display_white_; - return cached > 0.0f ? cached : 203.0f; -} - -HRESULT XboxPresentation::SetFrameIntervalX(IUnknown*, UINT interval_period_us, UINT latency, UINT flags) { - return from_pacer(pacer_.set_frame_interval(interval_period_us, latency, flags)); -} - -HRESULT XboxPresentation::ScheduleFrameEventX(UINT event, UINT offset_us, UINT flags) { - return from_pacer(pacer_.schedule_frame_event(event, offset_us, flags)); -} - -HRESULT XboxPresentation::WaitFrameEventX(UINT event, DWORD timeout_ms, UINT flags, std::uint64_t* token) { - return from_pacer(pacer_.wait_frame_event(event, timeout_ms, flags, token)); -} - -HRESULT XboxPresentation::GetFrameStatisticsX(std::uint64_t token, UINT type_mask, UINT* count, - leonida::FrameStatistic* out) { - return from_pacer(pacer_.get_frame_statistics(token, type_mask, count, out)); -} - -HRESULT XboxPresentation::PresentX(UINT plane_count, const XboxPresentPlaneParameters* planes, - const XboxPresentParameters* params) { - // One trace line per present, whatever path the call takes out of present_x: the queue proxy's PresentX slot is - // past the PC chain, so nothing else records it, and a frame loop's presents could not be counted from a trace. - return d3d12_trace::result("XboxPresentation::PresentX", present_x(plane_count, planes, params)); -} - -HRESULT XboxPresentation::present_x(UINT plane_count, const XboxPresentPlaneParameters* planes, - const XboxPresentParameters* params) { - std::lock_guard serialise(present_mutex_); - if (plane_count > 2 || (plane_count && !planes)) return E_INVALIDARG; - if (pacer_.suspended()) return from_pacer(hr::invalid_state); - // A zero, negative or NaN threshold never tears; an uncapped frame is never late for anything either. - const float threshold = params ? params->ImmediateThresholdPercent : 0.0f; - const bool wants_tear = threshold > 0.0f && !pacer_.uncapped(); - if (wants_tear && !presenter_->tear_supported()) - log_once(logged_threshold_, - "ImmediateThresholdPercent has no effect on this swapchain (tearing disabled by LEONIDA_PRESENT_NO_TEAR, " - "no VK_KHR/EXT_swapchain_maintenance1, or no IMMEDIATE/FIFO_RELAXED mode the surface can switch to): " - "a late frame waits for the next vblank"); - - // Unpaced (no interval registered, or uncapped): do not hold the queue for vblanks. - const UINT sync_interval = pacer_.registered() && !pacer_.uncapped() ? 1 : 0; - - if (plane_count == 0) { - const HRESULT result = presenter_->present_blank(sync_interval); - if (SUCCEEDED(result)) { - pacer_.note_untokened_present(); - ++presents_; - } - return result; - } - - // All planes carry the token of one frame. - const std::uint64_t token = planes[0].Token; - for (UINT i = 0; i < plane_count; ++i) { - const XboxPresentPlaneParameters& plane = planes[i]; - if (plane.Token != token || plane.ResourceCount == 0 || !plane.ppResources || !plane.ppResources[0]) - return E_INVALIDARG; - // Both paths read ppResources[0] only: a plane with several resources would silently lose the others and could show - // the wrong frame, so it is refused (before anything is presented) until it is modelled. What the console does - // with ResourceCount above 1 (views? stereo?) is unmeasured. - if (plane.ResourceCount != 1) { - log_once(logged_resource_count_, "PresentX plane with ResourceCount other than 1: not implemented, refused"); - return DXGI_ERROR_UNSUPPORTED; - } - } - // Only a token that was never handed out is refused. Null, stale and repeated tokens are presented anyway (what the - // console does with them is unmeasured, and a title that does it must not freeze); each kind is logged once. - FramePacer::TokenIssue issue{}; - if (const std::int32_t checked = pacer_.check_present_token(token, &issue); checked != hr::ok) - return from_pacer(checked); - switch (issue) { - case FramePacer::TokenIssue::null_token: - log_once(logged_null_token_, "PresentX with the null token: presented anyway (real behaviour unmeasured)"); - break; - case FramePacer::TokenIssue::stale: - log_once(logged_stale_token_, "PresentX with a token older than the last presented: presented anyway"); - break; - case FramePacer::TokenIssue::repeated: - log_once(logged_repeated_token_, "PresentX with the token of the last present again: presented anyway"); - break; - case FramePacer::TokenIssue::none: - break; - } - - // What each plane asks for. Colour spaces other than HDR10 are composed as the SDR default (logged once). - const auto is_hdr10 = [&](const XboxPresentPlaneParameters& p) { - if (p.ColorSpace != xbox_color_space_g22_p709 && p.ColorSpace != xbox_color_space_g2084_p2020) - log_once(logged_color_space_, "a present plane's DXGI colour space is neither G22/P709 nor G2084/P2020: composed as SDR G22/P709"); - return p.ColorSpace == xbox_color_space_g2084_p2020; - }; - // The extra fields are unmeasured, so they are read defensively: a placement that is not a sane sub-rectangle of the output - // (also NaN) counts as none, an unknown filter as the default, unknown flag bits are ignored, extended descriptors are - // not read; each is logged once and the frame is shown anyway (a title must not freeze on a field we misread). - const auto placement = [&](const XboxPresentPlaneParameters& p) -> const XboxViewRect* { - const XboxViewRect* r = p.pDestPlacementBase; - if (!r) return nullptr; - if (!(r->left >= 0.0f && r->left < r->right && r->right <= 1.0f && r->top >= 0.0f && r->top < r->bottom && - r->bottom <= 1.0f)) { - log_once(logged_extras_, "a present plane's pDestPlacementBase is not a sub-rectangle of 0..1: ignored (whole output)"); - return nullptr; - } - return (r->left == 0.0f && r->top == 0.0f && r->right == 1.0f && r->bottom == 1.0f) ? nullptr : r; - }; - const auto filter_of = [&](const XboxPresentPlaneParameters& p) { - if (p.ScaleFilter == xbox_scale_filter_point || p.ScaleFilter == xbox_scale_filter_linear) return p.ScaleFilter; - if (p.ScaleFilter != xbox_scale_filter_default) - log_once(logged_extras_, "a present plane's ScaleFilter is not a known value: default filter"); - return int(xbox_scale_filter_default); - }; - for (UINT i = 0; i < plane_count; ++i) - if (planes[i].ExtendedDescCount) - log_once(logged_extras_, "a present plane has extended descriptors: ignored"); - const bool hdr0 = is_hdr10(planes[0]); - // Plane 1 is composed over plane 0 only when flagged an overlay (hypothesis). Otherwise it is not shown, as before: in - // the public HDR sample it is the GameDVR copy of the frame, and blending a plane we cannot tell apart from it risks - // drawing the frame twice with an alpha that was never meant to be blended. - const bool overlay = plane_count == 2 && (planes[1].Flags & xbox_plane_flag_overlay) != 0; - if (plane_count == 2 && !overlay) - log_once(logged_planes_, "PresentX with 2 planes and no overlay flag on plane 1: only plane 0 is shown (plane 1 is taken " - "as the GameDVR copy of the frame)"); - const bool compose = hdr0 || placement(planes[0]) || filter_of(planes[0]) != xbox_scale_filter_default || overlay; - - if (compose) { - // Every shown plane: a 2D texture, a source rectangle inside it, a placement inside the output. - leonida::PresentPlanes composed; - composed.count = overlay ? 2 : 1; - composed.sdr_white_nits = effective_sdr_white_nits(); - composed.sdr_eotf = sdr_eotf_; - composed.hdr_peak_nits = hdr_peak_nits_; - for (UINT i = 0; i < composed.count; ++i) { - const XboxPresentPlaneParameters& p = planes[i]; - ID3D12Resource* source = p.ppResources[0]; - const D3D12_RESOURCE_DESC source_desc = source->GetDesc(); - if (source_desc.Dimension != D3D12_RESOURCE_DIMENSION_TEXTURE2D) return E_INVALIDARG; - const D3D12_RECT* source_rect = p.pSrcViewRects; - if (source_rect && (source_rect->left < 0 || source_rect->top < 0 || source_rect->left >= source_rect->right || - source_rect->top >= source_rect->bottom || UINT64(source_rect->right) > source_desc.Width || - UINT(source_rect->bottom) > source_desc.Height)) - return E_INVALIDARG; - const XboxViewRect* place = placement(p); - leonida::PresentPlane& out = composed.plane[i]; - out.source = resource_id(source); - if (source_rect) { - out.source_rect = {source_rect->left, source_rect->top, source_rect->right, source_rect->bottom}; - out.has_source_rect = true; - } - if (place) { - out.dest[0] = place->left; - out.dest[1] = place->top; - out.dest[2] = place->right; - out.dest[3] = place->bottom; - } - out.point_filter = filter_of(p) == xbox_scale_filter_point; - out.hdr10 = is_hdr10(p); - out.straight_alpha = (p.Flags & xbox_plane_flag_straight_alpha) != 0; - } - bool tear = false; - if (wants_tear && sync_interval > 0 && presenter_->tear_supported()) { - const FramePacer::PresentTiming timing = pacer_.present_timing(token); - tear = leonida::decide_present_sync(timing.late_us, timing.period_us, threshold) == leonida::PresentSync::immediate; - } - const HRESULT result = presenter_->present_planes(composed, sync_interval, tear); - if (FAILED(result)) return pacer_.suspended() ? from_pacer(hr::invalid_state) : result; - pacer_.commit_present_token(token, plane_count, - tear && presenter_->last_present_tore() ? leonida::PresentSync::immediate - : leonida::PresentSync::vblank); - ++presents_; - return S_OK; - } - - const XboxPresentPlaneParameters& plane = planes[0]; - ID3D12Resource* resource = plane.ppResources[0]; - const D3D12_RESOURCE_DESC desc = resource->GetDesc(); - if (desc.Dimension != D3D12_RESOURCE_DIMENSION_TEXTURE2D) return E_INVALIDARG; - D3D12_HEAP_PROPERTIES heap{}; - D3D12_HEAP_FLAGS heap_flags = D3D12_HEAP_FLAG_NONE; - if (SUCCEEDED(resource->GetHeapProperties(&heap, &heap_flags)) && !(heap_flags & D3D12_HEAP_FLAG_ALLOW_DISPLAY)) - log_once(logged_display_, "a present plane's resource was created without D3D12_HEAP_FLAG_ALLOW_DISPLAY; presenting it anyway"); - - const D3D12_RECT* rect = plane.pSrcViewRects; - if (rect && (rect->left < 0 || rect->top < 0 || rect->left >= rect->right || rect->top >= rect->bottom || - UINT64(rect->right) > desc.Width || UINT(rect->bottom) > desc.Height)) - return E_INVALIDARG; - - // How late the frame is, now that everything that can refuse it has: past the vblank it was due at, by what part of - // the interval the scan has moved on. The presenter says whether it really queued it as a tear. - FramePacer::PresentTiming timing; - bool tear = false; - if (wants_tear && sync_interval > 0 && presenter_->tear_supported()) { - timing = pacer_.present_timing(token); - tear = leonida::decide_present_sync(timing.late_us, timing.period_us, threshold) == leonida::PresentSync::immediate; - } - const HRESULT result = presenter_->present(resource, sync_interval, rect, tear); - if (FAILED(result)) return pacer_.suspended() ? from_pacer(hr::invalid_state) : result; - pacer_.commit_present_token(token, plane_count, - tear && presenter_->last_present_tore() ? leonida::PresentSync::immediate - : leonida::PresentSync::vblank); - ++presents_; - return S_OK; -} - -// SuspendX and ResumeX do not take present_mutex_: a PresentX stuck waiting for a swapchain image must not hold them -// (it polls the suspended state and gives up). A present that was already past that point finishes normally. -HRESULT XboxPresentation::SuspendX(UINT) { - pacer_.suspend(); - return S_OK; -} - -HRESULT XboxPresentation::ResumeX() { - pacer_.resume(); - return S_OK; -} - -} // namespace rt::d3d12 diff --git a/runtime/shims/xbox_present.h b/runtime/shims/xbox_present.h deleted file mode 100644 index 60a317bee..000000000 --- a/runtime/shims/xbox_present.h +++ /dev/null @@ -1,203 +0,0 @@ -#pragma once - -// The Xbox presentation core (docs/d3d12_vulkan.md section 4.5): the frame events and PresentX of a GDKX title, which -// presents without a DXGI swapchain. FramePacer (src/frame_pacer.h) does the timing and the token bookkeeping; -// WindowPresenter (d3d12_com.h, over leonida::VulkanPresenter) puts the pixels in a window. This class is the -// glue, and the surface the Xbox device and queue proxy will forward to. -// -// WHAT IS KNOWN: the public GDKX samples give the call order and the argument counts; public code that is not -// Microsoft documentation gives most of the slots and the x64 layouts (docs/d3d12_xs_surface.md 7.1): -// - ebiten (Apache-2.0) mirrors the GDK structs in Go: D3D12XBOX_PRESENT_PLANE_PARAMETERS is 0x48 bytes on x64, -// D3D12XBOX_PRESENT_PARAMETERS 0x20 bytes, and D3D12XBOX_FRAME_PIPELINE_TOKEN is uint64. -// - XCL (GPL-2.0-only, facts only) measured the frame calls on device slots 78-81 and PresentX on queue slot 30 -// (older runtime layout: XDefiant, Minecraft, Fortnite) or 32 (newer: Unicorn Overlord). -// WHAT IS OURS: the constant values, the HRESULT choices and the ScaleFilter/plane-flag values; the real enum -// values are still unmeasured. The SuspendX/ResumeX slots are not in any public source. -// -// Slots (0-based, QueryInterface = 0) before the proxy can forward: -// ID3D12Device (Xbox): SetFrameIntervalX (output, interval, latency, flags) 78 -// ScheduleFrameEventX (event, offset, reserved pointer, flags) 79 -// WaitFrameEventX (event, timeout ms, reserved pointer, flags, &token) 80 -// GetFrameStatisticsX (token, type mask, &count, array) 81 -// ID3D12CommandQueue (Xbox): PresentX (plane count, planes, params) 30 (older) / 32 (newer) -// SuspendX (flags) slot unknown -// ResumeX () slot unknown -// The public numbers are measurements of other titles' runtimes, not of this game. The runtime version moves -// PresentX, so neither value may be assumed; trace the game's slots. -// The queue-side calls do not look at the queue: the Vulkan device has one VkQueue behind every D3D12 queue, and -// the present is submitted after the work already executed on it. - -#include "d3d12_com.h" -#include "../src/frame_pacer.h" -#include "../src/vulkan_present.h" - -#include -#include -#include -#include -#include -#include - -namespace rt::d3d12 { - -// Provisional (ours): D3D12XBOX_FRAME_INTERVAL_* as periods in microseconds. -inline constexpr std::uint32_t xbox_frame_interval_30hz_us = 33333; -inline constexpr std::uint32_t xbox_frame_interval_60hz_us = 16667; -inline constexpr std::uint32_t xbox_frame_interval_120hz_us = 8333; - -// D3D12XBOX_PRESENT_PLANE_PARAMETERS. The names and the x64 layout are confirmed by the public ebiten Go binding -// (Apache-2.0, internal/graphicsdriver/directx/d3d12_windows.go, _D3D12XBOX_PRESENT_PLANE_PARAMETERS) and by XCL's -// reads of the first three fields: 0x48 bytes, Token @0x00, ResourceCount @0x08, ppResources @0x10, pSrcViewRects -// @0x18, pDestPlacementBase @0x20, ColorSpace @0x28, ScaleFilter @0x2C, ExtendedDescCount @0x30, pExtendedDescs -// @0x38, Flags @0x40. The enum values and flag bits remain unmeasured; the values below are placeholders that make -// the composition (section 4.5) testable. -// -// Zero everything is the default and means "as before": the whole output, bilinear when scaling, SDR, plane 1 -// premultiplied and not composed. -struct XboxViewRect { // D3D12XBOX_VIEW_RECT: four floats; as fractions 0..1 of the output (hypothesis, section 4.5) - float left, top, right, bottom; -}; -// DXGI_COLOR_SPACE_TYPE values (documented DXGI numbers). Only these two are composed; any other is treated as the first. -inline constexpr int xbox_color_space_g22_p709 = 0; // DXGI_COLOR_SPACE_RGB_FULL_G22_NONE_P709: SDR -inline constexpr int xbox_color_space_g2084_p2020 = 12; // DXGI_COLOR_SPACE_RGB_FULL_G2084_NONE_P2020: HDR10 -// Provisional (ours): ScaleFilter and Flags. -inline constexpr int xbox_scale_filter_default = 0; // bilinear (point when not scaled makes no difference) -inline constexpr int xbox_scale_filter_point = 1; -inline constexpr int xbox_scale_filter_linear = 2; -// Plane 1 is composed over plane 0 as an overlay only with this flag (hypothesis: whether the console blends a second plane -// at all is unmeasured; the public HDR sample's plane 1 is the GameDVR copy of the frame, not shown, so without the flag -// plane 1 is not composed, as before). -inline constexpr UINT xbox_plane_flag_overlay = 1; -inline constexpr UINT xbox_plane_flag_straight_alpha = 2; // plane 1's colour is not premultiplied by its alpha - -struct XboxPresentPlaneParameters { - // Field order, types and x64 offsets: the public ebiten binding above; XCL reads Token, ResourceCount and - // ppResources at the same offsets. This is the console's layout on x64. - std::uint64_t Token; // from WaitFrameEventX; 64-bit storage confirmed, 0 = ..._NULL - UINT ResourceCount; // 1 in the samples - ID3D12Resource* const* ppResources; // ResourceCount committed resources with ALLOW_DISPLAY, in PRESENT - const D3D12_RECT* pSrcViewRects; // null, or one rectangle per resource (the HDR sample sets it) - const XboxViewRect* pDestPlacementBase; // null: the whole output - int ColorSpace; // a DXGI_COLOR_SPACE_TYPE (see above) - int ScaleFilter; // xbox_scale_filter_*; anything unknown is the default - UINT ExtendedDescCount; // not used (logged once when non-zero) - const void* pExtendedDescs; - UINT Flags; // xbox_plane_flag_*; unknown bits are ignored -}; - -// D3D12XBOX_PRESENT_PARAMETERS. The console's object is 0x20 bytes on x64 (ebiten): ImmediateThresholdPercent @0x00, -// ViewCount @0x04, ExtendedDescCount @0x08, pExtendedDescs @0x10, Flags @0x18. This struct is the first 4 bytes; -// it is only read through a pointer, so never size a copy by sizeof(XboxPresentParameters). -struct XboxPresentParameters { - // 0 (the default): a frame that missed its vblank waits for the next one. Above 0: a frame that missed it is shown - // at once, mid-scan, when the scan is not further than this percentage down the screen (100: wherever it is). - // Needs VK_KHR/EXT_swapchain_maintenance1 and an IMMEDIATE or FIFO_RELAXED mode the swapchain can switch to; - // without them it is ignored (logged once). What late means: see FramePacer::present_timing. - float ImmediateThresholdPercent; -}; - -class XboxPresentation { -public: - // `clock` null: real time (a steady high-resolution timer). Tests pass a leonida::ManualFrameClock, which must - // outlive this object. `presenter` is what create_window_presenter returned. - explicit XboxPresentation(std::unique_ptr presenter, leonida::FrameClock* clock = nullptr); - ~XboxPresentation(); - XboxPresentation(const XboxPresentation&) = delete; - XboxPresentation& operator=(const XboxPresentation&) = delete; - - // Device side. `output` (an IDXGIOutput*, which the samples fetch from the device) is not used: there is one - // window. `interval_period_us` is the period of a frame interval, e.g. xbox_frame_interval_60hz_us; `latency` - // is the frames allowed in flight (the samples pass the buffer count minus 1, or 1). - HRESULT SetFrameIntervalX(IUnknown* output, UINT interval_period_us, UINT latency, UINT flags); - // Only the origin event (xbox_frame_event_origin) exists. `offset_us` delays it inside the frame. The pointer - // argument the samples pass as null is not modelled. - HRESULT ScheduleFrameEventX(UINT event, UINT offset_us, UINT flags); - // Blocks for the next origin and while the latency is used up. HRESULT_FROM_WIN32(WAIT_TIMEOUT) after `timeout_ms` - // (INFINITE waits for ever); `*token` is untouched then. E_INVALIDARG for a null token pointer or another event; - // HRESULT_FROM_WIN32(ERROR_INVALID_STATE) when nothing is registered (not yet, or since SuspendX). - // XCL's public implementation returns S_FALSE on a finite timeout and writes the token on timeout only with - // flag 2, and E_INVALIDARG when the event is not scheduled; the WAIT_TIMEOUT and ERROR_INVALID_STATE here are - // this layer's choices and known divergences (docs/d3d12_xs_surface.md 7.1). - HRESULT WaitFrameEventX(UINT event, DWORD timeout_ms, UINT flags, std::uint64_t* token); - // See FramePacer::get_frame_statistics: S_FALSE and count 0 when nothing is available. - HRESULT GetFrameStatisticsX(std::uint64_t token, UINT type_mask, UINT* count, leonida::FrameStatistic* out); - - // Queue side. - // 0 planes: a black frame (what a title does before it releases its resources); no token is looked at. - // 1 plane: plane 0's first resource, which must be a single-sample 2D colour texture in the PRESENT state, - // is blitted to the window (format conversion by the blit; an sRGB format gets an sRGB swapchain), - // limited to pSrcViewRects[0] when that is set. This is the whole behaviour while the plane asks for - // nothing else (SDR colour space, whole output, default filter). - // Composed: a plane with pDestPlacementBase, a point or linear ScaleFilter, or the HDR10 colour space (and any - // second plane that is an overlay) is composed by a compute pass (VulkanPresenter::present_planes): plane 0 - // from its source rectangle to its destination placement, plane 1 alpha-blended over it, colour spaces - // converted to the swapchain's (HDR10 when the surface has it, else HDR10 is tone mapped to SDR). Needs sampled, - // single-sample, non-integer sources; others give DXGI_ERROR_UNSUPPORTED. - // 2 planes: the two share one token. Plane 1 is composed over plane 0 only when xbox_plane_flag_overlay is set on it - // (hypothesis); otherwise it is not shown (the GameDVR copy of the public HDR sample), logged once. - // Placement, ScaleFilter and Flags values that are not plausible are ignored and logged once, not refused. - // More than 2: E_INVALIDARG (the UMD limit, section 4.5). - // ResourceCount above 1 on any plane: DXGI_ERROR_UNSUPPORTED (logged once), nothing presented; only resource 0 is read. - // Token: the one from WaitFrameEventX. Real behaviour for a null, repeated or out-of-order token is unmeasured and a - // title must not freeze on it, so those are presented anyway and logged once per kind; only a token that was never - // handed out gives E_INVALIDARG (nothing presented). Skipping a token is fine. Sources the GPU cannot blit - // (multisampled, integer, block-compressed) give DXGI_ERROR_UNSUPPORTED and present nothing; resolving a - // multisampled plane into a temporary is not done. While suspended: HRESULT_FROM_WIN32(ERROR_INVALID_STATE), also - // for a present that was waiting for a swapchain image when SuspendX came. - // `params` may be null (threshold 0). ImmediateThresholdPercent: see XboxPresentParameters; a frame that was shown - // at once has its display statistic's percent_scanned set and is counted in immediate_presents(). - // With --trace-d3d12 every call writes one `[d3d12-trace] ... XboxPresentation::PresentX ` - // line (shims/d3d12_trace.h), so a run's presents can be counted and a refused one is visible. - HRESULT PresentX(UINT plane_count, const XboxPresentPlaneParameters* planes, const XboxPresentParameters* params); - // SuspendX drops the interval, the origin event and the frames in flight, and refuses presents. ResumeX allows - // presents again; SetFrameIntervalX and ScheduleFrameEventX must be called again before the next wait. - HRESULT SuspendX(UINT flags); - HRESULT ResumeX(); - - // What SDR white is in nits when SDR and HDR10 planes meet (docs section 4.5). `nits` > 0 overrides everything; 0 goes - // back to automatic: while the swapchain is HDR10, the SDR content brightness Windows has for the output the window - // is on (a background thread refreshes it once a second; PresentX only reads the cached value), else 203 (ITU-R - // BT.2408's reference white). Applies to the next PresentX. The setters may be called from any thread. - void set_sdr_white_nits(float nits) { sdr_white_override_ = nits > 0.0f ? nits : 0.0f; } - // How SDR planes are decoded and an SDR output is encoded: piecewise sRGB (default) or gamma 2.2. The environment - // variable LEONIDA_SDR_EOTF=gamma22 (or 2.2; any case; "srgb" is the default; other values are logged once and - // ignored) chooses when the object is made. - void set_sdr_eotf(leonida::PresentPlanes::SdrEotf eotf) { sdr_eotf_ = eotf; } - // Peak of HDR10 content in nits, the white point of the tone map onto an SDR output (default 1000; no metadata is read). - void set_hdr_peak_nits(float nits) { hdr_peak_nits_ = nits > 0.0f ? nits : 1000.0f; } - - leonida::FramePacer& pacer() { return pacer_; } - WindowPresenter& presenter() { return *presenter_; } - std::uint64_t presents() const { return presents_; } - // Frames shown mid-scan because of ImmediateThresholdPercent. - std::uint64_t immediate_presents() const { return pacer_.immediate_presents(); } - -private: - // PresentX without its `[d3d12-trace]` line. - HRESULT present_x(UINT plane_count, const XboxPresentPlaneParameters* planes, const XboxPresentParameters* params); - float effective_sdr_white_nits(); // override, else the cached Windows setting while HDR10, else 203 - void display_white_worker(); // refreshes display_white_ off the present path - std::unique_ptr presenter_; - std::unique_ptr own_clock_; - leonida::FramePacer pacer_; - std::mutex present_mutex_; // PresentX, SuspendX and ResumeX one at a time - std::atomic presents_{0}; - bool logged_planes_ = false, logged_threshold_ = false, logged_display_ = false, logged_color_space_ = false, - logged_extras_ = false, logged_resource_count_ = false; - std::atomic sdr_white_override_{0.0f}; // > 0: set_sdr_white_nits - std::atomic sdr_eotf_{leonida::PresentPlanes::SdrEotf::srgb}; - std::atomic hdr_peak_nits_{1000.0f}; - // The last good Windows SDR white level (nits, 0: none yet), refreshed by display_white_thread_ about once a second while - // an HDR10 swapchain is in use (white_wanted_); a failed query keeps the previous value. - std::atomic display_white_{0.0f}; - std::atomic white_wanted_{false}; - std::mutex worker_mutex_; - std::condition_variable worker_wake_; - bool worker_stop_ = false; - std::thread display_white_thread_; - bool logged_null_token_ = false, logged_stale_token_ = false, logged_repeated_token_ = false; -}; - -inline constexpr UINT xbox_frame_event_origin = leonida::frame_event_origin; - -} // namespace rt::d3d12 diff --git a/runtime/shims/xg_xs.cpp b/runtime/shims/xg_xs.cpp deleted file mode 100644 index b190d284a..000000000 --- a/runtime/shims/xg_xs.cpp +++ /dev/null @@ -1,96 +0,0 @@ -// xg_xs.dll: the console's texture layout library. The game executable (1.0.2.1) imports two functions from it. -// -// Measured from the call sites in the executable, read statically (shapes and checks only): -// HRESULT XGSuggestSwizzleMode(const desc*, 0, uint32_t* mode) -// 2 call sites, both in the game's helper that fills a texture description before XGCreateTextureComputer. The -// out pointer is a 32-bit field of that description, which the helper first sets to 0 and, when the mode is -// known, writes itself as 0x100 | mode. The HRESULT is only passed back up; no caller branches on it. -// HRESULT XGCreateTextureComputer(const desc*, computer** out) -// 4 call sites. Two test the HRESULT and take their failure path when it is negative; two ignore it and call -// through *out at once. On the computer the callers use vtable slot 1 after they are done (3 sites, read as -// Release; no site calls slot 0, read as AddRef, nor QueryInterface), slot 2 with one out pointer to a large -// stack structure (2 sites), slot 8 with six arguments in a loop over subresources (1 site) and slot 10 with -// seven arguments (1 site). No site reads the return value of slots 2, 8 or 10. -// -// The runtime has no model of the console's resource layout (runtime/src/gfx10_tiling.h covers two swizzle modes of -// one 2D level, without mips or the layout structure slot 2 fills), so nothing here computes a layout: -// - XGSuggestSwizzleMode returns E_NOTIMPL and writes nothing, so the field keeps the 0 the caller put there. -// - XGCreateTextureComputer returns E_NOTIMPL, but still stores a computer in *out. The two checking callers then -// fail cleanly; the two that do not check would otherwise call through a null pointer. COM says *out is null on -// failure; this breaks that on purpose, because the measured callers need it. -// - Slot 0 and slot 1 count nothing (the computer is one static object). Every other slot, up to kSlots, prints its -// index and caller once and returns E_NOTIMPL without writing its arguments, so a caller's own zero-filled outputs -// stay zero and a stack structure the caller did not fill stays as it was. -// Hypothesis, not measured: slots 0 and 1 being AddRef and Release; the meaning of slots 2, 8 and 10; that callers -// reach no slot above kSlots - 1 (the computer is also stored in an object at one site and may be called later). -#include -#include - -#include -#include -#include -#include -#include - -#include "../core/log.h" -#include "shims.h" - -namespace { - -constexpr HRESULT kNotImpl = static_cast(rt::shims::kENotImpl); -constexpr size_t kSlots = 32; - -// Prints once per entry point; `slot` is the vtable index for a computer method, or -1 for an export. -void warn_once(std::atomic& warned, const char* what, int slot, const void* caller) { - if (warned.exchange(true, std::memory_order_relaxed)) return; - char name[64]; - if (slot < 0) std::snprintf(name, sizeof(name), "%s", what); - else std::snprintf(name, sizeof(name), "%s%d", what, slot); - RT_LOG_WARN("xg_xs: %s: no console texture layout on the PC; E_NOTIMPL (caller %s, logged once)\n", - name, rt::shims::module_offset(reinterpret_cast(caller)).c_str()); -} - -ULONG __stdcall computer_add_ref(void*) { return 1; } -ULONG __stdcall computer_release(void*) { return 1; } - -template -HRESULT __stdcall computer_slot(void*) { - static std::atomic warned{false}; - warn_once(warned, "texture computer slot ", static_cast(Slot), _ReturnAddress()); - return kNotImpl; -} - -template -constexpr auto make_vtable(std::index_sequence) { - return std::array{ - (Slot == 0 ? reinterpret_cast(&computer_add_ref) - : Slot == 1 ? reinterpret_cast(&computer_release) - : reinterpret_cast(&computer_slot))...}; -} - -const auto kVtable = make_vtable(std::make_index_sequence{}); -struct Computer { - const void* const* vtable; -}; -Computer g_computer{kVtable.data()}; - -HRESULT __stdcall XGCreateTextureComputer(const void* /*desc*/, void** out) { - static std::atomic warned{false}; - warn_once(warned, "XGCreateTextureComputer", -1, _ReturnAddress()); - if (!out) return E_POINTER; - *out = &g_computer; // see the top of the file: two measured callers use *out without checking the HRESULT - return kNotImpl; -} - -HRESULT __stdcall XGSuggestSwizzleMode(const void* /*desc*/, uint32_t /*flags*/, uint32_t* /*mode*/) { - static std::atomic warned{false}; - warn_once(warned, "XGSuggestSwizzleMode", -1, _ReturnAddress()); - return kNotImpl; -} - -} // namespace - -SHIM_TABLE(xg_xs, - {"xg_xs.dll", "XGCreateTextureComputer", reinterpret_cast(&XGCreateTextureComputer)}, - {"xg_xs.dll", "XGSuggestSwizzleMode", reinterpret_cast(&XGSuggestSwizzleMode)}, -); diff --git a/runtime/shims/xgameruntime.cpp b/runtime/shims/xgameruntime.cpp deleted file mode 100644 index 6a1382838..000000000 --- a/runtime/shims/xgameruntime.cpp +++ /dev/null @@ -1,1402 +0,0 @@ -// xgameruntime: the GDK runtime surface a title calls before anything else, offline. -// -// Every GDK title starts with XGameRuntimeInitialize and builds its async work on XTaskQueue/XAsync. This table -// serves those from third_party/xtaskqueue (Microsoft's MIT-licensed implementation from libHttpClient), plus the -// XGameRuntime and XSystem calls a title makes at boot. Signatures and enum values follow Microsoft's public GDK -// documentation (learn.microsoft.com/gaming/gdk); no GDK header or library code is used. -// -// Nothing here goes online. -// -// Measured on the retail executable (docs/runtime_imports.md, "The retail executable's runtime classes"): it does not -// import xgameruntime.dll. Its 161 runtime thunks are linked into the image and reach the classes through -// QueryApiImpl, as libHttpClient.GDK.dll's do, so "xgameruntime.dll" below is the only module name needed. The name -// occurs in the image as a UTF-16 string, which would be a run-time load. -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include -#include -#include - -#include "../core/config.h" -#include "../core/log.h" -#include "file_system.h" -#include "shims.h" - -namespace rt::shims { -bool xgameruntime_user_query(const GUID& class_id, REFIID interface_id, void** out, HRESULT* hr); -bool xgameruntime_gamesave_query(const GUID& class_id, REFIID interface_id, void** out, HRESULT* hr); -bool xgameruntime_store_query(const GUID& class_id, REFIID interface_id, void** out, HRESULT* hr); -bool xgameruntime_offline_query(const GUID& class_id, REFIID interface_id, void** out, HRESULT* hr); -} - -namespace { - -// ---- XGameRuntime ---- - -std::atomic g_runtime_refs{0}; - -// ---- The run-time entry points xgameruntime.lib looks up ---- -// -// A title linked against xgameruntime.lib doesn't import XGameRuntimeInitialize: the static library's thunks load -// "xgameruntime.dll" and GetProcAddress these five names (measured in the package's libHttpClient.GDK.dll and -// XCurl.dll, docs/runtime_imports.md). Signatures, the options struct and the error for an unknown class follow -// xodus-gaming/xgameruntime-docs (GPL-3.0; facts only, nothing copied): InitializeApiImplEx2 is the one -// XGameRuntimeInitialize[WithOptions] calls, and QueryApiImpl hands out the runtime's COM classes. XThreadingImpl, -// XErrorImpl, XNetworkingImpl, XSystemImpl, XPackageImpl, XGameRuntimeFeatureImpl and XSystemAnalyticsImpl are -// served (their layouts are measured, below), XPersistentLocalStorageImpl and XGameImpl from the public docs' layout -// (no caller in the shipped DLLs to measure), and the classes of the other xgameruntime_*.cpp files through their -// query functions; for any other class QueryApiImpl logs the class and interface id and refuses it, so the first boot -// with the executable lists the interfaces to implement next. - -struct ApiImplOptions { // InitializeApiImplEx2's fourth argument - uint32_t unknown; // documented as always 1 - BOOL is_inline; // 1 when XGameRuntimeOptions::gameConfigSource is Inline - const char* game_config; -}; - -constexpr HRESULT kClassNotProvided = static_cast(0x80070032); // HRESULT_FROM_WIN32(ERROR_NOT_SUPPORTED) - -std::atomic g_api_refs{0}; - -HRESULT api_initialize(const char* which, ULONG gdk_ver, ULONG gs_ver, int mode, const ApiImplOptions* options) { - if (g_api_refs.fetch_add(1) == 0) - RT_LOG_INFO("xgameruntime: %s(gdk=%lu, gs=%lu, mode=%#x, options=%s) (offline)\n", which, - gdk_ver, gs_ver, mode & 0xFF, - options ? (options->is_inline ? "inline game config" : "default game config") : "none"); - return S_OK; -} - -HRESULT WINAPI InitializeApiImpl(ULONG gdk_ver, ULONG gs_ver) { - return api_initialize("InitializeApiImpl", gdk_ver, gs_ver, -1, nullptr); -} - -HRESULT WINAPI InitializeApiImplEx(ULONG gdk_ver, ULONG gs_ver, char mode) { - return api_initialize("InitializeApiImplEx", gdk_ver, gs_ver, static_cast(mode), nullptr); -} - -HRESULT WINAPI InitializeApiImplEx2(ULONG gdk_ver, ULONG gs_ver, char mode, const ApiImplOptions* options) { - return api_initialize("InitializeApiImplEx2", gdk_ver, gs_ver, static_cast(mode), options); -} - -HRESULT WINAPI UninitializeApiImpl() { - int prev = g_api_refs.load(); - while (prev > 0 && !g_api_refs.compare_exchange_weak(prev, prev - 1)) {} - return S_OK; -} - -void print_guid(char (&out)[40], const GUID* g) { - if (!g) { - std::snprintf(out, sizeof out, "(null)"); - return; - } - std::snprintf(out, sizeof out, "%08lx-%04x-%04x-%02x%02x-%02x%02x%02x%02x%02x%02x", g->Data1, g->Data2, - g->Data3, g->Data4[0], g->Data4[1], g->Data4[2], g->Data4[3], g->Data4[4], g->Data4[5], - g->Data4[6], g->Data4[7]); -} - -// ---- The runtime classes QueryApiImpl hands out ---- -// -// xgameruntime.lib's thunk for each function asks QueryApiImpl for the class (passing the class id as the interface -// id too), calls one slot of the object's vtable with the function's own arguments after `this`, and Releases it. -// The slot order is xgameruntime-docs' "Layout" list after IUnknown's three slots, and it is measured: the thunks -// statically linked into the package's libHttpClient.GDK.dll and XCurl.dll (disassembled, their code not run) -// call IXThreadingImpl slots 3-7 and 9-30, each with the argument shape of the documented function in that -// position (XAsyncBegin's five arguments at slot 7, XTaskQueueCreate's two modes and a handle pointer at 12, -// XTaskQueueTerminate's bool at 22, XThreadSetTimeSensitive's bool at 27, ...), and IXErrorImpl slot 3 with an -// HRESULT and a pointer. docs/runtime_imports.md has the table. Each function is served by the implementation the -// named export already uses (third_party/xtaskqueue), so the two ways in behave the same. - -constexpr GUID kThreadingClass = {0x073b7dcb, 0x1fcf, 0x4030, {0x94, 0xbe, 0xe3, 0xc9, 0xeb, 0x62, 0x34, 0x28}}; -constexpr GUID kErrorClass = {0x8ca467f7, 0x22e8, 0x4096, {0x84, 0x56, 0xbb, 0x8a, 0xa1, 0x3f, 0x79, 0xd8}}; - -// A function's arguments after `this`, forwarded unchanged (x64 has one calling convention). -// Specialised on the function's exact type, so a noexcept function matches only one form. -template struct Method; -template struct Method { - static R STDMETHODCALLTYPE call(void*, A... a) { return F(a...); } -}; -template struct Method { - static R STDMETHODCALLTYPE call(void*, A... a) noexcept { return F(a...); } -}; - -constexpr GUID kIUnknown = {0x00000000, 0x0000, 0x0000, {0xc0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x46}}; - -// The runtime's objects are process-wide singletons: AddRef/Release count but never free. -struct RuntimeObject { - const void* const* vtable; - const GUID* class_id; // the coclass id - const GUID* const* interface_ids; // every interface the vtable serves, base first, null-terminated: a derived - // interface answers for each one it inherits (IXSystemImpl5 : ... : IXSystemImpl) - std::atomic refs{1}; -}; - -HRESULT STDMETHODCALLTYPE object_query_interface(void* self, REFIID iid, void** out) { - if (!out) return E_POINTER; - auto* o = static_cast(self); - bool known = iid == kIUnknown || iid == *o->class_id; - for (const GUID* const* i = o->interface_ids; !known && i && *i; ++i) known = iid == **i; - if (known) { - o->refs.fetch_add(1); - *out = self; - return S_OK; - } - *out = nullptr; - return E_NOINTERFACE; -} -ULONG STDMETHODCALLTYPE object_add_ref(void* self) { return static_cast(static_cast(self)->refs.fetch_add(1) + 1); } -ULONG STDMETHODCALLTYPE object_release(void* self) { - long prev = static_cast(self)->refs.load(); - while (prev > 1 && !static_cast(self)->refs.compare_exchange_weak(prev, prev - 1)) {} - return static_cast(prev > 1 ? prev - 1 : 1); // the singleton's own reference stays -} - -// A private slot whose signature isn't public: logged once, answers 0 (S_OK / false / nothing to do). -template uint64_t STDMETHODCALLTYPE private_slot(void*) { - static std::atomic s_logged{false}; - if (!s_logged.exchange(true)) - RT_LOG_WARN("xgameruntime: XThreadingImpl private slot %d called; answering 0\n", Slot); - return 0; -} - -// Slot 8, XAsyncBeginAlloc: private (no public page) and never called by the package's DLLs, so its signature here -// is not measured. Refuse it: answering S_OK would tell the caller its async call has begun while no provider ever -// receives XAsyncOp::Begin, so its completion never arrives. -HRESULT STDMETHODCALLTYPE begin_alloc_not_provided(void*) { - static std::atomic s_logged{false}; - if (!s_logged.exchange(true)) - RT_LOG_WARN("xgameruntime: XThreadingImpl slot 8 (XAsyncBeginAlloc) called; not provided, " - "returning E_NOTIMPL\n"); - return E_NOTIMPL; -} - -// XThreadSetTimeSensitive / XThreadIsTimeSensitive / XThreadAssertNotTimeSensitive. The flag is per thread, as in -// the GDK; nothing is enforced offline (a time-sensitive thread may still block). -thread_local bool t_time_sensitive = false; -HRESULT STDMETHODCALLTYPE thread_set_time_sensitive(void*, bool value) { - t_time_sensitive = value; - return S_OK; -} -void STDMETHODCALLTYPE thread_assert_not_time_sensitive(void*) {} -bool STDMETHODCALLTYPE thread_is_time_sensitive(void*) { return t_time_sensitive; } - -#define XM(fn) reinterpret_cast(&Method<&fn>::call) -const void* const kThreadingVtable[] = { - reinterpret_cast(&object_query_interface), reinterpret_cast(&object_add_ref), - reinterpret_cast(&object_release), - XM(XAsyncGetStatus), // 3 - XM(XAsyncGetResultSize), // 4 - XM(XAsyncCancel), // 5 - XM(XAsyncRun), // 6 - XM(XAsyncBegin), // 7 - reinterpret_cast(&begin_alloc_not_provided), // 8 XAsyncBeginAlloc (private, not called by the package) - XM(XAsyncSchedule), // 9 - XM(XAsyncComplete), // 10 - XM(XAsyncGetResult), // 11 - XM(XTaskQueueCreate), // 12 - XM(XTaskQueueCreateComposite), // 13 - XM(XTaskQueueGetPort), // 14 - XM(XTaskQueueDuplicateHandle), // 15 - XM(XTaskQueueDispatch), // 16 - XM(XTaskQueueCloseHandle), // 17 - XM(XTaskQueueSubmitCallback), // 18 - XM(XTaskQueueSubmitDelayedCallback), // 19 - XM(XTaskQueueRegisterWaiter), // 20 - XM(XTaskQueueUnregisterWaiter), // 21 - XM(XTaskQueueTerminate), // 22 - XM(XTaskQueueRegisterMonitor), // 23 - XM(XTaskQueueUnregisterMonitor), // 24 - XM(XTaskQueueGetCurrentProcessTaskQueue), // 25 - XM(XTaskQueueSetCurrentProcessTaskQueue), // 26 - reinterpret_cast(&thread_set_time_sensitive), // 27 - reinterpret_cast(&private_slot<28>), // 28 XTaskQueueIsEmpty (private; no arguments) - reinterpret_cast(&thread_assert_not_time_sensitive), // 29 - reinterpret_cast(&thread_is_time_sensitive), // 30 -}; -#undef XM -static_assert(std::size(kThreadingVtable) == 31, "IUnknown + IXThreadingImpl's 28 methods"); - -// IXErrorImpl: XErrorReport(HRESULT, const char*) at slot 3 (the docs' "_unknown_"; XCurl calls it with an HRESULT -// and a string), XErrorSetCallback(XErrorCallback*, void*) and XErrorSetOptions(options, options). Offline, a report -// is logged and handed to the callback the title set, if any. -using XErrorCallback = bool(CALLBACK*)(HRESULT hr, const char* message, void* context); -std::atomic g_error_callback{nullptr}; -std::atomic g_error_context{nullptr}; -std::mutex g_error_mutex{}; // guards g_error_callback + g_error_context as one consistent pair - -// HRESULT XErrorReport(HRESULT, const char*) (xgameruntime-docs' XErrorReport.md): S_OK once reported. -HRESULT STDMETHODCALLTYPE error_report(void*, HRESULT hr, const char* message) { - static std::atomic s_logged{0}; - if (s_logged.fetch_add(1) < 64) - RT_LOG_ERROR("xgameruntime: XErrorReport(0x%08lx, %s)\n", static_cast(hr), - message ? message : "(null)"); - std::lock_guard lock(g_error_mutex); - if (XErrorCallback cb = g_error_callback.load()) cb(hr, message, g_error_context.load()); - return S_OK; -} - -// The same function as a DLL export: xgameruntime.lib's XGameRuntimeInitialize looks up "XErrorReport" with -// GetProcAddress next to QueryApiImpl, the InitializeApiImpl* and UninitializeApiImpl, and refuses to initialise when it -// is missing (retail executable: the lookup at +0x55e2b7e, the null check at +0x55e2c08, then an int3 at +0x5a91c21). -HRESULT WINAPI XErrorReport(HRESULT hr, const char* message) { return error_report(nullptr, hr, message); } -void STDMETHODCALLTYPE error_set_callback(void*, XErrorCallback callback, void* context) { - std::lock_guard lock(g_error_mutex); - g_error_context = context; - g_error_callback = callback; -} -// void XErrorSetOptions(XErrorOptions, XErrorOptions), as Microsoft documents it: nothing to configure offline. -void STDMETHODCALLTYPE error_set_options(void*, uint32_t, uint32_t) {} - -const void* const kErrorVtable[] = { - reinterpret_cast(&object_query_interface), reinterpret_cast(&object_add_ref), - reinterpret_cast(&object_release), - reinterpret_cast(&error_report), // 3 - reinterpret_cast(&error_set_callback), // 4 - reinterpret_cast(&error_set_options), // 5 -}; - -// ---- XNetworkingImpl (IXNetworkingImpl, IXNetworkingImpl2), offline ---- -// -// XCurl.dll asks for the class with IXNetworkingImpl2's interface id and calls slots 11-17 (docs/runtime_imports.md, -// "Class layouts, measured"): the UTF-16 security-information query for a URL, the server certificate check, the -// connectivity hint and its change registration. Signatures follow Microsoft's public XNetworking documentation. -// Offline there is no network: the hint says so (initialized, no connectivity), every query that would need the -// network fails with kNoNetwork (asynchronously, through XAsync, for the *Async calls), a change registration sends -// the initial notification Microsoft documents (on the queue's completion port) and none after, since nothing -// changes, and the IXNetworkingImpl2 additions are E_NOTIMPL. - -constexpr GUID kNetworkingClass = {0x37e56907, 0x2f10, 0x41e8, {0xb7, 0x2f, 0x36, 0xed, 0xb1, 0x85, 0x33, 0x1a}}; -constexpr GUID kNetworking2 = {0xbf2346b2, 0x39af, 0x4658, {0xb5, 0xea, 0x44, 0x71, 0x3c, 0x7e, 0x83, 0xb3}}; -constexpr HRESULT kNoNetwork = HRESULT_FROM_WIN32(ERROR_NETWORK_UNREACHABLE); - -// XNetworkingConnectivityHint: level, cost, IANA interface type (u32 each), then four bools. -struct ConnectivityHint { - uint32_t connectivity_level; // XNetworkingConnectivityLevelHint: Unknown 0, None 1, LocalAccess 2, Internet 3 - uint32_t connectivity_cost; // XNetworkingConnectivityCostHint: Unknown 0, Unrestricted 1, Fixed 2, Variable 3 - uint32_t iana_interface_type; - bool network_initialized; - bool approaching_data_limit; - bool over_data_limit; - bool roaming; -}; -static_assert(sizeof(ConnectivityHint) == 16, "XNetworkingConnectivityHint is 16 bytes"); - -HRESULT STDMETHODCALLTYPE net_query_port(void*, uint16_t* port) { - if (!port) return E_POINTER; - *port = 0; - return kNoNetwork; -} -// Completes `async` with kNoNetwork on its queue, as the GDK does for a query that fails. -HRESULT start_failed_async(XAsyncBlock* async) { - if (!async) return E_POINTER; - return XAsyncRun(async, [](XAsyncBlock*) -> HRESULT { return kNoNetwork; }); -} -HRESULT STDMETHODCALLTYPE net_query_port_async(void*, XAsyncBlock* async) { return start_failed_async(async); } -HRESULT STDMETHODCALLTYPE net_query_port_result(void*, XAsyncBlock* async, uint16_t* port) { - if (!async || !port) return E_POINTER; - *port = 0; - return XAsyncGetStatus(async, false); -} -HRESULT STDMETHODCALLTYPE net_security_async(void*, const void* url, XAsyncBlock* async) { - if (!url) return E_INVALIDARG; - return start_failed_async(async); -} -HRESULT STDMETHODCALLTYPE net_security_result_size(void*, XAsyncBlock* async, size_t* size) { - if (!async || !size) return E_POINTER; - *size = 0; - return XAsyncGetStatus(async, false); -} -// XNetworkingQuerySecurityInformationForUrl[Utf16]AsyncResult(XAsyncBlock*, size_t bufferByteCount, -// size_t* bufferByteCountUsed, uint8_t* buffer, XNetworkingSecurityInformation** securityInformation), in the order -// of Microsoft's reference pages. The buffer itself is never written: there is no result to copy offline. -HRESULT STDMETHODCALLTYPE net_security_result(void*, XAsyncBlock* async, size_t, size_t* used, uint8_t*, void** info) { - if (!async) return E_POINTER; - if (used) *used = 0; - if (info) *info = nullptr; - return XAsyncGetStatus(async, false); -} -HRESULT STDMETHODCALLTYPE net_verify_certificate(void*, void*, const void*) { return kNoNetwork; } -HRESULT STDMETHODCALLTYPE net_connectivity_hint(void*, ConnectivityHint* hint) { - if (!hint) return E_POINTER; - *hint = {}; - hint->connectivity_level = 1; // None: the stack is up, nothing is reachable - hint->network_initialized = true; - return S_OK; -} - -using PortChangedCallback = void(CALLBACK*)(void* context, uint16_t port); -using HintChangedCallback = void(CALLBACK*)(void* context, const ConnectivityHint* hint); - -struct NetRegistration { - bool running = false; - bool unregistered = false; -}; -std::mutex g_net_mu; -std::condition_variable g_net_cv; -std::unordered_map g_net_registrations; -std::atomic g_net_tokens{0}; - -void notify(PortChangedCallback callback, void* context) { - uint16_t port = 0; - net_query_port(nullptr, &port); - callback(context, port); -} -void notify(HintChangedCallback callback, void* context) { - ConnectivityHint hint{}; - net_connectivity_hint(nullptr, &hint); - callback(context, &hint); -} - -template struct InitialNotification { - uint64_t token; - void* context; - Callback callback; - - static void CALLBACK run(void* self, bool canceled) { - std::unique_ptr n(static_cast(self)); - { - std::lock_guard lock(g_net_mu); - const auto it = g_net_registrations.find(n->token); - if (canceled || it == g_net_registrations.end()) return; - it->second.running = true; - } - notify(n->callback, n->context); - { - std::lock_guard lock(g_net_mu); - const auto it = g_net_registrations.find(n->token); - if (it->second.unregistered) g_net_registrations.erase(it); - else it->second.running = false; - } - g_net_cv.notify_all(); - } -}; - -template -HRESULT STDMETHODCALLTYPE net_register(void*, XTaskQueueHandle queue, void* context, Callback callback, - XTaskQueueRegistrationToken* token) { - if (!callback) return E_INVALIDARG; - if (!token) return E_POINTER; - XTaskQueueHandle process_queue = nullptr; - if (!queue) { - if (!XTaskQueueGetCurrentProcessTaskQueue(&process_queue)) return HRESULT_FROM_WIN32(ERROR_NO_TASK_QUEUE); - queue = process_queue; - } - const uint64_t id = g_net_tokens.fetch_add(1) + 1; - { - std::lock_guard lock(g_net_mu); - g_net_registrations.emplace(id, NetRegistration{}); - } - token->token = id; - auto* initial = new InitialNotification{id, context, callback}; - const HRESULT hr = XTaskQueueSubmitCallback(queue, XTaskQueuePort::Completion, initial, - &InitialNotification::run); - if (process_queue) XTaskQueueCloseHandle(process_queue); - if (FAILED(hr)) { - delete initial; - token->token = 0; - std::lock_guard lock(g_net_mu); - g_net_registrations.erase(id); - } - return hr; -} -bool STDMETHODCALLTYPE net_unregister(void*, XTaskQueueRegistrationToken token, bool wait) { - std::unique_lock lock(g_net_mu); - const auto it = g_net_registrations.find(token.token); - if (it == g_net_registrations.end()) return true; - if (!it->second.running) { - g_net_registrations.erase(it); - return true; - } - it->second.unregistered = true; - if (wait) g_net_cv.wait(lock, [&] { return !g_net_registrations.contains(token.token); }); - return wait; -} -HRESULT STDMETHODCALLTYPE net_not_implemented(void*) { return E_NOTIMPL; } - -#define NM(fn) reinterpret_cast(&fn) -const void* const kNetworkingVtable[] = { - NM(object_query_interface), NM(object_add_ref), NM(object_release), - NM(net_query_port), // 3 XNetworkingQueryPreferredLocalUdpMultiplayerPort - NM(net_query_port_async), // 4 ...Async - NM(net_query_port_result), // 5 ...AsyncResult - NM(net_register), // 6 XNetworkingRegisterPreferredLocalUdpMultiplayerPortChanged - NM(net_unregister), // 7 XNetworkingUnregisterPreferredLocalUdpMultiplayerPortChanged - NM(net_security_async), // 8 XNetworkingQuerySecurityInformationForUrlAsync - NM(net_security_result_size), // 9 ...AsyncResultSize - NM(net_security_result), // 10 ...AsyncResult - NM(net_security_async), // 11 XNetworkingQuerySecurityInformationForUrlUtf16Async (XCurl) - NM(net_security_result_size), // 12 ...Utf16AsyncResultSize (XCurl) - NM(net_security_result), // 13 ...Utf16AsyncResult (XCurl) - NM(net_verify_certificate), // 14 XNetworkingVerifyServerCertificate (XCurl) - NM(net_connectivity_hint), // 15 XNetworkingGetConnectivityHint (XCurl) - NM(net_register), // 16 XNetworkingRegisterConnectivityHintChanged (XCurl) - NM(net_unregister), // 17 XNetworkingUnregisterConnectivityHintChanged (XCurl) - NM(net_not_implemented), // 18 XNetworkingQueryConfigurationSetting (IXNetworkingImpl2) - NM(net_not_implemented), // 19 XNetworkingSetConfigurationSetting - NM(net_not_implemented), // 20 XNetworkingQueryStatistics -}; -#undef NM -static_assert(std::size(kNetworkingVtable) == 21, "IUnknown + IXNetworkingImpl's 15 + IXNetworkingImpl2's 3"); - -// ---- XPersistentLocalStorageImpl (IXPersistentLocalStorageImpl .. 3), a folder beside the overlay ---- -// -// The package declares persistent local storage (MicrosoftGame.Config, PersistentLocalStorage, 2048 MB), so the title -// can ask where it may keep its cache. Slots 3-7 follow Microsoft's XPersistentLocalStorage reference and the ids and -// layout in the public xgameruntime-docs and Wine IDL (facts only): GetPathSize, GetPath, GetSpaceInfo, -// PromptUserForSpaceAsync and PromptUserForSpaceResult; IXPersistentLocalStorageImpl3 adds MountForPackage at slot 8. -// The storage is \.gta6rt-persistent, so the package stays read-only, --overlay moves it with everything -// else a title writes, and GAME: does not see it. Offline there is nobody to ask for more room: a prompt for space the -// quota can hold succeeds, one it cannot fails with ERROR_DISK_FULL. - -constexpr GUID kPersistentStorageClass = {0xf4faf4d4, 0x2d04, 0x4fce, {0xb3, 0xe0, 0x47, 0x4a, 0x71, 0x3a, 0x3e, 0x84}}; -constexpr GUID kPersistentStorage2 = {0xd29411df, 0x0794, 0x4553, {0x8b, 0x27, 0x95, 0xfc, 0x02, 0xd0, 0xf7, 0x5d}}; -constexpr GUID kPersistentStorage3 = {0x41a4e10c, 0x5a7e, 0x41d9, {0x8c, 0x37, 0x37, 0xbd, 0xe6, 0x2a, 0x07, 0xd6}}; -constexpr uint64_t kPersistentQuotaBytes = 2048ull * 1024 * 1024; // MicrosoftGame.Config of package 1.0.2.1 - -// XPersistentLocalStorageSpaceInfo: four 64-bit counts. -struct PersistentSpaceInfo { - uint64_t available_free_bytes; // what the title can still write: the quota left, capped by the host volume - uint64_t total_free_bytes; // the quota left - uint64_t used_bytes; - uint64_t total_bytes; // the quota -}; -static_assert(sizeof(PersistentSpaceInfo) == 32, "XPersistentLocalStorageSpaceInfo is four UINT64"); - -// The storage folder, created on first use. Empty when there is no overlay (no place to keep files) or the folder -// cannot be created. -std::filesystem::path persistent_storage_dir() { - const std::filesystem::path overlay = rt::fs::overlay_dir(); - if (overlay.empty()) return {}; - std::filesystem::path dir = overlay / rt::fs::kPersistentStorageDir; - std::error_code ec; - std::filesystem::create_directories(dir, ec); - return ec ? std::filesystem::path{} : dir; -} - -std::string utf8_of(const std::wstring& wide) { - const int n = WideCharToMultiByte(CP_UTF8, 0, wide.c_str(), static_cast(wide.size()), nullptr, 0, nullptr, nullptr); - if (n <= 0) return {}; - std::string utf8(static_cast(n), '\0'); - WideCharToMultiByte(CP_UTF8, 0, wide.c_str(), static_cast(wide.size()), utf8.data(), n, nullptr, nullptr); - return utf8; -} - -uint64_t folder_bytes(const std::filesystem::path& dir) { - uint64_t total = 0; - std::error_code ec; - for (std::filesystem::recursive_directory_iterator it(dir, std::filesystem::directory_options::skip_permission_denied, ec), end; - !ec && it != end; it.increment(ec)) { - std::error_code file_ec; - if (!it->is_regular_file(file_ec) || file_ec) continue; - const uintmax_t size = it->file_size(file_ec); - if (!file_ec) total += size; - } - return total; -} - -HRESULT STDMETHODCALLTYPE pls_get_path_size(void*, size_t* path_size) { - if (!path_size) return E_POINTER; - *path_size = 0; - const std::string path = utf8_of(persistent_storage_dir().native()); - if (path.empty()) return HRESULT_FROM_WIN32(ERROR_PATH_NOT_FOUND); - *path_size = path.size() + 1; // with the terminating NUL - return S_OK; -} - -HRESULT STDMETHODCALLTYPE pls_get_path(void*, size_t path_size, char* path, size_t* path_used) { - if (path_used) *path_used = 0; - if (!path) return E_POINTER; - const std::string folder = utf8_of(persistent_storage_dir().native()); - if (folder.empty()) return HRESULT_FROM_WIN32(ERROR_PATH_NOT_FOUND); - if (path_size < folder.size() + 1) return HRESULT_FROM_WIN32(ERROR_INSUFFICIENT_BUFFER); - std::memcpy(path, folder.c_str(), folder.size() + 1); - if (path_used) *path_used = folder.size() + 1; - return S_OK; -} - -HRESULT STDMETHODCALLTYPE pls_get_space_info(void*, PersistentSpaceInfo* info) { - if (!info) return E_POINTER; - *info = {}; - const std::filesystem::path dir = persistent_storage_dir(); - if (dir.empty()) return HRESULT_FROM_WIN32(ERROR_PATH_NOT_FOUND); - const uint64_t used = folder_bytes(dir); - const uint64_t left = used < kPersistentQuotaBytes ? kPersistentQuotaBytes - used : 0; - std::error_code ec; - const std::filesystem::space_info host = std::filesystem::space(dir, ec); - info->total_bytes = kPersistentQuotaBytes; - info->used_bytes = used; - info->total_free_bytes = left; - info->available_free_bytes = ec || left < host.available ? left : host.available; - return S_OK; -} - -HRESULT STDMETHODCALLTYPE pls_prompt_async(void*, uint64_t requested_bytes, XAsyncBlock* async) { - if (!async) return E_POINTER; - const std::filesystem::path dir = persistent_storage_dir(); - const bool fits = !dir.empty() && requested_bytes <= kPersistentQuotaBytes - (std::min)(folder_bytes(dir), kPersistentQuotaBytes); - if (fits) return XAsyncRun(async, [](XAsyncBlock*) -> HRESULT { return S_OK; }); - return XAsyncRun(async, [](XAsyncBlock*) -> HRESULT { return HRESULT_FROM_WIN32(ERROR_DISK_FULL); }); -} - -HRESULT STDMETHODCALLTYPE pls_prompt_result(void*, XAsyncBlock* async) { - if (!async) return E_POINTER; - return XAsyncGetStatus(async, false); -} - -// IXPersistentLocalStorageImpl3's package mount has nothing to mount offline; the handle is left empty. -HRESULT STDMETHODCALLTYPE pls_mount_for_package(void*, const char*, void** mount_handle) { - if (!mount_handle) return E_POINTER; - *mount_handle = nullptr; - return E_NOTIMPL; -} - -#define PLS(fn) reinterpret_cast(&fn) -const void* const kPersistentStorageVtable[] = { - PLS(object_query_interface), PLS(object_add_ref), PLS(object_release), - PLS(pls_get_path_size), // 3 XPersistentLocalStorageGetPathSize - PLS(pls_get_path), // 4 XPersistentLocalStorageGetPath - PLS(pls_get_space_info), // 5 XPersistentLocalStorageGetSpaceInfo - PLS(pls_prompt_async), // 6 XPersistentLocalStoragePromptUserForSpaceAsync - PLS(pls_prompt_result), // 7 XPersistentLocalStoragePromptUserForSpaceResult - PLS(pls_mount_for_package), // 8 XPersistentLocalStorageMountForPackage (IXPersistentLocalStorageImpl3) -}; -#undef PLS -static_assert(std::size(kPersistentStorageVtable) == 9, "IUnknown + IXPersistentLocalStorageImpl's 5 + Impl3's 1"); - -// The ids xgameruntime-docs and the xgameruntime IDL give: XThreadingImpl's and XErrorImpl's class id is also their -// one interface's; IXNetworkingImpl's id is the class id, and IXNetworkingImpl2 derives from it. -const GUID* const kNetworkingIids[] = {&kNetworking2, nullptr}; -RuntimeObject g_threading{kThreadingVtable, &kThreadingClass, nullptr}; -RuntimeObject g_error{kErrorVtable, &kErrorClass, nullptr}; -RuntimeObject g_networking{kNetworkingVtable, &kNetworkingClass, kNetworkingIids}; -const GUID* const kPersistentStorageIids[] = {&kPersistentStorage2, &kPersistentStorage3, nullptr}; -RuntimeObject g_persistent_storage{kPersistentStorageVtable, &kPersistentStorageClass, kPersistentStorageIids}; - -RuntimeObject& system_object(); // XSystemImpl, defined after the XSystem functions it serves -RuntimeObject& package_object(); // XPackageImpl, after the XPackage functions -RuntimeObject& game_object(); // XGameImpl, after XPackageImpl -RuntimeObject* const* measured_objects(); // XGameRuntimeFeatureImpl and XSystemAnalyticsImpl, after XGameImpl - -// The object this file hands out for a class id, or null when the class isn't one of this file's. -RuntimeObject* find_object(const GUID& class_id) { - for (RuntimeObject* o : {&g_threading, &g_error, &g_networking, &g_persistent_storage, &system_object(), - &package_object(), &game_object()}) - if (class_id == *o->class_id) return o; - for (RuntimeObject* const* o = measured_objects(); *o; ++o) - if (class_id == *(*o)->class_id) return *o; - return nullptr; -} - -// QueryApiImpl's answer for a served class: true with *hr set (and *out on success) when this file or one of the -// other xgameruntime_*.cpp files serves the class, false when none does. -bool query_served(const GUID& class_id, REFIID interface_id, void** out, HRESULT* hr) { - if (RuntimeObject* o = find_object(class_id)) { - *hr = object_query_interface(o, interface_id, out); - return true; - } - return rt::shims::xgameruntime_user_query(class_id, interface_id, out, hr) || // xgameruntime_user.cpp - rt::shims::xgameruntime_gamesave_query(class_id, interface_id, out, hr) || // xgameruntime_gamesave.cpp - rt::shims::xgameruntime_store_query(class_id, interface_id, out, hr) || // xgameruntime_store.cpp - rt::shims::xgameruntime_offline_query(class_id, interface_id, out, hr); // xgameruntime_offline.cpp -} - -// Whether QueryApiImpl serves the class, whichever file serves it (the reference taken to find out is released). -bool class_served(const GUID& class_id) { - void* obj = nullptr; - HRESULT hr = S_OK; - if (!query_served(class_id, kIUnknown, &obj, &hr)) return false; - if (obj) (*static_cast(obj))[2](obj); // Release - return true; -} - -HRESULT WINAPI QueryApiImpl(const GUID* class_id, REFIID interface_id, void** out) { - if (out) *out = nullptr; - if (class_id && out) { - HRESULT hr = S_OK; - if (query_served(*class_id, interface_id, out, &hr)) return hr; - } - char cls[40], iid[40]; - print_guid(cls, class_id); - print_guid(iid, &interface_id); - static std::atomic s_logged{0}; - if (s_logged.fetch_add(1) < 256) // one line per request, bounded - RT_LOG_WARN("xgameruntime: QueryApiImpl(class %s, interface %s): not provided yet\n", cls, iid); - return kClassNotProvided; -} - -// gameplatformservices.dll: XCurl.dll's other way into the runtime (docs/runtime_imports.md). It reads -// HKLM\Microsoft\GamingServices ServiceRetryTimeout, LoadLibraryExW's this module from System32, calls -// GetApiVersionImpl through the CFG dispatch with two pointers to 64-bit locals (the result unread), compares them -// with the pair it saw last and keeps them, and then GetProcAddress'es QueryApiImpl. Served by the shims, so that call -// never reaches a PC's Gaming Services runtime (which would bypass these offline classes, and could go online) and -// never fails because the PC has none. The two values only have to be stable: the offline runtime has one version. -constexpr uint64_t kOfflineApiVersion = 1; -HRESULT WINAPI GetApiVersionImpl(uint64_t* first, uint64_t* second) { - if (first) *first = kOfflineApiVersion; - if (second) *second = kOfflineApiVersion; - return S_OK; -} - -// HRESULT XGameRuntimeInitialize(). Reference counted, as in the GDK: each call needs an XGameRuntimeUninitialize. -HRESULT __stdcall XGameRuntimeInitialize() { - if (g_runtime_refs.fetch_add(1) == 0) RT_LOG_INFO("xgameruntime: initialized (offline)\n"); - return S_OK; -} - -// void XGameRuntimeUninitialize() -void __stdcall XGameRuntimeUninitialize() { - int prev = g_runtime_refs.load(); - while (prev > 0 && !g_runtime_refs.compare_exchange_weak(prev, prev - 1)) {} -} - -// ---- XSystem ---- - -// XSystemDeviceType, in the order of the public documentation: Unknown, Pc, XboxOne, XboxOneS, XboxOneX, -// XboxOneXDevkit, XboxScarlettLockhart, XboxScarlettAnaconda, XboxScarlettDevkit. -enum class XSystemDeviceType : uint32_t { - Unknown = 0, Pc = 1, XboxOne = 2, XboxOneS = 3, XboxOneX = 4, XboxOneXDevkit = 5, - XboxScarlettLockhart = 6, XboxScarlettAnaconda = 7, XboxScarlettDevkit = 8, -}; - -// XSystemDeviceType XSystemGetDeviceType(). The package is the Xbox Series build, so report Series X (Anaconda). -// LEONIDA_DEVICE_TYPE=<0..8> overrides it, for trying other code paths on day one. -uint32_t __stdcall XSystemGetDeviceType() { - // A value of 16 characters or more is ignored, as before the setting moved to the table. - const std::string s = rt::config::get("system.device_type").text; - if (s.size() < 16) { - int v = std::atoi(s.c_str()); - if (v >= 0 && v <= 8) return static_cast(v); - } - return static_cast(XSystemDeviceType::XboxScarlettAnaconda); -} - -// HRESULT XSystemGetConsoleId(size_t consoleIdSize, char* consoleId, size_t* consoleIdUsed). -// XSystemConsoleIdBytes is 39 (including the terminator). An offline PC has no console id, so this returns a -// fixed placeholder of that length. -constexpr size_t kConsoleIdBytes = 39; -constexpr char kConsoleId[kConsoleIdBytes] = "00000000.00000000.00000000.00000000.00"; -static_assert(sizeof(kConsoleId) == kConsoleIdBytes, "placeholder console id must fill XSystemConsoleIdBytes"); - -HRESULT __stdcall XSystemGetConsoleId(size_t size, char* out, size_t* used) { - if (!out) return E_INVALIDARG; - if (size < kConsoleIdBytes) return HRESULT_FROM_WIN32(ERROR_INSUFFICIENT_BUFFER); - std::memcpy(out, kConsoleId, kConsoleIdBytes); - if (used) *used = kConsoleIdBytes; - return S_OK; -} - -// uint64_t XSystemGetAppMemoryUsageLimit(). Reports total physical RAM, or 12 GB fallback for Series X. -uint64_t __stdcall XSystemGetAppMemoryUsageLimit() { - MEMORYSTATUSEX ms{sizeof(ms)}; - if (GlobalMemoryStatusEx(&ms)) return ms.ullTotalPhys; - return 12ULL * 1024 * 1024 * 1024; -} - -// uint64_t XSystemGetAppMemoryUsage() -uint64_t __stdcall XSystemGetAppMemoryUsage() { - return 0; -} - -// ---- XSystemImpl (asked for as IXSystemImpl5), offline ---- -// -// libHttpClient.GDK.dll asks QueryApiImpl for XSystemImpl with IXSystemImpl5's id and calls slots 3-8, each with the -// argument shape of the function at that position of xgameruntime-docs' IXSystemImpl / IXSystemImpl3 / -// IXSystemImpl4 lists (IXSystemImpl2 and 5 add nothing known): three (size, buffer, used) id queries, then -// XSystemHandleTrack (two pointers), XSystemIsHandleValid (a handle) and XSystemAllowFullDownloadBandwidth (a bool). -// docs/runtime_imports.md has the measurement. - -constexpr GUID kSystemClass = {0xe349bd1a, 0xfc20, 0x4e40, {0xb9, 0x9c, 0x41, 0x78, 0xcc, 0x6b, 0x40, 0x9f}}; -// IXSystemImpl's id is the class id; IXSystemImpl5 : IXSystemImpl4 : IXSystemImpl3 : IXSystemImpl2 : IXSystemImpl -// (xgameruntime's include/xsystem.idl). One vtable serves all five. -constexpr GUID kSystem2 = {0x6fd71f09, 0x7513, 0x49f0, {0x89, 0xbc, 0xbf, 0xaf, 0x5d, 0xf6, 0xf8, 0x52}}; -constexpr GUID kSystem3 = {0x67ce4bfc, 0xb1d1, 0x4ac7, {0xbc, 0x3a, 0xcb, 0x92, 0x19, 0xa9, 0x7a, 0x85}}; -constexpr GUID kSystem4 = {0xdadc2895, 0x34b0, 0x4ef5, {0xa8, 0x3e, 0x45, 0x11, 0x4d, 0x62, 0x9b, 0x80}}; -constexpr GUID kSystem5 = {0x1861cf2e, 0xe18b, 0x4834, {0xa9, 0xf5, 0xb4, 0xa4, 0xe6, 0xef, 0xb4, 0xcf}}; -const GUID* const kSystemIids[] = {&kSystem2, &kSystem3, &kSystem4, &kSystem5, nullptr}; - -// A fixed string into a (size, buffer, used) out parameter, as the XSystem id queries take one. `minimum` is the -// buffer size the API requires (its *Bytes constant), which can be larger than the string. -HRESULT copy_id(const char* id, size_t bytes, size_t minimum, size_t size, char* out, size_t* used) { - if (!out) return E_INVALIDARG; - if (size < minimum || size < bytes) return HRESULT_FROM_WIN32(ERROR_INSUFFICIENT_BUFFER); - std::memcpy(out, id, bytes); - if (used) *used = bytes; - return S_OK; -} - -// XSystemXboxLiveSandboxIdMaxBytes is 16, and Microsoft's contract asks for a buffer at least that large (smaller -// ones get ERROR_INSUFFICIENT_BUFFER, whatever the id's length); an offline title runs in the retail sandbox. -constexpr size_t kSandboxIdMaxBytes = 16; -constexpr char kSandboxId[] = "RETAIL"; -static_assert(sizeof(kSandboxId) <= kSandboxIdMaxBytes, "fits XSystemXboxLiveSandboxIdMaxBytes"); -// XSystemAppSpecificDeviceIdBytes is 45 (including the terminator): a fixed placeholder of that length, like the -// console id. -constexpr char kAppDeviceId[] = "00000000000000000000000000000000000000000000"; -static_assert(sizeof(kAppDeviceId) == 45, "fills XSystemAppSpecificDeviceIdBytes"); - -HRESULT STDMETHODCALLTYPE sys_console_id(void*, size_t size, char* out, size_t* used) { - return XSystemGetConsoleId(size, out, used); -} -HRESULT STDMETHODCALLTYPE sys_sandbox_id(void*, size_t size, char* out, size_t* used) { - return copy_id(kSandboxId, sizeof(kSandboxId), kSandboxIdMaxBytes, size, out, used); -} -HRESULT STDMETHODCALLTYPE sys_app_device_id(void*, size_t size, char* out, size_t* used) { - return copy_id(kAppDeviceId, sizeof(kAppDeviceId), sizeof(kAppDeviceId), size, out, used); -} -// XSystemHandleTrack(callback, context): the GDK reports handle creation and destruction to it. Offline nothing is -// tracked, so the callback is accepted and never called. -HRESULT STDMETHODCALLTYPE sys_handle_track(void*, void*, void*) { return S_OK; } -// bool XSystemIsHandleValid(XSystemHandle) and void XSystemAllowFullDownloadBandwidth(bool), as Microsoft documents -// them: a bool, not an HRESULT (S_OK would read as false). -bool STDMETHODCALLTYPE sys_is_handle_valid(void*, void* handle) { return handle != nullptr; } -void STDMETHODCALLTYPE sys_allow_full_download_bandwidth(void*, bool) {} - -const void* const kSystemVtable[] = { - reinterpret_cast(&object_query_interface), reinterpret_cast(&object_add_ref), - reinterpret_cast(&object_release), - reinterpret_cast(&sys_console_id), // 3 XSystemGetConsoleId - reinterpret_cast(&sys_sandbox_id), // 4 XSystemGetXboxLiveSandboxId - reinterpret_cast(&sys_app_device_id), // 5 XSystemGetAppSpecificDeviceId - reinterpret_cast(&sys_handle_track), // 6 XSystemHandleTrack (IXSystemImpl3) - reinterpret_cast(&sys_is_handle_valid), // 7 XSystemIsHandleValid - reinterpret_cast(&sys_allow_full_download_bandwidth), // 8 XSystemAllowFullDownloadBandwidth (4) -}; -static_assert(std::size(kSystemVtable) == 9, "IUnknown + the six methods IXSystemImpl5 is known to have"); - -RuntimeObject& system_object() { - static RuntimeObject object{kSystemVtable, &kSystemClass, kSystemIids}; - return object; -} - -// XVersion: 4-part version structure from GDK XGameRuntimeTypes.h (8 bytes) -struct alignas(8) XVersion { - uint16_t major; - uint16_t minor; - uint16_t build; - uint16_t revision; -}; -static_assert(sizeof(XVersion) == 8, "XVersion must be 8 bytes"); - -// XSystemAnalyticsInfo: hardware and OS version telemetry (144 bytes) -struct XSystemAnalyticsInfo { - XVersion osVersion; - XVersion hostingOsVersion; - char family[64]; - char form[64]; -}; -static_assert(sizeof(XSystemAnalyticsInfo) == 144, "XSystemAnalyticsInfo must be 144 bytes"); - -static void copy_string_padded(char* dst, size_t dst_cap, const char* src) { - if (!dst || dst_cap == 0) return; - std::memset(dst, 0, dst_cap); - if (!src) return; - const size_t len = std::strlen(src); - const size_t copy_len = len < dst_cap - 1 ? len : dst_cap - 1; - std::memcpy(dst, src, copy_len); -} - -// XSystemAnalyticsInfo XSystemGetAnalyticsInfo() -// Returned by value per Microsoft GDK specification. -XSystemAnalyticsInfo __stdcall XSystemGetAnalyticsInfo() { - XSystemAnalyticsInfo info{}; - info.osVersion = {10, 0, 22000, 0}; - info.hostingOsVersion = {10, 0, 22000, 0}; - copy_string_padded(info.family, sizeof(info.family), "Xbox"); - - const uint32_t dt = XSystemGetDeviceType(); - if (dt == static_cast(XSystemDeviceType::XboxScarlettLockhart)) { - copy_string_padded(info.form, sizeof(info.form), "Xbox Series S"); - } else { - copy_string_padded(info.form, sizeof(info.form), "Xbox Series X"); - } - - // A form of 64 characters or more is ignored, as before the setting moved to the table. - const std::string form_override = rt::config::get("system.analytics_form").text; - if (!form_override.empty() && form_override.size() < 64) { - copy_string_padded(info.form, sizeof(info.form), form_override.c_str()); - } - return info; -} - -// ---- XPackage ---- - -constexpr size_t XPACKAGE_IDENTIFIER_MAX_LENGTH = 33; -constexpr char kDefaultPackageIdentifier[XPACKAGE_IDENTIFIER_MAX_LENGTH] = "LeonidaPackageIdentifier00000000"; -static_assert(sizeof(kDefaultPackageIdentifier) == XPACKAGE_IDENTIFIER_MAX_LENGTH, - "default package identifier must match XPACKAGE_IDENTIFIER_MAX_LENGTH"); - -// The identifier of the running package: system.package_id (LEONIDA_PACKAGE_ID). A value too long for an -// identifier is ignored and the default is used, as before the setting moved to the table. -static std::string configured_package_identifier() { - std::string id = rt::config::get("system.package_id").text; - if (id.empty() || id.size() >= XPACKAGE_IDENTIFIER_MAX_LENGTH) id = kDefaultPackageIdentifier; - return id; -} - -// HRESULT XPackageGetCurrentProcessPackageIdentifier(size_t bufferSize, char* buffer). -// Retrieves the package identifier string for the current process. -HRESULT __stdcall XPackageGetCurrentProcessPackageIdentifier(size_t bufferSize, char* buffer) { - if (!buffer || bufferSize == 0) return E_INVALIDARG; - - const std::string id = configured_package_identifier(); - const char* selected = id.c_str(); - const size_t len = id.size(); - - if (bufferSize < len + 1) return HRESULT_FROM_WIN32(ERROR_INSUFFICIENT_BUFFER); - std::memcpy(buffer, selected, len + 1); - return S_OK; -} - -// XPackageMountHandle: opaque 64-bit mount handle per GDK XPackage.h -struct XPackageMountHandle { - uint64_t handle; -}; - -static std::mutex s_mount_mutex; -static std::atomic s_next_mount_id{1}; -static std::unordered_map s_active_mounts; - -// Resolves the installation path for a specific content package identifier. -// GDK specifies that XPackageMount is only for content packages; mounting the main game returns E_ACCESSDENIED. -// Returns HRESULT_FROM_WIN32(ERROR_NOT_FOUND) if the package identifier is not installed. -static std::string resolve_package_path(const char* packageIdentifier, HRESULT& result) { - - // Check against configured process/game package identifier; mounting the game itself is denied - if (configured_package_identifier() == packageIdentifier) { - result = E_ACCESSDENIED; - return {}; - } - - // Check optional installed content packages mapping: "id1=path1;id2=path2" - // The table gives UTF-8, which is what the GDK returns even when Windows uses a legacy ANSI code page. - if (std::string mapping = rt::config::get("system.content_packages").text; !mapping.empty()) { - char* token = mapping.data(); - while (token && *token) { - char* sep = std::strchr(token, ';'); - if (sep) *sep = '\0'; - char* eq = std::strchr(token, '='); - if (eq) { - *eq = '\0'; - if (std::strcmp(token, packageIdentifier) == 0) { - result = S_OK; - return eq + 1; - } - } - token = sep ? sep + 1 : nullptr; - } - } - - result = HRESULT_FROM_WIN32(ERROR_NOT_FOUND); - return {}; -} - -// HRESULT XPackageMount(const char* packageIdentifier, XPackageMountHandle* mount) -// Mounts an installed content package given its identifier and yields a valid mount handle. -// Returns ERROR_NOT_FOUND if the package identifier is not recognized/installed. -HRESULT __stdcall XPackageMount(const char* packageIdentifier, XPackageMountHandle* mount) { - if (!packageIdentifier || !mount) return E_INVALIDARG; - mount->handle = 0; - - HRESULT hr; - const std::string path = resolve_package_path(packageIdentifier, hr); - if (FAILED(hr)) return hr; - - const uint64_t id = s_next_mount_id.fetch_add(1); - { - std::lock_guard lock(s_mount_mutex); - s_active_mounts[id] = path; - } - mount->handle = id; - return S_OK; -} - -// void XPackageCloseMountHandle(XPackageMountHandle mount) -// Closes a previously mounted package handle. -void __stdcall XPackageCloseMountHandle(XPackageMountHandle mount) { - if (mount.handle == 0) return; - std::lock_guard lock(s_mount_mutex); - s_active_mounts.erase(mount.handle); -} - -// HRESULT XPackageGetMountPathSize(XPackageMountHandle mount, size_t* pathSize). -// Retrieves the size of the buffer needed to store the mounted package path, including the null terminator. -HRESULT __stdcall XPackageGetMountPathSize(XPackageMountHandle mount, size_t* pathSize) { - if (mount.handle == 0 || !pathSize) return E_INVALIDARG; - - std::string path; - { - std::lock_guard lock(s_mount_mutex); - auto it = s_active_mounts.find(mount.handle); - if (it == s_active_mounts.end()) return HRESULT_FROM_WIN32(ERROR_NOT_FOUND); - path = it->second; - } - - *pathSize = path.size() + 1; - return S_OK; -} - -// HRESULT XPackageGetMountPath(XPackageMountHandle mount, size_t pathSize, char* path). -// Retrieves the installed filesystem path for the mounted package. -HRESULT __stdcall XPackageGetMountPath(XPackageMountHandle mount, size_t pathSize, char* path) { - if (mount.handle == 0 || !path || pathSize == 0) return E_INVALIDARG; - - std::string mount_path; - { - std::lock_guard lock(s_mount_mutex); - auto it = s_active_mounts.find(mount.handle); - if (it == s_active_mounts.end()) return HRESULT_FROM_WIN32(ERROR_NOT_FOUND); - mount_path = it->second; - } - - if (pathSize < mount_path.size() + 1) return HRESULT_FROM_WIN32(ERROR_INSUFFICIENT_BUFFER); - std::memcpy(path, mount_path.c_str(), mount_path.size() + 1); - return S_OK; -} - -// bool XPackageIsPackagedProcess(). -// Returns true on Xbox Series console. LEONIDA_PACKAGED=0 overrides it. -bool __stdcall XPackageIsPackagedProcess() { - // A value of 16 characters or more is ignored, as before the setting moved to the table. - const std::string s = rt::config::get("system.packaged").text; - if (s.size() < 16 && std::atoi(s.c_str()) == 0) return false; - return true; -} - -// ---- XPackageImpl (asked for as IXPackageImpl3), offline ---- -// -// libHttpClient.GDK.dll asks QueryApiImpl for XPackageImpl with IXPackageImpl3's id through 30 thunks (slots 3-19, -// 22, 24-27, 30, 32-34, 37-40), each in the argument shape of the method at that position of xgameruntime-docs' -// IXPackageImpl (slots 3-34), IXPackageImpl2 (35-38) and IXPackageImpl3 (39-40) lists (docs/runtime_imports.md). -// The slots with an offline answer forward to the XPackage functions above (the package identifier, whether the -// process is packaged, the mount path and its size, the user's locale); every other slot logs its number once and -// returns E_NOTIMPL, so the first boot shows which ones the title needs. - -constexpr GUID kPackageClass = {0xaf406016, 0xe850, 0x4aa8, {0xa8, 0x8d, 0x2f, 0x3d, 0xcb, 0x9d, 0xac, 0x7e}}; -// IXPackageImpl3 : IXPackageImpl2 : IXPackageImpl (xgameruntime include/xpackage.idl); the class id is its own. -constexpr GUID kPackage1 = {0x3720de07, 0xe8e4, 0x44a3, {0xad, 0x32, 0xb3, 0x59, 0xe8, 0xad, 0xbe, 0x55}}; -constexpr GUID kPackage2 = {0xf92d8712, 0x2b27, 0x4d8a, {0xbf, 0x01, 0x11, 0xa6, 0xf8, 0xe3, 0xeb, 0x42}}; -constexpr GUID kPackage3 = {0xe2a4734b, 0x2f4a, 0x456d, {0xaa, 0x8f, 0xd0, 0x65, 0xe0, 0x4f, 0xb2, 0x09}}; -const GUID* const kPackageIids[] = {&kPackage1, &kPackage2, &kPackage3, nullptr}; - -template HRESULT STDMETHODCALLTYPE package_not_implemented(void*) { - static std::atomic s_logged{false}; - if (!s_logged.exchange(true)) - RT_LOG_WARN("xgameruntime: XPackageImpl slot %d not implemented offline (E_NOTIMPL)\n", Slot); - return E_NOTIMPL; -} -HRESULT STDMETHODCALLTYPE pkg_identifier(void*, size_t size, char* buffer) { - return XPackageGetCurrentProcessPackageIdentifier(size, buffer); -} -bool STDMETHODCALLTYPE pkg_is_packaged(void*) { return XPackageIsPackagedProcess(); } -// The package's MicrosoftGame.Config as text, from the game folder (LEONIDA_GAME_DIR, else --game-dir); empty when -// there is no folder or no config. Wide on purpose: a game folder named outside the ANSI code page must reach the file -// intact. -std::string package_config() { - // A folder of MAX_PATH characters or more is ignored, as before the setting moved to the table. - std::filesystem::path dir = rt::config::path("paths.game_dir"); - if (dir.empty() || dir.native().size() >= MAX_PATH) dir = rt::fs::game_dir(); - if (dir.empty()) return {}; - std::ifstream f(dir / L"MicrosoftGame.Config", std::ios::binary); - if (!f) return {}; - return std::string{std::istreambuf_iterator(f), {}}; -} - -// The locales the package declares: in MicrosoftGame.Config, read from -// the game folder (LEONIDA_GAME_DIR, else --game-dir). Empty when there is no config or it declares none. -// A inside an XML comment is not declared (Microsoft's config template ships commented-out entries), XML -// allows whitespace around an attribute's '=', and only an attribute named exactly Language on an element named -// exactly Resource counts. -std::vector package_locales() { - std::vector out; - const std::string raw = package_config(); - if (raw.empty()) return out; - std::string xml; // the config without its comments; an unterminated comment runs to the end of the file - xml.reserve(raw.size()); - for (size_t at = 0; at < raw.size();) { - const size_t open = raw.find("", open + 4); - if (close == std::string::npos) break; - at = close + 3; - } - const auto space = [](char c) { return c == ' ' || c == '\t' || c == '\r' || c == '\n'; }; - const auto skip_space = [&](size_t p) { - while (p < xml.size() && space(xml[p])) ++p; - return p; - }; - for (size_t at = 0; (at = xml.find(", ... - // The attributes, name = "value" or name = 'value', up to the tag's end; a malformed one ends the tag. - for (p = skip_space(p); p < xml.size() && xml[p] != '>' && xml[p] != '/'; p = skip_space(p)) { - const size_t name = p; - while (p < xml.size() && !space(xml[p]) && xml[p] != '=' && xml[p] != '>' && xml[p] != '/') ++p; - const size_t name_end = p; - p = skip_space(p); - if (p >= xml.size() || xml[p] != '=') break; - p = skip_space(p + 1); - if (p >= xml.size() || (xml[p] != '"' && xml[p] != '\'')) break; - const size_t close = xml.find(xml[p], p + 1); - if (close == std::string::npos) break; - if (xml.compare(name, name_end - name, "Language") == 0) out.push_back(xml.substr(p + 1, close - p - 1)); - p = close + 1; - } - } - return out; -} - -// XPackageGetUserLocale(size_t localeSize, char* locale): of the locales the package declares, the one closest to -// the user's (the same name, else the same language, else the first declared). Microsoft's contract: "If no locale -// information is declared for the package, this function succeeds but does not return a user locale". The host's -// locale is never handed out as the package's. -HRESULT STDMETHODCALLTYPE pkg_user_locale(void*, size_t size, char* locale) { - if (!locale || !size) return E_INVALIDARG; - const std::vector declared = package_locales(); - if (declared.empty()) { - locale[0] = '\0'; - return S_OK; - } - wchar_t wide[LOCALE_NAME_MAX_LENGTH] = {}; - char user[LOCALE_NAME_MAX_LENGTH * 4] = ""; - if (GetUserDefaultLocaleName(wide, LOCALE_NAME_MAX_LENGTH) > 0) - WideCharToMultiByte(CP_UTF8, 0, wide, -1, user, static_cast(sizeof(user)), nullptr, nullptr); - const auto language = [](const std::string& name) { return name.substr(0, name.find('-')); }; - const auto same = [](const std::string& a, const std::string& b) { return _stricmp(a.c_str(), b.c_str()) == 0; }; - const std::string* pick = &declared.front(); - bool exact = false; - for (const std::string& d : declared) - if (same(d, user)) { pick = &d; exact = true; break; } - if (!exact) - for (const std::string& d : declared) - if (same(language(d), language(user))) { pick = &d; break; } - if (size < pick->size() + 1) return HRESULT_FROM_WIN32(ERROR_INSUFFICIENT_BUFFER); - std::memcpy(locale, pick->c_str(), pick->size() + 1); - return S_OK; -} -// Slots 23-26 forward to the named exports' content-package mounts (XPackageMount and its handle registry), so the two -// ways in behave the same. XPackageMountHandle is one u64, passed in a register like the named exports take it. -HRESULT STDMETHODCALLTYPE pkg_mount(void*, const char* package_identifier, XPackageMountHandle* mount) { - return XPackageMount(package_identifier, mount); -} -HRESULT STDMETHODCALLTYPE pkg_mount_path_size(void*, XPackageMountHandle mount, size_t* size) { - return XPackageGetMountPathSize(mount, size); -} -HRESULT STDMETHODCALLTYPE pkg_mount_path(void*, XPackageMountHandle mount, size_t size, char* path) { - return XPackageGetMountPath(mount, size, path); -} -void STDMETHODCALLTYPE pkg_close_mount(void*, XPackageMountHandle mount) { XPackageCloseMountHandle(mount); } - -// XPackageInstallationProgress: totalBytes, installedBytes, launchBytes (u64), launchable, completed (bool). -struct InstallationProgress { - uint64_t total_bytes, installed_bytes, launch_bytes; - bool launchable, completed; -}; -static_assert(sizeof(InstallationProgress) == 32, "XPackageInstallationProgress layout"); -// void XPackageGetInstallationProgress(monitor, XPackageInstallationProgress*): an offline package is installed, -// launchable and completed, every byte present. -void STDMETHODCALLTYPE pkg_installation_progress(void*, void*, InstallationProgress* progress) { - if (progress) *progress = {0, 0, 0, true, true}; -} -// The bool methods with no offline work, as Microsoft documents them: XPackageUpdateInstallationMonitor is false -// (nothing changed), the two Unregister* calls are true (nothing pending), XPackageUninstallPackage is false (not -// uninstalled). A generic E_NOTIMPL stub would read as true in al. -bool STDMETHODCALLTYPE pkg_update_monitor(void*, void*) { return false; } -bool STDMETHODCALLTYPE pkg_unregister_progress(void*, void*, XTaskQueueRegistrationToken, bool) { return true; } -bool STDMETHODCALLTYPE pkg_unregister_installed(void*, XTaskQueueRegistrationToken, bool) { return true; } -bool STDMETHODCALLTYPE pkg_uninstall_package(void*, const char*) { return false; } - -#define PN(n) reinterpret_cast(&package_not_implemented) -const void* const kPackageVtable[] = { - reinterpret_cast(&object_query_interface), reinterpret_cast(&object_add_ref), - reinterpret_cast(&object_release), - reinterpret_cast(&pkg_identifier), // 3 XPackageGetCurrentProcessPackageIdentifier - reinterpret_cast(&pkg_is_packaged), // 4 XPackageIsPackagedProcess - PN(5), PN(6), // 5-6 installation monitor: create, close - reinterpret_cast(&pkg_installation_progress), // 7 XPackageGetInstallationProgress (void, writes) - reinterpret_cast(&pkg_update_monitor), // 8 XPackageUpdateInstallationMonitor (bool) - PN(9), // 9 XPackageRegisterInstallationProgressChanged - reinterpret_cast(&pkg_unregister_progress), // 10 ...UnregisterInstallationProgressChanged (bool) - reinterpret_cast(&pkg_user_locale), // 11 XPackageGetUserLocale - PN(12), PN(13), PN(14), PN(15), PN(16), PN(17), // 12-19 chunks: find / enumerate availability, change order, - PN(18), PN(19), // install (+ async, result), estimate size, uninstall - PN(20), PN(21), // 20-21 _unknown_ (older enumerate / register installed) - reinterpret_cast(&pkg_unregister_installed), // 22 XPackageUnregisterPackageInstalled (bool) - reinterpret_cast(&pkg_mount), // 23 XPackageMount - reinterpret_cast(&pkg_mount_path_size), // 24 XPackageGetMountPathSize - reinterpret_cast(&pkg_mount_path), // 25 XPackageGetMountPath - reinterpret_cast(&pkg_close_mount), // 26 XPackageCloseMountHandle - PN(27), PN(28), PN(29), PN(30), PN(31), // 27 _unknown_, 28 EnumeratePackages, 29 RegisterPackageInstalled, - // 30 GetWriteStats, 31 _unknown_ - PN(32), PN(33), // 32 UninstallUWPInstance, 33 EnumerateFeatures - reinterpret_cast(&pkg_uninstall_package), // 34 XPackageUninstallPackage (bool) - PN(35), PN(36), PN(37), PN(38), // IXPackageImpl2: EnumeratePackages, RegisterPackageInstalled, - // MountWithUiAsync, MountWithUiResult - PN(39), PN(40), // IXPackageImpl3: EnumeratePackages, RegisterPackageInstalled -}; -#undef PN -static_assert(std::size(kPackageVtable) == 41, "IUnknown + IXPackageImpl's 32 + IXPackageImpl2's 4 + IXPackageImpl3's 2"); - -RuntimeObject& package_object() { - static RuntimeObject object{kPackageVtable, &kPackageClass, kPackageIids}; - return object; -} - -// ---- XGameImpl (asked for as IXGameImpl3), offline ---- -// -// IXGameImpl3 : IXGameImpl2 : IXGameImpl (xgameruntime include/xgame.idl); the class id is IXGameImpl's. Three -// methods after IUnknown: 3 XGameGetXboxTitleId (IXGameImpl), 4 XLaunchNewGame (IXGameImpl2), 5 XLaunchRestartOnCrash -// (IXGameImpl3). A retail Gen9 title asks QueryApiImpl for this class (Freminet/ScarlettX's README, observed on -// Concept Destruction); the executable here is not available yet, so its own requests are unmeasured. - -constexpr GUID kGameClass = {0x973a344e, 0x24bf, 0x4d0f, {0x84, 0x57, 0x56, 0xc5, 0x34, 0x89, 0x2b, 0x29}}; -constexpr GUID kGame2 = {0x50849859, 0x0ad8, 0x4f81, {0x80, 0xe4, 0x5b, 0xc7, 0x86, 0x26, 0xf8, 0x52}}; -constexpr GUID kGame3 = {0x2549f142, 0x6419, 0x4a06, {0x97, 0xb5, 0x93, 0x1a, 0xab, 0x7c, 0x2f, 0x34}}; -const GUID* const kGameIids[] = {&kGame2, &kGame3, nullptr}; - -// The title id MicrosoftGame.Config declares (, eight hex digits), or false when there is none or it is not -// hex. The first element counts; surrounding whitespace is allowed. -bool package_title_id(uint32_t& out) { - const std::string xml = package_config(); - const size_t open = xml.find(""); - if (open == std::string::npos) return false; - const size_t begin = xml.find_first_not_of(" \t\r\n", open + 9); - const size_t close = xml.find("", open); - if (begin == std::string::npos || close == std::string::npos || begin >= close) return false; - size_t end = close; - while (end > begin && std::isspace(static_cast(xml[end - 1]))) --end; - if (end - begin == 0 || end - begin > 8) return false; - uint32_t value = 0; - for (size_t i = begin; i < end; ++i) { - const char c = xml[i]; - const int digit = c >= '0' && c <= '9' ? c - '0' : c >= 'a' && c <= 'f' ? c - 'a' + 10 - : c >= 'A' && c <= 'F' ? c - 'A' + 10 : -1; - if (digit < 0) return false; - value = value << 4 | static_cast(digit); - } - out = value; - return true; -} - -// HRESULT XGameGetXboxTitleId(uint32_t* titleId): the package's title id. Without a config that declares one there -// is no title id to give (E_FAIL), rather than a made-up one. -HRESULT STDMETHODCALLTYPE game_get_title_id(void*, uint32_t* title_id) { - if (!title_id) return E_INVALIDARG; - uint32_t id = 0; - if (!package_title_id(id)) { - static std::atomic s_logged{false}; - if (!s_logged.exchange(true)) - RT_LOG_ERROR("xgameruntime: XGameGetXboxTitleId: no in MicrosoftGame.Config\n"); - return E_FAIL; - } - *title_id = id; - return S_OK; -} - -// void XLaunchNewGame(const char* exePath, const char* args, XUserHandle defaultUser): on the console this ends the -// title and starts another. Offline there is no other title to start; the call is logged and returns. -void STDMETHODCALLTYPE game_launch_new(void*, const char* exe_path, const char* args, void*) { - RT_LOG_WARN("xgameruntime: XLaunchNewGame(\"%s\", \"%s\") ignored offline\n", - exe_path ? exe_path : "", args ? args : ""); -} - -// HRESULT XLaunchRestartOnCrash(const char* args, uint32_t reserved): asks the console to restart the title after a -// crash. Nothing restarts the process here; it succeeds with nothing registered. -HRESULT STDMETHODCALLTYPE game_restart_on_crash(void*, const char*, uint32_t) { - static std::atomic s_logged{false}; - if (!s_logged.exchange(true)) - RT_LOG_WARN("xgameruntime: XLaunchRestartOnCrash: no restart is registered offline\n"); - return S_OK; -} - -const void* const kGameVtable[] = { - reinterpret_cast(&object_query_interface), reinterpret_cast(&object_add_ref), - reinterpret_cast(&object_release), - reinterpret_cast(&game_get_title_id), // 3 XGameGetXboxTitleId (IXGameImpl) - reinterpret_cast(&game_launch_new), // 4 XLaunchNewGame (IXGameImpl2, void) - reinterpret_cast(&game_restart_on_crash), // 5 XLaunchRestartOnCrash (IXGameImpl3) -}; -static_assert(std::size(kGameVtable) == 6, "IUnknown + IXGameImpl3's 3 methods"); - -RuntimeObject& game_object() { - static RuntimeObject object{kGameVtable, &kGameClass, kGameIids}; - return object; -} - -// ---- XGameRuntimeFeatureImpl, XSystemAnalyticsImpl ---- -// -// Measured with tools/gdk_runtime_calls.py, which finds xgameruntime.lib's thunks in an image's code without running -// it: for each class, the interface id the thunks ask QueryApiImpl for, the slots they call and the number of -// arguments each passes after `this`. On the package's libHttpClient.GDK.dll every slot below is the function at that -// position of the interface's "Layout" list in xodus-gaming/xgameruntime-docs (GPL-3.0; facts only), and the measured -// argument count is the documented one. Signatures and semantics are Microsoft's public GDK reference pages, -// learn.microsoft.com/gaming/gdk/docs/reference/system//functions/, cited per function as -// /. -// The thunks are in libHttpClient.GDK.dll but nothing there calls them; a title linked with the same xgameruntime.lib -// reaches these classes through the same thunks. docs/runtime_imports.md has the table. - -#define VT(fn) reinterpret_cast(&fn) - -// XSystemAnalyticsImpl (IXSystemAnalyticsImpl, whose id is the class id): slot 3 is -// XSystemAnalyticsInfo XSystemGetAnalyticsInfo() (xsystem/xsystemgetanalyticsinfo) -// The one argument measured after `this` is where the result goes: a member function returning a struct takes its -// address after `this` and returns it (MSVC x64), and the thunk copies the struct out of the returned pointer. The -// answer is the named export's. -constexpr GUID kSystemAnalyticsClass = {0xb884675d, 0xb738, 0x4a9c, {0x81, 0x5d, 0x9a, 0x9a, 0x1e, 0x0c, 0x6c, 0x9b}}; - -XSystemAnalyticsInfo* STDMETHODCALLTYPE system_analytics_info(void*, XSystemAnalyticsInfo* result) { - if (result) *result = XSystemGetAnalyticsInfo(); - return result; -} - -const void* const kSystemAnalyticsVtable[] = { - VT(object_query_interface), VT(object_add_ref), VT(object_release), - VT(system_analytics_info), // 3 -}; - -// XGameRuntimeFeatureImpl (IXGameRuntimeFeatureImpl, whose id is the class id): slot 3 is -// bool XGameRuntimeIsFeatureAvailable(XGameRuntimeFeature feature) -// (xgameruntimefeature/xgameruntimeisfeatureavailable), measured with one 32-bit argument and a byte result. -// XGameRuntimeFeature : uint32_t has the values of Microsoft's enum page, XAccessibility = 0 to XGameStreaming = 21. -// Offline a feature is available when both hold: -// - QueryApiImpl serves the class its functions go through (xgameruntime-docs' layouts), from this file or another -// xgameruntime_*.cpp, so a call can reach it; the answer follows each class as it is served; -// - Microsoft documents it for Windows: an offline PC lacks what is documented only for the consoles (XDisplay: -// xdisplay/xdisplaytryenablehdrmode lists only the Xbox consoles as supported platforms). -// Values past the enum are false. -constexpr GUID kGameRuntimeFeatureClass = {0x8836fe87, 0xedb9, 0x4fe3, {0x8d, 0xad, 0x05, 0xf0, 0xd2, 0xcd, 0x5b, 0x40}}; - -// The classes no object in this file stands for; the other files serve some of them. Named ...ClassId, not ...Class, -// because tools/gdk_runtime_calls.py counts every `constexpr GUID k...Class` in these files as a served class. -constexpr GUID kAccessibilityClassId = {0x3e241977, 0x6237, 0x41e9, {0x85, 0x59, 0x10, 0x2c, 0x2d, 0x99, 0x83, 0xf1}}; -constexpr GUID kAppCaptureClassId = {0xa4f1aee2, 0x4bf1, 0x4485, {0xb0, 0x08, 0xa7, 0xc2, 0x6d, 0x52, 0xac, 0x27}}; -constexpr GUID kDisplayClassId = {0x03f0fe74, 0xfdd9, 0x4e5c, {0xb6, 0x30, 0xf9, 0x33, 0x9c, 0x47, 0xac, 0xc5}}; -constexpr GUID kGameEventClassId = {0xbbfbdcc7, 0xbfe7, 0x409b, {0xa5, 0xca, 0xed, 0xf0, 0x54, 0x96, 0x0b, 0x4d}}; -constexpr GUID kGameInviteClassId = {0x0651aae2, 0x4012, 0x4077, {0xbf, 0x84, 0x8b, 0x90, 0x97, 0x09, 0x0e, 0x2c}}; -constexpr GUID kGameSaveClassId = {0x704c3f58, 0xe629, 0x4cc2, {0xb1, 0x97, 0x30, 0x51, 0x1b, 0x99, 0x6f, 0xe2}}; -constexpr GUID kGameStreamingClassId = {0x0a2192aa, 0xb2d5, 0x4d58, {0x83, 0xbe, 0x38, 0x3b, 0x6d, 0x80, 0x79, 0x9e}}; -constexpr GUID kGameUiClassId = {0xdfcd4649, 0x4ff8, 0x4043, {0xba, 0x07, 0x35, 0xd6, 0x07, 0xdf, 0x98, 0xb0}}; -constexpr GUID kLauncherClassId = {0x1b339674, 0x328d, 0x4283, {0xa2, 0x00, 0x31, 0x71, 0xf1, 0x8d, 0x36, 0x39}}; -constexpr GUID kStoreClassId = {0x0dd112ac, 0x7c24, 0x448c, {0xb9, 0x2b, 0x39, 0x60, 0xfb, 0x5b, 0xd3, 0x0c}}; -constexpr GUID kUserClassId = {0x01acd177, 0x91f9, 0x4763, {0xa3, 0x8e, 0xcc, 0xbb, 0x55, 0xce, 0x32, 0xe0}}; - -struct RuntimeFeature { - const GUID* class_id; // the class the feature's functions go through - bool console_only; // documented for the Xbox consoles only -}; -const RuntimeFeature kRuntimeFeatures[] = { - {&kAccessibilityClassId, false}, // 0 XAccessibility - {&kAppCaptureClassId, false}, // 1 XAppCapture - {&kThreadingClass, false}, // 2 XAsync - {&kThreadingClass, false}, // 3 XAsyncProvider - {&kDisplayClassId, true}, // 4 XDisplay - {&kGameClass, false}, // 5 XGame - {&kGameInviteClassId, false}, // 6 XGameInvite - {&kGameSaveClassId, false}, // 7 XGameSave - {&kGameUiClassId, false}, // 8 XGameUI - {&kLauncherClassId, false}, // 9 XLauncher - {&kNetworkingClass, false}, // 10 XNetworking - {&kPackageClass, false}, // 11 XPackage - {&kPersistentStorageClass, false}, // 12 XPersistentLocalStorage - {&kAccessibilityClassId, false}, // 13 XSpeechSynthesizer (IXAccessibilityImpl holds its functions) - {&kStoreClassId, false}, // 14 XStore - {&kSystemClass, false}, // 15 XSystem - {&kThreadingClass, false}, // 16 XTaskQueue - {&kThreadingClass, false}, // 17 XThread - {&kUserClassId, false}, // 18 XUser - {&kErrorClass, false}, // 19 XError - {&kGameEventClassId, false}, // 20 XGameEvent - {&kGameStreamingClassId, false}, // 21 XGameStreaming -}; -static_assert(std::size(kRuntimeFeatures) == 22, "XGameRuntimeFeature has 22 values"); - -bool STDMETHODCALLTYPE runtime_is_feature_available(void*, uint32_t feature) { - if (feature >= std::size(kRuntimeFeatures)) return false; - const RuntimeFeature& f = kRuntimeFeatures[feature]; - return !f.console_only && class_served(*f.class_id); -} - -const void* const kGameRuntimeFeatureVtable[] = { - VT(object_query_interface), VT(object_add_ref), VT(object_release), - VT(runtime_is_feature_available), // 3 -}; -#undef VT - -RuntimeObject g_game_runtime_feature{kGameRuntimeFeatureVtable, &kGameRuntimeFeatureClass, nullptr}; -RuntimeObject g_system_analytics{kSystemAnalyticsVtable, &kSystemAnalyticsClass, nullptr}; - -RuntimeObject* const* measured_objects() { - static RuntimeObject* const objects[] = {&g_game_runtime_feature, &g_system_analytics, nullptr}; - return objects; -} - -#define XGR(name) {"xgameruntime.dll", #name, reinterpret_cast(&name)} - -} // namespace - -SHIM_TABLE(xgameruntime, - // what xgameruntime.lib's thunks GetProcAddress (library_loader.cpp serves the LoadLibrary before it) - XGR(InitializeApiImpl), - XGR(InitializeApiImplEx), - XGR(InitializeApiImplEx2), - XGR(UninitializeApiImpl), - XGR(QueryApiImpl), - XGR(XErrorReport), - // the same runtime through gameplatformservices.dll, which XCurl.dll loads from System32 (GetApiVersionImpl above) - {"gameplatformservices.dll", "QueryApiImpl", reinterpret_cast(&QueryApiImpl)}, - {"gameplatformservices.dll", "GetApiVersionImpl", reinterpret_cast(&GetApiVersionImpl)}, - XGR(XGameRuntimeInitialize), - XGR(XGameRuntimeUninitialize), - XGR(XSystemGetDeviceType), - XGR(XSystemGetConsoleId), - XGR(XSystemGetAppMemoryUsageLimit), - XGR(XSystemGetAppMemoryUsage), - XGR(XSystemGetAnalyticsInfo), - XGR(XPackageGetCurrentProcessPackageIdentifier), - XGR(XPackageMount), - XGR(XPackageCloseMountHandle), - XGR(XPackageGetMountPathSize), - XGR(XPackageGetMountPath), - XGR(XPackageIsPackagedProcess), - // XTaskQueue (third_party/xtaskqueue) - XGR(XTaskQueueCreate), - XGR(XTaskQueueCreateComposite), - XGR(XTaskQueueGetPort), - XGR(XTaskQueueDuplicateHandle), - XGR(XTaskQueueCloseHandle), - XGR(XTaskQueueTerminate), - XGR(XTaskQueueDispatch), - XGR(XTaskQueueSubmitCallback), - XGR(XTaskQueueSubmitDelayedCallback), - XGR(XTaskQueueRegisterWaiter), - XGR(XTaskQueueUnregisterWaiter), - XGR(XTaskQueueRegisterMonitor), - XGR(XTaskQueueUnregisterMonitor), - XGR(XTaskQueueGetCurrentProcessTaskQueue), - XGR(XTaskQueueSetCurrentProcessTaskQueue), - // XAsync (third_party/xtaskqueue) - XGR(XAsyncGetStatus), - XGR(XAsyncGetResultSize), - XGR(XAsyncCancel), - XGR(XAsyncRun), - XGR(XAsyncBegin), - XGR(XAsyncSchedule), - XGR(XAsyncComplete), - XGR(XAsyncGetResult), -); diff --git a/runtime/shims/xgameruntime_gamesave.cpp b/runtime/shims/xgameruntime_gamesave.cpp deleted file mode 100644 index 1fdc2f774..000000000 --- a/runtime/shims/xgameruntime_gamesave.cpp +++ /dev/null @@ -1,993 +0,0 @@ -// xgameruntime: XGameSaveImpl, the class xgameruntime.lib's XGameSave* functions reach through QueryApiImpl, offline. -// -// A GDK title opens its save provider during boot (XGameSaveInitializeProvider), then reads and writes containers -// of named blobs. Each XGameSave* function in xgameruntime.lib asks QueryApiImpl for XGameSaveImpl and calls one slot -// with its own arguments after `this`. The class and interface ids and the slot order are -// xodus-gaming/xgameruntime-docs' "Layout" lists (GPL-3.0; facts only, nothing copied). Signatures, limits and error -// codes follow Microsoft's public GDK reference (learn.microsoft.com/gaming/gdk: the XGameSave function pages and -// "Error codes"). No GDK header or library code is used. -// -// Offline the saves are files, in the layout tools/saves.py imports into (docs/saves.md): -// \local-user\\ root = LEONIDA_SAVE_DIR, else %LOCALAPPDATA%\Leonida\saves -// Container and blob names are %-encoded: [A-Za-z0-9_-] and '.' (except as the first character) stay, every other -// UTF-8 byte becomes %XX. A container's display name is kept in "\.display", which no encoded blob name -// can collide with (an encoded name never starts with '.'). Names ending in '~' are temporary files of an update in -// progress; an encoded name never ends in '~' either. -// -// An update buffers its writes and deletes; SubmitUpdate writes every new blob to "~", then renames each over -// its blob and removes the deleted ones, so a failed write leaves the container as it was. -// -// ASSUMPTION (no executable yet): the quota is a fixed 1 GiB (the GDK says the per-user quota "is not a fixed size"); -// a blob name is at most 256 bytes (GS_MAX_BLOB_NAME_SIZE is not on the public pages); GetContainerInfo of a -// container that does not exist returns S_OK without calling the callback; ReadBlobData with blobNames = nullptr -// reads every blob of the container. syncOnDemand is accepted and ignored: nothing syncs offline. -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include -#include -#include - -#include "../core/config.h" -#include "../core/log.h" - -namespace { - -namespace fs = std::filesystem; - -// ---- Public GDK types (XGameSave.h, as the GDK reference documents them) ---- - -using XUserHandle = void*; -struct XGameSaveProvider; -struct XGameSaveContainer; -struct XGameSaveUpdate; -using XGameSaveProviderHandle = XGameSaveProvider*; -using XGameSaveContainerHandle = XGameSaveContainer*; -using XGameSaveUpdateHandle = XGameSaveUpdate*; - -struct XGameSaveContainerInfo { - const char* name; - const char* displayName; - uint32_t blobCount; - uint64_t totalSize; - time_t lastModifiedTime; - bool needsSync; -}; -struct XGameSaveBlobInfo { - const char* name; - uint32_t size; -}; -struct XGameSaveBlob { - XGameSaveBlobInfo info; - uint8_t* data; -}; -using ContainerInfoCallback = bool(CALLBACK*)(const XGameSaveContainerInfo* info, void* context); -using BlobInfoCallback = bool(CALLBACK*)(const XGameSaveBlobInfo* info, void* context); - -// XGameErr.h values, from the GDK "Error codes" page (Game save). -constexpr HRESULT E_GS_INVALID_CONTAINER_NAME = static_cast(0x80830001); -constexpr HRESULT E_GS_OUT_OF_LOCAL_STORAGE = static_cast(0x80830003); -constexpr HRESULT E_GS_UPDATE_TOO_BIG = static_cast(0x80830005); -constexpr HRESULT E_GS_QUOTA_EXCEEDED = static_cast(0x80830006); -constexpr HRESULT E_GS_PROVIDED_BUFFER_TOO_SMALL = static_cast(0x80830007); -constexpr HRESULT E_GS_BLOB_NOT_FOUND = static_cast(0x80830008); -constexpr HRESULT E_GS_HANDLE_EXPIRED = static_cast(0x8083000D); - -constexpr uint64_t kMaxUpdateBytes = 16ull * 1024 * 1024; // GS_MAX_BLOB_SIZE, 16 MB: one blob and one update -constexpr uint64_t kQuotaBytes = 1ull << 30; // ASSUMPTION, see the header -constexpr size_t kMaxContainerName = 256; -constexpr size_t kMaxBlobName = 256; // ASSUMPTION, see the header - -// ---- Names ---- - -std::string encode_name(std::string_view name) { - static const char hex[] = "0123456789ABCDEF"; - std::string out; - for (const char ch : name) { - const auto c = static_cast(ch); - const bool keep = (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || (c >= '0' && c <= '9') || c == '_' || - c == '-' || (c == '.' && !out.empty()); - if (keep) { - out += ch; - } else { - out += '%'; - out += hex[c >> 4]; - out += hex[c & 15]; - } - } - return out; -} - -// The inverse; false for a file name encode_name could not have produced (temporary files, .display, strays). -bool decode_name(std::string_view encoded, std::string& out) { - out.clear(); - if (encoded.empty() || encoded.front() == '.' || encoded.back() == '~') return false; - auto digit = [](char c) { return c >= '0' && c <= '9' ? c - '0' : c >= 'A' && c <= 'F' ? c - 'A' + 10 : -1; }; - for (size_t i = 0; i < encoded.size(); ++i) { - if (encoded[i] != '%') { - out += encoded[i]; - continue; - } - if (i + 2 >= encoded.size()) return false; - const int hi = digit(encoded[i + 1]), lo = digit(encoded[i + 2]); - if (hi < 0 || lo < 0) return false; - out += static_cast(hi << 4 | lo); - i += 2; - } - return encode_name(out) == encoded; // one spelling per name -} - -// XGameSaveCreateContainer's rule: at most 256 characters; a path part (up to the last '/') of [A-Za-z0-9_/], then a -// non-empty file part of [A-Za-z0-9_.-] that does not end in '.' nor hold "..". -bool valid_container_name(const char* name) { - if (!name) return false; - const std::string_view n(name); - if (n.empty() || n.size() > kMaxContainerName) return false; - const size_t slash = n.rfind('/'); - const std::string_view path = slash == std::string_view::npos ? std::string_view{} : n.substr(0, slash + 1); - const std::string_view file = slash == std::string_view::npos ? n : n.substr(slash + 1); - auto alnum = [](char c) { return (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || (c >= '0' && c <= '9'); }; - for (const char c : path) - if (!alnum(c) && c != '_' && c != '/') return false; - if (file.empty() || file.back() == '.' || file.find("..") != std::string_view::npos) return false; - for (const char c : file) - if (!alnum(c) && c != '_' && c != '.' && c != '-') return false; - return true; -} - -bool valid_blob_name(const char* name) { return name && name[0] && std::strlen(name) <= kMaxBlobName; } - -std::wstring widen(const std::string& s) { - if (s.empty()) return {}; - const int n = MultiByteToWideChar(CP_UTF8, 0, s.data(), static_cast(s.size()), nullptr, 0); - std::wstring w(static_cast(n > 0 ? n : 0), L'\0'); - if (n > 0) MultiByteToWideChar(CP_UTF8, 0, s.data(), static_cast(s.size()), w.data(), n); - return w; -} -std::string narrow(const std::wstring& w) { - if (w.empty()) return {}; - const int n = WideCharToMultiByte(CP_UTF8, 0, w.data(), static_cast(w.size()), nullptr, 0, nullptr, nullptr); - std::string s(static_cast(n > 0 ? n : 0), '\0'); - if (n > 0) WideCharToMultiByte(CP_UTF8, 0, w.data(), static_cast(w.size()), s.data(), n, nullptr, nullptr); - return s; -} - -fs::path save_root() { - // paths.save_dir (LEONIDA_SAVE_DIR). A folder of MAX_PATH * 2 characters or more is ignored, as before the - // setting moved to the table. - if (fs::path dir = rt::config::path("paths.save_dir"); !dir.empty() && dir.native().size() < MAX_PATH * 2) - return dir; - wchar_t buffer[MAX_PATH * 2]; - const DWORD n = GetEnvironmentVariableW(L"LOCALAPPDATA", buffer, static_cast(std::size(buffer))); - if (n > 0 && n < std::size(buffer)) return fs::path(buffer) / L"Leonida" / L"saves"; - return {}; -} - -// ---- Handles ---- - -// One mutex for the handle sets and the files: saves are small and rare, so nothing is gained by finer locking. -std::recursive_mutex g_mutex; - -struct XGameSaveProvider { - fs::path user_dir; // \local-user - std::string config_id; - uint64_t serial = 0; -}; -struct XGameSaveContainer { - fs::path user_dir; // the provider's, copied: a container outlives a closed provider safely - std::string name; - uint64_t serial = 0; - fs::path dir() const { return user_dir / widen(encode_name(name)); } -}; -struct Op { - bool write; - std::vector data; -}; -struct XGameSaveUpdate { - XGameSaveContainer* container; - uint64_t container_serial; // the container's serial when the update was made - std::string display_name; - bool has_display_name; - std::map ops; // blob name -> its one write or delete - uint64_t bytes; - uint64_t serial = 0; -}; - -std::unordered_set g_providers, g_containers, g_updates; - -bool live(const std::unordered_set& set, const void* h) { return h && set.count(h) != 0; } - -// Every handle gets a serial when it is made, and no two get the same one. The heap may hand a closed handle's address -// to the next handle of its kind, so whatever keeps a handle past the call that gave it (an update its container, an -// async job its provider, container or update) keeps the serial as well, and the handle counts as the same one only -// while both match. A reused address is then refused as expired instead of acting on another save. Under g_mutex. -uint64_t g_next_serial = 1; - -template bool live_as(const std::unordered_set& set, const T* h, uint64_t serial) { - return live(set, h) && h->serial == serial; -} - -// The serial of a live handle; 0, which no handle has, for one that isn't, so a job made from it fails as expired. -template uint64_t serial_of(const std::unordered_set& set, const T* h) { - std::lock_guard lock(g_mutex); - return live(set, h) ? h->serial : 0; -} - -// ---- Files ---- - -struct BlobFile { - std::string name; - uint64_t size; - fs::path path; -}; - -std::vector list_blobs(const fs::path& dir) { - std::vector out; - std::error_code ec; - for (const auto& e : fs::directory_iterator(dir, ec)) { - if (!e.is_regular_file(ec)) continue; - std::string name; - if (!decode_name(narrow(e.path().filename().wstring()), name)) continue; - out.push_back({name, static_cast(e.file_size(ec)), e.path()}); - } - std::sort(out.begin(), out.end(), [](const BlobFile& a, const BlobFile& b) { return a.name < b.name; }); - return out; -} - -time_t modified_time(const fs::path& p) { - WIN32_FILE_ATTRIBUTE_DATA data{}; - if (!GetFileAttributesExW(p.c_str(), GetFileExInfoStandard, &data)) return 0; - const uint64_t t = (static_cast(data.ftLastWriteTime.dwHighDateTime) << 32) | data.ftLastWriteTime.dwLowDateTime; - return t < 116444736000000000ull ? 0 : static_cast((t - 116444736000000000ull) / 10000000ull); -} - -std::string read_text(const fs::path& p) { - std::ifstream f(p, std::ios::binary); - return f ? std::string((std::istreambuf_iterator(f)), std::istreambuf_iterator()) : std::string{}; -} - -bool write_file(const fs::path& p, const void* data, size_t size) { - std::ofstream f(p, std::ios::binary | std::ios::trunc); - if (!f) return false; - f.write(static_cast(data), static_cast(size)); - f.close(); - return !f.fail(); -} - -struct ContainerRecord { - std::string name, display_name; - uint32_t blob_count = 0; - uint64_t total_size = 0; - time_t modified = 0; -}; - -ContainerRecord describe(const std::string& name, const fs::path& dir) { - ContainerRecord r; - r.name = name; - r.display_name = read_text(dir / L".display"); - for (const BlobFile& b : list_blobs(dir)) { - ++r.blob_count; - r.total_size += b.size; - const time_t t = modified_time(b.path); - if (t > r.modified) r.modified = t; - } - return r; -} - -std::vector list_containers(const fs::path& user_dir, std::string_view prefix) { - std::vector out; - std::error_code ec; - for (const auto& e : fs::directory_iterator(user_dir, ec)) { - if (!e.is_directory(ec)) continue; - std::string name; - if (!decode_name(narrow(e.path().filename().wstring()), name)) continue; - if (name.compare(0, prefix.size(), prefix) != 0) continue; - out.push_back(describe(name, e.path())); - } - std::sort(out.begin(), out.end(), [](const ContainerRecord& a, const ContainerRecord& b) { return a.name < b.name; }); - return out; -} - -uint64_t used_bytes(const fs::path& user_dir) { - uint64_t used = 0; - for (const ContainerRecord& c : list_containers(user_dir, {})) used += c.total_size; - return used; -} - -void enumerate_containers(const fs::path& user_dir, std::string_view prefix, void* context, ContainerInfoCallback cb) { - for (const ContainerRecord& c : list_containers(user_dir, prefix)) { - const XGameSaveContainerInfo info{c.name.c_str(), c.display_name.c_str(), c.blob_count, c.total_size, - c.modified, false}; - if (!cb(&info, context)) break; - } -} - -// ---- Reading blobs into the title's buffer ---- -// -// The buffer is laid out as the GDK samples read it: an array of XGameSaveBlob, one per blob, whose info.name and -// data point further into the same buffer (each blob's bytes 8-aligned, then its name). - -struct BlobRead { - std::string name; - std::vector data; -}; - -size_t align8(size_t n) { return (n + 7) & ~size_t{7}; } - -size_t packed_size(const std::vector& blobs) { - size_t n = align8(blobs.size() * sizeof(XGameSaveBlob)); - for (const BlobRead& b : blobs) n += align8(b.data.size()) + align8(b.name.size() + 1); - return n; -} - -void pack(const std::vector& blobs, void* buffer) { - auto* base = static_cast(buffer); - auto* entries = static_cast(buffer); - size_t at = align8(blobs.size() * sizeof(XGameSaveBlob)); - for (size_t i = 0; i < blobs.size(); ++i) { - uint8_t* data = base + at; - if (!blobs[i].data.empty()) std::memcpy(data, blobs[i].data.data(), blobs[i].data.size()); - at += align8(blobs[i].data.size()); - char* name = reinterpret_cast(base + at); - std::memcpy(name, blobs[i].name.c_str(), blobs[i].name.size() + 1); - at += align8(blobs[i].name.size() + 1); - entries[i].info.name = name; - entries[i].info.size = static_cast(blobs[i].data.size()); - entries[i].data = data; - } -} - -// Reads the named blobs (every blob when names is null) of a live container. -HRESULT read_blobs(const XGameSaveContainer* c, const char* const* names, uint32_t count, std::vector& out) { - out.clear(); - const fs::path dir = c->dir(); - std::vector wanted; - if (names) { - for (uint32_t i = 0; i < count; ++i) { - if (!valid_blob_name(names[i])) return E_INVALIDARG; - wanted.emplace_back(names[i]); - } - } else { - for (const BlobFile& b : list_blobs(dir)) wanted.push_back(b.name); - } - for (const std::string& name : wanted) { - std::ifstream f(dir / widen(encode_name(name)), std::ios::binary); - if (!f) return E_GS_BLOB_NOT_FOUND; - out.push_back({name, std::vector((std::istreambuf_iterator(f)), std::istreambuf_iterator())}); - } - return S_OK; -} - -// ---- Committing an update ---- - -HRESULT commit(XGameSaveUpdate* u) { - XGameSaveContainer* c = u->container; - const fs::path dir = c->dir(); - // The quota: what the container holds after the update, plus every other container. - uint64_t after = used_bytes(c->user_dir); - for (const auto& [name, op] : u->ops) { - std::error_code ec; - const fs::path p = dir / widen(encode_name(name)); - const uint64_t old = fs::is_regular_file(p, ec) ? static_cast(fs::file_size(p, ec)) : 0; - after = after - old + (op.write ? op.data.size() : 0); - } - if (after > kQuotaBytes) return E_GS_QUOTA_EXCEEDED; - - std::error_code ec; - fs::create_directories(dir, ec); - if (ec) return E_GS_OUT_OF_LOCAL_STORAGE; - std::vector> renames; // temporary -> final - for (const auto& [name, op] : u->ops) { - if (!op.write) continue; - const fs::path final_path = dir / widen(encode_name(name)); - fs::path temp = final_path; - temp += L"~"; - if (!write_file(temp, op.data.data(), op.data.size())) { - for (const auto& r : renames) fs::remove(r.first, ec); - fs::remove(temp, ec); - return E_GS_OUT_OF_LOCAL_STORAGE; - } - renames.emplace_back(temp, final_path); - } - for (const auto& [temp, final_path] : renames) - if (!MoveFileExW(temp.c_str(), final_path.c_str(), MOVEFILE_REPLACE_EXISTING | MOVEFILE_WRITE_THROUGH)) - return E_GS_OUT_OF_LOCAL_STORAGE; - for (const auto& [name, op] : u->ops) - if (!op.write) fs::remove(dir / widen(encode_name(name)), ec); - if (u->has_display_name) write_file(dir / L".display", u->display_name.data(), u->display_name.size()); - return S_OK; -} - - -// ---- Operations shared by the sync slots and the async work ---- - -HRESULT open_provider(XUserHandle user, const char* config_id, XGameSaveProviderHandle* out) { - if (!out) return E_POINTER; - *out = nullptr; - if (!user || !config_id) return E_INVALIDARG; - const fs::path root = save_root(); - if (root.empty()) return E_GS_OUT_OF_LOCAL_STORAGE; - const fs::path user_dir = root / L"local-user"; - std::error_code ec; - fs::create_directories(user_dir, ec); - if (ec) return E_GS_OUT_OF_LOCAL_STORAGE; - auto* p = new XGameSaveProvider{user_dir, config_id}; - std::lock_guard lock(g_mutex); - p->serial = g_next_serial++; - g_providers.insert(p); - *out = p; - static std::atomic s_logged{0}; - if (s_logged.fetch_add(1) == 0) - RT_LOG_INFO("xgamesave: offline provider for \"%s\" at %ls\n", config_id, user_dir.c_str()); - return S_OK; -} - -HRESULT remaining_quota(XGameSaveProviderHandle p, int64_t* remaining) { - if (!remaining) return E_POINTER; - std::lock_guard lock(g_mutex); - if (!live(g_providers, p)) return E_GS_HANDLE_EXPIRED; - const uint64_t used = used_bytes(p->user_dir); - *remaining = used >= kQuotaBytes ? 0 : static_cast(kQuotaBytes - used); - return S_OK; -} - -HRESULT delete_container(XGameSaveProviderHandle p, const char* name) { - std::lock_guard lock(g_mutex); - if (!live(g_providers, p)) return E_GS_HANDLE_EXPIRED; - if (!valid_container_name(name)) return E_GS_INVALID_CONTAINER_NAME; - std::error_code ec; - fs::remove_all(p->user_dir / widen(encode_name(name)), ec); - return ec ? E_FAIL : S_OK; -} - -HRESULT submit_update(XGameSaveUpdateHandle u) { - std::lock_guard lock(g_mutex); - if (!live(g_updates, u) || !live_as(g_containers, u->container, u->container_serial)) return E_GS_HANDLE_EXPIRED; - return commit(u); -} - -// ---- Async: each *Async slot runs its work on the title's queue ---- - -struct Job { - const void* identity; - XUserHandle user = nullptr; - std::string text; // configId - XGameSaveProviderHandle provider = nullptr; - XGameSaveContainerHandle container = nullptr; - XGameSaveUpdateHandle update = nullptr; - uint64_t serial = 0; // the serial of the provider, container or update above, when the job was made - std::vector names; - bool all_blobs = false; - // results - int64_t quota = 0; - std::vector blobs; - std::string folder; -}; - -const char kInitIdentity = 0, kQuotaIdentity = 0, kDeleteIdentity = 0, kReadIdentity = 0, kSubmitIdentity = 0, - kFolderIdentity = 0; - -// The blob count of the last ReadBlobDataAsync result collected on this thread (GetResult runs on the caller's). -thread_local uint32_t t_read_count = 0; - -HRESULT do_work(Job& job, size_t& size) { - size = 0; - if (job.identity == &kInitIdentity) { - // The handle is made when the title collects the result, so an uncollected result leaks nothing; here only - // the folder is checked. - if (!job.user) return E_INVALIDARG; - const fs::path root = save_root(); - std::error_code ec; - if (root.empty() || (fs::create_directories(root / L"local-user", ec), ec)) return E_GS_OUT_OF_LOCAL_STORAGE; - size = sizeof(XGameSaveProviderHandle); - return S_OK; - } - if (job.identity == &kQuotaIdentity) { - std::lock_guard lock(g_mutex); - if (!live_as(g_providers, job.provider, job.serial)) return E_GS_HANDLE_EXPIRED; - const HRESULT hr = remaining_quota(job.provider, &job.quota); - if (SUCCEEDED(hr)) size = sizeof(int64_t); - return hr; - } - if (job.identity == &kDeleteIdentity) { - std::lock_guard lock(g_mutex); - if (!live_as(g_providers, job.provider, job.serial)) return E_GS_HANDLE_EXPIRED; - return delete_container(job.provider, job.text.c_str()); - } - if (job.identity == &kSubmitIdentity) { - std::lock_guard lock(g_mutex); - if (!live_as(g_updates, job.update, job.serial)) return E_GS_HANDLE_EXPIRED; - return submit_update(job.update); - } - if (job.identity == &kReadIdentity) { - std::lock_guard lock(g_mutex); - if (!live_as(g_containers, job.container, job.serial)) return E_GS_HANDLE_EXPIRED; - std::vector names; - for (const std::string& n : job.names) names.push_back(n.c_str()); - const HRESULT hr = read_blobs(job.container, job.all_blobs ? nullptr : names.data(), - static_cast(names.size()), job.blobs); - if (SUCCEEDED(hr)) size = packed_size(job.blobs); - return hr; - } - if (job.identity == &kFolderIdentity) { - const fs::path root = save_root(); - if (root.empty()) return E_GS_OUT_OF_LOCAL_STORAGE; - const fs::path dir = root / L"files" / widen(encode_name(job.text)); - std::error_code ec; - fs::create_directories(dir, ec); - if (ec) return E_GS_OUT_OF_LOCAL_STORAGE; - job.folder = narrow(dir.wstring()); - size = job.folder.size() + 1; - return S_OK; - } - return E_UNEXPECTED; -} - -HRESULT CALLBACK job_provider(XAsyncOp op, const XAsyncProviderData* data) { - auto* job = static_cast(data->context); - switch (op) { - case XAsyncOp::Begin: - return XAsyncSchedule(data->async, 0); - case XAsyncOp::DoWork: { - size_t size = 0; - const HRESULT hr = do_work(*job, size); - XAsyncComplete(data->async, hr, SUCCEEDED(hr) ? size : 0); - return S_OK; - } - case XAsyncOp::GetResult: - if (!data->buffer) return E_INVALIDARG; - if (job->identity == &kInitIdentity) { - if (data->bufferSize < sizeof(XGameSaveProviderHandle)) return E_INVALIDARG; - return open_provider(job->user, job->text.c_str(), static_cast(data->buffer)); - } - if (job->identity == &kQuotaIdentity) { - if (data->bufferSize < sizeof(int64_t)) return E_INVALIDARG; - *static_cast(data->buffer) = job->quota; - return S_OK; - } - if (job->identity == &kReadIdentity) { - if (data->bufferSize < packed_size(job->blobs)) return E_GS_PROVIDED_BUFFER_TOO_SMALL; - pack(job->blobs, data->buffer); - t_read_count = static_cast(job->blobs.size()); - return S_OK; - } - if (job->identity == &kFolderIdentity) { - if (data->bufferSize < job->folder.size() + 1) return E_GS_PROVIDED_BUFFER_TOO_SMALL; - std::memcpy(data->buffer, job->folder.c_str(), job->folder.size() + 1); - return S_OK; - } - return S_OK; - case XAsyncOp::Cleanup: - delete job; - return S_OK; - default: - return S_OK; - } -} - -HRESULT begin(XAsyncBlock* async, Job* job, const char* name) { - if (!async) { - delete job; - return E_POINTER; - } - const HRESULT hr = XAsyncBegin(async, job, job->identity, name, job_provider); - if (FAILED(hr)) delete job; - return hr; -} - -// ---- IXGameSaveImpl (slots 3-29), IXGameSaveImpl2 (30-32) ---- - -// 3: HRESULT XGameSaveInitializeProvider(XUserHandle requestingUser, const char* configurationId, bool syncOnDemand, -// XGameSaveProviderHandle* provider) -HRESULT STDMETHODCALLTYPE save_init(void*, XUserHandle user, const char* config_id, bool, XGameSaveProviderHandle* out) { - return open_provider(user, config_id, out); -} - -// 4: HRESULT XGameSaveInitializeProviderAsync(XUserHandle, const char* configurationId, bool syncOnDemand, XAsyncBlock*) -HRESULT STDMETHODCALLTYPE save_init_async(void*, XUserHandle user, const char* config_id, bool, XAsyncBlock* async) { - if (!user || !config_id) return E_INVALIDARG; - auto* job = new Job{&kInitIdentity}; - job->user = user; - job->text = config_id; - return begin(async, job, "XGameSaveInitializeProviderAsync"); -} - -// 5: HRESULT XGameSaveInitializeProviderResult(XAsyncBlock* async, XGameSaveProviderHandle* provider) -HRESULT STDMETHODCALLTYPE save_init_result(void*, XAsyncBlock* async, XGameSaveProviderHandle* out) { - if (!out) return E_POINTER; - *out = nullptr; - return XAsyncGetResult(async, &kInitIdentity, sizeof(*out), out, nullptr); -} - -// 6: void XGameSaveCloseProvider(XGameSaveProviderHandle provider) -void STDMETHODCALLTYPE save_close_provider(void*, XGameSaveProviderHandle p) { - { - std::lock_guard lock(g_mutex); - if (!p || g_providers.erase(p) == 0) return; - } - delete p; -} - -// 7: HRESULT XGameSaveGetRemainingQuota(XGameSaveProviderHandle provider, int64_t* remainingQuota) -HRESULT STDMETHODCALLTYPE save_quota(void*, XGameSaveProviderHandle p, int64_t* remaining) { - return remaining_quota(p, remaining); -} - -// 8: HRESULT XGameSaveGetRemainingQuotaAsync(XGameSaveProviderHandle provider, XAsyncBlock* async) -HRESULT STDMETHODCALLTYPE save_quota_async(void*, XGameSaveProviderHandle p, XAsyncBlock* async) { - auto* job = new Job{&kQuotaIdentity}; - job->provider = p; - job->serial = serial_of(g_providers, p); - return begin(async, job, "XGameSaveGetRemainingQuotaAsync"); -} - -// 9: HRESULT XGameSaveGetRemainingQuotaResult(XAsyncBlock* async, int64_t* remainingQuota) -HRESULT STDMETHODCALLTYPE save_quota_result(void*, XAsyncBlock* async, int64_t* remaining) { - if (!remaining) return E_POINTER; - return XAsyncGetResult(async, &kQuotaIdentity, sizeof(*remaining), remaining, nullptr); -} - -// 10: HRESULT XGameSaveDeleteContainer(XGameSaveProviderHandle provider, const char* containerName) -HRESULT STDMETHODCALLTYPE save_delete(void*, XGameSaveProviderHandle p, const char* name) { - return delete_container(p, name); -} - -// 11: HRESULT XGameSaveDeleteContainerAsync(XGameSaveProviderHandle provider, const char* containerName, XAsyncBlock*) -HRESULT STDMETHODCALLTYPE save_delete_async(void*, XGameSaveProviderHandle p, const char* name, XAsyncBlock* async) { - if (!valid_container_name(name)) return E_GS_INVALID_CONTAINER_NAME; - auto* job = new Job{&kDeleteIdentity}; - job->provider = p; - job->serial = serial_of(g_providers, p); - job->text = name; - return begin(async, job, "XGameSaveDeleteContainerAsync"); -} - -// 12: HRESULT XGameSaveDeleteContainerResult(XAsyncBlock* async) -HRESULT STDMETHODCALLTYPE save_delete_result(void*, XAsyncBlock* async) { - return XAsyncGetResult(async, &kDeleteIdentity, 0, nullptr, nullptr); -} - -// 13: HRESULT XGameSaveGetContainerInfo(XGameSaveProviderHandle, const char* containerName, void* context, -// XGameSaveContainerInfoCallback* callback) -HRESULT STDMETHODCALLTYPE save_container_info(void*, XGameSaveProviderHandle p, const char* name, void* context, - ContainerInfoCallback cb) { - if (!cb) return E_INVALIDARG; - std::lock_guard lock(g_mutex); - if (!live(g_providers, p)) return E_GS_HANDLE_EXPIRED; - if (!valid_container_name(name)) return E_GS_INVALID_CONTAINER_NAME; - const fs::path dir = p->user_dir / widen(encode_name(name)); - std::error_code ec; - if (!fs::is_directory(dir, ec)) return S_OK; - const ContainerRecord c = describe(name, dir); - const XGameSaveContainerInfo info{c.name.c_str(), c.display_name.c_str(), c.blob_count, c.total_size, c.modified, - false}; - cb(&info, context); - return S_OK; -} - -// 14: HRESULT XGameSaveEnumerateContainerInfo(XGameSaveProviderHandle, void* context, XGameSaveContainerInfoCallback*) -HRESULT STDMETHODCALLTYPE save_enum_containers(void*, XGameSaveProviderHandle p, void* context, ContainerInfoCallback cb) { - if (!cb) return E_INVALIDARG; - std::lock_guard lock(g_mutex); - if (!live(g_providers, p)) return E_GS_HANDLE_EXPIRED; - enumerate_containers(p->user_dir, {}, context, cb); - return S_OK; -} - -// 15: HRESULT XGameSaveEnumerateContainerInfoByName(XGameSaveProviderHandle, const char* containerNamePrefix, -// void* context, XGameSaveContainerInfoCallback*) -HRESULT STDMETHODCALLTYPE save_enum_containers_by_name(void*, XGameSaveProviderHandle p, const char* prefix, - void* context, ContainerInfoCallback cb) { - if (!cb) return E_INVALIDARG; - std::lock_guard lock(g_mutex); - if (!live(g_providers, p)) return E_GS_HANDLE_EXPIRED; - enumerate_containers(p->user_dir, prefix ? std::string_view(prefix) : std::string_view{}, context, cb); - return S_OK; -} - -// 16: HRESULT XGameSaveCreateContainer(XGameSaveProviderHandle, const char* containerName, XGameSaveContainerHandle*). -// The folder appears when the first update is submitted. -HRESULT STDMETHODCALLTYPE save_create_container(void*, XGameSaveProviderHandle p, const char* name, - XGameSaveContainerHandle* out) { - if (!out) return E_POINTER; - *out = nullptr; - std::lock_guard lock(g_mutex); - if (!live(g_providers, p)) return E_GS_HANDLE_EXPIRED; - if (!valid_container_name(name)) return E_GS_INVALID_CONTAINER_NAME; - auto* c = new XGameSaveContainer{p->user_dir, name}; - c->serial = g_next_serial++; - g_containers.insert(c); - *out = c; - return S_OK; -} - -// 17: void XGameSaveCloseContainer(XGameSaveContainerHandle context) -void STDMETHODCALLTYPE save_close_container(void*, XGameSaveContainerHandle c) { - { - std::lock_guard lock(g_mutex); - if (!c || g_containers.erase(c) == 0) return; - } - delete c; -} - -HRESULT enumerate_blobs(XGameSaveContainerHandle c, std::string_view prefix, void* context, BlobInfoCallback cb) { - if (!cb) return E_INVALIDARG; - std::lock_guard lock(g_mutex); - if (!live(g_containers, c)) return E_GS_HANDLE_EXPIRED; - for (const BlobFile& b : list_blobs(c->dir())) { - if (b.name.compare(0, prefix.size(), prefix) != 0) continue; - const XGameSaveBlobInfo info{b.name.c_str(), static_cast(b.size)}; - if (!cb(&info, context)) break; - } - return S_OK; -} - -// 18: HRESULT XGameSaveEnumerateBlobInfo(XGameSaveContainerHandle, void* context, XGameSaveBlobInfoCallback*) -HRESULT STDMETHODCALLTYPE save_enum_blobs(void*, XGameSaveContainerHandle c, void* context, BlobInfoCallback cb) { - return enumerate_blobs(c, {}, context, cb); -} - -// 19: HRESULT XGameSaveEnumerateBlobInfoByName(XGameSaveContainerHandle, const char* blobNamePrefix, void* context, -// XGameSaveBlobInfoCallback*) -HRESULT STDMETHODCALLTYPE save_enum_blobs_by_name(void*, XGameSaveContainerHandle c, const char* prefix, void* context, - BlobInfoCallback cb) { - return enumerate_blobs(c, prefix ? std::string_view(prefix) : std::string_view{}, context, cb); -} - -// 20: HRESULT XGameSaveReadBlobData(XGameSaveContainerHandle, const char** blobNames, uint32_t* countOfBlobs, -// size_t blobsSize, XGameSaveBlob* blobData) -HRESULT STDMETHODCALLTYPE save_read(void*, XGameSaveContainerHandle c, const char** names, uint32_t* count, - size_t size, XGameSaveBlob* out) { - if (!count || !out) return E_POINTER; - std::lock_guard lock(g_mutex); - if (!live(g_containers, c)) return E_GS_HANDLE_EXPIRED; - std::vector blobs; - const HRESULT hr = read_blobs(c, names, names ? *count : 0, blobs); - if (FAILED(hr)) return hr; - if (size < packed_size(blobs)) return E_GS_PROVIDED_BUFFER_TOO_SMALL; - pack(blobs, out); - *count = static_cast(blobs.size()); - return S_OK; -} - -// 21: HRESULT XGameSaveReadBlobDataAsync(XGameSaveContainerHandle, const char** blobNames, uint32_t countOfBlobs, -// XAsyncBlock* async). The names are copied: the title may free them at once. -HRESULT STDMETHODCALLTYPE save_read_async(void*, XGameSaveContainerHandle c, const char** names, uint32_t count, - XAsyncBlock* async) { - auto* job = new Job{&kReadIdentity}; - job->container = c; - job->serial = serial_of(g_containers, c); - job->all_blobs = names == nullptr; - for (uint32_t i = 0; names && i < count; ++i) { - if (!valid_blob_name(names[i])) { - delete job; - return E_INVALIDARG; - } - job->names.emplace_back(names[i]); - } - return begin(async, job, "XGameSaveReadBlobDataAsync"); -} - -// 22: HRESULT XGameSaveReadBlobDataResult(XAsyncBlock* async, size_t blobsSize, XGameSaveBlob* blobData, -// uint32_t* countOfBlobs). blobsSize: XAsyncGetResultSize's answer. -HRESULT STDMETHODCALLTYPE save_read_result(void*, XAsyncBlock* async, size_t size, XGameSaveBlob* out, uint32_t* count) { - if (!out || !count) return E_POINTER; - *count = 0; - t_read_count = 0; - HRESULT hr = XAsyncGetResult(async, &kReadIdentity, size, out, nullptr); - if (hr == HRESULT_FROM_WIN32(ERROR_INSUFFICIENT_BUFFER) || hr == E_NOT_SUFFICIENT_BUFFER) - hr = E_GS_PROVIDED_BUFFER_TOO_SMALL; - if (SUCCEEDED(hr)) *count = t_read_count; - return hr; -} - -// 23: HRESULT XGameSaveCreateUpdate(XGameSaveContainerHandle, const char* containerDisplayName, XGameSaveUpdateHandle*) -HRESULT STDMETHODCALLTYPE save_create_update(void*, XGameSaveContainerHandle c, const char* display_name, - XGameSaveUpdateHandle* out) { - if (!out) return E_POINTER; - *out = nullptr; - std::lock_guard lock(g_mutex); - if (!live(g_containers, c)) return E_GS_HANDLE_EXPIRED; - auto* u = new XGameSaveUpdate{c, c->serial, display_name ? display_name : "", display_name != nullptr, {}, 0}; - u->serial = g_next_serial++; - g_updates.insert(u); - *out = u; - return S_OK; -} - -// 24: void XGameSaveCloseUpdate(XGameSaveUpdateHandle context) -void STDMETHODCALLTYPE save_close_update(void*, XGameSaveUpdateHandle u) { - { - std::lock_guard lock(g_mutex); - if (!u || g_updates.erase(u) == 0) return; - } - delete u; -} - -// 25: HRESULT XGameSaveSubmitBlobWrite(XGameSaveUpdateHandle, const char* blobName, const uint8_t* data, size_t size). -// One write or delete per blob per update; the update (and so each blob) stays within GS_MAX_BLOB_SIZE. -HRESULT STDMETHODCALLTYPE save_write(void*, XGameSaveUpdateHandle u, const char* name, const uint8_t* data, size_t size) { - if (!valid_blob_name(name) || (!data && size)) return E_INVALIDARG; - std::lock_guard lock(g_mutex); - if (!live(g_updates, u)) return E_GS_HANDLE_EXPIRED; - if (u->ops.count(name)) return E_INVALIDARG; - if (size > kMaxUpdateBytes || u->bytes + size > kMaxUpdateBytes) return E_GS_UPDATE_TOO_BIG; - u->ops.emplace(name, Op{true, std::vector(data, data + size)}); - u->bytes += size; - return S_OK; -} - -// 26: HRESULT XGameSaveSubmitBlobDelete(XGameSaveUpdateHandle, const char* blobName) -HRESULT STDMETHODCALLTYPE save_delete_blob(void*, XGameSaveUpdateHandle u, const char* name) { - if (!valid_blob_name(name)) return E_INVALIDARG; - std::lock_guard lock(g_mutex); - if (!live(g_updates, u)) return E_GS_HANDLE_EXPIRED; - if (u->ops.count(name)) return E_INVALIDARG; - u->ops.emplace(name, Op{false, {}}); - return S_OK; -} - -// 27: HRESULT XGameSaveSubmitUpdate(XGameSaveUpdateHandle update) -HRESULT STDMETHODCALLTYPE save_submit(void*, XGameSaveUpdateHandle u) { return submit_update(u); } - -// 28: HRESULT XGameSaveSubmitUpdateAsync(XGameSaveUpdateHandle update, XAsyncBlock* async) -HRESULT STDMETHODCALLTYPE save_submit_async(void*, XGameSaveUpdateHandle u, XAsyncBlock* async) { - auto* job = new Job{&kSubmitIdentity}; - job->update = u; - job->serial = serial_of(g_updates, u); - return begin(async, job, "XGameSaveSubmitUpdateAsync"); -} - -// 29: HRESULT XGameSaveSubmitUpdateResult(XAsyncBlock* async) -HRESULT STDMETHODCALLTYPE save_submit_result(void*, XAsyncBlock* async) { - return XAsyncGetResult(async, &kSubmitIdentity, 0, nullptr, nullptr); -} - -// 30: HRESULT XGameSaveFilesGetFolderWithUiAsync(XUserHandle requestingUser, const char* configurationId, -// XAsyncBlock* async): a folder of its own, \files\. -HRESULT STDMETHODCALLTYPE files_folder_async(void*, XUserHandle user, const char* config_id, XAsyncBlock* async) { - if (!user || !config_id) return E_INVALIDARG; - auto* job = new Job{&kFolderIdentity}; - job->user = user; - job->text = config_id; - return begin(async, job, "XGameSaveFilesGetFolderWithUiAsync"); -} - -// 31: HRESULT XGameSaveFilesGetFolderWithUiResult(XAsyncBlock* async, size_t folderSize, char* folderResult) -HRESULT STDMETHODCALLTYPE files_folder_result(void*, XAsyncBlock* async, size_t size, char* folder) { - if (!folder) return E_POINTER; - HRESULT hr = XAsyncGetResult(async, &kFolderIdentity, size, folder, nullptr); - if (hr == HRESULT_FROM_WIN32(ERROR_INSUFFICIENT_BUFFER) || hr == E_NOT_SUFFICIENT_BUFFER) - hr = E_GS_PROVIDED_BUFFER_TOO_SMALL; - return hr; -} - -// 32: HRESULT XGameSaveFilesGetRemainingQuota(XUserHandle requestingUser, const char* configurationId, -// int64_t* remainingQuota) -HRESULT STDMETHODCALLTYPE files_quota(void*, XUserHandle user, const char* config_id, int64_t* remaining) { - if (!remaining) return E_POINTER; - if (!user || !config_id) return E_INVALIDARG; - const fs::path root = save_root(); - if (root.empty()) return E_GS_OUT_OF_LOCAL_STORAGE; - uint64_t used = 0; - std::error_code ec; - for (const auto& e : fs::recursive_directory_iterator(root / L"files" / widen(encode_name(config_id)), ec)) - if (e.is_regular_file(ec)) used += static_cast(e.file_size(ec)); - *remaining = used >= kQuotaBytes ? 0 : static_cast(kQuotaBytes - used); - return S_OK; -} - -// ---- The object ---- - -constexpr GUID kSaveClass = {0x704c3f58, 0xe629, 0x4cc2, {0xb1, 0x97, 0x30, 0x51, 0x1b, 0x99, 0x6f, 0xe2}}; -const GUID kSaveInterfaces[] = { - kSaveClass, // IXGameSaveImpl - {0x704c3f58, 0xe629, 0x4cc2, {0xb1, 0x97, 0x30, 0x51, 0x1b, 0x99, 0x6e, 0xe2}}, // IXGameSaveImpl2 - {0x1bfff3af, 0xf14a, 0x40a3, {0x8e, 0x35, 0x9a, 0xda, 0x90, 0x65, 0x93, 0xf9}}, // IXGameSaveImpl3 (no methods) -}; -constexpr GUID kIUnknown = {0x00000000, 0x0000, 0x0000, {0xc0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x46}}; - -struct SaveObject { - const void* const* vtable; -}; -SaveObject* save_object(); - -HRESULT query(REFIID iid, void** out) { - if (!out) return E_POINTER; - *out = nullptr; - if (iid == kIUnknown) { - *out = save_object(); - return S_OK; - } - for (const GUID& id : kSaveInterfaces) - if (iid == id) { - *out = save_object(); - return S_OK; - } - return E_NOINTERFACE; -} - -// A process-wide singleton, as the other runtime classes: AddRef and Release don't free. -HRESULT STDMETHODCALLTYPE object_query_interface(void*, REFIID iid, void** out) { return query(iid, out); } -ULONG STDMETHODCALLTYPE object_add_ref(void*) { return 2; } -ULONG STDMETHODCALLTYPE object_release(void*) { return 1; } - -#define FN(f) reinterpret_cast(&f) - -const void* const kSaveVtable[] = { - FN(object_query_interface), FN(object_add_ref), FN(object_release), // 0-2 IUnknown - FN(save_init), // 3 XGameSaveInitializeProvider - FN(save_init_async), // 4 XGameSaveInitializeProviderAsync - FN(save_init_result), // 5 XGameSaveInitializeProviderResult - FN(save_close_provider), // 6 XGameSaveCloseProvider - FN(save_quota), // 7 XGameSaveGetRemainingQuota - FN(save_quota_async), // 8 XGameSaveGetRemainingQuotaAsync - FN(save_quota_result), // 9 XGameSaveGetRemainingQuotaResult - FN(save_delete), // 10 XGameSaveDeleteContainer - FN(save_delete_async), // 11 XGameSaveDeleteContainerAsync - FN(save_delete_result), // 12 XGameSaveDeleteContainerResult - FN(save_container_info), // 13 XGameSaveGetContainerInfo - FN(save_enum_containers), // 14 XGameSaveEnumerateContainerInfo - FN(save_enum_containers_by_name), // 15 XGameSaveEnumerateContainerInfoByName - FN(save_create_container), // 16 XGameSaveCreateContainer - FN(save_close_container), // 17 XGameSaveCloseContainer - FN(save_enum_blobs), // 18 XGameSaveEnumerateBlobInfo - FN(save_enum_blobs_by_name), // 19 XGameSaveEnumerateBlobInfoByName - FN(save_read), // 20 XGameSaveReadBlobData - FN(save_read_async), // 21 XGameSaveReadBlobDataAsync - FN(save_read_result), // 22 XGameSaveReadBlobDataResult - FN(save_create_update), // 23 XGameSaveCreateUpdate - FN(save_close_update), // 24 XGameSaveCloseUpdate - FN(save_write), // 25 XGameSaveSubmitBlobWrite - FN(save_delete_blob), // 26 XGameSaveSubmitBlobDelete - FN(save_submit), // 27 XGameSaveSubmitUpdate - FN(save_submit_async), // 28 XGameSaveSubmitUpdateAsync - FN(save_submit_result), // 29 XGameSaveSubmitUpdateResult - FN(files_folder_async), // 30 XGameSaveFilesGetFolderWithUiAsync (2) - FN(files_folder_result), // 31 XGameSaveFilesGetFolderWithUiResult (2) - FN(files_quota), // 32 XGameSaveFilesGetRemainingQuota (2) -}; -static_assert(std::size(kSaveVtable) == 33, "IUnknown + IXGameSaveImpl's 27 methods + IXGameSaveImpl2's 3"); - -#undef FN - -SaveObject* save_object() { - static SaveObject o{kSaveVtable}; - return &o; -} - -} // namespace - -namespace rt::shims { - -// Called by xgameruntime.cpp's QueryApiImpl for every class: true when the class is XGameSaveImpl, with *hr set. -bool xgameruntime_gamesave_query(const GUID& class_id, REFIID interface_id, void** out, HRESULT* hr) { - if (class_id != kSaveClass) return false; - *hr = query(interface_id, out); - return true; -} - -// For tests: the provider, container and update handles a title holds open. -long xgameruntime_gamesave_open_handles() { - std::lock_guard lock(g_mutex); - return static_cast(g_providers.size() + g_containers.size() + g_updates.size()); -} - -} // namespace rt::shims diff --git a/runtime/shims/xgameruntime_offline.cpp b/runtime/shims/xgameruntime_offline.cpp deleted file mode 100644 index 419d0385c..000000000 --- a/runtime/shims/xgameruntime_offline.cpp +++ /dev/null @@ -1,752 +0,0 @@ -// xgameruntime: XGameEventImpl, XGameUiImpl, XGameStreamingImpl, XDisplayImpl, XUserDeviceImpl, XAccessibilityImpl and -// XLauncherImpl, offline: small classes a title calls early. -// -// Each XGameEvent*, XGameUi* and XGameStreaming* function in xgameruntime.lib asks QueryApiImpl for its class and -// calls one slot with its own arguments after `this`. The class and interface ids and the method order are -// xodus-gaming/xgameruntime-docs' COM pages (GPL-3.0; facts only, nothing copied); IUnknown takes slots 0-2, so each -// class's first method is slot 3. Signatures follow Microsoft's public GDK reference (learn.microsoft.com/gaming/gdk). -// No GDK header or library code is used. -// -// XGameEventImpl XGameEventWrite (telemetry) succeeds and is dropped; the first event's name is logged, and -// LEONIDA_LOG_GAME_EVENTS=1 logs every one. -// XGameUiImpl a message dialog or error dialog has no screen: its title and text go to the log and it -// completes at once with the dialog's default button (error dialogs: dismissed). Every other UI -// (profile cards, pickers, text entry, web authentication, invites) fails before starting. -// XGameStreamingImpl the game is never streamed: initialising succeeds, IsStreaming is false, there are no -// clients, the connection-state registration hands out a token that never fires. -// XDisplayImpl XDisplayTryEnableHdrMode: Disabled (the host output is SDR), Enabled with LEONIDA_HDR=1. -// XUserDeviceImpl every device belongs to the offline user; associations and audio endpoints never change, so -// their change registrations are kept until unregistered and never called back; the user has -// no audio endpoint of its own; finding a controller shows no UI (as on desktop). -// XAccessibilityImpl high contrast is Off, closed captions can't be configured, no voice is installed (enumerating -// calls back zero times), XSpeechSynthesizerCreate fails (E_FAIL) with a null handle, the other -// speech calls refuse the handle they were never given (E_INVALIDARG), speech-to-text display -// calls fail (E_FAIL). -// XLauncherImpl XLaunchUri and the display timeout deferral calls fail (E_FAIL); nothing is launched. -// -// Slots whose signature the public pages don't give answer with a value that is safe whichever way the caller reads -// it: see `client_not_connected` (XGameStreaming) and `offline_failure`. -#include - -#include -#include -#include -#include -#include -#include -#include -#include - -#include -#include -#include - -#include "../core/config.h" -#include "../core/log.h" - -namespace rt::shims { -void* xgameruntime_user_new_handle(); // xgameruntime_user.cpp -} - -namespace { - -using XUserHandle = void*; - -// XGameErr.h values, from the GDK "Error codes" page. -constexpr HRESULT E_GAMESTREAMING_NOT_INITIALIZED = static_cast(0x89245400); - -constexpr GUID kIUnknown = {0x00000000, 0x0000, 0x0000, {0xc0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x46}}; - -#define FN(f) reinterpret_cast(&f) - -// A process-wide singleton per class, as the other runtime classes: AddRef and Release don't free. -ULONG STDMETHODCALLTYPE object_add_ref(void*) { return 2; } -ULONG STDMETHODCALLTYPE object_release(void*) { return 1; } - -// One class: its object (a pointer to its vtable) and the interface ids it answers with that vtable. -struct ClassObject { - const void* const* vtable; -}; - -HRESULT answer(ClassObject* object, const GUID* begin, const GUID* end, REFIID iid, void** out) { - if (!out) return E_POINTER; - *out = nullptr; - if (iid == kIUnknown) { - *out = object; - return S_OK; - } - for (const GUID* id = begin; id != end; ++id) - if (iid == *id) { - *out = object; - return S_OK; - } - return E_NOINTERFACE; -} - -// A slot the docs don't name: E_NOTIMPL, so nothing reads outputs it didn't write. -template HRESULT STDMETHODCALLTYPE unknown_slot(void*) { - static std::atomic s_logged{false}; - if (!s_logged.exchange(true)) - RT_LOG_WARN("xgameruntime: %s slot %d (unknown in the docs) called; E_NOTIMPL\n", Class, Slot); - return E_NOTIMPL; -} - -// A UI the offline runtime doesn't have. The *Async function fails before starting, so the XAsyncBlock is never used -// and no callback runs; its Result partners return the same error. Arguments don't matter (x64: the caller owns the -// argument area). -template HRESULT STDMETHODCALLTYPE offline_failure(void*) { - static std::atomic s_logged{false}; - if (!s_logged.exchange(true)) - RT_LOG_WARN("xgameruntime: %s slot %d is not available offline (E_FAIL)\n", Class, Slot); - return E_FAIL; -} - -// ======================= XGameEventImpl ======================= - -constexpr char kEventName[] = "XGameEventImpl"; -constexpr GUID kEventClass = {0xbbfbdcc7, 0xbfe7, 0x409b, {0xa5, 0xca, 0xed, 0xf0, 0x54, 0x96, 0x0b, 0x4d}}; -std::atomic g_events{0}; - -bool log_every_event() { - static const bool on = rt::config::get("system.log_game_events").text == "1"; - return on; -} - -// 3: HRESULT XGameEventWrite(XUserHandle user, const char* serviceConfigId, const char* playSessionId, -// const char* eventName, const char* dimensionsJson, const char* measurementsJson) -HRESULT STDMETHODCALLTYPE event_write(void*, XUserHandle, const char*, const char*, const char* name, - const char* dimensions, const char* measurements) { - if (!name) return E_INVALIDARG; - const long n = g_events.fetch_add(1); - if (log_every_event()) - RT_LOG_DEBUG("game event %s dimensions=%s measurements=%s\n", name, dimensions ? dimensions : "", - measurements ? measurements : ""); - else if (n == 0) - RT_LOG_INFO("xgameruntime: game events are dropped offline (first: %s; " - "LEONIDA_LOG_GAME_EVENTS=1 logs them)\n", name); - return S_OK; -} - -HRESULT STDMETHODCALLTYPE event_query_interface(void*, REFIID iid, void** out); -const void* const kEventVtable[] = { - FN(event_query_interface), FN(object_add_ref), FN(object_release), // 0-2 IUnknown - FN(event_write), // 3 XGameEventWrite -}; -ClassObject g_event_object{kEventVtable}; -const GUID kEventInterfaces[] = {kEventClass}; -HRESULT STDMETHODCALLTYPE event_query_interface(void*, REFIID iid, void** out) { - return answer(&g_event_object, std::begin(kEventInterfaces), std::end(kEventInterfaces), iid, out); -} - -// ======================= XGameUiImpl ======================= - -constexpr char kUiName[] = "XGameUiImpl"; -constexpr GUID kUiClass = {0xdfcd4649, 0x4ff8, 0x4043, {0xba, 0x07, 0x35, 0xd6, 0x07, 0xdf, 0x98, 0xb0}}; -const GUID kUiInterfaces[] = { - kUiClass, // the class id, which a thunk may pass for its implemented interface (IXGameUiImpl4) - {0x6eeaa73e, 0x9669, 0x43ad, {0xa2, 0xc7, 0xd0, 0xda, 0x4e, 0x1f, 0x50, 0xa1}}, // IXGameUiImpl - {0x36a03122, 0x9ea3, 0x4a3a, {0xa8, 0xa4, 0x89, 0x9c, 0xfd, 0x85, 0xd7, 0xdb}}, // IXGameUiImpl2 - {0xade7eba1, 0x2093, 0x42ce, {0xa5, 0x44, 0xa5, 0x23, 0xa6, 0x67, 0x90, 0xe0}}, // IXGameUiImpl3 - {0xeaf669df, 0x5542, 0x4590, {0x99, 0xa3, 0x8d, 0xc0, 0x61, 0xf8, 0x37, 0xcc}}, // IXGameUiImpl4 -}; - -enum class XGameUiMessageDialogButton : uint32_t { First = 0, Second = 1, Third = 2 }; - -const char kDialogIdentity = 0, kErrorDialogIdentity = 0; - -// The answer of a message dialog rides in the async context: the button, which never needs more. -HRESULT CALLBACK dialog_provider(XAsyncOp op, const XAsyncProviderData* data) { - switch (op) { - case XAsyncOp::Begin: - return XAsyncSchedule(data->async, 0); - case XAsyncOp::DoWork: - XAsyncComplete(data->async, S_OK, sizeof(XGameUiMessageDialogButton)); - return S_OK; - case XAsyncOp::GetResult: - if (!data->buffer || data->bufferSize < sizeof(XGameUiMessageDialogButton)) return E_INVALIDARG; - *static_cast(data->buffer) = - static_cast(reinterpret_cast(data->context)); - return S_OK; - default: - return S_OK; - } -} - -HRESULT CALLBACK error_dialog_provider(XAsyncOp op, const XAsyncProviderData* data) { - if (op == XAsyncOp::Begin) return XAsyncSchedule(data->async, 0); - if (op == XAsyncOp::DoWork) XAsyncComplete(data->async, S_OK, 0); - return S_OK; -} - -// 3: HRESULT XGameUiShowMessageDialogAsync(XAsyncBlock* async, const char* titleText, const char* contentText, -// const char* firstButtonText, const char* secondButtonText, const char* thirdButtonText, -// XGameUiMessageDialogButton defaultButton, XGameUiMessageDialogButton cancelButton) -// The parameter list is the one the GDK reference gives; only the result-page and the enum were checked for this -// file. No caller confirms it: tools/gdk_runtime_calls.py finds no thunk for this slot in the executable -// (docs/runtime_imports.md). The dialog is "answered" with its default button. -HRESULT STDMETHODCALLTYPE ui_message_dialog_async(void*, XAsyncBlock* async, const char* title, const char* content, - const char* first, const char* second, const char* third, - XGameUiMessageDialogButton default_button, XGameUiMessageDialogButton) { - if (!async) return E_POINTER; - const auto button = static_cast(default_button); - if (button > 2) return E_INVALIDARG; - const char* labels[] = {first, second, third}; - RT_LOG_INFO("game dialog: \"%s\": %s [buttons: %s%s%s%s%s; answered: %s]\n", title ? title : "", - content ? content : "", first ? first : "", second ? " / " : "", second ? second : "", - third ? " / " : "", third ? third : "", labels[button] ? labels[button] : "(default)"); - return XAsyncBegin(async, reinterpret_cast(static_cast(button)), &kDialogIdentity, - "XGameUiShowMessageDialogAsync", dialog_provider); -} - -// 4: HRESULT XGameUiShowMessageDialogResult(XAsyncBlock* async, XGameUiMessageDialogButton* resultButton) -HRESULT STDMETHODCALLTYPE ui_message_dialog_result(void*, XAsyncBlock* async, XGameUiMessageDialogButton* button) { - if (!button) return E_POINTER; - return XAsyncGetResult(async, &kDialogIdentity, sizeof(*button), button, nullptr); -} - -// 14: HRESULT XGameUiShowErrorDialogAsync(XAsyncBlock* async, HRESULT errorCode, const char* context) -HRESULT STDMETHODCALLTYPE ui_error_dialog_async(void*, XAsyncBlock* async, HRESULT code, const char* context) { - if (!async) return E_POINTER; - RT_LOG_ERROR("game error dialog: HRESULT 0x%08lX%s%s [dismissed]\n", static_cast(code), - context ? " context " : "", context ? context : ""); - return XAsyncBegin(async, nullptr, &kErrorDialogIdentity, "XGameUiShowErrorDialogAsync", error_dialog_provider); -} - -// 15: HRESULT XGameUiShowErrorDialogResult(XAsyncBlock* async) -HRESULT STDMETHODCALLTYPE ui_error_dialog_result(void*, XAsyncBlock* async) { - return XAsyncGetResult(async, &kErrorDialogIdentity, 0, nullptr, nullptr); -} - -// 16: XGameUiSetNotificationPositionHint(position): there are no notifications to place. -HRESULT STDMETHODCALLTYPE ui_set_notification_hint(void*) { return S_OK; } - -template HRESULT STDMETHODCALLTYPE ui_offline(void* self) { return offline_failure(self); } -template HRESULT STDMETHODCALLTYPE ui_unknown(void* self) { return unknown_slot(self); } - -HRESULT STDMETHODCALLTYPE ui_query_interface(void*, REFIID iid, void** out); -const void* const kUiVtable[] = { - FN(ui_query_interface), FN(object_add_ref), FN(object_release), // 0-2 IUnknown - FN(ui_message_dialog_async), // 3 XGameUiShowMessageDialogAsync - FN(ui_message_dialog_result), // 4 XGameUiShowMessageDialogResult - FN(ui_offline<5>), // 5 XGameUiShowSendGameInviteAsync - FN(ui_offline<6>), // 6 XGameUiShowSendGameInviteResult - FN(ui_offline<7>), // 7 XGameUiShowPlayerProfileCardAsync - FN(ui_offline<8>), // 8 XGameUiShowPlayerProfileCardResult - FN(ui_offline<9>), // 9 XGameUiShowAchievementsAsync - FN(ui_offline<10>), // 10 XGameUiShowAchievementsResult - FN(ui_offline<11>), // 11 XGameUiShowPlayerPickerAsync - FN(ui_offline<12>), // 12 XGameUiShowPlayerPickerResultCount - FN(ui_offline<13>), // 13 XGameUiShowPlayerPickerResult - FN(ui_error_dialog_async), // 14 XGameUiShowErrorDialogAsync - FN(ui_error_dialog_result), // 15 XGameUiShowErrorDialogResult - FN(ui_set_notification_hint), // 16 XGameUiSetNotificationPositionHint - FN(ui_offline<17>), // 17 XGameUiShowTextEntryAsync - FN(ui_offline<18>), // 18 XGameUiShowTextEntryResultSize - FN(ui_offline<19>), // 19 XGameUiShowTextEntryResult - FN(ui_unknown<20>), // 20 (unknown in the docs) - FN(ui_unknown<21>), // 21 (unknown in the docs) - FN(ui_unknown<22>), // 22 (unknown in the docs) - FN(ui_unknown<23>), // 23 (unknown in the docs) - FN(ui_offline<24>), // 24 XGameUiShowWebAuthenticationAsync - FN(ui_offline<25>), // 25 XGameUiShowWebAuthenticationResultSize - FN(ui_offline<26>), // 26 XGameUiShowWebAuthenticationResult - FN(ui_offline<27>), // 27 XGameUiShowWebAuthenticationWithOptionsAsync - FN(ui_unknown<28>), // 28 (unknown in the docs) - FN(ui_unknown<29>), // 29 (unknown in the docs) - FN(ui_offline<30>), // 30 XGameUiShowMultiplayerActivityGameInviteAsync (2) - FN(ui_offline<31>), // 31 XGameUiShowMultiplayerActivityGameInviteResult (2) - FN(ui_unknown<32>), // 32 (unknown in the docs) (2) - FN(ui_unknown<33>), // 33 (unknown in the docs) (2) - FN(ui_offline<34>), // 34 XGameUiTextEntryOpen (2) - FN(ui_offline<35>), // 35 XGameUiTextEntryClose (2) - FN(ui_offline<36>), // 36 XGameUiTextEntryGetState (2) - FN(ui_offline<37>), // 37 XGameUiTextEntryGetExtents (2) - FN(ui_offline<38>), // 38 XGameUiTextEntryUpdatePositionHint (2) - FN(ui_offline<39>), // 39 XGameUiTextEntryUpdateVisibility (2) - FN(ui_offline<40>), // 40 XGameUiShowStateShareAsync (3) - FN(ui_offline<41>), // 41 XGameUiShowStateShareResult (3) - FN(ui_unknown<42>), // 42 XGameUiSetUiCallbacks (4, PC-hosted UI; signature not given) - FN(ui_unknown<43>), // 43 XGameUiSetMessageDialogUiResponse (4) - FN(ui_unknown<44>), // 44 XGameUiSetPlayerPickerUiResponse (4) - FN(ui_unknown<45>), // 45 XGameUiSetTextEntryUiResponse (4) - FN(ui_unknown<46>), // 46 XGameUiSetPlayerProfileCardUiResponse (4) - FN(ui_unknown<47>), // 47 XGameUiSetSendGameInviteUiResponse (4) - FN(ui_unknown<48>), // 48 XGameUiSetAchievementsUiResponse (4) - FN(ui_unknown<49>), // 49 XGameUiSetMultiplayerActivityGameInviteUiResponse (4) - FN(ui_unknown<50>), // 50 XGameUiSetErrorDialogUiResponse (4) -}; -static_assert(std::size(kUiVtable) == 51, "IUnknown + IXGameUiImpl's 27 methods + 10 + 2 + 9"); -ClassObject g_ui_object{kUiVtable}; -HRESULT STDMETHODCALLTYPE ui_query_interface(void*, REFIID iid, void** out) { - return answer(&g_ui_object, std::begin(kUiInterfaces), std::end(kUiInterfaces), iid, out); -} - -// ======================= XGameStreamingImpl ======================= - -constexpr GUID kStreamingClass = {0x0a2192aa, 0xb2d5, 0x4d58, {0x83, 0xbe, 0x38, 0x3b, 0x6d, 0x80, 0x79, 0x9e}}; -const GUID kStreamingInterfaces[] = { - kStreamingClass, // the class id, for its implemented interface (IXGameStreamingImpl3) - {0x8aff07f5, 0xa1bf, 0x4db8, {0x80, 0xa5, 0x31, 0xcc, 0xa0, 0xde, 0x51, 0xb7}}, // IXGameStreamingImpl - {0x5f5e5169, 0x746c, 0x4001, {0xad, 0x1c, 0xda, 0x72, 0x8d, 0x01, 0xc9, 0xeb}}, // IXGameStreamingImpl2 - {0x57786622, 0x6605, 0x46d0, {0xb9, 0x17, 0x0f, 0x22, 0xbb, 0xcd, 0x9c, 0x52}}, // IXGameStreamingImpl3 -}; - -std::mutex g_streaming_mutex; -uint64_t g_next_token = 1; - -// 3: HRESULT XGameStreamingInitialize() -HRESULT STDMETHODCALLTYPE streaming_initialize(void*) { return S_OK; } -// 4: void XGameStreamingUninitialize() -void STDMETHODCALLTYPE streaming_uninitialize(void*) {} -// 5: bool XGameStreamingIsStreaming(): no client is ever connected. -bool STDMETHODCALLTYPE streaming_is_streaming(void*) { return false; } -// 9: uint32_t XGameStreamingGetClientCount() -uint32_t STDMETHODCALLTYPE streaming_client_count(void*) { return 0; } - -// 12: HRESULT XGameStreamingRegisterConnectionStateChanged(XTaskQueueHandle queue, void* context, -// XGameStreamingConnectionStateChangedCallback* callback, XTaskQueueRegistrationToken* token) -// That parameter list is the GDK reference's, not re-checked for this file, and no caller confirms it: the executable -// links no XGameStreamingImpl thunk (docs/runtime_imports.md). No client connects, so the callback never runs. -HRESULT STDMETHODCALLTYPE streaming_register_connection(void*, XTaskQueueHandle, void*, void* callback, - XTaskQueueRegistrationToken* token) { - if (!callback || !token) return E_INVALIDARG; - std::lock_guard lock(g_streaming_mutex); - token->token = g_next_token++; - return S_OK; -} - -// Unregistering (7, 13): nothing is ever pending. Returns true, in case the caller reads a bool; a void caller -// ignores it. -bool STDMETHODCALLTYPE streaming_unregister(void*) { return true; } - -// Every other slot asks about a client, its touch controls or its stream, and there is none. The answer is -// E_GAMESTREAMING_NOT_INITIALIZED (0x89245400), chosen for its shape: a caller reading an HRESULT sees a failure, and -// one reading a bool (al) sees false, since its low byte is 0. The slots returning an enum or a count are the ones -// above, answered explicitly. -template HRESULT STDMETHODCALLTYPE client_not_connected(void*) { - static std::atomic s_logged{false}; - if (!s_logged.exchange(true)) - RT_LOG_WARN("xgameruntime: XGameStreamingImpl slot %d: no streaming client offline\n", Slot); - return E_GAMESTREAMING_NOT_INITIALIZED; -} -static_assert((static_cast(E_GAMESTREAMING_NOT_INITIALIZED) & 0xFF) == 0, "reads as false in al"); - -// 11: XGameStreamingConnectionState XGameStreamingGetConnectionState(XGameStreamingClientId client): 0, the first -// enumerator, taken to be Disconnected; there is no client to ask about either way, and the executable has no caller. -uint32_t STDMETHODCALLTYPE streaming_connection_state(void*) { return 0; } - -HRESULT STDMETHODCALLTYPE streaming_query_interface(void*, REFIID iid, void** out); -const void* const kStreamingVtable[] = { - FN(streaming_query_interface), FN(object_add_ref), FN(object_release), // 0-2 IUnknown - FN(streaming_initialize), // 3 XGameStreamingInitialize - FN(streaming_uninitialize), // 4 XGameStreamingUninitialize - FN(streaming_is_streaming), // 5 XGameStreamingIsStreaming - FN(client_not_connected<6>), // 6 XGameStreamingRegisterClientPropertiesChanged (per client) - FN(streaming_unregister), // 7 XGameStreamingUnregisterClientPropertiesChanged - FN(client_not_connected<8>), // 8 XGameStreamingGetStreamPhysicalDimensions - FN(streaming_client_count), // 9 XGameStreamingGetClientCount - FN(client_not_connected<10>), // 10 XGameStreamingGetClients - FN(streaming_connection_state), // 11 XGameStreamingGetConnectionState - FN(streaming_register_connection), // 12 XGameStreamingRegisterConnectionStateChanged - FN(streaming_unregister), // 13 XGameStreamingUnregisterConnectionStateChanged - FN(client_not_connected<14>), // 14 XGameStreamingGetStreamAddedLatency - FN(client_not_connected<15>), // 15 XGameStreamingGetServerLocationNameSize - FN(client_not_connected<16>), // 16 XGameStreamingGetServerLocationName - FN(client_not_connected<17>), // 17 XGameStreamingHideTouchControls - FN(client_not_connected<18>), // 18 XGameStreamingShowTouchControlLayout - FN(client_not_connected<19>), // 19 XGameStreamingHideTouchControlsOnClient - FN(client_not_connected<20>), // 20 XGameStreamingShowTouchControlLayoutOnClient - FN(client_not_connected<21>), // 21 XGameStreamingIsTouchInputEnabled (reads as false) - FN(client_not_connected<22>), // 22 XGameStreamingGetLastFrameDisplayed - FN(client_not_connected<23>), // 23 XGameStreamingGetAssociatedFrame - FN(client_not_connected<24>), // 24 XGameStreamingGetGamepadPhysicality - FN(client_not_connected<25>), // 25 XGameStreamingUpdateTouchControlsState - FN(client_not_connected<26>), // 26 XGameStreamingUpdateTouchControlsStateOnClient - FN(client_not_connected<27>), // 27 XGameStreamingShowTouchControlsWithStateUpdate - FN(client_not_connected<28>), // 28 XGameStreamingShowTouchControlsWithStateUpdateOnClient - FN(client_not_connected<29>), // 29 XGameStreamingGetTouchBundleVersionNameSize - FN(client_not_connected<30>), // 30 XGameStreamingGetTouchBundleVersion - FN(client_not_connected<31>), // 31 XGameStreamingGetClientIPAddress - FN(client_not_connected<32>), // 32 XGameStreamingGetSessionId (2) - FN(client_not_connected<33>), // 33 XGameStreamingGetDisplayDetails (3) - FN(client_not_connected<34>), // 34 XGameStreamingSetResolution (3) -}; -static_assert(std::size(kStreamingVtable) == 35, "IUnknown + IXGameStreamingImpl's 29 methods + 1 + 2"); -ClassObject g_streaming_object{kStreamingVtable}; -HRESULT STDMETHODCALLTYPE streaming_query_interface(void*, REFIID iid, void** out) { - return answer(&g_streaming_object, std::begin(kStreamingInterfaces), std::end(kStreamingInterfaces), iid, out); -} - - -// ======================= XDisplayImpl ======================= - -constexpr char kDisplayName[] = "XDisplayImpl"; -constexpr GUID kDisplayClass = {0x03f0fe74, 0xfdd9, 0x4e5c, {0xb6, 0x30, 0xf9, 0x33, 0x9c, 0x47, 0xac, 0xc5}}; -const GUID kDisplayInterfaces[] = { - kDisplayClass, - {0x35f07670, 0x706e, 0x4bfb, {0x94, 0x76, 0x09, 0x07, 0x98, 0xc5, 0xeb, 0xf3}}, // IXDisplayImpl -}; - -enum class XDisplayHdrModePreference : uint32_t { PreferHdr = 0, PreferRefreshRate = 1 }; -enum class XDisplayHdrModeResult : uint32_t { Unknown = 0, Enabled = 1, Disabled = 2 }; -struct XDisplayHdrModeInfo { - float minToneMapLuminance; // nits - float maxToneMapLuminance; - float maxFullFrameToneMapLuminance; -}; - -bool hdr_requested() { - static const bool on = rt::config::get("system.hdr").text == "1"; - return on; -} - -// 4: XDisplayHdrModeResult XDisplayTryEnableHdrMode(XDisplayHdrModePreference preference, XDisplayHdrModeInfo* info) -// The host swapchain is SDR, so HDR stays off unless LEONIDA_HDR=1; then it is "enabled" with the documented -// defaults (0.01 / 1000 / 1000 nits). -uint32_t STDMETHODCALLTYPE display_try_enable_hdr(void*, XDisplayHdrModePreference, XDisplayHdrModeInfo* info) { - const bool on = hdr_requested(); - if (info) *info = on ? XDisplayHdrModeInfo{0.01f, 1000.0f, 1000.0f} : XDisplayHdrModeInfo{}; - static std::atomic s_logged{false}; - if (!s_logged.exchange(true)) - RT_LOG_INFO("xgameruntime: XDisplayTryEnableHdrMode: HDR %s\n", - on ? "enabled (LEONIDA_HDR=1)" : "disabled (SDR output; LEONIDA_HDR=1 asks for HDR)"); - return static_cast(on ? XDisplayHdrModeResult::Enabled : XDisplayHdrModeResult::Disabled); -} - -template HRESULT STDMETHODCALLTYPE display_unknown(void* self) { return unknown_slot(self); } - -HRESULT STDMETHODCALLTYPE display_query_interface(void*, REFIID iid, void** out); -const void* const kDisplayVtable[] = { - FN(display_query_interface), FN(object_add_ref), FN(object_release), // 0-2 IUnknown - FN(display_unknown<3>), // 3 (unknown in the docs) - FN(display_try_enable_hdr), // 4 XDisplayTryEnableHdrMode -}; -ClassObject g_display_object{kDisplayVtable}; -HRESULT STDMETHODCALLTYPE display_query_interface(void*, REFIID iid, void** out) { - return answer(&g_display_object, std::begin(kDisplayInterfaces), std::end(kDisplayInterfaces), iid, out); -} - -// ======================= XUserDeviceImpl ======================= - -constexpr GUID kUserDeviceClass = {0x7d824997, 0x10dc, 0x45ab, {0x86, 0xb7, 0x27, 0x37, 0x76, 0x7c, 0x0b, 0xf1}}; -const GUID kUserDeviceInterfaces[] = { - kUserDeviceClass, // IXUserDeviceImpl - {0x0cc6a956, 0xe7e1, 0x4fdf, {0x93, 0x41, 0x9d, 0x5d, 0xa6, 0x49, 0xeb, 0xc8}}, // IXUserDeviceImpl2 (no methods) -}; - -// APP_LOCAL_DEVICE_ID is taken to be 32 bytes (APP_LOCAL_DEVICE_ID_SIZE), not on the pages read for this file. No -// caller confirms it: the executable links no XUserDeviceImpl thunk (docs/runtime_imports.md). -struct APP_LOCAL_DEVICE_ID { - uint8_t value[32]; -}; - -const char kFindControllerIdentity = 0; - -// 3: HRESULT XUserFindForDevice(const APP_LOCAL_DEVICE_ID* deviceId, XUserHandle* handle): every device belongs to -// the one offline user. -HRESULT STDMETHODCALLTYPE device_find_user(void*, const APP_LOCAL_DEVICE_ID* device, XUserHandle* out) { - if (!device || !out) return E_INVALIDARG; - *out = rt::shims::xgameruntime_user_new_handle(); - return S_OK; -} - -// 4: HRESULT XUserRegisterForDeviceAssociationChanged(XTaskQueueHandle queue, void* context, -// XUserDeviceAssociationChangedCallback* callback, XTaskQueueRegistrationToken* token) -// 5: bool XUserUnregisterForDeviceAssociationChanged(XTaskQueueRegistrationToken token, bool wait) -// 7: HRESULT XUserRegisterForDefaultAudioEndpointUtf16Changed(XTaskQueueHandle queue, void* context, -// XUserDefaultAudioEndpointUtf16ChangedCallback* callback, XTaskQueueRegistrationToken* token) -// 8: bool XUserUnregisterForDefaultAudioEndpointUtf16Changed(XTaskQueueRegistrationToken token, bool wait) -// -// Each registration is kept (its kind, a duplicate of its queue, its context and callback) under a token unique -// across both kinds and never 0, until the title unregisters it with the matching function. Offline, the device -// association and the default audio endpoint never change, so no event is ever raised: no callback is queued or -// run, and nothing here calls one. Unregistering therefore never has to wait, whatever `wait` says, and removes the -// registration at once. It returns true for every token, as XUserUnregisterForChangeEvent does: a token already -// unregistered, never handed out or of the other kind is left alone (a title polling with wait = false would spin -// on false). queue and context are _In_opt_; a null queue stays null (the process queue, if an event ever came); -// callback and token are required (E_INVALIDARG). -// -// The state is namespace-scope and the lock a constinit SRW lock, not function-local statics: these calls run on -// the title's threads. -enum class DeviceEvent : uint32_t { Association = 0, AudioEndpoint = 1 }; - -struct DeviceRegistration { - uint64_t token; - DeviceEvent kind; - XTaskQueueHandle queue; // our duplicate, closed on unregister; null for the process queue - void* context; - void* callback; -}; - -constinit SRWLOCK g_device_lock = SRWLOCK_INIT; -std::vector g_device_registrations; // guarded by g_device_lock -constinit uint64_t g_device_next_token = 1; // guarded by g_device_lock - -template -HRESULT STDMETHODCALLTYPE device_register(void*, XTaskQueueHandle queue, void* context, void* callback, - XTaskQueueRegistrationToken* token) { - if (!callback || !token) return E_INVALIDARG; - XTaskQueueHandle kept = nullptr; - if (queue) { - const HRESULT hr = XTaskQueueDuplicateHandle(queue, &kept); - if (FAILED(hr)) return hr; - } - uint64_t issued = 0; - AcquireSRWLockExclusive(&g_device_lock); - try { - g_device_registrations.push_back({g_device_next_token, Kind, kept, context, callback}); - issued = g_device_next_token++; - } catch (...) { // out of memory: no exception reaches the title - } - ReleaseSRWLockExclusive(&g_device_lock); - if (!issued) { - if (kept) XTaskQueueCloseHandle(kept); - return E_OUTOFMEMORY; - } - token->token = issued; - return S_OK; -} - -template bool STDMETHODCALLTYPE device_unregister(void*, XTaskQueueRegistrationToken token, bool) { - XTaskQueueHandle queue = nullptr; - AcquireSRWLockExclusive(&g_device_lock); - for (auto it = g_device_registrations.begin(); it != g_device_registrations.end(); ++it) - if (it->token == token.token && it->kind == Kind) { - queue = it->queue; - g_device_registrations.erase(it); - break; - } - ReleaseSRWLockExclusive(&g_device_lock); - if (queue) XTaskQueueCloseHandle(queue); - return true; -} - -// 6: HRESULT XUserGetDefaultAudioEndpointUtf16(XUserLocalId user, XUserDefaultAudioEndpointKind kind, -// size_t endpointIdUtf16Count, wchar_t* endpointIdUtf16, size_t* endpointIdUtf16Used) -// The user has no audio endpoint of its own (no headset): ERROR_NOT_FOUND, with an empty string written. -HRESULT STDMETHODCALLTYPE device_audio_endpoint(void*, uint64_t, uint32_t, size_t count, wchar_t* id, size_t* used) { - if (id && count) id[0] = L'\0'; - if (used) *used = 0; - return HRESULT_FROM_WIN32(ERROR_NOT_FOUND); -} - -HRESULT CALLBACK find_controller_provider(XAsyncOp op, const XAsyncProviderData* data) { - switch (op) { - case XAsyncOp::Begin: - return XAsyncSchedule(data->async, 0); - case XAsyncOp::DoWork: - XAsyncComplete(data->async, S_OK, sizeof(APP_LOCAL_DEVICE_ID)); - return S_OK; - case XAsyncOp::GetResult: - if (!data->buffer || data->bufferSize < sizeof(APP_LOCAL_DEVICE_ID)) return E_INVALIDARG; - *static_cast(data->buffer) = APP_LOCAL_DEVICE_ID{}; - return S_OK; - default: - return S_OK; - } -} - -// 9: HRESULT XUserFindControllerForUserWithUiAsync(XUserHandle user, XAsyncBlock* async): no UI, as on desktop. -HRESULT STDMETHODCALLTYPE device_find_controller_async(void*, XUserHandle user, XAsyncBlock* async) { - if (!user) return E_INVALIDARG; - if (!async) return E_POINTER; - return XAsyncBegin(async, nullptr, &kFindControllerIdentity, "XUserFindControllerForUserWithUiAsync", - find_controller_provider); -} - -// 10: HRESULT XUserFindControllerForUserWithUiResult(XAsyncBlock* async, APP_LOCAL_DEVICE_ID* deviceId): all zero, -// as the GDK documents for desktop. -HRESULT STDMETHODCALLTYPE device_find_controller_result(void*, XAsyncBlock* async, APP_LOCAL_DEVICE_ID* device) { - if (!device) return E_POINTER; - return XAsyncGetResult(async, &kFindControllerIdentity, sizeof(*device), device, nullptr); -} - -HRESULT STDMETHODCALLTYPE device_query_interface(void*, REFIID iid, void** out); -const void* const kUserDeviceVtable[] = { - FN(device_query_interface), FN(object_add_ref), FN(object_release), // 0-2 IUnknown - FN(device_find_user), // 3 XUserFindForDevice - FN(device_register), // 4 XUserRegisterForDeviceAssociationChanged - FN(device_unregister), // 5 XUserUnregisterForDeviceAssociationChanged - FN(device_audio_endpoint), // 6 XUserGetDefaultAudioEndpointUtf16 - FN(device_register), // 7 XUserRegisterForDefaultAudioEndpointUtf16Changed - FN(device_unregister), // 8 XUserUnregisterForDefaultAudioEndpointUtf16Changed - FN(device_find_controller_async), // 9 XUserFindControllerForUserWithUiAsync - FN(device_find_controller_result), // 10 XUserFindControllerForUserWithUiResult -}; -static_assert(std::size(kUserDeviceVtable) == 11, "IUnknown + IXUserDeviceImpl's 8 methods"); -ClassObject g_user_device_object{kUserDeviceVtable}; -HRESULT STDMETHODCALLTYPE device_query_interface(void*, REFIID iid, void** out) { - return answer(&g_user_device_object, std::begin(kUserDeviceInterfaces), std::end(kUserDeviceInterfaces), iid, out); -} - -// ======================= XAccessibilityImpl ======================= - -constexpr char kAccessibilityName[] = "XAccessibilityImpl"; -constexpr GUID kAccessibilityClass = {0x3e241977, 0x6237, 0x41e9, {0x85, 0x59, 0x10, 0x2c, 0x2d, 0x99, 0x83, 0xf1}}; -const GUID kAccessibilityInterfaces[] = { - kAccessibilityClass, // IXAccessibilityImpl: the class id - {0xd722b373, 0x8c4d, 0x4692, {0x9e, 0x51, 0xd6, 0xad, 0x9b, 0x37, 0xaa, 0x7d}}, // IXAccessibilityImpl2 -}; - -// 5: HRESULT XHighContrastGetMode(XHighContrastMode* mode): Off, the first enumerator. ASSUMPTION: the signature and -// that Off is 0 (GDK reference, not re-checked for this file). -HRESULT STDMETHODCALLTYPE accessibility_high_contrast(void*, uint32_t* mode) { - if (!mode) return E_POINTER; - *mode = 0; - return S_OK; -} - -// 4: HRESULT XClosedCaptionSetEnabled(bool enabled): there are no captions to show; accepted and dropped. -HRESULT STDMETHODCALLTYPE accessibility_captions_set_enabled(void*, bool) { return S_OK; } - -// 8: HRESULT XSpeechSynthesizerEnumerateInstalledVoices(callback, void* context): no voice is installed, so the -// callback runs zero times. ASSUMPTION: the argument order (GDK reference), only the count (2) was measured. -HRESULT STDMETHODCALLTYPE speech_enumerate_voices(void*, void* callback, void*) { - return callback ? S_OK : E_INVALIDARG; -} - -// 9: HRESULT XSpeechSynthesizerCreate(XSpeechSynthesizerHandle* handle): no synthesizer offline. -HRESULT STDMETHODCALLTYPE speech_create(void* self, void** handle) { - if (handle) *handle = nullptr; - return offline_failure(self); -} - -// 10-12, 14: a synthesizer or stream handle is the first argument, and none was ever handed out: E_INVALIDARG. -HRESULT STDMETHODCALLTYPE speech_bad_handle(void*) { return E_INVALIDARG; } - -// 13, 21: HRESULT XSpeechSynthesizerCreateStreamFromText/Ssml(synthesizer, const char* text, -// XSpeechSynthesizerStreamHandle* stream) -HRESULT STDMETHODCALLTYPE speech_create_stream(void*, void*, const char*, void** stream) { - if (stream) *stream = nullptr; - return E_INVALIDARG; -} - -// 15: HRESULT XSpeechSynthesizerGetStreamDataSize(stream, size_t* size) -HRESULT STDMETHODCALLTYPE speech_stream_size(void*, void*, size_t* size) { - if (size) *size = 0; - return E_INVALIDARG; -} - -// 16: HRESULT XSpeechSynthesizerGetStreamData(stream, size_t size, void* buffer, size_t* used) -HRESULT STDMETHODCALLTYPE speech_stream_data(void*, void*, size_t, void*, size_t* used) { - if (used) *used = 0; - return E_INVALIDARG; -} - -// The slots with no offline counterpart whose arguments the layout doesn't give: the caption properties (3) and -// speech-to-text display (6, 7, 17-20). Nothing is written. -template HRESULT STDMETHODCALLTYPE accessibility_offline(void* self) { - return offline_failure(self); -} - -HRESULT STDMETHODCALLTYPE accessibility_query_interface(void*, REFIID iid, void** out); -const void* const kAccessibilityVtable[] = { - FN(accessibility_query_interface), FN(object_add_ref), FN(object_release), // 0-2 IUnknown - FN(accessibility_offline<3>), // 3 XClosedCaptionGetProperties - FN(accessibility_captions_set_enabled), // 4 XClosedCaptionSetEnabled - FN(accessibility_high_contrast), // 5 XHighContrastGetMode - FN(accessibility_offline<6>), // 6 XSpeechToTextSetPositionHint - FN(accessibility_offline<7>), // 7 XSpeechToTextSendString - FN(speech_enumerate_voices), // 8 XSpeechSynthesizerEnumerateInstalledVoices - FN(speech_create), // 9 XSpeechSynthesizerCreate - FN(speech_bad_handle), // 10 XSpeechSynthesizerCloseHandle - FN(speech_bad_handle), // 11 XSpeechSynthesizerSetDefaultVoice - FN(speech_bad_handle), // 12 XSpeechSynthesizerSetCustomVoice - FN(speech_create_stream), // 13 XSpeechSynthesizerCreateStreamFromText - FN(speech_bad_handle), // 14 XSpeechSynthesizerCloseStreamHandle - FN(speech_stream_size), // 15 XSpeechSynthesizerGetStreamDataSize - FN(speech_stream_data), // 16 XSpeechSynthesizerGetStreamData - FN(accessibility_offline<17>), // 17 XSpeechToTextBeginHypothesisString - FN(accessibility_offline<18>), // 18 XSpeechToTextUpdateHypothesisString - FN(accessibility_offline<19>), // 19 XSpeechToTextFinalizeHypothesisString - FN(accessibility_offline<20>), // 20 XSpeechToTextCancelHypothesisString - FN(speech_create_stream), // 21 XSpeechSynthesizerCreateStreamFromSsml -}; -static_assert(std::size(kAccessibilityVtable) == 22, "IUnknown + IXAccessibilityImpl's 19 methods"); -ClassObject g_accessibility_object{kAccessibilityVtable}; -HRESULT STDMETHODCALLTYPE accessibility_query_interface(void*, REFIID iid, void** out) { - return answer(&g_accessibility_object, std::begin(kAccessibilityInterfaces), std::end(kAccessibilityInterfaces), - iid, out); -} - -// ======================= XLauncherImpl ======================= - -constexpr char kLauncherName[] = "XLauncherImpl"; -constexpr GUID kLauncherClass = {0x1b339674, 0x328d, 0x4283, {0xa2, 0x00, 0x31, 0x71, 0xf1, 0x8d, 0x36, 0x39}}; - -// 3: HRESULT XLaunchUri(XUserHandle user, const char* uri): nothing is launched; E_FAIL. -// 4: HRESULT XDisplayAcquireTimeoutDeferral(XDisplayTimeoutDeferralHandle* handle): none is handed out. -// 5: XDisplayCloseTimeoutDeferralHandle(handle): no handle exists; E_FAIL, which a void caller ignores. -HRESULT STDMETHODCALLTYPE launcher_acquire_deferral(void* self, void** handle) { - if (handle) *handle = nullptr; - return offline_failure(self); -} - -HRESULT STDMETHODCALLTYPE launcher_query_interface(void*, REFIID iid, void** out); -const void* const kLauncherVtable[] = { - FN(launcher_query_interface), FN(object_add_ref), FN(object_release), // 0-2 IUnknown - FN((offline_failure)), // 3 XLaunchUri - FN(launcher_acquire_deferral), // 4 XDisplayAcquireTimeoutDeferral - FN((offline_failure)), // 5 XDisplayCloseTimeoutDeferralHandle -}; -static_assert(std::size(kLauncherVtable) == 6, "IUnknown + IXLauncherImpl's 3 methods"); -ClassObject g_launcher_object{kLauncherVtable}; -HRESULT STDMETHODCALLTYPE launcher_query_interface(void*, REFIID iid, void** out) { - // IXLauncherImpl's id is the class id. - return answer(&g_launcher_object, &kLauncherClass, &kLauncherClass + 1, iid, out); -} - -#undef FN - -} // namespace - -namespace rt::shims { - -// Called by xgameruntime.cpp's QueryApiImpl for every class: true when the class is one of this file's, with *hr set. -bool xgameruntime_offline_query(const GUID& class_id, REFIID interface_id, void** out, HRESULT* hr) { - if (class_id == kEventClass) { - *hr = event_query_interface(nullptr, interface_id, out); - return true; - } - if (class_id == kUiClass) { - *hr = ui_query_interface(nullptr, interface_id, out); - return true; - } - if (class_id == kStreamingClass) { - *hr = streaming_query_interface(nullptr, interface_id, out); - return true; - } - if (class_id == kDisplayClass) { - *hr = display_query_interface(nullptr, interface_id, out); - return true; - } - if (class_id == kUserDeviceClass) { - *hr = device_query_interface(nullptr, interface_id, out); - return true; - } - if (class_id == kAccessibilityClass) { - *hr = accessibility_query_interface(nullptr, interface_id, out); - return true; - } - if (class_id == kLauncherClass) { - *hr = launcher_query_interface(nullptr, interface_id, out); - return true; - } - return false; -} - -// For tests: how many game events were written. -long xgameruntime_offline_game_events() { return g_events.load(); } - -// For tests: how many XUserDeviceImpl registrations of one kind (0 device association, 1 default audio endpoint) -// are kept. -long xgameruntime_offline_device_registrations(uint32_t kind) { - long n = 0; - AcquireSRWLockShared(&g_device_lock); - for (const auto& registration : g_device_registrations) - if (static_cast(registration.kind) == kind) ++n; - ReleaseSRWLockShared(&g_device_lock); - return n; -} - -} // namespace rt::shims diff --git a/runtime/shims/xgameruntime_store.cpp b/runtime/shims/xgameruntime_store.cpp deleted file mode 100644 index ff5eaebb4..000000000 --- a/runtime/shims/xgameruntime_store.cpp +++ /dev/null @@ -1,505 +0,0 @@ -// xgameruntime: XStoreImpl, the class xgameruntime.lib's XStore* functions reach through QueryApiImpl, offline. -// -// A GDK title checks its license at boot (XStoreCreateContext, XStoreQueryGameLicenseAsync) and often its add-ons -// and package updates. Each XStore* function in xgameruntime.lib asks QueryApiImpl for XStoreImpl and calls one slot -// with its own arguments after `this`. The class and interface ids and the method order are xodus-gaming/ -// xgameruntime-docs' COM/XStoreImpl pages (GPL-3.0; facts only, nothing copied); IUnknown takes slots 0-2, so the -// docs' first method is slot 3. Signatures follow Microsoft's public GDK reference (learn.microsoft.com/gaming/gdk, -// XStore pages). No GDK header or library code is used. -// -// Offline the game is owned: the game license is active, not a trial; a package's license is acquirable and valid; -// there are no add-on licenses, no products in any query and no package updates. Everything that needs the store -// service or a store UI (purchases, consumables, tokens, collections ids, downloads) fails before starting, so no -// XAsyncBlock waits, and logs once. License-changed and license-lost callbacks are never called: nothing changes. -// -// XStoreGameLicense's layout is measured on the retail executable (docs/runtime_imports.md): the title's -// XStoreQueryGameLicenseResult call passes a 104-byte stack buffer and reads the SKU id as a C string at +0x00, the -// three booleans at +0x13..+0x15, the trial id as a C string at +0x1C and the expiration time at +0x60. That fixes -// STORE_SKU_ID_SIZE = 18 and the struct's 104-byte total. -// -// UNVERIFIED: SKU_ID_SIZE = 5 and the exact TRIAL_UNIQUE_ID_MAX_SIZE = 64. The executable does not call either -// can-acquire slot (IXStoreImpl slots 24-27), so XStoreCanAcquireLicenseResult is unmeasured. It bounds the trial id -// to at most 68 bytes (the expiration time is at +0x60) but reads it as a C string, so it does not name the bound; -// 64 is the public source's value. -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include -#include -#include - -#include "../core/log.h" - -namespace { - -// ---- Public GDK types (XStore.h, as the GDK reference documents them) ---- - -using XUserHandle = void*; -struct XStoreContext { - uint32_t unused; -}; -struct XStoreLicense { - uint32_t unused; -}; -struct XStoreProductQuery { - uint32_t unused; -}; -using XStoreContextHandle = XStoreContext*; -using XStoreLicenseHandle = XStoreLicense*; -using XStoreProductQueryHandle = XStoreProductQuery*; - -constexpr size_t STORE_SKU_ID_SIZE = 18; // measured, see the header -constexpr size_t SKU_ID_SIZE = 5; // UNVERIFIED; the executable has no call site for it -constexpr size_t TRIAL_UNIQUE_ID_MAX_SIZE = 64; // public source; the executable bounds it to <= 68 - -struct XStoreGameLicense { - char skuStoreId[STORE_SKU_ID_SIZE]; - bool isActive; - bool isTrialOwnedByThisUser; - bool isDiscLicense; - bool isTrial; - uint32_t trialTimeRemainingInSeconds; - char trialUniqueId[TRIAL_UNIQUE_ID_MAX_SIZE]; - time_t expirationDate; -}; -static_assert(sizeof(XStoreGameLicense) == 104, "the layout the executable's result buffer gives"); -// The offsets the executable's XStoreQueryGameLicenseResult caller reads (docs/runtime_imports.md). -static_assert(offsetof(XStoreGameLicense, isTrialOwnedByThisUser) == 0x13, "measured flag offset"); -static_assert(offsetof(XStoreGameLicense, trialUniqueId) == 0x1C, "measured trial-id offset"); -static_assert(offsetof(XStoreGameLicense, expirationDate) == 0x60, "measured expiration offset"); - -enum class XStoreCanLicenseStatus : uint32_t { NotLicensableToUser = 0, Licensable = 1, LicenseActionNotApplicableToProduct = 2 }; -struct XStoreCanAcquireLicenseResult { - char licensableSku[SKU_ID_SIZE]; - XStoreCanLicenseStatus status; -}; -static_assert(sizeof(XStoreCanAcquireLicenseResult) == 12, "the layout the UNVERIFIED constant gives"); - -using LicenseChangedCallback = void(CALLBACK*)(void* context); - -// The SKU the offline license names. ASSUMPTION: a title compares it with nothing offline. -constexpr char kOfflineSku[] = "0010"; -static_assert(sizeof(kOfflineSku) <= SKU_ID_SIZE, "fits licensableSku"); - -// ---- Handles ---- - -std::mutex g_mutex; -std::unordered_set g_contexts, g_licenses, g_queries; -uint64_t g_next_token = 1; - -template T* new_handle(std::unordered_set& set) { - auto* h = new T{}; - std::lock_guard lock(g_mutex); - set.insert(h); - return h; -} -bool live(const std::unordered_set& set, const void* h) { - if (!h) return false; - std::lock_guard lock(g_mutex); - return set.count(h) != 0; -} -template void close_handle(std::unordered_set& set, T* h) { - { - std::lock_guard lock(g_mutex); - if (!h || set.erase(h) == 0) return; // closed already, or not ours - } - delete h; -} - -// ---- Slots that are not available offline ---- - -// An operation that needs the store service or a store UI. The *Async function fails before starting, so the -// XAsyncBlock is never used and no callback runs; its Result/ResultSize partners return the same error. Their -// arguments don't matter, so the functions take none (x64: the caller owns the argument area). -template HRESULT STDMETHODCALLTYPE offline_failure(void*) { - static std::atomic s_logged{false}; - if (!s_logged.exchange(true)) - RT_LOG_WARN("xgameruntime: XStoreImpl slot %d is not available offline (E_FAIL)\n", Slot); - return E_FAIL; -} - -// A slot the docs don't name, or name without a signature: E_NOTIMPL, so nothing reads outputs it didn't write. -template HRESULT STDMETHODCALLTYPE unknown_slot(void*) { - static std::atomic s_logged{false}; - if (!s_logged.exchange(true)) - RT_LOG_WARN("xgameruntime: XStoreImpl slot %d (no documented signature) called; E_NOTIMPL\n", Slot); - return E_NOTIMPL; -} - -// ---- Async: every served *Async completes at once on the title's queue ---- - -const char kProductsIdentity = 0, kLicenseIdentity = 0, kCanAcquireIdentity = 0, kGameLicenseIdentity = 0, - kAddOnsIdentity = 0, kUpdatesIdentity = 0; - -size_t result_size(const void* identity) { - if (identity == &kProductsIdentity) return sizeof(XStoreProductQueryHandle); - if (identity == &kLicenseIdentity) return sizeof(XStoreLicenseHandle); - if (identity == &kCanAcquireIdentity) return sizeof(XStoreCanAcquireLicenseResult); - if (identity == &kGameLicenseIdentity) return sizeof(XStoreGameLicense); - return 0; // add-ons, updates: a count of 0, no buffer -} - -// The context is the identity, so one provider serves every kind; handles are made when the title collects the -// result, so a result never collected leaks nothing. -HRESULT CALLBACK store_provider(XAsyncOp op, const XAsyncProviderData* data) { - const void* identity = data->context; - switch (op) { - case XAsyncOp::Begin: - return XAsyncSchedule(data->async, 0); - case XAsyncOp::DoWork: - XAsyncComplete(data->async, S_OK, result_size(identity)); - return S_OK; - case XAsyncOp::GetResult: - if (!data->buffer || data->bufferSize < result_size(identity)) return E_INVALIDARG; - if (identity == &kProductsIdentity) { - *static_cast(data->buffer) = new_handle(g_queries); - } else if (identity == &kLicenseIdentity) { - *static_cast(data->buffer) = new_handle(g_licenses); - } else if (identity == &kCanAcquireIdentity) { - auto* r = static_cast(data->buffer); - *r = XStoreCanAcquireLicenseResult{}; - std::memcpy(r->licensableSku, kOfflineSku, sizeof(kOfflineSku)); - r->status = XStoreCanLicenseStatus::Licensable; - } else if (identity == &kGameLicenseIdentity) { - auto* l = static_cast(data->buffer); - *l = XStoreGameLicense{}; - std::memcpy(l->skuStoreId, kOfflineSku, sizeof(kOfflineSku)); - l->isActive = true; // owned; not a trial, not a disc license, no expiry - } - return S_OK; - default: - return S_OK; - } -} - -HRESULT begin(XStoreContextHandle context, XAsyncBlock* async, const char* identity, const char* name) { - if (!async) return E_POINTER; - if (!live(g_contexts, context)) return E_INVALIDARG; - return XAsyncBegin(async, const_cast(identity), identity, name, store_provider); -} - -// ---- IXStoreImpl (slots 3-69), IXStoreImpl2-6 (70-83) ---- - -// 3: HRESULT XStoreCreateContext(const XUserHandle user, XStoreContextHandle* storeContextHandle). The user may be -// null (PC: the store's user). -HRESULT STDMETHODCALLTYPE store_create_context(void*, XUserHandle, XStoreContextHandle* out) { - if (!out) return E_POINTER; - *out = new_handle(g_contexts); - static std::atomic s_logged{false}; - if (!s_logged.exchange(true)) - RT_LOG_INFO("xgameruntime: XStore offline: the game license is active, no add-ons, no updates\n"); - return S_OK; -} - -// 4: void XStoreCloseContextHandle(XStoreContextHandle storeContextHandle) -void STDMETHODCALLTYPE store_close_context(void*, XStoreContextHandle h) { close_handle(g_contexts, h); } - -// Product queries (5-14, 77-78): every one completes with an empty query: no products, no further pages. -// 5: XStoreQueryAssociatedProductsAsync(context, XStoreProductKind, uint32_t maxItemsToRetrievePerPage, XAsyncBlock*) -HRESULT STDMETHODCALLTYPE store_query_associated_async(void*, XStoreContextHandle c, uint32_t, uint32_t, XAsyncBlock* a) { - return begin(c, a, &kProductsIdentity, "XStoreQueryAssociatedProductsAsync"); -} -// 7: XStoreQueryProductsAsync(context, kinds, const char** storeIds, size_t, const char** actionFilters, size_t, async) -HRESULT STDMETHODCALLTYPE store_query_products_async(void*, XStoreContextHandle c, uint32_t, const char**, size_t, - const char**, size_t, XAsyncBlock* a) { - return begin(c, a, &kProductsIdentity, "XStoreQueryProductsAsync"); -} -// 9: XStoreQueryEntitledProductsAsync(context, kinds, uint32_t maxItemsToRetrievePerPage, XAsyncBlock*) -HRESULT STDMETHODCALLTYPE store_query_entitled_async(void*, XStoreContextHandle c, uint32_t, uint32_t, XAsyncBlock* a) { - return begin(c, a, &kProductsIdentity, "XStoreQueryEntitledProductsAsync"); -} -// 11: XStoreQueryProductForCurrentGameAsync(context, XAsyncBlock*) -HRESULT STDMETHODCALLTYPE store_query_current_game_async(void*, XStoreContextHandle c, XAsyncBlock* a) { - return begin(c, a, &kProductsIdentity, "XStoreQueryProductForCurrentGameAsync"); -} -// 13: XStoreQueryProductForPackageAsync(context, kinds, const char* packageIdentifier, XAsyncBlock*) -HRESULT STDMETHODCALLTYPE store_query_for_package_async(void*, XStoreContextHandle c, uint32_t, const char*, - XAsyncBlock* a) { - return begin(c, a, &kProductsIdentity, "XStoreQueryProductForPackageAsync"); -} -// 77: XStoreQueryAssociatedProductsForStoreIdAsync(context, const char* storeId, kinds, uint32_t maxItems, async) -HRESULT STDMETHODCALLTYPE store_query_associated_for_id_async(void*, XStoreContextHandle c, const char*, uint32_t, - uint32_t, XAsyncBlock* a) { - return begin(c, a, &kProductsIdentity, "XStoreQueryAssociatedProductsForStoreIdAsync"); -} -// 6, 8, 10, 12, 14, 18, 78: HRESULT ...Result(XAsyncBlock* async, XStoreProductQueryHandle* productQueryHandle) -HRESULT STDMETHODCALLTYPE store_products_result(void*, XAsyncBlock* async, XStoreProductQueryHandle* out) { - if (!out) return E_POINTER; - *out = nullptr; - return XAsyncGetResult(async, &kProductsIdentity, sizeof(*out), out, nullptr); -} - -// 15: HRESULT XStoreEnumerateProductsQuery(productQueryHandle, void* context, XStoreProductQueryCallback* callback) -HRESULT STDMETHODCALLTYPE store_enumerate_products(void*, XStoreProductQueryHandle q, void*, void* callback) { - if (!callback) return E_INVALIDARG; - return live(g_queries, q) ? S_OK : E_INVALIDARG; // no products: the callback is never called -} - -// 16: bool XStoreProductsQueryHasMorePages(const XStoreProductQueryHandle productQueryHandle) -bool STDMETHODCALLTYPE store_has_more_pages(void*, XStoreProductQueryHandle) { return false; } - -// 17: HRESULT XStoreProductsQueryNextPageAsync(productQueryHandle, XAsyncBlock*): there is no next page. -HRESULT STDMETHODCALLTYPE store_next_page_async(void*, XStoreProductQueryHandle, XAsyncBlock* async) { - return async ? E_INVALIDARG : E_POINTER; -} - -// 19: void XStoreCloseProductsQueryHandle(XStoreProductQueryHandle productQueryHandle) -void STDMETHODCALLTYPE store_close_query(void*, XStoreProductQueryHandle h) { close_handle(g_queries, h); } - -// 20: HRESULT XStoreAcquireLicenseForPackageAsync(context, const char* packageIdentifier, XAsyncBlock*) -HRESULT STDMETHODCALLTYPE store_acquire_package_async(void*, XStoreContextHandle c, const char* package, XAsyncBlock* a) { - if (!package) return E_INVALIDARG; - return begin(c, a, &kLicenseIdentity, "XStoreAcquireLicenseForPackageAsync"); -} -// 21: HRESULT XStoreAcquireLicenseForPackageResult(XAsyncBlock* async, XStoreLicenseHandle* storeLicenseHandle) -HRESULT STDMETHODCALLTYPE store_acquire_package_result(void*, XAsyncBlock* async, XStoreLicenseHandle* out) { - if (!out) return E_POINTER; - *out = nullptr; - return XAsyncGetResult(async, &kLicenseIdentity, sizeof(*out), out, nullptr); -} - -// 22: bool XStoreIsLicenseValid(const XStoreLicenseHandle storeLicenseHandle) -bool STDMETHODCALLTYPE store_is_license_valid(void*, XStoreLicenseHandle h) { return live(g_licenses, h); } - -// 23: void XStoreCloseLicenseHandle(XStoreLicenseHandle storeLicenseHandle) -void STDMETHODCALLTYPE store_close_license(void*, XStoreLicenseHandle h) { close_handle(g_licenses, h); } - -// 24: HRESULT XStoreCanAcquireLicenseForStoreIdAsync(context, const char* storeProductId, XAsyncBlock*) -// 26: HRESULT XStoreCanAcquireLicenseForPackageAsync(context, const char* packageIdentifier, XAsyncBlock*) -HRESULT STDMETHODCALLTYPE store_can_acquire_async(void*, XStoreContextHandle c, const char* id, XAsyncBlock* a) { - if (!id) return E_INVALIDARG; - return begin(c, a, &kCanAcquireIdentity, "XStoreCanAcquireLicenseAsync"); -} -// 25, 27: HRESULT ...Result(XAsyncBlock* async, XStoreCanAcquireLicenseResult* storeCanAcquireLicense) -HRESULT STDMETHODCALLTYPE store_can_acquire_result(void*, XAsyncBlock* async, XStoreCanAcquireLicenseResult* out) { - if (!out) return E_POINTER; - return XAsyncGetResult(async, &kCanAcquireIdentity, sizeof(*out), out, nullptr); -} - -// 28: HRESULT XStoreQueryGameLicenseAsync(const XStoreContextHandle storeContextHandle, XAsyncBlock* async) -HRESULT STDMETHODCALLTYPE store_game_license_async(void*, XStoreContextHandle c, XAsyncBlock* a) { - return begin(c, a, &kGameLicenseIdentity, "XStoreQueryGameLicenseAsync"); -} -// 29: HRESULT XStoreQueryGameLicenseResult(XAsyncBlock* async, XStoreGameLicense* license) -HRESULT STDMETHODCALLTYPE store_game_license_result(void*, XAsyncBlock* async, XStoreGameLicense* out) { - if (!out) return E_POINTER; - return XAsyncGetResult(async, &kGameLicenseIdentity, sizeof(*out), out, nullptr); -} - -// 30: HRESULT XStoreQueryAddOnLicensesAsync(const XStoreContextHandle storeContextHandle, XAsyncBlock* async) -HRESULT STDMETHODCALLTYPE store_addons_async(void*, XStoreContextHandle c, XAsyncBlock* a) { - return begin(c, a, &kAddOnsIdentity, "XStoreQueryAddOnLicensesAsync"); -} -// 55: HRESULT XStoreQueryGameAndDlcPackageUpdatesAsync(const XStoreContextHandle storeContextHandle, XAsyncBlock*) -HRESULT STDMETHODCALLTYPE store_updates_async(void*, XStoreContextHandle c, XAsyncBlock* a) { - return begin(c, a, &kUpdatesIdentity, "XStoreQueryGameAndDlcPackageUpdatesAsync"); -} -// 79: HRESULT XStoreQueryPackageUpdatesAsync(context, const char** packageIdentifiers, size_t count, XAsyncBlock*) -HRESULT STDMETHODCALLTYPE store_package_updates_async(void*, XStoreContextHandle c, const char**, size_t, XAsyncBlock* a) { - return begin(c, a, &kUpdatesIdentity, "XStoreQueryPackageUpdatesAsync"); -} - -// 31: HRESULT XStoreQueryAddOnLicensesResultCount(XAsyncBlock* async, uint32_t* count) -HRESULT STDMETHODCALLTYPE store_addons_count(void*, XAsyncBlock* async, uint32_t* count) { - if (!count) return E_POINTER; - *count = 0; - return XAsyncGetResult(async, &kAddOnsIdentity, 0, nullptr, nullptr); -} -// 56, 80: HRESULT ...ResultCount(XAsyncBlock* async, uint32_t* count) -HRESULT STDMETHODCALLTYPE store_updates_count(void*, XAsyncBlock* async, uint32_t* count) { - if (!count) return E_POINTER; - *count = 0; - return XAsyncGetResult(async, &kUpdatesIdentity, 0, nullptr, nullptr); -} -// 32: HRESULT XStoreQueryAddOnLicensesResult(XAsyncBlock* async, uint32_t count, XStoreAddonLicense* addOnLicenses) -HRESULT STDMETHODCALLTYPE store_addons_result(void*, XAsyncBlock* async, uint32_t count, void*) { - if (count != 0) return E_INVALIDARG; // the count was 0 - return XAsyncGetResult(async, &kAddOnsIdentity, 0, nullptr, nullptr); -} -// 57, 81: HRESULT ...Result(XAsyncBlock* async, uint32_t count, XStorePackageUpdate* packageUpdates) -HRESULT STDMETHODCALLTYPE store_updates_result(void*, XAsyncBlock* async, uint32_t count, void*) { - if (count != 0) return E_INVALIDARG; - return XAsyncGetResult(async, &kUpdatesIdentity, 0, nullptr, nullptr); -} - -// 65: HRESULT XStoreQueryPackageIdentifier(const char* storeId, size_t size, char* packageIdentifier): no store -// product is installed as a package offline. -HRESULT STDMETHODCALLTYPE store_query_package_identifier(void*, const char* store_id, size_t size, char* out) { - if (!store_id || !out) return E_INVALIDARG; - if (size) out[0] = '\0'; - return HRESULT_FROM_WIN32(ERROR_NOT_FOUND); -} - -// 66: HRESULT XStoreRegisterGameLicenseChanged(context, XTaskQueueHandle, void* context, callback, token*) -// 68: HRESULT XStoreRegisterPackageLicenseLost(licenseHandle, XTaskQueueHandle, void* context, callback, token*) -// Nothing changes offline: the token is handed out, the callback is never called. -HRESULT STDMETHODCALLTYPE store_register(void*, void* handle, XTaskQueueHandle, void*, LicenseChangedCallback callback, - XTaskQueueRegistrationToken* token) { - if (!handle || !callback || !token) return E_INVALIDARG; - std::lock_guard lock(g_mutex); - token->token = g_next_token++; - return S_OK; -} -// 67, 69: bool ...Unregister...(handle, XTaskQueueRegistrationToken token, bool wait): never pending, so true. -bool STDMETHODCALLTYPE store_unregister(void*, void*, XTaskQueueRegistrationToken, bool) { return true; } - -// ---- The object ---- - -constexpr GUID kStoreClass = {0x0dd112ac, 0x7c24, 0x448c, {0xb9, 0x2b, 0x39, 0x60, 0xfb, 0x5b, 0xd3, 0x0c}}; -const GUID kStoreInterfaces[] = { - kStoreClass, // IXStoreImpl - {0x60b09f4e, 0x1b85, 0x45b1, {0x82, 0x6c, 0x16, 0x91, 0x18, 0xe2, 0x30, 0xe1}}, // IXStoreImpl2 - {0x2d42fea5, 0xe71d, 0x4b76, {0x97, 0xcd, 0xc5, 0x0a, 0xfb, 0xb3, 0xae, 0x5d}}, // IXStoreImpl3 - {0xde3dbdd4, 0x0b37, 0x4bdb, {0xa1, 0x0e, 0xac, 0xf3, 0xa3, 0x54, 0xd0, 0x6a}}, // IXStoreImpl4 - {0x5c48dedf, 0x0b67, 0x4492, {0xa4, 0xb5, 0x68, 0x29, 0xb8, 0xe7, 0x96, 0xe1}}, // IXStoreImpl5 - {0xb09d803c, 0x2414, 0x4a05, {0x82, 0xc6, 0x66, 0xdf, 0xdc, 0x9e, 0x9a, 0x44}}, // IXStoreImpl6 -}; -constexpr GUID kIUnknown = {0x00000000, 0x0000, 0x0000, {0xc0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x46}}; - -struct StoreObject { - const void* const* vtable; -}; -StoreObject* store_object(); - -HRESULT query(REFIID iid, void** out) { - if (!out) return E_POINTER; - *out = nullptr; - if (iid == kIUnknown) { - *out = store_object(); - return S_OK; - } - for (const GUID& id : kStoreInterfaces) - if (iid == id) { - *out = store_object(); - return S_OK; - } - return E_NOINTERFACE; -} - -// A process-wide singleton, as the other runtime classes: AddRef and Release don't free. -HRESULT STDMETHODCALLTYPE object_query_interface(void*, REFIID iid, void** out) { return query(iid, out); } -ULONG STDMETHODCALLTYPE object_add_ref(void*) { return 2; } -ULONG STDMETHODCALLTYPE object_release(void*) { return 1; } - -#define FN(f) reinterpret_cast(&f) - -const void* const kStoreVtable[] = { - FN(object_query_interface), FN(object_add_ref), FN(object_release), // 0-2 IUnknown - FN(store_create_context), // 3 XStoreCreateContext - FN(store_close_context), // 4 XStoreCloseContextHandle - FN(store_query_associated_async), // 5 XStoreQueryAssociatedProductsAsync - FN(store_products_result), // 6 XStoreQueryAssociatedProductsResult - FN(store_query_products_async), // 7 XStoreQueryProductsAsync - FN(store_products_result), // 8 XStoreQueryProductsResult - FN(store_query_entitled_async), // 9 XStoreQueryEntitledProductsAsync - FN(store_products_result), // 10 XStoreQueryEntitledProductsResult - FN(store_query_current_game_async), // 11 XStoreQueryProductForCurrentGameAsync - FN(store_products_result), // 12 XStoreQueryProductForCurrentGameResult - FN(store_query_for_package_async), // 13 XStoreQueryProductForPackageAsync - FN(store_products_result), // 14 XStoreQueryProductForPackageResult - FN(store_enumerate_products), // 15 XStoreEnumerateProductsQuery - FN(store_has_more_pages), // 16 XStoreProductsQueryHasMorePages - FN(store_next_page_async), // 17 XStoreProductsQueryNextPageAsync - FN(store_products_result), // 18 XStoreProductsQueryNextPageResult - FN(store_close_query), // 19 XStoreCloseProductsQueryHandle - FN(store_acquire_package_async), // 20 XStoreAcquireLicenseForPackageAsync - FN(store_acquire_package_result), // 21 XStoreAcquireLicenseForPackageResult - FN(store_is_license_valid), // 22 XStoreIsLicenseValid - FN(store_close_license), // 23 XStoreCloseLicenseHandle - FN(store_can_acquire_async), // 24 XStoreCanAcquireLicenseForStoreIdAsync - FN(store_can_acquire_result), // 25 XStoreCanAcquireLicenseForStoreIdResult - FN(store_can_acquire_async), // 26 XStoreCanAcquireLicenseForPackageAsync - FN(store_can_acquire_result), // 27 XStoreCanAcquireLicenseForPackageResult - FN(store_game_license_async), // 28 XStoreQueryGameLicenseAsync - FN(store_game_license_result), // 29 XStoreQueryGameLicenseResult - FN(store_addons_async), // 30 XStoreQueryAddOnLicensesAsync - FN(store_addons_count), // 31 XStoreQueryAddOnLicensesResultCount - FN(store_addons_result), // 32 XStoreQueryAddOnLicensesResult - FN(offline_failure<33>), // 33 XStoreQueryConsumableBalanceRemainingAsync - FN(offline_failure<34>), // 34 XStoreQueryConsumableBalanceRemainingResult - FN(offline_failure<35>), // 35 XStoreReportConsumableFulfillmentAsync - FN(offline_failure<36>), // 36 XStoreReportConsumableFulfillmentResult - FN(offline_failure<37>), // 37 XStoreGetUserCollectionsIdAsync - FN(offline_failure<38>), // 38 XStoreGetUserCollectionsIdResultSize - FN(offline_failure<39>), // 39 XStoreGetUserCollectionsIdResult - FN(offline_failure<40>), // 40 XStoreGetUserPurchaseIdAsync - FN(offline_failure<41>), // 41 XStoreGetUserPurchaseIdResultSize - FN(offline_failure<42>), // 42 XStoreGetUserPurchaseIdResult - FN(offline_failure<43>), // 43 XStoreQueryLicenseTokenAsync - FN(offline_failure<44>), // 44 XStoreQueryLicenseTokenResultSize - FN(offline_failure<45>), // 45 XStoreQueryLicenseTokenResult - FN(unknown_slot<46>), // 46 (unknown in the docs) - FN(unknown_slot<47>), // 47 (unknown in the docs) - FN(unknown_slot<48>), // 48 (unknown in the docs) - FN(offline_failure<49>), // 49 XStoreShowPurchaseUIAsync - FN(offline_failure<50>), // 50 XStoreShowPurchaseUIResult - FN(offline_failure<51>), // 51 XStoreShowRateAndReviewUIAsync - FN(offline_failure<52>), // 52 XStoreShowRateAndReviewUIResult - FN(offline_failure<53>), // 53 XStoreShowRedeemTokenUIAsync - FN(offline_failure<54>), // 54 XStoreShowRedeemTokenUIResult - FN(store_updates_async), // 55 XStoreQueryGameAndDlcPackageUpdatesAsync - FN(store_updates_count), // 56 XStoreQueryGameAndDlcPackageUpdatesResultCount - FN(store_updates_result), // 57 XStoreQueryGameAndDlcPackageUpdatesResult - FN(offline_failure<58>), // 58 XStoreDownloadPackageUpdatesAsync - FN(offline_failure<59>), // 59 XStoreDownloadPackageUpdatesResult - FN(offline_failure<60>), // 60 XStoreDownloadAndInstallPackageUpdatesAsync - FN(offline_failure<61>), // 61 XStoreDownloadAndInstallPackageUpdatesResult - FN(offline_failure<62>), // 62 XStoreDownloadAndInstallPackagesAsync - FN(offline_failure<63>), // 63 XStoreDownloadAndInstallPackagesResultCount - FN(offline_failure<64>), // 64 XStoreDownloadAndInstallPackagesResult - FN(store_query_package_identifier), // 65 XStoreQueryPackageIdentifier - FN(store_register), // 66 XStoreRegisterGameLicenseChanged - FN(store_unregister), // 67 XStoreUnregisterGameLicenseChanged - FN(store_register), // 68 XStoreRegisterPackageLicenseLost - FN(store_unregister), // 69 XStoreUnregisterPackageLicenseLost - FN(unknown_slot<70>), // 70 XStoreIsAvailabilityPurchasable (2; no documented signature) - FN(offline_failure<71>), // 71 XStoreAcquireLicenseForDurablesAsync (3) - FN(offline_failure<72>), // 72 XStoreAcquireLicenseForDurablesResult (3) - FN(offline_failure<73>), // 73 XStoreShowAssociatedProductsUIAsync (4) - FN(offline_failure<74>), // 74 XStoreShowAssociatedProductsUIResult (4) - FN(offline_failure<75>), // 75 XStoreShowProductPageUIAsync (4) - FN(offline_failure<76>), // 76 XStoreShowProductPageUIResult (4) - FN(store_query_associated_for_id_async), // 77 XStoreQueryAssociatedProductsForStoreIdAsync (5) - FN(store_products_result), // 78 XStoreQueryAssociatedProductsForStoreIdResult (5) - FN(store_package_updates_async), // 79 XStoreQueryPackageUpdatesAsync (5) - FN(store_updates_count), // 80 XStoreQueryPackageUpdatesResultCount (5) - FN(store_updates_result), // 81 XStoreQueryPackageUpdatesResult (5) - FN(offline_failure<82>), // 82 XStoreShowGiftingUIAsync (6) - FN(offline_failure<83>), // 83 XStoreShowGiftingUIResult (6) -}; -static_assert(std::size(kStoreVtable) == 84, "IUnknown + IXStoreImpl's 67 methods + 1 + 2 + 4 + 5 + 2"); - -#undef FN - -StoreObject* store_object() { - static StoreObject o{kStoreVtable}; - return &o; -} - -} // namespace - -namespace rt::shims { - -// Called by xgameruntime.cpp's QueryApiImpl for every class: true when the class is XStoreImpl, with *hr set. -bool xgameruntime_store_query(const GUID& class_id, REFIID interface_id, void** out, HRESULT* hr) { - if (class_id != kStoreClass) return false; - *hr = query(interface_id, out); - return true; -} - -// For tests: the context, license and product-query handles a title holds open. -long xgameruntime_store_open_handles() { - std::lock_guard lock(g_mutex); - return static_cast(g_contexts.size() + g_licenses.size() + g_queries.size()); -} - -} // namespace rt::shims diff --git a/runtime/shims/xgameruntime_user.cpp b/runtime/shims/xgameruntime_user.cpp deleted file mode 100644 index 1e9e90c79..000000000 --- a/runtime/shims/xgameruntime_user.cpp +++ /dev/null @@ -1,545 +0,0 @@ -// xgameruntime: XUserImpl, the class xgameruntime.lib's XUser* functions reach through QueryApiImpl, offline. -// -// A GDK title links XUserAddAsync, XUserGetId, XUserGetGamertag and the rest statically (xgameruntime.lib); each of -// those thunks asks QueryApiImpl for XUserImpl and calls one slot with the function's own arguments after `this` -// (docs/runtime_imports.md, "Run-time loaded modules"; xgameruntime.cpp serves the other classes the same way). -// The class and interface ids and the slot order are xodus-gaming/xgameruntime-docs' "Layout" lists (GPL-3.0; facts -// only, nothing copied). Signatures, enum values and error codes follow Microsoft's public GDK reference -// (learn.microsoft.com/gaming/gdk, XUser and Error Codes pages). No GDK header or library code is used. -// -// Offline there is one local user, always signed in: the default user XUserAddAsync returns (with or without -// AddDefaultUserSilently), with a fixed Xbox user id and local id, and a gamertag from LEONIDA_GAMERTAG (15 ASCII -// characters at most, "Player" otherwise). Nothing goes online: token and gamer-picture requests fail as they would -// without a network, and the user never changes, so registered change callbacks are never called. -// -// The executable links thunks for IXUserImpl slots 3-5, 7-14, 19-25 and 33-34 and IXUserGamertagImpl slot 3 -// (tools/gdk_runtime_calls.py, from the file alone; docs/runtime_imports.md). None of them is a private or PC-only -// slot; those still log once when called. -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include -#include -#include - -#include "../core/config.h" -#include "../core/log.h" - -namespace { - -// ---- Public GDK types (XUser.h, as the GDK reference documents them) ---- - -using XUserHandle = struct XUserLocal*; // opaque to the title -using XUserSignOutDeferralHandle = struct XUserSignOutDeferral*; -struct XUserLocalId { - uint64_t value; -}; -enum class XUserAddOptions : uint32_t { None = 0x00, AddDefaultUserSilently = 0x01, AllowGuests = 0x02, AddDefaultUserAllowingUI = 0x04 }; -enum class XUserState : uint32_t { SignedIn = 0, SigningOut = 1, SignedOut = 2 }; -enum class XUserAgeGroup : uint32_t { Unknown = 0, Child = 1, Teen = 2, Adult = 3 }; -enum class XUserGamertagComponent : uint32_t { Classic = 0, Modern = 1, ModernSuffix = 2, UniqueModern = 3 }; -enum class XUserPrivilegeDenyReason : uint32_t { None = 0 }; -enum class XUserChangeEvent : uint32_t { SignedInAgain = 0 }; -using XUserChangeEventCallback = void(CALLBACK*)(void* context, XUserLocalId user, XUserChangeEvent event); - -// XGameErr.h values, from the GDK "Error codes" page. -constexpr HRESULT E_GAMEUSER_USER_NOT_FOUND = static_cast(0x89245104); -constexpr HRESULT E_GAMEUSER_DEFERRAL_NOT_AVAILABLE = static_cast(0x89245103); -constexpr HRESULT E_GAMEUSER_FAILED_TO_RESOLVE = static_cast(0x89245107); -constexpr HRESULT E_GAMEUSER_FAILED_TO_GET_TOKEN = static_cast(0x89245111); -constexpr HRESULT kInsufficientBuffer = HRESULT_FROM_WIN32(ERROR_INSUFFICIENT_BUFFER); - -// ---- The offline user ---- - -// Fixed, non-zero ids. The Xbox user id has the shape of a real XUID (a 64-bit number); nothing checks it offline. -constexpr uint64_t kOfflineXuid = 0x0009000000000001ull; -constexpr uint64_t kOfflineLocalId = 1; - -const char* gamertag() { - static char tag[16] = "Player"; - static std::once_flag once; - std::call_once(once, [] { - const std::string value = rt::config::get("system.gamertag").text; // "Player" when nothing sets it - if (value.size() > 15) { - RT_LOG_WARN("xgameruntime: LEONIDA_GAMERTAG is longer than 15 characters; using \"Player\"\n"); - return; - } - for (const char c : value) - if (static_cast(c) < 0x20 || static_cast(c) > 0x7e) { - RT_LOG_WARN("xgameruntime: LEONIDA_GAMERTAG is not printable ASCII; using \"Player\"\n"); - return; - } - std::memcpy(tag, value.c_str(), value.size() + 1); - }); - return tag; -} - -// A title must close every XUserHandle it gets exactly once, so each one is its own allocation; they all name the -// one local user. A handle is valid while it is in the live set: it's looked up, never read, so a closed or foreign -// pointer is refused without touching its memory. The block is freed on close, so the heap may hand its address out -// again; a stale handle then names a newer live one, which is harmless here since every handle names the same user. -struct XUserLocal { - uint32_t unused; -}; -std::mutex g_handles_mutex; -std::unordered_set g_handles; - -XUserHandle new_handle() { - auto* h = new XUserLocal{}; - std::lock_guard lock(g_handles_mutex); - g_handles.insert(h); - return h; -} -bool valid(XUserHandle h) { - if (!h) return false; - std::lock_guard lock(g_handles_mutex); - return g_handles.count(h) != 0; -} - -// ---- IXUserImpl (slots 3-36) ---- - -// 3: HRESULT XUserDuplicateHandle(XUserHandle handle, XUserHandle* duplicatedHandle) -HRESULT STDMETHODCALLTYPE user_duplicate(void*, XUserHandle handle, XUserHandle* dup) { - if (!dup) return E_POINTER; - *dup = nullptr; - if (!valid(handle)) return E_INVALIDARG; - *dup = new_handle(); - return S_OK; -} - -// 4: void XUserCloseHandle(XUserHandle user) -void STDMETHODCALLTYPE user_close(void*, XUserHandle user) { - { - std::lock_guard lock(g_handles_mutex); - if (!user || g_handles.erase(user) == 0) return; // closed already, or not ours - } - delete user; -} - -// 5: int32_t XUserCompare(XUserHandle user1, XUserHandle user2): 0 when both name the same user. Every valid handle -// names the one local user. -int32_t STDMETHODCALLTYPE user_compare(void*, XUserHandle a, XUserHandle b) { - const bool va = valid(a), vb = valid(b); - if (va && vb) return 0; - if (va != vb) return va ? 1 : -1; - return a == b ? 0 : (a < b ? -1 : 1); -} - -// 6: HRESULT XUserGetMaxUsers(uint32_t* maxUsers). One local user offline. -HRESULT STDMETHODCALLTYPE user_get_max_users(void*, uint32_t* max_users) { - if (!max_users) return E_POINTER; - *max_users = 1; - return S_OK; -} - -// XAsync providers. The result of an add is a new handle, created when the title collects it, so a result the -// title never collects leaks nothing. -const char kAddIdentity = 0; -const char kAddByIdIdentity = 0; -const char kResolveIdentity = 0; - -HRESULT CALLBACK add_provider(XAsyncOp op, const XAsyncProviderData* data) { - switch (op) { - case XAsyncOp::Begin: - return XAsyncSchedule(data->async, 0); - case XAsyncOp::DoWork: - XAsyncComplete(data->async, S_OK, sizeof(XUserHandle)); - return S_OK; - case XAsyncOp::GetResult: - if (data->bufferSize < sizeof(XUserHandle) || !data->buffer) return E_INVALIDARG; - *static_cast(data->buffer) = new_handle(); - return S_OK; - default: - return S_OK; - } -} - -// The add-by-id flavour: the context is the requested id; an id other than the local user's completes with -// E_GAMEUSER_USER_NOT_FOUND (no other user can sign in offline). -HRESULT CALLBACK add_by_id_provider(XAsyncOp op, const XAsyncProviderData* data) { - switch (op) { - case XAsyncOp::Begin: - return XAsyncSchedule(data->async, 0); - case XAsyncOp::DoWork: { - const bool known = reinterpret_cast(data->context) == static_cast(kOfflineXuid); - XAsyncComplete(data->async, known ? S_OK : E_GAMEUSER_USER_NOT_FOUND, known ? sizeof(XUserHandle) : 0); - return S_OK; - } - case XAsyncOp::GetResult: - if (data->bufferSize < sizeof(XUserHandle) || !data->buffer) return E_INVALIDARG; - *static_cast(data->buffer) = new_handle(); - return S_OK; - default: - return S_OK; - } -} - -// Resolving a privilege: every privilege is granted offline, so there is nothing to show; completes with S_OK. -HRESULT CALLBACK resolve_provider(XAsyncOp op, const XAsyncProviderData* data) { - if (op == XAsyncOp::Begin) return XAsyncSchedule(data->async, 0); - if (op == XAsyncOp::DoWork) XAsyncComplete(data->async, S_OK, 0); - return S_OK; -} - -// 7: HRESULT XUserAddAsync(XUserAddOptions options, XAsyncBlock* async). AllowGuests with AddDefaultUserSilently is -// refused, as documented ("A guest cannot be the default user"). Without a silent option the console would show the -// account picker; offline the one user is the answer either way. -HRESULT STDMETHODCALLTYPE user_add_async(void*, XUserAddOptions options, XAsyncBlock* async) { - if (!async) return E_POINTER; - const auto bits = static_cast(options); - if ((bits & static_cast(XUserAddOptions::AddDefaultUserSilently)) && - (bits & static_cast(XUserAddOptions::AllowGuests))) - return E_INVALIDARG; - return XAsyncBegin(async, nullptr, &kAddIdentity, "XUserAddAsync", add_provider); -} - -// 8: HRESULT XUserAddResult(XAsyncBlock* async, XUserHandle* newUser) -HRESULT STDMETHODCALLTYPE user_add_result(void*, XAsyncBlock* async, XUserHandle* user) { - if (!user) return E_POINTER; - *user = nullptr; - return XAsyncGetResult(async, &kAddIdentity, sizeof(*user), user, nullptr); -} - -// 9: HRESULT XUserGetLocalId(XUserHandle user, XUserLocalId* userLocalId) -HRESULT STDMETHODCALLTYPE user_get_local_id(void*, XUserHandle user, XUserLocalId* id) { - if (!id) return E_POINTER; - if (!valid(user)) return E_INVALIDARG; - id->value = kOfflineLocalId; - return S_OK; -} - -// 10: HRESULT XUserFindUserByLocalId(XUserLocalId userLocalId, XUserHandle* handle) -HRESULT STDMETHODCALLTYPE user_find_by_local_id(void*, XUserLocalId id, XUserHandle* handle) { - if (!handle) return E_POINTER; - *handle = nullptr; - if (id.value != kOfflineLocalId) return E_GAMEUSER_USER_NOT_FOUND; - *handle = new_handle(); - return S_OK; -} - -// 11: HRESULT XUserGetId(XUserHandle user, uint64_t* userId) -HRESULT STDMETHODCALLTYPE user_get_id(void*, XUserHandle user, uint64_t* id) { - if (!id) return E_POINTER; - if (!valid(user)) return E_INVALIDARG; - *id = kOfflineXuid; - return S_OK; -} - -// 12: HRESULT XUserFindUserById(uint64_t userId, XUserHandle* handle) -HRESULT STDMETHODCALLTYPE user_find_by_id(void*, uint64_t id, XUserHandle* handle) { - if (!handle) return E_POINTER; - *handle = nullptr; - if (id != kOfflineXuid) return E_GAMEUSER_USER_NOT_FOUND; - *handle = new_handle(); - return S_OK; -} - -// 13: HRESULT XUserGetIsGuest(XUserHandle user, bool* isGuest) -HRESULT STDMETHODCALLTYPE user_get_is_guest(void*, XUserHandle user, bool* guest) { - if (!guest) return E_POINTER; - if (!valid(user)) return E_INVALIDARG; - *guest = false; - return S_OK; -} - -// 14: HRESULT XUserGetState(XUserHandle user, XUserState* state) -HRESULT STDMETHODCALLTYPE user_get_state(void*, XUserHandle user, XUserState* state) { - if (!state) return E_POINTER; - if (!valid(user)) return E_INVALIDARG; - *state = XUserState::SignedIn; - return S_OK; -} - -// A slot with no public signature, logged once. Slot 15 (the docs' "unknown") answers E_NOTIMPL, so a caller fails -// instead of reading outputs nothing wrote. Slot 47, IXUserImpl6's undocumented XUserIsSignOutPresent, is read as a -// bool, where E_NOTIMPL's low byte (1) would mean true, so it answers 0 (false: nothing signs out offline). -template HRESULT STDMETHODCALLTYPE unknown_slot(void*) { - static std::atomic s_logged{false}; - if (!s_logged.exchange(true)) - RT_LOG_WARN("xgameruntime: XUserImpl slot %d has no public signature; answering E_NOTIMPL\n", Slot); - return E_NOTIMPL; -} -template uint64_t STDMETHODCALLTYPE private_slot(void*) { - static std::atomic s_logged{false}; - if (!s_logged.exchange(true)) - RT_LOG_WARN("xgameruntime: XUserImpl private slot %d called; answering 0\n", Slot); - return 0; -} - -// An operation that needs the network or a system UI the offline runtime doesn't have. The *Async function fails -// before starting, so the XAsyncBlock is never used and no callback runs; its Result/ResultSize partners return the -// same error. Their arguments don't matter, so the functions take none (x64: the caller owns the argument area). -template HRESULT STDMETHODCALLTYPE offline_failure(void*) { - static std::atomic s_logged{false}; - if (!s_logged.exchange(true)) - RT_LOG_WARN("xgameruntime: XUserImpl slot %d is not available offline (HRESULT 0x%08lx)\n", Slot, - static_cast(Error)); - return Error; -} - -// 19: HRESULT XUserGetAgeGroup(XUserHandle user, XUserAgeGroup* ageGroup) -HRESULT STDMETHODCALLTYPE user_get_age_group(void*, XUserHandle user, XUserAgeGroup* group) { - if (!group) return E_POINTER; - if (!valid(user)) return E_INVALIDARG; - *group = XUserAgeGroup::Adult; - return S_OK; -} - -// 20: HRESULT XUserCheckPrivilege(XUserHandle user, XUserPrivilegeOptions options, XUserPrivilege privilege, -// bool* hasPrivilege, XUserPrivilegeDenyReason* reason). Everything is allowed offline -// (multiplayer and the like then fail at the network, as on a console without one). -HRESULT STDMETHODCALLTYPE user_check_privilege(void*, XUserHandle user, uint32_t, uint32_t, bool* has, - XUserPrivilegeDenyReason* reason) { - if (!has) return E_POINTER; - if (!valid(user)) return E_INVALIDARG; - *has = true; - if (reason) *reason = XUserPrivilegeDenyReason::None; - return S_OK; -} - -// 21: HRESULT XUserResolvePrivilegeWithUiAsync(XUserHandle user, XUserPrivilegeOptions options, XUserPrivilege privilege, -// XAsyncBlock* async) -HRESULT STDMETHODCALLTYPE user_resolve_privilege_async(void*, XUserHandle user, uint32_t, uint32_t, XAsyncBlock* async) { - if (!async) return E_POINTER; - if (!valid(user)) return E_INVALIDARG; - return XAsyncBegin(async, nullptr, &kResolveIdentity, "XUserResolvePrivilegeWithUiAsync", resolve_provider); -} - -// 22: HRESULT XUserResolvePrivilegeWithUiResult(XAsyncBlock* async) -HRESULT STDMETHODCALLTYPE user_resolve_privilege_result(void*, XAsyncBlock* async) { - return XAsyncGetResult(async, &kResolveIdentity, 0, nullptr, nullptr); -} - -// 33: HRESULT XUserRegisterForChangeEvent(XTaskQueueHandle queue, void* context, XUserChangeEventCallback* callback, -// XTaskQueueRegistrationToken* token) -// 34: bool XUserUnregisterForChangeEvent(XTaskQueueRegistrationToken token, bool wait) -// The user never changes offline, so the callbacks are kept only as tokens. -std::mutex g_tokens_mutex; -std::set g_tokens; -uint64_t g_next_token = 1; - -HRESULT STDMETHODCALLTYPE user_register_change(void*, XTaskQueueHandle, void*, XUserChangeEventCallback callback, - XTaskQueueRegistrationToken* token) { - if (!callback || !token) return E_POINTER; - std::lock_guard lock(g_tokens_mutex); - token->token = g_next_token++; - g_tokens.insert(token->token); - return S_OK; -} - -// false means "wait was false and the unregistration is still pending"; nothing is ever pending offline, so it is -// true for every token, including one already unregistered or never handed out (a title polling with wait = false -// would otherwise spin). -bool STDMETHODCALLTYPE user_unregister_change(void*, XTaskQueueRegistrationToken token, bool) { - std::lock_guard lock(g_tokens_mutex); - g_tokens.erase(token.token); - return true; -} - -// 35: HRESULT XUserGetSignOutDeferral(XUserSignOutDeferralHandle* deferral): nothing signs out offline, so there is -// no sign-out to defer (the documented E_GAMEUSER_DEFERRAL_NOT_AVAILABLE). -HRESULT STDMETHODCALLTYPE user_get_signout_deferral(void*, XUserSignOutDeferralHandle* deferral) { - if (deferral) *deferral = nullptr; - return E_GAMEUSER_DEFERRAL_NOT_AVAILABLE; -} - -// 36: void XUserCloseSignOutDeferralHandle(XUserSignOutDeferralHandle deferral) -void STDMETHODCALLTYPE user_close_signout_deferral(void*, XUserSignOutDeferralHandle) {} - -// ---- IXUserImpl2 (37-38) ---- - -// 37: HRESULT XUserAddByIdWithUiAsync(uint64_t userId, XAsyncBlock* async) -HRESULT STDMETHODCALLTYPE user_add_by_id_async(void*, uint64_t id, XAsyncBlock* async) { - if (!async) return E_POINTER; - return XAsyncBegin(async, reinterpret_cast(static_cast(id)), &kAddByIdIdentity, - "XUserAddByIdWithUiAsync", add_by_id_provider); -} - -// 38: HRESULT XUserAddByIdWithUiResult(XAsyncBlock* async, XUserHandle* newUser) -HRESULT STDMETHODCALLTYPE user_add_by_id_result(void*, XAsyncBlock* async, XUserHandle* user) { - if (!user) return E_POINTER; - *user = nullptr; - return XAsyncGetResult(async, &kAddByIdIdentity, sizeof(*user), user, nullptr); -} - -// ---- IXUserImpl4 (42) ---- - -// 42: bool XUserIsStoreUser(XUserHandle user): the handle is _In_opt_, and the GDK reference says the function -// always returns true on console. -bool STDMETHODCALLTYPE user_is_store_user(void*, XUserHandle) { return true; } - -// ---- IXUserGamertagImpl (its slot 3) ---- - -// HRESULT XUserGetGamertag(XUserHandle user, XUserGamertagComponent component, size_t gamertagSize, char* gamertag, -// size_t* gamertagUsed). The offline user has a classic gamertag: Modern and UniqueModern are -// the same text (a classic tag has no '#' and no suffix) and ModernSuffix is empty. gamertagUsed counts the -// terminator. -HRESULT STDMETHODCALLTYPE user_get_gamertag(void*, XUserHandle user, XUserGamertagComponent component, size_t size, - char* out, size_t* used) { - if (used) *used = 0; - if (!valid(user)) return E_INVALIDARG; - const char* text = nullptr; - switch (component) { - case XUserGamertagComponent::Classic: - case XUserGamertagComponent::Modern: - case XUserGamertagComponent::UniqueModern: - text = gamertag(); - break; - case XUserGamertagComponent::ModernSuffix: - text = ""; - break; - default: - return E_INVALIDARG; - } - const size_t need = std::strlen(text) + 1; - if (!out || size < need) return kInsufficientBuffer; - std::memcpy(out, text, need); - if (used) *used = need; - return S_OK; -} - -// ---- The object: one vtable for the IXUserImpl..IXUserImpl6 chain, one for IXUserGamertagImpl ---- - -constexpr GUID kUserClass = {0x01acd177, 0x91f9, 0x4763, {0xa3, 0x8e, 0xcc, 0xbb, 0x55, 0xce, 0x32, 0xe0}}; -// IXUserImpl's id is the class id; IXUserImpl2..6 extend it, so each of them answers with the same vtable. -constexpr GUID kUserInterfaces[] = { - kUserClass, - {0xeb9bf948, 0x18dc, 0x4d82, {0xbb, 0xcc, 0x40, 0xe0, 0xa8, 0x09, 0xc4, 0xc0}}, // IXUserImpl2 - {0x1bf2f8c5, 0xd507, 0x4e52, {0xbb, 0x05, 0xf7, 0x26, 0xd0, 0xe7, 0x11, 0x61}}, // IXUserImpl3 - {0x079415e3, 0x6727, 0x437f, {0x8e, 0x9d, 0x8f, 0x8f, 0x9b, 0x24, 0x39, 0xf7}}, // IXUserImpl4 - {0x26f3c674, 0xa2fe, 0x44fa, {0xb6, 0xc4, 0xa3, 0x23, 0xbc, 0x94, 0xff, 0x53}}, // IXUserImpl5 - {0x5131d685, 0x4394, 0x4ee6, {0x8c, 0x18, 0xbf, 0xb5, 0xd4, 0xae, 0xf1, 0xff}}, // IXUserImpl6 -}; -constexpr GUID kGamertagInterface = {0xcef4fac0, 0x7676, 0x4a94, {0xa1, 0x19, 0x4c, 0x43, 0xf9, 0xeb, 0x5b, 0x74}}; -constexpr GUID kIUnknown = {0x00000000, 0x0000, 0x0000, {0xc0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x46}}; - -struct UserObject { - const void* const* vtable; // IXUserImpl6 - const void* const* gamertag_vtable; // IXUserGamertagImpl -}; -UserObject* user_object(); - -HRESULT query(REFIID iid, void** out) { - if (!out) return E_POINTER; - *out = nullptr; - UserObject* o = user_object(); - if (iid == kIUnknown) { - *out = &o->vtable; - return S_OK; - } - for (const GUID& id : kUserInterfaces) - if (iid == id) { - *out = &o->vtable; - return S_OK; - } - if (iid == kGamertagInterface) { - *out = &o->gamertag_vtable; - return S_OK; - } - return E_NOINTERFACE; -} - -// A process-wide singleton, as the other runtime classes: AddRef and Release don't free. -HRESULT STDMETHODCALLTYPE object_query_interface(void*, REFIID iid, void** out) { return query(iid, out); } -ULONG STDMETHODCALLTYPE object_add_ref(void*) { return 2; } -ULONG STDMETHODCALLTYPE object_release(void*) { return 1; } - -#define FN(f) reinterpret_cast(&f) - -const void* const kUserVtable[] = { - FN(object_query_interface), FN(object_add_ref), FN(object_release), // 0-2 IUnknown - FN(user_duplicate), // 3 XUserDuplicateHandle - FN(user_close), // 4 XUserCloseHandle - FN(user_compare), // 5 XUserCompare - FN(user_get_max_users), // 6 XUserGetMaxUsers - FN(user_add_async), // 7 XUserAddAsync - FN(user_add_result), // 8 XUserAddResult - FN(user_get_local_id), // 9 XUserGetLocalId - FN(user_find_by_local_id), // 10 XUserFindUserByLocalId - FN(user_get_id), // 11 XUserGetId - FN(user_find_by_id), // 12 XUserFindUserById - FN(user_get_is_guest), // 13 XUserGetIsGuest - FN(user_get_state), // 14 XUserGetState - FN(unknown_slot<15>), // 15 (unknown in the docs) - FN((offline_failure<16, E_FAIL>)), // 16 XUserGetGamerPictureAsync - FN((offline_failure<17, E_FAIL>)), // 17 XUserGetGamerPictureResultSize - FN((offline_failure<18, E_FAIL>)), // 18 XUserGetGamerPictureResult - FN(user_get_age_group), // 19 XUserGetAgeGroup - FN(user_check_privilege), // 20 XUserCheckPrivilege - FN(user_resolve_privilege_async), // 21 XUserResolvePrivilegeWithUiAsync - FN(user_resolve_privilege_result), // 22 XUserResolvePrivilegeWithUiResult - FN((offline_failure<23, E_GAMEUSER_FAILED_TO_GET_TOKEN>)), // 23 XUserGetTokenAndSignatureAsync - FN((offline_failure<24, E_GAMEUSER_FAILED_TO_GET_TOKEN>)), // 24 ...ResultSize - FN((offline_failure<25, E_GAMEUSER_FAILED_TO_GET_TOKEN>)), // 25 ...Result - FN((offline_failure<26, E_GAMEUSER_FAILED_TO_GET_TOKEN>)), // 26 XUserGetTokenAndSignatureUtf16Async - FN((offline_failure<27, E_GAMEUSER_FAILED_TO_GET_TOKEN>)), // 27 ...Utf16ResultSize - FN((offline_failure<28, E_GAMEUSER_FAILED_TO_GET_TOKEN>)), // 28 ...Utf16Result - FN((offline_failure<29, E_GAMEUSER_FAILED_TO_RESOLVE>)), // 29 XUserResolveIssueWithUiAsync - FN((offline_failure<30, E_GAMEUSER_FAILED_TO_RESOLVE>)), // 30 XUserResolveIssueWithUiResult - FN((offline_failure<31, E_GAMEUSER_FAILED_TO_RESOLVE>)), // 31 XUserResolveIssueWithUiUtf16Async - FN((offline_failure<32, E_GAMEUSER_FAILED_TO_RESOLVE>)), // 32 XUserResolveIssueWithUiUtf16Result - FN(user_register_change), // 33 XUserRegisterForChangeEvent - FN(user_unregister_change), // 34 XUserUnregisterForChangeEvent - FN(user_get_signout_deferral), // 35 XUserGetSignOutDeferral - FN(user_close_signout_deferral), // 36 XUserCloseSignOutDeferralHandle - FN(user_add_by_id_async), // 37 XUserAddByIdWithUiAsync (2) - FN(user_add_by_id_result), // 38 XUserAddByIdWithUiResult (2) - FN((offline_failure<39, E_GAMEUSER_FAILED_TO_GET_TOKEN>)), // 39 XUserGetMsaTokenSilentlyAsync (3) - FN((offline_failure<40, E_GAMEUSER_FAILED_TO_GET_TOKEN>)), // 40 ...Result (3) - FN((offline_failure<41, E_GAMEUSER_FAILED_TO_GET_TOKEN>)), // 41 ...ResultSize (3) - FN(user_is_store_user), // 42 XUserIsStoreUser (4) - FN((offline_failure<43, E_NOTIMPL>)), // 43 XUserPlatformRemoteConnectSetEventHandlers (5, PC) - FN((offline_failure<44, E_NOTIMPL>)), // 44 XUserPlatformRemoteConnectCancelPrompt (5, PC) - FN((offline_failure<45, E_NOTIMPL>)), // 45 XUserPlatformSpopPromptSetEventHandlers (5, PC) - FN((offline_failure<46, E_NOTIMPL>)), // 46 XUserPlatformSpopPromptComplete (5, PC) - FN(private_slot<47>), // 47 XUserIsSignOutPresent (6): false - FN((offline_failure<48, E_NOTIMPL>)), // 48 XUserSignOutAsync (6) - FN((offline_failure<49, E_NOTIMPL>)), // 49 XUserSignOutResult (6) -}; -static_assert(std::size(kUserVtable) == 50, "IUnknown + IXUserImpl's 34 methods + 2 + 3 + 1 + 4 + 3"); - -// The gamertag face's IUnknown slots get `this` = &gamertag_vtable; the object is a singleton, so they ignore it. -const void* const kGamertagVtable[] = { - FN(object_query_interface), FN(object_add_ref), FN(object_release), - FN(user_get_gamertag), // 3 XUserGetGamertag -}; - -#undef FN - -UserObject* user_object() { - static UserObject o{kUserVtable, kGamertagVtable}; - return &o; -} - -} // namespace - -namespace rt::shims { - -// Called by xgameruntime.cpp's QueryApiImpl for every class: true when the class is XUserImpl, with *hr set. -bool xgameruntime_user_query(const GUID& class_id, REFIID interface_id, void** out, HRESULT* hr) { - if (class_id != kUserClass) return false; - *hr = query(interface_id, out); - return true; -} - -// A new handle to the offline user, for the classes that hand one out too (XUserFindForDevice, in -// xgameruntime_offline.cpp). The title closes it with XUserCloseHandle like any other. -void* xgameruntime_user_new_handle() { return new_handle(); } - -// For tests: the XUserHandles a title holds open. -long xgameruntime_user_open_handles() { - std::lock_guard lock(g_handles_mutex); - return static_cast(g_handles.size()); -} - -} // namespace rt::shims diff --git a/runtime/shims/xmem.cpp b/runtime/shims/xmem.cpp deleted file mode 100644 index 84a91c70c..000000000 --- a/runtime/shims/xmem.cpp +++ /dev/null @@ -1,883 +0,0 @@ -// xmem.dll: the GDK's tracked allocator. Mapped onto the CRT's aligned heap and VirtualQueryEx. -// -// The measured ABI (docs from the clean-room spec) shows four imports: -// XMemAlloc(size, attributes) -// XMemFree(ptr, attributes) -// XMemVirtualQuery(process, address, out64) -// XMemGetWorkingSetStatistics(kind, out) (kind 0x20000001 at all seven FSR call sites) -// -// ASSUMPTION: the attribute word is not decoded by the measured call sites (one passes 0x5e50000). Until a call -// site shows the alignment/type fields, every block is 64-byte aligned (covers cache lines and SIMD) and a size of -// zero is rounded up to one byte so the result is a stable, non-null pointer that XMemFree can release. -// -// The default allocators, the physical-page functions and XMemIsToolsMemAvailable follow argument shapes measured -// locally at a title's call sites (each function says which). The page functions are built on the Windows placeholder -// APIs (VirtualAlloc2, MapViewOfFile3), whose flags the title's own XMemVirtualAlloc calls already use. -#include -#include -#include -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include "../core/log.h" -#include "shims.h" -#include "startup_trace.h" -#include "xmem.h" - -namespace { - -constexpr size_t kAlign = 64; -constexpr size_t kNoSize = static_cast(-1); // XMemFree has no size field - -std::string caller_field(const void* caller) { - return ",\"caller\":" + rt::startup_trace::quote(rt::startup_trace::where(reinterpret_cast(caller))); -} - -// gta6rt --trace FILE: the first XMemAlloc, XMemFree, XMemAllocDefault, XMemFreeDefault and XMemVirtualAlloc call for -// each distinct raw attribute word go to the startup trace as an "xmem_attributes" event (api, the word, the size for an -// allocation, the caller as module+RVA). The bits of the attribute word are not known yet; this records them from a -// real run without logging every allocation, which would fill the file. Off: one relaxed load per call. -void note_attributes(const char* api, uint64_t attributes, size_t size, const void* caller) { - if (!rt::startup_trace::enabled()) return; - static std::mutex mutex; - static std::set> seen; - { - const std::lock_guard lock(mutex); - if (!seen.insert({api, attributes}).second) return; - } - std::string fields = std::string("\"api\":\"") + api + - "\",\"attributes\":" + rt::startup_trace::quote(rt::startup_trace::hex(attributes)); - if (size != kNoSize) fields += ",\"size\":" + std::to_string(size); - fields += caller_field(caller); - rt::startup_trace::event("xmem_attributes", fields); -} - -void* allocate_block(size_t size) { return _aligned_malloc(size ? size : 1, kAlign); } - -void* __stdcall XMemAlloc(size_t size, uint64_t attributes) { - note_attributes("XMemAlloc", attributes, size, _ReturnAddress()); - return allocate_block(size); -} - -void __stdcall XMemFree(void* p, uint64_t attributes) { - note_attributes("XMemFree", attributes, kNoSize, _ReturnAddress()); - _aligned_free(p); -} - -// XMemAllocDefault / XMemFreeDefault: the GDK's own allocator behind XMemAlloc and XMemFree, which a title that hooks -// XMemAlloc forwards to. The measured title reaches each through one wrapper that is a bare tail jump to the import, -// so they take exactly XMemAlloc's and XMemFree's arguments. They share the heap: a block from either allocator may be -// released by either free. -void* __stdcall XMemAllocDefault(size_t size, uint64_t attributes) { - note_attributes("XMemAllocDefault", attributes, size, _ReturnAddress()); - return allocate_block(size); -} - -void __stdcall XMemFreeDefault(void* p, uint64_t attributes) { - note_attributes("XMemFreeDefault", attributes, kNoSize, _ReturnAddress()); - _aligned_free(p); -} - -// BOOL XMemIsToolsMemAvailable(void). The measured title calls it from one helper, which six out-of-memory paths reach -// only after an allocation has failed; the helper breaks into the debugger when the result is zero. Tools memory is -// the extra memory of a development kit. A PC has none, so the answer is FALSE, and the title's own breakpoint marks -// where it ran out of memory. -BOOL WINAPI XMemIsToolsMemAvailable() { - static std::atomic warned{false}; - if (!warned.exchange(true, std::memory_order_relaxed)) { - RT_LOG_WARN("xmem: XMemIsToolsMemAvailable -> FALSE (no devkit tools memory; logged once)\n"); - } - return FALSE; -} - -// Measured call sites pass a zeroed 64-byte structure. Only the MEMORY_BASIC_INFORMATION-compatible prefix is -// known: callers read at least the base and size fields. Fill that prefix from VirtualQueryEx and zero the rest. -constexpr size_t kVirtualQueryOutSize = 64; -static_assert(sizeof(MEMORY_BASIC_INFORMATION) <= kVirtualQueryOutSize, - "the 64-byte XMemVirtualQuery output must hold MEMORY_BASIC_INFORMATION"); - -// Returns the number of bytes written (the VirtualQuery convention) or 0 on failure. The exact return type and the -// meaning of every output field are not fully known; callers in the package only test for success. -SIZE_T __stdcall XMemVirtualQuery(HANDLE process, const void* address, void* out) { - if (!out) return 0; - std::memset(out, 0, kVirtualQueryOutSize); - if (!address) return 0; - - static std::atomic warned{false}; - if (!warned.exchange(true, std::memory_order_relaxed)) { - RT_LOG_WARN("xmem: XMemVirtualQuery: fields after MEMORY_BASIC_INFORMATION are unknown; " - "the 64-byte output is zero-filled there\n"); - } - - // A null handle means the current process; GetCurrentProcess() is the (HANDLE)-1 pseudo handle. - HANDLE target = process ? process : GetCurrentProcess(); - MEMORY_BASIC_INFORMATION info{}; - SIZE_T written = VirtualQueryEx(target, address, &info, sizeof(info)); - if (!written) return 0; - - std::memcpy(out, &info, written < kVirtualQueryOutSize ? written : kVirtualQueryOutSize); - return written; -} - -// BOOL XMemGetWorkingSetStatistics(UINT32 kind, XMEM_WORKING_SET_STATISTICS* stats). Measured at all seven call sites -// in amd_fidelityfx_upscaler_xbox.dll (1.0.2.1; calls at RVAs 0x26b3, 0x2ea1, 0x39a9, 0x7452, 0x74d2, 0x7568, -// 0x75b1): ECX is the constant 0x20000001 (its meaning is not known) and RDX points at a stack buffer (0x80 bytes -// where the frame shows it). The caller reads a 64-bit size at +8 and treats a zero return as "no data". Taking the -// pointer from the first argument wrote to address 0x20000001. -// The measured FSR sites establish argument shape, kind and the 64-bit working-set read at +8; +0's title-total memory -// limit interpretation is inferred from other Series implementations (xcl, xbox-emulator) and title engine telemetry -// sizing memory pools (RT-220). Note that if GlobalMemoryStatusEx reports 0 physical memory, XMem falls back to the -// 12 GiB title limit, whereas XSystemGetAppMemoryUsageLimit remains 0. -BOOL __stdcall XMemGetWorkingSetStatistics(uint32_t /*kind*/, void* stats) { - if (!stats) { - static std::atomic warned{false}; - if (!warned.exchange(true, std::memory_order_relaxed)) { - RT_LOG_WARN("xmem: XMemGetWorkingSetStatistics(nullptr) -> FALSE\n"); - } - return FALSE; - } - - PROCESS_MEMORY_COUNTERS pmc{}; - if (!GetProcessMemoryInfo(GetCurrentProcess(), &pmc, sizeof(pmc))) return FALSE; - - MEMORYSTATUSEX ms{sizeof(ms)}; - uint64_t total_memory = 12ULL * 1024 * 1024 * 1024; - if (GlobalMemoryStatusEx(&ms) && ms.ullTotalPhys != 0) { - total_memory = ms.ullTotalPhys; - } - - uint8_t* bytes = static_cast(stats); - std::memset(bytes, 0, 16); - std::memcpy(bytes + 0, &total_memory, sizeof(total_memory)); - uint64_t working_set = pmc.WorkingSetSize; - std::memcpy(bytes + 8, &working_set, sizeof(working_set)); - return TRUE; -} - -// The placeholder APIs (Windows 10 1803 and later) come from kernelbase.dll at run time, so neither gta6rt nor the -// tests link onecore.lib. A host without them fails the calls that need them with ERROR_NOT_SUPPORTED. -using VirtualAlloc2Fn = PVOID(WINAPI*)(HANDLE, PVOID, SIZE_T, ULONG, ULONG, MEM_EXTENDED_PARAMETER*, ULONG); -using MapViewOfFile3Fn = PVOID(WINAPI*)(HANDLE, HANDLE, PVOID, ULONG64, SIZE_T, ULONG, ULONG, MEM_EXTENDED_PARAMETER*, - ULONG); -using UnmapViewOfFile2Fn = BOOL(WINAPI*)(HANDLE, PVOID, ULONG); - -struct PlaceholderApi { - VirtualAlloc2Fn virtual_alloc2 = nullptr; - MapViewOfFile3Fn map_view3 = nullptr; - UnmapViewOfFile2Fn unmap_view2 = nullptr; - bool available() const { return virtual_alloc2 && map_view3 && unmap_view2; } -}; - -const PlaceholderApi& placeholder_api() { - static const PlaceholderApi api = [] { - PlaceholderApi resolved; - if (const HMODULE kernelbase = GetModuleHandleW(L"kernelbase.dll")) { - resolved.virtual_alloc2 = reinterpret_cast(GetProcAddress(kernelbase, "VirtualAlloc2")); - resolved.map_view3 = reinterpret_cast(GetProcAddress(kernelbase, "MapViewOfFile3")); - resolved.unmap_view2 = - reinterpret_cast(GetProcAddress(kernelbase, "UnmapViewOfFile2")); - } - return resolved; - }(); - return api; -} - -// XMem allocation-type page bits select the guest page granularity and must not be forwarded as Win32 flags. -constexpr DWORD kXmemLargePages = 0x20000000; // 2 MiB pages -constexpr DWORD kXmem64kPages = 0x20400000; // 64 KiB pages -constexpr DWORD kXmemPageModeMask = kXmem64kPages; -constexpr SIZE_T kXmemPageSize64k = 0x10000; -constexpr SIZE_T kXmemPageSize2m = 0x200000; -constexpr DWORD kXmemHostAllocationTypeMask = MEM_COMMIT | MEM_RESERVE | MEM_REPLACE_PLACEHOLDER | - MEM_RESERVE_PLACEHOLDER | MEM_RESET | MEM_TOP_DOWN | MEM_WRITE_WATCH | - MEM_RESET_UNDO; - -bool round_up_size(SIZE_T value, SIZE_T alignment, SIZE_T& rounded) { - const SIZE_T max = (std::numeric_limits::max)(); - if (alignment == 0 || (alignment & (alignment - 1)) != 0 || value > max - (alignment - 1)) return false; - rounded = (value + alignment - 1) & ~(alignment - 1); - return true; -} - -// The console's PAGE_GRAPHICS_* protection bits (winnt.h: PAGE_GRAPHICS_NOACCESS 0x800 .. PAGE_GRAPHICS_NOCACHE -// 0x40000). The host refuses them with ERROR_INVALID_PARAMETER, and the D3D12 layer reads guest memory through the -// CPU mapping, so only the CPU protection is applied. The retail executable passes 0x801 and 0x22004. -constexpr DWORD kPageGraphicsMask = 0x0007F800; - -DWORD host_protect(DWORD p) { - const DWORD cpu = p & ~kPageGraphicsMask; - return cpu ? cpu : PAGE_NOACCESS; -} - -// Physical pages and the windows they are mapped into. One mutex covers both tables and every map and unmap. -// -// A physical-page window is a reserve-only XMemVirtualAlloc in a guest page mode, or a reserve-only replacement of -// part of a placeholder. On the host it is a placeholder, the only kind of reservation a section view can later -// replace, and its protection is kept here: the map calls take none, so a mapped page gets its window's protection, as -// AWE's MapUserPhysicalPages does. -// -// ASSUMPTION: a title does not commit memory inside such a window with kernel32!VirtualAlloc. A placeholder refuses a -// plain commit; the measured windows are only ever passed to the map calls. -struct Window { - SIZE_T size; - DWORD protect; -}; - -struct Section { - HANDLE handle; - void* scratch; - explicit Section(HANDLE h) : handle(h), scratch(MapViewOfFile(h, FILE_MAP_WRITE, 0, 0, 0)) {} - Section(const Section&) = delete; - Section& operator=(const Section&) = delete; - ~Section() { - if (scratch) UnmapViewOfFile(scratch); - CloseHandle(handle); - } -}; - -struct PhysicalPage { - std::shared_ptr
section; // a mapped view holds its own reference to the section - uint64_t offset; -}; - -constexpr uint64_t kPhysicalPageSize = 0x10000; -// Page numbers are 4 KiB frame numbers of 64 KiB pages: the measured title stores them packed and assumes each is a -// non-zero multiple of 16 below 2^25, with 0 for an entry it unmaps. So a page number is slot * 16 with slot in -// [1, 2^21), and freed slots are reused so a long run never runs out. -constexpr uint64_t kFramesPerPage = kPhysicalPageSize / 0x1000; -constexpr uint64_t kPageSlotLimit = uint64_t{1} << 21; - -std::mutex g_phys_mutex; -std::map g_windows; // base -> window -std::unordered_map g_pages; // page number -> backing -std::vector g_free_slots; -uint64_t g_next_slot = 1; -struct MappedPage { - uint64_t page; - std::shared_ptr
section; - uint64_t offset; -}; - -std::unordered_map g_mapped; -SRWLOCK g_fault_lock = SRWLOCK_INIT; - -struct FaultLockExclusive { - FaultLockExclusive() { AcquireSRWLockExclusive(&g_fault_lock); } - ~FaultLockExclusive() { ReleaseSRWLockExclusive(&g_fault_lock); } - FaultLockExclusive(const FaultLockExclusive&) = delete; - FaultLockExclusive& operator=(const FaultLockExclusive&) = delete; -}; - -struct FaultLockShared { - FaultLockShared() { AcquireSRWLockShared(&g_fault_lock); } - ~FaultLockShared() { ReleaseSRWLockShared(&g_fault_lock); } - FaultLockShared(const FaultLockShared&) = delete; - FaultLockShared& operator=(const FaultLockShared&) = delete; -}; - -// With g_phys_mutex held. A window replaces every window it overlaps: the title released those regions (with -// kernel32!VirtualFree, which the shim does not see) before the host could hand the addresses out again. -void record_window(void* base, SIZE_T size, DWORD protect) { - const uintptr_t start = reinterpret_cast(base); - const uintptr_t end = start + size; - auto it = g_windows.lower_bound(start); - if (it != g_windows.begin()) { - const auto prev = std::prev(it); - if (prev->first + prev->second.size > start) it = prev; - } - while (it != g_windows.end() && it->first < end) it = g_windows.erase(it); - g_windows[start] = Window{size, protect}; -} - -// With g_phys_mutex held: the window holding [address, address + bytes), if one does. -const Window* find_window(uintptr_t address, uint64_t bytes) { - auto it = g_windows.upper_bound(address); - if (it == g_windows.begin()) return nullptr; - --it; - const uint64_t offset = address - it->first; - if (offset >= it->second.size || bytes > it->second.size - offset) return nullptr; - return &it->second; -} - -// [address, address + size) as one placeholder of its own: split it out of the placeholder that holds it. Fails when -// the range is not inside one placeholder. -bool isolate_placeholder(void* address, SIZE_T size) { - MEMORY_BASIC_INFORMATION info{}; - if (!VirtualQuery(address, &info, sizeof(info)) || info.State != MEM_RESERVE) { - SetLastError(ERROR_INVALID_ADDRESS); - return false; - } - if (info.AllocationBase == address && info.RegionSize == size) return true; - return VirtualFree(address, size, MEM_RELEASE | MEM_PRESERVE_PLACEHOLDER) != FALSE; -} - -PVOID reserve_placeholder(void* address, SIZE_T size, SIZE_T alignment) { - MEM_ADDRESS_REQUIREMENTS requirements{}; - MEM_EXTENDED_PARAMETER parameter{}; - ULONG parameter_count = 0; - if (!address && alignment > kXmemPageSize64k) { - requirements.Alignment = alignment; - parameter.Type = MemExtendedParameterAddressRequirements; - parameter.Pointer = &requirements; - parameter_count = 1; - } - return placeholder_api().virtual_alloc2(GetCurrentProcess(), address, size, MEM_RESERVE | MEM_RESERVE_PLACEHOLDER, - PAGE_NOACCESS, parameter_count ? ¶meter : nullptr, parameter_count); -} - -// PVOID XMemVirtualAlloc(address, size, allocationType, attributes, protect). All 23 calls of the measured title pass a -// nonzero attribute word; its bits are not decoded and nothing on the host depends on them, so it is accepted and only -// recorded (xmem_attributes). Its types cover committed 2 MiB and 64 KiB pages, reserve-only 64 KiB windows for physical pages, one -// MEM_RESERVE_PLACEHOLDER reservation and five MEM_REPLACE_PLACEHOLDER windows carved out of it, each then filled with -// XMemMapPhysicalPages. The guest page size sets the alignment and rounding of the region; the host's own pages stay -// 4 KiB (host large pages need SeLockMemoryPrivilege). A 2 MiB region the host places is reserved 2 MiB-aligned through -// VirtualAlloc2. -void* WINAPI XMemVirtualAlloc(void* address, SIZE_T size, DWORD allocation_type, ULONGLONG attributes, DWORD protect) { - note_attributes("XMemVirtualAlloc", attributes, size, _ReturnAddress()); - if (size == 0) { - SetLastError(ERROR_INVALID_PARAMETER); - return nullptr; - } - - const DWORD page_mode = allocation_type & kXmemPageModeMask; - if (page_mode != 0 && page_mode != kXmem64kPages && page_mode != kXmemLargePages) { - SetLastError(ERROR_INVALID_PARAMETER); - return nullptr; - } - - const DWORD unsupported = allocation_type & ~(kXmemHostAllocationTypeMask | kXmemPageModeMask); - if (unsupported != 0) { - SetLastError(ERROR_INVALID_PARAMETER); - return nullptr; - } - - DWORD host_type = allocation_type & kXmemHostAllocationTypeMask; - if (host_type == 0) host_type = MEM_RESERVE | MEM_COMMIT; - const DWORD host_prot = host_protect(protect); - - const bool commit = (host_type & MEM_COMMIT) != 0; - const bool new_placeholder = (host_type & MEM_RESERVE_PLACEHOLDER) != 0; - const bool replace = (host_type & MEM_REPLACE_PLACEHOLDER) != 0; - const bool window = page_mode != 0 && !commit && !new_placeholder; - if ((new_placeholder || replace || window || page_mode == kXmemLargePages) && !placeholder_api().available()) { - SetLastError(ERROR_NOT_SUPPORTED); - return nullptr; - } - - SYSTEM_INFO system_info{}; - GetSystemInfo(&system_info); - SIZE_T page_granularity = system_info.dwPageSize; - SIZE_T base_granularity = (host_type & MEM_RESERVE) ? system_info.dwAllocationGranularity : system_info.dwPageSize; - if (page_mode == kXmem64kPages) page_granularity = base_granularity = kXmemPageSize64k; - if (page_mode == kXmemLargePages) page_granularity = base_granularity = kXmemPageSize2m; - if (new_placeholder || replace) { - // Placeholders are split and replaced on allocation-granularity boundaries only. - if (page_granularity < system_info.dwAllocationGranularity) page_granularity = system_info.dwAllocationGranularity; - if (base_granularity < system_info.dwAllocationGranularity) base_granularity = system_info.dwAllocationGranularity; - } - if (page_granularity == 0 || (page_granularity & (page_granularity - 1)) != 0 || base_granularity == 0 || - (base_granularity & (base_granularity - 1)) != 0) { - SetLastError(ERROR_INVALID_PARAMETER); - return nullptr; - } - - if (address != nullptr) { - const uintptr_t requested = reinterpret_cast(address); - const uintptr_t max = (std::numeric_limits::max)(); - if (size > max - requested) { - SetLastError(ERROR_INVALID_PARAMETER); - return nullptr; - } - const uintptr_t requested_end = requested + size; - const uintptr_t base = requested & ~(static_cast(base_granularity) - 1); - if (requested_end > max - (static_cast(page_granularity) - 1)) { - SetLastError(ERROR_INVALID_PARAMETER); - return nullptr; - } - const uintptr_t end = (requested_end + static_cast(page_granularity) - 1) & - ~(static_cast(page_granularity) - 1); - address = reinterpret_cast(base); - size = static_cast(end - base); - } else if (replace) { - SetLastError(ERROR_INVALID_PARAMETER); // a replacement names the placeholder it replaces - return nullptr; - } else if (page_granularity > system_info.dwPageSize && !round_up_size(size, page_granularity, size)) { - SetLastError(ERROR_INVALID_PARAMETER); - return nullptr; - } - - if (replace) { - const std::lock_guard lock(g_phys_mutex); - if (!isolate_placeholder(address, size)) return nullptr; - if (window) { - // A reserve-only replacement stays a placeholder: the physical pages are mapped into it. - record_window(address, size, host_prot); - return address; - } - return placeholder_api().virtual_alloc2(GetCurrentProcess(), address, size, host_type | MEM_RESERVE, host_prot, - nullptr, 0); - } - if (new_placeholder || window) { - void* const result = reserve_placeholder(address, size, base_granularity); - if (result && window) { - const std::lock_guard lock(g_phys_mutex); - record_window(result, size, host_prot); - } - return result; - } - if (page_mode == kXmemLargePages && address == nullptr) { - MEM_ADDRESS_REQUIREMENTS requirements{}; - requirements.Alignment = kXmemPageSize2m; - MEM_EXTENDED_PARAMETER parameter{}; - parameter.Type = MemExtendedParameterAddressRequirements; - parameter.Pointer = &requirements; - return placeholder_api().virtual_alloc2(GetCurrentProcess(), nullptr, size, host_type | MEM_RESERVE, host_prot, - ¶meter, 1); - } - return VirtualAlloc(address, size, host_type, host_prot); -} - -// With g_phys_mutex held. Unmaps the page at `address` if one is mapped there; the address becomes a placeholder again. -bool unmap_page(uintptr_t address) { - const FaultLockExclusive lock; - const auto it = g_mapped.find(address); - if (it == g_mapped.end()) return true; - if (!placeholder_api().unmap_view2(GetCurrentProcess(), reinterpret_cast(address), - MEM_PRESERVE_PLACEHOLDER)) { - return false; - } - g_mapped.erase(it); - return true; -} - -// With g_phys_mutex held. Maps physical page `page` (0: unmap) at the 64 KiB-aligned `address`, replacing what was -// mapped there. The caller has found the window. -bool map_page(uintptr_t address, uint64_t page, DWORD protect) { - if (!unmap_page(address)) return false; - if (page == 0) return true; - const auto it = g_pages.find(page); - if (it == g_pages.end()) { - SetLastError(ERROR_INVALID_PARAMETER); - return false; - } - void* const target = reinterpret_cast(address); - if (!isolate_placeholder(target, kPhysicalPageSize)) return false; - const FaultLockExclusive lock; - void* const view = placeholder_api().map_view3(it->second.section->handle, GetCurrentProcess(), target, - it->second.offset, kPhysicalPageSize, MEM_REPLACE_PLACEHOLDER, - protect, nullptr, 0); - if (!view) return false; - g_mapped[address] = MappedPage{page, it->second.section, it->second.offset}; - return true; -} - -enum class PageCommit { not_ours, committed_before, committed_now, failed }; - -PageCommit commit_mapped_page(uintptr_t address, uintptr_t accessed, DWORD& protect) { - const auto it = g_mapped.find(address); - if (it == g_mapped.end() || !it->second.section->scratch) return PageCommit::not_ours; - MEMORY_BASIC_INFORMATION info{}; - if (!VirtualQuery(reinterpret_cast(accessed), &info, sizeof(info)) || info.Type != MEM_MAPPED) { - return PageCommit::not_ours; - } - if (info.State == MEM_COMMIT) { - protect = info.Protect; - return PageCommit::committed_before; - } - void* const backing = static_cast(it->second.section->scratch) + it->second.offset; - return VirtualAlloc(backing, kPhysicalPageSize, MEM_COMMIT, PAGE_READWRITE) ? PageCommit::committed_now - : PageCommit::failed; -} - -bool access_allowed(DWORD protect, ULONG_PTR access) { - if (protect & PAGE_GUARD) return false; - switch (protect & 0xff) { - case PAGE_EXECUTE_READWRITE: - case PAGE_EXECUTE_WRITECOPY: - return true; - case PAGE_READWRITE: - case PAGE_WRITECOPY: - return access != 8; - case PAGE_EXECUTE_READ: - return access != 1; - case PAGE_READONLY: - return access == 0; - case PAGE_EXECUTE: - return access == 8; - default: - return false; - } -} - -LONG CALLBACK physical_page_fault(EXCEPTION_POINTERS* info) { - thread_local bool busy = false; - const EXCEPTION_RECORD* record = info ? info->ExceptionRecord : nullptr; - if (busy || !record || record->ExceptionCode != EXCEPTION_ACCESS_VIOLATION || record->NumberParameters < 2) { - return EXCEPTION_CONTINUE_SEARCH; - } - busy = true; - const uintptr_t accessed = static_cast(record->ExceptionInformation[1]); - const uintptr_t address = accessed & ~static_cast(kPhysicalPageSize - 1); - DWORD protect = 0; - PageCommit result; - { - const FaultLockShared lock; - result = commit_mapped_page(address, accessed, protect); - } - busy = false; - if (result == PageCommit::committed_now) return EXCEPTION_CONTINUE_EXECUTION; - if (result == PageCommit::committed_before && access_allowed(protect, record->ExceptionInformation[0])) { - return EXCEPTION_CONTINUE_EXECUTION; - } - return EXCEPTION_CONTINUE_SEARCH; -} - -bool install_physical_page_fault_handler() { - static const bool installed = AddVectoredExceptionHandler(1, &physical_page_fault) != nullptr; - return installed; -} - -// Two of the measured windows are reserved PAGE_NOACCESS for the CPU and the GPU alike; pages mapped there are still -// GPU memory, which the D3D12 layer reads on the CPU. -DWORD view_protect(const Window& window) { - return window.protect == PAGE_NOACCESS ? PAGE_READWRITE : window.protect; -} - -bool aligned_page_address(uintptr_t address) { return (address & (kPhysicalPageSize - 1)) == 0; } - -// gta6rt --trace FILE: the first XMemAllocatePhysicalPages for each distinct attribute word goes to the startup trace -// as an "xmem_physical_pages" event with the page count and the caller. -void note_physical_attributes(uint64_t attributes, uint64_t count, const void* caller) { - if (!rt::startup_trace::enabled()) return; - static std::mutex mutex; - static std::set seen; - { - const std::lock_guard lock(mutex); - if (!seen.insert(attributes).second) return; - } - rt::startup_trace::event("xmem_physical_pages", - "\"api\":\"XMemAllocatePhysicalPages\",\"attributes\":" + - rt::startup_trace::quote(rt::startup_trace::hex(attributes)) + - ",\"pages\":" + std::to_string(count) + caller_field(caller)); -} - -// BOOL XMemAllocatePhysicalPages(attributes, UINT64* pageCount, UINT64* pageArray). Measured at four call sites: RCX is -// a constant attribute word, RDX points at the number of 64 KiB pages (every caller computes it as the byte size -// rounded up and shifted right by 16), R8 at an array that receives one page number per page. The result is tested as -// a 32-bit BOOL. After success every caller compares the count with the one it asked for and frees the pages if they -// differ, so the count is in/out. -// -// Each call is backed by one pagefile-backed section of count * 64 KiB: committed (charged) on touch, given physical -// memory as it is touched, zero-filled. Pages keep their contents while unmapped or mapped elsewhere, and one page can -// be mapped at several addresses. ASSUMPTION: the attribute word (memory type, perhaps the page size) is not decoded; -// every page is 64 KiB, which all four callers' arithmetic agrees with. -BOOL WINAPI XMemAllocatePhysicalPages(uint64_t attributes, uint64_t* page_count, uint64_t* page_array) { - note_physical_attributes(attributes, page_count ? *page_count : 0, _ReturnAddress()); - if (!page_count || (*page_count && !page_array)) { - SetLastError(ERROR_INVALID_PARAMETER); - return FALSE; - } - const uint64_t count = *page_count; - if (count == 0) return TRUE; - - const std::lock_guard lock(g_phys_mutex); - if (count > g_free_slots.size() + (kPageSlotLimit - g_next_slot)) { - *page_count = 0; - SetLastError(ERROR_NOT_ENOUGH_MEMORY); - return FALSE; - } - if (!install_physical_page_fault_handler()) { - *page_count = 0; - SetLastError(ERROR_NOT_SUPPORTED); - return FALSE; - } - const uint64_t bytes = count * kPhysicalPageSize; // below 2^37: count is below 2^21 - const HANDLE handle = CreateFileMappingW(INVALID_HANDLE_VALUE, nullptr, PAGE_READWRITE | SEC_RESERVE, - static_cast(bytes >> 32), static_cast(bytes), nullptr); - if (!handle) { - *page_count = 0; - return FALSE; - } - const auto section = std::make_shared
(handle); - if (!section->scratch) { - *page_count = 0; - return FALSE; - } - for (uint64_t i = 0; i < count; ++i) { - uint64_t slot; - if (!g_free_slots.empty()) { - slot = g_free_slots.back(); - g_free_slots.pop_back(); - } else { - slot = g_next_slot++; - } - const uint64_t page = slot * kFramesPerPage; - g_pages[page] = PhysicalPage{section, i * kPhysicalPageSize}; - page_array[i] = page; - } - return TRUE; -} - -// BOOL XMemFreePhysicalPages(UINT64 pageCount, UINT64* pageArray). Measured at three call sites: RCX is the count (the -// one XMemAllocatePhysicalPages returned, or the sum of several allocations), RDX the array. The callers unmap the -// pages first; a page that is still mapped keeps its memory until it is unmapped. FALSE, with the entries before it -// freed, for a number that is not a live page. -BOOL WINAPI XMemFreePhysicalPages(uint64_t page_count, const uint64_t* page_array) { - if (page_count && !page_array) { - SetLastError(ERROR_INVALID_PARAMETER); - return FALSE; - } - const std::lock_guard lock(g_phys_mutex); - for (uint64_t i = 0; i < page_count; ++i) { - const auto it = g_pages.find(page_array[i]); - if (it == g_pages.end()) { - SetLastError(ERROR_INVALID_PARAMETER); - return FALSE; - } - g_pages.erase(it); - g_free_slots.push_back(page_array[i] / kFramesPerPage); - } - return TRUE; -} - -// PVOID XMemMapPhysicalPages(PVOID address, UINT64 pageCount, UINT64* pageArray). Measured at twelve call sites: RCX -// is an address in a window XMemVirtualAlloc reserved, RDX a 64-bit count, R8 the pages to map there one after another, -// or null to unmap that many (four calls at shutdown). Callers test the 64-bit result for zero, so it is the address on -// success. A page number of 0 in the array unmaps that one page. -// -// Each page is its own view (MapViewOfFile3 into a 64 KiB placeholder), so any page can be remapped or unmapped later -// without touching its neighbours. A failure part-way leaves the pages before it mapped. -void* WINAPI XMemMapPhysicalPages(void* address, uint64_t page_count, const uint64_t* page_array) { - const uintptr_t start = reinterpret_cast(address); - if (!aligned_page_address(start) || page_count > (std::numeric_limits::max)() / kPhysicalPageSize || - start > (std::numeric_limits::max)() - page_count * kPhysicalPageSize) { - SetLastError(ERROR_INVALID_PARAMETER); - return nullptr; - } - if (!placeholder_api().available()) { - SetLastError(ERROR_NOT_SUPPORTED); - return nullptr; - } - const std::lock_guard lock(g_phys_mutex); - if (!page_array) { - for (uint64_t i = 0; i < page_count; ++i) { - if (!unmap_page(start + i * kPhysicalPageSize)) return nullptr; - } - return address; - } - const Window* const window = find_window(start, page_count * kPhysicalPageSize); - if (!window) { - SetLastError(ERROR_INVALID_ADDRESS); - return nullptr; - } - const DWORD protect = view_protect(*window); - for (uint64_t i = 0; i < page_count; ++i) { - if (!map_page(start + i * kPhysicalPageSize, page_array[i], protect)) return nullptr; - } - return address; -} - -// BOOL XMemMapPhysicalPagesScatter(PVOID* addresses, UINT32 pageCount, UINT64* pageArray). Measured at two call sites: -// RCX is an array of addresses, EDX a 32-bit count, R8 the page for each address (an entry of 0, or a null array, -// unmaps). The result is tested as a 32-bit BOOL. Like MapUserPhysicalPagesScatter: entry i maps pageArray[i] at -// addresses[i]. -BOOL WINAPI XMemMapPhysicalPagesScatter(void* const* addresses, uint32_t page_count, const uint64_t* page_array) { - if (page_count && !addresses) { - SetLastError(ERROR_INVALID_PARAMETER); - return FALSE; - } - if (!placeholder_api().available()) { - SetLastError(ERROR_NOT_SUPPORTED); - return FALSE; - } - const std::lock_guard lock(g_phys_mutex); - for (uint32_t i = 0; i < page_count; ++i) { - const uintptr_t address = reinterpret_cast(addresses[i]); - if (!aligned_page_address(address)) { - SetLastError(ERROR_INVALID_PARAMETER); - return FALSE; - } - const uint64_t page = page_array ? page_array[i] : 0; - if (page == 0) { - if (!unmap_page(address)) return FALSE; - continue; - } - const Window* const window = find_window(address, kPhysicalPageSize); - if (!window) { - SetLastError(ERROR_INVALID_ADDRESS); - return FALSE; - } - if (!map_page(address, page, view_protect(*window))) return FALSE; - } - return TRUE; -} - -UINT WINAPI XMemGetWriteWatch(DWORD flags, void* base_address, SIZE_T region_size, void** addresses, ULONG_PTR* count, - ULONG* granularity) { - return GetWriteWatch(flags, base_address, region_size, addresses, count, granularity); -} - -UINT WINAPI XMemResetWriteWatch(void* base_address, SIZE_T region_size) { - return ResetWriteWatch(base_address, region_size); -} - -// BOOL XMemTransferMemory(XMEM_TRANSFER_TYPE type, SIZE_T size). Its reference page and the XMEM_TRANSFER_TYPE enum -// page (gaming/gdk/docs/reference/system/xmem/{functions/xmemtransfermemory,enums/xmem_transfer_type}) are NDA -// topics on Microsoft Learn, so the shape comes from public code built against the GDK's xmem.h: Microsoft's -// XBOX-MonoGame-NetRumble sample (console/NetRumble.Bootstrap/Main.cpp) and FNA-XNA/NativeAOT-Xbox (Bootstrap/Main.cpp) -// both call `if (!XMemTransferMemory(XMemTransferTitleToSystem, additionalKernelPoolMemory))` with a `const size_t`, -// commented "Transfer additional memory to kernel pool" and "Must be multiples of 2MB sizes". So: two arguments, the -// enum (32 bits) in ECX and the size in RDX, and a zero return is failure. The public XLaunchNewGame page adds that -// "Memory transferred to the system using XMemTransferMemory (NDA topic) is persisted", and the game-save debugging -// page suggests it for E_OUTOFMEMORY "to transfer some memory to the system partition". -// -// On the console it moves budget between the title's partition and the system's. A PC has one pool and no budget -// split, so there is nothing to move: every direction and size returns TRUE and nothing is allocated or reserved. Not -// known (the pages are NDA): the numeric XMEM_TRANSFER_TYPE values, and whether the console refuses or rounds a size -// that is not a multiple of 2 MiB. Refusing would stop a title at startup (both samples return -1), while succeeding -// changes nothing here. TRUE is 1 in EAX, so it also reads as true if the real return type is a one-byte bool. -// -// gta6rt --trace FILE: the first call for each distinct (type, size) pair goes to the startup trace as an -// "xmem_transfer" event with the caller as module+RVA, so a run with the executable records the values it passes. -BOOL WINAPI XMemTransferMemory(uint32_t type, SIZE_T size) { - static std::atomic warned{false}; - if (!warned.exchange(true, std::memory_order_relaxed)) { - RT_LOG_WARN("xmem: XMemTransferMemory(type %u, %zu bytes): a PC has no title/system memory partition; " - "returning TRUE without moving anything (logged once)\n", - type, static_cast(size)); - } - if (rt::startup_trace::enabled()) { - static std::mutex mutex; - static std::set> seen; - bool first = false; - { - const std::lock_guard lock(mutex); - first = seen.insert({type, static_cast(size)}).second; - } - if (first) { - rt::startup_trace::event( - "xmem_transfer", - "\"api\":\"XMemTransferMemory\",\"type\":" + std::to_string(type) + - ",\"size\":" + std::to_string(static_cast(size)) + ",\"caller\":" + - rt::startup_trace::quote( - rt::startup_trace::where(reinterpret_cast(_ReturnAddress())))); - } - } - return TRUE; -} - -// kernel32!VirtualAlloc as a title calls it. The console's allocation type has two bits of its own, MEM_GRAPHICS -// (0x10000000, memory the GPU reads) and MEM_TITLE (0x40000000, the title's own heap). On a PC the host rejects both -// with ERROR_INVALID_PARAMETER (measured on Windows 11 26200: VirtualAlloc(NULL, 64 KiB, MEM_COMMIT | MEM_RESERVE | -// 0x10000000, PAGE_READWRITE) returns NULL; so does 0x40000000), so an engine allocating its heaps this way gets -// NULL at boot. Both are hints about where the memory lives; the host has no such split, so they are dropped and -// the rest is passed through. The PAGE_GRAPHICS_* protection bits are dropped (host_protect). Not done: whether -// graphics memory has to come from an arena the D3D12 layer can see (#313). -constexpr DWORD kMemGraphics = 0x10000000; -constexpr DWORD kMemTitle = 0x40000000; - -LPVOID WINAPI TitleVirtualAlloc(LPVOID address, SIZE_T size, DWORD allocation_type, DWORD protect) { - return VirtualAlloc(address, size, allocation_type & ~(kMemGraphics | kMemTitle), host_protect(protect)); -} - -} // namespace - -namespace rt::xmem { - -bool commit_physical_range(const void* address, size_t size) { - if (size == 0) return true; - const uintptr_t start = reinterpret_cast(address); - if (start > (std::numeric_limits::max)() - (size - 1)) { - SetLastError(ERROR_INVALID_PARAMETER); - return false; - } - const uintptr_t mask = ~static_cast(kPhysicalPageSize - 1); - const uintptr_t first = start & mask; - const uintptr_t pages = (((start + (size - 1)) & mask) - first) / kPhysicalPageSize + 1; - const FaultLockShared lock; - for (uintptr_t i = 0; i < pages; ++i) { - DWORD protect = 0; - const uintptr_t page = first + i * kPhysicalPageSize; - if (commit_mapped_page(page, page, protect) == PageCommit::failed) return false; - } - return true; -} - -bool commit_physical_pages(const uint64_t* page_array, size_t count) { - if (count == 0) return true; - if (!page_array) { - SetLastError(ERROR_INVALID_PARAMETER); - return false; - } - const std::lock_guard lock(g_phys_mutex); - size_t first = 0; - while (first < count) { - const auto it = g_pages.find(page_array[first]); - if (it == g_pages.end() || !it->second.section->scratch) { - SetLastError(ERROR_INVALID_PARAMETER); - return false; - } - size_t last = first + 1; - while (last < count) { - const auto next = g_pages.find(page_array[last]); - if (next == g_pages.end() || next->second.section != it->second.section || - next->second.offset != it->second.offset + (last - first) * kPhysicalPageSize) { - break; - } - ++last; - } - void* const backing = static_cast(it->second.section->scratch) + it->second.offset; - if (!VirtualAlloc(backing, (last - first) * kPhysicalPageSize, MEM_COMMIT, PAGE_READWRITE)) return false; - first = last; - } - return true; -} - -} - -#define TITLE_VIRTUAL_ALLOC(dll) {dll, "VirtualAlloc", reinterpret_cast(&TitleVirtualAlloc)} - -// The classic libraries and the memory api sets a title's imports name. -SHIM_TABLE(title_memory, - TITLE_VIRTUAL_ALLOC("kernel32.dll"), - TITLE_VIRTUAL_ALLOC("kernelbase.dll"), - TITLE_VIRTUAL_ALLOC("api-ms-win-core-memory-l1-1-0.dll"), - TITLE_VIRTUAL_ALLOC("api-ms-win-core-memory-l1-1-1.dll"), - TITLE_VIRTUAL_ALLOC("api-ms-win-core-memory-l1-1-2.dll"), - TITLE_VIRTUAL_ALLOC("api-ms-win-core-memory-l1-1-3.dll"), - TITLE_VIRTUAL_ALLOC("api-ms-win-core-memory-l1-1-4.dll"), - TITLE_VIRTUAL_ALLOC("api-ms-win-core-memory-l1-1-5.dll"), - TITLE_VIRTUAL_ALLOC("api-ms-win-core-memory-l1-1-6.dll"), -); - -SHIM_TABLE(xmem, - {"xmem.dll", "XMemAlloc", reinterpret_cast(&XMemAlloc)}, - {"xmem.dll", "XMemFree", reinterpret_cast(&XMemFree)}, - {"xmem.dll", "XMemVirtualQuery", reinterpret_cast(&XMemVirtualQuery)}, - {"xmem.dll", "XMemGetWorkingSetStatistics", reinterpret_cast(&XMemGetWorkingSetStatistics)}, - {"xmem.dll", "XMemVirtualAlloc", reinterpret_cast(&XMemVirtualAlloc)}, - {"xmem.dll", "XMemGetWriteWatch", reinterpret_cast(&XMemGetWriteWatch)}, - {"xmem.dll", "XMemResetWriteWatch", reinterpret_cast(&XMemResetWriteWatch)}, - {"xmem.dll", "XMemTransferMemory", reinterpret_cast(&XMemTransferMemory)}, - {"xmem.dll", "XMemAllocDefault", reinterpret_cast(&XMemAllocDefault)}, - {"xmem.dll", "XMemFreeDefault", reinterpret_cast(&XMemFreeDefault)}, - {"xmem.dll", "XMemIsToolsMemAvailable", reinterpret_cast(&XMemIsToolsMemAvailable)}, - {"xmem.dll", "XMemAllocatePhysicalPages", reinterpret_cast(&XMemAllocatePhysicalPages)}, - {"xmem.dll", "XMemFreePhysicalPages", reinterpret_cast(&XMemFreePhysicalPages)}, - {"xmem.dll", "XMemMapPhysicalPages", reinterpret_cast(&XMemMapPhysicalPages)}, - {"xmem.dll", "XMemMapPhysicalPagesScatter", reinterpret_cast(&XMemMapPhysicalPagesScatter)}, -); diff --git a/runtime/shims/xmem.h b/runtime/shims/xmem.h deleted file mode 100644 index beef935e6..000000000 --- a/runtime/shims/xmem.h +++ /dev/null @@ -1,11 +0,0 @@ -#pragma once - -#include -#include - -namespace rt::xmem { - -bool commit_physical_range(const void* address, std::size_t size); -bool commit_physical_pages(const std::uint64_t* page_array, std::size_t count); - -} diff --git a/runtime/shims/xtaskqueue/pch.h b/runtime/shims/xtaskqueue/pch.h deleted file mode 100644 index 81c16c437..000000000 --- a/runtime/shims/xtaskqueue/pch.h +++ /dev/null @@ -1,57 +0,0 @@ -// Stand-in for libHttpClient's pch.h, so third_party/xtaskqueue (Source/Task: XTaskQueue and XAsync) builds alone, -// without the HTTP stack. Only the macros and error codes those files use are defined here. -#pragma once -#ifndef WIN32_LEAN_AND_MEAN -#define WIN32_LEAN_AND_MEAN -#endif -#include -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#ifndef E_NO_TASK_QUEUE -#define E_NO_TASK_QUEUE _HRESULT_TYPEDEF_(0x800701ABL) -#endif -#ifndef E_ILLEGAL_METHOD_CALL -#define E_ILLEGAL_METHOD_CALL _HRESULT_TYPEDEF_(0x8000000EL) -#endif -#ifndef E_NOT_SUPPORTED -#define E_NOT_SUPPORTED _HRESULT_TYPEDEF_(0x80070032L) -#endif -#define E_GAMERUNTIME_INVALID_HANDLE E_HANDLE - -#include -#include -#include - -#define ASSERT(condition) assert(condition) -using DefaultUnnamedMutex = std::mutex; -using DefaultUnnamedConditionVariable = std::condition_variable; - -// No tracing, no GDK system-handle tracking, no runtime iterations. -#define HC_TRACE_ERROR(area, msg, ...) ((void)0) -#define ASYNC_LIB_TRACE(result, message) ((void)0) -#define SYSTEM_HANDLE_DEFINE_HELPERS(a, b) -#define SystemHandleAssert(h) -#define SystemHandleMarkCreated(h) -#define SystemHandleMarkDestroyed(h) -#define USE_UNIQUE_HANDLES() (true) -#define GetCurrentRuntimeIteration() 0 -#define CATCH_RETURN() catch (std::bad_alloc const&) { return E_OUTOFMEMORY; } catch (...) { return E_FAIL; } -#define CATCH_RETURN_WITH(errCode) catch (...) { return errCode; } - -#include "ResultMacros.h" diff --git a/runtime/src/active_input.h b/runtime/src/active_input.h deleted file mode 100644 index c0f7451b1..000000000 --- a/runtime/src/active_input.h +++ /dev/null @@ -1,146 +0,0 @@ -#pragma once - -// Which kind of input device the player used last: an Xbox-style pad, a PlayStation pad, a Nintendo pad or the -// keyboard pad (docs/gameinput.md). The GameInput shim reports every pad to the title as an Xbox One pad, so the title -// itself cannot tell; this is the port's own record, for whatever wants to follow the device in use (button prompt -// glyphs first). No SDL, no Windows headers: the shim feeds it one sample per device per poll, and tests feed it -// synthetic samples with their own times. -// -// The rules, chosen so that only deliberate input changes the answer: -// * Only an edge counts: a button going down, a trigger rising past `trigger`, a stick leaving the `stick` radius. -// A button held down, a trigger held, a stick held over, stick drift that stays inside the radius and analog -// noise never count, so a pad lying on the desk cannot take over. The keyboard pad's right stick follows the -// mouse, so a real mouse movement counts as keyboard input through the same stick rule. -// * A device's first sample is its baseline and counts for nothing: a pad that connects with a button held or a -// worn stick resting past the radius does not switch anything until it produces a new edge. -// * After a change, another change waits until `min_switch_us` has passed. An edge from another family inside that -// window is ignored (not queued), so two devices used at once cannot make the answer flicker. -// * Edges from a device of the family already active change nothing. -// * Before any edge the answer is `initial` (Xbox unless the caller says otherwise). -// * A forced family (LEONIDA_PROMPTS) wins over all of this; the tracking still runs underneath, so clearing the -// force goes straight back to the device in use. -// `generation` counts changes of the answer (tracked or forced), so a reader can tell that something changed without -// comparing families. - -#include -#include -#include -#include - -namespace leonida { - -enum class InputFamily : std::uint8_t { - Xbox, // Xbox One/Series, Xbox 360, and any pad SDL does not know better (generic, unknown) - PlayStation5, // DualSense, DualSense Edge - PlayStation4, // DualShock 4 - PlayStation3, // DualShock 3 - Nintendo, // Switch Pro controller and Joy-Cons - Keyboard, // the keyboard pad: keyboard and mouse -}; - -inline const char* input_family_name(InputFamily f) { - switch (f) { - case InputFamily::Xbox: return "Xbox"; - case InputFamily::PlayStation5: return "PlayStation 5"; - case InputFamily::PlayStation4: return "PlayStation 4"; - case InputFamily::PlayStation3: return "PlayStation 3"; - case InputFamily::Nintendo: return "Nintendo"; - case InputFamily::Keyboard: return "keyboard and mouse"; - } - return "unknown"; -} - -// One device's state at one poll, in GameInput's units: sticks -1..1, triggers 0..1. `buttons` is any bit set per -// pressed button (the shim passes the GameInput gamepad bits plus one bit for the guide button); only its changes -// matter. -struct InputSample { - std::uint32_t buttons = 0; - float left_trigger = 0, right_trigger = 0; - float left_x = 0, left_y = 0, right_x = 0, right_y = 0; -}; - -// What made the answer change, for the log line. -enum class InputEdge : std::uint8_t { None, Button, Trigger, Stick }; - -inline const char* input_edge_name(InputEdge e) { - switch (e) { - case InputEdge::None: return "none"; - case InputEdge::Button: return "button press"; - case InputEdge::Trigger: return "trigger pull"; - case InputEdge::Stick: return "stick movement"; - } - return "unknown"; -} - -class ActiveInputTracker { -public: - struct Thresholds { - float stick = 0.35f; // radius a stick has to leave - float trigger = 0.3f; // a trigger has to rise past this - std::uint64_t min_switch_us = 300'000; // shortest time between two changes - }; - - explicit ActiveInputTracker(InputFamily initial = InputFamily::Xbox) : tracked_(initial) {} - ActiveInputTracker(InputFamily initial, Thresholds t) : thresholds_(t), tracked_(initial) {} - - // One sample of one device (`device` is any key that stays the same while the device is connected). Returns the - // edge that changed the tracked family, or None when it did not change. With a family forced, the tracked family - // still follows the devices, but active() does not move. - InputEdge observe(std::uint64_t device, InputFamily family, const InputSample& now, std::uint64_t time_us) { - auto it = devices_.find(device); - if (it == devices_.end()) { - devices_.emplace(device, now); // the baseline: counts for nothing - return InputEdge::None; - } - const InputEdge edge = edge_between(it->second, now); - it->second = now; - if (edge == InputEdge::None || family == tracked_) return InputEdge::None; - if (changed_once_ && time_us - changed_at_ < thresholds_.min_switch_us) return InputEdge::None; - const InputFamily before = active(); - tracked_ = family; - changed_at_ = time_us; - changed_once_ = true; - if (active() != before) ++generation_; - return edge; - } - - // The device disconnected: its next sample, if it comes back, is a baseline again. - void forget(std::uint64_t device) { devices_.erase(device); } - - // Forces the answer (a family) or returns to tracking (nullopt). Changing what active() returns bumps generation. - void force(std::optional family) { - const InputFamily before = active(); - forced_ = family; - if (active() != before) ++generation_; - } - - InputFamily active() const { return forced_ ? *forced_ : tracked_; } - InputFamily tracked() const { return tracked_; } - bool forced() const { return forced_.has_value(); } - std::uint64_t generation() const { return generation_; } - const Thresholds& thresholds() const { return thresholds_; } - void set_thresholds(const Thresholds& t) { thresholds_ = t; } - -private: - InputEdge edge_between(const InputSample& was, const InputSample& now) const { - if (now.buttons & ~was.buttons) return InputEdge::Button; - const float t = thresholds_.trigger; - if ((was.left_trigger <= t && now.left_trigger > t) || (was.right_trigger <= t && now.right_trigger > t)) - return InputEdge::Trigger; - const auto out = [this](float x, float y) { return std::hypot(x, y) > thresholds_.stick; }; - if ((!out(was.left_x, was.left_y) && out(now.left_x, now.left_y)) || - (!out(was.right_x, was.right_y) && out(now.right_x, now.right_y))) - return InputEdge::Stick; - return InputEdge::None; - } - - Thresholds thresholds_{}; - InputFamily tracked_; - std::optional forced_; - std::uint64_t generation_ = 0; - std::uint64_t changed_at_ = 0; - bool changed_once_ = false; - std::unordered_map devices_; -}; - -} // namespace leonida diff --git a/runtime/src/arena_size.h b/runtime/src/arena_size.h deleted file mode 100644 index 8f4ca4caf..000000000 --- a/runtime/src/arena_size.h +++ /dev/null @@ -1,90 +0,0 @@ -#pragma once - -// The size of the GPU address arena (docs/d3d12_vulkan.md section 3.3): one VkBuffer bound to one VkDeviceMemory -// allocation. LEONIDA_ARENA_MB asks for a size (default 256 MiB, 16..4095 MiB: every console VA must fit 32 bits); -// the device then caps it, since the buffer may be no larger than maxBufferSize (Vulkan 1.3 / VK_KHR_maintenance4) -// and the allocation, which can be larger than the buffer, no larger than maxMemoryAllocationSize (Vulkan 1.1 / -// VK_KHR_maintenance3). Vulkan guarantees at least 1 GiB for both; the RX 6800 (AMD 26.11.2) reports 2 GiB for both. -// -// The decision is a pure function of the variable's text and the two limits, so it is tested without a GPU -// (arena_size_test). It depends only on the Vulkan headers. - -#include - -#include -#include -#include - -namespace leonida { - -constexpr VkDeviceSize kArenaMiB = VkDeviceSize(1) << 20; -constexpr VkDeviceSize kArenaDefaultMiB = 256; -constexpr VkDeviceSize kArenaMinMiB = 16; -constexpr VkDeviceSize kArenaMaxMiB = 4095; - -// The device's limits; 0 is "not known", which caps nothing. -struct ArenaLimits { - VkDeviceSize max_buffer_size = 0; // VkPhysicalDeviceMaintenance4Properties::maxBufferSize - VkDeviceSize max_allocation_size = 0; // VkPhysicalDeviceMaintenance3Properties::maxMemoryAllocationSize -}; - -// Reads both limits with vkGetPhysicalDeviceProperties2 (the device is Vulkan 1.3, which has both structures). -template -ArenaLimits query_arena_limits(GetProperties2 get_properties2, VkPhysicalDevice physical) { - VkPhysicalDeviceMaintenance4Properties m4{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MAINTENANCE_4_PROPERTIES}; - VkPhysicalDeviceMaintenance3Properties m3{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MAINTENANCE_3_PROPERTIES, &m4}; - VkPhysicalDeviceProperties2 properties{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROPERTIES_2, &m3}; - get_properties2(physical, &properties); - return {m4.maxBufferSize, m3.maxMemoryAllocationSize}; -} - -// Which limits made the arena smaller than asked (both bits when they cap it to the same size). -enum ArenaCap : unsigned { - arena_cap_none = 0, - arena_cap_buffer = 1, // maxBufferSize - arena_cap_allocation = 2, // maxMemoryAllocationSize -}; - -struct ArenaSize { - VkDeviceSize requested = 0; // LEONIDA_ARENA_MB (or the default) after the 16..4095 MiB clamp, in bytes - VkDeviceSize bytes = 0; // the buffer size to create; 0 when a limit leaves less than 1 MiB - unsigned capped = arena_cap_none; -}; - -// `env` is LEONIDA_ARENA_MB's text, or null when it is unset or empty. `allocation_overhead` is how much larger the -// buffer's memory requirement is than the buffer (alignment padding): 0 for a first try, then requirements.size - -// buffer size if that allocation would pass maxMemoryAllocationSize. -// - The request is clamped to 16..4095 MiB first (text that is not a number reads as 0, so 16). -// - Each known limit then caps it, rounded down to whole MiB: the buffer to maxBufferSize, the buffer plus the -// overhead to maxMemoryAllocationSize. A limit wins over the 16 MiB floor: an arena over a device limit is -// invalid Vulkan, while one under 16 MiB is only small (and no conformant device reports under 1 GiB). -inline ArenaSize decide_arena_size(const char* env, const ArenaLimits& limits, VkDeviceSize allocation_overhead = 0) { - VkDeviceSize megabytes = kArenaDefaultMiB; - if (env && *env) megabytes = std::clamp(std::strtoull(env, nullptr, 10), kArenaMinMiB, kArenaMaxMiB); - ArenaSize size; - size.requested = size.bytes = megabytes * kArenaMiB; - VkDeviceSize by_buffer = size.requested, by_allocation = size.requested; - if (limits.max_buffer_size) by_buffer = limits.max_buffer_size / kArenaMiB * kArenaMiB; - if (limits.max_allocation_size) - by_allocation = limits.max_allocation_size > allocation_overhead - ? (limits.max_allocation_size - allocation_overhead) / kArenaMiB * kArenaMiB - : 0; - const VkDeviceSize cap = std::min(by_buffer, by_allocation); - if (cap >= size.requested) return size; - size.bytes = cap; - if (by_buffer == cap) size.capped |= arena_cap_buffer; - if (by_allocation == cap) size.capped |= arena_cap_allocation; - return size; -} - -// The Vulkan names of the limits in `capped`, for the log line. -inline const char* arena_cap_name(unsigned capped) { - switch (capped) { - case arena_cap_buffer: return "maxBufferSize"; - case arena_cap_allocation: return "maxMemoryAllocationSize"; - case arena_cap_buffer | arena_cap_allocation: return "maxBufferSize and maxMemoryAllocationSize"; - default: return "no limit"; - } -} - -} // namespace leonida diff --git a/runtime/src/base_reservation.h b/runtime/src/base_reservation.h deleted file mode 100644 index b76c28c70..000000000 --- a/runtime/src/base_reservation.h +++ /dev/null @@ -1,152 +0,0 @@ -#pragma once - -// Keeping a relocation-less game image's preferred range free until the loader maps it there. -// -// An EXE without a .reloc directory can only run at its ImageBase (0x140000000 by default). Windows and x86-64 Wine -// leave that range alone, but arm64 Wine on macOS (CrossOver's arm64 bottles, whose x86-64 code runs under FEX) puts -// its own start-up allocations at 0x100000000 and up, over that range, before gta6rt's first line runs. So gta6rt -// starts itself again, suspended, reserves [ImageBase, ImageBase + SizeOfImage) in that child before any of its code -// runs, and resumes it; the child's loader then commits the image inside the reservation (commit_reserved), so -// nothing else can take the range in between. The child is told by LEONIDA_BASE_RESERVED=: (hex), which -// also stops it from starting itself again. Measured on CrossOver Preview 20260821 (arm64 bottle, M2 Max): in a -// suspended child 0x140000000-0x170000000 is free and reservable; macOS maps its own regions above that (the arm64 -// shared region starts at 0x180000000), so a range there can't be had either way. -// -// Nothing changes where the range is free at start-up (Windows, x86-64 Wine) or where the image has relocations. - -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace rt::base_reservation { - -inline constexpr wchar_t kVariable[] = L"LEONIDA_BASE_RESERVED"; - -struct Range { - std::uint64_t base = 0; - std::uint64_t size = 0; -}; - -// The range this process was started with (LEONIDA_BASE_RESERVED), if any. -inline std::optional inherited() { - wchar_t value[64] = {}; - const DWORD length = GetEnvironmentVariableW(kVariable, value, 64); - if (!length || length >= 64) return std::nullopt; - Range r{}; - // swscanf_s, not swscanf (MSVC's C4996): integer conversions take no buffer sizes, so the parse is the same. - if (swscanf_s(value, L"%llx:%llx", reinterpret_cast(&r.base), - reinterpret_cast(&r.size)) != 2 || - !r.size) - return std::nullopt; - return r; -} - -// Commits [base, base + size) for the loader when it lies inside the reservation this process was started with and -// that reservation is still in place; returns null otherwise (the caller then allocates as usual). The reservation -// is the allocation, so VirtualFree(base, 0, MEM_RELEASE) frees it as it frees any image. -inline void* commit_reserved(std::uint64_t base, std::uint64_t size) { - const auto r = inherited(); - if (!r || base != r->base || size > r->size) return nullptr; - MEMORY_BASIC_INFORMATION info{}; - if (!VirtualQuery(reinterpret_cast(base), &info, sizeof info) || info.State != MEM_RESERVE || - reinterpret_cast(info.AllocationBase) != base) - return nullptr; - return VirtualAlloc(reinterpret_cast(base), static_cast(size), MEM_COMMIT, PAGE_READWRITE); -} - -// The preferred range of `image` when it has no relocations and that range is not free in this process; nullopt -// when the image can be mapped as it is (or is not a readable PE32+, which the loader reports itself). -inline std::optional needed(const std::filesystem::path& image) { - std::ifstream file(image, std::ios::binary); - IMAGE_DOS_HEADER dos{}; - if (!file.read(reinterpret_cast(&dos), sizeof dos) || dos.e_magic != IMAGE_DOS_SIGNATURE || dos.e_lfanew < 0) - return std::nullopt; - IMAGE_NT_HEADERS64 nt{}; - if (!file.seekg(dos.e_lfanew) || !file.read(reinterpret_cast(&nt), sizeof nt) || - nt.Signature != IMAGE_NT_SIGNATURE || nt.OptionalHeader.Magic != IMAGE_NT_OPTIONAL_HDR64_MAGIC || - !nt.OptionalHeader.SizeOfImage) - return std::nullopt; - const auto& oh = nt.OptionalHeader; - if (oh.NumberOfRvaAndSizes > IMAGE_DIRECTORY_ENTRY_BASERELOC && - oh.DataDirectory[IMAGE_DIRECTORY_ENTRY_BASERELOC].Size) - return std::nullopt; // relocatable: the loader moves it if the base is taken - const Range r{oh.ImageBase, (static_cast(oh.SizeOfImage) + 0xffff) & ~std::uint64_t{0xffff}}; - for (std::uint64_t at = r.base; at < r.base + r.size;) { - MEMORY_BASIC_INFORMATION info{}; - if (!VirtualQuery(reinterpret_cast(at), &info, sizeof info)) return r; - if (info.State != MEM_FREE) return r; - at = reinterpret_cast(info.BaseAddress) + info.RegionSize; - } - return std::nullopt; -} - -// Runs this program again with the same command line, suspended, reserves `r` in the new process, resumes it and -// returns its exit code. On failure prints why and returns 1 (the child, if any, is ended unrun). -inline int relaunch(const Range& r) { - wchar_t self[MAX_PATH * 4] = {}; - if (!GetModuleFileNameW(nullptr, self, MAX_PATH * 4)) { - std::fprintf(stderr, "error: GetModuleFileName failed (%lu)\n", GetLastError()); - return 1; - } - wchar_t marker[64]; - std::swprintf(marker, 64, L"%llx:%llx", static_cast(r.base), - static_cast(r.size)); - // Inherited by the child: it tells it to commit inside the reservation and not to relaunch again. - if (!SetEnvironmentVariableW(kVariable, marker)) { - std::fprintf(stderr, "error: setting %ls failed (%lu)\n", kVariable, GetLastError()); - return 1; - } - std::wstring command_line = GetCommandLineW(); - STARTUPINFOW startup{sizeof startup}; - startup.dwFlags = STARTF_USESTDHANDLES; - startup.hStdInput = GetStdHandle(STD_INPUT_HANDLE); - startup.hStdOutput = GetStdHandle(STD_OUTPUT_HANDLE); - startup.hStdError = GetStdHandle(STD_ERROR_HANDLE); - for (HANDLE h : {startup.hStdInput, startup.hStdOutput, startup.hStdError}) - if (h && h != INVALID_HANDLE_VALUE) SetHandleInformation(h, HANDLE_FLAG_INHERIT, HANDLE_FLAG_INHERIT); - PROCESS_INFORMATION process{}; - std::fflush(stdout); - std::fflush(stderr); - if (!CreateProcessW(self, command_line.data(), nullptr, nullptr, TRUE, CREATE_SUSPENDED, nullptr, nullptr, - &startup, &process)) { - std::fprintf(stderr, "error: starting gta6rt again to reserve the image range failed (%lu)\n", GetLastError()); - return 1; - } - const auto abandon = [&process] { // the child never ran: end it and release its handles - TerminateProcess(process.hProcess, 1); - CloseHandle(process.hThread); - CloseHandle(process.hProcess); - }; - if (!VirtualAllocEx(process.hProcess, reinterpret_cast(r.base), static_cast(r.size), MEM_RESERVE, - PAGE_NOACCESS)) { - const DWORD error = GetLastError(); - abandon(); - std::fprintf(stderr, - "error: the image has no relocations and its range %#llx-%#llx is taken, also in a new " - "process (VirtualAllocEx %lu)\n", - static_cast(r.base), static_cast(r.base + r.size), error); - return 1; - } - if (ResumeThread(process.hThread) == static_cast(-1)) { // still suspended: the wait would never end - const DWORD error = GetLastError(); - abandon(); - std::fprintf(stderr, "error: resuming the relaunched gta6rt failed (%lu)\n", error); - return 1; - } - WaitForSingleObject(process.hProcess, INFINITE); - DWORD code = 1; - GetExitCodeProcess(process.hProcess, &code); - CloseHandle(process.hThread); - CloseHandle(process.hProcess); - return static_cast(code); -} - -} // namespace rt::base_reservation diff --git a/runtime/src/binary_occlusion.comp b/runtime/src/binary_occlusion.comp deleted file mode 100644 index 30f43ebc6..000000000 --- a/runtime/src/binary_occlusion.comp +++ /dev/null @@ -1,13 +0,0 @@ -#version 450 - -layout(local_size_x = 64) in; -layout(set = 0, binding = 0, std430) buffer QueryResults { uvec2 results[]; }; -layout(push_constant) uniform ResolveRange { uint count; }; - -void main() { - uint index = gl_GlobalInvocationID.x; - if (index < count) { - uvec2 raw = results[index]; - results[index] = uvec2(uint((raw.x | raw.y) != 0u), 0u); - } -} diff --git a/runtime/src/binary_occlusion_spirv.h b/runtime/src/binary_occlusion_spirv.h deleted file mode 100644 index 163bf5723..000000000 --- a/runtime/src/binary_occlusion_spirv.h +++ /dev/null @@ -1,44 +0,0 @@ -#pragma once - -#include - -namespace leonida { - -// From binary_occlusion.comp. Regenerate with glslangValidator -V --target-env vulkan1.0 -Os -g0, -// then encode the resulting little-endian SPIR-V as uint32_t words. -// Embedded so the runtime can build with Vulkan headers alone. -inline constexpr std::uint32_t binary_occlusion_spirv[] = { - 0x07230203, 0x00010000, 0x0008000b, 0x00000035, 0x00000000, 0x00020011, 0x00000001, 0x0006000b, - 0x00000001, 0x4c534c47, 0x6474732e, 0x3035342e, 0x00000000, 0x0003000e, 0x00000000, 0x00000001, - 0x0006000f, 0x00000005, 0x00000004, 0x6e69616d, 0x00000000, 0x0000000b, 0x00060010, 0x00000004, - 0x00000011, 0x00000040, 0x00000001, 0x00000001, 0x00040047, 0x0000000b, 0x0000000b, 0x0000001c, - 0x00030047, 0x00000011, 0x00000002, 0x00050048, 0x00000011, 0x00000000, 0x00000023, 0x00000000, - 0x00040047, 0x00000020, 0x00000006, 0x00000008, 0x00030047, 0x00000021, 0x00000003, 0x00050048, - 0x00000021, 0x00000000, 0x00000023, 0x00000000, 0x00040047, 0x00000023, 0x00000021, 0x00000000, - 0x00040047, 0x00000023, 0x00000022, 0x00000000, 0x00040047, 0x00000034, 0x0000000b, 0x00000019, - 0x00020013, 0x00000002, 0x00030021, 0x00000003, 0x00000002, 0x00040015, 0x00000006, 0x00000020, - 0x00000000, 0x00040017, 0x00000009, 0x00000006, 0x00000003, 0x00040020, 0x0000000a, 0x00000001, - 0x00000009, 0x0004003b, 0x0000000a, 0x0000000b, 0x00000001, 0x0004002b, 0x00000006, 0x0000000c, - 0x00000000, 0x00040020, 0x0000000d, 0x00000001, 0x00000006, 0x0003001e, 0x00000011, 0x00000006, - 0x00040020, 0x00000012, 0x00000009, 0x00000011, 0x0004003b, 0x00000012, 0x00000013, 0x00000009, - 0x00040015, 0x00000014, 0x00000020, 0x00000001, 0x0004002b, 0x00000014, 0x00000015, 0x00000000, - 0x00040020, 0x00000016, 0x00000009, 0x00000006, 0x00020014, 0x00000019, 0x00040017, 0x0000001d, - 0x00000006, 0x00000002, 0x0003001d, 0x00000020, 0x0000001d, 0x0003001e, 0x00000021, 0x00000020, - 0x00040020, 0x00000022, 0x00000002, 0x00000021, 0x0004003b, 0x00000022, 0x00000023, 0x00000002, - 0x00040020, 0x00000025, 0x00000002, 0x0000001d, 0x0004002b, 0x00000006, 0x0000002b, 0x00000001, - 0x0004002b, 0x00000006, 0x00000033, 0x00000040, 0x0006002c, 0x00000009, 0x00000034, 0x00000033, - 0x0000002b, 0x0000002b, 0x00050036, 0x00000002, 0x00000004, 0x00000000, 0x00000003, 0x000200f8, - 0x00000005, 0x00050041, 0x0000000d, 0x0000000e, 0x0000000b, 0x0000000c, 0x0004003d, 0x00000006, - 0x0000000f, 0x0000000e, 0x00050041, 0x00000016, 0x00000017, 0x00000013, 0x00000015, 0x0004003d, - 0x00000006, 0x00000018, 0x00000017, 0x000500b0, 0x00000019, 0x0000001a, 0x0000000f, 0x00000018, - 0x000300f7, 0x0000001c, 0x00000000, 0x000400fa, 0x0000001a, 0x0000001b, 0x0000001c, 0x000200f8, - 0x0000001b, 0x00060041, 0x00000025, 0x00000026, 0x00000023, 0x00000015, 0x0000000f, 0x0004003d, - 0x0000001d, 0x00000027, 0x00000026, 0x00050051, 0x00000006, 0x0000002a, 0x00000027, 0x00000000, - 0x00050051, 0x00000006, 0x0000002d, 0x00000027, 0x00000001, 0x000500c5, 0x00000006, 0x0000002e, - 0x0000002a, 0x0000002d, 0x000500ab, 0x00000019, 0x0000002f, 0x0000002e, 0x0000000c, 0x000600a9, - 0x00000006, 0x00000030, 0x0000002f, 0x0000002b, 0x0000000c, 0x00050050, 0x0000001d, 0x00000031, - 0x00000030, 0x0000000c, 0x0003003e, 0x00000026, 0x00000031, 0x000200f9, 0x0000001c, 0x000200f8, - 0x0000001c, 0x000100fd, 0x00010038, -}; - -} // namespace leonida diff --git a/runtime/src/buffer_va_index.h b/runtime/src/buffer_va_index.h deleted file mode 100644 index 2ea0f9380..000000000 --- a/runtime/src/buffer_va_index.h +++ /dev/null @@ -1,99 +0,0 @@ -#pragma once - -// Which registered buffer a console VA falls in (VulkanContext::buffer_at, for vertex and index views and -// WriteBufferImmediate). Ranges are kept ordered by their first VA, so a lookup is a binary search instead of a scan of -// every registered resource. No Vulkan or Windows dependency; not thread-safe (VulkanContext guards it with -// resource_mutex_, like the bindings themselves). -// -// D3D12 lets placed buffers alias, so ranges may overlap. A lookup names the bytes it needs, [va, va + bytes), and -// returns, among the ranges that hold va, the one that starts closest below it (the larger ID on a tie) that also -// holds all of those bytes; when none does, the closest one that holds va. So a view that starts in a small placed -// buffer and runs past its end resolves to a larger buffer that aliases the same memory and holds all of it, instead -// of being cut at the small one's end (found in review of #2823). The walk goes down from the nearest start and stops -// once no range can still reach the VA, or, with a fallback found, once no range can still hold all the bytes; both -// are bounded by `longest_`. Without overlaps the first range it looks at is the answer, or none is. -// `longest_` is the longest range indexed now, not the longest ever: a large buffer that is freed stops lengthening -// later misses. A miss still walks every start within the longest live range below the VA. - -#include -#include -#include -#include -#include - -namespace leonida { - -template -class BufferVaIndex { -public: - // Registers [va, va + size). A null VA or an empty range is not indexed (no lookup can land in it). - void insert(std::uint64_t va, std::uint64_t size, Id id) { - if (!va || !size) return; - const auto [it, added] = ranges_.try_emplace({va, id}, size); - try { - sizes_.insert(size); - } catch (...) { - if (added) ranges_.erase(it); - throw; - } - if (!added) { // the same (va, id) again: its new size replaces the old one - drop_size(it->second); - it->second = size; - } - longest_ = *sizes_.rbegin(); - } - - // Forgets what insert(va, size, id) registered; nothing when it was not indexed. - void erase(std::uint64_t va, Id id) { - const auto it = ranges_.find({va, id}); - if (it == ranges_.end()) return; - drop_size(it->second); - ranges_.erase(it); - longest_ = sizes_.empty() ? 0 : *sizes_.rbegin(); - } - - struct Hit { - Id id; - std::uint64_t start; // the range's first VA - std::uint64_t size; - }; - - // The range that holds `va`, preferring one that holds [va, va + bytes) (bytes 0 counts as 1); false when none - // holds va. - bool find(std::uint64_t va, Hit& out, std::uint64_t bytes = 1) const { - if (!bytes) bytes = 1; - bool found = false; // `out` holds the closest range that holds va, though not all the bytes - auto it = ranges_.upper_bound({va, max_id()}); - while (it != ranges_.begin()) { - --it; - const std::uint64_t start = it->first.first; - const std::uint64_t offset = va - start; // start <= va here; it only grows as the walk goes down - if (offset >= longest_) break; // no range that starts this low reaches va - if (found && bytes > longest_ - offset) break; // nor holds all the bytes - if (offset >= it->second) continue; - if (bytes <= it->second - offset) { - out = {it->first.second, start, it->second}; - return true; - } - if (!found) { - out = {it->first.second, start, it->second}; - found = true; - } - } - return found; - } - - std::size_t size() const { return ranges_.size(); } - std::uint64_t longest() const { return longest_; } - -private: - static constexpr Id max_id() { return ~Id(0); } - - void drop_size(std::uint64_t size) { sizes_.erase(sizes_.find(size)); } // one copy, not every range of that size - - std::map, std::uint64_t> ranges_; // (first VA, id) -> bytes - std::multiset sizes_; // the size of every indexed range, so the longest is known after an erase - std::uint64_t longest_ = 0; // the longest indexed range, 0 when none is -}; - -} // namespace leonida diff --git a/runtime/src/cached_pso.h b/runtime/src/cached_pso.h deleted file mode 100644 index 32710244e..000000000 --- a/runtime/src/cached_pso.h +++ /dev/null @@ -1,110 +0,0 @@ -// The blob ID3D12PipelineState::GetCachedBlob hands out and Create*PipelineState checks in CachedPSO. -// -// The Vulkan layer keeps no driver-compiled pipeline in it (D3D-34 seeds a VkPipelineCache from the build instead); -// the blob only records what the PC runtime checks before accepting a cached PSO, measured with the host runtime on -// an RTX 3060 (driver 32.0.16.1714) and WARP: -// - the same description: accepted; -// - another shader, or a root signature with other content: E_INVALIDARG (an equal root signature object is fine; -// D3D12_PIPELINE_STATE_DESC::Flags is not part of the match); -// - any byte changed, a truncated blob, or a pointer with CachedBlobSizeInBytes 0: E_INVALIDARG; -// - a null pointer with a size: ignored, the PSO is created; -// - a blob from another adapter: D3D12_ERROR_ADAPTER_NOT_FOUND. -// A blob from the same adapter and another driver gives D3D12_ERROR_DRIVER_VERSION_MISMATCH (DirectX docs; not -// measured, it needs a driver change). -#pragma once - -#include -#include -#include -#include -#include -#include - -namespace leonida::cached_pso { - -// The physical device the blob was made on: VkPhysicalDeviceProperties' IDs, driverVersion and pipelineCacheUUID. -struct Identity { - std::uint32_t vendor = 0; - std::uint32_t device = 0; - std::uint32_t driver = 0; - std::uint8_t cache_uuid[16] = {}; -}; - -// What a blob is checked against: the SHA-256 (hex) of the parts of the description the PC runtime matches. -using Key = std::string; - -enum class Check { accepted, invalid, other_adapter, other_driver, other_description }; - -inline constexpr std::uint32_t magic = 0x4f53504c; // "LPSO" -inline constexpr std::uint32_t version = 1; -inline constexpr std::size_t key_bytes = 64; -inline constexpr std::size_t blob_bytes = 4 + 4 + 12 + 16 + key_bytes + 4; - -inline std::uint32_t fnv1a(const std::uint8_t* data, std::size_t size) { - std::uint32_t h = 0x811c9dc5u; - for (std::size_t i = 0; i < size; ++i) h = (h ^ data[i]) * 0x01000193u; - return h; -} - -inline void put32(std::vector& out, std::uint32_t v) { - for (int i = 0; i < 4; ++i) out.push_back(std::uint8_t(v >> (8 * i))); -} - -inline std::uint32_t get32(const std::uint8_t* p) { - return std::uint32_t(p[0]) | (std::uint32_t(p[1]) << 8) | (std::uint32_t(p[2]) << 16) | (std::uint32_t(p[3]) << 24); -} - -// magic, version, vendor, device, driver, pipelineCacheUUID, key, then FNV-1a of everything before it: a changed -// byte anywhere makes the blob invalid, as with the PC runtime. -inline std::vector encode(const Identity& identity, const Key& key) { - std::vector out; - out.reserve(blob_bytes); - put32(out, magic); - put32(out, version); - put32(out, identity.vendor); - put32(out, identity.device); - put32(out, identity.driver); - out.insert(out.end(), std::begin(identity.cache_uuid), std::end(identity.cache_uuid)); - std::string padded = key; - padded.resize(key_bytes, '\0'); - out.insert(out.end(), padded.begin(), padded.end()); - put32(out, fnv1a(out.data(), out.size())); - return out; -} - -inline Check check(const Identity& identity, const Key& key, std::span blob) { - if (blob.size() != blob_bytes) return Check::invalid; - const std::uint8_t* p = blob.data(); - if (get32(p + blob_bytes - 4) != fnv1a(p, blob_bytes - 4)) return Check::invalid; - if (get32(p) != magic || get32(p + 4) != version) return Check::invalid; - if (get32(p + 8) != identity.vendor || get32(p + 12) != identity.device) return Check::other_adapter; - if (get32(p + 16) != identity.driver || std::memcmp(p + 20, identity.cache_uuid, 16) != 0) - return Check::other_driver; - std::string padded = key; - padded.resize(key_bytes, '\0'); - if (std::memcmp(p + 36, padded.data(), key_bytes) != 0) return Check::other_description; - return Check::accepted; -} - -// Builds the bytes a key is hashed from: every field the PC runtime matches, in a fixed order with lengths, so two -// descriptions give the same bytes only when those fields are equal. -class KeyBuilder { -public: - KeyBuilder& tag(const char* name) { return bytes(name, std::strlen(name)); } - KeyBuilder& u32(std::uint32_t v) { - put32(data_, v); - return *this; - } - KeyBuilder& bytes(const void* p, std::size_t n) { - put32(data_, std::uint32_t(n)); - if (n) data_.insert(data_.end(), static_cast(p), static_cast(p) + n); - return *this; - } - KeyBuilder& text(const char* s) { return s ? bytes(s, std::strlen(s)) : u32(0xffffffffu); } - const std::vector& data() const { return data_; } - -private: - std::vector data_; -}; - -} // namespace leonida::cached_pso diff --git a/runtime/src/code_hooks.h b/runtime/src/code_hooks.h deleted file mode 100644 index c87f1b2b1..000000000 --- a/runtime/src/code_hooks.h +++ /dev/null @@ -1,250 +0,0 @@ -// Hooks on a function of the loaded game image, by redirecting its direct callers (docs/modding.md, "Day one"). -// -// Patching inside a function needs an instruction decoder to move its prologue. Redirecting the callers does not: -// every `call rel32` (E8) and `jmp rel32` (E9) in the image's executable sections whose target is the function is -// pointed at a thunk instead. The thunk saves the argument registers (rcx, rdx, r8, r9, xmm0-3), passes one 32-bit -// argument through a C++ function, restores the rest and jumps to the original. A call through a pointer (vtable, -// import slot) is not redirected, which suits RAGE's archetype lookup: a static function called directly. -// -// A byte pattern can look like E8/E9 + rel32 inside another instruction; it is only rewritten when its target is -// exactly the hooked function, so a false match must also point there. x64 Windows only. -#pragma once - -#include - -#include -#include -#include -#include - -namespace leonida::hooks { - -using RemapFn = uint32_t (*)(uint32_t); - -// Executable memory within +-2 GiB of `close_to`, so a rel32 branch from the image reaches it. nullptr if none is free. -inline uint8_t* alloc_near(const void* close_to, std::size_t size) { - if (!close_to || size == 0) return nullptr; - SYSTEM_INFO si; - GetSystemInfo(&si); - const uintptr_t gran = si.dwAllocationGranularity; - const uintptr_t center = reinterpret_cast(close_to) & ~(gran - 1); - const uintptr_t span = 0x70000000; // stay well inside the rel32 range from anywhere in a large image - for (uintptr_t delta = gran; delta < span; delta += gran) { - for (int side = 0; side < 2; ++side) { - if (side == 0 && center < delta) continue; - if (side == 1 && UINTPTR_MAX - center < delta) continue; - const uintptr_t at = side ? center + delta : center - delta; - if (void* p = VirtualAlloc(reinterpret_cast(at), size, MEM_RESERVE | MEM_COMMIT, - PAGE_EXECUTE_READWRITE)) - return static_cast(p); - } - } - return nullptr; -} - -// A thunk's page: its code, then the unwind data Windows needs to walk the stack through it. Without that data the -// unwinder takes the thunk for a leaf function and reads the return address from the wrong place, so an exception -// raised below it (in the hooked function or the callback) finds no handler and ends the process, and a stack trace -// stops there. -constexpr DWORD kThunkUnwindOffset = 0x200; -constexpr DWORD kThunkFunctionOffset = 0x240; - -// Seals a thunk of `code_size` bytes: writes its UNWIND_INFO (`unwind`: version, prolog size, code count and codes) and -// RUNTIME_FUNCTION, makes the page executable and registers the function table. Frees the page and returns null on -// failure. -inline uint8_t* finish_thunk(uint8_t* t, std::size_t code_size, std::initializer_list unwind) { - std::size_t i = 0; - for (uint8_t b : unwind) t[kThunkUnwindOffset + i++] = b; - auto* function = reinterpret_cast(t + kThunkFunctionOffset); - function->BeginAddress = 0; - function->EndAddress = static_cast(code_size); - function->UnwindData = kThunkUnwindOffset; - DWORD old = 0; - if (!VirtualProtect(t, 4096, PAGE_EXECUTE_READ, &old) || - !RtlAddFunctionTable(function, 1, reinterpret_cast(t))) { - VirtualFree(t, 0, MEM_RELEASE); - return nullptr; - } - FlushInstructionCache(GetCurrentProcess(), t, code_size); - return t; -} - -// Frees a thunk that nothing points at. Its function table goes first: a table left behind would send every later -// unwind through freed memory. -inline void free_thunk(uint8_t* thunk) { - if (!thunk) return; - RtlDeleteFunctionTable(reinterpret_cast(thunk + kThunkFunctionOffset)); - VirtualFree(thunk, 0, MEM_RELEASE); -} - -// The thunk: argument `arg` (0 = rcx, 1 = rdx; the low 32 bits) goes through `fn`, then the original runs with every -// other argument register as the caller left it. Stack: the caller's call leaves rsp = 8 mod 16; four pushes and -// 0x68 bytes make it 16-aligned for the call to `fn`, with its 32-byte shadow space and room for xmm0-3. -inline uint8_t* make_remap_thunk(const void* close_to, int arg, RemapFn fn, const void* original) { - if (!close_to || !fn || !original || (arg != 0 && arg != 1)) return nullptr; - uint8_t* t = alloc_near(close_to, 4096); - if (!t) return nullptr; - uint8_t* p = t; - auto put = [&](std::initializer_list bytes) { for (uint8_t b : bytes) *p++ = b; }; - auto put64 = [&](uint64_t v) { std::memcpy(p, &v, 8); p += 8; }; - put({0x51, 0x52, 0x41, 0x50, 0x41, 0x51}); // push rcx, rdx, r8, r9 - put({0x48, 0x83, 0xEC, 0x68}); // sub rsp, 0x68 - put({0xF3, 0x0F, 0x7F, 0x44, 0x24, 0x20}); // movdqu [rsp+0x20], xmm0 - put({0xF3, 0x0F, 0x7F, 0x4C, 0x24, 0x30}); // movdqu [rsp+0x30], xmm1 - put({0xF3, 0x0F, 0x7F, 0x54, 0x24, 0x40}); // movdqu [rsp+0x40], xmm2 - put({0xF3, 0x0F, 0x7F, 0x5C, 0x24, 0x50}); // movdqu [rsp+0x50], xmm3 - if (arg == 1) put({0x89, 0xD1}); // mov ecx, edx - put({0x48, 0xB8}); put64(reinterpret_cast(fn)); // mov rax, fn - put({0xFF, 0xD0}); // call rax - put({0xF3, 0x0F, 0x6F, 0x44, 0x24, 0x20}); // movdqu xmm0, [rsp+0x20] - put({0xF3, 0x0F, 0x6F, 0x4C, 0x24, 0x30}); // movdqu xmm1, [rsp+0x30] - put({0xF3, 0x0F, 0x6F, 0x54, 0x24, 0x40}); // movdqu xmm2, [rsp+0x40] - put({0xF3, 0x0F, 0x6F, 0x5C, 0x24, 0x50}); // movdqu xmm3, [rsp+0x50] - put({0x48, 0x83, 0xC4, 0x68}); // add rsp, 0x68 - put({0x41, 0x59, 0x41, 0x58, 0x5A, 0x59}); // pop r9, r8, rdx, rcx - put({0x89, static_cast(arg == 0 ? 0xC1 : 0xC2)}); // mov ecx|edx, eax (the remapped value) - put({0x48, 0xB8}); put64(reinterpret_cast(original)); // mov rax, original - put({0xFF, 0xE0}); // jmp rax - // UNWIND_INFO version 1, 10-byte prolog, five UWOP_ALLOC_SMALL codes (size / 8 - 1 in the high nibble), the last - // prolog instruction first: sub rsp,0x68 at 10, then 8 bytes for each push (the pushed registers are volatile). - return finish_thunk(t, p - t, {0x01, 10, 5, 0, 10, 0xC2, 6, 0x02, 4, 0x02, 2, 0x02, 1, 0x02, 0, 0}); -} - -using ResultFn = uint32_t (*)(uint32_t result, uint32_t arg0); - -// A thunk that runs the original and then passes (its 32-bit result, its first argument) through `fn`, returning -// what `fn` returns: for a getter such as "the view mode of context N". Only for functions with at most four -// register arguments (a stack argument would be one slot off) and an integer result. -// Stack: rsp = 8 mod 16 at entry; one push and 0x20 bytes of shadow space make it 16-aligned for both calls. -inline uint8_t* make_result_thunk(const void* close_to, ResultFn fn, const void* original) { - if (!close_to || !fn || !original) return nullptr; - uint8_t* t = alloc_near(close_to, 4096); - if (!t) return nullptr; - uint8_t* p = t; - auto put = [&](std::initializer_list bytes) { for (uint8_t b : bytes) *p++ = b; }; - auto put64 = [&](uint64_t v) { std::memcpy(p, &v, 8); p += 8; }; - put({0x51}); // push rcx (the first argument, for fn) - put({0x48, 0x83, 0xEC, 0x20}); // sub rsp, 0x20 - put({0x48, 0xB8}); put64(reinterpret_cast(original)); // mov rax, original - put({0xFF, 0xD0}); // call rax (rcx, rdx, r8, r9 still the caller's) - put({0x48, 0x8B, 0x54, 0x24, 0x20}); // mov rdx, [rsp+0x20] (the saved first argument) - put({0x89, 0xC1}); // mov ecx, eax (the original's result) - put({0x48, 0xB8}); put64(reinterpret_cast(fn)); // mov rax, fn - put({0xFF, 0xD0}); // call rax - put({0x48, 0x83, 0xC4, 0x20}); // add rsp, 0x20 - put({0x59, 0xC3}); // pop rcx ; ret - // As above: 5-byte prolog, sub rsp,0x20 at 5, push rcx at 1. - return finish_thunk(t, p - t, {0x01, 5, 2, 0, 5, 0x32, 1, 0x02}); -} - -// Points every E8/E9 rel32 in [begin, begin + size) whose target is `target` at `thunk`. The range must be writable. -// Returns how many were rewritten. -inline std::size_t redirect_direct_branches(uint8_t* begin, std::size_t size, const uint8_t* target, - const uint8_t* thunk) { - if (!begin || !target || !thunk || size < 5) return 0; - std::size_t n = 0; - for (std::size_t i = 0; i + 5 <= size; ++i) { - if (begin[i] != 0xE8 && begin[i] != 0xE9) continue; - int32_t rel; - std::memcpy(&rel, begin + i + 1, 4); - const uint8_t* next = begin + i + 5; - const uintptr_t next_addr = reinterpret_cast(next); - const uintptr_t dst_addr = next_addr + static_cast(static_cast(rel)); - if (dst_addr != reinterpret_cast(target)) continue; - const intptr_t to = static_cast(reinterpret_cast(thunk) - next_addr); - if (to < INT32_MIN || to > INT32_MAX) continue; - const int32_t rel2 = static_cast(to); - std::memcpy(begin + i + 1, &rel2, 4); - ++n; - i += 4; - } - return n; -} - -struct HookResult { - bool ok = false; - std::size_t redirected = 0; - const char* error = ""; -}; - -// Hooks the function at `target_rva` of the mapped image at `base`: one thunk, then every direct call or jump to it -// in the image's executable sections. Runs before any image code (main.cpp), so no thread is executing the bytes. -// Validates `target_rva` as code of the mapped image at `base`, builds the thunk with `make(target)` and points the -// image's direct calls and jumps to the target at it. -template -inline HookResult redirect_image_calls(uint8_t* base, uint32_t target_rva, MakeThunk make) { - HookResult r; - if (!base) return r.error = "not a mapped PE image", r; - const auto* dos = reinterpret_cast(base); - if (dos->e_magic != IMAGE_DOS_SIGNATURE || dos->e_lfanew < static_cast(sizeof(IMAGE_DOS_HEADER))) - return r.error = "not a mapped PE image", r; - const uint64_t lfanew = static_cast(dos->e_lfanew); - const auto* nt = reinterpret_cast(base + lfanew); - if (nt->Signature != IMAGE_NT_SIGNATURE || - nt->FileHeader.SizeOfOptionalHeader < sizeof(IMAGE_OPTIONAL_HEADER64) || - nt->OptionalHeader.Magic != IMAGE_NT_OPTIONAL_HDR64_MAGIC) - return r.error = "not a mapped PE64 image", r; - const uint64_t image_size = nt->OptionalHeader.SizeOfImage; - const uint64_t sec_table_end = - lfanew + offsetof(IMAGE_NT_HEADERS64, OptionalHeader) + - static_cast(nt->FileHeader.SizeOfOptionalHeader) + - static_cast(nt->FileHeader.NumberOfSections) * sizeof(IMAGE_SECTION_HEADER); - if (image_size == 0 || sec_table_end > image_size) - return r.error = "not a mapped PE64 image", r; - if (target_rva >= image_size) return r.error = "the RVA is outside the image", r; - const IMAGE_SECTION_HEADER* sec = IMAGE_FIRST_SECTION(nt); - // Match pe_loader.cpp's effective section span (VirtualSize, falling back to SizeOfRawData when 0), clamped to SizeOfImage. - auto exec_section_span = [&](const IMAGE_SECTION_HEADER& s, uint64_t& va, uint64_t& len) -> bool { - if (!(s.Characteristics & IMAGE_SCN_MEM_EXECUTE)) return false; - va = s.VirtualAddress; - const uint64_t raw = s.Misc.VirtualSize ? static_cast(s.Misc.VirtualSize) - : static_cast(s.SizeOfRawData); - if (raw == 0 || va >= image_size) return false; - len = raw > image_size - va ? image_size - va : raw; - return len > 0; - }; - bool in_code = false; - for (unsigned i = 0; i < nt->FileHeader.NumberOfSections; ++i) { - uint64_t va = 0, len = 0; - if (exec_section_span(sec[i], va, len) && target_rva >= va && target_rva < va + len) - in_code = true; - } - if (!in_code) return r.error = "the RVA is not in an executable section", r; - uint8_t* target = base + target_rva; - uint8_t* thunk = make(target); - if (!thunk) return r.error = "no memory within 2 GiB of the image for the thunk", r; - for (unsigned i = 0; i < nt->FileHeader.NumberOfSections; ++i) { - uint64_t va = 0, len = 0; - if (!exec_section_span(sec[i], va, len)) continue; - uint8_t* begin = base + va; - const std::size_t size = static_cast(len); - DWORD old = 0; - if (!VirtualProtect(begin, size, PAGE_EXECUTE_READWRITE, &old)) { - if (r.redirected == 0) free_thunk(thunk); - return r.error = "VirtualProtect failed", r; - } - r.redirected += redirect_direct_branches(begin, size, target, thunk); - DWORD ignored = 0; - VirtualProtect(begin, size, old, &ignored); - FlushInstructionCache(GetCurrentProcess(), begin, size); - } - r.ok = true; - return r; -} - -// The argument-remapping hook (archetype lookup): argument `arg` of every direct call goes through `fn`. -inline HookResult hook_image_calls(uint8_t* base, uint32_t target_rva, RemapFn fn, int arg) { - if (!fn) return HookResult{false, 0, "hook callback is null"}; - if (arg != 0 && arg != 1) return HookResult{false, 0, "only argument 0 or 1 can be remapped"}; - return redirect_image_calls(base, target_rva, - [&](uint8_t* target) { return make_remap_thunk(target, arg, fn, target); }); -} - -// The result-override hook (view-mode getter): every direct call's result goes through `fn` with the first argument. -inline HookResult hook_image_results(uint8_t* base, uint32_t target_rva, ResultFn fn) { - if (!fn) return HookResult{false, 0, "hook callback is null"}; - return redirect_image_calls(base, target_rva, - [&](uint8_t* target) { return make_result_thunk(target, fn, target); }); -} - -} // namespace leonida::hooks diff --git a/runtime/src/command_list.h b/runtime/src/command_list.h deleted file mode 100644 index 7c5c09e0a..000000000 --- a/runtime/src/command_list.h +++ /dev/null @@ -1,954 +0,0 @@ -#pragma once - -// The command-list IR (docs/d3d12_vulkan.md section 3.2): what a D3D12 command list records, kept until -// ExecuteCommandLists replays it on Vulkan (vulkan_replay.h). This slice covers legacy and enhanced barriers and -// render-target, depth-stencil and unordered-access clears (whole views or rectangles), copies, resolves, -// predication, discards, immediate buffer writes, atomic copies, queries, debug markers and dispatches. It has -// no Windows or Vulkan dependency. - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace leonida { - -using ResourceId = std::uintptr_t; -using ClearColor = std::array; - -// D3D12 enum values from the public d3d12.h, so the IR builds without the Windows SDK. -// d3d12_state_map_test checks every one against d3d12.h on Windows. -namespace d3d12_state { -inline constexpr std::uint32_t common = 0; -inline constexpr std::uint32_t vertex_and_constant_buffer = 0x1; -inline constexpr std::uint32_t index_buffer = 0x2; -inline constexpr std::uint32_t render_target = 0x4; -inline constexpr std::uint32_t unordered_access = 0x8; -inline constexpr std::uint32_t depth_write = 0x10; -inline constexpr std::uint32_t depth_read = 0x20; -inline constexpr std::uint32_t non_pixel_shader_resource = 0x40; -inline constexpr std::uint32_t pixel_shader_resource = 0x80; -inline constexpr std::uint32_t stream_out = 0x100; -inline constexpr std::uint32_t indirect_argument = 0x200; -inline constexpr std::uint32_t predication = 0x200; // D3D12_RESOURCE_STATE_PREDICATION, the same bit -inline constexpr std::uint32_t copy_dest = 0x400; -inline constexpr std::uint32_t copy_source = 0x800; -inline constexpr std::uint32_t resolve_dest = 0x1000; -inline constexpr std::uint32_t resolve_source = 0x2000; -inline constexpr std::uint32_t raytracing_acceleration_structure = 0x400000; -inline constexpr std::uint32_t shading_rate_source = 0x1000000; -inline constexpr std::uint32_t generic_read = 0xac3; -inline constexpr std::uint32_t present = 0; -} // namespace d3d12_state - -// D3D12_BARRIER_SYNC (enhanced barriers). -namespace d3d12_sync { -inline constexpr std::uint32_t none = 0; -inline constexpr std::uint32_t all = 0x1; -inline constexpr std::uint32_t draw = 0x2; -inline constexpr std::uint32_t index_input = 0x4; -inline constexpr std::uint32_t vertex_shading = 0x8; -inline constexpr std::uint32_t pixel_shading = 0x10; -inline constexpr std::uint32_t depth_stencil = 0x20; -inline constexpr std::uint32_t render_target = 0x40; -inline constexpr std::uint32_t compute_shading = 0x80; -inline constexpr std::uint32_t raytracing = 0x100; -inline constexpr std::uint32_t copy = 0x200; -inline constexpr std::uint32_t resolve = 0x400; -inline constexpr std::uint32_t execute_indirect = 0x800; -inline constexpr std::uint32_t predication = 0x800; -inline constexpr std::uint32_t all_shading = 0x1000; -inline constexpr std::uint32_t non_pixel_shading = 0x2000; -inline constexpr std::uint32_t emit_raytracing_acceleration_structure_postbuild_info = 0x4000; -inline constexpr std::uint32_t clear_unordered_access_view = 0x8000; -inline constexpr std::uint32_t video_decode = 0x100000; -inline constexpr std::uint32_t video_process = 0x200000; -inline constexpr std::uint32_t video_encode = 0x400000; -inline constexpr std::uint32_t build_raytracing_acceleration_structure = 0x800000; -inline constexpr std::uint32_t copy_raytracing_acceleration_structure = 0x1000000; -inline constexpr std::uint32_t split = 0x80000000; -} // namespace d3d12_sync - -// D3D12_BARRIER_ACCESS. -namespace d3d12_access { -inline constexpr std::uint32_t common = 0; -inline constexpr std::uint32_t vertex_buffer = 0x1; -inline constexpr std::uint32_t constant_buffer = 0x2; -inline constexpr std::uint32_t index_buffer = 0x4; -inline constexpr std::uint32_t render_target = 0x8; -inline constexpr std::uint32_t unordered_access = 0x10; -inline constexpr std::uint32_t depth_stencil_write = 0x20; -inline constexpr std::uint32_t depth_stencil_read = 0x40; -inline constexpr std::uint32_t shader_resource = 0x80; -inline constexpr std::uint32_t stream_output = 0x100; -inline constexpr std::uint32_t indirect_argument = 0x200; -inline constexpr std::uint32_t predication = 0x200; -inline constexpr std::uint32_t copy_dest = 0x400; -inline constexpr std::uint32_t copy_source = 0x800; -inline constexpr std::uint32_t resolve_dest = 0x1000; -inline constexpr std::uint32_t resolve_source = 0x2000; -inline constexpr std::uint32_t raytracing_acceleration_structure_read = 0x4000; -inline constexpr std::uint32_t raytracing_acceleration_structure_write = 0x8000; -inline constexpr std::uint32_t shading_rate_source = 0x10000; -inline constexpr std::uint32_t video_decode_read = 0x20000; -inline constexpr std::uint32_t video_decode_write = 0x40000; -inline constexpr std::uint32_t video_process_read = 0x80000; -inline constexpr std::uint32_t video_process_write = 0x100000; -inline constexpr std::uint32_t video_encode_read = 0x200000; -inline constexpr std::uint32_t video_encode_write = 0x400000; -inline constexpr std::uint32_t no_access = 0x80000000; -} // namespace d3d12_access - -// D3D12_BARRIER_LAYOUT. -namespace d3d12_layout { -inline constexpr std::uint32_t undefined = 0xffffffff; -inline constexpr std::uint32_t common = 0; -inline constexpr std::uint32_t present = 0; -inline constexpr std::uint32_t generic_read = 1; -inline constexpr std::uint32_t render_target = 2; -inline constexpr std::uint32_t unordered_access = 3; -inline constexpr std::uint32_t depth_stencil_write = 4; -inline constexpr std::uint32_t depth_stencil_read = 5; -inline constexpr std::uint32_t shader_resource = 6; -inline constexpr std::uint32_t copy_source = 7; -inline constexpr std::uint32_t copy_dest = 8; -inline constexpr std::uint32_t resolve_source = 9; -inline constexpr std::uint32_t resolve_dest = 10; -inline constexpr std::uint32_t shading_rate_source = 11; -inline constexpr std::uint32_t video_decode_read = 12; -inline constexpr std::uint32_t video_decode_write = 13; -inline constexpr std::uint32_t video_process_read = 14; -inline constexpr std::uint32_t video_process_write = 15; -inline constexpr std::uint32_t video_encode_read = 16; -inline constexpr std::uint32_t video_encode_write = 17; -inline constexpr std::uint32_t direct_queue_common = 18; -inline constexpr std::uint32_t direct_queue_generic_read = 19; -inline constexpr std::uint32_t direct_queue_unordered_access = 20; -inline constexpr std::uint32_t direct_queue_shader_resource = 21; -inline constexpr std::uint32_t direct_queue_copy_source = 22; -inline constexpr std::uint32_t direct_queue_copy_dest = 23; -inline constexpr std::uint32_t compute_queue_common = 24; -inline constexpr std::uint32_t compute_queue_generic_read = 25; -inline constexpr std::uint32_t compute_queue_unordered_access = 26; -inline constexpr std::uint32_t compute_queue_shader_resource = 27; -inline constexpr std::uint32_t compute_queue_copy_source = 28; -inline constexpr std::uint32_t compute_queue_copy_dest = 29; -inline constexpr std::uint32_t video_queue_common = 30; -} // namespace d3d12_layout - -// D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES, D3D12_RESOURCE_BARRIER_FLAGS, D3D12_CLEAR_FLAGS and -// D3D12_TEXTURE_BARRIER_FLAGS. -inline constexpr std::uint32_t all_subresources = 0xffffffff; -inline constexpr std::uint32_t barrier_begin_only = 0x1; -inline constexpr std::uint32_t barrier_end_only = 0x2; -inline constexpr std::uint32_t clear_depth = 0x1; -inline constexpr std::uint32_t clear_stencil = 0x2; -inline constexpr std::uint32_t texture_barrier_discard = 0x1; - -// The format a color view names, as a VkFormat number (0, `resource`, is the resource's own). The named values are -// the RGBA8 family's; a typeless resource of any other family stores its view's VkFormat the same way (D3D-275). -enum class ColorViewFormat : std::uint32_t { - resource = 0, rgba8_unorm = 37, rgba8_snorm = 38, rgba8_uint = 41, rgba8_sint = 42, rgba8_srgb = 43 -}; - -// D3D12_QUERY_HEAP_TYPE and D3D12_QUERY_TYPE. -namespace d3d12_query_heap { -inline constexpr std::uint32_t occlusion = 0; -inline constexpr std::uint32_t timestamp = 1; -inline constexpr std::uint32_t pipeline_statistics = 2; -inline constexpr std::uint32_t so_statistics = 3; -inline constexpr std::uint32_t video_decode_statistics = 4; -inline constexpr std::uint32_t copy_queue_timestamp = 5; -inline constexpr std::uint32_t pipeline_statistics1 = 7; -} // namespace d3d12_query_heap - -namespace d3d12_query { -inline constexpr std::uint32_t occlusion = 0; -inline constexpr std::uint32_t binary_occlusion = 1; -inline constexpr std::uint32_t timestamp = 2; -inline constexpr std::uint32_t pipeline_statistics = 3; -inline constexpr std::uint32_t so_statistics_stream0 = 4; -inline constexpr std::uint32_t so_statistics_stream3 = 7; -inline constexpr std::uint32_t video_decode_statistics = 8; -inline constexpr std::uint32_t pipeline_statistics1 = 10; -} // namespace d3d12_query - -// A stream-output statistics query (SO_STATISTICS_STREAM0..3). -constexpr bool is_so_statistics(std::uint32_t query_type) { - return query_type >= d3d12_query::so_statistics_stream0 && query_type <= d3d12_query::so_statistics_stream3; -} - -// Whether a heap of `heap_type` holds queries of `query_type` (the D3D12 pairing rules). -constexpr bool query_fits_heap(std::uint32_t heap_type, std::uint32_t query_type) { - namespace h = d3d12_query_heap; - namespace q = d3d12_query; - switch (heap_type) { - case h::occlusion: return query_type == q::occlusion || query_type == q::binary_occlusion; - case h::timestamp: - case h::copy_queue_timestamp: return query_type == q::timestamp; - case h::pipeline_statistics: return query_type == q::pipeline_statistics; - case h::so_statistics: return query_type >= q::so_statistics_stream0 && query_type <= q::so_statistics_stream3; - case h::video_decode_statistics: return query_type == q::video_decode_statistics; - case h::pipeline_statistics1: return query_type == q::pipeline_statistics1; - default: return false; - } -} - -// Bytes one resolved query takes: a UINT64 for occlusion and timestamps, D3D12_QUERY_DATA_PIPELINE_STATISTICS -// (11 UINT64s) for pipeline statistics, D3D12_QUERY_DATA_SO_STATISTICS (2 UINT64s) for stream output. 0 for the -// types this layer does not resolve. -constexpr std::uint32_t query_result_size(std::uint32_t query_type) { - namespace q = d3d12_query; - switch (query_type) { - case q::occlusion: - case q::binary_occlusion: - case q::timestamp: return 8; - case q::pipeline_statistics: return 11 * 8; - // D3D12_QUERY_DATA_SO_STATISTICS: NumPrimitivesWritten, PrimitivesStorageNeeded. - case q::so_statistics_stream0: - case q::so_statistics_stream0 + 1: - case q::so_statistics_stream0 + 2: - case q::so_statistics_stream3: return 2 * 8; - default: return 0; - } -} - -// A view captured by value while recording: the CPU descriptor slot may be rewritten after the call. -struct TargetView { - ResourceId resource; - std::uint32_t mip; - std::uint32_t first_layer; - std::uint32_t layer_count; - ColorViewFormat format = ColorViewFormat::resource; -}; - -// D3D12_RECT: right and bottom are exclusive. -struct Rect { - std::int32_t left; - std::int32_t top; - std::int32_t right; - std::int32_t bottom; -}; - -// D3D12 subresource index: mip + layer * mips + plane * mips * layers, or all_subresources. -struct TransitionBarrier { - ResourceId resource; - std::uint32_t subresource; - std::uint32_t before; - std::uint32_t after; -}; - -// resource 0 means every UAV access, as a null pResource does in D3D12. -struct UavBarrier { - ResourceId resource; -}; - -// Either resource may be 0 ("any placed or reserved resource"). -struct AliasingBarrier { - ResourceId before; - ResourceId after; -}; - -// Enhanced barriers (ID3D12GraphicsCommandList7::Barrier). -struct GlobalBarrier { - std::uint32_t sync_before; - std::uint32_t sync_after; - std::uint32_t access_before; - std::uint32_t access_after; -}; - -// Offset and size are not kept: D3D12 requires 0 and UINT64_MAX (the whole buffer). -struct BufferBarrier { - std::uint32_t sync_before; - std::uint32_t sync_after; - std::uint32_t access_before; - std::uint32_t access_after; - ResourceId resource; -}; - -// D3D12_BARRIER_SUBRESOURCE_RANGE: mip_count == 0 means index_or_first_mip is a subresource index -// (all_subresources for every one). -struct BarrierSubresourceRange { - std::uint32_t index_or_first_mip; - std::uint32_t mip_count; - std::uint32_t first_layer; - std::uint32_t layer_count; - std::uint32_t first_plane; - std::uint32_t plane_count; -}; - -struct TextureBarrier { - std::uint32_t sync_before; - std::uint32_t sync_after; - std::uint32_t access_before; - std::uint32_t access_after; - std::uint32_t layout_before; - std::uint32_t layout_after; - ResourceId resource; - BarrierSubresourceRange range; - std::uint32_t flags; // texture_barrier_discard -}; - -// rects empty: the whole view. -// CopyBufferRegion. -struct CopyBuffer { - ResourceId dst; - std::uint64_t dst_offset; - ResourceId src; - std::uint64_t src_offset; - std::uint64_t size; - ResourceId tiled_resource = 0; // CopyTiles uses the padded size of the sparse side -}; - -// D3D12_TEXTURE_COPY_LOCATION: a texture subresource, or a placed footprint in a buffer. The footprint's format is -// not kept: the copy uses the texture's own format for the plane, which D3D12 requires to be compatible. -struct CopyLocation { - ResourceId resource; - bool footprint; - std::uint32_t subresource; // texture - std::uint64_t offset; // footprint: byte offset in the buffer - std::uint32_t width; - std::uint32_t height; - std::uint32_t depth; - std::uint32_t row_pitch; -}; - -// D3D12_BOX: right, bottom and back are exclusive. -struct CopyBox { - std::uint32_t left; - std::uint32_t top; - std::uint32_t front; - std::uint32_t right; - std::uint32_t bottom; - std::uint32_t back; -}; - -// CopyTextureRegion. Without a box, the whole source subresource or footprint is copied. -struct CopyTexture { - CopyLocation dst; - std::uint32_t x; - std::uint32_t y; - std::uint32_t z; - CopyLocation src; - bool has_box; - CopyBox box; - bool tile_footprint = false; // RGBA8 CopyTiles: rows in a linear 64 KiB tile, at any byte offset -}; - -// CopyResource: every subresource, or the whole buffer. -struct CopyResource { - ResourceId dst; - ResourceId src; -}; - -// D3D12_RESOLVE_MODE values a region resolve replays. -namespace d3d12_resolve_mode { -inline constexpr std::uint32_t minimum = 1; -inline constexpr std::uint32_t maximum = 2; -inline constexpr std::uint32_t average = 3; -} - -struct ResolveRegion { - std::uint32_t dst_x; - std::uint32_t dst_y; - std::optional src_rect; - std::uint32_t mode = d3d12_resolve_mode::average; // colour: average only; stencil: minimum or maximum -}; - -// Without a region, both subresources have the same extent. A region with no source rectangle takes the -// entire source to the given destination offset. The resolve uses the images' own format. -struct ResolveSubresource { - ResourceId dst; - std::uint32_t dst_subresource; - ResourceId src; - std::uint32_t src_subresource; - std::optional region = std::nullopt; -}; - -// Dispatch, with what it uses captured when it is recorded: the pipeline (an opaque id the replay resolves) and -// the 32 user-data dwords the root arguments produced (s0..s31 of the translated shader, section 3.5). -struct Dispatch { - std::uintptr_t pipeline; - std::array user_data; - std::uint32_t x; - std::uint32_t y; - std::uint32_t z; -}; - -// D3D12_VIEWPORT. -struct Viewport { - float x; - float y; - float width; - float height; - float min_depth; - float max_depth; -}; - -// D3D12_VERTEX_BUFFER_VIEW / D3D12_INDEX_BUFFER_VIEW: console VAs, resolved to buffers at replay. -struct VertexBufferView { - std::uint64_t va; - std::uint32_t size; - std::uint32_t stride; -}; - -struct IndexBufferView { - std::uint64_t va; - std::uint32_t size; - std::uint32_t format; // DXGI_FORMAT_R16_UINT (57) or DXGI_FORMAT_R32_UINT (42) -}; - -// The views a draw captured, at the D3D12 maxima. Kept by value because the CPU descriptor slots and the bound -// views can change after the draw is recorded, and out of line because the command variant is sized by its largest -// member: inline they made every recorded command, barriers included, 976 bytes. -struct DrawViews { - std::array render_targets{}; - std::array vertex_buffers{}; // by input slot - std::uint32_t render_target_count = 8; -}; - -// DrawInstanced / DrawIndexedInstanced / DispatchMesh, with everything they use captured when they are recorded: -// D3D12 reads render-target and depth descriptors at OMSetRenderTargets, and every other piece of state is the -// list's state at the draw. resource 0 marks an unbound render-target slot or no depth buffer. A mesh draw -// (DispatchMesh) takes its thread-group counts in count (x), instances (y) and first (z), and ignores the vertex -// and index buffers and the topology. -// Render targets and vertex buffer views are inlined (8 simultaneous targets, 32 input slots), eliminating heap allocations -// during command list recording (D3D-289). -struct Draw { - std::uintptr_t pipeline = 0; - std::array user_data{}; - std::shared_ptr views; // null: no render targets or vertex buffers captured - TargetView depth{}; - IndexBufferView index{}; - std::uint32_t topology = 0; // D3D_PRIMITIVE_TOPOLOGY - Viewport viewport{}; // the first; more viewports are not modelled yet - Rect scissor{}; // the first; D3D12 always scissors - std::array blend_factor{1, 1, 1, 1}; - std::uint32_t stencil_front = 0; - std::uint32_t stencil_back = 0; - bool indexed = false; - std::uint32_t count = 0; // vertices or indices per instance - std::uint32_t instances = 0; - std::uint32_t first = 0; // first vertex or first index - std::int32_t base_vertex = 0; - std::uint32_t first_instance = 0; - bool mesh = false; -}; - -// D3D12_TEXTURE_DATA_PITCH_ALIGNMENT and D3D12_TEXTURE_DATA_PLACEMENT_ALIGNMENT. -inline constexpr std::uint32_t texture_data_pitch_alignment = 256; -inline constexpr std::uint32_t texture_data_placement_alignment = 512; - -struct ClearRenderTarget { - TargetView target; - ClearColor color; - std::vector rects; -}; - -struct ClearDepthStencil { - TargetView target; - std::uint32_t flags; // clear_depth | clear_stencil - float depth; - std::uint8_t stencil; - std::vector rects; -}; - -// DiscardResource. whole: the whole resource (a null region); first_subresource and count are then ignored. -// Otherwise count subresources from first_subresource, an explicit range even when count is all_subresources. -// partial: the region had rectangles, so only part of each subresource is discarded. -struct DiscardResource { - ResourceId resource; - std::uint32_t first_subresource; - std::uint32_t count; - bool partial; - bool whole = false; -}; - -// D3D12_WRITEBUFFERIMMEDIATE_MODE. -namespace write_immediate_mode { -inline constexpr std::uint32_t normal = 0; // DEFAULT: ordered like any copy write -inline constexpr std::uint32_t marker_in = 1; // after every earlier command has started -inline constexpr std::uint32_t marker_out = 2; // after every earlier command has finished -} // namespace write_immediate_mode - -// One D3D12_WRITEBUFFERIMMEDIATE_PARAMETER: a 32-bit value written at a GPU virtual address. -struct WriteImmediate { - std::uint64_t address; - std::uint32_t value; - std::uint32_t mode; -}; - -// D3D12_SUBRESOURCE_RANGE_UINT64 of a dependent resource: [begin, end) in bytes of one subresource -// (end == UINT64_MAX is the D3D12 sentinel meaning through the end of the subresource). -struct DependentRange { - ResourceId resource; - std::uint32_t subresource; - std::uint64_t begin; - std::uint64_t end; -}; - -// AtomicCopyBufferUINT (bytes 4) and AtomicCopyBufferUINT64 (bytes 8). The copy runs once every earlier write to -// the dependent resources has finished. -struct AtomicCopyBuffer { - ResourceId dst; - std::uint64_t dst_offset; - ResourceId src; - std::uint64_t src_offset; - std::uint32_t bytes; - std::vector dependencies; -}; - -// What a UAV descriptor said when ClearUnorderedAccessView* was recorded (the CPU slot may be rewritten after). -// A buffer view is a byte range of the buffer and an element format; a texture view is one mip and a layer range. -struct UavView { - ResourceId resource; - bool buffer; - std::uint32_t format; // the view's VkFormat value; 0 (VK_FORMAT_UNDEFINED): a raw or structured buffer - std::uint64_t offset; // buffer: first byte of the view - std::uint64_t size; // buffer: bytes in the view - std::uint32_t element_size; // buffer: bytes an element (rects count elements), 4 for a raw view - std::uint32_t mip; // texture - std::uint32_t first_layer; - std::uint32_t layer_count; -}; - -// ClearUnorderedAccessViewUint / ...Float; the resource must be in unordered_access state at execution. values are -// the four UINTs, or the four FLOATs' bits. rects empty: the whole view. A buffer view's rects are element ranges -// [left, right) (top and bottom must cover row 0). -struct ClearUnorderedAccess { - UavView view; - bool is_float; - std::array values; - std::vector rects; -}; - -// D3D12_PREDICATION_OP. -namespace d3d12_predication { -inline constexpr std::uint32_t equal_zero = 0; // skip the predicated commands when the value is 0 -inline constexpr std::uint32_t not_equal_zero = 1; // skip them when it isn't -} // namespace d3d12_predication - -// D3D12 requires the predicate's offset to be a multiple of 8 (the value is 64 bits). -inline constexpr std::uint64_t predication_alignment = 8; - -// SetPredication. buffer 0 turns predication off. A command list starts without predication, and it does not carry -// over to the next list. -struct Predication { - ResourceId buffer; - std::uint64_t offset; - std::uint32_t op; // d3d12_predication -}; - -// Query heaps are identified like resources, by the COM object's pointer value. A heap's type and size are checked -// at replay, when the heap is known. -using QueryHeapId = std::uintptr_t; - -// BeginQuery: occlusion and pipeline statistics only (D3D12 has no Begin for timestamps). -struct BeginQuery { - QueryHeapId heap; - std::uint32_t type; - std::uint32_t index; -}; - -// EndQuery; for a timestamp, the time at which every earlier command has finished. -struct EndQuery { - QueryHeapId heap; - std::uint32_t type; - std::uint32_t index; -}; - -// ResolveQueryData: `count` results from `first` on, written to the buffer `dst` at `offset`. -struct ResolveQueries { - QueryHeapId heap; - std::uint32_t type; - std::uint32_t first; - std::uint32_t count; - ResourceId dst; - std::uint64_t offset; -}; - -// SetMarker, BeginEvent and EndEvent, replayed as VK_EXT_debug_utils labels when the device has them (and skipped -// when it does not). The label is UTF-8; an end has none. -struct DebugMarker { - enum class Kind : std::uint8_t { set, begin, end }; - Kind kind; - std::string label; -}; - -// ExecuteIndirect argument kind (from ID3D12CommandSignature). -enum class IndirectKind : std::uint8_t { - draw = 0, - draw_indexed = 1, - dispatch = 2, -}; - -struct ExecuteIndirect { - IndirectKind kind = IndirectKind::draw; - std::uint32_t stride = 0; - std::uint32_t max_count = 0; - ResourceId argument_buffer = 0; - std::uint64_t argument_offset = 0; - ResourceId count_buffer = 0; // 0: fixed max_count; non-zero: vkCmdDraw*IndirectCount - std::uint64_t count_offset = 0; - // kind == dispatch: the compute pipeline and root arguments in effect, as Dispatch records them, so the dispatches - // run that pipeline with those arguments whatever the command buffer had bound. A pipeline of 0 leaves the binding - // as it is. - std::uintptr_t pipeline = 0; - std::array user_data{}; -}; - -// Triangle geometry descriptor for a BLAS build (ID3D12GraphicsCommandList4::BuildRaytracingAccelerationStructure). -struct RtTriangleGeometry { - std::uint64_t vertex_va = 0; - std::uint32_t vertex_count = 0; - std::uint32_t vertex_stride = 0; - std::uint32_t vertex_format = 0; // VkFormat (e.g. VK_FORMAT_R32G32B32_SFLOAT) - std::uint64_t index_va = 0; - std::uint32_t index_count = 0; - std::uint32_t index_type = 0; // 0=NONE, 1=UINT16, 2=UINT32 - std::uint64_t transform_va = 0; - bool opaque = true; - std::uint32_t flags = 0; // D3D12_RAYTRACING_GEOMETRY_FLAGS (bit 0 opaque, bit 1 no duplicate any-hit) -}; - -// BLAS or TLAS build command (VK_KHR_acceleration_structure). -struct BuildAccelerationStructure { - bool is_tlas = false; - bool update = false; - std::uint32_t build_flags = 0; - std::uint64_t dst_va = 0; - std::uint64_t src_va = 0; - std::uint64_t scratch_va = 0; - std::uint64_t instances_va = 0; - std::uint32_t instance_count = 0; - // D3D12_ELEMENTS_LAYOUT_ARRAY_OF_POINTERS: instances_va is an array of instance_count GPU virtual addresses, one - // per 64-byte D3D12_RAYTRACING_INSTANCE_DESC; otherwise the descs themselves, consecutively. - bool instance_pointers = false; - std::vector triangles; -}; - -// CopyRaytracingAccelerationStructure. `mode` is D3D12_RAYTRACING_ACCELERATION_STRUCTURE_COPY_MODE; replay supports -// CLONE (0) and COMPACT (1) for XDXR structures. -struct CopyAccelerationStructure { - std::uint64_t dst_va = 0; - std::uint64_t src_va = 0; - std::uint32_t mode = 0; -}; - -// EmitRaytracingAccelerationStructurePostbuildInfo, and each postbuild desc of BuildRaytracingAccelerationStructure: -// one value per source, consecutively from `dest_va`. `type` is D3D12_RAYTRACING_ACCELERATION_STRUCTURE_POSTBUILD_INFO_TYPE; -// replay supports COMPACTED_SIZE (0) and CURRENT_SIZE (3), 8 bytes each. -struct AccelerationStructurePostbuild { - std::uint64_t dest_va = 0; - std::uint32_t type = 0; - std::vector sources; -}; - -using Command = std::variant; - -class CommandList { -public: - // D3D12 split barriers: the begin half only marks the resource unusable until the end half, so the transition - // is recorded once, at the end. A full barrier (flags 0) is recorded where it is issued. - bool transition(const TransitionBarrier& barrier, std::uint32_t flags = 0) { - if (closed_ || !barrier.resource) return false; - if (flags & ~(barrier_begin_only | barrier_end_only)) return false; - if (flags == (barrier_begin_only | barrier_end_only)) return false; - if (flags & barrier_begin_only) return true; - commands_.push_back(barrier); - return true; - } - - bool uav_barrier(const UavBarrier& barrier) { return append(barrier); } - bool aliasing_barrier(const AliasingBarrier& barrier) { return append(barrier); } - - // Enhanced split barriers follow the same rule: the half with sync_after == split is dropped, and the half with - // sync_before == split is replayed as a full barrier. - bool barrier(const GlobalBarrier& barrier) { - if (!valid_sync(barrier.sync_before, barrier.sync_after)) return false; - if (barrier.sync_after == d3d12_sync::split) return !closed_; - return append(barrier); - } - - bool barrier(const BufferBarrier& barrier) { - if (!barrier.resource || !valid_sync(barrier.sync_before, barrier.sync_after)) return false; - if (barrier.sync_after == d3d12_sync::split) return !closed_; - return append(barrier); - } - - bool barrier(const TextureBarrier& barrier) { - if (!barrier.resource || !valid_sync(barrier.sync_before, barrier.sync_after)) return false; - if (barrier.layout_after == d3d12_layout::undefined && barrier.layout_before != d3d12_layout::undefined) - return false; - if (barrier.flags & ~texture_barrier_discard) return false; - if (barrier.range.mip_count && (!barrier.range.layer_count || !barrier.range.plane_count)) return false; - if (barrier.sync_after == d3d12_sync::split) return !closed_; - return append(barrier); - } - - // Copies. The rules D3D12 states for the call itself are checked here; ranges against the resources are - // checked at replay, when the resources are known. - bool copy_buffer(const CopyBuffer& copy) { - if (!copy.dst || !copy.src) return false; - if (!copy.size) return !closed_; // Native D3D12 accepts a zero-byte CopyBufferRegion as a no-op. - return append(copy); - } - - bool copy_texture(const CopyTexture& copy) { - const auto alignment = copy.tile_footprint ? 1u : texture_data_placement_alignment; - if (!valid(copy.dst, alignment) || !valid(copy.src, alignment) || (copy.dst.footprint && copy.src.footprint)) - return false; - if (copy.has_box && (copy.box.right <= copy.box.left || copy.box.bottom <= copy.box.top || - copy.box.back <= copy.box.front)) - return !closed_; // D3D12 accepts empty/inverted source boxes; emit no zero-extent Vulkan region. - return append(copy); - } - - bool copy_resource(const CopyResource& copy) { - if (!copy.dst || !copy.src) return false; - if (copy.dst == copy.src) return !closed_; // A self-copy is a legal no-op, not a failed command list. - return append(copy); - } - - // A resource has one sample count, so it cannot be resolved into itself. - bool resolve_subresource(const ResolveSubresource& resolve) { - if (!resolve.dst || !resolve.src || resolve.dst == resolve.src) return false; - if (const auto& region = resolve.region) { - if (region->dst_x > INT32_MAX || region->dst_y > INT32_MAX) return false; - if (region->mode < d3d12_resolve_mode::minimum || region->mode > d3d12_resolve_mode::average) return false; - if (const auto& r = region->src_rect; - r && (r->left < 0 || r->top < 0 || r->right <= r->left || r->bottom <= r->top)) - return false; - } - return append(resolve); - } - - // A dispatch with no groups does nothing in D3D12, and is not recorded. - bool dispatch(const Dispatch& dispatch) { - if (!dispatch.pipeline) return false; - if (!dispatch.x || !dispatch.y || !dispatch.z) return !closed_; - return append(dispatch); - } - - // A draw with no vertices or instances, or a mesh draw with no thread groups, does nothing in D3D12, and is - // not recorded. - bool draw(const Draw& draw) { - if (!draw.pipeline) return false; - if (!draw.count || !draw.instances || (draw.mesh && !draw.first)) return !closed_; - return append(draw); - } - bool draw(Draw&& draw) { - if (!draw.pipeline) return false; - if (!draw.count || !draw.instances) return !closed_; - return append(std::move(draw)); - } - - // ClearRenderTargetView; the resource must be in render_target state at execution. No rects: the whole view. - bool clear_render_target(const TargetView& target, const ClearColor& color, std::span rects = {}) { - if (!valid(target)) return false; - return append(ClearRenderTarget{target, color, {rects.begin(), rects.end()}}); - } - - // ClearDepthStencilView; the cleared planes must be in depth_write state at execution. - // A D32_FLOAT target keeps the depth exactly as given, outside [0, 1] and NaN included (measured on WARP, - // d3d12_clear_test); a D16 target quantizes it at replay. Flags that name no plane close the list and clear nothing. - bool clear_depth_stencil(const TargetView& target, std::uint32_t flags, float depth, std::uint8_t stencil, - std::span rects = {}) { - if (!valid(target)) return false; - if (flags & ~(clear_depth | clear_stencil)) return false; - if (!flags) return !closed_; - return append(ClearDepthStencil{target, flags, depth, stencil, {rects.begin(), rects.end()}}); - } - - // DiscardResource: a count of 0 discards nothing, as in D3D12. An explicit range must end before - // all_subresources, the largest index plus one; whether it fits the resource is checked at replay. - bool discard(const DiscardResource& discard) { - if (!discard.resource) return false; - if (discard.whole) return append(DiscardResource{discard.resource, 0, 0, discard.partial, true}); - if (discard.count == 0) return !closed_; - if (std::uint64_t(discard.first_subresource) + discard.count > all_subresources) return false; - return append(discard); - } - - // WriteBufferImmediate: D3D12 requires a 4-byte aligned, non-null address and one of the three modes. - bool write_immediate(const WriteImmediate& write) { - if (!write.address || write.address % 4 || write.mode > write_immediate_mode::marker_out) return false; - return append(write); - } - - // AtomicCopyBufferUINT/UINT64: both offsets aligned to the copy's size and each dependency on a named resource with - // a non-empty, non-inverted range (zero dependencies is accepted by the Windows 11 WARP and RTX 5090 D3D12 - // runtimes). A copy of a value onto itself (vkCmdCopyBuffer forbids the overlap) is refused too. - bool atomic_copy(const AtomicCopyBuffer& copy) { - if ((copy.bytes != 4 && copy.bytes != 8) || !copy.dst || !copy.src) return false; - if (copy.dst == copy.src && copy.dst_offset == copy.src_offset) return false; - if (copy.dst_offset % copy.bytes || copy.src_offset % copy.bytes) return false; - for (const auto& d : copy.dependencies) - if (!d.resource || d.begin >= d.end) return false; - return append(copy); - } - - // A view of nothing (no resource, an empty buffer range or no layers) is invalid, as is a rectangle that is - // inside out. Ranges against the resource are checked at replay. - bool clear_unordered_access(const UavView& view, bool is_float, const std::array& values, - std::span rects = {}) { - if (!view.resource) return false; - if (view.buffer ? (!view.size || !view.element_size) : !view.layer_count) return false; - for (const Rect& r : rects) - if (r.right < r.left || r.bottom < r.top) return false; - return append(ClearUnorderedAccess{view, is_float, values, {rects.begin(), rects.end()}}); - } - - // ExecuteBundle copies the closed bundle's commands [first, last) at the call site. The COM layer validates D3D12 - // list types and bundle-only restrictions before calling this method, and calls it once per stretch between the - // bundle's deferred state calls and draws (d3d12_com.cpp, GraphicsCommandList::ExecuteBundle). - bool execute_bundle(const CommandList& bundle, std::size_t first = 0, std::size_t last = std::size_t(-1)) { - if (this == &bundle || closed_ || !bundle.closed_) return false; - last = std::min(last, bundle.commands_.size()); - if (first < last) - commands_.insert(commands_.end(), bundle.commands_.begin() + std::ptrdiff_t(first), - bundle.commands_.begin() + std::ptrdiff_t(last)); - return true; - } - - // SetPredication. Turning it off ignores the offset and op, as D3D12 does. - bool set_predication(const Predication& predication) { - if (!predication.buffer) return append(Predication{0, 0, 0}); - if (predication.op != d3d12_predication::equal_zero && predication.op != d3d12_predication::not_equal_zero) - return false; - if (predication.offset % predication_alignment) return false; - return append(predication); - } - - // Queries. D3D12 rules for the calls themselves: timestamps have only an EndQuery; any other query is begun and - // ended in the same list, with the same type, and is not begun again while it is running. - bool begin_query(const BeginQuery& query) { - if (closed_ || !query.heap || query.type == d3d12_query::timestamp) return false; - if (find_active(query.heap, query.index) != active_.end()) return false; - active_.push_back(query); - return append(query); - } - - bool end_query(const EndQuery& query) { - if (closed_ || !query.heap) return false; - if (query.type != d3d12_query::timestamp) { - const auto it = find_active(query.heap, query.index); - if (it == active_.end() || it->type != query.type) return false; - active_.erase(it); - } - return append(query); - } - - // The offset is a multiple of 8, as D3D12 requires. A resolve of no queries records nothing. - bool resolve_queries(const ResolveQueries& resolve) { - if (closed_ || !resolve.heap || !resolve.dst || resolve.offset % 8) return false; - if (resolve.count > ~std::uint32_t(0) - resolve.first) return false; - for (const BeginQuery& running : active_) - if (running.heap == resolve.heap && running.index - resolve.first < resolve.count) return false; - return resolve.count ? append(resolve) : true; - } - - // A query begun and not ended. Such a list still closes (D3D12's Close reports the error), but is not replayed. - bool queries_open() const { return !active_.empty(); } - - // Debug markers. D3D12 does not ask a list to balance its events (one list may end what another began), so - // they are recorded as given; the replay balances them per submission (vulkan_replay.h, emit). - bool marker(DebugMarker::Kind kind, std::string label = {}) { - if (kind == DebugMarker::Kind::end) label.clear(); - return append(DebugMarker{kind, std::move(label)}); - } - - bool execute_indirect(const ExecuteIndirect& indirect) { - if (!indirect.argument_buffer || !indirect.stride || indirect.stride % 4) return false; - if (indirect.argument_offset % 4) return false; - if (!indirect.count_buffer && indirect.count_offset) return false; - if (indirect.count_buffer && indirect.count_offset % 4) return false; - if (!indirect.max_count) return !closed_; // the PC runtime takes MaxCommandCount 0 as a no-op - return append(indirect); - } - - // D3D12: acceleration structures and build scratch are 256-byte aligned; postbuild destinations 8-byte aligned. - bool build_acceleration_structure(BuildAccelerationStructure build) { - if (!build.dst_va || build.dst_va % 256 || !build.scratch_va || build.scratch_va % 256) return false; - if (build.update && (!build.src_va || build.src_va % 256)) return false; - return append(std::move(build)); - } - bool copy_acceleration_structure(CopyAccelerationStructure copy) { - if (!copy.dst_va || !copy.src_va || copy.dst_va % 256 || copy.src_va % 256 || copy.mode > 4) return false; - return append(copy); - } - bool acceleration_structure_postbuild(AccelerationStructurePostbuild info) { - if (!info.dest_va || info.dest_va % 8 || info.type > 3 || info.sources.empty()) return false; - for (const auto va : info.sources) - if (!va || va % 256) return false; - return append(std::move(info)); - } - bool close() { - if (closed_) return false; - closed_ = true; - return true; - } - - bool reset() { - if (!closed_) return false; - commands_.clear(); - active_.clear(); - closed_ = false; - return true; - } - - bool closed() const { return closed_; } - std::span commands() const { return commands_; } - -private: - static bool valid(const TargetView& target) { return target.resource && target.layer_count; } - - // A placed footprint needs aligned offsets and pitches and a non-empty size. - static bool valid(const CopyLocation& location, std::uint32_t alignment) { - if (!location.resource) return false; - if (!location.footprint) return true; - return location.width && location.height && location.depth && location.row_pitch && - location.offset % alignment == 0 && - location.row_pitch % texture_data_pitch_alignment == 0; - } - - // A split begin and end cannot be the same barrier. - static bool valid_sync(std::uint32_t before, std::uint32_t after) { - return !(before == d3d12_sync::split && after == d3d12_sync::split); - } - - bool append(const Command& command) { - if (closed_) return false; - commands_.push_back(command); - return true; - } - // The recording calls pass a temporary: moved, so a command's rectangles are not copied a second time. - bool append(Command&& command) { - if (closed_) return false; - commands_.push_back(std::move(command)); - return true; - } - - std::vector::iterator find_active(QueryHeapId heap, std::uint32_t index) { - return std::find_if(active_.begin(), active_.end(), - [&](const BeginQuery& q) { return q.heap == heap && q.index == index; }); - } - - std::vector commands_; - std::vector active_; // queries begun and not yet ended - bool closed_ = false; -}; - -} // namespace leonida diff --git a/runtime/src/conservative_raster.h b/runtime/src/conservative_raster.h deleted file mode 100644 index 469066d17..000000000 --- a/runtime/src/conservative_raster.h +++ /dev/null @@ -1,49 +0,0 @@ -#pragma once -#include -#include -#include -#include - -namespace leonida::conservative_raster { -// Tier 1 bounds the outer uncertainty to half a pixel and requires a 16.8 rasterization grid. Leave room for -// half a grid step at that minimum precision in addition to Vulkan's fixed primitive overestimation. Do not -// infer Tier 3 from degenerate-triangle support: InnerCoverage also needs an explicit shader ABI opt-in. -inline bool tier1(bool extension_enabled, std::uint32_t subpixel_bits, float overestimate) { - constexpr float maximum = 0.5f - 1.0f / 512.0f; - return extension_enabled && subpixel_bits >= 8 && std::isfinite(overestimate) && - overestimate >= 0.0f && overestimate <= maximum; -} -inline std::uint32_t tier(bool extension_enabled, std::uint32_t subpixel_bits, float overestimate, - bool degenerate_triangles, bool fully_covered = false, bool inner_coverage_abi = false) { - if (!tier1(extension_enabled, subpixel_bits, overestimate)) return 0; - // Tier 2 allows 1/256 pixel total uncertainty and requires post-snap degenerates. Reserve half of the - // device's actual raster grid step, conservatively capped at float's useful precision, for snapping. - const float snap = std::ldexp(0.5f, -int(std::min(subpixel_bits, 24u))); - if (!degenerate_triangles || overestimate > 1.0f / 256.0f - snap) return 1; - // The physical property alone does not establish the guest shader-input ABI. Caller-owned libraries can - // opt in once their InnerCoverage input is lowered to FullyCoveredEXT; the standalone device does not. - return fully_covered && inner_coverage_abi ? 3u : 2u; -} - -struct InnerCoverageRequirements { - bool valid = false; - bool fully_covered = false; - bool post_depth = false; -}; - -// Inspect the actual module, not optional index metadata, before vkCreateShaderModule. Every valid use of -// FullyCoveredEXT requires FragmentFullyCoveredEXT; PostDepthCoverage has an additional device property. -inline InnerCoverageRequirements inner_coverage_requirements(std::span words) { - InnerCoverageRequirements result; - if (words.size() < 5 || words[0] != 0x07230203) return result; - for (std::size_t i = 5; i < words.size();) { - const auto count = words[i] >> 16, op = words[i] & 0xffff; - if (!count || count > words.size() - i) return result; - if (op == 17 && count >= 2 && words[i + 1] == 5265) result.fully_covered = true; - if (op == 16 && count >= 3 && words[i + 2] == 4446) result.post_depth = true; - i += count; - } - result.valid = true; - return result; -} -} // namespace leonida::conservative_raster diff --git a/runtime/src/cpu_emulation.h b/runtime/src/cpu_emulation.h deleted file mode 100644 index 46950103e..000000000 --- a/runtime/src/cpu_emulation.h +++ /dev/null @@ -1,310 +0,0 @@ -// Emulates the few Zen 2 instructions in the game's code that a desktop CPU may lack (docs/cpu_features.md). -// -// The executable is built for the console's AMD Zen 2 and uses some of its instructions without asking CPUID: -// SSE4a INSERTQ/EXTRQ, CLZERO and MONITORX/MWAITX (AMD only) and CLWB (Intel since Ice Lake). On a host without -// one, the CPU raises #UD (STATUS_ILLEGAL_INSTRUCTION) at that instruction. A vectored handler recognises these -// encodings at the faulting RIP, does the same work on the thread's CONTEXT and continues after the instruction. -// On a host that has the feature the CPU runs the instruction itself and the handler never sees it. -// -// What each one does, from the AMD64 Architecture Programmer's Manual (vol. 3 for CLZERO, MONITORX, MWAITX; vol. 4 -// for INSERTQ, EXTRQ) and the Intel SDM vol. 2 for CLWB: -// INSERTQ xmm1, xmm2, len, idx F2 0F 78 /r ib ib insert the low `len` bits of xmm2[63:0] into xmm1[63:0] at -// bit `idx` (len 0 means 64) -// INSERTQ xmm1, xmm2 F2 0F 79 /r same, len = xmm2[69:64], idx = xmm2[77:72] -// EXTRQ xmm1, len, idx 66 0F 78 /0 ib ib xmm1[63:0] = (xmm1[63:0] >> idx), `len` bits, zero-extended -// EXTRQ xmm1, xmm2 66 0F 79 /r same, len = xmm2[5:0], idx = xmm2[13:8] -// CLZERO 0F 01 FC zero the 64-byte cache line that rAX points into; a line -// it cannot write raises that write fault, as the CPU does -// MONITORX 0F 01 FA arm an address monitor: a hint, nothing to do here -// MWAITX 0F 01 FB wait for the monitor or a timer; returning at once is one -// of the exits the manual allows, so it is a pause -// CLWB m8 66 0F AE /6 (mem) write a line back, keeping it cached: ordinary write-back -// memory is coherent, so there is nothing to do here -// The APM leaves xmm1[127:64] undefined after INSERTQ and EXTRQ; a Zen 3 zeroes it in all four forms (measured in -// #7111's review), so the emulation does too. A field with len + idx > 64 is undefined as well; the emulation keeps -// the bits that fit, which matched that Zen 3 on every len/idx pair. -#pragma once - -#include -#include -#include - -namespace rt::cpu_emulation { - -enum class Op { none, insertq_imm, insertq_reg, extrq_imm, extrq_reg, clzero, monitorx, mwaitx, clwb }; - -struct Decoded { - Op op = Op::none; - std::size_t length = 0; // bytes, prefixes included - int dst = 0; // xmm register (INSERTQ, EXTRQ) - int src = 0; // xmm register (the register forms) - uint8_t len = 0; // field length and index of the immediate forms - uint8_t idx = 0; - bool addr32 = false; // a 67 prefix: CLZERO uses EAX -}; - -// One of the encodings above at `code` (`avail` readable bytes), or Op::none. -inline Decoded decode(const uint8_t* code, std::size_t avail) { - Decoded d; - std::size_t i = 0; - bool p66 = false, pf2 = false, pf3 = false; - uint8_t rex = 0; - // Legacy prefixes and REX bytes in any order; only a REX right before the opcode counts, an earlier one is - // ignored (as AMD CPUs do: `48 66 0F 01 FC` and `48 48 0F 01 FC` are CLZERO). LOCK (F0) ends the scan: #UD. - for (; i < avail && i < 14; ++i) { - const uint8_t b = code[i]; - if ((b & 0xF0) == 0x40) { rex = b; continue; } - if (b == 0x66) p66 = true; - else if (b == 0xF2) pf2 = true; - else if (b == 0xF3) pf3 = true; - else if (b == 0x67) d.addr32 = true; - else if (b == 0x2E || b == 0x3E || b == 0x26 || b == 0x36 || b == 0x64 || b == 0x65) {} - else break; - rex = 0; - } - if (i + 2 > avail || code[i] != 0x0F) return {}; - const uint8_t op = code[i + 1]; - i += 2; - if (op == 0x01) { // CLZERO, MONITORX, MWAITX - if (i >= avail) return {}; - const uint8_t m = code[i++]; - // AMD CPUs run CLZERO with 66, F2 or F3 in front (measured on Zen 3 in #7055's reviews). For FA/FB an F3 - // selects another instruction (F3 0F 01 FA is MCOMMIT), so those stay #UD with F2/F3. - if ((pf2 || pf3) && m != 0xFC) return {}; - d.op = m == 0xFC ? Op::clzero : m == 0xFA ? Op::monitorx : m == 0xFB ? Op::mwaitx : Op::none; - d.length = i; - return d.op == Op::none ? Decoded{} : d; - } - if (i >= avail) return {}; - const uint8_t modrm = code[i++]; - const int mod = modrm >> 6, reg = ((modrm >> 3) & 7) | ((rex & 4) << 1), rm = (modrm & 7) | ((rex & 1) << 3); - if (op == 0x78 || op == 0x79) { // SSE4a; F2 is INSERTQ, 66 is EXTRQ; both need a register operand - if (mod != 3 || pf3 || p66 == pf2) return {}; - const bool imm = op == 0x78; - if (imm) { - if (i + 2 > avail) return {}; - if (p66 && (modrm & 0x38)) return {}; // EXTRQ's immediate form is /0 - d.len = code[i] & 0x3F; - d.idx = code[i + 1] & 0x3F; - i += 2; - } - d.op = pf2 ? (imm ? Op::insertq_imm : Op::insertq_reg) : (imm ? Op::extrq_imm : Op::extrq_reg); - if (p66 && imm) d.dst = rm; // EXTRQ xmm1, imm, imm names xmm1 in r/m - else d.dst = reg, d.src = rm; - d.length = i; - return d; - } - if (op == 0xAE && p66 && !pf2 && !pf3 && mod != 3 && ((modrm >> 3) & 7) == 6) { // CLWB m8 - if ((modrm & 7) == 4) { // SIB - if (i >= avail) return {}; - const uint8_t sib = code[i++]; - if (mod == 0 && (sib & 7) == 5) i += 4; - } else if (mod == 0 && (modrm & 7) == 5) { - i += 4; // RIP-relative - } - i += mod == 1 ? 1 : mod == 2 ? 4 : 0; - if (i > avail) return {}; - d.op = Op::clwb; - d.length = i; - return d; - } - return {}; -} - -inline uint64_t field_mask(unsigned len) { return len >= 64 ? ~uint64_t(0) : (uint64_t(1) << len) - 1; } - -// INSERTQ on the low quadword: `len` (0 means 64) bits of `src` placed at bit `idx` of `dst`. -inline uint64_t insert_bits(uint64_t dst, uint64_t src, unsigned len, unsigned idx) { - len &= 63; - idx &= 63; - const uint64_t mask = field_mask(len ? len : 64) << idx; - return (dst & ~mask) | ((src << idx) & mask); -} - -// EXTRQ on the low quadword: `len` (0 means 64) bits of `src` from bit `idx`, zero-extended. -inline uint64_t extract_bits(uint64_t src, unsigned len, unsigned idx) { - len &= 63; - idx &= 63; - return (src >> idx) & field_mask(len ? len : 64); -} - -} // namespace rt::cpu_emulation - -#ifdef _WIN32 -#include -#include - -#include -#include - -#include "../core/log.h" - -namespace rt::cpu_emulation { - -struct Host { - bool sse4a = false, monitorx = false, clzero = false, clwb = false; -}; - -inline Host detect_host() { - Host h; - int r[4]; - __cpuid(r, 0); - const int max_leaf = r[0]; - if (max_leaf >= 7) { - __cpuidex(r, 7, 0); - h.clwb = (r[1] >> 24) & 1; // EBX bit 24 - } - __cpuid(r, 0x80000000); - const unsigned max_ext = unsigned(r[0]); - if (max_ext >= 0x80000001) { - __cpuid(r, 0x80000001); - h.sse4a = (r[2] >> 6) & 1; // ECX bit 6 - h.monitorx = (r[2] >> 29) & 1; // ECX bit 29 - } - if (max_ext >= 0x80000008) { - __cpuid(r, 0x80000008); - h.clzero = r[1] & 1; // EBX bit 0 - } - return h; -} - -inline const char* name(Op op) { - switch (op) { - case Op::insertq_imm: case Op::insertq_reg: return "INSERTQ (SSE4a)"; - case Op::extrq_imm: case Op::extrq_reg: return "EXTRQ (SSE4a)"; - case Op::clzero: return "CLZERO"; - case Op::monitorx: return "MONITORX"; - case Op::mwaitx: return "MWAITX"; - case Op::clwb: return "CLWB"; - default: return "none"; - } -} - -// How many times each instruction was emulated; the two forms of INSERTQ and of EXTRQ share one count. -inline std::atomic& count(Op op) { - static std::atomic counts[9]; - if (op == Op::insertq_reg) op = Op::insertq_imm; - if (op == Op::extrq_reg) op = Op::extrq_imm; - return counts[int(op)]; -} - -// 0 when the page holding `addr` can be written; otherwise the exception a write raises there. A guard page loses -// its guard on that first touch and reports STATUS_GUARD_PAGE_VIOLATION, as the system does for a real access. -inline DWORD writable(uint64_t addr) { - MEMORY_BASIC_INFORMATION mbi; - if (!VirtualQuery(reinterpret_cast(addr), &mbi, sizeof mbi) || mbi.State != MEM_COMMIT) - return DWORD(STATUS_ACCESS_VIOLATION); - if (mbi.Protect & PAGE_GUARD) { - DWORD old = 0; - VirtualProtect(reinterpret_cast(addr & ~uint64_t(0xFFF)), 1, mbi.Protect & ~DWORD(PAGE_GUARD), &old); - return DWORD(STATUS_GUARD_PAGE_VIOLATION); - } - const DWORD p = mbi.Protect & 0xFF; - const bool ok = p == PAGE_READWRITE || p == PAGE_WRITECOPY || p == PAGE_EXECUTE_READWRITE || - p == PAGE_EXECUTE_WRITECOPY; - return ok ? 0 : DWORD(STATUS_ACCESS_VIOLATION); -} - -// How many of the `want` bytes at `addr` can be read, by page protection (no fault is taken to find out). -inline std::size_t readable(uint64_t addr, std::size_t want) { - std::size_t got = 0; - while (got < want) { - MEMORY_BASIC_INFORMATION mbi; - if (!VirtualQuery(reinterpret_cast(addr + got), &mbi, sizeof mbi) || mbi.State != MEM_COMMIT || - (mbi.Protect & (PAGE_GUARD | PAGE_NOACCESS)) || !mbi.Protect) - break; - const uint64_t end = reinterpret_cast(mbi.BaseAddress) + mbi.RegionSize; - got += std::size_t(end - (addr + got)) < want - got ? std::size_t(end - (addr + got)) : want - got; - } - return got; -} - -inline uint64_t& lo(CONTEXT* c, int r) { return c->FltSave.XmmRegisters[r].Low; } -inline uint64_t hi(const CONTEXT* c, int r) { return uint64_t(c->FltSave.XmmRegisters[r].High); } - -// Apply one decoded instruction to `c` and step past it. False when the line CLZERO zeroes cannot be written; then -// `fault`, when given, receives the exception the write raised (STATUS_ACCESS_VIOLATION with the write flag and the -// line's address, or STATUS_GUARD_PAGE_VIOLATION, as the real instruction would raise) and `c` is unchanged. -inline bool apply(const Decoded& d, CONTEXT* c, EXCEPTION_RECORD* fault = nullptr) { - switch (d.op) { - case Op::insertq_imm: - lo(c, d.dst) = insert_bits(lo(c, d.dst), lo(c, d.src), d.len, d.idx); - c->FltSave.XmmRegisters[d.dst].High = 0; - break; - case Op::insertq_reg: { - const uint64_t ctl = hi(c, d.src); - lo(c, d.dst) = insert_bits(lo(c, d.dst), lo(c, d.src), unsigned(ctl) & 63, unsigned(ctl >> 8) & 63); - c->FltSave.XmmRegisters[d.dst].High = 0; - break; - } - case Op::extrq_imm: - lo(c, d.dst) = extract_bits(lo(c, d.dst), d.len, d.idx); - c->FltSave.XmmRegisters[d.dst].High = 0; - break; - case Op::extrq_reg: { - const uint64_t ctl = lo(c, d.src); - lo(c, d.dst) = extract_bits(lo(c, d.dst), unsigned(ctl) & 63, unsigned(ctl >> 8) & 63); - c->FltSave.XmmRegisters[d.dst].High = 0; - break; - } - case Op::clzero: { - const uint64_t addr = (d.addr32 ? (c->Rax & 0xFFFFFFFFu) : c->Rax) & ~uint64_t(63); - // The line's page is checked first instead of catching a fault from the write: a compiler may turn the - // write into inline stores that a local __try does not cover (clang-cl without /EHa). A 64-byte aligned - // line never spans two pages, so one query answers for all of it. - const DWORD code = writable(addr); - if (code) { - if (fault) { - std::memset(fault, 0, sizeof *fault); - fault->ExceptionCode = code; - fault->NumberParameters = 2; - fault->ExceptionInformation[0] = 1; // a write - fault->ExceptionInformation[1] = ULONG_PTR(addr); - } - return false; - } - std::memset(reinterpret_cast(addr), 0, 64); - break; - } - case Op::mwaitx: YieldProcessor(); break; - case Op::monitorx: case Op::clwb: break; - default: return false; - } - c->Rip += d.length; - return true; -} - -inline LONG CALLBACK handler(EXCEPTION_POINTERS* info) { - if (info->ExceptionRecord->ExceptionCode != STATUS_ILLEGAL_INSTRUCTION) return EXCEPTION_CONTINUE_SEARCH; - CONTEXT* c = info->ContextRecord; - uint8_t code[15] = {}; - const std::size_t avail = readable(c->Rip, sizeof code); // the instruction may end at a page boundary - std::memcpy(code, reinterpret_cast(c->Rip), avail); - const Decoded d = decode(code, avail); - if (d.op == Op::none) return EXCEPTION_CONTINUE_SEARCH; - EXCEPTION_RECORD fault; - if (!apply(d, c, &fault)) { - // CLZERO on a line it cannot write: the CPU would raise that fault at this instruction, so the next handlers - // see it instead of the #UD (RIP still points at the instruction). - EXCEPTION_RECORD* r = info->ExceptionRecord; - r->ExceptionCode = fault.ExceptionCode; - r->ExceptionFlags = 0; - r->NumberParameters = fault.NumberParameters; - r->ExceptionInformation[0] = fault.ExceptionInformation[0]; - r->ExceptionInformation[1] = fault.ExceptionInformation[1]; - return EXCEPTION_CONTINUE_SEARCH; - } - if (count(d.op).fetch_add(1, std::memory_order_relaxed) == 0) - RT_LOG_WARN("cpu: this CPU has no %s; emulating it (first at %p)\n", name(d.op), - reinterpret_cast(c->Rip - d.length)); - return EXCEPTION_CONTINUE_EXECUTION; -} - -// Installs the handler first in the vectored chain, once. Returns false if Windows refused it. -inline bool install() { - static void* const cookie = AddVectoredExceptionHandler(1, &handler); - return cookie != nullptr; -} - -} // namespace rt::cpu_emulation -#endif diff --git a/runtime/src/crt_timed_wait.cpp b/runtime/src/crt_timed_wait.cpp deleted file mode 100644 index 6441f2868..000000000 --- a/runtime/src/crt_timed_wait.cpp +++ /dev/null @@ -1,74 +0,0 @@ -// The timed condition-variable wait of every runtime binary built against the dynamic CRT (/MD), routed through -// msvcp140.dll so it uses the same _Mtx_t layout as the mutex it unlocks. -// -// In the 14.4x STL, condition_variable::wait_for/wait_until call _Cnd_timedwait_for_unchecked. declares -// it without _CRTIMP2_PURE, so it is not imported: it is linked statically from msvcprt.lib (its sharedmutex.obj), -// and it unlocks the mutex by reaching into Windows' _Mtx_t layout for its SRW lock. _Mtx_lock/_Mtx_unlock are -// imported from msvcp140.dll. Wine's builtin msvcp140 laid _Mtx_t out differently until wine-10.1 ("msvcp140: Fix -// field order in _Mtx_t", 757bd7909fda), so on Wine 9.0 (Ubuntu 24.04's wine) a timed wait released nothing and -// kept the mutex for its whole timeout: the thread that would set the predicate could not take the lock, and every -// wait_for timed out instead of being woken (issue #3796, measured 2000 ms vs 0.3 ms for a 2 s wait). -// -// Defining the public symbols of that msvcprt.lib member here keeps it out of the link. The timed wait then goes -// through msvcp140's exported _Cnd_timedwait, which locks and waits on its own layout, whatever DLL provides it -// (Windows, any Wine). The other definitions are the ones the member would bring in, with the same behaviour: -// std::shared_mutex on an SRW lock, and this_thread::sleep_for. Only /MD targets get this file (CMakeLists.txt); -// a /MT target links the whole STL statically, so its mutex and wait already agree. No game files. -#include - -#include -#include - -extern "C" { - -// Exported by every msvcp140.dll, Windows' and Wine's; no longer declared by the 14.4x headers. The deadline is -// absolute, in TIME_UTC seconds and nanoseconds, and the result uses _Thrd_result's values (0, or 2 on timeout). -__declspec(dllimport) int __cdecl _Cnd_timedwait(_Cnd_t, _Mtx_t, const _timespec64*) noexcept; - -_Thrd_result __stdcall _Cnd_timedwait_for_unchecked(_Cnd_t cond, _Mtx_t mtx, unsigned int ms) noexcept { - _timespec64 deadline{}; - if (_timespec64_get(&deadline, TIME_UTC) != TIME_UTC) deadline = {}; - deadline.tv_sec += ms / 1000; - deadline.tv_nsec += static_cast(ms % 1000) * 1000000L; - if (deadline.tv_nsec >= 1000000000L) { - deadline.tv_sec += 1; - deadline.tv_nsec -= 1000000000L; - } - // A spurious or early return is allowed ("unchecked"): the STL's callers check the clock themselves. - return static_cast<_Thrd_result>(_Cnd_timedwait(cond, mtx, &deadline)); -} - -// Not declared by the 14.4x headers, but defined by the same member: keep a caller of the older name off it too. -_Thrd_result __stdcall _Cnd_timedwait_for(_Cnd_t cond, _Mtx_t mtx, unsigned int ms) noexcept { - return _Cnd_timedwait_for_unchecked(cond, mtx, ms); -} - -void __cdecl _Smtx_lock_exclusive(_Smtx_t* lock) noexcept { - AcquireSRWLockExclusive(reinterpret_cast(lock)); -} - -void __cdecl _Smtx_lock_shared(_Smtx_t* lock) noexcept { - AcquireSRWLockShared(reinterpret_cast(lock)); -} - -int __cdecl _Smtx_try_lock_exclusive(_Smtx_t* lock) noexcept { - return TryAcquireSRWLockExclusive(reinterpret_cast(lock)); -} - -int __cdecl _Smtx_try_lock_shared(_Smtx_t* lock) noexcept { - return TryAcquireSRWLockShared(reinterpret_cast(lock)); -} - -void __cdecl _Smtx_unlock_exclusive(_Smtx_t* lock) noexcept { - ReleaseSRWLockExclusive(reinterpret_cast(lock)); -} - -void __cdecl _Smtx_unlock_shared(_Smtx_t* lock) noexcept { - ReleaseSRWLockShared(reinterpret_cast(lock)); -} - -void __stdcall _Thrd_sleep_for(unsigned long ms) noexcept { - Sleep(ms); -} - -} // extern "C" diff --git a/runtime/src/depth24.h b/runtime/src/depth24.h deleted file mode 100644 index b9100297b..000000000 --- a/runtime/src/depth24.h +++ /dev/null @@ -1,76 +0,0 @@ -// D24_UNORM_S8_UINT without a native D24 (the layer stores D32_SFLOAT_S8_UINT): what the conversions are, as plain C++. -// vulkan_depth24.h runs them on the GPU around copies (depth24_convert.comp); the reference here is what the -// compute shader and the clear path must equal, and it is what the clears use. -// -// A D24 texel is a 24-bit UNORM: d / 16777215. The footprint of a copy holds it in bits 0-23 of a 32-bit word (bits -// 24-31 are unspecified; the PC runtime reads them as 0 and writes 0), the stencil plane is a separate plane of -// bytes. The layer's D32 holds the float nearest to d / 16777215, which the 24-bit quantisation maps back to d. -#pragma once - -#include - -#include -#include - -namespace leonida { - -inline constexpr std::uint32_t depth24_max = 0xffffff; - -// What the D3D11.3 functional spec says (3.2.3.6, FLOAT -> UNORM, which D3D12 inherits): NaN is 0; above 1.0f, INF -// included, is 1.0f and below 0.0f is 0.0f; then c = c * (2^n - 1) "in float", c = c + 0.5f, and the fraction is -// dropped; the conversion has a tolerance of 0.6 ULP on the integer side ("exact (1/2 ULP) conversion precision is -// acknowledged to be too expensive") and must be non-decreasing with every output attainable. Read literally, a tie -// goes up (2.5 -> 3). The spec's general rule (3.2.2) names round-to-nearest for FLOAT -> UNORM as an exception to -// round-to-nearest-even, so the spec does not fix ties. What WARP and AMD's D3D12 driver do was measured: they -// round the float product to nearest even (2.5 -> 2, 0.5 -> 0), which the tolerance allows; NVIDIA's differ at -// ties. That is a measurement of those two implementations, not a rule of the spec. -// -// The conversion of a float to a 24-bit UNORM as WARP and AMD's D3D12 drivers do it (measured against both, 5215 -// clear values, ties and their neighbours included, in d3d12_depth24_compare.h): NaN and values below 0 give 0, 1 and above the -// maximum, anything in between multiplies by 2^24 - 1 in float (a rounded product, so a value a hair over a tie can -// land on it) and then rounds to nearest, ties to even (std::nearbyint's default mode). NVIDIA's D3D12 driver breaks -// some of those ties the other way, and its Vulkan driver, which has a native D24, agrees with it; a texture the -// layer stores as D32 follows WARP and AMD, which is what the Xbox build's own hardware is. -inline std::uint32_t depth24_quantize(float value) { - if (!(value > 0.0f)) return 0; - if (value >= 1.0f) return depth24_max; - const float product = value * 16777215.0f; // a float multiply, not a double one - return static_cast(std::nearbyint(product)); -} - -// The float stored for a 24-bit UNORM: the nearest float to d / 16777215 (quantising it gives d back). -inline float depth24_to_float(std::uint32_t d) { - return static_cast(double(d & depth24_max) / double(depth24_max)); -} - -// A depth value as the layer's D32 must hold it for a D24 texture: what a clear writes, so that reading the texture -// back gives the quantisation D3D makes. -inline float depth24_clear_value(float value) { return depth24_to_float(depth24_quantize(value)); } - -// One copy between a footprint (words of 24-bit depth) and the D32 aspect of a texture, as the compute pass sees it. -// The pass converts between the application's buffer and a tight scratch buffer of floats; a copy command moves the -// scratch to or from the image. vulkan_depth24.h fills the scratch and descriptor fields in `prepare`. -// -// The same pass, scratch and job repack 96-bit R32G32B32 texels (`rgb96`, D3D-62): the footprint then has three -// words a texel and the scratch four (the layer's R32G32B32A32 image), copied as they are. The row and slice -// distances stay in words; only the texel's width differs (app_texel_words, scratch_texel_words). -struct Depth24Job { - bool to_float = false; // an upload (D24 words to floats); false: a readback (floats to words) - bool rgb96 = false; // 96-bit texels: `to_float` is only the direction (true: the upload) - std::uint32_t app_texel_words() const { return rgb96 ? 3 : 1; } - std::uint32_t scratch_texel_words() const { return rgb96 ? 4 : 1; } - VkBuffer app = VK_NULL_HANDLE; // the application's buffer - std::uint64_t app_offset = 0; // bytes, a multiple of 4 - std::uint64_t app_size = 0; // bytes in the buffer - std::uint32_t width = 0, height = 0, slices = 0; - std::uint32_t app_row_words = 0; // words between rows and between slices of the footprint - std::uint32_t app_slice_words = 0; - // Set by prepare: - VkBuffer scratch = VK_NULL_HANDLE; // width * height * slices texels (floats, or four words), tightly packed - VkDeviceSize scratch_offset = 0; - VkDescriptorSet set = VK_NULL_HANDLE; - std::uint32_t app_base_words = 0; // the region's first word in the descriptor's window - std::uint32_t scratch_base_words = 0; // and the scratch's -}; - -} // namespace leonida diff --git a/runtime/src/depth24_convert.comp b/runtime/src/depth24_convert.comp deleted file mode 100644 index 822a67459..000000000 --- a/runtime/src/depth24_convert.comp +++ /dev/null @@ -1,73 +0,0 @@ -// D24_UNORM_S8_UINT on a GPU without D24: the layer stores D32_SFLOAT_S8_UINT, and the depth words of a copy -// footprint (24-bit UNORM in bits 0-23, bits 24-31 unspecified) are converted here. depth24_convert_spv.h is this file -// compiled with `glslc --target-env=vulkan1.1 -O -mfmt=c` (see the header for the command); keep them together. -// -// to_float != 0 (upload): scratch[s] = float bits of the float nearest to d / 16777215, d = app[a] & 0xffffff -// to_float == 0 (readback): app[a] = D3D's quantisation of scratch[s] (depth24.h; round to nearest even of f * 16777215, -// NaN and negatives 0, 1 and above 16777215), the unspecified top byte written as 0 -// The upload direction is integer arithmetic (no float division, whose rounding is the GPU's choice); the readback -// uses one float multiply, which Vulkan requires to be correctly rounded, and roundEven. -// -// The same pass repacks 96-bit R32G32B32 texels, which the layer holds in R32G32B32A32 images (D3D-62; `to_float` -// 2 and 3). A footprint texel is then three words and a scratch texel four, and the words are copied as they are: -// to_float == 3 (upload): scratch[s .. s+2] = app[a .. a+2], scratch[s+3] = 0 (never read: views read alpha as one) -// to_float == 2 (readback): app[a .. a+2] = scratch[s .. s+2] -#version 450 - -layout(local_size_x = 8, local_size_y = 8, local_size_z = 1) in; - -layout(set = 0, binding = 0) buffer App { uint app[]; }; -layout(set = 0, binding = 1) buffer Scratch { uint scratch[]; }; - -layout(push_constant) uniform Push { - uint width, height, slices; - uint to_float; // 0 and 1: D24 words and floats; 2 and 3: 96-bit texels of 3 and 4 words (see above) - uint app_base; // first word of the region in `app`, within the bound window - uint app_row; // words between rows and between slices of the app buffer - uint app_slice; - uint scratch_base; // first word of the region in `scratch`, within the bound window -} pc; - -// d / (2^24 - 1) as a float. With m the 24-bit mantissa of d (d = m * 2^(e-23)) the quotient is -// (m + m / (2^24 - 1)) * 2^(e-47), and m / (2^24 - 1) lies in (0.5, 1] for every m in [2^23, 2^24], so the nearest -// 24-bit mantissa is m + 1 and the result is exactly float(m + 1) * 2^(e-47). -float depth24_to_float(uint d) { - if (d == 0u) return 0.0; - int e = findMSB(d); - uint m = d << uint(23 - e); - return float(m + 1u) * uintBitsToFloat(uint(e - 47 + 127) << 23); -} - -// The 24-bit UNORM of f as WARP and AMD's D3D12 drivers write it: the product with 2^24 - 1 is rounded to a float -// first, then to the nearest integer with ties to even (NVIDIA's hardware breaks some ties the other way; see -// depth24.h). NaN and negatives give 0, 1 and above the maximum. -uint depth24_from_bits(uint bits) { - // In unsigned order, all negative encodings and positive NaNs lie above positive infinity. - if (bits > 0x7f800000u) return 0u; - if (bits >= 0x3f800000u) return 0xffffffu; - return uint(roundEven(uintBitsToFloat(bits) * 16777215.0)); -} - -void main() { - uvec3 g = gl_GlobalInvocationID; - if (g.x >= pc.width || g.y >= pc.height || g.z >= pc.slices) return; - if (pc.to_float >= 2u) { - uint a = pc.app_base + g.z * pc.app_slice + g.y * pc.app_row + g.x * 3u; - uint s = pc.scratch_base + ((g.z * pc.height + g.y) * pc.width + g.x) * 4u; - if (pc.to_float == 3u) { - scratch[s] = app[a]; - scratch[s + 1u] = app[a + 1u]; - scratch[s + 2u] = app[a + 2u]; - scratch[s + 3u] = 0u; - } else { - app[a] = scratch[s]; - app[a + 1u] = scratch[s + 1u]; - app[a + 2u] = scratch[s + 2u]; - } - return; - } - uint a = pc.app_base + g.z * pc.app_slice + g.y * pc.app_row + g.x; - uint s = pc.scratch_base + (g.z * pc.height + g.y) * pc.width + g.x; - if (pc.to_float != 0u) scratch[s] = floatBitsToUint(depth24_to_float(app[a] & 0xffffffu)); - else app[a] = depth24_from_bits(scratch[s]); -} diff --git a/runtime/src/depth24_convert.inc b/runtime/src/depth24_convert.inc deleted file mode 100644 index 155b6b22f..000000000 --- a/runtime/src/depth24_convert.inc +++ /dev/null @@ -1,277 +0,0 @@ -{0x07230203,0x00010300,0x000d000b,0x0000016d, -0x00000000,0x00020011,0x00000001,0x0006000b, -0x00000001,0x4c534c47,0x6474732e,0x3035342e, -0x00000000,0x0003000e,0x00000000,0x00000001, -0x0006000f,0x00000005,0x00000004,0x6e69616d, -0x00000000,0x0000004d,0x00060010,0x00000004, -0x00000011,0x00000008,0x00000008,0x00000001, -0x00040047,0x0000004d,0x0000000b,0x0000001c, -0x00030047,0x00000051,0x00000002,0x00050048, -0x00000051,0x00000000,0x00000023,0x00000000, -0x00050048,0x00000051,0x00000001,0x00000023, -0x00000004,0x00050048,0x00000051,0x00000002, -0x00000023,0x00000008,0x00050048,0x00000051, -0x00000003,0x00000023,0x0000000c,0x00050048, -0x00000051,0x00000004,0x00000023,0x00000010, -0x00050048,0x00000051,0x00000005,0x00000023, -0x00000014,0x00050048,0x00000051,0x00000006, -0x00000023,0x00000018,0x00050048,0x00000051, -0x00000007,0x00000023,0x0000001c,0x00040047, -0x000000a8,0x00000006,0x00000004,0x00030047, -0x000000a9,0x00000002,0x00050048,0x000000a9, -0x00000000,0x00000023,0x00000000,0x00040047, -0x000000ab,0x00000021,0x00000001,0x00040047, -0x000000ab,0x00000022,0x00000000,0x00040047, -0x000000ad,0x00000006,0x00000004,0x00030047, -0x000000ae,0x00000002,0x00050048,0x000000ae, -0x00000000,0x00000023,0x00000000,0x00040047, -0x000000b0,0x00000021,0x00000000,0x00040047, -0x000000b0,0x00000022,0x00000000,0x00040047, -0x00000117,0x0000000b,0x00000019,0x00020013, -0x00000002,0x00030021,0x00000003,0x00000002, -0x00040015,0x00000006,0x00000020,0x00000000, -0x00030016,0x00000008,0x00000020,0x0004002b, -0x00000006,0x00000012,0x00000000,0x00020014, -0x00000013,0x0004002b,0x00000008,0x00000017, -0x00000000,0x00040015,0x00000019,0x00000020, -0x00000001,0x0004002b,0x00000019,0x00000020, -0x00000017,0x0004002b,0x00000006,0x00000026, -0x00000001,0x0004002b,0x00000006,0x00000035, -0x7f800000,0x0004002b,0x00000006,0x0000003b, -0x3f800000,0x0004002b,0x00000006,0x0000003f, -0x00ffffff,0x0004002b,0x00000008,0x00000043, -0x4b7fffff,0x00040017,0x00000049,0x00000006, -0x00000003,0x00040020,0x0000004c,0x00000001, -0x00000049,0x0004003b,0x0000004c,0x0000004d, -0x00000001,0x000a001e,0x00000051,0x00000006, -0x00000006,0x00000006,0x00000006,0x00000006, -0x00000006,0x00000006,0x00000006,0x00040020, -0x00000052,0x00000009,0x00000051,0x0004003b, -0x00000052,0x00000053,0x00000009,0x0004002b, -0x00000019,0x00000054,0x00000000,0x00040020, -0x00000055,0x00000009,0x00000006,0x0004002b, -0x00000019,0x0000005e,0x00000001,0x0004002b, -0x00000006,0x00000066,0x00000002,0x0004002b, -0x00000019,0x00000069,0x00000002,0x0004002b, -0x00000019,0x00000071,0x00000003,0x0004002b, -0x00000019,0x00000078,0x00000004,0x0004002b, -0x00000019,0x0000007d,0x00000006,0x0004002b, -0x00000019,0x00000084,0x00000005,0x0004002b, -0x00000006,0x0000008b,0x00000003,0x0004002b, -0x00000019,0x0000008f,0x00000007,0x0004002b, -0x00000006,0x000000a0,0x00000004,0x0003001d, -0x000000a8,0x00000006,0x0003001e,0x000000a9, -0x000000a8,0x00040020,0x000000aa,0x0000000c, -0x000000a9,0x0004003b,0x000000aa,0x000000ab, -0x0000000c,0x0003001d,0x000000ad,0x00000006, -0x0003001e,0x000000ae,0x000000ad,0x00040020, -0x000000af,0x0000000c,0x000000ae,0x0004003b, -0x000000af,0x000000b0,0x0000000c,0x00040020, -0x000000b2,0x0000000c,0x00000006,0x0004002b, -0x00000006,0x00000116,0x00000008,0x0006002c, -0x00000049,0x00000117,0x00000116,0x00000116, -0x00000026,0x0004002b,0x00000019,0x0000016c, -0x00000050,0x00050036,0x00000002,0x00000004, -0x00000000,0x00000003,0x000200f8,0x00000005, -0x000300f7,0x00000118,0x00000000,0x000300fb, -0x00000012,0x00000119,0x000200f8,0x00000119, -0x0004003d,0x00000049,0x0000004e,0x0000004d, -0x00050051,0x00000006,0x00000050,0x0000004e, -0x00000000,0x00050041,0x00000055,0x00000056, -0x00000053,0x00000054,0x0004003d,0x00000006, -0x00000057,0x00000056,0x000500ae,0x00000013, -0x00000058,0x00000050,0x00000057,0x000400a8, -0x00000013,0x00000059,0x00000058,0x000300f7, -0x0000005b,0x00000000,0x000400fa,0x00000059, -0x0000005a,0x0000005b,0x000200f8,0x0000005a, -0x00050051,0x00000006,0x0000005d,0x0000004e, -0x00000001,0x00050041,0x00000055,0x0000005f, -0x00000053,0x0000005e,0x0004003d,0x00000006, -0x00000060,0x0000005f,0x000500ae,0x00000013, -0x00000061,0x0000005d,0x00000060,0x000200f9, -0x0000005b,0x000200f8,0x0000005b,0x000700f5, -0x00000013,0x00000062,0x00000058,0x00000119, -0x00000061,0x0000005a,0x000400a8,0x00000013, -0x00000063,0x00000062,0x000300f7,0x00000065, -0x00000000,0x000400fa,0x00000063,0x00000064, -0x00000065,0x000200f8,0x00000064,0x00050051, -0x00000006,0x00000068,0x0000004e,0x00000002, -0x00050041,0x00000055,0x0000006a,0x00000053, -0x00000069,0x0004003d,0x00000006,0x0000006b, -0x0000006a,0x000500ae,0x00000013,0x0000006c, -0x00000068,0x0000006b,0x000200f9,0x00000065, -0x000200f8,0x00000065,0x000700f5,0x00000013, -0x0000006d,0x00000062,0x0000005b,0x0000006c, -0x00000064,0x000300f7,0x0000006f,0x00000000, -0x000400fa,0x0000006d,0x0000006e,0x0000006f, -0x000200f8,0x0000006e,0x000200f9,0x00000118, -0x000200f8,0x0000006f,0x00050041,0x00000055, -0x00000072,0x00000053,0x00000071,0x0004003d, -0x00000006,0x00000073,0x00000072,0x000500ae, -0x00000013,0x00000074,0x00000073,0x00000066, -0x000300f7,0x00000076,0x00000000,0x000400fa, -0x00000074,0x00000075,0x00000076,0x000200f8, -0x00000075,0x00050041,0x00000055,0x00000079, -0x00000053,0x00000078,0x0004003d,0x00000006, -0x0000007a,0x00000079,0x00050051,0x00000006, -0x0000007c,0x0000004e,0x00000002,0x00050041, -0x00000055,0x0000007e,0x00000053,0x0000007d, -0x0004003d,0x00000006,0x0000007f,0x0000007e, -0x00050084,0x00000006,0x00000080,0x0000007c, -0x0000007f,0x00050080,0x00000006,0x00000081, -0x0000007a,0x00000080,0x00050051,0x00000006, -0x00000083,0x0000004e,0x00000001,0x00050041, -0x00000055,0x00000085,0x00000053,0x00000084, -0x0004003d,0x00000006,0x00000086,0x00000085, -0x00050084,0x00000006,0x00000087,0x00000083, -0x00000086,0x00050080,0x00000006,0x00000088, -0x00000081,0x00000087,0x00050084,0x00000006, -0x0000008c,0x00000050,0x0000008b,0x00050080, -0x00000006,0x0000008d,0x00000088,0x0000008c, -0x00050041,0x00000055,0x00000090,0x00000053, -0x0000008f,0x0004003d,0x00000006,0x00000091, -0x00000090,0x00050041,0x00000055,0x00000094, -0x00000053,0x0000005e,0x0004003d,0x00000006, -0x00000095,0x00000094,0x00050084,0x00000006, -0x00000096,0x0000007c,0x00000095,0x00050080, -0x00000006,0x00000099,0x00000096,0x00000083, -0x00050084,0x00000006,0x0000009c,0x00000099, -0x00000057,0x00050080,0x00000006,0x0000009f, -0x0000009c,0x00000050,0x00050084,0x00000006, -0x000000a1,0x0000009f,0x000000a0,0x00050080, -0x00000006,0x000000a2,0x00000091,0x000000a1, -0x000500aa,0x00000013,0x000000a5,0x00000073, -0x0000008b,0x000300f7,0x000000a7,0x00000000, -0x000400fa,0x000000a5,0x000000a6,0x000000c7, -0x000200f8,0x000000a6,0x00060041,0x000000b2, -0x000000b3,0x000000b0,0x00000054,0x0000008d, -0x0004003d,0x00000006,0x000000b4,0x000000b3, -0x00060041,0x000000b2,0x000000b5,0x000000ab, -0x00000054,0x000000a2,0x0003003e,0x000000b5, -0x000000b4,0x00050080,0x00000006,0x000000b7, -0x000000a2,0x00000026,0x00050080,0x00000006, -0x000000b9,0x0000008d,0x00000026,0x00060041, -0x000000b2,0x000000ba,0x000000b0,0x00000054, -0x000000b9,0x0004003d,0x00000006,0x000000bb, -0x000000ba,0x00060041,0x000000b2,0x000000bc, -0x000000ab,0x00000054,0x000000b7,0x0003003e, -0x000000bc,0x000000bb,0x00050080,0x00000006, -0x000000be,0x000000a2,0x00000066,0x00050080, -0x00000006,0x000000c0,0x0000008d,0x00000066, -0x00060041,0x000000b2,0x000000c1,0x000000b0, -0x00000054,0x000000c0,0x0004003d,0x00000006, -0x000000c2,0x000000c1,0x00060041,0x000000b2, -0x000000c3,0x000000ab,0x00000054,0x000000be, -0x0003003e,0x000000c3,0x000000c2,0x00050080, -0x00000006,0x000000c5,0x000000a2,0x0000008b, -0x00060041,0x000000b2,0x000000c6,0x000000ab, -0x00000054,0x000000c5,0x0003003e,0x000000c6, -0x00000012,0x000200f9,0x000000a7,0x000200f8, -0x000000c7,0x00060041,0x000000b2,0x000000ca, -0x000000ab,0x00000054,0x000000a2,0x0004003d, -0x00000006,0x000000cb,0x000000ca,0x00060041, -0x000000b2,0x000000cc,0x000000b0,0x00000054, -0x0000008d,0x0003003e,0x000000cc,0x000000cb, -0x00050080,0x00000006,0x000000ce,0x0000008d, -0x00000026,0x00050080,0x00000006,0x000000d0, -0x000000a2,0x00000026,0x00060041,0x000000b2, -0x000000d1,0x000000ab,0x00000054,0x000000d0, -0x0004003d,0x00000006,0x000000d2,0x000000d1, -0x00060041,0x000000b2,0x000000d3,0x000000b0, -0x00000054,0x000000ce,0x0003003e,0x000000d3, -0x000000d2,0x00050080,0x00000006,0x000000d5, -0x0000008d,0x00000066,0x00050080,0x00000006, -0x000000d7,0x000000a2,0x00000066,0x00060041, -0x000000b2,0x000000d8,0x000000ab,0x00000054, -0x000000d7,0x0004003d,0x00000006,0x000000d9, -0x000000d8,0x00060041,0x000000b2,0x000000da, -0x000000b0,0x00000054,0x000000d5,0x0003003e, -0x000000da,0x000000d9,0x000200f9,0x000000a7, -0x000200f8,0x000000a7,0x000200f9,0x00000118, -0x000200f8,0x00000076,0x00050041,0x00000055, -0x000000dd,0x00000053,0x00000078,0x0004003d, -0x00000006,0x000000de,0x000000dd,0x00050051, -0x00000006,0x000000e0,0x0000004e,0x00000002, -0x00050041,0x00000055,0x000000e1,0x00000053, -0x0000007d,0x0004003d,0x00000006,0x000000e2, -0x000000e1,0x00050084,0x00000006,0x000000e3, -0x000000e0,0x000000e2,0x00050080,0x00000006, -0x000000e4,0x000000de,0x000000e3,0x00050051, -0x00000006,0x000000e6,0x0000004e,0x00000001, -0x00050041,0x00000055,0x000000e7,0x00000053, -0x00000084,0x0004003d,0x00000006,0x000000e8, -0x000000e7,0x00050084,0x00000006,0x000000e9, -0x000000e6,0x000000e8,0x00050080,0x00000006, -0x000000ea,0x000000e4,0x000000e9,0x00050080, -0x00000006,0x000000ed,0x000000ea,0x00000050, -0x00050041,0x00000055,0x000000ef,0x00000053, -0x0000008f,0x0004003d,0x00000006,0x000000f0, -0x000000ef,0x00050041,0x00000055,0x000000f3, -0x00000053,0x0000005e,0x0004003d,0x00000006, -0x000000f4,0x000000f3,0x00050084,0x00000006, -0x000000f5,0x000000e0,0x000000f4,0x00050080, -0x00000006,0x000000f8,0x000000f5,0x000000e6, -0x00050084,0x00000006,0x000000fb,0x000000f8, -0x00000057,0x00050080,0x00000006,0x000000fc, -0x000000f0,0x000000fb,0x00050080,0x00000006, -0x000000ff,0x000000fc,0x00000050,0x000500ab, -0x00000013,0x00000102,0x00000073,0x00000012, -0x000300f7,0x00000104,0x00000000,0x000400fa, -0x00000102,0x00000103,0x0000010e,0x000200f8, -0x00000103,0x00060041,0x000000b2,0x00000107, -0x000000b0,0x00000054,0x000000ed,0x0004003d, -0x00000006,0x00000108,0x00000107,0x000500c7, -0x00000006,0x00000109,0x00000108,0x0000003f, -0x000300f7,0x00000145,0x00000000,0x000300fb, -0x00000012,0x0000012f,0x000200f8,0x0000012f, -0x000500aa,0x00000013,0x00000131,0x00000109, -0x00000012,0x000300f7,0x00000133,0x00000000, -0x000400fa,0x00000131,0x00000132,0x00000133, -0x000200f8,0x00000132,0x000200f9,0x00000145, -0x000200f8,0x00000133,0x0006000c,0x00000019, -0x00000135,0x00000001,0x0000004b,0x00000109, -0x00050082,0x00000019,0x00000138,0x00000020, -0x00000135,0x0004007c,0x00000006,0x00000139, -0x00000138,0x000500c4,0x00000006,0x0000013a, -0x00000109,0x00000139,0x00050080,0x00000006, -0x0000013c,0x0000013a,0x00000026,0x00040070, -0x00000008,0x0000013d,0x0000013c,0x00050080, -0x00000019,0x00000140,0x00000135,0x0000016c, -0x0004007c,0x00000006,0x00000141,0x00000140, -0x000500c4,0x00000006,0x00000142,0x00000141, -0x00000020,0x0004007c,0x00000008,0x00000143, -0x00000142,0x00050085,0x00000008,0x00000144, -0x0000013d,0x00000143,0x000200f9,0x00000145, -0x000200f8,0x00000145,0x000700f5,0x00000008, -0x0000016b,0x00000017,0x00000132,0x00000144, -0x00000133,0x0004007c,0x00000006,0x0000010c, -0x0000016b,0x00060041,0x000000b2,0x0000010d, -0x000000ab,0x00000054,0x000000ff,0x0003003e, -0x0000010d,0x0000010c,0x000200f9,0x00000104, -0x000200f8,0x0000010e,0x00060041,0x000000b2, -0x00000112,0x000000ab,0x00000054,0x000000ff, -0x0004003d,0x00000006,0x00000113,0x00000112, -0x000300f7,0x00000159,0x00000000,0x000300fb, -0x00000012,0x0000014b,0x000200f8,0x0000014b, -0x000500ac,0x00000013,0x0000014d,0x00000113, -0x00000035,0x000300f7,0x0000014f,0x00000000, -0x000400fa,0x0000014d,0x0000014e,0x0000014f, -0x000200f8,0x0000014e,0x000200f9,0x00000159, -0x000200f8,0x0000014f,0x000500ae,0x00000013, -0x00000151,0x00000113,0x0000003b,0x000300f7, -0x00000153,0x00000000,0x000400fa,0x00000151, -0x00000152,0x00000153,0x000200f8,0x00000152, -0x000200f9,0x00000159,0x000200f8,0x00000153, -0x0004007c,0x00000008,0x00000155,0x00000113, -0x00050085,0x00000008,0x00000156,0x00000155, -0x00000043,0x0006000c,0x00000008,0x00000157, -0x00000001,0x00000002,0x00000156,0x0004006d, -0x00000006,0x00000158,0x00000157,0x000200f9, -0x00000159,0x000200f8,0x00000159,0x000900f5, -0x00000006,0x0000016a,0x00000012,0x0000014e, -0x0000003f,0x00000152,0x00000158,0x00000153, -0x00060041,0x000000b2,0x00000115,0x000000b0, -0x00000054,0x000000ed,0x0003003e,0x00000115, -0x0000016a,0x000200f9,0x00000104,0x000200f8, -0x00000104,0x000200f9,0x00000118,0x000200f8, -0x00000118,0x000100fd,0x00010038} diff --git a/runtime/src/depth24_convert_spv.h b/runtime/src/depth24_convert_spv.h deleted file mode 100644 index 82c3243d7..000000000 --- a/runtime/src/depth24_convert_spv.h +++ /dev/null @@ -1,11 +0,0 @@ -#pragma once -#include - -namespace leonida { - -// depth24_convert.comp compiled with: glslc --target-env=vulkan1.1 -O -mfmt=c depth24_convert.comp -o depth24_convert.inc -inline constexpr std::uint32_t depth24_convert_spirv[] = -#include "depth24_convert.inc" -; - -} // namespace leonida diff --git a/runtime/src/depth24_fragment.h b/runtime/src/depth24_fragment.h deleted file mode 100644 index 10f0dada8..000000000 --- a/runtime/src/depth24_fragment.h +++ /dev/null @@ -1,445 +0,0 @@ -#pragma once - -// D24_UNORM_S8_UINT on a GPU without D24 (the layer stores D32_SFLOAT_S8_UINT, depth24.h) in draws (D3D-309). -// -// Two D3D rules break when the depth attachment is float (found by @marquezinii, measured by @Vonsek on #291): -// * the integer RasterizerState.DepthBias is in fixed D24 units, r = 1 / (2^24 - 1) ("the minimum representable -// value > 0 in the depth-buffer format"), while Vulkan scales a float attachment's constant bias by the -// primitive's exponent; -// * clears are quantised to the D24 code (depth24_clear_value), fragment depth is not, so an EQUAL test at a -// cleared value fails where D24 hardware passes. -// The fix moves both into the pixel stage: the fragment writes FragDepth = quantise(z + bias), with z the rasterised -// depth, bias = DepthBias * r + SlopeScaledDepthBias * max(|dz/dx|, |dz/dy|) clamped by DepthBiasClamp (D3D's -// formula), and quantise = depth24_to_float(depth24_quantize(.)) from depth24_convert.comp, so a fragment holds -// exactly the float a D24 code reads back as. The rasterizer's own bias is then turned off for the pipeline. -// A shader that writes its own depth (SV_Depth) keeps its value, quantised; D3D applies no bias to it. -// -// depth24_patch_fragment edits a translated pixel shader's SPIR-V; depth24_depth_only_fragment builds the stage -// for a pipeline without a pixel shader (depth-only passes such as shadow maps). Both are plain word editing with -// no dependency beyond the standard library; d3d12_depth24_draw_test runs them (with LEONIDA_VK_VALIDATION=1 the -// validation layer checks the modules). -// -// Not covered (logged by the caller): a pixel shader with EarlyFragmentTests (its FragDepth write would be ignored), -// multisampled targets (FragDepth is per pixel, which would flatten per-sample depth), and a viewport depth range -// narrower than the biased depth (D3D clamps to MinDepth..MaxDepth before quantising; the quantisation here clamps -// to 0..1 and Vulkan's clamp to the viewport range follows it). - -#include -#include -#include -#include -#include -#include - -namespace leonida { - -struct Depth24Bias { - int constant = 0; // D3D12_RASTERIZER_DESC::DepthBias - float slope = 0.0f; // SlopeScaledDepthBias - float clamp = 0.0f; // DepthBiasClamp: > 0 caps the bias, < 0 floors it, 0 leaves it - bool any() const { return constant != 0 || slope != 0.0f; } -}; - -// D3D's constant term in float: (float)DepthBias * r, with r the float nearest 1 / (2^24 - 1). -inline float depth24_bias_constant(int bias) { - return float(bias) * float(1.0 / 16777215.0); -} - -namespace spirv24 { - -enum : std::uint32_t { - op_name = 5, op_line = 8, op_ext_inst_import = 11, op_ext_inst = 12, op_memory_model = 14, op_entry_point = 15, - op_execution_mode = 16, op_capability = 17, op_type_void = 19, op_type_bool = 20, op_type_int = 21, - op_type_float = 22, op_type_vector = 23, op_type_pointer = 32, op_type_function = 33, op_constant = 43, - op_function = 54, op_function_end = 56, op_variable = 59, op_load = 61, op_store = 62, op_decorate = 71, - op_composite_extract = 81, op_convert_f_to_u = 109, op_convert_u_to_f = 112, op_bitcast = 124, op_i_add = 128, - op_f_add = 129, op_i_sub = 130, op_f_mul = 133, op_select = 169, op_i_equal = 170, op_u_greater_than = 172, - op_u_greater_than_equal = 174, op_shift_left_logical = 196, op_dpdx = 207, op_dpdy = 208, op_label = 248, - op_return = 253, op_no_line = 317, op_execution_mode_id = 331, -}; -enum : std::uint32_t { storage_input = 1, storage_output = 3 }; -enum : std::uint32_t { decoration_builtin = 11, builtin_frag_coord = 15, builtin_frag_depth = 22 }; -enum : std::uint32_t { model_fragment = 4 }; -enum : std::uint32_t { - mode_origin_upper_left = 7, mode_early_fragment_tests = 9, mode_depth_replacing = 12, mode_depth_greater = 14, - mode_depth_less = 15, mode_depth_unchanged = 16, -}; -enum : std::uint32_t { glsl_round_even = 2, glsl_fabs = 4, glsl_fmin = 37, glsl_fmax = 40, glsl_find_umsb = 75 }; - -using Inst = std::vector; // a whole instruction, word 0 included - -inline std::uint32_t opcode(const Inst& i) { return i[0] & 0xffffu; } -inline Inst make(std::uint32_t op, std::initializer_list operands) { - Inst i; - i.reserve(operands.size() + 1); - i.push_back(std::uint32_t(operands.size() + 1) << 16 | op); - i.insert(i.end(), operands.begin(), operands.end()); - return i; -} -inline void append_string(Inst& i, const char* s) { - const std::size_t n = std::strlen(s) + 1, words = (n + 3) / 4; - const std::size_t at = i.size(); - i.resize(at + words, 0); - std::memcpy(&i[at], s, n); -} -inline void fix_length(Inst& i) { i[0] = std::uint32_t(i.size()) << 16 | opcode(i); } -inline std::uint32_t bits(float f) { - std::uint32_t u; - std::memcpy(&u, &f, 4); - return u; -} -// Words a literal string takes in an instruction, starting at `at`. -inline std::size_t string_words(const Inst& i, std::size_t at) { - std::size_t w = at; - while (w < i.size()) { - const std::uint32_t word = i[w++]; - if ((word & 0xff000000u) == 0 || (word & 0x00ff0000u) == 0 || (word & 0x0000ff00u) == 0 || - (word & 0x000000ffu) == 0) - break; - } - return w - at; -} - -inline bool is_global_decl(std::uint32_t op) { - return op == 1 /* OpUndef */ || (op >= op_type_void && op <= 39) || (op >= 41 && op <= 52) || op == op_variable; -} - -class Module { -public: - bool parse(const std::vector& words, std::string& why) { - if (words.size() < 5 || words[0] != 0x07230203u) { - why = "not a SPIR-V module"; - return false; - } - header_.assign(words.begin(), words.begin() + 5); - for (std::size_t w = 5; w < words.size();) { - const std::uint32_t count = words[w] >> 16; - if (count == 0 || w + count > words.size()) { - why = "truncated instruction"; - return false; - } - insts_.emplace_back(words.begin() + std::ptrdiff_t(w), words.begin() + std::ptrdiff_t(w + count)); - w += count; - } - return true; - } - std::vector words() const { - std::vector out = header_; - for (const Inst& i : insts_) out.insert(out.end(), i.begin(), i.end()); - return out; - } - std::uint32_t fresh() { return header_[3]++; } - std::uint32_t version() const { return header_[1]; } - std::vector& insts() { return insts_; } - std::vector& header() { return header_; } - -private: - std::vector header_; - std::vector insts_; -}; - -// The edit, on a parsed module. Globals are collected first and spliced in at their section's end. -class Patch { -public: - Patch(Module& m, std::uint32_t entry) : m_(m), entry_(entry) { - // Copies: apply() moves the module's instructions while the code at returns still looks types up. - for (const Inst& i : m.insts()) { - if (opcode(i) == op_function) break; - existing_.push_back(i); - } - } - - // A type, reused when the module already declares it (SPIR-V forbids duplicate non-aggregate types). - std::uint32_t type(std::uint32_t op, std::initializer_list operands) { - auto same = [&](const Inst& i) { - if (opcode(i) != op || i.size() != operands.size() + 2) return false; - std::size_t k = 2; - for (std::uint32_t o : operands) - if (i[k++] != o) return false; - return true; - }; - for (const Inst& ex : existing_) - if (same(ex)) return ex[1]; - for (const Inst& i : globals_) - if (same(i)) return i[1]; - const std::uint32_t id = m_.fresh(); - Inst i = make(op, {id}); - i.insert(i.end(), operands.begin(), operands.end()); - fix_length(i); - globals_.push_back(std::move(i)); - return id; - } - std::uint32_t t_float() { return type(op_type_float, {32}); } - std::uint32_t t_uint() { return type(op_type_int, {32, 0}); } - std::uint32_t t_bool() { return type(op_type_bool, {}); } - // Constants are cached by type and value: all of them are declared before apply() writes the globals out. - std::uint32_t constant(std::uint32_t t, std::uint32_t value) { - for (const auto& c : constants_) - if (c[0] == t && c[1] == value) return c[2]; - const std::uint32_t id = m_.fresh(); - globals_.push_back(make(op_constant, {t, id, value})); - constants_.push_back({t, value, id}); - return id; - } - // Declares what quantise() uses, so it can run inside apply() (at returns) without adding globals. - void prime_quantise() { - t_bool(); - glsl(); - for (float f : {16777215.0f, 0.0f}) f32(f); - for (std::uint32_t u : {0x3f800000u, 0xffffffu, 0x7f800000u, 0u, 23u, 1u, 80u}) u32(u); - } - std::uint32_t f32(float f) { return constant(t_float(), bits(f)); } - std::uint32_t u32(std::uint32_t u) { return constant(t_uint(), u); } - - std::uint32_t glsl() { - if (glsl_) return glsl_; - for (const Inst& ex : existing_) { - if (opcode(ex) != op_ext_inst_import || ex.size() < 3) continue; - std::string name((ex.size() - 2) * 4, '\0'); - std::memcpy(name.data(), &ex[2], name.size()); - if (std::strcmp(name.c_str(), "GLSL.std.450") == 0) return glsl_ = ex[1]; - } - glsl_ = m_.fresh(); - Inst i = make(op_ext_inst_import, {glsl_}); - append_string(i, "GLSL.std.450"); - fix_length(i); - import_ = std::move(i); - return glsl_; - } - - // A built-in variable already decorated in the module, or 0. - std::uint32_t builtin_variable(std::uint32_t builtin) const { - for (const Inst& ex : existing_) - if (opcode(ex) == op_decorate && ex.size() == 4 && ex[2] == decoration_builtin && ex[3] == builtin) - return ex[1]; - return 0; - } - std::uint32_t variable(std::uint32_t pointer_type, std::uint32_t storage, std::uint32_t builtin) { - const std::uint32_t id = m_.fresh(); - globals_.push_back(make(op_variable, {pointer_type, id, storage})); - decorations_.push_back(make(op_decorate, {id, decoration_builtin, builtin})); - interface_.push_back(id); - return id; - } - void ensure_interface(std::uint32_t id) { interface_.push_back(id); } - void mode(std::uint32_t m) { modes_.push_back(make(op_execution_mode, {entry_, m})); } - - // Instructions in a function body: emit returns the result id. - std::uint32_t emit(std::vector& code, std::uint32_t op, std::uint32_t type, - std::initializer_list operands) { - const std::uint32_t id = m_.fresh(); - Inst i = make(op, {type, id}); - i.insert(i.end(), operands.begin(), operands.end()); - fix_length(i); - code.push_back(std::move(i)); - return id; - } - std::uint32_t ext(std::vector& code, std::uint32_t type, std::uint32_t inst, - std::initializer_list operands) { - const std::uint32_t id = m_.fresh(); - Inst i = make(op_ext_inst, {type, id, glsl(), inst}); - i.insert(i.end(), operands.begin(), operands.end()); - fix_length(i); - code.push_back(std::move(i)); - return id; - } - - // depth24_to_float(depth24_from_bits(z)) of depth24_convert.comp, branch-free. - std::uint32_t quantise(std::vector& code, std::uint32_t z) { - const std::uint32_t tf = t_float(), tu = t_uint(), tb = t_bool(); - const std::uint32_t b = emit(code, op_bitcast, tu, {z}); - const std::uint32_t product = emit(code, op_f_mul, tf, {z, f32(16777215.0f)}); - const std::uint32_t rounded = ext(code, tf, glsl_round_even, {product}); - // Clamped before the conversion so an out-of-range float never reaches OpConvertFToU (undefined there). - const std::uint32_t safe = ext(code, tf, glsl_fmin, {ext(code, tf, glsl_fmax, {rounded, f32(0.0f)}), - f32(16777215.0f)}); - const std::uint32_t code_mid = emit(code, op_convert_f_to_u, tu, {safe}); - const std::uint32_t at_least_one = emit(code, op_u_greater_than_equal, tb, {b, u32(0x3f800000u)}); - const std::uint32_t code_hi = emit(code, op_select, tu, {at_least_one, u32(0xffffffu), code_mid}); - const std::uint32_t negative_or_nan = emit(code, op_u_greater_than, tb, {b, u32(0x7f800000u)}); - const std::uint32_t d = emit(code, op_select, tu, {negative_or_nan, u32(0), code_hi}); - // float(m + 1) * 2^(e - 47) with e = findMSB(d) and m = d << (23 - e); d == 0 gives 0. - const std::uint32_t e = ext(code, tu, glsl_find_umsb, {d}); - const std::uint32_t m = emit(code, op_shift_left_logical, tu, {d, emit(code, op_i_sub, tu, {u32(23), e})}); - const std::uint32_t mf = emit(code, op_convert_u_to_f, tf, {emit(code, op_i_add, tu, {m, u32(1)})}); - const std::uint32_t exponent = emit(code, op_shift_left_logical, tu, {emit(code, op_i_add, tu, {e, u32(80)}), - u32(23)}); - const std::uint32_t scale = emit(code, op_bitcast, tf, {exponent}); - const std::uint32_t value = emit(code, op_f_mul, tf, {mf, scale}); - const std::uint32_t zero = emit(code, op_i_equal, tb, {d, u32(0)}); - return emit(code, op_select, tf, {zero, f32(0.0f), value}); - } - - // Splices everything into the module. - void apply(std::vector entry_code, std::vector (*at_return)(Patch&, void*), void* ctx, - bool drop_conservative_modes) { - auto& in = m_.insts(); - std::size_t last_entry_point = 0; - for (std::size_t k = 0; k < in.size(); ++k) - if (opcode(in[k]) == op_entry_point) last_entry_point = k; - std::vector out; - out.reserve(in.size() + globals_.size() + entry_code.size() + 16); - bool imported = import_.empty(), decorated = false, declared = false; - bool in_main = false, entry_done = false; - for (std::size_t k = 0; k < in.size(); ++k) { - Inst& i = in[k]; - const std::uint32_t op = opcode(i); - if (!imported && op == op_memory_model) { - out.push_back(std::move(import_)); - imported = true; - } - if (op == op_execution_mode && i.size() >= 3 && i[1] == entry_ && drop_conservative_modes && - (i[2] == mode_depth_greater || i[2] == mode_depth_less || i[2] == mode_depth_unchanged || - i[2] == mode_depth_replacing)) - continue; // replaced by the DepthReplacing in modes_ - if (op == op_entry_point && i.size() > 2 && i[2] == entry_) { - const std::size_t names = 3 + string_words(i, 3); - for (std::uint32_t id : interface_) { - bool listed = false; - for (std::size_t w = names; w < i.size(); ++w) listed |= i[w] == id; - if (!listed) i.push_back(id); - } - fix_length(i); - } - if (!decorated && (is_global_decl(op) || op == op_function)) { - for (Inst& d : decorations_) out.push_back(std::move(d)); - decorated = true; - } - if (!declared && op == op_function) { - for (const Inst& g : globals_) out.push_back(g); // copies: type() may still read them - declared = true; - } - if (op == op_function && i.size() > 2 && i[2] == entry_) in_main = true; - if (in_main && !entry_done && op != op_function && op != op_label && op != op_variable && - op != op_line && op != op_no_line && op != 55 /* OpFunctionParameter */) { - for (Inst& c : entry_code) out.push_back(std::move(c)); - entry_done = true; - } - if (in_main && op == op_return && at_return) { - for (Inst& c : at_return(*this, ctx)) out.push_back(std::move(c)); - } - if (op == op_function_end) in_main = false; - out.push_back(std::move(i)); - if (k == last_entry_point) // execution modes follow the entry points - for (Inst& mo : modes_) out.push_back(std::move(mo)); - } - in = std::move(out); - } - -private: - Module& m_; - std::uint32_t entry_; - std::vector existing_; - std::vector globals_, decorations_, modes_; - Inst import_; - std::vector interface_; - std::vector> constants_; // type, value, id - std::uint32_t glsl_ = 0; -}; - -} // namespace spirv24 - -// Edits a pixel shader so it writes the D24-quantised (and, unless it writes depth itself, D3D-biased) depth. -// Returns the new words, or an empty vector with `why` set when the shader can't take the edit. -inline std::vector depth24_patch_fragment(const std::vector& words, - const Depth24Bias& bias, std::string& why) { - using namespace spirv24; - Module m; - if (!m.parse(words, why)) return {}; - std::uint32_t entry = 0; - for (const Inst& i : m.insts()) { - if (opcode(i) == op_entry_point && i.size() > 2 && i[1] == model_fragment) { - if (entry) { - why = "more than one fragment entry point"; - return {}; - } - entry = i[2]; - } - if (opcode(i) == op_function) break; - } - if (!entry) { - why = "no fragment entry point"; - return {}; - } - for (const Inst& i : m.insts()) { - if (opcode(i) == op_execution_mode && i.size() >= 3 && i[1] == entry && i[2] == mode_early_fragment_tests) { - why = "the shader forces early fragment tests, which ignore a FragDepth write"; - return {}; - } - if (opcode(i) == op_function) break; - } - - Patch p(m, entry); - const std::uint32_t tf = p.t_float(); - p.prime_quantise(); - std::uint32_t frag_depth = p.builtin_variable(builtin_frag_depth); - const bool shader_writes_depth = frag_depth != 0; - if (!shader_writes_depth) - frag_depth = p.variable(p.type(op_type_pointer, {storage_output, tf}), storage_output, builtin_frag_depth); - else - p.ensure_interface(frag_depth); - p.mode(mode_depth_replacing); - - std::vector entry_code; - if (!shader_writes_depth) { - std::uint32_t frag_coord = p.builtin_variable(builtin_frag_coord); - const std::uint32_t tv4 = p.type(op_type_vector, {tf, 4}); - if (!frag_coord) - frag_coord = p.variable(p.type(op_type_pointer, {storage_input, tv4}), storage_input, builtin_frag_coord); - else - p.ensure_interface(frag_coord); - const std::uint32_t coord = p.emit(entry_code, op_load, tv4, {frag_coord}); - std::uint32_t z = p.emit(entry_code, op_composite_extract, tf, {coord, 2}); - if (bias.any()) { - // In the entry block: uniform control flow, so the derivatives are defined. - const std::uint32_t dx = p.ext(entry_code, tf, glsl_fabs, {p.emit(entry_code, op_dpdx, tf, {z})}); - const std::uint32_t dy = p.ext(entry_code, tf, glsl_fabs, {p.emit(entry_code, op_dpdy, tf, {z})}); - const std::uint32_t max_slope = p.ext(entry_code, tf, glsl_fmax, {dx, dy}); - std::uint32_t amount = p.emit(entry_code, op_f_mul, tf, {p.f32(bias.slope), max_slope}); - amount = p.emit(entry_code, op_f_add, tf, {amount, p.f32(depth24_bias_constant(bias.constant))}); - if (bias.clamp > 0.0f) amount = p.ext(entry_code, tf, glsl_fmin, {amount, p.f32(bias.clamp)}); - if (bias.clamp < 0.0f) amount = p.ext(entry_code, tf, glsl_fmax, {amount, p.f32(bias.clamp)}); - z = p.emit(entry_code, op_f_add, tf, {z, amount}); - } - const std::uint32_t q = p.quantise(entry_code, z); - entry_code.push_back(make(op_store, {frag_depth, q})); - p.apply(std::move(entry_code), nullptr, nullptr, true); - } else { - struct Ctx { std::uint32_t var, tf; } ctx{frag_depth, tf}; - p.apply({}, [](Patch& patch, void* c) { - const auto& x = *static_cast(c); - std::vector code; - const std::uint32_t written = patch.emit(code, op_load, x.tf, {x.var}); - code.push_back(make(op_store, {x.var, patch.quantise(code, written)})); - return code; - }, &ctx, true); - } - return m.words(); -} - -// A pixel stage for a pipeline without one: no colour output, only the biased, quantised depth. -inline std::vector depth24_depth_only_fragment(const Depth24Bias& bias) { - using namespace spirv24; - // OpCapability Shader; OpMemoryModel Logical GLSL450; OpEntryPoint Fragment %main "main"; - // OpExecutionMode %main OriginUpperLeft; %void; %fn = void(); %main = function { label; return } - enum : std::uint32_t { id_main = 1, id_void = 2, id_fn = 3, id_label = 4, bound = 5 }; - std::vector w = {0x07230203u, 0x00010000u, 0, bound, 0}; - auto put = [&](Inst i) { w.insert(w.end(), i.begin(), i.end()); }; - put(make(op_capability, {1})); - put(make(op_memory_model, {0, 1})); - Inst ep = make(op_entry_point, {model_fragment, id_main}); - append_string(ep, "main"); - fix_length(ep); - put(ep); - put(make(op_execution_mode, {id_main, mode_origin_upper_left})); - put(make(op_type_void, {id_void})); - put(make(op_type_function, {id_fn, id_void})); - put(make(op_function, {id_void, id_main, 0, id_fn})); - put(make(op_label, {id_label})); - put(make(op_return, {})); - put(make(op_function_end, {})); - std::string why; - return depth24_patch_fragment(w, bias, why); -} - -} // namespace leonida diff --git a/runtime/src/descriptor_table.h b/runtime/src/descriptor_table.h deleted file mode 100644 index 69857c4c6..000000000 --- a/runtime/src/descriptor_table.h +++ /dev/null @@ -1,396 +0,0 @@ -#pragma once - -// The descriptor hash table for set 0, binding 2 (docs/d3d12_vulkan.md section 5.1 and docs/design.md): -// Shaders look up bindless resource/sampler indices by FNV-1a hashing the 8-dword descriptor key (T# or padded S#) -// and probing up to 8 slots in this table. Miss or fallback yields index 0. - -#include -#include -#include -#include -#include -#include -#include -#include - -namespace leonida { - -// FNV-1a constants for 32-bit dwords -inline constexpr std::uint32_t kFnvOffsetBasis = 2166136261u; -inline constexpr std::uint32_t kFnvPrime = 16777619u; -inline constexpr std::uint32_t kDescriptorProbes = 8; -inline constexpr std::uint32_t kSlotOccupiedMarker = 0xA11CA7EDu; - -// Key types: -// T# key is 8 dwords. -// S# key is 4 dwords followed by 4x 0xFFFFFFFF. -using DescriptorKey = std::array; - -inline std::uint32_t hash_descriptor_key(const std::uint32_t key[8]) { - std::uint32_t h = kFnvOffsetBasis; - for (int i = 0; i < 8; ++i) { - h = (h ^ key[i]) * kFnvPrime; - } - return h; -} - -inline std::uint32_t hash_descriptor_key(const DescriptorKey& key) { - return hash_descriptor_key(key.data()); -} - -inline DescriptorKey make_tsharp_key(const std::uint32_t tsharp[8]) { - DescriptorKey k{}; - std::memcpy(k.data(), tsharp, sizeof(DescriptorKey)); - return k; -} - -inline DescriptorKey make_ssharp_key(const std::uint32_t ssharp[4]) { - DescriptorKey k{}; - k[0] = ssharp[0]; - k[1] = ssharp[1]; - k[2] = ssharp[2]; - k[3] = ssharp[3]; - k[4] = 0xFFFFFFFFu; - k[5] = 0xFFFFFFFFu; - k[6] = 0xFFFFFFFFu; - k[7] = 0xFFFFFFFFu; - return k; -} - -// Memory layout of each entry in the table: 10 uint32s = 40 bytes. -struct DescriptorEntry { - std::uint32_t key[8] = {}; - std::uint32_t index = 0; - std::uint32_t pad = 0; // 0 when empty, kSlotOccupiedMarker when occupied -}; -static_assert(sizeof(DescriptorEntry) == 40); - -class DescriptorTable { -public: - enum class InsertResult { added, unchanged, replaced, added_with_relocation }; - - explicit DescriptorTable(std::uint32_t initial_capacity = 16) { - // Slots use nonnegative int indices internally. Larger powers also wrap the capacity counter. - if (initial_capacity > max_capacity) throw std::length_error("Descriptor table capacity exceeds slot range"); - std::uint32_t cap = 16; - while (cap < initial_capacity) cap <<= 1; - mask_ = cap - 1; - entries_.resize(cap); - } - - // Inserts or updates a key -> index mapping. - // If the key already exists in one of the 8 probe slots, its index is updated. - // Try one bounded relocation before growing. Load never exceeds 50%. - bool insert(const std::uint32_t key[8], std::uint32_t index) { - insert_or_update(key, index); - return true; - } - - // Report the change under the same lock so the GPU caller can synchronize writes to live slots. - InsertResult insert_or_update(const std::uint32_t key[8], std::uint32_t index) { - std::lock_guard lock(mutex_); - return insert_locked(key, index); - } - - bool insert(const DescriptorKey& key, std::uint32_t index) { - return insert(key.data(), index); - } - - // Queries the index associated with key. Returns 0 if not found. - std::uint32_t lookup(const std::uint32_t key[8]) const { - std::lock_guard lock(mutex_); - const std::uint32_t h = hash_descriptor_key(key); - for (std::uint32_t k = 0; k < kDescriptorProbes; ++k) { - const std::uint32_t slot = (h + k) & mask_; - const auto& entry = entries_[slot]; - if (entry.pad == kSlotOccupiedMarker && std::memcmp(entry.key, key, sizeof(entry.key)) == 0) { - return entry.index; - } - } - return 0; // Exceeded 8 probes without a match - } - - std::uint32_t lookup(const DescriptorKey& key) const { - return lookup(key.data()); - } - - bool contains(const std::uint32_t key[8]) const { - std::lock_guard lock(mutex_); - const std::uint32_t h = hash_descriptor_key(key); - for (std::uint32_t k = 0; k < kDescriptorProbes; ++k) { - const std::uint32_t slot = (h + k) & mask_; - const auto& entry = entries_[slot]; - if (entry.pad == kSlotOccupiedMarker && std::memcmp(entry.key, key, sizeof(entry.key)) == 0) { - return true; - } - } - return false; - } - - bool contains(const DescriptorKey& key) const { - return contains(key.data()); - } - - // Erases a key from the table. Returns true if the key was found and erased, false otherwise. - // Only the key's own slot changes (it becomes empty): no other entry moves. Every lookup, here and in the - // shaders (rdna2spirv.py desc_probe), compares all kDescriptorProbes slots and never stops at an empty one, so - // a hole breaks no probe chain and inserts reuse it. Keeping the other entries in place is what lets the GPU - // copy of the table take an erase while shaders still probe it (BindlessSet::flush_replaces_table). - bool erase(const std::uint32_t key[8]) { - std::lock_guard lock(mutex_); - return erase_locked(key); - } - - bool erase(const DescriptorKey& key) { - return erase(key.data()); - } - - void clear() { - std::lock_guard lock(mutex_); - std::fill(entries_.begin(), entries_.end(), DescriptorEntry{}); - occupied_count_ = 0; - all_changed_ = true; - changed_slots_.clear(); - } - - std::size_t size() const { - std::lock_guard lock(mutex_); - return occupied_count_; - } - - std::size_t capacity() const { - std::lock_guard lock(mutex_); - return entries_.size(); - } - - std::uint32_t mask() const { - std::lock_guard lock(mutex_); - return mask_; - } - - std::size_t size_dwords() const { - std::lock_guard lock(mutex_); - return 1 + entries_.size() * 10; - } - - std::size_t size_bytes() const { - return size_dwords() * sizeof(std::uint32_t); - } - - // Exports the table buffer format consumed by SPIR-V set 0, binding 2. - // Word 0 is mask; followed by entries[mask + 1] of 10 dwords: key[8], index, pad. - std::vector build_gpu_buffer(bool clear_pad = false) const { - std::lock_guard lock(mutex_); - std::vector out(1 + entries_.size() * 10, 0); - out[0] = mask_; - for (std::size_t s = 0; s < entries_.size(); ++s) { - const std::size_t base = 1 + s * 10; - std::memcpy(&out[base], entries_[s].key, sizeof(entries_[s].key)); - out[base + 8] = entries_[s].index; - out[base + 9] = clear_pad ? 0 : entries_[s].pad; - } - return out; - } - - // What a shader's copy of the table needs re-uploaded since the last take_changes(). - struct Changes { - bool all = false; // the mask (table grew or was cleared): every slot and the header - std::vector slots; // slots whose 10 dwords changed, in no particular order - }; - - Changes take_changes() { - std::lock_guard lock(mutex_); - Changes changes; - changes.all = all_changed_; - changes.slots = std::move(changed_slots_); - changed_slots_.clear(); - all_changed_ = false; - return changes; - } - - // One slot's 10 dwords (key[8], index, pad) to `dest`; false when the slot is out of range. - bool read_slot(std::uint32_t slot, std::uint32_t* dest) const { return read_slots(slot, 1, dest); } - - // `count` consecutive slots' 10 dwords each to `dest`, under one lock; false when any is out of range. - bool read_slots(std::uint32_t first, std::uint32_t count, std::uint32_t* dest) const { - if (count > 0 && !dest) return false; - std::lock_guard lock(mutex_); - if (first > entries_.size() || count > entries_.size() - first) return false; - for (std::uint32_t i = 0; i < count; ++i) { - const DescriptorEntry& entry = entries_[first + i]; - std::memcpy(dest + i * 10, entry.key, sizeof(entry.key)); - dest[i * 10 + 8] = entry.index; - dest[i * 10 + 9] = entry.pad; - } - return true; - } - - // Serializes directly into `dest` (must hold at least size_bytes()) without allocating a temporary vector. - void write_to_buffer(void* dest, bool clear_pad = false) const { - if (!dest) return; - std::lock_guard lock(mutex_); - auto* out = static_cast(dest); - std::memcpy(out, &mask_, sizeof(mask_)); - out += sizeof(mask_); - for (const auto& entry : entries_) { - std::uint32_t slot[10]; - std::memcpy(slot, entry.key, sizeof(entry.key)); - slot[8] = entry.index; - slot[9] = clear_pad ? 0 : entry.pad; - std::memcpy(out, slot, sizeof(slot)); - out += sizeof(slot); - } - } - -private: - void mark(std::uint32_t slot) { changed_slots_.push_back(slot); } - - // All eight slots for the incoming key are occupied. Try moving one resident - // to the first empty slot beyond that window, within its own eight probes. - // A later hole is farther from every resident, so failure here is final for a single move. - // `moved_to` receives the hole the resident moved into, so the caller can mark that slot changed too. - static int make_probe_slot(std::vector& entries, std::uint32_t hash, - std::uint32_t* moved_to = nullptr) { - const auto mask = static_cast(entries.size() - 1); - for (auto offset = kDescriptorProbes; offset < 2 * kDescriptorProbes - 1; ++offset) { - const auto hole = (hash + offset) & mask; - if (entries[hole].pad == kSlotOccupiedMarker) continue; - for (auto k = kDescriptorProbes; k > 0; --k) { - const auto slot = (hash + k - 1) & mask; - const auto home = hash_descriptor_key(entries[slot].key); - if (((hole - home) & mask) < kDescriptorProbes) { - entries[hole] = entries[slot]; - if (moved_to) *moved_to = hole; - return static_cast(slot); // caller immediately overwrites the resident - } - } - break; - } - return -1; - } - - InsertResult insert_locked(const std::uint32_t key[8], std::uint32_t index) { - while (true) { - const std::uint32_t h = hash_descriptor_key(key); - int empty_slot = -1; - - for (std::uint32_t k = 0; k < kDescriptorProbes; ++k) { - const std::uint32_t slot = (h + k) & mask_; - auto& entry = entries_[slot]; - if (entry.pad == kSlotOccupiedMarker) { - if (std::memcmp(entry.key, key, sizeof(entry.key)) == 0) { - if (entry.index == index) return InsertResult::unchanged; - entry.index = index; - mark(slot); - return InsertResult::replaced; - } - } else if (empty_slot < 0) { - empty_slot = static_cast(slot); - } - } - - if ((occupied_count_ + 1) * 2 > entries_.size()) { - grow_locked(); - continue; - } - - // Nine distinct keys with the same full hash can never fit the shader's eight probes, - // regardless of capacity. Refuse before allocating ever larger tables. - if (empty_slot < 0) { - std::uint32_t same_hash = 0; - for (std::uint32_t k = 0; k < kDescriptorProbes; ++k) { - const auto& entry = entries_[(h + k) & mask_]; - if (hash_descriptor_key(entry.key) == h) ++same_hash; - } - if (same_hash == kDescriptorProbes) - throw std::length_error("Descriptor hash collision exceeds shader probe limit"); - } - const bool relocate = empty_slot < 0; - std::uint32_t moved_to = 0; - if (relocate) empty_slot = make_probe_slot(entries_, h, &moved_to); - if (empty_slot >= 0) { - auto& entry = entries_[empty_slot]; - std::memcpy(entry.key, key, sizeof(entry.key)); - entry.index = index; - entry.pad = kSlotOccupiedMarker; - ++occupied_count_; - if (relocate) mark(moved_to); - mark(std::uint32_t(empty_slot)); - return relocate ? InsertResult::added_with_relocation : InsertResult::added; - } - - grow_locked(); - } - } - - bool erase_locked(const std::uint32_t key[8]) { - const std::uint32_t h = hash_descriptor_key(key); - std::uint32_t found_slot = 0; - bool found = false; - for (std::uint32_t k = 0; k < kDescriptorProbes; ++k) { - const std::uint32_t slot = (h + k) & mask_; - const auto& entry = entries_[slot]; - if (entry.pad == kSlotOccupiedMarker && std::memcmp(entry.key, key, sizeof(entry.key)) == 0) { - found_slot = slot; - found = true; - break; - } - } - if (!found) return false; - - // No backward shift: see erase(). - entries_[found_slot] = DescriptorEntry{}; - mark(found_slot); - --occupied_count_; - return true; - } - - void grow_locked() { - if (entries_.size() >= max_capacity) throw std::length_error("Descriptor table capacity exhausted"); - std::uint32_t new_cap = static_cast(entries_.size() * 2); - while (true) { - std::vector new_entries(new_cap); - const std::uint32_t new_mask = new_cap - 1; - bool rehash_ok = true; - - for (const auto& old : entries_) { - if (old.pad != kSlotOccupiedMarker) continue; - const std::uint32_t h = hash_descriptor_key(old.key); - int slot = -1; - for (std::uint32_t k = 0; k < kDescriptorProbes; ++k) { - const std::uint32_t s = (h + k) & new_mask; - if (new_entries[s].pad != kSlotOccupiedMarker) { - slot = static_cast(s); - break; - } - } - if (slot < 0) slot = make_probe_slot(new_entries, h); - if (slot < 0) { - rehash_ok = false; - break; - } - new_entries[slot] = old; - } - - if (rehash_ok) { - entries_ = std::move(new_entries); - mask_ = new_mask; - all_changed_ = true; - changed_slots_.clear(); - break; - } - if (new_cap >= max_capacity) throw std::length_error("Descriptor probe range exhausted"); - new_cap *= 2; - } - } - - static constexpr std::uint32_t max_capacity = std::uint32_t{1} << 31; - mutable std::mutex mutex_; - std::uint32_t mask_ = 15; - std::vector entries_; - std::size_t occupied_count_ = 0; - bool all_changed_ = false; // clear() or a grow: the mask and every slot changed - std::vector changed_slots_; // slots inserted, replaced or moved since take_changes() -}; - -} // namespace leonida diff --git a/runtime/src/frame_pacer.h b/runtime/src/frame_pacer.h deleted file mode 100644 index fa9c20df1..000000000 --- a/runtime/src/frame_pacer.h +++ /dev/null @@ -1,467 +0,0 @@ -#pragma once - -// Frame pacing for the Xbox presentation path (docs/d3d12_vulkan.md section 4.5): what SetFrameIntervalX, -// ScheduleFrameEventX, WaitFrameEventX and GetFrameStatisticsX do, and the token check and flip bookkeeping that -// PresentX needs. No Vulkan and no Windows headers: time comes from an injectable FrameClock, so the tests drive it -// with a fake clock and the real runtime uses a steady high-resolution timer (a host vblank source can replace it). -// -// What is known and what is ours. From the public GDKX samples (section 4.5): the call order, the argument counts, that -// the interval call takes an allowed frame latency (buffer count - 1 in one sample, 1 in another), that the origin -// event is scheduled once and waited on every frame, that the wait yields a token that PresentX carries, and that -// frame events must be registered again after ResumeX. Everything below the call shapes is our own model, chosen to -// be deterministic and to behave like the samples expect; none of it is measured on the console: -// * An interval is a period in microseconds (the real enum values are unmeasured). -// * Vblanks happen at epoch + n * period (n = 1, 2, ...), the epoch being the time of SetFrameIntervalX. The -// first origin after ScheduleFrameEventX is the next vblank. The origin event of vblank n is signalled -// offset microseconds after it (ScheduleFrameEventX's offset). -// * A frame is "in flight" from PresentX until the vblank that shows it. Frames show one per vblank, in order. -// WaitFrameEventX does not return while `latency` frames are in flight. A frame presented while the origin event -// is not armed is not paced (PresentX does not hold it for a vblank): it shows at once and is never in flight. -// * A wait that comes late (after the next origin already passed) returns at once with the newest passed origin; -// the missed origins are skipped, not queued. -// * Tokens are 1, 2, 3, ... (0 is the null token), one per successful wait, never reused, across suspend/resume. -// * A frame is due at the vblank after the origin that handed out its token; a PresentX after that vblank is late by -// the time since it (present_timing), and ImmediateThresholdPercent decides whether that lateness is shown at once -// (decide_present_sync). -// -// Uncapped (set_uncapped; LEONIDA_PRESENT_UNCAP in the shim): the registration calls keep working and waits keep -// handing out one token each, but a wait never blocks — no vblank grid, no latency throttle — and a presented -// frame counts as shown at once. The frame rate is then the title's own; the error surface (nothing registered, -// suspended) is unchanged. - -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace leonida { - -// HRESULT values as plain numbers, so this header stands alone. -namespace pacer_hr { -inline constexpr std::int32_t ok = 0; -inline constexpr std::int32_t false_ = 1; // S_FALSE -inline constexpr std::int32_t invalid_arg = std::int32_t(0x80070057); // E_INVALIDARG -inline constexpr std::int32_t invalid_state = std::int32_t(0x8007139F); // HRESULT_FROM_WIN32(ERROR_INVALID_STATE) -inline constexpr std::int32_t timeout = std::int32_t(0x80070102); // HRESULT_FROM_WIN32(WAIT_TIMEOUT) -} // namespace pacer_hr - -inline constexpr std::uint64_t no_deadline = std::numeric_limits::max(); -inline constexpr std::uint32_t infinite_timeout_ms = 0xFFFFFFFFu; // INFINITE - -class FrameClock { -public: - virtual ~FrameClock() = default; - virtual std::uint64_t now_us() = 0; - // Called with `lock` held on the pacer's mutex. Returns when `cv` is notified, `deadline_us` (in now_us() time; - // no_deadline for none) has passed, or spuriously; the caller re-checks its condition. - virtual void wait(std::unique_lock& lock, std::condition_variable& cv, std::uint64_t deadline_us) = 0; - // The pacer gives a function that takes its mutex and notifies; a fake clock calls it when time moves. - virtual void set_wake(std::function wake) { (void)wake; } -}; - -// Real time: std::chrono::steady_clock (QueryPerformanceCounter on Windows). -class SteadyFrameClock final : public FrameClock { -public: - std::uint64_t now_us() override { - return std::uint64_t(std::chrono::duration_cast( - std::chrono::steady_clock::now() - start_).count()); - } - void wait(std::unique_lock& lock, std::condition_variable& cv, std::uint64_t deadline_us) override { - if (deadline_us == no_deadline) cv.wait(lock); - else cv.wait_until(lock, start_ + std::chrono::microseconds(deadline_us)); - } - -private: - std::chrono::steady_clock::time_point start_ = std::chrono::steady_clock::now(); -}; - -// Time that only moves when the test says so. A pacer waiting on it blocks until advance_us() is called. -class ManualFrameClock final : public FrameClock { -public: - std::uint64_t now_us() override { return now_.load(); } - void wait(std::unique_lock& lock, std::condition_variable& cv, std::uint64_t) override { cv.wait(lock); } - void set_wake(std::function wake) override { - std::lock_guard guard(wake_mutex_); - wake_ = std::move(wake); - } - void advance_us(std::uint64_t microseconds) { - now_ += microseconds; - // Called under the lock, so a pacer that is being destroyed (set_wake({})) is never woken after it is gone. - std::lock_guard guard(wake_mutex_); - if (wake_) wake_(); - } - -private: - std::atomic now_{0}; - std::mutex wake_mutex_; - std::function wake_; -}; - -// Provisional definitions of ours: the real constants and layouts of the console API are unmeasured. -inline constexpr std::uint32_t frame_event_origin = 0; -// Statistics types (bit mask). Interval and render entries are never produced here. -inline constexpr std::uint32_t stat_frame_interval = 0x01; -inline constexpr std::uint32_t stat_frame_event = 0x02; -inline constexpr std::uint32_t stat_render = 0x04; -inline constexpr std::uint32_t stat_present = 0x08; -inline constexpr std::uint32_t stat_display = 0x10; - -// How a frame that is being presented is put on the display. -enum class PresentSync { - vblank, // at the next vblank (FIFO) - immediate, // now, mid-scan (a tear) -}; - -// D3D12XBOX_PRESENT_PARAMETERS::ImmediateThresholdPercent (docs/d3d12_vulkan.md section 4.5): a frame that missed its -// vblank is flipped at once, mid-scan, when the scan has not got further than `threshold_percent` of the screen, -// instead of waiting a whole interval. `late_by_us` is how long after the vblank the frame was ready (0: on time), -// `interval_us` the refresh period; the vblank grid is regular, so the scan is `late_by_us % interval_us` of the way -// down. 0 (or a negative or NaN value) never tears, 100 or more tears wherever the scan is. A frame on time, or an -// interval of 0 (unpaced), is never torn. Pure, so the tests can sweep it. -inline PresentSync decide_present_sync(std::uint64_t late_by_us, std::uint32_t interval_us, float threshold_percent) { - if (!(threshold_percent > 0.0f) || late_by_us == 0 || interval_us == 0) return PresentSync::vblank; - const double scanned_percent = 100.0 * double(late_by_us % interval_us) / double(interval_us); - return scanned_percent <= double(std::min(threshold_percent, 100.0f)) ? PresentSync::immediate - : PresentSync::vblank; -} - -// Where the scan of a frame that was shown mid-scan stood, in percent (0 for a frame shown at a vblank). -inline float scan_percent(std::uint64_t late_by_us, std::uint32_t interval_us) { - return interval_us ? float(100.0 * double(late_by_us % interval_us) / double(interval_us)) : 0.0f; -} - -struct FrameStatistic { - std::uint32_t type = 0; // one stat_* bit - std::uint32_t plane_index = 0; - std::uint64_t token = 0; - std::uint64_t time_us = 0; // pacer clock - float percent_scanned = 0.0f; // display entries: where the scan was when the frame came up (0 at a vblank) -}; - -class FramePacer { -public: - explicit FramePacer(FrameClock& clock) : clock_(clock) { - clock_.set_wake([this] { - { std::lock_guard guard(mutex_); } - cv_.notify_all(); - }); - } - ~FramePacer() { - clock_.set_wake({}); - { - std::lock_guard guard(mutex_); - shutdown_ = true; - } - cv_.notify_all(); - std::unique_lock lock(mutex_); // waiters leave before the members go - cv_.wait(lock, [this] { return waiters_ == 0; }); - } - FramePacer(const FramePacer&) = delete; - FramePacer& operator=(const FramePacer&) = delete; - - // SetFrameIntervalX(output, interval, latency, flags). `period_us` is the interval as a period; `latency` is - // the number of frames allowed in flight (0 counts as 1). The vblank grid is re-based: its epoch is now. A - // scheduled origin event stays armed (with its offset, kept below the new period) and its next origin is one - // new period from now; waiters blocked on the old grid pick the new one up. - std::int32_t set_frame_interval(std::uint32_t period_us, std::uint32_t latency, std::uint32_t flags) { - (void)flags; - if (period_us == 0) return pacer_hr::invalid_arg; - std::lock_guard guard(mutex_); - if (suspended_) return pacer_hr::invalid_state; - period_us_ = period_us; - latency_ = std::max(latency, 1u); - epoch_us_ = clock_.now_us(); - interval_set_ = true; - offset_us_ = std::min(offset_us_, period_us - 1); - last_origin_ = 0; // origin 0 is the epoch itself, which has passed - cv_.notify_all(); - return pacer_hr::ok; - } - - // ScheduleFrameEventX(event, offset, ..., flags). Only the origin event exists here. - std::int32_t schedule_frame_event(std::uint32_t event, std::uint32_t offset_us, std::uint32_t flags) { - (void)flags; - if (event != frame_event_origin) return pacer_hr::invalid_arg; - std::lock_guard guard(mutex_); - if (suspended_ || !interval_set_) return pacer_hr::invalid_state; - if (offset_us >= period_us_) return pacer_hr::invalid_arg; - offset_us_ = offset_us; - armed_ = true; - // The first origin is the next one that has not come yet: origin n is due at epoch + n * period + offset. - const std::uint64_t now = clock_.now_us(); - last_origin_ = now >= epoch_us_ + offset_us_ ? std::int64_t((now - epoch_us_ - offset_us_) / period_us_) : 0; - cv_.notify_all(); - return pacer_hr::ok; - } - - // WaitFrameEventX(event, timeout, ..., flags, &token). Blocks until the next origin, and while `latency` frames - // are in flight. pacer_hr::timeout when `timeout_ms` passes first (infinite_timeout_ms: never); the token is left - // alone then. invalid_state when nothing is registered, the pacer is suspended, or one of those happens while waiting. - std::int32_t wait_frame_event(std::uint32_t event, std::uint32_t timeout_ms, std::uint32_t flags, - std::uint64_t* token) { - (void)flags; - if (event != frame_event_origin || !token) return pacer_hr::invalid_arg; - std::unique_lock lock(mutex_); - ++waiters_; - const std::int32_t result = wait_locked(lock, timeout_ms, token); - if (--waiters_ == 0) cv_.notify_all(); - return result; - } - - // GetFrameStatisticsX(token, type_mask, &count, array). `count` is the room in `out` on entry and the number of - // entries written on return. S_OK when every producible requested type was written (event, present, display), - // S_FALSE with count 0 or fewer when they are not (there yet, or the token is unknown or has aged out of the - // last 64). With a null `out`, count only receives how many entries are available. - std::int32_t get_frame_statistics(std::uint64_t token, std::uint32_t type_mask, std::uint32_t* count, - FrameStatistic* out) { - if (!count) return pacer_hr::invalid_arg; - std::lock_guard guard(mutex_); - retire_locked(clock_.now_us()); - const Record* record = nullptr; - for (const Record& r : records_) - if (r.token == token) record = &r; - FrameStatistic found[3]; - std::uint32_t n = 0, expected = 0; - auto add = [&](std::uint32_t type, bool present, std::uint64_t time) { - if (!(type_mask & type)) return; - ++expected; - if (!record || !present) return; - found[n++] = FrameStatistic{type, 0, token, time, type == stat_display ? record->percent_scanned : 0.0f}; - }; - if (record) { - add(stat_frame_event, true, record->origin_us); - add(stat_present, record->presented, record->present_us); - add(stat_display, record->displayed, record->display_us); - } else { - expected = ((type_mask & stat_frame_event) ? 1u : 0u) + ((type_mask & stat_present) ? 1u : 0u) + - ((type_mask & stat_display) ? 1u : 0u); - } - if (!out) { - const std::uint32_t available = n; - *count = available; - return available && available == expected ? pacer_hr::ok : pacer_hr::false_; - } - const std::uint32_t written = std::min(n, *count); - for (std::uint32_t i = 0; i < written; ++i) out[i] = found[i]; - *count = written; - return written && written == expected ? pacer_hr::ok : pacer_hr::false_; - } - - // Queue side. check_present_token before the frame is presented, commit_present_token after it was queued. - // What real hardware does with a null, repeated or out-of-order token is unmeasured, and a title that presents - // with Token = 0 (a loading screen), re-presents with one token, or presents from a render thread out of order - // must not freeze. So the only refusal is a token that was never handed out (invalid_arg, which is a bug in the - // caller); null, stale (older than the last presented) and repeated tokens return ok and say which kind they - // were in `issue`, so the caller can log it. invalid_state while suspended. - enum class TokenIssue { none, null_token, stale, repeated }; - std::int32_t check_present_token(std::uint64_t token, TokenIssue* issue = nullptr) { - std::lock_guard guard(mutex_); - if (issue) *issue = TokenIssue::none; - if (suspended_) return pacer_hr::invalid_state; - if (token > issued_) return pacer_hr::invalid_arg; - if (issue) { - if (token == 0) *issue = TokenIssue::null_token; - else if (token == last_presented_) *issue = TokenIssue::repeated; - else if (token < last_presented_) *issue = TokenIssue::stale; - } - return pacer_hr::ok; - } - // How late the frame of `token` is if it is presented now (see the model above). late_us stays 0 when the frame - // could not be shown at once anyway: unpaced, uncapped, null or unknown token, or earlier frames still waiting - // for their vblank (a flip cannot overtake them), or the token was already presented or is older than the last - // presented (a repeated or stale token never tears). - struct PresentTiming { - std::uint64_t late_us = 0; - std::uint32_t period_us = 0; // 0: unpaced - }; - PresentTiming present_timing(std::uint64_t token) { - std::lock_guard guard(mutex_); - PresentTiming timing; - if (!interval_set_ || uncapped_ || !token) return timing; - const std::uint64_t now = clock_.now_us(); - retire_locked(now); - timing.period_us = period_us_; - if (!pending_.empty()) return timing; - for (const Record& r : records_) - if (r.token == token && !r.presented && token > last_presented_ && now > r.due_us) - timing.late_us = now - r.due_us; - return timing; - } - - // `sync` immediate: the frame is shown at once (display time = present time) instead of at the next vblank, and - // percent_scanned is the lateness measured at this commit, so it agrees with the display time. The caller got - // `sync` from decide_present_sync and the presenter confirmed it. - void commit_present_token(std::uint64_t token, std::uint32_t plane_count, PresentSync sync = PresentSync::vblank) { - (void)plane_count; - std::lock_guard guard(mutex_); - const std::uint64_t now = clock_.now_us(); - retire_locked(now); - last_presented_ = std::max(last_presented_, token); - if (!interval_set_ || !armed_ || uncapped_) { // not paced or uncapped: shows at once - for (Record& r : records_) - if (r.token == token) { r.presented = r.displayed = true; r.present_us = r.display_us = now; } - return; - } - // The vblank after now, and not before the one after the previous queued frame. - const std::uint64_t since = now > epoch_us_ ? now - epoch_us_ : 0; - std::uint64_t flip = epoch_us_ + (since / period_us_ + 1) * period_us_; - if (!pending_.empty()) flip = std::max(flip, pending_.back().flip_us + period_us_); - float percent = 0.0f; - if (sync == PresentSync::immediate && pending_.empty()) { - flip = now; - std::uint64_t late_us = 0; - for (const Record& r : records_) - if (r.token == token && now > r.due_us) late_us = now - r.due_us; - percent = scan_percent(late_us, period_us_); - ++immediate_presents_; - } - pending_.push_back(Pending{token, flip, percent}); - for (Record& r : records_) - if (r.token == token) { r.presented = true; r.present_us = now; } - retire_locked(now); - cv_.notify_all(); - } - // A blank present (no planes) carries no token: it is only counted as a frame to show. With no interval set, - // the origin event not armed or the cap off it is not paced: it shows at once and is not counted. - void note_untokened_present() { - std::lock_guard guard(mutex_); - if (!interval_set_ || !armed_ || uncapped_) return; - const std::uint64_t now = clock_.now_us(); - retire_locked(now); - const std::uint64_t since = now > epoch_us_ ? now - epoch_us_ : 0; - std::uint64_t flip = epoch_us_ + (since / period_us_ + 1) * period_us_; - if (!pending_.empty()) flip = std::max(flip, pending_.back().flip_us + period_us_); - pending_.push_back(Pending{0, flip, 0.0f}); - cv_.notify_all(); - } - - // SuspendX: presentation stops, the registration and the frames in flight are dropped, waiters fail. - void suspend() { - std::lock_guard guard(mutex_); - suspended_ = true; - interval_set_ = armed_ = false; - pending_.clear(); - cv_.notify_all(); - } - // ResumeX: presents work again, but the interval and the origin event must be set up again. - void resume() { - std::lock_guard guard(mutex_); - suspended_ = false; - interval_set_ = armed_ = false; - cv_.notify_all(); - } - - bool suspended() const { std::lock_guard guard(mutex_); return suspended_; } - std::uint64_t tokens_issued() const { std::lock_guard guard(mutex_); return issued_; } - std::uint32_t frames_in_flight() { - std::lock_guard guard(mutex_); - retire_locked(clock_.now_us()); - return std::uint32_t(pending_.size()); - } - // Frames that were flipped mid-scan because of ImmediateThresholdPercent. - std::uint64_t immediate_presents() const { std::lock_guard guard(mutex_); return immediate_presents_; } - std::uint32_t period_us() const { std::lock_guard guard(mutex_); return period_us_; } - bool registered() const { std::lock_guard guard(mutex_); return interval_set_ && armed_; } - - // The fps cap off (LEONIDA_PRESENT_UNCAP; see the top comment): waits never block and presents count as shown - // at once. Registration and suspension keep meaning what they did; the flag survives suspend/resume. - void set_uncapped(bool on) { std::lock_guard guard(mutex_); uncapped_ = on; } - bool uncapped() const { std::lock_guard guard(mutex_); return uncapped_; } - -private: - struct Pending { - std::uint64_t token; - std::uint64_t flip_us; - float percent_scanned; // where the scan was for a frame shown mid-scan, else 0 - }; - struct Record { - std::uint64_t token = 0, origin_us = 0, present_us = 0, display_us = 0; - std::uint64_t due_us = 0; // vblank after this token's origin, fixed when issued - float percent_scanned = 0.0f; - bool presented = false, displayed = false; - }; - - // Frames whose vblank has come are shown. - void retire_locked(std::uint64_t now) { - while (!pending_.empty() && pending_.front().flip_us <= now) { - for (Record& r : records_) - if (r.token == pending_.front().token && pending_.front().token) { - r.displayed = true; - r.display_us = pending_.front().flip_us; - r.percent_scanned = pending_.front().percent_scanned; - } - pending_.pop_front(); - } - } - - std::int32_t wait_locked(std::unique_lock& lock, std::uint32_t timeout_ms, std::uint64_t* token) { - const std::uint64_t start = clock_.now_us(); - const std::uint64_t give_up = timeout_ms == infinite_timeout_ms ? no_deadline - : start + std::uint64_t(timeout_ms) * 1000; - for (;;) { - if (shutdown_ || suspended_ || !interval_set_ || !armed_) return pacer_hr::invalid_state; - const std::uint64_t now = clock_.now_us(); - retire_locked(now); - if (uncapped_) { // no vblank grid and no latency throttle: a token at once, due now - *token = ++issued_; - Record record; - record.token = *token; - record.origin_us = now; - record.due_us = now; - records_.push_back(record); - if (records_.size() > 64) records_.pop_front(); - return pacer_hr::ok; - } - const std::uint64_t first = epoch_us_ + offset_us_; // origin 0 - const std::int64_t next = last_origin_ + 1; - const std::uint64_t next_us = first + std::uint64_t(next) * period_us_; - std::uint64_t wake = next_us; - if (now >= next_us) { - if (pending_.size() < latency_) { - const std::int64_t newest = std::int64_t((now - first) / period_us_); - const std::int64_t origin = std::max(next, newest); - last_origin_ = origin; - *token = ++issued_; - Record record; - record.token = *token; - record.origin_us = first + std::uint64_t(origin) * period_us_; - record.due_us = record.origin_us - offset_us_ + period_us_; - records_.push_back(record); - if (records_.size() > 64) records_.pop_front(); - return pacer_hr::ok; - } - wake = pending_.front().flip_us; // blocked by the latency: until the oldest frame is shown - } - if (give_up != no_deadline && now >= give_up) return pacer_hr::timeout; - clock_.wait(lock, cv_, give_up == no_deadline ? wake : std::min(wake, give_up)); - } - } - - FrameClock& clock_; - mutable std::mutex mutex_; - std::condition_variable cv_; - bool shutdown_ = false; - std::uint32_t waiters_ = 0; - - bool suspended_ = false; - bool interval_set_ = false; - bool armed_ = false; - bool uncapped_ = false; - std::uint32_t period_us_ = 0; - std::uint32_t latency_ = 1; - std::uint32_t offset_us_ = 0; - std::uint64_t epoch_us_ = 0; - std::int64_t last_origin_ = 0; // origin 0 is the epoch itself, which has passed - std::uint64_t issued_ = 0; - std::uint64_t last_presented_ = 0; - std::uint64_t immediate_presents_ = 0; - std::deque pending_; - std::deque records_; -}; - -} // namespace leonida diff --git a/runtime/src/gfx10_descriptors.h b/runtime/src/gfx10_descriptors.h deleted file mode 100644 index b225cddef..000000000 --- a/runtime/src/gfx10_descriptors.h +++ /dev/null @@ -1,708 +0,0 @@ -#pragma once - -// GFX10 resource descriptors: the T# (image, 8 dwords), S# (sampler, 4 dwords) and V# (buffer, 4 dwords) the -// console's shaders load from descriptor heaps. Translated shaders hash a T# or S# to find its bindless index and -// dereference a V# (docs/d3d12_vulkan.md sections 3.4, 5.1 and 5.3). This header writes them for Create*View and -// CreateSampler, reads them back when a heap is scanned, and maps what they say to Vulkan. It needs the Vulkan -// headers only. -// -// Where the layout comes from: -// - Field positions: Mesa's register database, src/amd/registers/gfx10-rsrc.json, the SQ_IMG_RSRC_WORD0..7, -// SQ_IMG_SAMP_WORD0..3 and SQ_BUF_RSRC_WORD0..3 types with their gfx103 variants (RDNA2). The comments below -// name those fields. -// - Enum values in the fields: Mesa's gfx6.json (SQ_RSRC_IMG_TYPE, SQ_SEL_XYZW01, SQ_TEX_CLAMP, SQ_TEX_XY_FILTER, -// SQ_TEX_MIP_FILTER, SQ_TEX_DEPTH_COMPARE, SQ_TEX_BORDER_COLOR, SQ_IMG_FILTER_TYPE). -// - Which value goes into which field: Mesa's src/amd/common/ac_descriptors.c (ac_build_gfx10_texture_descriptor, -// ac_build_sampler_descriptor, ac_build_buffer_descriptor) and radv's radv_image_view.c and radv_sampler.c. -// - Formats: the GFX10_FORMAT enum, which tools/gfx10_formats.json holds too. A format names its channel sizes -// from the top bit down, and says nothing about which channel is red (src/amd/common/gfx10_format_table.py); -// that is DST_SEL's job. -// Mesa is MIT-licensed; only positions and values are taken from it. What this repository measured agrees with -// it: tools/rdna2spirv.py reads the T# FORMAT at word 1 bits 28:20, the V# base as word 0 | (word 1 & 0xFFFF) -// << 32, its stride at word 1 bits 29:16, NUM_RECORDS in word 2 and FORMAT and DST_SEL at word 3 bits 18:12 and -// 11:0, and runtime/test/shaders/cs_imgstore.asm builds T#s with word 1 = FORMAT << 20. -// -// Only what a Vulkan view or sampler needs is encoded. Every other bit (tiling mode, compression metadata, -// performance hints, RESOURCE_LEVEL) is written as zero and ignored when decoding: no hardware reads these -// descriptors, and what the console's driver puts in those bits is not known. - -#include - -#include -#include -#include -#include - -namespace leonida::gfx10 { - -using ImageWords = std::array; // a T# -using SamplerWords = std::array; // an S# -using BufferWords = std::array; // a V# -using Swizzle = std::array; // DST_SEL_X..W - -namespace detail { - -constexpr std::uint32_t field(std::uint32_t value, unsigned low, unsigned width) { - return (value & ((1u << width) - 1)) << low; -} - -constexpr std::uint32_t get(std::uint32_t word, unsigned low, unsigned width) { - return (word >> low) & ((1u << width) - 1); -} - -// Mesa's util_unsigned_fixed and util_signed_fixed with 8 fraction bits, after its CLAMP. A NaN becomes `low`. -inline float clamped(float value, float low, float high) { - return value > low ? (value < high ? value : high) : low; -} - -inline std::uint32_t unsigned_fixed(float value, float low, float high) { - return std::uint32_t(clamped(value, low, high) * 256.0f); -} - -inline std::uint32_t signed_fixed(float value, float low, float high) { - return std::uint32_t(std::int32_t(clamped(value, low, high) * 256.0f)); -} - -} // namespace detail - -// SQ_SEL_XYZW01: what one DST_SEL field selects. 2 and 3 are reserved. -inline constexpr std::uint8_t select_zero = 0, select_one = 1, select_x = 4, select_y = 5, select_z = 6, select_w = 7; -inline constexpr Swizzle identity_swizzle{select_x, select_y, select_z, select_w}; - -inline constexpr bool valid_swizzle(const Swizzle& swizzle) { - return std::all_of(swizzle.begin(), swizzle.end(), [](std::uint8_t s) { return s <= 7 && s != 2 && s != 3; }); -} - -// ---- T#: SQ_IMG_RSRC_WORD0..7 ---- - -// SQ_RSRC_IMG_TYPE (WORD3.TYPE). 0..7 are reserved, which is how a 32-byte heap slot holding a V# is told apart. -enum class ImageType : std::uint32_t { - image_1d = 8, - image_2d = 9, - image_3d = 10, - cube = 11, - image_1d_array = 12, - image_2d_array = 13, - image_2d_msaa = 14, - image_2d_msaa_array = 15, -}; - -inline constexpr bool multisampled(ImageType type) { - return type == ImageType::image_2d_msaa || type == ImageType::image_2d_msaa_array; -} - -// What a T# says. decode() returns the normal form: depth is 1 unless the type is 3D, layer_count is 1 for 3D, -// samples is 1 unless the type is multisampled, and a multisampled image has one mip. -struct Image { - std::uint64_t address = 0; // console VA of the image; the T# keeps it in 256-byte units (48 bits) - std::uint32_t format = 0; // GFX10_FORMAT_* code, 9 bits - ImageType type = ImageType::image_2d; - std::uint32_t width = 1; // of mip 0, 1..16384 - std::uint32_t height = 1; - std::uint32_t depth = 1; // of mip 0, for 3D: 1..8192 - std::uint32_t first_layer = 0; // arrays and cubes (a cube's layers are its faces, six to a cube) - std::uint32_t layer_count = 1; - std::uint32_t first_mip = 0; // the view's range - std::uint32_t mip_count = 1; - std::uint32_t resource_mips = 1; // of the whole resource - std::uint32_t samples = 1; // a power of two - Swizzle swizzle = identity_swizzle; - float min_lod = 0.0f; // the view's LOD clamp, 0..15 in steps of 1/256 (D3D12 ResourceMinLODClamp) - bool operator==(const Image&) const = default; -}; - -// As ac_build_gfx10_texture_descriptor and ac_set_mutable_tex_desc_fields fill it: -// WORD0 BASE_ADDRESS = address >> 8 -// WORD1 BASE_ADDRESS_HI [7:0] = address >> 40, MIN_LOD [19:8] (4.8 fixed), FORMAT [28:20], WIDTH_LO [31:30] -// WORD2 WIDTH_HI [11:0], HEIGHT [27:14] (width - 1 and height - 1) -// WORD3 DST_SEL_X/Y/Z/W [11:0], BASE_LEVEL [15:12], LAST_LEVEL [19:16], TYPE [31:28] -// WORD4 DEPTH [12:0] = depth - 1 for 3D, else the last layer; BASE_ARRAY [28:16] = the first layer -// WORD5 MAX_MIP [7:4] = resource mips - 1 -// A multisampled image has BASE_LEVEL 0 and log2(samples) in LAST_LEVEL and MAX_MIP. -inline ImageWords encode(const Image& image) { - using detail::field; - const bool msaa = multisampled(image.type); - const std::uint32_t sample_log2 = std::uint32_t(std::bit_width(std::max(image.samples, 1u)) - 1); - const std::uint32_t base_level = msaa ? 0 : image.first_mip; - const std::uint32_t last_level = msaa ? sample_log2 : image.first_mip + image.mip_count - 1; - const std::uint32_t max_mip = msaa ? sample_log2 : image.resource_mips - 1; - const std::uint32_t last = - image.type == ImageType::image_3d ? image.depth - 1 : image.first_layer + image.layer_count - 1; - const std::uint64_t units = image.address >> 8; - const std::uint32_t width = image.width - 1, height = image.height - 1; - ImageWords words{}; - words[0] = std::uint32_t(units); - words[1] = field(std::uint32_t(units >> 32), 0, 8) | field(detail::unsigned_fixed(image.min_lod, 0, 15), 8, 12) | - field(image.format, 20, 9) | field(width, 30, 2); - words[2] = field(width >> 2, 0, 12) | field(height, 14, 14); - words[3] = field(image.swizzle[0], 0, 3) | field(image.swizzle[1], 3, 3) | field(image.swizzle[2], 6, 3) | - field(image.swizzle[3], 9, 3) | field(base_level, 12, 4) | field(last_level, 16, 4) | - field(std::uint32_t(image.type), 28, 4); - words[4] = field(last, 0, 13) | field(image.first_layer, 16, 13); - words[5] = field(max_mip, 4, 4); - return words; -} - -// TYPE names an image, so these eight dwords are a T# and not a V# followed by something else. -inline constexpr bool is_image(const ImageWords& words) { return detail::get(words[3], 28, 4) >= 8; } - -inline constexpr float image_min_lod(const ImageWords& words) { - return float(detail::get(words[1], 8, 12)) / 256.0f; -} - -// False when the dwords are not an image descriptor, or a field contradicts another: a reserved DST_SEL, a last -// level or layer before the first, or a cube whose layers are not whole cubes. -inline bool decode(const ImageWords& words, Image& out) { - using detail::get; - if (!is_image(words)) return false; - Image image{}; - image.type = ImageType(get(words[3], 28, 4)); - image.address = ((std::uint64_t(get(words[1], 0, 8)) << 32) | words[0]) << 8; - image.min_lod = image_min_lod(words); - image.format = get(words[1], 20, 9); - image.width = (get(words[1], 30, 2) | (get(words[2], 0, 12) << 2)) + 1; - image.height = get(words[2], 14, 14) + 1; - for (unsigned i = 0; i < 4; ++i) image.swizzle[i] = std::uint8_t(get(words[3], 3 * i, 3)); - if (!valid_swizzle(image.swizzle)) return false; - - const std::uint32_t base_level = get(words[3], 12, 4), last_level = get(words[3], 16, 4); - if (multisampled(image.type)) { - if (base_level) return false; - image.samples = 1u << last_level; - } else { - if (last_level < base_level) return false; - image.first_mip = base_level; - image.mip_count = last_level - base_level + 1; - image.resource_mips = get(words[5], 4, 4) + 1; - } - - const std::uint32_t last = get(words[4], 0, 13); - image.first_layer = get(words[4], 16, 13); - if (image.type == ImageType::image_3d) { - image.depth = last + 1; - } else { - if (last < image.first_layer) return false; - image.layer_count = last - image.first_layer + 1; - if (image.type == ImageType::cube && image.layer_count % 6) return false; - } - out = image; - return true; -} - -// The view type translated shaders sample a T# of this type through. A cube is a six-layer 2D array there: the -// shader has already chosen the face (tools/rdna2spirv.py, image_op; docs/design.md, "Images and samplers"). -inline constexpr VkImageViewType vulkan_view_type(ImageType type) { - switch (type) { - case ImageType::image_1d: return VK_IMAGE_VIEW_TYPE_1D; - case ImageType::image_1d_array: return VK_IMAGE_VIEW_TYPE_1D_ARRAY; - case ImageType::image_3d: return VK_IMAGE_VIEW_TYPE_3D; - case ImageType::cube: - case ImageType::image_2d_array: - case ImageType::image_2d_msaa_array: return VK_IMAGE_VIEW_TYPE_2D_ARRAY; - default: return VK_IMAGE_VIEW_TYPE_2D; - } -} - -// ---- formats ---- - -// One row for each Vulkan format: its GFX10_FORMAT code, and the DST_SEL that reads its channels as R, G, B, A -// (0 and 1 where the format has no such channel). A format's channels are X, Y, Z, W from the lowest bit (the -// first byte) up: Mesa pairs the channels of a format in that order with the sizes in the code's name reversed -// (gfx10_format_table.py). So R8G8B8A8 is the identity and B8G8R8A8 is the same code read as Z, Y, X, W. The -// first row of a code is the format vulkan_format() returns for it: the one in the identity order, where Vulkan -// has one. Depth formats share the codes of the colour formats with the same bits. -struct FormatRow { - std::uint32_t gfx10; - VkFormat vulkan; - Swizzle channels; -}; - -inline constexpr Swizzle channels_r{select_x, select_zero, select_zero, select_one}; -inline constexpr Swizzle channels_rg{select_x, select_y, select_zero, select_one}; -inline constexpr Swizzle channels_rgb{select_x, select_y, select_z, select_one}; -inline constexpr Swizzle channels_rgba = identity_swizzle; -inline constexpr Swizzle channels_bgr{select_z, select_y, select_x, select_one}; -inline constexpr Swizzle channels_bgra{select_z, select_y, select_x, select_w}; -inline constexpr Swizzle channels_abgr{select_w, select_z, select_y, select_x}; - -inline constexpr FormatRow format_table[] = { - {1, VK_FORMAT_R8_UNORM, channels_r}, // GFX10_FORMAT_8_UNORM - {2, VK_FORMAT_R8_SNORM, channels_r}, // GFX10_FORMAT_8_SNORM - {3, VK_FORMAT_R8_USCALED, channels_r}, // GFX10_FORMAT_8_USCALED - {4, VK_FORMAT_R8_SSCALED, channels_r}, // GFX10_FORMAT_8_SSCALED - {5, VK_FORMAT_R8_UINT, channels_r}, // GFX10_FORMAT_8_UINT - {5, VK_FORMAT_S8_UINT, channels_r}, // GFX10_FORMAT_8_UINT - {6, VK_FORMAT_R8_SINT, channels_r}, // GFX10_FORMAT_8_SINT - {7, VK_FORMAT_R16_UNORM, channels_r}, // GFX10_FORMAT_16_UNORM - {7, VK_FORMAT_D16_UNORM, channels_r}, // GFX10_FORMAT_16_UNORM - {8, VK_FORMAT_R16_SNORM, channels_r}, // GFX10_FORMAT_16_SNORM - {9, VK_FORMAT_R16_USCALED, channels_r}, // GFX10_FORMAT_16_USCALED - {10, VK_FORMAT_R16_SSCALED, channels_r}, // GFX10_FORMAT_16_SSCALED - {11, VK_FORMAT_R16_UINT, channels_r}, // GFX10_FORMAT_16_UINT - {12, VK_FORMAT_R16_SINT, channels_r}, // GFX10_FORMAT_16_SINT - {13, VK_FORMAT_R16_SFLOAT, channels_r}, // GFX10_FORMAT_16_FLOAT - {14, VK_FORMAT_R8G8_UNORM, channels_rg}, // GFX10_FORMAT_8_8_UNORM - {15, VK_FORMAT_R8G8_SNORM, channels_rg}, // GFX10_FORMAT_8_8_SNORM - {16, VK_FORMAT_R8G8_USCALED, channels_rg}, // GFX10_FORMAT_8_8_USCALED - {17, VK_FORMAT_R8G8_SSCALED, channels_rg}, // GFX10_FORMAT_8_8_SSCALED - {18, VK_FORMAT_R8G8_UINT, channels_rg}, // GFX10_FORMAT_8_8_UINT - {19, VK_FORMAT_R8G8_SINT, channels_rg}, // GFX10_FORMAT_8_8_SINT - {20, VK_FORMAT_R32_UINT, channels_r}, // GFX10_FORMAT_32_UINT - {21, VK_FORMAT_R32_SINT, channels_r}, // GFX10_FORMAT_32_SINT - {22, VK_FORMAT_R32_SFLOAT, channels_r}, // GFX10_FORMAT_32_FLOAT - {22, VK_FORMAT_D32_SFLOAT, channels_r}, // GFX10_FORMAT_32_FLOAT - {23, VK_FORMAT_R16G16_UNORM, channels_rg}, // GFX10_FORMAT_16_16_UNORM - {24, VK_FORMAT_R16G16_SNORM, channels_rg}, // GFX10_FORMAT_16_16_SNORM - {25, VK_FORMAT_R16G16_USCALED, channels_rg}, // GFX10_FORMAT_16_16_USCALED - {26, VK_FORMAT_R16G16_SSCALED, channels_rg}, // GFX10_FORMAT_16_16_SSCALED - {27, VK_FORMAT_R16G16_UINT, channels_rg}, // GFX10_FORMAT_16_16_UINT - {28, VK_FORMAT_R16G16_SINT, channels_rg}, // GFX10_FORMAT_16_16_SINT - {29, VK_FORMAT_R16G16_SFLOAT, channels_rg}, // GFX10_FORMAT_16_16_FLOAT - {36, VK_FORMAT_B10G11R11_UFLOAT_PACK32, channels_rgb}, // GFX10_FORMAT_10_11_11_FLOAT - {50, VK_FORMAT_A2B10G10R10_UNORM_PACK32, channels_rgba}, // GFX10_FORMAT_2_10_10_10_UNORM - {50, VK_FORMAT_A2R10G10B10_UNORM_PACK32, channels_bgra}, // GFX10_FORMAT_2_10_10_10_UNORM - {51, VK_FORMAT_A2B10G10R10_SNORM_PACK32, channels_rgba}, // GFX10_FORMAT_2_10_10_10_SNORM - {52, VK_FORMAT_A2B10G10R10_USCALED_PACK32, channels_rgba}, // GFX10_FORMAT_2_10_10_10_USCALED - {53, VK_FORMAT_A2B10G10R10_SSCALED_PACK32, channels_rgba}, // GFX10_FORMAT_2_10_10_10_SSCALED - {54, VK_FORMAT_A2B10G10R10_UINT_PACK32, channels_rgba}, // GFX10_FORMAT_2_10_10_10_UINT - {54, VK_FORMAT_A2R10G10B10_UINT_PACK32, channels_bgra}, // GFX10_FORMAT_2_10_10_10_UINT - {55, VK_FORMAT_A2B10G10R10_SINT_PACK32, channels_rgba}, // GFX10_FORMAT_2_10_10_10_SINT - {56, VK_FORMAT_R8G8B8A8_UNORM, channels_rgba}, // GFX10_FORMAT_8_8_8_8_UNORM - {56, VK_FORMAT_B8G8R8A8_UNORM, channels_bgra}, // GFX10_FORMAT_8_8_8_8_UNORM - {57, VK_FORMAT_R8G8B8A8_SNORM, channels_rgba}, // GFX10_FORMAT_8_8_8_8_SNORM - {58, VK_FORMAT_R8G8B8A8_USCALED, channels_rgba}, // GFX10_FORMAT_8_8_8_8_USCALED - {59, VK_FORMAT_R8G8B8A8_SSCALED, channels_rgba}, // GFX10_FORMAT_8_8_8_8_SSCALED - {60, VK_FORMAT_R8G8B8A8_UINT, channels_rgba}, // GFX10_FORMAT_8_8_8_8_UINT - {61, VK_FORMAT_R8G8B8A8_SINT, channels_rgba}, // GFX10_FORMAT_8_8_8_8_SINT - {62, VK_FORMAT_R32G32_UINT, channels_rg}, // GFX10_FORMAT_32_32_UINT - {63, VK_FORMAT_R32G32_SINT, channels_rg}, // GFX10_FORMAT_32_32_SINT - {64, VK_FORMAT_R32G32_SFLOAT, channels_rg}, // GFX10_FORMAT_32_32_FLOAT - {65, VK_FORMAT_R16G16B16A16_UNORM, channels_rgba}, // GFX10_FORMAT_16_16_16_16_UNORM - {66, VK_FORMAT_R16G16B16A16_SNORM, channels_rgba}, // GFX10_FORMAT_16_16_16_16_SNORM - {67, VK_FORMAT_R16G16B16A16_USCALED, channels_rgba}, // GFX10_FORMAT_16_16_16_16_USCALED - {68, VK_FORMAT_R16G16B16A16_SSCALED, channels_rgba}, // GFX10_FORMAT_16_16_16_16_SSCALED - {69, VK_FORMAT_R16G16B16A16_UINT, channels_rgba}, // GFX10_FORMAT_16_16_16_16_UINT - {70, VK_FORMAT_R16G16B16A16_SINT, channels_rgba}, // GFX10_FORMAT_16_16_16_16_SINT - {71, VK_FORMAT_R16G16B16A16_SFLOAT, channels_rgba}, // GFX10_FORMAT_16_16_16_16_FLOAT - {72, VK_FORMAT_R32G32B32_UINT, channels_rgb}, // GFX10_FORMAT_32_32_32_UINT - {73, VK_FORMAT_R32G32B32_SINT, channels_rgb}, // GFX10_FORMAT_32_32_32_SINT - {74, VK_FORMAT_R32G32B32_SFLOAT, channels_rgb}, // GFX10_FORMAT_32_32_32_FLOAT - {75, VK_FORMAT_R32G32B32A32_UINT, channels_rgba}, // GFX10_FORMAT_32_32_32_32_UINT - {76, VK_FORMAT_R32G32B32A32_SINT, channels_rgba}, // GFX10_FORMAT_32_32_32_32_SINT - {77, VK_FORMAT_R32G32B32A32_SFLOAT, channels_rgba}, // GFX10_FORMAT_32_32_32_32_FLOAT - {128, VK_FORMAT_R8_SRGB, channels_r}, // GFX10_FORMAT_8_SRGB - {129, VK_FORMAT_R8G8_SRGB, channels_rg}, // GFX10_FORMAT_8_8_SRGB - {130, VK_FORMAT_R8G8B8A8_SRGB, channels_rgba}, // GFX10_FORMAT_8_8_8_8_SRGB - {130, VK_FORMAT_B8G8R8A8_SRGB, channels_bgra}, // GFX10_FORMAT_8_8_8_8_SRGB - {132, VK_FORMAT_E5B9G9R9_UFLOAT_PACK32, channels_rgb}, // GFX10_FORMAT_5_9_9_9_FLOAT - {133, VK_FORMAT_B5G6R5_UNORM_PACK16, channels_rgb}, // GFX10_FORMAT_5_6_5_UNORM - {133, VK_FORMAT_R5G6B5_UNORM_PACK16, channels_bgr}, // GFX10_FORMAT_5_6_5_UNORM - {134, VK_FORMAT_A1R5G5B5_UNORM_PACK16, channels_bgra}, // GFX10_FORMAT_1_5_5_5_UNORM - {136, VK_FORMAT_A4B4G4R4_UNORM_PACK16, channels_rgba}, // GFX10_FORMAT_4_4_4_4_UNORM - {136, VK_FORMAT_A4R4G4B4_UNORM_PACK16, channels_bgra}, // GFX10_FORMAT_4_4_4_4_UNORM - {136, VK_FORMAT_R4G4B4A4_UNORM_PACK16, channels_abgr}, // GFX10_FORMAT_4_4_4_4_UNORM - {141, VK_FORMAT_D24_UNORM_S8_UINT, channels_r}, // GFX10_FORMAT_8_24_UNORM - {141, VK_FORMAT_X8_D24_UNORM_PACK32, channels_r}, // GFX10_FORMAT_8_24_UNORM - {146, VK_FORMAT_D32_SFLOAT_S8_UINT, channels_r}, // GFX10_FORMAT_X24_8_32_FLOAT - {169, VK_FORMAT_BC1_RGBA_UNORM_BLOCK, channels_rgba}, // GFX10_FORMAT_BC1_UNORM - {169, VK_FORMAT_BC1_RGB_UNORM_BLOCK, channels_rgb}, // GFX10_FORMAT_BC1_UNORM - {170, VK_FORMAT_BC1_RGBA_SRGB_BLOCK, channels_rgba}, // GFX10_FORMAT_BC1_SRGB - {170, VK_FORMAT_BC1_RGB_SRGB_BLOCK, channels_rgb}, // GFX10_FORMAT_BC1_SRGB - {171, VK_FORMAT_BC2_UNORM_BLOCK, channels_rgba}, // GFX10_FORMAT_BC2_UNORM - {172, VK_FORMAT_BC2_SRGB_BLOCK, channels_rgba}, // GFX10_FORMAT_BC2_SRGB - {173, VK_FORMAT_BC3_UNORM_BLOCK, channels_rgba}, // GFX10_FORMAT_BC3_UNORM - {174, VK_FORMAT_BC3_SRGB_BLOCK, channels_rgba}, // GFX10_FORMAT_BC3_SRGB - {175, VK_FORMAT_BC4_UNORM_BLOCK, channels_r}, // GFX10_FORMAT_BC4_UNORM - {176, VK_FORMAT_BC4_SNORM_BLOCK, channels_r}, // GFX10_FORMAT_BC4_SNORM - {177, VK_FORMAT_BC5_UNORM_BLOCK, channels_rg}, // GFX10_FORMAT_BC5_UNORM - {178, VK_FORMAT_BC5_SNORM_BLOCK, channels_rg}, // GFX10_FORMAT_BC5_SNORM - {179, VK_FORMAT_BC6H_UFLOAT_BLOCK, channels_rgb}, // GFX10_FORMAT_BC6_UFLOAT - {180, VK_FORMAT_BC6H_SFLOAT_BLOCK, channels_rgb}, // GFX10_FORMAT_BC6_SFLOAT - {181, VK_FORMAT_BC7_UNORM_BLOCK, channels_rgba}, // GFX10_FORMAT_BC7_UNORM - {182, VK_FORMAT_BC7_SRGB_BLOCK, channels_rgba}, // GFX10_FORMAT_BC7_SRGB -}; - -// The format of the console's separate stencil surface: what a T# of a depth-stencil texture's stencil plane names. -inline constexpr std::uint32_t stencil_format = 5; // GFX10_FORMAT_8_UINT - -inline constexpr const FormatRow* format_row(VkFormat format) { - for (const FormatRow& row : format_table) - if (row.vulkan == format) return &row; - return nullptr; -} - -// The Vulkan format with the code's bits, in the hardware's channel order where Vulkan has such a format. -// VK_FORMAT_UNDEFINED: not in the table. A code that depth and colour formats share gives the colour format. -inline constexpr VkFormat vulkan_format(std::uint32_t gfx10_format) { - for (const FormatRow& row : format_table) - if (row.gfx10 == gfx10_format) return row.vulkan; - return VK_FORMAT_UNDEFINED; -} - -// 0 (GFX10_FORMAT_INVALID): not in the table. -inline constexpr std::uint32_t format_from_vulkan(VkFormat format) { - const FormatRow* row = format_row(format); - return row ? row->gfx10 : 0; -} - -// The DST_SEL a T# of this format carries when the view applies no component mapping of its own: it reads the -// format's channels as R, G, B, A. The identity for a format that is not in the table. -inline constexpr Swizzle format_swizzle(VkFormat format) { - const FormatRow* row = format_row(format); - return row ? row->channels : identity_swizzle; -} - -inline constexpr bool is_depth_stencil_format(VkFormat format) { - switch (format) { - case VK_FORMAT_D16_UNORM: - case VK_FORMAT_X8_D24_UNORM_PACK32: - case VK_FORMAT_D32_SFLOAT: - case VK_FORMAT_S8_UINT: - case VK_FORMAT_D16_UNORM_S8_UINT: - case VK_FORMAT_D24_UNORM_S8_UINT: - case VK_FORMAT_D32_SFLOAT_S8_UINT: - return true; - default: - return false; - } -} - -// The format to view an image of `image_format` in when a T# names `gfx10_format`: the image's own format when -// the codes agree, else the format of that code with the image's channel order (the sRGB view of a UNORM image, -// say). With `allow_channel_cast`, a listed same-size cross-family cast may use the code's first Vulkan format -// when no channel-order match exists (R8G8B8A8_UINT viewed as R32_UINT, say). Depth/stencil images are only -// compatible with their own format in Vulkan (VUID-VkImageViewCreateInfo-image-01762 / 09594), and colour -// images can never be viewed as depth/stencil. VK_FORMAT_UNDEFINED: no compatible format exists. -inline constexpr VkFormat vulkan_view_format(VkFormat image_format, std::uint32_t gfx10_format, - bool allow_channel_cast = false) { - const FormatRow* image = format_row(image_format); - if (!image) return VK_FORMAT_UNDEFINED; - if (image->gfx10 == gfx10_format) return image_format; - if (is_depth_stencil_format(image_format)) return VK_FORMAT_UNDEFINED; - const FormatRow* fallback = nullptr; - for (const FormatRow& row : format_table) { - if (row.gfx10 != gfx10_format || is_depth_stencil_format(row.vulkan)) continue; - if (row.channels == image->channels) return row.vulkan; - if (!fallback) fallback = &row; - } - return allow_channel_cast && fallback ? fallback->vulkan : VK_FORMAT_UNDEFINED; -} - -// DST_SEL as the component mapping of a view whose format is `view_format`: X, Y, Z, W name the hardware's -// channels, and the format says which of R, G, B, A each one is. A channel the format does not have reads as zero. -inline constexpr VkComponentMapping vulkan_swizzle(const Swizzle& swizzle, VkFormat view_format) { - const Swizzle channels = format_swizzle(view_format); - const auto component = [&](std::uint8_t select) { - if (select == select_one) return VK_COMPONENT_SWIZZLE_ONE; - if (select >= select_x && select <= select_w) - for (unsigned i = 0; i < 4; ++i) - if (channels[i] == select) return VkComponentSwizzle(VK_COMPONENT_SWIZZLE_R + i); - return VK_COMPONENT_SWIZZLE_ZERO; - }; - return {component(swizzle[0]), component(swizzle[1]), component(swizzle[2]), component(swizzle[3])}; -} - -// The same for a format in the hardware's own order (X, Y, Z, W are R, G, B, A). -inline constexpr VkComponentMapping vulkan_swizzle(const Swizzle& swizzle) { - return vulkan_swizzle(swizzle, VK_FORMAT_R8G8B8A8_UNORM); -} - -// ---- S#: SQ_IMG_SAMP_WORD0..3 ---- - -enum class AddressMode : std::uint32_t { // SQ_TEX_CLAMP - wrap = 0, - mirror = 1, - clamp_last_texel = 2, - mirror_once_last_texel = 3, - clamp_half_border = 4, - mirror_once_half_border = 5, - clamp_border = 6, - mirror_once_border = 7, -}; - -enum class Filter : std::uint32_t { // SQ_TEX_XY_FILTER - point = 0, - bilinear = 1, - aniso_point = 2, - aniso_bilinear = 3, -}; - -enum class MipFilter : std::uint32_t { // SQ_TEX_MIP_FILTER - none = 0, - point = 1, - linear = 2, -}; - -enum class CompareFunction : std::uint32_t { // SQ_TEX_DEPTH_COMPARE; the same values as VkCompareOp - never = 0, - less = 1, - equal = 2, - less_equal = 3, - greater = 4, - not_equal = 5, - greater_equal = 6, - always = 7, -}; - -enum class BorderColor : std::uint32_t { // SQ_TEX_BORDER_COLOR - transparent_black = 0, - opaque_black = 1, - opaque_white = 2, - table = 3, // SQ_TEX_BORDER_COLOR_REGISTER: the colour at border_color_index in the device's table -}; - -enum class FilterMode : std::uint32_t { // SQ_IMG_FILTER_TYPE: D3D12's MINIMUM_ and MAXIMUM_ filters - blend = 0, - minimum = 1, - maximum = 2, -}; - -// What an S# says. decode() returns the normal form: max_anisotropy is 1, 2, 4, 8 or 16. -struct Sampler { - AddressMode address_u = AddressMode::wrap; - AddressMode address_v = AddressMode::wrap; - AddressMode address_w = AddressMode::wrap; - Filter mag_filter = Filter::point; - Filter min_filter = Filter::point; - MipFilter mip_filter = MipFilter::none; - std::uint32_t max_anisotropy = 1; - CompareFunction compare = CompareFunction::never; // never: not a comparison sampler, as radv writes it - float min_lod = 0.0f; // 0..15 in steps of 1/256 - float max_lod = 0.0f; - float lod_bias = 0.0f; // -32..31 in steps of 1/256 - BorderColor border_color = BorderColor::transparent_black; - std::uint32_t border_color_index = 0; // 12 bits - bool unnormalized = false; - FilterMode filter_mode = FilterMode::blend; - // The layer's own: the border colour is read as integers (D3D12_SAMPLER_FLAG_UINT_BORDER_COLOR). The hardware - // picks integer or float by the image's format, but Vulkan needs VK_BORDER_COLOR_INT_* in the sampler, so the - // layer keeps it in the S# words, which are the sampler's key: see kIntegerBorderPtr. - bool integer_border = false; - bool compare_never = false; // D3D12 comparison filter with DEPTH_COMPARE_FUNC = NEVER - bool operator==(const Sampler&) const = default; -}; - -// BORDER_COLOR_PTR of an S# with an integer border. The hardware reads the pointer only for BorderColor::table -// (Mesa writes it only for SQ_TEX_BORDER_COLOR_REGISTER), so with the three built-in types the field is free, and -// the layer marks an integer border there. An integer table colour is not marked: table colours are not kept yet. -inline constexpr std::uint32_t kIntegerBorderPtr = 0x800; - -// With DERIV_ADJUST_EN clear, GFX10 S# WORD3 has BORDER_COLOR_PTR in bits 0..11 and BORDER_COLOR_TYPE -// in 30..31. Use an otherwise unused bit in layer-created samplers to distinguish a D3D12 NEVER comparison -// from an ordinary filter: both hardware DEPTH_COMPARE_FUNC fields are zero, but Vulkan needs distinct samplers. -inline constexpr std::uint32_t kCompareNever = 1u << 12; - -// As ac_build_sampler_descriptor fills it for GFX10: -// WORD0 CLAMP_X [2:0], CLAMP_Y [5:3], CLAMP_Z [8:6], MAX_ANISO_RATIO [11:9] = log2(anisotropy), at most 4, -// DEPTH_COMPARE_FUNC [14:12], FORCE_UNNORMALIZED [15], FILTER_MODE [30:29] -// WORD1 MIN_LOD [11:0], MAX_LOD [23:12] (4.8 fixed, clamped to 0..15) -// WORD2 LOD_BIAS [13:0] (signed 5.8 fixed, clamped to -32..31), XY_MAG_FILTER [21:20], XY_MIN_FILTER [23:22], -// MIP_FILTER [27:26] -// WORD3 BORDER_COLOR_PTR [11:0], BORDER_COLOR_TYPE [31:30] -// Mesa also sets tuning fields from the anisotropy (ANISO_THRESHOLD, ANISO_BIAS, PERF_MIP, ANISO_OVERRIDE) and -// TRUNC_COORD for point filters. They are not written here, and decode() ignores them. -inline SamplerWords encode(const Sampler& sampler) { - using detail::field; - const std::uint32_t aniso_log2 = - std::min(std::uint32_t(std::bit_width(std::max(sampler.max_anisotropy, 1u)) - 1), 4u); - SamplerWords words{}; - words[0] = field(std::uint32_t(sampler.address_u), 0, 3) | field(std::uint32_t(sampler.address_v), 3, 3) | - field(std::uint32_t(sampler.address_w), 6, 3) | field(aniso_log2, 9, 3) | - field(std::uint32_t(sampler.compare), 12, 3) | field(sampler.unnormalized ? 1u : 0u, 15, 1) | - field(std::uint32_t(sampler.filter_mode), 29, 2); - words[1] = field(detail::unsigned_fixed(sampler.min_lod, 0, 15), 0, 12) | - field(detail::unsigned_fixed(sampler.max_lod, 0, 15), 12, 12); - words[2] = field(detail::signed_fixed(sampler.lod_bias, -32, 31), 0, 14) | - field(std::uint32_t(sampler.mag_filter), 20, 2) | field(std::uint32_t(sampler.min_filter), 22, 2) | - field(std::uint32_t(sampler.mip_filter), 26, 2); - const bool marked = sampler.integer_border && sampler.border_color != BorderColor::table; - words[3] = field(marked ? kIntegerBorderPtr : sampler.border_color_index, 0, 12) | - field(std::uint32_t(sampler.border_color), 30, 2); - if (sampler.compare == CompareFunction::never && sampler.compare_never) words[3] |= kCompareNever; - return words; -} - -// Every bit pattern is a sampler; values the enums do not name (MIP_FILTER 3, FILTER_MODE 3) are kept as they -// are, and vulkan_sampler() treats them as the default. -inline Sampler decode(const SamplerWords& words) { - using detail::get; - Sampler sampler{}; - sampler.address_u = AddressMode(get(words[0], 0, 3)); - sampler.address_v = AddressMode(get(words[0], 3, 3)); - sampler.address_w = AddressMode(get(words[0], 6, 3)); - sampler.max_anisotropy = 1u << std::min(get(words[0], 9, 3), 4u); - sampler.compare = CompareFunction(get(words[0], 12, 3)); - // DERIV_ADJUST_EN repurposes WORD3, so its bits are not layer markers in that layout. - const bool deriv_adjust = get(words[2], 31, 1) != 0; - sampler.compare_never = !deriv_adjust && sampler.compare == CompareFunction::never && (words[3] & kCompareNever); - sampler.unnormalized = get(words[0], 15, 1) != 0; - sampler.filter_mode = FilterMode(get(words[0], 29, 2)); - sampler.min_lod = float(get(words[1], 0, 12)) / 256.0f; - sampler.max_lod = float(get(words[1], 12, 12)) / 256.0f; - const std::uint32_t bias = get(words[2], 0, 14); - sampler.lod_bias = float(std::int32_t(bias ^ 0x2000u) - 0x2000) / 256.0f; // sign-extend 14 bits - sampler.mag_filter = Filter(get(words[2], 20, 2)); - sampler.min_filter = Filter(get(words[2], 22, 2)); - sampler.mip_filter = MipFilter(get(words[2], 26, 2)); - sampler.border_color_index = get(words[3], 0, 12); - sampler.border_color = BorderColor(get(words[3], 30, 2)); - if (sampler.border_color != BorderColor::table && sampler.border_color_index == kIntegerBorderPtr) { - sampler.integer_border = true; - sampler.border_color_index = 0; - } - return sampler; -} - -// The inverse of radv_tex_wrap. Vulkan has no half-border or mirror-once-border mode; the nearest one is used. -inline constexpr VkSamplerAddressMode vulkan_address_mode(AddressMode mode) { - switch (mode) { - case AddressMode::wrap: return VK_SAMPLER_ADDRESS_MODE_REPEAT; - case AddressMode::mirror: return VK_SAMPLER_ADDRESS_MODE_MIRRORED_REPEAT; - case AddressMode::clamp_border: return VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_BORDER; - case AddressMode::mirror_once_last_texel: - case AddressMode::mirror_once_half_border: - case AddressMode::mirror_once_border: return VK_SAMPLER_ADDRESS_MODE_MIRROR_CLAMP_TO_EDGE; - default: return VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE; // clamp_last_texel, clamp_half_border - } -} - -inline constexpr VkSamplerReductionMode vulkan_reduction_mode(FilterMode mode) { - switch (mode) { - case FilterMode::minimum: return VK_SAMPLER_REDUCTION_MODE_MIN; - case FilterMode::maximum: return VK_SAMPLER_REDUCTION_MODE_MAX; - default: return VK_SAMPLER_REDUCTION_MODE_WEIGHTED_AVERAGE; - } -} - -// The inverse of radv_make_sampler_descriptor. Left to the caller, because they need more than this structure: -// - border_color == table: VK_BORDER_COLOR_FLOAT_TRANSPARENT_BLACK is returned; the colour itself is in a table -// the S# only indexes (VK_EXT_custom_border_color); -// - filter_mode != blend: chain a VkSamplerReductionModeCreateInfo with vulkan_reduction_mode(); -// - mirror-once modes need samplerMirrorClampToEdge, anisotropy needs samplerAnisotropy. -// MIP_FILTER_NONE samples the base level only, which Vulkan expresses as nearest mip filtering with the LOD held -// in [0, 0.25] (the Vulkan specification's note on samplers without mipmapping). An unnormalised sampler gets -// what Vulkan requires of one: no mips, no anisotropy, no comparison. -// A decoded GFX10 bias has absolute value at most 32. When creating a device sampler, pass its smaller limit. -inline VkSamplerCreateInfo vulkan_sampler(const Sampler& sampler, float max_lod_bias = 32.0f) { - static_assert(int(CompareFunction::never) == int(VK_COMPARE_OP_NEVER) && - int(CompareFunction::less) == int(VK_COMPARE_OP_LESS) && - int(CompareFunction::equal) == int(VK_COMPARE_OP_EQUAL) && - int(CompareFunction::less_equal) == int(VK_COMPARE_OP_LESS_OR_EQUAL) && - int(CompareFunction::greater) == int(VK_COMPARE_OP_GREATER) && - int(CompareFunction::not_equal) == int(VK_COMPARE_OP_NOT_EQUAL) && - int(CompareFunction::greater_equal) == int(VK_COMPARE_OP_GREATER_OR_EQUAL) && - int(CompareFunction::always) == int(VK_COMPARE_OP_ALWAYS)); - const auto filter = [](Filter f) { - return f == Filter::bilinear || f == Filter::aniso_bilinear ? VK_FILTER_LINEAR : VK_FILTER_NEAREST; - }; - VkSamplerCreateInfo info{VK_STRUCTURE_TYPE_SAMPLER_CREATE_INFO}; - info.magFilter = filter(sampler.mag_filter); - info.minFilter = filter(sampler.min_filter); - info.mipmapMode = - sampler.mip_filter == MipFilter::linear ? VK_SAMPLER_MIPMAP_MODE_LINEAR : VK_SAMPLER_MIPMAP_MODE_NEAREST; - info.addressModeU = vulkan_address_mode(sampler.address_u); - info.addressModeV = vulkan_address_mode(sampler.address_v); - info.addressModeW = vulkan_address_mode(sampler.address_w); - info.mipLodBias = std::clamp(sampler.lod_bias, -max_lod_bias, max_lod_bias); - info.anisotropyEnable = sampler.max_anisotropy > 1 ? VK_TRUE : VK_FALSE; - info.maxAnisotropy = float(std::max(sampler.max_anisotropy, 1u)); - info.compareEnable = (sampler.compare_never || sampler.compare != CompareFunction::never) ? VK_TRUE : VK_FALSE; - info.compareOp = VkCompareOp(sampler.compare); - info.minLod = sampler.min_lod; - info.maxLod = sampler.max_lod; - if (sampler.mip_filter == MipFilter::none) { - info.minLod = 0.0f; - info.maxLod = 0.25f; - } - // An integer image sampled with a FLOAT border colour reads it as 0 on NVIDIA (Vonsek, #538), so the type follows - // integer_border. A table colour falls back to transparent black matching integer_border. - const bool integer = sampler.integer_border; - switch (sampler.border_color) { - case BorderColor::opaque_black: - info.borderColor = integer ? VK_BORDER_COLOR_INT_OPAQUE_BLACK : VK_BORDER_COLOR_FLOAT_OPAQUE_BLACK; - break; - case BorderColor::opaque_white: - info.borderColor = integer ? VK_BORDER_COLOR_INT_OPAQUE_WHITE : VK_BORDER_COLOR_FLOAT_OPAQUE_WHITE; - break; - default: - info.borderColor = integer ? VK_BORDER_COLOR_INT_TRANSPARENT_BLACK : VK_BORDER_COLOR_FLOAT_TRANSPARENT_BLACK; - break; - } - if (sampler.unnormalized) { - info.unnormalizedCoordinates = VK_TRUE; - // VUID-VkSamplerCreateInfo-unnormalizedCoordinates-01075: U and V clamp to the edge or the border (a - // repeating mode would wrap at a texel count the sampler cannot know); -01072: one filter for min and mag. - // The S# allows any address mode with FORCE_UNNORMALIZED, and WRAP is its default (word 0 = 0). - const auto clamp_or_border = [](VkSamplerAddressMode m) { - return m == VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_BORDER ? m : VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE; - }; - info.addressModeU = clamp_or_border(info.addressModeU); - info.addressModeV = clamp_or_border(info.addressModeV); - info.minFilter = info.magFilter; - info.mipmapMode = VK_SAMPLER_MIPMAP_MODE_NEAREST; - info.minLod = info.maxLod = 0.0f; - info.anisotropyEnable = VK_FALSE; - info.maxAnisotropy = 1.0f; - info.compareEnable = VK_FALSE; - } - return info; -} - -// ---- V#: SQ_BUF_RSRC_WORD0..3 ---- - -// SQ_BUF_RSRC_WORD3.OOB_SELECT: the bounds check the hardware makes, and the one the translator makes too -// (tools/rdna2spirv.py, buffer_address; docs/design.md, Buffer bounds checking): structured_with_offset is out of -// range at index >= num_records or offset + 4 > stride, structured at index >= num_records, disabled only at -// num_records == 0, raw at offset + 4 > num_records (docs/buffer_bounds.md). A V# built here for a shader to read must say which: the default -// below makes every stride-0 access out of range. -enum class OobSelect : std::uint32_t { - structured_with_offset = 0, - structured = 1, - disabled = 2, - raw = 3, -}; - -struct Buffer { - std::uint64_t address = 0; // console VA of the first byte, 48 bits - std::uint32_t stride = 0; // bytes a record, 14 bits; 0: a raw buffer - std::uint32_t num_records = 0; // records, or bytes when the stride is 0 - std::uint32_t format = 0; // GFX10_FORMAT_* code below 128, for typed loads and stores - Swizzle swizzle = identity_swizzle; - OobSelect oob_select = OobSelect::structured_with_offset; - bool operator==(const Buffer&) const = default; -}; - -// As ac_build_buffer_descriptor fills it: -// WORD0 BASE_ADDRESS = address -// WORD1 BASE_ADDRESS_HI [15:0] = address >> 32, STRIDE [29:16] -// WORD2 NUM_RECORDS -// WORD3 DST_SEL_X/Y/Z/W [11:0], FORMAT [18:12], OOB_SELECT [29:28], TYPE [31:30] = 0 (SQ_RSRC_BUF) -inline BufferWords encode(const Buffer& buffer) { - using detail::field; - BufferWords words{}; - words[0] = std::uint32_t(buffer.address); - words[1] = field(std::uint32_t(buffer.address >> 32), 0, 16) | field(buffer.stride, 16, 14); - words[2] = buffer.num_records; - words[3] = field(buffer.swizzle[0], 0, 3) | field(buffer.swizzle[1], 3, 3) | field(buffer.swizzle[2], 6, 3) | - field(buffer.swizzle[3], 9, 3) | field(buffer.format, 12, 7) | - field(std::uint32_t(buffer.oob_select), 28, 2); - return words; -} - -// False when TYPE is not a buffer's (an image's TYPE has its top bit set) or a DST_SEL is reserved. -inline bool decode(const BufferWords& words, Buffer& out) { - using detail::get; - if (get(words[3], 30, 2) != 0) return false; - Buffer buffer{}; - buffer.address = (std::uint64_t(get(words[1], 0, 16)) << 32) | words[0]; - buffer.stride = get(words[1], 16, 14); - buffer.num_records = words[2]; - for (unsigned i = 0; i < 4; ++i) buffer.swizzle[i] = std::uint8_t(get(words[3], 3 * i, 3)); - if (!valid_swizzle(buffer.swizzle)) return false; - buffer.format = get(words[3], 12, 7); - buffer.oob_select = OobSelect(get(words[3], 28, 2)); - out = buffer; - return true; -} - -} // namespace leonida::gfx10 diff --git a/runtime/src/gfx10_tiling.h b/runtime/src/gfx10_tiling.h deleted file mode 100644 index d869d1102..000000000 --- a/runtime/src/gfx10_tiling.h +++ /dev/null @@ -1,158 +0,0 @@ -#pragma once - -#include -#include -#include -#include -#include -#include - -namespace leonida::gfx10 { - -enum class TileMode { sw_4kb_s, sw_64kb_d }; - -namespace tiling_detail { - -// Mesa addrlib GFX10_SW_4K_S_RBPLUS_PATINFO / GFX10_SW_64K_D_RBPLUS_PATINFO; -// tools/ttpf_mips.py patterns, corpus validation in docs/textures.md. Zero bits address bytes within an element. -inline constexpr int patterns_4k[5][12] = { - {1, 2, 3, 4, -1, -2, -3, -4, -5, 5, -6, 6}, - {0, 1, 2, 3, -1, -2, -3, 4, -4, 5, -5, 6}, - {0, 0, 1, 2, -1, -2, -3, 3, -4, 4, -5, 5}, - {0, 0, 0, 1, -1, -2, 2, 3, -3, 4, -4, 5}, - {0, 0, 0, 0, -1, -2, 1, 2, -3, 3, -4, 4}}; -inline constexpr int patterns_64k[5][16] = { - {1, 2, 3, -2, -1, -3, 4, -4, -5, 5, -6, 6, -7, 7, -8, 8}, - {0, 1, 2, 3, -1, -2, -3, 4, -4, 5, -5, 6, -6, 7, -7, 8}, - {0, 0, 1, 2, -1, -2, 3, -3, -4, 4, -5, 5, -6, 6, -7, 7}, - {0, 0, 0, 1, -1, 2, 3, -2, -3, 4, -4, 5, -5, 6, -6, 7}, - {0, 0, 0, 0, 1, -1, 2, -2, -3, 3, -4, 4, -5, 5, -6, 6}}; - -inline bool overlap(std::span source, std::span destination) { - const auto a = reinterpret_cast(source.data()); - const auto b = reinterpret_cast(destination.data()); - return a <= b ? b - a < source.size() : a - b < destination.size(); -} - -} // namespace tiling_detail - -// One standalone 2D level, no mip tail or tile XOR. BC formats use a compressed block as one element. -class TiledSurface2D { -public: - static bool make(TileMode mode, std::size_t element_bytes, std::size_t width, std::size_t height, - TiledSurface2D& out) { - if (!width || !height) return false; - unsigned index = 0; - switch (element_bytes) { - case 1: break; - case 2: index = 1; break; - case 4: index = 2; break; - case 8: index = 3; break; - case 16: index = 4; break; - default: return false; - } - TiledSurface2D next; - switch (mode) { - case TileMode::sw_4kb_s: - next.pattern_ = tiling_detail::patterns_4k[index]; - next.bits_ = 12; - break; - case TileMode::sw_64kb_d: - next.pattern_ = tiling_detail::patterns_64k[index]; - next.bits_ = 16; - break; - default: return false; - } - unsigned x_bits = 0, y_bits = 0; - for (unsigned bit = 0; bit < next.bits_; ++bit) { - x_bits += next.pattern_[bit] > 0; - y_bits += next.pattern_[bit] < 0; - } - next.tile_width_ = std::size_t{1} << x_bits; - next.tile_height_ = std::size_t{1} << y_bits; - next.tiles_x_ = (width - 1) / next.tile_width_ + 1; - const std::size_t tiles_y = (height - 1) / next.tile_height_ + 1; - const std::size_t tile_bytes = std::size_t{1} << next.bits_; - constexpr auto max = std::numeric_limits::max(); - if (next.tiles_x_ > max / tiles_y || next.tiles_x_ * tiles_y > max / tile_bytes) return false; - next.size_ = next.tiles_x_ * tiles_y * tile_bytes; - next.width_ = width; - next.height_ = height; - next.element_bytes_ = element_bytes; - out = next; - return true; - } - - std::size_t tiled_size() const { return size_; } - std::size_t tile_width() const { return tile_width_; } - std::size_t tile_height() const { return tile_height_; } - - bool element_offset(std::size_t x, std::size_t y, std::size_t& offset) const { - if (!size_ || x >= width_ || y >= height_) return false; - offset = address(x, y); - return true; - } - - // Buffers must not overlap. Padding in either destination is left untouched; failure writes nothing. - bool detile(std::span tiled, std::span linear, std::size_t row_pitch) const { - return copy(tiled, linear, row_pitch, false); - } - - bool tile(std::span linear, std::span tiled, std::size_t row_pitch) const { - return copy(linear, tiled, row_pitch, true); - } - -private: - std::size_t address(std::size_t x, std::size_t y) const { - std::size_t offset = ((y / tile_height_) * tiles_x_ + x / tile_width_) << bits_; - for (unsigned bit = 0; bit < bits_; ++bit) { - const int source = pattern_[bit]; - if (source > 0) offset |= ((x >> (source - 1)) & 1) << bit; - else if (source < 0) offset |= ((y >> (-source - 1)) & 1) << bit; - } - return offset; - } - - bool copy(std::span source, std::span destination, std::size_t pitch, - bool to_tiled) const { - if (!size_) return false; - const std::size_t row_bytes = width_ * element_bytes_; - if (pitch < row_bytes || (height_ - 1 && - pitch > (std::numeric_limits::max() - row_bytes) / (height_ - 1))) return false; - const std::size_t linear_size = (height_ - 1) * pitch + row_bytes; - if (source.size() < (to_tiled ? linear_size : size_) || - destination.size() < (to_tiled ? size_ : linear_size) || - tiling_detail::overlap(source, destination)) return false; - const auto tile_x_bits = std::countr_zero(tile_width_); - std::size_t x_offsets[256]{}; - for (std::size_t x = 0; x < tile_width_; ++x) { - for (unsigned bit = 0; bit < bits_; ++bit) { - const int source_bit = pattern_[bit]; - if (source_bit > 0) x_offsets[x] |= ((x >> (source_bit - 1)) & 1) << bit; - } - } - for (std::size_t y = 0; y < height_; ++y) { - std::size_t y_offset = 0; - for (unsigned bit = 0; bit < bits_; ++bit) { - const int source_bit = pattern_[bit]; - if (source_bit < 0) y_offset |= ((y >> (-source_bit - 1)) & 1) << bit; - } - const std::size_t tile_row = (y / tile_height_) * tiles_x_; - for (std::size_t x = 0; x < width_; ++x) { - const std::size_t linear = y * pitch + x * element_bytes_; - const std::size_t tiled = ((tile_row + (x >> tile_x_bits)) << bits_) + - y_offset + x_offsets[x & (tile_width_ - 1)]; - std::memcpy(destination.data() + (to_tiled ? tiled : linear), - source.data() + (to_tiled ? linear : tiled), element_bytes_); - } - } - return true; - } - - const int* pattern_ = nullptr; - unsigned bits_ = 0; - std::size_t width_ = 0, height_ = 0, element_bytes_ = 0; - std::size_t tile_width_ = 0, tile_height_ = 0, tiles_x_ = 0, size_ = 0; -}; - -} // namespace leonida::gfx10 diff --git a/runtime/src/host_cpu.cpp b/runtime/src/host_cpu.cpp deleted file mode 100644 index e6276b259..000000000 --- a/runtime/src/host_cpu.cpp +++ /dev/null @@ -1,66 +0,0 @@ -#include "host_cpu.h" - -#include "../core/config.h" - -#if defined(_M_X64) || defined(__x86_64__) -#if defined(_MSC_VER) -#include -#else -#include -#endif -#endif - -namespace rt::host_cpu { - -std::vector missing_host_features(uint32_t cpuid1_ecx, uint64_t (*read_xcr0)()) { - std::vector missing; - if (!(cpuid1_ecx & kCpuid1EcxAvx)) missing.push_back(kMissingAvx); - if (!(cpuid1_ecx & kCpuid1EcxOsxsave)) - missing.push_back(kMissingOsxsave); // XGETBV is #UD without OSXSAVE: XCR0 is not read - else if ((read_xcr0() & kXcr0SseYmm) != kXcr0SseYmm) - missing.push_back(kMissingYmmState); - return missing; -} - -#if defined(_M_X64) || defined(__x86_64__) -namespace { - -uint32_t cpuid1_ecx() { -#if defined(_MSC_VER) - int r[4] = {}; - __cpuid(r, 1); - return static_cast(r[2]); -#else - unsigned a = 0, b = 0, c = 0, d = 0; - return __get_cpuid(1, &a, &b, &c, &d) ? c : 0; -#endif -} - -uint64_t xcr0() { -#if defined(_MSC_VER) - return _xgetbv(0); -#else - uint32_t lo = 0, hi = 0; - __asm__ volatile("xgetbv" : "=a"(lo), "=d"(hi) : "c"(0)); - return (static_cast(hi) << 32) | lo; -#endif -} - -} // namespace - -std::vector missing_host_features() { return missing_host_features(cpuid1_ecx(), &xcr0); } -#else -std::vector missing_host_features() { return {}; } -#endif - -std::string message(const std::vector& missing) { - std::string names; - for (const char* m : missing) names += (names.empty() ? "" : ", ") + std::string(m); - return "error: the game's code needs AVX, and this CPU or OS lacks " + names + - "; in a virtual machine, pass the host CPU through (for example QEMU -cpu host); under Rosetta on " - "macOS, set ROSETTA_ADVERTISE_AVX=1. LEONIDA_SKIP_CPU_CHECK=1 skips this check"; -} - -bool check_skipped() { return rt::config::get("loader.skip_cpu_check").text == "1"; } - -} // namespace rt::host_cpu diff --git a/runtime/src/host_cpu.h b/runtime/src/host_cpu.h deleted file mode 100644 index b9dd143db..000000000 --- a/runtime/src/host_cpu.h +++ /dev/null @@ -1,38 +0,0 @@ -// Host CPU preflight for --init and --run: the game executes AVX instructions from its TLS callbacks on, so a host -// whose CPU or OS lacks AVX (a QEMU qemu64 guest, for one) dies there with a bare EXCEPTION_ILLEGAL_INSTRUCTION -// (0xC000001D) that reads like a loader bug. This checks AVX only, which is what was measured; it claims nothing -// about AVX2, FMA or BMI2. No emulation here: that is RT-500's scope. Rosetta on macOS runs AVX code but leaves -// AVX out of CPUID unless ROSETTA_ADVERTISE_AVX=1 is set, so the check fails there until that variable is set. -#pragma once - -#include -#include -#include - -namespace rt::host_cpu { - -constexpr uint32_t kCpuid1EcxOsxsave = 1u << 27; // CPUID.1:ECX.OSXSAVE: the OS enabled XSAVE, XGETBV is usable -constexpr uint32_t kCpuid1EcxAvx = 1u << 28; // CPUID.1:ECX.AVX -constexpr uint64_t kXcr0SseYmm = 0x6; // XCR0 bits 1 (SSE state) and 2 (AVX/YMM state) - -// gta6rt's exit code when the check fails (2 is a usage error, 3 is LEONIDA_UNIMPLEMENTED=stop). -constexpr int kExitCode = 4; - -constexpr const char* kMissingAvx = "AVX"; -constexpr const char* kMissingOsxsave = "OSXSAVE"; -constexpr const char* kMissingYmmState = "OS support for YMM state (XCR0 bits 1-2)"; - -// The features missing for the game's AVX code, from CPUID.1:ECX. read_xcr0 is called only when OSXSAVE is set, -// because XGETBV faults without it. An empty list means the host can run AVX code. -std::vector missing_host_features(uint32_t cpuid1_ecx, uint64_t (*read_xcr0)()); - -// The same for the running host: CPUID leaf 1 and XGETBV(0). Empty on a host that is not x86-64. -std::vector missing_host_features(); - -// The one stderr line gta6rt prints when the list is not empty. -std::string message(const std::vector& missing); - -// LEONIDA_SKIP_CPU_CHECK=1 skips the check (for the #UD emulation work). -bool check_skipped(); - -} // namespace rt::host_cpu diff --git a/runtime/src/indirect_dispatch_count.comp b/runtime/src/indirect_dispatch_count.comp deleted file mode 100644 index 9cbc371d9..000000000 --- a/runtime/src/indirect_dispatch_count.comp +++ /dev/null @@ -1,34 +0,0 @@ -// Clamp a GPU-written D3D12 ExecuteIndirect DISPATCH count without reading it on the CPU. -// Each record is a VkDispatchIndirectCommand (three uints); disabled records are zero. -#version 460 -#extension GL_EXT_buffer_reference : require -layout(local_size_x = 64) in; -layout(buffer_reference, std430, buffer_reference_align = 4) readonly buffer WordsIn { - uint data[]; -}; -layout(buffer_reference, std430, buffer_reference_align = 4) buffer WordsOut { - uint data[]; -}; -layout(push_constant) uniform Params { - WordsIn arguments; - WordsIn count; - WordsOut output_words; - uint stride_words; - uint first_record; - uint records; -} p; -void main() { - const uint local_record = gl_GlobalInvocationID.x; - if (local_record >= p.records) return; - const uint target = local_record * 3u; - if (p.first_record + local_record < p.count.data[0]) { - const uint source = local_record * p.stride_words; - p.output_words.data[target] = p.arguments.data[source]; - p.output_words.data[target + 1u] = p.arguments.data[source + 1u]; - p.output_words.data[target + 2u] = p.arguments.data[source + 2u]; - } else { - p.output_words.data[target] = 0u; - p.output_words.data[target + 1u] = 0u; - p.output_words.data[target + 2u] = 0u; - } -} diff --git a/runtime/src/indirect_dispatch_count_spv.h b/runtime/src/indirect_dispatch_count_spv.h deleted file mode 100644 index 9cf7bbae5..000000000 --- a/runtime/src/indirect_dispatch_count_spv.h +++ /dev/null @@ -1,84 +0,0 @@ -// Generated with glslangValidator -V --target-env vulkan1.2 -Os --spirv-val indirect_dispatch_count.comp -#pragma once -#include -namespace leonida { -inline constexpr std::uint32_t indirect_dispatch_count_spirv[] = { - 0x07230203u, 0x00010500u, 0x0008000bu, 0x00000074u, 0x00000000u, 0x00020011u, 0x00000001u, 0x00020011u, - 0x000014e3u, 0x0006000bu, 0x00000001u, 0x4c534c47u, 0x6474732eu, 0x3035342eu, 0x00000000u, 0x0003000eu, - 0x000014e4u, 0x00000001u, 0x0007000fu, 0x00000005u, 0x00000004u, 0x6e69616du, 0x00000000u, 0x0000000bu, - 0x00000019u, 0x00060010u, 0x00000004u, 0x00000011u, 0x00000040u, 0x00000001u, 0x00000001u, 0x00030003u, - 0x00000002u, 0x000001ccu, 0x00070004u, 0x455f4c47u, 0x625f5458u, 0x65666675u, 0x65725f72u, 0x65726566u, - 0x0065636eu, 0x00040005u, 0x00000004u, 0x6e69616du, 0x00000000u, 0x00080005u, 0x0000000bu, 0x475f6c67u, - 0x61626f6cu, 0x766e496cu, 0x7461636fu, 0x496e6f69u, 0x00000044u, 0x00040005u, 0x00000013u, 0x61726150u, - 0x0000736du, 0x00060006u, 0x00000013u, 0x00000000u, 0x75677261u, 0x746e656du, 0x00000073u, 0x00050006u, - 0x00000013u, 0x00000001u, 0x6e756f63u, 0x00000074u, 0x00070006u, 0x00000013u, 0x00000002u, 0x7074756fu, - 0x775f7475u, 0x7364726fu, 0x00000000u, 0x00070006u, 0x00000013u, 0x00000003u, 0x69727473u, 0x775f6564u, - 0x7364726fu, 0x00000000u, 0x00070006u, 0x00000013u, 0x00000004u, 0x73726966u, 0x65725f74u, 0x64726f63u, - 0x00000000u, 0x00050006u, 0x00000013u, 0x00000005u, 0x6f636572u, 0x00736472u, 0x00040005u, 0x00000015u, - 0x64726f57u, 0x006e4973u, 0x00050006u, 0x00000015u, 0x00000000u, 0x61746164u, 0x00000000u, 0x00050005u, - 0x00000017u, 0x64726f57u, 0x74754f73u, 0x00000000u, 0x00050006u, 0x00000017u, 0x00000000u, 0x61746164u, - 0x00000000u, 0x00030005u, 0x00000019u, 0x00000070u, 0x00040047u, 0x0000000bu, 0x0000000bu, 0x0000001cu, - 0x00030047u, 0x00000013u, 0x00000002u, 0x00050048u, 0x00000013u, 0x00000000u, 0x00000023u, 0x00000000u, - 0x00050048u, 0x00000013u, 0x00000001u, 0x00000023u, 0x00000008u, 0x00050048u, 0x00000013u, 0x00000002u, - 0x00000023u, 0x00000010u, 0x00050048u, 0x00000013u, 0x00000003u, 0x00000023u, 0x00000018u, 0x00050048u, - 0x00000013u, 0x00000004u, 0x00000023u, 0x0000001cu, 0x00050048u, 0x00000013u, 0x00000005u, 0x00000023u, - 0x00000020u, 0x00040047u, 0x00000014u, 0x00000006u, 0x00000004u, 0x00030047u, 0x00000015u, 0x00000002u, - 0x00040048u, 0x00000015u, 0x00000000u, 0x00000018u, 0x00050048u, 0x00000015u, 0x00000000u, 0x00000023u, - 0x00000000u, 0x00040047u, 0x00000016u, 0x00000006u, 0x00000004u, 0x00030047u, 0x00000017u, 0x00000002u, - 0x00050048u, 0x00000017u, 0x00000000u, 0x00000023u, 0x00000000u, 0x00040047u, 0x00000071u, 0x0000000bu, - 0x00000019u, 0x00020013u, 0x00000002u, 0x00030021u, 0x00000003u, 0x00000002u, 0x00040015u, 0x00000006u, - 0x00000020u, 0x00000000u, 0x00040017u, 0x00000009u, 0x00000006u, 0x00000003u, 0x00040020u, 0x0000000au, - 0x00000001u, 0x00000009u, 0x0004003bu, 0x0000000au, 0x0000000bu, 0x00000001u, 0x0004002bu, 0x00000006u, - 0x0000000cu, 0x00000000u, 0x00040020u, 0x0000000du, 0x00000001u, 0x00000006u, 0x00030027u, 0x00000011u, - 0x000014e5u, 0x00030027u, 0x00000012u, 0x000014e5u, 0x0008001eu, 0x00000013u, 0x00000011u, 0x00000011u, - 0x00000012u, 0x00000006u, 0x00000006u, 0x00000006u, 0x0003001du, 0x00000014u, 0x00000006u, 0x0003001eu, - 0x00000015u, 0x00000014u, 0x00040020u, 0x00000011u, 0x000014e5u, 0x00000015u, 0x0003001du, 0x00000016u, - 0x00000006u, 0x0003001eu, 0x00000017u, 0x00000016u, 0x00040020u, 0x00000012u, 0x000014e5u, 0x00000017u, - 0x00040020u, 0x00000018u, 0x00000009u, 0x00000013u, 0x0004003bu, 0x00000018u, 0x00000019u, 0x00000009u, - 0x00040015u, 0x0000001au, 0x00000020u, 0x00000001u, 0x0004002bu, 0x0000001au, 0x0000001bu, 0x00000005u, - 0x00040020u, 0x0000001cu, 0x00000009u, 0x00000006u, 0x00020014u, 0x0000001fu, 0x0004002bu, 0x00000006u, - 0x00000026u, 0x00000003u, 0x0004002bu, 0x0000001au, 0x00000028u, 0x00000004u, 0x0004002bu, 0x0000001au, - 0x0000002du, 0x00000001u, 0x00040020u, 0x0000002eu, 0x00000009u, 0x00000011u, 0x0004002bu, 0x0000001au, - 0x00000031u, 0x00000000u, 0x00040020u, 0x00000032u, 0x000014e5u, 0x00000006u, 0x0004002bu, 0x0000001au, - 0x0000003au, 0x00000003u, 0x0004002bu, 0x0000001au, 0x0000003eu, 0x00000002u, 0x00040020u, 0x0000003fu, - 0x00000009u, 0x00000012u, 0x0004002bu, 0x00000006u, 0x0000004cu, 0x00000001u, 0x0004002bu, 0x00000006u, - 0x00000058u, 0x00000002u, 0x0004002bu, 0x00000006u, 0x00000070u, 0x00000040u, 0x0006002cu, 0x00000009u, - 0x00000071u, 0x00000070u, 0x0000004cu, 0x0000004cu, 0x00050036u, 0x00000002u, 0x00000004u, 0x00000000u, - 0x00000003u, 0x000200f8u, 0x00000005u, 0x000300f7u, 0x00000072u, 0x00000000u, 0x000300fbu, 0x0000000cu, - 0x00000073u, 0x000200f8u, 0x00000073u, 0x00050041u, 0x0000000du, 0x0000000eu, 0x0000000bu, 0x0000000cu, - 0x0004003du, 0x00000006u, 0x0000000fu, 0x0000000eu, 0x00050041u, 0x0000001cu, 0x0000001du, 0x00000019u, - 0x0000001bu, 0x0004003du, 0x00000006u, 0x0000001eu, 0x0000001du, 0x000500aeu, 0x0000001fu, 0x00000020u, - 0x0000000fu, 0x0000001eu, 0x000300f7u, 0x00000022u, 0x00000000u, 0x000400fau, 0x00000020u, 0x00000021u, - 0x00000022u, 0x000200f8u, 0x00000021u, 0x000200f9u, 0x00000072u, 0x000200f8u, 0x00000022u, 0x00050084u, - 0x00000006u, 0x00000027u, 0x0000000fu, 0x00000026u, 0x00050041u, 0x0000001cu, 0x00000029u, 0x00000019u, - 0x00000028u, 0x0004003du, 0x00000006u, 0x0000002au, 0x00000029u, 0x00050080u, 0x00000006u, 0x0000002cu, - 0x0000002au, 0x0000000fu, 0x00050041u, 0x0000002eu, 0x0000002fu, 0x00000019u, 0x0000002du, 0x0004003du, - 0x00000011u, 0x00000030u, 0x0000002fu, 0x00060041u, 0x00000032u, 0x00000033u, 0x00000030u, 0x00000031u, - 0x00000031u, 0x0006003du, 0x00000006u, 0x00000034u, 0x00000033u, 0x00000002u, 0x00000004u, 0x000500b0u, - 0x0000001fu, 0x00000035u, 0x0000002cu, 0x00000034u, 0x000300f7u, 0x00000037u, 0x00000000u, 0x000400fau, - 0x00000035u, 0x00000036u, 0x00000061u, 0x000200f8u, 0x00000036u, 0x00050041u, 0x0000001cu, 0x0000003bu, - 0x00000019u, 0x0000003au, 0x0004003du, 0x00000006u, 0x0000003cu, 0x0000003bu, 0x00050084u, 0x00000006u, - 0x0000003du, 0x0000000fu, 0x0000003cu, 0x00050041u, 0x0000003fu, 0x00000040u, 0x00000019u, 0x0000003eu, - 0x0004003du, 0x00000012u, 0x00000041u, 0x00000040u, 0x00050041u, 0x0000002eu, 0x00000043u, 0x00000019u, - 0x00000031u, 0x0004003du, 0x00000011u, 0x00000044u, 0x00000043u, 0x00060041u, 0x00000032u, 0x00000046u, - 0x00000044u, 0x00000031u, 0x0000003du, 0x0006003du, 0x00000006u, 0x00000047u, 0x00000046u, 0x00000002u, - 0x00000004u, 0x00060041u, 0x00000032u, 0x00000048u, 0x00000041u, 0x00000031u, 0x00000027u, 0x0005003eu, - 0x00000048u, 0x00000047u, 0x00000002u, 0x00000004u, 0x00050080u, 0x00000006u, 0x0000004du, 0x00000027u, - 0x0000004cu, 0x00050080u, 0x00000006u, 0x00000051u, 0x0000003du, 0x0000004cu, 0x00060041u, 0x00000032u, - 0x00000052u, 0x00000044u, 0x00000031u, 0x00000051u, 0x0006003du, 0x00000006u, 0x00000053u, 0x00000052u, - 0x00000002u, 0x00000004u, 0x00060041u, 0x00000032u, 0x00000054u, 0x00000041u, 0x00000031u, 0x0000004du, - 0x0005003eu, 0x00000054u, 0x00000053u, 0x00000002u, 0x00000004u, 0x00050080u, 0x00000006u, 0x00000059u, - 0x00000027u, 0x00000058u, 0x00050080u, 0x00000006u, 0x0000005du, 0x0000003du, 0x00000058u, 0x00060041u, - 0x00000032u, 0x0000005eu, 0x00000044u, 0x00000031u, 0x0000005du, 0x0006003du, 0x00000006u, 0x0000005fu, - 0x0000005eu, 0x00000002u, 0x00000004u, 0x00060041u, 0x00000032u, 0x00000060u, 0x00000041u, 0x00000031u, - 0x00000059u, 0x0005003eu, 0x00000060u, 0x0000005fu, 0x00000002u, 0x00000004u, 0x000200f9u, 0x00000037u, - 0x000200f8u, 0x00000061u, 0x00050041u, 0x0000003fu, 0x00000062u, 0x00000019u, 0x0000003eu, 0x0004003du, - 0x00000012u, 0x00000063u, 0x00000062u, 0x00060041u, 0x00000032u, 0x00000065u, 0x00000063u, 0x00000031u, - 0x00000027u, 0x0005003eu, 0x00000065u, 0x0000000cu, 0x00000002u, 0x00000004u, 0x00050080u, 0x00000006u, - 0x00000069u, 0x00000027u, 0x0000004cu, 0x00060041u, 0x00000032u, 0x0000006au, 0x00000063u, 0x00000031u, - 0x00000069u, 0x0005003eu, 0x0000006au, 0x0000000cu, 0x00000002u, 0x00000004u, 0x00050080u, 0x00000006u, - 0x0000006eu, 0x00000027u, 0x00000058u, 0x00060041u, 0x00000032u, 0x0000006fu, 0x00000063u, 0x00000031u, - 0x0000006eu, 0x0005003eu, 0x0000006fu, 0x0000000cu, 0x00000002u, 0x00000004u, 0x000200f9u, 0x00000037u, - 0x000200f8u, 0x00000037u, 0x000200f9u, 0x00000072u, 0x000200f8u, 0x00000072u, 0x000100fdu, 0x00010038u, -}; -} // namespace leonida diff --git a/runtime/src/main.cpp b/runtime/src/main.cpp deleted file mode 100644 index 01d82f364..000000000 --- a/runtime/src/main.cpp +++ /dev/null @@ -1,339 +0,0 @@ -// gta6rt: native runtime for the Xbox Series build. -// -// gta6rt --dry-run [--game-dir DIR] [--overlay DIR] -// Maps the image and its bundled modules, applies relocations, binds every import, installs static TLS for -// this thread and prints a report. No code from the mapped images -// runs. TLS needs the runtime's own gta6rt_tls_host.dll, which reserves the module TLS index; system DLLs are -// loaded to resolve host imports, as before. -// -// gta6rt --init [--game-dir DIR] [--overlay DIR] -// The same mapping, then each loaded DLL's TLS callbacks and DllMain(DLL_PROCESS_ATTACH) are run. -// -// gta6rt --run [--game-dir DIR] [--overlay DIR] [--trace-d3d12] [--trace FILE] [-- game arguments...] -// The same, then the EXE's own TLS callbacks and its entry point, on a game thread. The game's argv and -// command line are plus the arguments after "--"; exit/ExitProcess from the game end the run -// (shims/process.cpp). gta6rt prints the binding report first and returns the game's exit code. -// -// --game-dir is also where a title's GAME: paths read from; anything it writes or deletes goes to the overlay -// (--overlay, default /overlay) so the package is never modified (shims/file_system.cpp). -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include "base_reservation.h" -#include "code_hooks.h" -#include "cpu_emulation.h" -#include "host_cpu.h" -#include "mods.h" -#include "pe_loader.h" -#include "../core/config.h" -#include "../core/log.h" -#include "../shims/d3d12_trace.h" -#include "../shims/d3d12_xs_device.h" -#include "../shims/file_system.h" -#include "../shims/process_shim.h" -#include "../shims/shims.h" -#include "../shims/startup_trace.h" -#include "../shims/xmem.h" - -namespace { - -const char* binding_name(rt::Binding b) { - switch (b) { - case rt::Binding::Shim: return "shim"; - case rt::Binding::Host: return "host"; - case rt::Binding::Module: return "module"; - default: return "UNIMPLEMENTED"; - } -} - -// The folder of gta6rt.exe; empty when Windows does not give its path. -std::filesystem::path program_dir() { - std::wstring self(32768, L'\0'); - const DWORD n = GetModuleFileNameW(nullptr, self.data(), static_cast(self.size())); - if (!n || n >= self.size()) return {}; - return std::filesystem::path(self.substr(0, n)).parent_path(); -} - -int usage() { - std::fprintf(stderr, - "usage: gta6rt config\n" - " gta6rt --dry-run [--game-dir DIR] [--overlay DIR] [--mods DIR] [--archetype-lookup RVA[,ARG]] [--view-mode-getter RVA] [--trace FILE]\n" - " gta6rt --init [--game-dir DIR] [--overlay DIR] [--mods DIR] [--archetype-lookup RVA[,ARG]] [--view-mode-getter RVA] [--trace-d3d12] [--trace FILE]\n" - " gta6rt --run [--game-dir DIR] [--overlay DIR] [--mods DIR] [--archetype-lookup RVA[,ARG]] [--view-mode-getter RVA] [--trace-d3d12] [--trace FILE] [-- game arguments...]\n"); - return 2; -} - -// Prints UTF-8 text to stdout: as wide text on a console, which shows a path the code page lacks, and as the bytes -// themselves into a pipe or a file. -void print_utf8(const std::string& text) { - const HANDLE out = GetStdHandle(STD_OUTPUT_HANDLE); - DWORD mode; - if (GetConsoleMode(out, &mode)) { - const int size = MultiByteToWideChar(CP_UTF8, 0, text.data(), static_cast(text.size()), nullptr, 0); - std::wstring wide(static_cast(size > 0 ? size : 0), L'\0'); - if (size > 0) MultiByteToWideChar(CP_UTF8, 0, text.data(), static_cast(text.size()), wide.data(), size); - std::fflush(stdout); - DWORD written; - if (WriteConsoleW(out, wide.data(), static_cast(wide.size()), &written, nullptr)) return; - } - std::fwrite(text.data(), 1, text.size(), stdout); -} - -} // namespace - -int wmain(int argc, wchar_t** argv) { - // The settings file, before anything reads a setting (core/config.h). A file that cannot be read, or that names - // a setting that does not exist, ends the run: a misspelt setting must not pass as one that does nothing. - if (std::string error; !rt::config::load(program_dir(), &error)) { - std::fprintf(stderr, "error: %s\n", error.c_str()); - return 2; - } - // The log level (core/log.h), before the first "[rt]" line. A gta6rt that was started again to reserve the image - // range (base_reservation.h) reads the same setting; the first one already printed the warning for a value that - // is not a level. - rt::log::apply_settings(!rt::base_reservation::inherited().has_value()); - // `gta6rt config`, alone on the command line: every setting, its value and where the value comes from. - if (argc == 2 && std::wstring_view(argv[1]) == L"config") { - print_utf8(rt::config::report()); - return 0; - } - std::filesystem::path image, game_dir, overlay_dir, mods_dir; - uint32_t archetype_lookup_rva = 0; // --archetype-lookup RVA[,ARG]: the game's archetype lookup by hash - int archetype_lookup_arg = 0; - uint32_t view_mode_getter_rva = 0; // --view-mode-getter RVA: the game's view mode of a camera context - bool dry_run = false, init = false, run = false, trace_d3d12 = false; - std::vector game_args; // wide: path::string() throws on a character the code page lacks (RT-84) - std::wstring trace_file; - for (int i = 1; i < argc; ++i) { - std::wstring a = argv[i]; - if (a == L"--") { - for (++i; i < argc; ++i) game_args.push_back(argv[i]); - break; - } - if (a == L"--dry-run") dry_run = true; - else if (a == L"--init") init = true; - else if (a == L"--run") run = true; - else if (a == L"--trace-d3d12") trace_d3d12 = true; - else if (a == L"--trace" && i + 1 < argc) trace_file = argv[++i]; - else if (a == L"--game-dir" && i + 1 < argc) game_dir = argv[++i]; - else if (a == L"--overlay" && i + 1 < argc) overlay_dir = argv[++i]; - else if (a == L"--mods" && i + 1 < argc) mods_dir = argv[++i]; - else if (a == L"--view-mode-getter" && i + 1 < argc) { - wchar_t* end = nullptr; - const unsigned long rva = std::wcstoul(argv[++i], &end, 16); - if (!end || *end || rva == 0) return usage(); - view_mode_getter_rva = static_cast(rva); - } - else if (a == L"--archetype-lookup" && i + 1 < argc) { - const std::wstring v = argv[++i]; - const auto comma = v.find(L','); - wchar_t* end = nullptr; - const unsigned long rva = std::wcstoul(v.substr(0, comma).c_str(), &end, 16); - if (!end || *end || rva == 0) return usage(); - archetype_lookup_rva = static_cast(rva); - if (comma != std::wstring::npos) archetype_lookup_arg = v.substr(comma + 1) == L"1" ? 1 : 0; - } - else if (image.empty()) image = a; - else return usage(); - } - if (image.empty()) return usage(); - // Exactly one mode: --dry-run --run would otherwise initialise the modules and call the entry point. - if (dry_run + init + run != 1) return usage(); - // The game runs AVX code from its TLS callbacks on; without AVX that is a bare 0xC000001D (src/host_cpu.h). - if ((init || run) && !rt::host_cpu::check_skipped()) - if (const auto missing = rt::host_cpu::missing_host_features(); !missing.empty()) { - std::fprintf(stderr, "%s\n", rt::host_cpu::message(missing).c_str()); - return rt::host_cpu::kExitCode; - } - // The console folders are fixed once, as absolute paths. A bare image name (`gta6rt --run game.exe` from the - // game folder) has an empty parent path, which left GAME: with no root; and a relative --game-dir or --overlay - // would follow the title's later SetCurrentDirectory. If absolute() fails the path stays as given. - const auto absolute_or_same = [](const std::filesystem::path& p) { - std::error_code ec; - std::filesystem::path a = std::filesystem::absolute(p, ec); - return ec ? p : a; - }; - game_dir = game_dir.empty() ? absolute_or_same(image).parent_path() : absolute_or_same(game_dir); - if (!overlay_dir.empty()) overlay_dir = absolute_or_same(overlay_dir); - // paths.shaders (LEONIDA_SHADERS, else leonida.toml) too: the D3D12 device reads it at the title's first - // pipeline state, after it may have moved. The absolute path goes into the variable, which wins over the file, - // so a relative path in either is taken from the folder gta6rt was started in. - if (const std::filesystem::path shaders = rt::config::path("paths.shaders"); !shaders.empty()) - SetEnvironmentVariableW(L"LEONIDA_SHADERS", absolute_or_same(shaders).c_str()); - // An image without relocations whose range this process already uses (arm64 Wine on macOS) runs in a new - // process that has the range reserved from the start (base_reservation.h); that process does not do this again. - if (!rt::base_reservation::inherited()) - if (const auto range = rt::base_reservation::needed(image)) return rt::base_reservation::relaunch(*range); - // GAME: paths read under --game-dir; whatever a title writes lands in the overlay, never in the package. - if (overlay_dir.empty()) overlay_dir = game_dir / "overlay"; - rt::fs::configure(game_dir, overlay_dir); - // Mods (docs/modding.md): \mods unless --mods names another. Loaded and reported here; - // the archetype swaps take effect once the game's archetype lookup is hooked for this executable version. - if (mods_dir.empty()) { - std::wstring self(32768, L'\0'); - const DWORD n = GetModuleFileNameW(nullptr, self.data(), static_cast(self.size())); - if (n && n < self.size()) mods_dir = std::filesystem::path(self.substr(0, n)).parent_path() / L"mods"; - } - { - const leonida::mods::LoadResult mods = leonida::mods::load_mods(mods_dir); - for (const std::string& e : mods.errors) RT_LOG_WARN("mods: skipped %s\n", e.c_str()); - for (const auto& m : mods.mods) { - RT_LOG_INFO("mods: %s%s\n", m.name.c_str(), m.enabled ? "" : " (disabled)"); - for (const auto& sw : m.archetype_swaps) - RT_LOG_INFO("mods: archetype %s (0x%08X) -> %s (0x%08X)\n", sw.from_name.c_str(), - sw.from, sw.to_name.c_str(), sw.to); - } - leonida::mods::set_active(leonida::mods::ArchetypeSwaps(mods.mods)); - const leonida::mods::CameraView camera = leonida::mods::camera_of(mods.mods); - leonida::mods::set_active_camera(camera); - if (camera.first_person) - RT_LOG_INFO("mods: first-person view (value %u) for %s%s\n", camera.first_person_value, - camera.contexts.empty() ? "every context" : "the listed contexts", - view_mode_getter_rva ? "" : "; not applied: no --view-mode-getter RVA for this executable"); - if (leonida::mods::active().size()) { - if (archetype_lookup_rva) - RT_LOG_INFO("mods: %zu archetype swap(s) loaded\n", leonida::mods::active().size()); - else - RT_LOG_WARN("mods: %zu archetype swap(s) loaded; not applied: no --archetype-lookup RVA for " - "this executable (docs/modding.md)\n", leonida::mods::active().size()); - } - } - rt::d3d12_trace::set_enabled(trace_d3d12); - // Slot 133 imports the title's pages; xmem commits them on first touch, so they are committed first. - rt::d3d12_xs::set_placed_at_va_pages_hook(&rt::xmem::commit_physical_range); - // loader.skip_int3 (LEONIDA_SKIP_INT3), set before the trace's exception handler exists. The variable turns it on - // with any value, also 0, as before the setting moved to the table; in leonida.toml only true (or a value other - // than 0) does, so that skip_int3 = false there means off. - if (const rt::config::Value skip = rt::config::get("loader.skip_int3"); skip.is_set()) - rt::startup_trace::set_skip_int3(skip.source == rt::config::Source::Environment || skip.text != "0"); - if (int trace_error = 0; !trace_file.empty() && !rt::startup_trace::open(trace_file.c_str(), &trace_error)) { - std::fprintf(stderr, trace_error == EEXIST ? "error: the trace file already exists; --trace only creates a new file\n" - : "error: cannot create the trace file\n"); - return 2; - } - // The console's Zen 2 instructions this CPU may lack (docs/cpu_features.md): emulated on #UD. Installed after the - // trace's handler so it runs first, and an emulated instruction is not recorded as an exception. - if (const auto host = rt::cpu_emulation::detect_host(); !host.sse4a || !host.clzero || !host.monitorx || !host.clwb) - RT_LOG_WARN("cpu: this CPU lacks%s%s%s%s; the game's uses are emulated (docs/cpu_features.md)\n", - host.sse4a ? "" : " SSE4a", host.clzero ? "" : " CLZERO", host.monitorx ? "" : " MONITORX", - host.clwb ? "" : " CLWB"); - if (!rt::cpu_emulation::install()) - RT_LOG_ERROR("cpu: AddVectoredExceptionHandler failed (error %lu); instructions this CPU lacks " - "will stop the game\n", GetLastError()); - - try { - rt::Loader loader(game_dir); - rt::Module& main_module = loader.load(image); // maps, binds and installs TLS; runs no image code - // The mods' archetype swaps (docs/modding.md): hooked here, before any image code runs, when the lookup's RVA - // for this executable is given. The count of redirected calls shows whether the RVA is the real lookup. - if (view_mode_getter_rva) { - const auto r = leonida::hooks::hook_image_results(main_module.base, view_mode_getter_rva, - &leonida::mods::override_view_mode); - if (r.ok) - RT_LOG_INFO("mods: view-mode getter at RVA 0x%X hooked: %zu direct call(s) redirected\n", - view_mode_getter_rva, r.redirected); - else - RT_LOG_ERROR("mods: view-mode getter at RVA 0x%X not hooked: %s\n", view_mode_getter_rva, - r.error); - } - if (archetype_lookup_rva) { - const auto r = leonida::hooks::hook_image_calls( - main_module.base, archetype_lookup_rva, - [](uint32_t hash) { return leonida::mods::active().remap(hash); }, archetype_lookup_arg); - if (r.ok) - RT_LOG_INFO("mods: archetype lookup at RVA 0x%X hooked (argument %d): %zu direct " - "call(s) redirected\n", archetype_lookup_rva, archetype_lookup_arg, r.redirected); - else - RT_LOG_ERROR("mods: archetype lookup at RVA 0x%X not hooked: %s\n", archetype_lookup_rva, - r.error); - } - if (run) rt::process::set_command_line(image.filename().wstring(), game_args); - std::exception_ptr init_failure; - if (init || run) { - try { - loader.initialise(); // TLS callbacks, then DllMain(DLL_PROCESS_ATTACH) for DLLs - std::printf("%zu module(s) initialised\n", loader.modules().size()); - } catch (const std::exception&) { - // Keep the mapped modules available for the binding report on an attach failure. - init_failure = std::current_exception(); - } - } - int unimplemented = 0, unimplemented_hresult = 0; - for (auto* m : loader.modules()) { - std::map counts; - for (auto& r : m->imports) counts[r.binding]++; - std::printf("%-36s base=%p%s size=%u entry=+%#x shim=%d host=%d module=%d unimplemented=%d\n", - m->name.c_str(), m->base, m->relocated ? " (relocated)" : "", m->size, m->entry_rva, - counts[rt::Binding::Shim], counts[rt::Binding::Host], counts[rt::Binding::Module], - counts[rt::Binding::Unimplemented]); - for (auto& r : m->imports) - if (r.binding == rt::Binding::Unimplemented || r.binding == rt::Binding::Shim) { - const bool missing = r.binding == rt::Binding::Unimplemented; - const bool hresult = - missing && rt::shims::classify_import(r.dll, r.name) == rt::shims::ReturnClass::HResult; - std::printf(" %-13s %s!%s%s\n", binding_name(r.binding), r.dll.c_str(), r.name.c_str(), - hresult ? " [returns HRESULT]" : ""); - unimplemented += missing; - unimplemented_hresult += hresult; - } - } - std::printf("%zu module(s) mapped, %d unimplemented import(s)\n", loader.modules().size(), unimplemented); - std::printf("unimplemented by return policy: hresult=%d other=%d\n", unimplemented_hresult, - unimplemented - unimplemented_hresult); - if (init_failure) { - std::fflush(stdout); - std::rethrow_exception(init_failure); - } - if (!run) { - rt::startup_trace::event("exit", "\"code\":0"); - return 0; - } - if (!main_module.entry_rva) { - std::fprintf(stderr, "error: %s has no entry point\n", main_module.name.c_str()); - return 1; - } - const std::wstring paths = L"console paths: GAME: -> " + game_dir.native() + L", writes -> " + overlay_dir.native(); - const HANDLE out = GetStdHandle(STD_OUTPUT_HANDLE); - DWORD mode; - bool printed = false; - if (GetConsoleMode(out, &mode)) { - std::fflush(stdout); - const std::wstring line = paths + L"\r\n"; - DWORD written; - printed = WriteConsoleW(out, line.data(), static_cast(line.size()), &written, nullptr) != FALSE; - } - if (!printed) { - const auto game = game_dir.u8string(); - const auto overlay = overlay_dir.u8string(); - std::printf("console paths: GAME: -> %s, writes -> %s\n", - reinterpret_cast(game.c_str()), reinterpret_cast(overlay.c_str())); - } - std::printf("running %s\n", main_module.name.c_str()); - std::fflush(stdout); - const int code = rt::process::run_entry(main_module.base + main_module.entry_rva); - std::fflush(stdout); - std::printf("game exited with code %d\n", code); - rt::shims::report_called_unimplemented(); - rt::startup_trace::event("exit", "\"code\":" + std::to_string(code)); - std::fflush(stdout); - std::fflush(stderr); - // Not `return`: a normal host exit runs the CRT's atexit table, which the game shares with gta6rt (its - // handlers would run against a game that has stopped) and whose last word decides the exit status. - // ExitProcess also skips atexit, so the TLS clone cleanup registered there is run here instead. - rt::cleanup_tls_clones(); - ExitProcess(static_cast(code)); - } catch (const std::exception& e) { - std::fprintf(stderr, "error: %s\n", e.what()); - rt::startup_trace::event("error", "\"what\":" + rt::startup_trace::quote(e.what())); - return 1; - } -} diff --git a/runtime/src/mods.h b/runtime/src/mods.h deleted file mode 100644 index 10155bf19..000000000 --- a/runtime/src/mods.h +++ /dev/null @@ -1,291 +0,0 @@ -// Mods: folders under mods/ with a mod.json that the runtime reads at start (docs/modding.md). -// -// A mod never ships game data. It names things the game already has, by the names (or joaat hashes) the game uses, -// and says how to swap them. The first kind is an archetype swap: whenever the game asks for the model archetype -// `from`, it gets `to` instead (e.g. Lucia's player model player_story000_00 -> cs_mandy). Applying a swap needs one -// hook in the game: its archetype lookup by hash, whose address is per executable version and is filled in once the -// executable is analysed. Until then the swaps are loaded, checked and logged, and `remap_archetype` is ready for it. -// -// mod.json: -// { "name": "Mandy in the prison intro", "enabled": true, "game_version": "1.0.2.1", -// "archetype_swaps": [ { "from": "player_story000_00", "to": "cs_mandy", "when": "always" } ] } -// `from`/`to`: a model name (hashed with joaat, lower case, as the game does) or a 32-bit hash written "0x...". -// `when`: "always" (default). Narrower conditions (one mission, one cutscene) need the game's mission state and are -// rejected until a hook provides it, so a mod never silently does more than it says. -#pragma once - -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include "shader_library.h" // leonida::Json / JsonReader - -namespace leonida::mods { - -// RAGE's joaat (Jenkins one-at-a-time over the lower-cased name): joaat("player_story000_00") = 0xE472B687, -// joaat("cs_mandy") = 0xD7C0CDFF, the model ids docs/character_skeleton.md measured in the packs tables. -constexpr uint32_t joaat(std::string_view name) { - uint32_t h = 0; - for (char c : name) { - const auto u = static_cast(c >= 'A' && c <= 'Z' ? c - 'A' + 'a' : c); - h += u; - h += h << 10; - h ^= h >> 6; - } - h += h << 3; - h ^= h >> 11; - h += h << 15; - return h; -} - -struct ArchetypeSwap { - uint32_t from = 0, to = 0; - std::string from_name, to_name; // as written in mod.json - std::string when = "always"; -}; - -// "camera": the view mode the game's view-mode getter answers (docs/modding.md, "First-person view"). The getter -// takes a context (on foot, in a vehicle, ...) and returns an enum; `first_person_value` is that enum's first-person -// value, 4 in GTA V's camViewModeSettings, to be confirmed in the executable. `contexts`: the getter's first-argument -// values to override; empty = every context. -struct CameraView { - bool set = false; // the mod has a "camera" section - bool first_person = false; // "view_mode": "first_person" (else "default": leave the game's choice) - uint32_t first_person_value = 4; - std::vector contexts; -}; - -struct Mod { - std::string folder; // the folder name under mods/ - std::string name; - std::string game_version; - bool enabled = true; - std::vector archetype_swaps; - CameraView camera; -}; - -struct LoadResult { - std::vector mods; // every mod.json that parsed, enabled or not - std::vector errors; // ": what was wrong" (that mod is skipped) -}; - -// "0x..." -> that value; anything else -> joaat(name). Returns false for an empty name or a malformed hex value. -inline bool parse_model_id(const std::string& text, uint32_t& out) { - if (text.empty()) return false; - if (text.size() > 2 && text[0] == '0' && (text[1] == 'x' || text[1] == 'X')) { - if (text.size() > 10) return false; - uint32_t v = 0; - for (std::size_t i = 2; i < text.size(); ++i) { - const char c = text[i]; - const int d = c >= '0' && c <= '9' ? c - '0' : c >= 'a' && c <= 'f' ? c - 'a' + 10 - : c >= 'A' && c <= 'F' ? c - 'A' + 10 : -1; - if (d < 0) return false; - v = v << 4 | static_cast(d); - } - out = v; - return true; - } - out = joaat(text); - return true; -} - -// A JSON number that is a whole value in [0, max]. Checked before any integer cast: converting a double outside the -// target type's range is undefined, so `v != static_cast(v)` cannot be the test for a value past INT_MAX. -inline bool whole_number(double v, double max) { return v >= 0 && v <= max && v == std::floor(v); } - -// Parses one mod.json's text. On failure returns false with `error` set; `mod` is then not to be used. -inline bool parse_mod(std::string_view text, const std::string& folder, Mod& mod, std::string& error) { - // Windows editors and shells mark the encoding. Notepad's "UTF-8 with BOM" and Windows PowerShell 5.1's - // `-Encoding utf8` put EF BB BF in front of the same JSON, so it is skipped. PowerShell 5.1's `>` writes UTF-16, - // which is not readable as bytes: say so, instead of blaming the JSON. A NUL in the first two bytes is UTF-16 - // without a mark; no UTF-8 JSON text starts that way. - if (text.substr(0, 3) == std::string_view("\xEF\xBB\xBF", 3)) { - text.remove_prefix(3); - } else if (text.size() >= 2 && (text.substr(0, 2) == std::string_view("\xFF\xFE", 2) || - text.substr(0, 2) == std::string_view("\xFE\xFF", 2) || text[0] == '\0' || - text[1] == '\0')) { - error = "mod.json is UTF-16; save it as UTF-8"; - return false; - } - Json root; - if (!JsonReader(text).parse(root) || root.kind != Json::Kind::object) { - error = "mod.json is not a JSON object"; - return false; - } - mod = Mod{}; - mod.folder = folder; - const Json* name = root.find("name"); - mod.name = name && name->kind == Json::Kind::string ? name->string : folder; - if (const Json* v = root.find("game_version"); v && v->kind == Json::Kind::string) mod.game_version = v->string; - if (const Json* e = root.find("enabled")) { - if (e->kind != Json::Kind::boolean) { - error = "\"enabled\" must be true or false"; - return false; - } - mod.enabled = e->boolean; - } - if (const Json* swaps = root.find("archetype_swaps")) { - if (swaps->kind != Json::Kind::array) { - error = "\"archetype_swaps\" must be a list"; - return false; - } - for (const Json& s : swaps->array) { - const Json* from = s.find("from"); - const Json* to = s.find("to"); - if (s.kind != Json::Kind::object || !from || !to || from->kind != Json::Kind::string || - to->kind != Json::Kind::string) { - error = "each archetype swap needs \"from\" and \"to\" model names"; - return false; - } - ArchetypeSwap swap; - swap.from_name = from->string; - swap.to_name = to->string; - if (!parse_model_id(swap.from_name, swap.from) || !parse_model_id(swap.to_name, swap.to)) { - error = "archetype swap " + swap.from_name + " -> " + swap.to_name + ": not a model name or 0x hash"; - return false; - } - if (const Json* when = s.find("when")) { - if (when->kind != Json::Kind::string || when->string != "always") { - error = "archetype swap " + swap.from_name + ": \"when\" can only be \"always\" until a game hook " - "provides mission state (docs/modding.md)"; - return false; - } - } - if (swap.from == swap.to) { - error = "archetype swap " + swap.from_name + " -> " + swap.to_name + " swaps a model with itself"; - return false; - } - mod.archetype_swaps.push_back(std::move(swap)); - } - } - if (const Json* cam = root.find("camera")) { - if (cam->kind != Json::Kind::object) { - error = "\"camera\" must be an object"; - return false; - } - mod.camera.set = true; - const Json* view = cam->find("view_mode"); - if (!view || view->kind != Json::Kind::string || - (view->string != "first_person" && view->string != "default")) { - error = "\"camera\": \"view_mode\" must be \"first_person\" or \"default\""; - return false; - } - mod.camera.first_person = view->string == "first_person"; - if (const Json* v = cam->find("first_person_value")) { - if (v->kind != Json::Kind::number || !whole_number(v->number, 255)) { - error = "\"camera\": \"first_person_value\" must be a whole number 0-255"; - return false; - } - mod.camera.first_person_value = static_cast(v->number); - } - if (const Json* c = cam->find("contexts")) { - if (c->kind != Json::Kind::array) { - error = "\"camera\": \"contexts\" must be a list of numbers"; - return false; - } - for (const Json& x : c->array) { - if (x.kind != Json::Kind::number || !whole_number(x.number, 4294967295.0)) { - error = "\"camera\": \"contexts\" must be a list of whole numbers from 0 to 4294967295"; - return false; - } - mod.camera.contexts.push_back(static_cast(x.number)); - } - } - } - return true; -} - -// Reads every //mod.json, in folder-name order. A missing dir is no mods, not an error. -inline LoadResult load_mods(const std::filesystem::path& dir) { - LoadResult result; - std::error_code ec; - if (!std::filesystem::is_directory(dir, ec)) return result; - std::vector folders; - for (const auto& entry : std::filesystem::directory_iterator(dir, ec)) - if (entry.is_directory(ec)) folders.push_back(entry.path()); - std::sort(folders.begin(), folders.end()); - for (const auto& folder : folders) { - const std::string name = folder.filename().string(); - std::ifstream f(folder / "mod.json", std::ios::binary); - if (!f) continue; // a folder without a manifest is not a mod (notes, assets of another tool) - const std::string text((std::istreambuf_iterator(f)), std::istreambuf_iterator()); - Mod mod; - std::string error; - if (parse_mod(text, name, mod, error)) - result.mods.push_back(std::move(mod)); - else - result.errors.push_back(name + ": " + error); - } - return result; -} - -// The swap table the archetype hook consults: enabled mods only, later folders win for the same `from`. -class ArchetypeSwaps { -public: - explicit ArchetypeSwaps(const std::vector& mods) { - for (const Mod& m : mods) { - if (!m.enabled) continue; - for (const ArchetypeSwap& s : m.archetype_swaps) { - bool replaced = false; - for (auto& [from, to] : table_) - if (from == s.from) to = s.to, replaced = true; - if (!replaced) table_.emplace_back(s.from, s.to); - } - } - } - - // The archetype the game should get when it asks for `hash` (itself when no mod swaps it). One step only: a swap - // to a model that is itself swapped is not followed, so two mods cannot loop. - uint32_t remap(uint32_t hash) const { - for (const auto& [from, to] : table_) - if (from == hash) return to; - return hash; - } - - std::size_t size() const { return table_.size(); } - -private: - std::vector> table_; -}; - -// The process's swaps: set once at start (main.cpp), before any game code runs; read by the archetype hook. -inline ArchetypeSwaps& active_slot() { - static ArchetypeSwaps swaps{std::vector{}}; - return swaps; -} -inline void set_active(ArchetypeSwaps swaps) { active_slot() = std::move(swaps); } -inline const ArchetypeSwaps& active() { return active_slot(); } - -// The camera override of the enabled mods: the last one (in folder order) with a "camera" section decides. -inline CameraView camera_of(const std::vector& mods) { - CameraView view; - for (const Mod& m : mods) - if (m.enabled && m.camera.set) view = m.camera; - return view; -} - -inline CameraView& camera_slot() { - static CameraView view; - return view; -} -inline void set_active_camera(CameraView view) { camera_slot() = std::move(view); } - -// What the hooked view-mode getter returns: the mod's first-person value for an overridden context, else the game's. -inline uint32_t override_view_mode(uint32_t result, uint32_t context) { - const CameraView& v = camera_slot(); - if (!v.first_person) return result; - if (!v.contexts.empty()) { - bool listed = false; - for (uint32_t c : v.contexts) listed = listed || c == context; - if (!listed) return result; - } - return v.first_person_value; -} - -} // namespace leonida::mods diff --git a/runtime/src/occlusion_sum.comp b/runtime/src/occlusion_sum.comp deleted file mode 100644 index ade324229..000000000 --- a/runtime/src/occlusion_sum.comp +++ /dev/null @@ -1,19 +0,0 @@ -#version 450 - -layout(local_size_x = 1) in; -layout(set = 0, binding = 0, std430) buffer QueryResults { - uvec2 total; - uvec2 segments[]; -}; -layout(push_constant) uniform ResolveRange { uint count; }; - -void main() { - uvec2 sum = total; - for (uint i = 0; i < count; ++i) { - uvec2 segment = segments[i]; - uint low = sum.x + segment.x; - sum.y += segment.y + uint(low < sum.x); - sum.x = low; - } - total = sum; -} diff --git a/runtime/src/occlusion_sum_spirv.h b/runtime/src/occlusion_sum_spirv.h deleted file mode 100644 index 54fc938de..000000000 --- a/runtime/src/occlusion_sum_spirv.h +++ /dev/null @@ -1,47 +0,0 @@ -#pragma once - -#include - -namespace leonida { - -// From occlusion_sum.comp. Compile with glslangValidator -V --target-env vulkan1.0 -Os -g0, -// then encode the little-endian SPIR-V as uint32_t words. No shader compiler is needed at runtime build time. -inline constexpr std::uint32_t occlusion_sum_spirv[] = { - 0x07230203, 0x00010000, 0x0008000b, 0x00000050, 0x00000000, 0x00020011, 0x00000001, 0x0006000b, - 0x00000001, 0x4c534c47, 0x6474732e, 0x3035342e, 0x00000000, 0x0003000e, 0x00000000, 0x00000001, - 0x0005000f, 0x00000005, 0x00000004, 0x6e69616d, 0x00000000, 0x00060010, 0x00000004, 0x00000011, - 0x00000001, 0x00000001, 0x00000001, 0x00040047, 0x0000000a, 0x00000006, 0x00000008, 0x00030047, - 0x0000000b, 0x00000003, 0x00050048, 0x0000000b, 0x00000000, 0x00000023, 0x00000000, 0x00050048, - 0x0000000b, 0x00000001, 0x00000023, 0x00000008, 0x00040047, 0x0000000d, 0x00000021, 0x00000000, - 0x00040047, 0x0000000d, 0x00000022, 0x00000000, 0x00030047, 0x0000001c, 0x00000002, 0x00050048, - 0x0000001c, 0x00000000, 0x00000023, 0x00000000, 0x00040047, 0x00000043, 0x0000000b, 0x00000019, - 0x00020013, 0x00000002, 0x00030021, 0x00000003, 0x00000002, 0x00040015, 0x00000006, 0x00000020, - 0x00000000, 0x00040017, 0x00000007, 0x00000006, 0x00000002, 0x0003001d, 0x0000000a, 0x00000007, - 0x0004001e, 0x0000000b, 0x00000007, 0x0000000a, 0x00040020, 0x0000000c, 0x00000002, 0x0000000b, - 0x0004003b, 0x0000000c, 0x0000000d, 0x00000002, 0x00040015, 0x0000000e, 0x00000020, 0x00000001, - 0x0004002b, 0x0000000e, 0x0000000f, 0x00000000, 0x00040020, 0x00000010, 0x00000002, 0x00000007, - 0x0004002b, 0x00000006, 0x00000015, 0x00000000, 0x0003001e, 0x0000001c, 0x00000006, 0x00040020, - 0x0000001d, 0x00000009, 0x0000001c, 0x0004003b, 0x0000001d, 0x0000001e, 0x00000009, 0x00040020, - 0x0000001f, 0x00000009, 0x00000006, 0x00020014, 0x00000022, 0x0004002b, 0x0000000e, 0x00000025, - 0x00000001, 0x0004002b, 0x00000006, 0x0000002f, 0x00000001, 0x00040017, 0x00000042, 0x00000006, - 0x00000003, 0x0006002c, 0x00000042, 0x00000043, 0x0000002f, 0x0000002f, 0x0000002f, 0x00050036, - 0x00000002, 0x00000004, 0x00000000, 0x00000003, 0x000200f8, 0x00000005, 0x00050041, 0x00000010, - 0x00000011, 0x0000000d, 0x0000000f, 0x0004003d, 0x00000007, 0x00000012, 0x00000011, 0x000200f9, - 0x00000016, 0x000200f8, 0x00000016, 0x000700f5, 0x00000007, 0x0000004e, 0x00000012, 0x00000005, - 0x0000004f, 0x00000017, 0x000700f5, 0x00000006, 0x00000044, 0x00000015, 0x00000005, 0x0000003f, - 0x00000017, 0x00050041, 0x0000001f, 0x00000020, 0x0000001e, 0x0000000f, 0x0004003d, 0x00000006, - 0x00000021, 0x00000020, 0x000500b0, 0x00000022, 0x00000023, 0x00000044, 0x00000021, 0x000400f6, - 0x00000018, 0x00000017, 0x00000000, 0x000400fa, 0x00000023, 0x00000017, 0x00000018, 0x000200f8, - 0x00000017, 0x00060041, 0x00000010, 0x00000027, 0x0000000d, 0x00000025, 0x00000044, 0x0004003d, - 0x00000007, 0x00000028, 0x00000027, 0x00050051, 0x00000006, 0x0000002b, 0x0000004e, 0x00000000, - 0x00050051, 0x00000006, 0x0000002d, 0x00000028, 0x00000000, 0x00050080, 0x00000006, 0x0000002e, - 0x0000002b, 0x0000002d, 0x00050051, 0x00000006, 0x00000031, 0x00000028, 0x00000001, 0x000500b0, - 0x00000022, 0x00000035, 0x0000002e, 0x0000002b, 0x000600a9, 0x00000006, 0x00000036, 0x00000035, - 0x0000002f, 0x00000015, 0x00050080, 0x00000006, 0x00000037, 0x00000031, 0x00000036, 0x00050051, - 0x00000006, 0x00000039, 0x0000004e, 0x00000001, 0x00050080, 0x00000006, 0x0000003a, 0x00000039, - 0x00000037, 0x00050050, 0x00000007, 0x0000004f, 0x0000002e, 0x0000003a, 0x00050080, 0x00000006, - 0x0000003f, 0x00000044, 0x00000025, 0x000200f9, 0x00000016, 0x000200f8, 0x00000018, 0x0003003e, - 0x00000011, 0x0000004e, 0x000100fd, 0x00010038, -}; - -} // namespace leonida diff --git a/runtime/src/pe_loader.cpp b/runtime/src/pe_loader.cpp deleted file mode 100644 index 48907c20c..000000000 --- a/runtime/src/pe_loader.cpp +++ /dev/null @@ -1,1857 +0,0 @@ -#include "pe_loader.h" - -#include -#include -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include "../core/config.h" -#include "../core/log.h" -#include "../shims/shims.h" -#include "../shims/startup_trace.h" -#include "base_reservation.h" - -namespace rt { - -std::string lower(std::string s) { - std::transform(s.begin(), s.end(), s.begin(), [](unsigned char c) { return (char)std::tolower(c); }); - return s; -} - -namespace { - -std::filesystem::path::string_type module_key(const std::filesystem::path& path) { - // Keep identity in the platform's native path representation. Only the existing ASCII case folding is - // applied here; representable names also retain their old narrow-byte alias below. - auto key = path.filename().native(); - for (auto& c : key) - if (c >= 'A' && c <= 'Z') c = static_cast(c + ('a' - 'A')); - return key; -} - -std::string narrow_module_key(const std::filesystem::path& path) { - const auto filename = path.filename(); - try { - const auto narrow = filename.string(); - // A lossy/default-character alias must not collapse two distinct Unicode basenames. - if (std::filesystem::path(narrow).native() == filename.native()) return lower(narrow); - } catch (const std::system_error&) { - // Some Windows standard libraries throw when a basename is outside the current narrow code page. - // It still has a native identity; it simply has no alias in the existing narrow lookup API. - } - return {}; -} - -// Windows matches module names case-insensitively with its own upcase table (RtlEqualUnicodeString); the -// ordinal ignore-case compare is that table. -bool same_module_name(const wchar_t* a, const wchar_t* b) { - return CompareStringOrdinal(a, -1, b, -1, TRUE) == CSTR_EQUAL; -} - -// A narrow (ANSI code page) module name widened for a case-insensitive compare; empty when it is not valid in the -// code page. -std::wstring acp_to_wide(const std::string& narrow) { - if (narrow.empty()) return {}; - const int n = MultiByteToWideChar(CP_ACP, MB_ERR_INVALID_CHARS, narrow.data(), static_cast(narrow.size()), - nullptr, 0); - if (n <= 0) return {}; - std::wstring wide(static_cast(n), L'\0'); - MultiByteToWideChar(CP_ACP, MB_ERR_INVALID_CHARS, narrow.data(), static_cast(narrow.size()), wide.data(), n); - return wide; -} - -std::string path_utf8(const std::filesystem::path& path) { - const auto bytes = path.u8string(); - return {reinterpret_cast(bytes.data()), bytes.size()}; -} - -std::vector read_file(const std::filesystem::path& p) { - std::ifstream f(p, std::ios::binary); - if (!f) throw std::runtime_error("cannot open " + path_utf8(p)); - return {std::istreambuf_iterator(f), {}}; -} - -template -T* at(uint8_t* base, uint32_t rva) { return reinterpret_cast(base + rva); } - -// Every RVA followed below comes out of the image itself, so each one is checked first. A truncated or corrupt -// image then fails with a message instead of reading, writing or protecting memory outside its allocation. -void require_range(const std::string& name, uint64_t rva, uint64_t len, uint32_t image_size, const char* what) { - if (rva > image_size || len > image_size - rva) - throw std::runtime_error(name + ": " + what + " runs past the image"); -} - -std::string read_string(const std::string& name, uint8_t* base, uint32_t image_size, uint32_t rva, const char* what) { - if (rva >= image_size) throw std::runtime_error(name + ": " + what + " is outside the image"); - auto* s = reinterpret_cast(base + rva); - auto* end = static_cast(std::memchr(s, 0, image_size - rva)); - if (!end) throw std::runtime_error(name + ": " + what + " isn't terminated inside the image"); - return {s, end}; -} - -// PE/COFF: NumberOfRvaAndSizes counts the data directories; entries past it are not directories, whatever they hold. -IMAGE_DATA_DIRECTORY directory(const IMAGE_NT_HEADERS64* nt, unsigned index) { - return index < nt->OptionalHeader.NumberOfRvaAndSizes ? nt->OptionalHeader.DataDirectory[index] : IMAGE_DATA_DIRECTORY{}; -} - -// The TLS directory holds virtual addresses, which relocations have already moved to this mapping. -uint64_t rva_in(const Module& m, uint64_t va, const char* what) { - const uint64_t base = reinterpret_cast(m.base); - if (va < base || va - base >= m.size) throw std::runtime_error(m.name + ": " + what + " is outside the image"); - return va - base; -} - -IMAGE_TLS_DIRECTORY64* tls_directory(Module& m) { - auto* nt = at(m.base, reinterpret_cast(m.base)->e_lfanew); - // Through directory(), as every other directory: an entry past NumberOfRvaAndSizes is not a TLS directory. - const auto dir = directory(nt, IMAGE_DIRECTORY_ENTRY_TLS); - if (!dir.Size || !dir.VirtualAddress) return nullptr; - require_range(m.name, dir.VirtualAddress, sizeof(IMAGE_TLS_DIRECTORY64), m.size, "the TLS directory"); - return at(m.base, dir.VirtualAddress); -} - -// __declspec(thread) reads TEB->ThreadLocalStoragePointer[_tls_index] at gs:[58h]. That array is indexed by the -// loader-assigned per-module TLS index and is a different index space from TlsAlloc/TlsGetValue (TlsSlots). Only the OS -// loader can allocate a module index, so the runtime ships a minimal DLL whose only content is a TLS anchor -// (src/tls_host.cpp). Loading it makes the OS reserve an index and give every thread a block for it; the native loader -// reuses that index for the mapped image. When more than one manually mapped module uses static TLS at once, the loader -// clones gta6rt_tls_host.dll to a per-process temporary path on demand and loads it, so the OS assigns an independent -// module TLS index for each simultaneous module (up to kMaxMappedTlsModules). -constexpr DWORD kMaxModuleTlsSlots = 64; -constexpr size_t kMaxMappedTlsModules = 16; -void** module_tls_slots() { return reinterpret_cast(__readgsqword(0x58)); } - -void __cdecl on_host_thread_event(DWORD reason); - -struct TlsHostModule { - HMODULE module = nullptr; - DWORD index = TLS_OUT_OF_INDEXES; -}; - -std::filesystem::path tls_host_base_path() { - std::wstring exe_path; - DWORD size = MAX_PATH; - while (true) { - exe_path.resize(size); - DWORD len = GetModuleFileNameW(nullptr, exe_path.data(), size); - if (len == 0) return {}; - if (len < size - 1) { - exe_path.resize(len); - break; - } - size *= 2; - } - return std::filesystem::path(exe_path).parent_path() / L"gta6rt_tls_host.dll"; -} - -std::filesystem::path tls_host_clone_dir() { - wchar_t buf[MAX_PATH]; - DWORD n = GetTempPathW(MAX_PATH, buf); - if (n > 0 && n < MAX_PATH) return std::filesystem::path(buf); - return std::filesystem::temp_directory_path(); -} - -struct TlsCloneRecord { - HMODULE module = nullptr; - std::filesystem::path path; -}; - -std::mutex g_tls_alloc_mutex; -std::array g_tls_hosts{}; -std::array, kMaxMappedTlsModules> g_tls_slot_owners{}; -std::array, kMaxMappedTlsModules> g_tls_slot_generations{}; -std::atomic g_next_tls_generation{1}; -std::vector g_tls_clones; - -// Frees every TLS helper clone this process loaded and deletes its files. load() registers the wrapper with atexit; -// the --run path in main() must also call this directly before ExitProcess, which skips the atexit table. Call it -// only when no mapped code can run again: it unmaps the helper images. -void cleanup_tls_clones_internal() { - for (const auto& rec : g_tls_clones) { - if (rec.module) FreeLibrary(rec.module); - if (!rec.path.empty()) DeleteFileW(rec.path.c_str()); - } - g_tls_clones.clear(); -} - -void cleanup_tls_clones_at_exit() { cleanup_tls_clones_internal(); } - -// The owner process named by "leonida_tls_host__.dll"; 0 when the name does not carry one. -DWORD clone_owner_pid(const wchar_t* name) { - constexpr wchar_t prefix[] = L"leonida_tls_host_"; - const wchar_t* p = name; - for (size_t i = 0; i < sizeof(prefix) / sizeof(wchar_t) - 1; ++i) - if (*p++ != prefix[i]) return 0; - if (*p < L'0' || *p > L'9') return 0; - unsigned long pid = 0; - while (*p >= L'0' && *p <= L'9') { - pid = pid * 10 + (*p - L'0'); - if (pid > 0xFFFFFFFFul) return 0; - ++p; - } - return static_cast(pid); -} - -bool process_alive(DWORD pid) { - // PROCESS_QUERY_LIMITED_INFORMATION needs no handle rights a normal process could deny; a failure means the - // process is gone. A still-mapped or still-open file is caught by the checks below even for a misjudged PID. - HANDLE p = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, FALSE, pid); - if (!p) return false; - CloseHandle(p); - return true; -} - -// Deletes clones left behind by processes that have exited. Deletion is scoped to files whose owner is gone: a -// clone of a live process is either still open by its copy step's handle or mapped as an image, so it is skipped -// (or DeleteFileW fails harmlessly), and a concurrent process between CopyFileW and LoadLibraryExW keeps its file. -void sweep_stale_tls_clones(const std::filesystem::path& dir) { - WIN32_FIND_DATAW fd{}; - const std::filesystem::path pattern = dir / L"leonida_tls_host_*.dll"; - HANDLE h = FindFirstFileW(pattern.c_str(), &fd); - if (h == INVALID_HANDLE_VALUE) return; - do { - if (fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) continue; - const std::filesystem::path path = dir / fd.cFileName; - const DWORD owner = clone_owner_pid(fd.cFileName); - if (owner && owner != GetCurrentProcessId() && process_alive(owner)) continue; - // An exclusive open (no sharing) conflicts with any handle another process holds on the file, so a failure - // means the copy->load sequence or a mapped image still owns it. Only unowned files reach DeleteFileW, and - // that stays harmless for a mapped image. - HANDLE probe = - CreateFileW(path.c_str(), GENERIC_READ, 0, nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr); - if (probe == INVALID_HANDLE_VALUE) continue; - CloseHandle(probe); - DeleteFileW(path.c_str()); - } while (FindNextFileW(h, &fd)); - FindClose(h); -} - -TlsHostModule load_tls_host_image(const std::filesystem::path& path, bool hook_thread_events) { - TlsHostModule host; - if (path.empty()) return host; - // The helper is linked with the static CRT (/MT), so it needs only system DLLs. Restricting the dependency search - // to System32 keeps a game-supplied vcruntime next to the executable from being picked up. - host.module = LoadLibraryExW(path.c_str(), nullptr, LOAD_LIBRARY_SEARCH_SYSTEM32); - if (!host.module) return host; - - auto* base = reinterpret_cast(host.module); - auto* dos = reinterpret_cast(base); - auto* nt = at(base, dos->e_lfanew); - const auto& dir = nt->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_TLS]; - if (!dir.Size || !dir.VirtualAddress) { - FreeLibrary(host.module); - host.module = nullptr; - return host; - } - auto* tls = at(base, dir.VirtualAddress); - if (!tls->AddressOfIndex) { - FreeLibrary(host.module); - host.module = nullptr; - return host; - } - host.index = *reinterpret_cast(tls->AddressOfIndex); - if (hook_thread_events) { - // Only the primary helper reports thread attach/detach events; on_host_thread_event iterates all active slots. - using SetThreadEvent = void(__cdecl*)(void(__cdecl*)(DWORD)); - if (auto set = reinterpret_cast(GetProcAddress(host.module, "gta6rt_tls_host_set_thread_event"))) - set(&on_host_thread_event); - } - return host; -} - -// Must be called with g_tls_alloc_mutex held and WITHOUT g_tls_lock held (LoadLibraryExW takes the Windows loader lock). -TlsHostModule ensure_tls_host(size_t slot) { - if (slot >= kMaxMappedTlsModules) return {}; - if (g_tls_hosts[slot].index != TLS_OUT_OF_INDEXES) return g_tls_hosts[slot]; - - const std::filesystem::path primary = tls_host_base_path(); - if (primary.empty()) return {}; - - if (slot == 0) { - g_tls_hosts[0] = load_tls_host_image(primary, true); - return g_tls_hosts[0]; - } - - // Ensure slot 0 is loaded first so thread attach/detach events are hooked. - if (g_tls_hosts[0].index == TLS_OUT_OF_INDEXES) { - g_tls_hosts[0] = load_tls_host_image(primary, true); - if (g_tls_hosts[0].index == TLS_OUT_OF_INDEXES) return {}; - } - - // Clone gta6rt_tls_host.dll to a distinct path using CopyFileW (Wine 9 lacks CopyFile2 used by std::filesystem). - const std::filesystem::path dir = tls_host_clone_dir(); - static bool swept = false; - if (!swept) { - swept = true; - sweep_stale_tls_clones(dir); - std::atexit(&cleanup_tls_clones_at_exit); - } - const std::wstring name = - L"leonida_tls_host_" + std::to_wstring(GetCurrentProcessId()) + L"_" + std::to_wstring(slot) + L".dll"; - const std::filesystem::path clone_path = dir / name; - // The staging name must not match the sweep pattern, which only covers final clone names ending in .dll. - const std::filesystem::path staging = clone_path.wstring() + L".new"; - if (!CopyFileW(primary.c_str(), staging.c_str(), FALSE)) return {}; - - // Open the guard before the clone exists under its final name and hold it across LoadLibraryExW: the rename - // below needs DELETE access, which the handle's FILE_SHARE_DELETE grants, and no purge can remove the clone - // while the handle is open (an exclusive open conflicts with it) or once the image is mapped. Copying straight - // to the final name would leave a window where a concurrent sweep sees an unowned file. - HANDLE guard = CreateFileW(staging.c_str(), GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_DELETE, nullptr, - OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr); - if (guard == INVALID_HANDLE_VALUE) { - DeleteFileW(staging.c_str()); - return {}; - } - if (!MoveFileExW(staging.c_str(), clone_path.c_str(), MOVEFILE_REPLACE_EXISTING)) { - CloseHandle(guard); - DeleteFileW(staging.c_str()); - return {}; - } - TlsHostModule loaded = load_tls_host_image(clone_path, false); - CloseHandle(guard); - - if (loaded.index == TLS_OUT_OF_INDEXES) { - DeleteFileW(clone_path.c_str()); - return {}; - } - for (size_t i = 0; i < kMaxMappedTlsModules; ++i) { - if (i != slot && g_tls_hosts[i].index == loaded.index) { - FreeLibrary(loaded.module); - DeleteFileW(clone_path.c_str()); - return {}; - } - } - g_tls_clones.push_back({loaded.module, clone_path}); - g_tls_hosts[slot] = loaded; - return g_tls_hosts[slot]; -} - -struct ThreadTlsSlot { - Module* module = nullptr; - uint64_t generation = 0; - void* saved = nullptr; - void* block = nullptr; - uint32_t index = kNoTlsIndex; - void** ga_view = nullptr; // the thread's slot-0 view for a /GA EXE (Module::tls_ga_slot) - uint32_t ga_slot = kNoTlsIndex; -}; - -// Per-thread installation state for each reserved TLS slot. -thread_local std::array g_thread_tls_slots{}; - -// Orders the TLS owners' publication, their `initialised` flags and their retirement against the thread events. Shared -// in on_host_thread_event, exclusive only for those short writes (no allocation and no call that takes the Windows -// loader lock, which the events run under). -SRWLOCK g_tls_lock = SRWLOCK_INIT; -struct SharedTlsLock { - SharedTlsLock() { AcquireSRWLockShared(&g_tls_lock); } - ~SharedTlsLock() { ReleaseSRWLockShared(&g_tls_lock); } - SharedTlsLock(const SharedTlsLock&) = delete; - SharedTlsLock& operator=(const SharedTlsLock&) = delete; -}; -struct ExclusiveTlsLock { - ExclusiveTlsLock() { AcquireSRWLockExclusive(&g_tls_lock); } - ~ExclusiveTlsLock() { ReleaseSRWLockExclusive(&g_tls_lock); } - ExclusiveTlsLock(const ExclusiveTlsLock&) = delete; - ExclusiveTlsLock& operator=(const ExclusiveTlsLock&) = delete; -}; - -// Puts the helper DLL's own block back in this thread's slot and frees the copy that replaced it. Uses only this -// thread's record, so it also works after the module that installed the copy is gone. -void release_thread_slot(size_t slot) { - if (slot >= kMaxMappedTlsModules) return; - ThreadTlsSlot& entry = g_thread_tls_slots[slot]; - if (!entry.module && !entry.block) return; - if (entry.ga_view) { - if (TlsGetValue(entry.ga_slot) == entry.ga_view) TlsSetValue(entry.ga_slot, nullptr); - VirtualFree(entry.ga_view, 0, MEM_RELEASE); - } - if (entry.block) { - void** slots = module_tls_slots(); - if (slots && entry.index < kMaxModuleTlsSlots && slots[entry.index] == entry.block) - slots[entry.index] = entry.saved; - VirtualFree(entry.block, 0, MEM_RELEASE); - } - entry = ThreadTlsSlot{}; -} - -// A block load() put into a thread that was already running (install_on_existing_threads). Such a thread has no -// g_thread_tls_slots record of it: the record is here, keyed by thread id, and the thread's own DLL_THREAD_DETACH or -// the module's ~Loader takes the block out again. -struct ExistingThreadBlock { - DWORD thread = 0; - size_t slot = 0; - Module* module = nullptr; - uint64_t generation = 0; // the module's tls_generation: with the pointer, what identifies the module - uint32_t index = kNoTlsIndex; - void*** vector = nullptr; // that thread's TEB->ThreadLocalStoragePointer field; the array itself can be replaced - void* saved = nullptr; // what the block replaced - void* block = nullptr; - void** ga_cell = nullptr; // that thread's TEB->TlsSlots[tls_ga_slot]: inline in the TEB, so it never moves - void* ga_view = nullptr; // the /GA view that cell points at (Module::tls_ga_slot) -}; - -// Immortal, like the thread events that use them. `ended` holds the ids of threads whose DLL_THREAD_DETACH has run: -// Windows frees such a thread's TLS array next, so nothing may be put into it any more. -struct ExistingThreads { - SRWLOCK lock = SRWLOCK_INIT; // a leaf: nothing is called while it is held but VirtualFree and thread queries - std::vector blocks; - std::vector ended; -}; -ExistingThreads& existing_threads() { - static auto* state = new ExistingThreads; - return *state; -} -struct ExistingThreadsLock { - ExistingThreadsLock() { AcquireSRWLockExclusive(&existing_threads().lock); } - ~ExistingThreadsLock() { ReleaseSRWLockExclusive(&existing_threads().lock); } - ExistingThreadsLock(const ExistingThreadsLock&) = delete; - ExistingThreadsLock& operator=(const ExistingThreadsLock&) = delete; -}; - -bool has_existing_thread_block(DWORD thread, const Module& m) { - ExistingThreadsLock lock; - for (const auto& b : existing_threads().blocks) - if (b.thread == thread && b.module == &m && b.generation == m.tls_generation) return true; - return false; -} - -// The /GA view a thread's TlsSlots[Module::tls_ga_slot] points at: [0] and [tls_index] are this thread's block. -// Null when it cannot be allocated. -void** make_ga_view(const Module& m, void* block) { - auto* view = static_cast( - VirtualAlloc(nullptr, kMaxModuleTlsSlots * sizeof(void*), MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE)); - if (!view) return nullptr; - view[0] = block; - view[m.tls_index] = block; - return view; -} - -void install_thread_block(Module& m) { - if (m.tls_slot >= kMaxMappedTlsModules) return; - const size_t slot = m.tls_slot; - ThreadTlsSlot& entry = g_thread_tls_slots[slot]; - if (entry.module == &m && entry.generation == m.tls_generation) return; - if (has_existing_thread_block(GetCurrentThreadId(), m)) return; // load() already gave this thread its copy - if (entry.module) { - // A copy left by a module whose Loader is gone (or from an earlier generation) is released; a live owner's is a conflict. - if (entry.module == g_tls_slot_owners[slot].load() && - entry.generation == g_tls_slot_generations[slot].load()) { - throw std::runtime_error("another manually mapped module's TLS is already installed in this thread slot"); - } - release_thread_slot(slot); - } - - const uint64_t total = static_cast(m.tls_raw_size) + m.tls_zero_fill; - if (!total) { - // Callback-only TLS module (no data block): still record attachment in this slot so DLL_THREAD_DETACH runs. - entry.module = &m; - entry.generation = m.tls_generation; - return; - } - if (m.tls_index == kNoTlsIndex) return; - void** slots = module_tls_slots(); - if (!slots || m.tls_index >= kMaxModuleTlsSlots) - throw std::runtime_error(m.name + ": cannot install TLS in this thread"); - - void* block = VirtualAlloc(nullptr, static_cast(total), MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE); - if (!block) throw std::runtime_error(m.name + ": TLS block allocation failed"); - if (m.tls_raw_size) std::memcpy(block, m.tls_template, m.tls_raw_size); - if (m.tls_zero_fill) - std::memset(static_cast(block) + m.tls_raw_size, 0, m.tls_zero_fill); - - void** view = nullptr; - if (m.tls_ga_slot != kNoTlsIndex) { - // The /GA view: [0] and [tls_index] are this thread's block, the rest stays null (the image reads no other). - view = make_ga_view(m, block); - if (!view) { - VirtualFree(block, 0, MEM_RELEASE); - throw std::runtime_error(m.name + ": TLS view allocation failed"); - } - TlsSetValue(m.tls_ga_slot, view); - } - - void* saved = slots[m.tls_index]; - slots[m.tls_index] = block; - entry.module = &m; - entry.generation = m.tls_generation; - entry.saved = saved; - entry.block = block; - entry.index = m.tls_index; - entry.ga_view = view; - entry.ga_slot = m.tls_ga_slot; -} - -// Rewrites a /GA EXE's slot-0 TLS reads (Module::tls_ga_slot): every `mov r64, gs:[58h]` (65 REX.W 8B /r with -// mod=00, r/m=100, SIB=25, disp32=58h; REX 48 or 4C for r8-r15) in an executable section becomes the same -// instruction with disp32 = 1480h + 8 * slot, TEB->TlsSlots[slot]. Same length, so nothing else moves. The 9-byte -// form, with its segment prefix, SIB 25 and that displacement, is not something code or tables produce by accident. -// Must run before protect_sections() and before any of the image's code (its TLS callbacks included). -size_t patch_ga_tls_reads(Module& m, uint32_t slot) { - const auto* dos = reinterpret_cast(m.base); - const auto* nt = reinterpret_cast(m.base + dos->e_lfanew); - const IMAGE_SECTION_HEADER* sec = IMAGE_FIRST_SECTION(nt); - const uint32_t disp = 0x1480u + 8u * slot; - size_t sites = 0; - for (unsigned i = 0; i < nt->FileHeader.NumberOfSections; ++i, ++sec) { - if (!(sec->Characteristics & IMAGE_SCN_MEM_EXECUTE)) continue; - const uint32_t size = (std::min)(sec->Misc.VirtualSize, sec->SizeOfRawData); - if (sec->VirtualAddress > m.size || size > m.size - sec->VirtualAddress || size < 9) continue; - uint8_t* p = m.base + sec->VirtualAddress; - for (uint32_t k = 0; k + 9 <= size; ++k) { - if (p[k] != 0x65 || (p[k + 1] != 0x48 && p[k + 1] != 0x4C) || p[k + 2] != 0x8B) continue; - const uint8_t modrm = p[k + 3]; - if ((modrm & 0xC7) != 0x04 || p[k + 4] != 0x25) continue; - uint32_t d; - std::memcpy(&d, p + k + 5, 4); - if (d != 0x58) continue; - std::memcpy(p + k + 5, &disp, 4); - ++sites; - k += 8; - } - } - return sites; -} - -bool ga_tls_patch_enabled() { return rt::config::get("loader.tls_ga_patch").text != "0"; } - -void uninstall_thread_block(Module& m) { - if (m.tls_slot >= kMaxMappedTlsModules) return; - const size_t slot = m.tls_slot; - ThreadTlsSlot& entry = g_thread_tls_slots[slot]; - if (entry.module != &m || entry.generation != m.tls_generation) return; - if (m.tls_block == entry.block) { - m.tls_block = nullptr; - m.tls_saved_block = nullptr; - } - release_thread_slot(slot); -} - -// `trace`: record each callback in the startup trace. Only the Loader's own calls (process attach and detach) pass -// true; the thread events run under the Windows loader lock and stay out of the trace. -void run_callbacks(Module& m, uint32_t reason, bool trace = false) { - auto* tls = tls_directory(m); - if (!tls || !tls->AddressOfCallBacks) return; - const uint64_t table_rva = rva_in(m, tls->AddressOfCallBacks, "the TLS callback table"); - // The callback table has no length field: it ends at a zero entry, so every step is checked against the image. - for (uint64_t i = 0;; ++i) { - const uint64_t entry_rva = table_rva + i * sizeof(uint64_t); - require_range(m.name, entry_rva, sizeof(uint64_t), m.size, "a TLS callback table entry"); - const uint64_t fn = *at(m.base, static_cast(entry_rva)); - if (!fn) break; - auto callback = - reinterpret_cast(m.base + rva_in(m, fn, "a TLS callback")); - if (trace && startup_trace::enabled()) - startup_trace::event("tls_callback", "\"module\":" + startup_trace::quote(m.name) + ",\"at\":" + - startup_trace::quote(startup_trace::where(reinterpret_cast(callback))) + - ",\"reason\":" + std::to_string(reason)); - callback(m.base, static_cast(reason), nullptr); - } -} - -// ---- Threads that existed before load() --------------------------------------------------------------------------- -// -// When Windows loads a DLL with static TLS itself, every running thread gets a block for it (and no DLL_THREAD_ATTACH). -// The helper DLL gets exactly that, so in a thread that was already running the reserved slot holds the helper's -// one-byte block, and mapped __declspec(thread) code there would read and write past it. Such threads are not rare: -// the workers of the process thread pool predate most loads, and the task queue runs a title's callbacks on them. -// load() therefore gives each of them a copy of the template too, through the thread's TEB, which is ordinary memory -// of this process. -// -// What makes that safe: -// - The slot is the helper's, and nothing reads the helper's variable, so swapping the pointer under a running -// thread disturbs nothing; the thread cannot be in mapped code of a module whose load() has not returned. -// - The swap is made with g_tls_lock held exclusively, so no thread is inside its attach or detach event meanwhile. -// - A thread whose detach event has run is skipped (`ended`), and so is one with no TLS array or no helper block: -// Windows is about to free, or never built, what the block would go into. -// - The block comes out again in that thread's own detach event, before Windows frees the array, or in ~Loader. -// What is left: -// - A thread that ran its detach event before the helper DLL was ever loaded and has not left the process yet is -// not in `ended`; if Windows leaves a stale array pointer in its TEB for those last instructions, the write goes -// to freed heap memory. -// - Windows replaces a thread's TLS array (a new one, copied from the old) when some thread loads a DLL with static -// TLS. If that happens during the swap, the write can land in the old array; the thread then still has the -// helper's one-byte block, and the first mapped __declspec(thread) access on it writes past that block: heap -// corruption, with nothing to show for it. The swap therefore reads the array pointer again after writing and -// repeats on the new array (kSwapAttempts times); if the block is not in the thread's current array at the end, -// it is taken back and the miss is logged. A replacement after that last look is not seen. -// - TerminateThread frees a thread's TEB with no detach event. Every read and write of another thread's TEB or -// TLS array here is made right after the thread was seen running and inside __try, so a TEB that has just gone -// is a skipped thread, not a fault in load() or ~Loader. If the memory was already given to something else, the -// write is not caught. -using QueryThreadFn = LONG(NTAPI*)(HANDLE, int, void*, ULONG, ULONG*); -struct ThreadBasicInfo { // THREAD_BASIC_INFORMATION (winternl.h keeps it opaque), x64 - LONG exit_status; - void* teb; - void* process_id; - void* thread_id; - ULONG_PTR affinity; - LONG priority; - LONG base_priority; -}; -static_assert(sizeof(ThreadBasicInfo) == 48); - -QueryThreadFn query_thread_fn() { - static const auto fn = reinterpret_cast( - reinterpret_cast(GetProcAddress(GetModuleHandleW(L"ntdll.dll"), "NtQueryInformationThread"))); - return fn; -} - -// The TEB's ThreadLocalStoragePointer field of a thread that is still running; null otherwise. -void*** running_thread_tls_vector(HANDLE thread) { - ThreadBasicInfo info{}; - const QueryThreadFn query = query_thread_fn(); - if (!query || query(thread, 0 /* ThreadBasicInformation */, &info, sizeof info, nullptr) < 0) return nullptr; - if (info.exit_status != STILL_ACTIVE || !info.teb) return nullptr; - return reinterpret_cast(static_cast(info.teb) + 0x58); -} - -// That thread's TEB->TlsSlots[slot] cell (0x1480 + 8 * slot): inline in the TEB, so it cannot be replaced while the -// thread runs. Null when the thread is gone. -void** running_thread_tls_cell(HANDLE thread, uint32_t slot) { - ThreadBasicInfo info{}; - const QueryThreadFn query = query_thread_fn(); - if (!query || query(thread, 0 /* ThreadBasicInformation */, &info, sizeof info, nullptr) < 0) return nullptr; - if (info.exit_status != STILL_ACTIVE || !info.teb) return nullptr; - return reinterpret_cast(static_cast(info.teb) + 0x1480 + 8 * slot); -} - -// Another thread's TLS array and one entry of it, read through its TEB. False when the memory is not there any more -// (the thread was terminated). No C++ objects in these three: they are __try frames. -bool read_thread_slot(void*** vector, uint32_t index, void**& slots, void*& value) noexcept { - __try { - slots = *vector; - value = slots ? slots[index] : nullptr; - return true; - } __except (EXCEPTION_EXECUTE_HANDLER) { - slots = nullptr; - value = nullptr; - return false; - } -} - -bool write_thread_slot(void** slots, uint32_t index, void* value) noexcept { - __try { - slots[index] = value; - return true; - } __except (EXCEPTION_EXECUTE_HANDLER) { - return false; - } -} - -// Puts `saved` back where `block` is, if it is still there. -void restore_thread_slot(void*** vector, uint32_t index, void* block, void* saved) noexcept { - __try { - void** slots = *vector; - if (slots && slots[index] == block) slots[index] = saved; - } __except (EXCEPTION_EXECUTE_HANDLER) { - } -} - -// Writes one TlsSlots cell of another thread; false when the thread's TEB is gone already. -bool write_tls_cell(void** cell, void* value) noexcept { - __try { - *cell = value; - return true; - } __except (EXCEPTION_EXECUTE_HANDLER) { - return false; - } -} - -// Empties a TlsSlots cell that still holds `view` (a thread that ended may hold another value). -void restore_tls_cell(void** cell, void* view) noexcept { - __try { - if (*cell == view) *cell = nullptr; - } __except (EXCEPTION_EXECUTE_HANDLER) { - } -} - -// Takes a block out of its slot and frees it. The existing-threads lock is held; b.vector is null when the thread -// is gone. -void remove_existing_block(const ExistingThreadBlock& b) { - if (b.vector && b.index < kMaxModuleTlsSlots) restore_thread_slot(b.vector, b.index, b.block, b.saved); - if (b.ga_view) { - if (b.ga_cell) restore_tls_cell(b.ga_cell, b.ga_view); - VirtualFree(b.ga_view, 0, MEM_RELEASE); - } - VirtualFree(b.block, 0, MEM_RELEASE); -} - -constexpr int kSwapAttempts = 4; -constexpr size_t kMaxEndedThreads = 1024; - -// load(): every other running thread gets its own copy of m's template. Not fatal where it cannot be done. -void install_on_existing_threads(Module& m) { - const uint64_t total = static_cast(m.tls_raw_size) + m.tls_zero_fill; - if (!total || m.tls_index >= kMaxModuleTlsSlots || m.tls_slot >= kMaxMappedTlsModules) return; - // Stays ahead of the TLS lock: the first call resolves the function with GetModuleHandle and GetProcAddress, which - // take the Windows loader lock, and a thread inside its attach event holds that lock while it waits for ours. - if (!query_thread_fn()) return; - - // Outside the TLS lock: none of this may wait for a thread that is inside its attach event. - // The handles are closed on every way out, also when a vector below cannot grow. - struct Candidate { - DWORD id = 0; - HANDLE handle = nullptr; - }; - struct Candidates { - std::vector list; - HANDLE snapshot = INVALID_HANDLE_VALUE; - ~Candidates() { - if (snapshot != INVALID_HANDLE_VALUE) CloseHandle(snapshot); - for (const Candidate& c : list) - if (c.handle) CloseHandle(c.handle); - } - } found; - std::vector& candidates = found.list; - // TH32CS_SNAPTHREAD lists the threads of every process; the loop keeps this one's. - found.snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, 0); - if (found.snapshot == INVALID_HANDLE_VALUE) return; - THREADENTRY32 entry{}; - entry.dwSize = sizeof entry; - const DWORD process = GetCurrentProcessId(), self = GetCurrentThreadId(); - for (BOOL more = Thread32First(found.snapshot, &entry); more; more = Thread32Next(found.snapshot, &entry)) { - if (entry.th32OwnerProcessID != process || entry.th32ThreadID == self) continue; - candidates.push_back({entry.th32ThreadID, nullptr}); // the slot first, so the handle always has an owner - candidates.back().handle = OpenThread(THREAD_QUERY_INFORMATION, FALSE, entry.th32ThreadID); - } - - { - ExclusiveTlsLock tls_lock; - ExistingThreadsLock lock; - ExistingThreads& state = existing_threads(); - for (const Candidate& c : candidates) { - if (!c.handle) continue; - if (std::find(state.ended.begin(), state.ended.end(), c.id) != state.ended.end()) continue; - void*** vector = running_thread_tls_vector(c.handle); - void** slots = nullptr; - void* saved = nullptr; - if (!vector || !read_thread_slot(vector, m.tls_index, slots, saved) || !slots || !saved) continue; - // A copy an earlier module left in this slot of this thread goes first; what it replaced is kept. - bool present = false; - for (auto it = state.blocks.begin(); it != state.blocks.end();) { - if (it->thread != c.id || it->slot != m.tls_slot) { - ++it; - } else if (it->module == &m && it->generation == m.tls_generation) { - present = true; - break; - } else { - if (saved == it->block) saved = it->saved; - it->vector = vector; - remove_existing_block(*it); - it = state.blocks.erase(it); - } - } - if (present) continue; - void* block = VirtualAlloc(nullptr, static_cast(total), MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE); - if (!block) continue; - if (m.tls_raw_size) std::memcpy(block, m.tls_template, m.tls_raw_size); - - // Write, then look at the thread's array pointer again: if Windows has replaced the array meanwhile, the - // write went into the old one, and it is made again in the new one. - bool installed = false; - for (int attempt = 0; attempt < kSwapAttempts && !installed; ++attempt) { - if (!running_thread_tls_vector(c.handle) || !write_thread_slot(slots, m.tls_index, block)) break; - void** now = nullptr; - void* value = nullptr; - if (!read_thread_slot(vector, m.tls_index, now, value) || !now) break; - installed = now == slots && value == block; - slots = now; - } - if (!installed) { - restore_thread_slot(vector, m.tls_index, block, saved); - VirtualFree(block, 0, MEM_RELEASE); - static std::atomic logged{false}; - if (!logged.exchange(true)) - RT_LOG_ERROR("loader: %s: a running thread did not take its TLS block (it ended, or " - "its TLS array kept changing); mapped thread-local data is not valid on it\n", - m.name.c_str()); - continue; - } - void** ga_cell = nullptr; - void* ga_view = nullptr; - if (m.tls_ga_slot != kNoTlsIndex) { - // The /GA view this thread's rewritten index-0 TLS reads go through, as install_thread_block gives - // a thread started after load(). Without it those reads dereference null on this thread. - ga_cell = running_thread_tls_cell(c.handle, m.tls_ga_slot); - if (ga_cell) ga_view = make_ga_view(m, block); - if (!ga_view || !write_tls_cell(ga_cell, ga_view)) { - if (ga_view) VirtualFree(ga_view, 0, MEM_RELEASE); - ga_cell = nullptr; - ga_view = nullptr; - static std::atomic logged_view{false}; - if (!logged_view.exchange(true)) - RT_LOG_ERROR("loader: %s: a running thread did not take its /GA TLS view; " - "index-0 TLS reads in it have no block\n", - m.name.c_str()); - } - } - state.blocks.push_back( - {c.id, m.tls_slot, &m, m.tls_generation, m.tls_index, vector, saved, block, ga_cell, ga_view}); - } - } -} - -// ~Loader, with g_tls_lock held exclusively: the blocks load() put into other threads come out. A thread that has -// ended without a detach event (TerminateThread) has no TEB to restore. -void remove_from_existing_threads(Module& m) { - ExistingThreadsLock lock; - ExistingThreads& state = existing_threads(); - for (auto it = state.blocks.begin(); it != state.blocks.end();) { - if (it->module != &m || it->generation != m.tls_generation) { - ++it; - continue; - } - ExistingThreadBlock b = *it; - it = state.blocks.erase(it); - const HANDLE h = OpenThread(THREAD_QUERY_INFORMATION, FALSE, b.thread); - if (!h || running_thread_tls_vector(h) != b.vector) b.vector = nullptr; - if (h) CloseHandle(h); - if (!b.vector) b.ga_cell = nullptr; // the TEB went with the thread - remove_existing_block(b); - } -} - -// DLL_THREAD_ATTACH: a record under this thread's id is from a thread that ended without a detach event. -void forget_ended_thread_id() { - const DWORD self = GetCurrentThreadId(); - ExistingThreadsLock lock; - ExistingThreads& state = existing_threads(); - state.ended.erase(std::remove(state.ended.begin(), state.ended.end(), self), state.ended.end()); - for (auto it = state.blocks.begin(); it != state.blocks.end();) { - if (it->thread != self) { - ++it; - continue; - } - VirtualFree(it->block, 0, MEM_RELEASE); - VirtualFree(it->ga_view, 0, MEM_RELEASE); - it = state.blocks.erase(it); - } -} - -// DLL_THREAD_DETACH, before this thread's own records are released: the blocks load() gave it come out, newest first, -// after the module's TLS callbacks have seen the event (Windows sends DLL_THREAD_DETACH to a DLL for a thread that -// was running before it was loaded, too). -void release_existing_blocks_of_this_thread() { - const DWORD self = GetCurrentThreadId(); - std::vector mine; - { - ExistingThreadsLock lock; - for (const auto& b : existing_threads().blocks) - if (b.thread == self) mine.push_back(b); - } - for (auto it = mine.rbegin(); it != mine.rend(); ++it) { - Module* m = it->module; - if (g_tls_slot_owners[it->slot].load() != m || g_tls_slot_generations[it->slot].load() != it->generation || - !m->initialised) - continue; - try { - run_callbacks(*m, DLL_THREAD_DETACH); - } catch (const std::exception& e) { - RT_LOG_ERROR("loader: thread detach: %s\n", e.what()); - } - } - ExistingThreadsLock lock; - ExistingThreads& state = existing_threads(); - for (auto it = state.blocks.end(); it != state.blocks.begin();) { - --it; - if (it->thread != self) continue; - remove_existing_block(*it); - it = state.blocks.erase(it); - } - // Bounded: an id matters only until its thread has left the process, moments after this event, so the oldest - // can go. (An id also leaves the list when a new thread gets it.) - if (state.ended.size() >= kMaxEndedThreads) state.ended.erase(state.ended.begin(), state.ended.begin() + kMaxEndedThreads / 2); - state.ended.push_back(self); -} - -// Runs in gta6rt_tls_host.dll's DllMain for each thread the process starts or ends once the helper is loaded, under -// the Windows loader lock, on that thread. A new thread gets its own copy of each active TLS owner's template; an -// ending one gives each helper's block back before the Windows loader frees it. TLS callbacks get the thread events -// only after the module's DLL_PROCESS_ATTACH (initialise()), as the Windows loader orders them. -void __cdecl on_host_thread_event(DWORD reason) { - SharedTlsLock lock; - // The try/catch is per slot: a throw from one module's install or callbacks must not take the thread events - // away from the other slots. Nothing may leave DllMain. - if (reason == DLL_THREAD_ATTACH) { - try { - forget_ended_thread_id(); - } catch (const std::exception& e) { - RT_LOG_ERROR("loader: thread attach: %s\n", e.what()); - } - for (size_t slot = 0; slot < kMaxMappedTlsModules; ++slot) { - Module* m = g_tls_slot_owners[slot].load(); - if (!m) continue; - try { - install_thread_block(*m); - if (m->initialised) run_callbacks(*m, DLL_THREAD_ATTACH); - } catch (const std::exception& e) { - // The thread runs on without this module's TLS; later slots still get theirs. - RT_LOG_ERROR("loader: thread attach, slot %zu (%s): %s\n", slot, m->name.c_str(), - e.what()); - } - } - } else if (reason == DLL_THREAD_DETACH) { - // The blocks load() gave this thread while it was already running come out first (they can sit on top of - // an older module's block in the same slot). - try { - release_existing_blocks_of_this_thread(); - } catch (const std::exception& e) { - RT_LOG_ERROR("loader: thread detach: %s\n", e.what()); - } - for (size_t i = kMaxMappedTlsModules; i-- > 0;) { - Module* m = g_tls_slot_owners[i].load(); - if (m && g_thread_tls_slots[i].module == m && - g_thread_tls_slots[i].generation == m->tls_generation) { - try { - if (m->initialised) run_callbacks(*m, DLL_THREAD_DETACH); - } catch (const std::exception& e) { - RT_LOG_ERROR("loader: thread detach, slot %zu (%s): %s\n", i, m->name.c_str(), - e.what()); - } - // Released even when the callbacks threw: a leaked block would be handed to the OS loader as the - // helper's own TLS block and freed with it at thread exit. - uninstall_thread_block(*m); - } else { - release_thread_slot(i); // installed by a module whose Loader is gone (or nothing to do) - } - } - } -} - -// The Xbox builds of the MSVC runtime import the same CRT the desktop does, so the host's own copies are used. -bool prefer_host_copy(const std::string& dll) { - // The second row is the Debug builds of the same DLLs. A Debug build of a stand-in image (tiny_game) links them, - // and without them here its C++ exceptions were not redirected below: a throw caught inside the image ended the - // run with 0xE06D7363 (run_tiny_game_eh in a Debug build). - static const char* names[] = {"vcruntime140.dll", "vcruntime140_1.dll", "msvcp140.dll", "msvcp140_1.dll", - "msvcp140_2.dll", "msvcp140_atomic_wait.dll", "msvcp140_codecvt_ids.dll", - "concrt140.dll", "vccorlib140.dll", "vcomp140.dll", - "vcruntime140d.dll", "vcruntime140_1d.dll", "msvcp140d.dll", "msvcp140_1d.dll", - "msvcp140_2d.dll", "msvcp140d_atomic_wait.dll", "msvcp140d_codecvt_ids.dll", - "concrt140d.dll", "vccorlib140d.dll", "vcomp140d.dll"}; - for (auto* n : names) - if (dll == n) return true; - return false; -} - -// MSVC C++ exceptions in a mapped image. _CxxThrowException (vcruntime140.dll) puts the throwing image's base in the -// exception record, from RtlPcToFileHeader(pThrowInfo); the frame handler adds the ThrowInfo's RVAs (catchable types, -// copy constructor, destructor) to it. RtlPcToFileHeader only knows images the Windows loader mapped, so for ours the -// base is 0 and the exception can't be matched to a catch. The host copies the loader binds get their import of it -// redirected: the Windows answer first, then the modules a live Loader has mapped (shims::mapped_image_base). -using PcToFileHeaderFn = PVOID(NTAPI*)(PVOID, PVOID*); -std::atomic g_host_pc_to_file_header{nullptr}; - -PVOID NTAPI pc_to_file_header(PVOID pc, PVOID* base) { - if (PVOID found = g_host_pc_to_file_header.load()(pc, base)) return found; - uint64_t mapped = 0; - if (!shims::mapped_image_base(reinterpret_cast(pc), mapped)) { - *base = nullptr; - return nullptr; - } - *base = reinterpret_cast(mapped); - return *base; -} - -// Points every import of RtlPcToFileHeader by name in a host module at pc_to_file_header, once per module. The -// module is a system DLL the Windows loader has already validated and bound, so its tables are read unchecked. -// The redirect stays for the process lifetime; with no live Loader it answers exactly as Windows does. -void redirect_pc_to_file_header(HMODULE host) { - static std::mutex mutex; - static std::vector done; - std::lock_guard lock(mutex); - if (std::find(done.begin(), done.end(), host) != done.end()) return; - done.push_back(host); - - auto* base = reinterpret_cast(host); - auto* nt = at(base, reinterpret_cast(base)->e_lfanew); - const auto& dir = nt->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT]; - if (!dir.Size || !dir.VirtualAddress) return; - for (auto* d = at(base, dir.VirtualAddress); d->Name; ++d) { - if (!d->OriginalFirstThunk) continue; // no name table to match against - auto* names = at(base, d->OriginalFirstThunk); - auto* iat = at(base, d->FirstThunk); - for (; names->u1.AddressOfData; ++names, ++iat) { - if (IMAGE_SNAP_BY_ORDINAL64(names->u1.Ordinal)) continue; - auto* by_name = at(base, static_cast(names->u1.AddressOfData)); - if (std::strcmp(reinterpret_cast(by_name->Name), "RtlPcToFileHeader") != 0) continue; - auto* slot = reinterpret_cast(&iat->u1.Function); - if (*slot == reinterpret_cast(&pc_to_file_header)) continue; - PcToFileHeaderFn expected = nullptr; // the first bound address is the Windows function - g_host_pc_to_file_header.compare_exchange_strong(expected, reinterpret_cast(*slot)); - DWORD old = 0; - if (!VirtualProtect(slot, sizeof(void*), PAGE_READWRITE, &old)) continue; - *slot = reinterpret_cast(&pc_to_file_header); - VirtualProtect(slot, sizeof(void*), old, &old); - } - } -} - -// The module a host import actually resolved into. GetProcAddress follows forwarders, so this can be another DLL -// than the one imported (on Windows vcruntime140.dll implements _CxxThrowException itself); that module's -// RtlPcToFileHeader import is the one the throw calls. -void redirect_pc_to_file_header_at(const void* resolved) { - HMODULE owner = nullptr; - if (GetModuleHandleExW(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT, - static_cast(resolved), &owner) && owner) - redirect_pc_to_file_header(owner); -} - -} // namespace - -// Declared in pe_loader.h; the body needs the internal clone registry above. -void cleanup_tls_clones() { cleanup_tls_clones_internal(); } - -namespace { -bool lookup_in_loader(void* ctx, uint64_t address, std::string& module, uint32_t& rva) { - return static_cast(ctx)->find_address(address, module, rva); -} - -void* bundled_find_loaded(void* ctx, const std::string& dll_lower) { - return static_cast(ctx)->find_loaded_module(dll_lower); -} - -void* bundled_load(void* ctx, const std::string& dll_lower, uint32_t flags, bool& handled) { - return static_cast(ctx)->load_runtime_module(dll_lower, flags, handled); -} - -void* bundled_get_proc(void* ctx, void* module, const std::string& sym, bool& owns_handle) { - return static_cast(ctx)->resolve_module_export(module, sym, owns_handle); -} - -bool bundled_owns_handle(void* ctx, void* module) { - return static_cast(ctx)->owns_module_handle(module); -} - -void* bundled_find_loaded_w(void* ctx, const std::wstring& basename) { - return static_cast(ctx)->find_loaded_module_w(basename); -} - -void* bundled_load_w(void* ctx, const std::wstring& basename, uint32_t flags, bool& handled) { - return static_cast(ctx)->load_runtime_module_w(basename, flags, handled); -} - -const shims::BundledModuleOps kBundledOps{ - &bundled_find_loaded, - &bundled_load, - &bundled_get_proc, - &bundled_owns_handle, - &bundled_find_loaded_w, - &bundled_load_w, -}; - -// Marks what a run-time load maps as a dynamic load for as long as it is in scope (the caller holds the mutex). -struct RuntimeLoadScope { - explicit RuntimeLoadScope(int& depth) : depth_(depth) { ++depth_; } - ~RuntimeLoadScope() { --depth_; } - RuntimeLoadScope(const RuntimeLoadScope&) = delete; - RuntimeLoadScope& operator=(const RuntimeLoadScope&) = delete; - int& depth_; -}; -} // namespace - -Loader::Loader(std::filesystem::path game_dir) : game_dir_(std::move(game_dir)) { - compat_dir_ = rt::config::path("paths.compat_dir"); - shims::add_module_lookup(this, &lookup_in_loader); - shims::add_bundled_loader(this, &kBundledOps); -} - -Loader::~Loader() { - // Importers must release their resources before their dependencies. Keep every mapping, unwind table and TLS - // block alive throughout the notifications: a detach handler can still call an imported function or free an - // FLS slot whose destructor lives in another mapped image. - for (auto it = init_order_.rbegin(); it != init_order_.rend(); ++it) { - Module& m = **it; - if (!m.initialised) continue; // a map-only load never opts in to running image code - set_initialised(m, false); // under the TLS lock: thread events stop running its callbacks - try { - run_tls_callbacks(m, DLL_PROCESS_DETACH); - } catch (const std::exception& e) { - // A module may have changed its callback table since attach. A destructor cannot propagate the validation - // error; report it and still let DllMain release resources before the image is freed. - RT_LOG_ERROR("TLS process detach failed for %s: %s\n", m.name.c_str(), e.what()); - } - auto* nt = at(m.base, reinterpret_cast(m.base)->e_lfanew); - if ((nt->FileHeader.Characteristics & IMAGE_FILE_DLL) && m.entry_rva) { - auto entry = reinterpret_cast(m.base + m.entry_rva); - entry(m.base, DLL_PROCESS_DETACH, nullptr); // explicit unload; the return value is ignored - } - } - shims::remove_bundled_loader(this); - shims::remove_module_lookup(this); - for (auto* m : order_) { - // TLS state must go away before the image and its TLS block are unmapped. - if (m->tls_index != kNoTlsIndex && m->tls_slot < kMaxMappedTlsModules) { - // Retired first, under the lock: no thread event installs it or runs its callbacks after this, and a - // thread that still holds a copy frees it when it ends (on_host_thread_event). - { - ExclusiveTlsLock lock; - Module* owner = m; - if (g_tls_slot_owners[m->tls_slot].compare_exchange_strong(owner, nullptr)) - g_tls_slot_generations[m->tls_slot].store(0); - remove_from_existing_threads(*m); - } - uninstall_tls_for_thread(*m); - } - // Before the image is freed: a stale table would let a later stack walk read unmapped memory. - if (m->function_table) RtlDeleteFunctionTable(static_cast(m->function_table)); - if (m->tls_block) VirtualFree(m->tls_block, 0, MEM_RELEASE); - if (m->base) VirtualFree(m->base, 0, MEM_RELEASE); - delete m; - } -} - -Module& Loader::load(const std::filesystem::path& image) { - std::lock_guard lock(mutex_); - const auto key = module_key(image); - if (auto it = by_name_.find(key); it != by_name_.end()) return *it->second; - const auto narrow_key = narrow_module_key(image); - if (Module* existing = find_narrow_module(narrow_key)) return *existing; - Module* mapped = nullptr; - try { - mapped = &map_image(image, narrow_key); - mapped->dynamic_load = runtime_loads_ > 0; // before bind_imports: its dependencies are marked the same way - bind_imports(*mapped); // loads every bundled module m imports first, so they land in init_order_ before m - protect_sections(*mapped); - register_unwind(*mapped); - } catch (...) { - // A failed load, nested ones (a dependency of a run-time load) included, must not stay findable by name: - // a later lookup would get a half-mapped image with unbound imports. ~Loader still frees it through order_. - by_name_.erase(key); - throw; - } - Module& m = *mapped; - init_order_.push_back(&m); - if (startup_trace::enabled()) - startup_trace::event("map", "\"module\":" + startup_trace::quote(m.name) + - ",\"base\":" + startup_trace::quote(startup_trace::hex(reinterpret_cast(m.base))) + - ",\"size\":" + startup_trace::quote(startup_trace::hex(m.size)) + - ",\"relocated\":" + (m.relocated ? "true" : "false")); - return m; -} - -Module* Loader::find_narrow_module(const std::string& dll_lower) const { - if (dll_lower.empty()) return nullptr; - // library_loader and PE import names keep their existing narrow-byte contract: the exact compare below is - // bytewise, and the key is never reinterpreted as UTF-8. - for (const auto& entry : by_name_) - if (entry.second->narrow_key == dll_lower) return entry.second; - // The key is ASCII case-folded only. A name with letters outside ASCII (Cyrillic in code page 1251, say) - // compares case-insensitively through the code page, as GetModuleHandleA does: GUEST_ДА.EXE finds guest_да.exe. - // Widening the folded key is safe here: rt::lower() folds ASCII letters only, and no ANSI code page's multibyte - // sequences contain ASCII letter bytes, so both sides widen to the same characters they were spelt with. - if (const std::wstring wide = acp_to_wide(dll_lower); !wide.empty()) - for (const auto& entry : by_name_) - if (!entry.second->narrow_key.empty() && - same_module_name(acp_to_wide(entry.second->narrow_key).c_str(), wide.c_str())) - return entry.second; - return nullptr; -} - -Module* Loader::find_wide_module(const std::wstring& basename) const { - if (basename.empty()) return nullptr; - for (const auto& entry : by_name_) - if (same_module_name(entry.first.c_str(), basename.c_str())) return entry.second; - return nullptr; -} - -void* Loader::find_loaded_module_w(const std::wstring& basename) const { - std::lock_guard lock(mutex_); - Module* m = find_wide_module(basename); - return m ? static_cast(m->base) : nullptr; -} - -void* Loader::find_loaded_module(const std::string& dll_lower) const { - std::lock_guard lock(mutex_); - Module* m = find_narrow_module(dll_lower); - return m ? static_cast(m->base) : nullptr; -} - -void* Loader::load_runtime_module(const std::string& dll_lower, uint32_t flags, bool& handled) { - handled = false; - if (dll_lower.empty() || prefer_host_copy(dll_lower)) return nullptr; - - std::lock_guard lock(mutex_); - const RuntimeLoadScope dynamic(runtime_loads_); - Module* existing = find_narrow_module(dll_lower); - const std::filesystem::path candidate = game_dir_ / dll_lower; - std::error_code ec; - const bool is_bundled = existing || std::filesystem::is_regular_file(candidate, ec); - if (!is_bundled) return nullptr; - - handled = true; - return load_runtime_candidate(existing, candidate, flags, dll_lower); -} - -void* Loader::load_runtime_module_w(const std::wstring& basename, uint32_t flags, bool& handled) { - handled = false; - if (basename.empty()) return nullptr; - // A name the code page can spell takes the narrow path's host-copy rule as well. - if (const std::string narrow = narrow_module_key(std::filesystem::path(basename)); !narrow.empty()) - if (prefer_host_copy(narrow)) return nullptr; - - std::lock_guard lock(mutex_); - Module* existing = find_wide_module(basename); - const std::filesystem::path candidate = game_dir_ / basename; - std::error_code ec; - if (!existing && !std::filesystem::is_regular_file(candidate, ec)) return nullptr; - - handled = true; - return load_runtime_candidate(existing, candidate, flags, path_utf8(basename)); -} - -void* Loader::load_runtime_candidate(Module* existing, const std::filesystem::path& candidate, uint32_t flags, - const std::string& display) { - // Win32 DONT_RESOLVE_DLL_REFERENCES (0x1) forbids resolving dependencies or running TLS/DllMain; refuse it - // explicitly instead of silently performing a normal resolving + initialising load. - if ((flags & DONT_RESOLVE_DLL_REFERENCES) != 0) { - RT_LOG_ERROR("loader: LoadLibraryEx(%s, DONT_RESOLVE_DLL_REFERENCES) is not supported for bundled DLLs\n", - display.c_str()); - SetLastError(ERROR_NOT_SUPPORTED); - return nullptr; - } - - if (existing) { - try { - initialise(); - return static_cast(existing->base); - } catch (const std::exception& e) { - RT_LOG_ERROR("loader: run-time initialise of %s failed: %s\n", display.c_str(), e.what()); - SetLastError(ERROR_DLL_INIT_FAILED); - return nullptr; - } - } - - Module* mapped = nullptr; - try { - Module& m = load(candidate); - mapped = &m; - initialise(); - RT_LOG_INFO("loader: %s mapped from game_dir (run-time load)\n", m.name.c_str()); - return static_cast(m.base); - } catch (const std::exception& e) { - // load() drops a module that failed to map or bind (dependencies included); this also drops one whose - // initialise() failed, so later GetModuleHandle/LoadLibrary calls don't see it. ~Loader frees it via order_. - by_name_.erase(module_key(mapped ? mapped->path : candidate)); - RT_LOG_ERROR("loader: run-time load of %s failed: %s\n", display.c_str(), e.what()); - SetLastError(ERROR_DLL_INIT_FAILED); - return nullptr; - } -} - -void* Loader::resolve_module_export(void* module_handle, const std::string& sym, bool& owns_handle) { - owns_handle = false; - if (!module_handle) return nullptr; - std::lock_guard lock(mutex_); - Module* target = nullptr; - for (Module* m : order_) { - if (m->base == module_handle) { - target = m; - break; - } - } - if (!target) return nullptr; - owns_handle = true; - if (auto it = target->exports.find(sym); it != target->exports.end()) return it->second; - if (auto it = target->forwarders.find(sym); it != target->forwarders.end()) { - try { - const RuntimeLoadScope dynamic(runtime_loads_); - Binding binding = Binding::Unimplemented; - void* fn = resolve_forwarder(it->second, binding, 0); - if (binding == Binding::Module) initialise(); - return fn; - } catch (const std::exception& e) { - RT_LOG_ERROR("loader: forwarder %s from %s failed: %s\n", it->second.c_str(), - target->name.c_str(), e.what()); - return nullptr; - } - } - return nullptr; -} - -bool Loader::find_address(uint64_t address, std::string& module, uint32_t& rva) const { - std::shared_lock lock(ranges_mutex_); - for (const MappedRange& r : ranges_) { - if (address >= r.base && address - r.base < r.size) { - module = r.name; - rva = static_cast(address - r.base); - return true; - } - } - return false; -} - -bool Loader::owns_module_handle(void* module_handle) const { - if (!module_handle) return false; - std::lock_guard lock(mutex_); - for (const Module* m : order_) - if (m->base == module_handle) return true; - return false; -} - -// x64 has no frame-pointer chain to fall back on: without its .pdata registered, an exception raised in (or passing -// through) a mapped image can't be dispatched past that frame, and the process dies. Images the system loader maps -// are found through its own module list; ours are VirtualAlloc'd, so they are registered as dynamic function tables. -// -// The table is checked before it is handed over, because RtlLookupFunctionEntry trusts it: it binary-searches the -// entries by BeginAddress and follows UnwindData without bounds checks. Measured over 3,780 x64 images in -// System32 (5,023,071 entries) and the package's FidelityFX DLLs: every table is sorted and non-overlapping and in -// bounds, and one shipped image (symcryptk.dll) has a zero-length entry (BeginAddress == EndAddress), so that is -// allowed. No entry in that set uses the indirect form (UnwindData bit 0). -void Loader::register_unwind(Module& m) { - auto* nt = at(m.base, reinterpret_cast(m.base)->e_lfanew); - const auto dir = directory(nt, IMAGE_DIRECTORY_ENTRY_EXCEPTION); - // Like the system loader, a trailing partial entry is ignored. - const uint32_t count = dir.Size / sizeof(RUNTIME_FUNCTION); - if (!count) return; - require_range(m.name, dir.VirtualAddress, static_cast(count) * sizeof(RUNTIME_FUNCTION), m.size, - "the exception directory"); - auto* table = at(m.base, dir.VirtualAddress); - auto reject = [&](uint32_t i, const char* why) { - throw std::runtime_error(m.name + ": unwind entry " + std::to_string(i) + " " + why); - }; - uint32_t previous_end = 0; - for (uint32_t i = 0; i < count; ++i) { - const RUNTIME_FUNCTION& f = table[i]; - if (f.EndAddress < f.BeginAddress || f.EndAddress > m.size) reject(i, "covers code outside the image"); - if (f.BeginAddress < previous_end) reject(i, "is out of order or overlaps the one before it"); - // UNWIND_INFO starts with a 4-byte header; its codes and handler data are the unwinder's to read. - const uint32_t info = f.UnwindData & ~1u; - if (info > m.size || m.size - info < 4) reject(i, "has unwind data outside the image"); - previous_end = f.EndAddress; - } - if (!RtlAddFunctionTable(table, count, reinterpret_cast(m.base))) - throw std::runtime_error(m.name + ": RtlAddFunctionTable failed"); - m.function_table = table; - m.function_count = count; -} - -void Loader::initialise() { - // Not order_: map_image pushes a module there before bind_imports maps its dependencies, so order_ lists an - // importer ahead of the DLLs it imports. init_order_ is filled once a module's imports are all loaded. - for (auto* m : init_order_) initialise(*m); -} - -void Loader::initialise(Module& m) { - if (m.initialised) return; - - // TLS was installed by load(); initialise() only delivers the events, so no slot is allocated or written twice. - run_tls_callbacks(m, DLL_PROCESS_ATTACH); - - // Only a DLL gets DllMain. An EXE's entry point has a different signature and is the caller's to run. - auto* nt = at(m.base, reinterpret_cast(m.base)->e_lfanew); - if ((nt->FileHeader.Characteristics & IMAGE_FILE_DLL) && m.entry_rva) { - auto entry = reinterpret_cast(m.base + m.entry_rva); - // lpvReserved "is NULL for dynamic loads and non-NULL for static loads" (DllMain docs). What Windows points - // it at is its own; a static load gets a CONTEXT captured here, so a DLL that reads through it reads memory. - CONTEXT context{}; - if (!m.dynamic_load) RtlCaptureContext(&context); - const BOOL ok = entry(m.base, DLL_PROCESS_ATTACH, m.dynamic_load ? nullptr : &context); - if (startup_trace::enabled()) - startup_trace::event("dllmain", "\"module\":" + startup_trace::quote(m.name) + - ",\"result\":" + std::to_string(ok)); - if (!ok) { - set_initialised(m, true); // it ran: a second DLL_PROCESS_ATTACH would be wrong - throw std::runtime_error(m.name + ": DllMain returned FALSE"); - } - } - set_initialised(m, true); -} - -// Under the TLS lock, which orders it against the thread events: they run a module's TLS callbacks only while this is -// true (from initialise() until ~Loader starts the process detach). -void Loader::set_initialised(Module& m, bool value) { - ExclusiveTlsLock lock; - m.initialised = value; -} - -Module& Loader::map_image(const std::filesystem::path& path, const std::string& narrow_key) { - auto file = read_file(path); - const std::string name = path_utf8(path.filename()); - auto* dos = reinterpret_cast(file.data()); - if (file.size() < sizeof(IMAGE_DOS_HEADER) || dos->e_magic != IMAGE_DOS_SIGNATURE) - throw std::runtime_error(path_utf8(path) + ": not an MZ image"); - if (dos->e_lfanew < 0 || static_cast(dos->e_lfanew) + sizeof(IMAGE_NT_HEADERS64) > file.size()) - throw std::runtime_error(name + ": the NT headers are outside the file"); - auto* nt = reinterpret_cast(file.data() + dos->e_lfanew); - if (nt->Signature != IMAGE_NT_SIGNATURE || nt->FileHeader.Machine != IMAGE_FILE_MACHINE_AMD64) - throw std::runtime_error(name + ": not an x86-64 PE"); - if (nt->FileHeader.SizeOfOptionalHeader < sizeof(IMAGE_OPTIONAL_HEADER64) || - nt->OptionalHeader.Magic != IMAGE_NT_OPTIONAL_HDR64_MAGIC) - throw std::runtime_error(name + ": not a PE32+ image"); - auto& oh = nt->OptionalHeader; - const uint64_t sections = static_cast(dos->e_lfanew) + 4 + sizeof(IMAGE_FILE_HEADER) + - nt->FileHeader.SizeOfOptionalHeader; - const uint64_t headers_end = - sections + static_cast(nt->FileHeader.NumberOfSections) * sizeof(IMAGE_SECTION_HEADER); - if (headers_end > file.size()) - throw std::runtime_error(name + ": the section table runs past the end of the file"); - if (!oh.SizeOfImage || oh.SizeOfHeaders < headers_end || oh.SizeOfHeaders > oh.SizeOfImage || - oh.SizeOfHeaders > file.size()) - throw std::runtime_error(name + ": SizeOfHeaders and SizeOfImage don't fit the headers and file"); - if (oh.AddressOfEntryPoint && oh.AddressOfEntryPoint >= oh.SizeOfImage) - throw std::runtime_error(name + ": the entry point is outside the image"); - - auto* m = new Module; - m->name = name; - m->narrow_key = narrow_key; - m->path = path; - m->preferred_base = oh.ImageBase; - m->size = oh.SizeOfImage; - m->entry_rva = oh.AddressOfEntryPoint; - by_name_[module_key(path)] = m; - order_.push_back(m); - - // Inside the range gta6rt reserved for this image before the process started (base_reservation.h), else as usual. - m->base = static_cast(base_reservation::commit_reserved(oh.ImageBase, oh.SizeOfImage)); - if (!m->base) - m->base = static_cast(VirtualAlloc(reinterpret_cast(oh.ImageBase), oh.SizeOfImage, - MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE)); - if (!m->base) { - const auto relocs = directory(nt, IMAGE_DIRECTORY_ENTRY_BASERELOC); - if (!relocs.Size) - throw std::runtime_error(m->name + ": preferred base is taken and the image has no relocations"); - m->base = static_cast(VirtualAlloc(nullptr, oh.SizeOfImage, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE)); - if (!m->base) throw std::runtime_error(m->name + ": VirtualAlloc failed"); - } - { - // From here an address inside the image names it. The memory stays until ~Loader, which unregisters the - // lookup first. - std::unique_lock lock(ranges_mutex_); - ranges_.push_back({reinterpret_cast(m->base), m->size, m->name}); - } - - std::memcpy(m->base, file.data(), oh.SizeOfHeaders); - auto* sec = IMAGE_FIRST_SECTION(nt); - for (unsigned i = 0; i < nt->FileHeader.NumberOfSections; ++i, ++sec) { - if (sec->VirtualAddress < oh.SizeOfHeaders) - throw std::runtime_error(m->name + ": section " + std::to_string(i) + " overlaps the headers"); - uint32_t n = std::min(sec->SizeOfRawData, sec->Misc.VirtualSize ? sec->Misc.VirtualSize : sec->SizeOfRawData); - if (!n) continue; - if (sec->PointerToRawData > file.size() || n > file.size() - sec->PointerToRawData) - throw std::runtime_error(m->name + ": section " + std::to_string(i) + " reads past the end of the file"); - require_range(m->name, sec->VirtualAddress, n, m->size, "a section's data"); - std::memcpy(m->base + sec->VirtualAddress, file.data() + sec->PointerToRawData, n); - } - - int64_t delta = reinterpret_cast(m->base) - static_cast(oh.ImageBase); - if (delta) { - m->relocated = true; - const auto dir = directory(nt, IMAGE_DIRECTORY_ENTRY_BASERELOC); - if (!dir.Size) throw std::runtime_error(m->name + ": the image has no relocations and isn't at its base"); - require_range(m->name, dir.VirtualAddress, dir.Size, m->size, "the relocation table"); - auto* block = at(m->base, dir.VirtualAddress); - auto* end = reinterpret_cast(block) + dir.Size; - while (reinterpret_cast(block) < end) { - const size_t remaining = static_cast(end - reinterpret_cast(block)); - if (remaining < sizeof(IMAGE_BASE_RELOCATION) || block->SizeOfBlock < sizeof(IMAGE_BASE_RELOCATION) || - block->SizeOfBlock > remaining) - throw std::runtime_error(m->name + ": a relocation block doesn't fit the relocation table"); - auto* entries = reinterpret_cast(block + 1); - size_t count = (block->SizeOfBlock - sizeof(IMAGE_BASE_RELOCATION)) / 2; - for (size_t i = 0; i < count; ++i) { - uint16_t type = entries[i] >> 12, off = entries[i] & 0xFFF; - if (type != IMAGE_REL_BASED_ABSOLUTE && - static_cast(block->VirtualAddress) + off < oh.SizeOfHeaders) - throw std::runtime_error(m->name + ": a relocation lands in the headers"); - if (type == IMAGE_REL_BASED_DIR64) { - require_range(m->name, static_cast(block->VirtualAddress) + off, sizeof(uint64_t), m->size, - "a relocation"); - *at(m->base, block->VirtualAddress + off) += delta; - } else if (type == IMAGE_REL_BASED_HIGHLOW) { - // A 32-bit absolute address (code built /LARGEADDRESSAWARE:NO), which the x64 Windows loader - // also applies. Where the new address no longer fits in 32 bits, Windows would truncate it; the - // image would then jump or read through a wrong pointer, so the load is refused instead. - require_range(m->name, static_cast(block->VirtualAddress) + off, sizeof(uint32_t), - m->size, "a relocation"); - auto* slot = at(m->base, block->VirtualAddress + off); - const int64_t moved = static_cast(*slot) + delta; - if (moved < 0 || moved > 0xFFFFFFFFll) - throw std::runtime_error(m->name + ": a 32-bit (HIGHLOW) relocation does not fit at this base"); - *slot = static_cast(moved); - } else if (type != IMAGE_REL_BASED_ABSOLUTE) { - throw std::runtime_error(m->name + ": unsupported relocation type " + std::to_string(type)); - } - } - block = reinterpret_cast(reinterpret_cast(block) + block->SizeOfBlock); - } - } - // The TLS directory and the exception directory hold virtual addresses, so both are read after relocation. TLS is - // installed here, before bind_imports can return control to the caller and before any image code can run. - initialize_tls(*m); - parse_exports(*m); - return *m; -} - -// Static TLS for the thread that calls load(). The PE TLS directory only carries the template (Start..End) and the -// zero-fill size; it has no field naming the TLS block. The Windows loader allocates a block per module per thread and -// puts it in TEB->ThreadLocalStoragePointer[module index], which is what __declspec(thread) code reads via _tls_index. -// Only the OS loader can allocate that module index, so the loader reuses the index the OS assigned to -// gta6rt_tls_host.dll and maps a fresh clone of the helper for every additional simultaneous TLS module, each clone -// getting its own index. All kMaxMappedTlsModules slots can be live at once; a further module is rejected rather than -// silently sharing (and corrupting) a slot. -void Loader::initialize_tls(Module& m) { - auto* tls = tls_directory(m); - if (!tls) return; - // A present but all-zero directory is treated like an absent one. - if (!tls->StartAddressOfRawData && !tls->EndAddressOfRawData && !tls->AddressOfIndex && !tls->AddressOfCallBacks && - !tls->SizeOfZeroFill) - return; - if (tls->EndAddressOfRawData < tls->StartAddressOfRawData) - throw std::runtime_error(m.name + ": TLS template end precedes its start"); - uint64_t raw = tls->EndAddressOfRawData - tls->StartAddressOfRawData; - uint64_t total = raw + tls->SizeOfZeroFill; - if (total > 0xFFFFFFFFull) throw std::runtime_error(m.name + ": TLS block is too large"); - const uint32_t raw_rva = - raw ? static_cast(rva_in(m, tls->StartAddressOfRawData, "the TLS template")) : 0; - if (raw) require_range(m.name, raw_rva, raw, m.size, "the TLS template"); - uint64_t index_rva = 0; - if (tls->AddressOfIndex) { - index_rva = rva_in(m, tls->AddressOfIndex, "the TLS index"); - require_range(m.name, index_rva, sizeof(uint32_t), m.size, "the TLS index"); - } - - if (!module_tls_slots()) throw std::runtime_error(m.name + ": this thread has no TLS array"); - - size_t slot = kMaxMappedTlsModules; - DWORD index = TLS_OUT_OF_INDEXES; - { - std::lock_guard alloc_lock(g_tls_alloc_mutex); - for (size_t i = 0; i < kMaxMappedTlsModules; ++i) { - if (g_tls_slot_owners[i].load() == nullptr) { - slot = i; - break; - } - } - if (slot >= kMaxMappedTlsModules) - throw std::runtime_error(m.name + ": all " + std::to_string(kMaxMappedTlsModules) + - " manually mapped static TLS slots are in use"); - - // Load/clone gta6rt_tls_host.dll OUTSIDE ExclusiveTlsLock so LoadLibraryExW cannot deadlock with - // on_host_thread_event (which runs under the Windows loader lock and takes SharedTlsLock). - index = ensure_tls_host(slot).index; - if (index == TLS_OUT_OF_INDEXES) - throw std::runtime_error(m.name + ": gta6rt_tls_host.dll is missing or has no module TLS index"); - if (index >= kMaxModuleTlsSlots) throw std::runtime_error(m.name + ": reserved TLS index is out of range"); - - // The fields are complete before a thread event can see the owner. - ExclusiveTlsLock lock; - Module* expected = nullptr; - if (!g_tls_slot_owners[slot].compare_exchange_strong(expected, &m)) - throw std::runtime_error(m.name + ": static TLS slot was claimed concurrently"); - - m.tls_slot = static_cast(slot); - m.tls_generation = g_next_tls_generation.fetch_add(1, std::memory_order_relaxed); - g_tls_slot_generations[slot].store(m.tls_generation); - m.tls_index = index; - m.tls_template = raw ? m.base + raw_rva : nullptr; - m.tls_raw_size = static_cast(raw); - m.tls_zero_fill = tls->SizeOfZeroFill; - m.tls_block_size = static_cast(total); - // The index lives in a writable section and protect_sections() has not run yet, so the write needs no - // VirtualProtect dance. - if (index_rva) *reinterpret_cast(m.base + index_rva) = index; - } - { - // An EXE's code may read its TLS at index 0 directly (/GA); index 0 is gta6rt.exe's here (pe_loader.h, - // tls_ga_slot). Patched before any of the image's code runs, TLS callbacks included. - const auto* dos = reinterpret_cast(m.base); - const auto* nt = reinterpret_cast(m.base + dos->e_lfanew); - if (!(nt->FileHeader.Characteristics & IMAGE_FILE_DLL) && total && index != 0 && ga_tls_patch_enabled()) { - static const DWORD ga_slot = TlsAlloc(); - if (ga_slot == TLS_OUT_OF_INDEXES || ga_slot >= 64) { - RT_LOG_ERROR("loader: %s: no TlsAlloc slot below 64 for its index-0 TLS reads\n", - m.name.c_str()); - } else { - m.tls_ga_sites = patch_ga_tls_reads(m, ga_slot); - if (m.tls_ga_sites) m.tls_ga_slot = ga_slot; - RT_LOG_INFO("loader: %s: %zu index-0 TLS reads (gs:[58h]) now read its own TLS (TlsSlots[%lu]); " - "its module TLS index is %u\n", - m.name.c_str(), m.tls_ga_sites, static_cast(ga_slot), index); - } - } - } - try { - install_thread_block(m); - } catch (...) { - ExclusiveTlsLock lock; - m.tls_index = kNoTlsIndex; - m.tls_slot = kNoTlsIndex; - m.tls_generation = 0; - g_tls_slot_generations[slot].store(0); - g_tls_slot_owners[slot].store(nullptr); - throw; - } - // The loading thread's copy is the one the Module records (and ~Loader frees on that thread). - if (g_thread_tls_slots[slot].module == &m && g_thread_tls_slots[slot].generation == m.tls_generation) { - m.tls_block = g_thread_tls_slots[slot].block; - m.tls_saved_block = g_thread_tls_slots[slot].saved; - } - // Threads started from here on get their copy from the helper DLL's DLL_THREAD_ATTACH; the ones already running - // get it now. - install_on_existing_threads(m); -} - -void Loader::install_tls_for_thread(Module& m) { install_thread_block(m); } - -void Loader::uninstall_tls_for_thread(Module& m) { uninstall_thread_block(m); } - -void Loader::run_tls_callbacks(Module& m, uint32_t reason) { run_callbacks(m, reason, /*trace=*/true); } - -void Loader::parse_exports(Module& m) { - auto* nt = at(m.base, reinterpret_cast(m.base)->e_lfanew); - const auto dir = directory(nt, IMAGE_DIRECTORY_ENTRY_EXPORT); - if (!dir.Size) return; - require_range(m.name, dir.VirtualAddress, sizeof(IMAGE_EXPORT_DIRECTORY), m.size, "the export directory"); - auto* ed = at(m.base, dir.VirtualAddress); - require_range(m.name, ed->AddressOfFunctions, static_cast(ed->NumberOfFunctions) * sizeof(uint32_t), m.size, - "the export address table"); - require_range(m.name, ed->AddressOfNames, static_cast(ed->NumberOfNames) * sizeof(uint32_t), m.size, - "the export name table"); - require_range(m.name, ed->AddressOfNameOrdinals, static_cast(ed->NumberOfNames) * sizeof(uint16_t), m.size, - "the export ordinal table"); - auto* funcs = at(m.base, ed->AddressOfFunctions); - auto* names = at(m.base, ed->AddressOfNames); - auto* ords = at(m.base, ed->AddressOfNameOrdinals); - // An export whose RVA lands inside the export directory is a forwarder string ("KERNEL32.Sleep", - // "api-ms-win-core-file-l1-1-0.CreateFileW"), not code. Storing base + that RVA would hand callers a pointer - // into the string, so forwarders are kept apart and followed when an import asks for one. - const uint64_t dir_begin = dir.VirtualAddress, dir_end = dir_begin + dir.Size; - auto add_export = [&](const std::string& key, uint32_t rva) { - if (!rva) return; // An unused address-table slot is absent even when a name refers to it. - if (rva >= dir_begin && rva < dir_end) - m.forwarders[key] = read_string(m.name, m.base, m.size, rva, "a forwarded export"); - else if (rva >= m.size) // base + rva would point past the mapping, and a caller would jump there - throw std::runtime_error(m.name + ": export " + key + " points outside the image"); - else - m.exports[key] = m.base + rva; - }; - for (uint32_t i = 0; i < ed->NumberOfFunctions; ++i) - if (funcs[i]) add_export("#" + std::to_string(ed->Base + i), funcs[i]); - for (uint32_t i = 0; i < ed->NumberOfNames; ++i) { - if (ords[i] >= ed->NumberOfFunctions) - throw std::runtime_error(m.name + ": an export name points past the address table"); - add_export(read_string(m.name, m.base, m.size, names[i], "an export name"), funcs[ords[i]]); - } -} - -// Follows a forwarder string to the module and export it names. Bundled modules are searched first, with or without -// the extension, because a forwarder may point at another mapped module; system DLLs go through LoadLibraryEx, whose -// own GetProcAddress already follows its forwarders. Errors are "not found": the caller decides what to bind. -void* Loader::resolve_forwarder(const std::string& spec, Binding& binding, int depth) { - if (depth >= 8) return nullptr; // a longer chain is a loop between modules, not a re-export - auto dot = spec.rfind('.'); - if (dot == std::string::npos || dot == 0 || dot + 1 >= spec.size()) return nullptr; - const std::string module = spec.substr(0, dot), symbol = spec.substr(dot + 1); - - // A forwarder can name a module the loader shims. Shims take precedence over a bundled or host copy, exactly as - // they do for a direct import in resolve(); without this, a forwarded xmem or d3d12_xs call becomes a failure thunk. - std::string shim_key = lower(module); - if (shim_key.size() < 4 || shim_key.compare(shim_key.size() - 4, 4, ".dll") != 0) shim_key += ".dll"; - if (void* p = shims::find(shim_key, symbol)) { - binding = Binding::Shim; - return p; - } - - const bool by_ordinal = symbol.size() > 1 && symbol[0] == '#'; - uint32_t ordinal = 0; - if (by_ordinal) { - for (size_t i = 1; i < symbol.size(); ++i) { - if (symbol[i] < '0' || symbol[i] > '9') return nullptr; - ordinal = ordinal * 10 + static_cast(symbol[i] - '0'); - if (ordinal > 0xFFFF) return nullptr; // checked after the digit, so "#65537" can't truncate to 1 - } - } - - // shim_key, not the bare module name: forwarder strings usually leave out ".dll" ("MSVCP140.?foo"), and the host - // CRT copies are named with it, so a forwarded CRT symbol must skip the bundled Xbox build as a direct import does. - const std::filesystem::path candidates[] = {game_dir_ / module, game_dir_ / (module + ".dll")}; - for (const auto& candidate : candidates) { - std::error_code ec; - if (prefer_host_copy(shim_key) || !std::filesystem::exists(candidate, ec)) continue; - Module& dep = load(candidate); - if (auto it = dep.exports.find(symbol); it != dep.exports.end()) { - binding = Binding::Module; - return it->second; - } - if (auto it = dep.forwarders.find(symbol); it != dep.forwarders.end()) - return resolve_forwarder(it->second, binding, depth + 1); - return nullptr; // the bundled module exists and does not export it; don't look for a host namesake - } - - HMODULE h = LoadLibraryExA(module.c_str(), nullptr, LOAD_LIBRARY_SEARCH_SYSTEM32); - if (!h) return nullptr; - if (prefer_host_copy(shim_key)) redirect_pc_to_file_header(h); - FARPROC p = GetProcAddress(h, by_ordinal ? MAKEINTRESOURCEA(static_cast(ordinal)) : symbol.c_str()); - if (!p) return nullptr; - if (prefer_host_copy(shim_key)) redirect_pc_to_file_header_at(reinterpret_cast(p)); - binding = Binding::Host; - return reinterpret_cast(p); -} - -bool Loader::resolve_compat(const std::string& key, const std::string& dll, const std::string& name, uint16_t ordinal, - bool by_ordinal, void*& out) { - out = nullptr; - if (compat_dir_.empty() || key.empty() || key.find_first_of("/\\:") != std::string::npos) return false; - HMODULE h = nullptr; - if (auto it = compat_modules_.find(key); it != compat_modules_.end()) { - h = static_cast(it->second); - } else { - const std::filesystem::path candidate = compat_dir_ / std::filesystem::path(dll); - std::error_code ec; - if (!std::filesystem::is_regular_file(candidate, ec)) return false; - // The full path, with the compat folder on the DLL's own search path for its dependencies; never the game - // folder. Windows maps it, so its CRT, TLS and SEH work as for any host DLL. - // A file Windows cannot map (truncated, wrong machine, not a PE image) otherwise raises a modal "Bad Image" - // box and LoadLibraryExW does not return until someone clicks it: a headless run would hang on a failure - // that is reported right below anyway. The mode is this thread's, and goes back as it was. - DWORD previous_mode = 0; - const bool mode_set = SetThreadErrorMode(GetThreadErrorMode() | SEM_FAILCRITICALERRORS, &previous_mode) != 0; - h = LoadLibraryExW(candidate.c_str(), nullptr, LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR | LOAD_LIBRARY_SEARCH_SYSTEM32); - const DWORD load_error = h ? ERROR_SUCCESS : GetLastError(); - if (mode_set) SetThreadErrorMode(previous_mode, nullptr); - if (!h) - throw std::runtime_error("LEONIDA_COMPAT_DIR: " + path_utf8(candidate) + " exists but Windows could not " + - "load it (error " + std::to_string(load_error) + ")"); - compat_modules_.emplace(key, h); - RT_LOG_INFO("compat: %s -> %s\n", dll.c_str(), path_utf8(candidate).c_str()); - } - out = reinterpret_cast(GetProcAddress(h, by_ordinal ? MAKEINTRESOURCEA(ordinal) : name.c_str())); - return true; -} - -void* Loader::resolve(Module& m, const std::string& dll, const std::string& name, uint16_t ordinal, bool by_ordinal) { - std::string key = lower(dll); - std::string sym = by_ordinal ? "#" + std::to_string(ordinal) : name; - - // Opt-in compat modules come first: a DLL the player put in LEONIDA_COMPAT_DIR owns all of its imports, so one - // console module is never served half by a shim and half by the drop-in (they would not share state). - if (void* p = nullptr; resolve_compat(key, dll, name, ordinal, by_ordinal, p)) { - m.imports.push_back({dll, sym, p ? Binding::Host : Binding::Unimplemented}); - return p ? p : shims::make_unimplemented_thunk(dll, sym); - } - - if (void* p = shims::find(key, sym)) { - m.imports.push_back({dll, sym, Binding::Shim}); - return p; - } - // Bundled game module (an Xbox build that ships beside the game)? - auto bundled = game_dir_ / dll; - if (!prefer_host_copy(key) && std::filesystem::exists(bundled)) { - Module& dep = load(bundled); - if (auto it = dep.exports.find(sym); it != dep.exports.end()) { - m.imports.push_back({dll, sym, Binding::Module}); - return it->second; - } - if (auto it = dep.forwarders.find(sym); it != dep.forwarders.end()) { - Binding binding = Binding::Unimplemented; - if (void* p = resolve_forwarder(it->second, binding, 0)) { - m.imports.push_back({dll, sym, binding}); - return p; - } - } - } - // Host Windows: system DLLs and API sets. LOAD_LIBRARY_SEARCH_SYSTEM32 keeps the game folder out of the search. - if (HMODULE h = LoadLibraryExA(dll.c_str(), nullptr, LOAD_LIBRARY_SEARCH_SYSTEM32)) { - if (prefer_host_copy(key)) redirect_pc_to_file_header(h); // before any mapped code can throw through it - FARPROC p = GetProcAddress(h, by_ordinal ? MAKEINTRESOURCEA(ordinal) : name.c_str()); - if (p) { - if (prefer_host_copy(key)) redirect_pc_to_file_header_at(reinterpret_cast(p)); - m.imports.push_back({dll, sym, Binding::Host}); - return reinterpret_cast(p); - } - } - m.imports.push_back({dll, sym, Binding::Unimplemented}); - return shims::make_unimplemented_thunk(dll, sym); -} - -void Loader::bind_imports(Module& m) { - auto* nt = at(m.base, reinterpret_cast(m.base)->e_lfanew); - - // Thunk tables have no length field: they end at a zero entry, so each step is checked against the image. - auto bind_thunks = [&](const std::string& dll, uint64_t lookup_rva, uint64_t iat_rva) { - for (;; lookup_rva += sizeof(IMAGE_THUNK_DATA64), iat_rva += sizeof(IMAGE_THUNK_DATA64)) { - require_range(m.name, lookup_rva, sizeof(IMAGE_THUNK_DATA64), m.size, "an import lookup table"); - require_range(m.name, iat_rva, sizeof(IMAGE_THUNK_DATA64), m.size, "an import address table"); - auto* lookup = at(m.base, static_cast(lookup_rva)); - if (!lookup->u1.AddressOfData) return; - bool by_ord = IMAGE_SNAP_BY_ORDINAL64(lookup->u1.Ordinal); - uint16_t ord = by_ord ? (uint16_t)IMAGE_ORDINAL64(lookup->u1.Ordinal) : 0; - std::string name; - if (!by_ord) { - require_range(m.name, lookup->u1.AddressOfData, sizeof(uint16_t), m.size, "an import name"); - uint32_t hint = static_cast(lookup->u1.AddressOfData); - name = read_string(m.name, m.base, m.size, hint + sizeof(uint16_t), "an import name"); - } - at(m.base, static_cast(iat_rva))->u1.Function = - reinterpret_cast(resolve(m, dll, name, ord, by_ord)); - } - }; - - const auto dir = directory(nt, IMAGE_DIRECTORY_ENTRY_IMPORT); - if (dir.Size) { - for (uint64_t i = 0;; ++i) { - uint64_t rva = dir.VirtualAddress + i * sizeof(IMAGE_IMPORT_DESCRIPTOR); - require_range(m.name, rva, sizeof(IMAGE_IMPORT_DESCRIPTOR), m.size, "the import table"); - auto* d = at(m.base, static_cast(rva)); - if (!d->Name) break; - std::string dll = read_string(m.name, m.base, m.size, d->Name, "an imported DLL name"); - uint32_t lookup = d->OriginalFirstThunk ? d->OriginalFirstThunk : d->FirstThunk; - bind_thunks(dll, lookup, d->FirstThunk); - } - } - // Delay imports are bound eagerly: simpler, and the full import surface shows up in --dry-run. - const auto ddir = directory(nt, IMAGE_DIRECTORY_ENTRY_DELAY_IMPORT); - if (ddir.Size) { - for (uint64_t i = 0;; ++i) { - uint64_t rva = ddir.VirtualAddress + i * sizeof(IMAGE_DELAYLOAD_DESCRIPTOR); - require_range(m.name, rva, sizeof(IMAGE_DELAYLOAD_DESCRIPTOR), m.size, "the delay-import table"); - auto* d = at(m.base, static_cast(rva)); - if (!d->DllNameRVA) break; - // x64 descriptors always carry dlattrRva (0x1). Without it the fields would be 32-bit virtual - // addresses, which cannot express a 64-bit image base, so the descriptor is not usable as written. - if (!d->Attributes.RvaBased) - throw std::runtime_error(m.name + ": a delay-import descriptor without the RVA attribute"); - if (!d->ImportAddressTableRVA) - throw std::runtime_error(m.name + ": a delay-import descriptor has no address table"); - std::string dll = read_string(m.name, m.base, m.size, d->DllNameRVA, "a delay-imported DLL name"); - // Without a name table the IAT still holds delay thunks, not import names, so there is no symbol to bind - // eagerly. Every MSVC delay descriptor and every System32 DLL has one; reject the form instead of reading - // thunk addresses as name RVAs. - if (!d->ImportNameTableRVA) - throw std::runtime_error(m.name + ": a delay-import descriptor has no name table"); - bind_thunks(dll, d->ImportNameTableRVA, d->ImportAddressTableRVA); - } - } -} - -void Loader::protect_sections(Module& m) { - auto* nt = at(m.base, reinterpret_cast(m.base)->e_lfanew); - DWORD old; - VirtualProtect(m.base, nt->OptionalHeader.SizeOfHeaders, PAGE_READONLY, &old); - auto* sec = IMAGE_FIRST_SECTION(nt); - for (unsigned i = 0; i < nt->FileHeader.NumberOfSections; ++i, ++sec) { - bool x = sec->Characteristics & IMAGE_SCN_MEM_EXECUTE, w = sec->Characteristics & IMAGE_SCN_MEM_WRITE; - DWORD prot = x ? (w ? PAGE_EXECUTE_READWRITE : PAGE_EXECUTE_READ) : (w ? PAGE_READWRITE : PAGE_READONLY); - uint64_t size = sec->Misc.VirtualSize ? sec->Misc.VirtualSize : sec->SizeOfRawData; - if (sec->VirtualAddress >= m.size) continue; - size = std::min(size, m.size - sec->VirtualAddress); - if (size) VirtualProtect(m.base + sec->VirtualAddress, static_cast(size), prot, &old); - } - FlushInstructionCache(GetCurrentProcess(), m.base, m.size); -} - -} // namespace rt diff --git a/runtime/src/pe_loader.h b/runtime/src/pe_loader.h deleted file mode 100644 index fda924440..000000000 --- a/runtime/src/pe_loader.h +++ /dev/null @@ -1,187 +0,0 @@ -// Native PE mapper for Xbox Series (x86-64) images. -// Maps an image, applies relocations, binds every import through the shim registry, registers its unwind table and -// installs static TLS for the calling thread. -// Mapping never runs code from the image. Loader::initialise() delivers process attach to TLS callbacks and DllMain; -// ~Loader() delivers process detach before unmapping initialised modules. The TLS slot and template are set up by load(). -// gta6rt_tls_host.dll must sit next to the executable; the loader reuses the module TLS index the OS assigns it. -#pragma once -#include -#include -#include -#include -#include -#include -#include - -namespace rt { - -enum class Binding { Shim, Host, Module, Unimplemented }; - -// No module TLS index has been assigned (matches TLS_OUT_OF_INDEXES without pulling into this header). -inline constexpr uint32_t kNoTlsIndex = 0xFFFFFFFFu; - -struct ImportRecord { - std::string dll; - std::string name; // "#123" for ordinals - Binding binding; -}; - -struct Module { - std::string name; // UTF-8 basename for diagnostics and traces, not a lookup key - std::string narrow_key; // legacy lower-case narrow basename; empty when it cannot round-trip - std::filesystem::path path; - uint8_t* base = nullptr; - uint64_t preferred_base = 0; - uint32_t size = 0; - uint32_t entry_rva = 0; - bool relocated = false; - bool initialised = false; - - // The image's exception directory (.pdata), registered with RtlAddFunctionTable by load() so that exception - // dispatch and stack walks can unwind through its frames. Removed when the loader is destroyed. - void* function_table = nullptr; - uint32_t function_count = 0; - - // Mapped for a run-time LoadLibrary or a GetProcAddress forwarder (a dynamic load), not by a host load() (the - // start-up graph, a static load). DllMain's DLL_PROCESS_ATTACH gets lpvReserved NULL only for a dynamic load. - bool dynamic_load = false; - - std::vector imports; - std::map exports; // by name, plus "#ordinal" - std::map forwarders; // same keys, holding "module.symbol" for re-exports - - // Static TLS (IMAGE_DIRECTORY_ENTRY_TLS). load() installs tls_block in the calling thread and writes tls_index to - // the image's _tls_index. tls_index names TEB->ThreadLocalStoragePointer[tls_index], the array - // __declspec(thread) reads; it is not a TlsAlloc slot. The loader reserves distinct indices by loading - // gta6rt_tls_host.dll (and cloning it on demand for additional simultaneous TLS modules, up to 16 at a time). - // Every thread started after load() gets its own copy through the helper's DLL_THREAD_ATTACH, and gives it back - // at DLL_THREAD_DETACH. A thread that was already running gets its copy from load() itself, as it would from - // Windows for a DLL Windows loads: a block, no DLL_THREAD_ATTACH, and DLL_THREAD_DETACH when it ends. - uint32_t tls_index = kNoTlsIndex; - uint32_t tls_slot = kNoTlsIndex; // index into the loader's reserved TLS-host slot pool - uint64_t tls_generation = 0; // unique token per TLS initialisation, distinguishing reused slots/addresses - void* tls_block = nullptr; // calling thread's copy of the image's template - void* tls_saved_block = nullptr; // helper DLL block replaced in that thread, restored by ~Loader - uint32_t tls_block_size = 0; // raw template + zero fill - const uint8_t* tls_template = nullptr; // raw template in the mapped image - uint32_t tls_raw_size = 0; - uint32_t tls_zero_fill = 0; - // An EXE built with /GA reads its own TLS as ThreadLocalStoragePointer[0] without _tls_index: the process EXE - // always has index 0. Mapped into gta6rt, index 0 belongs to gta6rt.exe, so load() rewrites each such read - // (`mov r64, gs:[58h]`) to `mov r64, gs:[1480h + 8 * tls_ga_slot]`, a TlsAlloc slot (TEB->TlsSlots) whose value in - // each thread is a small array with this image's block at [0] and at [tls_index]. kNoTlsIndex when not patched. - uint32_t tls_ga_slot = kNoTlsIndex; - size_t tls_ga_sites = 0; -}; - -class Loader { -public: - // Also registers the module list with the shim registry, so an unimplemented import called under - // LEONIDA_UNIMPLEMENTED=stop can name the module and RVA of its caller. - explicit Loader(std::filesystem::path game_dir); - Loader(const Loader&) = delete; - Loader& operator=(const Loader&) = delete; - // Delivers process detach to initialised modules in reverse dependency order before freeing any mappings or TLS. - // Restores the TLS slot for the calling thread. Destroy the Loader on the thread that called load() while any - // mapped TLS module is still live; all other threads executing mapped code must have finished first. - ~Loader(); - - // Loads an image and (recursively) the bundled modules it imports. Throws std::runtime_error on failure. - // Static TLS is installed here, before any image code can run; initialise() does not install it again. - Module& load(const std::filesystem::path& image); - - const std::vector& modules() const { return order_; } - - // The mapped module `address` lies in, with its RVA there. Safe from any thread at any time, also while another - // thread is in load(): it is what the shim registry asks for a caller's module (rt::shims::mapped_image_base on - // every C++ throw from a mapped image, and the trace and stop lines), and it reads its own table, not modules(). - bool find_address(uint64_t address, std::string& module, uint32_t& rva) const; - - // The order initialise() runs modules in: each module after every module it imports (a cycle is broken at the - // module that closed it). modules() is mapping order, which puts an importer before its imports. - const std::vector& initialisation_order() const { return init_order_; } - - // Runs each loaded module's TLS callbacks and then its DllMain(DLL_PROCESS_ATTACH), dependencies first. - // Only DLLs get DllMain called: an EXE's entry point is the caller's to run. Throws on a corrupt TLS - // directory, a TLS callback outside its image, or a DllMain that returns FALSE. - // TLS was already installed by load(), so this is safe to call on the loading thread without a second install. - void initialise(); - - // Calls the image's IMAGE_TLS_DIRECTORY64 callbacks in order with (base, reason, nullptr). This is opt-in: - // load() never runs image code; initialise() and ~Loader() use it for process attach/detach. No-op for - // images without TLS callbacks. Once initialise() has run a module, the loader delivers DLL_THREAD_ATTACH and - // DLL_THREAD_DETACH itself on threads started after load(), until ~Loader() starts the process detach; for a - // thread that already existed, install its TLS first, then call this with DLL_THREAD_ATTACH/DETACH, and - // uninstall after the detach callbacks. - void run_tls_callbacks(Module& m, uint32_t reason); - - // Installs/removes this module's template copy in the calling thread's TEB slot. load() does this for its caller - // and for every other thread running at the time, and the thread events for threads started after it, so on any - // of those both are no-ops. They remain for a thread load() could not reach (pe_loader.cpp, "Threads that - // existed before load()", lists the cases): install before mapped code runs there, uninstall before the thread - // exits. Each module's copy sits in its own TEB slot, so one thread can hold copies of several modules. These do - // not run TLS callbacks (use run_tls_callbacks with DLL_THREAD_ATTACH/DETACH for that). - void install_tls_for_thread(Module& m); - void uninstall_tls_for_thread(Module& m); - - // Run-time module lookup/loading used by the library_loader shim for bundled package DLLs. - void* find_loaded_module(const std::string& dll_lower) const; - void* load_runtime_module(const std::string& dll_lower, uint32_t flags, bool& handled); - // The same by the module's native basename (any Unicode name, matched case-insensitively as Windows matches - // module names), for the W entries of LoadLibrary / GetModuleHandle. - void* find_loaded_module_w(const std::wstring& basename) const; - void* load_runtime_module_w(const std::wstring& basename, uint32_t flags, bool& handled); - void* resolve_module_export(void* module_handle, const std::string& sym, bool& owns_handle); - bool owns_module_handle(void* module_handle) const; - -private: - void initialise(Module& m); - static void set_initialised(Module& m, bool value); - Module* find_narrow_module(const std::string& dll_lower) const; // caller holds mutex_ - Module* find_wide_module(const std::wstring& basename) const; // caller holds mutex_ - void* load_runtime_candidate(Module* existing, const std::filesystem::path& candidate, uint32_t flags, - const std::string& display); // caller holds mutex_ - Module& map_image(const std::filesystem::path& path, const std::string& narrow_key); - void initialize_tls(Module& m); - void bind_imports(Module& m); - void* resolve(Module& m, const std::string& dll, const std::string& name, uint16_t ordinal, bool by_ordinal); - // The compat-module step of resolve(): true when `key` (lower-case DLL name) is a file in compat_dir_, which then - // owns every import of that DLL; `out` is the export, or null when the DLL lacks it. Caller holds mutex_. - bool resolve_compat(const std::string& key, const std::string& dll, const std::string& name, uint16_t ordinal, - bool by_ordinal, void*& out); - void* resolve_forwarder(const std::string& spec, Binding& binding, int depth); - void parse_exports(Module& m); - void protect_sections(Module& m); - void register_unwind(Module& m); - - mutable std::recursive_mutex mutex_; - std::filesystem::path game_dir_; - // LEONIDA_COMPAT_DIR, read when the Loader is made; empty = no compat step. Drop-in DLLs named like console - // modules (runtime/README.md, "Compat modules"), loaded by Windows from there and kept for the process lifetime. - std::filesystem::path compat_dir_; - std::map compat_modules_; // lower-case DLL name -> HMODULE - std::map by_name_; // native basename, ASCII case folded - std::vector order_; // mapping order; owns the modules - std::vector init_order_; // dependencies first, see initialisation_order() - int runtime_loads_ = 0; // > 0 while a run-time load or forwarder maps modules (under mutex_): they are dynamic - - // What find_address reads: one entry per mapped image, added once its memory exists. Under ranges_mutex_, a leaf - // lock: mutex_ is held while image code runs and the registry holds its own lock around the lookup, so the - // lookup must not wait for either. - struct MappedRange { - uint64_t base = 0; - uint32_t size = 0; - std::string name; - }; - mutable std::shared_mutex ranges_mutex_; // shared in find_address: lookups on different threads do not queue - std::vector ranges_; -}; - -// Frees the TLS helper clones load() created and deletes their files (Module::tls_index background). load() -// registers this with atexit; a caller that ends with ExitProcess must invoke it directly, because ExitProcess -// skips the atexit table. Call it when no mapped code can run again: it unmaps the helper images. -void cleanup_tls_clones(); - -std::string lower(std::string s); - -} // namespace rt diff --git a/runtime/src/predicate_reduce.comp b/runtime/src/predicate_reduce.comp deleted file mode 100644 index 86b07d67f..000000000 --- a/runtime/src/predicate_reduce.comp +++ /dev/null @@ -1,6 +0,0 @@ -// Synthetic internal shader: one invocation captures a D3D12 64-bit predicate as a Vulkan condition. -#version 450 -layout(local_size_x=1) in; -layout(set=0,binding=0,std430) buffer Words { uint words[]; } data; -layout(push_constant) uniform Index { uint base; } index; -void main() { data.words[index.base+2] = data.words[index.base] | data.words[index.base+1]; } diff --git a/runtime/src/predicate_reduce_spv.h b/runtime/src/predicate_reduce_spv.h deleted file mode 100644 index 2d703597f..000000000 --- a/runtime/src/predicate_reduce_spv.h +++ /dev/null @@ -1,36 +0,0 @@ -// Generated with glslang 16.6.0: -// glslang -V --target-env vulkan1.1 -Os --spirv-val predicate_reduce.comp -o predicate_reduce.spv -#pragma once -#include -namespace leonida { -inline constexpr std::uint32_t predicate_reduce_spirv[] = { - 0x07230203u, 0x00010300u, 0x0008000bu, 0x00000024u, 0x00000000u, 0x00020011u, 0x00000001u, 0x0006000bu, - 0x00000001u, 0x4c534c47u, 0x6474732eu, 0x3035342eu, 0x00000000u, 0x0003000eu, 0x00000000u, 0x00000001u, - 0x0005000fu, 0x00000005u, 0x00000004u, 0x6e69616du, 0x00000000u, 0x00060010u, 0x00000004u, 0x00000011u, - 0x00000001u, 0x00000001u, 0x00000001u, 0x00030003u, 0x00000002u, 0x000001c2u, 0x00040005u, 0x00000004u, - 0x6e69616du, 0x00000000u, 0x00040005u, 0x00000008u, 0x64726f57u, 0x00000073u, 0x00050006u, 0x00000008u, - 0x00000000u, 0x64726f77u, 0x00000073u, 0x00040005u, 0x0000000au, 0x61746164u, 0x00000000u, 0x00040005u, - 0x0000000du, 0x65646e49u, 0x00000078u, 0x00050006u, 0x0000000du, 0x00000000u, 0x65736162u, 0x00000000u, - 0x00040005u, 0x0000000fu, 0x65646e69u, 0x00000078u, 0x00040047u, 0x00000007u, 0x00000006u, 0x00000004u, - 0x00030047u, 0x00000008u, 0x00000002u, 0x00050048u, 0x00000008u, 0x00000000u, 0x00000023u, 0x00000000u, - 0x00040047u, 0x0000000au, 0x00000021u, 0x00000000u, 0x00040047u, 0x0000000au, 0x00000022u, 0x00000000u, - 0x00030047u, 0x0000000du, 0x00000002u, 0x00050048u, 0x0000000du, 0x00000000u, 0x00000023u, 0x00000000u, - 0x00040047u, 0x00000023u, 0x0000000bu, 0x00000019u, 0x00020013u, 0x00000002u, 0x00030021u, 0x00000003u, - 0x00000002u, 0x00040015u, 0x00000006u, 0x00000020u, 0x00000000u, 0x0003001du, 0x00000007u, 0x00000006u, - 0x0003001eu, 0x00000008u, 0x00000007u, 0x00040020u, 0x00000009u, 0x0000000cu, 0x00000008u, 0x0004003bu, - 0x00000009u, 0x0000000au, 0x0000000cu, 0x00040015u, 0x0000000bu, 0x00000020u, 0x00000001u, 0x0004002bu, - 0x0000000bu, 0x0000000cu, 0x00000000u, 0x0003001eu, 0x0000000du, 0x00000006u, 0x00040020u, 0x0000000eu, - 0x00000009u, 0x0000000du, 0x0004003bu, 0x0000000eu, 0x0000000fu, 0x00000009u, 0x00040020u, 0x00000010u, - 0x00000009u, 0x00000006u, 0x0004002bu, 0x00000006u, 0x00000013u, 0x00000002u, 0x00040020u, 0x00000017u, - 0x0000000cu, 0x00000006u, 0x0004002bu, 0x00000006u, 0x0000001cu, 0x00000001u, 0x00040017u, 0x00000022u, - 0x00000006u, 0x00000003u, 0x0006002cu, 0x00000022u, 0x00000023u, 0x0000001cu, 0x0000001cu, 0x0000001cu, - 0x00050036u, 0x00000002u, 0x00000004u, 0x00000000u, 0x00000003u, 0x000200f8u, 0x00000005u, 0x00050041u, - 0x00000010u, 0x00000011u, 0x0000000fu, 0x0000000cu, 0x0004003du, 0x00000006u, 0x00000012u, 0x00000011u, - 0x00050080u, 0x00000006u, 0x00000014u, 0x00000012u, 0x00000013u, 0x00060041u, 0x00000017u, 0x00000018u, - 0x0000000au, 0x0000000cu, 0x00000012u, 0x0004003du, 0x00000006u, 0x00000019u, 0x00000018u, 0x00050080u, - 0x00000006u, 0x0000001du, 0x00000012u, 0x0000001cu, 0x00060041u, 0x00000017u, 0x0000001eu, 0x0000000au, - 0x0000000cu, 0x0000001du, 0x0004003du, 0x00000006u, 0x0000001fu, 0x0000001eu, 0x000500c5u, 0x00000006u, - 0x00000020u, 0x00000019u, 0x0000001fu, 0x00060041u, 0x00000017u, 0x00000021u, 0x0000000au, 0x0000000cu, - 0x00000014u, 0x0003003eu, 0x00000021u, 0x00000020u, 0x000100fdu, 0x00010038u, -}; -} diff --git a/runtime/src/predicated_copy.comp b/runtime/src/predicated_copy.comp deleted file mode 100644 index 0a105554d..000000000 --- a/runtime/src/predicated_copy.comp +++ /dev/null @@ -1,11 +0,0 @@ -// Synthetic byte-granular buffer copy, executed inside the captured conditional-rendering scope. -#version 450 -#extension GL_EXT_shader_8bit_storage : require -layout(local_size_x=64) in; -layout(set=0,binding=0,std430) readonly buffer Source { uint8_t bytes[]; } source; -layout(set=0,binding=1,std430) buffer Destination { uint8_t bytes[]; } destination; -layout(push_constant) uniform Copy { uint source_offset; uint destination_offset; uint size; } copy; -void main() { - uint i=gl_GlobalInvocationID.x; - if(i -namespace leonida { inline constexpr std::uint32_t predicated_copy_spirv[] = { - 0x07230203u, 0x00010500u, 0x0008000bu, 0x00000037u, 0x00000000u, 0x00020011u, 0x00000001u, 0x00020011u, - 0x00001160u, 0x0006000bu, 0x00000001u, 0x4c534c47u, 0x6474732eu, 0x3035342eu, 0x00000000u, 0x0003000eu, - 0x00000000u, 0x00000001u, 0x0009000fu, 0x00000005u, 0x00000004u, 0x6e69616du, 0x00000000u, 0x0000000bu, - 0x00000013u, 0x00000021u, 0x0000002bu, 0x00060010u, 0x00000004u, 0x00000011u, 0x00000040u, 0x00000001u, - 0x00000001u, 0x00030003u, 0x00000002u, 0x000001c2u, 0x00080004u, 0x455f4c47u, 0x735f5458u, 0x65646168u, - 0x62385f72u, 0x735f7469u, 0x61726f74u, 0x00006567u, 0x00040005u, 0x00000004u, 0x6e69616du, 0x00000000u, - 0x00080005u, 0x0000000bu, 0x475f6c67u, 0x61626f6cu, 0x766e496cu, 0x7461636fu, 0x496e6f69u, 0x00000044u, - 0x00040005u, 0x00000011u, 0x79706f43u, 0x00000000u, 0x00070006u, 0x00000011u, 0x00000000u, 0x72756f73u, - 0x6f5f6563u, 0x65736666u, 0x00000074u, 0x00080006u, 0x00000011u, 0x00000001u, 0x74736564u, 0x74616e69u, - 0x5f6e6f69u, 0x7366666fu, 0x00007465u, 0x00050006u, 0x00000011u, 0x00000002u, 0x657a6973u, 0x00000000u, - 0x00040005u, 0x00000013u, 0x79706f63u, 0x00000000u, 0x00050005u, 0x0000001fu, 0x74736544u, 0x74616e69u, - 0x006e6f69u, 0x00050006u, 0x0000001fu, 0x00000000u, 0x65747962u, 0x00000073u, 0x00050005u, 0x00000021u, - 0x74736564u, 0x74616e69u, 0x006e6f69u, 0x00040005u, 0x00000029u, 0x72756f53u, 0x00006563u, 0x00050006u, - 0x00000029u, 0x00000000u, 0x65747962u, 0x00000073u, 0x00040005u, 0x0000002bu, 0x72756f73u, 0x00006563u, - 0x00040047u, 0x0000000bu, 0x0000000bu, 0x0000001cu, 0x00030047u, 0x00000011u, 0x00000002u, 0x00050048u, - 0x00000011u, 0x00000000u, 0x00000023u, 0x00000000u, 0x00050048u, 0x00000011u, 0x00000001u, 0x00000023u, - 0x00000004u, 0x00050048u, 0x00000011u, 0x00000002u, 0x00000023u, 0x00000008u, 0x00040047u, 0x0000001eu, - 0x00000006u, 0x00000001u, 0x00030047u, 0x0000001fu, 0x00000002u, 0x00050048u, 0x0000001fu, 0x00000000u, - 0x00000023u, 0x00000000u, 0x00040047u, 0x00000021u, 0x00000021u, 0x00000001u, 0x00040047u, 0x00000021u, - 0x00000022u, 0x00000000u, 0x00040047u, 0x00000028u, 0x00000006u, 0x00000001u, 0x00030047u, 0x00000029u, - 0x00000002u, 0x00040048u, 0x00000029u, 0x00000000u, 0x00000018u, 0x00050048u, 0x00000029u, 0x00000000u, - 0x00000023u, 0x00000000u, 0x00030047u, 0x0000002bu, 0x00000018u, 0x00040047u, 0x0000002bu, 0x00000021u, - 0x00000000u, 0x00040047u, 0x0000002bu, 0x00000022u, 0x00000000u, 0x00040047u, 0x00000036u, 0x0000000bu, - 0x00000019u, 0x00020013u, 0x00000002u, 0x00030021u, 0x00000003u, 0x00000002u, 0x00040015u, 0x00000006u, - 0x00000020u, 0x00000000u, 0x00040017u, 0x00000009u, 0x00000006u, 0x00000003u, 0x00040020u, 0x0000000au, - 0x00000001u, 0x00000009u, 0x0004003bu, 0x0000000au, 0x0000000bu, 0x00000001u, 0x0004002bu, 0x00000006u, - 0x0000000cu, 0x00000000u, 0x00040020u, 0x0000000du, 0x00000001u, 0x00000006u, 0x0005001eu, 0x00000011u, - 0x00000006u, 0x00000006u, 0x00000006u, 0x00040020u, 0x00000012u, 0x00000009u, 0x00000011u, 0x0004003bu, - 0x00000012u, 0x00000013u, 0x00000009u, 0x00040015u, 0x00000014u, 0x00000020u, 0x00000001u, 0x0004002bu, - 0x00000014u, 0x00000015u, 0x00000002u, 0x00040020u, 0x00000016u, 0x00000009u, 0x00000006u, 0x00020014u, - 0x00000019u, 0x00040015u, 0x0000001du, 0x00000008u, 0x00000000u, 0x0003001du, 0x0000001eu, 0x0000001du, - 0x0003001eu, 0x0000001fu, 0x0000001eu, 0x00040020u, 0x00000020u, 0x0000000cu, 0x0000001fu, 0x0004003bu, - 0x00000020u, 0x00000021u, 0x0000000cu, 0x0004002bu, 0x00000014u, 0x00000022u, 0x00000000u, 0x0004002bu, - 0x00000014u, 0x00000023u, 0x00000001u, 0x0003001du, 0x00000028u, 0x0000001du, 0x0003001eu, 0x00000029u, - 0x00000028u, 0x00040020u, 0x0000002au, 0x0000000cu, 0x00000029u, 0x0004003bu, 0x0000002au, 0x0000002bu, - 0x0000000cu, 0x00040020u, 0x00000030u, 0x0000000cu, 0x0000001du, 0x0004002bu, 0x00000006u, 0x00000034u, - 0x00000040u, 0x0004002bu, 0x00000006u, 0x00000035u, 0x00000001u, 0x0006002cu, 0x00000009u, 0x00000036u, - 0x00000034u, 0x00000035u, 0x00000035u, 0x00050036u, 0x00000002u, 0x00000004u, 0x00000000u, 0x00000003u, - 0x000200f8u, 0x00000005u, 0x00050041u, 0x0000000du, 0x0000000eu, 0x0000000bu, 0x0000000cu, 0x0004003du, - 0x00000006u, 0x0000000fu, 0x0000000eu, 0x00050041u, 0x00000016u, 0x00000017u, 0x00000013u, 0x00000015u, - 0x0004003du, 0x00000006u, 0x00000018u, 0x00000017u, 0x000500b0u, 0x00000019u, 0x0000001au, 0x0000000fu, - 0x00000018u, 0x000300f7u, 0x0000001cu, 0x00000000u, 0x000400fau, 0x0000001au, 0x0000001bu, 0x0000001cu, - 0x000200f8u, 0x0000001bu, 0x00050041u, 0x00000016u, 0x00000024u, 0x00000013u, 0x00000023u, 0x0004003du, - 0x00000006u, 0x00000025u, 0x00000024u, 0x00050080u, 0x00000006u, 0x00000027u, 0x00000025u, 0x0000000fu, - 0x00050041u, 0x00000016u, 0x0000002cu, 0x00000013u, 0x00000022u, 0x0004003du, 0x00000006u, 0x0000002du, - 0x0000002cu, 0x00050080u, 0x00000006u, 0x0000002fu, 0x0000002du, 0x0000000fu, 0x00060041u, 0x00000030u, - 0x00000031u, 0x0000002bu, 0x00000022u, 0x0000002fu, 0x0004003du, 0x0000001du, 0x00000032u, 0x00000031u, - 0x00060041u, 0x00000030u, 0x00000033u, 0x00000021u, 0x00000022u, 0x00000027u, 0x0003003eu, 0x00000033u, - 0x00000032u, 0x000200f9u, 0x0000001cu, 0x000200f8u, 0x0000001cu, 0x000100fdu, 0x00010038u, -}; } diff --git a/runtime/src/present_compose.comp b/runtime/src/present_compose.comp deleted file mode 100644 index ff3b0a0c0..000000000 --- a/runtime/src/present_compose.comp +++ /dev/null @@ -1,150 +0,0 @@ -// PresentX plane composition (docs/d3d12_vulkan.md section 4.5): one or two planes, each scaled from a source rectangle to -// a destination rectangle of the output, plane 1 blended over plane 0, written to an RGBA16F image the presenter then -// copies to the swapchain. present_compose_spv.h is this file compiled with -// `glslc --target-env=vulkan1.1 -O -mfmt=c` (see the header for the command); keep them together. -// -// Every plane is read with texelFetch (no sampler: the filtering is done here, so it works on any sampled format and -// only reads texels inside the source rectangle). Values are the encoded ones of the plane's colour space: SDR planes -// hold sRGB or G2.2 values (push constant sdr_eotf), HDR10 planes hold ST.2084 (PQ) Rec.2020 values. An sRGB-format -// source is decoded by the texture unit, so it is encoded again first and its bytes are read as they went in. -// -// Filtering and blending happen in linear light, premultiplied (docs section 4.5): every texel is decoded to linear before -// it is weighted (SDR: the EOTF, 1.0 = SDR white, Rec.709; HDR10: PQ to nits, Rec.2020). The filtered plane is converted to -// the working space of the output (HDR10 output: linear Rec.2020 nits, SDR white = sdr_white nits; SDR output: linear -// Rec.709, 1.0 = SDR white), plane 1 is blended over plane 0 there, and the sum is encoded once (PQ, or the inverse of -// the SDR EOTF). HDR10 plane -> SDR output: a luminance shoulder (identity below 0.8 of SDR white, extended Reinhard above, peak at -// hdr_peak nits mapped to 1.0), then clipped per channel (no gamut mapping). -#version 450 -#extension GL_EXT_samplerless_texture_functions : require - -layout(local_size_x = 8, local_size_y = 8, local_size_z = 1) in; - -layout(set = 0, binding = 0) uniform texture2D plane0; -layout(set = 0, binding = 1) uniform texture2D plane1; -layout(set = 0, binding = 2, rgba16f) uniform writeonly image2D out_image; - -const uint flag_point = 1u; -const uint flag_srgb_source = 2u; -const uint flag_hdr10 = 4u; -const uint flag_straight_alpha = 8u; -const uint flag_opaque = 16u; // set here for plane 0: its alpha is ignored - -layout(push_constant) uniform Push { - vec4 dest0; // destination rectangle in output pixels: left, top, right, bottom - vec4 dest1; - vec4 src0; // source rectangle in texels - vec4 src1; - uint flags0; - uint flags1; - uint plane_count; - uint out_hdr; // 1: the output holds PQ Rec.2020 values - float sdr_white; // nits of SDR white, for the conversions - uint width, height; - uint sdr_eotf; // 0: piecewise sRGB, 1: gamma 2.2 - float hdr_peak; // nits of the HDR10 content's peak, the tone mapper's white point - uint pad0, pad1, pad2; -} pc; - -vec3 srgb_encode(vec3 c) { - c = clamp(c, 0.0, 1.0); - return mix(c * 12.92, 1.055 * pow(c, vec3(1.0 / 2.4)) - 0.055, greaterThan(c, vec3(0.0031308))); -} - -vec3 srgb_decode(vec3 e) { - e = max(e, 0.0); - return mix(e / 12.92, pow((e + 0.055) / 1.055, vec3(2.4)), greaterThan(e, vec3(0.04045))); -} - -// SDR encoded -> linear (1.0 = SDR white; may exceed 1 for additive premultiplied colour), and back (clipped to 0..1). -vec3 sdr_decode(vec3 e) { return pc.sdr_eotf == 1u ? pow(max(e, 0.0), vec3(2.2)) : srgb_decode(e); } -vec3 sdr_encode(vec3 l) { return pc.sdr_eotf == 1u ? pow(clamp(l, 0.0, 1.0), vec3(1.0 / 2.2)) : srgb_encode(l); } - -const float m1 = 0.1593017578125, m2 = 78.84375, c1 = 0.8359375, c2 = 18.8515625, c3 = 18.6875; - -vec3 pq_to_nits(vec3 e) { - vec3 ep = pow(clamp(e, 0.0, 1.0), vec3(1.0 / m2)); - return 10000.0 * pow(max(ep - c1, 0.0) / (c2 - c3 * ep), vec3(1.0 / m1)); -} - -vec3 nits_to_pq(vec3 nits) { - vec3 y = pow(clamp(nits / 10000.0, 0.0, 1.0), vec3(m1)); - return pow((c1 + c2 * y) / (1.0 + c3 * y), vec3(m2)); -} - -// One texel as linear premultiplied colour (plane space) and its alpha. Premultiplied data is divided by alpha for the -// decode (the curve applies to the colour, not to colour times alpha) and multiplied again after. -vec4 fetch_texel(texture2D t, ivec2 i, uint flags) { - vec4 c = texelFetch(t, i, 0); - bool opaque = (flags & flag_opaque) != 0u; - float a = opaque ? 1.0 : clamp(c.a, 0.0, 1.0); - vec3 e = (flags & flag_srgb_source) != 0u ? srgb_encode(c.rgb) : c.rgb; - if (!opaque && (flags & flag_straight_alpha) == 0u) e = a > 0.0 ? e / a : vec3(0.0); - vec3 lin = (flags & flag_hdr10) != 0u ? pq_to_nits(e) : sdr_decode(e); - return vec4(lin * a, a); -} - -// The plane's linear premultiplied value at output pixel `pixel` (its centre), in the plane's own space. -vec4 fetch_plane(texture2D t, vec4 dest, vec4 src, uint flags, ivec2 pixel) { - vec2 p = (vec2(pixel) + 0.5 - dest.xy) / (dest.zw - dest.xy); // 0..1 across the destination rectangle - vec2 s = src.xy + p * (src.zw - src.xy); // continuous texel coordinates - vec2 lo = src.xy, hi = src.zw - 1.0; - if ((flags & flag_point) != 0u) return fetch_texel(t, ivec2(clamp(floor(s), lo, hi)), flags); - vec2 f = clamp(s - 0.5, lo, hi); // the texel whose centre is at or before the sample, clamped inside the rectangle - vec2 base = floor(f), w = f - base; - ivec2 i0 = ivec2(base), i1 = ivec2(min(base + 1.0, hi)); - return mix(mix(fetch_texel(t, ivec2(i0.x, i0.y), flags), fetch_texel(t, ivec2(i1.x, i0.y), flags), w.x), - mix(fetch_texel(t, ivec2(i0.x, i1.y), flags), fetch_texel(t, ivec2(i1.x, i1.y), flags), w.x), w.y); -} - -vec3 bt709_to_bt2020(vec3 v) { - return vec3(dot(vec3(0.627404, 0.329283, 0.043313), v), dot(vec3(0.069097, 0.919540, 0.011362), v), - dot(vec3(0.016391, 0.088013, 0.895595), v)); -} - -vec3 bt2020_to_bt709(vec3 v) { - return vec3(dot(vec3(1.660491, -0.587641, -0.072850), v), dot(vec3(-0.124550, 1.132900, -0.008349), v), - dot(vec3(-0.018151, -0.100579, 1.118730), v)); -} - -// Tone map: a shoulder on luminance. Identity up to the knee (0.8 of SDR white), then extended Reinhard (Reinhard et al. -// 2002, eq. 4) on the excess, scaled to be continuous in value and slope at the knee and to map the content peak to 1.0: -// with t = 1 - knee, u = (Y - knee) / t, w = (Lw - knee) / t: Yd = knee + t u (1 + u / w^2) / (1 + u). The colour is scaled -// by Yd / Y. `v`: linear Rec.709, 1.0 = SDR white; Lw = hdr_peak / sdr_white (at least 1). -vec3 tone_map(vec3 v) { - const float knee = 0.8; - float y = dot(v, vec3(0.2126, 0.7152, 0.0722)); - if (y <= knee) return v; - float t = 1.0 - knee; - float w = (max(pc.hdr_peak / pc.sdr_white, 1.0) - knee) / t; - float u = (y - knee) / t; - return v * ((knee + t * u * (1.0 + u / (w * w)) / (1.0 + u)) / y); -} - -// A linear premultiplied colour of alpha `a` from the plane's space to the output's working space. Both conversions are -// linear except the tone map, which needs the unassociated colour. -vec3 to_working(vec3 lin, float a, bool plane_hdr) { - bool out_hdr = pc.out_hdr != 0u; - if (plane_hdr == out_hdr) return lin; - if (!plane_hdr) return bt709_to_bt2020(lin) * pc.sdr_white; - if (a <= 0.0) return vec3(0.0); - return tone_map(max(bt2020_to_bt709(lin / a) / pc.sdr_white, 0.0)) * a; -} - -vec3 encode_output(vec3 w) { return pc.out_hdr != 0u ? nits_to_pq(max(w, 0.0)) : sdr_encode(w); } - -void main() { - ivec2 pixel = ivec2(gl_GlobalInvocationID.xy); - if (pixel.x >= int(pc.width) || pixel.y >= int(pc.height)) return; - vec2 centre = vec2(pixel) + 0.5; - - vec3 base = vec3(0.0); // outside plane 0's rectangle: black - if (all(greaterThanEqual(centre, pc.dest0.xy)) && all(lessThan(centre, pc.dest0.zw))) { - vec4 c = fetch_plane(plane0, pc.dest0, pc.src0, pc.flags0 | flag_opaque, pixel); - base = to_working(c.rgb, 1.0, (pc.flags0 & flag_hdr10) != 0u); - } - if (pc.plane_count > 1u && all(greaterThanEqual(centre, pc.dest1.xy)) && all(lessThan(centre, pc.dest1.zw))) { - vec4 c = fetch_plane(plane1, pc.dest1, pc.src1, pc.flags1, pixel); - base = to_working(c.rgb, c.a, (pc.flags1 & flag_hdr10) != 0u) + (1.0 - c.a) * base; - } - imageStore(out_image, pixel, vec4(encode_output(base), 1.0)); -} diff --git a/runtime/src/present_compose.inc b/runtime/src/present_compose.inc deleted file mode 100644 index 92ddfcb0b..000000000 --- a/runtime/src/present_compose.inc +++ /dev/null @@ -1,1523 +0,0 @@ -{0x07230203,0x00010300,0x000d000b,0x00000bb3, -0x00000000,0x00020011,0x00000001,0x0006000b, -0x00000001,0x4c534c47,0x6474732e,0x3035342e, -0x00000000,0x0003000e,0x00000000,0x00000001, -0x0006000f,0x00000005,0x00000004,0x6e69616d, -0x00000000,0x00000251,0x00060010,0x00000004, -0x00000011,0x00000008,0x00000008,0x00000001, -0x00030047,0x00000077,0x00000002,0x00050048, -0x00000077,0x00000000,0x00000023,0x00000000, -0x00050048,0x00000077,0x00000001,0x00000023, -0x00000010,0x00050048,0x00000077,0x00000002, -0x00000023,0x00000020,0x00050048,0x00000077, -0x00000003,0x00000023,0x00000030,0x00050048, -0x00000077,0x00000004,0x00000023,0x00000040, -0x00050048,0x00000077,0x00000005,0x00000023, -0x00000044,0x00050048,0x00000077,0x00000006, -0x00000023,0x00000048,0x00050048,0x00000077, -0x00000007,0x00000023,0x0000004c,0x00050048, -0x00000077,0x00000008,0x00000023,0x00000050, -0x00050048,0x00000077,0x00000009,0x00000023, -0x00000054,0x00050048,0x00000077,0x0000000a, -0x00000023,0x00000058,0x00050048,0x00000077, -0x0000000b,0x00000023,0x0000005c,0x00050048, -0x00000077,0x0000000c,0x00000023,0x00000060, -0x00050048,0x00000077,0x0000000d,0x00000023, -0x00000064,0x00050048,0x00000077,0x0000000e, -0x00000023,0x00000068,0x00050048,0x00000077, -0x0000000f,0x00000023,0x0000006c,0x00040047, -0x00000251,0x0000000b,0x0000001c,0x00040047, -0x00000285,0x00000021,0x00000000,0x00040047, -0x00000285,0x00000022,0x00000000,0x00040047, -0x000002b9,0x00000021,0x00000001,0x00040047, -0x000002b9,0x00000022,0x00000000,0x00030047, -0x000002dc,0x00000019,0x00040047,0x000002dc, -0x00000021,0x00000002,0x00040047,0x000002dc, -0x00000022,0x00000000,0x00040047,0x000002e6, -0x0000000b,0x00000019,0x00020013,0x00000002, -0x00030021,0x00000003,0x00000002,0x00030016, -0x00000006,0x00000020,0x00040017,0x00000007, -0x00000006,0x00000003,0x00090019,0x0000001c, -0x00000006,0x00000001,0x00000000,0x00000000, -0x00000000,0x00000001,0x00000000,0x00040020, -0x0000001d,0x00000000,0x0000001c,0x00040015, -0x0000001e,0x00000020,0x00000001,0x00040017, -0x0000001f,0x0000001e,0x00000002,0x00040015, -0x00000021,0x00000020,0x00000000,0x00040017, -0x00000023,0x00000006,0x00000004,0x00020014, -0x0000003d,0x0004002b,0x00000006,0x00000049, -0x00000000,0x0004002b,0x00000006,0x0000004a, -0x3f800000,0x0004002b,0x00000006,0x0000004f, -0x414eb852,0x0004002b,0x00000006,0x00000051, -0x3f870a3d,0x0004002b,0x00000006,0x00000053, -0x3ed55555,0x0006002c,0x00000007,0x00000054, -0x00000053,0x00000053,0x00000053,0x0004002b, -0x00000006,0x00000057,0x3d6147ae,0x0004002b, -0x00000006,0x0000005b,0x3b4d2e1c,0x0006002c, -0x00000007,0x0000005c,0x0000005b,0x0000005b, -0x0000005b,0x00040017,0x0000005d,0x0000003d, -0x00000003,0x0004002b,0x00000006,0x0000006d, -0x4019999a,0x0006002c,0x00000007,0x0000006e, -0x0000006d,0x0000006d,0x0000006d,0x0004002b, -0x00000006,0x00000071,0x3d25aee6,0x0006002c, -0x00000007,0x00000072,0x00000071,0x00000071, -0x00000071,0x0012001e,0x00000077,0x00000023, -0x00000023,0x00000023,0x00000023,0x00000021, -0x00000021,0x00000021,0x00000021,0x00000006, -0x00000021,0x00000021,0x00000021,0x00000006, -0x00000021,0x00000021,0x00000021,0x00040020, -0x00000078,0x00000009,0x00000077,0x0004003b, -0x00000078,0x00000079,0x00000009,0x0004002b, -0x0000001e,0x0000007a,0x0000000b,0x00040020, -0x0000007b,0x00000009,0x00000021,0x0004002b, -0x00000021,0x0000007e,0x00000001,0x0004002b, -0x00000006,0x00000086,0x400ccccd,0x0006002c, -0x00000007,0x00000087,0x00000086,0x00000086, -0x00000086,0x0004002b,0x00000006,0x0000009a, -0x3ee8ba2f,0x0006002c,0x00000007,0x0000009b, -0x0000009a,0x0000009a,0x0000009a,0x0004002b, -0x00000006,0x000000a9,0x3c4fcdac,0x0006002c, -0x00000007,0x000000aa,0x000000a9,0x000000a9, -0x000000a9,0x0004002b,0x00000006,0x000000ac, -0x461c4000,0x0004002b,0x00000006,0x000000ae, -0x3f560000,0x0004002b,0x00000006,0x000000b3, -0x4196d000,0x0004002b,0x00000006,0x000000b4, -0x41958000,0x0004002b,0x00000006,0x000000ba, -0x40c8e06b,0x0006002c,0x00000007,0x000000bb, -0x000000ba,0x000000ba,0x000000ba,0x0004002b, -0x00000006,0x000000c7,0x3e232000,0x0006002c, -0x00000007,0x000000c8,0x000000c7,0x000000c7, -0x000000c7,0x0004002b,0x00000006,0x000000d3, -0x429db000,0x0006002c,0x00000007,0x000000d4, -0x000000d3,0x000000d3,0x000000d3,0x0004002b, -0x0000001e,0x000000db,0x00000000,0x0004002b, -0x00000021,0x000000df,0x00000010,0x0004002b, -0x00000021,0x000000e1,0x00000000,0x0004002b, -0x00000021,0x000000f0,0x00000002,0x0004002b, -0x00000021,0x00000103,0x00000008,0x0006002c, -0x00000007,0x00000113,0x00000049,0x00000049, -0x00000049,0x0004002b,0x00000021,0x00000117, -0x00000004,0x00040017,0x0000012f,0x00000006, -0x00000002,0x0004002b,0x00000006,0x00000134, -0x3f000000,0x0004002b,0x00000006,0x000001ae, -0x3f209d8c,0x0004002b,0x00000006,0x000001af, -0x3ea897c8,0x0004002b,0x00000006,0x000001b0, -0x3d3168f9,0x0006002c,0x00000007,0x000001b1, -0x000001ae,0x000001af,0x000001b0,0x0004002b, -0x00000006,0x000001b4,0x3d8d82ba,0x0004002b, -0x00000006,0x000001b5,0x3f6b66f9,0x0004002b, -0x00000006,0x000001b6,0x3c3a27af,0x0006002c, -0x00000007,0x000001b7,0x000001b4,0x000001b5, -0x000001b6,0x0004002b,0x00000006,0x000001ba, -0x3c86466b,0x0004002b,0x00000006,0x000001bb, -0x3db44029,0x0004002b,0x00000006,0x000001bc, -0x3f6545b7,0x0006002c,0x00000007,0x000001bd, -0x000001ba,0x000001bb,0x000001bc,0x0004002b, -0x00000006,0x000001c3,0x3fd48af8,0x0004002b, -0x00000006,0x000001c4,0xbf166fa4,0x0004002b, -0x00000006,0x000001c5,0xbd953261,0x0006002c, -0x00000007,0x000001c6,0x000001c3,0x000001c4, -0x000001c5,0x0004002b,0x00000006,0x000001c9, -0xbdff1412,0x0004002b,0x00000006,0x000001ca, -0x3f9102de,0x0004002b,0x00000006,0x000001cb, -0xbc08ca3e,0x0006002c,0x00000007,0x000001cc, -0x000001c9,0x000001ca,0x000001cb,0x0004002b, -0x00000006,0x000001cf,0xbc94b168,0x0004002b, -0x00000006,0x000001d0,0xbdcdfc5d,0x0004002b, -0x00000006,0x000001d1,0x3f8f328b,0x0006002c, -0x00000007,0x000001d2,0x000001cf,0x000001d0, -0x000001d1,0x0004002b,0x00000006,0x000001da, -0x3e59b3d0,0x0004002b,0x00000006,0x000001db, -0x3f371759,0x0004002b,0x00000006,0x000001dc, -0x3d93dd98,0x0006002c,0x00000007,0x000001dd, -0x000001da,0x000001db,0x000001dc,0x0004002b, -0x00000006,0x000001e0,0x3f4ccccd,0x0004002b, -0x0000001e,0x000001e9,0x0000000c,0x00040020, -0x000001ea,0x00000009,0x00000006,0x0004002b, -0x0000001e,0x000001ed,0x00000008,0x0004002b, -0x0000001e,0x0000020f,0x00000007,0x00040017, -0x0000024f,0x00000021,0x00000003,0x00040020, -0x00000250,0x00000001,0x0000024f,0x0004003b, -0x00000250,0x00000251,0x00000001,0x00040017, -0x00000252,0x00000021,0x00000002,0x0004002b, -0x0000001e,0x00000258,0x00000009,0x0004002b, -0x0000001e,0x00000262,0x0000000a,0x00040020, -0x00000272,0x00000009,0x00000023,0x00040017, -0x00000276,0x0000003d,0x00000002,0x0004003b, -0x0000001d,0x00000285,0x00000000,0x0004002b, -0x0000001e,0x00000286,0x00000002,0x0004002b, -0x0000001e,0x00000287,0x00000004,0x0004002b, -0x0000001e,0x0000029f,0x00000006,0x0004002b, -0x0000001e,0x000002a6,0x00000001,0x0004003b, -0x0000001d,0x000002b9,0x00000000,0x0004002b, -0x0000001e,0x000002ba,0x00000003,0x0004002b, -0x0000001e,0x000002bb,0x00000005,0x00090019, -0x000002da,0x00000006,0x00000001,0x00000000, -0x00000000,0x00000000,0x00000002,0x00000002, -0x00040020,0x000002db,0x00000000,0x000002da, -0x0004003b,0x000002db,0x000002dc,0x00000000, -0x0006002c,0x0000024f,0x000002e6,0x00000103, -0x00000103,0x0000007e,0x0005002c,0x0000012f, -0x00000b94,0x00000134,0x00000134,0x0005002c, -0x0000012f,0x00000b95,0x0000004a,0x0000004a, -0x0006002c,0x00000007,0x00000b97,0x0000004a, -0x0000004a,0x0000004a,0x0006002c,0x00000007, -0x00000b98,0x000000ae,0x000000ae,0x000000ae, -0x0006002c,0x00000007,0x00000b9b,0x00000057, -0x00000057,0x00000057,0x0003002a,0x0000003d, -0x00000b9f,0x0006002c,0x00000007,0x00000ba1, -0x000000b3,0x000000b3,0x000000b3,0x00030029, -0x0000003d,0x00000ba4,0x0004002b,0x00000006, -0x00000ba5,0x3d9e8391,0x0006002c,0x00000007, -0x00000ba6,0x00000ba5,0x00000ba5,0x00000ba5, -0x0004002b,0x00000006,0x00000ba7,0x3f72a76f, -0x0006002c,0x00000007,0x00000ba8,0x00000ba7, -0x00000ba7,0x00000ba7,0x0004002b,0x00000006, -0x00000ba9,0x40a00000,0x0004002b,0x00000006, -0x00000bad,0x3e4ccccc,0x0004002b,0x00000006, -0x00000bb1,0x38d1b717,0x0006002c,0x00000007, -0x00000bb2,0x00000bb1,0x00000bb1,0x00000bb1, -0x00050036,0x00000002,0x00000004,0x00000000, -0x00000003,0x000200f8,0x00000005,0x000300f7, -0x000002e7,0x00000000,0x000300fb,0x000000e1, -0x000002e8,0x000200f8,0x000002e8,0x0004003d, -0x0000024f,0x00000253,0x00000251,0x0007004f, -0x00000252,0x00000254,0x00000253,0x00000253, -0x00000000,0x00000001,0x0004007c,0x0000001f, -0x00000255,0x00000254,0x00050051,0x0000001e, -0x00000257,0x00000255,0x00000000,0x00050041, -0x0000007b,0x00000259,0x00000079,0x00000258, -0x0004003d,0x00000021,0x0000025a,0x00000259, -0x0004007c,0x0000001e,0x0000025b,0x0000025a, -0x000500af,0x0000003d,0x0000025c,0x00000257, -0x0000025b,0x000400a8,0x0000003d,0x0000025d, -0x0000025c,0x000300f7,0x0000025f,0x00000000, -0x000400fa,0x0000025d,0x0000025e,0x0000025f, -0x000200f8,0x0000025e,0x00050051,0x0000001e, -0x00000261,0x00000255,0x00000001,0x00050041, -0x0000007b,0x00000263,0x00000079,0x00000262, -0x0004003d,0x00000021,0x00000264,0x00000263, -0x0004007c,0x0000001e,0x00000265,0x00000264, -0x000500af,0x0000003d,0x00000266,0x00000261, -0x00000265,0x000200f9,0x0000025f,0x000200f8, -0x0000025f,0x000700f5,0x0000003d,0x00000267, -0x0000025c,0x000002e8,0x00000266,0x0000025e, -0x000300f7,0x00000269,0x00000000,0x000400fa, -0x00000267,0x00000268,0x00000269,0x000200f8, -0x00000268,0x000200f9,0x000002e7,0x000200f8, -0x00000269,0x0004006f,0x0000012f,0x0000026d, -0x00000255,0x00050081,0x0000012f,0x0000026f, -0x0000026d,0x00000b94,0x00050041,0x00000272, -0x00000273,0x00000079,0x000000db,0x0004003d, -0x00000023,0x00000274,0x00000273,0x0007004f, -0x0000012f,0x00000275,0x00000274,0x00000274, -0x00000000,0x00000001,0x000500be,0x00000276, -0x00000277,0x0000026f,0x00000275,0x0004009b, -0x0000003d,0x00000278,0x00000277,0x000300f7, -0x0000027a,0x00000000,0x000400fa,0x00000278, -0x00000279,0x0000027a,0x000200f8,0x00000279, -0x0007004f,0x0000012f,0x0000027e,0x00000274, -0x00000274,0x00000002,0x00000003,0x000500b8, -0x00000276,0x0000027f,0x0000026f,0x0000027e, -0x0004009b,0x0000003d,0x00000280,0x0000027f, -0x000200f9,0x0000027a,0x000200f8,0x0000027a, -0x000700f5,0x0000003d,0x00000281,0x00000278, -0x00000269,0x00000280,0x00000279,0x000300f7, -0x00000283,0x00000000,0x000400fa,0x00000281, -0x00000282,0x00000283,0x000200f8,0x00000282, -0x00050041,0x0000007b,0x00000288,0x00000079, -0x00000287,0x0004003d,0x00000021,0x00000289, -0x00000288,0x00050041,0x00000272,0x0000028f, -0x00000079,0x00000286,0x0004003d,0x00000023, -0x00000290,0x0000028f,0x000300f7,0x00000378, -0x00000000,0x000300fb,0x000000e1,0x00000312, -0x000200f8,0x00000312,0x00050083,0x0000012f, -0x00000319,0x0000026f,0x00000275,0x0007004f, -0x0000012f,0x0000031b,0x00000274,0x00000274, -0x00000002,0x00000003,0x00050083,0x0000012f, -0x0000031e,0x0000031b,0x00000275,0x00050088, -0x0000012f,0x0000031f,0x00000319,0x0000031e, -0x0007004f,0x0000012f,0x00000321,0x00000290, -0x00000290,0x00000000,0x00000001,0x0007004f, -0x0000012f,0x00000324,0x00000290,0x00000290, -0x00000002,0x00000003,0x00050083,0x0000012f, -0x00000327,0x00000324,0x00000321,0x00050085, -0x0000012f,0x00000328,0x0000031f,0x00000327, -0x00050081,0x0000012f,0x00000329,0x00000321, -0x00000328,0x00050083,0x0000012f,0x0000032f, -0x00000324,0x00000b95,0x000500c7,0x00000021, -0x00000331,0x00000289,0x0000007e,0x000500ab, -0x0000003d,0x00000332,0x00000331,0x000000e1, -0x000300f7,0x0000033c,0x00000000,0x000400fa, -0x00000332,0x00000333,0x0000033c,0x000200f8, -0x00000333,0x0006000c,0x0000012f,0x00000335, -0x00000001,0x00000008,0x00000329,0x0008000c, -0x0000012f,0x00000338,0x00000001,0x0000002b, -0x00000335,0x00000321,0x0000032f,0x0004006e, -0x0000001f,0x00000339,0x00000338,0x0004003d, -0x0000001c,0x00000388,0x00000285,0x0007005f, -0x00000023,0x0000038a,0x00000388,0x00000339, -0x00000002,0x000000db,0x000500c7,0x00000021, -0x00000397,0x00000289,0x000000f0,0x000500ab, -0x0000003d,0x00000398,0x00000397,0x000000e1, -0x000300f7,0x000003a0,0x00000000,0x000400fa, -0x00000398,0x00000399,0x0000039d,0x000200f8, -0x0000039d,0x0008004f,0x00000007,0x0000039f, -0x0000038a,0x0000038a,0x00000000,0x00000001, -0x00000002,0x000200f9,0x000003a0,0x000200f8, -0x00000399,0x0008004f,0x00000007,0x0000039b, -0x0000038a,0x0000038a,0x00000000,0x00000001, -0x00000002,0x0008000c,0x00000007,0x000003ce, -0x00000001,0x0000002b,0x0000039b,0x00000113, -0x00000b97,0x0005008e,0x00000007,0x000003d0, -0x000003ce,0x0000004f,0x0007000c,0x00000007, -0x000003d2,0x00000001,0x0000001a,0x000003ce, -0x00000054,0x0005008e,0x00000007,0x000003d3, -0x000003d2,0x00000051,0x00050083,0x00000007, -0x000003d5,0x000003d3,0x00000b9b,0x000500ba, -0x0000005d,0x000003d7,0x000003ce,0x0000005c, -0x000600a9,0x00000007,0x000003d8,0x000003d7, -0x000003d5,0x000003d0,0x000200f9,0x000003a0, -0x000200f8,0x000003a0,0x000700f5,0x00000007, -0x00000b38,0x000003d8,0x00000399,0x0000039f, -0x0000039d,0x000500c7,0x00000021,0x000003b7, -0x00000289,0x00000117,0x000500ab,0x0000003d, -0x000003b8,0x000003b7,0x000000e1,0x000300f7, -0x000003bf,0x00000000,0x000400fa,0x000003b8, -0x000003b9,0x000003bc,0x000200f8,0x000003bc, -0x00050041,0x0000007b,0x000003f1,0x00000079, -0x0000007a,0x0004003d,0x00000021,0x000003f2, -0x000003f1,0x000500aa,0x0000003d,0x000003f3, -0x000003f2,0x0000007e,0x000300f7,0x000003fc, -0x00000000,0x000400fa,0x000003f3,0x000003f4, -0x000003f9,0x000200f8,0x000003f9,0x0007000c, -0x00000007,0x00000402,0x00000001,0x00000028, -0x00000b38,0x00000113,0x00050085,0x00000007, -0x00000405,0x00000402,0x00000ba6,0x00050081, -0x00000007,0x00000408,0x00000402,0x00000b9b, -0x00050085,0x00000007,0x0000040a,0x00000408, -0x00000ba8,0x0007000c,0x00000007,0x0000040b, -0x00000001,0x0000001a,0x0000040a,0x0000006e, -0x000500ba,0x0000005d,0x0000040d,0x00000402, -0x00000072,0x000600a9,0x00000007,0x0000040e, -0x0000040d,0x0000040b,0x00000405,0x000200f9, -0x000003fc,0x000200f8,0x000003f4,0x0007000c, -0x00000007,0x000003f7,0x00000001,0x00000028, -0x00000b38,0x00000113,0x0007000c,0x00000007, -0x000003f8,0x00000001,0x0000001a,0x000003f7, -0x00000087,0x000200f9,0x000003fc,0x000200f8, -0x000003fc,0x000700f5,0x00000007,0x00000b3c, -0x000003f8,0x000003f4,0x0000040e,0x000003f9, -0x000200f9,0x000003bf,0x000200f8,0x000003b9, -0x0008000c,0x00000007,0x000003df,0x00000001, -0x0000002b,0x00000b38,0x00000113,0x00000b97, -0x0007000c,0x00000007,0x000003e0,0x00000001, -0x0000001a,0x000003df,0x000000aa,0x00050083, -0x00000007,0x000003e3,0x000003e0,0x00000b98, -0x0007000c,0x00000007,0x000003e5,0x00000001, -0x00000028,0x000003e3,0x00000113,0x0005008e, -0x00000007,0x000003e7,0x000003e0,0x000000b4, -0x00050083,0x00000007,0x000003e9,0x00000ba1, -0x000003e7,0x00050088,0x00000007,0x000003ea, -0x000003e5,0x000003e9,0x0007000c,0x00000007, -0x000003eb,0x00000001,0x0000001a,0x000003ea, -0x000000bb,0x0005008e,0x00000007,0x000003ec, -0x000003eb,0x000000ac,0x000200f9,0x000003bf, -0x000200f8,0x000003bf,0x000700f5,0x00000007, -0x00000b3d,0x000003ec,0x000003b9,0x00000b3c, -0x000003fc,0x0005008e,0x00000007,0x000003c3, -0x00000b3d,0x0000004a,0x00050051,0x00000006, -0x000003c5,0x000003c3,0x00000000,0x00050051, -0x00000006,0x000003c6,0x000003c3,0x00000001, -0x00050051,0x00000006,0x000003c7,0x000003c3, -0x00000002,0x00070050,0x00000023,0x000003c8, -0x000003c5,0x000003c6,0x000003c7,0x0000004a, -0x000200f9,0x00000378,0x000200f8,0x0000033c, -0x00050083,0x0000012f,0x0000033f,0x00000329, -0x00000b94,0x0008000c,0x0000012f,0x00000342, -0x00000001,0x0000002b,0x0000033f,0x00000321, -0x0000032f,0x0006000c,0x0000012f,0x00000344, -0x00000001,0x00000008,0x00000342,0x00050083, -0x0000012f,0x00000347,0x00000342,0x00000344, -0x0004006e,0x0000001f,0x00000349,0x00000344, -0x00050081,0x0000012f,0x0000034c,0x00000344, -0x00000b95,0x0007000c,0x0000012f,0x0000034e, -0x00000001,0x00000025,0x0000034c,0x0000032f, -0x0004006e,0x0000001f,0x0000034f,0x0000034e, -0x00050051,0x0000001e,0x00000351,0x00000349, -0x00000000,0x00050051,0x0000001e,0x00000353, -0x00000349,0x00000001,0x0004003d,0x0000001c, -0x0000041d,0x00000285,0x0007005f,0x00000023, -0x0000041f,0x0000041d,0x00000349,0x00000002, -0x000000db,0x000500c7,0x00000021,0x0000042c, -0x00000289,0x000000f0,0x000500ab,0x0000003d, -0x0000042d,0x0000042c,0x000000e1,0x000300f7, -0x00000435,0x00000000,0x000400fa,0x0000042d, -0x0000042e,0x00000432,0x000200f8,0x00000432, -0x0008004f,0x00000007,0x00000434,0x0000041f, -0x0000041f,0x00000000,0x00000001,0x00000002, -0x000200f9,0x00000435,0x000200f8,0x0000042e, -0x0008004f,0x00000007,0x00000430,0x0000041f, -0x0000041f,0x00000000,0x00000001,0x00000002, -0x0008000c,0x00000007,0x00000463,0x00000001, -0x0000002b,0x00000430,0x00000113,0x00000b97, -0x0005008e,0x00000007,0x00000465,0x00000463, -0x0000004f,0x0007000c,0x00000007,0x00000467, -0x00000001,0x0000001a,0x00000463,0x00000054, -0x0005008e,0x00000007,0x00000468,0x00000467, -0x00000051,0x00050083,0x00000007,0x0000046a, -0x00000468,0x00000b9b,0x000500ba,0x0000005d, -0x0000046c,0x00000463,0x0000005c,0x000600a9, -0x00000007,0x0000046d,0x0000046c,0x0000046a, -0x00000465,0x000200f9,0x00000435,0x000200f8, -0x00000435,0x000700f5,0x00000007,0x00000b1c, -0x0000046d,0x0000042e,0x00000434,0x00000432, -0x000500c7,0x00000021,0x0000044c,0x00000289, -0x00000117,0x000500ab,0x0000003d,0x0000044d, -0x0000044c,0x000000e1,0x000300f7,0x00000454, -0x00000000,0x000400fa,0x0000044d,0x0000044e, -0x00000451,0x000200f8,0x00000451,0x00050041, -0x0000007b,0x00000486,0x00000079,0x0000007a, -0x0004003d,0x00000021,0x00000487,0x00000486, -0x000500aa,0x0000003d,0x00000488,0x00000487, -0x0000007e,0x000300f7,0x00000491,0x00000000, -0x000400fa,0x00000488,0x00000489,0x0000048e, -0x000200f8,0x0000048e,0x0007000c,0x00000007, -0x00000497,0x00000001,0x00000028,0x00000b1c, -0x00000113,0x00050085,0x00000007,0x0000049a, -0x00000497,0x00000ba6,0x00050081,0x00000007, -0x0000049d,0x00000497,0x00000b9b,0x00050085, -0x00000007,0x0000049f,0x0000049d,0x00000ba8, -0x0007000c,0x00000007,0x000004a0,0x00000001, -0x0000001a,0x0000049f,0x0000006e,0x000500ba, -0x0000005d,0x000004a2,0x00000497,0x00000072, -0x000600a9,0x00000007,0x000004a3,0x000004a2, -0x000004a0,0x0000049a,0x000200f9,0x00000491, -0x000200f8,0x00000489,0x0007000c,0x00000007, -0x0000048c,0x00000001,0x00000028,0x00000b1c, -0x00000113,0x0007000c,0x00000007,0x0000048d, -0x00000001,0x0000001a,0x0000048c,0x00000087, -0x000200f9,0x00000491,0x000200f8,0x00000491, -0x000700f5,0x00000007,0x00000b20,0x0000048d, -0x00000489,0x000004a3,0x0000048e,0x000200f9, -0x00000454,0x000200f8,0x0000044e,0x0008000c, -0x00000007,0x00000474,0x00000001,0x0000002b, -0x00000b1c,0x00000113,0x00000b97,0x0007000c, -0x00000007,0x00000475,0x00000001,0x0000001a, -0x00000474,0x000000aa,0x00050083,0x00000007, -0x00000478,0x00000475,0x00000b98,0x0007000c, -0x00000007,0x0000047a,0x00000001,0x00000028, -0x00000478,0x00000113,0x0005008e,0x00000007, -0x0000047c,0x00000475,0x000000b4,0x00050083, -0x00000007,0x0000047e,0x00000ba1,0x0000047c, -0x00050088,0x00000007,0x0000047f,0x0000047a, -0x0000047e,0x0007000c,0x00000007,0x00000480, -0x00000001,0x0000001a,0x0000047f,0x000000bb, -0x0005008e,0x00000007,0x00000481,0x00000480, -0x000000ac,0x000200f9,0x00000454,0x000200f8, -0x00000454,0x000700f5,0x00000007,0x00000b21, -0x00000481,0x0000044e,0x00000b20,0x00000491, -0x0005008e,0x00000007,0x00000458,0x00000b21, -0x0000004a,0x00050051,0x00000006,0x0000045a, -0x00000458,0x00000000,0x00050051,0x00000006, -0x0000045b,0x00000458,0x00000001,0x00050051, -0x00000006,0x0000045c,0x00000458,0x00000002, -0x00070050,0x00000023,0x0000045d,0x0000045a, -0x0000045b,0x0000045c,0x0000004a,0x00050051, -0x0000001e,0x00000358,0x0000034f,0x00000000, -0x00050050,0x0000001f,0x0000035b,0x00000358, -0x00000353,0x0004003d,0x0000001c,0x000004b2, -0x00000285,0x0007005f,0x00000023,0x000004b4, -0x000004b2,0x0000035b,0x00000002,0x000000db, -0x000300f7,0x000004ca,0x00000000,0x000400fa, -0x0000042d,0x000004c3,0x000004c7,0x000200f8, -0x000004c7,0x0008004f,0x00000007,0x000004c9, -0x000004b4,0x000004b4,0x00000000,0x00000001, -0x00000002,0x000200f9,0x000004ca,0x000200f8, -0x000004c3,0x0008004f,0x00000007,0x000004c5, -0x000004b4,0x000004b4,0x00000000,0x00000001, -0x00000002,0x0008000c,0x00000007,0x000004f8, -0x00000001,0x0000002b,0x000004c5,0x00000113, -0x00000b97,0x0005008e,0x00000007,0x000004fa, -0x000004f8,0x0000004f,0x0007000c,0x00000007, -0x000004fc,0x00000001,0x0000001a,0x000004f8, -0x00000054,0x0005008e,0x00000007,0x000004fd, -0x000004fc,0x00000051,0x00050083,0x00000007, -0x000004ff,0x000004fd,0x00000b9b,0x000500ba, -0x0000005d,0x00000501,0x000004f8,0x0000005c, -0x000600a9,0x00000007,0x00000502,0x00000501, -0x000004ff,0x000004fa,0x000200f9,0x000004ca, -0x000200f8,0x000004ca,0x000700f5,0x00000007, -0x00000b23,0x00000502,0x000004c3,0x000004c9, -0x000004c7,0x000300f7,0x000004e9,0x00000000, -0x000400fa,0x0000044d,0x000004e3,0x000004e6, -0x000200f8,0x000004e6,0x00050041,0x0000007b, -0x0000051b,0x00000079,0x0000007a,0x0004003d, -0x00000021,0x0000051c,0x0000051b,0x000500aa, -0x0000003d,0x0000051d,0x0000051c,0x0000007e, -0x000300f7,0x00000526,0x00000000,0x000400fa, -0x0000051d,0x0000051e,0x00000523,0x000200f8, -0x00000523,0x0007000c,0x00000007,0x0000052c, -0x00000001,0x00000028,0x00000b23,0x00000113, -0x00050085,0x00000007,0x0000052f,0x0000052c, -0x00000ba6,0x00050081,0x00000007,0x00000532, -0x0000052c,0x00000b9b,0x00050085,0x00000007, -0x00000534,0x00000532,0x00000ba8,0x0007000c, -0x00000007,0x00000535,0x00000001,0x0000001a, -0x00000534,0x0000006e,0x000500ba,0x0000005d, -0x00000537,0x0000052c,0x00000072,0x000600a9, -0x00000007,0x00000538,0x00000537,0x00000535, -0x0000052f,0x000200f9,0x00000526,0x000200f8, -0x0000051e,0x0007000c,0x00000007,0x00000521, -0x00000001,0x00000028,0x00000b23,0x00000113, -0x0007000c,0x00000007,0x00000522,0x00000001, -0x0000001a,0x00000521,0x00000087,0x000200f9, -0x00000526,0x000200f8,0x00000526,0x000700f5, -0x00000007,0x00000b27,0x00000522,0x0000051e, -0x00000538,0x00000523,0x000200f9,0x000004e9, -0x000200f8,0x000004e3,0x0008000c,0x00000007, -0x00000509,0x00000001,0x0000002b,0x00000b23, -0x00000113,0x00000b97,0x0007000c,0x00000007, -0x0000050a,0x00000001,0x0000001a,0x00000509, -0x000000aa,0x00050083,0x00000007,0x0000050d, -0x0000050a,0x00000b98,0x0007000c,0x00000007, -0x0000050f,0x00000001,0x00000028,0x0000050d, -0x00000113,0x0005008e,0x00000007,0x00000511, -0x0000050a,0x000000b4,0x00050083,0x00000007, -0x00000513,0x00000ba1,0x00000511,0x00050088, -0x00000007,0x00000514,0x0000050f,0x00000513, -0x0007000c,0x00000007,0x00000515,0x00000001, -0x0000001a,0x00000514,0x000000bb,0x0005008e, -0x00000007,0x00000516,0x00000515,0x000000ac, -0x000200f9,0x000004e9,0x000200f8,0x000004e9, -0x000700f5,0x00000007,0x00000b28,0x00000516, -0x000004e3,0x00000b27,0x00000526,0x0005008e, -0x00000007,0x000004ed,0x00000b28,0x0000004a, -0x00050051,0x00000006,0x000004ef,0x000004ed, -0x00000000,0x00050051,0x00000006,0x000004f0, -0x000004ed,0x00000001,0x00050051,0x00000006, -0x000004f1,0x000004ed,0x00000002,0x00070050, -0x00000023,0x000004f2,0x000004ef,0x000004f0, -0x000004f1,0x0000004a,0x00050051,0x00000006, -0x0000035f,0x00000347,0x00000000,0x00070050, -0x00000023,0x00000360,0x0000035f,0x0000035f, -0x0000035f,0x0000035f,0x0008000c,0x00000023, -0x00000361,0x00000001,0x0000002e,0x0000045d, -0x000004f2,0x00000360,0x00050051,0x0000001e, -0x00000365,0x0000034f,0x00000001,0x00050050, -0x0000001f,0x00000366,0x00000351,0x00000365, -0x0004003d,0x0000001c,0x00000547,0x00000285, -0x0007005f,0x00000023,0x00000549,0x00000547, -0x00000366,0x00000002,0x000000db,0x000300f7, -0x0000055f,0x00000000,0x000400fa,0x0000042d, -0x00000558,0x0000055c,0x000200f8,0x0000055c, -0x0008004f,0x00000007,0x0000055e,0x00000549, -0x00000549,0x00000000,0x00000001,0x00000002, -0x000200f9,0x0000055f,0x000200f8,0x00000558, -0x0008004f,0x00000007,0x0000055a,0x00000549, -0x00000549,0x00000000,0x00000001,0x00000002, -0x0008000c,0x00000007,0x0000058d,0x00000001, -0x0000002b,0x0000055a,0x00000113,0x00000b97, -0x0005008e,0x00000007,0x0000058f,0x0000058d, -0x0000004f,0x0007000c,0x00000007,0x00000591, -0x00000001,0x0000001a,0x0000058d,0x00000054, -0x0005008e,0x00000007,0x00000592,0x00000591, -0x00000051,0x00050083,0x00000007,0x00000594, -0x00000592,0x00000b9b,0x000500ba,0x0000005d, -0x00000596,0x0000058d,0x0000005c,0x000600a9, -0x00000007,0x00000597,0x00000596,0x00000594, -0x0000058f,0x000200f9,0x0000055f,0x000200f8, -0x0000055f,0x000700f5,0x00000007,0x00000b2a, -0x00000597,0x00000558,0x0000055e,0x0000055c, -0x000300f7,0x0000057e,0x00000000,0x000400fa, -0x0000044d,0x00000578,0x0000057b,0x000200f8, -0x0000057b,0x00050041,0x0000007b,0x000005b0, -0x00000079,0x0000007a,0x0004003d,0x00000021, -0x000005b1,0x000005b0,0x000500aa,0x0000003d, -0x000005b2,0x000005b1,0x0000007e,0x000300f7, -0x000005bb,0x00000000,0x000400fa,0x000005b2, -0x000005b3,0x000005b8,0x000200f8,0x000005b8, -0x0007000c,0x00000007,0x000005c1,0x00000001, -0x00000028,0x00000b2a,0x00000113,0x00050085, -0x00000007,0x000005c4,0x000005c1,0x00000ba6, -0x00050081,0x00000007,0x000005c7,0x000005c1, -0x00000b9b,0x00050085,0x00000007,0x000005c9, -0x000005c7,0x00000ba8,0x0007000c,0x00000007, -0x000005ca,0x00000001,0x0000001a,0x000005c9, -0x0000006e,0x000500ba,0x0000005d,0x000005cc, -0x000005c1,0x00000072,0x000600a9,0x00000007, -0x000005cd,0x000005cc,0x000005ca,0x000005c4, -0x000200f9,0x000005bb,0x000200f8,0x000005b3, -0x0007000c,0x00000007,0x000005b6,0x00000001, -0x00000028,0x00000b2a,0x00000113,0x0007000c, -0x00000007,0x000005b7,0x00000001,0x0000001a, -0x000005b6,0x00000087,0x000200f9,0x000005bb, -0x000200f8,0x000005bb,0x000700f5,0x00000007, -0x00000b2e,0x000005b7,0x000005b3,0x000005cd, -0x000005b8,0x000200f9,0x0000057e,0x000200f8, -0x00000578,0x0008000c,0x00000007,0x0000059e, -0x00000001,0x0000002b,0x00000b2a,0x00000113, -0x00000b97,0x0007000c,0x00000007,0x0000059f, -0x00000001,0x0000001a,0x0000059e,0x000000aa, -0x00050083,0x00000007,0x000005a2,0x0000059f, -0x00000b98,0x0007000c,0x00000007,0x000005a4, -0x00000001,0x00000028,0x000005a2,0x00000113, -0x0005008e,0x00000007,0x000005a6,0x0000059f, -0x000000b4,0x00050083,0x00000007,0x000005a8, -0x00000ba1,0x000005a6,0x00050088,0x00000007, -0x000005a9,0x000005a4,0x000005a8,0x0007000c, -0x00000007,0x000005aa,0x00000001,0x0000001a, -0x000005a9,0x000000bb,0x0005008e,0x00000007, -0x000005ab,0x000005aa,0x000000ac,0x000200f9, -0x0000057e,0x000200f8,0x0000057e,0x000700f5, -0x00000007,0x00000b2f,0x000005ab,0x00000578, -0x00000b2e,0x000005bb,0x0005008e,0x00000007, -0x00000582,0x00000b2f,0x0000004a,0x00050051, -0x00000006,0x00000584,0x00000582,0x00000000, -0x00050051,0x00000006,0x00000585,0x00000582, -0x00000001,0x00050051,0x00000006,0x00000586, -0x00000582,0x00000002,0x00070050,0x00000023, -0x00000587,0x00000584,0x00000585,0x00000586, -0x0000004a,0x0004003d,0x0000001c,0x000005dc, -0x00000285,0x0007005f,0x00000023,0x000005de, -0x000005dc,0x0000034f,0x00000002,0x000000db, -0x000300f7,0x000005f4,0x00000000,0x000400fa, -0x0000042d,0x000005ed,0x000005f1,0x000200f8, -0x000005f1,0x0008004f,0x00000007,0x000005f3, -0x000005de,0x000005de,0x00000000,0x00000001, -0x00000002,0x000200f9,0x000005f4,0x000200f8, -0x000005ed,0x0008004f,0x00000007,0x000005ef, -0x000005de,0x000005de,0x00000000,0x00000001, -0x00000002,0x0008000c,0x00000007,0x00000622, -0x00000001,0x0000002b,0x000005ef,0x00000113, -0x00000b97,0x0005008e,0x00000007,0x00000624, -0x00000622,0x0000004f,0x0007000c,0x00000007, -0x00000626,0x00000001,0x0000001a,0x00000622, -0x00000054,0x0005008e,0x00000007,0x00000627, -0x00000626,0x00000051,0x00050083,0x00000007, -0x00000629,0x00000627,0x00000b9b,0x000500ba, -0x0000005d,0x0000062b,0x00000622,0x0000005c, -0x000600a9,0x00000007,0x0000062c,0x0000062b, -0x00000629,0x00000624,0x000200f9,0x000005f4, -0x000200f8,0x000005f4,0x000700f5,0x00000007, -0x00000b31,0x0000062c,0x000005ed,0x000005f3, -0x000005f1,0x000300f7,0x00000613,0x00000000, -0x000400fa,0x0000044d,0x0000060d,0x00000610, -0x000200f8,0x00000610,0x00050041,0x0000007b, -0x00000645,0x00000079,0x0000007a,0x0004003d, -0x00000021,0x00000646,0x00000645,0x000500aa, -0x0000003d,0x00000647,0x00000646,0x0000007e, -0x000300f7,0x00000650,0x00000000,0x000400fa, -0x00000647,0x00000648,0x0000064d,0x000200f8, -0x0000064d,0x0007000c,0x00000007,0x00000656, -0x00000001,0x00000028,0x00000b31,0x00000113, -0x00050085,0x00000007,0x00000659,0x00000656, -0x00000ba6,0x00050081,0x00000007,0x0000065c, -0x00000656,0x00000b9b,0x00050085,0x00000007, -0x0000065e,0x0000065c,0x00000ba8,0x0007000c, -0x00000007,0x0000065f,0x00000001,0x0000001a, -0x0000065e,0x0000006e,0x000500ba,0x0000005d, -0x00000661,0x00000656,0x00000072,0x000600a9, -0x00000007,0x00000662,0x00000661,0x0000065f, -0x00000659,0x000200f9,0x00000650,0x000200f8, -0x00000648,0x0007000c,0x00000007,0x0000064b, -0x00000001,0x00000028,0x00000b31,0x00000113, -0x0007000c,0x00000007,0x0000064c,0x00000001, -0x0000001a,0x0000064b,0x00000087,0x000200f9, -0x00000650,0x000200f8,0x00000650,0x000700f5, -0x00000007,0x00000b35,0x0000064c,0x00000648, -0x00000662,0x0000064d,0x000200f9,0x00000613, -0x000200f8,0x0000060d,0x0008000c,0x00000007, -0x00000633,0x00000001,0x0000002b,0x00000b31, -0x00000113,0x00000b97,0x0007000c,0x00000007, -0x00000634,0x00000001,0x0000001a,0x00000633, -0x000000aa,0x00050083,0x00000007,0x00000637, -0x00000634,0x00000b98,0x0007000c,0x00000007, -0x00000639,0x00000001,0x00000028,0x00000637, -0x00000113,0x0005008e,0x00000007,0x0000063b, -0x00000634,0x000000b4,0x00050083,0x00000007, -0x0000063d,0x00000ba1,0x0000063b,0x00050088, -0x00000007,0x0000063e,0x00000639,0x0000063d, -0x0007000c,0x00000007,0x0000063f,0x00000001, -0x0000001a,0x0000063e,0x000000bb,0x0005008e, -0x00000007,0x00000640,0x0000063f,0x000000ac, -0x000200f9,0x00000613,0x000200f8,0x00000613, -0x000700f5,0x00000007,0x00000b36,0x00000640, -0x0000060d,0x00000b35,0x00000650,0x0005008e, -0x00000007,0x00000617,0x00000b36,0x0000004a, -0x00050051,0x00000006,0x00000619,0x00000617, -0x00000000,0x00050051,0x00000006,0x0000061a, -0x00000617,0x00000001,0x00050051,0x00000006, -0x0000061b,0x00000617,0x00000002,0x00070050, -0x00000023,0x0000061c,0x00000619,0x0000061a, -0x0000061b,0x0000004a,0x0008000c,0x00000023, -0x00000373,0x00000001,0x0000002e,0x00000587, -0x0000061c,0x00000360,0x00050051,0x00000006, -0x00000375,0x00000347,0x00000001,0x00070050, -0x00000023,0x00000376,0x00000375,0x00000375, -0x00000375,0x00000375,0x0008000c,0x00000023, -0x00000377,0x00000001,0x0000002e,0x00000361, -0x00000373,0x00000376,0x000200f9,0x00000378, -0x000200f8,0x00000378,0x000700f5,0x00000023, -0x00000b3e,0x000003c8,0x000003bf,0x00000377, -0x00000613,0x000500c7,0x00000021,0x00000297, -0x00000289,0x00000117,0x000500ab,0x0000003d, -0x00000298,0x00000297,0x000000e1,0x0008004f, -0x00000007,0x0000029b,0x00000b3e,0x00000b3e, -0x00000000,0x00000001,0x00000002,0x000300f7, -0x00000690,0x00000000,0x000300fb,0x000000e1, -0x0000066b,0x000200f8,0x0000066b,0x00050041, -0x0000007b,0x0000066c,0x00000079,0x0000020f, -0x0004003d,0x00000021,0x0000066d,0x0000066c, -0x000500ab,0x0000003d,0x0000066e,0x0000066d, -0x000000e1,0x000500a4,0x0000003d,0x00000671, -0x00000298,0x0000066e,0x000300f7,0x00000674, -0x00000000,0x000400fa,0x00000671,0x00000672, -0x00000674,0x000200f8,0x00000672,0x000200f9, -0x00000690,0x000200f8,0x00000674,0x000400a8, -0x0000003d,0x00000676,0x00000298,0x000300f7, -0x0000067d,0x00000000,0x000400fa,0x00000676, -0x00000677,0x0000067d,0x000200f8,0x00000677, -0x00050094,0x00000006,0x00000695,0x000001b1, -0x0000029b,0x00050094,0x00000006,0x00000697, -0x000001b7,0x0000029b,0x00050094,0x00000006, -0x00000699,0x000001bd,0x0000029b,0x00060050, -0x00000007,0x0000069a,0x00000695,0x00000697, -0x00000699,0x00050041,0x000001ea,0x0000067a, -0x00000079,0x000001ed,0x0004003d,0x00000006, -0x0000067b,0x0000067a,0x0005008e,0x00000007, -0x0000067c,0x0000069a,0x0000067b,0x000200f9, -0x00000690,0x000200f8,0x0000067d,0x00050094, -0x00000006,0x0000069e,0x000001c6,0x0000029b, -0x00050094,0x00000006,0x000006a0,0x000001cc, -0x0000029b,0x00050094,0x00000006,0x000006a2, -0x000001d2,0x0000029b,0x00060050,0x00000007, -0x000006a3,0x0000069e,0x000006a0,0x000006a2, -0x00050041,0x000001ea,0x00000687,0x00000079, -0x000001ed,0x0004003d,0x00000006,0x00000688, -0x00000687,0x00060050,0x00000007,0x00000689, -0x00000688,0x00000688,0x00000688,0x00050088, -0x00000007,0x0000068a,0x000006a3,0x00000689, -0x0007000c,0x00000007,0x0000068c,0x00000001, -0x00000028,0x0000068a,0x00000113,0x000300f7, -0x000006d3,0x00000000,0x000300fb,0x000000e1, -0x000006ac,0x000200f8,0x000006ac,0x00050094, -0x00000006,0x000006ae,0x0000068c,0x000001dd, -0x000500bc,0x0000003d,0x000006b0,0x000006ae, -0x000001e0,0x000300f7,0x000006b3,0x00000000, -0x000400fa,0x000006b0,0x000006b1,0x000006b3, -0x000200f8,0x000006b1,0x000200f9,0x000006d3, -0x000200f8,0x000006b3,0x00050041,0x000001ea, -0x000006b4,0x00000079,0x000001e9,0x0004003d, -0x00000006,0x000006b5,0x000006b4,0x00050088, -0x00000006,0x000006b8,0x000006b5,0x00000688, -0x0007000c,0x00000006,0x000006b9,0x00000001, -0x00000028,0x000006b8,0x0000004a,0x00050083, -0x00000006,0x000006ba,0x000006b9,0x000001e0, -0x00050083,0x00000006,0x000006be,0x000006ae, -0x000001e0,0x00050085,0x00000006,0x000006c0, -0x000006be,0x00000ba9,0x00050085,0x00000006, -0x00000bab,0x000006ba,0x000006ba,0x00050088, -0x00000006,0x00000bae,0x000006be,0x00000bab, -0x00050085,0x00000006,0x000006c9,0x00000bad, -0x00000bae,0x00050081,0x00000006,0x000006ca, -0x0000004a,0x000006c9,0x00050085,0x00000006, -0x000006cb,0x000006be,0x000006ca,0x00050081, -0x00000006,0x000006cd,0x0000004a,0x000006c0, -0x00050088,0x00000006,0x000006ce,0x000006cb, -0x000006cd,0x00050081,0x00000006,0x000006cf, -0x000001e0,0x000006ce,0x00050088,0x00000006, -0x000006d1,0x000006cf,0x000006ae,0x0005008e, -0x00000007,0x000006d2,0x0000068c,0x000006d1, -0x000200f9,0x000006d3,0x000200f8,0x000006d3, -0x000700f5,0x00000007,0x00000b3f,0x0000068c, -0x000006b1,0x000006d2,0x000006b3,0x0005008e, -0x00000007,0x0000068f,0x00000b3f,0x0000004a, -0x000200f9,0x00000690,0x000200f8,0x00000690, -0x000900f5,0x00000007,0x00000b40,0x0000029b, -0x00000672,0x0000067c,0x00000677,0x0000068f, -0x000006d3,0x000200f9,0x00000283,0x000200f8, -0x00000283,0x000700f5,0x00000007,0x00000b70, -0x00000113,0x0000027a,0x00000b40,0x00000690, -0x00050041,0x0000007b,0x000002a0,0x00000079, -0x0000029f,0x0004003d,0x00000021,0x000002a1, -0x000002a0,0x000500ac,0x0000003d,0x000002a2, -0x000002a1,0x0000007e,0x000300f7,0x000002a4, -0x00000000,0x000400fa,0x000002a2,0x000002a3, -0x000002a4,0x000200f8,0x000002a3,0x00050041, -0x00000272,0x000002a7,0x00000079,0x000002a6, -0x0004003d,0x00000023,0x000002a8,0x000002a7, -0x0007004f,0x0000012f,0x000002a9,0x000002a8, -0x000002a8,0x00000000,0x00000001,0x000500be, -0x00000276,0x000002aa,0x0000026f,0x000002a9, -0x0004009b,0x0000003d,0x000002ab,0x000002aa, -0x000200f9,0x000002a4,0x000200f8,0x000002a4, -0x000700f5,0x0000003d,0x000002ac,0x000002a2, -0x00000283,0x000002ab,0x000002a3,0x000300f7, -0x000002ae,0x00000000,0x000400fa,0x000002ac, -0x000002ad,0x000002ae,0x000200f8,0x000002ad, -0x00050041,0x00000272,0x000002b0,0x00000079, -0x000002a6,0x0004003d,0x00000023,0x000002b1, -0x000002b0,0x0007004f,0x0000012f,0x000002b2, -0x000002b1,0x000002b1,0x00000002,0x00000003, -0x000500b8,0x00000276,0x000002b3,0x0000026f, -0x000002b2,0x0004009b,0x0000003d,0x000002b4, -0x000002b3,0x000200f9,0x000002ae,0x000200f8, -0x000002ae,0x000700f5,0x0000003d,0x000002b5, -0x000002ac,0x000002a4,0x000002b4,0x000002ad, -0x000300f7,0x000002b7,0x00000000,0x000400fa, -0x000002b5,0x000002b6,0x000002b7,0x000200f8, -0x000002b6,0x00050041,0x00000272,0x000002bd, -0x00000079,0x000002a6,0x0004003d,0x00000023, -0x000002be,0x000002bd,0x00050041,0x00000272, -0x000002c0,0x00000079,0x000002ba,0x0004003d, -0x00000023,0x000002c1,0x000002c0,0x00050041, -0x0000007b,0x000002c3,0x00000079,0x000002bb, -0x0004003d,0x00000021,0x000002c4,0x000002c3, -0x000300f7,0x00000752,0x00000000,0x000300fb, -0x000000e1,0x000006ec,0x000200f8,0x000006ec, -0x0007004f,0x0000012f,0x000006f2,0x000002be, -0x000002be,0x00000000,0x00000001,0x00050083, -0x0000012f,0x000006f3,0x0000026f,0x000006f2, -0x0007004f,0x0000012f,0x000006f5,0x000002be, -0x000002be,0x00000002,0x00000003,0x00050083, -0x0000012f,0x000006f8,0x000006f5,0x000006f2, -0x00050088,0x0000012f,0x000006f9,0x000006f3, -0x000006f8,0x0007004f,0x0000012f,0x000006fb, -0x000002c1,0x000002c1,0x00000000,0x00000001, -0x0007004f,0x0000012f,0x000006fe,0x000002c1, -0x000002c1,0x00000002,0x00000003,0x00050083, -0x0000012f,0x00000701,0x000006fe,0x000006fb, -0x00050085,0x0000012f,0x00000702,0x000006f9, -0x00000701,0x00050081,0x0000012f,0x00000703, -0x000006fb,0x00000702,0x00050083,0x0000012f, -0x00000709,0x000006fe,0x00000b95,0x000500c7, -0x00000021,0x0000070b,0x000002c4,0x0000007e, -0x000500ab,0x0000003d,0x0000070c,0x0000070b, -0x000000e1,0x000300f7,0x00000716,0x00000000, -0x000400fa,0x0000070c,0x0000070d,0x00000716, -0x000200f8,0x0000070d,0x0006000c,0x0000012f, -0x0000070f,0x00000001,0x00000008,0x00000703, -0x0008000c,0x0000012f,0x00000712,0x00000001, -0x0000002b,0x0000070f,0x000006fb,0x00000709, -0x0004006e,0x0000001f,0x00000713,0x00000712, -0x0004003d,0x0000001c,0x00000762,0x000002b9, -0x0007005f,0x00000023,0x00000764,0x00000762, -0x00000713,0x00000002,0x000000db,0x000500c7, -0x00000021,0x00000766,0x000002c4,0x000000df, -0x000500ab,0x0000003d,0x00000767,0x00000766, -0x000000e1,0x000300f7,0x0000076e,0x00000000, -0x000400fa,0x00000767,0x00000769,0x0000076a, -0x000200f8,0x0000076a,0x00050051,0x00000006, -0x0000076c,0x00000764,0x00000003,0x0008000c, -0x00000006,0x0000076d,0x00000001,0x0000002b, -0x0000076c,0x00000049,0x0000004a,0x000200f9, -0x0000076e,0x000200f8,0x00000769,0x000200f9, -0x0000076e,0x000200f8,0x0000076e,0x000700f5, -0x00000006,0x00000b5d,0x0000004a,0x00000769, -0x0000076d,0x0000076a,0x000500c7,0x00000021, -0x00000771,0x000002c4,0x000000f0,0x000500ab, -0x0000003d,0x00000772,0x00000771,0x000000e1, -0x000300f7,0x0000077a,0x00000000,0x000400fa, -0x00000772,0x00000773,0x00000777,0x000200f8, -0x00000777,0x0008004f,0x00000007,0x00000779, -0x00000764,0x00000764,0x00000000,0x00000001, -0x00000002,0x000200f9,0x0000077a,0x000200f8, -0x00000773,0x0008004f,0x00000007,0x00000775, -0x00000764,0x00000764,0x00000000,0x00000001, -0x00000002,0x0008000c,0x00000007,0x000007a8, -0x00000001,0x0000002b,0x00000775,0x00000113, -0x00000b97,0x0005008e,0x00000007,0x000007aa, -0x000007a8,0x0000004f,0x0007000c,0x00000007, -0x000007ac,0x00000001,0x0000001a,0x000007a8, -0x00000054,0x0005008e,0x00000007,0x000007ad, -0x000007ac,0x00000051,0x00050083,0x00000007, -0x000007af,0x000007ad,0x00000b9b,0x000500ba, -0x0000005d,0x000007b1,0x000007a8,0x0000005c, -0x000600a9,0x00000007,0x000007b2,0x000007b1, -0x000007af,0x000007aa,0x000200f9,0x0000077a, -0x000200f8,0x0000077a,0x000700f5,0x00000007, -0x00000b5e,0x000007b2,0x00000773,0x00000779, -0x00000777,0x000400a8,0x0000003d,0x0000077d, -0x00000767,0x000300f7,0x00000782,0x00000000, -0x000400fa,0x0000077d,0x0000077e,0x00000782, -0x000200f8,0x0000077e,0x000500c7,0x00000021, -0x00000780,0x000002c4,0x00000103,0x000500aa, -0x0000003d,0x00000781,0x00000780,0x000000e1, -0x000200f9,0x00000782,0x000200f8,0x00000782, -0x000700f5,0x0000003d,0x00000783,0x0000077d, -0x0000077a,0x00000781,0x0000077e,0x000300f7, -0x0000078f,0x00000000,0x000400fa,0x00000783, -0x00000784,0x0000078f,0x000200f8,0x00000784, -0x000500ba,0x0000003d,0x00000786,0x00000b5d, -0x00000049,0x000300f7,0x0000078d,0x00000000, -0x000400fa,0x00000786,0x00000787,0x0000078c, -0x000200f8,0x0000078c,0x000200f9,0x0000078d, -0x000200f8,0x00000787,0x00060050,0x00000007, -0x0000078a,0x00000b5d,0x00000b5d,0x00000b5d, -0x00050088,0x00000007,0x0000078b,0x00000b5e, -0x0000078a,0x000200f9,0x0000078d,0x000200f8, -0x0000078d,0x000700f5,0x00000007,0x00000b60, -0x0000078b,0x00000787,0x00000113,0x0000078c, -0x000200f9,0x0000078f,0x000200f8,0x0000078f, -0x000700f5,0x00000007,0x00000b61,0x00000b5e, -0x00000782,0x00000b60,0x0000078d,0x000500c7, -0x00000021,0x00000791,0x000002c4,0x00000117, -0x000500ab,0x0000003d,0x00000792,0x00000791, -0x000000e1,0x000300f7,0x00000799,0x00000000, -0x000400fa,0x00000792,0x00000793,0x00000796, -0x000200f8,0x00000796,0x00050041,0x0000007b, -0x000007cb,0x00000079,0x0000007a,0x0004003d, -0x00000021,0x000007cc,0x000007cb,0x000500aa, -0x0000003d,0x000007cd,0x000007cc,0x0000007e, -0x000300f7,0x000007d6,0x00000000,0x000400fa, -0x000007cd,0x000007ce,0x000007d3,0x000200f8, -0x000007d3,0x0007000c,0x00000007,0x000007dc, -0x00000001,0x00000028,0x00000b61,0x00000113, -0x00050085,0x00000007,0x000007df,0x000007dc, -0x00000ba6,0x00050081,0x00000007,0x000007e2, -0x000007dc,0x00000b9b,0x00050085,0x00000007, -0x000007e4,0x000007e2,0x00000ba8,0x0007000c, -0x00000007,0x000007e5,0x00000001,0x0000001a, -0x000007e4,0x0000006e,0x000500ba,0x0000005d, -0x000007e7,0x000007dc,0x00000072,0x000600a9, -0x00000007,0x000007e8,0x000007e7,0x000007e5, -0x000007df,0x000200f9,0x000007d6,0x000200f8, -0x000007ce,0x0007000c,0x00000007,0x000007d1, -0x00000001,0x00000028,0x00000b61,0x00000113, -0x0007000c,0x00000007,0x000007d2,0x00000001, -0x0000001a,0x000007d1,0x00000087,0x000200f9, -0x000007d6,0x000200f8,0x000007d6,0x000700f5, -0x00000007,0x00000b62,0x000007d2,0x000007ce, -0x000007e8,0x000007d3,0x000200f9,0x00000799, -0x000200f8,0x00000793,0x0008000c,0x00000007, -0x000007b9,0x00000001,0x0000002b,0x00000b61, -0x00000113,0x00000b97,0x0007000c,0x00000007, -0x000007ba,0x00000001,0x0000001a,0x000007b9, -0x000000aa,0x00050083,0x00000007,0x000007bd, -0x000007ba,0x00000b98,0x0007000c,0x00000007, -0x000007bf,0x00000001,0x00000028,0x000007bd, -0x00000113,0x0005008e,0x00000007,0x000007c1, -0x000007ba,0x000000b4,0x00050083,0x00000007, -0x000007c3,0x00000ba1,0x000007c1,0x00050088, -0x00000007,0x000007c4,0x000007bf,0x000007c3, -0x0007000c,0x00000007,0x000007c5,0x00000001, -0x0000001a,0x000007c4,0x000000bb,0x0005008e, -0x00000007,0x000007c6,0x000007c5,0x000000ac, -0x000200f9,0x00000799,0x000200f8,0x00000799, -0x000700f5,0x00000007,0x00000b63,0x000007c6, -0x00000793,0x00000b62,0x000007d6,0x0005008e, -0x00000007,0x0000079d,0x00000b63,0x00000b5d, -0x00050051,0x00000006,0x0000079f,0x0000079d, -0x00000000,0x00050051,0x00000006,0x000007a0, -0x0000079d,0x00000001,0x00050051,0x00000006, -0x000007a1,0x0000079d,0x00000002,0x00070050, -0x00000023,0x000007a2,0x0000079f,0x000007a0, -0x000007a1,0x00000b5d,0x000200f9,0x00000752, -0x000200f8,0x00000716,0x00050083,0x0000012f, -0x00000719,0x00000703,0x00000b94,0x0008000c, -0x0000012f,0x0000071c,0x00000001,0x0000002b, -0x00000719,0x000006fb,0x00000709,0x0006000c, -0x0000012f,0x0000071e,0x00000001,0x00000008, -0x0000071c,0x00050083,0x0000012f,0x00000721, -0x0000071c,0x0000071e,0x0004006e,0x0000001f, -0x00000723,0x0000071e,0x00050081,0x0000012f, -0x00000726,0x0000071e,0x00000b95,0x0007000c, -0x0000012f,0x00000728,0x00000001,0x00000025, -0x00000726,0x00000709,0x0004006e,0x0000001f, -0x00000729,0x00000728,0x00050051,0x0000001e, -0x0000072b,0x00000723,0x00000000,0x00050051, -0x0000001e,0x0000072d,0x00000723,0x00000001, -0x0004003d,0x0000001c,0x000007f7,0x000002b9, -0x0007005f,0x00000023,0x000007f9,0x000007f7, -0x00000723,0x00000002,0x000000db,0x000500c7, -0x00000021,0x000007fb,0x000002c4,0x000000df, -0x000500ab,0x0000003d,0x000007fc,0x000007fb, -0x000000e1,0x000300f7,0x00000803,0x00000000, -0x000400fa,0x000007fc,0x000007fe,0x000007ff, -0x000200f8,0x000007ff,0x00050051,0x00000006, -0x00000801,0x000007f9,0x00000003,0x0008000c, -0x00000006,0x00000802,0x00000001,0x0000002b, -0x00000801,0x00000049,0x0000004a,0x000200f9, -0x00000803,0x000200f8,0x000007fe,0x000200f9, -0x00000803,0x000200f8,0x00000803,0x000700f5, -0x00000006,0x00000b41,0x0000004a,0x000007fe, -0x00000802,0x000007ff,0x000500c7,0x00000021, -0x00000806,0x000002c4,0x000000f0,0x000500ab, -0x0000003d,0x00000807,0x00000806,0x000000e1, -0x000300f7,0x0000080f,0x00000000,0x000400fa, -0x00000807,0x00000808,0x0000080c,0x000200f8, -0x0000080c,0x0008004f,0x00000007,0x0000080e, -0x000007f9,0x000007f9,0x00000000,0x00000001, -0x00000002,0x000200f9,0x0000080f,0x000200f8, -0x00000808,0x0008004f,0x00000007,0x0000080a, -0x000007f9,0x000007f9,0x00000000,0x00000001, -0x00000002,0x0008000c,0x00000007,0x0000083d, -0x00000001,0x0000002b,0x0000080a,0x00000113, -0x00000b97,0x0005008e,0x00000007,0x0000083f, -0x0000083d,0x0000004f,0x0007000c,0x00000007, -0x00000841,0x00000001,0x0000001a,0x0000083d, -0x00000054,0x0005008e,0x00000007,0x00000842, -0x00000841,0x00000051,0x00050083,0x00000007, -0x00000844,0x00000842,0x00000b9b,0x000500ba, -0x0000005d,0x00000846,0x0000083d,0x0000005c, -0x000600a9,0x00000007,0x00000847,0x00000846, -0x00000844,0x0000083f,0x000200f9,0x0000080f, -0x000200f8,0x0000080f,0x000700f5,0x00000007, -0x00000b42,0x00000847,0x00000808,0x0000080e, -0x0000080c,0x000400a8,0x0000003d,0x00000812, -0x000007fc,0x000300f7,0x00000817,0x00000000, -0x000400fa,0x00000812,0x00000813,0x00000817, -0x000200f8,0x00000813,0x000500c7,0x00000021, -0x00000815,0x000002c4,0x00000103,0x000500aa, -0x0000003d,0x00000816,0x00000815,0x000000e1, -0x000200f9,0x00000817,0x000200f8,0x00000817, -0x000700f5,0x0000003d,0x00000818,0x00000812, -0x0000080f,0x00000816,0x00000813,0x000300f7, -0x00000824,0x00000000,0x000400fa,0x00000818, -0x00000819,0x00000824,0x000200f8,0x00000819, -0x000500ba,0x0000003d,0x0000081b,0x00000b41, -0x00000049,0x000300f7,0x00000822,0x00000000, -0x000400fa,0x0000081b,0x0000081c,0x00000821, -0x000200f8,0x00000821,0x000200f9,0x00000822, -0x000200f8,0x0000081c,0x00060050,0x00000007, -0x0000081f,0x00000b41,0x00000b41,0x00000b41, -0x00050088,0x00000007,0x00000820,0x00000b42, -0x0000081f,0x000200f9,0x00000822,0x000200f8, -0x00000822,0x000700f5,0x00000007,0x00000b44, -0x00000820,0x0000081c,0x00000113,0x00000821, -0x000200f9,0x00000824,0x000200f8,0x00000824, -0x000700f5,0x00000007,0x00000b45,0x00000b42, -0x00000817,0x00000b44,0x00000822,0x000500c7, -0x00000021,0x00000826,0x000002c4,0x00000117, -0x000500ab,0x0000003d,0x00000827,0x00000826, -0x000000e1,0x000300f7,0x0000082e,0x00000000, -0x000400fa,0x00000827,0x00000828,0x0000082b, -0x000200f8,0x0000082b,0x00050041,0x0000007b, -0x00000860,0x00000079,0x0000007a,0x0004003d, -0x00000021,0x00000861,0x00000860,0x000500aa, -0x0000003d,0x00000862,0x00000861,0x0000007e, -0x000300f7,0x0000086b,0x00000000,0x000400fa, -0x00000862,0x00000863,0x00000868,0x000200f8, -0x00000868,0x0007000c,0x00000007,0x00000871, -0x00000001,0x00000028,0x00000b45,0x00000113, -0x00050085,0x00000007,0x00000874,0x00000871, -0x00000ba6,0x00050081,0x00000007,0x00000877, -0x00000871,0x00000b9b,0x00050085,0x00000007, -0x00000879,0x00000877,0x00000ba8,0x0007000c, -0x00000007,0x0000087a,0x00000001,0x0000001a, -0x00000879,0x0000006e,0x000500ba,0x0000005d, -0x0000087c,0x00000871,0x00000072,0x000600a9, -0x00000007,0x0000087d,0x0000087c,0x0000087a, -0x00000874,0x000200f9,0x0000086b,0x000200f8, -0x00000863,0x0007000c,0x00000007,0x00000866, -0x00000001,0x00000028,0x00000b45,0x00000113, -0x0007000c,0x00000007,0x00000867,0x00000001, -0x0000001a,0x00000866,0x00000087,0x000200f9, -0x0000086b,0x000200f8,0x0000086b,0x000700f5, -0x00000007,0x00000b46,0x00000867,0x00000863, -0x0000087d,0x00000868,0x000200f9,0x0000082e, -0x000200f8,0x00000828,0x0008000c,0x00000007, -0x0000084e,0x00000001,0x0000002b,0x00000b45, -0x00000113,0x00000b97,0x0007000c,0x00000007, -0x0000084f,0x00000001,0x0000001a,0x0000084e, -0x000000aa,0x00050083,0x00000007,0x00000852, -0x0000084f,0x00000b98,0x0007000c,0x00000007, -0x00000854,0x00000001,0x00000028,0x00000852, -0x00000113,0x0005008e,0x00000007,0x00000856, -0x0000084f,0x000000b4,0x00050083,0x00000007, -0x00000858,0x00000ba1,0x00000856,0x00050088, -0x00000007,0x00000859,0x00000854,0x00000858, -0x0007000c,0x00000007,0x0000085a,0x00000001, -0x0000001a,0x00000859,0x000000bb,0x0005008e, -0x00000007,0x0000085b,0x0000085a,0x000000ac, -0x000200f9,0x0000082e,0x000200f8,0x0000082e, -0x000700f5,0x00000007,0x00000b47,0x0000085b, -0x00000828,0x00000b46,0x0000086b,0x0005008e, -0x00000007,0x00000832,0x00000b47,0x00000b41, -0x00050051,0x00000006,0x00000834,0x00000832, -0x00000000,0x00050051,0x00000006,0x00000835, -0x00000832,0x00000001,0x00050051,0x00000006, -0x00000836,0x00000832,0x00000002,0x00070050, -0x00000023,0x00000837,0x00000834,0x00000835, -0x00000836,0x00000b41,0x00050051,0x0000001e, -0x00000732,0x00000729,0x00000000,0x00050050, -0x0000001f,0x00000735,0x00000732,0x0000072d, -0x0004003d,0x0000001c,0x0000088c,0x000002b9, -0x0007005f,0x00000023,0x0000088e,0x0000088c, -0x00000735,0x00000002,0x000000db,0x000300f7, -0x00000898,0x00000000,0x000400fa,0x000007fc, -0x00000893,0x00000894,0x000200f8,0x00000894, -0x00050051,0x00000006,0x00000896,0x0000088e, -0x00000003,0x0008000c,0x00000006,0x00000897, -0x00000001,0x0000002b,0x00000896,0x00000049, -0x0000004a,0x000200f9,0x00000898,0x000200f8, -0x00000893,0x000200f9,0x00000898,0x000200f8, -0x00000898,0x000700f5,0x00000006,0x00000b48, -0x0000004a,0x00000893,0x00000897,0x00000894, -0x000300f7,0x000008a4,0x00000000,0x000400fa, -0x00000807,0x0000089d,0x000008a1,0x000200f8, -0x000008a1,0x0008004f,0x00000007,0x000008a3, -0x0000088e,0x0000088e,0x00000000,0x00000001, -0x00000002,0x000200f9,0x000008a4,0x000200f8, -0x0000089d,0x0008004f,0x00000007,0x0000089f, -0x0000088e,0x0000088e,0x00000000,0x00000001, -0x00000002,0x0008000c,0x00000007,0x000008d2, -0x00000001,0x0000002b,0x0000089f,0x00000113, -0x00000b97,0x0005008e,0x00000007,0x000008d4, -0x000008d2,0x0000004f,0x0007000c,0x00000007, -0x000008d6,0x00000001,0x0000001a,0x000008d2, -0x00000054,0x0005008e,0x00000007,0x000008d7, -0x000008d6,0x00000051,0x00050083,0x00000007, -0x000008d9,0x000008d7,0x00000b9b,0x000500ba, -0x0000005d,0x000008db,0x000008d2,0x0000005c, -0x000600a9,0x00000007,0x000008dc,0x000008db, -0x000008d9,0x000008d4,0x000200f9,0x000008a4, -0x000200f8,0x000008a4,0x000700f5,0x00000007, -0x00000b49,0x000008dc,0x0000089d,0x000008a3, -0x000008a1,0x000300f7,0x000008ac,0x00000000, -0x000400fa,0x00000812,0x000008a8,0x000008ac, -0x000200f8,0x000008a8,0x000500c7,0x00000021, -0x000008aa,0x000002c4,0x00000103,0x000500aa, -0x0000003d,0x000008ab,0x000008aa,0x000000e1, -0x000200f9,0x000008ac,0x000200f8,0x000008ac, -0x000700f5,0x0000003d,0x000008ad,0x00000812, -0x000008a4,0x000008ab,0x000008a8,0x000300f7, -0x000008b9,0x00000000,0x000400fa,0x000008ad, -0x000008ae,0x000008b9,0x000200f8,0x000008ae, -0x000500ba,0x0000003d,0x000008b0,0x00000b48, -0x00000049,0x000300f7,0x000008b7,0x00000000, -0x000400fa,0x000008b0,0x000008b1,0x000008b6, -0x000200f8,0x000008b6,0x000200f9,0x000008b7, -0x000200f8,0x000008b1,0x00060050,0x00000007, -0x000008b4,0x00000b48,0x00000b48,0x00000b48, -0x00050088,0x00000007,0x000008b5,0x00000b49, -0x000008b4,0x000200f9,0x000008b7,0x000200f8, -0x000008b7,0x000700f5,0x00000007,0x00000b4b, -0x000008b5,0x000008b1,0x00000113,0x000008b6, -0x000200f9,0x000008b9,0x000200f8,0x000008b9, -0x000700f5,0x00000007,0x00000b4c,0x00000b49, -0x000008ac,0x00000b4b,0x000008b7,0x000300f7, -0x000008c3,0x00000000,0x000400fa,0x00000827, -0x000008bd,0x000008c0,0x000200f8,0x000008c0, -0x00050041,0x0000007b,0x000008f5,0x00000079, -0x0000007a,0x0004003d,0x00000021,0x000008f6, -0x000008f5,0x000500aa,0x0000003d,0x000008f7, -0x000008f6,0x0000007e,0x000300f7,0x00000900, -0x00000000,0x000400fa,0x000008f7,0x000008f8, -0x000008fd,0x000200f8,0x000008fd,0x0007000c, -0x00000007,0x00000906,0x00000001,0x00000028, -0x00000b4c,0x00000113,0x00050085,0x00000007, -0x00000909,0x00000906,0x00000ba6,0x00050081, -0x00000007,0x0000090c,0x00000906,0x00000b9b, -0x00050085,0x00000007,0x0000090e,0x0000090c, -0x00000ba8,0x0007000c,0x00000007,0x0000090f, -0x00000001,0x0000001a,0x0000090e,0x0000006e, -0x000500ba,0x0000005d,0x00000911,0x00000906, -0x00000072,0x000600a9,0x00000007,0x00000912, -0x00000911,0x0000090f,0x00000909,0x000200f9, -0x00000900,0x000200f8,0x000008f8,0x0007000c, -0x00000007,0x000008fb,0x00000001,0x00000028, -0x00000b4c,0x00000113,0x0007000c,0x00000007, -0x000008fc,0x00000001,0x0000001a,0x000008fb, -0x00000087,0x000200f9,0x00000900,0x000200f8, -0x00000900,0x000700f5,0x00000007,0x00000b4d, -0x000008fc,0x000008f8,0x00000912,0x000008fd, -0x000200f9,0x000008c3,0x000200f8,0x000008bd, -0x0008000c,0x00000007,0x000008e3,0x00000001, -0x0000002b,0x00000b4c,0x00000113,0x00000b97, -0x0007000c,0x00000007,0x000008e4,0x00000001, -0x0000001a,0x000008e3,0x000000aa,0x00050083, -0x00000007,0x000008e7,0x000008e4,0x00000b98, -0x0007000c,0x00000007,0x000008e9,0x00000001, -0x00000028,0x000008e7,0x00000113,0x0005008e, -0x00000007,0x000008eb,0x000008e4,0x000000b4, -0x00050083,0x00000007,0x000008ed,0x00000ba1, -0x000008eb,0x00050088,0x00000007,0x000008ee, -0x000008e9,0x000008ed,0x0007000c,0x00000007, -0x000008ef,0x00000001,0x0000001a,0x000008ee, -0x000000bb,0x0005008e,0x00000007,0x000008f0, -0x000008ef,0x000000ac,0x000200f9,0x000008c3, -0x000200f8,0x000008c3,0x000700f5,0x00000007, -0x00000b4e,0x000008f0,0x000008bd,0x00000b4d, -0x00000900,0x0005008e,0x00000007,0x000008c7, -0x00000b4e,0x00000b48,0x00050051,0x00000006, -0x000008c9,0x000008c7,0x00000000,0x00050051, -0x00000006,0x000008ca,0x000008c7,0x00000001, -0x00050051,0x00000006,0x000008cb,0x000008c7, -0x00000002,0x00070050,0x00000023,0x000008cc, -0x000008c9,0x000008ca,0x000008cb,0x00000b48, -0x00050051,0x00000006,0x00000739,0x00000721, -0x00000000,0x00070050,0x00000023,0x0000073a, -0x00000739,0x00000739,0x00000739,0x00000739, -0x0008000c,0x00000023,0x0000073b,0x00000001, -0x0000002e,0x00000837,0x000008cc,0x0000073a, -0x00050051,0x0000001e,0x0000073f,0x00000729, -0x00000001,0x00050050,0x0000001f,0x00000740, -0x0000072b,0x0000073f,0x0004003d,0x0000001c, -0x00000921,0x000002b9,0x0007005f,0x00000023, -0x00000923,0x00000921,0x00000740,0x00000002, -0x000000db,0x000300f7,0x0000092d,0x00000000, -0x000400fa,0x000007fc,0x00000928,0x00000929, -0x000200f8,0x00000929,0x00050051,0x00000006, -0x0000092b,0x00000923,0x00000003,0x0008000c, -0x00000006,0x0000092c,0x00000001,0x0000002b, -0x0000092b,0x00000049,0x0000004a,0x000200f9, -0x0000092d,0x000200f8,0x00000928,0x000200f9, -0x0000092d,0x000200f8,0x0000092d,0x000700f5, -0x00000006,0x00000b4f,0x0000004a,0x00000928, -0x0000092c,0x00000929,0x000300f7,0x00000939, -0x00000000,0x000400fa,0x00000807,0x00000932, -0x00000936,0x000200f8,0x00000936,0x0008004f, -0x00000007,0x00000938,0x00000923,0x00000923, -0x00000000,0x00000001,0x00000002,0x000200f9, -0x00000939,0x000200f8,0x00000932,0x0008004f, -0x00000007,0x00000934,0x00000923,0x00000923, -0x00000000,0x00000001,0x00000002,0x0008000c, -0x00000007,0x00000967,0x00000001,0x0000002b, -0x00000934,0x00000113,0x00000b97,0x0005008e, -0x00000007,0x00000969,0x00000967,0x0000004f, -0x0007000c,0x00000007,0x0000096b,0x00000001, -0x0000001a,0x00000967,0x00000054,0x0005008e, -0x00000007,0x0000096c,0x0000096b,0x00000051, -0x00050083,0x00000007,0x0000096e,0x0000096c, -0x00000b9b,0x000500ba,0x0000005d,0x00000970, -0x00000967,0x0000005c,0x000600a9,0x00000007, -0x00000971,0x00000970,0x0000096e,0x00000969, -0x000200f9,0x00000939,0x000200f8,0x00000939, -0x000700f5,0x00000007,0x00000b50,0x00000971, -0x00000932,0x00000938,0x00000936,0x000300f7, -0x00000941,0x00000000,0x000400fa,0x00000812, -0x0000093d,0x00000941,0x000200f8,0x0000093d, -0x000500c7,0x00000021,0x0000093f,0x000002c4, -0x00000103,0x000500aa,0x0000003d,0x00000940, -0x0000093f,0x000000e1,0x000200f9,0x00000941, -0x000200f8,0x00000941,0x000700f5,0x0000003d, -0x00000942,0x00000812,0x00000939,0x00000940, -0x0000093d,0x000300f7,0x0000094e,0x00000000, -0x000400fa,0x00000942,0x00000943,0x0000094e, -0x000200f8,0x00000943,0x000500ba,0x0000003d, -0x00000945,0x00000b4f,0x00000049,0x000300f7, -0x0000094c,0x00000000,0x000400fa,0x00000945, -0x00000946,0x0000094b,0x000200f8,0x0000094b, -0x000200f9,0x0000094c,0x000200f8,0x00000946, -0x00060050,0x00000007,0x00000949,0x00000b4f, -0x00000b4f,0x00000b4f,0x00050088,0x00000007, -0x0000094a,0x00000b50,0x00000949,0x000200f9, -0x0000094c,0x000200f8,0x0000094c,0x000700f5, -0x00000007,0x00000b52,0x0000094a,0x00000946, -0x00000113,0x0000094b,0x000200f9,0x0000094e, -0x000200f8,0x0000094e,0x000700f5,0x00000007, -0x00000b53,0x00000b50,0x00000941,0x00000b52, -0x0000094c,0x000300f7,0x00000958,0x00000000, -0x000400fa,0x00000827,0x00000952,0x00000955, -0x000200f8,0x00000955,0x00050041,0x0000007b, -0x0000098a,0x00000079,0x0000007a,0x0004003d, -0x00000021,0x0000098b,0x0000098a,0x000500aa, -0x0000003d,0x0000098c,0x0000098b,0x0000007e, -0x000300f7,0x00000995,0x00000000,0x000400fa, -0x0000098c,0x0000098d,0x00000992,0x000200f8, -0x00000992,0x0007000c,0x00000007,0x0000099b, -0x00000001,0x00000028,0x00000b53,0x00000113, -0x00050085,0x00000007,0x0000099e,0x0000099b, -0x00000ba6,0x00050081,0x00000007,0x000009a1, -0x0000099b,0x00000b9b,0x00050085,0x00000007, -0x000009a3,0x000009a1,0x00000ba8,0x0007000c, -0x00000007,0x000009a4,0x00000001,0x0000001a, -0x000009a3,0x0000006e,0x000500ba,0x0000005d, -0x000009a6,0x0000099b,0x00000072,0x000600a9, -0x00000007,0x000009a7,0x000009a6,0x000009a4, -0x0000099e,0x000200f9,0x00000995,0x000200f8, -0x0000098d,0x0007000c,0x00000007,0x00000990, -0x00000001,0x00000028,0x00000b53,0x00000113, -0x0007000c,0x00000007,0x00000991,0x00000001, -0x0000001a,0x00000990,0x00000087,0x000200f9, -0x00000995,0x000200f8,0x00000995,0x000700f5, -0x00000007,0x00000b54,0x00000991,0x0000098d, -0x000009a7,0x00000992,0x000200f9,0x00000958, -0x000200f8,0x00000952,0x0008000c,0x00000007, -0x00000978,0x00000001,0x0000002b,0x00000b53, -0x00000113,0x00000b97,0x0007000c,0x00000007, -0x00000979,0x00000001,0x0000001a,0x00000978, -0x000000aa,0x00050083,0x00000007,0x0000097c, -0x00000979,0x00000b98,0x0007000c,0x00000007, -0x0000097e,0x00000001,0x00000028,0x0000097c, -0x00000113,0x0005008e,0x00000007,0x00000980, -0x00000979,0x000000b4,0x00050083,0x00000007, -0x00000982,0x00000ba1,0x00000980,0x00050088, -0x00000007,0x00000983,0x0000097e,0x00000982, -0x0007000c,0x00000007,0x00000984,0x00000001, -0x0000001a,0x00000983,0x000000bb,0x0005008e, -0x00000007,0x00000985,0x00000984,0x000000ac, -0x000200f9,0x00000958,0x000200f8,0x00000958, -0x000700f5,0x00000007,0x00000b55,0x00000985, -0x00000952,0x00000b54,0x00000995,0x0005008e, -0x00000007,0x0000095c,0x00000b55,0x00000b4f, -0x00050051,0x00000006,0x0000095e,0x0000095c, -0x00000000,0x00050051,0x00000006,0x0000095f, -0x0000095c,0x00000001,0x00050051,0x00000006, -0x00000960,0x0000095c,0x00000002,0x00070050, -0x00000023,0x00000961,0x0000095e,0x0000095f, -0x00000960,0x00000b4f,0x0004003d,0x0000001c, -0x000009b6,0x000002b9,0x0007005f,0x00000023, -0x000009b8,0x000009b6,0x00000729,0x00000002, -0x000000db,0x000300f7,0x000009c2,0x00000000, -0x000400fa,0x000007fc,0x000009bd,0x000009be, -0x000200f8,0x000009be,0x00050051,0x00000006, -0x000009c0,0x000009b8,0x00000003,0x0008000c, -0x00000006,0x000009c1,0x00000001,0x0000002b, -0x000009c0,0x00000049,0x0000004a,0x000200f9, -0x000009c2,0x000200f8,0x000009bd,0x000200f9, -0x000009c2,0x000200f8,0x000009c2,0x000700f5, -0x00000006,0x00000b56,0x0000004a,0x000009bd, -0x000009c1,0x000009be,0x000300f7,0x000009ce, -0x00000000,0x000400fa,0x00000807,0x000009c7, -0x000009cb,0x000200f8,0x000009cb,0x0008004f, -0x00000007,0x000009cd,0x000009b8,0x000009b8, -0x00000000,0x00000001,0x00000002,0x000200f9, -0x000009ce,0x000200f8,0x000009c7,0x0008004f, -0x00000007,0x000009c9,0x000009b8,0x000009b8, -0x00000000,0x00000001,0x00000002,0x0008000c, -0x00000007,0x000009fc,0x00000001,0x0000002b, -0x000009c9,0x00000113,0x00000b97,0x0005008e, -0x00000007,0x000009fe,0x000009fc,0x0000004f, -0x0007000c,0x00000007,0x00000a00,0x00000001, -0x0000001a,0x000009fc,0x00000054,0x0005008e, -0x00000007,0x00000a01,0x00000a00,0x00000051, -0x00050083,0x00000007,0x00000a03,0x00000a01, -0x00000b9b,0x000500ba,0x0000005d,0x00000a05, -0x000009fc,0x0000005c,0x000600a9,0x00000007, -0x00000a06,0x00000a05,0x00000a03,0x000009fe, -0x000200f9,0x000009ce,0x000200f8,0x000009ce, -0x000700f5,0x00000007,0x00000b57,0x00000a06, -0x000009c7,0x000009cd,0x000009cb,0x000300f7, -0x000009d6,0x00000000,0x000400fa,0x00000812, -0x000009d2,0x000009d6,0x000200f8,0x000009d2, -0x000500c7,0x00000021,0x000009d4,0x000002c4, -0x00000103,0x000500aa,0x0000003d,0x000009d5, -0x000009d4,0x000000e1,0x000200f9,0x000009d6, -0x000200f8,0x000009d6,0x000700f5,0x0000003d, -0x000009d7,0x00000812,0x000009ce,0x000009d5, -0x000009d2,0x000300f7,0x000009e3,0x00000000, -0x000400fa,0x000009d7,0x000009d8,0x000009e3, -0x000200f8,0x000009d8,0x000500ba,0x0000003d, -0x000009da,0x00000b56,0x00000049,0x000300f7, -0x000009e1,0x00000000,0x000400fa,0x000009da, -0x000009db,0x000009e0,0x000200f8,0x000009e0, -0x000200f9,0x000009e1,0x000200f8,0x000009db, -0x00060050,0x00000007,0x000009de,0x00000b56, -0x00000b56,0x00000b56,0x00050088,0x00000007, -0x000009df,0x00000b57,0x000009de,0x000200f9, -0x000009e1,0x000200f8,0x000009e1,0x000700f5, -0x00000007,0x00000b59,0x000009df,0x000009db, -0x00000113,0x000009e0,0x000200f9,0x000009e3, -0x000200f8,0x000009e3,0x000700f5,0x00000007, -0x00000b5a,0x00000b57,0x000009d6,0x00000b59, -0x000009e1,0x000300f7,0x000009ed,0x00000000, -0x000400fa,0x00000827,0x000009e7,0x000009ea, -0x000200f8,0x000009ea,0x00050041,0x0000007b, -0x00000a1f,0x00000079,0x0000007a,0x0004003d, -0x00000021,0x00000a20,0x00000a1f,0x000500aa, -0x0000003d,0x00000a21,0x00000a20,0x0000007e, -0x000300f7,0x00000a2a,0x00000000,0x000400fa, -0x00000a21,0x00000a22,0x00000a27,0x000200f8, -0x00000a27,0x0007000c,0x00000007,0x00000a30, -0x00000001,0x00000028,0x00000b5a,0x00000113, -0x00050085,0x00000007,0x00000a33,0x00000a30, -0x00000ba6,0x00050081,0x00000007,0x00000a36, -0x00000a30,0x00000b9b,0x00050085,0x00000007, -0x00000a38,0x00000a36,0x00000ba8,0x0007000c, -0x00000007,0x00000a39,0x00000001,0x0000001a, -0x00000a38,0x0000006e,0x000500ba,0x0000005d, -0x00000a3b,0x00000a30,0x00000072,0x000600a9, -0x00000007,0x00000a3c,0x00000a3b,0x00000a39, -0x00000a33,0x000200f9,0x00000a2a,0x000200f8, -0x00000a22,0x0007000c,0x00000007,0x00000a25, -0x00000001,0x00000028,0x00000b5a,0x00000113, -0x0007000c,0x00000007,0x00000a26,0x00000001, -0x0000001a,0x00000a25,0x00000087,0x000200f9, -0x00000a2a,0x000200f8,0x00000a2a,0x000700f5, -0x00000007,0x00000b5b,0x00000a26,0x00000a22, -0x00000a3c,0x00000a27,0x000200f9,0x000009ed, -0x000200f8,0x000009e7,0x0008000c,0x00000007, -0x00000a0d,0x00000001,0x0000002b,0x00000b5a, -0x00000113,0x00000b97,0x0007000c,0x00000007, -0x00000a0e,0x00000001,0x0000001a,0x00000a0d, -0x000000aa,0x00050083,0x00000007,0x00000a11, -0x00000a0e,0x00000b98,0x0007000c,0x00000007, -0x00000a13,0x00000001,0x00000028,0x00000a11, -0x00000113,0x0005008e,0x00000007,0x00000a15, -0x00000a0e,0x000000b4,0x00050083,0x00000007, -0x00000a17,0x00000ba1,0x00000a15,0x00050088, -0x00000007,0x00000a18,0x00000a13,0x00000a17, -0x0007000c,0x00000007,0x00000a19,0x00000001, -0x0000001a,0x00000a18,0x000000bb,0x0005008e, -0x00000007,0x00000a1a,0x00000a19,0x000000ac, -0x000200f9,0x000009ed,0x000200f8,0x000009ed, -0x000700f5,0x00000007,0x00000b5c,0x00000a1a, -0x000009e7,0x00000b5b,0x00000a2a,0x0005008e, -0x00000007,0x000009f1,0x00000b5c,0x00000b56, -0x00050051,0x00000006,0x000009f3,0x000009f1, -0x00000000,0x00050051,0x00000006,0x000009f4, -0x000009f1,0x00000001,0x00050051,0x00000006, -0x000009f5,0x000009f1,0x00000002,0x00070050, -0x00000023,0x000009f6,0x000009f3,0x000009f4, -0x000009f5,0x00000b56,0x0008000c,0x00000023, -0x0000074d,0x00000001,0x0000002e,0x00000961, -0x000009f6,0x0000073a,0x00050051,0x00000006, -0x0000074f,0x00000721,0x00000001,0x00070050, -0x00000023,0x00000750,0x0000074f,0x0000074f, -0x0000074f,0x0000074f,0x0008000c,0x00000023, -0x00000751,0x00000001,0x0000002e,0x0000073b, -0x0000074d,0x00000750,0x000200f9,0x00000752, -0x000200f8,0x00000752,0x000700f5,0x00000023, -0x00000b64,0x000007a2,0x00000799,0x00000751, -0x000009ed,0x000500c7,0x00000021,0x000002ca, -0x000002c4,0x00000117,0x000500ab,0x0000003d, -0x000002cb,0x000002ca,0x000000e1,0x0008004f, -0x00000007,0x000002ce,0x00000b64,0x00000b64, -0x00000000,0x00000001,0x00000002,0x00050051, -0x00000006,0x000002d1,0x00000b64,0x00000003, -0x000300f7,0x00000a6a,0x00000000,0x000300fb, -0x000000e1,0x00000a45,0x000200f8,0x00000a45, -0x00050041,0x0000007b,0x00000a46,0x00000079, -0x0000020f,0x0004003d,0x00000021,0x00000a47, -0x00000a46,0x000500ab,0x0000003d,0x00000a48, -0x00000a47,0x000000e1,0x000500a4,0x0000003d, -0x00000a4b,0x000002cb,0x00000a48,0x000300f7, -0x00000a4e,0x00000000,0x000400fa,0x00000a4b, -0x00000a4c,0x00000a4e,0x000200f8,0x00000a4c, -0x000200f9,0x00000a6a,0x000200f8,0x00000a4e, -0x000400a8,0x0000003d,0x00000a50,0x000002cb, -0x000300f7,0x00000a57,0x00000000,0x000400fa, -0x00000a50,0x00000a51,0x00000a57,0x000200f8, -0x00000a51,0x00050094,0x00000006,0x00000a6f, -0x000001b1,0x000002ce,0x00050094,0x00000006, -0x00000a71,0x000001b7,0x000002ce,0x00050094, -0x00000006,0x00000a73,0x000001bd,0x000002ce, -0x00060050,0x00000007,0x00000a74,0x00000a6f, -0x00000a71,0x00000a73,0x00050041,0x000001ea, -0x00000a54,0x00000079,0x000001ed,0x0004003d, -0x00000006,0x00000a55,0x00000a54,0x0005008e, -0x00000007,0x00000a56,0x00000a74,0x00000a55, -0x000200f9,0x00000a6a,0x000200f8,0x00000a57, -0x000500bc,0x0000003d,0x00000a59,0x000002d1, -0x00000049,0x000300f7,0x00000a5b,0x00000000, -0x000400fa,0x00000a59,0x00000a5a,0x00000a5b, -0x000200f8,0x00000a5a,0x000200f9,0x00000a6a, -0x000200f8,0x00000a5b,0x00060050,0x00000007, -0x00000a5e,0x000002d1,0x000002d1,0x000002d1, -0x00050088,0x00000007,0x00000a5f,0x000002ce, -0x00000a5e,0x00050094,0x00000006,0x00000a78, -0x000001c6,0x00000a5f,0x00050094,0x00000006, -0x00000a7a,0x000001cc,0x00000a5f,0x00050094, -0x00000006,0x00000a7c,0x000001d2,0x00000a5f, -0x00060050,0x00000007,0x00000a7d,0x00000a78, -0x00000a7a,0x00000a7c,0x00050041,0x000001ea, -0x00000a61,0x00000079,0x000001ed,0x0004003d, -0x00000006,0x00000a62,0x00000a61,0x00060050, -0x00000007,0x00000a63,0x00000a62,0x00000a62, -0x00000a62,0x00050088,0x00000007,0x00000a64, -0x00000a7d,0x00000a63,0x0007000c,0x00000007, -0x00000a66,0x00000001,0x00000028,0x00000a64, -0x00000113,0x000300f7,0x00000aad,0x00000000, -0x000300fb,0x000000e1,0x00000a86,0x000200f8, -0x00000a86,0x00050094,0x00000006,0x00000a88, -0x00000a66,0x000001dd,0x000500bc,0x0000003d, -0x00000a8a,0x00000a88,0x000001e0,0x000300f7, -0x00000a8d,0x00000000,0x000400fa,0x00000a8a, -0x00000a8b,0x00000a8d,0x000200f8,0x00000a8b, -0x000200f9,0x00000aad,0x000200f8,0x00000a8d, -0x00050041,0x000001ea,0x00000a8e,0x00000079, -0x000001e9,0x0004003d,0x00000006,0x00000a8f, -0x00000a8e,0x00050088,0x00000006,0x00000a92, -0x00000a8f,0x00000a62,0x0007000c,0x00000006, -0x00000a93,0x00000001,0x00000028,0x00000a92, -0x0000004a,0x00050083,0x00000006,0x00000a94, -0x00000a93,0x000001e0,0x00050083,0x00000006, -0x00000a98,0x00000a88,0x000001e0,0x00050085, -0x00000006,0x00000a9a,0x00000a98,0x00000ba9, -0x00050085,0x00000006,0x00000baf,0x00000a94, -0x00000a94,0x00050088,0x00000006,0x00000bb0, -0x00000a98,0x00000baf,0x00050085,0x00000006, -0x00000aa3,0x00000bad,0x00000bb0,0x00050081, -0x00000006,0x00000aa4,0x0000004a,0x00000aa3, -0x00050085,0x00000006,0x00000aa5,0x00000a98, -0x00000aa4,0x00050081,0x00000006,0x00000aa7, -0x0000004a,0x00000a9a,0x00050088,0x00000006, -0x00000aa8,0x00000aa5,0x00000aa7,0x00050081, -0x00000006,0x00000aa9,0x000001e0,0x00000aa8, -0x00050088,0x00000006,0x00000aab,0x00000aa9, -0x00000a88,0x0005008e,0x00000007,0x00000aac, -0x00000a66,0x00000aab,0x000200f9,0x00000aad, -0x000200f8,0x00000aad,0x000700f5,0x00000007, -0x00000b65,0x00000a66,0x00000a8b,0x00000aac, -0x00000a8d,0x0005008e,0x00000007,0x00000a69, -0x00000b65,0x000002d1,0x000200f9,0x00000a6a, -0x000200f8,0x00000a6a,0x000b00f5,0x00000007, -0x00000b66,0x000002ce,0x00000a4c,0x00000a56, -0x00000a51,0x00000113,0x00000a5a,0x00000a69, -0x00000aad,0x00050083,0x00000006,0x000002d6, -0x0000004a,0x000002d1,0x0005008e,0x00000007, -0x000002d8,0x00000b70,0x000002d6,0x00050081, -0x00000007,0x000002d9,0x00000b66,0x000002d8, -0x000200f9,0x000002b7,0x000200f8,0x000002b7, -0x000700f5,0x00000007,0x00000b91,0x00000b70, -0x000002ae,0x000002d9,0x00000a6a,0x0004003d, -0x000002da,0x000002dd,0x000002dc,0x00050041, -0x0000007b,0x00000ab4,0x00000079,0x0000020f, -0x0004003d,0x00000021,0x00000ab5,0x00000ab4, -0x000500ab,0x0000003d,0x00000ab6,0x00000ab5, -0x000000e1,0x000300f7,0x00000abf,0x00000000, -0x000400fa,0x00000ab6,0x00000ab7,0x00000abc, -0x000200f8,0x00000abc,0x00050041,0x0000007b, -0x00000ad9,0x00000079,0x0000007a,0x0004003d, -0x00000021,0x00000ada,0x00000ad9,0x000500aa, -0x0000003d,0x00000adb,0x00000ada,0x0000007e, -0x000300f7,0x00000ae5,0x00000000,0x000400fa, -0x00000adb,0x00000adc,0x00000ae2,0x000200f8, -0x00000ae2,0x0008000c,0x00000007,0x00000aec, -0x00000001,0x0000002b,0x00000b91,0x00000113, -0x00000b97,0x0005008e,0x00000007,0x00000aee, -0x00000aec,0x0000004f,0x0007000c,0x00000007, -0x00000af0,0x00000001,0x0000001a,0x00000aec, -0x00000054,0x0005008e,0x00000007,0x00000af1, -0x00000af0,0x00000051,0x00050083,0x00000007, -0x00000af3,0x00000af1,0x00000b9b,0x000500ba, -0x0000005d,0x00000af5,0x00000aec,0x0000005c, -0x000600a9,0x00000007,0x00000af6,0x00000af5, -0x00000af3,0x00000aee,0x000200f9,0x00000ae5, -0x000200f8,0x00000adc,0x0008000c,0x00000007, -0x00000ae0,0x00000001,0x0000002b,0x00000b91, -0x00000113,0x00000b97,0x0007000c,0x00000007, -0x00000ae1,0x00000001,0x0000001a,0x00000ae0, -0x0000009b,0x000200f9,0x00000ae5,0x000200f8, -0x00000ae5,0x000700f5,0x00000007,0x00000b92, -0x00000ae1,0x00000adc,0x00000af6,0x00000ae2, -0x000200f9,0x00000abf,0x000200f8,0x00000ab7, -0x0007000c,0x00000007,0x00000aba,0x00000001, -0x00000028,0x00000b91,0x00000113,0x00050085, -0x00000007,0x00000ac6,0x00000aba,0x00000bb2, -0x0008000c,0x00000007,0x00000ac9,0x00000001, -0x0000002b,0x00000ac6,0x00000113,0x00000b97, -0x0007000c,0x00000007,0x00000aca,0x00000001, -0x0000001a,0x00000ac9,0x000000c8,0x0005008e, -0x00000007,0x00000acc,0x00000aca,0x000000b3, -0x00050081,0x00000007,0x00000ace,0x00000b98, -0x00000acc,0x0005008e,0x00000007,0x00000ad0, -0x00000aca,0x000000b4,0x00050081,0x00000007, -0x00000ad2,0x00000b97,0x00000ad0,0x00050088, -0x00000007,0x00000ad3,0x00000ace,0x00000ad2, -0x0007000c,0x00000007,0x00000ad4,0x00000001, -0x0000001a,0x00000ad3,0x000000d4,0x000200f9, -0x00000abf,0x000200f8,0x00000abf,0x000700f5, -0x00000007,0x00000b93,0x00000ad4,0x00000ab7, -0x00000b92,0x00000ae5,0x00050051,0x00000006, -0x000002e2,0x00000b93,0x00000000,0x00050051, -0x00000006,0x000002e3,0x00000b93,0x00000001, -0x00050051,0x00000006,0x000002e4,0x00000b93, -0x00000002,0x00070050,0x00000023,0x000002e5, -0x000002e2,0x000002e3,0x000002e4,0x0000004a, -0x00040063,0x000002dd,0x00000255,0x000002e5, -0x000200f9,0x000002e7,0x000200f8,0x000002e7, -0x000100fd,0x00010038} diff --git a/runtime/src/present_compose_spv.h b/runtime/src/present_compose_spv.h deleted file mode 100644 index 966f31976..000000000 --- a/runtime/src/present_compose_spv.h +++ /dev/null @@ -1,11 +0,0 @@ -#pragma once -#include - -namespace leonida { - -// present_compose.comp compiled with: glslc --target-env=vulkan1.1 -O -mfmt=c present_compose.comp -o present_compose.inc -inline constexpr std::uint32_t present_compose_spirv[] = -#include "present_compose.inc" -; - -} // namespace leonida diff --git a/runtime/src/queue_families.h b/runtime/src/queue_families.h deleted file mode 100644 index 3148d0ad1..000000000 --- a/runtime/src/queue_families.h +++ /dev/null @@ -1,96 +0,0 @@ -#pragma once - -// Picking Vulkan queue families for D3D12's direct, compute and copy queues. Header-only and free of the rest of -// the backend, so test harnesses can use it too. - -#include - -#include -#include -#include -#include - -namespace leonida { - -// Queue families for D3D12's three queue types. Direct needs graphics. Compute prefers a family with compute and no -// graphics (async compute), copy one with transfer and neither (a DMA engine); each falls back to a more capable -// family, ending at the graphics one. A dedicated copy family is only used when its image transfer granularity is -// 1x1x1, because D3D12 copies any box. -struct QueueFamilies { - std::uint32_t direct = 0; - std::uint32_t compute = 0; - std::uint32_t copy = 0; -}; - -inline QueueFamilies pick_queue_families(std::span families, std::uint32_t graphics) { - QueueFamilies out{graphics, graphics, graphics}; - constexpr VkQueueFlags g = VK_QUEUE_GRAPHICS_BIT, c = VK_QUEUE_COMPUTE_BIT, t = VK_QUEUE_TRANSFER_BIT; - const auto fine_grained = [](const VkQueueFamilyProperties& f) { - return f.minImageTransferGranularity.width == 1 && f.minImageTransferGranularity.height == 1 && - f.minImageTransferGranularity.depth == 1; - }; - bool have_compute = false, have_copy = false; - for (std::uint32_t i = 0; i < families.size(); ++i) { - const auto& f = families[i]; - if (!f.queueCount) continue; - if (!have_compute && (f.queueFlags & c) && !(f.queueFlags & g)) { - out.compute = i; - have_compute = true; - } - if (!have_copy && (f.queueFlags & t) && !(f.queueFlags & (g | c)) && fine_grained(f)) { - out.copy = i; - have_copy = true; - } - } - // No DMA family: copies go to the async-compute family, which can transfer too (compute implies transfer). - if (!have_copy && have_compute && fine_grained(families[out.compute])) out.copy = out.compute; - return out; -} - -// A D3D12 COPY/COMPUTE queue may call UpdateTileMappings at any time. Vulkan binds sparse -// pages on the VkQueue itself, so a family without SPARSE_BINDING cannot back that D3D12 -// queue when reserved buffers are offered. Use the graphics family (already checked for -// sparse support by the device) rather than submitting an invalid vkQueueBindSparse. -// Kept separate from the preference-only picker so devices without sparse resources keep -// their dedicated async families unchanged. -inline QueueFamilies sparse_capable_queue_families(std::span families, - QueueFamilies chosen, bool sparse_buffers) { - if (!sparse_buffers || chosen.direct >= families.size() || - !(families[chosen.direct].queueFlags & VK_QUEUE_SPARSE_BINDING_BIT)) - return chosen; - if (chosen.compute >= families.size() || - !(families[chosen.compute].queueFlags & VK_QUEUE_SPARSE_BINDING_BIT)) - chosen.compute = chosen.direct; - if (chosen.copy >= families.size() || - !(families[chosen.copy].queueFlags & VK_QUEUE_SPARSE_BINDING_BIT)) - chosen.copy = chosen.direct; - return chosen; -} - -// Which VkQueue a new D3D12 queue runs on. `pools` are its candidate VkQueues in order of preference (a COMPUTE or -// COPY queue's own family first, then the graphics family); each entry counts the live D3D12 queues on that VkQueue. -// An unused VkQueue comes first, in pool order, so a GPU with enough queues keeps one VkQueue per live D3D12 queue -// (D3D-97). With none unused, the VkQueue with the fewest D3D12 queues is shared, the earliest on a tie: the D3D12 -// queues on it then run one after the other, in the order their batches reach it (docs/d3d12_vulkan.md 4.4). -// `pool` is SIZE_MAX when every pool is empty. -struct QueueSlot { - std::size_t pool = SIZE_MAX; - std::size_t index = 0; -}; - -inline QueueSlot pick_queue_slot(std::initializer_list> pools) { - QueueSlot chosen; // the first VkQueue with the fewest users: an unused one whenever there is one - std::uint32_t fewest = UINT32_MAX; - std::size_t p = 0; - for (const auto users : pools) { - for (std::size_t i = 0; i < users.size(); ++i) - if (users[i] < fewest) { - fewest = users[i]; - chosen = {p, i}; - } - ++p; - } - return chosen; -} - -} // namespace leonida diff --git a/runtime/src/queue_holds.h b/runtime/src/queue_holds.h deleted file mode 100644 index 2839d4210..000000000 --- a/runtime/src/queue_holds.h +++ /dev/null @@ -1,235 +0,0 @@ -#pragma once - -#include -#include -#include -#include -#include -#include -#include - -namespace leonida { - -// Cross-queue Wait-before-Signal (docs section 4.4, "Wait before Signal across queues"). -// -// A queue replays its ExecuteCommandLists against one device-wide layout tracker, in the order the calls reach the -// layer. When queue B calls Wait(fence, v) and the Signal(fence, v) on queue A is only submitted afterwards, B's -// lists would be replayed against the layouts from before A's work. So a queue holds a batch (and everything it -// is asked to do after it) while any fence it waits on has no submitted Signal of at least that value, and -// releases it, in order, once one has been submitted: the layouts then follow the dependency order, while Vulkan's -// own timeline semaphores still order the GPU work. -// -// This class is the device-wide half: for every fence, the highest value a Signal has been submitted for (or the -// CPU has set it to), which is not the completed value; the held queues, which it asks to release whatever became -// ready; and "after held work" callbacks (the presenter), which run once every operation held when they were -// registered has been released. It owns no Vulkan objects. Semaphores it was never told about count as satisfied, -// so a queue used with a plain VkSemaphore behaves as before. -// -// Threads. No GPU wait happens here, but the thread that makes a wait satisfiable (a queue's Signal, a CPU Signal) -// does the release itself, after it has dropped its own queue's state lock: it records and submits the held -// batches (a held ExecuteCommandLists costs what it would have cost when called, which includes whatever -// execute_now does: the bindless upload's wait for the device is one) and runs the callbacks. The COM wrapper -// still holds the mutex of the queue whose call that thread is in, so that queue's other calls wait meanwhile. -// One thread releases at a time; a thread that finds another one releasing leaves a note and that one takes -// another pass. detach() and cancel_after() (and remove_fence() from outside a release) wait for a running -// release. -template -class QueueHolds { -public: - // A queue that can hold batches. The calls take the queue's own lock; none is made with it held. - struct Holder { - // Releases the held operations at the front of the queue whose waits are satisfied. True if any was. - virtual bool release_ready() = 0; - // Drops the held operations that wait on `semaphore` (its fence is gone), reporting each. - virtual void discard_waiting_on(Semaphore semaphore) = 0; - // Sequence number (next_seq()) of the oldest held operation, 0 when nothing is held. - virtual std::uint64_t oldest_held_seq() = 0; - - protected: - ~Holder() = default; - }; - - void add_fence(Semaphore semaphore, std::uint64_t initial) { - std::lock_guard lock(mutex_); - fences_[semaphore] = initial; - } - - // The fence is gone. Operations that still reference it are dropped and reported (the COM layer keeps a fence - // alive while a held operation names it, so this is a safety net for direct users of VulkanFence). Not done - // from inside a release: the releasing thread already holds the lock, and what it is releasing cannot - // reference a fence whose last reference it is dropping, since that reference is the one it holds. - void remove_fence(Semaphore semaphore) { - { - std::lock_guard lock(mutex_); - fences_.erase(semaphore); - } - if (held_.load(std::memory_order_acquire) == 0 || in_pump()) return; - { - std::lock_guard pump(pump_mutex_); - in_pump() = true; // what is dropped may release other fences: they must not wait for this lock - for (Holder* holder : snapshot()) holder->discard_waiting_on(semaphore); - in_pump() = false; - } - pump_ready(); - } - - // A Signal of `value` was submitted to the GPU (or the CPU set the fence). Call after the submission, with no - // queue lock held; then pump_ready() to release what it satisfied. - void signaled(Semaphore semaphore, std::uint64_t value) { - std::lock_guard lock(mutex_); - const auto it = fences_.find(semaphore); - if (it != fences_.end() && it->second < value) it->second = value; - } - - // A queue is about to submit a Signal of `value`; call inside the device submit lock, and record the value with - // signaled() only once the vkQueueSubmit succeeded (a failed submit signals nothing: waiters must stay held and a - // retry must go through). False when a Signal of at least `value` was already submitted: the timeline cannot go - // down or stay (VUID-VkSubmitInfo-pSignalSemaphores-03242 and the timeline rules), and a wait for `value` is - // already satisfied, so the Vulkan signal is left out. This happens when a held Signal(F, 2) is released after an - // unheld Signal(F, 3). Unknown semaphores are always signaled. - bool would_signal(Semaphore semaphore, std::uint64_t value) const { - std::lock_guard lock(mutex_); - const auto it = fences_.find(semaphore); - return it == fences_.end() || it->second < value; - } - - // true when no submitted Signal reaches `value` yet. Unknown semaphores are satisfied. - bool pending(Semaphore semaphore, std::uint64_t value) const { - std::lock_guard lock(mutex_); - const auto it = fences_.find(semaphore); - return it != fences_.end() && it->second < value; - } - - void attach(Holder* holder) { - std::lock_guard lock(mutex_); - holders_.push_back(holder); - } - - // Returns once no thread is using `holder`. - void detach(Holder* holder) { - { - std::lock_guard pump(pump_mutex_); - std::lock_guard lock(mutex_); - for (auto it = holders_.begin(); it != holders_.end(); ++it) - if (*it == holder) { - holders_.erase(it); - break; - } - } - pump_ready(); - } - - // Sequence numbers of held operations, in the order they were held (across queues). - std::uint64_t next_seq() { return seq_.fetch_add(1, std::memory_order_acq_rel) + 1; } - std::uint64_t current_seq() const { return seq_.load(std::memory_order_acquire); } - - // Runs `fn` once every operation held up to now has been released (or dropped), on the thread that releases the - // last of them, or right here if none is held. Callbacks of one owner run in registration order. Used by the - // presenter: a Present queued behind held work shows what that work draws. - void after_held(const void* owner, std::function fn) { - { - std::lock_guard lock(mutex_); - barriers_.push_back({owner, current_seq(), std::move(fn)}); - barrier_count_.fetch_add(1, std::memory_order_acq_rel); - } - pump_ready(); - } - - // Drops the callbacks of `owner` that have not run, and waits for one that is running. - void cancel_after(const void* owner) { - { - std::lock_guard pump(pump_mutex_); - std::lock_guard lock(mutex_); - for (auto it = barriers_.begin(); it != barriers_.end();) - if (it->owner == owner) { - it = barriers_.erase(it); - barrier_count_.fetch_sub(1, std::memory_order_acq_rel); - } else { - ++it; - } - } - pump_ready(); - } - - // Held operations over all queues, for the cheap "is there anything to do" test. - void held_changed(std::int64_t delta) { held_.fetch_add(delta, std::memory_order_acq_rel); } - bool any_held() const { return held_.load(std::memory_order_acquire) > 0; } - - // Releases every held operation that has become ready, in dependency order: a release can submit a Signal - // that makes another queue's front ready, so passes repeat until one finds nothing new. Then the callbacks - // whose held work is all gone. - void pump_ready() { - if (!any_held() && barrier_count_.load(std::memory_order_acquire) == 0) return; - dirty_.store(true, std::memory_order_release); - if (in_pump()) return; // a release on this thread submitted a Signal: the running pass will go again - for (;;) { - std::unique_lock pump(pump_mutex_, std::try_to_lock); - if (!pump) return; // another thread is releasing and will see dirty_ - in_pump() = true; - while (dirty_.exchange(false, std::memory_order_acq_rel)) { - bool progress = true; - while (progress) { - progress = false; - for (Holder* holder : snapshot()) progress |= holder->release_ready(); - } - run_barriers(); - } - in_pump() = false; - pump.unlock(); - if (!dirty_.load(std::memory_order_acquire)) return; - } - } - -private: - struct Barrier { - const void* owner; - std::uint64_t seq; - std::function fn; - }; - - static bool& in_pump() { - static thread_local bool pumping = false; - return pumping; - } - - std::vector snapshot() const { - std::lock_guard lock(mutex_); - return holders_; - } - - // Called with pump_mutex_ held. A callback runs when no held operation is older than the moment it was asked. - void run_barriers() { - for (;;) { - Barrier front; - { - std::lock_guard lock(mutex_); - if (barriers_.empty()) return; - front = barriers_.front(); - } - for (Holder* holder : snapshot()) { - const std::uint64_t oldest = holder->oldest_held_seq(); - if (oldest && oldest <= front.seq) return; - } - { - std::lock_guard lock(mutex_); - if (barriers_.empty() || barriers_.front().seq != front.seq || barriers_.front().owner != front.owner) - continue; // cancelled meanwhile - barriers_.pop_front(); - barrier_count_.fetch_sub(1, std::memory_order_acq_rel); - } - front.fn(); - } - } - - mutable std::mutex mutex_; // leaf: fences_, holders_ and barriers_ - std::mutex pump_mutex_; // one releasing thread; held across release_ready(), so detach() waits for it - std::unordered_map fences_; - std::vector holders_; - std::deque barriers_; - std::atomic held_{0}; - std::atomic barrier_count_{0}; - std::atomic seq_{0}; - std::atomic dirty_{false}; -}; - -} // namespace leonida diff --git a/runtime/src/resource_detile.h b/runtime/src/resource_detile.h deleted file mode 100644 index 74f22aac5..000000000 --- a/runtime/src/resource_detile.h +++ /dev/null @@ -1,294 +0,0 @@ -#pragma once - -// Detiling and tiling for AMD GFX10 / RDNA2 console-tiled resources (docs/d3d12_vulkan.md section 4.2). -// -// Resources created through Xbox slot 76 carry layout 0x101 (kXboxTiledLayout). -// The data layout inside each 64 KiB tile is GFX10 SW_64KB_D (Mesa addrlib GFX10_SW_64K_D_RBPLUS_PATINFO): -// 64 KiB macro-blocks are laid out in row-major order across the surface, and intra-tile coordinates (x, y) -// are swizzled into byte offsets via bit-permutation equations matching RDNA2 / Xbox Series hardware. -// -// Independent X and Y coordinate bit mappings permit O(1) intra-tile offset resolution via compile-time -// lookup tables (lut_x[x % tile_w] | lut_y[y % tile_h]). No Windows or Vulkan dependency. - -#include "resource_tiling.h" - -#include -#include -#include -#include -#include -#include -#include -#include - -namespace leonida { - -// The Xbox tiled layout word (device slot 76, docs/d3d12_vulkan.md section 4.2). -inline constexpr std::uint32_t xbox_tiled_layout = 0x101; - -constexpr bool is_xbox_tiled(std::uint32_t layout) { - return layout == xbox_tiled_layout; -} - -// Intra-tile bit permutation equations for 64 KiB tiles (Mesa addrlib GFX10_SW_64K_D_RBPLUS_PATINFO). -// For each bit 0..15: -// s > 0: bit is ((x >> (s - 1)) & 1) -// s < 0: bit is ((y >> (-s - 1)) & 1) -// s == 0: intra-element byte bit (element_bytes > 1) -template -struct SwizzleLut64K { - static constexpr std::uint32_t bpe = ElementBytes; - static constexpr TileShape shape = element_tile_shape(false, bpe); - static constexpr std::uint32_t tile_w = shape.width; - static constexpr std::uint32_t tile_h = shape.height; - - std::array lut_x{}; - std::array lut_y{}; - - constexpr SwizzleLut64K() { - constexpr std::array pat = []() { - if constexpr (bpe == 1) { - return std::array{1, 2, 3, -2, -1, -3, 4, -4, -5, 5, -6, 6, -7, 7, -8, 8}; - } else if constexpr (bpe == 2) { - return std::array{0, 1, 2, 3, -1, -2, -3, 4, -4, 5, -5, 6, -6, 7, -7, 8}; - } else if constexpr (bpe == 4) { - // RDNA2/RbPlus SW_64KB_D: bits 6..7 swapped vs Navi 1x ((3, -3) instead of (-3, 3)) - return std::array{0, 0, 1, 2, -1, -2, 3, -3, -4, 4, -5, 5, -6, 6, -7, 7}; - } else if constexpr (bpe == 8) { - return std::array{0, 0, 0, 1, -1, 2, 3, -2, -3, 4, -4, 5, -5, 6, -6, 7}; - } else if constexpr (bpe == 16) { - return std::array{0, 0, 0, 0, 1, -1, 2, -2, -3, 3, -4, 4, -5, 5, -6, 6}; - } else { - return std::array{}; - } - }(); - - for (std::uint32_t x = 0; x < tile_w; ++x) { - std::uint16_t val = 0; - for (std::uint32_t bit = 0; bit < 16; ++bit) { - const int8_t s = pat[bit]; - if (s > 0) { - val |= static_cast(((x >> (s - 1)) & 1) << bit); - } - } - lut_x[x] = val; - } - - for (std::uint32_t y = 0; y < tile_h; ++y) { - std::uint16_t val = 0; - for (std::uint32_t bit = 0; bit < 16; ++bit) { - const int8_t s = pat[bit]; - if (s < 0) { - val |= static_cast(((y >> (-s - 1)) & 1) << bit); - } - } - lut_y[y] = val; - } - } -}; - -inline constexpr SwizzleLut64K<1> swizzle_lut_64k_1bpe{}; -inline constexpr SwizzleLut64K<2> swizzle_lut_64k_2bpe{}; -inline constexpr SwizzleLut64K<4> swizzle_lut_64k_4bpe{}; -inline constexpr SwizzleLut64K<8> swizzle_lut_64k_8bpe{}; -inline constexpr SwizzleLut64K<16> swizzle_lut_64k_16bpe{}; - -namespace detail { - -constexpr bool checked_mul(std::size_t a, std::size_t b, std::size_t& out) { - if (a != 0 && b > (std::numeric_limits::max)() / a) return false; - out = a * b; - return true; -} - -struct SurfaceLayout64K { - std::uint32_t blocks_w = 0; - std::uint32_t blocks_h = 0; - std::uint32_t tiles_x = 0; - std::uint32_t tiles_y = 0; - std::size_t linear_bytes = 0; - std::size_t tiled_bytes = 0; -}; - -constexpr bool compute_surface_layout_64k(std::uint32_t width, std::uint32_t height, - std::uint32_t element_bytes, std::uint32_t block_dim, - SurfaceLayout64K& out) { - if (!width || !height || (block_dim != 1 && block_dim != 4)) return false; - const TileShape shape = element_tile_shape(false, element_bytes); - if (!shape.width || !shape.height) return false; - - // Overflow-free ceiling division for positive uint32_t operands: 1 + (n - 1) / d. - const std::uint32_t blocks_w = 1u + (width - 1u) / block_dim; - const std::uint32_t blocks_h = 1u + (height - 1u) / block_dim; - const std::uint32_t tiles_x = 1u + (blocks_w - 1u) / shape.width; - const std::uint32_t tiles_y = 1u + (blocks_h - 1u) / shape.height; - - std::size_t block_count = 0; - std::size_t linear_bytes = 0; - std::size_t tile_count = 0; - std::size_t tiled_bytes = 0; - if (!checked_mul(blocks_w, blocks_h, block_count) || - !checked_mul(block_count, element_bytes, linear_bytes) || - !checked_mul(tiles_x, tiles_y, tile_count) || - !checked_mul(tile_count, tile_size_in_bytes, tiled_bytes)) { - return false; - } - - out = {blocks_w, blocks_h, tiles_x, tiles_y, linear_bytes, tiled_bytes}; - return true; -} - -inline bool spans_overlap(const std::byte* a, std::size_t a_len, - const std::byte* b, std::size_t b_len) { - if (!a_len || !b_len) return false; - const std::less lt{}; - return lt(a, b + b_len) && lt(b, a + a_len); -} - -} // namespace detail - -// Compute required tiled byte size for a 2D surface of the given dimensions (0 on invalid input or overflow). -constexpr std::size_t tiled_surface_size_64k(std::uint32_t width, std::uint32_t height, - std::uint32_t element_bytes, std::uint32_t block_dim = 1) { - detail::SurfaceLayout64K layout{}; - return detail::compute_surface_layout_64k(width, height, element_bytes, block_dim, layout) - ? layout.tiled_bytes - : 0; -} - -// Compute required linear byte size for a 2D surface of the given dimensions (0 on invalid input or overflow). -constexpr std::size_t linear_surface_size(std::uint32_t width, std::uint32_t height, - std::uint32_t element_bytes, std::uint32_t block_dim = 1) { - detail::SurfaceLayout64K layout{}; - return detail::compute_surface_layout_64k(width, height, element_bytes, block_dim, layout) - ? layout.linear_bytes - : 0; -} - -namespace detail { - -template -void detile_typed(std::span tiled, std::span linear, - std::uint32_t blocks_w, std::uint32_t blocks_h, std::uint32_t tiles_x) { - constexpr const auto& lut = []() constexpr -> const auto& { - if constexpr (Bpe == 1) return swizzle_lut_64k_1bpe; - else if constexpr (Bpe == 2) return swizzle_lut_64k_2bpe; - else if constexpr (Bpe == 4) return swizzle_lut_64k_4bpe; - else if constexpr (Bpe == 8) return swizzle_lut_64k_8bpe; - else if constexpr (Bpe == 16) return swizzle_lut_64k_16bpe; - }(); - - constexpr std::uint32_t tile_w = lut.tile_w; - constexpr std::uint32_t tile_h = lut.tile_h; - - for (std::uint32_t y = 0; y < blocks_h; ++y) { - const std::uint32_t ty = y / tile_h; - const std::uint16_t intra_y = lut.lut_y[y % tile_h]; - const std::size_t macro_y_base = static_cast(ty) * tiles_x * tile_size_in_bytes; - const std::size_t linear_row = static_cast(y) * blocks_w * Bpe; - - for (std::uint32_t x = 0; x < blocks_w; ++x) { - const std::uint32_t tx = x / tile_w; - const std::uint16_t intra_x = lut.lut_x[x % tile_w]; - const std::size_t tiled_off = macro_y_base + static_cast(tx) * tile_size_in_bytes + (intra_x | intra_y); - const std::size_t linear_off = linear_row + static_cast(x) * Bpe; - - std::memcpy(&linear[linear_off], &tiled[tiled_off], Bpe); - } - } -} - -template -void tile_typed(std::span linear, std::span tiled, - std::uint32_t blocks_w, std::uint32_t blocks_h, std::uint32_t tiles_x) { - constexpr const auto& lut = []() constexpr -> const auto& { - if constexpr (Bpe == 1) return swizzle_lut_64k_1bpe; - else if constexpr (Bpe == 2) return swizzle_lut_64k_2bpe; - else if constexpr (Bpe == 4) return swizzle_lut_64k_4bpe; - else if constexpr (Bpe == 8) return swizzle_lut_64k_8bpe; - else if constexpr (Bpe == 16) return swizzle_lut_64k_16bpe; - }(); - - constexpr std::uint32_t tile_w = lut.tile_w; - constexpr std::uint32_t tile_h = lut.tile_h; - - for (std::uint32_t y = 0; y < blocks_h; ++y) { - const std::uint32_t ty = y / tile_h; - const std::uint16_t intra_y = lut.lut_y[y % tile_h]; - const std::size_t macro_y_base = static_cast(ty) * tiles_x * tile_size_in_bytes; - const std::size_t linear_row = static_cast(y) * blocks_w * Bpe; - - for (std::uint32_t x = 0; x < blocks_w; ++x) { - const std::uint32_t tx = x / tile_w; - const std::uint16_t intra_x = lut.lut_x[x % tile_w]; - const std::size_t tiled_off = macro_y_base + static_cast(tx) * tile_size_in_bytes + (intra_x | intra_y); - const std::size_t linear_off = linear_row + static_cast(x) * Bpe; - - std::memcpy(&tiled[tiled_off], &linear[linear_off], Bpe); - } - } -} - -} // namespace detail - -// Detile a 2D surface from console-tiled 64 KiB layout into linear row-major order. -inline bool detile_surface_64k(std::span tiled, std::span linear, - std::uint32_t width, std::uint32_t height, - std::uint32_t element_bytes, std::uint32_t block_dim = 1) { - detail::SurfaceLayout64K layout{}; - if (!detail::compute_surface_layout_64k(width, height, element_bytes, block_dim, layout)) return false; - if (linear.size() < layout.linear_bytes || tiled.size() < layout.tiled_bytes) return false; - if (detail::spans_overlap(tiled.data(), layout.tiled_bytes, linear.data(), layout.linear_bytes)) return false; - - switch (element_bytes) { - case 1: - detail::detile_typed<1>(tiled, linear, layout.blocks_w, layout.blocks_h, layout.tiles_x); - return true; - case 2: - detail::detile_typed<2>(tiled, linear, layout.blocks_w, layout.blocks_h, layout.tiles_x); - return true; - case 4: - detail::detile_typed<4>(tiled, linear, layout.blocks_w, layout.blocks_h, layout.tiles_x); - return true; - case 8: - detail::detile_typed<8>(tiled, linear, layout.blocks_w, layout.blocks_h, layout.tiles_x); - return true; - case 16: - detail::detile_typed<16>(tiled, linear, layout.blocks_w, layout.blocks_h, layout.tiles_x); - return true; - default: - return false; - } -} - -// Tile a 2D surface from linear row-major order into console-tiled 64 KiB layout. -inline bool tile_surface_64k(std::span linear, std::span tiled, - std::uint32_t width, std::uint32_t height, - std::uint32_t element_bytes, std::uint32_t block_dim = 1) { - detail::SurfaceLayout64K layout{}; - if (!detail::compute_surface_layout_64k(width, height, element_bytes, block_dim, layout)) return false; - if (linear.size() < layout.linear_bytes || tiled.size() < layout.tiled_bytes) return false; - if (detail::spans_overlap(linear.data(), layout.linear_bytes, tiled.data(), layout.tiled_bytes)) return false; - - switch (element_bytes) { - case 1: - detail::tile_typed<1>(linear, tiled, layout.blocks_w, layout.blocks_h, layout.tiles_x); - return true; - case 2: - detail::tile_typed<2>(linear, tiled, layout.blocks_w, layout.blocks_h, layout.tiles_x); - return true; - case 4: - detail::tile_typed<4>(linear, tiled, layout.blocks_w, layout.blocks_h, layout.tiles_x); - return true; - case 8: - detail::tile_typed<8>(linear, tiled, layout.blocks_w, layout.blocks_h, layout.tiles_x); - return true; - case 16: - detail::tile_typed<16>(linear, tiled, layout.blocks_w, layout.blocks_h, layout.tiles_x); - return true; - default: - return false; - } -} - -} // namespace leonida diff --git a/runtime/src/resource_tiling.h b/runtime/src/resource_tiling.h deleted file mode 100644 index 99302f2b7..000000000 --- a/runtime/src/resource_tiling.h +++ /dev/null @@ -1,196 +0,0 @@ -#pragma once - -// How a D3D12 reserved (tiled) resource divides into 64 KiB tiles: ID3D12Device::GetResourceTiling -// (docs/d3d12_vulkan.md section 4.2). No Windows or Vulkan dependency. -// -// What D3D12 defines, and d3d12_vulkan_device_test compares with the PC runtime: the standard tile shape for each -// element size, that a mip filling at least one tile shape in every dimension is standard, the tile counts of every -// standard mip, and the order of the tiles: each array slice holds its standard mips in order, then its packed tiles. -// -// What a driver chooses (D3D11.3 functional spec 5.9.2.8.5: a mip with any dimension below the tile "may or may not -// be packed, depending on the IHV"): where the packed tail starts, and how many tiles the packed mips take. Here -// a mip stays standard while it is wider than half the tile or taller than the tile (depth does not count), as -// AMD's PC runtime does on RDNA2 and RDNA4 (D3D-65; the console is AMD): measured on the 47 layouts of #868, see -// resource_tiling_test. A standard mip may be smaller than a tile and then takes one tile on that axis. An NVIDIA -// GPU packs from the first mip smaller than a tile on any axis and WARP packs nothing; the test accepts all of -// them. The packed tail takes one tile per tile-depth slice it spans: ceil(depth of the first packed mip / tile -// depth), so 1 for 2D, as AMD's PC runtime reports on RDNA2 and RDNA4 (those 47 and 32 deeper volumes, see -// resource_tiling_test), and never fewer than the tail's tight linear size in whole tiles. NVIDIA sometimes reports -// one more. Applications read the numbers rather than assume them, and this layer backs reserved textures fully, so -// any split is consistent. - -#include -#include -#include -#include - -namespace leonida { - -inline constexpr std::uint32_t tile_size_in_bytes = 65536; // D3D12_TILED_RESOURCE_TILE_SIZE_IN_BYTES -inline constexpr std::uint32_t packed_tile = 0xffffffff; // D3D12_PACKED_TILE - -// In texels, or in bytes for a buffer (65536 x 1 x 1). -struct TileShape { - std::uint32_t width = 0; - std::uint32_t height = 0; - std::uint32_t depth = 0; -}; - -enum class TiledKind { buffer, texture2d, texture3d }; - -struct TilingDesc { - TiledKind kind = TiledKind::texture2d; - std::uint64_t width = 0; // bytes for a buffer - std::uint32_t height = 1; - std::uint32_t depth_or_layers = 1; // depth for a volume, array size otherwise - std::uint32_t mips = 1; - std::uint32_t element_bytes = 0; // bytes per texel, or per block of a block-compressed format - std::uint32_t block = 1; // texels per block side: 4 for BC1-7 - std::uint32_t samples = 1; // 1, or 4 for 2D single-mip MSAA -}; - -// D3D12_SUBRESOURCE_TILING: a packed mip has no tiles of its own and starts at packed_tile. -struct SubresourceTiling { - std::uint32_t width = 0; - std::uint32_t height = 0; - std::uint32_t depth = 0; - std::uint32_t start = 0; -}; - -struct ResourceTiling { - std::uint32_t total_tiles = 0; - TileShape shape; - std::uint32_t standard_mips = 0; // D3D12_PACKED_MIP_INFO, per array slice - std::uint32_t packed_mips = 0; - std::uint32_t packed_tiles = 0; - std::uint32_t packed_start = 0; // the first packed tile of slice 0; 0 without packed mips - std::vector subresources; // mip + layer * mips -}; - -// The standard tile shape in elements (D3D12 "standard swizzle" tile shapes for 64 KiB tiles; 2D 4x MSAA scales the -// tile shape down by 4 samples per texel, measured on RTX 5070 Ti and WARP), or {} for an unsupported sample count or -// an element size that cannot be tiled (3- and 12-byte formats). -constexpr TileShape element_tile_shape(bool volume, std::uint32_t element_bytes, std::uint32_t samples = 1) { - if (samples == 4) { - if (volume) return {}; - switch (element_bytes) { - case 1: return {128, 128, 1}; - case 2: return {128, 64, 1}; - case 4: return {64, 64, 1}; - case 8: return {64, 32, 1}; - case 16: return {32, 32, 1}; - default: return {}; - } - } - if (samples != 1) return {}; - switch (element_bytes) { - case 1: return volume ? TileShape{64, 32, 32} : TileShape{256, 256, 1}; - case 2: return volume ? TileShape{32, 32, 32} : TileShape{256, 128, 1}; - case 4: return volume ? TileShape{32, 32, 16} : TileShape{128, 128, 1}; - case 8: return volume ? TileShape{32, 16, 16} : TileShape{128, 64, 1}; - case 16: return volume ? TileShape{16, 16, 16} : TileShape{64, 64, 1}; - default: return {}; - } -} - -// The 4 KiB tile shape in elements the PC runtime counts to allow D3D12_SMALL_RESOURCE_PLACEMENT_ALIGNMENT (16 of -// them must cover a texture's top mip), or {} as above. Measured with GetResourceAllocationInfo on an RTX 5070 and -// WARP (d3d12_vulkan_device_test). -constexpr TileShape small_tile_shape(bool volume, std::uint32_t element_bytes) { - switch (element_bytes) { - case 1: return volume ? TileShape{16, 16, 16} : TileShape{64, 64, 1}; - case 2: return volume ? TileShape{16, 16, 8} : TileShape{64, 32, 1}; - case 4: return volume ? TileShape{16, 8, 8} : TileShape{32, 32, 1}; - case 8: return volume ? TileShape{8, 8, 8} : TileShape{32, 16, 1}; - case 16: return volume ? TileShape{8, 8, 4} : TileShape{16, 16, 1}; - default: return {}; - } -} - -// False when the resource cannot be tiled: an unknown kind, an untileable element size, out-of-range mips/layers/extents, or more than 2^32 tiles. -inline bool resource_tiling(const TilingDesc& desc, ResourceTiling& out) { - out = {}; - constexpr std::uint64_t max_tiles = 0xffffffffu; - constexpr std::uint64_t max_packed_bytes = max_tiles * tile_size_in_bytes; - constexpr std::uint32_t max_mips = 0xffu; // D3D12_PACKED_MIP_INFO mip counters are UINT8 - constexpr std::uint32_t max_depth_or_layers = 0xffffu; // D3D12_RESOURCE_DESC::DepthOrArraySize is UINT16 - constexpr std::uint64_t max_subresource_extent_16 = 0xffffu; // D3D12_SUBRESOURCE_TILING HeightInTiles / DepthInTiles are UINT16 - const auto up = [](std::uint64_t value, std::uint64_t by) -> std::uint64_t { - return value ? 1 + (value - 1) / by : 0; - }; - if (desc.kind == TiledKind::buffer) { - const std::uint64_t tiles = up(desc.width, tile_size_in_bytes); - if (!tiles || tiles > max_tiles) return false; - out.total_tiles = std::uint32_t(tiles); - out.shape = {tile_size_in_bytes, 1, 1}; - out.subresources = {{out.total_tiles, 1, 1, 0}}; - return true; - } - if (desc.kind != TiledKind::texture2d && desc.kind != TiledKind::texture3d) return false; - const bool volume = desc.kind == TiledKind::texture3d; - if (desc.samples != 1 && (desc.samples != 4 || volume || desc.mips != 1 || desc.block != 1)) return false; - const TileShape elements = element_tile_shape(volume, desc.element_bytes, desc.samples); - if (!elements.width || !desc.mips || desc.mips > max_mips || !desc.block || !desc.width || !desc.height || - !desc.depth_or_layers || desc.depth_or_layers > max_depth_or_layers) - return false; - const std::uint64_t shape_w = std::uint64_t(elements.width) * desc.block; - const std::uint64_t shape_h = std::uint64_t(elements.height) * desc.block; - if (shape_w > 0xffffffffu || shape_h > 0xffffffffu) return false; - ResourceTiling result; - result.shape = {std::uint32_t(shape_w), std::uint32_t(shape_h), elements.depth}; - const std::uint32_t layers = volume ? 1 : desc.depth_or_layers; - const std::uint32_t depth = volume ? desc.depth_or_layers : 1; - - // One array slice: standard mips while wider than half a tile or taller than a tile, then the packed tail. - std::vector slice(desc.mips); - std::uint64_t standard_tiles = 0, packed_bytes = 0; - std::uint32_t tail_depth = 0; // depth of the first packed mip - for (std::uint32_t mip = 0; mip < desc.mips; ++mip) { - const std::uint64_t w = mip >= 64 ? 1 : std::max(1, desc.width >> mip); - const std::uint32_t h = mip >= 32 ? 1u : std::max(1u, desc.height >> mip); - const std::uint32_t d = mip >= 32 ? 1u : std::max(1u, depth >> mip); - const bool standard = result.packed_mips == 0 && (w > result.shape.width / 2 || h > result.shape.height); - if (standard) { - const std::uint64_t tw = up(w, result.shape.width); - const std::uint64_t th = up(h, result.shape.height); - const std::uint64_t td = up(d, result.shape.depth); - if (tw > max_tiles || th > max_subresource_extent_16 || td > max_subresource_extent_16) return false; - const std::uint64_t xy = tw * th; - if (xy > max_tiles || xy > max_tiles / td) return false; - const std::uint64_t mip_tiles = xy * td; - if (mip_tiles > max_tiles - standard_tiles) return false; - slice[mip] = {std::uint32_t(tw), std::uint32_t(th), std::uint32_t(td), std::uint32_t(standard_tiles)}; - standard_tiles += mip_tiles; - ++result.standard_mips; - } else { - slice[mip] = {0, 0, 0, packed_tile}; - const std::uint64_t row_slice_bytes = - up(w, desc.block) * up(h, desc.block) * desc.element_bytes * desc.samples; - if (d > (max_packed_bytes - packed_bytes) / row_slice_bytes) return false; - packed_bytes += row_slice_bytes * d; - if (result.packed_mips == 0) tail_depth = d; - ++result.packed_mips; - } - } - // One tile per tile-depth slice of the tail (AMD), at least its tight size; 1 for 2D. - const std::uint64_t packed_tiles = - result.packed_mips ? std::max({1, up(packed_bytes, tile_size_in_bytes), - up(tail_depth, result.shape.depth)}) - : 0; - if (packed_tiles > max_tiles - standard_tiles) return false; - const std::uint64_t per_slice = standard_tiles + packed_tiles; - if (per_slice > max_tiles / layers) return false; - result.packed_tiles = std::uint32_t(packed_tiles); - result.packed_start = result.packed_mips ? std::uint32_t(standard_tiles) : 0; - result.total_tiles = std::uint32_t(per_slice * layers); - result.subresources.reserve(std::size_t(desc.mips) * layers); - for (std::uint32_t layer = 0; layer < layers; ++layer) - for (SubresourceTiling s : slice) { - if (s.start != packed_tile) s.start += std::uint32_t(per_slice * layer); - result.subresources.push_back(s); - } - out = std::move(result); - return true; -} - -} // namespace leonida diff --git a/runtime/src/retire_tickets.h b/runtime/src/retire_tickets.h deleted file mode 100644 index a48302859..000000000 --- a/runtime/src/retire_tickets.h +++ /dev/null @@ -1,60 +0,0 @@ -#pragma once - -#include -#include -#include -#include - -namespace leonida { - -// Global submission tickets may finish out of order on independent Vulkan queues. Only the -// contiguous completed prefix is safe for deferred resource destruction. The caller serializes -// record(), completed() and queue_idle() with the device submission mutex. record() must -// receive strictly increasing global ticket numbers; otherwise a duplicate or backward ticket -// can make the completed prefix stall or move backward. -template -class RetireTickets { -public: - void record(std::uint64_t ticket, Semaphore semaphore, std::uint64_t value) { - pending_.push_back({ticket, semaphore, value, false}); - } - - template - std::uint64_t completed(Query&& query) { - while (!pending_.empty()) { - const Entry& front = pending_.front(); - if (!front.idle && !query(front.semaphore, front.value)) break; - completed_ = front.ticket; - pending_.pop_front(); - } - return completed_; - } - - // The (semaphore, value) of every submission up to `ticket` that has not been seen complete: what a caller - // that must have them done (and may not hold the lock that guards this object while it waits) waits for. - std::vector> pending_through(std::uint64_t ticket) const { - std::vector> out; - for (const Entry& entry : pending_) - if (entry.ticket <= ticket && !entry.idle) out.emplace_back(entry.semaphore, entry.value); - return out; - } - - // Call only after the owning queue's wait-idle succeeded. Merely requesting idle does not - // prove its submissions completed and must not advance the retirement prefix. - void queue_idle(Semaphore semaphore) { - for (Entry& entry : pending_) - if (entry.semaphore == semaphore) entry.idle = true; - } - -private: - struct Entry { - std::uint64_t ticket; - Semaphore semaphore; - std::uint64_t value; - bool idle; - }; - std::deque pending_; - std::uint64_t completed_ = 0; -}; - -} // namespace leonida diff --git a/runtime/src/root_signature.cpp b/runtime/src/root_signature.cpp deleted file mode 100644 index a0eb96cce..000000000 --- a/runtime/src/root_signature.cpp +++ /dev/null @@ -1,518 +0,0 @@ -// Portable root-signature packer, see root_signature.h. -#include "root_signature.h" - -#include - -namespace rt::rootsig { - -PackResult pack(const RootSignature& sig) { - PackResult out; - if (sig.params.size() > 64) { - out.error = "root signature has more than 64 root parameters"; - return out; - } - uint64_t cost = 0; // 64-bit: a parameter of 0xFFFFFFFF constants must not wrap past the limits - for (const RootParameter& p : sig.params) { - if (p.type != ParamType::Constants && p.type != ParamType::Descriptor && p.type != ParamType::Table) { - out.error = "unknown root parameter type"; - return out; - } - if (p.type == ParamType::Constants && p.num_values == 0) { - out.error = "root constant parameter needs at least 1 dword"; - return out; - } - const uint32_t dwords = p.type == ParamType::Table ? 2 - : p.type == ParamType::Descriptor ? 2 - : p.num_values; - cost += param_cost(p.type, p.num_values); - if (cost > kMaxD3d12Cost) { - out.error = "root signature exceeds the 64-dword D3D12 cost limit"; - return out; - } - if (uint64_t(out.dword_count) + dwords > kMaxUserSgprs) { - // Spill layout is unknown (see __XB_GetRootSignatureSpillPointer): - // refuse loudly instead of silently truncating every draw. - out.error = "root signature needs more than 32 user SGPRs (spill unsupported)"; - return out; - } - const uint32_t param_index = - static_cast(&p - sig.params.data()); - for (uint32_t i = 0; i < dwords; ++i) { - out.dwords[out.dword_count] = 0; // filled at bind time - out.provenance.push_back({param_index, i}); - ++out.dword_count; - } - } - out.d3d12_cost = static_cast(cost); // <= kMaxD3d12Cost here - out.ok = true; - return out; -} - -StagePackResult pack_stage(const RootSignature& sig, Stage stage) { - StagePackResult out; - out.stage = stage; - out.base = stage_base(stage); - out.end_sgpr = out.base; - if (sig.params.size() > 64) { - out.error = "root signature has more than 64 root parameters"; - return out; - } - uint64_t cost = 0; // 64-bit, as in pack() - uint64_t next = out.base; - std::vector first; - first.reserve(sig.params.size()); - for (size_t i = 0; i < sig.params.size(); ++i) { - const RootParameter& p = sig.params[i]; - if (p.type == ParamType::Constants && p.num_values == 0) { - out.error = "root constant parameter needs at least 1 dword"; - return out; - } - cost += param_cost(p.type, p.num_values); - if (cost > kMaxD3d12Cost) { - out.error = "root signature exceeds the 64-dword D3D12 cost limit"; - return out; - } - const uint64_t dwords = stage_dwords(p.type, p.num_values); - if (next + dwords > kMaxUserSgprs) { - // The console moves this parameter and every later one to the spill array behind s[0:1]; that array's - // layout is not modelled here, so refuse rather than drop arguments. - out.error = "root parameter " + std::to_string(i) + " does not fit in the user SGPRs from s" + - std::to_string(out.base) + " (spill array not modelled)"; - return out; - } - first.push_back(static_cast(next)); - next += dwords; - } - out.first_sgpr = std::move(first); - out.end_sgpr = static_cast(next); - out.d3d12_cost = static_cast(cost); - out.ok = true; - return out; -} - -namespace { - -void put_u32(std::vector& out, uint32_t v) { - out.push_back(static_cast(v)); - out.push_back(static_cast(v >> 8)); - out.push_back(static_cast(v >> 16)); - out.push_back(static_cast(v >> 24)); -} - -void put_f32(std::vector& out, float v) { - uint32_t bits = 0; - static_assert(sizeof(bits) == sizeof(v)); - std::memcpy(&bits, &v, sizeof(bits)); - put_u32(out, bits); -} - -class Reader { -public: - Reader(const uint8_t* data, size_t size) : data_(data), size_(size) {} - - [[nodiscard]] bool u32(uint32_t& v) { - if (pos_ + 4 > size_) return false; - v = static_cast(data_[pos_]) | - (static_cast(data_[pos_ + 1]) << 8) | - (static_cast(data_[pos_ + 2]) << 16) | - (static_cast(data_[pos_ + 3]) << 24); - pos_ += 4; - return true; - } - - [[nodiscard]] bool f32(float& v) { - uint32_t bits = 0; - if (!u32(bits)) return false; - std::memcpy(&v, &bits, sizeof(v)); - return true; - } - - [[nodiscard]] bool at_end() const { return pos_ == size_; } - -private: - const uint8_t* data_ = nullptr; - size_t size_ = 0; - size_t pos_ = 0; -}; - -constexpr uint32_t kCanonicalMagic = 0x3153524Cu; // "LRS1" little-endian -// 2: ranges store all six D3D12_DESCRIPTOR_RANGE1 fields (1 stored only type and count). Nothing persists these -// blobs across builds, so version 1 is simply refused. -constexpr uint32_t kCanonicalVersion = 2; - -// D3D_ROOT_SIGNATURE_VERSION 1 (1.0), 2 (1.1), 3 (1.2): the numbering RTS0 and the canonical codec both store. -bool known_version(uint32_t v, Version& out) { - if (v < 1 || v > 3) return false; - out = static_cast(v); - return true; -} - -} // namespace - -std::vector encode_canonical(const RootSignature& sig) { - std::vector out; - put_u32(out, kCanonicalMagic); - put_u32(out, kCanonicalVersion); - put_u32(out, static_cast(sig.version)); - put_u32(out, static_cast(sig.params.size())); - put_u32(out, static_cast(sig.static_samplers.size())); - put_u32(out, sig.flags); - for (const RootParameter& p : sig.params) { - put_u32(out, static_cast(p.type)); - put_u32(out, static_cast(p.visibility)); - put_u32(out, p.num_values); - put_u32(out, p.shader_register); - put_u32(out, p.register_space); - put_u32(out, p.descriptor_register); - put_u32(out, p.descriptor_space); - put_u32(out, static_cast(p.ranges.size())); - for (const DescriptorRange& r : p.ranges) { - put_u32(out, r.range_type); - put_u32(out, r.num_descriptors); - put_u32(out, r.base_shader_register); - put_u32(out, r.register_space); - put_u32(out, r.flags); - put_u32(out, r.offset_in_table); - } - } - for (const StaticSampler& s : sig.static_samplers) { - put_u32(out, s.filter); - put_u32(out, s.address_u); - put_u32(out, s.address_v); - put_u32(out, s.address_w); - put_f32(out, s.mip_lod_bias); - put_u32(out, s.max_anisotropy); - put_u32(out, s.comparison_func); - put_u32(out, s.border_color); - put_f32(out, s.min_lod); - put_f32(out, s.max_lod); - put_u32(out, s.shader_register); - put_u32(out, s.register_space); - put_u32(out, static_cast(s.visibility)); - if (sig.version == Version::V1_2) put_u32(out, s.flags); - } - return out; -} - -DecodeResult decode_canonical(const uint8_t* data, size_t size) { - DecodeResult out; - if (data == nullptr && size != 0) { - out.error = "null data with nonzero size"; - return out; - } - Reader r(data == nullptr ? reinterpret_cast("") : data, size); - uint32_t magic = 0, version = 0, nparams = 0, nsamplers = 0; - if (!r.u32(magic) || magic != kCanonicalMagic) { - out.error = "bad canonical magic"; - return out; - } - if (!r.u32(version) || version != kCanonicalVersion) { - out.error = "unsupported canonical version"; - return out; - } - uint32_t ver = 0; - if (!r.u32(ver) || !r.u32(nparams) || !r.u32(nsamplers) || !r.u32(out.sig.flags)) { - out.error = "truncated canonical header"; - return out; - } - if (!known_version(ver, out.sig.version)) { - out.error = "unknown root-signature version"; - return out; - } - if (nparams > 64) { - out.error = "more than 64 root parameters"; - return out; - } - if (nsamplers > 4096) { - out.error = "absurd sampler count"; - return out; - } - out.sig.params.reserve(nparams); - for (uint32_t i = 0; i < nparams; ++i) { - RootParameter p; - uint32_t type = 0, vis = 0, nranges = 0; - if (!r.u32(type) || !r.u32(vis) || !r.u32(p.num_values) || !r.u32(p.shader_register) || - !r.u32(p.register_space) || !r.u32(p.descriptor_register) || - !r.u32(p.descriptor_space) || !r.u32(nranges)) { - out.error = "truncated canonical parameter"; - return out; - } - if (type > 2) { - out.error = "unknown parameter type"; - return out; - } - p.type = static_cast(type); - p.visibility = static_cast(vis); - if (nranges > 1024) { - out.error = "absurd range count"; - return out; - } - p.ranges.reserve(nranges); - for (uint32_t j = 0; j < nranges; ++j) { - DescriptorRange range; - if (!r.u32(range.range_type) || !r.u32(range.num_descriptors) || !r.u32(range.base_shader_register) || - !r.u32(range.register_space) || !r.u32(range.flags) || !r.u32(range.offset_in_table)) { - out.error = "truncated canonical range"; - return out; - } - p.ranges.push_back(range); - } - out.sig.params.push_back(std::move(p)); - } - out.sig.static_samplers.reserve(nsamplers); - for (uint32_t i = 0; i < nsamplers; ++i) { - StaticSampler s; - uint32_t vis = 0; - if (!r.u32(s.filter) || !r.u32(s.address_u) || !r.u32(s.address_v) || !r.u32(s.address_w) || - !r.f32(s.mip_lod_bias) || !r.u32(s.max_anisotropy) || !r.u32(s.comparison_func) || - !r.u32(s.border_color) || !r.f32(s.min_lod) || !r.f32(s.max_lod) || - !r.u32(s.shader_register) || !r.u32(s.register_space) || !r.u32(vis) || - (out.sig.version == Version::V1_2 && !r.u32(s.flags))) { - out.error = "truncated canonical sampler"; - return out; - } - s.visibility = static_cast(vis); - out.sig.static_samplers.push_back(s); - } - if (!r.at_end()) { - out.error = "trailing bytes after canonical root signature"; - return out; - } - out.ok = true; - return out; -} - -// RTS0 payload: u32 version (1 = 1.0, 2 = 1.1, 3 = 1.2), u32 num_params, -// u32 num_static_samplers, u32 flags, then per-parameter fields in d3d12.h -// order. Static samplers follow the field order of D3D12_STATIC_SAMPLER_DESC, and -// of D3D12_STATIC_SAMPLER_DESC1 (one more dword, Flags) in 1.2. Root descriptors -// and ranges have a flags dword from 1.1 on. Anything else (unknown versions, -// truncation) is a hard error. -// Payload decoder: the RTS0 chunk contents (see header for the hypothesis). -static DecodeResult parse_rts0_payload(const uint8_t* data, size_t size) { - DecodeResult out; - if (data == nullptr && size != 0) { - out.error = "null data with nonzero size"; - return out; - } - if (data == nullptr) { - out.error = "null RTS0 payload"; - return out; - } - // Random access into the payload: every (offset, byte-count) pair is - // validated before any byte is touched. Offsets count from payload start. - auto at = [&](size_t off, size_t bytes) -> const uint8_t* { - if (bytes > size || off > size - bytes) return nullptr; - return data + off; - }; - auto u32_at = [&](size_t off, uint32_t& v) { - const uint8_t* p = at(off, 4); - if (p == nullptr) return false; - v = static_cast(p[0]) | (static_cast(p[1]) << 8) | - (static_cast(p[2]) << 16) | (static_cast(p[3]) << 24); - return true; - }; - auto f32_at = [&](size_t off, float& v) { - uint32_t bits = 0; - if (!u32_at(off, bits)) return false; - static_assert(sizeof(bits) == sizeof(v)); - std::memcpy(&v, &bits, sizeof(v)); - return true; - }; - // Header: version, num_params, params_offset, num_samplers, - // samplers_offset, flags. - uint32_t ver = 0, nparams = 0, params_off = 0, nsamplers = 0, samplers_off = 0, flags = 0; - if (!u32_at(0, ver) || !u32_at(4, nparams) || !u32_at(8, params_off) || - !u32_at(12, nsamplers) || !u32_at(16, samplers_off) || !u32_at(20, flags)) { - out.error = "truncated RTS0 header"; - return out; - } - if (!known_version(ver, out.sig.version)) { - out.error = "unknown RTS0 version (not 1.0/1.1/1.2)"; - return out; - } - if (nparams > 64) { - out.error = "RTS0 with more than 64 root parameters"; - return out; - } - if (nsamplers > 4096) { - out.error = "RTS0 with absurd sampler count"; - return out; - } - const bool flags_v11 = ver >= 2; // descriptor and range flags (1.1 and 1.2) - out.sig.flags = flags; - // Parameter table at params_off: num_params x {u32 d3d_type, u32 - // visibility, u32 offset}. d3d_type follows D3D12_ROOT_PARAMETER_TYPE - // (0 table, 1 constants, 2/3/4 CBV/SRV/UAV root descriptors). - constexpr size_t kEntryBytes = 12; - if (nparams > 0 && - (params_off > size || nparams > (size - params_off) / kEntryBytes)) { - out.error = "RTS0 parameter table overruns its payload"; - return out; - } - out.sig.params.reserve(nparams); - for (uint32_t i = 0; i < nparams; ++i) { - const size_t eoff = static_cast(params_off) + i * kEntryBytes; - uint32_t dtype = 0, vis = 0, poff = 0; - if (!u32_at(eoff, dtype) || !u32_at(eoff + 4, vis) || !u32_at(eoff + 8, poff)) { - out.error = "truncated RTS0 parameter entry"; - return out; - } - RootParameter p; - p.visibility = static_cast(vis); - if (dtype == 1) { - p.type = ParamType::Constants; - if (!u32_at(poff, p.shader_register) || !u32_at(poff + 4, p.register_space) || - !u32_at(poff + 8, p.num_values)) { - out.error = "truncated RTS0 constants payload"; - return out; - } - } else if (dtype == 2 || dtype == 3 || dtype == 4) { - p.type = ParamType::Descriptor; - uint32_t dflags = 0; - const size_t need = flags_v11 ? 12 : 8; - if (poff > size || need > size - static_cast(poff)) { - out.error = "truncated RTS0 descriptor payload"; - return out; - } - if (!u32_at(poff, p.descriptor_register) || !u32_at(poff + 4, p.descriptor_space)) { - out.error = "truncated RTS0 descriptor payload"; - return out; - } - if (flags_v11 && !u32_at(poff + 8, dflags)) { - out.error = "truncated RTS0 descriptor flags"; - return out; - } - (void)dflags; // descriptor flags do not affect the user-SGPR map - } else if (dtype == 0) { - p.type = ParamType::Table; - // Table payload: {u32 num_ranges, u32 ranges_offset}; the ranges sit at ranges_offset (from the payload - // start), like every other table in RTS0. Measured against the PC serializer (root_signature_oracle_test). - uint32_t nranges = 0, ranges_off = 0; - if (!u32_at(poff, nranges) || !u32_at(static_cast(poff) + 4, ranges_off)) { - out.error = "truncated RTS0 table payload"; - return out; - } - if (nranges > 1024) { - out.error = "absurd RTS0 range count"; - return out; - } - // Range record, in D3D12_DESCRIPTOR_RANGE(1) order: {type, num, base_reg, space, offset} in 1.0, and - // {type, num, base_reg, space, flags, offset} in 1.1 and 1.2: the flags come BEFORE the table offset - // (measured against the PC serializer in root_signature_oracle_test). - const size_t stride = flags_v11 ? 24 : 20; - if (nranges > 0 && (ranges_off > size || nranges > (size - ranges_off) / stride)) { - out.error = "RTS0 ranges overrun their payload"; - return out; - } - p.ranges.reserve(nranges); - for (uint32_t j = 0; j < nranges; ++j) { - const size_t roff = static_cast(ranges_off) + j * stride; - DescriptorRange range; - const size_t offset_at = roff + (flags_v11 ? 20 : 16); - if (!u32_at(roff, range.range_type) || !u32_at(roff + 4, range.num_descriptors) || - !u32_at(roff + 8, range.base_shader_register) || !u32_at(roff + 12, range.register_space) || - (flags_v11 && !u32_at(roff + 16, range.flags)) || !u32_at(offset_at, range.offset_in_table)) { - out.error = "truncated RTS0 range"; - return out; - } - p.ranges.push_back(range); - } - } else { - out.error = "unknown RTS0 parameter type"; - return out; - } - out.sig.params.push_back(std::move(p)); - } - // Sampler records mirror D3D12_STATIC_SAMPLER_DESC field order; 1.2 appends Flags (D3D12_STATIC_SAMPLER_DESC1). - const bool sampler_flags = ver == 3; - const size_t kSamplerBytes = (sampler_flags ? 14 : 13) * 4; - if (nsamplers > 0 && - (samplers_off > size || nsamplers > (size - samplers_off) / kSamplerBytes)) { - out.error = "RTS0 samplers overrun their payload"; - return out; - } - out.sig.static_samplers.reserve(nsamplers); - for (uint32_t i = 0; i < nsamplers; ++i) { - const size_t soff = static_cast(samplers_off) + i * kSamplerBytes; - StaticSampler s; - uint32_t vis = 0; - if (!u32_at(soff, s.filter) || !u32_at(soff + 4, s.address_u) || - !u32_at(soff + 8, s.address_v) || !u32_at(soff + 12, s.address_w) || - !f32_at(soff + 16, s.mip_lod_bias) || !u32_at(soff + 20, s.max_anisotropy) || - !u32_at(soff + 24, s.comparison_func) || !u32_at(soff + 28, s.border_color) || - !f32_at(soff + 32, s.min_lod) || !f32_at(soff + 36, s.max_lod) || - !u32_at(soff + 40, s.shader_register) || !u32_at(soff + 44, s.register_space) || - !u32_at(soff + 48, vis) || (sampler_flags && !u32_at(soff + 52, s.flags))) { - out.error = "truncated RTS0 sampler"; - return out; - } - s.visibility = static_cast(vis); - out.sig.static_samplers.push_back(s); - } - out.ok = true; - return out; -} - -DecodeResult parse_rts0(const uint8_t* data, size_t size) { - DecodeResult out; - if ((data == nullptr && size != 0) || (data != nullptr && size < 4)) { - out.error = "blob too small for a DXBC container"; - return out; - } - if (data == nullptr) { - out.error = "null blob"; - return out; - } - // A bare payload (unit-test path) has no DXBC magic: decode directly. - if (!(data[0] == 'D' && data[1] == 'X' && data[2] == 'B' && data[3] == 'C')) { - return parse_rts0_payload(data, size); - } - // DXBC container walk (mirrors input_signature in tools/rdna2spirv.py): - // +28: chunk count, +32: chunk offsets, each chunk is FourCC + u32 size. - auto at = [&](size_t off, uint32_t& v) { - if (off + 4 > size) return false; - v = static_cast(data[off]) | (static_cast(data[off + 1]) << 8) | - (static_cast(data[off + 2]) << 16) | (static_cast(data[off + 3]) << 24); - return true; - }; - uint32_t nchunks = 0; - if (!at(28, nchunks)) { - out.error = "truncated DXBC header"; - return out; - } - if (nchunks > 1024) { - out.error = "absurd DXBC chunk count"; - return out; - } - for (uint32_t k = 0; k < nchunks; ++k) { - uint32_t off = 0; - // NOTE: off and payload_size are u32; promote to size_t BEFORE adding - // or a hostile container wraps the check and turns it into an OOB read. - if (!at(32 + 4 * static_cast(k), off) || - static_cast(off) + 8 > size) { - out.error = "truncated DXBC chunk table"; - return out; - } - if (data[off] == 'R' && data[off + 1] == 'T' && data[off + 2] == 'S' && data[off + 3] == '0') { - uint32_t payload_size = 0; - if (static_cast(off) + 8 > size) { - out.error = "truncated RTS0 chunk header"; - return out; - } - payload_size = static_cast(data[off + 4]) | - (static_cast(data[off + 5]) << 8) | - (static_cast(data[off + 6]) << 16) | - (static_cast(data[off + 7]) << 24); - if (static_cast(off) + 8 + payload_size > size) { - out.error = "RTS0 chunk overruns its container"; - return out; - } - return parse_rts0_payload(data + off + 8, payload_size); - } - } - out.error = "no RTS0 chunk in DXBC container"; - return out; -} - -} // namespace rt::rootsig diff --git a/runtime/src/root_signature.h b/runtime/src/root_signature.h deleted file mode 100644 index 376962940..000000000 --- a/runtime/src/root_signature.h +++ /dev/null @@ -1,230 +0,0 @@ -// Portable D3D12 root-signature model + packer to user SGPRs (s0..s31). -// -// No d3d12.h, no windows.h: this compiles on Linux CI and in the Windows -// runtime alike. It models exactly what docs/d3d12_vulkan.md section 3.5 -// needs: root parameters in order, static samplers (no dwords), the 64-dword -// D3D12 cost limit, and the 32-dword console user-SGPR budget. Anything that -// does not fit is refused loudly, never guessed (see pack()). -// -// Numbering follows D3D12 docs: descriptor tables cost 1 dword of the 64-dword -// limit, root views (CBV/SRV/UAV) cost 2, 32-bit constants cost their count. -#pragma once - -#include -#include -#include -#include - -namespace rt::rootsig { - -// D3D12_ROOT_SIGNATURE_VERSION subset the layer handles. 1.2 is 1.1 plus a flags dword on each static sampler. -enum class Version : uint32_t { V1_0 = 1, V1_1 = 2, V1_2 = 3 }; - -// D3D12_ROOT_PARAMETER_TYPE subset (order matches D3D12 docs). -enum class ParamType : uint32_t { - Constants = 0, // 32BIT_CONSTANTS: NumValues dwords - Descriptor = 1, // CBV/SRV/UAV root descriptor: 2 dwords (64-bit VA) - Table = 2, // DESCRIPTOR_TABLE: 2 dwords (table GPU VA) -}; - -// D3D12_SHADER_VISIBILITY (ALL 0, VERTEX 1, HULL 2, DOMAIN 3, -// GEOMETRY 4, PIXEL 5, AMPLIFICATION 6, MESH 7). -enum class Visibility : uint32_t { - All = 0, - Vertex = 1, - Geometry = 4, - Pixel = 5, - Amplification = 6, - Mesh = 7, -}; - -// D3D12_DESCRIPTOR_RANGE_OFFSET_APPEND: the range starts right after the previous one in its table. -constexpr uint32_t kRangeOffsetAppend = 0xFFFFFFFFu; - -// One descriptor range inside a table (SRV/CBV/UAV/sampler + count), with every field of D3D12_DESCRIPTOR_RANGE1. -struct DescriptorRange { - uint32_t range_type = 0; // 0 SRV, 1 UAV, 2 CBV, 3 sampler (D3D12 order) - uint32_t num_descriptors = 0; - uint32_t base_shader_register = 0; - uint32_t register_space = 0; - // D3D12_DESCRIPTOR_RANGE_FLAGS, 1.1 and 1.2 only. A 1.0 range has no flags dword; it stays 0 here. - uint32_t flags = 0; - uint32_t offset_in_table = 0; // OffsetInDescriptorsFromTableStart, or kRangeOffsetAppend -}; - -// Static sampler: no user-SGPR dwords; registered in the hash table instead. -struct StaticSampler { - uint32_t filter = 0; - uint32_t address_u = 0; - uint32_t address_v = 0; - uint32_t address_w = 0; - float mip_lod_bias = 0.0f; - uint32_t max_anisotropy = 0; - uint32_t comparison_func = 0; - uint32_t border_color = 0; // 0 transparent-black .. 4 opaque-white - float min_lod = 0.0f; - float max_lod = 0.0f; - uint32_t shader_register = 0; - uint32_t register_space = 0; - Visibility visibility = Visibility::All; - // D3D12_SAMPLER_FLAGS (D3D12_STATIC_SAMPLER_DESC1, version 1.2 only): 1 UINT border colour, 2 non-normalized - // coordinates. Earlier versions have no such field; it stays 0 and the codecs neither write nor read it. - uint32_t flags = 0; -}; - -struct RootParameter { - ParamType type = ParamType::Constants; - Visibility visibility = Visibility::All; - // Constants: - uint32_t num_values = 0; // shader register + space describe the slot - uint32_t shader_register = 0; - uint32_t register_space = 0; - // Root descriptor: - uint32_t descriptor_register = 0; - uint32_t descriptor_space = 0; - // Descriptor table: - std::vector ranges; -}; - -struct RootSignature { - Version version = Version::V1_1; - std::vector params; // at most 64 root parameters (D3D12) - std::vector static_samplers; - uint32_t flags = 0; // low 16 bits: PC meaning; high byte: Xbox type bits -}; - -// Where one packed dword came from (provenance for diagnostics). -struct DwordProvenance { - uint32_t param_index = 0; // index into RootSignature::params - uint32_t sub_index = 0; // constant index, or 0 = VA lo, 1 = VA hi -}; - -struct PackResult { - bool ok = false; - std::string error; // set when !ok; names the refusing parameter - std::array dwords{}; // valid dwords [0, dword_count) - uint32_t dword_count = 0; - std::vector provenance; // same length as dword_count - uint32_t d3d12_cost = 0; // cost against the 64-dword D3D12 limit -}; - -constexpr uint32_t kMaxUserSgprs = 32; -constexpr uint32_t kMaxD3d12Cost = 64; - -// Packs root parameters in order. Static samplers consume no dwords. -// Fails (ok == false) when the signature needs more than 32 user SGPRs -// (spill layout unknown: refuse, do not guess) or exceeds the 64-dword -// D3D12 cost limit, or holds more than 64 root parameters. -[[nodiscard]] PackResult pack(const RootSignature& sig); - -// The console layout of root arguments in a stage's user SGPRs (docs/d3d12_vulkan.md section 3.5, D3D-448). -// -// Parameters go in root-signature order from the stage's first root-argument SGPR, each while it fits whole: -// a 32-bit constant takes one SGPR per value, a root CBV/SRV/UAV two (its 64-bit VA), a descriptor table ONE -// (the 32-bit VA of its first descriptor; the heaps live below 4 GiB). Static samplers take none. -// -// How each part is known: -// - compute, base s4: measured. The console compiler's output (section 7) and the package's FidelityFX DLL, whose -// 29 compute containers carry their RTS0 next to the console-compiled program: base s4 plus the signature's span -// in this layout equals the program's RSRC2 USER_SGPR count in 29 of 29, and the programs read the tables and -// root CBVs at exactly these SGPRs (tools/rootsig_census.py --disasm). The game's compute census agrees (lowest -// pointer s4, one-dword tables). -// - vertex/pixel/geometry s8 and mesh s16: a hypothesis from the corpus census only (lowest pointer SGPR per stage); -// no signature confirms them, and visibility is not modelled (every parameter takes its place in every stage). -// A parameter that does not fit goes to the console's spill array behind s[0:1] (compute, section 7) together with -// every parameter after it; that array is not modelled, so such a signature is refused, never truncated. -enum class Stage : uint32_t { Vertex = 0, Pixel = 1, Geometry = 2, Compute = 3, Mesh = 4 }; - -[[nodiscard]] constexpr uint32_t stage_base(Stage stage) noexcept { - switch (stage) { - case Stage::Compute: - return 4; - case Stage::Mesh: - return 16; - case Stage::Vertex: - case Stage::Pixel: - case Stage::Geometry: - return 8; - } - return 8; -} - -// User SGPRs one parameter takes in the console layout (see Stage). -[[nodiscard]] constexpr uint32_t stage_dwords(ParamType type, uint32_t num_values) noexcept { - switch (type) { - case ParamType::Constants: - return num_values; - case ParamType::Descriptor: - return 2; - case ParamType::Table: - return 1; - } - return 0; -} - -constexpr uint32_t kNoSgpr = 0xFFFFFFFFu; - -struct StagePackResult { - bool ok = false; - std::string error; // set when !ok; names the refusing parameter - Stage stage = Stage::Compute; - uint32_t base = 0; // stage_base(stage) - std::vector first_sgpr; // per parameter: its first user SGPR (kNoSgpr when the signature is refused) - uint32_t end_sgpr = 0; // one past the last SGPR used: the RSRC2 USER_SGPR count the layout implies - uint32_t d3d12_cost = 0; // cost against the 64-dword D3D12 limit -}; - -// Lays the parameters out for `stage` in the console layout. Fails like pack() on more than 64 parameters, a -// constant parameter of 0 values or the 64-dword cost limit, and on any parameter that would spill. -[[nodiscard]] StagePackResult pack_stage(const RootSignature& sig, Stage stage); - -// D3D12 cost of one parameter against the 64-dword limit. -[[nodiscard]] constexpr uint32_t param_cost(ParamType type, uint32_t num_values) noexcept { - switch (type) { - case ParamType::Constants: - return num_values; - case ParamType::Descriptor: - return 2; - case ParamType::Table: - return 1; - } - return 0; -} - -// Canonical binary codec for caching root signatures (magic "LRS1", -// little-endian). This is Leonida's own layout, NOT the Microsoft RTS0 -// format: it round-trips pack() inputs byte-exactly and is fully tested on -// every CI leg. Never write game blobs in this format and claim otherwise. -// Static samplers carry their flags dword only in version 1.2 signatures, so -// 1.0/1.1 encodings are unchanged. Codec version 2 stores all six range -// fields (version 1 stored only type and count, and is no longer read). -[[nodiscard]] std::vector encode_canonical(const RootSignature& sig); - -struct DecodeResult { - bool ok = false; - std::string error; - RootSignature sig; -}; - -[[nodiscard]] DecodeResult decode_canonical(const uint8_t* data, size_t size); - -// RTS0 chunk parser (payload layout per the maintainer: offset table). -// -// The input is a whole DXBC container (what D3D12SerializeVersionedRootSignature -// returns: "DXBC" magic, hash, size, chunk table). The parser walks the chunk -// table exactly like tools/rdna2spirv.py:input_signature does, finds the -// "RTS0" chunk and decodes its payload: version, counts and table offsets, -// then a parameter table of {d3d_type, visibility, offset} entries with -// payloads at their offsets (d3d types follow D3D12_ROOT_PARAMETER_TYPE -// numbering). A bare payload without the DXBC header is also accepted -// (unit-test path). Every deviation the oracle test finds is a hard failure -// to investigate, not a quirk to absorb. -// Versions 1 (1.0), 2 (1.1) and 3 (1.2): 1.1 and 1.2 add a flags dword to -// root descriptors and ranges; 1.2 adds one to each static sampler (13 dwords -// before, 14 after), as the PC serializer writes them (root_signature_oracle_test). -// A range record follows D3D12_DESCRIPTOR_RANGE1 order: type, count, base -// register, space, then Flags (1.1/1.2 only) BEFORE the table offset. -// Returns ok == false with a reason for unknown versions or truncation. -[[nodiscard]] DecodeResult parse_rts0(const uint8_t* data, size_t size); - -} // namespace rt::rootsig diff --git a/runtime/src/shader_library.h b/runtime/src/shader_library.h deleted file mode 100644 index 9f752317e..000000000 --- a/runtime/src/shader_library.h +++ /dev/null @@ -1,1082 +0,0 @@ -#pragma once - -// Finds the translated SPIR-V for a shader the game hands to D3D12 (docs/d3d12_vulkan.md section 3.6). -// -// A pipeline's bytecode is a DXBC container. Its DXIL part holds an XDAT table whose entry 0x0D is an XBCH header -// followed by a zlib stream; the stream inflates to the FSSM blob, the native RDNA2 program the translator read -// (tools/fssm_unpack.py does the same in Python). The SHA-256 of that blob is the `fssm_sha256` field the translator -// writes into `spirv/index.json`, next to `.spv`. This header needs no Windows, Vulkan or third-party code: -// it carries its own inflate (RFC 1950/1951), SHA-256 (FIPS 180-4) and a minimal JSON reader. - -#include "spirv_words.h" - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace leonida { - -// --------------------------------------------------------------------------------------------------------------- -// zlib inflate - -// Why zlib_inflate failed, for a caller that reports the reason (runtime/shims/dstorage.cpp turns each into its -// E_DSTORAGE_ZLIB_* code). `limit`: the output would pass the caller's limit; the stream was not read to its end. -enum class ZlibError { none, header, data, checksum, limit }; - -namespace detail { - -class BitReader { -public: - explicit BitReader(std::span in) : in_(in) {} - - // Refill up to 56..63 buffered bits without failing at EOF; bits >= count_ stay zero. - void fill() { - if constexpr (std::endian::native == std::endian::little) { - if (count_ < 56 && in_.size() - pos_ >= 8) { - std::uint64_t next; - std::memcpy(&next, in_.data() + pos_, 8); - const int take = (63 - count_) >> 3; - const int next_count = count_ | 56; - buffer_ = (buffer_ | (next << count_)) & ((std::uint64_t(1) << next_count) - 1); - pos_ += std::size_t(take); - count_ = next_count; - return; - } - } - while (count_ <= 55 && pos_ < in_.size()) { - buffer_ |= std::uint64_t(in_[pos_++]) << count_; - count_ += 8; - } - } - - std::uint32_t bits(int need) { - if (count_ < need) { - fill(); - if (count_ < need) { - failed_ = true; - buffer_ = 0; - count_ = 0; - return 0; - } - } - const std::uint32_t out = std::uint32_t(buffer_ & ((std::uint64_t(1) << need) - 1)); - buffer_ >>= need; - count_ -= need; - return out; - } - - std::uint64_t peek() const { return buffer_; } - int available() const { return count_; } - void drop(int n) { - buffer_ >>= n; - count_ -= n; - } - void fail() { - failed_ = true; - buffer_ = 0; - count_ = 0; - } - - void align() { - pos_ -= std::size_t(count_ / 8); - buffer_ = 0; - count_ = 0; - } - - bool byte(std::uint8_t& out) { - if (pos_ >= in_.size()) return failed_ = true, false; - out = in_[pos_++]; - return true; - } - - std::size_t position() const { return pos_ - std::size_t(count_ / 8); } - bool failed() const { return failed_; } - -private: - std::span in_; - std::size_t pos_ = 0; - std::uint64_t buffer_ = 0; - int count_ = 0; - bool failed_ = false; -}; - -struct Huffman { - static constexpr int kFastBits = 9; - static constexpr std::size_t kFastSize = std::size_t(1) << kFastBits; - - std::array count{}; - std::array symbol{}; - int fast_bits = 0; - std::uint32_t fast_mask = 0; - // Direct lookup for canonical codes of length 1..fast_bits, indexed by LSB-first bits. - // Entry encoding: (symbol << 4) | length; 0 means length > fast_bits or an unassigned code. - std::array fast{}; -}; - -// Canonical Huffman table from code lengths. Returns false for an over-subscribed set. -inline bool build_huffman(Huffman& h, const std::int16_t* lengths, int n) { - static constexpr std::uint8_t kRev4[16] = {0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15}; - h.count.fill(0); - int max_len = 0; - for (int i = 0; i < n; ++i) { - const int len = lengths[i]; - ++h.count[len]; - if (len > max_len) max_len = len; - } - if (h.count[0] == n) { // no codes: valid only if never used - h.fast_bits = 0; - h.fast_mask = 0; - h.fast[0] = 0; - return true; - } - int left = 1; - for (int len = 1; len < 16; ++len) { - left <<= 1; - left -= h.count[len]; - if (left < 0) { - h.fast_bits = 0; - h.fast_mask = 0; - h.fast[0] = 0; - return false; - } - } - std::array offsets{}; - for (int len = 1; len < 15; ++len) offsets[len + 1] = std::int16_t(offsets[len] + h.count[len]); - for (int i = 0; i < n; ++i) - if (lengths[i]) h.symbol[offsets[lengths[i]]++] = std::int16_t(i); - const int fast_bits = max_len < Huffman::kFastBits ? max_len : Huffman::kFastBits; - const std::size_t fast_size = std::size_t(1) << fast_bits; - h.fast_bits = fast_bits; - h.fast_mask = std::uint32_t(fast_size - 1); - std::fill_n(h.fast.data(), fast_size, std::uint16_t(0)); - int code = 0; - int idx = 0; - for (int len = 1; len <= fast_bits; ++len) { - const int c = h.count[len]; - const std::size_t step = std::size_t(1) << len; - const int shift = Huffman::kFastBits - len; - for (int k = 0; k < c; ++k) { - const std::uint16_t sym = std::uint16_t(h.symbol[idx++]); - const std::uint16_t packed = std::uint16_t((sym << 4) | std::uint16_t(len)); - const std::uint32_t v = std::uint32_t(code) << shift; - const std::uint32_t rev = - (std::uint32_t(kRev4[v & 15u]) << 5) | (std::uint32_t(kRev4[(v >> 4) & 15u]) << 1) | (v >> 8); - for (std::size_t slot = rev; slot < fast_size; slot += step) h.fast[slot] = packed; - ++code; - } - code <<= 1; - } - return true; -} - -inline int decode(BitReader& in, const Huffman& h) { - if (in.available() < h.fast_bits) in.fill(); - const std::uint16_t entry = h.fast[in.peek() & h.fast_mask]; - if (entry != 0) { - const int len = int(entry & 0x0fu); - if (len > in.available()) { - in.fail(); - return -1; - } - in.drop(len); - return int(entry >> 4); - } - if (in.available() < 15) in.fill(); - const int avail = in.available(); - std::uint64_t bits = in.peek(); - int code = 0, first = 0, index = 0; - for (int len = 1; len < 16; ++len) { - if (len > avail) { - in.fail(); - return -1; - } - code |= int(bits & 1u); - bits >>= 1; - const int count = h.count[len]; - if (code - count < first) { - in.drop(len); - return h.symbol[index + (code - first)]; - } - index += count; - first += count; - first <<= 1; - code <<= 1; - } - return -1; -} - -inline ZlibError inflate_codes(BitReader& in, std::vector& out, const Huffman& lengths, - const Huffman& distances, std::size_t limit) { - static constexpr std::int16_t length_base[29] = {3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, - 31, 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258}; - static constexpr std::int16_t length_extra[29] = {0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, - 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0}; - static constexpr std::int16_t distance_base[30] = {1, 2, 3, 4, 5, 7, 9, 13, 17, 25, - 33, 49, 65, 97, 129, 193, 257, 385, 513, 769, - 1025, 1537, 2049, 3073, 4097, 6145, 8193, 12289, 16385, 24577}; - static constexpr std::int16_t distance_extra[30] = {0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, - 6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13}; - for (;;) { - int symbol = decode(in, lengths); - if (symbol < 0 || in.failed()) return ZlibError::data; - if (symbol < 256) { - if (out.size() >= limit) return ZlibError::limit; - out.push_back(std::uint8_t(symbol)); - continue; - } - if (symbol == 256) return ZlibError::none; - symbol -= 257; - if (symbol >= 29) return ZlibError::data; - const std::size_t length = std::size_t(length_base[symbol]) + in.bits(length_extra[symbol]); - const int d = decode(in, distances); - if (d < 0 || d >= 30) return ZlibError::data; - const std::size_t distance = std::size_t(distance_base[d]) + in.bits(distance_extra[d]); - if (in.failed() || distance > out.size()) return ZlibError::data; - if (out.size() + length > limit) return ZlibError::limit; - const std::size_t from = out.size() - distance; - for (std::size_t i = 0; i < length; ++i) out.push_back(out[from + i]); - } -} - -} // namespace detail - -// Inflates a zlib stream (RFC 1950: header, deflate data, Adler-32). Returns false for a malformed stream, a -// preset dictionary, a checksum mismatch, or output beyond `limit` bytes, and then stores the reason in `*why` when -// it is given: `header` for the two header bytes (not deflate, a window over 32 KiB, a bad check value, a preset -// dictionary), `data` for the deflate data or a missing trailer, `checksum` for an Adler-32 mismatch, `limit` for -// output beyond `limit`. Bytes after the Adler-32 trailer are not read. -inline bool zlib_inflate(std::span in, std::vector& out, - std::size_t limit = std::size_t(1) << 30, ZlibError* why = nullptr) { - out.clear(); - const auto fail = [why](ZlibError reason) { - if (why) *why = reason; - return false; - }; - if (why) *why = ZlibError::none; - if (in.size() < 2) return fail(ZlibError::header); - const unsigned cmf = in[0], flg = in[1]; - if ((cmf & 0x0f) != 8 || (cmf >> 4) > 7 || ((cmf << 8) | flg) % 31 != 0 || (flg & 0x20)) - return fail(ZlibError::header); - if (in.size() < 6) return fail(ZlibError::data); - detail::BitReader reader(in.subspan(2)); - for (bool last = false; !last;) { - last = reader.bits(1) != 0; - const std::uint32_t type = reader.bits(2); - if (reader.failed()) return fail(ZlibError::data); - if (type == 0) { // stored - reader.align(); - std::uint8_t b[4]; - for (auto& x : b) - if (!reader.byte(x)) return fail(ZlibError::data); - const unsigned length = b[0] | (b[1] << 8), complement = b[2] | (b[3] << 8); - if (length != (~complement & 0xffff)) return fail(ZlibError::data); - if (out.size() + length > limit) return fail(ZlibError::limit); - for (unsigned i = 0; i < length; ++i) { - std::uint8_t x; - if (!reader.byte(x)) return fail(ZlibError::data); - out.push_back(x); - } - } else if (type == 1) { // fixed Huffman - static const auto tables = [] { - std::pair t; - std::int16_t lengths[288]; - for (int i = 0; i < 144; ++i) lengths[i] = 8; - for (int i = 144; i < 256; ++i) lengths[i] = 9; - for (int i = 256; i < 280; ++i) lengths[i] = 7; - for (int i = 280; i < 288; ++i) lengths[i] = 8; - detail::build_huffman(t.first, lengths, 288); - for (int i = 0; i < 30; ++i) lengths[i] = 5; - detail::build_huffman(t.second, lengths, 30); - return t; - }(); - if (const ZlibError e = detail::inflate_codes(reader, out, tables.first, tables.second, limit); e != ZlibError::none) - return fail(e); - } else if (type == 2) { // dynamic Huffman - const int literal_count = int(reader.bits(5)) + 257, distance_count = int(reader.bits(5)) + 1; - const int code_count = int(reader.bits(4)) + 4; - if (literal_count > 286 || distance_count > 30) return fail(ZlibError::data); - static constexpr int order[19] = {16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15}; - std::int16_t lengths[320] = {}; - for (int i = 0; i < code_count; ++i) lengths[order[i]] = std::int16_t(reader.bits(3)); - detail::Huffman code_lengths; - if (!detail::build_huffman(code_lengths, lengths, 19)) return fail(ZlibError::data); - for (int i = 0; i < literal_count + distance_count;) { - const int symbol = detail::decode(reader, code_lengths); - if (symbol < 0) return fail(ZlibError::data); - if (symbol < 16) { - lengths[i++] = std::int16_t(symbol); - continue; - } - std::int16_t value = 0; - int repeat; - if (symbol == 16) { - if (i == 0) return fail(ZlibError::data); - value = lengths[i - 1]; - repeat = 3 + int(reader.bits(2)); - } else if (symbol == 17) { - repeat = 3 + int(reader.bits(3)); - } else { - repeat = 11 + int(reader.bits(7)); - } - if (i + repeat > literal_count + distance_count) return fail(ZlibError::data); - while (repeat--) lengths[i++] = value; - } - if (lengths[256] == 0) return fail(ZlibError::data); // no end-of-block code - detail::Huffman literal, distance; - if (!detail::build_huffman(literal, lengths, literal_count) || - !detail::build_huffman(distance, lengths + literal_count, distance_count)) - return fail(ZlibError::data); - if (const ZlibError e = detail::inflate_codes(reader, out, literal, distance, limit); e != ZlibError::none) - return fail(e); - } else { - return fail(ZlibError::data); - } - if (reader.failed()) return fail(ZlibError::data); - } - // Adler-32, big-endian, after the deflate data's last whole byte. - const std::size_t at = 2 + reader.position(); - if (at + 4 > in.size()) return fail(ZlibError::data); - std::uint32_t a = 1, b = 0; - for (const std::uint8_t x : out) { - a = (a + x) % 65521; - b = (b + a) % 65521; - } - const std::uint32_t expected = (std::uint32_t(in[at]) << 24) | (std::uint32_t(in[at + 1]) << 16) | - (std::uint32_t(in[at + 2]) << 8) | in[at + 3]; - return ((b << 16) | a) == expected || fail(ZlibError::checksum); -} - -// --------------------------------------------------------------------------------------------------------------- -// SHA-256 - -inline std::string sha256_hex(std::span data) { - static constexpr std::uint32_t k[64] = { - 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, - 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, - 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, - 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, - 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, - 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, - 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3, - 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2}; - std::uint32_t h[8] = {0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, - 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19}; - const auto rotr = [](std::uint32_t x, int n) { return (x >> n) | (x << (32 - n)); }; - std::vector message(data.begin(), data.end()); - const std::uint64_t bits = std::uint64_t(data.size()) * 8; - message.push_back(0x80); - while (message.size() % 64 != 56) message.push_back(0); - for (int i = 7; i >= 0; --i) message.push_back(std::uint8_t(bits >> (8 * i))); - for (std::size_t block = 0; block < message.size(); block += 64) { - std::uint32_t w[64]; - for (int i = 0; i < 16; ++i) - w[i] = (std::uint32_t(message[block + 4 * i]) << 24) | (std::uint32_t(message[block + 4 * i + 1]) << 16) | - (std::uint32_t(message[block + 4 * i + 2]) << 8) | message[block + 4 * i + 3]; - for (int i = 16; i < 64; ++i) { - const std::uint32_t s0 = rotr(w[i - 15], 7) ^ rotr(w[i - 15], 18) ^ (w[i - 15] >> 3); - const std::uint32_t s1 = rotr(w[i - 2], 17) ^ rotr(w[i - 2], 19) ^ (w[i - 2] >> 10); - w[i] = w[i - 16] + s0 + w[i - 7] + s1; - } - std::uint32_t a = h[0], b = h[1], c = h[2], d = h[3], e = h[4], f = h[5], g = h[6], hh = h[7]; - for (int i = 0; i < 64; ++i) { - const std::uint32_t t1 = hh + (rotr(e, 6) ^ rotr(e, 11) ^ rotr(e, 25)) + ((e & f) ^ (~e & g)) + k[i] + w[i]; - const std::uint32_t t2 = (rotr(a, 2) ^ rotr(a, 13) ^ rotr(a, 22)) + ((a & b) ^ (a & c) ^ (b & c)); - hh = g; - g = f; - f = e; - e = d + t1; - d = c; - c = b; - b = a; - a = t1 + t2; - } - h[0] += a; h[1] += b; h[2] += c; h[3] += d; h[4] += e; h[5] += f; h[6] += g; h[7] += hh; - } - static constexpr char hex[] = "0123456789abcdef"; - std::string out; - for (const std::uint32_t word : h) - for (int shift = 28; shift >= 0; shift -= 4) out.push_back(hex[(word >> shift) & 0xf]); - return out; -} - -// --------------------------------------------------------------------------------------------------------------- -// JSON (the subset the translator's index uses, which is all of JSON except number precision beyond double) - -struct JsonObjectEntry; - -struct Json { - enum class Kind { null, boolean, number, string, array, object } kind = Kind::null; - bool boolean = false; - double number = 0; - std::string string; - std::vector array; - // Declared through the incomplete JsonObjectEntry and destroyed out of line: a vector element type that holds a - // Json by value cannot be instantiated while Json is still being defined. GCC tolerates it, Clang with libstdc++ - // does not (the pair form used to fail to build there). Structured bindings still work. - std::vector object; - - ~Json(); - const Json* find(std::string_view key) const; -}; - -struct JsonObjectEntry { - std::string key; - Json value; -}; - -inline Json::~Json() = default; - -inline const Json* Json::find(std::string_view key) const { - for (const auto& [k, v] : object) - if (k == key) return &v; - return nullptr; -} - -class JsonReader { -public: - explicit JsonReader(std::string_view text) : text_(text) {} - - bool parse(Json& out) { - if (!value(out, 0)) return false; - space(); - return pos_ == text_.size(); - } - -private: - void space() { - while (pos_ < text_.size() && (text_[pos_] == ' ' || text_[pos_] == '\n' || text_[pos_] == '\r' || - text_[pos_] == '\t')) - ++pos_; - } - - bool literal(std::string_view word) { - if (text_.substr(pos_, word.size()) != word) return false; - pos_ += word.size(); - return true; - } - - bool value(Json& out, int depth) { - if (depth > 64) return false; - space(); - if (pos_ >= text_.size()) return false; - const char c = text_[pos_]; - if (c == '{') { - out.kind = Json::Kind::object; - ++pos_; - space(); - if (pos_ < text_.size() && text_[pos_] == '}') return ++pos_, true; - for (;;) { - space(); - std::string key; - if (!string(key)) return false; - space(); - if (pos_ >= text_.size() || text_[pos_++] != ':') return false; - Json item; - if (!value(item, depth + 1)) return false; - out.object.emplace_back(std::move(key), std::move(item)); - space(); - if (pos_ >= text_.size()) return false; - if (text_[pos_] == ',') { - ++pos_; - continue; - } - return text_[pos_++] == '}'; - } - } - if (c == '[') { - out.kind = Json::Kind::array; - ++pos_; - space(); - if (pos_ < text_.size() && text_[pos_] == ']') return ++pos_, true; - for (;;) { - Json item; - if (!value(item, depth + 1)) return false; - out.array.push_back(std::move(item)); - space(); - if (pos_ >= text_.size()) return false; - if (text_[pos_] == ',') { - ++pos_; - continue; - } - return text_[pos_++] == ']'; - } - } - if (c == '"') { - out.kind = Json::Kind::string; - return string(out.string); - } - if (literal("true")) return out.kind = Json::Kind::boolean, out.boolean = true, true; - if (literal("false")) return out.kind = Json::Kind::boolean, out.boolean = false, true; - if (literal("null")) return out.kind = Json::Kind::null, true; - // Numbers through strtod: Apple's libc++ does not provide the floating-point from_chars overload. The - // token is already limited to JSON number characters, and the end check requires all of it to be consumed. - const std::size_t start = pos_; - while (pos_ < text_.size() && std::strchr("+-0123456789.eE", text_[pos_])) ++pos_; - if (pos_ == start) return false; - out.kind = Json::Kind::number; - const std::string token(text_.substr(start, pos_ - start)); - char* end = nullptr; - errno = 0; - out.number = std::strtod(token.c_str(), &end); - return errno != ERANGE && end == token.c_str() + token.size(); - } - - static int hex_digit(char c) { - if (c >= '0' && c <= '9') return c - '0'; - if (c >= 'a' && c <= 'f') return c - 'a' + 10; - if (c >= 'A' && c <= 'F') return c - 'A' + 10; - return -1; - } - - bool string(std::string& out) { - if (pos_ >= text_.size() || text_[pos_++] != '"') return false; - while (pos_ < text_.size()) { - const char c = text_[pos_++]; - if (c == '"') return true; - if (c != '\\') { - out.push_back(c); - continue; - } - if (pos_ >= text_.size()) return false; - const char e = text_[pos_++]; - switch (e) { - case '"': case '\\': case '/': out.push_back(e); break; - case 'b': out.push_back('\b'); break; - case 'f': out.push_back('\f'); break; - case 'n': out.push_back('\n'); break; - case 'r': out.push_back('\r'); break; - case 't': out.push_back('\t'); break; - case 'u': { - if (pos_ + 4 > text_.size()) return false; - unsigned code = 0; - for (int i = 0; i < 4; ++i) { // exactly four hex digits - const int digit = hex_digit(text_[pos_++]); - if (digit < 0) return false; - code = code << 4 | unsigned(digit); - } - if (code < 0x80) { - out.push_back(char(code)); - } else if (code < 0x800) { - out.push_back(char(0xc0 | (code >> 6))); - out.push_back(char(0x80 | (code & 0x3f))); - } else { // surrogate pairs are kept as two 3-byte sequences; index names are ASCII - out.push_back(char(0xe0 | (code >> 12))); - out.push_back(char(0x80 | ((code >> 6) & 0x3f))); - out.push_back(char(0x80 | (code & 0x3f))); - } - break; - } - default: return false; - } - } - return false; - } - - std::string_view text_; - std::size_t pos_ = 0; -}; - -// --------------------------------------------------------------------------------------------------------------- -// DXBC containers and the FSSM program - -// The payload of one DXBC part ("DXIL", "PRIV", ...), or an empty span. -inline std::span dxbc_part(std::span container, const char (&fourcc)[5]) { - const auto u32 = [&](std::size_t at) -> std::uint32_t { - if (at + 4 > container.size()) return 0; - std::uint32_t v; - std::memcpy(&v, container.data() + at, 4); - return v; - }; - if (container.size() < 32 || std::memcmp(container.data(), "DXBC", 4) != 0) return {}; - const std::uint32_t parts = u32(28); - if (parts > (container.size() - 32) / 4) return {}; - for (std::uint32_t i = 0; i < parts; ++i) { - const std::uint32_t at = u32(32 + 4 * std::size_t(i)); - if (std::size_t(at) + 8 > container.size()) return {}; - const std::uint32_t size = u32(std::size_t(at) + 4); - if (std::size_t(at) + 8 + size > container.size()) return {}; - if (std::memcmp(container.data() + at, fourcc, 4) == 0) return container.subspan(at + 8, size); - } - return {}; -} - -// The FSSM blob of a shader: inflated from the container's DXIL/XDAT/XBCH entry, or the bytecode itself when it is -// already a bare FSSM blob. Empty when neither applies. -inline std::vector fssm_program(std::span bytecode) { - if (bytecode.size() >= 4 && std::memcmp(bytecode.data(), "FSSM", 4) == 0) - return {bytecode.begin(), bytecode.end()}; - const auto dxil = dxbc_part(bytecode, "DXIL"); - const auto u32 = [&](std::size_t at) -> std::uint32_t { - if (at + 4 > dxil.size()) return 0; - std::uint32_t v; - std::memcpy(&v, dxil.data() + at, 4); - return v; - }; - std::size_t xdat = 0; - for (; xdat + 4 <= dxil.size(); ++xdat) - if (std::memcmp(dxil.data() + xdat, "XDAT", 4) == 0) break; - if (xdat + 12 > dxil.size()) return {}; - // Some containers carry two different 0x0D payloads (195 of 26,503, tools/fssm_unpack.py). The translator's - // fssm_sha256 is taken from the last one (fssm_unpack.py's default, which make_game.py uses), so this does too. - const std::uint32_t count = u32(xdat + 4); - std::span blob; - for (std::uint32_t i = 0; i < count; ++i) { - const std::size_t entry = xdat + 12 + 12 * std::size_t(i); - if (entry + 12 > dxil.size()) return {}; - const std::uint32_t tag = u32(entry), offset = u32(entry + 4), size = u32(entry + 8); - if (tag != 0x0d) continue; - if (std::size_t(offset) + size > dxil.size() || size < 24) return {}; - blob = dxil.subspan(offset, size); - } - if (blob.empty() || std::memcmp(blob.data(), "XBCH", 4) != 0) return {}; - std::uint32_t unpacked; - std::memcpy(&unpacked, blob.data() + 16, 4); - std::vector out; - if (!zlib_inflate(blob.subspan(24), out, unpacked) || out.size() != unpacked) return {}; - return out; -} - -// --------------------------------------------------------------------------------------------------------------- -// FSPX payloads: the FidelityFX DLL's compute programs (docs/fspx.md) - -// The two entries of an FSPX payload the runtime reads: kind 0 (dispatch state) and kind 6 (the program). -struct FspxParts { - std::span state, code; -}; - -// Kinds 0 and 6 of an FSPX payload, both empty when the payload is not one the DLL's reader accepts. Same rules as -// that reader and tools/fspx_unpack.py's parse_fspx: the total is clamped to the buffer, the directory must fit it, -// an entry whose range starts inside the directory or ends past the total is skipped, the last entry of a kind wins, -// and kind 0 and kind 6 must both be there and non-empty. -inline FspxParts fspx_parts(std::span payload) { - const auto u32 = [&](std::size_t at) { - std::uint32_t v; - std::memcpy(&v, payload.data() + at, 4); - return v; - }; - if (payload.size() < 16 || std::memcmp(payload.data(), "FSPX", 4) != 0) return {}; - const std::uint64_t total = std::min(u32(12), payload.size()); - const std::uint64_t end_dir = 16 + 16 * std::uint64_t(u32(8)); - if (total < end_dir) return {}; - std::uint64_t code_offset = 0, code_size = 0, state_offset = 0, state_size = 0; - for (std::uint64_t at = 16; at < end_dir; at += 16) { - const std::uint32_t kind = u32(std::size_t(at)), offset = u32(std::size_t(at) + 4), - size = u32(std::size_t(at) + 8); - if (offset < end_dir || std::uint64_t(offset) + size > total) continue; // the DLL skips it too - if (kind == 6) code_offset = offset, code_size = size; - if (kind == 0) state_offset = offset, state_size = size; - } - if (!state_size || !code_size) return {}; - return {payload.subspan(std::size_t(state_offset), std::size_t(state_size)), - payload.subspan(std::size_t(code_offset), std::size_t(code_size))}; -} - -// The kind-6 program of an FSPX payload, or an empty span (fspx_parts). -inline std::span fspx_program(std::span payload) { - return fspx_parts(payload).code; -} - -// One pointer and size pair of the description device slot 67 receives (docs/fspx.md, "How the DLL reads it"). -struct FspxPart { - std::uint32_t kind; - const void* data; - std::uint64_t size; -}; - -// The largest entry fspx_payload_from_parts takes: far above the 1.0.2.1 DLL's largest (a 41,536-byte program), and -// small enough that the payload's u32 offsets cannot overflow. -inline constexpr std::uint64_t kFspxPartLimit = 16u << 20; - -// An FSPX payload built from the pairs of a slot-67 description, in the layout fspx_parts() reads: the header, one -// directory entry per present pair and the entries' bytes after it, each at a 16-byte boundary. A pair is present -// when its pointer is non-null and its size non-zero; a pointer without a size or a size without a pointer, a size -// over kFspxPartLimit, a kind other than 0, 1, 6 and 7, the same kind twice, or a missing kind 0 or kind 6 gives an -// empty result, and nothing is read. Every pointer is read only for its own size. -inline std::vector fspx_payload_from_parts(std::span parts) { - bool seen[8] = {}; - std::vector present; - for (const FspxPart& part : parts) { - if (part.kind > 7 || (part.kind != 0 && part.kind != 1 && part.kind != 6 && part.kind != 7)) return {}; - if (seen[part.kind]) return {}; - seen[part.kind] = true; - if (!part.data && !part.size) continue; - if (!part.data || !part.size || part.size > kFspxPartLimit) return {}; - present.push_back(&part); - } - const auto has = [&](std::uint32_t kind) { - return std::any_of(present.begin(), present.end(), [&](const FspxPart* p) { return p->kind == kind; }); - }; - if (!has(0) || !has(6)) return {}; - const auto align = [](std::uint64_t v) { return (v + 15) & ~std::uint64_t(15); }; - std::uint64_t at = align(16 + 16 * std::uint64_t(present.size())); - std::vector offsets; - for (const FspxPart* p : present) { - offsets.push_back(at); - at = align(at + p->size); - } - std::vector out(std::size_t(at), 0); - const auto put = [&](std::size_t where, std::uint32_t v) { std::memcpy(out.data() + where, &v, 4); }; - std::memcpy(out.data(), "FSPX", 4); - put(4, 1); - put(8, std::uint32_t(present.size())); - put(12, std::uint32_t(at)); - for (std::size_t i = 0; i < present.size(); ++i) { - put(16 + 16 * i, present[i]->kind); - put(16 + 16 * i + 4, std::uint32_t(offsets[i])); - put(16 + 16 * i + 8, std::uint32_t(present[i]->size)); - std::memcpy(out.data() + offsets[i], present[i]->data, std::size_t(present[i]->size)); - } - return out; -} - -// Whether `code` looks like a bare kind-6 program: the 36-byte prologue of three VOP3 words with opcode 0x180 -// (bits 31..16 = 0xD580) at words 0, 3 and 6, which all 29 programs of the 1.0.2.1 DLL have (docs/fspx.md). -inline bool fspx_bare_program(std::span code) { - if (code.size() < 36 || code.size() % 4) return false; - for (const std::size_t word : {0u, 3u, 6u}) { - std::uint32_t v; - std::memcpy(&v, code.data() + 4 * word, 4); - if (v >> 16 != 0xD580) return false; - } - return true; -} - -// What a compute shader's bytecode is looked up by in the translator's index. -struct ComputeProgram { - enum class Kind { none, fssm, fspx } kind = Kind::none; - // The bytes whose SHA-256 is the index key (fssm_sha256 or fspx_code_sha256), and which the pipeline copies to - // the GPU address arena as its code base: the program's code offsets are into them. - std::vector bytes; - // An FSPX program from a container or a bare payload: its kind-0 entry, whose SHA-256 (fspx_state_sha256) picks - // among translations of the same kind-6 bytes. Empty for a bare kind-6 program, which comes without it. - std::vector state; -}; - -// The program in a compute shader's bytecode: -// - an FSSM blob, bare or in a DXBC container's DXIL part (fssm_program), the game's own shaders; -// - the kind-6 program of an FSPX payload in a DXBC container's ACCC part, what the FidelityFX DLL passes to device -// slot 62, or of a bare FSPX payload; -// - a bare kind-6 program, what the DLL passes in its slot-67 description at +0x28 (with its exact size at +0x30). -// A DXBC container whose ACCC part is not a usable FSPX payload, and anything else, gives Kind::none. -inline ComputeProgram compute_program(std::span bytecode) { - ComputeProgram out; - out.bytes = fssm_program(bytecode); - if (!out.bytes.empty()) { - out.kind = ComputeProgram::Kind::fssm; - return out; - } - FspxParts parts; - if (bytecode.size() >= 4 && std::memcmp(bytecode.data(), "DXBC", 4) == 0) - parts = fspx_parts(dxbc_part(bytecode, "ACCC")); - else if (bytecode.size() >= 4 && std::memcmp(bytecode.data(), "FSPX", 4) == 0) - parts = fspx_parts(bytecode); - else if (fspx_bare_program(bytecode)) - parts.code = bytecode; - if (parts.code.empty()) return out; - out.kind = ComputeProgram::Kind::fspx; - out.bytes.assign(parts.code.begin(), parts.code.end()); - out.state.assign(parts.state.begin(), parts.state.end()); - return out; -} - -// --------------------------------------------------------------------------------------------------------------- -// The translator's spirv/index.json - -// One element of a shader's DXBC input signature (ISG1), as tools/shader_meta.py records it. For a vertex shader -// the register is the Vulkan input location the translator gave it (docs/design.md, "Vertex fetch"). -struct SignatureElement { - std::string semantic; - std::uint32_t semantic_index = 0; - std::uint32_t register_index = 0; - std::uint32_t system_value = 0; // 0: an ordinary input fed by the input layout - std::string component_type; // "float", "uint", "sint" -}; - -struct ShaderEntry { - std::string name; - std::string stage; // "vs", "ps", "cs", "ms", "gs" - std::string fssm_sha256; - std::string fspx_code_sha256; // an FSPX program (docs/fspx.md): the SHA-256 of its kind-6 bytes - std::string fspx_state_sha256; // and of its kind-0 entry (dispatch state) - std::size_t binding_count = 0; // set-0 bindings the module declares - std::uint32_t push_constant_bytes = 0; - std::array local_size{1, 1, 1}; - // Workgroup memory the module declares: its LDS array plus what --wave64-emulate adds (SHADER-309). A compute - // pipeline needs it at or under the device's maxComputeSharedMemorySize (32768 on some drivers). - std::uint32_t lds_bytes = 0; - bool uses_code_base = false; - bool wave64 = false; - // The subgroup size the translator assumed (64 for a wave64 shader, 32 otherwise); 0 when the entry says null, - // as one translated with --wave64-emulate does, or has none. - std::uint32_t subgroup_size = 0; - // "workgroup" for a shader translated with --wave64-emulate: it uses no subgroup operation and is exact on any - // subgroup size. Empty for a native translation. - std::string wave64_exchange; - bool emulated() const { return wave64_exchange == "workgroup"; } - std::vector input_signature; // vertex shaders: what the input layout must feed - std::vector inputs; // pixel shaders: input locations declared - std::vector outputs; // pixel/vertex shaders: output locations written - // --f16-interp-fallback: param/attr index -> {low_half_location, high_half_location} (SHADER-378). - std::map> f16_halves; - // The S#s the shader builds from immediates (the index's literal_samplers): no heap slot names them, so a - // pipeline that uses the shader registers them in the bindless set itself (docs/design.md, Literal samplers). - std::vector> literal_samplers; - // Mesh shaders: the output array sizes the SPIR-V declares (OutputVertices / OutputPrimitivesEXT), checked - // against the device's maxMeshOutputVertices / maxMeshOutputPrimitives when a pipeline is created. 0: not given. - std::uint32_t max_vertices = 0; - std::uint32_t max_primitives = 0; -}; - -class ShaderLibrary { -public: - // Reads /index.json, then the indexes of the programs make_game.py translates from the package's DLLs, each - // when it is there: - // - /fspx/index.json, the FidelityFX DLL's FSPX programs, entries named "fspx/" (docs/fspx.md); - // - /bvh/index.json, XboxBvhBuilder.dll's FSSM programs, entries named "bvh/" and found by - // fssm_sha256 like the game's own shaders (docs/embedded_shaders.md); - // - /library/index.json, the compute programs of the pipeline library in shaders.rpf, which the executable - // creates with slot 67; entries named "library/" and found by fspx_code_sha256 and fspx_state_sha256 - // like the FSPX ones (docs/shader_library.md). - // Entries with neither fssm_sha256 nor fspx_code_sha256 cannot be found by content and are skipped. Both folders - // are optional: a missing or unreadable index there leaves the main one, and the other folder's, loaded. - bool load(const std::filesystem::path& dir, std::string* error = nullptr) { - const auto fail = [&](const std::string& why) { - if (error) *error = why; - return false; - }; - // Nothing here may throw into the D3D12 shim (only allocation can, and that is caught too). - std::filesystem::path folder; - try { - // The modules are read when a pipeline needs them, later than this. A relative folder would follow the - // current directory, which the title may change (SetCurrentDirectory), so it is fixed here once. - std::error_code ec; - folder = std::filesystem::absolute(dir, ec); - if (ec) folder = dir; - if (!load_index(folder, "", fail)) return false; - } catch (...) { - return fail("index.json could not be read"); - } - for (const char* sub_folder : {"fspx", "bvh", "library"}) { - try { - const auto ignore = [](const std::string&) { return false; }; - const std::filesystem::path sub = folder / sub_folder; - if (std::ifstream(sub / "index.json", std::ios::binary)) - load_index(sub, std::string(sub_folder) + "/", ignore); - } catch (...) { - } - } - return true; - } - - bool loaded() const { return !dir_.empty(); } - // The folder load() read, made absolute; empty before. - const std::filesystem::path& directory() const { return dir_; } - std::size_t size() const { return count_; } - // Entries loaded from /fspx/index.json and /library/index.json. A corpus of RPF containers never - // reaches these: their programs come from FidelityFX DLLs and the pipeline library, so callers comparing reached - // entries with size() must leave them out. - std::size_t fspx_size() const { return fspx_count_; } - // Entries loaded from /bvh/index.json. No RPF container reaches these either: XboxBvhBuilder.dll passes - // their containers itself. - std::size_t bvh_size() const { return bvh_count_; } - - // The first entry for this program. Two containers can hold the same FSSM program with different input - // signatures; `candidates` returns all of them. - const ShaderEntry* find(std::string_view stage, std::string_view fssm_sha256) const { - const auto all = candidates(stage, fssm_sha256); - return all.empty() ? nullptr : all.front(); - } - - std::vector candidates(std::string_view stage, std::string_view fssm_sha256) const { - return lookup(entries_, stage, fssm_sha256); - } - - // The entries of an FSPX program, by the SHA-256 of its kind-6 bytes (fspx_code_sha256). - std::vector fspx_candidates(std::string_view stage, std::string_view fspx_code_sha256) const { - return lookup(fspx_entries_, stage, fspx_code_sha256); - } - - // The entries for a program compute_program() found, by the key of its kind (docs/fspx.md, "Build and run-time - // lookup"): - // - FSSM: by fssm_sha256, as before; - // - FSPX with its kind-0 entry (a container or a bare payload): by fspx_code_sha256, then only the entries - // whose fspx_state_sha256 is the SHA-256 of that kind-0 entry; - // - a bare kind-6 program, which comes without kind 0: by fspx_code_sha256 when all those entries have the - // same module and runtime metadata; otherwise the program is ambiguous and the result is empty. - std::vector program_candidates(std::string_view stage, const ComputeProgram& program, - bool* ambiguous = nullptr) const { - if (ambiguous) *ambiguous = false; - if (program.kind == ComputeProgram::Kind::none) return {}; - const std::string hash = sha256_hex(program.bytes); - if (program.kind == ComputeProgram::Kind::fssm) return candidates(stage, hash); - auto all = fspx_candidates(stage, hash); - if (!program.state.empty()) { - const std::string state = sha256_hex(program.state); - std::erase_if(all, [&](const ShaderEntry* e) { return e->fspx_state_sha256 != state; }); - return all; - } - if (all.size() > 1) { - const auto first = spirv(*all.front()); - const auto runtime_metadata = [](const ShaderEntry& e) { - return std::tie(e.binding_count, e.push_constant_bytes, e.local_size, e.lds_bytes, e.uses_code_base, - e.wave64, e.subgroup_size, e.wave64_exchange, e.literal_samplers); - }; - for (std::size_t i = 1; i < all.size(); ++i) { - if (first.empty() || runtime_metadata(*all[i]) != runtime_metadata(*all.front()) || - spirv(*all[i]) != first) { - if (ambiguous) *ambiguous = true; - return {}; - } - } - } - return all; - } - - // The module's words, or empty when /.spv is missing or not SPIR-V. - std::vector spirv(const ShaderEntry& entry) const { - auto path = dir_; - path += "/" + entry.name + ".spv"; - std::ifstream file(path, std::ios::binary | std::ios::ate); - return read_spirv_words(file, file.tellg()); - } - -private: - // A non-negative integer field, or 0 when it is missing, not a number or out of range. - static std::uint32_t u32(const Json* value) { - if (!value || value->kind != Json::Kind::number) return 0; - const double n = value->number; - return n >= 0 && n <= 4294967295.0 ? std::uint32_t(n) : 0; - } - - using LookupKey = std::pair; - struct KeyLess { - using is_transparent = void; - bool operator()(LookupKey a, LookupKey b) const { return a < b; } - }; - using Entries = std::map, std::vector, KeyLess>; - - static std::vector lookup(const Entries& entries, std::string_view stage, std::string_view key) { - std::vector out; - const auto it = entries.find(LookupKey{stage, key}); - if (it != entries.end()) - for (const ShaderEntry& e : it->second) out.push_back(&e); - return out; - } - - // Reads /index.json. With an empty prefix it replaces what was loaded (the main index); with a prefix it - // adds its entries under "", the path of their modules relative to the main folder. - template - bool load_index(const std::filesystem::path& dir, const std::string& prefix, Fail&& fail) { - const auto index = dir / "index.json"; - std::ifstream file(index, std::ios::binary); - if (!file) { - const auto path = index.u8string(); - return fail("cannot open " + std::string(path.begin(), path.end())); - } - const std::string text((std::istreambuf_iterator(file)), std::istreambuf_iterator()); - constexpr std::string_view utf8_bom = "\xef\xbb\xbf"; - std::string_view json(text); - if (json.starts_with(utf8_bom)) json.remove_prefix(utf8_bom.size()); - Json root; - if (!JsonReader(json).parse(root) || root.kind != Json::Kind::object) return fail("index.json is not a JSON object"); - if (prefix.empty()) { - dir_ = dir; - entries_.clear(); - fspx_entries_.clear(); - count_ = 0; - fspx_count_ = 0; - bvh_count_ = 0; - } - for (const auto& [name, meta] : root.object) { - const Json* hash = meta.find("fssm_sha256"); - const Json* code_hash = meta.find("fspx_code_sha256"); - const Json* stage = meta.find("stage"); - const bool by_fssm = hash && hash->kind == Json::Kind::string; - const bool by_fspx = code_hash && code_hash->kind == Json::Kind::string; - if ((!by_fssm && !by_fspx) || !stage || stage->kind != Json::Kind::string) continue; - ShaderEntry e; - e.name = prefix + name; - e.stage = stage->string; - if (by_fssm) e.fssm_sha256 = hash->string; - if (by_fspx) e.fspx_code_sha256 = code_hash->string; - if (const Json* s = meta.find("fspx_state_sha256"); s && s->kind == Json::Kind::string) - e.fspx_state_sha256 = s->string; - if (const Json* b = meta.find("bindings"); b && b->kind == Json::Kind::array) e.binding_count = b->array.size(); - e.push_constant_bytes = u32(meta.find("push_constant_bytes")); - e.lds_bytes = u32(meta.find("lds_bytes")); - if (const Json* l = meta.find("local_size"); l && l->kind == Json::Kind::array) - for (std::size_t i = 0; i < l->array.size() && i < 3; ++i) e.local_size[i] = u32(&l->array[i]); - if (const Json* c = meta.find("uses_code_base"); c && c->kind == Json::Kind::boolean) e.uses_code_base = c->boolean; - if (const Json* w = meta.find("wave64"); w && w->kind == Json::Kind::boolean) e.wave64 = w->boolean; - if (const Json* g = meta.find("subgroup_size"); g && g->kind == Json::Kind::number) - e.subgroup_size = u32(g); - if (const Json* x = meta.find("wave64_exchange"); x && x->kind == Json::Kind::string) - e.wave64_exchange = x->string; - if (const Json* s = meta.find("input_signature"); s && s->kind == Json::Kind::array) { - for (const Json& item : s->array) { - SignatureElement element; - if (const Json* v = item.find("semantic"); v && v->kind == Json::Kind::string) element.semantic = v->string; - element.semantic_index = u32(item.find("semantic_index")); - element.register_index = u32(item.find("register")); - element.system_value = u32(item.find("system_value")); - if (const Json* v = item.find("component_type"); v && v->kind == Json::Kind::string) - element.component_type = v->string; - e.input_signature.push_back(std::move(element)); - } - } - if (const Json* in = meta.find("inputs"); in && in->kind == Json::Kind::array) - for (const Json& item : in->array) e.inputs.push_back(u32(&item)); - if (const Json* o = meta.find("outputs"); o && o->kind == Json::Kind::array) - for (const Json& item : o->array) e.outputs.push_back(u32(&item)); - if (const Json* fh = meta.find("f16_halves"); fh && fh->kind == Json::Kind::object) { - for (const auto& [key, val] : fh->object) { - if (key.empty() || val.kind != Json::Kind::array || val.array.size() != 2) continue; - char* end = nullptr; - const unsigned long param = std::strtoul(key.c_str(), &end, 10); - if (!end || *end != '\0') continue; - e.f16_halves[std::uint32_t(param)] = {u32(&val.array[0]), u32(&val.array[1])}; - } - } - if (const Json* l = meta.find("literal_samplers"); l && l->kind == Json::Kind::array) { - for (const Json& item : l->array) { - if (item.kind != Json::Kind::array || item.array.size() != 4) continue; - std::array words{}; - for (std::size_t i = 0; i < 4; ++i) words[i] = u32(&item.array[i]); - e.literal_samplers.push_back(words); - } - } - e.max_vertices = u32(meta.find("max_vertices")); - e.max_primitives = u32(meta.find("max_primitives")); - if (by_fspx) fspx_entries_[{e.stage, e.fspx_code_sha256}].push_back(e); - if (by_fssm) entries_[{e.stage, e.fssm_sha256}].push_back(std::move(e)); - if (by_fspx && (prefix == "fspx/" || prefix == "library/")) ++fspx_count_; - if (prefix == "bvh/") ++bvh_count_; - ++count_; - } - return true; - } - - std::filesystem::path dir_; - std::size_t count_ = 0; - std::size_t fspx_count_ = 0; - std::size_t bvh_count_ = 0; - // Entries by (stage, fssm_sha256) and by (stage, fspx_code_sha256), in index order. - Entries entries_; - Entries fspx_entries_; -}; - -} // namespace leonida diff --git a/runtime/src/spirv_f16_halves.h b/runtime/src/spirv_f16_halves.h deleted file mode 100644 index ea8d4f458..000000000 --- a/runtime/src/spirv_f16_halves.h +++ /dev/null @@ -1,660 +0,0 @@ -#pragma once - -// Per-pipeline `--f16-interp-fallback` half placement and SPIR-V specialization (SHADER-378). -// -// Under `--f16-interp-fallback` (MoltenVK / devices without PerVertexKHR), a pixel shader reads decoded f16 halves -// as ordinary smooth vec4 inputs recorded in `index.json` under `f16_halves: {param: [lo_loc, hi_loc]}`. When a -// producer (VS) exports many params (up to 16) or a PS reads high attributes alongside f16 attributes, no fixed -// static location map fits all pairs within MoltenVK's 30 locations (0..29, 124 output components counting -// gl_Position). At graphics PSO creation, once both VS and PS are known, `link_f16_halves`: -// 1. Fast-paths unchanged when every PS `f16_halves` entry is already exported at the exact same locations by VS. -// 2. Chooses mutually non-colliding `[lo_loc, hi_loc]` slots in `0..top_location` (keeping PS locations unchanged -// whenever they do not collide with any raw VS output; otherwise relocating PS `OpDecorate Location` in place). -// 3. Specializes the VS SPIR-V binary for the pair: reuses matching static `f16_halves` outputs (updating their -// `Location` decorations), demotes unneeded static `f16_halves` outputs to `Private` (freeing their locations), -// and synthesizes `UnpackHalf2x16` half exports right before every `OpReturn` in the Vertex entry function for -// any param the VS did not emit statically. -// -// Pure C++20 stdlib, no Vulkan or Windows headers required. - -#include "shader_library.h" - -#include -#include -#include -#include -#include -#include -#include -#include - -namespace leonida { - -namespace spirv_detail { - -constexpr std::uint32_t kSpirvMagic = 0x07230203u; -constexpr std::uint32_t kSpirvVersion14 = 0x00010400u; - -constexpr std::uint16_t kOpSourceContinued = 2; -constexpr std::uint16_t kOpSource = 3; -constexpr std::uint16_t kOpSourceExtension = 4; -constexpr std::uint16_t kOpName = 5; -constexpr std::uint16_t kOpMemberName = 6; -constexpr std::uint16_t kOpString = 7; -constexpr std::uint16_t kOpExtension = 10; -constexpr std::uint16_t kOpExtInstImport = 11; -constexpr std::uint16_t kOpExtInst = 12; -constexpr std::uint16_t kOpMemoryModel = 14; -constexpr std::uint16_t kOpEntryPoint = 15; -constexpr std::uint16_t kOpExecutionMode = 16; -constexpr std::uint16_t kOpCapability = 17; -constexpr std::uint16_t kOpTypeInt = 21; -constexpr std::uint16_t kOpTypeFloat = 22; -constexpr std::uint16_t kOpTypeVector = 23; -constexpr std::uint16_t kOpTypePointer = 32; -constexpr std::uint16_t kOpConstantNull = 46; -constexpr std::uint16_t kOpFunction = 54; -constexpr std::uint16_t kOpFunctionEnd = 56; -constexpr std::uint16_t kOpVariable = 59; -constexpr std::uint16_t kOpLoad = 61; -constexpr std::uint16_t kOpStore = 62; -constexpr std::uint16_t kOpAccessChain = 65; -constexpr std::uint16_t kOpInBoundsAccessChain = 66; -constexpr std::uint16_t kOpDecorate = 71; -constexpr std::uint16_t kOpMemberDecorate = 72; -constexpr std::uint16_t kOpDecorationGroup = 73; -constexpr std::uint16_t kOpGroupDecorate = 74; -constexpr std::uint16_t kOpGroupMemberDecorate = 75; -constexpr std::uint16_t kOpCompositeConstruct = 80; -constexpr std::uint16_t kOpCompositeExtract = 81; -constexpr std::uint16_t kOpBitcast = 124; -constexpr std::uint16_t kOpReturn = 253; -constexpr std::uint16_t kOpModuleProcessed = 330; -constexpr std::uint16_t kOpExecutionModeId = 331; -constexpr std::uint16_t kOpDecorateId = 332; -constexpr std::uint16_t kOpDecorateString = 5632; -constexpr std::uint16_t kOpMemberDecorateString = 5633; - -constexpr std::uint32_t kExecModelVertex = 0; -constexpr std::uint32_t kExecModelFragment = 4; - -constexpr std::uint32_t kStorageInput = 1; -constexpr std::uint32_t kStorageOutput = 3; -constexpr std::uint32_t kStoragePrivate = 6; - -constexpr std::uint32_t kDecorationLocation = 30; -constexpr std::uint32_t kGlslUnpackHalf2x16 = 62; - -inline constexpr bool is_interface_only_decoration(std::uint32_t dec) { - switch (dec) { - case 13: // NoPerspective - case 14: // Flat - case 15: // Patch - case 16: // Centroid - case 17: // Sample - case 18: // Invariant - case kDecorationLocation: - case 31: // Component - return true; - default: - return false; - } -} - -struct Inst { - std::uint16_t opcode = 0; - std::vector words; -}; - -inline Inst make_inst(std::uint16_t opcode, std::initializer_list operands) { - Inst inst; - inst.opcode = opcode; - inst.words.reserve(1 + operands.size()); - inst.words.push_back((std::uint32_t(1 + operands.size()) << 16) | opcode); - for (std::uint32_t w : operands) inst.words.push_back(w); - return inst; -} - -inline Inst make_inst_vec(std::uint16_t opcode, const std::vector& operands) { - Inst inst; - inst.opcode = opcode; - inst.words.reserve(1 + operands.size()); - inst.words.push_back((std::uint32_t(1 + operands.size()) << 16) | opcode); - inst.words.insert(inst.words.end(), operands.begin(), operands.end()); - return inst; -} - -struct Module { - std::array header{}; - std::vector insts; - - bool parse(std::span words) { - if (words.size() < 5 || words[0] != kSpirvMagic || words[3] == 0) return false; - for (std::size_t i = 0; i < 5; ++i) header[i] = words[i]; - insts.clear(); - std::size_t pos = 5; - while (pos < words.size()) { - const std::uint32_t head = words[pos]; - const std::uint32_t wc = head >> 16; - const std::uint16_t op = std::uint16_t(head & 0xffffu); - if (wc == 0 || pos + wc > words.size()) return false; - Inst inst; - inst.opcode = op; - inst.words.assign(words.begin() + std::ptrdiff_t(pos), words.begin() + std::ptrdiff_t(pos + wc)); - insts.push_back(std::move(inst)); - pos += wc; - } - return true; - } - - std::vector serialize() const { - std::size_t total = 5; - for (const Inst& inst : insts) total += inst.words.size(); - std::vector out; - out.reserve(total); - out.insert(out.end(), header.begin(), header.end()); - for (const Inst& inst : insts) out.insert(out.end(), inst.words.begin(), inst.words.end()); - return out; - } - - std::uint32_t alloc_id() { return header[3]++; } -}; - -inline bool is_pre_type_opcode(std::uint16_t op) { - switch (op) { - case kOpCapability: - case kOpExtension: - case kOpExtInstImport: - case kOpMemoryModel: - case kOpEntryPoint: - case kOpExecutionMode: - case kOpExecutionModeId: - case kOpString: - case kOpSourceContinued: - case kOpSource: - case kOpSourceExtension: - case kOpName: - case kOpMemberName: - case kOpModuleProcessed: - case kOpDecorate: - case kOpMemberDecorate: - case kOpDecorationGroup: - case kOpGroupDecorate: - case kOpGroupMemberDecorate: - case kOpDecorateId: - case kOpDecorateString: - case kOpMemberDecorateString: - return true; - default: - return false; - } -} - -inline std::string decode_literal_string(std::span words) { - std::string s; - for (std::uint32_t w : words) { - for (int b = 0; b < 4; ++b) { - const char c = char((w >> (8 * b)) & 0xffu); - if (c == '\0') return s; - s.push_back(c); - } - } - return s; -} - -inline std::size_t entry_point_interface_start(const Inst& ep) { - // OpEntryPoint - for (std::size_t i = 3; i < ep.words.size(); ++i) { - const std::uint32_t w = ep.words[i]; - if ((w & 0x000000ffu) == 0 || (w & 0x0000ff00u) == 0 || (w & 0x00ff0000u) == 0 || (w & 0xff000000u) == 0) - return i + 1; - } - return ep.words.size(); -} - -// Collects global OpVariables of `storage_class` that carry `OpDecorate Location `. -// Returns map: location -> variable_id (first variable found at that location). -inline std::map collect_located_vars(const Module& mod, std::uint32_t storage_class) { - std::map var_storage; - for (const Inst& inst : mod.insts) { - if (inst.opcode == kOpFunction) break; - if (inst.opcode == kOpVariable && inst.words.size() >= 4) var_storage[inst.words[2]] = inst.words[3]; - } - std::map by_loc; - for (const Inst& inst : mod.insts) { - if (inst.opcode == kOpDecorate && inst.words.size() >= 4 && inst.words[2] == kDecorationLocation) { - const std::uint32_t target = inst.words[1]; - const auto it = var_storage.find(target); - if (it != var_storage.end() && it->second == storage_class) by_loc.emplace(inst.words[3], target); - } - } - return by_loc; -} - -} // namespace spirv_detail - -// Highest usable vec4 Location (capped at 29, MoltenVK's 124-component limit) for a device's stage interface limits. -// Reserves 4 components for BuiltIn Position (so 128 -> 29, 124 -> 29, 64 -> 14). -inline constexpr std::uint32_t f16_half_top_location(std::uint32_t max_vertex_output_components, - std::uint32_t max_fragment_input_components) { - const std::uint32_t limit = std::min(max_vertex_output_components, max_fragment_input_components); - if (limit < 8) return 0; - return std::min(29u, limit / 4u - 2u); -} - -// Specializes/patches `vs_words` and (if needed) `ps_words` so that every entry in `ps_entry.f16_halves` is -// exported by the VS at the exact smooth location the PS reads, within `0..top_location` (default 29, MoltenVK's -// 124-component vertex output limit counting gl_Position). -// -// Returns true on success (including the no-op fast path when no patching is needed). On failure returns false and -// writes a concise reason to `*error` if non-null; the caller's word vectors are only replaced on success. -inline bool link_f16_halves(std::vector& vs_words, const ShaderEntry& vs_entry, - std::vector& ps_words, const ShaderEntry& ps_entry, - std::string* error = nullptr, std::uint32_t top_location = 29) { - const auto fail = [&](const std::string& msg) { - if (error) *error = msg; - return false; - }; - if (ps_entry.f16_halves.empty() && vs_entry.f16_halves.empty()) return true; - - using namespace spirv_detail; - Module vs_mod, ps_mod; - if (!vs_mod.parse(vs_words)) return fail("f16_halves: malformed VS SPIR-V"); - if (!ps_mod.parse(ps_words)) return fail("f16_halves: malformed PS SPIR-V"); - - const auto vs_outputs = collect_located_vars(vs_mod, kStorageOutput); - const auto ps_inputs = collect_located_vars(ps_mod, kStorageInput); - - std::set vs_static_half_locs; - for (const auto& [param, pair] : vs_entry.f16_halves) { - vs_static_half_locs.insert(pair[0]); - vs_static_half_locs.insert(pair[1]); - } - std::set ps_static_half_locs; - for (const auto& [param, pair] : ps_entry.f16_halves) { - ps_static_half_locs.insert(pair[0]); - ps_static_half_locs.insert(pair[1]); - } - - // Raw outputs of VS (all located Output variables excluding VS's own static f16_halves). - std::map vs_raw_outputs; - std::set vs_raw_locs; - for (const auto& [loc, var_id] : vs_outputs) { - if (!vs_static_half_locs.count(loc)) { - vs_raw_outputs[loc] = var_id; - vs_raw_locs.insert(loc); - } - } - std::set ps_raw_locs; - for (const auto& [loc, var_id] : ps_inputs) { - if (!ps_static_half_locs.count(loc)) ps_raw_locs.insert(loc); - } - - // Fast path: every PS half pair is already exported at the exact same locations by VS, all static halves fit - // within 0..top_location, and no unused VS static half collides with a raw PS input. - bool already_linked = true; - for (const auto& [param, ps_pair] : ps_entry.f16_halves) { - const auto it = vs_entry.f16_halves.find(param); - if (it == vs_entry.f16_halves.end() || it->second != ps_pair || ps_pair[0] > top_location || - ps_pair[1] > top_location) { - already_linked = false; - break; - } - } - if (already_linked) { - for (const auto& [param, vs_pair] : vs_entry.f16_halves) { - const bool used_by_ps = ps_entry.f16_halves.count(param) != 0; - for (std::uint32_t loc : vs_pair) { - if (loc > top_location || (!used_by_ps && ps_raw_locs.count(loc))) { - already_linked = false; - break; - } - } - if (!already_linked) break; - } - } - if (already_linked) return true; - - // Choose paired [lo, hi] locations for every param in ps_entry.f16_halves. - // Keep PS's existing locations unchanged whenever none collides with VS/PS raw outputs/inputs or exceeds top_location. - bool keep_ps_locs = true; - std::set seen_ps_halves; - for (const auto& [param, pair] : ps_entry.f16_halves) { - for (std::uint32_t loc : pair) { - if (loc > top_location || vs_raw_locs.count(loc) || ps_raw_locs.count(loc) || - !seen_ps_halves.insert(loc).second) { - keep_ps_locs = false; - break; - } - } - if (!keep_ps_locs) break; - } - - std::map> pair_halves; - if (keep_ps_locs) { - pair_halves = ps_entry.f16_halves; - } else { - std::set reserved = vs_raw_locs; - reserved.insert(ps_raw_locs.begin(), ps_raw_locs.end()); - std::vector free_locs; - for (std::int64_t loc = top_location; loc >= 0; --loc) - if (!reserved.count(std::uint32_t(loc))) free_locs.push_back(std::uint32_t(loc)); - const std::size_t need = 2 * ps_entry.f16_halves.size(); - if (free_locs.size() < need) - return fail("f16_halves: need " + std::to_string(need) + " free locations in 0.." + - std::to_string(top_location) + ", only " + std::to_string(free_locs.size()) + " available"); - std::size_t k = 0; - for (const auto& [param, old_pair] : ps_entry.f16_halves) { - const std::uint32_t hi = free_locs[2 * k]; - const std::uint32_t lo = free_locs[2 * k + 1]; - pair_halves[param] = {lo, hi}; - ++k; - } - } - - // Patch PS OpDecorate Location in place if we relocated any PS half input. - bool ps_changed = false; - if (!keep_ps_locs) { - std::map ps_var_new_loc; - for (const auto& [param, old_pair] : ps_entry.f16_halves) { - const auto& new_pair = pair_halves[param]; - for (std::size_t h = 0; h < 2; ++h) { - const auto it = ps_inputs.find(old_pair[h]); - if (it != ps_inputs.end()) ps_var_new_loc[it->second] = new_pair[h]; - } - } - for (Inst& inst : ps_mod.insts) { - if (inst.opcode == kOpDecorate && inst.words.size() >= 4 && inst.words[2] == kDecorationLocation) { - const auto it = ps_var_new_loc.find(inst.words[1]); - if (it != ps_var_new_loc.end() && inst.words[3] != it->second) { - inst.words[3] = it->second; - ps_changed = true; - } - } - } - } - - // Inspect VS types, globals, entry point, and uses of existing static f16_halves variables. - std::uint32_t float_ty = 0, uint_ty = 0, v2float_ty = 0, v4float_ty = 0; - std::uint32_t ptr_out_v4_ty = 0, ptr_priv_v4_ty = 0, null_v4_id = 0, glsl_id = 0; - std::map ptr_pointee; // ptr_type_id -> pointee_type_id - std::map var_ptr_type; // var_id -> ptr_type_id - std::uint32_t vs_entry_fn = 0; - std::size_t vs_ep_idx = vs_mod.insts.size(); - - for (std::size_t idx = 0; idx < vs_mod.insts.size(); ++idx) { - const Inst& inst = vs_mod.insts[idx]; - if (inst.opcode == kOpExtInstImport && inst.words.size() >= 3) { - if (decode_literal_string(std::span(inst.words).subspan(2)) == "GLSL.std.450") - glsl_id = inst.words[1]; - } else if (inst.opcode == kOpEntryPoint && inst.words.size() >= 4 && inst.words[1] == kExecModelVertex) { - if (vs_ep_idx == vs_mod.insts.size()) { - vs_ep_idx = idx; - vs_entry_fn = inst.words[2]; - } - } else if (inst.opcode == kOpTypeFloat && inst.words.size() == 3 && inst.words[2] == 32) { - float_ty = inst.words[1]; - } else if (inst.opcode == kOpTypeInt && inst.words.size() == 4 && inst.words[2] == 32 && inst.words[3] == 0) { - uint_ty = inst.words[1]; - } else if (inst.opcode == kOpTypeVector && inst.words.size() == 4) { - if (float_ty && inst.words[2] == float_ty && inst.words[3] == 2) v2float_ty = inst.words[1]; - if (float_ty && inst.words[2] == float_ty && inst.words[3] == 4) v4float_ty = inst.words[1]; - } else if (inst.opcode == kOpTypePointer && inst.words.size() == 4) { - ptr_pointee[inst.words[1]] = inst.words[3]; - if (v4float_ty && inst.words[3] == v4float_ty) { - if (inst.words[2] == kStorageOutput) ptr_out_v4_ty = inst.words[1]; - if (inst.words[2] == kStoragePrivate) ptr_priv_v4_ty = inst.words[1]; - } - } else if (inst.opcode == kOpConstantNull && inst.words.size() == 3 && v4float_ty && inst.words[1] == v4float_ty) { - null_v4_id = inst.words[2]; - } else if (inst.opcode == kOpVariable && inst.words.size() >= 4) { - var_ptr_type[inst.words[2]] = inst.words[1]; - } else if (inst.opcode == kOpFunction) { - break; - } - } - if (vs_ep_idx == vs_mod.insts.size() || !vs_entry_fn) return fail("f16_halves: VS has no Vertex entry point"); - - // Check which existing VS variables are addressed by OpAccessChain (those cannot be trivially demoted to Private). - std::set access_chained_vars; - for (const Inst& inst : vs_mod.insts) { - if ((inst.opcode == kOpAccessChain || inst.opcode == kOpInBoundsAccessChain) && inst.words.size() >= 4) - access_chained_vars.insert(inst.words[3]); - } - - // Decide per VS static f16_halves entry: reuse (update Location) or demote (Output -> Private, drop Location). - std::map vs_var_new_loc; - std::set demote_vars; - std::set satisfied_params; - for (const auto& [param, old_pair] : vs_entry.f16_halves) { - const auto lo_it = vs_outputs.find(old_pair[0]); - const auto hi_it = vs_outputs.find(old_pair[1]); - const auto want_it = pair_halves.find(param); - if (want_it != pair_halves.end() && lo_it != vs_outputs.end() && hi_it != vs_outputs.end()) { - vs_var_new_loc[lo_it->second] = want_it->second[0]; - vs_var_new_loc[hi_it->second] = want_it->second[1]; - satisfied_params.insert(param); - } else { - for (const auto& it : {lo_it, hi_it}) { - if (it == vs_outputs.end()) continue; - const std::uint32_t vid = it->second; - const auto pty = var_ptr_type.find(vid); - const bool is_v4 = pty != var_ptr_type.end() && v4float_ty && ptr_pointee[pty->second] == v4float_ty; - if (!is_v4 || access_chained_vars.count(vid)) - return fail("f16_halves: cannot demote non-vec4 or access-chained VS static half output"); - demote_vars.insert(vid); - } - } - } - - // Params that must be synthesized in the VS epilogue. - struct SynthParam { - std::uint32_t param = 0; - std::uint32_t src_var = 0; // 0 if VS does not export this param (emit null vec4) - std::uint32_t lo_loc = 0; - std::uint32_t hi_loc = 0; - std::uint32_t lo_var = 0; - std::uint32_t hi_var = 0; - }; - std::vector synth; - bool need_null_v4 = false; - for (const auto& [param, target_pair] : pair_halves) { - if (satisfied_params.count(param)) continue; - SynthParam sp; - sp.param = param; - sp.lo_loc = target_pair[0]; - sp.hi_loc = target_pair[1]; - const auto raw_it = vs_raw_outputs.find(param); - if (raw_it != vs_raw_outputs.end()) { - const auto pty = var_ptr_type.find(raw_it->second); - if (pty == var_ptr_type.end() || !v4float_ty || ptr_pointee[pty->second] != v4float_ty) - return fail("f16_halves: VS param " + std::to_string(param) + " output is not vec4 float"); - sp.src_var = raw_it->second; - } else { - need_null_v4 = true; - } - synth.push_back(sp); - } - - // Create any missing types / GLSL.std.450 import needed for demotion or synthesis. - std::vector new_types; - const bool need_glsl = std::any_of(synth.begin(), synth.end(), [](const SynthParam& s) { return s.src_var != 0; }); - bool insert_glsl = false; - if (need_glsl && !glsl_id) { - glsl_id = vs_mod.alloc_id(); - insert_glsl = true; - } - if ((!synth.empty() || !demote_vars.empty()) && !float_ty) { - float_ty = vs_mod.alloc_id(); - new_types.push_back(make_inst(kOpTypeFloat, {float_ty, 32})); - } - if (need_glsl && !uint_ty) { - uint_ty = vs_mod.alloc_id(); - new_types.push_back(make_inst(kOpTypeInt, {uint_ty, 32, 0})); - } - if (need_glsl && !v2float_ty) { - v2float_ty = vs_mod.alloc_id(); - new_types.push_back(make_inst(kOpTypeVector, {v2float_ty, float_ty, 2})); - } - if ((!synth.empty() || !demote_vars.empty()) && !v4float_ty) { - v4float_ty = vs_mod.alloc_id(); - new_types.push_back(make_inst(kOpTypeVector, {v4float_ty, float_ty, 4})); - } - if (!synth.empty() && !ptr_out_v4_ty) { - ptr_out_v4_ty = vs_mod.alloc_id(); - new_types.push_back(make_inst(kOpTypePointer, {ptr_out_v4_ty, kStorageOutput, v4float_ty})); - } - if (!demote_vars.empty() && !ptr_priv_v4_ty) { - ptr_priv_v4_ty = vs_mod.alloc_id(); - new_types.push_back(make_inst(kOpTypePointer, {ptr_priv_v4_ty, kStoragePrivate, v4float_ty})); - } - if (need_null_v4 && !null_v4_id) { - null_v4_id = vs_mod.alloc_id(); - new_types.push_back(make_inst(kOpConstantNull, {v4float_ty, null_v4_id})); - } - - // Allocate Output OpVariables for synthesized params. - std::vector new_decorates; - std::vector new_vars; - for (SynthParam& sp : synth) { - sp.lo_var = vs_mod.alloc_id(); - sp.hi_var = vs_mod.alloc_id(); - new_decorates.push_back(make_inst(kOpDecorate, {sp.lo_var, kDecorationLocation, sp.lo_loc})); - new_decorates.push_back(make_inst(kOpDecorate, {sp.hi_var, kDecorationLocation, sp.hi_loc})); - new_vars.push_back(make_inst(kOpVariable, {ptr_out_v4_ty, sp.lo_var, kStorageOutput})); - new_vars.push_back(make_inst(kOpVariable, {ptr_out_v4_ty, sp.hi_var, kStorageOutput})); - } - - // Rebuild VS instruction stream in exact SPIR-V logical layout order. - // Demoted OpVariables are emitted right after new_types (before the first OpFunction) so ptr_priv_v4_ty is - // always defined before every OpVariable that uses it. - const bool drop_private_from_ep = vs_mod.header[1] < kSpirvVersion14; - std::vector demoted_var_insts; - std::vector out_insts; - out_insts.reserve(vs_mod.insts.size() + new_types.size() + new_decorates.size() + new_vars.size() + - synth.size() * 32); - - bool glsl_inserted = !insert_glsl; - bool decorates_inserted = new_decorates.empty(); - bool globals_inserted = new_types.empty() && new_vars.empty() && demote_vars.empty(); - bool in_entry_fn = false; - bool found_entry_return = false; - - for (std::size_t idx = 0; idx < vs_mod.insts.size(); ++idx) { - Inst inst = vs_mod.insts[idx]; - - // Insert OpExtInstImport "GLSL.std.450" right before OpMemoryModel if the module didn't already have it. - if (!glsl_inserted && inst.opcode == kOpMemoryModel) { - // "GLSL.std.450\0" -> 4 little-endian words: 0x4c534c47, 0x6474732e, 0x3035342e, 0x00000000 - out_insts.push_back( - make_inst(kOpExtInstImport, {glsl_id, 0x4c534c47u, 0x6474732eu, 0x3035342eu, 0x00000000u})); - glsl_inserted = true; - } - - // Insert new OpDecorate instructions at the end of the Annotations section (before the first type/global). - if (!decorates_inserted && !is_pre_type_opcode(inst.opcode)) { - out_insts.insert(out_insts.end(), new_decorates.begin(), new_decorates.end()); - decorates_inserted = true; - } - - // Insert new Types / Constants, demoted Private OpVariables, and new Output OpVariables before OpFunction. - if (!globals_inserted && inst.opcode == kOpFunction) { - out_insts.insert(out_insts.end(), new_types.begin(), new_types.end()); - out_insts.insert(out_insts.end(), demoted_var_insts.begin(), demoted_var_insts.end()); - out_insts.insert(out_insts.end(), new_vars.begin(), new_vars.end()); - globals_inserted = true; - } - - // Update Vertex OpEntryPoint interface list. - if (idx == vs_ep_idx) { - const std::size_t if_start = entry_point_interface_start(inst); - std::vector operands(inst.words.begin() + 1, inst.words.begin() + std::ptrdiff_t(if_start)); - for (std::size_t i = if_start; i < inst.words.size(); ++i) { - const std::uint32_t id = inst.words[i]; - if (drop_private_from_ep && demote_vars.count(id)) continue; - operands.push_back(id); - } - for (const SynthParam& sp : synth) { - operands.push_back(sp.lo_var); - operands.push_back(sp.hi_var); - } - out_insts.push_back(make_inst_vec(kOpEntryPoint, operands)); - continue; - } - - // Update Location or strip interface-only decorations on static VS f16_halves outputs. - if (inst.opcode == kOpDecorate && inst.words.size() >= 3) { - const std::uint32_t target = inst.words[1]; - const std::uint32_t dec = inst.words[2]; - if (demote_vars.count(target) && is_interface_only_decoration(dec)) continue; - if (dec == kDecorationLocation && inst.words.size() >= 4) { - const auto it = vs_var_new_loc.find(target); - if (it != vs_var_new_loc.end()) inst.words[3] = it->second; - } - out_insts.push_back(std::move(inst)); - continue; - } - - // Demote unneeded static VS f16_halves OpVariable from Output to Private (emitted after new_types). - if (!globals_inserted && inst.opcode == kOpVariable && inst.words.size() >= 4 && - demote_vars.count(inst.words[2])) { - inst.words[1] = ptr_priv_v4_ty; - inst.words[3] = kStoragePrivate; - demoted_var_insts.push_back(std::move(inst)); - continue; - } - - // Track Vertex entry function and inject UnpackHalf2x16 epilogue before every OpReturn inside it. - if (inst.opcode == kOpFunction && inst.words.size() >= 3 && inst.words[2] == vs_entry_fn) { - in_entry_fn = true; - } else if (inst.opcode == kOpFunctionEnd && in_entry_fn) { - in_entry_fn = false; - } else if (in_entry_fn && inst.opcode == kOpReturn && !synth.empty()) { - found_entry_return = true; - for (const SynthParam& sp : synth) { - if (sp.src_var == 0) { - out_insts.push_back(make_inst(kOpStore, {sp.lo_var, null_v4_id})); - out_insts.push_back(make_inst(kOpStore, {sp.hi_var, null_v4_id})); - continue; - } - const std::uint32_t raw_id = vs_mod.alloc_id(); - out_insts.push_back(make_inst(kOpLoad, {v4float_ty, raw_id, sp.src_var})); - std::array lo_c{}, hi_c{}; - for (std::uint32_t c = 0; c < 4; ++c) { - const std::uint32_t e_id = vs_mod.alloc_id(); - const std::uint32_t u_id = vs_mod.alloc_id(); - const std::uint32_t h2_id = vs_mod.alloc_id(); - const std::uint32_t a_id = vs_mod.alloc_id(); - const std::uint32_t b_id = vs_mod.alloc_id(); - out_insts.push_back(make_inst(kOpCompositeExtract, {float_ty, e_id, raw_id, c})); - out_insts.push_back(make_inst(kOpBitcast, {uint_ty, u_id, e_id})); - out_insts.push_back(make_inst(kOpExtInst, {v2float_ty, h2_id, glsl_id, kGlslUnpackHalf2x16, u_id})); - out_insts.push_back(make_inst(kOpCompositeExtract, {float_ty, a_id, h2_id, 0})); - out_insts.push_back(make_inst(kOpCompositeExtract, {float_ty, b_id, h2_id, 1})); - lo_c[c] = a_id; - hi_c[c] = b_id; - } - const std::uint32_t lo_vec = vs_mod.alloc_id(); - const std::uint32_t hi_vec = vs_mod.alloc_id(); - out_insts.push_back(make_inst(kOpCompositeConstruct, {v4float_ty, lo_vec, lo_c[0], lo_c[1], lo_c[2], lo_c[3]})); - out_insts.push_back(make_inst(kOpCompositeConstruct, {v4float_ty, hi_vec, hi_c[0], hi_c[1], hi_c[2], hi_c[3]})); - out_insts.push_back(make_inst(kOpStore, {sp.lo_var, lo_vec})); - out_insts.push_back(make_inst(kOpStore, {sp.hi_var, hi_vec})); - } - } - - out_insts.push_back(std::move(inst)); - } - - if (!synth.empty() && !found_entry_return) - return fail("f16_halves: Vertex entry point has no OpReturn to emit decoded halves"); - if (!glsl_inserted || !decorates_inserted || !globals_inserted) - return fail("f16_halves: unexpected VS SPIR-V layout"); - - vs_mod.insts = std::move(out_insts); - vs_words = vs_mod.serialize(); - if (ps_changed) ps_words = ps_mod.serialize(); - return true; -} - -} // namespace leonida diff --git a/runtime/src/spirv_stores.h b/runtime/src/spirv_stores.h deleted file mode 100644 index b8dcf2168..000000000 --- a/runtime/src/spirv_stores.h +++ /dev/null @@ -1,133 +0,0 @@ -#pragma once - -// Does a SPIR-V module declare a storage image, storage texel buffer or storage buffer it may write? -// -// Vulkan lets a shader stage other than compute write such a variable only when the device enabled a feature for -// it: fragmentStoresAndAtomics for the fragment stage (VUID-RuntimeSpirv-NonWritable-06340), and -// vertexPipelineStoresAndAtomics for the vertex, tessellation and geometry stages (-06341). Without the feature, -// every such variable of the stage must carry the NonWritable decoration. The translator declares the storage -// images of a shader that stores or does an image atomic without it, so the device has to know which modules need -// the feature before it builds a pipeline from them. -// -// The scan is conservative the way the rule is: it looks at declarations, not at whether an instruction writes. -// No Vulkan headers; the caller has already checked the binary's framing (spirv_words.h). - -#include -#include -#include -#include -#include -#include -#include - -namespace leonida { - -inline bool spirv_declares_writable_storage(std::span words) { - constexpr std::uint32_t magic = 0x07230203; - constexpr std::uint16_t op_type_image = 25, op_type_array = 28, op_type_runtime_array = 29, op_type_struct = 30, - op_type_pointer = 32, op_variable = 59, op_decorate = 71, op_member_decorate = 72, - op_group_decorate = 74, op_group_member_decorate = 75; - constexpr std::uint32_t decoration_buffer_block = 3, decoration_non_writable = 24; - constexpr std::uint32_t dim_subpass_data = 6; // an input attachment: Sampled 2 as well, but read-only - constexpr std::uint32_t class_uniform_constant = 0, class_uniform = 2, class_storage_buffer = 12; - if (words.size() < 5 || words[0] != magic) return false; - - struct Pointer { - std::uint32_t storage_class, pointee; - }; - struct Variable { - std::uint32_t pointer_type, id, storage_class; - }; - std::unordered_set storage_images; // OpTypeImage with Sampled == 2 - std::unordered_map element_of; // array type -> element type - std::unordered_map member_count; // struct type -> members - std::unordered_map pointers; - std::unordered_set non_writable, buffer_blocks; // decorated ids - std::unordered_map> non_writable_members; - std::vector variables; - // OpGroupDecorate / OpGroupMemberDecorate: a decoration group's decorations reach these targets. Resolved after - // the scan, once every OpDecorate of the group has been seen. - std::vector> group_targets; // group, target - std::vector>> group_members; // group, (type, member) - - for (std::size_t at = 5; at < words.size();) { - const std::uint32_t count = words[at] >> 16; - const std::uint16_t op = static_cast(words[at] & 0xffff); - if (count == 0 || at + count > words.size()) return false; // not a module the driver would take either - const std::uint32_t* w = &words[at]; - switch (op) { - case op_type_image: // result, sampled type, dim, depth, arrayed, ms, sampled, format - if (count >= 9 && w[7] == 2 && w[3] != dim_subpass_data) storage_images.insert(w[1]); - break; - case op_type_array: - case op_type_runtime_array: - if (count >= 3) element_of[w[1]] = w[2]; - break; - case op_type_struct: - if (count >= 2) member_count[w[1]] = count - 2; - break; - case op_type_pointer: - if (count >= 4) pointers[w[1]] = {w[2], w[3]}; - break; - case op_variable: - if (count >= 4) variables.push_back({w[1], w[2], w[3]}); - break; - case op_decorate: - if (count >= 3 && w[2] == decoration_non_writable) non_writable.insert(w[1]); - if (count >= 3 && w[2] == decoration_buffer_block) buffer_blocks.insert(w[1]); - break; - case op_member_decorate: - if (count >= 4 && w[3] == decoration_non_writable) non_writable_members[w[1]].insert(w[2]); - break; - case op_group_decorate: // group, targets... - for (std::uint32_t i = 2; i < count; ++i) group_targets.push_back({w[1], w[i]}); - break; - case op_group_member_decorate: // group, (target, member) pairs - for (std::uint32_t i = 2; i + 1 < count; i += 2) group_members.push_back({w[1], {w[i], w[i + 1]}}); - break; - default: - break; - } - at += count; - } - - for (const auto& [group, target] : group_targets) { - if (non_writable.count(group)) non_writable.insert(target); - if (buffer_blocks.count(group)) buffer_blocks.insert(target); - } - for (const auto& [group, member] : group_members) - if (non_writable.count(group)) non_writable_members[member.first].insert(member.second); - - for (const Variable& variable : variables) { - const auto pointer = pointers.find(variable.pointer_type); - if (pointer == pointers.end()) continue; - // An array of images or of buffer blocks: the element decides. Arrays nest a few levels at most; the bound - // is for a malformed module whose array type names itself, which would otherwise never end. - constexpr int max_array_depth = 16; - std::uint32_t type = pointer->second.pointee; - int depth = 0; - for (auto element = element_of.find(type); element != element_of.end() && depth < max_array_depth; - element = element_of.find(type), ++depth) - type = element->second; - if (depth == max_array_depth) continue; // not a type a driver would accept either - if (non_writable.count(variable.id)) continue; - if (variable.storage_class == class_uniform_constant) { - if (storage_images.count(type)) return true; // a storage image or a storage texel buffer - continue; - } - const bool storage_buffer = variable.storage_class == class_storage_buffer || - (variable.storage_class == class_uniform && buffer_blocks.count(type)); - if (!storage_buffer) continue; - // A block is read-only only when every declared member [0, total) is NonWritable; counting the set's size - // alone would let an out-of-range member decoration mask an undecorated writable member. - const auto members = member_count.find(type); - const auto read_only = non_writable_members.find(type); - const std::uint32_t total = members == member_count.end() ? 0 : members->second; - if (total == 0 || read_only == non_writable_members.end()) return true; - for (std::uint32_t member = 0; member < total; ++member) - if (!read_only->second.count(member)) return true; - } - return false; -} - -} // namespace leonida diff --git a/runtime/src/spirv_words.h b/runtime/src/spirv_words.h deleted file mode 100644 index e7e91fe5d..000000000 --- a/runtime/src/spirv_words.h +++ /dev/null @@ -1,26 +0,0 @@ -#pragma once - -#include -#include -#include -#include - -namespace leonida { - -// Checks the binary framing used by the translator and returns words aligned for Vulkan. -// The caller still relies on the driver or spirv-val for instruction and capability validation. -inline std::vector read_spirv_words(std::istream& input, std::streamoff byte_count) { - constexpr std::streamoff word_bytes = sizeof(std::uint32_t); - constexpr std::streamoff header_bytes = 5 * word_bytes; - if (byte_count < header_bytes || byte_count % word_bytes || !input.seekg(0)) return {}; - - std::uint32_t magic = 0; - if (!input.read(reinterpret_cast(&magic), word_bytes) || magic != 0x07230203) return {}; - - std::vector words(static_cast(byte_count / word_bytes)); - words.front() = magic; - if (!input.read(reinterpret_cast(words.data() + 1), byte_count - word_bytes)) return {}; - return words; -} - -} // namespace leonida diff --git a/runtime/src/statistics_sum.comp b/runtime/src/statistics_sum.comp deleted file mode 100644 index c4960347c..000000000 --- a/runtime/src/statistics_sum.comp +++ /dev/null @@ -1,27 +0,0 @@ -#version 450 - -// Adds the D3D12_QUERY_DATA_PIPELINE_STATISTICS segments of one split pipeline-statistics query (D3D-162): one -// invocation per counter, in the order of VkQueryPipelineStatisticFlagBits, which is the D3D12 field order. -// `mesh` segments come from the pool a mesh draw can run in (D3D-291), which counts only clipping, fragment and -// compute: they are copied to counters 5..8 of their record, so CSInvocations sits at 8 and the input-assembly, -// vertex, geometry and tessellation counters (0..4, 8 and 9 of the D3D12 order) add nothing. -layout(local_size_x = 11) in; -layout(set = 0, binding = 0, std430) buffer QueryResults { - uvec2 total[11]; - uvec2 segments[]; // `count` results of 11 counters each -}; -layout(push_constant) uniform ResolveRange { uint count; uint mesh; }; - -void main() { - const uint counter = gl_LocalInvocationID.x; - uvec2 sum = total[counter]; - const bool counted = mesh == 0u || (counter >= 5u && counter <= 7u) || counter == 10u; - const uint source = mesh != 0u && counter == 10u ? 8u : counter; - for (uint i = 0; counted && i < count; ++i) { - uvec2 segment = segments[i * 11 + source]; - uint low = sum.x + segment.x; - sum.y += segment.y + uint(low < sum.x); - sum.x = low; - } - total[counter] = sum; -} diff --git a/runtime/src/statistics_sum_spirv.h b/runtime/src/statistics_sum_spirv.h deleted file mode 100644 index 9c67f0429..000000000 --- a/runtime/src/statistics_sum_spirv.h +++ /dev/null @@ -1,69 +0,0 @@ -#pragma once - -#include - -namespace leonida { - -// From statistics_sum.comp. Compile with glslangValidator -V --target-env vulkan1.0 -Os -g0, -// then encode the little-endian SPIR-V as uint32_t words. No shader compiler is needed at runtime build time. -inline constexpr std::uint32_t statistics_sum_spirv[] = { - 0x07230203, 0x00010000, 0x0008000b, 0x00000080, 0x00000000, 0x00020011, 0x00000001, 0x0006000b, - 0x00000001, 0x4c534c47, 0x6474732e, 0x3035342e, 0x00000000, 0x0003000e, 0x00000000, 0x00000001, - 0x0006000f, 0x00000005, 0x00000004, 0x6e69616d, 0x00000000, 0x0000000b, 0x00060010, 0x00000004, - 0x00000011, 0x0000000b, 0x00000001, 0x00000001, 0x00040047, 0x0000000b, 0x0000000b, 0x0000001b, - 0x00040047, 0x00000014, 0x00000006, 0x00000008, 0x00040047, 0x00000015, 0x00000006, 0x00000008, - 0x00030047, 0x00000016, 0x00000003, 0x00050048, 0x00000016, 0x00000000, 0x00000023, 0x00000000, - 0x00050048, 0x00000016, 0x00000001, 0x00000023, 0x00000058, 0x00040047, 0x00000018, 0x00000021, - 0x00000000, 0x00040047, 0x00000018, 0x00000022, 0x00000000, 0x00030047, 0x00000022, 0x00000002, - 0x00050048, 0x00000022, 0x00000000, 0x00000023, 0x00000000, 0x00050048, 0x00000022, 0x00000001, - 0x00000023, 0x00000004, 0x00040047, 0x00000072, 0x0000000b, 0x00000019, 0x00020013, 0x00000002, - 0x00030021, 0x00000003, 0x00000002, 0x00040015, 0x00000006, 0x00000020, 0x00000000, 0x00040017, - 0x00000009, 0x00000006, 0x00000003, 0x00040020, 0x0000000a, 0x00000001, 0x00000009, 0x0004003b, - 0x0000000a, 0x0000000b, 0x00000001, 0x0004002b, 0x00000006, 0x0000000c, 0x00000000, 0x00040020, - 0x0000000d, 0x00000001, 0x00000006, 0x00040017, 0x00000010, 0x00000006, 0x00000002, 0x0004002b, - 0x00000006, 0x00000013, 0x0000000b, 0x0004001c, 0x00000014, 0x00000010, 0x00000013, 0x0003001d, - 0x00000015, 0x00000010, 0x0004001e, 0x00000016, 0x00000014, 0x00000015, 0x00040020, 0x00000017, - 0x00000002, 0x00000016, 0x0004003b, 0x00000017, 0x00000018, 0x00000002, 0x00040015, 0x00000019, - 0x00000020, 0x00000001, 0x0004002b, 0x00000019, 0x0000001a, 0x00000000, 0x00040020, 0x0000001c, - 0x00000002, 0x00000010, 0x00020014, 0x0000001f, 0x0004001e, 0x00000022, 0x00000006, 0x00000006, - 0x00040020, 0x00000023, 0x00000009, 0x00000022, 0x0004003b, 0x00000023, 0x00000024, 0x00000009, - 0x0004002b, 0x00000019, 0x00000025, 0x00000001, 0x00040020, 0x00000026, 0x00000009, 0x00000006, - 0x0004002b, 0x00000006, 0x0000002e, 0x00000005, 0x0004002b, 0x00000006, 0x00000031, 0x00000007, - 0x0004002b, 0x00000006, 0x00000036, 0x0000000a, 0x0004002b, 0x00000006, 0x00000040, 0x00000008, - 0x0004002b, 0x00000006, 0x0000005e, 0x00000001, 0x0006002c, 0x00000009, 0x00000072, 0x00000013, - 0x0000005e, 0x0000005e, 0x00050036, 0x00000002, 0x00000004, 0x00000000, 0x00000003, 0x000200f8, - 0x00000005, 0x00050041, 0x0000000d, 0x0000000e, 0x0000000b, 0x0000000c, 0x0004003d, 0x00000006, - 0x0000000f, 0x0000000e, 0x00060041, 0x0000001c, 0x0000001d, 0x00000018, 0x0000001a, 0x0000000f, - 0x0004003d, 0x00000010, 0x0000001e, 0x0000001d, 0x00050041, 0x00000026, 0x00000027, 0x00000024, - 0x00000025, 0x0004003d, 0x00000006, 0x00000028, 0x00000027, 0x000500aa, 0x0000001f, 0x00000029, - 0x00000028, 0x0000000c, 0x000400a8, 0x0000001f, 0x0000002a, 0x00000029, 0x000300f7, 0x0000002c, - 0x00000000, 0x000400fa, 0x0000002a, 0x0000002b, 0x0000002c, 0x000200f8, 0x0000002b, 0x000500ae, - 0x0000001f, 0x0000002f, 0x0000000f, 0x0000002e, 0x000500b2, 0x0000001f, 0x00000032, 0x0000000f, - 0x00000031, 0x000500a7, 0x0000001f, 0x00000033, 0x0000002f, 0x00000032, 0x000200f9, 0x0000002c, - 0x000200f8, 0x0000002c, 0x000700f5, 0x0000001f, 0x00000034, 0x00000029, 0x00000005, 0x00000033, - 0x0000002b, 0x000500aa, 0x0000001f, 0x00000037, 0x0000000f, 0x00000036, 0x000500a6, 0x0000001f, - 0x00000038, 0x00000034, 0x00000037, 0x000500ab, 0x0000001f, 0x0000003c, 0x00000028, 0x0000000c, - 0x000500a7, 0x0000001f, 0x0000003f, 0x0000003c, 0x00000037, 0x000600a9, 0x00000006, 0x00000042, - 0x0000003f, 0x00000040, 0x0000000f, 0x000200f9, 0x00000044, 0x000200f8, 0x00000044, 0x000700f5, - 0x00000010, 0x0000007f, 0x0000001e, 0x0000002c, 0x0000007c, 0x00000045, 0x000700f5, 0x00000006, - 0x0000007d, 0x0000000c, 0x0000002c, 0x0000006e, 0x00000045, 0x000400f6, 0x00000046, 0x00000045, - 0x00000000, 0x000200f9, 0x00000048, 0x000200f8, 0x00000048, 0x000300f7, 0x0000004b, 0x00000000, - 0x000400fa, 0x00000038, 0x0000004a, 0x0000004b, 0x000200f8, 0x0000004a, 0x00050041, 0x00000026, - 0x0000004d, 0x00000024, 0x0000001a, 0x0004003d, 0x00000006, 0x0000004e, 0x0000004d, 0x000500b0, - 0x0000001f, 0x0000004f, 0x0000007d, 0x0000004e, 0x000200f9, 0x0000004b, 0x000200f8, 0x0000004b, - 0x000700f5, 0x0000001f, 0x00000050, 0x00000038, 0x00000048, 0x0000004f, 0x0000004a, 0x000400fa, - 0x00000050, 0x00000045, 0x00000046, 0x000200f8, 0x00000045, 0x00050084, 0x00000006, 0x00000053, - 0x0000007d, 0x00000013, 0x00050080, 0x00000006, 0x00000055, 0x00000053, 0x00000042, 0x00060041, - 0x0000001c, 0x00000056, 0x00000018, 0x00000025, 0x00000055, 0x0004003d, 0x00000010, 0x00000057, - 0x00000056, 0x00050051, 0x00000006, 0x0000005a, 0x0000007f, 0x00000000, 0x00050051, 0x00000006, - 0x0000005c, 0x00000057, 0x00000000, 0x00050080, 0x00000006, 0x0000005d, 0x0000005a, 0x0000005c, - 0x00050051, 0x00000006, 0x00000060, 0x00000057, 0x00000001, 0x000500b0, 0x0000001f, 0x00000064, - 0x0000005d, 0x0000005a, 0x000600a9, 0x00000006, 0x00000065, 0x00000064, 0x0000005e, 0x0000000c, - 0x00050080, 0x00000006, 0x00000066, 0x00000060, 0x00000065, 0x00050051, 0x00000006, 0x00000068, - 0x0000007f, 0x00000001, 0x00050080, 0x00000006, 0x00000069, 0x00000068, 0x00000066, 0x00050050, - 0x00000010, 0x0000007c, 0x0000005d, 0x00000069, 0x00050080, 0x00000006, 0x0000006e, 0x0000007d, - 0x00000025, 0x000200f9, 0x00000044, 0x000200f8, 0x00000046, 0x0003003e, 0x0000001d, 0x0000007f, - 0x000100fd, 0x00010038, -}; - -} // namespace leonida diff --git a/runtime/src/subgroup_size.h b/runtime/src/subgroup_size.h deleted file mode 100644 index c391b7e63..000000000 --- a/runtime/src/subgroup_size.h +++ /dev/null @@ -1,158 +0,0 @@ -#pragma once - -// Subgroup size control for pipeline creation (docs/d3d12_vulkan.md, "Subgroup size"). A translated shader assumes -// one subgroup size: 64 when the game's shader was wave64, 32 otherwise (spirv/index.json `subgroup_size`). A GPU -// whose default differs runs it inexact (a wave64 shader reads lanes 32-63 of a 32-wide subgroup; a wave32 pixel -// shader on a 64-wide default reads the other half's lanes), so each stage asks for the size it was translated for -// where Vulkan allows (VK_EXT_subgroup_size_control, core in 1.3). -// -// The decision is a pure function of the shader's index entry and what the device offers, so it is tested without -// a GPU (subgroup_size_test). It depends only on the Vulkan headers. - -#include "shader_library.h" - -#include - -#include -#include - -namespace leonida { - -// What the device offers. `subgroup_size_control` and `compute_full_subgroups` say the feature is ENABLED on the -// device (the validation layers reject the structure and the flag otherwise), not merely supported. -struct SubgroupSizeCaps { - bool subgroup_size_control = false; - bool compute_full_subgroups = false; - std::uint32_t min_size = 0; - std::uint32_t max_size = 0; - std::uint32_t default_size = 0; // VkPhysicalDeviceSubgroupProperties::subgroupSize - std::uint32_t max_compute_workgroup_subgroups = 0; - VkShaderStageFlags required_stages = 0; // requiredSubgroupSizeStages -}; - -// Fills the limits of `caps` from vkGetPhysicalDeviceProperties2 and sets the two feature flags from what the -// caller enables. Returns false when the device reports no subgroup size at all. -template -bool query_subgroup_size_caps(GetProperties2 get_properties2, VkPhysicalDevice physical, bool enable_size_control, - bool enable_full_subgroups, SubgroupSizeCaps& caps) { - VkPhysicalDeviceSubgroupSizeControlProperties control{ - VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SUBGROUP_SIZE_CONTROL_PROPERTIES}; - VkPhysicalDeviceSubgroupProperties subgroup{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SUBGROUP_PROPERTIES, &control}; - VkPhysicalDeviceProperties2 properties{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROPERTIES_2, &subgroup}; - get_properties2(physical, &properties); - caps = {}; - caps.default_size = subgroup.subgroupSize; - caps.min_size = control.minSubgroupSize; - caps.max_size = control.maxSubgroupSize; - caps.max_compute_workgroup_subgroups = control.maxComputeWorkgroupSubgroups; - caps.required_stages = control.requiredSubgroupSizeStages; - caps.subgroup_size_control = enable_size_control; - caps.compute_full_subgroups = enable_full_subgroups; - return caps.default_size != 0; -} - -// The Vulkan stage of an index entry's `stage` ("cs", "ps", ...); 0 for one this layer has no pipeline for. -inline VkShaderStageFlagBits subgroup_stage_bit(std::string_view stage) { - if (stage == "cs") return VK_SHADER_STAGE_COMPUTE_BIT; - if (stage == "ps") return VK_SHADER_STAGE_FRAGMENT_BIT; - if (stage == "vs") return VK_SHADER_STAGE_VERTEX_BIT; - if (stage == "gs") return VK_SHADER_STAGE_GEOMETRY_BIT; - if (stage == "ms") return VK_SHADER_STAGE_MESH_BIT_EXT; - return VkShaderStageFlagBits(0); -} - -enum class SubgroupOutcome { - emulated, // --wave64-emulate: exact on any size, nothing is required - required, // the stage asks for `size` - device_fixed, // the device has one size and it is the wanted one: nothing to ask for - device_default, // cannot be required, but the default size is the wanted one: works, not guaranteed stable - unavailable, // the wanted size cannot be had: the shader runs at another size and may be inexact - unknown_stage, // no Vulkan stage for this entry - unknown_device, // the device sizes were not queried (all zero): nothing is asked for -}; - -struct SubgroupRequest { - SubgroupOutcome outcome = SubgroupOutcome::unknown_stage; - VkShaderStageFlagBits stage = VkShaderStageFlagBits(0); - std::uint32_t wanted = 0; // the size the translation assumed - std::uint32_t size = 0; // requiredSubgroupSize to chain; 0: chain nothing - VkPipelineShaderStageCreateFlags flags = 0; // REQUIRE_FULL_SUBGROUPS, compute only -}; - -inline bool subgroup_is_power_of_two(std::uint32_t v) { return v && !(v & (v - 1)); } - -// Overflow-safe check of local_size[0] * local_size[1] * local_size[2] <= max_invocations. -inline bool subgroup_workgroup_fits(const std::array& local_size, std::uint64_t max_invocations) { - const std::uint64_t xy = std::uint64_t(local_size[0]) * local_size[1]; - if (local_size[2] == 0) return true; - return xy <= max_invocations / local_size[2]; -} - -// What to ask for one stage of a pipeline made from `entry`. -// - Emulated (`wave64_exchange` present): nothing. -// - Otherwise the wanted size is the entry's `subgroup_size`, or 64 for a wave64 entry without one and 32 for the -// rest. VkPipelineShaderStageRequiredSubgroupSizeCreateInfo is chained when the subgroupSizeControl feature is -// enabled, the stage is in requiredSubgroupSizeStages, the size is a power of two in [min, max] and, for -// compute and mesh, the workgroup fits in size * maxComputeWorkgroupSubgroups -// (VUID-VkPipelineShaderStageCreateInfo-pNext-02755 and -02756, -// VUID-VkPipelineShaderStageRequiredSubgroupSizeCreateInfo-requiredSubgroupSize-02760..02762). -// - A compute stage also gets VK_PIPELINE_SHADER_STAGE_CREATE_REQUIRE_FULL_SUBGROUPS_BIT when computeFullSubgroups -// is enabled and the local size X is a multiple of the size (VUID-VkPipelineShaderStageCreateInfo-flags-02785: -// the flag needs the feature; -flags-08988: a compute, task or mesh stage; with a required size, -pNext-02757 -// wants X to be a multiple of it). -// - A device whose one and only subgroup size (min == max) is the wanted one needs nothing (`device_fixed`). -// - Where the size cannot be required (stage not listed, feature off) but the device default is the wanted size, -// the shader works as it is (`device_default`): nothing guarantees it, a driver may change its default. -// Otherwise the outcome is `unavailable`. -inline SubgroupRequest decide_subgroup_size(const ShaderEntry& entry, const SubgroupSizeCaps& caps) { - SubgroupRequest r; - r.stage = subgroup_stage_bit(entry.stage); - if (!r.stage) return r; - if (entry.emulated()) { - r.outcome = SubgroupOutcome::emulated; - return r; - } - r.wanted = entry.subgroup_size ? entry.subgroup_size : (entry.wave64 ? 64 : 32); - if (!caps.default_size && !caps.max_size) { - r.outcome = SubgroupOutcome::unknown_device; - return r; - } - - const bool compute_like = r.stage == VK_SHADER_STAGE_COMPUTE_BIT || r.stage == VK_SHADER_STAGE_MESH_BIT_EXT; - const std::uint64_t max_invocations = std::uint64_t(r.wanted) * caps.max_compute_workgroup_subgroups; - const bool fixed = caps.min_size && caps.min_size == caps.max_size && caps.min_size == r.wanted; - const bool requirable = - caps.subgroup_size_control && (caps.required_stages & r.stage) && subgroup_is_power_of_two(r.wanted) && - r.wanted >= caps.min_size && r.wanted <= caps.max_size && - (!compute_like || subgroup_workgroup_fits(entry.local_size, max_invocations)); - - if (fixed) { - r.outcome = SubgroupOutcome::device_fixed; - } else if (requirable) { - r.outcome = SubgroupOutcome::required; - r.size = r.wanted; - if (r.stage == VK_SHADER_STAGE_COMPUTE_BIT && caps.compute_full_subgroups && entry.local_size[0] != 0 && - entry.local_size[0] % r.wanted == 0) - r.flags |= VK_PIPELINE_SHADER_STAGE_CREATE_REQUIRE_FULL_SUBGROUPS_BIT; - } else if (caps.default_size == r.wanted) { - r.outcome = SubgroupOutcome::device_default; - } else { - r.outcome = SubgroupOutcome::unavailable; - } - return r; -} - -// Puts a request into a stage create-info. `storage` holds the chained structure and must outlive the -// vkCreate*Pipelines call. Chains in front of whatever pNext already holds. -inline void apply_subgroup_request(const SubgroupRequest& request, - VkPipelineShaderStageRequiredSubgroupSizeCreateInfo& storage, - VkPipelineShaderStageCreateInfo& stage) { - stage.flags |= request.flags; - if (!request.size) return; - storage = {VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_REQUIRED_SUBGROUP_SIZE_CREATE_INFO}; - storage.requiredSubgroupSize = request.size; - storage.pNext = const_cast(stage.pNext); - stage.pNext = &storage; -} - -} // namespace leonida diff --git a/runtime/src/tls_host.cpp b/runtime/src/tls_host.cpp deleted file mode 100644 index ab234cbd9..000000000 --- a/runtime/src/tls_host.cpp +++ /dev/null @@ -1,41 +0,0 @@ -// Minimal TLS anchor DLL for the native loader. -// -// Loading this image makes the Windows loader assign it a per-module TLS index and allocate a block for that index in -// every thread's TEB. Loader::initialize_tls reuses that reserved index for the manually mapped image, so -// __declspec(thread) access in mapped code reads a valid TEB slot. The anchor itself is never used; the loader saves -// and restores the helper's own block, so the helper's CRT TLS state is not disturbed. -// -// The Windows loader also calls this DLL's DllMain with DLL_THREAD_ATTACH on every new thread (after it has built that -// thread's TLS array) and with DLL_THREAD_DETACH when a thread exits (before it frees the array). The loader registers -// a callback here so it can give each new thread its own copy of the mapped image's TLS, and put this DLL's block back -// before the thread exits. DllMain itself must not touch TLS: this DLL's slot is the one being swapped. -#include - -__declspec(thread) unsigned char g_tls_host_anchor = 0; - -namespace { - -using ThreadEventFn = void(__cdecl*)(DWORD reason); - -// A plain global, not TLS (see above). Written once by the loader, read on every thread event. -void* volatile g_thread_event = nullptr; - -} // namespace - -// Never called. The export keeps the TLS variable (and therefore the image's TLS directory) from being dropped by -// the linker without making DllMain touch TLS during thread attach/detach. -extern "C" __declspec(dllexport) void gta6rt_tls_host_keep() { g_tls_host_anchor = 1; } - -// Called by the loader. `fn` runs inside DllMain (under the Windows loader lock) for DLL_THREAD_ATTACH and -// DLL_THREAD_DETACH; nullptr stops the calls. -extern "C" __declspec(dllexport) void gta6rt_tls_host_set_thread_event(ThreadEventFn fn) { - InterlockedExchangePointer(&g_thread_event, reinterpret_cast(fn)); -} - -BOOL WINAPI DllMain(HINSTANCE, DWORD reason, LPVOID) { - if (reason == DLL_THREAD_ATTACH || reason == DLL_THREAD_DETACH) { - void* fn = InterlockedCompareExchangePointer(&g_thread_event, nullptr, nullptr); - if (fn) reinterpret_cast(fn)(reason); - } - return TRUE; -} diff --git a/runtime/src/uav_clear.h b/runtime/src/uav_clear.h deleted file mode 100644 index b73ec50e1..000000000 --- a/runtime/src/uav_clear.h +++ /dev/null @@ -1,315 +0,0 @@ -#pragma once - -// ClearUnorderedAccessViewUint / ClearUnorderedAccessViewFloat values as the bytes of one element of a view's -// format, and those bytes as the VkClearColorValue that writes them into an image of another format of the same -// size (a typeless resource viewed through a typed UAV). Needs the Vulkan headers only. -// -// The conversion rules are D3D's (Microsoft's documentation of ID3D11DeviceContext::ClearUnorderedAccessViewUint -// and ...Float, which the D3D12 methods keep): -// - Uint copies the low n bits of value i into channel i, where n is the channel's width, with no conversion, -// whatever the format's type: 0x3f800000 into an R32_FLOAT channel is 1.0, 0xff into an R8_UNORM one is 1.0. -// A raw or structured buffer view takes value 0 for every 32-bit word. R9G9B9E5_SHAREDEXP has no independent -// per-channel integer bit layout and WARP clears it to 0 for any uint input. -// - Float converts to the format: UNORM and SNORM clamp to [0, 1] / [-1, 1] and round to nearest (NaN is 0); -// 16-bit and the packed 11/10-bit floats round toward zero, a finite value too large becoming the largest finite -// (D3D11.3 3.2.2; WARP and NVIDIA agree), and the small floats have no sign: negative is 0. -// R9G9B9E5_SHAREDEXP clamps negative/NaN to 0 and +Inf/overflow to 65408.0, shares the largest channel's -// exponent and rounds mantissas half-up (bumping the exponent on 512), matching WARP. -// D3D11 calls Float on an integer view invalid and D3D12 does not say; here the value is converted to the -// integer (rounded toward zero, clamped, NaN is 0) so the result is defined. A raw or structured buffer view -// takes value 0's bits. -// -// An image is cleared with the value that decodes those bytes in the image's own format, which is exact for every -// format here except the SNORM pattern 0x80..00 (Vulkan writes -1.0 as 0x81..), and NaN payloads, which a driver -// may canonicalise. - -#ifndef VK_NO_PROTOTYPES -#define VK_NO_PROTOTYPES -#endif -#include - -#include -#include -#include -#include -#include -#include -#include - -namespace leonida::uav_clear { - -enum class Kind : std::uint8_t { unorm, snorm, uint, sint, sfloat, ufloat, shared_exp }; - -// One channel: where its bits are in the element (little-endian, from bit 0 of byte 0) and how many. -struct Channel { - std::uint8_t offset = 0; - std::uint8_t bits = 0; // 0: the format has no such channel -}; - -struct Layout { - VkFormat format; - Kind kind; - std::uint8_t bytes; // of one element - std::array rgba; // R, G, B, A -}; - -// The formats D3D12 allows for typed UAVs (D3D12_FORMAT_SUPPORT2_UAV_TYPED_STORE), as their Vulkan formats. -inline constexpr Layout layouts[] = { - {VK_FORMAT_R32G32B32A32_SFLOAT, Kind::sfloat, 16, {{{0, 32}, {32, 32}, {64, 32}, {96, 32}}}}, - {VK_FORMAT_R32G32B32A32_UINT, Kind::uint, 16, {{{0, 32}, {32, 32}, {64, 32}, {96, 32}}}}, - {VK_FORMAT_R32G32B32A32_SINT, Kind::sint, 16, {{{0, 32}, {32, 32}, {64, 32}, {96, 32}}}}, - {VK_FORMAT_R16G16B16A16_SFLOAT, Kind::sfloat, 8, {{{0, 16}, {16, 16}, {32, 16}, {48, 16}}}}, - {VK_FORMAT_R16G16B16A16_UNORM, Kind::unorm, 8, {{{0, 16}, {16, 16}, {32, 16}, {48, 16}}}}, - {VK_FORMAT_R16G16B16A16_SNORM, Kind::snorm, 8, {{{0, 16}, {16, 16}, {32, 16}, {48, 16}}}}, - {VK_FORMAT_R16G16B16A16_UINT, Kind::uint, 8, {{{0, 16}, {16, 16}, {32, 16}, {48, 16}}}}, - {VK_FORMAT_R16G16B16A16_SINT, Kind::sint, 8, {{{0, 16}, {16, 16}, {32, 16}, {48, 16}}}}, - {VK_FORMAT_R32G32_SFLOAT, Kind::sfloat, 8, {{{0, 32}, {32, 32}, {}, {}}}}, - {VK_FORMAT_R32G32_UINT, Kind::uint, 8, {{{0, 32}, {32, 32}, {}, {}}}}, - {VK_FORMAT_R32G32_SINT, Kind::sint, 8, {{{0, 32}, {32, 32}, {}, {}}}}, - {VK_FORMAT_A2B10G10R10_UNORM_PACK32, Kind::unorm, 4, {{{0, 10}, {10, 10}, {20, 10}, {30, 2}}}}, - {VK_FORMAT_A2B10G10R10_UINT_PACK32, Kind::uint, 4, {{{0, 10}, {10, 10}, {20, 10}, {30, 2}}}}, - {VK_FORMAT_B10G11R11_UFLOAT_PACK32, Kind::ufloat, 4, {{{0, 11}, {11, 11}, {22, 10}, {}}}}, - {VK_FORMAT_E5B9G9R9_UFLOAT_PACK32, Kind::shared_exp, 4, {{{0, 9}, {9, 9}, {18, 9}, {27, 5}}}}, - {VK_FORMAT_R8G8B8A8_UNORM, Kind::unorm, 4, {{{0, 8}, {8, 8}, {16, 8}, {24, 8}}}}, - {VK_FORMAT_R8G8B8A8_SNORM, Kind::snorm, 4, {{{0, 8}, {8, 8}, {16, 8}, {24, 8}}}}, - {VK_FORMAT_R8G8B8A8_UINT, Kind::uint, 4, {{{0, 8}, {8, 8}, {16, 8}, {24, 8}}}}, - {VK_FORMAT_R8G8B8A8_SINT, Kind::sint, 4, {{{0, 8}, {8, 8}, {16, 8}, {24, 8}}}}, - {VK_FORMAT_B8G8R8A8_UNORM, Kind::unorm, 4, {{{16, 8}, {8, 8}, {0, 8}, {24, 8}}}}, - {VK_FORMAT_R16G16_SFLOAT, Kind::sfloat, 4, {{{0, 16}, {16, 16}, {}, {}}}}, - {VK_FORMAT_R16G16_UNORM, Kind::unorm, 4, {{{0, 16}, {16, 16}, {}, {}}}}, - {VK_FORMAT_R16G16_SNORM, Kind::snorm, 4, {{{0, 16}, {16, 16}, {}, {}}}}, - {VK_FORMAT_R16G16_UINT, Kind::uint, 4, {{{0, 16}, {16, 16}, {}, {}}}}, - {VK_FORMAT_R16G16_SINT, Kind::sint, 4, {{{0, 16}, {16, 16}, {}, {}}}}, - {VK_FORMAT_R32_SFLOAT, Kind::sfloat, 4, {{{0, 32}, {}, {}, {}}}}, - {VK_FORMAT_R32_UINT, Kind::uint, 4, {{{0, 32}, {}, {}, {}}}}, - {VK_FORMAT_R32_SINT, Kind::sint, 4, {{{0, 32}, {}, {}, {}}}}, - {VK_FORMAT_R8G8_UNORM, Kind::unorm, 2, {{{0, 8}, {8, 8}, {}, {}}}}, - {VK_FORMAT_R8G8_SNORM, Kind::snorm, 2, {{{0, 8}, {8, 8}, {}, {}}}}, - {VK_FORMAT_R8G8_UINT, Kind::uint, 2, {{{0, 8}, {8, 8}, {}, {}}}}, - {VK_FORMAT_R8G8_SINT, Kind::sint, 2, {{{0, 8}, {8, 8}, {}, {}}}}, - {VK_FORMAT_R16_SFLOAT, Kind::sfloat, 2, {{{0, 16}, {}, {}, {}}}}, - {VK_FORMAT_R16_UNORM, Kind::unorm, 2, {{{0, 16}, {}, {}, {}}}}, - // A4B4G4R4_UNORM: typed UAVs are the driver's call (WARP has them, AMD's D3D12 driver doesn't). - {VK_FORMAT_R4G4B4A4_UNORM_PACK16, Kind::unorm, 2, {{{12, 4}, {8, 4}, {4, 4}, {0, 4}}}}, - {VK_FORMAT_R16_SNORM, Kind::snorm, 2, {{{0, 16}, {}, {}, {}}}}, - {VK_FORMAT_R16_UINT, Kind::uint, 2, {{{0, 16}, {}, {}, {}}}}, - {VK_FORMAT_R16_SINT, Kind::sint, 2, {{{0, 16}, {}, {}, {}}}}, - {VK_FORMAT_R8_UNORM, Kind::unorm, 1, {{{0, 8}, {}, {}, {}}}}, - {VK_FORMAT_R8_SNORM, Kind::snorm, 1, {{{0, 8}, {}, {}, {}}}}, - {VK_FORMAT_R8_UINT, Kind::uint, 1, {{{0, 8}, {}, {}, {}}}}, - {VK_FORMAT_R8_SINT, Kind::sint, 1, {{{0, 8}, {}, {}, {}}}}, -}; - -inline constexpr const Layout* layout(VkFormat format) { - for (const Layout& l : layouts) - if (l.format == format) return &l; - return nullptr; -} - -// Up to one element of the largest format. -struct Element { - std::array bytes{}; - std::uint32_t size = 0; -}; - -namespace detail { - -inline constexpr std::uint32_t mask(unsigned bits) { return bits >= 32 ? 0xffffffffu : (1u << bits) - 1; } - -inline void put(Element& e, Channel c, std::uint32_t value) { - value &= mask(c.bits); - for (unsigned i = 0; i < c.bits; ++i) - if (value >> i & 1) e.bytes[(c.offset + i) / 8] |= std::uint8_t(1u << ((c.offset + i) % 8)); -} - -inline std::uint32_t get(const Element& e, Channel c) { - std::uint32_t value = 0; - for (unsigned i = 0; i < c.bits; ++i) - value |= std::uint32_t(e.bytes[(c.offset + i) / 8] >> ((c.offset + i) % 8) & 1) << i; - return value; -} - -// A float32 as a float with `mantissa` fraction bits, `exponent` exponent bits and an optional sign bit (IEEE -// half: 10, 5, signed; the packed formats: 6 or 5, 5, unsigned), rounded toward zero. Too large is the largest finite; only infinity stays infinity. -inline std::uint32_t small_float(float value, unsigned mantissa, unsigned exponent, bool sign) { - const std::uint32_t f = std::bit_cast(value); - const std::uint32_t negative = f >> 31; - const std::uint32_t max_exponent = mask(exponent); - const std::uint32_t sign_bit = sign ? negative << (mantissa + exponent) : 0; - if (std::isnan(value)) return sign_bit | (max_exponent << mantissa) | (1u << (mantissa - 1)); - if (!sign && negative) return 0; - const std::uint32_t magnitude = f & 0x7fffffffu; - if (magnitude == 0x7f800000u) return sign_bit | (max_exponent << mantissa); // infinity stays infinity - // D3D11.3 3.2.2: float-to-float conversion rounds toward zero, so a finite value too large is the largest finite. - const std::uint32_t largest = (max_exponent << mantissa) - 1; - const int bias = int(max_exponent >> 1); - const int e = int(magnitude >> 23) - 127 + bias; // the exponent field in the small format - if (e >= int(max_exponent)) return sign_bit | largest; - const std::uint32_t full = (magnitude & 0x7fffffu) | 0x800000u; // 24-bit significand - const int shift = (e > 0 ? 0 : 1 - e) + int(23 - mantissa); - if (shift > 24) return sign_bit; - const std::uint32_t kept = full >> shift; - const std::uint32_t biased = e > 0 ? (std::uint32_t(e) << mantissa) + (kept - (1u << mantissa)) : kept; - return sign_bit | biased; -} - -inline float from_small_float(std::uint32_t bits, unsigned mantissa, unsigned exponent, bool sign) { - const bool negative = sign && (bits >> (mantissa + exponent) & 1); - const std::uint32_t e = bits >> mantissa & mask(exponent); - const std::uint32_t m = bits & mask(mantissa); - const int bias = int(mask(exponent) >> 1); - float value; - if (e == mask(exponent)) - value = m ? std::numeric_limits::quiet_NaN() : std::numeric_limits::infinity(); - else if (e == 0) - value = std::ldexp(float(m), 1 - bias - int(mantissa)); - else - value = std::ldexp(float(m | (1u << mantissa)), int(e) - bias - int(mantissa)); - return negative ? -value : value; -} - -inline std::uint32_t to_float_bits(float value, const Layout& l, unsigned bits) { - if (l.kind == Kind::ufloat) return small_float(value, bits - 5, 5, false); - if (bits == 16) return small_float(value, 10, 5, true); - return std::bit_cast(value); -} - -inline float from_float_bits(std::uint32_t raw, const Layout& l, unsigned bits) { - if (l.kind == Kind::ufloat) return from_small_float(raw, bits - 5, 5, false); - if (bits == 16) return from_small_float(raw, 10, 5, true); - return std::bit_cast(raw); -} - -// Float to an integer channel: rounded toward zero, clamped, NaN is 0. -inline std::uint32_t to_integer(float value, bool is_signed, unsigned bits) { - if (std::isnan(value)) return 0; - if (is_signed) { - const double low = -std::ldexp(1.0, int(bits) - 1), high = std::ldexp(1.0, int(bits) - 1) - 1; - return std::uint32_t(std::int64_t(std::clamp(std::trunc(double(value)), low, high))); - } - return std::uint32_t(std::clamp(std::trunc(double(value)), 0.0, std::ldexp(1.0, int(bits)) - 1)); -} - -// Shared-exponent 9:9:9:5 unsigned float (EXT_texture_shared_exponent / D3D11.3). -// Clamps negative and NaN to 0 and overflow/+Inf to 65408.0 ((511/512) * 2^16), shares the largest channel's -// exponent, rounds mantissas half-up (floor(c / denom + 0.5)), and bumps the exponent if the largest mantissa -// rounds to 512. Matches ClearUnorderedAccessViewFloat on WARP. -inline std::uint32_t to_rgb9e5(float r, float g, float b) { - constexpr float max_value = 65408.0f; - const auto clamp_channel = [](float v) { return !(v > 0.0f) ? 0.0f : (v > max_value ? max_value : v); }; - r = clamp_channel(r); - g = clamp_channel(g); - b = clamp_channel(b); - const float max_c = std::max(r, std::max(g, b)); - if (max_c == 0.0f) return 0u; - int exp_raw = 0; - (void)std::frexp(max_c, &exp_raw); // floor(log2(max_c)) == exp_raw - 1 - int exp_shared = std::max(0, exp_raw + 15); - double denom = std::ldexp(1.0, exp_shared - 24); // 2^(exp_shared - 15 - 9) - const int max_m = static_cast(std::floor(double(max_c) / denom + 0.5)); - if (max_m == 512) { - ++exp_shared; - denom *= 2.0; - } - const auto rm = static_cast(std::floor(double(r) / denom + 0.5)); - const auto gm = static_cast(std::floor(double(g) / denom + 0.5)); - const auto bm = static_cast(std::floor(double(b) / denom + 0.5)); - return rm | (gm << 9) | (bm << 18) | (static_cast(exp_shared) << 27); -} - -} // namespace detail - -// The element a clear writes into a view of `format`. `values` are the call's four UINTs, or the bits of its four -// FLOATs when is_float. False: not a typed-UAV format. -inline bool encode(VkFormat format, bool is_float, const std::array& values, Element& out) { - const Layout* l = layout(format); - if (!l) return false; - out = {}; - out.size = l->bytes; - if (l->kind == Kind::shared_exp) { - const std::uint32_t word = is_float ? detail::to_rgb9e5(std::bit_cast(values[0]), - std::bit_cast(values[1]), - std::bit_cast(values[2])) - : 0u; - std::memcpy(out.bytes.data(), &word, 4); - return true; - } - for (unsigned i = 0; i < 4; ++i) { - const Channel c = l->rgba[i]; - if (!c.bits) continue; - if (!is_float) { - detail::put(out, c, values[i]); - continue; - } - const float v = std::bit_cast(values[i]); - const double scale = double(detail::mask(c.bits)); - switch (l->kind) { - case Kind::unorm: - detail::put(out, c, std::isnan(v) ? 0 : std::uint32_t(std::lround(std::clamp(double(v), 0.0, 1.0) * scale))); - break; - case Kind::snorm: { - const double max = double(detail::mask(c.bits - 1)); - detail::put(out, c, std::isnan(v) ? 0 : std::uint32_t(std::lround(std::clamp(double(v), -1.0, 1.0) * max))); - break; - } - case Kind::uint: detail::put(out, c, detail::to_integer(v, false, c.bits)); break; - case Kind::sint: detail::put(out, c, detail::to_integer(v, true, c.bits)); break; - case Kind::sfloat: - case Kind::ufloat: detail::put(out, c, detail::to_float_bits(v, *l, c.bits)); break; - case Kind::shared_exp: break; - } - } - return true; -} - -// The clear value that writes `element` into an image of `format` (same element size). False: not a format here, -// or a different size. -inline bool decode(VkFormat format, const Element& element, VkClearColorValue& out) { - const Layout* l = layout(format); - if (!l || l->bytes != element.size) return false; - out = {}; - if (l->kind == Kind::shared_exp) { - std::uint32_t word = 0; - std::memcpy(&word, element.bytes.data(), 4); - const float scale = std::ldexp(1.0f, static_cast(word >> 27) - 24); - out.float32[0] = float(word & 0x1ffu) * scale; - out.float32[1] = float((word >> 9) & 0x1ffu) * scale; - out.float32[2] = float((word >> 18) & 0x1ffu) * scale; - out.float32[3] = 1.0f; - return true; - } - for (unsigned i = 0; i < 4; ++i) { - const Channel c = l->rgba[i]; - if (!c.bits) continue; - const std::uint32_t raw = detail::get(element, c); - switch (l->kind) { - case Kind::uint: out.uint32[i] = raw; break; - case Kind::sint: { - const std::uint32_t sign = 1u << (c.bits - 1); - out.int32[i] = c.bits >= 32 ? std::int32_t(raw) : std::int32_t((raw ^ sign)) - std::int32_t(sign); - break; - } - case Kind::unorm: out.float32[i] = float(double(raw) / double(detail::mask(c.bits))); break; - case Kind::snorm: { - const std::uint32_t sign = 1u << (c.bits - 1); - const std::int32_t s = std::int32_t(raw ^ sign) - std::int32_t(sign); - out.float32[i] = std::max(-1.0f, float(double(s) / double(sign - 1))); - break; - } - case Kind::sfloat: - case Kind::ufloat: out.float32[i] = detail::from_float_bits(raw, *l, c.bits); break; - case Kind::shared_exp: break; - } - } - return true; -} - -// A raw or structured buffer view: every 32-bit word gets value 0 (its bits, for Float). -inline Element raw_element(const std::array& values) { - Element e{}; - e.size = 4; - std::memcpy(e.bytes.data(), &values[0], 4); - return e; -} - -} // namespace leonida::uav_clear diff --git a/runtime/src/vulkan13_features.h b/runtime/src/vulkan13_features.h deleted file mode 100644 index ea65caa2d..000000000 --- a/runtime/src/vulkan13_features.h +++ /dev/null @@ -1,177 +0,0 @@ -#pragma once - -// dynamicRendering and synchronization2, the two Vulkan 1.3 features the D3D12 layer needs, on a Vulkan 1.3 device -// or on a Vulkan 1.2 device through VK_KHR_dynamic_rendering and VK_KHR_synchronization2. CrossOver's MoltenVK on -// macOS is such a 1.2 device (1.2.10: Vulkan 1.2 with both extensions); the extension structs, functions and -// behaviour are the core ones under another name, so the rest of the layer does not see the difference. -// Graphics pipelines also use the 1.3 core dynamic states (primitive topology, primitive restart, vertex binding -// stride); a 1.2 device gives them through VK_EXT_extended_dynamic_state and VK_EXT_extended_dynamic_state2, enabled -// where the device has both (extended_dynamic_state). Without them the device still works for compute. -// -// leonida::Vulkan13Features v13; -// v13.query(physical, props.apiVersion, get_features2, enumerate_extensions); // per candidate -// if (!v13.usable()) continue; -// enable12.pNext = v13.enable(chain); // chain: what came after VkPhysicalDeviceVulkan13Features -// ... v13.next() is where later feature structs go (it used to be enable13.pNext) -// v13.add_extensions(device_extensions); -// fn = leonida::device_proc_or_khr(get_device_proc, device, "vkCmdPipelineBarrier2"); - -#include - -#include -#include -#include -#include - -namespace leonida { - -class Vulkan13Features { -public: - Vulkan13Features() = default; - Vulkan13Features(const Vulkan13Features&) = delete; // enable() links pointers into this object - Vulkan13Features& operator=(const Vulkan13Features&) = delete; - - bool core = false; // a Vulkan 1.3 device: the features are core - bool dynamic_rendering = false; // supported, as a core feature or through VK_KHR_dynamic_rendering - bool synchronization2 = false; // supported, as a core feature or through VK_KHR_synchronization2 - // Optional 1.3 core features, available through VK_EXT_subgroup_size_control on a 1.2 device. - bool subgroup_size_control = false; - bool compute_full_subgroups = false; - bool extended_dynamic_state = false; // core on 1.3; on 1.2 both VK_EXT_extended_dynamic_state(2) extensions - - bool usable() const { return dynamic_rendering && synchronization2; } - - // Fills the flags above for one physical device. A device older than 1.2 never qualifies. - void query(VkPhysicalDevice physical, std::uint32_t api_version, PFN_vkGetPhysicalDeviceFeatures2 features2, - PFN_vkEnumerateDeviceExtensionProperties enumerate_extensions) { - core = api_version >= VK_API_VERSION_1_3; - dynamic_rendering = synchronization2 = subgroup_size_control = compute_full_subgroups = false; - extended_dynamic_state = false; - if (!features2) return; - if (core) { - VkPhysicalDeviceVulkan13Features f13{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_3_FEATURES}; - VkPhysicalDeviceFeatures2 query{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2, &f13}; - features2(physical, &query); - dynamic_rendering = f13.dynamicRendering == VK_TRUE; - synchronization2 = f13.synchronization2 == VK_TRUE; - subgroup_size_control = f13.subgroupSizeControl == VK_TRUE; - compute_full_subgroups = f13.computeFullSubgroups == VK_TRUE; - extended_dynamic_state = true; // core in 1.3, no feature bit - return; - } - if (api_version < VK_API_VERSION_1_2 || !enumerate_extensions) return; - std::uint32_t count = 0; - enumerate_extensions(physical, nullptr, &count, nullptr); - std::vector extensions(count); - enumerate_extensions(physical, nullptr, &count, extensions.data()); - bool has_dynamic_rendering = false, has_synchronization2 = false, has_eds = false, has_eds2 = false; - bool has_subgroup_control = false; - for (const auto& e : extensions) { - has_dynamic_rendering |= std::strcmp(e.extensionName, VK_KHR_DYNAMIC_RENDERING_EXTENSION_NAME) == 0; - has_synchronization2 |= std::strcmp(e.extensionName, VK_KHR_SYNCHRONIZATION_2_EXTENSION_NAME) == 0; - has_eds |= std::strcmp(e.extensionName, VK_EXT_EXTENDED_DYNAMIC_STATE_EXTENSION_NAME) == 0; - has_eds2 |= std::strcmp(e.extensionName, VK_EXT_EXTENDED_DYNAMIC_STATE_2_EXTENSION_NAME) == 0; - has_subgroup_control |= std::strcmp(e.extensionName, VK_EXT_SUBGROUP_SIZE_CONTROL_EXTENSION_NAME) == 0; - } - if (!has_dynamic_rendering || !has_synchronization2) return; - VkPhysicalDeviceExtendedDynamicState2FeaturesEXT eds2{ - VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_EXTENDED_DYNAMIC_STATE_2_FEATURES_EXT}; - VkPhysicalDeviceExtendedDynamicStateFeaturesEXT eds{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_EXTENDED_DYNAMIC_STATE_FEATURES_EXT, - has_eds2 ? &eds2 : nullptr}; - VkPhysicalDeviceSynchronization2FeaturesKHR sync2{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SYNCHRONIZATION_2_FEATURES_KHR, - has_eds ? &eds : nullptr}; - VkPhysicalDeviceSubgroupSizeControlFeaturesEXT sg{ - VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SUBGROUP_SIZE_CONTROL_FEATURES_EXT, &sync2}; - VkPhysicalDeviceDynamicRenderingFeaturesKHR rendering{ - VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_DYNAMIC_RENDERING_FEATURES_KHR, &sync2}; - if (has_subgroup_control) rendering.pNext = &sg; - VkPhysicalDeviceFeatures2 query{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2, &rendering}; - features2(physical, &query); - dynamic_rendering = rendering.dynamicRendering == VK_TRUE; - synchronization2 = sync2.synchronization2 == VK_TRUE; - subgroup_size_control = has_subgroup_control && sg.subgroupSizeControl == VK_TRUE; - compute_full_subgroups = subgroup_size_control && sg.computeFullSubgroups == VK_TRUE; - extended_dynamic_state = has_eds && has_eds2 && eds.extendedDynamicState == VK_TRUE && - eds2.extendedDynamicState2 == VK_TRUE; - } - - // Copies the flags of the device query() chose (a later query() for another candidate overwrites them). - void choose(const Vulkan13Features& from) { - core = from.core; - dynamic_rendering = from.dynamic_rendering; - synchronization2 = from.synchronization2; - subgroup_size_control = from.subgroup_size_control; - compute_full_subgroups = from.compute_full_subgroups; - extended_dynamic_state = from.extended_dynamic_state; - } - - // The structs that enable both features, ahead of `chain`; returns their head for VkPhysicalDeviceVulkan12Features' - // pNext. Call once, after query() or choose(). - void* enable(void* chain) { - if (core) { - enable13_.pNext = chain; - enable13_.dynamicRendering = VK_TRUE; - enable13_.synchronization2 = VK_TRUE; - enable13_.subgroupSizeControl = subgroup_size_control ? VK_TRUE : VK_FALSE; - enable13_.computeFullSubgroups = compute_full_subgroups ? VK_TRUE : VK_FALSE; - return &enable13_; - } - if (subgroup_size_control) { - sg_.pNext = chain; - sg_.subgroupSizeControl = VK_TRUE; - sg_.computeFullSubgroups = compute_full_subgroups ? VK_TRUE : VK_FALSE; - chain = &sg_; - } - sync2_.pNext = chain; - sync2_.synchronization2 = VK_TRUE; - if (extended_dynamic_state) { - eds2_.pNext = chain; - eds2_.extendedDynamicState2 = VK_TRUE; - eds_.pNext = &eds2_; - eds_.extendedDynamicState = VK_TRUE; - sync2_.pNext = &eds_; - } - rendering_.pNext = &sync2_; - rendering_.dynamicRendering = VK_TRUE; - return &rendering_; - } - - // Where a feature struct goes to follow these: insert with `s.pNext = *next(); *next() = &s;`. - void** next() { - if (core) return &enable13_.pNext; - if (subgroup_size_control) return &sg_.pNext; - return extended_dynamic_state ? &eds2_.pNext : &sync2_.pNext; - } - - // The device extensions a 1.2 device needs for both features; none on 1.3. - void add_extensions(std::vector& extensions) const { - if (core) return; - extensions.push_back(VK_KHR_DYNAMIC_RENDERING_EXTENSION_NAME); - extensions.push_back(VK_KHR_SYNCHRONIZATION_2_EXTENSION_NAME); - if (subgroup_size_control) extensions.push_back(VK_EXT_SUBGROUP_SIZE_CONTROL_EXTENSION_NAME); - if (!extended_dynamic_state) return; - extensions.push_back(VK_EXT_EXTENDED_DYNAMIC_STATE_EXTENSION_NAME); - extensions.push_back(VK_EXT_EXTENDED_DYNAMIC_STATE_2_EXTENSION_NAME); - } - -private: - VkPhysicalDeviceVulkan13Features enable13_{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_3_FEATURES}; - VkPhysicalDeviceDynamicRenderingFeaturesKHR rendering_{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_DYNAMIC_RENDERING_FEATURES_KHR}; - VkPhysicalDeviceSynchronization2FeaturesKHR sync2_{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SYNCHRONIZATION_2_FEATURES_KHR}; - VkPhysicalDeviceExtendedDynamicStateFeaturesEXT eds_{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_EXTENDED_DYNAMIC_STATE_FEATURES_EXT}; - VkPhysicalDeviceSubgroupSizeControlFeaturesEXT sg_{ - VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SUBGROUP_SIZE_CONTROL_FEATURES_EXT}; - VkPhysicalDeviceExtendedDynamicState2FeaturesEXT eds2_{ - VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_EXTENDED_DYNAMIC_STATE_2_FEATURES_EXT}; -}; - -// A device function by its core name, or else by its KHR or EXT name: a Vulkan 1.2 device returns null for Vulkan -// 1.3 core names (vkCmdPipelineBarrier2, vkCmdBeginRendering, vkCmdSetPrimitiveTopology, ...) and serves the enabled -// extension's vkCmdPipelineBarrier2KHR, vkCmdSetPrimitiveTopologyEXT and the like, which have the same signatures. -inline PFN_vkVoidFunction device_proc_or_khr(PFN_vkGetDeviceProcAddr get, VkDevice device, const char* name) { - if (const PFN_vkVoidFunction function = get(device, name)) return function; - if (const PFN_vkVoidFunction function = get(device, (std::string(name) + "KHR").c_str())) return function; - return get(device, (std::string(name) + "EXT").c_str()); -} - -} // namespace leonida diff --git a/runtime/src/vulkan_backend.h b/runtime/src/vulkan_backend.h deleted file mode 100644 index 023858951..000000000 --- a/runtime/src/vulkan_backend.h +++ /dev/null @@ -1,3252 +0,0 @@ -#pragma once - -// The execution side of the D3D12 layer, without COM: the per-device Vulkan context (resources, layout tracker, -// image views), queues that execute command lists, and timeline-semaphore fences. The COM objects in -// shims/d3d12_com.cpp are thin wrappers over these. Needs Vulkan 1.2 timeline semaphores; rectangle clears and -// enhanced barriers need the Vulkan 1.3 functions (dynamicRendering, synchronization2) to be enabled, as core -// features or through their KHR extensions on a 1.2 device (vulkan13_features.h). - -#ifndef VK_NO_PROTOTYPES -#define VK_NO_PROTOTYPES -#endif -#include "binary_occlusion_spirv.h" -#include "buffer_va_index.h" -#include "occlusion_sum_spirv.h" -#include "queue_holds.h" -#include "retire_tickets.h" -#include "statistics_sum_spirv.h" -#include "vulkan13_features.h" -#include "vulkan_depth24.h" -#include "vulkan_indirect_dispatch_count.h" -#include "vulkan_scratch.h" -#include "vulkan_replay.h" -#include "queue_families.h" -#include "resource_tiling.h" -#include "xdxr_build.h" -#include "../core/log.h" - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace leonida { - -// A CPU-written Vulkan-address instance pointer array, kept until the submission that builds with it completes. -// Completed stages are pooled per queue and reused, so a per-frame TLAS build does not allocate memory each frame. -struct KhrInstanceStage { - VkBuffer buffer = VK_NULL_HANDLE; - VkDeviceMemory memory = VK_NULL_HANDLE; - VkDeviceAddress address = 0; - std::uint64_t size = 0; // bytes available in buffer, so a larger later list can be refused for a new stage -}; - -// One per-queue query pool of VK_QUERY_TYPE_ACCELERATION_STRUCTURE_COMPACTED_SIZE_KHR, retained on the -// CommandSlot until its submission completes and then recycled to the queue pool. -struct KhrAsQueryPool { - VkQueryPool pool = VK_NULL_HANDLE; - std::uint32_t capacity = 0; - std::uint32_t used = 0; -}; - -// VK_EXT_debug_utils labels: an instance extension, so a device has them only when its instance enabled it. -struct DebugLabelFunctions { - PFN_vkCmdInsertDebugUtilsLabelEXT cmd_insert = nullptr; - PFN_vkCmdBeginDebugUtilsLabelEXT cmd_begin = nullptr; - PFN_vkCmdEndDebugUtilsLabelEXT cmd_end = nullptr; - PFN_vkQueueInsertDebugUtilsLabelEXT queue_insert = nullptr; - PFN_vkQueueBeginDebugUtilsLabelEXT queue_begin = nullptr; - PFN_vkQueueEndDebugUtilsLabelEXT queue_end = nullptr; - - bool complete() const { return cmd_insert && cmd_begin && cmd_end && queue_insert && queue_begin && queue_end; } -}; - -struct VulkanDeviceFunctions { -#define LEONIDA_VK_DEVICE_FUNCTIONS(X) \ - X(vkCreateCommandPool) X(vkDestroyCommandPool) X(vkAllocateCommandBuffers) X(vkResetCommandBuffer) \ - X(vkBeginCommandBuffer) X(vkEndCommandBuffer) X(vkQueueSubmit) X(vkQueueWaitIdle) X(vkCreateSemaphore) \ - X(vkDestroySemaphore) X(vkGetSemaphoreCounterValue) X(vkWaitSemaphores) X(vkSignalSemaphore) \ - X(vkCreateImageView) X(vkDestroyImageView) X(vkCmdPipelineBarrier) X(vkCmdPipelineBarrier2) \ - X(vkCmdClearColorImage) X(vkCmdClearDepthStencilImage) X(vkCmdBeginRendering) X(vkCmdEndRendering) \ - X(vkCmdClearAttachments) X(vkDeviceWaitIdle) X(vkCreateImage) X(vkDestroyImage) \ - X(vkGetImageMemoryRequirements) X(vkBindImageMemory) X(vkCreateBuffer) X(vkDestroyBuffer) \ - X(vkGetBufferMemoryRequirements) X(vkBindBufferMemory) X(vkAllocateMemory) X(vkFreeMemory) X(vkMapMemory) \ - X(vkUnmapMemory) X(vkCmdCopyBuffer) X(vkCmdCopyBufferToImage) X(vkCmdCopyImageToBuffer) X(vkCmdCopyImage) \ - X(vkCmdResolveImage) X(vkCmdFillBuffer) X(vkCmdUpdateBuffer) X(vkCreateSampler) X(vkDestroySampler) \ - X(vkCmdBeginConditionalRenderingEXT) X(vkCmdEndConditionalRenderingEXT) X(vkCreateQueryPool) \ - X(vkDestroyQueryPool) X(vkCmdResetQueryPool) X(vkCmdBeginQuery) X(vkCmdEndQuery) X(vkCmdWriteTimestamp) \ - X(vkCmdCopyQueryPoolResults) X(vkCmdDrawIndirect) X(vkCmdDrawIndexedIndirect) X(vkCmdDrawIndirectCount) \ - X(vkCmdDrawIndexedIndirectCount) X(vkCmdDispatchIndirect) X(vkGetBufferDeviceAddress) \ - X(vkGetAccelerationStructureBuildSizesKHR) X(vkCreateAccelerationStructureKHR) \ - X(vkDestroyAccelerationStructureKHR) X(vkGetAccelerationStructureDeviceAddressKHR) \ - X(vkCmdBuildAccelerationStructuresKHR) X(vkCmdCopyAccelerationStructureKHR) \ - X(vkCmdWriteAccelerationStructuresPropertiesKHR) \ - X(vkCreateDescriptorSetLayout) X(vkDestroyDescriptorSetLayout) X(vkCreateDescriptorPool) \ - X(vkDestroyDescriptorPool) X(vkAllocateDescriptorSets) X(vkUpdateDescriptorSets) \ - X(vkCreatePipelineLayout) X(vkDestroyPipelineLayout) X(vkCreateShaderModule) X(vkDestroyShaderModule) \ - X(vkCreateComputePipelines) X(vkDestroyPipeline) X(vkCmdBindPipeline) X(vkCmdBindDescriptorSets) \ - X(vkCmdPushConstants) X(vkCmdDispatch) \ - X(vkCmdBindVertexBuffers2) X(vkCmdBindIndexBuffer) X(vkCmdSetViewport) X(vkCmdSetScissor) \ - X(vkCmdSetPrimitiveTopology) X(vkCmdSetPrimitiveRestartEnable) X(vkCmdSetStencilReference) \ - X(vkCmdSetBlendConstants) X(vkCmdDraw) \ - X(vkCmdDrawIndexed) X(vkCreateGraphicsPipelines) X(vkQueueBindSparse) X(vkGetImageSparseMemoryRequirements) \ - X(vkCreatePipelineCache) X(vkDestroyPipelineCache) \ - X(vkCreateEvent) X(vkDestroyEvent) X(vkResetEvent) X(vkCmdSetEvent) X(vkCmdWaitEvents) X(vkCmdDrawMeshTasksEXT) \ - X(vkCreateRenderPass2) X(vkDestroyRenderPass) X(vkCreateFramebuffer) X(vkDestroyFramebuffer) \ - X(vkCmdBeginRenderPass) X(vkCmdEndRenderPass) -#define LEONIDA_VK_MEMBER(name) PFN_##name name = nullptr; - LEONIDA_VK_DEVICE_FUNCTIONS(LEONIDA_VK_MEMBER) -#undef LEONIDA_VK_MEMBER - - // The Vulkan 1.3 entry points may be null on older devices, the extension ones (conditional rendering, mesh - // shaders) when the extension is not enabled, and the query functions are optional (a list that uses queries - // without them is unsupported). The compute and descriptor functions are needed for normalized or summed - // occlusion results. - bool load(PFN_vkGetDeviceProcAddr get, VkDevice device) { -#define LEONIDA_VK_LOAD(name) name = reinterpret_cast(leonida::device_proc_or_khr(get, device, #name)); - LEONIDA_VK_DEVICE_FUNCTIONS(LEONIDA_VK_LOAD) -#undef LEONIDA_VK_LOAD - return vkCreateCommandPool && vkDestroyCommandPool && vkAllocateCommandBuffers && vkResetCommandBuffer && - vkBeginCommandBuffer && vkEndCommandBuffer && vkQueueSubmit && vkQueueWaitIdle && vkCreateSemaphore && - vkDestroySemaphore && vkGetSemaphoreCounterValue && vkWaitSemaphores && vkSignalSemaphore && - vkCreateImageView && vkDestroyImageView && vkCmdPipelineBarrier && vkCmdClearColorImage && - vkCmdClearDepthStencilImage && vkCmdClearAttachments && vkDeviceWaitIdle && vkCreateImage && - vkDestroyImage && vkGetImageMemoryRequirements && vkBindImageMemory && vkCreateBuffer && - vkDestroyBuffer && vkGetBufferMemoryRequirements && vkBindBufferMemory && vkAllocateMemory && - vkFreeMemory && vkMapMemory && vkUnmapMemory && vkCmdCopyBuffer && vkCmdCopyBufferToImage && - vkCmdCopyImageToBuffer && vkCmdCopyImage && vkCmdResolveImage && vkCmdFillBuffer && - vkCmdUpdateBuffer && vkCmdBindPipeline && vkCmdPushConstants && vkCmdDispatch && - vkCreateShaderModule && vkDestroyShaderModule && vkCreatePipelineLayout && - vkDestroyPipelineLayout && vkCreateComputePipelines && vkDestroyPipeline && - vkGetBufferDeviceAddress && vkCmdBindIndexBuffer && vkCmdSetViewport && vkCmdSetScissor && - vkCmdSetStencilReference && vkCmdSetBlendConstants && vkCmdDraw && vkCmdDrawIndexed && - vkCreateGraphicsPipelines; - } - - // Graphics pipelines also need these Vulkan 1.3 entry points (dynamic rendering, extended dynamic state). - bool graphics_complete() const { - return vkCmdBeginRendering && vkCmdEndRendering && vkCmdBindVertexBuffers2 && vkCmdSetPrimitiveTopology && - vkCmdSetPrimitiveRestartEnable; - } -}; - -// Both kinds of compute resolve use the same storage buffer, descriptor set and pipeline layout. -// The destination needs transfer usage only. Pipelines are created on first use. -class OcclusionResolve { -public: - OcclusionResolve(const VulkanDeviceFunctions& vk, VkDevice device) : vk_(vk), device_(device) {} - OcclusionResolve(const OcclusionResolve&) = delete; - OcclusionResolve& operator=(const OcclusionResolve&) = delete; - - ~OcclusionResolve() { - if (sum_pipeline_) vk_.vkDestroyPipeline(device_, sum_pipeline_, nullptr); - if (binary_pipeline_) vk_.vkDestroyPipeline(device_, binary_pipeline_, nullptr); - if (statistics_pipeline_) vk_.vkDestroyPipeline(device_, statistics_pipeline_, nullptr); - if (layout_) vk_.vkDestroyPipelineLayout(device_, layout_, nullptr); - if (pool_) vk_.vkDestroyDescriptorPool(device_, pool_, nullptr); - if (set_layout_) vk_.vkDestroyDescriptorSetLayout(device_, set_layout_, nullptr); - if (scratch_) vk_.vkDestroyBuffer(device_, scratch_, nullptr); - if (memory_) vk_.vkFreeMemory(device_, memory_, nullptr); - } - - bool initialize(const VkPhysicalDeviceMemoryProperties& memory) { - if (!vk_.vkCreateDescriptorSetLayout || !vk_.vkDestroyDescriptorSetLayout || - !vk_.vkCreateDescriptorPool || !vk_.vkDestroyDescriptorPool || !vk_.vkAllocateDescriptorSets || - !vk_.vkUpdateDescriptorSets || !vk_.vkCreatePipelineLayout || !vk_.vkDestroyPipelineLayout || - !vk_.vkCreateShaderModule || !vk_.vkDestroyShaderModule || !vk_.vkCreateComputePipelines || - !vk_.vkDestroyPipeline || !vk_.vkCmdBindPipeline || !vk_.vkCmdBindDescriptorSets || - !vk_.vkCmdPushConstants || !vk_.vkCmdDispatch) - return false; - - VkBufferCreateInfo buffer{VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO}; - buffer.size = scratch_size; - buffer.usage = VK_BUFFER_USAGE_TRANSFER_SRC_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT | - VK_BUFFER_USAGE_STORAGE_BUFFER_BIT; - if (vk_.vkCreateBuffer(device_, &buffer, nullptr, &scratch_) != VK_SUCCESS) return false; - VkMemoryRequirements requirements{}; - vk_.vkGetBufferMemoryRequirements(device_, scratch_, &requirements); - auto type = memory.memoryTypeCount; - for (std::uint32_t i = 0; i < memory.memoryTypeCount; ++i) { - if (!(requirements.memoryTypeBits & (1u << i))) continue; - if (type == memory.memoryTypeCount) type = i; - if (memory.memoryTypes[i].propertyFlags & VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT) { - type = i; - break; - } - } - if (type == memory.memoryTypeCount) return false; - VkMemoryAllocateInfo allocation{VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO}; - allocation.allocationSize = requirements.size; - allocation.memoryTypeIndex = type; - if (vk_.vkAllocateMemory(device_, &allocation, nullptr, &memory_) != VK_SUCCESS || - vk_.vkBindBufferMemory(device_, scratch_, memory_, 0) != VK_SUCCESS) - return false; - - const VkDescriptorSetLayoutBinding binding{0, VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, 1, - VK_SHADER_STAGE_COMPUTE_BIT, nullptr}; - VkDescriptorSetLayoutCreateInfo set_layout{VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO}; - set_layout.bindingCount = 1; - set_layout.pBindings = &binding; - if (vk_.vkCreateDescriptorSetLayout(device_, &set_layout, nullptr, &set_layout_) != VK_SUCCESS) return false; - const VkDescriptorPoolSize size{VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, 1}; - VkDescriptorPoolCreateInfo pool{VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO}; - pool.maxSets = 1; - pool.poolSizeCount = 1; - pool.pPoolSizes = &size; - if (vk_.vkCreateDescriptorPool(device_, &pool, nullptr, &pool_) != VK_SUCCESS) return false; - VkDescriptorSetAllocateInfo set{VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO}; - set.descriptorPool = pool_; - set.descriptorSetCount = 1; - set.pSetLayouts = &set_layout_; - if (vk_.vkAllocateDescriptorSets(device_, &set, &set_) != VK_SUCCESS) return false; - const VkDescriptorBufferInfo storage{scratch_, 0, scratch_size}; - VkWriteDescriptorSet write{VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET}; - write.dstSet = set_; - write.descriptorCount = 1; - write.descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER; - write.pBufferInfo = &storage; - vk_.vkUpdateDescriptorSets(device_, 1, &write, 0, nullptr); - - // The count, and for statistics_sum.comp whether the segments are mesh-pool results. - const VkPushConstantRange count{VK_SHADER_STAGE_COMPUTE_BIT, 0, 2 * sizeof(std::uint32_t)}; - VkPipelineLayoutCreateInfo layout{VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO}; - layout.setLayoutCount = 1; - layout.pSetLayouts = &set_layout_; - layout.pushConstantRangeCount = 1; - layout.pPushConstantRanges = &count; - return vk_.vkCreatePipelineLayout(device_, &layout, nullptr, &layout_) == VK_SUCCESS; - } - - bool prepare(bool needs_sum, bool needs_binary, bool needs_statistics_sum = false, - bool needs_sum_binary = false) { - // The composite (sum then normalize, D3D-252) uses both pipelines. - needs_sum = needs_sum || needs_sum_binary; - needs_binary = needs_binary || needs_sum_binary; - return (!needs_sum || sum_pipeline_ || create_pipeline(occlusion_sum_spirv, sum_pipeline_)) && - (!needs_binary || binary_pipeline_ || create_pipeline(binary_occlusion_spirv, binary_pipeline_)) && - (!needs_statistics_sum || statistics_pipeline_ || - create_pipeline(statistics_sum_spirv, statistics_pipeline_)); - } - - // Adds `count` pipeline-statistics results into one D3D12_QUERY_DATA_PIPELINE_STATISTICS at dst + offset: the - // segments of a statistics query that was split around helper dispatches (D3D-162) or mesh draws (D3D-291). - // Segment i is in `mesh_queries` when mesh[i] is set (four counters: clipping, fragment and compute; see - // statistics_sum.comp), otherwise in `queries` (all eleven). - void sum_statistics(VkCommandBuffer cb, VkQueryPool queries, VkQueryPool mesh_queries, const std::uint8_t* mesh, - std::uint32_t first, std::uint32_t count, VkBuffer dst, VkDeviceSize offset) const { - constexpr VkDeviceSize result = statistics_counters * word_size; - constexpr VkDeviceSize mesh_slot = 5 * word_size; // CInvocations, where the mesh pool's first counter goes - begin_scratch_write(cb); - vk_.vkCmdFillBuffer(cb, scratch_, 0, result, 0); - bind(cb, statistics_pipeline_); - while (count) { - const bool in_mesh = mesh && mesh[first]; - std::uint32_t chunk = 1; - while (chunk < std::min(count, statistics_capacity) && bool(mesh && mesh[first + chunk]) == in_mesh) - ++chunk; - vk_.vkCmdCopyQueryPoolResults(cb, in_mesh ? mesh_queries : queries, first, chunk, scratch_, - result + (in_mesh ? mesh_slot : 0), result, - VK_QUERY_RESULT_64_BIT | VK_QUERY_RESULT_WAIT_BIT); - barrier(cb, transfer | compute, compute, VK_ACCESS_TRANSFER_WRITE_BIT | VK_ACCESS_SHADER_WRITE_BIT, - shader_access); - dispatch(cb, chunk, 1, in_mesh); - first += chunk; - count -= chunk; - if (count) barrier(cb, compute, transfer, shader_access, VK_ACCESS_TRANSFER_WRITE_BIT); - } - copy_result(cb, dst, offset, result); - } - - void sum(VkCommandBuffer cb, VkQueryPool queries, std::uint32_t first, std::uint32_t count, - VkBuffer dst, VkDeviceSize offset) const { - begin_scratch_write(cb); - vk_.vkCmdFillBuffer(cb, scratch_, 0, word_size, 0); - bind(cb, sum_pipeline_); - while (count) { - const auto chunk = std::min(count, sum_capacity); - vk_.vkCmdCopyQueryPoolResults(cb, queries, first, chunk, scratch_, word_size, word_size, - VK_QUERY_RESULT_64_BIT | VK_QUERY_RESULT_WAIT_BIT); - barrier(cb, transfer | compute, compute, VK_ACCESS_TRANSFER_WRITE_BIT | VK_ACCESS_SHADER_WRITE_BIT, - shader_access); - dispatch(cb, chunk, 1); - first += chunk; - count -= chunk; - if (count) barrier(cb, compute, transfer, shader_access, VK_ACCESS_TRANSFER_WRITE_BIT); - } - copy_result(cb, dst, offset, word_size); - } - - // Sums `count` binary-occlusion segments into one value and normalizes that total in place to 0 or 1: the - // result of a binary query whose interval spans more than one physical segment (overlapping queries, D3D-252). - void sum_binary(VkCommandBuffer cb, VkQueryPool queries, std::uint32_t first, std::uint32_t count, - VkBuffer dst, VkDeviceSize offset) const { - begin_scratch_write(cb); - vk_.vkCmdFillBuffer(cb, scratch_, 0, word_size, 0); - bind(cb, sum_pipeline_); - auto tail = first, left = count; - while (left) { - const auto chunk = std::min(left, sum_capacity); - vk_.vkCmdCopyQueryPoolResults(cb, queries, tail, chunk, scratch_, word_size, word_size, - VK_QUERY_RESULT_64_BIT | VK_QUERY_RESULT_WAIT_BIT); - barrier(cb, transfer | compute, compute, VK_ACCESS_TRANSFER_WRITE_BIT | VK_ACCESS_SHADER_WRITE_BIT, - shader_access); - dispatch(cb, chunk, 1); - tail += chunk; - left -= chunk; - if (left) barrier(cb, compute, transfer, shader_access, VK_ACCESS_TRANSFER_WRITE_BIT); - } - barrier(cb, compute, compute, VK_ACCESS_SHADER_WRITE_BIT, shader_access); - bind(cb, binary_pipeline_); - dispatch(cb, 1, 1); - copy_result(cb, dst, offset, word_size); - } - - void normalize(VkCommandBuffer cb, VkQueryPool queries, std::uint32_t first, std::uint32_t count, - VkBuffer dst, VkDeviceSize offset) const { - bind(cb, binary_pipeline_); - while (count) { - const auto chunk = std::min(count, binary_capacity); - const VkDeviceSize bytes = VkDeviceSize(chunk) * word_size; - begin_scratch_write(cb); - vk_.vkCmdCopyQueryPoolResults(cb, queries, first, chunk, scratch_, 0, word_size, - VK_QUERY_RESULT_64_BIT | VK_QUERY_RESULT_WAIT_BIT); - barrier(cb, transfer, compute, VK_ACCESS_TRANSFER_WRITE_BIT, shader_access); - dispatch(cb, chunk, (chunk + binary_group_size - 1) / binary_group_size); - copy_result(cb, dst, offset, bytes); - first += chunk; - count -= chunk; - offset += bytes; - } - } - -private: - bool create_pipeline(std::span code, VkPipeline& out) const { - VkShaderModuleCreateInfo module{VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO}; - module.codeSize = code.size_bytes(); - module.pCode = code.data(); - VkShaderModule shader = VK_NULL_HANDLE; - if (vk_.vkCreateShaderModule(device_, &module, nullptr, &shader) != VK_SUCCESS) return false; - VkComputePipelineCreateInfo pipeline{VK_STRUCTURE_TYPE_COMPUTE_PIPELINE_CREATE_INFO}; - pipeline.stage = {VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO, nullptr, 0, - VK_SHADER_STAGE_COMPUTE_BIT, shader, "main", nullptr}; - pipeline.layout = layout_; - VkPipeline handle = VK_NULL_HANDLE; - const VkResult result = vk_.vkCreateComputePipelines(device_, VK_NULL_HANDLE, 1, &pipeline, nullptr, &handle); - vk_.vkDestroyShaderModule(device_, shader, nullptr); - if (result == VK_SUCCESS) out = handle; - else if (handle) vk_.vkDestroyPipeline(device_, handle, nullptr); - return result == VK_SUCCESS; - } - - void bind(VkCommandBuffer cb, VkPipeline pipeline) const { - vk_.vkCmdBindPipeline(cb, VK_PIPELINE_BIND_POINT_COMPUTE, pipeline); - vk_.vkCmdBindDescriptorSets(cb, VK_PIPELINE_BIND_POINT_COMPUTE, layout_, 0, 1, &set_, 0, nullptr); - } - - void dispatch(VkCommandBuffer cb, std::uint32_t chunk, std::uint32_t groups, bool mesh = false) const { - const std::uint32_t range[2] = {chunk, mesh ? 1u : 0u}; - vk_.vkCmdPushConstants(cb, layout_, VK_SHADER_STAGE_COMPUTE_BIT, 0, sizeof(range), range); - vk_.vkCmdDispatch(cb, groups, 1, 1); - } - - void begin_scratch_write(VkCommandBuffer cb) const { - // A sum or a normalization in an earlier submission may still use this buffer. - barrier(cb, transfer | compute, transfer, - VK_ACCESS_TRANSFER_READ_BIT | VK_ACCESS_TRANSFER_WRITE_BIT | shader_access, - VK_ACCESS_TRANSFER_WRITE_BIT); - } - - void copy_result(VkCommandBuffer cb, VkBuffer dst, VkDeviceSize offset, VkDeviceSize bytes) const { - barrier(cb, compute, transfer, VK_ACCESS_SHADER_WRITE_BIT, VK_ACCESS_TRANSFER_READ_BIT); - const VkBufferCopy copy{0, offset, bytes}; - vk_.vkCmdCopyBuffer(cb, scratch_, dst, 1, ©); - } - - void barrier(VkCommandBuffer cb, VkPipelineStageFlags src, VkPipelineStageFlags dst, - VkAccessFlags before, VkAccessFlags after) const { - VkBufferMemoryBarrier memory{VK_STRUCTURE_TYPE_BUFFER_MEMORY_BARRIER}; - memory.srcAccessMask = before; - memory.dstAccessMask = after; - memory.srcQueueFamilyIndex = memory.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; - memory.buffer = scratch_; - memory.size = scratch_size; - vk_.vkCmdPipelineBarrier(cb, src, dst, 0, 0, nullptr, 1, &memory, 0, nullptr); - } - - static constexpr auto transfer = VK_PIPELINE_STAGE_TRANSFER_BIT; - static constexpr auto compute = VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT; - static constexpr VkAccessFlags shader_access = VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT; - static constexpr std::uint32_t sum_capacity = 256; // one more word holds the running sum - static constexpr std::uint32_t binary_capacity = 1024; - static constexpr std::uint32_t binary_group_size = 64; // local_size_x in binary_occlusion.comp - static constexpr std::uint32_t statistics_counters = 11; // local_size_x in statistics_sum.comp - static constexpr std::uint32_t statistics_capacity = 64; // segments per pass; 11 more words hold the sums - static constexpr VkDeviceSize word_size = sizeof(std::uint64_t); - static constexpr VkDeviceSize scratch_size = - std::max({sum_capacity + 1, binary_capacity, (statistics_capacity + 1) * statistics_counters}) * word_size; - const VulkanDeviceFunctions& vk_; - VkDevice device_; - VkBuffer scratch_ = VK_NULL_HANDLE; - VkDeviceMemory memory_ = VK_NULL_HANDLE; - VkDescriptorSetLayout set_layout_ = VK_NULL_HANDLE; - VkDescriptorPool pool_ = VK_NULL_HANDLE; - VkDescriptorSet set_ = VK_NULL_HANDLE; - VkPipelineLayout layout_ = VK_NULL_HANDLE; - VkPipeline sum_pipeline_ = VK_NULL_HANDLE; - VkPipeline binary_pipeline_ = VK_NULL_HANDLE; - VkPipeline statistics_pipeline_ = VK_NULL_HANDLE; -}; - -struct SparseResource; - -// Zero-allocation O(1) Ring Buffer deferred deletion queue tied to the device timeline semaphore. -class DeferredDeletionQueue { -public: - enum class Kind : std::uint8_t { - bindless_slot, - image_view, - image, - sparse_resource, - buffer, - device_memory, - acceleration_structure, - framebuffer, - }; - - struct Item { - std::uint64_t ticket = 0; - std::uint64_t handle = 0; // for bindless_slot: (uint64_t(dimension) << 32) | index - Kind kind = Kind::image_view; - }; - - using BindlessReleaseFn = void (*)(void* user, std::uint32_t dimension, std::uint32_t index); - - explicit DeferredDeletionQueue(std::size_t initial_capacity = 256) : pending_(next_pow2(initial_capacity)) {} - - void set_bindless_release(BindlessReleaseFn fn, void* user) { - std::lock_guard lock(mutex_); - bindless_release_fn_ = fn; - bindless_release_user_ = user; - } - - void push(std::uint64_t retire_ticket, Kind kind, std::uint64_t handle) { - if (!handle && kind != Kind::bindless_slot) return; - std::lock_guard lock(mutex_); - if (count_ == pending_.size()) { - const std::size_t old_cap = pending_.size(); - std::vector grown(old_cap * 2); - const std::size_t first = old_cap - head_; - std::memcpy(grown.data(), pending_.data() + head_, first * sizeof(Item)); - if (head_ > 0) std::memcpy(grown.data() + first, pending_.data(), head_ * sizeof(Item)); - pending_ = std::move(grown); - head_ = 0; - tail_ = count_; - } - pending_[tail_] = {retire_ticket, handle, kind}; - tail_ = (tail_ + 1) & (pending_.size() - 1); - ++count_; - } - - // Drains all items with ticket <= current_ticket in O(k), invoking vkDestroy* outside the lock. - // Uses a stack-local batch vector so concurrent drain() calls from multiple queues never race. - void drain(std::uint64_t current_ticket, VkDevice device, const VulkanDeviceFunctions& vk) { - BindlessReleaseFn release_fn = nullptr; - void* release_user = nullptr; - std::vector to_destroy; - { - std::lock_guard lock(mutex_); - if (count_ == 0 || pending_[head_].ticket > current_ticket) return; - release_fn = bindless_release_fn_; - release_user = bindless_release_user_; - const std::size_t mask = pending_.size() - 1; - while (count_ > 0 && pending_[head_].ticket <= current_ticket) { - to_destroy.push_back(pending_[head_]); - head_ = (head_ + 1) & mask; - --count_; - } - if (count_ == 0) { - head_ = 0; - tail_ = 0; - } - } - - for (const Item& item : to_destroy) { - switch (item.kind) { - case Kind::bindless_slot: - if (release_fn) { - release_fn(release_user, static_cast(item.handle >> 32), - static_cast(item.handle & 0xFFFFFFFFu)); - } - break; - case Kind::image_view: - vk.vkDestroyImageView(device, reinterpret_cast(item.handle), nullptr); - break; - case Kind::image: - vk.vkDestroyImage(device, reinterpret_cast(item.handle), nullptr); - break; - case Kind::sparse_resource: - // Releases the resource and its page backing together after outstanding submissions. - delete reinterpret_cast*>(item.handle); - break; - case Kind::buffer: - vk.vkDestroyBuffer(device, reinterpret_cast(item.handle), nullptr); - break; - case Kind::device_memory: - vk.vkFreeMemory(device, reinterpret_cast(item.handle), nullptr); - break; - case Kind::acceleration_structure: - if (vk.vkDestroyAccelerationStructureKHR) - vk.vkDestroyAccelerationStructureKHR( - device, reinterpret_cast(item.handle), nullptr); - break; - case Kind::framebuffer: - vk.vkDestroyFramebuffer(device, reinterpret_cast(item.handle), nullptr); - break; - } - } - } - -private: - static std::size_t next_pow2(std::size_t n) { - std::size_t p = 16; - while (p < n) p <<= 1; - return p; - } - - std::mutex mutex_; - std::vector pending_; - std::size_t head_ = 0; - std::size_t tail_ = 0; - std::size_t count_ = 0; - BindlessReleaseFn bindless_release_fn_ = nullptr; - void* bindless_release_user_ = nullptr; -}; - -// Centralized single-thread fence dispatcher using Vulkan 1.2 vkWaitSemaphores(VK_SEMAPHORE_WAIT_ANY_BIT). -// Eliminates per-fence OS threads and 10ms polling: a synthetic timeline semaphore (wakeup_sem_) at index 0 -// wakes vkWaitSemaphores immediately whenever a new wait, a released fence, or shutdown arrives while waiting_ == true. -class FenceWaitDispatcher { -public: - struct Entry { - VkSemaphore semaphore = VK_NULL_HANDLE; - std::uint64_t value = 0; - void* event_handle = nullptr; - std::function callback; - }; - - // A dispatch runs outside mutex_. Each entry in a ready batch gets its own slot: a callback may re-entrantly - // call cancel() for a later entry in the same batch, which marks that entry cancelled so it is skipped before - // it can use the semaphore. A callback running on another thread must still be waited for. - // A cancelled entry still in pending_ is dispatched by cancel() itself (callback and bookkeeping both run); - // one already in a ready batch is skipped and only its event is signalled. The held Signal op's count is - // therefore not decremented for a skipped batch entry. That is safe because only ~Fence cancels a wait, but - // keep it in mind if cancel() gains other callers. - struct DispatchSlot { - VkSemaphore semaphore = VK_NULL_HANDLE; - std::thread::id owner; - bool active = false; // guarded by mutex_ - bool cancelled = false; // guarded by mutex_ - }; - - using SignalEventFn = void (*)(void* event_handle); - - // Longest single vkWaitSemaphores call in run(): bounds how long the thread can sit in an uninterruptible wait. - static constexpr std::uint64_t kWaitSliceNs = 100'000'000; // 100 ms - - FenceWaitDispatcher(VkDevice device, const VulkanDeviceFunctions& vk, std::atomic& device_lost) - : device_(device), vk_(vk), device_lost_(device_lost) { - VkSemaphoreTypeCreateInfo type{VK_STRUCTURE_TYPE_SEMAPHORE_TYPE_CREATE_INFO}; - type.semaphoreType = VK_SEMAPHORE_TYPE_TIMELINE; - type.initialValue = 0; - VkSemaphoreCreateInfo info{VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO, &type}; - if (vk_.vkCreateSemaphore(device_, &info, nullptr, &wakeup_sem_) != VK_SUCCESS) - wakeup_sem_ = VK_NULL_HANDLE; - semaphores_.reserve(64); - values_.reserve(64); - } - - ~FenceWaitDispatcher() { - stop(); - if (wakeup_sem_) vk_.vkDestroySemaphore(device_, wakeup_sem_, nullptr); - } - - FenceWaitDispatcher(const FenceWaitDispatcher&) = delete; - FenceWaitDispatcher& operator=(const FenceWaitDispatcher&) = delete; - - void set_signal_event_fn(SignalEventFn fn) { - std::lock_guard lock(mutex_); - signal_event_ = fn; - } - - void enqueue(VkSemaphore sem, std::uint64_t value, void* event_handle) { - if (!sem || !event_handle) return; - SignalEventFn immediate_fn = nullptr; - { - std::lock_guard lock(mutex_); - if (stop_ || device_lost_.load(std::memory_order_acquire)) { - immediate_fn = signal_event_; - } else { - pending_.push_back({sem, value, event_handle, {}}); - if (!thread_.joinable() && wakeup_sem_) thread_ = std::thread([this] { run(); }); - signal_wakeup_locked(); - } - } - if (immediate_fn) { - immediate_fn(event_handle); - return; - } - cv_.notify_one(); - } - - void enqueue_callback(VkSemaphore sem, std::uint64_t value, std::function cb) { - if (!sem || !cb) return; - std::function immediate_cb; - { - std::lock_guard lock(mutex_); - if (stop_ || device_lost_.load(std::memory_order_acquire)) { - immediate_cb = std::move(cb); - } else { - pending_.push_back({sem, value, nullptr, std::move(cb)}); - if (!thread_.joinable() && wakeup_sem_) thread_ = std::thread([this] { run(); }); - signal_wakeup_locked(); - } - } - if (immediate_cb) { - immediate_cb(); - return; - } - cv_.notify_one(); - } - - // Wakes run() when another path marks the device lost so pending waits complete and stop()/cancel() never hang. - void notify_device_lost() { - { - std::lock_guard lock(mutex_); - signal_wakeup_locked(); - } - cv_.notify_all(); - } - - // Completes the pending waits for `sem` (a released D3D12 fence counts as reached, as on the PC runtime) and - // blocks until both a vkWaitSemaphores on `sem` and any callback already dispatched for it have finished, before - // the caller destroys the VkSemaphore. - void cancel(VkSemaphore sem) { - if (!sem) return; - std::vector cancelled; - SignalEventFn fn = nullptr; - { - std::unique_lock lock(mutex_); - fn = signal_event_; - std::size_t write = 0; - for (std::size_t i = 0; i < pending_.size(); ++i) { - if (pending_[i].semaphore == sem) { - cancelled.push_back(std::move(pending_[i])); - } else { - if (write != i) pending_[write] = std::move(pending_[i]); - ++write; - } - } - pending_.resize(write); - // Entries already taken out of pending_ but not yet started belong to a live ready batch. Mark them - // cancelled so dispatch skips them; this is how a re-entrant cancel() from another callback in the - // same batch is completed without waiting on the callback that is already on this thread's stack. - for (const auto& slot : dispatching_) { - if (slot->semaphore == sem && !slot->active) slot->cancelled = true; - } - if (thread_.joinable() && (waiting_ || callback_on_other_thread(sem))) { - const std::uint64_t target_epoch = epoch_ + 1; - signal_wakeup_locked(); - epoch_cv_.wait(lock, [this, sem, target_epoch] { - return (!waiting_ || epoch_ >= target_epoch) && !callback_on_other_thread(sem); - }); - } - } - dispatch_entries(cancelled, fn); - } - - void stop() { - { - std::lock_guard lock(mutex_); - if (stop_) return; - stop_ = true; - signal_wakeup_locked(); - } - cv_.notify_all(); - if (thread_.joinable()) thread_.join(); - } - -private: - static void dispatch_entries(std::vector& entries, SignalEventFn signal_event) { - for (Entry& e : entries) { - if (e.callback) e.callback(); - else if (signal_event && e.event_handle) signal_event(e.event_handle); - } - } - - // True only for a callback already running on another thread. A slot that has not started yet is cancelled by - // cancel() and skipped, so it never uses a destroyed semaphore and must not hold up the cancelling caller. - bool callback_on_other_thread(VkSemaphore sem) const { - const std::thread::id me = std::this_thread::get_id(); - return std::any_of(dispatching_.begin(), dispatching_.end(), [&](const auto& d) { - return d->semaphore == sem && d->active && d->owner != me; - }); - } - - // mutex_ is held on entry and again on return. Recording every entry before unlocking closes the window where - // run() has taken them out of pending_ but has not started the callback, yet cancel() can return and let the - // caller destroy the semaphore. Each entry has its own slot so a cancel() for a later entry in the same batch - // skips that entry instead of being mistaken for the callback already on the cancelling thread's stack. - void dispatch_outside_lock(std::unique_lock& lock, std::vector& entries, SignalEventFn fn) { - const std::thread::id me = std::this_thread::get_id(); - std::vector> slots; - slots.reserve(entries.size()); - for (const Entry& e : entries) { - auto slot = std::make_shared(); - slot->semaphore = e.semaphore; - slot->owner = me; - slots.push_back(slot); - dispatching_.push_back(slot); - } - lock.unlock(); - for (std::size_t i = 0; i < entries.size(); ++i) { - Entry& e = entries[i]; - DispatchSlot& slot = *slots[i]; - bool skip = false; - { - std::lock_guard guard(mutex_); - skip = slot.cancelled; - if (!skip) slot.active = true; - } - if (skip) { - // A re-entrant cancel() removed this wait; still complete its event so no waiter is left behind. - if (fn && e.event_handle) fn(e.event_handle); - continue; - } - if (e.callback) e.callback(); - else if (fn && e.event_handle) fn(e.event_handle); - { - std::lock_guard guard(mutex_); - slot.active = false; - const auto it = std::find(dispatching_.begin(), dispatching_.end(), slots[i]); - if (it != dispatching_.end()) dispatching_.erase(it); - } - epoch_cv_.notify_all(); - } - lock.lock(); - for (const auto& slot : slots) { - const auto it = std::find(dispatching_.begin(), dispatching_.end(), slot); - if (it != dispatching_.end()) dispatching_.erase(it); - } - epoch_cv_.notify_all(); - } - - // Only signals wakeup_sem_ when run() is actively waiting (waiting_ == true) on wakeup_val_ + 1, - // eliminating any lost-wakeup race between snapshot construction and vkWaitSemaphores. Keep signaling even if - // device_lost_ is already set so a blocked vkWaitSemaphores wakes cleanly for cancel()/stop(). - void signal_wakeup_locked() { - if (!waiting_ || !wakeup_sem_) return; - const std::uint64_t next = ++wakeup_val_; - VkSemaphoreSignalInfo si{VK_STRUCTURE_TYPE_SEMAPHORE_SIGNAL_INFO}; - si.semaphore = wakeup_sem_; - si.value = next; - vk_.vkSignalSemaphore(device_, &si); - } - - void run() { - std::unique_lock lock(mutex_); - while (true) { - cv_.wait(lock, [this] { return stop_ || !pending_.empty() || device_lost_.load(std::memory_order_acquire); }); - if (device_lost_.load(std::memory_order_acquire)) { - std::vector drained = std::move(pending_); - pending_.clear(); - dispatch_outside_lock(lock, drained, signal_event_); - return; - } - if (stop_) return; - - semaphores_.clear(); - values_.clear(); - semaphores_.push_back(wakeup_sem_); - values_.push_back(wakeup_val_ + 1); - for (const Entry& e : pending_) { - semaphores_.push_back(e.semaphore); - values_.push_back(e.value); - } - - waiting_ = true; - lock.unlock(); - - VkSemaphoreWaitInfo wi{VK_STRUCTURE_TYPE_SEMAPHORE_WAIT_INFO}; - wi.flags = VK_SEMAPHORE_WAIT_ANY_BIT; - wi.semaphoreCount = static_cast(semaphores_.size()); - wi.pSemaphores = semaphores_.data(); - wi.pValues = values_.data(); - // A bounded slice, not UINT64_MAX. Under GPU paravirtualization (measured in Windows Sandbox on an - // RTX 5060 Ti) this wait is a kernel wait the OS cannot interrupt: a process that exits while a wait - // is pending (d3d12_queue_wait_timeout's _Exit, or quitting with a fence outstanding) never finishes - // exiting, and TerminateProcess cannot end it either. A timeout returns here and the loop re-arms the - // same wait; completions still wake it at once through the ANY wait. - const VkResult res = vk_.vkWaitSemaphores(device_, &wi, kWaitSliceNs); - - lock.lock(); - waiting_ = false; - ++epoch_; - epoch_cv_.notify_all(); - - if (res == VK_ERROR_DEVICE_LOST || device_lost_.load(std::memory_order_acquire)) { - device_lost_.store(true, std::memory_order_release); - std::vector drained = std::move(pending_); - pending_.clear(); - dispatch_outside_lock(lock, drained, signal_event_); - return; - } - if (stop_) return; - - std::vector ready; - bool lost = false; - std::size_t write = 0; - for (std::size_t i = 0; i < pending_.size(); ++i) { - std::uint64_t done = 0; - const VkResult cr = vk_.vkGetSemaphoreCounterValue(device_, pending_[i].semaphore, &done); - if (cr == VK_ERROR_DEVICE_LOST) { - lost = true; - for (std::size_t j = i; j < pending_.size(); ++j) ready.push_back(std::move(pending_[j])); - break; - } - if (cr == VK_SUCCESS && done >= pending_[i].value) { - ready.push_back(std::move(pending_[i])); - } else { - if (write != i) pending_[write] = std::move(pending_[i]); - ++write; - } - } - if (lost) { - pending_.resize(write); - for (Entry& e : pending_) ready.push_back(std::move(e)); - pending_.clear(); - device_lost_.store(true, std::memory_order_release); - dispatch_outside_lock(lock, ready, signal_event_); - return; - } - pending_.resize(write); - if (!ready.empty()) { - dispatch_outside_lock(lock, ready, signal_event_); - if (stop_) return; - } - } - } - - VkDevice device_; - const VulkanDeviceFunctions& vk_; - std::atomic& device_lost_; - SignalEventFn signal_event_ = nullptr; - VkSemaphore wakeup_sem_ = VK_NULL_HANDLE; - std::uint64_t wakeup_val_ = 0; - - std::mutex mutex_; - std::condition_variable cv_; - std::condition_variable epoch_cv_; - std::vector pending_; - std::vector> dispatching_; // ready-batch callbacks outside mutex_ - std::vector semaphores_; - std::vector values_; - std::uint64_t epoch_ = 0; - bool waiting_ = false; - bool stop_ = false; - std::thread thread_; -}; - -// A range of a D3D12 heap allocation. Mappings and in-flight unbinds keep the arena range alive. -struct TileHeapAllocation { - VkDeviceMemory memory = VK_NULL_HANDLE; - VkDeviceSize offset = 0; - VkDeviceSize size = 0; - std::uint32_t memory_type = 0; -}; - -struct TileMapping { - std::shared_ptr heap; - VkDeviceSize offset = 0; - bool operator==(const TileMapping&) const = default; -}; - -struct SparseResource { - SparseResource(VkDevice device, const VulkanDeviceFunctions& vk) : device(device), vk(vk) {} - SparseResource(const SparseResource&) = delete; - SparseResource& operator=(const SparseResource&) = delete; - ~SparseResource() { - if (image) vk.vkDestroyImage(device, image, nullptr); - if (buffer) vk.vkDestroyBuffer(device, buffer, nullptr); - } - - VkDevice device; - const VulkanDeviceFunctions& vk; - VkBuffer buffer = VK_NULL_HANDLE; - VkImage image = VK_NULL_HANDLE; - VkExtent2D image_extent{}; - std::uint64_t tile_count = 0; - std::uint32_t memory_types = 0; - std::map mapped; -}; - -struct TileRegion { - std::uint64_t first = 0; - std::uint64_t count = 0; -}; - -enum class TileRangeMode { sequential, unmap, skip, reuse }; - -struct TileRange { - TileRangeMode mode; - std::uint64_t first; - std::uint64_t count; -}; - -// Per device: what the queues share. Resources are registered by their stable ID (the COM resource pointer). -#ifdef _MSC_VER -#pragma warning(push) -#pragma warning(disable : 4324) // intentional alignas(64) cache-line padding to prevent false sharing -#endif -class VulkanContext { -public: - // conditional_rendering: VK_EXT_conditional_rendering is enabled on `device` (SetPredication). - // ray_tracing: VK_KHR_acceleration_structure + VK_KHR_ray_query are enabled on `device`. - // xdxr: acceleration-structure builds write XDXR BVH4 records (xdxr_build.h) instead; needs bufferDeviceAddress. - VulkanContext(PFN_vkGetDeviceProcAddr get, VkDevice device, bool separate_depth_stencil_layouts, - bool conditional_rendering = false, bool ray_tracing = false, bool xdxr = false) - : device_(device), tracker_(separate_depth_stencil_layouts), ray_tracing_(ray_tracing) { - loaded_ = vk.load(get, device); - replay_.pipeline_barrier = vk.vkCmdPipelineBarrier; - replay_.clear_color_image = vk.vkCmdClearColorImage; - replay_.clear_depth_stencil_image = vk.vkCmdClearDepthStencilImage; - replay_.pipeline_barrier2 = vk.vkCmdPipelineBarrier2; - replay_.begin_rendering = vk.vkCmdBeginRendering; - replay_.end_rendering = vk.vkCmdEndRendering; - replay_.clear_attachments = vk.vkCmdClearAttachments; - replay_.copy_buffer = vk.vkCmdCopyBuffer; - replay_.copy_buffer_to_image = vk.vkCmdCopyBufferToImage; - replay_.copy_image_to_buffer = vk.vkCmdCopyImageToBuffer; - replay_.copy_image = vk.vkCmdCopyImage; - replay_.resolve_image = vk.vkCmdResolveImage; - replay_.fill_buffer = vk.vkCmdFillBuffer; - replay_.update_buffer = vk.vkCmdUpdateBuffer; - replay_.draw_indirect = vk.vkCmdDrawIndirect; - replay_.draw_indexed_indirect = vk.vkCmdDrawIndexedIndirect; - replay_.draw_indirect_count = vk.vkCmdDrawIndirectCount; - replay_.draw_indexed_indirect_count = vk.vkCmdDrawIndexedIndirectCount; - replay_.dispatch_indirect = vk.vkCmdDispatchIndirect; - if (conditional_rendering) { // a driver may hand out these pointers even when the extension is off - replay_.begin_conditional_rendering = vk.vkCmdBeginConditionalRenderingEXT; - replay_.end_conditional_rendering = vk.vkCmdEndConditionalRenderingEXT; - } - replay_.reset_query_pool = vk.vkCmdResetQueryPool; - replay_.begin_query = vk.vkCmdBeginQuery; - replay_.end_query = vk.vkCmdEndQuery; - replay_.write_timestamp = vk.vkCmdWriteTimestamp; - replay_.copy_query_pool_results = vk.vkCmdCopyQueryPoolResults; - replay_.bind_pipeline = vk.vkCmdBindPipeline; - replay_.push_constants = vk.vkCmdPushConstants; - replay_.bind_descriptor_sets = vk.vkCmdBindDescriptorSets; - replay_.dispatch = vk.vkCmdDispatch; - replay_.compute_pipeline = [this](std::uintptr_t id) -> const ComputePipeline* { - const auto it = pipelines_.find(id); - return it == pipelines_.end() ? nullptr : &it->second; - }; - replay_.bind_vertex_buffers2 = vk.vkCmdBindVertexBuffers2; - replay_.bind_index_buffer = vk.vkCmdBindIndexBuffer; - replay_.set_viewport = vk.vkCmdSetViewport; - replay_.set_scissor = vk.vkCmdSetScissor; - replay_.set_primitive_topology = vk.vkCmdSetPrimitiveTopology; - replay_.set_primitive_restart_enable = vk.vkCmdSetPrimitiveRestartEnable; - replay_.set_stencil_reference = vk.vkCmdSetStencilReference; - replay_.set_blend_constants = vk.vkCmdSetBlendConstants; - replay_.draw = vk.vkCmdDraw; - replay_.draw_mesh_tasks = vk.vkCmdDrawMeshTasksEXT; // null unless VK_EXT_mesh_shader is enabled - replay_.draw_indexed = vk.vkCmdDrawIndexed; - replay_.graphics_pipeline = [this](std::uintptr_t id) -> const GraphicsPipeline* { - const auto it = graphics_pipelines_.find(id); - return it == graphics_pipelines_.end() ? nullptr : &it->second; - }; - // Called with resource_mutex_ held. A binary search of the buffers' VA ranges (buffer_va_index.h), kept in step - // with resources_ by set_resource_locked and remove_resource. - // A range that runs past its buffer is cut at the buffer's end (`size` is updated): D3D12 reads past a view's - // buffer as out of bounds, which is no reason to drop the submission. - replay_.buffer_at = [this](std::uint64_t va, std::uint64_t& size, VkBuffer& buffer, VkDeviceSize& offset) { - BufferVaIndex::Hit hit{}; - if (!buffer_vas_.find(va, hit, size)) return false; // prefers an aliasing buffer that holds all of it - const ResourceBinding* b = resolve(hit.id); - if (!b) return false; - buffer = b->buffer; - offset = b->buffer_offset + (va - b->va); - size = std::min(size, b->size - (va - b->va)); - return true; - }; - // Host reads of small CPU-written inputs. Unlike buffer_at, the whole range must be in one CPU-writable - // mapping: a partial read would see bytes the application has not written through the D3D12 API. The - // binding's host pointer is null on DEFAULT and READBACK heaps, whose mapped bytes the GPU can write. - replay_.host_at = [this](std::uint64_t va, std::uint64_t bytes, const std::uint8_t*& host) { - BufferVaIndex::Hit hit{}; - if (!buffer_vas_.find(va, hit)) return HostReadStatus::absent; - const ResourceBinding* b = resolve(hit.id); - if (!b) return HostReadStatus::absent; - if (!b->host) return HostReadStatus::not_cpu_written; - const std::uint64_t offset = va - b->va; - if (offset > b->size || bytes > b->size - offset) return HostReadStatus::absent; - host = b->host + offset; - return HostReadStatus::ok; - }; - if (xdxr && loaded_) { - xdxr_ = std::make_unique(get, device); - if (xdxr_->loaded()) { - replay_.xdxr_check = [](const BuildAccelerationStructure& b) { - XdxrLayout layout; - // An update needs ALLOW_UPDATE (D3D12 requires it on the build and the update): a structure - // built without it may have paired leaves, which a refit would rewrite as wrong geometry. - return xdxr_inputs(b, nullptr, 0) && layout.compute(xdxr_elements(b), b.is_tlas, xdxr_box16(b)) && - b.dst_va && b.scratch_va && (!b.is_tlas || !b.instance_count || b.instances_va) && - (!b.update || (b.build_flags & VK_BUILD_ACCELERATION_STRUCTURE_ALLOW_UPDATE_BIT_KHR) != 0); - }; - replay_.xdxr_record = [this](VkCommandBuffer cb, const BuildAccelerationStructure& b) { - // Every address is a console VA in the GPU address arena: the device address is heap_base + VA, - // and the BLAS addresses in instance descs get the same bias. - const std::uint64_t base = replay_.heap_base; - XdxrLayout layout; - layout.compute(xdxr_elements(b), b.is_tlas, xdxr_box16(b)); - // PERFORM_UPDATE refits the source (the destination itself when no source is given, as D3D12 - // allows for an in-place update); a full build otherwise. - const std::uint64_t from = b.update ? base + (b.src_va ? b.src_va : b.dst_va) : 0; - if (b.is_tlas) { - xdxr_->record_tlas(cb, layout, b.instances_va ? base + b.instances_va : 0, base + b.dst_va, - base + b.scratch_va, base, from); - } else { - std::vector geometries; - xdxr_inputs(b, &geometries, base); - xdxr_->record_blas(cb, layout, geometries, base + b.dst_va, base + b.scratch_va, from, - xdxr_pair(b)); - } - }; - replay_.xdxr_copy = [this](VkCommandBuffer cb, std::uint64_t src, std::uint64_t dst, std::uint64_t bytes) { - const std::uint64_t base = replay_.heap_base; - xdxr_->record_copy(cb, base + src, base + dst, bytes); - }; - replay_.xdxr_postbuild = [this](VkCommandBuffer cb, std::uint64_t src, std::uint64_t dest) { - const std::uint64_t base = replay_.heap_base; - xdxr_->record_postbuild(cb, base + src, base + dest); - }; - } else { - xdxr_.reset(); - } - } - if (!xdxr_ && ray_tracing_ && vk.vkCmdBuildAccelerationStructuresKHR) { - replay_.build_acceleration_structures = vk.vkCmdBuildAccelerationStructuresKHR; - replay_.copy_acceleration_structure = vk.vkCmdCopyAccelerationStructureKHR; - replay_.write_acceleration_structures_properties = vk.vkCmdWriteAccelerationStructuresPropertiesKHR; - replay_.resolve_acceleration_structure = [this](std::uint64_t va) { - const auto it = acceleration_structures_.find(va); - return it == acceleration_structures_.end() ? VK_NULL_HANDLE : it->second; - }; - } - replay_.image_view = [this](const ResourceBinding& r, const VkImageSubresourceRange& range) { - return view(r, range); - }; - if (vk.vkCreateRenderPass2 && vk.vkDestroyRenderPass && vk.vkCreateFramebuffer && vk.vkDestroyFramebuffer && - vk.vkCmdBeginRenderPass && vk.vkCmdEndRenderPass) { - replay_.begin_render_pass = vk.vkCmdBeginRenderPass; - replay_.end_render_pass = vk.vkCmdEndRenderPass; - replay_.depth_resolve_framebuffer = [this](const ResourceBinding& source, VkImageView from, - VkImageLayout from_layout, const ResourceBinding& target, - VkImageView to, VkImageLayout to_layout, - VkResolveModeFlagBits mode, VkExtent2D extent, - VkRenderPass& pass) { - return depth_resolve_framebuffer(source, from, from_layout, target, to, to_layout, mode, extent, pass); - }; - } - replay_.query_pool = [this](QueryHeapId id) -> QueryPool* { // called with resource_mutex_ held - const auto it = query_pools_.find(id); - return it == query_pools_.end() ? nullptr : &it->second; - }; - replay_.separate_depth_stencil_layouts = separate_depth_stencil_layouts; - if (loaded_) { - fence_dispatcher_ = std::make_unique(device_, vk, device_lost_); - } - } - - ~VulkanContext() { - fence_dispatcher_.reset(); - deletion_queue_.drain(UINT64_MAX, device_, vk); - for (const auto& [key, framebuffer] : resolve_framebuffers_) - vk.vkDestroyFramebuffer(device_, framebuffer, nullptr); - for (const auto& [key, pass] : resolve_passes_) vk.vkDestroyRenderPass(device_, pass, nullptr); - for (const auto& [key, view] : views_) vk.vkDestroyImageView(device_, view, nullptr); - } - - VulkanContext(const VulkanContext&) = delete; - VulkanContext& operator=(const VulkanContext&) = delete; - - bool loaded() const { return loaded_; } - void configure_predication(PFN_vkGetDeviceProcAddr get, const VkPhysicalDeviceMemoryProperties& memory, - VkDeviceSize max_range, std::uint32_t family) { - std::unique_lock lock(resource_mutex_); - predicate_family_ = family; - predicate_reducer_ = std::make_unique(get, device_, memory, max_range); - } - // Configure before submitting work, only when storageBuffer8BitAccess is enabled on the device. - void configure_predicated_copy(PFN_vkGetDeviceProcAddr get, const VkPhysicalDeviceLimits& limits) { - std::unique_lock lock(resource_mutex_); - predicated_copier_ = std::make_unique(get, device_, limits); - } - // Counts for DISPATCH-only ExecuteIndirect are read by a helper compute shader from GPU memory. - // Requires Vulkan bufferDeviceAddress, already enabled for the D3D12 address arena. - void configure_counted_dispatch(PFN_vkGetDeviceProcAddr get, const VkPhysicalDeviceMemoryProperties& memory, - const VkPhysicalDeviceLimits& limits) { - std::unique_lock lock(resource_mutex_); - counted_dispatch_ = std::make_unique(get, device_, memory, limits); - } - VkDevice device() const { return device_; } - - // Debug markers become labels from here on; call before any queue or list uses the context. Incomplete sets - // are ignored, so markers stay no-ops. - void enable_debug_labels(const DebugLabelFunctions& labels) { - if (!labels.complete()) return; - labels_ = labels; - replay_.insert_label = labels.cmd_insert; - replay_.begin_label = labels.cmd_begin; - replay_.end_label = labels.cmd_end; - } - bool debug_labels() const { return labels_.complete(); } - - // Registers a resource in its D3D12 initial state (a legacy state; images get the matching layout). - // The image must already be in that layout, e.g. transitioned from UNDEFINED at creation. - void add_resource(ResourceId id, const ResourceBinding& binding) { - std::unique_lock lock(resource_mutex_); - set_resource_locked(id, binding); - } - void add_resource(ResourceId id, const ResourceBinding& binding, VkImageLayout current_layout) { - std::unique_lock rlock(resource_mutex_); - set_resource_locked(id, binding); - if (binding.image) { - std::lock_guard tlock(tracker_mutex_); - tracker_.track(id, binding, current_layout); - } - } - - // A shader can access a storage image or an initially unbound sparse image before any command names it. - // The first shader submission moves it to GENERAL, the descriptor's layout, ahead of its lists. - void note_shader_image(ResourceId id) { - std::lock_guard lock(storage_mutex_); - storage_pending_.insert(id); - } - - // A device-local buffer D3D12 says starts zeroed (D3D-71): the host cannot write it, so the next submission on - // any queue fills it with zeros ahead of its lists. That submission publishes the same initialisation semaphore as - // the storage images above, so a list on another queue that uses the buffer first waits for the fill. - void zero_on_next_submit(ResourceId id, VkBuffer buffer) { - std::lock_guard lock(storage_mutex_); - zero_pending_.push_back({id, buffer}); - } - - void add_sparse_resource(ResourceId id, const ResourceBinding& binding, std::shared_ptr sparse) { - std::unique_lock lock(resource_mutex_); - if (!binding.image) { - auto [it, inserted] = sparse_resources_.try_emplace(id, std::move(sparse)); - try { - set_resource_locked(id, binding); - } catch (...) { - if (inserted) sparse_resources_.erase(it); - throw; - } - return; - } - set_resource_locked(id, binding); - sparse_resources_.emplace(id, std::move(sparse)); - if (binding.image) { - std::lock_guard tlock(tracker_mutex_); - tracker_.track(id, binding, VK_IMAGE_LAYOUT_UNDEFINED); - } - } - - void remove_resource(ResourceId id) { - VkImage img = VK_NULL_HANDLE; - std::shared_ptr sparse_resource; - { - std::unique_lock rlock(resource_mutex_); - const auto it = resources_.find(id); - if (it == resources_.end()) return; - img = it->second.image; - unindex_buffer(id, it->second); - resources_.erase(it); - if (auto sparse = sparse_resources_.find(id); sparse != sparse_resources_.end()) { - sparse_resource = std::move(sparse->second); - sparse_resources_.erase(sparse); - } - } - { - std::lock_guard lock(storage_mutex_); // a buffer destroyed before any submission is not filled - std::erase_if(zero_pending_, [id](const PendingZero& zero) { return zero.id == id; }); - } - if (img) { - std::lock_guard vlock(views_mutex_); - for (auto f = resolve_framebuffers_.begin(); f != resolve_framebuffers_.end();) { - if (std::get<0>(f->first) == img || std::get<1>(f->first) == img) { - defer_destroy(DeferredDeletionQueue::Kind::framebuffer, f->second); - f = resolve_framebuffers_.erase(f); - } else { - ++f; - } - } - for (auto v = views_.begin(); v != views_.end();) { - if (std::get<0>(v->first) == img) { - defer_destroy(DeferredDeletionQueue::Kind::image_view, v->second); - v = views_.erase(v); - } else { - ++v; - } - } - } - if (sparse_resource) - defer_destroy(DeferredDeletionQueue::Kind::sparse_resource, - new std::shared_ptr(std::move(sparse_resource))); - std::lock_guard tlock(tracker_mutex_); - tracker_.forget(id); - } - - // A query heap, by its stable ID (the COM query heap pointer). The pool stays the caller's to destroy, after - // remove_query_pool. - void add_query_pool(QueryHeapId id, const QueryPool& pool) { - std::unique_lock lock(resource_mutex_); - query_pools_[id] = pool; - } - void remove_query_pool(QueryHeapId id) { - // Lock hierarchy: resource_mutex_ -> tracker_mutex_. Holding tracker_mutex_ before erasing keeps the - // QueryPool node alive until any in-flight execute() that unlocked resource_mutex_ finishes QueryReplay::commit(). - std::unique_lock lock(resource_mutex_); - std::lock_guard tlock(tracker_mutex_); - query_pools_.erase(id); - } - // The heap's d3d12_query_heap type, or ~0u for a heap that is not registered. - std::uint32_t query_heap_type(QueryHeapId id) { - std::shared_lock lock(resource_mutex_); // query_pools_ is guarded by resource_mutex_, like add/remove - const auto it = query_pools_.find(id); - return it == query_pools_.end() ? ~0u : it->second.heap_type; - } - - // VkPhysicalDeviceLimits::timestampPeriod (nanoseconds per tick), or 0 when the queue writes no timestamps - // (timestampValidBits 0). Set by the device before any queue uses it. - double timestamp_period() const { return timestamp_period_; } - void set_timestamp_period(double period) { timestamp_period_ = period; } - // True where a timestamp resolve must be ordered explicitly after the timestamps it copies (MoltenVK on Apple - // GPUs, docs/d3d12_vulkan.md section 4.6). Set by the device before any queue uses it. - bool order_timestamp_copies() const { return order_timestamp_copies_; } - void set_order_timestamp_copies(bool order) { order_timestamp_copies_ = order; } - - // The device address of the GPU address arena: console VAs are offsets from it (docs section 3.3). - // execute() copies replay_ under a shared resource_mutex_, so writers hold it uniquely. - void set_heap_base(std::uint64_t heap_base) { - std::unique_lock lock(resource_mutex_); - replay_.heap_base = heap_base; - } - - // Zeroed memory for unbound vertex and index buffers to read (ReplayFunctions::zero_buffer). - void set_zero_page(VkBuffer buffer, VkDeviceSize offset, VkDeviceSize size) { - std::unique_lock lock(resource_mutex_); - replay_.zero_buffer = buffer; - replay_.zero_offset = offset; - replay_.zero_size = size; - } - - // Physical-device COLOR_ATTACHMENT format check for reinterpreted UAV clears. - void set_color_attachment_format(std::function check) { - std::unique_lock lock(resource_mutex_); - replay_.color_attachment_format = std::move(check); - } - std::uint64_t heap_base() { - std::shared_lock lock(resource_mutex_); - return replay_.heap_base; - } - - // Pipelines are registered by an opaque id (the PSO object) for as long as the PSO lives. - void add_pipeline(std::uintptr_t id, const ComputePipeline& pipeline) { - std::unique_lock lock(resource_mutex_); - pipelines_[id] = pipeline; - } - void remove_pipeline(std::uintptr_t id) { - std::unique_lock lock(resource_mutex_); - pipelines_.erase(id); - graphics_pipelines_.erase(id); - } - void add_graphics_pipeline(std::uintptr_t id, const GraphicsPipeline& pipeline) { - std::unique_lock lock(resource_mutex_); - graphics_pipelines_[id] = pipeline; - } - // Configure before queue creation, when the selected queue family supports compute. - void set_occlusion_resolve_memory(const VkPhysicalDeviceMemoryProperties& memory) { - occlusion_resolve_memory_ = memory; - } - - // For tests and traces. - VkImageLayout layout(ResourceId id, std::uint32_t subresource) { - std::lock_guard lock(tracker_mutex_); - return tracker_.layout(id, subresource); - } - - bool has_resource(ResourceId id) { - std::shared_lock lock(resource_mutex_); - return resources_.find(id) != resources_.end(); - } - - bool ray_tracing_supported() const { return ray_tracing_ && vk.vkCmdBuildAccelerationStructuresKHR != nullptr; } - bool xdxr_acceleration_structures() const { return xdxr_ != nullptr; } - - // Whether a build's inner nodes are BOX16 (64 bytes, half boxes rounded outward) instead of BOX32: bottom-level - // builds with MINIMIZE_MEMORY (VK LOW_MEMORY). A top-level build keeps BOX32: it is in world space, where half - // precision would make boxes metres too large a few kilometres from the origin. The flags of an update must match - // its build's (D3D12), so prebuild info, the build and its refits agree. WARNING: an update that breaks that rule - // (MINIMIZE_MEMORY on one and not the other) is refitted with the wrong layout and writes past the structure; it - // cannot be detected when the command is recorded. - static bool xdxr_box16(const BuildAccelerationStructure& b) { - return !b.is_tlas && (b.build_flags & VK_BUILD_ACCELERATION_STRUCTURE_LOW_MEMORY_BIT_KHR) != 0; - } - // Whether a bottom-level build pairs sibling triangles into TRI0/TRI1 leaves: not when the structure may be - // updated (ALLOW_UPDATE), since a refit rewrites the leaves one triangle each and would leave every TRI1 child - // reading wrong vertices. xdxr_check refuses an update without ALLOW_UPDATE for that reason. Pairing changes - // neither the layout nor the tree, so prebuild info does not depend on it. - static bool xdxr_pair(const BuildAccelerationStructure& b) { - return !b.is_tlas && !b.update && (b.build_flags & VK_BUILD_ACCELERATION_STRUCTURE_ALLOW_UPDATE_BIT_KHR) == 0; - } - // Triangles (BLAS) or instances (TLAS) a build has: what XdxrLayout is computed from, for the build and for - // GetRaytracingAccelerationStructurePrebuildInfo. - static std::uint32_t xdxr_elements(const BuildAccelerationStructure& b) { - if (b.is_tlas) return b.instance_count; - std::uint64_t n = 0; - for (const auto& t : b.triangles) n += (t.index_type ? t.index_count : t.vertex_count) / 3; - return n > 0xffffffffu ? 0xffffffffu : std::uint32_t(n); - } - // The geometries as the builder reads them, with `base` added to their VAs; false for an input it cannot read - // (a vertex format other than R32G32B32_FLOAT or R32G32_FLOAT, an index type other than none/R16/R32). - static bool xdxr_inputs(const BuildAccelerationStructure& b, std::vector* out, std::uint64_t base) { - if (b.is_tlas) return true; - for (const auto& t : b.triangles) { - if (t.vertex_format != VK_FORMAT_R32G32B32_SFLOAT && t.vertex_format != VK_FORMAT_R32G32_SFLOAT) return false; - if (t.index_type > 2) return false; - const std::uint32_t count = (t.index_type ? t.index_count : t.vertex_count) / 3; - if (count && !t.vertex_va) return false; - if (count && t.index_type && !t.index_va) return false; - if (!out) continue; - XdxrTriangles g; - g.vertices = t.vertex_va ? base + t.vertex_va : 0; - g.vertex_stride = t.vertex_stride; - g.xy_only = t.vertex_format == VK_FORMAT_R32G32_SFLOAT; - g.indices = t.index_type && t.index_va ? base + t.index_va : 0; - g.index_type = t.index_type; - g.triangle_count = count; - g.transform = t.transform_va ? base + t.transform_va : 0; - g.flags = t.flags | (t.opaque ? 1u : 0u); - out->push_back(g); - } - return true; - } - - void register_acceleration_structure(std::uint64_t va, VkAccelerationStructureKHR as) { - if (!va || !as) return; - std::unique_lock lock(resource_mutex_); - acceleration_structures_[va] = as; - } - - void unregister_acceleration_structure(std::uint64_t va) { - if (!va) return; - std::unique_lock lock(resource_mutex_); - acceleration_structures_.erase(va); - } - - VkAccelerationStructureKHR resolve_acceleration_structure(std::uint64_t va) { - std::shared_lock lock(resource_mutex_); - const auto it = acceleration_structures_.find(va); - return it == acceleration_structures_.end() ? VK_NULL_HANDLE : it->second; - } - - // `prepare` is called at the start of the command buffer of every ExecuteCommandLists, before the lists are - // written: the device brings the bindless set 0 of the translated shaders up to date there (vulkan_bindless.h) - // and records what the set needs first. When it fails, nothing of that call is executed. - void set_transfer_only_family(std::uint32_t family) { transfer_only_family_ = family; } - - void set_bindless_prepare(std::function prepare) { - std::unique_lock lock(resource_mutex_); - bindless_prepare_ = std::move(prepare); - } - - // D24_UNORM_S8_UINT stored as D32: copies of its depth plane run a compute pass (vulkan_depth24.h). `allocate` - // gives the scratch buffers device-local memory. Without this such a copy is refused as unsupported. - void enable_depth24(PFN_vkGetDeviceProcAddr get, Depth24Converter::Allocate allocate, - std::uint64_t max_storage_range = 1u << 27) { - std::unique_lock lock(resource_mutex_); - depth24_ = std::make_unique(get, device_, std::move(allocate), max_storage_range); - if (!depth24_->loaded()) { - depth24_.reset(); - return; - } - replay_.depth24_prepare = [this](Depth24Job& job, std::vector& parts) { return depth24_->prepare(job, parts); }; - replay_.depth24_run = [this](VkCommandBuffer command_buffer, const Depth24Job& job) { - depth24_->run(command_buffer, job); - }; - } - - // Copies the replay stages through a buffer (depth <-> colour, vulkan_replay.h) take device-local scratch from - // `allocate`. Without this such a copy is refused as unsupported. - void enable_copy_scratch(PFN_vkGetDeviceProcAddr get, ScratchBuffers::Allocate allocate) { - std::unique_lock lock(resource_mutex_); - scratch_ = std::make_unique(get, device_, std::move(allocate)); - if (!scratch_->loaded()) scratch_.reset(); - } - - // Called after that command buffer's submit: true when it was accepted, false when vkQueueSubmit failed. The - // set keeps its upload pending in the second case, because the copy never reached the GPU. - void set_bindless_commit(std::function commit) { - std::unique_lock lock(resource_mutex_); - bindless_commit_ = std::move(commit); - } - - // The set 0 the commands of this ExecuteCommandLists bind, read after `prepare` succeeded and under the same - // locks (a flush may have made a new set). Without it the pipelines' own set is bound. - void set_bindless_current(std::function current) { - std::unique_lock lock(resource_mutex_); - bindless_current_ = std::move(current); - } - - void set_bindless_release(DeferredDeletionQueue::BindlessReleaseFn fn, void* user) { - deletion_queue_.set_bindless_release(fn, user); - } - - // The ticket of the latest submission: everything submitted so far is at or below it, and a resource that any - // of that work may use can be freed once completed_retire_ticket() has reached it. Tickets run over all queues, - // each recorded with its queue's timeline value, so this waits for every queue's timeline to pass what was - // submitted to it, and never makes a queue wait. - std::uint64_t submitted_retire_ticket() const { return submitted_ticket_.load(std::memory_order_acquire); } - - template - void defer_destroy(DeferredDeletionQueue::Kind kind, VkHandle handle) { - const auto raw = static_cast(reinterpret_cast(handle)); - if (!raw) return; - std::lock_guard lock(submit_mutex_); - const std::uint64_t safe_ticket = submitted_ticket_.load(std::memory_order_acquire) + 1; - deletion_queue_.push(safe_ticket, kind, raw); - } - - void defer_destroy(DeferredDeletionQueue::Kind kind, std::uint64_t raw_handle) { - if (!raw_handle && kind != DeferredDeletionQueue::Kind::bindless_slot) return; - std::lock_guard lock(submit_mutex_); - const std::uint64_t safe_ticket = submitted_ticket_.load(std::memory_order_acquire) + 1; - deletion_queue_.push(safe_ticket, kind, raw_handle); - } - - // Waits (not for the device: for the queues' timelines) until every submission up to `ticket` is done, then - // returns the completed ticket. For a caller whose list of retired objects has grown past what it will hold. - std::uint64_t wait_retire_ticket(std::uint64_t ticket) { - std::vector> pending; - { - std::lock_guard lock(submit_mutex_); - if (is_device_lost()) return 0; - pending = retire_tickets_.pending_through(ticket); - } - if (!pending.empty()) { - std::vector semaphores; - std::vector values; - for (const auto& [semaphore, value] : pending) { - semaphores.push_back(semaphore); - values.push_back(value); - } - VkSemaphoreWaitInfo wait{VK_STRUCTURE_TYPE_SEMAPHORE_WAIT_INFO}; - wait.semaphoreCount = std::uint32_t(semaphores.size()); - wait.pSemaphores = semaphores.data(); - wait.pValues = values.data(); - vk.vkWaitSemaphores(device_, &wait, UINT64_MAX); // outside submit_mutex_: a signal may need it - } - return completed_retire_ticket(); - } - - // The bindless flush of this ExecuteCommandLists started a new set generation, whose table upload is in its - // command buffer: called from the `prepare` callback (tracker_mutex_ held), so execute() makes every other - // queue's next submission wait for this one, which binds the new set. - void note_bindless_upload() { bindless_upload_pending_ = true; } - - std::uint64_t completed_retire_ticket() { - std::lock_guard lock(submit_mutex_); - if (is_device_lost()) return 0; - return retire_tickets_.completed([this](VkSemaphore semaphore, std::uint64_t value) { - std::uint64_t done = 0; - return vk.vkGetSemaphoreCounterValue(device_, semaphore, &done) == VK_SUCCESS && done >= value; - }); - } - - void drain_deleted_resources(std::uint64_t current_ticket) { - deletion_queue_.drain(current_ticket, device_, vk); - } - - // Both methods are called with submit_mutex_ held. A queue's own progress timeline is - // monotonic even when another queue completes first; global tickets are retired in order. - void record_submit_locked(VkSemaphore progress, std::uint64_t value) { - const auto ticket = submitted_ticket_.fetch_add(1, std::memory_order_acq_rel) + 1; - retire_tickets_.record(ticket, progress, value); - } - void retire_queue_idle_locked(VkSemaphore progress) { - retire_tickets_.queue_idle(progress); - } - - VulkanDeviceFunctions vk; - - // Vulkan requires external synchronisation of a VkQueue; every D3D12 queue of the device may share one. - std::mutex& submit_mutex() { return submit_mutex_; } - - void mark_device_lost() noexcept { - device_lost_.store(true, std::memory_order_release); - if (fence_dispatcher_) { - try { - fence_dispatcher_->notify_device_lost(); - } catch (...) { - } - } - } - bool is_device_lost() const noexcept { return device_lost_.load(std::memory_order_acquire); } - - void set_signal_event_fn(FenceWaitDispatcher::SignalEventFn fn) { - if (fence_dispatcher_) fence_dispatcher_->set_signal_event_fn(fn); - } - void enqueue_fence_wait(VkSemaphore sem, std::uint64_t value, void* event_handle) { - if (fence_dispatcher_) fence_dispatcher_->enqueue(sem, value, event_handle); - } - void enqueue_fence_callback(VkSemaphore sem, std::uint64_t value, std::function cb) { - if (fence_dispatcher_) fence_dispatcher_->enqueue_callback(sem, value, std::move(cb)); - } - void cancel_fence_waits(VkSemaphore sem) { - if (fence_dispatcher_) fence_dispatcher_->cancel(sem); - } - - // Cross-queue Wait-before-Signal: per fence, the highest value a Signal was submitted for, and the queues that - // hold batches until one is (queue_holds.h). - QueueHolds& holds() { return holds_; } - -private: - friend class VulkanQueue; - friend class VulkanPresenter; - - // buffer_at finds a buffer by VA: one with no image, a VkBuffer, a VA and bytes (what the linear search it replaced - // accepted). Both are called with resource_mutex_ held uniquely. - static bool addressable(const ResourceBinding& b) { return !b.image && b.buffer && b.va && b.size; } - void unindex_buffer(ResourceId id, const ResourceBinding& b) { - if (addressable(b)) buffer_vas_.erase(b.va, id); - } - // resources_[id] = binding, with the VA index kept in step (a re-registered ID drops its old range first). - void set_resource_locked(ResourceId id, const ResourceBinding& binding) { - auto [it, inserted] = resources_.try_emplace(id, binding); - if (addressable(binding)) { - try { - buffer_vas_.insert(binding.va, binding.size, id); - } catch (...) { - if (inserted) resources_.erase(it); - throw; - } - } - if (!inserted) { - // A same-VA insert updates its size in place; removing the old key would remove the new range. - if (addressable(it->second) && (!addressable(binding) || it->second.va != binding.va)) - unindex_buffer(id, it->second); - it->second = binding; - } - } - - const ResourceBinding* resolve(ResourceId id) const { - const auto it = resources_.find(id); - return it == resources_.end() ? nullptr : &it->second; - } - - // Called from prepare; protected by views_mutex_ so concurrent shared_lock readers are safe. - VkImageView view(const ResourceBinding& r, const VkImageSubresourceRange& range) { - std::lock_guard lock(views_mutex_); - const auto key = std::make_tuple(r.image, range.aspectMask, range.baseMipLevel, range.baseArrayLayer, - range.layerCount, r.format); - if (const auto it = views_.find(key); it != views_.end()) return it->second; - VkImageViewCreateInfo info{VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO}; - info.image = r.image; - info.viewType = r.line ? VK_IMAGE_VIEW_TYPE_1D_ARRAY : VK_IMAGE_VIEW_TYPE_2D_ARRAY; // 1D images take no 2D view - info.format = r.format; - info.subresourceRange = range; - // Attachment views need only color-attachment usage. Inheriting STORAGE usage from a mutable/extended - // resource (typeless views such as RGBA8 sRGB, or R32_UINT-backed R9G9B9E5 UAV images) would require unrelated usages. - VkImageViewUsageCreateInfo usage{VK_STRUCTURE_TYPE_IMAGE_VIEW_USAGE_CREATE_INFO}; - usage.usage = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT; - if (r.typeless || (range.aspectMask == VK_IMAGE_ASPECT_COLOR_BIT && r.color_attachment)) - info.pNext = &usage; - VkImageView view = VK_NULL_HANDLE; - if (vk.vkCreateImageView(device_, &info, nullptr, &view) != VK_SUCCESS) return VK_NULL_HANDLE; - views_[key] = view; - return view; - } - - // The render pass and framebuffer that resolve one layer of a depth-only multisampled image into one layer of - // another: views `from` and `to` (from view()), in the layouts given. Used where the dynamic-rendering resolve - // reads the wrong source layer (D3D-417; vulkan_replay.h says when). Both objects are cached: a pass by what it - // describes, a framebuffer by its images and views, until remove_resource retires either image. - VkFramebuffer depth_resolve_framebuffer(const ResourceBinding& source, VkImageView from, VkImageLayout from_layout, - const ResourceBinding& target, VkImageView to, VkImageLayout to_layout, - VkResolveModeFlagBits mode, VkExtent2D extent, VkRenderPass& pass) { - std::lock_guard lock(views_mutex_); - const auto pass_key = std::make_tuple(source.format, source.samples, from_layout, to_layout, mode); - if (const auto it = resolve_passes_.find(pass_key); it != resolve_passes_.end()) { - pass = it->second; - } else { - VkAttachmentDescription2 attachments[2]{}; - for (auto& attachment : attachments) { - attachment.sType = VK_STRUCTURE_TYPE_ATTACHMENT_DESCRIPTION_2; - attachment.format = source.format; - attachment.samples = VK_SAMPLE_COUNT_1_BIT; - attachment.loadOp = VK_ATTACHMENT_LOAD_OP_LOAD; // the source is read; the destination keeps - attachment.storeOp = VK_ATTACHMENT_STORE_OP_STORE; // what is outside the render area - attachment.stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE; // depth-only formats - attachment.stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE; - } - attachments[0].samples = static_cast(source.samples); - attachments[0].initialLayout = attachments[0].finalLayout = from_layout; - attachments[1].initialLayout = attachments[1].finalLayout = to_layout; - const VkAttachmentReference2 from_reference{VK_STRUCTURE_TYPE_ATTACHMENT_REFERENCE_2, nullptr, 0, - from_layout, VK_IMAGE_ASPECT_DEPTH_BIT}; - const VkAttachmentReference2 to_reference{VK_STRUCTURE_TYPE_ATTACHMENT_REFERENCE_2, nullptr, 1, to_layout, - VK_IMAGE_ASPECT_DEPTH_BIT}; - VkSubpassDescriptionDepthStencilResolve resolve{ - VK_STRUCTURE_TYPE_SUBPASS_DESCRIPTION_DEPTH_STENCIL_RESOLVE}; - resolve.depthResolveMode = mode; - resolve.stencilResolveMode = VK_RESOLVE_MODE_NONE; - resolve.pDepthStencilResolveAttachment = &to_reference; - VkSubpassDescription2 subpass{VK_STRUCTURE_TYPE_SUBPASS_DESCRIPTION_2}; - subpass.pNext = &resolve; - subpass.pipelineBindPoint = VK_PIPELINE_BIND_POINT_GRAPHICS; - subpass.pDepthStencilAttachment = &from_reference; - VkRenderPassCreateInfo2 info{VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO_2}; - info.attachmentCount = 2; - info.pAttachments = attachments; - info.subpassCount = 1; - info.pSubpasses = &subpass; - if (vk.vkCreateRenderPass2(device_, &info, nullptr, &pass) != VK_SUCCESS) return VK_NULL_HANDLE; - resolve_passes_[pass_key] = pass; - } - const auto key = std::make_tuple(source.image, target.image, from, to, pass); - if (const auto it = resolve_framebuffers_.find(key); it != resolve_framebuffers_.end()) return it->second; - const VkImageView views[] = {from, to}; - VkFramebufferCreateInfo info{VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO}; - info.renderPass = pass; - info.attachmentCount = 2; - info.pAttachments = views; - info.width = extent.width; - info.height = extent.height; - info.layers = 1; - VkFramebuffer framebuffer = VK_NULL_HANDLE; - if (vk.vkCreateFramebuffer(device_, &info, nullptr, &framebuffer) != VK_SUCCESS) return VK_NULL_HANDLE; - resolve_framebuffers_[key] = framebuffer; - return framebuffer; - } - - VkDevice device_; - bool loaded_ = false; - bool ray_tracing_ = false; - std::unique_ptr xdxr_; // set: acceleration structures are XDXR BVH4 records - std::atomic device_lost_{false}; - alignas(64) std::shared_mutex resource_mutex_; // shared for prepare lookups, unique for add/remove - alignas(64) std::mutex tracker_mutex_; - alignas(64) std::mutex views_mutex_; - alignas(64) std::mutex submit_mutex_; - RetireTickets retire_tickets_; - std::atomic submitted_ticket_{0}; - DeferredDeletionQueue deletion_queue_; - std::unique_ptr fence_dispatcher_; - QueueHolds holds_; - std::unordered_map resources_; - BufferVaIndex buffer_vas_; // the addressable buffers of resources_, by VA range (buffer_at) - std::unordered_map> sparse_resources_; - std::unordered_map pipelines_; - std::unordered_map graphics_pipelines_; - std::unordered_map acceleration_structures_; - LayoutTracker tracker_; - std::mutex storage_mutex_; // a leaf lock: guards storage_pending_ and zero_pending_ only - std::unordered_set storage_pending_; - struct PendingZero { - ResourceId id; - VkBuffer buffer; - }; - std::vector zero_pending_; // zero_on_next_submit - // The last submission that initialized storage images (its queue's progress semaphore and ticket) and a counter - // that says which one: every other queue's next submission waits for it, so no queue uses such an image before - // the zero-fill that put it in GENERAL has run. - VkSemaphore storage_init_semaphore_ = VK_NULL_HANDLE; - std::uint64_t storage_init_value_ = 0; - std::uint64_t storage_init_version_ = 0; - std::map, VkImageView> views_; - // depth_resolve_framebuffer's caches, under views_mutex_ like views_. - std::map, VkRenderPass> - resolve_passes_; - std::map, VkFramebuffer> resolve_framebuffers_; - std::function bindless_prepare_; - std::function bindless_current_; - bool bindless_upload_pending_ = false; // tracker_mutex_ - // The last submission that carried a new generation's table upload (its queue's progress semaphore and value), and - // a counter that says which one: every other queue's next submission waits for it (storage_mutex_). - VkSemaphore bindless_upload_semaphore_ = VK_NULL_HANDLE; - std::uint64_t bindless_upload_value_ = 0; - std::uint64_t bindless_upload_version_ = 0; - std::unique_ptr depth24_; - std::unique_ptr scratch_; // copies staged through a buffer (depth <-> colour) - std::function bindless_commit_; - std::unordered_map query_pools_; // element pointers stay valid across inserts - double timestamp_period_ = 0; - bool order_timestamp_copies_ = false; - VkPhysicalDeviceMemoryProperties occlusion_resolve_memory_{}; - ReplayFunctions replay_; - std::unique_ptr predicate_reducer_; - std::unique_ptr predicated_copier_; - std::unique_ptr counted_dispatch_; - std::uint32_t predicate_family_ = UINT32_MAX; - std::uint32_t transfer_only_family_ = UINT32_MAX; - DebugLabelFunctions labels_; -}; -#ifdef _MSC_VER -#pragma warning(pop) -#endif - -// A Vulkan timeline semaphore with D3D12 fence semantics for the host side. -class VulkanFence { -public: - VulkanFence(VulkanContext& context, std::uint64_t initial) : context_(context) { - VkSemaphoreTypeCreateInfo type{VK_STRUCTURE_TYPE_SEMAPHORE_TYPE_CREATE_INFO}; - type.semaphoreType = VK_SEMAPHORE_TYPE_TIMELINE; - type.initialValue = initial; - VkSemaphoreCreateInfo info{VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO, &type}; - if (context.vk.vkCreateSemaphore(context.device(), &info, nullptr, &semaphore_) != VK_SUCCESS) - semaphore_ = VK_NULL_HANDLE; - if (semaphore_) context.holds().add_fence(semaphore_, initial); - } - ~VulkanFence() { - if (!semaphore_) return; - context_.holds().remove_fence(semaphore_); // batches held on it can never run: dropped and reported - context_.vk.vkDestroySemaphore(context_.device(), semaphore_, nullptr); - } - VulkanFence(const VulkanFence&) = delete; - VulkanFence& operator=(const VulkanFence&) = delete; - - VkSemaphore semaphore() const { return semaphore_; } - - std::uint64_t completed() const { - if (context_.is_device_lost()) return UINT64_MAX; - std::uint64_t value = 0; - const VkResult result = context_.vk.vkGetSemaphoreCounterValue(context_.device(), semaphore_, &value); - if (result == VK_ERROR_DEVICE_LOST) { - context_.mark_device_lost(); - return UINT64_MAX; - } - if (result != VK_SUCCESS) return 0; - return value; - } - - // ID3D12Fence::Signal from the CPU. Vulkan timelines only increase: a value at or below the current one is - // ignored (D3D12 would set it), and the caller is told. - bool signal(std::uint64_t value) { - // The dispatcher may be testing a failed counter query. Do not call completed() here: - // it marks the context lost on a query error and prevents the dispatcher from waking. - if (context_.is_device_lost()) return false; - std::uint64_t current = 0; - if (context_.vk.vkGetSemaphoreCounterValue(context_.device(), semaphore_, ¤t) == VK_SUCCESS && - value <= current) - return false; - VkSemaphoreSignalInfo info{VK_STRUCTURE_TYPE_SEMAPHORE_SIGNAL_INFO}; - info.semaphore = semaphore_; - info.value = value; - const VkResult result = context_.vk.vkSignalSemaphore(context_.device(), &info); - if (result == VK_ERROR_DEVICE_LOST) context_.mark_device_lost(); - if (result != VK_SUCCESS) return false; - context_.holds().signaled(semaphore_, value); // queues that held a batch for this value run it now - context_.holds().pump_ready(); - return true; - } - - // true when the value was reached within the timeout. - bool wait(std::uint64_t value, std::uint64_t timeout_ns) const { - VkSemaphoreWaitInfo info{VK_STRUCTURE_TYPE_SEMAPHORE_WAIT_INFO}; - info.semaphoreCount = 1; - info.pSemaphores = &semaphore_; - info.pValues = &value; - const VkResult result = context_.vk.vkWaitSemaphores(context_.device(), &info, timeout_ns); - if (result == VK_ERROR_DEVICE_LOST) context_.mark_device_lost(); - return result == VK_SUCCESS; - } - -private: - VulkanContext& context_; - VkSemaphore semaphore_ = VK_NULL_HANDLE; -}; - -// One D3D12 command queue on one VkQueue. D3D12 lets one thread use a queue at a time per call and the COM wrapper -// serialises its calls; state_mutex_ additionally serialises them against the thread that releases a held batch -// (Wait-before-Signal, queue_holds.h), the only other thread that touches a queue. -// -// A Wait on a fence value no Signal has been submitted for yet holds the next batch (ExecuteCommandLists or Signal) -// on the CPU, with everything the queue is asked to do after it, instead of replaying it against layouts from before -// the work it waits for: Vulkan itself would accept the wait (timeline semaphores allow wait-before-signal), but the -// layout tracker follows replay order. Holding on the CPU also keeps a Wait and the Signal that satisfies it from -// landing on one VkQueue in the wrong order, which would never make progress on the GPU. -class VulkanQueue : private QueueHolds::Holder { -public: - enum class QueueKind : std::uint8_t { direct, compute, copy }; - - // The most command buffers a queue holds at once. At that many, a caller that outruns the GPU waits for the oldest - // submitted one to finish (before taking any context lock, see wait_for_room) instead of allocating without bound. The - // cap holds while the GPU is slow too: a wait that times out is retried, in kQueuedWaitNs slices so a device lost - // meanwhile ends it, and a device lost makes execute() submit nothing. - static constexpr std::size_t kMaxQueuedCommandBuffers = 64; - static constexpr std::uint64_t kQueuedWaitNs = 5'000'000'000; - - static constexpr VkPipelineStageFlags2 queue_supported_stages(QueueKind kind) noexcept { - switch (kind) { - case QueueKind::copy: - return VK_PIPELINE_STAGE_2_COPY_BIT | VK_PIPELINE_STAGE_2_TRANSFER_BIT; - case QueueKind::compute: - return VK_PIPELINE_STAGE_2_COPY_BIT | VK_PIPELINE_STAGE_2_TRANSFER_BIT | - VK_PIPELINE_STAGE_2_COMPUTE_SHADER_BIT; - case QueueKind::direct: - default: - return VK_PIPELINE_STAGE_2_COPY_BIT | VK_PIPELINE_STAGE_2_TRANSFER_BIT | - VK_PIPELINE_STAGE_2_COMPUTE_SHADER_BIT | VK_PIPELINE_STAGE_2_ALL_GRAPHICS_BIT; - } - } - - VulkanQueue(VulkanContext& context, VkQueue queue, std::uint32_t family, QueueKind kind = QueueKind::direct) - : context_(context), queue_(queue), kind_(kind), family_(family) { - auto& vk = context.vk; - VkCommandPoolCreateInfo pool{VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO}; - pool.flags = VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT; - pool.queueFamilyIndex = family; - ok_ = vk.vkCreateCommandPool(context.device(), &pool, nullptr, &pool_) == VK_SUCCESS; - VkSemaphoreTypeCreateInfo type{VK_STRUCTURE_TYPE_SEMAPHORE_TYPE_CREATE_INFO}; - type.semaphoreType = VK_SEMAPHORE_TYPE_TIMELINE; - VkSemaphoreCreateInfo info{VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO, &type}; - ok_ = ok_ && vk.vkCreateSemaphore(context.device(), &info, nullptr, &progress_) == VK_SUCCESS; - try { - context_.holds().attach(this); - } catch (...) { - // A failed registration leaves no queue to run the destructor for these Vulkan handles. - if (progress_) vk.vkDestroySemaphore(context.device(), progress_, nullptr); - if (pool_) vk.vkDestroyCommandPool(context.device(), pool_, nullptr); - throw; - } - } - - ~VulkanQueue() { - auto& vk = context_.vk; - context_.holds().detach(this); // no thread releases into this queue from here on - report_held_at_teardown(); - context_.holds().pump_ready(); // presents queued behind what was just dropped can run - if (queue_) { - std::lock_guard lock(context_.submit_mutex()); - for (; open_labels_; --open_labels_) context_.labels_.queue_end(queue_); - const VkResult idle_result = vk.vkQueueWaitIdle(queue_); - if (idle_result == VK_SUCCESS) { - if (progress_) context_.retire_queue_idle_locked(progress_); - } else { - context_.mark_device_lost(); - } - } - if (progress_) { - std::lock_guard lock(context_.tracker_mutex_); - if (context_.depth24_) context_.depth24_->forget(progress_); // its scratch is idle now - if (context_.scratch_) context_.scratch_->forget(progress_); - } - if (progress_) { - // This queue is idle, so whatever initialisation it published (storage images, zero-filled buffers) has - // finished: the next submission on another queue must not wait on a semaphore that is about to go. - std::lock_guard lock(context_.storage_mutex_); - if (context_.storage_init_semaphore_ == progress_) context_.storage_init_semaphore_ = VK_NULL_HANDLE; - } - if (pool_) vk.vkDestroyCommandPool(context_.device(), pool_, nullptr); - if (progress_) vk.vkDestroySemaphore(context_.device(), progress_, nullptr); - destroy_khr_stages(khr_stage_pool_); - destroy_khr_as_queries(khr_as_query_pool_); - for (auto& slot : buffers_) { - destroy_khr_stages(slot.khr_instances); - destroy_khr_as_queries(slot.khr_as_queries); - free_events_.insert(free_events_.end(), slot.events.begin(), slot.events.end()); - } - for (VkEvent event : free_events_) vk.vkDestroyEvent(context_.device(), event, nullptr); - } - - VulkanQueue(const VulkanQueue&) = delete; - VulkanQueue& operator=(const VulkanQueue&) = delete; - - bool ok() const { return ok_; } - - // Entries kept between executions. Execute only uses the first lists.size(); a larger count is retained storage, - // not work the next submission will replay (vk_queue_test checks both halves of that contract). - std::size_t prepared_entries() const { return prepared_.size(); } - - template - bool update_tiles(ResourceId id, std::span regions, - std::span ranges, GetHeap&& get_heap) { - std::lock_guard state(state_mutex_); // outermost: held batches are released from other threads - std::unique_lock lock(context_.resource_mutex_); - const auto it = context_.sparse_resources_.find(id); - if (it == context_.sparse_resources_.end()) return false; - const auto& sparse = it->second; - for (const auto& region : regions) - if (!valid_tiles(*sparse, region)) return false; - const auto heap = get_heap(sparse->image != VK_NULL_HANDLE, sparse->memory_types); - - std::map changes; - std::size_t region_index = 0; - std::uint64_t consumed = 0; - for (const auto& range : ranges) { - const bool backed = range.mode == TileRangeMode::sequential || range.mode == TileRangeMode::reuse; - const std::uint64_t heap_count = heap ? heap->size / tile_size_in_bytes : 0; - const std::uint64_t required = range.mode == TileRangeMode::reuse ? 1 : range.count; - if (backed && (!heap || range.first > heap_count || required > heap_count - range.first)) return false; - for (std::uint64_t i = 0; i < range.count;) { - if (region_index == regions.size()) return false; - const auto& region = regions[region_index]; - const auto count = std::min(range.count - i, region.count - consumed); - const auto first = region.first + consumed; - if (range.mode == TileRangeMode::unmap) { - const auto end = first + count; - for (auto old = sparse->mapped.lower_bound(first); old != sparse->mapped.end() && old->first < end; ++old) - changes[old->first] = {}; - for (auto change = changes.lower_bound(first); change != changes.end() && change->first < end; ++change) - change->second = {}; - } else if (backed) { - for (std::uint64_t j = 0; j < count; ++j) { - const auto page = range.first + (range.mode == TileRangeMode::sequential ? i + j : 0); - changes[first + j] = {heap, heap->offset + page * tile_size_in_bytes}; - } - } - i += count; - consumed += count; - if (consumed == region.count) { - ++region_index; - consumed = 0; - } - } - } - return region_index == regions.size() && bind_tiles(id, sparse, changes); - } - - bool copy_tile_mappings(ResourceId dst, std::span dst_regions, ResourceId src, - std::span src_regions) { - std::lock_guard state(state_mutex_); - std::unique_lock lock(context_.resource_mutex_); - const auto source = context_.sparse_resources_.find(src), target = context_.sparse_resources_.find(dst); - if (source == context_.sparse_resources_.end() || target == context_.sparse_resources_.end() || - bool(source->second->image) != bool(target->second->image) || src_regions.size() != dst_regions.size()) - return false; - // Read the complete source mapping before changing any destination slot, including copies within one resource. - std::map changes; - for (std::size_t row = 0; row < src_regions.size(); ++row) { - const auto from = src_regions[row], to = dst_regions[row]; - if (!valid_tiles(*source->second, from) || !valid_tiles(*target->second, to) || from.count != to.count) - return false; - for (std::uint64_t i = 0; i < from.count; ++i) { - const auto page = source->second->mapped.find(from.first + i); - changes.emplace(to.first + i, page == source->second->mapped.end() ? TileMapping{} : page->second); - } - } - return bind_tiles(dst, target->second, changes); - } - - // ExecuteCommandLists: every list is checked before any is written, so a failure submits nothing and leaves - // the layout tracker as it was. Pending Wait()s are attached to this submission. When one of them (or an - // earlier held operation) waits for a fence value no Signal has been submitted for, the lists are copied and - // held instead, and the call succeeds: the batch is replayed by the thread that submits the Signal (or the CPU - // Signal), which is also where its errors are reported (stderr, and take_held_failure()). - // - // `pin`, called only when the batch is held, returns what has to stay alive until the batch has run: the COM layer - // passes the pipeline states and root signatures the lists named (the application may release them and Reset - // the lists as soon as the call returns). - using PinFn = std::function()>; - - ReplayResult execute(std::span lists, const PinFn& pin = {}) { - ReplayResult result = ReplayResult::success; - bool held = false; - std::vector> retired; // destroyed after state_mutex_ is released - { - std::lock_guard state(state_mutex_); - if (!must_hold()) { - result = execute_now(lists); - } else if (context_.is_device_lost()) { - result = ReplayResult::unsupported; - } else { - Deferred op; - op.kind = Deferred::Kind::batch; - op.lists.reserve(lists.size()); - for (const CommandList* list : lists) op.lists.push_back(*list); - if (pin) op.pins.push_back(pin()); - hold(std::move(op)); - held = true; - } - drain_pins(retired); - } - retired.clear(); - if (held) context_.holds().pump_ready(); // a Signal may have been submitted since the check - return result; - } - - // ID3D12CommandQueue::Signal: the fence reaches `value` after all work submitted so far. Held behind earlier - // held operations, so the fence does not run ahead of the work it follows. `pin` (called only when the Signal is - // held) keeps the fence object alive until it has been submitted, as D3D12 does. - bool signal(VkSemaphore fence, std::uint64_t value, const PinFn& pin = {}) { - bool ok = true; - std::vector> retired; - { - std::lock_guard state(state_mutex_); - if (must_hold()) { - Deferred op; - op.kind = Deferred::Kind::signal; - op.fence = fence; - op.value = value; - if (pin) op.pins.push_back(pin()); - hold(std::move(op)); - } else { - ok = submit(VK_NULL_HANDLE, fence, value); - } - drain_pins(retired); - } - retired.clear(); - context_.holds().pump_ready(); // this Signal, or the hold above, may have made a held batch ready - return ok; - } - - // ID3D12CommandQueue::Wait: later submissions wait for the fence. A wait in a Vulkan batch only holds back that - // batch, so it is kept and attached to the next submission (held on the CPU if no Signal reaches it yet). - // `pin` returns what keeps the fence object alive until then (a D3D12 queue holds its fences). - void wait(VkSemaphore fence, std::uint64_t value, const PinFn& pin = {}) { - std::vector> retired; // fences whose submission has completed: released unlocked - { - std::lock_guard state(state_mutex_); - waits_.push_back(fence); - wait_values_.push_back(value); - if (pin) wait_pins_.push_back(pin()); - drain_pins(retired); - } - } - - // The first failure of a held ExecuteCommandLists since the last call (what the call would have returned had it - // not been held), or success. A Signal behind a failed batch still signals, as when the failure is not held: the - // work did not run, the application is told here and on stderr, and nothing waits forever. - ReplayResult take_held_failure() { - return static_cast(held_failure_.exchange(static_cast(ReplayResult::success))); - } - - // ID3D12CommandQueue::SetMarker/BeginEvent/EndEvent: queue labels, between the submissions around them. An end - // with no begin open on this queue is dropped, as Vulkan requires a matching begin. No-ops without the extension. - void marker(DebugMarker::Kind kind, const char* label) { - std::vector> retired; - std::lock_guard state(state_mutex_); - drain_pins(retired); // destroyed after the lock (reverse declaration order) - if (!held_.empty()) { // behind the held work, so behind it in the queue's labels too - Deferred op; - op.kind = Deferred::Kind::marker; - op.marker_kind = kind; - op.label = label ? label : ""; - hold(std::move(op)); - return; - } - marker_now(kind, label); - } - - bool idle() { - std::lock_guard lock(context_.submit_mutex()); - return context_.vk.vkQueueWaitIdle(queue_) == VK_SUCCESS; - } - -private: - // Completed stages, reused by later ARRAY_OF_POINTERS builds. Only execute_now() touches the pool, and it holds - // state_mutex_ (including the deferred/held release paths), so no extra lock is needed. - std::vector khr_stage_pool_; - std::vector khr_as_query_pool_; - - void destroy_khr_stages(std::vector& stages) { - for (const auto& stage : stages) { - if (stage.memory) context_.vk.vkFreeMemory(context_.device(), stage.memory, nullptr); - if (stage.buffer) context_.vk.vkDestroyBuffer(context_.device(), stage.buffer, nullptr); - } - stages.clear(); - } - - // A stage returns to the pool only after its submission has completed, so rewriting it cannot race the GPU. - void recycle_khr_stages(std::vector& stages) { - for (auto& stage : stages) khr_stage_pool_.push_back(std::move(stage)); - stages.clear(); - } - - void destroy_khr_as_queries(std::vector& pools) { - if (context_.vk.vkDestroyQueryPool) { - for (const auto& entry : pools) { - if (entry.pool) context_.vk.vkDestroyQueryPool(context_.device(), entry.pool, nullptr); - } - } - pools.clear(); - } - - void recycle_khr_as_queries(std::vector& pools) { - for (auto& entry : pools) { - entry.used = 0; - khr_as_query_pool_.push_back(entry); - } - pools.clear(); - } - - bool allocate_khr_as_queries(std::uint32_t count, std::vector& active, VkQueryPool& out_pool, - std::uint32_t& out_first) { - if (!count || !context_.vk.vkCreateQueryPool || !context_.vk.vkDestroyQueryPool) return false; - if (!active.empty()) { - auto& back = active.back(); - if (back.used <= back.capacity && count <= back.capacity - back.used) { - out_pool = back.pool; - out_first = back.used; - back.used += count; - return true; - } - } - for (auto it = khr_as_query_pool_.begin(); it != khr_as_query_pool_.end(); ++it) { - if (it->capacity >= count) { - KhrAsQueryPool entry = *it; - khr_as_query_pool_.erase(it); - entry.used = count; - active.push_back(entry); - out_pool = entry.pool; - out_first = 0; - return true; - } - } - const std::uint32_t capacity = std::max(count, 16u); - VkQueryPoolCreateInfo info{VK_STRUCTURE_TYPE_QUERY_POOL_CREATE_INFO}; - info.queryType = VK_QUERY_TYPE_ACCELERATION_STRUCTURE_COMPACTED_SIZE_KHR; - info.queryCount = capacity; - VkQueryPool pool = VK_NULL_HANDLE; - if (context_.vk.vkCreateQueryPool(context_.device(), &info, nullptr, &pool) != VK_SUCCESS || !pool) - return false; - active.push_back({pool, capacity, count}); - out_pool = pool; - out_first = 0; - return true; - } - - // A KHR TLAS built with D3D12_ELEMENTS_LAYOUT_ARRAY_OF_POINTERS holds console VAs in its pointer list; Vulkan - // reads those 8-byte entries as device addresses. Stage a translated copy in our own host-visible buffer instead - // of editing the guest's input. The caller keeps the stage until the submission that builds with it completes. - ReplayResult stage_khr_instances(const ReplayFunctions& vk, const BuildAccelerationStructure& build, - std::vector& stages, VkDeviceAddress& address) { - const auto& funcs = context_.vk; - if (!funcs.vkCreateBuffer || !funcs.vkDestroyBuffer || !funcs.vkGetBufferMemoryRequirements || - !funcs.vkAllocateMemory || !funcs.vkFreeMemory || !funcs.vkBindBufferMemory || !funcs.vkMapMemory || - !funcs.vkUnmapMemory || !funcs.vkGetBufferDeviceAddress || !vk.host_at || !vk.buffer_at || - !build.instance_count) - return ReplayResult::unsupported; - const std::uint64_t bytes = 8ull * build.instance_count; - const std::uint8_t* guest = nullptr; - const HostReadStatus status = vk.host_at(build.instances_va, bytes, guest); - if (status == HostReadStatus::not_cpu_written) return ReplayResult::unsupported; - if (status != HostReadStatus::ok) return ReplayResult::invalid_copy; - - KhrInstanceStage stage{}; - const auto discard = [&] { - if (stage.memory) funcs.vkFreeMemory(context_.device(), stage.memory, nullptr); - if (stage.buffer) funcs.vkDestroyBuffer(context_.device(), stage.buffer, nullptr); - }; - // Reuse a completed stage that is already large enough. A per-frame TLAS rebuild then reuses the same buffer - // and memory instead of making a new vkAllocateMemory call every frame. - for (auto it = khr_stage_pool_.begin(); it != khr_stage_pool_.end(); ++it) { - if (it->size >= bytes) { - stage = std::move(*it); - khr_stage_pool_.erase(it); - break; - } - } - if (!stage.buffer) { - VkBufferCreateInfo info{VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO}; - info.size = bytes; - info.usage = VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT | - VK_BUFFER_USAGE_ACCELERATION_STRUCTURE_BUILD_INPUT_READ_ONLY_BIT_KHR; - if (funcs.vkCreateBuffer(context_.device(), &info, nullptr, &stage.buffer) != VK_SUCCESS) - return ReplayResult::unsupported; - VkMemoryRequirements requirements{}; - funcs.vkGetBufferMemoryRequirements(context_.device(), stage.buffer, &requirements); - const auto& memory = context_.occlusion_resolve_memory_; - constexpr VkMemoryPropertyFlags host_flags = - VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT; - std::uint32_t type = memory.memoryTypeCount; - for (std::uint32_t i = 0; i < memory.memoryTypeCount; ++i) { - if (!(requirements.memoryTypeBits & (1u << i))) continue; - if ((memory.memoryTypes[i].propertyFlags & host_flags) == host_flags) { - type = i; - break; - } - } - if (type == memory.memoryTypeCount) { - discard(); - return ReplayResult::unsupported; - } - VkMemoryAllocateFlagsInfo flags{VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_FLAGS_INFO}; - flags.flags = VK_MEMORY_ALLOCATE_DEVICE_ADDRESS_BIT; - VkMemoryAllocateInfo allocation{VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO, &flags}; - allocation.allocationSize = requirements.size; - allocation.memoryTypeIndex = type; - if (funcs.vkAllocateMemory(context_.device(), &allocation, nullptr, &stage.memory) != VK_SUCCESS || - funcs.vkBindBufferMemory(context_.device(), stage.buffer, stage.memory, 0) != VK_SUCCESS) { - discard(); - return ReplayResult::unsupported; - } - stage.size = bytes; - } - - void* mapped = nullptr; - if (funcs.vkMapMemory(context_.device(), stage.memory, 0, bytes, 0, &mapped) != VK_SUCCESS) { - discard(); - return ReplayResult::unsupported; - } - // Validate and translate in one pass straight into the staging buffer; no second vector of addresses. - for (std::uint32_t i = 0; i < build.instance_count; ++i) { - std::uint64_t va = 0; - std::memcpy(&va, guest + 8ull * i, sizeof(va)); - VkBuffer buffer = VK_NULL_HANDLE; - VkDeviceSize offset = 0; - std::uint64_t room = 64; // one D3D12_RAYTRACING_INSTANCE_DESC - // No overflow check on heap_base + va: a buffer outside the arena whose device address lies below the - // arena's (an UPLOAD heap in system memory without Resizable BAR) has a VA that wraps (address - base), - // and the unsigned sum wraps back to its device address, as the replay's other VA translations do. - if (!va || !vk.buffer_at(va, room, buffer, offset) || room < 64) { - funcs.vkUnmapMemory(context_.device(), stage.memory); - discard(); - return ReplayResult::invalid_copy; - } - const std::uint64_t device_address = vk.heap_base + va; - std::memcpy(static_cast(mapped) + 8ull * i, &device_address, sizeof(device_address)); - } - funcs.vkUnmapMemory(context_.device(), stage.memory); - VkBufferDeviceAddressInfo device_address{VK_STRUCTURE_TYPE_BUFFER_DEVICE_ADDRESS_INFO}; - device_address.buffer = stage.buffer; - stage.address = funcs.vkGetBufferDeviceAddress(context_.device(), &device_address); - if (!stage.address) { - discard(); - return ReplayResult::unsupported; - } - stages.push_back(std::move(stage)); - address = stages.back().address; - return ReplayResult::success; - } - - ReplayResult execute_now(std::span lists) { - if (context_.is_device_lost() || !wait_for_room()) return ReplayResult::unsupported; - if (kind_ != QueueKind::direct) - for (const auto* list : lists) - for (const auto& command : list->commands()) - if (std::holds_alternative(command) || - std::holds_alternative(command)) - return ReplayResult::unsupported; - VkCommandBuffer command_buffer = VK_NULL_HANDLE; - struct KhrGuard { - VulkanQueue* queue; - std::vector stages; - std::vector as_queries; - ~KhrGuard() { - queue->recycle_khr_stages(stages); - queue->recycle_khr_as_queries(as_queries); - } - } khr_guard{this}; - std::function bindless_commit; - // Lock hierarchy: resource_mutex_ -> tracker_mutex_ -> submit_mutex_. - // Shared read-lock allows concurrent prepare() across queues; tracker_mutex_ is acquired lazily during - // prepare() only if a list actually converts a depth24_as_float copy, and otherwise right before - // bindless_prepare_/emit() through submit() so bindless flushes, layout emits, and submissions stay in order. - std::shared_lock resource_lock(context_.resource_mutex_); - std::unique_lock tracker_lock(context_.tracker_mutex_, std::defer_lock); - // Declared after tracker_lock so any early return after depth24_->prepare() retires uncommitted scratch/pools - // with ticket 0 while tracker_lock is still held. - struct Depth24Guard { - Depth24Converter* d24 = nullptr; - VkSemaphore progress = VK_NULL_HANDLE; - bool active = false; - ~Depth24Guard() { - if (active && d24) d24->retire(progress, 0); - } - } depth24_guard{context_.depth24_.get(), progress_, false}; - struct ScratchGuard { // the same for the copy scratch - ScratchBuffers* scratch = nullptr; - VkSemaphore progress = VK_NULL_HANDLE; - bool active = false; - ~ScratchGuard() { - if (active && scratch) scratch->retire(progress, 0); - } - } scratch_guard{context_.scratch_.get(), progress_, false}; - const bool transfer_only = family_ == context_.transfer_only_family_; - if (!transfer_only) bindless_commit = context_.bindless_commit_; - // Kept between executions: prepare refills each list's entries in the storage the last execution left, where - // making them fresh for every command was about half the layer's CPU cost per command (replay_cpu_bench). - auto& prepared = prepared_; - // Keep the storage from a larger batch. resize() down would destroy the unused entries and their vectors, so - // a queue that sees 8 lists and then 1 in every frame would rebuild them on each execution. The loops below - // use only the first lists.size() entries, so stale entries are never prepared, queried or emitted. - if (prepared.size() < lists.size()) prepared.resize(lists.size()); - ReplayFunctions replay = context_.replay_; - replay.queue_stages = kind_ == QueueKind::copy ? detail::queue_stages_copy - : kind_ == QueueKind::compute ? detail::queue_stages_compute - : 0; - replay.prepare_khr_instances = [this, &replay, &khr_guard](const BuildAccelerationStructure& build, - VkDeviceAddress& address) { - return stage_khr_instances(replay, build, khr_guard.stages, address); - }; - if (replay.write_acceleration_structures_properties) { - replay.prepare_khr_postbuild = [this, &khr_guard](std::uint32_t count, VkQueryPool& pool, - std::uint32_t& first) { - return allocate_khr_as_queries(count, khr_guard.as_queries, pool, first); - }; - } - std::uint64_t captures = 0; - for (const auto* list : lists) - for (const auto& command : list->commands()) - if (const auto* p = std::get_if(&command); p && p->buffer) ++captures; - std::unique_ptr batch; - std::unique_ptr copy_batch; - std::unique_ptr counted_batch; - if (captures) { - if (kind_ == QueueKind::copy || !context_.predicate_reducer_ || family_ != context_.predicate_family_) - return ReplayResult::unsupported; - // The helper's lazy pipeline is shared by queues. Serialize preparation with the tracker lock, - // retaining main's resource -> tracker -> submit lock order through emit and submission. - if (!tracker_lock.owns_lock()) tracker_lock.lock(); - batch = context_.predicate_reducer_->batch(captures); - if (!batch) return ReplayResult::unsupported; - replay.prepare_predicate = [&](VkBuffer buffer, VkDeviceSize offset, PredicateCapture& out) { - return batch->prepare(buffer, offset, out); - }; - replay.capture_predicate = [&](VkCommandBuffer cb, const PredicateCapture& p) { - context_.predicate_reducer_->capture(cb, p); - }; - if (context_.predicated_copier_) { - copy_batch = context_.predicated_copier_->batch(); - replay.prepare_predicated_copy = [&](VkBuffer source, VkBuffer destination, VkDeviceSize src, - VkDeviceSize dst, VkDeviceSize size, - std::vector& out) { - return copy_batch->prepare(source, destination, src, dst, size, out); - }; - replay.emit_predicated_copy = [&](VkCommandBuffer cb, const std::vector& jobs) { - context_.predicated_copier_->emit(cb, jobs); - }; - } - } - if (context_.scratch_) { - replay.copy_scratch = [this, &tracker_lock, &scratch_guard](VkDeviceSize bytes, VkBuffer& buffer, - VkDeviceSize& offset) { - if (!tracker_lock.owns_lock()) tracker_lock.lock(); - if (!scratch_guard.active) { - context_.scratch_->collect(); - scratch_guard.active = true; - } - return context_.scratch_->get(bytes, buffer, offset); - }; - } - if (kind_ != QueueKind::copy && context_.counted_dispatch_) { - replay.prepare_counted_dispatch = [this, &tracker_lock, &counted_batch]( - VkBuffer args, VkDeviceSize args_offset, VkBuffer count, VkDeviceSize count_offset, - std::uint32_t stride, std::uint32_t maximum, CountedDispatch& out) { - // Pipeline creation is lazy and shared across queues; serialize it with other replay preparation. - if (!tracker_lock.owns_lock()) tracker_lock.lock(); - if (!counted_batch) counted_batch = context_.counted_dispatch_->batch(); - return counted_batch->prepare(args, args_offset, count, count_offset, stride, maximum, out); - }; - replay.emit_counted_dispatch = [this](VkCommandBuffer cb, const CountedDispatch& job) { - context_.counted_dispatch_->emit(cb, job); - }; - } - if (context_.depth24_ && !transfer_only) { - replay.depth24_prepare = [this, &tracker_lock, &depth24_guard](Depth24Job& job, - std::vector& parts) { - if (!tracker_lock.owns_lock()) tracker_lock.lock(); - if (!depth24_guard.active) { - context_.depth24_->collect(); - depth24_guard.active = true; - } - return context_.depth24_->prepare(job, parts); - }; - } - const auto& occlusion_memory = context_.occlusion_resolve_memory_; - const bool can_resolve_occlusion = occlusion_memory.memoryTypeCount != 0; - if (can_resolve_occlusion) { - replay.sum_occlusion = [this](VkCommandBuffer cb, VkQueryPool pool, std::uint32_t first, - std::uint32_t count, VkBuffer dst, VkDeviceSize offset) { - occlusion_resolve_->sum(cb, pool, first, count, dst, offset); - }; - replay.resolve_binary_occlusion = [this](VkCommandBuffer cb, VkQueryPool pool, std::uint32_t first, - std::uint32_t count, VkBuffer dst, VkDeviceSize offset) { - occlusion_resolve_->normalize(cb, pool, first, count, dst, offset); - }; - replay.sum_statistics = [this](VkCommandBuffer cb, VkQueryPool pool, VkQueryPool mesh_pool, - const std::uint8_t* mesh, std::uint32_t first, std::uint32_t count, - VkBuffer dst, VkDeviceSize offset) { - occlusion_resolve_->sum_statistics(cb, pool, mesh_pool, mesh, first, count, dst, offset); - }; - replay.sum_binary_occlusion = [this](VkCommandBuffer cb, VkQueryPool pool, std::uint32_t first, - std::uint32_t count, VkBuffer dst, VkDeviceSize offset) { - occlusion_resolve_->sum_binary(cb, pool, first, count, dst, offset); - }; - } - const auto resolve = [this](ResourceId id) { return context_.resolve(id); }; - std::uint32_t segments = 0, statistics_segments = 0; - bool has_queries = false; - for (std::size_t i = 0; i < lists.size(); ++i) { - const auto result = prepare(*lists[i], resolve, replay, prepared[i], can_resolve_occlusion); - if (result != ReplayResult::success) return result; - if (prepared[i].segment_count > UINT32_MAX - segments || - prepared[i].statistics_segment_count > UINT32_MAX - statistics_segments) - return ReplayResult::unsupported; - segments += prepared[i].segment_count; - statistics_segments += prepared[i].statistics_segment_count; - has_queries = has_queries || !prepared[i].queries.empty(); - } - const auto segment_pool = [this](VkQueryType type, std::uint32_t count, - std::shared_ptr& out) { - const auto& vk = context_.vk; - if (!vk.vkCreateQueryPool || !vk.vkDestroyQueryPool) return false; - out = std::make_shared(); - out->device = context_.device(); - out->destroy = vk.vkDestroyQueryPool; - VkQueryPoolCreateInfo info{VK_STRUCTURE_TYPE_QUERY_POOL_CREATE_INFO}; - info.queryType = type; - info.queryCount = count; - // The counters of a D3D12 pipeline-statistics heap, in D3D12_QUERY_DATA_PIPELINE_STATISTICS order. - if (type == VK_QUERY_TYPE_PIPELINE_STATISTICS) info.pipelineStatistics = 0x7ff; - return vk.vkCreateQueryPool(out->device, &info, nullptr, &out->pool) == VK_SUCCESS; - }; - std::shared_ptr physical, statistics; - if (segments && !segment_pool(VK_QUERY_TYPE_OCCLUSION, segments, physical)) return ReplayResult::unsupported; - // Without the compute helper a split query could not be summed: leave statistics queries whole, as before - // (QueryReplay::plan refuses a list whose statistics query holds a mesh draw then). - if (statistics_segments && can_resolve_occlusion) { - if (!segment_pool(VK_QUERY_TYPE_PIPELINE_STATISTICS, statistics_segments, statistics)) - return ReplayResult::unsupported; - for (const auto& list : prepared) - statistics->mesh.insert(statistics->mesh.end(), list.statistics_mesh.begin(), - list.statistics_mesh.end()); - if (std::find(statistics->mesh.begin(), statistics->mesh.end(), 1) == statistics->mesh.end()) { - statistics->mesh.clear(); - } else { - // The counters a mesh draw allows (VUID-vkCmdDrawMeshTasksEXT-pipelineStatistics-07076): clipping - // invocations and primitives, fragment and compute invocations (D3D-291). - VkQueryPoolCreateInfo info{VK_STRUCTURE_TYPE_QUERY_POOL_CREATE_INFO}; - info.queryType = VK_QUERY_TYPE_PIPELINE_STATISTICS; - info.queryCount = statistics_segments; - info.pipelineStatistics = VK_QUERY_PIPELINE_STATISTIC_CLIPPING_INVOCATIONS_BIT | - VK_QUERY_PIPELINE_STATISTIC_CLIPPING_PRIMITIVES_BIT | - VK_QUERY_PIPELINE_STATISTIC_FRAGMENT_SHADER_INVOCATIONS_BIT | - VK_QUERY_PIPELINE_STATISTIC_COMPUTE_SHADER_INVOCATIONS_BIT; - if (context_.vk.vkCreateQueryPool(statistics->device, &info, nullptr, &statistics->mesh_pool) != - VK_SUCCESS) - return ReplayResult::unsupported; - } - } - // QueryReplay::plan() reads QueryPool::ended / occlusion and QueryReplay::commit() writes them after - // resource_lock is unlocked. Hold tracker_mutex_ across plan -> emit -> submit -> commit so concurrent queues - // see submission-order query state and remove_query_pool() waits until commit finishes. - if (has_queries && !tracker_lock.owns_lock()) tracker_lock.lock(); - QueryReplay queries; - std::uint32_t base = 0, statistics_base = 0; - for (std::size_t i = 0; i < lists.size(); ++i) { - auto& list = prepared[i]; - const auto result = queries.plan(list, physical, base, can_resolve_occlusion, statistics, statistics_base); - if (result != ReplayResult::success) return result; - base += list.segment_count; - statistics_base += list.statistics_segment_count; - } - if (queries.needs_sum || queries.needs_binary || queries.needs_statistics_sum || queries.needs_sum_binary) { - if (!occlusion_resolve_) { - auto helper = std::make_unique(context_.vk, context_.device()); - if (!helper->initialize(occlusion_memory)) return ReplayResult::unsupported; - occlusion_resolve_ = std::move(helper); - } - if (!occlusion_resolve_->prepare(queries.needs_sum, queries.needs_binary, queries.needs_statistics_sum, - queries.needs_sum_binary)) - return ReplayResult::unsupported; - } - - CommandSlot* slot = acquire(); - if (!slot) return ReplayResult::unsupported; - slot->khr_instances = std::move(khr_guard.stages); // freed when this slot is reused - khr_guard.stages.clear(); - slot->khr_as_queries = std::move(khr_guard.as_queries); - khr_guard.as_queries.clear(); - command_buffer = slot->buffer; - // MoltenVK writes a timestamp at the end of a Metal encoder and resolves it with a blit that nothing orders - // after that write, so a copy in the same or the next command buffer reads the old value (docs section 4.6). - // An event set and waited for in this command buffer orders it after this submission's timestamps; a wait for - // this queue's previous submission orders it after earlier ones still running. - bool ordered_timestamps = false; - const auto& events = context_.vk; - if (context_.order_timestamp_copies() && events.vkCreateEvent && events.vkDestroyEvent && events.vkResetEvent && - events.vkCmdSetEvent && events.vkCmdWaitEvents) - replay.order_timestamp_copy = [this, slot, &ordered_timestamps](VkCommandBuffer cb) { - const VkEvent event = take_event(); - if (!event) return; - slot->events.push_back(event); - const auto& vk = context_.vk; - vk.vkCmdSetEvent(cb, event, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT); - vk.vkCmdWaitEvents(cb, 1, &event, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, - VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, 0, nullptr, 0, nullptr, 0, nullptr); - ordered_timestamps = true; - }; - const auto discard = [&] { - if (context_.vk.vkResetCommandBuffer(command_buffer, 0) == VK_SUCCESS) slot->ticket = 0; - }; - VkCommandBufferBeginInfo begin{VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO}; - begin.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT; - if (context_.vk.vkBeginCommandBuffer(command_buffer, &begin) != VK_SUCCESS) { - discard(); - return ReplayResult::unsupported; - } - if (!tracker_lock.owns_lock()) tracker_lock.lock(); - if (!transfer_only && context_.bindless_prepare_ && !context_.bindless_prepare_(command_buffer)) { - const bool ended = context_.vk.vkEndCommandBuffer(command_buffer) == VK_SUCCESS; - resource_lock.unlock(); - const bool submitted = ended && submit(command_buffer, VK_NULL_HANDLE, 0); - if (!submitted) discard(); - if (depth24_guard.active) { - context_.depth24_->retire(progress_, 0); - depth24_guard.active = false; - } - if (scratch_guard.active) { - context_.scratch_->retire(progress_, 0); - scratch_guard.active = false; - } - if (bindless_commit) bindless_commit(submitted); - tracker_lock.unlock(); - return ReplayResult::unsupported; - } - replay.bindless_set = context_.bindless_current_ ? context_.bindless_current_() : VK_NULL_HANDLE; - const bool bindless_uploaded = std::exchange(context_.bindless_upload_pending_, false); - auto next_tracker = context_.tracker_; - // Bindless images that may already be visible to shaders are initialized on a submission that runs shaders. - // initialize() zeroes committed storage images and only transitions sparse images. - bool runs_shaders = false; - for (const CommandList* list : lists) - for (const auto& command : list->commands()) - runs_shaders |= std::holds_alternative(command) || std::holds_alternative(command) || - std::holds_alternative(command); - std::vector storage_images; - std::vector zero_buffers; - { - std::lock_guard lock(context_.storage_mutex_); - if (context_.storage_init_semaphore_ && context_.storage_init_semaphore_ != progress_ && - context_.storage_init_version_ != storage_init_seen_) { - waits_.push_back(context_.storage_init_semaphore_); - wait_values_.push_back(context_.storage_init_value_); - storage_init_seen_ = context_.storage_init_version_; - } - // The set this submission binds may be a new generation whose table another queue's submission uploads: - // wait for that one, as for the storage images (the table's buffers are used by one queue family only: - // every D3D12 queue of the device is made in info.queue_family). - if (context_.bindless_upload_semaphore_ && context_.bindless_upload_semaphore_ != progress_ && - context_.bindless_upload_version_ != bindless_upload_seen_) { - waits_.push_back(context_.bindless_upload_semaphore_); - wait_values_.push_back(context_.bindless_upload_value_); - } - bindless_upload_seen_ = context_.bindless_upload_version_; - if (kind_ != QueueKind::copy && runs_shaders) - storage_images.assign(context_.storage_pending_.begin(), context_.storage_pending_.end()); - if (!storage_images.empty()) context_.storage_pending_.clear(); - zero_buffers.swap(context_.zero_pending_); // any queue can fill a buffer - } - for (const auto& zero : zero_buffers) - context_.vk.vkCmdFillBuffer(command_buffer, zero.buffer, 0, VK_WHOLE_SIZE, 0); - if (!zero_buffers.empty()) { - VkMemoryBarrier filled{VK_STRUCTURE_TYPE_MEMORY_BARRIER}; - filled.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT; - filled.dstAccessMask = VK_ACCESS_MEMORY_READ_BIT | VK_ACCESS_MEMORY_WRITE_BIT; - context_.vk.vkCmdPipelineBarrier(command_buffer, VK_PIPELINE_STAGE_TRANSFER_BIT, - VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, 0, 1, &filled, 0, nullptr, 0, nullptr); - } - for (const ResourceId id : storage_images) { - const ResourceBinding* image = context_.resolve(id); - if (!image || !image->image) continue; - const VkImageSubresourceRange range{image->aspects, 0, image->mip_levels, 0, image->array_layers}; - auto pieces = detail::current(&next_tracker, id, range, VK_IMAGE_LAYOUT_UNDEFINED); - detail::initialize(replay, command_buffer, *image, id, pieces, VK_IMAGE_LAYOUT_GENERAL, &next_tracker); - } - bool wrote_readback = false; - VkPipelineStageFlags2 readback_stages = 0; - std::uint32_t open_labels = 0; // events may span the lists of one ExecuteCommandLists - for (std::size_t i = 0; i < lists.size(); ++i) { - const auto& list = prepared[i]; - emit(list, command_buffer, replay, &next_tracker, &open_labels); - wrote_readback |= list.wrote_readback; - readback_stages |= list.readback_src_stages; - } - close_labels(command_buffer, replay, open_labels); - // Only flush GPU writes to the host domain when this batch actually wrote to a readback buffer. - if (wrote_readback) { - const VkPipelineStageFlags2 allowed = queue_supported_stages(kind_); - VkPipelineStageFlags2 src_stages = readback_stages & allowed; - if (!src_stages) src_stages = VK_PIPELINE_STAGE_2_TRANSFER_BIT; - const bool copy_only = - (src_stages & ~(VK_PIPELINE_STAGE_2_COPY_BIT | VK_PIPELINE_STAGE_2_TRANSFER_BIT)) == 0; - const VkAccessFlags2 src_access = - copy_only ? VK_ACCESS_2_TRANSFER_WRITE_BIT : VK_ACCESS_2_MEMORY_WRITE_BIT; - - if (context_.vk.vkCmdPipelineBarrier2) { - VkMemoryBarrier2 host{VK_STRUCTURE_TYPE_MEMORY_BARRIER_2}; - host.srcStageMask = src_stages; - host.srcAccessMask = src_access; - host.dstStageMask = VK_PIPELINE_STAGE_2_HOST_BIT; - host.dstAccessMask = VK_ACCESS_2_HOST_READ_BIT; - VkDependencyInfo dep{VK_STRUCTURE_TYPE_DEPENDENCY_INFO}; - dep.memoryBarrierCount = 1; - dep.pMemoryBarriers = &host; - context_.vk.vkCmdPipelineBarrier2(command_buffer, &dep); - } else { - const VkPipelineStageFlags legacy_src = - copy_only ? VK_PIPELINE_STAGE_TRANSFER_BIT : VK_PIPELINE_STAGE_ALL_COMMANDS_BIT; - VkMemoryBarrier host{VK_STRUCTURE_TYPE_MEMORY_BARRIER}; - host.srcAccessMask = copy_only ? VK_ACCESS_TRANSFER_WRITE_BIT : VK_ACCESS_MEMORY_WRITE_BIT; - host.dstAccessMask = VK_ACCESS_HOST_READ_BIT; - context_.vk.vkCmdPipelineBarrier(command_buffer, legacy_src, VK_PIPELINE_STAGE_HOST_BIT, - 0, 1, &host, 0, nullptr, 0, nullptr); - } - } - const bool ended = context_.vk.vkEndCommandBuffer(command_buffer) == VK_SUCCESS; - resource_lock.unlock(); // release resource_mutex_ before vkQueueSubmit while keeping tracker_lock held - const bool wait_previous = ordered_timestamps && submitted_; - if (wait_previous) { - waits_.push_back(progress_); - wait_values_.push_back(submitted_); - } - const bool submitted = ended && submit(command_buffer, VK_NULL_HANDLE, 0); - if (!submitted && (!storage_images.empty() || !zero_buffers.empty())) { - // not initialized after all: try again with the next submission - std::lock_guard lock(context_.storage_mutex_); - context_.storage_pending_.insert(storage_images.begin(), storage_images.end()); - context_.zero_pending_.insert(context_.zero_pending_.end(), zero_buffers.begin(), zero_buffers.end()); - } - if (submitted && (!storage_images.empty() || !zero_buffers.empty())) { - std::lock_guard lock(context_.storage_mutex_); - context_.storage_init_semaphore_ = progress_; - context_.storage_init_value_ = submitted_; - ++context_.storage_init_version_; - storage_init_seen_ = context_.storage_init_version_; - } - if (submitted && bindless_uploaded) { - std::lock_guard lock(context_.storage_mutex_); - context_.bindless_upload_semaphore_ = progress_; - context_.bindless_upload_value_ = submitted_; - ++context_.bindless_upload_version_; - bindless_upload_seen_ = context_.bindless_upload_version_; - } - if (wait_previous && !submitted && !waits_.empty()) { // a failed submit keeps the waits for the next one - waits_.pop_back(); - wait_values_.pop_back(); - } - if (submitted) { - context_.tracker_ = std::move(next_tracker); - slot->predicate = std::move(batch); - slot->predicated_copy = std::move(copy_batch); - slot->counted_dispatch = std::move(counted_batch); - queries.commit(); - slot->segments = std::move(queries.retained); - } else { - discard(); - } - if (depth24_guard.active) { - context_.depth24_->retire(progress_, submitted ? submitted_ : 0); - depth24_guard.active = false; - } - if (scratch_guard.active) { - context_.scratch_->retire(progress_, submitted ? submitted_ : 0); - scratch_guard.active = false; - } - // Under tracker_mutex_, so no other flush comes between this submit and the set's note of whether it reached - // the queue (it keeps a single upload obligation). - if (bindless_commit) bindless_commit(submitted); - tracker_lock.unlock(); - return submitted ? ReplayResult::success : ReplayResult::unsupported; - } - - void marker_now(DebugMarker::Kind kind, const char* label) { - const DebugLabelFunctions& f = context_.labels_; - if (!f.complete()) return; - if (kind == DebugMarker::Kind::end && !open_labels_) return; - VkDebugUtilsLabelEXT info{VK_STRUCTURE_TYPE_DEBUG_UTILS_LABEL_EXT}; - info.pLabelName = label ? label : ""; - std::lock_guard lock(context_.submit_mutex()); - if (kind == DebugMarker::Kind::set) { - f.queue_insert(queue_, &info); - } else if (kind == DebugMarker::Kind::begin) { - f.queue_begin(queue_, &info); - ++open_labels_; - } else { - f.queue_end(queue_); - --open_labels_; - } - } - - // ---- Wait-before-Signal: operations held on the CPU (queue_holds.h) ---- - - // One held operation, with the waits that were pending when it was asked for. - struct Deferred { - enum class Kind : std::uint8_t { batch, signal, marker }; - Kind kind = Kind::batch; - std::uint64_t seq = 0; // QueueHolds::next_seq(): the order operations were held in, across queues - std::vector waits; - std::vector wait_values; - std::vector lists; // batch: copies, so the application may Reset its lists after the call - VkSemaphore fence = VK_NULL_HANDLE; // signal - std::uint64_t value = 0; - DebugMarker::Kind marker_kind = DebugMarker::Kind::set; // marker - std::string label; - // Alive until the operation has run: the fences it waits on and signals, the pipeline states and root - // signatures of the lists (the application may release them right after the call). - std::vector> pins; - std::vector> wait_pins; // the fences of `waits` - }; - - bool waits_pending(const std::vector& semaphores, const std::vector& values) const { - for (std::size_t i = 0; i < semaphores.size(); ++i) - if (context_.holds().pending(semaphores[i], values[i])) return true; - return false; - } - - // The next batch or Signal has to be held: something is held ahead of it (queue order), or a Wait it carries - // has no submitted Signal yet. Called with state_mutex_ held. - bool must_hold() const { return !held_.empty() || waits_pending(waits_, wait_values_); } - - // The waits are consumed: submitted as `ticket` (0: dropped on device loss). What the application may release - // (the fences they named) is kept until that submission has completed on the GPU, as a D3D12 queue does: - // destroying a semaphore a pending submission uses is a validation error. Retired pins are destroyed by the - // caller after state_mutex_ is released (drain_pins): the last release of a fence waits for a running release, - // which must not be waiting for this lock. - void clear_waits(std::uint64_t ticket = 0) { - waits_.clear(); - wait_values_.clear(); - retire_pins(wait_pins_, ticket); - } - - void retire_pins(std::vector>& pins, std::uint64_t ticket) { - for (auto& pin : pins) { - if (ticket) pin_queue_.push_back({ticket, std::move(pin)}); - else retired_pins_.push_back(std::move(pin)); - } - pins.clear(); - } - - // Moves the pins whose submission has completed (and the ones retired outright) to `out`. state_mutex_ held. - void drain_pins(std::vector>& out) { - out.swap(retired_pins_); - if (pin_queue_.empty()) return; - const std::uint64_t done = completed(); - while (!pin_queue_.empty() && pin_queue_.front().ticket <= done) { - out.push_back(std::move(pin_queue_.front().pin)); - pin_queue_.pop_front(); - } - } - - // Appends `op`, which takes the pending waits with it (a marker has none). Called with state_mutex_ held. - void hold(Deferred&& op) { - op.seq = context_.holds().next_seq(); - if (op.kind != Deferred::Kind::marker) { - op.waits = std::move(waits_); - op.wait_values = std::move(wait_values_); - op.wait_pins = std::move(wait_pins_); - waits_.clear(); - wait_values_.clear(); - wait_pins_.clear(); - } - held_.push_back(std::move(op)); - context_.holds().held_changed(1); - } - - // Runs one held operation as the call would have, with its own waits and none of the ones queued since. - // A submission that fails leaves its waits for the next one, as when the call is not held (a transient - // vkQueueSubmit failure is retried by the application's next call), ahead of the waits asked for since. - void run(Deferred& op) { - auto later_waits = std::move(waits_); - auto later_values = std::move(wait_values_); - auto later_pins = std::move(wait_pins_); - waits_ = std::move(op.waits); - wait_values_ = std::move(op.wait_values); - wait_pins_ = std::move(op.wait_pins); // the fences stay alive until the submission has consumed their waits - switch (op.kind) { - case Deferred::Kind::batch: { - std::vector lists; - for (const CommandList& list : op.lists) lists.push_back(&list); - // The pipeline states and root signatures of the lists are in op.pins (see execute()): they live until - // the batch has been recorded and then, with the fences, until its submission has completed (below). - const ReplayResult result = execute_now(lists); - if (result != ReplayResult::success) { - int none = static_cast(ReplayResult::success); - held_failure_.compare_exchange_strong(none, static_cast(result)); - RT_LOG_ERROR("d3d12: a held ExecuteCommandLists failed when it was released (result %d); " - "nothing was submitted for it, and a Signal behind it still signals\n", - static_cast(result)); - } - break; - } - case Deferred::Kind::signal: - if (!submit(VK_NULL_HANDLE, op.fence, op.value)) - RT_LOG_ERROR("d3d12: a held Signal failed when it was released\n"); - break; - case Deferred::Kind::marker: - marker_now(op.marker_kind, op.label.c_str()); - break; - } - retire_pins(op.pins, submitted_); // the fence it signals, the pipeline states: until its submission is done - waits_.insert(waits_.end(), later_waits.begin(), later_waits.end()); - wait_values_.insert(wait_values_.end(), later_values.begin(), later_values.end()); - for (auto& pin : later_pins) wait_pins_.push_back(std::move(pin)); - } - - bool ready(const Deferred& op) const { return !waits_pending(op.waits, op.wait_values); } - - // Holder: called by the thread whose Signal made a held operation ready (never with a queue lock held). - bool release_ready() override { - std::vector> retired; - bool released = false; - { - std::lock_guard state(state_mutex_); - while (!held_.empty() && (context_.is_device_lost() || ready(held_.front()))) { - Deferred op = std::move(held_.front()); - held_.pop_front(); - context_.holds().held_changed(-1); - if (!context_.is_device_lost()) run(op); - released = true; - } - drain_pins(retired); - } - return released; - } - - // Holder: the fence is released, so what waits on it can never run. - void discard_waiting_on(VkSemaphore semaphore) override { - std::vector dropped; - { - std::lock_guard state(state_mutex_); - for (auto it = held_.begin(); it != held_.end();) { - if (std::find(it->waits.begin(), it->waits.end(), semaphore) == it->waits.end() && - !(it->kind == Deferred::Kind::signal && it->fence == semaphore)) { - ++it; - continue; - } - RT_LOG_WARN("d3d12: a fence was released while a queue still held work that names it; " - "that work is dropped\n"); - dropped.push_back(std::move(*it)); - it = held_.erase(it); - context_.holds().held_changed(-1); - } - } - } - - // Holder: the sequence number of the oldest held operation. - std::uint64_t oldest_held_seq() override { - std::lock_guard state(state_mutex_); - return held_.empty() ? 0 : held_.front().seq; - } - - // A queue destroyed with held work. Reported, not waited for: nothing was submitted for it, so the VkQueue is - // idle and the destructor goes on. The fences of held Signals will never reach their values, so what is waiting - // for them on the CPU (SetEventOnCompletion, as a released fence completes them) is woken, and the batches - // that wait for them on other queues stay held (and are reported when those queues are destroyed). - void report_held_at_teardown() { - std::deque dropped; - { - std::lock_guard state(state_mutex_); - if (held_.empty()) return; - std::uint64_t value = 0; - for (const Deferred& op : held_) - for (std::size_t i = 0; i < op.waits.size() && !value; ++i) - if (context_.holds().pending(op.waits[i], op.wait_values[i])) value = op.wait_values[i]; - std::size_t signals = 0; - for (const Deferred& op : held_) signals += op.kind == Deferred::Kind::signal; - RT_LOG_WARN("d3d12: queue destroyed with %zu held operation(s) never submitted: waits for a " - "fence value (%llu) that no Signal reached; the fence was never signaled%s\n", - held_.size(), static_cast(value), - signals ? "; CPU waits on the fences of its held Signals are completed" : ""); - for (const Deferred& op : held_) - if (op.kind == Deferred::Kind::signal) context_.cancel_fence_waits(op.fence); - context_.holds().held_changed(-static_cast(held_.size())); - dropped.swap(held_); - } - // The pins (fences, pipeline states) are released here, outside the lock. - } - - struct CommandSlot { - VkCommandBuffer buffer; - std::uint64_t ticket; - std::vector> segments; - std::vector events; // order_timestamp_copy's, reset and reused once the slot completes - std::unique_ptr predicated_copy; - std::unique_ptr counted_dispatch; - std::unique_ptr predicate; // retained until this slot completes - std::vector khr_instances; // KHR ARRAY_OF_POINTERS staging, same lifetime - std::vector khr_as_queries; // KHR postbuild COMPACTED_SIZE query pools, same lifetime - }; - - struct PendingBindings { - std::uint64_t ticket = 0; - // Vulkan needs the resource until the bind completes and the previous allocation until it is unmapped. - std::vector> old_heaps; - std::shared_ptr resource; - }; - - static bool valid_tiles(const SparseResource& resource, TileRegion region) { - return region.count && region.first < resource.tile_count && region.count <= resource.tile_count - region.first; - } - - bool initialize_sparse_image_layout(ResourceId id) { - std::lock_guard lock(context_.tracker_mutex_); - if (context_.tracker_.layout(id, 0) != VK_IMAGE_LAYOUT_UNDEFINED) return true; - auto* slot = acquire(); - if (!slot) return false; - const VkCommandBuffer command_buffer = slot->buffer; - auto& vk = context_.vk; - VkCommandBufferBeginInfo begin{VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO}; - begin.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT; - if (vk.vkBeginCommandBuffer(command_buffer, &begin) != VK_SUCCESS) { - slot->ticket = 0; - return false; - } - // Transition while the image is still unbound. Doing this after binding could discard another image's - // contents in an aliased page. Subsequent uses keep the image in GENERAL. - constexpr VkImageSubresourceRange range{VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1}; - detail::image_barrier(context_.replay_, command_buffer, context_.resources_.at(id), range, - VK_IMAGE_LAYOUT_UNDEFINED, VK_IMAGE_LAYOUT_GENERAL, 0, - VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, VK_ACCESS_MEMORY_READ_BIT | VK_ACCESS_MEMORY_WRITE_BIT, - VK_PIPELINE_STAGE_ALL_COMMANDS_BIT); - if (vk.vkEndCommandBuffer(command_buffer) != VK_SUCCESS || !submit(command_buffer, VK_NULL_HANDLE, 0)) { - slot->ticket = 0; - return false; - } - context_.tracker_.set(id, range, VK_IMAGE_LAYOUT_GENERAL); - return true; - } - - bool bind_tiles(ResourceId id, const std::shared_ptr& resource, - std::map& changes) { - auto& vk = context_.vk; - if (!vk.vkQueueBindSparse || context_.is_device_lost()) return false; - PendingBindings pending{0, {}, resource}; - std::vector binds; - std::vector image_binds; - for (const auto& [index, page] : changes) { - const auto old = resource->mapped.find(index); - if (old != resource->mapped.end()) { - if (old->second == page) continue; - pending.old_heaps.push_back(old->second.heap); - } else if (!page.heap) { - continue; - } - if (page.heap && !(resource->memory_types & (1u << page.heap->memory_type))) return false; - const VkDeviceMemory memory = page.heap ? page.heap->memory : VK_NULL_HANDLE; - if (resource->image) { - constexpr auto shape = element_tile_shape(false, 4); - const auto extent = resource->image_extent; - const auto columns = 1 + (extent.width - 1) / shape.width; - const auto x = std::uint32_t(index % columns) * shape.width; - const auto y = std::uint32_t(index / columns) * shape.height; - image_binds.push_back({ - {VK_IMAGE_ASPECT_COLOR_BIT, 0, 0}, {std::int32_t(x), std::int32_t(y), 0}, - {std::min(shape.width, extent.width - x), std::min(shape.height, extent.height - y), 1}, - memory, page.offset, 0}); - continue; - } - const VkDeviceSize resource_offset = index * tile_size_in_bytes; - if (!binds.empty()) { - auto& previous = binds.back(); - if (previous.resourceOffset + previous.size == resource_offset && previous.memory == memory && - (!memory || previous.memoryOffset + previous.size == page.offset)) { - previous.size += tile_size_in_bytes; - continue; - } - } - binds.push_back({resource_offset, tile_size_in_bytes, memory, page.offset, 0}); - } - if (binds.empty() && image_binds.empty()) return true; - if (!image_binds.empty() && !initialize_sparse_image_layout(id)) return false; - const auto ticket = submitted_ + 1; - pending.ticket = ticket; - collect_bindings(completed()); - auto semaphores = waits_; - auto values = wait_values_; - // Sparse binds are not ordered against work on the same Vulkan queue by submission order alone. - if (submitted_) { - semaphores.push_back(progress_); - values.push_back(submitted_); - } - VkTimelineSemaphoreSubmitInfo tickets{VK_STRUCTURE_TYPE_TIMELINE_SEMAPHORE_SUBMIT_INFO}; - tickets.waitSemaphoreValueCount = std::uint32_t(values.size()); - tickets.pWaitSemaphoreValues = values.data(); - tickets.signalSemaphoreValueCount = 1; - tickets.pSignalSemaphoreValues = &ticket; - const VkSparseBufferMemoryBindInfo buffer_bind{resource->buffer, std::uint32_t(binds.size()), binds.data()}; - const VkSparseImageMemoryBindInfo image_bind{ - resource->image, std::uint32_t(image_binds.size()), image_binds.data()}; - VkBindSparseInfo info{VK_STRUCTURE_TYPE_BIND_SPARSE_INFO, &tickets}; - info.waitSemaphoreCount = std::uint32_t(semaphores.size()); - info.pWaitSemaphores = semaphores.data(); - if (!binds.empty()) { - info.bufferBindCount = 1; - info.pBufferBinds = &buffer_bind; - } - if (!image_binds.empty()) { - info.imageBindCount = 1; - info.pImageBinds = &image_bind; - } - info.signalSemaphoreCount = 1; - info.pSignalSemaphores = &progress_; - pending_bindings_.push_back(std::move(pending)); - { - std::lock_guard lock(context_.submit_mutex()); - const auto result = vk.vkQueueBindSparse(queue_, 1, &info, VK_NULL_HANDLE); - if (result != VK_SUCCESS) { - if (result == VK_ERROR_DEVICE_LOST) context_.mark_device_lost(); - pending_bindings_.pop_back(); - return false; - } - context_.record_submit_locked(progress_, ticket); - } - submitted_ = last_sparse_ = ticket; - clear_waits(ticket); - for (auto it = changes.begin(); it != changes.end();) { - resource->mapped.erase(it->first); - if (it->second.heap) ++it; - else it = changes.erase(it); - } - resource->mapped.merge(changes); - return true; - } - - std::uint64_t completed() const { - if (context_.is_device_lost()) return 0; - std::uint64_t done = 0; - const VkResult result = context_.vk.vkGetSemaphoreCounterValue(context_.device(), progress_, &done); - if (result == VK_ERROR_DEVICE_LOST) context_.mark_device_lost(); - // A failed timeline query cannot be used as a resource-retirement or command-buffer reuse ticket. - return result == VK_SUCCESS ? done : 0; - } - - void collect_bindings(std::uint64_t done) { - while (!pending_bindings_.empty() && pending_bindings_.front().ticket <= done) - pending_bindings_.pop_front(); - if (last_sparse_ <= done) last_sparse_ = 0; - } - - // Releases what every finished command buffer holds; the first of them, or null when none has finished. - CommandSlot* recycle_finished() { - const auto done = completed(); - if (context_.is_device_lost()) return nullptr; - collect_bindings(done); - CommandSlot* reuse = nullptr; - for (auto& slot : buffers_) { - if (slot.ticket > done) continue; - slot.segments.clear(); - recycle_khr_stages(slot.khr_instances); - recycle_khr_as_queries(slot.khr_as_queries); - for (VkEvent event : slot.events) - if (context_.vk.vkResetEvent(context_.device(), event) == VK_SUCCESS) free_events_.push_back(event); - else context_.vk.vkDestroyEvent(context_.device(), event, nullptr); - slot.events.clear(); - if (!reuse) reuse = &slot; - } - return reuse; - } - - // A queue at the cap with nothing finished waits here for its oldest submission. execute_now() calls it before it - // takes resource_mutex_ or tracker_mutex_: the submission waited for may itself wait on another queue's work, and - // that queue needs those locks to submit it. One execute runs at a time on a queue, so buffers_ is this caller's. - // A timeout only means the GPU is slow: wait again rather than allocate past the cap. False when the device is lost - // (now or while waiting), so the caller submits nothing. - bool wait_for_room() { - for (;;) { - if (context_.is_device_lost()) return false; - if (buffers_.size() < kMaxQueuedCommandBuffers) return true; - const auto done = completed(); - for (const auto& slot : buffers_) - if (slot.ticket <= done) return true; - switch (wait_oldest_submitted()) { - case VK_SUCCESS: - return true; - case VK_TIMEOUT: - continue; - case VK_ERROR_DEVICE_LOST: - context_.mark_device_lost(); - return false; - default: - return true; // nothing submitted to wait for (or a host error): no wait can make room, allocate - } - } - } - - // Waits up to kQueuedWaitNs for the oldest submitted command buffer. VK_INCOMPLETE when none is submitted yet. - VkResult wait_oldest_submitted() { - std::uint64_t oldest = UINT64_MAX; - for (const auto& slot : buffers_) - if (slot.ticket < oldest) oldest = slot.ticket; - if (oldest == UINT64_MAX) return VK_INCOMPLETE; // all still being recorded - VkSemaphoreWaitInfo info{VK_STRUCTURE_TYPE_SEMAPHORE_WAIT_INFO}; - info.semaphoreCount = 1; - info.pSemaphores = &progress_; - info.pValues = &oldest; - return context_.vk.vkWaitSemaphores(context_.device(), &info, kQueuedWaitNs); - } - - CommandSlot* acquire() { - if (context_.is_device_lost()) return nullptr; - context_.drain_deleted_resources(context_.completed_retire_ticket()); - CommandSlot* reuse = recycle_finished(); - if (reuse) { - if (context_.vk.vkResetCommandBuffer(reuse->buffer, 0) != VK_SUCCESS) return nullptr; - reuse->predicate.reset(); - reuse->predicated_copy.reset(); - reuse->counted_dispatch.reset(); - reuse->ticket = UINT64_MAX; // in use until submitted - return reuse; - } - VkCommandBufferAllocateInfo info{VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO}; - info.commandPool = pool_; - info.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY; - info.commandBufferCount = 1; - VkCommandBuffer command_buffer = VK_NULL_HANDLE; - if (context_.vk.vkAllocateCommandBuffers(context_.device(), &info, &command_buffer) != VK_SUCCESS) - return nullptr; - buffers_.push_back({command_buffer, UINT64_MAX}); - return &buffers_.back(); - } - - // An unsignaled event for order_timestamp_copy, or null. MoltenVK decides when the command buffer is submitted - // whether a set or wait does anything, from the event's state then, so each use gets an event of its own. - VkEvent take_event() { - if (!free_events_.empty()) { - const VkEvent event = free_events_.back(); - free_events_.pop_back(); - return event; - } - VkEventCreateInfo info{VK_STRUCTURE_TYPE_EVENT_CREATE_INFO}; - VkEvent event = VK_NULL_HANDLE; - if (context_.vk.vkCreateEvent(context_.device(), &info, nullptr, &event) != VK_SUCCESS) return VK_NULL_HANDLE; - return event; - } - - bool submit(VkCommandBuffer command_buffer, VkSemaphore fence, std::uint64_t value) { - if (context_.is_device_lost()) return false; - const std::uint64_t ticket = submitted_ + 1; - if (last_sparse_) { - collect_bindings(completed()); - if (context_.is_device_lost()) return false; - } - std::span semaphores = waits_; - std::span values = wait_values_; - std::vector sparse_waits; - std::vector sparse_values; - if (last_sparse_) { - sparse_waits = waits_; - sparse_values = wait_values_; - sparse_waits.push_back(progress_); - sparse_values.push_back(last_sparse_); - semaphores = sparse_waits; - values = sparse_values; - } - const std::vector stages(semaphores.size(), VK_PIPELINE_STAGE_ALL_COMMANDS_BIT); - VkResult res = VK_SUCCESS; - { - std::lock_guard lock(context_.submit_mutex()); - VkSemaphore signals[2]{progress_, VK_NULL_HANDLE}; - std::uint64_t signal_values[2]{ticket, 0}; - std::uint32_t signal_count = 1; - // Decided under the submit lock, so the order of the checks is the order of the submissions. A Signal - // that is not above what was already submitted for this fence (a held Signal(F, 2) released after an - // unheld Signal(F, 3)) leaves the Vulkan signal out: the timeline cannot go down, and waits for 2 pass. - // The value counts as submitted only after the submit succeeded (below). - const bool signals_fence = fence && context_.holds().would_signal(fence, value); - if (signals_fence) { - signals[signal_count] = fence; - signal_values[signal_count] = value; - ++signal_count; - } - VkTimelineSemaphoreSubmitInfo timeline{VK_STRUCTURE_TYPE_TIMELINE_SEMAPHORE_SUBMIT_INFO}; - timeline.waitSemaphoreValueCount = std::uint32_t(values.size()); - timeline.pWaitSemaphoreValues = values.data(); - timeline.signalSemaphoreValueCount = signal_count; - timeline.pSignalSemaphoreValues = signal_values; - VkSubmitInfo submit{VK_STRUCTURE_TYPE_SUBMIT_INFO, &timeline}; - submit.waitSemaphoreCount = std::uint32_t(semaphores.size()); - submit.pWaitSemaphores = semaphores.data(); - submit.pWaitDstStageMask = stages.data(); - submit.commandBufferCount = command_buffer ? 1 : 0; - submit.pCommandBuffers = &command_buffer; - submit.signalSemaphoreCount = signal_count; - submit.pSignalSemaphores = signals; - res = context_.vk.vkQueueSubmit(queue_, 1, &submit, VK_NULL_HANDLE); - if (res == VK_SUCCESS) { - context_.record_submit_locked(progress_, ticket); - if (signals_fence) context_.holds().signaled(fence, value); - } - } - if (res == VK_ERROR_DEVICE_LOST) { - context_.mark_device_lost(); - clear_waits(); - return false; - } - const bool ok = (res == VK_SUCCESS); - if (ok) { - submitted_ = ticket; - clear_waits(ticket); - for (auto& slot : buffers_) - if (slot.buffer == command_buffer) slot.ticket = ticket; - } - return ok; - } - - VulkanContext& context_; - VkQueue queue_; - QueueKind kind_ = QueueKind::direct; - std::uint32_t family_; - VkCommandPool pool_ = VK_NULL_HANDLE; - VkSemaphore progress_ = VK_NULL_HANDLE; // our own timeline: which command buffers are done - std::uint64_t submitted_ = 0; - std::vector buffers_; - std::vector free_events_; // unsignaled, for order_timestamp_copy - std::unique_ptr occlusion_resolve_; - std::uint64_t storage_init_seen_ = 0; // the storage_init_version_ this queue has waited for - std::uint64_t bindless_upload_seen_ = 0; // the bindless_upload_version_ this queue has waited for - std::uint64_t last_sparse_ = 0; - std::deque pending_bindings_; - std::vector waits_; - std::vector wait_values_; - // execute's working storage. Per queue like buffers_: one execute at a time on a queue, as acquire() and - // submit() already assume; other queues prepare concurrently with their own. - std::vector prepared_; - std::uint32_t open_labels_ = 0; // queue labels begun and not ended - bool ok_ = false; - // Wait-before-Signal. state_mutex_ is outermost (before resource_mutex_ -> tracker_mutex_ -> submit_mutex_) and - // guards the members above that execute, signal, wait and marker touch. - std::mutex state_mutex_; - std::deque held_; - std::vector> wait_pins_; // keep the fences of waits_ alive - std::vector> retired_pins_; // released by the caller once state_mutex_ is dropped - struct TicketedPin { - std::uint64_t ticket; - std::shared_ptr pin; - }; - std::deque pin_queue_; // released once progress_ reaches the ticket - std::atomic held_failure_{0}; // a ReplayResult: the first held batch that failed -}; - -} // namespace leonida diff --git a/runtime/src/vulkan_bindless.h b/runtime/src/vulkan_bindless.h deleted file mode 100644 index cb5b61f65..000000000 --- a/runtime/src/vulkan_bindless.h +++ /dev/null @@ -1,1055 +0,0 @@ -#pragma once - -// The bindless descriptor set of translated shaders: set 0 of the contract in docs/design.md and -// docs/d3d12_vulkan.md section 5, as tools/rdna2spirv.py declares it. -// -// binding 0 sampled 2D images 4096 5 sampled 1D images 256 -// 1 samplers 1024 6 sampled 3D images 256 -// 2 the descriptor hash table 1 7 3D r32ui storage images 256 -// 3 sampled 2D-array images 1024 8 + 3 * dimension + class 256 each: -// 4 2D r32ui storage images 1024 storage images by component class -// dimension: 0 = 2D, 1 = 2D array, 2 = 3D, 3 = 1D (the translator's STORE_DIMS); class: 0 = float, 1 = uint, 2 = sint. -// bindings 20/21: sampled multisample 2D images / 2D arrays, 256 each (runtime SRVs). -// bindings 22/23 and 24/25 are their UINT and SINT equivalents on devices supporting those classes. -// These are the default counts (BindlessFeatures::counts). size_bindings() sizes the 2D, sampler and storage arrays -// from the device's limits instead; the shaders declare runtime arrays, so any count works for them. -// -// A shader turns a T# or S# into an index through the hash table (descriptor_table.h) and uses that index in -// whichever binding the instruction calls for: the sampled array of the image's dimension, or one of its storage -// arrays. So an image has one index, the same in every binding of its dimension, and each dimension has its own -// index space. The storage arrays are shorter (storage_capacity()), so an image with storage views gets an index -// they hold; one without takes a higher index while there is one. Index 0 of every array is a fallback, because a -// miss gives 0: a 1x1 image of zeros, a nearest clamping sampler, and 1x1 storage images. The caller owns the views -// and samplers it adds and keeps them alive while they are in the set; this class owns only the fallbacks and the -// table's buffer. -// -// Device features: runtimeDescriptorArray for the shaders. With BindlessFeatures::update_after_bind -// (descriptorBindingSampledImageUpdateAfterBind, ...StorageImage..., ...StorageBuffer...) flush() may run while -// command buffers that use the set are pending, as long as no descriptor they use changes and -// flush_replaces_table() is false; without it the caller flushes only when none is. When it is true the flush -// does not touch what pending work reads: it makes a new generation (table buffers and descriptor set, the -// descriptors copied from a CPU shadow) and retires the old one, which release_retired() frees once the owner -// says the submissions that could have used it are done (D3D-314). With partially_bound (descriptorBindingPartiallyBound) only index 0 is written at -// creation; otherwise every element of every array starts as the fallback. -// -// The table of binding 2 lives in DEVICE_LOCAL memory: every divergent T#/S# lookup reads it, and a HOST_VISIBLE -// table measured 19-46x slower there at 100k entries on an RTX 2060 SUPER (vk_descriptor_bench, D3D-56, #639). -// flush() takes the command buffer that will use the set: it uploads only the slots that changed, from a mapped -// staging buffer, and barriers the copy before the draws. The table at creation is empty until that first flush. -// -// Not thread-safe: the owner serialises calls. - -#ifndef VK_NO_PROTOTYPES -#define VK_NO_PROTOTYPES -#endif -#include "descriptor_table.h" - -#include - -#include -#include -#include -#include -#include -#include -#include - -namespace leonida { - -// The first four dimensions are the translator's STORE_DIMS indices. A cube is a 2D array of six layers. -enum class ImageDimension : std::uint32_t { dim_2d, dim_2d_array, dim_3d, dim_1d, dim_2d_ms, dim_2d_ms_array }; - -// Storage views of one image by the component type a shader reads or writes it with (the translator picks by the -// T# format at run time). r32ui is for the atomic instructions, whose image type is R32ui (2D and 3D only). -// A null view leaves the fallback in that binding. -struct StorageViews { - VkImageView as_float = VK_NULL_HANDLE; - VkImageView as_uint = VK_NULL_HANDLE; - VkImageView as_sint = VK_NULL_HANDLE; - VkImageView r32ui = VK_NULL_HANDLE; -}; - -namespace bindless { -inline constexpr std::uint32_t binding_count = 26; -constexpr std::array default_counts(); -} // namespace bindless - -struct BindlessFeatures { - bool update_after_bind = false; - bool partially_bound = false; - // Fallback sample counts for RGBA8_UNORM, R32_UINT, R32_SINT. A single sample omits that class's MS bindings. - std::array ms_samples{ - VK_SAMPLE_COUNT_1_BIT, VK_SAMPLE_COUNT_1_BIT, VK_SAMPLE_COUNT_1_BIT}; - // Descriptors in each binding, by binding number: bindless::bindings by default, or what size_bindings() chose. - std::array counts = bindless::default_counts(); -}; - -namespace bindless { - -struct Binding { - VkDescriptorType type; - std::uint32_t count; -}; - -inline constexpr std::uint32_t table_binding = 2; -inline constexpr std::uint32_t sampler_binding = 1; -inline constexpr std::uint32_t first_ms_binding = 20; -inline constexpr std::uint32_t no_binding = 0xffffffffu; - -// Indexed by binding number. -inline constexpr std::array bindings = {{ - {VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE, 4096}, {VK_DESCRIPTOR_TYPE_SAMPLER, 1024}, - {VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, 1}, {VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE, 1024}, - {VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, 1024}, {VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE, 256}, - {VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE, 256}, {VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, 256}, - {VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, 256}, {VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, 256}, - {VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, 256}, {VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, 256}, - {VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, 256}, {VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, 256}, - {VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, 256}, {VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, 256}, - {VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, 256}, {VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, 256}, - {VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, 256}, {VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, 256}, - {VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE, 256}, {VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE, 256}, - {VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE, 256}, {VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE, 256}, - {VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE, 256}, {VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE, 256}, -}}; - -static_assert(bindings.size() == binding_count); - -constexpr std::array default_counts() { - std::array counts{}; - for (std::uint32_t b = 0; b < binding_count; ++b) counts[b] = bindings[b].count; - return counts; -} - -constexpr bool binding_enabled(std::uint32_t binding, const BindlessFeatures& features) { - return binding < first_ms_binding || features.ms_samples[(binding - first_ms_binding) / 2] != VK_SAMPLE_COUNT_1_BIT; -} - -// Every binding is visible to every shader stage. Preserve the single-sample layout on devices whose -// per-stage or per-set limits have no room for additional pairs of MS arrays. -constexpr void limit_ms_bindings(BindlessFeatures& features, std::uint32_t sampled_limit, - std::uint32_t resource_limit) { - const auto& counts = features.counts; - std::uint32_t sampled = 0, total = 0; - for (std::uint32_t b = 0; b < first_ms_binding; ++b) { - if (bindings[b].type == VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE) sampled += counts[b]; - if (bindings[b].type != VK_DESCRIPTOR_TYPE_SAMPLER) total += counts[b]; - } - for (std::uint32_t c = 0; c < features.ms_samples.size(); ++c) { - if (features.ms_samples[c] == VK_SAMPLE_COUNT_1_BIT) continue; - const auto b = first_ms_binding + 2 * c; - const auto pair = counts[b] + counts[b + 1]; - if (sampled + pair > sampled_limit || total + pair > resource_limit) { - features.ms_samples[c] = VK_SAMPLE_COUNT_1_BIT; - } else { - sampled += pair; - total += pair; - } - } -} - -constexpr bool multisampled(ImageDimension dimension) { - return dimension == ImageDimension::dim_2d_ms || dimension == ImageDimension::dim_2d_ms_array; -} - -constexpr std::uint32_t sampled_binding(ImageDimension dimension, std::uint32_t component_class = 0) { - constexpr std::uint32_t by_dimension[] = {0, 3, 6, 5, first_ms_binding, first_ms_binding + 1}; - return by_dimension[std::uint32_t(dimension)] + (multisampled(dimension) ? component_class * 2 : 0); -} - -// component_class: 0 = float, 1 = uint, 2 = sint. -constexpr std::uint32_t storage_binding(ImageDimension dimension, std::uint32_t component_class) { - return multisampled(dimension) ? no_binding : 8 + 3 * std::uint32_t(dimension) + component_class; -} - -constexpr std::uint32_t r32ui_binding(ImageDimension dimension) { - return dimension == ImageDimension::dim_2d ? 4 : dimension == ImageDimension::dim_3d ? 7 : no_binding; -} - -// Set 0's descriptor set layout at features' counts: what create_layout creates and what size_bindings' -// layout_supported asks vkGetDescriptorSetLayoutSupport about. It points into itself, so it is not copied. -struct SetLayout { - std::array entries{}; - std::array flags{}; - VkDescriptorSetLayoutBindingFlagsCreateInfo flags_info{ - VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_BINDING_FLAGS_CREATE_INFO}; - VkDescriptorSetLayoutCreateInfo info{VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO}; - - explicit SetLayout(const BindlessFeatures& features) { - std::uint32_t count = 0; - for (std::uint32_t b = 0; b < binding_count; ++b) { - if (!binding_enabled(b, features)) continue; - entries[count] = {b, bindings[b].type, features.counts[b], VK_SHADER_STAGE_ALL, nullptr}; - flags[count] = (features.update_after_bind ? VK_DESCRIPTOR_BINDING_UPDATE_AFTER_BIND_BIT : 0) | - (features.partially_bound ? VK_DESCRIPTOR_BINDING_PARTIALLY_BOUND_BIT : 0); - ++count; - } - flags_info.bindingCount = count; - flags_info.pBindingFlags = flags.data(); - info.pNext = &flags_info; - info.flags = features.update_after_bind ? VK_DESCRIPTOR_SET_LAYOUT_CREATE_UPDATE_AFTER_BIND_POOL_BIT : 0; - info.bindingCount = count; - info.pBindings = entries.data(); - } - SetLayout(const SetLayout&) = delete; - SetLayout& operator=(const SetLayout&) = delete; -}; - -// What size_bindings() grows to where the device's limits allow. At 32-64 bytes a descriptor the whole set is then -// 3-6 MiB (93793 descriptors on an RTX 5070). -inline constexpr std::uint32_t max_2d_images = 65536; -inline constexpr std::uint32_t max_storage_indices = 4096; // in each storage array, at most its dimension's images -// A full D3D12 shader-visible sampler heap (2048) and room for literal and static S#s, within what the device can -// create (maxSamplerAllocationCount, at least 4000) less the samplers that are not in the set. -inline constexpr std::uint32_t max_samplers = 4096; -inline constexpr std::uint32_t reserved_samplers = 64; -// Growth leaves this many descriptors of each limit to the other sets of a pipeline layout. -inline constexpr std::uint32_t growth_headroom = 64; - -// Sizes the 2D image, sampler and storage arrays from the device's limits: the update-after-bind ones with -// features.update_after_bind, the plain ones otherwise. Every binding is visible to every stage, so the per-stage -// limits apply to the whole set; fragment outputs count as stage resources (D3D12 allows eight render targets) and -// standalone samplers do not, though they count in an update-after-bind pool. -// 1. The default counts, or as much of them as the device holds: samplers, then storage, then 2D images. -// 2. The MS pairs that fit beside them (limit_ms_bindings, which may turn classes off). -// 3. Growth towards the maximums above, in the same order, within maxPerSetDescriptors. That limit only says -// what is sure to work (vkGetDescriptorSetLayoutSupport may allow more), so it never shrinks step 1. -// A storage array holds the smaller of the storage count and its dimension's images: add_image never gives a -// storage view an index past the sampled array. The other bindings keep their default counts. -// layout_supported, when given, answers vkGetDescriptorSetLayoutSupport for set 0 at the counts in its argument: -// step 3 then also grows past maxPerSetDescriptors where the device says the layout works (Intel's Xe-LP reports -// 6159 and supports the full sizes, D3D-219). It is asked only once the sum is above maxPerSetDescriptors. -// Sets features.counts; returns false when a count is below its default because the device's limits are. -inline bool size_bindings(BindlessFeatures& features, const VkPhysicalDeviceLimits& limits, - const VkPhysicalDeviceVulkan11Properties& v11, - const VkPhysicalDeviceVulkan12Properties& v12, - const std::function& layout_supported = {}) { - const bool uab = features.update_after_bind; - const std::uint32_t sampled_limit = - uab ? std::min(v12.maxPerStageDescriptorUpdateAfterBindSampledImages, - v12.maxDescriptorSetUpdateAfterBindSampledImages) - : std::min(limits.maxPerStageDescriptorSampledImages, limits.maxDescriptorSetSampledImages); - const std::uint32_t sampler_limit = - uab ? std::min(v12.maxPerStageDescriptorUpdateAfterBindSamplers, v12.maxDescriptorSetUpdateAfterBindSamplers) - : std::min(limits.maxPerStageDescriptorSamplers, limits.maxDescriptorSetSamplers); - const std::uint32_t storage_limit = - uab ? std::min(v12.maxPerStageDescriptorUpdateAfterBindStorageImages, - v12.maxDescriptorSetUpdateAfterBindStorageImages) - : std::min(limits.maxPerStageDescriptorStorageImages, limits.maxDescriptorSetStorageImages); - std::uint32_t resource_limit = uab ? v12.maxPerStageUpdateAfterBindResources : limits.maxPerStageResources; - resource_limit -= std::min(resource_limit, std::min(limits.maxColorAttachments, 8u)); - const std::uint32_t pool_limit = uab ? v12.maxUpdateAfterBindDescriptorsInAllPools : 0xffffffffu; - - auto& counts = features.counts; - counts = default_counts(); - std::uint32_t images = 1, samplers = 1, storage = 1; - // Until the end the 2D storage arrays are not capped by the 2D images, which grow after them: capping can only - // take descriptors away. - const auto apply = [&](bool final) { - counts[sampled_binding(ImageDimension::dim_2d)] = images; - counts[sampler_binding] = samplers; - for (std::uint32_t d = 0; d < 4; ++d) { - const auto dimension = ImageDimension(d); - const bool capped = final || dimension != ImageDimension::dim_2d; - const std::uint32_t held = capped ? std::min(storage, counts[sampled_binding(dimension)]) : storage; - for (std::uint32_t c = 0; c < 3; ++c) counts[storage_binding(dimension, c)] = held; - if (r32ui_binding(dimension) != no_binding) counts[r32ui_binding(dimension)] = held; - } - }; - const auto fits = [&](std::uint32_t headroom, std::uint64_t set_limit) { - apply(false); - std::uint64_t sampled = 0, sampler = 0, stored = 0, buffers = 0; - for (std::uint32_t b = 0; b < binding_count; ++b) { - if (!binding_enabled(b, features)) continue; - const auto type = bindings[b].type; - (type == VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE ? sampled - : type == VK_DESCRIPTOR_TYPE_SAMPLER ? sampler - : type == VK_DESCRIPTOR_TYPE_STORAGE_IMAGE ? stored - : buffers) += counts[b]; - } - const auto within = [&](std::uint64_t n, std::uint32_t limit) { return n + headroom <= limit; }; - const std::uint64_t all = sampled + sampler + stored + buffers; - return within(sampled, sampled_limit) && within(sampler, sampler_limit) && within(stored, storage_limit) && - within(sampled + stored + buffers, resource_limit) && all <= pool_limit && - (all <= set_limit || (layout_supported && layout_supported(features))); - }; - // Raises n to the largest value up to `high` that fits; leaves it where it is when none does. - const auto grow = [&](std::uint32_t& n, std::uint32_t high, std::uint32_t headroom, std::uint64_t set_limit) { - std::uint32_t low = n; - while (low < high) { - n = low + (high - low + 1) / 2; - if (fits(headroom, set_limit)) low = n; - else high = n - 1; - } - n = low; - }; - - constexpr std::uint64_t no_limit = ~0ull; - const auto ms_samples = features.ms_samples; - features.ms_samples.fill(VK_SAMPLE_COUNT_1_BIT); - grow(samplers, bindings[sampler_binding].count, 0, no_limit); - grow(storage, bindings[storage_binding(ImageDimension::dim_2d, 0)].count, 0, no_limit); - grow(images, bindings[sampled_binding(ImageDimension::dim_2d)].count, 0, no_limit); - apply(false); - const bool full = images == bindings[0].count && samplers == bindings[sampler_binding].count && - storage == bindings[storage_binding(ImageDimension::dim_2d, 0)].count; - features.ms_samples = ms_samples; - limit_ms_bindings(features, sampled_limit, std::min(resource_limit, pool_limit - std::min(pool_limit, samplers))); - - std::uint64_t set_limit = 0; - for (std::uint32_t b = 0; b < binding_count; ++b) - if (binding_enabled(b, features)) set_limit += counts[b]; - set_limit = std::max(set_limit, std::uint64_t(v11.maxPerSetDescriptors)); - const std::uint32_t creatable = - limits.maxSamplerAllocationCount - std::min(limits.maxSamplerAllocationCount, reserved_samplers); - grow(samplers, std::max(samplers, std::min(max_samplers, creatable)), growth_headroom, set_limit); - grow(images, std::max(images, max_2d_images), growth_headroom, set_limit); - grow(storage, std::max(storage, max_storage_indices), growth_headroom, set_limit); - apply(true); - return full; -} - -} // namespace bindless - -class BindlessSet { -public: - BindlessSet(PFN_vkGetDeviceProcAddr get, VkDevice device, const VkPhysicalDeviceMemoryProperties& memory, - BindlessFeatures features = {}) - : device_(device), memory_(memory), features_(features) { - ok_ = vk_.load(get, device) && create_layout() && create_fallbacks() && create_table_buffers() && fill(); - } - - ~BindlessSet() { - release_retired(); - destroy(table_buffers_); - if (fallback_sampler_) vk_.vkDestroySampler(device_, fallback_sampler_, nullptr); - for (const VkImageView view : fallback_views_) vk_.vkDestroyImageView(device_, view, nullptr); - for (const auto& image : fallback_images_) { - if (image.image) vk_.vkDestroyImage(device_, image.image, nullptr); - if (image.memory) vk_.vkFreeMemory(device_, image.memory, nullptr); - } - if (pool_) vk_.vkDestroyDescriptorPool(device_, pool_, nullptr); // frees the set - if (layout_) vk_.vkDestroyDescriptorSetLayout(device_, layout_, nullptr); - } - - BindlessSet(const BindlessSet&) = delete; - BindlessSet& operator=(const BindlessSet&) = delete; - - bool ok() const { return ok_; } - bool supports_ms_class(std::uint32_t component_class) const { - return component_class < classes && features_.ms_samples[component_class] != VK_SAMPLE_COUNT_1_BIT; - } - // How many images of a dimension the set holds, the fallback included, and how many of the lowest of those - // indices its storage arrays hold (0 for the MS dimensions, which have none). The same for samplers. - std::uint32_t image_capacity(ImageDimension dimension) const { - return features_.counts[bindless::sampled_binding(dimension)]; - } - std::uint32_t storage_capacity(ImageDimension dimension) const { - return bindless::multisampled(dimension) ? 0 : features_.counts[bindless::storage_binding(dimension, 0)]; - } - std::uint32_t sampler_capacity() const { return features_.counts[bindless::sampler_binding]; } - // How many more images of a dimension, or samplers, add_image and add_sampler can take before they return 0. - std::uint32_t free_images(ImageDimension dimension) const { - const auto& used = image_used_[std::uint32_t(dimension)]; - return std::uint32_t(std::count(used.begin(), used.end(), std::uint8_t(0))); - } - std::uint32_t free_samplers() const { - return std::uint32_t(std::count(sampler_used_.begin(), sampler_used_.end(), std::uint8_t(0))); - } - // Set 0 of every pipeline layout made for translated shaders. - VkDescriptorSetLayout layout() const { return layout_; } - // Bound at set 0. flush() updates it in place until flush_replaces_table() is true: then the flush makes a new - // set (and table buffers), so read set() again after it, when recording the commands that use it. A submission - // that bound the previous set keeps it, intact, until release_retired() frees it. - VkDescriptorSet set() const { return set_; } - - // The fallback images are created with undefined contents: record this once, in a command buffer that executes - // before anything uses the set. It moves them to GENERAL, the layout their descriptors name, and zeroes them. - bool fallbacks_ready() const { return fallbacks_ready_; } - void record_fallback_init(VkCommandBuffer command_buffer) { - fallbacks_ready_ = true; - std::vector barriers; - for (const auto& image : fallback_images_) { - if (!image.image) continue; // unsupported multisample component class - VkImageMemoryBarrier barrier{VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER}; - barrier.dstAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT; - barrier.oldLayout = VK_IMAGE_LAYOUT_UNDEFINED; - barrier.newLayout = VK_IMAGE_LAYOUT_GENERAL; - barrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; - barrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; - barrier.image = image.image; - barrier.subresourceRange = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1}; - barriers.push_back(barrier); - } - vk_.vkCmdPipelineBarrier(command_buffer, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, 0, 0, - nullptr, 0, nullptr, std::uint32_t(barriers.size()), barriers.data()); - const VkClearColorValue zero{}; - for (const auto& barrier : barriers) - vk_.vkCmdClearColorImage(command_buffer, barrier.image, VK_IMAGE_LAYOUT_GENERAL, &zero, 1, - &barrier.subresourceRange); - VkMemoryBarrier done{VK_STRUCTURE_TYPE_MEMORY_BARRIER}; - done.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT; - done.dstAccessMask = VK_ACCESS_MEMORY_READ_BIT | VK_ACCESS_MEMORY_WRITE_BIT; - vk_.vkCmdPipelineBarrier(command_buffer, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, 0, 1, - &done, 0, nullptr, 0, nullptr); - } - - // Gives an image an index in its dimension's bindings: 0 when the dimension is full. `sampled` goes to the - // sampled array in `sampled_layout` (the layout the image is in when shaders read it); the storage views go to - // the storage arrays in GENERAL. For MS views, sampled_class selects the float, uint or sint sampled array. - // The caller maps the T# to the index with insert_key(). Takes effect at flush(). - std::uint32_t add_image(ImageDimension dimension, VkImageView sampled, VkImageLayout sampled_layout, - const StorageViews& storage = {}, std::uint32_t sampled_class = 0) { - const bool stores = storage.as_float || storage.as_uint || storage.as_sint || storage.r32ui; - if (bindless::multisampled(dimension) && (stores || !supports_ms_class(sampled_class))) return 0; - auto& used = image_used_[std::uint32_t(dimension)]; - const std::uint32_t low_end = std::min(std::uint32_t(used.size()), storage_capacity(dimension)); - std::uint32_t index = stores ? 0 : allocate(used, low_end, std::uint32_t(used.size())); - if (!index) index = allocate(used, 1, low_end); - if (index) write_image(dimension, index, sampled, sampled_layout, storage, sampled_class); - return index; - } - - // New views or a new layout for an index add_image returned (a texture's state changed, say). - void update_image(ImageDimension dimension, std::uint32_t index, VkImageView sampled, VkImageLayout sampled_layout, - const StorageViews& storage = {}, std::uint32_t sampled_class = 0) { - const auto& used = image_used_[std::uint32_t(dimension)]; - if (index && index < used.size() && used[index]) - write_image(dimension, index, sampled, sampled_layout, storage, sampled_class); - } - - // Returns the index to the fallback and frees it. The caller removes the image's keys with erase_key() first. - void remove_image(ImageDimension dimension, std::uint32_t index) { - auto& used = image_used_[std::uint32_t(dimension)]; - if (!index || index >= used.size() || !used[index]) return; - write_image(dimension, index, VK_NULL_HANDLE, VK_IMAGE_LAYOUT_GENERAL, {}, 0); - used[index] = 0; - } - - // 0 when the sampler array is full. - std::uint32_t add_sampler(VkSampler sampler) { - const std::uint32_t index = allocate(sampler_used_, 1, std::uint32_t(sampler_used_.size())); - if (index) write_sampler(index, sampler); - return index; - } - - void remove_sampler(std::uint32_t index) { - if (!index || index >= sampler_used_.size() || !sampler_used_[index]) return; - write_sampler(index, fallback_sampler_); - sampler_used_[index] = 0; - } - - // T# and S# keys to the indices above: the table of binding 2 (descriptor_table.h). Changes reach the shaders - // at flush(). - bool insert_key(const DescriptorKey& key, std::uint32_t index) { - const auto result = table_.insert_or_update(key.data(), index); - table_dirty_ |= result != DescriptorTable::InsertResult::unchanged; - existing_entries_changed_ |= result == DescriptorTable::InsertResult::replaced || - result == DescriptorTable::InsertResult::added_with_relocation; - return true; - } - // Erasing empties only the key's own slot; no other entry moves (DescriptorTable::erase), so it needs no idle. - // The caller erases a key once no submitted work uses it (its texture is gone), like D3D12 requires. - bool erase_key(const DescriptorKey& key) { - if (!table_.erase(key)) return false; - table_dirty_ = true; - return true; - } - const DescriptorTable& table() const { return table_; } - - // True when the next flush() would change entries a running shader may be probing (a live key's index replaced - // or a live key moved by a relocating insert), or replace the table's buffer. flush() then does not write in - // place: it uploads the whole table to new buffers, names them in a new descriptor set, and retires the old - // generation, so running work keeps reading an unchanged table and nobody waits for it. Without it the flush only - // adds entries or empties the slots of erased keys, and the copy of an entry is not atomic: a shader probing a - // different key could in principle see a torn entry that matches it, which is accepted as vanishingly unlikely - // because the added or erased key is not live (no running work uses it). - bool flush_replaces_table() const { - return table_dirty_ && (existing_entries_changed_ || force_full_upload_ || - table_.size_bytes() > table_buffers_.table.size); - } - - // True when the table's buffer was allocated in DEVICE_LOCAL memory (the fallback for a device without it is - // HOST_VISIBLE, which still works, just slower). - bool table_in_device_local_memory() const { return table_device_local_; } - - // True when the command buffer that carried the last table upload reached the queue; false keeps the upload - // obligation, and the next flush() rebuilds the whole table (the changed-slot list was consumed when the copy - // was recorded). A failed vkQueueSubmit is the caller's signal, not ours. - void table_upload_result(bool submitted) { - if (!upload_in_flight_) return; - upload_in_flight_ = false; - if (submitted) return; - table_dirty_ = true; - force_full_upload_ = true; - } - - // Writes the pending descriptor changes and uploads the table, in `command_buffer`, before the commands that use - // the set are recorded after it. When flush_replaces_table() was true this starts a new generation (table - // buffers, descriptor set, binding 2 and every descriptor written so far) and puts the previous one on the retire - // list, stamped `retire_ticket`: the owner's number for "every submission made so far", which release_retired() - // compares with what has completed. False when the new generation cannot be made: the set then still has the - // table as of the last flush. - bool flush(VkCommandBuffer command_buffer, std::uint64_t retire_ticket = 0) { - bool replaced = false; - bool written = true; - const bool must_replace = flush_replaces_table(); - if (table_dirty_ || !table_uploaded_) written = upload_table(command_buffer, retire_ticket, replaced); - last_flush_replaced_ = replaced; - // The new generation could not be made: the current set is the one running work reads, so its descriptors are - // not written in place either. The pending writes and the table's changes stay for the next flush. - if (!written && must_replace) return false; - for (const Pending& pending : pending_) { - if (pending.binding >= shadow_.size() || pending.index >= shadow_[pending.binding].size()) continue; - shadow_[pending.binding][pending.index] = pending.info; - shadow_written_[pending.binding][pending.index] = 1; - } - if (replaced) { - write_shadow(); // includes the pending writes just folded in - } else if (!pending_.empty()) { - std::vector writes(pending_.size()); - for (std::size_t i = 0; i < pending_.size(); ++i) { - writes[i] = {VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET}; - writes[i].dstSet = set_; - writes[i].dstBinding = pending_[i].binding; - writes[i].dstArrayElement = pending_[i].index; - writes[i].descriptorCount = 1; - writes[i].descriptorType = bindless::bindings[pending_[i].binding].type; - writes[i].pImageInfo = &pending_[i].info; - } - vk_.vkUpdateDescriptorSets(device_, std::uint32_t(writes.size()), writes.data(), 0, nullptr); - } - pending_.clear(); - pending_slots_.clear(); - return written; - } - - // Frees the generations (table buffers and descriptor set) that flush() retired with a ticket up to `completed`. - // The default frees all of them: when nothing submitted before the last flush() still runs. - void release_retired(std::uint64_t completed = UINT64_MAX) { - std::size_t kept = 0; - for (auto& generation : retired_) { - if (generation.ticket <= completed) { - destroy(generation.buffers); - if (generation.pool) vk_.vkDestroyDescriptorPool(device_, generation.pool, nullptr); - } else { - retired_[kept++] = generation; - } - } - retired_.resize(kept); - } - bool has_retired() const { return !retired_.empty(); } - // True when the last flush() started a new generation: its table upload is in that flush's command buffer, so - // work on other queues that binds the new set must run after it (the owner orders them). - bool last_flush_replaced() const { return last_flush_replaced_; } - // The ticket of the oldest retired generation (0 when there is none). - std::uint64_t oldest_retired_ticket() const { return retired_.empty() ? 0 : retired_.front().ticket; } - // How many generations flush() has made after the first, and how many wait for release_retired(). - std::uint64_t generations_made() const { return generations_made_; } - std::size_t retired_count() const { return retired_.size(); } - -private: - struct Functions { -#define LEONIDA_BINDLESS_FUNCTIONS(X) \ - X(vkCreateDescriptorSetLayout) X(vkDestroyDescriptorSetLayout) X(vkCreateDescriptorPool) \ - X(vkDestroyDescriptorPool) X(vkAllocateDescriptorSets) X(vkUpdateDescriptorSets) X(vkCreateBuffer) \ - X(vkDestroyBuffer) X(vkGetBufferMemoryRequirements) X(vkBindBufferMemory) X(vkAllocateMemory) \ - X(vkFreeMemory) X(vkMapMemory) X(vkCreateImage) X(vkDestroyImage) X(vkGetImageMemoryRequirements) \ - X(vkBindImageMemory) X(vkCreateImageView) X(vkDestroyImageView) X(vkCreateSampler) X(vkDestroySampler) \ - X(vkCmdPipelineBarrier) X(vkCmdCopyBuffer) X(vkCmdUpdateBuffer) X(vkCmdClearColorImage) -#define LEONIDA_BINDLESS_MEMBER(name) PFN_##name name = nullptr; - LEONIDA_BINDLESS_FUNCTIONS(LEONIDA_BINDLESS_MEMBER) -#undef LEONIDA_BINDLESS_MEMBER - - bool load(PFN_vkGetDeviceProcAddr get, VkDevice device) { - bool all = true; -#define LEONIDA_BINDLESS_LOAD(name) \ - name = reinterpret_cast(get(device, #name)); \ - all = all && name != nullptr; - LEONIDA_BINDLESS_FUNCTIONS(LEONIDA_BINDLESS_LOAD) -#undef LEONIDA_BINDLESS_LOAD -#undef LEONIDA_BINDLESS_FUNCTIONS - return all; - } - }; - - struct FallbackImage { - VkImage image = VK_NULL_HANDLE; - VkDeviceMemory memory = VK_NULL_HANDLE; - }; - - struct TableBuffer { - VkBuffer buffer = VK_NULL_HANDLE; - VkDeviceMemory memory = VK_NULL_HANDLE; - void* mapped = nullptr; - std::size_t size = 0; - }; - - // The table and the mapped staging copy the CPU writes before vkCmdCopyBuffer moves the changes. - struct TableBuffers { - TableBuffer table; // DEVICE_LOCAL when the device has it; what binding 2 names - TableBuffer staging; // HOST_VISIBLE | HOST_COHERENT - }; - - struct Pending { - std::uint32_t binding; - std::uint32_t index; - VkDescriptorImageInfo info; - }; - - static constexpr std::uint32_t dimensions = 6, classes = 3; - - // The first free index in [begin, end), marked used; 0 when there is none. - static std::uint32_t allocate(std::vector& used, std::uint32_t begin, std::uint32_t end) { - for (std::uint32_t i = begin; i < end; ++i) { - if (used[i]) continue; - used[i] = 1; - return i; - } - return 0; - } - - std::uint32_t memory_type(std::uint32_t allowed, VkMemoryPropertyFlags wanted) const { - for (std::uint32_t i = 0; i < memory_.memoryTypeCount; ++i) - if ((allowed & (1u << i)) && (memory_.memoryTypes[i].propertyFlags & wanted) == wanted) return i; - return 0xffffffffu; - } - - bool create_layout() { - const bindless::SetLayout layout(features_); - const std::uint32_t count = layout.info.bindingCount; - pool_size_count_ = count; - for (std::uint32_t i = 0; i < count; ++i) - pool_sizes_[i] = {layout.entries[i].descriptorType, layout.entries[i].descriptorCount}; - if (vk_.vkCreateDescriptorSetLayout(device_, &layout.info, nullptr, &layout_) != VK_SUCCESS) return false; - if (!make_set(pool_, set_)) return false; - for (std::uint32_t b = 0; b < bindless::bindings.size(); ++b) { - if (b == bindless::table_binding || !bindless::binding_enabled(b, features_)) continue; - shadow_[b].assign(features_.counts[b], VkDescriptorImageInfo{}); - shadow_written_[b].assign(features_.counts[b], 0); - } - - for (std::uint32_t d = 0; d < dimensions; ++d) { - image_used_[d].assign(image_capacity(ImageDimension(d)), 0); - image_used_[d][0] = 1; - } - sampler_used_.assign(sampler_capacity(), 0); - sampler_used_[0] = 1; - return true; - } - - // A one-set pool and its set at the layout's sizes: the first generation's, and each replacement's. - bool make_set(VkDescriptorPool& pool, VkDescriptorSet& set) const { - VkDescriptorPoolCreateInfo pool_info{VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO}; - pool_info.flags = features_.update_after_bind ? VK_DESCRIPTOR_POOL_CREATE_UPDATE_AFTER_BIND_BIT : 0; - pool_info.maxSets = 1; - pool_info.poolSizeCount = pool_size_count_; - pool_info.pPoolSizes = pool_sizes_.data(); - if (vk_.vkCreateDescriptorPool(device_, &pool_info, nullptr, &pool) != VK_SUCCESS) { - pool = VK_NULL_HANDLE; - return false; - } - VkDescriptorSetAllocateInfo set_info{VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO}; - set_info.descriptorPool = pool; - set_info.descriptorSetCount = 1; - set_info.pSetLayouts = &layout_; - if (vk_.vkAllocateDescriptorSets(device_, &set_info, &set) == VK_SUCCESS) return true; - vk_.vkDestroyDescriptorPool(device_, pool, nullptr); - pool = VK_NULL_HANDLE; - set = VK_NULL_HANDLE; - return false; - } - - // Writes every descriptor written so far (the shadow) into the current set, one update per run of written - // elements: the set was just made, and unwritten elements stay unwritten, as partially_bound allows. - void write_shadow() const { - std::vector writes; - for (std::uint32_t b = 0; b < bindless::bindings.size(); ++b) { - const auto& written = shadow_written_[b]; - for (std::size_t i = 0; i < written.size();) { - if (!written[i]) { - ++i; - continue; - } - std::size_t end = i; - while (end < written.size() && written[end]) ++end; - VkWriteDescriptorSet write{VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET}; - write.dstSet = set_; - write.dstBinding = b; - write.dstArrayElement = std::uint32_t(i); - write.descriptorCount = std::uint32_t(end - i); - write.descriptorType = bindless::bindings[b].type; - write.pImageInfo = &shadow_[b][i]; - writes.push_back(write); - i = end; - } - } - if (!writes.empty()) - vk_.vkUpdateDescriptorSets(device_, std::uint32_t(writes.size()), writes.data(), 0, nullptr); - } - - // One 1x1 image for each image type and component class, and the views of them every binding needs. - bool create_fallbacks() { - // Each MS class shares one sampled-only fallback between its 2D and 2D-array views. - constexpr VkImageType types[] = {VK_IMAGE_TYPE_2D, VK_IMAGE_TYPE_3D, VK_IMAGE_TYPE_1D, VK_IMAGE_TYPE_2D}; - constexpr std::uint32_t ms_type = 3; - constexpr VkFormat formats[classes] = {VK_FORMAT_R8G8B8A8_UNORM, VK_FORMAT_R32_UINT, VK_FORMAT_R32_SINT}; - // dimension -> (index into types, view type) - constexpr std::uint32_t type_of[dimensions] = {0, 0, 1, 2, ms_type, ms_type}; - constexpr VkImageViewType view_types[dimensions] = {VK_IMAGE_VIEW_TYPE_2D, VK_IMAGE_VIEW_TYPE_2D_ARRAY, - VK_IMAGE_VIEW_TYPE_3D, VK_IMAGE_VIEW_TYPE_1D, - VK_IMAGE_VIEW_TYPE_2D, VK_IMAGE_VIEW_TYPE_2D_ARRAY}; - for (std::uint32_t t = 0; t < std::size(types); ++t) { - for (std::uint32_t c = 0; c < classes; ++c) { - if (t == ms_type && !supports_ms_class(c)) continue; - VkImageCreateInfo info{VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO}; - info.imageType = types[t]; - info.format = formats[c]; - info.extent = {1, 1, 1}; - info.mipLevels = 1; - info.arrayLayers = 1; - info.samples = t == ms_type ? features_.ms_samples[c] : VK_SAMPLE_COUNT_1_BIT; - info.usage = VK_IMAGE_USAGE_TRANSFER_DST_BIT; - if (t != ms_type) info.usage |= VK_IMAGE_USAGE_STORAGE_BIT; - if (t == ms_type || c == 0) info.usage |= VK_IMAGE_USAGE_SAMPLED_BIT; - FallbackImage& image = fallback_images_[t * classes + c]; - if (vk_.vkCreateImage(device_, &info, nullptr, &image.image) != VK_SUCCESS) return false; - VkMemoryRequirements requirements{}; - vk_.vkGetImageMemoryRequirements(device_, image.image, &requirements); - VkMemoryAllocateInfo allocation{VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO}; - allocation.allocationSize = requirements.size; - allocation.memoryTypeIndex = memory_type(requirements.memoryTypeBits, 0); - if (allocation.memoryTypeIndex == 0xffffffffu || - vk_.vkAllocateMemory(device_, &allocation, nullptr, &image.memory) != VK_SUCCESS || - vk_.vkBindImageMemory(device_, image.image, image.memory, 0) != VK_SUCCESS) - return false; - } - } - for (std::uint32_t d = 0; d < dimensions; ++d) { - const ImageDimension dimension{d}; - for (std::uint32_t c = 0; c < classes; ++c) { - VkImageViewCreateInfo info{VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO}; - info.image = fallback_images_[type_of[d] * classes + c].image; - if (!info.image) continue; - info.viewType = view_types[d]; - info.format = formats[c]; - info.subresourceRange = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1}; - VkImageView view = VK_NULL_HANDLE; - if (vk_.vkCreateImageView(device_, &info, nullptr, &view) != VK_SUCCESS) return false; - fallback_views_.push_back(view); - if (c == 0 || bindless::multisampled(dimension)) - fallback_by_binding_[bindless::sampled_binding(dimension, c)] = view; - const auto storage_at = bindless::storage_binding(dimension, c); - if (storage_at != bindless::no_binding) fallback_by_binding_[storage_at] = view; - const auto r32ui_at = bindless::r32ui_binding(dimension); - if (c == 1 && r32ui_at != bindless::no_binding) fallback_by_binding_[r32ui_at] = view; - } - } - VkSamplerCreateInfo sampler{VK_STRUCTURE_TYPE_SAMPLER_CREATE_INFO}; - sampler.magFilter = sampler.minFilter = VK_FILTER_NEAREST; - sampler.mipmapMode = VK_SAMPLER_MIPMAP_MODE_NEAREST; - sampler.addressModeU = sampler.addressModeV = sampler.addressModeW = VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE; - sampler.maxLod = VK_LOD_CLAMP_NONE; - return vk_.vkCreateSampler(device_, &sampler, nullptr, &fallback_sampler_) == VK_SUCCESS; - } - - bool create(TableBuffer& out, std::size_t bytes, bool device_local, bool* got_device_local = nullptr) const { - VkBufferCreateInfo info{VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO}; - info.size = bytes; - info.usage = VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | - (device_local ? VK_BUFFER_USAGE_TRANSFER_DST_BIT : VK_BUFFER_USAGE_TRANSFER_SRC_BIT); - TableBuffer made; - made.size = bytes; - if (vk_.vkCreateBuffer(device_, &info, nullptr, &made.buffer) != VK_SUCCESS) return false; - VkMemoryRequirements requirements{}; - vk_.vkGetBufferMemoryRequirements(device_, made.buffer, &requirements); - VkMemoryAllocateInfo allocation{VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO}; - allocation.allocationSize = requirements.size; - allocation.memoryTypeIndex = - device_local ? memory_type(requirements.memoryTypeBits, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT) - : memory_type(requirements.memoryTypeBits, - VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT); - if (device_local && allocation.memoryTypeIndex == 0xffffffffu) - allocation.memoryTypeIndex = memory_type(requirements.memoryTypeBits, - VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | - VK_MEMORY_PROPERTY_HOST_COHERENT_BIT); - if (got_device_local) - *got_device_local = allocation.memoryTypeIndex != 0xffffffffu && - (memory_.memoryTypes[allocation.memoryTypeIndex].propertyFlags & - VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT) != 0; - bool ready = allocation.memoryTypeIndex != 0xffffffffu && - vk_.vkAllocateMemory(device_, &allocation, nullptr, &made.memory) == VK_SUCCESS && - vk_.vkBindBufferMemory(device_, made.buffer, made.memory, 0) == VK_SUCCESS; - if (ready && !device_local) - ready = vk_.vkMapMemory(device_, made.memory, 0, VK_WHOLE_SIZE, 0, &made.mapped) == VK_SUCCESS; - if (!ready) { - destroy(made); - return false; - } - out = made; - return true; - } - - void destroy(TableBuffer& buffer) const { - if (buffer.buffer) vk_.vkDestroyBuffer(device_, buffer.buffer, nullptr); - if (buffer.memory) vk_.vkFreeMemory(device_, buffer.memory, nullptr); // unmaps it - buffer = {}; - } - - void destroy(TableBuffers& buffers) const { - destroy(buffers.staging); - destroy(buffers.table); - } - - bool create_table_buffers() { - const std::size_t bytes = table_.size_bytes(); - TableBuffers made; - bool device_local = false; - if (!create(made.table, bytes, true, &device_local) || !create(made.staging, bytes, false)) { - destroy(made); - return false; - } - table_buffers_ = made; - table_device_local_ = device_local; - table_uploaded_ = false; // the first flush() uploads it, in the command buffer that will use it - table_dirty_ = existing_entries_changed_ = false; - return true; - } - - // Uploads what changed since the last call: the whole table when it grew (the mask moved) or was never uploaded, - // the changed slots otherwise. The copy and its barrier go into `command_buffer`, before the draws. - bool upload_table(VkCommandBuffer command_buffer, std::uint64_t retire_ticket, bool& replaced) { - if (!command_buffer) return false; - const std::size_t bytes = table_.size_bytes(); - // A table that grew, or whose live entries change, goes to a new generation; the old one may still be read. - const bool replace = bytes > table_buffers_.table.size || - (table_uploaded_ && (existing_entries_changed_ || force_full_upload_)); - bool full = force_full_upload_ || !table_uploaded_ || replace; - if (replace) { - TableBuffers larger; - VkDescriptorPool pool = VK_NULL_HANDLE; - VkDescriptorSet set = VK_NULL_HANDLE; - bool device_local = false; - if (!create(larger.table, bytes, true, &device_local) || !create(larger.staging, bytes, false) || - !make_set(pool, set)) { - destroy(larger); - return false; - } - table_device_local_ = device_local; - retired_.push_back({table_buffers_, pool_, set_, retire_ticket}); - table_buffers_ = larger; - pool_ = pool; - set_ = set; - write_table_binding(table_buffers_.table.buffer); - replaced = true; - ++generations_made_; - } - DescriptorTable::Changes changes = table_.take_changes(); - full = full || changes.all; - bool recorded = false; - // The staging buffer is written only for buffers that were just created (first upload or growth): a later - // flush then either updates slots with vkCmdUpdateBuffer or rebuilds from a fresh pair, so no copy still in - // flight can be reading bytes the CPU rewrites. - const bool fresh = replace || !table_uploaded_; - const auto upload_all = [&]() { - if (fresh) { - table_.write_to_buffer(table_buffers_.staging.mapped); - copy_table_range(command_buffer, 0, bytes); - } else { - const std::vector words = table_.build_gpu_buffer(); - update_table_range(command_buffer, 0, words.data(), bytes); - } - recorded = true; - }; - if (full) { - upload_all(); - } else if (!changes.slots.empty()) { - std::vector slots = std::move(changes.slots); - std::sort(slots.begin(), slots.end()); - slots.erase(std::unique(slots.begin(), slots.end()), slots.end()); - std::vector words; - bool staged = true; - for (std::size_t first = 0; staged && first < slots.size();) { - std::size_t last = first; - while (last + 1 < slots.size() && slots[last + 1] == slots[last] + 1) ++last; - const std::uint32_t count = std::uint32_t(last - first + 1); - words.resize(std::size_t(count) * 10); - staged = table_.read_slots(slots[first], count, words.data()); - if (staged) { - update_table_range(command_buffer, entry_offset(slots[first]), words.data(), - VkDeviceSize(words.size() * sizeof(std::uint32_t))); - recorded = true; - } - first = last + 1; - } - if (!staged) upload_all(); // an inconsistent slot list: the whole table is still correct - } - if (!recorded) return true; // nothing was copied: keep the obligation for the next flush - record_table_barrier(command_buffer); - upload_in_flight_ = true; - table_dirty_ = existing_entries_changed_ = false; - table_uploaded_ = true; - force_full_upload_ = false; - return true; - } - - // Copies the data into the command buffer while recording (64 KiB per call, the Vulkan limit), so no staging - // buffer is read at execution: a later flush can rewrite its own staging without racing a pending copy. - void update_table_range(VkCommandBuffer command_buffer, VkDeviceSize offset, const void* data, - VkDeviceSize size) const { - constexpr VkDeviceSize max_chunk = 65536; - const auto* bytes = static_cast(data); - for (VkDeviceSize done = 0; done < size; done += max_chunk) { - const VkDeviceSize chunk = std::min(max_chunk, size - done); - vk_.vkCmdUpdateBuffer(command_buffer, table_buffers_.table.buffer, offset + done, chunk, bytes + done); - } - } - - void copy_table_range(VkCommandBuffer command_buffer, VkDeviceSize offset, VkDeviceSize size) const { - const VkBufferCopy region{offset, offset, size}; - vk_.vkCmdCopyBuffer(command_buffer, table_buffers_.staging.buffer, table_buffers_.table.buffer, 1, ®ion); - } - - void record_table_barrier(VkCommandBuffer command_buffer) const { - VkBufferMemoryBarrier barrier{VK_STRUCTURE_TYPE_BUFFER_MEMORY_BARRIER}; - barrier.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT; - barrier.dstAccessMask = VK_ACCESS_SHADER_READ_BIT; - barrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; - barrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; - barrier.buffer = table_buffers_.table.buffer; - barrier.offset = 0; - barrier.size = VK_WHOLE_SIZE; - vk_.vkCmdPipelineBarrier(command_buffer, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, 0, 0, - nullptr, 1, &barrier, 0, nullptr); - } - - // The entry's first dword after the mask word; each entry is 10 dwords (40 bytes). - static constexpr VkDeviceSize entry_bytes = 10 * sizeof(std::uint32_t); - static VkDeviceSize entry_offset(std::uint32_t slot) { - return sizeof(std::uint32_t) + VkDeviceSize(slot) * entry_bytes; - } - - void write_table_binding(VkBuffer buffer) const { - const VkDescriptorBufferInfo info{buffer, 0, VK_WHOLE_SIZE}; - VkWriteDescriptorSet write{VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET}; - write.dstSet = set_; - write.dstBinding = bindless::table_binding; - write.descriptorCount = 1; - write.descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER; - write.pBufferInfo = &info; - vk_.vkUpdateDescriptorSets(device_, 1, &write, 0, nullptr); - } - - VkDescriptorImageInfo fallback_info(std::uint32_t binding) const { - if (binding == bindless::sampler_binding) return {fallback_sampler_, VK_NULL_HANDLE, VK_IMAGE_LAYOUT_UNDEFINED}; - return {VK_NULL_HANDLE, fallback_by_binding_[binding], VK_IMAGE_LAYOUT_GENERAL}; - } - - // The table at binding 2 and the fallback at index 0 of every array, or in every element without partially_bound. - bool fill() { - write_table_binding(table_buffers_.table.buffer); - std::vector> infos; - std::vector writes; - infos.reserve(bindless::bindings.size()); - for (std::uint32_t b = 0; b < bindless::bindings.size(); ++b) { - if (b == bindless::table_binding || !bindless::binding_enabled(b, features_)) continue; - const std::uint32_t count = features_.partially_bound ? 1 : features_.counts[b]; - infos.emplace_back(count, fallback_info(b)); - std::fill_n(shadow_[b].begin(), count, infos.back()[0]); - std::fill_n(shadow_written_[b].begin(), count, std::uint8_t(1)); - VkWriteDescriptorSet write{VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET}; - write.dstSet = set_; - write.dstBinding = b; - write.descriptorCount = count; - write.descriptorType = bindless::bindings[b].type; - write.pImageInfo = infos.back().data(); - writes.push_back(write); - } - vk_.vkUpdateDescriptorSets(device_, std::uint32_t(writes.size()), writes.data(), 0, nullptr); - return true; - } - - // A slot has one pending write: a later one takes its place. So a view or sampler that is removed before the - // next flush(), and may be destroyed by then, is never written. - void queue(std::uint32_t binding, std::uint32_t index, const VkDescriptorImageInfo& info) { - const std::uint64_t slot = (std::uint64_t(binding) << 32) | index; - const auto [at, added] = pending_slots_.try_emplace(slot, pending_.size()); - if (added) - pending_.push_back({binding, index, info}); - else - pending_[at->second].info = info; - } - - void write_sampler(std::uint32_t index, VkSampler sampler) { - queue(bindless::sampler_binding, index, {sampler, VK_NULL_HANDLE, VK_IMAGE_LAYOUT_UNDEFINED}); - } - - // Queues every binding of the dimension at `index`: the given views, or the fallback where one is null. - void write_image(ImageDimension dimension, std::uint32_t index, VkImageView sampled, VkImageLayout sampled_layout, - const StorageViews& storage, std::uint32_t sampled_class) { - if (bindless::multisampled(dimension)) { - for (std::uint32_t c = 0; c < classes; ++c) { - if (!supports_ms_class(c)) continue; - const auto binding = bindless::sampled_binding(dimension, c); - queue(binding, index, c == sampled_class && sampled - ? VkDescriptorImageInfo{VK_NULL_HANDLE, sampled, sampled_layout} - : fallback_info(binding)); - } - return; - } - const std::uint32_t sampled_at = bindless::sampled_binding(dimension); - queue(sampled_at, index, - sampled ? VkDescriptorImageInfo{VK_NULL_HANDLE, sampled, sampled_layout} : fallback_info(sampled_at)); - const auto store = [&](std::uint32_t binding, VkImageView view) { - if (binding == bindless::no_binding || index >= features_.counts[binding]) return; - queue(binding, index, - view ? VkDescriptorImageInfo{VK_NULL_HANDLE, view, VK_IMAGE_LAYOUT_GENERAL} : fallback_info(binding)); - }; - store(bindless::storage_binding(dimension, 0), storage.as_float); - store(bindless::storage_binding(dimension, 1), storage.as_uint); - store(bindless::storage_binding(dimension, 2), storage.as_sint); - store(bindless::r32ui_binding(dimension), storage.r32ui); - } - - VkDevice device_; - VkPhysicalDeviceMemoryProperties memory_; - BindlessFeatures features_; - Functions vk_; - bool ok_ = false; - VkDescriptorSetLayout layout_ = VK_NULL_HANDLE; - VkDescriptorPool pool_ = VK_NULL_HANDLE; - VkDescriptorSet set_ = VK_NULL_HANDLE; - std::array fallback_images_{}; // [2D, 3D, 1D, 2D MS][class] - std::vector fallback_views_; - std::array fallback_by_binding_{}; - VkSampler fallback_sampler_ = VK_NULL_HANDLE; - bool fallbacks_ready_ = false; - std::array, dimensions> image_used_; - std::vector sampler_used_; - std::vector pending_; - std::unordered_map pending_slots_; // binding and index -> place in pending_ - DescriptorTable table_{64}; - TableBuffers table_buffers_; - bool table_uploaded_ = false; // the table's current contents are in table_buffers_.table - bool table_device_local_ = false; - bool table_dirty_ = false; // the table differs from the buffer - bool existing_entries_changed_ = false; // ... and not only by entries added - bool upload_in_flight_ = false; // a copy is recorded, not yet known to have reached the queue - bool force_full_upload_ = false; // the last submit failed: rebuild the whole table on the next flush - struct Generation { // what a replaced table leaves for release_retired() - TableBuffers buffers; - VkDescriptorPool pool = VK_NULL_HANDLE; // owns the descriptor set - VkDescriptorSet set = VK_NULL_HANDLE; - std::uint64_t ticket = 0; - }; - std::vector retired_; - std::uint64_t generations_made_ = 0; - bool last_flush_replaced_ = false; - std::array pool_sizes_{}; - std::uint32_t pool_size_count_ = 0; - // Every descriptor written to the set (the table's binding aside), to fill the next generation's set. - std::array, bindless::bindings.size()> shadow_; - std::array, bindless::bindings.size()> shadow_written_; -}; - -} // namespace leonida diff --git a/runtime/src/vulkan_depth24.h b/runtime/src/vulkan_depth24.h deleted file mode 100644 index 988b79d9f..000000000 --- a/runtime/src/vulkan_depth24.h +++ /dev/null @@ -1,369 +0,0 @@ -// Also the repack of 96-bit R32G32B32 texels, held in R32G32B32A32 images (Depth24Job::rgb96, D3D-62): the same -// scratch, parts and lifetime, with texels of three words in the footprint and four in the scratch. -// -// The compute pass behind D24_UNORM_S8_UINT on a GPU without D24 (depth24.h, depth24_convert.comp). A copy between a -// footprint and the depth aspect of such a texture goes through a scratch buffer of floats: an upload converts the -// footprint's words into the scratch and a copy command moves the scratch into the image; a readback copies the image -// into the scratch and the pass converts it into the footprint. Single-threaded: the caller holds the context's lock. -#pragma once - -#ifndef VK_NO_PROTOTYPES -#define VK_NO_PROTOTYPES -#endif -#include - -#include -#include -#include -#include -#include - -#include "depth24.h" -#include "depth24_convert_spv.h" - -namespace leonida { - -class Depth24Converter { -public: - // A device-local allocation for the scratch buffers; null on failure. - using Allocate = std::function; - - // `max_range`: the device's maxStorageBufferRange; a copy is split into dispatches that stay inside it. - Depth24Converter(PFN_vkGetDeviceProcAddr get, VkDevice device, Allocate allocate, std::uint64_t max_range = 1u << 27) - : device_(device), allocate_(std::move(allocate)), max_range_(max_range) { - loaded_ = vk_.load(get, device); - } - - ~Depth24Converter() { - if (!loaded_) return; - vk_.vkDeviceWaitIdle(device_); - release(current_); - for (auto& batch : retired_) release(batch); - for (auto& chunk : spare_) destroy(chunk); - if (pipeline_) vk_.vkDestroyPipeline(device_, pipeline_, nullptr); - if (pipeline_layout_) vk_.vkDestroyPipelineLayout(device_, pipeline_layout_, nullptr); - if (set_layout_) vk_.vkDestroyDescriptorSetLayout(device_, set_layout_, nullptr); - } - - Depth24Converter(const Depth24Converter&) = delete; - Depth24Converter& operator=(const Depth24Converter&) = delete; - - bool loaded() const { return loaded_; } - - // Everything the next submission needs for a copy: the pipeline (once), a tightly packed scratch region for the - // whole copy (unless `whole` brings its own scratch buffer, as a test does; its scratch_offset is then the region's - // start) and the dispatches, `parts`, each with a descriptor set over windows of the application's buffer and the - // scratch. A part covers as many slices as fit one storage buffer range, or rows of one slice when a slice alone is - // larger, so no copy is too big for the device. `whole.scratch` and `whole.scratch_offset` tell the copy where - // the floats are. - bool prepare(Depth24Job& whole, std::vector& parts) { - // A row of the footprint is `aw` words wide and a row of the scratch `sw` (a texel is one word of each for - // D24, three and four for 96-bit texels). - const std::uint64_t aw = std::uint64_t(whole.width) * whole.app_texel_words(); - const std::uint64_t sw = std::uint64_t(whole.width) * whole.scratch_texel_words(); - if (!loaded_ || !make_pipeline() || !whole.app || !whole.width || !whole.height || !whole.slices || - whole.app_offset % 4 || whole.app_row_words < aw || - whole.app_slice_words < std::uint64_t(whole.app_row_words) * (whole.height - 1) + aw) - return false; - const std::uint64_t h = whole.height, s = whole.slices; - const std::uint64_t span_words = (s - 1) * whole.app_slice_words + (h - 1) * whole.app_row_words + aw; - if (whole.app_offset + span_words * 4 > whole.app_size) return false; - if (!whole.scratch && !scratch(sw * h * s * 4, whole.scratch, whole.scratch_offset)) return false; - - // A window starts at a multiple of 256 (the largest minStorageBufferOffsetAlignment), which costs up to 252 bytes. - constexpr std::uint64_t slack = 256; - const std::uint64_t limit = max_range_; - const auto app_bytes = [&](std::uint64_t slices, std::uint64_t rows) { - return ((slices - 1) * whole.app_slice_words + (rows - 1) * whole.app_row_words + aw) * 4 + slack; - }; - const auto scratch_bytes = [&](std::uint64_t slices, std::uint64_t rows) { return slices * rows * sw * 4 + slack; }; - std::uint64_t slices_per_part = 0; // 0: a slice alone is too big - while (slices_per_part < s && app_bytes(slices_per_part + 1, h) <= limit && scratch_bytes(slices_per_part + 1, h) <= limit) - ++slices_per_part; - std::uint64_t rows_per_part = h; - if (!slices_per_part) { - rows_per_part = 0; - while (rows_per_part < h && app_bytes(1, rows_per_part + 1) <= limit && scratch_bytes(1, rows_per_part + 1) <= limit) - ++rows_per_part; - if (!rows_per_part) return false; - } - parts.clear(); - for (std::uint64_t z = 0; z < s;) { - const std::uint64_t n = slices_per_part ? std::min(slices_per_part, s - z) : 1; - for (std::uint64_t y = 0; y < h; y += rows_per_part) { - const std::uint64_t rows = std::min(rows_per_part, h - y); - Depth24Job part = whole; - part.slices = std::uint32_t(n); - part.height = std::uint32_t(rows); - part.app_offset = whole.app_offset + (z * whole.app_slice_words + y * whole.app_row_words) * 4; - part.scratch_offset = whole.scratch_offset + ((z * h + y) * sw) * 4; - if (!make_part(part, whole.app_size)) return false; - parts.push_back(part); - } - z += n; - } - return true; - } - - - // Records the dispatch. The caller records the barriers around it. - void run(VkCommandBuffer command_buffer, const Depth24Job& job) const { - struct Push { - std::uint32_t width, height, slices, to_float, app_base, app_row, app_slice, scratch_base; - } push{job.width, job.height, job.slices, (job.to_float ? 1u : 0u) | (job.rgb96 ? 2u : 0u), job.app_base_words, - job.app_row_words, job.app_slice_words, job.scratch_base_words}; - vk_.vkCmdBindPipeline(command_buffer, VK_PIPELINE_BIND_POINT_COMPUTE, pipeline_); - vk_.vkCmdBindDescriptorSets(command_buffer, VK_PIPELINE_BIND_POINT_COMPUTE, pipeline_layout_, 0, 1, &job.set, 0, - nullptr); - vk_.vkCmdPushConstants(command_buffer, pipeline_layout_, VK_SHADER_STAGE_COMPUTE_BIT, 0, sizeof(push), &push); - vk_.vkCmdDispatch(command_buffer, (job.width + 7) / 8, (job.height + 7) / 8, job.slices); - } - - // The jobs prepared since the last call belong to a submission that `timeline` reaches `ticket` for. - void retire(VkSemaphore timeline, std::uint64_t ticket) { - if (current_.chunks.empty() && current_.pools.empty()) return; - current_.timeline = timeline; - current_.ticket = ticket; - retired_.push_back(std::move(current_)); - current_ = {}; - } - - // The submissions on `timeline` are over and the semaphore is about to go (its queue is idle). - void forget(VkSemaphore timeline) { - for (std::size_t i = 0; i < retired_.size();) { - if (retired_[i].timeline != timeline) { - ++i; - continue; - } - release(retired_[i]); - retired_.erase(retired_.begin() + std::ptrdiff_t(i)); - } - } - - // Frees (or keeps for reuse) what finished submissions used. - void collect() { - for (std::size_t i = 0; i < retired_.size();) { - if (retired_[i].ticket != 0) { - std::uint64_t done = 0; - if (!retired_[i].timeline || - vk_.vkGetSemaphoreCounterValue(device_, retired_[i].timeline, &done) != VK_SUCCESS || - done < retired_[i].ticket) { - ++i; - continue; - } - } - for (auto& chunk : retired_[i].chunks) { - chunk.used = 0; - if (spare_.size() < 4) spare_.push_back(chunk); - else destroy(chunk); - } - retired_[i].chunks.clear(); - release(retired_[i]); - retired_.erase(retired_.begin() + std::ptrdiff_t(i)); - } - } - -private: - struct Chunk { - VkBuffer buffer = VK_NULL_HANDLE; - VkDeviceMemory memory = VK_NULL_HANDLE; - VkDeviceSize size = 0, used = 0; - }; - struct Batch { - std::vector chunks; - std::vector pools; - VkSemaphore timeline = VK_NULL_HANDLE; - std::uint64_t ticket = 0; - }; - - struct Functions { -#define LEONIDA_DEPTH24_FUNCTIONS(X) \ - X(vkCreateShaderModule) X(vkDestroyShaderModule) X(vkCreateDescriptorSetLayout) \ - X(vkDestroyDescriptorSetLayout) X(vkCreatePipelineLayout) X(vkDestroyPipelineLayout) \ - X(vkCreateComputePipelines) X(vkDestroyPipeline) X(vkCreateDescriptorPool) X(vkDestroyDescriptorPool) \ - X(vkAllocateDescriptorSets) X(vkUpdateDescriptorSets) X(vkCreateBuffer) X(vkDestroyBuffer) \ - X(vkGetBufferMemoryRequirements) X(vkBindBufferMemory) X(vkFreeMemory) X(vkCmdBindPipeline) \ - X(vkCmdBindDescriptorSets) X(vkCmdPushConstants) X(vkCmdDispatch) X(vkGetSemaphoreCounterValue) \ - X(vkDeviceWaitIdle) -#define LEONIDA_DEPTH24_MEMBER(name) PFN_##name name = nullptr; - LEONIDA_DEPTH24_FUNCTIONS(LEONIDA_DEPTH24_MEMBER) -#undef LEONIDA_DEPTH24_MEMBER - - bool load(PFN_vkGetDeviceProcAddr get, VkDevice device) { - bool all = true; -#define LEONIDA_DEPTH24_LOAD(name) \ - name = reinterpret_cast(get(device, #name)); \ - all = all && name != nullptr; - LEONIDA_DEPTH24_FUNCTIONS(LEONIDA_DEPTH24_LOAD) -#undef LEONIDA_DEPTH24_LOAD -#undef LEONIDA_DEPTH24_FUNCTIONS - return all; - } - }; - - bool make_pipeline() { - if (pipeline_) return true; - VkDescriptorSetLayoutBinding bindings[2]{}; - for (std::uint32_t i = 0; i < 2; ++i) { - bindings[i].binding = i; - bindings[i].descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER; - bindings[i].descriptorCount = 1; - bindings[i].stageFlags = VK_SHADER_STAGE_COMPUTE_BIT; - } - VkDescriptorSetLayoutCreateInfo set_info{VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO}; - set_info.bindingCount = 2; - set_info.pBindings = bindings; - const VkPushConstantRange push{VK_SHADER_STAGE_COMPUTE_BIT, 0, 32}; - VkPipelineLayoutCreateInfo layout_info{VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO}; - layout_info.setLayoutCount = 1; - layout_info.pushConstantRangeCount = 1; - layout_info.pPushConstantRanges = &push; - VkShaderModuleCreateInfo module_info{VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO}; - module_info.codeSize = sizeof(depth24_convert_spirv); - module_info.pCode = depth24_convert_spirv; - VkShaderModule module = VK_NULL_HANDLE; - bool ok = vk_.vkCreateDescriptorSetLayout(device_, &set_info, nullptr, &set_layout_) == VK_SUCCESS; - layout_info.pSetLayouts = &set_layout_; - ok = ok && vk_.vkCreatePipelineLayout(device_, &layout_info, nullptr, &pipeline_layout_) == VK_SUCCESS && - vk_.vkCreateShaderModule(device_, &module_info, nullptr, &module) == VK_SUCCESS; - if (ok) { - VkComputePipelineCreateInfo info{VK_STRUCTURE_TYPE_COMPUTE_PIPELINE_CREATE_INFO}; - info.stage = {VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO, nullptr, 0, VK_SHADER_STAGE_COMPUTE_BIT, - module, "main", nullptr}; - info.layout = pipeline_layout_; - ok = vk_.vkCreateComputePipelines(device_, VK_NULL_HANDLE, 1, &info, nullptr, &pipeline_) == VK_SUCCESS; - } - if (module) vk_.vkDestroyShaderModule(device_, module, nullptr); - if (!ok) { // leave nothing half made; the next call tries again - if (pipeline_layout_) vk_.vkDestroyPipelineLayout(device_, pipeline_layout_, nullptr); - if (set_layout_) vk_.vkDestroyDescriptorSetLayout(device_, set_layout_, nullptr); - pipeline_layout_ = VK_NULL_HANDLE; - set_layout_ = VK_NULL_HANDLE; - } - return ok; - } - - // The descriptor set of one dispatch: windows of the application's buffer and of the scratch, each starting at - // a multiple of 256 bytes, with the part's first word given to the shader as a base. - bool make_part(Depth24Job& part, std::uint64_t app_size) { - constexpr std::uint64_t alignment = 256; - const std::uint64_t span = ((std::uint64_t(part.slices) - 1) * part.app_slice_words + - (std::uint64_t(part.height) - 1) * part.app_row_words + - std::uint64_t(part.width) * part.app_texel_words()) * 4; - const std::uint64_t window = part.app_offset / alignment * alignment; - const std::uint64_t range = part.app_offset - window + span; - const std::uint64_t tight = std::uint64_t(part.width) * part.scratch_texel_words() * part.height * part.slices * 4; - const std::uint64_t scratch_window = part.scratch_offset / alignment * alignment; - const std::uint64_t scratch_range = part.scratch_offset - scratch_window + tight; - if (window + range > app_size) return false; - part.app_base_words = std::uint32_t((part.app_offset - window) / 4); - part.scratch_base_words = std::uint32_t((part.scratch_offset - scratch_window) / 4); - part.set = allocate_set(); - if (!part.set) return false; - const VkDescriptorBufferInfo buffers[2] = {{part.app, window, range}, {part.scratch, scratch_window, scratch_range}}; - VkWriteDescriptorSet writes[2]{}; - for (std::uint32_t i = 0; i < 2; ++i) { - writes[i].sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET; - writes[i].dstSet = part.set; - writes[i].dstBinding = i; - writes[i].descriptorCount = 1; - writes[i].descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER; - writes[i].pBufferInfo = &buffers[i]; - } - vk_.vkUpdateDescriptorSets(device_, 2, writes, 0, nullptr); - return true; - } - - VkDescriptorSet allocate_set() { - for (int attempt = 0; attempt < 2; ++attempt) { - if (!current_.pools.empty()) { - VkDescriptorSetAllocateInfo info{VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO}; - info.descriptorPool = current_.pools.back(); - info.descriptorSetCount = 1; - info.pSetLayouts = &set_layout_; - VkDescriptorSet set = VK_NULL_HANDLE; - if (vk_.vkAllocateDescriptorSets(device_, &info, &set) == VK_SUCCESS) return set; - } - constexpr std::uint32_t sets = 64; - const VkDescriptorPoolSize size{VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, sets * 2}; - VkDescriptorPoolCreateInfo info{VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO}; - info.maxSets = sets; - info.poolSizeCount = 1; - info.pPoolSizes = &size; - VkDescriptorPool pool = VK_NULL_HANDLE; - if (vk_.vkCreateDescriptorPool(device_, &info, nullptr, &pool) != VK_SUCCESS) return VK_NULL_HANDLE; - current_.pools.push_back(pool); - } - return VK_NULL_HANDLE; - } - - // `bytes` of scratch, aligned for a descriptor offset, from this submission's chunks. - bool scratch(std::uint64_t bytes, VkBuffer& buffer, VkDeviceSize& offset) { - constexpr VkDeviceSize alignment = 256, minimum = 4u << 20; - for (auto& chunk : current_.chunks) { - const VkDeviceSize start = (chunk.used + alignment - 1) / alignment * alignment; - if (start + bytes <= chunk.size) { - chunk.used = start + bytes; - buffer = chunk.buffer; - offset = start; - return true; - } - } - Chunk chunk; - for (std::size_t i = 0; i < spare_.size(); ++i) - if (spare_[i].size >= bytes) { - chunk = spare_[i]; - spare_.erase(spare_.begin() + std::ptrdiff_t(i)); - break; - } - if (!chunk.buffer && !make_chunk(std::max(bytes, minimum), chunk)) return false; - chunk.used = bytes; - buffer = chunk.buffer; - offset = 0; - current_.chunks.push_back(chunk); - return true; - } - - bool make_chunk(std::uint64_t size, Chunk& out) { - VkBufferCreateInfo info{VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO}; - info.size = size; - info.usage = VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_SRC_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT; - if (vk_.vkCreateBuffer(device_, &info, nullptr, &out.buffer) != VK_SUCCESS) return false; - VkMemoryRequirements requirements{}; - vk_.vkGetBufferMemoryRequirements(device_, out.buffer, &requirements); - out.memory = allocate_ ? allocate_(requirements) : VK_NULL_HANDLE; - if (!out.memory || vk_.vkBindBufferMemory(device_, out.buffer, out.memory, 0) != VK_SUCCESS) { - destroy(out); - return false; - } - out.size = size; - return true; - } - - void destroy(Chunk& chunk) { - if (chunk.buffer) vk_.vkDestroyBuffer(device_, chunk.buffer, nullptr); - if (chunk.memory) vk_.vkFreeMemory(device_, chunk.memory, nullptr); - chunk = {}; - } - - void release(Batch& batch) { - for (auto& chunk : batch.chunks) destroy(chunk); - for (const auto pool : batch.pools) vk_.vkDestroyDescriptorPool(device_, pool, nullptr); - batch.chunks.clear(); - batch.pools.clear(); - } - - VkDevice device_; - Allocate allocate_; - std::uint64_t max_range_; - Functions vk_; - bool loaded_ = false; - VkDescriptorSetLayout set_layout_ = VK_NULL_HANDLE; - VkPipelineLayout pipeline_layout_ = VK_NULL_HANDLE; - VkPipeline pipeline_ = VK_NULL_HANDLE; - Batch current_; // prepared, not yet submitted - std::vector retired_; // submitted, waiting for the GPU - std::vector spare_; // finished scratch buffers kept for reuse -}; - -} // namespace leonida diff --git a/runtime/src/vulkan_device_filter.h b/runtime/src/vulkan_device_filter.h deleted file mode 100644 index 25d093140..000000000 --- a/runtime/src/vulkan_device_filter.h +++ /dev/null @@ -1,72 +0,0 @@ -#pragma once - -// LEONIDA_VK_DEVICE: which Vulkan GPU the runtime and its tests take on a machine with more than one. The value is -// part of the device name, compared without case ("5070", "radeon"); unset or empty takes every device, and the -// caller then picks by vulkan_device_rank (below) among the devices it can use. Several GPUs of one vendor share -// one driver, so the loader's own driver filters cannot tell them apart. A value that matches no device must fail -// the caller, not fall back, so a typo cannot silently test another GPU (as LEONIDA_HOST_ADAPTER does). - -#include -#include -#include -#include - -namespace leonida { - -// `text` as a filter: lower-cased, which is how it is compared with a device name. -inline std::string vulkan_device_filter_of(std::string text) { - for (char& c : text) c = char(std::tolower(static_cast(c))); - return text; -} - -// The filter from the variable alone, lower-cased; empty when unset. This is what the test harnesses and tools use, -// which load no settings file. The runtime's device takes the setting vulkan.device (the variable, else leonida.toml) -// and passes it to the two-argument vulkan_device_wanted below (shims/d3d12_vulkan_device.cpp). -inline std::string vulkan_device_filter() { -#ifdef _MSC_VER -#pragma warning(push) -#pragma warning(disable : 4996) // getenv: read at device selection only -#endif - const char* value = std::getenv("LEONIDA_VK_DEVICE"); -#ifdef _MSC_VER -#pragma warning(pop) -#endif - return vulkan_device_filter_of(value ? value : ""); -} - -// True when `device_name` (VkPhysicalDeviceProperties::deviceName) is wanted by `filter`, which is lower-cased -// (vulkan_device_filter_of); an empty filter takes every device. -inline bool vulkan_device_wanted(const char* device_name, const std::string& filter) { - if (filter.empty()) return true; - std::string name = device_name ? device_name : ""; - for (char& c : name) c = char(std::tolower(static_cast(c))); - return name.find(filter) != std::string::npos; -} - -// The same with the filter of the variable. -inline bool vulkan_device_wanted(const char* device_name) { - return vulkan_device_wanted(device_name, vulkan_device_filter()); -} - -// Microsoft is the vendor of the D3D12 translation layers Windows adds next to the real GPU (Mesa's Dozen from the -// "OpenCL, OpenGL and Vulkan Compatibility Pack", and the Basic Render Driver); no native GPU driver uses it. Dozen -// reports a discrete GPU, so "the last discrete device wins" took the wrapper over the native driver (#915). -inline constexpr std::uint32_t microsoft_vulkan_vendor_id = 0x1414; - -// How much a device is wanted, higher first: a native driver over Microsoft's layers, then discrete > integrated > -// virtual > CPU > other. `device_type` is VkPhysicalDeviceType (OTHER 0, INTEGRATED 1, DISCRETE 2, VIRTUAL 3, CPU 4; -// as an int so this header needs no Vulkan headers). The runtime and every test harness pick the first device with -// the highest rank among those they can use, so on a PC with two usable GPUs they take the same one. -inline int vulkan_device_rank(int device_type, std::uint32_t vendor_id) { - int type_rank = 0; - switch (device_type) { - case 2: type_rank = 4; break; // VK_PHYSICAL_DEVICE_TYPE_DISCRETE_GPU - case 1: type_rank = 3; break; // VK_PHYSICAL_DEVICE_TYPE_INTEGRATED_GPU - case 3: type_rank = 2; break; // VK_PHYSICAL_DEVICE_TYPE_VIRTUAL_GPU - case 4: type_rank = 1; break; // VK_PHYSICAL_DEVICE_TYPE_CPU - default: type_rank = 0; break; - } - return (vendor_id == microsoft_vulkan_vendor_id ? 0 : 10) + type_rank; -} - -} // namespace leonida diff --git a/runtime/src/vulkan_indirect_dispatch_count.h b/runtime/src/vulkan_indirect_dispatch_count.h deleted file mode 100644 index 510a4dcad..000000000 --- a/runtime/src/vulkan_indirect_dispatch_count.h +++ /dev/null @@ -1,200 +0,0 @@ -// GPU-only count gating for simple D3D12 ExecuteIndirect(DISPATCH) signatures. -// Vulkan has vkCmdDispatchIndirect but no vkCmdDispatchIndirectCount. We prepare a private indirect -// buffer with zero-group records past the GPU count, then execute all MaxCommandCount records. -#pragma once -#ifndef VK_NO_PROTOTYPES -#define VK_NO_PROTOTYPES -#endif -#include -#include -#include -#include -#include -#include -#include "indirect_dispatch_count_spv.h" -#include "vulkan_memory.h" - -namespace leonida { - -struct CountedDispatch { - VkBuffer indirect = VK_NULL_HANDLE; - VkDeviceSize offset = 0; - VkDeviceAddress arguments = 0; - VkDeviceAddress count = 0; - VkDeviceAddress output = 0; - std::uint32_t stride = 0; - std::uint32_t max_count = 0; -}; - -class IndirectDispatchCounter { -public: - IndirectDispatchCounter(PFN_vkGetDeviceProcAddr get, VkDevice device, - const VkPhysicalDeviceMemoryProperties& memory, const VkPhysicalDeviceLimits& limits) - : get_(get), device_(device), memory_(memory), limits_(limits) {} - ~IndirectDispatchCounter() { - if (pipeline_) fn("vkDestroyPipeline")(device_, pipeline_, nullptr); - if (layout_) fn("vkDestroyPipelineLayout")(device_, layout_, nullptr); - } - IndirectDispatchCounter(const IndirectDispatchCounter&) = delete; - IndirectDispatchCounter& operator=(const IndirectDispatchCounter&) = delete; - - // Retained by the command-buffer slot until its submission's timeline ticket completes. - struct Batch { - IndirectDispatchCounter& owner; - struct Allocation { - VkBuffer buffer = VK_NULL_HANDLE; - VkDeviceMemory memory = VK_NULL_HANDLE; - }; - std::vector allocations; - explicit Batch(IndirectDispatchCounter& value) : owner(value) {} - ~Batch() { - for (auto& a : allocations) { - if (a.buffer) owner.fn("vkDestroyBuffer")(owner.device_, a.buffer, nullptr); - if (a.memory) owner.fn("vkFreeMemory")(owner.device_, a.memory, nullptr); - } - } - Batch(const Batch&) = delete; - Batch& operator=(const Batch&) = delete; - - bool prepare(VkBuffer arguments, VkDeviceSize argument_offset, VkBuffer count, - VkDeviceSize count_offset, std::uint32_t stride, std::uint32_t max_count, - CountedDispatch& out) { - out = {}; - constexpr VkDeviceSize record_bytes = 3 * sizeof(std::uint32_t); - if (!arguments || !count || stride < record_bytes || stride % 4 || - (argument_offset % 4) != 0 || (count_offset % 4) != 0 || !max_count || - !owner.limits_.maxComputeWorkGroupCount[0] || !owner.make_pipeline()) return false; - if (VkDeviceSize(max_count) > std::numeric_limits::max() / record_bytes) - return false; - const VkDeviceSize bytes = VkDeviceSize(max_count) * record_bytes; - VkBufferCreateInfo info{VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO}; - info.size = bytes; - info.usage = VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | VK_BUFFER_USAGE_INDIRECT_BUFFER_BIT | - VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT; - Allocation scratch{}; - if (owner.fn("vkCreateBuffer")(owner.device_, &info, nullptr, &scratch.buffer) != VK_SUCCESS) - return false; - allocations.push_back(scratch); // all failure paths free it with the batch - auto& a = allocations.back(); - VkMemoryRequirements requirements{}; - owner.fn("vkGetBufferMemoryRequirements")( - owner.device_, a.buffer, &requirements); - const auto order = memory_type_order(owner.memory_, requirements.memoryTypeBits, 0, - VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, requirements.size); - if (order.empty()) return false; - VkMemoryAllocateFlagsInfo flags{VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_FLAGS_INFO}; - flags.flags = VK_MEMORY_ALLOCATE_DEVICE_ADDRESS_BIT; - VkMemoryAllocateInfo allocation{VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO, &flags}; - allocation.allocationSize = requirements.size; - const auto alloc_memory = owner.fn("vkAllocateMemory"); - for (const std::uint32_t memory_type : order) { - allocation.memoryTypeIndex = memory_type; - if (alloc_memory(owner.device_, &allocation, nullptr, &a.memory) == VK_SUCCESS) break; - a.memory = VK_NULL_HANDLE; - } - if (!a.memory || - owner.fn("vkBindBufferMemory")(owner.device_, a.buffer, a.memory, 0) != VK_SUCCESS) - return false; - const auto address = owner.fn("vkGetBufferDeviceAddress"); - VkBufferDeviceAddressInfo addr{VK_STRUCTURE_TYPE_BUFFER_DEVICE_ADDRESS_INFO}; - addr.buffer = arguments; - const VkDeviceAddress args_va = address(owner.device_, &addr); - addr.buffer = count; - const VkDeviceAddress count_va = address(owner.device_, &addr); - addr.buffer = a.buffer; - const VkDeviceAddress output_va = address(owner.device_, &addr); - if (!args_va || !count_va || !output_va || - argument_offset > UINT64_MAX - args_va || count_offset > UINT64_MAX - count_va) - return false; - out = {a.buffer, 0, args_va + argument_offset, count_va + count_offset, - output_va, stride, max_count}; - return true; - } - }; - - std::unique_ptr batch() { return std::make_unique(*this); } - - void emit(VkCommandBuffer cb, const CountedDispatch& job) const { - const auto barrier = fn("vkCmdPipelineBarrier"); - VkMemoryBarrier before{VK_STRUCTURE_TYPE_MEMORY_BARRIER}; - before.srcAccessMask = VK_ACCESS_MEMORY_WRITE_BIT; - before.dstAccessMask = VK_ACCESS_SHADER_READ_BIT; - barrier(cb, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, - 0, 1, &before, 0, nullptr, 0, nullptr); - fn("vkCmdBindPipeline")(cb, VK_PIPELINE_BIND_POINT_COMPUTE, pipeline_); - struct Push { - VkDeviceAddress arguments, count, output; - std::uint32_t stride_words, first_record, records; - }; - static_assert(sizeof(Push) == 40); - const VkDeviceSize dispatch_limit = VkDeviceSize(limits_.maxComputeWorkGroupCount[0]) * 64; - // Bound per-dispatch indexing to 32 bits, even when the D3D12 stride is very large. - // The shader loads and stores three consecutive dwords per record, so leave room for the final +2. - const std::uint32_t index_stride_words = std::max(3u, job.stride / 4); - const VkDeviceSize index_limit = (UINT32_MAX - 2u) / index_stride_words; - const VkDeviceSize chunk_limit = std::min(dispatch_limit, index_limit + 1); - for (VkDeviceSize first = 0; first < job.max_count;) { - const std::uint32_t count = std::uint32_t(std::min(chunk_limit, job.max_count - first)); - const Push push{job.arguments + first * job.stride, job.count, job.output + first * 12, - job.stride / 4, std::uint32_t(first), count}; - fn("vkCmdPushConstants")(cb, layout_, VK_SHADER_STAGE_COMPUTE_BIT, - 0, sizeof(push), &push); - fn("vkCmdDispatch")(cb, (count - 1u) / 64u + 1u, 1, 1); - first += count; - } - VkMemoryBarrier after{VK_STRUCTURE_TYPE_MEMORY_BARRIER}; - after.srcAccessMask = VK_ACCESS_SHADER_WRITE_BIT | VK_ACCESS_SHADER_READ_BIT; - after.dstAccessMask = VK_ACCESS_INDIRECT_COMMAND_READ_BIT | VK_ACCESS_MEMORY_READ_BIT | - VK_ACCESS_MEMORY_WRITE_BIT; - barrier(cb, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, - 0, 1, &after, 0, nullptr, 0, nullptr); - } - -private: - template T fn(const char* name) const { return reinterpret_cast(get_(device_, name)); } - bool make_pipeline() { - if (pipeline_) return true; - for (const char* name : {"vkCreateBuffer", "vkDestroyBuffer", "vkGetBufferMemoryRequirements", - "vkAllocateMemory", "vkFreeMemory", "vkBindBufferMemory", "vkGetBufferDeviceAddress", - "vkCreateShaderModule", "vkDestroyShaderModule", "vkCreatePipelineLayout", - "vkDestroyPipelineLayout", "vkCreateComputePipelines", "vkDestroyPipeline", - "vkCmdPipelineBarrier", "vkCmdBindPipeline", "vkCmdPushConstants", "vkCmdDispatch"}) - if (!get_(device_, name)) return false; - VkShaderModule module = VK_NULL_HANDLE; - VkPipelineLayout layout = VK_NULL_HANDLE; - VkPipeline pipeline = VK_NULL_HANDLE; - VkShaderModuleCreateInfo shader{VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO}; - shader.codeSize = sizeof(indirect_dispatch_count_spirv); - shader.pCode = indirect_dispatch_count_spirv; - bool ok = fn("vkCreateShaderModule")(device_, &shader, nullptr, &module) == VK_SUCCESS; - const VkPushConstantRange range{VK_SHADER_STAGE_COMPUTE_BIT, 0, 40}; - VkPipelineLayoutCreateInfo layout_info{VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO}; - layout_info.pushConstantRangeCount = 1; - layout_info.pPushConstantRanges = ⦥ - ok = ok && fn("vkCreatePipelineLayout")(device_, &layout_info, nullptr, &layout) == VK_SUCCESS; - VkComputePipelineCreateInfo info{VK_STRUCTURE_TYPE_COMPUTE_PIPELINE_CREATE_INFO}; - info.stage = {VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO}; - info.stage.stage = VK_SHADER_STAGE_COMPUTE_BIT; - info.stage.module = module; - info.stage.pName = "main"; - info.layout = layout; - ok = ok && fn("vkCreateComputePipelines")( - device_, VK_NULL_HANDLE, 1, &info, nullptr, &pipeline) == VK_SUCCESS; - if (module) fn("vkDestroyShaderModule")(device_, module, nullptr); - if (!ok) { - if (pipeline) fn("vkDestroyPipeline")(device_, pipeline, nullptr); - if (layout) fn("vkDestroyPipelineLayout")(device_, layout, nullptr); - return false; - } - layout_ = layout; - pipeline_ = pipeline; - return true; - } - PFN_vkGetDeviceProcAddr get_; - VkDevice device_; - VkPhysicalDeviceMemoryProperties memory_; - VkPhysicalDeviceLimits limits_; - VkPipelineLayout layout_ = VK_NULL_HANDLE; - VkPipeline pipeline_ = VK_NULL_HANDLE; -}; -} // namespace leonida diff --git a/runtime/src/vulkan_memory.h b/runtime/src/vulkan_memory.h deleted file mode 100644 index 08c764d33..000000000 --- a/runtime/src/vulkan_memory.h +++ /dev/null @@ -1,68 +0,0 @@ -#pragma once - -// Memory-type policy for the D3D12 layer that depends only on VkPhysicalDeviceMemoryProperties, so it can be checked -// without a GPU (d3d12_state_map_test) on the heap layouts real cards report. - -#ifndef VK_NO_PROTOTYPES -#define VK_NO_PROTOTYPES -#endif -#include - -#include -#include -#include - -namespace leonida { - -// Without Resizable BAR the CPU sees at most a 256 MiB window of VRAM: the DEVICE_LOCAL | HOST_VISIBLE type sits in a -// heap of that size or smaller (256 MiB on AMD and on RADV, 214 MiB on an RTX 3090 with driver 616.56). Anything -// larger is Resizable BAR (or Smart Access Memory), or a GPU whose memory is all device-local and host-visible. -inline constexpr VkDeviceSize kBarWindowBytes = VkDeviceSize(256) << 20; - -// True when the device has DEVICE_LOCAL | HOST_VISIBLE | HOST_COHERENT memory in a device-local heap larger than -// the 256 MiB BAR window (D3D-96): then CPU-written memory that the GPU reads, such as an upload heap, can live in -// VRAM without exhausting a small window that every such allocation would share. -inline bool resizable_bar(const VkPhysicalDeviceMemoryProperties& memory) { - constexpr VkMemoryPropertyFlags wanted = VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT | - VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | - VK_MEMORY_PROPERTY_HOST_COHERENT_BIT; - for (std::uint32_t i = 0; i < memory.memoryTypeCount && i < VK_MAX_MEMORY_TYPES; ++i) { - const VkMemoryType& type = memory.memoryTypes[i]; - if ((type.propertyFlags & wanted) != wanted || type.heapIndex >= memory.memoryHeapCount) continue; - const VkMemoryHeap& heap = memory.memoryHeaps[type.heapIndex]; - if ((heap.flags & VK_MEMORY_HEAP_DEVICE_LOCAL_BIT) && heap.size > kBarWindowBytes) return true; - } - return false; -} - -// The memory types to try for an allocation of `size` bytes, best first: those with `required | preferred`, then -// those with only `required`. A type whose heap is smaller than the allocation is left out, as the allocation would -// break VUID-vkAllocateMemory-pAllocateInfo-01713 (some drivers still return VK_SUCCESS). Without Resizable BAR the -// heap of DEVICE_LOCAL | HOST_VISIBLE memory is typically 256 MiB or less, so a larger host-visible allocation falls -// through to system memory. A heap that is big enough but already partly used is left to the driver: a failed -// vkAllocateMemory moves on to the next type. -inline std::vector memory_type_order(const VkPhysicalDeviceMemoryProperties& memory, - std::uint32_t type_bits, VkMemoryPropertyFlags required, - VkMemoryPropertyFlags preferred, VkDeviceSize size) { - std::vector order; - for (const VkMemoryPropertyFlags flags : {required | preferred, required}) { - for (std::uint32_t i = 0; i < memory.memoryTypeCount && i < VK_MAX_MEMORY_TYPES; ++i) { - const VkMemoryType& type = memory.memoryTypes[i]; - if (!(type_bits & (1u << i)) || (type.propertyFlags & flags) != flags) continue; - if (type.heapIndex >= memory.memoryHeapCount || memory.memoryHeaps[type.heapIndex].size < size) continue; - if (std::find(order.begin(), order.end(), i) == order.end()) order.push_back(i); - } - } - return order; -} - -// D3D-299: true when an allocation that preferred DEVICE_LOCAL without needing host access (a texture, a default-heap -// buffer outside the arena) got a type without it, so the GPU now reads it from system memory. A host-visible -// allocation (the arena, an upload heap) in system memory is the memory type policy without Resizable BAR, not this. -inline bool spilled_to_host(VkMemoryPropertyFlags required, VkMemoryPropertyFlags preferred, - VkMemoryPropertyFlags chosen) { - return (preferred & VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT) && !(required & VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT) && - !(chosen & VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT); -} - -} // namespace leonida diff --git a/runtime/src/vulkan_mesh_limits.h b/runtime/src/vulkan_mesh_limits.h deleted file mode 100644 index 0a288f90a..000000000 --- a/runtime/src/vulkan_mesh_limits.h +++ /dev/null @@ -1,54 +0,0 @@ -// The device limits a mesh pipeline must fit, checked before vkCreate*Pipelines (docs/d3d12_vulkan.md, "Pipelines"). -// Vulkan has no per-pipeline limit to set: a module whose output arrays, workgroup or shared memory are over the -// device's is invalid usage that spirv-val accepts and drivers die on (RADV, #1721, for compute), so the PSO is -// refused up front with the stage named. -#pragma once - -#include "shader_library.h" - -#include - -#include -#include -#include -#include - -namespace leonida { - -// Empty when the mesh entry fits the device's mesh-shader limits, else why not. `limits` is -// VkPhysicalDeviceMeshShaderPropertiesEXT as the device reports it, all zeros when it could not be asked. -// - output vertices and primitives, workgroup size and invocations: as before. -// - Workgroup memory (the entry's lds_bytes: the LDS array, %x_buf of --wave64-emulate and the mesh's own counter) -// against maxMeshSharedMemorySize, and against maxMeshPayloadAndSharedMemorySize, which bounds shared memory -// plus the task payload (the game has no amplification shaders, so the payload is 0). Mesh shared memory is a -// separate, smaller budget than maxComputeSharedMemorySize: 28672 on NVIDIA, while a compute shader may have 48 KiB. -// A limit of 0 means the properties were not read; the memory is not refused on a number nobody gave. -inline std::string mesh_limit_refusal(const ShaderEntry& entry, const VkPhysicalDeviceMeshShaderPropertiesEXT& limits) { - const auto& n = entry.local_size; - char text[384]; - if (entry.max_vertices > limits.maxMeshOutputVertices || entry.max_primitives > limits.maxMeshOutputPrimitives || - n[0] > limits.maxMeshWorkGroupSize[0] || n[1] > limits.maxMeshWorkGroupSize[1] || - n[2] > limits.maxMeshWorkGroupSize[2] || - std::uint64_t(n[0]) * n[1] * n[2] > limits.maxMeshWorkGroupInvocations) { - std::snprintf(text, sizeof text, - "%s needs %u vertices, %u primitives, %ux%ux%u threads; the device allows %u, %u, %u invocations", - entry.name.c_str(), entry.max_vertices, entry.max_primitives, n[0], n[1], n[2], - limits.maxMeshOutputVertices, limits.maxMeshOutputPrimitives, limits.maxMeshWorkGroupInvocations); - return text; - } - std::uint32_t shared_limit = limits.maxMeshSharedMemorySize; - if (limits.maxMeshPayloadAndSharedMemorySize) - shared_limit = shared_limit ? std::min(shared_limit, limits.maxMeshPayloadAndSharedMemorySize) - : limits.maxMeshPayloadAndSharedMemorySize; - if (entry.lds_bytes && shared_limit && entry.lds_bytes > shared_limit) { - std::snprintf(text, sizeof text, - "%s declares %u bytes of workgroup memory, over the device's mesh shared memory limit %u " - "(maxMeshSharedMemorySize %u, maxMeshPayloadAndSharedMemorySize %u)", - entry.name.c_str(), entry.lds_bytes, shared_limit, limits.maxMeshSharedMemorySize, - limits.maxMeshPayloadAndSharedMemorySize); - return text; - } - return {}; -} - -} // namespace leonida diff --git a/runtime/src/vulkan_predicate.h b/runtime/src/vulkan_predicate.h deleted file mode 100644 index cedb8af81..000000000 --- a/runtime/src/vulkan_predicate.h +++ /dev/null @@ -1,183 +0,0 @@ -// GPU snapshot of D3D12's 64-bit predicate. No host readback and no per-predicate queue wait. -#pragma once -#ifndef VK_NO_PROTOTYPES -#define VK_NO_PROTOTYPES -#endif -#include -#include -#include -#include -#include "predicate_reduce_spv.h" - -namespace leonida { -struct PredicateCapture { - VkBuffer source = VK_NULL_HANDLE; - VkDeviceSize source_offset = 0; - VkBuffer scratch = VK_NULL_HANDLE; - VkDeviceSize offset = 0; // two input words, then the reduced condition - VkDescriptorSet set = VK_NULL_HANDLE; -}; - -class PredicateReducer { -public: - PredicateReducer(PFN_vkGetDeviceProcAddr get, VkDevice device, VkPhysicalDeviceMemoryProperties memory, - VkDeviceSize max_range) : get_(get), device_(device), memory_(memory), max_range_(max_range) {} - ~PredicateReducer() { - if (pipeline_) fn("vkDestroyPipeline")(device_, pipeline_, nullptr); - if (layout_) fn("vkDestroyPipelineLayout")(device_, layout_, nullptr); - if (set_layout_) fn("vkDestroyDescriptorSetLayout")(device_, set_layout_, nullptr); - } - PredicateReducer(const PredicateReducer&) = delete; - PredicateReducer& operator=(const PredicateReducer&) = delete; - - // Owned by a command-buffer slot until its timeline ticket completes (or a failed recording is reset). - struct Batch { - PredicateReducer& owner; - VkBuffer buffer = VK_NULL_HANDLE; - VkDeviceMemory memory = VK_NULL_HANDLE; - VkDescriptorPool pool = VK_NULL_HANDLE; - VkDescriptorSet set = VK_NULL_HANDLE; - VkDeviceSize bytes = 0; - std::uint32_t count = 0, next = 0; - explicit Batch(PredicateReducer& r) : owner(r) {} - ~Batch() { - if (pool) owner.fn("vkDestroyDescriptorPool")(owner.device_, pool, nullptr); - if (buffer) owner.fn("vkDestroyBuffer")(owner.device_, buffer, nullptr); - if (memory) owner.fn("vkFreeMemory")(owner.device_, memory, nullptr); - } - Batch(const Batch&) = delete; - Batch& operator=(const Batch&) = delete; - bool prepare(VkBuffer source, VkDeviceSize offset, PredicateCapture& out) { - if (next >= count || !source) return false; - out = {source, offset, buffer, VkDeviceSize(next++) * 16, set}; - return true; - } - }; - - std::unique_ptr batch(std::uint64_t count) { - // One descriptor starts at offset zero; a push constant selects each aligned 16-byte slot. - if (!count || count > max_range_ / 16 || count > UINT32_MAX / 4 || !make_pipeline()) return {}; - auto b = std::make_unique(*this); - b->count = static_cast(count); - b->bytes = count * 16; - VkBufferCreateInfo buffer{VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO}; - buffer.size = b->bytes; - buffer.usage = VK_BUFFER_USAGE_TRANSFER_DST_BIT | VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | - VK_BUFFER_USAGE_CONDITIONAL_RENDERING_BIT_EXT; - if (fn("vkCreateBuffer")(device_, &buffer, nullptr, &b->buffer) != VK_SUCCESS) return {}; - VkMemoryRequirements requirements{}; - fn("vkGetBufferMemoryRequirements")(device_, b->buffer, &requirements); - std::uint32_t type = UINT32_MAX; - for (std::uint32_t i = 0; i < memory_.memoryTypeCount; ++i) { - if (!(requirements.memoryTypeBits & (1u << i))) continue; - if (type == UINT32_MAX) type = i; - if (memory_.memoryTypes[i].propertyFlags & VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT) { type = i; break; } - } - if (type == UINT32_MAX) return {}; - VkMemoryAllocateInfo allocation{VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO}; - allocation.allocationSize = requirements.size; - allocation.memoryTypeIndex = type; - if (fn("vkAllocateMemory")(device_, &allocation, nullptr, &b->memory) != VK_SUCCESS || - fn("vkBindBufferMemory")(device_, b->buffer, b->memory, 0) != VK_SUCCESS) return {}; - const VkDescriptorPoolSize size{VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, 1}; - VkDescriptorPoolCreateInfo pool{VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO}; - pool.maxSets = 1; pool.poolSizeCount = 1; pool.pPoolSizes = &size; - if (fn("vkCreateDescriptorPool")(device_, &pool, nullptr, &b->pool) != VK_SUCCESS) return {}; - VkDescriptorSetAllocateInfo sets{VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO}; - sets.descriptorPool = b->pool; sets.descriptorSetCount = 1; sets.pSetLayouts = &set_layout_; - if (fn("vkAllocateDescriptorSets")(device_, &sets, &b->set) != VK_SUCCESS) return {}; - const VkDescriptorBufferInfo info{b->buffer, 0, b->bytes}; - VkWriteDescriptorSet write{VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET}; - write.dstSet = b->set; write.dstBinding = 0; write.descriptorCount = 1; - write.descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER; write.pBufferInfo = &info; - fn("vkUpdateDescriptorSets")(device_, 1, &write, 0, nullptr); - return b; - } - - void capture(VkCommandBuffer cb, const PredicateCapture& p) const { - // End an earlier conditional scope before entering this helper: dispatch is itself conditional. - // The descriptor spans the arena, so order all prior accesses before reusing it for another slot. - VkMemoryBarrier before{VK_STRUCTURE_TYPE_MEMORY_BARRIER}; - before.srcAccessMask = VK_ACCESS_MEMORY_WRITE_BIT | VK_ACCESS_MEMORY_READ_BIT; - before.dstAccessMask = VK_ACCESS_TRANSFER_READ_BIT | VK_ACCESS_TRANSFER_WRITE_BIT; - const auto barrier = fn("vkCmdPipelineBarrier"); - barrier(cb, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, 0, 1, &before, 0, nullptr, 0, nullptr); - const VkBufferCopy copy{p.source_offset, p.offset, 8}; - fn("vkCmdCopyBuffer")(cb, p.source, p.scratch, 1, ©); - // The application's PREDICATION state does not describe this internal transfer read. Preserve snapshot - // semantics when it subsequently transitions and overwrites the source in the same command list. - VkBufferMemoryBarrier source_done{VK_STRUCTURE_TYPE_BUFFER_MEMORY_BARRIER}; - source_done.srcAccessMask = VK_ACCESS_TRANSFER_READ_BIT; - source_done.dstAccessMask = VK_ACCESS_MEMORY_READ_BIT | VK_ACCESS_MEMORY_WRITE_BIT; - source_done.srcQueueFamilyIndex = source_done.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; - source_done.buffer = p.source; source_done.offset = p.source_offset; source_done.size = 8; - barrier(cb, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, - 0, 0, nullptr, 1, &source_done, 0, nullptr); - VkMemoryBarrier compute{VK_STRUCTURE_TYPE_MEMORY_BARRIER}; - compute.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT; - compute.dstAccessMask = VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT; - barrier(cb, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, 0, 1, &compute, 0, nullptr, 0, nullptr); - fn("vkCmdBindPipeline")(cb, VK_PIPELINE_BIND_POINT_COMPUTE, pipeline_); - fn("vkCmdBindDescriptorSets")(cb, VK_PIPELINE_BIND_POINT_COMPUTE, layout_, 0, 1, &p.set, 0, nullptr); - const std::uint32_t index = static_cast(p.offset / 4); - fn("vkCmdPushConstants")(cb, layout_, VK_SHADER_STAGE_COMPUTE_BIT, 0, 4, &index); - fn("vkCmdDispatch")(cb, 1, 1, 1); - VkMemoryBarrier condition{VK_STRUCTURE_TYPE_MEMORY_BARRIER}; - condition.srcAccessMask = VK_ACCESS_SHADER_WRITE_BIT; - condition.dstAccessMask = VK_ACCESS_CONDITIONAL_RENDERING_READ_BIT_EXT; - barrier(cb, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, VK_PIPELINE_STAGE_CONDITIONAL_RENDERING_BIT_EXT, - 0, 1, &condition, 0, nullptr, 0, nullptr); - } - -private: - template T fn(const char* name) const { return reinterpret_cast(get_(device_, name)); } - bool make_pipeline() { - if (pipeline_) return true; - // No entry-point assumptions for partial/mock devices: fail before allocating or recording anything. - for (const char* name : {"vkCreateBuffer", "vkDestroyBuffer", "vkGetBufferMemoryRequirements", "vkAllocateMemory", - "vkFreeMemory", "vkBindBufferMemory", "vkCreateDescriptorPool", "vkDestroyDescriptorPool", - "vkAllocateDescriptorSets", "vkUpdateDescriptorSets", "vkCreateShaderModule", "vkDestroyShaderModule", - "vkCreateDescriptorSetLayout", "vkDestroyDescriptorSetLayout", "vkCreatePipelineLayout", - "vkDestroyPipelineLayout", "vkCreateComputePipelines", "vkDestroyPipeline", "vkCmdCopyBuffer", - "vkCmdPipelineBarrier", "vkCmdBindPipeline", "vkCmdBindDescriptorSets", "vkCmdPushConstants", "vkCmdDispatch"}) - if (!get_(device_, name)) return false; - VkDescriptorSetLayout set = VK_NULL_HANDLE; - VkPipelineLayout layout = VK_NULL_HANDLE; - VkShaderModule shader = VK_NULL_HANDLE; - VkPipeline pipeline = VK_NULL_HANDLE; - const VkDescriptorSetLayoutBinding binding{0, VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, 1, VK_SHADER_STAGE_COMPUTE_BIT, nullptr}; - VkDescriptorSetLayoutCreateInfo set_info{VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO}; - set_info.bindingCount = 1; set_info.pBindings = &binding; - bool ok = fn("vkCreateDescriptorSetLayout")(device_, &set_info, nullptr, &set) == VK_SUCCESS; - const VkPushConstantRange push{VK_SHADER_STAGE_COMPUTE_BIT, 0, 4}; - VkPipelineLayoutCreateInfo layout_info{VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO}; - layout_info.setLayoutCount = 1; layout_info.pSetLayouts = &set; - layout_info.pushConstantRangeCount = 1; layout_info.pPushConstantRanges = &push; - ok = ok && fn("vkCreatePipelineLayout")(device_, &layout_info, nullptr, &layout) == VK_SUCCESS; - VkShaderModuleCreateInfo module{VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO}; - module.codeSize = sizeof(predicate_reduce_spirv); module.pCode = predicate_reduce_spirv; - ok = ok && fn("vkCreateShaderModule")(device_, &module, nullptr, &shader) == VK_SUCCESS; - VkComputePipelineCreateInfo info{VK_STRUCTURE_TYPE_COMPUTE_PIPELINE_CREATE_INFO}; - info.stage = {VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO}; - info.stage.stage = VK_SHADER_STAGE_COMPUTE_BIT; info.stage.module = shader; info.stage.pName = "main"; - info.layout = layout; - ok = ok && fn("vkCreateComputePipelines")(device_, VK_NULL_HANDLE, 1, &info, nullptr, &pipeline) == VK_SUCCESS; - if (shader) fn("vkDestroyShaderModule")(device_, shader, nullptr); - if (!ok) { - if (pipeline) fn("vkDestroyPipeline")(device_, pipeline, nullptr); - if (layout) fn("vkDestroyPipelineLayout")(device_, layout, nullptr); - if (set) fn("vkDestroyDescriptorSetLayout")(device_, set, nullptr); - return false; - } - set_layout_ = set; layout_ = layout; pipeline_ = pipeline; - return true; - } - PFN_vkGetDeviceProcAddr get_; - VkDevice device_; - VkPhysicalDeviceMemoryProperties memory_; - VkDeviceSize max_range_; - VkDescriptorSetLayout set_layout_ = VK_NULL_HANDLE; - VkPipelineLayout layout_ = VK_NULL_HANDLE; - VkPipeline pipeline_ = VK_NULL_HANDLE; -}; -} // namespace leonida diff --git a/runtime/src/vulkan_predicated_copy.h b/runtime/src/vulkan_predicated_copy.h deleted file mode 100644 index 6a225ced7..000000000 --- a/runtime/src/vulkan_predicated_copy.h +++ /dev/null @@ -1,154 +0,0 @@ -// Byte-granular conditional CopyBufferRegion. Requires enabled storageBuffer8BitAccess, not shaderInt8. -#pragma once -#ifndef VK_NO_PROTOTYPES -#define VK_NO_PROTOTYPES -#endif -#include -#include -#include -#include -#include -#include -#include "predicated_copy_spv.h" -namespace leonida { -struct PredicatedCopyDispatch { - VkDescriptorSet set = VK_NULL_HANDLE; - std::uint32_t source = 0, destination = 0, bytes = 0; -}; -class PredicatedBufferCopier { -public: - PredicatedBufferCopier(PFN_vkGetDeviceProcAddr get, VkDevice device, const VkPhysicalDeviceLimits& limits) - : get_(get), device_(device), limits_(limits) {} - ~PredicatedBufferCopier() { - if(pipeline_)fn("vkDestroyPipeline")(device_,pipeline_,nullptr); - if(layout_)fn("vkDestroyPipelineLayout")(device_,layout_,nullptr); - if(set_layout_)fn("vkDestroyDescriptorSetLayout")(device_,set_layout_,nullptr); - } - PredicatedBufferCopier(const PredicatedBufferCopier&)=delete; - PredicatedBufferCopier& operator=(const PredicatedBufferCopier&)=delete; - struct Batch { - PredicatedBufferCopier& owner; - std::vector pools; - explicit Batch(PredicatedBufferCopier& value):owner(value){} - ~Batch(){for(auto pool:pools)owner.fn("vkDestroyDescriptorPool")(owner.device_,pool,nullptr);} - bool prepare(VkBuffer source,VkBuffer destination,VkDeviceSize src,VkDeviceSize dst,VkDeviceSize bytes, - std::vector& out) { - out.clear(); - if(!bytes)return true; - if(!source||!destination||bytes>UINT64_MAX-src||bytes>UINT64_MAX-dst)return false; - if(source==destination && src windows; - const auto alignment=std::max(1,owner.limits_.minStorageBufferOffsetAlignment); - const VkDeviceSize maximum=owner.limits_.maxStorageBufferRange; - const VkDeviceSize threads=VkDeviceSize(owner.limits_.maxComputeWorkGroupCount[0])*64; - for(VkDeviceSize done=0;done=maximum||dp>=maximum||!threads)return false; - const auto n=std::min({bytes-done,maximum-sp,maximum-dp,threads}); - if(!n||n>UINT32_MAX)return false; - windows.push_back({{source,s-sp,sp+n},{destination,d-dp,dp+n}, - static_cast(sp),static_cast(dp),static_cast(n)}); - if(windows.size()>UINT32_MAX/2)return false; - done+=n; - } - const auto count=static_cast(windows.size()); - const VkDescriptorPoolSize size{VK_DESCRIPTOR_TYPE_STORAGE_BUFFER,count*2}; - VkDescriptorPoolCreateInfo pool_info{VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO}; - pool_info.maxSets=count;pool_info.poolSizeCount=1;pool_info.pPoolSizes=&size; - VkDescriptorPool pool=VK_NULL_HANDLE; - if(owner.fn("vkCreateDescriptorPool")(owner.device_,&pool_info,nullptr,&pool)!=VK_SUCCESS)return false; - // The batch is retained with the command buffer until its timeline ticket completes. - pools.push_back(pool); - const std::vector layouts(count,owner.set_layout_); - std::vector sets(count); - VkDescriptorSetAllocateInfo allocate{VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO}; - allocate.descriptorPool=pool;allocate.descriptorSetCount=count;allocate.pSetLayouts=layouts.data(); - if(owner.fn("vkAllocateDescriptorSets")(owner.device_,&allocate,sets.data())!=VK_SUCCESS)return false; - for(std::uint32_t i=0;i("vkUpdateDescriptorSets")(owner.device_,2,writes,0,nullptr); - out.push_back({sets[i],windows[i].src,windows[i].dst,windows[i].bytes}); - } - return true; - } - }; - std::unique_ptr batch(){return std::make_unique(*this);} - void emit(VkCommandBuffer cb,const std::vector& jobs)const{ - const auto barrier=fn("vkCmdPipelineBarrier"); - // Barriers are unconditional even when the dispatch is skipped by conditional rendering. They order - // transfer producers, dependent copies, and adjacent windows whose aligned descriptors may overlap. - for(const auto& job:jobs){ - VkMemoryBarrier before{VK_STRUCTURE_TYPE_MEMORY_BARRIER}; - before.srcAccessMask=VK_ACCESS_MEMORY_WRITE_BIT|VK_ACCESS_MEMORY_READ_BIT; - before.dstAccessMask=VK_ACCESS_SHADER_READ_BIT|VK_ACCESS_SHADER_WRITE_BIT; - barrier(cb,VK_PIPELINE_STAGE_ALL_COMMANDS_BIT,VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT,0,1,&before,0,nullptr,0,nullptr); - fn("vkCmdBindPipeline")(cb,VK_PIPELINE_BIND_POINT_COMPUTE,pipeline_); - fn("vkCmdBindDescriptorSets")(cb,VK_PIPELINE_BIND_POINT_COMPUTE,layout_,0,1,&job.set,0,nullptr); - const std::uint32_t push[]={job.source,job.destination,job.bytes}; - fn("vkCmdPushConstants")(cb,layout_,VK_SHADER_STAGE_COMPUTE_BIT,0,sizeof(push),push); - fn("vkCmdDispatch")(cb,(job.bytes-1u)/64u+1u,1,1); - VkMemoryBarrier after{VK_STRUCTURE_TYPE_MEMORY_BARRIER}; - after.srcAccessMask=VK_ACCESS_SHADER_WRITE_BIT|VK_ACCESS_SHADER_READ_BIT; - after.dstAccessMask=VK_ACCESS_MEMORY_READ_BIT|VK_ACCESS_MEMORY_WRITE_BIT; - barrier(cb,VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT,VK_PIPELINE_STAGE_ALL_COMMANDS_BIT,0,1,&after,0,nullptr,0,nullptr); - } - } -private: - templateT fn(const char* name)const{return reinterpret_cast(get_(device_,name));} - bool make_pipeline() { - if (pipeline_) return true; - // No entry-point assumptions for partial/mock devices: fail before allocating or recording anything. - for (const char* name : {"vkCreateDescriptorPool", "vkDestroyDescriptorPool", - "vkAllocateDescriptorSets", "vkUpdateDescriptorSets", "vkCreateShaderModule", "vkDestroyShaderModule", - "vkCreateDescriptorSetLayout", "vkDestroyDescriptorSetLayout", "vkCreatePipelineLayout", - "vkDestroyPipelineLayout", "vkCreateComputePipelines", "vkDestroyPipeline", - "vkCmdPipelineBarrier", "vkCmdBindPipeline", "vkCmdBindDescriptorSets", "vkCmdPushConstants", "vkCmdDispatch"}) - if (!get_(device_, name)) return false; - VkDescriptorSetLayout set = VK_NULL_HANDLE; - VkPipelineLayout layout = VK_NULL_HANDLE; - VkShaderModule shader = VK_NULL_HANDLE; - VkPipeline pipeline = VK_NULL_HANDLE; - const VkDescriptorSetLayoutBinding bindings[]={{0,VK_DESCRIPTOR_TYPE_STORAGE_BUFFER,1,VK_SHADER_STAGE_COMPUTE_BIT,nullptr},{1,VK_DESCRIPTOR_TYPE_STORAGE_BUFFER,1,VK_SHADER_STAGE_COMPUTE_BIT,nullptr}}; - VkDescriptorSetLayoutCreateInfo set_info{VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO}; - set_info.bindingCount = 2; set_info.pBindings = bindings; - bool ok = fn("vkCreateDescriptorSetLayout")(device_, &set_info, nullptr, &set) == VK_SUCCESS; - const VkPushConstantRange push{VK_SHADER_STAGE_COMPUTE_BIT, 0, 12}; - VkPipelineLayoutCreateInfo layout_info{VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO}; - layout_info.setLayoutCount = 1; layout_info.pSetLayouts = &set; - layout_info.pushConstantRangeCount = 1; layout_info.pPushConstantRanges = &push; - ok = ok && fn("vkCreatePipelineLayout")(device_, &layout_info, nullptr, &layout) == VK_SUCCESS; - VkShaderModuleCreateInfo module{VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO}; - module.codeSize = sizeof(predicated_copy_spirv); module.pCode = predicated_copy_spirv; - ok = ok && fn("vkCreateShaderModule")(device_, &module, nullptr, &shader) == VK_SUCCESS; - VkComputePipelineCreateInfo info{VK_STRUCTURE_TYPE_COMPUTE_PIPELINE_CREATE_INFO}; - info.stage = {VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO}; - info.stage.stage = VK_SHADER_STAGE_COMPUTE_BIT; info.stage.module = shader; info.stage.pName = "main"; - info.layout = layout; - ok = ok && fn("vkCreateComputePipelines")(device_, VK_NULL_HANDLE, 1, &info, nullptr, &pipeline) == VK_SUCCESS; - if (shader) fn("vkDestroyShaderModule")(device_, shader, nullptr); - if (!ok) { - if (pipeline) fn("vkDestroyPipeline")(device_, pipeline, nullptr); - if (layout) fn("vkDestroyPipelineLayout")(device_, layout, nullptr); - if (set) fn("vkDestroyDescriptorSetLayout")(device_, set, nullptr); - return false; - } - set_layout_ = set; layout_ = layout; pipeline_ = pipeline; - return true; - } - PFN_vkGetDeviceProcAddr get_; - VkDevice device_; - VkPhysicalDeviceLimits limits_; - VkDescriptorSetLayout set_layout_=VK_NULL_HANDLE; - VkPipelineLayout layout_=VK_NULL_HANDLE; - VkPipeline pipeline_=VK_NULL_HANDLE; -}; -} diff --git a/runtime/src/vulkan_present.h b/runtime/src/vulkan_present.h deleted file mode 100644 index d94672971..000000000 --- a/runtime/src/vulkan_present.h +++ /dev/null @@ -1,1494 +0,0 @@ -#pragma once - -// Puts a D3D12 back buffer on screen through a Vulkan swapchain, for whichever front end the game turns out to use -// (DXGI or the console's PresentX; docs/d3d12_vulkan.md question 6). The back buffer is an ordinary texture in the -// D3D12 PRESENT (common) state; present() blits it to the acquired swapchain image, scaling if the window size -// differs, and queues the present. The application's own work reaches the same VkQueue first, so every draw it -// submitted before present() is in the frame. -// -// Needs VK_KHR_swapchain on the device and a surface from the caller (which this object then owns). The swapchain -// is recreated when the window changes size or the surface reports it out of date; a minimised window skips -// presents. Two frames are in flight; present() waits for the older one before reusing its command buffer. -// -// Beyond the plain blit (the Xbox PresentX path, docs/d3d12_vulkan.md section 4.5): a source rectangle (only that part -// of the back buffer is scaled to the window), a blank present (the window cleared to black), a swapchain format -// that follows the source (an sRGB source gets an sRGB swapchain, so the blit's decode and encode cancel; every -// other source gets a UNORM one), and an optional capture that copies each presented frame to host memory. -// -// Plane composition (PresentX with placement, a filter, HDR10 or a second plane): present_planes() runs a compute pass -// (present_compose.comp, vulkan_present_compose.h) over up to two textures into an RGBA16F image and copies that to the -// swapchain; with an HDR10 plane and a surface that lists an ST.2084 format the swapchain is created in it. The plain -// blit above is unchanged. -// -// Tearing on request (PresentX's ImmediateThresholdPercent): with VK_KHR_swapchain_maintenance1 (or the EXT original) -// the vsync swapchain is created with FIFO plus IMMEDIATE (FIFO_RELAXED when the surface cannot switch to IMMEDIATE), -// and a present that asks for it is queued in that mode alone. Without the extension, or without either mode, a -// request is ignored and the frame waits for the vblank. - -#include "vulkan_backend.h" -#include "vulkan_present_compose.h" -#include "../core/log.h" - -// Use the original EXT spellings. They are aliases of the promoted KHR types and are available in older headers. -#if defined(VK_EXT_SWAPCHAIN_MAINTENANCE_1_EXTENSION_NAME) && defined(VK_EXT_SURFACE_MAINTENANCE_1_EXTENSION_NAME) -#define LEONIDA_SWAPCHAIN_MAINTENANCE1 1 -#endif - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace leonida { - -// A sub-rectangle of a back buffer in texels; left/top inclusive, right/bottom exclusive (D3D12_RECT's convention). -struct PresentRect { - std::int32_t left, top, right, bottom; -}; - -// One plane of present_planes(): a colour texture, the part of it shown, and where in the output it goes. -struct PresentPlane { - ResourceId source{}; - PresentRect source_rect{}; // texels; used when has_source_rect - bool has_source_rect = false; - float dest[4] = {0, 0, 1, 1}; // left, top, right, bottom as fractions of the output (0..1) - bool point_filter = false; // nearest texel; otherwise bilinear inside the source rectangle - bool hdr10 = false; // the texture holds ST.2084 (PQ) Rec.2020 values; otherwise sRGB or G2.2 (PresentPlanes::sdr_eotf) Rec.709 ones - bool straight_alpha = false; // plane 1 only: alpha is not premultiplied into the colour -}; -struct PresentPlanes { - PresentPlane plane[2]; - std::uint32_t count = 1; - // What SDR white maps to in an HDR10 output, and what HDR10 is divided by for an SDR one (the white of the SDR output). - float sdr_white_nits = 203.0f; - // How SDR planes (and an SDR output) are encoded: piecewise sRGB (default; what Windows applies to SDR content in HDR - // mode, community-sourced, docs section 4.5) or a pure power of 2.2. - enum class SdrEotf : std::uint32_t { srgb = 0, gamma22 = 1 }; - SdrEotf sdr_eotf = SdrEotf::srgb; - float hdr_peak_nits = 1000.0f; // peak of the HDR10 content: the white point of the tone map on an SDR output -}; - -namespace detail { -inline bool is_srgb_format(VkFormat format) { - switch (format) { - case VK_FORMAT_R8_SRGB: case VK_FORMAT_R8G8_SRGB: case VK_FORMAT_R8G8B8_SRGB: case VK_FORMAT_B8G8R8_SRGB: - case VK_FORMAT_R8G8B8A8_SRGB: case VK_FORMAT_B8G8R8A8_SRGB: case VK_FORMAT_A8B8G8R8_SRGB_PACK32: - return true; - default: - return false; - } -} -// What vkCmdBlitImage cannot read: integer and block-compressed colour formats. -inline bool blit_unsupported_format(VkFormat format) { - switch (format) { - case VK_FORMAT_R8_UINT: case VK_FORMAT_R8_SINT: case VK_FORMAT_R8G8_UINT: case VK_FORMAT_R8G8_SINT: - case VK_FORMAT_R8G8B8A8_UINT: case VK_FORMAT_R8G8B8A8_SINT: case VK_FORMAT_R16_UINT: case VK_FORMAT_R16_SINT: - case VK_FORMAT_R16G16_UINT: case VK_FORMAT_R16G16_SINT: case VK_FORMAT_R16G16B16A16_UINT: - case VK_FORMAT_R16G16B16A16_SINT: case VK_FORMAT_R32_UINT: case VK_FORMAT_R32_SINT: case VK_FORMAT_R32G32_UINT: - case VK_FORMAT_R32G32_SINT: case VK_FORMAT_R32G32B32A32_UINT: case VK_FORMAT_R32G32B32A32_SINT: - case VK_FORMAT_A2B10G10R10_UINT_PACK32: case VK_FORMAT_UNDEFINED: - return true; - default: - return format >= VK_FORMAT_BC1_RGB_UNORM_BLOCK && format <= VK_FORMAT_BC7_SRGB_BLOCK; - } -} -// A path as UTF-8 text, for a message. -inline std::string path_text(const std::filesystem::path& path) { - const auto text = path.u8string(); - return std::string(reinterpret_cast(text.data()), text.size()); -} -} // namespace detail - -// Writing presented frames to disk. The runtime fills this from the settings present.capture_dir, -// present.capture_every and present.capture_limit (LEONIDA_CAPTURE, LEONIDA_CAPTURE_EVERY, LEONIDA_CAPTURE_LIMIT); -// this header reads no setting itself. -struct PresentCapture { - std::filesystem::path dir; // the folder the frames go to, made when it is missing; empty: no capture - int every = 30; // presented frames between files; below 1 counts as 1 - int limit = 24; // files at most; below 1 counts as 1 -}; - -class VulkanPresenter { -public: - VulkanPresenter(VulkanContext& context, PFN_vkGetInstanceProcAddr get_instance, VkInstance instance, - VkPhysicalDevice physical, VkQueue queue, std::uint32_t family, VkSurfaceKHR surface, - bool swapchain_maintenance1 = false, - std::function extent_fn = nullptr, - std::function recreate_surface_fn = nullptr, - PresentCapture capture = {}) - : context_(context), instance_(instance), physical_(physical), queue_(queue), surface_(surface), - maintenance1_(swapchain_maintenance1), extent_fn_(std::move(extent_fn)), - recreate_surface_fn_(std::move(recreate_surface_fn)) { -#define LEONIDA_INSTANCE_FN(name) name##_ = reinterpret_cast(get_instance(instance, #name)); - LEONIDA_INSTANCE_FN(vkGetPhysicalDeviceSurfaceSupportKHR) - LEONIDA_INSTANCE_FN(vkGetPhysicalDeviceSurfaceCapabilitiesKHR) - LEONIDA_INSTANCE_FN(vkGetPhysicalDeviceSurfaceFormatsKHR) - LEONIDA_INSTANCE_FN(vkGetPhysicalDeviceSurfacePresentModesKHR) - LEONIDA_INSTANCE_FN(vkGetPhysicalDeviceSurfaceCapabilities2KHR) - LEONIDA_INSTANCE_FN(vkDestroySurfaceKHR) - LEONIDA_INSTANCE_FN(vkGetDeviceProcAddr) - LEONIDA_INSTANCE_FN(vkGetPhysicalDeviceMemoryProperties) - LEONIDA_INSTANCE_FN(vkGetPhysicalDeviceFormatProperties) -#undef LEONIDA_INSTANCE_FN - if (!vkGetDeviceProcAddr_ || !vkDestroySurfaceKHR_) return; - const VkDevice device = context.device(); -#define LEONIDA_DEVICE_FN(name) name##_ = reinterpret_cast(vkGetDeviceProcAddr_(device, #name)); - LEONIDA_DEVICE_FN(vkCreateSwapchainKHR) - LEONIDA_DEVICE_FN(vkDestroySwapchainKHR) - LEONIDA_DEVICE_FN(vkGetSwapchainImagesKHR) - LEONIDA_DEVICE_FN(vkAcquireNextImageKHR) - LEONIDA_DEVICE_FN(vkQueuePresentKHR) - LEONIDA_DEVICE_FN(vkCmdBlitImage) - LEONIDA_DEVICE_FN(vkCmdClearColorImage) - LEONIDA_DEVICE_FN(vkCreateFence) - LEONIDA_DEVICE_FN(vkDestroyFence) - LEONIDA_DEVICE_FN(vkWaitForFences) - LEONIDA_DEVICE_FN(vkResetFences) -#undef LEONIDA_DEVICE_FN - if (!vkCreateSwapchainKHR_ || !vkQueuePresentKHR_ || !vkCmdBlitImage_ || !vkCreateFence_) return; - - VkBool32 supported = VK_FALSE; - vkGetPhysicalDeviceSurfaceSupportKHR_(physical, family, surface, &supported); - if (!supported) return; - - auto& vk = context.vk; - VkCommandPoolCreateInfo pool{VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO}; - pool.flags = VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT; - pool.queueFamilyIndex = family; - if (vk.vkCreateCommandPool(device, &pool, nullptr, &pool_) != VK_SUCCESS) return; - for (Frame& frame : frames_) { - VkCommandBufferAllocateInfo allocate{VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO}; - allocate.commandPool = pool_; - allocate.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY; - allocate.commandBufferCount = 1; - VkFenceCreateInfo fence{VK_STRUCTURE_TYPE_FENCE_CREATE_INFO}; - fence.flags = VK_FENCE_CREATE_SIGNALED_BIT; - VkSemaphoreCreateInfo semaphore{VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO}; - if (vk.vkAllocateCommandBuffers(device, &allocate, &frame.commands) != VK_SUCCESS || - vkCreateFence_(device, &fence, nullptr, &frame.done) != VK_SUCCESS || - vk.vkCreateSemaphore(device, &semaphore, nullptr, &frame.acquired) != VK_SUCCESS) - return; - } - // Capture (PresentCapture; LEONIDA_CAPTURE= in the runtime): besides presenting, copy the swapchain image - // to host memory and write it out as a binary PPM, every capture.every presented frames, at most - // capture.limit of them. Off unless a folder is named; a capture that cannot be made shows nothing and is - // reported here instead of failing the presenter. - if (!capture.dir.empty()) { - capture_dir_ = std::move(capture.dir); - // Create the folder: a capture run names its own output folder and should not have to make it first. - std::error_code created; - std::filesystem::create_directories(capture_dir_, created); - capture_to_disk_ = true; - capture_ = true; // the swapchain needs TRANSFER_SRC, and every frame copies into a staging buffer - capture_every_ = std::max(1, capture.every); - capture_limit_ = std::max(1, capture.limit); - RT_LOG_INFO("present: capture on: every %d presented frame(s), at most %d, into %s\n", - capture_every_, capture_limit_, detail::path_text(capture_dir_).c_str()); - } - ok_ = recreate(true, false); - if (!ok_ && capture_to_disk_) { - // The surface refused a TRANSFER_SRC swapchain, or the staging buffer could not be made: present - // without the capture rather than not at all. - RT_LOG_WARN("present: capture is unavailable on this surface; presenting without it\n"); - capture_to_disk_ = false; - capture_ = false; - capture_dir_.clear(); - ok_ = recreate(true, false); - } - } - - ~VulkanPresenter() { - context_.holds().cancel_after(this); // presents still queued behind held work are dropped - auto& vk = context_.vk; - const VkDevice device = context_.device(); - { - std::lock_guard lock(context_.submit_mutex()); - vk.vkQueueWaitIdle(queue_); - // A WSI layer may perform a device-wide idle while destroying the swapchain. - // Keep that implicit idle serialized with submits from every context queue. - release(swapchain_); - } - swapchain_ = VK_NULL_HANDLE; - // A capture still pending has its copy complete once the queue is idle: write it before the buffer goes. - finish_pending_capture(); - release_capture(); - composer_.reset(); - for (Frame& frame : frames_) { - drop_views(frame); - if (frame.done) vkDestroyFence_(device, frame.done, nullptr); - if (frame.acquired) vk.vkDestroySemaphore(device, frame.acquired, nullptr); - } - if (pool_) vk.vkDestroyCommandPool(device, pool_, nullptr); - if (surface_ && vkDestroySurfaceKHR_) vkDestroySurfaceKHR_(instance_, surface_, nullptr); - } - - VulkanPresenter(const VulkanPresenter&) = delete; - VulkanPresenter& operator=(const VulkanPresenter&) = delete; - - bool ok() const { return ok_; } - VkExtent2D extent() const { - const std::uint64_t packed = extent_packed_; - return {std::uint32_t(packed >> 32), std::uint32_t(packed)}; - } - VkFormat format() const { return format_; } - std::uint64_t presented() const { return presented_; } - // The present mode a tearing present uses (IMMEDIATE, else FIFO_RELAXED) while the current swapchain was created - // for it, else VK_PRESENT_MODE_MAX_ENUM_KHR: ImmediateThresholdPercent cannot be honoured then. - VkPresentModeKHR tear_mode() const { return tear_mode_; } - bool tear_supported() const { return tear_mode_ != VK_PRESENT_MODE_MAX_ENUM_KHR; } - // Whether the last present was queued in the tearing mode, and how many were. - // A present queued behind held work (see submit()) is reported as not tearing. - bool last_present_tore() const { return last_tore_; } - std::uint64_t tear_presents() const { return tear_presents_; } - - // Blits the colour texture `source` (mip 0, layer 0, in D3D12's PRESENT state) to the window and presents it. - // `source_rect`, when given, limits the blit to that part of the texture (stretched to the whole window); it - // must be non-empty and inside the texture (VK_ERROR_UNKNOWN otherwise). Integer, block-compressed and - // multisampled sources are refused (VK_ERROR_FORMAT_NOT_SUPPORTED); the other formats are converted by the blit. - // The blit filters bilinearly, so with a rectangle the outermost texels blend with their neighbours outside it. - // vsync: FIFO; otherwise MAILBOX or IMMEDIATE when the surface has them. VK_SUCCESS also covers a skipped - // present (minimised window) and one the surface reported out of date (the swapchain is recreated next time); - // VK_ERROR_OUT_OF_DATE_KHR means recreating the swapchain failed, and the next present tries again. - // - // A failure after an image was acquired (the blit's submission) is recovered here, so the next present does not - // wait on a fence nothing will signal: an empty batch takes the acquire semaphore and signals the frame's fence, - // and the swapchain is recreated next time, which gives back the image that was never presented. If even that - // batch fails, the presenter stops (ok() is false) and its owner has to make a new one. - // - // `tear` (only with vsync): queue the present in tear_mode() instead of FIFO when the swapchain can, so a frame - // that missed its vblank is shown at once; last_present_tore() says whether it was. - VkResult present(ResourceId source, bool vsync, const PresentRect* source_rect = nullptr, bool tear = false) { - ResourceBinding binding; - { - std::shared_lock lock(context_.resource_mutex_); // the resource table (vulkan_backend.h) - const ResourceBinding* found = context_.resolve(source); - if (!found || !found->image || found->aspects != VK_IMAGE_ASPECT_COLOR_BIT) return VK_ERROR_UNKNOWN; - binding = *found; - } - // Multisampled sources (no resolve into a temporary yet), integer formats (a UNORM swapchain cannot take them) - // and anything the GPU cannot blit from are refused. - if (binding.samples > 1 || detail::blit_unsupported_format(binding.format) || - !(format_features(binding.format) & VK_FORMAT_FEATURE_BLIT_SRC_BIT)) - return VK_ERROR_FORMAT_NOT_SUPPORTED; - if (source_rect && (source_rect->left < 0 || source_rect->top < 0 || source_rect->left >= source_rect->right || - source_rect->top >= source_rect->bottom || - std::uint32_t(source_rect->right) > binding.width || - std::uint32_t(source_rect->bottom) > binding.height)) - return VK_ERROR_UNKNOWN; - return submit(&binding, source, vsync, source_rect, detail::is_srgb_format(binding.format), tear); - } - - // PresentX with planes (docs section 4.5): one or two textures, each scaled from its source rectangle to its - // destination rectangle of the window, plane 1 blended over plane 0, composed by a compute pass into an RGBA16F image - // that is then copied to the swapchain image. Colour spaces are converted to the swapchain's: when a plane is HDR10 and - // the surface lists an HDR10 (ST.2084) format the swapchain uses it (hdr_active()), else the HDR10 planes are - // tone mapped to SDR (shoulder above 0.8 of SDR white, then clipped). Planes are filtered and blended in linear light. The swapchain - // is always UNORM here; sRGB-format sources are - // encoded again by the pass. Sources must be single-sample, sampled (no DENY_SHADER_RESOURCE) float/UNORM/sRGB - // colour textures; others are refused (VK_ERROR_FORMAT_NOT_SUPPORTED). Rectangles outside their range give - // VK_ERROR_UNKNOWN. vsync and `tear` as for present(). - VkResult present_planes(const PresentPlanes& planes, bool vsync, bool tear = false) { - if (planes.count < 1 || planes.count > 2) return VK_ERROR_UNKNOWN; - if (!(planes.sdr_white_nits > 0.0f) || !std::isfinite(planes.sdr_white_nits)) return VK_ERROR_UNKNOWN; - if (!(planes.hdr_peak_nits > 0.0f) || !std::isfinite(planes.hdr_peak_nits)) return VK_ERROR_UNKNOWN; - for (std::uint32_t i = 0; i < planes.count; ++i) { - const PresentPlane& plane = planes.plane[i]; - ResourceBinding binding; - { - std::shared_lock lock(context_.resource_mutex_); - const ResourceBinding* found = context_.resolve(plane.source); - if (!found || !found->image) return VK_ERROR_UNKNOWN; - binding = *found; - } - if (binding.aspects != VK_IMAGE_ASPECT_COLOR_BIT || binding.samples > 1 || !binding.sampled || detail::blit_unsupported_format(binding.format) || - !(format_features(binding.format) & VK_FORMAT_FEATURE_SAMPLED_IMAGE_BIT)) - return VK_ERROR_FORMAT_NOT_SUPPORTED; - const PresentRect& r = plane.source_rect; - if (plane.has_source_rect && (r.left < 0 || r.top < 0 || r.left >= r.right || r.top >= r.bottom || - std::uint32_t(r.right) > binding.width || std::uint32_t(r.bottom) > binding.height)) - return VK_ERROR_UNKNOWN; - const float* d = plane.dest; - if (!(d[0] >= 0.0f && d[0] < d[2] && d[2] <= 1.0f && d[1] >= 0.0f && d[1] < d[3] && d[3] <= 1.0f)) - return VK_ERROR_UNKNOWN; // (also false for NaN) - } - return submit(nullptr, ResourceId{}, vsync, nullptr, false, tear, &planes); - } - // The swapchain holds HDR10 (ST.2084) values: a plane asked for it and the surface has the format. - bool hdr_active() const { return hdr_active_; } - // Presents that went through the compose pass (present_planes); plain blits and blank frames are not counted. - std::uint64_t composed_presents() const { return composed_; } - // Tests, on surfaces without HDR10: compose as if the output were HDR10 but write the PQ values into the (8-bit, - // UNORM) swapchain, so the encoder can be checked on any GPU. Takes effect with the next present_planes(). - void force_hdr_encoding(bool on) { force_hdr_encoding_ = on; } - - // Polled while a present waits for a swapchain image (every 50 ms): when it returns true the present gives up with - // VK_NOT_READY, so a caller that is being suspended is never held by a window that stopped taking frames. - void set_abort(std::function abort) { - std::lock_guard lock(abort_mutex_); - abort_ = std::move(abort); - } - - // Presents a black frame: the swapchain image cleared, nothing read. PresentX with no planes. - VkResult present_blank(bool vsync, bool tear = false) { - return submit(nullptr, ResourceId{}, vsync, nullptr, swapchain_srgb_, tear); - } - - // From now on every presented frame is also copied to host memory (the swapchain gets TRANSFER_SRC usage), for - // read_back(). False when the surface cannot do it or its format is not 8 bits per channel with 4 channels. - // Call before the first present. - bool enable_capture() { - std::lock_guard lock(present_mutex_); - if (!ok_) return false; - capture_ = true; - stale_ = true; - if (!recreate(vsync_, swapchain_srgb_, swapchain_hdr_req_) || (swapchain_ && !capture_buffer_)) { - capture_ = false; - return false; - } - return true; - } - - // The last presented frame as the swapchain stores it (4 bytes a texel, rows tightly packed, format() order). - // Waits for the frame to finish. False when nothing was presented since enable_capture(), after a present - // that was skipped because the window is minimised (it returned VK_SUCCESS but showed nothing), until the next - // frame that is shown (the frame before it is not what the window was last asked to show), or when the wait fails. - bool read_back(std::vector& pixels, VkExtent2D* extent, VkFormat* format) { - std::lock_guard lock(present_mutex_); - if (!capture_ || !capture_ptr_ || !captured_) return false; - const Frame& frame = frames_[(frame_index_ + frames_.size() - 1) % frames_.size()]; - if (vkWaitForFences_(context_.device(), 1, &frame.done, VK_TRUE, UINT64_MAX) != VK_SUCCESS) - return false; - pixels.assign(capture_ptr_, capture_ptr_ + std::size_t(captured_extent_.width) * captured_extent_.height * 4); - if (extent) *extent = captured_extent_; - if (format) *format = captured_format_; - return true; - } - - // Shared by present(), present_blank() and present_planes(). - // - // A Present is ordered behind the work the queues hold (a batch that waits for a Signal not yet submitted, - // queue_holds.h): it would otherwise blit whatever the source texture held before that batch ran. It is not - // blocked: it is queued, returns VK_SUCCESS as ExecuteCommandLists does for a held batch, and is submitted, - // in order with the presents before it, by the thread that releases the last operation held when it was called - // (its failure is printed there). Held work that is never released holds back the presents after it, as it - // holds back the queue's own work; with nothing held this is the plain path. A blank present reads nothing and - // is only ordered behind earlier presents. Waiting instead was rejected: the Signal that releases the work may - // be one the application's own thread makes after Present returns. Like a full frame-latency queue, a Present that - // finds max_deferred_presents queued ahead of it does wait, for held work to release (logged once; set_abort ends - // the wait), so the queue behind never-released work is bounded. A queued Present reports its tear as false - // (last_present_tore()): the frame pacer's default sync. - static constexpr std::size_t max_deferred_presents = 8; - - VkResult submit(const ResourceBinding* binding, ResourceId source, bool vsync, const PresentRect* source_rect, - bool srgb, bool tear = false, const PresentPlanes* planes = nullptr) { - wait_for_room(); - std::lock_guard lock(present_mutex_); - // `binding` null and `planes` null: clear instead of blit; `planes`: compose them (`binding`, `source`, - // `source_rect` unused). Only a present that reads a texture waits for held work. - if (deferred_.empty() && !((binding || planes) && context_.holds().any_held())) - return submit_now(binding, source, vsync, source_rect, srgb, tear, planes); - PendingPresent pending{binding != nullptr, source, vsync, source_rect != nullptr, {}, srgb, tear, - planes != nullptr, {}}; - if (source_rect) pending.rect = *source_rect; - if (planes) pending.planes = *planes; - deferred_.push_back(pending); - last_tore_ = false; - context_.holds().after_held(this, [this] { run_deferred(); }); - return VK_SUCCESS; - } - -private: - bool should_abort() { - std::function abort; - { - std::lock_guard lock(abort_mutex_); - abort = abort_; - } - return abort && abort(); - } - - // Called without present_mutex_: the thread that releases the queued presents needs it. - void wait_for_room() { - bool logged = false; - for (;;) { - { - std::lock_guard lock(present_mutex_); - if (deferred_.size() < max_deferred_presents) return; - } - if (!logged) { - logged = true; - RT_LOG_WARN("d3d12: %zu Presents are queued behind held work; this one waits for it\n", - max_deferred_presents); - } - if (should_abort()) return; - std::this_thread::sleep_for(std::chrono::milliseconds(1)); - } - } - - struct PendingPresent { - bool has_source; - ResourceId source; - bool vsync; - bool has_rect; - PresentRect rect; - bool srgb; - bool tear; - bool has_planes; - PresentPlanes planes; - }; - - void run_deferred() { - std::lock_guard lock(present_mutex_); - if (deferred_.empty()) return; - const PendingPresent p = deferred_.front(); - deferred_.pop_front(); - ResourceBinding binding{}; - const VkResult result = submit_now(p.has_source ? &binding : nullptr, p.source, p.vsync, - p.has_rect ? &p.rect : nullptr, p.srgb, p.tear, - p.has_planes ? &p.planes : nullptr); - if (result != VK_SUCCESS) - RT_LOG_ERROR("d3d12: a Present held behind queued work failed when it was released (%d)\n", - int(result)); - } - - VkResult submit_now(const ResourceBinding* binding, ResourceId source, bool vsync, const PresentRect* source_rect, - bool srgb, bool tear = false, const PresentPlanes* planes = nullptr) { - last_tore_ = false; - if (!ok_) return VK_ERROR_INITIALIZATION_FAILED; - if (surface_lost_) { // the window's display went away under a presented swapchain - // Try to make a new surface for the same window (the hwnd is retained by the factory's callback). - // Until that succeeds, vkd3d's precedent keeps rendering to nothing: the frame is not shown, but - // the run continues instead of wedging on a sticky E_FAIL. - surface_ = recreate_surface_fn_ ? recreate_surface_fn_() : VK_NULL_HANDLE; - if (!surface_) { - captured_ = false; // nothing was shown: read_back() must not hand out the frame - return VK_SUCCESS; - } - surface_lost_ = false; - stale_ = true; // the old swapchain is gone: rebuild on the new surface below - } - // The swapchain's HDR10 format is only for composed planes that ask for it; a blit of an SDR source or a blank - // frame keeps whatever the swapchain has (black is black), except that a blit needs the SDR one. - bool want_hdr = swapchain_hdr_req_; - if (planes) - want_hdr = (planes->plane[0].hdr10) || (planes->count > 1 && planes->plane[1].hdr10); - else if (binding) - want_hdr = false; - if (vsync != vsync_ || stale_ || srgb != swapchain_srgb_ || want_hdr != swapchain_hdr_req_) { - // The swapchain's colour encoding is only recorded once the new swapchain exists, so a failed - // recreate is tried again at the next present. - if (!recreate(vsync, srgb, want_hdr)) return VK_ERROR_OUT_OF_DATE_KHR; - } - if (!swapchain_) { // minimised: try again next frame - stale_ = true; - captured_ = false; // nothing was shown: read_back() must not hand out the frame before - return VK_SUCCESS; - } - if (binding && !presentable(source)) return VK_ERROR_UNKNOWN; // checked before an image is acquired for it - if ((binding || planes) && !(format_features(format_) & VK_FORMAT_FEATURE_BLIT_DST_BIT)) - return VK_ERROR_FORMAT_NOT_SUPPORTED; - if (planes && !prepare_compose()) return VK_ERROR_FORMAT_NOT_SUPPORTED; - auto& vk = context_.vk; - const VkDevice device = context_.device(); - Frame& frame = frames_[frame_index_ % frames_.size()]; - if (const VkResult waited = vkWaitForFences_(device, 1, &frame.done, VK_TRUE, UINT64_MAX); waited != VK_SUCCESS) - return stop(waited); - // Every submit copies into the same mapped buffer, even if its frame is outside the disk capture stride. - if (const VkResult r = finish_pending_capture(); r != VK_SUCCESS) return stop(r); - - std::uint32_t image = 0; - VkResult acquired = acquire(frame.acquired, &image); - if (acquired == VK_ERROR_OUT_OF_DATE_KHR) { - if (!recreate(vsync, swapchain_srgb_, swapchain_hdr_req_)) return acquired; - if (!swapchain_) { // minimised since the last present: skipped, as above - captured_ = false; - return VK_SUCCESS; - } - acquired = acquire(frame.acquired, &image); - } - if (acquired == VK_ERROR_SURFACE_LOST_KHR) { - captured_ = false; // nothing was acquired, nothing was shown - mark_surface_lost(); - return VK_SUCCESS; - } - if (acquired != VK_SUCCESS && acquired != VK_SUBOPTIMAL_KHR) return acquired; // nothing was acquired - if (acquired == VK_SUBOPTIMAL_KHR) stale_ = true; - // An out-of-date retry above may have given the swapchain another extent: the compose target follows it. - if (planes && !prepare_compose()) return give_back(frame, VK_ERROR_FORMAT_NOT_SUPPORTED); - - bool recorded = false; - std::unique_lock tracker_lock(context_.tracker_mutex_, std::defer_lock); - bool rollback_source = false; - VkImageLayout prev_layout = VK_IMAGE_LAYOUT_UNDEFINED; - std::array plane_rollbacks{}; // present_planes(): the same, per plane - if (planes) { - std::array current{}; - bool found_all = true; - { - std::shared_lock resource_lock(context_.resource_mutex_); - for (std::uint32_t i = 0; i < planes->count; ++i) { - const ResourceBinding* found = context_.resolve(planes->plane[i].source); - if (found && found->image && found->aspects == VK_IMAGE_ASPECT_COLOR_BIT && found->sampled) - current[i] = *found; - else - found_all = false; - } - if (found_all) { - tracker_lock.lock(); - for (std::uint32_t i = 0; i < planes->count; ++i) { - plane_rollbacks[i].id = planes->plane[i].source; - plane_rollbacks[i].tracked = context_.tracker_.tracked(plane_rollbacks[i].id); - if (plane_rollbacks[i].tracked) plane_rollbacks[i].layout = context_.tracker_.layout(plane_rollbacks[i].id, 0); - } - recorded = record_planes(frame, std::uint32_t(frame_index_ % frames_.size()), current, *planes, image); - } - } - } else if (binding) { - // Lock hierarchy: resource_mutex_ -> tracker_mutex_ -> submit_mutex_ (vulkan_backend.h). - // record() only touches subresource 0 (mip 0, layer 0, color) of `source`, so saving that one layout - // rolls back a failed submit in O(1) without copying the entire LayoutTracker map. - std::shared_lock resource_lock(context_.resource_mutex_); - const ResourceBinding* current = context_.resolve(source); - if (current && current->image && current->aspects == VK_IMAGE_ASPECT_COLOR_BIT) { - tracker_lock.lock(); - rollback_source = context_.tracker_.tracked(source); - if (rollback_source) prev_layout = context_.tracker_.layout(source, 0); - record(frame.commands, *current, source, image, source_rect); - recorded = true; - } - } else { - record_blank(frame.commands, image); - recorded = true; - } - const auto rollback = [&] { - if (rollback_source) - context_.tracker_.set(source, {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1}, prev_layout); - if (planes) - for (std::uint32_t i = 0; i < planes->count; ++i) - if (plane_rollbacks[i].tracked) - context_.tracker_.set(plane_rollbacks[i].id, {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1}, - plane_rollbacks[i].layout); - }; - if (!recorded) return give_back(frame, VK_ERROR_UNKNOWN); // released by another thread since presentable() - if (const VkResult reset = vkResetFences_(device, 1, &frame.done); reset != VK_SUCCESS) { - rollback(); - return stop(reset); - } - const VkPipelineStageFlags wait_stage = VK_PIPELINE_STAGE_TRANSFER_BIT; - VkSubmitInfo submit_info{VK_STRUCTURE_TYPE_SUBMIT_INFO}; - submit_info.waitSemaphoreCount = 1; - submit_info.pWaitSemaphores = &frame.acquired; - submit_info.pWaitDstStageMask = &wait_stage; - submit_info.commandBufferCount = 1; - submit_info.pCommandBuffers = &frame.commands; - submit_info.signalSemaphoreCount = 1; - submit_info.pSignalSemaphores = &ready_[image]; // one per image: reused only once that image comes back - VkPresentInfoKHR present{VK_STRUCTURE_TYPE_PRESENT_INFO_KHR}; - present.waitSemaphoreCount = 1; - present.pWaitSemaphores = &ready_[image]; - present.swapchainCount = 1; - present.pSwapchains = &swapchain_; - present.pImageIndices = ℑ -#ifdef LEONIDA_SWAPCHAIN_MAINTENANCE1 - // The swapchain was created with FIFO and tear_mode_ (both come from the same recreate). - VkSwapchainPresentModeInfoEXT present_mode{VK_STRUCTURE_TYPE_SWAPCHAIN_PRESENT_MODE_INFO_EXT}; - const bool tearing = tear && vsync_ && tear_supported(); - if (tearing) { - present_mode.swapchainCount = 1; - present_mode.pPresentModes = &tear_mode_; - present.pNext = &present_mode; - } -#else - const bool tearing = false; - (void)tear; -#endif - VkResult submitted, result = VK_SUCCESS; - { - std::lock_guard lock(context_.submit_mutex()); - submitted = vk.vkQueueSubmit(queue_, 1, &submit_info, frame.done); - if (submitted != VK_SUCCESS) rollback(); - // Commit/rollback happened before releasing tracker_mutex_ inside submit_mutex(), preserving submission - // order without holding tracker_mutex_ across vkQueuePresentKHR. - if (tracker_lock.owns_lock()) tracker_lock.unlock(); - if (submitted == VK_SUCCESS) result = vkQueuePresentKHR_(queue_, &present); - } - if (submitted != VK_SUCCESS) return give_back(frame, submitted); - ++frame_index_; - // Only a present the engine took counts (SUBOPTIMAL is shown too). OUT_OF_DATE was not shown: the swapchain - // is recreated next time, and the caller sees VK_SUCCESS, since its work was submitted. - if (result == VK_SUCCESS || result == VK_SUBOPTIMAL_KHR) { - ++presented_; - if (planes) ++composed_; - if (tearing) { - last_tore_ = true; - ++tear_presents_; - } - if (capture_to_disk_ && capture_ && capture_ptr_ && capture_written_ < capture_limit_ && - (presented_ - 1) % std::uint64_t(capture_every_) == 0) - pending_capture_ = frame.done; - } - if (capture_ && capture_ptr_) { - captured_ = true; - captured_extent_ = extent_; - captured_format_ = format_; - } - if (result == VK_ERROR_SURFACE_LOST_KHR) { - // The surface was lost during the present (display disconnected, a driver reset of the window's - // plane): vkd3d keeps rendering to nothing, and the next present recreates surface and swapchain. - captured_ = false; - mark_surface_lost(); - result = VK_SUCCESS; - } - if (result == VK_ERROR_OUT_OF_DATE_KHR || result == VK_SUBOPTIMAL_KHR) { - stale_ = true; - result = VK_SUCCESS; - } - return result; - } - -private: - struct Frame { - VkCommandBuffer commands = VK_NULL_HANDLE; - VkFence done = VK_NULL_HANDLE; - VkSemaphore acquired = VK_NULL_HANDLE; - std::array views{}; // the plane views of the last composed present, until the frame is reused - }; - - // Whether `source` is a colour texture the device knows, so present() can refuse it before acquiring an image. - bool presentable(ResourceId source) { - std::shared_lock lock(context_.resource_mutex_); // the resource table (vulkan_backend.h) - const ResourceBinding* binding = context_.resolve(source); - return binding && binding->image && binding->aspects == VK_IMAGE_ASPECT_COLOR_BIT; - } - - // An image was acquired into `frame` but its blit was not submitted. An empty batch waits on the acquire - // semaphore and signals the frame's fence, so both are usable again; the swapchain is recreated on the next - // present, which gives back the image that was never presented. Returns `failure`, the error to report. - VkResult give_back(Frame& frame, VkResult failure) { - const VkDevice device = context_.device(); - if (vkResetFences_(device, 1, &frame.done) != VK_SUCCESS) return stop(failure); - const VkPipelineStageFlags wait_stage = VK_PIPELINE_STAGE_ALL_COMMANDS_BIT; - VkSubmitInfo submit_info{VK_STRUCTURE_TYPE_SUBMIT_INFO}; - submit_info.waitSemaphoreCount = 1; - submit_info.pWaitSemaphores = &frame.acquired; - submit_info.pWaitDstStageMask = &wait_stage; - VkResult submitted; - { - std::lock_guard lock(context_.submit_mutex()); - submitted = context_.vk.vkQueueSubmit(queue_, 1, &submit_info, frame.done); - } - if (submitted != VK_SUCCESS) return stop(failure); - stale_ = true; - return failure; - } - - // The swapchain image as a binding, for the barrier helpers. - ResourceBinding target_of(std::uint32_t image) const { - ResourceBinding target{}; - target.image = images_[image]; - target.format = format_; - target.aspects = VK_IMAGE_ASPECT_COLOR_BIT; - return target; - } - - // The frame's fence or acquire semaphore can no longer be trusted: no more presents (ok() is false), and the - // owner makes a new presenter. Returns `failure`. - VkResult stop(VkResult failure) { - ok_ = false; - return failure; - } - - // The window's surface is dead (VK_ERROR_SURFACE_LOST_KHR): the swapchain that presented into it is retired - // and the surface destroyed. The next submit_now() first tries the factory's recreate-surface callback; until - // it succeeds the presenter keeps the vkd3d "render to nothing" behaviour, not a sticky failure. - void mark_surface_lost() { - auto& vk = context_.vk; - const VkDevice device = context_.device(); - { - std::lock_guard lock(context_.submit_mutex()); - vk.vkQueueWaitIdle(queue_); // the old swapchain's images and semaphores may still be in use - release(swapchain_); - } - swapchain_ = VK_NULL_HANDLE; - if (surface_ && vkDestroySurfaceKHR_) vkDestroySurfaceKHR_(instance_, surface_, nullptr); - surface_ = VK_NULL_HANDLE; - surface_lost_ = true; - stale_ = true; - captured_ = false; - } - - void record(VkCommandBuffer commands, const ResourceBinding& binding, ResourceId source, std::uint32_t image, - const PresentRect* source_rect) { - auto& vk = context_.vk; - const ReplayFunctions& fn = context_.replay_; - vk.vkResetCommandBuffer(commands, 0); - VkCommandBufferBeginInfo begin{VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO}; - begin.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT; - vk.vkBeginCommandBuffer(commands, &begin); - - constexpr VkAccessFlags any = VK_ACCESS_MEMORY_READ_BIT | VK_ACCESS_MEMORY_WRITE_BIT; - const VkImageSubresourceRange range{VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1}; - // PRESENT is D3D12's common state: GENERAL for an ordinary texture. A never-written back buffer is - // zero-filled first, as any committed resource is. - const VkImageLayout common = image_layout(binding, VK_IMAGE_LAYOUT_GENERAL); - auto pieces = detail::current(&context_.tracker_, source, range, common); - detail::initialize(fn, commands, binding, source, pieces, common, &context_.tracker_); - for (const auto& piece : pieces) - detail::image_barrier(fn, commands, binding, piece.range, piece.layout, - VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, VK_ACCESS_MEMORY_WRITE_BIT, - VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, VK_ACCESS_TRANSFER_READ_BIT, - VK_PIPELINE_STAGE_TRANSFER_BIT); - ResourceBinding target{}; // the swapchain image, for the barrier helpers - target.image = images_[image]; - target.format = format_; - target.aspects = VK_IMAGE_ASPECT_COLOR_BIT; - // The acquire semaphore is waited at the transfer stage, so the swapchain image's barrier starts there. - detail::image_barrier(fn, commands, target, range, VK_IMAGE_LAYOUT_UNDEFINED, - VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 0, VK_PIPELINE_STAGE_TRANSFER_BIT, - VK_ACCESS_TRANSFER_WRITE_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT); - - const PresentRect whole{0, 0, std::int32_t(binding.width), std::int32_t(binding.height)}; - const PresentRect& src = source_rect ? *source_rect : whole; - const std::int32_t sw = src.right - src.left, sh = src.bottom - src.top; - const std::int32_t dw = std::int32_t(extent_.width), dh = std::int32_t(extent_.height); - VkImageBlit blit{}; - blit.srcSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1}; - blit.srcOffsets[0] = {src.left, src.top, 0}; - blit.srcOffsets[1] = {src.right, src.bottom, 1}; - blit.dstSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1}; - blit.dstOffsets[1] = {dw, dh, 1}; - vkCmdBlitImage_(commands, binding.image, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, images_[image], - VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, &blit, - sw == dw && sh == dh ? VK_FILTER_NEAREST : blit_filter(binding.format)); - - finish_image(commands, image); - for (const auto& piece : pieces) - detail::image_barrier(fn, commands, binding, piece.range, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, - piece.layout, VK_ACCESS_TRANSFER_READ_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, any, - VK_PIPELINE_STAGE_ALL_COMMANDS_BIT); - vk.vkEndCommandBuffer(commands); - } - - struct RollbackPlane { - ResourceId id{}; - bool tracked = false; - VkImageLayout layout = VK_IMAGE_LAYOUT_UNDEFINED; - }; - - void drop_views(Frame& frame) { - for (VkImageView& view : frame.views) - if (view) context_.vk.vkDestroyImageView(context_.device(), view, nullptr); - frame.views = {}; - } - - // The compose pass and its target image, for the swapchain's current size. - bool prepare_compose() { - if (!composer_) { - VkPhysicalDeviceMemoryProperties memory{}; - if (!vkGetPhysicalDeviceMemoryProperties_) return false; - vkGetPhysicalDeviceMemoryProperties_(physical_, &memory); - composer_ = std::make_unique(context_, memory); - } - if (!composer_->ready()) return false; - if (composer_->target() && composer_->extent().width == extent_.width && - composer_->extent().height == extent_.height) - return true; - { - std::lock_guard lock(context_.submit_mutex()); - context_.vk.vkQueueWaitIdle(queue_); // the old target may still be in use - } - bool changed = false; - return composer_->ensure_target(extent_, changed); - } - - // Records the composition of `planes` and its copy to swapchain image `image`. False, with nothing recorded and the - // tracker untouched, when a view cannot be made. The caller holds the resource and tracker locks. - bool record_planes(Frame& frame, std::uint32_t slot, const std::array& current, - const PresentPlanes& planes, std::uint32_t image) { - auto& vk = context_.vk; - const ReplayFunctions& fn = context_.replay_; - if (composer_->target() == VK_NULL_HANDLE || composer_->extent().width != extent_.width || - composer_->extent().height != extent_.height) - return false; // the target does not match the swapchain: nothing recorded - drop_views(frame); - for (std::uint32_t i = 0; i < planes.count; ++i) { - VkImageViewCreateInfo view_info{VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO}; - view_info.image = current[i].image; - view_info.viewType = VK_IMAGE_VIEW_TYPE_2D; - view_info.format = current[i].format; - view_info.subresourceRange = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1}; - if (vk.vkCreateImageView(context_.device(), &view_info, nullptr, &frame.views[i]) != VK_SUCCESS) { - drop_views(frame); - return false; - } - } - if (planes.count == 1) frame.views[1] = VK_NULL_HANDLE; // the shader never reads it; plane 0's view is bound twice - - VkCommandBuffer commands = frame.commands; - vk.vkResetCommandBuffer(commands, 0); - VkCommandBufferBeginInfo begin{VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO}; - begin.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT; - vk.vkBeginCommandBuffer(commands, &begin); - - constexpr VkAccessFlags any = VK_ACCESS_MEMORY_READ_BIT | VK_ACCESS_MEMORY_WRITE_BIT; - const VkImageSubresourceRange range{VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1}; - const bool same = planes.count > 1 && planes.plane[1].source == planes.plane[0].source; - std::array pieces; - std::array read_layout{}; - // Each distinct source: its PRESENT (common) layout, then readable by the compute pass. A never-written back buffer - // is zero-filled first, as any committed resource is. - for (std::uint32_t i = 0; i < planes.count; ++i) { - read_layout[i] = image_layout(current[i], VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL); - if (i == 1 && same) continue; - const VkImageLayout common = image_layout(current[i], VK_IMAGE_LAYOUT_GENERAL); - pieces[i] = detail::current(&context_.tracker_, planes.plane[i].source, range, common); - detail::initialize(fn, commands, current[i], planes.plane[i].source, pieces[i], common, &context_.tracker_); - for (const auto& piece : pieces[i]) - detail::image_barrier(fn, commands, current[i], piece.range, piece.layout, read_layout[i], - VK_ACCESS_MEMORY_WRITE_BIT, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, - VK_ACCESS_SHADER_READ_BIT, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT); - } - - // The pass: destinations in output pixels, sources in texels. - PresentComposePush push{}; - const float out_w = float(extent_.width), out_h = float(extent_.height); - std::uint32_t* flags[2] = {&push.flags0, &push.flags1}; - float* dest[2] = {push.dest0, push.dest1}; - float* src[2] = {push.src0, push.src1}; - for (std::uint32_t i = 0; i < planes.count; ++i) { - const PresentPlane& plane = planes.plane[i]; - dest[i][0] = plane.dest[0] * out_w; - dest[i][1] = plane.dest[1] * out_h; - dest[i][2] = plane.dest[2] * out_w; - dest[i][3] = plane.dest[3] * out_h; - const PresentRect whole{0, 0, std::int32_t(current[i].width), std::int32_t(current[i].height)}; - const PresentRect& r = plane.has_source_rect ? plane.source_rect : whole; - src[i][0] = float(r.left); - src[i][1] = float(r.top); - src[i][2] = float(r.right); - src[i][3] = float(r.bottom); - *flags[i] = (plane.point_filter ? compose_flag::point : 0u) | - (detail::is_srgb_format(current[i].format) ? compose_flag::srgb_source : 0u) | - (plane.hdr10 ? compose_flag::hdr10 : 0u) | (plane.straight_alpha ? compose_flag::straight_alpha : 0u); - } - push.plane_count = planes.count; - push.out_hdr = (hdr_active_ || force_hdr_encoding_) ? 1u : 0u; - push.sdr_white = planes.sdr_white_nits; - push.sdr_eotf = std::uint32_t(planes.sdr_eotf); - push.hdr_peak = planes.hdr_peak_nits; - push.width = extent_.width; - push.height = extent_.height; - composer_->record(commands, slot, frame.views[0], read_layout[0], frame.views[1] ? frame.views[1] : frame.views[0], - read_layout[1] ? read_layout[1] : read_layout[0], push); - - // The swapchain image, written by a copy of the composed image (same size: no scaling). - ResourceBinding target = target_of(image); - detail::image_barrier(fn, commands, target, range, VK_IMAGE_LAYOUT_UNDEFINED, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 0, - VK_PIPELINE_STAGE_TRANSFER_BIT, VK_ACCESS_TRANSFER_WRITE_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT); - VkImageBlit blit{}; - blit.srcSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1}; - blit.srcOffsets[1] = {std::int32_t(extent_.width), std::int32_t(extent_.height), 1}; - blit.dstSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1}; - blit.dstOffsets[1] = {std::int32_t(extent_.width), std::int32_t(extent_.height), 1}; - vkCmdBlitImage_(commands, composer_->target(), VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, images_[image], - VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, &blit, VK_FILTER_NEAREST); - finish_image(commands, image); - for (std::uint32_t i = 0; i < planes.count; ++i) { - if (i == 1 && same) continue; - for (const auto& piece : pieces[i]) - detail::image_barrier(fn, commands, current[i], piece.range, read_layout[i], piece.layout, - VK_ACCESS_SHADER_READ_BIT, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, any, - VK_PIPELINE_STAGE_ALL_COMMANDS_BIT); - } - vk.vkEndCommandBuffer(commands); - return true; - } - - // vkGetPhysicalDeviceFormatProperties, optimal tiling, cached per format. - VkFormatFeatureFlags format_features(VkFormat format) { - const auto it = features_.find(format); - if (it != features_.end()) return it->second; - VkFormatProperties properties{}; - if (vkGetPhysicalDeviceFormatProperties_) vkGetPhysicalDeviceFormatProperties_(physical_, format, &properties); - return features_[format] = properties.optimalTilingFeatures; - } - // Scaling blits filter bilinearly when the source format allows it, else take the nearest texel. - VkFilter blit_filter(VkFormat source) { - return (format_features(source) & VK_FORMAT_FEATURE_SAMPLED_IMAGE_FILTER_LINEAR_BIT) ? VK_FILTER_LINEAR - : VK_FILTER_NEAREST; - } - - VkResult acquire(VkSemaphore semaphore, std::uint32_t* image) { - for (;;) { - const VkResult result = vkAcquireNextImageKHR_(context_.device(), swapchain_, 50'000'000, semaphore, - VK_NULL_HANDLE, image); - if (result != VK_TIMEOUT && result != VK_NOT_READY) return result; - if (should_abort()) return VK_NOT_READY; - } - } - - // Clears the swapchain image to opaque black. - void record_blank(VkCommandBuffer commands, std::uint32_t image) { - auto& vk = context_.vk; - const ReplayFunctions& fn = context_.replay_; - vk.vkResetCommandBuffer(commands, 0); - VkCommandBufferBeginInfo begin{VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO}; - begin.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT; - vk.vkBeginCommandBuffer(commands, &begin); - const VkImageSubresourceRange range{VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1}; - detail::image_barrier(fn, commands, target_of(image), range, VK_IMAGE_LAYOUT_UNDEFINED, - VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 0, VK_PIPELINE_STAGE_TRANSFER_BIT, - VK_ACCESS_TRANSFER_WRITE_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT); - const VkClearColorValue black{{0.0f, 0.0f, 0.0f, 1.0f}}; - vkCmdClearColorImage_(commands, images_[image], VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, &black, 1, &range); - finish_image(commands, image); - vk.vkEndCommandBuffer(commands); - } - - // The swapchain image is written (TRANSFER_DST): optionally copy it to the capture buffer, then hand it to - // the presentation engine. - void finish_image(VkCommandBuffer commands, std::uint32_t image) { - const ReplayFunctions& fn = context_.replay_; - const VkImageSubresourceRange range{VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1}; - VkImageLayout layout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL; - VkAccessFlags access = VK_ACCESS_TRANSFER_WRITE_BIT; - if (capture_ && capture_buffer_) { - // Two frames may be in flight and share `capture_buffer_`: serialize the prior frame's capture copy - // before overwriting it, while moving this frame's swapchain image to TRANSFER_SRC. - VkBufferMemoryBarrier capture_waw{VK_STRUCTURE_TYPE_BUFFER_MEMORY_BARRIER}; - capture_waw.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT; - capture_waw.dstAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT; - capture_waw.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; - capture_waw.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; - capture_waw.buffer = capture_buffer_; - capture_waw.offset = 0; - capture_waw.size = VK_WHOLE_SIZE; - VkImageMemoryBarrier to_src{VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER}; - to_src.srcAccessMask = access; - to_src.dstAccessMask = VK_ACCESS_TRANSFER_READ_BIT; - to_src.oldLayout = layout; - to_src.newLayout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL; - to_src.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; - to_src.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; - to_src.image = images_[image]; - to_src.subresourceRange = range; - fn.pipeline_barrier(commands, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, 0, 0, - nullptr, 1, &capture_waw, 1, &to_src); - VkBufferImageCopy copy{}; - copy.imageSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1}; - copy.imageExtent = {extent_.width, extent_.height, 1}; - fn.copy_image_to_buffer(commands, images_[image], VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, capture_buffer_, 1, - ©); - layout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL; - access = VK_ACCESS_TRANSFER_READ_BIT; - } - detail::image_barrier(fn, commands, target_of(image), range, layout, VK_IMAGE_LAYOUT_PRESENT_SRC_KHR, access, - VK_PIPELINE_STAGE_TRANSFER_BIT, 0, VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT); - } - - // (Re)creates the capture buffer for the current swapchain size: host visible, coherent, persistently mapped. - bool make_capture_buffer() { - release_capture(); - auto& vk = context_.vk; - const VkDevice device = context_.device(); - capture_size_ = VkDeviceSize(extent_.width) * extent_.height * 4; - VkBufferCreateInfo info{VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO}; - info.size = capture_size_; - info.usage = VK_BUFFER_USAGE_TRANSFER_DST_BIT; - info.sharingMode = VK_SHARING_MODE_EXCLUSIVE; - if (vk.vkCreateBuffer(device, &info, nullptr, &capture_buffer_) != VK_SUCCESS) return false; - VkMemoryRequirements requirements{}; - vk.vkGetBufferMemoryRequirements(device, capture_buffer_, &requirements); - VkPhysicalDeviceMemoryProperties memory{}; - vkGetPhysicalDeviceMemoryProperties_(physical_, &memory); - constexpr VkMemoryPropertyFlags wanted = VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT; - std::uint32_t type = UINT32_MAX; - for (std::uint32_t i = 0; i < memory.memoryTypeCount; ++i) - if ((requirements.memoryTypeBits & (1u << i)) && (memory.memoryTypes[i].propertyFlags & wanted) == wanted) { - type = i; - break; - } - VkMemoryAllocateInfo allocate{VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO}; - allocate.allocationSize = requirements.size; - allocate.memoryTypeIndex = type; - void* mapped = nullptr; - if (type == UINT32_MAX || vk.vkAllocateMemory(device, &allocate, nullptr, &capture_memory_) != VK_SUCCESS || - vk.vkBindBufferMemory(device, capture_buffer_, capture_memory_, 0) != VK_SUCCESS || - vk.vkMapMemory(device, capture_memory_, 0, VK_WHOLE_SIZE, 0, &mapped) != VK_SUCCESS) { - release_capture(); - return false; - } - capture_ptr_ = static_cast(mapped); - captured_ = false; - return true; - } - - void release_capture() { - auto& vk = context_.vk; - const VkDevice device = context_.device(); - if (capture_memory_) vk.vkFreeMemory(device, capture_memory_, nullptr); // unmaps - if (capture_buffer_) vk.vkDestroyBuffer(device, capture_buffer_, nullptr); - capture_memory_ = VK_NULL_HANDLE; - capture_buffer_ = VK_NULL_HANDLE; - capture_ptr_ = nullptr; - captured_ = false; - } - - // The name VkFormat has in the index; the few formats a capture can be written from, else its number. - static const char* capture_format_name(VkFormat format) { - switch (format) { - case VK_FORMAT_B8G8R8A8_UNORM: return "VK_FORMAT_B8G8R8A8_UNORM"; - case VK_FORMAT_B8G8R8A8_SRGB: return "VK_FORMAT_B8G8R8A8_SRGB"; - case VK_FORMAT_R8G8B8A8_UNORM: return "VK_FORMAT_R8G8B8A8_UNORM"; - case VK_FORMAT_R8G8B8A8_SRGB: return "VK_FORMAT_R8G8B8A8_SRGB"; - case VK_FORMAT_A2B10G10R10_UNORM_PACK32: return "VK_FORMAT_A2B10G10R10_UNORM_PACK32"; - case VK_FORMAT_A2R10G10B10_UNORM_PACK32: return "VK_FORMAT_A2R10G10B10_UNORM_PACK32"; - default: return "unknown"; - } - } - - VkResult finish_pending_capture() { - if (!pending_capture_) return VK_SUCCESS; - const VkResult waited = vkWaitForFences_(context_.device(), 1, &pending_capture_, VK_TRUE, UINT64_MAX); - pending_capture_ = VK_NULL_HANDLE; - if (waited == VK_SUCCESS) write_capture(); - return waited; - } - - void write_capture() { - const VkExtent2D extent = captured_extent_; - const VkFormat format = captured_format_; - const std::uint64_t number = presented_; - const std::size_t texels = std::size_t(extent.width) * extent.height; - if (!capture_ptr_ || !texels || texels > capture_size_ / 4) return; - std::vector rgb(texels * 3); - std::uint64_t sum[3] = {0, 0, 0}; - const std::uint8_t* src = capture_ptr_; - switch (format) { - case VK_FORMAT_B8G8R8A8_UNORM: - case VK_FORMAT_B8G8R8A8_SRGB: - for (std::size_t i = 0; i < texels; ++i) { - const std::uint8_t b = src[i * 4 + 0], g = src[i * 4 + 1], r = src[i * 4 + 2]; - rgb[i * 3 + 0] = r; - rgb[i * 3 + 1] = g; - rgb[i * 3 + 2] = b; - sum[0] += r; - sum[1] += g; - sum[2] += b; - } - break; - case VK_FORMAT_R8G8B8A8_UNORM: - case VK_FORMAT_R8G8B8A8_SRGB: - for (std::size_t i = 0; i < texels; ++i) { - const std::uint8_t r = src[i * 4 + 0], g = src[i * 4 + 1], b = src[i * 4 + 2]; - rgb[i * 3 + 0] = r; - rgb[i * 3 + 1] = g; - rgb[i * 3 + 2] = b; - sum[0] += r; - sum[1] += g; - sum[2] += b; - } - break; - case VK_FORMAT_A2B10G10R10_UNORM_PACK32: - case VK_FORMAT_A2R10G10B10_UNORM_PACK32: { - const bool bgra = format == VK_FORMAT_A2R10G10B10_UNORM_PACK32; // B in the low bits - for (std::size_t i = 0; i < texels; ++i) { - std::uint32_t word = 0; - std::memcpy(&word, src + i * 4, sizeof word); - const std::uint32_t low = word & 0x3ffu, mid = (word >> 10) & 0x3ffu, high = (word >> 20) & 0x3ffu; - const auto to8 = [](std::uint32_t v) { return std::uint8_t((v * 255u + 511u) / 1023u); }; - const std::uint8_t r = to8(bgra ? high : low), g = to8(mid), b = to8(bgra ? low : high); - rgb[i * 3 + 0] = r; - rgb[i * 3 + 1] = g; - rgb[i * 3 + 2] = b; - sum[0] += r; - sum[1] += g; - sum[2] += b; - } - break; - } - default: return; // not a format the capture can be written from (recreate() refused the others) - } - char name[64]; - std::snprintf(name, sizeof name, "frame_%05llu.ppm", static_cast(number)); - const std::filesystem::path path = capture_dir_ / name; - std::ofstream file(path, std::ios::binary | std::ios::trunc); - if (!file) { - RT_LOG_ERROR("present: cannot write %s\n", detail::path_text(path).c_str()); - return; - } - file << "P6\n" << extent.width << ' ' << extent.height << "\n255\n"; - file.write(reinterpret_cast(rgb.data()), std::streamsize(rgb.size())); - file.close(); - const double scale = 1.0 / double(texels); - const double mean[3] = {sum[0] * scale, sum[1] * scale, sum[2] * scale}; - std::ofstream index(capture_dir_ / "index.txt", std::ios::app); - if (index) - index << "frame " << number << " format " << int(format) << " (" << capture_format_name(format) - << ") extent " << extent.width << 'x' << extent.height << " mean rgb " << std::fixed - << std::setprecision(2) << mean[0] << ' ' << mean[1] << ' ' << mean[2] << '\n'; - ++capture_written_; - RT_LOG_DEBUG("present: capture %s (%ux%u, mean rgb %.2f %.2f %.2f)\n", name, extent.width, - extent.height, mean[0], mean[1], mean[2]); - } - - // (Re)creates the swapchain for the surface's current size. A zero-sized surface (minimised) leaves no - // swapchain and is retried on the next present. Keep the old swapchain until the surface queries succeed and - // the replacement can be attempted. An incomplete replacement stays stale so the next present tries again. - bool recreate(bool vsync, bool srgb, bool hdr = false) { - auto& vk = context_.vk; - const VkDevice device = context_.device(); - { - std::lock_guard lock(context_.submit_mutex()); - vk.vkQueueWaitIdle(queue_); // the old swapchain's images and semaphores may still be in use - } - if (finish_pending_capture() != VK_SUCCESS) return false; - stale_ = true; // until this succeeds - tear_mode_ = VK_PRESENT_MODE_MAX_ENUM_KHR; - VkSurfaceCapabilitiesKHR caps{}; - if (vkGetPhysicalDeviceSurfaceCapabilitiesKHR_(physical_, surface_, &caps) != VK_SUCCESS) return false; - VkExtent2D extent = caps.currentExtent; - // When the platform leaves the swapchain extent to the application (0xFFFFFFFF, as on Intel UHD / Win32 WSI), - // query the window client area or fall back to the last known extent, and clamp to the surface bounds (D3D-165). - if (extent.width == 0xFFFFFFFF || extent.height == 0xFFFFFFFF) { - if (extent_fn_) extent = extent_fn_(); - // ponytail: if no window extent function was supplied, fall back to last extent_ or minImageExtent - if (extent.width == 0xFFFFFFFF || extent.height == 0xFFFFFFFF || (extent.width == 0 && extent.height == 0)) { - extent = extent_.width && extent_.height ? extent_ : caps.minImageExtent; - } - if (extent.width && extent.height) { - extent.width = std::clamp(extent.width, caps.minImageExtent.width, caps.maxImageExtent.width); - extent.height = std::clamp(extent.height, caps.minImageExtent.height, caps.maxImageExtent.height); - } - } - if (extent.width == 0 || extent.height == 0) { - { - std::lock_guard lock(context_.submit_mutex()); - release(swapchain_); - } - swapchain_ = VK_NULL_HANDLE; - vsync_ = vsync; - swapchain_srgb_ = srgb; - swapchain_hdr_req_ = hdr; - hdr_active_ = false; - stale_ = false; - return true; - } - VkImageUsageFlags usage = VK_IMAGE_USAGE_TRANSFER_DST_BIT; - if (capture_) usage |= VK_IMAGE_USAGE_TRANSFER_SRC_BIT; - if ((caps.supportedUsageFlags & usage) != usage) return false; - // Not used by the presenter itself (it blits or copies into the images), but overlays that hook the swapchain - // draw their own frame into its images through a framebuffer, which needs COLOR_ATTACHMENT: without it - // Bandicam's VK_LAYER_bandicam_helper builds framebuffers and image views on images that don't allow it - // (VUID-VkFramebufferCreateInfo-pAttachments-00877, VUID-VkImageViewCreateInfo-image-04441). The surface - // reports it for every swapchain (the spec requires it in supportedUsageFlags), and the DXGI swapchain - // (dxgi_swapchain.h) already asks for it. - if (caps.supportedUsageFlags & VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT) usage |= VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT; - - std::uint32_t count = 0; - if (vkGetPhysicalDeviceSurfaceFormatsKHR_(physical_, surface_, &count, nullptr) != VK_SUCCESS || !count) - return false; - std::vector formats(count); - if (vkGetPhysicalDeviceSurfaceFormatsKHR_(physical_, surface_, &count, formats.data()) != VK_SUCCESS || !count) - return false; - formats.resize(count); - // An sRGB source wants an sRGB swapchain (the blit decodes and encodes, which cancel); any other source - // wants UNORM (the bytes go through as they are). BGRA before RGBA, as the surface lists them. - VkSurfaceFormatKHR chosen = formats[0]; - bool found = false; - bool chose_hdr = false; - if (hdr) { - // A plane in HDR10 (PQ, Rec.2020): the surface's ST.2084 format, which needs VK_EXT_swapchain_colorspace on - // the instance. Without it the composition converts to SDR. - for (const VkFormat wanted : {VK_FORMAT_A2B10G10R10_UNORM_PACK32, VK_FORMAT_A2R10G10B10_UNORM_PACK32}) { - for (const auto& f : formats) - if (f.format == wanted && f.colorSpace == VK_COLOR_SPACE_HDR10_ST2084_EXT) { - chosen = f; - found = chose_hdr = true; - break; - } - if (found) break; - } - if (!found && !warned_hdr_) { - warned_hdr_ = true; - RT_LOG_WARN("present: the surface has no HDR10 (ST.2084) format; HDR10 planes are converted to " - "SDR by tone mapping\n"); - } - } - for (const VkFormat wanted : srgb ? std::array{VK_FORMAT_B8G8R8A8_SRGB, VK_FORMAT_R8G8B8A8_SRGB} - : std::array{VK_FORMAT_B8G8R8A8_UNORM, VK_FORMAT_R8G8B8A8_UNORM}) { - if (chose_hdr) break; - for (const auto& f : formats) - if (f.format == wanted && f.colorSpace == VK_COLOR_SPACE_SRGB_NONLINEAR_KHR) { - chosen = f; - found = true; - break; - } - if (found) break; - } - if (!found && srgb) { - if (!warned_srgb_) - RT_LOG_WARN("present: the surface has no sRGB 8-bit format; an sRGB back buffer is shown darker\n"); - warned_srgb_ = true; - for (const auto& f : formats) - if ((f.format == VK_FORMAT_B8G8R8A8_UNORM || f.format == VK_FORMAT_R8G8B8A8_UNORM) && - f.colorSpace == VK_COLOR_SPACE_SRGB_NONLINEAR_KHR) { - chosen = f; - break; - } - } - if (vkGetPhysicalDeviceSurfacePresentModesKHR_(physical_, surface_, &count, nullptr) != VK_SUCCESS || !count) - return false; - std::vector modes(count); - if (vkGetPhysicalDeviceSurfacePresentModesKHR_(physical_, surface_, &count, modes.data()) != VK_SUCCESS || !count) - return false; - modes.resize(count); - VkPresentModeKHR mode = VK_PRESENT_MODE_FIFO_KHR; // always available - if (!vsync) { - for (const VkPresentModeKHR wanted : {VK_PRESENT_MODE_MAILBOX_KHR, VK_PRESENT_MODE_IMMEDIATE_KHR}) - if (std::find(modes.begin(), modes.end(), wanted) != modes.end()) { - mode = wanted; - break; - } - } - - VkSwapchainCreateInfoKHR info{VK_STRUCTURE_TYPE_SWAPCHAIN_CREATE_INFO_KHR}; - info.surface = surface_; - info.minImageCount = std::max(caps.minImageCount + 1, 2u); - if (caps.maxImageCount) info.minImageCount = std::min(info.minImageCount, caps.maxImageCount); - info.imageFormat = chosen.format; - info.imageColorSpace = chosen.colorSpace; - info.imageExtent = extent; - info.imageArrayLayers = 1; - info.imageUsage = usage; - info.imageSharingMode = VK_SHARING_MODE_EXCLUSIVE; - info.preTransform = caps.currentTransform; - info.compositeAlpha = VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR; - if (!(caps.supportedCompositeAlpha & info.compositeAlpha)) info.compositeAlpha = VK_COMPOSITE_ALPHA_INHERIT_BIT_KHR; - info.presentMode = mode; -#ifdef LEONIDA_SWAPCHAIN_MAINTENANCE1 - // A vsync swapchain that can also be presented in IMMEDIATE (or FIFO_RELAXED), switched per present. - VkSwapchainPresentModesCreateInfoEXT switchable{VK_STRUCTURE_TYPE_SWAPCHAIN_PRESENT_MODES_CREATE_INFO_EXT}; - std::array switchable_modes{VK_PRESENT_MODE_FIFO_KHR, VK_PRESENT_MODE_MAX_ENUM_KHR}; - VkPresentModeKHR tear = VK_PRESENT_MODE_MAX_ENUM_KHR; - if (vsync && mode == VK_PRESENT_MODE_FIFO_KHR) tear = find_tear_mode(modes, info.minImageCount, info.imageUsage, info.imageExtent); - if (tear != VK_PRESENT_MODE_MAX_ENUM_KHR) { - switchable_modes[1] = tear; - switchable.presentModeCount = 2; - switchable.pPresentModes = switchable_modes.data(); - info.pNext = &switchable; - } -#endif - info.clipped = VK_TRUE; - const VkSwapchainKHR old = swapchain_; - swapchain_ = VK_NULL_HANDLE; - info.oldSwapchain = old; - VkSwapchainKHR fresh = VK_NULL_HANDLE; - const VkResult created = vkCreateSwapchainKHR_(device, &info, nullptr, &fresh); - { - std::lock_guard lock(context_.submit_mutex()); - release(old); // retired by the creation attempt, whether or not it succeeded - } - if (created != VK_SUCCESS) return false; - - std::vector images; - std::vector ready; - const auto discard = [&] { - for (VkSemaphore semaphore : ready) vk.vkDestroySemaphore(device, semaphore, nullptr); - // The WSI implementation may block on the device here too. - std::lock_guard lock(context_.submit_mutex()); - vkDestroySwapchainKHR_(device, fresh, nullptr); - return false; - }; - if (vkGetSwapchainImagesKHR_(device, fresh, &count, nullptr) != VK_SUCCESS || !count) return discard(); - images.resize(count); - if (vkGetSwapchainImagesKHR_(device, fresh, &count, images.data()) != VK_SUCCESS) return discard(); - images.resize(count); - for (std::uint32_t i = 0; i < count; ++i) { - VkSemaphoreCreateInfo semaphore_info{VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO}; - VkSemaphore semaphore = VK_NULL_HANDLE; - if (vk.vkCreateSemaphore(device, &semaphore_info, nullptr, &semaphore) != VK_SUCCESS) return discard(); - ready.push_back(semaphore); - } - swapchain_ = fresh; -#ifdef LEONIDA_SWAPCHAIN_MAINTENANCE1 - tear_mode_ = tear; -#endif - images_ = std::move(images); - ready_ = std::move(ready); - format_ = chosen.format; - extent_ = extent; - extent_packed_ = (std::uint64_t(extent.width) << 32) | extent.height; - hdr_active_ = chose_hdr; - if (capture_) { - // A capture that cannot be made fails the recreation with the swapchain in place and stale_ still set. - const bool four_bytes = format_ == VK_FORMAT_B8G8R8A8_UNORM || format_ == VK_FORMAT_R8G8B8A8_UNORM || - format_ == VK_FORMAT_B8G8R8A8_SRGB || format_ == VK_FORMAT_R8G8B8A8_SRGB || - format_ == VK_FORMAT_A2B10G10R10_UNORM_PACK32 || - format_ == VK_FORMAT_A2R10G10B10_UNORM_PACK32; - if (!four_bytes || !make_capture_buffer()) return false; - } - vsync_ = vsync; - swapchain_srgb_ = srgb; - swapchain_hdr_req_ = hdr; - stale_ = false; - return true; - } - -#ifdef LEONIDA_SWAPCHAIN_MAINTENANCE1 - // The mode a FIFO swapchain can also present in, so that a late frame can be shown at once: IMMEDIATE, else - // FIFO_RELAXED, each only if the surface lists it and reports it compatible with FIFO (VK_KHR_surface_maintenance1). - // `min_images` is raised to what that mode needs too. The mode must also accept the swapchain's image usage and - // extent (its capabilities can differ from FIFO's). MAX_ENUM when there is none or the extension is not in use. - VkPresentModeKHR find_tear_mode(const std::vector& modes, std::uint32_t& min_images, - VkImageUsageFlags usage, VkExtent2D extent) { - if (!maintenance1_ || !vkGetPhysicalDeviceSurfaceCapabilities2KHR_) return VK_PRESENT_MODE_MAX_ENUM_KHR; - // The capabilities of the surface for one present mode, and the modes it can switch to from there. - const auto ask = [&](VkPresentModeKHR asked, VkSurfaceCapabilitiesKHR& caps, - std::array* compatible, std::uint32_t* compatible_count) { - VkSurfacePresentModeEXT for_mode{VK_STRUCTURE_TYPE_SURFACE_PRESENT_MODE_EXT}; - for_mode.presentMode = asked; - VkPhysicalDeviceSurfaceInfo2KHR surface_info{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SURFACE_INFO_2_KHR, &for_mode}; - surface_info.surface = surface_; - VkSurfacePresentModeCompatibilityEXT compat{VK_STRUCTURE_TYPE_SURFACE_PRESENT_MODE_COMPATIBILITY_EXT}; - if (compatible) { - compat.presentModeCount = std::uint32_t(compatible->size()); - compat.pPresentModes = compatible->data(); - } - VkSurfaceCapabilities2KHR out{VK_STRUCTURE_TYPE_SURFACE_CAPABILITIES_2_KHR, compatible ? &compat : nullptr}; - if (vkGetPhysicalDeviceSurfaceCapabilities2KHR_(physical_, &surface_info, &out) != VK_SUCCESS) return false; - caps = out.surfaceCapabilities; - if (compatible_count) *compatible_count = std::min(compat.presentModeCount, 16); - return true; - }; - VkSurfaceCapabilitiesKHR fifo_caps{}; - std::array compatible{}; - std::uint32_t compatible_count = 0; - if (!ask(VK_PRESENT_MODE_FIFO_KHR, fifo_caps, &compatible, &compatible_count)) return VK_PRESENT_MODE_MAX_ENUM_KHR; - for (const VkPresentModeKHR wanted : {VK_PRESENT_MODE_IMMEDIATE_KHR, VK_PRESENT_MODE_FIFO_RELAXED_KHR}) { - if (std::find(modes.begin(), modes.end(), wanted) == modes.end() || - std::find(compatible.begin(), compatible.begin() + compatible_count, wanted) == - compatible.begin() + compatible_count) - continue; - VkSurfaceCapabilitiesKHR mode_caps{}; - if (!ask(wanted, mode_caps, nullptr, nullptr)) continue; - if ((mode_caps.supportedUsageFlags & usage) != usage) continue; - if (extent.width < mode_caps.minImageExtent.width || extent.height < mode_caps.minImageExtent.height || - extent.width > mode_caps.maxImageExtent.width || extent.height > mode_caps.maxImageExtent.height) - continue; - // One image count that every mode of the swapchain accepts. - std::uint32_t count = std::max({min_images, fifo_caps.minImageCount, mode_caps.minImageCount}); - const std::uint32_t most = std::min(fifo_caps.maxImageCount ? fifo_caps.maxImageCount : UINT32_MAX, - mode_caps.maxImageCount ? mode_caps.maxImageCount : UINT32_MAX); - if (count > most) continue; - min_images = count; - return wanted; - } - return VK_PRESENT_MODE_MAX_ENUM_KHR; - } -#endif - - // Destroys a swapchain that is being replaced (or the last one), with the per-image semaphores that went with it. - void release(VkSwapchainKHR swapchain) { - const VkDevice device = context_.device(); - for (VkSemaphore semaphore : ready_) - if (semaphore) context_.vk.vkDestroySemaphore(device, semaphore, nullptr); - ready_.clear(); - images_.clear(); - if (swapchain) vkDestroySwapchainKHR_(device, swapchain, nullptr); - } - - VulkanContext& context_; - VkInstance instance_; - VkPhysicalDevice physical_; - VkQueue queue_; - mutable std::recursive_mutex present_mutex_; // all presenter state: submit(), a deferred present, the accessors - mutable std::mutex abort_mutex_; // abort_ alone: set_abort() must work while a present waits - std::deque deferred_; // presents queued behind held work, in call order - VkSurfaceKHR surface_; - bool maintenance1_ = false; // VK_KHR/EXT_swapchain_maintenance1 (and the surface extension) are enabled - VkPresentModeKHR tear_mode_ = VK_PRESENT_MODE_MAX_ENUM_KHR; // set with the swapchain, see tear_mode() - std::atomic last_tore_{false}; - std::atomic extent_packed_{0}; // extent_ for readers that must not wait for a present - std::atomic tear_presents_{0}; - VkSwapchainKHR swapchain_ = VK_NULL_HANDLE; - VkFormat format_ = VK_FORMAT_UNDEFINED; - VkExtent2D extent_{}; - std::vector images_; - std::vector ready_; // per swapchain image: blit done, present may start - std::array frames_{}; - VkCommandPool pool_ = VK_NULL_HANDLE; - std::uint64_t frame_index_ = 0; - std::atomic presented_{0}; - bool vsync_ = true; - bool stale_ = false; - bool ok_ = false; - bool swapchain_srgb_ = false; // the swapchain format follows the source being presented (set once it exists) - bool swapchain_hdr_req_ = false; // the swapchain was built for an HDR10 request (it has the format only if hdr_active_) - bool hdr_active_ = false; - std::atomic composed_{0}; - std::atomic force_hdr_encoding_{false}; - bool warned_hdr_ = false; - std::unique_ptr composer_; - std::function abort_; - std::function extent_fn_; - std::function recreate_surface_fn_; // makes a new Win32 surface for the same window - bool surface_lost_ = false; // set by mark_surface_lost(); cleared once a new surface was created - std::map features_; - bool warned_srgb_ = false; - bool capture_ = false; - VkBuffer capture_buffer_ = VK_NULL_HANDLE; - VkDeviceMemory capture_memory_ = VK_NULL_HANDLE; - VkDeviceSize capture_size_ = 0; - std::uint8_t* capture_ptr_ = nullptr; - bool captured_ = false; - VkExtent2D captured_extent_{}; - VkFormat captured_format_ = VK_FORMAT_UNDEFINED; - // LEONIDA_CAPTURE: write the copies the staging buffer makes to (see finish_pending_capture()). - bool capture_to_disk_ = false; - std::filesystem::path capture_dir_; - int capture_every_ = 30; // presented frames between files - int capture_limit_ = 24; // files at most - VkFence pending_capture_ = VK_NULL_HANDLE; // owns the shared staging bytes until written - std::uint64_t capture_written_ = 0; - - PFN_vkGetPhysicalDeviceSurfaceSupportKHR vkGetPhysicalDeviceSurfaceSupportKHR_ = nullptr; - PFN_vkGetPhysicalDeviceSurfaceCapabilitiesKHR vkGetPhysicalDeviceSurfaceCapabilitiesKHR_ = nullptr; - PFN_vkGetPhysicalDeviceSurfaceFormatsKHR vkGetPhysicalDeviceSurfaceFormatsKHR_ = nullptr; - PFN_vkGetPhysicalDeviceSurfacePresentModesKHR vkGetPhysicalDeviceSurfacePresentModesKHR_ = nullptr; - PFN_vkGetPhysicalDeviceSurfaceCapabilities2KHR vkGetPhysicalDeviceSurfaceCapabilities2KHR_ = nullptr; - PFN_vkDestroySurfaceKHR vkDestroySurfaceKHR_ = nullptr; - PFN_vkGetDeviceProcAddr vkGetDeviceProcAddr_ = nullptr; - PFN_vkCreateSwapchainKHR vkCreateSwapchainKHR_ = nullptr; - PFN_vkDestroySwapchainKHR vkDestroySwapchainKHR_ = nullptr; - PFN_vkGetSwapchainImagesKHR vkGetSwapchainImagesKHR_ = nullptr; - PFN_vkAcquireNextImageKHR vkAcquireNextImageKHR_ = nullptr; - PFN_vkQueuePresentKHR vkQueuePresentKHR_ = nullptr; - PFN_vkCmdBlitImage vkCmdBlitImage_ = nullptr; - PFN_vkCmdClearColorImage vkCmdClearColorImage_ = nullptr; - PFN_vkGetPhysicalDeviceMemoryProperties vkGetPhysicalDeviceMemoryProperties_ = nullptr; - PFN_vkGetPhysicalDeviceFormatProperties vkGetPhysicalDeviceFormatProperties_ = nullptr; - PFN_vkCreateFence vkCreateFence_ = nullptr; - PFN_vkDestroyFence vkDestroyFence_ = nullptr; - PFN_vkWaitForFences vkWaitForFences_ = nullptr; - PFN_vkResetFences vkResetFences_ = nullptr; -}; - -} // namespace leonida diff --git a/runtime/src/vulkan_present_compose.h b/runtime/src/vulkan_present_compose.h deleted file mode 100644 index 3b2bb2b8e..000000000 --- a/runtime/src/vulkan_present_compose.h +++ /dev/null @@ -1,259 +0,0 @@ -#pragma once - -// The compute pass behind PresentX's plane composition (docs/d3d12_vulkan.md section 4.5), used by VulkanPresenter:: -// present_planes(): up to two sampled planes in, each scaled from a source rectangle to a destination rectangle, -// plane 1 blended over plane 0, colour spaces converted, the result in an RGBA16F image of the swapchain's size that the -// presenter copies to the swapchain image. The shader is present_compose.comp (SPIR-V embedded, present_compose_spv.h). -// Not thread safe: the presenter calls it with its own state locked, one present at a time. - -#include "vulkan_backend.h" -#include "present_compose_spv.h" - -#include -#include -#include - -namespace leonida { - -// Mirrors the shader's push constants (112 bytes). -struct PresentComposePush { - float dest0[4], dest1[4]; // destination rectangles in output pixels: left, top, right, bottom - float src0[4], src1[4]; // source rectangles in texels - std::uint32_t flags0, flags1, plane_count, out_hdr; - float sdr_white; - std::uint32_t width, height, sdr_eotf; // sdr_eotf: PresentPlanes::SdrEotf - float hdr_peak; - std::uint32_t pad[3]; -}; -static_assert(sizeof(PresentComposePush) == 112); - -namespace compose_flag { -inline constexpr std::uint32_t point = 1, srgb_source = 2, hdr10 = 4, straight_alpha = 8; -} - -class PresentComposer { -public: - static constexpr std::uint32_t frame_slots = 2; - - PresentComposer(VulkanContext& context, const VkPhysicalDeviceMemoryProperties& memory) - : context_(context), memory_(memory) {} - - ~PresentComposer() { - const VkDevice device = context_.device(); - auto& vk = context_.vk; - release_target(); - if (pipeline_) vk.vkDestroyPipeline(device, pipeline_, nullptr); - if (pipeline_layout_) vk.vkDestroyPipelineLayout(device, pipeline_layout_, nullptr); - if (pool_) vk.vkDestroyDescriptorPool(device, pool_, nullptr); // frees its sets - if (set_layout_) vk.vkDestroyDescriptorSetLayout(device, set_layout_, nullptr); - } - PresentComposer(const PresentComposer&) = delete; - PresentComposer& operator=(const PresentComposer&) = delete; - - // Builds the pipeline once; false when the device cannot (a function is missing, or creation fails). - bool ready() { - if (state_ != State::untried) return state_ == State::ready; - state_ = State::failed; - auto& vk = context_.vk; - const VkDevice device = context_.device(); - if (!vk.vkCreateDescriptorSetLayout || !vk.vkCreateDescriptorPool || !vk.vkAllocateDescriptorSets || - !vk.vkUpdateDescriptorSets || !vk.vkCreatePipelineLayout || !vk.vkCreateShaderModule || - !vk.vkCreateComputePipelines || !vk.vkCmdBindPipeline || !vk.vkCmdBindDescriptorSets || - !vk.vkCmdPushConstants || !vk.vkCmdDispatch || !vk.vkCreateImage || !vk.vkCreateImageView || - !vk.vkAllocateMemory) - return false; - std::array bindings{}; - for (std::uint32_t i = 0; i < 3; ++i) { - bindings[i].binding = i; - bindings[i].descriptorType = i < 2 ? VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE : VK_DESCRIPTOR_TYPE_STORAGE_IMAGE; - bindings[i].descriptorCount = 1; - bindings[i].stageFlags = VK_SHADER_STAGE_COMPUTE_BIT; - } - VkDescriptorSetLayoutCreateInfo set_info{VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO}; - set_info.bindingCount = std::uint32_t(bindings.size()); - set_info.pBindings = bindings.data(); - if (vk.vkCreateDescriptorSetLayout(device, &set_info, nullptr, &set_layout_) != VK_SUCCESS) return false; - const std::array sizes{{{VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE, 2 * frame_slots}, - {VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, frame_slots}}}; - VkDescriptorPoolCreateInfo pool_info{VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO}; - pool_info.maxSets = frame_slots; - pool_info.poolSizeCount = std::uint32_t(sizes.size()); - pool_info.pPoolSizes = sizes.data(); - if (vk.vkCreateDescriptorPool(device, &pool_info, nullptr, &pool_) != VK_SUCCESS) return false; - std::array layouts; - layouts.fill(set_layout_); - VkDescriptorSetAllocateInfo allocate{VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO}; - allocate.descriptorPool = pool_; - allocate.descriptorSetCount = frame_slots; - allocate.pSetLayouts = layouts.data(); - if (vk.vkAllocateDescriptorSets(device, &allocate, sets_.data()) != VK_SUCCESS) return false; - const VkPushConstantRange push{VK_SHADER_STAGE_COMPUTE_BIT, 0, sizeof(PresentComposePush)}; - VkPipelineLayoutCreateInfo layout_info{VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO}; - layout_info.setLayoutCount = 1; - layout_info.pSetLayouts = &set_layout_; - layout_info.pushConstantRangeCount = 1; - layout_info.pPushConstantRanges = &push; - if (vk.vkCreatePipelineLayout(device, &layout_info, nullptr, &pipeline_layout_) != VK_SUCCESS) return false; - VkShaderModuleCreateInfo module_info{VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO}; - module_info.codeSize = sizeof(present_compose_spirv); - module_info.pCode = present_compose_spirv; - VkShaderModule module = VK_NULL_HANDLE; - if (vk.vkCreateShaderModule(device, &module_info, nullptr, &module) != VK_SUCCESS) return false; - VkComputePipelineCreateInfo pipeline_info{VK_STRUCTURE_TYPE_COMPUTE_PIPELINE_CREATE_INFO}; - pipeline_info.stage = {VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO, nullptr, 0, - VK_SHADER_STAGE_COMPUTE_BIT, module, "main", nullptr}; - pipeline_info.layout = pipeline_layout_; - const VkResult created = - vk.vkCreateComputePipelines(device, VK_NULL_HANDLE, 1, &pipeline_info, nullptr, &pipeline_); - vk.vkDestroyShaderModule(device, module, nullptr); - if (created != VK_SUCCESS) return false; - state_ = State::ready; - return true; - } - - // The RGBA16F image of `extent` the pass writes (storage + transfer source), made again when the extent changes. - // The caller has made the queue idle first when this returns after a change (changed() says so): the old image - // may still be in use. - bool ensure_target(VkExtent2D extent, bool& changed) { - changed = false; - if (image_ && extent_.width == extent.width && extent_.height == extent.height) return true; - changed = true; - release_target(); - auto& vk = context_.vk; - const VkDevice device = context_.device(); - VkImageCreateInfo info{VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO}; - info.imageType = VK_IMAGE_TYPE_2D; - info.format = target_format; - info.extent = {extent.width, extent.height, 1}; - info.mipLevels = 1; - info.arrayLayers = 1; - info.samples = VK_SAMPLE_COUNT_1_BIT; - info.tiling = VK_IMAGE_TILING_OPTIMAL; - info.usage = VK_IMAGE_USAGE_STORAGE_BIT | VK_IMAGE_USAGE_TRANSFER_SRC_BIT; - info.sharingMode = VK_SHARING_MODE_EXCLUSIVE; - info.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED; - if (vk.vkCreateImage(device, &info, nullptr, &image_) != VK_SUCCESS) return false; - VkMemoryRequirements requirements{}; - vk.vkGetImageMemoryRequirements(device, image_, &requirements); - std::uint32_t type = UINT32_MAX; - for (std::uint32_t i = 0; i < memory_.memoryTypeCount; ++i) - if ((requirements.memoryTypeBits & (1u << i)) && - (memory_.memoryTypes[i].propertyFlags & VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT)) { - type = i; - break; - } - VkMemoryAllocateInfo allocate{VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO}; - allocate.allocationSize = requirements.size; - allocate.memoryTypeIndex = type; - if (type == UINT32_MAX || vk.vkAllocateMemory(device, &allocate, nullptr, &memory_object_) != VK_SUCCESS || - vk.vkBindImageMemory(device, image_, memory_object_, 0) != VK_SUCCESS) { - release_target(); - return false; - } - VkImageViewCreateInfo view_info{VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO}; - view_info.image = image_; - view_info.viewType = VK_IMAGE_VIEW_TYPE_2D; - view_info.format = target_format; - view_info.subresourceRange = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1}; - if (vk.vkCreateImageView(device, &view_info, nullptr, &view_) != VK_SUCCESS) { - release_target(); - return false; - } - extent_ = extent; - return true; - } - - VkImage target() const { return image_; } - VkExtent2D extent() const { return extent_; } - static constexpr VkFormat target_format = VK_FORMAT_R16G16B16A16_SFLOAT; - - // The binding the image barrier helpers take for the target. - ResourceBinding target_binding() const { - ResourceBinding binding{}; - binding.image = image_; - binding.format = target_format; - binding.aspects = VK_IMAGE_ASPECT_COLOR_BIT; - binding.width = extent_.width; - binding.height = extent_.height; - return binding; - } - - // Records the dispatch into `commands`: the planes' views (`plane1` may repeat `plane0` for a single plane) are - // bound with the target, the target goes UNDEFINED -> GENERAL for the writes and ends in TRANSFER_SRC_OPTIMAL for - // the copy that follows. The planes themselves must be in SHADER_READ_ONLY_OPTIMAL (or GENERAL) already. - void record(VkCommandBuffer commands, std::uint32_t slot, VkImageView plane0, VkImageLayout layout0, - VkImageView plane1, VkImageLayout layout1, - const PresentComposePush& push) { - auto& vk = context_.vk; - const VkDevice device = context_.device(); - const VkDescriptorSet set = sets_[slot % frame_slots]; - std::array images{}; - images[0] = {VK_NULL_HANDLE, plane0, layout0}; - images[1] = {VK_NULL_HANDLE, plane1, layout1}; - images[2] = {VK_NULL_HANDLE, view_, VK_IMAGE_LAYOUT_GENERAL}; - std::array writes{}; - for (std::uint32_t i = 0; i < 3; ++i) { - writes[i].sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET; - writes[i].dstSet = set; - writes[i].dstBinding = i; - writes[i].descriptorCount = 1; - writes[i].descriptorType = i < 2 ? VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE : VK_DESCRIPTOR_TYPE_STORAGE_IMAGE; - writes[i].pImageInfo = &images[i]; - } - vk.vkUpdateDescriptorSets(device, std::uint32_t(writes.size()), writes.data(), 0, nullptr); - - VkImageMemoryBarrier to_write{VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER}; - to_write.srcAccessMask = 0; // the previous reader (a copy) only needs the execution dependency - to_write.dstAccessMask = VK_ACCESS_SHADER_WRITE_BIT; - to_write.oldLayout = VK_IMAGE_LAYOUT_UNDEFINED; - to_write.newLayout = VK_IMAGE_LAYOUT_GENERAL; - to_write.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; - to_write.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; - to_write.image = image_; - to_write.subresourceRange = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1}; - vk.vkCmdPipelineBarrier(commands, VK_PIPELINE_STAGE_TRANSFER_BIT | VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, - VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, 0, 0, nullptr, 0, nullptr, 1, &to_write); - vk.vkCmdBindPipeline(commands, VK_PIPELINE_BIND_POINT_COMPUTE, pipeline_); - vk.vkCmdBindDescriptorSets(commands, VK_PIPELINE_BIND_POINT_COMPUTE, pipeline_layout_, 0, 1, &set, 0, nullptr); - vk.vkCmdPushConstants(commands, pipeline_layout_, VK_SHADER_STAGE_COMPUTE_BIT, 0, sizeof(push), &push); - vk.vkCmdDispatch(commands, (extent_.width + 7) / 8, (extent_.height + 7) / 8, 1); - VkImageMemoryBarrier to_read = to_write; - to_read.srcAccessMask = VK_ACCESS_SHADER_WRITE_BIT; - to_read.dstAccessMask = VK_ACCESS_TRANSFER_READ_BIT; - to_read.oldLayout = VK_IMAGE_LAYOUT_GENERAL; - to_read.newLayout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL; - vk.vkCmdPipelineBarrier(commands, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, 0, 0, - nullptr, 0, nullptr, 1, &to_read); - } - - -private: - enum class State { untried, ready, failed }; - - void release_target() { - auto& vk = context_.vk; - const VkDevice device = context_.device(); - if (view_) vk.vkDestroyImageView(device, view_, nullptr); - if (image_) vk.vkDestroyImage(device, image_, nullptr); - if (memory_object_) vk.vkFreeMemory(device, memory_object_, nullptr); - view_ = VK_NULL_HANDLE; - image_ = VK_NULL_HANDLE; - memory_object_ = VK_NULL_HANDLE; - extent_ = {}; - } - - VulkanContext& context_; - VkPhysicalDeviceMemoryProperties memory_; - State state_ = State::untried; - VkDescriptorSetLayout set_layout_ = VK_NULL_HANDLE; - VkDescriptorPool pool_ = VK_NULL_HANDLE; - std::array sets_{}; - VkPipelineLayout pipeline_layout_ = VK_NULL_HANDLE; - VkPipeline pipeline_ = VK_NULL_HANDLE; - VkImage image_ = VK_NULL_HANDLE; - VkDeviceMemory memory_object_ = VK_NULL_HANDLE; - VkImageView view_ = VK_NULL_HANDLE; - VkExtent2D extent_{}; -}; - -} // namespace leonida diff --git a/runtime/src/vulkan_replay.h b/runtime/src/vulkan_replay.h deleted file mode 100644 index 889bb71f7..000000000 --- a/runtime/src/vulkan_replay.h +++ /dev/null @@ -1,4256 +0,0 @@ -#pragma once - -#include "resource_tiling.h" - -// Replays a closed CommandList (command_list.h) into a Vulkan command buffer. -// -// Layouts. With a LayoutTracker, every image's current Vulkan layout is known per subresource, and barriers and -// clears start from it rather than from what the application claims. That is how D3D12's implicit state promotion -// and decay are honoured: a texture in `common` sits in GENERAL, which every promotable access (shader read, copy) -// can use directly, so a later barrier whose `before` names the promoted state still starts from GENERAL; decay -// back to `common` changes no layout. Buffers have no layouts, and simultaneous-access textures stay in GENERAL -// for their whole life, so their decay is free too. Without a tracker, `before` is trusted as the D3D12 runtime -// trusts it. -// -// Depth/stencil planes. With separate_depth_stencil_layouts (Vulkan 1.2 separateDepthStencilLayouts, enabled on -// the device), each plane has its own layout, so a transition or clear of one plane leaves the other alone. Without -// it, both planes always move together. -// -// Requirements on the device and images: -// - a queue with graphics support (the stage masks use ALL_GRAPHICS); -// - images cleared without rectangles have TRANSFER_DST usage; images cleared with rectangles have attachment usage -// and image_view must return views for them (dynamicRendering, Vulkan 1.3); reinterpreted whole-view clears -// use the same attachment path because vkCmdClearColorImage has no view-format argument; -// - enhanced barriers need pipeline_barrier2 (synchronization2, Vulkan 1.3); -// - unordered-access clears need fill_buffer, update_buffer and copy_buffer for buffers; texture views cleared with -// rectangles need color_attachment usage on the image (ResourceBinding::color_attachment); -// - query commands need the query functions, fill_buffer and query_pool; resolve destinations have TRANSFER_DST -// usage and binary occlusion resolves need resolve_binary_occlusion. -// - predicated buffer copies need the byte-copy helper and buffers with STORAGE_BUFFER usage; helper descriptors -// must remain alive through submission completion (VulkanQueue owns them). -// A list that needs a missing function fails with ReplayResult::unsupported before anything is written. - -#include "command_list.h" -#include "depth24.h" -#include "uav_clear.h" - -#include -#include "vulkan_predicate.h" -#include "vulkan_predicated_copy.h" -#include "vulkan_indirect_dispatch_count.h" - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace leonida { - -// What the resolver knows about a resource. image == VK_NULL_HANDLE means a buffer in the shared GPU address -// space: its transitions become global memory barriers. -struct ResourceBinding { - VkImage image = VK_NULL_HANDLE; - VkFormat format = VK_FORMAT_UNDEFINED; - VkImageAspectFlags aspects = VK_IMAGE_ASPECT_COLOR_BIT; - std::uint32_t width = 1; - std::uint32_t height = 1; - std::uint32_t mip_levels = 1; - std::uint32_t array_layers = 1; - bool presentable = false; // a swapchain image: common/present maps to PRESENT_SRC_KHR - bool simultaneous_access = false; // D3D12_RESOURCE_FLAG_ALLOW_SIMULTANEOUS_ACCESS: always GENERAL - bool not_zeroed = false; // D3D12_HEAP_FLAG_CREATE_NOT_ZEROED: first use skips the zero fill - // A descriptor in the bindless set 0 has one layout, but D3D12 lets a texture be sampled both in a - // shader-resource state and while promoted from common (GENERAL). With this set, the shader-resource states - // use GENERAL too, so the descriptor's layout is right in both. - bool sampled_in_general = false; - VkBuffer buffer = VK_NULL_HANDLE; // a buffer resource, for copies - VkDeviceSize buffer_offset = 0; // where it starts in `buffer` (the GPU address arena holds many) - VkDeviceSize size = 0; // its size in bytes - const std::uint8_t* host = nullptr; // mapped CPU-written bytes (UPLOAD/write-back), for small CPU-side reads - std::uint64_t va = 0; // a buffer's console VA (GetGPUVirtualAddress), for vertex/index views - std::uint32_t depth = 1; - bool volume = false; // one array layer, including at mips with a single slice - bool line = false; // a 1D image (TEXTURE1D): its attachment views are 1D arrays - std::uint32_t samples = 1; // more than one: a multisampled 2D texture - bool typeless = false; // A TYPELESS color resource: views name a format of its family (D3D-275). - bool castable_view_formats = false; // A creation-time castable list made the image mutable (D3D-85/D3D-90), - // so views may reinterpret it as typeless resources do. - // A UAV texture stored as a mutable unsigned image because its format has no storage support (R16_UINT for - // A1R5G5B5): the format its render-target views use. UNDEFINED otherwise. - VkFormat uint_backed = VK_FORMAT_UNDEFINED; - // D24_UNORM_S8_UINT stored as D32_SFLOAT_S8_UINT (the GPU has no D24): footprint copies of the depth plane convert - // (depth24.h) and clears quantise to 24 bits. - bool depth24_as_float = false; - bool depth24 = false; // a D24 family format, native or not: depth clears are quantised to 24 bits first - // A D3D12 R32G32B32 texture (12 bytes a texel) held in an R32G32B32A32 image (16): footprints keep D3D12's 12 - // bytes, and copies between it and a buffer are repacked by the depth24 pass (Depth24Job::rgb96). - bool rgb96 = false; - bool color_attachment = false; // has COLOR_ATTACHMENT usage: unordered-access rectangle clears need it - bool sampled = false; // has SAMPLED usage (no DENY_SHADER_RESOURCE): the present compose pass reads it - bool host_readable = false; // D3D12_HEAP_TYPE_READBACK (or CUSTOM write-back): needs host-read flush - bool sparse_buffer = false; -}; - -struct VulkanAccess { - VkImageLayout layout; - VkAccessFlags access; - VkPipelineStageFlags stages; -}; - -inline constexpr VkPipelineStageFlags shader_stages = - VK_PIPELINE_STAGE_ALL_GRAPHICS_BIT | VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT; -inline constexpr VkImageAspectFlags depth_stencil_aspects = VK_IMAGE_ASPECT_DEPTH_BIT | VK_IMAGE_ASPECT_STENCIL_BIT; - -// Maps a legacy D3D12_RESOURCE_STATES combination to the Vulkan layout, accesses and stages that cover it. -// Read-only combinations share one layout when every bit agrees on it (depth_read with shader reads stays in -// DEPTH_STENCIL_READ_ONLY_OPTIMAL, which can be sampled); otherwise they fall back to GENERAL. -// Buffer-only and extension states map to GENERAL with conservative memory access. -// conditional_rendering: VK_EXT_conditional_rendering is enabled. PREDICATION shares its bit with -// INDIRECT_ARGUMENT, and conditional rendering reads the predicate in a stage of its own, so the bit covers both. -inline VulkanAccess vulkan_access(std::uint32_t states, bool presentable, bool conditional_rendering = false) { - namespace s = d3d12_state; - constexpr VkAccessFlags any_memory = VK_ACCESS_MEMORY_READ_BIT | VK_ACCESS_MEMORY_WRITE_BIT; - if (states == s::common) { - if (presentable) return {VK_IMAGE_LAYOUT_PRESENT_SRC_KHR, 0, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT}; - return {VK_IMAGE_LAYOUT_GENERAL, any_memory, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT}; - } - - struct Bit { - std::uint32_t state; - VkImageLayout layout; - VkAccessFlags access; - VkPipelineStageFlags stages; - }; - constexpr VkPipelineStageFlags fragment_tests = - VK_PIPELINE_STAGE_EARLY_FRAGMENT_TESTS_BIT | VK_PIPELINE_STAGE_LATE_FRAGMENT_TESTS_BIT; - static constexpr Bit bits[] = { - // A root CBV can be loaded through a shader buffer device address. - {s::vertex_and_constant_buffer, VK_IMAGE_LAYOUT_GENERAL, - VK_ACCESS_VERTEX_ATTRIBUTE_READ_BIT | VK_ACCESS_UNIFORM_READ_BIT | VK_ACCESS_SHADER_READ_BIT, - VK_PIPELINE_STAGE_VERTEX_INPUT_BIT | shader_stages}, - {s::index_buffer, VK_IMAGE_LAYOUT_GENERAL, VK_ACCESS_INDEX_READ_BIT, VK_PIPELINE_STAGE_VERTEX_INPUT_BIT}, - {s::render_target, VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL, - VK_ACCESS_COLOR_ATTACHMENT_READ_BIT | VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT, - VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT}, - {s::unordered_access, VK_IMAGE_LAYOUT_GENERAL, VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT, - shader_stages}, - {s::depth_write, VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL, - VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_READ_BIT | VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT, fragment_tests}, - {s::depth_read, VK_IMAGE_LAYOUT_DEPTH_STENCIL_READ_ONLY_OPTIMAL, VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_READ_BIT, - fragment_tests}, - {s::non_pixel_shader_resource, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL, VK_ACCESS_SHADER_READ_BIT, - shader_stages}, - {s::pixel_shader_resource, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL, VK_ACCESS_SHADER_READ_BIT, - VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT}, - {s::stream_out, VK_IMAGE_LAYOUT_GENERAL, any_memory, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT}, - {s::indirect_argument, VK_IMAGE_LAYOUT_GENERAL, VK_ACCESS_INDIRECT_COMMAND_READ_BIT, - VK_PIPELINE_STAGE_DRAW_INDIRECT_BIT}, - {s::copy_dest, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, VK_ACCESS_TRANSFER_WRITE_BIT, - VK_PIPELINE_STAGE_TRANSFER_BIT}, - {s::copy_source, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, VK_ACCESS_TRANSFER_READ_BIT, - VK_PIPELINE_STAGE_TRANSFER_BIT}, - {s::resolve_dest, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, VK_ACCESS_TRANSFER_WRITE_BIT, - VK_PIPELINE_STAGE_TRANSFER_BIT}, - {s::resolve_source, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, VK_ACCESS_TRANSFER_READ_BIT, - VK_PIPELINE_STAGE_TRANSFER_BIT}, - {s::raytracing_acceleration_structure, VK_IMAGE_LAYOUT_GENERAL, any_memory, - VK_PIPELINE_STAGE_ALL_COMMANDS_BIT}, - {s::shading_rate_source, VK_IMAGE_LAYOUT_GENERAL, VK_ACCESS_MEMORY_READ_BIT, - VK_PIPELINE_STAGE_ALL_COMMANDS_BIT}, - }; - - const auto merge = [](VkImageLayout a, VkImageLayout b) { - if (a == VK_IMAGE_LAYOUT_UNDEFINED || a == b) return b; - const auto pair = [&](VkImageLayout x, VkImageLayout y) { return (a == x && b == y) || (a == y && b == x); }; - if (pair(VK_IMAGE_LAYOUT_DEPTH_STENCIL_READ_ONLY_OPTIMAL, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL)) - return VK_IMAGE_LAYOUT_DEPTH_STENCIL_READ_ONLY_OPTIMAL; - return VK_IMAGE_LAYOUT_GENERAL; - }; - - VulkanAccess out{VK_IMAGE_LAYOUT_UNDEFINED, 0, 0}; - std::uint32_t known = 0; - for (const auto& bit : bits) { - if (!(states & bit.state)) continue; - known |= bit.state; - out.layout = merge(out.layout, bit.layout); - out.access |= bit.access; - out.stages |= bit.stages; - } - if (states & ~known) { - out.layout = VK_IMAGE_LAYOUT_GENERAL; - out.access |= any_memory; - out.stages |= VK_PIPELINE_STAGE_ALL_COMMANDS_BIT; - } - if (conditional_rendering && (states & s::predication)) { - out.access |= VK_ACCESS_CONDITIONAL_RENDERING_READ_BIT_EXT; - out.stages |= VK_PIPELINE_STAGE_CONDITIONAL_RENDERING_BIT_EXT; - } - return out; -} - -// Enhanced barriers: D3D12_BARRIER_SYNC -> VkPipelineStageFlags2. split (the end half of a split barrier) waits -// for everything, since the begin half's scope is not kept. -inline VkPipelineStageFlags2 vulkan_sync(std::uint32_t sync) { - namespace y = d3d12_sync; - if (sync == y::none) return VK_PIPELINE_STAGE_2_NONE; - constexpr VkPipelineStageFlags2 pre_raster = VK_PIPELINE_STAGE_2_PRE_RASTERIZATION_SHADERS_BIT; - struct Bit { - std::uint32_t sync; - VkPipelineStageFlags2 stages; - }; - static constexpr Bit bits[] = { - {y::all, VK_PIPELINE_STAGE_2_ALL_COMMANDS_BIT}, - {y::draw, VK_PIPELINE_STAGE_2_ALL_GRAPHICS_BIT}, - {y::index_input, VK_PIPELINE_STAGE_2_INDEX_INPUT_BIT}, - {y::vertex_shading, pre_raster | VK_PIPELINE_STAGE_2_VERTEX_ATTRIBUTE_INPUT_BIT}, - {y::pixel_shading, VK_PIPELINE_STAGE_2_FRAGMENT_SHADER_BIT}, - {y::depth_stencil, - VK_PIPELINE_STAGE_2_EARLY_FRAGMENT_TESTS_BIT | VK_PIPELINE_STAGE_2_LATE_FRAGMENT_TESTS_BIT}, - {y::render_target, VK_PIPELINE_STAGE_2_COLOR_ATTACHMENT_OUTPUT_BIT}, - {y::compute_shading, VK_PIPELINE_STAGE_2_COMPUTE_SHADER_BIT}, - {y::copy, VK_PIPELINE_STAGE_2_COPY_BIT}, - {y::resolve, VK_PIPELINE_STAGE_2_RESOLVE_BIT}, - {y::execute_indirect, VK_PIPELINE_STAGE_2_DRAW_INDIRECT_BIT}, - {y::all_shading, pre_raster | VK_PIPELINE_STAGE_2_FRAGMENT_SHADER_BIT | VK_PIPELINE_STAGE_2_COMPUTE_SHADER_BIT}, - {y::non_pixel_shading, pre_raster | VK_PIPELINE_STAGE_2_COMPUTE_SHADER_BIT}, - {y::clear_unordered_access_view, VK_PIPELINE_STAGE_2_CLEAR_BIT | VK_PIPELINE_STAGE_2_COMPUTE_SHADER_BIT}, - }; - VkPipelineStageFlags2 out = 0; - std::uint32_t known = 0; - for (const auto& bit : bits) { - if (!(sync & bit.sync)) continue; - known |= bit.sync; - out |= bit.stages; - } - // Ray tracing, video and split have no narrower equivalent without extensions. - if (sync & ~known) out |= VK_PIPELINE_STAGE_2_ALL_COMMANDS_BIT; - return out; -} - -// D3D12_BARRIER_ACCESS -> VkAccessFlags2. common means "any access the layout allows". -inline VkAccessFlags2 vulkan_barrier_access(std::uint32_t access) { - namespace a = d3d12_access; - constexpr VkAccessFlags2 any_memory = VK_ACCESS_2_MEMORY_READ_BIT | VK_ACCESS_2_MEMORY_WRITE_BIT; - if (access & a::no_access) return VK_ACCESS_2_NONE; - if (access == a::common) return any_memory; - struct Bit { - std::uint32_t access; - VkAccessFlags2 flags; - }; - static constexpr Bit bits[] = { - {a::vertex_buffer, VK_ACCESS_2_VERTEX_ATTRIBUTE_READ_BIT}, - {a::constant_buffer, VK_ACCESS_2_UNIFORM_READ_BIT | VK_ACCESS_2_SHADER_STORAGE_READ_BIT}, - {a::index_buffer, VK_ACCESS_2_INDEX_READ_BIT}, - {a::render_target, VK_ACCESS_2_COLOR_ATTACHMENT_READ_BIT | VK_ACCESS_2_COLOR_ATTACHMENT_WRITE_BIT}, - {a::unordered_access, VK_ACCESS_2_SHADER_READ_BIT | VK_ACCESS_2_SHADER_WRITE_BIT}, - {a::depth_stencil_write, - VK_ACCESS_2_DEPTH_STENCIL_ATTACHMENT_READ_BIT | VK_ACCESS_2_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT}, - {a::depth_stencil_read, VK_ACCESS_2_DEPTH_STENCIL_ATTACHMENT_READ_BIT}, - {a::shader_resource, VK_ACCESS_2_SHADER_READ_BIT}, - {a::stream_output, VK_ACCESS_2_MEMORY_WRITE_BIT}, - {a::indirect_argument, VK_ACCESS_2_INDIRECT_COMMAND_READ_BIT}, - {a::copy_dest, VK_ACCESS_2_TRANSFER_WRITE_BIT}, - {a::copy_source, VK_ACCESS_2_TRANSFER_READ_BIT}, - {a::resolve_dest, VK_ACCESS_2_TRANSFER_WRITE_BIT}, - {a::resolve_source, VK_ACCESS_2_TRANSFER_READ_BIT}, - {a::raytracing_acceleration_structure_read, VK_ACCESS_2_MEMORY_READ_BIT}, - {a::raytracing_acceleration_structure_write, VK_ACCESS_2_MEMORY_WRITE_BIT}, - {a::shading_rate_source, VK_ACCESS_2_MEMORY_READ_BIT}, - }; - VkAccessFlags2 out = 0; - std::uint32_t known = 0; - for (const auto& bit : bits) { - if (!(access & bit.access)) continue; - known |= bit.access; - out |= bit.flags; - } - if (access & ~known) out |= any_memory; // video and unknown bits - return out; -} - -// For accesses that vulkan_barrier_access produces: the stages Vulkan lets perform them (the "supported -// access types" table of the synchronization2 chapter, with the meta stages that contain them), and the narrowest -// stage to add when a barrier's stages have none of those. MEMORY_READ/WRITE are valid in every stage. -struct AccessStages { - VkAccessFlags2 access; - VkPipelineStageFlags2 supported; - VkPipelineStageFlags2 narrowest; -}; - -inline constexpr VkPipelineStageFlags2 shader_stages2 = - VK_PIPELINE_STAGE_2_VERTEX_SHADER_BIT | VK_PIPELINE_STAGE_2_TESSELLATION_CONTROL_SHADER_BIT | - VK_PIPELINE_STAGE_2_TESSELLATION_EVALUATION_SHADER_BIT | VK_PIPELINE_STAGE_2_GEOMETRY_SHADER_BIT | - VK_PIPELINE_STAGE_2_FRAGMENT_SHADER_BIT | VK_PIPELINE_STAGE_2_COMPUTE_SHADER_BIT | - VK_PIPELINE_STAGE_2_PRE_RASTERIZATION_SHADERS_BIT | VK_PIPELINE_STAGE_2_ALL_GRAPHICS_BIT | - VK_PIPELINE_STAGE_2_ALL_COMMANDS_BIT; - -inline constexpr AccessStages access_stages[] = { - {VK_ACCESS_2_INDIRECT_COMMAND_READ_BIT, - VK_PIPELINE_STAGE_2_DRAW_INDIRECT_BIT | VK_PIPELINE_STAGE_2_ALL_GRAPHICS_BIT | VK_PIPELINE_STAGE_2_ALL_COMMANDS_BIT, - VK_PIPELINE_STAGE_2_DRAW_INDIRECT_BIT}, - {VK_ACCESS_2_INDEX_READ_BIT, - VK_PIPELINE_STAGE_2_INDEX_INPUT_BIT | VK_PIPELINE_STAGE_2_VERTEX_INPUT_BIT | VK_PIPELINE_STAGE_2_ALL_GRAPHICS_BIT | - VK_PIPELINE_STAGE_2_ALL_COMMANDS_BIT, - VK_PIPELINE_STAGE_2_INDEX_INPUT_BIT}, - {VK_ACCESS_2_VERTEX_ATTRIBUTE_READ_BIT, - VK_PIPELINE_STAGE_2_VERTEX_ATTRIBUTE_INPUT_BIT | VK_PIPELINE_STAGE_2_VERTEX_INPUT_BIT | - VK_PIPELINE_STAGE_2_ALL_GRAPHICS_BIT | VK_PIPELINE_STAGE_2_ALL_COMMANDS_BIT, - VK_PIPELINE_STAGE_2_VERTEX_ATTRIBUTE_INPUT_BIT}, - // Shader accesses: D3D12 does not say which shader stage, so every one that can run (all shading). - {VK_ACCESS_2_UNIFORM_READ_BIT | VK_ACCESS_2_SHADER_STORAGE_READ_BIT, shader_stages2, - VK_PIPELINE_STAGE_2_PRE_RASTERIZATION_SHADERS_BIT | VK_PIPELINE_STAGE_2_FRAGMENT_SHADER_BIT | - VK_PIPELINE_STAGE_2_COMPUTE_SHADER_BIT}, - {VK_ACCESS_2_SHADER_READ_BIT, shader_stages2, - VK_PIPELINE_STAGE_2_PRE_RASTERIZATION_SHADERS_BIT | VK_PIPELINE_STAGE_2_FRAGMENT_SHADER_BIT | - VK_PIPELINE_STAGE_2_COMPUTE_SHADER_BIT}, - {VK_ACCESS_2_SHADER_WRITE_BIT, shader_stages2, - VK_PIPELINE_STAGE_2_PRE_RASTERIZATION_SHADERS_BIT | VK_PIPELINE_STAGE_2_FRAGMENT_SHADER_BIT | - VK_PIPELINE_STAGE_2_COMPUTE_SHADER_BIT}, - {VK_ACCESS_2_COLOR_ATTACHMENT_READ_BIT, - VK_PIPELINE_STAGE_2_COLOR_ATTACHMENT_OUTPUT_BIT | VK_PIPELINE_STAGE_2_ALL_GRAPHICS_BIT | - VK_PIPELINE_STAGE_2_ALL_COMMANDS_BIT, - VK_PIPELINE_STAGE_2_COLOR_ATTACHMENT_OUTPUT_BIT}, - {VK_ACCESS_2_COLOR_ATTACHMENT_WRITE_BIT, - VK_PIPELINE_STAGE_2_COLOR_ATTACHMENT_OUTPUT_BIT | VK_PIPELINE_STAGE_2_ALL_GRAPHICS_BIT | - VK_PIPELINE_STAGE_2_ALL_COMMANDS_BIT, - VK_PIPELINE_STAGE_2_COLOR_ATTACHMENT_OUTPUT_BIT}, - {VK_ACCESS_2_DEPTH_STENCIL_ATTACHMENT_READ_BIT, - VK_PIPELINE_STAGE_2_EARLY_FRAGMENT_TESTS_BIT | VK_PIPELINE_STAGE_2_LATE_FRAGMENT_TESTS_BIT | - VK_PIPELINE_STAGE_2_ALL_GRAPHICS_BIT | VK_PIPELINE_STAGE_2_ALL_COMMANDS_BIT, - VK_PIPELINE_STAGE_2_EARLY_FRAGMENT_TESTS_BIT | VK_PIPELINE_STAGE_2_LATE_FRAGMENT_TESTS_BIT}, - {VK_ACCESS_2_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT, - VK_PIPELINE_STAGE_2_EARLY_FRAGMENT_TESTS_BIT | VK_PIPELINE_STAGE_2_LATE_FRAGMENT_TESTS_BIT | - VK_PIPELINE_STAGE_2_ALL_GRAPHICS_BIT | VK_PIPELINE_STAGE_2_ALL_COMMANDS_BIT, - VK_PIPELINE_STAGE_2_EARLY_FRAGMENT_TESTS_BIT | VK_PIPELINE_STAGE_2_LATE_FRAGMENT_TESTS_BIT}, - // Transfers: ALL_GRAPHICS does not contain the transfer stages, and CLEAR only writes. - {VK_ACCESS_2_TRANSFER_READ_BIT, - VK_PIPELINE_STAGE_2_COPY_BIT | VK_PIPELINE_STAGE_2_BLIT_BIT | VK_PIPELINE_STAGE_2_RESOLVE_BIT | - VK_PIPELINE_STAGE_2_ALL_TRANSFER_BIT | VK_PIPELINE_STAGE_2_ALL_COMMANDS_BIT, - VK_PIPELINE_STAGE_2_ALL_TRANSFER_BIT}, - {VK_ACCESS_2_TRANSFER_WRITE_BIT, - VK_PIPELINE_STAGE_2_COPY_BIT | VK_PIPELINE_STAGE_2_BLIT_BIT | VK_PIPELINE_STAGE_2_RESOLVE_BIT | - VK_PIPELINE_STAGE_2_CLEAR_BIT | VK_PIPELINE_STAGE_2_ALL_TRANSFER_BIT | VK_PIPELINE_STAGE_2_ALL_COMMANDS_BIT, - VK_PIPELINE_STAGE_2_ALL_TRANSFER_BIT}, - {VK_ACCESS_2_CONDITIONAL_RENDERING_READ_BIT_EXT, - VK_PIPELINE_STAGE_2_CONDITIONAL_RENDERING_BIT_EXT | VK_PIPELINE_STAGE_2_ALL_GRAPHICS_BIT | - VK_PIPELINE_STAGE_2_ALL_COMMANDS_BIT, - VK_PIPELINE_STAGE_2_CONDITIONAL_RENDERING_BIT_EXT}, -}; - -// One side of an enhanced barrier: D3D12 sync and access to a Vulkan stage mask and access mask that Vulkan accepts -// together. D3D12 lets an access be named with a sync scope whose Vulkan stages cannot perform it (SYNC_ALL_SHADING -// with ACCESS_VERTEX_BUFFER is valid D3D12, but VERTEX_ATTRIBUTE_READ needs VERTEX_ATTRIBUTE_INPUT). The stages are -// widened by the narrowest stage that can, never the access dropped: the dependency still covers every access the -// application named, only over a slightly larger scope. With no stages (SYNC_NONE) there is no access either. -struct BarrierScope { - VkPipelineStageFlags2 stages; - VkAccessFlags2 access; -}; - -// conditional_rendering: VK_EXT_conditional_rendering is enabled. SYNC_PREDICATION and ACCESS_PREDICATION share -// their bits with EXECUTE_INDIRECT and INDIRECT_ARGUMENT, and conditional rendering reads the predicate in a stage -// of its own, so those bits cover it too. -inline BarrierScope vulkan_barrier_scope(std::uint32_t sync, std::uint32_t access, bool conditional_rendering = false) { - BarrierScope out{vulkan_sync(sync), 0}; - if (!out.stages) return out; - if (conditional_rendering && (sync & d3d12_sync::predication)) - out.stages |= VK_PIPELINE_STAGE_2_CONDITIONAL_RENDERING_BIT_EXT; - out.access = vulkan_barrier_access(access); - if (conditional_rendering && (access & d3d12_access::predication) && !(access & d3d12_access::no_access)) - out.access |= VK_ACCESS_2_CONDITIONAL_RENDERING_READ_BIT_EXT; - for (const AccessStages& entry : access_stages) - if ((out.access & entry.access) && !(out.stages & entry.supported)) out.stages |= entry.narrowest; - return out; -} - -// D3D12_BARRIER_LAYOUT -> VkImageLayout. Queue-specific layouts map like their generic forms. -inline VkImageLayout vulkan_layout(std::uint32_t layout, bool presentable) { - namespace l = d3d12_layout; - switch (layout) { - case l::undefined: return VK_IMAGE_LAYOUT_UNDEFINED; - case l::common: return presentable ? VK_IMAGE_LAYOUT_PRESENT_SRC_KHR : VK_IMAGE_LAYOUT_GENERAL; - case l::render_target: return VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL; - case l::depth_stencil_write: return VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL; - case l::depth_stencil_read: return VK_IMAGE_LAYOUT_DEPTH_STENCIL_READ_ONLY_OPTIMAL; - case l::shader_resource: - case l::direct_queue_shader_resource: - case l::compute_queue_shader_resource: return VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL; - case l::copy_source: - case l::resolve_source: - case l::direct_queue_copy_source: - case l::compute_queue_copy_source: return VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL; - case l::copy_dest: - case l::resolve_dest: - case l::direct_queue_copy_dest: - case l::compute_queue_copy_dest: return VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL; - default: return VK_IMAGE_LAYOUT_GENERAL; // generic read, UAV, shading rate, video, *_common - } -} - -// The layout an image actually uses: simultaneous-access images live in GENERAL, and so do images in a -// shader-resource state when set 0 names them (sampled_in_general). -inline VkImageLayout image_layout(const ResourceBinding& resource, VkImageLayout layout) { - if (resource.simultaneous_access && layout != VK_IMAGE_LAYOUT_UNDEFINED && - layout != VK_IMAGE_LAYOUT_PRESENT_SRC_KHR) - return VK_IMAGE_LAYOUT_GENERAL; - if (resource.sampled_in_general && layout == VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL) - return VK_IMAGE_LAYOUT_GENERAL; - return layout; -} - -// Bytes per texel, or per 4x4 block for block-compressed formats, of one aspect as copies lay it out in a buffer -// (D3D12 footprints and Vulkan buffer-image copies agree on these). bytes == 0: not a format copies support yet. -struct BlockFormat { - std::uint32_t bytes = 0; - std::uint32_t block = 1; // texels per block edge -}; - -inline BlockFormat block_format(VkFormat format, VkImageAspectFlags aspect) { - if (aspect == VK_IMAGE_ASPECT_STENCIL_BIT) return {1, 1}; - switch (format) { - case VK_FORMAT_R32G32B32A32_SFLOAT: - case VK_FORMAT_R32G32B32A32_SINT: - case VK_FORMAT_R32G32B32A32_UINT: return {16, 1}; - case VK_FORMAT_R16G16B16A16_SFLOAT: - case VK_FORMAT_R16G16B16A16_UNORM: - case VK_FORMAT_R16G16B16A16_SNORM: - case VK_FORMAT_R16G16B16A16_UINT: - case VK_FORMAT_R16G16B16A16_SINT: - case VK_FORMAT_R32G32_SFLOAT: - case VK_FORMAT_R32G32_UINT: - case VK_FORMAT_R32G32_SINT: return {8, 1}; - case VK_FORMAT_A2B10G10R10_UNORM_PACK32: - case VK_FORMAT_A2B10G10R10_UINT_PACK32: - case VK_FORMAT_E5B9G9R9_UFLOAT_PACK32: - case VK_FORMAT_B10G11R11_UFLOAT_PACK32: - case VK_FORMAT_R8G8B8A8_UNORM: - case VK_FORMAT_R8G8B8A8_SRGB: - case VK_FORMAT_R8G8B8A8_SNORM: - case VK_FORMAT_R8G8B8A8_UINT: - case VK_FORMAT_R8G8B8A8_SINT: - case VK_FORMAT_B8G8R8A8_UNORM: - case VK_FORMAT_B8G8R8A8_SRGB: - case VK_FORMAT_R16G16_SFLOAT: - case VK_FORMAT_R16G16_UNORM: - case VK_FORMAT_R16G16_SNORM: - case VK_FORMAT_R16G16_UINT: - case VK_FORMAT_R16G16_SINT: - case VK_FORMAT_R32_SFLOAT: - case VK_FORMAT_R32_UINT: - case VK_FORMAT_R32_SINT: - case VK_FORMAT_D32_SFLOAT: - case VK_FORMAT_D32_SFLOAT_S8_UINT: // depth aspect - case VK_FORMAT_D24_UNORM_S8_UINT: return {4, 1}; - case VK_FORMAT_R8G8_UNORM: - case VK_FORMAT_R8G8_SNORM: - case VK_FORMAT_R5G6B5_UNORM_PACK16: - case VK_FORMAT_A1R5G5B5_UNORM_PACK16: - case VK_FORMAT_R8G8_UINT: - case VK_FORMAT_R8G8_SINT: - case VK_FORMAT_R16_SFLOAT: - case VK_FORMAT_R16_UNORM: - case VK_FORMAT_R16_SNORM: - case VK_FORMAT_R16_UINT: - case VK_FORMAT_R16_SINT: - case VK_FORMAT_A4R4G4B4_UNORM_PACK16: - case VK_FORMAT_R4G4B4A4_UNORM_PACK16: - case VK_FORMAT_D16_UNORM: return {2, 1}; - case VK_FORMAT_R8_UNORM: - case VK_FORMAT_R8_SNORM: - case VK_FORMAT_R8_UINT: - case VK_FORMAT_R8_SINT: return {1, 1}; - case VK_FORMAT_BC1_RGBA_UNORM_BLOCK: - case VK_FORMAT_BC1_RGBA_SRGB_BLOCK: - case VK_FORMAT_BC4_UNORM_BLOCK: - case VK_FORMAT_BC4_SNORM_BLOCK: return {8, 4}; - case VK_FORMAT_BC2_UNORM_BLOCK: - case VK_FORMAT_BC2_SRGB_BLOCK: - case VK_FORMAT_BC3_UNORM_BLOCK: - case VK_FORMAT_BC3_SRGB_BLOCK: - case VK_FORMAT_BC5_UNORM_BLOCK: - case VK_FORMAT_BC5_SNORM_BLOCK: - case VK_FORMAT_BC6H_UFLOAT_BLOCK: - case VK_FORMAT_BC6H_SFLOAT_BLOCK: - case VK_FORMAT_BC7_UNORM_BLOCK: - case VK_FORMAT_BC7_SRGB_BLOCK: return {16, 4}; - default: return {}; - } -} - -// The same for a resource as D3D12 lays it out, which for an rgb96 texture is not its image's layout. -inline constexpr std::uint32_t rgb96_bytes = 12; -inline BlockFormat copy_block_format(const ResourceBinding& resource, VkImageAspectFlags aspect) { - BlockFormat format = block_format(resource.format, aspect); - if (resource.rgb96 && format.bytes) format.bytes = rgb96_bytes; - return format; -} - -inline bool two_planes(const ResourceBinding& resource) { - return (resource.aspects & depth_stencil_aspects) == depth_stencil_aspects; -} - -// D3D12 copies between a depth format and a colour format of the same typeless family, bit for bit: D32_FLOAT with -// R32_FLOAT/UINT/SINT (R32_TYPELESS) and D16_UNORM with R16_FLOAT/UNORM/SNORM/UINT/SINT (R16_TYPELESS). Single-sampled, single-plane depth only: D24 and D32 with stencil have two planes, and a D24 -// stored as D32 would need the depth24 conversion. Vulkan's vkCmdCopyImage refuses mismatched aspects, so the replay -// stages these through a buffer. -inline bool depth_colour_pair(const ResourceBinding& a, const ResourceBinding& b) { - const auto family = [](VkFormat format) -> int { - switch (format) { - case VK_FORMAT_D32_SFLOAT: - case VK_FORMAT_R32_SFLOAT: - case VK_FORMAT_R32_UINT: - case VK_FORMAT_R32_SINT: return 32; - case VK_FORMAT_D16_UNORM: - case VK_FORMAT_R16_SFLOAT: - case VK_FORMAT_R16_UNORM: - case VK_FORMAT_R16_SNORM: - case VK_FORMAT_R16_UINT: - case VK_FORMAT_R16_SINT: return 16; - default: return 0; - } - }; - const auto depth_only = [](const ResourceBinding& r) { - return r.aspects == VK_IMAGE_ASPECT_DEPTH_BIT && !r.depth24_as_float; - }; - const ResourceBinding *depth = &a, *colour = &b; - if (!depth_only(*depth)) std::swap(depth, colour); - return depth_only(*depth) && colour->aspects == VK_IMAGE_ASPECT_COLOR_BIT && a.image && b.image && - a.samples == 1 && b.samples == 1 && !a.volume && !b.volume && family(a.format) && - family(a.format) == family(b.format); -} - -// Decodes a D3D12 subresource index. Combined depth-stencil images have two planes (0 depth, 1 stencil); -// every other image has one. -inline bool image_range(const ResourceBinding& resource, std::uint32_t subresource, VkImageSubresourceRange& out) { - if (!resource.mip_levels || !resource.array_layers) return false; - if (subresource == all_subresources) { - out = {resource.aspects, 0, resource.mip_levels, 0, resource.array_layers}; - return true; - } - const std::uint64_t per_plane = std::uint64_t(resource.mip_levels) * resource.array_layers; - const std::uint64_t plane = subresource / per_plane; - if (plane >= (two_planes(resource) ? 2u : 1u)) return false; - const auto within = static_cast(subresource % per_plane); - const VkImageAspectFlags aspect = - two_planes(resource) ? (plane ? VK_IMAGE_ASPECT_STENCIL_BIT : VK_IMAGE_ASPECT_DEPTH_BIT) : resource.aspects; - out = {aspect, within % resource.mip_levels, 1, within / resource.mip_levels, 1}; - return true; -} - -// Decodes D3D12_BARRIER_SUBRESOURCE_RANGE. -inline bool barrier_range(const ResourceBinding& resource, const BarrierSubresourceRange& range, - VkImageSubresourceRange& out) { - if (!range.mip_count) return image_range(resource, range.index_or_first_mip, out); - const std::uint32_t planes = two_planes(resource) ? 2 : 1; - if (range.index_or_first_mip >= resource.mip_levels || - range.mip_count > resource.mip_levels - range.index_or_first_mip) - return false; - if (range.first_layer >= resource.array_layers || !range.layer_count || - range.layer_count > resource.array_layers - range.first_layer) - return false; - if (range.first_plane >= planes || !range.plane_count || range.plane_count > planes - range.first_plane) - return false; - VkImageAspectFlags aspects = resource.aspects; - if (planes == 2) { - aspects = 0; - for (std::uint32_t p = range.first_plane; p < range.first_plane + range.plane_count; ++p) - aspects |= p ? VK_IMAGE_ASPECT_STENCIL_BIT : VK_IMAGE_ASPECT_DEPTH_BIT; - } - out = {aspects, range.index_or_first_mip, range.mip_count, range.first_layer, range.layer_count}; - return true; -} - -// A part of an image range with one current layout. -struct LayoutPiece { - VkImageSubresourceRange range; - VkImageLayout layout; -}; - -// The layout pieces of one range: nearly always one (the tracked layouts agree over the range) or two (depth and -// stencil apart), so those live inline and a barrier or clear makes no heap allocation; more spill to the heap. -class LayoutPieces { -public: - LayoutPiece* begin() { return data(); } - LayoutPiece* end() { return data() + size_; } - const LayoutPiece* begin() const { return data(); } - const LayoutPiece* end() const { return data() + size_; } - std::size_t size() const { return size_; } - bool empty() const { return size_ == 0; } - LayoutPiece& operator[](std::size_t i) { return data()[i]; } - const LayoutPiece& operator[](std::size_t i) const { return data()[i]; } - - void clear() { - size_ = 0; - heap_.clear(); - } - void push_back(const LayoutPiece& piece) { - if (heap_.empty() && size_ < inline_.size()) { - inline_[size_++] = piece; - return; - } - if (heap_.empty()) heap_.assign(inline_.begin(), inline_.begin() + size_); - heap_.push_back(piece); - ++size_; - } - -private: - LayoutPiece* data() { return heap_.empty() ? inline_.data() : heap_.data(); } - const LayoutPiece* data() const { return heap_.empty() ? inline_.data() : heap_.data(); } - - std::array inline_{}; - std::vector heap_; - std::size_t size_ = 0; -}; - -// The current Vulkan layout of every tracked image subresource. Shared by all queues of a device; lists are -// emitted in submission order. Images are tracked from creation (their initial state) until destruction. -class LayoutTracker { -public: - explicit LayoutTracker(bool separate_depth_stencil_layouts = false) - : separate_(separate_depth_stencil_layouts) {} - - bool separate_depth_stencil_layouts() const { return separate_; } - - void track(ResourceId id, const ResourceBinding& resource, VkImageLayout layout) { - Entry entry{resource.mip_levels, resource.array_layers, two_planes(resource) ? 2u : 1u, - separate_ && two_planes(resource), {}}; - entry.layouts.assign(std::size_t(entry.mips) * entry.layers * (entry.two_planes ? 2 : 1), layout); - entries_[id] = std::move(entry); - } - - void forget(ResourceId id) { entries_.erase(id); } - bool tracked(ResourceId id) const { return entries_.count(id) != 0; } - - // Current layout of one D3D12 subresource; UNDEFINED when the resource or index is unknown. - VkImageLayout layout(ResourceId id, std::uint32_t subresource) const { - const auto it = entries_.find(id); - if (it == entries_.end()) return VK_IMAGE_LAYOUT_UNDEFINED; - const Entry& e = it->second; - const std::uint32_t per_plane = e.mips * e.layers; - const std::uint32_t plane = subresource / per_plane; - if (plane >= e.planes) return VK_IMAGE_LAYOUT_UNDEFINED; - return e.layouts[(e.two_planes ? plane : 0) * per_plane + subresource % per_plane]; // merged planes share - } - - // The current layouts over a range: one piece when they all agree, else one per subresource. - // Out is LayoutPieces or std::vector. - template - bool pieces(ResourceId id, const VkImageSubresourceRange& range, Out& out) const { - const auto it = entries_.find(id); - if (it == entries_.end()) return false; - const Entry& e = it->second; - out.clear(); - bool uniform = true; - VkImageLayout first = VK_IMAGE_LAYOUT_UNDEFINED; - bool any = false; - visit(e, range, [&](std::size_t index, VkImageAspectFlags, std::uint32_t, std::uint32_t) { - if (!any) first = e.layouts[index]; - uniform = uniform && e.layouts[index] == first; - any = true; - }); - if (uniform) { - out.push_back({range, first}); - return true; - } - visit(e, range, [&](std::size_t index, VkImageAspectFlags aspect, std::uint32_t mip, std::uint32_t layer) { - out.push_back({{aspect, mip, 1, layer, 1}, e.layouts[index]}); - }); - return true; - } - - void set(ResourceId id, const VkImageSubresourceRange& range, VkImageLayout layout) { - const auto it = entries_.find(id); - if (it == entries_.end()) return; - Entry& e = it->second; - visit(e, range, [&](std::size_t index, VkImageAspectFlags, std::uint32_t, std::uint32_t) { - e.layouts[index] = layout; - }); - } - -private: - struct Entry { - std::uint32_t mips; - std::uint32_t layers; - std::uint32_t planes; // of the resource - bool two_planes; // depth and stencil tracked apart - std::vector layouts; - }; - - template - static void visit(const Entry& e, const VkImageSubresourceRange& range, F&& f) { - const std::uint32_t mip_end = range.levelCount == VK_REMAINING_MIP_LEVELS ? e.mips - : range.baseMipLevel + range.levelCount; - const std::uint32_t layer_end = range.layerCount == VK_REMAINING_ARRAY_LAYERS - ? e.layers - : range.baseArrayLayer + range.layerCount; - for (std::uint32_t plane = 0; plane < (e.two_planes ? 2u : 1u); ++plane) { - VkImageAspectFlags aspect = range.aspectMask; - if (e.two_planes) { - aspect = plane ? VK_IMAGE_ASPECT_STENCIL_BIT : VK_IMAGE_ASPECT_DEPTH_BIT; - if (!(range.aspectMask & aspect)) continue; - } - for (std::uint32_t layer = range.baseArrayLayer; layer < std::min(layer_end, e.layers); ++layer) - for (std::uint32_t mip = range.baseMipLevel; mip < std::min(mip_end, e.mips); ++mip) - f((std::size_t(plane) * e.layers + layer) * e.mips + mip, aspect, mip, layer); - } - } - - bool separate_; - std::unordered_map entries_; -}; - -// Each physical slot records one non-overlapping interval. Logical queries can share slots. -struct OcclusionSegmentPool { - VkDevice device = VK_NULL_HANDLE; - PFN_vkDestroyQueryPool destroy = nullptr; - VkQueryPool pool = VK_NULL_HANDLE; - // Pipeline-statistics segments only: a second pool with the counters a mesh draw allows (D3D-291), and for each - // segment index whether it runs there. Empty when no segment of the submission holds a mesh draw. - VkQueryPool mesh_pool = VK_NULL_HANDLE; - std::vector mesh; - - OcclusionSegmentPool() = default; - OcclusionSegmentPool(const OcclusionSegmentPool&) = delete; - OcclusionSegmentPool& operator=(const OcclusionSegmentPool&) = delete; - ~OcclusionSegmentPool() { - if (pool) destroy(device, pool, nullptr); - if (mesh_pool) destroy(device, mesh_pool, nullptr); - } -}; - -struct OcclusionResult { - std::shared_ptr segments; - std::uint32_t first = 0; - std::uint32_t count = 0; -}; - -// A D3D12 query heap on Vulkan. The host tracks which queries hold a result. A resolve of a query that -// was never ended writes zeros instead of waiting on it. -struct QueryPool { - // Null for a stream-output statistics heap: the layer has no stream output (PSOs with StreamOutput entries are - // refused), so every SO_STATISTICS_STREAMn query counts 0 written and 0 needed, and a resolve fills zeros. - VkQueryPool pool = VK_NULL_HANDLE; - std::uint32_t heap_type = 0; // d3d12_query_heap - std::uint32_t count = 0; - bool precise = false; // occlusionQueryPrecise: D3D12_QUERY_TYPE_OCCLUSION counts exact samples - std::vector ended; - std::unordered_map occlusion; -}; - -// A compute pipeline as replay needs it. code_base is the console VA of the shader's FSSM blob (push-constant -// dwords 34-35), 0 when the shader does not read it. -struct ComputePipeline { - VkPipeline pipeline = VK_NULL_HANDLE; - VkPipelineLayout layout = VK_NULL_HANDLE; - std::uint64_t code_base = 0; - VkDescriptorSet bindless_set = VK_NULL_HANDLE; // set 0 of the layout, bound at every dispatch; null: none -}; - -// A graphics pipeline as replay needs it: the formats its attachments must have and which vertex-input slots it -// reads. code_base: as for compute (one per pipeline; two stages that both read theirs are refused, question 14). -struct GraphicsPipeline { - VkPipeline pipeline = VK_NULL_HANDLE; - VkPipelineLayout layout = VK_NULL_HANDLE; - VkShaderStageFlags push_stages = 0; // the layout's push-constant range; vkCmdPushConstants must name the same - std::uint64_t code_base = 0; - VkDescriptorSet bindless_set = VK_NULL_HANDLE; // set 0 of the layout, bound at every draw; null: none - std::vector color_formats; // by render-target slot - VkFormat depth_format = VK_FORMAT_UNDEFINED; - VkImageAspectFlags depth_aspects = 0; - std::uint32_t vertex_slots = 0; // bit per input slot the input layout uses - std::uint32_t zero_step_slots = 0; // per-instance slots with InstanceDataStepRate 0: stride 0 at draw time - std::uint32_t strip_cut = 0; // D3D12_INDEX_BUFFER_STRIP_CUT_VALUE (0: off, 1: 0xFFFF, 2: 0xFFFFFFFF) - bool mesh = false; // a mesh shader instead of a vertex shader: drawn by DispatchMesh only - // The same pipeline with some attachment formats VK_FORMAT_UNDEFINED, for a draw that leaves those slots - // unbound (D3D12 allows it; dynamic rendering needs the formats to agree). Bit i: colour slot i, bit 8: depth - // and stencil. Null when it cannot be built. - static constexpr std::uint32_t unbound_depth = 1u << 8; - std::function variant; - std::uint32_t samples = 1; // rasterizationSamples; every bound attachment must have this count -}; - -// The 144-byte push-constant block every translated shader declares: s0..s31, heap base, code base. -struct ShaderUserData { - std::uint32_t s[32]; - std::uint64_t heap_base; - std::uint64_t code_base; -}; -static_assert(sizeof(ShaderUserData) == 144); - -// A host read of a small CPU-written input either succeeds, names no VA, or names GPU-written memory. The last is a -// capability limit, not bad contents: DEFAULT and READBACK bytes may still be stale while replay prepares a command. -enum class HostReadStatus { ok, absent, not_cpu_written }; - -enum class ReplayResult { - success, - list_open, - unresolved_resource, - invalid_subresource, - invalid_clear, - invalid_copy, - invalid_predication, - invalid_query, - invalid_indirect_arguments, - invalid_draw, // DispatchMesh with a pipeline that has no mesh shader, or a vertex draw with one that has - unsupported -}; - -struct ReplayFunctions { - // Set 0 for the pipelines that declare one (their own `bindless_set` is only the marker): the device's current - // generation of it, which a flush may have replaced since the pipeline was made. Null: the pipeline's. - VkDescriptorSet bindless_set = VK_NULL_HANDLE; - PFN_vkCmdPipelineBarrier pipeline_barrier = nullptr; - PFN_vkCmdClearColorImage clear_color_image = nullptr; - PFN_vkCmdClearDepthStencilImage clear_depth_stencil_image = nullptr; - // Optional; a list that needs a missing one is rejected with ReplayResult::unsupported. - PFN_vkCmdPipelineBarrier2 pipeline_barrier2 = nullptr; // enhanced barriers - VkPipelineStageFlags2 queue_stages = 0; - PFN_vkCmdBeginRendering begin_rendering = nullptr; // rectangle clears - PFN_vkCmdEndRendering end_rendering = nullptr; - PFN_vkCmdClearAttachments clear_attachments = nullptr; - PFN_vkCmdCopyBuffer copy_buffer = nullptr; // copies - PFN_vkCmdCopyBufferToImage copy_buffer_to_image = nullptr; - PFN_vkCmdCopyImageToBuffer copy_image_to_buffer = nullptr; - PFN_vkCmdCopyImage copy_image = nullptr; - PFN_vkCmdResolveImage resolve_image = nullptr; // resolves - PFN_vkCmdFillBuffer fill_buffer = nullptr; // unordered-access buffer clears, with copy_buffer - PFN_vkCmdUpdateBuffer update_buffer = nullptr; // WriteBufferImmediate, unordered-access clears - // VK_EXT_conditional_rendering: SetPredication. The predicate buffer must have been created with - // VK_BUFFER_USAGE_CONDITIONAL_RENDERING_BIT_EXT. - PFN_vkCmdBeginConditionalRenderingEXT begin_conditional_rendering = nullptr; - PFN_vkCmdEndConditionalRenderingEXT end_conditional_rendering = nullptr; - PFN_vkCmdResetQueryPool reset_query_pool = nullptr; // queries, with fill_buffer for unavailable results - PFN_vkCmdBeginQuery begin_query = nullptr; - PFN_vkCmdEndQuery end_query = nullptr; - PFN_vkCmdWriteTimestamp write_timestamp = nullptr; - PFN_vkCmdCopyQueryPoolResults copy_query_pool_results = nullptr; - // Set only where a copy of timestamp results is not ordered after the timestamps written before it (MoltenVK on - // Apple GPUs, docs/d3d12_vulkan.md section 4.6): records what orders them, before each timestamp resolve. - std::function order_timestamp_copy; - std::function - sum_occlusion; - // Creates a query pool of `count` queries of that type for the single-list replay()'s occlusion and - // pipeline-statistics segments (D3D-399); the batched path creates its own. Unset, or with any sum helper unset, - // replay() refuses a list whose queries overlap, as before. - std::function(VkQueryType, std::uint32_t count)> create_segment_pool; - PFN_vkCmdBindPipeline bind_pipeline = nullptr; // dispatches - PFN_vkCmdPushConstants push_constants = nullptr; - PFN_vkCmdBindDescriptorSets bind_descriptor_sets = nullptr; // set 0 of pipelines that declare bindings - PFN_vkCmdDispatch dispatch = nullptr; - std::function compute_pipeline; - PFN_vkCmdBindVertexBuffers2 bind_vertex_buffers2 = nullptr; // draws - PFN_vkCmdBindIndexBuffer bind_index_buffer = nullptr; - PFN_vkCmdSetViewport set_viewport = nullptr; - PFN_vkCmdSetScissor set_scissor = nullptr; - PFN_vkCmdSetPrimitiveTopology set_primitive_topology = nullptr; - PFN_vkCmdSetPrimitiveRestartEnable set_primitive_restart_enable = nullptr; - PFN_vkCmdSetStencilReference set_stencil_reference = nullptr; - PFN_vkCmdSetBlendConstants set_blend_constants = nullptr; - PFN_vkCmdDraw draw = nullptr; - PFN_vkCmdDrawMeshTasksEXT draw_mesh_tasks = nullptr; // VK_EXT_mesh_shader; null: mesh draws are unsupported - PFN_vkCmdDrawIndexed draw_indexed = nullptr; - std::function graphics_pipeline; - // The buffer and offset a console VA range starts in (from ResourceBinding::va), false when none does. `size` is - // cut to what the buffer holds from there: vertex and index views use what fits, WriteBufferImmediate needs all - // of it. - std::function buffer_at; - // Host bytes for a whole console VA range; `not_cpu_written` when it names GPU-writable memory. For small - // CPU-written inputs, such as the pointer list of an ARRAY_OF_POINTERS TLAS build. - std::function host_at; - // Zeroed memory that unbound vertex-buffer slots and an unbound index buffer read (D3D12 reads zeros there). - VkBuffer zero_buffer = VK_NULL_HANDLE; - VkDeviceSize zero_offset = 0; - VkDeviceSize zero_size = 0; - std::uint64_t heap_base = 0; // device address of the GPU address arena (push-constant dwords 32-33) - // Resolves available binary-occlusion queries to 64-bit 0/1 values, outside conditional rendering. - std::function resolve_binary_occlusion; - // Adds `count` pipeline-statistics results into one D3D12_QUERY_DATA_PIPELINE_STATISTICS, outside conditional - // rendering: the segments of a statistics query split around resolves (D3D-162) and mesh draws (D3D-291). - // Segment i is in the second pool when mesh[i] is set (mesh may be null: none is). - std::function - sum_statistics; - // Sums `count` binary-occlusion segments and normalizes the total to a 64-bit 0 or 1, outside conditional - // rendering: a binary query split over physical segments because it overlaps other occlusion queries (D3D-252). - std::function sum_binary_occlusion; - // VK_EXT_debug_utils, set only when the instance enabled it; debug markers are skipped without them. - PFN_vkCmdInsertDebugUtilsLabelEXT insert_label = nullptr; - PFN_vkCmdBeginDebugUtilsLabelEXT begin_label = nullptr; - PFN_vkCmdEndDebugUtilsLabelEXT end_label = nullptr; - // ExecuteIndirect (Vulkan 1.0/1.2 core). - PFN_vkCmdDrawIndirect draw_indirect = nullptr; - PFN_vkCmdDrawIndexedIndirect draw_indexed_indirect = nullptr; - PFN_vkCmdDrawIndirectCount draw_indirect_count = nullptr; - PFN_vkCmdDrawIndexedIndirectCount draw_indexed_indirect_count = nullptr; - PFN_vkCmdDispatchIndirect dispatch_indirect = nullptr; - // A DISPATCH-only ExecuteIndirect signature with a GPU count buffer needs a compute prepass to clamp - // the number of commands. The resulting scratch buffer is owned by the queue's timeline-retained batch. - std::function prepare_counted_dispatch; - std::function emit_counted_dispatch; - // Optional VK_KHR_acceleration_structure: BuildRaytracingAccelerationStructure. - PFN_vkCmdBuildAccelerationStructuresKHR build_acceleration_structures = nullptr; - // A KHR TLAS built from D3D12_ELEMENTS_LAYOUT_ARRAY_OF_POINTERS needs a pointer array whose entries are Vulkan - // device addresses, not console VAs. This stages one that stays alive until the submission completes and returns - // its device address. A GPU-written list is refused as unsupported; a bad entry is invalid_copy. - std::function prepare_khr_instances; - // XDXR BVH4 builds (xdxr_build.h), used instead of the KHR ones when set: `xdxr_check` refuses inputs the builder - // cannot read while the list is prepared, `xdxr_record` records the build. - std::function xdxr_check; - std::function xdxr_record; - // CopyRaytracingAccelerationStructure (CLONE, COMPACT) of XDXR structures: `bytes` is the room the destination - // resource has; and one postbuild value (COMPACTED_SIZE, CURRENT_SIZE) of the structure at `src` to `dest`. - std::function xdxr_copy; - std::function xdxr_postbuild; - std::function resolve_acceleration_structure; - // CopyRaytracingAccelerationStructure (CLONE, COMPACT) and COMPACTED_SIZE postbuild on KHR acceleration structures. - PFN_vkCmdCopyAccelerationStructureKHR copy_acceleration_structure = nullptr; - PFN_vkCmdWriteAccelerationStructuresPropertiesKHR write_acceleration_structures_properties = nullptr; - std::function prepare_khr_postbuild; - // Preparation only allocates a slot; capture records the GPU snapshot at the SetPredication command. - std::function prepare_predicate; - std::function capture_predicate; - std::function&)> prepare_predicated_copy; - std::function&)> emit_predicated_copy; - // Returns a 2D-array view of the range (caller-owned, alive until execution completes); rectangle clears. - std::function image_view; - // Optional. The framebuffer, and through the last argument the render pass, that resolve the depth of the - // source's one-layer view into the destination's (both from image_view, each image in the layout after its - // view); alive until execution completes. Null: not available. For the resolves prepare names (D3D-417). - std::function - depth_resolve_framebuffer; - PFN_vkCmdBeginRenderPass begin_render_pass = nullptr; - PFN_vkCmdEndRenderPass end_render_pass = nullptr; - // Optional format check for color-attachment reinterpretation on mutable UAV clears; unset assumes every format - // except E5B9G9R9_UFLOAT_PACK32 supports COLOR_ATTACHMENT. - std::function color_attachment_format; - // Footprint copies of a depth24_as_float texture (depth24.h): `depth24_prepare` makes the scratch and descriptors - // for a job while the list is checked, `depth24_run` records its dispatch. Without them such a copy is unsupported. - std::function&)> depth24_prepare; // whole copy in, dispatches out - std::function depth24_run; - // `bytes` of transfer scratch that stays alive until the submission completes (vulkan_scratch.h): depth <-> colour - // copies go through it, image to buffer to image. Without it such a copy is unsupported. - std::function copy_scratch; - // Returns the query heap with that ID, or nullptr; it stays valid while the lists that use it run. - std::function query_pool; - bool separate_depth_stencil_layouts = false; // must match the LayoutTracker, if one is used -}; - -namespace detail { - -struct QueryResolveRun { - VkQueryPool pool = VK_NULL_HANDLE; // null: zero fill for queries that were never ended - std::uint32_t first = 0; - std::uint32_t count = 0; - VkDeviceSize offset = 0; - bool sum = false; - // Statistics segments: the mesh-compatible pool and the kind of each segment (OcclusionSegmentPool::mesh). - VkQueryPool mesh_pool = VK_NULL_HANDLE; - const std::uint8_t* mesh = nullptr; -}; - -struct PreparedQuery { - static constexpr std::uint32_t no_segment = UINT32_MAX; - std::size_t command = 0; - QueryPool* heap = nullptr; - bool statistics_active = false; - std::uint32_t begin_segment = no_segment; - std::uint32_t end_segment = no_segment; - std::uint32_t first_result = 0; - std::uint32_t result_count = 0; - // A pipeline-statistics query split around the helpers it contains (plan_statistics_segments): the physical - // statistics segment this command ends or begins, and for its EndQuery the segments that hold its result. - std::uint32_t statistics_end = no_segment; - std::uint32_t statistics_begin = no_segment; - std::uint32_t statistics_first = 0; - std::uint32_t statistics_count = 0; - std::vector resolves; -}; - -struct PreparedKhrPostbuild { - VkBuffer dst_buffer = VK_NULL_HANDLE; - VkDeviceSize dst_offset = 0; - VkQueryPool query_pool = VK_NULL_HANDLE; - std::uint32_t first_query = 0; - std::vector sources; -}; - -struct Prepared { - // Helper commands split the active statistics query just like query resolves, and so does a draw whose kind (mesh - // or vertex) differs from the draws before it in the current segment (plan_statistics_segments, D3D-291). - std::uint32_t statistics_end = PreparedQuery::no_segment; - std::uint32_t statistics_begin = PreparedQuery::no_segment; - PredicateCapture predicate; - std::vector predicated_copy; - CountedDispatch counted_dispatch; - ResourceBinding binding; - VkImageSubresourceRange range{}; // the barrier range, or the cleared view (cleared aspects only) - VkImageView view = VK_NULL_HANDLE; - VkFormat clear_format = VK_FORMAT_UNDEFINED; // The clear view format (RTV or reinterpreted UAV), without changing the resource binding. - std::vector rects; // rectangle clears, clipped to the mip - bool skip = false; // every rectangle was empty - ResourceBinding source; // copies: the source resource - VkImageSubresourceRange source_range{}; // copies: the source subresources (range: the destination's) - std::vector buffer_copies; - std::vector buffer_image_copies; // one direction, given by which side is an image - VkBuffer tile_scratch = VK_NULL_HANDLE; // CopyTiles with a byte-unaligned linear buffer offset - std::vector tile_rows; - std::vector image_copies; - bool same_copy_subresource = false; - VkImageResolve resolve{}; // resolves - // Depth or stencil resolves: the mode, and the destination view (`view` is the source's). - VkResolveModeFlagBits resolve_mode = VK_RESOLVE_MODE_NONE; - VkImageView resolve_view = VK_NULL_HANDLE; - // Set: the resolve runs in this render pass and framebuffer instead of a dynamic-rendering scope. - VkRenderPass resolve_pass = VK_NULL_HANDLE; - VkFramebuffer resolve_framebuffer = VK_NULL_HANDLE; - bool has_depth24 = false; // a depth plane copy of a depth24_as_float texture: convert through depth24 - // (or a copy of an rgb96 texture: repacked by the same pass) - std::uint32_t rgb96_row_words = 0; // an rgb96 footprint: words between its rows and between its slices - std::uint32_t rgb96_slice_words = 0; - Depth24Job depth24; // the whole copy: where its scratch floats are - std::vector depth24_parts; // the dispatches that convert it - // A depth <-> colour copy: the source into `staged` (image to buffer), then `staged` into the destination. - VkBuffer staged = VK_NULL_HANDLE; - std::vector staged_reads, staged_writes; - std::vector discards; // DiscardResource: the subresources to discard - VkBuffer write_buffer = VK_NULL_HANDLE; // WriteBufferImmediate: where the address lands - VkDeviceSize write_offset = 0; - uav_clear::Element element; // unordered-access clears: one element of the view's format - VkClearColorValue clear_color{}; // ... the value that writes it into the image - std::vector> fills; // ... buffer byte ranges, offset and size - VkBuffer fill_scratch = VK_NULL_HANDLE; // short buffer clears: one repeated 8-byte pattern - VkDeviceSize fill_scratch_offset = 0; - QueryPool* queries = nullptr; // query commands: the heap - ComputePipeline pipeline; // dispatches - std::uint32_t draw = 0; // draws: its PreparedDraw in PreparedList::draws - VkAccelerationStructureKHR accel_dst = VK_NULL_HANDLE; - VkDeviceAddress khr_instances = 0; // staged ARRAY_OF_POINTERS instance list for a KHR TLAS; 0: use the VA directly - std::uint64_t xdxr_bytes = 0; // CopyAccelerationStructure: the most bytes the copy may write - VkAccelerationStructureKHR accel_src = VK_NULL_HANDLE; - std::uint32_t khr_postbuild = ~0u; // index into PreparedList::khr_postbuilds; ~0u: skipped or XDXR -}; - -inline constexpr std::size_t max_render_targets = 8; // D3D12_SIMULTANEOUS_RENDER_TARGET_COUNT - -// What a draw needs beyond Prepared, kept apart in PreparedList::draws: every command's entry is refilled on every -// ExecuteCommandLists, and most commands are not draws. -struct PreparedDraw { - struct Attachment { - ResourceBinding binding; - ResourceId id = 0; - VkImageSubresourceRange range{}; - VkImageView view = VK_NULL_HANDLE; - }; - // The context's pipeline: alive while the list is prepared and emitted (VulkanQueue::execute holds the resource - // lock across both), so it is not copied. - const GraphicsPipeline* graphics = nullptr; - VkPipeline pipeline = VK_NULL_HANDLE; // graphics->pipeline, or its variant for the slots the draw leaves unbound - std::vector colors; // by slot; id 0 = unbound - Attachment depth; - std::vector vertex_buffers; - std::vector vertex_offsets, vertex_sizes, vertex_strides; - VkBuffer index_buffer = VK_NULL_HANDLE; - VkDeviceSize index_offset = 0; - VkIndexType index_type = VK_INDEX_TYPE_UINT16; - VkExtent2D area{}; - std::uint32_t layers = 1; // the fewest layers any bound attachment view has - - // Back to a new draw's state, keeping the vectors' storage. - void reset() { - graphics = nullptr; - pipeline = VK_NULL_HANDLE; - colors.clear(); - depth = {}; - vertex_buffers.clear(); - vertex_offsets.clear(); - vertex_sizes.clear(); - vertex_strides.clear(); - index_buffer = VK_NULL_HANDLE; - index_offset = 0; - index_type = VK_INDEX_TYPE_UINT16; - area = {}; - layers = 1; - } -}; - -// D3D converts a float clear value to a normalised format by rounding to nearest even, so an exact tie goes to the -// even neighbour (0.5 on 8 bits is 128). Vulkan leaves the rounding of ties to the GPU, and NVIDIA writes 127, one -// step below WARP and AMD. The value is rounded here and handed over as the exact fraction, which no GPU rounds -// differently. NaN is 0 and values outside 0..1 clamp, as in D3D. -// -// Ties go to even whatever the thread's floating-point rounding mode: std::nearbyint follows it, so a game that -// changes the mode would round differently. floor() does not depend on it, and x + 0.5 is exact here (x is at most -// a float times 65535, well inside a double's 53 bits). -inline double round_half_even(double x) { - const double r = std::floor(x + 0.5); - return r - x == 0.5 && std::fmod(r, 2.0) != 0.0 ? r - 1.0 : r; -} - -inline float quantize_unorm(float value, double maximum) { - if (!(value > 0.0f)) return 0.0f; - if (value >= 1.0f) return 1.0f; - return static_cast(round_half_even(double(value) * maximum) / maximum); -} - -// The same for a signed normalised format: -1..1 on a scale of 127 (8 bits) or 32767 (16 bits), where D3D writes -1.0 -// as -127 and ties go to the even neighbour. -inline float quantize_snorm(float value, double maximum) { - if (!(value > -1.0f)) return value != value ? 0.0f : -1.0f; - if (value >= 1.0f) return 1.0f; - return static_cast(round_half_even(double(value) * maximum) / maximum); -} - -// ClearRenderTargetView takes FLOATs even for integer RTVs. Windows D3D12 (WARP and AMD) clamps to the -// component range and truncates fractions. Vulkan instead interprets the matching union member as an integer -// already; copying float bits changes the value without a validation error. The normalised formats are rounded like -// D3D (quantize_unorm, quantize_snorm). -inline VkClearColorValue render_target_clear_color(VkFormat format, const ClearColor& input) { - // Integer formats convert the float numerically: NaN maps to zero, values below the range clamp to the low - // end, positive overflow (and +infinity) to the high end, and fractions truncate toward zero. Unsigned uses - // uint32, signed int32. A2B10G10R10 clamps RGB to 10 bits and alpha (channel 3) to 2 bits. - constexpr double u32_max = 4294967295.0, s32_min = -2147483648.0, s32_max = 2147483647.0; - double low = 0, high = 0, alpha_high = 0; - bool is_integer = true, is_signed = false; - std::array unorm{}; // the largest value of each normalised channel; 0 leaves the channel to the GPU - double snorm = 0; // the largest value of a signed normalised format - switch (format) { - case VK_FORMAT_R8_UINT: - case VK_FORMAT_R8G8_UINT: - case VK_FORMAT_R8G8B8A8_UINT: high = 255; break; - case VK_FORMAT_R16_UINT: - case VK_FORMAT_R16G16_UINT: - case VK_FORMAT_R16G16B16A16_UINT: high = 65535; break; - case VK_FORMAT_R32_UINT: - case VK_FORMAT_R32G32_UINT: - case VK_FORMAT_R32G32B32A32_UINT: high = u32_max; break; - case VK_FORMAT_A2B10G10R10_UINT_PACK32: high = 1023; alpha_high = 3; break; - case VK_FORMAT_R8_SINT: - case VK_FORMAT_R8G8_SINT: - case VK_FORMAT_R8G8B8A8_SINT: low = -128; high = 127; is_signed = true; break; - case VK_FORMAT_R16_SINT: - case VK_FORMAT_R16G16_SINT: - case VK_FORMAT_R16G16B16A16_SINT: low = -32768; high = 32767; is_signed = true; break; - case VK_FORMAT_R32_SINT: - case VK_FORMAT_R32G32_SINT: - case VK_FORMAT_R32G32B32A32_SINT: low = s32_min; high = s32_max; is_signed = true; break; - case VK_FORMAT_R8_SNORM: - case VK_FORMAT_R8G8_SNORM: - case VK_FORMAT_R8G8B8A8_SNORM: is_integer = false; snorm = 127; break; - case VK_FORMAT_R16_SNORM: - case VK_FORMAT_R16G16_SNORM: - case VK_FORMAT_R16G16B16A16_SNORM: is_integer = false; snorm = 32767; break; - case VK_FORMAT_R8_UNORM: - case VK_FORMAT_R8G8_UNORM: - case VK_FORMAT_R8G8B8A8_UNORM: - case VK_FORMAT_B8G8R8A8_UNORM: is_integer = false; unorm = {255, 255, 255, 255}; break; - case VK_FORMAT_R8G8B8A8_SRGB: - case VK_FORMAT_B8G8R8A8_SRGB: // the colour channels go through the sRGB curve on the GPU - is_integer = false; - unorm = {0, 0, 0, 255}; - break; - case VK_FORMAT_A2B10G10R10_UNORM_PACK32: is_integer = false; unorm = {1023, 1023, 1023, 3}; break; - case VK_FORMAT_R16_UNORM: - case VK_FORMAT_R16G16_UNORM: - case VK_FORMAT_R16G16B16A16_UNORM: is_integer = false; unorm = {65535, 65535, 65535, 65535}; break; - default: is_integer = false; break; - } - if (format != VK_FORMAT_A2B10G10R10_UINT_PACK32) alpha_high = high; - VkClearColorValue value{}; - for (std::size_t i = 0; i < input.size(); ++i) { - if (!is_integer) { - if (snorm != 0) value.float32[i] = quantize_snorm(input[i], snorm); - else value.float32[i] = unorm[i] != 0.0 ? quantize_unorm(input[i], unorm[i]) : input[i]; - continue; - } - const double maximum = i == 3 ? alpha_high : high; - const double v = double(input[i]); - // In range the cast truncates toward zero; out-of-range values never reach a float-to-int cast. - const double clamped = v != v ? 0.0 : v <= low ? low : v >= maximum ? maximum : v; - if (is_signed) value.int32[i] = static_cast(clamped); - else value.uint32[i] = static_cast(clamped); - } - return value; -} - -// The DXGI typeless family a color view format belongs to, by the Vulkan formats the layer maps its members to: the -// same nonzero number for formats one typeless resource can be viewed as, 0 for a format of no such family. -inline int typeless_view_family(VkFormat format) { - switch (format) { - case VK_FORMAT_R8G8B8A8_UNORM: case VK_FORMAT_R8G8B8A8_SRGB: case VK_FORMAT_R8G8B8A8_SNORM: - case VK_FORMAT_R8G8B8A8_UINT: case VK_FORMAT_R8G8B8A8_SINT: return 1; - case VK_FORMAT_B8G8R8A8_UNORM: case VK_FORMAT_B8G8R8A8_SRGB: return 2; - case VK_FORMAT_R16G16B16A16_SFLOAT: case VK_FORMAT_R16G16B16A16_UNORM: case VK_FORMAT_R16G16B16A16_SNORM: - case VK_FORMAT_R16G16B16A16_UINT: case VK_FORMAT_R16G16B16A16_SINT: return 3; - case VK_FORMAT_R32G32B32A32_SFLOAT: case VK_FORMAT_R32G32B32A32_UINT: case VK_FORMAT_R32G32B32A32_SINT: return 4; - case VK_FORMAT_R32G32_SFLOAT: case VK_FORMAT_R32G32_UINT: case VK_FORMAT_R32G32_SINT: return 5; - case VK_FORMAT_R16G16_SFLOAT: case VK_FORMAT_R16G16_UNORM: case VK_FORMAT_R16G16_SNORM: - case VK_FORMAT_R16G16_UINT: case VK_FORMAT_R16G16_SINT: return 6; - case VK_FORMAT_A2B10G10R10_UNORM_PACK32: case VK_FORMAT_A2B10G10R10_UINT_PACK32: return 7; - case VK_FORMAT_R8G8_UNORM: case VK_FORMAT_R8G8_SNORM: case VK_FORMAT_R8G8_UINT: case VK_FORMAT_R8G8_SINT: return 8; - case VK_FORMAT_R32_SFLOAT: case VK_FORMAT_R32_UINT: case VK_FORMAT_R32_SINT: return 9; - case VK_FORMAT_R16_SFLOAT: case VK_FORMAT_R16_UNORM: case VK_FORMAT_R16_SNORM: case VK_FORMAT_R16_UINT: - case VK_FORMAT_R16_SINT: return 10; - case VK_FORMAT_R8_UNORM: case VK_FORMAT_R8_SNORM: case VK_FORMAT_R8_UINT: case VK_FORMAT_R8_SINT: return 11; - default: return 0; - } -} - -// The RGBA8 and BGRA8 UNORM and SRGB formats: a castable-format list may cross between the two channel orders. -inline bool rgba8_any_order(VkFormat format) { - return format == VK_FORMAT_R8G8B8A8_UNORM || format == VK_FORMAT_R8G8B8A8_SRGB || - format == VK_FORMAT_B8G8R8A8_UNORM || format == VK_FORMAT_B8G8R8A8_SRGB; -} - -// The format a color view clears or renders in. A view of the resource's own format keeps it (a typeless resource -// has none, so it needs an explicit one). A typeless resource, or one created with a castable-format list (its image -// is mutable and lists the view formats), may be viewed in another format of its family: the image is mutable, so -// the view reinterprets its bits (D3D-275; before it only the RGBA8 family was). A castable RGBA8 or BGRA8 image may -// also be viewed in the other channel order, which the device let through only when the list names it. A volume -// keeps its own format. -inline VkFormat color_view_format(const ResourceBinding& resource, const TargetView& target) { - if (target.format == ColorViewFormat::resource) - return resource.typeless ? VK_FORMAT_UNDEFINED : resource.format; - const auto format = static_cast(target.format); - if (resource.uint_backed && format == resource.uint_backed) return format; // its logical format, listed at creation - const int family = typeless_view_family(format); - if (!family) return VK_FORMAT_UNDEFINED; - if (!resource.typeless && !resource.castable_view_formats) - return format == resource.format ? format : VK_FORMAT_UNDEFINED; - const bool other_order = resource.castable_view_formats && rgba8_any_order(format) && - rgba8_any_order(resource.format); - if ((family != typeless_view_family(resource.format) && !other_order) || resource.volume || resource.depth != 1) - return VK_FORMAT_UNDEFINED; - return format; -} - -inline bool view_range(const ResourceBinding& resource, const TargetView& view, VkImageAspectFlags aspects, - VkImageSubresourceRange& out) { - if (view.mip >= resource.mip_levels) return false; - if (resource.volume) { - const auto depth = std::max(1u, resource.depth >> view.mip); - if (aspects != VK_IMAGE_ASPECT_COLOR_BIT || view.first_layer >= depth || - !view.layer_count || view.layer_count > depth - view.first_layer) return false; - // Layouts and transfers address one array layer for the whole 3D mip. - out = {aspects, view.mip, 1, 0, 1}; - return true; - } - if (view.first_layer >= resource.array_layers || view.layer_count > resource.array_layers - view.first_layer) - return false; - out = {aspects, view.mip, 1, view.first_layer, view.layer_count}; - return true; -} - -// Without separate depth/stencil layouts both planes of a combined image move together. -inline VkImageSubresourceRange planes_for_layout(const ResourceBinding& resource, VkImageSubresourceRange range, - bool separate) { - if (two_planes(resource) && !separate) range.aspectMask = depth_stencil_aspects; - return range; -} - -inline VkExtent2D mip_extent(const ResourceBinding& resource, std::uint32_t mip) { - return {std::max(1u, resource.width >> mip), std::max(1u, resource.height >> mip)}; -} - -// Into `out`, replacing what it held: a kept PreparedList entry reuses the vector's storage. -inline void clip(std::span rects, VkExtent2D extent, std::uint32_t layers, std::vector& out) { - out.clear(); - for (const Rect& r : rects) { - const std::int64_t left = std::max(r.left, 0), top = std::max(r.top, 0); - const std::int64_t right = std::min(r.right, extent.width); - const std::int64_t bottom = std::min(r.bottom, extent.height); - if (right <= left || bottom <= top) continue; - out.push_back({{{std::int32_t(left), std::int32_t(top)}, {std::uint32_t(right - left), std::uint32_t(bottom - top)}}, - 0, layers}); - } -} - -inline constexpr VkPipelineStageFlags2 queue_stages_copy = - VK_PIPELINE_STAGE_2_TOP_OF_PIPE_BIT | VK_PIPELINE_STAGE_2_BOTTOM_OF_PIPE_BIT | VK_PIPELINE_STAGE_2_ALL_COMMANDS_BIT | - VK_PIPELINE_STAGE_2_HOST_BIT | VK_PIPELINE_STAGE_2_TRANSFER_BIT | VK_PIPELINE_STAGE_2_COPY_BIT; -inline constexpr VkPipelineStageFlags2 queue_stages_compute = - queue_stages_copy | VK_PIPELINE_STAGE_2_COMPUTE_SHADER_BIT | VK_PIPELINE_STAGE_2_DRAW_INDIRECT_BIT | - VK_PIPELINE_STAGE_2_CLEAR_BIT; - -inline void restrict_to_queue(const ReplayFunctions& vk, VkPipelineStageFlags2& stages, VkAccessFlags2& access) { - if (!vk.queue_stages) return; - VkAccessFlags2 allowed = VK_ACCESS_2_TRANSFER_READ_BIT | VK_ACCESS_2_TRANSFER_WRITE_BIT | - VK_ACCESS_2_MEMORY_READ_BIT | VK_ACCESS_2_MEMORY_WRITE_BIT | VK_ACCESS_2_HOST_READ_BIT | - VK_ACCESS_2_HOST_WRITE_BIT; - if (vk.queue_stages & VK_PIPELINE_STAGE_2_COMPUTE_SHADER_BIT) - allowed |= VK_ACCESS_2_SHADER_READ_BIT | VK_ACCESS_2_SHADER_WRITE_BIT | VK_ACCESS_2_UNIFORM_READ_BIT | - VK_ACCESS_2_SHADER_SAMPLED_READ_BIT | VK_ACCESS_2_SHADER_STORAGE_READ_BIT | - VK_ACCESS_2_SHADER_STORAGE_WRITE_BIT | VK_ACCESS_2_INDIRECT_COMMAND_READ_BIT; - stages &= vk.queue_stages; - if (!stages) stages = VK_PIPELINE_STAGE_2_ALL_COMMANDS_BIT; - access &= allowed; -} - -inline void restrict_to_queue(const ReplayFunctions& vk, VkPipelineStageFlags& stages, VkAccessFlags& access) { - if (!vk.queue_stages) return; - VkPipelineStageFlags2 s2 = stages; - VkAccessFlags2 a2 = access; - restrict_to_queue(vk, s2, a2); - stages = static_cast(s2 & 0xFFFFFFFFull); - access = static_cast(a2 & 0xFFFFFFFFull); -} - -// A D3D12 barrier on a volume mip covers every W slice, including on devices with maintenance9. -inline VkImageSubresourceRange layout_range(const ResourceBinding& resource, VkImageSubresourceRange range) { - if (resource.volume) range.layerCount = VK_REMAINING_ARRAY_LAYERS; - return range; -} - -inline void image_barrier(const ReplayFunctions& vk, VkCommandBuffer command_buffer, const ResourceBinding& resource, - const VkImageSubresourceRange& range, VkImageLayout old_layout, VkImageLayout new_layout, - VkAccessFlags src_access, VkPipelineStageFlags src_stages, VkAccessFlags dst_access, - VkPipelineStageFlags dst_stages) { - restrict_to_queue(vk, src_stages, src_access); - restrict_to_queue(vk, dst_stages, dst_access); - VkImageMemoryBarrier barrier{}; - barrier.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER; - barrier.srcAccessMask = src_access; - barrier.dstAccessMask = dst_access; - barrier.oldLayout = old_layout; - barrier.newLayout = new_layout; - barrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; - barrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; - barrier.image = resource.image; - barrier.subresourceRange = layout_range(resource, range); - vk.pipeline_barrier(command_buffer, src_stages, dst_stages, 0, 0, nullptr, 0, nullptr, 1, &barrier); -} - -inline void memory_barrier(const ReplayFunctions& vk, VkCommandBuffer command_buffer, VkAccessFlags src_access, - VkPipelineStageFlags src_stages, VkAccessFlags dst_access, VkPipelineStageFlags dst_stages) { - restrict_to_queue(vk, src_stages, src_access); - restrict_to_queue(vk, dst_stages, dst_access); - VkMemoryBarrier barrier{}; - barrier.sType = VK_STRUCTURE_TYPE_MEMORY_BARRIER; - barrier.srcAccessMask = src_access; - barrier.dstAccessMask = dst_access; - vk.pipeline_barrier(command_buffer, src_stages, dst_stages, 0, 1, &barrier, 0, nullptr, 0, nullptr); -} - -// The current layouts of a range: from the tracker, or `assumed` for an untracked image. -inline LayoutPieces current(const LayoutTracker* tracker, ResourceId id, const VkImageSubresourceRange& range, - VkImageLayout assumed) { - LayoutPieces out; - if (!tracker || !tracker->pieces(id, range, out)) { - out.clear(); - out.push_back({range, assumed}); - } - return out; -} - -// Zero-fills a block-compressed image range via vkCmdCopyBufferToImage from either the device's zero page -// (`vk.zero_buffer`) or a zeroed transfer-scratch chunk (`vk.copy_scratch` + `vk.fill_buffer`). Vulkan forbids -// vkCmdClearColorImage on BC formats, yet D3D12 committed resources start zeroed unless CREATE_NOT_ZEROED is set -// (D3D-220). -inline bool zero_compressed_image(const ReplayFunctions& vk, VkCommandBuffer command_buffer, - const ResourceBinding& resource, const VkImageSubresourceRange& range, - VkImageLayout dst_layout) { - const BlockFormat fmt = block_format(resource.format, VK_IMAGE_ASPECT_COLOR_BIT); - if (fmt.block < 1 || !fmt.bytes || !vk.copy_buffer_to_image) return false; - const std::uint32_t mip_begin = range.baseMipLevel; - const std::uint32_t mip_end = - range.levelCount == VK_REMAINING_MIP_LEVELS ? resource.mip_levels - : std::min(resource.mip_levels, mip_begin + range.levelCount); - const std::uint32_t layer_begin = range.baseArrayLayer; - const std::uint32_t layer_end = - range.layerCount == VK_REMAINING_ARRAY_LAYERS ? resource.array_layers - : std::min(resource.array_layers, layer_begin + range.layerCount); - if (mip_begin >= mip_end || layer_begin >= layer_end) return true; - - constexpr VkDeviceSize kMaxChunk = 64u * 1024u; - const std::uint32_t layer_count = layer_end - layer_begin; - VkDeviceSize needed = 0; - for (std::uint32_t mip = mip_begin; mip < mip_end; ++mip) { - const VkExtent2D ext = mip_extent(resource, mip); - const std::uint64_t bx = (std::uint64_t(ext.width) + fmt.block - 1) / fmt.block; - const std::uint64_t by = (std::uint64_t(ext.height) + fmt.block - 1) / fmt.block; - const std::uint64_t mip_d = std::max(1u, resource.depth >> mip); - const std::uint64_t slice_bytes = bx * by * fmt.bytes; - if (slice_bytes >= kMaxChunk || mip_d > kMaxChunk / slice_bytes || - layer_count > kMaxChunk / (slice_bytes * mip_d)) { - needed = kMaxChunk; - break; - } - needed = std::max(needed, slice_bytes * mip_d * layer_count); - } - if (!needed) return true; - - VkBuffer zero_buf = VK_NULL_HANDLE; - VkDeviceSize zero_off = 0; - VkDeviceSize zero_cap = 0; - if (vk.zero_buffer && vk.zero_size >= fmt.bytes) { - const VkDeviceSize align = fmt.bytes; - const VkDeviceSize pad = (align - (vk.zero_offset % align)) % align; - if (vk.zero_size >= pad + fmt.bytes) { - zero_buf = vk.zero_buffer; - zero_off = vk.zero_offset + pad; - zero_cap = vk.zero_size - pad; - } - } - if (!zero_buf && vk.copy_scratch && vk.fill_buffer) { - // Round up to a multiple of fmt.bytes (8 or 16, always a multiple of 4 for vkCmdFillBuffer). - const VkDeviceSize fill_bytes = ((needed + fmt.bytes - 1) / fmt.bytes) * fmt.bytes; - VkBuffer scratch = VK_NULL_HANDLE; - VkDeviceSize offset = 0; - if (vk.copy_scratch(fill_bytes, scratch, offset)) { - const VkDeviceSize align = fmt.bytes; - const VkDeviceSize pad = (align - (offset % align)) % align; - if (fill_bytes >= pad + fmt.bytes) { - vk.fill_buffer(command_buffer, scratch, offset + pad, fill_bytes - pad, 0); - memory_barrier(vk, command_buffer, VK_ACCESS_TRANSFER_WRITE_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, - VK_ACCESS_TRANSFER_READ_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT); - zero_buf = scratch; - zero_off = offset + pad; - zero_cap = fill_bytes - pad; - } - } - } - if (!zero_buf || zero_cap < fmt.bytes) return false; - - std::vector regions; - for (std::uint32_t mip = mip_begin; mip < mip_end; ++mip) { - const VkExtent2D ext = mip_extent(resource, mip); - const std::uint32_t mip_d = std::max(1u, resource.depth >> mip); - const std::uint64_t bx_total = (std::uint64_t(ext.width) + fmt.block - 1) / fmt.block; - const std::uint64_t by_total = (std::uint64_t(ext.height) + fmt.block - 1) / fmt.block; - const std::uint64_t slice_bytes = bx_total * by_total * fmt.bytes; - if (slice_bytes && slice_bytes <= zero_cap && mip_d <= zero_cap / slice_bytes && - layer_count <= zero_cap / (slice_bytes * mip_d)) { - VkBufferImageCopy r{}; - r.bufferOffset = zero_off; - r.imageSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, mip, layer_begin, layer_count}; - r.imageExtent = {ext.width, ext.height, mip_d}; - regions.push_back(r); - continue; - } - const std::uint64_t row_bytes = bx_total * fmt.bytes; - for (std::uint32_t layer = layer_begin; layer < layer_end; ++layer) { - if (slice_bytes <= zero_cap) { - const std::uint32_t slices_per_copy = - std::max(1u, std::uint32_t(std::min(mip_d, zero_cap / slice_bytes))); - for (std::uint32_t z = 0; z < mip_d; z += slices_per_copy) { - VkBufferImageCopy r{}; - r.bufferOffset = zero_off; - r.imageSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, mip, layer, 1}; - r.imageOffset = {0, 0, std::int32_t(z)}; - r.imageExtent = {ext.width, ext.height, std::min(slices_per_copy, mip_d - z)}; - regions.push_back(r); - } - } else if (row_bytes <= zero_cap) { - const std::uint32_t rows_per_copy = - std::max(1u, std::uint32_t(std::min(by_total, zero_cap / row_bytes))); - for (std::uint32_t z = 0; z < mip_d; ++z) { - for (std::uint64_t y_blk = 0; y_blk < by_total; y_blk += rows_per_copy) { - const std::uint32_t oy = std::uint32_t(y_blk * fmt.block); - const std::uint32_t eh = std::min(rows_per_copy * fmt.block, ext.height - oy); - VkBufferImageCopy r{}; - r.bufferOffset = zero_off; - r.imageSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, mip, layer, 1}; - r.imageOffset = {0, std::int32_t(oy), std::int32_t(z)}; - r.imageExtent = {ext.width, eh, 1}; - regions.push_back(r); - } - } - } else { - const std::uint32_t cols_per_copy = - std::max(1u, std::uint32_t(std::min(bx_total, zero_cap / fmt.bytes))); - for (std::uint32_t z = 0; z < mip_d; ++z) { - for (std::uint64_t y_blk = 0; y_blk < by_total; ++y_blk) { - const std::uint32_t oy = std::uint32_t(y_blk * fmt.block); - const std::uint32_t eh = std::min(fmt.block, ext.height - oy); - for (std::uint64_t x_blk = 0; x_blk < bx_total; x_blk += cols_per_copy) { - const std::uint32_t ox = std::uint32_t(x_blk * fmt.block); - const std::uint32_t ew = - std::min(cols_per_copy * fmt.block, ext.width - ox); - VkBufferImageCopy r{}; - r.bufferOffset = zero_off; - r.imageSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, mip, layer, 1}; - r.imageOffset = {std::int32_t(ox), std::int32_t(oy), std::int32_t(z)}; - r.imageExtent = {ew, eh, 1}; - regions.push_back(r); - } - } - } - } - } - } - if (!regions.empty()) - vk.copy_buffer_to_image(command_buffer, zero_buf, resource.image, dst_layout, - std::uint32_t(regions.size()), regions.data()); - return true; -} - -// Images registered with the tracker in UNDEFINED have never been used. D3D12 committed resources start zeroed, -// so each such piece is zero-filled (clear for uncompressed images, zero-buffer copy for block-compressed formats -// when a zero page or transfer scratch is available) and moved to `layout`, the layout the operation about to run -// expects; with not_zeroed, it is only moved. The tracker records it. -inline void initialize(const ReplayFunctions& vk, VkCommandBuffer command_buffer, const ResourceBinding& resource, - ResourceId id, LayoutPieces& pieces, VkImageLayout layout, LayoutTracker* tracker) { - constexpr VkAccessFlags any_memory = VK_ACCESS_MEMORY_READ_BIT | VK_ACCESS_MEMORY_WRITE_BIT; - for (auto& piece : pieces) { - if (piece.layout != VK_IMAGE_LAYOUT_UNDEFINED) continue; - const BlockFormat fmt = block_format(resource.format, VK_IMAGE_ASPECT_COLOR_BIT); - const bool color = piece.range.aspectMask & VK_IMAGE_ASPECT_COLOR_BIT; - const bool can_clear = !vk.queue_stages || ((vk.queue_stages & VK_PIPELINE_STAGE_2_CLEAR_BIT) && color); - const bool compressed = fmt.block > 1 || (!can_clear && color); - if (resource.not_zeroed || (!can_clear && !color)) { - image_barrier(vk, command_buffer, resource, piece.range, VK_IMAGE_LAYOUT_UNDEFINED, layout, 0, - VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, any_memory, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT); - } else if (compressed) { - const bool can_zero = - vk.copy_buffer_to_image && - ((vk.zero_buffer && vk.zero_size >= fmt.bytes) || (vk.copy_scratch && vk.fill_buffer)); - if (can_zero) { - const VkImageLayout dst = image_layout(resource, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL); - image_barrier(vk, command_buffer, resource, piece.range, VK_IMAGE_LAYOUT_UNDEFINED, dst, 0, - VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, VK_ACCESS_TRANSFER_WRITE_BIT, - VK_PIPELINE_STAGE_TRANSFER_BIT); - const bool zeroed = zero_compressed_image(vk, command_buffer, resource, piece.range, dst); - image_barrier(vk, command_buffer, resource, piece.range, dst, layout, - zeroed ? VK_ACCESS_TRANSFER_WRITE_BIT : 0, - zeroed ? VK_PIPELINE_STAGE_TRANSFER_BIT : VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, any_memory, - VK_PIPELINE_STAGE_ALL_COMMANDS_BIT); - } else { - image_barrier(vk, command_buffer, resource, piece.range, VK_IMAGE_LAYOUT_UNDEFINED, layout, 0, - VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, any_memory, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT); - } - } else { - const VkImageLayout dst = image_layout(resource, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL); - image_barrier(vk, command_buffer, resource, piece.range, VK_IMAGE_LAYOUT_UNDEFINED, dst, 0, - VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, VK_ACCESS_TRANSFER_WRITE_BIT, - VK_PIPELINE_STAGE_TRANSFER_BIT); - if (piece.range.aspectMask & VK_IMAGE_ASPECT_COLOR_BIT) { - const VkClearColorValue zero{}; - vk.clear_color_image(command_buffer, resource.image, dst, &zero, 1, &piece.range); - } else { - const VkClearDepthStencilValue zero{}; - vk.clear_depth_stencil_image(command_buffer, resource.image, dst, &zero, 1, &piece.range); - } - image_barrier(vk, command_buffer, resource, piece.range, dst, layout, VK_ACCESS_TRANSFER_WRITE_BIT, - VK_PIPELINE_STAGE_TRANSFER_BIT, any_memory, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT); - } - piece.layout = layout; - if (tracker) tracker->set(id, piece.range, layout); - } -} - -inline bool within(std::uint64_t offset, std::uint64_t size, std::uint64_t total) { - return offset <= total && size <= total - offset; -} - -inline VkDeviceSize indirect_record_size(IndirectKind kind) { - switch (kind) { - case IndirectKind::draw: return sizeof(VkDrawIndirectCommand); - case IndirectKind::draw_indexed: return sizeof(VkDrawIndexedIndirectCommand); - case IndirectKind::dispatch: return sizeof(VkDispatchIndirectCommand); - } - return 0; -} - -inline bool indirect_range(const ResourceBinding& binding, VkDeviceSize offset, VkDeviceSize bytes) { - return (binding.buffer_offset | offset) % sizeof(std::uint32_t) == 0 && - within(offset, bytes, binding.size) && - within(binding.buffer_offset, offset + bytes, UINT64_MAX); -} - -// The bytes of a buffer UAV clear, and whether the transfer commands can write them. Elements of up to 4 bytes -// repeat in every aligned word, so vkCmdFillBuffer writes the aligned middle and copies from it the unaligned ends -// (vkCmdCopyBuffer has no alignment rule); ranges without that word use transfer scratch. Wider elements are written -// with vkCmdUpdateBuffer and doubled with copies, which needs a word-aligned range. -inline bool buffer_fill_needs_scratch(const uav_clear::Element& element, VkDeviceSize offset, VkDeviceSize size) { - const VkDeviceSize prefix = (4 - offset % 4) % 4; - return element.size <= 4 && size && size < prefix + 4; -} - -inline ReplayResult prepare_buffer_uav_clear(const ClearUnorderedAccess& clear, Prepared& p) { - const UavView& view = clear.view; - if (!p.binding.buffer || p.binding.image) return ReplayResult::invalid_clear; - if (view.offset >= p.binding.size) return ReplayResult::invalid_subresource; - // A V# may reach past the end of the buffer (the hardware bounds-checks it); the clear stops at the end. - const std::uint64_t size = std::min(view.size, p.binding.size - view.offset); - if (view.format) { - if (!uav_clear::encode(VkFormat(view.format), clear.is_float, clear.values, p.element)) - return ReplayResult::unsupported; - if (view.element_size != p.element.size) return ReplayResult::invalid_clear; - } else { - p.element = uav_clear::raw_element(clear.values); - } - const std::uint32_t e = p.element.size; - const auto add = [&](std::uint64_t offset, std::uint64_t bytes) { - if (!bytes) return ReplayResult::success; - if (offset % std::min(e, 4u)) return ReplayResult::invalid_clear; - if (offset > UINT64_MAX - p.binding.buffer_offset || - bytes > UINT64_MAX - (p.binding.buffer_offset + offset)) return ReplayResult::invalid_clear; - offset += p.binding.buffer_offset; // the view is relative to the resource, which starts at buffer_offset - if (e > 4 && bytes % 4) { - return ReplayResult::unsupported; - } - p.fills.push_back({offset, bytes}); - return ReplayResult::success; - }; - if (clear.rects.empty()) return add(view.offset, size); - const std::uint64_t elements = size / view.element_size; - for (const Rect& r : clear.rects) { - if (r.top > 0 || r.bottom <= 0) continue; // a buffer has one row - const std::uint64_t left = std::uint64_t(std::max(r.left, 0)); - const std::uint64_t right = std::min(std::uint64_t(std::max(r.right, 0)), elements); - if (right <= left) continue; - if (const auto result = add(view.offset + left * view.element_size, (right - left) * view.element_size); - result != ReplayResult::success) - return result; - } - if (p.fills.empty()) p.skip = true; - return ReplayResult::success; -} - -// Writes one prepared range; the caller has made the buffer writable by transfers. -inline void emit_buffer_fill(const ReplayFunctions& vk, VkCommandBuffer command_buffer, VkBuffer buffer, - const uav_clear::Element& element, VkDeviceSize offset, VkDeviceSize size, - VkBuffer scratch = VK_NULL_HANDLE, VkDeviceSize scratch_offset = 0) { - const auto transfer_barrier = [&] { - memory_barrier(vk, command_buffer, VK_ACCESS_TRANSFER_WRITE_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, - VK_ACCESS_TRANSFER_READ_BIT | VK_ACCESS_TRANSFER_WRITE_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT); - }; - if (element.size <= 4) { - std::uint32_t word = 0; - for (unsigned i = 0; i < 4; ++i) word |= std::uint32_t(element.bytes[i % element.size]) << (8 * i); - if (buffer_fill_needs_scratch(element, offset, size)) { - // At most six bytes lack a complete aligned word. Fill eight scratch bytes, then copy just the - // requested range: never borrow a word from the application's neighbouring bytes. - vk.fill_buffer(command_buffer, scratch, scratch_offset, 8, word); - transfer_barrier(); - const VkBufferCopy region{scratch_offset, offset, size}; - vk.copy_buffer(command_buffer, scratch, buffer, 1, ®ion); - return; - } - const VkDeviceSize a0 = (offset + 3) / 4 * 4, a1 = (offset + size) / 4 * 4; - if (a1 > a0) vk.fill_buffer(command_buffer, buffer, a0, a1 - a0, word); - VkBufferCopy ends[2]{}; - std::uint32_t count = 0; - if (a0 > offset) ends[count++] = {offset + 4, offset, a0 - offset}; - if (a1 < offset + size) ends[count++] = {a1 - 4, a1, offset + size - a1}; - if (count) { - transfer_barrier(); - vk.copy_buffer(command_buffer, buffer, buffer, count, ends); - } - return; - } - constexpr VkDeviceSize update_limit = 65536; // vkCmdUpdateBuffer's, a multiple of every element size - const VkDeviceSize first = std::min(size, update_limit); - std::vector data(static_cast(first)); - for (std::size_t i = 0; i < data.size(); ++i) data[i] = element.bytes[i % element.size]; - vk.update_buffer(command_buffer, buffer, offset, first, data.data()); - for (VkDeviceSize filled = first; filled < size;) { - const VkDeviceSize step = std::min(filled, size - filled); - transfer_barrier(); - const VkBufferCopy copy{offset, offset + filled, step}; - vk.copy_buffer(command_buffer, buffer, buffer, 1, ©); - filled += step; - } -} - -// The one plane of one subresource a texture copy location names. -inline bool copy_subresource(const ResourceBinding& resource, std::uint32_t subresource, VkImageSubresourceRange& out) { - return resource.image && subresource != all_subresources && image_range(resource, subresource, out); -} - -// CopyTextureRegion: texture to texture, footprint to texture (upload) or texture to footprint (readback). -// Block-compressed footprints are padded to whole blocks; the Vulkan extent stops at the mip edge. -inline ReplayResult prepare_texture_copy(const CopyTexture& copy, Prepared& p) { - if (!copy.dst.footprint && !copy.src.footprint) { - VkImageSubresourceRange dst{}, src{}; - if (!copy_subresource(p.binding, copy.dst.subresource, dst) || - !copy_subresource(p.source, copy.src.subresource, src)) - return ReplayResult::invalid_subresource; - if ((dst.aspectMask != src.aspectMask && !depth_colour_pair(p.binding, p.source)) || - p.binding.volume != p.source.volume || p.binding.samples != p.source.samples || - p.binding.rgb96 != p.source.rgb96) - return ReplayResult::invalid_copy; - p.same_copy_subresource = p.source.image == p.binding.image && src.aspectMask == dst.aspectMask && - src.baseMipLevel == dst.baseMipLevel && src.baseArrayLayer == dst.baseArrayLayer; - const VkExtent2D from = mip_extent(p.source, src.baseMipLevel), to = mip_extent(p.binding, dst.baseMipLevel); - const auto from_depth = std::max(1u, p.source.depth >> src.baseMipLevel); - const auto to_depth = std::max(1u, p.binding.depth >> dst.baseMipLevel); - const CopyBox box = copy.has_box ? copy.box : CopyBox{0, 0, 0, from.width, from.height, from_depth}; - // A block-compressed box is in whole blocks and may run to the block-padded edge of the mip (the host runtime - // accepts it); Vulkan wants the extent to stop at the mip edge, as with a footprint. - const std::uint32_t block = block_format(p.source.format, src.aspectMask).block; - const auto padded = [block](std::uint32_t size) { return (size + block - 1) / block * block; }; - if (box.right > padded(from.width) || box.bottom > padded(from.height) || box.back > from_depth) - return ReplayResult::invalid_copy; - if (const std::uint32_t dst_block = block_format(p.binding.format, dst.aspectMask).block; dst_block != block) { - // A BC format and its uncompressed equivalent ("Format Conversion using Direct3D 10.1"): one texel of the - // uncompressed side is one block of the other. The box is in source texels, the offset in destination - // texels, and Vulkan takes the extent in source texels, cut at the source's mip edge. - const auto blocks = [](std::uint32_t size, std::uint32_t b) { return (size + b - 1) / b; }; - const bool same_bytes = - block_format(p.binding.format, dst.aspectMask).bytes == block_format(p.source.format, src.aspectMask).bytes; - if (!same_bytes || (box.left | box.top) % block || (copy.x | copy.y) % dst_block || box.left >= from.width || - box.top >= from.height || !within(copy.z, box.back - box.front, to_depth) || - copy.x / dst_block + blocks(box.right - box.left, block) > blocks(to.width, dst_block) || - copy.y / dst_block + blocks(box.bottom - box.top, block) > blocks(to.height, dst_block)) - return ReplayResult::invalid_copy; - const std::uint32_t w = std::min(padded(box.right - box.left), from.width - box.left); - const std::uint32_t h = std::min(padded(box.bottom - box.top), from.height - box.top); - const VkImageCopy region{{src.aspectMask, src.baseMipLevel, src.baseArrayLayer, 1}, - {std::int32_t(box.left), std::int32_t(box.top), std::int32_t(box.front)}, - {dst.aspectMask, dst.baseMipLevel, dst.baseArrayLayer, 1}, - {std::int32_t(copy.x), std::int32_t(copy.y), std::int32_t(copy.z)}, - {w, h, box.back - box.front}}; - const std::uint32_t dst_w = w * dst_block, dst_h = h * dst_block; - if (dst_block > 1 && (copy.x + dst_w > to.width || copy.y + dst_h > to.height)) { - // Each uncompressed texel supplies a whole BC block. Keep the same scratch row and slice strides - // in bytes on both sides, with a destination extent clipped to the actual mip. - const VkBufferImageCopy read{0, w, h, region.srcSubresource, region.srcOffset, region.extent}; - const VkBufferImageCopy write{0, dst_w, dst_h, region.dstSubresource, region.dstOffset, - {std::min(dst_w, to.width - copy.x), std::min(dst_h, to.height - copy.y), region.extent.depth}}; - p.staged_reads.push_back(read); - p.staged_writes.push_back(write); - } else { - p.image_copies.push_back(region); - } - p.range = dst; - p.source_range = src; - return ReplayResult::success; - } - std::uint32_t w = box.right - box.left, h = box.bottom - box.top; - const std::uint32_t d = box.back - box.front; - if (p.same_copy_subresource) { - const auto intersects = [](std::uint32_t a, std::uint32_t b, std::uint32_t size) { - return (a < b ? b - a : a - b) < size; - }; - if (intersects(box.left, copy.x, padded(w)) && intersects(box.top, copy.y, padded(h)) && - intersects(box.front, copy.z, d)) - return ReplayResult::invalid_copy; - } - if (block > 1) { - // D3D12 copies whole blocks: the box is rounded up to blocks and must fit the destination's padded mip. - // Vulkan takes an extent that is a block multiple or reaches the edge of each image separately, so the - // extent is cut where it reaches an edge, and a copy that cannot satisfy both images is staged (below). - if ((box.left | box.top | copy.x | copy.y) % block || box.left >= from.width || box.top >= from.height || - copy.x >= padded(to.width) || copy.y >= padded(to.height)) - return ReplayResult::invalid_copy; - w = padded(w); - h = padded(h); - if (w > padded(to.width) - copy.x || h > padded(to.height) - copy.y) return ReplayResult::invalid_copy; - // Each image's own extent: the whole blocks, cut where they reach that image's edge. - const std::uint32_t src_w = std::min(w, from.width - box.left), src_h = std::min(h, from.height - box.top); - const std::uint32_t dst_w = std::min(w, to.width - copy.x), dst_h = std::min(h, to.height - copy.y); - const std::uint32_t blocks_w = w, blocks_h = h; - w = std::min(src_w, dst_w); - h = std::min(src_h, dst_h); - const auto fits = [block](std::uint32_t offset, std::uint32_t extent, std::uint32_t size) { - return extent % block == 0 || offset + extent == size; - }; - if (!fits(box.left, w, from.width) || !fits(copy.x, w, to.width) || !fits(box.top, h, from.height) || - !fits(copy.y, h, to.height)) { - // No one extent does for both images: a mip edge inside a block on one side only (a 4x4 box into a - // 3x3 mip, a 6x6 mip into a 12x12 one). The source's blocks go into transfer scratch with its own - // cut extent and from there into the destination with the destination's (`staged_reads` and - // `staged_writes`, offsets from the start of the scratch; prepare allocates it). The box fits the - // source's padded mip, so the scratch holds every block the destination reads. - if (!within(copy.z, d, to_depth)) return ReplayResult::invalid_copy; - VkBufferImageCopy read{}; - read.bufferRowLength = blocks_w; - read.bufferImageHeight = blocks_h; - read.imageSubresource = {src.aspectMask, src.baseMipLevel, src.baseArrayLayer, 1}; - read.imageOffset = {std::int32_t(box.left), std::int32_t(box.top), std::int32_t(box.front)}; - read.imageExtent = {src_w, src_h, d}; - VkBufferImageCopy write = read; - write.imageSubresource = {dst.aspectMask, dst.baseMipLevel, dst.baseArrayLayer, 1}; - write.imageOffset = {std::int32_t(copy.x), std::int32_t(copy.y), std::int32_t(copy.z)}; - write.imageExtent = {dst_w, dst_h, d}; - p.staged_reads.push_back(read); - p.staged_writes.push_back(write); - p.range = dst; - p.source_range = src; - return ReplayResult::success; - } - } - if (!within(copy.x, w, to.width) || !within(copy.y, h, to.height) || !within(copy.z, d, to_depth)) - return ReplayResult::invalid_copy; - p.image_copies.push_back({{src.aspectMask, src.baseMipLevel, src.baseArrayLayer, 1}, - {std::int32_t(box.left), std::int32_t(box.top), std::int32_t(box.front)}, - {dst.aspectMask, dst.baseMipLevel, dst.baseArrayLayer, 1}, - {std::int32_t(copy.x), std::int32_t(copy.y), std::int32_t(copy.z)}, - {w, h, d}}); - p.range = dst; - p.source_range = src; - return ReplayResult::success; - } - - const bool upload = copy.src.footprint; - const ResourceBinding& image = upload ? p.binding : p.source; - const ResourceBinding& buffer = upload ? p.source : p.binding; - const CopyLocation& texture = upload ? copy.dst : copy.src; - const CopyLocation& placed = upload ? copy.src : copy.dst; - if (!buffer.buffer) return ReplayResult::invalid_copy; - VkImageSubresourceRange range{}; - if (!copy_subresource(image, texture.subresource, range)) return ReplayResult::invalid_subresource; - if (image.samples != 1) return ReplayResult::invalid_copy; // multisampled textures have no footprint - const BlockFormat format = copy_block_format(image, range.aspectMask); - // A 12-byte texel does not divide D3D12's 256-byte pitches; an rgb96 copy hands Vulkan the scratch buffer of - // the repack, never this pitch, and the pass reads the footprint in words. - if (!format.bytes || placed.row_pitch % (image.rgb96 ? 4 : format.bytes)) return ReplayResult::unsupported; - const VkExtent2D mip = mip_extent(image, range.baseMipLevel); - const auto mip_depth = std::max(1u, image.depth >> range.baseMipLevel); - // The box is in the source's coordinates: the footprint for an upload, the texture for a readback. - const CopyBox box = copy.has_box ? copy.box - : upload ? CopyBox{0, 0, 0, placed.width, placed.height, placed.depth} - : CopyBox{0, 0, 0, mip.width, mip.height, mip_depth}; - const std::uint32_t texture_x = upload ? copy.x : box.left, texture_y = upload ? copy.y : box.top; - const std::uint32_t placed_x = upload ? box.left : copy.x, placed_y = upload ? box.top : copy.y; - std::uint32_t w = box.right - box.left, h = box.bottom - box.top; - const auto texture_z = upload ? copy.z : box.front, placed_z = upload ? box.front : copy.z; - const auto depth = box.back - box.front; - if (!depth || !within(placed_z, depth, placed.depth) || !within(texture_z, depth, mip_depth) || - !within(placed_x, w, placed.width) || !within(placed_y, h, placed.height)) return ReplayResult::invalid_copy; - if (texture_x >= mip.width || texture_y >= mip.height) return ReplayResult::invalid_copy; - if (format.block > 1) { - w = std::min(w, mip.width - texture_x); - h = std::min(h, mip.height - texture_y); - } - if (!within(texture_x, w, mip.width) || !within(texture_y, h, mip.height)) return ReplayResult::invalid_copy; - if ((placed_x | placed_y | texture_x | texture_y) % format.block) return ReplayResult::invalid_copy; - const auto slice_rows = (std::uint64_t(placed.height) + format.block - 1) / format.block; - const std::uint64_t slice_pitch = slice_rows * placed.row_pitch; - if (!slice_pitch || placed.offset > buffer.size || placed_z > (buffer.size - placed.offset) / slice_pitch) - return ReplayResult::invalid_copy; - const auto slice_start = placed.offset + placed_z * slice_pitch; - const auto in_slice = std::uint64_t(placed_y / format.block) * placed.row_pitch + - std::uint64_t(placed_x / format.block) * format.bytes; - if (!within(slice_start, in_slice, buffer.size)) return ReplayResult::invalid_copy; - const auto offset = slice_start + in_slice; - // Vulkan wants a buffer offset that is a multiple of the texel size (VUID-vkCmdCopyBufferToImage-dstImage-07975), - // which D3D12's 512-byte placement does not give a 12-byte texel: one more reason an rgb96 copy is repacked. - const std::uint32_t alignment = (range.aspectMask & depth_stencil_aspects) || image.rgb96 ? 4 : format.bytes; - if (offset % alignment && !copy.tile_footprint) return ReplayResult::unsupported; - const std::uint64_t rows = (std::uint64_t(h) + format.block - 1) / format.block; - const std::uint64_t row_bytes = (std::uint64_t(w) + format.block - 1) / format.block * format.bytes; - if (!rows || !row_bytes || !within(std::uint64_t(placed_x / format.block) * format.bytes, row_bytes, placed.row_pitch) || - depth - 1 > (buffer.size - offset) / slice_pitch || - !within(offset + (depth - 1) * slice_pitch, (rows - 1) * placed.row_pitch + row_bytes, buffer.size)) - return ReplayResult::invalid_copy; - if (buffer.size > UINT64_MAX - buffer.buffer_offset) return ReplayResult::invalid_copy; - const VkDeviceSize backing_offset = buffer.buffer_offset + offset; - if (backing_offset % alignment && !copy.tile_footprint) return ReplayResult::unsupported; - VkBufferImageCopy region{}; - region.bufferOffset = backing_offset; - region.bufferRowLength = placed.row_pitch / format.bytes * format.block; - region.bufferImageHeight = depth > 1 ? std::uint32_t(slice_rows * format.block) : 0; - region.imageSubresource = {range.aspectMask, range.baseMipLevel, range.baseArrayLayer, 1}; - region.imageOffset = {std::int32_t(texture_x), std::int32_t(texture_y), std::int32_t(texture_z)}; - region.imageExtent = {w, h, depth}; - if (image.rgb96) { // the repack's scratch replaces this buffer in the copy; these are for the pass - if (placed.row_pitch / 4 > UINT32_MAX || slice_pitch / 4 > UINT32_MAX) return ReplayResult::unsupported; - p.rgb96_row_words = std::uint32_t(placed.row_pitch / 4); - p.rgb96_slice_words = std::uint32_t(slice_pitch / 4); - region.bufferRowLength = 0; - region.bufferImageHeight = 0; - } - p.buffer_image_copies.push_back(region); - (upload ? p.range : p.source_range) = range; - return ReplayResult::success; -} - -// RGBA8 CopyTiles accepts arbitrary byte offsets into its linear buffer, while VkBufferImageCopy requires texel -// alignment. Stage only the occupied texels through aligned transfer scratch; leave partial-tile padding alone. -inline bool stage_unaligned_tile(const ReplayFunctions& vk, Prepared& p, bool upload) { - auto& region = p.buffer_image_copies.front(); - const VkDeviceSize row_bytes = VkDeviceSize(region.imageExtent.width) * 4; - const VkDeviceSize pitch = VkDeviceSize(region.bufferRowLength) * 4; - const auto rows = region.imageExtent.height; - VkDeviceSize scratch_offset = 0; - if (!vk.copy_scratch || !vk.copy_scratch(row_bytes * rows, p.tile_scratch, scratch_offset)) return false; - const auto app_offset = region.bufferOffset; - const auto add_copy = [&](VkDeviceSize linear, VkDeviceSize scratch, VkDeviceSize bytes) { - p.tile_rows.push_back(upload ? VkBufferCopy{linear, scratch, bytes} : VkBufferCopy{scratch, linear, bytes}); - }; - if (row_bytes == pitch) { - add_copy(app_offset, scratch_offset, row_bytes * rows); - } else { - for (std::uint32_t row = 0; row < rows; ++row) - add_copy(app_offset + row * pitch, scratch_offset + row * row_bytes, row_bytes); - } - region.bufferOffset = scratch_offset; - region.bufferRowLength = 0; - return true; -} - -// CopyResource: the whole buffer, or every subresource of two textures of the same shape. -inline ReplayResult prepare_resource_copy(Prepared& p) { - if (p.binding.buffer && p.source.buffer) { - if (p.binding.size != p.source.size || !p.source.size) return ReplayResult::invalid_copy; - if (p.source.size > UINT64_MAX - p.source.buffer_offset || - p.binding.size > UINT64_MAX - p.binding.buffer_offset) - return ReplayResult::invalid_copy; - const VkDeviceSize src = p.source.buffer_offset; - const VkDeviceSize dst = p.binding.buffer_offset; - if (p.source.buffer == p.binding.buffer && src < dst + p.source.size && dst < src + p.source.size) - return ReplayResult::invalid_copy; - p.buffer_copies.push_back({src, dst, p.source.size}); - return ReplayResult::success; - } - const ResourceBinding &dst = p.binding, &src = p.source; - // A BC texture and one of its uncompressed equivalent match block for texel ("Format Conversion using - // Direct3D 10.1"); the Vulkan extent is in source texels. - const std::uint32_t sb = block_format(src.format, VK_IMAGE_ASPECT_COLOR_BIT).block; - const std::uint32_t db = block_format(dst.format, VK_IMAGE_ASPECT_COLOR_BIT).block; - const auto blocks = [](std::uint32_t size, std::uint32_t b) { return (size + b - 1) / b; }; - const bool same_shape = sb == db ? dst.width == src.width && dst.height == src.height - : blocks(dst.width, db) == blocks(src.width, sb) && - blocks(dst.height, db) == blocks(src.height, sb); - if (!dst.image || !src.image || !same_shape || - dst.depth != src.depth || dst.volume != src.volume || dst.mip_levels != src.mip_levels || - dst.array_layers != src.array_layers || (dst.aspects != src.aspects && !depth_colour_pair(dst, src)) || - dst.samples != src.samples || dst.rgb96 != src.rgb96 || - block_format(dst.format, VK_IMAGE_ASPECT_COLOR_BIT).bytes != block_format(src.format, VK_IMAGE_ASPECT_COLOR_BIT).bytes) - return ReplayResult::invalid_copy; - // A depth <-> colour pair has one aspect on each side; the copies name each side's own (staged by the caller). - const bool cross = dst.aspects != src.aspects; - for (const VkImageAspectFlags aspect : {VK_IMAGE_ASPECT_COLOR_BIT, VK_IMAGE_ASPECT_DEPTH_BIT, VK_IMAGE_ASPECT_STENCIL_BIT}) { - if (!(dst.aspects & aspect)) continue; - const VkImageAspectFlags src_aspect = cross ? src.aspects : aspect; - for (std::uint32_t mip = 0; mip < dst.mip_levels; ++mip) { - const VkExtent2D extent = mip_extent(src, mip), to = mip_extent(dst, mip); - // Lower mips can differ in blocks (BC 12x8 mip 1 is 2x1 blocks, R32G32 3x2 mip 1 is 1x1): more source - // blocks than the destination holds is refused, as by WARP. shortcut: a BC destination mip with a partial - // edge block cannot take a whole uncompressed texel per block in one vkCmdCopyImage; refused until such - // a copy is staged through a buffer. - if (sb != db && (blocks(extent.width, sb) * db > to.width || blocks(extent.height, sb) * db > to.height)) - return ReplayResult::invalid_copy; - p.image_copies.push_back({{src_aspect, mip, 0, dst.array_layers}, {0, 0, 0}, {aspect, mip, 0, dst.array_layers}, - {0, 0, 0}, {extent.width, extent.height, std::max(1u, src.depth >> mip)}}); - } - } - p.range = {dst.aspects, 0, dst.mip_levels, 0, dst.array_layers}; - p.source_range = {src.aspects, 0, src.mip_levels, 0, src.array_layers}; - return ReplayResult::success; -} - -// Resolve a multisampled colour image into a single-sampled image of the same format, or (a region) one plane of a -// depth/stencil image into the same plane of another: MIN or MAX, or AVERAGE of depth. -inline ReplayResult prepare_resolve(const ResolveSubresource& resolve, Prepared& p) { - VkImageSubresourceRange dst{}, src{}; - if (!copy_subresource(p.binding, resolve.dst_subresource, dst) || - !copy_subresource(p.source, resolve.src_subresource, src)) - return ReplayResult::invalid_subresource; - if (p.source.samples <= 1 || p.binding.samples != 1 || p.binding.volume) return ReplayResult::invalid_copy; - const VkExtent2D from = mip_extent(p.source, src.baseMipLevel), to = mip_extent(p.binding, dst.baseMipLevel); - VkOffset3D src_offset{}, dst_offset{}; - VkExtent3D extent{from.width, from.height, 1}; - if (const auto& region = resolve.region) { - dst_offset = {std::int32_t(region->dst_x), std::int32_t(region->dst_y), 0}; - if (const auto& r = region->src_rect) { - if (std::uint32_t(r->right) > from.width || std::uint32_t(r->bottom) > from.height) - return ReplayResult::invalid_copy; - src_offset = {r->left, r->top, 0}; - extent = {std::uint32_t(r->right - r->left), std::uint32_t(r->bottom - r->top), 1}; - } - if (!within(region->dst_x, extent.width, to.width) || !within(region->dst_y, extent.height, to.height)) - return ReplayResult::invalid_copy; - } else if (from.width != to.width || from.height != to.height) { - return ReplayResult::invalid_copy; - } - if (src.aspectMask != dst.aspectMask || p.source.format != p.binding.format) return ReplayResult::unsupported; - const auto& region = resolve.region; - if (src.aspectMask == VK_IMAGE_ASPECT_COLOR_BIT) { - if (region && region->mode != d3d12_resolve_mode::average) return ReplayResult::unsupported; - } else { - // A rendering scope resolves each pixel in place, so the destination offset must be the source's. - if (!region || dst_offset.x != src_offset.x || dst_offset.y != src_offset.y || - (region->mode == d3d12_resolve_mode::average && src.aspectMask != VK_IMAGE_ASPECT_DEPTH_BIT)) - return ReplayResult::unsupported; - p.resolve_mode = region->mode == d3d12_resolve_mode::minimum ? VK_RESOLVE_MODE_MIN_BIT - : region->mode == d3d12_resolve_mode::maximum ? VK_RESOLVE_MODE_MAX_BIT - : VK_RESOLVE_MODE_AVERAGE_BIT; - } - p.resolve = {{src.aspectMask, src.baseMipLevel, src.baseArrayLayer, 1}, src_offset, - {dst.aspectMask, dst.baseMipLevel, dst.baseArrayLayer, 1}, dst_offset, extent}; - p.range = dst; - p.source_range = src; - return ReplayResult::success; -} - -// A depth or stencil resolve of a rectangle runs in a rendering scope whose render area is the rectangle, and Vulkan -// resolves only inside it. MoltenVK resolves the whole destination subresource instead: the resolve is Metal's -// store action, which has no render area (measured on MoltenVK 1.4.2 and 1.4.3, docs/d3d12_vulkan.md). No Vulkan -// property tells, so on every GPU the texels around the rectangle go into `staged` before the resolve and come back -// after it, in up to four bands (`staged_reads`, one region per band, used in both directions). -inline ReplayResult keep_around_resolve(const ReplayFunctions& vk, Prepared& p) { - const VkExtent2D to = mip_extent(p.binding, p.range.baseMipLevel); - const auto x0 = std::uint32_t(p.resolve.dstOffset.x), y0 = std::uint32_t(p.resolve.dstOffset.y); - const std::uint32_t x1 = x0 + p.resolve.extent.width, y1 = y0 + p.resolve.extent.height; - const VkRect2D bands[4] = { - {{0, 0}, {to.width, y0}}, // above - {{0, std::int32_t(y1)}, {to.width, to.height - y1}}, // below - {{0, std::int32_t(y0)}, {x0, y1 - y0}}, // left - {{std::int32_t(x1), std::int32_t(y0)}, {to.width - x1, y1 - y0}}, // right - }; - // Depth aspects want 4-byte buffer offsets; 16 covers every texel size here. - const std::uint32_t texel = block_format(p.binding.format, p.range.aspectMask).bytes; - VkDeviceSize total = 0; - for (const VkRect2D& band : bands) { - if (!band.extent.width || !band.extent.height) continue; - VkBufferImageCopy region{}; - region.bufferOffset = total; - region.imageSubresource = p.resolve.dstSubresource; - region.imageOffset = {band.offset.x, band.offset.y, 0}; - region.imageExtent = {band.extent.width, band.extent.height, 1}; - p.staged_reads.push_back(region); - total += (VkDeviceSize(band.extent.width) * band.extent.height * texel + 15) / 16 * 16; - } - if (p.staged_reads.empty()) return ReplayResult::success; // the rectangle is the whole subresource - VkDeviceSize base = 0; - if (!texel || !vk.copy_image_to_buffer || !vk.copy_buffer_to_image || !vk.copy_scratch || - !vk.copy_scratch(total, p.staged, base)) - return ReplayResult::unsupported; - for (VkBufferImageCopy& region : p.staged_reads) region.bufferOffset += base; - return ReplayResult::success; -} - -// The layout a copy uses for a range: D3D12 requires copy_dest/copy_source, or common (GENERAL), where an implicit -// promotion lets the copy run in place. Anything else is moved to `wanted` and tracked. -inline VkImageLayout copy_layout(const ReplayFunctions& vk, VkCommandBuffer command_buffer, - const ResourceBinding& resource, ResourceId id, const VkImageSubresourceRange& range, - VkImageLayout wanted, VkAccessFlags access, LayoutTracker* tracker) { - const VkImageLayout target = image_layout(resource, wanted); - auto pieces = current(tracker, id, range, target); - initialize(vk, command_buffer, resource, id, pieces, target, tracker); - // D3D12 orders back-to-back copies and resolves on a resource that stays in COPY_DEST or COPY_SOURCE without a - // barrier from the application; Vulkan does not. A piece already in the transfer layout gets no layout - // transition, so an earlier transfer write to it is ordered here instead (write-after-write and read-after-write, - // which synchronization validation reports otherwise). - const auto after_transfer_writes = [&] { - memory_barrier(vk, command_buffer, VK_ACCESS_TRANSFER_WRITE_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, access, - VK_PIPELINE_STAGE_TRANSFER_BIT); - }; - if (pieces.size() == 1 && (pieces[0].layout == target || pieces[0].layout == VK_IMAGE_LAYOUT_GENERAL)) { - after_transfer_writes(); - return pieces[0].layout; - } - bool ordered = false; - for (const auto& piece : pieces) { - if (piece.layout == target) { - if (!ordered) after_transfer_writes(); - ordered = true; - continue; - } - image_barrier(vk, command_buffer, resource, piece.range, piece.layout, target, - VK_ACCESS_MEMORY_WRITE_BIT, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, access, - VK_PIPELINE_STAGE_TRANSFER_BIT); - } - if (tracker) tracker->set(id, range, target); - return target; -} - -// Moves every piece to `target` (src: the D3D12 state the operation requires), runs `body`, and moves the pieces -// back to where they were. Pieces already in `target` need no transition. -template -void round_trip(const ReplayFunctions& vk, VkCommandBuffer command_buffer, const ResourceBinding& resource, - const LayoutPieces& pieces, VkImageLayout target, const VulkanAccess& state, - VkAccessFlags target_access, VkPipelineStageFlags target_stages, Body&& body) { - for (const auto& piece : pieces) { - if (piece.layout == target) { - memory_barrier(vk, command_buffer, state.access, state.stages, target_access, target_stages); - continue; - } - image_barrier(vk, command_buffer, resource, piece.range, piece.layout, target, state.access, state.stages, - target_access, target_stages); - } - body(); - for (const auto& piece : pieces) { - if (piece.layout == target) { - memory_barrier(vk, command_buffer, target_access, target_stages, state.access, state.stages); - continue; - } - image_barrier(vk, command_buffer, resource, piece.range, target, piece.layout, target_access, target_stages, - state.access, state.stages); - } -} - -} // namespace detail - -namespace detail { - -// Resolves a draw's pipeline, attachments and buffers. Attachment views take the pipeline's formats, so a -// typeless texture is viewed as the format the pipeline renders. -template -ReplayResult prepare_draw(const Draw& draw, Resolve&& resolve, const ReplayFunctions& vk, PreparedDraw& p) { - if (!vk.graphics_pipeline || !vk.buffer_at || !vk.image_view || !vk.begin_rendering || !vk.end_rendering || - !vk.bind_vertex_buffers2 || !vk.bind_index_buffer || !vk.set_viewport || !vk.set_scissor || - !vk.set_primitive_topology || !vk.set_primitive_restart_enable || !vk.set_stencil_reference || - !vk.set_blend_constants || !vk.draw || - !vk.draw_indexed || !vk.bind_pipeline || !vk.push_constants) - return ReplayResult::unsupported; - const GraphicsPipeline* pipeline = vk.graphics_pipeline(draw.pipeline); - if (!pipeline || !pipeline->pipeline) return ReplayResult::unresolved_resource; - if (pipeline->mesh != draw.mesh) return ReplayResult::invalid_draw; - if (draw.mesh && !vk.draw_mesh_tasks) return ReplayResult::unsupported; - if (pipeline->bindless_set && !vk.bind_descriptor_sets) return ReplayResult::unsupported; - if (pipeline->color_formats.size() > max_render_targets) return ReplayResult::unsupported; - p.graphics = pipeline; - p.pipeline = pipeline->pipeline; - p.area = {UINT32_MAX, UINT32_MAX}; - std::uint32_t layers = UINT32_MAX; - const auto shrink = [&](const ResourceBinding& b, const TargetView& view, const VkImageSubresourceRange& range) { - const VkExtent2D e = mip_extent(b, view.mip); - p.area = {std::min(p.area.width, e.width), std::min(p.area.height, e.height)}; - layers = std::min(layers, range.layerCount); - }; - - p.colors.assign(pipeline->color_formats.size(), {}); - const std::uint32_t render_target_count = draw.views ? draw.views->render_target_count : 0; - for (std::size_t slot = 0; slot < render_target_count && slot < p.colors.size(); ++slot) { - const TargetView& target = draw.views->render_targets[slot]; - if (!target.resource) continue; - const ResourceBinding* binding = resolve(target.resource); - if (!binding) return ReplayResult::unresolved_resource; - auto& a = p.colors[slot]; - a.binding = *binding; - a.id = target.resource; - if (!a.binding.image || a.binding.aspects != VK_IMAGE_ASPECT_COLOR_BIT) return ReplayResult::invalid_clear; - // D3D12 requires the PSO's SampleDesc on every bound target (a mismatch is undefined); Vulkan's dynamic - // rendering requires the counts to agree, so the list fails here instead of in the driver. - if (a.binding.samples != pipeline->samples) return ReplayResult::invalid_subresource; - if (!view_range(a.binding, target, VK_IMAGE_ASPECT_COLOR_BIT, a.range)) return ReplayResult::invalid_subresource; - ResourceBinding viewed = a.binding; - if (pipeline->color_formats[slot] != VK_FORMAT_UNDEFINED) viewed.format = pipeline->color_formats[slot]; - a.view = vk.image_view(viewed, a.range); - if (!a.view) return ReplayResult::unsupported; - shrink(a.binding, target, a.range); - } - if (draw.depth.resource && pipeline->depth_format != VK_FORMAT_UNDEFINED) { - const ResourceBinding* binding = resolve(draw.depth.resource); - if (!binding) return ReplayResult::unresolved_resource; - auto& a = p.depth; - a.binding = *binding; - a.id = draw.depth.resource; - if (!a.binding.image || !(a.binding.aspects & depth_stencil_aspects)) return ReplayResult::invalid_clear; - if (a.binding.samples != pipeline->samples) return ReplayResult::invalid_subresource; - if (!view_range(a.binding, draw.depth, a.binding.aspects, a.range)) return ReplayResult::invalid_subresource; - ResourceBinding viewed = a.binding; - viewed.format = pipeline->depth_format; - a.view = vk.image_view(viewed, a.range); - if (!a.view) return ReplayResult::unsupported; - shrink(a.binding, draw.depth, a.range); - } - if (p.area.width == UINT32_MAX) { // no attachment: the viewport bounds the rendering - p.area = {std::uint32_t(std::max(0.0f, draw.viewport.x + draw.viewport.width)), - std::uint32_t(std::max(0.0f, draw.viewport.y + draw.viewport.height))}; - } - p.layers = layers == UINT32_MAX ? 1 : std::max(1u, layers); - - // Slots the pipeline has a format for but the draw leaves unbound take a variant whose format there is - // VK_FORMAT_UNDEFINED: D3D12 discards those writes, Vulkan wants the formats to match the attachments. - std::uint32_t unbound = 0; - for (std::size_t slot = 0; slot < p.colors.size(); ++slot) - if (pipeline->color_formats[slot] != VK_FORMAT_UNDEFINED && !p.colors[slot].id) unbound |= 1u << slot; - if (pipeline->depth_format != VK_FORMAT_UNDEFINED && !p.depth.id) unbound |= GraphicsPipeline::unbound_depth; - if (unbound) { - p.pipeline = pipeline->variant ? pipeline->variant(unbound) : VK_NULL_HANDLE; - if (!p.pipeline) return ReplayResult::unsupported; - } - - // An unbound vertex-buffer slot reads zeros, as in D3D12: the zero page with stride 0. Per-instance slots with - // step rate 0 also take stride 0, so every instance reads element 0. - for (std::uint32_t slot = 0; slot < 32; ++slot) { - if (!(pipeline->vertex_slots & (1u << slot))) continue; - p.vertex_buffers.resize(slot + 1, VK_NULL_HANDLE); - p.vertex_offsets.resize(slot + 1, 0); - p.vertex_sizes.resize(slot + 1, VK_WHOLE_SIZE); - p.vertex_strides.resize(slot + 1, 0); - const bool bound = draw.views && slot < draw.views->vertex_buffers.size() && - draw.views->vertex_buffers[slot].va; - if (!bound) { - if (!vk.zero_buffer) return ReplayResult::unresolved_resource; - p.vertex_buffers[slot] = vk.zero_buffer; - p.vertex_offsets[slot] = vk.zero_offset; - p.vertex_sizes[slot] = vk.zero_size; - p.vertex_strides[slot] = 0; - continue; - } - const VertexBufferView& view = draw.views->vertex_buffers[slot]; - std::uint64_t size = view.size; - if (!vk.buffer_at(view.va, size, p.vertex_buffers[slot], p.vertex_offsets[slot])) - return ReplayResult::unresolved_resource; - p.vertex_sizes[slot] = size; - p.vertex_strides[slot] = (pipeline->zero_step_slots & (1u << slot)) ? 0 : view.stride; - } - if (draw.indexed) { - if (draw.index.format == 57) p.index_type = VK_INDEX_TYPE_UINT16; - else if (draw.index.format == 42) p.index_type = VK_INDEX_TYPE_UINT32; - else if (draw.index.va) return ReplayResult::unsupported; - if (!draw.index.va) { // no index buffer: every index reads 0 - if (!vk.zero_buffer) return ReplayResult::unresolved_resource; - p.index_buffer = vk.zero_buffer; - p.index_offset = vk.zero_offset; - } else { - std::uint64_t size = draw.index.size; - if (!vk.buffer_at(draw.index.va, size, p.index_buffer, p.index_offset)) - return ReplayResult::unresolved_resource; - } - } - return ReplayResult::success; -} - -inline bool strip_topology(VkPrimitiveTopology topology) { - return topology == VK_PRIMITIVE_TOPOLOGY_LINE_STRIP || topology == VK_PRIMITIVE_TOPOLOGY_TRIANGLE_STRIP || - topology == VK_PRIMITIVE_TOPOLOGY_LINE_STRIP_WITH_ADJACENCY || - topology == VK_PRIMITIVE_TOPOLOGY_TRIANGLE_STRIP_WITH_ADJACENCY; -} - -// D3D_PRIMITIVE_TOPOLOGY -> VkPrimitiveTopology (patch lists are not modelled). -inline VkPrimitiveTopology vulkan_topology(std::uint32_t topology) { - switch (topology) { - case 1: return VK_PRIMITIVE_TOPOLOGY_POINT_LIST; - case 2: return VK_PRIMITIVE_TOPOLOGY_LINE_LIST; - case 3: return VK_PRIMITIVE_TOPOLOGY_LINE_STRIP; - case 5: return VK_PRIMITIVE_TOPOLOGY_TRIANGLE_STRIP; - case 10: return VK_PRIMITIVE_TOPOLOGY_LINE_LIST_WITH_ADJACENCY; - case 11: return VK_PRIMITIVE_TOPOLOGY_LINE_STRIP_WITH_ADJACENCY; - case 12: return VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST_WITH_ADJACENCY; - case 13: return VK_PRIMITIVE_TOPOLOGY_TRIANGLE_STRIP_WITH_ADJACENCY; - default: return VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST; - } -} - -// Moves an attachment's tracked pieces to `layout` before rendering (first use zero-fills, as everywhere). -inline void to_attachment(const ReplayFunctions& vk, VkCommandBuffer command_buffer, const PreparedDraw::Attachment& a, - VkImageLayout layout, VkAccessFlags access, VkPipelineStageFlags stages, - LayoutTracker* tracker, bool separate) { - const VkImageSubresourceRange range = planes_for_layout(a.binding, a.range, separate); - auto pieces = current(tracker, a.id, range, layout); - initialize(vk, command_buffer, a.binding, a.id, pieces, layout, tracker); - for (const auto& piece : pieces) { - if (piece.layout == layout) { - // Attachment writes of an earlier rendering scope are not ordered with this one without a barrier. - memory_barrier(vk, command_buffer, access, stages, access, stages); - continue; - } - image_barrier(vk, command_buffer, a.binding, piece.range, piece.layout, layout, - VK_ACCESS_MEMORY_WRITE_BIT, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, access, stages); - } - if (tracker) tracker->set(a.id, range, layout); -} - -} // namespace detail - -// Destination and source of a copy or resolve command. -inline std::pair copy_ids(const Command& command) { - if (const auto* c = std::get_if(&command)) return {c->dst, c->src}; - if (const auto* c = std::get_if(&command)) return {c->dst.resource, c->src.resource}; - if (const auto* c = std::get_if(&command)) return {c->dst, c->src}; - if (const auto* c = std::get_if(&command)) return {c->dst, c->src}; - return {0, 0}; -} - -// The heap, type and query range of a query command; count 0 for any other command. -struct QueryRange { - QueryHeapId heap = 0; - std::uint32_t type = 0; - std::uint32_t first = 0; - std::uint32_t count = 0; -}; - -inline QueryRange query_range(const Command& command) { - if (const auto* q = std::get_if(&command)) return {q->heap, q->type, q->index, 1}; - if (const auto* q = std::get_if(&command)) return {q->heap, q->type, q->index, 1}; - if (const auto* q = std::get_if(&command)) return {q->heap, q->type, q->first, q->count}; - return {}; -} - -// A list checked against the current resources, ready to emit. -class PreparedList { -public: - const CommandList* list = nullptr; - std::vector commands; - // The draws' own data, by Prepared::draw. Kept from one execution to the next like the PreparedList itself: the - // first draw_count entries are this list's, and the rest keep their vectors' storage for later draws. - std::vector draws; - std::size_t draw_count = 0; - std::vector queries; - VkQueryPool segment_pool = VK_NULL_HANDLE; - std::uint32_t segment_base = 0; - std::uint32_t segment_count = 0; - bool precise_segments = false; - // Physical pipeline-statistics segments (plan_statistics_segments), in a pool of their own. - VkQueryPool statistics_pool = VK_NULL_HANDLE; - std::uint32_t statistics_base = 0; - std::uint32_t statistics_segment_count = 0; - // The list's statistics queries overlap (D3D-252): without a statistics pool they cannot run whole, because - // two Vulkan queries of one type may not be active at once; QueryReplay::plan refuses such a list. - bool statistics_overlaps = false; - // For each of those segments, whether it holds mesh draws and so runs in statistics_mesh_pool (D3D-291). - std::vector statistics_mesh; - VkQueryPool statistics_mesh_pool = VK_NULL_HANDLE; - // Copies, resolves and UAV clears that run as transfers, recorded while a predicate was set. D3D12 skips them - // when the predicate says so, but Vulkan's conditional rendering does not cover transfer commands, so they run - // unconditionally (docs/d3d12_vulkan.md section 4.7). Counted so the caller can report it. - std::size_t unpredicated_copies = 0; - // Set when any command writes to a host_readable (READBACK) buffer so VulkanQueue only flushes to HOST_BIT when needed. - bool wrote_readback = false; - VkPipelineStageFlags2 readback_src_stages = 0; - std::vector khr_postbuilds; -}; - -inline ReplayResult plan_occlusion_segments(PreparedList& out) { - // Active logical queries cover a contiguous range of physical slots. A Begin or End closes the old - // slot and opens a new one if any query remains active. Each shared interval is recorded only once. - std::map, std::uint32_t> active; - std::uint32_t current = detail::PreparedQuery::no_segment; - for (auto& query : out.queries) { - const Command& command = out.list->commands()[query.command]; - if (std::holds_alternative(command)) continue; - const auto range = query_range(command); - // Binary occlusion is virtualized alongside the ordinary kind (D3D-252): both are VK_QUERY_TYPE_OCCLUSION, - // so one physical query is open at a time and a binary resolve normalizes the summed counts (0 or 1). - if (range.type != d3d12_query::occlusion && range.type != d3d12_query::binary_occlusion) continue; - const auto key = std::pair{range.heap, range.first}; - query.end_segment = current; - if (std::holds_alternative(command)) { - // A flattened bundle can reuse a slot already active in the parent list. - if (!active.emplace(key, out.segment_count).second) return ReplayResult::invalid_query; - out.precise_segments |= query.heap->precise; - } else { - const auto start = active.find(key); - if (start == active.end()) return ReplayResult::invalid_query; - query.first_result = start->second; - query.result_count = out.segment_count - start->second; - active.erase(start); - } - current = active.empty() ? detail::PreparedQuery::no_segment : out.segment_count++; - query.begin_segment = current; - } - return active.empty() ? ReplayResult::success : ReplayResult::invalid_query; -} - -// Helper dispatches must not contribute to the application's CSInvocations (D3D-162). Query resolves and -// ordinary helper commands share one sequence of physical statistics segments. Resolve dispatch requirements -// depend on heap state at planning time, so every non-timestamp resolve splits conservatively. -// A mesh draw cannot run while a query with the input-assembly, vertex, geometry or tessellation counters is active -// (VUID-vkCmdDrawMeshTasksEXT-pipelineStatistics-07076), though D3D12 allows it and reads those fields as 0. A query -// that holds a mesh draw is split as well (D3D-291): a segment's first draw decides whether it runs in the full pool -// or in the mesh one (statistics_mesh), and a later draw of the other kind ends it and begins one of its own kind. -// Dispatches and segments without draws use the full pool; ExecuteIndirect draws count as vertex draws. Each draw -// has its own rendering scope, so a split before one stays outside rendering, as a helper's does. -inline void plan_statistics_segments(PreparedList& out) { - detail::PreparedQuery* begin = nullptr; - // A split point (a helper or a resolve), or a draw: kind 0 vertex, 1 mesh. - struct Event { std::uint32_t* end; std::uint32_t* begin; int kind; }; - std::vector inner; - bool splits = false, mesh = false; - std::size_t next_query = 0; - const auto commands = out.list->commands(); - for (std::size_t i = 0; i < out.commands.size(); ++i) { - auto& p = out.commands[i]; - if (begin && (p.predicate.scratch || !p.predicated_copy.empty() || p.has_depth24 || - p.counted_dispatch.indirect)) { - inner.push_back({&p.statistics_end, &p.statistics_begin, -1}); - splits = true; - } - if (begin) { - int kind = -1; - if (const auto* draw = std::get_if(&commands[i])) kind = draw->mesh ? 1 : 0; - else if (const auto* indirect = std::get_if(&commands[i])) - kind = indirect->kind == IndirectKind::dispatch ? -1 : 0; - if (kind >= 0) inner.push_back({&p.statistics_end, &p.statistics_begin, kind}); - mesh |= kind == 1; - } - if (next_query == out.queries.size() || out.queries[next_query].command != i) continue; - auto& query = out.queries[next_query++]; - const Command& command = commands[i]; - const auto range = query_range(command); - if (std::holds_alternative(command)) { - // A stream-output resolve only fills zeros (no dispatch), so it needs no split. - if (begin && range.type != d3d12_query::timestamp && !is_so_statistics(range.type)) { - inner.push_back({&query.statistics_end, &query.statistics_begin, -1}); - splits = true; - } - } else if (range.type == d3d12_query::pipeline_statistics) { - if (std::holds_alternative(command)) { - begin = &query; - inner.clear(); - splits = mesh = false; - } else if (begin) { - if (splits || mesh) { - const std::uint32_t first = out.statistics_segment_count; - const auto open = [&] { - out.statistics_mesh.push_back(0); - return out.statistics_segment_count++; - }; - std::uint32_t current = begin->statistics_begin = open(); - int kind = -1; // of the current segment's draws, -1 before its first - for (const auto& event : inner) { - if (event.kind < 0) { - *event.end = current; - current = *event.begin = open(); - kind = -1; - continue; - } - if (kind >= 0 && event.kind != kind) { - *event.end = current; - current = *event.begin = open(); - } - kind = event.kind; - out.statistics_mesh[current] = std::uint8_t(kind); - } - query.statistics_end = current; - query.statistics_first = first; - query.statistics_count = out.statistics_segment_count - first; - } - begin = nullptr; - inner.clear(); - } - } - } -} - -// Overlapping pipeline-statistics queries (D3D-252): the same physical-segment layout the occlusion planner -// builds, in the statistics pool. Each Begin and End of a statistics query — and every non-timestamp resolve -// while one runs, because its helper dispatch would be counted — closes the one open physical query and opens -// a new one, so each logical query keeps a contiguous slot range and its result is the sum of that range -// (statistics_sum.comp). A Begin or End of another query kind leaves the segments alone. -inline ReplayResult plan_overlapping_statistics_segments(PreparedList& out) { - std::map, std::uint32_t> active; - std::uint32_t current = detail::PreparedQuery::no_segment; - std::size_t next_query = 0; - // Each physical segment's draw kind (D3D-291): -1 before its first draw, 0 vertex, 1 mesh. - int kind = -1; - const auto open = [&] { - out.statistics_mesh.push_back(0); - kind = -1; - return out.statistics_segment_count++; - }; - const auto commands = out.list->commands(); - for (std::size_t i = 0; i < out.commands.size(); ++i) { - auto& p = out.commands[i]; - detail::PreparedQuery* query = nullptr; - if (next_query != out.queries.size() && out.queries[next_query].command == i) - query = &out.queries[next_query++]; - if (!query) { - // A helper dispatch while a query runs would be counted into it (D3D-162): close the shared physical - // segment before it and open a new one after, the way resolves do. - if (!active.empty() && (p.predicate.scratch || !p.predicated_copy.empty() || p.has_depth24 || - p.counted_dispatch.indirect)) { - p.statistics_end = current; - current = open(); - p.statistics_begin = current; - continue; - } - // A draw of the other kind than the open segment's starts a segment in its own pool (D3D-291). - int draw = -1; - if (const auto* d = std::get_if(&commands[i])) draw = d->mesh ? 1 : 0; - else if (const auto* indirect = std::get_if(&commands[i])) - draw = indirect->kind == IndirectKind::dispatch ? -1 : 0; - if (!active.empty() && draw >= 0) { - if (kind >= 0 && draw != kind) { - p.statistics_end = current; - current = open(); - p.statistics_begin = current; - } - kind = draw; - out.statistics_mesh[current] = std::uint8_t(draw); - } - continue; - } - const Command& command = out.list->commands()[i]; - const auto range = query_range(command); - if (!std::holds_alternative(command)) { - // A Begin or End of another query kind leaves the shared segment alone. - if (range.type != d3d12_query::pipeline_statistics) continue; - query->statistics_end = current; - const auto key = std::pair{range.heap, range.first}; - if (std::holds_alternative(command)) { - // A flattened bundle can reuse a slot already active in the parent list. - if (!active.emplace(key, out.statistics_segment_count).second) return ReplayResult::invalid_query; - } else { - const auto start = active.find(key); - if (start == active.end()) return ReplayResult::invalid_query; - query->statistics_first = start->second; - query->statistics_count = out.statistics_segment_count - start->second; - active.erase(start); - } - } else { - if (current == detail::PreparedQuery::no_segment || range.type == d3d12_query::timestamp) continue; - query->statistics_end = current; - current = open(); - query->statistics_begin = current; - continue; - } - current = active.empty() ? detail::PreparedQuery::no_segment : open(); - query->statistics_begin = current; - } - return active.empty() ? ReplayResult::success : ReplayResult::invalid_query; -} - -// detail::initialize zero-clears an image piece the tracker holds in UNDEFINED (D3D12 committed resources start -// zeroed) the first time a command touches it, with vkCmdClearColorImage or vkCmdClearDepthStencilImage. True when -// a command of the list would need one of those and it is unset; replay() then refuses the list as unsupported, as -// prepare() does for every other optional function, rather than emit calling a null pointer. -inline bool zero_clear_unavailable(const PreparedList& prepared, const ReplayFunctions& vk, - const LayoutTracker& tracker) { - if (vk.clear_color_image && vk.clear_depth_stencil_image) return false; - std::vector pieces; - const auto missing = [&](ResourceId id, const ResourceBinding& resource, const VkImageSubresourceRange& range) { - if (!id || !resource.image || resource.not_zeroed || - block_format(resource.format, VK_IMAGE_ASPECT_COLOR_BIT).block > 1) // only moved, never cleared - return false; - pieces.clear(); - if (!tracker.pieces(id, range, pieces)) return false; - for (const auto& piece : pieces) - if (piece.layout == VK_IMAGE_LAYOUT_UNDEFINED && - ((piece.range.aspectMask & VK_IMAGE_ASPECT_COLOR_BIT) ? !vk.clear_color_image - : !vk.clear_depth_stencil_image)) - return true; - return false; - }; - const auto commands = prepared.list->commands(); - for (std::size_t i = 0; i < commands.size(); ++i) { - const auto& command = commands[i]; - const auto& p = prepared.commands[i]; - if (p.skip) continue; - if (const auto [dst, src] = copy_ids(command); dst || src) { - if (missing(dst, p.binding, p.range) || missing(src, p.source, p.source_range)) return true; - continue; - } - const ResourceId id = std::visit( - [](const auto& c) -> ResourceId { - using T = std::decay_t; - if constexpr (std::is_same_v || std::is_same_v) - return c.target.resource; - else if constexpr (std::is_same_v) - return c.view.resource; - else if constexpr (requires { c.resource; }) - return c.resource; - else - return 0; - }, - command); - if (missing(id, p.binding, p.range)) return true; - } - return false; -} - -// Resolves and checks every command. Nothing is written to a command buffer. -// Resolve maps a ResourceId to a const ResourceBinding* (nullptr: unknown). -// statistics_helpers promises a statistics segment pool at QueryReplay::plan(). Keep the default for replay() -// and callers without a summation helper: reject before allocating any helper scratch. -template -ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFunctions& vk, PreparedList& out, - bool statistics_helpers = false) { - if (!list.closed()) return ReplayResult::list_open; - if (list.queries_open()) return ReplayResult::invalid_query; // a Vulkan query must end in its command buffer - const auto commands = list.commands(); - out.list = &list; - out.commands.assign(commands.size(), {}); - out.draw_count = 0; - out.queries.clear(); - out.segment_pool = VK_NULL_HANDLE; - out.segment_base = out.segment_count = 0; - out.precise_segments = false; - out.statistics_pool = out.statistics_mesh_pool = VK_NULL_HANDLE; - out.statistics_base = out.statistics_segment_count = 0; - out.statistics_mesh.clear(); - out.khr_postbuilds.clear(); - const bool rendering = vk.begin_rendering && vk.end_rendering && vk.clear_attachments && vk.image_view; - const bool copies = vk.copy_buffer && vk.copy_buffer_to_image && vk.copy_image_to_buffer && vk.copy_image; - const bool conditional = vk.begin_conditional_rendering && vk.end_conditional_rendering; - // While a predicate is set, a whole-view clear is replayed as one rectangle over the view: vkCmdClearColorImage - // and vkCmdClearDepthStencilImage ignore conditional rendering, vkCmdClearAttachments does not. - bool predicated = false; - constexpr Rect whole_view{0, 0, INT32_MAX, INT32_MAX}; - const auto clear_rects = [&](std::span rects) { - return predicated && rects.empty() ? std::span(&whole_view, 1) : rects; - }; - out.unpredicated_copies = 0; - const bool queries = vk.reset_query_pool && vk.begin_query && vk.end_query && vk.write_timestamp && - vk.copy_query_pool_results && vk.fill_buffer && vk.query_pool; - // Vulkan allows one active query per type. Overlapping ordinary and binary occlusion share one physical - // segment pool, and overlapping statistics split into the statistics pool (D3D-252); a physical query of a - // type is still open at most once at any point, because each event closes the one open slot and opens a new - // one. The occlusion kinds share their D3D12 heap, statistics have their own, so their states are separate. - std::size_t ordinary_active = 0, binary_active = 0, statistics_active_count = 0; - bool overlaps = false, statistics_overlaps = false, statistics_active = false; - out.wrote_readback = false; - out.readback_src_stages = 0; - - for (std::size_t i = 0; i < commands.size(); ++i) { - const auto& command = commands[i]; - auto& p = out.commands[i]; - const auto bind = [&](ResourceId id) { - const ResourceBinding* binding = resolve(id); - if (binding) p.binding = *binding; - return binding != nullptr; - }; - const auto rect_view = [&](std::span rects, const TargetView& target, VkImageAspectFlags view_aspects) { - if (rects.empty()) return ReplayResult::success; - if (!rendering) return ReplayResult::unsupported; - detail::clip(rects, detail::mip_extent(p.binding, target.mip), target.layer_count, p.rects); - if (p.rects.empty()) { - p.skip = true; - return ReplayResult::success; - } - VkImageSubresourceRange range = p.range; - range.aspectMask = view_aspects; - if (p.binding.volume) { - // A 2D-array attachment view of a 3D image selects W slices here. - range.baseArrayLayer = target.first_layer; - range.layerCount = target.layer_count; - } - ResourceBinding view_binding = p.binding; - if (p.clear_format != VK_FORMAT_UNDEFINED) view_binding.format = p.clear_format; - p.view = vk.image_view(view_binding, range); - return p.view ? ReplayResult::success : ReplayResult::unsupported; - }; - - if (const auto* transition = std::get_if(&command)) { - if (!bind(transition->resource)) return ReplayResult::unresolved_resource; - if (p.binding.image == VK_NULL_HANDLE) { - if (transition->subresource != 0 && transition->subresource != all_subresources) - return ReplayResult::invalid_subresource; - } else if (!image_range(p.binding, transition->subresource, p.range)) { - return ReplayResult::invalid_subresource; - } - } else if (std::holds_alternative(command) || std::holds_alternative(command)) { - if (!vk.pipeline_barrier2) return ReplayResult::unsupported; - if (const auto* buffer_barrier = std::get_if(&command)) - if (!bind(buffer_barrier->resource)) return ReplayResult::unresolved_resource; - } else if (const auto* texture = std::get_if(&command)) { - if (!vk.pipeline_barrier2) return ReplayResult::unsupported; - if (!bind(texture->resource)) return ReplayResult::unresolved_resource; - if (!p.binding.image || !barrier_range(p.binding, texture->range, p.range)) - return ReplayResult::invalid_subresource; - } else if (const auto* color_clear = std::get_if(&command)) { - if (!bind(color_clear->target.resource)) return ReplayResult::unresolved_resource; - if (!p.binding.image || p.binding.aspects != VK_IMAGE_ASPECT_COLOR_BIT) return ReplayResult::invalid_clear; - if (!detail::view_range(p.binding, color_clear->target, VK_IMAGE_ASPECT_COLOR_BIT, p.range)) - return ReplayResult::invalid_subresource; - p.clear_format = detail::color_view_format(p.binding, color_clear->target); - // Older ownerless replay callers omit the resource format for float-only clears. Preserve - // that path; an explicit format or a typeless resource must still resolve a concrete RTV. - if (p.clear_format == VK_FORMAT_UNDEFINED && - (p.binding.typeless || color_clear->target.format != ColorViewFormat::resource)) - return ReplayResult::invalid_clear; - const bool partial_volume = p.binding.volume && - color_clear->target.layer_count != std::max(1u, p.binding.depth >> color_clear->target.mip); - if ((p.clear_format != p.binding.format || partial_volume) && color_clear->rects.empty()) { - // vkCmdClearColorImage can neither reinterpret the format nor select W slices of a mip. - const auto extent = detail::mip_extent(p.binding, color_clear->target.mip); - const Rect full{0, 0, std::int32_t(extent.width), std::int32_t(extent.height)}; - if (const auto r = rect_view(std::span(&full, 1), color_clear->target, - VK_IMAGE_ASPECT_COLOR_BIT); r != ReplayResult::success) return r; - } else if (const auto r = rect_view(clear_rects(color_clear->rects), color_clear->target, VK_IMAGE_ASPECT_COLOR_BIT); - r != ReplayResult::success) return r; - if (!p.skip && p.rects.empty() && !vk.clear_color_image) return ReplayResult::unsupported; - } else if (const auto* depth_clear = std::get_if(&command)) { - if (!bind(depth_clear->target.resource)) return ReplayResult::unresolved_resource; - VkImageAspectFlags aspects = 0; - if (depth_clear->flags & clear_depth) aspects |= VK_IMAGE_ASPECT_DEPTH_BIT; - if (depth_clear->flags & clear_stencil) aspects |= VK_IMAGE_ASPECT_STENCIL_BIT; - const VkImageAspectFlags available = p.binding.aspects & depth_stencil_aspects; - if (!p.binding.image || !available || (p.binding.aspects & ~depth_stencil_aspects)) - return ReplayResult::invalid_clear; - // A flag for a plane the view's format doesn't have is ignored, as the PC D3D12 runtime (WARP) and native - // drivers do: STENCIL on a D32_FLOAT view clears nothing, DEPTH | STENCIL clears the depth plane. Until - // 2026-11-23 it returned invalid_clear here and the whole list was dropped (D3D-437). - aspects &= available; - if (!detail::view_range(p.binding, depth_clear->target, aspects, p.range)) - return ReplayResult::invalid_subresource; - if (!aspects) p.skip = true; - if (const auto r = rect_view(clear_rects(depth_clear->rects), depth_clear->target, p.binding.aspects); - r != ReplayResult::success) - return r; - if (!p.skip && p.rects.empty() && !vk.clear_depth_stencil_image) return ReplayResult::unsupported; - } else if (const auto* uav = std::get_if(&command)) { - const UavView& view = uav->view; - if (!bind(view.resource)) return ReplayResult::unresolved_resource; - if (view.buffer) { - if (!vk.fill_buffer || !vk.update_buffer || !vk.copy_buffer) return ReplayResult::unsupported; - if (predicated) ++out.unpredicated_copies; // fills and copies are transfer commands - if (const auto r = detail::prepare_buffer_uav_clear(*uav, p); r != ReplayResult::success) return r; - const bool short_fill = std::any_of(p.fills.begin(), p.fills.end(), [&](const auto& fill) { - return detail::buffer_fill_needs_scratch(p.element, fill[0], fill[1]); - }); - if (short_fill && (!vk.copy_scratch || - !vk.copy_scratch(8, p.fill_scratch, p.fill_scratch_offset) || !p.fill_scratch || - p.fill_scratch_offset % 4 || p.fill_scratch_offset > UINT64_MAX - 8)) - return ReplayResult::unsupported; - if (!p.skip && !p.fills.empty() && p.binding.host_readable) { - out.wrote_readback = true; - out.readback_src_stages |= VK_PIPELINE_STAGE_2_TRANSFER_BIT; - } - continue; - } - if (!p.binding.image || p.binding.aspects != VK_IMAGE_ASPECT_COLOR_BIT) return ReplayResult::invalid_clear; - const TargetView target{view.resource, view.mip, view.first_layer, view.layer_count}; - if (!detail::view_range(p.binding, target, VK_IMAGE_ASPECT_COLOR_BIT, p.range)) - return ReplayResult::invalid_subresource; - // The view's format turns the values into bytes. When the view format differs from the image's backing - // format (a typeless or castable texture) and can be cleared as a color attachment, clear through a view of - // view_format instead of decoding into the backing format (which turns non-float bit patterns like - // R16G16_UNORM 1.0 = 0xffff or R32_UINT 0x7f800001 into SFLOAT NaNs that vkCmdClearColorImage quiets). - // Emulated R9G9B9E5_SHAREDEXP images (backed by R32_UINT) lack COLOR_ATTACHMENT on E5B9G9R9 and keep the - // bit-exact R32_UINT backing path. - const VkFormat view_format = view.format ? VkFormat(view.format) : p.binding.format; - if (!uav_clear::encode(view_format, uav->is_float, uav->values, p.element)) - return ReplayResult::unsupported; - const auto* image_layout = uav_clear::layout(p.binding.format); - if (!image_layout || image_layout->bytes != p.element.size) - return ReplayResult::unsupported; - const bool attachment = p.binding.color_attachment && !p.binding.volume; - const bool view_attachable = vk.color_attachment_format - ? vk.color_attachment_format(view_format) - : view_format != VK_FORMAT_E5B9G9R9_UFLOAT_PACK32; - const bool reinterpret = view_format != p.binding.format && attachment && view_attachable; - const VkFormat clear_format = reinterpret ? view_format : p.binding.format; - if (!uav_clear::decode(clear_format, p.element, p.clear_color)) - return ReplayResult::unsupported; - if (reinterpret) p.clear_format = view_format; - if (!uav->rects.empty() && !attachment) - return ReplayResult::unsupported; - // Under a predicate a whole view is cleared as one rectangle where the image can be an attachment, as - // render targets are; otherwise vkCmdClearColorImage runs unconditionally and is counted. - if (predicated && uav->rects.empty() && !attachment) ++out.unpredicated_copies; - const auto rects = (reinterpret && uav->rects.empty()) - ? std::span(&whole_view, 1) - : attachment ? clear_rects(uav->rects) : std::span(uav->rects); - if (const auto r = rect_view(rects, target, VK_IMAGE_ASPECT_COLOR_BIT); r != ReplayResult::success) - return r; - if (!p.skip && p.rects.empty() && !vk.clear_color_image) return ReplayResult::unsupported; - } else if (std::holds_alternative(command) || std::holds_alternative(command) || - std::holds_alternative(command)) { - if (!copies) return ReplayResult::unsupported; - if (predicated && !std::holds_alternative(command)) ++out.unpredicated_copies; - const auto [dst_id, src_id] = copy_ids(command); - const ResourceBinding* source = resolve(src_id); - if (!bind(dst_id) || !source) return ReplayResult::unresolved_resource; - p.source = *source; - ReplayResult result = ReplayResult::success; - if (const auto* buffer_copy = std::get_if(&command)) { - const auto size = [&](const ResourceBinding& binding, ResourceId id) { - if (buffer_copy->tiled_resource != id) return binding.size; - if (!binding.sparse_buffer) return VkDeviceSize(0); - return (binding.size + tile_size_in_bytes - 1) / tile_size_in_bytes * tile_size_in_bytes; - }; - if (!p.binding.buffer || !p.source.buffer || - !detail::within(buffer_copy->dst_offset, buffer_copy->size, size(p.binding, dst_id)) || - !detail::within(buffer_copy->src_offset, buffer_copy->size, size(p.source, src_id))) - return ReplayResult::invalid_copy; - if (buffer_copy->src_offset > UINT64_MAX - p.source.buffer_offset || - buffer_copy->dst_offset > UINT64_MAX - p.binding.buffer_offset) return ReplayResult::invalid_copy; - const VkDeviceSize src = p.source.buffer_offset + buffer_copy->src_offset; - const VkDeviceSize dst = p.binding.buffer_offset + buffer_copy->dst_offset; - if (buffer_copy->size > UINT64_MAX - src || buffer_copy->size > UINT64_MAX - dst) - return ReplayResult::invalid_copy; - if (p.source.buffer == p.binding.buffer && src < dst + buffer_copy->size && dst < src + buffer_copy->size) - return ReplayResult::invalid_copy; - if (predicated) { - if ((statistics_active && !statistics_helpers) || !vk.prepare_predicated_copy || !vk.emit_predicated_copy || - !vk.prepare_predicated_copy(p.source.buffer, p.binding.buffer, src, dst, buffer_copy->size, p.predicated_copy)) - return ReplayResult::unsupported; - } else p.buffer_copies.push_back({src, dst, buffer_copy->size}); - } else if (const auto* texture_copy = std::get_if(&command)) { - result = detail::prepare_texture_copy(*texture_copy, p); - if (result == ReplayResult::success && !p.staged_reads.empty()) { - // A block-compressed copy staged through transfer scratch (prepare_texture_copy): whole blocks of - // the read's row length and height, one region a copy. - const VkBufferImageCopy& read = p.staged_reads[0]; - const BlockFormat f = block_format(p.source.format, read.imageSubresource.aspectMask); - const VkDeviceSize bytes = VkDeviceSize(read.bufferRowLength / f.block) * - (read.bufferImageHeight / f.block) * read.imageExtent.depth * f.bytes; - VkDeviceSize base = 0; - if (!f.bytes || !vk.copy_image_to_buffer || !vk.copy_buffer_to_image || !vk.copy_scratch || - !vk.copy_scratch(bytes, p.staged, base)) - return ReplayResult::invalid_copy; // refused as before this path existed - p.staged_reads[0].bufferOffset += base; - p.staged_writes[0].bufferOffset += base; - } - // A depth plane footprint of a D24 texture stored as D32: words of 24-bit UNORM, floats in the image. - const bool upload = texture_copy->src.footprint; - const ResourceBinding& image = upload ? p.binding : p.source; - if (result == ReplayResult::success && texture_copy->tile_footprint && !p.buffer_image_copies.empty() && - p.buffer_image_copies.front().bufferOffset % 4 && !detail::stage_unaligned_tile(vk, p, upload)) - return ReplayResult::unsupported; - const bool depth24_footprint = result == ReplayResult::success && image.depth24_as_float && - !p.buffer_image_copies.empty() && - p.buffer_image_copies[0].imageSubresource.aspectMask == VK_IMAGE_ASPECT_DEPTH_BIT; - const bool rgb96_footprint = result == ReplayResult::success && image.rgb96 && - !p.buffer_image_copies.empty(); - // Without a segment pool, refuse before allocating conversion scratch/descriptors. - if (statistics_active && !statistics_helpers && (depth24_footprint || rgb96_footprint)) return ReplayResult::unsupported; - if (depth24_footprint) { - const VkBufferImageCopy& region = p.buffer_image_copies[0]; - const ResourceBinding& buffer = upload ? p.source : p.binding; - Depth24Job& job = p.depth24; - job.to_float = upload; - job.app = buffer.buffer; - job.app_offset = region.bufferOffset; - job.app_size = buffer.buffer_offset + buffer.size; - job.width = region.imageExtent.width; - job.height = region.imageExtent.height; - job.slices = region.imageExtent.depth; - job.app_row_words = region.bufferRowLength ? region.bufferRowLength : job.width; - job.app_slice_words = job.app_row_words * (region.bufferImageHeight ? region.bufferImageHeight : job.height); - if (!vk.depth24_prepare || !vk.depth24_run || !vk.depth24_prepare(job, p.depth24_parts)) return ReplayResult::unsupported; - p.has_depth24 = true; - } else if (rgb96_footprint) { - // A footprint of a 96-bit texture: 12-byte texels, 16 in the image. The same pass and scratch. - const VkBufferImageCopy& region = p.buffer_image_copies[0]; - const ResourceBinding& buffer = upload ? p.source : p.binding; - Depth24Job& job = p.depth24; - job.rgb96 = true; - job.to_float = upload; - job.app = buffer.buffer; - job.app_offset = region.bufferOffset; - job.app_size = buffer.buffer_offset + buffer.size; - job.width = region.imageExtent.width; - job.height = region.imageExtent.height; - job.slices = region.imageExtent.depth; - job.app_row_words = p.rgb96_row_words; - job.app_slice_words = p.rgb96_slice_words; - if (!vk.depth24_prepare || !vk.depth24_run || !vk.depth24_prepare(job, p.depth24_parts)) return ReplayResult::unsupported; - p.has_depth24 = true; - } - } else { - result = detail::prepare_resource_copy(p); - } - if (result == ReplayResult::success && !p.image_copies.empty() && - p.image_copies[0].srcSubresource.aspectMask != p.image_copies[0].dstSubresource.aspectMask) { - // Depth <-> colour: vkCmdCopyImage cannot mix aspects, so each region goes image -> scratch -> image, - // tightly packed. Depth aspects want 4-byte buffer offsets; 16 covers every texel size here. - const std::uint32_t texel = - block_format(p.source.format, p.image_copies[0].srcSubresource.aspectMask).bytes; - VkDeviceSize total = 0; - std::vector offsets; - for (const VkImageCopy& c : p.image_copies) { - offsets.push_back(total); - total += (VkDeviceSize(c.extent.width) * c.extent.height * c.extent.depth * - c.srcSubresource.layerCount * texel + 15) / 16 * 16; - } - VkDeviceSize base = 0; - if (!texel || !vk.copy_scratch || !vk.copy_scratch(total, p.staged, base)) - return ReplayResult::unsupported; - for (std::size_t r = 0; r < p.image_copies.size(); ++r) { - const VkImageCopy& c = p.image_copies[r]; - VkBufferImageCopy region{}; - region.bufferOffset = base + offsets[r]; - region.imageSubresource = c.srcSubresource; - region.imageOffset = c.srcOffset; - region.imageExtent = c.extent; - p.staged_reads.push_back(region); - region.imageSubresource = c.dstSubresource; - region.imageOffset = c.dstOffset; - p.staged_writes.push_back(region); - } - p.image_copies.clear(); - } - if (result != ReplayResult::success) return result; - if (p.binding.host_readable) { - out.wrote_readback = true; - const bool compute_write = - (predicated && std::holds_alternative(command)) || (p.has_depth24 && !p.binding.image); - out.readback_src_stages |= compute_write - ? VK_PIPELINE_STAGE_2_COMPUTE_SHADER_BIT : VK_PIPELINE_STAGE_2_COPY_BIT; - } - } else if (const auto* resolve_command = std::get_if(&command)) { - if (!vk.resolve_image) return ReplayResult::unsupported; - if (predicated) ++out.unpredicated_copies; // a transfer command, like the copies - const ResourceBinding* source = resolve(resolve_command->src); - if (!bind(resolve_command->dst) || !source) return ReplayResult::unresolved_resource; - p.source = *source; - if (const auto result = detail::prepare_resolve(*resolve_command, p); result != ReplayResult::success) - return result; - if (p.resolve_mode != VK_RESOLVE_MODE_NONE) { - if (!vk.begin_rendering || !vk.end_rendering || !vk.image_view) return ReplayResult::unsupported; - p.view = vk.image_view(p.source, p.source_range); - p.resolve_view = vk.image_view(p.binding, p.range); - if (!p.view || !p.resolve_view) return ReplayResult::unsupported; - if (const auto result = detail::keep_around_resolve(vk, p); result != ReplayResult::success) - return result; - // D3D-417, a driver workaround: AMD's Windows driver (32.0.21042.62, Radeon RDNA2 iGPU) resolves a - // dynamic-rendering depth attachment from layer 0 of the image when the multisampled view starts at - // another layer (the resolve view's first layer it honours). The same two views in a framebuffer - // of a render pass resolve the right layer there, and on NVIDIA both ways do - // (docs/d3d12_vulkan.md). So a depth-only source above layer 0 goes through a render pass, on - // every GPU. A depth-stencil source does not: its planes can be in different layouts here. - if (p.source_range.baseArrayLayer && p.source.aspects == VK_IMAGE_ASPECT_DEPTH_BIT && - vk.depth_resolve_framebuffer && vk.begin_render_pass && vk.end_render_pass) { - const VkExtent2D from = detail::mip_extent(p.source, p.source_range.baseMipLevel); - const VkExtent2D to = detail::mip_extent(p.binding, p.range.baseMipLevel); - p.resolve_framebuffer = vk.depth_resolve_framebuffer( - p.source, p.view, image_layout(p.source, VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL), - p.binding, p.resolve_view, - image_layout(p.binding, VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL), p.resolve_mode, - {std::min(from.width, to.width), std::min(from.height, to.height)}, p.resolve_pass); - if (!p.resolve_framebuffer) return ReplayResult::unsupported; - } - } - } else if (const auto* discard = std::get_if(&command)) { - // Buffers and partial (rectangle) discards keep their contents, which "undefined" allows. - if (!bind(discard->resource)) return ReplayResult::unresolved_resource; - const std::uint64_t end = std::uint64_t(discard->first_subresource) + discard->count; - if (!p.binding.image) { - if (!discard->whole && end > 1) return ReplayResult::invalid_subresource; - } else if (discard->whole) { - VkImageSubresourceRange range{}; - if (!image_range(p.binding, all_subresources, range)) return ReplayResult::invalid_subresource; - if (!discard->partial) p.discards.push_back(range); - } else { - for (std::uint64_t sub = discard->first_subresource; sub < end; ++sub) { - const auto s = static_cast(sub); - VkImageSubresourceRange range{}; - if (!image_range(p.binding, s, range)) return ReplayResult::invalid_subresource; - if (!discard->partial) p.discards.push_back(range); - } - } - } else if (const auto* write = std::get_if(&command)) { - if (!vk.update_buffer || !vk.buffer_at) return ReplayResult::unsupported; - std::uint64_t bytes = 4; - if (!vk.buffer_at(write->address, bytes, p.write_buffer, p.write_offset) || bytes < 4) - return ReplayResult::unresolved_resource; - if (p.write_offset % 4) return ReplayResult::invalid_copy; - // WriteBufferImmediate resolves by VA and may target a readback buffer in COPY_DEST. - out.wrote_readback = true; - out.readback_src_stages |= VK_PIPELINE_STAGE_2_TRANSFER_BIT; - } else if (const auto* atomic = std::get_if(&command)) { - if (!vk.copy_buffer) return ReplayResult::unsupported; - if (predicated) ++out.unpredicated_copies; // a transfer command, like the copies - const ResourceBinding* source = resolve(atomic->src); - if (!bind(atomic->dst) || !source) return ReplayResult::unresolved_resource; - p.source = *source; - if (!p.binding.buffer || !p.source.buffer || !detail::within(atomic->dst_offset, atomic->bytes, p.binding.size) || - !detail::within(atomic->src_offset, atomic->bytes, p.source.size)) - return ReplayResult::invalid_copy; - for (const auto& d : atomic->dependencies) { - const ResourceBinding* dependent = resolve(d.resource); - if (!dependent) return ReplayResult::unresolved_resource; - if (!dependent->image) { - const std::uint64_t end = d.end == UINT64_MAX ? dependent->size : d.end; - if (d.subresource != 0 || d.begin >= end || end > dependent->size) - return ReplayResult::invalid_copy; - } - } - p.buffer_copies.push_back({p.source.buffer_offset + atomic->src_offset, - p.binding.buffer_offset + atomic->dst_offset, atomic->bytes}); - if (p.binding.host_readable) { - out.wrote_readback = true; - out.readback_src_stages |= VK_PIPELINE_STAGE_2_COPY_BIT | VK_PIPELINE_STAGE_2_TRANSFER_BIT; - } - } else if (const auto* predication = std::get_if(&command)) { - predicated = predication->buffer != 0; - if (!predicated) continue; - if (!conditional) return ReplayResult::unsupported; - // Without physical segments the capture dispatch would pollute CSInvocations. - if (statistics_active && !statistics_helpers) return ReplayResult::unsupported; - if (!bind(predication->buffer)) return ReplayResult::unresolved_resource; - if (!p.binding.buffer || !detail::within(predication->offset, 8, p.binding.size) || - predication->offset > UINT64_MAX - p.binding.buffer_offset) - return ReplayResult::invalid_predication; - if (!vk.prepare_predicate || !vk.capture_predicate || - !vk.prepare_predicate(p.binding.buffer, p.binding.buffer_offset + predication->offset, p.predicate)) - return ReplayResult::unsupported; - } else if (const QueryRange range = query_range(command); range.count) { - // BeginQuery, EndQuery and ResolveQueryData are not among D3D12's predicated calls, so a predicate does - // not suppress them (emit_query suspends conditional rendering around ResolveQueryData). - if (!queries) return ReplayResult::unsupported; - QueryPool* heap = vk.query_pool(range.heap); - if (!heap) return ReplayResult::unresolved_resource; - if (!query_fits_heap(heap->heap_type, range.type)) return ReplayResult::invalid_query; - if (range.first >= heap->count || range.count > heap->count - range.first) - return ReplayResult::invalid_query; - if (!query_result_size(range.type)) return ReplayResult::unsupported; - if (range.type != d3d12_query::timestamp && !std::holds_alternative(command)) { - const bool begin = std::holds_alternative(command); - if (range.type == d3d12_query::occlusion) { - overlaps |= begin && (ordinary_active || binary_active); - if (begin) ++ordinary_active; else --ordinary_active; - } else if (range.type == d3d12_query::binary_occlusion) { - overlaps |= begin && (ordinary_active || binary_active); - if (begin) ++binary_active; else --binary_active; - } else if (is_so_statistics(range.type)) { - // No Vulkan query runs for it (QueryPool::pool is null), so it overlaps nothing. - } else { - statistics_overlaps |= begin && statistics_active_count; - if (begin) ++statistics_active_count; else --statistics_active_count; - statistics_active = statistics_active_count != 0; - } - } - if (const auto* resolve_queries = std::get_if(&command)) { - // The destination is a buffer, as D3D12 requires, large enough for every result. - if (!bind(resolve_queries->dst)) return ReplayResult::unresolved_resource; - const std::uint64_t bytes = std::uint64_t(range.count) * query_result_size(range.type); - if (!p.binding.buffer || p.binding.buffer_offset % 8 || - !detail::within(resolve_queries->offset, bytes, p.binding.size) || - !detail::within(p.binding.buffer_offset, resolve_queries->offset + bytes, - std::numeric_limits::max())) - return ReplayResult::invalid_query; - // Inside a pipeline-statistics query, QueryReplay::plan checks that the helper dispatch is kept out - // of the application's counters. - if (range.type == d3d12_query::binary_occlusion && !vk.resolve_binary_occlusion) - return ReplayResult::unsupported; - if (p.binding.host_readable) { - out.wrote_readback = true; - out.readback_src_stages |= VK_PIPELINE_STAGE_2_COPY_BIT | VK_PIPELINE_STAGE_2_TRANSFER_BIT; - } - } - out.queries.push_back({i, heap, statistics_active}); - } else if (const auto* ind = std::get_if(&command)) { - if (!bind(ind->argument_buffer) || !p.binding.buffer) return ReplayResult::unresolved_resource; - const VkDeviceSize record_size = detail::indirect_record_size(ind->kind); - if (!record_size || ind->stride < record_size || ind->stride % sizeof(std::uint32_t)) - return ReplayResult::invalid_indirect_arguments; - // The span is max_count * stride, the bytes the signature can walk, as D3D12 measures it: a record that - // fits at the end of the buffer while its stride runs past it is refused (`240` with stride `20` in a - // `256`-byte buffer). A zero max_count still has to name an offset inside the buffer. - if (ind->argument_offset > p.binding.size || - ind->max_count > (p.binding.size - ind->argument_offset) / ind->stride || - !detail::indirect_range(p.binding, ind->argument_offset, - VkDeviceSize(ind->max_count) * ind->stride)) - return ReplayResult::invalid_indirect_arguments; - if (ind->count_buffer) { - const ResourceBinding* cnt = resolve(ind->count_buffer); - if (!cnt || !cnt->buffer) return ReplayResult::unresolved_resource; - if (!detail::indirect_range(*cnt, ind->count_offset, sizeof(std::uint32_t))) - return ReplayResult::invalid_indirect_arguments; - p.source = *cnt; - if (ind->kind == IndirectKind::dispatch) { - // Vulkan lacks vkCmdDispatchIndirectCount. Copy the GPU-visible commands to private scratch - // and replace commands past min(count, max_count) with zero-group dispatches. - if (!ind->pipeline || !vk.dispatch_indirect || !vk.prepare_counted_dispatch || - !vk.emit_counted_dispatch || (statistics_active && !statistics_helpers) || - !vk.prepare_counted_dispatch(p.binding.buffer, p.binding.buffer_offset + ind->argument_offset, - p.source.buffer, p.source.buffer_offset + ind->count_offset, - ind->stride, ind->max_count, p.counted_dispatch)) - return ReplayResult::unsupported; - } else if ((ind->kind == IndirectKind::draw && !vk.draw_indirect_count) || - (ind->kind == IndirectKind::draw_indexed && !vk.draw_indexed_indirect_count)) { - return ReplayResult::unsupported; - } - } else { - if ((ind->kind == IndirectKind::draw && !vk.draw_indirect) || - (ind->kind == IndirectKind::draw_indexed && !vk.draw_indexed_indirect) || - (ind->kind == IndirectKind::dispatch && !vk.dispatch_indirect)) - return ReplayResult::unsupported; - } - if (ind->kind == IndirectKind::dispatch && ind->pipeline) { // the pipeline and root arguments it was recorded - if (!vk.bind_pipeline || !vk.push_constants || !vk.compute_pipeline) return ReplayResult::unsupported; - const ComputePipeline* pipeline = vk.compute_pipeline(ind->pipeline); - if (!pipeline || !pipeline->pipeline) return ReplayResult::unresolved_resource; - if (pipeline->bindless_set && !vk.bind_descriptor_sets) return ReplayResult::unsupported; - p.pipeline = *pipeline; - } - } else if (const auto* build = std::get_if(&command)) { - p.khr_instances = 0; - if (vk.xdxr_check) { - if (!vk.xdxr_check(*build)) return ReplayResult::unsupported; - } else { - if (!vk.build_acceleration_structures || !vk.resolve_acceleration_structure) - return ReplayResult::unsupported; - p.accel_dst = vk.resolve_acceleration_structure(build->dst_va); - if (!p.accel_dst) return ReplayResult::unresolved_resource; - if (build->update && build->src_va) { - p.accel_src = vk.resolve_acceleration_structure(build->src_va); - if (!p.accel_src) return ReplayResult::unresolved_resource; - } - if (build->is_tlas && build->instance_pointers && build->instance_count) { - if (!vk.prepare_khr_instances || !vk.host_at || !vk.buffer_at) return ReplayResult::unsupported; - return vk.prepare_khr_instances(*build, p.khr_instances); - } - } - } else if (const auto* copy = std::get_if(&command)) { - if (vk.xdxr_copy) { - // XDXR structures: the destination's room bounds the copy, as the size is only known to the GPU. - if (!vk.buffer_at || copy->mode > 1) return ReplayResult::unsupported; - std::uint64_t room = ~std::uint64_t(0); - VkBuffer buffer = VK_NULL_HANDLE; - VkDeviceSize offset = 0; - if (!vk.buffer_at(copy->dst_va, room, buffer, offset)) return ReplayResult::unresolved_resource; - std::uint64_t source = ~std::uint64_t(0); - if (!vk.buffer_at(copy->src_va, source, buffer, offset)) return ReplayResult::unresolved_resource; - p.xdxr_bytes = std::min(room, source); - } else { - if (vk.queue_stages == detail::queue_stages_copy || !vk.copy_acceleration_structure || - !vk.resolve_acceleration_structure || copy->mode > 1) - return ReplayResult::unsupported; - p.accel_dst = vk.resolve_acceleration_structure(copy->dst_va); - p.accel_src = vk.resolve_acceleration_structure(copy->src_va); - if (!p.accel_dst || !p.accel_src) return ReplayResult::unresolved_resource; - // Vulkan forbids overlapping source and destination handles in CLONE/COMPACT copies. - if (p.accel_dst == p.accel_src) return ReplayResult::invalid_copy; - } - } else if (const auto* info = std::get_if(&command)) { - if (vk.xdxr_postbuild) { - if (!vk.buffer_at || (info->type != 0 && info->type != 3)) return ReplayResult::unsupported; - std::uint64_t room = 8 * info->sources.size(); - VkBuffer buffer = VK_NULL_HANDLE; - VkDeviceSize offset = 0; - if (!vk.buffer_at(info->dest_va, room, buffer, offset)) return ReplayResult::unresolved_resource; - if (room < 8 * info->sources.size()) return ReplayResult::invalid_copy; - } else if (info->type == 0 && vk.write_acceleration_structures_properties && - vk.resolve_acceleration_structure && vk.reset_query_pool && vk.copy_query_pool_results && - vk.pipeline_barrier && vk.buffer_at && vk.prepare_khr_postbuild) { - if (vk.queue_stages == detail::queue_stages_copy || info->sources.empty() || - info->sources.size() > std::numeric_limits::max() / 8u) - return ReplayResult::unsupported; - const std::uint64_t need = 8ull * info->sources.size(); - std::uint64_t room = need; - detail::PreparedKhrPostbuild pb; - if (!vk.buffer_at(info->dest_va, room, pb.dst_buffer, pb.dst_offset)) - return ReplayResult::unresolved_resource; - // vkCmdCopyQueryPoolResults with VK_QUERY_RESULT_64_BIT requires an 8-byte aligned dstOffset. - if (!pb.dst_buffer || room < need || (pb.dst_offset % 8) != 0) - return ReplayResult::invalid_copy; - pb.sources.reserve(info->sources.size()); - for (const std::uint64_t src_va : info->sources) { - const VkAccelerationStructureKHR as = vk.resolve_acceleration_structure(src_va); - if (!as) return ReplayResult::unresolved_resource; - pb.sources.push_back(as); - } - if (!vk.prepare_khr_postbuild(static_cast(pb.sources.size()), pb.query_pool, - pb.first_query) || - !pb.query_pool) - return ReplayResult::unsupported; - p.khr_postbuild = static_cast(out.khr_postbuilds.size()); - out.khr_postbuilds.push_back(std::move(pb)); - // dest_va is resolved by VA and may target a host-readable buffer in COPY_DEST. - out.wrote_readback = true; - out.readback_src_stages |= VK_PIPELINE_STAGE_2_TRANSFER_BIT; - } else { - // Other postbuild info types (or callers without KHR postbuild wired) keep skipping rather than failing. - p.skip = true; - } - } else if (const auto* dispatch = std::get_if(&command)) { - if (!vk.bind_pipeline || !vk.push_constants || !vk.dispatch || !vk.compute_pipeline) - return ReplayResult::unsupported; - const ComputePipeline* pipeline = vk.compute_pipeline(dispatch->pipeline); - if (!pipeline || !pipeline->pipeline) return ReplayResult::unresolved_resource; - if (pipeline->bindless_set && !vk.bind_descriptor_sets) return ReplayResult::unsupported; - p.pipeline = *pipeline; - } else if (const auto* draw = std::get_if(&command)) { - if (out.draw_count == out.draws.size()) out.draws.emplace_back(); - auto& prepared_draw = out.draws[out.draw_count]; - prepared_draw.reset(); - p.draw = std::uint32_t(out.draw_count++); - if (const auto r = detail::prepare_draw(*draw, resolve, vk, prepared_draw); r != ReplayResult::success) - return r; - } - } - if (ordinary_active || binary_active) return ReplayResult::invalid_query; - out.statistics_overlaps = statistics_overlaps; - if (statistics_overlaps) { - const auto result = plan_overlapping_statistics_segments(out); - if (result != ReplayResult::success) return result; - } else { - plan_statistics_segments(out); - } - if (overlaps) { - if (!vk.sum_occlusion || out.queries.size() >= detail::PreparedQuery::no_segment) - return ReplayResult::unsupported; - return plan_occlusion_segments(out); - } - return ReplayResult::success; -} - -// A submission is planned against the currently published query state plus its own earlier lists. -// Keep every physical pool referenced by the recorded batch alive until that batch completes. -class QueryReplay { -public: - // `statistics_pool` holds the list's pipeline-statistics segments (plan_statistics_segments). Without one, the - // list's statistics queries are not split: ordinary helper commands are refused, as are resolves that dispatch. - ReplayResult plan(PreparedList& list, const std::shared_ptr& pool = {}, - std::uint32_t base = 0, bool can_sum = false, - const std::shared_ptr& statistics_pool = {}, - std::uint32_t statistics_base = 0) { - if (list.segment_count) { - if (!pool) return ReplayResult::unsupported; - retain(pool); - list.segment_pool = pool->pool; - list.segment_base = base; - } - if (list.statistics_segment_count) { - const bool mesh = std::find(list.statistics_mesh.begin(), list.statistics_mesh.end(), 1) != - list.statistics_mesh.end(); - if (statistics_pool && (!mesh || statistics_pool->mesh_pool)) { - retain(statistics_pool); - list.statistics_pool = statistics_pool->pool; - list.statistics_mesh_pool = statistics_pool->mesh_pool; - list.statistics_base = statistics_base; - } else if (mesh) { - // Unsplit, the query would be active around a mesh draw with counters Vulkan forbids there. - return ReplayResult::unsupported; - } else if (list.statistics_overlaps) { - // Whole queries on the heap pool would keep two pipeline-statistics queries active at once. - return ReplayResult::unsupported; - } else { - for (const auto& command : list.commands) - if (command.statistics_end != detail::PreparedQuery::no_segment) - return ReplayResult::unsupported; - for (auto& query : list.queries) { - query.statistics_end = query.statistics_begin = detail::PreparedQuery::no_segment; - query.statistics_count = 0; - } - list.statistics_segment_count = 0; - } - } - for (auto& query : list.queries) { - const Command& command = list.list->commands()[query.command]; - if (const auto* begin = std::get_if(&command)) { - pending_[{query.heap, begin->index}] = {}; - } else if (const auto* end = std::get_if(&command)) { - Value result{true, {}}; - if (query.result_count) result.occlusion = {pool, base + query.first_result, query.result_count}; - if (query.statistics_count) - result.occlusion = {statistics_pool, statistics_base + query.statistics_first, - query.statistics_count}; - pending_[{query.heap, end->index}] = std::move(result); - } else { - const auto& resolve = std::get(command); - const bool binary = resolve.type == d3d12_query::binary_occlusion; - const bool statistics = resolve.type == d3d12_query::pipeline_statistics; - // A helper dispatch inside an unsplit statistics query would count in the application's - // CSInvocations. - const bool uncounted = !query.statistics_active || - query.statistics_end != detail::PreparedQuery::no_segment; - const std::uint32_t size = query_result_size(resolve.type); - const auto offset = list.commands[query.command].binding.buffer_offset + resolve.offset; - for (std::uint32_t i = 0; i < resolve.count; ++i) { - const auto index = resolve.first + i; - const auto value = lookup(*query.heap, index); - if (binary && value.ended && !uncounted) return ReplayResult::unsupported; - needs_binary |= binary && value.ended; - detail::QueryResolveRun run{value.ended ? query.heap->pool : VK_NULL_HANDLE, - index, 1, offset + VkDeviceSize(i) * size}; - if (value.occlusion.segments) { - if (resolve.type != d3d12_query::occlusion && !binary && !statistics) - return ReplayResult::invalid_query; - const auto& saved = value.occlusion; - const std::uint8_t* kinds = saved.segments->mesh.empty() ? nullptr - : saved.segments->mesh.data(); - // A mesh segment's four counters go through the sum to land in their D3D12 fields. - const bool any_mesh = kinds && std::find(kinds + saved.first, kinds + saved.first + saved.count, - std::uint8_t(1)) != kinds + saved.first + saved.count; - run = {saved.segments->pool, saved.first, saved.count, run.offset, - saved.count > 1 || any_mesh, saved.segments->mesh_pool, kinds}; - if (any_mesh && !statistics) return ReplayResult::invalid_query; - if (!can_sum || (run.sum && !uncounted)) return ReplayResult::unsupported; - if (statistics) needs_statistics_sum |= run.sum; - else if (binary) (run.sum ? needs_sum_binary : needs_binary) = true; - else needs_sum |= run.sum; - retain(saved.segments); - } - if (!query.resolves.empty() && !run.sum && run.count == 1) { - auto& last = query.resolves.back(); - if (!last.sum && last.pool == run.pool && last.first + last.count == run.first) { - ++last.count; - continue; - } - } - query.resolves.push_back(run); - } - } - } - return ReplayResult::success; - } - - void commit() { - for (auto& [key, result] : pending_) { - const auto [heap, index] = key; - heap->ended[index] = result.ended; - if (result.occlusion.segments) heap->occlusion[index] = std::move(result.occlusion); - else heap->occlusion.erase(index); - } - } - - bool needs_sum = false; - bool needs_binary = false; - bool needs_statistics_sum = false; - bool needs_sum_binary = false; // a binary query whose segments must be summed before the 0/1 normalize - std::vector> retained; - -private: - struct Value { - bool ended = false; - OcclusionResult occlusion; - }; - - Value lookup(QueryPool& heap, std::uint32_t index) const { - if (const auto it = pending_.find({&heap, index}); it != pending_.end()) return it->second; - if (const auto it = heap.occlusion.find(index); it != heap.occlusion.end()) return {true, it->second}; - return {heap.ended[index], {}}; - } - - void retain(const std::shared_ptr& pool) { - if (std::find(retained.begin(), retained.end(), pool) == retained.end()) retained.push_back(pool); - } - - std::map, Value> pending_; -}; - -namespace detail { - -// A physical pipeline-statistics segment (plan_statistics_segments), in the pool its kind needs. -inline VkQueryPool statistics_segment_pool(const PreparedList& list, std::uint32_t segment) { - return list.statistics_mesh[segment] ? list.statistics_mesh_pool : list.statistics_pool; -} - -inline void end_statistics_segment(const PreparedList& list, std::uint32_t segment, VkCommandBuffer cb, - const ReplayFunctions& vk) { - if (segment == PreparedQuery::no_segment) return; - vk.end_query(cb, statistics_segment_pool(list, segment), list.statistics_base + segment); -} - -inline void begin_statistics_segment(const PreparedList& list, std::uint32_t segment, VkCommandBuffer cb, - const ReplayFunctions& vk) { - if (segment == PreparedQuery::no_segment) return; - const auto pool = statistics_segment_pool(list, segment); - vk.reset_query_pool(cb, pool, list.statistics_base + segment, 1); - vk.begin_query(cb, pool, list.statistics_base + segment, 0); -} - -} // namespace detail - -inline void emit_query(const PreparedList& list, const detail::PreparedQuery& query, VkCommandBuffer cb, - const ReplayFunctions& vk, const VkConditionalRenderingBeginInfoEXT& predicate) { - constexpr auto none = detail::PreparedQuery::no_segment; - if (query.end_segment != none || query.begin_segment != none) { - if (query.end_segment != none) vk.end_query(cb, list.segment_pool, list.segment_base + query.end_segment); - if (query.begin_segment != none) { - const auto index = list.segment_base + query.begin_segment; - vk.reset_query_pool(cb, list.segment_pool, index, 1); - vk.begin_query(cb, list.segment_pool, index, list.precise_segments ? VK_QUERY_CONTROL_PRECISE_BIT : 0); - } - return; - } - // A split pipeline-statistics query (plan_statistics_segments): its counters run in the physical segments. - const auto end_statistics = [&] { detail::end_statistics_segment(list, query.statistics_end, cb, vk); }; - const auto begin_statistics = [&] { detail::begin_statistics_segment(list, query.statistics_begin, cb, vk); }; - const auto& command = list.list->commands()[query.command]; - const QueryPool& heap = *query.heap; - if (!std::holds_alternative(command) && - (query.statistics_begin != none || query.statistics_end != none)) { - end_statistics(); - begin_statistics(); - return; - } - // A heap without a Vulkan pool (stream-output statistics: the layer has no stream output) runs nothing for - // BeginQuery and EndQuery; its resolves were planned as zero fills. - if (!heap.pool && !std::holds_alternative(command)) return; - if (const auto* begin = std::get_if(&command)) { - vk.reset_query_pool(cb, heap.pool, begin->index, 1); - const bool precise = begin->type == d3d12_query::occlusion && heap.precise; - vk.begin_query(cb, heap.pool, begin->index, precise ? VK_QUERY_CONTROL_PRECISE_BIT : 0); - } else if (const auto* end = std::get_if(&command)) { - if (end->type == d3d12_query::timestamp) { - vk.reset_query_pool(cb, heap.pool, end->index, 1); - vk.write_timestamp(cb, VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT, heap.pool, end->index); - } else { - vk.end_query(cb, heap.pool, end->index); - } - } else { - const auto& resolve = std::get(command); - const bool binary = resolve.type == d3d12_query::binary_occlusion; - const auto size = query_result_size(resolve.type); - const auto dst = list.commands[query.command].binding.buffer; - // ResolveQueryData is unconditional in D3D12. Suspend conditional rendering for the whole resolve rather - // than only before helper dispatches: on Intel's Windows Vulkan driver, vkCmdFillBuffer (used for un-ended - // queries) is suppressed inside an active conditional rendering scope after PredicateReducer::capture's - // compute dispatch (D3D-148). - const bool suspend = predicate.buffer && !query.resolves.empty(); - end_statistics(); - if (suspend) vk.end_conditional_rendering(cb); - if (resolve.type == d3d12_query::timestamp && vk.order_timestamp_copy && - std::any_of(query.resolves.begin(), query.resolves.end(), [](const auto& run) { return run.pool; })) - vk.order_timestamp_copy(cb); - for (const auto& run : query.resolves) { - if (!run.pool) { - vk.fill_buffer(cb, dst, run.offset, VkDeviceSize(run.count) * size, 0); - } else if (run.sum && resolve.type == d3d12_query::pipeline_statistics) { - vk.sum_statistics(cb, run.pool, run.mesh_pool, run.mesh, run.first, run.count, dst, run.offset); - } else if (run.sum && binary) { - vk.sum_binary_occlusion(cb, run.pool, run.first, run.count, dst, run.offset); - } else if (run.sum || binary) { - const auto& resolve_occlusion = run.sum ? vk.sum_occlusion : vk.resolve_binary_occlusion; - resolve_occlusion(cb, run.pool, run.first, run.count, dst, run.offset); - } else { - vk.copy_query_pool_results(cb, run.pool, run.first, run.count, dst, run.offset, size, - VK_QUERY_RESULT_64_BIT | VK_QUERY_RESULT_WAIT_BIT); - } - } - if (suspend) vk.begin_conditional_rendering(cb, &predicate); - begin_statistics(); - } -} - -// Ends the debug labels a submission left open, so every command buffer is balanced as Vulkan requires. -inline void close_labels(VkCommandBuffer command_buffer, const ReplayFunctions& vk, std::uint32_t& open_labels) { - for (; open_labels && vk.end_label; --open_labels) vk.end_label(command_buffer); - open_labels = 0; -} - -// Writes a prepared list. With a tracker, barriers start from the tracked layouts and update them. -// `open_labels` counts the debug labels begun and not yet ended in this command buffer: an EndEvent with none open -// is dropped (Vulkan requires a matching begin), and the caller ends what is still open before it ends the buffer -// (close_labels). Without it, the list's own events are balanced at its end. -inline void emit(const PreparedList& prepared, VkCommandBuffer command_buffer, const ReplayFunctions& vk, - LayoutTracker* tracker = nullptr, std::uint32_t* open_labels = nullptr) { - std::uint32_t own_labels = 0; - std::uint32_t& labels = open_labels ? *open_labels : own_labels; - const auto commands = prepared.list->commands(); - const bool separate = vk.separate_depth_stencil_layouts; - const VulkanAccess transfer_dst = vulkan_access(d3d12_state::copy_dest, false); - // The extension is enabled: barriers into and out of PREDICATION also cover conditional rendering's read. - const bool predicates = vk.begin_conditional_rendering != nullptr; - VkConditionalRenderingBeginInfoEXT predicate{VK_STRUCTURE_TYPE_CONDITIONAL_RENDERING_BEGIN_INFO_EXT}; - std::size_t next_query = 0; - // A dispatch honours conditional rendering and a copy does not (the layer runs copies unpredicated), so the - // conversion around a copy must run whatever the predicate says: end it for the dispatch and begin it again. - const auto run_depth24 = [&](const Depth24Job& job) { - if (predicate.buffer) vk.end_conditional_rendering(command_buffer); - vk.depth24_run(command_buffer, job); - if (predicate.buffer) vk.begin_conditional_rendering(command_buffer, &predicate); - }; - - for (std::size_t i = 0; i < commands.size(); ++i) { - const auto& command = commands[i]; - const auto& p = prepared.commands[i]; - if (next_query < prepared.queries.size() && prepared.queries[next_query].command == i) { - emit_query(prepared, prepared.queries[next_query++], command_buffer, vk, predicate); - continue; - } - // Helpers run outside the per-command rendering scopes; both segment endpoints stay outside too. - const auto end_statistics = [&] { - detail::end_statistics_segment(prepared, p.statistics_end, command_buffer, vk); - }; - const auto begin_statistics = [&] { - detail::begin_statistics_segment(prepared, p.statistics_begin, command_buffer, vk); - }; - // A draw of the other kind inside a statistics query starts a segment in its pool (D3D-291), before the - // draw's own rendering scope begins. - if (std::holds_alternative(command) || std::holds_alternative(command)) { - end_statistics(); - begin_statistics(); - } - if (const auto* predication = std::get_if(&command)) { - // Conditional rendering cannot nest, so a new predicate ends the previous one first. - if (predicate.buffer) vk.end_conditional_rendering(command_buffer); - predicate.buffer = predication->buffer ? p.predicate.scratch : VK_NULL_HANDLE; - if (predicate.buffer) { - end_statistics(); - vk.capture_predicate(command_buffer, p.predicate); - begin_statistics(); - predicate.offset = p.predicate.offset + 8; - // Vulkan discards the commands when the word is 0, which is EQUAL_ZERO; INVERTED gives NOT_EQUAL_ZERO. - predicate.flags = predication->op == d3d12_predication::not_equal_zero - ? VK_CONDITIONAL_RENDERING_INVERTED_BIT_EXT - : 0; - vk.begin_conditional_rendering(command_buffer, &predicate); - } - continue; - } - const ResourceId id = std::visit( - [](const auto& c) -> ResourceId { - using T = std::decay_t; - if constexpr (std::is_same_v || std::is_same_v) - return c.target.resource; - else if constexpr (std::is_same_v) - return c.view.resource; - else if constexpr (requires { c.resource; }) - return c.resource; - else - return 0; - }, - command); - - if (const auto* transition = std::get_if(&command)) { - const VulkanAccess from = vulkan_access(transition->before, p.binding.presentable, predicates); - const VulkanAccess to = vulkan_access(transition->after, p.binding.presentable, predicates); - if (!p.binding.image) { - detail::memory_barrier(vk, command_buffer, from.access, from.stages, to.access, to.stages); - continue; - } - const auto range = detail::planes_for_layout(p.binding, p.range, separate); - const VkImageLayout new_layout = image_layout(p.binding, to.layout); - auto pieces = detail::current(tracker, id, range, image_layout(p.binding, from.layout)); - detail::initialize(vk, command_buffer, p.binding, id, pieces, image_layout(p.binding, from.layout), tracker); - for (const auto& piece : pieces) - detail::image_barrier(vk, command_buffer, p.binding, piece.range, piece.layout, new_layout, - from.access, from.stages, to.access, to.stages); - if (tracker) tracker->set(id, range, new_layout); - } else if (std::holds_alternative(command)) { - const VulkanAccess uav = vulkan_access(d3d12_state::unordered_access, false); - VkAccessFlags src_access = VK_ACCESS_SHADER_WRITE_BIT; - VkAccessFlags dst_access = uav.access; - VkPipelineStageFlags stages = uav.stages; - if (vk.build_acceleration_structures) { - src_access |= VK_ACCESS_ACCELERATION_STRUCTURE_WRITE_BIT_KHR; - dst_access |= VK_ACCESS_ACCELERATION_STRUCTURE_READ_BIT_KHR | - VK_ACCESS_ACCELERATION_STRUCTURE_WRITE_BIT_KHR; - stages |= VK_PIPELINE_STAGE_ACCELERATION_STRUCTURE_BUILD_BIT_KHR; - } - detail::memory_barrier(vk, command_buffer, src_access, stages, dst_access, stages); - } else if (std::holds_alternative(command)) { - detail::memory_barrier(vk, command_buffer, VK_ACCESS_MEMORY_WRITE_BIT, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, - VK_ACCESS_MEMORY_READ_BIT | VK_ACCESS_MEMORY_WRITE_BIT, - VK_PIPELINE_STAGE_ALL_COMMANDS_BIT); - } else if (std::holds_alternative(command) || std::holds_alternative(command)) { - const auto [sync_before, sync_after, access_before, access_after] = std::visit( - [](const auto& c) -> std::array { - if constexpr (requires { c.sync_before; }) - return {c.sync_before, c.sync_after, c.access_before, c.access_after}; - else - return {}; - }, - command); - const BarrierScope src = vulkan_barrier_scope(sync_before, access_before, predicates); - const BarrierScope dst = vulkan_barrier_scope(sync_after, access_after, predicates); - VkMemoryBarrier2 barrier{VK_STRUCTURE_TYPE_MEMORY_BARRIER_2}; - barrier.srcStageMask = src.stages; - barrier.dstStageMask = dst.stages; - barrier.srcAccessMask = src.access; - barrier.dstAccessMask = dst.access; - if (barrier.srcStageMask) detail::restrict_to_queue(vk, barrier.srcStageMask, barrier.srcAccessMask); - if (barrier.dstStageMask) detail::restrict_to_queue(vk, barrier.dstStageMask, barrier.dstAccessMask); - VkDependencyInfo dependency{VK_STRUCTURE_TYPE_DEPENDENCY_INFO}; - dependency.memoryBarrierCount = 1; - dependency.pMemoryBarriers = &barrier; - vk.pipeline_barrier2(command_buffer, &dependency); - } else if (const auto* texture = std::get_if(&command)) { - const auto range = detail::planes_for_layout(p.binding, p.range, separate); - const bool discard = (texture->flags & texture_barrier_discard) || - texture->layout_before == d3d12_layout::undefined; - const VkImageLayout new_layout = - image_layout(p.binding, vulkan_layout(texture->layout_after, p.binding.presentable)); - LayoutPieces pieces; - if (discard) - pieces.push_back({range, VK_IMAGE_LAYOUT_UNDEFINED}); - else { - const VkImageLayout before = - image_layout(p.binding, vulkan_layout(texture->layout_before, p.binding.presentable)); - pieces = detail::current(tracker, id, range, before); - detail::initialize(vk, command_buffer, p.binding, id, pieces, before, tracker); - } - const BarrierScope src = vulkan_barrier_scope(texture->sync_before, texture->access_before, predicates); - const BarrierScope dst = vulkan_barrier_scope(texture->sync_after, texture->access_after, predicates); - // One barrier for each piece: nearly always one or two (LayoutPieces), which stay on the stack. - std::array few; - std::vector many; - if (pieces.size() > few.size()) many.resize(pieces.size()); - VkImageMemoryBarrier2* const barriers = many.empty() ? few.data() : many.data(); - std::uint32_t barrier_count = 0; - for (const auto& piece : pieces) { - VkImageMemoryBarrier2& b = barriers[barrier_count++]; - b = {VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER_2}; - b.srcStageMask = src.stages; - b.dstStageMask = dst.stages; - b.srcAccessMask = src.access; - b.dstAccessMask = dst.access; - b.oldLayout = piece.layout; - b.newLayout = new_layout; - b.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; - b.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; - b.image = p.binding.image; - b.subresourceRange = detail::layout_range(p.binding, piece.range); - if (b.srcStageMask) detail::restrict_to_queue(vk, b.srcStageMask, b.srcAccessMask); - if (b.dstStageMask) detail::restrict_to_queue(vk, b.dstStageMask, b.dstAccessMask); - } - VkDependencyInfo dependency{VK_STRUCTURE_TYPE_DEPENDENCY_INFO}; - dependency.imageMemoryBarrierCount = barrier_count; - dependency.pImageMemoryBarriers = barriers; - vk.pipeline_barrier2(command_buffer, &dependency); - if (tracker) tracker->set(id, range, new_layout); - } else if (const auto* color_clear = std::get_if(&command)) { - if (p.skip) continue; - const VulkanAccess state = vulkan_access(d3d12_state::render_target, false); - auto pieces = detail::current(tracker, id, p.range, image_layout(p.binding, state.layout)); - detail::initialize(vk, command_buffer, p.binding, id, pieces, image_layout(p.binding, state.layout), tracker); - const VkClearColorValue color = detail::render_target_clear_color(p.clear_format, color_clear->color); - if (p.rects.empty()) { - detail::round_trip(vk, command_buffer, p.binding, pieces, image_layout(p.binding, transfer_dst.layout), - state, transfer_dst.access, transfer_dst.stages, [&] { - vk.clear_color_image(command_buffer, p.binding.image, image_layout(p.binding, transfer_dst.layout), - &color, 1, &p.range); - }); - continue; - } - const VkImageLayout attachment = image_layout(p.binding, state.layout); - detail::round_trip(vk, command_buffer, p.binding, pieces, attachment, state, state.access, - state.stages, [&] { - VkRenderingAttachmentInfo info{VK_STRUCTURE_TYPE_RENDERING_ATTACHMENT_INFO}; - info.imageView = p.view; - info.imageLayout = attachment; - info.loadOp = VK_ATTACHMENT_LOAD_OP_LOAD; - info.storeOp = VK_ATTACHMENT_STORE_OP_STORE; - VkRenderingInfo rendering{VK_STRUCTURE_TYPE_RENDERING_INFO}; - rendering.renderArea = {{0, 0}, detail::mip_extent(p.binding, color_clear->target.mip)}; - rendering.layerCount = color_clear->target.layer_count; - rendering.colorAttachmentCount = 1; - rendering.pColorAttachments = &info; - vk.begin_rendering(command_buffer, &rendering); - VkClearAttachment attachment_clear{VK_IMAGE_ASPECT_COLOR_BIT, 0, {}}; - attachment_clear.clearValue.color = color; - vk.clear_attachments(command_buffer, 1, &attachment_clear, std::uint32_t(p.rects.size()), p.rects.data()); - vk.end_rendering(command_buffer); - }); - } else if (const auto* depth_clear = std::get_if(&command)) { - if (p.skip) continue; - // With separate layouts only the cleared planes move; otherwise both do. - const auto range = detail::planes_for_layout(p.binding, p.range, separate); - const VulkanAccess state = vulkan_access(d3d12_state::depth_write, false); - auto pieces = detail::current(tracker, id, range, image_layout(p.binding, state.layout)); - detail::initialize(vk, command_buffer, p.binding, id, pieces, image_layout(p.binding, state.layout), tracker); - const float depth = p.binding.depth24 ? depth24_clear_value(depth_clear->depth) // see depth24.h - : p.binding.format == VK_FORMAT_D16_UNORM - ? detail::quantize_unorm(depth_clear->depth, 65535.0) // see quantize_unorm - : depth_clear->depth; - const VkClearDepthStencilValue value{depth, depth_clear->stencil}; - if (p.rects.empty()) { - detail::round_trip(vk, command_buffer, p.binding, pieces, image_layout(p.binding, transfer_dst.layout), - state, transfer_dst.access, transfer_dst.stages, [&] { - vk.clear_depth_stencil_image(command_buffer, p.binding.image, - image_layout(p.binding, transfer_dst.layout), &value, 1, &p.range); - }); - continue; - } - const VkImageLayout attachment = image_layout(p.binding, state.layout); - detail::round_trip(vk, command_buffer, p.binding, pieces, attachment, state, state.access, - state.stages, [&] { - VkRenderingAttachmentInfo info{VK_STRUCTURE_TYPE_RENDERING_ATTACHMENT_INFO}; - info.imageView = p.view; - info.imageLayout = attachment; - info.loadOp = VK_ATTACHMENT_LOAD_OP_LOAD; - info.storeOp = VK_ATTACHMENT_STORE_OP_STORE; - VkRenderingInfo rendering{VK_STRUCTURE_TYPE_RENDERING_INFO}; - rendering.renderArea = {{0, 0}, detail::mip_extent(p.binding, depth_clear->target.mip)}; - rendering.layerCount = depth_clear->target.layer_count; - if (p.range.aspectMask & VK_IMAGE_ASPECT_DEPTH_BIT) rendering.pDepthAttachment = &info; - if (p.range.aspectMask & VK_IMAGE_ASPECT_STENCIL_BIT) rendering.pStencilAttachment = &info; - vk.begin_rendering(command_buffer, &rendering); - VkClearAttachment attachment_clear{p.range.aspectMask, 0, {}}; - attachment_clear.clearValue.depthStencil = value; - vk.clear_attachments(command_buffer, 1, &attachment_clear, std::uint32_t(p.rects.size()), p.rects.data()); - vk.end_rendering(command_buffer); - }); - } else if (const auto* uav = std::get_if(&command)) { - if (p.skip) continue; - // The UAV state, widened to transfers: a later barrier from SYNC_CLEAR_UNORDERED_ACCESS_VIEW names the - // clear stage, which is a transfer stage in the legacy masks. - VulkanAccess state = vulkan_access(d3d12_state::unordered_access, false); - state.access |= VK_ACCESS_TRANSFER_READ_BIT | VK_ACCESS_TRANSFER_WRITE_BIT; - state.stages |= VK_PIPELINE_STAGE_TRANSFER_BIT; - if (uav->view.buffer) { - constexpr VkAccessFlags transfer = VK_ACCESS_TRANSFER_READ_BIT | VK_ACCESS_TRANSFER_WRITE_BIT; - detail::memory_barrier(vk, command_buffer, state.access, state.stages, transfer, - VK_PIPELINE_STAGE_TRANSFER_BIT); - for (std::size_t f = 0; f < p.fills.size(); ++f) { - if (f) // rectangles may overlap - detail::memory_barrier(vk, command_buffer, VK_ACCESS_TRANSFER_READ_BIT | VK_ACCESS_TRANSFER_WRITE_BIT, - VK_PIPELINE_STAGE_TRANSFER_BIT, transfer, VK_PIPELINE_STAGE_TRANSFER_BIT); - detail::emit_buffer_fill(vk, command_buffer, p.binding.buffer, p.element, p.fills[f][0], - p.fills[f][1], p.fill_scratch, p.fill_scratch_offset); - } - detail::memory_barrier(vk, command_buffer, VK_ACCESS_TRANSFER_WRITE_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, - state.access, state.stages); - continue; - } - // Cleared in place in GENERAL, the UAV layout, which transfer clears and attachments both accept. - const VkImageLayout layout = image_layout(p.binding, state.layout); - auto pieces = detail::current(tracker, id, p.range, layout); - detail::initialize(vk, command_buffer, p.binding, id, pieces, layout, tracker); - if (p.rects.empty()) { - detail::round_trip(vk, command_buffer, p.binding, pieces, layout, state, - VK_ACCESS_TRANSFER_WRITE_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, [&] { - vk.clear_color_image(command_buffer, p.binding.image, layout, &p.clear_color, 1, &p.range); - }); - continue; - } - detail::round_trip(vk, command_buffer, p.binding, pieces, layout, state, - VK_ACCESS_COLOR_ATTACHMENT_READ_BIT | VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT, - VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT, [&] { - VkRenderingAttachmentInfo info{VK_STRUCTURE_TYPE_RENDERING_ATTACHMENT_INFO}; - info.imageView = p.view; - info.imageLayout = layout; - info.loadOp = VK_ATTACHMENT_LOAD_OP_LOAD; - info.storeOp = VK_ATTACHMENT_STORE_OP_STORE; - VkRenderingInfo rendering{VK_STRUCTURE_TYPE_RENDERING_INFO}; - rendering.renderArea = {{0, 0}, detail::mip_extent(p.binding, uav->view.mip)}; - rendering.layerCount = uav->view.layer_count; - rendering.colorAttachmentCount = 1; - rendering.pColorAttachments = &info; - vk.begin_rendering(command_buffer, &rendering); - VkClearAttachment attachment_clear{VK_IMAGE_ASPECT_COLOR_BIT, 0, {}}; - attachment_clear.clearValue.color = p.clear_color; - vk.clear_attachments(command_buffer, 1, &attachment_clear, std::uint32_t(p.rects.size()), p.rects.data()); - vk.end_rendering(command_buffer); - }); - } else if (std::holds_alternative(command) || std::holds_alternative(command) || - std::holds_alternative(command)) { - const auto [dst_id, src_id] = copy_ids(command); - if (!p.predicated_copy.empty()) { - end_statistics(); - vk.emit_predicated_copy(command_buffer, p.predicated_copy); - begin_statistics(); - } else if (!p.buffer_copies.empty()) { - vk.copy_buffer(command_buffer, p.source.buffer, p.binding.buffer, std::uint32_t(p.buffer_copies.size()), - p.buffer_copies.data()); - } else if (p.staged) { - // Depth <-> colour, or a block-compressed copy no one extent fits: the source into the scratch, then - // the scratch into the destination. The destination's copy_layout comes after the scratch write, so - // its barrier orders every earlier transfer write before the destination's (#860, Vonsek's - // synchronization-validation run). - const VkImageLayout src_layout = detail::copy_layout( - vk, command_buffer, p.source, src_id, detail::planes_for_layout(p.source, p.source_range, separate), - VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, VK_ACCESS_TRANSFER_READ_BIT, tracker); - vk.copy_image_to_buffer(command_buffer, p.source.image, src_layout, p.staged, - std::uint32_t(p.staged_reads.size()), p.staged_reads.data()); - detail::memory_barrier(vk, command_buffer, VK_ACCESS_TRANSFER_WRITE_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, - VK_ACCESS_TRANSFER_READ_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT); - const VkImageLayout dst_layout = detail::copy_layout( - vk, command_buffer, p.binding, dst_id, detail::planes_for_layout(p.binding, p.range, separate), - VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, VK_ACCESS_TRANSFER_WRITE_BIT, tracker); - vk.copy_buffer_to_image(command_buffer, p.staged, p.binding.image, dst_layout, - std::uint32_t(p.staged_writes.size()), p.staged_writes.data()); - } else if (!p.image_copies.empty()) { - // A subresource can be both the source and destination only in a shared layout. - const bool self = p.same_copy_subresource; - const VkImageLayout src_layout = detail::copy_layout( - vk, command_buffer, p.source, src_id, detail::planes_for_layout(p.source, p.source_range, separate), - self ? VK_IMAGE_LAYOUT_GENERAL : VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, - self ? VK_ACCESS_TRANSFER_READ_BIT | VK_ACCESS_TRANSFER_WRITE_BIT : VK_ACCESS_TRANSFER_READ_BIT, - tracker); - const VkImageLayout dst_layout = self ? src_layout : detail::copy_layout( - vk, command_buffer, p.binding, dst_id, detail::planes_for_layout(p.binding, p.range, separate), - VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, VK_ACCESS_TRANSFER_WRITE_BIT, tracker); - const auto count = std::uint32_t(p.image_copies.size()); - const auto depth_stencil = VK_IMAGE_ASPECT_DEPTH_BIT | VK_IMAGE_ASPECT_STENCIL_BIT; - if (std::holds_alternative(command) && - (p.binding.aspects & depth_stencil) == depth_stencil) { - // prepare_resource_copy groups regions by aspect. On RX 5700 XT (Windows driver - // 32.0.21045.5002), copying both groups in one command corrupts stencil in multi-mip - // arrays, even with validation clean. Order the aspect writes explicitly; a barrier - // before or after the bulk copy does not fix it. Keep all mips/layers batched per aspect. - const auto depth_count = p.source.mip_levels; - vk.copy_image(command_buffer, p.source.image, src_layout, p.binding.image, dst_layout, - depth_count, p.image_copies.data()); - detail::memory_barrier(vk, command_buffer, VK_ACCESS_TRANSFER_WRITE_BIT, - VK_PIPELINE_STAGE_TRANSFER_BIT, - VK_ACCESS_TRANSFER_READ_BIT | VK_ACCESS_TRANSFER_WRITE_BIT, - VK_PIPELINE_STAGE_TRANSFER_BIT); - vk.copy_image(command_buffer, p.source.image, src_layout, p.binding.image, dst_layout, - count - depth_count, p.image_copies.data() + depth_count); - } else { - vk.copy_image(command_buffer, p.source.image, src_layout, p.binding.image, dst_layout, - count, p.image_copies.data()); - } - } else if (p.binding.image) { - VkBuffer source = p.source.buffer; - std::vector converted; - const std::vector* regions = &p.buffer_image_copies; - if (p.tile_scratch) { - vk.copy_buffer(command_buffer, source, p.tile_scratch, std::uint32_t(p.tile_rows.size()), - p.tile_rows.data()); - detail::memory_barrier(vk, command_buffer, VK_ACCESS_TRANSFER_WRITE_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, - VK_ACCESS_TRANSFER_READ_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT); - source = p.tile_scratch; - } else if (p.has_depth24) { - // The words become floats in the scratch buffer, which the copy then reads (tightly packed). - detail::memory_barrier(vk, command_buffer, VK_ACCESS_MEMORY_WRITE_BIT, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, - VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT, - VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT); - end_statistics(); - for (const auto& part : p.depth24_parts) run_depth24(part); - begin_statistics(); - detail::memory_barrier(vk, command_buffer, VK_ACCESS_SHADER_WRITE_BIT, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, - VK_ACCESS_TRANSFER_READ_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT); - converted = p.buffer_image_copies; - converted[0].bufferOffset = p.depth24.scratch_offset; - converted[0].bufferRowLength = 0; - converted[0].bufferImageHeight = 0; - regions = &converted; - source = p.depth24.scratch; - } - const VkImageLayout dst_layout = detail::copy_layout( - vk, command_buffer, p.binding, dst_id, detail::planes_for_layout(p.binding, p.range, separate), - VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, VK_ACCESS_TRANSFER_WRITE_BIT, tracker); - vk.copy_buffer_to_image(command_buffer, source, p.binding.image, dst_layout, - std::uint32_t(regions->size()), regions->data()); - } else { - const VkImageLayout src_layout = detail::copy_layout( - vk, command_buffer, p.source, src_id, detail::planes_for_layout(p.source, p.source_range, separate), - VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, VK_ACCESS_TRANSFER_READ_BIT, tracker); - if (!p.has_depth24) { - const auto target = p.tile_scratch ? p.tile_scratch : p.binding.buffer; - vk.copy_image_to_buffer(command_buffer, p.source.image, src_layout, target, - std::uint32_t(p.buffer_image_copies.size()), p.buffer_image_copies.data()); - if (p.tile_scratch) { - detail::memory_barrier(vk, command_buffer, VK_ACCESS_TRANSFER_WRITE_BIT, - VK_PIPELINE_STAGE_TRANSFER_BIT, VK_ACCESS_TRANSFER_READ_BIT, - VK_PIPELINE_STAGE_TRANSFER_BIT); - vk.copy_buffer(command_buffer, p.tile_scratch, p.binding.buffer, - std::uint32_t(p.tile_rows.size()), p.tile_rows.data()); - } - } else { - // The floats land tightly packed in the scratch buffer; the pass turns them into the footprint's words. - VkBufferImageCopy region = p.buffer_image_copies[0]; - region.bufferOffset = p.depth24.scratch_offset; - region.bufferRowLength = 0; - region.bufferImageHeight = 0; - vk.copy_image_to_buffer(command_buffer, p.source.image, src_layout, p.depth24.scratch, 1, ®ion); - detail::memory_barrier(vk, command_buffer, VK_ACCESS_MEMORY_WRITE_BIT, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, - VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT, - VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT); - end_statistics(); - for (const auto& part : p.depth24_parts) run_depth24(part); - begin_statistics(); - detail::memory_barrier(vk, command_buffer, VK_ACCESS_SHADER_WRITE_BIT, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, - VK_ACCESS_MEMORY_READ_BIT | VK_ACCESS_MEMORY_WRITE_BIT, - VK_PIPELINE_STAGE_ALL_COMMANDS_BIT); - } - } - } else if (std::holds_alternative(command)) { - // resolve_source and resolve_dest are the transfer layouts, as copy_source and copy_dest are. - const auto [dst_id, src_id] = copy_ids(command); - if (p.resolve_mode != VK_RESOLVE_MODE_NONE) { - // A rendering scope of its own, with no draws: the source plane as the attachment, the destination - // as its resolve target. Both go to the attachment layout and back. Resolves run in the colour - // attachment output stage with colour attachment accesses, depth and stencil ones included. - constexpr VkAccessFlags attachment_access = - VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_READ_BIT | VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT | - VK_ACCESS_COLOR_ATTACHMENT_READ_BIT | VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT; - constexpr VkPipelineStageFlags attachment_stages = VK_PIPELINE_STAGE_EARLY_FRAGMENT_TESTS_BIT | - VK_PIPELINE_STAGE_LATE_FRAGMENT_TESTS_BIT | - VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT; - const VulkanAccess source_state = vulkan_access(d3d12_state::resolve_source, false); - const VulkanAccess dest_state = vulkan_access(d3d12_state::resolve_dest, false); - const VkImageLayout source_layout = image_layout(p.source, source_state.layout); - const VkImageLayout dest_layout = image_layout(p.binding, dest_state.layout); - auto source_pieces = detail::current( - tracker, src_id, detail::planes_for_layout(p.source, p.source_range, separate), source_layout); - detail::initialize(vk, command_buffer, p.source, src_id, source_pieces, source_layout, tracker); - auto dest_pieces = detail::current( - tracker, dst_id, detail::planes_for_layout(p.binding, p.range, separate), dest_layout); - detail::initialize(vk, command_buffer, p.binding, dst_id, dest_pieces, dest_layout, tracker); - // The texels around the rectangle, kept in `staged` across the resolve (keep_around_resolve). - const auto keep = [&](VkImageLayout wanted, VkAccessFlags access, auto&& copy) { - const VkImageLayout layout = image_layout(p.binding, wanted); - detail::round_trip(vk, command_buffer, p.binding, dest_pieces, layout, dest_state, access, - VK_PIPELINE_STAGE_TRANSFER_BIT, [&] { copy(layout); }); - }; - const auto bands = std::uint32_t(p.staged_reads.size()); - if (p.staged) { - keep(VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, VK_ACCESS_TRANSFER_READ_BIT, [&](VkImageLayout layout) { - vk.copy_image_to_buffer(command_buffer, p.binding.image, layout, p.staged, bands, - p.staged_reads.data()); - }); - detail::memory_barrier(vk, command_buffer, VK_ACCESS_TRANSFER_WRITE_BIT, - VK_PIPELINE_STAGE_TRANSFER_BIT, VK_ACCESS_TRANSFER_READ_BIT, - VK_PIPELINE_STAGE_TRANSFER_BIT); - } - const VkImageLayout source_attachment = - image_layout(p.source, VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL); - const VkImageLayout dest_attachment = - image_layout(p.binding, VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL); - detail::round_trip(vk, command_buffer, p.source, source_pieces, source_attachment, source_state, - attachment_access, attachment_stages, [&] { - detail::round_trip(vk, command_buffer, p.binding, dest_pieces, dest_attachment, dest_state, - attachment_access, attachment_stages, [&] { - if (p.resolve_framebuffer) { // D3D-417 (prepare): the same resolve as a render pass - VkRenderPassBeginInfo begin{VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO}; - begin.renderPass = p.resolve_pass; - begin.framebuffer = p.resolve_framebuffer; - begin.renderArea = {{p.resolve.srcOffset.x, p.resolve.srcOffset.y}, - {p.resolve.extent.width, p.resolve.extent.height}}; - vk.begin_render_pass(command_buffer, &begin, VK_SUBPASS_CONTENTS_INLINE); - vk.end_render_pass(command_buffer); - return; - } - VkRenderingAttachmentInfo info{VK_STRUCTURE_TYPE_RENDERING_ATTACHMENT_INFO}; - info.imageView = p.view; - info.imageLayout = source_attachment; - info.resolveMode = p.resolve_mode; - info.resolveImageView = p.resolve_view; - info.resolveImageLayout = dest_attachment; - info.loadOp = VK_ATTACHMENT_LOAD_OP_LOAD; - info.storeOp = VK_ATTACHMENT_STORE_OP_NONE; // the source is only read - VkRenderingInfo rendering{VK_STRUCTURE_TYPE_RENDERING_INFO}; - rendering.renderArea = {{p.resolve.srcOffset.x, p.resolve.srcOffset.y}, - {p.resolve.extent.width, p.resolve.extent.height}}; - rendering.layerCount = 1; - // One plane only, so independentResolve(None) never applies. - if (p.range.aspectMask == VK_IMAGE_ASPECT_DEPTH_BIT) rendering.pDepthAttachment = &info; - else rendering.pStencilAttachment = &info; - vk.begin_rendering(command_buffer, &rendering); - vk.end_rendering(command_buffer); - }); - }); - if (p.staged) { - keep(VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, VK_ACCESS_TRANSFER_WRITE_BIT, [&](VkImageLayout layout) { - vk.copy_buffer_to_image(command_buffer, p.staged, p.binding.image, layout, bands, - p.staged_reads.data()); - }); - } - continue; - } - const VkImageLayout src_layout = detail::copy_layout( - vk, command_buffer, p.source, src_id, detail::planes_for_layout(p.source, p.source_range, separate), - VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, VK_ACCESS_TRANSFER_READ_BIT, tracker); - const VkImageLayout dst_layout = detail::copy_layout( - vk, command_buffer, p.binding, dst_id, detail::planes_for_layout(p.binding, p.range, separate), - VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, VK_ACCESS_TRANSFER_WRITE_BIT, tracker); - vk.resolve_image(command_buffer, p.source.image, src_layout, p.binding.image, dst_layout, 1, &p.resolve); - } else if (const auto* marker = std::get_if(&command)) { - if (!vk.insert_label || !vk.begin_label || !vk.end_label) continue; - VkDebugUtilsLabelEXT label{VK_STRUCTURE_TYPE_DEBUG_UTILS_LABEL_EXT}; - label.pLabelName = marker->label.c_str(); - if (marker->kind == DebugMarker::Kind::set) { - vk.insert_label(command_buffer, &label); - } else if (marker->kind == DebugMarker::Kind::begin) { - vk.begin_label(command_buffer, &label); - ++labels; - } else if (labels) { - vk.end_label(command_buffer); - --labels; - } - } else if (std::holds_alternative(command)) { - // oldLayout = UNDEFINED tells the driver the contents may go; the image stays in the layout the tracker - // has for it, so later commands see no change. Without a tracker the layout is unknown, and a part - // never used yet is still to be zero-filled: both are left alone. Without separate depth/stencil - // layouts, discarding one plane would also discard the other, so that is left alone too. - constexpr VkAccessFlags any_memory = VK_ACCESS_MEMORY_READ_BIT | VK_ACCESS_MEMORY_WRITE_BIT; - for (const auto& range : p.discards) { - if (!tracker || detail::planes_for_layout(p.binding, range, separate).aspectMask != range.aspectMask) - continue; - LayoutPieces pieces; - if (!tracker->pieces(id, range, pieces)) continue; - for (const auto& piece : pieces) - if (piece.layout != VK_IMAGE_LAYOUT_UNDEFINED) - detail::image_barrier(vk, command_buffer, p.binding, piece.range, VK_IMAGE_LAYOUT_UNDEFINED, - piece.layout, VK_ACCESS_MEMORY_WRITE_BIT, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, - any_memory, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT); - } - } else if (const auto* write = std::get_if(&command)) { - // vkCmdUpdateBuffer runs in the transfer stage. MARKER_OUT waits for every earlier command to finish - // and sees its writes. MARKER_IN only needs them started, which Vulkan cannot express (TOP_OF_PIPE in a - // first scope is no stage at all), so it waits for them to finish too, without their writes. DEFAULT is - // ordered like any copy, by the application's barriers. - if (write->mode == write_immediate_mode::marker_out) - detail::memory_barrier(vk, command_buffer, VK_ACCESS_MEMORY_WRITE_BIT, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, - VK_ACCESS_TRANSFER_WRITE_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT); - else if (write->mode == write_immediate_mode::marker_in) - detail::memory_barrier(vk, command_buffer, 0, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, 0, - VK_PIPELINE_STAGE_TRANSFER_BIT); - // WriteBufferImmediate is unconditional on hardware D3D12 (measured on Intel and NVIDIA D3D12; not in - // SetPredication's predicated list). Suspend conditional rendering around vkCmdUpdateBuffer because - // Intel's Windows Vulkan driver suppresses it after PredicateReducer::capture's compute dispatch. - if (predicate.buffer) vk.end_conditional_rendering(command_buffer); - vk.update_buffer(command_buffer, p.write_buffer, p.write_offset, 4, &write->value); - if (predicate.buffer) vk.begin_conditional_rendering(command_buffer, &predicate); - } else if (std::holds_alternative(command)) { - // Every earlier write, to the dependent resources among others, finishes and is visible before the copy. - // Vulkan promises no atomicity for a transfer; that a naturally aligned 4- or 8-byte copy is one write - // is an assumption about the hardware (docs/d3d12_vulkan.md, section 4.2). - detail::memory_barrier(vk, command_buffer, VK_ACCESS_MEMORY_WRITE_BIT, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, - VK_ACCESS_TRANSFER_READ_BIT | VK_ACCESS_TRANSFER_WRITE_BIT, - VK_PIPELINE_STAGE_TRANSFER_BIT); - vk.copy_buffer(command_buffer, p.source.buffer, p.binding.buffer, 1, p.buffer_copies.data()); - } else if (const auto* ind = std::get_if(&command)) { - const VkDeviceSize arguments = p.binding.buffer_offset + ind->argument_offset; - if (ind->count_buffer && ind->kind != IndirectKind::dispatch) { - const VkDeviceSize count = p.source.buffer_offset + ind->count_offset; - if (ind->kind == IndirectKind::draw) { - vk.draw_indirect_count(command_buffer, p.binding.buffer, arguments, p.source.buffer, - count, ind->max_count, ind->stride); - } else if (ind->kind == IndirectKind::draw_indexed) { - vk.draw_indexed_indirect_count(command_buffer, p.binding.buffer, arguments, - p.source.buffer, count, ind->max_count, ind->stride); - } - } else { - if (ind->kind == IndirectKind::draw) { - vk.draw_indirect(command_buffer, p.binding.buffer, arguments, ind->max_count, ind->stride); - } else if (ind->kind == IndirectKind::draw_indexed) { - vk.draw_indexed_indirect(command_buffer, p.binding.buffer, arguments, ind->max_count, ind->stride); - } else if (ind->kind == IndirectKind::dispatch) { - if (ind->count_buffer) { - // No D3D12 query must count this internal compute pass as an application dispatch. - end_statistics(); - vk.emit_counted_dispatch(command_buffer, p.counted_dispatch); - begin_statistics(); - } - if (ind->pipeline) { - ShaderUserData data{}; - std::copy(ind->user_data.begin(), ind->user_data.end(), data.s); - data.heap_base = vk.heap_base; - data.code_base = p.pipeline.code_base; - vk.bind_pipeline(command_buffer, VK_PIPELINE_BIND_POINT_COMPUTE, p.pipeline.pipeline); - if (p.pipeline.bindless_set) { - const VkDescriptorSet set0 = vk.bindless_set ? vk.bindless_set : p.pipeline.bindless_set; - vk.bind_descriptor_sets(command_buffer, VK_PIPELINE_BIND_POINT_COMPUTE, p.pipeline.layout, 0, - 1, &set0, 0, nullptr); - } - vk.push_constants(command_buffer, p.pipeline.layout, VK_SHADER_STAGE_COMPUTE_BIT, 0, sizeof(data), - &data); - } - for (std::uint32_t k = 0; k < ind->max_count; ++k) { - vk.dispatch_indirect(command_buffer, - ind->count_buffer ? p.counted_dispatch.indirect : p.binding.buffer, - (ind->count_buffer ? p.counted_dispatch.offset + VkDeviceSize(k) * 12 - : arguments + VkDeviceSize(k) * ind->stride)); - } - } - } - } else if (const auto* xdxr_build = std::get_if(&command); - xdxr_build && vk.xdxr_record) { - vk.xdxr_record(command_buffer, *xdxr_build); - } else if (const auto* copy = std::get_if(&command)) { - if (vk.xdxr_copy) { - vk.xdxr_copy(command_buffer, copy->src_va, copy->dst_va, p.xdxr_bytes); - } else { - VkCopyAccelerationStructureInfoKHR copy_info{VK_STRUCTURE_TYPE_COPY_ACCELERATION_STRUCTURE_INFO_KHR}; - copy_info.src = p.accel_src; - copy_info.dst = p.accel_dst; - copy_info.mode = copy->mode == 1 ? VK_COPY_ACCELERATION_STRUCTURE_MODE_COMPACT_KHR - : VK_COPY_ACCELERATION_STRUCTURE_MODE_CLONE_KHR; - vk.copy_acceleration_structure(command_buffer, ©_info); - } - } else if (const auto* postbuild = std::get_if(&command); - postbuild && !p.skip) { - if (vk.xdxr_postbuild) { - for (std::size_t s = 0; s < postbuild->sources.size(); ++s) - vk.xdxr_postbuild(command_buffer, postbuild->sources[s], postbuild->dest_va + 8 * s); - } else if (p.khr_postbuild < prepared.khr_postbuilds.size()) { - const auto& pb = prepared.khr_postbuilds[p.khr_postbuild]; - const auto count = static_cast(pb.sources.size()); - // Ensure an inline BuildRaytracingAccelerationStructure (or preceding copy) is visible before query read. - VkMemoryBarrier as_mb{VK_STRUCTURE_TYPE_MEMORY_BARRIER}; - as_mb.srcAccessMask = VK_ACCESS_ACCELERATION_STRUCTURE_WRITE_BIT_KHR; - as_mb.dstAccessMask = VK_ACCESS_ACCELERATION_STRUCTURE_READ_BIT_KHR; - vk.pipeline_barrier(command_buffer, VK_PIPELINE_STAGE_ACCELERATION_STRUCTURE_BUILD_BIT_KHR, - VK_PIPELINE_STAGE_ACCELERATION_STRUCTURE_BUILD_BIT_KHR, 0, 1, &as_mb, 0, nullptr, - 0, nullptr); - vk.reset_query_pool(command_buffer, pb.query_pool, pb.first_query, count); - vk.write_acceleration_structures_properties( - command_buffer, count, pb.sources.data(), - VK_QUERY_TYPE_ACCELERATION_STRUCTURE_COMPACTED_SIZE_KHR, pb.query_pool, pb.first_query); - vk.copy_query_pool_results(command_buffer, pb.query_pool, pb.first_query, count, pb.dst_buffer, - pb.dst_offset, 8, VK_QUERY_RESULT_64_BIT | VK_QUERY_RESULT_WAIT_BIT); - // Make query result writes visible to D3D12 UNORDERED_ACCESS shaders and subsequent CopyBufferRegion. - VkMemoryBarrier dst_mb{VK_STRUCTURE_TYPE_MEMORY_BARRIER}; - dst_mb.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT; - dst_mb.dstAccessMask = VK_ACCESS_TRANSFER_READ_BIT | VK_ACCESS_TRANSFER_WRITE_BIT | - VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT; - vk.pipeline_barrier(command_buffer, VK_PIPELINE_STAGE_TRANSFER_BIT, - VK_PIPELINE_STAGE_TRANSFER_BIT | shader_stages, 0, 1, &dst_mb, 0, nullptr, 0, - nullptr); - } - } else if (const auto* build = std::get_if(&command)) { - // The build's addresses are console VAs into the GPU address arena (heap_base is its device address). - // A null VA (no index buffer, no transform) stays null: heap_base + 0 would name the arena's zero page. - const VkDeviceSize heap_base = vk.heap_base; - const auto addr = [&](std::uint64_t va) -> VkDeviceAddress { return va ? heap_base + va : 0; }; - std::vector geoms; - std::vector ranges; - if (build->is_tlas) { - VkAccelerationStructureGeometryKHR g{VK_STRUCTURE_TYPE_ACCELERATION_STRUCTURE_GEOMETRY_KHR}; - g.geometryType = VK_GEOMETRY_TYPE_INSTANCES_KHR; - g.geometry.instances.sType = VK_STRUCTURE_TYPE_ACCELERATION_STRUCTURE_GEOMETRY_INSTANCES_DATA_KHR; - g.geometry.instances.arrayOfPointers = p.khr_instances ? VK_TRUE : VK_FALSE; - g.geometry.instances.data.deviceAddress = - p.khr_instances ? p.khr_instances : addr(build->instances_va); - geoms.push_back(g); - ranges.push_back({build->instance_count, 0, 0, 0}); - } else { - geoms.reserve(build->triangles.size()); - ranges.reserve(build->triangles.size()); - for (const auto& t : build->triangles) { - VkAccelerationStructureGeometryKHR g{VK_STRUCTURE_TYPE_ACCELERATION_STRUCTURE_GEOMETRY_KHR}; - g.geometryType = VK_GEOMETRY_TYPE_TRIANGLES_KHR; - g.flags = t.opaque ? VK_GEOMETRY_OPAQUE_BIT_KHR : 0u; - auto& tr = g.geometry.triangles; - tr.sType = VK_STRUCTURE_TYPE_ACCELERATION_STRUCTURE_GEOMETRY_TRIANGLES_DATA_KHR; - tr.vertexFormat = static_cast(t.vertex_format); - tr.vertexData.deviceAddress = addr(t.vertex_va); - tr.vertexStride = t.vertex_stride; - tr.maxVertex = t.vertex_count ? (t.vertex_count - 1u) : 0u; - tr.indexType = (t.index_type == 1) - ? VK_INDEX_TYPE_UINT16 - : ((t.index_type == 2) ? VK_INDEX_TYPE_UINT32 : VK_INDEX_TYPE_NONE_KHR); - tr.indexData.deviceAddress = addr(t.index_va); - tr.transformData.deviceAddress = addr(t.transform_va); - geoms.push_back(g); - const std::uint32_t prim_count = - (t.index_type != 0 && t.index_count >= 3) ? (t.index_count / 3u) : (t.vertex_count / 3u); - ranges.push_back({prim_count, 0, 0, 0}); - } - } - VkAccelerationStructureBuildGeometryInfoKHR info{ - VK_STRUCTURE_TYPE_ACCELERATION_STRUCTURE_BUILD_GEOMETRY_INFO_KHR}; - info.type = build->is_tlas ? VK_ACCELERATION_STRUCTURE_TYPE_TOP_LEVEL_KHR - : VK_ACCELERATION_STRUCTURE_TYPE_BOTTOM_LEVEL_KHR; - info.flags = build->build_flags; - info.mode = build->update ? VK_BUILD_ACCELERATION_STRUCTURE_MODE_UPDATE_KHR - : VK_BUILD_ACCELERATION_STRUCTURE_MODE_BUILD_KHR; - info.srcAccelerationStructure = build->update ? p.accel_src : VK_NULL_HANDLE; - info.dstAccelerationStructure = p.accel_dst; - info.geometryCount = static_cast(geoms.size()); - info.pGeometries = geoms.data(); - info.scratchData.deviceAddress = addr(build->scratch_va); - const VkAccelerationStructureBuildRangeInfoKHR* range_ptr = ranges.data(); - vk.build_acceleration_structures(command_buffer, 1, &info, &range_ptr); - } else if (const auto* dispatch = std::get_if(&command)) { - ShaderUserData data{}; - std::copy(dispatch->user_data.begin(), dispatch->user_data.end(), data.s); - data.heap_base = vk.heap_base; - data.code_base = p.pipeline.code_base; - vk.bind_pipeline(command_buffer, VK_PIPELINE_BIND_POINT_COMPUTE, p.pipeline.pipeline); - if (p.pipeline.bindless_set) { - const VkDescriptorSet set0 = vk.bindless_set ? vk.bindless_set : p.pipeline.bindless_set; - vk.bind_descriptor_sets(command_buffer, VK_PIPELINE_BIND_POINT_COMPUTE, p.pipeline.layout, 0, 1, - &set0, 0, nullptr); - } - vk.push_constants(command_buffer, p.pipeline.layout, VK_SHADER_STAGE_COMPUTE_BIT, 0, sizeof(data), &data); - vk.dispatch(command_buffer, dispatch->x, dispatch->y, dispatch->z); - } else if (const auto* draw = std::get_if(&command)) { - const detail::PreparedDraw& d = prepared.draws[p.draw]; - constexpr VkAccessFlags color_access = - VK_ACCESS_COLOR_ATTACHMENT_READ_BIT | VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT; - constexpr VkAccessFlags depth_access = - VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_READ_BIT | VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT; - constexpr VkPipelineStageFlags depth_stages = - VK_PIPELINE_STAGE_EARLY_FRAGMENT_TESTS_BIT | VK_PIPELINE_STAGE_LATE_FRAGMENT_TESTS_BIT; - std::array colors; - colors.fill({VK_STRUCTURE_TYPE_RENDERING_ATTACHMENT_INFO}); - for (std::size_t slot = 0; slot < d.colors.size(); ++slot) { - const auto& a = d.colors[slot]; - if (!a.id) continue; // an unbound slot: no image view, writes are dropped - const VkImageLayout layout = image_layout(a.binding, VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL); - detail::to_attachment(vk, command_buffer, a, layout, color_access, - VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT, tracker, separate); - colors[slot].imageView = a.view; - colors[slot].imageLayout = layout; - colors[slot].loadOp = VK_ATTACHMENT_LOAD_OP_LOAD; - colors[slot].storeOp = VK_ATTACHMENT_STORE_OP_STORE; - } - VkRenderingAttachmentInfo depth{VK_STRUCTURE_TYPE_RENDERING_ATTACHMENT_INFO}; - if (d.depth.id) { - const VkImageLayout layout = image_layout(d.depth.binding, VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL); - detail::to_attachment(vk, command_buffer, d.depth, layout, depth_access, depth_stages, tracker, - separate); - depth.imageView = d.depth.view; - depth.imageLayout = layout; - depth.loadOp = VK_ATTACHMENT_LOAD_OP_LOAD; - depth.storeOp = VK_ATTACHMENT_STORE_OP_STORE; - } - VkRenderingInfo rendering{VK_STRUCTURE_TYPE_RENDERING_INFO}; - rendering.renderArea = {{0, 0}, d.area}; - rendering.layerCount = d.layers; // array views: SV_RenderTargetArrayIndex picks the layer - rendering.colorAttachmentCount = std::uint32_t(d.colors.size()); - rendering.pColorAttachments = colors.data(); - const GraphicsPipeline& graphics = *d.graphics; - if (d.depth.id && (graphics.depth_aspects & VK_IMAGE_ASPECT_DEPTH_BIT)) rendering.pDepthAttachment = &depth; - if (d.depth.id && (graphics.depth_aspects & VK_IMAGE_ASPECT_STENCIL_BIT)) rendering.pStencilAttachment = &depth; - vk.begin_rendering(command_buffer, &rendering); - - ShaderUserData data{}; - std::copy(draw->user_data.begin(), draw->user_data.end(), data.s); - data.heap_base = vk.heap_base; - data.code_base = graphics.code_base; - vk.bind_pipeline(command_buffer, VK_PIPELINE_BIND_POINT_GRAPHICS, d.pipeline); - if (graphics.bindless_set) { - const VkDescriptorSet set0 = vk.bindless_set ? vk.bindless_set : graphics.bindless_set; - vk.bind_descriptor_sets(command_buffer, VK_PIPELINE_BIND_POINT_GRAPHICS, graphics.layout, 0, 1, - &set0, 0, nullptr); - } - vk.push_constants(command_buffer, graphics.layout, graphics.push_stages, 0, sizeof(data), &data); - // Translated vertex shaders write D3D clip coordinates (y up); a negative-height viewport keeps the - // image upright, and winding as D3D12 sees it. - const Viewport& v = draw->viewport; - const VkViewport viewport{v.x, v.y + v.height, v.width, -v.height, v.min_depth, v.max_depth}; - vk.set_viewport(command_buffer, 0, 1, &viewport); - const Rect& s = draw->scissor; - const VkRect2D scissor{{std::max(0, s.left), std::max(0, s.top)}, - {std::uint32_t(std::max(0, s.right - std::max(0, s.left))), - std::uint32_t(std::max(0, s.bottom - std::max(0, s.top)))}}; - vk.set_scissor(command_buffer, 0, 1, &scissor); - // A mesh pipeline has no input assembly: its topology comes from the shader, and neither the topology - // nor primitive restart is dynamic state there (VUID-VkGraphicsPipelineCreateInfo-pDynamicStates-07065). - if (!draw->mesh) { - const VkPrimitiveTopology topology = detail::vulkan_topology(draw->topology); - vk.set_primitive_topology(command_buffer, topology); - const bool restart = draw->indexed && detail::strip_topology(topology) && - ((graphics.strip_cut == 1 && d.index_type == VK_INDEX_TYPE_UINT16) || - (graphics.strip_cut == 2 && d.index_type == VK_INDEX_TYPE_UINT32)); - vk.set_primitive_restart_enable(command_buffer, restart ? VK_TRUE : VK_FALSE); - } - vk.set_stencil_reference(command_buffer, VK_STENCIL_FACE_FRONT_BIT, draw->stencil_front); - vk.set_stencil_reference(command_buffer, VK_STENCIL_FACE_BACK_BIT, draw->stencil_back); - vk.set_blend_constants(command_buffer, draw->blend_factor.data()); - for (std::uint32_t slot = 0; slot < d.vertex_buffers.size(); ++slot) { - if (!d.vertex_buffers[slot]) continue; - vk.bind_vertex_buffers2(command_buffer, slot, 1, &d.vertex_buffers[slot], &d.vertex_offsets[slot], - &d.vertex_sizes[slot], &d.vertex_strides[slot]); - } - if (draw->mesh) { - vk.draw_mesh_tasks(command_buffer, draw->count, draw->instances, draw->first); - } else if (draw->indexed) { - vk.bind_index_buffer(command_buffer, d.index_buffer, d.index_offset, d.index_type); - vk.draw_indexed(command_buffer, draw->count, draw->instances, draw->first, draw->base_vertex, - draw->first_instance); - } else { - vk.draw(command_buffer, draw->count, draw->instances, draw->first, draw->first_instance); - } - vk.end_rendering(command_buffer); - } - } - // Predication does not carry over to the next command list. - if (predicate.buffer) vk.end_conditional_rendering(command_buffer); - if (!open_labels) close_labels(command_buffer, vk, own_labels); -} - -// prepare + emit for one list. A failed replay leaves the command buffer and the tracker untouched. -// With `keep` and vk.create_segment_pool (and the sum helpers) set, overlapping occlusion or statistics queries get -// segment pools as in the batched path; the caller holds `keep` until the command buffer has completed. -template -ReplayResult replay(const CommandList& list, VkCommandBuffer command_buffer, Resolve&& resolve, - const ReplayFunctions& vk, LayoutTracker* tracker = nullptr, - std::vector>* keep = nullptr) { - if (tracker && tracker->separate_depth_stencil_layouts() != vk.separate_depth_stencil_layouts) - return ReplayResult::unsupported; - const bool pools = keep && vk.create_segment_pool && vk.sum_occlusion && vk.resolve_binary_occlusion && - vk.sum_statistics && vk.sum_binary_occlusion; - PreparedList prepared; - if (const auto result = prepare(list, resolve, vk, prepared, pools); result != ReplayResult::success) - return result; - if (tracker && zero_clear_unavailable(prepared, vk, *tracker)) return ReplayResult::unsupported; - std::shared_ptr physical, statistics; - if (pools && prepared.segment_count && - !(physical = vk.create_segment_pool(VK_QUERY_TYPE_OCCLUSION, prepared.segment_count))) - return ReplayResult::unsupported; - if (pools && prepared.statistics_segment_count && - !(statistics = vk.create_segment_pool(VK_QUERY_TYPE_PIPELINE_STATISTICS, prepared.statistics_segment_count))) - return ReplayResult::unsupported; - QueryReplay queries; - if (const auto result = queries.plan(prepared, physical, 0, pools, statistics, 0); result != ReplayResult::success) - return result; - emit(prepared, command_buffer, vk, tracker); - queries.commit(); // the caller owns submission of the legacy command buffer - if (keep) keep->insert(keep->end(), queries.retained.begin(), queries.retained.end()); - return ReplayResult::success; -} - -} // namespace leonida diff --git a/runtime/src/vulkan_scratch.h b/runtime/src/vulkan_scratch.h deleted file mode 100644 index 4a8a59ddd..000000000 --- a/runtime/src/vulkan_scratch.h +++ /dev/null @@ -1,182 +0,0 @@ -// Scratch buffers that live until the submission that used them has completed: device-local chunks handed out -// while a list is prepared, retired with the submission's timeline value, and reused (or freed) once the GPU is past -// it. The replay stages copies Vulkan cannot do in one command through them (vulkan_replay.h, depth <-> colour -// copies). Single-threaded: the caller holds the context's lock. The same life cycle as the depth24 converter's own -// scratch (vulkan_depth24.h), which also needs descriptor pools and exists only on GPUs without D24. -#pragma once - -#ifndef VK_NO_PROTOTYPES -#define VK_NO_PROTOTYPES -#endif -#include - -#include -#include -#include -#include -#include - -namespace leonida { - -class ScratchBuffers { -public: - // A device-local allocation for a chunk; null on failure. - using Allocate = std::function; - - ScratchBuffers(PFN_vkGetDeviceProcAddr get, VkDevice device, Allocate allocate) - : device_(device), allocate_(std::move(allocate)) { - loaded_ = vk_.load(get, device); - } - - ~ScratchBuffers() { - if (!loaded_) return; - vk_.vkDeviceWaitIdle(device_); - release(current_); - for (auto& batch : retired_) release(batch); - for (auto& chunk : spare_) destroy(chunk); - } - - ScratchBuffers(const ScratchBuffers&) = delete; - ScratchBuffers& operator=(const ScratchBuffers&) = delete; - - bool loaded() const { return loaded_; } - - // `bytes` of transfer scratch for the next submission, at a 256-byte aligned offset (more than any copy needs). - bool get(std::uint64_t bytes, VkBuffer& buffer, VkDeviceSize& offset) { - constexpr VkDeviceSize alignment = 256, minimum = 4u << 20; - if (!loaded_ || !bytes) return false; - for (auto& chunk : current_.chunks) { - const VkDeviceSize start = (chunk.used + alignment - 1) / alignment * alignment; - if (start <= chunk.size && bytes <= chunk.size - start) { - chunk.used = start + bytes; - buffer = chunk.buffer; - offset = start; - return true; - } - } - Chunk chunk; - for (std::size_t i = 0; i < spare_.size(); ++i) - if (spare_[i].size >= bytes) { - chunk = spare_[i]; - spare_.erase(spare_.begin() + std::ptrdiff_t(i)); - break; - } - if (!chunk.buffer && !make_chunk(std::max(bytes, minimum), chunk)) return false; - chunk.used = bytes; - buffer = chunk.buffer; - offset = 0; - current_.chunks.push_back(chunk); - return true; - } - - // The chunks handed out since the last call belong to a submission that `timeline` reaches `ticket` for - // (ticket 0: nothing was submitted, they are free once `collect` runs). - void retire(VkSemaphore timeline, std::uint64_t ticket) { - if (current_.chunks.empty()) return; - current_.timeline = timeline; - current_.ticket = ticket; - retired_.push_back(std::move(current_)); - current_ = {}; - } - - // The submissions on `timeline` are over and the semaphore is about to go (its queue is idle). - void forget(VkSemaphore timeline) { - for (std::size_t i = 0; i < retired_.size();) { - if (retired_[i].timeline != timeline) { - ++i; - continue; - } - release(retired_[i]); - retired_.erase(retired_.begin() + std::ptrdiff_t(i)); - } - } - - // Keeps for reuse (or frees) the chunks of finished submissions. - void collect() { - for (std::size_t i = 0; i < retired_.size();) { - if (retired_[i].ticket != 0) { - std::uint64_t done = 0; - if (!retired_[i].timeline || - vk_.vkGetSemaphoreCounterValue(device_, retired_[i].timeline, &done) != VK_SUCCESS || - done < retired_[i].ticket) { - ++i; - continue; - } - } - for (auto& chunk : retired_[i].chunks) { - chunk.used = 0; - if (spare_.size() < 4) spare_.push_back(chunk); - else destroy(chunk); - } - retired_[i].chunks.clear(); - retired_.erase(retired_.begin() + std::ptrdiff_t(i)); - } - } - -private: - struct Chunk { - VkBuffer buffer = VK_NULL_HANDLE; - VkDeviceMemory memory = VK_NULL_HANDLE; - VkDeviceSize size = 0, used = 0; - }; - struct Batch { - std::vector chunks; - VkSemaphore timeline = VK_NULL_HANDLE; - std::uint64_t ticket = 0; - }; - - struct Functions { -#define LEONIDA_SCRATCH_FUNCTIONS(X) \ - X(vkCreateBuffer) X(vkDestroyBuffer) X(vkGetBufferMemoryRequirements) X(vkBindBufferMemory) X(vkFreeMemory) \ - X(vkGetSemaphoreCounterValue) X(vkDeviceWaitIdle) -#define LEONIDA_SCRATCH_MEMBER(name) PFN_##name name = nullptr; - LEONIDA_SCRATCH_FUNCTIONS(LEONIDA_SCRATCH_MEMBER) -#undef LEONIDA_SCRATCH_MEMBER - - bool load(PFN_vkGetDeviceProcAddr get, VkDevice device) { - bool all = true; -#define LEONIDA_SCRATCH_LOAD(name) \ - name = reinterpret_cast(get(device, #name)); \ - all = all && name != nullptr; - LEONIDA_SCRATCH_FUNCTIONS(LEONIDA_SCRATCH_LOAD) -#undef LEONIDA_SCRATCH_LOAD -#undef LEONIDA_SCRATCH_FUNCTIONS - return all; - } - }; - - bool make_chunk(std::uint64_t size, Chunk& out) { - VkBufferCreateInfo info{VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO}; - info.size = size; - info.usage = VK_BUFFER_USAGE_TRANSFER_SRC_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT; - if (vk_.vkCreateBuffer(device_, &info, nullptr, &out.buffer) != VK_SUCCESS) return false; - VkMemoryRequirements requirements{}; - vk_.vkGetBufferMemoryRequirements(device_, out.buffer, &requirements); - out.memory = allocate_ ? allocate_(requirements) : VK_NULL_HANDLE; - if (!out.memory || vk_.vkBindBufferMemory(device_, out.buffer, out.memory, 0) != VK_SUCCESS) { - destroy(out); - return false; - } - out.size = size; - return true; - } - void destroy(Chunk& chunk) { - if (chunk.buffer) vk_.vkDestroyBuffer(device_, chunk.buffer, nullptr); - if (chunk.memory) vk_.vkFreeMemory(device_, chunk.memory, nullptr); - chunk = {}; - } - void release(Batch& batch) { - for (auto& chunk : batch.chunks) destroy(chunk); - batch.chunks.clear(); - } - - VkDevice device_; - Allocate allocate_; - Functions vk_; - bool loaded_ = false; - Batch current_; // handed out, not yet submitted - std::vector retired_; // submitted, waiting for the GPU - std::vector spare_; // finished chunks kept for reuse -}; - -} // namespace leonida diff --git a/runtime/src/xdxr_build.comp b/runtime/src/xdxr_build.comp deleted file mode 100644 index 22a3a1334..000000000 --- a/runtime/src/xdxr_build.comp +++ /dev/null @@ -1,809 +0,0 @@ -// Builds an XDXR BVH4 runtime acceleration structure on the GPU (docs/bvh.md 3.1 and 7a): the records the game's -// translated traversal shaders read with image_bvh_intersect_ray, written straight into the destination resource. -// tools/xdxr_bvh.py is the CPU reference; runtime/test/vk_xdxr_build_test.cpp checks this pass against it. -// xdxr_build_spv.h is this file compiled with `glslc --target-env=vulkan1.2 -O -mfmt=c` (see the header); keep them -// together. -// -// One pipeline, one dispatch per step, selected by pc.mode (xdxr_build.h records them in this order, with a compute -// barrier between each): -// MODE_INIT parent table to 0xffffffff, centroid bounds to empty -// MODE_TRIANGLES one thread per triangle of one geometry: the leaf (TRI0, remap 0x09), its box, the centroid bounds -// MODE_INSTANCES one thread per D3D12_RAYTRACING_INSTANCE_DESC: the 128-byte INSTANCE record and its world box -// MODE_MORTON one thread per element: 30-bit Morton key of its box centre (empty boxes sort last) -// MODE_RADIX_* a stable LSD radix sort of the keys with their element indices: 8 passes of 4-bit digits, each -// a count per tile of RADIX_TILE elements, one exclusive scan, and a scatter (24 dispatches in all, -// whatever the count; shared memory only, no subgroup operations) -// MODE_SMALL_SORT up to SMALL_SORT_MAX keys: one workgroup sorts them in shared memory (bitonic, ties by element -// index, so the order is the stable one), in one dispatch instead of the radix sort's 24, whose -// fixed latency dominated small builds -// MODE_KARRAS one thread per inner node of the binary radix tree over the sorted keys (Karras 2012, keys tied -// by sorted position): its two children and their parent -// MODE_KEPT per tile of RADIX_TILE inner nodes: which ones become box nodes (those at an even depth: each -// takes its children's children, so up to four), and how many per tile -// MODE_KEPT_SCAN one workgroup: the exclusive prefix sum of the tile counts, and the node count -// MODE_KEPT_INDEX per tile: each kept inner node's box node index, in sorted order (the root is node 0) -// MODE_NODES one thread per inner node: a kept one writes its node's child pointers (pairing its sibling -// triangles into TRI1 leaves with FLAG_PAIR), its children's parent table entries, and clears its -// box accumulator. The nodes are BOX32 (128 bytes, float boxes) or, with FLAG_BOX16, BOX16 (64 -// bytes, half boxes rounded outward); the accumulators keep every box exact either way, so -// rounding never compounds up the tree -// MODE_PROPAGATE one thread per element, bottom-up: each record writes its box into its parent's slot and merges it -// into the parent's accumulator; the last child to arrive carries on with the parent's box -// MODE_HEADER one thread: the 64-byte header -// An update (D3D12 PERFORM_UPDATE: same topology, new positions or transforms) refits instead: MODE_COPY_AS copies -// the source structure to the destination when they differ, MODE_TRIANGLES / MODE_INSTANCES rewrite the elements at -// their slots, MODE_CLEAR clears the box accumulators, MODE_PROPAGATE recomputes the boxes through the children each -// node already points to (the tree is kept, so there is no Morton pass and no sort), and MODE_HEADER with arg2 = 1 -// rewrites the bounds. -// MODE_CLEAR one thread per node the layout has room for: its accumulator to empty -// MODE_COPY_AS CopyRaytracingAccelerationStructure CLONE / COMPACT: the source structure's size comes from its -// header (totalSizeIn64BNodes, which does not count the 64-byte header: the size is 64 * (field + -// 1) bytes), so the copy can follow a build in the same list; at most count -// words. The records are position-independent (node pointers count from the structure's start, and -// a TLAS names its BLASes by address), so the bytes are the copy. -// MODE_POSTBUILD one thread: the 8-byte COMPACTED_SIZE or CURRENT_SIZE of the structure at src0, at dst. A build -// is already as small as it gets, so both are (totalSizeIn64BNodes + 1) * 64. -// The node count depends on the keys, so the layout (xdxr_build.h XdxrLayout) leaves room for the most a tree of -// that many elements can have, and the header's size counts only the nodes the build wrote (compaction drops the -// rest). -// -// MODE_PROPAGATE passes boxes between invocations of one dispatch. They only meet through atomics (the -// accumulators and the arrival counters), so no plain load depends on another workgroup's store in the same -// dispatch. The arrival counter's atomicAdd has acquire-release semantics at device scope on buffer memory: a -// child's merges happen before its arrival, and the last arrival sees them all. It is not a memoryBarrierBuffer, -// because the pass is divergent (threads leave at every level) and SPIRV-Cross before MSL 3.2 turns a memory -// barrier into a threadgroup_barrier, which every thread of the threadgroup must reach. -// -// Addresses are 64-bit buffer device addresses passed as uvec2 (GL_EXT_buffer_reference_uvec2): only the -// bufferDeviceAddress feature is needed, no shaderInt64. An address read from memory (an instance's BLAS) is a -// D3D12 GPU virtual address and gets pc.bias added, the distance between the application's address space and the -// device's (0 where they are the same). -// -// No invocation stores to a word and then uses a value it loaded from that word earlier in the same dispatch. The -// SPIRV-Cross in MoltenVK 1.4.2 (6c09849f, and aa217aeb, which MoltenVK main pins) moves a load through a pointer -// made by OpBitcast from a uvec2 to where its value is used, after a store to the same address, so the load reads -// the new value. SPIRV-Cross 38abe362 fixes it. The radix scan used to rewrite the counts in place this way and lost -// elements on MoltenVK (docs/bvh.md, GPU builder). -#version 450 -#extension GL_EXT_buffer_reference : require -#extension GL_EXT_buffer_reference_uvec2 : require -#extension GL_KHR_memory_scope_semantics : require - -layout(local_size_x = 64) in; - -layout(buffer_reference, std430, buffer_reference_align = 4) buffer Words { uint w[]; }; - -const uint MODE_INIT = 0u, MODE_TRIANGLES = 1u, MODE_INSTANCES = 2u, MODE_MORTON = 3u, MODE_KARRAS = 4u, - MODE_NODES = 5u, MODE_HEADER = 6u, MODE_RADIX_COUNT = 7u, MODE_RADIX_SCAN = 8u, MODE_RADIX_SCATTER = 9u, - MODE_SMALL_SORT = 10u, MODE_COPY_AS = 12u, MODE_POSTBUILD = 13u, MODE_KEPT = 14u, - MODE_KEPT_SCAN = 15u, MODE_KEPT_INDEX = 16u, MODE_PROPAGATE = 17u, MODE_CLEAR = 18u; -const uint SMALL_SORT_MAX = 1024u; // xdxr_build.h XdxrLayout::small_sort_max -const uint RADIX_BITS = 4u, RADIX_BINS = 16u, RADIX_PASSES = 8u; -const uint RADIX_TILE = 256u; // elements per workgroup in count and scatter: 4 chunks of 64 -const uint INVALID = 0xffffffffu; -const uint TRI0 = 0u, TRI1 = 1u, BOX16 = 4u, BOX32 = 5u, INSTANCE = 6u; -const uint LEAF = 0x80000000u; // a binary child that is a sorted element, not an inner node -const uint REMAP_IDENTITY = 0x09u; -const uint FLAG_TLAS = 1u, FLAG_BOX16 = 2u, FLAG_PAIR = 4u; // pc.flags; xdxr_build.h XdxrBuilder flag_* -const uint FLAG_BOTTOM_LEVEL = 0x80000000u, VERSION_2403 = 6u, INST_IDENTITY_ROTATION = 0x80000000u, - INST_FLAGS_MASK = 0xc0000000u; - -layout(push_constant) uniform Push { - uvec2 dst; // the acceleration structure (header at byte 0) - uvec2 scratch; // xdxr_build.h XdxrLayout scratch words - uvec2 src0; // triangles: vertices; instances: the instance descs - uvec2 src1; // triangles: indices (0 = none) - uvec2 src2; // triangles: 3x4 transform (0 = none) - uvec2 bias; // added to addresses read from memory - uint mode; - uint count; // threads of this dispatch - uint first; // triangles: first element; radix: the pass (0..7) - uint arg0; // triangles: vertex stride; otherwise the most nodes the layout has room for - uint arg1; // triangles: 0 = R32G32B32_FLOAT, 1 = R32G32_FLOAT - uint arg2; // triangles: index type (0 none, 1 u16, 2 u32); header: 1 = an update (bounds only) - uint geometry; // triangles: geometry index << 8 | D3D12_RAYTRACING_GEOMETRY_FLAGS - uint elements; // element count N - uint sort_size; // N: the keys sorted (one per element) - uint elements_off; // byte offsets in dst (XdxrLayout) - uint nodes_off; - uint parents_off; - uint total_size; - uint flags; // FLAG_TLAS: elements are 128-byte instances; FLAG_BOX16: inner nodes are 64-byte BOX16; - // FLAG_PAIR: pair sibling triangles that share an edge into TRI0/TRI1 leaves -} pc; - -// ---- 64-bit addresses as uvec2 ---- -uvec2 add(uvec2 a, uint b) { - uint carry; - uint lo = uaddCarry(a.x, b, carry); - return uvec2(lo, a.y + carry); -} -uvec2 add64(uvec2 a, uvec2 b) { - uint carry; - uint lo = uaddCarry(a.x, b.x, carry); - return uvec2(lo, a.y + b.y + carry); -} -Words at(uvec2 base, uint byte_offset) { return Words(add(base, byte_offset)); } -uint load(uvec2 base, uint byte_offset) { return at(base, byte_offset).w[0]; } -void store(uvec2 base, uint byte_offset, uint v) { at(base, byte_offset).w[0] = v; } -void storef(uvec2 base, uint byte_offset, float v) { store(base, byte_offset, floatBitsToUint(v)); } -bool is_null(uvec2 a) { return a.x == 0u && a.y == 0u; } - -// ---- scratch: centroid bounds (6 ordered words at 0) and the node count (word 6), keys and element indices twice -// (the radix sort's two sides; the sorted result is back in the first after an even number of passes), digit -// counts, their exclusive prefix sums, element boxes, a box accumulator per node, the binary tree ---- -const uint SCRATCH_KEYS = 64u; -const uint SCRATCH_NODE_COUNT = 24u; -uint radix_tiles() { return (pc.sort_size + RADIX_TILE - 1u) / RADIX_TILE; } -uint keys_off() { return SCRATCH_KEYS; } -uint vals_off() { return SCRATCH_KEYS + 4u * pc.sort_size; } -uint keys2_off() { return SCRATCH_KEYS + 8u * pc.sort_size; } -uint vals2_off() { return SCRATCH_KEYS + 12u * pc.sort_size; } -uint counts_off() { return SCRATCH_KEYS + 16u * pc.sort_size; } // RADIX_BINS x tiles, digit-major -uint offsets_off() { return counts_off() + 4u * RADIX_BINS * radix_tiles(); } // the same shape: the scan of counts -uint boxes_off() { return offsets_off() + 4u * RADIX_BINS * radix_tiles(); } // 6 floats per element -// 8 words per node: the arrival counter, the ordered min x y z (atomicMin), the ordered max x y z (atomicMax), unused -uint accum_off() { return boxes_off() + 24u * pc.elements; } -uint inner() { return pc.elements > 1u ? pc.elements - 1u : 0u; } // inner nodes of the binary tree -uint left_off() { return accum_off() + 32u * pc.arg0; } -uint right_off() { return left_off() + 4u * inner(); } -uint bparent_off() { return right_off() + 4u * inner(); } -uint kept_off() { return bparent_off() + 4u * inner(); } // 1 when the inner node is a box node -uint kmap_off() { return kept_off() + 4u * inner(); } // its BOX32 index -uint kept_tiles() { return (inner() + RADIX_TILE - 1u) / RADIX_TILE; } -uint ktile_counts_off() { return kmap_off() + 4u * inner(); } -uint ktile_offsets_off() { return ktile_counts_off() + 4u * kept_tiles(); } -uint tptr_off() { return ktile_offsets_off() + 4u * kept_tiles(); } // per element: its pointer in the tree - -// A float as a uint that orders the same way, for atomicMin/atomicMax. -uint ordered(float f) { - uint b = floatBitsToUint(f); - return (b & 0x80000000u) != 0u ? ~b : (b | 0x80000000u); -} -float unordered(uint u) { - return uintBitsToFloat((u & 0x80000000u) != 0u ? (u & 0x7fffffffu) : ~u); -} - -void store_box(uint index, vec3 lo, vec3 hi) { - uint o = boxes_off() + 24u * index; - storef(pc.scratch, o, lo.x); storef(pc.scratch, o + 4u, lo.y); storef(pc.scratch, o + 8u, lo.z); - storef(pc.scratch, o + 12u, hi.x); storef(pc.scratch, o + 16u, hi.y); storef(pc.scratch, o + 20u, hi.z); -} -void load_box(uint index, out vec3 lo, out vec3 hi) { - uint o = boxes_off() + 24u * index; - lo = vec3(uintBitsToFloat(load(pc.scratch, o)), uintBitsToFloat(load(pc.scratch, o + 4u)), - uintBitsToFloat(load(pc.scratch, o + 8u))); - hi = vec3(uintBitsToFloat(load(pc.scratch, o + 12u)), uintBitsToFloat(load(pc.scratch, o + 16u)), - uintBitsToFloat(load(pc.scratch, o + 20u))); -} -bool box_empty(vec3 lo, vec3 hi) { return !(lo.x <= hi.x && lo.y <= hi.y && lo.z <= hi.z); } - -void grow_centroid_bounds(vec3 lo, vec3 hi) { - if (box_empty(lo, hi)) return; - vec3 c = (lo + hi) * 0.5; - Words s = at(pc.scratch, 0u); - atomicMin(s.w[0], ordered(c.x)); atomicMin(s.w[1], ordered(c.y)); atomicMin(s.w[2], ordered(c.z)); - atomicMax(s.w[3], ordered(c.x)); atomicMax(s.w[4], ordered(c.y)); atomicMax(s.w[5], ordered(c.z)); -} - -bool is_tlas() { return (pc.flags & FLAG_TLAS) != 0u; } -bool is_box16() { return (pc.flags & FLAG_BOX16) != 0u; } -uint element_size() { return is_tlas() ? 128u : 64u; } -uint node_size() { return is_box16() ? 64u : 128u; } -uint element_ptr(uint e) { return ((pc.elements_off + e * element_size()) >> 6) << 3 | (is_tlas() ? INSTANCE : TRI0); } -uint node_ptr(uint n) { return ((pc.nodes_off + n * node_size()) >> 6) << 3 | (is_box16() ? BOX16 : BOX32); } -uint ptr_unit(uint p) { return p >> 3; } -bool ptr_is_node(uint p) { return (p & 7u) == BOX16 || (p & 7u) == BOX32; } - -// ---- BOX16 bounds: six IEEE halves in three words (min.x | min.y << 16, min.z | max.x << 16, max.y | max.z << 16; -// docs/bvh.md 3.1, XdxrDecompressBox16) ---- -// A float rounded to a half toward -inf (up = false) or +inf (up = true), so the quantised box still contains the -// exact one. Integer code: packHalf2x16's rounding is implementation-defined (AMD's rounds toward zero), and this has -// to be directed. Beyond the half range a value becomes +-inf on its outward side and +-HALF_MAX (0x7bff) on its -// inward side, so an empty box (min +inf, max -inf) stays empty. No denormal half is produced: a value below the -// smallest normal (2^-14) in magnitude goes to 0 or to +-2^-14, whichever is on its side, because a decoder that -// flushes half denormals to zero would otherwise shrink the box. tools/xdxr_bvh.py half_round is the same function. -uint half_directed(float x, bool up) { - uint u = floatBitsToUint(x); - uint sign = (u >> 16) & 0x8000u; - uint a = u & 0x7fffffffu; - bool away = up != (sign != 0u); // round the magnitude up (away from zero) or down (toward zero) - if (a > 0x7f800000u) return sign | 0x7e00u; // NaN: not produced by the box code - if (a == 0u) return sign; - int e = int(a >> 23) - 127; - if (e >= 16) return sign | (away ? 0x7c00u : 0x7bffu); // >= 65536, and +-inf - if (e < -14) return away ? (sign | 0x0400u) : sign; // below the smallest normal half - uint m = a & 0x7fffffu; - uint h = uint(e + 15) << 10 | (m >> 13); - if (away && (m & 0x1fffu) != 0u) h += 1u; // 0x7bff + 1 carries into 0x7c00 = inf - return sign | h; -} -void store_box16(uint o, vec3 lo, vec3 hi) { - store(pc.dst, o, half_directed(lo.x, false) | half_directed(lo.y, false) << 16); - store(pc.dst, o + 4u, half_directed(lo.z, false) | half_directed(hi.x, true) << 16); - store(pc.dst, o + 8u, half_directed(hi.y, true) | half_directed(hi.z, true) << 16); -} - -// ---- MODE_TRIANGLES ---- -vec3 vertex(uint v) { - uvec2 a = add(pc.src0, v * pc.arg0); - float x = uintBitsToFloat(load(a, 0u)), y = uintBitsToFloat(load(a, 4u)); - float z = pc.arg1 == 1u ? 0.0 : uintBitsToFloat(load(a, 8u)); - return vec3(x, y, z); -} -uint index_of(uint i) { - if (pc.arg2 == 0u) return i; - if (pc.arg2 == 2u) return load(pc.src1, 4u * i); - uint word = load(pc.src1, 4u * (i >> 1)); // u16 indices: D3D12 requires 2-byte alignment; the word is aligned - return (i & 1u) != 0u ? word >> 16 : word & 0xffffu; -} -vec3 transformed(vec3 p) { - if (is_null(pc.src2)) return p; - vec3 r; - for (uint row = 0u; row < 3u; ++row) { - uint o = 16u * row; - vec4 m = vec4(uintBitsToFloat(load(pc.src2, o)), uintBitsToFloat(load(pc.src2, o + 4u)), - uintBitsToFloat(load(pc.src2, o + 8u)), uintBitsToFloat(load(pc.src2, o + 12u))); - r[row] = dot(m.xyz, p) + m.w; - } - return r; -} - -void build_triangle(uint t) { - vec3 v[3]; - for (uint k = 0u; k < 3u; ++k) v[k] = transformed(vertex(index_of(3u * t + k))); - uint e = pc.first + t; - uint o = pc.elements_off + 64u * e; - for (uint k = 0u; k < 3u; ++k) { - storef(pc.dst, o + 12u * k, v[k].x); storef(pc.dst, o + 12u * k + 4u, v[k].y); - storef(pc.dst, o + 12u * k + 8u, v[k].z); - } - storef(pc.dst, o + 36u, v[2].x); storef(pc.dst, o + 40u, v[2].y); storef(pc.dst, o + 44u, v[2].z); // slot 3 unused - store(pc.dst, o + 48u, pc.geometry); - store(pc.dst, o + 52u, t); // primitive index within its geometry - store(pc.dst, o + 56u, INVALID); // no TRI1 in this leaf - store(pc.dst, o + 60u, REMAP_IDENTITY); - // D3D12: a triangle whose first vertex has a NaN x is inactive, and so is one with a NaN anywhere it cannot - // be hit; an empty box keeps it out of every traversal and of the centroid bounds. - bool nan_any = any(isnan(v[0])) || any(isnan(v[1])) || any(isnan(v[2])); - vec3 lo = min(min(v[0], v[1]), v[2]), hi = max(max(v[0], v[1]), v[2]); - if (nan_any) { lo = vec3(uintBitsToFloat(0x7f800000u)); hi = -lo; } - store_box(e, lo, hi); - grow_centroid_bounds(lo, hi); -} - -// ---- MODE_INSTANCES ---- -void build_instance(uint i) { - uint d = 64u * i; - float m[12]; - for (uint k = 0u; k < 12u; ++k) m[k] = uintBitsToFloat(load(pc.src0, d + 4u * k)); - uint id_mask = load(pc.src0, d + 48u), contrib = load(pc.src0, d + 52u); - uvec2 blas_va = uvec2(load(pc.src0, d + 56u), load(pc.src0, d + 60u)); - uint o = pc.elements_off + 128u * i; - for (uint k = 0u; k < 12u; ++k) storef(pc.dst, o + 4u * k, m[k]); - store(pc.dst, o + 48u, id_mask); - store(pc.dst, o + 52u, contrib); - vec3 lo = vec3(uintBitsToFloat(0x7f800000u)), hi = -lo; - uint root = INVALID; - if (!is_null(blas_va)) { - uvec2 blas = add64(blas_va, pc.bias); - root = load(blas, 48u); - vec3 blo = vec3(uintBitsToFloat(load(blas, 16u)), uintBitsToFloat(load(blas, 20u)), uintBitsToFloat(load(blas, 24u))); - vec3 bhi = vec3(uintBitsToFloat(load(blas, 28u)), uintBitsToFloat(load(blas, 32u)), uintBitsToFloat(load(blas, 36u))); - if (!box_empty(blo, bhi) && (id_mask >> 24) != 0u) { // mask 0: never hit, no box - for (uint c = 0u; c < 8u; ++c) { - vec3 p = vec3((c & 1u) != 0u ? bhi.x : blo.x, (c & 2u) != 0u ? bhi.y : blo.y, (c & 4u) != 0u ? bhi.z : blo.z); - vec3 w = vec3(m[0] * p.x + m[1] * p.y + m[2] * p.z + m[3], - m[4] * p.x + m[5] * p.y + m[6] * p.z + m[7], - m[8] * p.x + m[9] * p.y + m[10] * p.z + m[11]); - lo = min(lo, w); hi = max(hi, w); - } - } - } - bool identity = m[0] == 1.0 && m[1] == 0.0 && m[2] == 0.0 && m[4] == 0.0 && m[5] == 1.0 && m[6] == 0.0 && - m[8] == 0.0 && m[9] == 0.0 && m[10] == 1.0; - store(pc.dst, o + 56u, (root & ~INST_FLAGS_MASK) | (identity ? INST_IDENTITY_ROTATION : 0u)); - // The record holds the BLAS address in 256-byte units: the application's address, as the game wrote it. - store(pc.dst, o + 60u, (blas_va.x >> 8) | (blas_va.y << 24)); - // world-to-object: the inverse of the affine transform - mat3 a = mat3(m[0], m[4], m[8], m[1], m[5], m[9], m[2], m[6], m[10]); // columns - float det = determinant(a); - mat3 inv = det != 0.0 ? inverse(a) : mat3(0.0); - vec3 t = vec3(m[3], m[7], m[11]); - vec3 it = -(inv * t); - for (uint row = 0u; row < 3u; ++row) { - storef(pc.dst, o + 64u + 16u * row, inv[0][row]); - storef(pc.dst, o + 68u + 16u * row, inv[1][row]); - storef(pc.dst, o + 72u + 16u * row, inv[2][row]); - storef(pc.dst, o + 76u + 16u * row, it[row]); - } - store(pc.dst, o + 112u, i); - store(pc.dst, o + 116u, INVALID); // parent node: MODE_PROPAGATE fills it - store(pc.dst, o + 120u, 0u); - store(pc.dst, o + 124u, 0u); - if (det == 0.0) { lo = vec3(uintBitsToFloat(0x7f800000u)); hi = -lo; } - store_box(i, lo, hi); - grow_centroid_bounds(lo, hi); -} - -// ---- MODE_MORTON ---- -uint spread10(uint x) { - x &= 0x3ffu; - x = (x | (x << 16)) & 0x030000ffu; - x = (x | (x << 8)) & 0x0300f00fu; - x = (x | (x << 4)) & 0x030c30c3u; - x = (x | (x << 2)) & 0x09249249u; - return x; -} -void morton(uint i) { - uint key = 0x3fffffffu; // empty boxes keep the largest key and sort last - vec3 lo, hi; - load_box(i, lo, hi); - if (!box_empty(lo, hi)) { - Words s = at(pc.scratch, 0u); - vec3 cmin = vec3(unordered(s.w[0]), unordered(s.w[1]), unordered(s.w[2])); - vec3 cmax = vec3(unordered(s.w[3]), unordered(s.w[4]), unordered(s.w[5])); - vec3 extent = max(cmax - cmin, vec3(1e-30)); - uvec3 q = uvec3(clamp((((lo + hi) * 0.5) - cmin) / extent, 0.0, 1.0) * 1023.0); - key = spread10(q.x) << 2 | spread10(q.y) << 1 | spread10(q.z); - } - store(pc.scratch, keys_off() + 4u * i, key); - store(pc.scratch, vals_off() + 4u * i, i); -} -// ---- MODE_SMALL_SORT ---- -// 8 KiB, with the radix and kept arrays below about 12.9 KiB: under the 16 KiB every Vulkan device must allow. -shared uint small_keys[SMALL_SORT_MAX]; -shared uint small_vals[SMALL_SORT_MAX]; - -void small_sort(uint t) { - uint n = pc.sort_size, p = 1u; - while (p < n) p <<= 1; - for (uint i = t; i < p; i += 64u) { - small_keys[i] = i < n ? load(pc.scratch, keys_off() + 4u * i) : INVALID; - small_vals[i] = i < n ? load(pc.scratch, vals_off() + 4u * i) : INVALID; - } - barrier(); - for (uint k = 2u; k <= p; k <<= 1) { - for (uint j = k >> 1; j > 0u; j >>= 1) { - for (uint i = t; i < p; i += 64u) { - uint l = i ^ j; - if (l > i) { - uint ki = small_keys[i], kl = small_keys[l], vi = small_vals[i], vl = small_vals[l]; - bool greater = ki > kl || (ki == kl && vi > vl); - if (greater == ((i & k) == 0u)) { - small_keys[i] = kl; small_keys[l] = ki; - small_vals[i] = vl; small_vals[l] = vi; - } - } - } - barrier(); - } - } - for (uint i = t; i < n; i += 64u) { - store(pc.scratch, keys_off() + 4u * i, small_keys[i]); - store(pc.scratch, vals_off() + 4u * i, small_vals[i]); - } -} - -// ---- MODE_RADIX_* ---- -shared uint radix_hist[RADIX_BINS]; -shared uint radix_rank[RADIX_BINS][64]; -shared uint radix_base[RADIX_BINS]; -shared uint radix_part[64]; - -uint src_keys() { return (pc.first & 1u) == 0u ? keys_off() : keys2_off(); } -uint src_vals() { return (pc.first & 1u) == 0u ? vals_off() : vals2_off(); } -uint dst_keys() { return (pc.first & 1u) == 0u ? keys2_off() : keys_off(); } -uint dst_vals() { return (pc.first & 1u) == 0u ? vals2_off() : vals_off(); } -uint digit(uint key) { return (key >> (RADIX_BITS * pc.first)) & (RADIX_BINS - 1u); } - -// Workgroup w counts the digits of its tile; counts[d * tiles + w]. -void radix_count(uint w, uint t) { - if (t < RADIX_BINS) radix_hist[t] = 0u; - barrier(); - uint begin = w * RADIX_TILE, end = min(begin + RADIX_TILE, pc.sort_size); - for (uint i = begin + t; i < end; i += 64u) atomicAdd(radix_hist[digit(load(pc.scratch, src_keys() + 4u * i))], 1u); - barrier(); - if (t < RADIX_BINS) store(pc.scratch, counts_off() + 4u * (t * radix_tiles() + w), radix_hist[t]); -} - -// One workgroup: the exclusive prefix sum of n words at src into dst (not in place: see the SPIRV-Cross note at the -// top), and their total at the scratch byte offset `total` unless it is INVALID. Each thread sums a contiguous -// segment, the 64 segment sums are scanned in shared memory, then each thread writes its segment. -void scan(uint t, uint src, uint dst, uint n, uint total) { - uint per = (n + 63u) / 64u; - uint begin = min(t * per, n), end = min(begin + per, n); - uint sum = 0u; - for (uint i = begin; i < end; ++i) sum += load(pc.scratch, src + 4u * i); - radix_part[t] = sum; - barrier(); - if (t == 0u) { - uint running = 0u; - for (uint k = 0u; k < 64u; ++k) { uint v = radix_part[k]; radix_part[k] = running; running += v; } - if (total != INVALID) store(pc.scratch, total, running); - } - barrier(); - uint running = radix_part[t]; - for (uint i = begin; i < end; ++i) { - uint v = load(pc.scratch, src + 4u * i); - store(pc.scratch, dst + 4u * i, running); - running += v; - } -} - -// Workgroup w moves its tile's keys to their places, in order: the tile is read in chunks of 64, and an element's -// place is its digit's base for this tile plus the number of earlier elements of the tile with the same digit. -void radix_scatter(uint w, uint t) { - if (t < RADIX_BINS) radix_base[t] = load(pc.scratch, offsets_off() + 4u * (t * radix_tiles() + w)); - uint begin = w * RADIX_TILE, end = min(begin + RADIX_TILE, pc.sort_size); - for (uint chunk = begin; chunk < end; chunk += 64u) { - uint i = chunk + t; - bool live = i < end; - uint key = live ? load(pc.scratch, src_keys() + 4u * i) : 0u; - uint val = live ? load(pc.scratch, src_vals() + 4u * i) : 0u; - uint d = digit(key); - for (uint b = 0u; b < RADIX_BINS; ++b) radix_rank[b][t] = (live && b == d) ? 1u : 0u; - barrier(); - // inclusive scan of each digit's flags across the chunk (Hillis-Steele) - for (uint step = 1u; step < 64u; step <<= 1) { - uint add[RADIX_BINS]; - for (uint b = 0u; b < RADIX_BINS; ++b) add[b] = t >= step ? radix_rank[b][t - step] : 0u; - barrier(); - for (uint b = 0u; b < RADIX_BINS; ++b) radix_rank[b][t] += add[b]; - barrier(); - } - if (live) { - uint place = radix_base[d] + radix_rank[d][t] - 1u; - store(pc.scratch, dst_keys() + 4u * place, key); - store(pc.scratch, dst_vals() + 4u * place, val); - } - barrier(); - if (t < RADIX_BINS) radix_base[t] += radix_rank[t][63]; - barrier(); - } -} - -// ---- TRI1 pairing (FLAG_PAIR, bottom level, a full build): among one node's element children, a triangle and a -// later sibling that shares an edge with it, traversed in the opposite direction (the same two vertices, bit for bit), -// from the same geometry and both active, go into the first one's leaf: TRI0 reads slots (0, 1, 2) and TRI1 (1, 3, 2) -// (docs/bvh.md 7a), so the first triangle is rotated to put the shared edge in slots 1 -> 2, the sibling's third -// vertex goes in slot 3, its primitive index in PrimitiveIndex2 and its remap byte in byte 1. The node keeps one child -// per triangle, each with its own box, so the tree is unchanged: the TRI1 child points at the first triangle's leaf -// and the sibling's own leaf is left unreferenced. Both pointers have this node as parent. Pairs never cross nodes, -// so no other thread touches these leaves. The barycentric remap byte of a node type returns D3D12's (b1, b2): bits -// [1:0] and [3:2] are the positions, in the order that node type reads its slots, of the triangle's vertices 1 and 2. -// MODE_NODES records each element's pointer (TRI0, or TRI1 for a paired sibling) for MODE_PROPAGATE. ---- -uint leaf_off(uint e) { return pc.elements_off + 64u * e; } -uvec3 leaf_vertex(uint e, uint k) { - uint o = leaf_off(e) + 12u * k; - return uvec3(load(pc.dst, o), load(pc.dst, o + 4u), load(pc.dst, o + 8u)); -} -void store_vertex(uint e, uint slot, uvec3 v) { - uint o = leaf_off(e) + 12u * slot; - store(pc.dst, o, v.x); store(pc.dst, o + 4u, v.y); store(pc.dst, o + 8u, v.z); -} -// e[c]: the element of child slot c, INVALID when the slot holds an inner node or nothing; kids[c] already holds -// element_ptr(e[c]) for an element. -void pair_children(uint e[4], inout uint kids[4]) { - uvec3 v[4][3]; - uint geo[4]; - bool live[4], used[4]; - for (uint c = 0u; c < 4u; ++c) { - live[c] = false; used[c] = false; geo[c] = 0u; - for (uint k = 0u; k < 3u; ++k) v[c][k] = uvec3(0u); - if (e[c] == INVALID) continue; - geo[c] = load(pc.dst, leaf_off(e[c]) + 48u); - for (uint k = 0u; k < 3u; ++k) v[c][k] = leaf_vertex(e[c], k); - vec3 lo, hi; - load_box(e[c], lo, hi); - live[c] = !box_empty(lo, hi); // inactive (NaN vertex): never paired. Conservative only: its box is empty, - // so a pair with it would never be traversed anyway - } - for (uint c = 0u; c < 4u; ++c) { - if (used[c] || !live[c]) continue; - used[c] = true; - for (uint d = c + 1u; d < 4u; ++d) { - if (used[d] || !live[d] || geo[d] != geo[c]) continue; - uint k = 3u, kd = 3u; - for (uint a = 0u; a < 3u && k == 3u; ++a) { - uvec3 p = v[c][a], q = v[c][(a + 1u) % 3u]; // edge p -> q of the first triangle - if (all(equal(p, q))) continue; - for (uint b = 0u; b < 3u; ++b) { - if (all(equal(v[d][b], q)) && all(equal(v[d][(b + 1u) % 3u], p))) { k = a; kd = b; break; } - } - } - if (k == 3u) continue; - used[d] = true; - // the first triangle as (p0, p1, p2) with the shared edge p1 -> p2; slot 3 is the sibling's third vertex - store_vertex(e[c], 0u, v[c][(k + 2u) % 3u]); - store_vertex(e[c], 1u, v[c][k]); - store_vertex(e[c], 2u, v[c][(k + 1u) % 3u]); - store_vertex(e[c], 3u, v[d][(kd + 2u) % 3u]); - store(pc.dst, leaf_off(e[c]) + 56u, load(pc.dst, leaf_off(e[d]) + 52u)); - // TRI0 reads (p0, p1, p2): vertex m of the first triangle is in slot (m + 4 - k) % 3. TRI1 reads - // (p1, p3, p2): vertex m of the sibling is in slot (m + 5 - kd) % 3. - uint remap0 = (5u - k) % 3u | ((6u - k) % 3u) << 2; - uint remap1 = (6u - kd) % 3u | ((7u - kd) % 3u) << 2; - store(pc.dst, leaf_off(e[c]) + 60u, remap0 | remap1 << 8); - kids[d] = (kids[c] & ~7u) | TRI1; - break; - } - } -} - -// ---- MODE_KARRAS: the binary radix tree over the sorted keys (Karras 2012, "Maximizing Parallelism in the -// Construction of BVHs, Octrees, and k-d Trees"). Inner node i covers a range of sorted elements that starts or ends -// at i; node 0 is the root. Equal keys are told apart by their sorted position, so every key is distinct. ---- -uint sorted_key(int i) { return load(pc.scratch, keys_off() + 4u * uint(i)); } -// Length of the common prefix of the keys at sorted positions i and j, -1 when j is outside. -int delta(int i, int j) { - if (j < 0 || j >= int(pc.elements)) return -1; - uint a = sorted_key(i), b = sorted_key(j); - if (a == b) return 64 - findMSB(uint(i ^ j)); // 32 + the prefix of the positions: longer than any key's - return 31 - findMSB(a ^ b); -} -void karras(int i) { - int d = delta(i, i + 1) - delta(i, i - 1) > 0 ? 1 : -1; - int dmin = delta(i, i - d); - int lmax = 2; - while (delta(i, i + lmax * d) > dmin) lmax <<= 1; - int l = 0; - for (int t = lmax >> 1; t >= 1; t >>= 1) - if (delta(i, i + (l + t) * d) > dmin) l += t; - int j = i + l * d; - int dnode = delta(i, j); - int s = 0, t = l; - do { - t = (t + 1) >> 1; - if (delta(i, i + (s + t) * d) > dnode) s += t; - } while (t > 1); - int split = i + s * d + min(d, 0); - uint left = min(i, j) == split ? (LEAF | uint(split)) : uint(split); - uint right = max(i, j) == split + 1 ? (LEAF | uint(split + 1)) : uint(split + 1); - store(pc.scratch, left_off() + 4u * uint(i), left); - store(pc.scratch, right_off() + 4u * uint(i), right); - if ((left & LEAF) == 0u) store(pc.scratch, bparent_off() + 4u * left, uint(i)); - if ((right & LEAF) == 0u) store(pc.scratch, bparent_off() + 4u * right, uint(i)); - if (i == 0) store(pc.scratch, bparent_off(), INVALID); -} - -// ---- MODE_KEPT, MODE_KEPT_SCAN, MODE_KEPT_INDEX: the inner nodes at an even depth become the box nodes, numbered -// in sorted order. Each takes the children of its children (a sorted element stays as it is), so it has two to four: -// the usual collapse of a binary tree to a 4-wide one, and it needs no pass from the top down. ---- -shared uint kept_count; -shared uint kept_scan[64]; - -// Workgroup w: the flags of its tile and their count. -void kept_flags(uint w, uint t) { - if (t == 0u) kept_count = 0u; - barrier(); - uint begin = w * RADIX_TILE, end = min(begin + RADIX_TILE, inner()); - for (uint i = begin + t; i < end; i += 64u) { - uint depth = 0u, p = load(pc.scratch, bparent_off() + 4u * i); - for (uint guard = 0u; p != INVALID && guard < 128u; ++guard) { // depth <= 30 + 32: the guard never trips - ++depth; - p = load(pc.scratch, bparent_off() + 4u * p); - } - uint kept = (depth & 1u) == 0u ? 1u : 0u; - store(pc.scratch, kept_off() + 4u * i, kept); - if (kept != 0u) atomicAdd(kept_count, 1u); - } - barrier(); - if (t == 0u) store(pc.scratch, ktile_counts_off() + 4u * w, kept_count); -} - -// Workgroup w: each kept node's index, the tile's base plus the kept nodes before it in the tile, read in chunks -// of 64 with an inclusive scan of the flags. -void kept_index(uint w, uint t) { - uint base = load(pc.scratch, ktile_offsets_off() + 4u * w); - uint begin = w * RADIX_TILE, end = min(begin + RADIX_TILE, inner()); - for (uint chunk = begin; chunk < end; chunk += 64u) { - uint i = chunk + t; - uint flag = i < end ? load(pc.scratch, kept_off() + 4u * i) : 0u; - kept_scan[t] = flag; - barrier(); - for (uint step = 1u; step < 64u; step <<= 1) { - uint add = t >= step ? kept_scan[t - step] : 0u; - barrier(); - kept_scan[t] += add; - barrier(); - } - if (flag != 0u) store(pc.scratch, kmap_off() + 4u * i, base + kept_scan[t] - 1u); - base += kept_scan[63]; - barrier(); - } -} - -// ---- MODE_NODES ---- -Words accum(uint node) { return at(pc.scratch, accum_off() + 32u * node); } -void clear_accum(uint node) { - Words a = accum(node); - a.w[0] = 0u; - a.w[1] = INVALID; a.w[2] = INVALID; a.w[3] = INVALID; - a.w[4] = 0u; a.w[5] = 0u; a.w[6] = 0u; -} - -uint child_element(uint c) { return (c & LEAF) != 0u ? load(pc.scratch, vals_off() + 4u * (c & ~LEAF)) : INVALID; } -uint child_ptr(uint c) { - if ((c & LEAF) != 0u) return element_ptr(child_element(c)); - return node_ptr(load(pc.scratch, kmap_off() + 4u * c)); -} -// A box's six floats, or with BOX16 its three words of halves rounded outward, at child slot c of the node record at -// byte o; `box16` is the node's own type (what the structure holds, whatever the flags). -void store_slot_box(uint o, uint c, bool box16, vec3 lo, vec3 hi) { - if (box16) { - store_box16(o + 16u + 12u * c, lo, hi); - return; - } - uint b = o + 16u + 24u * c; - storef(pc.dst, b, lo.x); storef(pc.dst, b + 4u, lo.y); storef(pc.dst, b + 8u, lo.z); - storef(pc.dst, b + 12u, hi.x); storef(pc.dst, b + 16u, hi.y); storef(pc.dst, b + 20u, hi.z); -} - -void build_node(uint i) { - uint kids[4] = uint[4](INVALID, INVALID, INVALID, INVALID); - uint elems[4] = uint[4](INVALID, INVALID, INVALID, INVALID); - uint node = 0u; - if (pc.elements <= 1u) { // one root: the single element, or nothing - if (pc.elements == 1u) { - elems[0] = load(pc.scratch, vals_off()); - kids[0] = element_ptr(elems[0]); - } - } else { - if (load(pc.scratch, kept_off() + 4u * i) == 0u) return; - node = load(pc.scratch, kmap_off() + 4u * i); - if (node >= pc.arg0) return; // the layout's bound (xdxr_build.h) makes this impossible - uint n = 0u; - uint halves[2] = uint[2](load(pc.scratch, left_off() + 4u * i), load(pc.scratch, right_off() + 4u * i)); - for (uint h = 0u; h < 2u; ++h) { - uint c = halves[h]; - uint grand[2] = uint[2](c, c); - uint m = 1u; - if ((c & LEAF) == 0u) { - grand[0] = load(pc.scratch, left_off() + 4u * c); - grand[1] = load(pc.scratch, right_off() + 4u * c); - m = 2u; - } - for (uint g = 0u; g < m; ++g) { - elems[n] = child_element(grand[g]); - kids[n++] = child_ptr(grand[g]); - } - } - if (!is_tlas() && (pc.flags & FLAG_PAIR) != 0u) pair_children(elems, kids); - } - for (uint c = 0u; c < 4u; ++c) - if (elems[c] != INVALID) store(pc.scratch, tptr_off() + 4u * elems[c], kids[c]); - uint me = node_ptr(node); - uint o = pc.nodes_off + node_size() * node; - for (uint c = 0u; c < 4u; ++c) { - store(pc.dst, o + 4u * c, kids[c]); - if (kids[c] != INVALID) { // MODE_PROPAGATE writes its box - store(pc.dst, pc.parents_off + 4u * (ptr_unit(kids[c]) - pc.elements_off / 64u), me); - continue; - } - vec3 empty = vec3(uintBitsToFloat(0x7f800000u)); - store_slot_box(o, c, is_box16(), empty, -empty); // min > max: the box test misses it - } - if (!is_box16()) for (uint k = 0u; k < 4u; ++k) store(pc.dst, o + 112u + 4u * k, 0u); // BOX32 padding - clear_accum(node); -} - -// ---- MODE_PROPAGATE ---- -uint parent_of(uint p) { return load(pc.dst, pc.parents_off + 4u * (ptr_unit(p) - pc.elements_off / 64u)); } -bool ptr_box16(uint p) { return (p & 7u) == BOX16; } -uint node_index(uint p) { return (ptr_unit(p) * 64u - pc.nodes_off) / (ptr_box16(p) ? 64u : 128u); } -void accum_box(uint node, out vec3 lo, out vec3 hi) { - Words a = accum(node); - uint w[6]; - for (uint k = 0u; k < 6u; ++k) w[k] = atomicOr(a.w[1u + k], 0u); // an atomic read: coherent across workgroups - if (w[0] == INVALID) { // no child had a box - lo = vec3(uintBitsToFloat(0x7f800000u)); hi = -lo; - return; - } - lo = vec3(unordered(w[0]), unordered(w[1]), unordered(w[2])); - hi = vec3(unordered(w[3]), unordered(w[4]), unordered(w[5])); -} - -// pc.arg2 = 1: an update, whose leaves are never paired (xdxr_build.h), so an element's pointer is its own. -void propagate(uint e) { - uint me = pc.arg2 == 1u ? element_ptr(e) : load(pc.scratch, tptr_off() + 4u * e); - vec3 lo, hi; - load_box(e, lo, hi); - uint parent = parent_of(me); - if (is_tlas()) store(pc.dst, pc.elements_off + 128u * e + 116u, parent); - for (uint guard = 0u; parent != INVALID && guard < 128u; ++guard) { - uint o = ptr_unit(parent) * 64u, children = 0u; - for (uint c = 0u; c < 4u; ++c) { - uint k = load(pc.dst, o + 4u * c); - if (k == INVALID) continue; - ++children; - if (k == me) store_slot_box(o, c, ptr_box16(parent), lo, hi); - } - uint node = node_index(parent); - Words a = accum(node); - if (!box_empty(lo, hi)) { - atomicMin(a.w[1], ordered(lo.x)); atomicMin(a.w[2], ordered(lo.y)); atomicMin(a.w[3], ordered(lo.z)); - atomicMax(a.w[4], ordered(hi.x)); atomicMax(a.w[5], ordered(hi.y)); atomicMax(a.w[6], ordered(hi.z)); - } - // release: this child's merges before its arrival; acquire: the last arrival sees every sibling's merges - uint arrived = atomicAdd(a.w[0], 1u, gl_ScopeDevice, gl_StorageSemanticsBuffer, gl_SemanticsAcquireRelease); - if (arrived + 1u != children) return; // a sibling is still on its way: it carries on - accum_box(node, lo, hi); - me = parent; - parent = parent_of(me); - } -} - -// ---- MODE_HEADER ---- -void build_header() { - vec3 lo, hi; - accum_box(0u, lo, hi); // the root is node 0 - storef(pc.dst, 16u, lo.x); storef(pc.dst, 20u, lo.y); storef(pc.dst, 24u, lo.z); - storef(pc.dst, 28u, hi.x); storef(pc.dst, 32u, hi.y); storef(pc.dst, 36u, hi.z); - if (pc.arg2 == 1u) return; // an update: the rest is the source's, unchanged - uint nodes = pc.elements <= 1u ? 1u : load(pc.scratch, SCRATCH_NODE_COUNT); - uint end = pc.nodes_off + node_size() * nodes; - if (is_box16()) { // the spare unit after the last node (xdxr_build.h) - for (uint k = 0u; k < 16u; ++k) store(pc.dst, end + 4u * k, 0u); - end += 64u; - } - store(pc.dst, 0u, (is_tlas() ? 0u : FLAG_BOTTOM_LEVEL) | VERSION_2403); - store(pc.dst, 4u, end / 64u - 1u); // totalSizeIn64BNodes does not count the header - store(pc.dst, 8u, 0u); // crc32: not computed for runtime builds - store(pc.dst, 12u, pc.elements); - store(pc.dst, 40u, pc.nodes_off); - store(pc.dst, 44u, 0u); // offsetToPrimRemap - store(pc.dst, 48u, node_ptr(0u)); - store(pc.dst, 52u, pc.elements_off); - store(pc.dst, 56u, pc.parents_off); - store(pc.dst, 60u, 0u); // compressionParams: uncompressed -} - -void main() { - uint i = gl_GlobalInvocationID.x; - // the radix and kept modes use shared memory and barriers: every invocation of a workgroup takes part - if (pc.mode == MODE_RADIX_COUNT) { radix_count(gl_WorkGroupID.x, gl_LocalInvocationID.x); return; } - if (pc.mode == MODE_RADIX_SCAN) { - scan(gl_LocalInvocationID.x, counts_off(), offsets_off(), RADIX_BINS * radix_tiles(), INVALID); - return; - } - if (pc.mode == MODE_RADIX_SCATTER) { radix_scatter(gl_WorkGroupID.x, gl_LocalInvocationID.x); return; } - if (pc.mode == MODE_SMALL_SORT) { small_sort(gl_LocalInvocationID.x); return; } - if (pc.mode == MODE_KEPT) { kept_flags(gl_WorkGroupID.x, gl_LocalInvocationID.x); return; } - if (pc.mode == MODE_KEPT_SCAN) { - scan(gl_LocalInvocationID.x, ktile_counts_off(), ktile_offsets_off(), kept_tiles(), SCRATCH_NODE_COUNT); - return; - } - if (pc.mode == MODE_KEPT_INDEX) { kept_index(gl_WorkGroupID.x, gl_LocalInvocationID.x); return; } - if (pc.mode == MODE_HEADER) { - if (i == 0u) build_header(); - return; - } - if (i >= pc.count) return; - if (pc.mode == MODE_POSTBUILD) { - if (i == 0u) { store(pc.dst, 0u, (load(pc.src0, 4u) + 1u) * 64u); store(pc.dst, 4u, 0u); } - return; - } - if (pc.mode == MODE_COPY_AS) { - if (4u * i < (load(pc.src0, 4u) + 1u) * 64u) store(pc.dst, 4u * i, load(pc.src0, 4u * i)); - return; - } - if (pc.mode == MODE_INIT) { - store(pc.dst, pc.parents_off + 4u * i, INVALID); - if (i < 3u) { store(pc.scratch, 4u * i, INVALID); store(pc.scratch, 12u + 4u * i, 0u); } - } else if (pc.mode == MODE_TRIANGLES) { - build_triangle(i); - } else if (pc.mode == MODE_INSTANCES) { - build_instance(i); - } else if (pc.mode == MODE_MORTON) { - morton(i); - } else if (pc.mode == MODE_KARRAS) { - karras(int(i)); - } else if (pc.mode == MODE_NODES) { - build_node(i); - } else if (pc.mode == MODE_PROPAGATE) { - propagate(i); - } else if (pc.mode == MODE_CLEAR) { - clear_accum(i); - } -} diff --git a/runtime/src/xdxr_build.h b/runtime/src/xdxr_build.h deleted file mode 100644 index e0851098f..000000000 --- a/runtime/src/xdxr_build.h +++ /dev/null @@ -1,402 +0,0 @@ -// XDXR BVH4 acceleration-structure builds on the GPU (xdxr_build.comp): what BuildRaytracingAccelerationStructure -// has to produce for the game's translated traversal shaders, which read the console's node records themselves -// (docs/d3d12_vulkan.md 4.8, docs/bvh.md 7a). tools/xdxr_bvh.py is the CPU reference. -// -// XdxrLayout gives the byte layout of a structure from its element count alone: the same numbers answer -// GetRaytracingAccelerationStructurePrebuildInfo and place the records when the build is recorded. The region -// order (header, parent table, elements, nodes) is the one tools/xdxr_bvh.py writes (an ASSUMPTION there: a shader -// reaches each region through the header). Nodes are BOX32 (128 bytes, float boxes) or, when the layout asks for -// them, BOX16 (64 bytes, half boxes rounded outward): a binary radix tree over the elements' Morton keys, collapsed -// to four children per node by keeping every other level; the root is node 0. Their count depends on the keys, so -// the layout has room for the most there can be and the header counts the ones a build wrote. -// -// XdxrBuilder records the dispatches into a command buffer. Every address is a buffer device address; `bias` is -// added to the BLAS addresses read from instance descs (the distance between the application's GPU virtual -// addresses and device addresses; 0 where they are the same). An INSTANCE record holds its BLAS address in 256-byte -// units in 32 bits, so the application's BLAS addresses must be below 2^40, as console GPU addresses are; where -// device addresses are wider (llvmpipe's are host pointers), the layer must present a narrower window and a bias. -#pragma once - -#include -#include -#include -#include - -#include - -#include "xdxr_build_spv.h" - -namespace leonida { - -struct XdxrLayout { - static constexpr std::uint32_t header_size = 64; - - bool tlas = false; - bool box16 = false; // inner nodes are BOX16 - std::uint32_t node_size = 128; // BOX32 128 bytes, BOX16 64 - std::uint32_t elements = 0; // triangles (BLAS) or instances (TLAS) - std::uint32_t element_size = 64; // a leaf, or a 128-byte instance record - std::uint32_t nodes = 0; // the most BOX32 nodes a build can write - std::uint32_t parents_off = header_size; - std::uint32_t elements_off = 0; - std::uint32_t nodes_off = 0; - std::uint32_t size = 0; // result data size in bytes, a multiple of 64 - std::uint32_t parent_entries = 0; // one per 64-byte unit from elements_off on - std::uint32_t sort_size = 0; // keys the radix sort orders: one per element - static constexpr std::uint32_t radix_tile = 256; // xdxr_build.comp RADIX_TILE - static constexpr std::uint32_t radix_bins = 16; - static constexpr std::uint32_t radix_passes = 8; - static constexpr std::uint32_t small_sort_max = 1024; // xdxr_build.comp SMALL_SORT_MAX: one-workgroup sort - std::uint64_t scratch = 0; // scratch bytes - - // False when the count would overflow the 32-bit offsets of the format. `half_boxes`: BOX16 inner nodes. - bool compute(std::uint32_t count, bool top_level, bool half_boxes = false) { - *this = XdxrLayout{}; - tlas = top_level; - box16 = half_boxes; - node_size = box16 ? 64u : 128u; - elements = count; - element_size = tlas ? 128u : 64u; - // A kept inner node has two children when both of its binary children are elements, which takes two - // elements of its own, and three or four otherwise. With K nodes and a of the first kind, the child slots - // count K - 1 + N >= 2a + 3(K - a), and a <= N / 2, so K <= (3N - 2) / 4. An empty structure or a single - // element keeps one root. - nodes = count <= 1 ? 1u : std::uint32_t((3ull * count - 2) / 4); - // BOX16: one spare 64-byte unit after the last node a build writes (xdxr_build.comp MODE_HEADER zeroes it - // and the header's size counts it). The translator's image_bvh_intersect_ray loads a box node's 112 bytes of - // BOX32 bounds before it knows the type, so without it the last BOX16 node (64 bytes) would be read 48 bytes - // past the structure, a compacted one too. - const std::uint64_t pad = box16 ? 64u : 0u; - const std::uint64_t body_units = - (std::uint64_t(count) * element_size + std::uint64_t(nodes) * node_size + pad) / 64; - const std::uint64_t parent_bytes = (4 * body_units + 63) / 64 * 64; - const std::uint64_t e_off = header_size + parent_bytes; - const std::uint64_t n_off = e_off + std::uint64_t(count) * element_size; - const std::uint64_t end = n_off + std::uint64_t(nodes) * node_size + pad; - // node pointers hold the 64-byte unit index in 29 bits - if (end > (std::uint64_t(1) << 32) - 64 || (end >> 6) >= (std::uint64_t(1) << 29)) return false; - elements_off = std::uint32_t(e_off); - nodes_off = std::uint32_t(n_off); - size = std::uint32_t(end); - parent_entries = std::uint32_t(body_units); - sort_size = count; - // centroid bounds and the node count, keys and element indices twice, digit counts per tile and their prefix - // sums, a box per element, a box accumulator per node, then per inner node of the binary tree its two - // children, its parent, its kept flag and its node index, a kept count per tile with its prefix sum, and - // each element's pointer in the tree - scratch = 64 + 16ull * sort_size + 8ull * radix_bins * tiles() + 24ull * count + 32ull * nodes + - 20ull * inner() + 8ull * kept_tiles() + 4ull * count; - return true; - } - std::uint32_t tiles() const { return (sort_size + radix_tile - 1) / radix_tile; } - std::uint32_t inner() const { return elements > 1 ? elements - 1 : 0; } // binary tree inner nodes - std::uint32_t kept_tiles() const { return (inner() + radix_tile - 1) / radix_tile; } -}; - -// One geometry of a bottom-level build, as D3D12_RAYTRACING_GEOMETRY_TRIANGLES_DESC gives it. -struct XdxrTriangles { - std::uint64_t vertices = 0; // device address - std::uint32_t vertex_stride = 12; - bool xy_only = false; // DXGI_FORMAT_R32G32_FLOAT (z = 0); otherwise R32G32B32_FLOAT - std::uint64_t indices = 0; // device address, 0 = none - std::uint32_t index_type = 0; // 0 none, 1 R16_UINT, 2 R32_UINT - std::uint32_t triangle_count = 0; - std::uint64_t transform = 0; // device address of a 3x4 row-major float matrix, 0 = none - std::uint32_t flags = 0; // D3D12_RAYTRACING_GEOMETRY_FLAGS (bit 0 opaque) -}; - -class XdxrBuilder { -public: - XdxrBuilder(PFN_vkGetDeviceProcAddr get, VkDevice device) : device_(device) { - loaded_ = load(get) && make_pipeline(); - } - ~XdxrBuilder() { - if (pipeline_) vk_.vkDestroyPipeline(device_, pipeline_, nullptr); - if (layout_) vk_.vkDestroyPipelineLayout(device_, layout_, nullptr); - } - XdxrBuilder(const XdxrBuilder&) = delete; - XdxrBuilder& operator=(const XdxrBuilder&) = delete; - - bool loaded() const { return loaded_; } - - // Records a bottom-level build into `dst` (layout.size bytes) using `scratch` (layout.scratch bytes). `layout` - // must come from compute() with the sum of the geometries' triangle counts. - // - // With `update_from` set, an update (D3D12 PERFORM_UPDATE) instead: the structure at `update_from` (the - // destination itself, or another one, which is copied first) was built from the same topology, and is refitted - // to the new positions. Its tree is kept and only its boxes change, which is valid for any motion and costs no - // sort, though a refitted tree traverses more slowly as the geometry moves away from where it was built. - // - // `pair`: sibling triangles that share an edge go into one leaf as TRI0 and TRI1 (xdxr_build.comp MODE_NODES). - // The layout and the tree are the same either way. A refit rewrites every leaf as one triangle, so a structure - // that will be updated must be built without pairing (the layer pairs only builds without ALLOW_UPDATE), and an - // update ignores `pair`. - bool record_blas(VkCommandBuffer cb, const XdxrLayout& layout, const std::vector& geometries, - std::uint64_t dst, std::uint64_t scratch, std::uint64_t update_from = 0, bool pair = false) { - if (!loaded_ || layout.tlas) return false; - Push p = base(layout, dst, scratch); - if (pair && !update_from) p.flags |= flag_pair; - if (update_from) refit_begin(cb, layout, p, update_from); else begin(cb, layout, p); - std::uint32_t first = 0; - for (std::size_t g = 0; g < geometries.size(); ++g) { - const auto& geo = geometries[g]; - if (!geo.triangle_count) continue; - Push t = p; - t.mode = mode_triangles; - t.count = geo.triangle_count; - t.first = first; - t.src0 = split(geo.vertices); - t.src1 = split(geo.indices); - t.src2 = split(geo.transform); - t.arg0 = geo.vertex_stride; - t.arg1 = geo.xy_only ? 1u : 0u; - t.arg2 = geo.index_type; - t.geometry = std::uint32_t(g) << 8 | (geo.flags & 0xffu); - dispatch(cb, t, t.count); - first += geo.triangle_count; - } - if (first != layout.elements) return false; - if (update_from) refit_finish(cb, layout, p); else finish(cb, layout, p); - return true; - } - - // Records a top-level build from `count` D3D12_RAYTRACING_INSTANCE_DESCs at `instances`. - // `update_from`: as for record_blas; the instances may move, and name other BLASes. - bool record_tlas(VkCommandBuffer cb, const XdxrLayout& layout, std::uint64_t instances, std::uint64_t dst, - std::uint64_t scratch, std::uint64_t bias = 0, std::uint64_t update_from = 0) { - if (!loaded_ || !layout.tlas) return false; - Push p = base(layout, dst, scratch); - p.bias = split(bias); - if (update_from) refit_begin(cb, layout, p, update_from); else begin(cb, layout, p); - if (layout.elements) { - Push t = p; - t.mode = mode_instances; - t.count = layout.elements; - t.src0 = split(instances); - dispatch(cb, t, t.count); - } - if (update_from) refit_finish(cb, layout, p); else finish(cb, layout, p); - return true; - } - - // CopyRaytracingAccelerationStructure CLONE or COMPACT: the structure at `src` to `dst`, as many bytes as its - // header says, at most `max_bytes` (the room the destination has). The structures are position-independent. - bool record_copy(VkCommandBuffer cb, std::uint64_t src, std::uint64_t dst, std::uint64_t max_bytes) { - if (!loaded_ || !src || !dst || max_bytes < XdxrLayout::header_size) return false; - if (src == dst) return true; - vk_.vkCmdBindPipeline(cb, VK_PIPELINE_BIND_POINT_COMPUTE, pipeline_); - Push p{}; - p.mode = mode_copy_as; - p.src0 = split(src); - p.dst = split(dst); - p.count = std::uint32_t(std::min(max_bytes, 0xffffffffull) / 4); - dispatch(cb, p, p.count, false); - return true; - } - - // One postbuild value (COMPACTED_SIZE or CURRENT_SIZE, the same for these builds): 8 bytes at `dst` for the - // structure at `src`. A barrier first: a build or copy recorded just before writes the header it reads. - bool record_postbuild(VkCommandBuffer cb, std::uint64_t src, std::uint64_t dst) { - if (!loaded_ || !src || !dst) return false; - VkMemoryBarrier b{VK_STRUCTURE_TYPE_MEMORY_BARRIER, nullptr, VK_ACCESS_SHADER_WRITE_BIT, - VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT}; - vk_.vkCmdPipelineBarrier(cb, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, 0, 1, - &b, 0, nullptr, 0, nullptr); - vk_.vkCmdBindPipeline(cb, VK_PIPELINE_BIND_POINT_COMPUTE, pipeline_); - Push p{}; - p.mode = mode_postbuild; - p.src0 = split(src); - p.dst = split(dst); - p.count = 1; - dispatch(cb, p, 1, false); - return true; - } - -private: - enum : std::uint32_t { - mode_init = 0, mode_triangles = 1, mode_instances = 2, mode_morton = 3, mode_karras = 4, mode_nodes = 5, - mode_header = 6, mode_radix_count = 7, mode_radix_scan = 8, mode_radix_scatter = 9, mode_small_sort = 10, - mode_copy_as = 12, mode_postbuild = 13, mode_kept = 14, mode_kept_scan = 15, - mode_kept_index = 16, mode_propagate = 17, mode_clear = 18 - }; - struct Addr { std::uint32_t lo = 0, hi = 0; }; - struct Push { // xdxr_build.comp `Push`, std430 push-constant layout - Addr dst, scratch, src0, src1, src2, bias; - std::uint32_t mode = 0, count = 0, first = 0, arg0 = 0, arg1 = 0, arg2 = 0, geometry = 0, elements = 0, - sort_size = 0, elements_off = 0, nodes_off = 0, parents_off = 0, total_size = 0, flags = 0; - }; - enum : std::uint32_t { flag_tlas = 1, flag_box16 = 2, flag_pair = 4 }; // xdxr_build.comp FLAG_* - static_assert(sizeof(Push) == 104, "push constants must match xdxr_build.comp"); - - static Addr split(std::uint64_t a) { return {std::uint32_t(a), std::uint32_t(a >> 32)}; } - - static Push base(const XdxrLayout& l, std::uint64_t dst, std::uint64_t scratch) { - Push p{}; - p.dst = split(dst); - p.scratch = split(scratch); - p.elements = l.elements; - p.sort_size = l.sort_size; - p.elements_off = l.elements_off; - p.nodes_off = l.nodes_off; - p.parents_off = l.parents_off; - p.total_size = l.size; - p.flags = (l.tlas ? flag_tlas : 0u) | (l.box16 ? flag_box16 : 0u); - p.arg0 = l.nodes; // where the scratch arrays after the accumulators start - return p; - } - - void begin(VkCommandBuffer cb, const XdxrLayout& l, const Push& p) { - vk_.vkCmdBindPipeline(cb, VK_PIPELINE_BIND_POINT_COMPUTE, pipeline_); - Push init = p; - init.mode = mode_init; - init.count = l.parent_entries > 16 ? l.parent_entries : 16; // the parent table has at least 16 entries - dispatch(cb, init, init.count); - } - - // An update: the source's tree is copied unless it is the destination, as many bytes as its header says (a - // compacted source is shorter than the layout). Its parent table stays as it is, so there is no MODE_INIT. - void refit_begin(VkCommandBuffer cb, const XdxrLayout& l, const Push& p, std::uint64_t source) { - vk_.vkCmdBindPipeline(cb, VK_PIPELINE_BIND_POINT_COMPUTE, pipeline_); - const std::uint64_t dst = std::uint64_t(p.dst.hi) << 32 | p.dst.lo; - if (source == dst) return; - Push c = p; - c.mode = mode_copy_as; - c.count = l.size / 4; - c.src0 = split(source); - dispatch(cb, c, c.count); - } - - // Boxes bottom-up through the existing nodes, then the header (its bounds change; nothing else does). - void refit_finish(VkCommandBuffer cb, const XdxrLayout& l, const Push& p) { - Push c = p; - c.mode = mode_clear; - c.count = l.nodes; - dispatch(cb, c, c.count); - propagate(cb, l, p, true); - Push h = p; - h.mode = mode_header; - h.count = 1; - h.arg2 = 1; // an update: the bounds only - dispatch(cb, h, 1, false); - } - - // `update`: the elements' pointers are their own (an update never pairs), not the ones MODE_NODES recorded. - void propagate(VkCommandBuffer cb, const XdxrLayout& l, const Push& p, bool update = false) { - if (!l.elements) return; - Push b = p; - b.mode = mode_propagate; - b.count = l.elements; - b.arg2 = update ? 1u : 0u; - dispatch(cb, b, b.count); - } - - void finish(VkCommandBuffer cb, const XdxrLayout& l, const Push& p) { - Push m = p; - m.mode = mode_morton; - m.count = l.sort_size; - dispatch(cb, m, m.count); - // stable LSD radix sort, 4 bits a pass; an even pass count leaves the result where the keys started - static_assert(XdxrLayout::radix_passes % 2 == 0, "the sorted keys must end in the first buffer"); - if (l.sort_size > 1 && l.sort_size <= XdxrLayout::small_sort_max) { - Push s = p; - s.mode = mode_small_sort; - dispatch(cb, s, 64); // one workgroup, shared memory - } else if (l.sort_size > 1) { - for (std::uint32_t pass = 0; pass < XdxrLayout::radix_passes; ++pass) { - Push s = p; - s.first = pass; - s.mode = mode_radix_count; - dispatch(cb, s, 64 * l.tiles()); // one workgroup of 64 per tile - s.mode = mode_radix_scan; - dispatch(cb, s, 64); // one workgroup - s.mode = mode_radix_scatter; - dispatch(cb, s, 64 * l.tiles()); - } - } - // the binary radix tree, which of its inner nodes become BOX32 nodes, and their indices - if (l.inner()) { - Push t = p; - t.mode = mode_karras; - t.count = l.inner(); - dispatch(cb, t, t.count); - t.mode = mode_kept; - dispatch(cb, t, 64 * l.kept_tiles()); // one workgroup of 64 per tile - t.mode = mode_kept_scan; - dispatch(cb, t, 64); // one workgroup - t.mode = mode_kept_index; - dispatch(cb, t, 64 * l.kept_tiles()); - } - Push n = p; - n.mode = mode_nodes; - n.count = l.inner() ? l.inner() : 1; // one root of its own for zero or one element - dispatch(cb, n, n.count); - propagate(cb, l, p); - Push h = p; - h.mode = mode_header; - h.count = 1; - dispatch(cb, h, 1, false); - } - - // One dispatch, then a compute-to-compute dependency so the next step sees its writes. The last step leaves the - // dependency on its results to the caller's barrier (the application's UAV or AS barrier). - void dispatch(VkCommandBuffer cb, const Push& p, std::uint32_t threads, bool barrier = true) { - vk_.vkCmdPushConstants(cb, layout_, VK_SHADER_STAGE_COMPUTE_BIT, 0, sizeof(Push), &p); - vk_.vkCmdDispatch(cb, (threads + 63) / 64, 1, 1); - if (!barrier) return; - VkMemoryBarrier b{VK_STRUCTURE_TYPE_MEMORY_BARRIER}; - b.srcAccessMask = VK_ACCESS_SHADER_WRITE_BIT; - b.dstAccessMask = VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT; - vk_.vkCmdPipelineBarrier(cb, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, 0, 1, - &b, 0, nullptr, 0, nullptr); - } - - struct Functions { -#define LEONIDA_XDXR_FUNCTIONS(X) \ - X(vkCreateShaderModule) X(vkDestroyShaderModule) X(vkCreatePipelineLayout) X(vkDestroyPipelineLayout) \ - X(vkCreateComputePipelines) X(vkDestroyPipeline) X(vkCmdBindPipeline) X(vkCmdPushConstants) \ - X(vkCmdDispatch) X(vkCmdPipelineBarrier) -#define LEONIDA_XDXR_MEMBER(name) PFN_##name name = nullptr; - LEONIDA_XDXR_FUNCTIONS(LEONIDA_XDXR_MEMBER) -#undef LEONIDA_XDXR_MEMBER - }; - - bool load(PFN_vkGetDeviceProcAddr get) { - if (!get || !device_) return false; - bool all = true; -#define LEONIDA_XDXR_LOAD(name) \ - vk_.name = reinterpret_cast(get(device_, #name)); \ - all = all && vk_.name != nullptr; - LEONIDA_XDXR_FUNCTIONS(LEONIDA_XDXR_LOAD) -#undef LEONIDA_XDXR_LOAD -#undef LEONIDA_XDXR_FUNCTIONS - return all; - } - - bool make_pipeline() { - const VkPushConstantRange push{VK_SHADER_STAGE_COMPUTE_BIT, 0, sizeof(Push)}; - VkPipelineLayoutCreateInfo layout_info{VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO}; - layout_info.pushConstantRangeCount = 1; - layout_info.pPushConstantRanges = &push; - if (vk_.vkCreatePipelineLayout(device_, &layout_info, nullptr, &layout_) != VK_SUCCESS) return false; - VkShaderModuleCreateInfo module_info{VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO}; - module_info.codeSize = sizeof(xdxr_build_spirv); - module_info.pCode = xdxr_build_spirv; - VkShaderModule module = VK_NULL_HANDLE; - if (vk_.vkCreateShaderModule(device_, &module_info, nullptr, &module) != VK_SUCCESS) return false; - VkComputePipelineCreateInfo info{VK_STRUCTURE_TYPE_COMPUTE_PIPELINE_CREATE_INFO}; - info.stage = {VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO, nullptr, 0, VK_SHADER_STAGE_COMPUTE_BIT, - module, "main", nullptr}; - info.layout = layout_; - const bool ok = vk_.vkCreateComputePipelines(device_, VK_NULL_HANDLE, 1, &info, nullptr, &pipeline_) == VK_SUCCESS; - vk_.vkDestroyShaderModule(device_, module, nullptr); - return ok; - } - - VkDevice device_ = VK_NULL_HANDLE; - Functions vk_; - VkPipelineLayout layout_ = VK_NULL_HANDLE; - VkPipeline pipeline_ = VK_NULL_HANDLE; - bool loaded_ = false; -}; - -} // namespace leonida diff --git a/runtime/src/xdxr_build.inc b/runtime/src/xdxr_build.inc deleted file mode 100644 index f6b8f949c..000000000 --- a/runtime/src/xdxr_build.inc +++ /dev/null @@ -1,7580 +0,0 @@ -{0x07230203,0x00010500,0x000d000b,0x00005ce9, -0x00000000,0x00020011,0x00000001,0x00020011, -0x000014e3,0x0006000b,0x00000001,0x4c534c47, -0x6474732e,0x3035342e,0x00000000,0x0003000e, -0x000014e4,0x00000001,0x0011000f,0x00000005, -0x00000004,0x6e69616d,0x00000000,0x00000180, -0x00000825,0x0000083a,0x00000919,0x00000980, -0x000009d5,0x00000a2e,0x00000d70,0x00000e00, -0x000011db,0x000011e4,0x000011e5,0x00060010, -0x00000004,0x00000011,0x00000040,0x00000001, -0x00000001,0x00040047,0x00000015,0x00000006, -0x00000004,0x00030047,0x00000016,0x00000002, -0x00050048,0x00000016,0x00000000,0x00000023, -0x00000000,0x00030047,0x0000017e,0x00000002, -0x00050048,0x0000017e,0x00000000,0x00000023, -0x00000000,0x00050048,0x0000017e,0x00000001, -0x00000023,0x00000008,0x00050048,0x0000017e, -0x00000002,0x00000023,0x00000010,0x00050048, -0x0000017e,0x00000003,0x00000023,0x00000018, -0x00050048,0x0000017e,0x00000004,0x00000023, -0x00000020,0x00050048,0x0000017e,0x00000005, -0x00000023,0x00000028,0x00050048,0x0000017e, -0x00000006,0x00000023,0x00000030,0x00050048, -0x0000017e,0x00000007,0x00000023,0x00000034, -0x00050048,0x0000017e,0x00000008,0x00000023, -0x00000038,0x00050048,0x0000017e,0x00000009, -0x00000023,0x0000003c,0x00050048,0x0000017e, -0x0000000a,0x00000023,0x00000040,0x00050048, -0x0000017e,0x0000000b,0x00000023,0x00000044, -0x00050048,0x0000017e,0x0000000c,0x00000023, -0x00000048,0x00050048,0x0000017e,0x0000000d, -0x00000023,0x0000004c,0x00050048,0x0000017e, -0x0000000e,0x00000023,0x00000050,0x00050048, -0x0000017e,0x0000000f,0x00000023,0x00000054, -0x00050048,0x0000017e,0x00000010,0x00000023, -0x00000058,0x00050048,0x0000017e,0x00000011, -0x00000023,0x0000005c,0x00050048,0x0000017e, -0x00000012,0x00000023,0x00000060,0x00050048, -0x0000017e,0x00000013,0x00000023,0x00000064, -0x00040047,0x000011db,0x0000000b,0x0000001c, -0x00040047,0x000011e4,0x0000000b,0x0000001a, -0x00040047,0x000011e5,0x0000000b,0x0000001b, -0x00040047,0x000012fc,0x0000000b,0x00000019, -0x00020013,0x00000002,0x00030021,0x00000003, -0x00000002,0x00040015,0x00000006,0x00000020, -0x00000000,0x00040017,0x00000007,0x00000006, -0x00000002,0x00040020,0x00000009,0x00000007, -0x00000006,0x00030027,0x00000014,0x000014e5, -0x0003001d,0x00000015,0x00000006,0x0003001e, -0x00000016,0x00000015,0x00040020,0x00000014, -0x000014e5,0x00000016,0x00030016,0x00000027, -0x00000020,0x00040020,0x00000028,0x00000007, -0x00000027,0x00020014,0x0000002f,0x00040017, -0x00000063,0x00000027,0x00000003,0x00040020, -0x00000064,0x00000007,0x00000063,0x00040020, -0x0000008d,0x00000007,0x0000002f,0x00040017, -0x000000d2,0x00000006,0x00000003,0x00040020, -0x000000d8,0x00000007,0x000000d2,0x0004002b, -0x00000006,0x000000df,0x00000004,0x0004001c, -0x000000e0,0x00000006,0x000000df,0x00040020, -0x000000e1,0x00000007,0x000000e0,0x00040015, -0x000000e7,0x00000020,0x00000001,0x0004002b, -0x00000006,0x0000012b,0x00000000,0x0004001e, -0x00000130,0x00000006,0x00000006,0x0004002b, -0x00000006,0x00000135,0x00000001,0x0004002b, -0x000000e7,0x0000015e,0x00000000,0x00040020, -0x0000015f,0x000014e5,0x00000006,0x0016001e, -0x0000017e,0x00000007,0x00000007,0x00000007, -0x00000007,0x00000007,0x00000007,0x00000006, -0x00000006,0x00000006,0x00000006,0x00000006, -0x00000006,0x00000006,0x00000006,0x00000006, -0x00000006,0x00000006,0x00000006,0x00000006, -0x00000006,0x00040020,0x0000017f,0x00000009, -0x0000017e,0x0004003b,0x0000017f,0x00000180, -0x00000009,0x0004002b,0x000000e7,0x00000181, -0x0000000e,0x00040020,0x00000182,0x00000009, -0x00000006,0x0004002b,0x00000006,0x00000185, -0x00000100,0x0004002b,0x00000006,0x0000018b, -0x00000040,0x0004002b,0x00000006,0x00000194, -0x00000008,0x0004002b,0x00000006,0x0000019b, -0x0000000c,0x0004002b,0x00000006,0x000001a2, -0x00000010,0x0004002b,0x00000006,0x000001b6, -0x00000018,0x0004002b,0x000000e7,0x000001b7, -0x0000000d,0x0004002b,0x00000006,0x000001cc, -0x00000020,0x0004002b,0x000000e7,0x000001cd, -0x00000009,0x0004002b,0x00000006,0x00000208, -0x80000000,0x0004002b,0x00000006,0x0000021d, -0x7fffffff,0x0004002b,0x000000e7,0x0000022b, -0x00000001,0x00040020,0x0000022d,0x00000009, -0x00000007,0x0004002b,0x00000006,0x00000247, -0x00000002,0x0004002b,0x00000006,0x00000260, -0x00000014,0x0004002b,0x00000027,0x000002c4, -0x3f000000,0x0004002b,0x000000e7,0x000002dc, -0x00000002,0x0004002b,0x000000e7,0x000002e4, -0x00000003,0x0004002b,0x000000e7,0x000002ec, -0x00000004,0x0004002b,0x000000e7,0x000002f4, -0x00000005,0x0004002b,0x000000e7,0x000002fb, -0x00000013,0x0004002b,0x00000006,0x00000309, -0x00000080,0x0004002b,0x000000e7,0x00000311, -0x0000000f,0x0004002b,0x000000e7,0x00000318, -0x00000006,0x0004002b,0x00000006,0x0000031c, -0x00000006,0x0004002b,0x000000e7,0x00000321, -0x00000010,0x0004002b,0x00000006,0x0000032b, -0x00000005,0x0004002b,0x00000006,0x0000033a, -0x00008000,0x0004002b,0x00000006,0x00000345, -0x7f800000,0x0004002b,0x00000006,0x0000034a, -0x00007e00,0x0004002b,0x000000e7,0x00000355, -0x00000017,0x0004002b,0x000000e7,0x00000358, -0x0000007f,0x0004002b,0x00000006,0x00000360, -0x00007c00,0x0004002b,0x00000006,0x00000361, -0x00007bff,0x0004002b,0x000000e7,0x00000366, -0xfffffff2,0x0004002b,0x00000006,0x0000036f, -0x00000400,0x0004002b,0x00000006,0x00000377, -0x007fffff,0x0004002b,0x000000e7,0x0000037d, -0x0000000a,0x0004002b,0x00000006,0x00000386, -0x00001fff,0x0003002a,0x0000002f,0x00000393, -0x00030029,0x0000002f,0x000003ae,0x0004002b, -0x00000027,0x000003ed,0x00000000,0x0004002b, -0x000000e7,0x000003fb,0x0000000b,0x0004002b, -0x00000006,0x00000423,0x0000ffff,0x0004002b, -0x00000006,0x00000437,0x00000003,0x00040017, -0x0000043c,0x00000027,0x00000004,0x0004001c, -0x00000476,0x00000063,0x00000437,0x00040020, -0x00000477,0x00000007,0x00000476,0x0004002b, -0x000000e7,0x00000488,0x00000008,0x0004002b, -0x00000006,0x000004c7,0x00000024,0x0004002b, -0x00000006,0x000004d2,0x00000028,0x0004002b, -0x00000006,0x000004dd,0x0000002c,0x0004002b, -0x00000006,0x000004e8,0x00000030,0x0004002b, -0x000000e7,0x000004ea,0x0000000c,0x0004002b, -0x00000006,0x000004f4,0x00000034,0x0004002b, -0x00000006,0x000004fe,0x00000038,0x0004002b, -0x00000006,0x00000500,0xffffffff,0x0004002b, -0x00000006,0x00000508,0x0000003c,0x0004002b, -0x00000006,0x0000050a,0x00000009,0x00040017, -0x00000514,0x0000002f,0x00000003,0x0004002b, -0x00000027,0x0000053c,0x7f800000,0x0006002c, -0x00000063,0x0000053d,0x0000053c,0x0000053c, -0x0000053c,0x0004001c,0x00000557,0x00000027, -0x0000019b,0x00040020,0x00000558,0x00000007, -0x00000557,0x0004002b,0x00000006,0x000005df, -0x0000001c,0x0004002b,0x000000e7,0x000005f9, -0x00000018,0x0004002b,0x000000e7,0x00000653, -0x00000007,0x0004002b,0x00000027,0x00000677, -0x3f800000,0x0004002b,0x00000006,0x000006ac, -0x3fffffff,0x00040018,0x000006c6,0x00000063, -0x00000003,0x00040020,0x000006c7,0x00000007, -0x000006c6,0x0006002c,0x00000063,0x000006eb, -0x000003ed,0x000003ed,0x000003ed,0x0006002c, -0x000006c6,0x000006ec,0x000006eb,0x000006eb, -0x000006eb,0x0004002b,0x00000006,0x00000712, -0x00000044,0x0004002b,0x00000006,0x00000721, -0x00000048,0x0004002b,0x00000006,0x00000730, -0x0000004c,0x0004002b,0x00000006,0x00000741, -0x00000070,0x0004002b,0x00000006,0x0000074b, -0x00000074,0x0004002b,0x00000006,0x00000754, -0x00000078,0x0004002b,0x00000006,0x0000075d, -0x0000007c,0x0004002b,0x00000006,0x00000777, -0x000003ff,0x0004002b,0x00000006,0x0000077e, -0x030000ff,0x0004002b,0x00000006,0x00000784, -0x0300f00f,0x0004002b,0x00000006,0x0000078a, -0x030c30c3,0x0004002b,0x00000006,0x00000790, -0x09249249,0x0004002b,0x00000027,0x000007d3, -0x0da24260,0x0006002c,0x00000063,0x000007d4, -0x000007d3,0x000007d3,0x000007d3,0x0004002b, -0x00000027,0x000007e2,0x447fc000,0x0004001c, -0x00000823,0x00000006,0x0000036f,0x00040020, -0x00000824,0x00000004,0x00000823,0x0004003b, -0x00000824,0x00000825,0x00000004,0x00040020, -0x00000838,0x00000004,0x00000006,0x0004003b, -0x00000824,0x0000083a,0x00000004,0x0004002b, -0x00000006,0x00000850,0x00000108,0x0004002b, -0x00000006,0x0000090f,0x0000000f,0x0004001c, -0x00000917,0x00000006,0x000001a2,0x00040020, -0x00000918,0x00000004,0x00000917,0x0004003b, -0x00000918,0x00000919,0x00000004,0x0004002b, -0x00000006,0x00000957,0x0000003f,0x0004001c, -0x0000097e,0x00000006,0x0000018b,0x00040020, -0x0000097f,0x00000004,0x0000097e,0x0004003b, -0x0000097f,0x00000980,0x00000004,0x0004003b, -0x00000918,0x000009d5,0x00000004,0x0004001c, -0x00000a2c,0x0000097e,0x000001a2,0x00040020, -0x00000a2d,0x00000004,0x00000a2c,0x0004003b, -0x00000a2d,0x00000a2e,0x00000004,0x00040020, -0x00000a4a,0x00000007,0x00000917,0x0004002b, -0x000000e7,0x00000a9c,0x0000003f,0x0004001c, -0x00000af6,0x0000002f,0x000000df,0x00040020, -0x00000af7,0x00000007,0x00000af6,0x0004001c, -0x00000b09,0x000000d2,0x00000437,0x0004001c, -0x00000b0a,0x00000b09,0x000000df,0x00040020, -0x00000b0b,0x00000007,0x00000b0a,0x0006002c, -0x000000d2,0x00000b0f,0x0000012b,0x0000012b, -0x0000012b,0x0004002b,0x00000006,0x00000c2c, -0x00000007,0x0004002b,0x00000006,0x00000c46, -0xfffffff8,0x0004002b,0x000000e7,0x00000c68, -0xffffffff,0x0004002b,0x000000e7,0x00000c77, -0x00000040,0x0004002b,0x000000e7,0x00000c7f, -0x0000001f,0x0004003b,0x00000838,0x00000d70, -0x00000004,0x0004003b,0x0000097f,0x00000e00, -0x00000004,0x0007002c,0x000000e0,0x00000ed6, -0x00000500,0x00000500,0x00000500,0x00000500, -0x0004001c,0x00000f0e,0x00000006,0x00000247, -0x00040020,0x00000f0f,0x00000007,0x00000f0e, -0x0004002b,0x000000e7,0x00000fbf,0x00000011, -0x0004001c,0x00001031,0x00000006,0x0000031c, -0x00040020,0x00001032,0x00000007,0x00001031, -0x00040020,0x000011da,0x00000001,0x000000d2, -0x0004003b,0x000011da,0x000011db,0x00000001, -0x00040020,0x000011dc,0x00000001,0x00000006, -0x0004003b,0x000011da,0x000011e4,0x00000001, -0x0004003b,0x000011da,0x000011e5,0x00000001, -0x0004002b,0x00000006,0x0000120f,0x0000000a, -0x0004002b,0x00000006,0x0000121a,0x0000000e, -0x0004002b,0x00000006,0x00001258,0x0000000d, -0x0004002b,0x00000006,0x000012eb,0x00000011, -0x0004002b,0x00000006,0x000012f5,0x00000012, -0x0006002c,0x000000d2,0x000012fc,0x0000018b, -0x00000135,0x00000135,0x0006002c,0x00000063, -0x00005cc0,0x00000677,0x00000677,0x00000677, -0x0004002b,0x00000027,0x00005cc1,0xff800000, -0x0006002c,0x00000063,0x00005cc2,0x00005cc1, -0x00005cc1,0x00005cc1,0x0004002b,0x00000006, -0x00005cc3,0x000000ff,0x0004002b,0x000000e7, -0x00005cc4,0xffffff90,0x0004002b,0x00000006, -0x00005cc5,0xff800000,0x0004002b,0x00000006, -0x00005cd3,0x80000006,0x0004002b,0x00000006, -0x00005cd7,0x7bff7bff,0x0004002b,0x00000006, -0x00005cd9,0xfbff7bff,0x0004002b,0x00000006, -0x00005cda,0xfbfffbff,0x00050036,0x00000002, -0x00000004,0x00000000,0x00000003,0x000200f8, -0x00000005,0x0004003b,0x00001032,0x00005579, -0x00000007,0x0004003b,0x00000af7,0x000041c5, -0x00000007,0x0004003b,0x00000af7,0x000041c6, -0x00000007,0x0004003b,0x000000e1,0x000041c7, -0x00000007,0x0004003b,0x00000b0b,0x000041c9, -0x00000007,0x0004003b,0x000000e1,0x00003c67, -0x00000007,0x0004003b,0x000000e1,0x00003c68, -0x00000007,0x0004003b,0x00000f0f,0x00003c72, -0x00000007,0x0004003b,0x00000f0f,0x00003c79, -0x00000007,0x0004003b,0x000000e1,0x00003c82, -0x00000007,0x0004003b,0x000000e1,0x00003c83, -0x00000007,0x0004003b,0x00000558,0x00002b2c, -0x00000007,0x0004003b,0x000006c7,0x00002b6d, -0x00000007,0x0004003b,0x00000064,0x00002b70, -0x00000007,0x0004003b,0x00000064,0x000026bf, -0x00000007,0x0004003b,0x00000477,0x000024d6, -0x00000007,0x0004003b,0x00001032,0x0000202d, -0x00000007,0x0004003b,0x00000a4a,0x00001508, -0x00000007,0x000300f7,0x000012fe,0x00000000, -0x000300fb,0x0000012b,0x000012ff,0x000200f8, -0x000012ff,0x00050041,0x000011dc,0x000011dd, -0x000011db,0x0000012b,0x0004003d,0x00000006, -0x000011de,0x000011dd,0x00050041,0x00000182, -0x000011df,0x00000180,0x00000318,0x0004003d, -0x00000006,0x000011e0,0x000011df,0x000500aa, -0x0000002f,0x000011e1,0x000011e0,0x00000c2c, -0x000300f7,0x000011e3,0x00000000,0x000400fa, -0x000011e1,0x000011e2,0x000011e3,0x000200f8, -0x000011e2,0x00050041,0x000011dc,0x000011e7, -0x000011e4,0x0000012b,0x0004003d,0x00000006, -0x000011e8,0x000011e7,0x00050041,0x000011dc, -0x000011ea,0x000011e5,0x0000012b,0x0004003d, -0x00000006,0x000011eb,0x000011ea,0x000500b0, -0x0000002f,0x00001339,0x000011eb,0x000001a2, -0x000300f7,0x0000133d,0x00000000,0x000400fa, -0x00001339,0x0000133a,0x0000133d,0x000200f8, -0x0000133a,0x00050041,0x00000838,0x0000133c, -0x00000919,0x000011eb,0x0003003e,0x0000133c, -0x0000012b,0x000200f9,0x0000133d,0x000200f8, -0x0000133d,0x000400e0,0x00000247,0x00000247, -0x00000850,0x00050084,0x00000006,0x0000133f, -0x000011e8,0x00000185,0x00050080,0x00000006, -0x00001341,0x0000133f,0x00000185,0x00050041, -0x00000182,0x00001342,0x00000180,0x00000181, -0x0004003d,0x00000006,0x00001343,0x00001342, -0x0007000c,0x00000006,0x00001344,0x00000001, -0x00000026,0x00001341,0x00001343,0x00050080, -0x00000006,0x00001347,0x0000133f,0x000011eb, -0x000200f9,0x00001348,0x000200f8,0x00001348, -0x000700f5,0x00000006,0x00005ba2,0x00001347, -0x0000133d,0x0000135a,0x00001358,0x000500b0, -0x0000002f,0x0000134c,0x00005ba2,0x00001344, -0x000400f6,0x0000135b,0x00001358,0x00000000, -0x000400fa,0x0000134c,0x0000134d,0x0000135b, -0x000200f8,0x0000134d,0x00050041,0x00000182, -0x00001371,0x00000180,0x00000488,0x0004003d, -0x00000006,0x00001372,0x00001371,0x000500c7, -0x00000006,0x00001373,0x00001372,0x00000135, -0x000500aa,0x0000002f,0x00001374,0x00001373, -0x0000012b,0x000300f7,0x00001379,0x00000000, -0x000400fa,0x00001374,0x00001375,0x00001377, -0x000200f8,0x00001377,0x00050084,0x00000006, -0x00001381,0x00000194,0x00001343,0x00050080, -0x00000006,0x00001382,0x0000018b,0x00001381, -0x000200f9,0x00001379,0x000200f8,0x00001375, -0x000200f9,0x00001379,0x000200f8,0x00001379, -0x000700f5,0x00000006,0x00005ba3,0x0000018b, -0x00001375,0x00001382,0x00001377,0x00050084, -0x00000006,0x00001350,0x000000df,0x00005ba2, -0x00050080,0x00000006,0x00001351,0x00005ba3, -0x00001350,0x00050041,0x0000022d,0x00001352, -0x00000180,0x0000022b,0x0004003d,0x00000007, -0x00001353,0x00001352,0x00050051,0x00000006, -0x00001399,0x00001353,0x00000000,0x00050095, -0x00000130,0x0000139b,0x00001399,0x00001351, -0x00050051,0x00000006,0x0000139c,0x0000139b, -0x00000001,0x00050051,0x00000006,0x0000139d, -0x0000139b,0x00000000,0x00050051,0x00000006, -0x000013a0,0x00001353,0x00000001,0x00050080, -0x00000006,0x000013a2,0x000013a0,0x0000139c, -0x00050050,0x00000007,0x000013a3,0x0000139d, -0x000013a2,0x0004007c,0x00000014,0x00001393, -0x000013a3,0x00060041,0x0000015f,0x0000138a, -0x00001393,0x0000015e,0x0000015e,0x0006003d, -0x00000006,0x0000138b,0x0000138a,0x00000002, -0x00000004,0x00050084,0x00000006,0x000013a9, -0x000000df,0x00001372,0x000500c2,0x00000006, -0x000013aa,0x0000138b,0x000013a9,0x000500c7, -0x00000006,0x000013ab,0x000013aa,0x0000090f, -0x00050041,0x00000838,0x00001356,0x00000919, -0x000013ab,0x000700ea,0x00000006,0x00001357, -0x00001356,0x00000135,0x0000012b,0x00000135, -0x000200f9,0x00001358,0x000200f8,0x00001358, -0x00050080,0x00000006,0x0000135a,0x00005ba2, -0x0000018b,0x000200f9,0x00001348,0x000200f8, -0x0000135b,0x000400e0,0x00000247,0x00000247, -0x00000850,0x000300f7,0x0000136d,0x00000000, -0x000400fa,0x00001339,0x0000135e,0x0000136d, -0x000200f8,0x0000135e,0x00050084,0x00000006, -0x000013b0,0x000001a2,0x00001343,0x00050080, -0x00000006,0x000013b1,0x0000018b,0x000013b0, -0x00050080,0x00000006,0x000013b7,0x00001343, -0x00005cc3,0x00050086,0x00000006,0x000013b8, -0x000013b7,0x00000185,0x00050084,0x00000006, -0x00001362,0x000011eb,0x000013b8,0x00050080, -0x00000006,0x00001364,0x00001362,0x000011e8, -0x00050084,0x00000006,0x00001365,0x000000df, -0x00001364,0x00050080,0x00000006,0x00001366, -0x000013b1,0x00001365,0x00050041,0x0000022d, -0x00001368,0x00000180,0x0000022b,0x0004003d, -0x00000007,0x00001369,0x00001368,0x00050041, -0x00000838,0x0000136a,0x00000919,0x000011eb, -0x0004003d,0x00000006,0x0000136b,0x0000136a, -0x00050051,0x00000006,0x000013ce,0x00001369, -0x00000000,0x00050095,0x00000130,0x000013d0, -0x000013ce,0x00001366,0x00050051,0x00000006, -0x000013d1,0x000013d0,0x00000001,0x00050051, -0x00000006,0x000013d2,0x000013d0,0x00000000, -0x00050051,0x00000006,0x000013d5,0x00001369, -0x00000001,0x00050080,0x00000006,0x000013d7, -0x000013d5,0x000013d1,0x00050050,0x00000007, -0x000013d8,0x000013d2,0x000013d7,0x0004007c, -0x00000014,0x000013c8,0x000013d8,0x00060041, -0x0000015f,0x000013c0,0x000013c8,0x0000015e, -0x0000015e,0x0005003e,0x000013c0,0x0000136b, -0x00000002,0x00000004,0x000200f9,0x0000136d, -0x000200f8,0x0000136d,0x000200f9,0x000012fe, -0x000200f8,0x000011e3,0x000500aa,0x0000002f, -0x000011f0,0x000011e0,0x00000194,0x000300f7, -0x000011f2,0x00000000,0x000400fa,0x000011f0, -0x000011f1,0x000011f2,0x000200f8,0x000011f1, -0x00050041,0x00000182,0x000013db,0x00000180, -0x00000181,0x0004003d,0x00000006,0x000013dc, -0x000013db,0x00050084,0x00000006,0x000013dd, -0x000001a2,0x000013dc,0x00050080,0x00000006, -0x000013de,0x0000018b,0x000013dd,0x00050080, -0x00000006,0x000013f0,0x000013dc,0x00005cc3, -0x00050086,0x00000006,0x000013f1,0x000013f0, -0x00000185,0x00050084,0x00000006,0x000013e3, -0x0000018b,0x000013f1,0x00050080,0x00000006, -0x000013e4,0x000013de,0x000013e3,0x00050084, -0x00000006,0x000011f6,0x000001a2,0x000013f1, -0x00050041,0x000011dc,0x000011f8,0x000011e5, -0x0000012b,0x0004003d,0x00000006,0x000011f9, -0x000011f8,0x00050080,0x00000006,0x00001410, -0x000011f6,0x00000957,0x00050086,0x00000006, -0x00001411,0x00001410,0x0000018b,0x00050084, -0x00000006,0x00001414,0x000011f9,0x00001411, -0x0007000c,0x00000006,0x00001416,0x00000001, -0x00000026,0x00001414,0x000011f6,0x00050080, -0x00000006,0x00001419,0x00001416,0x00001411, -0x0007000c,0x00000006,0x0000141b,0x00000001, -0x00000026,0x00001419,0x000011f6,0x000200f9, -0x0000141d,0x000200f8,0x0000141d,0x000700f5, -0x00000006,0x00005b9d,0x0000012b,0x000011f1, -0x0000142b,0x00001422,0x000700f5,0x00000006, -0x00005b9c,0x00001416,0x000011f1,0x0000142e, -0x00001422,0x000500b0,0x0000002f,0x00001421, -0x00005b9c,0x0000141b,0x000400f6,0x0000142f, -0x00001422,0x00000000,0x000400fa,0x00001421, -0x00001422,0x0000142f,0x000200f8,0x00001422, -0x00050084,0x00000006,0x00001425,0x000000df, -0x00005b9c,0x00050080,0x00000006,0x00001426, -0x000013de,0x00001425,0x00050041,0x0000022d, -0x00001427,0x00000180,0x0000022b,0x0004003d, -0x00000007,0x00001428,0x00001427,0x00050051, -0x00000006,0x00001488,0x00001428,0x00000000, -0x00050095,0x00000130,0x0000148a,0x00001488, -0x00001426,0x00050051,0x00000006,0x0000148b, -0x0000148a,0x00000001,0x00050051,0x00000006, -0x0000148c,0x0000148a,0x00000000,0x00050051, -0x00000006,0x0000148f,0x00001428,0x00000001, -0x00050080,0x00000006,0x00001491,0x0000148f, -0x0000148b,0x00050050,0x00000007,0x00001492, -0x0000148c,0x00001491,0x0004007c,0x00000014, -0x00001482,0x00001492,0x00060041,0x0000015f, -0x00001479,0x00001482,0x0000015e,0x0000015e, -0x0006003d,0x00000006,0x0000147a,0x00001479, -0x00000002,0x00000004,0x00050080,0x00000006, -0x0000142b,0x00005b9d,0x0000147a,0x00050080, -0x00000006,0x0000142e,0x00005b9c,0x0000022b, -0x000200f9,0x0000141d,0x000200f8,0x0000142f, -0x00050041,0x00000838,0x00001432,0x00000980, -0x000011f9,0x0003003e,0x00001432,0x00005b9d, -0x000400e0,0x00000247,0x00000247,0x00000850, -0x000500aa,0x0000002f,0x00001434,0x000011f9, -0x0000012b,0x000300f7,0x00001451,0x00000000, -0x000400fa,0x00001434,0x00001435,0x00001451, -0x000200f8,0x00001435,0x000200f9,0x00001436, -0x000200f8,0x00001436,0x000700f5,0x00000006, -0x00005b9f,0x0000012b,0x00001435,0x00001443, -0x0000143a,0x000700f5,0x00000006,0x00005b9e, -0x0000012b,0x00001435,0x00001446,0x0000143a, -0x000500b0,0x0000002f,0x00001439,0x00005b9e, -0x0000018b,0x000400f6,0x00001447,0x0000143a, -0x00000000,0x000400fa,0x00001439,0x0000143a, -0x00001447,0x000200f8,0x0000143a,0x00050041, -0x00000838,0x0000143c,0x00000980,0x00005b9e, -0x0004003d,0x00000006,0x0000143d,0x0000143c, -0x0003003e,0x0000143c,0x00005b9f,0x00050080, -0x00000006,0x00001443,0x00005b9f,0x0000143d, -0x00050080,0x00000006,0x00001446,0x00005b9e, -0x0000022b,0x000200f9,0x00001436,0x000200f8, -0x00001447,0x000200f9,0x00001451,0x000200f8, -0x00001451,0x000400e0,0x00000247,0x00000247, -0x00000850,0x0004003d,0x00000006,0x00001454, -0x00001432,0x000200f9,0x00001456,0x000200f8, -0x00001456,0x000700f5,0x00000006,0x00005ba1, -0x00001454,0x00001451,0x0000146d,0x0000145b, -0x000700f5,0x00000006,0x00005ba0,0x00001416, -0x00001451,0x00001470,0x0000145b,0x000500b0, -0x0000002f,0x0000145a,0x00005ba0,0x0000141b, -0x000400f6,0x00001471,0x0000145b,0x00000000, -0x000400fa,0x0000145a,0x0000145b,0x00001471, -0x000200f8,0x0000145b,0x00050084,0x00000006, -0x0000145e,0x000000df,0x00005ba0,0x00050080, -0x00000006,0x0000145f,0x000013de,0x0000145e, -0x00050041,0x0000022d,0x00001460,0x00000180, -0x0000022b,0x0004003d,0x00000007,0x00001461, -0x00001460,0x00050051,0x00000006,0x000014c9, -0x00001461,0x00000000,0x00050095,0x00000130, -0x000014cb,0x000014c9,0x0000145f,0x00050051, -0x00000006,0x000014cc,0x000014cb,0x00000001, -0x00050051,0x00000006,0x000014cd,0x000014cb, -0x00000000,0x00050051,0x00000006,0x000014d0, -0x00001461,0x00000001,0x00050080,0x00000006, -0x000014d2,0x000014d0,0x000014cc,0x00050050, -0x00000007,0x000014d3,0x000014cd,0x000014d2, -0x0004007c,0x00000014,0x000014c3,0x000014d3, -0x00060041,0x0000015f,0x000014ba,0x000014c3, -0x0000015e,0x0000015e,0x0006003d,0x00000006, -0x000014bb,0x000014ba,0x00000002,0x00000004, -0x00050080,0x00000006,0x00001466,0x000013e4, -0x0000145e,0x00050095,0x00000130,0x000014eb, -0x000014c9,0x00001466,0x00050051,0x00000006, -0x000014ec,0x000014eb,0x00000001,0x00050051, -0x00000006,0x000014ed,0x000014eb,0x00000000, -0x00050080,0x00000006,0x000014f2,0x000014d0, -0x000014ec,0x00050050,0x00000007,0x000014f3, -0x000014ed,0x000014f2,0x0004007c,0x00000014, -0x000014e3,0x000014f3,0x00060041,0x0000015f, -0x000014db,0x000014e3,0x0000015e,0x0000015e, -0x0005003e,0x000014db,0x00005ba1,0x00000002, -0x00000004,0x00050080,0x00000006,0x0000146d, -0x00005ba1,0x000014bb,0x00050080,0x00000006, -0x00001470,0x00005ba0,0x0000022b,0x000200f9, -0x00001456,0x000200f8,0x00001471,0x000200f9, -0x000012fe,0x000200f8,0x000011f2,0x000500aa, -0x0000002f,0x00001202,0x000011e0,0x0000050a, -0x000300f7,0x00001204,0x00000000,0x000400fa, -0x00001202,0x00001203,0x00001204,0x000200f8, -0x00001203,0x00050041,0x000011dc,0x00001206, -0x000011e4,0x0000012b,0x0004003d,0x00000006, -0x00001207,0x00001206,0x00050041,0x000011dc, -0x00001209,0x000011e5,0x0000012b,0x0004003d, -0x00000006,0x0000120a,0x00001209,0x000500b0, -0x0000002f,0x00001514,0x0000120a,0x000001a2, -0x000300f7,0x00001523,0x00000000,0x000400fa, -0x00001514,0x00001515,0x00001523,0x000200f8, -0x00001515,0x00050041,0x00000182,0x000015cb, -0x00000180,0x00000181,0x0004003d,0x00000006, -0x000015cc,0x000015cb,0x00050084,0x00000006, -0x000015cd,0x000001a2,0x000015cc,0x00050080, -0x00000006,0x000015ce,0x0000018b,0x000015cd, -0x00050080,0x00000006,0x000015d4,0x000015cc, -0x00005cc3,0x00050086,0x00000006,0x000015d5, -0x000015d4,0x00000185,0x00050084,0x00000006, -0x000015c7,0x0000018b,0x000015d5,0x00050080, -0x00000006,0x000015c8,0x000015ce,0x000015c7, -0x00050084,0x00000006,0x0000151a,0x0000120a, -0x000015d5,0x00050080,0x00000006,0x0000151c, -0x0000151a,0x00001207,0x00050084,0x00000006, -0x0000151d,0x000000df,0x0000151c,0x00050080, -0x00000006,0x0000151e,0x000015c8,0x0000151d, -0x00050041,0x0000022d,0x0000151f,0x00000180, -0x0000022b,0x0004003d,0x00000007,0x00001520, -0x0000151f,0x00050051,0x00000006,0x000015f3, -0x00001520,0x00000000,0x00050095,0x00000130, -0x000015f5,0x000015f3,0x0000151e,0x00050051, -0x00000006,0x000015f6,0x000015f5,0x00000001, -0x00050051,0x00000006,0x000015f7,0x000015f5, -0x00000000,0x00050051,0x00000006,0x000015fa, -0x00001520,0x00000001,0x00050080,0x00000006, -0x000015fc,0x000015fa,0x000015f6,0x00050050, -0x00000007,0x000015fd,0x000015f7,0x000015fc, -0x0004007c,0x00000014,0x000015ed,0x000015fd, -0x00060041,0x0000015f,0x000015e4,0x000015ed, -0x0000015e,0x0000015e,0x0006003d,0x00000006, -0x000015e5,0x000015e4,0x00000002,0x00000004, -0x00050041,0x00000838,0x00001522,0x000009d5, -0x0000120a,0x0003003e,0x00001522,0x000015e5, -0x000200f9,0x00001523,0x000200f8,0x00001523, -0x00050084,0x00000006,0x00001525,0x00001207, -0x00000185,0x00050080,0x00000006,0x00001527, -0x00001525,0x00000185,0x00050041,0x00000182, -0x00001528,0x00000180,0x00000181,0x0004003d, -0x00000006,0x00001529,0x00001528,0x0007000c, -0x00000006,0x0000152a,0x00000001,0x00000026, -0x00001527,0x00001529,0x000200f9,0x0000152c, -0x000200f8,0x0000152c,0x000700f5,0x00000006, -0x00005b83,0x00001525,0x00001523,0x000015c1, -0x000015bf,0x000500b0,0x0000002f,0x00001530, -0x00005b83,0x0000152a,0x000400f6,0x000015c2, -0x000015bf,0x00000000,0x000400fa,0x00001530, -0x00001531,0x000015c2,0x000200f8,0x00001531, -0x00050080,0x00000006,0x00001534,0x00005b83, -0x0000120a,0x000500b0,0x0000002f,0x00001537, -0x00001534,0x0000152a,0x000300f7,0x00001542, -0x00000000,0x000400fa,0x00001537,0x00001539, -0x00001541,0x000200f8,0x00001541,0x000200f9, -0x00001542,0x000200f8,0x00001539,0x00050041, -0x00000182,0x00001601,0x00000180,0x00000488, -0x0004003d,0x00000006,0x00001602,0x00001601, -0x000500c7,0x00000006,0x00001603,0x00001602, -0x00000135,0x000500aa,0x0000002f,0x00001604, -0x00001603,0x0000012b,0x000300f7,0x00001609, -0x00000000,0x000400fa,0x00001604,0x00001605, -0x00001607,0x000200f8,0x00001607,0x00050084, -0x00000006,0x00001611,0x00000194,0x00001529, -0x00050080,0x00000006,0x00001612,0x0000018b, -0x00001611,0x000200f9,0x00001609,0x000200f8, -0x00001605,0x000200f9,0x00001609,0x000200f8, -0x00001609,0x000700f5,0x00000006,0x00005b84, -0x0000018b,0x00001605,0x00001612,0x00001607, -0x00050084,0x00000006,0x0000153c,0x000000df, -0x00001534,0x00050080,0x00000006,0x0000153d, -0x00005b84,0x0000153c,0x00050041,0x0000022d, -0x0000153e,0x00000180,0x0000022b,0x0004003d, -0x00000007,0x0000153f,0x0000153e,0x00050051, -0x00000006,0x00001629,0x0000153f,0x00000000, -0x00050095,0x00000130,0x0000162b,0x00001629, -0x0000153d,0x00050051,0x00000006,0x0000162c, -0x0000162b,0x00000001,0x00050051,0x00000006, -0x0000162d,0x0000162b,0x00000000,0x00050051, -0x00000006,0x00001630,0x0000153f,0x00000001, -0x00050080,0x00000006,0x00001632,0x00001630, -0x0000162c,0x00050050,0x00000007,0x00001633, -0x0000162d,0x00001632,0x0004007c,0x00000014, -0x00001623,0x00001633,0x00060041,0x0000015f, -0x0000161a,0x00001623,0x0000015e,0x0000015e, -0x0006003d,0x00000006,0x0000161b,0x0000161a, -0x00000002,0x00000004,0x000200f9,0x00001542, -0x000200f8,0x00001542,0x000700f5,0x00000006, -0x00005b85,0x0000161b,0x00001609,0x0000012b, -0x00001541,0x000300f7,0x0000154e,0x00000000, -0x000400fa,0x00001537,0x00001545,0x0000154d, -0x000200f8,0x0000154d,0x000200f9,0x0000154e, -0x000200f8,0x00001545,0x00050041,0x00000182, -0x00001637,0x00000180,0x00000488,0x0004003d, -0x00000006,0x00001638,0x00001637,0x000500c7, -0x00000006,0x00001639,0x00001638,0x00000135, -0x000500aa,0x0000002f,0x0000163a,0x00001639, -0x0000012b,0x000300f7,0x0000163f,0x00000000, -0x000400fa,0x0000163a,0x0000163b,0x0000163d, -0x000200f8,0x0000163d,0x00050084,0x00000006, -0x0000164b,0x0000019b,0x00001529,0x00050080, -0x00000006,0x0000164c,0x0000018b,0x0000164b, -0x000200f9,0x0000163f,0x000200f8,0x0000163b, -0x00050084,0x00000006,0x00001645,0x000000df, -0x00001529,0x00050080,0x00000006,0x00001646, -0x0000018b,0x00001645,0x000200f9,0x0000163f, -0x000200f8,0x0000163f,0x000700f5,0x00000006, -0x00005b86,0x00001646,0x0000163b,0x0000164c, -0x0000163d,0x00050084,0x00000006,0x00001548, -0x000000df,0x00001534,0x00050080,0x00000006, -0x00001549,0x00005b86,0x00001548,0x00050041, -0x0000022d,0x0000154a,0x00000180,0x0000022b, -0x0004003d,0x00000007,0x0000154b,0x0000154a, -0x00050051,0x00000006,0x00001663,0x0000154b, -0x00000000,0x00050095,0x00000130,0x00001665, -0x00001663,0x00001549,0x00050051,0x00000006, -0x00001666,0x00001665,0x00000001,0x00050051, -0x00000006,0x00001667,0x00001665,0x00000000, -0x00050051,0x00000006,0x0000166a,0x0000154b, -0x00000001,0x00050080,0x00000006,0x0000166c, -0x0000166a,0x00001666,0x00050050,0x00000007, -0x0000166d,0x00001667,0x0000166c,0x0004007c, -0x00000014,0x0000165d,0x0000166d,0x00060041, -0x0000015f,0x00001654,0x0000165d,0x0000015e, -0x0000015e,0x0006003d,0x00000006,0x00001655, -0x00001654,0x00000002,0x00000004,0x000200f9, -0x0000154e,0x000200f8,0x0000154e,0x000700f5, -0x00000006,0x00005b87,0x00001655,0x0000163f, -0x0000012b,0x0000154d,0x00050041,0x00000182, -0x00001671,0x00000180,0x00000488,0x0004003d, -0x00000006,0x00001672,0x00001671,0x00050084, -0x00000006,0x00001673,0x000000df,0x00001672, -0x000500c2,0x00000006,0x00001674,0x00005b85, -0x00001673,0x000500c7,0x00000006,0x00001675, -0x00001674,0x0000090f,0x000200f9,0x00001552, -0x000200f8,0x00001552,0x000700f5,0x00000006, -0x00005b88,0x0000012b,0x0000154e,0x00001562, -0x00001556,0x000500b0,0x0000002f,0x00001555, -0x00005b88,0x000001a2,0x000400f6,0x00001563, -0x00001556,0x00000000,0x000400fa,0x00001555, -0x00001556,0x00001563,0x000200f8,0x00001556, -0x000500aa,0x0000002f,0x0000155c,0x00005b88, -0x00001675,0x000500a7,0x0000002f,0x0000155d, -0x00001537,0x0000155c,0x000600a9,0x00000006, -0x0000155e,0x0000155d,0x00000135,0x0000012b, -0x00060041,0x00000838,0x0000155f,0x00000a2e, -0x00005b88,0x0000120a,0x0003003e,0x0000155f, -0x0000155e,0x00050080,0x00000006,0x00001562, -0x00005b88,0x0000022b,0x000200f9,0x00001552, -0x000200f8,0x00001563,0x000400e0,0x00000247, -0x00000247,0x00000850,0x000200f9,0x00001564, -0x000200f8,0x00001564,0x000700f5,0x00000006, -0x00005b89,0x00000135,0x00001563,0x00001595, -0x00001593,0x000500b0,0x0000002f,0x00001567, -0x00005b89,0x0000018b,0x000400f6,0x00001596, -0x00001593,0x00000000,0x000400fa,0x00001567, -0x00001568,0x00001596,0x000200f8,0x00001568, -0x000200f9,0x00001569,0x000200f8,0x00001569, -0x000700f5,0x00000006,0x00005b96,0x0000012b, -0x00001568,0x0000157f,0x0000157d,0x000500b0, -0x0000002f,0x0000156c,0x00005b96,0x000001a2, -0x000400f6,0x00001580,0x0000157d,0x00000000, -0x000400fa,0x0000156c,0x0000156d,0x00001580, -0x000200f8,0x0000156d,0x000500ae,0x0000002f, -0x00001571,0x0000120a,0x00005b89,0x000300f7, -0x0000157a,0x00000000,0x000400fa,0x00001571, -0x00001572,0x00001579,0x000200f8,0x00001579, -0x000200f9,0x0000157a,0x000200f8,0x00001572, -0x00050082,0x00000006,0x00001576,0x0000120a, -0x00005b89,0x00060041,0x00000838,0x00001577, -0x00000a2e,0x00005b96,0x00001576,0x0004003d, -0x00000006,0x00001578,0x00001577,0x000200f9, -0x0000157a,0x000200f8,0x0000157a,0x000700f5, -0x00000006,0x00005b9a,0x00001578,0x00001572, -0x0000012b,0x00001579,0x00050041,0x00000009, -0x0000157c,0x00001508,0x00005b96,0x0003003e, -0x0000157c,0x00005b9a,0x000200f9,0x0000157d, -0x000200f8,0x0000157d,0x00050080,0x00000006, -0x0000157f,0x00005b96,0x0000022b,0x000200f9, -0x00001569,0x000200f8,0x00001580,0x000400e0, -0x00000247,0x00000247,0x00000850,0x000200f9, -0x00001581,0x000200f8,0x00001581,0x000700f5, -0x00000006,0x00005b97,0x0000012b,0x00001580, -0x00001591,0x00001585,0x000500b0,0x0000002f, -0x00001584,0x00005b97,0x000001a2,0x000400f6, -0x00001592,0x00001585,0x00000000,0x000400fa, -0x00001584,0x00001585,0x00001592,0x000200f8, -0x00001585,0x00050041,0x00000009,0x00001589, -0x00001508,0x00005b97,0x0004003d,0x00000006, -0x0000158a,0x00001589,0x00060041,0x00000838, -0x0000158b,0x00000a2e,0x00005b97,0x0000120a, -0x0004003d,0x00000006,0x0000158c,0x0000158b, -0x00050080,0x00000006,0x0000158d,0x0000158c, -0x0000158a,0x0003003e,0x0000158b,0x0000158d, -0x00050080,0x00000006,0x00001591,0x00005b97, -0x0000022b,0x000200f9,0x00001581,0x000200f8, -0x00001592,0x000400e0,0x00000247,0x00000247, -0x00000850,0x000200f9,0x00001593,0x000200f8, -0x00001593,0x000500c4,0x00000006,0x00001595, -0x00005b89,0x0000022b,0x000200f9,0x00001564, -0x000200f8,0x00001596,0x000300f7,0x000015b2, -0x00000000,0x000400fa,0x00001537,0x00001598, -0x000015b2,0x000200f8,0x00001598,0x00050041, -0x00000838,0x0000159a,0x000009d5,0x00001675, -0x0004003d,0x00000006,0x0000159b,0x0000159a, -0x00060041,0x00000838,0x0000159e,0x00000a2e, -0x00001675,0x0000120a,0x0004003d,0x00000006, -0x0000159f,0x0000159e,0x00050080,0x00000006, -0x000015a0,0x0000159b,0x0000159f,0x00050082, -0x00000006,0x000015a1,0x000015a0,0x00000135, -0x000500c7,0x00000006,0x0000167b,0x00001672, -0x00000135,0x000500aa,0x0000002f,0x0000167c, -0x0000167b,0x0000012b,0x000300f7,0x00001681, -0x00000000,0x000400fa,0x0000167c,0x0000167d, -0x0000167f,0x000200f8,0x0000167f,0x000200f9, -0x00001681,0x000200f8,0x0000167d,0x00050084, -0x00000006,0x00001687,0x00000194,0x00001529, -0x00050080,0x00000006,0x00001688,0x0000018b, -0x00001687,0x000200f9,0x00001681,0x000200f8, -0x00001681,0x000700f5,0x00000006,0x00005b8a, -0x00001688,0x0000167d,0x0000018b,0x0000167f, -0x00050084,0x00000006,0x000015a4,0x000000df, -0x000015a1,0x00050080,0x00000006,0x000015a5, -0x00005b8a,0x000015a4,0x00050041,0x0000022d, -0x000015a6,0x00000180,0x0000022b,0x0004003d, -0x00000007,0x000015a7,0x000015a6,0x00050051, -0x00000006,0x000016a0,0x000015a7,0x00000000, -0x00050095,0x00000130,0x000016a2,0x000016a0, -0x000015a5,0x00050051,0x00000006,0x000016a3, -0x000016a2,0x00000001,0x00050051,0x00000006, -0x000016a4,0x000016a2,0x00000000,0x00050051, -0x00000006,0x000016a7,0x000015a7,0x00000001, -0x00050080,0x00000006,0x000016a9,0x000016a7, -0x000016a3,0x00050050,0x00000007,0x000016aa, -0x000016a4,0x000016a9,0x0004007c,0x00000014, -0x0000169a,0x000016aa,0x00060041,0x0000015f, -0x00001692,0x0000169a,0x0000015e,0x0000015e, -0x0005003e,0x00001692,0x00005b85,0x00000002, -0x00000004,0x000300f7,0x000016b6,0x00000000, -0x000400fa,0x0000167c,0x000016b2,0x000016b4, -0x000200f8,0x000016b4,0x00050084,0x00000006, -0x000016c2,0x000000df,0x00001529,0x00050080, -0x00000006,0x000016c3,0x0000018b,0x000016c2, -0x000200f9,0x000016b6,0x000200f8,0x000016b2, -0x00050084,0x00000006,0x000016bc,0x0000019b, -0x00001529,0x00050080,0x00000006,0x000016bd, -0x0000018b,0x000016bc,0x000200f9,0x000016b6, -0x000200f8,0x000016b6,0x000700f5,0x00000006, -0x00005b8b,0x000016bd,0x000016b2,0x000016c3, -0x000016b4,0x00050080,0x00000006,0x000015ad, -0x00005b8b,0x000015a4,0x00050095,0x00000130, -0x000016db,0x000016a0,0x000015ad,0x00050051, -0x00000006,0x000016dc,0x000016db,0x00000001, -0x00050051,0x00000006,0x000016dd,0x000016db, -0x00000000,0x00050080,0x00000006,0x000016e2, -0x000016a7,0x000016dc,0x00050050,0x00000007, -0x000016e3,0x000016dd,0x000016e2,0x0004007c, -0x00000014,0x000016d3,0x000016e3,0x00060041, -0x0000015f,0x000016cb,0x000016d3,0x0000015e, -0x0000015e,0x0005003e,0x000016cb,0x00005b87, -0x00000002,0x00000004,0x000200f9,0x000015b2, -0x000200f8,0x000015b2,0x000400e0,0x00000247, -0x00000247,0x00000850,0x000300f7,0x000015be, -0x00000000,0x000400fa,0x00001514,0x000015b5, -0x000015be,0x000200f8,0x000015b5,0x00060041, -0x00000838,0x000015b8,0x00000a2e,0x0000120a, -0x00000a9c,0x0004003d,0x00000006,0x000015b9, -0x000015b8,0x00050041,0x00000838,0x000015ba, -0x000009d5,0x0000120a,0x0004003d,0x00000006, -0x000015bb,0x000015ba,0x00050080,0x00000006, -0x000015bc,0x000015bb,0x000015b9,0x0003003e, -0x000015ba,0x000015bc,0x000200f9,0x000015be, -0x000200f8,0x000015be,0x000400e0,0x00000247, -0x00000247,0x00000850,0x000200f9,0x000015bf, -0x000200f8,0x000015bf,0x00050080,0x00000006, -0x000015c1,0x00005b83,0x0000018b,0x000200f9, -0x0000152c,0x000200f8,0x000015c2,0x000200f9, -0x000012fe,0x000200f8,0x00001204,0x000500aa, -0x0000002f,0x00001210,0x000011e0,0x0000120f, -0x000300f7,0x00001212,0x00000000,0x000400fa, -0x00001210,0x00001211,0x00001212,0x000200f8, -0x00001211,0x00050041,0x000011dc,0x00001214, -0x000011e5,0x0000012b,0x0004003d,0x00000006, -0x00001215,0x00001214,0x00050041,0x00000182, -0x000016fe,0x00000180,0x00000181,0x0004003d, -0x00000006,0x000016ff,0x000016fe,0x000200f9, -0x00001700,0x000200f8,0x00001700,0x000700f5, -0x00000006,0x00005b6e,0x00000135,0x00001211, -0x00001707,0x00001705,0x000500b0,0x0000002f, -0x00001704,0x00005b6e,0x000016ff,0x000400f6, -0x00001709,0x00001705,0x00000000,0x000400fa, -0x00001704,0x00001705,0x00001709,0x000200f8, -0x00001705,0x000500c4,0x00000006,0x00001707, -0x00005b6e,0x0000022b,0x000200f9,0x00001700, -0x000200f8,0x00001709,0x000200f9,0x0000170b, -0x000200f8,0x0000170b,0x000700f5,0x00000006, -0x00005b6f,0x00001215,0x00001709,0x00001733, -0x00001731,0x000500b0,0x0000002f,0x0000170f, -0x00005b6f,0x00005b6e,0x000400f6,0x00001734, -0x00001731,0x00000000,0x000400fa,0x0000170f, -0x00001710,0x00001734,0x000200f8,0x00001710, -0x000500b0,0x0000002f,0x00001714,0x00005b6f, -0x000016ff,0x000300f7,0x0000171e,0x00000000, -0x000400fa,0x00001714,0x00001715,0x0000171d, -0x000200f8,0x0000171d,0x000200f9,0x0000171e, -0x000200f8,0x00001715,0x00050084,0x00000006, -0x00001718,0x000000df,0x00005b6f,0x00050080, -0x00000006,0x00001719,0x0000018b,0x00001718, -0x00050041,0x0000022d,0x0000171a,0x00000180, -0x0000022b,0x0004003d,0x00000007,0x0000171b, -0x0000171a,0x00050051,0x00000006,0x000017c2, -0x0000171b,0x00000000,0x00050095,0x00000130, -0x000017c4,0x000017c2,0x00001719,0x00050051, -0x00000006,0x000017c5,0x000017c4,0x00000001, -0x00050051,0x00000006,0x000017c6,0x000017c4, -0x00000000,0x00050051,0x00000006,0x000017c9, -0x0000171b,0x00000001,0x00050080,0x00000006, -0x000017cb,0x000017c9,0x000017c5,0x00050050, -0x00000007,0x000017cc,0x000017c6,0x000017cb, -0x0004007c,0x00000014,0x000017bc,0x000017cc, -0x00060041,0x0000015f,0x000017b3,0x000017bc, -0x0000015e,0x0000015e,0x0006003d,0x00000006, -0x000017b4,0x000017b3,0x00000002,0x00000004, -0x000200f9,0x0000171e,0x000200f8,0x0000171e, -0x000700f5,0x00000006,0x00005b7f,0x000017b4, -0x00001715,0x00000500,0x0000171d,0x00050041, -0x00000838,0x00001720,0x00000825,0x00005b6f, -0x0003003e,0x00001720,0x00005b7f,0x000300f7, -0x0000172e,0x00000000,0x000400fa,0x00001714, -0x00001725,0x0000172d,0x000200f8,0x0000172d, -0x000200f9,0x0000172e,0x000200f8,0x00001725, -0x00050084,0x00000006,0x000017d1,0x000000df, -0x000016ff,0x00050080,0x00000006,0x000017d2, -0x0000018b,0x000017d1,0x00050084,0x00000006, -0x00001728,0x000000df,0x00005b6f,0x00050080, -0x00000006,0x00001729,0x000017d2,0x00001728, -0x00050041,0x0000022d,0x0000172a,0x00000180, -0x0000022b,0x0004003d,0x00000007,0x0000172b, -0x0000172a,0x00050051,0x00000006,0x000017e9, -0x0000172b,0x00000000,0x00050095,0x00000130, -0x000017eb,0x000017e9,0x00001729,0x00050051, -0x00000006,0x000017ec,0x000017eb,0x00000001, -0x00050051,0x00000006,0x000017ed,0x000017eb, -0x00000000,0x00050051,0x00000006,0x000017f0, -0x0000172b,0x00000001,0x00050080,0x00000006, -0x000017f2,0x000017f0,0x000017ec,0x00050050, -0x00000007,0x000017f3,0x000017ed,0x000017f2, -0x0004007c,0x00000014,0x000017e3,0x000017f3, -0x00060041,0x0000015f,0x000017da,0x000017e3, -0x0000015e,0x0000015e,0x0006003d,0x00000006, -0x000017db,0x000017da,0x00000002,0x00000004, -0x000200f9,0x0000172e,0x000200f8,0x0000172e, -0x000700f5,0x00000006,0x00005b81,0x000017db, -0x00001725,0x00000500,0x0000172d,0x00050041, -0x00000838,0x00001730,0x0000083a,0x00005b6f, -0x0003003e,0x00001730,0x00005b81,0x000200f9, -0x00001731,0x000200f8,0x00001731,0x00050080, -0x00000006,0x00001733,0x00005b6f,0x0000018b, -0x000200f9,0x0000170b,0x000200f8,0x00001734, -0x000400e0,0x00000247,0x00000247,0x00000850, -0x000200f9,0x00001735,0x000200f8,0x00001735, -0x000700f5,0x00000006,0x00005b71,0x00000247, -0x00001734,0x00001789,0x00001787,0x000500b2, -0x0000002f,0x00001739,0x00005b71,0x00005b6e, -0x000400f6,0x0000178a,0x00001787,0x00000000, -0x000400fa,0x00001739,0x0000173a,0x0000178a, -0x000200f8,0x0000173a,0x000500c2,0x00000006, -0x0000173c,0x00005b71,0x0000022b,0x000200f9, -0x0000173d,0x000200f8,0x0000173d,0x000700f5, -0x00000006,0x00005b74,0x0000173c,0x0000173a, -0x00001785,0x00001783,0x000500ac,0x0000002f, -0x00001740,0x00005b74,0x0000012b,0x000400f6, -0x00001786,0x00001783,0x00000000,0x000400fa, -0x00001740,0x00001741,0x00001786,0x000200f8, -0x00001741,0x000200f9,0x00001743,0x000200f8, -0x00001743,0x000700f5,0x00000006,0x00005b76, -0x00001215,0x00001741,0x00001781,0x0000177f, -0x000500b0,0x0000002f,0x00001747,0x00005b76, -0x00005b6e,0x000400f6,0x00001782,0x0000177f, -0x00000000,0x000400fa,0x00001747,0x00001748, -0x00001782,0x000200f8,0x00001748,0x000500c6, -0x00000006,0x0000174b,0x00005b76,0x00005b74, -0x000500ac,0x0000002f,0x0000174e,0x0000174b, -0x00005b76,0x000300f7,0x0000177e,0x00000000, -0x000400fa,0x0000174e,0x0000174f,0x0000177e, -0x000200f8,0x0000174f,0x00050041,0x00000838, -0x00001751,0x00000825,0x00005b76,0x0004003d, -0x00000006,0x00001752,0x00001751,0x00050041, -0x00000838,0x00001754,0x00000825,0x0000174b, -0x0004003d,0x00000006,0x00001755,0x00001754, -0x00050041,0x00000838,0x00001757,0x0000083a, -0x00005b76,0x0004003d,0x00000006,0x00001758, -0x00001757,0x00050041,0x00000838,0x0000175a, -0x0000083a,0x0000174b,0x0004003d,0x00000006, -0x0000175b,0x0000175a,0x000500ac,0x0000002f, -0x0000175e,0x00001752,0x00001755,0x000400a8, -0x0000002f,0x0000175f,0x0000175e,0x000300f7, -0x00001768,0x00000000,0x000400fa,0x0000175f, -0x00001760,0x00001768,0x000200f8,0x00001760, -0x000500aa,0x0000002f,0x00001763,0x00001752, -0x00001755,0x000500ac,0x0000002f,0x00001766, -0x00001758,0x0000175b,0x000500a7,0x0000002f, -0x00001767,0x00001763,0x00001766,0x000200f9, -0x00001768,0x000200f8,0x00001768,0x000700f5, -0x0000002f,0x00001769,0x0000175e,0x0000174f, -0x00001767,0x00001760,0x000500c7,0x00000006, -0x0000176d,0x00005b76,0x00005b71,0x000500aa, -0x0000002f,0x0000176e,0x0000176d,0x0000012b, -0x000500a4,0x0000002f,0x0000176f,0x00001769, -0x0000176e,0x000300f7,0x0000177d,0x00000000, -0x000400fa,0x0000176f,0x00001770,0x0000177d, -0x000200f8,0x00001770,0x0003003e,0x00001751, -0x00001755,0x0003003e,0x00001754,0x00001752, -0x0003003e,0x00001757,0x0000175b,0x0003003e, -0x0000175a,0x00001758,0x000200f9,0x0000177d, -0x000200f8,0x0000177d,0x000200f9,0x0000177e, -0x000200f8,0x0000177e,0x000200f9,0x0000177f, -0x000200f8,0x0000177f,0x00050080,0x00000006, -0x00001781,0x00005b76,0x0000018b,0x000200f9, -0x00001743,0x000200f8,0x00001782,0x000400e0, -0x00000247,0x00000247,0x00000850,0x000200f9, -0x00001783,0x000200f8,0x00001783,0x000500c2, -0x00000006,0x00001785,0x00005b74,0x0000022b, -0x000200f9,0x0000173d,0x000200f8,0x00001786, -0x000200f9,0x00001787,0x000200f8,0x00001787, -0x000500c4,0x00000006,0x00001789,0x00005b71, -0x0000022b,0x000200f9,0x00001735,0x000200f8, -0x0000178a,0x000200f9,0x0000178c,0x000200f8, -0x0000178c,0x000700f5,0x00000006,0x00005b73, -0x00001215,0x0000178a,0x000017a8,0x00001791, -0x000500b0,0x0000002f,0x00001790,0x00005b73, -0x000016ff,0x000400f6,0x000017a9,0x00001791, -0x00000000,0x000400fa,0x00001790,0x00001791, -0x000017a9,0x000200f8,0x00001791,0x00050084, -0x00000006,0x00001794,0x000000df,0x00005b73, -0x00050080,0x00000006,0x00001795,0x0000018b, -0x00001794,0x00050041,0x0000022d,0x00001797, -0x00000180,0x0000022b,0x0004003d,0x00000007, -0x00001798,0x00001797,0x00050041,0x00000838, -0x00001799,0x00000825,0x00005b73,0x0004003d, -0x00000006,0x0000179a,0x00001799,0x00050051, -0x00000006,0x0000180b,0x00001798,0x00000000, -0x00050095,0x00000130,0x0000180d,0x0000180b, -0x00001795,0x00050051,0x00000006,0x0000180e, -0x0000180d,0x00000001,0x00050051,0x00000006, -0x0000180f,0x0000180d,0x00000000,0x00050051, -0x00000006,0x00001812,0x00001798,0x00000001, -0x00050080,0x00000006,0x00001814,0x00001812, -0x0000180e,0x00050050,0x00000007,0x00001815, -0x0000180f,0x00001814,0x0004007c,0x00000014, -0x00001805,0x00001815,0x00060041,0x0000015f, -0x000017fd,0x00001805,0x0000015e,0x0000015e, -0x0005003e,0x000017fd,0x0000179a,0x00000002, -0x00000004,0x00050084,0x00000006,0x0000181a, -0x000000df,0x000016ff,0x00050080,0x00000006, -0x0000181b,0x0000018b,0x0000181a,0x00050080, -0x00000006,0x0000179f,0x0000181b,0x00001794, -0x00050041,0x00000838,0x000017a3,0x0000083a, -0x00005b73,0x0004003d,0x00000006,0x000017a4, -0x000017a3,0x00050095,0x00000130,0x00001833, -0x0000180b,0x0000179f,0x00050051,0x00000006, -0x00001834,0x00001833,0x00000001,0x00050051, -0x00000006,0x00001835,0x00001833,0x00000000, -0x00050080,0x00000006,0x0000183a,0x00001812, -0x00001834,0x00050050,0x00000007,0x0000183b, -0x00001835,0x0000183a,0x0004007c,0x00000014, -0x0000182b,0x0000183b,0x00060041,0x0000015f, -0x00001823,0x0000182b,0x0000015e,0x0000015e, -0x0005003e,0x00001823,0x000017a4,0x00000002, -0x00000004,0x00050080,0x00000006,0x000017a8, -0x00005b73,0x0000018b,0x000200f9,0x0000178c, -0x000200f8,0x000017a9,0x000200f9,0x000012fe, -0x000200f8,0x00001212,0x000500aa,0x0000002f, -0x0000121b,0x000011e0,0x0000121a,0x000300f7, -0x0000121d,0x00000000,0x000400fa,0x0000121b, -0x0000121c,0x0000121d,0x000200f8,0x0000121c, -0x00050041,0x000011dc,0x0000121f,0x000011e4, -0x0000012b,0x0004003d,0x00000006,0x00001220, -0x0000121f,0x00050041,0x000011dc,0x00001222, -0x000011e5,0x0000012b,0x0004003d,0x00000006, -0x00001223,0x00001222,0x000500aa,0x0000002f, -0x0000184f,0x00001223,0x0000012b,0x000300f7, -0x00001851,0x00000000,0x000400fa,0x0000184f, -0x00001850,0x00001851,0x000200f8,0x00001850, -0x0003003e,0x00000d70,0x0000012b,0x000200f9, -0x00001851,0x000200f8,0x00001851,0x000400e0, -0x00000247,0x00000247,0x00000850,0x00050084, -0x00000006,0x00001853,0x00001220,0x00000185, -0x00050080,0x00000006,0x00001855,0x00001853, -0x00000185,0x00050041,0x00000182,0x000018a1, -0x00000180,0x000001b7,0x0004003d,0x00000006, -0x000018a2,0x000018a1,0x000500ac,0x0000002f, -0x000018a3,0x000018a2,0x00000135,0x000300f7, -0x000018a9,0x00000000,0x000400fa,0x000018a3, -0x000018a4,0x000018a8,0x000200f8,0x000018a8, -0x000200f9,0x000018a9,0x000200f8,0x000018a4, -0x00050082,0x00000006,0x000018a7,0x000018a2, -0x00000135,0x000200f9,0x000018a9,0x000200f8, -0x000018a9,0x000700f5,0x00000006,0x00005b50, -0x000018a7,0x000018a4,0x0000012b,0x000018a8, -0x0007000c,0x00000006,0x00001857,0x00000001, -0x00000026,0x00001855,0x00005b50,0x00050080, -0x00000006,0x0000185a,0x00001853,0x00001223, -0x000200f9,0x0000185b,0x000200f8,0x0000185b, -0x000700f5,0x00000006,0x00005b51,0x0000185a, -0x000018a9,0x00001890,0x0000188e,0x000500b0, -0x0000002f,0x0000185f,0x00005b51,0x00001857, -0x000400f6,0x00001891,0x0000188e,0x00000000, -0x000400fa,0x0000185f,0x00001860,0x00001891, -0x000200f8,0x00001860,0x00050041,0x00000182, -0x000018d3,0x00000180,0x00000181,0x0004003d, -0x00000006,0x000018d4,0x000018d3,0x00050084, -0x00000006,0x000018d5,0x000001a2,0x000018d4, -0x00050080,0x00000006,0x000018d6,0x0000018b, -0x000018d5,0x00050080,0x00000006,0x000018dc, -0x000018d4,0x00005cc3,0x00050086,0x00000006, -0x000018dd,0x000018dc,0x00000185,0x00050084, -0x00000006,0x000018cf,0x0000018b,0x000018dd, -0x00050080,0x00000006,0x000018d0,0x000018d6, -0x000018cf,0x00050080,0x00000006,0x000018ca, -0x000018d0,0x000018cf,0x00050084,0x00000006, -0x000018c3,0x000001b6,0x000018a2,0x00050080, -0x00000006,0x000018c4,0x000018ca,0x000018c3, -0x00050041,0x00000182,0x000018ba,0x00000180, -0x000001cd,0x0004003d,0x00000006,0x000018bb, -0x000018ba,0x00050084,0x00000006,0x000018bc, -0x000001cc,0x000018bb,0x00050080,0x00000006, -0x000018bd,0x000018c4,0x000018bc,0x000300f7, -0x000018f0,0x00000000,0x000400fa,0x000018a3, -0x000018eb,0x000018ef,0x000200f8,0x000018ef, -0x000200f9,0x000018f0,0x000200f8,0x000018eb, -0x00050082,0x00000006,0x000018ee,0x000018a2, -0x00000135,0x000200f9,0x000018f0,0x000200f8, -0x000018f0,0x000700f5,0x00000006,0x00005b57, -0x000018ee,0x000018eb,0x0000012b,0x000018ef, -0x00050084,0x00000006,0x000018b5,0x000000df, -0x00005b57,0x00050080,0x00000006,0x000018b6, -0x000018bd,0x000018b5,0x000300f7,0x000018fd, -0x00000000,0x000400fa,0x000018a3,0x000018f8, -0x000018fc,0x000200f8,0x000018fc,0x000200f9, -0x000018fd,0x000200f8,0x000018f8,0x00050082, -0x00000006,0x000018fb,0x000018a2,0x00000135, -0x000200f9,0x000018fd,0x000200f8,0x000018fd, -0x000700f5,0x00000006,0x00005b58,0x000018fb, -0x000018f8,0x0000012b,0x000018fc,0x00050084, -0x00000006,0x000018af,0x000000df,0x00005b58, -0x00050080,0x00000006,0x000018b0,0x000018b6, -0x000018af,0x00050084,0x00000006,0x00001863, -0x000000df,0x00005b51,0x00050080,0x00000006, -0x00001864,0x000018b0,0x00001863,0x00050041, -0x0000022d,0x00001865,0x00000180,0x0000022b, -0x0004003d,0x00000007,0x00001866,0x00001865, -0x00050051,0x00000006,0x00001915,0x00001866, -0x00000000,0x00050095,0x00000130,0x00001917, -0x00001915,0x00001864,0x00050051,0x00000006, -0x00001918,0x00001917,0x00000001,0x00050051, -0x00000006,0x00001919,0x00001917,0x00000000, -0x00050051,0x00000006,0x0000191c,0x00001866, -0x00000001,0x00050080,0x00000006,0x0000191e, -0x0000191c,0x00001918,0x00050050,0x00000007, -0x0000191f,0x00001919,0x0000191e,0x0004007c, -0x00000014,0x0000190f,0x0000191f,0x00060041, -0x0000015f,0x00001906,0x0000190f,0x0000015e, -0x0000015e,0x0006003d,0x00000006,0x00001907, -0x00001906,0x00000002,0x00000004,0x000200f9, -0x00001868,0x000200f8,0x00001868,0x000700f5, -0x00000006,0x00005b5d,0x0000012b,0x000018fd, -0x00001871,0x00001879,0x000700f5,0x00000006, -0x00005b5c,0x0000012b,0x000018fd,0x0000187b, -0x00001879,0x000700f5,0x00000006,0x00005b5b, -0x00001907,0x000018fd,0x0000197c,0x00001879, -0x000500ab,0x0000002f,0x0000186b,0x00005b5b, -0x00000500,0x000500b0,0x0000002f,0x0000186d, -0x00005b5c,0x00000309,0x000500a7,0x0000002f, -0x0000186e,0x0000186b,0x0000186d,0x000400f6, -0x0000187c,0x00001879,0x00000000,0x000400fa, -0x0000186e,0x0000186f,0x0000187c,0x000200f8, -0x0000186f,0x00050080,0x00000006,0x00001871, -0x00005b5d,0x0000022b,0x000300f7,0x00001965, -0x00000000,0x000400fa,0x000018a3,0x00001960, -0x00001964,0x000200f8,0x00001964,0x000200f9, -0x00001965,0x000200f8,0x00001960,0x00050082, -0x00000006,0x00001963,0x000018a2,0x00000135, -0x000200f9,0x00001965,0x000200f8,0x00001965, -0x000700f5,0x00000006,0x00005b68,0x00001963, -0x00001960,0x0000012b,0x00001964,0x00050084, -0x00000006,0x0000192a,0x000000df,0x00005b68, -0x00050080,0x00000006,0x0000192b,0x000018bd, -0x0000192a,0x000300f7,0x00001972,0x00000000, -0x000400fa,0x000018a3,0x0000196d,0x00001971, -0x000200f8,0x00001971,0x000200f9,0x00001972, -0x000200f8,0x0000196d,0x00050082,0x00000006, -0x00001970,0x000018a2,0x00000135,0x000200f9, -0x00001972,0x000200f8,0x00001972,0x000700f5, -0x00000006,0x00005b69,0x00001970,0x0000196d, -0x0000012b,0x00001971,0x00050084,0x00000006, -0x00001924,0x000000df,0x00005b69,0x00050080, -0x00000006,0x00001925,0x0000192b,0x00001924, -0x00050084,0x00000006,0x00001874,0x000000df, -0x00005b5b,0x00050080,0x00000006,0x00001875, -0x00001925,0x00001874,0x00050095,0x00000130, -0x0000198c,0x00001915,0x00001875,0x00050051, -0x00000006,0x0000198d,0x0000198c,0x00000001, -0x00050051,0x00000006,0x0000198e,0x0000198c, -0x00000000,0x00050080,0x00000006,0x00001993, -0x0000191c,0x0000198d,0x00050050,0x00000007, -0x00001994,0x0000198e,0x00001993,0x0004007c, -0x00000014,0x00001984,0x00001994,0x00060041, -0x0000015f,0x0000197b,0x00001984,0x0000015e, -0x0000015e,0x0006003d,0x00000006,0x0000197c, -0x0000197b,0x00000002,0x00000004,0x000200f9, -0x00001879,0x000200f8,0x00001879,0x00050080, -0x00000006,0x0000187b,0x00005b5c,0x0000022b, -0x000200f9,0x00001868,0x000200f8,0x0000187c, -0x000500c7,0x00000006,0x0000187e,0x00005b5d, -0x00000135,0x000500aa,0x0000002f,0x0000187f, -0x0000187e,0x0000012b,0x000600a9,0x00000006, -0x00001880,0x0000187f,0x00000135,0x0000012b, -0x000300f7,0x000019e0,0x00000000,0x000400fa, -0x000018a3,0x000019db,0x000019df,0x000200f8, -0x000019df,0x000200f9,0x000019e0,0x000200f8, -0x000019db,0x00050082,0x00000006,0x000019de, -0x000018a2,0x00000135,0x000200f9,0x000019e0, -0x000200f8,0x000019e0,0x000700f5,0x00000006, -0x00005b60,0x000019de,0x000019db,0x0000012b, -0x000019df,0x00050084,0x00000006,0x000019a5, -0x000000df,0x00005b60,0x00050080,0x00000006, -0x000019a6,0x000018bd,0x000019a5,0x000300f7, -0x000019ed,0x00000000,0x000400fa,0x000018a3, -0x000019e8,0x000019ec,0x000200f8,0x000019ec, -0x000200f9,0x000019ed,0x000200f8,0x000019e8, -0x00050082,0x00000006,0x000019eb,0x000018a2, -0x00000135,0x000200f9,0x000019ed,0x000200f8, -0x000019ed,0x000700f5,0x00000006,0x00005b61, -0x000019eb,0x000019e8,0x0000012b,0x000019ec, -0x00050084,0x00000006,0x0000199f,0x000000df, -0x00005b61,0x00050080,0x00000006,0x000019a0, -0x000019a6,0x0000199f,0x000300f7,0x000019fa, -0x00000000,0x000400fa,0x000018a3,0x000019f5, -0x000019f9,0x000200f8,0x000019f9,0x000200f9, -0x000019fa,0x000200f8,0x000019f5,0x00050082, -0x00000006,0x000019f8,0x000018a2,0x00000135, -0x000200f9,0x000019fa,0x000200f8,0x000019fa, -0x000700f5,0x00000006,0x00005b62,0x000019f8, -0x000019f5,0x0000012b,0x000019f9,0x00050084, -0x00000006,0x00001999,0x000000df,0x00005b62, -0x00050080,0x00000006,0x0000199a,0x000019a0, -0x00001999,0x00050080,0x00000006,0x00001884, -0x0000199a,0x00001863,0x00050095,0x00000130, -0x00001a13,0x00001915,0x00001884,0x00050051, -0x00000006,0x00001a14,0x00001a13,0x00000001, -0x00050051,0x00000006,0x00001a15,0x00001a13, -0x00000000,0x00050080,0x00000006,0x00001a1a, -0x0000191c,0x00001a14,0x00050050,0x00000007, -0x00001a1b,0x00001a15,0x00001a1a,0x0004007c, -0x00000014,0x00001a0b,0x00001a1b,0x00060041, -0x0000015f,0x00001a03,0x00001a0b,0x0000015e, -0x0000015e,0x0005003e,0x00001a03,0x00001880, -0x00000002,0x00000004,0x000300f7,0x0000188d, -0x00000000,0x000400fa,0x0000187f,0x0000188b, -0x0000188d,0x000200f8,0x0000188b,0x000700ea, -0x00000006,0x0000188c,0x00000d70,0x00000135, -0x0000012b,0x00000135,0x000200f9,0x0000188d, -0x000200f8,0x0000188d,0x000200f9,0x0000188e, -0x000200f8,0x0000188e,0x00050080,0x00000006, -0x00001890,0x00005b51,0x0000018b,0x000200f9, -0x0000185b,0x000200f8,0x00001891,0x000400e0, -0x00000247,0x00000247,0x00000850,0x000300f7, -0x0000189d,0x00000000,0x000400fa,0x0000184f, -0x00001894,0x0000189d,0x000200f8,0x00001894, -0x00050041,0x00000182,0x00001a56,0x00000180, -0x00000181,0x0004003d,0x00000006,0x00001a57, -0x00001a56,0x00050084,0x00000006,0x00001a58, -0x000001a2,0x00001a57,0x00050080,0x00000006, -0x00001a59,0x0000018b,0x00001a58,0x00050080, -0x00000006,0x00001a5f,0x00001a57,0x00005cc3, -0x00050086,0x00000006,0x00001a60,0x00001a5f, -0x00000185,0x00050084,0x00000006,0x00001a52, -0x0000018b,0x00001a60,0x00050080,0x00000006, -0x00001a53,0x00001a59,0x00001a52,0x00050080, -0x00000006,0x00001a4d,0x00001a53,0x00001a52, -0x00050084,0x00000006,0x00001a46,0x000001b6, -0x000018a2,0x00050080,0x00000006,0x00001a47, -0x00001a4d,0x00001a46,0x00050041,0x00000182, -0x00001a3d,0x00000180,0x000001cd,0x0004003d, -0x00000006,0x00001a3e,0x00001a3d,0x00050084, -0x00000006,0x00001a3f,0x000001cc,0x00001a3e, -0x00050080,0x00000006,0x00001a40,0x00001a47, -0x00001a3f,0x000300f7,0x00001a73,0x00000000, -0x000400fa,0x000018a3,0x00001a6e,0x00001a72, -0x000200f8,0x00001a72,0x000200f9,0x00001a73, -0x000200f8,0x00001a6e,0x00050082,0x00000006, -0x00001a71,0x000018a2,0x00000135,0x000200f9, -0x00001a73,0x000200f8,0x00001a73,0x000700f5, -0x00000006,0x00005b52,0x00001a71,0x00001a6e, -0x0000012b,0x00001a72,0x00050084,0x00000006, -0x00001a38,0x000000df,0x00005b52,0x00050080, -0x00000006,0x00001a39,0x00001a40,0x00001a38, -0x000300f7,0x00001a80,0x00000000,0x000400fa, -0x000018a3,0x00001a7b,0x00001a7f,0x000200f8, -0x00001a7f,0x000200f9,0x00001a80,0x000200f8, -0x00001a7b,0x00050082,0x00000006,0x00001a7e, -0x000018a2,0x00000135,0x000200f9,0x00001a80, -0x000200f8,0x00001a80,0x000700f5,0x00000006, -0x00005b53,0x00001a7e,0x00001a7b,0x0000012b, -0x00001a7f,0x00050084,0x00000006,0x00001a32, -0x000000df,0x00005b53,0x00050080,0x00000006, -0x00001a33,0x00001a39,0x00001a32,0x000300f7, -0x00001a8d,0x00000000,0x000400fa,0x000018a3, -0x00001a88,0x00001a8c,0x000200f8,0x00001a8c, -0x000200f9,0x00001a8d,0x000200f8,0x00001a88, -0x00050082,0x00000006,0x00001a8b,0x000018a2, -0x00000135,0x000200f9,0x00001a8d,0x000200f8, -0x00001a8d,0x000700f5,0x00000006,0x00005b54, -0x00001a8b,0x00001a88,0x0000012b,0x00001a8c, -0x00050084,0x00000006,0x00001a2c,0x000000df, -0x00005b54,0x00050080,0x00000006,0x00001a2d, -0x00001a33,0x00001a2c,0x000300f7,0x00001a9a, -0x00000000,0x000400fa,0x000018a3,0x00001a95, -0x00001a99,0x000200f8,0x00001a99,0x000200f9, -0x00001a9a,0x000200f8,0x00001a95,0x00050082, -0x00000006,0x00001a98,0x000018a2,0x00000135, -0x000200f9,0x00001a9a,0x000200f8,0x00001a9a, -0x000700f5,0x00000006,0x00005b55,0x00001a98, -0x00001a95,0x0000012b,0x00001a99,0x00050084, -0x00000006,0x00001a26,0x000000df,0x00005b55, -0x00050080,0x00000006,0x00001a27,0x00001a2d, -0x00001a26,0x000300f7,0x00001aa7,0x00000000, -0x000400fa,0x000018a3,0x00001aa2,0x00001aa6, -0x000200f8,0x00001aa6,0x000200f9,0x00001aa7, -0x000200f8,0x00001aa2,0x00050082,0x00000006, -0x00001aa5,0x000018a2,0x00000135,0x000200f9, -0x00001aa7,0x000200f8,0x00001aa7,0x000700f5, -0x00000006,0x00005b56,0x00001aa5,0x00001aa2, -0x0000012b,0x00001aa6,0x00050084,0x00000006, -0x00001a20,0x000000df,0x00005b56,0x00050080, -0x00000006,0x00001a21,0x00001a27,0x00001a20, -0x00050084,0x00000006,0x00001897,0x000000df, -0x00001220,0x00050080,0x00000006,0x00001898, -0x00001a21,0x00001897,0x00050041,0x0000022d, -0x00001899,0x00000180,0x0000022b,0x0004003d, -0x00000007,0x0000189a,0x00001899,0x0004003d, -0x00000006,0x0000189b,0x00000d70,0x00050051, -0x00000006,0x00001abe,0x0000189a,0x00000000, -0x00050095,0x00000130,0x00001ac0,0x00001abe, -0x00001898,0x00050051,0x00000006,0x00001ac1, -0x00001ac0,0x00000001,0x00050051,0x00000006, -0x00001ac2,0x00001ac0,0x00000000,0x00050051, -0x00000006,0x00001ac5,0x0000189a,0x00000001, -0x00050080,0x00000006,0x00001ac7,0x00001ac5, -0x00001ac1,0x00050050,0x00000007,0x00001ac8, -0x00001ac2,0x00001ac7,0x0004007c,0x00000014, -0x00001ab8,0x00001ac8,0x00060041,0x0000015f, -0x00001ab0,0x00001ab8,0x0000015e,0x0000015e, -0x0005003e,0x00001ab0,0x0000189b,0x00000002, -0x00000004,0x000200f9,0x0000189d,0x000200f8, -0x0000189d,0x000200f9,0x000012fe,0x000200f8, -0x0000121d,0x000500aa,0x0000002f,0x00001228, -0x000011e0,0x0000090f,0x000300f7,0x0000122a, -0x00000000,0x000400fa,0x00001228,0x00001229, -0x0000122a,0x000200f8,0x00001229,0x00050041, -0x00000182,0x00001b03,0x00000180,0x00000181, -0x0004003d,0x00000006,0x00001b04,0x00001b03, -0x00050084,0x00000006,0x00001b05,0x000001a2, -0x00001b04,0x00050080,0x00000006,0x00001b06, -0x0000018b,0x00001b05,0x00050080,0x00000006, -0x00001b0c,0x00001b04,0x00005cc3,0x00050086, -0x00000006,0x00001b0d,0x00001b0c,0x00000185, -0x00050084,0x00000006,0x00001aff,0x0000018b, -0x00001b0d,0x00050080,0x00000006,0x00001b00, -0x00001b06,0x00001aff,0x00050080,0x00000006, -0x00001afa,0x00001b00,0x00001aff,0x00050041, -0x00000182,0x00001af1,0x00000180,0x000001b7, -0x0004003d,0x00000006,0x00001af2,0x00001af1, -0x00050084,0x00000006,0x00001af3,0x000001b6, -0x00001af2,0x00050080,0x00000006,0x00001af4, -0x00001afa,0x00001af3,0x00050041,0x00000182, -0x00001aea,0x00000180,0x000001cd,0x0004003d, -0x00000006,0x00001aeb,0x00001aea,0x00050084, -0x00000006,0x00001aec,0x000001cc,0x00001aeb, -0x00050080,0x00000006,0x00001aed,0x00001af4, -0x00001aec,0x000500ac,0x0000002f,0x00001b1a, -0x00001af2,0x00000135,0x000300f7,0x00001b20, -0x00000000,0x000400fa,0x00001b1a,0x00001b1b, -0x00001b1f,0x000200f8,0x00001b1f,0x000200f9, -0x00001b20,0x000200f8,0x00001b1b,0x00050082, -0x00000006,0x00001b1e,0x00001af2,0x00000135, -0x000200f9,0x00001b20,0x000200f8,0x00001b20, -0x000700f5,0x00000006,0x00005b3e,0x00001b1e, -0x00001b1b,0x0000012b,0x00001b1f,0x00050084, -0x00000006,0x00001ae5,0x000000df,0x00005b3e, -0x00050080,0x00000006,0x00001ae6,0x00001aed, -0x00001ae5,0x000300f7,0x00001b2d,0x00000000, -0x000400fa,0x00001b1a,0x00001b28,0x00001b2c, -0x000200f8,0x00001b2c,0x000200f9,0x00001b2d, -0x000200f8,0x00001b28,0x00050082,0x00000006, -0x00001b2b,0x00001af2,0x00000135,0x000200f9, -0x00001b2d,0x000200f8,0x00001b2d,0x000700f5, -0x00000006,0x00005b3f,0x00001b2b,0x00001b28, -0x0000012b,0x00001b2c,0x00050084,0x00000006, -0x00001adf,0x000000df,0x00005b3f,0x00050080, -0x00000006,0x00001ae0,0x00001ae6,0x00001adf, -0x000300f7,0x00001b3a,0x00000000,0x000400fa, -0x00001b1a,0x00001b35,0x00001b39,0x000200f8, -0x00001b39,0x000200f9,0x00001b3a,0x000200f8, -0x00001b35,0x00050082,0x00000006,0x00001b38, -0x00001af2,0x00000135,0x000200f9,0x00001b3a, -0x000200f8,0x00001b3a,0x000700f5,0x00000006, -0x00005b40,0x00001b38,0x00001b35,0x0000012b, -0x00001b39,0x00050084,0x00000006,0x00001ad9, -0x000000df,0x00005b40,0x00050080,0x00000006, -0x00001ada,0x00001ae0,0x00001ad9,0x000300f7, -0x00001b47,0x00000000,0x000400fa,0x00001b1a, -0x00001b42,0x00001b46,0x000200f8,0x00001b46, -0x000200f9,0x00001b47,0x000200f8,0x00001b42, -0x00050082,0x00000006,0x00001b45,0x00001af2, -0x00000135,0x000200f9,0x00001b47,0x000200f8, -0x00001b47,0x000700f5,0x00000006,0x00005b41, -0x00001b45,0x00001b42,0x0000012b,0x00001b46, -0x00050084,0x00000006,0x00001ad3,0x000000df, -0x00005b41,0x00050080,0x00000006,0x00001ad4, -0x00001ada,0x00001ad3,0x000300f7,0x00001b54, -0x00000000,0x000400fa,0x00001b1a,0x00001b4f, -0x00001b53,0x000200f8,0x00001b53,0x000200f9, -0x00001b54,0x000200f8,0x00001b4f,0x00050082, -0x00000006,0x00001b52,0x00001af2,0x00000135, -0x000200f9,0x00001b54,0x000200f8,0x00001b54, -0x000700f5,0x00000006,0x00005b42,0x00001b52, -0x00001b4f,0x0000012b,0x00001b53,0x00050084, -0x00000006,0x00001acd,0x000000df,0x00005b42, -0x00050080,0x00000006,0x00001ace,0x00001ad4, -0x00001acd,0x000300f7,0x00001bb3,0x00000000, -0x000400fa,0x00001b1a,0x00001bae,0x00001bb2, -0x000200f8,0x00001bb2,0x000200f9,0x00001bb3, -0x000200f8,0x00001bae,0x00050082,0x00000006, -0x00001bb1,0x00001af2,0x00000135,0x000200f9, -0x00001bb3,0x000200f8,0x00001bb3,0x000700f5, -0x00000006,0x00005b43,0x00001bb1,0x00001bae, -0x0000012b,0x00001bb2,0x00050084,0x00000006, -0x00001b78,0x000000df,0x00005b43,0x00050080, -0x00000006,0x00001b79,0x00001aed,0x00001b78, -0x000300f7,0x00001bc0,0x00000000,0x000400fa, -0x00001b1a,0x00001bbb,0x00001bbf,0x000200f8, -0x00001bbf,0x000200f9,0x00001bc0,0x000200f8, -0x00001bbb,0x00050082,0x00000006,0x00001bbe, -0x00001af2,0x00000135,0x000200f9,0x00001bc0, -0x000200f8,0x00001bc0,0x000700f5,0x00000006, -0x00005b44,0x00001bbe,0x00001bbb,0x0000012b, -0x00001bbf,0x00050084,0x00000006,0x00001b72, -0x000000df,0x00005b44,0x00050080,0x00000006, -0x00001b73,0x00001b79,0x00001b72,0x000300f7, -0x00001bcd,0x00000000,0x000400fa,0x00001b1a, -0x00001bc8,0x00001bcc,0x000200f8,0x00001bcc, -0x000200f9,0x00001bcd,0x000200f8,0x00001bc8, -0x00050082,0x00000006,0x00001bcb,0x00001af2, -0x00000135,0x000200f9,0x00001bcd,0x000200f8, -0x00001bcd,0x000700f5,0x00000006,0x00005b45, -0x00001bcb,0x00001bc8,0x0000012b,0x00001bcc, -0x00050084,0x00000006,0x00001b6c,0x000000df, -0x00005b45,0x00050080,0x00000006,0x00001b6d, -0x00001b73,0x00001b6c,0x000300f7,0x00001bda, -0x00000000,0x000400fa,0x00001b1a,0x00001bd5, -0x00001bd9,0x000200f8,0x00001bd9,0x000200f9, -0x00001bda,0x000200f8,0x00001bd5,0x00050082, -0x00000006,0x00001bd8,0x00001af2,0x00000135, -0x000200f9,0x00001bda,0x000200f8,0x00001bda, -0x000700f5,0x00000006,0x00005b46,0x00001bd8, -0x00001bd5,0x0000012b,0x00001bd9,0x00050084, -0x00000006,0x00001b66,0x000000df,0x00005b46, -0x00050080,0x00000006,0x00001b67,0x00001b6d, -0x00001b66,0x000300f7,0x00001be7,0x00000000, -0x000400fa,0x00001b1a,0x00001be2,0x00001be6, -0x000200f8,0x00001be6,0x000200f9,0x00001be7, -0x000200f8,0x00001be2,0x00050082,0x00000006, -0x00001be5,0x00001af2,0x00000135,0x000200f9, -0x00001be7,0x000200f8,0x00001be7,0x000700f5, -0x00000006,0x00005b47,0x00001be5,0x00001be2, -0x0000012b,0x00001be6,0x00050084,0x00000006, -0x00001b60,0x000000df,0x00005b47,0x00050080, -0x00000006,0x00001b61,0x00001b67,0x00001b60, -0x000300f7,0x00001bfa,0x00000000,0x000400fa, -0x00001b1a,0x00001bf5,0x00001bf9,0x000200f8, -0x00001bf9,0x000200f9,0x00001bfa,0x000200f8, -0x00001bf5,0x00050082,0x00000006,0x00001bf8, -0x00001af2,0x00000135,0x000200f9,0x00001bfa, -0x000200f8,0x00001bfa,0x000700f5,0x00000006, -0x00005b48,0x00001bf8,0x00001bf5,0x0000012b, -0x00001bf9,0x00050080,0x00000006,0x00001bed, -0x00005b48,0x00005cc3,0x00050086,0x00000006, -0x00001bee,0x00001bed,0x00000185,0x00050084, -0x00000006,0x00001b5a,0x000000df,0x00001bee, -0x00050080,0x00000006,0x00001b5b,0x00001b61, -0x00001b5a,0x000300f7,0x00001c0d,0x00000000, -0x000400fa,0x00001b1a,0x00001c08,0x00001c0c, -0x000200f8,0x00001c0c,0x000200f9,0x00001c0d, -0x000200f8,0x00001c08,0x00050082,0x00000006, -0x00001c0b,0x00001af2,0x00000135,0x000200f9, -0x00001c0d,0x000200f8,0x00001c0d,0x000700f5, -0x00000006,0x00005b49,0x00001c0b,0x00001c08, -0x0000012b,0x00001c0c,0x00050080,0x00000006, -0x00001c00,0x00005b49,0x00005cc3,0x00050086, -0x00000006,0x00001c01,0x00001c00,0x00000185, -0x00050041,0x000011dc,0x0000122f,0x000011e5, -0x0000012b,0x0004003d,0x00000006,0x00001230, -0x0000122f,0x00050080,0x00000006,0x00001c26, -0x00001c01,0x00000957,0x00050086,0x00000006, -0x00001c27,0x00001c26,0x0000018b,0x00050084, -0x00000006,0x00001c2a,0x00001230,0x00001c27, -0x0007000c,0x00000006,0x00001c2c,0x00000001, -0x00000026,0x00001c2a,0x00001c01,0x00050080, -0x00000006,0x00001c2f,0x00001c2c,0x00001c27, -0x0007000c,0x00000006,0x00001c31,0x00000001, -0x00000026,0x00001c2f,0x00001c01,0x000200f9, -0x00001c33,0x000200f8,0x00001c33,0x000700f5, -0x00000006,0x00005b4b,0x0000012b,0x00001c0d, -0x00001c41,0x00001c38,0x000700f5,0x00000006, -0x00005b4a,0x00001c2c,0x00001c0d,0x00001c44, -0x00001c38,0x000500b0,0x0000002f,0x00001c37, -0x00005b4a,0x00001c31,0x000400f6,0x00001c45, -0x00001c38,0x00000000,0x000400fa,0x00001c37, -0x00001c38,0x00001c45,0x000200f8,0x00001c38, -0x00050084,0x00000006,0x00001c3b,0x000000df, -0x00005b4a,0x00050080,0x00000006,0x00001c3c, -0x00001ace,0x00001c3b,0x00050041,0x0000022d, -0x00001c3d,0x00000180,0x0000022b,0x0004003d, -0x00000007,0x00001c3e,0x00001c3d,0x00050051, -0x00000006,0x00001c9e,0x00001c3e,0x00000000, -0x00050095,0x00000130,0x00001ca0,0x00001c9e, -0x00001c3c,0x00050051,0x00000006,0x00001ca1, -0x00001ca0,0x00000001,0x00050051,0x00000006, -0x00001ca2,0x00001ca0,0x00000000,0x00050051, -0x00000006,0x00001ca5,0x00001c3e,0x00000001, -0x00050080,0x00000006,0x00001ca7,0x00001ca5, -0x00001ca1,0x00050050,0x00000007,0x00001ca8, -0x00001ca2,0x00001ca7,0x0004007c,0x00000014, -0x00001c98,0x00001ca8,0x00060041,0x0000015f, -0x00001c8f,0x00001c98,0x0000015e,0x0000015e, -0x0006003d,0x00000006,0x00001c90,0x00001c8f, -0x00000002,0x00000004,0x00050080,0x00000006, -0x00001c41,0x00005b4b,0x00001c90,0x00050080, -0x00000006,0x00001c44,0x00005b4a,0x0000022b, -0x000200f9,0x00001c33,0x000200f8,0x00001c45, -0x00050041,0x00000838,0x00001c48,0x00000980, -0x00001230,0x0003003e,0x00001c48,0x00005b4b, -0x000400e0,0x00000247,0x00000247,0x00000850, -0x000500aa,0x0000002f,0x00001c4a,0x00001230, -0x0000012b,0x000300f7,0x00001c67,0x00000000, -0x000400fa,0x00001c4a,0x00001c4b,0x00001c67, -0x000200f8,0x00001c4b,0x000200f9,0x00001c4c, -0x000200f8,0x00001c4c,0x000700f5,0x00000006, -0x00005b4d,0x0000012b,0x00001c4b,0x00001c59, -0x00001c50,0x000700f5,0x00000006,0x00005b4c, -0x0000012b,0x00001c4b,0x00001c5c,0x00001c50, -0x000500b0,0x0000002f,0x00001c4f,0x00005b4c, -0x0000018b,0x000400f6,0x00001c5d,0x00001c50, -0x00000000,0x000400fa,0x00001c4f,0x00001c50, -0x00001c5d,0x000200f8,0x00001c50,0x00050041, -0x00000838,0x00001c52,0x00000980,0x00005b4c, -0x0004003d,0x00000006,0x00001c53,0x00001c52, -0x0003003e,0x00001c52,0x00005b4d,0x00050080, -0x00000006,0x00001c59,0x00005b4d,0x00001c53, -0x00050080,0x00000006,0x00001c5c,0x00005b4c, -0x0000022b,0x000200f9,0x00001c4c,0x000200f8, -0x00001c5d,0x00050041,0x0000022d,0x00001c61, -0x00000180,0x0000022b,0x0004003d,0x00000007, -0x00001c62,0x00001c61,0x00050051,0x00000006, -0x00001cbe,0x00001c62,0x00000000,0x00050095, -0x00000130,0x00001cc0,0x00001cbe,0x000001b6, -0x00050051,0x00000006,0x00001cc1,0x00001cc0, -0x00000001,0x00050051,0x00000006,0x00001cc2, -0x00001cc0,0x00000000,0x00050051,0x00000006, -0x00001cc5,0x00001c62,0x00000001,0x00050080, -0x00000006,0x00001cc7,0x00001cc5,0x00001cc1, -0x00050050,0x00000007,0x00001cc8,0x00001cc2, -0x00001cc7,0x0004007c,0x00000014,0x00001cb8, -0x00001cc8,0x00060041,0x0000015f,0x00001cb0, -0x00001cb8,0x0000015e,0x0000015e,0x0005003e, -0x00001cb0,0x00005b4d,0x00000002,0x00000004, -0x000200f9,0x00001c67,0x000200f8,0x00001c67, -0x000400e0,0x00000247,0x00000247,0x00000850, -0x0004003d,0x00000006,0x00001c6a,0x00001c48, -0x000200f9,0x00001c6c,0x000200f8,0x00001c6c, -0x000700f5,0x00000006,0x00005b4f,0x00001c6a, -0x00001c67,0x00001c83,0x00001c71,0x000700f5, -0x00000006,0x00005b4e,0x00001c2c,0x00001c67, -0x00001c86,0x00001c71,0x000500b0,0x0000002f, -0x00001c70,0x00005b4e,0x00001c31,0x000400f6, -0x00001c87,0x00001c71,0x00000000,0x000400fa, -0x00001c70,0x00001c71,0x00001c87,0x000200f8, -0x00001c71,0x00050084,0x00000006,0x00001c74, -0x000000df,0x00005b4e,0x00050080,0x00000006, -0x00001c75,0x00001ace,0x00001c74,0x00050041, -0x0000022d,0x00001c76,0x00000180,0x0000022b, -0x0004003d,0x00000007,0x00001c77,0x00001c76, -0x00050051,0x00000006,0x00001cdf,0x00001c77, -0x00000000,0x00050095,0x00000130,0x00001ce1, -0x00001cdf,0x00001c75,0x00050051,0x00000006, -0x00001ce2,0x00001ce1,0x00000001,0x00050051, -0x00000006,0x00001ce3,0x00001ce1,0x00000000, -0x00050051,0x00000006,0x00001ce6,0x00001c77, -0x00000001,0x00050080,0x00000006,0x00001ce8, -0x00001ce6,0x00001ce2,0x00050050,0x00000007, -0x00001ce9,0x00001ce3,0x00001ce8,0x0004007c, -0x00000014,0x00001cd9,0x00001ce9,0x00060041, -0x0000015f,0x00001cd0,0x00001cd9,0x0000015e, -0x0000015e,0x0006003d,0x00000006,0x00001cd1, -0x00001cd0,0x00000002,0x00000004,0x00050080, -0x00000006,0x00001c7c,0x00001b5b,0x00001c74, -0x00050095,0x00000130,0x00001d01,0x00001cdf, -0x00001c7c,0x00050051,0x00000006,0x00001d02, -0x00001d01,0x00000001,0x00050051,0x00000006, -0x00001d03,0x00001d01,0x00000000,0x00050080, -0x00000006,0x00001d08,0x00001ce6,0x00001d02, -0x00050050,0x00000007,0x00001d09,0x00001d03, -0x00001d08,0x0004007c,0x00000014,0x00001cf9, -0x00001d09,0x00060041,0x0000015f,0x00001cf1, -0x00001cf9,0x0000015e,0x0000015e,0x0005003e, -0x00001cf1,0x00005b4f,0x00000002,0x00000004, -0x00050080,0x00000006,0x00001c83,0x00005b4f, -0x00001cd1,0x00050080,0x00000006,0x00001c86, -0x00005b4e,0x0000022b,0x000200f9,0x00001c6c, -0x000200f8,0x00001c87,0x000200f9,0x000012fe, -0x000200f8,0x0000122a,0x000500aa,0x0000002f, -0x00001239,0x000011e0,0x000001a2,0x000300f7, -0x0000123b,0x00000000,0x000400fa,0x00001239, -0x0000123a,0x0000123b,0x000200f8,0x0000123a, -0x00050041,0x000011dc,0x0000123d,0x000011e4, -0x0000012b,0x0004003d,0x00000006,0x0000123e, -0x0000123d,0x00050041,0x000011dc,0x00001240, -0x000011e5,0x0000012b,0x0004003d,0x00000006, -0x00001241,0x00001240,0x00050041,0x00000182, -0x00001db8,0x00000180,0x00000181,0x0004003d, -0x00000006,0x00001db9,0x00001db8,0x00050084, -0x00000006,0x00001dba,0x000001a2,0x00001db9, -0x00050080,0x00000006,0x00001dbb,0x0000018b, -0x00001dba,0x00050080,0x00000006,0x00001dc1, -0x00001db9,0x00005cc3,0x00050086,0x00000006, -0x00001dc2,0x00001dc1,0x00000185,0x00050084, -0x00000006,0x00001db4,0x0000018b,0x00001dc2, -0x00050080,0x00000006,0x00001db5,0x00001dbb, -0x00001db4,0x00050080,0x00000006,0x00001daf, -0x00001db5,0x00001db4,0x00050041,0x00000182, -0x00001da6,0x00000180,0x000001b7,0x0004003d, -0x00000006,0x00001da7,0x00001da6,0x00050084, -0x00000006,0x00001da8,0x000001b6,0x00001da7, -0x00050080,0x00000006,0x00001da9,0x00001daf, -0x00001da8,0x00050041,0x00000182,0x00001d9f, -0x00000180,0x000001cd,0x0004003d,0x00000006, -0x00001da0,0x00001d9f,0x00050084,0x00000006, -0x00001da1,0x000001cc,0x00001da0,0x00050080, -0x00000006,0x00001da2,0x00001da9,0x00001da1, -0x000500ac,0x0000002f,0x00001dcf,0x00001da7, -0x00000135,0x000300f7,0x00001dd5,0x00000000, -0x000400fa,0x00001dcf,0x00001dd0,0x00001dd4, -0x000200f8,0x00001dd4,0x000200f9,0x00001dd5, -0x000200f8,0x00001dd0,0x00050082,0x00000006, -0x00001dd3,0x00001da7,0x00000135,0x000200f9, -0x00001dd5,0x000200f8,0x00001dd5,0x000700f5, -0x00000006,0x00005b15,0x00001dd3,0x00001dd0, -0x0000012b,0x00001dd4,0x00050084,0x00000006, -0x00001d9a,0x000000df,0x00005b15,0x00050080, -0x00000006,0x00001d9b,0x00001da2,0x00001d9a, -0x000300f7,0x00001de2,0x00000000,0x000400fa, -0x00001dcf,0x00001ddd,0x00001de1,0x000200f8, -0x00001de1,0x000200f9,0x00001de2,0x000200f8, -0x00001ddd,0x00050082,0x00000006,0x00001de0, -0x00001da7,0x00000135,0x000200f9,0x00001de2, -0x000200f8,0x00001de2,0x000700f5,0x00000006, -0x00005b16,0x00001de0,0x00001ddd,0x0000012b, -0x00001de1,0x00050084,0x00000006,0x00001d94, -0x000000df,0x00005b16,0x00050080,0x00000006, -0x00001d95,0x00001d9b,0x00001d94,0x000300f7, -0x00001def,0x00000000,0x000400fa,0x00001dcf, -0x00001dea,0x00001dee,0x000200f8,0x00001dee, -0x000200f9,0x00001def,0x000200f8,0x00001dea, -0x00050082,0x00000006,0x00001ded,0x00001da7, -0x00000135,0x000200f9,0x00001def,0x000200f8, -0x00001def,0x000700f5,0x00000006,0x00005b17, -0x00001ded,0x00001dea,0x0000012b,0x00001dee, -0x00050084,0x00000006,0x00001d8e,0x000000df, -0x00005b17,0x00050080,0x00000006,0x00001d8f, -0x00001d95,0x00001d8e,0x000300f7,0x00001dfc, -0x00000000,0x000400fa,0x00001dcf,0x00001df7, -0x00001dfb,0x000200f8,0x00001dfb,0x000200f9, -0x00001dfc,0x000200f8,0x00001df7,0x00050082, -0x00000006,0x00001dfa,0x00001da7,0x00000135, -0x000200f9,0x00001dfc,0x000200f8,0x00001dfc, -0x000700f5,0x00000006,0x00005b18,0x00001dfa, -0x00001df7,0x0000012b,0x00001dfb,0x00050084, -0x00000006,0x00001d88,0x000000df,0x00005b18, -0x00050080,0x00000006,0x00001d89,0x00001d8f, -0x00001d88,0x000300f7,0x00001e09,0x00000000, -0x000400fa,0x00001dcf,0x00001e04,0x00001e08, -0x000200f8,0x00001e08,0x000200f9,0x00001e09, -0x000200f8,0x00001e04,0x00050082,0x00000006, -0x00001e07,0x00001da7,0x00000135,0x000200f9, -0x00001e09,0x000200f8,0x00001e09,0x000700f5, -0x00000006,0x00005b19,0x00001e07,0x00001e04, -0x0000012b,0x00001e08,0x00050084,0x00000006, -0x00001d82,0x000000df,0x00005b19,0x00050080, -0x00000006,0x00001d83,0x00001d89,0x00001d82, -0x000300f7,0x00001e1c,0x00000000,0x000400fa, -0x00001dcf,0x00001e17,0x00001e1b,0x000200f8, -0x00001e1b,0x000200f9,0x00001e1c,0x000200f8, -0x00001e17,0x00050082,0x00000006,0x00001e1a, -0x00001da7,0x00000135,0x000200f9,0x00001e1c, -0x000200f8,0x00001e1c,0x000700f5,0x00000006, -0x00005b1a,0x00001e1a,0x00001e17,0x0000012b, -0x00001e1b,0x00050080,0x00000006,0x00001e0f, -0x00005b1a,0x00005cc3,0x00050086,0x00000006, -0x00001e10,0x00001e0f,0x00000185,0x00050084, -0x00000006,0x00001d7c,0x000000df,0x00001e10, -0x00050080,0x00000006,0x00001d7d,0x00001d83, -0x00001d7c,0x00050084,0x00000006,0x00001d1e, -0x000000df,0x0000123e,0x00050080,0x00000006, -0x00001d1f,0x00001d7d,0x00001d1e,0x00050041, -0x0000022d,0x00001d20,0x00000180,0x0000022b, -0x0004003d,0x00000007,0x00001d21,0x00001d20, -0x00050051,0x00000006,0x00001e34,0x00001d21, -0x00000000,0x00050095,0x00000130,0x00001e36, -0x00001e34,0x00001d1f,0x00050051,0x00000006, -0x00001e37,0x00001e36,0x00000001,0x00050051, -0x00000006,0x00001e38,0x00001e36,0x00000000, -0x00050051,0x00000006,0x00001e3b,0x00001d21, -0x00000001,0x00050080,0x00000006,0x00001e3d, -0x00001e3b,0x00001e37,0x00050050,0x00000007, -0x00001e3e,0x00001e38,0x00001e3d,0x0004007c, -0x00000014,0x00001e2e,0x00001e3e,0x00060041, -0x0000015f,0x00001e25,0x00001e2e,0x0000015e, -0x0000015e,0x0006003d,0x00000006,0x00001e26, -0x00001e25,0x00000002,0x00000004,0x00050084, -0x00000006,0x00001d24,0x0000123e,0x00000185, -0x00050080,0x00000006,0x00001d26,0x00001d24, -0x00000185,0x000300f7,0x00001e4a,0x00000000, -0x000400fa,0x00001dcf,0x00001e45,0x00001e49, -0x000200f8,0x00001e49,0x000200f9,0x00001e4a, -0x000200f8,0x00001e45,0x00050082,0x00000006, -0x00001e48,0x00001da7,0x00000135,0x000200f9, -0x00001e4a,0x000200f8,0x00001e4a,0x000700f5, -0x00000006,0x00005b1b,0x00001e48,0x00001e45, -0x0000012b,0x00001e49,0x0007000c,0x00000006, -0x00001d28,0x00000001,0x00000026,0x00001d26, -0x00005b1b,0x000200f9,0x00001d2a,0x000200f8, -0x00001d2a,0x000700f5,0x00000006,0x00005b2f, -0x00001e26,0x00001e4a,0x00001d73,0x00001d74, -0x000700f5,0x00000006,0x00005b1c,0x00001d24, -0x00001e4a,0x00001d76,0x00001d74,0x000500b0, -0x0000002f,0x00001d2e,0x00005b1c,0x00001d28, -0x000400f6,0x00001d77,0x00001d74,0x00000000, -0x000400fa,0x00001d2e,0x00001d2f,0x00001d77, -0x000200f8,0x00001d2f,0x00050080,0x00000006, -0x00001d32,0x00005b1c,0x00001241,0x000500b0, -0x0000002f,0x00001d35,0x00001d32,0x00001d28, -0x000300f7,0x00001d3f,0x00000000,0x000400fa, -0x00001d35,0x00001d36,0x00001d3e,0x000200f8, -0x00001d3e,0x000200f9,0x00001d3f,0x000200f8, -0x00001d36,0x000300f7,0x00001e97,0x00000000, -0x000400fa,0x00001dcf,0x00001e92,0x00001e96, -0x000200f8,0x00001e96,0x000200f9,0x00001e97, -0x000200f8,0x00001e92,0x00050082,0x00000006, -0x00001e95,0x00001da7,0x00000135,0x000200f9, -0x00001e97,0x000200f8,0x00001e97,0x000700f5, -0x00000006,0x00005b1d,0x00001e95,0x00001e92, -0x0000012b,0x00001e96,0x00050084,0x00000006, -0x00001e5c,0x000000df,0x00005b1d,0x00050080, -0x00000006,0x00001e5d,0x00001da2,0x00001e5c, -0x000300f7,0x00001ea4,0x00000000,0x000400fa, -0x00001dcf,0x00001e9f,0x00001ea3,0x000200f8, -0x00001ea3,0x000200f9,0x00001ea4,0x000200f8, -0x00001e9f,0x00050082,0x00000006,0x00001ea2, -0x00001da7,0x00000135,0x000200f9,0x00001ea4, -0x000200f8,0x00001ea4,0x000700f5,0x00000006, -0x00005b1e,0x00001ea2,0x00001e9f,0x0000012b, -0x00001ea3,0x00050084,0x00000006,0x00001e56, -0x000000df,0x00005b1e,0x00050080,0x00000006, -0x00001e57,0x00001e5d,0x00001e56,0x000300f7, -0x00001eb1,0x00000000,0x000400fa,0x00001dcf, -0x00001eac,0x00001eb0,0x000200f8,0x00001eb0, -0x000200f9,0x00001eb1,0x000200f8,0x00001eac, -0x00050082,0x00000006,0x00001eaf,0x00001da7, -0x00000135,0x000200f9,0x00001eb1,0x000200f8, -0x00001eb1,0x000700f5,0x00000006,0x00005b1f, -0x00001eaf,0x00001eac,0x0000012b,0x00001eb0, -0x00050084,0x00000006,0x00001e50,0x000000df, -0x00005b1f,0x00050080,0x00000006,0x00001e51, -0x00001e57,0x00001e50,0x00050084,0x00000006, -0x00001d39,0x000000df,0x00001d32,0x00050080, -0x00000006,0x00001d3a,0x00001e51,0x00001d39, -0x00050095,0x00000130,0x00001ecb,0x00001e34, -0x00001d3a,0x00050051,0x00000006,0x00001ecc, -0x00001ecb,0x00000001,0x00050051,0x00000006, -0x00001ecd,0x00001ecb,0x00000000,0x00050080, -0x00000006,0x00001ed2,0x00001e3b,0x00001ecc, -0x00050050,0x00000007,0x00001ed3,0x00001ecd, -0x00001ed2,0x0004007c,0x00000014,0x00001ec3, -0x00001ed3,0x00060041,0x0000015f,0x00001eba, -0x00001ec3,0x0000015e,0x0000015e,0x0006003d, -0x00000006,0x00001ebb,0x00001eba,0x00000002, -0x00000004,0x000200f9,0x00001d3f,0x000200f8, -0x00001d3f,0x000700f5,0x00000006,0x00005b20, -0x00001ebb,0x00001eb1,0x0000012b,0x00001d3e, -0x00050041,0x00000838,0x00001d43,0x00000e00, -0x00001241,0x0003003e,0x00001d43,0x00005b20, -0x000400e0,0x00000247,0x00000247,0x00000850, -0x000200f9,0x00001d44,0x000200f8,0x00001d44, -0x000700f5,0x00000006,0x00005b21,0x00000135, -0x00001d3f,0x00001d5d,0x00001d5b,0x000500b0, -0x0000002f,0x00001d47,0x00005b21,0x0000018b, -0x000400f6,0x00001d5e,0x00001d5b,0x00000000, -0x000400fa,0x00001d47,0x00001d48,0x00001d5e, -0x000200f8,0x00001d48,0x000500ae,0x0000002f, -0x00001d4b,0x00001241,0x00005b21,0x000300f7, -0x00001d53,0x00000000,0x000400fa,0x00001d4b, -0x00001d4c,0x00001d52,0x000200f8,0x00001d52, -0x000200f9,0x00001d53,0x000200f8,0x00001d4c, -0x00050082,0x00000006,0x00001d4f,0x00001241, -0x00005b21,0x00050041,0x00000838,0x00001d50, -0x00000e00,0x00001d4f,0x0004003d,0x00000006, -0x00001d51,0x00001d50,0x000200f9,0x00001d53, -0x000200f8,0x00001d53,0x000700f5,0x00000006, -0x00005b3c,0x00001d51,0x00001d4c,0x0000012b, -0x00001d52,0x000400e0,0x00000247,0x00000247, -0x00000850,0x0004003d,0x00000006,0x00001d58, -0x00001d43,0x00050080,0x00000006,0x00001d59, -0x00001d58,0x00005b3c,0x0003003e,0x00001d43, -0x00001d59,0x000400e0,0x00000247,0x00000247, -0x00000850,0x000200f9,0x00001d5b,0x000200f8, -0x00001d5b,0x000500c4,0x00000006,0x00001d5d, -0x00005b21,0x0000022b,0x000200f9,0x00001d44, -0x000200f8,0x00001d5e,0x000500ab,0x0000002f, -0x00001d60,0x00005b20,0x0000012b,0x000300f7, -0x00001d6f,0x00000000,0x000400fa,0x00001d60, -0x00001d61,0x00001d6f,0x000200f8,0x00001d61, -0x000300f7,0x00001f25,0x00000000,0x000400fa, -0x00001dcf,0x00001f20,0x00001f24,0x000200f8, -0x00001f24,0x000200f9,0x00001f25,0x000200f8, -0x00001f20,0x00050082,0x00000006,0x00001f23, -0x00001da7,0x00000135,0x000200f9,0x00001f25, -0x000200f8,0x00001f25,0x000700f5,0x00000006, -0x00005b22,0x00001f23,0x00001f20,0x0000012b, -0x00001f24,0x00050084,0x00000006,0x00001eea, -0x000000df,0x00005b22,0x00050080,0x00000006, -0x00001eeb,0x00001da2,0x00001eea,0x000300f7, -0x00001f32,0x00000000,0x000400fa,0x00001dcf, -0x00001f2d,0x00001f31,0x000200f8,0x00001f31, -0x000200f9,0x00001f32,0x000200f8,0x00001f2d, -0x00050082,0x00000006,0x00001f30,0x00001da7, -0x00000135,0x000200f9,0x00001f32,0x000200f8, -0x00001f32,0x000700f5,0x00000006,0x00005b23, -0x00001f30,0x00001f2d,0x0000012b,0x00001f31, -0x00050084,0x00000006,0x00001ee4,0x000000df, -0x00005b23,0x00050080,0x00000006,0x00001ee5, -0x00001eeb,0x00001ee4,0x000300f7,0x00001f3f, -0x00000000,0x000400fa,0x00001dcf,0x00001f3a, -0x00001f3e,0x000200f8,0x00001f3e,0x000200f9, -0x00001f3f,0x000200f8,0x00001f3a,0x00050082, -0x00000006,0x00001f3d,0x00001da7,0x00000135, -0x000200f9,0x00001f3f,0x000200f8,0x00001f3f, -0x000700f5,0x00000006,0x00005b24,0x00001f3d, -0x00001f3a,0x0000012b,0x00001f3e,0x00050084, -0x00000006,0x00001ede,0x000000df,0x00005b24, -0x00050080,0x00000006,0x00001edf,0x00001ee5, -0x00001ede,0x000300f7,0x00001f4c,0x00000000, -0x000400fa,0x00001dcf,0x00001f47,0x00001f4b, -0x000200f8,0x00001f4b,0x000200f9,0x00001f4c, -0x000200f8,0x00001f47,0x00050082,0x00000006, -0x00001f4a,0x00001da7,0x00000135,0x000200f9, -0x00001f4c,0x000200f8,0x00001f4c,0x000700f5, -0x00000006,0x00005b25,0x00001f4a,0x00001f47, -0x0000012b,0x00001f4b,0x00050084,0x00000006, -0x00001ed8,0x000000df,0x00005b25,0x00050080, -0x00000006,0x00001ed9,0x00001edf,0x00001ed8, -0x00050084,0x00000006,0x00001d64,0x000000df, -0x00001d32,0x00050080,0x00000006,0x00001d65, -0x00001ed9,0x00001d64,0x0004003d,0x00000006, -0x00001d69,0x00001d43,0x00050080,0x00000006, -0x00001d6a,0x00005b2f,0x00001d69,0x00050082, -0x00000006,0x00001d6b,0x00001d6a,0x00000135, -0x00050095,0x00000130,0x00001f65,0x00001e34, -0x00001d65,0x00050051,0x00000006,0x00001f66, -0x00001f65,0x00000001,0x00050051,0x00000006, -0x00001f67,0x00001f65,0x00000000,0x00050080, -0x00000006,0x00001f6c,0x00001e3b,0x00001f66, -0x00050050,0x00000007,0x00001f6d,0x00001f67, -0x00001f6c,0x0004007c,0x00000014,0x00001f5d, -0x00001f6d,0x00060041,0x0000015f,0x00001f55, -0x00001f5d,0x0000015e,0x0000015e,0x0005003e, -0x00001f55,0x00001d6b,0x00000002,0x00000004, -0x000200f9,0x00001d6f,0x000200f8,0x00001d6f, -0x00050041,0x00000838,0x00001d70,0x00000e00, -0x00000a9c,0x0004003d,0x00000006,0x00001d71, -0x00001d70,0x00050080,0x00000006,0x00001d73, -0x00005b2f,0x00001d71,0x000400e0,0x00000247, -0x00000247,0x00000850,0x000200f9,0x00001d74, -0x000200f8,0x00001d74,0x00050080,0x00000006, -0x00001d76,0x00005b1c,0x0000018b,0x000200f9, -0x00001d2a,0x000200f8,0x00001d77,0x000200f9, -0x000012fe,0x000200f8,0x0000123b,0x000500aa, -0x0000002f,0x00001246,0x000011e0,0x0000031c, -0x000300f7,0x00001248,0x00000000,0x000400fa, -0x00001246,0x00001247,0x00001248,0x000200f8, -0x00001247,0x000500aa,0x0000002f,0x0000124a, -0x000011de,0x0000012b,0x000300f7,0x0000124c, -0x00000000,0x000400fa,0x0000124a,0x0000124b, -0x0000124c,0x000200f8,0x0000124b,0x000300f7, -0x00002028,0x00000000,0x000300fb,0x0000012b, -0x00001faf,0x000200f8,0x00001faf,0x000300f7, -0x00002063,0x00000000,0x000300fb,0x0000012b, -0x00002035,0x000200f8,0x00002035,0x00050041, -0x00000182,0x00002084,0x00000180,0x00000181, -0x0004003d,0x00000006,0x00002085,0x00002084, -0x00050084,0x00000006,0x00002086,0x000001a2, -0x00002085,0x00050080,0x00000006,0x00002087, -0x0000018b,0x00002086,0x00050080,0x00000006, -0x0000208d,0x00002085,0x00005cc3,0x00050086, -0x00000006,0x0000208e,0x0000208d,0x00000185, -0x00050084,0x00000006,0x00002080,0x0000018b, -0x0000208e,0x00050080,0x00000006,0x00002081, -0x00002087,0x00002080,0x00050080,0x00000006, -0x0000207b,0x00002081,0x00002080,0x00050041, -0x00000182,0x00002072,0x00000180,0x000001b7, -0x0004003d,0x00000006,0x00002073,0x00002072, -0x00050084,0x00000006,0x00002074,0x000001b6, -0x00002073,0x00050080,0x00000006,0x00002075, -0x0000207b,0x00002074,0x00050041,0x0000022d, -0x0000206c,0x00000180,0x0000022b,0x0004003d, -0x00000007,0x0000206d,0x0000206c,0x00050051, -0x00000006,0x000020a3,0x0000206d,0x00000000, -0x00050095,0x00000130,0x000020a5,0x000020a3, -0x00002075,0x00050051,0x00000006,0x000020a6, -0x000020a5,0x00000001,0x00050051,0x00000006, -0x000020a7,0x000020a5,0x00000000,0x00050051, -0x00000006,0x000020aa,0x0000206d,0x00000001, -0x00050080,0x00000006,0x000020ac,0x000020aa, -0x000020a6,0x00050050,0x00000007,0x000020ad, -0x000020a7,0x000020ac,0x0004007c,0x00000014, -0x0000209d,0x000020ad,0x000200f9,0x00002038, -0x000200f8,0x00002038,0x000700f5,0x00000006, -0x00005b05,0x0000012b,0x00002035,0x00002046, -0x0000203c,0x000500b0,0x0000002f,0x0000203b, -0x00005b05,0x0000031c,0x000400f6,0x00002047, -0x0000203c,0x00000000,0x000400fa,0x0000203b, -0x0000203c,0x00002047,0x000200f8,0x0000203c, -0x00050080,0x00000006,0x00002040,0x00000135, -0x00005b05,0x00060041,0x0000015f,0x00002041, -0x0000209d,0x0000015e,0x00002040,0x000700f1, -0x00000006,0x00002042,0x00002041,0x00000135, -0x0000012b,0x0000012b,0x00050041,0x00000009, -0x00002043,0x0000202d,0x00005b05,0x0003003e, -0x00002043,0x00002042,0x00050080,0x00000006, -0x00002046,0x00005b05,0x0000022b,0x000200f9, -0x00002038,0x000200f8,0x00002047,0x00050041, -0x00000009,0x00002048,0x0000202d,0x0000015e, -0x0004003d,0x00000006,0x00002049,0x00002048, -0x000500aa,0x0000002f,0x0000204a,0x00002049, -0x00000500,0x000300f7,0x0000204e,0x00000000, -0x000400fa,0x0000204a,0x0000204b,0x0000204e, -0x000200f8,0x0000204b,0x000200f9,0x00002063, -0x000200f8,0x0000204e,0x0004003d,0x00000006, -0x00002050,0x00002048,0x000500c7,0x00000006, -0x000020b2,0x00002050,0x00000208,0x000500ab, -0x0000002f,0x000020b3,0x000020b2,0x0000012b, -0x000300f7,0x000020ba,0x00000000,0x000400fa, -0x000020b3,0x000020b4,0x000020b7,0x000200f8, -0x000020b7,0x000400c8,0x00000006,0x000020b9, -0x00002050,0x000200f9,0x000020ba,0x000200f8, -0x000020b4,0x000500c7,0x00000006,0x000020b6, -0x00002050,0x0000021d,0x000200f9,0x000020ba, -0x000200f8,0x000020ba,0x000700f5,0x00000006, -0x00005b06,0x000020b6,0x000020b4,0x000020b9, -0x000020b7,0x0004007c,0x00000027,0x000020bc, -0x00005b06,0x00050041,0x00000009,0x00002052, -0x0000202d,0x0000022b,0x0004003d,0x00000006, -0x00002053,0x00002052,0x000500c7,0x00000006, -0x000020c1,0x00002053,0x00000208,0x000500ab, -0x0000002f,0x000020c2,0x000020c1,0x0000012b, -0x000300f7,0x000020c9,0x00000000,0x000400fa, -0x000020c2,0x000020c3,0x000020c6,0x000200f8, -0x000020c6,0x000400c8,0x00000006,0x000020c8, -0x00002053,0x000200f9,0x000020c9,0x000200f8, -0x000020c3,0x000500c7,0x00000006,0x000020c5, -0x00002053,0x0000021d,0x000200f9,0x000020c9, -0x000200f8,0x000020c9,0x000700f5,0x00000006, -0x00005b07,0x000020c5,0x000020c3,0x000020c8, -0x000020c6,0x0004007c,0x00000027,0x000020cb, -0x00005b07,0x00050041,0x00000009,0x00002055, -0x0000202d,0x000002dc,0x0004003d,0x00000006, -0x00002056,0x00002055,0x000500c7,0x00000006, -0x000020d0,0x00002056,0x00000208,0x000500ab, -0x0000002f,0x000020d1,0x000020d0,0x0000012b, -0x000300f7,0x000020d8,0x00000000,0x000400fa, -0x000020d1,0x000020d2,0x000020d5,0x000200f8, -0x000020d5,0x000400c8,0x00000006,0x000020d7, -0x00002056,0x000200f9,0x000020d8,0x000200f8, -0x000020d2,0x000500c7,0x00000006,0x000020d4, -0x00002056,0x0000021d,0x000200f9,0x000020d8, -0x000200f8,0x000020d8,0x000700f5,0x00000006, -0x00005b08,0x000020d4,0x000020d2,0x000020d7, -0x000020d5,0x0004007c,0x00000027,0x000020da, -0x00005b08,0x00060050,0x00000063,0x00002058, -0x000020bc,0x000020cb,0x000020da,0x00050041, -0x00000009,0x00002059,0x0000202d,0x000002e4, -0x0004003d,0x00000006,0x0000205a,0x00002059, -0x000500c7,0x00000006,0x000020df,0x0000205a, -0x00000208,0x000500ab,0x0000002f,0x000020e0, -0x000020df,0x0000012b,0x000300f7,0x000020e7, -0x00000000,0x000400fa,0x000020e0,0x000020e1, -0x000020e4,0x000200f8,0x000020e4,0x000400c8, -0x00000006,0x000020e6,0x0000205a,0x000200f9, -0x000020e7,0x000200f8,0x000020e1,0x000500c7, -0x00000006,0x000020e3,0x0000205a,0x0000021d, -0x000200f9,0x000020e7,0x000200f8,0x000020e7, -0x000700f5,0x00000006,0x00005b09,0x000020e3, -0x000020e1,0x000020e6,0x000020e4,0x0004007c, -0x00000027,0x000020e9,0x00005b09,0x00050041, -0x00000009,0x0000205c,0x0000202d,0x000002ec, -0x0004003d,0x00000006,0x0000205d,0x0000205c, -0x000500c7,0x00000006,0x000020ee,0x0000205d, -0x00000208,0x000500ab,0x0000002f,0x000020ef, -0x000020ee,0x0000012b,0x000300f7,0x000020f6, -0x00000000,0x000400fa,0x000020ef,0x000020f0, -0x000020f3,0x000200f8,0x000020f3,0x000400c8, -0x00000006,0x000020f5,0x0000205d,0x000200f9, -0x000020f6,0x000200f8,0x000020f0,0x000500c7, -0x00000006,0x000020f2,0x0000205d,0x0000021d, -0x000200f9,0x000020f6,0x000200f8,0x000020f6, -0x000700f5,0x00000006,0x00005b0a,0x000020f2, -0x000020f0,0x000020f5,0x000020f3,0x0004007c, -0x00000027,0x000020f8,0x00005b0a,0x00050041, -0x00000009,0x0000205f,0x0000202d,0x000002f4, -0x0004003d,0x00000006,0x00002060,0x0000205f, -0x000500c7,0x00000006,0x000020fd,0x00002060, -0x00000208,0x000500ab,0x0000002f,0x000020fe, -0x000020fd,0x0000012b,0x000300f7,0x00002105, -0x00000000,0x000400fa,0x000020fe,0x000020ff, -0x00002102,0x000200f8,0x00002102,0x000400c8, -0x00000006,0x00002104,0x00002060,0x000200f9, -0x00002105,0x000200f8,0x000020ff,0x000500c7, -0x00000006,0x00002101,0x00002060,0x0000021d, -0x000200f9,0x00002105,0x000200f8,0x00002105, -0x000700f5,0x00000006,0x00005b0b,0x00002101, -0x000020ff,0x00002104,0x00002102,0x0004007c, -0x00000027,0x00002107,0x00005b0b,0x00060050, -0x00000063,0x00002062,0x000020e9,0x000020f8, -0x00002107,0x000200f9,0x00002063,0x000200f8, -0x00002063,0x000700f5,0x00000063,0x00005b10, -0x00005cc2,0x0000204b,0x00002062,0x00002105, -0x000700f5,0x00000063,0x00005b0c,0x0000053d, -0x0000204b,0x00002058,0x00002105,0x00050041, -0x0000022d,0x00001fb3,0x00000180,0x0000015e, -0x0004003d,0x00000007,0x00001fb4,0x00001fb3, -0x00050051,0x00000027,0x00001fb6,0x00005b0c, -0x00000000,0x0004007c,0x00000006,0x0000210d, -0x00001fb6,0x00050051,0x00000006,0x00002126, -0x00001fb4,0x00000000,0x00050095,0x00000130, -0x00002128,0x00002126,0x000001a2,0x00050051, -0x00000006,0x00002129,0x00002128,0x00000001, -0x00050051,0x00000006,0x0000212a,0x00002128, -0x00000000,0x00050051,0x00000006,0x0000212d, -0x00001fb4,0x00000001,0x00050080,0x00000006, -0x0000212f,0x0000212d,0x00002129,0x00050050, -0x00000007,0x00002130,0x0000212a,0x0000212f, -0x0004007c,0x00000014,0x00002120,0x00002130, -0x00060041,0x0000015f,0x00002118,0x00002120, -0x0000015e,0x0000015e,0x0005003e,0x00002118, -0x0000210d,0x00000002,0x00000004,0x00050051, -0x00000027,0x00001fbb,0x00005b0c,0x00000001, -0x0004007c,0x00000006,0x00002136,0x00001fbb, -0x00050095,0x00000130,0x00002151,0x00002126, -0x00000260,0x00050051,0x00000006,0x00002152, -0x00002151,0x00000001,0x00050051,0x00000006, -0x00002153,0x00002151,0x00000000,0x00050080, -0x00000006,0x00002158,0x0000212d,0x00002152, -0x00050050,0x00000007,0x00002159,0x00002153, -0x00002158,0x0004007c,0x00000014,0x00002149, -0x00002159,0x00060041,0x0000015f,0x00002141, -0x00002149,0x0000015e,0x0000015e,0x0005003e, -0x00002141,0x00002136,0x00000002,0x00000004, -0x00050051,0x00000027,0x00001fc0,0x00005b0c, -0x00000002,0x0004007c,0x00000006,0x0000215f, -0x00001fc0,0x00050095,0x00000130,0x0000217a, -0x00002126,0x000001b6,0x00050051,0x00000006, -0x0000217b,0x0000217a,0x00000001,0x00050051, -0x00000006,0x0000217c,0x0000217a,0x00000000, -0x00050080,0x00000006,0x00002181,0x0000212d, -0x0000217b,0x00050050,0x00000007,0x00002182, -0x0000217c,0x00002181,0x0004007c,0x00000014, -0x00002172,0x00002182,0x00060041,0x0000015f, -0x0000216a,0x00002172,0x0000015e,0x0000015e, -0x0005003e,0x0000216a,0x0000215f,0x00000002, -0x00000004,0x00050051,0x00000027,0x00001fc5, -0x00005b10,0x00000000,0x0004007c,0x00000006, -0x00002188,0x00001fc5,0x00050095,0x00000130, -0x000021a3,0x00002126,0x000005df,0x00050051, -0x00000006,0x000021a4,0x000021a3,0x00000001, -0x00050051,0x00000006,0x000021a5,0x000021a3, -0x00000000,0x00050080,0x00000006,0x000021aa, -0x0000212d,0x000021a4,0x00050050,0x00000007, -0x000021ab,0x000021a5,0x000021aa,0x0004007c, -0x00000014,0x0000219b,0x000021ab,0x00060041, -0x0000015f,0x00002193,0x0000219b,0x0000015e, -0x0000015e,0x0005003e,0x00002193,0x00002188, -0x00000002,0x00000004,0x00050051,0x00000027, -0x00001fca,0x00005b10,0x00000001,0x0004007c, -0x00000006,0x000021b1,0x00001fca,0x00050095, -0x00000130,0x000021cc,0x00002126,0x000001cc, -0x00050051,0x00000006,0x000021cd,0x000021cc, -0x00000001,0x00050051,0x00000006,0x000021ce, -0x000021cc,0x00000000,0x00050080,0x00000006, -0x000021d3,0x0000212d,0x000021cd,0x00050050, -0x00000007,0x000021d4,0x000021ce,0x000021d3, -0x0004007c,0x00000014,0x000021c4,0x000021d4, -0x00060041,0x0000015f,0x000021bc,0x000021c4, -0x0000015e,0x0000015e,0x0005003e,0x000021bc, -0x000021b1,0x00000002,0x00000004,0x00050051, -0x00000027,0x00001fcf,0x00005b10,0x00000002, -0x0004007c,0x00000006,0x000021da,0x00001fcf, -0x00050095,0x00000130,0x000021f5,0x00002126, -0x000004c7,0x00050051,0x00000006,0x000021f6, -0x000021f5,0x00000001,0x00050051,0x00000006, -0x000021f7,0x000021f5,0x00000000,0x00050080, -0x00000006,0x000021fc,0x0000212d,0x000021f6, -0x00050050,0x00000007,0x000021fd,0x000021f7, -0x000021fc,0x0004007c,0x00000014,0x000021ed, -0x000021fd,0x00060041,0x0000015f,0x000021e5, -0x000021ed,0x0000015e,0x0000015e,0x0005003e, -0x000021e5,0x000021da,0x00000002,0x00000004, -0x00050041,0x00000182,0x00001fd1,0x00000180, -0x000003fb,0x0004003d,0x00000006,0x00001fd2, -0x00001fd1,0x000500aa,0x0000002f,0x00001fd3, -0x00001fd2,0x00000135,0x000300f7,0x00001fd5, -0x00000000,0x000400fa,0x00001fd3,0x00001fd4, -0x00001fd5,0x000200f8,0x00001fd4,0x000200f9, -0x00002028,0x000200f8,0x00001fd5,0x000500b2, -0x0000002f,0x00001fd8,0x00002073,0x00000135, -0x000300f7,0x00001fde,0x00000000,0x000400fa, -0x00001fd8,0x00001fd9,0x00001fda,0x000200f8, -0x00001fda,0x00050095,0x00000130,0x00002216, -0x000020a3,0x000001b6,0x00050051,0x00000006, -0x00002217,0x00002216,0x00000001,0x00050051, -0x00000006,0x00002218,0x00002216,0x00000000, -0x00050080,0x00000006,0x0000221d,0x000020aa, -0x00002217,0x00050050,0x00000007,0x0000221e, -0x00002218,0x0000221d,0x0004007c,0x00000014, -0x0000220e,0x0000221e,0x00060041,0x0000015f, -0x00002205,0x0000220e,0x0000015e,0x0000015e, -0x0006003d,0x00000006,0x00002206,0x00002205, -0x00000002,0x00000004,0x000200f9,0x00001fde, -0x000200f8,0x00001fd9,0x000200f9,0x00001fde, -0x000200f8,0x00001fde,0x000700f5,0x00000006, -0x00005b11,0x00000135,0x00001fd9,0x00002206, -0x00001fda,0x00050041,0x00000182,0x00001fe0, -0x00000180,0x00000321,0x0004003d,0x00000006, -0x00001fe1,0x00001fe0,0x00050041,0x00000182, -0x00002225,0x00000180,0x000002fb,0x0004003d, -0x00000006,0x00002226,0x00002225,0x000500c7, -0x00000006,0x00002227,0x00002226,0x00000247, -0x000500ab,0x0000002f,0x00002228,0x00002227, -0x0000012b,0x000600a9,0x00000006,0x00002222, -0x00002228,0x0000018b,0x00000309,0x00050084, -0x00000006,0x00001fe4,0x00002222,0x00005b11, -0x00050080,0x00000006,0x00001fe5,0x00001fe1, -0x00001fe4,0x000300f7,0x00001ffa,0x00000000, -0x000400fa,0x00002228,0x00001fe7,0x00001ffa, -0x000200f8,0x00001fe7,0x000200f9,0x00001fe8, -0x000200f8,0x00001fe8,0x000700f5,0x00000006, -0x00005b12,0x0000012b,0x00001fe7,0x00001ff6, -0x00001fec,0x000500b0,0x0000002f,0x00001feb, -0x00005b12,0x000001a2,0x000400f6,0x00001ff7, -0x00001fec,0x00000000,0x000400fa,0x00001feb, -0x00001fec,0x00001ff7,0x000200f8,0x00001fec, -0x00050084,0x00000006,0x00001fef,0x000000df, -0x00005b12,0x00050080,0x00000006,0x00001ff0, -0x00001fe5,0x00001fef,0x00050095,0x00000130, -0x00002246,0x00002126,0x00001ff0,0x00050051, -0x00000006,0x00002247,0x00002246,0x00000001, -0x00050051,0x00000006,0x00002248,0x00002246, -0x00000000,0x00050080,0x00000006,0x0000224d, -0x0000212d,0x00002247,0x00050050,0x00000007, -0x0000224e,0x00002248,0x0000224d,0x0004007c, -0x00000014,0x0000223e,0x0000224e,0x00060041, -0x0000015f,0x00002236,0x0000223e,0x0000015e, -0x0000015e,0x0005003e,0x00002236,0x0000012b, -0x00000002,0x00000004,0x00050080,0x00000006, -0x00001ff6,0x00005b12,0x0000022b,0x000200f9, -0x00001fe8,0x000200f8,0x00001ff7,0x00050080, -0x00000006,0x00001ff9,0x00001fe5,0x0000018b, -0x000200f9,0x00001ffa,0x000200f8,0x00001ffa, -0x000700f5,0x00000006,0x00005b14,0x00001fe5, -0x00001fde,0x00001ff9,0x00001ff7,0x000500c7, -0x00000006,0x00002253,0x00002226,0x00000135, -0x000500ab,0x0000002f,0x00002254,0x00002253, -0x0000012b,0x000600a9,0x00000006,0x00001ffd, -0x00002254,0x0000031c,0x00005cd3,0x00050095, -0x00000130,0x0000226c,0x00002126,0x0000012b, -0x00050051,0x00000006,0x0000226d,0x0000226c, -0x00000001,0x00050051,0x00000006,0x0000226e, -0x0000226c,0x00000000,0x00050080,0x00000006, -0x00002273,0x0000212d,0x0000226d,0x00050050, -0x00000007,0x00002274,0x0000226e,0x00002273, -0x0004007c,0x00000014,0x00002264,0x00002274, -0x00060041,0x0000015f,0x0000225c,0x00002264, -0x0000015e,0x0000015e,0x0005003e,0x0000225c, -0x00001ffd,0x00000002,0x00000004,0x00050086, -0x00000006,0x00002002,0x00005b14,0x0000018b, -0x00050082,0x00000006,0x00002003,0x00002002, -0x00000135,0x00050095,0x00000130,0x0000228c, -0x00002126,0x000000df,0x00050051,0x00000006, -0x0000228d,0x0000228c,0x00000001,0x00050051, -0x00000006,0x0000228e,0x0000228c,0x00000000, -0x00050080,0x00000006,0x00002293,0x0000212d, -0x0000228d,0x00050050,0x00000007,0x00002294, -0x0000228e,0x00002293,0x0004007c,0x00000014, -0x00002284,0x00002294,0x00060041,0x0000015f, -0x0000227c,0x00002284,0x0000015e,0x0000015e, -0x0005003e,0x0000227c,0x00002003,0x00000002, -0x00000004,0x00050095,0x00000130,0x000022ac, -0x00002126,0x00000194,0x00050051,0x00000006, -0x000022ad,0x000022ac,0x00000001,0x00050051, -0x00000006,0x000022ae,0x000022ac,0x00000000, -0x00050080,0x00000006,0x000022b3,0x0000212d, -0x000022ad,0x00050050,0x00000007,0x000022b4, -0x000022ae,0x000022b3,0x0004007c,0x00000014, -0x000022a4,0x000022b4,0x00060041,0x0000015f, -0x0000229c,0x000022a4,0x0000015e,0x0000015e, -0x0005003e,0x0000229c,0x0000012b,0x00000002, -0x00000004,0x00050095,0x00000130,0x000022cc, -0x00002126,0x0000019b,0x00050051,0x00000006, -0x000022cd,0x000022cc,0x00000001,0x00050051, -0x00000006,0x000022ce,0x000022cc,0x00000000, -0x00050080,0x00000006,0x000022d3,0x0000212d, -0x000022cd,0x00050050,0x00000007,0x000022d4, -0x000022ce,0x000022d3,0x0004007c,0x00000014, -0x000022c4,0x000022d4,0x00060041,0x0000015f, -0x000022bc,0x000022c4,0x0000015e,0x0000015e, -0x0005003e,0x000022bc,0x00002073,0x00000002, -0x00000004,0x00050095,0x00000130,0x000022ec, -0x00002126,0x000004d2,0x00050051,0x00000006, -0x000022ed,0x000022ec,0x00000001,0x00050051, -0x00000006,0x000022ee,0x000022ec,0x00000000, -0x00050080,0x00000006,0x000022f3,0x0000212d, -0x000022ed,0x00050050,0x00000007,0x000022f4, -0x000022ee,0x000022f3,0x0004007c,0x00000014, -0x000022e4,0x000022f4,0x00060041,0x0000015f, -0x000022dc,0x000022e4,0x0000015e,0x0000015e, -0x0005003e,0x000022dc,0x00001fe1,0x00000002, -0x00000004,0x00050095,0x00000130,0x0000230c, -0x00002126,0x000004dd,0x00050051,0x00000006, -0x0000230d,0x0000230c,0x00000001,0x00050051, -0x00000006,0x0000230e,0x0000230c,0x00000000, -0x00050080,0x00000006,0x00002313,0x0000212d, -0x0000230d,0x00050050,0x00000007,0x00002314, -0x0000230e,0x00002313,0x0004007c,0x00000014, -0x00002304,0x00002314,0x00060041,0x0000015f, -0x000022fc,0x00002304,0x0000015e,0x0000015e, -0x0005003e,0x000022fc,0x0000012b,0x00000002, -0x00000004,0x000500c2,0x00000006,0x0000231d, -0x00001fe1,0x00000318,0x000500c4,0x00000006, -0x0000231e,0x0000231d,0x000002e4,0x000600a9, -0x00000006,0x00002320,0x00002228,0x000000df, -0x0000032b,0x000500c5,0x00000006,0x00002321, -0x0000231e,0x00002320,0x00050095,0x00000130, -0x00002349,0x00002126,0x000004e8,0x00050051, -0x00000006,0x0000234a,0x00002349,0x00000001, -0x00050051,0x00000006,0x0000234b,0x00002349, -0x00000000,0x00050080,0x00000006,0x00002350, -0x0000212d,0x0000234a,0x00050050,0x00000007, -0x00002351,0x0000234b,0x00002350,0x0004007c, -0x00000014,0x00002341,0x00002351,0x00060041, -0x0000015f,0x00002339,0x00002341,0x0000015e, -0x0000015e,0x0005003e,0x00002339,0x00002321, -0x00000002,0x00000004,0x00050041,0x00000182, -0x0000201d,0x00000180,0x00000311,0x0004003d, -0x00000006,0x0000201e,0x0000201d,0x00050095, -0x00000130,0x00002369,0x00002126,0x000004f4, -0x00050051,0x00000006,0x0000236a,0x00002369, -0x00000001,0x00050051,0x00000006,0x0000236b, -0x00002369,0x00000000,0x00050080,0x00000006, -0x00002370,0x0000212d,0x0000236a,0x00050050, -0x00000007,0x00002371,0x0000236b,0x00002370, -0x0004007c,0x00000014,0x00002361,0x00002371, -0x00060041,0x0000015f,0x00002359,0x00002361, -0x0000015e,0x0000015e,0x0005003e,0x00002359, -0x0000201e,0x00000002,0x00000004,0x00050041, -0x00000182,0x00002022,0x00000180,0x00000fbf, -0x0004003d,0x00000006,0x00002023,0x00002022, -0x00050095,0x00000130,0x00002389,0x00002126, -0x000004fe,0x00050051,0x00000006,0x0000238a, -0x00002389,0x00000001,0x00050051,0x00000006, -0x0000238b,0x00002389,0x00000000,0x00050080, -0x00000006,0x00002390,0x0000212d,0x0000238a, -0x00050050,0x00000007,0x00002391,0x0000238b, -0x00002390,0x0004007c,0x00000014,0x00002381, -0x00002391,0x00060041,0x0000015f,0x00002379, -0x00002381,0x0000015e,0x0000015e,0x0005003e, -0x00002379,0x00002023,0x00000002,0x00000004, -0x00050095,0x00000130,0x000023a9,0x00002126, -0x00000508,0x00050051,0x00000006,0x000023aa, -0x000023a9,0x00000001,0x00050051,0x00000006, -0x000023ab,0x000023a9,0x00000000,0x00050080, -0x00000006,0x000023b0,0x0000212d,0x000023aa, -0x00050050,0x00000007,0x000023b1,0x000023ab, -0x000023b0,0x0004007c,0x00000014,0x000023a1, -0x000023b1,0x00060041,0x0000015f,0x00002399, -0x000023a1,0x0000015e,0x0000015e,0x0005003e, -0x00002399,0x0000012b,0x00000002,0x00000004, -0x000200f9,0x00002028,0x000200f8,0x00002028, -0x000200f9,0x0000124c,0x000200f8,0x0000124c, -0x000200f9,0x000012fe,0x000200f8,0x00001248, -0x00050041,0x00000182,0x00001250,0x00000180, -0x00000653,0x0004003d,0x00000006,0x00001251, -0x00001250,0x000500ae,0x0000002f,0x00001252, -0x000011de,0x00001251,0x000300f7,0x00001254, -0x00000000,0x000400fa,0x00001252,0x00001253, -0x00001254,0x000200f8,0x00001253,0x000200f9, -0x000012fe,0x000200f8,0x00001254,0x000500aa, -0x0000002f,0x00001259,0x000011e0,0x00001258, -0x000300f7,0x0000125b,0x00000000,0x000400fa, -0x00001259,0x0000125a,0x0000125b,0x000200f8, -0x0000125a,0x000500aa,0x0000002f,0x0000125d, -0x000011de,0x0000012b,0x000300f7,0x0000125f, -0x00000000,0x000400fa,0x0000125d,0x0000125e, -0x0000125f,0x000200f8,0x0000125e,0x00050041, -0x0000022d,0x00001261,0x00000180,0x000002dc, -0x0004003d,0x00000007,0x00001262,0x00001261, -0x00050051,0x00000006,0x000023c8,0x00001262, -0x00000000,0x00050095,0x00000130,0x000023ca, -0x000023c8,0x000000df,0x00050051,0x00000006, -0x000023cb,0x000023ca,0x00000001,0x00050051, -0x00000006,0x000023cc,0x000023ca,0x00000000, -0x00050051,0x00000006,0x000023cf,0x00001262, -0x00000001,0x00050080,0x00000006,0x000023d1, -0x000023cf,0x000023cb,0x00050050,0x00000007, -0x000023d2,0x000023cc,0x000023d1,0x0004007c, -0x00000014,0x000023c2,0x000023d2,0x00060041, -0x0000015f,0x000023b9,0x000023c2,0x0000015e, -0x0000015e,0x0006003d,0x00000006,0x000023ba, -0x000023b9,0x00000002,0x00000004,0x00050080, -0x00000006,0x00001265,0x000023ba,0x00000135, -0x00050084,0x00000006,0x00001266,0x00001265, -0x0000018b,0x00050041,0x0000022d,0x00001268, -0x00000180,0x0000015e,0x0004003d,0x00000007, -0x00001269,0x00001268,0x00050051,0x00000006, -0x000023e8,0x00001269,0x00000000,0x00050095, -0x00000130,0x000023ea,0x000023e8,0x0000012b, -0x00050051,0x00000006,0x000023eb,0x000023ea, -0x00000001,0x00050051,0x00000006,0x000023ec, -0x000023ea,0x00000000,0x00050051,0x00000006, -0x000023ef,0x00001269,0x00000001,0x00050080, -0x00000006,0x000023f1,0x000023ef,0x000023eb, -0x00050050,0x00000007,0x000023f2,0x000023ec, -0x000023f1,0x0004007c,0x00000014,0x000023e2, -0x000023f2,0x00060041,0x0000015f,0x000023da, -0x000023e2,0x0000015e,0x0000015e,0x0005003e, -0x000023da,0x00001266,0x00000002,0x00000004, -0x00050095,0x00000130,0x0000240a,0x000023e8, -0x000000df,0x00050051,0x00000006,0x0000240b, -0x0000240a,0x00000001,0x00050051,0x00000006, -0x0000240c,0x0000240a,0x00000000,0x00050080, -0x00000006,0x00002411,0x000023ef,0x0000240b, -0x00050050,0x00000007,0x00002412,0x0000240c, -0x00002411,0x0004007c,0x00000014,0x00002402, -0x00002412,0x00060041,0x0000015f,0x000023fa, -0x00002402,0x0000015e,0x0000015e,0x0005003e, -0x000023fa,0x0000012b,0x00000002,0x00000004, -0x000200f9,0x0000125f,0x000200f8,0x0000125f, -0x000200f9,0x000012fe,0x000200f8,0x0000125b, -0x000500aa,0x0000002f,0x00001276,0x000011e0, -0x0000019b,0x000300f7,0x00001278,0x00000000, -0x000400fa,0x00001276,0x00001277,0x00001278, -0x000200f8,0x00001277,0x00050084,0x00000006, -0x0000127a,0x000000df,0x000011de,0x00050041, -0x0000022d,0x0000127c,0x00000180,0x000002dc, -0x0004003d,0x00000007,0x0000127d,0x0000127c, -0x00050051,0x00000006,0x00002429,0x0000127d, -0x00000000,0x00050095,0x00000130,0x0000242b, -0x00002429,0x000000df,0x00050051,0x00000006, -0x0000242c,0x0000242b,0x00000001,0x00050051, -0x00000006,0x0000242d,0x0000242b,0x00000000, -0x00050051,0x00000006,0x00002430,0x0000127d, -0x00000001,0x00050080,0x00000006,0x00002432, -0x00002430,0x0000242c,0x00050050,0x00000007, -0x00002433,0x0000242d,0x00002432,0x0004007c, -0x00000014,0x00002423,0x00002433,0x00060041, -0x0000015f,0x0000241a,0x00002423,0x0000015e, -0x0000015e,0x0006003d,0x00000006,0x0000241b, -0x0000241a,0x00000002,0x00000004,0x00050080, -0x00000006,0x00001280,0x0000241b,0x00000135, -0x00050084,0x00000006,0x00001281,0x00001280, -0x0000018b,0x000500b0,0x0000002f,0x00001282, -0x0000127a,0x00001281,0x000300f7,0x00001284, -0x00000000,0x000400fa,0x00001282,0x00001283, -0x00001284,0x000200f8,0x00001283,0x00050095, -0x00000130,0x0000244c,0x00002429,0x0000127a, -0x00050051,0x00000006,0x0000244d,0x0000244c, -0x00000001,0x00050051,0x00000006,0x0000244e, -0x0000244c,0x00000000,0x00050080,0x00000006, -0x00002453,0x00002430,0x0000244d,0x00050050, -0x00000007,0x00002454,0x0000244e,0x00002453, -0x0004007c,0x00000014,0x00002444,0x00002454, -0x00060041,0x0000015f,0x0000243b,0x00002444, -0x0000015e,0x0000015e,0x0006003d,0x00000006, -0x0000243c,0x0000243b,0x00000002,0x00000004, -0x00050041,0x0000022d,0x0000128f,0x00000180, -0x0000015e,0x0004003d,0x00000007,0x00001290, -0x0000128f,0x00050051,0x00000006,0x0000246a, -0x00001290,0x00000000,0x00050095,0x00000130, -0x0000246c,0x0000246a,0x0000127a,0x00050051, -0x00000006,0x0000246d,0x0000246c,0x00000001, -0x00050051,0x00000006,0x0000246e,0x0000246c, -0x00000000,0x00050051,0x00000006,0x00002471, -0x00001290,0x00000001,0x00050080,0x00000006, -0x00002473,0x00002471,0x0000246d,0x00050050, -0x00000007,0x00002474,0x0000246e,0x00002473, -0x0004007c,0x00000014,0x00002464,0x00002474, -0x00060041,0x0000015f,0x0000245c,0x00002464, -0x0000015e,0x0000015e,0x0005003e,0x0000245c, -0x0000243c,0x00000002,0x00000004,0x000200f9, -0x00001284,0x000200f8,0x00001284,0x000200f9, -0x000012fe,0x000200f8,0x00001278,0x000500aa, -0x0000002f,0x00001297,0x000011e0,0x0000012b, -0x000300f7,0x00001299,0x00000000,0x000400fa, -0x00001297,0x00001298,0x000012ba,0x000200f8, -0x000012ba,0x000500aa,0x0000002f,0x000012bd, -0x000011e0,0x00000135,0x000300f7,0x000012bf, -0x00000000,0x000400fa,0x000012bd,0x000012be, -0x000012c3,0x000200f8,0x000012c3,0x000500aa, -0x0000002f,0x000012c6,0x000011e0,0x00000247, -0x000300f7,0x000012c8,0x00000000,0x000400fa, -0x000012c6,0x000012c7,0x000012cc,0x000200f8, -0x000012cc,0x000500aa,0x0000002f,0x000012cf, -0x000011e0,0x00000437,0x000300f7,0x000012d1, -0x00000000,0x000400fa,0x000012cf,0x000012d0, -0x000012d5,0x000200f8,0x000012d5,0x000500aa, -0x0000002f,0x000012d8,0x000011e0,0x000000df, -0x000300f7,0x000012da,0x00000000,0x000400fa, -0x000012d8,0x000012d9,0x000012df,0x000200f8, -0x000012df,0x000500aa,0x0000002f,0x000012e2, -0x000011e0,0x0000032b,0x000300f7,0x000012e4, -0x00000000,0x000400fa,0x000012e2,0x000012e3, -0x000012e8,0x000200f8,0x000012e8,0x000500aa, -0x0000002f,0x000012ec,0x000011e0,0x000012eb, -0x000300f7,0x000012ee,0x00000000,0x000400fa, -0x000012ec,0x000012ed,0x000012f2,0x000200f8, -0x000012f2,0x000500aa,0x0000002f,0x000012f6, -0x000011e0,0x000012f5,0x000300f7,0x000012f8, -0x00000000,0x000400fa,0x000012f6,0x000012f7, -0x000012f8,0x000200f8,0x000012f7,0x00050041, -0x00000182,0x000056be,0x00000180,0x00000181, -0x0004003d,0x00000006,0x000056bf,0x000056be, -0x00050084,0x00000006,0x000056c0,0x000001a2, -0x000056bf,0x00050080,0x00000006,0x000056c1, -0x0000018b,0x000056c0,0x00050080,0x00000006, -0x000056c7,0x000056bf,0x00005cc3,0x00050086, -0x00000006,0x000056c8,0x000056c7,0x00000185, -0x00050084,0x00000006,0x000056ba,0x0000018b, -0x000056c8,0x00050080,0x00000006,0x000056bb, -0x000056c1,0x000056ba,0x00050080,0x00000006, -0x000056b5,0x000056bb,0x000056ba,0x00050041, -0x00000182,0x000056ac,0x00000180,0x000001b7, -0x0004003d,0x00000006,0x000056ad,0x000056ac, -0x00050084,0x00000006,0x000056ae,0x000001b6, -0x000056ad,0x00050080,0x00000006,0x000056af, -0x000056b5,0x000056ae,0x00050084,0x00000006, -0x000056a4,0x000001cc,0x000011de,0x00050080, -0x00000006,0x000056a5,0x000056af,0x000056a4, -0x00050041,0x0000022d,0x000056a6,0x00000180, -0x0000022b,0x0004003d,0x00000007,0x000056a7, -0x000056a6,0x00050051,0x00000006,0x000056dd, -0x000056a7,0x00000000,0x00050095,0x00000130, -0x000056df,0x000056dd,0x000056a5,0x00050051, -0x00000006,0x000056e0,0x000056df,0x00000001, -0x00050051,0x00000006,0x000056e1,0x000056df, -0x00000000,0x00050051,0x00000006,0x000056e4, -0x000056a7,0x00000001,0x00050080,0x00000006, -0x000056e6,0x000056e4,0x000056e0,0x00050050, -0x00000007,0x000056e7,0x000056e1,0x000056e6, -0x0004007c,0x00000014,0x000056d7,0x000056e7, -0x00060041,0x0000015f,0x00005691,0x000056d7, -0x0000015e,0x0000015e,0x0005003e,0x00005691, -0x0000012b,0x00000002,0x00000004,0x00060041, -0x0000015f,0x00005693,0x000056d7,0x0000015e, -0x0000022b,0x0005003e,0x00005693,0x00000500, -0x00000002,0x00000004,0x00060041,0x0000015f, -0x00005695,0x000056d7,0x0000015e,0x000002dc, -0x0005003e,0x00005695,0x00000500,0x00000002, -0x00000004,0x00060041,0x0000015f,0x00005697, -0x000056d7,0x0000015e,0x000002e4,0x0005003e, -0x00005697,0x00000500,0x00000002,0x00000004, -0x00060041,0x0000015f,0x00005699,0x000056d7, -0x0000015e,0x000002ec,0x0005003e,0x00005699, -0x0000012b,0x00000002,0x00000004,0x00060041, -0x0000015f,0x0000569b,0x000056d7,0x0000015e, -0x000002f4,0x0005003e,0x0000569b,0x0000012b, -0x00000002,0x00000004,0x00060041,0x0000015f, -0x0000569d,0x000056d7,0x0000015e,0x00000318, -0x0005003e,0x0000569d,0x0000012b,0x00000002, -0x00000004,0x000200f9,0x000012f8,0x000200f8, -0x000012f8,0x000200f9,0x000012ee,0x000200f8, -0x000012ed,0x000300f7,0x00004e17,0x00000000, -0x000300fb,0x0000012b,0x00004d82,0x000200f8, -0x00004d82,0x00050041,0x00000182,0x00004d83, -0x00000180,0x000003fb,0x0004003d,0x00000006, -0x00004d84,0x00004d83,0x000500aa,0x0000002f, -0x00004d85,0x00004d84,0x00000135,0x000300f7, -0x00004d91,0x00000000,0x000400fa,0x00004d85, -0x00004d86,0x00004d89,0x000200f8,0x00004d89, -0x00050041,0x00000182,0x00004e7b,0x00000180, -0x00000181,0x0004003d,0x00000006,0x00004e7c, -0x00004e7b,0x00050084,0x00000006,0x00004e7d, -0x000001a2,0x00004e7c,0x00050080,0x00000006, -0x00004e7e,0x0000018b,0x00004e7d,0x00050080, -0x00000006,0x00004e84,0x00004e7c,0x00005cc3, -0x00050086,0x00000006,0x00004e85,0x00004e84, -0x00000185,0x00050084,0x00000006,0x00004e77, -0x0000018b,0x00004e85,0x00050080,0x00000006, -0x00004e78,0x00004e7e,0x00004e77,0x00050080, -0x00000006,0x00004e72,0x00004e78,0x00004e77, -0x00050041,0x00000182,0x00004e69,0x00000180, -0x000001b7,0x0004003d,0x00000006,0x00004e6a, -0x00004e69,0x00050084,0x00000006,0x00004e6b, -0x000001b6,0x00004e6a,0x00050080,0x00000006, -0x00004e6c,0x00004e72,0x00004e6b,0x00050041, -0x00000182,0x00004e62,0x00000180,0x000001cd, -0x0004003d,0x00000006,0x00004e63,0x00004e62, -0x00050084,0x00000006,0x00004e64,0x000001cc, -0x00004e63,0x00050080,0x00000006,0x00004e65, -0x00004e6c,0x00004e64,0x000500ac,0x0000002f, -0x00004e92,0x00004e6a,0x00000135,0x000300f7, -0x00004e98,0x00000000,0x000400fa,0x00004e92, -0x00004e93,0x00004e97,0x000200f8,0x00004e97, -0x000200f9,0x00004e98,0x000200f8,0x00004e93, -0x00050082,0x00000006,0x00004e96,0x00004e6a, -0x00000135,0x000200f9,0x00004e98,0x000200f8, -0x00004e98,0x000700f5,0x00000006,0x0000591b, -0x00004e96,0x00004e93,0x0000012b,0x00004e97, -0x00050084,0x00000006,0x00004e5d,0x000000df, -0x0000591b,0x00050080,0x00000006,0x00004e5e, -0x00004e65,0x00004e5d,0x000300f7,0x00004ea5, -0x00000000,0x000400fa,0x00004e92,0x00004ea0, -0x00004ea4,0x000200f8,0x00004ea4,0x000200f9, -0x00004ea5,0x000200f8,0x00004ea0,0x00050082, -0x00000006,0x00004ea3,0x00004e6a,0x00000135, -0x000200f9,0x00004ea5,0x000200f8,0x00004ea5, -0x000700f5,0x00000006,0x0000591c,0x00004ea3, -0x00004ea0,0x0000012b,0x00004ea4,0x00050084, -0x00000006,0x00004e57,0x000000df,0x0000591c, -0x00050080,0x00000006,0x00004e58,0x00004e5e, -0x00004e57,0x000300f7,0x00004eb2,0x00000000, -0x000400fa,0x00004e92,0x00004ead,0x00004eb1, -0x000200f8,0x00004eb1,0x000200f9,0x00004eb2, -0x000200f8,0x00004ead,0x00050082,0x00000006, -0x00004eb0,0x00004e6a,0x00000135,0x000200f9, -0x00004eb2,0x000200f8,0x00004eb2,0x000700f5, -0x00000006,0x0000591d,0x00004eb0,0x00004ead, -0x0000012b,0x00004eb1,0x00050084,0x00000006, -0x00004e51,0x000000df,0x0000591d,0x00050080, -0x00000006,0x00004e52,0x00004e58,0x00004e51, -0x000300f7,0x00004ebf,0x00000000,0x000400fa, -0x00004e92,0x00004eba,0x00004ebe,0x000200f8, -0x00004ebe,0x000200f9,0x00004ebf,0x000200f8, -0x00004eba,0x00050082,0x00000006,0x00004ebd, -0x00004e6a,0x00000135,0x000200f9,0x00004ebf, -0x000200f8,0x00004ebf,0x000700f5,0x00000006, -0x0000591e,0x00004ebd,0x00004eba,0x0000012b, -0x00004ebe,0x00050084,0x00000006,0x00004e4b, -0x000000df,0x0000591e,0x00050080,0x00000006, -0x00004e4c,0x00004e52,0x00004e4b,0x000300f7, -0x00004ecc,0x00000000,0x000400fa,0x00004e92, -0x00004ec7,0x00004ecb,0x000200f8,0x00004ecb, -0x000200f9,0x00004ecc,0x000200f8,0x00004ec7, -0x00050082,0x00000006,0x00004eca,0x00004e6a, -0x00000135,0x000200f9,0x00004ecc,0x000200f8, -0x00004ecc,0x000700f5,0x00000006,0x0000591f, -0x00004eca,0x00004ec7,0x0000012b,0x00004ecb, -0x00050084,0x00000006,0x00004e45,0x000000df, -0x0000591f,0x00050080,0x00000006,0x00004e46, -0x00004e4c,0x00004e45,0x000300f7,0x00004edf, -0x00000000,0x000400fa,0x00004e92,0x00004eda, -0x00004ede,0x000200f8,0x00004ede,0x000200f9, -0x00004edf,0x000200f8,0x00004eda,0x00050082, -0x00000006,0x00004edd,0x00004e6a,0x00000135, -0x000200f9,0x00004edf,0x000200f8,0x00004edf, -0x000700f5,0x00000006,0x00005920,0x00004edd, -0x00004eda,0x0000012b,0x00004ede,0x00050080, -0x00000006,0x00004ed2,0x00005920,0x00005cc3, -0x00050086,0x00000006,0x00004ed3,0x00004ed2, -0x00000185,0x00050084,0x00000006,0x00004e3f, -0x000000df,0x00004ed3,0x00050080,0x00000006, -0x00004e40,0x00004e46,0x00004e3f,0x000300f7, -0x00004ef2,0x00000000,0x000400fa,0x00004e92, -0x00004eed,0x00004ef1,0x000200f8,0x00004ef1, -0x000200f9,0x00004ef2,0x000200f8,0x00004eed, -0x00050082,0x00000006,0x00004ef0,0x00004e6a, -0x00000135,0x000200f9,0x00004ef2,0x000200f8, -0x00004ef2,0x000700f5,0x00000006,0x00005921, -0x00004ef0,0x00004eed,0x0000012b,0x00004ef1, -0x00050080,0x00000006,0x00004ee5,0x00005921, -0x00005cc3,0x00050086,0x00000006,0x00004ee6, -0x00004ee5,0x00000185,0x00050084,0x00000006, -0x00004e39,0x000000df,0x00004ee6,0x00050080, -0x00000006,0x00004e3a,0x00004e40,0x00004e39, -0x00050084,0x00000006,0x00004d8c,0x000000df, -0x000011de,0x00050080,0x00000006,0x00004d8d, -0x00004e3a,0x00004d8c,0x00050041,0x0000022d, -0x00004d8e,0x00000180,0x0000022b,0x0004003d, -0x00000007,0x00004d8f,0x00004d8e,0x00050051, -0x00000006,0x00004f0a,0x00004d8f,0x00000000, -0x00050095,0x00000130,0x00004f0c,0x00004f0a, -0x00004d8d,0x00050051,0x00000006,0x00004f0d, -0x00004f0c,0x00000001,0x00050051,0x00000006, -0x00004f0e,0x00004f0c,0x00000000,0x00050051, -0x00000006,0x00004f11,0x00004d8f,0x00000001, -0x00050080,0x00000006,0x00004f13,0x00004f11, -0x00004f0d,0x00050050,0x00000007,0x00004f14, -0x00004f0e,0x00004f13,0x0004007c,0x00000014, -0x00004f04,0x00004f14,0x00060041,0x0000015f, -0x00004efb,0x00004f04,0x0000015e,0x0000015e, -0x0006003d,0x00000006,0x00004efc,0x00004efb, -0x00000002,0x00000004,0x000200f9,0x00004d91, -0x000200f8,0x00004d86,0x00050041,0x00000182, -0x00004e1a,0x00000180,0x00000311,0x0004003d, -0x00000006,0x00004e1b,0x00004e1a,0x00050041, -0x00000182,0x00004e2b,0x00000180,0x000002fb, -0x0004003d,0x00000006,0x00004e2c,0x00004e2b, -0x000500c7,0x00000006,0x00004e2d,0x00004e2c, -0x00000135,0x000500ab,0x0000002f,0x00004e2e, -0x00004e2d,0x0000012b,0x000600a9,0x00000006, -0x00004e28,0x00004e2e,0x00000309,0x0000018b, -0x00050084,0x00000006,0x00004e1e,0x000011de, -0x00004e28,0x00050080,0x00000006,0x00004e1f, -0x00004e1b,0x00004e1e,0x000500c2,0x00000006, -0x00004e20,0x00004e1f,0x00000318,0x000500c4, -0x00000006,0x00004e21,0x00004e20,0x000002e4, -0x000600a9,0x00000006,0x00004e23,0x00004e2e, -0x0000031c,0x0000012b,0x000500c5,0x00000006, -0x00004e24,0x00004e21,0x00004e23,0x000200f9, -0x00004d91,0x000200f8,0x00004d91,0x000700f5, -0x00000006,0x00005922,0x00004e24,0x00004d86, -0x00004efc,0x00004ef2,0x00050041,0x00000182, -0x00004f5a,0x00000180,0x00000181,0x0004003d, -0x00000006,0x00004f5b,0x00004f5a,0x00050084, -0x00000006,0x00004f5c,0x000001a2,0x00004f5b, -0x00050080,0x00000006,0x00004f5d,0x0000018b, -0x00004f5c,0x00050080,0x00000006,0x00004f63, -0x00004f5b,0x00005cc3,0x00050086,0x00000006, -0x00004f64,0x00004f63,0x00000185,0x00050084, -0x00000006,0x00004f56,0x0000018b,0x00004f64, -0x00050080,0x00000006,0x00004f57,0x00004f5d, -0x00004f56,0x00050080,0x00000006,0x00004f51, -0x00004f57,0x00004f56,0x00050084,0x00000006, -0x00004f25,0x000001b6,0x000011de,0x00050080, -0x00000006,0x00004f26,0x00004f51,0x00004f25, -0x00050041,0x0000022d,0x00004f27,0x00000180, -0x0000022b,0x0004003d,0x00000007,0x00004f28, -0x00004f27,0x00050051,0x00000006,0x00004f82, -0x00004f28,0x00000000,0x00050095,0x00000130, -0x00004f84,0x00004f82,0x00004f26,0x00050051, -0x00000006,0x00004f85,0x00004f84,0x00000001, -0x00050051,0x00000006,0x00004f86,0x00004f84, -0x00000000,0x00050051,0x00000006,0x00004f89, -0x00004f28,0x00000001,0x00050080,0x00000006, -0x00004f8b,0x00004f89,0x00004f85,0x00050050, -0x00000007,0x00004f8c,0x00004f86,0x00004f8b, -0x0004007c,0x00000014,0x00004f7c,0x00004f8c, -0x00060041,0x0000015f,0x00004f73,0x00004f7c, -0x0000015e,0x0000015e,0x0006003d,0x00000006, -0x00004f74,0x00004f73,0x00000002,0x00000004, -0x0004007c,0x00000027,0x00004f2b,0x00004f74, -0x00050080,0x00000006,0x00004f2d,0x00004f26, -0x000000df,0x00050095,0x00000130,0x00004fa5, -0x00004f82,0x00004f2d,0x00050051,0x00000006, -0x00004fa6,0x00004fa5,0x00000001,0x00050051, -0x00000006,0x00004fa7,0x00004fa5,0x00000000, -0x00050080,0x00000006,0x00004fac,0x00004f89, -0x00004fa6,0x00050050,0x00000007,0x00004fad, -0x00004fa7,0x00004fac,0x0004007c,0x00000014, -0x00004f9d,0x00004fad,0x00060041,0x0000015f, -0x00004f94,0x00004f9d,0x0000015e,0x0000015e, -0x0006003d,0x00000006,0x00004f95,0x00004f94, -0x00000002,0x00000004,0x0004007c,0x00000027, -0x00004f31,0x00004f95,0x00050080,0x00000006, -0x00004f33,0x00004f26,0x00000194,0x00050095, -0x00000130,0x00004fc6,0x00004f82,0x00004f33, -0x00050051,0x00000006,0x00004fc7,0x00004fc6, -0x00000001,0x00050051,0x00000006,0x00004fc8, -0x00004fc6,0x00000000,0x00050080,0x00000006, -0x00004fcd,0x00004f89,0x00004fc7,0x00050050, -0x00000007,0x00004fce,0x00004fc8,0x00004fcd, -0x0004007c,0x00000014,0x00004fbe,0x00004fce, -0x00060041,0x0000015f,0x00004fb5,0x00004fbe, -0x0000015e,0x0000015e,0x0006003d,0x00000006, -0x00004fb6,0x00004fb5,0x00000002,0x00000004, -0x0004007c,0x00000027,0x00004f37,0x00004fb6, -0x00060050,0x00000063,0x00004f38,0x00004f2b, -0x00004f31,0x00004f37,0x00050080,0x00000006, -0x00004f3a,0x00004f26,0x0000019b,0x00050095, -0x00000130,0x00004fe7,0x00004f82,0x00004f3a, -0x00050051,0x00000006,0x00004fe8,0x00004fe7, -0x00000001,0x00050051,0x00000006,0x00004fe9, -0x00004fe7,0x00000000,0x00050080,0x00000006, -0x00004fee,0x00004f89,0x00004fe8,0x00050050, -0x00000007,0x00004fef,0x00004fe9,0x00004fee, -0x0004007c,0x00000014,0x00004fdf,0x00004fef, -0x00060041,0x0000015f,0x00004fd6,0x00004fdf, -0x0000015e,0x0000015e,0x0006003d,0x00000006, -0x00004fd7,0x00004fd6,0x00000002,0x00000004, -0x0004007c,0x00000027,0x00004f3e,0x00004fd7, -0x00050080,0x00000006,0x00004f40,0x00004f26, -0x000001a2,0x00050095,0x00000130,0x00005008, -0x00004f82,0x00004f40,0x00050051,0x00000006, -0x00005009,0x00005008,0x00000001,0x00050051, -0x00000006,0x0000500a,0x00005008,0x00000000, -0x00050080,0x00000006,0x0000500f,0x00004f89, -0x00005009,0x00050050,0x00000007,0x00005010, -0x0000500a,0x0000500f,0x0004007c,0x00000014, -0x00005000,0x00005010,0x00060041,0x0000015f, -0x00004ff7,0x00005000,0x0000015e,0x0000015e, -0x0006003d,0x00000006,0x00004ff8,0x00004ff7, -0x00000002,0x00000004,0x0004007c,0x00000027, -0x00004f44,0x00004ff8,0x00050080,0x00000006, -0x00004f46,0x00004f26,0x00000260,0x00050095, -0x00000130,0x00005029,0x00004f82,0x00004f46, -0x00050051,0x00000006,0x0000502a,0x00005029, -0x00000001,0x00050051,0x00000006,0x0000502b, -0x00005029,0x00000000,0x00050080,0x00000006, -0x00005030,0x00004f89,0x0000502a,0x00050050, -0x00000007,0x00005031,0x0000502b,0x00005030, -0x0004007c,0x00000014,0x00005021,0x00005031, -0x00060041,0x0000015f,0x00005018,0x00005021, -0x0000015e,0x0000015e,0x0006003d,0x00000006, -0x00005019,0x00005018,0x00000002,0x00000004, -0x0004007c,0x00000027,0x00004f4a,0x00005019, -0x00060050,0x00000063,0x00004f4b,0x00004f3e, -0x00004f44,0x00004f4a,0x00050041,0x00000182, -0x00005037,0x00000180,0x00000fbf,0x0004003d, -0x00000006,0x00005038,0x00005037,0x000500c2, -0x00000006,0x00005047,0x00005922,0x000002e4, -0x00050041,0x00000182,0x0000503b,0x00000180, -0x00000311,0x0004003d,0x00000006,0x0000503c, -0x0000503b,0x00050086,0x00000006,0x0000503d, -0x0000503c,0x0000018b,0x00050082,0x00000006, -0x0000503e,0x00005047,0x0000503d,0x00050084, -0x00000006,0x0000503f,0x000000df,0x0000503e, -0x00050080,0x00000006,0x00005040,0x00005038, -0x0000503f,0x00050041,0x0000022d,0x00005041, -0x00000180,0x0000015e,0x0004003d,0x00000007, -0x00005042,0x00005041,0x00050051,0x00000006, -0x0000505e,0x00005042,0x00000000,0x00050095, -0x00000130,0x00005060,0x0000505e,0x00005040, -0x00050051,0x00000006,0x00005061,0x00005060, -0x00000001,0x00050051,0x00000006,0x00005062, -0x00005060,0x00000000,0x00050051,0x00000006, -0x00005065,0x00005042,0x00000001,0x00050080, -0x00000006,0x00005067,0x00005065,0x00005061, -0x00050050,0x00000007,0x00005068,0x00005062, -0x00005067,0x0004007c,0x00000014,0x00005058, -0x00005068,0x00060041,0x0000015f,0x0000504f, -0x00005058,0x0000015e,0x0000015e,0x0006003d, -0x00000006,0x00005050,0x0000504f,0x00000002, -0x00000004,0x00050041,0x00000182,0x0000506b, -0x00000180,0x000002fb,0x0004003d,0x00000006, -0x0000506c,0x0000506b,0x000500c7,0x00000006, -0x0000506d,0x0000506c,0x00000135,0x000500ab, -0x0000002f,0x0000506e,0x0000506d,0x0000012b, -0x000300f7,0x00004da5,0x00000000,0x000400fa, -0x0000506e,0x00004d9a,0x00004da5,0x000200f8, -0x00004d9a,0x00050084,0x00000006,0x00004d9e, -0x00000309,0x000011de,0x00050080,0x00000006, -0x00004d9f,0x0000503c,0x00004d9e,0x00050080, -0x00000006,0x00004da0,0x00004d9f,0x0000074b, -0x00050095,0x00000130,0x00005086,0x0000505e, -0x00004da0,0x00050051,0x00000006,0x00005087, -0x00005086,0x00000001,0x00050051,0x00000006, -0x00005088,0x00005086,0x00000000,0x00050080, -0x00000006,0x0000508d,0x00005065,0x00005087, -0x00050050,0x00000007,0x0000508e,0x00005088, -0x0000508d,0x0004007c,0x00000014,0x0000507e, -0x0000508e,0x00060041,0x0000015f,0x00005076, -0x0000507e,0x0000015e,0x0000015e,0x0005003e, -0x00005076,0x00005050,0x00000002,0x00000004, -0x000200f9,0x00004da5,0x000200f8,0x00004da5, -0x000200f9,0x00004da6,0x000200f8,0x00004da6, -0x000700f5,0x00000063,0x0000592c,0x00004f4b, -0x00004da5,0x00005954,0x00004e11,0x000700f5, -0x00000063,0x00005929,0x00004f38,0x00004da5, -0x00005950,0x00004e11,0x000700f5,0x00000006, -0x00005925,0x0000012b,0x00004da5,0x00004e13, -0x00004e11,0x000700f5,0x00000006,0x00005923, -0x00005050,0x00004da5,0x00005672,0x00004e11, -0x000700f5,0x00000006,0x00005996,0x00005922, -0x00004da5,0x00005923,0x00004e11,0x000500ab, -0x0000002f,0x00004da9,0x00005923,0x00000500, -0x000500b0,0x0000002f,0x00004dab,0x00005925, -0x00000309,0x000500a7,0x0000002f,0x00004dac, -0x00004da9,0x00004dab,0x000400f6,0x00004e14, -0x00004e11,0x00000000,0x000400fa,0x00004dac, -0x00004dad,0x00004e14,0x000200f8,0x00004dad, -0x000500c2,0x00000006,0x00005092,0x00005923, -0x000002e4,0x00050084,0x00000006,0x00004db0, -0x00005092,0x0000018b,0x000200f9,0x00004db1, -0x000200f8,0x00004db1,0x000700f5,0x00000006, -0x00005942,0x0000012b,0x00004dad,0x00005bf6, -0x00004dcf,0x000700f5,0x00000006,0x00005926, -0x0000012b,0x00004dad,0x00004dd1,0x00004dcf, -0x000500b0,0x0000002f,0x00004db4,0x00005926, -0x000000df,0x000400f6,0x00004dd2,0x00004dcf, -0x00000000,0x000400fa,0x00004db4,0x00004db5, -0x00004dd2,0x000200f8,0x00004db5,0x00050084, -0x00000006,0x00004db8,0x000000df,0x00005926, -0x00050080,0x00000006,0x00004db9,0x00004db0, -0x00004db8,0x00050095,0x00000130,0x000050ab, -0x0000505e,0x00004db9,0x00050051,0x00000006, -0x000050ac,0x000050ab,0x00000001,0x00050051, -0x00000006,0x000050ad,0x000050ab,0x00000000, -0x00050080,0x00000006,0x000050b2,0x00005065, -0x000050ac,0x00050050,0x00000007,0x000050b3, -0x000050ad,0x000050b2,0x0004007c,0x00000014, -0x000050a3,0x000050b3,0x00060041,0x0000015f, -0x0000509a,0x000050a3,0x0000015e,0x0000015e, -0x0006003d,0x00000006,0x0000509b,0x0000509a, -0x00000002,0x00000004,0x000500aa,0x0000002f, -0x00004dbe,0x0000509b,0x00000500,0x000300f7, -0x00004dc0,0x00000000,0x000400fa,0x00004dbe, -0x00004dbf,0x00004dc0,0x000200f8,0x00004dbf, -0x000200f9,0x00004dcf,0x000200f8,0x00004dc0, -0x00050080,0x00000006,0x00004dc2,0x00005942, -0x0000022b,0x000500aa,0x0000002f,0x00004dc5, -0x0000509b,0x00005996,0x000300f7,0x00004dce, -0x00000000,0x000400fa,0x00004dc5,0x00004dc6, -0x00004dce,0x000200f8,0x00004dc6,0x000500c7, -0x00000006,0x000050b7,0x00005923,0x00000c2c, -0x000500aa,0x0000002f,0x000050b8,0x000050b7, -0x000000df,0x000300f7,0x0000510b,0x00000000, -0x000300fb,0x0000012b,0x000050d1,0x000200f8, -0x000050d1,0x000300f7,0x000050dc,0x00000000, -0x000400fa,0x000050b8,0x000050d3,0x000050dc, -0x000200f8,0x000050d3,0x00050080,0x00000006, -0x000050d5,0x00004db0,0x000001a2,0x00050084, -0x00000006,0x000050d7,0x0000019b,0x00005926, -0x00050080,0x00000006,0x000050d8,0x000050d5, -0x000050d7,0x00050051,0x00000027,0x00005123, -0x00005929,0x00000000,0x000300f7,0x0000519a, -0x00000000,0x000300fb,0x0000012b,0x00005154, -0x000200f8,0x00005154,0x0004007c,0x00000006, -0x00005156,0x00005123,0x000500c2,0x00000006, -0x00005158,0x00005156,0x00000321,0x000500c7, -0x00000006,0x00005159,0x00005158,0x0000033a, -0x000500c7,0x00000006,0x0000515b,0x00005156, -0x0000021d,0x000500ab,0x0000002f,0x0000515e, -0x00005159,0x0000012b,0x000500ac,0x0000002f, -0x00005161,0x0000515b,0x00000345,0x000300f7, -0x00005165,0x00000000,0x000400fa,0x00005161, -0x00005162,0x00005165,0x000200f8,0x00005162, -0x000500c5,0x00000006,0x00005164,0x00005159, -0x0000034a,0x000200f9,0x0000519a,0x000200f8, -0x00005165,0x000500aa,0x0000002f,0x00005167, -0x0000515b,0x0000012b,0x000300f7,0x0000516a, -0x00000000,0x000400fa,0x00005167,0x00005168, -0x0000516a,0x000200f8,0x00005168,0x000200f9, -0x0000519a,0x000200f8,0x0000516a,0x000500c2, -0x00000006,0x0000516c,0x0000515b,0x00000355, -0x0004007c,0x000000e7,0x0000516d,0x0000516c, -0x00050082,0x000000e7,0x0000516e,0x0000516d, -0x00000358,0x000500af,0x0000002f,0x00005170, -0x0000516e,0x00000321,0x000300f7,0x00005176, -0x00000000,0x000400fa,0x00005170,0x00005171, -0x00005176,0x000200f8,0x00005171,0x000600a9, -0x00000006,0x00005174,0x0000515e,0x00000360, -0x00000361,0x000500c5,0x00000006,0x00005175, -0x00005159,0x00005174,0x000200f9,0x0000519a, -0x000200f8,0x00005176,0x000500b1,0x0000002f, -0x00005178,0x0000516e,0x00000366,0x000300f7, -0x00005182,0x00000000,0x000400fa,0x00005178, -0x00005179,0x00005182,0x000200f8,0x00005179, -0x000300f7,0x00005180,0x00000000,0x000400fa, -0x0000515e,0x0000517b,0x0000517e,0x000200f8, -0x0000517e,0x000200f9,0x00005180,0x000200f8, -0x0000517b,0x000500c5,0x00000006,0x0000517d, -0x00005159,0x0000036f,0x000200f9,0x00005180, -0x000200f8,0x00005180,0x000700f5,0x00000006, -0x0000599a,0x0000517d,0x0000517b,0x00005159, -0x0000517e,0x000200f9,0x0000519a,0x000200f8, -0x00005182,0x000500c7,0x00000006,0x00005184, -0x00005156,0x00000377,0x00050080,0x000000e7, -0x00005186,0x0000516d,0x00005cc4,0x0004007c, -0x00000006,0x00005187,0x00005186,0x000500c4, -0x00000006,0x00005188,0x00005187,0x0000037d, -0x000500c2,0x00000006,0x0000518a,0x00005184, -0x000001b7,0x000500c5,0x00000006,0x0000518b, -0x00005188,0x0000518a,0x000300f7,0x00005191, -0x00000000,0x000400fa,0x0000515e,0x0000518d, -0x00005191,0x000200f8,0x0000518d,0x000500c7, -0x00000006,0x0000518f,0x00005156,0x00000386, -0x000500ab,0x0000002f,0x00005190,0x0000518f, -0x0000012b,0x000200f9,0x00005191,0x000200f8, -0x00005191,0x000700f5,0x0000002f,0x00005192, -0x0000515e,0x00005182,0x00005190,0x0000518d, -0x000300f7,0x00005196,0x00000000,0x000400fa, -0x00005192,0x00005193,0x00005196,0x000200f8, -0x00005193,0x00050080,0x00000006,0x00005195, -0x0000518b,0x00000135,0x000200f9,0x00005196, -0x000200f8,0x00005196,0x000700f5,0x00000006, -0x00005999,0x0000518b,0x00005191,0x00005195, -0x00005193,0x000500c5,0x00000006,0x00005199, -0x00005159,0x00005999,0x000200f9,0x0000519a, -0x000200f8,0x0000519a,0x000d00f5,0x00000006, -0x0000599b,0x00005164,0x00005162,0x00005159, -0x00005168,0x00005175,0x00005171,0x0000599a, -0x00005180,0x00005199,0x00005196,0x00050051, -0x00000027,0x00005126,0x00005929,0x00000001, -0x000300f7,0x000051ee,0x00000000,0x000300fb, -0x0000012b,0x000051a8,0x000200f8,0x000051a8, -0x0004007c,0x00000006,0x000051aa,0x00005126, -0x000500c2,0x00000006,0x000051ac,0x000051aa, -0x00000321,0x000500c7,0x00000006,0x000051ad, -0x000051ac,0x0000033a,0x000500c7,0x00000006, -0x000051af,0x000051aa,0x0000021d,0x000500ab, -0x0000002f,0x000051b2,0x000051ad,0x0000012b, -0x000500ac,0x0000002f,0x000051b5,0x000051af, -0x00000345,0x000300f7,0x000051b9,0x00000000, -0x000400fa,0x000051b5,0x000051b6,0x000051b9, -0x000200f8,0x000051b6,0x000500c5,0x00000006, -0x000051b8,0x000051ad,0x0000034a,0x000200f9, -0x000051ee,0x000200f8,0x000051b9,0x000500aa, -0x0000002f,0x000051bb,0x000051af,0x0000012b, -0x000300f7,0x000051be,0x00000000,0x000400fa, -0x000051bb,0x000051bc,0x000051be,0x000200f8, -0x000051bc,0x000200f9,0x000051ee,0x000200f8, -0x000051be,0x000500c2,0x00000006,0x000051c0, -0x000051af,0x00000355,0x0004007c,0x000000e7, -0x000051c1,0x000051c0,0x00050082,0x000000e7, -0x000051c2,0x000051c1,0x00000358,0x000500af, -0x0000002f,0x000051c4,0x000051c2,0x00000321, -0x000300f7,0x000051ca,0x00000000,0x000400fa, -0x000051c4,0x000051c5,0x000051ca,0x000200f8, -0x000051c5,0x000600a9,0x00000006,0x000051c8, -0x000051b2,0x00000360,0x00000361,0x000500c5, -0x00000006,0x000051c9,0x000051ad,0x000051c8, -0x000200f9,0x000051ee,0x000200f8,0x000051ca, -0x000500b1,0x0000002f,0x000051cc,0x000051c2, -0x00000366,0x000300f7,0x000051d6,0x00000000, -0x000400fa,0x000051cc,0x000051cd,0x000051d6, -0x000200f8,0x000051cd,0x000300f7,0x000051d4, -0x00000000,0x000400fa,0x000051b2,0x000051cf, -0x000051d2,0x000200f8,0x000051d2,0x000200f9, -0x000051d4,0x000200f8,0x000051cf,0x000500c5, -0x00000006,0x000051d1,0x000051ad,0x0000036f, -0x000200f9,0x000051d4,0x000200f8,0x000051d4, -0x000700f5,0x00000006,0x0000599e,0x000051d1, -0x000051cf,0x000051ad,0x000051d2,0x000200f9, -0x000051ee,0x000200f8,0x000051d6,0x000500c7, -0x00000006,0x000051d8,0x000051aa,0x00000377, -0x00050080,0x000000e7,0x000051da,0x000051c1, -0x00005cc4,0x0004007c,0x00000006,0x000051db, -0x000051da,0x000500c4,0x00000006,0x000051dc, -0x000051db,0x0000037d,0x000500c2,0x00000006, -0x000051de,0x000051d8,0x000001b7,0x000500c5, -0x00000006,0x000051df,0x000051dc,0x000051de, -0x000300f7,0x000051e5,0x00000000,0x000400fa, -0x000051b2,0x000051e1,0x000051e5,0x000200f8, -0x000051e1,0x000500c7,0x00000006,0x000051e3, -0x000051aa,0x00000386,0x000500ab,0x0000002f, -0x000051e4,0x000051e3,0x0000012b,0x000200f9, -0x000051e5,0x000200f8,0x000051e5,0x000700f5, -0x0000002f,0x000051e6,0x000051b2,0x000051d6, -0x000051e4,0x000051e1,0x000300f7,0x000051ea, -0x00000000,0x000400fa,0x000051e6,0x000051e7, -0x000051ea,0x000200f8,0x000051e7,0x00050080, -0x00000006,0x000051e9,0x000051df,0x00000135, -0x000200f9,0x000051ea,0x000200f8,0x000051ea, -0x000700f5,0x00000006,0x0000599d,0x000051df, -0x000051e5,0x000051e9,0x000051e7,0x000500c5, -0x00000006,0x000051ed,0x000051ad,0x0000599d, -0x000200f9,0x000051ee,0x000200f8,0x000051ee, -0x000d00f5,0x00000006,0x0000599f,0x000051b8, -0x000051b6,0x000051ad,0x000051bc,0x000051c9, -0x000051c5,0x0000599e,0x000051d4,0x000051ed, -0x000051ea,0x000500c4,0x00000006,0x00005128, -0x0000599f,0x00000321,0x000500c5,0x00000006, -0x00005129,0x0000599b,0x00005128,0x00050095, -0x00000130,0x00005207,0x0000505e,0x000050d8, -0x00050051,0x00000006,0x00005208,0x00005207, -0x00000001,0x00050051,0x00000006,0x00005209, -0x00005207,0x00000000,0x00050080,0x00000006, -0x0000520e,0x00005065,0x00005208,0x00050050, -0x00000007,0x0000520f,0x00005209,0x0000520e, -0x0004007c,0x00000014,0x000051ff,0x0000520f, -0x00060041,0x0000015f,0x000051f7,0x000051ff, -0x0000015e,0x0000015e,0x0005003e,0x000051f7, -0x00005129,0x00000002,0x00000004,0x00050080, -0x00000006,0x0000512f,0x000050d8,0x000000df, -0x00050051,0x00000027,0x00005131,0x00005929, -0x00000002,0x000300f7,0x00005262,0x00000000, -0x000300fb,0x0000012b,0x0000521c,0x000200f8, -0x0000521c,0x0004007c,0x00000006,0x0000521e, -0x00005131,0x000500c2,0x00000006,0x00005220, -0x0000521e,0x00000321,0x000500c7,0x00000006, -0x00005221,0x00005220,0x0000033a,0x000500c7, -0x00000006,0x00005223,0x0000521e,0x0000021d, -0x000500ab,0x0000002f,0x00005226,0x00005221, -0x0000012b,0x000500ac,0x0000002f,0x00005229, -0x00005223,0x00000345,0x000300f7,0x0000522d, -0x00000000,0x000400fa,0x00005229,0x0000522a, -0x0000522d,0x000200f8,0x0000522a,0x000500c5, -0x00000006,0x0000522c,0x00005221,0x0000034a, -0x000200f9,0x00005262,0x000200f8,0x0000522d, -0x000500aa,0x0000002f,0x0000522f,0x00005223, -0x0000012b,0x000300f7,0x00005232,0x00000000, -0x000400fa,0x0000522f,0x00005230,0x00005232, -0x000200f8,0x00005230,0x000200f9,0x00005262, -0x000200f8,0x00005232,0x000500c2,0x00000006, -0x00005234,0x00005223,0x00000355,0x0004007c, -0x000000e7,0x00005235,0x00005234,0x00050082, -0x000000e7,0x00005236,0x00005235,0x00000358, -0x000500af,0x0000002f,0x00005238,0x00005236, -0x00000321,0x000300f7,0x0000523e,0x00000000, -0x000400fa,0x00005238,0x00005239,0x0000523e, -0x000200f8,0x00005239,0x000600a9,0x00000006, -0x0000523c,0x00005226,0x00000360,0x00000361, -0x000500c5,0x00000006,0x0000523d,0x00005221, -0x0000523c,0x000200f9,0x00005262,0x000200f8, -0x0000523e,0x000500b1,0x0000002f,0x00005240, -0x00005236,0x00000366,0x000300f7,0x0000524a, -0x00000000,0x000400fa,0x00005240,0x00005241, -0x0000524a,0x000200f8,0x00005241,0x000300f7, -0x00005248,0x00000000,0x000400fa,0x00005226, -0x00005243,0x00005246,0x000200f8,0x00005246, -0x000200f9,0x00005248,0x000200f8,0x00005243, -0x000500c5,0x00000006,0x00005245,0x00005221, -0x0000036f,0x000200f9,0x00005248,0x000200f8, -0x00005248,0x000700f5,0x00000006,0x000059a2, -0x00005245,0x00005243,0x00005221,0x00005246, -0x000200f9,0x00005262,0x000200f8,0x0000524a, -0x000500c7,0x00000006,0x0000524c,0x0000521e, -0x00000377,0x00050080,0x000000e7,0x0000524e, -0x00005235,0x00005cc4,0x0004007c,0x00000006, -0x0000524f,0x0000524e,0x000500c4,0x00000006, -0x00005250,0x0000524f,0x0000037d,0x000500c2, -0x00000006,0x00005252,0x0000524c,0x000001b7, -0x000500c5,0x00000006,0x00005253,0x00005250, -0x00005252,0x000300f7,0x00005259,0x00000000, -0x000400fa,0x00005226,0x00005255,0x00005259, -0x000200f8,0x00005255,0x000500c7,0x00000006, -0x00005257,0x0000521e,0x00000386,0x000500ab, -0x0000002f,0x00005258,0x00005257,0x0000012b, -0x000200f9,0x00005259,0x000200f8,0x00005259, -0x000700f5,0x0000002f,0x0000525a,0x00005226, -0x0000524a,0x00005258,0x00005255,0x000300f7, -0x0000525e,0x00000000,0x000400fa,0x0000525a, -0x0000525b,0x0000525e,0x000200f8,0x0000525b, -0x00050080,0x00000006,0x0000525d,0x00005253, -0x00000135,0x000200f9,0x0000525e,0x000200f8, -0x0000525e,0x000700f5,0x00000006,0x000059a1, -0x00005253,0x00005259,0x0000525d,0x0000525b, -0x000500c5,0x00000006,0x00005261,0x00005221, -0x000059a1,0x000200f9,0x00005262,0x000200f8, -0x00005262,0x000d00f5,0x00000006,0x000059a3, -0x0000522c,0x0000522a,0x00005221,0x00005230, -0x0000523d,0x00005239,0x000059a2,0x00005248, -0x00005261,0x0000525e,0x00050051,0x00000027, -0x00005134,0x0000592c,0x00000000,0x000300f7, -0x000052b6,0x00000000,0x000300fb,0x0000012b, -0x00005270,0x000200f8,0x00005270,0x0004007c, -0x00000006,0x00005272,0x00005134,0x000500c2, -0x00000006,0x00005274,0x00005272,0x00000321, -0x000500c7,0x00000006,0x00005275,0x00005274, -0x0000033a,0x000500c7,0x00000006,0x00005277, -0x00005272,0x0000021d,0x000500aa,0x0000002f, -0x0000527b,0x00005275,0x0000012b,0x000500ac, -0x0000002f,0x0000527d,0x00005277,0x00000345, -0x000300f7,0x00005281,0x00000000,0x000400fa, -0x0000527d,0x0000527e,0x00005281,0x000200f8, -0x0000527e,0x000500c5,0x00000006,0x00005280, -0x00005275,0x0000034a,0x000200f9,0x000052b6, -0x000200f8,0x00005281,0x000500aa,0x0000002f, -0x00005283,0x00005277,0x0000012b,0x000300f7, -0x00005286,0x00000000,0x000400fa,0x00005283, -0x00005284,0x00005286,0x000200f8,0x00005284, -0x000200f9,0x000052b6,0x000200f8,0x00005286, -0x000500c2,0x00000006,0x00005288,0x00005277, -0x00000355,0x0004007c,0x000000e7,0x00005289, -0x00005288,0x00050082,0x000000e7,0x0000528a, -0x00005289,0x00000358,0x000500af,0x0000002f, -0x0000528c,0x0000528a,0x00000321,0x000300f7, -0x00005292,0x00000000,0x000400fa,0x0000528c, -0x0000528d,0x00005292,0x000200f8,0x0000528d, -0x000600a9,0x00000006,0x00005290,0x0000527b, -0x00000360,0x00000361,0x000500c5,0x00000006, -0x00005291,0x00005275,0x00005290,0x000200f9, -0x000052b6,0x000200f8,0x00005292,0x000500b1, -0x0000002f,0x00005294,0x0000528a,0x00000366, -0x000300f7,0x0000529e,0x00000000,0x000400fa, -0x00005294,0x00005295,0x0000529e,0x000200f8, -0x00005295,0x000300f7,0x0000529c,0x00000000, -0x000400fa,0x0000527b,0x00005297,0x0000529a, -0x000200f8,0x0000529a,0x000200f9,0x0000529c, -0x000200f8,0x00005297,0x000500c5,0x00000006, -0x00005299,0x00005275,0x0000036f,0x000200f9, -0x0000529c,0x000200f8,0x0000529c,0x000700f5, -0x00000006,0x000059a6,0x00005299,0x00005297, -0x00005275,0x0000529a,0x000200f9,0x000052b6, -0x000200f8,0x0000529e,0x000500c7,0x00000006, -0x000052a0,0x00005272,0x00000377,0x00050080, -0x000000e7,0x000052a2,0x00005289,0x00005cc4, -0x0004007c,0x00000006,0x000052a3,0x000052a2, -0x000500c4,0x00000006,0x000052a4,0x000052a3, -0x0000037d,0x000500c2,0x00000006,0x000052a6, -0x000052a0,0x000001b7,0x000500c5,0x00000006, -0x000052a7,0x000052a4,0x000052a6,0x000300f7, -0x000052ad,0x00000000,0x000400fa,0x0000527b, -0x000052a9,0x000052ad,0x000200f8,0x000052a9, -0x000500c7,0x00000006,0x000052ab,0x00005272, -0x00000386,0x000500ab,0x0000002f,0x000052ac, -0x000052ab,0x0000012b,0x000200f9,0x000052ad, -0x000200f8,0x000052ad,0x000700f5,0x0000002f, -0x000052ae,0x0000527b,0x0000529e,0x000052ac, -0x000052a9,0x000300f7,0x000052b2,0x00000000, -0x000400fa,0x000052ae,0x000052af,0x000052b2, -0x000200f8,0x000052af,0x00050080,0x00000006, -0x000052b1,0x000052a7,0x00000135,0x000200f9, -0x000052b2,0x000200f8,0x000052b2,0x000700f5, -0x00000006,0x000059a5,0x000052a7,0x000052ad, -0x000052b1,0x000052af,0x000500c5,0x00000006, -0x000052b5,0x00005275,0x000059a5,0x000200f9, -0x000052b6,0x000200f8,0x000052b6,0x000d00f5, -0x00000006,0x000059a7,0x00005280,0x0000527e, -0x00005275,0x00005284,0x00005291,0x0000528d, -0x000059a6,0x0000529c,0x000052b5,0x000052b2, -0x000500c4,0x00000006,0x00005136,0x000059a7, -0x00000321,0x000500c5,0x00000006,0x00005137, -0x000059a3,0x00005136,0x00050095,0x00000130, -0x000052cf,0x0000505e,0x0000512f,0x00050051, -0x00000006,0x000052d0,0x000052cf,0x00000001, -0x00050051,0x00000006,0x000052d1,0x000052cf, -0x00000000,0x00050080,0x00000006,0x000052d6, -0x00005065,0x000052d0,0x00050050,0x00000007, -0x000052d7,0x000052d1,0x000052d6,0x0004007c, -0x00000014,0x000052c7,0x000052d7,0x00060041, -0x0000015f,0x000052bf,0x000052c7,0x0000015e, -0x0000015e,0x0005003e,0x000052bf,0x00005137, -0x00000002,0x00000004,0x00050080,0x00000006, -0x0000513c,0x000050d8,0x00000194,0x00050051, -0x00000027,0x0000513e,0x0000592c,0x00000001, -0x000300f7,0x0000532a,0x00000000,0x000300fb, -0x0000012b,0x000052e4,0x000200f8,0x000052e4, -0x0004007c,0x00000006,0x000052e6,0x0000513e, -0x000500c2,0x00000006,0x000052e8,0x000052e6, -0x00000321,0x000500c7,0x00000006,0x000052e9, -0x000052e8,0x0000033a,0x000500c7,0x00000006, -0x000052eb,0x000052e6,0x0000021d,0x000500aa, -0x0000002f,0x000052ef,0x000052e9,0x0000012b, -0x000500ac,0x0000002f,0x000052f1,0x000052eb, -0x00000345,0x000300f7,0x000052f5,0x00000000, -0x000400fa,0x000052f1,0x000052f2,0x000052f5, -0x000200f8,0x000052f2,0x000500c5,0x00000006, -0x000052f4,0x000052e9,0x0000034a,0x000200f9, -0x0000532a,0x000200f8,0x000052f5,0x000500aa, -0x0000002f,0x000052f7,0x000052eb,0x0000012b, -0x000300f7,0x000052fa,0x00000000,0x000400fa, -0x000052f7,0x000052f8,0x000052fa,0x000200f8, -0x000052f8,0x000200f9,0x0000532a,0x000200f8, -0x000052fa,0x000500c2,0x00000006,0x000052fc, -0x000052eb,0x00000355,0x0004007c,0x000000e7, -0x000052fd,0x000052fc,0x00050082,0x000000e7, -0x000052fe,0x000052fd,0x00000358,0x000500af, -0x0000002f,0x00005300,0x000052fe,0x00000321, -0x000300f7,0x00005306,0x00000000,0x000400fa, -0x00005300,0x00005301,0x00005306,0x000200f8, -0x00005301,0x000600a9,0x00000006,0x00005304, -0x000052ef,0x00000360,0x00000361,0x000500c5, -0x00000006,0x00005305,0x000052e9,0x00005304, -0x000200f9,0x0000532a,0x000200f8,0x00005306, -0x000500b1,0x0000002f,0x00005308,0x000052fe, -0x00000366,0x000300f7,0x00005312,0x00000000, -0x000400fa,0x00005308,0x00005309,0x00005312, -0x000200f8,0x00005309,0x000300f7,0x00005310, -0x00000000,0x000400fa,0x000052ef,0x0000530b, -0x0000530e,0x000200f8,0x0000530e,0x000200f9, -0x00005310,0x000200f8,0x0000530b,0x000500c5, -0x00000006,0x0000530d,0x000052e9,0x0000036f, -0x000200f9,0x00005310,0x000200f8,0x00005310, -0x000700f5,0x00000006,0x000059aa,0x0000530d, -0x0000530b,0x000052e9,0x0000530e,0x000200f9, -0x0000532a,0x000200f8,0x00005312,0x000500c7, -0x00000006,0x00005314,0x000052e6,0x00000377, -0x00050080,0x000000e7,0x00005316,0x000052fd, -0x00005cc4,0x0004007c,0x00000006,0x00005317, -0x00005316,0x000500c4,0x00000006,0x00005318, -0x00005317,0x0000037d,0x000500c2,0x00000006, -0x0000531a,0x00005314,0x000001b7,0x000500c5, -0x00000006,0x0000531b,0x00005318,0x0000531a, -0x000300f7,0x00005321,0x00000000,0x000400fa, -0x000052ef,0x0000531d,0x00005321,0x000200f8, -0x0000531d,0x000500c7,0x00000006,0x0000531f, -0x000052e6,0x00000386,0x000500ab,0x0000002f, -0x00005320,0x0000531f,0x0000012b,0x000200f9, -0x00005321,0x000200f8,0x00005321,0x000700f5, -0x0000002f,0x00005322,0x000052ef,0x00005312, -0x00005320,0x0000531d,0x000300f7,0x00005326, -0x00000000,0x000400fa,0x00005322,0x00005323, -0x00005326,0x000200f8,0x00005323,0x00050080, -0x00000006,0x00005325,0x0000531b,0x00000135, -0x000200f9,0x00005326,0x000200f8,0x00005326, -0x000700f5,0x00000006,0x000059a9,0x0000531b, -0x00005321,0x00005325,0x00005323,0x000500c5, -0x00000006,0x00005329,0x000052e9,0x000059a9, -0x000200f9,0x0000532a,0x000200f8,0x0000532a, -0x000d00f5,0x00000006,0x000059ab,0x000052f4, -0x000052f2,0x000052e9,0x000052f8,0x00005305, -0x00005301,0x000059aa,0x00005310,0x00005329, -0x00005326,0x00050051,0x00000027,0x00005141, -0x0000592c,0x00000002,0x000300f7,0x0000537e, -0x00000000,0x000300fb,0x0000012b,0x00005338, -0x000200f8,0x00005338,0x0004007c,0x00000006, -0x0000533a,0x00005141,0x000500c2,0x00000006, -0x0000533c,0x0000533a,0x00000321,0x000500c7, -0x00000006,0x0000533d,0x0000533c,0x0000033a, -0x000500c7,0x00000006,0x0000533f,0x0000533a, -0x0000021d,0x000500aa,0x0000002f,0x00005343, -0x0000533d,0x0000012b,0x000500ac,0x0000002f, -0x00005345,0x0000533f,0x00000345,0x000300f7, -0x00005349,0x00000000,0x000400fa,0x00005345, -0x00005346,0x00005349,0x000200f8,0x00005346, -0x000500c5,0x00000006,0x00005348,0x0000533d, -0x0000034a,0x000200f9,0x0000537e,0x000200f8, -0x00005349,0x000500aa,0x0000002f,0x0000534b, -0x0000533f,0x0000012b,0x000300f7,0x0000534e, -0x00000000,0x000400fa,0x0000534b,0x0000534c, -0x0000534e,0x000200f8,0x0000534c,0x000200f9, -0x0000537e,0x000200f8,0x0000534e,0x000500c2, -0x00000006,0x00005350,0x0000533f,0x00000355, -0x0004007c,0x000000e7,0x00005351,0x00005350, -0x00050082,0x000000e7,0x00005352,0x00005351, -0x00000358,0x000500af,0x0000002f,0x00005354, -0x00005352,0x00000321,0x000300f7,0x0000535a, -0x00000000,0x000400fa,0x00005354,0x00005355, -0x0000535a,0x000200f8,0x00005355,0x000600a9, -0x00000006,0x00005358,0x00005343,0x00000360, -0x00000361,0x000500c5,0x00000006,0x00005359, -0x0000533d,0x00005358,0x000200f9,0x0000537e, -0x000200f8,0x0000535a,0x000500b1,0x0000002f, -0x0000535c,0x00005352,0x00000366,0x000300f7, -0x00005366,0x00000000,0x000400fa,0x0000535c, -0x0000535d,0x00005366,0x000200f8,0x0000535d, -0x000300f7,0x00005364,0x00000000,0x000400fa, -0x00005343,0x0000535f,0x00005362,0x000200f8, -0x00005362,0x000200f9,0x00005364,0x000200f8, -0x0000535f,0x000500c5,0x00000006,0x00005361, -0x0000533d,0x0000036f,0x000200f9,0x00005364, -0x000200f8,0x00005364,0x000700f5,0x00000006, -0x000059ae,0x00005361,0x0000535f,0x0000533d, -0x00005362,0x000200f9,0x0000537e,0x000200f8, -0x00005366,0x000500c7,0x00000006,0x00005368, -0x0000533a,0x00000377,0x00050080,0x000000e7, -0x0000536a,0x00005351,0x00005cc4,0x0004007c, -0x00000006,0x0000536b,0x0000536a,0x000500c4, -0x00000006,0x0000536c,0x0000536b,0x0000037d, -0x000500c2,0x00000006,0x0000536e,0x00005368, -0x000001b7,0x000500c5,0x00000006,0x0000536f, -0x0000536c,0x0000536e,0x000300f7,0x00005375, -0x00000000,0x000400fa,0x00005343,0x00005371, -0x00005375,0x000200f8,0x00005371,0x000500c7, -0x00000006,0x00005373,0x0000533a,0x00000386, -0x000500ab,0x0000002f,0x00005374,0x00005373, -0x0000012b,0x000200f9,0x00005375,0x000200f8, -0x00005375,0x000700f5,0x0000002f,0x00005376, -0x00005343,0x00005366,0x00005374,0x00005371, -0x000300f7,0x0000537a,0x00000000,0x000400fa, -0x00005376,0x00005377,0x0000537a,0x000200f8, -0x00005377,0x00050080,0x00000006,0x00005379, -0x0000536f,0x00000135,0x000200f9,0x0000537a, -0x000200f8,0x0000537a,0x000700f5,0x00000006, -0x000059ad,0x0000536f,0x00005375,0x00005379, -0x00005377,0x000500c5,0x00000006,0x0000537d, -0x0000533d,0x000059ad,0x000200f9,0x0000537e, -0x000200f8,0x0000537e,0x000d00f5,0x00000006, -0x000059af,0x00005348,0x00005346,0x0000533d, -0x0000534c,0x00005359,0x00005355,0x000059ae, -0x00005364,0x0000537d,0x0000537a,0x000500c4, -0x00000006,0x00005143,0x000059af,0x00000321, -0x000500c5,0x00000006,0x00005144,0x000059ab, -0x00005143,0x00050095,0x00000130,0x00005397, -0x0000505e,0x0000513c,0x00050051,0x00000006, -0x00005398,0x00005397,0x00000001,0x00050051, -0x00000006,0x00005399,0x00005397,0x00000000, -0x00050080,0x00000006,0x0000539e,0x00005065, -0x00005398,0x00050050,0x00000007,0x0000539f, -0x00005399,0x0000539e,0x0004007c,0x00000014, -0x0000538f,0x0000539f,0x00060041,0x0000015f, -0x00005387,0x0000538f,0x0000015e,0x0000015e, -0x0005003e,0x00005387,0x00005144,0x00000002, -0x00000004,0x000200f9,0x0000510b,0x000200f8, -0x000050dc,0x00050080,0x00000006,0x000050de, -0x00004db0,0x000001a2,0x00050084,0x00000006, -0x000050e0,0x000001b6,0x00005926,0x00050080, -0x00000006,0x000050e1,0x000050de,0x000050e0, -0x00050051,0x00000027,0x000050e6,0x00005929, -0x00000000,0x0004007c,0x00000006,0x000053a5, -0x000050e6,0x00050095,0x00000130,0x000053c0, -0x0000505e,0x000050e1,0x00050051,0x00000006, -0x000053c1,0x000053c0,0x00000001,0x00050051, -0x00000006,0x000053c2,0x000053c0,0x00000000, -0x00050080,0x00000006,0x000053c7,0x00005065, -0x000053c1,0x00050050,0x00000007,0x000053c8, -0x000053c2,0x000053c7,0x0004007c,0x00000014, -0x000053b8,0x000053c8,0x00060041,0x0000015f, -0x000053b0,0x000053b8,0x0000015e,0x0000015e, -0x0005003e,0x000053b0,0x000053a5,0x00000002, -0x00000004,0x00050080,0x00000006,0x000050e9, -0x000050e1,0x000000df,0x00050051,0x00000027, -0x000050ed,0x00005929,0x00000001,0x0004007c, -0x00000006,0x000053ce,0x000050ed,0x00050095, -0x00000130,0x000053e9,0x0000505e,0x000050e9, -0x00050051,0x00000006,0x000053ea,0x000053e9, -0x00000001,0x00050051,0x00000006,0x000053eb, -0x000053e9,0x00000000,0x00050080,0x00000006, -0x000053f0,0x00005065,0x000053ea,0x00050050, -0x00000007,0x000053f1,0x000053eb,0x000053f0, -0x0004007c,0x00000014,0x000053e1,0x000053f1, -0x00060041,0x0000015f,0x000053d9,0x000053e1, -0x0000015e,0x0000015e,0x0005003e,0x000053d9, -0x000053ce,0x00000002,0x00000004,0x00050080, -0x00000006,0x000050f0,0x000050e1,0x00000194, -0x00050051,0x00000027,0x000050f4,0x00005929, -0x00000002,0x0004007c,0x00000006,0x000053f7, -0x000050f4,0x00050095,0x00000130,0x00005412, -0x0000505e,0x000050f0,0x00050051,0x00000006, -0x00005413,0x00005412,0x00000001,0x00050051, -0x00000006,0x00005414,0x00005412,0x00000000, -0x00050080,0x00000006,0x00005419,0x00005065, -0x00005413,0x00050050,0x00000007,0x0000541a, -0x00005414,0x00005419,0x0004007c,0x00000014, -0x0000540a,0x0000541a,0x00060041,0x0000015f, -0x00005402,0x0000540a,0x0000015e,0x0000015e, -0x0005003e,0x00005402,0x000053f7,0x00000002, -0x00000004,0x00050080,0x00000006,0x000050f7, -0x000050e1,0x0000019b,0x00050051,0x00000027, -0x000050fb,0x0000592c,0x00000000,0x0004007c, -0x00000006,0x00005420,0x000050fb,0x00050095, -0x00000130,0x0000543b,0x0000505e,0x000050f7, -0x00050051,0x00000006,0x0000543c,0x0000543b, -0x00000001,0x00050051,0x00000006,0x0000543d, -0x0000543b,0x00000000,0x00050080,0x00000006, -0x00005442,0x00005065,0x0000543c,0x00050050, -0x00000007,0x00005443,0x0000543d,0x00005442, -0x0004007c,0x00000014,0x00005433,0x00005443, -0x00060041,0x0000015f,0x0000542b,0x00005433, -0x0000015e,0x0000015e,0x0005003e,0x0000542b, -0x00005420,0x00000002,0x00000004,0x00050080, -0x00000006,0x000050fe,0x000050e1,0x000001a2, -0x00050051,0x00000027,0x00005102,0x0000592c, -0x00000001,0x0004007c,0x00000006,0x00005449, -0x00005102,0x00050095,0x00000130,0x00005464, -0x0000505e,0x000050fe,0x00050051,0x00000006, -0x00005465,0x00005464,0x00000001,0x00050051, -0x00000006,0x00005466,0x00005464,0x00000000, -0x00050080,0x00000006,0x0000546b,0x00005065, -0x00005465,0x00050050,0x00000007,0x0000546c, -0x00005466,0x0000546b,0x0004007c,0x00000014, -0x0000545c,0x0000546c,0x00060041,0x0000015f, -0x00005454,0x0000545c,0x0000015e,0x0000015e, -0x0005003e,0x00005454,0x00005449,0x00000002, -0x00000004,0x00050080,0x00000006,0x00005105, -0x000050e1,0x00000260,0x00050051,0x00000027, -0x00005109,0x0000592c,0x00000002,0x0004007c, -0x00000006,0x00005472,0x00005109,0x00050095, -0x00000130,0x0000548d,0x0000505e,0x00005105, -0x00050051,0x00000006,0x0000548e,0x0000548d, -0x00000001,0x00050051,0x00000006,0x0000548f, -0x0000548d,0x00000000,0x00050080,0x00000006, -0x00005494,0x00005065,0x0000548e,0x00050050, -0x00000007,0x00005495,0x0000548f,0x00005494, -0x0004007c,0x00000014,0x00005485,0x00005495, -0x00060041,0x0000015f,0x0000547d,0x00005485, -0x0000015e,0x0000015e,0x0005003e,0x0000547d, -0x00005472,0x00000002,0x00000004,0x000200f9, -0x0000510b,0x000200f8,0x0000510b,0x000200f9, -0x00004dce,0x000200f8,0x00004dce,0x000200f9, -0x00004dcf,0x000200f8,0x00004dcf,0x000700f5, -0x00000006,0x00005bf6,0x00005942,0x00004dbf, -0x00004dc2,0x00004dce,0x00050080,0x00000006, -0x00004dd1,0x00005926,0x0000022b,0x000200f9, -0x00004db1,0x000200f8,0x00004dd2,0x00050041, -0x00000182,0x0000549d,0x00000180,0x00000321, -0x0004003d,0x00000006,0x0000549e,0x0000549d, -0x00050082,0x00000006,0x0000549f,0x00004db0, -0x0000549e,0x000500c7,0x00000006,0x000054ab, -0x00005923,0x00000c2c,0x000500aa,0x0000002f, -0x000054ac,0x000054ab,0x000000df,0x000600a9, -0x00000006,0x000054a2,0x000054ac,0x0000018b, -0x00000309,0x00050086,0x00000006,0x000054a3, -0x0000549f,0x000054a2,0x00050041,0x00000182, -0x000054bb,0x00000180,0x000001b7,0x0004003d, -0x00000006,0x000054bc,0x000054bb,0x00050084, -0x00000006,0x000054bd,0x000001b6,0x000054bc, -0x00050080,0x00000006,0x000054be,0x00004f51, -0x000054bd,0x00050084,0x00000006,0x000054b3, -0x000001cc,0x000054a3,0x00050080,0x00000006, -0x000054b4,0x000054be,0x000054b3,0x00050095, -0x00000130,0x000054ee,0x00004f82,0x000054b4, -0x00050051,0x00000006,0x000054ef,0x000054ee, -0x00000001,0x00050051,0x00000006,0x000054f0, -0x000054ee,0x00000000,0x00050080,0x00000006, -0x000054f5,0x00004f89,0x000054ef,0x00050050, -0x00000007,0x000054f6,0x000054f0,0x000054f5, -0x0004007c,0x00000014,0x000054e6,0x000054f6, -0x00050051,0x00000027,0x000054fa,0x00005929, -0x00000000,0x00050051,0x00000027,0x000054fc, -0x0000592c,0x00000000,0x000500bc,0x0000002f, -0x000054fd,0x000054fa,0x000054fc,0x000300f7, -0x00005504,0x00000000,0x000400fa,0x000054fd, -0x000054fe,0x00005504,0x000200f8,0x000054fe, -0x00050051,0x00000027,0x00005500,0x00005929, -0x00000001,0x00050051,0x00000027,0x00005502, -0x0000592c,0x00000001,0x000500bc,0x0000002f, -0x00005503,0x00005500,0x00005502,0x000200f9, -0x00005504,0x000200f8,0x00005504,0x000700f5, -0x0000002f,0x00005505,0x000054fd,0x00004dd2, -0x00005503,0x000054fe,0x000300f7,0x0000550c, -0x00000000,0x000400fa,0x00005505,0x00005506, -0x0000550c,0x000200f8,0x00005506,0x00050051, -0x00000027,0x00005508,0x00005929,0x00000002, -0x00050051,0x00000027,0x0000550a,0x0000592c, -0x00000002,0x000500bc,0x0000002f,0x0000550b, -0x00005508,0x0000550a,0x000200f9,0x0000550c, -0x000200f8,0x0000550c,0x000700f5,0x0000002f, -0x0000550d,0x00005505,0x00005504,0x0000550b, -0x00005506,0x000300f7,0x00004e00,0x00000000, -0x000400fa,0x0000550d,0x00004ddb,0x00004e00, -0x000200f8,0x00004ddb,0x00060041,0x0000015f, -0x00004ddd,0x000054e6,0x0000015e,0x0000022b, -0x0004007c,0x00000006,0x00005514,0x000054fa, -0x000500c7,0x00000006,0x00005516,0x00005514, -0x00000208,0x000500ab,0x0000002f,0x00005517, -0x00005516,0x0000012b,0x000300f7,0x0000551e, -0x00000000,0x000400fa,0x00005517,0x00005518, -0x0000551b,0x000200f8,0x0000551b,0x000500c5, -0x00000006,0x0000551d,0x00005514,0x00000208, -0x000200f9,0x0000551e,0x000200f8,0x00005518, -0x000400c8,0x00000006,0x0000551a,0x00005514, -0x000200f9,0x0000551e,0x000200f8,0x0000551e, -0x000700f5,0x00000006,0x00005930,0x0000551a, -0x00005518,0x0000551d,0x0000551b,0x000700ed, -0x00000006,0x00004de1,0x00004ddd,0x00000135, -0x0000012b,0x00005930,0x00060041,0x0000015f, -0x00004de3,0x000054e6,0x0000015e,0x000002dc, -0x00050051,0x00000027,0x00004de5,0x00005929, -0x00000001,0x0004007c,0x00000006,0x00005525, -0x00004de5,0x000500c7,0x00000006,0x00005527, -0x00005525,0x00000208,0x000500ab,0x0000002f, -0x00005528,0x00005527,0x0000012b,0x000300f7, -0x0000552f,0x00000000,0x000400fa,0x00005528, -0x00005529,0x0000552c,0x000200f8,0x0000552c, -0x000500c5,0x00000006,0x0000552e,0x00005525, -0x00000208,0x000200f9,0x0000552f,0x000200f8, -0x00005529,0x000400c8,0x00000006,0x0000552b, -0x00005525,0x000200f9,0x0000552f,0x000200f8, -0x0000552f,0x000700f5,0x00000006,0x00005932, -0x0000552b,0x00005529,0x0000552e,0x0000552c, -0x000700ed,0x00000006,0x00004de7,0x00004de3, -0x00000135,0x0000012b,0x00005932,0x00060041, -0x0000015f,0x00004de9,0x000054e6,0x0000015e, -0x000002e4,0x00050051,0x00000027,0x00004deb, -0x00005929,0x00000002,0x0004007c,0x00000006, -0x00005536,0x00004deb,0x000500c7,0x00000006, -0x00005538,0x00005536,0x00000208,0x000500ab, -0x0000002f,0x00005539,0x00005538,0x0000012b, -0x000300f7,0x00005540,0x00000000,0x000400fa, -0x00005539,0x0000553a,0x0000553d,0x000200f8, -0x0000553d,0x000500c5,0x00000006,0x0000553f, -0x00005536,0x00000208,0x000200f9,0x00005540, -0x000200f8,0x0000553a,0x000400c8,0x00000006, -0x0000553c,0x00005536,0x000200f9,0x00005540, -0x000200f8,0x00005540,0x000700f5,0x00000006, -0x00005934,0x0000553c,0x0000553a,0x0000553f, -0x0000553d,0x000700ed,0x00000006,0x00004ded, -0x00004de9,0x00000135,0x0000012b,0x00005934, -0x00060041,0x0000015f,0x00004def,0x000054e6, -0x0000015e,0x000002ec,0x0004007c,0x00000006, -0x00005547,0x000054fc,0x000500c7,0x00000006, -0x00005549,0x00005547,0x00000208,0x000500ab, -0x0000002f,0x0000554a,0x00005549,0x0000012b, -0x000300f7,0x00005551,0x00000000,0x000400fa, -0x0000554a,0x0000554b,0x0000554e,0x000200f8, -0x0000554e,0x000500c5,0x00000006,0x00005550, -0x00005547,0x00000208,0x000200f9,0x00005551, -0x000200f8,0x0000554b,0x000400c8,0x00000006, -0x0000554d,0x00005547,0x000200f9,0x00005551, -0x000200f8,0x00005551,0x000700f5,0x00000006, -0x0000593a,0x0000554d,0x0000554b,0x00005550, -0x0000554e,0x000700ef,0x00000006,0x00004df3, -0x00004def,0x00000135,0x0000012b,0x0000593a, -0x00060041,0x0000015f,0x00004df5,0x000054e6, -0x0000015e,0x000002f4,0x00050051,0x00000027, -0x00004df7,0x0000592c,0x00000001,0x0004007c, -0x00000006,0x00005558,0x00004df7,0x000500c7, -0x00000006,0x0000555a,0x00005558,0x00000208, -0x000500ab,0x0000002f,0x0000555b,0x0000555a, -0x0000012b,0x000300f7,0x00005562,0x00000000, -0x000400fa,0x0000555b,0x0000555c,0x0000555f, -0x000200f8,0x0000555f,0x000500c5,0x00000006, -0x00005561,0x00005558,0x00000208,0x000200f9, -0x00005562,0x000200f8,0x0000555c,0x000400c8, -0x00000006,0x0000555e,0x00005558,0x000200f9, -0x00005562,0x000200f8,0x00005562,0x000700f5, -0x00000006,0x0000593c,0x0000555e,0x0000555c, -0x00005561,0x0000555f,0x000700ef,0x00000006, -0x00004df9,0x00004df5,0x00000135,0x0000012b, -0x0000593c,0x00060041,0x0000015f,0x00004dfb, -0x000054e6,0x0000015e,0x00000318,0x00050051, -0x00000027,0x00004dfd,0x0000592c,0x00000002, -0x0004007c,0x00000006,0x00005569,0x00004dfd, -0x000500c7,0x00000006,0x0000556b,0x00005569, -0x00000208,0x000500ab,0x0000002f,0x0000556c, -0x0000556b,0x0000012b,0x000300f7,0x00005573, -0x00000000,0x000400fa,0x0000556c,0x0000556d, -0x00005570,0x000200f8,0x00005570,0x000500c5, -0x00000006,0x00005572,0x00005569,0x00000208, -0x000200f9,0x00005573,0x000200f8,0x0000556d, -0x000400c8,0x00000006,0x0000556f,0x00005569, -0x000200f9,0x00005573,0x000200f8,0x00005573, -0x000700f5,0x00000006,0x0000593e,0x0000556f, -0x0000556d,0x00005572,0x00005570,0x000700ef, -0x00000006,0x00004dff,0x00004dfb,0x00000135, -0x0000012b,0x0000593e,0x000200f9,0x00004e00, -0x000200f8,0x00004e00,0x00060041,0x0000015f, -0x00004e02,0x000054e6,0x0000015e,0x0000015e, -0x000700ea,0x00000006,0x00004e03,0x00004e02, -0x0000022b,0x00000721,0x00000135,0x00050080, -0x00000006,0x00004e05,0x00004e03,0x00000135, -0x000500ab,0x0000002f,0x00004e07,0x00004e05, -0x00005942,0x000300f7,0x00004e09,0x00000000, -0x000400fa,0x00004e07,0x00004e08,0x00004e09, -0x000200f8,0x00004e08,0x000200f9,0x00004e14, -0x000200f8,0x00004e09,0x000300f7,0x000055af, -0x00000000,0x000300fb,0x0000012b,0x00005581, -0x000200f8,0x00005581,0x000200f9,0x00005584, -0x000200f8,0x00005584,0x000700f5,0x00000006, -0x00005949,0x0000012b,0x00005581,0x00005592, -0x00005588,0x000500b0,0x0000002f,0x00005587, -0x00005949,0x0000031c,0x000400f6,0x00005593, -0x00005588,0x00000000,0x000400fa,0x00005587, -0x00005588,0x00005593,0x000200f8,0x00005588, -0x00050080,0x00000006,0x0000558c,0x00000135, -0x00005949,0x00060041,0x0000015f,0x0000558d, -0x000054e6,0x0000015e,0x0000558c,0x000700f1, -0x00000006,0x0000558e,0x0000558d,0x00000135, -0x0000012b,0x0000012b,0x00050041,0x00000009, -0x0000558f,0x00005579,0x00005949,0x0003003e, -0x0000558f,0x0000558e,0x00050080,0x00000006, -0x00005592,0x00005949,0x0000022b,0x000200f9, -0x00005584,0x000200f8,0x00005593,0x00050041, -0x00000009,0x00005594,0x00005579,0x0000015e, -0x0004003d,0x00000006,0x00005595,0x00005594, -0x000500aa,0x0000002f,0x00005596,0x00005595, -0x00000500,0x000300f7,0x0000559a,0x00000000, -0x000400fa,0x00005596,0x00005597,0x0000559a, -0x000200f8,0x00005597,0x000200f9,0x000055af, -0x000200f8,0x0000559a,0x0004003d,0x00000006, -0x0000559c,0x00005594,0x000500c7,0x00000006, -0x000055fe,0x0000559c,0x00000208,0x000500ab, -0x0000002f,0x000055ff,0x000055fe,0x0000012b, -0x000300f7,0x00005606,0x00000000,0x000400fa, -0x000055ff,0x00005600,0x00005603,0x000200f8, -0x00005603,0x000400c8,0x00000006,0x00005605, -0x0000559c,0x000200f9,0x00005606,0x000200f8, -0x00005600,0x000500c7,0x00000006,0x00005602, -0x0000559c,0x0000021d,0x000200f9,0x00005606, -0x000200f8,0x00005606,0x000700f5,0x00000006, -0x0000594a,0x00005602,0x00005600,0x00005605, -0x00005603,0x0004007c,0x00000027,0x00005608, -0x0000594a,0x00050041,0x00000009,0x0000559e, -0x00005579,0x0000022b,0x0004003d,0x00000006, -0x0000559f,0x0000559e,0x000500c7,0x00000006, -0x0000560d,0x0000559f,0x00000208,0x000500ab, -0x0000002f,0x0000560e,0x0000560d,0x0000012b, -0x000300f7,0x00005615,0x00000000,0x000400fa, -0x0000560e,0x0000560f,0x00005612,0x000200f8, -0x00005612,0x000400c8,0x00000006,0x00005614, -0x0000559f,0x000200f9,0x00005615,0x000200f8, -0x0000560f,0x000500c7,0x00000006,0x00005611, -0x0000559f,0x0000021d,0x000200f9,0x00005615, -0x000200f8,0x00005615,0x000700f5,0x00000006, -0x0000594b,0x00005611,0x0000560f,0x00005614, -0x00005612,0x0004007c,0x00000027,0x00005617, -0x0000594b,0x00050041,0x00000009,0x000055a1, -0x00005579,0x000002dc,0x0004003d,0x00000006, -0x000055a2,0x000055a1,0x000500c7,0x00000006, -0x0000561c,0x000055a2,0x00000208,0x000500ab, -0x0000002f,0x0000561d,0x0000561c,0x0000012b, -0x000300f7,0x00005624,0x00000000,0x000400fa, -0x0000561d,0x0000561e,0x00005621,0x000200f8, -0x00005621,0x000400c8,0x00000006,0x00005623, -0x000055a2,0x000200f9,0x00005624,0x000200f8, -0x0000561e,0x000500c7,0x00000006,0x00005620, -0x000055a2,0x0000021d,0x000200f9,0x00005624, -0x000200f8,0x00005624,0x000700f5,0x00000006, -0x0000594c,0x00005620,0x0000561e,0x00005623, -0x00005621,0x0004007c,0x00000027,0x00005626, -0x0000594c,0x00060050,0x00000063,0x000055a4, -0x00005608,0x00005617,0x00005626,0x00050041, -0x00000009,0x000055a5,0x00005579,0x000002e4, -0x0004003d,0x00000006,0x000055a6,0x000055a5, -0x000500c7,0x00000006,0x0000562b,0x000055a6, -0x00000208,0x000500ab,0x0000002f,0x0000562c, -0x0000562b,0x0000012b,0x000300f7,0x00005633, -0x00000000,0x000400fa,0x0000562c,0x0000562d, -0x00005630,0x000200f8,0x00005630,0x000400c8, -0x00000006,0x00005632,0x000055a6,0x000200f9, -0x00005633,0x000200f8,0x0000562d,0x000500c7, -0x00000006,0x0000562f,0x000055a6,0x0000021d, -0x000200f9,0x00005633,0x000200f8,0x00005633, -0x000700f5,0x00000006,0x0000594d,0x0000562f, -0x0000562d,0x00005632,0x00005630,0x0004007c, -0x00000027,0x00005635,0x0000594d,0x00050041, -0x00000009,0x000055a8,0x00005579,0x000002ec, -0x0004003d,0x00000006,0x000055a9,0x000055a8, -0x000500c7,0x00000006,0x0000563a,0x000055a9, -0x00000208,0x000500ab,0x0000002f,0x0000563b, -0x0000563a,0x0000012b,0x000300f7,0x00005642, -0x00000000,0x000400fa,0x0000563b,0x0000563c, -0x0000563f,0x000200f8,0x0000563f,0x000400c8, -0x00000006,0x00005641,0x000055a9,0x000200f9, -0x00005642,0x000200f8,0x0000563c,0x000500c7, -0x00000006,0x0000563e,0x000055a9,0x0000021d, -0x000200f9,0x00005642,0x000200f8,0x00005642, -0x000700f5,0x00000006,0x0000594e,0x0000563e, -0x0000563c,0x00005641,0x0000563f,0x0004007c, -0x00000027,0x00005644,0x0000594e,0x00050041, -0x00000009,0x000055ab,0x00005579,0x000002f4, -0x0004003d,0x00000006,0x000055ac,0x000055ab, -0x000500c7,0x00000006,0x00005649,0x000055ac, -0x00000208,0x000500ab,0x0000002f,0x0000564a, -0x00005649,0x0000012b,0x000300f7,0x00005651, -0x00000000,0x000400fa,0x0000564a,0x0000564b, -0x0000564e,0x000200f8,0x0000564e,0x000400c8, -0x00000006,0x00005650,0x000055ac,0x000200f9, -0x00005651,0x000200f8,0x0000564b,0x000500c7, -0x00000006,0x0000564d,0x000055ac,0x0000021d, -0x000200f9,0x00005651,0x000200f8,0x00005651, -0x000700f5,0x00000006,0x0000594f,0x0000564d, -0x0000564b,0x00005650,0x0000564e,0x0004007c, -0x00000027,0x00005653,0x0000594f,0x00060050, -0x00000063,0x000055ae,0x00005635,0x00005644, -0x00005653,0x000200f9,0x000055af,0x000200f8, -0x000055af,0x000700f5,0x00000063,0x00005954, -0x00005cc2,0x00005597,0x000055ae,0x00005651, -0x000700f5,0x00000063,0x00005950,0x0000053d, -0x00005597,0x000055a4,0x00005651,0x00050082, -0x00000006,0x00005660,0x00005092,0x0000503d, -0x00050084,0x00000006,0x00005661,0x000000df, -0x00005660,0x00050080,0x00000006,0x00005662, -0x00005038,0x00005661,0x00050095,0x00000130, -0x00005682,0x0000505e,0x00005662,0x00050051, -0x00000006,0x00005683,0x00005682,0x00000001, -0x00050051,0x00000006,0x00005684,0x00005682, -0x00000000,0x00050080,0x00000006,0x00005689, -0x00005065,0x00005683,0x00050050,0x00000007, -0x0000568a,0x00005684,0x00005689,0x0004007c, -0x00000014,0x0000567a,0x0000568a,0x00060041, -0x0000015f,0x00005671,0x0000567a,0x0000015e, -0x0000015e,0x0006003d,0x00000006,0x00005672, -0x00005671,0x00000002,0x00000004,0x000200f9, -0x00004e11,0x000200f8,0x00004e11,0x00050080, -0x00000006,0x00004e13,0x00005925,0x0000022b, -0x000200f9,0x00004da6,0x000200f8,0x00004e14, -0x000700f5,0x0000002f,0x00005978,0x00000393, -0x00004da6,0x000003ae,0x00004e08,0x000300f7, -0x00004e16,0x00000000,0x000400fa,0x00005978, -0x00004e17,0x00004e16,0x000200f8,0x00004e16, -0x000200f9,0x00004e17,0x000200f8,0x00004e17, -0x000200f9,0x000012ee,0x000200f8,0x000012ee, -0x000200f9,0x000012e4,0x000200f8,0x000012e3, -0x000300f7,0x00003d8d,0x00000000,0x000300fb, -0x0000012b,0x00003c9f,0x000200f8,0x00003c9f, -0x0003003e,0x00003c67,0x00000ed6,0x0003003e, -0x00003c68,0x00000ed6,0x00050041,0x00000182, -0x00003ca0,0x00000180,0x000001b7,0x0004003d, -0x00000006,0x00003ca1,0x00003ca0,0x000500b2, -0x0000002f,0x00003ca2,0x00003ca1,0x00000135, -0x000300f7,0x00003d22,0x00000000,0x000400fa, -0x00003ca2,0x00003ca3,0x00003cb2,0x000200f8, -0x00003cb2,0x00050041,0x00000182,0x00003e00, -0x00000180,0x00000181,0x0004003d,0x00000006, -0x00003e01,0x00003e00,0x00050084,0x00000006, -0x00003e02,0x000001a2,0x00003e01,0x00050080, -0x00000006,0x00003e03,0x0000018b,0x00003e02, -0x00050080,0x00000006,0x00003e09,0x00003e01, -0x00005cc3,0x00050086,0x00000006,0x00003e0a, -0x00003e09,0x00000185,0x00050084,0x00000006, -0x00003dfc,0x0000018b,0x00003e0a,0x00050080, -0x00000006,0x00003dfd,0x00003e03,0x00003dfc, -0x00050080,0x00000006,0x00003df7,0x00003dfd, -0x00003dfc,0x00050084,0x00000006,0x00003df0, -0x000001b6,0x00003ca1,0x00050080,0x00000006, -0x00003df1,0x00003df7,0x00003df0,0x00050041, -0x00000182,0x00003de7,0x00000180,0x000001cd, -0x0004003d,0x00000006,0x00003de8,0x00003de7, -0x00050084,0x00000006,0x00003de9,0x000001cc, -0x00003de8,0x00050080,0x00000006,0x00003dea, -0x00003df1,0x00003de9,0x000500ac,0x0000002f, -0x00003e17,0x00003ca1,0x00000135,0x000300f7, -0x00003e1d,0x00000000,0x000400fa,0x00003e17, -0x00003e18,0x00003e1c,0x000200f8,0x00003e1c, -0x000200f9,0x00003e1d,0x000200f8,0x00003e18, -0x00050082,0x00000006,0x00003e1b,0x00003ca1, -0x00000135,0x000200f9,0x00003e1d,0x000200f8, -0x00003e1d,0x000700f5,0x00000006,0x000059cb, -0x00003e1b,0x00003e18,0x0000012b,0x00003e1c, -0x00050084,0x00000006,0x00003de2,0x000000df, -0x000059cb,0x00050080,0x00000006,0x00003de3, -0x00003dea,0x00003de2,0x000300f7,0x00003e2a, -0x00000000,0x000400fa,0x00003e17,0x00003e25, -0x00003e29,0x000200f8,0x00003e29,0x000200f9, -0x00003e2a,0x000200f8,0x00003e25,0x00050082, -0x00000006,0x00003e28,0x00003ca1,0x00000135, -0x000200f9,0x00003e2a,0x000200f8,0x00003e2a, -0x000700f5,0x00000006,0x000059cc,0x00003e28, -0x00003e25,0x0000012b,0x00003e29,0x00050084, -0x00000006,0x00003ddc,0x000000df,0x000059cc, -0x00050080,0x00000006,0x00003ddd,0x00003de3, -0x00003ddc,0x000300f7,0x00003e37,0x00000000, -0x000400fa,0x00003e17,0x00003e32,0x00003e36, -0x000200f8,0x00003e36,0x000200f9,0x00003e37, -0x000200f8,0x00003e32,0x00050082,0x00000006, -0x00003e35,0x00003ca1,0x00000135,0x000200f9, -0x00003e37,0x000200f8,0x00003e37,0x000700f5, -0x00000006,0x000059cd,0x00003e35,0x00003e32, -0x0000012b,0x00003e36,0x00050084,0x00000006, -0x00003dd6,0x000000df,0x000059cd,0x00050080, -0x00000006,0x00003dd7,0x00003ddd,0x00003dd6, -0x00050084,0x00000006,0x00003cb5,0x000000df, -0x000011de,0x00050080,0x00000006,0x00003cb6, -0x00003dd7,0x00003cb5,0x00050041,0x0000022d, -0x00003cb7,0x00000180,0x0000022b,0x0004003d, -0x00000007,0x00003cb8,0x00003cb7,0x00050051, -0x00000006,0x00003e4f,0x00003cb8,0x00000000, -0x00050095,0x00000130,0x00003e51,0x00003e4f, -0x00003cb6,0x00050051,0x00000006,0x00003e52, -0x00003e51,0x00000001,0x00050051,0x00000006, -0x00003e53,0x00003e51,0x00000000,0x00050051, -0x00000006,0x00003e56,0x00003cb8,0x00000001, -0x00050080,0x00000006,0x00003e58,0x00003e56, -0x00003e52,0x00050050,0x00000007,0x00003e59, -0x00003e53,0x00003e58,0x0004007c,0x00000014, -0x00003e49,0x00003e59,0x00060041,0x0000015f, -0x00003e40,0x00003e49,0x0000015e,0x0000015e, -0x0006003d,0x00000006,0x00003e41,0x00003e40, -0x00000002,0x00000004,0x000500aa,0x0000002f, -0x00003cba,0x00003e41,0x0000012b,0x000300f7, -0x00003cbc,0x00000000,0x000400fa,0x00003cba, -0x00003cbb,0x00003cbc,0x000200f8,0x00003cbb, -0x000200f9,0x00003d8d,0x000200f8,0x00003cbc, -0x000300f7,0x00003eab,0x00000000,0x000400fa, -0x00003e17,0x00003ea6,0x00003eaa,0x000200f8, -0x00003eaa,0x000200f9,0x00003eab,0x000200f8, -0x00003ea6,0x00050082,0x00000006,0x00003ea9, -0x00003ca1,0x00000135,0x000200f9,0x00003eab, -0x000200f8,0x00003eab,0x000700f5,0x00000006, -0x000059ce,0x00003ea9,0x00003ea6,0x0000012b, -0x00003eaa,0x00050084,0x00000006,0x00003e70, -0x000000df,0x000059ce,0x00050080,0x00000006, -0x00003e71,0x00003dea,0x00003e70,0x000300f7, -0x00003eb8,0x00000000,0x000400fa,0x00003e17, -0x00003eb3,0x00003eb7,0x000200f8,0x00003eb7, -0x000200f9,0x00003eb8,0x000200f8,0x00003eb3, -0x00050082,0x00000006,0x00003eb6,0x00003ca1, -0x00000135,0x000200f9,0x00003eb8,0x000200f8, -0x00003eb8,0x000700f5,0x00000006,0x000059cf, -0x00003eb6,0x00003eb3,0x0000012b,0x00003eb7, -0x00050084,0x00000006,0x00003e6a,0x000000df, -0x000059cf,0x00050080,0x00000006,0x00003e6b, -0x00003e71,0x00003e6a,0x000300f7,0x00003ec5, -0x00000000,0x000400fa,0x00003e17,0x00003ec0, -0x00003ec4,0x000200f8,0x00003ec4,0x000200f9, -0x00003ec5,0x000200f8,0x00003ec0,0x00050082, -0x00000006,0x00003ec3,0x00003ca1,0x00000135, -0x000200f9,0x00003ec5,0x000200f8,0x00003ec5, -0x000700f5,0x00000006,0x000059d0,0x00003ec3, -0x00003ec0,0x0000012b,0x00003ec4,0x00050084, -0x00000006,0x00003e64,0x000000df,0x000059d0, -0x00050080,0x00000006,0x00003e65,0x00003e6b, -0x00003e64,0x000300f7,0x00003ed2,0x00000000, -0x000400fa,0x00003e17,0x00003ecd,0x00003ed1, -0x000200f8,0x00003ed1,0x000200f9,0x00003ed2, -0x000200f8,0x00003ecd,0x00050082,0x00000006, -0x00003ed0,0x00003ca1,0x00000135,0x000200f9, -0x00003ed2,0x000200f8,0x00003ed2,0x000700f5, -0x00000006,0x000059d1,0x00003ed0,0x00003ecd, -0x0000012b,0x00003ed1,0x00050084,0x00000006, -0x00003e5e,0x000000df,0x000059d1,0x00050080, -0x00000006,0x00003e5f,0x00003e65,0x00003e5e, -0x00050080,0x00000006,0x00003cc0,0x00003e5f, -0x00003cb5,0x00050095,0x00000130,0x00003eec, -0x00003e4f,0x00003cc0,0x00050051,0x00000006, -0x00003eed,0x00003eec,0x00000001,0x00050051, -0x00000006,0x00003eee,0x00003eec,0x00000000, -0x00050080,0x00000006,0x00003ef3,0x00003e56, -0x00003eed,0x00050050,0x00000007,0x00003ef4, -0x00003eee,0x00003ef3,0x0004007c,0x00000014, -0x00003ee4,0x00003ef4,0x00060041,0x0000015f, -0x00003edb,0x00003ee4,0x0000015e,0x0000015e, -0x0006003d,0x00000006,0x00003edc,0x00003edb, -0x00000002,0x00000004,0x000500ae,0x0000002f, -0x00003cc7,0x00003edc,0x00003de8,0x000300f7, -0x00003cc9,0x00000000,0x000400fa,0x00003cc7, -0x00003cc8,0x00003cc9,0x000200f8,0x00003cc8, -0x000200f9,0x00003d8d,0x000200f8,0x00003cc9, -0x00050080,0x00000006,0x00003ccd,0x00003dea, -0x00003cb5,0x00050095,0x00000130,0x00003f3b, -0x00003e4f,0x00003ccd,0x00050051,0x00000006, -0x00003f3c,0x00003f3b,0x00000001,0x00050051, -0x00000006,0x00003f3d,0x00003f3b,0x00000000, -0x00050080,0x00000006,0x00003f42,0x00003e56, -0x00003f3c,0x00050050,0x00000007,0x00003f43, -0x00003f3d,0x00003f42,0x0004007c,0x00000014, -0x00003f33,0x00003f43,0x00060041,0x0000015f, -0x00003f2a,0x00003f33,0x0000015e,0x0000015e, -0x0006003d,0x00000006,0x00003f2b,0x00003f2a, -0x00000002,0x00000004,0x000300f7,0x00003f83, -0x00000000,0x000400fa,0x00003e17,0x00003f7e, -0x00003f82,0x000200f8,0x00003f82,0x000200f9, -0x00003f83,0x000200f8,0x00003f7e,0x00050082, -0x00000006,0x00003f81,0x00003ca1,0x00000135, -0x000200f9,0x00003f83,0x000200f8,0x00003f83, -0x000700f5,0x00000006,0x000059d2,0x00003f81, -0x00003f7e,0x0000012b,0x00003f82,0x00050084, -0x00000006,0x00003f48,0x000000df,0x000059d2, -0x00050080,0x00000006,0x00003f49,0x00003dea, -0x00003f48,0x00050080,0x00000006,0x00003cd4, -0x00003f49,0x00003cb5,0x00050095,0x00000130, -0x00003f9d,0x00003e4f,0x00003cd4,0x00050051, -0x00000006,0x00003f9e,0x00003f9d,0x00000001, -0x00050051,0x00000006,0x00003f9f,0x00003f9d, -0x00000000,0x00050080,0x00000006,0x00003fa4, -0x00003e56,0x00003f9e,0x00050050,0x00000007, -0x00003fa5,0x00003f9f,0x00003fa4,0x0004007c, -0x00000014,0x00003f95,0x00003fa5,0x00060041, -0x0000015f,0x00003f8c,0x00003f95,0x0000015e, -0x0000015e,0x0006003d,0x00000006,0x00003f8d, -0x00003f8c,0x00000002,0x00000004,0x00050050, -0x00000f0e,0x00003cd8,0x00003f2b,0x00003f8d, -0x0003003e,0x00003c72,0x00003cd8,0x000200f9, -0x00003cd9,0x000200f8,0x00003cd9,0x000700f5, -0x00000006,0x000059d3,0x0000012b,0x00003f83, -0x00003d11,0x00003d0f,0x000700f5,0x00000006, -0x000059fc,0x0000012b,0x00003f83,0x000059fa, -0x00003d0f,0x000500b0,0x0000002f,0x00003cdc, -0x000059d3,0x00000247,0x000400f6,0x00003d12, -0x00003d0f,0x00000000,0x000400fa,0x00003cdc, -0x00003cdd,0x00003d12,0x000200f8,0x00003cdd, -0x00050041,0x00000009,0x00003cdf,0x00003c72, -0x000059d3,0x0004003d,0x00000006,0x00003ce0, -0x00003cdf,0x00050050,0x00000f0e,0x00003ce2, -0x00003ce0,0x00003ce0,0x0003003e,0x00003c79, -0x00003ce2,0x000500c7,0x00000006,0x00003ce4, -0x00003ce0,0x00000208,0x000500aa,0x0000002f, -0x00003ce5,0x00003ce4,0x0000012b,0x000300f7, -0x00003cf7,0x00000000,0x000400fa,0x00003ce5, -0x00003ce6,0x00003cf7,0x000200f8,0x00003ce6, -0x00050084,0x00000006,0x00003ce9,0x000000df, -0x00003ce0,0x00050080,0x00000006,0x00003cea, -0x00003dea,0x00003ce9,0x00050095,0x00000130, -0x00003fec,0x00003e4f,0x00003cea,0x00050051, -0x00000006,0x00003fed,0x00003fec,0x00000001, -0x00050051,0x00000006,0x00003fee,0x00003fec, -0x00000000,0x00050080,0x00000006,0x00003ff3, -0x00003e56,0x00003fed,0x00050050,0x00000007, -0x00003ff4,0x00003fee,0x00003ff3,0x0004007c, -0x00000014,0x00003fe4,0x00003ff4,0x00060041, -0x0000015f,0x00003fdb,0x00003fe4,0x0000015e, -0x0000015e,0x0006003d,0x00000006,0x00003fdc, -0x00003fdb,0x00000002,0x00000004,0x00050041, -0x00000009,0x00003cee,0x00003c79,0x0000015e, -0x0003003e,0x00003cee,0x00003fdc,0x000300f7, -0x00004034,0x00000000,0x000400fa,0x00003e17, -0x0000402f,0x00004033,0x000200f8,0x00004033, -0x000200f9,0x00004034,0x000200f8,0x0000402f, -0x00050082,0x00000006,0x00004032,0x00003ca1, -0x00000135,0x000200f9,0x00004034,0x000200f8, -0x00004034,0x000700f5,0x00000006,0x000059f3, -0x00004032,0x0000402f,0x0000012b,0x00004033, -0x00050084,0x00000006,0x00003ff9,0x000000df, -0x000059f3,0x00050080,0x00000006,0x00003ffa, -0x00003dea,0x00003ff9,0x00050080,0x00000006, -0x00003cf2,0x00003ffa,0x00003ce9,0x00050095, -0x00000130,0x0000404e,0x00003e4f,0x00003cf2, -0x00050051,0x00000006,0x0000404f,0x0000404e, -0x00000001,0x00050051,0x00000006,0x00004050, -0x0000404e,0x00000000,0x00050080,0x00000006, -0x00004055,0x00003e56,0x0000404f,0x00050050, -0x00000007,0x00004056,0x00004050,0x00004055, -0x0004007c,0x00000014,0x00004046,0x00004056, -0x00060041,0x0000015f,0x0000403d,0x00004046, -0x0000015e,0x0000015e,0x0006003d,0x00000006, -0x0000403e,0x0000403d,0x00000002,0x00000004, -0x00050041,0x00000009,0x00003cf6,0x00003c79, -0x0000022b,0x0003003e,0x00003cf6,0x0000403e, -0x000200f9,0x00003cf7,0x000200f8,0x00003cf7, -0x000600a9,0x00000006,0x00005cdb,0x00003ce5, -0x00000247,0x00000135,0x000200f9,0x00003cf8, -0x000200f8,0x00003cf8,0x000700f5,0x00000006, -0x000059fa,0x000059fc,0x00003cf7,0x00003d05, -0x00003d0b,0x000700f5,0x00000006,0x000059f4, -0x0000012b,0x00003cf7,0x00003d0d,0x00003d0b, -0x000500b0,0x0000002f,0x00003cfc,0x000059f4, -0x00005cdb,0x000400f6,0x00003d0e,0x00003d0b, -0x00000000,0x000400fa,0x00003cfc,0x00003cfd, -0x00003d0e,0x000200f8,0x00003cfd,0x00050041, -0x00000009,0x00003d00,0x00003c79,0x000059f4, -0x0004003d,0x00000006,0x00003d01,0x00003d00, -0x000500c7,0x00000006,0x0000405d,0x00003d01, -0x00000208,0x000500ab,0x0000002f,0x0000405e, -0x0000405d,0x0000012b,0x000300f7,0x00004069, -0x00000000,0x000400fa,0x0000405e,0x0000405f, -0x00004068,0x000200f8,0x00004068,0x000200f9, -0x00004069,0x000200f8,0x0000405f,0x00050084, -0x00000006,0x0000406f,0x000000df,0x00003e01, -0x00050080,0x00000006,0x00004070,0x0000018b, -0x0000406f,0x000500c7,0x00000006,0x00004062, -0x00003d01,0x0000021d,0x00050084,0x00000006, -0x00004063,0x000000df,0x00004062,0x00050080, -0x00000006,0x00004064,0x00004070,0x00004063, -0x00050095,0x00000130,0x00004089,0x00003e4f, -0x00004064,0x00050051,0x00000006,0x0000408a, -0x00004089,0x00000001,0x00050051,0x00000006, -0x0000408b,0x00004089,0x00000000,0x00050080, -0x00000006,0x00004090,0x00003e56,0x0000408a, -0x00050050,0x00000007,0x00004091,0x0000408b, -0x00004090,0x0004007c,0x00000014,0x00004081, -0x00004091,0x00060041,0x0000015f,0x00004078, -0x00004081,0x0000015e,0x0000015e,0x0006003d, -0x00000006,0x00004079,0x00004078,0x00000002, -0x00000004,0x000200f9,0x00004069,0x000200f8, -0x00004069,0x000700f5,0x00000006,0x000059ff, -0x00004079,0x0000405f,0x00000500,0x00004068, -0x00050041,0x00000009,0x00003d03,0x00003c68, -0x000059fa,0x0003003e,0x00003d03,0x000059ff, -0x00050080,0x00000006,0x00003d05,0x000059fa, -0x0000022b,0x0004003d,0x00000006,0x00003d08, -0x00003d00,0x000300f7,0x000040ac,0x00000000, -0x000300fb,0x0000012b,0x0000409b,0x000200f8, -0x0000409b,0x000500c7,0x00000006,0x0000409d, -0x00003d08,0x00000208,0x000500ab,0x0000002f, -0x0000409e,0x0000409d,0x0000012b,0x000300f7, -0x000040a3,0x00000000,0x000400fa,0x0000409e, -0x0000409f,0x000040a3,0x000200f8,0x0000409f, -0x000300f7,0x000040c0,0x00000000,0x000400fa, -0x0000409e,0x000040b6,0x000040bf,0x000200f8, -0x000040bf,0x000200f9,0x000040c0,0x000200f8, -0x000040b6,0x00050084,0x00000006,0x000040c6, -0x000000df,0x00003e01,0x00050080,0x00000006, -0x000040c7,0x0000018b,0x000040c6,0x000500c7, -0x00000006,0x000040b9,0x00003d08,0x0000021d, -0x00050084,0x00000006,0x000040ba,0x000000df, -0x000040b9,0x00050080,0x00000006,0x000040bb, -0x000040c7,0x000040ba,0x00050095,0x00000130, -0x000040e0,0x00003e4f,0x000040bb,0x00050051, -0x00000006,0x000040e1,0x000040e0,0x00000001, -0x00050051,0x00000006,0x000040e2,0x000040e0, -0x00000000,0x00050080,0x00000006,0x000040e7, -0x00003e56,0x000040e1,0x00050050,0x00000007, -0x000040e8,0x000040e2,0x000040e7,0x0004007c, -0x00000014,0x000040d8,0x000040e8,0x00060041, -0x0000015f,0x000040cf,0x000040d8,0x0000015e, -0x0000015e,0x0006003d,0x00000006,0x000040d0, -0x000040cf,0x00000002,0x00000004,0x000200f9, -0x000040c0,0x000200f8,0x000040c0,0x000700f5, -0x00000006,0x00005a06,0x000040d0,0x000040b6, -0x00000500,0x000040bf,0x00050041,0x00000182, -0x000040eb,0x00000180,0x00000311,0x0004003d, -0x00000006,0x000040ec,0x000040eb,0x00050041, -0x00000182,0x000040fc,0x00000180,0x000002fb, -0x0004003d,0x00000006,0x000040fd,0x000040fc, -0x000500c7,0x00000006,0x000040fe,0x000040fd, -0x00000135,0x000500ab,0x0000002f,0x000040ff, -0x000040fe,0x0000012b,0x000600a9,0x00000006, -0x000040f9,0x000040ff,0x00000309,0x0000018b, -0x00050084,0x00000006,0x000040ef,0x00005a06, -0x000040f9,0x00050080,0x00000006,0x000040f0, -0x000040ec,0x000040ef,0x000500c2,0x00000006, -0x000040f1,0x000040f0,0x00000318,0x000500c4, -0x00000006,0x000040f2,0x000040f1,0x000002e4, -0x000600a9,0x00000006,0x000040f4,0x000040ff, -0x0000031c,0x0000012b,0x000500c5,0x00000006, -0x000040f5,0x000040f2,0x000040f4,0x000200f9, -0x000040ac,0x000200f8,0x000040a3,0x000300f7, -0x00004157,0x00000000,0x000400fa,0x00003e17, -0x00004152,0x00004156,0x000200f8,0x00004156, -0x000200f9,0x00004157,0x000200f8,0x00004152, -0x00050082,0x00000006,0x00004155,0x00003ca1, -0x00000135,0x000200f9,0x00004157,0x000200f8, -0x00004157,0x000700f5,0x00000006,0x00005a02, -0x00004155,0x00004152,0x0000012b,0x00004156, -0x00050084,0x00000006,0x0000411c,0x000000df, -0x00005a02,0x00050080,0x00000006,0x0000411d, -0x00003dea,0x0000411c,0x000300f7,0x00004164, -0x00000000,0x000400fa,0x00003e17,0x0000415f, -0x00004163,0x000200f8,0x00004163,0x000200f9, -0x00004164,0x000200f8,0x0000415f,0x00050082, -0x00000006,0x00004162,0x00003ca1,0x00000135, -0x000200f9,0x00004164,0x000200f8,0x00004164, -0x000700f5,0x00000006,0x00005a03,0x00004162, -0x0000415f,0x0000012b,0x00004163,0x00050084, -0x00000006,0x00004116,0x000000df,0x00005a03, -0x00050080,0x00000006,0x00004117,0x0000411d, -0x00004116,0x000300f7,0x00004171,0x00000000, -0x000400fa,0x00003e17,0x0000416c,0x00004170, -0x000200f8,0x00004170,0x000200f9,0x00004171, -0x000200f8,0x0000416c,0x00050082,0x00000006, -0x0000416f,0x00003ca1,0x00000135,0x000200f9, -0x00004171,0x000200f8,0x00004171,0x000700f5, -0x00000006,0x00005a04,0x0000416f,0x0000416c, -0x0000012b,0x00004170,0x00050084,0x00000006, -0x00004110,0x000000df,0x00005a04,0x00050080, -0x00000006,0x00004111,0x00004117,0x00004110, -0x000300f7,0x0000417e,0x00000000,0x000400fa, -0x00003e17,0x00004179,0x0000417d,0x000200f8, -0x0000417d,0x000200f9,0x0000417e,0x000200f8, -0x00004179,0x00050082,0x00000006,0x0000417c, -0x00003ca1,0x00000135,0x000200f9,0x0000417e, -0x000200f8,0x0000417e,0x000700f5,0x00000006, -0x00005a05,0x0000417c,0x00004179,0x0000012b, -0x0000417d,0x00050084,0x00000006,0x0000410a, -0x000000df,0x00005a05,0x00050080,0x00000006, -0x0000410b,0x00004111,0x0000410a,0x00050084, -0x00000006,0x000040a6,0x000000df,0x00003d08, -0x00050080,0x00000006,0x000040a7,0x0000410b, -0x000040a6,0x00050095,0x00000130,0x00004198, -0x00003e4f,0x000040a7,0x00050051,0x00000006, -0x00004199,0x00004198,0x00000001,0x00050051, -0x00000006,0x0000419a,0x00004198,0x00000000, -0x00050080,0x00000006,0x0000419f,0x00003e56, -0x00004199,0x00050050,0x00000007,0x000041a0, -0x0000419a,0x0000419f,0x0004007c,0x00000014, -0x00004190,0x000041a0,0x00060041,0x0000015f, -0x00004187,0x00004190,0x0000015e,0x0000015e, -0x0006003d,0x00000006,0x00004188,0x00004187, -0x00000002,0x00000004,0x00050041,0x00000182, -0x000041a3,0x00000180,0x00000321,0x0004003d, -0x00000006,0x000041a4,0x000041a3,0x00050041, -0x00000182,0x000041b4,0x00000180,0x000002fb, -0x0004003d,0x00000006,0x000041b5,0x000041b4, -0x000500c7,0x00000006,0x000041b6,0x000041b5, -0x00000247,0x000500ab,0x0000002f,0x000041b7, -0x000041b6,0x0000012b,0x000600a9,0x00000006, -0x000041b1,0x000041b7,0x0000018b,0x00000309, -0x00050084,0x00000006,0x000041a7,0x00004188, -0x000041b1,0x00050080,0x00000006,0x000041a8, -0x000041a4,0x000041a7,0x000500c2,0x00000006, -0x000041a9,0x000041a8,0x00000318,0x000500c4, -0x00000006,0x000041aa,0x000041a9,0x000002e4, -0x000600a9,0x00000006,0x000041ac,0x000041b7, -0x000000df,0x0000032b,0x000500c5,0x00000006, -0x000041ad,0x000041aa,0x000041ac,0x000200f9, -0x000040ac,0x000200f8,0x000040ac,0x000700f5, -0x00000006,0x00005a07,0x000040f5,0x000040c0, -0x000041ad,0x0000417e,0x00050041,0x00000009, -0x00003d0a,0x00003c67,0x000059fa,0x0003003e, -0x00003d0a,0x00005a07,0x000200f9,0x00003d0b, -0x000200f8,0x00003d0b,0x00050080,0x00000006, -0x00003d0d,0x000059f4,0x0000022b,0x000200f9, -0x00003cf8,0x000200f8,0x00003d0e,0x000200f9, -0x00003d0f,0x000200f8,0x00003d0f,0x00050080, -0x00000006,0x00003d11,0x000059d3,0x0000022b, -0x000200f9,0x00003cd9,0x000200f8,0x00003d12, -0x00050041,0x00000182,0x000041c0,0x00000180, -0x000002fb,0x0004003d,0x00000006,0x000041c1, -0x000041c0,0x000500c7,0x00000006,0x000041c2, -0x000041c1,0x00000135,0x000500aa,0x0000002f, -0x00003d14,0x000041c2,0x0000012b,0x000300f7, -0x00003d1a,0x00000000,0x000400fa,0x00003d14, -0x00003d15,0x00003d1a,0x000200f8,0x00003d15, -0x000500c7,0x00000006,0x00003d18,0x000041c1, -0x000000df,0x000500ab,0x0000002f,0x00003d19, -0x00003d18,0x0000012b,0x000200f9,0x00003d1a, -0x000200f8,0x00003d1a,0x000700f5,0x0000002f, -0x00003d1b,0x00003d14,0x00003d12,0x00003d19, -0x00003d15,0x000300f7,0x00003d21,0x00000000, -0x000400fa,0x00003d1b,0x00003d1c,0x00003d21, -0x000200f8,0x00003d1c,0x0004003d,0x000000e0, -0x00003d1d,0x00003c68,0x0003003e,0x00003c82, -0x00003d1d,0x0004003d,0x000000e0,0x00003d1e, -0x00003c67,0x0003003e,0x00003c83,0x00003d1e, -0x000200f9,0x000041f9,0x000200f8,0x000041f9, -0x000700f5,0x00000006,0x000059d4,0x0000012b, -0x00003d1c,0x0000423f,0x0000423d,0x000500b0, -0x0000002f,0x000041fc,0x000059d4,0x000000df, -0x000400f6,0x00004240,0x0000423d,0x00000000, -0x000400fa,0x000041fc,0x000041fd,0x00004240, -0x000200f8,0x000041fd,0x00050041,0x0000008d, -0x000041ff,0x000041c5,0x000059d4,0x0003003e, -0x000041ff,0x00000393,0x00050041,0x0000008d, -0x00004201,0x000041c6,0x000059d4,0x0003003e, -0x00004201,0x00000393,0x00050041,0x00000009, -0x00004203,0x000041c7,0x000059d4,0x0003003e, -0x00004203,0x0000012b,0x000200f9,0x00004204, -0x000200f8,0x00004204,0x000700f5,0x00000006, -0x000059ec,0x0000012b,0x000041fd,0x0000420e, -0x00004208,0x000500b0,0x0000002f,0x00004207, -0x000059ec,0x00000437,0x000400f6,0x0000420f, -0x00004208,0x00000000,0x000400fa,0x00004207, -0x00004208,0x0000420f,0x000200f8,0x00004208, -0x00060041,0x000000d8,0x0000420b,0x000041c9, -0x000059d4,0x000059ec,0x0003003e,0x0000420b, -0x00000b0f,0x00050080,0x00000006,0x0000420e, -0x000059ec,0x0000022b,0x000200f9,0x00004204, -0x000200f8,0x0000420f,0x00050041,0x00000009, -0x00004211,0x00003c82,0x000059d4,0x0004003d, -0x00000006,0x00004212,0x00004211,0x000500aa, -0x0000002f,0x00004213,0x00004212,0x00000500, -0x000300f7,0x00004215,0x00000000,0x000400fa, -0x00004213,0x00004214,0x00004215,0x000200f8, -0x00004214,0x000200f9,0x0000423d,0x000200f8, -0x00004215,0x0004003d,0x00000006,0x00004219, -0x00004211,0x00050041,0x00000182,0x00004319, -0x00000180,0x00000311,0x0004003d,0x00000006, -0x0000431a,0x00004319,0x00050084,0x00000006, -0x0000431c,0x0000018b,0x00004219,0x00050080, -0x00000006,0x0000431d,0x0000431a,0x0000431c, -0x00050080,0x00000006,0x0000421b,0x0000431d, -0x000004e8,0x00050041,0x0000022d,0x0000421c, -0x00000180,0x0000015e,0x0004003d,0x00000007, -0x0000421d,0x0000421c,0x00050051,0x00000006, -0x00004334,0x0000421d,0x00000000,0x00050095, -0x00000130,0x00004336,0x00004334,0x0000421b, -0x00050051,0x00000006,0x00004337,0x00004336, -0x00000001,0x00050051,0x00000006,0x00004338, -0x00004336,0x00000000,0x00050051,0x00000006, -0x0000433b,0x0000421d,0x00000001,0x00050080, -0x00000006,0x0000433d,0x0000433b,0x00004337, -0x00050050,0x00000007,0x0000433e,0x00004338, -0x0000433d,0x0004007c,0x00000014,0x0000432e, -0x0000433e,0x00060041,0x0000015f,0x00004325, -0x0000432e,0x0000015e,0x0000015e,0x0006003d, -0x00000006,0x00004326,0x00004325,0x00000002, -0x00000004,0x0003003e,0x00004203,0x00004326, -0x000200f9,0x00004220,0x000200f8,0x00004220, -0x000700f5,0x00000006,0x000059ee,0x0000012b, -0x00004215,0x0000422f,0x00004224,0x000500b0, -0x0000002f,0x00004223,0x000059ee,0x00000437, -0x000400f6,0x00004230,0x00004224,0x00000000, -0x000400fa,0x00004223,0x00004224,0x00004230, -0x000200f8,0x00004224,0x0004003d,0x00000006, -0x00004229,0x00004211,0x00050084,0x00000006, -0x00004362,0x0000018b,0x00004229,0x00050080, -0x00000006,0x00004363,0x0000431a,0x00004362, -0x00050084,0x00000006,0x0000434c,0x0000019b, -0x000059ee,0x00050080,0x00000006,0x0000434d, -0x00004363,0x0000434c,0x00050095,0x00000130, -0x0000437c,0x00004334,0x0000434d,0x00050051, -0x00000006,0x0000437d,0x0000437c,0x00000001, -0x00050051,0x00000006,0x0000437e,0x0000437c, -0x00000000,0x00050080,0x00000006,0x00004383, -0x0000433b,0x0000437d,0x00050050,0x00000007, -0x00004384,0x0000437e,0x00004383,0x0004007c, -0x00000014,0x00004374,0x00004384,0x00060041, -0x0000015f,0x0000436b,0x00004374,0x0000015e, -0x0000015e,0x0006003d,0x00000006,0x0000436c, -0x0000436b,0x00000002,0x00000004,0x00050080, -0x00000006,0x00004353,0x0000434d,0x000000df, -0x00050095,0x00000130,0x0000439d,0x00004334, -0x00004353,0x00050051,0x00000006,0x0000439e, -0x0000439d,0x00000001,0x00050051,0x00000006, -0x0000439f,0x0000439d,0x00000000,0x00050080, -0x00000006,0x000043a4,0x0000433b,0x0000439e, -0x00050050,0x00000007,0x000043a5,0x0000439f, -0x000043a4,0x0004007c,0x00000014,0x00004395, -0x000043a5,0x00060041,0x0000015f,0x0000438c, -0x00004395,0x0000015e,0x0000015e,0x0006003d, -0x00000006,0x0000438d,0x0000438c,0x00000002, -0x00000004,0x00050080,0x00000006,0x00004358, -0x0000434d,0x00000194,0x00050095,0x00000130, -0x000043be,0x00004334,0x00004358,0x00050051, -0x00000006,0x000043bf,0x000043be,0x00000001, -0x00050051,0x00000006,0x000043c0,0x000043be, -0x00000000,0x00050080,0x00000006,0x000043c5, -0x0000433b,0x000043bf,0x00050050,0x00000007, -0x000043c6,0x000043c0,0x000043c5,0x0004007c, -0x00000014,0x000043b6,0x000043c6,0x00060041, -0x0000015f,0x000043ad,0x000043b6,0x0000015e, -0x0000015e,0x0006003d,0x00000006,0x000043ae, -0x000043ad,0x00000002,0x00000004,0x00060050, -0x000000d2,0x0000435c,0x0000436c,0x0000438d, -0x000043ae,0x00060041,0x000000d8,0x0000422c, -0x000041c9,0x000059d4,0x000059ee,0x0003003e, -0x0000422c,0x0000435c,0x00050080,0x00000006, -0x0000422f,0x000059ee,0x0000022b,0x000200f9, -0x00004220,0x000200f8,0x00004230,0x0004003d, -0x00000006,0x00004233,0x00004211,0x00050084, -0x00000006,0x000043d7,0x000001b6,0x00004233, -0x00050080,0x00000006,0x000043d8,0x00003df7, -0x000043d7,0x00050095,0x00000130,0x00004436, -0x00003e4f,0x000043d8,0x00050051,0x00000006, -0x00004437,0x00004436,0x00000001,0x00050051, -0x00000006,0x00004438,0x00004436,0x00000000, -0x00050080,0x00000006,0x0000443d,0x00003e56, -0x00004437,0x00050050,0x00000007,0x0000443e, -0x00004438,0x0000443d,0x0004007c,0x00000014, -0x0000442e,0x0000443e,0x00060041,0x0000015f, -0x00004425,0x0000442e,0x0000015e,0x0000015e, -0x0006003d,0x00000006,0x00004426,0x00004425, -0x00000002,0x00000004,0x0004007c,0x00000027, -0x000043dd,0x00004426,0x00050080,0x00000006, -0x000043df,0x000043d8,0x000000df,0x00050095, -0x00000130,0x00004457,0x00003e4f,0x000043df, -0x00050051,0x00000006,0x00004458,0x00004457, -0x00000001,0x00050051,0x00000006,0x00004459, -0x00004457,0x00000000,0x00050080,0x00000006, -0x0000445e,0x00003e56,0x00004458,0x00050050, -0x00000007,0x0000445f,0x00004459,0x0000445e, -0x0004007c,0x00000014,0x0000444f,0x0000445f, -0x00060041,0x0000015f,0x00004446,0x0000444f, -0x0000015e,0x0000015e,0x0006003d,0x00000006, -0x00004447,0x00004446,0x00000002,0x00000004, -0x0004007c,0x00000027,0x000043e3,0x00004447, -0x00050080,0x00000006,0x000043e5,0x000043d8, -0x00000194,0x00050095,0x00000130,0x00004478, -0x00003e4f,0x000043e5,0x00050051,0x00000006, -0x00004479,0x00004478,0x00000001,0x00050051, -0x00000006,0x0000447a,0x00004478,0x00000000, -0x00050080,0x00000006,0x0000447f,0x00003e56, -0x00004479,0x00050050,0x00000007,0x00004480, -0x0000447a,0x0000447f,0x0004007c,0x00000014, -0x00004470,0x00004480,0x00060041,0x0000015f, -0x00004467,0x00004470,0x0000015e,0x0000015e, -0x0006003d,0x00000006,0x00004468,0x00004467, -0x00000002,0x00000004,0x0004007c,0x00000027, -0x000043e9,0x00004468,0x00050080,0x00000006, -0x000043ec,0x000043d8,0x0000019b,0x00050095, -0x00000130,0x00004499,0x00003e4f,0x000043ec, -0x00050051,0x00000006,0x0000449a,0x00004499, -0x00000001,0x00050051,0x00000006,0x0000449b, -0x00004499,0x00000000,0x00050080,0x00000006, -0x000044a0,0x00003e56,0x0000449a,0x00050050, -0x00000007,0x000044a1,0x0000449b,0x000044a0, -0x0004007c,0x00000014,0x00004491,0x000044a1, -0x00060041,0x0000015f,0x00004488,0x00004491, -0x0000015e,0x0000015e,0x0006003d,0x00000006, -0x00004489,0x00004488,0x00000002,0x00000004, -0x0004007c,0x00000027,0x000043f0,0x00004489, -0x00050080,0x00000006,0x000043f2,0x000043d8, -0x000001a2,0x00050095,0x00000130,0x000044ba, -0x00003e4f,0x000043f2,0x00050051,0x00000006, -0x000044bb,0x000044ba,0x00000001,0x00050051, -0x00000006,0x000044bc,0x000044ba,0x00000000, -0x00050080,0x00000006,0x000044c1,0x00003e56, -0x000044bb,0x00050050,0x00000007,0x000044c2, -0x000044bc,0x000044c1,0x0004007c,0x00000014, -0x000044b2,0x000044c2,0x00060041,0x0000015f, -0x000044a9,0x000044b2,0x0000015e,0x0000015e, -0x0006003d,0x00000006,0x000044aa,0x000044a9, -0x00000002,0x00000004,0x0004007c,0x00000027, -0x000043f6,0x000044aa,0x00050080,0x00000006, -0x000043f8,0x000043d8,0x00000260,0x00050095, -0x00000130,0x000044db,0x00003e4f,0x000043f8, -0x00050051,0x00000006,0x000044dc,0x000044db, -0x00000001,0x00050051,0x00000006,0x000044dd, -0x000044db,0x00000000,0x00050080,0x00000006, -0x000044e2,0x00003e56,0x000044dc,0x00050050, -0x00000007,0x000044e3,0x000044dd,0x000044e2, -0x0004007c,0x00000014,0x000044d3,0x000044e3, -0x00060041,0x0000015f,0x000044ca,0x000044d3, -0x0000015e,0x0000015e,0x0006003d,0x00000006, -0x000044cb,0x000044ca,0x00000002,0x00000004, -0x0004007c,0x00000027,0x000043fc,0x000044cb, -0x000500bc,0x0000002f,0x000044ea,0x000043dd, -0x000043f0,0x000300f7,0x000044f1,0x00000000, -0x000400fa,0x000044ea,0x000044eb,0x000044f1, -0x000200f8,0x000044eb,0x000500bc,0x0000002f, -0x000044f0,0x000043e3,0x000043f6,0x000200f9, -0x000044f1,0x000200f8,0x000044f1,0x000700f5, -0x0000002f,0x000044f2,0x000044ea,0x00004230, -0x000044f0,0x000044eb,0x000300f7,0x000044f9, -0x00000000,0x000400fa,0x000044f2,0x000044f3, -0x000044f9,0x000200f8,0x000044f3,0x000500bc, -0x0000002f,0x000044f8,0x000043e9,0x000043fc, -0x000200f9,0x000044f9,0x000200f8,0x000044f9, -0x000700f5,0x0000002f,0x000044fa,0x000044f2, -0x000044f1,0x000044f8,0x000044f3,0x0003003e, -0x000041ff,0x000044fa,0x000200f9,0x0000423d, -0x000200f8,0x0000423d,0x00050080,0x00000006, -0x0000423f,0x000059d4,0x0000022b,0x000200f9, -0x000041f9,0x000200f8,0x00004240,0x000200f9, -0x00004241,0x000200f8,0x00004241,0x000700f5, -0x00000006,0x000059d5,0x0000012b,0x00004240, -0x00004315,0x00004313,0x000500b0,0x0000002f, -0x00004244,0x000059d5,0x000000df,0x000400f6, -0x00004316,0x00004313,0x00000000,0x000400fa, -0x00004244,0x00004245,0x00004316,0x000200f8, -0x00004245,0x00050041,0x0000008d,0x00004247, -0x000041c6,0x000059d5,0x0004003d,0x0000002f, -0x00004248,0x00004247,0x000400a8,0x0000002f, -0x00004249,0x00004248,0x000300f7,0x0000424f, -0x00000000,0x000400fa,0x00004249,0x0000424a, -0x0000424f,0x000200f8,0x0000424a,0x00050041, -0x0000008d,0x0000424c,0x000041c5,0x000059d5, -0x0004003d,0x0000002f,0x0000424d,0x0000424c, -0x000400a8,0x0000002f,0x0000424e,0x0000424d, -0x000200f9,0x0000424f,0x000200f8,0x0000424f, -0x000700f5,0x0000002f,0x00004250,0x00004248, -0x00004245,0x0000424e,0x0000424a,0x000300f7, -0x00004252,0x00000000,0x000400fa,0x00004250, -0x00004251,0x00004252,0x000200f8,0x00004251, -0x000200f9,0x00004313,0x000200f8,0x00004252, -0x0003003e,0x00004247,0x000003ae,0x00050080, -0x00000006,0x00004256,0x000059d5,0x00000135, -0x000200f9,0x00004257,0x000200f8,0x00004257, -0x000700f5,0x00000006,0x000059d7,0x00004256, -0x00004252,0x00004311,0x0000430f,0x000500b0, -0x0000002f,0x0000425a,0x000059d7,0x000000df, -0x000400f6,0x00004312,0x0000430f,0x00000000, -0x000400fa,0x0000425a,0x0000425b,0x00004312, -0x000200f8,0x0000425b,0x00050041,0x0000008d, -0x0000425d,0x000041c6,0x000059d7,0x0004003d, -0x0000002f,0x0000425e,0x0000425d,0x000400a8, -0x0000002f,0x0000425f,0x0000425e,0x000300f7, -0x00004265,0x00000000,0x000400fa,0x0000425f, -0x00004260,0x00004265,0x000200f8,0x00004260, -0x00050041,0x0000008d,0x00004262,0x000041c5, -0x000059d7,0x0004003d,0x0000002f,0x00004263, -0x00004262,0x000400a8,0x0000002f,0x00004264, -0x00004263,0x000200f9,0x00004265,0x000200f8, -0x00004265,0x000700f5,0x0000002f,0x00004266, -0x0000425e,0x0000425b,0x00004264,0x00004260, -0x000400a8,0x0000002f,0x00004267,0x00004266, -0x000300f7,0x00004270,0x00000000,0x000400fa, -0x00004267,0x00004268,0x00004270,0x000200f8, -0x00004268,0x00050041,0x00000009,0x0000426a, -0x000041c7,0x000059d7,0x0004003d,0x00000006, -0x0000426b,0x0000426a,0x00050041,0x00000009, -0x0000426d,0x000041c7,0x000059d5,0x0004003d, -0x00000006,0x0000426e,0x0000426d,0x000500ab, -0x0000002f,0x0000426f,0x0000426b,0x0000426e, -0x000200f9,0x00004270,0x000200f8,0x00004270, -0x000700f5,0x0000002f,0x00004271,0x00004266, -0x00004265,0x0000426f,0x00004268,0x000300f7, -0x00004273,0x00000000,0x000400fa,0x00004271, -0x00004272,0x00004273,0x000200f8,0x00004272, -0x000200f9,0x0000430f,0x000200f8,0x00004273, -0x000200f9,0x00004274,0x000200f8,0x00004274, -0x000700f5,0x00000006,0x000059e1,0x00000437, -0x00004273,0x00005c6e,0x000042ac,0x000700f5, -0x00000006,0x000059dc,0x00000437,0x00004273, -0x00005c63,0x000042ac,0x000700f5,0x00000006, -0x000059db,0x0000012b,0x00004273,0x000042ae, -0x000042ac,0x000500b0,0x0000002f,0x00004277, -0x000059db,0x00000437,0x000500aa,0x0000002f, -0x00004279,0x000059dc,0x00000437,0x000500a7, -0x0000002f,0x0000427a,0x00004277,0x00004279, -0x000400f6,0x000042af,0x000042ac,0x00000000, -0x000400fa,0x0000427a,0x0000427b,0x000042af, -0x000200f8,0x0000427b,0x00060041,0x000000d8, -0x0000427e,0x000041c9,0x000059d5,0x000059db, -0x0004003d,0x000000d2,0x0000427f,0x0000427e, -0x00050080,0x00000006,0x00004282,0x000059db, -0x00000135,0x00050089,0x00000006,0x00004283, -0x00004282,0x00000437,0x00060041,0x000000d8, -0x00004284,0x000041c9,0x000059d5,0x00004283, -0x0004003d,0x000000d2,0x00004285,0x00004284, -0x000500aa,0x00000514,0x00004288,0x0000427f, -0x00004285,0x0004009b,0x0000002f,0x00004289, -0x00004288,0x000300f7,0x0000428b,0x00000000, -0x000400fa,0x00004289,0x0000428a,0x0000428b, -0x000200f8,0x0000428a,0x000200f9,0x000042ac, -0x000200f8,0x0000428b,0x000200f9,0x0000428c, -0x000200f8,0x0000428c,0x000700f5,0x00000006, -0x000059e2,0x0000012b,0x0000428b,0x000042aa, -0x000042a8,0x000500b0,0x0000002f,0x0000428f, -0x000059e2,0x00000437,0x000400f6,0x000042ab, -0x000042a8,0x00000000,0x000400fa,0x0000428f, -0x00004290,0x000042ab,0x000200f8,0x00004290, -0x00060041,0x000000d8,0x00004293,0x000041c9, -0x000059d7,0x000059e2,0x0004003d,0x000000d2, -0x00004294,0x00004293,0x000500aa,0x00000514, -0x00004296,0x00004294,0x00004285,0x0004009b, -0x0000002f,0x00004297,0x00004296,0x000300f7, -0x000042a2,0x00000000,0x000400fa,0x00004297, -0x00004298,0x000042a2,0x000200f8,0x00004298, -0x00050080,0x00000006,0x0000429b,0x000059e2, -0x00000135,0x00050089,0x00000006,0x0000429c, -0x0000429b,0x00000437,0x00060041,0x000000d8, -0x0000429d,0x000041c9,0x000059d7,0x0000429c, -0x0004003d,0x000000d2,0x0000429e,0x0000429d, -0x000500aa,0x00000514,0x000042a0,0x0000429e, -0x0000427f,0x0004009b,0x0000002f,0x000042a1, -0x000042a0,0x000200f9,0x000042a2,0x000200f8, -0x000042a2,0x000700f5,0x0000002f,0x000042a3, -0x00004297,0x00004290,0x000042a1,0x00004298, -0x000300f7,0x000042a7,0x00000000,0x000400fa, -0x000042a3,0x000042a4,0x000042a7,0x000200f8, -0x000042a4,0x000200f9,0x000042ab,0x000200f8, -0x000042a7,0x000200f9,0x000042a8,0x000200f8, -0x000042a8,0x00050080,0x00000006,0x000042aa, -0x000059e2,0x0000022b,0x000200f9,0x0000428c, -0x000200f8,0x000042ab,0x000700f5,0x00000006, -0x00005c6f,0x000059e1,0x0000428c,0x000059e2, -0x000042a4,0x000700f5,0x00000006,0x00005c64, -0x000059dc,0x0000428c,0x000059db,0x000042a4, -0x000200f9,0x000042ac,0x000200f8,0x000042ac, -0x000700f5,0x00000006,0x00005c6e,0x000059e1, -0x0000428a,0x00005c6f,0x000042ab,0x000700f5, -0x00000006,0x00005c63,0x000059dc,0x0000428a, -0x00005c64,0x000042ab,0x00050080,0x00000006, -0x000042ae,0x000059db,0x0000022b,0x000200f9, -0x00004274,0x000200f8,0x000042af,0x000300f7, -0x000042b3,0x00000000,0x000400fa,0x00004279, -0x000042b2,0x000042b3,0x000200f8,0x000042b2, -0x000200f9,0x0000430f,0x000200f8,0x000042b3, -0x0003003e,0x0000425d,0x000003ae,0x00050080, -0x00000006,0x000042b9,0x000059dc,0x00000247, -0x00050089,0x00000006,0x000042ba,0x000042b9, -0x00000437,0x00050041,0x00000009,0x000042bb, -0x00003c82,0x000059d5,0x0004003d,0x00000006, -0x000042bc,0x000042bb,0x00060041,0x000000d8, -0x000042bd,0x000041c9,0x000059d5,0x000042ba, -0x0004003d,0x000000d2,0x000042be,0x000042bd, -0x00050041,0x00000182,0x00004523,0x00000180, -0x00000311,0x0004003d,0x00000006,0x00004524, -0x00004523,0x00050084,0x00000006,0x00004526, -0x0000018b,0x000042bc,0x00050080,0x00000006, -0x00004527,0x00004524,0x00004526,0x00050041, -0x0000022d,0x0000450d,0x00000180,0x0000015e, -0x0004003d,0x00000007,0x0000450e,0x0000450d, -0x00050051,0x00000006,0x00004511,0x000042be, -0x00000000,0x00050051,0x00000006,0x0000453d, -0x0000450e,0x00000000,0x00050095,0x00000130, -0x0000453f,0x0000453d,0x00004527,0x00050051, -0x00000006,0x00004540,0x0000453f,0x00000001, -0x00050051,0x00000006,0x00004541,0x0000453f, -0x00000000,0x00050051,0x00000006,0x00004544, -0x0000450e,0x00000001,0x00050080,0x00000006, -0x00004546,0x00004544,0x00004540,0x00050050, -0x00000007,0x00004547,0x00004541,0x00004546, -0x0004007c,0x00000014,0x00004537,0x00004547, -0x00060041,0x0000015f,0x0000452f,0x00004537, -0x0000015e,0x0000015e,0x0005003e,0x0000452f, -0x00004511,0x00000002,0x00000004,0x00050080, -0x00000006,0x00004514,0x00004527,0x000000df, -0x00050051,0x00000006,0x00004518,0x000042be, -0x00000001,0x00050095,0x00000130,0x0000455f, -0x0000453d,0x00004514,0x00050051,0x00000006, -0x00004560,0x0000455f,0x00000001,0x00050051, -0x00000006,0x00004561,0x0000455f,0x00000000, -0x00050080,0x00000006,0x00004566,0x00004544, -0x00004560,0x00050050,0x00000007,0x00004567, -0x00004561,0x00004566,0x0004007c,0x00000014, -0x00004557,0x00004567,0x00060041,0x0000015f, -0x0000454f,0x00004557,0x0000015e,0x0000015e, -0x0005003e,0x0000454f,0x00004518,0x00000002, -0x00000004,0x00050080,0x00000006,0x0000451b, -0x00004527,0x00000194,0x00050051,0x00000006, -0x0000451f,0x000042be,0x00000002,0x00050095, -0x00000130,0x0000457f,0x0000453d,0x0000451b, -0x00050051,0x00000006,0x00004580,0x0000457f, -0x00000001,0x00050051,0x00000006,0x00004581, -0x0000457f,0x00000000,0x00050080,0x00000006, -0x00004586,0x00004544,0x00004580,0x00050050, -0x00000007,0x00004587,0x00004581,0x00004586, -0x0004007c,0x00000014,0x00004577,0x00004587, -0x00060041,0x0000015f,0x0000456f,0x00004577, -0x0000015e,0x0000015e,0x0005003e,0x0000456f, -0x0000451f,0x00000002,0x00000004,0x0004003d, -0x00000006,0x000042c4,0x000042bb,0x00060041, -0x000000d8,0x000042c5,0x000041c9,0x000059d5, -0x000059dc,0x0004003d,0x000000d2,0x000042c6, -0x000042c5,0x00050084,0x00000006,0x000045b2, -0x0000018b,0x000042c4,0x00050080,0x00000006, -0x000045b3,0x00004524,0x000045b2,0x00050080, -0x00000006,0x00004598,0x000045b3,0x0000019b, -0x00050051,0x00000006,0x0000459d,0x000042c6, -0x00000000,0x00050095,0x00000130,0x000045cb, -0x0000453d,0x00004598,0x00050051,0x00000006, -0x000045cc,0x000045cb,0x00000001,0x00050051, -0x00000006,0x000045cd,0x000045cb,0x00000000, -0x00050080,0x00000006,0x000045d2,0x00004544, -0x000045cc,0x00050050,0x00000007,0x000045d3, -0x000045cd,0x000045d2,0x0004007c,0x00000014, -0x000045c3,0x000045d3,0x00060041,0x0000015f, -0x000045bb,0x000045c3,0x0000015e,0x0000015e, -0x0005003e,0x000045bb,0x0000459d,0x00000002, -0x00000004,0x00050080,0x00000006,0x000045a0, -0x000045b3,0x000001a2,0x00050051,0x00000006, -0x000045a4,0x000042c6,0x00000001,0x00050095, -0x00000130,0x000045eb,0x0000453d,0x000045a0, -0x00050051,0x00000006,0x000045ec,0x000045eb, -0x00000001,0x00050051,0x00000006,0x000045ed, -0x000045eb,0x00000000,0x00050080,0x00000006, -0x000045f2,0x00004544,0x000045ec,0x00050050, -0x00000007,0x000045f3,0x000045ed,0x000045f2, -0x0004007c,0x00000014,0x000045e3,0x000045f3, -0x00060041,0x0000015f,0x000045db,0x000045e3, -0x0000015e,0x0000015e,0x0005003e,0x000045db, -0x000045a4,0x00000002,0x00000004,0x00050080, -0x00000006,0x000045a7,0x000045b3,0x00000260, -0x00050051,0x00000006,0x000045ab,0x000042c6, -0x00000002,0x00050095,0x00000130,0x0000460b, -0x0000453d,0x000045a7,0x00050051,0x00000006, -0x0000460c,0x0000460b,0x00000001,0x00050051, -0x00000006,0x0000460d,0x0000460b,0x00000000, -0x00050080,0x00000006,0x00004612,0x00004544, -0x0000460c,0x00050050,0x00000007,0x00004613, -0x0000460d,0x00004612,0x0004007c,0x00000014, -0x00004603,0x00004613,0x00060041,0x0000015f, -0x000045fb,0x00004603,0x0000015e,0x0000015e, -0x0005003e,0x000045fb,0x000045ab,0x00000002, -0x00000004,0x00050080,0x00000006,0x000042cb, -0x000059dc,0x00000135,0x00050089,0x00000006, -0x000042cc,0x000042cb,0x00000437,0x0004003d, -0x00000006,0x000042ce,0x000042bb,0x00060041, -0x000000d8,0x000042cf,0x000041c9,0x000059d5, -0x000042cc,0x0004003d,0x000000d2,0x000042d0, -0x000042cf,0x00050084,0x00000006,0x0000463e, -0x0000018b,0x000042ce,0x00050080,0x00000006, -0x0000463f,0x00004524,0x0000463e,0x00050080, -0x00000006,0x00004624,0x0000463f,0x000001b6, -0x00050051,0x00000006,0x00004629,0x000042d0, -0x00000000,0x00050095,0x00000130,0x00004657, -0x0000453d,0x00004624,0x00050051,0x00000006, -0x00004658,0x00004657,0x00000001,0x00050051, -0x00000006,0x00004659,0x00004657,0x00000000, -0x00050080,0x00000006,0x0000465e,0x00004544, -0x00004658,0x00050050,0x00000007,0x0000465f, -0x00004659,0x0000465e,0x0004007c,0x00000014, -0x0000464f,0x0000465f,0x00060041,0x0000015f, -0x00004647,0x0000464f,0x0000015e,0x0000015e, -0x0005003e,0x00004647,0x00004629,0x00000002, -0x00000004,0x00050080,0x00000006,0x0000462c, -0x0000463f,0x000005df,0x00050051,0x00000006, -0x00004630,0x000042d0,0x00000001,0x00050095, -0x00000130,0x00004677,0x0000453d,0x0000462c, -0x00050051,0x00000006,0x00004678,0x00004677, -0x00000001,0x00050051,0x00000006,0x00004679, -0x00004677,0x00000000,0x00050080,0x00000006, -0x0000467e,0x00004544,0x00004678,0x00050050, -0x00000007,0x0000467f,0x00004679,0x0000467e, -0x0004007c,0x00000014,0x0000466f,0x0000467f, -0x00060041,0x0000015f,0x00004667,0x0000466f, -0x0000015e,0x0000015e,0x0005003e,0x00004667, -0x00004630,0x00000002,0x00000004,0x00050080, -0x00000006,0x00004633,0x0000463f,0x000001cc, -0x00050051,0x00000006,0x00004637,0x000042d0, -0x00000002,0x00050095,0x00000130,0x00004697, -0x0000453d,0x00004633,0x00050051,0x00000006, -0x00004698,0x00004697,0x00000001,0x00050051, -0x00000006,0x00004699,0x00004697,0x00000000, -0x00050080,0x00000006,0x0000469e,0x00004544, -0x00004698,0x00050050,0x00000007,0x0000469f, -0x00004699,0x0000469e,0x0004007c,0x00000014, -0x0000468f,0x0000469f,0x00060041,0x0000015f, -0x00004687,0x0000468f,0x0000015e,0x0000015e, -0x0005003e,0x00004687,0x00004637,0x00000002, -0x00000004,0x00050080,0x00000006,0x000042d5, -0x000059e1,0x00000247,0x00050089,0x00000006, -0x000042d6,0x000042d5,0x00000437,0x0004003d, -0x00000006,0x000042d8,0x000042bb,0x00060041, -0x000000d8,0x000042d9,0x000041c9,0x000059d7, -0x000042d6,0x0004003d,0x000000d2,0x000042da, -0x000042d9,0x00050084,0x00000006,0x000046ca, -0x0000018b,0x000042d8,0x00050080,0x00000006, -0x000046cb,0x00004524,0x000046ca,0x00050080, -0x00000006,0x000046b0,0x000046cb,0x000004c7, -0x00050051,0x00000006,0x000046b5,0x000042da, -0x00000000,0x00050095,0x00000130,0x000046e3, -0x0000453d,0x000046b0,0x00050051,0x00000006, -0x000046e4,0x000046e3,0x00000001,0x00050051, -0x00000006,0x000046e5,0x000046e3,0x00000000, -0x00050080,0x00000006,0x000046ea,0x00004544, -0x000046e4,0x00050050,0x00000007,0x000046eb, -0x000046e5,0x000046ea,0x0004007c,0x00000014, -0x000046db,0x000046eb,0x00060041,0x0000015f, -0x000046d3,0x000046db,0x0000015e,0x0000015e, -0x0005003e,0x000046d3,0x000046b5,0x00000002, -0x00000004,0x00050080,0x00000006,0x000046b8, -0x000046cb,0x000004d2,0x00050051,0x00000006, -0x000046bc,0x000042da,0x00000001,0x00050095, -0x00000130,0x00004703,0x0000453d,0x000046b8, -0x00050051,0x00000006,0x00004704,0x00004703, -0x00000001,0x00050051,0x00000006,0x00004705, -0x00004703,0x00000000,0x00050080,0x00000006, -0x0000470a,0x00004544,0x00004704,0x00050050, -0x00000007,0x0000470b,0x00004705,0x0000470a, -0x0004007c,0x00000014,0x000046fb,0x0000470b, -0x00060041,0x0000015f,0x000046f3,0x000046fb, -0x0000015e,0x0000015e,0x0005003e,0x000046f3, -0x000046bc,0x00000002,0x00000004,0x00050080, -0x00000006,0x000046bf,0x000046cb,0x000004dd, -0x00050051,0x00000006,0x000046c3,0x000042da, -0x00000002,0x00050095,0x00000130,0x00004723, -0x0000453d,0x000046bf,0x00050051,0x00000006, -0x00004724,0x00004723,0x00000001,0x00050051, -0x00000006,0x00004725,0x00004723,0x00000000, -0x00050080,0x00000006,0x0000472a,0x00004544, -0x00004724,0x00050050,0x00000007,0x0000472b, -0x00004725,0x0000472a,0x0004007c,0x00000014, -0x0000471b,0x0000472b,0x00060041,0x0000015f, -0x00004713,0x0000471b,0x0000015e,0x0000015e, -0x0005003e,0x00004713,0x000046c3,0x00000002, -0x00000004,0x0004003d,0x00000006,0x000042de, -0x000042bb,0x00050084,0x00000006,0x00004731, -0x0000018b,0x000042de,0x00050080,0x00000006, -0x00004732,0x00004524,0x00004731,0x00050080, -0x00000006,0x000042e0,0x00004732,0x000004fe, -0x00050041,0x00000009,0x000042e2,0x00003c82, -0x000059d7,0x0004003d,0x00000006,0x000042e3, -0x000042e2,0x00050084,0x00000006,0x00004738, -0x0000018b,0x000042e3,0x00050080,0x00000006, -0x00004739,0x00004524,0x00004738,0x00050080, -0x00000006,0x000042e5,0x00004739,0x000004f4, -0x00050095,0x00000130,0x00004752,0x0000453d, -0x000042e5,0x00050051,0x00000006,0x00004753, -0x00004752,0x00000001,0x00050051,0x00000006, -0x00004754,0x00004752,0x00000000,0x00050080, -0x00000006,0x00004759,0x00004544,0x00004753, -0x00050050,0x00000007,0x0000475a,0x00004754, -0x00004759,0x0004007c,0x00000014,0x0000474a, -0x0000475a,0x00060041,0x0000015f,0x00004741, -0x0000474a,0x0000015e,0x0000015e,0x0006003d, -0x00000006,0x00004742,0x00004741,0x00000002, -0x00000004,0x00050095,0x00000130,0x00004772, -0x0000453d,0x000042e0,0x00050051,0x00000006, -0x00004773,0x00004772,0x00000001,0x00050051, -0x00000006,0x00004774,0x00004772,0x00000000, -0x00050080,0x00000006,0x00004779,0x00004544, -0x00004773,0x00050050,0x00000007,0x0000477a, -0x00004774,0x00004779,0x0004007c,0x00000014, -0x0000476a,0x0000477a,0x00060041,0x0000015f, -0x00004762,0x0000476a,0x0000015e,0x0000015e, -0x0005003e,0x00004762,0x00004742,0x00000002, -0x00000004,0x00050082,0x00000006,0x000042ed, -0x0000032b,0x000059dc,0x00050089,0x00000006, -0x000042ee,0x000042ed,0x00000437,0x00050082, -0x00000006,0x000042f0,0x0000031c,0x000059dc, -0x00050089,0x00000006,0x000042f1,0x000042f0, -0x00000437,0x000500c4,0x00000006,0x000042f2, -0x000042f1,0x000002dc,0x000500c5,0x00000006, -0x000042f3,0x000042ee,0x000042f2,0x00050082, -0x00000006,0x000042f5,0x0000031c,0x000059e1, -0x00050089,0x00000006,0x000042f6,0x000042f5, -0x00000437,0x00050082,0x00000006,0x000042f8, -0x00000c2c,0x000059e1,0x00050089,0x00000006, -0x000042f9,0x000042f8,0x00000437,0x000500c4, -0x00000006,0x000042fa,0x000042f9,0x000002dc, -0x000500c5,0x00000006,0x000042fb,0x000042f6, -0x000042fa,0x0004003d,0x00000006,0x000042fe, -0x000042bb,0x00050084,0x00000006,0x00004780, -0x0000018b,0x000042fe,0x00050080,0x00000006, -0x00004781,0x00004524,0x00004780,0x00050080, -0x00000006,0x00004300,0x00004781,0x00000508, -0x000500c4,0x00000006,0x00004303,0x000042fb, -0x00000488,0x000500c5,0x00000006,0x00004304, -0x000042f3,0x00004303,0x00050095,0x00000130, -0x00004799,0x0000453d,0x00004300,0x00050051, -0x00000006,0x0000479a,0x00004799,0x00000001, -0x00050051,0x00000006,0x0000479b,0x00004799, -0x00000000,0x00050080,0x00000006,0x000047a0, -0x00004544,0x0000479a,0x00050050,0x00000007, -0x000047a1,0x0000479b,0x000047a0,0x0004007c, -0x00000014,0x00004791,0x000047a1,0x00060041, -0x0000015f,0x00004789,0x00004791,0x0000015e, -0x0000015e,0x0005003e,0x00004789,0x00004304, -0x00000002,0x00000004,0x00050041,0x00000009, -0x0000430a,0x00003c83,0x000059d5,0x0004003d, -0x00000006,0x0000430b,0x0000430a,0x000500c7, -0x00000006,0x0000430c,0x0000430b,0x00000c46, -0x000500c5,0x00000006,0x0000430d,0x0000430c, -0x00000135,0x00050041,0x00000009,0x0000430e, -0x00003c83,0x000059d7,0x0003003e,0x0000430e, -0x0000430d,0x000200f9,0x00004312,0x000200f8, -0x0000430f,0x00050080,0x00000006,0x00004311, -0x000059d7,0x0000022b,0x000200f9,0x00004257, -0x000200f8,0x00004312,0x000200f9,0x00004313, -0x000200f8,0x00004313,0x00050080,0x00000006, -0x00004315,0x000059d5,0x0000022b,0x000200f9, -0x00004241,0x000200f8,0x00004316,0x0004003d, -0x000000e0,0x00003d20,0x00003c83,0x0003003e, -0x00003c67,0x00003d20,0x000200f9,0x00003d21, -0x000200f8,0x00003d21,0x000200f9,0x00003d22, -0x000200f8,0x00003ca3,0x000500aa,0x0000002f, -0x00003ca6,0x00003ca1,0x00000135,0x000300f7, -0x00003cb1,0x00000000,0x000400fa,0x00003ca6, -0x00003ca7,0x00003cb1,0x000200f8,0x00003ca7, -0x00050041,0x00000182,0x00003d90,0x00000180, -0x00000181,0x0004003d,0x00000006,0x00003d91, -0x00003d90,0x00050084,0x00000006,0x00003d92, -0x000000df,0x00003d91,0x00050080,0x00000006, -0x00003d93,0x0000018b,0x00003d92,0x00050041, -0x0000022d,0x00003ca9,0x00000180,0x0000022b, -0x0004003d,0x00000007,0x00003caa,0x00003ca9, -0x00050051,0x00000006,0x00003daa,0x00003caa, -0x00000000,0x00050095,0x00000130,0x00003dac, -0x00003daa,0x00003d93,0x00050051,0x00000006, -0x00003dad,0x00003dac,0x00000001,0x00050051, -0x00000006,0x00003dae,0x00003dac,0x00000000, -0x00050051,0x00000006,0x00003db1,0x00003caa, -0x00000001,0x00050080,0x00000006,0x00003db3, -0x00003db1,0x00003dad,0x00050050,0x00000007, -0x00003db4,0x00003dae,0x00003db3,0x0004007c, -0x00000014,0x00003da4,0x00003db4,0x00060041, -0x0000015f,0x00003d9b,0x00003da4,0x0000015e, -0x0000015e,0x0006003d,0x00000006,0x00003d9c, -0x00003d9b,0x00000002,0x00000004,0x00050041, -0x00000009,0x00003cac,0x00003c68,0x0000015e, -0x0003003e,0x00003cac,0x00003d9c,0x0004003d, -0x00000006,0x00003cae,0x00003cac,0x00050041, -0x00000182,0x00003db7,0x00000180,0x00000311, -0x0004003d,0x00000006,0x00003db8,0x00003db7, -0x00050041,0x00000182,0x00003dc8,0x00000180, -0x000002fb,0x0004003d,0x00000006,0x00003dc9, -0x00003dc8,0x000500c7,0x00000006,0x00003dca, -0x00003dc9,0x00000135,0x000500ab,0x0000002f, -0x00003dcb,0x00003dca,0x0000012b,0x000600a9, -0x00000006,0x00003dc5,0x00003dcb,0x00000309, -0x0000018b,0x00050084,0x00000006,0x00003dbb, -0x00003cae,0x00003dc5,0x00050080,0x00000006, -0x00003dbc,0x00003db8,0x00003dbb,0x000500c2, -0x00000006,0x00003dbd,0x00003dbc,0x00000318, -0x000500c4,0x00000006,0x00003dbe,0x00003dbd, -0x000002e4,0x000600a9,0x00000006,0x00003dc0, -0x00003dcb,0x0000031c,0x0000012b,0x000500c5, -0x00000006,0x00003dc1,0x00003dbe,0x00003dc0, -0x00050041,0x00000009,0x00003cb0,0x00003c67, -0x0000015e,0x0003003e,0x00003cb0,0x00003dc1, -0x000200f9,0x00003cb1,0x000200f8,0x00003cb1, -0x000200f9,0x00003d22,0x000200f8,0x00003d22, -0x000700f5,0x00000006,0x00005a10,0x0000012b, -0x00003cb1,0x00003edc,0x00003d21,0x000200f9, -0x00003d23,0x000200f8,0x00003d23,0x000700f5, -0x00000006,0x00005a0e,0x0000012b,0x00003d22, -0x00003d3c,0x00003d3a,0x000500b0,0x0000002f, -0x00003d26,0x00005a0e,0x000000df,0x000400f6, -0x00003d3d,0x00003d3a,0x00000000,0x000400fa, -0x00003d26,0x00003d27,0x00003d3d,0x000200f8, -0x00003d27,0x00050041,0x00000009,0x00003d29, -0x00003c68,0x00005a0e,0x0004003d,0x00000006, -0x00003d2a,0x00003d29,0x000500ab,0x0000002f, -0x00003d2b,0x00003d2a,0x00000500,0x000300f7, -0x00003d39,0x00000000,0x000400fa,0x00003d2b, -0x00003d2c,0x00003d39,0x000200f8,0x00003d2c, -0x00050041,0x00000182,0x000047e8,0x00000180, -0x00000181,0x0004003d,0x00000006,0x000047e9, -0x000047e8,0x00050084,0x00000006,0x000047ea, -0x000001a2,0x000047e9,0x00050080,0x00000006, -0x000047eb,0x0000018b,0x000047ea,0x00050080, -0x00000006,0x000047f1,0x000047e9,0x00005cc3, -0x00050086,0x00000006,0x000047f2,0x000047f1, -0x00000185,0x00050084,0x00000006,0x000047e4, -0x0000018b,0x000047f2,0x00050080,0x00000006, -0x000047e5,0x000047eb,0x000047e4,0x00050080, -0x00000006,0x000047df,0x000047e5,0x000047e4, -0x00050084,0x00000006,0x000047d8,0x000001b6, -0x00003ca1,0x00050080,0x00000006,0x000047d9, -0x000047df,0x000047d8,0x00050041,0x00000182, -0x000047cf,0x00000180,0x000001cd,0x0004003d, -0x00000006,0x000047d0,0x000047cf,0x00050084, -0x00000006,0x000047d1,0x000001cc,0x000047d0, -0x00050080,0x00000006,0x000047d2,0x000047d9, -0x000047d1,0x000500ac,0x0000002f,0x000047ff, -0x00003ca1,0x00000135,0x000300f7,0x00004805, -0x00000000,0x000400fa,0x000047ff,0x00004800, -0x00004804,0x000200f8,0x00004804,0x000200f9, -0x00004805,0x000200f8,0x00004800,0x00050082, -0x00000006,0x00004803,0x00003ca1,0x00000135, -0x000200f9,0x00004805,0x000200f8,0x00004805, -0x000700f5,0x00000006,0x00005a6a,0x00004803, -0x00004800,0x0000012b,0x00004804,0x00050084, -0x00000006,0x000047ca,0x000000df,0x00005a6a, -0x00050080,0x00000006,0x000047cb,0x000047d2, -0x000047ca,0x000300f7,0x00004812,0x00000000, -0x000400fa,0x000047ff,0x0000480d,0x00004811, -0x000200f8,0x00004811,0x000200f9,0x00004812, -0x000200f8,0x0000480d,0x00050082,0x00000006, -0x00004810,0x00003ca1,0x00000135,0x000200f9, -0x00004812,0x000200f8,0x00004812,0x000700f5, -0x00000006,0x00005a6b,0x00004810,0x0000480d, -0x0000012b,0x00004811,0x00050084,0x00000006, -0x000047c4,0x000000df,0x00005a6b,0x00050080, -0x00000006,0x000047c5,0x000047cb,0x000047c4, -0x000300f7,0x0000481f,0x00000000,0x000400fa, -0x000047ff,0x0000481a,0x0000481e,0x000200f8, -0x0000481e,0x000200f9,0x0000481f,0x000200f8, -0x0000481a,0x00050082,0x00000006,0x0000481d, -0x00003ca1,0x00000135,0x000200f9,0x0000481f, -0x000200f8,0x0000481f,0x000700f5,0x00000006, -0x00005a6c,0x0000481d,0x0000481a,0x0000012b, -0x0000481e,0x00050084,0x00000006,0x000047be, -0x000000df,0x00005a6c,0x00050080,0x00000006, -0x000047bf,0x000047c5,0x000047be,0x000300f7, -0x0000482c,0x00000000,0x000400fa,0x000047ff, -0x00004827,0x0000482b,0x000200f8,0x0000482b, -0x000200f9,0x0000482c,0x000200f8,0x00004827, -0x00050082,0x00000006,0x0000482a,0x00003ca1, -0x00000135,0x000200f9,0x0000482c,0x000200f8, -0x0000482c,0x000700f5,0x00000006,0x00005a6d, -0x0000482a,0x00004827,0x0000012b,0x0000482b, -0x00050084,0x00000006,0x000047b8,0x000000df, -0x00005a6d,0x00050080,0x00000006,0x000047b9, -0x000047bf,0x000047b8,0x000300f7,0x00004839, -0x00000000,0x000400fa,0x000047ff,0x00004834, -0x00004838,0x000200f8,0x00004838,0x000200f9, -0x00004839,0x000200f8,0x00004834,0x00050082, -0x00000006,0x00004837,0x00003ca1,0x00000135, -0x000200f9,0x00004839,0x000200f8,0x00004839, -0x000700f5,0x00000006,0x00005a6e,0x00004837, -0x00004834,0x0000012b,0x00004838,0x00050084, -0x00000006,0x000047b2,0x000000df,0x00005a6e, -0x00050080,0x00000006,0x000047b3,0x000047b9, -0x000047b2,0x000300f7,0x0000484c,0x00000000, -0x000400fa,0x000047ff,0x00004847,0x0000484b, -0x000200f8,0x0000484b,0x000200f9,0x0000484c, -0x000200f8,0x00004847,0x00050082,0x00000006, -0x0000484a,0x00003ca1,0x00000135,0x000200f9, -0x0000484c,0x000200f8,0x0000484c,0x000700f5, -0x00000006,0x00005a6f,0x0000484a,0x00004847, -0x0000012b,0x0000484b,0x00050080,0x00000006, -0x0000483f,0x00005a6f,0x00005cc3,0x00050086, -0x00000006,0x00004840,0x0000483f,0x00000185, -0x00050084,0x00000006,0x000047ac,0x000000df, -0x00004840,0x00050080,0x00000006,0x000047ad, -0x000047b3,0x000047ac,0x000300f7,0x0000485f, -0x00000000,0x000400fa,0x000047ff,0x0000485a, -0x0000485e,0x000200f8,0x0000485e,0x000200f9, -0x0000485f,0x000200f8,0x0000485a,0x00050082, -0x00000006,0x0000485d,0x00003ca1,0x00000135, -0x000200f9,0x0000485f,0x000200f8,0x0000485f, -0x000700f5,0x00000006,0x00005a70,0x0000485d, -0x0000485a,0x0000012b,0x0000485e,0x00050080, -0x00000006,0x00004852,0x00005a70,0x00005cc3, -0x00050086,0x00000006,0x00004853,0x00004852, -0x00000185,0x00050084,0x00000006,0x000047a6, -0x000000df,0x00004853,0x00050080,0x00000006, -0x000047a7,0x000047ad,0x000047a6,0x0004003d, -0x00000006,0x00003d30,0x00003d29,0x00050084, -0x00000006,0x00003d31,0x000000df,0x00003d30, -0x00050080,0x00000006,0x00003d32,0x000047a7, -0x00003d31,0x00050041,0x0000022d,0x00003d34, -0x00000180,0x0000022b,0x0004003d,0x00000007, -0x00003d35,0x00003d34,0x00050041,0x00000009, -0x00003d36,0x00003c67,0x00005a0e,0x0004003d, -0x00000006,0x00003d37,0x00003d36,0x00050051, -0x00000006,0x00004876,0x00003d35,0x00000000, -0x00050095,0x00000130,0x00004878,0x00004876, -0x00003d32,0x00050051,0x00000006,0x00004879, -0x00004878,0x00000001,0x00050051,0x00000006, -0x0000487a,0x00004878,0x00000000,0x00050051, -0x00000006,0x0000487d,0x00003d35,0x00000001, -0x00050080,0x00000006,0x0000487f,0x0000487d, -0x00004879,0x00050050,0x00000007,0x00004880, -0x0000487a,0x0000487f,0x0004007c,0x00000014, -0x00004870,0x00004880,0x00060041,0x0000015f, -0x00004868,0x00004870,0x0000015e,0x0000015e, -0x0005003e,0x00004868,0x00003d37,0x00000002, -0x00000004,0x000200f9,0x00003d39,0x000200f8, -0x00003d39,0x000200f9,0x00003d3a,0x000200f8, -0x00003d3a,0x00050080,0x00000006,0x00003d3c, -0x00005a0e,0x0000022b,0x000200f9,0x00003d23, -0x000200f8,0x00003d3d,0x00050041,0x00000182, -0x00004883,0x00000180,0x00000321,0x0004003d, -0x00000006,0x00004884,0x00004883,0x00050041, -0x00000182,0x00004894,0x00000180,0x000002fb, -0x0004003d,0x00000006,0x00004895,0x00004894, -0x000500c7,0x00000006,0x00004896,0x00004895, -0x00000247,0x000500ab,0x0000002f,0x00004897, -0x00004896,0x0000012b,0x000600a9,0x00000006, -0x00004891,0x00004897,0x0000018b,0x00000309, -0x00050084,0x00000006,0x00004887,0x00005a10, -0x00004891,0x00050080,0x00000006,0x00004888, -0x00004884,0x00004887,0x000500c2,0x00000006, -0x00004889,0x00004888,0x00000318,0x000500c4, -0x00000006,0x0000488a,0x00004889,0x000002e4, -0x000600a9,0x00000006,0x0000488c,0x00004897, -0x000000df,0x0000032b,0x000500c5,0x00000006, -0x0000488d,0x0000488a,0x0000488c,0x000200f9, -0x00003d46,0x000200f8,0x00003d46,0x000700f5, -0x00000006,0x00005a33,0x0000012b,0x00003d3d, -0x00003d74,0x00003d72,0x000500b0,0x0000002f, -0x00003d49,0x00005a33,0x000000df,0x000400f6, -0x00003d75,0x00003d72,0x00000000,0x000400fa, -0x00003d49,0x00003d4a,0x00003d75,0x000200f8, -0x00003d4a,0x00050084,0x00000006,0x00003d4d, -0x000000df,0x00005a33,0x00050080,0x00000006, -0x00003d4e,0x00004888,0x00003d4d,0x00050041, -0x0000022d,0x00003d50,0x00000180,0x0000015e, -0x0004003d,0x00000007,0x00003d51,0x00003d50, -0x00050041,0x00000009,0x00003d52,0x00003c67, -0x00005a33,0x0004003d,0x00000006,0x00003d53, -0x00003d52,0x00050051,0x00000006,0x000048bd, -0x00003d51,0x00000000,0x00050095,0x00000130, -0x000048bf,0x000048bd,0x00003d4e,0x00050051, -0x00000006,0x000048c0,0x000048bf,0x00000001, -0x00050051,0x00000006,0x000048c1,0x000048bf, -0x00000000,0x00050051,0x00000006,0x000048c4, -0x00003d51,0x00000001,0x00050080,0x00000006, -0x000048c6,0x000048c4,0x000048c0,0x00050050, -0x00000007,0x000048c7,0x000048c1,0x000048c6, -0x0004007c,0x00000014,0x000048b7,0x000048c7, -0x00060041,0x0000015f,0x000048af,0x000048b7, -0x0000015e,0x0000015e,0x0005003e,0x000048af, -0x00003d53,0x00000002,0x00000004,0x0004003d, -0x00000006,0x00003d57,0x00003d52,0x000500ab, -0x0000002f,0x00003d58,0x00003d57,0x00000500, -0x000300f7,0x00003d6a,0x00000000,0x000400fa, -0x00003d58,0x00003d59,0x00003d6a,0x000200f8, -0x00003d59,0x00050041,0x00000182,0x00003d5a, -0x00000180,0x00000fbf,0x0004003d,0x00000006, -0x00003d5b,0x00003d5a,0x0004003d,0x00000006, -0x00003d5e,0x00003d52,0x000500c2,0x00000006, -0x000048cb,0x00003d5e,0x000002e4,0x00050041, -0x00000182,0x00003d60,0x00000180,0x00000311, -0x0004003d,0x00000006,0x00003d61,0x00003d60, -0x00050086,0x00000006,0x00003d62,0x00003d61, -0x0000018b,0x00050082,0x00000006,0x00003d63, -0x000048cb,0x00003d62,0x00050084,0x00000006, -0x00003d64,0x000000df,0x00003d63,0x00050080, -0x00000006,0x00003d65,0x00003d5b,0x00003d64, -0x00050095,0x00000130,0x000048e3,0x000048bd, -0x00003d65,0x00050051,0x00000006,0x000048e4, -0x000048e3,0x00000001,0x00050051,0x00000006, -0x000048e5,0x000048e3,0x00000000,0x00050080, -0x00000006,0x000048ea,0x000048c4,0x000048e4, -0x00050050,0x00000007,0x000048eb,0x000048e5, -0x000048ea,0x0004007c,0x00000014,0x000048db, -0x000048eb,0x00060041,0x0000015f,0x000048d3, -0x000048db,0x0000015e,0x0000015e,0x0005003e, -0x000048d3,0x0000488d,0x00000002,0x00000004, -0x000200f9,0x00003d72,0x000200f8,0x00003d6a, -0x000300f7,0x00004944,0x00000000,0x000300fb, -0x0000012b,0x0000490a,0x000200f8,0x0000490a, -0x000300f7,0x00004915,0x00000000,0x000400fa, -0x00004897,0x0000490c,0x00004915,0x000200f8, -0x0000490c,0x00050080,0x00000006,0x0000490e, -0x00004888,0x000001a2,0x00050084,0x00000006, -0x00004910,0x0000019b,0x00005a33,0x00050080, -0x00000006,0x00004911,0x0000490e,0x00004910, -0x00050095,0x00000130,0x00004a40,0x000048bd, -0x00004911,0x00050051,0x00000006,0x00004a41, -0x00004a40,0x00000001,0x00050051,0x00000006, -0x00004a42,0x00004a40,0x00000000,0x00050080, -0x00000006,0x00004a47,0x000048c4,0x00004a41, -0x00050050,0x00000007,0x00004a48,0x00004a42, -0x00004a47,0x0004007c,0x00000014,0x00004a38, -0x00004a48,0x00060041,0x0000015f,0x00004a30, -0x00004a38,0x0000015e,0x0000015e,0x0005003e, -0x00004a30,0x00005cd7,0x00000002,0x00000004, -0x00050080,0x00000006,0x00004968,0x00004911, -0x000000df,0x00050095,0x00000130,0x00004b08, -0x000048bd,0x00004968,0x00050051,0x00000006, -0x00004b09,0x00004b08,0x00000001,0x00050051, -0x00000006,0x00004b0a,0x00004b08,0x00000000, -0x00050080,0x00000006,0x00004b0f,0x000048c4, -0x00004b09,0x00050050,0x00000007,0x00004b10, -0x00004b0a,0x00004b0f,0x0004007c,0x00000014, -0x00004b00,0x00004b10,0x00060041,0x0000015f, -0x00004af8,0x00004b00,0x0000015e,0x0000015e, -0x0005003e,0x00004af8,0x00005cd9,0x00000002, -0x00000004,0x00050080,0x00000006,0x00004975, -0x00004911,0x00000194,0x00050095,0x00000130, -0x00004bd0,0x000048bd,0x00004975,0x00050051, -0x00000006,0x00004bd1,0x00004bd0,0x00000001, -0x00050051,0x00000006,0x00004bd2,0x00004bd0, -0x00000000,0x00050080,0x00000006,0x00004bd7, -0x000048c4,0x00004bd1,0x00050050,0x00000007, -0x00004bd8,0x00004bd2,0x00004bd7,0x0004007c, -0x00000014,0x00004bc8,0x00004bd8,0x00060041, -0x0000015f,0x00004bc0,0x00004bc8,0x0000015e, -0x0000015e,0x0005003e,0x00004bc0,0x00005cda, -0x00000002,0x00000004,0x000200f9,0x00004944, -0x000200f8,0x00004915,0x00050080,0x00000006, -0x00004917,0x00004888,0x000001a2,0x00050084, -0x00000006,0x00004919,0x000001b6,0x00005a33, -0x00050080,0x00000006,0x0000491a,0x00004917, -0x00004919,0x00050095,0x00000130,0x00004bf9, -0x000048bd,0x0000491a,0x00050051,0x00000006, -0x00004bfa,0x00004bf9,0x00000001,0x00050051, -0x00000006,0x00004bfb,0x00004bf9,0x00000000, -0x00050080,0x00000006,0x00004c00,0x000048c4, -0x00004bfa,0x00050050,0x00000007,0x00004c01, -0x00004bfb,0x00004c00,0x0004007c,0x00000014, -0x00004bf1,0x00004c01,0x00060041,0x0000015f, -0x00004be9,0x00004bf1,0x0000015e,0x0000015e, -0x0005003e,0x00004be9,0x00000345,0x00000002, -0x00000004,0x00050080,0x00000006,0x00004922, -0x0000491a,0x000000df,0x00050095,0x00000130, -0x00004c22,0x000048bd,0x00004922,0x00050051, -0x00000006,0x00004c23,0x00004c22,0x00000001, -0x00050051,0x00000006,0x00004c24,0x00004c22, -0x00000000,0x00050080,0x00000006,0x00004c29, -0x000048c4,0x00004c23,0x00050050,0x00000007, -0x00004c2a,0x00004c24,0x00004c29,0x0004007c, -0x00000014,0x00004c1a,0x00004c2a,0x00060041, -0x0000015f,0x00004c12,0x00004c1a,0x0000015e, -0x0000015e,0x0005003e,0x00004c12,0x00000345, -0x00000002,0x00000004,0x00050080,0x00000006, -0x00004929,0x0000491a,0x00000194,0x00050095, -0x00000130,0x00004c4b,0x000048bd,0x00004929, -0x00050051,0x00000006,0x00004c4c,0x00004c4b, -0x00000001,0x00050051,0x00000006,0x00004c4d, -0x00004c4b,0x00000000,0x00050080,0x00000006, -0x00004c52,0x000048c4,0x00004c4c,0x00050050, -0x00000007,0x00004c53,0x00004c4d,0x00004c52, -0x0004007c,0x00000014,0x00004c43,0x00004c53, -0x00060041,0x0000015f,0x00004c3b,0x00004c43, -0x0000015e,0x0000015e,0x0005003e,0x00004c3b, -0x00000345,0x00000002,0x00000004,0x00050080, -0x00000006,0x00004930,0x0000491a,0x0000019b, -0x00050095,0x00000130,0x00004c74,0x000048bd, -0x00004930,0x00050051,0x00000006,0x00004c75, -0x00004c74,0x00000001,0x00050051,0x00000006, -0x00004c76,0x00004c74,0x00000000,0x00050080, -0x00000006,0x00004c7b,0x000048c4,0x00004c75, -0x00050050,0x00000007,0x00004c7c,0x00004c76, -0x00004c7b,0x0004007c,0x00000014,0x00004c6c, -0x00004c7c,0x00060041,0x0000015f,0x00004c64, -0x00004c6c,0x0000015e,0x0000015e,0x0005003e, -0x00004c64,0x00005cc5,0x00000002,0x00000004, -0x00050080,0x00000006,0x00004937,0x0000491a, -0x000001a2,0x00050095,0x00000130,0x00004c9d, -0x000048bd,0x00004937,0x00050051,0x00000006, -0x00004c9e,0x00004c9d,0x00000001,0x00050051, -0x00000006,0x00004c9f,0x00004c9d,0x00000000, -0x00050080,0x00000006,0x00004ca4,0x000048c4, -0x00004c9e,0x00050050,0x00000007,0x00004ca5, -0x00004c9f,0x00004ca4,0x0004007c,0x00000014, -0x00004c95,0x00004ca5,0x00060041,0x0000015f, -0x00004c8d,0x00004c95,0x0000015e,0x0000015e, -0x0005003e,0x00004c8d,0x00005cc5,0x00000002, -0x00000004,0x00050080,0x00000006,0x0000493e, -0x0000491a,0x00000260,0x00050095,0x00000130, -0x00004cc6,0x000048bd,0x0000493e,0x00050051, -0x00000006,0x00004cc7,0x00004cc6,0x00000001, -0x00050051,0x00000006,0x00004cc8,0x00004cc6, -0x00000000,0x00050080,0x00000006,0x00004ccd, -0x000048c4,0x00004cc7,0x00050050,0x00000007, -0x00004cce,0x00004cc8,0x00004ccd,0x0004007c, -0x00000014,0x00004cbe,0x00004cce,0x00060041, -0x0000015f,0x00004cb6,0x00004cbe,0x0000015e, -0x0000015e,0x0005003e,0x00004cb6,0x00005cc5, -0x00000002,0x00000004,0x000200f9,0x00004944, -0x000200f8,0x00004944,0x000200f9,0x00003d72, -0x000200f8,0x00003d72,0x00050080,0x00000006, -0x00003d74,0x00005a33,0x0000022b,0x000200f9, -0x00003d46,0x000200f8,0x00003d75,0x000400a8, -0x0000002f,0x00003d77,0x00004897,0x000300f7, -0x00003d8a,0x00000000,0x000400fa,0x00003d77, -0x00003d78,0x00003d8a,0x000200f8,0x00003d78, -0x000200f9,0x00003d79,0x000200f8,0x00003d79, -0x000700f5,0x00000006,0x00005a34,0x0000012b, -0x00003d78,0x00003d88,0x00003d7d,0x000500b0, -0x0000002f,0x00003d7c,0x00005a34,0x000000df, -0x000400f6,0x00003d89,0x00003d7d,0x00000000, -0x000400fa,0x00003d7c,0x00003d7d,0x00003d89, -0x000200f8,0x00003d7d,0x00050080,0x00000006, -0x00003d7f,0x00004888,0x00000741,0x00050084, -0x00000006,0x00003d81,0x000000df,0x00005a34, -0x00050080,0x00000006,0x00003d82,0x00003d7f, -0x00003d81,0x00050041,0x0000022d,0x00003d83, -0x00000180,0x0000015e,0x0004003d,0x00000007, -0x00003d84,0x00003d83,0x00050051,0x00000006, -0x00004cea,0x00003d84,0x00000000,0x00050095, -0x00000130,0x00004cec,0x00004cea,0x00003d82, -0x00050051,0x00000006,0x00004ced,0x00004cec, -0x00000001,0x00050051,0x00000006,0x00004cee, -0x00004cec,0x00000000,0x00050051,0x00000006, -0x00004cf1,0x00003d84,0x00000001,0x00050080, -0x00000006,0x00004cf3,0x00004cf1,0x00004ced, -0x00050050,0x00000007,0x00004cf4,0x00004cee, -0x00004cf3,0x0004007c,0x00000014,0x00004ce4, -0x00004cf4,0x00060041,0x0000015f,0x00004cdc, -0x00004ce4,0x0000015e,0x0000015e,0x0005003e, -0x00004cdc,0x0000012b,0x00000002,0x00000004, -0x00050080,0x00000006,0x00003d88,0x00005a34, -0x0000022b,0x000200f9,0x00003d79,0x000200f8, -0x00003d89,0x000200f9,0x00003d8a,0x000200f8, -0x00003d8a,0x00050041,0x00000182,0x00004d28, -0x00000180,0x00000181,0x0004003d,0x00000006, -0x00004d29,0x00004d28,0x00050084,0x00000006, -0x00004d2a,0x000001a2,0x00004d29,0x00050080, -0x00000006,0x00004d2b,0x0000018b,0x00004d2a, -0x00050080,0x00000006,0x00004d31,0x00004d29, -0x00005cc3,0x00050086,0x00000006,0x00004d32, -0x00004d31,0x00000185,0x00050084,0x00000006, -0x00004d24,0x0000018b,0x00004d32,0x00050080, -0x00000006,0x00004d25,0x00004d2b,0x00004d24, -0x00050080,0x00000006,0x00004d1f,0x00004d25, -0x00004d24,0x00050084,0x00000006,0x00004d18, -0x000001b6,0x00003ca1,0x00050080,0x00000006, -0x00004d19,0x00004d1f,0x00004d18,0x00050084, -0x00000006,0x00004d0e,0x000001cc,0x00005a10, -0x00050080,0x00000006,0x00004d0f,0x00004d19, -0x00004d0e,0x00050041,0x0000022d,0x00004d10, -0x00000180,0x0000022b,0x0004003d,0x00000007, -0x00004d11,0x00004d10,0x00050051,0x00000006, -0x00004d47,0x00004d11,0x00000000,0x00050095, -0x00000130,0x00004d49,0x00004d47,0x00004d0f, -0x00050051,0x00000006,0x00004d4a,0x00004d49, -0x00000001,0x00050051,0x00000006,0x00004d4b, -0x00004d49,0x00000000,0x00050051,0x00000006, -0x00004d4e,0x00004d11,0x00000001,0x00050080, -0x00000006,0x00004d50,0x00004d4e,0x00004d4a, -0x00050050,0x00000007,0x00004d51,0x00004d4b, -0x00004d50,0x0004007c,0x00000014,0x00004d41, -0x00004d51,0x00060041,0x0000015f,0x00004cfb, -0x00004d41,0x0000015e,0x0000015e,0x0005003e, -0x00004cfb,0x0000012b,0x00000002,0x00000004, -0x00060041,0x0000015f,0x00004cfd,0x00004d41, -0x0000015e,0x0000022b,0x0005003e,0x00004cfd, -0x00000500,0x00000002,0x00000004,0x00060041, -0x0000015f,0x00004cff,0x00004d41,0x0000015e, -0x000002dc,0x0005003e,0x00004cff,0x00000500, -0x00000002,0x00000004,0x00060041,0x0000015f, -0x00004d01,0x00004d41,0x0000015e,0x000002e4, -0x0005003e,0x00004d01,0x00000500,0x00000002, -0x00000004,0x00060041,0x0000015f,0x00004d03, -0x00004d41,0x0000015e,0x000002ec,0x0005003e, -0x00004d03,0x0000012b,0x00000002,0x00000004, -0x00060041,0x0000015f,0x00004d05,0x00004d41, -0x0000015e,0x000002f4,0x0005003e,0x00004d05, -0x0000012b,0x00000002,0x00000004,0x00060041, -0x0000015f,0x00004d07,0x00004d41,0x0000015e, -0x00000318,0x0005003e,0x00004d07,0x0000012b, -0x00000002,0x00000004,0x000200f9,0x00003d8d, -0x000200f8,0x00003d8d,0x000200f9,0x000012e4, -0x000200f8,0x000012e4,0x000200f9,0x000012da, -0x000200f8,0x000012d9,0x0004007c,0x000000e7, -0x000012dc,0x000011de,0x00050080,0x000000e7, -0x000035dc,0x000012dc,0x0000022b,0x000300f7, -0x000036bf,0x00000000,0x000300fb,0x0000012b, -0x0000369d,0x000200f8,0x0000369d,0x000500b1, -0x0000002f,0x0000369f,0x000035dc,0x0000015e, -0x000400a8,0x0000002f,0x000036a0,0x0000369f, -0x000300f7,0x000036a7,0x00000000,0x000400fa, -0x000036a0,0x000036a1,0x000036a7,0x000200f8, -0x000036a1,0x00050041,0x00000182,0x000036a3, -0x00000180,0x000001b7,0x0004003d,0x00000006, -0x000036a4,0x000036a3,0x0004007c,0x000000e7, -0x000036a5,0x000036a4,0x000500af,0x0000002f, -0x000036a6,0x000035dc,0x000036a5,0x000200f9, -0x000036a7,0x000200f8,0x000036a7,0x000700f5, -0x0000002f,0x000036a8,0x0000369f,0x0000369d, -0x000036a6,0x000036a1,0x000300f7,0x000036aa, -0x00000000,0x000400fa,0x000036a8,0x000036a9, -0x000036aa,0x000200f8,0x000036a9,0x000200f9, -0x000036bf,0x000200f8,0x000036aa,0x00050084, -0x00000006,0x000036c8,0x000000df,0x000011de, -0x00050080,0x00000006,0x000036c9,0x0000018b, -0x000036c8,0x00050041,0x0000022d,0x000036ca, -0x00000180,0x0000022b,0x0004003d,0x00000007, -0x000036cb,0x000036ca,0x00050051,0x00000006, -0x000036e5,0x000036cb,0x00000000,0x00050095, -0x00000130,0x000036e7,0x000036e5,0x000036c9, -0x00050051,0x00000006,0x000036e8,0x000036e7, -0x00000001,0x00050051,0x00000006,0x000036e9, -0x000036e7,0x00000000,0x00050051,0x00000006, -0x000036ec,0x000036cb,0x00000001,0x00050080, -0x00000006,0x000036ee,0x000036ec,0x000036e8, -0x00050050,0x00000007,0x000036ef,0x000036e9, -0x000036ee,0x0004007c,0x00000014,0x000036df, -0x000036ef,0x00060041,0x0000015f,0x000036d6, -0x000036df,0x0000015e,0x0000015e,0x0006003d, -0x00000006,0x000036d7,0x000036d6,0x00000002, -0x00000004,0x0004007c,0x00000006,0x000036f6, -0x000035dc,0x00050084,0x00000006,0x000036f7, -0x000000df,0x000036f6,0x00050080,0x00000006, -0x000036f8,0x0000018b,0x000036f7,0x00050095, -0x00000130,0x00003716,0x000036e5,0x000036f8, -0x00050051,0x00000006,0x00003717,0x00003716, -0x00000001,0x00050051,0x00000006,0x00003718, -0x00003716,0x00000000,0x00050080,0x00000006, -0x0000371d,0x000036ec,0x00003717,0x00050050, -0x00000007,0x0000371e,0x00003718,0x0000371d, -0x0004007c,0x00000014,0x0000370e,0x0000371e, -0x00060041,0x0000015f,0x00003705,0x0000370e, -0x0000015e,0x0000015e,0x0006003d,0x00000006, -0x00003706,0x00003705,0x00000002,0x00000004, -0x000500aa,0x0000002f,0x000036b1,0x000036d7, -0x00003706,0x000300f7,0x000036b9,0x00000000, -0x000400fa,0x000036b1,0x000036b2,0x000036b9, -0x000200f8,0x000036b2,0x000500c6,0x000000e7, -0x000036b5,0x000012dc,0x000035dc,0x0004007c, -0x00000006,0x000036b6,0x000036b5,0x0006000c, -0x000000e7,0x000036b7,0x00000001,0x0000004b, -0x000036b6,0x00050082,0x000000e7,0x000036b8, -0x00000c77,0x000036b7,0x000200f9,0x000036bf, -0x000200f8,0x000036b9,0x000500c6,0x00000006, -0x000036bc,0x000036d7,0x00003706,0x0006000c, -0x000000e7,0x000036bd,0x00000001,0x0000004b, -0x000036bc,0x00050082,0x000000e7,0x000036be, -0x00000c7f,0x000036bd,0x000200f9,0x000036bf, -0x000200f8,0x000036bf,0x000900f5,0x000000e7, -0x00005a79,0x00000c68,0x000036a9,0x000036b8, -0x000036b2,0x000036be,0x000036b9,0x00050082, -0x000000e7,0x000035e0,0x000012dc,0x0000022b, -0x000300f7,0x00003749,0x00000000,0x000300fb, -0x0000012b,0x00003727,0x000200f8,0x00003727, -0x000500b1,0x0000002f,0x00003729,0x000035e0, -0x0000015e,0x000400a8,0x0000002f,0x0000372a, -0x00003729,0x000300f7,0x00003731,0x00000000, -0x000400fa,0x0000372a,0x0000372b,0x00003731, -0x000200f8,0x0000372b,0x00050041,0x00000182, -0x0000372d,0x00000180,0x000001b7,0x0004003d, -0x00000006,0x0000372e,0x0000372d,0x0004007c, -0x000000e7,0x0000372f,0x0000372e,0x000500af, -0x0000002f,0x00003730,0x000035e0,0x0000372f, -0x000200f9,0x00003731,0x000200f8,0x00003731, -0x000700f5,0x0000002f,0x00003732,0x00003729, -0x00003727,0x00003730,0x0000372b,0x000300f7, -0x00003734,0x00000000,0x000400fa,0x00003732, -0x00003733,0x00003734,0x000200f8,0x00003733, -0x000200f9,0x00003749,0x000200f8,0x00003734, -0x00050084,0x00000006,0x00003752,0x000000df, -0x000011de,0x00050080,0x00000006,0x00003753, -0x0000018b,0x00003752,0x00050041,0x0000022d, -0x00003754,0x00000180,0x0000022b,0x0004003d, -0x00000007,0x00003755,0x00003754,0x00050051, -0x00000006,0x0000376f,0x00003755,0x00000000, -0x00050095,0x00000130,0x00003771,0x0000376f, -0x00003753,0x00050051,0x00000006,0x00003772, -0x00003771,0x00000001,0x00050051,0x00000006, -0x00003773,0x00003771,0x00000000,0x00050051, -0x00000006,0x00003776,0x00003755,0x00000001, -0x00050080,0x00000006,0x00003778,0x00003776, -0x00003772,0x00050050,0x00000007,0x00003779, -0x00003773,0x00003778,0x0004007c,0x00000014, -0x00003769,0x00003779,0x00060041,0x0000015f, -0x00003760,0x00003769,0x0000015e,0x0000015e, -0x0006003d,0x00000006,0x00003761,0x00003760, -0x00000002,0x00000004,0x0004007c,0x00000006, -0x00003780,0x000035e0,0x00050084,0x00000006, -0x00003781,0x000000df,0x00003780,0x00050080, -0x00000006,0x00003782,0x0000018b,0x00003781, -0x00050095,0x00000130,0x000037a0,0x0000376f, -0x00003782,0x00050051,0x00000006,0x000037a1, -0x000037a0,0x00000001,0x00050051,0x00000006, -0x000037a2,0x000037a0,0x00000000,0x00050080, -0x00000006,0x000037a7,0x00003776,0x000037a1, -0x00050050,0x00000007,0x000037a8,0x000037a2, -0x000037a7,0x0004007c,0x00000014,0x00003798, -0x000037a8,0x00060041,0x0000015f,0x0000378f, -0x00003798,0x0000015e,0x0000015e,0x0006003d, -0x00000006,0x00003790,0x0000378f,0x00000002, -0x00000004,0x000500aa,0x0000002f,0x0000373b, -0x00003761,0x00003790,0x000300f7,0x00003743, -0x00000000,0x000400fa,0x0000373b,0x0000373c, -0x00003743,0x000200f8,0x0000373c,0x000500c6, -0x000000e7,0x0000373f,0x000012dc,0x000035e0, -0x0004007c,0x00000006,0x00003740,0x0000373f, -0x0006000c,0x000000e7,0x00003741,0x00000001, -0x0000004b,0x00003740,0x00050082,0x000000e7, -0x00003742,0x00000c77,0x00003741,0x000200f9, -0x00003749,0x000200f8,0x00003743,0x000500c6, -0x00000006,0x00003746,0x00003761,0x00003790, -0x0006000c,0x000000e7,0x00003747,0x00000001, -0x0000004b,0x00003746,0x00050082,0x000000e7, -0x00003748,0x00000c7f,0x00003747,0x000200f9, -0x00003749,0x000200f8,0x00003749,0x000900f5, -0x000000e7,0x00005a7a,0x00000c68,0x00003733, -0x00003742,0x0000373c,0x00003748,0x00003743, -0x00050082,0x000000e7,0x000035e3,0x00005a79, -0x00005a7a,0x000500ad,0x0000002f,0x000035e4, -0x000035e3,0x0000015e,0x000600a9,0x000000e7, -0x000035e5,0x000035e4,0x0000022b,0x00000c68, -0x00050082,0x000000e7,0x000035e8,0x000012dc, -0x000035e5,0x000300f7,0x000037d3,0x00000000, -0x000300fb,0x0000012b,0x000037b1,0x000200f8, -0x000037b1,0x000500b1,0x0000002f,0x000037b3, -0x000035e8,0x0000015e,0x000400a8,0x0000002f, -0x000037b4,0x000037b3,0x000300f7,0x000037bb, -0x00000000,0x000400fa,0x000037b4,0x000037b5, -0x000037bb,0x000200f8,0x000037b5,0x00050041, -0x00000182,0x000037b7,0x00000180,0x000001b7, -0x0004003d,0x00000006,0x000037b8,0x000037b7, -0x0004007c,0x000000e7,0x000037b9,0x000037b8, -0x000500af,0x0000002f,0x000037ba,0x000035e8, -0x000037b9,0x000200f9,0x000037bb,0x000200f8, -0x000037bb,0x000700f5,0x0000002f,0x000037bc, -0x000037b3,0x000037b1,0x000037ba,0x000037b5, -0x000300f7,0x000037be,0x00000000,0x000400fa, -0x000037bc,0x000037bd,0x000037be,0x000200f8, -0x000037bd,0x000200f9,0x000037d3,0x000200f8, -0x000037be,0x00050084,0x00000006,0x000037dc, -0x000000df,0x000011de,0x00050080,0x00000006, -0x000037dd,0x0000018b,0x000037dc,0x00050041, -0x0000022d,0x000037de,0x00000180,0x0000022b, -0x0004003d,0x00000007,0x000037df,0x000037de, -0x00050051,0x00000006,0x000037f9,0x000037df, -0x00000000,0x00050095,0x00000130,0x000037fb, -0x000037f9,0x000037dd,0x00050051,0x00000006, -0x000037fc,0x000037fb,0x00000001,0x00050051, -0x00000006,0x000037fd,0x000037fb,0x00000000, -0x00050051,0x00000006,0x00003800,0x000037df, -0x00000001,0x00050080,0x00000006,0x00003802, -0x00003800,0x000037fc,0x00050050,0x00000007, -0x00003803,0x000037fd,0x00003802,0x0004007c, -0x00000014,0x000037f3,0x00003803,0x00060041, -0x0000015f,0x000037ea,0x000037f3,0x0000015e, -0x0000015e,0x0006003d,0x00000006,0x000037eb, -0x000037ea,0x00000002,0x00000004,0x0004007c, -0x00000006,0x0000380a,0x000035e8,0x00050084, -0x00000006,0x0000380b,0x000000df,0x0000380a, -0x00050080,0x00000006,0x0000380c,0x0000018b, -0x0000380b,0x00050095,0x00000130,0x0000382a, -0x000037f9,0x0000380c,0x00050051,0x00000006, -0x0000382b,0x0000382a,0x00000001,0x00050051, -0x00000006,0x0000382c,0x0000382a,0x00000000, -0x00050080,0x00000006,0x00003831,0x00003800, -0x0000382b,0x00050050,0x00000007,0x00003832, -0x0000382c,0x00003831,0x0004007c,0x00000014, -0x00003822,0x00003832,0x00060041,0x0000015f, -0x00003819,0x00003822,0x0000015e,0x0000015e, -0x0006003d,0x00000006,0x0000381a,0x00003819, -0x00000002,0x00000004,0x000500aa,0x0000002f, -0x000037c5,0x000037eb,0x0000381a,0x000300f7, -0x000037cd,0x00000000,0x000400fa,0x000037c5, -0x000037c6,0x000037cd,0x000200f8,0x000037c6, -0x000500c6,0x000000e7,0x000037c9,0x000012dc, -0x000035e8,0x0004007c,0x00000006,0x000037ca, -0x000037c9,0x0006000c,0x000000e7,0x000037cb, -0x00000001,0x0000004b,0x000037ca,0x00050082, -0x000000e7,0x000037cc,0x00000c77,0x000037cb, -0x000200f9,0x000037d3,0x000200f8,0x000037cd, -0x000500c6,0x00000006,0x000037d0,0x000037eb, -0x0000381a,0x0006000c,0x000000e7,0x000037d1, -0x00000001,0x0000004b,0x000037d0,0x00050082, -0x000000e7,0x000037d2,0x00000c7f,0x000037d1, -0x000200f9,0x000037d3,0x000200f8,0x000037d3, -0x000900f5,0x000000e7,0x00005a7b,0x00000c68, -0x000037bd,0x000037cc,0x000037c6,0x000037d2, -0x000037cd,0x000200f9,0x000035eb,0x000200f8, -0x000035eb,0x000700f5,0x000000e7,0x00005a7c, -0x000002dc,0x000037d3,0x000035f8,0x000035f6, -0x000400f6,0x000035fa,0x000035f6,0x00000000, -0x000200f9,0x000035ec,0x000200f8,0x000035ec, -0x00050084,0x000000e7,0x000035f0,0x00005a7c, -0x000035e5,0x00050080,0x000000e7,0x000035f1, -0x000012dc,0x000035f0,0x000300f7,0x0000385d, -0x00000000,0x000300fb,0x0000012b,0x0000383b, -0x000200f8,0x0000383b,0x000500b1,0x0000002f, -0x0000383d,0x000035f1,0x0000015e,0x000400a8, -0x0000002f,0x0000383e,0x0000383d,0x000300f7, -0x00003845,0x00000000,0x000400fa,0x0000383e, -0x0000383f,0x00003845,0x000200f8,0x0000383f, -0x00050041,0x00000182,0x00003841,0x00000180, -0x000001b7,0x0004003d,0x00000006,0x00003842, -0x00003841,0x0004007c,0x000000e7,0x00003843, -0x00003842,0x000500af,0x0000002f,0x00003844, -0x000035f1,0x00003843,0x000200f9,0x00003845, -0x000200f8,0x00003845,0x000700f5,0x0000002f, -0x00003846,0x0000383d,0x0000383b,0x00003844, -0x0000383f,0x000300f7,0x00003848,0x00000000, -0x000400fa,0x00003846,0x00003847,0x00003848, -0x000200f8,0x00003847,0x000200f9,0x0000385d, -0x000200f8,0x00003848,0x00050084,0x00000006, -0x00003866,0x000000df,0x000011de,0x00050080, -0x00000006,0x00003867,0x0000018b,0x00003866, -0x00050041,0x0000022d,0x00003868,0x00000180, -0x0000022b,0x0004003d,0x00000007,0x00003869, -0x00003868,0x00050051,0x00000006,0x00003883, -0x00003869,0x00000000,0x00050095,0x00000130, -0x00003885,0x00003883,0x00003867,0x00050051, -0x00000006,0x00003886,0x00003885,0x00000001, -0x00050051,0x00000006,0x00003887,0x00003885, -0x00000000,0x00050051,0x00000006,0x0000388a, -0x00003869,0x00000001,0x00050080,0x00000006, -0x0000388c,0x0000388a,0x00003886,0x00050050, -0x00000007,0x0000388d,0x00003887,0x0000388c, -0x0004007c,0x00000014,0x0000387d,0x0000388d, -0x00060041,0x0000015f,0x00003874,0x0000387d, -0x0000015e,0x0000015e,0x0006003d,0x00000006, -0x00003875,0x00003874,0x00000002,0x00000004, -0x0004007c,0x00000006,0x00003894,0x000035f1, -0x00050084,0x00000006,0x00003895,0x000000df, -0x00003894,0x00050080,0x00000006,0x00003896, -0x0000018b,0x00003895,0x00050095,0x00000130, -0x000038b4,0x00003883,0x00003896,0x00050051, -0x00000006,0x000038b5,0x000038b4,0x00000001, -0x00050051,0x00000006,0x000038b6,0x000038b4, -0x00000000,0x00050080,0x00000006,0x000038bb, -0x0000388a,0x000038b5,0x00050050,0x00000007, -0x000038bc,0x000038b6,0x000038bb,0x0004007c, -0x00000014,0x000038ac,0x000038bc,0x00060041, -0x0000015f,0x000038a3,0x000038ac,0x0000015e, -0x0000015e,0x0006003d,0x00000006,0x000038a4, -0x000038a3,0x00000002,0x00000004,0x000500aa, -0x0000002f,0x0000384f,0x00003875,0x000038a4, -0x000300f7,0x00003857,0x00000000,0x000400fa, -0x0000384f,0x00003850,0x00003857,0x000200f8, -0x00003850,0x000500c6,0x000000e7,0x00003853, -0x000012dc,0x000035f1,0x0004007c,0x00000006, -0x00003854,0x00003853,0x0006000c,0x000000e7, -0x00003855,0x00000001,0x0000004b,0x00003854, -0x00050082,0x000000e7,0x00003856,0x00000c77, -0x00003855,0x000200f9,0x0000385d,0x000200f8, -0x00003857,0x000500c6,0x00000006,0x0000385a, -0x00003875,0x000038a4,0x0006000c,0x000000e7, -0x0000385b,0x00000001,0x0000004b,0x0000385a, -0x00050082,0x000000e7,0x0000385c,0x00000c7f, -0x0000385b,0x000200f9,0x0000385d,0x000200f8, -0x0000385d,0x000900f5,0x000000e7,0x00005a7d, -0x00000c68,0x00003847,0x00003856,0x00003850, -0x0000385c,0x00003857,0x000500ad,0x0000002f, -0x000035f5,0x00005a7d,0x00005a7b,0x000400fa, -0x000035f5,0x000035f6,0x000035fa,0x000200f8, -0x000035f6,0x000500c4,0x000000e7,0x000035f8, -0x00005a7c,0x0000022b,0x000200f9,0x000035eb, -0x000200f8,0x000035fa,0x000500c3,0x000000e7, -0x000035fc,0x00005a7c,0x0000022b,0x000200f9, -0x000035fd,0x000200f8,0x000035fd,0x000700f5, -0x000000e7,0x00005a81,0x0000015e,0x000035fa, -0x00005cdc,0x00003612,0x000700f5,0x000000e7, -0x00005a80,0x000035fc,0x000035fa,0x00003614, -0x00003612,0x000500af,0x0000002f,0x00003600, -0x00005a80,0x0000022b,0x000400f6,0x00003615, -0x00003612,0x00000000,0x000400fa,0x00003600, -0x00003601,0x00003615,0x000200f8,0x00003601, -0x00050080,0x000000e7,0x00003605,0x00005a81, -0x00005a80,0x00050084,0x000000e7,0x00003607, -0x00003605,0x000035e5,0x00050080,0x000000e7, -0x00003608,0x000012dc,0x00003607,0x000300f7, -0x000038e7,0x00000000,0x000300fb,0x0000012b, -0x000038c5,0x000200f8,0x000038c5,0x000500b1, -0x0000002f,0x000038c7,0x00003608,0x0000015e, -0x000400a8,0x0000002f,0x000038c8,0x000038c7, -0x000300f7,0x000038cf,0x00000000,0x000400fa, -0x000038c8,0x000038c9,0x000038cf,0x000200f8, -0x000038c9,0x00050041,0x00000182,0x000038cb, -0x00000180,0x000001b7,0x0004003d,0x00000006, -0x000038cc,0x000038cb,0x0004007c,0x000000e7, -0x000038cd,0x000038cc,0x000500af,0x0000002f, -0x000038ce,0x00003608,0x000038cd,0x000200f9, -0x000038cf,0x000200f8,0x000038cf,0x000700f5, -0x0000002f,0x000038d0,0x000038c7,0x000038c5, -0x000038ce,0x000038c9,0x000300f7,0x000038d2, -0x00000000,0x000400fa,0x000038d0,0x000038d1, -0x000038d2,0x000200f8,0x000038d1,0x000200f9, -0x000038e7,0x000200f8,0x000038d2,0x00050084, -0x00000006,0x000038f0,0x000000df,0x000011de, -0x00050080,0x00000006,0x000038f1,0x0000018b, -0x000038f0,0x00050041,0x0000022d,0x000038f2, -0x00000180,0x0000022b,0x0004003d,0x00000007, -0x000038f3,0x000038f2,0x00050051,0x00000006, -0x0000390d,0x000038f3,0x00000000,0x00050095, -0x00000130,0x0000390f,0x0000390d,0x000038f1, -0x00050051,0x00000006,0x00003910,0x0000390f, -0x00000001,0x00050051,0x00000006,0x00003911, -0x0000390f,0x00000000,0x00050051,0x00000006, -0x00003914,0x000038f3,0x00000001,0x00050080, -0x00000006,0x00003916,0x00003914,0x00003910, -0x00050050,0x00000007,0x00003917,0x00003911, -0x00003916,0x0004007c,0x00000014,0x00003907, -0x00003917,0x00060041,0x0000015f,0x000038fe, -0x00003907,0x0000015e,0x0000015e,0x0006003d, -0x00000006,0x000038ff,0x000038fe,0x00000002, -0x00000004,0x0004007c,0x00000006,0x0000391e, -0x00003608,0x00050084,0x00000006,0x0000391f, -0x000000df,0x0000391e,0x00050080,0x00000006, -0x00003920,0x0000018b,0x0000391f,0x00050095, -0x00000130,0x0000393e,0x0000390d,0x00003920, -0x00050051,0x00000006,0x0000393f,0x0000393e, -0x00000001,0x00050051,0x00000006,0x00003940, -0x0000393e,0x00000000,0x00050080,0x00000006, -0x00003945,0x00003914,0x0000393f,0x00050050, -0x00000007,0x00003946,0x00003940,0x00003945, -0x0004007c,0x00000014,0x00003936,0x00003946, -0x00060041,0x0000015f,0x0000392d,0x00003936, -0x0000015e,0x0000015e,0x0006003d,0x00000006, -0x0000392e,0x0000392d,0x00000002,0x00000004, -0x000500aa,0x0000002f,0x000038d9,0x000038ff, -0x0000392e,0x000300f7,0x000038e1,0x00000000, -0x000400fa,0x000038d9,0x000038da,0x000038e1, -0x000200f8,0x000038da,0x000500c6,0x000000e7, -0x000038dd,0x000012dc,0x00003608,0x0004007c, -0x00000006,0x000038de,0x000038dd,0x0006000c, -0x000000e7,0x000038df,0x00000001,0x0000004b, -0x000038de,0x00050082,0x000000e7,0x000038e0, -0x00000c77,0x000038df,0x000200f9,0x000038e7, -0x000200f8,0x000038e1,0x000500c6,0x00000006, -0x000038e4,0x000038ff,0x0000392e,0x0006000c, -0x000000e7,0x000038e5,0x00000001,0x0000004b, -0x000038e4,0x00050082,0x000000e7,0x000038e6, -0x00000c7f,0x000038e5,0x000200f9,0x000038e7, -0x000200f8,0x000038e7,0x000900f5,0x000000e7, -0x00005a97,0x00000c68,0x000038d1,0x000038e0, -0x000038da,0x000038e6,0x000038e1,0x000500ad, -0x0000002f,0x0000360c,0x00005a97,0x00005a7b, -0x000600a9,0x000000e7,0x00005cdc,0x0000360c, -0x00003605,0x00005a81,0x000200f9,0x00003612, -0x000200f8,0x00003612,0x000500c3,0x000000e7, -0x00003614,0x00005a80,0x0000022b,0x000200f9, -0x000035fd,0x000200f8,0x00003615,0x00050084, -0x000000e7,0x00003619,0x00005a81,0x000035e5, -0x00050080,0x000000e7,0x0000361a,0x000012dc, -0x00003619,0x000300f7,0x00003971,0x00000000, -0x000300fb,0x0000012b,0x0000394f,0x000200f8, -0x0000394f,0x000500b1,0x0000002f,0x00003951, -0x0000361a,0x0000015e,0x000400a8,0x0000002f, -0x00003952,0x00003951,0x000300f7,0x00003959, -0x00000000,0x000400fa,0x00003952,0x00003953, -0x00003959,0x000200f8,0x00003953,0x00050041, -0x00000182,0x00003955,0x00000180,0x000001b7, -0x0004003d,0x00000006,0x00003956,0x00003955, -0x0004007c,0x000000e7,0x00003957,0x00003956, -0x000500af,0x0000002f,0x00003958,0x0000361a, -0x00003957,0x000200f9,0x00003959,0x000200f8, -0x00003959,0x000700f5,0x0000002f,0x0000395a, -0x00003951,0x0000394f,0x00003958,0x00003953, -0x000300f7,0x0000395c,0x00000000,0x000400fa, -0x0000395a,0x0000395b,0x0000395c,0x000200f8, -0x0000395b,0x000200f9,0x00003971,0x000200f8, -0x0000395c,0x00050084,0x00000006,0x0000397a, -0x000000df,0x000011de,0x00050080,0x00000006, -0x0000397b,0x0000018b,0x0000397a,0x00050041, -0x0000022d,0x0000397c,0x00000180,0x0000022b, -0x0004003d,0x00000007,0x0000397d,0x0000397c, -0x00050051,0x00000006,0x00003997,0x0000397d, -0x00000000,0x00050095,0x00000130,0x00003999, -0x00003997,0x0000397b,0x00050051,0x00000006, -0x0000399a,0x00003999,0x00000001,0x00050051, -0x00000006,0x0000399b,0x00003999,0x00000000, -0x00050051,0x00000006,0x0000399e,0x0000397d, -0x00000001,0x00050080,0x00000006,0x000039a0, -0x0000399e,0x0000399a,0x00050050,0x00000007, -0x000039a1,0x0000399b,0x000039a0,0x0004007c, -0x00000014,0x00003991,0x000039a1,0x00060041, -0x0000015f,0x00003988,0x00003991,0x0000015e, -0x0000015e,0x0006003d,0x00000006,0x00003989, -0x00003988,0x00000002,0x00000004,0x0004007c, -0x00000006,0x000039a8,0x0000361a,0x00050084, -0x00000006,0x000039a9,0x000000df,0x000039a8, -0x00050080,0x00000006,0x000039aa,0x0000018b, -0x000039a9,0x00050095,0x00000130,0x000039c8, -0x00003997,0x000039aa,0x00050051,0x00000006, -0x000039c9,0x000039c8,0x00000001,0x00050051, -0x00000006,0x000039ca,0x000039c8,0x00000000, -0x00050080,0x00000006,0x000039cf,0x0000399e, -0x000039c9,0x00050050,0x00000007,0x000039d0, -0x000039ca,0x000039cf,0x0004007c,0x00000014, -0x000039c0,0x000039d0,0x00060041,0x0000015f, -0x000039b7,0x000039c0,0x0000015e,0x0000015e, -0x0006003d,0x00000006,0x000039b8,0x000039b7, -0x00000002,0x00000004,0x000500aa,0x0000002f, -0x00003963,0x00003989,0x000039b8,0x000300f7, -0x0000396b,0x00000000,0x000400fa,0x00003963, -0x00003964,0x0000396b,0x000200f8,0x00003964, -0x000500c6,0x000000e7,0x00003967,0x000012dc, -0x0000361a,0x0004007c,0x00000006,0x00003968, -0x00003967,0x0006000c,0x000000e7,0x00003969, -0x00000001,0x0000004b,0x00003968,0x00050082, -0x000000e7,0x0000396a,0x00000c77,0x00003969, -0x000200f9,0x00003971,0x000200f8,0x0000396b, -0x000500c6,0x00000006,0x0000396e,0x00003989, -0x000039b8,0x0006000c,0x000000e7,0x0000396f, -0x00000001,0x0000004b,0x0000396e,0x00050082, -0x000000e7,0x00003970,0x00000c7f,0x0000396f, -0x000200f9,0x00003971,0x000200f8,0x00003971, -0x000900f5,0x000000e7,0x00005a82,0x00000c68, -0x0000395b,0x0000396a,0x00003964,0x00003970, -0x0000396b,0x000200f9,0x0000361f,0x000200f8, -0x0000361f,0x000700f5,0x000000e7,0x00005a86, -0x0000015e,0x00003971,0x00005cdd,0x00003634, -0x000700f5,0x000000e7,0x00005a85,0x00005a81, -0x00003971,0x00003623,0x00003634,0x000400f6, -0x00003637,0x00003634,0x00000000,0x000200f9, -0x00003620,0x000200f8,0x00003620,0x00050080, -0x000000e7,0x00003622,0x00005a85,0x0000022b, -0x000500c3,0x000000e7,0x00003623,0x00003622, -0x0000022b,0x00050080,0x000000e7,0x00003627, -0x00005a86,0x00003623,0x00050084,0x000000e7, -0x00003629,0x00003627,0x000035e5,0x00050080, -0x000000e7,0x0000362a,0x000012dc,0x00003629, -0x000300f7,0x000039fb,0x00000000,0x000300fb, -0x0000012b,0x000039d9,0x000200f8,0x000039d9, -0x000500b1,0x0000002f,0x000039db,0x0000362a, -0x0000015e,0x000400a8,0x0000002f,0x000039dc, -0x000039db,0x000300f7,0x000039e3,0x00000000, -0x000400fa,0x000039dc,0x000039dd,0x000039e3, -0x000200f8,0x000039dd,0x00050041,0x00000182, -0x000039df,0x00000180,0x000001b7,0x0004003d, -0x00000006,0x000039e0,0x000039df,0x0004007c, -0x000000e7,0x000039e1,0x000039e0,0x000500af, -0x0000002f,0x000039e2,0x0000362a,0x000039e1, -0x000200f9,0x000039e3,0x000200f8,0x000039e3, -0x000700f5,0x0000002f,0x000039e4,0x000039db, -0x000039d9,0x000039e2,0x000039dd,0x000300f7, -0x000039e6,0x00000000,0x000400fa,0x000039e4, -0x000039e5,0x000039e6,0x000200f8,0x000039e5, -0x000200f9,0x000039fb,0x000200f8,0x000039e6, -0x00050084,0x00000006,0x00003a04,0x000000df, -0x000011de,0x00050080,0x00000006,0x00003a05, -0x0000018b,0x00003a04,0x00050041,0x0000022d, -0x00003a06,0x00000180,0x0000022b,0x0004003d, -0x00000007,0x00003a07,0x00003a06,0x00050051, -0x00000006,0x00003a21,0x00003a07,0x00000000, -0x00050095,0x00000130,0x00003a23,0x00003a21, -0x00003a05,0x00050051,0x00000006,0x00003a24, -0x00003a23,0x00000001,0x00050051,0x00000006, -0x00003a25,0x00003a23,0x00000000,0x00050051, -0x00000006,0x00003a28,0x00003a07,0x00000001, -0x00050080,0x00000006,0x00003a2a,0x00003a28, -0x00003a24,0x00050050,0x00000007,0x00003a2b, -0x00003a25,0x00003a2a,0x0004007c,0x00000014, -0x00003a1b,0x00003a2b,0x00060041,0x0000015f, -0x00003a12,0x00003a1b,0x0000015e,0x0000015e, -0x0006003d,0x00000006,0x00003a13,0x00003a12, -0x00000002,0x00000004,0x0004007c,0x00000006, -0x00003a32,0x0000362a,0x00050084,0x00000006, -0x00003a33,0x000000df,0x00003a32,0x00050080, -0x00000006,0x00003a34,0x0000018b,0x00003a33, -0x00050095,0x00000130,0x00003a52,0x00003a21, -0x00003a34,0x00050051,0x00000006,0x00003a53, -0x00003a52,0x00000001,0x00050051,0x00000006, -0x00003a54,0x00003a52,0x00000000,0x00050080, -0x00000006,0x00003a59,0x00003a28,0x00003a53, -0x00050050,0x00000007,0x00003a5a,0x00003a54, -0x00003a59,0x0004007c,0x00000014,0x00003a4a, -0x00003a5a,0x00060041,0x0000015f,0x00003a41, -0x00003a4a,0x0000015e,0x0000015e,0x0006003d, -0x00000006,0x00003a42,0x00003a41,0x00000002, -0x00000004,0x000500aa,0x0000002f,0x000039ed, -0x00003a13,0x00003a42,0x000300f7,0x000039f5, -0x00000000,0x000400fa,0x000039ed,0x000039ee, -0x000039f5,0x000200f8,0x000039ee,0x000500c6, -0x000000e7,0x000039f1,0x000012dc,0x0000362a, -0x0004007c,0x00000006,0x000039f2,0x000039f1, -0x0006000c,0x000000e7,0x000039f3,0x00000001, -0x0000004b,0x000039f2,0x00050082,0x000000e7, -0x000039f4,0x00000c77,0x000039f3,0x000200f9, -0x000039fb,0x000200f8,0x000039f5,0x000500c6, -0x00000006,0x000039f8,0x00003a13,0x00003a42, -0x0006000c,0x000000e7,0x000039f9,0x00000001, -0x0000004b,0x000039f8,0x00050082,0x000000e7, -0x000039fa,0x00000c7f,0x000039f9,0x000200f9, -0x000039fb,0x000200f8,0x000039fb,0x000900f5, -0x000000e7,0x00005a87,0x00000c68,0x000039e5, -0x000039f4,0x000039ee,0x000039fa,0x000039f5, -0x000500ad,0x0000002f,0x0000362e,0x00005a87, -0x00005a82,0x000600a9,0x000000e7,0x00005cdd, -0x0000362e,0x00003627,0x00005a86,0x000200f9, -0x00003634,0x000200f8,0x00003634,0x000500ad, -0x0000002f,0x00003636,0x00003623,0x0000022b, -0x000400fa,0x00003636,0x0000361f,0x00003637, -0x000200f8,0x00003637,0x00050084,0x000000e7, -0x0000363b,0x00005cdd,0x000035e5,0x00050080, -0x000000e7,0x0000363c,0x000012dc,0x0000363b, -0x0007000c,0x000000e7,0x0000363e,0x00000001, -0x00000027,0x000035e5,0x0000015e,0x00050080, -0x000000e7,0x0000363f,0x0000363c,0x0000363e, -0x0007000c,0x000000e7,0x00003642,0x00000001, -0x00000027,0x000012dc,0x0000361a,0x000500aa, -0x0000002f,0x00003644,0x00003642,0x0000363f, -0x000300f7,0x0000364c,0x00000000,0x000400fa, -0x00003644,0x00003645,0x00003649,0x000200f8, -0x00003649,0x0004007c,0x00000006,0x0000364b, -0x0000363f,0x000200f9,0x0000364c,0x000200f8, -0x00003645,0x0004007c,0x00000006,0x00003647, -0x0000363f,0x000500c5,0x00000006,0x00003648, -0x00000208,0x00003647,0x000200f9,0x0000364c, -0x000200f8,0x0000364c,0x000700f5,0x00000006, -0x00005a8e,0x00003648,0x00003645,0x0000364b, -0x00003649,0x0007000c,0x000000e7,0x00003650, -0x00000001,0x0000002a,0x000012dc,0x0000361a, -0x00050080,0x000000e7,0x00003652,0x0000363f, -0x0000022b,0x000500aa,0x0000002f,0x00003653, -0x00003650,0x00003652,0x000300f7,0x0000365d, -0x00000000,0x000400fa,0x00003653,0x00003654, -0x00003659,0x000200f8,0x00003659,0x0004007c, -0x00000006,0x0000365c,0x00003652,0x000200f9, -0x0000365d,0x000200f8,0x00003654,0x0004007c, -0x00000006,0x00003657,0x00003652,0x000500c5, -0x00000006,0x00003658,0x00000208,0x00003657, -0x000200f9,0x0000365d,0x000200f8,0x0000365d, -0x000700f5,0x00000006,0x00005a8f,0x00003658, -0x00003654,0x0000365c,0x00003659,0x00050041, -0x00000182,0x00003a77,0x00000180,0x00000181, -0x0004003d,0x00000006,0x00003a78,0x00003a77, -0x00050084,0x00000006,0x00003a79,0x000001a2, -0x00003a78,0x00050080,0x00000006,0x00003a7a, -0x0000018b,0x00003a79,0x00050080,0x00000006, -0x00003a80,0x00003a78,0x00005cc3,0x00050086, -0x00000006,0x00003a81,0x00003a80,0x00000185, -0x00050084,0x00000006,0x00003a73,0x0000018b, -0x00003a81,0x00050080,0x00000006,0x00003a74, -0x00003a7a,0x00003a73,0x00050080,0x00000006, -0x00003a6e,0x00003a74,0x00003a73,0x00050041, -0x00000182,0x00003a65,0x00000180,0x000001b7, -0x0004003d,0x00000006,0x00003a66,0x00003a65, -0x00050084,0x00000006,0x00003a67,0x000001b6, -0x00003a66,0x00050080,0x00000006,0x00003a68, -0x00003a6e,0x00003a67,0x00050041,0x00000182, -0x00003a5e,0x00000180,0x000001cd,0x0004003d, -0x00000006,0x00003a5f,0x00003a5e,0x00050084, -0x00000006,0x00003a60,0x000001cc,0x00003a5f, -0x00050080,0x00000006,0x00003a61,0x00003a68, -0x00003a60,0x00050084,0x00000006,0x00003662, -0x000000df,0x000011de,0x00050080,0x00000006, -0x00003663,0x00003a61,0x00003662,0x00050041, -0x0000022d,0x00003664,0x00000180,0x0000022b, -0x0004003d,0x00000007,0x00003665,0x00003664, -0x00050051,0x00000006,0x00003a9e,0x00003665, -0x00000000,0x00050095,0x00000130,0x00003aa0, -0x00003a9e,0x00003663,0x00050051,0x00000006, -0x00003aa1,0x00003aa0,0x00000001,0x00050051, -0x00000006,0x00003aa2,0x00003aa0,0x00000000, -0x00050051,0x00000006,0x00003aa5,0x00003665, -0x00000001,0x00050080,0x00000006,0x00003aa7, -0x00003aa5,0x00003aa1,0x00050050,0x00000007, -0x00003aa8,0x00003aa2,0x00003aa7,0x0004007c, -0x00000014,0x00003a98,0x00003aa8,0x00060041, -0x0000015f,0x00003a90,0x00003a98,0x0000015e, -0x0000015e,0x0005003e,0x00003a90,0x00005a8e, -0x00000002,0x00000004,0x000500ac,0x0000002f, -0x00003ae2,0x00003a66,0x00000135,0x000300f7, -0x00003ae8,0x00000000,0x000400fa,0x00003ae2, -0x00003ae3,0x00003ae7,0x000200f8,0x00003ae7, -0x000200f9,0x00003ae8,0x000200f8,0x00003ae3, -0x00050082,0x00000006,0x00003ae6,0x00003a66, -0x00000135,0x000200f9,0x00003ae8,0x000200f8, -0x00003ae8,0x000700f5,0x00000006,0x00005a90, -0x00003ae6,0x00003ae3,0x0000012b,0x00003ae7, -0x00050084,0x00000006,0x00003aad,0x000000df, -0x00005a90,0x00050080,0x00000006,0x00003aae, -0x00003a61,0x00003aad,0x00050080,0x00000006, -0x0000366c,0x00003aae,0x00003662,0x00050095, -0x00000130,0x00003b01,0x00003a9e,0x0000366c, -0x00050051,0x00000006,0x00003b02,0x00003b01, -0x00000001,0x00050051,0x00000006,0x00003b03, -0x00003b01,0x00000000,0x00050080,0x00000006, -0x00003b08,0x00003aa5,0x00003b02,0x00050050, -0x00000007,0x00003b09,0x00003b03,0x00003b08, -0x0004007c,0x00000014,0x00003af9,0x00003b09, -0x00060041,0x0000015f,0x00003af1,0x00003af9, -0x0000015e,0x0000015e,0x0005003e,0x00003af1, -0x00005a8f,0x00000002,0x00000004,0x000500c7, -0x00000006,0x00003672,0x00005a8e,0x00000208, -0x000500aa,0x0000002f,0x00003673,0x00003672, -0x0000012b,0x000300f7,0x0000367e,0x00000000, -0x000400fa,0x00003673,0x00003674,0x0000367e, -0x000200f8,0x00003674,0x000300f7,0x00003b4f, -0x00000000,0x000400fa,0x00003ae2,0x00003b4a, -0x00003b4e,0x000200f8,0x00003b4e,0x000200f9, -0x00003b4f,0x000200f8,0x00003b4a,0x00050082, -0x00000006,0x00003b4d,0x00003a66,0x00000135, -0x000200f9,0x00003b4f,0x000200f8,0x00003b4f, -0x000700f5,0x00000006,0x00005a91,0x00003b4d, -0x00003b4a,0x0000012b,0x00003b4e,0x00050084, -0x00000006,0x00003b14,0x000000df,0x00005a91, -0x00050080,0x00000006,0x00003b15,0x00003a61, -0x00003b14,0x000300f7,0x00003b5c,0x00000000, -0x000400fa,0x00003ae2,0x00003b57,0x00003b5b, -0x000200f8,0x00003b5b,0x000200f9,0x00003b5c, -0x000200f8,0x00003b57,0x00050082,0x00000006, -0x00003b5a,0x00003a66,0x00000135,0x000200f9, -0x00003b5c,0x000200f8,0x00003b5c,0x000700f5, -0x00000006,0x00005a92,0x00003b5a,0x00003b57, -0x0000012b,0x00003b5b,0x00050084,0x00000006, -0x00003b0e,0x000000df,0x00005a92,0x00050080, -0x00000006,0x00003b0f,0x00003b15,0x00003b0e, -0x00050084,0x00000006,0x00003677,0x000000df, -0x00005a8e,0x00050080,0x00000006,0x00003678, -0x00003b0f,0x00003677,0x00050095,0x00000130, -0x00003b75,0x00003a9e,0x00003678,0x00050051, -0x00000006,0x00003b76,0x00003b75,0x00000001, -0x00050051,0x00000006,0x00003b77,0x00003b75, -0x00000000,0x00050080,0x00000006,0x00003b7c, -0x00003aa5,0x00003b76,0x00050050,0x00000007, -0x00003b7d,0x00003b77,0x00003b7c,0x0004007c, -0x00000014,0x00003b6d,0x00003b7d,0x00060041, -0x0000015f,0x00003b65,0x00003b6d,0x0000015e, -0x0000015e,0x0005003e,0x00003b65,0x000011de, -0x00000002,0x00000004,0x000200f9,0x0000367e, -0x000200f8,0x0000367e,0x000500c7,0x00000006, -0x00003680,0x00005a8f,0x00000208,0x000500aa, -0x0000002f,0x00003681,0x00003680,0x0000012b, -0x000300f7,0x0000368c,0x00000000,0x000400fa, -0x00003681,0x00003682,0x0000368c,0x000200f8, -0x00003682,0x000300f7,0x00003bc3,0x00000000, -0x000400fa,0x00003ae2,0x00003bbe,0x00003bc2, -0x000200f8,0x00003bc2,0x000200f9,0x00003bc3, -0x000200f8,0x00003bbe,0x00050082,0x00000006, -0x00003bc1,0x00003a66,0x00000135,0x000200f9, -0x00003bc3,0x000200f8,0x00003bc3,0x000700f5, -0x00000006,0x00005a93,0x00003bc1,0x00003bbe, -0x0000012b,0x00003bc2,0x00050084,0x00000006, -0x00003b88,0x000000df,0x00005a93,0x00050080, -0x00000006,0x00003b89,0x00003a61,0x00003b88, -0x000300f7,0x00003bd0,0x00000000,0x000400fa, -0x00003ae2,0x00003bcb,0x00003bcf,0x000200f8, -0x00003bcf,0x000200f9,0x00003bd0,0x000200f8, -0x00003bcb,0x00050082,0x00000006,0x00003bce, -0x00003a66,0x00000135,0x000200f9,0x00003bd0, -0x000200f8,0x00003bd0,0x000700f5,0x00000006, -0x00005a94,0x00003bce,0x00003bcb,0x0000012b, -0x00003bcf,0x00050084,0x00000006,0x00003b82, -0x000000df,0x00005a94,0x00050080,0x00000006, -0x00003b83,0x00003b89,0x00003b82,0x00050084, -0x00000006,0x00003685,0x000000df,0x00005a8f, -0x00050080,0x00000006,0x00003686,0x00003b83, -0x00003685,0x00050095,0x00000130,0x00003be9, -0x00003a9e,0x00003686,0x00050051,0x00000006, -0x00003bea,0x00003be9,0x00000001,0x00050051, -0x00000006,0x00003beb,0x00003be9,0x00000000, -0x00050080,0x00000006,0x00003bf0,0x00003aa5, -0x00003bea,0x00050050,0x00000007,0x00003bf1, -0x00003beb,0x00003bf0,0x0004007c,0x00000014, -0x00003be1,0x00003bf1,0x00060041,0x0000015f, -0x00003bd9,0x00003be1,0x0000015e,0x0000015e, -0x0005003e,0x00003bd9,0x000011de,0x00000002, -0x00000004,0x000200f9,0x0000368c,0x000200f8, -0x0000368c,0x000500aa,0x0000002f,0x0000368e, -0x000012dc,0x0000015e,0x000300f7,0x00003694, -0x00000000,0x000400fa,0x0000368e,0x0000368f, -0x00003694,0x000200f8,0x0000368f,0x000300f7, -0x00003c37,0x00000000,0x000400fa,0x00003ae2, -0x00003c32,0x00003c36,0x000200f8,0x00003c36, -0x000200f9,0x00003c37,0x000200f8,0x00003c32, -0x00050082,0x00000006,0x00003c35,0x00003a66, -0x00000135,0x000200f9,0x00003c37,0x000200f8, -0x00003c37,0x000700f5,0x00000006,0x00005a95, -0x00003c35,0x00003c32,0x0000012b,0x00003c36, -0x00050084,0x00000006,0x00003bfc,0x000000df, -0x00005a95,0x00050080,0x00000006,0x00003bfd, -0x00003a61,0x00003bfc,0x000300f7,0x00003c44, -0x00000000,0x000400fa,0x00003ae2,0x00003c3f, -0x00003c43,0x000200f8,0x00003c43,0x000200f9, -0x00003c44,0x000200f8,0x00003c3f,0x00050082, -0x00000006,0x00003c42,0x00003a66,0x00000135, -0x000200f9,0x00003c44,0x000200f8,0x00003c44, -0x000700f5,0x00000006,0x00005a96,0x00003c42, -0x00003c3f,0x0000012b,0x00003c43,0x00050084, -0x00000006,0x00003bf6,0x000000df,0x00005a96, -0x00050080,0x00000006,0x00003bf7,0x00003bfd, -0x00003bf6,0x00050095,0x00000130,0x00003c5d, -0x00003a9e,0x00003bf7,0x00050051,0x00000006, -0x00003c5e,0x00003c5d,0x00000001,0x00050051, -0x00000006,0x00003c5f,0x00003c5d,0x00000000, -0x00050080,0x00000006,0x00003c64,0x00003aa5, -0x00003c5e,0x00050050,0x00000007,0x00003c65, -0x00003c5f,0x00003c64,0x0004007c,0x00000014, -0x00003c55,0x00003c65,0x00060041,0x0000015f, -0x00003c4d,0x00003c55,0x0000015e,0x0000015e, -0x0005003e,0x00003c4d,0x00000500,0x00000002, -0x00000004,0x000200f9,0x00003694,0x000200f8, -0x00003694,0x000200f9,0x000012da,0x000200f8, -0x000012da,0x000200f9,0x000012d1,0x000200f8, -0x000012d0,0x00050041,0x00000182,0x000033ba, -0x00000180,0x00000181,0x0004003d,0x00000006, -0x000033bb,0x000033ba,0x00050084,0x00000006, -0x000033bc,0x000001a2,0x000033bb,0x00050080, -0x00000006,0x000033bd,0x0000018b,0x000033bc, -0x00050080,0x00000006,0x000033c3,0x000033bb, -0x00005cc3,0x00050086,0x00000006,0x000033c4, -0x000033c3,0x00000185,0x00050084,0x00000006, -0x000033b6,0x0000018b,0x000033c4,0x00050080, -0x00000006,0x000033b7,0x000033bd,0x000033b6, -0x00050080,0x00000006,0x000033b1,0x000033b7, -0x000033b6,0x00050084,0x00000006,0x00003385, -0x000001b6,0x000011de,0x00050080,0x00000006, -0x00003386,0x000033b1,0x00003385,0x00050041, -0x0000022d,0x00003387,0x00000180,0x0000022b, -0x0004003d,0x00000007,0x00003388,0x00003387, -0x00050051,0x00000006,0x000033e2,0x00003388, -0x00000000,0x00050095,0x00000130,0x000033e4, -0x000033e2,0x00003386,0x00050051,0x00000006, -0x000033e5,0x000033e4,0x00000001,0x00050051, -0x00000006,0x000033e6,0x000033e4,0x00000000, -0x00050051,0x00000006,0x000033e9,0x00003388, -0x00000001,0x00050080,0x00000006,0x000033eb, -0x000033e9,0x000033e5,0x00050050,0x00000007, -0x000033ec,0x000033e6,0x000033eb,0x0004007c, -0x00000014,0x000033dc,0x000033ec,0x00060041, -0x0000015f,0x000033d3,0x000033dc,0x0000015e, -0x0000015e,0x0006003d,0x00000006,0x000033d4, -0x000033d3,0x00000002,0x00000004,0x0004007c, -0x00000027,0x0000338b,0x000033d4,0x00050080, -0x00000006,0x0000338d,0x00003386,0x000000df, -0x00050095,0x00000130,0x00003405,0x000033e2, -0x0000338d,0x00050051,0x00000006,0x00003406, -0x00003405,0x00000001,0x00050051,0x00000006, -0x00003407,0x00003405,0x00000000,0x00050080, -0x00000006,0x0000340c,0x000033e9,0x00003406, -0x00050050,0x00000007,0x0000340d,0x00003407, -0x0000340c,0x0004007c,0x00000014,0x000033fd, -0x0000340d,0x00060041,0x0000015f,0x000033f4, -0x000033fd,0x0000015e,0x0000015e,0x0006003d, -0x00000006,0x000033f5,0x000033f4,0x00000002, -0x00000004,0x0004007c,0x00000027,0x00003391, -0x000033f5,0x00050080,0x00000006,0x00003393, -0x00003386,0x00000194,0x00050095,0x00000130, -0x00003426,0x000033e2,0x00003393,0x00050051, -0x00000006,0x00003427,0x00003426,0x00000001, -0x00050051,0x00000006,0x00003428,0x00003426, -0x00000000,0x00050080,0x00000006,0x0000342d, -0x000033e9,0x00003427,0x00050050,0x00000007, -0x0000342e,0x00003428,0x0000342d,0x0004007c, -0x00000014,0x0000341e,0x0000342e,0x00060041, -0x0000015f,0x00003415,0x0000341e,0x0000015e, -0x0000015e,0x0006003d,0x00000006,0x00003416, -0x00003415,0x00000002,0x00000004,0x0004007c, -0x00000027,0x00003397,0x00003416,0x00060050, -0x00000063,0x00003398,0x0000338b,0x00003391, -0x00003397,0x00050080,0x00000006,0x0000339a, -0x00003386,0x0000019b,0x00050095,0x00000130, -0x00003447,0x000033e2,0x0000339a,0x00050051, -0x00000006,0x00003448,0x00003447,0x00000001, -0x00050051,0x00000006,0x00003449,0x00003447, -0x00000000,0x00050080,0x00000006,0x0000344e, -0x000033e9,0x00003448,0x00050050,0x00000007, -0x0000344f,0x00003449,0x0000344e,0x0004007c, -0x00000014,0x0000343f,0x0000344f,0x00060041, -0x0000015f,0x00003436,0x0000343f,0x0000015e, -0x0000015e,0x0006003d,0x00000006,0x00003437, -0x00003436,0x00000002,0x00000004,0x0004007c, -0x00000027,0x0000339e,0x00003437,0x00050080, -0x00000006,0x000033a0,0x00003386,0x000001a2, -0x00050095,0x00000130,0x00003468,0x000033e2, -0x000033a0,0x00050051,0x00000006,0x00003469, -0x00003468,0x00000001,0x00050051,0x00000006, -0x0000346a,0x00003468,0x00000000,0x00050080, -0x00000006,0x0000346f,0x000033e9,0x00003469, -0x00050050,0x00000007,0x00003470,0x0000346a, -0x0000346f,0x0004007c,0x00000014,0x00003460, -0x00003470,0x00060041,0x0000015f,0x00003457, -0x00003460,0x0000015e,0x0000015e,0x0006003d, -0x00000006,0x00003458,0x00003457,0x00000002, -0x00000004,0x0004007c,0x00000027,0x000033a4, -0x00003458,0x00050080,0x00000006,0x000033a6, -0x00003386,0x00000260,0x00050095,0x00000130, -0x00003489,0x000033e2,0x000033a6,0x00050051, -0x00000006,0x0000348a,0x00003489,0x00000001, -0x00050051,0x00000006,0x0000348b,0x00003489, -0x00000000,0x00050080,0x00000006,0x00003490, -0x000033e9,0x0000348a,0x00050050,0x00000007, -0x00003491,0x0000348b,0x00003490,0x0004007c, -0x00000014,0x00003481,0x00003491,0x00060041, -0x0000015f,0x00003478,0x00003481,0x0000015e, -0x0000015e,0x0006003d,0x00000006,0x00003479, -0x00003478,0x00000002,0x00000004,0x0004007c, -0x00000027,0x000033aa,0x00003479,0x00060050, -0x00000063,0x000033ab,0x0000339e,0x000033a4, -0x000033aa,0x000500bc,0x0000002f,0x00003498, -0x0000338b,0x0000339e,0x000300f7,0x0000349f, -0x00000000,0x000400fa,0x00003498,0x00003499, -0x0000349f,0x000200f8,0x00003499,0x000500bc, -0x0000002f,0x0000349e,0x00003391,0x000033a4, -0x000200f9,0x0000349f,0x000200f8,0x0000349f, -0x000700f5,0x0000002f,0x000034a0,0x00003498, -0x000012d0,0x0000349e,0x00003499,0x000300f7, -0x000034a7,0x00000000,0x000400fa,0x000034a0, -0x000034a1,0x000034a7,0x000200f8,0x000034a1, -0x000500bc,0x0000002f,0x000034a6,0x00003397, -0x000033aa,0x000200f9,0x000034a7,0x000200f8, -0x000034a7,0x000700f5,0x0000002f,0x000034a8, -0x000034a0,0x0000349f,0x000034a6,0x000034a1, -0x000300f7,0x00003364,0x00000000,0x000400fa, -0x000034a8,0x00003328,0x00003364,0x000200f8, -0x00003328,0x00050095,0x00000130,0x000034b9, -0x000033e2,0x0000012b,0x00050051,0x00000006, -0x000034ba,0x000034b9,0x00000001,0x00050051, -0x00000006,0x000034bb,0x000034b9,0x00000000, -0x00050080,0x00000006,0x000034c0,0x000033e9, -0x000034ba,0x00050050,0x00000007,0x000034c1, -0x000034bb,0x000034c0,0x0004007c,0x00000014, -0x000034b1,0x000034c1,0x00060041,0x0000015f, -0x0000332d,0x000034b1,0x0000015e,0x0000015e, -0x0006003d,0x00000006,0x0000332e,0x0000332d, -0x00000002,0x00000004,0x000500c7,0x00000006, -0x000034c6,0x0000332e,0x00000208,0x000500ab, -0x0000002f,0x000034c7,0x000034c6,0x0000012b, -0x000300f7,0x000034ce,0x00000000,0x000400fa, -0x000034c7,0x000034c8,0x000034cb,0x000200f8, -0x000034cb,0x000400c8,0x00000006,0x000034cd, -0x0000332e,0x000200f9,0x000034ce,0x000200f8, -0x000034c8,0x000500c7,0x00000006,0x000034ca, -0x0000332e,0x0000021d,0x000200f9,0x000034ce, -0x000200f8,0x000034ce,0x000700f5,0x00000006, -0x00005a9d,0x000034ca,0x000034c8,0x000034cd, -0x000034cb,0x0004007c,0x00000027,0x000034d0, -0x00005a9d,0x00060041,0x0000015f,0x00003331, -0x000034b1,0x0000015e,0x0000022b,0x0006003d, -0x00000006,0x00003332,0x00003331,0x00000002, -0x00000004,0x000500c7,0x00000006,0x000034d5, -0x00003332,0x00000208,0x000500ab,0x0000002f, -0x000034d6,0x000034d5,0x0000012b,0x000300f7, -0x000034dd,0x00000000,0x000400fa,0x000034d6, -0x000034d7,0x000034da,0x000200f8,0x000034da, -0x000400c8,0x00000006,0x000034dc,0x00003332, -0x000200f9,0x000034dd,0x000200f8,0x000034d7, -0x000500c7,0x00000006,0x000034d9,0x00003332, -0x0000021d,0x000200f9,0x000034dd,0x000200f8, -0x000034dd,0x000700f5,0x00000006,0x00005a9e, -0x000034d9,0x000034d7,0x000034dc,0x000034da, -0x0004007c,0x00000027,0x000034df,0x00005a9e, -0x00060041,0x0000015f,0x00003335,0x000034b1, -0x0000015e,0x000002dc,0x0006003d,0x00000006, -0x00003336,0x00003335,0x00000002,0x00000004, -0x000500c7,0x00000006,0x000034e4,0x00003336, -0x00000208,0x000500ab,0x0000002f,0x000034e5, -0x000034e4,0x0000012b,0x000300f7,0x000034ec, -0x00000000,0x000400fa,0x000034e5,0x000034e6, -0x000034e9,0x000200f8,0x000034e9,0x000400c8, -0x00000006,0x000034eb,0x00003336,0x000200f9, -0x000034ec,0x000200f8,0x000034e6,0x000500c7, -0x00000006,0x000034e8,0x00003336,0x0000021d, -0x000200f9,0x000034ec,0x000200f8,0x000034ec, -0x000700f5,0x00000006,0x00005a9f,0x000034e8, -0x000034e6,0x000034eb,0x000034e9,0x0004007c, -0x00000027,0x000034ee,0x00005a9f,0x00060050, -0x00000063,0x00003338,0x000034d0,0x000034df, -0x000034ee,0x00060041,0x0000015f,0x0000333a, -0x000034b1,0x0000015e,0x000002e4,0x0006003d, -0x00000006,0x0000333b,0x0000333a,0x00000002, -0x00000004,0x000500c7,0x00000006,0x000034f3, -0x0000333b,0x00000208,0x000500ab,0x0000002f, -0x000034f4,0x000034f3,0x0000012b,0x000300f7, -0x000034fb,0x00000000,0x000400fa,0x000034f4, -0x000034f5,0x000034f8,0x000200f8,0x000034f8, -0x000400c8,0x00000006,0x000034fa,0x0000333b, -0x000200f9,0x000034fb,0x000200f8,0x000034f5, -0x000500c7,0x00000006,0x000034f7,0x0000333b, -0x0000021d,0x000200f9,0x000034fb,0x000200f8, -0x000034fb,0x000700f5,0x00000006,0x00005aa0, -0x000034f7,0x000034f5,0x000034fa,0x000034f8, -0x0004007c,0x00000027,0x000034fd,0x00005aa0, -0x00060041,0x0000015f,0x0000333e,0x000034b1, -0x0000015e,0x000002ec,0x0006003d,0x00000006, -0x0000333f,0x0000333e,0x00000002,0x00000004, -0x000500c7,0x00000006,0x00003502,0x0000333f, -0x00000208,0x000500ab,0x0000002f,0x00003503, -0x00003502,0x0000012b,0x000300f7,0x0000350a, -0x00000000,0x000400fa,0x00003503,0x00003504, -0x00003507,0x000200f8,0x00003507,0x000400c8, -0x00000006,0x00003509,0x0000333f,0x000200f9, -0x0000350a,0x000200f8,0x00003504,0x000500c7, -0x00000006,0x00003506,0x0000333f,0x0000021d, -0x000200f9,0x0000350a,0x000200f8,0x0000350a, -0x000700f5,0x00000006,0x00005aa1,0x00003506, -0x00003504,0x00003509,0x00003507,0x0004007c, -0x00000027,0x0000350c,0x00005aa1,0x00060041, -0x0000015f,0x00003342,0x000034b1,0x0000015e, -0x000002f4,0x0006003d,0x00000006,0x00003343, -0x00003342,0x00000002,0x00000004,0x000500c7, -0x00000006,0x00003511,0x00003343,0x00000208, -0x000500ab,0x0000002f,0x00003512,0x00003511, -0x0000012b,0x000300f7,0x00003519,0x00000000, -0x000400fa,0x00003512,0x00003513,0x00003516, -0x000200f8,0x00003516,0x000400c8,0x00000006, -0x00003518,0x00003343,0x000200f9,0x00003519, -0x000200f8,0x00003513,0x000500c7,0x00000006, -0x00003515,0x00003343,0x0000021d,0x000200f9, -0x00003519,0x000200f8,0x00003519,0x000700f5, -0x00000006,0x00005aa2,0x00003515,0x00003513, -0x00003518,0x00003516,0x0004007c,0x00000027, -0x0000351b,0x00005aa2,0x00060050,0x00000063, -0x00003345,0x000034fd,0x0000350c,0x0000351b, -0x00050083,0x00000063,0x00003348,0x00003345, -0x00003338,0x0007000c,0x00000063,0x00003349, -0x00000001,0x00000028,0x00003348,0x000007d4, -0x00050081,0x00000063,0x0000334c,0x00003398, -0x000033ab,0x0005008e,0x00000063,0x0000334d, -0x0000334c,0x000002c4,0x00050083,0x00000063, -0x0000334f,0x0000334d,0x00003338,0x00050088, -0x00000063,0x00003351,0x0000334f,0x00003349, -0x0008000c,0x00000063,0x00003354,0x00000001, -0x0000002b,0x00003351,0x000006eb,0x00005cc0, -0x0005008e,0x00000063,0x00003355,0x00003354, -0x000007e2,0x0004006d,0x000000d2,0x00003356, -0x00003355,0x00050051,0x00000006,0x00003358, -0x00003356,0x00000000,0x000500c7,0x00000006, -0x0000351f,0x00003358,0x00000777,0x000500c4, -0x00000006,0x00003522,0x0000351f,0x00000321, -0x000500c5,0x00000006,0x00003523,0x0000351f, -0x00003522,0x000500c7,0x00000006,0x00003524, -0x00003523,0x0000077e,0x000500c4,0x00000006, -0x00003527,0x00003524,0x00000488,0x000500c5, -0x00000006,0x00003528,0x00003524,0x00003527, -0x000500c7,0x00000006,0x00003529,0x00003528, -0x00000784,0x000500c4,0x00000006,0x0000352c, -0x00003529,0x000002ec,0x000500c5,0x00000006, -0x0000352d,0x00003529,0x0000352c,0x000500c7, -0x00000006,0x0000352e,0x0000352d,0x0000078a, -0x000500c4,0x00000006,0x00003531,0x0000352e, -0x000002dc,0x000500c5,0x00000006,0x00003532, -0x0000352e,0x00003531,0x000500c7,0x00000006, -0x00003533,0x00003532,0x00000790,0x000500c4, -0x00000006,0x0000335a,0x00003533,0x000002dc, -0x00050051,0x00000006,0x0000335c,0x00003356, -0x00000001,0x000500c7,0x00000006,0x00003538, -0x0000335c,0x00000777,0x000500c4,0x00000006, -0x0000353b,0x00003538,0x00000321,0x000500c5, -0x00000006,0x0000353c,0x00003538,0x0000353b, -0x000500c7,0x00000006,0x0000353d,0x0000353c, -0x0000077e,0x000500c4,0x00000006,0x00003540, -0x0000353d,0x00000488,0x000500c5,0x00000006, -0x00003541,0x0000353d,0x00003540,0x000500c7, -0x00000006,0x00003542,0x00003541,0x00000784, -0x000500c4,0x00000006,0x00003545,0x00003542, -0x000002ec,0x000500c5,0x00000006,0x00003546, -0x00003542,0x00003545,0x000500c7,0x00000006, -0x00003547,0x00003546,0x0000078a,0x000500c4, -0x00000006,0x0000354a,0x00003547,0x000002dc, -0x000500c5,0x00000006,0x0000354b,0x00003547, -0x0000354a,0x000500c7,0x00000006,0x0000354c, -0x0000354b,0x00000790,0x000500c4,0x00000006, -0x0000335e,0x0000354c,0x0000022b,0x000500c5, -0x00000006,0x0000335f,0x0000335a,0x0000335e, -0x00050051,0x00000006,0x00003361,0x00003356, -0x00000002,0x000500c7,0x00000006,0x00003551, -0x00003361,0x00000777,0x000500c4,0x00000006, -0x00003554,0x00003551,0x00000321,0x000500c5, -0x00000006,0x00003555,0x00003551,0x00003554, -0x000500c7,0x00000006,0x00003556,0x00003555, -0x0000077e,0x000500c4,0x00000006,0x00003559, -0x00003556,0x00000488,0x000500c5,0x00000006, -0x0000355a,0x00003556,0x00003559,0x000500c7, -0x00000006,0x0000355b,0x0000355a,0x00000784, -0x000500c4,0x00000006,0x0000355e,0x0000355b, -0x000002ec,0x000500c5,0x00000006,0x0000355f, -0x0000355b,0x0000355e,0x000500c7,0x00000006, -0x00003560,0x0000355f,0x0000078a,0x000500c4, -0x00000006,0x00003563,0x00003560,0x000002dc, -0x000500c5,0x00000006,0x00003564,0x00003560, -0x00003563,0x000500c7,0x00000006,0x00003565, -0x00003564,0x00000790,0x000500c5,0x00000006, -0x00003363,0x0000335f,0x00003565,0x000200f9, -0x00003364,0x000200f8,0x00003364,0x000700f5, -0x00000006,0x00005aa3,0x000006ac,0x000034a7, -0x00003363,0x00003519,0x00050084,0x00000006, -0x00003367,0x000000df,0x000011de,0x00050080, -0x00000006,0x00003368,0x0000018b,0x00003367, -0x00050095,0x00000130,0x00003580,0x000033e2, -0x00003368,0x00050051,0x00000006,0x00003581, -0x00003580,0x00000001,0x00050051,0x00000006, -0x00003582,0x00003580,0x00000000,0x00050080, -0x00000006,0x00003587,0x000033e9,0x00003581, -0x00050050,0x00000007,0x00003588,0x00003582, -0x00003587,0x0004007c,0x00000014,0x00003578, -0x00003588,0x00060041,0x0000015f,0x00003570, -0x00003578,0x0000015e,0x0000015e,0x0005003e, -0x00003570,0x00005aa3,0x00000002,0x00000004, -0x00050084,0x00000006,0x0000358d,0x000000df, -0x000033bb,0x00050080,0x00000006,0x0000358e, -0x0000018b,0x0000358d,0x00050080,0x00000006, -0x00003370,0x0000358e,0x00003367,0x00050095, -0x00000130,0x000035a6,0x000033e2,0x00003370, -0x00050051,0x00000006,0x000035a7,0x000035a6, -0x00000001,0x00050051,0x00000006,0x000035a8, -0x000035a6,0x00000000,0x00050080,0x00000006, -0x000035ad,0x000033e9,0x000035a7,0x00050050, -0x00000007,0x000035ae,0x000035a8,0x000035ad, -0x0004007c,0x00000014,0x0000359e,0x000035ae, -0x00060041,0x0000015f,0x00003596,0x0000359e, -0x0000015e,0x0000015e,0x0005003e,0x00003596, -0x000011de,0x00000002,0x00000004,0x000200f9, -0x000012d1,0x000200f8,0x000012d1,0x000200f9, -0x000012c8,0x000200f8,0x000012c7,0x00050084, -0x00000006,0x00002b91,0x0000018b,0x000011de, -0x000200f9,0x00002b92,0x000200f8,0x00002b92, -0x000700f5,0x00000006,0x00005aa6,0x0000012b, -0x000012c7,0x00002ba3,0x00002b96,0x000500b0, -0x0000002f,0x00002b95,0x00005aa6,0x0000019b, -0x000400f6,0x00002ba4,0x00002b96,0x00000000, -0x000400fa,0x00002b95,0x00002b96,0x00002ba4, -0x000200f8,0x00002b96,0x00050084,0x00000006, -0x00002b9a,0x000000df,0x00005aa6,0x00050080, -0x00000006,0x00002b9b,0x00002b91,0x00002b9a, -0x00050041,0x0000022d,0x00002b9c,0x00000180, -0x000002dc,0x0004003d,0x00000007,0x00002b9d, -0x00002b9c,0x00050051,0x00000006,0x00002d5a, -0x00002b9d,0x00000000,0x00050095,0x00000130, -0x00002d5c,0x00002d5a,0x00002b9b,0x00050051, -0x00000006,0x00002d5d,0x00002d5c,0x00000001, -0x00050051,0x00000006,0x00002d5e,0x00002d5c, -0x00000000,0x00050051,0x00000006,0x00002d61, -0x00002b9d,0x00000001,0x00050080,0x00000006, -0x00002d63,0x00002d61,0x00002d5d,0x00050050, -0x00000007,0x00002d64,0x00002d5e,0x00002d63, -0x0004007c,0x00000014,0x00002d54,0x00002d64, -0x00060041,0x0000015f,0x00002d4b,0x00002d54, -0x0000015e,0x0000015e,0x0006003d,0x00000006, -0x00002d4c,0x00002d4b,0x00000002,0x00000004, -0x0004007c,0x00000027,0x00002b9f,0x00002d4c, -0x00050041,0x00000028,0x00002ba0,0x00002b2c, -0x00005aa6,0x0003003e,0x00002ba0,0x00002b9f, -0x00050080,0x00000006,0x00002ba3,0x00005aa6, -0x0000022b,0x000200f9,0x00002b92,0x000200f8, -0x00002ba4,0x00050080,0x00000006,0x00002ba6, -0x00002b91,0x000004e8,0x00050041,0x0000022d, -0x00002ba7,0x00000180,0x000002dc,0x0004003d, -0x00000007,0x00002ba8,0x00002ba7,0x00050051, -0x00000006,0x00002d7b,0x00002ba8,0x00000000, -0x00050095,0x00000130,0x00002d7d,0x00002d7b, -0x00002ba6,0x00050051,0x00000006,0x00002d7e, -0x00002d7d,0x00000001,0x00050051,0x00000006, -0x00002d7f,0x00002d7d,0x00000000,0x00050051, -0x00000006,0x00002d82,0x00002ba8,0x00000001, -0x00050080,0x00000006,0x00002d84,0x00002d82, -0x00002d7e,0x00050050,0x00000007,0x00002d85, -0x00002d7f,0x00002d84,0x0004007c,0x00000014, -0x00002d75,0x00002d85,0x00060041,0x0000015f, -0x00002d6c,0x00002d75,0x0000015e,0x0000015e, -0x0006003d,0x00000006,0x00002d6d,0x00002d6c, -0x00000002,0x00000004,0x00050080,0x00000006, -0x00002bab,0x00002b91,0x000004f4,0x00050095, -0x00000130,0x00002d9e,0x00002d7b,0x00002bab, -0x00050051,0x00000006,0x00002d9f,0x00002d9e, -0x00000001,0x00050051,0x00000006,0x00002da0, -0x00002d9e,0x00000000,0x00050080,0x00000006, -0x00002da5,0x00002d82,0x00002d9f,0x00050050, -0x00000007,0x00002da6,0x00002da0,0x00002da5, -0x0004007c,0x00000014,0x00002d96,0x00002da6, -0x00060041,0x0000015f,0x00002d8d,0x00002d96, -0x0000015e,0x0000015e,0x0006003d,0x00000006, -0x00002d8e,0x00002d8d,0x00000002,0x00000004, -0x00050080,0x00000006,0x00002bb0,0x00002b91, -0x000004fe,0x00050095,0x00000130,0x00002dbf, -0x00002d7b,0x00002bb0,0x00050051,0x00000006, -0x00002dc0,0x00002dbf,0x00000001,0x00050051, -0x00000006,0x00002dc1,0x00002dbf,0x00000000, -0x00050080,0x00000006,0x00002dc6,0x00002d82, -0x00002dc0,0x00050050,0x00000007,0x00002dc7, -0x00002dc1,0x00002dc6,0x0004007c,0x00000014, -0x00002db7,0x00002dc7,0x00060041,0x0000015f, -0x00002dae,0x00002db7,0x0000015e,0x0000015e, -0x0006003d,0x00000006,0x00002daf,0x00002dae, -0x00000002,0x00000004,0x00050080,0x00000006, -0x00002bb5,0x00002b91,0x00000508,0x00050095, -0x00000130,0x00002de0,0x00002d7b,0x00002bb5, -0x00050051,0x00000006,0x00002de1,0x00002de0, -0x00000001,0x00050051,0x00000006,0x00002de2, -0x00002de0,0x00000000,0x00050080,0x00000006, -0x00002de7,0x00002d82,0x00002de1,0x00050050, -0x00000007,0x00002de8,0x00002de2,0x00002de7, -0x0004007c,0x00000014,0x00002dd8,0x00002de8, -0x00060041,0x0000015f,0x00002dcf,0x00002dd8, -0x0000015e,0x0000015e,0x0006003d,0x00000006, -0x00002dd0,0x00002dcf,0x00000002,0x00000004, -0x00050041,0x00000182,0x00002bba,0x00000180, -0x00000311,0x0004003d,0x00000006,0x00002bbb, -0x00002bba,0x00050084,0x00000006,0x00002bbd, -0x00000309,0x000011de,0x00050080,0x00000006, -0x00002bbe,0x00002bbb,0x00002bbd,0x000200f9, -0x00002bbf,0x000200f8,0x00002bbf,0x000700f5, -0x00000006,0x00005aa7,0x0000012b,0x00002ba4, -0x00002bd0,0x00002bc3,0x000500b0,0x0000002f, -0x00002bc2,0x00005aa7,0x0000019b,0x000400f6, -0x00002bd1,0x00002bc3,0x00000000,0x000400fa, -0x00002bc2,0x00002bc3,0x00002bd1,0x000200f8, -0x00002bc3,0x00050084,0x00000006,0x00002bc6, -0x000000df,0x00005aa7,0x00050080,0x00000006, -0x00002bc7,0x00002bbe,0x00002bc6,0x00050041, -0x0000022d,0x00002bc9,0x00000180,0x0000015e, -0x0004003d,0x00000007,0x00002bca,0x00002bc9, -0x00050041,0x00000028,0x00002bcb,0x00002b2c, -0x00005aa7,0x0004003d,0x00000027,0x00002bcc, -0x00002bcb,0x0004007c,0x00000006,0x00002dee, -0x00002bcc,0x00050051,0x00000006,0x00002e07, -0x00002bca,0x00000000,0x00050095,0x00000130, -0x00002e09,0x00002e07,0x00002bc7,0x00050051, -0x00000006,0x00002e0a,0x00002e09,0x00000001, -0x00050051,0x00000006,0x00002e0b,0x00002e09, -0x00000000,0x00050051,0x00000006,0x00002e0e, -0x00002bca,0x00000001,0x00050080,0x00000006, -0x00002e10,0x00002e0e,0x00002e0a,0x00050050, -0x00000007,0x00002e11,0x00002e0b,0x00002e10, -0x0004007c,0x00000014,0x00002e01,0x00002e11, -0x00060041,0x0000015f,0x00002df9,0x00002e01, -0x0000015e,0x0000015e,0x0005003e,0x00002df9, -0x00002dee,0x00000002,0x00000004,0x00050080, -0x00000006,0x00002bd0,0x00005aa7,0x0000022b, -0x000200f9,0x00002bbf,0x000200f8,0x00002bd1, -0x00050080,0x00000006,0x00002bd3,0x00002bbe, -0x000004e8,0x00050041,0x0000022d,0x00002bd4, -0x00000180,0x0000015e,0x0004003d,0x00000007, -0x00002bd5,0x00002bd4,0x00050051,0x00000006, -0x00002e27,0x00002bd5,0x00000000,0x00050095, -0x00000130,0x00002e29,0x00002e27,0x00002bd3, -0x00050051,0x00000006,0x00002e2a,0x00002e29, -0x00000001,0x00050051,0x00000006,0x00002e2b, -0x00002e29,0x00000000,0x00050051,0x00000006, -0x00002e2e,0x00002bd5,0x00000001,0x00050080, -0x00000006,0x00002e30,0x00002e2e,0x00002e2a, -0x00050050,0x00000007,0x00002e31,0x00002e2b, -0x00002e30,0x0004007c,0x00000014,0x00002e21, -0x00002e31,0x00060041,0x0000015f,0x00002e19, -0x00002e21,0x0000015e,0x0000015e,0x0005003e, -0x00002e19,0x00002d6d,0x00000002,0x00000004, -0x00050080,0x00000006,0x00002bd9,0x00002bbe, -0x000004f4,0x00050095,0x00000130,0x00002e49, -0x00002e27,0x00002bd9,0x00050051,0x00000006, -0x00002e4a,0x00002e49,0x00000001,0x00050051, -0x00000006,0x00002e4b,0x00002e49,0x00000000, -0x00050080,0x00000006,0x00002e50,0x00002e2e, -0x00002e4a,0x00050050,0x00000007,0x00002e51, -0x00002e4b,0x00002e50,0x0004007c,0x00000014, -0x00002e41,0x00002e51,0x00060041,0x0000015f, -0x00002e39,0x00002e41,0x0000015e,0x0000015e, -0x0005003e,0x00002e39,0x00002d8e,0x00000002, -0x00000004,0x000500aa,0x0000002f,0x00002e56, -0x00002daf,0x0000012b,0x000300f7,0x00002e5b, -0x00000000,0x000400fa,0x00002e56,0x00002e57, -0x00002e5b,0x000200f8,0x00002e57,0x000500aa, -0x0000002f,0x00002e5a,0x00002dd0,0x0000012b, -0x000200f9,0x00002e5b,0x000200f8,0x00002e5b, -0x000700f5,0x0000002f,0x00002e5c,0x00002e56, -0x00002bd1,0x00002e5a,0x00002e57,0x000400a8, -0x0000002f,0x00002be2,0x00002e5c,0x000300f7, -0x00002c78,0x00000000,0x000400fa,0x00002be2, -0x00002be3,0x00002c78,0x000200f8,0x00002be3, -0x00050041,0x0000022d,0x00002be5,0x00000180, -0x000002f4,0x0004003d,0x00000007,0x00002be6, -0x00002be5,0x00050051,0x00000006,0x00002e64, -0x00002be6,0x00000000,0x00050095,0x00000130, -0x00002e65,0x00002daf,0x00002e64,0x00050051, -0x00000006,0x00002e66,0x00002e65,0x00000001, -0x00050051,0x00000006,0x00002e67,0x00002e65, -0x00000000,0x00050051,0x00000006,0x00002e6c, -0x00002be6,0x00000001,0x00050080,0x00000006, -0x00002e6d,0x00002dd0,0x00002e6c,0x00050080, -0x00000006,0x00002e6f,0x00002e6d,0x00002e66, -0x00050095,0x00000130,0x00002e89,0x00002e67, -0x000004e8,0x00050051,0x00000006,0x00002e8a, -0x00002e89,0x00000001,0x00050051,0x00000006, -0x00002e8b,0x00002e89,0x00000000,0x00050080, -0x00000006,0x00002e90,0x00002e6f,0x00002e8a, -0x00050050,0x00000007,0x00002e91,0x00002e8b, -0x00002e90,0x0004007c,0x00000014,0x00002e81, -0x00002e91,0x00060041,0x0000015f,0x00002e78, -0x00002e81,0x0000015e,0x0000015e,0x0006003d, -0x00000006,0x00002e79,0x00002e78,0x00000002, -0x00000004,0x00050095,0x00000130,0x00002eaa, -0x00002e67,0x000001a2,0x00050051,0x00000006, -0x00002eab,0x00002eaa,0x00000001,0x00050051, -0x00000006,0x00002eac,0x00002eaa,0x00000000, -0x00050080,0x00000006,0x00002eb1,0x00002e6f, -0x00002eab,0x00050050,0x00000007,0x00002eb2, -0x00002eac,0x00002eb1,0x0004007c,0x00000014, -0x00002ea2,0x00002eb2,0x00060041,0x0000015f, -0x00002e99,0x00002ea2,0x0000015e,0x0000015e, -0x0006003d,0x00000006,0x00002e9a,0x00002e99, -0x00000002,0x00000004,0x0004007c,0x00000027, -0x00002bec,0x00002e9a,0x00050095,0x00000130, -0x00002ecb,0x00002e67,0x00000260,0x00050051, -0x00000006,0x00002ecc,0x00002ecb,0x00000001, -0x00050051,0x00000006,0x00002ecd,0x00002ecb, -0x00000000,0x00050080,0x00000006,0x00002ed2, -0x00002e6f,0x00002ecc,0x00050050,0x00000007, -0x00002ed3,0x00002ecd,0x00002ed2,0x0004007c, -0x00000014,0x00002ec3,0x00002ed3,0x00060041, -0x0000015f,0x00002eba,0x00002ec3,0x0000015e, -0x0000015e,0x0006003d,0x00000006,0x00002ebb, -0x00002eba,0x00000002,0x00000004,0x0004007c, -0x00000027,0x00002bef,0x00002ebb,0x00050095, -0x00000130,0x00002eec,0x00002e67,0x000001b6, -0x00050051,0x00000006,0x00002eed,0x00002eec, -0x00000001,0x00050051,0x00000006,0x00002eee, -0x00002eec,0x00000000,0x00050080,0x00000006, -0x00002ef3,0x00002e6f,0x00002eed,0x00050050, -0x00000007,0x00002ef4,0x00002eee,0x00002ef3, -0x0004007c,0x00000014,0x00002ee4,0x00002ef4, -0x00060041,0x0000015f,0x00002edb,0x00002ee4, -0x0000015e,0x0000015e,0x0006003d,0x00000006, -0x00002edc,0x00002edb,0x00000002,0x00000004, -0x0004007c,0x00000027,0x00002bf2,0x00002edc, -0x00050095,0x00000130,0x00002f0d,0x00002e67, -0x000005df,0x00050051,0x00000006,0x00002f0e, -0x00002f0d,0x00000001,0x00050051,0x00000006, -0x00002f0f,0x00002f0d,0x00000000,0x00050080, -0x00000006,0x00002f14,0x00002e6f,0x00002f0e, -0x00050050,0x00000007,0x00002f15,0x00002f0f, -0x00002f14,0x0004007c,0x00000014,0x00002f05, -0x00002f15,0x00060041,0x0000015f,0x00002efc, -0x00002f05,0x0000015e,0x0000015e,0x0006003d, -0x00000006,0x00002efd,0x00002efc,0x00000002, -0x00000004,0x0004007c,0x00000027,0x00002bf6, -0x00002efd,0x00050095,0x00000130,0x00002f2e, -0x00002e67,0x000001cc,0x00050051,0x00000006, -0x00002f2f,0x00002f2e,0x00000001,0x00050051, -0x00000006,0x00002f30,0x00002f2e,0x00000000, -0x00050080,0x00000006,0x00002f35,0x00002e6f, -0x00002f2f,0x00050050,0x00000007,0x00002f36, -0x00002f30,0x00002f35,0x0004007c,0x00000014, -0x00002f26,0x00002f36,0x00060041,0x0000015f, -0x00002f1d,0x00002f26,0x0000015e,0x0000015e, -0x0006003d,0x00000006,0x00002f1e,0x00002f1d, -0x00000002,0x00000004,0x0004007c,0x00000027, -0x00002bf9,0x00002f1e,0x00050095,0x00000130, -0x00002f4f,0x00002e67,0x000004c7,0x00050051, -0x00000006,0x00002f50,0x00002f4f,0x00000001, -0x00050051,0x00000006,0x00002f51,0x00002f4f, -0x00000000,0x00050080,0x00000006,0x00002f56, -0x00002e6f,0x00002f50,0x00050050,0x00000007, -0x00002f57,0x00002f51,0x00002f56,0x0004007c, -0x00000014,0x00002f47,0x00002f57,0x00060041, -0x0000015f,0x00002f3e,0x00002f47,0x0000015e, -0x0000015e,0x0006003d,0x00000006,0x00002f3f, -0x00002f3e,0x00000002,0x00000004,0x0004007c, -0x00000027,0x00002bfc,0x00002f3f,0x000500bc, -0x0000002f,0x00002f5e,0x00002bec,0x00002bf6, -0x000300f7,0x00002f65,0x00000000,0x000400fa, -0x00002f5e,0x00002f5f,0x00002f65,0x000200f8, -0x00002f5f,0x000500bc,0x0000002f,0x00002f64, -0x00002bef,0x00002bf9,0x000200f9,0x00002f65, -0x000200f8,0x00002f65,0x000700f5,0x0000002f, -0x00002f66,0x00002f5e,0x00002be3,0x00002f64, -0x00002f5f,0x000300f7,0x00002f6d,0x00000000, -0x000400fa,0x00002f66,0x00002f67,0x00002f6d, -0x000200f8,0x00002f67,0x000500bc,0x0000002f, -0x00002f6c,0x00002bf2,0x00002bfc,0x000200f9, -0x00002f6d,0x000200f8,0x00002f6d,0x000700f5, -0x0000002f,0x00002f6e,0x00002f66,0x00002f65, -0x00002f6c,0x00002f67,0x000300f7,0x00002c06, -0x00000000,0x000400fa,0x00002f6e,0x00002c02, -0x00002c06,0x000200f8,0x00002c02,0x000500c2, -0x00000006,0x00002c04,0x00002d6d,0x000005f9, -0x000500ab,0x0000002f,0x00002c05,0x00002c04, -0x0000012b,0x000200f9,0x00002c06,0x000200f8, -0x00002c06,0x000700f5,0x0000002f,0x00002c07, -0x00002f6e,0x00002f6d,0x00002c05,0x00002c02, -0x000300f7,0x00002c77,0x00000000,0x000400fa, -0x00002c07,0x00002c08,0x00002c77,0x000200f8, -0x00002c08,0x000200f9,0x00002c09,0x000200f8, -0x00002c09,0x000700f5,0x00000063,0x00005add, -0x00005cc2,0x00002c08,0x00002c72,0x00002c0d, -0x000700f5,0x00000063,0x00005acb,0x0000053d, -0x00002c08,0x00002c6f,0x00002c0d,0x000700f5, -0x00000006,0x00005aa8,0x0000012b,0x00002c08, -0x00002c75,0x00002c0d,0x000500b0,0x0000002f, -0x00002c0c,0x00005aa8,0x00000194,0x000400f6, -0x00002c76,0x00002c0d,0x00000000,0x000400fa, -0x00002c0c,0x00002c0d,0x00002c76,0x000200f8, -0x00002c0d,0x000500c7,0x00000006,0x00002c0f, -0x00005aa8,0x00000135,0x000500ab,0x0000002f, -0x00002c10,0x00002c0f,0x0000012b,0x000600a9, -0x00000027,0x00005cde,0x00002c10,0x00002bf6, -0x00002bec,0x000500c7,0x00000006,0x00002c1a, -0x00005aa8,0x00000247,0x000500ab,0x0000002f, -0x00002c1b,0x00002c1a,0x0000012b,0x000600a9, -0x00000027,0x00005cdf,0x00002c1b,0x00002bf9, -0x00002bef,0x000500c7,0x00000006,0x00002c25, -0x00005aa8,0x000000df,0x000500ab,0x0000002f, -0x00002c26,0x00002c25,0x0000012b,0x000600a9, -0x00000027,0x00005ce0,0x00002c26,0x00002bfc, -0x00002bf2,0x00050041,0x00000028,0x00002c30, -0x00002b2c,0x0000015e,0x0004003d,0x00000027, -0x00002c31,0x00002c30,0x00050085,0x00000027, -0x00002c34,0x00002c31,0x00005cde,0x00050041, -0x00000028,0x00002c35,0x00002b2c,0x0000022b, -0x0004003d,0x00000027,0x00002c36,0x00002c35, -0x00050085,0x00000027,0x00002c39,0x00002c36, -0x00005cdf,0x00050081,0x00000027,0x00002c3a, -0x00002c34,0x00002c39,0x00050041,0x00000028, -0x00002c3b,0x00002b2c,0x000002dc,0x0004003d, -0x00000027,0x00002c3c,0x00002c3b,0x00050085, -0x00000027,0x00002c3f,0x00002c3c,0x00005ce0, -0x00050081,0x00000027,0x00002c40,0x00002c3a, -0x00002c3f,0x00050041,0x00000028,0x00002c41, -0x00002b2c,0x000002e4,0x0004003d,0x00000027, -0x00002c42,0x00002c41,0x00050081,0x00000027, -0x00002c43,0x00002c40,0x00002c42,0x00050041, -0x00000028,0x00002c44,0x00002b2c,0x000002ec, -0x0004003d,0x00000027,0x00002c45,0x00002c44, -0x00050085,0x00000027,0x00002c48,0x00002c45, -0x00005cde,0x00050041,0x00000028,0x00002c49, -0x00002b2c,0x000002f4,0x0004003d,0x00000027, -0x00002c4a,0x00002c49,0x00050085,0x00000027, -0x00002c4d,0x00002c4a,0x00005cdf,0x00050081, -0x00000027,0x00002c4e,0x00002c48,0x00002c4d, -0x00050041,0x00000028,0x00002c4f,0x00002b2c, -0x00000318,0x0004003d,0x00000027,0x00002c50, -0x00002c4f,0x00050085,0x00000027,0x00002c53, -0x00002c50,0x00005ce0,0x00050081,0x00000027, -0x00002c54,0x00002c4e,0x00002c53,0x00050041, -0x00000028,0x00002c55,0x00002b2c,0x00000653, -0x0004003d,0x00000027,0x00002c56,0x00002c55, -0x00050081,0x00000027,0x00002c57,0x00002c54, -0x00002c56,0x00050041,0x00000028,0x00002c58, -0x00002b2c,0x00000488,0x0004003d,0x00000027, -0x00002c59,0x00002c58,0x00050085,0x00000027, -0x00002c5c,0x00002c59,0x00005cde,0x00050041, -0x00000028,0x00002c5d,0x00002b2c,0x000001cd, -0x0004003d,0x00000027,0x00002c5e,0x00002c5d, -0x00050085,0x00000027,0x00002c61,0x00002c5e, -0x00005cdf,0x00050081,0x00000027,0x00002c62, -0x00002c5c,0x00002c61,0x00050041,0x00000028, -0x00002c63,0x00002b2c,0x0000037d,0x0004003d, -0x00000027,0x00002c64,0x00002c63,0x00050085, -0x00000027,0x00002c67,0x00002c64,0x00005ce0, -0x00050081,0x00000027,0x00002c68,0x00002c62, -0x00002c67,0x00050041,0x00000028,0x00002c69, -0x00002b2c,0x000003fb,0x0004003d,0x00000027, -0x00002c6a,0x00002c69,0x00050081,0x00000027, -0x00002c6b,0x00002c68,0x00002c6a,0x00060050, -0x00000063,0x00002c6c,0x00002c43,0x00002c57, -0x00002c6b,0x0007000c,0x00000063,0x00002c6f, -0x00000001,0x00000025,0x00005acb,0x00002c6c, -0x0007000c,0x00000063,0x00002c72,0x00000001, -0x00000028,0x00005add,0x00002c6c,0x00050080, -0x00000006,0x00002c75,0x00005aa8,0x0000022b, -0x000200f9,0x00002c09,0x000200f8,0x00002c76, -0x000200f9,0x00002c77,0x000200f8,0x00002c77, -0x000700f5,0x00000063,0x00005ad9,0x00005cc2, -0x00002c06,0x00005add,0x00002c76,0x000700f5, -0x00000063,0x00005ac7,0x0000053d,0x00002c06, -0x00005acb,0x00002c76,0x000200f9,0x00002c78, -0x000200f8,0x00002c78,0x000700f5,0x00000063, -0x00005ad7,0x00005cc2,0x00002e5b,0x00005ad9, -0x00002c77,0x000700f5,0x00000063,0x00005ac5, -0x0000053d,0x00002e5b,0x00005ac7,0x00002c77, -0x000700f5,0x00000006,0x00005ab1,0x00000500, -0x00002e5b,0x00002e79,0x00002c77,0x00050041, -0x00000028,0x00002c79,0x00002b2c,0x0000015e, -0x0004003d,0x00000027,0x00002c7a,0x00002c79, -0x000500b4,0x0000002f,0x00002c7b,0x00002c7a, -0x00000677,0x000300f7,0x00002c80,0x00000000, -0x000400fa,0x00002c7b,0x00002c7c,0x00002c80, -0x000200f8,0x00002c7c,0x00050041,0x00000028, -0x00002c7d,0x00002b2c,0x0000022b,0x0004003d, -0x00000027,0x00002c7e,0x00002c7d,0x000500b4, -0x0000002f,0x00002c7f,0x00002c7e,0x000003ed, -0x000200f9,0x00002c80,0x000200f8,0x00002c80, -0x000700f5,0x0000002f,0x00002c81,0x00002c7b, -0x00002c78,0x00002c7f,0x00002c7c,0x000300f7, -0x00002c86,0x00000000,0x000400fa,0x00002c81, -0x00002c82,0x00002c86,0x000200f8,0x00002c82, -0x00050041,0x00000028,0x00002c83,0x00002b2c, -0x000002dc,0x0004003d,0x00000027,0x00002c84, -0x00002c83,0x000500b4,0x0000002f,0x00002c85, -0x00002c84,0x000003ed,0x000200f9,0x00002c86, -0x000200f8,0x00002c86,0x000700f5,0x0000002f, -0x00002c87,0x00002c81,0x00002c80,0x00002c85, -0x00002c82,0x000300f7,0x00002c8c,0x00000000, -0x000400fa,0x00002c87,0x00002c88,0x00002c8c, -0x000200f8,0x00002c88,0x00050041,0x00000028, -0x00002c89,0x00002b2c,0x000002ec,0x0004003d, -0x00000027,0x00002c8a,0x00002c89,0x000500b4, -0x0000002f,0x00002c8b,0x00002c8a,0x000003ed, -0x000200f9,0x00002c8c,0x000200f8,0x00002c8c, -0x000700f5,0x0000002f,0x00002c8d,0x00002c87, -0x00002c86,0x00002c8b,0x00002c88,0x000300f7, -0x00002c92,0x00000000,0x000400fa,0x00002c8d, -0x00002c8e,0x00002c92,0x000200f8,0x00002c8e, -0x00050041,0x00000028,0x00002c8f,0x00002b2c, -0x000002f4,0x0004003d,0x00000027,0x00002c90, -0x00002c8f,0x000500b4,0x0000002f,0x00002c91, -0x00002c90,0x00000677,0x000200f9,0x00002c92, -0x000200f8,0x00002c92,0x000700f5,0x0000002f, -0x00002c93,0x00002c8d,0x00002c8c,0x00002c91, -0x00002c8e,0x000300f7,0x00002c98,0x00000000, -0x000400fa,0x00002c93,0x00002c94,0x00002c98, -0x000200f8,0x00002c94,0x00050041,0x00000028, -0x00002c95,0x00002b2c,0x00000318,0x0004003d, -0x00000027,0x00002c96,0x00002c95,0x000500b4, -0x0000002f,0x00002c97,0x00002c96,0x000003ed, -0x000200f9,0x00002c98,0x000200f8,0x00002c98, -0x000700f5,0x0000002f,0x00002c99,0x00002c93, -0x00002c92,0x00002c97,0x00002c94,0x000300f7, -0x00002c9e,0x00000000,0x000400fa,0x00002c99, -0x00002c9a,0x00002c9e,0x000200f8,0x00002c9a, -0x00050041,0x00000028,0x00002c9b,0x00002b2c, -0x00000488,0x0004003d,0x00000027,0x00002c9c, -0x00002c9b,0x000500b4,0x0000002f,0x00002c9d, -0x00002c9c,0x000003ed,0x000200f9,0x00002c9e, -0x000200f8,0x00002c9e,0x000700f5,0x0000002f, -0x00002c9f,0x00002c99,0x00002c98,0x00002c9d, -0x00002c9a,0x000300f7,0x00002ca4,0x00000000, -0x000400fa,0x00002c9f,0x00002ca0,0x00002ca4, -0x000200f8,0x00002ca0,0x00050041,0x00000028, -0x00002ca1,0x00002b2c,0x000001cd,0x0004003d, -0x00000027,0x00002ca2,0x00002ca1,0x000500b4, -0x0000002f,0x00002ca3,0x00002ca2,0x000003ed, -0x000200f9,0x00002ca4,0x000200f8,0x00002ca4, -0x000700f5,0x0000002f,0x00002ca5,0x00002c9f, -0x00002c9e,0x00002ca3,0x00002ca0,0x000300f7, -0x00002caa,0x00000000,0x000400fa,0x00002ca5, -0x00002ca6,0x00002caa,0x000200f8,0x00002ca6, -0x00050041,0x00000028,0x00002ca7,0x00002b2c, -0x0000037d,0x0004003d,0x00000027,0x00002ca8, -0x00002ca7,0x000500b4,0x0000002f,0x00002ca9, -0x00002ca8,0x00000677,0x000200f9,0x00002caa, -0x000200f8,0x00002caa,0x000700f5,0x0000002f, -0x00002cab,0x00002ca5,0x00002ca4,0x00002ca9, -0x00002ca6,0x00050080,0x00000006,0x00002cad, -0x00002bbe,0x000004fe,0x000500c7,0x00000006, -0x00002caf,0x00005ab1,0x000006ac,0x000600a9, -0x00000006,0x00002cb1,0x00002cab,0x00000208, -0x0000012b,0x000500c5,0x00000006,0x00002cb2, -0x00002caf,0x00002cb1,0x00050095,0x00000130, -0x00002f87,0x00002e27,0x00002cad,0x00050051, -0x00000006,0x00002f88,0x00002f87,0x00000001, -0x00050051,0x00000006,0x00002f89,0x00002f87, -0x00000000,0x00050080,0x00000006,0x00002f8e, -0x00002e2e,0x00002f88,0x00050050,0x00000007, -0x00002f8f,0x00002f89,0x00002f8e,0x0004007c, -0x00000014,0x00002f7f,0x00002f8f,0x00060041, -0x0000015f,0x00002f77,0x00002f7f,0x0000015e, -0x0000015e,0x0005003e,0x00002f77,0x00002cb2, -0x00000002,0x00000004,0x00050080,0x00000006, -0x00002cb7,0x00002bbe,0x00000508,0x000500c2, -0x00000006,0x00002cba,0x00002daf,0x00000488, -0x000500c4,0x00000006,0x00002cbd,0x00002dd0, -0x000005f9,0x000500c5,0x00000006,0x00002cbe, -0x00002cba,0x00002cbd,0x00050095,0x00000130, -0x00002fa7,0x00002e27,0x00002cb7,0x00050051, -0x00000006,0x00002fa8,0x00002fa7,0x00000001, -0x00050051,0x00000006,0x00002fa9,0x00002fa7, -0x00000000,0x00050080,0x00000006,0x00002fae, -0x00002e2e,0x00002fa8,0x00050050,0x00000007, -0x00002faf,0x00002fa9,0x00002fae,0x0004007c, -0x00000014,0x00002f9f,0x00002faf,0x00060041, -0x0000015f,0x00002f97,0x00002f9f,0x0000015e, -0x0000015e,0x0005003e,0x00002f97,0x00002cbe, -0x00000002,0x00000004,0x0004003d,0x00000027, -0x00002cc3,0x00002c79,0x00050041,0x00000028, -0x00002cc4,0x00002b2c,0x000002ec,0x0004003d, -0x00000027,0x00002cc5,0x00002cc4,0x00050041, -0x00000028,0x00002cc6,0x00002b2c,0x00000488, -0x0004003d,0x00000027,0x00002cc7,0x00002cc6, -0x00050041,0x00000028,0x00002cc8,0x00002b2c, -0x0000022b,0x0004003d,0x00000027,0x00002cc9, -0x00002cc8,0x00050041,0x00000028,0x00002cca, -0x00002b2c,0x000002f4,0x0004003d,0x00000027, -0x00002ccb,0x00002cca,0x00050041,0x00000028, -0x00002ccc,0x00002b2c,0x000001cd,0x0004003d, -0x00000027,0x00002ccd,0x00002ccc,0x00050041, -0x00000028,0x00002cce,0x00002b2c,0x000002dc, -0x0004003d,0x00000027,0x00002ccf,0x00002cce, -0x00050041,0x00000028,0x00002cd0,0x00002b2c, -0x00000318,0x0004003d,0x00000027,0x00002cd1, -0x00002cd0,0x00050041,0x00000028,0x00002cd2, -0x00002b2c,0x0000037d,0x0004003d,0x00000027, -0x00002cd3,0x00002cd2,0x00060050,0x00000063, -0x00002cd4,0x00002cc3,0x00002cc5,0x00002cc7, -0x00060050,0x00000063,0x00002cd5,0x00002cc9, -0x00002ccb,0x00002ccd,0x00060050,0x00000063, -0x00002cd6,0x00002ccf,0x00002cd1,0x00002cd3, -0x00060050,0x000006c6,0x00002cd7,0x00002cd4, -0x00002cd5,0x00002cd6,0x0006000c,0x00000027, -0x00002cd9,0x00000001,0x00000021,0x00002cd7, -0x000500b7,0x0000002f,0x00002cdb,0x00002cd9, -0x000003ed,0x000300f7,0x00002ce0,0x00000000, -0x000400fa,0x00002cdb,0x00002cdc,0x00002cdf, -0x000200f8,0x00002cdf,0x000200f9,0x00002ce0, -0x000200f8,0x00002cdc,0x0006000c,0x000006c6, -0x00002cde,0x00000001,0x00000022,0x00002cd7, -0x000200f9,0x00002ce0,0x000200f8,0x00002ce0, -0x000700f5,0x000006c6,0x00005ab8,0x00002cde, -0x00002cdc,0x000006ec,0x00002cdf,0x0003003e, -0x00002b6d,0x00005ab8,0x00050041,0x00000028, -0x00002ce2,0x00002b2c,0x000002e4,0x0004003d, -0x00000027,0x00002ce3,0x00002ce2,0x00050041, -0x00000028,0x00002ce4,0x00002b2c,0x00000653, -0x0004003d,0x00000027,0x00002ce5,0x00002ce4, -0x00050041,0x00000028,0x00002ce6,0x00002b2c, -0x000003fb,0x0004003d,0x00000027,0x00002ce7, -0x00002ce6,0x00060050,0x00000063,0x00002ce8, -0x00002ce3,0x00002ce5,0x00002ce7,0x00050091, -0x00000063,0x00002ceb,0x00005ab8,0x00002ce8, -0x0004007f,0x00000063,0x00002cec,0x00002ceb, -0x0003003e,0x00002b70,0x00002cec,0x000200f9, -0x00002ced,0x000200f8,0x00002ced,0x000700f5, -0x00000006,0x00005ab9,0x0000012b,0x00002ce0, -0x00002d20,0x00002cf1,0x000500b0,0x0000002f, -0x00002cf0,0x00005ab9,0x00000437,0x000400f6, -0x00002d21,0x00002cf1,0x00000000,0x000400fa, -0x00002cf0,0x00002cf1,0x00002d21,0x000200f8, -0x00002cf1,0x00050080,0x00000006,0x00002cf3, -0x00002bbe,0x0000018b,0x00050084,0x00000006, -0x00002cf5,0x000001a2,0x00005ab9,0x00050080, -0x00000006,0x00002cf6,0x00002cf3,0x00002cf5, -0x00060041,0x00000028,0x00002cfa,0x00002b6d, -0x0000015e,0x00005ab9,0x0004003d,0x00000027, -0x00002cfb,0x00002cfa,0x0004007c,0x00000006, -0x00002fb5,0x00002cfb,0x00050095,0x00000130, -0x00002fd0,0x00002e27,0x00002cf6,0x00050051, -0x00000006,0x00002fd1,0x00002fd0,0x00000001, -0x00050051,0x00000006,0x00002fd2,0x00002fd0, -0x00000000,0x00050080,0x00000006,0x00002fd7, -0x00002e2e,0x00002fd1,0x00050050,0x00000007, -0x00002fd8,0x00002fd2,0x00002fd7,0x0004007c, -0x00000014,0x00002fc8,0x00002fd8,0x00060041, -0x0000015f,0x00002fc0,0x00002fc8,0x0000015e, -0x0000015e,0x0005003e,0x00002fc0,0x00002fb5, -0x00000002,0x00000004,0x00050080,0x00000006, -0x00002cfe,0x00002bbe,0x00000712,0x00050080, -0x00000006,0x00002d01,0x00002cfe,0x00002cf5, -0x00060041,0x00000028,0x00002d05,0x00002b6d, -0x0000022b,0x00005ab9,0x0004003d,0x00000027, -0x00002d06,0x00002d05,0x0004007c,0x00000006, -0x00002fde,0x00002d06,0x00050095,0x00000130, -0x00002ff9,0x00002e27,0x00002d01,0x00050051, -0x00000006,0x00002ffa,0x00002ff9,0x00000001, -0x00050051,0x00000006,0x00002ffb,0x00002ff9, -0x00000000,0x00050080,0x00000006,0x00003000, -0x00002e2e,0x00002ffa,0x00050050,0x00000007, -0x00003001,0x00002ffb,0x00003000,0x0004007c, -0x00000014,0x00002ff1,0x00003001,0x00060041, -0x0000015f,0x00002fe9,0x00002ff1,0x0000015e, -0x0000015e,0x0005003e,0x00002fe9,0x00002fde, -0x00000002,0x00000004,0x00050080,0x00000006, -0x00002d09,0x00002bbe,0x00000721,0x00050080, -0x00000006,0x00002d0c,0x00002d09,0x00002cf5, -0x00060041,0x00000028,0x00002d10,0x00002b6d, -0x000002dc,0x00005ab9,0x0004003d,0x00000027, -0x00002d11,0x00002d10,0x0004007c,0x00000006, -0x00003007,0x00002d11,0x00050095,0x00000130, -0x00003022,0x00002e27,0x00002d0c,0x00050051, -0x00000006,0x00003023,0x00003022,0x00000001, -0x00050051,0x00000006,0x00003024,0x00003022, -0x00000000,0x00050080,0x00000006,0x00003029, -0x00002e2e,0x00003023,0x00050050,0x00000007, -0x0000302a,0x00003024,0x00003029,0x0004007c, -0x00000014,0x0000301a,0x0000302a,0x00060041, -0x0000015f,0x00003012,0x0000301a,0x0000015e, -0x0000015e,0x0005003e,0x00003012,0x00003007, -0x00000002,0x00000004,0x00050080,0x00000006, -0x00002d14,0x00002bbe,0x00000730,0x00050080, -0x00000006,0x00002d17,0x00002d14,0x00002cf5, -0x00050041,0x00000028,0x00002d1b,0x00002b70, -0x00005ab9,0x0004003d,0x00000027,0x00002d1c, -0x00002d1b,0x0004007c,0x00000006,0x00003030, -0x00002d1c,0x00050095,0x00000130,0x0000304b, -0x00002e27,0x00002d17,0x00050051,0x00000006, -0x0000304c,0x0000304b,0x00000001,0x00050051, -0x00000006,0x0000304d,0x0000304b,0x00000000, -0x00050080,0x00000006,0x00003052,0x00002e2e, -0x0000304c,0x00050050,0x00000007,0x00003053, -0x0000304d,0x00003052,0x0004007c,0x00000014, -0x00003043,0x00003053,0x00060041,0x0000015f, -0x0000303b,0x00003043,0x0000015e,0x0000015e, -0x0005003e,0x0000303b,0x00003030,0x00000002, -0x00000004,0x00050080,0x00000006,0x00002d20, -0x00005ab9,0x0000022b,0x000200f9,0x00002ced, -0x000200f8,0x00002d21,0x00050080,0x00000006, -0x00002d23,0x00002bbe,0x00000741,0x00050095, -0x00000130,0x0000306b,0x00002e27,0x00002d23, -0x00050051,0x00000006,0x0000306c,0x0000306b, -0x00000001,0x00050051,0x00000006,0x0000306d, -0x0000306b,0x00000000,0x00050080,0x00000006, -0x00003072,0x00002e2e,0x0000306c,0x00050050, -0x00000007,0x00003073,0x0000306d,0x00003072, -0x0004007c,0x00000014,0x00003063,0x00003073, -0x00060041,0x0000015f,0x0000305b,0x00003063, -0x0000015e,0x0000015e,0x0005003e,0x0000305b, -0x000011de,0x00000002,0x00000004,0x00050080, -0x00000006,0x00002d29,0x00002bbe,0x0000074b, -0x00050095,0x00000130,0x0000308b,0x00002e27, -0x00002d29,0x00050051,0x00000006,0x0000308c, -0x0000308b,0x00000001,0x00050051,0x00000006, -0x0000308d,0x0000308b,0x00000000,0x00050080, -0x00000006,0x00003092,0x00002e2e,0x0000308c, -0x00050050,0x00000007,0x00003093,0x0000308d, -0x00003092,0x0004007c,0x00000014,0x00003083, -0x00003093,0x00060041,0x0000015f,0x0000307b, -0x00003083,0x0000015e,0x0000015e,0x0005003e, -0x0000307b,0x00000500,0x00000002,0x00000004, -0x00050080,0x00000006,0x00002d2e,0x00002bbe, -0x00000754,0x00050095,0x00000130,0x000030ab, -0x00002e27,0x00002d2e,0x00050051,0x00000006, -0x000030ac,0x000030ab,0x00000001,0x00050051, -0x00000006,0x000030ad,0x000030ab,0x00000000, -0x00050080,0x00000006,0x000030b2,0x00002e2e, -0x000030ac,0x00050050,0x00000007,0x000030b3, -0x000030ad,0x000030b2,0x0004007c,0x00000014, -0x000030a3,0x000030b3,0x00060041,0x0000015f, -0x0000309b,0x000030a3,0x0000015e,0x0000015e, -0x0005003e,0x0000309b,0x0000012b,0x00000002, -0x00000004,0x00050080,0x00000006,0x00002d33, -0x00002bbe,0x0000075d,0x00050095,0x00000130, -0x000030cb,0x00002e27,0x00002d33,0x00050051, -0x00000006,0x000030cc,0x000030cb,0x00000001, -0x00050051,0x00000006,0x000030cd,0x000030cb, -0x00000000,0x00050080,0x00000006,0x000030d2, -0x00002e2e,0x000030cc,0x00050050,0x00000007, -0x000030d3,0x000030cd,0x000030d2,0x0004007c, -0x00000014,0x000030c3,0x000030d3,0x00060041, -0x0000015f,0x000030bb,0x000030c3,0x0000015e, -0x0000015e,0x0005003e,0x000030bb,0x0000012b, -0x00000002,0x00000004,0x000500b4,0x0000002f, -0x00002d38,0x00002cd9,0x000003ed,0x00060050, -0x00000514,0x00005ce1,0x00002d38,0x00002d38, -0x00002d38,0x000600a9,0x00000063,0x00005ce2, -0x00005ce1,0x00005cc2,0x00005ad7,0x000600a9, -0x00000063,0x00005ce4,0x00005ce1,0x0000053d, -0x00005ac5,0x00050041,0x00000182,0x00003123, -0x00000180,0x00000181,0x0004003d,0x00000006, -0x00003124,0x00003123,0x00050084,0x00000006, -0x00003125,0x000001a2,0x00003124,0x00050080, -0x00000006,0x00003126,0x0000018b,0x00003125, -0x00050080,0x00000006,0x0000312c,0x00003124, -0x00005cc3,0x00050086,0x00000006,0x0000312d, -0x0000312c,0x00000185,0x00050084,0x00000006, -0x0000311f,0x0000018b,0x0000312d,0x00050080, -0x00000006,0x00003120,0x00003126,0x0000311f, -0x00050080,0x00000006,0x0000311a,0x00003120, -0x0000311f,0x00050084,0x00000006,0x000030ea, -0x000001b6,0x000011de,0x00050080,0x00000006, -0x000030eb,0x0000311a,0x000030ea,0x00050041, -0x0000022d,0x000030ec,0x00000180,0x0000022b, -0x0004003d,0x00000007,0x000030ed,0x000030ec, -0x00050051,0x00000027,0x000030f0,0x00005ce4, -0x00000000,0x0004007c,0x00000006,0x0000313a, -0x000030f0,0x00050051,0x00000006,0x00003153, -0x000030ed,0x00000000,0x00050095,0x00000130, -0x00003155,0x00003153,0x000030eb,0x00050051, -0x00000006,0x00003156,0x00003155,0x00000001, -0x00050051,0x00000006,0x00003157,0x00003155, -0x00000000,0x00050051,0x00000006,0x0000315a, -0x000030ed,0x00000001,0x00050080,0x00000006, -0x0000315c,0x0000315a,0x00003156,0x00050050, -0x00000007,0x0000315d,0x00003157,0x0000315c, -0x0004007c,0x00000014,0x0000314d,0x0000315d, -0x00060041,0x0000015f,0x00003145,0x0000314d, -0x0000015e,0x0000015e,0x0005003e,0x00003145, -0x0000313a,0x00000002,0x00000004,0x00050080, -0x00000006,0x000030f3,0x000030eb,0x000000df, -0x00050051,0x00000027,0x000030f7,0x00005ce4, -0x00000001,0x0004007c,0x00000006,0x00003163, -0x000030f7,0x00050095,0x00000130,0x0000317e, -0x00003153,0x000030f3,0x00050051,0x00000006, -0x0000317f,0x0000317e,0x00000001,0x00050051, -0x00000006,0x00003180,0x0000317e,0x00000000, -0x00050080,0x00000006,0x00003185,0x0000315a, -0x0000317f,0x00050050,0x00000007,0x00003186, -0x00003180,0x00003185,0x0004007c,0x00000014, -0x00003176,0x00003186,0x00060041,0x0000015f, -0x0000316e,0x00003176,0x0000015e,0x0000015e, -0x0005003e,0x0000316e,0x00003163,0x00000002, -0x00000004,0x00050080,0x00000006,0x000030fa, -0x000030eb,0x00000194,0x00050051,0x00000027, -0x000030fe,0x00005ce4,0x00000002,0x0004007c, -0x00000006,0x0000318c,0x000030fe,0x00050095, -0x00000130,0x000031a7,0x00003153,0x000030fa, -0x00050051,0x00000006,0x000031a8,0x000031a7, -0x00000001,0x00050051,0x00000006,0x000031a9, -0x000031a7,0x00000000,0x00050080,0x00000006, -0x000031ae,0x0000315a,0x000031a8,0x00050050, -0x00000007,0x000031af,0x000031a9,0x000031ae, -0x0004007c,0x00000014,0x0000319f,0x000031af, -0x00060041,0x0000015f,0x00003197,0x0000319f, -0x0000015e,0x0000015e,0x0005003e,0x00003197, -0x0000318c,0x00000002,0x00000004,0x00050080, -0x00000006,0x00003101,0x000030eb,0x0000019b, -0x00050051,0x00000027,0x00003105,0x00005ce2, -0x00000000,0x0004007c,0x00000006,0x000031b5, -0x00003105,0x00050095,0x00000130,0x000031d0, -0x00003153,0x00003101,0x00050051,0x00000006, -0x000031d1,0x000031d0,0x00000001,0x00050051, -0x00000006,0x000031d2,0x000031d0,0x00000000, -0x00050080,0x00000006,0x000031d7,0x0000315a, -0x000031d1,0x00050050,0x00000007,0x000031d8, -0x000031d2,0x000031d7,0x0004007c,0x00000014, -0x000031c8,0x000031d8,0x00060041,0x0000015f, -0x000031c0,0x000031c8,0x0000015e,0x0000015e, -0x0005003e,0x000031c0,0x000031b5,0x00000002, -0x00000004,0x00050080,0x00000006,0x00003108, -0x000030eb,0x000001a2,0x00050051,0x00000027, -0x0000310c,0x00005ce2,0x00000001,0x0004007c, -0x00000006,0x000031de,0x0000310c,0x00050095, -0x00000130,0x000031f9,0x00003153,0x00003108, -0x00050051,0x00000006,0x000031fa,0x000031f9, -0x00000001,0x00050051,0x00000006,0x000031fb, -0x000031f9,0x00000000,0x00050080,0x00000006, -0x00003200,0x0000315a,0x000031fa,0x00050050, -0x00000007,0x00003201,0x000031fb,0x00003200, -0x0004007c,0x00000014,0x000031f1,0x00003201, -0x00060041,0x0000015f,0x000031e9,0x000031f1, -0x0000015e,0x0000015e,0x0005003e,0x000031e9, -0x000031de,0x00000002,0x00000004,0x00050080, -0x00000006,0x0000310f,0x000030eb,0x00000260, -0x00050051,0x00000027,0x00003113,0x00005ce2, -0x00000002,0x0004007c,0x00000006,0x00003207, -0x00003113,0x00050095,0x00000130,0x00003222, -0x00003153,0x0000310f,0x00050051,0x00000006, -0x00003223,0x00003222,0x00000001,0x00050051, -0x00000006,0x00003224,0x00003222,0x00000000, -0x00050080,0x00000006,0x00003229,0x0000315a, -0x00003223,0x00050050,0x00000007,0x0000322a, -0x00003224,0x00003229,0x0004007c,0x00000014, -0x0000321a,0x0000322a,0x00060041,0x0000015f, -0x00003212,0x0000321a,0x0000015e,0x0000015e, -0x0005003e,0x00003212,0x00003207,0x00000002, -0x00000004,0x000300f7,0x0000326a,0x00000000, -0x000300fb,0x0000012b,0x00003239,0x000200f8, -0x00003239,0x000500bc,0x0000002f,0x00003271, -0x000030f0,0x00003105,0x000300f7,0x00003278, -0x00000000,0x000400fa,0x00003271,0x00003272, -0x00003278,0x000200f8,0x00003272,0x000500bc, -0x0000002f,0x00003277,0x000030f7,0x0000310c, -0x000200f9,0x00003278,0x000200f8,0x00003278, -0x000700f5,0x0000002f,0x00003279,0x00003271, -0x00003239,0x00003277,0x00003272,0x000300f7, -0x00003280,0x00000000,0x000400fa,0x00003279, -0x0000327a,0x00003280,0x000200f8,0x0000327a, -0x000500bc,0x0000002f,0x0000327f,0x000030fe, -0x00003113,0x000200f9,0x00003280,0x000200f8, -0x00003280,0x000700f5,0x0000002f,0x00003281, -0x00003279,0x00003278,0x0000327f,0x0000327a, -0x000400a8,0x0000002f,0x00003282,0x00003281, -0x000300f7,0x0000323e,0x00000000,0x000400fa, -0x00003282,0x0000323d,0x0000323e,0x000200f8, -0x0000323d,0x000200f9,0x0000326a,0x000200f8, -0x0000323e,0x00050081,0x00000063,0x00003241, -0x00005ce4,0x00005ce2,0x0005008e,0x00000063, -0x00003242,0x00003241,0x000002c4,0x00050095, -0x00000130,0x00003292,0x00003153,0x0000012b, -0x00050051,0x00000006,0x00003293,0x00003292, -0x00000001,0x00050051,0x00000006,0x00003294, -0x00003292,0x00000000,0x00050080,0x00000006, -0x00003299,0x0000315a,0x00003293,0x00050050, -0x00000007,0x0000329a,0x00003294,0x00003299, -0x0004007c,0x00000014,0x0000328a,0x0000329a, -0x00060041,0x0000015f,0x00003247,0x0000328a, -0x0000015e,0x0000015e,0x00050051,0x00000027, -0x00003249,0x00003242,0x00000000,0x0004007c, -0x00000006,0x000032a0,0x00003249,0x000500c7, -0x00000006,0x000032a2,0x000032a0,0x00000208, -0x000500ab,0x0000002f,0x000032a3,0x000032a2, -0x0000012b,0x000300f7,0x000032aa,0x00000000, -0x000400fa,0x000032a3,0x000032a4,0x000032a7, -0x000200f8,0x000032a7,0x000500c5,0x00000006, -0x000032a9,0x000032a0,0x00000208,0x000200f9, -0x000032aa,0x000200f8,0x000032a4,0x000400c8, -0x00000006,0x000032a6,0x000032a0,0x000200f9, -0x000032aa,0x000200f8,0x000032aa,0x000700f5, -0x00000006,0x00005ade,0x000032a6,0x000032a4, -0x000032a9,0x000032a7,0x000700ed,0x00000006, -0x0000324b,0x00003247,0x00000135,0x0000012b, -0x00005ade,0x00060041,0x0000015f,0x0000324d, -0x0000328a,0x0000015e,0x0000022b,0x00050051, -0x00000027,0x0000324f,0x00003242,0x00000001, -0x0004007c,0x00000006,0x000032b1,0x0000324f, -0x000500c7,0x00000006,0x000032b3,0x000032b1, -0x00000208,0x000500ab,0x0000002f,0x000032b4, -0x000032b3,0x0000012b,0x000300f7,0x000032bb, -0x00000000,0x000400fa,0x000032b4,0x000032b5, -0x000032b8,0x000200f8,0x000032b8,0x000500c5, -0x00000006,0x000032ba,0x000032b1,0x00000208, -0x000200f9,0x000032bb,0x000200f8,0x000032b5, -0x000400c8,0x00000006,0x000032b7,0x000032b1, -0x000200f9,0x000032bb,0x000200f8,0x000032bb, -0x000700f5,0x00000006,0x00005adf,0x000032b7, -0x000032b5,0x000032ba,0x000032b8,0x000700ed, -0x00000006,0x00003251,0x0000324d,0x00000135, -0x0000012b,0x00005adf,0x00060041,0x0000015f, -0x00003253,0x0000328a,0x0000015e,0x000002dc, -0x00050051,0x00000027,0x00003255,0x00003242, -0x00000002,0x0004007c,0x00000006,0x000032c2, -0x00003255,0x000500c7,0x00000006,0x000032c4, -0x000032c2,0x00000208,0x000500ab,0x0000002f, -0x000032c5,0x000032c4,0x0000012b,0x000300f7, -0x000032cc,0x00000000,0x000400fa,0x000032c5, -0x000032c6,0x000032c9,0x000200f8,0x000032c9, -0x000500c5,0x00000006,0x000032cb,0x000032c2, -0x00000208,0x000200f9,0x000032cc,0x000200f8, -0x000032c6,0x000400c8,0x00000006,0x000032c8, -0x000032c2,0x000200f9,0x000032cc,0x000200f8, -0x000032cc,0x000700f5,0x00000006,0x00005ae0, -0x000032c8,0x000032c6,0x000032cb,0x000032c9, -0x000700ed,0x00000006,0x00003257,0x00003253, -0x00000135,0x0000012b,0x00005ae0,0x00060041, -0x0000015f,0x00003259,0x0000328a,0x0000015e, -0x000002e4,0x000300f7,0x000032dd,0x00000000, -0x000400fa,0x000032a3,0x000032d7,0x000032da, -0x000200f8,0x000032da,0x000500c5,0x00000006, -0x000032dc,0x000032a0,0x00000208,0x000200f9, -0x000032dd,0x000200f8,0x000032d7,0x000400c8, -0x00000006,0x000032d9,0x000032a0,0x000200f9, -0x000032dd,0x000200f8,0x000032dd,0x000700f5, -0x00000006,0x00005ae1,0x000032d9,0x000032d7, -0x000032dc,0x000032da,0x000700ef,0x00000006, -0x0000325d,0x00003259,0x00000135,0x0000012b, -0x00005ae1,0x00060041,0x0000015f,0x0000325f, -0x0000328a,0x0000015e,0x000002ec,0x000300f7, -0x000032ee,0x00000000,0x000400fa,0x000032b4, -0x000032e8,0x000032eb,0x000200f8,0x000032eb, -0x000500c5,0x00000006,0x000032ed,0x000032b1, -0x00000208,0x000200f9,0x000032ee,0x000200f8, -0x000032e8,0x000400c8,0x00000006,0x000032ea, -0x000032b1,0x000200f9,0x000032ee,0x000200f8, -0x000032ee,0x000700f5,0x00000006,0x00005ae2, -0x000032ea,0x000032e8,0x000032ed,0x000032eb, -0x000700ef,0x00000006,0x00003263,0x0000325f, -0x00000135,0x0000012b,0x00005ae2,0x00060041, -0x0000015f,0x00003265,0x0000328a,0x0000015e, -0x000002f4,0x000300f7,0x000032ff,0x00000000, -0x000400fa,0x000032c5,0x000032f9,0x000032fc, -0x000200f8,0x000032fc,0x000500c5,0x00000006, -0x000032fe,0x000032c2,0x00000208,0x000200f9, -0x000032ff,0x000200f8,0x000032f9,0x000400c8, -0x00000006,0x000032fb,0x000032c2,0x000200f9, -0x000032ff,0x000200f8,0x000032ff,0x000700f5, -0x00000006,0x00005ae3,0x000032fb,0x000032f9, -0x000032fe,0x000032fc,0x000700ef,0x00000006, -0x00003269,0x00003265,0x00000135,0x0000012b, -0x00005ae3,0x000200f9,0x0000326a,0x000200f8, -0x0000326a,0x000200f9,0x000012c8,0x000200f8, -0x000012c8,0x000200f9,0x000012bf,0x000200f8, -0x000012be,0x000200f9,0x00002504,0x000200f8, -0x00002504,0x000700f5,0x00000006,0x00005af0, -0x0000012b,0x000012be,0x00002514,0x00002512, -0x000500b0,0x0000002f,0x00002507,0x00005af0, -0x00000437,0x000400f6,0x00002515,0x00002512, -0x00000000,0x000400fa,0x00002507,0x00002508, -0x00002515,0x000200f8,0x00002508,0x00050084, -0x00000006,0x0000250b,0x00000437,0x000011de, -0x00050080,0x00000006,0x0000250d,0x0000250b, -0x00005af0,0x000300f7,0x000025d0,0x00000000, -0x000300fb,0x0000012b,0x000025ae,0x000200f8, -0x000025ae,0x00050041,0x00000182,0x000025af, -0x00000180,0x000003fb,0x0004003d,0x00000006, -0x000025b0,0x000025af,0x000500aa,0x0000002f, -0x000025b1,0x000025b0,0x0000012b,0x000300f7, -0x000025b4,0x00000000,0x000400fa,0x000025b1, -0x000025b2,0x000025b4,0x000200f8,0x000025b2, -0x000200f9,0x000025d0,0x000200f8,0x000025b4, -0x000500aa,0x0000002f,0x000025b7,0x000025b0, -0x00000247,0x000300f7,0x000025be,0x00000000, -0x000400fa,0x000025b7,0x000025b8,0x000025be, -0x000200f8,0x000025b8,0x00050084,0x00000006, -0x000025ba,0x000000df,0x0000250d,0x00050041, -0x0000022d,0x000025bb,0x00000180,0x000002e4, -0x0004003d,0x00000007,0x000025bc,0x000025bb, -0x00050051,0x00000006,0x000025e8,0x000025bc, -0x00000000,0x00050095,0x00000130,0x000025ea, -0x000025e8,0x000025ba,0x00050051,0x00000006, -0x000025eb,0x000025ea,0x00000001,0x00050051, -0x00000006,0x000025ec,0x000025ea,0x00000000, -0x00050051,0x00000006,0x000025ef,0x000025bc, -0x00000001,0x00050080,0x00000006,0x000025f1, -0x000025ef,0x000025eb,0x00050050,0x00000007, -0x000025f2,0x000025ec,0x000025f1,0x0004007c, -0x00000014,0x000025e2,0x000025f2,0x00060041, -0x0000015f,0x000025d9,0x000025e2,0x0000015e, -0x0000015e,0x0006003d,0x00000006,0x000025da, -0x000025d9,0x00000002,0x00000004,0x000200f9, -0x000025d0,0x000200f8,0x000025be,0x000500c2, -0x00000006,0x000025c0,0x0000250d,0x0000022b, -0x00050084,0x00000006,0x000025c1,0x000000df, -0x000025c0,0x00050041,0x0000022d,0x000025c2, -0x00000180,0x000002e4,0x0004003d,0x00000007, -0x000025c3,0x000025c2,0x00050051,0x00000006, -0x00002609,0x000025c3,0x00000000,0x00050095, -0x00000130,0x0000260b,0x00002609,0x000025c1, -0x00050051,0x00000006,0x0000260c,0x0000260b, -0x00000001,0x00050051,0x00000006,0x0000260d, -0x0000260b,0x00000000,0x00050051,0x00000006, -0x00002610,0x000025c3,0x00000001,0x00050080, -0x00000006,0x00002612,0x00002610,0x0000260c, -0x00050050,0x00000007,0x00002613,0x0000260d, -0x00002612,0x0004007c,0x00000014,0x00002603, -0x00002613,0x00060041,0x0000015f,0x000025fa, -0x00002603,0x0000015e,0x0000015e,0x0006003d, -0x00000006,0x000025fb,0x000025fa,0x00000002, -0x00000004,0x000500c7,0x00000006,0x000025c6, -0x0000250d,0x00000135,0x000500ab,0x0000002f, -0x000025c7,0x000025c6,0x0000012b,0x000300f7, -0x000025ce,0x00000000,0x000400fa,0x000025c7, -0x000025c8,0x000025cb,0x000200f8,0x000025cb, -0x000500c7,0x00000006,0x000025cd,0x000025fb, -0x00000423,0x000200f9,0x000025ce,0x000200f8, -0x000025c8,0x000500c2,0x00000006,0x000025ca, -0x000025fb,0x00000321,0x000200f9,0x000025ce, -0x000200f8,0x000025ce,0x000700f5,0x00000006, -0x00005afa,0x000025ca,0x000025c8,0x000025cd, -0x000025cb,0x000200f9,0x000025d0,0x000200f8, -0x000025d0,0x000900f5,0x00000006,0x00005afb, -0x0000250d,0x000025b2,0x000025da,0x000025b8, -0x00005afa,0x000025ce,0x00050041,0x00000182, -0x00002624,0x00000180,0x000001cd,0x0004003d, -0x00000006,0x00002625,0x00002624,0x00050084, -0x00000006,0x00002626,0x00005afb,0x00002625, -0x00050041,0x0000022d,0x00002627,0x00000180, -0x000002dc,0x0004003d,0x00000007,0x00002628, -0x00002627,0x00050051,0x00000006,0x00002643, -0x00002628,0x00000000,0x00050095,0x00000130, -0x00002645,0x00002643,0x00002626,0x00050051, -0x00000006,0x00002646,0x00002645,0x00000001, -0x00050051,0x00000006,0x00002647,0x00002645, -0x00000000,0x00050051,0x00000006,0x0000264a, -0x00002628,0x00000001,0x00050080,0x00000006, -0x0000264c,0x0000264a,0x00002646,0x00050095, -0x00000130,0x00002666,0x00002647,0x0000012b, -0x00050051,0x00000006,0x00002667,0x00002666, -0x00000001,0x00050051,0x00000006,0x00002668, -0x00002666,0x00000000,0x00050080,0x00000006, -0x0000266d,0x0000264c,0x00002667,0x00050050, -0x00000007,0x0000266e,0x00002668,0x0000266d, -0x0004007c,0x00000014,0x0000265e,0x0000266e, -0x00060041,0x0000015f,0x00002655,0x0000265e, -0x0000015e,0x0000015e,0x0006003d,0x00000006, -0x00002656,0x00002655,0x00000002,0x00000004, -0x0004007c,0x00000027,0x0000262c,0x00002656, -0x00050095,0x00000130,0x00002687,0x00002647, -0x000000df,0x00050051,0x00000006,0x00002688, -0x00002687,0x00000001,0x00050051,0x00000006, -0x00002689,0x00002687,0x00000000,0x00050080, -0x00000006,0x0000268e,0x0000264c,0x00002688, -0x00050050,0x00000007,0x0000268f,0x00002689, -0x0000268e,0x0004007c,0x00000014,0x0000267f, -0x0000268f,0x00060041,0x0000015f,0x00002676, -0x0000267f,0x0000015e,0x0000015e,0x0006003d, -0x00000006,0x00002677,0x00002676,0x00000002, -0x00000004,0x0004007c,0x00000027,0x0000262f, -0x00002677,0x00050041,0x00000182,0x00002630, -0x00000180,0x0000037d,0x0004003d,0x00000006, -0x00002631,0x00002630,0x000500aa,0x0000002f, -0x00002632,0x00002631,0x00000135,0x000300f7, -0x00002638,0x00000000,0x000400fa,0x00002632, -0x00002633,0x00002634,0x000200f8,0x00002634, -0x00050095,0x00000130,0x000026a8,0x00002647, -0x00000194,0x00050051,0x00000006,0x000026a9, -0x000026a8,0x00000001,0x00050051,0x00000006, -0x000026aa,0x000026a8,0x00000000,0x00050080, -0x00000006,0x000026af,0x0000264c,0x000026a9, -0x00050050,0x00000007,0x000026b0,0x000026aa, -0x000026af,0x0004007c,0x00000014,0x000026a0, -0x000026b0,0x00060041,0x0000015f,0x00002697, -0x000026a0,0x0000015e,0x0000015e,0x0006003d, -0x00000006,0x00002698,0x00002697,0x00000002, -0x00000004,0x0004007c,0x00000027,0x00002637, -0x00002698,0x000200f9,0x00002638,0x000200f8, -0x00002633,0x000200f9,0x00002638,0x000200f8, -0x00002638,0x000700f5,0x00000027,0x00005afc, -0x000003ed,0x00002633,0x00002637,0x00002634, -0x00060050,0x00000063,0x0000263d,0x0000262c, -0x0000262f,0x00005afc,0x000300f7,0x000026f6, -0x00000000,0x000300fb,0x0000012b,0x000026c2, -0x000200f8,0x000026c2,0x00050041,0x0000022d, -0x000026c3,0x00000180,0x000002ec,0x0004003d, -0x00000007,0x000026c4,0x000026c3,0x00050051, -0x00000006,0x000026fb,0x000026c4,0x00000000, -0x000500aa,0x0000002f,0x000026fc,0x000026fb, -0x0000012b,0x000300f7,0x00002701,0x00000000, -0x000400fa,0x000026fc,0x000026fd,0x00002701, -0x000200f8,0x000026fd,0x00050051,0x00000006, -0x000026ff,0x000026c4,0x00000001,0x000500aa, -0x0000002f,0x00002700,0x000026ff,0x0000012b, -0x000200f9,0x00002701,0x000200f8,0x00002701, -0x000700f5,0x0000002f,0x00002702,0x000026fc, -0x000026c2,0x00002700,0x000026fd,0x000300f7, -0x000026c8,0x00000000,0x000400fa,0x00002702, -0x000026c6,0x000026c8,0x000200f8,0x000026c6, -0x000200f9,0x000026f6,0x000200f8,0x000026c8, -0x000200f9,0x000026c9,0x000200f8,0x000026c9, -0x000700f5,0x00000006,0x00005afd,0x0000012b, -0x000026c8,0x000026f3,0x000026cd,0x000500b0, -0x0000002f,0x000026cc,0x00005afd,0x00000437, -0x000400f6,0x000026f4,0x000026cd,0x00000000, -0x000400fa,0x000026cc,0x000026cd,0x000026f4, -0x000200f8,0x000026cd,0x00050084,0x00000006, -0x000026cf,0x000001a2,0x00005afd,0x00050095, -0x00000130,0x0000271b,0x000026fb,0x000026cf, -0x00050051,0x00000006,0x0000271c,0x0000271b, -0x00000001,0x00050051,0x00000006,0x0000271d, -0x0000271b,0x00000000,0x00050051,0x00000006, -0x00002720,0x000026c4,0x00000001,0x00050080, -0x00000006,0x00002722,0x00002720,0x0000271c, -0x00050050,0x00000007,0x00002723,0x0000271d, -0x00002722,0x0004007c,0x00000014,0x00002713, -0x00002723,0x00060041,0x0000015f,0x0000270a, -0x00002713,0x0000015e,0x0000015e,0x0006003d, -0x00000006,0x0000270b,0x0000270a,0x00000002, -0x00000004,0x0004007c,0x00000027,0x000026d4, -0x0000270b,0x00050080,0x00000006,0x000026d6, -0x000026cf,0x000000df,0x00050095,0x00000130, -0x0000273c,0x000026fb,0x000026d6,0x00050051, -0x00000006,0x0000273d,0x0000273c,0x00000001, -0x00050051,0x00000006,0x0000273e,0x0000273c, -0x00000000,0x00050080,0x00000006,0x00002743, -0x00002720,0x0000273d,0x00050050,0x00000007, -0x00002744,0x0000273e,0x00002743,0x0004007c, -0x00000014,0x00002734,0x00002744,0x00060041, -0x0000015f,0x0000272b,0x00002734,0x0000015e, -0x0000015e,0x0006003d,0x00000006,0x0000272c, -0x0000272b,0x00000002,0x00000004,0x0004007c, -0x00000027,0x000026da,0x0000272c,0x00050080, -0x00000006,0x000026dc,0x000026cf,0x00000194, -0x00050095,0x00000130,0x0000275d,0x000026fb, -0x000026dc,0x00050051,0x00000006,0x0000275e, -0x0000275d,0x00000001,0x00050051,0x00000006, -0x0000275f,0x0000275d,0x00000000,0x00050080, -0x00000006,0x00002764,0x00002720,0x0000275e, -0x00050050,0x00000007,0x00002765,0x0000275f, -0x00002764,0x0004007c,0x00000014,0x00002755, -0x00002765,0x00060041,0x0000015f,0x0000274c, -0x00002755,0x0000015e,0x0000015e,0x0006003d, -0x00000006,0x0000274d,0x0000274c,0x00000002, -0x00000004,0x0004007c,0x00000027,0x000026e0, -0x0000274d,0x00050080,0x00000006,0x000026e2, -0x000026cf,0x0000019b,0x00050095,0x00000130, -0x0000277e,0x000026fb,0x000026e2,0x00050051, -0x00000006,0x0000277f,0x0000277e,0x00000001, -0x00050051,0x00000006,0x00002780,0x0000277e, -0x00000000,0x00050080,0x00000006,0x00002785, -0x00002720,0x0000277f,0x00050050,0x00000007, -0x00002786,0x00002780,0x00002785,0x0004007c, -0x00000014,0x00002776,0x00002786,0x00060041, -0x0000015f,0x0000276d,0x00002776,0x0000015e, -0x0000015e,0x0006003d,0x00000006,0x0000276e, -0x0000276d,0x00000002,0x00000004,0x0004007c, -0x00000027,0x000026e6,0x0000276e,0x00070050, -0x0000043c,0x000026e7,0x000026d4,0x000026da, -0x000026e0,0x000026e6,0x0008004f,0x00000063, -0x000026ea,0x000026e7,0x000026e7,0x00000000, -0x00000001,0x00000002,0x00050094,0x00000027, -0x000026ec,0x000026ea,0x0000263d,0x00050081, -0x00000027,0x000026ef,0x000026ec,0x000026e6, -0x00050041,0x00000028,0x000026f0,0x000026bf, -0x00005afd,0x0003003e,0x000026f0,0x000026ef, -0x00050080,0x00000006,0x000026f3,0x00005afd, -0x0000022b,0x000200f9,0x000026c9,0x000200f8, -0x000026f4,0x0004003d,0x00000063,0x000026f5, -0x000026bf,0x000200f9,0x000026f6,0x000200f8, -0x000026f6,0x000700f5,0x00000063,0x00005afe, -0x0000263d,0x000026c6,0x000026f5,0x000026f4, -0x00050041,0x00000064,0x00002511,0x000024d6, -0x00005af0,0x0003003e,0x00002511,0x00005afe, -0x000200f9,0x00002512,0x000200f8,0x00002512, -0x00050080,0x00000006,0x00002514,0x00005af0, -0x0000022b,0x000200f9,0x00002504,0x000200f8, -0x00002515,0x00050041,0x00000182,0x00002516, -0x00000180,0x00000488,0x0004003d,0x00000006, -0x00002517,0x00002516,0x00050080,0x00000006, -0x00002519,0x00002517,0x000011de,0x00050041, -0x00000182,0x0000251a,0x00000180,0x00000311, -0x0004003d,0x00000006,0x0000251b,0x0000251a, -0x00050084,0x00000006,0x0000251d,0x0000018b, -0x00002519,0x00050080,0x00000006,0x0000251e, -0x0000251b,0x0000251d,0x000200f9,0x0000251f, -0x000200f8,0x0000251f,0x000700f5,0x00000006, -0x00005af1,0x0000012b,0x00002515,0x00002546, -0x00002523,0x000500b0,0x0000002f,0x00002522, -0x00005af1,0x00000437,0x000400f6,0x00002547, -0x00002523,0x00000000,0x000400fa,0x00002522, -0x00002523,0x00002547,0x000200f8,0x00002523, -0x00050084,0x00000006,0x00002526,0x0000019b, -0x00005af1,0x00050080,0x00000006,0x00002527, -0x0000251e,0x00002526,0x00050041,0x0000022d, -0x00002529,0x00000180,0x0000015e,0x0004003d, -0x00000007,0x0000252a,0x00002529,0x00060041, -0x00000028,0x0000252b,0x000024d6,0x00005af1, -0x0000012b,0x0004003d,0x00000027,0x0000252c, -0x0000252b,0x0004007c,0x00000006,0x0000278c, -0x0000252c,0x00050051,0x00000006,0x000027a5, -0x0000252a,0x00000000,0x00050095,0x00000130, -0x000027a7,0x000027a5,0x00002527,0x00050051, -0x00000006,0x000027a8,0x000027a7,0x00000001, -0x00050051,0x00000006,0x000027a9,0x000027a7, -0x00000000,0x00050051,0x00000006,0x000027ac, -0x0000252a,0x00000001,0x00050080,0x00000006, -0x000027ae,0x000027ac,0x000027a8,0x00050050, -0x00000007,0x000027af,0x000027a9,0x000027ae, -0x0004007c,0x00000014,0x0000279f,0x000027af, -0x00060041,0x0000015f,0x00002797,0x0000279f, -0x0000015e,0x0000015e,0x0005003e,0x00002797, -0x0000278c,0x00000002,0x00000004,0x00050080, -0x00000006,0x00002532,0x00002527,0x000000df, -0x00060041,0x00000028,0x00002536,0x000024d6, -0x00005af1,0x00000135,0x0004003d,0x00000027, -0x00002537,0x00002536,0x0004007c,0x00000006, -0x000027b5,0x00002537,0x00050095,0x00000130, -0x000027d0,0x000027a5,0x00002532,0x00050051, -0x00000006,0x000027d1,0x000027d0,0x00000001, -0x00050051,0x00000006,0x000027d2,0x000027d0, -0x00000000,0x00050080,0x00000006,0x000027d7, -0x000027ac,0x000027d1,0x00050050,0x00000007, -0x000027d8,0x000027d2,0x000027d7,0x0004007c, -0x00000014,0x000027c8,0x000027d8,0x00060041, -0x0000015f,0x000027c0,0x000027c8,0x0000015e, -0x0000015e,0x0005003e,0x000027c0,0x000027b5, -0x00000002,0x00000004,0x00050080,0x00000006, -0x0000253d,0x00002527,0x00000194,0x00060041, -0x00000028,0x00002541,0x000024d6,0x00005af1, -0x00000247,0x0004003d,0x00000027,0x00002542, -0x00002541,0x0004007c,0x00000006,0x000027de, -0x00002542,0x00050095,0x00000130,0x000027f9, -0x000027a5,0x0000253d,0x00050051,0x00000006, -0x000027fa,0x000027f9,0x00000001,0x00050051, -0x00000006,0x000027fb,0x000027f9,0x00000000, -0x00050080,0x00000006,0x00002800,0x000027ac, -0x000027fa,0x00050050,0x00000007,0x00002801, -0x000027fb,0x00002800,0x0004007c,0x00000014, -0x000027f1,0x00002801,0x00060041,0x0000015f, -0x000027e9,0x000027f1,0x0000015e,0x0000015e, -0x0005003e,0x000027e9,0x000027de,0x00000002, -0x00000004,0x00050080,0x00000006,0x00002546, -0x00005af1,0x0000022b,0x000200f9,0x0000251f, -0x000200f8,0x00002547,0x00050080,0x00000006, -0x00002549,0x0000251e,0x000004c7,0x00050041, -0x0000022d,0x0000254a,0x00000180,0x0000015e, -0x0004003d,0x00000007,0x0000254b,0x0000254a, -0x00060041,0x00000028,0x0000254c,0x000024d6, -0x000002dc,0x0000012b,0x0004003d,0x00000027, -0x0000254d,0x0000254c,0x0004007c,0x00000006, -0x00002807,0x0000254d,0x00050051,0x00000006, -0x00002820,0x0000254b,0x00000000,0x00050095, -0x00000130,0x00002822,0x00002820,0x00002549, -0x00050051,0x00000006,0x00002823,0x00002822, -0x00000001,0x00050051,0x00000006,0x00002824, -0x00002822,0x00000000,0x00050051,0x00000006, -0x00002827,0x0000254b,0x00000001,0x00050080, -0x00000006,0x00002829,0x00002827,0x00002823, -0x00050050,0x00000007,0x0000282a,0x00002824, -0x00002829,0x0004007c,0x00000014,0x0000281a, -0x0000282a,0x00060041,0x0000015f,0x00002812, -0x0000281a,0x0000015e,0x0000015e,0x0005003e, -0x00002812,0x00002807,0x00000002,0x00000004, -0x00050080,0x00000006,0x00002550,0x0000251e, -0x000004d2,0x00060041,0x00000028,0x00002553, -0x000024d6,0x000002dc,0x00000135,0x0004003d, -0x00000027,0x00002554,0x00002553,0x0004007c, -0x00000006,0x00002830,0x00002554,0x00050095, -0x00000130,0x0000284b,0x00002820,0x00002550, -0x00050051,0x00000006,0x0000284c,0x0000284b, -0x00000001,0x00050051,0x00000006,0x0000284d, -0x0000284b,0x00000000,0x00050080,0x00000006, -0x00002852,0x00002827,0x0000284c,0x00050050, -0x00000007,0x00002853,0x0000284d,0x00002852, -0x0004007c,0x00000014,0x00002843,0x00002853, -0x00060041,0x0000015f,0x0000283b,0x00002843, -0x0000015e,0x0000015e,0x0005003e,0x0000283b, -0x00002830,0x00000002,0x00000004,0x00050080, -0x00000006,0x00002557,0x0000251e,0x000004dd, -0x00060041,0x00000028,0x0000255a,0x000024d6, -0x000002dc,0x00000247,0x0004003d,0x00000027, -0x0000255b,0x0000255a,0x0004007c,0x00000006, -0x00002859,0x0000255b,0x00050095,0x00000130, -0x00002874,0x00002820,0x00002557,0x00050051, -0x00000006,0x00002875,0x00002874,0x00000001, -0x00050051,0x00000006,0x00002876,0x00002874, -0x00000000,0x00050080,0x00000006,0x0000287b, -0x00002827,0x00002875,0x00050050,0x00000007, -0x0000287c,0x00002876,0x0000287b,0x0004007c, -0x00000014,0x0000286c,0x0000287c,0x00060041, -0x0000015f,0x00002864,0x0000286c,0x0000015e, -0x0000015e,0x0005003e,0x00002864,0x00002859, -0x00000002,0x00000004,0x00050080,0x00000006, -0x0000255e,0x0000251e,0x000004e8,0x00050041, -0x00000182,0x00002561,0x00000180,0x000004ea, -0x0004003d,0x00000006,0x00002562,0x00002561, -0x00050095,0x00000130,0x00002894,0x00002820, -0x0000255e,0x00050051,0x00000006,0x00002895, -0x00002894,0x00000001,0x00050051,0x00000006, -0x00002896,0x00002894,0x00000000,0x00050080, -0x00000006,0x0000289b,0x00002827,0x00002895, -0x00050050,0x00000007,0x0000289c,0x00002896, -0x0000289b,0x0004007c,0x00000014,0x0000288c, -0x0000289c,0x00060041,0x0000015f,0x00002884, -0x0000288c,0x0000015e,0x0000015e,0x0005003e, -0x00002884,0x00002562,0x00000002,0x00000004, -0x00050080,0x00000006,0x00002565,0x0000251e, -0x000004f4,0x00050095,0x00000130,0x000028b4, -0x00002820,0x00002565,0x00050051,0x00000006, -0x000028b5,0x000028b4,0x00000001,0x00050051, -0x00000006,0x000028b6,0x000028b4,0x00000000, -0x00050080,0x00000006,0x000028bb,0x00002827, -0x000028b5,0x00050050,0x00000007,0x000028bc, -0x000028b6,0x000028bb,0x0004007c,0x00000014, -0x000028ac,0x000028bc,0x00060041,0x0000015f, -0x000028a4,0x000028ac,0x0000015e,0x0000015e, -0x0005003e,0x000028a4,0x000011de,0x00000002, -0x00000004,0x00050080,0x00000006,0x0000256b, -0x0000251e,0x000004fe,0x00050095,0x00000130, -0x000028d4,0x00002820,0x0000256b,0x00050051, -0x00000006,0x000028d5,0x000028d4,0x00000001, -0x00050051,0x00000006,0x000028d6,0x000028d4, -0x00000000,0x00050080,0x00000006,0x000028db, -0x00002827,0x000028d5,0x00050050,0x00000007, -0x000028dc,0x000028d6,0x000028db,0x0004007c, -0x00000014,0x000028cc,0x000028dc,0x00060041, -0x0000015f,0x000028c4,0x000028cc,0x0000015e, -0x0000015e,0x0005003e,0x000028c4,0x00000500, -0x00000002,0x00000004,0x00050080,0x00000006, -0x00002570,0x0000251e,0x00000508,0x00050095, -0x00000130,0x000028f4,0x00002820,0x00002570, -0x00050051,0x00000006,0x000028f5,0x000028f4, -0x00000001,0x00050051,0x00000006,0x000028f6, -0x000028f4,0x00000000,0x00050080,0x00000006, -0x000028fb,0x00002827,0x000028f5,0x00050050, -0x00000007,0x000028fc,0x000028f6,0x000028fb, -0x0004007c,0x00000014,0x000028ec,0x000028fc, -0x00060041,0x0000015f,0x000028e4,0x000028ec, -0x0000015e,0x0000015e,0x0005003e,0x000028e4, -0x0000050a,0x00000002,0x00000004,0x00050041, -0x00000064,0x00002574,0x000024d6,0x0000015e, -0x0004003d,0x00000063,0x00002575,0x00002574, -0x0004009c,0x00000514,0x00002576,0x00002575, -0x0004009a,0x0000002f,0x00002577,0x00002576, -0x000400a8,0x0000002f,0x00002578,0x00002577, -0x000300f7,0x0000257e,0x00000000,0x000400fa, -0x00002578,0x00002579,0x0000257e,0x000200f8, -0x00002579,0x00050041,0x00000064,0x0000257a, -0x000024d6,0x0000022b,0x0004003d,0x00000063, -0x0000257b,0x0000257a,0x0004009c,0x00000514, -0x0000257c,0x0000257b,0x0004009a,0x0000002f, -0x0000257d,0x0000257c,0x000200f9,0x0000257e, -0x000200f8,0x0000257e,0x000700f5,0x0000002f, -0x0000257f,0x00002577,0x00002547,0x0000257d, -0x00002579,0x000400a8,0x0000002f,0x00002580, -0x0000257f,0x000300f7,0x00002586,0x00000000, -0x000400fa,0x00002580,0x00002581,0x00002586, -0x000200f8,0x00002581,0x00050041,0x00000064, -0x00002582,0x000024d6,0x000002dc,0x0004003d, -0x00000063,0x00002583,0x00002582,0x0004009c, -0x00000514,0x00002584,0x00002583,0x0004009a, -0x0000002f,0x00002585,0x00002584,0x000200f9, -0x00002586,0x000200f8,0x00002586,0x000700f5, -0x0000002f,0x00002587,0x0000257f,0x0000257e, -0x00002585,0x00002581,0x0004003d,0x00000063, -0x00002589,0x00002574,0x00050041,0x00000064, -0x0000258a,0x000024d6,0x0000022b,0x0004003d, -0x00000063,0x0000258b,0x0000258a,0x0007000c, -0x00000063,0x0000258c,0x00000001,0x00000025, -0x00002589,0x0000258b,0x00050041,0x00000064, -0x0000258d,0x000024d6,0x000002dc,0x0004003d, -0x00000063,0x0000258e,0x0000258d,0x0007000c, -0x00000063,0x0000258f,0x00000001,0x00000025, -0x0000258c,0x0000258e,0x0004003d,0x00000063, -0x00002591,0x00002574,0x0004003d,0x00000063, -0x00002593,0x0000258a,0x0007000c,0x00000063, -0x00002594,0x00000001,0x00000028,0x00002591, -0x00002593,0x0004003d,0x00000063,0x00002596, -0x0000258d,0x0007000c,0x00000063,0x00002597, -0x00000001,0x00000028,0x00002594,0x00002596, -0x00060050,0x00000514,0x00005ce5,0x00002587, -0x00002587,0x00002587,0x000600a9,0x00000063, -0x00005ce6,0x00005ce5,0x00005cc2,0x00002597, -0x000600a9,0x00000063,0x00005ce8,0x00005ce5, -0x0000053d,0x0000258f,0x00050041,0x00000182, -0x0000294c,0x00000180,0x00000181,0x0004003d, -0x00000006,0x0000294d,0x0000294c,0x00050084, -0x00000006,0x0000294e,0x000001a2,0x0000294d, -0x00050080,0x00000006,0x0000294f,0x0000018b, -0x0000294e,0x00050080,0x00000006,0x00002955, -0x0000294d,0x00005cc3,0x00050086,0x00000006, -0x00002956,0x00002955,0x00000185,0x00050084, -0x00000006,0x00002948,0x0000018b,0x00002956, -0x00050080,0x00000006,0x00002949,0x0000294f, -0x00002948,0x00050080,0x00000006,0x00002943, -0x00002949,0x00002948,0x00050084,0x00000006, -0x00002913,0x000001b6,0x00002519,0x00050080, -0x00000006,0x00002914,0x00002943,0x00002913, -0x00050041,0x0000022d,0x00002915,0x00000180, -0x0000022b,0x0004003d,0x00000007,0x00002916, -0x00002915,0x00050051,0x00000027,0x00002919, -0x00005ce8,0x00000000,0x0004007c,0x00000006, -0x00002963,0x00002919,0x00050051,0x00000006, -0x0000297c,0x00002916,0x00000000,0x00050095, -0x00000130,0x0000297e,0x0000297c,0x00002914, -0x00050051,0x00000006,0x0000297f,0x0000297e, -0x00000001,0x00050051,0x00000006,0x00002980, -0x0000297e,0x00000000,0x00050051,0x00000006, -0x00002983,0x00002916,0x00000001,0x00050080, -0x00000006,0x00002985,0x00002983,0x0000297f, -0x00050050,0x00000007,0x00002986,0x00002980, -0x00002985,0x0004007c,0x00000014,0x00002976, -0x00002986,0x00060041,0x0000015f,0x0000296e, -0x00002976,0x0000015e,0x0000015e,0x0005003e, -0x0000296e,0x00002963,0x00000002,0x00000004, -0x00050080,0x00000006,0x0000291c,0x00002914, -0x000000df,0x00050051,0x00000027,0x00002920, -0x00005ce8,0x00000001,0x0004007c,0x00000006, -0x0000298c,0x00002920,0x00050095,0x00000130, -0x000029a7,0x0000297c,0x0000291c,0x00050051, -0x00000006,0x000029a8,0x000029a7,0x00000001, -0x00050051,0x00000006,0x000029a9,0x000029a7, -0x00000000,0x00050080,0x00000006,0x000029ae, -0x00002983,0x000029a8,0x00050050,0x00000007, -0x000029af,0x000029a9,0x000029ae,0x0004007c, -0x00000014,0x0000299f,0x000029af,0x00060041, -0x0000015f,0x00002997,0x0000299f,0x0000015e, -0x0000015e,0x0005003e,0x00002997,0x0000298c, -0x00000002,0x00000004,0x00050080,0x00000006, -0x00002923,0x00002914,0x00000194,0x00050051, -0x00000027,0x00002927,0x00005ce8,0x00000002, -0x0004007c,0x00000006,0x000029b5,0x00002927, -0x00050095,0x00000130,0x000029d0,0x0000297c, -0x00002923,0x00050051,0x00000006,0x000029d1, -0x000029d0,0x00000001,0x00050051,0x00000006, -0x000029d2,0x000029d0,0x00000000,0x00050080, -0x00000006,0x000029d7,0x00002983,0x000029d1, -0x00050050,0x00000007,0x000029d8,0x000029d2, -0x000029d7,0x0004007c,0x00000014,0x000029c8, -0x000029d8,0x00060041,0x0000015f,0x000029c0, -0x000029c8,0x0000015e,0x0000015e,0x0005003e, -0x000029c0,0x000029b5,0x00000002,0x00000004, -0x00050080,0x00000006,0x0000292a,0x00002914, -0x0000019b,0x00050051,0x00000027,0x0000292e, -0x00005ce6,0x00000000,0x0004007c,0x00000006, -0x000029de,0x0000292e,0x00050095,0x00000130, -0x000029f9,0x0000297c,0x0000292a,0x00050051, -0x00000006,0x000029fa,0x000029f9,0x00000001, -0x00050051,0x00000006,0x000029fb,0x000029f9, -0x00000000,0x00050080,0x00000006,0x00002a00, -0x00002983,0x000029fa,0x00050050,0x00000007, -0x00002a01,0x000029fb,0x00002a00,0x0004007c, -0x00000014,0x000029f1,0x00002a01,0x00060041, -0x0000015f,0x000029e9,0x000029f1,0x0000015e, -0x0000015e,0x0005003e,0x000029e9,0x000029de, -0x00000002,0x00000004,0x00050080,0x00000006, -0x00002931,0x00002914,0x000001a2,0x00050051, -0x00000027,0x00002935,0x00005ce6,0x00000001, -0x0004007c,0x00000006,0x00002a07,0x00002935, -0x00050095,0x00000130,0x00002a22,0x0000297c, -0x00002931,0x00050051,0x00000006,0x00002a23, -0x00002a22,0x00000001,0x00050051,0x00000006, -0x00002a24,0x00002a22,0x00000000,0x00050080, -0x00000006,0x00002a29,0x00002983,0x00002a23, -0x00050050,0x00000007,0x00002a2a,0x00002a24, -0x00002a29,0x0004007c,0x00000014,0x00002a1a, -0x00002a2a,0x00060041,0x0000015f,0x00002a12, -0x00002a1a,0x0000015e,0x0000015e,0x0005003e, -0x00002a12,0x00002a07,0x00000002,0x00000004, -0x00050080,0x00000006,0x00002938,0x00002914, -0x00000260,0x00050051,0x00000027,0x0000293c, -0x00005ce6,0x00000002,0x0004007c,0x00000006, -0x00002a30,0x0000293c,0x00050095,0x00000130, -0x00002a4b,0x0000297c,0x00002938,0x00050051, -0x00000006,0x00002a4c,0x00002a4b,0x00000001, -0x00050051,0x00000006,0x00002a4d,0x00002a4b, -0x00000000,0x00050080,0x00000006,0x00002a52, -0x00002983,0x00002a4c,0x00050050,0x00000007, -0x00002a53,0x00002a4d,0x00002a52,0x0004007c, -0x00000014,0x00002a43,0x00002a53,0x00060041, -0x0000015f,0x00002a3b,0x00002a43,0x0000015e, -0x0000015e,0x0005003e,0x00002a3b,0x00002a30, -0x00000002,0x00000004,0x000300f7,0x00002a93, -0x00000000,0x000300fb,0x0000012b,0x00002a62, -0x000200f8,0x00002a62,0x000500bc,0x0000002f, -0x00002a9a,0x00002919,0x0000292e,0x000300f7, -0x00002aa1,0x00000000,0x000400fa,0x00002a9a, -0x00002a9b,0x00002aa1,0x000200f8,0x00002a9b, -0x000500bc,0x0000002f,0x00002aa0,0x00002920, -0x00002935,0x000200f9,0x00002aa1,0x000200f8, -0x00002aa1,0x000700f5,0x0000002f,0x00002aa2, -0x00002a9a,0x00002a62,0x00002aa0,0x00002a9b, -0x000300f7,0x00002aa9,0x00000000,0x000400fa, -0x00002aa2,0x00002aa3,0x00002aa9,0x000200f8, -0x00002aa3,0x000500bc,0x0000002f,0x00002aa8, -0x00002927,0x0000293c,0x000200f9,0x00002aa9, -0x000200f8,0x00002aa9,0x000700f5,0x0000002f, -0x00002aaa,0x00002aa2,0x00002aa1,0x00002aa8, -0x00002aa3,0x000400a8,0x0000002f,0x00002aab, -0x00002aaa,0x000300f7,0x00002a67,0x00000000, -0x000400fa,0x00002aab,0x00002a66,0x00002a67, -0x000200f8,0x00002a66,0x000200f9,0x00002a93, -0x000200f8,0x00002a67,0x00050081,0x00000063, -0x00002a6a,0x00005ce8,0x00005ce6,0x0005008e, -0x00000063,0x00002a6b,0x00002a6a,0x000002c4, -0x00050095,0x00000130,0x00002abb,0x0000297c, -0x0000012b,0x00050051,0x00000006,0x00002abc, -0x00002abb,0x00000001,0x00050051,0x00000006, -0x00002abd,0x00002abb,0x00000000,0x00050080, -0x00000006,0x00002ac2,0x00002983,0x00002abc, -0x00050050,0x00000007,0x00002ac3,0x00002abd, -0x00002ac2,0x0004007c,0x00000014,0x00002ab3, -0x00002ac3,0x00060041,0x0000015f,0x00002a70, -0x00002ab3,0x0000015e,0x0000015e,0x00050051, -0x00000027,0x00002a72,0x00002a6b,0x00000000, -0x0004007c,0x00000006,0x00002ac9,0x00002a72, -0x000500c7,0x00000006,0x00002acb,0x00002ac9, -0x00000208,0x000500ab,0x0000002f,0x00002acc, -0x00002acb,0x0000012b,0x000300f7,0x00002ad3, -0x00000000,0x000400fa,0x00002acc,0x00002acd, -0x00002ad0,0x000200f8,0x00002ad0,0x000500c5, -0x00000006,0x00002ad2,0x00002ac9,0x00000208, -0x000200f9,0x00002ad3,0x000200f8,0x00002acd, -0x000400c8,0x00000006,0x00002acf,0x00002ac9, -0x000200f9,0x00002ad3,0x000200f8,0x00002ad3, -0x000700f5,0x00000006,0x00005af4,0x00002acf, -0x00002acd,0x00002ad2,0x00002ad0,0x000700ed, -0x00000006,0x00002a74,0x00002a70,0x00000135, -0x0000012b,0x00005af4,0x00060041,0x0000015f, -0x00002a76,0x00002ab3,0x0000015e,0x0000022b, -0x00050051,0x00000027,0x00002a78,0x00002a6b, -0x00000001,0x0004007c,0x00000006,0x00002ada, -0x00002a78,0x000500c7,0x00000006,0x00002adc, -0x00002ada,0x00000208,0x000500ab,0x0000002f, -0x00002add,0x00002adc,0x0000012b,0x000300f7, -0x00002ae4,0x00000000,0x000400fa,0x00002add, -0x00002ade,0x00002ae1,0x000200f8,0x00002ae1, -0x000500c5,0x00000006,0x00002ae3,0x00002ada, -0x00000208,0x000200f9,0x00002ae4,0x000200f8, -0x00002ade,0x000400c8,0x00000006,0x00002ae0, -0x00002ada,0x000200f9,0x00002ae4,0x000200f8, -0x00002ae4,0x000700f5,0x00000006,0x00005af5, -0x00002ae0,0x00002ade,0x00002ae3,0x00002ae1, -0x000700ed,0x00000006,0x00002a7a,0x00002a76, -0x00000135,0x0000012b,0x00005af5,0x00060041, -0x0000015f,0x00002a7c,0x00002ab3,0x0000015e, -0x000002dc,0x00050051,0x00000027,0x00002a7e, -0x00002a6b,0x00000002,0x0004007c,0x00000006, -0x00002aeb,0x00002a7e,0x000500c7,0x00000006, -0x00002aed,0x00002aeb,0x00000208,0x000500ab, -0x0000002f,0x00002aee,0x00002aed,0x0000012b, -0x000300f7,0x00002af5,0x00000000,0x000400fa, -0x00002aee,0x00002aef,0x00002af2,0x000200f8, -0x00002af2,0x000500c5,0x00000006,0x00002af4, -0x00002aeb,0x00000208,0x000200f9,0x00002af5, -0x000200f8,0x00002aef,0x000400c8,0x00000006, -0x00002af1,0x00002aeb,0x000200f9,0x00002af5, -0x000200f8,0x00002af5,0x000700f5,0x00000006, -0x00005af6,0x00002af1,0x00002aef,0x00002af4, -0x00002af2,0x000700ed,0x00000006,0x00002a80, -0x00002a7c,0x00000135,0x0000012b,0x00005af6, -0x00060041,0x0000015f,0x00002a82,0x00002ab3, -0x0000015e,0x000002e4,0x000300f7,0x00002b06, -0x00000000,0x000400fa,0x00002acc,0x00002b00, -0x00002b03,0x000200f8,0x00002b03,0x000500c5, -0x00000006,0x00002b05,0x00002ac9,0x00000208, -0x000200f9,0x00002b06,0x000200f8,0x00002b00, -0x000400c8,0x00000006,0x00002b02,0x00002ac9, -0x000200f9,0x00002b06,0x000200f8,0x00002b06, -0x000700f5,0x00000006,0x00005af7,0x00002b02, -0x00002b00,0x00002b05,0x00002b03,0x000700ef, -0x00000006,0x00002a86,0x00002a82,0x00000135, -0x0000012b,0x00005af7,0x00060041,0x0000015f, -0x00002a88,0x00002ab3,0x0000015e,0x000002ec, -0x000300f7,0x00002b17,0x00000000,0x000400fa, -0x00002add,0x00002b11,0x00002b14,0x000200f8, -0x00002b14,0x000500c5,0x00000006,0x00002b16, -0x00002ada,0x00000208,0x000200f9,0x00002b17, -0x000200f8,0x00002b11,0x000400c8,0x00000006, -0x00002b13,0x00002ada,0x000200f9,0x00002b17, -0x000200f8,0x00002b17,0x000700f5,0x00000006, -0x00005af8,0x00002b13,0x00002b11,0x00002b16, -0x00002b14,0x000700ef,0x00000006,0x00002a8c, -0x00002a88,0x00000135,0x0000012b,0x00005af8, -0x00060041,0x0000015f,0x00002a8e,0x00002ab3, -0x0000015e,0x000002f4,0x000300f7,0x00002b28, -0x00000000,0x000400fa,0x00002aee,0x00002b22, -0x00002b25,0x000200f8,0x00002b25,0x000500c5, -0x00000006,0x00002b27,0x00002aeb,0x00000208, -0x000200f9,0x00002b28,0x000200f8,0x00002b22, -0x000400c8,0x00000006,0x00002b24,0x00002aeb, -0x000200f9,0x00002b28,0x000200f8,0x00002b28, -0x000700f5,0x00000006,0x00005af9,0x00002b24, -0x00002b22,0x00002b27,0x00002b25,0x000700ef, -0x00000006,0x00002a92,0x00002a8e,0x00000135, -0x0000012b,0x00005af9,0x000200f9,0x00002a93, -0x000200f8,0x00002a93,0x000200f9,0x000012bf, -0x000200f8,0x000012bf,0x000200f9,0x00001299, -0x000200f8,0x00001298,0x00050041,0x00000182, -0x0000129a,0x00000180,0x00000fbf,0x0004003d, -0x00000006,0x0000129b,0x0000129a,0x00050084, -0x00000006,0x0000129d,0x000000df,0x000011de, -0x00050080,0x00000006,0x0000129e,0x0000129b, -0x0000129d,0x00050041,0x0000022d,0x000012a0, -0x00000180,0x0000015e,0x0004003d,0x00000007, -0x000012a1,0x000012a0,0x00050051,0x00000006, -0x0000248a,0x000012a1,0x00000000,0x00050095, -0x00000130,0x0000248c,0x0000248a,0x0000129e, -0x00050051,0x00000006,0x0000248d,0x0000248c, -0x00000001,0x00050051,0x00000006,0x0000248e, -0x0000248c,0x00000000,0x00050051,0x00000006, -0x00002491,0x000012a1,0x00000001,0x00050080, -0x00000006,0x00002493,0x00002491,0x0000248d, -0x00050050,0x00000007,0x00002494,0x0000248e, -0x00002493,0x0004007c,0x00000014,0x00002484, -0x00002494,0x00060041,0x0000015f,0x0000247c, -0x00002484,0x0000015e,0x0000015e,0x0005003e, -0x0000247c,0x00000500,0x00000002,0x00000004, -0x000500b0,0x0000002f,0x000012a6,0x000011de, -0x00000437,0x000300f7,0x000012a8,0x00000000, -0x000400fa,0x000012a6,0x000012a7,0x000012a8, -0x000200f8,0x000012a7,0x00050041,0x0000022d, -0x000012ac,0x00000180,0x0000022b,0x0004003d, -0x00000007,0x000012ad,0x000012ac,0x00050051, -0x00000006,0x000024aa,0x000012ad,0x00000000, -0x00050095,0x00000130,0x000024ac,0x000024aa, -0x0000129d,0x00050051,0x00000006,0x000024ad, -0x000024ac,0x00000001,0x00050051,0x00000006, -0x000024ae,0x000024ac,0x00000000,0x00050051, -0x00000006,0x000024b1,0x000012ad,0x00000001, -0x00050080,0x00000006,0x000024b3,0x000024b1, -0x000024ad,0x00050050,0x00000007,0x000024b4, -0x000024ae,0x000024b3,0x0004007c,0x00000014, -0x000024a4,0x000024b4,0x00060041,0x0000015f, -0x0000249c,0x000024a4,0x0000015e,0x0000015e, -0x0005003e,0x0000249c,0x00000500,0x00000002, -0x00000004,0x00050080,0x00000006,0x000012b3, -0x0000019b,0x0000129d,0x00050095,0x00000130, -0x000024cc,0x000024aa,0x000012b3,0x00050051, -0x00000006,0x000024cd,0x000024cc,0x00000001, -0x00050051,0x00000006,0x000024ce,0x000024cc, -0x00000000,0x00050080,0x00000006,0x000024d3, -0x000024b1,0x000024cd,0x00050050,0x00000007, -0x000024d4,0x000024ce,0x000024d3,0x0004007c, -0x00000014,0x000024c4,0x000024d4,0x00060041, -0x0000015f,0x000024bc,0x000024c4,0x0000015e, -0x0000015e,0x0005003e,0x000024bc,0x0000012b, -0x00000002,0x00000004,0x000200f9,0x000012a8, -0x000200f8,0x000012a8,0x000200f9,0x00001299, -0x000200f8,0x00001299,0x000200f9,0x000012fe, -0x000200f8,0x000012fe,0x000100fd,0x00010038} diff --git a/runtime/src/xdxr_build_spv.h b/runtime/src/xdxr_build_spv.h deleted file mode 100644 index 4164b09b7..000000000 --- a/runtime/src/xdxr_build_spv.h +++ /dev/null @@ -1,11 +0,0 @@ -#pragma once -#include - -namespace leonida { - -// xdxr_build.comp compiled with: glslc --target-env=vulkan1.2 -O -mfmt=c xdxr_build.comp -o xdxr_build.inc -inline constexpr std::uint32_t xdxr_build_spirv[] = -#include "xdxr_build.inc" -; - -} // namespace leonida diff --git a/runtime/src/xdxr_descs.h b/runtime/src/xdxr_descs.h deleted file mode 100644 index b44ce0372..000000000 --- a/runtime/src/xdxr_descs.h +++ /dev/null @@ -1,125 +0,0 @@ -// Xbox XDXR build descriptions as XboxBvhBuilder.dll (package 1.0.2.1) reads them. docs/xdxr.md gives the evidence -// for every field. Names come from the DLL's exported symbols or the public D3D12 structs they extend; the stream -// record fields have no names in the DLL, so they are named by offset. Plain types only: this builds without the -// Windows SDK, and xdxr_descs_test checks it against d3d12.h where that is available. -#pragma once - -#include -#include - -namespace leonida::xdxr { - -// D3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_INPUTS (public layout). -struct BuildInputs { - uint32_t type; // D3D12_RAYTRACING_ACCELERATION_STRUCTURE_TYPE: 0 top level, 1 bottom level - uint32_t flags; // D3D12_RAYTRACING_ACCELERATION_STRUCTURE_BUILD_FLAGS - uint32_t num_descs; - uint32_t descs_layout; // D3D12_ELEMENTS_LAYOUT - uint64_t descs; // InstanceDescs (GPU VA) or pGeometryDescs / ppGeometryDescs -}; - -// D3D12_RAYTRACING_ACCELERATION_STRUCTURE_POSTBUILD_INFO_DESC (public layout). -struct PostbuildInfoDesc { - uint64_t dest_buffer; - uint32_t info_type; - uint32_t padding; -}; - -// D3D12XBOX_XDXR_STREAM_DESC: SizeInBytes of 16-byte StreamRecords at pStream. -struct StreamDesc { - uint64_t size_in_bytes; - const void* stream; -}; - -// One record of the stream; its type decides how the 12 bytes after it are read. -struct StreamRecord { - uint32_t type; - uint8_t payload[12]; -}; - -struct StreamRecord0 { // type 0 - uint32_t type; - float value_04; // default -1.0 - float value_08; // negative: default_record0_value_08(flags) - uint8_t bytes_0c[4]; // default 0 -}; - -struct StreamRecord1 { // type 1 - uint32_t type; - uint8_t unread_04[9]; - uint8_t level_0d; // bottom level only; 0 keeps the default, otherwise min(level, 15) - uint8_t flag_0e; // top level only - uint8_t unread_0f; -}; - -struct StreamRecord2 { // type 2 - uint32_t type; - uint32_t unread_04; - float count_08; // truncated to an integer; -1 means the default (0.2) - float value_0c; // 0.0 means the default (0.75) -}; - -// D3D12XBOX_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_BATCHED_DESC2. The first 0x30 bytes are the public -// D3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_DESC. -struct BatchedDesc2 { - uint64_t dest_acceleration_structure_data; // 256-byte aligned - BuildInputs inputs; - uint64_t source_acceleration_structure_data; - uint64_t scratch_acceleration_structure_data; - uint32_t num_postbuild_info_descs; - uint32_t padding; // the single-build wrapper writes 0; never read - const PostbuildInfoDesc* postbuild_info_descs; - StreamDesc stream; -}; - -static_assert(sizeof(BuildInputs) == 0x18); -static_assert(sizeof(PostbuildInfoDesc) == 0x10 && offsetof(PostbuildInfoDesc, info_type) == 0x08); -static_assert(sizeof(StreamDesc) == 0x10 && offsetof(StreamDesc, stream) == 0x08); -static_assert(sizeof(StreamRecord) == 0x10 && sizeof(StreamRecord0) == 0x10 && sizeof(StreamRecord1) == 0x10 && - sizeof(StreamRecord2) == 0x10); -static_assert(offsetof(StreamRecord0, value_04) == 0x04 && offsetof(StreamRecord0, value_08) == 0x08 && - offsetof(StreamRecord0, bytes_0c) == 0x0c); -static_assert(offsetof(StreamRecord1, level_0d) == 0x0d && offsetof(StreamRecord1, flag_0e) == 0x0e); -static_assert(offsetof(StreamRecord2, count_08) == 0x08 && offsetof(StreamRecord2, value_0c) == 0x0c); -static_assert(sizeof(BatchedDesc2) == 0x50); -static_assert(offsetof(BatchedDesc2, inputs) == 0x08); -static_assert(offsetof(BatchedDesc2, source_acceleration_structure_data) == 0x20); -static_assert(offsetof(BatchedDesc2, scratch_acceleration_structure_data) == 0x28); -static_assert(offsetof(BatchedDesc2, num_postbuild_info_descs) == 0x30); -static_assert(offsetof(BatchedDesc2, postbuild_info_descs) == 0x38); -static_assert(offsetof(BatchedDesc2, stream) == 0x40); - -constexpr uint32_t kBuildFlagPreferFastTrace = 0x04; -constexpr uint32_t kBuildFlagMinimizeMemory = 0x10; - -// D3D12XBOX_RAYTRACING_ACCELERATION_STRUCTURE_POSTBUILD_INFO_OFFLINE_STATISTICS: the DLL rejects it for every build -// it does (offline builds only). -constexpr uint32_t kPostbuildInfoOfflineStatistics = 0x10; - -// The record a setting is read from, the way the DLL finds it: the first record of `type` from the start, stepping -// over types 0, 1 and 2, and stopping at any other type. Null when there is none. -inline const StreamRecord* find_stream_record(const StreamDesc& desc, uint32_t type) { - if (desc.size_in_bytes == 0 || desc.stream == nullptr) - return nullptr; - const auto* record = static_cast(desc.stream); - const auto* end = reinterpret_cast(static_cast(desc.stream) + - desc.size_in_bytes); - for (; record < end; ++record) { - if (record->type == type) - return record; - if (record->type > 2) - return nullptr; - } - return nullptr; -} - -// Type 0's value at 0x08 when it is negative or absent, from Inputs.Flags. -inline float default_record0_value_08(uint32_t flags) { - const bool fast_trace = (flags & kBuildFlagPreferFastTrace) != 0; - const bool minimize_memory = (flags & kBuildFlagMinimizeMemory) != 0; - if (fast_trace) - return minimize_memory ? 1.005f : 0.0f; - return minimize_memory ? 1.01f : 1.005f; -} - -} // namespace leonida::xdxr diff --git a/runtime/test/acphal_test.cpp b/runtime/test/acphal_test.cpp deleted file mode 100644 index bd93f7040..000000000 --- a/runtime/test/acphal_test.cpp +++ /dev/null @@ -1,262 +0,0 @@ -// Checks the registered acphal.dll shim against the measured call shapes -// (docs/retail_boot_chain.md, docs/retail_boot_frame_loop.md Stop 28, PR #6885, PR #7009). -// -// All 9 exports are resolved through rt::shims::find so the test exercises -// the exact shim table and calling convention the runtime installs. - -#include - -#include -#include -#include -#include - -#include "shims.h" - -namespace { - -using AcpHalCreateFn = HRESULT(__stdcall*)(void**); -using AcpHalAllocShapeCtxFn = HRESULT(__stdcall*)(void*); -using AcpHalReleaseShapeCtxFn = HRESULT(__stdcall*)(void*); -using ApuCreateHeapFn = HRESULT(__stdcall*)(uint32_t, uint32_t); -// Measured: ApuAlloc(void** va, uint32_t* apu, uint32_t size, uint32_t align, uint32_t flags) -using ApuAllocFn = HRESULT(__stdcall*)(void**, uint32_t*, uint32_t, uint32_t, uint32_t); -using ApuFreeFn = void(__stdcall*)(void*); -// Measured: ApuIsVirtualAddressValid(void* va, uint32_t align) -using ApuIsValidFn = BOOL(__stdcall*)(void*, uint32_t); -using ApuMapApuAddrFn = void*(__stdcall*)(uint32_t); -using ApuMapVirtualAddrFn = uint32_t(__stdcall*)(void*); - -int g_checks = 0; -int g_failures = 0; - -void check(bool condition, const char* what) { - ++g_checks; - std::printf("%s %s\n", condition ? "PASS" : "FAIL", what); - if (!condition) ++g_failures; -} - -// Test mirror of SHAPE_CONTEXTS matching devdocs.xbox.com GDK spec -struct APU_ADDRESS { - uint64_t value; -}; - -struct TestShapeContexts { - uint32_t numSrcContexts; - uint32_t numEqCompContexts; - uint32_t numFiltVolContexts; - uint32_t numDmaContexts; - uint32_t numXmaContexts; - uint32_t numPcmContexts; - void* srcContextArray; - void* eqCompContextArray; - void* filtVolContextArray; - void* dmaContextArray; - void* xmaContextArray; - void* pcmContextArray; - APU_ADDRESS apuSrcContextArray; - APU_ADDRESS apuEqCompContextArray; - APU_ADDRESS apuFiltVolContextArray; - APU_ADDRESS apuDmaContextArray; - APU_ADDRESS apuXmaContextArray; - APU_ADDRESS apuPcmContextArray; -}; - -static_assert(sizeof(TestShapeContexts) == 120, "TestShapeContexts is 120 bytes"); -static_assert(offsetof(TestShapeContexts, xmaContextArray) == 0x38, - "xmaContextArray is at offset +0x38"); - -} // namespace - -int main() { - std::printf("acphal_test: registered acphal.dll shim verification\n"); - - const auto create = reinterpret_cast( - rt::shims::find("acphal.dll", "AcpHalCreate")); - const auto alloc_ctx = reinterpret_cast( - rt::shims::find("acphal.dll", "AcpHalAllocateShapeContexts")); - const auto release_ctx = reinterpret_cast( - rt::shims::find("acphal.dll", "AcpHalReleaseShapeContexts")); - const auto create_heap = reinterpret_cast( - rt::shims::find("acphal.dll", "ApuCreateHeap")); - const auto alloc = reinterpret_cast( - rt::shims::find("acphal.dll", "ApuAlloc")); - const auto free_mem = reinterpret_cast( - rt::shims::find("acphal.dll", "ApuFree")); - const auto is_valid = reinterpret_cast( - rt::shims::find("acphal.dll", "ApuIsVirtualAddressValid")); - const auto map_apu = reinterpret_cast( - rt::shims::find("acphal.dll", "ApuMapApuAddress")); - const auto map_virtual = reinterpret_cast( - rt::shims::find("acphal.dll", "ApuMapVirtualAddress")); - - check(create != nullptr, "AcpHalCreate is registered in registry"); - check(alloc_ctx != nullptr, "AcpHalAllocateShapeContexts is registered in registry"); - check(release_ctx != nullptr, "AcpHalReleaseShapeContexts is registered in registry"); - check(create_heap != nullptr, "ApuCreateHeap is registered in registry"); - check(alloc != nullptr, "ApuAlloc is registered in registry"); - check(free_mem != nullptr, "ApuFree is registered in registry"); - check(is_valid != nullptr, "ApuIsVirtualAddressValid is registered in registry"); - check(map_apu != nullptr, "ApuMapApuAddress is registered in registry"); - check(map_virtual != nullptr, "ApuMapVirtualAddress is registered in registry"); - check(rt::shims::owns_dll("acphal.dll"), "the registry owns acphal.dll"); - - if (!create || !alloc_ctx || !release_ctx || !create_heap || !alloc || - !free_mem || !is_valid || !map_apu || !map_virtual) { - std::printf("Fatal: Missing export bindings for acphal.dll\n"); - return 1; - } - - // 1. AcpHalCreate - void* acp = nullptr; - check(create(&acp) == S_OK && acp != nullptr, - "AcpHalCreate returns S_OK with a non-null object"); - check(create(nullptr) == E_POINTER, - "AcpHalCreate(nullptr) returns E_POINTER"); - - if (acp) { - using Slot0Fn = HRESULT(__stdcall*)(void*, uint32_t, uint32_t); - using Slot1Fn = HRESULT(__stdcall*)(void*); - using Slot2Fn = HRESULT(__stdcall*)(void*, uint32_t, uint32_t, uint32_t, const void*, uint32_t); - using Slot3Fn = uint32_t(__stdcall*)(void*); - using Slot5Fn = HRESULT(__stdcall*)(void*); - - auto vtable = *static_cast(acp); - check(vtable[0] != nullptr, "IAcpHal vtable slot 0 (connect) is present"); - check(vtable[1] != nullptr, "IAcpHal vtable slot 1 (disconnect) is present"); - check(vtable[2] != nullptr, "IAcpHal vtable slot 2 (submit_command) is present"); - check(vtable[3] != nullptr, "IAcpHal vtable slot 3 (pop_message) is present"); - check(vtable[4] != nullptr, "IAcpHal vtable slot 4 (get_num_messages) is present"); - check(vtable[5] != nullptr, "IAcpHal vtable slot 5 (release) is present"); - - // Slot 0: Connect (called at boot with (0x1000, 0x1000)) - check(reinterpret_cast(vtable[0])(acp, 0x1000, 0x1000) == S_OK, - "IAcpHal slot 0 (connect) returns S_OK"); - - // Slot 2: SubmitCommand. Critical boot requirement: The title calls - // slot 2 as (2, 0xf0f0f0f0, -1, config, 0) and treats failure as fatal int3. - check(reinterpret_cast(vtable[2])(acp, 2, 0xf0f0f0f0, 0xffffffffu, nullptr, 0) == S_OK, - "IAcpHal slot 2 (submit_command) returns S_OK (vital boot unblocker)"); - - // Slots 3 and 4: Message polling returns 0 - check(reinterpret_cast(vtable[3])(acp) == 0, "IAcpHal slot 3 returns 0"); - check(reinterpret_cast(vtable[4])(acp) == 0, "IAcpHal slot 4 returns 0"); - - // Slot 1: Disconnect returns S_OK - check(reinterpret_cast(vtable[1])(acp) == S_OK, "IAcpHal slot 1 returns S_OK"); - - // Slot 5: Release returns S_OK - check(reinterpret_cast(vtable[5])(acp) == S_OK, "IAcpHal slot 5 returns S_OK"); - } - - // 2. ApuCreateHeap: title passes (cachedSize, nonCachedSize=0x226e00) - check(create_heap(4 * 1024 * 1024, 0x226e00) == S_OK, - "ApuCreateHeap(4 MiB, 0x226e00) succeeds"); - check(create_heap(4 * 1024 * 1024, 0x226e00) != S_OK, - "ApuCreateHeap second call fails (heap already created)"); - - // 3. ApuAlloc argument validation - void* dummy = nullptr; - check(alloc(nullptr, nullptr, 1024, 0x800, 0) == E_POINTER, - "ApuAlloc(nullptr, ...) returns E_POINTER"); - check(alloc(&dummy, nullptr, 0, 0x800, 0) == E_INVALIDARG, - "ApuAlloc with size=0 returns E_INVALIDARG"); - check(alloc(&dummy, nullptr, 1024, 3, 0) == E_INVALIDARG, - "ApuAlloc with unaligned alignment (3) returns E_INVALIDARG"); - - // 4. ApuAlloc real boot sequence: - // First call: flags=2, size=0x222e00, align=0x800 (noncached heap) - void* va_nc = nullptr; - uint32_t apu_nc = 0; - check(alloc(&va_nc, &apu_nc, 0x222e00, 0x800, 2) == S_OK && va_nc != nullptr, - "ApuAlloc flags=2 at title's non-cached size 0x222e00 succeeds"); - check(apu_nc != 0, "ApuAlloc provides non-zero physical APU address"); - - // Second call: flags=1, size=4096, align=0x800 (cached heap) - void* va_c = nullptr; - uint32_t apu_c = 0; - check(alloc(&va_c, &apu_c, 4096, 0x800, 1) == S_OK && va_c != nullptr, - "ApuAlloc flags=1 succeeds on cached heap"); - check(apu_c != 0, "ApuAlloc flags=1 provides non-zero APU address"); - - // Address verification & disjoint ranges - check(va_nc != va_c, "Cached and non-cached allocations return different virtual pointers"); - check(apu_nc != apu_c, "Cached and non-cached APU addresses are distinct"); - check(is_valid(va_nc, 0x800) == TRUE, "Non-cached allocation is in a valid heap"); - check(is_valid(va_c, 0x800) == TRUE, "Cached allocation is in a valid heap"); - check(is_valid(nullptr, 0x800) == FALSE, "ApuIsVirtualAddressValid(nullptr) returns FALSE"); - check(is_valid(reinterpret_cast(0x1234), 0x800) == FALSE, - "ApuIsVirtualAddressValid(bogus) returns FALSE"); - - // Round-trip mapping - check(map_virtual(va_nc) == apu_nc, "ApuMapVirtualAddress matches apu_nc"); - check(map_virtual(va_c) == apu_c, "ApuMapVirtualAddress matches apu_c"); - check(map_apu(apu_nc) == va_nc, "ApuMapApuAddress round-trips non-cached address"); - check(map_apu(apu_c) == va_c, "ApuMapApuAddress round-trips cached address"); - check(map_apu(0) == nullptr, "ApuMapApuAddress(0) returns nullptr"); - check(map_virtual(nullptr) == 0, "ApuMapVirtualAddress(nullptr) returns 0"); - - // 5. Genuine State Tracking: Free & Memory Reuse - void* reusable_block1 = nullptr; - check(alloc(&reusable_block1, nullptr, 0x1000, 0x800, 1) == S_OK && reusable_block1 != nullptr, - "Allocate 4 KiB reusable block"); - free_mem(reusable_block1); - check(true, "ApuFree on valid address succeeds without error"); - free_mem(nullptr); - check(true, "ApuFree(nullptr) is a safe no-op"); - - // Reallocate in the freed slot: - void* reusable_block2 = nullptr; - check(alloc(&reusable_block2, nullptr, 0x1000, 0x800, 1) == S_OK && reusable_block2 != nullptr, - "Re-allocate in cached heap succeeds (memory successfully reused)"); - check(reusable_block2 == reusable_block1, - "Free block was genuinely reused at the same offset by the allocator"); - free_mem(reusable_block2); - - // 6. AcpHalAllocateShapeContexts & AcpHalReleaseShapeContexts - check(alloc_ctx(nullptr) == E_POINTER, - "AcpHalAllocateShapeContexts(nullptr) returns E_POINTER"); - - // Real executable call: 0 SRC, 350 XMA (+0x38), 0 PCM - TestShapeContexts ctx{}; - ctx.numXmaContexts = 350; - check(alloc_ctx(&ctx) == S_OK, "AcpHalAllocateShapeContexts succeeds"); - check(ctx.xmaContextArray != nullptr, - "xmaContextArray (+0x38) is non-null after allocation"); - check(ctx.srcContextArray == nullptr, "srcContextArray is null when count is 0"); - - // Verify zeroed memory across all 350 * 64 bytes - const uint8_t* xma_bytes = static_cast(ctx.xmaContextArray); - bool all_zero = true; - for (size_t i = 0; i < 350 * 64; ++i) { - if (xma_bytes[i] != 0) { - all_zero = false; - break; - } - } - check(all_zero, "SHAPE context buffer is zero-initialized for title's stride"); - - // Test multi-context allocation - TestShapeContexts ctx_all{}; - ctx_all.numSrcContexts = 10; - ctx_all.numEqCompContexts = 5; - ctx_all.numFiltVolContexts = 8; - ctx_all.numDmaContexts = 4; - ctx_all.numXmaContexts = 12; - ctx_all.numPcmContexts = 6; - check(alloc_ctx(&ctx_all) == S_OK, "AcpHalAllocateShapeContexts with all 6 types succeeds"); - check(ctx_all.srcContextArray != nullptr, "srcContextArray is allocated"); - check(ctx_all.eqCompContextArray != nullptr, "eqCompContextArray is allocated"); - check(ctx_all.filtVolContextArray != nullptr, "filtVolContextArray is allocated"); - check(ctx_all.dmaContextArray != nullptr, "dmaContextArray is allocated"); - check(ctx_all.xmaContextArray != nullptr, "xmaContextArray is allocated"); - check(ctx_all.pcmContextArray != nullptr, "pcmContextArray is allocated"); - - // Release shape contexts - check(release_ctx(&ctx_all) == S_OK, "AcpHalReleaseShapeContexts succeeds"); - check(ctx_all.xmaContextArray == nullptr, "xmaContextArray is reset to null"); - check(release_ctx(nullptr) == S_OK, "AcpHalReleaseShapeContexts(nullptr) succeeds"); - - std::printf("acphal_test complete: %d checks, %d failures\n", g_checks, g_failures); - return g_failures ? 1 : 0; -} diff --git a/runtime/test/active_input_test.cpp b/runtime/test/active_input_test.cpp deleted file mode 100644 index 11c628320..000000000 --- a/runtime/test/active_input_test.cpp +++ /dev/null @@ -1,236 +0,0 @@ -// ActiveInputTracker (src/active_input.h) on synthetic samples with its own clock: what counts as deliberate input -// (edges only, thresholds, baselines), the minimum time between changes, several devices of one family, a device that -// goes and comes back, and a forced family. No SDL, no controller, no GPU. -#include "../src/active_input.h" - -#include -#include -#include - -using namespace leonida; - -#define EXPECT(condition) do { \ - if (!(condition)) { std::fprintf(stderr, "line %d: %s\n", __LINE__, #condition); return 1; } \ -} while (0) - -namespace { - -constexpr std::uint64_t ms = 1000; // the tracker's clock is in microseconds - -InputSample rest() { return {}; } - -InputSample button(std::uint32_t bits) { - InputSample s; - s.buttons = bits; - return s; -} - -InputSample left_stick(float x, float y) { - InputSample s; - s.left_x = x; - s.left_y = y; - return s; -} - -InputSample right_stick(float x, float y) { - InputSample s; - s.right_x = x; - s.right_y = y; - return s; -} - -InputSample triggers(float left, float right) { - InputSample s; - s.left_trigger = left; - s.right_trigger = right; - return s; -} - -// Device keys and families used below. -constexpr std::uint64_t xbox = 1, dualsense = 2, ds4 = 3, keyboard = 4, xbox2 = 5, switch_pro = 6; - -int test_start_and_baseline() { - ActiveInputTracker t; - EXPECT(t.active() == InputFamily::Xbox && t.generation() == 0 && !t.forced()); - - // A first sample is a baseline, whatever it holds: a pad connecting with a button down changes nothing. - EXPECT(t.observe(dualsense, InputFamily::PlayStation5, button(1), 0) == InputEdge::None); - EXPECT(t.active() == InputFamily::Xbox && t.generation() == 0); - // Still held: no edge. - EXPECT(t.observe(dualsense, InputFamily::PlayStation5, button(1), 10 * ms) == InputEdge::None); - // Released, then pressed again: that press is the first deliberate input, and the first change needs no wait. - EXPECT(t.observe(dualsense, InputFamily::PlayStation5, rest(), 20 * ms) == InputEdge::None); - EXPECT(t.observe(dualsense, InputFamily::PlayStation5, button(1), 30 * ms) == InputEdge::Button); - EXPECT(t.active() == InputFamily::PlayStation5 && t.generation() == 1); - return 0; -} - -int test_drift_and_thresholds() { - ActiveInputTracker t; - EXPECT(t.observe(xbox, InputFamily::Xbox, rest(), 0) == InputEdge::None); - EXPECT(t.observe(dualsense, InputFamily::PlayStation5, rest(), 0) == InputEdge::None); - - // A worn stick drifting around inside the radius never counts, however long it wanders. - for (int i = 0; i < 200; ++i) { - const float d = 0.05f + 0.25f * static_cast(i % 7) / 6.0f; // 0.05 .. 0.30 - EXPECT(t.observe(dualsense, InputFamily::PlayStation5, left_stick(d, -d * 0.5f), (1 + i) * ms) == - InputEdge::None); - } - // Just inside the radius (0.35 along a diagonal is 0.247 per axis): nothing. - EXPECT(t.observe(dualsense, InputFamily::PlayStation5, left_stick(0.24f, 0.24f), 300 * ms) == InputEdge::None); - // Leaving it is an edge. - EXPECT(t.observe(dualsense, InputFamily::PlayStation5, left_stick(0.3f, 0.3f), 310 * ms) == InputEdge::Stick); - EXPECT(t.active() == InputFamily::PlayStation5 && t.generation() == 1); - // Held over the radius: no further edge from the same stick. - EXPECT(t.observe(dualsense, InputFamily::PlayStation5, left_stick(1.0f, 0.0f), 320 * ms) == InputEdge::None); - - // Triggers: resting at 0.29 is not a pull; rising past 0.3 is. - EXPECT(t.observe(xbox, InputFamily::Xbox, triggers(0.29f, 0.0f), 700 * ms) == InputEdge::None); - EXPECT(t.active() == InputFamily::PlayStation5); - EXPECT(t.observe(xbox, InputFamily::Xbox, triggers(0.31f, 0.0f), 710 * ms) == InputEdge::Trigger); - EXPECT(t.active() == InputFamily::Xbox && t.generation() == 2); - // A trigger held further down does not count again. - EXPECT(t.observe(xbox, InputFamily::Xbox, triggers(0.9f, 0.0f), 720 * ms) == InputEdge::None); - return 0; -} - -int test_min_switch_time() { - ActiveInputTracker t; - t.observe(xbox, InputFamily::Xbox, rest(), 0); - t.observe(dualsense, InputFamily::PlayStation5, rest(), 0); - - EXPECT(t.observe(dualsense, InputFamily::PlayStation5, button(2), 1000 * ms) == InputEdge::Button); - EXPECT(t.active() == InputFamily::PlayStation5 && t.generation() == 1); - // 100 ms later the Xbox pad's press is inside the window: ignored, and not remembered for later. - EXPECT(t.observe(xbox, InputFamily::Xbox, button(1), 1100 * ms) == InputEdge::None); - EXPECT(t.active() == InputFamily::PlayStation5); - EXPECT(t.observe(xbox, InputFamily::Xbox, button(1), 1400 * ms) == InputEdge::None); // still held: no edge - EXPECT(t.active() == InputFamily::PlayStation5); - // Released and pressed again after the window: that one counts. - t.observe(xbox, InputFamily::Xbox, rest(), 1500 * ms); - EXPECT(t.observe(xbox, InputFamily::Xbox, button(1), 1600 * ms) == InputEdge::Button); - EXPECT(t.active() == InputFamily::Xbox && t.generation() == 2); - // Exactly at the window's end counts (the window is "less than min_switch_us"). - EXPECT(t.observe(dualsense, InputFamily::PlayStation5, button(2 | 4), 1900 * ms) == InputEdge::Button); - EXPECT(t.active() == InputFamily::PlayStation5 && t.generation() == 3); - - // A zero window lets every deliberate input switch at once. - ActiveInputTracker fast(InputFamily::Xbox, {0.35f, 0.3f, 0}); - fast.observe(xbox, InputFamily::Xbox, rest(), 0); - fast.observe(keyboard, InputFamily::Keyboard, rest(), 0); - EXPECT(fast.observe(keyboard, InputFamily::Keyboard, button(8), 1) == InputEdge::Button); - EXPECT(fast.observe(xbox, InputFamily::Xbox, button(8), 2) == InputEdge::Button); - EXPECT(fast.active() == InputFamily::Xbox && fast.generation() == 2); - return 0; -} - -int test_same_family_and_holds() { - ActiveInputTracker t; - for (std::uint64_t d : {xbox, xbox2}) t.observe(d, InputFamily::Xbox, rest(), 0); - t.observe(keyboard, InputFamily::Keyboard, rest(), 0); - - // Input from a second pad of the family already in use changes nothing. - EXPECT(t.observe(xbox2, InputFamily::Xbox, button(1), 10 * ms) == InputEdge::None); - EXPECT(t.active() == InputFamily::Xbox && t.generation() == 0); - - // The keyboard pad: W held pushes the left stick to full. The first push is the edge; holding it is not. - EXPECT(t.observe(keyboard, InputFamily::Keyboard, left_stick(0.0f, 1.0f), 20 * ms) == InputEdge::Stick); - EXPECT(t.active() == InputFamily::Keyboard && t.generation() == 1); - // The player picks up the Xbox pad while W is still held down: the pad takes over after the window and the held - // key does not take it back. - EXPECT(t.observe(xbox, InputFamily::Xbox, button(1), 400 * ms) == InputEdge::Button); - for (int i = 0; i < 50; ++i) - EXPECT(t.observe(keyboard, InputFamily::Keyboard, left_stick(0.0f, 1.0f), (410 + 10 * i) * ms) == - InputEdge::None); - EXPECT(t.active() == InputFamily::Xbox && t.generation() == 2); - - // The mouse moves the keyboard pad's right stick: a small jitter stays inside the radius, a real movement - // leaves it. - t.observe(keyboard, InputFamily::Keyboard, rest(), 1000 * ms); - EXPECT(t.observe(keyboard, InputFamily::Keyboard, right_stick(0.03f, 0.0f), 1010 * ms) == InputEdge::None); - EXPECT(t.observe(keyboard, InputFamily::Keyboard, right_stick(0.5f, -0.1f), 1020 * ms) == InputEdge::Stick); - EXPECT(t.active() == InputFamily::Keyboard && t.generation() == 3); - return 0; -} - -int test_reconnect() { - ActiveInputTracker t; - t.observe(ds4, InputFamily::PlayStation4, rest(), 0); - EXPECT(t.observe(ds4, InputFamily::PlayStation4, button(1), 10 * ms) == InputEdge::Button); - EXPECT(t.active() == InputFamily::PlayStation4); - - // Unplugged while the button was down; it comes back with the button still down. The new first sample is a - // baseline, so there is no edge to count, and no stale state from before. - t.forget(ds4); - t.observe(switch_pro, InputFamily::Nintendo, rest(), 0); - EXPECT(t.observe(switch_pro, InputFamily::Nintendo, button(1), 500 * ms) == InputEdge::Button); - EXPECT(t.active() == InputFamily::Nintendo); - EXPECT(t.observe(ds4, InputFamily::PlayStation4, button(1), 900 * ms) == InputEdge::None); - EXPECT(t.active() == InputFamily::Nintendo); - t.observe(ds4, InputFamily::PlayStation4, rest(), 910 * ms); - EXPECT(t.observe(ds4, InputFamily::PlayStation4, button(1), 920 * ms) == InputEdge::Button); - EXPECT(t.active() == InputFamily::PlayStation4 && t.generation() == 3); - return 0; -} - -int test_forced() { - ActiveInputTracker t; - t.observe(dualsense, InputFamily::PlayStation5, rest(), 0); - t.observe(keyboard, InputFamily::Keyboard, rest(), 0); - - t.force(InputFamily::Keyboard); - EXPECT(t.forced() && t.active() == InputFamily::Keyboard && t.generation() == 1); - // Forcing the same family again changes nothing. - t.force(InputFamily::Keyboard); - EXPECT(t.generation() == 1); - - // Tracking still runs underneath: the DualSense becomes the tracked family, but the answer stays forced and the - // generation does not move. - EXPECT(t.observe(dualsense, InputFamily::PlayStation5, button(1), 10 * ms) == InputEdge::Button); - EXPECT(t.tracked() == InputFamily::PlayStation5 && t.active() == InputFamily::Keyboard && t.generation() == 1); - - // Clearing the force goes straight back to the device in use. - t.force(std::nullopt); - EXPECT(!t.forced() && t.active() == InputFamily::PlayStation5 && t.generation() == 2); - - // Forcing the family that is already tracked does not change the answer, so no new generation. - t.force(InputFamily::PlayStation5); - EXPECT(t.forced() && t.active() == InputFamily::PlayStation5 && t.generation() == 2); - t.force(std::nullopt); - EXPECT(t.generation() == 2); - return 0; -} - -int test_names() { - EXPECT(std::string_view(input_family_name(InputFamily::PlayStation5)) == "PlayStation 5"); - EXPECT(std::string_view(input_family_name(InputFamily::Keyboard)) == "keyboard and mouse"); - EXPECT(std::string_view(input_edge_name(InputEdge::Stick)) == "stick movement"); - return 0; -} - -} // namespace - -int main() { - struct Case { - const char* name; - int (*run)(); - }; - const Case cases[] = { - {"start and baseline", test_start_and_baseline}, - {"drift and thresholds", test_drift_and_thresholds}, - {"minimum time between changes", test_min_switch_time}, - {"one family, held input", test_same_family_and_holds}, - {"reconnect", test_reconnect}, - {"forced family", test_forced}, - {"names", test_names}, - }; - int failures = 0; - for (const Case& c : cases) { - const int r = c.run(); - std::printf("%s: %s\n", c.name, r ? "FAIL" : "ok"); - failures += r; - } - const int total = static_cast(std::size(cases)); - std::printf("active input: %d of %d cases pass\n", total - failures, total); - return failures ? 1 : 0; -} diff --git a/runtime/test/allocator_proxy_test.cpp b/runtime/test/allocator_proxy_test.cpp deleted file mode 100644 index 5f89366f5..000000000 --- a/runtime/test/allocator_proxy_test.cpp +++ /dev/null @@ -1,387 +0,0 @@ -// Xbox-ABI command allocator proxies (d3d12_xs_device.h, device slot 9) behind the device proxy, on the Vulkan-backed -// device and on the host PC runtime (WARP, and the first hardware adapter when there is one): -// - Vulkan device: slot 9 wraps the allocator; the public chain (9 slots) is forwarded with the real allocator's -// answers, every slot past it up to the end of the table is refused (E_NOTIMPL), and a read past the table faults -// in the guard region and is counted; -// - QueryInterface identity, GetDevice -> the device proxy, references and release orders; -// - a command list created on the proxy and Reset on it (the Vulkan layer resolves the proxy), recording a buffer -// copy that runs through the queue and fence proxies and is read back, twice, with the allocator Reset between; -// and D3D12's allocator rules through the proxy (Reset while a list records: E_FAIL; a second list on a busy -// allocator: E_INVALIDARG); -// - MakeResident/Evict with an allocator proxy give the real allocator's HRESULT; -// - host runtime: slot 9 hands out the PC allocator unwrapped (its lists could not resolve a proxy), and the same -// copy works. -// LEONIDA_VK_VALIDATION=1 runs the Vulkan device under VK_LAYER_KHRONOS_validation with synchronization validation; -// any validation error fails the test. Exits 77 when neither a host D3D12 device nor a Vulkan device can be made. -// No shaders, game data or Xbox DLLs. -#include "vk_test_device.h" -#include "../shims/d3d12_com.h" -#include "../shims/d3d12_xs_device.h" - -#include -#include - -#include -#include -#include - -#define EXPECT(condition) do { \ - if (!(condition)) { std::fprintf(stderr, "%s line %d: %s\n", label, __LINE__, #condition); return 1; } \ -} while (0) - -namespace { - -namespace xs = rt::d3d12_xs; - -template -struct Ref { - T* p = nullptr; - Ref() = default; - Ref(const Ref&) = delete; - Ref& operator=(const Ref&) = delete; - ~Ref() { reset(); } - void reset() { - if (p) p->Release(); - p = nullptr; - } - T* operator->() const { return p; } -}; - -struct Backend { - const char* label; - ID3D12Device* device; // the device proxy - ID3D12Device* real; // the device behind it (PC runtime or Vulkan layer) - bool vulkan; -}; - -using SlotFn = std::uint64_t(WINAPI*)(void*, std::uint64_t, std::uint64_t, std::uint64_t, std::uint64_t, - std::uint64_t, std::uint64_t, std::uint64_t, std::uint64_t, std::uint64_t, - std::uint64_t, std::uint64_t, std::uint64_t, std::uint64_t, std::uint64_t); - -// A call through slot `slot` with all words zero, the way a title calls a console method the PC interface lacks. -HRESULT call_slot(void* object, unsigned slot) { - void** vtable = *reinterpret_cast(object); - return static_cast(static_cast( - reinterpret_cast(vtable[slot])(object, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0))); -} - -ULONG_PTR g_fault_address = 0; -// The code is taken in the filter, from the exception record: GetExceptionCode() in the __except body returns 0 -// under Wine 9.0 (clang-cl reads it from what the unwind hands the handler, which that Wine does not supply). -DWORD g_fault_code = 0; - -int record_fault(EXCEPTION_POINTERS* info) { - g_fault_code = info->ExceptionRecord->ExceptionCode; - g_fault_address = info->ExceptionRecord->NumberParameters >= 2 ? info->ExceptionRecord->ExceptionInformation[1] : 0; - return EXCEPTION_EXECUTE_HANDLER; -} - -// The read in a function of its own: clang-cl's __try only catches a fault raised inside a call. -__declspec(noinline) void* read_entry(void* const* vtable, unsigned slot) { - return *static_cast(&vtable[slot]); -} - -// Reads vtable[slot] the way a call through it does. The exception code, or 0 when the read worked. -DWORD read_slot_guarded(void* const* vtable, unsigned slot) { - g_fault_address = 0; - g_fault_code = 0; - __try { - void* volatile entry = read_entry(vtable, slot); - (void)entry; - return 0; - } __except (record_fault(GetExceptionInformation())) { - return g_fault_code; - } -} - -int wait_for(const char* label, ID3D12Fence* fence, UINT64 value) { - HANDLE event = CreateEventW(nullptr, FALSE, FALSE, nullptr); - EXPECT(event != nullptr); - const bool set = SUCCEEDED(fence->SetEventOnCompletion(value, event)) && WaitForSingleObject(event, 5000) == 0; - CloseHandle(event); - EXPECT(set && fence->GetCompletedValue() >= value); - return 0; -} - -int make_buffer(const char* label, ID3D12Device* device, D3D12_HEAP_TYPE heap_type, D3D12_RESOURCE_STATES state, - Ref& out) { - D3D12_HEAP_PROPERTIES heap{}; - heap.Type = heap_type; - D3D12_RESOURCE_DESC desc{}; - desc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER; - desc.Width = 256; - desc.Height = desc.DepthOrArraySize = desc.MipLevels = 1; - desc.SampleDesc.Count = 1; - desc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; - EXPECT(SUCCEEDED(device->CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &desc, state, nullptr, - IID_PPV_ARGS(&out.p)))); - return 0; -} - -// One recording on `list` (open, recording into the allocator): 256 bytes of `byte` copied from an upload buffer to a -// readback buffer, executed through the queue proxy, finished through the fence proxy at `value`, then compared. -int copy_round(const char* label, ID3D12Device* device, ID3D12CommandQueue* queue, ID3D12Fence* fence, - ID3D12GraphicsCommandList* list, std::uint8_t byte, UINT64 value) { - Ref upload, readback; - if (make_buffer(label, device, D3D12_HEAP_TYPE_UPLOAD, D3D12_RESOURCE_STATE_GENERIC_READ, upload)) return 1; - if (make_buffer(label, device, D3D12_HEAP_TYPE_READBACK, D3D12_RESOURCE_STATE_COPY_DEST, readback)) return 1; - void* mapped = nullptr; - EXPECT(SUCCEEDED(upload->Map(0, nullptr, &mapped)) && mapped); - std::memset(mapped, byte, 256); - upload->Unmap(0, nullptr); - list->CopyBufferRegion(readback.p, 0, upload.p, 0, 256); - EXPECT(SUCCEEDED(list->Close())); - ID3D12CommandList* lists[] = {list}; - queue->ExecuteCommandLists(1, lists); - EXPECT(SUCCEEDED(queue->Signal(fence, value))); - if (wait_for(label, fence, value)) return 1; - const D3D12_RANGE read{0, 256}; - EXPECT(SUCCEEDED(readback->Map(0, &read, &mapped)) && mapped); - const auto* bytes = static_cast(mapped); - int wrong = 0; - for (int i = 0; i < 256; ++i) wrong += bytes[i] != byte; - const D3D12_RANGE none{0, 0}; - readback->Unmap(0, &none); - EXPECT(wrong == 0); - return 0; -} - -// ---- 1. The proxy itself: slots, identity, guard (Vulkan device) ---- - -int check_proxy(const Backend& b, ID3D12CommandAllocator* allocator) { - const char* label = b.label; - ID3D12CommandAllocator* real = xs::allocator_proxy_real_allocator(allocator); - EXPECT(real && static_cast(real) != static_cast(allocator)); - EXPECT(xs::allocator_proxy_slot_count(allocator) == 9); - EXPECT(xs::command_object_proxy_ref_count(allocator) == 1); - - // QueryInterface: the base chain and the allocator itself answer with the proxy; anything else is refused. - const IID modelled[] = {__uuidof(IUnknown), __uuidof(ID3D12Object), __uuidof(ID3D12DeviceChild), - __uuidof(ID3D12Pageable), __uuidof(ID3D12CommandAllocator)}; - for (const IID& iid : modelled) { - void* same = nullptr; - EXPECT(SUCCEEDED(allocator->QueryInterface(iid, &same)) && same == allocator); - static_cast(same)->Release(); - } - void* other = reinterpret_cast(1); - EXPECT(allocator->QueryInterface(__uuidof(ID3D12Fence), &other) == E_NOINTERFACE && !other); - other = reinterpret_cast(1); // the Vulkan layer's private tag: not modelled, the real object stays hidden - EXPECT(allocator->QueryInterface(xs::kLeonidaCommandAllocatorTag, &other) == E_NOINTERFACE && !other); - EXPECT(xs::command_object_proxy_ref_count(allocator) == 1); - - ID3D12Device* owner = nullptr; - EXPECT(SUCCEEDED(allocator->GetDevice(IID_PPV_ARGS(&owner))) && owner == b.device); - owner->Release(); - // Private data and SetName go to the real allocator; the proxy pointer round-trips as an interface. - EXPECT(SUCCEEDED(allocator->SetName(L"leonida allocator proxy"))); - constexpr GUID key{0x2a6b8c41, 0x77d2, 0x4e19, {0x9c, 0x3a, 0x51, 0xe0, 0x8f, 0x24, 0x6d, 0x0b}}; - EXPECT(SUCCEEDED(allocator->SetPrivateDataInterface(key, allocator))); - IUnknown* back = nullptr; - UINT size = sizeof(back); - EXPECT(SUCCEEDED(allocator->GetPrivateData(key, &size, &back)) && back == allocator); - back->Release(); - EXPECT(SUCCEEDED(allocator->SetPrivateDataInterface(key, nullptr))); - - // The refused tail: every slot past the public chain, up to the table end, is E_NOTIMPL and counted. - const unsigned table = xs::allocator_proxy_table_size(); - EXPECT(table == 64); - for (unsigned slot = 9; slot < table; ++slot) { - const std::uint64_t before = xs::allocator_slot_hits(slot); - EXPECT(call_slot(allocator, slot) == E_NOTIMPL); - EXPECT(xs::allocator_slot_hits(slot) == before + 1 && xs::allocator_slot_first_call_seen(slot)); - } - - // Past the table: the vtable read itself faults in the guard region, at the slot's address, and is counted. - EXPECT(xs::command_object_tables_guarded()); - void* const* vtable = *reinterpret_cast(allocator); - EXPECT(read_slot_guarded(vtable, table - 1) == 0); - for (unsigned slot : {table, table + 512, table + 7000}) { - const std::uint64_t before = xs::allocator_table_overruns(); - EXPECT(read_slot_guarded(vtable, slot) == EXCEPTION_ACCESS_VIOLATION); - EXPECT(g_fault_address == reinterpret_cast(&vtable[slot])); - EXPECT(xs::allocator_table_overruns() == before + 1); - } - std::printf("%s: allocator proxy: 9 public slots forwarded, slots 9-%u refused, the guard region names a read " - "past the table; QueryInterface/GetDevice/private data keep the proxy identity\n", label, table - 1); - return 0; -} - -// ---- 2. Lists on the allocator, GPU work, D3D12's allocator rules, residency ---- - -int check_backend(const Backend& b) { - const char* label = b.label; - const unsigned long device_refs = xs::device_proxy_ref_count(b.device); - { - Ref allocator; - EXPECT(SUCCEEDED(b.device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, - IID_PPV_ARGS(&allocator.p)))); - // Vulkan layer: wrapped. Host runtime: its lists could not resolve a proxy, so the PC allocator comes back. - EXPECT(xs::is_allocator_proxy(allocator.p) == b.vulkan); - if (b.vulkan && check_proxy(b, allocator.p)) return 1; - // As IUnknown, and without an output (the device's own answer), as slot 8 does for queues. - Ref as_unknown; - EXPECT(SUCCEEDED(b.device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, __uuidof(IUnknown), - reinterpret_cast(&as_unknown.p)))); - EXPECT(xs::is_allocator_proxy(as_unknown.p) == b.vulkan); -#pragma warning(suppress : 6387) // the null output on purpose - EXPECT(b.device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, __uuidof(ID3D12CommandAllocator), - nullptr) == - b.real->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, __uuidof(ID3D12CommandAllocator), - nullptr)); - Ref not_an_allocator; // asked for an interface the allocator does not have - not_an_allocator.p = reinterpret_cast(1); - const HRESULT wrong_iid = b.device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, - IID_PPV_ARGS(¬_an_allocator.p)); - const bool cleared = !not_an_allocator.p; - not_an_allocator.p = nullptr; - EXPECT(FAILED(wrong_iid) && cleared); - - D3D12_COMMAND_QUEUE_DESC queue_desc{}; - Ref queue; - Ref fence; - EXPECT(SUCCEEDED(b.device->CreateCommandQueue(&queue_desc, IID_PPV_ARGS(&queue.p)))); - EXPECT(SUCCEEDED(b.device->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&fence.p)))); - EXPECT(xs::is_queue_proxy(queue.p) && xs::is_fence_proxy(fence.p)); - - // A list on the allocator: the Vulkan layer resolves the proxy in CreateCommandList. - Ref list; - EXPECT(SUCCEEDED(b.device->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, allocator.p, nullptr, - IID_PPV_ARGS(&list.p)))); - // D3D12's rules, through the proxy: a recording list holds the allocator. - const std::uint64_t resets_before = xs::allocator_slot_hits(8); - EXPECT(allocator->Reset() == E_FAIL); - Ref second; - EXPECT(b.device->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, allocator.p, nullptr, - IID_PPV_ARGS(&second.p)) == E_INVALIDARG && !second.p); - if (copy_round(label, b.device, queue.p, fence.p, list.p, 0x5a, 1)) return 1; - - // Done on the GPU: the allocator resets through the proxy, and the list resets onto it (Reset resolves it). - EXPECT(SUCCEEDED(allocator->Reset())); - EXPECT(SUCCEEDED(list->Reset(allocator.p, nullptr))); - if (copy_round(label, b.device, queue.p, fence.p, list.p, 0xa5, 2)) return 1; - // The two allocator Reset calls above went through slot 8 (list->Reset is the list's method, not this one). - if (b.vulkan) EXPECT(xs::allocator_slot_hits(8) == resets_before + 2); - - // Residency: the real runtime gets the real allocator (an allocator is a pageable). - ID3D12Pageable* pageable = allocator.p; - ID3D12CommandAllocator* real_allocator = - b.vulkan ? xs::allocator_proxy_real_allocator(allocator.p) : allocator.p; - ID3D12Pageable* real_pageable = real_allocator; - EXPECT(b.device->MakeResident(1, &pageable) == b.real->MakeResident(1, &real_pageable)); - EXPECT(b.device->Evict(1, &pageable) == b.real->Evict(1, &real_pageable)); - - // Release orders: the allocator first while its (closed) list still exists, then the list. - if (b.vulkan) EXPECT(xs::command_object_proxy_ref_count(allocator.p) == 1); - allocator.reset(); - list.reset(); - } - EXPECT(xs::device_proxy_ref_count(b.device) == device_refs); // nothing the proxies made kept the device - std::printf("%s: CreateCommandAllocator %s; a list created and Reset on it, two GPU copies through the queue and " - "fence proxies read back exactly; allocator rules and residency as on the real allocator\n", label, - b.vulkan ? "returns an allocator proxy" : "returns the PC allocator unwrapped"); - return 0; -} - -int run_host(IDXGIAdapter1* adapter, const char* label) { - ID3D12Device* real = nullptr; - if (FAILED(D3D12CreateDevice(adapter, D3D_FEATURE_LEVEL_11_0, IID_PPV_ARGS(&real)))) { - std::printf("%s: no D3D12 device, skipped\n", label); - return 77; - } - real->AddRef(); // the backend's own reference; the proxy takes the other - Ref device; - if (FAILED(xs::create_device_proxy(real, __uuidof(ID3D12Device), reinterpret_cast(&device.p)))) { - real->Release(); - real->Release(); - std::fprintf(stderr, "%s: device proxy creation failed\n", label); - return 1; - } - const int result = check_backend(Backend{label, device.p, real, false}); - device.reset(); - if (result) return 1; - if (real->Release() != 0) { - std::fprintf(stderr, "%s: the PC device outlives its proxies\n", label); - return 1; - } - return 0; -} - -} // namespace - -// A failure ends the process with a message on stderr, never in a dialog a test run would wait on. -static void no_dialogs() { - _set_abort_behavior(0, _WRITE_ABORT_MSG | _CALL_REPORTFAULT); - SetErrorMode(GetErrorMode() | SEM_FAILCRITICALERRORS | SEM_NOGPFAULTERRORBOX); -} - -int main() { - no_dialogs(); - std::setvbuf(stdout, nullptr, _IONBF, 0); - const char* label = "allocator_proxy_test"; - int ran = 0; - - // Host PC runtime: WARP, then the first hardware adapter. Under Wine the host d3d12.dll is Wine's own, not the - // PC runtime the proxy is written against, so only Vulkan runs there. - const bool wine = GetProcAddress(GetModuleHandleW(L"ntdll.dll"), "wine_get_version") != nullptr; - Ref factory; - if (wine) std::printf("host D3D12: under Wine, skipped\n"); - if (!wine && SUCCEEDED(CreateDXGIFactory1(IID_PPV_ARGS(&factory.p)))) { - Ref warp; - if (SUCCEEDED(factory->EnumWarpAdapter(IID_PPV_ARGS(&warp.p)))) { - const int r = run_host(warp.p, "host WARP"); - if (r == 1) return 1; - ran += r == 0; - } - for (UINT i = 0;; ++i) { - Ref adapter; - if (factory->EnumAdapters1(i, &adapter.p) == DXGI_ERROR_NOT_FOUND) break; - DXGI_ADAPTER_DESC1 desc{}; - if (FAILED(adapter->GetDesc1(&desc)) || (desc.Flags & DXGI_ADAPTER_FLAG_SOFTWARE)) continue; - char name[128] = {}; - WideCharToMultiByte(CP_UTF8, 0, desc.Description, -1, name, sizeof(name) - 1, nullptr, nullptr); - char host_label[160]; - std::snprintf(host_label, sizeof(host_label), "host %s", name); - const int r = run_host(adapter.p, host_label); - if (r == 1) return 1; - ran += r == 0; - break; - } - } - - // The Vulkan-backed device, the way D3D12XboxCreateDevice hands it out with LEONIDA_D3D12=vulkan. - vktest::Device d; - if (d.create()) { - label = "Vulkan"; - rt::d3d12::VulkanDeviceInfo info{}; - info.get_instance_proc = d.instance_proc; - info.instance = d.instance; - info.physical = d.physical; - info.device = d.device; - info.queue = d.queue; - info.queue_family = d.family; - ID3D12Device* inner = nullptr; - EXPECT(SUCCEEDED(rt::d3d12::create_vulkan_device(info, IID_PPV_ARGS(&inner)))); - inner->AddRef(); // the backend's own reference; the proxy takes the other - ID3D12Device* device = nullptr; - EXPECT(SUCCEEDED(xs::create_device_proxy(inner, __uuidof(ID3D12Device), reinterpret_cast(&device)))); - rt::d3d12::set_device_outer(inner, device); - const int result = check_backend(Backend{label, device, inner, true}); - device->Release(); - if (result) return 1; - EXPECT(inner->Release() == 0); // nothing the proxies made kept the layer's device alive - ++ran; - if (d.validation_errors()) { - std::fprintf(stderr, "%u validation errors\n", d.validation_errors()); - return 1; - } - } else { - std::printf("Vulkan: no device, skipped\n"); - } - - if (!ran) { - std::printf("SKIP allocator_proxy_test: neither a host D3D12 device nor a Vulkan device\n"); - return 77; - } - std::printf("allocator_proxy_test: %d backend(s) passed\n", ran); - return 0; -} diff --git a/runtime/test/api_global_refs_test.cpp b/runtime/test/api_global_refs_test.cpp deleted file mode 100644 index eafc28c89..000000000 --- a/runtime/test/api_global_refs_test.cpp +++ /dev/null @@ -1,121 +0,0 @@ -#include -#include - -#include -#include -#include -#include - -// Internal API implemented by the vendored xtaskqueue runtime. -extern "C" bool __stdcall XTaskQueueUninitialize( - uint32_t timeoutMilliseconds) noexcept; - -static int failures = 0; - -void Check(bool condition, const char* name) -{ - std::printf("%s %s\n", - condition ? "PASS" : "FAIL", name); - - if (!condition) - ++failures; -} - -int main() -{ - std::setvbuf(stdout, nullptr, _IONBF, 0); - std::puts("api_global_refs_test"); - - XTaskQueueHandle owner = nullptr; - XTaskQueueHandle duplicate = nullptr; - - HRESULT hr = XTaskQueueCreate( - XTaskQueueDispatchMode::Manual, - XTaskQueueDispatchMode::Manual, - &owner); - - Check(SUCCEEDED(hr) && owner != nullptr, - "create task queue"); - - if (FAILED(hr) || owner == nullptr) - return 2; - - hr = XTaskQueueDuplicateHandle(owner, &duplicate); - - Check(SUCCEEDED(hr) && duplicate != nullptr, - "duplicate task queue handle"); - - if (FAILED(hr) || duplicate == nullptr) - { - XTaskQueueCloseHandle(owner); - return 3; - } - - XTaskQueueCloseHandle(owner); - - Check(!XTaskQueueUninitialize(0), - "uninitialize rejects outstanding handle"); - - XTaskQueueCloseHandle(duplicate); - - Check(XTaskQueueUninitialize(1000), - "uninitialize succeeds after final close"); - - owner = nullptr; - duplicate = nullptr; - - hr = XTaskQueueCreate( - XTaskQueueDispatchMode::Manual, - XTaskQueueDispatchMode::Manual, - &owner); - - Check(SUCCEEDED(hr) && owner != nullptr, - "create queue for concurrent shutdown"); - - if (FAILED(hr) || owner == nullptr) - return 4; - - hr = XTaskQueueDuplicateHandle(owner, &duplicate); - - Check(SUCCEEDED(hr) && duplicate != nullptr, - "duplicate handle for concurrent shutdown"); - - if (FAILED(hr) || duplicate == nullptr) - { - XTaskQueueCloseHandle(owner); - return 5; - } - - XTaskQueueCloseHandle(owner); - - std::atomic start{ false }; - - std::thread closer([&] - { - while (!start.load(std::memory_order_acquire)) - std::this_thread::yield(); - - std::this_thread::sleep_for( - std::chrono::milliseconds(75)); - - XTaskQueueCloseHandle(duplicate); - }); - - start.store(true, std::memory_order_release); - - bool shutdownCompleted = XTaskQueueUninitialize(2000); - - closer.join(); - - Check(shutdownCompleted, - "uninitialize waits for concurrent final close"); - - Check(XTaskQueueUninitialize(1000), - "no outstanding references after shutdown"); - - std::printf("RESULT: %s (%d failures)\n", - failures == 0 ? "PASS" : "FAIL", - failures); - - return failures == 0 ? 0 : 1; -} diff --git a/runtime/test/api_ref_state_test.cpp b/runtime/test/api_ref_state_test.cpp deleted file mode 100644 index b9ecf36b8..000000000 --- a/runtime/test/api_ref_state_test.cpp +++ /dev/null @@ -1,315 +0,0 @@ -#include -#include - -#include -#include -#include - -static int failures = 0; - -void Check(bool condition, const char* name) -{ - std::printf("%s %s\n", - condition ? "PASS" : "FAIL", name); - - if (!condition) - ++failures; -} - -struct RaceContext -{ - ApiRefState state; - HANDLE rundownEntered = nullptr; - HANDLE allowRundownExit = nullptr; -}; - -DWORD WINAPI RundownThread(void* arg) -{ - auto& ctx = *static_cast(arg); - - if (ctx.state.AddRef() != 0) - return 1; - - auto finalRelease = ctx.state.Release(); - - if (!finalRelease.startRundown || - finalRelease.remaining != 0) - return 2; - - // Simulate an internal AddRef during RundownObject(). - if (ctx.state.AddRef() != 0) - return 3; - - SetEvent(ctx.rundownEntered); - - if (WaitForSingleObject( - ctx.allowRundownExit, 3000) != WAIT_OBJECT_0) - return 4; - - auto internalRelease = ctx.state.Release(); - - if (internalRelease.startRundown || - internalRelease.remaining != 0) - return 5; - - return 0; -} - -void CheckPinWinsBeforeFinalRelease() -{ - constexpr int rounds = 200; - int failuresLocal = 0; - - for (int i = 0; i < rounds; ++i) - { - ApiRefState state; - state.AddRef(); - - std::atomic pinFinished{ false }; - std::atomic allowPinRelease{ false }; - - bool acquired = false; - ApiRefState::ReleaseResult pinRelease{ 0, false }; - - std::thread contender([&] - { - acquired = state.TryAddRef(); - - pinFinished.store(true, std::memory_order_release); - - if (acquired) - { - while (!allowPinRelease.load( - std::memory_order_acquire)) - { - std::this_thread::yield(); - } - - pinRelease = state.Release(); - } - }); - - while (!pinFinished.load(std::memory_order_acquire)) - { - std::this_thread::yield(); - } - - const auto ownerRelease = state.Release(); - - bool valid = - acquired && - ownerRelease.remaining == 1 && - !ownerRelease.startRundown && - state.RefCount() == 1 && - !state.IsDying(); - - allowPinRelease.store(true, std::memory_order_release); - - contender.join(); - - valid = - valid && - pinRelease.remaining == 0 && - pinRelease.startRundown && - state.RefCount() == 0 && - state.IsDying() && - !state.TryAddRef(); - - if (!valid) - { - ++failuresLocal; - } - } - - Check(failuresLocal == 0, - "pin acquired before final owner Release stays valid"); - - std::printf( - "forced pin-first rounds: %d, failures: %d\n", - rounds, failuresLocal); -} -void CheckFinalReleaseRace() -{ - constexpr int rounds = 1000; - int badRundown = 0; - int badFinalState = 0; - int successfulPins = 0; - - for (int i = 0; i < rounds; ++i) - { - ApiRefState state; - state.AddRef(); - - std::atomic ready{ false }; - std::atomic go{ false }; - std::atomic rundownCount{ 0 }; - std::atomic pinned{ false }; - - std::thread contender([&] - { - ready.store(true, std::memory_order_release); - - while (!go.load(std::memory_order_acquire)) - std::this_thread::yield(); - - if (state.TryAddRef()) - { - pinned.store(true, std::memory_order_relaxed); - - if (state.Release().startRundown) - rundownCount.fetch_add(1); - } - }); - - while (!ready.load(std::memory_order_acquire)) - std::this_thread::yield(); - - go.store(true, std::memory_order_release); - - if (state.Release().startRundown) - rundownCount.fetch_add(1); - - contender.join(); - - if (pinned.load(std::memory_order_relaxed)) - ++successfulPins; - - if (rundownCount.load() != 1) - ++badRundown; - - bool unexpectedPin = state.TryAddRef(); - - if (unexpectedPin) - state.Release(); - - if (state.RefCount() != 0 || - !state.IsDying() || - unexpectedPin) - { - ++badFinalState; - } - } - - Check(badRundown == 0, - "racing final Release starts rundown exactly once"); - - Check(badFinalState == 0, - "racing final Release preserves terminal state"); - - std::printf( - "race rounds: %d, successful pins: %d, rejected pins: %d\n", - rounds, successfulPins, rounds - successfulPins); -} -int main() -{ - std::setvbuf(stdout, nullptr, _IONBF, 0); - - std::puts("api_ref_state_test"); - - ApiRefState state; - - Check(!state.TryAddRef(), - "cannot pin zero-ref object"); - - Check(state.AddRef() == 0, - "initial AddRef"); - - Check(state.TryAddRef(), - "can pin live object"); - - Check(state.RefCount() == 2, - "two references held"); - - auto first = state.Release(); - - Check(first.remaining == 1 && - !first.startRundown, - "non-final Release"); - - auto last = state.Release(); - - Check(last.remaining == 0 && - last.startRundown, - "final Release starts rundown"); - - Check(state.IsDying(), - "dying marker is permanent"); - - Check(!state.TryAddRef(), - "cannot pin after final Release"); - - RaceContext race; - - race.rundownEntered = - CreateEventW(nullptr, TRUE, FALSE, nullptr); - - race.allowRundownExit = - CreateEventW(nullptr, TRUE, FALSE, nullptr); - - if (!race.rundownEntered || !race.allowRundownExit) - return 2; - - HANDLE thread = CreateThread( - nullptr, 0, RundownThread, &race, 0, nullptr); - - if (!thread) - return 3; - - DWORD entered = WaitForSingleObject( - race.rundownEntered, 3000); - - Check(entered == WAIT_OBJECT_0, - "rundown thread reached checkpoint"); - - if (entered == WAIT_OBJECT_0) - { - Check(race.state.IsDying(), - "dying bit survives internal AddRef"); - - Check(race.state.RefCount() == 1, - "temporary internal reference exists"); - - bool rejected = true; - - for (int i = 0; i < 10000; ++i) - { - if (race.state.TryAddRef()) - { - rejected = false; - race.state.Release(); - break; - } - } - - Check(rejected, - "concurrent pins rejected during rundown"); - } - - SetEvent(race.allowRundownExit); - - DWORD joined = WaitForSingleObject(thread, 3000); - - Check(joined == WAIT_OBJECT_0, - "rundown thread completed"); - - if (joined == WAIT_OBJECT_0) - { - DWORD exitCode = 1; - GetExitCodeThread(thread, &exitCode); - - Check(exitCode == 0, - "internal Release did not restart rundown"); - } - - CloseHandle(thread); - CloseHandle(race.rundownEntered); - CloseHandle(race.allowRundownExit); - - CheckPinWinsBeforeFinalRelease(); - CheckFinalReleaseRace(); - - std::printf("RESULT: %s (%d failures)\n", - failures == 0 ? "PASS" : "FAIL", failures); - - return failures == 0 ? 0 : 1; -} diff --git a/runtime/test/arena_size_test.cpp b/runtime/test/arena_size_test.cpp deleted file mode 100644 index 249af1355..000000000 --- a/runtime/test/arena_size_test.cpp +++ /dev/null @@ -1,113 +0,0 @@ -// The GPU address arena's size (src/arena_size.h) without a GPU: LEONIDA_ARENA_MB's text against synthetic -// maxBufferSize and maxMemoryAllocationSize values, including the RX 6800's (AMD 26.11.2): 2 GiB for both. -// No game data. -#include "../src/arena_size.h" - -#include -#include - -#define CHECK(condition) do { \ - if (!(condition)) { \ - std::fprintf(stderr, "line %d: %s\n", __LINE__, #condition); \ - return 1; \ - } \ -} while (0) - -using namespace leonida; - -namespace { - -constexpr VkDeviceSize MiB = kArenaMiB; -constexpr VkDeviceSize GiB = 1024 * MiB; - -int request_without_limits() { - const ArenaLimits none{}; - // Unset (or empty): the default; otherwise clamped to 16..4095 MiB; text that is no number reads as 0, so 16. - CHECK(decide_arena_size(nullptr, none).bytes == 256 * MiB); - CHECK(decide_arena_size("", none).bytes == 256 * MiB); - CHECK(decide_arena_size("1024", none).bytes == 1024 * MiB); - CHECK(decide_arena_size("1", none).bytes == 16 * MiB); - CHECK(decide_arena_size("0", none).bytes == 16 * MiB); - CHECK(decide_arena_size("lots", none).bytes == 16 * MiB); - CHECK(decide_arena_size("99999", none).bytes == 4095 * MiB); - const ArenaSize s = decide_arena_size("3000", none); - CHECK(s.bytes == 3000 * MiB && s.requested == 3000 * MiB && s.capped == arena_cap_none); - return 0; -} - -int each_limit() { - // RX 6800: both limits 2 GiB. Under them nothing changes; over them both are named. - const ArenaLimits rdna2{2 * GiB, 2 * GiB}; - ArenaSize s = decide_arena_size("2000", rdna2); - CHECK(s.bytes == 2000 * MiB && s.capped == arena_cap_none); - s = decide_arena_size("2048", rdna2); - CHECK(s.bytes == 2 * GiB && s.capped == arena_cap_none); - s = decide_arena_size("3000", rdna2); - CHECK(s.bytes == 2 * GiB && s.requested == 3000 * MiB && s.capped == (arena_cap_buffer | arena_cap_allocation)); - CHECK(std::string_view(arena_cap_name(s.capped)) == "maxBufferSize and maxMemoryAllocationSize"); - - // One limit below the other: that one applies. - s = decide_arena_size("4095", ArenaLimits{1 * GiB, 4 * GiB}); - CHECK(s.bytes == 1 * GiB && s.capped == arena_cap_buffer); - CHECK(std::string_view(arena_cap_name(s.capped)) == "maxBufferSize"); - s = decide_arena_size("4095", ArenaLimits{4 * GiB, 3 * GiB}); - CHECK(s.bytes == 3 * GiB && s.capped == arena_cap_allocation); - CHECK(std::string_view(arena_cap_name(s.capped)) == "maxMemoryAllocationSize"); - - // A limit that is not a whole number of MiB rounds the arena down to one. - s = decide_arena_size("4095", ArenaLimits{2 * GiB + 12345, 0}); - CHECK(s.bytes == 2 * GiB && s.capped == arena_cap_buffer); - return 0; -} - -int unknown_limits() { - // 0 is "not reported": it caps nothing, and the other limit still does. - ArenaSize s = decide_arena_size("3000", ArenaLimits{0, 0}); - CHECK(s.bytes == 3000 * MiB && s.capped == arena_cap_none); - s = decide_arena_size("3000", ArenaLimits{0, 2 * GiB}); - CHECK(s.bytes == 2 * GiB && s.capped == arena_cap_allocation); - s = decide_arena_size("3000", ArenaLimits{2 * GiB, 0}); - CHECK(s.bytes == 2 * GiB && s.capped == arena_cap_buffer); - return 0; -} - -int allocation_overhead() { - // The allocation is the buffer's memory requirement, which can be larger than the buffer: the allocation limit - // is checked against buffer + overhead, the buffer limit against the buffer alone. - const ArenaLimits rdna2{2 * GiB, 2 * GiB}; - ArenaSize s = decide_arena_size("3000", rdna2, 64 * 1024); - CHECK(s.bytes == 2047 * MiB && s.capped == arena_cap_allocation); - CHECK(s.bytes + 64 * 1024 <= rdna2.max_allocation_size); - s = decide_arena_size("3000", rdna2, 1 * MiB); - CHECK(s.bytes == 2047 * MiB && s.capped == arena_cap_allocation); - s = decide_arena_size("1024", rdna2, 1 * MiB); // still far under: unchanged - CHECK(s.bytes == 1024 * MiB && s.capped == arena_cap_none); - // Overhead at or past the limit leaves nothing. - s = decide_arena_size("3000", ArenaLimits{0, 4 * MiB}, 4 * MiB); - CHECK(s.bytes == 0 && s.capped == arena_cap_allocation); - return 0; -} - -int floor_and_limits() { - // The 16 MiB floor applies to the request; a device limit wins over it (no conformant device reports under - // 1 GiB, so this is a simulated device). - ArenaSize s = decide_arena_size("1", ArenaLimits{1 * GiB, 1 * GiB}); - CHECK(s.bytes == 16 * MiB && s.capped == arena_cap_none); - s = decide_arena_size("1", ArenaLimits{8 * MiB, 0}); - CHECK(s.bytes == 8 * MiB && s.requested == 16 * MiB && s.capped == arena_cap_buffer); - s = decide_arena_size("64", ArenaLimits{0, 32 * MiB}); - CHECK(s.bytes == 32 * MiB && s.capped == arena_cap_allocation); - // Under 1 MiB: nothing to create. - s = decide_arena_size(nullptr, ArenaLimits{512 * 1024, 0}); - CHECK(s.bytes == 0 && s.capped == arena_cap_buffer); - return 0; -} - -} // namespace - -int main() { - for (const auto test : {request_without_limits, each_limit, unknown_limits, allocation_overhead, floor_and_limits}) - if (test()) return 1; - std::printf("arena_size: request clamp, each device limit, unknown limits, allocation overhead and the floor\n"); - return 0; -} diff --git a/runtime/test/bcrypt_rng_test.cpp b/runtime/test/bcrypt_rng_test.cpp deleted file mode 100644 index ffdd70155..000000000 --- a/runtime/test/bcrypt_rng_test.cpp +++ /dev/null @@ -1,168 +0,0 @@ -// Tests for runtime/shims/bcrypt_rng.cpp through rt::shims::find. -#include - -#ifndef _NTDEF_ -using NTSTATUS = LONG; -#endif -#include - -#include -#include -#include - -#include "shims.h" - -namespace rt::bcrypt_rng { -void set_host_rng_enabled_for_test(bool enabled); -} // namespace rt::bcrypt_rng - -namespace { - -constexpr NTSTATUS kStatusSuccess = 0x00000000L; -constexpr NTSTATUS kStatusUnsuccessful = static_cast(0xC0000001L); -constexpr NTSTATUS kStatusInvalidHandle = static_cast(0xC0000008L); -constexpr NTSTATUS kStatusInvalidParameter = static_cast(0xC000000DL); -constexpr NTSTATUS kStatusNotFound = static_cast(0xC0000225L); - -using OpenAlgFn = NTSTATUS(WINAPI*)(BCRYPT_ALG_HANDLE*, LPCWSTR, LPCWSTR, ULONG); -using CloseAlgFn = NTSTATUS(WINAPI*)(BCRYPT_ALG_HANDLE, ULONG); -using GenRandomFn = NTSTATUS(WINAPI*)(BCRYPT_ALG_HANDLE, PUCHAR, ULONG, ULONG); - -int g_checks = 0; -int g_failures = 0; - -void check(bool condition, const char* what) { - ++g_checks; - std::printf("%s %s\n", condition ? "PASS" : "FAIL", what); - if (!condition) ++g_failures; -} - -template -Fn resolve(const char* name) { - return reinterpret_cast(rt::shims::find("bcrypt.dll", name)); -} - -void test_registry_coverage() { - check(resolve("BCryptOpenAlgorithmProvider") != nullptr, "BCryptOpenAlgorithmProvider resolves"); - check(resolve("BCryptGenRandom") != nullptr, "BCryptGenRandom resolves"); - check(resolve("BCryptCloseAlgorithmProvider") != nullptr, "BCryptCloseAlgorithmProvider resolves"); -} - -void test_provider_handles_and_validation() { - auto open_alg = resolve("BCryptOpenAlgorithmProvider"); - auto gen_random = resolve("BCryptGenRandom"); - auto close_alg = resolve("BCryptCloseAlgorithmProvider"); - - BCRYPT_ALG_HANDLE h = nullptr; - check(open_alg(nullptr, BCRYPT_RNG_ALGORITHM, nullptr, 0) == kStatusInvalidParameter, - "BCryptOpenAlgorithmProvider rejects null out handle"); - check(open_alg(&h, nullptr, nullptr, 0) == kStatusInvalidParameter, - "BCryptOpenAlgorithmProvider rejects null algorithm id"); - check(open_alg(&h, L"LEONIDA_NO_SUCH_ALG", nullptr, 0) == kStatusNotFound, - "BCryptOpenAlgorithmProvider reports STATUS_NOT_FOUND for unknown algorithm"); - - check(open_alg(&h, BCRYPT_RNG_ALGORITHM, nullptr, 0) == kStatusSuccess && h != nullptr, - "BCryptOpenAlgorithmProvider opens BCRYPT_RNG_ALGORITHM"); - - uint8_t buf[32]{}; - check(gen_random(h, nullptr, 0, 0) == kStatusInvalidParameter, - "BCryptGenRandom rejects null buffer"); - check(gen_random(nullptr, buf, sizeof(buf), 0) == kStatusInvalidHandle, - "BCryptGenRandom rejects null handle without BCRYPT_USE_SYSTEM_PREFERRED_RNG"); - check(gen_random(h, buf, sizeof(buf), BCRYPT_USE_SYSTEM_PREFERRED_RNG) == kStatusInvalidParameter, - "BCryptGenRandom rejects non-null handle with BCRYPT_USE_SYSTEM_PREFERRED_RNG"); - - std::memset(buf, 0, sizeof(buf)); - check(gen_random(h, buf, sizeof(buf), 0) == kStatusSuccess, - "BCryptGenRandom succeeds with open RNG handle"); - - bool nonzero = false; - for (uint8_t b : buf) { - if (b != 0) nonzero = true; - } - check(nonzero, "BCryptGenRandom writes non-zero random bytes"); - - uint8_t sys_buf[32]{}; - check(gen_random(nullptr, sys_buf, sizeof(sys_buf), BCRYPT_USE_SYSTEM_PREFERRED_RNG) == kStatusSuccess, - "BCryptGenRandom succeeds with BCRYPT_USE_SYSTEM_PREFERRED_RNG"); - - check(close_alg(nullptr, 0) == kStatusInvalidHandle, - "BCryptCloseAlgorithmProvider rejects nullptr"); - check(close_alg(reinterpret_cast(static_cast(0x1234)), 0) == kStatusInvalidHandle, - "BCryptCloseAlgorithmProvider rejects foreign pointer"); - check(close_alg(h, 0) == kStatusSuccess, - "BCryptCloseAlgorithmProvider closes live RNG handle"); - check(close_alg(h, 0) == kStatusInvalidHandle, - "BCryptCloseAlgorithmProvider refuses double close safely"); - check(gen_random(h, buf, sizeof(buf), 0) == kStatusInvalidHandle, - "BCryptGenRandom rejects closed handle safely"); -} - -void test_fail_closed_when_host_rng_unavailable(bool seeded) { - if (seeded) return; - auto open_alg = resolve("BCryptOpenAlgorithmProvider"); - auto gen_random = resolve("BCryptGenRandom"); - auto close_alg = resolve("BCryptCloseAlgorithmProvider"); - - BCRYPT_ALG_HANDLE h = nullptr; - check(open_alg(&h, BCRYPT_RNG_ALGORITHM, nullptr, 0) == kStatusSuccess && h != nullptr, - "fail-closed setup opens RNG handle"); - - rt::bcrypt_rng::set_host_rng_enabled_for_test(false); - uint8_t handle_buf[16]{}; - std::memset(handle_buf, 0xAA, sizeof(handle_buf)); - const NTSTATUS handle_st = gen_random(h, handle_buf, sizeof(handle_buf), 0); - bool handle_untouched = true; - for (uint8_t b : handle_buf) { - if (b != 0xAA) handle_untouched = false; - } - check(handle_st == kStatusUnsuccessful && handle_untouched, - "BCryptGenRandom fails closed with STATUS_UNSUCCESSFUL without mutating buffer (handle path)"); - - uint8_t sys_buf[16]{}; - std::memset(sys_buf, 0x55, sizeof(sys_buf)); - const NTSTATUS sys_st = gen_random(nullptr, sys_buf, sizeof(sys_buf), BCRYPT_USE_SYSTEM_PREFERRED_RNG); - bool sys_untouched = true; - for (uint8_t b : sys_buf) { - if (b != 0x55) sys_untouched = false; - } - check(sys_st == kStatusUnsuccessful && sys_untouched, - "BCryptGenRandom fails closed with STATUS_UNSUCCESSFUL without mutating buffer (system RNG path)"); - - rt::bcrypt_rng::set_host_rng_enabled_for_test(true); - close_alg(h, 0); -} - -void test_seeded_determinism(bool seeded) { - if (!seeded) return; - auto open_alg = resolve("BCryptOpenAlgorithmProvider"); - auto gen_random = resolve("BCryptGenRandom"); - auto close_alg = resolve("BCryptCloseAlgorithmProvider"); - - BCRYPT_ALG_HANDLE h = nullptr; - check(open_alg(&h, BCRYPT_RNG_ALGORITHM, nullptr, 0) == kStatusSuccess && h != nullptr, - "seeded BCryptOpenAlgorithmProvider opens RNG"); - uint8_t buf[16]{}; - check(gen_random(h, buf, sizeof(buf), 0) == kStatusSuccess, "seeded BCryptGenRandom succeeds"); - // Ensure reproducible non-trivial stream across runs when LEONIDA_RNG_SEED=0x123456789abcdef0 is set. - uint8_t second[16]{}; - check(gen_random(nullptr, second, sizeof(second), BCRYPT_USE_SYSTEM_PREFERRED_RNG) == kStatusSuccess && - std::memcmp(buf, second, sizeof(buf)) != 0, - "seeded PRNG advances cleanly across consecutive calls"); - close_alg(h, 0); -} - -} // namespace - -int main(int argc, char** argv) { - bool seeded = false; - for (int i = 1; i < argc; ++i) { - if (std::strcmp(argv[i], "--seeded") == 0) seeded = true; - } - test_registry_coverage(); - test_provider_handles_and_validation(); - test_fail_closed_when_host_rng_unavailable(seeded); - test_seeded_determinism(seeded); - std::printf("%d check(s), %d failure(s)\n", g_checks, g_failures); - return g_failures ? 1 : 0; -} diff --git a/runtime/test/bindless_sizing_test.cpp b/runtime/test/bindless_sizing_test.cpp deleted file mode 100644 index 4553f25b6..000000000 --- a/runtime/test/bindless_sizing_test.cpp +++ /dev/null @@ -1,226 +0,0 @@ -// bindless::size_bindings with synthetic device limits: no GPU. The counts of set 0 come from the device's descriptor -// limits (vulkan_bindless.h): today's sizes where a device is at them, larger 2D, sampler and storage arrays where it -// has room, and less where it is below them. -#ifndef VK_NO_PROTOTYPES -#define VK_NO_PROTOTYPES -#endif -#include "../src/vulkan_bindless.h" - -#include - -#define EXPECT(condition) do { \ - if (!(condition)) { std::fprintf(stderr, "line %d: %s\n", __LINE__, #condition); return 1; } \ -} while (0) - -using namespace leonida; - -namespace { - -struct Device { - VkPhysicalDeviceLimits limits{}; - VkPhysicalDeviceVulkan11Properties v11{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_1_PROPERTIES}; - VkPhysicalDeviceVulkan12Properties v12{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_2_PROPERTIES}; -}; - -// The same descriptor limit for every type, update-after-bind or not; the others are unlimited. -Device uniform(std::uint32_t plain, std::uint32_t update_after_bind) { - Device d; - auto& l = d.limits; - l.maxPerStageDescriptorSampledImages = l.maxDescriptorSetSampledImages = plain; - l.maxPerStageDescriptorSamplers = l.maxDescriptorSetSamplers = plain; - l.maxPerStageDescriptorStorageImages = l.maxDescriptorSetStorageImages = plain; - l.maxPerStageResources = 0xffffffffu; - l.maxColorAttachments = 8; - l.maxSamplerAllocationCount = 4000; // NVIDIA's; the minimum Vulkan allows - auto& u = d.v12; - u.maxPerStageDescriptorUpdateAfterBindSampledImages = update_after_bind; - u.maxDescriptorSetUpdateAfterBindSampledImages = update_after_bind; - u.maxPerStageDescriptorUpdateAfterBindSamplers = u.maxDescriptorSetUpdateAfterBindSamplers = update_after_bind; - u.maxPerStageDescriptorUpdateAfterBindStorageImages = update_after_bind; - u.maxDescriptorSetUpdateAfterBindStorageImages = update_after_bind; - u.maxPerStageUpdateAfterBindResources = 0xffffffffu; - u.maxUpdateAfterBindDescriptorsInAllPools = 0xffffffffu; - d.v11.maxPerSetDescriptors = 0xffffffffu; - return d; -} - -BindlessFeatures with_ms(bool update_after_bind) { - BindlessFeatures f{}; - f.update_after_bind = update_after_bind; - f.ms_samples.fill(VK_SAMPLE_COUNT_4_BIT); - return f; -} - -struct Totals { std::uint32_t sampled = 0, samplers = 0, storage = 0, all = 0; }; -Totals totals(const BindlessFeatures& f) { - Totals t; - for (std::uint32_t b = 0; b < bindless::binding_count; ++b) { - if (!bindless::binding_enabled(b, f)) continue; - const auto type = bindless::bindings[b].type; - if (type == VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE) t.sampled += f.counts[b]; - if (type == VK_DESCRIPTOR_TYPE_SAMPLER) t.samplers += f.counts[b]; - if (type == VK_DESCRIPTOR_TYPE_STORAGE_IMAGE) t.storage += f.counts[b]; - t.all += f.counts[b]; - } - return t; -} - -std::uint32_t count(const BindlessFeatures& f, ImageDimension dimension) { - return f.counts[bindless::sampled_binding(dimension)]; -} -std::uint32_t storage(const BindlessFeatures& f, ImageDimension dimension) { - return f.counts[bindless::storage_binding(dimension, 0)]; -} - -// Every storage array of a dimension, the r32ui one included, holds the same indices. -bool storage_consistent(const BindlessFeatures& f) { - for (std::uint32_t d = 0; d < 4; ++d) { - const auto dimension = ImageDimension(d); - const auto held = storage(f, dimension); - if (held > count(f, dimension)) return false; - for (std::uint32_t c = 0; c < 3; ++c) - if (f.counts[bindless::storage_binding(dimension, c)] != held) return false; - if (bindless::r32ui_binding(dimension) != bindless::no_binding && - f.counts[bindless::r32ui_binding(dimension)] != held) - return false; - } - return true; -} - -} // namespace - -int main() { - using D = ImageDimension; - constexpr auto defaults = bindless::default_counts(); - static_assert(defaults[0] == 4096 && defaults[bindless::sampler_binding] == 1024 && defaults[8] == 256); - - // An RTX 5070 (driver 621.24): 1048576 of each descriptor type, update-after-bind or not, 4000 samplers. - for (const bool update_after_bind : {true, false}) { - const Device d = uniform(1048576, 1048576); - BindlessFeatures f = with_ms(update_after_bind); - EXPECT(bindless::size_bindings(f, d.limits, d.v11, d.v12)); - EXPECT(count(f, D::dim_2d) == bindless::max_2d_images); - EXPECT(f.counts[bindless::sampler_binding] == 4000 - bindless::reserved_samplers); - EXPECT(f.counts[bindless::sampler_binding] > 2048); // a full sampler heap and the fallback - EXPECT(storage(f, D::dim_2d) == bindless::max_storage_indices); - EXPECT(storage(f, D::dim_2d_array) == 1024 && storage(f, D::dim_3d) == 256 && storage(f, D::dim_1d) == 256); - EXPECT(count(f, D::dim_2d_array) == 1024 && count(f, D::dim_3d) == 256 && count(f, D::dim_1d) == 256); - EXPECT(f.ms_samples[0] == VK_SAMPLE_COUNT_4_BIT && f.ms_samples[2] == VK_SAMPLE_COUNT_4_BIT); - EXPECT(storage_consistent(f)); - if (update_after_bind) - std::printf("RTX 5070-like: %u 2D images, %u samplers, %u storage indices in 2D, %u descriptors\n", - count(f, D::dim_2d), f.counts[bindless::sampler_binding], storage(f, D::dim_2d), totals(f).all); - } - - // At today's sizes exactly (5632 sampled images, 1024 samplers, 3584 storage images): today's set, no MS pairs. - { - Device d = uniform(1048576, 1048576); - d.v12.maxPerStageDescriptorUpdateAfterBindSampledImages = 5632; - d.v12.maxPerStageDescriptorUpdateAfterBindSamplers = 1024; - d.v12.maxPerStageDescriptorUpdateAfterBindStorageImages = 3584; - BindlessFeatures f = with_ms(true); - EXPECT(bindless::size_bindings(f, d.limits, d.v11, d.v12)); - EXPECT(count(f, D::dim_2d) == 4096 && f.counts[bindless::sampler_binding] == 1024 && - storage(f, D::dim_2d) == 256); - for (std::uint32_t b = 0; b < bindless::first_ms_binding; ++b) - if (bindless::bindings[b].type != VK_DESCRIPTOR_TYPE_STORAGE_IMAGE) EXPECT(f.counts[b] == defaults[b]); - EXPECT(f.ms_samples == (std::array{VK_SAMPLE_COUNT_1_BIT, VK_SAMPLE_COUNT_1_BIT, VK_SAMPLE_COUNT_1_BIT})); - EXPECT(storage_consistent(f)); - } - - // A small device below today's sizes: smaller arrays that fit, and false. - { - Device d = uniform(1048576, 1048576); - d.limits.maxPerStageDescriptorSampledImages = 3000; - d.limits.maxPerStageDescriptorSamplers = 512; - d.limits.maxPerStageDescriptorStorageImages = 2000; - d.limits.maxPerStageResources = 4500; - BindlessFeatures f = with_ms(false); - EXPECT(!bindless::size_bindings(f, d.limits, d.v11, d.v12)); - const Totals t = totals(f); - EXPECT(t.sampled <= 3000 && t.samplers <= 512 && t.storage <= 2000 && t.sampled + t.storage + 1 + 8 <= 4500); - EXPECT(count(f, D::dim_2d) >= 1 && count(f, D::dim_2d) < 4096 && f.counts[bindless::sampler_binding] == 512); - EXPECT(f.ms_samples[0] == VK_SAMPLE_COUNT_1_BIT); - EXPECT(storage_consistent(f)); - } - - // Update-after-bind and plain limits differ: each layout is sized by its own. - { - const Device d = uniform(16384, 1048576); - BindlessFeatures uab = with_ms(true), plain = with_ms(false); - EXPECT(bindless::size_bindings(uab, d.limits, d.v11, d.v12)); - EXPECT(bindless::size_bindings(plain, d.limits, d.v11, d.v12)); - EXPECT(count(uab, D::dim_2d) == bindless::max_2d_images); - const Totals t = totals(plain); - EXPECT(count(plain, D::dim_2d) > 4096 && count(plain, D::dim_2d) < 16384); - EXPECT(t.sampled + bindless::growth_headroom <= 16384 && t.storage + bindless::growth_headroom <= 16384); - EXPECT(plain.ms_samples[0] == VK_SAMPLE_COUNT_4_BIT && storage_consistent(plain)); - EXPECT(plain.counts[bindless::sampler_binding] == 4000 - bindless::reserved_samplers); - } - - // maxPerSetDescriptors stops growth but never takes a count below today's. - { - Device d = uniform(1048576, 1048576); - d.v11.maxPerSetDescriptors = 1024; - BindlessFeatures f = with_ms(true); - EXPECT(bindless::size_bindings(f, d.limits, d.v11, d.v12)); - EXPECT(count(f, D::dim_2d) == 4096 && f.counts[bindless::sampler_binding] == 1024 && - storage(f, D::dim_2d) == 256); - d.v11.maxPerSetDescriptors = 30000; - f = with_ms(true); - EXPECT(bindless::size_bindings(f, d.limits, d.v11, d.v12)); - EXPECT(totals(f).all <= 30000 && count(f, D::dim_2d) > 4096); - } - - // D3D-219: past maxPerSetDescriptors, growth follows layout_supported (vkGetDescriptorSetLayoutSupport), which - // is asked only above that limit. Intel's Xe-LP reports 6159 and supports the full sizes. - { - Device d = uniform(1048576, 1048576); - d.v11.maxPerSetDescriptors = 6159; - d.limits.maxSamplerAllocationCount = 4000; - unsigned asked = 0, asked_within = 0; - const auto all_supported = [&](const BindlessFeatures& candidate) { - ++asked; - asked_within += totals(candidate).all <= 6159; - return true; - }; - BindlessFeatures f = with_ms(true); - EXPECT(bindless::size_bindings(f, d.limits, d.v11, d.v12, all_supported)); - EXPECT(asked > 0 && asked_within == 0); - EXPECT(count(f, D::dim_2d) == bindless::max_2d_images && - f.counts[bindless::sampler_binding] == 4000 - bindless::reserved_samplers); - EXPECT(storage(f, D::dim_2d) == bindless::max_storage_indices && storage_consistent(f)); - - // A driver that supports less: growth stops where it says no. - const auto up_to_20000 = [&](const BindlessFeatures& candidate) { return totals(candidate).all <= 20000; }; - f = with_ms(true); - EXPECT(bindless::size_bindings(f, d.limits, d.v11, d.v12, up_to_20000)); - EXPECT(totals(f).all <= 20000 && totals(f).all > 6159 && count(f, D::dim_2d) > 4096); - - // Without the callback, maxPerSetDescriptors still caps growth as before. - f = with_ms(true); - EXPECT(bindless::size_bindings(f, d.limits, d.v11, d.v12)); - EXPECT(totals(f).all <= 6159 || (count(f, D::dim_2d) == 4096 && f.counts[bindless::sampler_binding] == 1024)); - } - - // MoltenVK 1.4.3 on an M3 Max: update-after-bind limits of 1000000 sampled images and 500000 samplers, but - // maxPerSetDescriptors 1212 and a vkGetDescriptorSetLayoutSupport that accepts only fewer descriptors than that - // (MVKDevice::getDescriptorSetLayoutSupport), though the device creates and samples far larger sets. So the - // set keeps the default counts: 1024 samplers, short of a full D3D12 sampler heap (d3d12_descriptor_test). - { - Device d = uniform(1048576, 1000000); - d.v12.maxPerStageDescriptorUpdateAfterBindSamplers = d.v12.maxDescriptorSetUpdateAfterBindSamplers = 500000; - d.limits.maxSamplerAllocationCount = 500000; - d.v11.maxPerSetDescriptors = 1212; - const auto below_1212 = [](const BindlessFeatures& candidate) { return totals(candidate).all < 1212; }; - BindlessFeatures f = with_ms(true); - EXPECT(bindless::size_bindings(f, d.limits, d.v11, d.v12, below_1212)); - EXPECT(count(f, D::dim_2d) == 4096 && f.counts[bindless::sampler_binding] == 1024 && - storage(f, D::dim_2d) == 256); - } - - // The default features are today's counts, which the device-less users (vk_image_fuzz) still get. - EXPECT(BindlessFeatures{}.counts == defaults); - std::printf("bindless sizing: synthetic limits gave the expected counts\n"); - return 0; -} diff --git a/runtime/test/bink_abi_test.cpp b/runtime/test/bink_abi_test.cpp deleted file mode 100644 index 0738e4b77..000000000 --- a/runtime/test/bink_abi_test.cpp +++ /dev/null @@ -1,389 +0,0 @@ -// Optional Windows test: measure the Bink2Scarlett ABI the runtime needs, over every stream of the package's -// movies.rpf, through the package's own DLL mapped by rt::Loader. -// -// LEONIDA_GAME_DIR= (contains Bink2Scarlett.dll and movies.rpf) -// LEONIDA_BINK_INDEX= (tools/bink_index.py /movies.rpf --out ) -// LEONIDA_BINK_LIMIT= (optional: only the first n streams of the index) -// -// Each stream is opened inside the archive with BinkSetFileOffset + BinkOpen(BINKFILEOFFSET), so nothing is -// extracted. For every stream the test reads the start of the HBINK and the BINKSUMMARY that BinkGetSummary writes, -// and keeps the word offsets whose value equals the stream header's (width, height, frame count, frame rate); an -// offset survives only if it matches on every stream. It also tallies the return values of BinkWait, BinkDoFrame and -// BinkCopyToBuffer. It prints offsets, counts and return values only: no frame, pixel or audio data. -// -// With either variable unset it prints "SKIP (no package/index)" and exits 77 (CTest skip). -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include "../shims/shims.h" -#include "../src/pe_loader.h" - -namespace { - -int g_failures = 0; - -void check(bool condition, const std::string& what) { - std::printf("%s %s\n", condition ? "PASS" : "FAIL", what.c_str()); - if (!condition) ++g_failures; -} - -[[noreturn]] void fatal(const std::string& what) { - std::fprintf(stderr, "FAIL %s\n", what.c_str()); - std::exit(1); -} - -std::string env(const char* name) { - const char* v = std::getenv(name); - return v ? v : ""; -} - -uint32_t read_u32(const uint8_t* p) { - return (uint32_t)p[0] | ((uint32_t)p[1] << 8) | ((uint32_t)p[2] << 16) | ((uint32_t)p[3] << 24); -} - -struct Stream { - uint64_t offset = 0; - uint32_t frames = 0, width = 0, height = 0, fps_num = 0, fps_den = 0, audio_tracks = 0; -}; - -// The stream header at `offset` (the same fields bink_decode_test reads from a carved file). -Stream read_stream(std::ifstream& f, uint64_t offset) { - uint8_t h[0x2C]{}; - f.clear(); - f.seekg((std::streamoff)offset); - f.read(reinterpret_cast(h), sizeof(h)); - if (f.gcount() != (std::streamsize)sizeof(h)) fatal("index offset is past the end of movies.rpf"); - if (h[0] != 'K' || h[1] != 'B' || h[2] != '2') fatal("index offset does not start a KB2 stream"); - Stream s; - s.offset = offset; - s.frames = read_u32(h + 0x08); - s.width = read_u32(h + 0x14); - s.height = read_u32(h + 0x18); - s.fps_num = read_u32(h + 0x1C); - s.fps_den = read_u32(h + 0x20); - s.audio_tracks = read_u32(h + 0x28); - if (!s.frames || !s.width || !s.height || !s.fps_num || !s.fps_den) fatal("stream header has a zero field"); - if (s.width > 16384 || s.height > 16384) fatal("stream header has an implausible frame size"); - return s; -} - -// The "offset" column of tools/bink_index.py's CSV. -std::vector read_index(const std::filesystem::path& path) { - std::ifstream f(path); - if (!f) fatal("cannot open LEONIDA_BINK_INDEX"); - std::string line; - if (!std::getline(f, line)) fatal("LEONIDA_BINK_INDEX is empty"); - std::vector head; - for (std::stringstream ss(line); std::getline(ss, line, ',');) head.push_back(line); - const auto col = std::find(head.begin(), head.end(), "offset"); - if (col == head.end()) fatal("LEONIDA_BINK_INDEX has no offset column"); - const size_t at = (size_t)(col - head.begin()); - std::vector out; - while (std::getline(f, line)) { - if (line.empty()) continue; - std::vector cells; - for (std::stringstream ss(line); std::getline(ss, line, ',');) cells.push_back(line); - if (cells.size() <= at) fatal("LEONIDA_BINK_INDEX row has no offset"); - out.push_back(std::strtoull(cells[at].c_str(), nullptr, 10)); - } - return out; -} - -constexpr size_t kWords = 64; // the first 256 bytes of each structure -using Words = std::vector; -using Mask = std::bitset; - -// Copy up to kWords words from `p`; stops at the first unreadable word. No C++ objects here: SEH only. -size_t copy_words(const void* p, uint32_t* out) { - size_t n = 0; - __try { - for (; n < kWords; ++n) out[n] = static_cast(p)[n]; - } __except (EXCEPTION_EXECUTE_HANDLER) { - } - return n; -} - -Words snapshot(const void* p) { - Words w(kWords, 0); - w.resize(copy_words(p, w.data())); - return w; -} - -Mask equal_to(const Words& w, uint32_t value) { - Mask m; - for (size_t i = 0; i < w.size(); ++i) m[i] = w[i] == value; - return m; -} - -std::string offsets(const Mask& m) { - std::string s; - for (size_t i = 0; i < kWords; ++i) - if (m[i]) { - char b[16]; - std::snprintf(b, sizeof(b), "%s0x%02zx", s.empty() ? "" : " ", i * 4); - s += b; - } - return s.empty() ? "(none)" : s; -} - -std::string hex(size_t v) { - char b[24]; - std::snprintf(b, sizeof(b), "%zx", v); - return b; -} - -// Bytes of a sentinel-filled buffer that a call replaced: the highest one is a lower bound on the struct size. -size_t written_extent(const std::vector& buf, uint8_t sentinel) { - for (size_t i = buf.size(); i-- > 0;) - if (buf[i] != sentinel) return i + 1; - return 0; -} - -struct BinkApi { - void* (*open)(const char*, uint32_t) = nullptr; - uint32_t (*wait)(void*) = nullptr; - uint32_t (*do_frame)(void*) = nullptr; - uint32_t (*copy)(void*, void*, uint32_t, uint32_t, uint32_t, uint32_t, uint32_t) = nullptr; - void (*next)(void*) = nullptr; - void (*go_to)(void*, uint32_t, uint32_t) = nullptr; - void (*close)(void*) = nullptr; - void (*summary)(void*, void*) = nullptr; - const char* (*get_error)() = nullptr; - void (*set_file_offset)(uint64_t) = nullptr; - void (*set_frame_rate)(uint32_t, uint32_t) = nullptr; // applies to the next BinkOpen with kFrameRate -}; - -template void bind(rt::Module& m, const char* name, F& out) { - auto it = m.exports.find(name); - if (it == m.exports.end()) fatal(std::string("Bink2Scarlett.dll does not export ") + name); - out = reinterpret_cast(it->second); -} - -constexpr uint32_t kCopyBgra32 = 3; // the BinkCopyToBuffer format bink_decode_test measured as 32-bit BGRA -constexpr uint32_t kFileOffset = 0x20; // BinkOpen flag: start at the offset BinkSetFileOffset gave -// BinkOpen flag: use the rate BinkSetFrameRate gave. Measured: of the 32 single-bit flags only 0x1000 changes the -// rate fields (RAD's Bink 1 header has BINKFRAMERATE at 0x00080000; that bit changes nothing here). -constexpr uint32_t kFrameRate = 0x1000; -constexpr size_t kSummaryBytes = 1024; -constexpr size_t kSummaryWritten = 144; // BinkGetSummary writes bytes 0..143, every one, on all 515 streams - -// One field, matched on every stream: the word offsets where the structure held the stream's value each time. -// hbink_at/summary_at are the measured offsets (docs/movies.md section 5); -1 when the structure has no such field. -struct Field { - const char* name; - int hbink_at, summary_at; - Mask hbink, summary; - uint32_t streams = 0; -}; - -bool has(const Mask& m, int byte_offset) { return byte_offset >= 0 && m[(size_t)byte_offset / 4]; } - -} // namespace - -int main() { - const std::string game_dir_arg = env("LEONIDA_GAME_DIR"); - const std::string index_arg = env("LEONIDA_BINK_INDEX"); - if (game_dir_arg.empty() || index_arg.empty()) { - std::printf("SKIP (no package/index)\n"); - return 77; - } - const std::filesystem::path game_dir = game_dir_arg; - const std::filesystem::path archive = game_dir / "movies.rpf"; - std::error_code ec; - if (!std::filesystem::is_regular_file(game_dir / "Bink2Scarlett.dll", ec)) - fatal("LEONIDA_GAME_DIR does not contain Bink2Scarlett.dll"); - if (!std::filesystem::is_regular_file(archive, ec)) fatal("LEONIDA_GAME_DIR does not contain movies.rpf"); - - std::vector index = read_index(index_arg); - if (!env("LEONIDA_BINK_LIMIT").empty()) - index.resize(std::min(index.size(), std::strtoul(env("LEONIDA_BINK_LIMIT").c_str(), nullptr, 10))); - if (index.empty()) fatal("LEONIDA_BINK_INDEX lists no stream"); - std::ifstream rpf(archive, std::ios::binary); - if (!rpf) fatal("cannot open movies.rpf"); - - try { - rt::Loader loader(game_dir); - rt::Module& dll = loader.load(game_dir / "Bink2Scarlett.dll"); - for (auto& r : dll.imports) - if (r.binding == rt::Binding::Unimplemented && rt::lower(r.dll).find("xaudio") == std::string::npos) - fatal("Bink2Scarlett.dll import " + r.dll + "!" + r.name + " is unimplemented"); - BinkApi api; - bind(dll, "BinkOpen", api.open); - bind(dll, "BinkWait", api.wait); - bind(dll, "BinkDoFrame", api.do_frame); - bind(dll, "BinkCopyToBuffer", api.copy); - bind(dll, "BinkNextFrame", api.next); - bind(dll, "BinkGoto", api.go_to); - bind(dll, "BinkClose", api.close); - bind(dll, "BinkGetSummary", api.summary); - bind(dll, "BinkGetError", api.get_error); - bind(dll, "BinkSetFileOffset", api.set_file_offset); - bind(dll, "BinkSetFrameRate", api.set_frame_rate); - - // fps_num/fps_den in BINKSUMMARY: the playback rate (0x3c/0x40); the file's rate is at 0x34/0x38. - Field fields[] = {{"width", 0x00, 0x28}, {"height", 0x04, 0x2c}, {"frames", 0x08, 0x48}, - {"fps_num", 0x14, 0x3c}, {"fps_den", 0x18, 0x40}, {"audio_tracks", 0x38, -1}}; - for (Field& f : fields) f.hbink.set(), f.summary.set(); - // The current frame number: 1 after BinkOpen, 2 after BinkNextFrame, N after BinkGoto(N) (1-based). - Mask frame_num; - frame_num.set(); - uint32_t goto_streams = 0; - std::map returns; - size_t hbink_min = kWords * 4, summary_min = kSummaryBytes, summary_max = 0; - uint32_t opened = 0, sentinel_replaced = 0, summary_gaps = 0; // streams with an unwritten byte below extent - - std::vector frame, sum(kSummaryBytes); - for (uint64_t offset : index) { - const Stream s = read_stream(rpf, offset); - api.set_file_offset(s.offset); - void* bink = api.open(archive.string().c_str(), kFileOffset); - if (!bink) { - const char* e = api.get_error ? api.get_error() : nullptr; - std::printf("FAIL BinkOpen at %llu: %s\n", (unsigned long long)s.offset, e && *e ? e : "(no text)"); - ++g_failures; - continue; - } - ++opened; - const Words open_words = snapshot(bink); - hbink_min = std::min(hbink_min, open_words.size() * 4); - - const uint32_t values[] = {s.width, s.height, s.frames, s.fps_num, s.fps_den, s.audio_tracks}; - for (size_t i = 0; i < std::size(fields); ++i) { - fields[i].hbink &= equal_to(open_words, values[i]); - ++fields[i].streams; - } - Mask fn = equal_to(open_words, 1); - - // Two sentinels: a byte the call writes differs from at least one of them (a value can't equal both), so - // a byte that kept the sentinel in both calls was not written. That gives the written bytes exactly, - // not only the highest one; it says nothing about padding the structure may have past them. - size_t extent = 0; - std::vector written(kSummaryBytes, false); - Words sum_words; - for (uint8_t sentinel : {(uint8_t)0xCD, (uint8_t)0x5A}) { - std::fill(sum.begin(), sum.end(), sentinel); - api.summary(bink, sum.data()); - extent = std::max(extent, written_extent(sum, sentinel)); - for (size_t i = 0; i < kSummaryBytes; ++i) written[i] = written[i] || sum[i] != sentinel; - sum_words.assign(kWords, 0); - std::memcpy(sum_words.data(), sum.data(), kWords * 4); - } - summary_min = std::min(summary_min, extent); - summary_max = std::max(summary_max, extent); - if (std::count(written.begin(), written.begin() + extent, false)) ++summary_gaps; - for (size_t i = 0; i < std::size(fields); ++i) fields[i].summary &= equal_to(sum_words, values[i]); - - frame.assign((size_t)s.width * 4 * s.height, 0xCD); - auto decode = [&](const char* step) { - const uint32_t w = api.wait(bink); - const uint32_t d = api.do_frame(bink); - const uint32_t c = api.copy(bink, frame.data(), s.width * 4, s.height, 0, 0, kCopyBgra32); - ++returns[std::string(step) + ": BinkWait=" + std::to_string(w) + " BinkDoFrame=" + - std::to_string(d) + " BinkCopyToBuffer=" + std::to_string(c)]; - }; - decode("frame 1"); - if (std::count(frame.begin(), frame.end(), (uint8_t)0xCD) < (std::ptrdiff_t)frame.size()) - ++sentinel_replaced; - api.next(bink); - fn &= equal_to(snapshot(bink), 2); - decode("frame 2"); - if (s.frames >= 4) { - const uint32_t target = s.frames / 2 + 1; - api.go_to(bink, target, 0); - fn &= equal_to(snapshot(bink), target); - decode("after BinkGoto"); - ++goto_streams; - } - frame_num &= fn; - api.close(bink); - } - - // Every stream of 1.0.2.1 runs at 30/1 fps, so the header alone can't tell the rate fields apart. Reopen - // the first stream with a forced 24000/1001 playback rate: the fields that follow it are the playback rate, - // the ones that keep 30/1 are the file's. - Mask forced_num, forced_den, file_num, file_den, sum_forced_num, sum_forced_den, sum_file_num, sum_file_den; - { - const Stream s = read_stream(rpf, index.front()); - api.set_frame_rate(24000, 1001); - api.set_file_offset(s.offset); - void* bink = api.open(archive.string().c_str(), kFileOffset | kFrameRate); - check(bink != nullptr, "BinkOpen with the frame-rate flag after BinkSetFrameRate(24000, 1001)"); - if (bink) { - const Words w = snapshot(bink); - forced_num = equal_to(w, 24000); - forced_den = equal_to(w, 1001); - file_num = equal_to(w, s.fps_num); - file_den = equal_to(w, s.fps_den); - std::fill(sum.begin(), sum.end(), (uint8_t)0xCD); - api.summary(bink, sum.data()); - Words sw(kWords); - std::memcpy(sw.data(), sum.data(), kWords * 4); - sum_forced_num = equal_to(sw, 24000); - sum_forced_den = equal_to(sw, 1001); - sum_file_num = equal_to(sw, s.fps_num); - sum_file_den = equal_to(sw, s.fps_den); - api.close(bink); - } - } - - std::printf("streams: %zu in the index, %u opened, %u with BinkGoto checked\n", index.size(), opened, - goto_streams); - std::printf("HBINK readable prefix: at least %zu bytes on every stream\n", hbink_min); - std::printf("BINKSUMMARY: highest written byte +1 is %zu..%zu (of a %zu-byte buffer); %u streams leave a " - "byte below it unwritten\n", summary_min, summary_max, kSummaryBytes, summary_gaps); - for (const Field& f : fields) - std::printf(" %-12s HBINK %-24s BINKSUMMARY %s\n", f.name, offsets(f.hbink).c_str(), - offsets(f.summary).c_str()); - std::printf(" %-12s HBINK %s\n", "frame number", offsets(frame_num).c_str()); - std::printf("forced 24000/1001 on the first stream:\n"); - std::printf(" playback num HBINK %-24s BINKSUMMARY %s\n", offsets(forced_num).c_str(), - offsets(sum_forced_num).c_str()); - std::printf(" playback den HBINK %-24s BINKSUMMARY %s\n", offsets(forced_den).c_str(), - offsets(sum_forced_den).c_str()); - std::printf(" file num HBINK %-24s BINKSUMMARY %s\n", offsets(file_num).c_str(), - offsets(sum_file_num).c_str()); - std::printf(" file den HBINK %-24s BINKSUMMARY %s\n", offsets(file_den).c_str(), - offsets(sum_file_den).c_str()); - for (const auto& [what, n] : returns) std::printf("returns %s: %u streams\n", what.c_str(), n); - - check(opened == index.size(), "BinkOpen inside movies.rpf succeeds on every indexed stream"); - check(sentinel_replaced == opened, "BinkCopyToBuffer replaced the sentinel on every stream"); - for (const Field& f : fields) { - char at[64]; - std::snprintf(at, sizeof(at), " is at HBINK +0x%02x", f.hbink_at); - check(has(f.hbink, f.hbink_at), std::string(f.name) + at); - if (f.summary_at >= 0) { - std::snprintf(at, sizeof(at), " is at BINKSUMMARY +0x%02x", f.summary_at); - check(has(f.summary, f.summary_at), std::string(f.name) + at); - } - } - check(has(frame_num, 0x0c), "the 1-based current frame number is at HBINK +0x0c"); - check(summary_min == kSummaryWritten && summary_max == kSummaryWritten && summary_gaps == 0, - "BinkGetSummary writes every byte of +0x00..+0x" + hex(kSummaryWritten - 1) + " and none after"); - check(has(forced_num, 0x14) && has(forced_den, 0x18), "BinkSetFrameRate's rate lands at HBINK +0x14/+0x18"); - check(has(sum_forced_num, 0x3c) && has(sum_forced_den, 0x40) && has(sum_file_num, 0x34) && - has(sum_file_den, 0x38), - "BINKSUMMARY keeps the file's rate at +0x34/+0x38 and the playback rate at +0x3c/+0x40"); - bool zero_returns = true; - for (const auto& [what, n] : returns) - zero_returns = zero_returns && what.find("BinkDoFrame=0 BinkCopyToBuffer=0") != std::string::npos; - check(zero_returns, "BinkDoFrame and BinkCopyToBuffer return 0 on every call"); - std::printf("%s\n", g_failures ? "RESULT FAIL" : "RESULT PASS"); - return g_failures ? 1 : 0; - } catch (const std::exception& e) { - std::fprintf(stderr, "FAIL %s\n", e.what()); - return 1; - } -} diff --git a/runtime/test/bink_abi_test.md b/runtime/test/bink_abi_test.md deleted file mode 100644 index 4906568aa..000000000 --- a/runtime/test/bink_abi_test.md +++ /dev/null @@ -1,44 +0,0 @@ -# Bink2Scarlett ABI over `movies.rpf` - -`bink_abi_test.cpp` is an optional Windows test. It maps the package's `Bink2Scarlett.dll` with `rt::Loader`, as -[`bink_decode_test`](bink_decode_test.md) does, and opens every stream listed in a `tools/bink_index.py` CSV in place -inside `movies.rpf`: `BinkSetFileOffset`, then `BinkOpen` with flag `0x20`. Nothing is extracted. - -For each stream, it: - -- reads the first 256 bytes of the `HBINK`; -- calls `BinkGetSummary` on a sentinel-filled 1,024-byte buffer; -- keeps the 32-bit word offsets whose value equals the stream header's width, height, frame count, frame rate and - audio track count; -- tracks the current frame number across `BinkOpen`, `BinkNextFrame` and `BinkGoto`; -- tallies the return values of `BinkWait`, `BinkDoFrame` and `BinkCopyToBuffer`. - -It then reopens the first stream with a forced `BinkSetFrameRate(24000, 1001)` to tell the playback rate fields apart -from the file's. It checks the measured offsets in [`docs/movies.md`](../../docs/movies.md#abi-over-the-archive). -Output is offsets, counts and return values only: the decoded frames stay in memory and are never written. - -It runs only when both variables are set: - -```sh -python -I tools/bink_index.py C:\path\to\package\movies.rpf --out %TEMP%\movies.csv -set LEONIDA_GAME_DIR=C:\path\to\package -set LEONIDA_BINK_INDEX=%TEMP%\movies.csv -set LEONIDA_BINK_LIMIT=8 # optional: only the first 8 streams -runtime\build\bink_abi_test.exe -``` - -With either required variable unset, it prints `SKIP (no package/index)` and exits 77, so `ctest` stays green on a -machine without the package. - -## Measured on 1.0.2.1 - -All 515 streams opened and `RESULT PASS`. It ran in 46 s on a hard disk: Windows 11, MSVC 19.52, RelWithDebInfo. No -GPU is involved. The field table is in [`docs/movies.md`](../../docs/movies.md#abi-over-the-archive). - -## Gaps - -- Only fields whose value appears in the stream header can be found this way. The rest of the `HBINK` (after - `+0x38`) and of the bytes `BINKSUMMARY` writes (+0x00..+0x8F) is not named. -- The forced frame rate was checked on one stream. -- The async, GPU and audio paths are not exercised; the audio track API is covered by - [`bink_audio_test`](bink_audio_test.md). diff --git a/runtime/test/bink_audio_test.cpp b/runtime/test/bink_audio_test.cpp deleted file mode 100644 index 8616d9165..000000000 --- a/runtime/test/bink_audio_test.cpp +++ /dev/null @@ -1,463 +0,0 @@ -// Optional Windows test: load Bink2Scarlett.dll through rt::Loader and inspect/extract the audio tracks of one -// Bink 2 movie. Skips unless both LEONIDA_GAME_DIR and LEONIDA_MOVIE_AUDIO are set. -// -// LEONIDA_GAME_DIR= (contains Bink2Scarlett.dll) -// LEONIDA_MOVIE_AUDIO= (a carved Bink 2 stream with audio) -// LEONIDA_AUDIO_FRAMES= (optional: stop after n video frames; default all) -// -// Output stays under %TEMP%\leonida_bink_audio. No movie, packet or PCM is committed. -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include "../shims/shims.h" -#include "../src/pe_loader.h" - -namespace { - -int g_failures = 0; -const char* g_step = "start"; - -LONG CALLBACK log_exception(EXCEPTION_POINTERS* info) { - std::printf("VEH exception code=0x%08lx address=%p step=%s\n", info->ExceptionRecord->ExceptionCode, - info->ExceptionRecord->ExceptionAddress, g_step); - return EXCEPTION_CONTINUE_SEARCH; -} - -void check(bool condition, const std::string& what) { - std::printf("%s %s\n", condition ? "PASS" : "FAIL", what.c_str()); - if (!condition) ++g_failures; -} - -[[noreturn]] void fatal(const std::string& what) { - std::fprintf(stderr, "FAIL %s\n", what.c_str()); - std::exit(1); -} - -std::string env(const char* name) { - const char* v = std::getenv(name); - return v ? v : ""; -} - -uint32_t read_u32(const uint8_t* p) { - return (uint32_t)p[0] | ((uint32_t)p[1] << 8) | ((uint32_t)p[2] << 16) | ((uint32_t)p[3] << 24); -} - -uint16_t read_u16(const uint8_t* p) { return (uint16_t)(p[0] | (p[1] << 8)); } - -struct MovieHeader { - uint32_t stored = 0; - uint32_t frames = 0; - uint32_t width = 0; - uint32_t height = 0; - uint32_t fps_num = 0; - uint32_t fps_den = 0; - uint32_t audio_tracks = 0; - std::vector track_ids; - std::vector max_sizes; - std::vector rates; - std::vector flags; -}; - -MovieHeader read_header(const std::filesystem::path& path) { - std::ifstream f(path, std::ios::binary); - if (!f) fatal("cannot open movie " + path.string()); - uint8_t h[512]{}; - f.read(reinterpret_cast(h), sizeof(h)); - size_t got = (size_t)f.gcount(); - if (got < 0x2C) fatal("movie is shorter than the 44-byte Bink 2 header"); - if (h[0] != 'K' || h[1] != 'B' || h[2] != '2' || h[3] < 'a' || h[3] > 'z') - fatal("movie does not start with KB2[a-z]"); - MovieHeader out; - out.stored = read_u32(h + 0x04) + 8; - out.frames = read_u32(h + 0x08); - out.width = read_u32(h + 0x14); - out.height = read_u32(h + 0x18); - out.fps_num = read_u32(h + 0x1C); - out.fps_den = read_u32(h + 0x20); - out.audio_tracks = read_u32(h + 0x28); - std::error_code ec; - auto size = std::filesystem::file_size(path, ec); - if (ec || out.stored > size) fatal("movie header's stored size is past EOF"); - if (!out.frames || !out.width || !out.height || !out.fps_num || !out.fps_den) - fatal("movie header has a zero frame count, size or fps"); - if (out.frames > 1'000'000 || out.width > 7680 || out.height > 4800) - fatal("movie header dimensions or frame count are out of range"); - if (out.audio_tracks > 16) fatal("movie header has an implausible audio track count"); - if (out.audio_tracks) { - // Revisions i/j/k/n put one opaque word at 0x2C before the audio metadata. - size_t p = 0x30; - if (got < p + 12 * out.audio_tracks) fatal("movie header is too short for its audio descriptors"); - for (uint32_t i = 0; i < out.audio_tracks; ++i) - out.max_sizes.push_back(read_u32(h + p + 4 * i)); - for (uint32_t i = 0; i < out.audio_tracks; ++i) { - out.rates.push_back(read_u16(h + p + 4 * out.audio_tracks + 4 * i)); - out.flags.push_back(read_u16(h + p + 4 * out.audio_tracks + 4 * i + 2)); - } - for (uint32_t i = 0; i < out.audio_tracks; ++i) - out.track_ids.push_back(read_u32(h + p + 8 * out.audio_tracks + 4 * i)); - } - return out; -} - -struct BinkTrack { - uint32_t frequency; // +0 measured 48000 - uint32_t channels; // +4 measured 2 - uint32_t max_size; // +8 measured 154624 - uint32_t unknown12; // +12 - void* bink; // +16 - uintptr_t sndcomp; // +24 - int32_t track_index; // +32 -}; -static_assert(sizeof(BinkTrack) == 40, "observed BINKTRACK x64 prefix"); - -struct BinkAudioApi { - using Open = void* (*)(const char*, uint32_t); - using Close = void (*)(void*); - using Wait = uint32_t (*)(void*); - using DoFrame = uint32_t (*)(void*); - using CopyToBuffer = uint32_t (*)(void*, void*, uint32_t, uint32_t, uint32_t, uint32_t, uint32_t); - using NextFrame = void (*)(void*); - using Service = void (*)(void*); - using SetSoundTrack = void (*)(uint32_t, uint32_t*); - using OpenTrack = BinkTrack* (*)(void*, uint32_t); - using CloseTrack = void (*)(BinkTrack*); - using GetTrackType = uint32_t (*)(void*, uint32_t); - using GetTrackMaxSize = uint32_t (*)(void*, uint32_t); - using GetTrackID = uint32_t (*)(void*, uint32_t); - using GetTrackData = uint32_t (*)(BinkTrack*, void*); - - Open open = nullptr; - Close close = nullptr; - Wait wait = nullptr; - DoFrame do_frame = nullptr; - CopyToBuffer copy = nullptr; - NextFrame next = nullptr; - Service service = nullptr; - SetSoundTrack set_sound_track = nullptr; - OpenTrack open_track = nullptr; - CloseTrack close_track = nullptr; - GetTrackType type = nullptr; - GetTrackMaxSize max_size = nullptr; - GetTrackID id = nullptr; - GetTrackData data = nullptr; -}; - -void* symbol(rt::Module& m, const char* name) { - auto it = m.exports.find(name); - if (it == m.exports.end()) fatal(std::string("Bink2Scarlett.dll does not export ") + name); - return it->second; -} - -void* iat_slot(rt::Module& m, const std::string& want_dll, const std::string& want_name) { - auto* dos = reinterpret_cast(m.base); - auto* nt = reinterpret_cast(m.base + dos->e_lfanew); - auto& dir = nt->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT]; - auto* desc = reinterpret_cast(m.base + dir.VirtualAddress); - for (; desc->Name; ++desc) { - const char* dll = reinterpret_cast(m.base + desc->Name); - if (rt::lower(dll) != rt::lower(want_dll)) continue; - auto* lookup = reinterpret_cast( - m.base + (desc->OriginalFirstThunk ? desc->OriginalFirstThunk : desc->FirstThunk)); - auto* iat = reinterpret_cast(m.base + desc->FirstThunk); - for (; lookup->u1.AddressOfData; ++lookup, ++iat) { - if (IMAGE_SNAP_BY_ORDINAL64(lookup->u1.Ordinal)) continue; - auto* name = reinterpret_cast(m.base + (uint32_t)lookup->u1.AddressOfData); - if (want_name == name->Name) return &iat->u1.Function; - } - } - return nullptr; -} - -void write_u16(std::ofstream& f, uint16_t v) { - char b[2] = {(char)(v & 0xFF), (char)(v >> 8)}; - f.write(b, 2); -} -void write_u32(std::ofstream& f, uint32_t v) { - char b[4] = {(char)(v & 0xFF), (char)((v >> 8) & 0xFF), (char)((v >> 16) & 0xFF), (char)(v >> 24)}; - f.write(b, 4); -} - -void write_wav(const std::filesystem::path& path, const std::vector& pcm, uint32_t rate, uint32_t bits, - uint32_t channels) { - const uint32_t block = channels * (bits / 8); - const uint32_t byte_rate = rate * block; - const uint32_t data_size = (uint32_t)pcm.size(); - std::ofstream f(path, std::ios::binary); - if (!f) fatal("cannot write " + path.string()); - f.write("RIFF", 4); - write_u32(f, 36 + data_size); - f.write("WAVEfmt ", 8); - write_u32(f, 16); - write_u16(f, 1); // PCM; Bink's 16-bit path is integer PCM. - write_u16(f, (uint16_t)channels); - write_u32(f, rate); - write_u32(f, byte_rate); - write_u16(f, (uint16_t)block); - write_u16(f, (uint16_t)bits); - f.write("data", 4); - write_u32(f, data_size); - f.write(reinterpret_cast(pcm.data()), (std::streamsize)pcm.size()); -} - -} // namespace - -int main() { - std::setvbuf(stdout, nullptr, _IONBF, 0); - AddVectoredExceptionHandler(1, log_exception); - const std::string game_dir_arg = env("LEONIDA_GAME_DIR"); - const std::string movie_arg = env("LEONIDA_MOVIE_AUDIO"); - if (game_dir_arg.empty() || movie_arg.empty()) { - std::printf("SKIP (no package/audio movie)\n"); - return 77; - } - - const std::filesystem::path game_dir = game_dir_arg; - const std::filesystem::path movie = movie_arg; - std::error_code ec; - if (!std::filesystem::is_directory(game_dir, ec)) fatal("LEONIDA_GAME_DIR is not a directory"); - if (!std::filesystem::is_regular_file(game_dir / "Bink2Scarlett.dll", ec)) - fatal("LEONIDA_GAME_DIR does not contain Bink2Scarlett.dll"); - if (!std::filesystem::is_regular_file(movie, ec)) fatal("LEONIDA_MOVIE_AUDIO is not a file"); - - const MovieHeader header = read_header(movie); - std::printf("movie: %s %ux%u %u frames %u audio tracks\n", movie.string().c_str(), header.width, - header.height, header.frames, header.audio_tracks); - for (uint32_t i = 0; i < header.audio_tracks; ++i) - std::printf(" header track %u: id=%u rate=%u flags=0x%04x\n", i, header.track_ids[i], header.rates[i], - header.flags[i]); - if (!header.audio_tracks) { - std::printf("SKIP (movie has no audio tracks)\n"); - return 77; // nothing was checked: a ctest SKIP (SKIP_RETURN_CODE 77), not a pass - } - - try { - rt::Loader loader(game_dir); - rt::Module& bink = loader.load(game_dir / "Bink2Scarlett.dll"); - std::printf("mapped %s at %p\n", bink.name.c_str(), bink.base); - - int shim = 0, host = 0, module = 0, unimplemented = 0; - bool xmem_alloc = false, xmem_free = false, non_audio_unimplemented = false; - for (auto& r : bink.imports) { - switch (r.binding) { - case rt::Binding::Shim: ++shim; break; - case rt::Binding::Host: ++host; break; - case rt::Binding::Module: ++module; break; - default: ++unimplemented; break; - } - if (rt::lower(r.dll) == "xmem.dll") { - if (r.name == "XMemAlloc") xmem_alloc = true; - if (r.name == "XMemFree") xmem_free = true; - check(r.binding == rt::Binding::Shim, "xmem.dll!" + r.name + " binds to the shim"); - void* expected = rt::shims::find("xmem.dll", r.name); - void* slot = iat_slot(bink, r.dll, r.name); - check(expected && slot && *static_cast(slot) == expected, - "xmem.dll!" + r.name + " IAT points at rt::shims::find"); - } - if (r.binding == rt::Binding::Unimplemented) { - std::printf(" UNIMPLEMENTED %s!%s\n", r.dll.c_str(), r.name.c_str()); - if (rt::lower(r.dll).find("xaudio") == std::string::npos) non_audio_unimplemented = true; - } - } - std::printf("imports: shim=%d host=%d module=%d unimplemented=%d\n", shim, host, module, unimplemented); - check(xmem_alloc && xmem_free, "both XMemAlloc and XMemFree imports are present"); - check(!non_audio_unimplemented, "no non-audio unimplemented imports"); - - BinkAudioApi api; - api.open = reinterpret_cast(symbol(bink, "BinkOpen")); - api.close = reinterpret_cast(symbol(bink, "BinkClose")); - api.wait = reinterpret_cast(symbol(bink, "BinkWait")); - api.do_frame = reinterpret_cast(symbol(bink, "BinkDoFrame")); - api.copy = reinterpret_cast(symbol(bink, "BinkCopyToBuffer")); - api.next = reinterpret_cast(symbol(bink, "BinkNextFrame")); - api.service = reinterpret_cast(symbol(bink, "BinkService")); - api.set_sound_track = reinterpret_cast(symbol(bink, "BinkSetSoundTrack")); - api.open_track = reinterpret_cast(symbol(bink, "BinkOpenTrack")); - api.close_track = reinterpret_cast(symbol(bink, "BinkCloseTrack")); - api.type = reinterpret_cast(symbol(bink, "BinkGetTrackType")); - api.max_size = reinterpret_cast(symbol(bink, "BinkGetTrackMaxSize")); - api.id = reinterpret_cast(symbol(bink, "BinkGetTrackID")); - api.data = reinterpret_cast(symbol(bink, "BinkGetTrackData")); - std::printf("addresses: DoFrame=%p Copy=%p Wait=%p Next=%p GetTrackData=%p OpenTrack=%p\n", - (void*)api.do_frame, (void*)api.copy, (void*)api.wait, (void*)api.next, (void*)api.data, - (void*)api.open_track); - - void* handle = nullptr; - if (env("LEONIDA_RUN_DLLMAIN") == "1") { - auto dll_main = reinterpret_cast(bink.base + bink.entry_rva); - check(dll_main(reinterpret_cast(bink.base), DLL_PROCESS_ATTACH, nullptr) != FALSE, - "DllMain(DLL_PROCESS_ATTACH) returned TRUE"); - } - uint32_t selected = 0; - if (!env("LEONIDA_AUDIO_TRACK").empty()) { - char* end = nullptr; - unsigned long n = std::strtoul(env("LEONIDA_AUDIO_TRACK").c_str(), &end, 10); - if (!end || *end || n >= header.audio_tracks) fatal("LEONIDA_AUDIO_TRACK is not a track index"); - selected = (uint32_t)n; - } - if (!header.track_ids.empty()) { - auto ids = header.track_ids; - api.set_sound_track(1, &ids[selected]); - std::printf("BinkSetSoundTrack(1, [%u])\n", ids[selected]); - } - handle = api.open(movie.string().c_str(), 0); - if (!handle) fatal("BinkOpen returned null"); - std::printf("PASS BinkOpen returned %p\n", handle); - - struct Track { - uint32_t index; - uint32_t id; - uint32_t type; - BinkTrack* handle; - std::vector pcm; - uint32_t calls; - uint32_t bytes; - }; - std::vector tracks; - for (uint32_t i = 0; i < header.audio_tracks; ++i) { - Track t{}; - t.index = i; - t.id = api.id(handle, i); - t.type = api.type(handle, i); - const uint32_t max_size = api.max_size(handle, i); - const uint32_t expected_type = ((uint32_t)header.flags[i] << 16) | header.rates[i]; - check(t.id == header.track_ids[i], "BinkGetTrackID matches the header track ID"); - check(t.type == expected_type, "BinkGetTrackType is (flags << 16) | sample rate"); - check(max_size >= header.max_sizes[i], "BinkGetTrackMaxSize covers the header max size"); - std::printf("track index %u: id=%u type=0x%08x max_size=%u (header %u)", i, t.id, t.type, max_size, - header.max_sizes[i]); - if (i != selected) { - std::printf(" (not opened; LEONIDA_AUDIO_TRACK=%u)\n", selected); - continue; - } - t.handle = api.open_track(handle, i); - std::printf(" open=%p", (void*)t.handle); - if (t.handle) { - check(t.handle->frequency == header.rates[i], "BINKTRACK.Frequency matches the header rate"); - check(t.handle->channels == ((header.flags[i] & 0x2000) ? 2u : 1u), - "BINKTRACK.Channels matches the header stereo flag"); - check(t.handle->track_index == (int32_t)i, "BINKTRACK.trackindex matches the requested index"); - std::printf(" BINKTRACK={freq=%u channels=%u max=%u trackindex=%d}", t.handle->frequency, - t.handle->channels, t.handle->max_size, t.handle->track_index); - const uint8_t* raw = reinterpret_cast(t.handle); - std::printf("\n track bytes:"); - for (int k = 0; k < 64; ++k) std::printf(" %02x", raw[k]); - } - std::printf("\n"); - check(t.handle != nullptr, "BinkOpenTrack returned a track"); - if (t.handle) tracks.push_back(std::move(t)); - } - - if (tracks.empty()) { - api.close(handle); - return 1; - } - - uint32_t limit = header.frames; - if (!env("LEONIDA_AUDIO_FRAMES").empty()) { - char* end = nullptr; - unsigned long n = std::strtoul(env("LEONIDA_AUDIO_FRAMES").c_str(), &end, 10); - if (!end || *end || !n) fatal("LEONIDA_AUDIO_FRAMES is not a positive frame count"); - limit = (uint32_t)std::min(n, header.frames); - } - - std::vector packet(16 << 20); - std::vector video((size_t)header.width * header.height * 4); - uint32_t frame_sizes_printed = 0; - const bool trace = env("LEONIDA_AUDIO_TRACE") == "1"; - const bool skip_sleep = env("LEONIDA_AUDIO_NO_SLEEP") == "1"; - for (uint32_t frame = 0; frame < limit; ++frame) { - if (trace) std::printf("trace: frame %u before BinkDoFrame\n", frame); - g_step = "BinkDoFrame"; - const uint32_t do_rc = api.do_frame(handle); - uint32_t wait = 0; - g_step = "BinkWait(after BinkDoFrame)"; - for (int spin = 0; spin < 1000 && (wait = api.wait(handle)) != 0; ++spin) Sleep(1); - g_step = "BinkCopyToBuffer"; - const uint32_t copy_rc = api.copy(handle, video.data(), header.width * 4, header.height, 0, 0, 3); - uint32_t wait2 = 0; - g_step = "BinkWait(after BinkCopyToBuffer)"; - for (int spin = 0; spin < 1000 && (wait2 = api.wait(handle)) != 0; ++spin) Sleep(1); - g_step = "BinkService"; - api.service(handle); - // The package DLL's audio decode is asynchronous. Without this delay BinkGetTrackData intermittently - // faults inside Bink2Scarlett.dll; BinkWait and BinkService both return before the audio path is ready. - // 1 ms is the smallest delay that made every tested stream stable. This is a property of the DLL, not - // the loader or the xmem shim. - if (!skip_sleep) Sleep(1); - if (trace) - std::printf("trace: frame %u after BinkDoFrame=%u wait=%u Copy=%u wait2=%u\n", frame, do_rc, wait, - copy_rc, wait2); - for (auto& t : tracks) { - g_step = "BinkGetTrackData"; - const uint32_t n = api.data(t.handle, packet.data()); - if (trace) std::printf("trace: frame %u track %u after BinkGetTrackData=%u\n", frame, t.index, n); - if (n > packet.size()) fatal("BinkGetTrackData returned a size larger than the packet buffer"); - ++t.calls; - t.bytes += n; - if (n) t.pcm.insert(t.pcm.end(), packet.begin(), packet.begin() + n); - if (frame < 3 || (n && frame_sizes_printed < 12)) { - std::printf("frame %u track %u: BinkDoFrame=%u BinkGetTrackData=%u", frame, t.index, do_rc, n); - if (n) { - std::printf(" head="); - for (uint32_t k = 0; k < 16 && k < n; ++k) std::printf("%02x", packet[k]); - } - std::printf("\n"); - ++frame_sizes_printed; - } - } - if ((frame % 50) == 0) std::printf("progress: frame %u/%u\n", frame, limit); - if (frame + 1 < limit) { - g_step = "BinkNextFrame"; - api.next(handle); - if (trace) std::printf("trace: frame %u after BinkNextFrame\n", frame); - } - } - - const std::filesystem::path out_dir = std::filesystem::temp_directory_path() / "leonida_bink_audio"; - std::filesystem::create_directories(out_dir, ec); - const std::string stem = movie.stem().string(); - for (auto& t : tracks) { - std::printf("track %u: calls=%u bytes=%u", t.index, t.calls, t.bytes); - if (t.handle) { - std::printf(" freq=%u channels=%u max=%u", t.handle->frequency, t.handle->channels, - t.handle->max_size); - } - std::printf("\n"); - if (!t.pcm.empty()) { - const std::string base = stem + "_track" + std::to_string(t.index); - const auto raw = out_dir / (base + ".pcm"); - { - std::ofstream f(raw, std::ios::binary); - f.write(reinterpret_cast(t.pcm.data()), (std::streamsize)t.pcm.size()); - } - const uint32_t rate = header.rates[t.index]; - const uint32_t channels = (header.flags[t.index] & 0x2000) ? 2 : 1; - const uint32_t bits = 16; // measured: BinkGetTrackData returns 16-bit PCM for both flag variants - const double seconds = t.pcm.size() / (double)(rate * channels * (bits / 8)); - check(t.pcm.size() % (channels * (bits / 8)) == 0, "PCM byte count is a whole number of samples"); - const auto wav = out_dir / (base + ".wav"); - write_wav(wav, t.pcm, rate, bits, channels); - std::printf(" wrote %s and %s %u Hz, %u ch, %u-bit, %.3f s\n", raw.string().c_str(), - wav.string().c_str(), rate, channels, bits, seconds); - } - if (t.handle) api.close_track(t.handle); - } - - api.close(handle); - std::printf("%s\n", g_failures ? "RESULT FAIL" : "RESULT PASS"); - return g_failures ? 1 : 0; - } catch (const std::exception& e) { - std::fprintf(stderr, "FAIL %s\n", e.what()); - return 1; - } -} diff --git a/runtime/test/bink_audio_test.md b/runtime/test/bink_audio_test.md deleted file mode 100644 index 9c9a7df22..000000000 --- a/runtime/test/bink_audio_test.md +++ /dev/null @@ -1,70 +0,0 @@ -# Bink Audio track extraction through `rt::Loader` - -`bink_audio_test.cpp` is an optional Windows diagnostic. It maps `Bink2Scarlett.dll` with `rt::Loader`, checks that -`xmem.dll!XMemAlloc`/`XMemFree` bind to `runtime/shims/xmem.cpp`, enumerates the movie's audio tracks, and decodes -one selected track to 16-bit PCM/WAV. - -```sh -set LEONIDA_GAME_DIR=C:\path\to\package -set LEONIDA_MOVIE_AUDIO=C:\path\to\stream.bk2 -set LEONIDA_AUDIO_TRACK=0 # optional, default 0 -set LEONIDA_AUDIO_FRAMES=100 # optional, default all frames -set LEONIDA_RUN_DLLMAIN=1 # optional, not needed -runtime\build\bink_audio_test.exe -``` - -With either required variable unset it prints `SKIP (no package/audio movie)` and exits 0. Output goes to -`%TEMP%\leonida_bink_audio`; no movie, packet or PCM is committed. - -## Measured API shape (1.0.2.1) - -- Loader binding is the same as the video path: **2 shim** (`xmem.dll!XMemAlloc`, `XMemFree`), **58 host**, - **0 unimplemented**; both xmem IAT slots equal `rt::shims::find`. -- `BinkGetTrackID(h, index)` returns the header track ID (0, 1, 2, 3 in the four-track sample). -- `BinkGetTrackType(h, index)` returns `(audio_flags << 16) | sample_rate`: `0x7000bb80` for `0x7000`/48 kHz and - `0x3000bb80` for `0x3000`/48 kHz. -- `BinkGetTrackMaxSize(h, index)` returns 146,432 for these tracks; the header's max-size field is 145,920 (512 - bytes smaller). -- `BinkOpenTrack(h, index)` returns a handle whose observed prefix is `Frequency=48000`, `Channels=2`, - `MaxSize=154624`, then `HBINK`, an internal pointer, and `trackindex`. This is not the public Bink 1 - `Frequency, Bits, Channels, MaxSize` order. -- **`BinkGetTrackData(track, dest)` returns decompressed 16-bit PCM bytes, not compressed Bink Audio packets.** - A full 15 s stereo 48 kHz track is exactly 2,880,000 bytes. The first call can return a pre-roll (145,920 bytes - on the 4K stream, 19 x 7,680); later inspected calls returned 7,680 or 0. The return is a byte count, not a fixed - packet size. `BinkSetSoundSystem` and `BinkOpenXAudio2` are never called; `BinkSetSoundTrack` is used only to - select the one track being extracted. -- A `BinkCopyToBuffer` call per frame followed by `Sleep(1)` is required by this build. Without the delay, - `BinkGetTrackData` intermittently faults inside `Bink2Scarlett.dll` at `+0x1EE1B`; `BinkWait` and `BinkService` - return before the audio path is ready. This is a DLL race, not a loader/xmem failure. - -## Measured tracks - -| Stream | Track | Frames | PCM bytes | Duration | -|---|---|---:|---:|---:| -| 3840x2160, 1 track | 0 | 450 | 2,880,000 | 15.000 s | -| 1920x1080, 2 tracks (`0x7000` each) | 0 | 151 | 966,400 | 5.033 s | -| 1920x1080, 2 tracks (`0x7000` each) | 1 | 151 | 966,400 | 5.033 s | -| 1920x1080, 4 tracks | 0 | 900 | 5,760,000 | 30.000 s | -| 1920x1080, 1 track `0x3000` | 0 | 4350 | 27,840,000 | 145.000 s | -| 1920x1080, 2 tracks (`0x3000` + `0x7000`) | 1 | 450 | 2,880,000 | 15.000 s | -| 1280x720, 1 track `0x7000` (`binkaudio_dct`, 48 kHz stereo) | 0 | 181 | 1,158,400 | 6.033 s | - -All decoded WAVs are 48 kHz, stereo, `pcm_s16le`. The sampled `0x3000`-only track is entirely silent (peak 0); the -`0x7000` track in the mixed two-track file has normal signal. This does not establish what each track is used for. - -The 1280x720 row is an independent run on a second machine (Windows 11, Ryzen 7 7800X3D, own 1.0.2.1 package): -every one of the 181 calls returned 6,400 bytes (no 7,680 or 0 calls, so no pre-roll on this stream), and the -total matches the API shape above (a byte count per call). - -## FFmpeg - -FFmpeg has the `binkaudio_dct` and `binkaudio_rdft` decoders, but its Bink demuxer misparses the `KB2n` audio header: -it reports 14,848 Hz mono RDFT and rejects the first packet. Changing the revision byte to `k` makes the demuxer skip -the extra header word, but the decoder then rejects the packets as "Incomplete packet". FFmpeg is not a usable path -for this package's Bink 2.2 audio; the DLL's track API returns PCM directly. - -## Gaps - -The harness does not extract compressed packets; the DLL returns PCM directly. One raw packet was probed manually for -the FFmpeg check, but its exact layout is not mapped. No sound system/XAudio2 output is opened, and the -async/GPU/subtitle paths are untested. Which track corresponds to which language or mix is not known. diff --git a/runtime/test/bink_decode_test.cpp b/runtime/test/bink_decode_test.cpp deleted file mode 100644 index 3bd20ac50..000000000 --- a/runtime/test/bink_decode_test.cpp +++ /dev/null @@ -1,296 +0,0 @@ -// Optional Windows test: map the package's Bink2Scarlett.dll through rt::Loader, verify that its xmem imports bind -// to the runtime's shim table, and decode a .bk2 through the loader's export map. -// -// LEONIDA_GAME_DIR= (contains Bink2Scarlett.dll) -// LEONIDA_MOVIE= (a carved Bink 2 stream) -// LEONIDA_GOTO= (optional: also BinkGoto that frame) -// LEONIDA_RUN_DLLMAIN=1 (optional: call the image entry point as DllMain before BinkOpen) -// -// With either required variable unset the test prints "SKIP (no package/movie)" and exits 77 (CTest skip). -// Output frames are written under %TEMP%\leonida_bink and are never committed. -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include "../shims/shims.h" -#include "../src/pe_loader.h" - -namespace { - -int g_failures = 0; - -void check(bool condition, const std::string& what) { - std::printf("%s %s\n", condition ? "PASS" : "FAIL", what.c_str()); - if (!condition) ++g_failures; -} - -[[noreturn]] void fatal(const std::string& what) { - std::fprintf(stderr, "FAIL %s\n", what.c_str()); - std::exit(1); -} - -std::string env(const char* name) { - const char* v = std::getenv(name); - return v ? v : ""; -} - -uint32_t read_u32(const uint8_t* p) { - return (uint32_t)p[0] | ((uint32_t)p[1] << 8) | ((uint32_t)p[2] << 16) | ((uint32_t)p[3] << 24); -} - -struct MovieHeader { - uint32_t stored = 0; - uint32_t frames = 0; - uint32_t width = 0; - uint32_t height = 0; - uint32_t fps_num = 0; - uint32_t fps_den = 0; -}; - -MovieHeader read_movie_header(const std::filesystem::path& path) { - std::ifstream f(path, std::ios::binary); - if (!f) fatal("cannot open movie " + path.string()); - uint8_t h[0x2C]{}; - f.read(reinterpret_cast(h), sizeof(h)); - if (f.gcount() != (std::streamsize)sizeof(h)) fatal("movie is shorter than the 44-byte Bink 2 header"); - if (h[0] != 'K' || h[1] != 'B' || h[2] != '2' || h[3] < 'a' || h[3] > 'z') - fatal("movie does not start with KB2[a-z]"); - MovieHeader out; - out.stored = read_u32(h + 0x04) + 8; - out.frames = read_u32(h + 0x08); - out.width = read_u32(h + 0x14); - out.height = read_u32(h + 0x18); - out.fps_num = read_u32(h + 0x1C); - out.fps_den = read_u32(h + 0x20); - std::error_code ec; - auto size = std::filesystem::file_size(path, ec); - if (ec || out.stored > size) fatal("movie header's stored size is past EOF"); - if (!out.frames || !out.width || !out.height || !out.fps_num || !out.fps_den) - fatal("movie header has a zero frame count, size or fps"); - return out; -} - -// Address of the IAT slot for dll!name, so the test can compare it with the shim table, not just trust a label. -void* iat_slot(rt::Module& m, const std::string& want_dll, const std::string& want_name) { - auto* dos = reinterpret_cast(m.base); - auto* nt = reinterpret_cast(m.base + dos->e_lfanew); - auto& dir = nt->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT]; - auto* desc = reinterpret_cast(m.base + dir.VirtualAddress); - for (; desc->Name; ++desc) { - const char* dll = reinterpret_cast(m.base + desc->Name); - if (rt::lower(dll) != rt::lower(want_dll)) continue; - auto* lookup = reinterpret_cast( - m.base + (desc->OriginalFirstThunk ? desc->OriginalFirstThunk : desc->FirstThunk)); - auto* iat = reinterpret_cast(m.base + desc->FirstThunk); - for (; lookup->u1.AddressOfData; ++lookup, ++iat) { - if (IMAGE_SNAP_BY_ORDINAL64(lookup->u1.Ordinal)) continue; - auto* name = reinterpret_cast(m.base + (uint32_t)lookup->u1.AddressOfData); - if (want_name == name->Name) return &iat->u1.Function; - } - } - return nullptr; -} - -uint64_t fnv1a(const std::vector& bytes) { - uint64_t h = 1469598103934665603ull; - for (uint8_t b : bytes) { - h ^= b; - h *= 1099511628211ull; - } - return h; -} - -size_t distinct_bytes(const std::vector& bytes) { - bool seen[256]{}; - size_t n = 0; - for (uint8_t b : bytes) - if (!seen[b]) { - seen[b] = true; - ++n; - } - return n; -} - -void write_raw(const std::filesystem::path& path, const std::vector& bytes) { - std::ofstream f(path, std::ios::binary); - if (!f) fatal("cannot write " + path.string()); - f.write(reinterpret_cast(bytes.data()), (std::streamsize)bytes.size()); -} - -void write_ppm(const std::filesystem::path& path, const std::vector& bgra, uint32_t w, uint32_t h) { - std::ofstream f(path, std::ios::binary); - if (!f) fatal("cannot write " + path.string()); - f << "P6\n" << w << ' ' << h << "\n255\n"; - for (size_t i = 0; i + 3 < bgra.size(); i += 4) { - const char rgb[3] = {(char)bgra[i + 2], (char)bgra[i + 1], (char)bgra[i]}; - f.write(rgb, 3); - } -} - -struct BinkApi { - using Open = void* (*)(const char*, uint32_t); - using Wait = uint32_t (*)(void*); - using DoFrame = uint32_t (*)(void*); - using CopyToBuffer = uint32_t (*)(void*, void*, uint32_t, uint32_t, uint32_t, uint32_t, uint32_t); - using NextFrame = void (*)(void*); - using Goto = void (*)(void*, uint32_t, uint32_t); - using Close = void (*)(void*); - using GetError = const char* (*)(); - - Open open = nullptr; - Wait wait = nullptr; - DoFrame do_frame = nullptr; - CopyToBuffer copy = nullptr; - NextFrame next = nullptr; - Goto go_to = nullptr; - Close close = nullptr; - GetError get_error = nullptr; -}; - -void* symbol(rt::Module& m, const char* name) { - auto it = m.exports.find(name); - if (it == m.exports.end()) fatal(std::string("Bink2Scarlett.dll does not export ") + name); - return it->second; -} - -} // namespace - -int main() { - const std::string game_dir_arg = env("LEONIDA_GAME_DIR"); - const std::string movie_arg = env("LEONIDA_MOVIE"); - if (game_dir_arg.empty() || movie_arg.empty()) { - std::printf("SKIP (no package/movie)\n"); - return 77; - } - - const std::filesystem::path game_dir = game_dir_arg; - const std::filesystem::path movie = movie_arg; - std::error_code ec; - if (!std::filesystem::is_directory(game_dir, ec)) fatal("LEONIDA_GAME_DIR is not a directory"); - if (!std::filesystem::is_regular_file(game_dir / "Bink2Scarlett.dll", ec)) - fatal("LEONIDA_GAME_DIR does not contain Bink2Scarlett.dll"); - if (!std::filesystem::is_regular_file(movie, ec)) fatal("LEONIDA_MOVIE is not a file"); - - const MovieHeader header = read_movie_header(movie); - std::printf("movie: %s %ux%u %u frames %u/%u fps %u bytes\n", movie.string().c_str(), header.width, - header.height, header.frames, header.fps_num, header.fps_den, header.stored); - - try { - rt::Loader loader(game_dir); - rt::Module& bink = loader.load(game_dir / "Bink2Scarlett.dll"); - std::printf("mapped %s at %p, size %u, entry +%#x%s\n", bink.name.c_str(), bink.base, bink.size, - bink.entry_rva, bink.relocated ? " (relocated)" : ""); - - int shim = 0, host = 0, module = 0, unimplemented = 0; - bool xmem_alloc = false, xmem_free = false, non_audio_unimplemented = false; - for (auto& r : bink.imports) { - switch (r.binding) { - case rt::Binding::Shim: ++shim; break; - case rt::Binding::Host: ++host; break; - case rt::Binding::Module: ++module; break; - default: ++unimplemented; break; - } - if (rt::lower(r.dll) == "xmem.dll") { - if (r.name == "XMemAlloc") xmem_alloc = true; - if (r.name == "XMemFree") xmem_free = true; - check(r.binding == rt::Binding::Shim, "xmem.dll!" + r.name + " binds to the shim"); - void* expected = rt::shims::find("xmem.dll", r.name); - void* slot = iat_slot(bink, r.dll, r.name); - check(expected && slot && *static_cast(slot) == expected, - "xmem.dll!" + r.name + " IAT points at rt::shims::find"); - } - if (r.binding == rt::Binding::Unimplemented) { - std::printf(" UNIMPLEMENTED %s!%s\n", r.dll.c_str(), r.name.c_str()); - // Audio is not exercised by this test; everything else must resolve. - if (rt::lower(r.dll).find("xaudio") == std::string::npos) non_audio_unimplemented = true; - } - } - std::printf("imports: shim=%d host=%d module=%d unimplemented=%d\n", shim, host, module, unimplemented); - check(xmem_alloc && xmem_free, "both XMemAlloc and XMemFree imports are present"); - check(!non_audio_unimplemented, "no non-audio unimplemented imports"); - - BinkApi api; - api.open = reinterpret_cast(symbol(bink, "BinkOpen")); - api.wait = reinterpret_cast(symbol(bink, "BinkWait")); - api.do_frame = reinterpret_cast(symbol(bink, "BinkDoFrame")); - api.copy = reinterpret_cast(symbol(bink, "BinkCopyToBuffer")); - api.next = reinterpret_cast(symbol(bink, "BinkNextFrame")); - api.go_to = reinterpret_cast(symbol(bink, "BinkGoto")); - api.close = reinterpret_cast(symbol(bink, "BinkClose")); - api.get_error = reinterpret_cast(symbol(bink, "BinkGetError")); - - if (env("LEONIDA_RUN_DLLMAIN") == "1") { - check(bink.entry_rva != 0, "image has an entry point to call as DllMain"); - auto dll_main = reinterpret_cast(bink.base + bink.entry_rva); - check(dll_main(reinterpret_cast(bink.base), DLL_PROCESS_ATTACH, nullptr) != FALSE, - "DllMain(DLL_PROCESS_ATTACH) returned TRUE"); - } - - void* handle = api.open(movie.string().c_str(), 0); - if (!handle) { - const char* error = api.get_error ? api.get_error() : ""; - std::printf("FAIL BinkOpen returned null: %s\n", error && *error ? error : "(no BinkGetError text)"); - return 1; - } - std::printf("PASS BinkOpen returned %p\n", handle); - - const uint32_t pitch = header.width * 4; - std::vector frame((size_t)pitch * header.height); - const std::filesystem::path out_dir = std::filesystem::temp_directory_path() / "leonida_bink"; - std::filesystem::create_directories(out_dir, ec); - const std::string stem = movie.stem().string(); - - auto decode = [&](uint32_t index, const char* label) { - const uint32_t wait = api.wait(handle); - const uint32_t do_rc = api.do_frame(handle); - // This GDK build returns 0 from BinkDoFrame/BinkCopyToBuffer even when it writes a valid frame; the - // sentinel replacement and the hash below are the proof, not the return values. - std::fill(frame.begin(), frame.end(), (uint8_t)0xCD); - const uint32_t copy_rc = api.copy(handle, frame.data(), pitch, header.height, 0, 0, 3); - const size_t untouched = (size_t)std::count(frame.begin(), frame.end(), 0xCD); - const size_t unique = distinct_bytes(frame); - const uint64_t hash = fnv1a(frame); - std::printf("%s frame %u: wait=%u BinkDoFrame=%u BinkCopyToBuffer=%u untouched=%zu unique=%zu " - "hash=%016llx\n", - label, index, wait, do_rc, copy_rc, untouched, unique, (unsigned long long)hash); - check(untouched < frame.size(), std::string(label) + " BinkCopyToBuffer replaced the sentinel buffer"); - check(unique > 1, std::string(label) + " wrote more than one byte value"); - const std::filesystem::path raw = out_dir / (stem + "_f" + std::to_string(index) + ".bgra"); - const std::filesystem::path ppm = out_dir / (stem + "_f" + std::to_string(index) + ".ppm"); - write_raw(raw, frame); - write_ppm(ppm, frame, header.width, header.height); - std::printf(" wrote %s and %s\n", raw.string().c_str(), ppm.string().c_str()); - return hash; - }; - - const uint64_t hash0 = decode(0, "first"); - api.next(handle); - const uint64_t hash1 = decode(1, "next"); - std::printf("frame 0 vs frame 1: %s\n", hash0 == hash1 ? "identical" : "different"); - - if (!env("LEONIDA_GOTO").empty()) { - char* end = nullptr; - unsigned long target = std::strtoul(env("LEONIDA_GOTO").c_str(), &end, 10); - if (!end || *end || target >= header.frames) fatal("LEONIDA_GOTO is not a frame in this movie"); - api.go_to(handle, (uint32_t)target, 0); - const uint64_t hash_goto = decode((uint32_t)target, "goto"); - std::printf("frame 0 vs goto %lu: %s\n", target, hash0 == hash_goto ? "identical" : "different"); - } - - api.close(handle); - std::printf("%s\n", g_failures ? "RESULT FAIL" : "RESULT PASS"); - return g_failures ? 1 : 0; - } catch (const std::exception& e) { - std::fprintf(stderr, "FAIL %s\n", e.what()); - return 1; - } -} diff --git a/runtime/test/bink_decode_test.md b/runtime/test/bink_decode_test.md deleted file mode 100644 index 4e692e1ca..000000000 --- a/runtime/test/bink_decode_test.md +++ /dev/null @@ -1,47 +0,0 @@ -# Bink 2 decode through `rt::Loader` - -`bink_decode_test.cpp` is an optional Windows test that maps the package's `Bink2Scarlett.dll` with `rt::Loader`, -checks that `xmem.dll!XMemAlloc`/`XMemFree` bind to `runtime/shims/xmem.cpp` (the IAT slot is compared with -`rt::shims::find`), and decodes a `.bk2` through the loader's export map. - -It runs only when both variables are set: - -```sh -set LEONIDA_GAME_DIR=C:\path\to\package -set LEONIDA_MOVIE=C:\path\to\stream.bk2 -set LEONIDA_GOTO=200 # optional -set LEONIDA_RUN_DLLMAIN=1 # optional; not needed for the measured streams -runtime\build\bink_decode_test.exe -``` - -With either required variable unset it prints `SKIP (no package/movie)` and exits 0, so `ctest` is green on a machine -without the package. Frames are written as raw BGRA and PPM under `%TEMP%\leonida_bink`; they are never committed. - -## Measured on 1.0.2.1 - -- `rt::Loader` maps `Bink2Scarlett.dll` at `0x180000000` with 2 shim imports (`xmem.dll!XMemAlloc`, - `xmem.dll!XMemFree`), 58 host imports, no bundled-module imports and **0 unimplemented imports**. Both xmem IAT - slots equal `rt::shims::find("xmem.dll", ...)`; `Bink2Scarlett.dll` is mapped by `rt::Loader`, not loaded with - `LoadLibrary`, and no msvcrt redirection is involved. -- `BinkOpen`, `BinkDoFrame`, `BinkCopyToBuffer`, `BinkNextFrame`, `BinkGoto` and `BinkClose` resolve from - `Module::exports`. The decoded BGRA frames are bit-identical to the earlier msvcrt-redirection experiment for the - 1280x720 frame 0 and 3840x2160 frame 200. -- The loader does **not** run `DllMain`/TLS, and decode still works. The image has no TLS directory. Calling the - entry point as `DllMain(DLL_PROCESS_ATTACH)` returns TRUE and also decodes; it is not required for these streams. -- 1280x720 (40 frames): frame 0 and frame 1 differ. -- 1920x1080 (150 frames): frame 0 and frame 1 are identical in the sampled stream; both replace the sentinel buffer. -- 3840x2160 (450 frames): frame 0 and frame 1 differ; `BinkGoto(200, 0)` differs from frame 0 and matches the - earlier 4K frame-200 decode. -- No `BinkSetSoundSystem` or XAudio2 call is made. A 3840x2160 stream with one audio track and a 1920x1080 - stream with four audio tracks both open and decode video without the sound system. -- Independent run on a second machine (Windows 11, Ryzen 7 7800X3D, own 1.0.2.1 package): a `KB2j`-revision - 512x512 15-frame stream decodes the same way (2 shim imports, 58 host, 0 unimplemented; frames 0 and 1 differ), so `KB2j` also decodes through the loader, on a second 1.0.2.1 copy (the `KB2n` - numbers above are from the first). The 10 `KB2j` streams are the nine 512x512 15-frame files plus one - 1920x1080 60-frame file ([docs/movies.md](../../docs/movies.md) section 1). - -## Gaps - -Audio tracks are only read as header metadata; no Bink Audio packet is decoded and no audio system is opened. The -async and GPU decode paths and subtitles are not tested; the `HBINK`/`BINKSUMMARY` fields are measured by -[`bink_abi_test`](bink_abi_test.md). `DllMain`/TLS -are not run by the loader by default; they were not needed for this video path. diff --git a/runtime/test/bink_play.cpp b/runtime/test/bink_play.cpp deleted file mode 100644 index 1682efe6a..000000000 --- a/runtime/test/bink_play.cpp +++ /dev/null @@ -1,494 +0,0 @@ -// bink_play: play a Bink 2 stream in a window through the package's own Bink2Scarlett.dll, mapped by rt::Loader (the -// same path bink_decode_test checks). A local viewing tool for movies carved from your own copy; nothing it reads or -// shows is written anywhere. -// -// bink_play [NAME | movie.bk2 | archive.rpf@OFFSET] [--game-dir DIR] [--frames N] [--headless] [--loop] -// -// NAME is a movie's path in the game (Stinger/RSG_STINGER.bk2) or any unique part of it (stinger), looked up in the -// name table tools/bink_play.py keeps (%LOCALAPPDATA%\Leonida\bink_names.csv); if there is none yet, bink_play runs -// that tool once to build it. With no movie at all a windowed run plays the Rockstar stinger, so double-clicking -// the executable plays it. The game folder comes from --game-dir, LEONIDA_GAME_DIR, or the archive the name table -// was built from. -// -// A movie inside an archive plays where it is: `movies.rpf@OFFSET` hands BinkOpen the archive with -// BinkSetFileOffset, so nothing is extracted (tools/bink_play.py finds the offset from the movie's name). A relative -// archive path is taken from the game folder. -// -// --game-dir defaults to LEONIDA_GAME_DIR, the movie to LEONIDA_MOVIE. Without a package or a movie it prints -// "SKIP (no package/movie)" and exits 77 (CTest skip). --headless decodes without a window (as fast as it can) and -// prints the decode rate, so CTest can run it; --frames stops after N frames. Each headless decode starts from a -// frame filled with 0xA5 and fails if it leaves the frame untouched, so a pass means every frame wrote the buffer. -// -// Keys: Space pause/resume, Left/Right one second back/forward, Home restart, L loop on/off, Esc or closing the -// window quits. The frame is scaled to the window, keeping its aspect ratio. -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include "../shims/shims.h" -#include "../src/pe_loader.h" - -namespace { - -// A windowed run is often started by double-click, where a console line vanishes with its window: say it in a box. -bool g_windowed = false; - -[[noreturn]] void fatal(const std::string& what) { - std::fprintf(stderr, "FAIL %s\n", what.c_str()); - if (g_windowed) MessageBoxA(nullptr, what.c_str(), "bink_play", MB_OK | MB_ICONERROR); - std::exit(1); -} - -std::string env(const char* name) { - const char* v = std::getenv(name); - return v ? v : ""; -} - -uint32_t read_u32(const uint8_t* p) { - return (uint32_t)p[0] | ((uint32_t)p[1] << 8) | ((uint32_t)p[2] << 16) | ((uint32_t)p[3] << 24); -} - -struct MovieHeader { - uint32_t frames = 0, width = 0, height = 0, fps_num = 0, fps_den = 0; -}; - -// The fixed Bink 2 header (docs/movies.md): frame count at 0x08, size at 0x14/0x18, frame rate at 0x1C/0x20. -MovieHeader read_movie_header(const std::filesystem::path& path, uint64_t offset) { - std::ifstream f(path, std::ios::binary); - if (!f) fatal("cannot open movie " + path.string()); - f.seekg((std::streamoff)offset); - uint8_t h[0x2C]{}; - f.read(reinterpret_cast(h), sizeof(h)); - if (f.gcount() != (std::streamsize)sizeof(h)) fatal("movie is shorter than the 44-byte Bink 2 header"); - if (h[0] != 'K' || h[1] != 'B' || h[2] != '2' || h[3] < 'a' || h[3] > 'z') - fatal("movie does not start with KB2[a-z]"); - MovieHeader out; - out.frames = read_u32(h + 0x08); - out.width = read_u32(h + 0x14); - out.height = read_u32(h + 0x18); - out.fps_num = read_u32(h + 0x1C); - out.fps_den = read_u32(h + 0x20); - if (!out.frames || !out.width || !out.height || !out.fps_num || !out.fps_den) - fatal("movie header has a zero frame count, size or fps"); - if (out.width > 16384 || out.height > 16384) fatal("movie header has an implausible frame size"); - return out; -} - -struct BinkApi { - void* (*open)(const char*, uint32_t) = nullptr; - uint32_t (*do_frame)(void*) = nullptr; - uint32_t (*copy)(void*, void*, uint32_t, uint32_t, uint32_t, uint32_t, uint32_t) = nullptr; - void (*next)(void*) = nullptr; - void (*go_to)(void*, uint32_t, uint32_t) = nullptr; - void (*close)(void*) = nullptr; - const char* (*get_error)() = nullptr; - void (*set_file_offset)(uint64_t) = nullptr; // applies to the next BinkOpen -}; - -template void bind(rt::Module& m, const char* name, F& out) { - auto it = m.exports.find(name); - if (it == m.exports.end()) fatal(std::string("Bink2Scarlett.dll does not export ") + name); - out = reinterpret_cast(it->second); -} - -constexpr uint32_t kCopyBgra32 = 3; // the BinkCopyToBuffer format bink_decode_test measured as 32-bit BGRA -constexpr uint32_t kFileOffset = 0x20; // BinkOpen flag: start at the offset BinkSetFileOffset gave - -struct Player { - BinkApi api; - void* bink = nullptr; - MovieHeader header; - std::vector frame; - uint32_t index = 0; // the frame in `frame` - bool paused = false; - bool loop = false; - bool quit = false; - bool seek_pending = false; - uint32_t seek_to = 0; - - void decode() { - // Headless, the frame is filled with a sentinel first, and a decode that leaves every byte of it fails: a - // pass then means each decoded frame wrote the buffer (not that its pixels are right). - constexpr uint8_t kSentinel = 0xa5; - if (!g_windowed) std::fill(frame.begin(), frame.end(), kSentinel); - api.do_frame(bink); - api.copy(bink, frame.data(), header.width * 4, header.height, 0, 0, kCopyBgra32); - if (!g_windowed && std::all_of(frame.begin(), frame.end(), [](uint8_t v) { return v == kSentinel; })) - fatal("headless decode left the BGRA buffer untouched"); - } - // Bink frame numbers in BinkGoto are 1-based. - void go_to(uint32_t target) { - index = std::min(target, header.frames - 1); - api.go_to(bink, index + 1, 0); - decode(); - } - uint32_t fps_frames(double seconds) const { - return (uint32_t)(seconds * header.fps_num / header.fps_den); - } -}; - -Player* g_player = nullptr; - -void paint(HWND hwnd) { - PAINTSTRUCT ps; - HDC dc = BeginPaint(hwnd, &ps); - RECT rc; - GetClientRect(hwnd, &rc); - const int cw = rc.right - rc.left, ch = rc.bottom - rc.top; - const Player& p = *g_player; - // Fit the frame in the client area, keeping its aspect ratio, and black out the bars. - int w = cw, h = (int)((int64_t)cw * p.header.height / p.header.width); - if (h > ch) { - h = ch; - w = (int)((int64_t)ch * p.header.width / p.header.height); - } - const int x = (cw - w) / 2, y = (ch - h) / 2; - HBRUSH black = (HBRUSH)GetStockObject(BLACK_BRUSH); - RECT bars[] = {{0, 0, cw, y}, {0, y + h, cw, ch}, {0, y, x, y + h}, {x + w, y, cw, y + h}}; - for (const RECT& b : bars) FillRect(dc, &b, black); - BITMAPINFO bi{}; - bi.bmiHeader.biSize = sizeof(bi.bmiHeader); - bi.bmiHeader.biWidth = (LONG)p.header.width; - bi.bmiHeader.biHeight = -(LONG)p.header.height; // top-down - bi.bmiHeader.biPlanes = 1; - bi.bmiHeader.biBitCount = 32; - bi.bmiHeader.biCompression = BI_RGB; - SetStretchBltMode(dc, COLORONCOLOR); - StretchDIBits(dc, x, y, w, h, 0, 0, (int)p.header.width, (int)p.header.height, p.frame.data(), &bi, - DIB_RGB_COLORS, SRCCOPY); - EndPaint(hwnd, &ps); -} - -LRESULT CALLBACK window_proc(HWND hwnd, UINT msg, WPARAM wp, LPARAM lp) { - Player& p = *g_player; - switch (msg) { - case WM_PAINT: paint(hwnd); return 0; - case WM_ERASEBKGND: return 1; - case WM_KEYDOWN: - switch (wp) { - case VK_ESCAPE: DestroyWindow(hwnd); return 0; - case VK_SPACE: p.paused = !p.paused; return 0; - case 'L': p.loop = !p.loop; return 0; - case VK_HOME: p.seek_pending = true; p.seek_to = 0; return 0; - case VK_LEFT: { - const uint32_t back = p.fps_frames(1.0); - p.seek_pending = true; - p.seek_to = p.index > back ? p.index - back : 0; - return 0; - } - case VK_RIGHT: - p.seek_pending = true; - p.seek_to = std::min(p.index + p.fps_frames(1.0), p.header.frames - 1); - return 0; - } - break; - case WM_DESTROY: p.quit = true; PostQuitMessage(0); return 0; - } - return DefWindowProcW(hwnd, msg, wp, lp); -} - -void set_title(HWND hwnd, const Player& p, const std::wstring& name, double rate) { - wchar_t title[256]; - swprintf(title, 256, L"bink_play - %s - frame %u/%u - decode %.1f fps%s%s", name.c_str(), p.index + 1, - p.header.frames, rate, p.paused ? L" - paused" : L"", p.loop ? L" - loop" : L""); - SetWindowTextW(hwnd, title); -} - -constexpr const char* kDefaultMovie = "Stinger/RSG_STINGER.bk2"; - -std::string lower_ascii(std::string v) { - for (char& c : v) c = (char)std::tolower((unsigned char)c); - std::replace(v.begin(), v.end(), '\\', '/'); - return v; -} - -struct NamedMovie { - std::string path; - uint64_t offset = 0; -}; - -struct NameTable { - std::filesystem::path archive; // the archive the table was built from (its first line) - std::vector movies; -}; - -std::filesystem::path name_table_path() { - const std::string base = env("LOCALAPPDATA"); - return base.empty() ? std::filesystem::path() : std::filesystem::path(base) / "Leonida" / "bink_names.csv"; -} - -// tools/bink_play.py's table: "# ||", then a header and path,offset,width,height,frames rows. -// Stale when the archive's size changed. Paths in the table have no commas (they are game file paths). -bool read_name_table(NameTable& out) { - const std::filesystem::path p = name_table_path(); - std::ifstream f(p); - std::string line; - if (p.empty() || !f || !std::getline(f, line) || line.rfind("# ", 0) != 0) return false; - const std::string stamp = line.substr(2); - const size_t bar1 = stamp.find('|'), bar2 = stamp.find('|', bar1 + 1); - if (bar1 == std::string::npos || bar2 == std::string::npos) return false; - out.archive = std::filesystem::path(stamp.substr(0, bar1)); - std::error_code ec; - const auto size = std::filesystem::file_size(out.archive, ec); - if (ec || std::to_string(size) != stamp.substr(bar1 + 1, bar2 - bar1 - 1)) return false; - std::getline(f, line); // header - out.movies.clear(); - while (std::getline(f, line)) { - if (!line.empty() && line.back() == '\r') line.pop_back(); - const size_t c1 = line.find(','), c2 = line.find(',', c1 + 1); - if (c1 == std::string::npos || c2 == std::string::npos) continue; - out.movies.push_back({line.substr(0, c1), std::strtoull(line.substr(c1 + 1, c2 - c1 - 1).c_str(), nullptr, 10)}); - } - return !out.movies.empty(); -} - -// Builds the table with tools/bink_play.py (the repository's copy, two folders up from runtime/build), once. -bool build_name_table(const std::filesystem::path& game_dir) { - wchar_t exe[MAX_PATH]; - GetModuleFileNameW(nullptr, exe, MAX_PATH); - std::filesystem::path tool; - for (std::filesystem::path d = std::filesystem::path(exe).parent_path(); !d.empty() && d != d.root_path(); - d = d.parent_path()) - if (std::filesystem::is_regular_file(d / "tools" / "bink_play.py")) { - tool = d / "tools" / "bink_play.py"; - break; - } - if (tool.empty() || game_dir.empty()) return false; - std::printf("naming the movies in movies.rpf (about half a minute, once)...\n"); - std::fflush(stdout); - const std::wstring cmd = L"python \"" + tool.wstring() + L"\" --list --game-dir \"" + game_dir.wstring() + L"\""; - STARTUPINFOW si{sizeof(si)}; - si.dwFlags = STARTF_USESTDHANDLES; - HANDLE nul = CreateFileW(L"NUL", GENERIC_WRITE, FILE_SHARE_WRITE, nullptr, OPEN_EXISTING, 0, nullptr); - si.hStdOutput = nul; // the list itself isn't wanted, only the table it leaves behind - si.hStdError = GetStdHandle(STD_ERROR_HANDLE); - si.hStdInput = GetStdHandle(STD_INPUT_HANDLE); - PROCESS_INFORMATION pi{}; - std::vector line(cmd.begin(), cmd.end()); - line.push_back(0); - const bool ok = CreateProcessW(nullptr, line.data(), nullptr, nullptr, TRUE, 0, nullptr, nullptr, &si, &pi); - if (ok) { - WaitForSingleObject(pi.hProcess, INFINITE); - CloseHandle(pi.hThread); - CloseHandle(pi.hProcess); - } - if (nul != INVALID_HANDLE_VALUE) CloseHandle(nul); - return ok; -} - -// The movie a NAME means: exactly that path (case-insensitive), else the only path containing it. -NamedMovie find_named(const NameTable& table, const std::string& name) { - const std::string want = lower_ascii(name); - std::vector part; - for (const NamedMovie& m : table.movies) { - const std::string have = lower_ascii(m.path); - if (have == want) return m; - if (have.find(want) != std::string::npos) part.push_back(&m); - } - if (part.size() == 1) return *part[0]; - std::string why = part.empty() ? "no movie is named like \"" + name + "\"" : - std::to_string(part.size()) + " movies match \"" + name + "\"; be more specific:"; - for (size_t i = 0; i < part.size() && i < 20; ++i) why += "\n " + part[i]->path; - if (part.empty()) why += " (python tools\\bink_play.py --list shows the names)"; - fatal(why); -} - -} // namespace - -int main(int argc, char** argv) { - std::string game_dir_arg = env("LEONIDA_GAME_DIR"), movie_arg = env("LEONIDA_MOVIE"); - long max_frames = -1; - bool headless = false, loop = false; - for (int i = 1; i < argc; ++i) { - const std::string a = argv[i]; - if (a == "--game-dir" && i + 1 < argc) game_dir_arg = argv[++i]; - else if (a == "--frames" && i + 1 < argc) { - char* end = nullptr; - max_frames = std::strtol(argv[++i], &end, 10); - if (!end || *end || max_frames <= 0) fatal("--frames takes a positive count"); - } else if (a == "--headless") headless = true; - else if (a == "--loop") loop = true; - else if (!a.empty() && a[0] != '-') movie_arg = a; - else { - std::fprintf(stderr, "usage: bink_play [NAME | movie.bk2 | archive.rpf@OFFSET] [--game-dir DIR] " - "[--frames N] [--headless] [--loop]\n"); - return 2; - } - } - g_windowed = !headless; - // CTest's headless smoke run gives no movie: that is a skip, not a request for the default one. - if (movie_arg.empty() && headless) { - std::printf("SKIP (no package/movie)\n"); - return 77; - } - if (movie_arg.empty()) movie_arg = kDefaultMovie; - - // A name (not a file, not archive@OFFSET) goes through the name table, which also knows the game folder. - std::error_code ec; - const bool is_name = movie_arg.find('@') == std::string::npos && !std::filesystem::is_regular_file(movie_arg, ec); - if (is_name) { - NameTable table; - if (!read_name_table(table)) { - if (game_dir_arg.empty()) - fatal("bink_play needs the game folder once, to name the movies:\n\n" - " bink_play " + movie_arg + " --game-dir \n\n" - "After that, double-clicking bink_play.exe plays the stinger."); - build_name_table(game_dir_arg); - if (!read_name_table(table)) fatal("could not build the movie name table with tools\\bink_play.py"); - } - const NamedMovie m = find_named(table, movie_arg); - std::printf("%s\n", m.path.c_str()); - if (game_dir_arg.empty()) game_dir_arg = table.archive.parent_path().string(); - movie_arg = table.archive.string() + "@" + std::to_string(m.offset); - } - if (game_dir_arg.empty()) fatal("no game folder: pass --game-dir or set LEONIDA_GAME_DIR"); - - const std::filesystem::path game_dir = game_dir_arg; - std::filesystem::path movie = movie_arg; - uint64_t offset = 0; - if (const size_t at = movie_arg.rfind('@'); at != std::string::npos) { - char* end = nullptr; - offset = std::strtoull(movie_arg.c_str() + at + 1, &end, 0); - if (at + 1 == movie_arg.size() || !end || *end) fatal("the movie's @OFFSET is not a number"); - movie = movie_arg.substr(0, at); - if (movie.is_relative() && !std::filesystem::exists(movie)) movie = game_dir / movie; - } - if (!std::filesystem::is_regular_file(game_dir / "Bink2Scarlett.dll", ec)) - fatal("the game folder does not contain Bink2Scarlett.dll"); - if (!std::filesystem::is_regular_file(movie, ec)) fatal("the movie is not a file"); - - Player player; - g_player = &player; - player.header = read_movie_header(movie, offset); - player.loop = loop; - const MovieHeader& h = player.header; - std::printf("movie: %ux%u, %u frames, %u/%u fps\n", h.width, h.height, h.frames, h.fps_num, h.fps_den); - - try { - rt::Loader loader(game_dir); - rt::Module& dll = loader.load(game_dir / "Bink2Scarlett.dll"); - for (auto& r : dll.imports) - if (r.binding == rt::Binding::Unimplemented && rt::lower(r.dll).find("xaudio") == std::string::npos) - fatal("Bink2Scarlett.dll import " + r.dll + "!" + r.name + " is unimplemented"); - BinkApi& api = player.api; - bind(dll, "BinkOpen", api.open); - bind(dll, "BinkDoFrame", api.do_frame); - bind(dll, "BinkCopyToBuffer", api.copy); - bind(dll, "BinkNextFrame", api.next); - bind(dll, "BinkGoto", api.go_to); - bind(dll, "BinkClose", api.close); - bind(dll, "BinkGetError", api.get_error); - if (offset) { - bind(dll, "BinkSetFileOffset", api.set_file_offset); - api.set_file_offset(offset); - } - - player.bink = api.open(movie.string().c_str(), offset ? kFileOffset : 0); - if (!player.bink) { - const char* e = api.get_error ? api.get_error() : nullptr; - fatal(std::string("BinkOpen failed: ") + (e && *e ? e : "(no BinkGetError text)")); - } - player.frame.assign((size_t)h.width * 4 * h.height, 0); - player.decode(); - - using clock = std::chrono::steady_clock; - const auto frame_time = std::chrono::duration((double)h.fps_den / h.fps_num); - const uint32_t last = max_frames > 0 ? (uint32_t)std::min(max_frames, (long)h.frames) : h.frames; - - if (headless) { - const auto start = clock::now(); - uint32_t decoded = 1; - while (decoded < last) { - api.next(player.bink); - player.decode(); - ++decoded; - } - const double s = std::chrono::duration(clock::now() - start).count(); - std::printf("decoded %u frames in %.2f s (%.1f fps; the movie runs at %.2f fps)\n", decoded, s, - s > 0 ? decoded / s : 0.0, (double)h.fps_num / h.fps_den); - api.close(player.bink); - std::printf("RESULT PASS\n"); - return 0; - } - - WNDCLASSW wc{}; - wc.lpfnWndProc = window_proc; - wc.hInstance = GetModuleHandleW(nullptr); - wc.hCursor = LoadCursor(nullptr, IDC_ARROW); - wc.lpszClassName = L"LeonidaBinkPlay"; - RegisterClassW(&wc); - // Start at up to 1280 wide (or the movie's size if smaller), the movie's aspect ratio. - const int start_w = (int)std::min(h.width, 1280); - RECT r{0, 0, start_w, (int)((int64_t)start_w * h.height / h.width)}; - AdjustWindowRect(&r, WS_OVERLAPPEDWINDOW, FALSE); - HWND hwnd = CreateWindowW(wc.lpszClassName, L"bink_play", WS_OVERLAPPEDWINDOW | WS_VISIBLE, CW_USEDEFAULT, - CW_USEDEFAULT, r.right - r.left, r.bottom - r.top, nullptr, nullptr, wc.hInstance, - nullptr); - if (!hwnd) fatal("CreateWindow failed"); - const std::wstring name = movie.filename().wstring() + (offset ? L"@" + std::to_wstring(offset) : L""); - - auto due = clock::now() + frame_time; - auto rate_start = clock::now(); - uint32_t rate_frames = 0, shown = 1; - double rate = 0; - while (!player.quit) { - MSG msg; - while (PeekMessageW(&msg, nullptr, 0, 0, PM_REMOVE)) { - TranslateMessage(&msg); - DispatchMessageW(&msg); - } - if (player.quit) break; - if (player.seek_pending) { - player.seek_pending = false; - player.go_to(player.seek_to); - InvalidateRect(hwnd, nullptr, FALSE); - due = clock::now() + frame_time; - } - if (player.paused || clock::now() < due) { - set_title(hwnd, player, name, rate); - std::this_thread::sleep_for(std::chrono::milliseconds(1)); - continue; - } - if (player.index + 1 >= h.frames || (max_frames > 0 && shown >= last)) { - if (!player.loop) break; - player.go_to(0); - } else { - api.next(player.bink); - player.decode(); - ++player.index; - } - ++shown; - InvalidateRect(hwnd, nullptr, FALSE); - UpdateWindow(hwnd); - ++rate_frames; - const double elapsed = std::chrono::duration(clock::now() - rate_start).count(); - if (elapsed >= 1.0) { - rate = rate_frames / elapsed; - rate_frames = 0; - rate_start = clock::now(); - } - set_title(hwnd, player, name, rate); - // Hold the movie's frame rate; when decoding falls behind, don't try to catch up in a burst. - due += std::chrono::duration_cast(frame_time); - if (clock::now() > due + std::chrono::duration_cast(frame_time * 4)) due = clock::now(); - } - if (IsWindow(hwnd)) DestroyWindow(hwnd); - api.close(player.bink); - std::printf("played %u frames\n", shown); - return 0; - } catch (const std::exception& e) { - fatal(e.what()); - } -} diff --git a/runtime/test/bink_play.md b/runtime/test/bink_play.md deleted file mode 100644 index a98371a46..000000000 --- a/runtime/test/bink_play.md +++ /dev/null @@ -1,55 +0,0 @@ -# `bink_play`: watch a Bink 2 movie through the package's decoder - -`bink_play.cpp` maps the package's `Bink2Scarlett.dll` with `rt::Loader` (the path `bink_decode_test` checks) and plays -a Bink 2 movie in a window at the movie's frame rate. A movie inside an archive plays where it is: nothing is -extracted and nothing it decodes is written to disk. - -```sh -bink_play # no movie: plays Stinger/RSG_STINGER.bk2 (so a double-click plays it) -bink_play stinger # a movie's path in the game, or any unique part of it -bink_play TV/.bk2 --loop -bink_play movies.rpf@OFFSET | file.bk2 # an offset in an archive, or a loose .bk2 -``` - -Options: `--game-dir DIR`, `--frames N`, `--headless`, `--loop`. The game folder comes from `--game-dir`, -`LEONIDA_GAME_DIR`, or the archive the name table was built from. - -Names come from the table `tools/bink_play.py` keeps in `%LOCALAPPDATA%\Leonida\bink_names.csv` (names, offsets -and frame sizes from `tools/bink_names.py` and `common.rpf`'s mount lists; no movie data), rebuilt when the archive's -size changes. Without a table, `bink_play` runs that tool once to build it, which takes about half a minute and needs -the game folder the first time: `bink_play stinger --game-dir C:\path\to\package`. After that a double-click -is enough. `python tools/bink_play.py --list [TEXT]` lists the names. - -For `archive@OFFSET` it calls `BinkSetFileOffset(OFFSET)` and opens the archive with `BinkOpen`'s `BINKFILEOFFSET` -flag (0x20); without the flag the offset is ignored and `BinkOpen` reports "Not a Bink file". An error in a windowed -run is shown in a message box too, since a double-clicked console closes with the process. - -| Key | Action | -|---|---| -| Space | pause / resume | -| Left / Right | one second back / forward (`BinkGoto`) | -| Home | back to the first frame | -| L | loop on / off | -| Esc, closing the window | quit | - -The window title shows the frame number and the rate frames are being shown. The frame is scaled to the window with -its aspect ratio kept (GDI `StretchDIBits`, no GPU path). - -`--headless` decodes without a window as fast as it can and prints the decode rate; `--frames N` stops after N -frames. CTest runs `bink_play --headless --frames 30` as `bink_play_headless`, which skips (exit 77) unless -`LEONIDA_MOVIE` names a movie (a headless run never falls back to the stinger). - -## Measured on 1.0.2.1 - -`Stinger/RSG_STINGER.bk2` (3840x2160, 450 frames, 30 fps), played from inside `movies.rpf`: 90 frames decode -headless in about 1 s (81-118 fps over runs) on a Ryzen 7 5700X (the decoder is CPU-only), so the 4K stinger plays in -real time; the windowed run shows all 450 frames. - -An independent run on a second machine (Windows 11, Ryzen 7 7800X3D, own 1.0.2.1 package) plays a 1280x720 181-frame -`KB2n` stream headless in 0.27 s (**672 fps**), consistent with the decoder being CPU-only and the 4K rate above -being resolution-bound rather than machine-bound. - -## Gaps - -No audio: the movie's Bink Audio tracks are not decoded and no sound system is opened (as in `bink_decode_test`). -Playback uses the synchronous `BinkDoFrame` path only. diff --git a/runtime/test/buffer_va_index_test.cpp b/runtime/test/buffer_va_index_test.cpp deleted file mode 100644 index 8abf4462d..000000000 --- a/runtime/test/buffer_va_index_test.cpp +++ /dev/null @@ -1,343 +0,0 @@ -// BufferVaIndex (runtime/src/buffer_va_index.h): the VA -> buffer lookup behind VulkanContext::buffer_at. CPU only. -// -// Checks fixed cases (edges, aliasing placed buffers, re-registration), then random tables against a linear scan -// with the same rule, and prints how long a lookup takes against the linear scan over every resource it replaces. -// `--bench` times larger tables. - -#include "../src/buffer_va_index.h" - -#include -#include -#include -#include -#include -#include -#include -#include -#include - -using leonida::BufferVaIndex; -using Index = BufferVaIndex; - -// Single-threaded test: arm only around insert(), after constructing the index and its existing ranges. -static int allocations_before_failure = -1; -void* operator new(std::size_t size) { - if (allocations_before_failure == 0) { - allocations_before_failure = -1; - throw std::bad_alloc(); - } - if (allocations_before_failure > 0) --allocations_before_failure; - if (void* p = std::malloc(size ? size : 1)) return p; - throw std::bad_alloc(); -} -void* operator new[](std::size_t size) { return operator new(size); } -void operator delete(void* p) noexcept { std::free(p); } -void operator delete[](void* p) noexcept { std::free(p); } -void operator delete(void* p, std::size_t) noexcept { std::free(p); } -void operator delete[](void* p, std::size_t) noexcept { std::free(p); } - -namespace { - -int failures = 0; - -void check(bool ok, const char* what) { - if (ok) return; - std::printf("FAIL: %s\n", what); - ++failures; -} - -// The id that holds `va` (preferring one that holds `bytes` from it), 0 for none. -std::uintptr_t at(const Index& index, std::uint64_t va, std::uint64_t bytes = 1) { - Index::Hit hit{}; - return index.find(va, hit, bytes) ? hit.id : 0; -} - -void fixed_cases() { - Index index; - check(at(index, 0x1000) == 0, "an empty index holds nothing"); - - index.insert(0x1000, 0x100, 1); // [0x1000, 0x1100) - index.insert(0x2000, 0x10, 2); // [0x2000, 0x2010) - check(at(index, 0x1000) == 1, "the first byte"); - check(at(index, 0x10ff) == 1, "the last byte"); - check(at(index, 0x1100) == 0, "one past the end"); - check(at(index, 0x0fff) == 0, "one before the start"); - check(at(index, 0x1800) == 0, "a gap between two buffers"); - check(at(index, 0x200f) == 2, "the second buffer's last byte"); - check(at(index, ~std::uint64_t(0)) == 0, "the highest VA"); - - Index::Hit hit{}; - check(index.find(0x1080, hit) && hit.start == 0x1000 && hit.size == 0x100, "a hit names its range"); - - index.insert(0, 0x100, 3); - index.insert(0x3000, 0, 4); - check(index.size() == 2 && at(index, 0) == 0 && at(index, 0x3000) == 0, "a null VA or an empty range is not indexed"); - - // Aliasing placed buffers: a long one with two short ones inside it. The nearest start that holds the VA wins. - Index alias; - alias.insert(0x10000, 0x10000, 10); // [0x10000, 0x20000) - alias.insert(0x11000, 0x100, 11); // inside it - alias.insert(0x12000, 0x100, 12); // inside it - check(at(alias, 0x11080) == 11, "a short buffer inside a long one"); - check(at(alias, 0x11100) == 10, "past the short buffer, the long one still holds the VA"); - check(at(alias, 0x1f000) == 10, "past every short buffer"); - check(at(alias, 0x20000) == 0, "past the long buffer"); - - // A view that starts in a short buffer and runs past its end: the long buffer around it holds all of it. - check(at(alias, 0x11080, 0x80) == 11, "a view that fits in the short buffer stays in it"); - check(at(alias, 0x11080, 0x81) == 10, "a view past the short buffer's end goes to the long one around it"); - check(at(alias, 0x1ff00, 0x200) == 10, "a view no range holds: the closest that holds its start"); - check(at(alias, 0x11080, 0x10000) == 11, "a view past the long buffer too: the closest start, as without a size"); - check(at(alias, 0x11080, 0) == 11, "a size of 0 counts as one byte"); - - // Two resources placed at the same offset: the larger ID, either way they were added. - alias.insert(0x30000, 0x100, 21); - alias.insert(0x30000, 0x200, 20); - check(at(alias, 0x30080) == 21, "the same start: the larger ID"); - check(at(alias, 0x30180) == 20, "the same start: past the shorter one"); - - // Erasing and re-registering. - alias.erase(0x11000, 11); - check(at(alias, 0x11080) == 10, "an erased buffer leaves the one around it"); - alias.erase(0x11000, 11); // twice: nothing - alias.erase(0x10000, 99); // a wrong ID: nothing - check(at(alias, 0x10000) == 10, "an erase with the wrong ID keeps the range"); - alias.erase(0x10000, 10); - alias.erase(0x12000, 12); - alias.erase(0x30000, 20); - alias.erase(0x30000, 21); - check(alias.size() == 0 && at(alias, 0x10000) == 0, "everything erased"); - alias.insert(0x40000, 0x10, 30); // the bound restarts from an empty index - check(at(alias, 0x40008) == 30 && at(alias, 0x40010) == 0, "an index refilled after it emptied"); - - // The bound follows the live ranges: freeing the longest one brings it down to the next longest. - Index bound; - bound.insert(0x10000, 0x100, 1); - bound.insert(0x20000, 0x100, 2); // the same size twice: dropping one keeps the other's - bound.insert(0x30000, 0x40000000, 3); - check(bound.longest() == 0x40000000, "the bound is the longest range"); - bound.erase(0x30000, 3); - check(bound.longest() == 0x100, "freeing the longest range lowers the bound"); - bound.erase(0x10000, 1); - check(bound.longest() == 0x100 && at(bound, 0x20080) == 2, "a range of the same size keeps the bound"); - bound.insert(0x20000, 0x40, 2); // re-registered with a smaller size: the old size goes - check(bound.longest() == 0x40 && at(bound, 0x20040) == 0, "re-registering replaces the size"); - bound.erase(0x20000, 2); - check(bound.longest() == 0 && bound.size() == 0, "an empty index has no bound"); -} - -void allocation_failures() { - for (bool replace : {false, true}) { - for (std::uint64_t size : {0x40u, 0x100u, 0x400u}) { - // New entries allocate a range and a size node; replacement only needs a size node. - for (int fail_after = 0; fail_after < (replace ? 1 : 2); ++fail_after) { - Index index; - index.insert(0x1000, 0x100, 1); - index.insert(0x2000, 0x100, 2); // equal sizes must retain separate multiset entries - const std::uint64_t va = replace ? 0x1000 : 0x3000; - const std::uintptr_t id = replace ? 1 : 3; - bool threw = false; - allocations_before_failure = fail_after; - try { - index.insert(va, size, id); - } catch (const std::bad_alloc&) { - threw = true; - } - allocations_before_failure = -1; - check(threw, "injected insert allocation failure reached"); - Index::Hit first{}, second{}; - const bool unchanged = index.size() == 2 && index.longest() == 0x100 && - index.find(0x1000, first) && first.id == 1 && first.size == 0x100 && - index.find(0x2000, second) && second.id == 2 && second.size == 0x100 && - at(index, 0x10ff) == 1 && at(index, 0x1100) == 0 && at(index, 0x3000) == 0; - check(unchanged, "failed insert preserves ranges and lookup bound"); - if (!unchanged) continue; // do not erase an inconsistent index in the negative control - - if (replace && size == 0x100) { - // A failed same-size replacement can look unchanged while silently dropping a size node. - index.erase(0x2000, 2); - const bool counted = index.size() == 1 && index.longest() == 0x100; - check(counted, "failed same-size replacement retains both size entries"); - if (!counted) continue; - index.insert(0x2000, 0x100, 2); - } - - index.insert(va, size, id); - Index::Hit retried{}; - check(index.size() == (replace ? 2u : 3u) && index.find(va, retried) && - retried.id == id && retried.size == size, "insert succeeds after allocation failure"); - check(index.longest() == (size > 0x100 ? size : 0x100), "retry updates the lookup bound"); - index.erase(va, id); - check(index.longest() == 0x100 && at(index, 0x20ff) == 2, - "erasing retried range keeps the other size entry"); - index.erase(0x1000, 1); - index.erase(0x2000, 2); - check(index.size() == 0 && index.longest() == 0, "all size entries disappear after erase"); - } - } - } -} - -// The rule BufferVaIndex follows, by a scan: among the ranges that hold all of [va, va + bytes), the greatest -// (start, id); when none does, the greatest among those that hold va. -struct Range { - std::uint64_t start, size; - std::uintptr_t id; -}; - -std::uintptr_t scan(const std::vector& ranges, std::uint64_t va, std::uint64_t bytes = 1) { - const Range* best = nullptr; - const Range* whole = nullptr; - const auto greater = [](const Range& a, const Range* b) { - return !b || a.start > b->start || (a.start == b->start && a.id > b->id); - }; - for (const Range& r : ranges) { - if (va < r.start || va - r.start >= r.size) continue; - if (greater(r, best)) best = &r; - if (bytes <= r.size - (va - r.start) && greater(r, whole)) whole = &r; - } - return whole ? whole->id : best ? best->id : 0; -} - -void random_tables() { - std::mt19937_64 rng(0x1e0a1da); - for (int round = 0; round < 200; ++round) { - Index index; - std::vector ranges; - const bool aliasing = round % 2; // half the tables pack buffers apart, half overlap them - std::uint64_t next = 0x10000; - const int count = 1 + int(rng() % 64); - for (int i = 0; i < count; ++i) { - const std::uint64_t size = 1 + rng() % 0x4000; - const std::uint64_t start = aliasing ? 0x10000 + rng() % 0x20000 : next; - next += size + rng() % 0x1000; - const Range r{start, size, std::uintptr_t(i + 1)}; - ranges.push_back(r); - index.insert(r.start, r.size, r.id); - } - // Drop a few, as remove_resource does. - for (int i = 0; i < count / 4; ++i) { - const std::size_t k = rng() % ranges.size(); - index.erase(ranges[k].start, ranges[k].id); - ranges.erase(ranges.begin() + std::ptrdiff_t(k)); - if (ranges.empty()) break; - } - std::uint64_t longest = 0; - for (const Range& r : ranges) longest = r.size > longest ? r.size : longest; - if (index.longest() != longest) { - std::printf("FAIL: round %d: bound %llu, longest live range %llu\n", round, - (unsigned long long)index.longest(), (unsigned long long)longest); - ++failures; - return; - } - for (int q = 0; q < 2000; ++q) { - const std::uint64_t va = 0x8000 + rng() % (next + 0x20000); - // A quarter of the lookups name one byte, the rest a view of up to twice the largest buffer. - const std::uint64_t bytes = q % 4 ? 1 + rng() % 0x8000 : 1; - if (at(index, va, bytes) != scan(ranges, va, bytes)) { - std::printf("FAIL: round %d va 0x%llx bytes 0x%llx: index %llu, scan %llu\n", round, - (unsigned long long)va, (unsigned long long)bytes, - (unsigned long long)at(index, va, bytes), (unsigned long long)scan(ranges, va, bytes)); - ++failures; - return; - } - } - } -} - -// What buffer_at did before: a walk over every registered resource, images included, in an unordered_map. -struct Binding { - bool image; - std::uint64_t va, size; -}; - -void time_lookups(std::size_t resources) { - std::unordered_map all; - Index index; - std::vector vas; - std::mt19937_64 rng(resources); - std::uint64_t next = 0x10000; - for (std::size_t i = 1; i <= resources; ++i) { - if (i % 2) { // half images, as in a frame's working set - all[i] = {true, 0, 0}; - continue; - } - const std::uint64_t size = 256 + rng() % (1 << 20); - all[i] = {false, next, size}; - index.insert(next, size, i); - vas.push_back(next + rng() % size); - next += (size + 255) / 256 * 256; - } - constexpr int lookups = 20000; - using clock = std::chrono::steady_clock; - std::uint64_t sink = 0; - - auto t0 = clock::now(); - for (int i = 0; i < lookups; ++i) { - const std::uint64_t va = vas[std::size_t(i) % vas.size()]; - for (const auto& [id, b] : all) { - if (b.image || va < b.va || va - b.va >= b.size) continue; - sink += id; - break; - } - } - const double linear = std::chrono::duration(clock::now() - t0).count() / lookups; - - t0 = clock::now(); - for (int i = 0; i < lookups; ++i) sink += at(index, vas[std::size_t(i) % vas.size()]); - const double indexed = std::chrono::duration(clock::now() - t0).count() / lookups; - - std::printf("%7zu resources: linear scan %10.1f ns/lookup, index %6.1f ns/lookup (x%.0f)%s\n", resources, linear, - indexed, linear / (indexed > 0 ? indexed : 1), sink ? "" : " "); -} - -// A miss past the last of many small buffers, once a large buffer has come and gone (found in review of #2823): the -// index that held it must be as fast as one that never did. -void time_miss_after_free() { - constexpr std::uint64_t count = 20000, stride = 256; - Index fresh, churned; - for (std::uint64_t i = 0; i < count; ++i) { - fresh.insert(0x10000 + i * stride, stride, i + 1); - churned.insert(0x10000 + i * stride, stride, i + 1); - } - churned.insert(0x10000, std::uint64_t(1) << 30, count + 1); // 1 GiB over all of them - churned.erase(0x10000, count + 1); - check(churned.longest() == stride, "the bound comes back down after a large buffer is freed"); - - const std::uint64_t miss = 0x10000 + count * stride + stride; - constexpr int lookups = 20000; - using clock = std::chrono::steady_clock; - std::uint64_t sink = 0; - double ns[2]; - const Index* indexes[2] = {&fresh, &churned}; - for (int k = 0; k < 2; ++k) { - const auto t0 = clock::now(); - for (int i = 0; i < lookups; ++i) sink += at(*indexes[k], miss + std::uint64_t(i % 64)); - ns[k] = std::chrono::duration(clock::now() - t0).count() / lookups; - } - std::printf("miss past %llu buffers: fresh index %.1f ns, after a freed 1 GiB buffer %.1f ns%s\n", - (unsigned long long)count, ns[0], ns[1], sink ? " (hit?)" : ""); -} - -} // namespace - -int main(int argc, char** argv) { - fixed_cases(); - allocation_failures(); - random_tables(); - if (failures) { - std::printf("%d failure(s)\n", failures); - return 1; - } - time_miss_after_free(); - if (failures) { - std::printf("%d failure(s)\n", failures); - return 1; - } - std::puts("BufferVaIndex: fixed cases and 200 random tables agree with the scan"); - const bool bench = argc > 1 && std::strcmp(argv[1], "--bench") == 0; - for (const std::size_t n : {std::size_t(1000), std::size_t(10000)}) time_lookups(n); - if (bench) - for (const std::size_t n : {std::size_t(50000), std::size_t(100000)}) time_lookups(n); - return 0; -} diff --git a/runtime/test/bvh_builder_test.cpp b/runtime/test/bvh_builder_test.cpp deleted file mode 100644 index 686d4ba79..000000000 --- a/runtime/test/bvh_builder_test.cpp +++ /dev/null @@ -1,903 +0,0 @@ -// Optional Windows test: map the package's XboxBvhBuilder.dll through rt::Loader, bring it up (Loader::initialise: -// TLS and DllMain), and construct an XboxBvhBuilder on a PC D3D12 device behind the Xbox-ABI device proxy. -// Needs the proxy's slot-62 shape (desc, w2, w3, riid, out). Results: docs/d3d12_vulkan.md, Appendix A.2. -// It records what the constructor does: how much of the object it writes, which device slots it calls, what it -// prints through OutputDebugString, and whether it gives up through TerminateProcess. -// -// LEONIDA_GAME_DIR= (contains XboxBvhBuilder.dll) -// LEONIDA_BVH_FLAG=1 (optional: pass true as the constructor's bool argument) -// LEONIDA_BVH_WARP=1 (optional: use the WARP adapter; the default on an NVIDIA adapter, RT-54) -// LEONIDA_BVH_HARDWARE=1 (optional: keep an NVIDIA adapter instead of switching to WARP) -// LEONIDA_BVH_RECORD62=1 (optional: print each CreateComputePipelineState's container shape, its ILDN -// module name and digest, the call site (stack frames as offsets from the DLL's -// image base with the enclosing function's start) and the name the builder -// gives the returned PSO through SetName / SetPrivateData, RT-266) -// LEONIDA_BVH_DXIL=1 (optional, with RECORD62: dx.op counts and validator error kinds, needs -// dxcompiler.dll and dxil.dll on PATH) -// LEONIDA_BVH_DEVICE=vulkan (optional: the Vulkan-backed ID3D12Device from #119 instead of a PC device) -// -// Without LEONIDA_GAME_DIR it prints "SKIP (no package)" and exits 77 (CTest skip). Nothing from the DLL is written to disk. -// -// The exports are C++ members (demangled): XboxBvhBuilder::XboxBvhBuilder(ID3D12Device11*, bool) and ~XboxBvhBuilder(). -// sizeof(XboxBvhBuilder) is not exported, so the object lives in a large buffer filled with a sentinel, and the -// highest byte the constructor changed is a lower bound for the size. OutputDebugStringA/W and TerminateProcess are -// redirected in this DLL's IAT only. Calls into the DLL run under SEH. -#include - -#include -#include -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include "../shims/d3d12_xs_device.h" -#include "../shims/shims.h" -#include "../src/pe_loader.h" -#ifdef LEONIDA_VULKAN_DEVICE -#include "../shims/d3d12_com.h" -#endif - -namespace { - -int g_failures = 0; -uint64_t g_debug_strings = 0; -uint64_t g_terminate_calls = 0; -constexpr DWORD kTerminateCalled = 0xE0B71E00; // raised instead of terminating, caught by the SEH guard - -void check(bool condition, const std::string& what) { - std::printf("%s %s\n", condition ? "PASS" : "FAIL", what.c_str()); - if (!condition) ++g_failures; -} - -void note(const std::string& what) { std::printf("INFO %s\n", what.c_str()); } - -std::string env(const char* name) { - const char* v = std::getenv(name); - return v ? v : ""; -} - -std::string hex(uint64_t v) { - char b[32]; - std::snprintf(b, sizeof(b), "0x%llx", static_cast(v)); - return b; -} - -void WINAPI debug_a(LPCSTR s) { - ++g_debug_strings; - std::printf(" dbg: %s%s", s ? s : "(null)", s && *s && s[std::strlen(s) - 1] == '\n' ? "" : "\n"); -} -void WINAPI debug_w(LPCWSTR s) { - ++g_debug_strings; - std::printf(" dbg: %ls%s", s ? s : L"(null)", s && *s && s[wcslen(s) - 1] == L'\n' ? "" : "\n"); -} -BOOL WINAPI terminate_stub(HANDLE, UINT exit_code) { - ++g_terminate_calls; - ULONG_PTR arg = exit_code; - RaiseException(kTerminateCalled, EXCEPTION_NONCONTINUABLE, 1, &arg); - return FALSE; -} - -void** iat_slot(rt::Module& m, const char* want_dll, const char* want_name) { - auto* dos = reinterpret_cast(m.base); - auto* nt = reinterpret_cast(m.base + dos->e_lfanew); - auto& dir = nt->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT]; - for (auto* d = reinterpret_cast(m.base + dir.VirtualAddress); d->Name; ++d) { - if (rt::lower(reinterpret_cast(m.base + d->Name)) != want_dll) continue; - auto* lookup = reinterpret_cast(m.base + (d->OriginalFirstThunk ? d->OriginalFirstThunk : d->FirstThunk)); - auto* iat = reinterpret_cast(m.base + d->FirstThunk); - for (; lookup->u1.AddressOfData; ++lookup, ++iat) { - if (IMAGE_SNAP_BY_ORDINAL64(lookup->u1.Ordinal)) continue; - auto* n = reinterpret_cast(m.base + static_cast(lookup->u1.AddressOfData)); - if (std::string(want_name) == n->Name) return reinterpret_cast(&iat->u1.Function); - } - } - return nullptr; -} - -bool patch(void** slot, void* fn) { - DWORD prot = 0; - if (!slot || !VirtualProtect(slot, sizeof(void*), PAGE_READWRITE, &prot)) return false; - *slot = fn; - VirtualProtect(slot, sizeof(void*), prot, &prot); - return true; -} - -struct Call { - bool faulted = false; - DWORD code = 0; - ULONG_PTR arg = 0; - char cxx_type[128] = {}; // first catchable type of a C++ exception, e.g. ".?AVruntime_error@std@@" - char cxx_what[256] = {}; // what() when that type is a std::exception -}; - -// MSVC x64 C++ exceptions (0xE06D7363): ExceptionInformation = {magic, object, ThrowInfo*, image base}; the -// ThrowInfo / CatchableTypeArray / CatchableType / TypeDescriptor chain uses 32-bit RVAs from that base. -void decode_cxx(const EXCEPTION_RECORD* r, Call* c) { - if (r->ExceptionCode != 0xE06D7363 || r->NumberParameters < 4) return; - auto* object = reinterpret_cast(r->ExceptionInformation[1]); - auto* info = reinterpret_cast(r->ExceptionInformation[2]); - auto* base = reinterpret_cast(r->ExceptionInformation[3]); - if (!info || !base) return; - const int32_t types_rva = *reinterpret_cast(info + 12); // pCatchableTypeArray - const uint8_t* types = base + types_rva; - const int32_t count = *reinterpret_cast(types); - bool is_std_exception = false; - for (int32_t i = 0; i < count; ++i) { - const uint8_t* ct = base + *reinterpret_cast(types + 4 + 4 * i); - const char* name = reinterpret_cast(base + *reinterpret_cast(ct + 4) + 16); - if (i == 0) strncpy_s(c->cxx_type, name, _TRUNCATE); - if (std::strcmp(name, ".?AVexception@std@@") == 0) is_std_exception = true; - } - if (std::strcmp(c->cxx_type, ".J") == 0 && object) // `long`: an HRESULT thrown by value - std::snprintf(c->cxx_what, sizeof(c->cxx_what), "long (HRESULT) 0x%08lx", - static_cast(*static_cast(object))); - if (is_std_exception && object) { - const char* what = static_cast(object)->what(); - if (what) strncpy_s(c->cxx_what, what, _TRUNCATE); - } -} - -int filter(EXCEPTION_POINTERS* e, Call* c) { - c->code = e->ExceptionRecord->ExceptionCode; - if (e->ExceptionRecord->NumberParameters) c->arg = e->ExceptionRecord->ExceptionInformation[0]; - __try { - decode_cxx(e->ExceptionRecord, c); - } __except (EXCEPTION_EXECUTE_HANDLER) { - } - return EXCEPTION_EXECUTE_HANDLER; -} - -using Ctor = void* (*)(void* self, void* device, bool flag); -using Dtor = void (*)(void* self); - -// Each guard returns a copy of `c`, not `c` itself: with `return c;` the local becomes the named return value, and -// clang-cl 19 and 20 crash (exit 139, in recoverAddrOfEscapedLocal) generating the __except filter that writes it, -// which stops the Linux cross-build (runtime/cmake/clang-cl-xwin.cmake). MSVC is fine either way. -Call guarded_ctor(Ctor fn, void* self, void* device, bool flag) { - Call c; - __try { - fn(self, device, flag); - } __except (filter(GetExceptionInformation(), &c)) { - c.faulted = true; - } - return Call(c); -} - -Call guarded_dtor(Dtor fn, void* self) { - Call c; - __try { - fn(self); - } __except (filter(GetExceptionInformation(), &c)) { - c.faulted = true; - } - return Call(c); -} - -// main's loader (#95) maps, sets up TLS and runs DllMain, but doesn't register the image's x64 unwind tables yet -// (#176 adds that). Both DLLs throw and catch C++ exceptions inside, which ends the process without them. Register -// .pdata here only when the loader hasn't, so the test keeps working once the loader does. -bool ensure_unwind_registered(rt::Module& m) { - DWORD64 base = 0; - if (RtlLookupFunctionEntry(reinterpret_cast(m.base + m.entry_rva), &base, nullptr)) return true; - auto* nt = reinterpret_cast(m.base + reinterpret_cast(m.base)->e_lfanew); - const auto& ex = nt->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXCEPTION]; - return ex.Size && RtlAddFunctionTable(reinterpret_cast(m.base + ex.VirtualAddress), - ex.Size / sizeof(RUNTIME_FUNCTION), reinterpret_cast(m.base)); -} - -// Loader::initialise() runs the module's TLS setup and DllMain (#95). SEH faults inside the DLL are reported here; -// C++ exceptions (a DllMain returning FALSE, a corrupt TLS directory) go on to the caller's catch. -DWORD guarded_initialise(rt::Loader* loader) { - DWORD code = 0; - __try { - loader->initialise(); - } __except ((code = GetExceptionCode()) == 0xE06D7363 ? EXCEPTION_CONTINUE_SEARCH : EXCEPTION_EXECUTE_HANDLER) { - } - return code == 0xE06D7363 ? 0 : code; -} - -std::string describe(const Call& c) { - if (!c.faulted) return "returned"; - if (c.code == kTerminateCalled) return "called TerminateProcess(exit code " + hex(c.arg) + ")"; - if (c.code == 0xE06D7363) - return std::string("threw a C++ exception ") + (c.cxx_type[0] ? c.cxx_type : "(type unknown)") + - (c.cxx_what[0] ? std::string(": \"") + c.cxx_what + "\"" : ""); - return "faulted with exception " + hex(c.code); -} - -void* symbol(rt::Module& m, const char* name) { - auto it = m.exports.find(name); - return it == m.exports.end() ? nullptr : it->second; -} - -// The D3D12 debug layer, when the Graphics Tools feature is installed, says why a PSO was rejected. -bool enable_debug_layer() { - ID3D12Debug* debug = nullptr; - if (FAILED(D3D12GetDebugInterface(IID_PPV_ARGS(&debug)))) return false; - debug->EnableDebugLayer(); - debug->Release(); - return true; -} - -void print_debug_messages(ID3D12Device* device) { - ID3D12InfoQueue* q = nullptr; - if (FAILED(device->QueryInterface(IID_PPV_ARGS(&q)))) return; - const UINT64 n = q->GetNumStoredMessages(); - for (UINT64 i = 0; i < n && i < 32; ++i) { - SIZE_T len = 0; - q->GetMessage(i, nullptr, &len); - std::vector buf(len); - auto* m = reinterpret_cast(buf.data()); - if (SUCCEEDED(q->GetMessage(i, m, &len))) std::printf(" d3d12 debug [%d]: %s\n", m->ID, m->pDescription); - } - q->ClearStoredMessages(); - q->Release(); -} - -// The first hardware adapter's PCI vendor ID, 0 when there is none. -UINT first_hardware_vendor() { - IDXGIFactory4* factory = nullptr; - if (FAILED(CreateDXGIFactory1(IID_PPV_ARGS(&factory)))) return 0; - UINT vendor = 0; - IDXGIAdapter1* adapter = nullptr; - for (UINT i = 0; !vendor && factory->EnumAdapters1(i, &adapter) != DXGI_ERROR_NOT_FOUND; ++i) { - DXGI_ADAPTER_DESC1 d{}; - adapter->GetDesc1(&d); - if (!(d.Flags & DXGI_ADAPTER_FLAG_SOFTWARE)) vendor = d.VendorId; - adapter->Release(); - } - factory->Release(); - return vendor; -} - -ID3D12Device* create_pc_device(bool warp) { - IDXGIFactory4* factory = nullptr; - if (FAILED(CreateDXGIFactory1(IID_PPV_ARGS(&factory)))) return nullptr; - IDXGIAdapter1* adapter = nullptr; - if (warp) { - factory->EnumWarpAdapter(IID_PPV_ARGS(&adapter)); - } else { - for (UINT i = 0; factory->EnumAdapters1(i, &adapter) != DXGI_ERROR_NOT_FOUND; ++i) { - DXGI_ADAPTER_DESC1 d{}; - adapter->GetDesc1(&d); - if (!(d.Flags & DXGI_ADAPTER_FLAG_SOFTWARE)) break; - adapter->Release(); - adapter = nullptr; - } - } - ID3D12Device* device = nullptr; - if (adapter) { - DXGI_ADAPTER_DESC1 d{}; - adapter->GetDesc1(&d); - std::printf("adapter: %ls\n", d.Description); - D3D12CreateDevice(adapter, D3D_FEATURE_LEVEL_12_0, IID_PPV_ARGS(&device)); - adapter->Release(); - } - factory->Release(); - return device; -} - -void print_slot_hits(const void* proxy) { - const unsigned n = rt::d3d12_xs::device_proxy_slot_count(proxy) + 32; - std::string dev, heap; - for (unsigned s = 0; s < n; ++s) - if (auto h = rt::d3d12_xs::device_slot_hits(s)) dev += " " + std::to_string(s) + "x" + std::to_string(h); - for (unsigned s = 0; s < 16; ++s) - if (auto h = rt::d3d12_xs::heap_slot_hits(s)) heap += " " + std::to_string(s) + "x" + std::to_string(h); - note("device slots hit (slot x count):" + (dev.empty() ? std::string(" none") : dev)); - note("descriptor-heap slots hit:" + (heap.empty() ? std::string(" none") : heap)); -} - -// Slot-62 recorder: the proxy's vtable is copied and slot 62 points here, so the raw argument words the DLL passes -// are printed before the proxy's own handler runs. Test-only; the proxy itself is unchanged. -using Slot62 = uint64_t(WINAPI*)(void*, uint64_t, uint64_t, uint64_t, uint64_t, uint64_t, uint64_t); -Slot62 g_slot62 = nullptr; -int g_slot62_logged = 0; - -bool looks_like_iid(uint64_t p, const IID& iid) { - __try { - return p && std::memcmp(reinterpret_cast(p), &iid, sizeof(IID)) == 0; - } __except (EXCEPTION_EXECUTE_HANDLER) { - return false; - } -} - -uint64_t g_slot62_ok = 0, g_slot62_failed = 0; - -// The shape of a DXBC container, for the record: its parts (four-character code and size), the DXIL part's shader -// model and DXIL version, the SFI0 feature flags, whether the hash is zero (unsigned), the ILDN module name and the -// first four bytes of the digest. Counts, flags and names only. -std::string container_shape(const void* bytecode, size_t length) { - const auto* b = static_cast(bytecode); - auto u32 = [&](size_t o) { - uint32_t v = 0; - if (o + 4 <= length) std::memcpy(&v, b + o, 4); - return v; - }; - if (!b || length < 32 || std::memcmp(b, "DXBC", 4) != 0) return "not a DXBC container"; - bool zero_hash = true; - for (int i = 4; i < 20; ++i) zero_hash &= b[i] == 0; - const uint32_t parts = u32(28); - std::string out = std::string(zero_hash ? "unsigned" : "signed") + ", " + std::to_string(parts) + " parts:"; - for (uint32_t i = 0; i < parts && 32 + 4 * size_t(i) + 4 <= length; ++i) { - const uint32_t off = u32(32 + 4 * size_t(i)); - if (size_t(off) + 8 > length) break; - const char fourcc[5] = {char(b[off]), char(b[off + 1]), char(b[off + 2]), char(b[off + 3]), 0}; - const uint32_t size = u32(off + 4); - char item[64]; - std::snprintf(item, sizeof(item), " %s:%u", fourcc, size); - out += item; - const size_t data = size_t(off) + 8; - if ((!std::strcmp(fourcc, "DXIL") || !std::strcmp(fourcc, "ILDB")) && size >= 24) { - const uint32_t version = u32(data), dxil = u32(data + 12); - std::snprintf(item, sizeof(item), "(sm %u.%u kind %u dxil %u.%u)", (version >> 4) & 0xf, version & 0xf, - version >> 16, (dxil >> 8) & 0xff, dxil & 0xff); - out += item; - } else if (!std::strcmp(fourcc, "SFI0") && size >= 8) { - std::snprintf(item, sizeof(item), "(flags %#llx)", - static_cast(u32(data) | (uint64_t(u32(data + 4)) << 32))); - out += item; - } else if (!std::strcmp(fourcc, "ILDN") && size >= 4) { - // ILDN: u16 flags, u16 name length, the debug name (NUL-padded): the module's PDB path, which names the - // container (docs/embedded_shaders.md section 3). Only the file name is printed. - const uint32_t name_length = u32(data) >> 16; - if (size_t(data) + 4 + name_length <= length && name_length > 0) { - std::string name(reinterpret_cast(b + data + 4), name_length); - name.erase(name.find_last_not_of('\0') + 1); - name = name.substr(name.find_last_of("\\/") + 1); - out += "(" + name + ")"; - } - } - } - // The first four bytes of the container digest (bytes 4..19 of the header), to tell two creations of the same - // container from two containers with the same module name. - char digest[24]; - std::snprintf(digest, sizeof(digest), " digest %02x%02x%02x%02x", b[4], b[5], b[6], b[7]); - return out + digest; -} - -// The module a container belongs to: the file name (without ".pdb") in its ILDN part, a DXIL debug-name record -// (u16 flags, u16 name length, then the PDB path). Empty when there is no such part. The module names are the ones -// listed in docs/embedded_shaders.md section 3. -std::string container_module(const void* bytecode, size_t length) { - const auto* b = static_cast(bytecode); - auto u32 = [&](size_t o) { - uint32_t v = 0; - if (o + 4 <= length) std::memcpy(&v, b + o, 4); - return v; - }; - if (!b || length < 32 || std::memcmp(b, "DXBC", 4) != 0) return {}; - const uint32_t parts = u32(28); - for (uint32_t i = 0; i < parts && 32 + 4 * size_t(i) + 4 <= length; ++i) { - const size_t off = u32(32 + 4 * size_t(i)); - if (off + 8 > length || std::memcmp(b + off, "ILDN", 4) != 0) continue; - const size_t size = u32(off + 4), data = off + 8; - if (size < 5 || data + size > length) return {}; - std::string path(reinterpret_cast(b + data + 4), size - 4); - path.resize(std::strlen(path.c_str())); - const size_t slash = path.find_last_of("\\/"); - std::string name = slash == std::string::npos ? path : path.substr(slash + 1); - if (name.size() > 4 && name.compare(name.size() - 4, 4, ".pdb") == 0) name.resize(name.size() - 4); - return name; - } - return {}; -} - -// Every container the constructor has passed to slot 62 so far, to find one that is passed twice (RT-182). The bytes -// are compared, not a hash, and nothing is printed from them. -std::vector> g_seen_containers; -std::vector g_seen_modules; -int g_repeat_first = 0, g_repeat_second = 0; // creation numbers (1-based) of the first repeat found, 0 = none -int g_repeats = 0; - -// LEONIDA_BVH_DXIL=1: what each shader uses, from dxcompiler.dll's disassembly in memory: the distinct dx.op names -// with call counts, and a few type/feature markers. Also dxil.dll's validator verdict. Names and counts only; the -// disassembly is not printed or written. The DLLs come from PATH or the Windows SDK, loaded at run time. -struct DxcTools { - IDxcCompiler* compiler = nullptr; - IDxcLibrary* library = nullptr; - IDxcValidator* validator = nullptr; -}; - -DxcTools* dxc_tools() { - static DxcTools tools; - static bool tried = false; - if (tried) return tools.compiler ? &tools : nullptr; - tried = true; - HMODULE compiler = LoadLibraryA("dxcompiler.dll"); - HMODULE validator = LoadLibraryA("dxil.dll"); - auto create = [](HMODULE m) { - return m ? reinterpret_cast(GetProcAddress(m, "DxcCreateInstance")) : nullptr; - }; - if (auto f = create(compiler)) { - f(CLSID_DxcCompiler, IID_PPV_ARGS(&tools.compiler)); - f(CLSID_DxcLibrary, IID_PPV_ARGS(&tools.library)); - } - if (auto f = create(validator)) f(CLSID_DxcValidator, IID_PPV_ARGS(&tools.validator)); - if (!tools.compiler || !tools.library) note("LEONIDA_BVH_DXIL: dxcompiler.dll not found on PATH"); - if (!tools.validator) note("LEONIDA_BVH_DXIL: dxil.dll not found on PATH (no validator verdict)"); - return tools.compiler && tools.library ? &tools : nullptr; -} - -std::string dxil_usage(const void* bytecode, size_t length) { - DxcTools* t = dxc_tools(); - if (!t) return "no dxcompiler"; - const std::vector copy(static_cast(bytecode), static_cast(bytecode) + length); - IDxcBlobEncoding* blob = nullptr; - if (FAILED(t->library->CreateBlobWithEncodingFromPinned(copy.data(), static_cast(copy.size()), 0, &blob))) - return "no blob"; - std::string out; - if (t->validator) { - IDxcOperationResult* result = nullptr; - HRESULT status = E_FAIL; - if (SUCCEEDED(t->validator->Validate(blob, DxcValidatorFlags_Default, &result)) && result) - result->GetStatus(&status); - out += std::string("validator ") + (SUCCEEDED(status) ? "ok" : "rejects (" + hex(uint32_t(status)) + ")"); - // The kinds of error with their counts. Quoted text (names, triples, instructions) is masked as 'X', and - // anything after the message's first sentence is dropped, so nothing of the shader is printed. - IDxcBlobEncoding* errors = nullptr; - if (result && FAILED(status) && SUCCEEDED(result->GetErrorBuffer(&errors)) && errors) { - const std::string m(static_cast(errors->GetBufferPointer()), errors->GetBufferSize()); - std::vector> kinds; - for (size_t p = m.find("error: "); p != std::string::npos; p = m.find("error: ", p + 1)) { - std::string kind; - bool quoted = false; - for (size_t i = p + 7; i < m.size(); ++i) { - const char ch = m[i]; - if (ch == '\n' || (ch == '.' && !quoted)) break; // the first sentence; dots in names don't end it - if (ch == '\'') { - if (!quoted) kind += "'X'"; - quoted = !quoted; - } else if (!quoted) { - kind += ch; - } - } - auto it = std::find_if(kinds.begin(), kinds.end(), [&](auto& k) { return k.first == kind; }); - if (it == kinds.end()) kinds.push_back({kind, 1}); else ++it->second; - } - for (auto& [kind, n] : kinds) out += "; " + kind + " x" + std::to_string(n); - errors->Release(); - } - if (result) result->Release(); - } - IDxcBlobEncoding* text = nullptr; - if (SUCCEEDED(t->compiler->Disassemble(blob, &text)) && text) { - const std::string s(static_cast(text->GetBufferPointer()), text->GetBufferSize()); - std::vector> ops; - for (size_t p = s.find("@dx.op."); p != std::string::npos; p = s.find("@dx.op.", p + 1)) { - const size_t line = s.rfind('\n', p); - const size_t call = s.find(" call ", line == std::string::npos ? 0 : line); - if (call == std::string::npos || call > p) continue; // a declaration, not a call - const size_t end = s.find_first_of(".(", p + 7); - const std::string name = s.substr(p + 7, end - p - 7); - auto it = std::find_if(ops.begin(), ops.end(), [&](auto& o) { return o.first == name; }); - if (it == ops.end()) ops.push_back({name, 1}); else ++it->second; - } - auto count = [&](const char* needle) { - int n = 0; - for (size_t p = s.find(needle); p != std::string::npos; p = s.find(needle, p + 1)) ++n; - return n; - }; - out += ", " + std::to_string(s.size() / 1024) + " KiB of text, lines " + std::to_string(count("\n")); - out += ", i64 " + std::to_string(count(" i64 ")) + ", half " + std::to_string(count(" half ")) + - ", double " + std::to_string(count(" double ")) + ", phi " + std::to_string(count(" phi ")) + - ", switch " + std::to_string(count(" switch ")) + ", br " + std::to_string(count(" br ")) + - ", alloca " + std::to_string(count(" alloca ")) + ", groupshared " + std::to_string(count("addrspace(3)")) + - ", undef " + std::to_string(count(" undef")) + "; ops:"; - for (auto& [name, n] : ops) out += " " + name + "x" + std::to_string(n); - text->Release(); - } - blob->Release(); - return out; -} - -// RT-266: where each creation comes from and which name the builder attaches to the PSO it gets back. The call -// site is the stack of the hook as offsets from the DLL's image base, each with the start of its function from the -// x64 unwind tables (RtlLookupFunctionEntry); the name is whatever the builder passes to the returned object's -// SetName (ID3D12Object slot 6) or SetPrivateData (slot 4) with the D3D debug-name GUIDs. The returned object gets a -// copy of its vtable with those two slots redirected (the creation number is looked up by object pointer). -uint64_t g_bvh_base = 0, g_bvh_size = 0; - -std::string module_offset(uint64_t addr) { - if (!g_bvh_base || addr < g_bvh_base || addr >= g_bvh_base + g_bvh_size) { - char b[40]; - std::snprintf(b, sizeof b, "outside the DLL (%#llx)", (unsigned long long)addr); - return b; - } - char b[96]; - DWORD64 image = 0; - const RUNTIME_FUNCTION* rf = RtlLookupFunctionEntry(addr, &image, nullptr); - if (rf) - std::snprintf(b, sizeof b, "+%#llx (function +%#lx)", (unsigned long long)(addr - g_bvh_base), - (unsigned long)rf->BeginAddress); - else - std::snprintf(b, sizeof b, "+%#llx (no unwind entry)", (unsigned long long)(addr - g_bvh_base)); - return b; -} - -void print_call_site(int number) { - // Unwound by hand with the x64 tables: RtlCaptureStackBackTrace stops after the first DLL frame here. - CONTEXT ctx; - RtlCaptureContext(&ctx); - unsigned printed = 0; - for (int step = 0; step < 12 && printed < 6; ++step) { - DWORD64 image = 0; - const RUNTIME_FUNCTION* rf = RtlLookupFunctionEntry(ctx.Rip, &image, nullptr); - if (!rf) break; - void* handler_data = nullptr; - DWORD64 frame = 0; - RtlVirtualUnwind(UNW_FLAG_NHANDLER, image, ctx.Rip, const_cast(rf), &ctx, &handler_data, - &frame, nullptr); - if (!ctx.Rip) break; - const auto addr = static_cast(ctx.Rip); - if (addr < g_bvh_base || addr >= g_bvh_base + g_bvh_size) continue; // this test's own frames - std::printf(" slot62 #%d call site frame %u: %s\n", number, printed++, module_offset(addr).c_str()); - } -} - -struct PsoName { - int number; - void* object; - void** original_vtable; - bool restored; - void** vtable_copy; // the hooked copy installed on the object; freed once the original is back -}; -std::vector g_pso_names; -std::set g_named; // creation numbers that got a name -thread_local bool g_in_set_name = false; - -// The newest live entry for the address (an address can be reused after a PSO is released). -PsoName* find_pso(void* object) { - for (auto it = g_pso_names.rbegin(); it != g_pso_names.rend(); ++it) - if (!it->restored && it->object == object) return &*it; - return nullptr; -} - -// Puts the object's own vtable back, so its destructor and every virtual call past the 9 copied slots see the -// original. Done as soon as the name is logged, and for the rest after the constructor returns. -void restore_pso_vtable(PsoName& p) { - if (p.restored) return; - p.restored = true; - __try { - *static_cast(p.object) = p.original_vtable; - } __except (EXCEPTION_EXECUTE_HANDLER) { - } - // The thunks that call this have already been dispatched through the copy and read only the original vtable - // afterwards; find_pso skips restored entries, so nothing reads the copy past this point. - delete[] p.vtable_copy; - p.vtable_copy = nullptr; - // Drops the reference hook_pso_names took; the builder still holds its own here, so this cannot free the object. - using ReleaseFn = ULONG(STDMETHODCALLTYPE*)(void*); - reinterpret_cast(p.original_vtable[2])(p.object); -} - -void restore_all_pso_vtables() { - for (auto& p : g_pso_names) restore_pso_vtable(p); -} - -std::string narrow(const wchar_t* w) { - std::string s; - for (; w && *w && s.size() < 200; ++w) s += *w < 0x80 ? char(*w) : '?'; - return s; -} - -constexpr GUID kDebugNameW = {0x4cca5fd8, 0x921f, 0x42c8, {0x85, 0x66, 0x70, 0xca, 0xf2, 0xa9, 0xb7, 0x41}}; -constexpr GUID kDebugNameA = {0x429b8c22, 0x9188, 0x4b0c, {0x87, 0x42, 0xac, 0xb0, 0xbf, 0x85, 0xc2, 0x00}}; - -HRESULT STDMETHODCALLTYPE pso_set_name(void* self, const wchar_t* name) { - if (auto* p = find_pso(self)) { - std::printf(" slot62 #%d name via SetName: \"%s\"\n", p->number, narrow(name).c_str()); - g_named.insert(p->number); - using Fn = HRESULT(STDMETHODCALLTYPE*)(void*, const wchar_t*); - g_in_set_name = true; // the runtime's SetName may call SetPrivateData through the vtable - const HRESULT hr = reinterpret_cast(p->original_vtable[6])(self, name); - g_in_set_name = false; - restore_pso_vtable(*p); - return hr; - } - return E_FAIL; -} - -HRESULT STDMETHODCALLTYPE pso_set_private_data(void* self, const GUID& guid, UINT size, const void* data) { - if (auto* p = find_pso(self)) { - if (g_in_set_name) { - using Fn = HRESULT(STDMETHODCALLTYPE*)(void*, const GUID&, UINT, const void*); - return reinterpret_cast(p->original_vtable[4])(self, guid, size, data); - } - char g[48]; - std::snprintf(g, sizeof g, "%08lx-%04x-%04x", guid.Data1, guid.Data2, guid.Data3); - std::string value; - if (data && size) { - if (!std::memcmp(&guid, &kDebugNameW, sizeof(GUID))) - value = narrow(std::wstring(static_cast(data), size / 2).c_str()); - else if (!std::memcmp(&guid, &kDebugNameA, sizeof(GUID))) - value = std::string(static_cast(data), size); - } - std::printf(" slot62 #%d SetPrivateData guid %s size %u%s%s%s\n", p->number, g, size, - value.empty() ? "" : " name \"", value.c_str(), value.empty() ? "" : "\""); - if (!value.empty()) g_named.insert(p->number); - using Fn = HRESULT(STDMETHODCALLTYPE*)(void*, const GUID&, UINT, const void*); - const HRESULT hr = reinterpret_cast(p->original_vtable[4])(self, guid, size, data); - if (!value.empty()) restore_pso_vtable(*p); - return hr; - } - return E_FAIL; -} - -void hook_pso_names(uint64_t out_ptr, int number) { - void* object = nullptr; - __try { - if (out_ptr) object = *reinterpret_cast(out_ptr); - } __except (EXCEPTION_EXECUTE_HANDLER) { - object = nullptr; - } - if (!object) { - std::printf(" slot62 #%d: no object at a5\n", number); - return; - } - constexpr unsigned kSlots = 9; // IUnknown, ID3D12Object, GetDevice, GetCachedBlob - void** orig = *static_cast(object); - auto** copy = new void*[kSlots]; - std::memcpy(copy, orig, kSlots * sizeof(void*)); - copy[4] = reinterpret_cast(&pso_set_private_data); - copy[6] = reinterpret_cast(&pso_set_name); - // Hold a reference until the vtable is restored, so the later write-back never lands in freed memory. - using AddRefFn = ULONG(STDMETHODCALLTYPE*)(void*); - reinterpret_cast(orig[1])(object); - g_pso_names.push_back({number, object, orig, false, copy}); - *static_cast(object) = copy; -} - -uint64_t WINAPI record_slot62(void* self, uint64_t a1, uint64_t a2, uint64_t a3, uint64_t a4, uint64_t a5, uint64_t a6) { - const int n = g_slot62_logged++; - if (n < 1) { - std::printf(" slot62 args: a1=%#llx a2=%#llx a3=%#llx a4=%#llx a5=%#llx a6=%#llx\n", - (unsigned long long)a1, (unsigned long long)a2, (unsigned long long)a3, (unsigned long long)a4, - (unsigned long long)a5, (unsigned long long)a6); - const uint64_t args[] = {a1, a2, a3, a4, a5, a6}; - for (int i = 0; i < 6; ++i) - if (looks_like_iid(args[i], __uuidof(ID3D12PipelineState))) - std::printf(" slot62: a%d points at IID_ID3D12PipelineState\n", i + 1); - } - const auto* desc = reinterpret_cast(a1); - // Printed before the call: a driver that rejects the shader may end the process inside it. - if (desc) { - std::printf(" slot62 #%d container: %s\n", n + 1, - container_shape(desc->CS.pShaderBytecode, desc->CS.BytecodeLength).c_str()); - const std::string module = container_module(desc->CS.pShaderBytecode, desc->CS.BytecodeLength); - std::printf(" slot62 #%d module: %s\n", n + 1, module.empty() ? "(no ILDN part)" : module.c_str()); - const auto* bytes = static_cast(desc->CS.pShaderBytecode); - std::vector copy(bytes, bytes + desc->CS.BytecodeLength); - int same_as = 0; - for (size_t i = 0; i < g_seen_containers.size(); ++i) - if (g_seen_containers[i] == copy) { - same_as = static_cast(i) + 1; - break; - } - if (same_as) { - std::printf(" slot62 #%d is byte-identical to #%d (module %s)\n", n + 1, same_as, - g_seen_modules[same_as - 1].c_str()); - if (!g_repeats) { - g_repeat_first = same_as; - g_repeat_second = n + 1; - } - ++g_repeats; - } - g_seen_containers.push_back(std::move(copy)); - g_seen_modules.push_back(module); - if (env("LEONIDA_BVH_DXIL") == "1") - std::printf(" slot62 #%d uses: %s\n", n + 1, dxil_usage(desc->CS.pShaderBytecode, desc->CS.BytecodeLength).c_str()); - } - print_call_site(n + 1); - const uint64_t r = g_slot62(self, a1, a2, a3, a4, a5, a6); - const auto hr = static_cast(static_cast(r)); - (SUCCEEDED(hr) ? g_slot62_ok : g_slot62_failed)++; - // The output slot is a5 (desc, two words, riid, out); the object it receives is the one the builder names. - if (SUCCEEDED(hr)) hook_pso_names(a5, n + 1); - std::printf(" slot62 #%d: CS bytecode %llu bytes, root signature %s, node mask %u, flags %#x -> hr %#010lx\n", n + 1, - desc ? (unsigned long long)desc->CS.BytecodeLength : 0ull, desc && desc->pRootSignature ? "set" : "null", - desc ? desc->NodeMask : 0u, desc ? (unsigned)desc->Flags : 0u, static_cast(hr)); - return r; -} - -void** g_proxy_vtable_copy = nullptr; -bool hook_slot62(void* proxy, unsigned slots) { - void** vtable = *static_cast(proxy); - g_proxy_vtable_copy = new void*[slots]; - std::memcpy(g_proxy_vtable_copy, vtable, slots * sizeof(void*)); - g_slot62 = reinterpret_cast(vtable[62]); - g_proxy_vtable_copy[62] = reinterpret_cast(&record_slot62); - *static_cast(proxy) = g_proxy_vtable_copy; - return true; -} - -constexpr const char* kCtor = "??0XboxBvhBuilder@@QEAA@PEAUID3D12Device11@@_N@Z"; -constexpr const char* kDtor = "??1XboxBvhBuilder@@QEAA@XZ"; -constexpr size_t kObjectBuffer = 1u << 20; -constexpr uint8_t kSentinel = 0xCD; - -// The module's TLS index, whichever loader this builds against: #95 records a slot (has_tls_slot/tls_slot), #93 -// a module TLS index (tls_index, kNoTlsIndex when there is none). ~0u means no TLS. -template -auto module_tls_index(const M& m, int) -> decltype(m.tls_index, uint32_t()) { return m.tls_index; } -template -auto module_tls_index(const M& m, long) -> decltype(m.tls_slot, uint32_t()) { return m.has_tls_slot ? m.tls_slot : ~0u; } - -} // namespace - -int main() { - std::setvbuf(stdout, nullptr, _IONBF, 0); // keep every line if the DLL takes the process down - const std::string game_dir_arg = env("LEONIDA_GAME_DIR"); - if (game_dir_arg.empty()) { - std::printf("SKIP (no package)\n"); - return 77; - } - const std::filesystem::path game_dir = game_dir_arg; - const std::filesystem::path dll = game_dir / "XboxBvhBuilder.dll"; - std::error_code ec; - if (!std::filesystem::is_regular_file(dll, ec)) { - std::printf("FAIL LEONIDA_GAME_DIR does not contain XboxBvhBuilder.dll\n"); - return 1; - } - - try { - rt::Loader loader(game_dir); - rt::Module& bvh = loader.load(dll); - std::printf("mapped %s at %p, size %u, entry +%#x%s\n", bvh.name.c_str(), bvh.base, bvh.size, - bvh.entry_rva, bvh.relocated ? " (relocated)" : ""); - g_bvh_base = reinterpret_cast(bvh.base); - g_bvh_size = bvh.size; - int shim = 0, host = 0, unimplemented = 0; - for (auto& r : bvh.imports) { - if (r.binding == rt::Binding::Shim) ++shim; - if (r.binding == rt::Binding::Host) ++host; - if (r.binding == rt::Binding::Unimplemented) { - ++unimplemented; - std::printf(" UNIMPLEMENTED %s!%s\n", r.dll.c_str(), r.name.c_str()); - } - const std::string d = rt::lower(r.dll); - if (d == "xmem.dll" || d == "d3d12_xs.dll") - check(r.binding == rt::Binding::Shim, r.dll + "!" + r.name + " binds to the shim"); - } - std::printf("imports: shim=%d host=%d unimplemented=%d\n", shim, host, unimplemented); - check(unimplemented == 0, "no unimplemented imports"); - - auto ctor = reinterpret_cast(symbol(bvh, kCtor)); - auto dtor = reinterpret_cast(symbol(bvh, kDtor)); - check(ctor && dtor, "constructor and destructor are exported"); - check(patch(iat_slot(bvh, "api-ms-win-core-debug-l1-1-0.dll", "OutputDebugStringA"), reinterpret_cast(&debug_a)) && - patch(iat_slot(bvh, "api-ms-win-core-debug-l1-1-0.dll", "OutputDebugStringW"), reinterpret_cast(&debug_w)) && - patch(iat_slot(bvh, "api-ms-win-core-processthreads-l1-1-0.dll", "TerminateProcess"), - reinterpret_cast(&terminate_stub)), - "OutputDebugStringA/W and TerminateProcess redirected in this DLL's IAT"); - if (g_failures) return 1; - - check(ensure_unwind_registered(bvh), "x64 unwind tables registered (by the loader or here)"); - const DWORD init = guarded_initialise(&loader); - check(init == 0, "Loader::initialise (TLS, DllMain) succeeds" + (init ? " (exception " + hex(init) + ")" : "")); - if (init) return 1; - const uint32_t tls = module_tls_index(bvh, 0); - std::printf("TLS: %s index %u\n", tls != ~0u ? "loader" : "no", tls); - - ID3D12Device* pc = nullptr; - const bool on_vulkan = env("LEONIDA_BVH_DEVICE") == "vulkan"; - if (on_vulkan) { -#ifdef LEONIDA_VULKAN_DEVICE - // The Vulkan-backed ID3D12Device (#119) instead of the host's D3D12 device, behind the same proxy. - const HRESULT vhr = rt::d3d12::create_vulkan_device_standalone(__uuidof(ID3D12Device), reinterpret_cast(&pc)); - check(SUCCEEDED(vhr) && pc, "Vulkan-backed D3D12 device created (" + hex(static_cast(vhr)) + ")"); -#else - check(false, "LEONIDA_BVH_DEVICE=vulkan needs a build with the Vulkan SDK (gta6rt_d3d12_com)"); -#endif - } else { - const bool debug_layer = enable_debug_layer(); - note(std::string("D3D12 debug layer ") + (debug_layer ? "enabled" : "not available (Graphics Tools not installed)")); - // RT-54: the package's shaders are Xbox DXIL (target triple dxil-ms-xb2), which no PC driver has to - // accept. NVIDIA's DXIL reader rejects one of them (the 49th CreateComputePipelineState, the only one - // with a resource in a function signature) and can end the process inside the driver (0xC0000409) - // instead of returning an error, so the constructor can't be measured there. AMD faults the same way - // (0xC0000005 right after the first slot 62 call on an RX 7900 XTX, RT-89). WARP accepts all 53, so it is - // the default on every hardware vendor; LEONIDA_BVH_HARDWARE=1 keeps the hardware device, to check a - // newer driver. - bool warp = env("LEONIDA_BVH_WARP") == "1"; - if (!warp && env("LEONIDA_BVH_HARDWARE") != "1") { - if (const UINT vendor = first_hardware_vendor()) { - char id[8]; - std::snprintf(id, sizeof id, "%04x", vendor); - note(std::string("hardware adapter (vendor ") + id + "): using WARP, since hardware DXIL readers " - "reject the DLL's Xbox DXIL shaders and can end the process (RT-54 NVIDIA, RT-89 AMD); " - "LEONIDA_BVH_HARDWARE=1 keeps the hardware device"); - } - warp = true; - } - pc = create_pc_device(warp); - check(pc != nullptr, "PC D3D12 device created"); - } - if (!pc) return 1; - if (!on_vulkan) { - // The proxy answers ID3D12Device11 with a QueryInterface on the host device. The Windows 10 runtime - // without the Agility SDK stops before ID3D12Device11, on hardware and WARP alike (#688). - ID3D12Device11* host11 = nullptr; - if (FAILED(pc->QueryInterface(IID_PPV_ARGS(&host11))) || !host11) { - std::printf("SKIP (the host D3D12 runtime has no ID3D12Device11, e.g. Windows 10 without the Agility " - "SDK; LEONIDA_BVH_DEVICE=vulkan runs on the Vulkan-backed device)\n"); - pc->Release(); - return g_failures ? 1 : 0; - } - host11->Release(); - } - pc->AddRef(); // kept for the debug messages; the proxy takes its own reference - void* proxy = nullptr; - const HRESULT hr = rt::d3d12_xs::create_device_proxy(pc, __uuidof(ID3D12Device11), &proxy); - check(SUCCEEDED(hr) && proxy, "Xbox-ABI device proxy created as ID3D12Device11 (" + hex(static_cast(hr)) + ")"); - if (!proxy) return 1; -#ifdef LEONIDA_VULKAN_DEVICE - if (on_vulkan) rt::d3d12::set_device_outer(pc, static_cast(proxy)); -#endif - rt::d3d12_xs::reset_device_proxy_stats(); - if (env("LEONIDA_BVH_RECORD62") == "1") - check(hook_slot62(proxy, rt::d3d12_xs::device_proxy_slot_count(proxy)), "slot 62 recorder installed"); - - const bool flag = env("LEONIDA_BVH_FLAG") == "1"; - std::vector object(kObjectBuffer, kSentinel); - const ULONGLONG t0 = GetTickCount64(); - Call c = guarded_ctor(ctor, object.data(), proxy, flag); - restore_all_pso_vtables(); // PSOs never named keep the copy until here (RT-266) - const ULONGLONG ms = GetTickCount64() - t0; - size_t last = 0, changed = 0; - for (size_t i = 0; i < object.size(); ++i) - if (object[i] != kSentinel) { - last = i + 1; - ++changed; - } - note(std::string("XboxBvhBuilder(device, ") + (flag ? "true" : "false") + ") " + describe(c) + " after " + - std::to_string(ms) + " ms"); - note("object bytes written: up to offset " + hex(last) + " (" + std::to_string(changed) + - " bytes differ from the sentinel): sizeof(XboxBvhBuilder) >= " + std::to_string(last)); - print_slot_hits(proxy); - print_debug_messages(pc); - note("slot 62 (Xbox CreateComputePipelineState) calls: " + std::to_string(rt::d3d12_xs::device_slot_hits(62)) + - (g_slot62_logged ? ", succeeded " + std::to_string(g_slot62_ok) + ", failed " + std::to_string(g_slot62_failed) - : std::string())); - if (g_slot62_logged) { - note("slot 62 creations given a name by the builder: " + std::to_string(g_named.size()) + " of " + - std::to_string(g_slot62_logged)); - note("slot 62 creations: " + std::to_string(g_slot62_logged) + ", distinct containers: " + - std::to_string(g_slot62_logged - g_repeats) + ", repeated creations: " + std::to_string(g_repeats)); - if (g_repeats) { - note("first repeat: creation #" + std::to_string(g_repeat_second) + " passes the same container as #" + - std::to_string(g_repeat_first) + ", module " + g_seen_modules[g_repeat_first - 1]); - check(g_seen_modules[g_repeat_first - 1] == g_seen_modules[g_repeat_second - 1], - "the repeated container names the same module both times"); - } - } - note("OutputDebugString calls: " + std::to_string(g_debug_strings) + ", TerminateProcess calls: " + - std::to_string(g_terminate_calls)); - check(!c.faulted || c.code == kTerminateCalled, "constructor returns or gives up through TerminateProcess, no fault"); - - if (!c.faulted) { - rt::d3d12_xs::reset_device_proxy_stats(); - c = guarded_dtor(dtor, object.data()); - note("~XboxBvhBuilder " + describe(c)); - print_slot_hits(proxy); - check(!c.faulted, "destructor returns"); - } - reinterpret_cast(proxy)->Release(); - pc->Release(); - } catch (const std::exception& e) { - std::printf("FAIL %s\n", e.what()); - return 1; - } - - std::printf("bvh_builder_test: %s (%d failure%s)\n", g_failures ? "FAILED" : "OK", g_failures, - g_failures == 1 ? "" : "s"); - return g_failures ? 1 : 0; -} diff --git a/runtime/test/check_argv_modes.py b/runtime/test/check_argv_modes.py deleted file mode 100644 index 649ab2f97..000000000 --- a/runtime/test/check_argv_modes.py +++ /dev/null @@ -1,138 +0,0 @@ -"""Compare real MSVC argv startup modes natively and through the PE loader. - -Each fixture is linked with the default, setargv/wsetargv, or noarg option. -Raw Windows command lines retain quoted wildcard cases and identical argv[0]. -All files are synthetic; the active code page's native result is the oracle. -""" - -import argparse -import ctypes -import json -import os -from pathlib import Path -import re -import subprocess -import tempfile - - -def run(executable, command, cwd, environment): - result = subprocess.run( - command, executable=executable, cwd=cwd, env=environment, - capture_output=True, timeout=15, - ) - output = result.stdout.decode("utf-8", "replace") - return { - "command": command, - "exit_code": result.returncode, - "lines": [line for line in output.splitlines() - if line.startswith(("STATE ", "NOOP ", "CONFIG "))], - "stdout": output, - "stderr": result.stderr.decode("utf-8", "replace"), - } - - -def entry_count(lines): - if not lines: - return None - match = re.fullmatch(r"STATE entry argc=(\d+) A=.* W=.*", lines[0]) - return int(match[1]) if match else None - - -def main(): - parser = argparse.ArgumentParser(description=__doc__) - parser.add_argument("--loader", type=Path, required=True) - parser.add_argument("--fixtures", type=Path, required=True) - parser.add_argument("--work-dir", type=Path, required=True) - parser.add_argument("--report", type=Path, help="optional retained JSON evidence") - args = parser.parse_args() - if os.name != "nt": - parser.error("this native MSVC startup comparison requires Windows") - loader = args.loader.resolve(strict=True) - fixtures = args.fixtures.resolve(strict=True) - work_dir = args.work_dir.resolve(strict=True) - rows = [] - failures = [] - tails = { - "plain": "data/*.txt literal", - "quoted": '"data/*.txt" literal', - "unmatched": "data/*.missing literal", - "empty": "empty/* literal", - "space": '"space dir/*.txt" literal', - "encoding": "unicode/\u6f22*.txt literal", - "sequence": "data/*.txt literal", - } - with tempfile.TemporaryDirectory(prefix="argv_modes_", dir=work_dir) as temporary: - root = Path(temporary) - for directory in ("data", "empty", "space dir", "unicode", "package"): - (root / directory).mkdir() - for name in ("data/a.txt", "data/b.txt", "data/c.bin", - "space dir/a.txt", "space dir/b.txt", - "unicode/A-only.txt", "unicode/\u6f22-only.txt"): - (root / name).write_text("synthetic\n", encoding="utf-8", newline="\n") - for width in ("a", "w"): - for mode in ("default", "expand", "noargs"): - guest = (fixtures / f"tiny_argv_{mode}_{width}.exe").resolve(strict=True) - cases = ["plain", "quoted", "unmatched"] - if mode == "expand": - cases += ["empty", "space", "encoding"] - if mode == "noargs": - cases += ["sequence"] - native_plain = None - for case in cases: - label = f"{width}/{mode}/{case}" - environment = os.environ.copy() - environment.pop("LEONIDA_GAME_DIR", None) - environment.pop("LEONIDA_ARGV_SEQUENCE", None) - if case == "sequence": - environment["LEONIDA_ARGV_SEQUENCE"] = "1" - native_command = subprocess.list2cmdline([guest.name]) + " " + tails[case] - mapped_command = subprocess.list2cmdline([ - loader.name, "--run", str(guest), "--game-dir", str(root / "package"), - "--overlay", str(root / "overlay"), - ]) + " -- " + tails[case] - native = run(guest, native_command, root, environment) - mapped = run(loader, mapped_command, root, environment) - problems = [] - for route, result in (("native", native), ("mapped", mapped)): - if result["exit_code"] != 0 or entry_count(result["lines"]) is None: - problems.append(f"{route} did not complete its fixture") - expected = 0 if mode == "noargs" else 3 - if mode == "expand" and case in ("plain", "quoted", "space"): - expected = 4 - if case != "encoding" and case != "empty": - if entry_count(native["lines"]) != expected: - problems.append(f"native fixture did not produce argc={expected}") - if mode == "noargs" and native["lines"] and native["lines"][0] != "STATE entry argc=0 A=null W=null": - problems.append("native noarg fixture did not start unconfigured") - if case == "plain": - native_plain = native["lines"] - if case == "quoted" and native["lines"] != native_plain: - problems.append("native quoted wildcard differs from unquoted") - if case == "sequence": - noops = [line for line in native["lines"] if line.startswith("NOOP ")] - configs = [line for line in native["lines"] if line.startswith("CONFIG ")] - if len(noops) != 6 or any(not line.endswith("status=0 unchanged=1") for line in noops): - problems.append("native no-argument reconfiguration changed state") - if len(configs) != 4 or any(not line.endswith("status=0") for line in configs): - problems.append("native reconfiguration did not succeed") - if native["lines"] != mapped["lines"]: - problems.append("mapped argv state differs from native") - if "game exited with code 0" not in mapped["stdout"]: - problems.append("loader did not report a completed guest run") - if problems: - failures.append(label + ": " + "; ".join(problems)) - print("FAIL " + failures[-1], flush=True) - print(" native: " + repr(native["lines"]), flush=True) - print(" mapped: " + repr(mapped["lines"]), flush=True) - rows.append({"case": label, "native": native, "mapped": mapped, "problems": problems}) - if any((root / "package").iterdir()): - failures.append("the synthetic package was modified") - report = {"acp": ctypes.windll.kernel32.GetACP(), "pairs": len(rows), "failures": failures, "rows": rows} - if args.report: - args.report.write_text(json.dumps(report, indent=2) + "\n", encoding="utf-8", newline="\n") - print(f"argv modes: {len(rows)} native/mapped pairs, {len(failures)} failures, ACP {report['acp']}") - return int(bool(failures)) - - -if __name__ == "__main__": - raise SystemExit(main()) diff --git a/runtime/test/check_atexit.cmake b/runtime/test/check_atexit.cmake deleted file mode 100644 index 255bb3a4f..000000000 --- a/runtime/test/check_atexit.cmake +++ /dev/null @@ -1,71 +0,0 @@ -# atexit handlers, static destructors and every way out: tiny_atexit run through `gta6rt --run` must print the -# sequence written below and end with its exit code. That is what the program does natively on Windows, and the -# native run is held to the same sequence, so the two cannot agree on a wrong answer. Under Wine both runs go through -# RUNNER, and Wine's own CRT differs in places (it drops a handler registered while handlers run, and its _exit does -# not wait for the exit lock), so there a native difference is reported without failing; --run is still held to the -# Windows sequence. -get_filename_component(guest_dir "${GUEST}" DIRECTORY) -get_filename_component(guest_name "${GUEST}" NAME) - -set(ctors "ctor first;ctor second;main") -set(handlers "atexit two;atexit registers late;atexit late;atexit one;dtor second;dtor first") -set(expect_return "${ctors};${handlers}") -set(code_return 3) -set(expect_exit "${ctors};${handlers}") -set(code_exit 7) -set(expect__exit "${ctors}") -set(code__exit 8) -set(expect_quick_exit "${ctors}") -set(code_quick_exit 9) -set(expect_ExitProcess "${ctors}") -set(code_ExitProcess 10) -set(expect_cexit "${ctors};${handlers};after _cexit") -set(code_cexit 11) -set(expect_c_exit "${ctors};after _c_exit;${handlers}") -set(code_c_exit 12) -# exit(7) is running a slow handler when a second thread calls _exit(7): the exit lock holds it back. -set(expect_concurrent_exit "${ctors};slow handler started;slow handler done;${handlers}") -set(code_concurrent_exit 7) - -# The program's own lines, in order, without the prefix; everything gta6rt prints is dropped. -function(guest_lines output result) - string(REPLACE "\r\n" "\n" output "${output}") - string(REPLACE ";" "," output "${output}") - string(REPLACE "\n" ";" output "${output}") - set(lines) - foreach(line IN LISTS output) - if(line MATCHES "^tiny_atexit: (.*)$") - list(APPEND lines "${CMAKE_MATCH_1}") - endif() - endforeach() - set(${result} "${lines}" PARENT_SCOPE) -endfunction() - -set(failures "") -foreach(mode return exit _exit quick_exit ExitProcess cexit c_exit concurrent_exit) - execute_process(COMMAND ${RUNNER} "${GUEST}" ${mode} - WORKING_DIRECTORY "${guest_dir}" TIMEOUT 60 - RESULT_VARIABLE native_code OUTPUT_VARIABLE native_out ERROR_VARIABLE native_err) - execute_process(COMMAND ${RUNNER} "${LOADER}" --run "${guest_name}" -- ${mode} - WORKING_DIRECTORY "${guest_dir}" TIMEOUT 60 - RESULT_VARIABLE run_code OUTPUT_VARIABLE run_out ERROR_VARIABLE run_err) - guest_lines("${native_out}" native_lines) - guest_lines("${run_out}" run_lines) - if(NOT native_code STREQUAL code_${mode} OR NOT native_lines STREQUAL expect_${mode}) - string(CONCAT native_diff "[${mode}] native run differs from the expected sequence" - "\n expected (${code_${mode}}): ${expect_${mode}}\n native (${native_code}): ${native_lines}") - if(RUNNER) - message(STATUS "${native_diff}\n (the host CRT differs from Windows; not a gta6rt failure)") - else() - string(APPEND failures "\n${native_diff}\n (the fixture or the host changed)") - endif() - endif() - if(NOT run_code STREQUAL code_${mode} OR NOT run_lines STREQUAL expect_${mode}) - string(APPEND failures "\n[${mode}] gta6rt --run differs from the expected sequence" - "\n expected (${code_${mode}}): ${expect_${mode}}\n --run (${run_code}): ${run_lines}\n${run_err}") - endif() -endforeach() -if(failures) - message(FATAL_ERROR "atexit/termination differences:${failures}") -endif() -message(STATUS "tiny_atexit: 8 termination paths match the Windows sequence") diff --git a/runtime/test/check_console_paths.cmake b/runtime/test/check_console_paths.cmake deleted file mode 100644 index bdd74a7d1..000000000 --- a/runtime/test/check_console_paths.cmake +++ /dev/null @@ -1,14 +0,0 @@ -# Redirect the loader's stdout so both console paths must survive as UTF-8. -execute_process( - COMMAND ${RUNNER} "${LOADER}" --game-dir "game-Игра" --overlay "overlay-保存" - --run "${GUEST}" -- hello 42 - TIMEOUT 90 ENCODING UTF-8 - RESULT_VARIABLE code OUTPUT_VARIABLE output ERROR_VARIABLE error) -if(NOT code STREQUAL "0" OR - NOT output MATCHES "console paths: GAME: -> [^\n]*game-Игра, writes -> [^\n]*overlay-保存\r?\n") - message(FATAL_ERROR "Runtime did not report both Unicode paths (exit ${code})\n${output}\n${error}") -endif() -if(NOT output MATCHES "(^|\n)tiny_game: OK(\r?\n|$)" OR - NOT output MATCHES "(^|\n)game exited with code 0(\r?\n|$)") - message(FATAL_ERROR "Synthetic guest did not finish successfully\n${output}\n${error}") -endif() diff --git a/runtime/test/check_d3d12_trace.py b/runtime/test/check_d3d12_trace.py deleted file mode 100644 index b054d7225..000000000 --- a/runtime/test/check_d3d12_trace.py +++ /dev/null @@ -1,97 +0,0 @@ -"""Check the trace on the CPU command-list fixture, or on d3d12_com_test with --queue.""" - -import argparse -import os -import re -import signal -import subprocess - - -RUNNER = [] # the command that runs a Windows executable here: empty on Windows, ["wine"] for a cross build -TIMEOUT, RUNNER_TIMEOUT = 30, 120 # seconds per fixture run, natively and through RUNNER - - -def run_fixture(exe, *args): - # A first start of Wine in a fresh prefix can take tens of seconds, hence the longer limit through a runner. - timeout = RUNNER_TIMEOUT if RUNNER else TIMEOUT - # A runner such as Wine can leave the fixture (and its children) running after the launcher is killed, so on - # POSIX the run gets a session of its own and a timeout kills the whole group. - group = bool(RUNNER) and os.name == "posix" - with subprocess.Popen([*RUNNER, exe, *args], stdin=subprocess.DEVNULL, stdout=subprocess.PIPE, - stderr=subprocess.PIPE, text=True, encoding="utf-8", errors="replace", - start_new_session=group) as process: - try: - stdout, stderr = process.communicate(timeout=timeout) - except subprocess.TimeoutExpired: - if group: - try: - os.killpg(process.pid, signal.SIGKILL) - except ProcessLookupError: - pass - process.kill() - process.wait() - raise SystemExit(f"{' '.join([exe, *args])}: no exit within {timeout}s") from None - if process.returncode: - raise SystemExit(f"{exe} exited with {process.returncode}\n{stdout}{stderr}") - return [line for line in stderr.splitlines() if line.startswith("[d3d12-trace]")] - - -def main(): - parser = argparse.ArgumentParser(description=__doc__) - parser.add_argument("exe") - parser.add_argument("--queue", action="store_true", help="use the Vulkan-backed d3d12_com_test fixture") - parser.add_argument("--runner", action="append", default=[], - help="run the fixture through this command (repeat for its arguments), e.g. wine") - options = parser.parse_args() - RUNNER[:] = options.runner - - if run_fixture(options.exe): - raise SystemExit("D3D12 trace appeared with tracing disabled") - - trace = run_fixture(options.exe, "--trace-d3d12") - entries = [] - for number, line in enumerate(trace, 1): - if "synthetic-marker-argument" in line: - raise SystemExit("D3D12 trace leaked the synthetic marker payload") - match = re.fullmatch(r"\[d3d12-trace\] #(\d+) ([A-Za-z_][\w:]* (?:called|ok|failed|unsupported|ignored))", line) - if not match or int(match[1]) != number: - raise SystemExit(f"Invalid trace sequence at entry {number}\n{line}") - entries.append(match[2]) - - if options.queue: - expected = [ - "ID3D12CommandQueue::ExecuteCommandLists failed", - "ID3D12GraphicsCommandList3::SetProtectedResourceSession unsupported", - "ID3D12GraphicsCommandList::Close failed", - "ID3D12CommandQueue::Wait ok", - "ID3D12CommandQueue::ExecuteCommandLists ok", - "ID3D12CommandQueue::Signal ok", - ] - else: - expected = [ - "ID3D12GraphicsCommandList::SetPipelineState called", - "ID3D12GraphicsCommandList::SetGraphicsRootSignature called", - "ID3D12GraphicsCommandList::SetMarker called", - "ID3D12GraphicsCommandList3::SetProtectedResourceSession unsupported", - "ID3D12GraphicsCommandList3::SetProtectedResourceSession unsupported", - "ID3D12GraphicsCommandList::Close ok", - "ID3D12GraphicsCommandList::Close failed", - "ID3D12GraphicsCommandList::Reset ok", - "ID3D12GraphicsCommandList::SetDescriptorHeaps called", - "ID3D12GraphicsCommandList::SetGraphicsRootDescriptorTable called", - "ID3D12GraphicsCommandList::SetComputeRootSignature called", - "ID3D12GraphicsCommandList::Dispatch called", - "ID3D12GraphicsCommandList::DrawInstanced called", - "ID3D12GraphicsCommandList::DrawIndexedInstanced called", - "ID3D12GraphicsCommandList::Close failed", - ] - - observed = iter(entries) - for entry in expected: - if entry not in observed: - raise SystemExit(f"Missing or out-of-order trace entry {entry!r}\n" + "\n".join(trace)) - print(f"D3D12 trace verified with {len(entries)} ordered entries") - - -if __name__ == "__main__": - main() diff --git a/runtime/test/check_device_filter_tools.py b/runtime/test/check_device_filter_tools.py deleted file mode 100644 index 299529482..000000000 --- a/runtime/test/check_device_filter_tools.py +++ /dev/null @@ -1,80 +0,0 @@ -"""LEONIDA_VK_DEVICE in vk_descriptor_bench and vk_sandbox (TEST-1141). - -With a filter that matches no device, a tool must not choose another GPU. It names the filter and fails the run, as -the other harnesses do (runtime/test/vk_device_pick.h, docs/testing.md "Choosing the GPU"). Before, both tools -ignored the filter and ran on the best-ranked GPU. - - python -I check_device_filter_tools.py - -Exit 0 when both tools refuse the filter, 1 when one does not or when the device list fails for another reason, and -77 (skip) on a machine with no Vulkan loader, driver or device, where no tool can choose one. Standard library only. -""" -import os -import re -import struct -import subprocess -import sys - -FILTER = "leonida-no-such-gpu" -UNSUPPORTED = 77 - - -def run(cmd, env=None): - p = subprocess.run(cmd, capture_output=True, text=True, errors="replace", env=env, timeout=120) - return p.returncode, p.stdout + p.stderr - - -def no_vulkan(code, out): - """Why `vk_descriptor_bench --list-devices` found no Vulkan device, or "" when it did or failed otherwise. Only - these count as "nothing to choose from": no Vulkan loader, no driver (vkCreateInstance gives - VK_ERROR_INCOMPATIBLE_DRIVER, -9), or a list with no device in it.""" - if code == 0: - return "" if any(line.startswith("[") for line in out.splitlines()) else "the device list is empty" - if code == 1 and ("could not load" in out or "has no vkGetInstanceProcAddr" in out): - return "no Vulkan loader" - if code == 1 and re.search(r"FAILED vkCreateInstance\(.*\) -> -9\b", out): - return "no Vulkan driver (VK_ERROR_INCOMPATIBLE_DRIVER)" - return "" - - -def main(argv): - if len(argv) != 4: - print(__doc__, file=sys.stderr) - return 2 - bench, sandbox, work = argv[1:] - os.makedirs(work, exist_ok=True) - - # The device list ignores the filter, so it shows whether there is any device to choose from. - plain = {k: v for k, v in os.environ.items() if k != "LEONIDA_VK_DEVICE"} - code, out = run([bench, "--list-devices"], env=plain) - reason = no_vulkan(code, out) - if reason: - print(f"SKIP: no Vulkan device to choose from ({reason})") - return UNSUPPORTED - if code != 0: # anything else is a failure of the tool, not a machine without Vulkan - print(f"FAIL: {bench} --list-devices exit {code}:\n{out.strip()}") - return 1 - - # The smallest scene vk_sandbox reads: magic, version 1, no textures, meshes or draws, and a centre. - scene = os.path.join(work, "empty_scene.bin") - with open(scene, "wb") as f: - f.write(b"LSB1" + struct.pack("<4I", 1, 0, 0, 0) + struct.pack("<3f", 0.0, 0.0, 0.0)) - missing = os.path.join(work, "never_read.spv") # the device is chosen before the shaders are read - - env = dict(plain, LEONIDA_VK_DEVICE=FILTER) - failures = [] - for name, cmd in (("vk_descriptor_bench", [bench]), - ("vk_sandbox", [sandbox, scene, missing, missing, "--out", os.path.join(work, "out.ppm")])): - code, out = run(cmd, env=env) - named = f"LEONIDA_VK_DEVICE={FILTER}" in out - if code == 0 or not named or "device:" in out: - failures.append(f"{name}: exit {code}, {'names' if named else 'does not name'} the filter:\n{out.strip()}") - else: - print(f"ok: {name} refuses LEONIDA_VK_DEVICE={FILTER} (exit {code})") - for failure in failures: - print(f"FAIL: {failure}") - return 1 if failures else 0 - - -if __name__ == "__main__": - sys.exit(main(sys.argv)) diff --git a/runtime/test/check_game_dir.cmake b/runtime/test/check_game_dir.cmake deleted file mode 100644 index 039a1ade3..000000000 --- a/runtime/test/check_game_dir.cmake +++ /dev/null @@ -1,34 +0,0 @@ -# Run the stand-in game from its own folder by bare name, as a player would (`gta6rt --run game.exe`), and again -# with `--game-dir .`. In both, GAME: has to name that folder as an absolute path: the guest moves its current -# directory away and then reads GAME:\tiny_game_probe.txt (argument game-file). Before, a bare name left GAME: with -# an empty root (`console paths: GAME: -> , writes -> overlay`) and the open failed with ERROR_PATH_NOT_FOUND. -# The verdict is checked from the output, as check_loaded_gdk.cmake does, because under Wine an exit status alone -# can look successful. -get_filename_component(guest_dir "${GUEST}" DIRECTORY) -get_filename_component(guest_name "${GUEST}" NAME) -file(WRITE "${guest_dir}/tiny_game_probe.txt" "game") -set(failures "") -foreach(variant "bare" "dot") - if(variant STREQUAL "dot") - set(dir_args --game-dir .) - else() - set(dir_args "") - endif() - execute_process( - COMMAND ${RUNNER} "${LOADER}" ${dir_args} --run "${guest_name}" -- hello 42 game-file - WORKING_DIRECTORY "${guest_dir}" - TIMEOUT 90 - RESULT_VARIABLE code OUTPUT_VARIABLE output ERROR_VARIABLE output) - string(REPLACE "\r\n" "\n" output "${output}") - # An absolute GAME: root: a drive letter (Windows, and Wine's Z:) or a leading slash, and an overlay inside it. - if(NOT code STREQUAL "0" OR NOT output MATCHES "(^|\n)tiny_game: PASS GAME:" - OR NOT output MATCHES "(^|\n)tiny_game: OK(\n|$)" - OR NOT output MATCHES "(^|\n)console paths: GAME: -> ([A-Za-z]:|[\\/])[^\n]*, writes -> ([A-Za-z]:|[\\/])[^\n]*overlay(\n|$)" - OR NOT output MATCHES "(^|\n)game exited with code 0(\n|$)") - string(APPEND failures "--- ${variant}: returned ${code}\n${output}\n") - endif() -endforeach() -file(REMOVE "${guest_dir}/tiny_game_probe.txt") -if(failures) - message(FATAL_ERROR "GAME: did not resolve to the game folder\n${failures}") -endif() diff --git a/runtime/test/check_loaded_async.cmake b/runtime/test/check_loaded_async.cmake deleted file mode 100644 index 4217b173f..000000000 --- a/runtime/test/check_loaded_async.cmake +++ /dev/null @@ -1,14 +0,0 @@ -# Observe the guest verdict and the loader from outside the process. Under Wine an -# exit status alone can look successful even when the mapped program reported failure. -get_filename_component(guest_dir "${GUEST}" DIRECTORY) -get_filename_component(guest_name "${GUEST}" NAME) -execute_process( - COMMAND ${RUNNER} "${LOADER}" --run "${guest_name}" - WORKING_DIRECTORY "${guest_dir}" - TIMEOUT 90 - RESULT_VARIABLE code OUTPUT_VARIABLE output ERROR_VARIABLE output) -string(REPLACE "\r\n" "\n" output "${output}") -if(NOT code STREQUAL "0" OR NOT output MATCHES "(^|\n)tiny_async: PASS(\n|$)" - OR NOT output MATCHES "(^|\n)game exited with code 0(\n|$)") - message(FATAL_ERROR "Loaded async fixture returned ${code}\n${output}") -endif() diff --git a/runtime/test/check_loaded_bundled.cmake b/runtime/test/check_loaded_bundled.cmake deleted file mode 100644 index 397e59c2f..000000000 --- a/runtime/test/check_loaded_bundled.cmake +++ /dev/null @@ -1,14 +0,0 @@ -# Run the run-time bundled-DLL load fixture (tiny_bundled_load) under the loader and check its verdict from outside, -# as check_loaded_gdk.cmake does. -get_filename_component(guest_dir "${GUEST}" DIRECTORY) -get_filename_component(guest_name "${GUEST}" NAME) -execute_process( - COMMAND ${RUNNER} "${LOADER}" --run "${guest_name}" - WORKING_DIRECTORY "${guest_dir}" - TIMEOUT 90 - RESULT_VARIABLE code OUTPUT_VARIABLE output ERROR_VARIABLE output) -string(REPLACE "\r\n" "\n" output "${output}") -if(NOT code STREQUAL "0" OR NOT output MATCHES "(^|\n)tiny_bundled_load: PASS(\n|$)" - OR NOT output MATCHES "(^|\n)game exited with code 0(\n|$)") - message(FATAL_ERROR "Loaded bundled-DLL run-time fixture returned ${code}\n${output}") -endif() diff --git a/runtime/test/check_loaded_gdk.cmake b/runtime/test/check_loaded_gdk.cmake deleted file mode 100644 index 237a30066..000000000 --- a/runtime/test/check_loaded_gdk.cmake +++ /dev/null @@ -1,16 +0,0 @@ -# Run the run-time GDK load fixture (tiny_gdk_load) under the loader and check its verdict from outside, as -# check_loaded_async.cmake does: under Wine an exit status alone can look successful even when the guest failed. -get_filename_component(guest_dir "${GUEST}" DIRECTORY) -get_filename_component(guest_name "${GUEST}" NAME) -file(WRITE "${guest_dir}/host_shim_probe.txt" "shim") -execute_process( - COMMAND ${RUNNER} "${LOADER}" --run "${guest_name}" -- host-shim-probe - WORKING_DIRECTORY "${guest_dir}" - TIMEOUT 90 - RESULT_VARIABLE code OUTPUT_VARIABLE output ERROR_VARIABLE output) -file(REMOVE "${guest_dir}/host_shim_probe.txt") -string(REPLACE "\r\n" "\n" output "${output}") -if(NOT code STREQUAL "0" OR NOT output MATCHES "(^|\n)tiny_gdk_load: PASS(\n|$)" - OR NOT output MATCHES "(^|\n)game exited with code 0(\n|$)") - message(FATAL_ERROR "Loaded GDK run-time fixture returned ${code}\n${output}") -endif() diff --git a/runtime/test/check_module_names.py b/runtime/test/check_module_names.py deleted file mode 100644 index 709d3220b..000000000 --- a/runtime/test/check_module_names.py +++ /dev/null @@ -1,167 +0,0 @@ -"""Original PE fixtures only; native Windows, real mapped entry, and strict UTF-8 traces.""" -from __future__ import annotations - -import argparse -import ctypes -import hashlib -import json -import os -from pathlib import Path -import shutil -import subprocess -import tempfile - - -def exact_acp(text: str) -> bytes | None: - try: - encoded = text.encode("mbcs", "strict") - return encoded if encoded.decode("mbcs", "strict") == text else None - except UnicodeError: - return None - - -def main() -> int: - parser = argparse.ArgumentParser(description=__doc__) - for name in ("loader", "guest", "importer", "dependency", "work-dir"): - parser.add_argument("--" + name, required=True, type=Path) - parser.add_argument("--report", type=Path) - args = parser.parse_args() - if os.name != "nt": - parser.error("this comparison needs native Windows") - args.work_dir.mkdir(parents=True, exist_ok=True) - page = ctypes.windll.kernel32.GetACP() - # The guest also looks up the upper-case spelling through GetModuleHandleA. - # ACP 936 can spell U+00E9 but not U+00C9, so require both forms to round-trip. - acp_char = next((c for c in "\u00e9\u03b4\u0436\u6f22" if exact_acp(c) and exact_acp(c.upper())), None) - unicode_char = next((c for c in "\u6f22\u5b57\u0436\u03b4\u00e9" if exact_acp(c) is None), "\u6f22") - rows: list[dict] = [] - failures: list[str] = [] - skips: list[str] = [] - environment = os.environ.copy() - for name in list(environment): - if name.upper().startswith("LEONIDA_"): - del environment[name] - environment["LEONIDA_UNIMPLEMENTED"] = "stop" - - with tempfile.TemporaryDirectory(prefix="module_names_", dir=args.work_dir.resolve()) as temp: - root = Path(temp) - package = root / "package" - package.mkdir() - originals: dict[Path, bytes] = {} - - def copy(source: Path, destination: Path) -> None: - destination.parent.mkdir(parents=True, exist_ok=True) - shutil.copyfile(source, destination) - originals[destination] = destination.read_bytes() - - def run(label: str, mode: str, image: Path, modules: set[str], self_probe: bool) -> None: - trace = root / (label + "_" + mode.removeprefix("--") + ".jsonl") - command = ([str(image), image.name] if mode == "native" else - [str(args.loader.resolve()), mode, str(image), - "--game-dir", str(image.parent), "--overlay", str(root / "overlay"), - "--trace", str(trace), "--", image.name]) - errors: list[str] = [] - try: - child = subprocess.run(command, cwd=root, env=environment, capture_output=True, timeout=15) - stdout = child.stdout.decode("utf-8", "replace") - stderr = child.stderr.decode("utf-8", "replace") - code = child.returncode - except subprocess.TimeoutExpired: - code, stdout, stderr = None, "", "" - errors.append("child exceeded 15 seconds") - if code != 0: - errors.append(f"exit code {code}") - entry = next((line for line in stdout.splitlines() if line.startswith("NAME_PROBE ")), None) - if self_probe and mode in ("native", "--run"): - if not entry or "entered=1" not in entry: - errors.append("guest did not reach its name checks") - # The wide lookups (as named, in the system table's upper case, and LoadLibraryW of the mapped - # image) must find the image for every name; the ANSI ones, exact, ASCII-case and code-page-case, - # for a name the code page can spell. - required = ["self_w=1", "case_w=1", "load_w=1"] - if exact_acp(image.name) is not None: - required += ["representable=1", "self_a=1", "ascii_case_a=1", "acp_case_a=1"] - # Under the loader, a shim-served DLL named through a directory outside ASCII is answered by basename - # (natively the probe depends on what the machine has installed, so it is only checked here). - if mode == "--run": - required += ["shim_dir_w=1", "shim_dir_load_w=1"] - missing = [field for field in required if not entry or field not in entry.split()] - if missing: - errors.append("guest lookups not retained: " + " ".join(missing)) - mapped_names: list[str] = [] - if mode != "native": - try: - events = [json.loads(line) for line in trace.read_text(encoding="utf-8").splitlines()] - mapped_names = [event["module"] for event in events if event.get("kind") == "map"] - if set(mapped_names) != modules or len(mapped_names) != len(modules): - errors.append(f"map trace names differ: {mapped_names!r}") - except (OSError, UnicodeError, ValueError, KeyError) as exc: - errors.append(f"invalid UTF-8 JSON trace: {exc}") - row = dict(case=label, mode=mode, command=command, exit_code=code, entry=entry, - mapped_names=mapped_names, stdout=stdout, stderr=stderr, errors=errors) - rows.append(row) - failures.extend(f"{label}/{mode}: {error}" for error in errors) - print(json.dumps({key: row[key] for key in ("case", "mode", "exit_code", "entry", "errors")}), - flush=True) - - cases = [ - ("ascii", "plain", "Name-plain.exe"), - ("unicode_basename", "plain", f"Name-{unicode_char}.exe"), - ("unicode_parent", f"{unicode_char}-folder", "Name-plain.exe"), - ] - if acp_char: - cases.insert(1, ("acp", "plain", f"Name-{acp_char}.exe")) - else: - skips.append("No selected non-ASCII character round-trips through the active ANSI code page") - for label, directory, name in cases: - image = package / directory / name - copy(args.guest, image) - for mode in ("native", "--dry-run", "--init", "--run"): - run(label, mode, image, {name}, self_probe=True) - - # Only the import-name string in our own compiled tiny_exe is replaced. Its function and data imports - # still have to resolve and execute successfully in both native and mapped children. - importer = args.importer.read_bytes() - needle = b"tiny_dll.dll\0" - if importer.count(needle) != 1: - raise RuntimeError("expected exactly one original synthetic DLL import name") - imports = [("import_ascii", "Import-plain.exe", "tiny_dll.dll", needle)] - if acp_char: - dll = f"d-{acp_char}.dll" - encoded = exact_acp(dll) - if encoded is None or len(encoded) + 1 > len(needle): - raise RuntimeError("ACP import fixture does not fit the original name span") - replacement = (encoded + b"\0").ljust(len(needle), b"\0") - imports.extend([ - ("import_acp", "Import-acp.exe", dll, replacement), - ("import_unicode_exe", f"Import-{unicode_char}.exe", dll, replacement), - ]) - for label, name, dll, replacement in imports: - folder = package / label - folder.mkdir() - image = folder / name - image.write_bytes(importer.replace(needle, replacement)) - originals[image] = image.read_bytes() - copy(args.dependency, folder / dll) - for mode in ("native", "--run"): - run(label, mode, image, {name, dll}, self_probe=False) - - for path, original in originals.items(): - if path.read_bytes() != original: - failures.append(f"fixture bytes changed: {path.name}") - hashes = {str(path.relative_to(root)): hashlib.sha256(original).hexdigest() - for path, original in originals.items()} - result = dict(acp=page, children=len(rows), failures=failures, skips=skips, - source_sha256={name: hashlib.sha256(getattr(args, name).read_bytes()).hexdigest() - for name in ("loader", "guest", "importer", "dependency")}, - fixture_sha256=hashes, rows=rows) - if args.report: - args.report.write_text(json.dumps(result, indent=2) + "\n", encoding="utf-8", newline="\n") - for skip in skips: - print("SKIP", skip) - print(f"module names: {len(rows)} native/mapped children, {len(failures)} failures, ACP {page}") - return bool(failures) - - -if __name__ == "__main__": - raise SystemExit(main()) diff --git a/runtime/test/check_sparse_queue_family.py b/runtime/test/check_sparse_queue_family.py deleted file mode 100644 index b5e0558bf..000000000 --- a/runtime/test/check_sparse_queue_family.py +++ /dev/null @@ -1,181 +0,0 @@ -"""Repo-friendly, optional GPU test: byte-exact Leonida COPY/COMPUTE tiled-buffer replay -AND actual VK_SHARING_MODE_CONCURRENT on *every* sparse VkBuffer created by the layer. - -Runs the original synthetic `d3d12_sparse_queue_family_test` target. -Invokes the SDK's VK_LAYER_LUNARG_api_dump in a short-lived isolated directory, then reruns the test -under VK_LAYER_KHRONOS_validation alone (api_dump's vkDestroyDevice can crash on AMD Windows, with both loaded -more often than alone: see died_in_vk_destroy_device); -no private-game files, asset paths, device memory dumps, or committed logs. - - python -I check_sparse_queue_family.py path/to/d3d12_sparse_queue_family_test.exe - python -I check_sparse_queue_family.py path/to/baseline.exe --expect-baseline-exclusive - -By default the baseline fails (exit 1) and patched runtime passes (exit 0). -If the API dump layer is absent the result skips (exit 77, CTest SKIP_RETURN_CODE). -""" -from __future__ import annotations - -import argparse -import os -import re -import subprocess -import sys -import tempfile -from pathlib import Path -from typing import Mapping - - -SPARSE_FLAGS = "VkBufferCreateFlags = 7 (VK_BUFFER_CREATE_SPARSE_BINDING_BIT" -MODE = re.compile(r"sharingMode:\s+VkSharingMode = (VK_SHARING_MODE_\w+)") -COUNT = re.compile(r"queueFamilyIndexCount:\s+uint32_t = (\d+)") -INDICES = re.compile(r"pQueueFamilyIndices\[(\d+)\]:\s+const uint32_t = (\d+)") -# Each of the two runs gets 30 s, so both together stay inside the CTest TIMEOUT of 65 s -# (runtime/cmake/d3d12_vulkan.cmake). -RUN_TIMEOUT = 30 -ACCESS_VIOLATION = 0xC0000005 # STATUS_ACCESS_VIOLATION, as Windows reports it in the exit code -CASES = ["LAYER_MAP_COMPUTE_COPY_COMPUTE", "LAYER_MAP_COPY_COPY_COMPUTE", "LAYER_MAP_DIRECT_COPY_COMPUTE"] # sorted -FINAL = re.compile(r"^LAYER_FINAL PASS$", re.M) -CALL_HEAD = re.compile(r"^(vk\w+)\(", re.M) -CASE = re.compile(r"^RESULT (LAYER_MAP_(?:DIRECT|COPY|COMPUTE)_COPY_COMPUTE) PASS mapped_mismatch=0/65536 unmapped_nonzero=0/65536$", re.M) - - -def check_trace(path: Path, expect_exclusive: bool) -> tuple[int, int]: - rows = path.read_text(encoding="utf-8", errors="replace").splitlines() - records = 0 - for i, line in enumerate(rows): - if SPARSE_FLAGS not in line: - continue - end = i + 1 - while end < len(rows) and "VkBufferCreateFlags =" not in rows[end] and not CALL_HEAD.match(rows[end]): - end += 1 - tail = "\n".join(rows[i + 1:end]) - mode, count = MODE.search(tail), COUNT.search(tail) - if not mode or not count: - raise AssertionError(f"incomplete API dump sparse VkBuffer at line {i+1}") - sharing, n = mode.group(1), int(count.group(1)) - indices = [(int(slot), int(family)) for slot, family in INDICES.findall(tail)] - if expect_exclusive: - if sharing != "VK_SHARING_MODE_EXCLUSIVE" or n != 0 or indices: - raise AssertionError(f"baseline negative control not reproduced at line {i+1}") - elif (sharing != "VK_SHARING_MODE_CONCURRENT" or n < 2 or len(indices) != n - or len({slot for slot, _ in indices if slot < n}) != n - or len({family for _, family in indices}) != n): - raise AssertionError(f"incomplete or non-concurrent sparse buffer at line {i+1}: " - f"{sharing}, count={n}, indices={indices}") - records += 1 - if records < 6 or records % 2: - raise AssertionError(f"insufficient sparse VkBuffer create-info records: {records}") - return records // 2, records - - -def main() -> int: - parser = argparse.ArgumentParser() - parser.add_argument("executable", type=Path, help="Compiled Leonida d3d12_sparse_queue_family_test binary") - parser.add_argument("--expect-baseline-exclusive", action="store_true", - help="negative-control mode: prove buggy EXCLUSIVE create infos instead of requiring fix") - args = parser.parse_args() - exe = args.executable.resolve() - if not exe.is_file(): - print(f"ERROR: missing executable {exe}", file=sys.stderr) - return 2 - with tempfile.TemporaryDirectory(prefix="leonida_sparse_trace_") as td: - path = Path(td) - dump_name = path / "sparse_create_info.log" - (path / "vk_layer_settings.txt").write_text( - "lunarg_api_dump.file = true\n" - f"lunarg_api_dump.log_filename = {dump_name}\n" - "lunarg_api_dump.output_format = text\n" - "lunarg_api_dump.pre_dump = true\n" - "lunarg_api_dump.detailed = true\n", - encoding="utf-8", - ) - dump_env, validation_env = pass_envs(os.environ, path) - # Two runs, one layer each. SDK 1.4.363's api_dump reads the VkDevice's dispatch key after the call down the - # chain has freed the device (fix: LunarG/VulkanTools#2754), so on the AMD Windows driver its vkDestroyDevice - # can crash with 0xC0000005. Validation below it makes that likelier (every run on some RDNA2 iGPUs), and an - # RX 9070 crashes now and then with api_dump alone, so this run allows exactly that crash. - dump_out, skip = run_pass(exe, dump_env, path, trace_dir=path) - if skip: - return skip - # Check the trace before the validation run: a skip there must not hide a contract the trace has broken. - candidates = list(path.glob("sparse_create_info.log*")) - if not candidates: - print("SKIP 77: Vulkan SDK VK_LAYER_LUNARG_api_dump unavailable or did not write trace") - return 77 - calls, infos = check_trace(candidates[0], args.expect_baseline_exclusive) - validation_out, skip = run_pass(exe, validation_env, path) - if skip: - return skip - errors = [line for line in validation_out.splitlines() if "Validation Error" in line or "VUID-" in line] - if errors: - raise AssertionError(f"Khronos validation reported {len(errors)} error line(s); first: {errors[0][:300]}") - kinds = sorted(CASE.findall(dump_out)) - print(f"GPU PASS: {len(kinds)} COPY/COMPUTE sparse queue cases, mapped 65,536 bytes exact, unmapped 65,536 zeros") - print(f"VK API CONTRACT PASS: {calls} sparse VkBuffer creations / {infos} create-info records = " - f"{'EXCLUSIVE negative-control' if args.expect_baseline_exclusive else 'CONCURRENT with 2+ unique families'}") - print("Khronos validation run (no api_dump): the same GPU cases pass with no validation errors reported") - return 0 - - -def pass_envs(base: Mapping[str, str], settings_dir: Path) -> tuple[dict[str, str], dict[str, str]]: - """Environments for the api_dump run and the validation run; each loads exactly one of the two SDK layers.""" - dump = dict(base) - # VK_INSTANCE_LAYERS makes the loader insert api_dump without the runtime asking for it. - dump["VK_INSTANCE_LAYERS"] = "VK_LAYER_LUNARG_api_dump" - dump["LEONIDA_VK_VALIDATION"] = "0" - dump["VK_LAYER_SETTINGS_PATH"] = str(settings_dir) - validation = dict(base) - validation.pop("VK_INSTANCE_LAYERS", None) - validation["LEONIDA_VK_VALIDATION"] = "1" - return dump, validation - - -def died_in_vk_destroy_device(trace_dir: Path) -> bool: - """True when the last call in the api_dump trace is vkDestroyDevice (pre_dump writes it before the call). - - The trace can't tell api_dump's own read of the freed device from a driver crash in the same call. The validation - run can: it destroys the device without api_dump and has to exit 0. - """ - traces = list(trace_dir.glob("sparse_create_info.log*")) - if len(traces) != 1: - return False - calls = CALL_HEAD.findall(traces[0].read_text(encoding="utf-8", errors="replace")) - return bool(calls) and calls[-1] == "vkDestroyDevice" - - -def run_pass(exe: Path, env: Mapping[str, str], cwd: Path, trace_dir: Path | None = None) -> tuple[str, int]: - """Run the GPU test once: (output, 77) for a skip, (output, 0) when all three cases passed. - - trace_dir (the api_dump run only) allows an access violation in vkDestroyDevice, once every result is printed. - """ - run = subprocess.run([str(exe)], cwd=cwd, env=dict(env), capture_output=True, - text=True, encoding="utf-8", errors="replace", timeout=RUN_TIMEOUT) - out = run.stdout + "\n" + run.stderr - if run.returncode == 77: - print("SKIP 77: Leonida Vulkan device / sparse features unavailable") - return out, 77 - # The loader refuses the instance when a layer named in VK_INSTANCE_LAYERS (or the validation layer - # LEONIDA_VK_VALIDATION asks for) is not installed: that is the "layer absent" skip, not a layer failure. - if run.returncode != 0 and "vkCreateInstance" in out and "failed" in out: - print("SKIP 77: VK_LAYER_LUNARG_api_dump or VK_LAYER_KHRONOS_validation unavailable (vkCreateInstance failed)") - return out, 77 - teardown_crash = (trace_dir is not None and run.returncode == ACCESS_VIOLATION - and died_in_vk_destroy_device(trace_dir)) - if run.returncode != 0 and not teardown_crash: - print(out[-7000:], file=sys.stderr) - raise AssertionError(f"Leonida GPU test failed exit={run.returncode}") - kinds = sorted(CASE.findall(out)) - if kinds != CASES or len(FINAL.findall(out)) != 1: - raise AssertionError(f"GPU byte verification missing: cases={kinds}; tail={out[-2000:]}") - if teardown_crash: - print("NOTE: the api_dump run crashed in vkDestroyDevice (0xC0000005) after every case passed; " - "the validation run still has to exit 0") - return out, 0 - - -if __name__ == "__main__": - try: - raise SystemExit(main()) - except (AssertionError, subprocess.TimeoutExpired) as error: - print(f"FAIL: {error}", file=sys.stderr) - raise SystemExit(1) diff --git a/runtime/test/check_stack_reserve.cmake b/runtime/test/check_stack_reserve.cmake deleted file mode 100644 index 6954b2afb..000000000 --- a/runtime/test/check_stack_reserve.cmake +++ /dev/null @@ -1,59 +0,0 @@ -# cmake -DTOOL= -DWANT= -P check_stack_reserve.cmake -# -# Fails unless the PE header of TOOL reserves at least WANT bytes of stack (SizeOfStackReserve). On Windows that -# reserve is the stack of the main thread and of every thread created without a size of its own, std::thread -# included, so it is what a driver's compiler runs on in vk_pipeline_check, and in gta6rt on every game thread but -# the entry thread (BUILD-1457). Only the header is read. - -# A little-endian unsigned integer of `bytes` bytes at `offset` in `file`. -function(read_le file offset bytes out) - file(READ "${file}" hex OFFSET ${offset} LIMIT ${bytes} HEX) - string(LENGTH "${hex}" length) - math(EXPR expected "${bytes} * 2") - if(NOT length EQUAL expected) - message(FATAL_ERROR "${file}: cannot read ${bytes} bytes at offset ${offset}") - endif() - set(big_endian "") - math(EXPR last "${bytes} - 1") - foreach(i RANGE ${last}) - math(EXPR at "(${last} - ${i}) * 2") - string(SUBSTRING "${hex}" ${at} 2 byte) - string(APPEND big_endian "${byte}") - endforeach() - math(EXPR value "0x${big_endian}" OUTPUT_FORMAT DECIMAL) - set(${out} "${value}" PARENT_SCOPE) -endfunction() - -if(NOT EXISTS "${TOOL}") - message(FATAL_ERROR "no such file: ${TOOL}") -endif() -# if( LESS ) is false, so a missing or misspelt WANT would pass every file. -if(NOT "${WANT}" MATCHES "^[1-9][0-9]*$") - message(FATAL_ERROR "WANT must be a number of bytes greater than 0, got \"${WANT}\"") -endif() -read_le("${TOOL}" 0 2 dos_magic) -if(NOT dos_magic EQUAL 23117) # "MZ" - message(FATAL_ERROR "${TOOL} is not a PE file (no MZ header)") -endif() -read_le("${TOOL}" 60 4 pe_offset) # e_lfanew -read_le("${TOOL}" ${pe_offset} 4 pe_signature) -if(NOT pe_signature EQUAL 17744) # "PE\0\0" - message(FATAL_ERROR "${TOOL} is not a PE file (no PE signature at ${pe_offset})") -endif() -math(EXPR optional_header "${pe_offset} + 24") -read_le("${TOOL}" ${optional_header} 2 optional_magic) -if(optional_magic EQUAL 523) # PE32+: SizeOfStackReserve is 8 bytes - set(width 8) -elseif(optional_magic EQUAL 267) # PE32: 4 bytes - set(width 4) -else() - message(FATAL_ERROR "${TOOL}: unknown optional header magic ${optional_magic}") -endif() -math(EXPR reserve_offset "${optional_header} + 72") # the same offset in PE32 and PE32+ -read_le("${TOOL}" ${reserve_offset} ${width} reserve) - -if(reserve LESS WANT) - message(FATAL_ERROR "${TOOL} reserves ${reserve} bytes of stack, expected at least ${WANT}: the link option " - "from runtime/cmake/*.cmake (BUILD-1457) did not reach the linker") -endif() -message(STATUS "stack reserve: ${reserve} bytes (at least ${WANT} wanted)") diff --git a/runtime/test/check_startup_cmdline.cmake b/runtime/test/check_startup_cmdline.cmake deleted file mode 100644 index d2c315f03..000000000 --- a/runtime/test/check_startup_cmdline.cmake +++ /dev/null @@ -1,31 +0,0 @@ -foreach(mode args no_args fail_init) - set(args) - if(mode STREQUAL "args") - set(args hello "two words") - elseif(mode STREQUAL "fail_init") - set(args fail-init) - endif() - if(NOT mode STREQUAL "fail_init") - execute_process(COMMAND ${RUNNER} "${GUEST}" ${args} TIMEOUT 90 - RESULT_VARIABLE native_code OUTPUT_VARIABLE native_output ERROR_VARIABLE native_error) - if(NOT native_code STREQUAL "0" OR NOT native_output MATCHES "tiny_startup_cmdline: PASS") - message(FATAL_ERROR "Native startup command line (${mode}) returned ${native_code}\n${native_output}\n${native_error}") - endif() - endif() - execute_process( - COMMAND ${RUNNER} "${LOADER}" --run "${GUEST}" -- ${args} - TIMEOUT 90 - RESULT_VARIABLE code OUTPUT_VARIABLE output ERROR_VARIABLE error) - if(mode STREQUAL "fail_init") - if(NOT code STREQUAL "1" OR NOT error MATCHES "DllMain returned FALSE" OR output MATCHES "running ") - message(FATAL_ERROR "Failed attach returned ${code}\n${output}\n${error}") - endif() - if(NOT output MATCHES "2 module\\(s\\) mapped, [0-9]+ unimplemented import\\(s\\)" - OR NOT output MATCHES "unimplemented by return policy: hresult=[0-9]+ other=[0-9]+") - message(FATAL_ERROR "Failed attach lost the import binding report\n${output}\n${error}") - endif() - elseif(NOT code STREQUAL "0" OR NOT output MATCHES "tiny_startup_cmdline: PASS" - OR NOT output MATCHES "game exited with code 0") - message(FATAL_ERROR "Startup command line (${mode}) returned ${code}\n${output}\n${error}") - endif() -endforeach() diff --git a/runtime/test/check_texture_readback_sync.cmake b/runtime/test/check_texture_readback_sync.cmake deleted file mode 100644 index 3905164f7..000000000 --- a/runtime/test/check_texture_readback_sync.cmake +++ /dev/null @@ -1,38 +0,0 @@ -# Run with -DTOOL= -DSPIRV= -# -DOUTPUT= -P runtime/test/check_texture_readback_sync.cmake. -# For a cross build, pass the configured emulator as "-DRUNNER=". -# Requires the Khronos validation layer and a device that supports the texture harness. -if(NOT DEFINED OUTPUT OR OUTPUT STREQUAL "") - message(FATAL_ERROR "Specify the readback file with -DOUTPUT") -endif() -get_filename_component(spirv_dir "${SPIRV}" ABSOLUTE) -# Relative output paths are resolved by the harness from its working directory. -get_filename_component(readback "${OUTPUT}" ABSOLUTE BASE_DIR "${spirv_dir}") -if(IS_DIRECTORY "${readback}") - message(FATAL_ERROR "Readback path is a directory: ${readback}") -endif() -file(REMOVE "${readback}") -if(EXISTS "${readback}" OR IS_SYMLINK "${readback}") - message(FATAL_ERROR "Could not remove the previous readback: ${readback}") -endif() - -execute_process( - COMMAND "${CMAKE_COMMAND}" -E env VK_INSTANCE_LAYERS=VK_LAYER_KHRONOS_validation - VK_LOADER_DEBUG=layer VK_LAYER_ENABLES=VK_VALIDATION_FEATURE_ENABLE_SYNCHRONIZATION_VALIDATION_EXT - ${RUNNER} "${TOOL}" cube "${OUTPUT}" - WORKING_DIRECTORY "${spirv_dir}" TIMEOUT 90 - RESULT_VARIABLE code OUTPUT_VARIABLE log ERROR_VARIABLE log) -if(NOT code STREQUAL "0" OR NOT log MATCHES "vk_texture_test cube: PASSED" - OR NOT log MATCHES "Insert instance layer \"VK_LAYER_KHRONOS_validation\"" - OR log MATCHES "SYNC-HAZARD|Validation Error") - message(FATAL_ERROR "Texture draw with synchronization validation returned ${code}\n${log}") -endif() -if(NOT EXISTS "${readback}" OR IS_DIRECTORY "${readback}") - message(FATAL_ERROR "Texture draw did not write a readback: ${readback}\n${log}") -endif() -# The cube harness writes a 64x64 VK_FORMAT_R32G32B32A32_SFLOAT frame. -math(EXPR expected_size "64 * 64 * 16") -file(SIZE "${readback}" actual_size) -if(NOT actual_size EQUAL expected_size) - message(FATAL_ERROR "Texture readback has ${actual_size} bytes, expected ${expected_size}: ${readback}\n${log}") -endif() diff --git a/runtime/test/check_tiny_frame.py b/runtime/test/check_tiny_frame.py deleted file mode 100644 index 2a734e43e..000000000 --- a/runtime/test/check_tiny_frame.py +++ /dev/null @@ -1,147 +0,0 @@ -"""Run tiny_frame under `gta6rt --run --trace-d3d12` on the Vulkan D3D12 device and check the run from outside. - - python -I check_tiny_frame.py [--probe d3d12_com_test.exe] [--runner wine ...] - -Checks the guest's verdict and exit code, that the loader's report binds d3d12_xs.dll!D3D12XboxCreateDevice to the -shim, and that the D3D12 trace is a gapless numbered sequence in which the calls a first frame needs appear in -order. Exits 77 (ctest: skipped) when --probe, one of the Vulkan device tests, says -there is no usable Vulkan device on this machine. -""" - -import argparse -import os -import re -import subprocess -import sys - -SKIP = 77 - -# The first frame, in the order the fixture makes the calls, as the trace words them (`called` for a method that -# returns nothing). Other traced calls, such as the queue and fence proxies' own entries, may sit between them. -EXPECTED = [ - "D3D12XboxCreateDevice ok", - "ID3D12Device::CreateCommandQueue ok", - "ID3D12Device::CreateCommandAllocator ok", - "ID3D12Device::CreateCommandList ok", - "ID3D12Device::CreateFence ok", - "ID3D12Device::CreateDescriptorHeap ok", - "ID3D12Device::CreateCommittedResource ok", - "ID3D12Device::CreateCommittedResource ok", - "ID3D12Device::CreateRenderTargetView called", - "ID3D12GraphicsCommandList::ClearRenderTargetView called", - "ID3D12GraphicsCommandList::ResourceBarrier called", - "ID3D12GraphicsCommandList::CopyTextureRegion called", - "ID3D12GraphicsCommandList::Close ok", - "ID3D12CommandQueue::ExecuteCommandLists ok", - "ID3D12CommandQueue::Signal ok", -] - - -def ordered_subsequence(expected, entries): - """The first expected entry that does not appear, in order, in entries; None when all do.""" - position = 0 - for want in expected: - while position < len(entries) and entries[position] != want: - position += 1 - if position == len(entries): - return want - position += 1 - return None - - -def parse_trace(lines): - """[(method, outcome)] from the `[d3d12-trace] #N method outcome` lines; raises ValueError on a gap.""" - entries = [] - for line in lines: - if not line.startswith("[d3d12-trace]"): - continue - match = re.fullmatch(r"\[d3d12-trace\] #(\d+) (.+) (called|ok|failed|unsupported|ignored|refused)", line) - if not match or int(match[1]) != len(entries) + 1: - raise ValueError(f"invalid trace sequence at entry {len(entries) + 1}: {line}") - entries.append((match[2], match[3])) - return entries - - -def check_output(code, output): - """A list of problems with one run's exit code and combined output; empty when it is what the test expects.""" - problems = [] - lines = output.replace("\r\n", "\n").split("\n") - if code != 0: - problems.append(f"exit code {code}") - if "tiny_frame: OK" not in lines: - problems.append("the guest did not print `tiny_frame: OK`") - if any(line.startswith("tiny_frame: FAIL") for line in lines): - problems.append("the guest reported a failed check") - if "game exited with code 0" not in lines: - problems.append("gta6rt did not report `game exited with code 0`") - if not any(re.fullmatch(r" +shim +d3d12_xs\.dll!D3D12XboxCreateDevice", line) for line in lines): - problems.append("d3d12_xs.dll!D3D12XboxCreateDevice was not bound to the shim") - try: - entries = parse_trace(lines) - except ValueError as error: - return problems + [str(error)] - bad = [f"{method} {outcome}" for method, outcome in entries if outcome in ("failed", "unsupported", "refused")] - if bad: - problems.append("traced calls that did not succeed: " + ", ".join(bad)) - missing = ordered_subsequence(EXPECTED, [f"{method} {outcome}" for method, outcome in entries]) - if missing: - problems.append(f"the trace has no `{missing}` at its place in the first-frame order") - return problems - - -# Left set in a game's environment, these would put every D3D12 queue of the game on one VkQueue. -QUEUE_TEST_SETTINGS = {"LEONIDA_VK_MAX_QUEUES_PER_FAMILY": "1", "LEONIDA_VK_GRAPHICS_FAMILY_ONLY": "1"} - - -def check_queue_test_settings_ignored(output): - """Problems if the game's device applied a queue test setting instead of saying it ignores it.""" - lines = output.replace("\r\n", "\n").split("\n") - problems = [] - for name in QUEUE_TEST_SETTINGS: - if any(line.startswith(f"[rt] d3d12: {name}: ") for line in lines): - problems.append(f"the game's device applied the test setting {name}") - if not any(line.startswith(f"[rt] d3d12: {name} is a test setting; the game's device ignores it") - for line in lines): - problems.append(f"the game's device did not say it ignores {name}") - return problems - - -def main(): - parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) - parser.add_argument("loader") - parser.add_argument("guest") - parser.add_argument("--probe", help="a Vulkan device test; its exit code 77 skips this test") - parser.add_argument("--queue-test-settings", action="store_true", - help="also set the queue test settings (docs/testing.md), which the game's device must ignore") - parser.add_argument("--runner", action="append", default=[], - help="run Windows executables through this command (repeat for its arguments), e.g. wine") - options = parser.parse_args() - timeout = 180 if options.runner else 90 # a first start of Wine in a fresh prefix can take tens of seconds - - if options.probe: - probe = subprocess.run([*options.runner, options.probe], capture_output=True, timeout=timeout) - if probe.returncode == SKIP: - print("SKIP: no usable Vulkan device (the probe test skipped)") - return SKIP - - environment = dict(os.environ, LEONIDA_D3D12="vulkan") - if options.queue_test_settings: - environment.update(QUEUE_TEST_SETTINGS) - run = subprocess.run([*options.runner, options.loader, "--run", os.path.basename(options.guest), "--trace-d3d12"], - cwd=os.path.dirname(os.path.abspath(options.guest)), env=environment, capture_output=True, - text=True, encoding="utf-8", errors="replace", timeout=timeout) - output = run.stdout + run.stderr - problems = check_output(run.returncode, output) - if options.queue_test_settings: - problems += check_queue_test_settings_ignored(output) - if problems: - print(output) - for problem in problems: - print(f"FAIL: {problem}") - return 1 - print("tiny_frame under gta6rt --run on the Vulkan D3D12 device: OK") - return 0 - - -if __name__ == "__main__": - sys.exit(main()) diff --git a/runtime/test/check_vk_pipeline_cli.cmake b/runtime/test/check_vk_pipeline_cli.cmake deleted file mode 100644 index 525cd6591..000000000 --- a/runtime/test/check_vk_pipeline_cli.cmake +++ /dev/null @@ -1,89 +0,0 @@ -file(MAKE_DIRECTORY "${TEST_DIR}") -file(WRITE "${TEST_DIR}/index.json" "not JSON\n") - -# ${RUNNER} is CMAKE_CROSSCOMPILING_EMULATOR: CTest does not apply it to a script -# test (the command is the host CMake), so the script runs the tool through it itself. -function(check_invalid option) - execute_process(COMMAND ${RUNNER} "${TOOL}" "${TEST_DIR}" "${option}" ${ARGN} - RESULT_VARIABLE code OUTPUT_VARIABLE log ERROR_VARIABLE log TIMEOUT 5) - if(NOT code STREQUAL "2" OR NOT log MATCHES "${option} requires a valid value") - message(FATAL_ERROR "${option} ${ARGN}: expected usage error, got ${code}\n${log}") - endif() -endfunction() - -check_invalid(--count) -check_invalid(--count --compute-only) -check_invalid(--count 18446744073709551616) -check_invalid(--jobs 4294967296) -check_invalid(--start -1) -check_invalid(--max-bytes 1MiB) -check_invalid(--large-module-bytes -1) -check_invalid(--slow nonsense) -check_invalid(--slow nan) -check_invalid(--slow -0.5) -check_invalid(--slow 1.2.3) # strtod must consume the whole token, not just its numeric prefix -check_invalid(--stage --graphics-only) -check_invalid(--stats) - -function(check_protected_input name) - execute_process(COMMAND ${RUNNER} "${TOOL}" "${TEST_DIR}" ${ARGN} - RESULT_VARIABLE code OUTPUT_VARIABLE log ERROR_VARIABLE log TIMEOUT 5) - string(FIND "${log}" "must not overwrite ${name}" found) - if(NOT code STREQUAL "2" OR found EQUAL -1) - message(FATAL_ERROR "${ARGN}: expected input/output path conflict, got ${code}\n${log}") - endif() -endfunction() - -file(WRITE "${TEST_DIR}/skip.txt" "example\n") -file(SHA256 "${TEST_DIR}/index.json" index_before) -file(SHA256 "${TEST_DIR}/skip.txt" skip_before) -check_protected_input("index.json" "${TEST_DIR}/index.json") -check_protected_input("index.json" --stats "${TEST_DIR}/./index.json") -check_protected_input("--skip-file" --skip-file "${TEST_DIR}/skip.txt" --inflight-file "${TEST_DIR}/skip.txt") - -# A hard link has a distinct path even after normalization. Some filesystems cannot create one. -file(CREATE_LINK "${TEST_DIR}/skip.txt" "${TEST_DIR}/skip-link.txt" RESULT hard_link) -if(hard_link STREQUAL "0") - check_protected_input("--skip-file" --skip-file "${TEST_DIR}/skip.txt" --inflight-file "${TEST_DIR}/skip-link.txt") - file(REMOVE "${TEST_DIR}/skip-link.txt") -endif() - -file(SHA256 "${TEST_DIR}/index.json" index_after) -file(SHA256 "${TEST_DIR}/skip.txt" skip_after) -if(NOT index_before STREQUAL index_after OR NOT skip_before STREQUAL skip_after) - message(FATAL_ERROR "Input/output conflicts modified the index or the skip file") -endif() - -execute_process(COMMAND ${RUNNER} "${TOOL}" "${TEST_DIR}" - --jobs 2 --start 3 --count 0 --max-bytes 0 --large-module-bytes 0 - --slow 0.5 --stage cs --stats report.csv - RESULT_VARIABLE code OUTPUT_VARIABLE log ERROR_VARIABLE log TIMEOUT 5) -# The index parser names the file and where it stopped (#1847: "index.json: expected '{' at byte 0"). -if(NOT code STREQUAL "2" OR NOT log MATCHES "index.json: ") - message(FATAL_ERROR "Expected valid arguments to reach the malformed index, got ${code}\n${log}") -endif() - -# A malformed byte count must not reach Vulkan or wrap to an in-range value. -foreach(bytes -1 1.5 4294967296) - file(WRITE "${TEST_DIR}/index.json" "{\"example\":{\"stage\":\"cs\",\"lds_bytes\":${bytes}}}\n") - execute_process(COMMAND ${RUNNER} "${TOOL}" "${TEST_DIR}" - RESULT_VARIABLE code OUTPUT_VARIABLE log ERROR_VARIABLE log TIMEOUT 5) - # The index parser says where it stopped (#1847: "expected unsigned 32-bit lds_bytes at byte 37"). - if(NOT code STREQUAL "2" OR NOT log MATCHES "at byte [0-9]+") - message(FATAL_ERROR "lds_bytes=${bytes}: expected a malformed index, got ${code}\n${log}") - endif() - - file(WRITE "${TEST_DIR}/index.json" "{\"example\":{\"stage\":\"cs\",\"push_constant_bytes\":${bytes}}}\n") - execute_process(COMMAND ${RUNNER} "${TOOL}" "${TEST_DIR}" - RESULT_VARIABLE code OUTPUT_VARIABLE log ERROR_VARIABLE log TIMEOUT 5) - if(NOT code STREQUAL "2" OR NOT log MATCHES "at byte [0-9]+") - message(FATAL_ERROR "push_constant_bytes=${bytes}: expected a malformed index, got ${code}\n${log}") - endif() - - file(WRITE "${TEST_DIR}/index.json" "{\"example\":{\"stage\":\"cs\",\"pc_tail\":{\"set\":1,\"binding\":0,\"bytes\":${bytes}}}}\n") - execute_process(COMMAND ${RUNNER} "${TOOL}" "${TEST_DIR}" - RESULT_VARIABLE code OUTPUT_VARIABLE log ERROR_VARIABLE log TIMEOUT 5) - if(NOT code STREQUAL "2" OR NOT log MATCHES "at byte [0-9]+") - message(FATAL_ERROR "pc_tail.bytes=${bytes}: expected a malformed index, got ${code}\n${log}") - endif() -endforeach() diff --git a/runtime/test/clear_color_test.cpp b/runtime/test/clear_color_test.cpp deleted file mode 100644 index 6f792cd83..000000000 --- a/runtime/test/clear_color_test.cpp +++ /dev/null @@ -1,235 +0,0 @@ -// Value-level replay regression: full and rectangular integer clears must carry integer values, not float bits, -// and normalised clears are rounded to nearest even like D3D (0.5 on 8 bits is 128). -// No Vulkan loader, GPU, shaders or game data. Expected conversions also match the WARP differential GPU tests. -#include "../src/vulkan_replay.h" -#include -#include -#include -#include -#include -#include - -namespace { -VkClearColorValue captured{}; -unsigned calls = 0; -VKAPI_ATTR void VKAPI_CALL barrier(VkCommandBuffer, VkPipelineStageFlags, VkPipelineStageFlags, VkDependencyFlags, - std::uint32_t, const VkMemoryBarrier*, std::uint32_t, const VkBufferMemoryBarrier*, - std::uint32_t, const VkImageMemoryBarrier*) {} -VKAPI_ATTR void VKAPI_CALL clear(VkCommandBuffer, VkImage, VkImageLayout, const VkClearColorValue* color, - std::uint32_t, const VkImageSubresourceRange*) { captured = *color; ++calls; } -VKAPI_ATTR void VKAPI_CALL begin(VkCommandBuffer, const VkRenderingInfo*) {} -VKAPI_ATTR void VKAPI_CALL end(VkCommandBuffer) {} -VKAPI_ATTR void VKAPI_CALL attachments(VkCommandBuffer, std::uint32_t n, const VkClearAttachment* a, - std::uint32_t, const VkClearRect*) { if (n == 1) { captured = a[0].clearValue.color; ++calls; } } - -bool replay_color(VkFormat format, const leonida::ClearColor& color, bool rectangle) { - leonida::CommandList list; - const leonida::Rect rect{1, 1, 3, 3}; - if (!list.clear_render_target({1, 0, 0, 1}, color, - rectangle ? std::span(&rect, 1) : std::span{}) || !list.close()) return false; - leonida::ResourceBinding binding{}; - binding.image = reinterpret_cast(std::uintptr_t{1}); - binding.format = format; - binding.width = binding.height = 4; - leonida::ReplayFunctions vk{}; - vk.pipeline_barrier = barrier; - vk.clear_color_image = clear; - vk.begin_rendering = begin; - vk.end_rendering = end; - vk.clear_attachments = attachments; - vk.image_view = [](const auto&, const auto&) { return reinterpret_cast(std::uintptr_t{1}); }; - calls = 0; - return leonida::replay(list, VK_NULL_HANDLE, [&](auto) { return &binding; }, vk) == leonida::ReplayResult::success && calls == 1; -} - -// Integer RTV format with its component range; A2B10G10R10 has a 2-bit alpha. -struct IntegerFormat { VkFormat format; const char* name; double low, high, alpha_high; bool is_signed; }; - -// Reference conversion measured against WARP: NaN -> 0, clamp to the range, truncate fractions toward zero. -std::uint32_t expected_bits(float input, double low, double high, bool is_signed) { - const double v = double(input); - const double r = v != v ? 0.0 : v <= low ? low : v >= high ? high : std::trunc(v); - return is_signed ? static_cast(static_cast(r)) : static_cast(r); -} -} // namespace - -int main() { - const float nan = std::numeric_limits::quiet_NaN(), inf = std::numeric_limits::infinity(); - const leonida::ClearColor cases[] = { - {1, 2, 3, 4}, - {1.5f, 2.5f, 3.5f, 4.5f}, - {-1, -0.0f, 254.5f, 255.5f}, - {256, 65536, 16777216, 4294967296.0f}, - {nan, inf, -inf, 0.5f}, - {0.499f, 0.501f, 1.499f, 1.501f}, - {4294967040.0f, std::numeric_limits::max(), 255, 0}, - // Component-range boundaries for the 8-, 16-, 10- and 2-bit formats and the signed 32-bit limits. - {127.5f, 128, -128.5f, -129}, - {32767.5f, 32768, -32768.5f, -32769}, - {65535.5f, 65536, 1023.5f, 1024}, - {3.5f, 4, 2147483520.0f, -2147483648.0f}, - }; - constexpr double u32max = 4294967295.0, s32min = -2147483648.0, s32max = 2147483647.0; - const IntegerFormat integer_formats[] = { - {VK_FORMAT_R8_UINT, "R8_UINT", 0, 255, 255, false}, - {VK_FORMAT_R8G8_UINT, "R8G8_UINT", 0, 255, 255, false}, - {VK_FORMAT_R8G8B8A8_UINT, "R8G8B8A8_UINT", 0, 255, 255, false}, - {VK_FORMAT_R16_UINT, "R16_UINT", 0, 65535, 65535, false}, - {VK_FORMAT_R16G16_UINT, "R16G16_UINT", 0, 65535, 65535, false}, - {VK_FORMAT_R16G16B16A16_UINT, "R16G16B16A16_UINT", 0, 65535, 65535, false}, - {VK_FORMAT_R32_UINT, "R32_UINT", 0, u32max, u32max, false}, - {VK_FORMAT_R32G32_UINT, "R32G32_UINT", 0, u32max, u32max, false}, - {VK_FORMAT_R32G32B32A32_UINT, "R32G32B32A32_UINT", 0, u32max, u32max, false}, - {VK_FORMAT_A2B10G10R10_UINT_PACK32, "A2B10G10R10_UINT_PACK32", 0, 1023, 3, false}, - {VK_FORMAT_R8_SINT, "R8_SINT", -128, 127, 127, true}, - {VK_FORMAT_R8G8_SINT, "R8G8_SINT", -128, 127, 127, true}, - {VK_FORMAT_R8G8B8A8_SINT, "R8G8B8A8_SINT", -128, 127, 127, true}, - {VK_FORMAT_R16_SINT, "R16_SINT", -32768, 32767, 32767, true}, - {VK_FORMAT_R16G16_SINT, "R16G16_SINT", -32768, 32767, 32767, true}, - {VK_FORMAT_R16G16B16A16_SINT, "R16G16B16A16_SINT", -32768, 32767, 32767, true}, - {VK_FORMAT_R32_SINT, "R32_SINT", s32min, s32max, s32max, true}, - {VK_FORMAT_R32G32_SINT, "R32G32_SINT", s32min, s32max, s32max, true}, - {VK_FORMAT_R32G32B32A32_SINT, "R32G32B32A32_SINT", s32min, s32max, s32max, true}, - }; - unsigned checks = 0, failed_formats = 0; - for (const auto& f : integer_formats) { - bool format_ok = true; - unsigned case_index = 0; - for (const auto& c : cases) { - for (const bool rect : {false, true}) { - if (!replay_color(f.format, c, rect)) { - std::fprintf(stderr, "%s: replay failed (case %u rect %d)\n", f.name, case_index, int(rect)); - return 1; - } - for (unsigned i = 0; i < 4 && format_ok; ++i) { - const std::uint32_t expected = expected_bits(c[i], f.low, i == 3 ? f.alpha_high : f.high, f.is_signed); - if (captured.uint32[i] != expected) { - std::fprintf(stderr, "integer clear %s case %u rect %d channel %u: got 0x%08x, expected 0x%08x\n", - f.name, case_index, int(rect), i, captured.uint32[i], expected); - format_ok = false; - } - } - if (!format_ok) break; - ++checks; - } - if (!format_ok) break; - ++case_index; - } - if (!format_ok) ++failed_formats; - } - for (const auto& c : cases) { - for (const VkFormat format : {VK_FORMAT_R32_SFLOAT, VK_FORMAT_R16G16B16A16_SFLOAT}) { - for (const bool rect : {false, true}) { - if (!replay_color(format, c, rect) || std::memcmp(captured.float32, c.data(), sizeof(captured)) != 0) { - std::fprintf(stderr, "float clear: format %d rect %d changed the value\n", int(format), int(rect)); - return 1; - } - ++checks; - } - } - } - // Normalised formats: D3D rounds to nearest even, the clamp and NaN rules are 0..1 and 0, and an exact tie goes to - // the even neighbour. NVIDIA rounds 0.5 on 8 bits down to 127 by itself, so the value is rounded before Vulkan sees it. - struct Norm { - VkFormat format; - leonida::ClearColor color; - std::array steps; // what D3D writes, in units of the channel's largest value - std::array maximum; - }; - const Norm norms[] = { - {VK_FORMAT_R8G8B8A8_UNORM, {0.5f, 0.499f, 0.501f, 1.0f}, {128, 127, 128, 255}, {255, 255, 255, 255}}, - {VK_FORMAT_B8G8R8A8_UNORM, {-1, 2, nan, 0.5f}, {0, 255, 0, 128}, {255, 255, 255, 255}}, - {VK_FORMAT_R8G8_UNORM, {0.5f, 1.5f, 0, 0}, {128, 255, 0, 0}, {255, 255, 255, 255}}, - {VK_FORMAT_A2B10G10R10_UNORM_PACK32, {0.5f, 0.5f, 0.5f, 0.5f}, {512, 512, 512, 2}, {1023, 1023, 1023, 3}}, - {VK_FORMAT_R16G16B16A16_UNORM, {0.5f, 0.25f, 0.75f, 1.0f}, {32768, 16384, 49151, 65535}, - {65535, 65535, 65535, 65535}}, - {VK_FORMAT_R8G8B8A8_SRGB, {0.2f, 0.7f, 0.5f, 0.5f}, {0, 0, 0, 128}, {0, 0, 0, 255}}, // colour: the GPU's sRGB curve - {VK_FORMAT_B8G8R8A8_SRGB, {0.5f, 0.25f, 0.75f, 0.499f}, {0, 0, 0, 127}, {0, 0, 0, 255}}, - {VK_FORMAT_R16_UNORM, {0.5f, 0, 0, 0}, {32768, 0, 0, 0}, {65535, 65535, 65535, 65535}}, - // Signed normalised: -1.0 is -127 (-32767), the scale is 127 (32767) and ties go to the even neighbour. - {VK_FORMAT_R8G8B8A8_SNORM, {-1, -0.5f, 0.5f, 1}, {-127, -64, 64, 127}, {127, 127, 127, 127}}, - {VK_FORMAT_R8G8_SNORM, {nan, inf, -inf, -0.5f}, {0, 127, -127, -64}, {127, 127, 127, 127}}, - {VK_FORMAT_R16G16B16A16_SNORM, {-2, 2, 0.001f, -0.001f}, {-32767, 32767, 33, -33}, - {32767, 32767, 32767, 32767}}, - }; - for (const auto& n : norms) { - for (const bool rect : {false, true}) { - if (!replay_color(n.format, n.color, rect)) return 1; - for (unsigned i = 0; i < 4; ++i) { - const float expected = n.maximum[i] != 0.0 ? static_cast(double(n.steps[i]) / n.maximum[i]) : n.color[i]; - if (captured.float32[i] != expected) { - std::fprintf(stderr, "normalised clear: format %d rect %d channel %u: got %.9g, expected %.9g\n", - int(n.format), int(rect), i, double(captured.float32[i]), double(expected)); - return 1; - } - } - ++checks; - } - } - // The other integer formats clamp to the component range and truncate toward zero (what WARP writes). - struct Integer { - VkFormat format; - leonida::ClearColor color; - std::array expected; - }; - const Integer integers[] = { - {VK_FORMAT_R8_SINT, {-1.5f, -2.5f, 2.5f, 3.5f}, {-1, -2, 2, 3}}, - {VK_FORMAT_R8G8B8A8_SINT, {-129, 128, -32769, 32768}, {-128, 127, -128, 127}}, - {VK_FORMAT_R8G8B8A8_SINT, {2147483648.0f, -2147483904.0f, nan, inf}, {127, -128, 0, 127}}, - {VK_FORMAT_R16_SINT, {-129, 128, -32769, 32768}, {-129, 128, -32768, 32767}}, - {VK_FORMAT_R32_SINT, {-129, 128, -32769, 32768}, {-129, 128, -32769, 32768}}, - {VK_FORMAT_R32_SINT, {2147483648.0f, -2147483904.0f, nan, inf}, {2147483647, -2147483647 - 1, 0, 2147483647}}, - {VK_FORMAT_R32G32B32A32_SINT, {-inf, 0.5f, -0.5f, 100000.0f}, {-2147483647 - 1, 0, 0, 100000}}, - {VK_FORMAT_R8_UINT, {256, 1.5f, -1, nan}, {255, 1, 0, 0}}, - {VK_FORMAT_R16_UINT, {65536, 65535.5f, -0.0f, 2.5f}, {65535, 65535, 0, 2}}, - {VK_FORMAT_R8G8_UINT, {256, 1.5f, -1, nan}, {255, 1, 0, 0}}, - {VK_FORMAT_R16G16_SINT, {-32769, 32768, -1.5f, nan}, {-32768, 32767, -1, 0}}, - {VK_FORMAT_R16G16B16A16_UINT, {65536, 65535.5f, -0.0f, 2.5f}, {65535, 65535, 0, 2}}, - // R10G10B10A2_UINT: each channel clamps to its own width, 10, 10, 10 and 2 bits. - {VK_FORMAT_A2B10G10R10_UINT_PACK32, {1023.5f, 2000, 1024, 4}, {1023, 1023, 1023, 3}}, - {VK_FORMAT_A2B10G10R10_UINT_PACK32, {5.5f, 1.5f, 1022.5f, 2.5f}, {5, 1, 1022, 2}}, - }; - for (const auto& c : integers) { - for (const bool rect : {false, true}) { - if (!replay_color(c.format, c.color, rect)) return 1; - for (unsigned i = 0; i < 4; ++i) { - if (captured.int32[i] != c.expected[i]) { - std::fprintf(stderr, "integer clear: format %d rect %d channel %u: got %d, expected %d\n", - int(c.format), int(rect), i, captured.int32[i], c.expected[i]); - return 1; - } - } - ++checks; - } - } - // Ties go to even whatever the thread's floating-point rounding mode (std::nearbyint would follow it: 127.5 is - // 127 when rounding down). Converted under each mode, checked after the default mode is back. - { - const int mode = std::fegetround(); - VkClearColorValue unorm[3]{}, snorm[3]{}; - const int modes[3] = {FE_DOWNWARD, FE_UPWARD, FE_TOWARDZERO}; - for (int m = 0; m < 3; ++m) { - std::fesetround(modes[m]); - unorm[m] = leonida::detail::render_target_clear_color(VK_FORMAT_R8G8B8A8_UNORM, {0.5f, 0.5f, 0.5f, 0.5f}); - snorm[m] = leonida::detail::render_target_clear_color(VK_FORMAT_R8G8B8A8_SNORM, {-0.5f, 0.5f, -0.5f, 0.5f}); - } - std::fesetround(mode); - for (int m = 0; m < 3; ++m) { - const long u = std::lround(double(unorm[m].float32[0]) * 255.0); - const long s0 = std::lround(double(snorm[m].float32[0]) * 127.0); - const long s1 = std::lround(double(snorm[m].float32[1]) * 127.0); - if (u != 128 || s0 != -64 || s1 != 64) { - std::fprintf(stderr, "tie rounding under FP mode %d: UNORM %ld (128), SNORM %ld %ld (-64 64)\n", - modes[m], u, s0, s1); - return 1; - } - ++checks; - } - } - if (failed_formats) { - std::fprintf(stderr, "clear_color_test: %u integer format(s) failed\n", failed_formats); - return 1; - } - std::printf("clear_color_test: %u full/rectangle integer, normalised and float replay checks passed\n", checks); - return 0; -} diff --git a/runtime/test/code_hooks_test.cpp b/runtime/test/code_hooks_test.cpp deleted file mode 100644 index 39efb9be1..000000000 --- a/runtime/test/code_hooks_test.cpp +++ /dev/null @@ -1,373 +0,0 @@ -// code_hooks.h: a remapping thunk and direct-call redirection, on small x64 functions written into memory. No game -// files: the archetype lookup they stand in for takes its model hash in ecx (docs/modding.md). -#include "../src/code_hooks.h" -#include "../src/mods.h" - -#include -#include -#include -#include - -namespace { - -int g_checks = 0, g_failures = 0; - -void check(bool ok, const char* what) { - ++g_checks; - if (!ok) { - ++g_failures; - std::printf("FAIL %s\n", what); - } -} - -uint32_t remap_lucia(uint32_t hash) { - return hash == leonida::mods::joaat("player_story000_00") ? leonida::mods::joaat("cs_mandy") : hash; -} - -void put(uint8_t* at, std::initializer_list bytes) { - for (uint8_t b : bytes) *at++ = b; -} - -// `call rel32` (or `jmp` with e9) at `at` towards `to`. -void branch(uint8_t* at, uint8_t opcode, const uint8_t* to) { - at[0] = opcode; - const int32_t rel = static_cast(to - (at + 5)); - std::memcpy(at + 1, &rel, 4); -} - -// sub rsp,0x28 / call to / add rsp,0x28 / ret -void caller(uint8_t* at, const uint8_t* to) { - put(at, {0x48, 0x83, 0xEC, 0x28}); - branch(at + 4, 0xE8, to); - put(at + 9, {0x48, 0x83, 0xC4, 0x28, 0xC3}); -} - -void init_pe64(uint8_t* img, uint32_t size_of_image, const std::vector& sections) { - auto* dos = reinterpret_cast(img); - dos->e_magic = IMAGE_DOS_SIGNATURE; - dos->e_lfanew = 0x80; - auto* nt = reinterpret_cast(img + dos->e_lfanew); - nt->Signature = IMAGE_NT_SIGNATURE; - nt->FileHeader.Machine = IMAGE_FILE_MACHINE_AMD64; - nt->FileHeader.NumberOfSections = static_cast(sections.size()); - nt->FileHeader.SizeOfOptionalHeader = sizeof(IMAGE_OPTIONAL_HEADER64); - nt->OptionalHeader.Magic = IMAGE_NT_OPTIONAL_HDR64_MAGIC; - nt->OptionalHeader.SizeOfImage = size_of_image; - IMAGE_SECTION_HEADER* sec = IMAGE_FIRST_SECTION(nt); - for (std::size_t i = 0; i < sections.size(); ++i) sec[i] = sections[i]; -} - -// Real functions for the unwinding checks: an exception leaves the hooked function, or the callback. -uint32_t throw_on_seven(uint32_t value) { - if (value == 7) throw std::runtime_error("seven"); - return value + 1; -} - -uint32_t throw_on_seven_result(uint32_t result, uint32_t argument) { - if (argument == 8) throw std::runtime_error("eight"); - return result * 100 + argument; -} - -// Leaves no return address of an earlier call where an unwinder that reads the wrong slot could find one. -void dirty_stack() { - volatile unsigned char bytes[8192]; - for (auto& b : bytes) b = 0xAB; -} - -bool caught_through(const uint8_t* thunk, uint32_t argument) { - dirty_stack(); - try { - reinterpret_cast(const_cast(thunk))(argument); - } catch (const std::runtime_error&) { - return true; - } - return false; -} - -// Unwinds one frame from inside `thunk`, where its call returns to (`return_offset`, after a prolog that moved rsp by -// `frame` bytes), and says whether the caller's rip and rsp come out. -bool unwinds_to_caller(uint8_t* thunk, std::size_t return_offset, std::size_t frame) { - alignas(16) uint64_t stack[64] = {}; - const uint64_t caller_rip = 0x1234567890ull; - uint64_t* at_entry = stack + 40; // rsp when the thunk is entered: the return address - *at_entry = caller_rip; - CONTEXT context{}; - context.ContextFlags = CONTEXT_CONTROL | CONTEXT_INTEGER; - context.Rip = reinterpret_cast(thunk + return_offset); - context.Rsp = reinterpret_cast(at_entry) - frame; - DWORD64 base = 0, establisher = 0; - PRUNTIME_FUNCTION function = RtlLookupFunctionEntry(context.Rip, &base, nullptr); - if (!function || base != reinterpret_cast(thunk)) return false; - void* handler_data = nullptr; - RtlVirtualUnwind(UNW_FLAG_NHANDLER, base, context.Rip, function, &context, &handler_data, &establisher, nullptr); - return context.Rip == caller_rip && context.Rsp == reinterpret_cast(at_entry + 1); -} - -// The offset just after the first `call rax` (FF D0) of a thunk. -std::size_t after_first_call(const uint8_t* thunk) { - for (std::size_t i = 0; i + 1 < 256; ++i) - if (thunk[i] == 0xFF && thunk[i + 1] == 0xD0) return i + 2; - return 0; -} - -} // namespace - -int main() { - using namespace leonida::hooks; - std::setvbuf(stdout, nullptr, _IONBF, 0); - uint8_t* mem = alloc_near(reinterpret_cast(&remap_lucia), 4096); - check(mem != nullptr, "executable memory near the module"); - if (!mem) return 1; - std::memset(mem, 0xCC, 4096); - - uint8_t* target0 = mem; // returns its first argument: mov eax, ecx ; ret - put(target0, {0x89, 0xC8, 0xC3}); - uint8_t* target1 = mem + 16; // returns its second argument: mov eax, edx ; ret - put(target1, {0x89, 0xD0, 0xC3}); - uint8_t* target2 = mem + 32; // returns its third argument: mov eax, r8d ; ret - put(target2, {0x44, 0x89, 0xC0, 0xC3}); - - uint8_t* call0 = mem + 64; - caller(call0, target0); - uint8_t* tail0 = mem + 96; // jmp target0 (a tail call) - branch(tail0, 0xE9, target0); - uint8_t* decoy = mem + 112; // a call to target0 + 1: not the hooked function, must stay as it is - caller(decoy, target0 + 1); - uint8_t* call1 = mem + 144; - caller(call1, target1); - uint8_t* call2 = mem + 176; - caller(call2, target2); - uint8_t decoy_before[16]; - std::memcpy(decoy_before, decoy, 16); - - uint8_t* thunk0 = make_remap_thunk(target0, 0, &remap_lucia, target0); - uint8_t* thunk1 = make_remap_thunk(target1, 1, &remap_lucia, target1); - uint8_t* thunk2 = make_remap_thunk(target2, 0, &remap_lucia, target2); - check(thunk0 && thunk1 && thunk2, "thunks are allocated near their targets"); - if (!thunk0 || !thunk1 || !thunk2) return 1; - - const std::size_t n0 = redirect_direct_branches(mem + 64, 112, target0, thunk0); - const std::size_t n1 = redirect_direct_branches(call1, 16, target1, thunk1); - const std::size_t n2 = redirect_direct_branches(call2, 16, target2, thunk2); - check(n0 == 2, "the call and the tail jump to the function are redirected, the decoy is not"); - check(n1 == 1 && n2 == 1, "one call each in the other callers"); - check(std::memcmp(decoy, decoy_before, 16) == 0, "a branch to another address is left byte for byte"); - FlushInstructionCache(GetCurrentProcess(), mem, 4096); - - using Fn1 = uint32_t (*)(uint32_t); - using Fn2 = uint32_t (*)(uint64_t, uint32_t); - using Fn3 = uint32_t (*)(uint32_t, uint32_t, uint32_t); - const uint32_t lucia = 0xE472B687u, mandy = 0xD7C0CDFFu; - check(reinterpret_cast(call0)(lucia) == mandy, "through the call, Lucia's model id becomes cs_mandy's"); - check(reinterpret_cast(call0)(1234) == 1234, "any other id passes through unchanged"); - check(reinterpret_cast(tail0)(lucia) == mandy, "a tail jump is remapped as well"); - check(reinterpret_cast(call1)(0x1111, lucia) == mandy, "argument 1 (edx) is remapped when asked"); - check(reinterpret_cast(call2)(lucia, 2, 777) == 777, "r8 reaches the original unchanged"); - - // hook_image_calls refuses what is not a mapped image or not code - check(!hook_image_calls(mem, 0, &remap_lucia, 0).ok, "memory without a PE header is refused"); - auto* self = reinterpret_cast(GetModuleHandleW(nullptr)); - check(!hook_image_calls(self, 0x7FFFFFF0u, &remap_lucia, 0).ok, "an RVA outside the image is refused"); - check(!hook_image_calls(self, 0, &remap_lucia, 0).ok, "an RVA in the headers (not code) is refused"); - check(!make_remap_thunk(target0, 2, &remap_lucia, target0), "only argument 0 or 1 can be remapped"); - - // The result-override thunk (a view-mode getter): the original returns 2 ("third person, far") for every - // context; the override answers 4 ("first person") for context 0 only and leaves the others as they were. - uint8_t* getter = mem + 512; - put(getter, {0xB8, 0x02, 0x00, 0x00, 0x00, 0xC3}); // mov eax, 2 ; ret - uint8_t* call_getter = mem + 544; - caller(call_getter, getter); - static int original_calls = 0; - auto first_person_on_foot = [](uint32_t result, uint32_t context) -> uint32_t { - ++original_calls; - return context == 0 ? 4u : result; - }; - uint8_t* rthunk = make_result_thunk(getter, first_person_on_foot, getter); - check(rthunk != nullptr, "a result thunk is allocated"); - if (rthunk) { - check(redirect_direct_branches(call_getter, 16, getter, rthunk) == 1, "the getter's caller is redirected"); - FlushInstructionCache(GetCurrentProcess(), mem, 4096); - using Ctx = uint32_t (*)(uint32_t); - check(reinterpret_cast(call_getter)(0) == 4, "context 0 gets the overridden result"); - check(reinterpret_cast(call_getter)(3) == 2, "another context keeps the original's result"); - check(original_calls == 2, "the override sees every call, after the original ran"); - } - check(!hook_image_results(mem, 0, first_person_on_foot).ok, "hook_image_results refuses memory without a PE"); - - // Test A: PE64 executable section with Misc.VirtualSize == 0 falls back to SizeOfRawData (matching pe_loader.cpp). - uint8_t* img_a = alloc_near(reinterpret_cast(&remap_lucia), 0x2000); - check(img_a != nullptr, "synthetic PE64 image A allocated near module"); - if (img_a) { - std::memset(img_a, 0, 0x2000); - IMAGE_SECTION_HEADER sec_a{}; - std::memcpy(sec_a.Name, ".text", 5); - sec_a.Misc.VirtualSize = 0; - sec_a.VirtualAddress = 0x1000; - sec_a.SizeOfRawData = 0x200; - sec_a.Characteristics = IMAGE_SCN_MEM_EXECUTE | IMAGE_SCN_CNT_CODE; - init_pe64(img_a, 0x2000, {sec_a}); - put(img_a + 0x1000, {0x89, 0xC8, 0xC3}); // mov eax, ecx ; ret - caller(img_a + 0x1020, img_a + 0x1000); - DWORD old_a = 0; - check(VirtualProtect(img_a + 0x1000, 0x1000, PAGE_EXECUTE_READ, &old_a) != FALSE, - "image A code page marked PAGE_EXECUTE_READ"); - FlushInstructionCache(GetCurrentProcess(), img_a + 0x1000, 0x1000); - - const HookResult ra = hook_image_calls(img_a, 0x1000, &remap_lucia, 0); - check(ra.ok && ra.redirected == 1, - "VirtualSize == 0 executable section uses SizeOfRawData and redirects its caller"); - if (ra.ok) { - check(reinterpret_cast(img_a + 0x1020)(lucia) == mandy, - "hooked caller in VirtualSize == 0 section remaps Lucia to Mandy"); - check(reinterpret_cast(img_a + 0x1020)(1234) == 1234, - "hooked caller in VirtualSize == 0 section passes other hashes through"); - } - } - - // Test B: a 0-byte executable section (VirtualSize == 0 && SizeOfRawData == 0) is skipped rather than failing VirtualProtect. - uint8_t* img_b = alloc_near(reinterpret_cast(&remap_lucia), 0x2000); - check(img_b != nullptr, "synthetic PE64 image B allocated near module"); - if (img_b) { - std::memset(img_b, 0, 0x2000); - IMAGE_SECTION_HEADER sec_empty{}; - std::memcpy(sec_empty.Name, ".empty", 6); - sec_empty.Misc.VirtualSize = 0; - sec_empty.VirtualAddress = 0x1000; - sec_empty.SizeOfRawData = 0; - sec_empty.Characteristics = IMAGE_SCN_MEM_EXECUTE; - IMAGE_SECTION_HEADER sec_text{}; - std::memcpy(sec_text.Name, ".text", 5); - sec_text.Misc.VirtualSize = 0x200; - sec_text.VirtualAddress = 0x1000; - sec_text.SizeOfRawData = 0x200; - sec_text.Characteristics = IMAGE_SCN_MEM_EXECUTE | IMAGE_SCN_CNT_CODE; - init_pe64(img_b, 0x2000, {sec_empty, sec_text}); - put(img_b + 0x1040, {0xB8, 0x02, 0x00, 0x00, 0x00, 0xC3}); // mov eax, 2 ; ret - caller(img_b + 0x1060, img_b + 0x1040); - DWORD old_b = 0; - check(VirtualProtect(img_b + 0x1000, 0x1000, PAGE_EXECUTE_READ, &old_b) != FALSE, - "image B code page marked PAGE_EXECUTE_READ"); - FlushInstructionCache(GetCurrentProcess(), img_b + 0x1000, 0x1000); - - const int before_calls = original_calls; - const HookResult rb = hook_image_results(img_b, 0x1040, first_person_on_foot); - check(rb.ok && rb.redirected == 1, - "0-byte executable section is skipped and the non-empty section is hooked"); - if (rb.ok) { - using Ctx = uint32_t (*)(uint32_t); - check(reinterpret_cast(img_b + 0x1060)(0) == 4, - "result hook in PE64 image overrides context 0"); - check(reinterpret_cast(img_b + 0x1060)(3) == 2, - "result hook in PE64 image preserves non-overridden contexts"); - check(original_calls == before_calls + 2, - "result hook invokes the original getter on each call"); - } - } - - // Test C: sections extending past SizeOfImage are clamped and 32-bit VirtualAddress + VirtualSize wraparound is safe. - uint8_t* img_c = alloc_near(reinterpret_cast(&remap_lucia), 0x2000); - check(img_c != nullptr, "synthetic PE64 image C allocated near module"); - if (img_c) { - std::memset(img_c, 0, 0x2000); - IMAGE_SECTION_HEADER sec_wrap{}; - std::memcpy(sec_wrap.Name, ".wrap", 5); - sec_wrap.Misc.VirtualSize = 0x200u; - sec_wrap.VirtualAddress = 0xFFFFFF00u; - sec_wrap.Characteristics = IMAGE_SCN_MEM_EXECUTE; - IMAGE_SECTION_HEADER sec_over{}; - std::memcpy(sec_over.Name, ".text", 5); - sec_over.Misc.VirtualSize = 0x1800u; // spans 0x0800..0x2000, past SizeOfImage = 0x1000 - sec_over.VirtualAddress = 0x0800u; - sec_over.Characteristics = IMAGE_SCN_MEM_EXECUTE | IMAGE_SCN_CNT_CODE; - init_pe64(img_c, 0x1000, {sec_wrap, sec_over}); - put(img_c + 0x0800, {0x89, 0xC8, 0xC3}); // mov eax, ecx ; ret - caller(img_c + 0x0820, img_c + 0x0800); // in-image caller - caller(img_c + 0x1020, img_c + 0x0800); // out-of-image bytes past SizeOfImage - uint8_t out_before[16]; - std::memcpy(out_before, img_c + 0x1020, sizeof(out_before)); - FlushInstructionCache(GetCurrentProcess(), img_c, 0x2000); - - const HookResult rc = hook_image_calls(img_c, 0x0800, &remap_lucia, 0); - check(rc.ok && rc.redirected == 1, - "section past SizeOfImage is clamped and wraparound section is ignored"); - if (rc.ok) { - check(reinterpret_cast(img_c + 0x0820)(lucia) == mandy, - "in-image caller inside clamped section is remapped"); - check(std::memcmp(img_c + 0x1020, out_before, sizeof(out_before)) == 0, - "bytes beyond SizeOfImage are left untouched"); - } - } - - // Test D: malformed headers, PE32 optional header, out-of-image section table, and null arguments/callbacks. - uint8_t* bad = static_cast(VirtualAlloc(nullptr, 0x1000, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE)); - check(bad != nullptr, "scratch buffer for malformed PE checks allocated"); - if (bad) { - std::memset(bad, 0, 0x1000); - auto* bad_dos = reinterpret_cast(bad); - bad_dos->e_magic = IMAGE_DOS_SIGNATURE; - bad_dos->e_lfanew = 0; - check(!hook_image_calls(bad, 0x200, &remap_lucia, 0).ok, "MZ with e_lfanew == 0 is refused"); - bad_dos->e_lfanew = -16; - check(!hook_image_calls(bad, 0x200, &remap_lucia, 0).ok, "MZ with negative e_lfanew is refused"); - - std::memset(bad, 0, 0x1000); - init_pe64(bad, 0x1000, {}); - auto* bad_nt = reinterpret_cast(bad + 0x80); - bad_nt->OptionalHeader.Magic = IMAGE_NT_OPTIONAL_HDR32_MAGIC; - check(!hook_image_calls(bad, 0x200, &remap_lucia, 0).ok, "PE32 optional header magic is refused"); - - std::memset(bad, 0, 0x1000); - init_pe64(bad, 0x200, {}); - bad_nt->FileHeader.NumberOfSections = 100; - check(!hook_image_calls(bad, 0x100, &remap_lucia, 0).ok, - "section table extending past SizeOfImage is refused"); - VirtualFree(bad, 0, MEM_RELEASE); - } - - if (img_a) { - check(!hook_image_calls(img_a, 0x1000, nullptr, 0).ok, "hook_image_calls refuses null callback"); - VirtualFree(img_a, 0, MEM_RELEASE); - } - if (img_b) { - check(!hook_image_results(img_b, 0x1040, nullptr).ok, "hook_image_results refuses null callback"); - VirtualFree(img_b, 0, MEM_RELEASE); - } - if (img_c) VirtualFree(img_c, 0, MEM_RELEASE); - - check(!hook_image_calls(nullptr, 0x1000, &remap_lucia, 0).ok, "hook_image_calls refuses null base"); - check(!hook_image_results(nullptr, 0x1000, first_person_on_foot).ok, "hook_image_results refuses null base"); - check(make_remap_thunk(target0, 0, nullptr, target0) == nullptr, "make_remap_thunk refuses null callback"); - check(make_remap_thunk(nullptr, 0, &remap_lucia, target0) == nullptr, "make_remap_thunk refuses null close_to"); - check(make_result_thunk(getter, nullptr, getter) == nullptr, "make_result_thunk refuses null callback"); - check(make_result_thunk(getter, first_person_on_foot, nullptr) == nullptr, - "make_result_thunk refuses null original"); - check(redirect_direct_branches(nullptr, 16, target0, thunk0) == 0, - "redirect_direct_branches returns 0 for null begin"); - VirtualFree(mem, 0, MEM_RELEASE); - - // Stack walks and exceptions pass through both thunks. - const auto* throwing = reinterpret_cast(&throw_on_seven); - uint8_t* unwind_result = make_result_thunk(throwing, &throw_on_seven_result, throwing); - uint8_t* unwind_remap = make_remap_thunk(throwing, 0, &throw_on_seven, throwing); - check(unwind_result && unwind_remap, "thunks for the unwinding checks"); - if (unwind_result && unwind_remap) { - check(reinterpret_cast(unwind_result)(1) == 201, "the result thunk still works"); - check(reinterpret_cast(unwind_remap)(1) == 3, "the remap thunk still works"); - check(unwinds_to_caller(unwind_result, after_first_call(unwind_result), 0x28), - "a stack walk from the hooked function reaches the result thunk's caller"); - check(unwinds_to_caller(unwind_remap, after_first_call(unwind_remap), 0x88), - "a stack walk from the callback reaches the remap thunk's caller"); - check(caught_through(unwind_result, 7), "an exception leaves the hooked function through the result thunk"); - check(caught_through(unwind_result, 8), "an exception leaves the callback through the result thunk"); - check(caught_through(unwind_remap, 7), "an exception leaves the callback through the remap thunk"); - const DWORD64 freed = reinterpret_cast(unwind_result) + 1; - DWORD64 base = 0; - free_thunk(unwind_result); - check(RtlLookupFunctionEntry(freed, &base, nullptr) == nullptr, "a freed thunk leaves no function table"); - free_thunk(unwind_remap); - } - free_thunk(nullptr); - - std::printf("code_hooks_test: %d checks, %d failures\n", g_checks, g_failures); - return g_failures == 0 ? 0 : 1; -} diff --git a/runtime/test/com_shim_test.cpp b/runtime/test/com_shim_test.cpp deleted file mode 100644 index 2ed849f78..000000000 --- a/runtime/test/com_shim_test.cpp +++ /dev/null @@ -1,172 +0,0 @@ -// Tests for runtime/shims/com_shim.cpp through rt::shims::find. -#include -#include -#include - -#include -#include -#include -#include - -#include "shims.h" - -namespace { - -using CoInitExFn = HRESULT(WINAPI*)(LPVOID, DWORD); -using CoUninitFn = void(WINAPI*)(); -using CoCreateInstFn = HRESULT(WINAPI*)(REFCLSID, LPUNKNOWN, DWORD, REFIID, LPVOID*); -using CoCreateGuidFn = HRESULT(WINAPI*)(GUID*); -using CoTaskMemFreeFn = void(WINAPI*)(LPVOID); -using PropVarClearFn = HRESULT(WINAPI*)(PROPVARIANT*); -using StringFromGuid2Fn = int(WINAPI*)(REFGUID, LPOLESTR, int); - -int g_checks = 0; -int g_failures = 0; - -void check(bool condition, const char* what) { - ++g_checks; - std::printf("%s %s\n", condition ? "PASS" : "FAIL", what); - if (!condition) ++g_failures; -} - -template -Fn resolve(const char* name) { - return reinterpret_cast(rt::shims::find("api-ms-win-core-com-l1-1-0.dll", name)); -} - -void test_registry_coverage() { - for (const char* dll : {"api-ms-win-core-com-l1-1-0.dll", "api-ms-win-core-com-l1-1-1.dll", - "api-ms-win-core-com-l1-1-2.dll", "api-ms-win-core-com-l1-1-3.dll"}) { - check(rt::shims::find(dll, "CoInitializeEx") != nullptr, "CoInitializeEx resolves"); - check(rt::shims::find(dll, "CoUninitialize") != nullptr, "CoUninitialize resolves"); - check(rt::shims::find(dll, "CoCreateInstance") != nullptr, "CoCreateInstance resolves"); - check(rt::shims::find(dll, "CoCreateGuid") != nullptr, "CoCreateGuid resolves"); - check(rt::shims::find(dll, "CoTaskMemFree") != nullptr, "CoTaskMemFree resolves"); - check(rt::shims::find(dll, "PropVariantClear") != nullptr, "PropVariantClear resolves"); - check(rt::shims::find(dll, "StringFromGUID2") != nullptr, "StringFromGUID2 resolves"); - } - check(!rt::shims::owns_dll("ole32.dll"), "ole32.dll stays host-owned"); - check(!rt::shims::owns_dll("api-ms-win-core-com-l1-1-0.dll"), "api-ms-win-core-com-l1-1-0.dll is not pseudo-owned"); -} - -void test_com_lifecycle_and_sta_isolation() { - auto co_init = resolve("CoInitializeEx"); - auto co_uninit = resolve("CoUninitialize"); - - // 1. Fresh thread: MTA init + nested MTA + intra-guest mismatch -> RPC_E_CHANGED_MODE + clean unwind. - bool fresh_ok = false; - std::thread([&]() { - int dummy = 1; - const HRESULT bad_res = co_init(&dummy, COINIT_MULTITHREADED); - const HRESULT r1 = co_init(nullptr, COINIT_MULTITHREADED); - const HRESULT r2 = co_init(nullptr, COINIT_MULTITHREADED); - const HRESULT r_mix = co_init(nullptr, COINIT_APARTMENTTHREADED); - co_uninit(); - co_uninit(); - co_uninit(); // extra unbalanced uninit must be ignored safely - // Host COM should now be uninitialized again on this thread; CoInitializeEx(STA) must return S_OK. - const HRESULT host_after = ::CoInitializeEx(nullptr, COINIT_APARTMENTTHREADED); - if (SUCCEEDED(host_after)) ::CoUninitialize(); - fresh_ok = (bad_res == E_INVALIDARG && r1 == S_OK && r2 == S_FALSE && r_mix == RPC_E_CHANGED_MODE && - host_after == S_OK); - }).join(); - check(fresh_ok, "fresh thread balances guest COM without leaking or corrupting host apartment"); - - // 2. Host pre-initialized as STA: guest requests MTA -> shim absorbs RPC_E_CHANGED_MODE, retains host apartment - // reference so guest outlives host teardown cleanly, and accepts matching STA on the real STA thread. - bool mismatch_ok = false; - std::thread([&]() { - const HRESULT host_sta = ::CoInitializeEx(nullptr, COINIT_APARTMENTTHREADED); - const HRESULT g1 = co_init(nullptr, COINIT_MULTITHREADED); - const HRESULT g_sta = co_init(nullptr, COINIT_APARTMENTTHREADED); - const HRESULT g2 = co_init(nullptr, COINIT_MULTITHREADED); - co_uninit(); - co_uninit(); - co_uninit(); - // Host STA must STILL be active on this thread (second host STA init must return S_FALSE, not S_OK!). - const HRESULT host_still_sta = ::CoInitializeEx(nullptr, COINIT_APARTMENTTHREADED); - if (SUCCEEDED(host_still_sta)) ::CoUninitialize(); - if (SUCCEEDED(host_sta)) ::CoUninitialize(); - mismatch_ok = - (host_sta == S_OK && g1 == S_OK && g_sta == S_FALSE && g2 == S_FALSE && host_still_sta == S_FALSE); - }).join(); - check(mismatch_ok, "guest MTA under host STA avoids RPC_E_CHANGED_MODE and keeps host STA alive"); - - // 3. Host-first teardown while guest COM initialization remains active (regression for #9516 review). - auto create_inst = resolve("CoCreateInstance"); - bool host_first_teardown_ok = false; - std::thread([&]() { - const HRESULT host_sta = ::CoInitializeEx(nullptr, COINIT_APARTMENTTHREADED); - const HRESULT g1 = co_init(nullptr, COINIT_MULTITHREADED); - // Host balances its own initialization while guest depth is still 1. - if (SUCCEEDED(host_sta)) ::CoUninitialize(); - - APTTYPE apt = APTTYPE_CURRENT; - APTTYPEQUALIFIER qual = APTTYPEQUALIFIER_NONE; - const HRESULT apt_hr = ::CoGetApartmentType(&apt, &qual); - void* out = reinterpret_cast(1); - const HRESULT cls_hr = create_inst(GUID_NULL, nullptr, CLSCTX_INPROC_SERVER, IID_IUnknown, &out); - - // Now guest balances; COM should become uninitialized afterwards. - co_uninit(); - const HRESULT apt_after_guest = ::CoGetApartmentType(&apt, &qual); - host_first_teardown_ok = - (host_sta == S_OK && g1 == S_OK && SUCCEEDED(apt_hr) && cls_hr == REGDB_E_CLASSNOTREG && out == nullptr && - apt_after_guest == CO_E_NOTINITIALIZED); - }).join(); - check(host_first_teardown_ok, "guest COM stays live after host CoUninitialize and unwinds cleanly on guest balance"); -} - -void test_com_helpers() { - auto co_init = resolve("CoInitializeEx"); - auto co_uninit = resolve("CoUninitialize"); - auto create_inst = resolve("CoCreateInstance"); - auto create_guid = resolve("CoCreateGuid"); - auto task_free = resolve("CoTaskMemFree"); - auto prop_clear = resolve("PropVariantClear"); - auto guid_str = resolve("StringFromGUID2"); - - check(co_init(nullptr, COINIT_MULTITHREADED) == S_OK, "CoInitializeEx succeeds for helper checks"); - - void* null_out = reinterpret_cast(1); - check(create_inst(GUID_NULL, nullptr, CLSCTX_INPROC_SERVER, IID_IUnknown, nullptr) == E_POINTER, - "CoCreateInstance rejects null out pointer"); - check(create_inst(GUID_NULL, nullptr, CLSCTX_INPROC_SERVER, IID_IUnknown, &null_out) != S_OK && null_out == nullptr, - "CoCreateInstance zeroes out pointer on unregistered CLSID"); - - check(create_guid(nullptr) == E_INVALIDARG, "CoCreateGuid rejects nullptr"); - GUID g1{}, g2{}; - check(create_guid(&g1) == S_OK && create_guid(&g2) == S_OK && - std::memcmp(&g1, &g2, sizeof(GUID)) != 0, - "CoCreateGuid produces distinct GUIDs"); - - wchar_t buf[64]{}; - check(guid_str(g1, nullptr, 64) == 0 && guid_str(g1, buf, 0) == 0, - "StringFromGUID2 rejects invalid output buffer"); - check(guid_str(g1, buf, 64) == 39 && buf[0] == L'{' && buf[37] == L'}', - "StringFromGUID2 formats 39-char braced GUID"); - - PROPVARIANT pv{}; - PropVariantInit(&pv); - pv.vt = VT_LPWSTR; - pv.pwszVal = static_cast(CoTaskMemAlloc(8 * sizeof(wchar_t))); - if (pv.pwszVal) std::wmemcpy(pv.pwszVal, L"abc", 4); - check(prop_clear(&pv) == S_OK && pv.vt == VT_EMPTY, "PropVariantClear resets PROPVARIANT"); - - void* mem = CoTaskMemAlloc(32); - task_free(mem); - task_free(nullptr); - check(true, "CoTaskMemFree accepts valid and null pointers"); - - co_uninit(); -} - -} // namespace - -int main() { - test_registry_coverage(); - test_com_lifecycle_and_sta_isolation(); - test_com_helpers(); - std::printf("%d check(s), %d failure(s)\n", g_checks, g_failures); - return g_failures ? 1 : 0; -} diff --git a/runtime/test/command_list_test.cpp b/runtime/test/command_list_test.cpp deleted file mode 100644 index 4367df6ec..000000000 --- a/runtime/test/command_list_test.cpp +++ /dev/null @@ -1,372 +0,0 @@ -#include "../src/command_list.h" - -#include - -#define CHECK(condition) do { \ - if (!(condition)) { \ - std::fprintf(stderr, "line %d: %s\n", __LINE__, #condition); \ - return 1; \ - } \ -} while (0) - -int main() { - using namespace leonida; - namespace s = d3d12_state; - CommandList list; - TargetView descriptor{12, 1, 2, 3}; - ClearColor color{1, 0, 0, 1}; - CHECK(!list.closed()); - CHECK(!list.clear_render_target({}, color)); - CHECK(list.clear_render_target(descriptor, color)); - // The CPU descriptor slot is reused; the recorded view keeps the old contents. - descriptor = {24, 0, 0, 1}; - color[0] = 0; - color[1] = 1; - CHECK(list.clear_render_target(descriptor, color)); - - // Barriers: a split barrier records only its end half. - CHECK(!list.transition({0, 0, s::common, s::render_target})); - CHECK(list.transition({24, all_subresources, s::render_target, s::copy_source}, barrier_begin_only)); - CHECK(list.transition({24, all_subresources, s::render_target, s::copy_source}, barrier_end_only)); - CHECK(!list.transition({24, 0, s::common, s::copy_dest}, barrier_begin_only | barrier_end_only)); - CHECK(!list.transition({24, 0, s::common, s::copy_dest}, 0x4)); - CHECK(list.uav_barrier({0})); - CHECK(list.aliasing_barrier({0, 24})); - - // Depth-stencil clears: no unknown flags. A clear that names no plane records nothing, and a depth outside [0, 1] - // is kept as given (WARP does that on a D32 target: d3d12_clear_test). - const TargetView depth{48, 0, 0, 1}; - CHECK(list.clear_depth_stencil(depth, 0, 1.0f, 0)); - CHECK(!list.clear_depth_stencil(depth, 0x4, 1.0f, 0)); - CHECK(list.clear_depth_stencil(depth, clear_depth, 1.5f, 0)); - CHECK(list.clear_depth_stencil(depth, clear_depth, -0.0001f, 0)); - CHECK(!list.clear_depth_stencil({}, clear_depth, 1.0f, 0)); - CHECK(list.clear_depth_stencil(depth, clear_stencil, 7.0f, 0x5a)); // depth is ignored without clear_depth - CHECK(list.clear_depth_stencil(depth, clear_depth | clear_stencil, 0.25f, 3)); - - CHECK(list.close()); - CHECK(list.closed()); - CHECK(!list.close()); - CHECK(!list.clear_render_target(descriptor, color)); - CHECK(!list.transition({24, 0, s::copy_source, s::render_target})); - CHECK(!list.uav_barrier({0})); - - const auto commands = list.commands(); - CHECK(commands.size() == 9); - const auto* first = std::get_if(&commands[0]); - const auto* second = std::get_if(&commands[1]); - CHECK(first && second); - CHECK(first->target.resource == 12 && second->target.resource == 24); - CHECK(first->target.mip == 1 && first->target.first_layer == 2 && first->target.layer_count == 3); - const ClearColor red{1, 0, 0, 1}; - CHECK(first->color == red && second->color == color); - const auto* transition = std::get_if(&commands[2]); - CHECK(transition && transition->resource == 24 && transition->subresource == all_subresources); - CHECK(transition->before == s::render_target && transition->after == s::copy_source); - CHECK(std::get_if(&commands[3]) && std::get(commands[3]).resource == 0); - CHECK(std::get_if(&commands[4]) && std::get(commands[4]).after == 24); - const auto* oversized = std::get_if(&commands[5]); - CHECK(oversized && oversized->depth == 1.5f); - const auto* negative = std::get_if(&commands[6]); - CHECK(negative && negative->depth == -0.0001f); - const auto* stencil = std::get_if(&commands[7]); - CHECK(stencil && stencil->flags == clear_stencil && stencil->stencil == 0x5a); - const auto* both = std::get_if(&commands[8]); - CHECK(both && both->flags == (clear_depth | clear_stencil) && both->depth == 0.25f && both->stencil == 3); - - // Rectangles are copied while recording. - CHECK(list.reset()); - Rect rects[] = {{1, 2, 3, 4}, {5, 6, 7, 8}}; - CHECK(list.clear_render_target({36, 0, 0, 1}, color, rects)); - CHECK(list.clear_depth_stencil({48, 0, 0, 1}, clear_depth, 0.5f, 0, {rects, 1})); - rects[0] = {}; - CHECK(list.close()); - const auto& rect_clear = std::get(list.commands()[0]); - CHECK(rect_clear.rects.size() == 2 && rect_clear.rects[0].left == 1 && rect_clear.rects[1].bottom == 8); - CHECK(std::get(list.commands()[1]).rects.size() == 1); - - // Enhanced barriers: split begin halves are dropped, end halves kept; invalid shapes are refused. - namespace y = d3d12_sync; - namespace a = d3d12_access; - namespace l = d3d12_layout; - CHECK(list.reset()); - const BarrierSubresourceRange all{all_subresources, 0, 0, 0, 0, 0}; - CHECK(list.barrier(GlobalBarrier{y::all, y::all, a::common, a::common})); - CHECK(list.barrier(GlobalBarrier{y::compute_shading, y::split, a::unordered_access, a::shader_resource})); - CHECK(list.barrier(GlobalBarrier{y::split, y::pixel_shading, a::unordered_access, a::shader_resource})); - CHECK(!list.barrier(GlobalBarrier{y::split, y::split, 0, 0})); - CHECK(list.barrier(BufferBarrier{y::copy, y::vertex_shading, a::copy_dest, a::vertex_buffer, 7})); - CHECK(!list.barrier(BufferBarrier{y::copy, y::vertex_shading, a::copy_dest, a::vertex_buffer, 0})); - CHECK(list.barrier(TextureBarrier{y::none, y::render_target, a::no_access, a::render_target, l::undefined, - l::render_target, 9, all, texture_barrier_discard})); - CHECK(!list.barrier(TextureBarrier{y::all, y::all, a::common, a::common, l::common, l::undefined, 9, all, 0})); - CHECK(!list.barrier(TextureBarrier{y::all, y::all, a::common, a::common, l::common, l::common, 9, all, 0x2})); - CHECK(!list.barrier(TextureBarrier{y::all, y::all, a::common, a::common, l::common, l::common, 9, - {0, 1, 0, 0, 0, 1}, 0})); // zero layers - CHECK(list.close()); - CHECK(list.commands().size() == 4); - CHECK(std::get(list.commands()[1]).sync_before == y::split); - CHECK(std::get(list.commands()[2]).resource == 7); - CHECK(std::get(list.commands()[3]).flags == texture_barrier_discard); - - // Copies: D3D12's own call rules (aligned footprints; degenerate boxes and DEFAULT-heap - // CopyResource self-copies are accepted as no-ops and must not record Vulkan commands). - CHECK(list.reset()); - CHECK(list.copy_buffer({1, 0, 2, 16, 64})); - CHECK(list.copy_buffer({1, 0, 2, 16, 0})); - CHECK(!list.copy_buffer({0, 0, 2, 16, 64})); - const CopyLocation texture{3, false, 0, 0, 0, 0, 0, 0}; - const CopyLocation placed{4, true, 0, 512, 8, 8, 1, 256}; - CHECK(list.copy_texture({texture, 0, 0, 0, placed, false, {}})); - CHECK(list.copy_texture({placed, 0, 0, 0, texture, true, {2, 2, 0, 6, 6, 1}})); - CHECK(!list.copy_texture({placed, 0, 0, 0, placed, false, {}})); // footprint to footprint - CHECK(!list.copy_texture({texture, 0, 0, 0, {4, true, 0, 100, 8, 8, 1, 256}, false, {}})); // offset not 512 - CHECK(!list.copy_texture({texture, 0, 0, 0, {4, true, 0, 512, 8, 8, 1, 100}, false, {}})); // pitch not 256 - CHECK(list.commands().size() == 3); - CHECK(list.copy_texture({texture, 0, 0, 0, texture, true, {2, 2, 0, 2, 6, 1}})); // empty box, no-op - CHECK(list.commands().size() == 3); - CHECK(list.copy_resource({5, 6})); - CHECK(list.commands().size() == 4); - CHECK(list.copy_resource({5, 5})); // DEFAULT-heap self-copy; COM layer rejects UPLOAD self-copies - CHECK(list.commands().size() == 4); - // A volume's box has a z range, and its footprint a depth; a resolve needs two different resources. - CHECK(list.copy_texture({texture, 0, 0, 2, {4, true, 0, 512, 4, 4, 4, 256}, true, {0, 0, 1, 4, 4, 3}})); - CHECK(!list.copy_texture({texture, 0, 0, 0, {4, true, 0, 512, 4, 4, 0, 256}, false, {}})); // no slices - CHECK(list.copy_texture({texture, 0, 0, 0, texture, true, {0, 0, 2, 4, 4, 2}})); // empty in z, no-op - CHECK(list.commands().size() == 5); - CHECK(list.resolve_subresource({7, 1, 8, 0})); - CHECK(!list.resolve_subresource({7, 0, 7, 0})); - CHECK(!list.resolve_subresource({0, 0, 8, 0})); - CHECK(!list.resolve_subresource({7, 0, 0, 0})); - CHECK(list.close()); - CHECK(!list.resolve_subresource({7, 1, 8, 0})); - CHECK(list.commands().size() == 6); - CHECK(std::get(list.commands()[0]).src_offset == 16); - CHECK(std::get(list.commands()[1]).src.footprint && !std::get(list.commands()[1]).has_box); - CHECK(std::get(list.commands()[2]).box.right == 6); - CHECK(std::get(list.commands()[3]).src == 6); - const auto& slices = std::get(list.commands()[4]); - CHECK(slices.z == 2 && slices.src.depth == 4 && slices.box.front == 1 && slices.box.back == 3); - const auto& resolved = std::get(list.commands()[5]); - CHECK(resolved.dst == 7 && resolved.dst_subresource == 1 && resolved.src == 8 && resolved.src_subresource == 0); - - // Dispatches keep the user data they were recorded with; no pipeline is refused, no groups records nothing. - CHECK(list.reset()); - Dispatch dispatch{0x1234, {}, 2, 1, 1}; - dispatch.user_data[0] = 7; - dispatch.user_data[31] = 9; - CHECK(list.dispatch(dispatch)); - dispatch.user_data[0] = 8; // the caller's block changes after recording - CHECK(!list.dispatch({0, {}, 1, 1, 1})); - CHECK(list.dispatch({0x1234, {}, 0, 1, 1})); - CHECK(list.close()); - CHECK(!list.dispatch(dispatch)); - CHECK(list.commands().size() == 1); - const auto& recorded = std::get(list.commands()[0]); - CHECK(recorded.pipeline == 0x1234 && recorded.user_data[0] == 7 && recorded.user_data[31] == 9 && recorded.x == 2); - - CHECK(list.reset()); - CHECK(!list.closed() && list.commands().empty()); - CHECK(!list.reset()); - CHECK(list.clear_render_target({36, 0, 0, 1}, color)); - CHECK(list.close()); - CHECK(list.commands().size() == 1); - CHECK(std::get(list.commands()[0]).target.resource == 36); - - // D3D-26: discards, immediate writes and atomic copies. - CHECK(list.reset()); - CHECK(list.discard({40, 0, 0, false, true})); // the whole resource - CHECK(list.discard({40, 2, 3, true})); - CHECK(list.discard({40, 0, 0, false})); // nothing to discard: not recorded - CHECK(!list.discard({0, 0, 0, false, true})); - CHECK(!list.discard({40, 0xfffffff0u, 0x20, false})); // past the last subresource index - CHECK(!list.discard({40, 1, all_subresources, false})); // an explicit count of UINT_MAX is a range - CHECK(!list.discard({40, all_subresources, 1, false})); - CHECK(list.write_immediate({0x1000, 7, write_immediate_mode::marker_out})); - CHECK(!list.write_immediate({0, 7, 0})); // null address - CHECK(!list.write_immediate({0x1002, 7, 0})); // not 4-byte aligned - CHECK(!list.write_immediate({0x1000, 7, 3})); // not a mode - const DependentRange dependent{41, 0, 0, 64}; - CHECK(list.atomic_copy({42, 8, 43, 16, 8, {dependent}})); - CHECK(list.atomic_copy({42, 4, 42, 8, 4, {dependent}})); // within one buffer - CHECK(!list.atomic_copy({42, 8, 42, 8, 8, {dependent}})); // onto itself - CHECK(!list.atomic_copy({42, 4, 43, 16, 8, {dependent}})); // UINT64 at an offset that is not 8-aligned - CHECK(!list.atomic_copy({42, 8, 43, 16, 2, {dependent}})); // neither UINT nor UINT64 - CHECK(list.atomic_copy({42, 8, 43, 16, 4, {}})); // zero dependencies is valid on Windows D3D12 - CHECK(!list.atomic_copy({42, 8, 43, 16, 4, {{41, 0, 8, 4}}})); // inverted dependent range - CHECK(!list.atomic_copy({42, 8, 43, 16, 4, {{41, 0, 4, 4}}})); // empty dependent range - CHECK(!list.atomic_copy({42, 8, 43, 16, 4, {{0, 0, 0, 4}}})); // a null dependent resource - CHECK(!list.atomic_copy({0, 8, 43, 16, 4, {dependent}})); - CHECK(list.close()); - CHECK(!list.discard({40, 0, 0, false, true}) && !list.discard({40, 0, 0, false})); - CHECK(list.commands().size() == 6); - CHECK(std::get(list.commands()[0]).whole); - CHECK(std::get(list.commands()[1]).first_subresource == 2 && - std::get(list.commands()[1]).partial && !std::get(list.commands()[1]).whole); - CHECK(std::get(list.commands()[2]).value == 7); - const auto& atomic = std::get(list.commands()[3]); - CHECK(atomic.bytes == 8 && atomic.dst_offset == 8 && atomic.dependencies.size() == 1 && - atomic.dependencies[0].end == 64); - - // Synthetic IR values here test copy-by-value mechanics only; the COM test below enforces D3D12 bundle - // restrictions on every currently implemented forbidden operation. - // Bundles are copied into the parent at ExecuteBundle time and can be reused independently. - CommandList parent, bundle; - CHECK(parent.copy_resource({1, 2})); - CHECK(bundle.copy_resource({3, 4})); - CHECK(bundle.copy_buffer({5, 0, 6, 16, 32})); - CHECK(bundle.close()); - CHECK(parent.execute_bundle(bundle)); - CHECK(parent.copy_resource({7, 8})); - CHECK(parent.execute_bundle(bundle)); // the same closed bundle can execute more than once - CHECK(parent.close()); - CHECK(parent.commands().size() == 6); - CHECK(std::get(parent.commands()[0]).src == 2); - CHECK(std::get(parent.commands()[1]).src == 4); - CHECK(std::get(parent.commands()[2]).size == 32); - CHECK(std::get(parent.commands()[3]).src == 8); - CHECK(std::get(parent.commands()[4]).src == 4); - CHECK(std::get(parent.commands()[5]).size == 32); - - // Resetting/rerecording the source bundle cannot mutate the parent's copied commands. - CHECK(bundle.reset()); - CHECK(bundle.copy_resource({9, 10})); - CHECK(bundle.close()); - CHECK(parent.commands().size() == 6); - CHECK(std::get(parent.commands()[1]).src == 4); - CHECK(!parent.execute_bundle(bundle)); // parent is closed - - // The range form: [first, last) of the bundle, with last clamped to its size. - { - CommandList source, target, other; - CHECK(source.copy_resource({1, 2}) && source.copy_resource({3, 4}) && source.copy_resource({5, 6})); - CHECK(source.close()); - CHECK(target.execute_bundle(source, 1, 2)); // the middle command only - CHECK(target.commands().size() == 1 && std::get(target.commands()[0]).src == 4); - CHECK(target.execute_bundle(source, 2, 100)); // last beyond the size is clamped - CHECK(target.commands().size() == 2 && std::get(target.commands()[1]).src == 6); - CHECK(target.execute_bundle(source, 1, 1) && target.commands().size() == 2); // first == last: nothing - CHECK(target.execute_bundle(source, 3, 3) && target.execute_bundle(source, 7, 9)); // first beyond the size - CHECK(target.execute_bundle(source, 2, 1) && target.commands().size() == 2); // first after last: nothing - CHECK(target.commands().size() == 2); - CHECK(other.execute_bundle(source)); // the default arguments copy all of it, as before - CHECK(other.commands().size() == 3 && std::get(other.commands()[0]).src == 2 && - std::get(other.commands()[2]).src == 6); - } - - CommandList open_parent, open_bundle; - CHECK(!open_parent.execute_bundle(open_bundle)); // bundle must be closed - CHECK(!open_parent.execute_bundle(open_parent)); // a list cannot execute itself - CHECK(open_parent.commands().empty()); - - // SetPredication (D3D-18): the op must be one of the two D3D12 values and the offset 8-byte aligned; a null - // buffer turns it off whatever the other arguments are. - namespace pred = d3d12_predication; - CommandList predicated; - CHECK(predicated.set_predication({7, 0, pred::equal_zero})); - CHECK(predicated.set_predication({7, 16, pred::not_equal_zero})); - CHECK(!predicated.set_predication({7, 4, pred::equal_zero})); // not 8-byte aligned - CHECK(!predicated.set_predication({7, 0, 2})); // no such op - CHECK(predicated.set_predication({0, 4, 2})); // off: offset and op ignored - CHECK(predicated.close()); - CHECK(!predicated.set_predication({7, 0, pred::equal_zero})); // closed - CHECK(predicated.commands().size() == 3); - CHECK(std::get(predicated.commands()[0]).op == pred::equal_zero); - CHECK(std::get(predicated.commands()[1]).offset == 16); - const auto& off = std::get(predicated.commands()[2]); - CHECK(off.buffer == 0 && off.offset == 0 && off.op == 0); - // Queries: timestamps only end; other queries are begun and ended in one list, with the same type, and are not - // begun twice or resolved while running. Resolve offsets are multiples of 8; a resolve of nothing records nothing. - namespace q = d3d12_query; - namespace h = d3d12_query_heap; - CHECK(list.reset()); - constexpr QueryHeapId heap = 70, other = 71; - CHECK(!list.begin_query({0, q::occlusion, 0})); - CHECK(!list.begin_query({heap, q::timestamp, 0})); - CHECK(list.end_query({heap, q::timestamp, 3})); - CHECK(list.end_query({heap, q::timestamp, 3})); // a timestamp can be written again - CHECK(!list.end_query({heap, q::occlusion, 1})); // never begun - CHECK(list.begin_query({heap, q::occlusion, 1})); - CHECK(!list.begin_query({heap, q::binary_occlusion, 1})); // already running - CHECK(list.begin_query({other, q::occlusion, 1})); // same index, another heap - CHECK(!list.end_query({heap, q::binary_occlusion, 1})); // begun with another type - CHECK(!list.resolve_queries({heap, q::occlusion, 0, 2, 9, 0})); // query 1 is running - CHECK(list.resolve_queries({heap, q::occlusion, 2, 2, 9, 0})); - CHECK(list.queries_open()); - CHECK(list.end_query({heap, q::occlusion, 1})); - CHECK(list.end_query({other, q::occlusion, 1})); - CHECK(!list.queries_open()); - CHECK(!list.resolve_queries({heap, q::occlusion, 0, 2, 9, 4})); // offset not a multiple of 8 - CHECK(!list.resolve_queries({heap, q::occlusion, 0, 2, 0, 8})); // no destination - CHECK(!list.resolve_queries({heap, q::occlusion, 0xffffffff, 2, 9, 8})); // range wraps - CHECK(list.resolve_queries({heap, q::occlusion, 0, 2, 9, 16})); - CHECK(list.resolve_queries({heap, q::occlusion, 0, 0, 9, 16})); // nothing to resolve - CHECK(list.close()); - CHECK(list.commands().size() == 8); - CHECK(std::get(list.commands()[0]).index == 3 && std::get(list.commands()[0]).type == q::timestamp); - CHECK(std::get(list.commands()[2]).heap == heap && std::get(list.commands()[3]).heap == other); - const auto& query_resolve = std::get(list.commands()[7]); - CHECK(query_resolve.first == 0 && query_resolve.count == 2 && query_resolve.dst == 9 && query_resolve.offset == 16); - - // A query still running at Close leaves the list closed and marked; Reset clears it. - CHECK(list.reset()); - CHECK(list.begin_query({heap, q::pipeline_statistics, 0})); - CHECK(list.close() && list.queries_open()); - CHECK(list.reset() && !list.queries_open()); - CHECK(list.begin_query({heap, q::pipeline_statistics, 0})); // free again after the reset - - CHECK(query_fits_heap(h::occlusion, q::binary_occlusion) && !query_fits_heap(h::occlusion, q::timestamp)); - CHECK(query_fits_heap(h::copy_queue_timestamp, q::timestamp) && !query_fits_heap(h::timestamp, q::occlusion)); - CHECK(query_fits_heap(h::so_statistics, q::so_statistics_stream3) && !query_fits_heap(6, q::occlusion)); - CHECK(query_result_size(q::occlusion) == 8 && query_result_size(q::timestamp) == 8); - CHECK(query_result_size(q::pipeline_statistics) == 88 && query_result_size(q::so_statistics_stream0) == 16); - - // Acceleration-structure commands: 256-byte AS/scratch alignment, 8-byte postbuild alignment, - // valid copy modes (0..4), valid postbuild info types (0..3), and PERFORM_UPDATE source checks. - CHECK(list.close()); - CHECK(list.reset()); - BuildAccelerationStructure build{}; - build.dst_va = 0x1000; - build.scratch_va = 0x2000; - CHECK(list.build_acceleration_structure(build)); - build.dst_va = 0; - CHECK(!list.build_acceleration_structure(build)); - build.dst_va = 0x1080; // misaligned - CHECK(!list.build_acceleration_structure(build)); - build.dst_va = 0x1000; - build.scratch_va = 0; - CHECK(!list.build_acceleration_structure(build)); - build.scratch_va = 0x2080; // misaligned - CHECK(!list.build_acceleration_structure(build)); - build.scratch_va = 0x2000; - build.update = true; - build.src_va = 0; - CHECK(!list.build_acceleration_structure(build)); - build.src_va = 0x3080; // misaligned update source - CHECK(!list.build_acceleration_structure(build)); - build.src_va = 0x3000; - CHECK(list.build_acceleration_structure(build)); - build.update = false; - build.src_va = 0x3080; // ignored when not updating - CHECK(list.build_acceleration_structure(build)); - - CHECK(list.copy_acceleration_structure({0x1000, 0x2000, 0})); - CHECK(list.copy_acceleration_structure({0x1000, 0x2000, 4})); - CHECK(!list.copy_acceleration_structure({0x1000, 0x2000, 5})); - CHECK(!list.copy_acceleration_structure({0, 0x2000, 0})); - CHECK(!list.copy_acceleration_structure({0x1080, 0x2000, 0})); - CHECK(!list.copy_acceleration_structure({0x1000, 0, 0})); - CHECK(!list.copy_acceleration_structure({0x1000, 0x2080, 0})); - - CHECK(list.acceleration_structure_postbuild({0x4000, 0, {0x1000}})); - CHECK(list.acceleration_structure_postbuild({0x4008, 3, {0x1000, 0x2000}})); - CHECK(!list.acceleration_structure_postbuild({0x4000, 4, {0x1000}})); - CHECK(!list.acceleration_structure_postbuild({0, 0, {0x1000}})); - CHECK(!list.acceleration_structure_postbuild({0x4004, 0, {0x1000}})); - CHECK(!list.acceleration_structure_postbuild({0x4000, 0, {}})); - CHECK(!list.acceleration_structure_postbuild({0x4000, 0, {0}})); - CHECK(!list.acceleration_structure_postbuild({0x4000, 0, {0x1080}})); - CHECK(list.close()); - CHECK(list.commands().size() == 7); - return 0; -} diff --git a/runtime/test/conservative_raster_fixture.h b/runtime/test/conservative_raster_fixture.h deleted file mode 100644 index 3471983ad..000000000 --- a/runtime/test/conservative_raster_fixture.h +++ /dev/null @@ -1,221 +0,0 @@ -#pragma once -// Synthetic D3D12/Vulkan conservative coverage. Required/forbidden pixels come from geometric clipping, -// not a driver snapshot: Tier 1 may over-cover by half a pixel, so uncertain pixels are not compared exactly. -#include "vk_test_device.h" -#include "d3d12_copy_compare.h" -#include "d3d12_test_shaders.h" -#include "host_wine.h" -#include "test_temp_dir.h" -#include "../src/conservative_raster.h" -#include "../src/shader_library.h" -#include -#include -#include -#include -#include - -#define CHECK(x) do { if (!(x)) { std::fprintf(stderr, "line %d: %s\n", __LINE__, #x); return false; } } while (0) -namespace conservative_test { -constexpr UINT width = 32, height = 32, pitch = 256; -struct Point { double x, y; }; -using Triangle = std::array; -using Mask = std::array; -struct Fixture { - copycmp::Run run; - copycmp::Ptr root; - D3D12_SHADER_BYTECODE vs{}, ps{}; - std::span input; -}; -struct VertexInput { - std::vector data; - UINT stride = 16; - std::vector indices; - D3D_PRIMITIVE_TOPOLOGY topology = D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST; -}; - -inline bool setup(Fixture& f, ID3D12Device* device, bool ours, D3D12_SHADER_BYTECODE vs, D3D12_SHADER_BYTECODE ps) { - f.vs = vs; f.ps = ps; - CHECK(f.run.init(device, ours)); - D3D12_VERSIONED_ROOT_SIGNATURE_DESC desc{}; - desc.Version = D3D_ROOT_SIGNATURE_VERSION_1_0; - desc.Desc_1_0.Flags = D3D12_ROOT_SIGNATURE_FLAG_ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT; - const auto bytes = d3d12test::serialize_root_signature(desc); - CHECK(!bytes.empty()); - CHECK(SUCCEEDED(device->CreateRootSignature(0, bytes.data(), bytes.size(), IID_PPV_ARGS(&f.root.p)))); - return true; -} - -inline D3D12_GRAPHICS_PIPELINE_STATE_DESC description(const Fixture& f, bool conservative, UINT samples, bool variant) { - static const D3D12_INPUT_ELEMENT_DESC element{ - "POSITION", 0, DXGI_FORMAT_R32G32_FLOAT, 0, 0, D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0}; - D3D12_GRAPHICS_PIPELINE_STATE_DESC d{}; - d.pRootSignature = f.root.p; - d.VS = f.vs; d.PS = f.ps; - d.InputLayout = f.input.empty() ? D3D12_INPUT_LAYOUT_DESC{&element, 1} - : D3D12_INPUT_LAYOUT_DESC{f.input.data(), UINT(f.input.size())}; - d.RasterizerState.FillMode = D3D12_FILL_MODE_SOLID; - d.RasterizerState.CullMode = D3D12_CULL_MODE_NONE; - d.RasterizerState.DepthClipEnable = TRUE; - d.RasterizerState.MultisampleEnable = samples > 1; - d.RasterizerState.ConservativeRaster = conservative ? D3D12_CONSERVATIVE_RASTERIZATION_MODE_ON - : D3D12_CONSERVATIVE_RASTERIZATION_MODE_OFF; - d.PrimitiveTopologyType = D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE; - d.NumRenderTargets = variant ? 2 : 1; - d.RTVFormats[0] = DXGI_FORMAT_R8G8B8A8_UNORM; - if (variant) d.RTVFormats[1] = DXGI_FORMAT_R8G8B8A8_UNORM; - d.BlendState.RenderTarget[0].RenderTargetWriteMask = D3D12_COLOR_WRITE_ENABLE_ALL; - d.SampleDesc.Count = samples; - d.SampleMask = UINT_MAX; - return d; -} - -// Clip the triangle to a pixel rectangle and return its intersection area. -inline double area(const Triangle& triangle, double left, double top, double right, double bottom, bool* intersects = nullptr) { - std::vector p(triangle.begin(), triangle.end()); - for (unsigned side = 0; side < 4 && !p.empty(); ++side) { - const auto distance = [&](Point v) { - return side == 0 ? v.x - left : side == 1 ? right - v.x : side == 2 ? v.y - top : bottom - v.y; - }; - std::vector out; - Point a = p.back(); double da = distance(a); - for (const Point b : p) { - const double db = distance(b); - if ((da >= 0) != (db >= 0)) { - const double t = da / (da - db); - out.push_back({a.x + t * (b.x - a.x), a.y + t * (b.y - a.y)}); - } - if (db >= 0) out.push_back(b); - a = b; da = db; - } - p = std::move(out); - } - double sum = 0; - if (intersects) *intersects = !p.empty(); // a degenerate triangle may cover pixels despite having zero area - for (std::size_t i = 0; i < p.size(); ++i) { - const Point a = p[i], b = p[(i + 1) % p.size()]; - sum += a.x * b.y - a.y * b.x; - } - return std::abs(sum) * 0.5; -} - -inline bool render(Fixture& f, const Triangle& triangle, bool conservative, UINT samples, bool variant, - const D3D12_RECT& scissor, Mask& mask, D3D12_CULL_MODE cull = D3D12_CULL_MODE_NONE, - const VertexInput* input = nullptr, std::vector* rgba = nullptr) { - auto& r = f.run; - auto desc = description(f, conservative, samples, variant); - desc.RasterizerState.CullMode = cull; - copycmp::Ptr pso; - const auto created = r.device->CreateGraphicsPipelineState(&desc, IID_PPV_ARGS(&pso.p)); - if (FAILED(created)) { - std::fprintf(stderr, "%s CreateGraphicsPipelineState=%08x conservative=%d samples=%u variant=%d\n", - r.ours ? "Vulkan" : "host", unsigned(created), int(conservative), samples, int(variant)); - return false; - } - D3D12_RESOURCE_DESC tex{}; - tex.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D; - tex.Width = width; tex.Height = height; - tex.DepthOrArraySize = tex.MipLevels = 1; - tex.Format = DXGI_FORMAT_R8G8B8A8_UNORM; - tex.SampleDesc.Count = samples; - tex.Flags = D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET; - copycmp::Ptr target, resolved, vertices, indices, readback; - CHECK(r.texture(tex, D3D12_RESOURCE_STATE_RENDER_TARGET, target)); - if (samples > 1) { - tex.SampleDesc.Count = 1; tex.Flags = D3D12_RESOURCE_FLAG_NONE; - CHECK(r.texture(tex, D3D12_RESOURCE_STATE_RESOLVE_DEST, resolved)); - } - const UINT vertex_bytes = input ? UINT(input->data.size() * sizeof(float)) : 24; - CHECK(r.buffer(D3D12_HEAP_TYPE_UPLOAD, vertex_bytes, D3D12_RESOURCE_STATE_GENERIC_READ, vertices)); - CHECK(r.buffer(D3D12_HEAP_TYPE_READBACK, pitch * height, D3D12_RESOURCE_STATE_COPY_DEST, readback)); - void* data = nullptr; - const D3D12_RANGE none{}; - CHECK(SUCCEEDED(vertices->Map(0, &none, &data))); - if (input) std::memcpy(data, input->data.data(), vertex_bytes); - else { - auto* positions = static_cast(data); - for (unsigned i = 0; i < 3; ++i) { - positions[i * 2] = float(triangle[i].x * 2 / width - 1); - positions[i * 2 + 1] = float(1 - triangle[i].y * 2 / height); - } - } - vertices->Unmap(0, nullptr); - if (input && !input->indices.empty()) { - CHECK(r.buffer(D3D12_HEAP_TYPE_UPLOAD, input->indices.size() * sizeof(std::uint16_t), - D3D12_RESOURCE_STATE_GENERIC_READ, indices)); - CHECK(SUCCEEDED(indices->Map(0, &none, &data))); - std::memcpy(data, input->indices.data(), input->indices.size() * sizeof(std::uint16_t)); - indices->Unmap(0, nullptr); - } - copycmp::Ptr heap; - const D3D12_DESCRIPTOR_HEAP_DESC hd{D3D12_DESCRIPTOR_HEAP_TYPE_RTV, 1}; - CHECK(SUCCEEDED(r.device->CreateDescriptorHeap(&hd, IID_PPV_ARGS(&heap.p)))); - const auto handle = heap->GetCPUDescriptorHandleForHeapStart(); - r.device->CreateRenderTargetView(target.p, nullptr, handle); - r.begin(); - const float clear[4] = {}; - r.list->ClearRenderTargetView(handle, clear, 0, nullptr); - r.list->OMSetRenderTargets(1, &handle, FALSE, nullptr); - r.list->SetGraphicsRootSignature(f.root.p); - r.list->SetPipelineState(pso.p); - const D3D12_VIEWPORT viewport{0, 0, float(width), float(height), 0, 1}; - r.list->RSSetViewports(1, &viewport); - r.list->RSSetScissorRects(1, &scissor); - const D3D12_VERTEX_BUFFER_VIEW vb{vertices->GetGPUVirtualAddress(), vertex_bytes, input ? input->stride : 8}; - r.list->IASetVertexBuffers(0, 1, &vb); - r.list->IASetPrimitiveTopology(input ? input->topology : D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST); - if (indices.p) { - const D3D12_INDEX_BUFFER_VIEW ib{indices->GetGPUVirtualAddress(), UINT(input->indices.size() * 2), DXGI_FORMAT_R16_UINT}; - r.list->IASetIndexBuffer(&ib); - r.list->DrawIndexedInstanced(UINT(input->indices.size()), 1, 0, 0, 0); - } else r.list->DrawInstanced(input ? vertex_bytes / input->stride : 3, 1, 0, 0); - ID3D12Resource* source = target.p; - if (samples > 1) { - r.barrier(target.p, D3D12_RESOURCE_STATE_RENDER_TARGET, D3D12_RESOURCE_STATE_RESOLVE_SOURCE); - r.list->ResolveSubresource(resolved.p, 0, target.p, 0, tex.Format); - r.barrier(resolved.p, D3D12_RESOURCE_STATE_RESOLVE_DEST, D3D12_RESOURCE_STATE_COPY_SOURCE); - source = resolved.p; - } else r.barrier(target.p, D3D12_RESOURCE_STATE_RENDER_TARGET, D3D12_RESOURCE_STATE_COPY_SOURCE); - D3D12_TEXTURE_COPY_LOCATION from{}, to{}; - from.pResource = source; from.Type = D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX; - to.pResource = readback.p; to.Type = D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT; - to.PlacedFootprint.Footprint = {tex.Format, width, height, 1, pitch}; - r.list->CopyTextureRegion(&to, 0, 0, 0, &from, nullptr); - const auto error = r.submit(); - if (!error.empty()) { std::fprintf(stderr, "%s\n", error.c_str()); return false; } - CHECK(SUCCEEDED(readback->Map(0, nullptr, &data))); - const auto* pixels = static_cast(data); - if (rgba) rgba->resize(width * height * 4); - for (UINT y = 0; y < height; ++y) for (UINT x = 0; x < width; ++x) { - const auto* p = pixels + y * pitch + x * 4; - if (rgba) { - std::copy(p, p + 4, rgba->begin() + (y * width + x) * 4); - mask[y * width + x] = (p[0] | p[1] | p[2] | p[3]) != 0; - } else { - CHECK(p[1] == 0 && p[2] == 0 && p[0] == p[3]); - if (conservative) CHECK(p[0] == 0 || p[0] == 255); // every MSAA sample is covered - mask[y * width + x] = p[0] != 0; - } - } - readback->Unmap(0, &none); - return true; -} - -inline bool coverage(const Triangle& triangle, const D3D12_RECT& scissor, const Mask& mask) { - constexpr double epsilon = 1.0 / 256; - for (UINT y = 0; y < height; ++y) for (UINT x = 0; x < width; ++x) { - const bool in = LONG(x) >= scissor.left && LONG(x) < scissor.right && LONG(y) >= scissor.top && LONG(y) < scissor.bottom; - const bool required = in && area(triangle, x + epsilon, y + epsilon, x + 1 - epsilon, y + 1 - epsilon) > 1e-9; - bool intersects = false; - area(triangle, x - 0.5 - epsilon, y - 0.5 - epsilon, x + 1.5 + epsilon, y + 1.5 + epsilon, &intersects); - const bool allowed = in && intersects; - if ((required && !mask[y * width + x]) || (!allowed && mask[y * width + x])) { - std::fprintf(stderr, "coverage (%u,%u): required=%d allowed=%d actual=%d\n", x, y, - int(required), int(allowed), int(mask[y * width + x])); - return false; - } - } - return true; -} - - -} // namespace conservative_test diff --git a/runtime/test/conservative_raster_test.cpp b/runtime/test/conservative_raster_test.cpp deleted file mode 100644 index b862e5fcb..000000000 --- a/runtime/test/conservative_raster_test.cpp +++ /dev/null @@ -1,49 +0,0 @@ -#include "../src/conservative_raster.h" -#include -#include - -int main() { - using leonida::conservative_raster::tier1; - unsigned failures = 0; - const auto check = [&](bool value) { if (!value) ++failures; }; - check(tier1(true, 8, 0.0f)); - check(tier1(true, 8, 1.0f / 256.0f)); - check(tier1(true, 8, 0.5f - 1.0f / 512.0f)); - check(!tier1(false, 8, 0.0f)); - check(!tier1(true, 7, 0.0f)); - check(!tier1(true, 8, 0.5f)); - check(!tier1(true, 8, -0.001f)); - check(!tier1(true, 8, std::numeric_limits::infinity())); - check(!tier1(true, 8, std::numeric_limits::quiet_NaN())); - using leonida::conservative_raster::tier; - check(tier(false, 8, 0, true) == 0); - check(tier(true, 7, 0, true) == 0); - check(tier(true, 8, 0, true) == 2); - check(tier(true, 8, 0, false) == 1); - check(tier(true, 8, 1.0f / 512.0f, true) == 2); - check(tier(true, 8, std::nextafter(1.0f / 512.0f, 1.0f), true) == 1); - check(tier(true, 8, 1.0f / 256.0f, true) == 1); - check(tier(true, 16, 0.003f, true) == 2); - check(tier(true, 16, 0.003f, false) == 1); - check(tier(true, 8, std::numeric_limits::quiet_NaN(), true) == 0); - check(tier(true, 8, 0, true, true, true) == 3); - check(tier(true, 8, 0, true, false, true) == 2); - check(tier(true, 8, 0, true, true, false) == 2); - check(tier(true, 8, 0, false, true, true) == 1); - check(tier(false, 8, 0, true, true, true) == 0); - check(tier(true, 8, 1.0f / 256.0f, true, true, true) == 1); - using leonida::conservative_raster::inner_coverage_requirements; - const std::uint32_t module[] = {0x07230203, 0x00010500, 0, 2, 0, (2u << 16) | 17, 5265, - (3u << 16) | 16, 1, 4446}; - const auto requirements = inner_coverage_requirements(module); - check(requirements.valid && requirements.fully_covered && requirements.post_depth); - check(!inner_coverage_requirements(std::span(module).first(9)).valid); - const std::uint32_t zero_count[] = {0x07230203, 0x00010500, 0, 2, 0, 0}; - check(!inner_coverage_requirements(zero_count).valid); - const std::uint32_t ordinary[] = {0x07230203, 0x00010500, 0, 2, 0, (2u << 16) | 17, 1}; - const auto regular = inner_coverage_requirements(ordinary); - check(regular.valid && !regular.fully_covered && !regular.post_depth); - if (failures) std::fprintf(stderr, "conservative raster capability checks: %u failures\n", failures); - else std::puts("conservative raster: enabled extension, precision and uncertainty bounds checked"); - return failures ? 1 : 0; -} diff --git a/runtime/test/context_attach_detach_stress_test.cpp b/runtime/test/context_attach_detach_stress_test.cpp deleted file mode 100644 index 061fac587..000000000 --- a/runtime/test/context_attach_detach_stress_test.cpp +++ /dev/null @@ -1,220 +0,0 @@ -#include "pch.h" -#include "XTaskQueue.h" -#include "XTaskQueuePriv.h" - -#include -#include -#include - -namespace -{ -constexpr int Iterations = 1500; - -struct State -{ - std::atomic created{0}; - std::atomic submitted{0}; - std::atomic completed{0}; - std::atomic monitors{0}; - std::atomic failures{0}; - std::atomic canceled{0}; -}; - -void CALLBACK OnCallback(void* context, bool canceled) -{ - auto* state = static_cast(context); - if (canceled) - { - ++state->canceled; - } - ++state->completed; -} - -void CALLBACK OnMonitor( - void* context, - XTaskQueueHandle, - XTaskQueuePort port) -{ - auto* state = static_cast(context); - if (port != XTaskQueuePort::Work) - { - ++state->failures; - } - ++state->monitors; -} - -bool Check(bool value, const char* message) -{ - std::printf("%s %s\n", value ? "PASS" : "FAIL", message); - return value; -} -} - -int main() -{ - std::setvbuf(stdout, nullptr, _IONBF, 0); - - State state; - XTaskQueueHandle owner = nullptr; - - HRESULT hr = XTaskQueueCreate( - XTaskQueueDispatchMode::Manual, - XTaskQueueDispatchMode::Manual, - &owner); - - if (!Check(SUCCEEDED(hr) && owner != nullptr, - "owner queue created")) - { - return 2; - } - - XTaskQueuePortHandle work = nullptr; - XTaskQueuePortHandle completion = nullptr; - - HRESULT workHr = XTaskQueueGetPort( - owner, XTaskQueuePort::Work, &work); - - HRESULT completionHr = XTaskQueueGetPort( - owner, XTaskQueuePort::Completion, &completion); - - if (!Check(SUCCEEDED(workHr) && - SUCCEEDED(completionHr) && - work != nullptr && completion != nullptr, - "owner ports acquired")) - { - XTaskQueueCloseHandle(owner); - return 2; - } - - XTaskQueueRegistrationToken token = {}; - - hr = XTaskQueueRegisterMonitor( - owner, &state, OnMonitor, &token); - - if (!Check(SUCCEEDED(hr), "monitor registered")) - { - XTaskQueueCloseHandle(owner); - return 2; - } - - std::atomic start{false}; - - std::thread churn([&] - { - while (!start.load(std::memory_order_acquire)) - { - std::this_thread::yield(); - } - - for (int i = 0; i < Iterations; ++i) - { - XTaskQueueHandle composite = nullptr; - - HRESULT result = XTaskQueueCreateComposite( - work, completion, &composite); - - if (SUCCEEDED(result) && composite != nullptr) - { - ++state.created; - XTaskQueueCloseHandle(composite); - } - else - { - ++state.failures; - } - - if ((i & 7) == 0) - { - std::this_thread::yield(); - } - } - }); - - std::thread submitter([&] - { - while (!start.load(std::memory_order_acquire)) - { - std::this_thread::yield(); - } - - for (int i = 0; i < Iterations; ++i) - { - HRESULT result = XTaskQueueSubmitCallback( - owner, - XTaskQueuePort::Work, - &state, - OnCallback); - - if (SUCCEEDED(result)) - { - ++state.submitted; - XTaskQueueDispatch( - owner, XTaskQueuePort::Work, 0); - } - else - { - ++state.failures; - } - - if ((i & 7) == 0) - { - std::this_thread::yield(); - } - } - }); - - std::puts("TRACE: starting concurrent attach/detach and submissions"); - start.store(true, std::memory_order_release); - - churn.join(); - submitter.join(); - - while (XTaskQueueDispatch( - owner, XTaskQueuePort::Work, 0)) - { - } - - XTaskQueueUnregisterMonitor(owner, token); - - int failures = 0; - - if (!Check(state.created.load() == Iterations, - "all composites created and closed")) ++failures; - - if (!Check(state.submitted.load() == Iterations, - "all callbacks submitted")) ++failures; - - if (!Check(state.completed.load() == Iterations, - "all callbacks executed")) ++failures; - - if (!Check(state.monitors.load() == Iterations, - "all monitor notifications received")) ++failures; - - if (!Check(state.failures.load() == 0, - "no API or monitor failures")) ++failures; - - if (!Check(state.canceled.load() == 0, - "no unexpected cancellation")) ++failures; - - std::printf( - "TRACE: created=%d submitted=%d completed=%d monitors=%d\n", - state.created.load(), - state.submitted.load(), - state.completed.load(), - state.monitors.load()); - - XTaskQueueCloseHandle(owner); - - if (!Check(XTaskQueueUninitialize(1000), - "all task queue references released")) - { - ++failures; - } - - std::printf( - "RESULT: %s (%d failures)\n", - failures == 0 ? "PASS" : "FAIL", - failures); - - return failures == 0 ? 0 : 1; -} diff --git a/runtime/test/context_concurrent_detach_test.cpp b/runtime/test/context_concurrent_detach_test.cpp deleted file mode 100644 index 7181f2d94..000000000 --- a/runtime/test/context_concurrent_detach_test.cpp +++ /dev/null @@ -1,205 +0,0 @@ -#include "pch.h" -#include "XTaskQueue.h" -#include "XTaskQueuePriv.h" - -#include -#include -#include -#include -#include - -namespace -{ -struct State -{ - std::mutex mutex; - std::condition_variable cv; - XTaskQueueHandle owner = nullptr; - XTaskQueueHandle composite = nullptr; - bool monitorEntered = false; - bool closeReturned = false; - bool observedClose = false; - bool unexpectedMonitor = false; -}; - -void CALLBACK NoopCallback(void*, bool) -{ -} - -void CALLBACK Monitor( - void* context, - XTaskQueueHandle, - XTaskQueuePort port) -{ - auto* state = static_cast(context); - - if (port != XTaskQueuePort::Work) - { - state->unexpectedMonitor = true; - return; - } - - { - std::lock_guard lock(state->mutex); - - if (state->monitorEntered) - { - state->unexpectedMonitor = true; - return; - } - - state->monitorEntered = true; - } - - std::puts("TRACE: monitor entered"); - state->cv.notify_all(); - - std::unique_lock lock(state->mutex); - - state->observedClose = state->cv.wait_for( - lock, - std::chrono::seconds(4), - [&] { return state->closeReturned; }); - - std::printf( - "TRACE: close observed before monitor return=%d\n", - state->observedClose ? 1 : 0); -} - -bool Check(bool condition, const char* description) -{ - std::printf( - "%s %s\n", - condition ? "PASS" : "FAIL", - description); - - return condition; -} -} - -int main() -{ - std::setvbuf(stdout, nullptr, _IONBF, 0); - - int failures = 0; - State state; - - HRESULT hr = XTaskQueueCreate( - XTaskQueueDispatchMode::Manual, - XTaskQueueDispatchMode::Manual, - &state.owner); - - if (!Check(SUCCEEDED(hr) && state.owner != nullptr, - "owner queue created")) - { - return 2; - } - - XTaskQueuePortHandle work = nullptr; - XTaskQueuePortHandle completion = nullptr; - - HRESULT workHr = XTaskQueueGetPort( - state.owner, XTaskQueuePort::Work, &work); - HRESULT completionHr = XTaskQueueGetPort( - state.owner, XTaskQueuePort::Completion, &completion); - - if (!Check(SUCCEEDED(workHr) && SUCCEEDED(completionHr) && - work != nullptr && completion != nullptr, - "owner ports acquired")) - { - XTaskQueueCloseHandle(state.owner); - return 2; - } - - hr = XTaskQueueCreateComposite( - work, completion, &state.composite); - - if (!Check(SUCCEEDED(hr) && state.composite != nullptr, - "composite queue created")) - { - XTaskQueueCloseHandle(state.owner); - return 2; - } - - XTaskQueueRegistrationToken token = {}; - hr = XTaskQueueRegisterMonitor( - state.owner, &state, Monitor, &token); - - if (!Check(SUCCEEDED(hr), "monitor registered")) - { - XTaskQueueCloseHandle(state.composite); - XTaskQueueCloseHandle(state.owner); - return 2; - } - - std::thread closer([&] - { - { - std::unique_lock lock(state.mutex); - - if (!state.cv.wait_for( - lock, - std::chrono::seconds(4), - [&] { return state.monitorEntered; })) - { - return; - } - } - - std::puts("TRACE: worker closing composite"); - XTaskQueueCloseHandle(state.composite); - - { - std::lock_guard lock(state.mutex); - state.composite = nullptr; - state.closeReturned = true; - } - - std::puts("TRACE: worker close returned"); - state.cv.notify_all(); - }); - - hr = XTaskQueueSubmitCallback( - state.owner, - XTaskQueuePort::Work, - nullptr, - NoopCallback); - - if (!Check(SUCCEEDED(hr), "submission succeeded")) ++failures; - - closer.join(); - - if (!Check(state.monitorEntered, "monitor entered")) ++failures; - if (!Check(state.closeReturned, "worker close returned")) ++failures; - if (!Check(state.observedClose, - "close completed while monitor was active")) ++failures; - if (!Check(!state.unexpectedMonitor, - "no unexpected monitor invocation")) ++failures; - - XTaskQueueUnregisterMonitor(state.owner, token); - - while (XTaskQueueDispatch( - state.owner, XTaskQueuePort::Work, 0)) - { - } - - if (state.composite != nullptr) - { - XTaskQueueCloseHandle(state.composite); - } - - XTaskQueueCloseHandle(state.owner); - - if (!Check(XTaskQueueUninitialize(1000), - "all task queue references released")) - { - ++failures; - } - - std::printf( - "RESULT: %s (%d failures)\n", - failures == 0 ? "PASS" : "FAIL", - failures); - - return failures == 0 ? 0 : 1; -} diff --git a/runtime/test/context_pinning_test.cpp b/runtime/test/context_pinning_test.cpp deleted file mode 100644 index e8bad99b4..000000000 --- a/runtime/test/context_pinning_test.cpp +++ /dev/null @@ -1,113 +0,0 @@ -#include "pch.h" -#include "XTaskQueuePriv.h" -#include "TaskQueueP.h" -#include "referenced_ptr.h" -#include "TaskQueueImpl.h" - -#include - - -static int failures = 0; - -static void Check(bool condition, const char* description) -{ - std::printf("%s %s\n", - condition ? "PASS" : "FAIL", description); - - if (!condition) - ++failures; -} - -int main() -{ - std::setvbuf(stdout, nullptr, _IONBF, 0); - - XTaskQueueHandle handle = nullptr; - - HRESULT hr = XTaskQueueCreate( - XTaskQueueDispatchMode::Manual, - XTaskQueueDispatchMode::Manual, - &handle); - - Check(SUCCEEDED(hr) && handle != nullptr, - "queue created"); - - if (FAILED(hr) || handle == nullptr) - return 2; - - ITaskQueue* owner = GetQueue(handle); - - for (XTaskQueuePort port : - { XTaskQueuePort::Work, XTaskQueuePort::Completion }) - { - ITaskQueuePortContext* context = nullptr; - hr = owner->GetPortContext(port, &context); - - Check(SUCCEEDED(hr) && context != nullptr, - "context acquired"); - - if (FAILED(hr) || context == nullptr) - continue; - - // Unsupported capabilities must clear the output pointer. - void* unsupported = reinterpret_cast(1); - HRESULT unsupportedHr = context->QueryApi( - static_cast(0x7F000001), &unsupported); - - Check(unsupportedHr == E_NOINTERFACE && - unsupported == nullptr, - "unsupported capability clears output"); - - Check(context->QueryApi( - TaskQueueInternal::kPinnableContextApiId, - nullptr) == E_POINTER, - "null output pointer rejected"); - - void* queried = nullptr; - - hr = context->QueryApi( - TaskQueueInternal::kPinnableContextApiId, - &queried); - - Check(SUCCEEDED(hr) && queried != nullptr, - "pinning capability available"); - - if (SUCCEEDED(hr) && queried != nullptr) - { - auto* concrete = - static_cast(queried); - - Check( - static_cast(concrete) - == context, - "capability identifies original context"); - - Check(concrete->GetQueue() == owner, - "context preserves queue identity"); - - bool pinned = concrete->TryPin(); - - Check(pinned, - "live queue accepts temporary pin"); - - if (pinned) - concrete->Release(); - - // Balance the reference acquired by QueryApi. - concrete->Release(); - } - - // Balance GetPortContext. - context->Release(); - } - - XTaskQueueCloseHandle(handle); - - Check(XTaskQueueUninitialize(1000), - "all references released after closing queue"); - - std::printf("RESULT: %s (%d failures)\n", - failures == 0 ? "PASS" : "FAIL", failures); - - return failures == 0 ? 0 : 1; -} diff --git a/runtime/test/context_reentrant_test.cpp b/runtime/test/context_reentrant_test.cpp deleted file mode 100644 index 8a2ab99fe..000000000 --- a/runtime/test/context_reentrant_test.cpp +++ /dev/null @@ -1,182 +0,0 @@ -#include "pch.h" -#include "XTaskQueue.h" -#include "XTaskQueuePriv.h" - -#include - -namespace -{ -struct TestState -{ - XTaskQueueHandle owner = nullptr; - XTaskQueueHandle composite = nullptr; - int monitorCalls = 0; - bool closeReturned = false; - bool unexpectedCallback = false; -}; - -void CALLBACK NoopCallback(void*, bool) -{ -} - -void CALLBACK CloseCompositeMonitor( - void* context, - XTaskQueueHandle queue, - XTaskQueuePort port) -{ - auto* state = static_cast(context); - - std::printf( - "TRACE: monitor queue=%p owner=%p port=%u expectedPort=%u\n", - static_cast(queue), - static_cast(state->owner), - static_cast(port), - static_cast(XTaskQueuePort::Work)); - - if (port != XTaskQueuePort::Work) - { - state->unexpectedCallback = true; - return; - } - - ++state->monitorCalls; - - if (state->monitorCalls != 1 || state->composite == nullptr) - { - state->unexpectedCallback = true; - return; - } - - // B has no extra handles or queued entries holding it alive. - // Its final handle is closed while AtomicVector::Visit is active. - XTaskQueueHandle composite = state->composite; - state->composite = nullptr; - - std::puts("TRACE: monitor A entered"); - std::puts("TRACE: closing final handle of composite B"); - - XTaskQueueCloseHandle(composite); - - state->closeReturned = true; - std::puts("TRACE: composite B close returned"); -} - -bool Check(bool condition, const char* description) -{ - std::printf("%s %s\n", - condition ? "PASS" : "FAIL", - description); - return condition; -} -} - -int main() -{ - std::setvbuf(stdout, nullptr, _IONBF, 0); - - int failures = 0; - XTaskQueueHandle owner = nullptr; - - HRESULT hr = XTaskQueueCreate( - XTaskQueueDispatchMode::Manual, - XTaskQueueDispatchMode::Manual, - &owner); - - if (!Check(SUCCEEDED(hr) && owner != nullptr, - "owner queue A created")) - { - return 2; - } - - XTaskQueuePortHandle workPort = nullptr; - XTaskQueuePortHandle completionPort = nullptr; - - HRESULT workHr = XTaskQueueGetPort( - owner, XTaskQueuePort::Work, &workPort); - - HRESULT completionHr = XTaskQueueGetPort( - owner, XTaskQueuePort::Completion, &completionPort); - - if (!Check(SUCCEEDED(workHr) && - SUCCEEDED(completionHr) && - workPort != nullptr && - completionPort != nullptr, - "owner ports acquired")) - { - XTaskQueueCloseHandle(owner); - return 2; - } - - TestState state; - state.owner = owner; - - hr = XTaskQueueCreateComposite( - workPort, completionPort, &state.composite); - - if (!Check(SUCCEEDED(hr) && state.composite != nullptr, - "composite queue B created")) - { - XTaskQueueCloseHandle(owner); - return 2; - } - - XTaskQueueRegistrationToken token = {}; - - hr = XTaskQueueRegisterMonitor( - owner, &state, CloseCompositeMonitor, &token); - - if (!Check(SUCCEEDED(hr), "monitor registered on A")) - { - XTaskQueueCloseHandle(state.composite); - XTaskQueueCloseHandle(owner); - return 2; - } - - // Submit to A, not B: the queued entry cannot keep B alive. - // On the original implementation this call is expected to hang - // while B.Detach tries to remove an active AtomicVector reader. - std::puts("TRACE: submitting callback to A"); - - hr = XTaskQueueSubmitCallback( - owner, XTaskQueuePort::Work, nullptr, NoopCallback); - - if (!Check(SUCCEEDED(hr), "submission returned")) - ++failures; - - if (!Check(state.monitorCalls == 1, - "monitor invoked exactly once")) - ++failures; - - if (!Check(state.closeReturned, - "final close of B returned inside monitor")) - ++failures; - - if (!Check(!state.unexpectedCallback, - "no unexpected monitor invocation")) - ++failures; - - XTaskQueueUnregisterMonitor(owner, token); - - // Drain the callback submitted to A before releasing its handle. - while (XTaskQueueDispatch(owner, XTaskQueuePort::Work, 0)) - { - } - - if (state.composite != nullptr) - { - XTaskQueueCloseHandle(state.composite); - state.composite = nullptr; - } - - XTaskQueueCloseHandle(owner); - - if (!Check(XTaskQueueUninitialize(1000), - "all task queue references released")) - ++failures; - - std::printf("RESULT: %s (%d failures)\n", - failures == 0 ? "PASS" : "FAIL", - failures); - - return failures == 0 ? 0 : 1; -} diff --git a/runtime/test/context_rundown_test.cpp b/runtime/test/context_rundown_test.cpp deleted file mode 100644 index bf9fbe49c..000000000 --- a/runtime/test/context_rundown_test.cpp +++ /dev/null @@ -1,177 +0,0 @@ -#include "pch.h" -#include "referenced_ptr.h" -#include "XTaskQueuePriv.h" -#include "TaskQueueP.h" -#include "TaskQueueImpl.h" - -#include -#include -#include -#include - -struct Results -{ - std::atomic rundowns{0}; - std::atomic destructors{0}; - std::atomic rejected{0}; - std::atomic errors{0}; -}; - -class ProbeQueue final : public TaskQueueImpl -{ -public: - explicit ProbeQueue(Results& results) : results_(results) {} - - ~ProbeQueue() override - { - ++results_.destructors; - } - - void SetContext(TaskQueuePortContextImpl* context) - { - context_ = context; - } - -protected: - void RundownObject() override - { - ++results_.rundowns; - - auto tryRejected = [this]() - { - if (context_->TryPin()) - { - ++results_.errors; - context_->Release(); - } - else - { - ++results_.rejected; - } - }; - - // The final Release has already marked the queue as dying. - tryRejected(); - - // Internal AddRef must not clear the dying state. - AddRef(); - tryRejected(); - - // Both phases execute on a second thread while the - // rundown stack guarantees the object's lifetime. - std::atomic phase{0}; - - std::thread worker([&]() - { - while (phase.load() != 1) - std::this_thread::yield(); - - for (int i = 0; i < 1000; ++i) - tryRejected(); - - phase.store(2); - - while (phase.load() != 3) - std::this_thread::yield(); - - for (int i = 0; i < 1000; ++i) - tryRejected(); - - phase.store(4); - }); - - phase.store(1); - - while (phase.load() != 2) - std::this_thread::yield(); - - // Drop the temporary reference while still in rundown. - Release(); - phase.store(3); - - while (phase.load() != 4) - std::this_thread::yield(); - - worker.join(); - tryRejected(); - - TaskQueueImpl::RundownObject(); - } - -private: - Results& results_; - TaskQueuePortContextImpl* context_ = nullptr; -}; - -int main() -{ - std::setvbuf(stdout, nullptr, _IONBF, 0); - - Results results; - auto* queue = new (std::nothrow) ProbeQueue(results); - - if (!queue) - return 2; - - queue->AddRef(); - - ITaskQueuePortContext* context = nullptr; - HRESULT hr = queue->GetPortContext( - XTaskQueuePort::Work, &context); - - if (FAILED(hr) || !context) - { - std::puts("FAIL acquire context"); - queue->Release(); - return 3; - } - - void* raw = nullptr; - hr = context->QueryApi( - TaskQueueInternal::kPinnableContextApiId, &raw); - - if (FAILED(hr) || !raw) - { - std::puts("FAIL query pinning capability"); - context->Release(); - queue->Release(); - return 4; - } - - auto* concrete = - static_cast(raw); - - // Release QueryApi and GetPortContext references. - // The original queue reference keeps the context alive. - concrete->Release(); - context->Release(); - - queue->SetContext(concrete); - - // This triggers RundownObject and destroys the queue. - // Do not access queue or concrete after this call. - queue->Release(); - - bool passed = - results.rundowns.load() == 1 && - results.destructors.load() == 1 && - results.rejected.load() == 2003 && - results.errors.load() == 0; - - bool zeroRefs = XTaskQueueUninitialize(1000); - - std::printf( - "rundowns=%d destructors=%d rejected=%d errors=%d\n", - results.rundowns.load(), - results.destructors.load(), - results.rejected.load(), - results.errors.load()); - - std::printf("uninitialize=%s\n", - zeroRefs ? "PASS" : "FAIL"); - - std::printf("RESULT: %s\n", - passed && zeroRefs ? "PASS" : "FAIL"); - - return passed && zeroRefs ? 0 : 1; -} diff --git a/runtime/test/core_config_test.cpp b/runtime/test/core_config_test.cpp deleted file mode 100644 index 176eb00cb..000000000 --- a/runtime/test/core_config_test.cpp +++ /dev/null @@ -1,396 +0,0 @@ -// rt::config (core/config.h): the shape of the table, the order environment > file > default, the file reader and -// what it refuses, the file load() picks, the report, and leonida.example.toml against the table. No game files. -// -// core_config_test -#include "../core/config.h" - -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#if defined(_WIN32) -#include -#endif - -namespace { - -namespace config = rt::config; - -// A key that is in the table builds and names its row. One that is not does not build (Name's constructor), which -// a test that has to build cannot show; index_of_key is what that constructor asks. -static_assert(config::Name("paths.game_dir").index() == 0); -static_assert(config::Name("input.mouse_sensitivity").index() == config::kSettingCount - 1); -static_assert(config::index_of_key("vulkan.no_such_setting") == config::kSettingCount); - -int g_failures = 0; - -void expect(bool ok, const std::string& what) { - if (ok) return; - std::fprintf(stderr, "FAIL: %s\n", what.c_str()); - ++g_failures; -} - -bool contains(std::string_view text, std::string_view part) { return text.find(part) != std::string_view::npos; } - -// Sets (value) or removes (nullptr) an environment variable of this process. -void set_env(const char* name, const char* value) { -#if defined(_WIN32) - SetEnvironmentVariableA(name, value); -#else - if (value) - setenv(name, value, 1); - else - unsetenv(name); -#endif -} - -void set_env_path(const char* name, const std::filesystem::path& value) { -#if defined(_WIN32) - std::wstring wide_name; - for (const char* c = name; *c; ++c) wide_name.push_back(static_cast(*c)); - SetEnvironmentVariableW(wide_name.c_str(), value.c_str()); -#else - setenv(name, value.c_str(), 1); -#endif -} - -void write_file(const std::filesystem::path& file, std::string_view text) { - std::ofstream out(file, std::ios::binary); - out.write(text.data(), static_cast(text.size())); -} - -// What `values` holds for `key`; "" when the file did not set it. -std::string file_value(const config::FileValues& values, std::string_view key) { - const std::size_t index = config::index_of_key(key); - if (index == config::kSettingCount) return ""; - return values[index] ? *values[index] : ""; -} - -void test_table() { - std::set keys, variables; - for (std::size_t i = 0; i < config::kSettingCount; ++i) { - const config::Setting& setting = config::kSettings[i]; - const std::string_view key = setting.key, variable = setting.variable; - const std::string name(key); - const std::size_t dot = key.find('.'); - expect(dot != std::string_view::npos && dot > 0 && dot + 1 < key.size() && - key.find('.', dot + 1) == std::string_view::npos, - name + ": a key is section.name"); - expect(!variable.empty(), name + ": has a variable"); - expect(setting.fallback != nullptr, name + ": has a default, \"\" for not set"); - expect(keys.insert(key).second, name + ": the key is in the table once"); - expect(variables.insert(variable).second, name + ": its variable belongs to no other setting"); - const auto by_key = config::Name::find(key); - const auto by_variable = config::Name::find(variable); - expect(by_key && by_key->index() == i, name + ": found by key"); - expect(by_variable && by_variable->index() == i, name + ": found by variable"); - expect(&config::Name::at(i).setting() == &setting, name + ": at() names the row"); - } - expect(!config::Name::find("vulkan.no_such_setting"), "a key that is not in the table is not found"); - expect(!config::Name::find(""), "an empty name is not found"); - expect(variables.count(config::kFileVariable) == 0, "the variable that names the file is not a setting"); - expect(std::string_view(config::source_name(config::Source::Default)) == "default" && - std::string_view(config::source_name(config::Source::File)) == "file" && - std::string_view(config::source_name(config::Source::Environment)) == "environment", - "the three sources have their names"); -} - -void test_order(const std::filesystem::path& dir) { - const auto validation = [] { return config::get("vulkan.validation"); }; - config::Value value = validation(); - expect(value.text == "0" && value.source == config::Source::Default && !value.is_set(), - "nothing set: the default"); - - const std::filesystem::path file = dir / "order.toml"; - write_file(file, "[vulkan]\nvalidation = true\n"); - std::string error; - expect(config::load_file(file, &error), "load_file reads a good file: " + error); - value = validation(); - expect(value.text == "1" && value.source == config::Source::File && value.is_set(), - "set in the file: the file's value"); - expect(config::get("vulkan.arena_mb").source == config::Source::Default, - "a setting the file leaves out keeps its default"); - - // The environment is read at each call, so a variable set after an earlier read is seen. - set_env("LEONIDA_VK_VALIDATION", "2"); - value = validation(); - expect(value.text == "2" && value.source == config::Source::Environment, "the variable wins over the file"); - set_env("LEONIDA_VK_VALIDATION", ""); - expect(validation().source == config::Source::File, "an empty variable counts as not set"); - set_env("LEONIDA_VK_VALIDATION", nullptr); - expect(validation().source == config::Source::File, "the variable removed: the file's value again"); - - config::unload(); - expect(validation().source == config::Source::Default && config::loaded_file().empty(), - "unload() forgets the file"); - - expect(config::path("paths.game_dir").empty(), "a path that is not set is empty"); - const std::filesystem::path game = dir / "game folder"; - set_env_path("LEONIDA_GAME_DIR", game); - expect(config::path("paths.game_dir") == game, "a path from the environment"); - set_env("LEONIDA_GAME_DIR", nullptr); -#if defined(_WIN32) - // UTF-8 in Value::text and the same characters back in path(): a folder named outside the ANSI code page - // reaches the reader intact. - const wchar_t wide[] = L"C:\\Spiele\\Gr\u00F6\u00DFe \u30B2\u30FC\u30E0"; - SetEnvironmentVariableW(L"LEONIDA_GAME_DIR", wide); - expect(config::get("paths.game_dir").text == - "C:\\Spiele\\Gr\xC3\xB6\xC3\x9F" "e \xE3\x82\xB2\xE3\x83\xBC\xE3\x83\xA0", - "a wide value is returned as UTF-8"); - expect(config::path("paths.game_dir").native() == wide, "a wide value comes back whole as a path"); - SetEnvironmentVariableW(L"LEONIDA_GAME_DIR", nullptr); -#endif -} - -void test_parse() { - const std::string_view good = - "\xEF\xBB\xBF# a comment, after the byte order mark Notepad writes\r\n" - "[paths]\r\n" - "game_dir = 'D:\\games\\gta6' # single quotes: as written\r\n" - "save_dir = \"D:\\\\saves \\\"one\\\"\"\r\n" - "shaders = ''\r\n" - "\r\n" - " [vulkan] # a second section\r\n" - "validation = true\r\n" - "graphics_family_only=false\r\n" - "arena_mb = 512\r\n" - "[input]\n" - "ds_trigger_gain = 1.5\n" - "[loader]\n" - "rng_seed = 0x1F\n" - "[present]\n" - "sdr_eotf = 'gamma22 # not a comment'"; // and no line break at the end - config::FileValues values; - std::string error; - expect(config::parse(good, "f.toml", &values, &error), "a file in the format is read: " + error); - const auto is = [&](std::string_view key, std::string_view want) { - const std::string got = file_value(values, key); - expect(got == want, std::string(key) + ": read \"" + got + "\", expected \"" + std::string(want) + "\""); - }; - is("paths.game_dir", "D:\\games\\gta6"); - is("paths.save_dir", "D:\\saves \"one\""); - is("paths.shaders", ""); // '' leaves a setting unset - is("vulkan.validation", "1"); - is("vulkan.graphics_family_only", "0"); - is("vulkan.arena_mb", "512"); - is("vulkan.device", ""); - is("input.ds_trigger_gain", "1.5"); - is("loader.rng_seed", "0x1F"); - is("present.sdr_eotf", "gamma22 # not a comment"); - - struct Refused { - const char* what; - const char* text; - int line; // the line the error names - const char* part; // text the error contains - }; - const Refused refused[] = { - {"an unknown section", "[nope]\n", 1, "no section [nope]"}, - {"a section with a dot", "# first\n[paths.sub]\n", 2, "no section [paths.sub]"}, - {"an unknown name", "[paths]\nnope = 1\n", 2, "no setting paths.nope"}, - {"a name of another section", "[paths]\nvalidation = true\n", 2, "no setting paths.validation"}, - {"a name set twice", "[paths]\ngame_dir = 'a'\ngame_dir = 'b'\n", 3, "paths.game_dir is set twice"}, - {"a name set twice, first to ''", "[paths]\nshaders = ''\nshaders = 'b'\n", 3, "set twice"}, - {"a section twice", "[paths]\n[vulkan]\n[paths]\n", 3, "[paths] is in the file twice"}, - {"a setting above every section", "game_dir = 'a'\n", 1, "[section]"}, - {"a single quote left open", "[paths]\ngame_dir = 'a\n", 2, "closing '"}, - {"a double quote left open", "[paths]\ngame_dir = \"a\n", 2, "closing \""}, - {"a Windows path in double quotes", "[paths]\ngame_dir = \"D:\\games\"\n", 2, "single quotes"}, - {"text without quotes", "[paths]\ngame_dir = D:\\games\n", 2, "in quotes"}, - {"True with a capital", "[vulkan]\nvalidation = True\n", 2, "in quotes"}, - {"a number that ends in a dot", "[vulkan]\narena_mb = 1.\n", 2, "in quotes"}, - {"two values", "[paths]\ngame_dir = 'a' 'b'\n", 2, "# comment"}, - {"no value", "[paths]\ngame_dir =\n", 2, "missing"}, - {"no equals sign", "[paths]\ngame_dir\n", 2, "name = value"}, - {"a section left open", "[paths\n", 1, "closing ]"}, - {"text after a section", "[paths] x\n", 1, "# comment"}, - }; - for (const Refused& r : refused) { - config::FileValues kept; - kept[0] = "kept"; - error.clear(); - const bool ok = config::parse(r.text, "f.toml", &kept, &error); - const std::string start = "f.toml:" + std::to_string(r.line) + ": "; - expect(!ok && error.rfind(start, 0) == 0 && contains(error, r.part), - std::string(r.what) + " is refused with its line; the error was \"" + error + "\""); - expect(kept[0] == "kept", std::string(r.what) + ": a refused file changes no value"); - } -} - -void test_load(const std::filesystem::path& dir) { - const auto gamertag = [] { return config::get("system.gamertag"); }; - std::string error; - expect(config::load({}, &error) && config::loaded_file().empty(), - "no program folder and no variable: nothing to read, and that is not an error"); - expect(config::load(dir, &error) && config::loaded_file().empty(), - "a program folder without leonida.toml: nothing to read"); - expect(gamertag().text == "Player" && gamertag().source == config::Source::Default, "no file: the default"); - - write_file(dir / config::kFileName, "[system]\ngamertag = 'Beside'\n"); - expect(config::load(dir, &error), "leonida.toml in the program folder is read: " + error); - expect(config::loaded_file().filename() == config::kFileName && config::loaded_file().is_absolute(), - "loaded_file() names it with its folder"); - expect(gamertag().text == "Beside" && gamertag().source == config::Source::File, - "its value is the one get() returns"); - - write_file(dir / "named.toml", "[system]\ngamertag = 'Named'\n"); - set_env_path(config::kFileVariable, dir / "named.toml"); - expect(config::load(dir, &error) && gamertag().text == "Named", - "the file the variable names is read instead of the one in the program folder: " + error); - - set_env_path(config::kFileVariable, dir / "missing.toml"); - error.clear(); - expect(!config::load(dir, &error) && contains(error, config::kFileVariable) && contains(error, "missing.toml"), - "a variable that names no file is an error that says so; the error was \"" + error + "\""); - expect(gamertag().text == "Named", "a failed load keeps the values loaded before"); - - write_file(dir / "bad.toml", "[system]\ngamer_tag = 'Typo'\n"); - set_env_path(config::kFileVariable, dir / "bad.toml"); - error.clear(); - expect(!config::load(dir, &error) && contains(error, "bad.toml:2: ") && contains(error, "system.gamer_tag"), - "a misspelt setting is an error with file and line; the error was \"" + error + "\""); - expect(gamertag().text == "Named", "a refused file keeps the values loaded before"); - - set_env(config::kFileVariable, nullptr); - config::unload(); - expect(gamertag().text == "Player", "unloaded: the default again"); -} - -// The report's line for `key`, without its line break; empty when there is none. -std::string_view report_line(std::string_view report, std::string_view key) { - while (!report.empty()) { - const std::size_t newline = report.find('\n'); - const std::string_view line = report.substr(0, newline); - report.remove_prefix(newline == std::string_view::npos ? report.size() : newline + 1); - if (line.size() > key.size() && line.substr(0, key.size()) == key && line[key.size()] == ' ') return line; - } - return {}; -} - -void test_report() { - config::unload(); - set_env("LEONIDA_GAMERTAG", "Tester"); - const std::string report = config::report(); - set_env("LEONIDA_GAMERTAG", nullptr); - - std::size_t lines = 0; - for (const char c : report) lines += c == '\n'; - expect(lines == config::kSettingCount + 1, "the report has a line for the file and one per setting"); - expect(report.rfind("settings file: none", 0) == 0, "without a file the first line says so"); - const std::string_view from_environment = report_line(report, "system.gamertag"); - expect(contains(from_environment, " environment ") && contains(from_environment, " LEONIDA_GAMERTAG ") && - from_environment.ends_with(" Tester"), - "a setting from the environment: source, variable and value; the line was \"" + - std::string(from_environment) + "\""); - const std::string_view not_set = report_line(report, "paths.game_dir"); - expect(contains(not_set, " default ") && not_set.ends_with(" (not set)"), - "a setting without a value; the line was \"" + std::string(not_set) + "\""); -} - -// The name a line of the example file sets: "name = value", or the same behind "# " (a default, shown but off). -// Empty for any other line. -std::string_view setting_name(std::string_view line, bool* commented) { - *commented = line.substr(0, 2) == "# "; - if (*commented) line.remove_prefix(2); - const auto in_name = [](char c) { return (c >= 'a' && c <= 'z') || (c >= '0' && c <= '9') || c == '_'; }; - std::size_t n = 0; - while (n < line.size() && in_name(line[n])) ++n; - if (n == 0 || line.substr(n, 3) != " = ") return {}; - return line.substr(0, n); -} - -// True when `text` names `variable` as a whole word, not as the start or end of a longer name. -bool names_variable(std::string_view text, std::string_view variable) { - const auto in_name = [](char c) { return (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || c == '_'; }; - for (std::size_t at = text.find(variable); at != std::string_view::npos; at = text.find(variable, at + 1)) { - const std::size_t end = at + variable.size(); - if ((at == 0 || !in_name(text[at - 1])) && (end == text.size() || !in_name(text[end]))) return true; - } - return false; -} - -void test_example(const std::filesystem::path& file) { - std::ifstream in(file, std::ios::binary); - expect(in.is_open(), "the example file named on the command line can be opened"); - if (!in.is_open()) return; - const std::string text{std::istreambuf_iterator(in), std::istreambuf_iterator()}; - const std::string name = "leonida.example.toml"; - - config::FileValues as_written; - std::string error; - expect(config::parse(text, name, &as_written, &error), "the example is read as it is written: " + error); - expect(names_variable(text, config::kFileVariable), "the example names the variable that selects the file"); - - // With every "# name = value" line switched on, the file has to name each setting once, under its section and - // with its variable, and give it the default of the table. - std::string switched_on, section; - std::set listed; - std::string_view rest = text; - while (!rest.empty()) { - const std::size_t newline = rest.find('\n'); - std::string_view line = rest.substr(0, newline); - rest.remove_prefix(newline == std::string_view::npos ? rest.size() : newline + 1); - if (!line.empty() && line.back() == '\r') line.remove_suffix(1); - if (line.size() > 2 && line.front() == '[' && line.back() == ']') section = line.substr(1, line.size() - 2); - bool commented = false; - if (const std::string_view setting = setting_name(line, &commented); !setting.empty()) { - listed.insert(section + "." + std::string(setting)); - if (commented) line.remove_prefix(2); - } - switched_on.append(line).append("\n"); - } - config::FileValues defaults; - error.clear(); - const bool parsed = config::parse(switched_on, name, &defaults, &error); - expect(parsed, "the example is read with every setting switched on: " + error); - for (std::size_t i = 0; i < config::kSettingCount; ++i) { - const config::Setting& setting = config::kSettings[i]; - const std::string key = setting.key; - expect(listed.count(key) == 1, key + " is in the example"); - expect(names_variable(text, setting.variable), key + ": the example names " + setting.variable); - if (parsed) - expect(defaults[i].value_or("") == setting.fallback, - key + ": the example shows the default, \"" + setting.fallback + "\""); - } - expect(listed.size() == config::kSettingCount, "the example lists the settings of the table and no others"); -} - -} // namespace - -int main(int argc, char** argv) { - if (argc != 2) { - std::fprintf(stderr, "usage: core_config_test \n"); - return 2; - } - // The settings of whoever runs this must not decide its result. - for (const config::Setting& setting : config::kSettings) set_env(setting.variable, nullptr); - set_env(config::kFileVariable, nullptr); - - std::error_code failed; - const auto now = std::chrono::steady_clock::now().time_since_epoch().count(); - const std::filesystem::path dir = - std::filesystem::temp_directory_path(failed) / ("leonida_core_config_test_" + std::to_string(now)); - std::filesystem::create_directories(dir, failed); - expect(!failed, "the scratch folder can be made"); - - test_table(); - test_order(dir); - test_parse(); - test_load(dir); - test_report(); - test_example(argv[1]); - - std::filesystem::remove_all(dir, failed); - if (g_failures) { - std::fprintf(stderr, "%d check(s) failed\n", g_failures); - return 1; - } - std::puts("core_config_test: ok"); - return 0; -} diff --git a/runtime/test/core_log_test.cpp b/runtime/test/core_log_test.cpp deleted file mode 100644 index 84623fe60..000000000 --- a/runtime/test/core_log_test.cpp +++ /dev/null @@ -1,298 +0,0 @@ -// rt::log (core/log.h): which lines each level lets through, the "[rt] " prefix, that a line held back evaluates -// none of its arguments, a value that is not a level, and the order environment > file > default of log.level -// (LEONIDA_LOG), where an empty variable falls through to the file. No game files. -#include "../core/log.h" - -#include "../core/config.h" - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#if defined(_WIN32) -#include -#include -#else -#include -#endif - -namespace { - -namespace config = rt::config; -namespace rtlog = rt::log; -using rtlog::Level; - -constexpr Level kLevels[] = {Level::Off, Level::Error, Level::Warn, Level::Info, Level::Debug, Level::Trace}; - -// A level is named in any case; nothing else is a level. -static_assert(rtlog::parse_level("off") == Level::Off && rtlog::parse_level("trace") == Level::Trace); -static_assert(rtlog::parse_level("WARN") == Level::Warn && rtlog::parse_level("Debug") == Level::Debug); -static_assert(!rtlog::parse_level("") && !rtlog::parse_level("warning") && !rtlog::parse_level("warn ") && - !rtlog::parse_level("1")); - -int g_failures = 0; - -void expect(bool ok, const std::string& what) { - if (ok) return; - std::fprintf(stderr, "FAIL: %s\n", what.c_str()); - ++g_failures; -} - -bool contains(std::string_view text, std::string_view part) { return text.find(part) != std::string_view::npos; } - -// Sets (value) or removes (nullptr) an environment variable of this process. -void set_env(const char* name, const char* value) { -#if defined(_WIN32) - SetEnvironmentVariableA(name, value); -#else - if (value) - setenv(name, value, 1); - else - unsetenv(name); -#endif -} - -void write_file(const std::filesystem::path& file, std::string_view text) { - std::ofstream out(file, std::ios::binary); - out.write(text.data(), static_cast(text.size())); -} - -#if defined(_WIN32) -int dup_fd(int fd) { return _dup(fd); } -int dup2_fd(int from, int to) { return _dup2(from, to); } -void close_fd(int fd) { _close(fd); } -int fd_of(std::FILE* stream) { return _fileno(stream); } -std::FILE* open_for_writing(const std::filesystem::path& file) { - std::FILE* out = nullptr; - if (_wfopen_s(&out, file.c_str(), L"wb") != 0) return nullptr; // wide: a TEMP outside the ANSI code page - return out; -} -#else -int dup_fd(int fd) { return dup(fd); } -int dup2_fd(int from, int to) { return dup2(from, to); } -void close_fd(int fd) { close(fd); } -int fd_of(std::FILE* stream) { return fileno(stream); } -std::FILE* open_for_writing(const std::filesystem::path& file) { return std::fopen(file.c_str(), "wb"); } -#endif - -// What `body` writes to stderr, without carriage returns. *redirected is false when stderr could not be sent to -// `file`; the text is then empty, which must not read as "nothing was printed". -std::string stderr_of(const std::filesystem::path& file, bool* redirected, const std::function& body) { - *redirected = false; - std::fflush(stderr); - const int stderr_fd = fd_of(stderr); - const int saved = dup_fd(stderr_fd); - std::FILE* out = open_for_writing(file); - if (out && saved >= 0) *redirected = dup2_fd(fd_of(out), stderr_fd) >= 0; - if (out) std::fclose(out); - if (*redirected) body(); - std::fflush(stderr); - if (saved >= 0) { - if (*redirected) dup2_fd(saved, stderr_fd); - close_fd(saved); - } - if (!*redirected) return {}; - std::ifstream in(file, std::ios::binary); - std::string text{std::istreambuf_iterator(in), std::istreambuf_iterator()}; - std::erase(text, '\r'); - return text; -} - -void test_levels() { - expect(rtlog::level() == rtlog::kDefaultLevel, "a program that sets no level logs at the default"); - expect(rtlog::kDefaultLevel == Level::Debug, - "the default lets every line through but trace lines, which is what was printed before the levels"); - for (const Level in_use : kLevels) { - const std::string name = rtlog::level_name(in_use); - rtlog::set_level(in_use); - expect(rtlog::level() == in_use, "set_level(" + name + ") is the level in use"); - for (const Level line : kLevels) { - const bool want = line != Level::Off && static_cast(line) <= static_cast(in_use); - expect(rtlog::enabled(line) == want, "at " + name + ", a line of level " + rtlog::level_name(line) + - (want ? " is printed" : " is held back")); - } - const auto named = rtlog::parse_level(name); - expect(named && *named == in_use, name + " is read back from its name"); - expect(contains(rtlog::kLevelList, name), "the list a warning shows names " + name); - } - rtlog::set_level(rtlog::kDefaultLevel); -} - -void test_output(const std::filesystem::path& dir) { - int evaluated = 0; - const auto number = [&](int value) { - ++evaluated; - return value; - }; - const auto all_five = [&] { - RT_LOG_ERROR("log_test: error %d\n", number(1)); - RT_LOG_WARN("log_test: warn %d\n", number(2)); - RT_LOG_INFO("log_test: info %s %d\n", "text", number(3)); - RT_LOG_DEBUG("log_test: debug %d\n", number(4)); - RT_LOG_TRACE("log_test: trace %d\n", number(5)); - RT_LOG_ERROR("log_test: no arguments\n"); - }; - struct Case { - Level in_use; - const char* text; - int evaluated; - }; - const Case cases[] = { - {Level::Off, "", 0}, - {Level::Error, "[rt] log_test: error 1\n[rt] log_test: no arguments\n", 1}, - {Level::Warn, "[rt] log_test: error 1\n[rt] log_test: warn 2\n[rt] log_test: no arguments\n", 2}, - {Level::Info, - "[rt] log_test: error 1\n[rt] log_test: warn 2\n[rt] log_test: info text 3\n" - "[rt] log_test: no arguments\n", - 3}, - {Level::Debug, - "[rt] log_test: error 1\n[rt] log_test: warn 2\n[rt] log_test: info text 3\n[rt] log_test: debug 4\n" - "[rt] log_test: no arguments\n", - 4}, - {Level::Trace, - "[rt] log_test: error 1\n[rt] log_test: warn 2\n[rt] log_test: info text 3\n[rt] log_test: debug 4\n" - "[rt] log_test: trace 5\n[rt] log_test: no arguments\n", - 5}, - }; - for (const Case& c : cases) { - const std::string name = rtlog::level_name(c.in_use); - rtlog::set_level(c.in_use); - evaluated = 0; - bool redirected = false; - const std::string text = stderr_of(dir / "output.txt", &redirected, all_five); - expect(redirected, "at " + name + ": stderr can be sent to a file"); - if (!redirected) continue; - expect(text == c.text, - "at " + name + " the lines printed are its own, each with the [rt] prefix; got \"" + text + "\""); - expect(evaluated == c.evaluated, - "at " + name + " a line held back evaluates none of its arguments (" + std::to_string(evaluated) + - " evaluated, expected " + std::to_string(c.evaluated) + ")"); - } - rtlog::set_level(rtlog::kDefaultLevel); -} - -void test_settings(const std::filesystem::path& dir) { - constexpr config::Name setting("log.level"); - const char* const variable = setting.setting().variable; - expect(std::string_view(variable) == "LEONIDA_LOG", "log.level is set by LEONIDA_LOG"); - expect(std::string_view(setting.setting().fallback) == rtlog::level_name(rtlog::kDefaultLevel), - "the default in kSettings is the default of the log"); - - // environment > file > default - std::string warning = "left over"; - const auto asked = [&] { return rtlog::level_from_settings(&warning); }; - expect(asked() == rtlog::kDefaultLevel && warning.empty(), "nothing set: the default, and no warning"); - - const std::filesystem::path file = dir / "log.toml"; - write_file(file, "[log]\nlevel = 'warn'\n"); - std::string error; - expect(config::load_file(file, &error), "a file that sets log.level is read: " + error); - expect(asked() == Level::Warn && warning.empty(), "set in the file: the file's level"); - - set_env(variable, "error"); - expect(asked() == Level::Error && warning.empty(), "the variable wins over the file"); - const std::string report = config::report(); - const std::size_t at = report.find("\nlog.level "); - std::string_view line; - if (at != std::string::npos) { - line = std::string_view(report).substr(at + 1); - line = line.substr(0, line.find('\n')); - } - expect(contains(line, " environment ") && contains(line, " LEONIDA_LOG ") && line.ends_with(" error"), - "the report (`gta6rt config`) shows log.level with its source, variable and value; the line was \"" + - std::string(line) + "\""); - set_env(variable, "TRACE"); - expect(asked() == Level::Trace && warning.empty(), "a level is named in any case"); - set_env(variable, ""); - expect(asked() == Level::Warn && warning.empty(), "an empty variable falls through to the file"); - set_env(variable, nullptr); - expect(asked() == Level::Warn && warning.empty(), "the variable removed: the file's level again"); - - // A value that is not a level: the default, and one warning that lists the levels. - set_env(variable, "loud"); - const std::string want = "log: LEONIDA_LOG=loud unknown (off, error, warn, info, debug or trace), using debug"; - Level got = asked(); - expect(got == rtlog::kDefaultLevel && warning == want, - "an unknown value gives the default and a warning that lists the levels; the warning was \"" + warning + - "\""); - expect(rtlog::level_from_settings() == rtlog::kDefaultLevel, "the warning is optional"); - set_env(variable, nullptr); - write_file(file, "[log]\nlevel = 'verbose'\n"); - expect(config::load_file(file, &error), "a file with an unknown level is still a file in the format: " + error); - got = asked(); - expect(got == rtlog::kDefaultLevel && contains(warning, "LEONIDA_LOG=verbose "), - "an unknown value from the file gives the default too and names the variable; the warning was \"" + - warning + "\""); - config::unload(); - expect(asked() == rtlog::kDefaultLevel && warning.empty(), "the file forgotten: the default again"); - - // apply_settings() makes it the level in use and prints the warning once, as a log line. - bool redirected = false; - rtlog::set_level(Level::Off); // the warning is printed although the level before was off - set_env(variable, "loud"); - std::string text = stderr_of(dir / "apply.txt", &redirected, [] { rtlog::apply_settings(); }); - expect(redirected, "stderr can be sent to a file"); - if (redirected) - expect(text == "[rt] " + want + "\n", "apply_settings() prints the warning once; got \"" + text + "\""); - expect(rtlog::level() == rtlog::kDefaultLevel, "apply_settings() with an unknown value: the default is in use"); - - rtlog::set_level(Level::Off); - text = stderr_of(dir / "apply.txt", &redirected, [] { rtlog::apply_settings(false); }); - expect(redirected && text.empty() && rtlog::level() == rtlog::kDefaultLevel, - "apply_settings(false) uses the default for an unknown value without printing; got \"" + text + "\""); - - set_env(variable, "off"); - text = stderr_of(dir / "apply.txt", &redirected, [] { - rtlog::apply_settings(); - RT_LOG_ERROR("log_test: must not be printed\n"); - }); - expect(redirected && text.empty() && rtlog::level() == Level::Off, - "LEONIDA_LOG=off: apply_settings() prints nothing and no line follows; got \"" + text + "\""); - - set_env(variable, "warn"); - text = stderr_of(dir / "apply.txt", &redirected, [] { - rtlog::apply_settings(); - RT_LOG_WARN("log_test: kept\n"); - RT_LOG_INFO("log_test: held back\n"); - }); - expect(redirected && text == "[rt] log_test: kept\n" && rtlog::level() == Level::Warn, - "LEONIDA_LOG=warn: warnings are printed, info lines are not; got \"" + text + "\""); - - set_env(variable, nullptr); - rtlog::apply_settings(); - expect(rtlog::level() == rtlog::kDefaultLevel, "nothing set: apply_settings() goes back to the default"); -} - -} // namespace - -int main() { - // The settings of whoever runs this must not decide its result. - for (const config::Setting& setting : config::kSettings) set_env(setting.variable, nullptr); - set_env(config::kFileVariable, nullptr); - - std::error_code failed; - const auto now = std::chrono::steady_clock::now().time_since_epoch().count(); - const std::filesystem::path dir = - std::filesystem::temp_directory_path(failed) / ("leonida_core_log_test_" + std::to_string(now)); - std::filesystem::create_directories(dir, failed); - expect(!failed, "the scratch folder can be made"); - - test_levels(); - test_output(dir); - test_settings(dir); - - std::filesystem::remove_all(dir, failed); - if (g_failures) { - std::fprintf(stderr, "%d check(s) failed\n", g_failures); - return 1; - } - std::puts("core_log_test: ok"); - return 0; -} diff --git a/runtime/test/cpp_unwind_test.cpp b/runtime/test/cpp_unwind_test.cpp deleted file mode 100644 index 30cfc6ca1..000000000 --- a/runtime/test/cpp_unwind_test.cpp +++ /dev/null @@ -1,31 +0,0 @@ -#include - -namespace { - -struct UnwindMarker { - bool& destroyed; - ~UnwindMarker() { destroyed = true; } -}; - -struct TestException {}; - -// Keep the object in a separate frame, outside the catch handler's function. -__declspec(noinline) void throw_with_marker(bool& destroyed) { - UnwindMarker marker{destroyed}; - throw TestException{}; -} - -} // namespace - -int main() { - bool destroyed = false; - try { - throw_with_marker(destroyed); - } catch (const TestException&) { - if (destroyed) return 0; - std::fputs("C++ exception unwound without running a destructor\n", stderr); - return 1; - } - std::fputs("Expected a C++ exception\n", stderr); - return 1; -} diff --git a/runtime/test/cpu_emulation_test.cpp b/runtime/test/cpu_emulation_test.cpp deleted file mode 100644 index 4e1ef3cdb..000000000 --- a/runtime/test/cpu_emulation_test.cpp +++ /dev/null @@ -1,282 +0,0 @@ -// The Zen 2 instruction emulation (src/cpu_emulation.h, docs/cpu_features.md): the decoder on hand-written -// encodings, the bit-field helpers, `apply` on a synthetic CONTEXT, and then each instruction run for real from an -// executable buffer with the handler installed. On a host that has the feature the CPU runs it and the results -// must be the same; on one that lacks it (an Intel CPU for SSE4a, CLZERO and MONITORX) the handler does the work. -// The test prints which path each instruction took. No game files. -#include - -#include -#include -#include -#include -#include - -#include "cpu_emulation.h" - -namespace ce = rt::cpu_emulation; - -namespace { -int failures = 0; - -void check(bool ok, const char* what) { - if (!ok) { - std::fprintf(stderr, "FAIL %s\n", what); - ++failures; - } -} - -ce::Decoded dec(std::initializer_list bytes) { - std::vector v(bytes); - return ce::decode(v.data(), v.size()); -} - -void test_decode() { - ce::Decoded d = dec({0xF2, 0x0F, 0x78, 0xC1, 0x10, 0x08}); // insertq xmm0, xmm1, 16, 8 - check(d.op == ce::Op::insertq_imm && d.length == 6 && d.dst == 0 && d.src == 1 && d.len == 16 && d.idx == 8, - "insertq imm"); - d = dec({0xF2, 0x45, 0x0F, 0x78, 0xD3, 0x05, 0x3B}); // insertq xmm10, xmm11, 5, 59 - check(d.op == ce::Op::insertq_imm && d.length == 7 && d.dst == 10 && d.src == 11 && d.len == 5 && d.idx == 59, - "insertq imm with REX"); - d = dec({0xF2, 0x0F, 0x79, 0xCA}); // insertq xmm1, xmm2 - check(d.op == ce::Op::insertq_reg && d.length == 4 && d.dst == 1 && d.src == 2, "insertq reg"); - d = dec({0x66, 0x0F, 0x78, 0xC3, 0x08, 0x04}); // extrq xmm3, 8, 4 - check(d.op == ce::Op::extrq_imm && d.length == 6 && d.dst == 3 && d.len == 8 && d.idx == 4, "extrq imm"); - d = dec({0x66, 0x41, 0x0F, 0x78, 0xC7, 0x00, 0x00}); // extrq xmm15, 0, 0 - check(d.op == ce::Op::extrq_imm && d.dst == 15 && d.length == 7, "extrq imm with REX.B"); - d = dec({0x66, 0x0F, 0x79, 0xE9}); // extrq xmm5, xmm1 - check(d.op == ce::Op::extrq_reg && d.dst == 5 && d.src == 1 && d.length == 4, "extrq reg"); - check(dec({0x66, 0x0F, 0x78, 0xC8, 0x08, 0x04}).op == ce::Op::none, "extrq imm needs /0"); - check(dec({0xF2, 0x0F, 0x78, 0x01, 0x08, 0x04}).op == ce::Op::none, "insertq needs a register operand"); - check(dec({0x0F, 0x78, 0xC1}).op == ce::Op::none, "0F 78 without F2/66 is VMREAD, not SSE4a"); - check(dec({0xF3, 0x0F, 0x78, 0xC1, 1, 1}).op == ce::Op::none, "F3 0F 78 is not SSE4a"); - - d = dec({0x0F, 0x01, 0xFC}); - check(d.op == ce::Op::clzero && d.length == 3 && !d.addr32, "clzero"); - d = dec({0x67, 0x0F, 0x01, 0xFC}); - check(d.op == ce::Op::clzero && d.length == 4 && d.addr32, "clzero with 67"); - check(dec({0x0F, 0x01, 0xFA}).op == ce::Op::monitorx, "monitorx"); - check(dec({0x0F, 0x01, 0xFB}).op == ce::Op::mwaitx, "mwaitx"); - check(dec({0x0F, 0x01, 0xF9}).op == ce::Op::none, "rdtscp is not handled"); - check(dec({0xF3, 0x0F, 0x01, 0xFA}).op == ce::Op::none, "F3 0F 01 FA is MCOMMIT, not monitorx"); - for (uint8_t pfx : {uint8_t(0x66), uint8_t(0xF2), uint8_t(0xF3), uint8_t(0x48)}) { - d = dec({pfx, 0x0F, 0x01, 0xFC}); - check(d.op == ce::Op::clzero && d.length == 4, "clzero with 66, F2, F3 or REX (native on Zen 3)"); - } - d = dec({0x48, 0x66, 0x0F, 0x01, 0xFC}); - check(d.op == ce::Op::clzero && d.length == 5, "clzero with REX before 66 (the REX is ignored)"); - d = dec({0x48, 0x48, 0x0F, 0x01, 0xFC}); - check(d.op == ce::Op::clzero && d.length == 5, "clzero with two REX bytes"); - check(dec({0xF2, 0x0F, 0x01, 0xFB}).op == ce::Op::none, "F2 0F 01 FB is not mwaitx"); - d = dec({0x48, 0x66, 0x0F, 0x78, 0xC1, 1, 1}); - check(d.op == ce::Op::extrq_imm && d.dst == 1, "a REX before 66 does not extend extrq's register"); - d = dec({0x66, 0x0F, 0x01, 0xFC}); - check(d.op == ce::Op::clzero && d.length == 4, "clzero with 66"); - d = dec({0x64, 0x48, 0x0F, 0x01, 0xFC}); - check(d.op == ce::Op::clzero && d.length == 5, "clzero with a segment override and REX"); - check(dec({0xF0, 0x0F, 0x01, 0xFC}).op == ce::Op::none, "LOCK clzero stays #UD"); - - check(dec({0x66, 0x0F, 0xAE, 0x31}).length == 4, "clwb [rcx]"); - check(dec({0x66, 0x0F, 0xAE, 0x74, 0x01, 0x08}).length == 6, "clwb [rcx+rax+8]"); - check(dec({0x66, 0x0F, 0xAE, 0xB1, 0, 1, 0, 0}).length == 8, "clwb [rcx+disp32]"); - check(dec({0x66, 0x0F, 0xAE, 0x35, 1, 2, 3, 4}).length == 8, "clwb [rip+disp32]"); - check(dec({0x66, 0x0F, 0xAE, 0x34, 0x25, 1, 2, 3, 4}).length == 9, "clwb [disp32] through SIB"); - check(dec({0x66, 0x41, 0x0F, 0xAE, 0x30}).length == 5 && dec({0x66, 0x41, 0x0F, 0xAE, 0x30}).op == ce::Op::clwb, - "clwb [r8]"); - check(dec({0x0F, 0xAE, 0x31}).op == ce::Op::none, "0F AE /6 without 66 is xsaveopt"); - check(dec({0x66, 0x0F, 0xAE, 0xF1}).op == ce::Op::none, "66 0F AE /6 with a register is not clwb"); - check(dec({0x66, 0x0F, 0xAE, 0x39}).op == ce::Op::none, "66 0F AE /7 is clflushopt"); - check(dec({0x66, 0x0F, 0xAE, 0x74, 0x01}).op == ce::Op::none, "a cut-off clwb is not decoded"); - check(dec({0x0F, 0x0B}).op == ce::Op::none, "ud2 is not handled"); -} - -void test_bits() { - check(ce::insert_bits(0xFFFFFFFFFFFFFFFFull, 0, 8, 4) == 0xFFFFFFFFFFFFF00Full, "insert 8 at 4"); - check(ce::insert_bits(0, 0xABCD, 16, 48) == 0xABCD000000000000ull, "insert 16 at 48"); - check(ce::insert_bits(0x1234, 0xFEDCBA9876543210ull, 0, 0) == 0xFEDCBA9876543210ull, "insert len 0 is 64"); - check(ce::insert_bits(0, 0xFF, 8, 60) == 0xF000000000000000ull, "a field past bit 63 keeps what fits"); - check(ce::extract_bits(0xFEDCBA9876543210ull, 8, 4) == 0x21, "extract 8 at 4"); - check(ce::extract_bits(0xFEDCBA9876543210ull, 0, 0) == 0xFEDCBA9876543210ull, "extract len 0 is 64"); - check(ce::extract_bits(0xFEDCBA9876543210ull, 16, 56) == 0xFE, "extract past bit 63 zero-fills"); -} - -void test_apply() { - CONTEXT c{}; - c.Rip = 0x1000; - c.FltSave.XmmRegisters[0].Low = 0x1111111111111111ull; - c.FltSave.XmmRegisters[0].High = 0x2222222222222222ll; - c.FltSave.XmmRegisters[1].Low = 0xAB; - check(ce::apply(dec({0xF2, 0x0F, 0x78, 0xC1, 0x08, 0x10}), &c), "apply insertq"); - check(c.FltSave.XmmRegisters[0].Low == 0x1111111111AB1111ull && c.Rip == 0x1006, "insertq result and rip"); - check(c.FltSave.XmmRegisters[0].High == 0, "insertq zeroes the upper quadword, as a Zen 3 does"); - - c.FltSave.XmmRegisters[2].Low = 0xFFFF; - c.FltSave.XmmRegisters[2].High = (20ll << 8) | 12; // len 12 at bits 69:64, idx 20 at bits 77:72 (APM vol. 4) - c.FltSave.XmmRegisters[3].Low = 0; - check(ce::apply(dec({0xF2, 0x0F, 0x79, 0xDA}), &c), "apply insertq reg"); // insertq xmm3, xmm2 - check(c.FltSave.XmmRegisters[3].Low == (0xFFFull << 20), "insertq reg takes len and idx from the upper half"); - - // Measured on a Zen 3 in #7111's review: control 0x0810 (len 16 in bits 5:0, idx 8 in bits 13:8 of the upper - // quadword) inserts 16 bits of 0xAB at bit 8 of 0x1234. - c.FltSave.XmmRegisters[6].Low = 0x1234; - c.FltSave.XmmRegisters[7].Low = 0xAB; - c.FltSave.XmmRegisters[7].High = 0x0810; - check(ce::apply(dec({0xF2, 0x0F, 0x79, 0xF7}), &c) && c.FltSave.XmmRegisters[6].Low == 0xAB34, - "insertq reg: the measured 0x0810 case"); // insertq xmm6, xmm7 - - c.FltSave.XmmRegisters[4].Low = 0xFEDCBA9876543210ull; - c.FltSave.XmmRegisters[5].Low = (4 << 8) | 8; // idx 4 at bits 13:8, len 8 at bits 5:0 - check(ce::apply(dec({0x66, 0x0F, 0x79, 0xE5}), &c), "apply extrq reg"); // extrq xmm4, xmm5 - check(c.FltSave.XmmRegisters[4].Low == 0x21, "extrq reg result"); - - alignas(64) static uint8_t line[128]; - std::memset(line, 0xEE, sizeof line); - c.Rax = reinterpret_cast(line + 64 + 17); - const uint64_t rip = c.Rip; - check(ce::apply(dec({0x0F, 0x01, 0xFC}), &c) && c.Rip == rip + 3, "apply clzero"); - bool zeroed = true, kept = true; - for (int i = 64; i < 128; ++i) zeroed &= line[i] == 0; - for (int i = 0; i < 64; ++i) kept &= line[i] == 0xEE; - check(zeroed && kept, "clzero zeroes exactly the line rax points into"); - - c.Rax = 0x10; // the null page: not writable, so the write fault the CPU would raise is reported - EXCEPTION_RECORD fault{}; - check(!ce::apply(dec({0x0F, 0x01, 0xFC}), &c, &fault) && c.Rip == rip + 3, - "clzero on an unwritable line is refused and leaves rip"); - check(fault.ExceptionCode == STATUS_ACCESS_VIOLATION && fault.NumberParameters == 2 && - fault.ExceptionInformation[0] == 1 && fault.ExceptionInformation[1] == 0, - "clzero on an unwritable line reports a write access violation at the line"); -} - -// ---- Running the real encodings ---- - -using Fn = void (*)(const void* in, void* out); - -struct Code { - uint8_t* mem = nullptr; - explicit Code(std::initializer_list bytes) { - mem = static_cast(VirtualAlloc(nullptr, 4096, MEM_COMMIT | MEM_RESERVE, PAGE_EXECUTE_READWRITE)); - if (mem) std::memcpy(mem, bytes.begin(), bytes.size()); - FlushInstructionCache(GetCurrentProcess(), mem, 4096); - } - ~Code() { if (mem) VirtualFree(mem, 0, MEM_RELEASE); } - Fn fn() const { return reinterpret_cast(mem); } -}; - -bool run(const Code& code, const void* in, void* out, DWORD* exception) { - *exception = 0; - __try { - code.fn()(in, out); - return true; - } __except (*exception = GetExceptionCode(), EXCEPTION_EXECUTE_HANDLER) { - return false; - } -} - -const char* path(bool host_has) { return host_has ? "native" : "emulated"; } - -void test_live(const ce::Host& host) { - DWORD ex = 0; - alignas(32) uint64_t in[8] = {}, out[8] = {}; - - // movdqu xmm0,[rcx]; movdqu xmm1,[rcx+16]; insertq xmm0,xmm1,12,20; movdqu [rdx],xmm0; ret - Code insq({0xF3, 0x0F, 0x6F, 0x01, 0xF3, 0x0F, 0x6F, 0x49, 0x10, 0xF2, 0x0F, 0x78, 0xC1, 12, 20, - 0xF3, 0x0F, 0x7F, 0x02, 0xC3}); - in[0] = 0x0123456789ABCDEFull; - in[1] = 0x5555555555555555ull; - in[2] = 0xFFFFFFFFFFFFFABCull; - check(run(insq, in, out, &ex), "insertq imm ran"); - check(out[0] == ce::insert_bits(in[0], in[2], 12, 20), "insertq imm result"); - std::printf("insertq imm: %s\n", path(host.sse4a)); - - // same with the register form: insertq xmm0, xmm1 (len in xmm1[69:64], idx in xmm1[77:72]) - Code insr({0xF3, 0x0F, 0x6F, 0x01, 0xF3, 0x0F, 0x6F, 0x49, 0x10, 0xF2, 0x0F, 0x79, 0xC1, - 0xF3, 0x0F, 0x7F, 0x02, 0xC3}); - in[3] = (7ull << 8) | 33; // len 33, idx 7 - check(run(insr, in, out, &ex), "insertq reg ran"); - check(out[0] == ce::insert_bits(in[0], in[2], 33, 7), "insertq reg result"); - - // movdqu xmm0,[rcx]; extrq xmm0,9,13; movdqu [rdx],xmm0; ret - Code exti({0xF3, 0x0F, 0x6F, 0x01, 0x66, 0x0F, 0x78, 0xC0, 9, 13, 0xF3, 0x0F, 0x7F, 0x02, 0xC3}); - check(run(exti, in, out, &ex), "extrq imm ran"); - check(out[0] == ce::extract_bits(in[0], 9, 13), "extrq imm result"); - - // movdqu xmm0,[rcx]; movdqu xmm1,[rcx+16]; extrq xmm0,xmm1; movdqu [rdx],xmm0; ret - Code extr({0xF3, 0x0F, 0x6F, 0x01, 0xF3, 0x0F, 0x6F, 0x49, 0x10, 0x66, 0x0F, 0x79, 0xC1, - 0xF3, 0x0F, 0x7F, 0x02, 0xC3}); - in[2] = (40ull << 8) | 20; - check(run(extr, in, out, &ex), "extrq reg ran"); - check(out[0] == ce::extract_bits(in[0], 20, 40), "extrq reg result"); - std::printf("extrq: %s\n", path(host.sse4a)); - - // The upper half of ymm0 survives an emulated (legacy SSE) insertq: - // vmovdqu ymm0,[rcx]; vmovdqu ymm1,[rcx+32]; insertq xmm0,xmm1,8,8; vmovdqu [rdx],ymm0; vzeroupper; ret - Code ymm({0xC5, 0xFE, 0x6F, 0x01, 0xC5, 0xFE, 0x6F, 0x49, 0x20, 0xF2, 0x0F, 0x78, 0xC1, 8, 8, - 0xC5, 0xFE, 0x7F, 0x02, 0xC5, 0xF8, 0x77, 0xC3}); - for (int i = 0; i < 8; ++i) in[i] = 0x1010101010101010ull * (i + 1); - std::memset(out, 0, sizeof out); - check(run(ymm, in, out, &ex), "insertq between AVX code ran"); - check(out[0] == ce::insert_bits(in[0], in[4], 8, 8), "insertq between AVX code: low quadword"); - check(out[2] == in[2] && out[3] == in[3], "insertq keeps ymm0[255:128]"); - if (!host.sse4a) check(out[1] == 0, "emulated insertq zeroes xmm0[127:64], as a Zen 3 does"); - - // mov rax,rcx; clzero; ret - Code clz({0x48, 0x89, 0xC8, 0x0F, 0x01, 0xFC, 0xC3}); - alignas(64) static uint8_t lines[192]; - std::memset(lines, 0x5A, sizeof lines); - check(run(clz, lines + 64 + 40, nullptr, &ex), "clzero ran"); - bool ok = true; - for (int i = 0; i < 192; ++i) ok &= lines[i] == ((i >= 64 && i < 128) ? 0 : 0x5A); - check(ok, "clzero zeroed one line"); - std::printf("clzero: %s\n", path(host.clzero)); - - // A read-only line: the CPU and the handler both raise a write access violation, not #UD. - if (auto* ro = static_cast(VirtualAlloc(nullptr, 4096, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE))) { - DWORD old = 0; - VirtualProtect(ro, 4096, PAGE_READONLY, &old); - check(!run(clz, ro + 128, nullptr, &ex) && ex == STATUS_ACCESS_VIOLATION, - "clzero on a read-only line raises an access violation"); - VirtualFree(ro, 0, MEM_RELEASE); - } - if (!host.clzero) { // the emulated path accepts the 66 prefix: mov rax,rcx; 66 clzero; ret - Code clz66({0x48, 0x89, 0xC8, 0x66, 0x0F, 0x01, 0xFC, 0xC3}); - std::memset(lines, 0x5A, sizeof lines); - check(run(clz66, lines + 130, nullptr, &ex) && lines[128] == 0 && lines[191] == 0 && lines[127] == 0x5A, - "clzero with 66 emulated"); - } - - // mov rax,rcx; xor ecx,ecx; xor edx,edx; monitorx; xor eax,eax; xor ecx,ecx; mwaitx; ret - // (no timer: an interrupt or a store ends a native wait; the emulated one returns at once) - Code mon({0x48, 0x89, 0xC8, 0x31, 0xC9, 0x31, 0xD2, 0x0F, 0x01, 0xFA, 0x31, 0xC0, 0x31, 0xC9, 0x0F, 0x01, 0xFB, - 0xC3}); - check(run(mon, lines, nullptr, &ex), "monitorx/mwaitx ran"); - std::printf("monitorx/mwaitx: %s\n", path(host.monitorx)); - - // xor eax,eax; clwb [rcx]; clwb [rcx+rax+8]; mov dword [rdx],1; ret - Code wb({0x31, 0xC0, 0x66, 0x0F, 0xAE, 0x31, 0x66, 0x0F, 0xAE, 0x74, 0x01, 0x08, 0xC7, 0x02, 0x01, 0, 0, 0, - 0xC3}); - uint32_t marker = 0; - check(run(wb, lines, &marker, &ex) && marker == 1, "clwb ran and execution continued after it"); - std::printf("clwb: %s\n", path(host.clwb)); - - // A #UD the handler does not know stays an illegal-instruction exception: ud2; ret - Code ud({0x0F, 0x0B, 0xC3}); - check(!run(ud, nullptr, nullptr, &ex) && ex == STATUS_ILLEGAL_INSTRUCTION, "ud2 still faults"); -} -} // namespace - -int main() { - test_decode(); - test_bits(); - test_apply(); - const ce::Host host = ce::detect_host(); - std::printf("host: SSE4a %d, MONITORX %d, CLZERO %d, CLWB %d\n", host.sse4a, host.monitorx, host.clzero, - host.clwb); - check(ce::install(), "install the handler"); - test_live(host); - if (failures) { - std::fprintf(stderr, "%d failure(s)\n", failures); - return 1; - } - std::printf("cpu_emulation: all checks passed\n"); - return 0; -} diff --git a/runtime/test/crt_timed_wait_test.cpp b/runtime/test/crt_timed_wait_test.cpp deleted file mode 100644 index 339a8a215..000000000 --- a/runtime/test/crt_timed_wait_test.cpp +++ /dev/null @@ -1,121 +0,0 @@ -// condition_variable timed waits release their mutex (src/crt_timed_wait.cpp, #3796). On Wine 9.0 the STL's -// statically linked timed wait kept the mutex for the whole timeout, so a thread setting the predicate waited until -// the wait timed out. Also checks the other definitions that file takes over: std::shared_mutex and -// this_thread::sleep_for. No game files, no GPU. -#include -#include -#include -#include -#include -#include - -namespace { -int failures = 0; - -void check(bool ok, const char* what) { - std::printf("%s %s\n", ok ? "PASS" : "FAIL", what); - if (!ok) ++failures; -} - -using Clock = std::chrono::steady_clock; - -long long ms_since(Clock::time_point start) { - return std::chrono::duration_cast(Clock::now() - start).count(); -} -} // namespace - -int main() { - std::mutex mutex; - std::condition_variable cv; - - { - // The waiter holds the mutex only until it waits: a second thread takes it, sets the flag and notifies. - bool flag = false; - long long took_lock_ms = -1; - const auto start = Clock::now(); - std::thread setter([&] { - std::this_thread::sleep_for(std::chrono::milliseconds(50)); - const auto before = Clock::now(); - { - std::lock_guard lock(mutex); - took_lock_ms = ms_since(before); - flag = true; - } - cv.notify_all(); - }); - bool woke = false; - { - std::unique_lock lock(mutex); - woke = cv.wait_for(lock, std::chrono::seconds(5), [&] { return flag; }); - } - const long long waited = ms_since(start); - setter.join(); - std::printf(" wait_for(5 s) returned after %lld ms; the setter waited %lld ms for the mutex\n", waited, - took_lock_ms); - check(woke, "wait_for sees the predicate another thread set"); - check(took_lock_ms >= 0 && took_lock_ms < 1000, "the mutex is free while wait_for waits"); - check(waited < 2500, "wait_for is woken, not timed out"); - } - - { - // wait_until goes through the same timed wait. - bool flag = false; - std::thread setter([&] { - std::this_thread::sleep_for(std::chrono::milliseconds(50)); - { std::lock_guard lock(mutex); flag = true; } - cv.notify_one(); - }); - const auto start = Clock::now(); - bool woke = false; - { - std::unique_lock lock(mutex); - woke = cv.wait_until(lock, Clock::now() + std::chrono::seconds(5), [&] { return flag; }); - } - const long long waited = ms_since(start); - setter.join(); - check(woke && waited < 2500, "wait_until is woken, not timed out"); - } - - { - // Nobody notifies: the wait times out after about its timeout, with the mutex held again. - const auto start = Clock::now(); - std::unique_lock lock(mutex); - const std::cv_status status = cv.wait_for(lock, std::chrono::milliseconds(200)); - const long long waited = ms_since(start); - std::printf(" an unnotified wait_for(200 ms) returned after %lld ms\n", waited); - check(status == std::cv_status::timeout, "an unnotified wait_for times out"); - check(waited >= 150 && waited < 2000, "an unnotified wait_for lasts about its timeout"); - check(lock.owns_lock(), "the mutex is held again after the timeout"); - bool other_got_it = true; - std::thread probe([&] { other_got_it = mutex.try_lock(); if (other_got_it) mutex.unlock(); }); - probe.join(); - check(!other_got_it, "another thread cannot take it then"); - } - - { - std::shared_mutex shared; - shared.lock_shared(); - check(shared.try_lock_shared(), "shared_mutex: two shared owners"); - bool exclusive = true; - std::thread probe([&] { exclusive = shared.try_lock(); if (exclusive) shared.unlock(); }); - probe.join(); - check(!exclusive, "shared_mutex: no exclusive owner while shared"); - shared.unlock_shared(); - shared.unlock_shared(); - check(shared.try_lock(), "shared_mutex: exclusive once released"); - shared.unlock(); - } - - { - const auto start = Clock::now(); - std::this_thread::sleep_for(std::chrono::milliseconds(100)); - check(ms_since(start) >= 90, "this_thread::sleep_for sleeps"); - } - - if (failures) { - std::printf("RESULT: FAIL (%d failures)\n", failures); - return 1; - } - std::printf("RESULT: PASS\n"); - return 0; -} diff --git a/runtime/test/cs_wave_probe_spv.h b/runtime/test/cs_wave_probe_spv.h deleted file mode 100644 index 28745ac06..000000000 --- a/runtime/test/cs_wave_probe_spv.h +++ /dev/null @@ -1,63 +0,0 @@ -// runtime/test/glsl/cs_wave_probe.comp, generated with glslang 16.6.0 (tests/test_cs_wave_probe_spv.py checks it): -// glslangValidator -V --target-env vulkan1.2 -Os -o cs_wave_probe.spv runtime/test/glsl/cs_wave_probe.comp -// SPIR-V 1.5, as the translator emits, so varying subgroup sizes are not allowed in it either. -#pragma once -#include -namespace leonida::vk_test { -inline constexpr std::uint32_t cs_wave_probe_spirv[] = { - 0x07230203u, 0x00010500u, 0x0008000bu, 0x00000042u, 0x00000000u, 0x00020011u, 0x00000001u, 0x00020011u, - 0x0000003du, 0x00020011u, 0x00000040u, 0x00020011u, 0x000014e3u, 0x0006000bu, 0x00000001u, 0x4c534c47u, - 0x6474732eu, 0x3035342eu, 0x00000000u, 0x0003000eu, 0x000014e4u, 0x00000001u, 0x000a000fu, 0x00000005u, - 0x00000004u, 0x6e69616du, 0x00000000u, 0x0000000fu, 0x00000019u, 0x00000021u, 0x00000029u, 0x00000030u, - 0x00060010u, 0x00000004u, 0x00000011u, 0x00000001u, 0x00000001u, 0x00000001u, 0x00030003u, 0x00000002u, - 0x000001c2u, 0x00070004u, 0x455f4c47u, 0x625f5458u, 0x65666675u, 0x65725f72u, 0x65726566u, 0x0065636eu, - 0x00090004u, 0x455f4c47u, 0x625f5458u, 0x65666675u, 0x65725f72u, 0x65726566u, 0x5f65636eu, 0x63657675u, - 0x00000032u, 0x00090004u, 0x4b5f4c47u, 0x735f5248u, 0x65646168u, 0x75735f72u, 0x6f726762u, 0x625f7075u, - 0x6f6c6c61u, 0x00000074u, 0x00090004u, 0x4b5f4c47u, 0x735f5248u, 0x65646168u, 0x75735f72u, 0x6f726762u, - 0x625f7075u, 0x63697361u, 0x00000000u, 0x00040005u, 0x00000004u, 0x6e69616du, 0x00000000u, 0x00040005u, - 0x00000009u, 0x64726f57u, 0x00000073u, 0x00040006u, 0x00000009u, 0x00000000u, 0x00000077u, 0x00050005u, - 0x0000000du, 0x72657355u, 0x61746144u, 0x00000000u, 0x00050006u, 0x0000000du, 0x00000000u, 0x65736162u, - 0x00000000u, 0x00030005u, 0x0000000fu, 0x00006370u, 0x00080005u, 0x00000019u, 0x4c5f6c67u, 0x6c61636fu, - 0x6f766e49u, 0x69746163u, 0x6e496e6fu, 0x00786564u, 0x00060005u, 0x00000021u, 0x535f6c67u, 0x72676275u, - 0x5370756fu, 0x00657a69u, 0x00080005u, 0x00000029u, 0x535f6c67u, 0x72676275u, 0x4970756fu, 0x636f766eu, - 0x6f697461u, 0x0044496eu, 0x00060005u, 0x00000030u, 0x535f6c67u, 0x72676275u, 0x4970756fu, 0x00000044u, - 0x00040047u, 0x00000008u, 0x00000006u, 0x00000004u, 0x00030047u, 0x00000009u, 0x00000002u, 0x00050048u, - 0x00000009u, 0x00000000u, 0x00000023u, 0x00000000u, 0x00030047u, 0x0000000du, 0x00000002u, 0x00050048u, - 0x0000000du, 0x00000000u, 0x00000023u, 0x00000000u, 0x00040047u, 0x00000019u, 0x0000000bu, 0x0000001du, - 0x00030047u, 0x00000021u, 0x00000000u, 0x00040047u, 0x00000021u, 0x0000000bu, 0x00000024u, 0x00030047u, - 0x00000022u, 0x00000000u, 0x00030047u, 0x00000029u, 0x00000000u, 0x00040047u, 0x00000029u, 0x0000000bu, - 0x00000029u, 0x00030047u, 0x0000002au, 0x00000000u, 0x00040047u, 0x00000030u, 0x0000000bu, 0x00000028u, - 0x00040047u, 0x0000003du, 0x00000001u, 0x00000000u, 0x00040047u, 0x0000003eu, 0x00000001u, 0x00000001u, - 0x00040047u, 0x0000003fu, 0x00000001u, 0x00000002u, 0x00040047u, 0x00000041u, 0x0000000bu, 0x00000019u, - 0x00020013u, 0x00000002u, 0x00030021u, 0x00000003u, 0x00000002u, 0x00030027u, 0x00000006u, 0x000014e5u, - 0x00040015u, 0x00000007u, 0x00000020u, 0x00000000u, 0x0003001du, 0x00000008u, 0x00000007u, 0x0003001eu, - 0x00000009u, 0x00000008u, 0x00040020u, 0x00000006u, 0x000014e5u, 0x00000009u, 0x00040017u, 0x0000000cu, - 0x00000007u, 0x00000002u, 0x0003001eu, 0x0000000du, 0x0000000cu, 0x00040020u, 0x0000000eu, 0x00000009u, - 0x0000000du, 0x0004003bu, 0x0000000eu, 0x0000000fu, 0x00000009u, 0x00040015u, 0x00000010u, 0x00000020u, - 0x00000001u, 0x0004002bu, 0x00000010u, 0x00000011u, 0x00000000u, 0x00040020u, 0x00000012u, 0x00000009u, - 0x0000000cu, 0x00040020u, 0x00000018u, 0x00000001u, 0x00000007u, 0x0004003bu, 0x00000018u, 0x00000019u, - 0x00000001u, 0x0004002bu, 0x00000007u, 0x0000001bu, 0x00000004u, 0x0004003bu, 0x00000018u, 0x00000021u, - 0x00000001u, 0x00040020u, 0x00000023u, 0x000014e5u, 0x00000007u, 0x0004002bu, 0x00000007u, 0x00000027u, - 0x00000001u, 0x0004003bu, 0x00000018u, 0x00000029u, 0x00000001u, 0x0004002bu, 0x00000007u, 0x0000002eu, - 0x00000002u, 0x0004003bu, 0x00000018u, 0x00000030u, 0x00000001u, 0x0004002bu, 0x00000007u, 0x00000035u, - 0x00000003u, 0x00020014u, 0x00000037u, 0x00030029u, 0x00000037u, 0x00000038u, 0x00040017u, 0x00000039u, - 0x00000007u, 0x00000004u, 0x00040032u, 0x00000007u, 0x0000003du, 0x00000001u, 0x00040032u, 0x00000007u, - 0x0000003eu, 0x00000001u, 0x00040032u, 0x00000007u, 0x0000003fu, 0x00000001u, 0x00040017u, 0x00000040u, - 0x00000007u, 0x00000003u, 0x00060033u, 0x00000040u, 0x00000041u, 0x0000003du, 0x0000003eu, 0x0000003fu, - 0x00050036u, 0x00000002u, 0x00000004u, 0x00000000u, 0x00000003u, 0x000200f8u, 0x00000005u, 0x00050041u, - 0x00000012u, 0x00000013u, 0x0000000fu, 0x00000011u, 0x0004003du, 0x0000000cu, 0x00000014u, 0x00000013u, - 0x0004007cu, 0x00000006u, 0x00000015u, 0x00000014u, 0x0004003du, 0x00000007u, 0x0000001au, 0x00000019u, - 0x00050084u, 0x00000007u, 0x0000001cu, 0x0000001au, 0x0000001bu, 0x0004003du, 0x00000007u, 0x00000022u, - 0x00000021u, 0x00060041u, 0x00000023u, 0x00000024u, 0x00000015u, 0x00000011u, 0x0000001cu, 0x0005003eu, - 0x00000024u, 0x00000022u, 0x00000002u, 0x00000004u, 0x00050080u, 0x00000007u, 0x00000028u, 0x0000001cu, - 0x00000027u, 0x0004003du, 0x00000007u, 0x0000002au, 0x00000029u, 0x00060041u, 0x00000023u, 0x0000002bu, - 0x00000015u, 0x00000011u, 0x00000028u, 0x0005003eu, 0x0000002bu, 0x0000002au, 0x00000002u, 0x00000004u, - 0x00050080u, 0x00000007u, 0x0000002fu, 0x0000001cu, 0x0000002eu, 0x0004003du, 0x00000007u, 0x00000031u, - 0x00000030u, 0x00060041u, 0x00000023u, 0x00000032u, 0x00000015u, 0x00000011u, 0x0000002fu, 0x0005003eu, - 0x00000032u, 0x00000031u, 0x00000002u, 0x00000004u, 0x00050080u, 0x00000007u, 0x00000036u, 0x0000001cu, - 0x00000035u, 0x00050153u, 0x00000039u, 0x0000003au, 0x00000035u, 0x00000038u, 0x00060156u, 0x00000007u, - 0x0000003bu, 0x00000035u, 0x00000000u, 0x0000003au, 0x00060041u, 0x00000023u, 0x0000003cu, 0x00000015u, - 0x00000011u, 0x00000036u, 0x0005003eu, 0x0000003cu, 0x0000003bu, 0x00000002u, 0x00000004u, 0x000100fdu, - 0x00010038u, -}; -} diff --git a/runtime/test/d3d12_b5g5r5a1_uav_test.cpp b/runtime/test/d3d12_b5g5r5a1_uav_test.cpp deleted file mode 100644 index aea50acb5..000000000 --- a/runtime/test/d3d12_b5g5r5a1_uav_test.cpp +++ /dev/null @@ -1,237 +0,0 @@ -// DXGI_FORMAT_B5G5R5A1_UNORM textures with D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS on Vulkan GPUs whose -// VK_FORMAT_A1R5G5B5_UNORM_PACK16 has no STORAGE_IMAGE support: the texture is a mutable R16_UINT image whose render -// target and shader resource views are A1R5G5B5 (Format::uint_backed, as R9G9B9E5 UAVs are R32_UINT images). -// -// Exercises: -// 1. GetResourceAllocationInfo and CreateCommittedResource for a 2560x1440 render-target + UAV texture (the shape a -// title's boot asks for; it was UINT64_MAX before) and a small one -// 2. ClearRenderTargetView through the A1R5G5B5 view, whole view and a rectangle, read back as packed 16-bit texels -// (B in bits 0-4, G 5-9, R 10-14, A 15) -// 3. The UAV and SRV T#s name GFX10's 1_5_5_5_UNORM format, not 16_UINT, so shaders see the texture's own format -// 4. A multisampled B5G5R5A1 UAV texture is still refused -// On a GPU with native A1R5G5B5 storage nothing is emulated and the test exits 77. -// -// Synthetic data only; no game files. Set LEONIDA_VK_VALIDATION=1 to run under VK_LAYER_KHRONOS_validation. -#include "vk_test_device.h" -#include "../shims/d3d12_com.h" -#include "../src/gfx10_descriptors.h" - -#include -#include -#include -#include - -#define EXPECT(condition) do { \ - if (!(condition)) { std::fprintf(stderr, "line %d: %s\n", __LINE__, #condition); return 1; } \ -} while (0) - -namespace { - -namespace g = leonida::gfx10; - -template -struct Ref { - T* p = nullptr; - ~Ref() { reset(); } - void reset() { - if (p) p->Release(); - p = nullptr; - } - T* operator->() const { return p; } -}; - -D3D12_RESOURCE_DESC tex_desc(UINT64 width, UINT height, D3D12_RESOURCE_FLAGS flags, UINT samples = 1) { - D3D12_RESOURCE_DESC d{}; - d.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D; - d.Width = width; - d.Height = height; - d.DepthOrArraySize = 1; - d.MipLevels = 1; - d.Format = DXGI_FORMAT_B5G5R5A1_UNORM; - d.SampleDesc = {samples, 0}; - d.Flags = flags; - return d; -} - -D3D12_RESOURCE_DESC buf_desc(UINT64 bytes) { - D3D12_RESOURCE_DESC d{}; - d.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER; - d.Width = bytes; - d.Height = 1; - d.DepthOrArraySize = 1; - d.MipLevels = 1; - d.SampleDesc.Count = 1; - d.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; - return d; -} - -D3D12_RESOURCE_BARRIER transition(ID3D12Resource* resource, D3D12_RESOURCE_STATES before, D3D12_RESOURCE_STATES after) { - D3D12_RESOURCE_BARRIER b{}; - b.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION; - b.Transition = {resource, D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES, before, after}; - return b; -} - -// GFX10 T# word 1 bits 20..28: the FORMAT field. -std::uint32_t tsharp_format(const void* descriptor) { - std::uint32_t words[8] = {}; - std::memcpy(words, descriptor, sizeof(words)); - return (words[1] >> 20) & 0x1ff; -} - -} // namespace - -int main() { - vktest::Device d; - const auto status = d.initialize(); - if (status == vktest::DeviceStatus::unavailable) return 77; - if (status != vktest::DeviceStatus::ready) return 1; - - VkFormatProperties props{}; - d.instance_fn("vkGetPhysicalDeviceFormatProperties")( - d.physical, VK_FORMAT_A1R5G5B5_UNORM_PACK16, &props); - if (props.optimalTilingFeatures & VK_FORMAT_FEATURE_STORAGE_IMAGE_BIT) { - std::printf("A1R5G5B5 has native storage on this GPU: nothing is emulated, skipping\n"); - return 77; - } - - rt::d3d12::VulkanDeviceInfo info{}; - info.get_instance_proc = d.instance_proc; - info.instance = d.instance; - info.physical = d.physical; - info.device = d.device; - info.queue = d.queue; - info.queue_family = d.family; - info.bindless = d.bindless; - info.bindless_partially_bound = d.partially_bound; - info.image_view_min_lod = d.image_view_min_lod; - info.host_image_copy = d.host_image_copy; - Ref device; - EXPECT(SUCCEEDED(rt::d3d12::create_vulkan_device(info, IID_PPV_ARGS(&device.p)))); - - constexpr auto kTargetUav = static_cast(D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET | - D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS); - const D3D12_HEAP_PROPERTIES def_heap{D3D12_HEAP_TYPE_DEFAULT}; - - // 1. The boot's shape: a size, and a resource. - const auto big = tex_desc(2560, 1440, kTargetUav); - VkFormatProperties r16{}; - d.instance_fn("vkGetPhysicalDeviceFormatProperties")( - d.physical, VK_FORMAT_R16_UINT, &r16); - constexpr VkFormatFeatureFlags kViewFeatures = - VK_FORMAT_FEATURE_SAMPLED_IMAGE_BIT | VK_FORMAT_FEATURE_COLOR_ATTACHMENT_BIT; - if (!(r16.optimalTilingFeatures & VK_FORMAT_FEATURE_STORAGE_IMAGE_BIT) || - (props.optimalTilingFeatures & kViewFeatures) != kViewFeatures) { - std::printf("R16_UINT storage or A1R5G5B5 sampling/attachment missing on this GPU, skipping\n"); - return 77; - } - const auto big_info = device->GetResourceAllocationInfo(0, 1, &big); - EXPECT(big_info.SizeInBytes != UINT64_MAX && big_info.SizeInBytes >= 2560ull * 1440 * 2); - Ref big_tex; - EXPECT(SUCCEEDED(device->CreateCommittedResource(&def_heap, D3D12_HEAP_FLAG_NONE, &big, D3D12_RESOURCE_STATE_COMMON, - nullptr, IID_PPV_ARGS(&big_tex.p)))); - EXPECT(big_tex->GetDesc().Format == DXGI_FORMAT_B5G5R5A1_UNORM && big_tex->GetDesc().Flags == kTargetUav); - - // 4. A multisampled UAV texture is refused (no Vulkan storage for multisampled images here either). - const auto msaa = tex_desc(64, 32, D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS, 4); - EXPECT(device->GetResourceAllocationInfo(0, 1, &msaa).SizeInBytes == UINT64_MAX); - - // 2. Clears through the render-target view, read back as packed texels. - constexpr UINT kW = 64, kH = 32, kPitch = 256; - const auto target_desc = tex_desc(kW, kH, kTargetUav); - Ref tex, readback; - EXPECT(SUCCEEDED(device->CreateCommittedResource(&def_heap, D3D12_HEAP_FLAG_NONE, &target_desc, - D3D12_RESOURCE_STATE_RENDER_TARGET, nullptr, - IID_PPV_ARGS(&tex.p)))); - const D3D12_HEAP_PROPERTIES rb_heap{D3D12_HEAP_TYPE_READBACK}; - const auto rb_desc = buf_desc(UINT64(kPitch) * kH); - EXPECT(SUCCEEDED(device->CreateCommittedResource(&rb_heap, D3D12_HEAP_FLAG_NONE, &rb_desc, - D3D12_RESOURCE_STATE_COPY_DEST, nullptr, - IID_PPV_ARGS(&readback.p)))); - - Ref rtv_heap, cpu_heap; - const D3D12_DESCRIPTOR_HEAP_DESC rtv_desc{D3D12_DESCRIPTOR_HEAP_TYPE_RTV, 1, D3D12_DESCRIPTOR_HEAP_FLAG_NONE}; - const D3D12_DESCRIPTOR_HEAP_DESC cpu_desc{D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, 2, D3D12_DESCRIPTOR_HEAP_FLAG_NONE}; - EXPECT(SUCCEEDED(device->CreateDescriptorHeap(&rtv_desc, IID_PPV_ARGS(&rtv_heap.p)))); - EXPECT(SUCCEEDED(device->CreateDescriptorHeap(&cpu_desc, IID_PPV_ARGS(&cpu_heap.p)))); - const auto rtv = rtv_heap->GetCPUDescriptorHandleForHeapStart(); - device->CreateRenderTargetView(tex.p, nullptr, rtv); - - // 3. The UAV and SRV T#s name the texture's own GFX10 format. - const auto uav_handle = cpu_heap->GetCPUDescriptorHandleForHeapStart(); - D3D12_CPU_DESCRIPTOR_HANDLE srv_handle = uav_handle; - srv_handle.ptr += device->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV); - D3D12_UNORDERED_ACCESS_VIEW_DESC uav{}; - uav.Format = DXGI_FORMAT_B5G5R5A1_UNORM; - uav.ViewDimension = D3D12_UAV_DIMENSION_TEXTURE2D; - device->CreateUnorderedAccessView(tex.p, nullptr, &uav, uav_handle); - device->CreateShaderResourceView(tex.p, nullptr, srv_handle); - const std::uint32_t expected_code = g::format_from_vulkan(VK_FORMAT_A1R5G5B5_UNORM_PACK16); - EXPECT(expected_code != 0 && expected_code != g::format_from_vulkan(VK_FORMAT_R16_UINT)); - EXPECT(tsharp_format(reinterpret_cast(uav_handle.ptr)) == expected_code); - EXPECT(tsharp_format(reinterpret_cast(srv_handle.ptr)) == expected_code); - - Ref queue; - const D3D12_COMMAND_QUEUE_DESC qd{D3D12_COMMAND_LIST_TYPE_DIRECT}; - EXPECT(SUCCEEDED(device->CreateCommandQueue(&qd, IID_PPV_ARGS(&queue.p)))); - Ref alloc; - EXPECT(SUCCEEDED(device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&alloc.p)))); - Ref list; - EXPECT(SUCCEEDED(device->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, alloc.p, nullptr, - IID_PPV_ARGS(&list.p)))); - Ref fence; - EXPECT(SUCCEEDED(device->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&fence.p)))); - - const FLOAT red[4] = {1, 0, 0, 1}; // R = 31, A = 1 -> 0xFC00 - const FLOAT green[4] = {0, 1, 0, 0}; // G = 31, A = 0 -> 0x03E0 - const D3D12_RECT rect{8, 4, 24, 12}; - list->ClearRenderTargetView(rtv, red, 0, nullptr); - list->ClearRenderTargetView(rtv, green, 1, &rect); - const auto to_src = transition(tex.p, D3D12_RESOURCE_STATE_RENDER_TARGET, D3D12_RESOURCE_STATE_COPY_SOURCE); - list->ResourceBarrier(1, &to_src); - D3D12_TEXTURE_COPY_LOCATION dst{readback.p, D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT}; - dst.PlacedFootprint = {0, {DXGI_FORMAT_B5G5R5A1_UNORM, kW, kH, 1, kPitch}}; - D3D12_TEXTURE_COPY_LOCATION src{tex.p, D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX}; - src.SubresourceIndex = 0; - list->CopyTextureRegion(&dst, 0, 0, 0, &src, nullptr); - EXPECT(SUCCEEDED(list->Close())); - ID3D12CommandList* lists[] = {list.p}; - queue->ExecuteCommandLists(1, lists); - EXPECT(rt::d3d12::last_execute_result(queue.p) == leonida::ReplayResult::success); - EXPECT(SUCCEEDED(queue->Signal(fence.p, 1)) && SUCCEEDED(fence->SetEventOnCompletion(1, nullptr))); - - void* mapped = nullptr; - EXPECT(SUCCEEDED(readback->Map(0, nullptr, &mapped))); - unsigned wrong = 0; - for (UINT y = 0; y < kH; ++y) { - for (UINT x = 0; x < kW; ++x) { - std::uint16_t texel = 0; - std::memcpy(&texel, static_cast(mapped) + y * kPitch + x * 2, sizeof(texel)); - const bool inside = x >= UINT(rect.left) && x < UINT(rect.right) && y >= UINT(rect.top) && - y < UINT(rect.bottom); - const std::uint16_t want = inside ? 0x03E0 : 0xFC00; - if (texel != want && wrong++ < 4) - std::fprintf(stderr, "texel (%u, %u) = 0x%04x, want 0x%04x\n", x, y, texel, want); - } - } - readback->Unmap(0, nullptr); - EXPECT(wrong == 0); - - readback.reset(); - tex.reset(); - big_tex.reset(); - list.reset(); - alloc.reset(); - queue.reset(); - fence.reset(); - rtv_heap.reset(); - cpu_heap.reset(); - device.reset(); - if (d.validation_errors()) { - std::fprintf(stderr, "%u Vulkan validation errors\n", d.validation_errors()); - return 1; - } - std::printf("d3d12_b5g5r5a1_uav_test: OK (R16_UINT image, A1R5G5B5 render-target clears %ux%u matched, " - "UAV/SRV T# format %u, 0 validation errors)\n", kW, kH, static_cast(expected_code)); - return 0; -} diff --git a/runtime/test/d3d12_bindless_churn_test.cpp b/runtime/test/d3d12_bindless_churn_test.cpp deleted file mode 100644 index 7209e58ab..000000000 --- a/runtime/test/d3d12_bindless_churn_test.cpp +++ /dev/null @@ -1,458 +0,0 @@ -// Bindless table churn without a device-idle wait (D3D-314). A game that makes and releases textures every frame -// changes the descriptor hash table of set 0 at every ExecuteCommandLists: the table grows, and keys that are still -// live move or change their index. Before D3D-314 each such flush waited for the whole device (vkDeviceWaitIdle) so -// the old table could be freed; now the flush makes a new generation (table buffers and descriptor set) and the old -// one is freed once every queue's submissions up to then are done. -// -// This test runs the churn through D3D12 alone, on the Xbox-ABI proxy over the Vulkan device: -// - a direct queue and a compute queue, three frames in flight, each frame on both queues; -// - every frame creates 24 new 8x8 textures with their SRVs (a ring of descriptor slots in a shader-visible heap) -// and releases the textures of seven frames ago, so keys are erased and the live set grows to about 190 keys; -// - the direct queue uploads the textures; the compute queue waits for that on the GPU (ID3D12CommandQueue::Wait); -// - each queue dispatches the sampling shader of d3d12_set0_compute_test (test/glsl/cs_set0_sample.comp, written -// to the translator's runtime contract) eight times, on SRVs of the current frame and of the three before it; -// - every result is compared byte for byte with the texels the CPU wrote. -// It runs twice on a fresh device each: as the layer is now (the number of vkDeviceWaitIdle calls for the bindless -// set must be 0, and generations must have been made), and with LEONIDA_BINDLESS_IDLE_WAIT=1, which restores the -// wait of before D3D-314 so the frame times can be compared (the results must be exact there too; its wait count -// must be above 0). The times are printed, not asserted. -// Set LEONIDA_VK_VALIDATION=1 to run under VK_LAYER_KHRONOS_validation with synchronization validation (0 errors -// required). -#include "vk_test_device.h" -#include "d3d12_test_shaders.h" -#include "test_temp_dir.h" -#include "../shims/d3d12_com.h" -#include "../shims/d3d12_xs_device.h" -#include "../src/shader_library.h" - -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#ifndef LEONIDA_TEST_CS_SET0_SAMPLE_SPV -#error "LEONIDA_TEST_CS_SET0_SAMPLE_SPV must name the compiled test shader" -#endif - -#define EXPECT(condition) do { \ - if (!(condition)) { std::fprintf(stderr, "line %d: %s\n", __LINE__, #condition); return false; } \ -} while (0) - -#define MAIN_EXPECT(condition) do { \ - if (!(condition)) { std::fprintf(stderr, "line %d: %s\n", __LINE__, #condition); return 1; } \ -} while (0) - -using namespace d3d12test; -using XboxHeapHandleFn = std::uint64_t(WINAPI*)(void* heap); // heap slots 9/10: handle in RAX - -namespace { - -using Texel = std::array; -constexpr UINT texture_size = 8, texels = texture_size * texture_size, run_bytes = texels * 4; -constexpr UINT frames = 96, in_flight = 3, per_frame = 24, use_span = 3; -constexpr UINT life = use_span + in_flight + 1; // frames a texture is kept: no list that samples it still runs -constexpr UINT ring = life + in_flight + 1; // frames of descriptor slots before one is written again -constexpr UINT probes = 8; -constexpr UINT queues = 2; // 0 direct, 1 compute - -// What frame `g` wrote into its texture `i`. -Texel texel(UINT g, UINT i, UINT x, UINT y) { - return {std::uint8_t(x * 29 + g * 7 + i), std::uint8_t(y * 31 + g * 3 + i * 5), - std::uint8_t(g * 13 + i * 17 + x * y), 255}; -} - -struct Probe { - UINT frame, index; -}; -// The SRVs a frame's dispatches sample: four of its own and four from up to three frames before. -// With `async`, the compute queue (q 1) samples only textures of `use_span` frames ago, which the CPU has seen -// finished: it has no D3D12 fence on the direct queue, so what it must wait for is the table the direct queue's -// flush just grew, nothing else. -bool async_compute(bool async, UINT q, UINT f) { return async && q == 1 && f >= use_span; } -Probe probe_of(UINT f, UINT p, bool async = false, UINT q = 0) { - static constexpr UINT ages[probes] = {0, 0, 0, 0, 1, 2, 3, 1}; - const UINT wanted = async_compute(async, q, f) ? use_span : ages[p]; - const UINT age = wanted <= f ? wanted : 0; - return {f - age, (p * 5 + f * 3) % per_frame}; -} - -struct Result { - double total_ms = 0, worst_frame_ms = 0; - rt::d3d12::BindlessStats stats{}; - unsigned mismatches = 0, compared = 0; - std::uint64_t max_retired_pending = 0; // seen right after an ExecuteCommandLists, with work in flight -}; - -bool run(vktest::Device& d, const std::filesystem::path& library, bool legacy_idle, bool async, Result& result) { - _putenv_s("LEONIDA_BINDLESS_IDLE_WAIT", legacy_idle ? "1" : "0"); - rt::d3d12::VulkanDeviceInfo info{}; - info.get_instance_proc = d.instance_proc; - info.instance = d.instance; - info.physical = d.physical; - info.device = d.device; - info.queue = d.queue; - info.queue_family = d.family; - // Distinct VkQueues for the D3D12 queues where the family has them: two queues on one VkQueue are ordered by - // submission, which hides a missing wait between them. - if (d.queues.size() >= 2) info.command_queues = d.queues; - info.buffer_device_address = true; - info.bindless = d.bindless; - info.bindless_partially_bound = d.partially_bound; - info.image_view_min_lod = d.image_view_min_lod; - info.shader_dir = library.string(); - ID3D12Device* inner = nullptr; - EXPECT(SUCCEEDED(rt::d3d12::create_vulkan_device(info, IID_PPV_ARGS(&inner)))); - Ref device; - EXPECT(SUCCEEDED(rt::d3d12_xs::create_device_proxy(inner, __uuidof(ID3D12Device), - reinterpret_cast(&device.p)))); - rt::d3d12::set_device_outer(inner, device.p); - EXPECT(rt::d3d12::bindless_set(device.p) != VK_NULL_HANDLE); - - // Root signature as in d3d12_set0_compute_test: [0] two constants, [1] a root UAV (the output), [2] the table of - // views (here: pointed at the SRV's own slot, so s0 is 0), [3] the table of samplers. - D3D12_DESCRIPTOR_RANGE view_range{D3D12_DESCRIPTOR_RANGE_TYPE_SRV, 1, 0, 0, 0}; - D3D12_DESCRIPTOR_RANGE sampler_range{D3D12_DESCRIPTOR_RANGE_TYPE_SAMPLER, 1, 0, 0, 0}; - D3D12_ROOT_PARAMETER params[4] = {}; - params[0].ParameterType = D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS; - params[0].Constants = {0, 0, 2}; - params[1].ParameterType = D3D12_ROOT_PARAMETER_TYPE_UAV; - params[1].Descriptor = {0, 0}; - params[2].ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE; - params[2].DescriptorTable = {1, &view_range}; - params[3].ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE; - params[3].DescriptorTable = {1, &sampler_range}; - D3D12_VERSIONED_ROOT_SIGNATURE_DESC root_desc{}; - root_desc.Version = D3D_ROOT_SIGNATURE_VERSION_1_0; - root_desc.Desc_1_0 = {4, params, 0, nullptr, D3D12_ROOT_SIGNATURE_FLAG_NONE}; - const auto root_blob = serialize_root_signature(root_desc); - EXPECT(!root_blob.empty()); - Ref root; - EXPECT(SUCCEEDED(device->CreateRootSignature(0, root_blob.data(), root_blob.size(), IID_PPV_ARGS(&root.p)))); - - const auto program = fssm_program({0x43530003, 0xbf810000}); - const auto container = shader_container(program); - D3D12_COMPUTE_PIPELINE_STATE_DESC pso_desc{}; - pso_desc.pRootSignature = root.p; - pso_desc.CS = {container.data(), container.size()}; - Ref pso; - EXPECT(SUCCEEDED(device->CreateComputePipelineState(&pso_desc, IID_PPV_ARGS(&pso.p)))); - - const D3D12_HEAP_PROPERTIES default_heap{D3D12_HEAP_TYPE_DEFAULT}; - const D3D12_HEAP_PROPERTIES upload_heap{D3D12_HEAP_TYPE_UPLOAD}; - const D3D12_HEAP_PROPERTIES readback_heap{D3D12_HEAP_TYPE_READBACK}; - D3D12_RESOURCE_DESC texture_desc{}; - texture_desc.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D; - texture_desc.Width = texture_desc.Height = texture_size; - texture_desc.DepthOrArraySize = 1; - texture_desc.MipLevels = 1; - texture_desc.Format = DXGI_FORMAT_R8G8B8A8_UNORM; - texture_desc.SampleDesc.Count = 1; - D3D12_PLACED_SUBRESOURCE_FOOTPRINT footprint{}; - device->GetCopyableFootprints(&texture_desc, 0, 1, 0, &footprint, nullptr, nullptr, nullptr); - const UINT pitch = footprint.Footprint.RowPitch; - EXPECT(pitch == 256); - constexpr UINT64 slice_bytes = UINT64(256) * texture_size; // one texture in the upload buffer - - // Per frame-in-flight: an upload buffer (direct queue only), and per queue an output buffer and its readback. - Ref upload[in_flight], output[queues][in_flight], readback[queues][in_flight]; - std::uint8_t* upload_ptr[in_flight] = {}; - bool output_in_uav[queues][in_flight] = {}; - for (UINT k = 0; k < in_flight; ++k) { - const auto upload_desc = buffer_desc(slice_bytes * per_frame); - EXPECT(SUCCEEDED(device->CreateCommittedResource(&upload_heap, D3D12_HEAP_FLAG_NONE, &upload_desc, - D3D12_RESOURCE_STATE_GENERIC_READ, nullptr, - IID_PPV_ARGS(&upload[k].p)))); - EXPECT(SUCCEEDED(upload[k]->Map(0, nullptr, reinterpret_cast(&upload_ptr[k])))); - for (UINT q = 0; q < queues; ++q) { - const auto output_desc = buffer_desc(probes * run_bytes, D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS); - EXPECT(SUCCEEDED(device->CreateCommittedResource(&default_heap, D3D12_HEAP_FLAG_NONE, &output_desc, - D3D12_RESOURCE_STATE_UNORDERED_ACCESS, nullptr, - IID_PPV_ARGS(&output[q][k].p)))); - output_in_uav[q][k] = true; - const auto readback_desc = buffer_desc(probes * run_bytes); - EXPECT(SUCCEEDED(device->CreateCommittedResource(&readback_heap, D3D12_HEAP_FLAG_NONE, &readback_desc, - D3D12_RESOURCE_STATE_COPY_DEST, nullptr, - IID_PPV_ARGS(&readback[q][k].p)))); - } - } - - // The view heap holds `ring` frames of `per_frame` SRVs; the sampler heap one wrapping POINT sampler. - const D3D12_DESCRIPTOR_HEAP_DESC view_heap_desc{D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, ring * per_frame, - D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE, 0}; - const D3D12_DESCRIPTOR_HEAP_DESC sampler_heap_desc{D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER, 1, - D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE, 0}; - Ref view_heap, sampler_heap; - EXPECT(SUCCEEDED(device->CreateDescriptorHeap(&view_heap_desc, IID_PPV_ARGS(&view_heap.p)))); - EXPECT(SUCCEEDED(device->CreateDescriptorHeap(&sampler_heap_desc, IID_PPV_ARGS(&sampler_heap.p)))); - const std::uint64_t view_cpu = reinterpret_cast(slot(view_heap.p, 9))(view_heap.p); - const std::uint64_t view_gpu = reinterpret_cast(slot(view_heap.p, 10))(view_heap.p); - const std::uint64_t sampler_cpu = reinterpret_cast(slot(sampler_heap.p, 9))(sampler_heap.p); - const std::uint64_t sampler_gpu = reinterpret_cast(slot(sampler_heap.p, 10))(sampler_heap.p); - const UINT view_step = device->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV); - EXPECT(view_cpu && sampler_cpu && view_gpu >= 0x10000 && sampler_gpu >= 0x10000); - EXPECT(view_gpu < (1ull << 32) && sampler_gpu < (1ull << 32)); - { - D3D12_SAMPLER_DESC sampler_desc{}; - sampler_desc.Filter = D3D12_FILTER_MIN_MAG_MIP_POINT; - sampler_desc.AddressU = sampler_desc.AddressV = sampler_desc.AddressW = D3D12_TEXTURE_ADDRESS_MODE_WRAP; - sampler_desc.MaxAnisotropy = 1; - sampler_desc.ComparisonFunc = D3D12_COMPARISON_FUNC_NEVER; - sampler_desc.MaxLOD = D3D12_FLOAT32_MAX; - device->CreateSampler(&sampler_desc, D3D12_CPU_DESCRIPTOR_HANDLE{SIZE_T(sampler_cpu)}); - } - - // The queues: each with its own fence, an allocator per frame in flight and one list. - const D3D12_COMMAND_LIST_TYPE types[queues] = {D3D12_COMMAND_LIST_TYPE_DIRECT, D3D12_COMMAND_LIST_TYPE_COMPUTE}; - Ref queue[queues]; - Ref allocator[queues][in_flight]; - Ref list[queues]; - Ref fence[queues]; - for (UINT q = 0; q < queues; ++q) { - D3D12_COMMAND_QUEUE_DESC queue_desc{}; - queue_desc.Type = types[q]; - EXPECT(SUCCEEDED(device->CreateCommandQueue(&queue_desc, IID_PPV_ARGS(&queue[q].p)))); - for (UINT k = 0; k < in_flight; ++k) - EXPECT(SUCCEEDED(device->CreateCommandAllocator(types[q], IID_PPV_ARGS(&allocator[q][k].p)))); - EXPECT(SUCCEEDED(device->CreateCommandList(0, types[q], allocator[q][0].p, nullptr, IID_PPV_ARGS(&list[q].p)))); - EXPECT(list[q]->Close() == S_OK); - EXPECT(SUCCEEDED(device->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&fence[q].p)))); - } - - std::array, per_frame>, life> textures; // frame g in [g % life] - - const auto check = [&](UINT g) { // results of frame g, once both queues finished it - const UINT k = g % in_flight; - for (UINT q = 0; q < queues; ++q) { - void* mapped = nullptr; - if (FAILED(readback[q][k]->Map(0, nullptr, &mapped))) { - ++result.mismatches; - continue; - } - const auto* bytes = static_cast(mapped); - for (UINT p = 0; p < probes; ++p) { - const Probe probe = probe_of(g, p, async, q); - for (UINT i = 0; i < texels; ++i) { - const Texel want = texel(probe.frame, probe.index, i % texture_size, i / texture_size); - const std::uint8_t* got = bytes + p * run_bytes + i * 4; - ++result.compared; - if (std::memcmp(got, want.data(), 4) == 0) continue; - if (result.mismatches++ < 8) - std::fprintf(stderr, "frame %u queue %u probe %u (frame %u texture %u) texel %u: got " - "%u,%u,%u,%u want %u,%u,%u,%u\n", - g, q, p, probe.frame, probe.index, i, got[0], got[1], got[2], got[3], want[0], - want[1], want[2], want[3]); - } - } - D3D12_RANGE none{0, 0}; - readback[q][k]->Unmap(0, &none); - } - return true; - }; - - using Clock = std::chrono::steady_clock; - const auto begin_all = Clock::now(); - UINT checked = 0; - for (UINT f = 0; f < frames; ++f) { - const auto frame_start = Clock::now(); - const UINT k = f % in_flight; - // Frame f - in_flight is done on both queues before its allocators, upload buffer and outputs are reused. - if (f >= in_flight) { - for (UINT q = 0; q < queues; ++q) EXPECT(SUCCEEDED(fence[q]->SetEventOnCompletion(f - in_flight + 1, nullptr))); - EXPECT(check(f - in_flight)); - ++checked; - } - // The textures of frame f - life are not sampled by any frame still in flight: release them (their keys go). - if (f >= life) - for (auto& texture : textures[f % life]) texture.reset(); - - // New textures and their SRVs, and their texels in the upload buffer. - for (UINT i = 0; i < per_frame; ++i) { - auto& texture = textures[f % life][i]; - EXPECT(SUCCEEDED(device->CreateCommittedResource(&default_heap, D3D12_HEAP_FLAG_NONE, &texture_desc, - D3D12_RESOURCE_STATE_COPY_DEST, nullptr, - IID_PPV_ARGS(&texture.p)))); - D3D12_SHADER_RESOURCE_VIEW_DESC srv{}; - srv.Format = DXGI_FORMAT_R8G8B8A8_UNORM; - srv.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2D; - srv.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; - srv.Texture2D = {0, 1, 0, 0.0f}; - const UINT heap_slot = (f % ring) * per_frame + i; - device->CreateShaderResourceView(texture.p, &srv, - D3D12_CPU_DESCRIPTOR_HANDLE{SIZE_T(view_cpu + UINT64(heap_slot) * view_step)}); - for (UINT y = 0; y < texture_size; ++y) - for (UINT x = 0; x < texture_size; ++x) { - const Texel t = texel(f, i, x, y); - std::memcpy(upload_ptr[k] + i * slice_bytes + y * pitch + x * 4, t.data(), 4); - } - } - - for (UINT q = 0; q < queues; ++q) { - EXPECT(SUCCEEDED(allocator[q][k]->Reset())); - EXPECT(SUCCEEDED(list[q]->Reset(allocator[q][k].p, nullptr))); - if (q == 0) { // upload, and make the textures shader resources for both queues - D3D12_RESOURCE_BARRIER sampled[per_frame]; - for (UINT i = 0; i < per_frame; ++i) { - D3D12_TEXTURE_COPY_LOCATION dst{}; - dst.pResource = textures[f % life][i].p; - dst.Type = D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX; - D3D12_TEXTURE_COPY_LOCATION src{}; - src.pResource = upload[k].p; - src.Type = D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT; - src.PlacedFootprint = footprint; - src.PlacedFootprint.Offset = i * slice_bytes; - list[q]->CopyTextureRegion(&dst, 0, 0, 0, &src, nullptr); - sampled[i] = transition(textures[f % life][i].p, D3D12_RESOURCE_STATE_COPY_DEST, - D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE); - } - list[q]->ResourceBarrier(per_frame, sampled); - } - if (!output_in_uav[q][k]) { - const auto back = transition(output[q][k].p, D3D12_RESOURCE_STATE_COPY_SOURCE, - D3D12_RESOURCE_STATE_UNORDERED_ACCESS); - list[q]->ResourceBarrier(1, &back); - } - ID3D12DescriptorHeap* heaps[] = {view_heap.p, sampler_heap.p}; - list[q]->SetDescriptorHeaps(2, heaps); - list[q]->SetComputeRootSignature(root.p); - list[q]->SetPipelineState(pso.p); - list[q]->SetComputeRootUnorderedAccessView(1, output[q][k]->GetGPUVirtualAddress()); - list[q]->SetComputeRootDescriptorTable(3, D3D12_GPU_DESCRIPTOR_HANDLE{sampler_gpu}); - for (UINT p = 0; p < probes; ++p) { - const Probe probe = probe_of(f, p, async, q); - const UINT heap_slot = (probe.frame % ring) * per_frame + probe.index; - list[q]->SetComputeRootDescriptorTable( - 2, D3D12_GPU_DESCRIPTOR_HANDLE{view_gpu + UINT64(heap_slot) * view_step}); - const std::uint32_t offset_and_first[2] = {0, p * texels}; - list[q]->SetComputeRoot32BitConstants(0, 2, offset_and_first, 0); - list[q]->Dispatch(1, 1, 1); - } - const auto to_copy = transition(output[q][k].p, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, - D3D12_RESOURCE_STATE_COPY_SOURCE); - list[q]->ResourceBarrier(1, &to_copy); - output_in_uav[q][k] = false; - list[q]->CopyBufferRegion(readback[q][k].p, 0, output[q][k].p, 0, probes * run_bytes); - EXPECT(list[q]->Close() == S_OK); - // The compute queue samples what the direct queue uploads: that is a wait on the GPU, not on the CPU. - if (q == 1 && !async_compute(async, q, f)) EXPECT(SUCCEEDED(queue[1]->Wait(fence[0].p, f + 1))); - ID3D12CommandList* lists[] = {list[q].p}; - queue[q]->ExecuteCommandLists(1, lists); - EXPECT(rt::d3d12::last_execute_result(queue[q].p) == leonida::ReplayResult::success); - EXPECT(SUCCEEDED(queue[q]->Signal(fence[q].p, f + 1))); - // A generation the flush retired stays until the submissions that may have used it are done. - result.max_retired_pending = std::max(result.max_retired_pending, - rt::d3d12::bindless_stats(device.p).retired_pending); - } - const double frame_ms = std::chrono::duration(Clock::now() - frame_start).count(); - result.worst_frame_ms = std::max(result.worst_frame_ms, frame_ms); - } - for (; checked < frames; ++checked) { - for (UINT q = 0; q < queues; ++q) EXPECT(SUCCEEDED(fence[q]->SetEventOnCompletion(checked + 1, nullptr))); - EXPECT(check(checked)); - } - result.total_ms = std::chrono::duration(Clock::now() - begin_all).count(); - result.stats = rt::d3d12::bindless_stats(device.p); - - for (auto& frame : textures) - for (auto& texture : frame) texture.reset(); - for (UINT k = 0; k < in_flight; ++k) { - upload[k].reset(); - for (UINT q = 0; q < queues; ++q) { - output[q][k].reset(); - readback[q][k].reset(); - allocator[q][k].reset(); - } - } - for (UINT q = 0; q < queues; ++q) { - list[q].reset(); - queue[q].reset(); - fence[q].reset(); - } - pso.reset(); - root.reset(); - view_heap.reset(); - sampler_heap.reset(); - EXPECT(rt::d3d12_xs::device_proxy_ref_count(device.p) == 1); - return true; -} - -} // namespace - -int main(int argc, char** argv) { - // `--validated` runs under the validation layer with synchronization validation, and skips when it is not there. - const bool validated = argc > 1 && std::strcmp(argv[1], "--validated") == 0; - if (validated) _putenv_s("LEONIDA_VK_VALIDATION", "1"); - vktest::Device d; - d.queue_count_wanted = 2; // a VkQueue for each of the two D3D12 queues, where the family has two - const auto device_status = d.initialize(); - if (device_status == vktest::DeviceStatus::unavailable) return 77; // no Vulkan GPU: ctest skips - if (validated && device_status != vktest::DeviceStatus::ready) { - std::printf("SKIP: the validation layer is not available\n"); - return 77; - } - if (device_status != vktest::DeviceStatus::ready) return 1; - if (!d.bindless) { - std::printf("SKIP: the device lacks the descriptor indexing features of the bindless set 0\n"); - return 77; - } - - // The shader's program and a translator index that maps its hash to the test module (as d3d12_set0_compute_test). - const auto program = fssm_program({0x43530003, 0xbf810000}); - const auto library = std::filesystem::temp_directory_path() / "leonida_bindless_churn_test"; - std::filesystem::create_directories(library); - if (!testfiles::copy_file(LEONIDA_TEST_CS_SET0_SAMPLE_SPV, library / "cs_set0_sample.spv")) return 1; - { - std::ofstream index(library / "index.json", std::ios::binary); - index << "{\"cs_set0_sample\": {\"stage\": \"cs\", \"fssm_sha256\": \"" << leonida::sha256_hex(program) - << "\", \"bindings\": [0, 1, 2], \"push_constant_bytes\": 144, \"local_size\": [64, 1, 1], " - "\"uses_code_base\": false, \"wave64\": false}}"; - } - - const bool distinct = d.queues.size() >= 2 && d.queues[0] != d.queues[1]; - std::printf("D3D12 queues on %s VkQueues (%zu created in family %u)\n", - distinct ? "distinct" : "ONE shared (the family has a single queue: the cross-queue wait is only " - "checked for validity)", d.queues.size(), d.family); - Result now, async, legacy, async_legacy; - bool ok = run(d, library, false, false, now); - if (ok) ok = run(d, library, false, true, async); - if (ok) ok = run(d, library, true, false, legacy); - if (ok) ok = run(d, library, true, true, async_legacy); // the old wait, and no wait between the queues - std::filesystem::remove_all(library); - if (!ok) return 1; - - const auto report = [](const char* name, const Result& r) { - std::printf("%-22s %u frames in %.1f ms (%.2f ms/frame, worst %.2f ms); %llu generations made, %llu " - "vkDeviceWaitIdle for the set, %llu retired not yet freed at the end; %u texels compared, " - "%u wrong\n", - name, frames, r.total_ms, r.total_ms / frames, r.worst_frame_ms, - static_cast(r.stats.generations_made), - static_cast(r.stats.device_idle_waits), - static_cast(r.stats.retired_pending), r.compared, r.mismatches); - }; - report("deferred retirement:", now); - report("async compute:", async); - report("old wait:", legacy); - report("old wait, async:", async_legacy); - MAIN_EXPECT(now.mismatches == 0 && async.mismatches == 0 && legacy.mismatches == 0 && - async_legacy.mismatches == 0); - MAIN_EXPECT(async.compared == now.compared && async.stats.device_idle_waits == 0 && async.stats.generations_made > 0); - MAIN_EXPECT(now.max_retired_pending > 0 && async.max_retired_pending > 0); - MAIN_EXPECT(now.compared == frames * queues * probes * texels); - MAIN_EXPECT(now.stats.device_idle_waits == 0); - MAIN_EXPECT(now.stats.generations_made > 0); - MAIN_EXPECT(legacy.stats.device_idle_waits > 0); - if (d.validation_errors()) { - std::fprintf(stderr, "%u validation errors\n", d.validation_errors()); - return 1; - } - std::printf("bindless churn: %u frames on a direct and a compute queue, 3 in flight, %u SRVs made and released " - "per frame; every sampled texel matched, the table moved to %llu new generations and no queue waited " - "for the device (the old path did %llu times)\n", - frames, per_frame, static_cast(now.stats.generations_made), - static_cast(legacy.stats.device_idle_waits)); - return 0; -} diff --git a/runtime/test/d3d12_boot_movie_test.cpp b/runtime/test/d3d12_boot_movie_test.cpp deleted file mode 100644 index 14506a232..000000000 --- a/runtime/test/d3d12_boot_movie_test.cpp +++ /dev/null @@ -1,691 +0,0 @@ -// TEST-528: a real boot-movie frame through the whole present path, on pixels. -// -// Decodes two frames of a real .bk2 through the package's own Bink2Scarlett.dll -// (rt::Loader, the bink_decode_test pattern), uploads each BGRA frame to a -// committed ALLOW_DISPLAY texture through the Xbox-ABI proxy (the -// d3d12_m2_textured_test CopyTextureRegion pattern), presents it with -// PresentX through the in-process XboxPresentation (the xbox_present_test -// pattern), and compares the presented pixels with the decoded frame. -// -// LEONIDA_GAME_DIR= (contains Bink2Scarlett.dll) -// LEONIDA_MOVIE= (a carved Bink 2 stream) -// LEONIDA_MOVIE_FRAME= (optional, default 0; a second frame, -// 200, is also tested when the movie has it) -// -// With LEONIDA_GAME_DIR or LEONIDA_MOVIE unset the test prints -// "SKIP (no package/movie)" and exits 77 (CTest skip), so CI passes without -// the package. Only movie properties (size, frame count, fps) are reported, -// never the file name. Nothing is written anywhere: every comparison is in -// memory, so no game data can end up in the repo or in %TEMP%. -#include "vk_test_device.h" -#include "../shims/d3d12_com.h" -#include "../shims/d3d12_xs_device.h" -#include "../shims/xbox_present.h" - -#include "../shims/shims.h" -#include "../src/pe_loader.h" - -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#define EXPECT(condition) do { \ - if (!(condition)) { std::fprintf(stderr, "line %d: %s\n", __LINE__, #condition); return 1; } \ -} while (0) - -namespace { - -int g_failures = 0; - -void check(bool condition, const std::string& what) { - std::printf("%s %s\n", condition ? "PASS" : "FAIL", what.c_str()); - if (!condition) ++g_failures; -} - -[[noreturn]] void fatal(const std::string& what) { - std::fprintf(stderr, "FAIL %s\n", what.c_str()); - std::exit(1); -} - -std::string env(const char* name) { - const char* v = std::getenv(name); - return v ? v : ""; -} - -uint32_t read_u32(const uint8_t* p) { - return (uint32_t)p[0] | ((uint32_t)p[1] << 8) | ((uint32_t)p[2] << 16) | ((uint32_t)p[3] << 24); -} - -struct MovieHeader { - uint32_t frames = 0; - uint32_t width = 0; - uint32_t height = 0; - uint32_t fps_num = 0; - uint32_t fps_den = 0; -}; - -MovieHeader read_movie_header(const std::filesystem::path& path) { - std::ifstream f(path, std::ios::binary); - if (!f) fatal("cannot open LEONIDA_MOVIE"); - uint8_t h[0x2C]{}; - f.read(reinterpret_cast(h), sizeof(h)); - if (f.gcount() != (std::streamsize)sizeof(h)) fatal("movie is shorter than the 44-byte Bink 2 header"); - if (h[0] != 'K' || h[1] != 'B' || h[2] != '2' || h[3] < 'a' || h[3] > 'z') - fatal("movie does not start with KB2[a-z]"); - MovieHeader out; - out.frames = read_u32(h + 0x08); - out.width = read_u32(h + 0x14); - out.height = read_u32(h + 0x18); - out.fps_num = read_u32(h + 0x1C); - out.fps_den = read_u32(h + 0x20); - if (!out.frames || !out.width || !out.height || !out.fps_num || !out.fps_den) - fatal("movie header has a zero frame count, size or fps"); - return out; -} - -uint64_t fnv1a(const std::vector& bytes) { - uint64_t h = 1469598103934665603ull; - for (uint8_t b : bytes) { - h ^= b; - h *= 1099511628211ull; - } - return h; -} - -size_t distinct_bytes(const std::vector& bytes) { - bool seen[256]{}; - size_t n = 0; - for (uint8_t b : bytes) - if (!seen[b]) { - seen[b] = true; - ++n; - } - return n; -} - -struct BinkApi { - using Open = void* (*)(const char*, uint32_t); - using Wait = uint32_t (*)(void*); - using DoFrame = uint32_t (*)(void*); - using CopyToBuffer = uint32_t (*)(void*, void*, uint32_t, uint32_t, uint32_t, uint32_t, uint32_t); - using NextFrame = void (*)(void*); - using Goto = void (*)(void*, uint32_t, uint32_t); - using Close = void (*)(void*); - using GetError = const char* (*)(); - - Open open = nullptr; - Wait wait = nullptr; - DoFrame do_frame = nullptr; - CopyToBuffer copy = nullptr; - NextFrame next = nullptr; - Goto go_to = nullptr; - Close close = nullptr; - GetError get_error = nullptr; -}; - -void* symbol(rt::Module& m, const char* name) { - auto it = m.exports.find(name); - if (it == m.exports.end()) fatal(std::string("Bink2Scarlett.dll does not export ") + name); - return it->second; -} - -template -struct Ref { - T* p = nullptr; - ~Ref() { reset(); } - void reset() { - if (p) p->Release(); - p = nullptr; - } - T* operator->() const { return p; } -}; - -LRESULT CALLBACK window_proc(HWND window, UINT message, WPARAM w, LPARAM l) { - return DefWindowProcW(window, message, w, l); -} - -void pump() { - MSG message; - while (PeekMessageW(&message, nullptr, 0, 0, PM_REMOVE)) { - TranslateMessage(&message); - DispatchMessage(&message); - } -} - -// The swapchain frame as RGB, whatever its channel order. -struct Frame { - std::vector bytes; - VkExtent2D extent{}; - VkFormat format = VK_FORMAT_UNDEFINED; - bool bgr() const { return format == VK_FORMAT_B8G8R8A8_UNORM || format == VK_FORMAT_B8G8R8A8_SRGB; } -}; - -struct RGB { - int r, g, b; -}; - -RGB presented_at(const Frame& f, UINT x, UINT y) { - const std::uint8_t* p = &f.bytes[(std::size_t(y) * f.extent.width + x) * 4]; - return f.bgr() ? RGB{p[2], p[1], p[0]} : RGB{p[0], p[1], p[2]}; -} - -RGB decoded_at(const std::vector& bgra, UINT w, UINT x, UINT y) { - const std::uint8_t* p = &bgra[(std::size_t(y) * w + x) * 4]; - return RGB{p[2], p[1], p[0]}; -} - -// The decoded frame as the presenter's scaling blit samples it at the centre of -// destination texel (x, y). vkCmdBlitImage maps the destination centre through -// normalized coordinates onto the source with CLAMP_TO_EDGE (so a sample outside -// the frame repeats the edge texel) and then filters: linearly when the source -// format reports VK_FORMAT_FEATURE_SAMPLED_IMAGE_FILTER_LINEAR_BIT, the nearest -// texel otherwise, which is the presenter's choice (runtime/src/vulkan_present.h, -// blit_filter). At 1:1 the centre lands on a texel centre and this reduces to -// decoded_at(x, y). -RGB sampled_at(const std::vector& bgra, UINT W, UINT H, UINT ew, UINT eh, UINT x, UINT y, bool linear) { - const double sx = ((double)x + 0.5) * double(W) / double(ew) - 0.5; - const double sy = ((double)y + 0.5) * double(H) / double(eh) - 0.5; - if (!linear) { - const int nx = std::clamp((int)std::floor(sx + 0.5), 0, (int)W - 1); - const int ny = std::clamp((int)std::floor(sy + 0.5), 0, (int)H - 1); - return decoded_at(bgra, W, (UINT)nx, (UINT)ny); - } - const int x0 = (int)std::floor(sx), y0 = (int)std::floor(sy); - const double fx = sx - x0, fy = sy - y0; - const auto texel = [&](int tx, int ty) { - return decoded_at(bgra, W, (UINT)std::clamp(tx, 0, (int)W - 1), (UINT)std::clamp(ty, 0, (int)H - 1)); - }; - const RGB t00 = texel(x0, y0), t10 = texel(x0 + 1, y0); - const RGB t01 = texel(x0, y0 + 1), t11 = texel(x0 + 1, y0 + 1); - const auto mix = [&](int a, int b, int c, int d) { - const double v = (1 - fx) * (1 - fy) * a + fx * (1 - fy) * b + (1 - fx) * fy * c + fx * fy * d; - return (int)std::lround(v); - }; - return RGB{mix(t00.r, t10.r, t01.r, t11.r), mix(t00.g, t10.g, t01.g, t11.g), - mix(t00.b, t10.b, t01.b, t11.b)}; -} - -D3D12_RESOURCE_DESC buffer_desc(UINT64 bytes) { - D3D12_RESOURCE_DESC d{}; - d.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER; - d.Width = bytes; - d.Height = 1; - d.DepthOrArraySize = 1; - d.MipLevels = 1; - d.Format = DXGI_FORMAT_UNKNOWN; - d.SampleDesc.Count = 1; - d.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; - return d; -} - -D3D12_RESOURCE_BARRIER transition(ID3D12Resource* resource, D3D12_RESOURCE_STATES before, - D3D12_RESOURCE_STATES after) { - D3D12_RESOURCE_BARRIER b{}; - b.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION; - b.Transition.pResource = resource; - b.Transition.Subresource = D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES; - b.Transition.StateBefore = before; - b.Transition.StateAfter = after; - return b; -} - -} // namespace - -int main() { - const std::string game_dir_arg = env("LEONIDA_GAME_DIR"); - const std::string movie_arg = env("LEONIDA_MOVIE"); - if (game_dir_arg.empty() || movie_arg.empty()) { - std::printf("SKIP (no package/movie)\n"); - return 77; - } - - const std::filesystem::path game_dir = game_dir_arg; - const std::filesystem::path movie = movie_arg; - std::error_code ec; - if (!std::filesystem::is_directory(game_dir, ec)) fatal("LEONIDA_GAME_DIR is not a directory"); - if (!std::filesystem::is_regular_file(game_dir / "Bink2Scarlett.dll", ec)) - fatal("LEONIDA_GAME_DIR does not contain Bink2Scarlett.dll"); - if (!std::filesystem::is_regular_file(movie, ec)) fatal("LEONIDA_MOVIE is not a file"); - - const MovieHeader header = read_movie_header(movie); - const UINT W = header.width, H = header.height; - // Properties only, never the file name. - std::printf("movie: %ux%u %u frames %u/%u fps\n", W, H, header.frames, header.fps_num, header.fps_den); - - uint32_t first = 0; - const std::string frame_arg = env("LEONIDA_MOVIE_FRAME"); - if (!frame_arg.empty()) { - char* end = nullptr; - const unsigned long v = std::strtoul(frame_arg.c_str(), &end, 10); - if (!end || *end || v >= header.frames) fatal("LEONIDA_MOVIE_FRAME is not a frame in this movie"); - first = (uint32_t)v; - } - // A second frame far from the first, when the movie has it. - uint32_t second = UINT32_MAX; - for (uint32_t candidate : {200u, header.frames - 1, 1u}) { - if (candidate < header.frames && candidate != first) { - second = candidate; - break; - } - } - const bool has_second = second != UINT32_MAX && second != first; - std::printf("frames under test: %u%s\n", first, has_second ? (" and " + std::to_string(second)).c_str() : " (only)"); - - std::vector decoded_first((size_t)W * H * 4), decoded_second; - if (has_second) decoded_second.resize((size_t)W * H * 4); - uint64_t hash_first = 0, hash_second = 0; - - try { - rt::Loader loader(game_dir); - rt::Module& bink = loader.load(game_dir / "Bink2Scarlett.dll"); - std::printf("mapped %s at %p, size %u%s\n", bink.name.c_str(), bink.base, bink.size, - bink.relocated ? " (relocated)" : ""); - - int shim = 0, host = 0, module = 0, unimplemented = 0; - for (auto& r : bink.imports) { - switch (r.binding) { - case rt::Binding::Shim: ++shim; break; - case rt::Binding::Host: ++host; break; - case rt::Binding::Module: ++module; break; - default: ++unimplemented; break; - } - if (rt::lower(r.dll) == "xmem.dll") { - check(r.binding == rt::Binding::Shim, "xmem.dll!" + r.name + " binds to the shim"); - void* expected = rt::shims::find("xmem.dll", r.name); - auto* dos = reinterpret_cast(bink.base); - auto* nt = reinterpret_cast(bink.base + dos->e_lfanew); - auto& dir = nt->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT]; - bool iat_ok = false; - if (dir.VirtualAddress) { - auto* desc = reinterpret_cast(bink.base + dir.VirtualAddress); - for (; desc->Name; ++desc) { - const char* dll = reinterpret_cast(bink.base + desc->Name); - if (rt::lower(dll) != "xmem.dll") continue; - auto* lookup = reinterpret_cast( - bink.base + (desc->OriginalFirstThunk ? desc->OriginalFirstThunk : desc->FirstThunk)); - auto* iat = reinterpret_cast(bink.base + desc->FirstThunk); - for (; lookup->u1.AddressOfData; ++lookup, ++iat) { - if (IMAGE_SNAP_BY_ORDINAL64(lookup->u1.Ordinal)) continue; - auto* name = reinterpret_cast( - bink.base + (uint32_t)lookup->u1.AddressOfData); - if (r.name == name->Name) - iat_ok = expected && *static_cast(reinterpret_cast(&iat->u1.Function)) == - expected; - } - } - } - check(iat_ok, "xmem.dll!" + r.name + " IAT points at rt::shims::find"); - } - if (r.binding == rt::Binding::Unimplemented && - rt::lower(r.dll).find("xaudio") == std::string::npos) - fatal("non-audio unimplemented import " + r.dll + "!" + r.name); - } - std::printf("imports: shim=%d host=%d module=%d unimplemented=%d\n", shim, host, module, unimplemented); - - BinkApi api; - api.open = reinterpret_cast(symbol(bink, "BinkOpen")); - api.wait = reinterpret_cast(symbol(bink, "BinkWait")); - api.do_frame = reinterpret_cast(symbol(bink, "BinkDoFrame")); - api.copy = reinterpret_cast(symbol(bink, "BinkCopyToBuffer")); - api.next = reinterpret_cast(symbol(bink, "BinkNextFrame")); - api.go_to = reinterpret_cast(symbol(bink, "BinkGoto")); - api.close = reinterpret_cast(symbol(bink, "BinkClose")); - api.get_error = reinterpret_cast(symbol(bink, "BinkGetError")); - - void* handle = api.open(movie.string().c_str(), 0); - if (!handle) { - const char* error = api.get_error ? api.get_error() : ""; - std::printf("FAIL BinkOpen returned null: %s\n", error && *error ? error : "(no BinkGetError text)"); - return 1; - } - std::printf("PASS BinkOpen returned %p\n", handle); - - const uint32_t pitch = W * 4; - uint32_t positioned = 0; // the frame the handle sits on after BinkOpen - auto decode = [&](uint32_t index, std::vector& out, const char* label) { - if (index != positioned) { - api.go_to(handle, index, 0); - positioned = index; - } - api.wait(handle); - api.do_frame(handle); - // This GDK build returns 0 from BinkDoFrame/BinkCopyToBuffer even when it writes a valid frame; the - // sentinel replacement and the hash below are the proof, not the return values. - std::fill(out.begin(), out.end(), (uint8_t)0xCD); - api.copy(handle, out.data(), pitch, H, 0, 0, 3); - const size_t untouched = (size_t)std::count(out.begin(), out.end(), 0xCD); - const size_t unique = distinct_bytes(out); - const uint64_t hash = fnv1a(out); - std::printf("%s frame %u: untouched=%zu unique=%zu hash=%016llx\n", label, index, untouched, unique, - (unsigned long long)hash); - check(untouched < out.size(), std::string(label) + " BinkCopyToBuffer replaced the sentinel buffer"); - check(unique > 1, std::string(label) + " wrote more than one byte value"); - return hash; - }; - - hash_first = decode(first, decoded_first, "first"); - if (has_second) hash_second = decode(second, decoded_second, "second"); - if (has_second) { - std::printf("decoded frame %u vs %u: %s\n", first, second, - hash_first == hash_second ? "identical" : "different"); - check(hash_first != hash_second, "the two decoded frames differ (the pipeline carries real frames)"); - } - api.close(handle); - } catch (const std::exception& e) { - std::fprintf(stderr, "FAIL %s\n", e.what()); - return 1; - } - if (g_failures) { - std::printf("RESULT FAIL (decode failed, no present attempted)\n"); - return 1; - } - std::printf("decode: ok, the texture round-trip and present come next\n"); - - // ---- GPU: the Xbox-ABI proxy device, a movie-sized window, PresentX, capture. ---- - vktest::Device d; - const auto device_status = d.initialize(true); - if (device_status == vktest::DeviceStatus::unavailable) { - std::printf("SKIP: no usable Vulkan presentation device\n"); - return 77; - } - EXPECT(device_status == vktest::DeviceStatus::ready); - - WNDCLASSW window_class{}; - window_class.lpfnWndProc = window_proc; - window_class.hInstance = GetModuleHandleW(nullptr); - window_class.lpszClassName = L"LeonidaBootMovieTest"; - window_class.hCursor = LoadCursorW(nullptr, reinterpret_cast(IDC_ARROW)); - EXPECT(RegisterClassW(&window_class)); - RECT frame_rect{0, 0, LONG(W), LONG(H)}; - AdjustWindowRect(&frame_rect, WS_OVERLAPPEDWINDOW, FALSE); - HWND window = CreateWindowExW(0, window_class.lpszClassName, L"Leonida: boot movie on Vulkan", WS_OVERLAPPEDWINDOW, - 0, 0, frame_rect.right - frame_rect.left, frame_rect.bottom - frame_rect.top, - nullptr, nullptr, window_class.hInstance, nullptr); - if (!window) { - std::fprintf(stderr, "FAIL: cannot create the presentation window (Win32 error %lu)\n", GetLastError()); - return 1; - } - ShowWindow(window, SW_SHOWNOACTIVATE); - UpdateWindow(window); - pump(); - { - RECT client{}; - GetClientRect(window, &client); - std::printf("window client: %ldx%ld (movie %ux%u)\n", client.right - client.left, - client.bottom - client.top, W, H); - } - - Frame presented_first, presented_second; - { - rt::d3d12::VulkanDeviceInfo info{}; - info.get_instance_proc = d.instance_proc; - info.instance = d.instance; - info.physical = d.physical; - info.device = d.device; - info.queue = d.queue; - info.queue_family = d.family; - info.presentation = true; - info.swapchain_maintenance1 = d.swapchain_maintenance1; - ID3D12Device* inner = nullptr; - EXPECT(SUCCEEDED(rt::d3d12::create_vulkan_device(info, IID_PPV_ARGS(&inner)))); - Ref device; - EXPECT(SUCCEEDED(rt::d3d12_xs::create_device_proxy(inner, __uuidof(ID3D12Device), - reinterpret_cast(&device.p)))); - rt::d3d12::set_device_outer(inner, device.p); - auto presenter = rt::d3d12::create_window_presenter(inner, window); - EXPECT(presenter); - EXPECT(presenter->enable_capture()); - - leonida::ManualFrameClock clock; - auto owner = std::make_unique(std::move(presenter), &clock); - rt::d3d12::XboxPresentation& xbox = *owner; - - D3D12_COMMAND_QUEUE_DESC queue_desc{}; - Ref queue; - Ref allocator; - Ref list; - Ref fence; - EXPECT(SUCCEEDED(device->CreateCommandQueue(&queue_desc, IID_PPV_ARGS(&queue.p)))); - EXPECT(SUCCEEDED(device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&allocator.p)))); - EXPECT(SUCCEEDED(device->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, allocator.p, nullptr, - IID_PPV_ARGS(&list.p)))); - EXPECT(SUCCEEDED(list->Close())); - EXPECT(SUCCEEDED(device->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&fence.p)))); - HANDLE fence_event = CreateEventW(nullptr, FALSE, FALSE, nullptr); - EXPECT(fence_event != nullptr); - - // The movie frame as a display-capable texture: committed, ALLOW_DISPLAY, in PRESENT. - const D3D12_HEAP_PROPERTIES default_heap{D3D12_HEAP_TYPE_DEFAULT}; - D3D12_RESOURCE_DESC tex_desc{}; - tex_desc.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D; - tex_desc.Width = W; - tex_desc.Height = H; - tex_desc.DepthOrArraySize = 1; - tex_desc.MipLevels = 1; - tex_desc.Format = DXGI_FORMAT_B8G8R8A8_UNORM; // the BinkCopyToBuffer byte order above - tex_desc.SampleDesc.Count = 1; - tex_desc.Flags = D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET; - Ref texture; - EXPECT(SUCCEEDED(device->CreateCommittedResource(&default_heap, D3D12_HEAP_FLAG_ALLOW_DISPLAY, &tex_desc, - D3D12_RESOURCE_STATE_PRESENT, nullptr, - IID_PPV_ARGS(&texture.p)))); - - D3D12_PLACED_SUBRESOURCE_FOOTPRINT footprint{}; - UINT64 total_bytes = 0; - device->GetCopyableFootprints(&tex_desc, 0, 1, 0, &footprint, nullptr, nullptr, &total_bytes); - EXPECT(total_bytes > 0 && footprint.Footprint.RowPitch >= W * 4); - const UINT row_pitch = footprint.Footprint.RowPitch; - - const D3D12_HEAP_PROPERTIES upload_heap{D3D12_HEAP_TYPE_UPLOAD}; - const D3D12_HEAP_PROPERTIES readback_heap{D3D12_HEAP_TYPE_READBACK}; - const auto upload_desc = buffer_desc(total_bytes); - const auto readback_desc = buffer_desc(total_bytes); - Ref upload, readback; - EXPECT(SUCCEEDED(device->CreateCommittedResource(&upload_heap, D3D12_HEAP_FLAG_NONE, &upload_desc, - D3D12_RESOURCE_STATE_GENERIC_READ, nullptr, - IID_PPV_ARGS(&upload.p)))); - EXPECT(SUCCEEDED(device->CreateCommittedResource(&readback_heap, D3D12_HEAP_FLAG_NONE, &readback_desc, - D3D12_RESOURCE_STATE_COPY_DEST, nullptr, - IID_PPV_ARGS(&readback.p)))); - std::uint8_t* up = nullptr; - EXPECT(SUCCEEDED(upload->Map(0, nullptr, reinterpret_cast(&up)))); - - UINT64 signalled = 0; - const auto run_list = [&]() -> bool { - if (FAILED(list->Close())) return false; - ID3D12CommandList* lists[] = {list.p}; - queue->ExecuteCommandLists(1, lists); - if (rt::d3d12::last_execute_result(queue.p) != leonida::ReplayResult::success) return false; - return SUCCEEDED(queue->Signal(fence.p, ++signalled)) && - SUCCEEDED(fence->SetEventOnCompletion(signalled, fence_event)) && - WaitForSingleObject(fence_event, 60'000) == WAIT_OBJECT_0; - }; - - // Uploads `bgra` to the display texture and copies the texture back to the - // readback buffer in the same list, so a failure here fails the texture - // round-trip before any present is attempted. - const auto upload_and_verify = [&](const std::vector& bgra, const char* label) -> bool { - for (UINT y = 0; y < H; ++y) - std::memcpy(up + (size_t)y * row_pitch, bgra.data() + (size_t)y * W * 4, (size_t)W * 4); - if (FAILED(allocator->Reset()) || FAILED(list->Reset(allocator.p, nullptr))) return false; - D3D12_RESOURCE_BARRIER b0 = transition(texture.p, D3D12_RESOURCE_STATE_PRESENT, - D3D12_RESOURCE_STATE_COPY_DEST); - list->ResourceBarrier(1, &b0); - D3D12_TEXTURE_COPY_LOCATION dst{}; - dst.pResource = texture.p; - dst.Type = D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX; - D3D12_TEXTURE_COPY_LOCATION src{}; - src.pResource = upload.p; - src.Type = D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT; - src.PlacedFootprint = footprint; - list->CopyTextureRegion(&dst, 0, 0, 0, &src, nullptr); - D3D12_RESOURCE_BARRIER b1 = transition(texture.p, D3D12_RESOURCE_STATE_COPY_DEST, - D3D12_RESOURCE_STATE_COPY_SOURCE); - list->ResourceBarrier(1, &b1); - D3D12_TEXTURE_COPY_LOCATION rb{}; - rb.pResource = readback.p; - rb.Type = D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT; - rb.PlacedFootprint = footprint; - D3D12_TEXTURE_COPY_LOCATION st{}; - st.pResource = texture.p; - st.Type = D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX; - list->CopyTextureRegion(&rb, 0, 0, 0, &st, nullptr); - D3D12_RESOURCE_BARRIER b2 = transition(texture.p, D3D12_RESOURCE_STATE_COPY_SOURCE, - D3D12_RESOURCE_STATE_PRESENT); - list->ResourceBarrier(1, &b2); - if (!run_list()) return false; - void* mapped = nullptr; - if (FAILED(readback->Map(0, nullptr, &mapped))) return false; - uint64_t differing = 0; - for (UINT y = 0; y < H; ++y) - if (std::memcmp(static_cast(mapped) + (size_t)y * row_pitch, - bgra.data() + (size_t)y * W * 4, (size_t)W * 4) != 0) - ++differing; - readback->Unmap(0, nullptr); - std::printf("%s texture round-trip: %llu of %u rows differ\n", label, - (unsigned long long)differing, (unsigned)H); - return differing == 0; - }; - - const bool first_round_trip = upload_and_verify(decoded_first, "first"); - check(first_round_trip, "first frame texture round-trip bit-exact"); - if (!first_round_trip) return 1; - - const UINT period = rt::d3d12::xbox_frame_interval_60hz_us; - EXPECT(SUCCEEDED(xbox.SetFrameIntervalX(nullptr, period, 1, 0))); - EXPECT(SUCCEEDED(xbox.ScheduleFrameEventX(rt::d3d12::xbox_frame_event_origin, 0, 0))); - - // The presenter filters a scaling blit linearly when the source format - // reports linear filtering and takes the nearest texel otherwise - // (runtime/src/vulkan_present.h, blit_filter). Mirror that query so the - // expected pixels follow the filter the blit actually used. - VkFormatProperties source_properties{}; - d.instance_fn("vkGetPhysicalDeviceFormatProperties")( - d.physical, VK_FORMAT_B8G8R8A8_UNORM, &source_properties); - const bool scaling_linear = - (source_properties.optimalTilingFeatures & VK_FORMAT_FEATURE_SAMPLED_IMAGE_FILTER_LINEAR_BIT) != 0; - - // Compares the captured swapchain image with the decoded BGRA frame: every - // pixel bit-exact at 1:1 (the window is the movie's size, so the plain - // blit samples texel centres), or within 2 levels of the presenter's - // filter model at destination texel centres when the swapchain came back - // at another size (documented, not silent: extent and filter are printed). - const auto compare_presented = [&](const Frame& frame, const std::vector& bgra, - const char* label) { - const UINT ew = frame.extent.width, eh = frame.extent.height; - const bool one_to_one = (ew == W && eh == H); - std::printf("%s presented extent: %ux%u (movie %ux%u, swapchain format %d, %s filter)%s\n", label, ew, eh, - W, H, int(frame.format), scaling_linear ? "linear" : "nearest", - one_to_one ? "" : " (scaled comparison)"); - if (frame.format == VK_FORMAT_B8G8R8A8_SRGB) { - std::printf("%s: sRGB swapchain, pixel comparison skipped (the blit encodes sRGB and these bytes " - "are compared as UNORM)\n", label); - return; - } - uint64_t exact = 0, within1 = 0, within2 = 0; - int worst = 0; - UINT bad_x = 0, bad_y = 0; - RGB bad_got{0, 0, 0}, bad_want{0, 0, 0}; - for (UINT y = 0; y < eh; ++y) { - for (UINT x = 0; x < ew; ++x) { - const RGB want = one_to_one ? decoded_at(bgra, W, x, y) - : sampled_at(bgra, W, H, ew, eh, x, y, scaling_linear); - const RGB got = presented_at(frame, x, y); - const int err = std::max({std::abs(got.r - want.r), std::abs(got.g - want.g), - std::abs(got.b - want.b)}); - worst = std::max(worst, err); - if (err > 0 && exact++ == 0) { - bad_x = x; - bad_y = y; - bad_got = got; - bad_want = want; - } - within1 += err <= 1; - within2 += err <= 2; - } - } - const uint64_t total = (uint64_t)ew * eh; - std::printf("%s presented vs decoded: exact %llu/%llu, within 1: %llu/%llu, within 2: %llu/%llu, " - "worst %d", - label, (unsigned long long)(total - exact), (unsigned long long)total, - (unsigned long long)within1, (unsigned long long)total, (unsigned long long)within2, - (unsigned long long)total, worst); - if (exact) - std::printf(" (first at %u,%u: got %d,%d,%d want %d,%d,%d)", bad_x, bad_y, bad_got.r, bad_got.g, - bad_got.b, bad_want.r, bad_want.g, bad_want.b); - std::printf("\n"); - if (one_to_one) - check(exact == 0, std::string(label) + " presented pixels bit-exact at 1:1"); - else - check(within2 == total, std::string(label) + " presented pixels within 2 of the filter model"); - // The centre pixel and the four corners of the presented frame, - // against the same filter model. - const UINT px[5][2] = {{ew / 2, eh / 2}, {0, 0}, {ew - 1, 0}, {0, eh - 1}, {ew - 1, eh - 1}}; - const char* name[5] = {"centre", "top-left", "top-right", "bottom-left", "bottom-right"}; - for (int i = 0; i < 5; ++i) { - const RGB got = presented_at(frame, px[i][0], px[i][1]); - const RGB want = one_to_one ? decoded_at(bgra, W, px[i][0], px[i][1]) - : sampled_at(bgra, W, H, ew, eh, px[i][0], px[i][1], scaling_linear); - const int err = std::max({std::abs(got.r - want.r), std::abs(got.g - want.g), - std::abs(got.b - want.b)}); - std::printf("%s %s (%u,%u): presented %d,%d,%d expected %d,%d,%d\n", label, name[i], px[i][0], - px[i][1], got.r, got.g, got.b, want.r, want.g, want.b); - check(err <= (one_to_one ? 0 : 2), std::string(label) + " " + name[i] + " pixel matches"); - } - }; - - std::uint64_t token = 0; - const auto present = [&](const char* label, Frame& out) -> bool { - clock.advance_us(period); - if (xbox.WaitFrameEventX(rt::d3d12::xbox_frame_event_origin, 0, 0, &token) != S_OK) return false; - rt::d3d12::XboxPresentPlaneParameters plane{token, 1, &texture.p, nullptr, 0}; - if (xbox.PresentX(1, &plane, nullptr) != S_OK) return false; - return xbox.presenter().read_back(out.bytes, &out.extent, &out.format); - }; - - EXPECT(present("first", presented_first)); - compare_presented(presented_first, decoded_first, "first"); - - if (has_second) { - const bool second_round_trip = upload_and_verify(decoded_second, "second"); - check(second_round_trip, "second frame texture round-trip bit-exact"); - if (!second_round_trip) return 1; - EXPECT(present("second", presented_second)); - compare_presented(presented_second, decoded_second, "second"); - if (presented_first.extent.width == presented_second.extent.width && - presented_first.extent.height == presented_second.extent.height && - presented_first.format == presented_second.format) { - uint64_t differing = 0; - for (size_t i = 0; i < presented_first.bytes.size(); ++i) - differing += presented_first.bytes[i] != presented_second.bytes[i]; - std::printf("presented frame %u vs %u: %llu of %zu bytes differ\n", first, second, - (unsigned long long)differing, presented_first.bytes.size()); - check(differing > 0, "the two presented frames differ (the present carries real frames)"); - } else { - std::printf("presented frames have different extents/formats, skipping the byte comparison\n"); - } - } - - upload->Unmap(0, nullptr); - CloseHandle(fence_event); - } - DestroyWindow(window); - UnregisterClassW(window_class.lpszClassName, window_class.hInstance); - - if (d.validation_errors()) { - std::fprintf(stderr, "%u validation errors\n", d.validation_errors()); - return 1; - } - std::printf("%s\n", g_failures ? "RESULT FAIL" : "RESULT PASS"); - return g_failures ? 1 : 0; -} diff --git a/runtime/test/d3d12_buffer_tiles_test.cpp b/runtime/test/d3d12_buffer_tiles_test.cpp deleted file mode 100644 index b63729b40..000000000 --- a/runtime/test/d3d12_buffer_tiles_test.cpp +++ /dev/null @@ -1,296 +0,0 @@ -// Synthetic reserved buffers and real D3D12 heap mappings. Run the same cases on the Vulkan layer and the host. -#include "../shims/d3d12_com.h" - -#include -#include - -#include -#include -#include -#include -#include -#include - -#define EXPECT(condition) do { \ - if (!(condition)) { std::fprintf(stderr, "line %d: %s\n", __LINE__, #condition); return false; } \ -} while (0) - -namespace { - -using Microsoft::WRL::ComPtr; -constexpr UINT64 tile_bytes = D3D12_TILED_RESOURCE_TILE_SIZE_IN_BYTES; -constexpr UINT snapshots = 3, tiles_per_buffer = 4; -constexpr UINT64 buffer_bytes = tiles_per_buffer * tile_bytes; -constexpr std::array patterns{0x23456789, 0xf1c0a761, 0x9a879651, 0xe721cc71}; -using Snapshot = std::array; -using Results = std::array; -constexpr Results expected{{ - {patterns[0], patterns[1], patterns[2], 0}, - {patterns[0], 0, patterns[2], patterns[2]}, - {0, patterns[1], 0, 0}, -}}; - -D3D12_RESOURCE_DESC buffer_desc(UINT64 bytes) { - D3D12_RESOURCE_DESC desc{}; - desc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER; - desc.Width = bytes; - desc.Height = desc.DepthOrArraySize = desc.MipLevels = 1; - desc.SampleDesc.Count = 1; - desc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; - return desc; -} - -struct Event { - HANDLE handle = CreateEventW(nullptr, FALSE, FALSE, nullptr); - ~Event() { if (handle) CloseHandle(handle); } -}; - -struct Gate { - ID3D12Fence* fence; - ~Gate() { if (fence) fence->Signal(1); } -}; - -bool run(ID3D12Device& device, Results& result, bool layer = false) { - ComPtr a, b, upload, readback; - const auto reserved = buffer_desc(buffer_bytes); - EXPECT(SUCCEEDED(device.CreateReservedResource(&reserved, D3D12_RESOURCE_STATE_COMMON, nullptr, IID_PPV_ARGS(&a)))); - EXPECT(SUCCEEDED(device.CreateReservedResource(&reserved, D3D12_RESOURCE_STATE_COMMON, nullptr, IID_PPV_ARGS(&b)))); - EXPECT(a->GetGPUVirtualAddress() && b->GetGPUVirtualAddress() && a->GetGPUVirtualAddress() != b->GetGPUVirtualAddress()); - UINT tile_count = 0; - device.GetResourceTiling(a.Get(), &tile_count, nullptr, nullptr, nullptr, 0, nullptr); - EXPECT(tile_count == tiles_per_buffer); - - D3D12_HEAP_DESC heap_desc{}; - heap_desc.SizeInBytes = 3 * tile_bytes; - heap_desc.Properties.Type = D3D12_HEAP_TYPE_DEFAULT; - heap_desc.Properties.CreationNodeMask = heap_desc.Properties.VisibleNodeMask = 1; - heap_desc.Flags = D3D12_HEAP_FLAG_ALLOW_ONLY_BUFFERS; - ComPtr heap; - EXPECT(SUCCEEDED(device.CreateHeap(&heap_desc, IID_PPV_ARGS(&heap)))); - D3D12_HEAP_PROPERTIES upload_heap = heap_desc.Properties, readback_heap = heap_desc.Properties; - upload_heap.Type = D3D12_HEAP_TYPE_UPLOAD; - readback_heap.Type = D3D12_HEAP_TYPE_READBACK; - const auto source_desc = buffer_desc(tile_bytes + buffer_bytes); - const auto target_desc = buffer_desc(snapshots * buffer_bytes); - EXPECT(SUCCEEDED(device.CreateCommittedResource(&upload_heap, D3D12_HEAP_FLAG_NONE, &source_desc, - D3D12_RESOURCE_STATE_GENERIC_READ, nullptr, IID_PPV_ARGS(&upload)))); - EXPECT(SUCCEEDED(device.CreateCommittedResource(&readback_heap, D3D12_HEAP_FLAG_NONE, &target_desc, - D3D12_RESOURCE_STATE_COPY_DEST, nullptr, IID_PPV_ARGS(&readback)))); - constexpr auto words_per_tile = std::size_t(tile_bytes / sizeof(std::uint32_t)); - const D3D12_RANGE empty{0, 0}; - void* mapped = nullptr; - EXPECT(SUCCEEDED(upload->Map(0, &empty, &mapped))); - auto* words = static_cast(mapped); - for (std::size_t i = 0; i < patterns.size(); ++i) - std::fill_n(words + (i + 1) * words_per_tile, words_per_tile, patterns[i]); - upload->Unmap(0, nullptr); - - ComPtr gate, done; - EXPECT(SUCCEEDED(device.CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&gate)))); - EXPECT(SUCCEEDED(device.CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&done)))); - std::array, snapshots> allocators; - std::array, snapshots> lists; - for (UINT i = 0; i < snapshots; ++i) { - EXPECT(SUCCEEDED(device.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&allocators[i])))); - EXPECT(SUCCEEDED(device.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, allocators[i].Get(), nullptr, - IID_PPV_ARGS(&lists[i])))); - } - ComPtr queue; - const D3D12_COMMAND_QUEUE_DESC queue_desc{}; - EXPECT(SUCCEEDED(device.CreateCommandQueue(&queue_desc, IID_PPV_ARGS(&queue)))); - Event event; - EXPECT(event.handle); - Gate open_on_exit{gate.Get()}; - EXPECT(SUCCEEDED(queue->Wait(gate.Get(), 1))); - - // Map disjoint tiles in a different order, using the default one-tile resource regions. - const D3D12_TILED_RESOURCE_COORDINATE starts[] = {{2, 0, 0, 0}, {0, 0, 0, 0}, {1, 0, 0, 0}}; - const UINT heap_offsets[] = {2, 0, 1}, heap_counts[] = {1, 1, 1}; - queue->UpdateTileMappings(a.Get(), 3, starts, nullptr, heap.Get(), 3, nullptr, heap_offsets, heap_counts, - D3D12_TILE_MAPPING_FLAG_NONE); - EXPECT(SUCCEEDED(device.GetDeviceRemovedReason())); - const D3D12_TILED_RESOURCE_COORDINATE origin{}; - const D3D12_TILE_REGION_SIZE all{tiles_per_buffer, FALSE, 0, 0, 0}; - queue->CopyTileMappings(b.Get(), &origin, a.Get(), &origin, &all, D3D12_TILE_MAPPING_FLAG_NONE); - EXPECT(SUCCEEDED(device.GetDeviceRemovedReason())); - lists[0]->CopyTiles(a.Get(), &origin, &all, upload.Get(), tile_bytes, - D3D12_TILE_COPY_FLAG_LINEAR_BUFFER_TO_SWIZZLED_TILED_RESOURCE); - D3D12_RESOURCE_BARRIER alias{}; - alias.Type = D3D12_RESOURCE_BARRIER_TYPE_ALIASING; - alias.Aliasing = {a.Get(), b.Get()}; - lists[0]->ResourceBarrier(1, &alias); - lists[0]->CopyTiles(b.Get(), &origin, &all, readback.Get(), 0, - D3D12_TILE_COPY_FLAG_SWIZZLED_TILED_RESOURCE_TO_LINEAR_BUFFER); - const auto submit = [&](UINT i) { - if (FAILED(lists[i]->Close())) return false; - ID3D12CommandList* batch[] = {lists[i].Get()}; - queue->ExecuteCommandLists(1, batch); - return true; - }; - EXPECT(submit(0)); - EXPECT(SUCCEEDED(device.GetDeviceRemovedReason())); - - // Preserve B[0], detach B[1] and make B[2:4] share the same physical tile. One range crosses a region boundary. - const D3D12_TILED_RESOURCE_COORDINATE regions[] = {{0, 0, 0, 0}, {3, 0, 0, 0}}; - const D3D12_TILE_REGION_SIZE sizes[] = {{3, FALSE, 0, 0, 0}, {1, FALSE, 0, 0, 0}}; - const D3D12_TILE_RANGE_FLAGS flags[] = {D3D12_TILE_RANGE_FLAG_SKIP, D3D12_TILE_RANGE_FLAG_NULL, - D3D12_TILE_RANGE_FLAG_REUSE_SINGLE_TILE}; - const UINT offsets[] = {0, 0, 2}, counts[] = {1, 1, 2}; - queue->UpdateTileMappings(b.Get(), 2, regions, sizes, heap.Get(), 3, flags, offsets, counts, - D3D12_TILE_MAPPING_FLAG_NONE); - EXPECT(SUCCEEDED(device.GetDeviceRemovedReason())); - if (layer) { - // One valid tile followed by an out-of-bounds heap index. The entire update is rejected. - const D3D12_TILE_RANGE_FLAGS invalid_flags[] = {D3D12_TILE_RANGE_FLAG_NULL, D3D12_TILE_RANGE_FLAG_NONE}; - const UINT invalid_offsets[] = {0, 3}, invalid_counts[] = {1, 1}; - const D3D12_TILE_REGION_SIZE first_two{2, FALSE, 0, 0, 0}; - queue->UpdateTileMappings(b.Get(), 1, &origin, &first_two, heap.Get(), 2, invalid_flags, invalid_offsets, - invalid_counts, D3D12_TILE_MAPPING_FLAG_NONE); - } - lists[1]->CopyBufferRegion(readback.Get(), buffer_bytes, b.Get(), 0, buffer_bytes); - EXPECT(submit(1)); - - const auto unmap = D3D12_TILE_RANGE_FLAG_NULL; - queue->UpdateTileMappings(b.Get(), 1, nullptr, nullptr, nullptr, 1, &unmap, nullptr, nullptr, - D3D12_TILE_MAPPING_FLAG_NONE); - const D3D12_TILE_REGION_SIZE one{1, FALSE, 0, 0, 0}; - queue->CopyTileMappings(b.Get(), &starts[2], a.Get(), &starts[2], &one, D3D12_TILE_MAPPING_FLAG_NONE); - lists[2]->CopyTiles(b.Get(), &origin, &all, readback.Get(), 2 * buffer_bytes, - D3D12_TILE_COPY_FLAG_SWIZZLED_TILED_RESOURCE_TO_LINEAR_BUFFER); - EXPECT(submit(2)); - EXPECT(SUCCEEDED(queue->Signal(done.Get(), 1))); - const auto before_open = done->GetCompletedValue(); - if (before_open != 0) { - std::fprintf(stderr, "fence before opening the gate: %llu, device status %#lx\n", - static_cast(before_open), static_cast(device.GetDeviceRemovedReason())); - return false; - } - EXPECT(SUCCEEDED(gate->Signal(1))); - open_on_exit.fence = nullptr; - EXPECT(SUCCEEDED(done->SetEventOnCompletion(1, event.handle))); - EXPECT(WaitForSingleObject(event.handle, 15000) == WAIT_OBJECT_0); - - EXPECT(SUCCEEDED(readback->Map(0, nullptr, &mapped))); - const auto* data = static_cast(mapped); - // Every word of every tile, with the first wrong word of each tile printed, so a failure says which side, - // snapshot and tile differ and what was read there. - UINT wrong_tiles = 0; - for (UINT i = 0; i < snapshots; ++i) { - for (UINT tile = 0; tile < tiles_per_buffer; ++tile) { - const auto* first = data + (i * tiles_per_buffer + tile) * words_per_tile; - result[i][tile] = *first; - const auto* bad = std::find_if(first, first + words_per_tile, [&](auto word) { return word != expected[i][tile]; }); - if (bad == first + words_per_tile) continue; - ++wrong_tiles; - const auto wrong_words = std::count_if(bad, first + words_per_tile, - [&](auto word) { return word != expected[i][tile]; }); - std::fprintf(stderr, "%s snapshot %u tile %u: word %u reads %#010x, want %#010x (%lld of %llu words wrong)\n", - layer ? "Vulkan layer" : "native D3D12", i, tile, unsigned(bad - first), unsigned(*bad), - unsigned(expected[i][tile]), static_cast(wrong_words), - static_cast(words_per_tile)); - } - } - readback->Unmap(0, &empty); - EXPECT(wrong_tiles == 0); - return true; -} - -// D3D12 on the adapter `luid` names, when it has tiled resources tier 2 or more; null otherwise. -ComPtr tiled_device(IDXGIFactory4& factory, LUID luid, bool print = true) { - ComPtr adapter; - if (!luid.LowPart && !luid.HighPart) return {}; - if (FAILED(factory.EnumAdapterByLuid(luid, IID_PPV_ARGS(&adapter)))) return {}; - DXGI_ADAPTER_DESC1 desc{}; - ComPtr device; - D3D12_FEATURE_DATA_D3D12_OPTIONS options{}; - if (FAILED(adapter->GetDesc1(&desc)) || (desc.Flags & DXGI_ADAPTER_FLAG_SOFTWARE) || - FAILED(D3D12CreateDevice(adapter.Get(), D3D_FEATURE_LEVEL_11_0, IID_PPV_ARGS(&device))) || - FAILED(device->CheckFeatureSupport(D3D12_FEATURE_D3D12_OPTIONS, &options, sizeof(options))) || - options.TiledResourcesTier < D3D12_TILED_RESOURCES_TIER_2) - return {}; - if (print) - std::printf("Native D3D12: %ls (the layer's adapter), tiled resources tier %u\n", desc.Description, - unsigned(options.TiledResourcesTier)); - return device; -} - -// The host adapter for the native half. LEONIDA_HOST_ADAPTER picks it as in d3d12_copy_compare.h: "warp", or part of -// an adapter name (case-insensitive); a value that names no adapter with tiled resources tier 2 skips the native half -// rather than testing another GPU. Unset: the adapter behind the layer's Vulkan device (`layer_luid`, as -// host_adapter.h picks it), so a PC with two GPUs compares the layer with its own GPU's driver; when that adapter -// has no tier 2, the first hardware adapter with tier 2 or more. -ComPtr native_device(LUID layer_luid) { - ComPtr factory; - if (FAILED(CreateDXGIFactory1(IID_PPV_ARGS(&factory)))) return {}; - char want[128] = {}; - GetEnvironmentVariableA("LEONIDA_HOST_ADAPTER", want, sizeof(want)); - std::string needle(want); - std::transform(needle.begin(), needle.end(), needle.begin(), [](unsigned char c) { return char(std::tolower(c)); }); - if (needle.empty()) - if (auto device = tiled_device(*factory.Get(), layer_luid)) return device; - for (UINT i = 0;; ++i) { - ComPtr adapter; - if (needle == "warp") { - if (i > 0 || FAILED(factory->EnumWarpAdapter(IID_PPV_ARGS(&adapter)))) break; - } else if (factory->EnumAdapters1(i, &adapter) != S_OK) { - break; - } - DXGI_ADAPTER_DESC1 desc{}; - if (FAILED(adapter->GetDesc1(&desc))) continue; - if (needle.empty()) { - if (desc.Flags & DXGI_ADAPTER_FLAG_SOFTWARE) continue; - } else if (needle != "warp") { - std::string name; - for (const wchar_t* c = desc.Description; *c; ++c) name += char(std::tolower(*c < 128 ? *c : '?')); - if (name.find(needle) == std::string::npos) continue; - } - ComPtr device; - if (FAILED(D3D12CreateDevice(adapter.Get(), D3D_FEATURE_LEVEL_11_0, IID_PPV_ARGS(&device)))) continue; - D3D12_FEATURE_DATA_D3D12_OPTIONS options{}; - if (FAILED(device->CheckFeatureSupport(D3D12_FEATURE_D3D12_OPTIONS, &options, sizeof(options))) || - options.TiledResourcesTier < D3D12_TILED_RESOURCES_TIER_2) continue; - std::printf("Native D3D12: %ls, tiled resources tier %u\n", desc.Description, unsigned(options.TiledResourcesTier)); - return device; - } - if (!needle.empty()) - std::printf("Native D3D12: no adapter matching LEONIDA_HOST_ADAPTER=%s with tiled resources tier 2 or more; " - "native half skipped\n", want); - return {}; -} - -} // namespace - -int main() { - ComPtr vulkan; - const auto init = rt::d3d12::create_vulkan_device_standalone(IID_PPV_ARGS(&vulkan)); - if (FAILED(init)) { - std::puts("Vulkan standalone device unavailable"); - return 77; - } - if (!rt::d3d12::device_sparse_buffer_tiles(vulkan.Get())) { - std::puts("Vulkan device lacks sparse buffer residency with aliasing and strict unbound reads"); - return 77; - } - Results observed{}, native{}; - if (!run(*vulkan.Get(), observed, true)) return 1; - std::puts("Vulkan replay: 12 full tiles matched across aliased, skipped, unmapped, reused and remapped ranges"); - std::puts("A rejected update left all tile mappings intact"); - const LUID layer_luid = vulkan->GetAdapterLuid(); - if (auto device = native_device(layer_luid)) { - // Unset LEONIDA_HOST_ADAPTER means the layer's own GPU whenever its driver can run the cases: comparing with - // another GPU's driver measures that driver (an Intel tier-4 iGPU read snapshot 1 as zeros), not the layer. - char want[2] = {}; - const LUID host_luid = device->GetAdapterLuid(); - ComPtr factory; - if (!GetEnvironmentVariableA("LEONIDA_HOST_ADAPTER", want, sizeof(want)) && - SUCCEEDED(CreateDXGIFactory1(IID_PPV_ARGS(&factory))) && tiled_device(*factory.Get(), layer_luid, false) && - (host_luid.LowPart != layer_luid.LowPart || host_luid.HighPart != layer_luid.HighPart)) { - std::fprintf(stderr, "Native D3D12 runs on another adapter than the layer's, which has tiled resources " - "tier 2 or more\n"); - return 1; - } - if (!run(*device.Get(), native) || native != observed) return 1; - std::puts("Native D3D12 matched all three GPU readbacks"); - } - return 0; -} diff --git a/runtime/test/d3d12_buffer_uav_test.cpp b/runtime/test/d3d12_buffer_uav_test.cpp deleted file mode 100644 index a2fa90330..000000000 --- a/runtime/test/d3d12_buffer_uav_test.cpp +++ /dev/null @@ -1,728 +0,0 @@ -// Typed buffer UAVs and UAV counters (docs/d3d12_vulkan.md section 3.4, "Buffer UAVs"), through the D3D12 API on the -// proxy, with compute shaders that are translator output (test/shaders/cs_buf_typed.asm and cs_buf_counter.asm, -// hand-written RDNA2), plus D3D12-only behaviour compared with the host runtime on the same adapter. -// -// Part 1, one DIRECT list: a compute root signature (four root constants and a table of six UAVs), two compute PSOs. -// cs_buf_typed writes typed buffer views (R32_UINT with an atomic add, R16G16B16A16_FLOAT, R8G8B8A8_UNORM from -// FirstElement 16, R32G32B32A32_UINT, R32_SINT) and reads an R32_FLOAT view. Two views are shorter -// than the dispatch (240 and 250 elements of 256): the V#'s NUM_RECORDS is the bound, so stores past -// it leave the buffer's sentinel and loads past it give 0. -// cs_buf_counter a structured UAV with a counter at CounterOffsetInBytes 4096 of another buffer: 256 lanes append -// (buffer_atomic_add on the counter V# in the slot's upper half, store at the returned index), then -// 128 lanes consume (buffer_atomic_sub, load the record just below). "CopyStructureCount" in D3D12 -// is CopyBufferRegion of the counter's 4 bytes into a buffer: read after the append (256) and after -// the consume (128). Lane order is up to the GPU, so records are compared as sets. -// Everything is compared with a CPU reference, word by word, error 0. -// Part 2, the layer's device (no proxy) and the host runtime on the SAME adapter (LUID): typed buffer UAVs created with -// CreateUnorderedAccessView and cleared with ClearUnorderedAccessViewUint / Float (thirteen formats, sub-ranges, an -// element range ending off a word boundary), and a structured UAV with a counter: a clear of the structured view and -// of the counter's own word through a raw view. The bytes read back are compared with the host's; with no host D3D12 -// the layer's are compared with the model of uav_clear.h. -// Set LEONIDA_VK_VALIDATION=1 to run under VK_LAYER_KHRONOS_validation (0 errors required). -#include "vk_test_device.h" -#include "d3d12_test_shaders.h" -#include "d3d12_copy_compare.h" -#include "../shims/d3d12_com.h" -#include "../shims/d3d12_xs_device.h" -#include "../src/gfx10_descriptors.h" -#include "../src/shader_library.h" -#include "../src/uav_clear.h" - -#include -#include -#include -#include -#include - -#ifndef LEONIDA_TEST_BUFFER_UAV_DIR -#error "LEONIDA_TEST_BUFFER_UAV_DIR must name the folder build.py wrote (spirv/index.json, fssm/cs_*.fssm)" -#endif - -#define EXPECT(condition) do { \ - if (!(condition)) { std::fprintf(stderr, "line %d: %s\n", __LINE__, #condition); return 1; } \ -} while (0) - -using namespace d3d12test; -using XboxHeapHandleFn = std::uint64_t(WINAPI*)(void* heap); // heap slots 9/10: handle in RAX -namespace g = leonida::gfx10; -namespace uc = leonida::uav_clear; - -namespace { - -std::vector read_file(const std::filesystem::path& path) { - std::ifstream in(path, std::ios::binary); - return {std::istreambuf_iterator(in), std::istreambuf_iterator()}; -} - -constexpr UINT lanes = 256; -constexpr UINT seed = 0x00c0ffee, multiplier = 0x01000193; -constexpr std::uint32_t sentinel = 0xa5a5a5a5u; -constexpr UINT out0_elements = 240, in4_elements = 250, out2_first = 16; -constexpr UINT64 counter_offset = 4096, counter_buffer_bytes = 8192; -constexpr UINT consumed = 128; - -// The buffers of part 1: sizes, in the order of their slices of the upload and of the readback buffer. -enum Buf { out0, out1, out2, out3, in4, out5, records, counter, consumed_out, buffer_count }; -constexpr UINT64 sizes[buffer_count] = {lanes * 4, lanes * 8, (out2_first + lanes) * 4, lanes * 16, lanes * 4, - lanes * 4, lanes * 8, counter_buffer_bytes, consumed * 8}; -constexpr UINT64 slice(Buf which) { - UINT64 at = 0; - for (int i = 0; i < which; ++i) at += (sizes[i] + 255) / 256 * 256; - return at; -} -constexpr UINT64 total_bytes = slice(consumed_out) + (sizes[consumed_out] + 255) / 256 * 256; -constexpr UINT64 count_after_append = total_bytes, count_after_consume = total_bytes + 4; -constexpr UINT64 readback_bytes = total_bytes + 8; - -std::uint16_t half_bits(float value) { // exact for the values the reference uses (finite, in the normal range) - const std::uint32_t f = std::bit_cast(value); - if (!(f & 0x7fffffffu)) return std::uint16_t(f >> 16); - const int exponent = int((f >> 23) & 0xff) - 127 + 15; - return std::uint16_t(((f >> 16) & 0x8000) | (exponent << 10) | ((f >> 13) & 0x3ff)); -} - -float input_value(UINT g) { return float(g) - 100.5f; } - -struct Reference { - std::vector words[buffer_count]; -}; - -Reference reference() { - Reference ref; - for (int i = 0; i < buffer_count; ++i) ref.words[i].assign(sizes[i] / 4, sentinel); - for (UINT g = 0; g < lanes; ++g) { - if (g < out0_elements) ref.words[out0][g] = (g * multiplier + seed) + g; - const float x = float(g); - ref.words[out1][g * 2] = half_bits(x) | std::uint32_t(half_bits(x + 0.5f)) << 16; - ref.words[out1][g * 2 + 1] = half_bits(-1.0f - x) | std::uint32_t(half_bits(0.25f)) << 16; - const std::uint32_t k = g & 255; - ref.words[out2][out2_first + g] = k | (255 - k) << 8 | 0xff000000u; - ref.words[out3][g * 4 + 0] = g; - ref.words[out3][g * 4 + 1] = g ^ 0xffff; - ref.words[out3][g * 4 + 2] = g * 7; - ref.words[out3][g * 4 + 3] = 0xa5; - ref.words[in4][g] = std::bit_cast(input_value(g)); - ref.words[out5][g] = g < in4_elements ? std::uint32_t(int(2.0f * input_value(g))) : 0; - } - return ref; -} - -D3D12_RESOURCE_BARRIER uav_barrier(ID3D12Resource* resource) { - D3D12_RESOURCE_BARRIER b{}; - b.Type = D3D12_RESOURCE_BARRIER_TYPE_UAV; - b.UAV.pResource = resource; - return b; -} - -D3D12_UNORDERED_ACCESS_VIEW_DESC buffer_view(DXGI_FORMAT format, UINT64 first, UINT count, UINT stride, - UINT64 counter_at = 0, D3D12_BUFFER_UAV_FLAGS flags = D3D12_BUFFER_UAV_FLAG_NONE) { - D3D12_UNORDERED_ACCESS_VIEW_DESC view{}; - view.Format = format; - view.ViewDimension = D3D12_UAV_DIMENSION_BUFFER; - view.Buffer = {first, count, stride, counter_at, flags}; - return view; -} - -// What a V# in a slot says, as the shader loads it. -struct Vsharp { - std::uint64_t address; - std::uint32_t stride, records, format, oob; -}; -Vsharp vsharp(const void* slot_pointer, unsigned dword = 0) { - std::uint32_t w[4]; - std::memcpy(w, static_cast(slot_pointer) + dword, sizeof(w)); - return {(std::uint64_t(w[1] & 0xffff) << 32) | w[0], w[1] >> 16 & 0x3fff, w[2], w[3] >> 12 & 0x7f, w[3] >> 28 & 3}; -} - -// ---- part 1 ----------------------------------------------------------------------------------------------------- - -int run_shaders(vktest::Device& d, const std::filesystem::path& root_dir, unsigned& words_checked) { - leonida::ShaderLibrary library; - EXPECT(library.load((root_dir / "spirv").string())); - const auto program = [&](const char* name) { return read_file(root_dir / "fssm" / (std::string(name) + ".fssm")); }; - const auto typed_fssm = program("cs_buf_typed"), counter_fssm = program("cs_buf_counter"); - EXPECT(typed_fssm.size() >= 0x150 && counter_fssm.size() >= 0x150 && typed_fssm != counter_fssm); - EXPECT(library.find("cs", leonida::sha256_hex(typed_fssm)) && library.find("cs", leonida::sha256_hex(counter_fssm))); - const auto typed_container = shader_container(typed_fssm), counter_container = shader_container(counter_fssm); - - rt::d3d12::VulkanDeviceInfo info{}; - info.get_instance_proc = d.instance_proc; - info.instance = d.instance; - info.physical = d.physical; - info.device = d.device; - info.queue = d.queue; - info.queue_family = d.family; - info.buffer_device_address = true; - info.bindless = d.bindless; - info.bindless_partially_bound = d.partially_bound; - info.image_view_min_lod = d.image_view_min_lod; - info.shader_dir = (root_dir / "spirv").string(); - ID3D12Device* inner = nullptr; - EXPECT(SUCCEEDED(rt::d3d12::create_vulkan_device(info, IID_PPV_ARGS(&inner)))); - Ref device; - EXPECT(SUCCEEDED(rt::d3d12_xs::create_device_proxy(inner, __uuidof(ID3D12Device), - reinterpret_cast(&device.p)))); - rt::d3d12::set_device_outer(inner, device.p); - EXPECT(rt::d3d12::bindless_set(device.p) != VK_NULL_HANDLE); - - D3D12_DESCRIPTOR_RANGE uav_range{D3D12_DESCRIPTOR_RANGE_TYPE_UAV, 6, 0, 0, 0}; - D3D12_ROOT_PARAMETER params[2] = {}; - params[0].ParameterType = D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS; - params[0].Constants = {0, 0, 4}; - params[0].ShaderVisibility = D3D12_SHADER_VISIBILITY_ALL; - params[1].ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE; - params[1].DescriptorTable = {1, &uav_range}; - params[1].ShaderVisibility = D3D12_SHADER_VISIBILITY_ALL; - D3D12_VERSIONED_ROOT_SIGNATURE_DESC root_desc{}; - root_desc.Version = D3D_ROOT_SIGNATURE_VERSION_1_0; - root_desc.Desc_1_0 = {2, params, 0, nullptr, D3D12_ROOT_SIGNATURE_FLAG_NONE}; - const auto root_blob = serialize_root_signature(root_desc); - EXPECT(!root_blob.empty()); - Ref root; - EXPECT(SUCCEEDED(device->CreateRootSignature(0, root_blob.data(), root_blob.size(), IID_PPV_ARGS(&root.p)))); - D3D12_COMPUTE_PIPELINE_STATE_DESC pso_desc{}; - pso_desc.pRootSignature = root.p; - pso_desc.CS = {typed_container.data(), typed_container.size()}; - Ref pso_typed, pso_counter; - EXPECT(SUCCEEDED(device->CreateComputePipelineState(&pso_desc, IID_PPV_ARGS(&pso_typed.p)))); - pso_desc.CS = {counter_container.data(), counter_container.size()}; - EXPECT(SUCCEEDED(device->CreateComputePipelineState(&pso_desc, IID_PPV_ARGS(&pso_counter.p)))); - - const D3D12_HEAP_PROPERTIES default_heap{D3D12_HEAP_TYPE_DEFAULT}, upload_heap{D3D12_HEAP_TYPE_UPLOAD}, - readback_heap{D3D12_HEAP_TYPE_READBACK}; - Ref upload, readback, buf[buffer_count]; - const auto create = [&](Ref& out, const D3D12_HEAP_PROPERTIES& heap, UINT64 bytes, - D3D12_RESOURCE_FLAGS flags, D3D12_RESOURCE_STATES state) { - const auto desc = buffer_desc(bytes, flags); - return SUCCEEDED(device->CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &desc, state, nullptr, - IID_PPV_ARGS(&out.p))); - }; - EXPECT(create(upload, upload_heap, total_bytes, D3D12_RESOURCE_FLAG_NONE, D3D12_RESOURCE_STATE_GENERIC_READ)); - EXPECT(create(readback, readback_heap, readback_bytes, D3D12_RESOURCE_FLAG_NONE, D3D12_RESOURCE_STATE_COPY_DEST)); - for (int i = 0; i < buffer_count; ++i) - EXPECT(create(buf[i], default_heap, sizes[i], D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS, - D3D12_RESOURCE_STATE_COPY_DEST)); - Reference want = reference(); - { - std::uint8_t* mapped = nullptr; - EXPECT(SUCCEEDED(upload->Map(0, nullptr, reinterpret_cast(&mapped)))); - for (UINT64 i = 0; i < total_bytes / 4; ++i) std::memcpy(mapped + i * 4, &sentinel, 4); - // The input buffer holds floats; the counter's own word starts at 0 (the rest of its buffer is sentinel). - std::memcpy(mapped + slice(in4), want.words[in4].data(), sizes[in4]); - std::memset(mapped + slice(counter) + counter_offset, 0, 4); - upload->Unmap(0, nullptr); - } - - // The table: slots 0..5 typed views for cs_buf_typed; slot 6 a structured UAV with a counter, slot 7 a raw output - // for cs_buf_counter (its table starts at slot 6). - const D3D12_DESCRIPTOR_HEAP_DESC heap_desc{D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, 12, - D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE, 0}; - Ref heap; - EXPECT(SUCCEEDED(device->CreateDescriptorHeap(&heap_desc, IID_PPV_ARGS(&heap.p)))); - const std::uint64_t cpu = reinterpret_cast(slot(heap.p, 9))(heap.p); - const std::uint64_t gpu = reinterpret_cast(slot(heap.p, 10))(heap.p); - const UINT step = device->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV); - EXPECT(cpu && gpu >= 0x10000 && gpu < (1ull << 32) && step == 32); // the shaders step 32 bytes a slot - const auto handle = [&](UINT i) { return D3D12_CPU_DESCRIPTOR_HANDLE{SIZE_T(cpu + std::uint64_t(i) * step)}; }; - const auto make = [&](UINT i, Buf which, const D3D12_UNORDERED_ACCESS_VIEW_DESC& view, ID3D12Resource* counter_res = nullptr) { - device->CreateUnorderedAccessView(buf[which].p, counter_res, &view, handle(i)); - }; - make(0, out0, buffer_view(DXGI_FORMAT_R32_UINT, 0, out0_elements, 0)); - make(1, out1, buffer_view(DXGI_FORMAT_R16G16B16A16_FLOAT, 0, lanes, 0)); - make(2, out2, buffer_view(DXGI_FORMAT_R8G8B8A8_UNORM, out2_first, lanes, 0)); - make(3, out3, buffer_view(DXGI_FORMAT_R32G32B32A32_UINT, 0, lanes, 0)); - make(4, in4, buffer_view(DXGI_FORMAT_R32_FLOAT, 0, in4_elements, 0)); - make(5, out5, buffer_view(DXGI_FORMAT_R32_SINT, 0, lanes, 0)); - make(6, records, buffer_view(DXGI_FORMAT_UNKNOWN, 0, lanes, 8, counter_offset), buf[counter].p); - make(7, consumed_out, buffer_view(DXGI_FORMAT_R32_TYPELESS, 0, consumed * 2, 0, 0, D3D12_BUFFER_UAV_FLAG_RAW)); - - // The V#s the shaders load: format code, element size as stride, element count, OOB_SELECT 1 (structured); the - // R8G8B8A8 view starts 16 elements in; the counter V# is raw (stride 0, 4 bytes, OOB_SELECT 3) in the slot's upper half. - const auto at = [&](UINT i) { return reinterpret_cast(handle(i).ptr); }; - const auto expect_typed = [&](UINT i, Buf which, UINT code, UINT bytes, UINT elements, UINT first) { - const Vsharp v = vsharp(at(i)); - return v.address == buf[which]->GetGPUVirtualAddress() + UINT64(first) * bytes && v.stride == bytes && - v.records == elements && v.format == code && v.oob == 1; - }; - EXPECT(expect_typed(0, out0, 20, 4, out0_elements, 0)); // GFX10_FORMAT_32_UINT - EXPECT(expect_typed(1, out1, 71, 8, lanes, 0)); // 16_16_16_16_FLOAT - EXPECT(expect_typed(2, out2, 56, 4, lanes, out2_first)); // 8_8_8_8_UNORM - EXPECT(expect_typed(3, out3, 75, 16, lanes, 0)); // 32_32_32_32_UINT - EXPECT(expect_typed(4, in4, 22, 4, in4_elements, 0)); // 32_FLOAT - EXPECT(expect_typed(5, out5, 21, 4, lanes, 0)); // 32_SINT - { - const Vsharp v = vsharp(at(6)), c = vsharp(at(6), 4); - EXPECT(v.address == buf[records]->GetGPUVirtualAddress() && v.stride == 8 && v.records == lanes && v.format == 0 && - v.oob == 0); - EXPECT(c.address == buf[counter]->GetGPUVirtualAddress() + counter_offset && c.stride == 0 && c.records == 4 && - c.format == 0 && c.oob == 3); - const Vsharp r = vsharp(at(7)); - EXPECT(r.address == buf[consumed_out]->GetGPUVirtualAddress() && r.stride == 0 && r.records == consumed * 8 && - r.oob == 3); - // A view with no counter leaves the slot's upper half zero. - const Vsharp none = vsharp(at(7), 4); - EXPECT(!none.address && !none.records); - } - - D3D12_COMMAND_QUEUE_DESC queue_desc{}; - queue_desc.Type = D3D12_COMMAND_LIST_TYPE_DIRECT; - Ref queue; - EXPECT(SUCCEEDED(device->CreateCommandQueue(&queue_desc, IID_PPV_ARGS(&queue.p)))); - Ref allocator; - Ref list; - Ref fence; - EXPECT(SUCCEEDED(device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&allocator.p)))); - EXPECT(SUCCEEDED(device->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, allocator.p, nullptr, - IID_PPV_ARGS(&list.p)))); - EXPECT(SUCCEEDED(device->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&fence.p)))); - - constexpr auto uav_state = D3D12_RESOURCE_STATE_UNORDERED_ACCESS; - for (int i = 0; i < buffer_count; ++i) list->CopyBufferRegion(buf[i].p, 0, upload.p, slice(Buf(i)), sizes[i]); - D3D12_RESOURCE_BARRIER barriers[buffer_count]; - for (int i = 0; i < buffer_count; ++i) barriers[i] = transition(buf[i].p, D3D12_RESOURCE_STATE_COPY_DEST, uav_state); - list->ResourceBarrier(buffer_count, barriers); - ID3D12DescriptorHeap* heaps[] = {heap.p}; - list->SetDescriptorHeaps(1, heaps); - list->SetComputeRootSignature(root.p); - const auto constants = [&](std::uint32_t a, std::uint32_t b) { - const std::uint32_t values[4] = {a, b, 0, 0}; - list->SetComputeRoot32BitConstants(0, 4, values, 0); - }; - list->SetPipelineState(pso_typed.p); - constants(seed, multiplier); - list->SetComputeRootDescriptorTable(1, D3D12_GPU_DESCRIPTOR_HANDLE{gpu}); - list->Dispatch(lanes / 64, 1, 1); - list->SetPipelineState(pso_counter.p); - constants(0, 0); // append - list->SetComputeRootDescriptorTable(1, D3D12_GPU_DESCRIPTOR_HANDLE{gpu + 6ull * step}); - list->Dispatch(lanes / 64, 1, 1); - D3D12_RESOURCE_BARRIER sync[2] = {uav_barrier(buf[records].p), uav_barrier(buf[counter].p)}; - list->ResourceBarrier(2, sync); - // CopyStructureCount: the counter's 4 bytes into a buffer, after the append. - D3D12_RESOURCE_BARRIER to_copy = transition(buf[counter].p, uav_state, D3D12_RESOURCE_STATE_COPY_SOURCE); - list->ResourceBarrier(1, &to_copy); - list->CopyBufferRegion(readback.p, count_after_append, buf[counter].p, counter_offset, 4); - D3D12_RESOURCE_BARRIER back = transition(buf[counter].p, D3D12_RESOURCE_STATE_COPY_SOURCE, uav_state); - list->ResourceBarrier(1, &back); - constants(1, 0); // consume - list->Dispatch(consumed / 64, 1, 1); - for (int i = 0; i < buffer_count; ++i) barriers[i] = transition(buf[i].p, uav_state, D3D12_RESOURCE_STATE_COPY_SOURCE); - list->ResourceBarrier(buffer_count, barriers); - for (int i = 0; i < buffer_count; ++i) list->CopyBufferRegion(readback.p, slice(Buf(i)), buf[i].p, 0, sizes[i]); - list->CopyBufferRegion(readback.p, count_after_consume, buf[counter].p, counter_offset, 4); - EXPECT(list->Close() == S_OK); - ID3D12CommandList* lists[] = {list.p}; - queue->ExecuteCommandLists(1, lists); - EXPECT(rt::d3d12::last_execute_result(queue.p) == leonida::ReplayResult::success); - EXPECT(SUCCEEDED(queue->Signal(fence.p, 1))); - const HANDLE event = CreateEventW(nullptr, FALSE, FALSE, nullptr); - EXPECT(event != nullptr); - EXPECT(SUCCEEDED(fence->SetEventOnCompletion(1, event))); - if (WaitForSingleObject(event, 20000) != WAIT_OBJECT_0) { - std::fprintf(stderr, "the fence never reached 1\n"); - return 1; - } - CloseHandle(event); - - std::vector got; - { - void* mapped = nullptr; - EXPECT(SUCCEEDED(readback->Map(0, nullptr, &mapped))); - got.assign(static_cast(mapped), static_cast(mapped) + readback_bytes); - readback->Unmap(0, nullptr); - } - const auto word_at = [&](UINT64 offset) { - std::uint32_t value = 0; - std::memcpy(&value, got.data() + offset, 4); - return value; - }; - - unsigned mismatches = 0; - const auto compare = [&](const char* what, Buf which, const std::vector& expected) { - unsigned bad = 0; - for (std::size_t i = 0; i < expected.size(); ++i) { - ++words_checked; - const std::uint32_t value = word_at(slice(which) + i * 4); - if (value == expected[i]) continue; - ++mismatches; - if (bad++ < 4) std::fprintf(stderr, "%s word %zu: got %08x want %08x\n", what, i, value, expected[i]); - } - if (bad) std::fprintf(stderr, "%s: %u of %zu words differ\n", what, bad, expected.size()); - }; - compare("R32_UINT store + atomic add (240 of 256 elements)", out0, want.words[out0]); - compare("R16G16B16A16_FLOAT store", out1, want.words[out1]); - compare("R8G8B8A8_UNORM store (FirstElement 16)", out2, want.words[out2]); - compare("R32G32B32A32_UINT store", out3, want.words[out3]); - compare("R32_FLOAT input untouched", in4, want.words[in4]); - compare("R32_FLOAT load -> R32_SINT store (250 of 256 loads in range)", out5, want.words[out5]); - - // The counter: 256 after the append, 128 after the consume, and nothing else of its buffer touched. - ++words_checked; - if (word_at(count_after_append) != lanes) { - std::fprintf(stderr, "counter after the append: %u, want %u\n", word_at(count_after_append), lanes); - ++mismatches; - } - ++words_checked; - if (word_at(count_after_consume) != lanes - consumed) { - std::fprintf(stderr, "counter after the consume: %u, want %u\n", word_at(count_after_consume), lanes - consumed); - ++mismatches; - } - for (UINT64 i = 0; i < counter_buffer_bytes / 4; ++i) { - ++words_checked; - const std::uint32_t expected = i == counter_offset / 4 ? lanes - consumed : sentinel; - if (word_at(slice(counter) + i * 4) != expected && mismatches++ < 12) - std::fprintf(stderr, "counter buffer word %llu: got %08x want %08x\n", static_cast(i), - word_at(slice(counter) + i * 4), expected); - } - // The appended records: every g exactly once with its second field, in whatever order the lanes took the counter. - std::vector> appended, taken; - for (UINT i = 0; i < lanes; ++i) - appended.push_back({word_at(slice(records) + i * 8), word_at(slice(records) + i * 8 + 4)}); - std::vector> sorted = appended; - std::sort(sorted.begin(), sorted.end()); - for (UINT i = 0; i < lanes; ++i) { - ++words_checked; - if (sorted[i][0] != i || sorted[i][1] != i * 3 + 1) { - if (mismatches++ < 12) - std::fprintf(stderr, "appended record %u (sorted): { %u, %u }, want { %u, %u }\n", i, sorted[i][0], - sorted[i][1], i, i * 3 + 1); - } - } - // The consumed ones: the records at indices 128..255 (the counter went from 256 down to 128), each once. - for (UINT i = 0; i < consumed; ++i) - taken.push_back({word_at(slice(consumed_out) + i * 8), word_at(slice(consumed_out) + i * 8 + 4)}); - std::vector> tail(appended.begin() + (lanes - consumed), appended.end()); - std::sort(taken.begin(), taken.end()); - std::sort(tail.begin(), tail.end()); - for (UINT i = 0; i < consumed; ++i) { - ++words_checked; - if (taken[i] != tail[i] && mismatches++ < 12) - std::fprintf(stderr, "consumed record %u (sorted): { %u, %u }, want { %u, %u }\n", i, taken[i][0], taken[i][1], - tail[i][0], tail[i][1]); - } - EXPECT(!mismatches); - - for (auto& b : buf) b.reset(); - upload.reset(); readback.reset(); list.reset(); allocator.reset(); fence.reset(); queue.reset(); - pso_typed.reset(); pso_counter.reset(); root.reset(); heap.reset(); - EXPECT(rt::d3d12_xs::device_proxy_ref_count(device.p) == 1); - return 0; -} - -// ---- part 2 ----------------------------------------------------------------------------------------------------- - -struct ClearCase { - DXGI_FORMAT format; - VkFormat vulkan; // for the model - bool is_float; - std::array values; - UINT64 byte_offset; - UINT elements; -}; -std::uint32_t fb(float f) { return std::bit_cast(f); } - -// Values in the domain D3D12 defines the same on every driver: no exact .5 ties in a float -> UNORM rounding (the RTX 5070's -// D3D12 rounds 127.5 down, the layer and the spec's round-to-nearest up) and no integer wider than its channel (the low bits -// are kept here, one vendor clamps). -const ClearCase clear_cases[] = { - {DXGI_FORMAT_R32_UINT, VK_FORMAT_R32_UINT, false, {0x12345678, 0, 0, 0}, 0, 16}, - {DXGI_FORMAT_R32_SINT, VK_FORMAT_R32_SINT, false, {0xfffffff0, 0, 0, 0}, 256, 8}, - {DXGI_FORMAT_R32_FLOAT, VK_FORMAT_R32_SFLOAT, true, {fb(1.5f), 0, 0, 0}, 512, 8}, - {DXGI_FORMAT_R16G16B16A16_FLOAT, VK_FORMAT_R16G16B16A16_SFLOAT, true, {fb(1.0f), fb(0.5f), fb(-2.0f), fb(0.25f)}, 768, 8}, - {DXGI_FORMAT_R8G8B8A8_UNORM, VK_FORMAT_R8G8B8A8_UNORM, true, {fb(1.0f), fb(0.4f), fb(0.2f), fb(2.0f)}, 1024, 16}, - {DXGI_FORMAT_R8G8B8A8_UINT, VK_FORMAT_R8G8B8A8_UINT, false, {0xf1, 2, 3, 0x80}, 1280, 16}, - {DXGI_FORMAT_R32G32B32A32_UINT, VK_FORMAT_R32G32B32A32_UINT, false, {1, 2, 3, 4}, 1536, 4}, - {DXGI_FORMAT_R16_UNORM, VK_FORMAT_R16_UNORM, true, {fb(0.25f), 0, 0, 0}, 1792, 16}, - {DXGI_FORMAT_R8_UNORM, VK_FORMAT_R8_UNORM, true, {fb(0.2f), 0, 0, 0}, 2048, 21}, // ends off a word boundary - {DXGI_FORMAT_R10G10B10A2_UNORM, VK_FORMAT_A2B10G10R10_UNORM_PACK32, true, {fb(0.25f), fb(0.4f), fb(0.75f), fb(1.0f)}, 2304, 8}, - {DXGI_FORMAT_R11G11B10_FLOAT, VK_FORMAT_B10G11R11_UFLOAT_PACK32, true, {fb(1.0f), fb(2.0f), fb(0.5f), 0}, 2560, 8}, - {DXGI_FORMAT_R16G16_FLOAT, VK_FORMAT_R16G16_SFLOAT, true, {fb(1.5f), fb(-0.5f), 0, 0}, 2816, 8}, - {DXGI_FORMAT_R8G8_UINT, VK_FORMAT_R8G8_UINT, false, {0xaa, 0xbb, 0, 0}, 3072, 10}, -}; -constexpr UINT64 api_data_bytes = 4096, api_records_bytes = 4096; -constexpr UINT api_readback = api_data_bytes + api_records_bytes + counter_buffer_bytes; - -// The same scenario on `device`: bytes read back, or empty on failure. host: a real heap pair (a non-shader-visible one the -// views are made in, a shader-visible one the clear's GPU handle comes from), as the PC runtime wants; the layer takes the -// CPU handle and ignores the GPU one. -bool run_api(ID3D12Device* device, bool host, std::vector& out, std::vector& supported_by_host) { - const D3D12_HEAP_PROPERTIES default_heap{D3D12_HEAP_TYPE_DEFAULT}, upload_heap{D3D12_HEAP_TYPE_UPLOAD}, - readback_heap{D3D12_HEAP_TYPE_READBACK}; - const auto create = [&](Ref& r, const D3D12_HEAP_PROPERTIES& heap, UINT64 bytes, - D3D12_RESOURCE_FLAGS flags, D3D12_RESOURCE_STATES state) { - const auto desc = buffer_desc(bytes, flags); - return SUCCEEDED(device->CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &desc, state, nullptr, - IID_PPV_ARGS(&r.p))); - }; - constexpr auto uav_flag = D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS; - Ref data, structured, counter_buffer, upload, readback; - if (!create(data, default_heap, api_data_bytes, uav_flag, D3D12_RESOURCE_STATE_UNORDERED_ACCESS) || - !create(structured, default_heap, api_records_bytes, uav_flag, D3D12_RESOURCE_STATE_COPY_DEST) || - !create(counter_buffer, default_heap, counter_buffer_bytes, uav_flag, D3D12_RESOURCE_STATE_COPY_DEST) || - !create(upload, upload_heap, api_records_bytes + counter_buffer_bytes, D3D12_RESOURCE_FLAG_NONE, - D3D12_RESOURCE_STATE_GENERIC_READ) || - !create(readback, readback_heap, api_readback, D3D12_RESOURCE_FLAG_NONE, D3D12_RESOURCE_STATE_COPY_DEST)) - return std::fprintf(stderr, "resource creation failed\n"), false; - { - std::uint8_t* mapped = nullptr; - if (FAILED(upload->Map(0, nullptr, reinterpret_cast(&mapped)))) return std::fprintf(stderr, "run_api: line %d\n", __LINE__), false; - std::memset(mapped, 0x11, api_records_bytes + counter_buffer_bytes); - const std::uint32_t seven = 7; - std::memcpy(mapped + api_records_bytes + counter_offset, &seven, 4); // the counter's word - upload->Unmap(0, nullptr); - } - constexpr UINT slots = 24; - Ref cpu_heap, gpu_heap; - D3D12_DESCRIPTOR_HEAP_DESC desc{D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, slots, D3D12_DESCRIPTOR_HEAP_FLAG_NONE, 0}; - if (FAILED(device->CreateDescriptorHeap(&desc, IID_PPV_ARGS(&cpu_heap.p)))) return std::fprintf(stderr, "run_api: line %d\n", __LINE__), false; - if (host) { - desc.Flags = D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE; - if (FAILED(device->CreateDescriptorHeap(&desc, IID_PPV_ARGS(&gpu_heap.p)))) return std::fprintf(stderr, "run_api: line %d\n", __LINE__), false; - } - const UINT step = device->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV); - const auto cpu = [&](UINT i) { - D3D12_CPU_DESCRIPTOR_HANDLE h = cpu_heap->GetCPUDescriptorHandleForHeapStart(); - h.ptr += SIZE_T(i) * step; - return h; - }; - const auto gpu = [&](UINT i) { - if (!host) return D3D12_GPU_DESCRIPTOR_HANDLE{0}; - D3D12_GPU_DESCRIPTOR_HANDLE h = gpu_heap->GetGPUDescriptorHandleForHeapStart(); - h.ptr += UINT64(i) * step; - return h; - }; - UINT next_slot = 0; - const auto make = [&](ID3D12Resource* resource, ID3D12Resource* counter, const D3D12_UNORDERED_ACCESS_VIEW_DESC& view) { - const UINT i = next_slot++; - device->CreateUnorderedAccessView(resource, counter, &view, cpu(i)); - if (host) { - D3D12_CPU_DESCRIPTOR_HANDLE visible = gpu_heap->GetCPUDescriptorHandleForHeapStart(); - visible.ptr += SIZE_T(i) * step; - device->CopyDescriptorsSimple(1, visible, cpu(i), D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV); - } - return i; - }; - - Ref queue; - Ref allocator; - Ref list; - Ref fence; - const D3D12_COMMAND_QUEUE_DESC queue_desc{D3D12_COMMAND_LIST_TYPE_DIRECT}; - if (FAILED(device->CreateCommandQueue(&queue_desc, IID_PPV_ARGS(&queue.p))) || - FAILED(device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&allocator.p))) || - FAILED(device->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, allocator.p, nullptr, IID_PPV_ARGS(&list.p))) || - FAILED(device->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&fence.p)))) - return std::fprintf(stderr, "run_api: line %d\n", __LINE__), false; - ID3D12DescriptorHeap* heaps[] = {gpu_heap.p}; - if (host) list->SetDescriptorHeaps(1, heaps); - - const auto clear = [&](UINT slot_index, ID3D12Resource* resource, bool is_float, const std::array& v) { - if (is_float) { - const float f[4] = {std::bit_cast(v[0]), std::bit_cast(v[1]), std::bit_cast(v[2]), - std::bit_cast(v[3])}; - list->ClearUnorderedAccessViewFloat(gpu(slot_index), cpu(slot_index), resource, f, 0, nullptr); - } else { - list->ClearUnorderedAccessViewUint(gpu(slot_index), cpu(slot_index), resource, v.data(), 0, nullptr); - } - const D3D12_RESOURCE_BARRIER barrier = uav_barrier(resource); - list->ResourceBarrier(1, &barrier); - }; - // The whole buffer 0xcdcdcdcd through a raw view, then each case's elements through a typed view. - clear(make(data.p, nullptr, buffer_view(DXGI_FORMAT_R32_TYPELESS, 0, api_data_bytes / 4, 0, 0, D3D12_BUFFER_UAV_FLAG_RAW)), - data.p, false, {0xcdcdcdcd, 0, 0, 0}); - supported_by_host.assign(std::size(clear_cases), true); - for (std::size_t c = 0; c < std::size(clear_cases); ++c) { - const ClearCase& test = clear_cases[c]; - if (host) { - D3D12_FEATURE_DATA_FORMAT_SUPPORT support{test.format}; - supported_by_host[c] = SUCCEEDED(device->CheckFeatureSupport(D3D12_FEATURE_FORMAT_SUPPORT, &support, sizeof(support))) && - (support.Support2 & D3D12_FORMAT_SUPPORT2_UAV_TYPED_STORE); - } - if (!supported_by_host[c]) continue; - const UINT size = uc::layout(test.vulkan)->bytes; - clear(make(data.p, nullptr, buffer_view(test.format, test.byte_offset / size, test.elements, 0)), data.p, - test.is_float, test.values); - } - // A structured view with a counter. The clear writes the records and leaves the counter (preset to 7) alone ... - list->CopyBufferRegion(structured.p, 0, upload.p, 0, api_records_bytes); - list->CopyBufferRegion(counter_buffer.p, 0, upload.p, api_records_bytes, counter_buffer_bytes); - D3D12_RESOURCE_BARRIER to_uav[2] = {transition(structured.p, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_UNORDERED_ACCESS), - transition(counter_buffer.p, D3D12_RESOURCE_STATE_COPY_DEST, - D3D12_RESOURCE_STATE_UNORDERED_ACCESS)}; - list->ResourceBarrier(2, to_uav); - clear(make(structured.p, counter_buffer.p, buffer_view(DXGI_FORMAT_UNKNOWN, 0, 256, 16, counter_offset)), structured.p, - false, {0xab, 0xcd, 0xef, 0x01}); - // ... and a raw view of the counter's own word (element 1024) clears it, as a game resets its counter. - clear(make(counter_buffer.p, nullptr, buffer_view(DXGI_FORMAT_R32_TYPELESS, counter_offset / 4, 1, 0, 0, D3D12_BUFFER_UAV_FLAG_RAW)), - counter_buffer.p, false, {3, 0, 0, 0}); - D3D12_RESOURCE_BARRIER to_copy[3] = { - transition(data.p, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_COPY_SOURCE), - transition(structured.p, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_COPY_SOURCE), - transition(counter_buffer.p, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_COPY_SOURCE)}; - list->ResourceBarrier(3, to_copy); - list->CopyBufferRegion(readback.p, 0, data.p, 0, api_data_bytes); - list->CopyBufferRegion(readback.p, api_data_bytes, structured.p, 0, api_records_bytes); - list->CopyBufferRegion(readback.p, api_data_bytes + api_records_bytes, counter_buffer.p, 0, counter_buffer_bytes); - if (const HRESULT hr = list->Close(); FAILED(hr)) return std::fprintf(stderr, "Close: %08lx\n", static_cast(hr)), false; - ID3D12CommandList* lists[] = {list.p}; - queue->ExecuteCommandLists(1, lists); - if (!host && rt::d3d12::last_execute_result(queue.p) != leonida::ReplayResult::success) - return std::fprintf(stderr, "replay result %d\n", int(rt::d3d12::last_execute_result(queue.p))), false; - if (FAILED(queue->Signal(fence.p, 1))) return std::fprintf(stderr, "run_api: line %d\n", __LINE__), false; - const HANDLE event = CreateEventW(nullptr, FALSE, FALSE, nullptr); - if (!event || FAILED(fence->SetEventOnCompletion(1, event)) || WaitForSingleObject(event, 20000) != WAIT_OBJECT_0) - return std::fprintf(stderr, "run_api: line %d\n", __LINE__), false; - CloseHandle(event); - void* mapped = nullptr; - if (FAILED(readback->Map(0, nullptr, &mapped))) return std::fprintf(stderr, "run_api: line %d\n", __LINE__), false; - out.assign(static_cast(mapped), static_cast(mapped) + api_readback); - readback->Unmap(0, nullptr); - return true; -} - -// What D3D12 says the same sequence leaves, from uav_clear.h: the model for a run with no host runtime to compare with. -std::vector model(const std::vector& supported) { - std::vector bytes(api_readback, 0x11); - std::fill(bytes.begin(), bytes.begin() + api_data_bytes, std::uint8_t(0xcd)); - for (std::size_t c = 0; c < std::size(clear_cases); ++c) { - const ClearCase& test = clear_cases[c]; - uc::Element e{}; - if (!supported[c] || !uc::encode(test.vulkan, test.is_float, test.values, e)) continue; - for (UINT64 i = 0; i < UINT64(test.elements) * e.size; ++i) bytes[test.byte_offset + i] = e.bytes[i % e.size]; - } - // A structured view clears every 32-bit word to the first value (D3D12 ignores the other three). - for (UINT64 i = 0; i < api_records_bytes; ++i) bytes[api_data_bytes + i] = i % 4 == 0 ? 0xab : 0; - const std::uint32_t three = 3; - std::memcpy(bytes.data() + api_data_bytes + api_records_bytes + counter_offset, &three, 4); - return bytes; -} - -} // namespace - -int main() { - vktest::Device d; - const auto device_status = d.initialize(); - if (device_status == vktest::DeviceStatus::unavailable) return 77; // no Vulkan GPU: ctest skips - if (device_status != vktest::DeviceStatus::ready) return 1; - if (!d.bindless) { - std::printf("SKIP: the device lacks the descriptor indexing features of the bindless set 0\n"); - return 77; - } - const std::filesystem::path root_dir = LEONIDA_TEST_BUFFER_UAV_DIR; - - unsigned words = 0; - if (const int status = run_shaders(d, root_dir, words)) return status; - - // Part 2: the layer's device and the host's on the same adapter. - std::vector ours, host_bytes; - std::vector supported; - { - rt::d3d12::VulkanDeviceInfo info{}; - info.get_instance_proc = d.instance_proc; - info.instance = d.instance; - info.physical = d.physical; - info.device = d.device; - info.queue = d.queue; - info.queue_family = d.family; - info.buffer_device_address = true; // the V# holds the buffer's address - Ref device; - EXPECT(SUCCEEDED(rt::d3d12::create_vulkan_device(info, IID_PPV_ARGS(&device.p)))); - EXPECT(run_api(device.p, false, ours, supported)); - } - std::string host_name = "none"; - bool compared = false; - std::uint32_t vendor = 0; - { - VkPhysicalDeviceIDProperties id{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_ID_PROPERTIES}; - VkPhysicalDeviceProperties2 properties{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROPERTIES_2, &id}; - d.instance_fn("vkGetPhysicalDeviceProperties2")(d.physical, &properties); - vendor = properties.properties.vendorID; - copycmp::Ptr host; - LUID luid{}; - std::memcpy(&luid, id.deviceLUID, sizeof(luid)); - if (id.deviceLUIDValid && copycmp::try_create_host(host, host_name, &luid)) { - std::vector host_supported; - EXPECT(run_api(host.p, true, host_bytes, host_supported)); - supported = host_supported; - compared = true; - } - } - if (!compared) { - std::printf("no host D3D12 device on the layer's adapter: the layer's bytes are compared with uav_clear.h\n"); - host_bytes = model(supported); - host_name = "the uav_clear.h model"; - } else { - // The layer ran every case; the host only those its adapter can store typed. Mask the others in both. - for (std::size_t c = 0; c < std::size(clear_cases); ++c) { - if (supported[c]) continue; - const ClearCase& test = clear_cases[c]; - const UINT size = uc::layout(test.vulkan)->bytes; - std::fill_n(ours.begin() + test.byte_offset, UINT64(test.elements) * size, std::uint8_t(0)); - std::fill_n(host_bytes.begin() + test.byte_offset, UINT64(test.elements) * size, std::uint8_t(0)); - std::printf("host adapter has no typed UAV store for DXGI format %d: that case is not compared\n", - int(test.format)); - } - // One measured host quirk, not a layer bug: Intel's D3D12 (Xe-LP, 32.0.101.7092) writes the R11G11B10_FLOAT - // clear (1.0, 2.0, 0.5) as 0x701e03c0, G = 1.0, as if the values were clamped to [0, 1]. Report it, don't - // fail, only when the host's bytes are exactly that clamped encoding. The layer and model() share - // uav_clear::encode, so the host stays the independent reference for every other format, adapter and value. - for (std::size_t c = 0; c < std::size(clear_cases); ++c) { - const ClearCase& test = clear_cases[c]; - if (vendor != 0x8086 || test.format != DXGI_FORMAT_R11G11B10_FLOAT || !supported[c] || - ours.size() != api_readback || host_bytes.size() != api_readback) continue; - std::array clamped = test.values; - for (auto& v : clamped) v = fb(std::clamp(std::bit_cast(v), 0.0f, 1.0f)); - uc::Element e{}; - if (!uc::encode(test.vulkan, true, clamped, e)) continue; - const UINT64 begin = test.byte_offset, end = begin + UINT64(test.elements) * e.size; - bool host_clamped = true; - for (UINT64 i = begin; i < end; ++i) host_clamped = host_clamped && host_bytes[i] == e.bytes[(i - begin) % e.size]; - const std::vector reference = model(supported); - if (!host_clamped || !std::equal(ours.begin() + begin, ours.begin() + end, reference.begin() + begin) || - std::equal(ours.begin() + begin, ours.begin() + end, host_bytes.begin() + begin)) continue; - UINT64 first = begin; - while (ours[first] == host_bytes[first]) ++first; - std::uint32_t host_word = 0; - std::memcpy(&host_word, host_bytes.data() + begin, 4); - std::printf("DXGI format %d: host quirk: %s writes 0x%08x, the clear clamped to [0, 1] (first differing " - "byte %llu: layer %02x, host %02x); not compared\n", int(test.format), host_name.c_str(), - host_word, static_cast(first), ours[first], host_bytes[first]); - std::copy(ours.begin() + begin, ours.begin() + end, host_bytes.begin() + begin); - } - } - EXPECT(ours.size() == api_readback && host_bytes.size() == api_readback); - unsigned differing = 0; - for (std::size_t i = 0; i < ours.size(); ++i) { - ++words; - if (ours[i] == host_bytes[i]) continue; - if (differing++ < 12) { - const char* where = i < api_data_bytes ? "typed clears" : i < api_data_bytes + api_records_bytes ? "structured clear with a counter" : "counter buffer"; - std::fprintf(stderr, "%s byte %zu: layer %02x, %s %02x\n", where, i, ours[i], host_name.c_str(), host_bytes[i]); - } - } - if (differing) { - // Say which clear case the first differing byte belongs to. - for (std::size_t c = 0; c < std::size(clear_cases); ++c) { - const ClearCase& test = clear_cases[c]; - const UINT size = uc::layout(test.vulkan)->bytes; - for (UINT64 i = 0; i < UINT64(test.elements) * size; ++i) - if (ours[test.byte_offset + i] != host_bytes[test.byte_offset + i]) { - std::fprintf(stderr, "case %zu (DXGI format %d) differs\n", c, int(test.format)); - break; - } - } - std::fprintf(stderr, "%u bytes differ\n", differing); - return 1; - } - if (d.validation_errors()) { - std::fprintf(stderr, "%u validation errors\n", d.validation_errors()); - return 1; - } - std::printf("Buffer UAVs: typed views (R32_UINT with an atomic, R16G16B16A16_FLOAT, R8G8B8A8_UNORM from FirstElement 16, " - "R32G32B32A32_UINT, R32_FLOAT loads, R32_SINT) written by a translated compute shader with NUM_RECORDS " - "as the bound, and a structured UAV with a counter at offset 4096 appended to by 256 lanes and consumed " - "by 128 (counter 256 then 128 through CopyBufferRegion) matched the CPU reference; typed-buffer and " - "counter clears matched %s: %u values compared, error 0\n", - host_name.c_str(), words); - return 0; -} diff --git a/runtime/test/d3d12_bundle_forbidden_test.cpp b/runtime/test/d3d12_bundle_forbidden_test.cpp deleted file mode 100644 index 3e3a5d133..000000000 --- a/runtime/test/d3d12_bundle_forbidden_test.cpp +++ /dev/null @@ -1,289 +0,0 @@ -// Calls a bundle may not make: what Close of the bundle and of the parent that executes it return for each, on the -// layer and on Windows' own D3D12 (no debug layer; the default adapter and WARP). One call is recorded per bundle, -// with valid arguments, on a bundle of its own; the parent direct list executes it, is closed and submitted, and the -// device's removed reason is read after the fence. A host device is created per call, so a call that removes the -// device does not touch the next one. Microsoft documents RSSetViewports, RSSetScissorRects, OMSetRenderTargets, -// ClearState and the calls below as not allowed in a bundle; the table is what the PC runtime does without the debug -// layer (every one of them fails the bundle's Close with E_FAIL, on both adapters, and executing such a bundle -// crashes the PC runtime, so the parent is only closed for bundles that closed). The layer is held to the same -// verdict for every call where both host adapters agree; its code for a refused bundle is E_INVALIDARG. -// Both host adapters always run (LEONIDA_HOST_ADAPTER is not read), except under Wine, where the host is skipped. -// No game data. -#include "vk_test_device.h" -#include "d3d12_test_shaders.h" -#include "host_wine.h" -#include "../shims/d3d12_com.h" - -#include - -#include -#include -#include -#include - -#define CHECK(condition) do { \ - if (!(condition)) { std::fprintf(stderr, "line %d: %s\n", __LINE__, #condition); return false; } \ -} while (0) - -#define REQUIRE(condition) do { \ - if (!(condition)) { std::fprintf(stderr, "line %d: %s\n", __LINE__, #condition); return 1; } \ -} while (0) - -using namespace d3d12test; - -namespace { - -constexpr HRESULT not_run = HRESULT(0x7fff0000); // no parent Close: the bundle could not be executed - -struct Env { - ID3D12Device* device = nullptr; - Ref queue; - Ref fence; - Ref target, buffer; - Ref rtv_heap; - D3D12_CPU_DESCRIPTOR_HANDLE rtv{}; - UINT64 fence_value = 0; - Ref other_allocator; // a closed bundle for ExecuteBundle inside a bundle - Ref other_bundle; - - bool init(ID3D12Device* d) { - device = d; - const D3D12_HEAP_PROPERTIES default_heap{D3D12_HEAP_TYPE_DEFAULT}; - D3D12_RESOURCE_DESC texture{}; - texture.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D; - texture.Width = texture.Height = 16; - texture.DepthOrArraySize = texture.MipLevels = 1; - texture.Format = DXGI_FORMAT_R8G8B8A8_UNORM; - texture.SampleDesc.Count = 1; - texture.Flags = D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET; - CHECK(SUCCEEDED(device->CreateCommittedResource(&default_heap, D3D12_HEAP_FLAG_NONE, &texture, - D3D12_RESOURCE_STATE_RENDER_TARGET, nullptr, - IID_PPV_ARGS(&target.p)))); - const auto desc = buffer_desc(256); - CHECK(SUCCEEDED(device->CreateCommittedResource(&default_heap, D3D12_HEAP_FLAG_NONE, &desc, - D3D12_RESOURCE_STATE_COMMON, nullptr, - IID_PPV_ARGS(&buffer.p)))); - const D3D12_DESCRIPTOR_HEAP_DESC heap_desc{D3D12_DESCRIPTOR_HEAP_TYPE_RTV, 1, D3D12_DESCRIPTOR_HEAP_FLAG_NONE, 0}; - CHECK(SUCCEEDED(device->CreateDescriptorHeap(&heap_desc, IID_PPV_ARGS(&rtv_heap.p)))); - rtv = rtv_heap->GetCPUDescriptorHandleForHeapStart(); - device->CreateRenderTargetView(target.p, nullptr, rtv); - D3D12_COMMAND_QUEUE_DESC queue_desc{}; - CHECK(SUCCEEDED(device->CreateCommandQueue(&queue_desc, IID_PPV_ARGS(&queue.p)))); - CHECK(SUCCEEDED(device->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&fence.p)))); - CHECK(SUCCEEDED(device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_BUNDLE, - IID_PPV_ARGS(&other_allocator.p)))); - CHECK(SUCCEEDED(device->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_BUNDLE, other_allocator.p, nullptr, - IID_PPV_ARGS(&other_bundle.p)))); - CHECK(SUCCEEDED(other_bundle->Close())); - return true; - } -}; - -using Recorder = std::function; - -struct Call { - const char* name; - Recorder record; -}; - -struct Outcome { - HRESULT bundle_close = E_FAIL, parent_close = not_run, removed = S_OK; - HRESULT direct_close = E_FAIL; // the same call, same arguments, on a direct list: the control -}; - -std::vector calls() { - return { - // Calls the layer did not refuse in a bundle before this test. Every call here is also valid on a direct - // list, which run_call checks as a control (none is bundle-only or meaningless there). - {"RSSetViewports", [](Env&, ID3D12GraphicsCommandList* b) { - const D3D12_VIEWPORT viewport{0, 0, 16, 16, 0, 1}; - b->RSSetViewports(1, &viewport); }}, - {"RSSetScissorRects", [](Env&, ID3D12GraphicsCommandList* b) { - const D3D12_RECT scissor{0, 0, 16, 16}; - b->RSSetScissorRects(1, &scissor); }}, - {"OMSetRenderTargets", [](Env& e, ID3D12GraphicsCommandList* b) { - b->OMSetRenderTargets(1, &e.rtv, FALSE, nullptr); }}, - {"ClearState", [](Env&, ID3D12GraphicsCommandList* b) { b->ClearState(nullptr); }}, - // Controls: calls the layer already refuses in a bundle. - {"ResourceBarrier", [](Env& e, ID3D12GraphicsCommandList* b) { - const auto barrier = transition(e.target.p, D3D12_RESOURCE_STATE_RENDER_TARGET, - D3D12_RESOURCE_STATE_COPY_SOURCE); - b->ResourceBarrier(1, &barrier); }}, - {"ClearRenderTargetView", [](Env& e, ID3D12GraphicsCommandList* b) { - const FLOAT color[4] = {0, 1, 0, 1}; - b->ClearRenderTargetView(e.rtv, color, 0, nullptr); }}, - {"SetPredication(null)", [](Env&, ID3D12GraphicsCommandList* b) { - b->SetPredication(nullptr, 0, D3D12_PREDICATION_OP_EQUAL_ZERO); }}, - {"ExecuteBundle", [](Env& e, ID3D12GraphicsCommandList* b) { b->ExecuteBundle(e.other_bundle.p); }}, - // Controls: calls a bundle may make. - {"OMSetStencilRef", [](Env&, ID3D12GraphicsCommandList* b) { b->OMSetStencilRef(1); }}, - {"OMSetBlendFactor", [](Env&, ID3D12GraphicsCommandList* b) { - const FLOAT factor[4] = {1, 1, 1, 1}; - b->OMSetBlendFactor(factor); }}, - }; -} - -// One call on one bundle, executed by a parent list, on `device` (its own for a host). -bool run_call(Env& env, const Call& call, Outcome& out) { - ID3D12Device* device = env.device; - Ref bundle_allocator, allocator; - Ref bundle, list; - CHECK(SUCCEEDED(device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_BUNDLE, IID_PPV_ARGS(&bundle_allocator.p)))); - CHECK(SUCCEEDED(device->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_BUNDLE, bundle_allocator.p, nullptr, - IID_PPV_ARGS(&bundle.p)))); - // The control: the call is valid, so its refusal in a bundle comes from the bundle rule and not its arguments. - { - Ref direct_allocator; - Ref direct; - CHECK(SUCCEEDED(device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, - IID_PPV_ARGS(&direct_allocator.p)))); - CHECK(SUCCEEDED(device->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, direct_allocator.p, nullptr, - IID_PPV_ARGS(&direct.p)))); - call.record(env, direct.p); - out.direct_close = direct->Close(); - } - call.record(env, bundle.p); - out.bundle_close = bundle->Close(); - // Executing a bundle whose Close failed crashes the PC runtime (measured), so the parent is left out then. - if (FAILED(out.bundle_close)) return true; - CHECK(SUCCEEDED(device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&allocator.p)))); - CHECK(SUCCEEDED(device->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, allocator.p, nullptr, - IID_PPV_ARGS(&list.p)))); - list->ExecuteBundle(bundle.p); - out.parent_close = list->Close(); - if (SUCCEEDED(out.parent_close)) { - ID3D12CommandList* lists[] = {list.p}; - env.queue->ExecuteCommandLists(1, lists); - // A device that is removed here makes the wait fail; GetDeviceRemovedReason below reports it. - if (SUCCEEDED(env.queue->Signal(env.fence.p, ++env.fence_value))) - env.fence->SetEventOnCompletion(env.fence_value, nullptr); - } - out.removed = device->GetDeviceRemovedReason(); - return true; -} - -struct Run { - const char* name = ""; - bool ran = false; - std::vector outcomes; -}; - -} // namespace - -int main() { - std::setvbuf(stdout, nullptr, _IONBF, 0); - vktest::Device vk; - const auto device_status = vk.initialize(); - if (device_status == vktest::DeviceStatus::unavailable) { - std::fprintf(stderr, "SKIP: no usable Vulkan 1.3 device\n"); - return 77; - } - REQUIRE(device_status == vktest::DeviceStatus::ready); - const auto list = calls(); - const unsigned errors_before = vk.validation_errors(); - - Run layer; - layer.name = "layer"; - { - rt::d3d12::VulkanDeviceInfo info{}; - info.get_instance_proc = vk.instance_proc; - info.instance = vk.instance; - info.physical = vk.physical; - info.device = vk.device; - info.queue = vk.queue; - info.queue_family = vk.family; - info.buffer_device_address = true; - Ref ours; - REQUIRE(SUCCEEDED(rt::d3d12::create_vulkan_device(info, IID_PPV_ARGS(&ours.p)))); - Env env; - REQUIRE(env.init(ours.p)); - for (const Call& call : list) { - layer.outcomes.emplace_back(); - REQUIRE(run_call(env, call, layer.outcomes.back())); - } - layer.ran = true; - } - - Run hosts[2]; - hosts[0].name = "default adapter"; - hosts[1].name = "WARP"; - if (hostwine::host_is_wine()) { - // Wine's vkd3d answers differently; the host is not compared. - } else { - Ref factory; - REQUIRE(SUCCEEDED(CreateDXGIFactory1(IID_PPV_ARGS(&factory.p)))); - for (int i = 0; i < 2; ++i) { - bool usable = true; - for (const Call& call : list) { - Ref adapter; - Ref host; - if (i == 1 && FAILED(factory->EnumWarpAdapter(IID_PPV_ARGS(&adapter.p)))) usable = false; - if (!usable || FAILED(D3D12CreateDevice(adapter.p, D3D_FEATURE_LEVEL_11_0, IID_PPV_ARGS(&host.p)))) { - usable = false; - break; - } - Env env; - REQUIRE(env.init(host.p)); - hosts[i].outcomes.emplace_back(); - REQUIRE(run_call(env, call, hosts[i].outcomes.back())); - } - hosts[i].ran = usable; - } - } - - // The layer's bundle Close must match the host's wherever the adapters that ran agree; where the two differ the - // case is reported and not compared. The direct-list control must succeed everywhere. - const auto text = [](HRESULT hr) { - char out[16]; - if (hr == not_run) return std::string("n/a"); - std::snprintf(out, sizeof(out), "0x%08lx", static_cast(hr)); - return std::string(out); - }; - unsigned failures = 0, compared = 0, disagreed = 0; - std::printf("%-24s | %-26s | %-26s | %-26s\n", "call (bundle/parent/removed)", "layer", hosts[0].name, hosts[1].name); - for (std::size_t i = 0; i < list.size(); ++i) { - std::printf("%-24s", list[i].name); - const auto cell = [&](const Run& run) { - if (!run.ran) return std::printf(" | %-26s", "(not run)"); - const Outcome& o = run.outcomes[i]; - return std::printf(" | %s %s %s", text(o.bundle_close).c_str(), text(o.parent_close).c_str(), - text(o.removed).c_str()); - }; - cell(layer); - cell(hosts[0]); - cell(hosts[1]); - std::printf("\n"); - for (const Run* run : {&layer, &hosts[0], &hosts[1]}) { - if (run->ran && FAILED(run->outcomes[i].direct_close)) { - std::fprintf(stderr, "FAIL %s on %s: Close of the direct-list control is %s\n", list[i].name, - run->name, text(run->outcomes[i].direct_close).c_str()); - ++failures; - } - } - if (!hosts[0].ran && !hosts[1].ran) continue; - const Run& first = hosts[0].ran ? hosts[0] : hosts[1]; - const HRESULT a = first.outcomes[i].bundle_close; - if (hosts[0].ran && hosts[1].ran && a != hosts[1].outcomes[i].bundle_close) { - std::printf(" the default adapter and WARP disagree on %s: not compared\n", list[i].name); - ++disagreed; - continue; - } - ++compared; - // The same verdict, not the same code: a refused bundle's Close is E_FAIL on the PC runtime and E_INVALIDARG here. - if (SUCCEEDED(layer.outcomes[i].bundle_close) != SUCCEEDED(a)) { - std::fprintf(stderr, "FAIL %s: layer bundle Close %s, host %s\n", list[i].name, - text(layer.outcomes[i].bundle_close).c_str(), text(a).c_str()); - ++failures; - } - } - const unsigned validation_errors = vk.validation_errors() - errors_before; - if (validation_errors) { - std::fprintf(stderr, "%u Vulkan validation errors\n", validation_errors); - ++failures; - } - if (!hosts[0].ran && !hosts[1].ran && !hostwine::host_is_wine()) - std::fprintf(stderr, "no D3D12 reference device (default adapter or WARP)\n"); - std::printf("bundle forbidden calls: %zu on the layer, %u compared with the host, %u hosts disagree, %u failures\n", - list.size(), compared, disagreed, failures); - return failures ? 1 : 0; -} diff --git a/runtime/test/d3d12_bundle_test.cpp b/runtime/test/d3d12_bundle_test.cpp deleted file mode 100644 index 115a7d96f..000000000 --- a/runtime/test/d3d12_bundle_test.cpp +++ /dev/null @@ -1,878 +0,0 @@ -// ExecuteBundle: what a bundle's draws inherit from the list that executes it, and what the bundle hands back. -// The same scenarios run on the layer (a Vulkan device, shaders written to the translator's contract, the ones -// d3d12_draw_test uses) and on Windows' own D3D12 (HLSL from D3DCompile, the default adapter and WARP), and each -// is read back as an 8x8 grid of letters: B blue (the clear), R, G, Y the draw's colour, C a green-only write over -// the clear, K black. The expected grids are what the host produced when they were measured (docs/d3d12_vulkan.md -// section 3.2); the default adapter and WARP gave the same grid in every scenario, so the layer is held to the PC -// runtime's behaviour and each host is checked against the table too. -// Only valid bundle usage is run: a bundle never calls RSSetViewports, RSSetScissorRects, OMSetRenderTargets or any -// barrier, clear or copy, sets its root signature before any root argument and sets its topology before a draw -// (the default adapter inherits the parent's topology when it does not, WARP removes the device, so that is not -// asserted). The layer alone is also checked for the order of a bundle's commands in its parent, for the trace -// (one line per call the application made, however often the bundle runs) and for object lifetimes. -// Both host adapters always run (LEONIDA_HOST_ADAPTER is not read), except under Wine, where the host is skipped. -// No game data. -#include "test_temp_dir.h" -#include "vk_test_device.h" -#include "d3d12_test_shaders.h" -#include "host_wine.h" -#include "../shims/d3d12_com.h" -#include "../shims/d3d12_trace.h" -#include "../src/shader_library.h" - -#include -#include -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#if !defined(LEONIDA_TEST_VS_SPV) || !defined(LEONIDA_TEST_PS_SPV) -#error "LEONIDA_TEST_VS_SPV and LEONIDA_TEST_PS_SPV must name the compiled test shaders" -#endif - -#define CHECK(condition) do { \ - if (!(condition)) { std::fprintf(stderr, "line %d: %s\n", __LINE__, #condition); return false; } \ -} while (0) - -#define REQUIRE(condition) do { \ - if (!(condition)) { std::fprintf(stderr, "line %d: %s\n", __LINE__, #condition); return 1; } \ -} while (0) - -using namespace d3d12test; - -namespace { - -constexpr UINT target_px = 64; -constexpr UINT grid_cells = 8; - -struct Vertex { - float x, y; - std::uint8_t r, g, b, a; -}; - -// Upload-heap layout, in bytes. -constexpr UINT64 vb_quad = 0; // the top-left quadrant as a strip: (-1,1) (0,1) (-1,0) (0,0) -constexpr UINT64 vb_other = 64; // the same shape in the bottom-right quadrant -constexpr UINT64 ib_quad = 128; // 0 1 2 2 1 3: both triangles of the quad -constexpr UINT64 ib_half = 144; // 3 2 1: the lower-right half -constexpr UINT64 tint_red = 256; // (1, 0, 1): the red vertices stay red -constexpr UINT64 tint_green = 512; // (0, 1, 0) -constexpr UINT64 tint_yellow = 768; // (1, 1, 1) - -// An expected grid: eight rows of eight letters, rows separated by a space. -#define BLANK4 "BBBBBBBB BBBBBBBB BBBBBBBB BBBBBBBB" -#define ROWS4(row) row " " row " " row " " row - -using Recorder = std::function; - -struct Rig { - ID3D12Device* device = nullptr; - Ref root1, root2; // root2 adds a third parameter, so it is a different signature - Ref pso_a, pso_b, pso_a2; // b writes only green and alpha; a2 is a on root2 - Ref queue; - Ref fence; - Ref upload, target, readback; - Ref rtv_heap; - D3D12_CPU_DESCRIPTOR_HANDLE rtv{}; - D3D12_GPU_VIRTUAL_ADDRESS upload_va = 0; - UINT64 fence_value = 0; - bool bundle_failed = false; - std::vector> bundle_allocators; - std::vector> bundles; - - std::vector vs_code, ps_code; - - // A root signature of two parameters (constants s0 s1, a CBV) or three (and one more constant). - bool make_root(UINT count, Ref& root) { - D3D12_ROOT_PARAMETER params[3] = {}; - params[0].ParameterType = D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS; - params[0].Constants = {0, 0, 2}; - params[1].ParameterType = D3D12_ROOT_PARAMETER_TYPE_CBV; - params[1].Descriptor = {1, 0}; - params[2].ParameterType = D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS; - params[2].Constants = {2, 0, 1}; - D3D12_VERSIONED_ROOT_SIGNATURE_DESC root_desc{}; - root_desc.Version = D3D_ROOT_SIGNATURE_VERSION_1_0; - root_desc.Desc_1_0 = {count, params, 0, nullptr, D3D12_ROOT_SIGNATURE_FLAG_ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT}; - const auto blob = serialize_root_signature(root_desc); - CHECK(!blob.empty()); - CHECK(SUCCEEDED(device->CreateRootSignature(0, blob.data(), blob.size(), IID_PPV_ARGS(&root.p)))); - return true; - } - - bool make_pso(ID3D12RootSignature* root, UINT8 write_mask, Ref& pso) { - static const D3D12_INPUT_ELEMENT_DESC elements[2] = { - {"POSITION", 0, DXGI_FORMAT_R32G32_FLOAT, 0, 0, D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0}, - {"COLOR", 0, DXGI_FORMAT_R8G8B8A8_UNORM, 0, D3D12_APPEND_ALIGNED_ELEMENT, - D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0}}; - D3D12_GRAPHICS_PIPELINE_STATE_DESC desc{}; - desc.pRootSignature = root; - desc.VS = {vs_code.data(), vs_code.size()}; - desc.PS = {ps_code.data(), ps_code.size()}; - desc.BlendState.RenderTarget[0].RenderTargetWriteMask = write_mask; - desc.SampleMask = 0xffffffff; - desc.RasterizerState.FillMode = D3D12_FILL_MODE_SOLID; - desc.RasterizerState.CullMode = D3D12_CULL_MODE_NONE; - desc.RasterizerState.DepthClipEnable = TRUE; - desc.InputLayout = {elements, 2}; - desc.PrimitiveTopologyType = D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE; - desc.NumRenderTargets = 1; - desc.RTVFormats[0] = DXGI_FORMAT_R8G8B8A8_UNORM; - desc.SampleDesc.Count = 1; - CHECK(SUCCEEDED(device->CreateGraphicsPipelineState(&desc, IID_PPV_ARGS(&pso.p)))); - return true; - } - - bool init(ID3D12Device* d, const std::vector& vs, const std::vector& ps) { - device = d; - vs_code = vs; - ps_code = ps; - CHECK(make_root(2, root1) && make_root(3, root2)); - constexpr UINT8 all = D3D12_COLOR_WRITE_ENABLE_ALL; - CHECK(make_pso(root1.p, all, pso_a)); - CHECK(make_pso(root1.p, D3D12_COLOR_WRITE_ENABLE_GREEN | D3D12_COLOR_WRITE_ENABLE_ALPHA, pso_b)); - CHECK(make_pso(root2.p, all, pso_a2)); - - const D3D12_HEAP_PROPERTIES upload_heap{D3D12_HEAP_TYPE_UPLOAD}; - const D3D12_HEAP_PROPERTIES default_heap{D3D12_HEAP_TYPE_DEFAULT}; - const D3D12_HEAP_PROPERTIES readback_heap{D3D12_HEAP_TYPE_READBACK}; - auto buffer = buffer_desc(4096); - CHECK(SUCCEEDED(device->CreateCommittedResource(&upload_heap, D3D12_HEAP_FLAG_NONE, &buffer, - D3D12_RESOURCE_STATE_GENERIC_READ, nullptr, - IID_PPV_ARGS(&upload.p)))); - buffer = buffer_desc(target_px * 256); - CHECK(SUCCEEDED(device->CreateCommittedResource(&readback_heap, D3D12_HEAP_FLAG_NONE, &buffer, - D3D12_RESOURCE_STATE_COPY_DEST, nullptr, - IID_PPV_ARGS(&readback.p)))); - D3D12_RESOURCE_DESC texture{}; - texture.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D; - texture.Width = texture.Height = target_px; - texture.DepthOrArraySize = texture.MipLevels = 1; - texture.Format = DXGI_FORMAT_R8G8B8A8_UNORM; - texture.SampleDesc.Count = 1; - texture.Flags = D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET; - CHECK(SUCCEEDED(device->CreateCommittedResource(&default_heap, D3D12_HEAP_FLAG_NONE, &texture, - D3D12_RESOURCE_STATE_COMMON, nullptr, - IID_PPV_ARGS(&target.p)))); - const Vertex quad[4] = {{-1, 1, 255, 0, 0, 255}, {0, 1, 255, 0, 0, 255}, {-1, 0, 255, 0, 0, 255}, - {0, 0, 255, 0, 0, 255}}; - const Vertex other[4] = {{0, 0, 255, 0, 0, 255}, {1, 0, 255, 0, 0, 255}, {0, -1, 255, 0, 0, 255}, - {1, -1, 255, 0, 0, 255}}; - const std::uint16_t indices[6] = {0, 1, 2, 2, 1, 3}; - const float tints[3][3] = {{1, 0, 1}, {0, 1, 0}, {1, 1, 1}}; - std::uint8_t* up = nullptr; - CHECK(SUCCEEDED(upload->Map(0, nullptr, reinterpret_cast(&up)))); - std::memset(up, 0, 4096); - std::memcpy(up + vb_quad, quad, sizeof(quad)); - std::memcpy(up + vb_other, other, sizeof(other)); - std::memcpy(up + ib_quad, indices, sizeof(indices)); - const std::uint16_t half[3] = {3, 2, 1}; - std::memcpy(up + ib_half, half, sizeof(half)); - std::memcpy(up + tint_red, tints[0], sizeof(tints[0])); - std::memcpy(up + tint_green, tints[1], sizeof(tints[1])); - std::memcpy(up + tint_yellow, tints[2], sizeof(tints[2])); - upload->Unmap(0, nullptr); - upload_va = upload->GetGPUVirtualAddress(); - - const D3D12_DESCRIPTOR_HEAP_DESC heap_desc{D3D12_DESCRIPTOR_HEAP_TYPE_RTV, 1, D3D12_DESCRIPTOR_HEAP_FLAG_NONE, 0}; - CHECK(SUCCEEDED(device->CreateDescriptorHeap(&heap_desc, IID_PPV_ARGS(&rtv_heap.p)))); - rtv = rtv_heap->GetCPUDescriptorHandleForHeapStart(); - device->CreateRenderTargetView(target.p, nullptr, rtv); - D3D12_COMMAND_QUEUE_DESC queue_desc{}; - CHECK(SUCCEEDED(device->CreateCommandQueue(&queue_desc, IID_PPV_ARGS(&queue.p)))); - CHECK(SUCCEEDED(device->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&fence.p)))); - return true; - } - - // A closed bundle created with `initial` as its pipeline state, kept alive until the rig goes. - template - ID3D12GraphicsCommandList* bundle(ID3D12PipelineState* initial, F&& record) { - bundle_allocators.emplace_back(); - bundles.emplace_back(); - if (FAILED(device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_BUNDLE, - IID_PPV_ARGS(&bundle_allocators.back().p))) || - FAILED(device->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_BUNDLE, bundle_allocators.back().p, initial, - IID_PPV_ARGS(&bundles.back().p)))) - return nullptr; - record(bundles.back().p); - if (FAILED(bundles.back()->Close())) return nullptr; - return bundles.back().p; - } - - // ExecuteBundle, unless the bundle's Close failed (reported in the output, the layer refuses such bundles). - void execute(ID3D12GraphicsCommandList* list, ID3D12GraphicsCommandList* b) { - if (b) - list->ExecuteBundle(b); - else - bundle_failed = true; - } - - // The parent's own targets, viewport and scissor: a bundle may not set them. - void targets(ID3D12GraphicsCommandList* list, float x = 0, float y = 0, float w = target_px, float h = target_px) { - const D3D12_VIEWPORT viewport{x, y, w, h, 0, 1}; - const D3D12_RECT scissor{0, 0, LONG(target_px), LONG(target_px)}; - list->OMSetRenderTargets(1, &rtv, FALSE, nullptr); - list->RSSetViewports(1, &viewport); - list->RSSetScissorRects(1, &scissor); - } - void vertices(ID3D12GraphicsCommandList* list, UINT64 offset) { - const D3D12_VERTEX_BUFFER_VIEW view{upload_va + offset, 4 * sizeof(Vertex), sizeof(Vertex)}; - list->IASetVertexBuffers(0, 1, &view); - } - void indices(ID3D12GraphicsCommandList* list, UINT64 offset) { - const D3D12_INDEX_BUFFER_VIEW view{upload_va + offset, 12, DXGI_FORMAT_R16_UINT}; - list->IASetIndexBuffer(&view); - } - void offset(ID3D12GraphicsCommandList* list, float x, float y) { - const float xy[2] = {x, y}; - list->SetGraphicsRoot32BitConstants(0, 2, xy, 0); - } - void tint(ID3D12GraphicsCommandList* list, UINT64 which) { - list->SetGraphicsRootConstantBufferView(1, upload_va + which); - } - - // Clears the target blue, runs `record` on the parent list and reads the target back as letters. - bool render(const Recorder& record, std::string& out, HRESULT& close) { - Ref allocator; - Ref list; - CHECK(SUCCEEDED(device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&allocator.p)))); - CHECK(SUCCEEDED(device->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, allocator.p, nullptr, - IID_PPV_ARGS(&list.p)))); - D3D12_RESOURCE_BARRIER to_target = transition(target.p, D3D12_RESOURCE_STATE_COMMON, - D3D12_RESOURCE_STATE_RENDER_TARGET); - list->ResourceBarrier(1, &to_target); - const FLOAT blue[4] = {0, 0, 1, 1}; - list->ClearRenderTargetView(rtv, blue, 0, nullptr); - record(*this, list.p); - D3D12_RESOURCE_BARRIER to_copy = transition(target.p, D3D12_RESOURCE_STATE_RENDER_TARGET, - D3D12_RESOURCE_STATE_COPY_SOURCE); - list->ResourceBarrier(1, &to_copy); - D3D12_TEXTURE_COPY_LOCATION dst{}, src{}; - dst.pResource = readback.p; - dst.Type = D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT; - dst.PlacedFootprint = {0, {DXGI_FORMAT_R8G8B8A8_UNORM, target_px, target_px, 1, 256}}; - src.pResource = target.p; - src.Type = D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX; - list->CopyTextureRegion(&dst, 0, 0, 0, &src, nullptr); - close = list->Close(); - if (FAILED(close)) return true; // reported by the caller - ID3D12CommandList* lists[] = {list.p}; - queue->ExecuteCommandLists(1, lists); - CHECK(SUCCEEDED(queue->Signal(fence.p, ++fence_value))); - CHECK(SUCCEEDED(fence->SetEventOnCompletion(fence_value, nullptr))); - const std::uint8_t* pixels = nullptr; - const HRESULT mapped = readback->Map(0, nullptr, const_cast(reinterpret_cast(&pixels))); - if (FAILED(mapped)) { - char text[96]; - std::snprintf(text, sizeof(text), "Map 0x%08lx, device removed 0x%08lx\n", static_cast(mapped), - static_cast(device->GetDeviceRemovedReason())); - out = text; - return true; - } - out = bundle_failed ? "bundle Close failed " : ""; - for (UINT row = 0; row < grid_cells; ++row) { - for (UINT column = 0; column < grid_cells; ++column) { - // Away from pixel centres on the quadrant diagonal (x + y = 32). - const std::uint8_t* p = pixels + (row * 8 + 3) * 256 + (column * 8 + 3) * 4; - char letter = '?'; - if (p[3] == 255) { - if (p[0] == 0 && p[1] == 0 && p[2] == 255) letter = 'B'; - else if (p[0] == 255 && p[1] == 0 && p[2] == 0) letter = 'R'; - else if (p[0] == 0 && p[1] == 255 && p[2] == 0) letter = 'G'; - else if (p[0] == 255 && p[1] == 255 && p[2] == 0) letter = 'Y'; - else if (p[0] == 0 && p[1] == 255 && p[2] == 255) letter = 'C'; - else if (p[0] == 0 && p[1] == 0 && p[2] == 0) letter = 'K'; - } - out += letter; - } - if (row + 1 < grid_cells) out += ' '; - } - readback->Unmap(0, nullptr); - return true; - } -}; - -struct Scenario { - const char* name; - Recorder record; - const char* expected; // null: print only - bool warp_oracle_only = false; // native hardware drivers may disagree with WARP about zero-count scissors -}; - -constexpr auto strip = D3D_PRIMITIVE_TOPOLOGY_TRIANGLESTRIP; -constexpr auto tlist = D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST; - -std::vector scenarios() { - std::vector s; - // The parent's state a bundle must see: targets, viewport and scissor, root signature and arguments, a vertex - // buffer and a topology. No pipeline state is set: a bundle starts with its creation one. - const auto parent_state = [](Rig& r, ID3D12GraphicsCommandList* l, D3D_PRIMITIVE_TOPOLOGY topology) { - r.targets(l); - l->SetGraphicsRootSignature(r.root1.p); - l->IASetPrimitiveTopology(topology); - r.vertices(l, vb_quad); - r.offset(l, 0, 0); - r.tint(l, tint_red); - }; - s.push_back({"inherit: a draw sees the parent's targets, viewport, root arguments and vertex buffer", - [parent_state](Rig& r, ID3D12GraphicsCommandList* l) { - auto* b = r.bundle(r.pso_a.p, [](ID3D12GraphicsCommandList* b) { - b->IASetPrimitiveTopology(strip); - b->DrawInstanced(4, 1, 0, 0); - }); - parent_state(r, l, tlist); - r.execute(l, b); - }, ROWS4("RRRRBBBB") " " BLANK4}); - s.push_back({"inherit: an indexed draw sees the parent's index buffer", - [parent_state](Rig& r, ID3D12GraphicsCommandList* l) { - auto* b = r.bundle(r.pso_a.p, [](ID3D12GraphicsCommandList* b) { - b->IASetPrimitiveTopology(tlist); - b->DrawIndexedInstanced(6, 1, 0, 0, 0); - }); - parent_state(r, l, strip); - r.indices(l, ib_quad); - r.execute(l, b); - }, ROWS4("RRRRBBBB") " " BLANK4}); - s.push_back({"inherit: a bundle that sets the same root signature keeps the parent's root arguments", - [parent_state](Rig& r, ID3D12GraphicsCommandList* l) { - auto* b = r.bundle(r.pso_a.p, [&](ID3D12GraphicsCommandList* b) { - b->SetGraphicsRootSignature(r.root1.p); - b->IASetPrimitiveTopology(strip); - b->DrawInstanced(4, 1, 0, 0); - }); - parent_state(r, l, tlist); - r.offset(l, 1, -1); - r.tint(l, tint_green); - r.execute(l, b); - }, BLANK4 " " ROWS4("BBBBGGGG")}); - s.push_back({"inherit: one bundle, executed twice with other root arguments and viewports in between", - [](Rig& r, ID3D12GraphicsCommandList* l) { - auto* b = r.bundle(r.pso_a.p, [](ID3D12GraphicsCommandList* b) { - b->IASetPrimitiveTopology(strip); - b->DrawInstanced(4, 1, 0, 0); - }); - l->SetGraphicsRootSignature(r.root1.p); - r.vertices(l, vb_quad); - r.offset(l, 0, 0); - r.targets(l, 0, 0, target_px / 2, target_px); - r.tint(l, tint_red); - r.execute(l, b); - r.targets(l, target_px / 2, 0, target_px / 2, target_px); - r.tint(l, tint_green); - r.execute(l, b); - }, ROWS4("RRBBGGBB") " " BLANK4}); - s.push_back({"pipeline state: a bundle starts with its creation one, not the parent's, and hands it back", - [parent_state](Rig& r, ID3D12GraphicsCommandList* l) { - auto* b = r.bundle(r.pso_a.p, [](ID3D12GraphicsCommandList* b) { - b->IASetPrimitiveTopology(strip); - b->DrawInstanced(4, 1, 0, 0); - }); - parent_state(r, l, tlist); - l->SetPipelineState(r.pso_b.p); - r.tint(l, tint_green); - r.execute(l, b); - r.offset(l, 1, -1); - l->DrawInstanced(4, 1, 0, 0); - }, ROWS4("GGGGBBBB") " " ROWS4("BBBBGGGG")}); - s.push_back({"hand back: a pipeline state the bundle sets", - [parent_state](Rig& r, ID3D12GraphicsCommandList* l) { - auto* b = r.bundle(r.pso_a.p, [&](ID3D12GraphicsCommandList* b) { - b->SetPipelineState(r.pso_b.p); - b->IASetPrimitiveTopology(strip); - }); - parent_state(r, l, tlist); - l->SetPipelineState(r.pso_a.p); - r.tint(l, tint_green); - r.execute(l, b); - l->DrawInstanced(4, 1, 0, 0); - }, ROWS4("CCCCBBBB") " " BLANK4}); - s.push_back({"hand back: topology", - [parent_state](Rig& r, ID3D12GraphicsCommandList* l) { - auto* b = r.bundle(r.pso_a.p, [](ID3D12GraphicsCommandList* b) { b->IASetPrimitiveTopology(strip); }); - parent_state(r, l, tlist); - r.execute(l, b); - l->DrawInstanced(4, 1, 0, 0); - }, ROWS4("RRRRBBBB") " " BLANK4}); - s.push_back({"hand back: root constants and a root CBV, after the same root signature", - [parent_state](Rig& r, ID3D12GraphicsCommandList* l) { - auto* b = r.bundle(r.pso_a.p, [&](ID3D12GraphicsCommandList* b) { - b->SetGraphicsRootSignature(r.root1.p); - b->IASetPrimitiveTopology(strip); - r.offset(b, 1, -1); - r.tint(b, tint_green); - }); - parent_state(r, l, tlist); - r.execute(l, b); - l->DrawInstanced(4, 1, 0, 0); - }, BLANK4 " " ROWS4("BBBBGGGG")}); - s.push_back({"hand back: vertex and index buffers", - [parent_state](Rig& r, ID3D12GraphicsCommandList* l) { - auto* b = r.bundle(r.pso_a.p, [&](ID3D12GraphicsCommandList* b) { - b->IASetPrimitiveTopology(tlist); - r.vertices(b, vb_other); - r.indices(b, ib_half); - }); - parent_state(r, l, strip); - r.indices(l, ib_quad); - r.execute(l, b); - l->DrawIndexedInstanced(3, 1, 0, 0, 0); - }, BLANK4 " BBBBBBBB BBBBBBBR BBBBBBRR BBBBBRRR"}); - // A different root signature: the bundle (created with pso_a2, on root2) sets it and its own arguments. The - // parent's arguments are gone afterwards and the bundle's are the parent's. - s.push_back({"root signature: a bundle sets another one; the parent continues with it and the bundle's arguments", - [parent_state](Rig& r, ID3D12GraphicsCommandList* l) { - auto* b = r.bundle(r.pso_a2.p, [&](ID3D12GraphicsCommandList* b) { - b->SetGraphicsRootSignature(r.root2.p); - b->IASetPrimitiveTopology(strip); - r.offset(b, 0, 0); - r.tint(b, tint_yellow); - const UINT extra = 0; - b->SetGraphicsRoot32BitConstants(2, 1, &extra, 0); - b->DrawInstanced(4, 1, 0, 0); - }); - parent_state(r, l, tlist); - r.offset(l, 1, -1); - r.tint(l, tint_green); - r.execute(l, b); - r.vertices(l, vb_other); - l->DrawInstanced(4, 1, 0, 0); - }, ROWS4("YYYYBBBB") " " ROWS4("BBBBYYYY")}); - s.push_back({"scissor zero: reset existing rectangles before the next draw", - [parent_state](Rig& r, ID3D12GraphicsCommandList* l) { - parent_state(r, l, strip); - l->SetPipelineState(r.pso_a.p); - l->RSSetScissorRects(0, nullptr); - l->DrawInstanced(4, 1, 0, 0); - }, BLANK4 " " BLANK4, true}); - s.push_back({"scissor zero then one: restores new rectangle for draw", - [parent_state](Rig& r, ID3D12GraphicsCommandList* l) { - parent_state(r, l, strip); - l->SetPipelineState(r.pso_a.p); - l->RSSetScissorRects(0, nullptr); - const D3D12_RECT full{0, 0, LONG(target_px), LONG(target_px)}; - l->RSSetScissorRects(1, &full); - l->DrawInstanced(4, 1, 0, 0); - }, ROWS4("RRRRBBBB") " " BLANK4}); - s.push_back({"scissor zero with non-null pointer still disables all rectangles", - [parent_state](Rig& r, ID3D12GraphicsCommandList* l) { - parent_state(r, l, strip); - l->SetPipelineState(r.pso_a.p); - const D3D12_RECT unused{0, 0, LONG(target_px), LONG(target_px)}; - l->RSSetScissorRects(0, &unused); - l->DrawInstanced(4, 1, 0, 0); - }, BLANK4 " " BLANK4, true}); - s.push_back({"scissor zero on parent suppresses inherited bundle draw", - [parent_state](Rig& r, ID3D12GraphicsCommandList* l) { - auto* b = r.bundle(r.pso_a.p, [](ID3D12GraphicsCommandList* b) { - b->IASetPrimitiveTopology(strip); - b->DrawInstanced(4, 1, 0, 0); - }); - parent_state(r, l, strip); - l->RSSetScissorRects(0, nullptr); - r.execute(l, b); - }, BLANK4 " " BLANK4, true}); - return s; -} - -} // namespace - -namespace { - -bool compile_hlsl(const char* source, const char* entry, const char* profile, std::vector& out) { - const HMODULE compiler = LoadLibraryExA("d3dcompiler_47.dll", nullptr, LOAD_LIBRARY_SEARCH_SYSTEM32); - const auto compile = compiler ? reinterpret_cast(GetProcAddress(compiler, "D3DCompile")) : nullptr; - if (!compile) return false; - ID3DBlob* blob = nullptr; - ID3DBlob* errors = nullptr; - const HRESULT hr = compile(source, std::strlen(source), "bundle.hlsl", nullptr, nullptr, entry, profile, 0, 0, - &blob, &errors); - if (FAILED(hr) && errors) std::fprintf(stderr, "%s\n", static_cast(errors->GetBufferPointer())); - if (errors) errors->Release(); - if (FAILED(hr) || !blob) return false; - const auto* p = static_cast(blob->GetBufferPointer()); - out.assign(p, p + blob->GetBufferSize()); - blob->Release(); - return true; -} - -// The same two shaders as test/glsl/vs_draw.vert and ps_draw.frag: s0, s1 offset the vertex, the root CBV tints. -constexpr char hlsl[] = - "cbuffer Offset : register(b0) { float2 offset; };\n" - "cbuffer Tint : register(b1) { float3 tint; };\n" - "struct V { float4 position : SV_Position; float4 color : COLOR; };\n" - "V vs(float2 position : POSITION, float4 color : COLOR) {\n" - " V v; v.position = float4(position + offset, 0, 1); v.color = color; return v; }\n" - "float4 ps(V v) : SV_Target { return float4(v.color.r * tint.x, tint.y, v.color.b * tint.z, 1); }\n"; - -// Runs every scenario and stores the grids; false on a harness failure. A host scenario gets a device of its own -// (`adapter`, null for the default one): a scenario that removes a host device must not hide the ones after it. -bool run_all(ID3D12Device* shared, bool own_device, IDXGIAdapter* adapter, const std::vector& vs, const std::vector& ps, - const std::vector& list, std::vector& grids, std::vector& closes) { - for (const Scenario& scenario : list) { - Rig rig; - Ref own; - if (own_device) D3D12CreateDevice(adapter, D3D_FEATURE_LEVEL_11_0, IID_PPV_ARGS(&own.p)); - ID3D12Device* device = own_device ? own.p : shared; - if (!device || !rig.init(device, vs, ps)) { - grids.push_back("device unusable\n"); - closes.push_back(E_FAIL); - continue; - } - std::string grid_text; - HRESULT close = S_OK; - if (!rig.render(scenario.record, grid_text, close)) return false; - grids.push_back(grid_text); - closes.push_back(close); - } - return true; -} - -} // namespace - -// What the layer alone can show: the order of commands in the parent, the trace, and object lifetimes. -int count_of(const std::string& text, const char* needle) { - int count = 0; - for (std::size_t at = text.find(needle); at != std::string::npos; at = text.find(needle, at + 1)) ++count; - return count; -} - -// Sends stderr (where the trace goes) to a file while it lives, with the trace on. -struct TraceCapture { - std::filesystem::path path; - int saved = -1; - explicit TraceCapture(const std::filesystem::path& file) : path(file) { - std::fflush(stderr); - std::FILE* out = std::fopen(path.string().c_str(), "wb"); - saved = _dup(2); - if (out && saved >= 0) _dup2(_fileno(out), 2); - if (out) std::fclose(out); - rt::d3d12_trace::set_enabled(true); - } - std::string finish() { - rt::d3d12_trace::set_enabled(false); - std::fflush(stderr); - if (saved >= 0) { - _dup2(saved, 2); - _close(saved); - saved = -1; - } - std::ifstream in(path, std::ios::binary); - return {std::istreambuf_iterator(in), std::istreambuf_iterator()}; - } - ~TraceCapture() { finish(); } -}; - -bool layer_checks(ID3D12Device* device, const std::vector& vs, const std::vector& ps, - const std::filesystem::path& scratch) { - constexpr UINT8 all = D3D12_COLOR_WRITE_ENABLE_ALL; - // The parent's commands hold the bundle's markers and draws where the bundle made them, between the parent's own. - { - Rig r; - CHECK(r.init(device, vs, ps)); - const auto mark = [](ID3D12GraphicsCommandList* l, const char* text) { - l->SetMarker(1, text, UINT(std::strlen(text) + 1)); - }; - auto* b = r.bundle(r.pso_a.p, [&](ID3D12GraphicsCommandList* b) { - mark(b, "b1"); - b->IASetPrimitiveTopology(strip); - b->DrawInstanced(4, 1, 0, 0); - mark(b, "b2"); - b->DrawInstanced(4, 1, 0, 0); - mark(b, "b3"); - }); - CHECK(b); - Ref allocator; - Ref parent; - CHECK(SUCCEEDED(device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&allocator.p)))); - CHECK(SUCCEEDED(device->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, allocator.p, nullptr, - IID_PPV_ARGS(&parent.p)))); - mark(parent.p, "p0"); - r.targets(parent.p); - parent.p->SetGraphicsRootSignature(r.root1.p); - r.vertices(parent.p, vb_quad); - r.offset(parent.p, 0, 0); - r.tint(parent.p, tint_red); - mark(parent.p, "p1"); - parent.p->ExecuteBundle(b); - mark(parent.p, "p2"); - std::string order; - std::vector recorded; - CHECK(rt::d3d12::recorded_commands(parent.p, recorded)); - for (const auto& command : recorded) { - if (const auto* marker = std::get_if(&command)) order += marker->label + ","; - else if (std::holds_alternative(command)) order += "draw,"; - } - if (order != "p0,p1,b1,draw,b2,draw,b3,p2,") { - std::fprintf(stderr, "bundle commands in the parent: %s\n", order.c_str()); - return false; - } - CHECK(parent->Close() == S_OK); - } - - // The trace has one line per call the application made on the bundle, however often it is executed, and none for - // the pipeline state it was created or reset with. - { - Rig r; - CHECK(r.init(device, vs, ps)); - TraceCapture capture(scratch / "trace.txt"); - auto* b = r.bundle(r.pso_a.p, [&](ID3D12GraphicsCommandList* b) { - b->SetGraphicsRootSignature(r.root1.p); - b->IASetPrimitiveTopology(strip); - b->DrawInstanced(4, 1, 0, 0); - }); - CHECK(b); - std::string grid_text; - HRESULT close = S_OK; - CHECK(r.render([&](Rig& rig, ID3D12GraphicsCommandList* l) { - rig.targets(l); - rig.vertices(l, vb_quad); - for (int i = 0; i < 3; ++i) rig.execute(l, b); - }, grid_text, close)); - CHECK(close == S_OK); - CHECK(SUCCEEDED(b->Reset(r.bundle_allocators.back().p, r.pso_a.p))); - b->SetGraphicsRootSignature(r.root1.p); - r.offset(b, 0, 0); - r.tint(b, tint_red); - b->IASetPrimitiveTopology(tlist); - b->DrawIndexedInstanced(6, 1, 0, 0, 0); - CHECK(SUCCEEDED(b->Close())); - CHECK(r.render([&](Rig& rig, ID3D12GraphicsCommandList* l) { - rig.targets(l); - rig.vertices(l, vb_quad); - rig.indices(l, ib_quad); - rig.execute(l, b); - rig.execute(l, b); - }, grid_text, close)); - CHECK(close == S_OK && grid_text == ROWS4("RRRRBBBB") " " BLANK4); - const std::string trace = capture.finish(); - const int pipeline = count_of(trace, "GraphicsCommandList::SetPipelineState called"); - const int root = count_of(trace, "GraphicsCommandList::SetGraphicsRootSignature called"); - const int draw = count_of(trace, "GraphicsCommandList::DrawInstanced called"); - const int indexed = count_of(trace, "GraphicsCommandList::DrawIndexedInstanced called"); - const int execute = count_of(trace, "GraphicsCommandList::ExecuteBundle called"); - if (pipeline != 0 || root != 2 || draw != 1 || indexed != 1 || execute != 5) { - std::fprintf(stderr, "trace lines: SetPipelineState %d, root signature %d, draw %d, indexed %d, " - "ExecuteBundle %d (expected 0, 2, 1, 1, 5)\n", pipeline, root, draw, indexed, execute); - return false; - } - } - - // A root-constant call of zero dwords is as valid in a bundle as on a direct list; a closed bundle takes no more - // state calls (they are ignored) and a draw on it makes it invalid, so a parent that executes it fails. - { - Rig r; - CHECK(r.init(device, vs, ps)); - const UINT none = 0; - auto* b = r.bundle(r.pso_a.p, [&](ID3D12GraphicsCommandList* b) { - b->SetGraphicsRootSignature(r.root1.p); - b->SetGraphicsRoot32BitConstants(0, 0, &none, 0); - b->IASetPrimitiveTopology(strip); - r.offset(b, 0, 0); - r.tint(b, tint_red); - b->DrawInstanced(4, 1, 0, 0); - }); - CHECK(b); - std::string grid_text; - HRESULT close = S_OK; - const auto run = [&](ID3D12GraphicsCommandList* bundle) { - return r.render([&](Rig& rig, ID3D12GraphicsCommandList* l) { - rig.targets(l); - rig.vertices(l, vb_quad); - rig.execute(l, bundle); - }, grid_text, close); - }; - CHECK(run(b)); - CHECK(close == S_OK && grid_text == ROWS4("RRRRBBBB") " " BLANK4); - b->IASetPrimitiveTopology(tlist); // closed: ignored, so the bundle still draws the whole quad - CHECK(run(b)); - CHECK(close == S_OK && grid_text == ROWS4("RRRRBBBB") " " BLANK4); - b->DrawInstanced(4, 1, 0, 0); // closed: invalid - CHECK(run(b)); - CHECK(close == E_INVALIDARG); - } - - // The application may release the pipeline state and root signature as soon as it has recorded them, and the - // bundle itself while a list that executed it is still open. - { - Rig r; - CHECK(r.init(device, vs, ps)); - ID3D12GraphicsCommandList* b = nullptr; - { - Ref root; - Ref pso; - CHECK(r.make_root(2, root) && r.make_pso(root.p, all, pso)); - b = r.bundle(pso.p, [&](ID3D12GraphicsCommandList* b) { - b->SetGraphicsRootSignature(root.p); - b->IASetPrimitiveTopology(strip); - r.offset(b, 0, 0); - r.tint(b, tint_red); - b->DrawInstanced(4, 1, 0, 0); - }); - } - CHECK(b); - std::string grid_text; - HRESULT close = S_OK; - bool reset_ok = false; - CHECK(r.render([&](Rig& rig, ID3D12GraphicsCommandList* l) { - rig.targets(l); - rig.vertices(l, vb_quad); - rig.execute(l, b); - }, grid_text, close)); - if (close != S_OK || grid_text != ROWS4("RRRRBBBB") " " BLANK4) { - std::fprintf(stderr, "first parent of a released bundle: Close 0x%08lx, %s\n", - static_cast(close), grid_text.c_str()); - return false; - } - CHECK(r.render([&](Rig& rig, ID3D12GraphicsCommandList* l) { - rig.targets(l); - rig.vertices(l, vb_quad); - rig.execute(l, b); - reset_ok = SUCCEEDED(rig.bundles.back()->Reset(rig.bundle_allocators.back().p, nullptr)); - rig.bundles.clear(); - rig.bundle_allocators.clear(); - rig.offset(l, 1, -1); // the bundle's root signature and pipeline state are the parent's now - l->DrawInstanced(4, 1, 0, 0); - }, grid_text, close)); - if (!reset_ok || close != S_OK || grid_text != ROWS4("RRRRBBBB") " " ROWS4("BBBBRRRR")) { - std::fprintf(stderr, "second parent, bundle released while open: Close 0x%08lx, %s\n", - static_cast(close), grid_text.c_str()); - return false; - } - } - return true; -} - -int main() { - std::setvbuf(stdout, nullptr, _IONBF, 0); - vktest::Device vk; - const auto device_status = vk.initialize(); - if (device_status == vktest::DeviceStatus::unavailable) { - std::fprintf(stderr, "SKIP: no usable Vulkan 1.3 device\n"); - return 77; - } - REQUIRE(device_status == vktest::DeviceStatus::ready); - const auto list = scenarios(); - - // Layer shaders: FSSM-shaped containers found by hash in a translator-style index. - const auto vs_program = fssm_program({0x56530101, 0xbf810000}); - const auto ps_program = fssm_program({0x50530101, 0xbf810000}); - const auto vs_container = shader_container(vs_program), ps_container = shader_container(ps_program); - const testfiles::ScratchDir scratch("leonida_bundle_test"); // removed on every way out of main - const auto& library = scratch.path(); - REQUIRE(testfiles::copy_file(LEONIDA_TEST_VS_SPV, library / "vs_draw.spv")); - REQUIRE(testfiles::copy_file(LEONIDA_TEST_PS_SPV, library / "ps_draw.spv")); - { - std::ofstream index(library / "index.json", std::ios::binary); - index << "{\"vs_draw\": {\"stage\": \"vs\", \"fssm_sha256\": \"" << leonida::sha256_hex(vs_program) - << "\", \"bindings\": [], \"push_constant_bytes\": 144, \"input_signature\": [" - "{\"semantic\": \"COLOR\", \"semantic_index\": 0, \"register\": 0, \"mask\": 15, \"rw_mask\": 15, " - "\"system_value\": 0, \"component_type\": \"float\"}, " - "{\"semantic\": \"POSITION\", \"semantic_index\": 0, \"register\": 1, \"mask\": 3, \"rw_mask\": 3, " - "\"system_value\": 0, \"component_type\": \"float\"}]},\n" - " \"ps_draw\": {\"stage\": \"ps\", \"fssm_sha256\": \"" << leonida::sha256_hex(ps_program) - << "\", \"bindings\": [], \"push_constant_bytes\": 144, \"outputs\": [0]}}"; - } - const unsigned errors_before = vk.validation_errors(); - std::vector layer_grids; - std::vector layer_closes; - { - rt::d3d12::VulkanDeviceInfo info{}; - info.get_instance_proc = vk.instance_proc; - info.instance = vk.instance; - info.physical = vk.physical; - info.device = vk.device; - info.queue = vk.queue; - info.queue_family = vk.family; - info.buffer_device_address = true; - info.shader_dir = library.string(); - Ref ours; - REQUIRE(SUCCEEDED(rt::d3d12::create_vulkan_device(info, IID_PPV_ARGS(&ours.p)))); - REQUIRE(run_all(ours.p, false, nullptr, vs_container, ps_container, list, layer_grids, layer_closes)); - REQUIRE(layer_checks(ours.p, vs_container, ps_container, library)); - } - - // The host: Windows' D3D12 on the default adapter and on WARP. - std::vector host_vs, host_ps; - const bool wine = hostwine::host_is_wine(); - const bool host_shaders = !wine && compile_hlsl(hlsl, "vs", "vs_5_0", host_vs) && - compile_hlsl(hlsl, "ps", "ps_5_0", host_ps); - struct HostRun { - const char* name = ""; - bool ran = false; - std::vector grids; - std::vector closes; - } hosts[2]; - hosts[0].name = "the default adapter"; - hosts[1].name = "WARP"; - if (host_shaders) { - Ref factory; - REQUIRE(SUCCEEDED(CreateDXGIFactory1(IID_PPV_ARGS(&factory.p)))); - for (int i = 0; i < 2; ++i) { - Ref adapter; - Ref host; - if (i == 1 && FAILED(factory->EnumWarpAdapter(IID_PPV_ARGS(&adapter.p)))) continue; - if (FAILED(D3D12CreateDevice(adapter.p, D3D_FEATURE_LEVEL_11_0, IID_PPV_ARGS(&host.p)))) continue; - REQUIRE(run_all(nullptr, true, adapter.p, host_vs, host_ps, list, hosts[i].grids, hosts[i].closes)); - hosts[i].ran = true; - } - } else if (!wine) { - std::fprintf(stderr, "no HLSL compiler: the host is not run\n"); - } - - // WARP is the reference for zero-count scissors. An AMD Windows D3D12 driver (RX 6700 XT, 26.11.2) keeps the - // old scissor after count zero, while WARP and other tested drivers disable it. Record that native divergence - // without failing the layer or WARP correctness test; all other default-adapter cases remain strict. - unsigned failures = 0, compared = 0; - const auto verdict = [&](const char* who, const Scenario& scenario, const std::string& grid, HRESULT close) { - const bool ok = grid == scenario.expected && close == S_OK; - if (!ok) { - std::fprintf(stderr, "FAIL %s on %s: Close 0x%08lx\n got %s\n expected %s\n", scenario.name, who, - static_cast(close), grid.c_str(), scenario.expected); - ++failures; - } - }; - for (std::size_t i = 0; i < list.size(); ++i) { - if (!list[i].expected) { - std::printf("%s | layer %s", list[i].name, layer_grids[i].c_str()); - for (const auto& host : hosts) - if (host.ran) std::printf(" | %s %s", host.name, host.grids[i].c_str()); - std::printf("\n"); - ++failures; - continue; - } - verdict("the layer", list[i], layer_grids[i], layer_closes[i]); - for (const auto& host : hosts) { - if (!host.ran) continue; - if (&host == &hosts[0] && list[i].warp_oracle_only) { - if (host.closes[i] != S_OK) { - verdict(host.name, list[i], host.grids[i], host.closes[i]); - } else if (host.grids[i] != list[i].expected) { - std::printf("NOTE %s on %s differs from WARP: %s\n", list[i].name, host.name, - host.grids[i].c_str()); - } - continue; - } - verdict(host.name, list[i], host.grids[i], host.closes[i]); - ++compared; - } - } - const unsigned validation_errors = vk.validation_errors() - errors_before; - if (validation_errors) { - std::fprintf(stderr, "%u Vulkan validation errors\n", validation_errors); - ++failures; - } - if (!hosts[0].ran && !hosts[1].ran && !hostwine::host_is_wine()) - std::fprintf(stderr, "no D3D12 reference device (default adapter or WARP)\n"); - std::printf("bundles: %zu scenarios on the layer, %u host comparisons, %u failures\n", list.size(), compared, - failures); - return failures ? 1 : 0; -} diff --git a/runtime/test/d3d12_clear_formats_test.cpp b/runtime/test/d3d12_clear_formats_test.cpp deleted file mode 100644 index aa674f2c6..000000000 --- a/runtime/test/d3d12_clear_formats_test.cpp +++ /dev/null @@ -1,420 +0,0 @@ -// Clears compared with native Windows D3D12/WARP across the format classes (D3D-45): ClearRenderTargetView on -// UNORM, SNORM, SRGB, FLOAT, UINT and SINT formats and ClearDepthStencilView on every depth format, each with and -// without rectangles. Every case clears, copies the result into a readback buffer through D3D12 and compares the -// bytes with what WARP wrote. Extends d3d12_uint_clear_test.cpp (UINT only). -// No game data or shaders. Run explicitly (needs Vulkan hardware and WARP); LEONIDA_VK_VALIDATION=1 checks Vulkan -// usage. A format the layer cannot create yet is listed as "not exposed" and does not fail the test; any other -// difference does. -#include "vk_test_device.h" -#include "host_wine.h" -#include "../shims/d3d12_com.h" -#include -#include -#include -#include -#include -#include -#include -#define CHECK(condition) do { \ - if (!(condition)) { std::fprintf(stderr, " line %d: %s\n", __LINE__, #condition); return false; } \ -} while (0) - -namespace { -template -struct Ref { - T* p = nullptr; - ~Ref() { if (p) p->Release(); } - T* operator->() const { return p; } -}; -struct Event { - HANDLE handle = CreateEventW(nullptr, FALSE, FALSE, nullptr); - ~Event() { if (handle) CloseHandle(handle); } -}; - -constexpr UINT kWidth = 5, kHeight = 3; // odd sizes expose a wrong treatment of footprint padding -using Color = std::array; -constexpr float kNaN = std::numeric_limits::quiet_NaN(); -constexpr float kInf = std::numeric_limits::infinity(); - -// Records the copy of one subresource into a readback buffer, to be read after the list has run. -struct Plane { - Ref buffer; - D3D12_PLACED_SUBRESOURCE_FOOTPRINT placed{}; - UINT64 total = 0; - unsigned bytes = 0; // per pixel in this plane -}; - -struct Run { - Ref queue; - Ref allocator; - Ref list; - Ref fence; - - bool create(ID3D12Device* device) { - const D3D12_COMMAND_QUEUE_DESC queue_desc{}; - CHECK(SUCCEEDED(device->CreateCommandQueue(&queue_desc, IID_PPV_ARGS(&queue.p)))); - CHECK(SUCCEEDED(device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&allocator.p)))); - CHECK(SUCCEEDED(device->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, allocator.p, nullptr, - IID_PPV_ARGS(&list.p)))); - CHECK(SUCCEEDED(device->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&fence.p)))); - return true; - } - bool execute() { - CHECK(SUCCEEDED(list->Close())); - ID3D12CommandList* lists[] = {list.p}; - queue->ExecuteCommandLists(1, lists); - CHECK(SUCCEEDED(queue->Signal(fence.p, 1))); - Event event; - CHECK(event.handle); - CHECK(SUCCEEDED(fence->SetEventOnCompletion(1, event.handle))); - CHECK(WaitForSingleObject(event.handle, 5000) == WAIT_OBJECT_0); - return true; - } -}; - -D3D12_RESOURCE_DESC texture_desc(DXGI_FORMAT format, D3D12_RESOURCE_FLAGS flags) { - D3D12_RESOURCE_DESC texture{}; - texture.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D; - texture.Width = kWidth; - texture.Height = kHeight; - texture.DepthOrArraySize = texture.MipLevels = 1; - texture.Format = format; - texture.SampleDesc.Count = 1; - texture.Flags = flags; - return texture; -} - -void transition(ID3D12GraphicsCommandList* list, ID3D12Resource* image, D3D12_RESOURCE_STATES before, - D3D12_RESOURCE_STATES after) { - D3D12_RESOURCE_BARRIER barrier{}; - barrier.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION; - barrier.Transition.pResource = image; - barrier.Transition.Subresource = D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES; - barrier.Transition.StateBefore = before; - barrier.Transition.StateAfter = after; - list->ResourceBarrier(1, &barrier); -} - -bool add_copy(ID3D12Device* device, ID3D12GraphicsCommandList* list, ID3D12Resource* image, - const D3D12_RESOURCE_DESC& texture, UINT subresource, unsigned bytes, Plane& plane) { - plane.bytes = bytes; - device->GetCopyableFootprints(&texture, subresource, 1, 0, &plane.placed, nullptr, nullptr, &plane.total); - D3D12_RESOURCE_DESC buffer{}; - buffer.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER; - buffer.Width = plane.total; - buffer.Height = buffer.SampleDesc.Count = 1; - buffer.DepthOrArraySize = buffer.MipLevels = 1; - buffer.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; - D3D12_HEAP_PROPERTIES heap{}; - heap.Type = D3D12_HEAP_TYPE_READBACK; - CHECK(SUCCEEDED(device->CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &buffer, - D3D12_RESOURCE_STATE_COPY_DEST, nullptr, - IID_PPV_ARGS(&plane.buffer.p)))); - D3D12_TEXTURE_COPY_LOCATION src{}, dst{}; - src.pResource = image; - src.Type = D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX; - src.SubresourceIndex = subresource; - dst.pResource = plane.buffer.p; - dst.Type = D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT; - dst.PlacedFootprint = plane.placed; - list->CopyTextureRegion(&dst, 0, 0, 0, &src, nullptr); - return true; -} - -bool read_plane(Plane& plane, std::vector& pixels) { - void* mapped = nullptr; - const D3D12_RANGE range{0, SIZE_T(plane.total)}; - CHECK(SUCCEEDED(plane.buffer->Map(0, &range, &mapped)) && mapped); - pixels.resize(kWidth * kHeight * plane.bytes); - for (UINT y = 0; y < kHeight; ++y) - std::memcpy(pixels.data() + y * kWidth * plane.bytes, - static_cast(mapped) + y * plane.placed.Footprint.RowPitch, kWidth * plane.bytes); - const D3D12_RANGE none{}; - plane.buffer->Unmap(0, &none); - return true; -} - -// The two results of a case: false when the device could not run it at all. -enum class Result { ok, not_created, failed }; - -Result clear_color(ID3D12Device* device, DXGI_FORMAT format, DXGI_FORMAT resource_format, unsigned bytes, - const Color& full, const Color& part, std::vector& pixels) { - Run run; - if (!run.create(device)) return Result::failed; - Ref image; - D3D12_HEAP_PROPERTIES heap{}; - heap.Type = D3D12_HEAP_TYPE_DEFAULT; - const D3D12_RESOURCE_DESC texture = texture_desc(resource_format != DXGI_FORMAT_UNKNOWN ? resource_format : format, - D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET); - if (FAILED(device->CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &texture, - D3D12_RESOURCE_STATE_RENDER_TARGET, nullptr, IID_PPV_ARGS(&image.p)))) - return Result::not_created; - Ref rtv_heap; - const D3D12_DESCRIPTOR_HEAP_DESC desc{D3D12_DESCRIPTOR_HEAP_TYPE_RTV, 1, D3D12_DESCRIPTOR_HEAP_FLAG_NONE, 0}; - if (FAILED(device->CreateDescriptorHeap(&desc, IID_PPV_ARGS(&rtv_heap.p)))) return Result::failed; - const auto handle = rtv_heap->GetCPUDescriptorHandleForHeapStart(); - D3D12_RENDER_TARGET_VIEW_DESC view{}; - view.Format = format; - view.ViewDimension = D3D12_RTV_DIMENSION_TEXTURE2D; - device->CreateRenderTargetView(image.p, resource_format != DXGI_FORMAT_UNKNOWN ? &view : nullptr, handle); - run.list->ClearRenderTargetView(handle, full.data(), 0, nullptr); - const D3D12_RECT rect{1, 1, 4, 3}; - run.list->ClearRenderTargetView(handle, part.data(), 1, &rect); - transition(run.list.p, image.p, D3D12_RESOURCE_STATE_RENDER_TARGET, D3D12_RESOURCE_STATE_COPY_SOURCE); - Plane plane; - if (!add_copy(device, run.list.p, image.p, texture, 0, bytes, plane) || !run.execute() || - !read_plane(plane, pixels)) - return Result::failed; - return Result::ok; -} - -struct DepthValues { - float depth_full; - UINT8 stencil_full; - float depth_part; - UINT8 stencil_part; -}; - -// Depth and stencil planes after: a full clear of both, a depth-only clear of one rectangle and a stencil-only -// clear of another. planes[1] is empty for a depth-only format. -Result clear_depth(ID3D12Device* device, DXGI_FORMAT format, bool stencil, unsigned depth_bytes, - const DepthValues& v, std::vector planes[2]) { - Run run; - if (!run.create(device)) return Result::failed; - Ref image; - D3D12_HEAP_PROPERTIES heap{}; - heap.Type = D3D12_HEAP_TYPE_DEFAULT; - const D3D12_RESOURCE_DESC texture = texture_desc(format, D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL); - if (FAILED(device->CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &texture, - D3D12_RESOURCE_STATE_DEPTH_WRITE, nullptr, IID_PPV_ARGS(&image.p)))) - return Result::not_created; - Ref dsv_heap; - const D3D12_DESCRIPTOR_HEAP_DESC desc{D3D12_DESCRIPTOR_HEAP_TYPE_DSV, 1, D3D12_DESCRIPTOR_HEAP_FLAG_NONE, 0}; - if (FAILED(device->CreateDescriptorHeap(&desc, IID_PPV_ARGS(&dsv_heap.p)))) return Result::failed; - const auto handle = dsv_heap->GetCPUDescriptorHandleForHeapStart(); - device->CreateDepthStencilView(image.p, nullptr, handle); - const D3D12_CLEAR_FLAGS both = stencil ? D3D12_CLEAR_FLAG_DEPTH | D3D12_CLEAR_FLAG_STENCIL : D3D12_CLEAR_FLAG_DEPTH; - run.list->ClearDepthStencilView(handle, both, v.depth_full, v.stencil_full, 0, nullptr); - const D3D12_RECT depth_rect{1, 1, 4, 3}; - run.list->ClearDepthStencilView(handle, D3D12_CLEAR_FLAG_DEPTH, v.depth_part, 0, 1, &depth_rect); - if (stencil) { - const D3D12_RECT stencil_rect{0, 0, 3, 2}; - run.list->ClearDepthStencilView(handle, D3D12_CLEAR_FLAG_STENCIL, 0.0f, v.stencil_part, 1, &stencil_rect); - } - transition(run.list.p, image.p, D3D12_RESOURCE_STATE_DEPTH_WRITE, D3D12_RESOURCE_STATE_COPY_SOURCE); - Plane depth, stencil_plane; - if (!add_copy(device, run.list.p, image.p, texture, 0, depth_bytes, depth) || - (stencil && !add_copy(device, run.list.p, image.p, texture, 1, 1, stencil_plane)) || !run.execute() || - !read_plane(depth, planes[0]) || (stencil && !read_plane(stencil_plane, planes[1]))) - return Result::failed; - return Result::ok; -} - -struct ColorCase { - const char* group; - const char* name; - DXGI_FORMAT format; - unsigned bytes; - const std::vector* colors; - DXGI_FORMAT resource = DXGI_FORMAT_UNKNOWN; // a TYPELESS format the resource is created with; format is the view -}; - -// Out-of-range values clamp in the normalised classes; NaN is 0 there. NaN is left out of the float classes, whose -// payload bits are not defined. -const std::vector kUnorm = {{0, 0.25f, 0.5f, 1}, {1, 0.75f, 0.125f, 0.5f}, {-1, 2, 0.5f, 1.5f}, - {0.0039f, 0.5019f, 0.9961f, 0.3333f}, {kNaN, kInf, -kInf, 0.5f}}; -const std::vector kSnorm = {{-1, -0.5f, 0.5f, 1}, {-2, 2, 0.001f, -0.001f}, {0, 0.25f, -0.25f, 0.7f}, - {kNaN, kInf, -kInf, -0.5f}}; -const std::vector kFloat = {{0.1f, 1.5f, -3.25f, 65504.0f}, {1e-8f, 70000.0f, -70000.0f, 0.5f}, - {0, 1, 2, 3}, {kInf, -kInf, 1e-5f, 123456.0f}}; -const std::vector kUint = {{1, 2, 3, 4}, {1.5f, 2.5f, 3.5f, 4.5f}, {-1, -0.0f, 254.5f, 255.5f}, - {256, 65536, 16777216, 4294967296.0f}, {kNaN, kInf, -kInf, 0.5f}, - {0.499f, 0.501f, 1.499f, 1.501f}, {4294967040.0f, 3.4e38f, 255, 0}}; -const std::vector kSint = {{-1, -2, -128, 127}, {-1.5f, -2.5f, 2.5f, 3.5f}, {-129, 128, -32769, 32768}, - {2147483648.0f, -2147483904.0f, kNaN, kInf}, {-kInf, 0.5f, -0.5f, 100000.0f}}; - -const ColorCase kColorCases[] = { - {"UNORM", "R8_UNORM", DXGI_FORMAT_R8_UNORM, 1, &kUnorm}, - {"UNORM", "R8G8_UNORM", DXGI_FORMAT_R8G8_UNORM, 2, &kUnorm}, - {"UNORM", "R8G8B8A8_UNORM", DXGI_FORMAT_R8G8B8A8_UNORM, 4, &kUnorm}, - {"UNORM", "B8G8R8A8_UNORM", DXGI_FORMAT_B8G8R8A8_UNORM, 4, &kUnorm}, - {"UNORM", "R10G10B10A2_UNORM", DXGI_FORMAT_R10G10B10A2_UNORM, 4, &kUnorm}, - {"UNORM", "R16_UNORM", DXGI_FORMAT_R16_UNORM, 2, &kUnorm}, - {"UNORM", "R16G16_UNORM", DXGI_FORMAT_R16G16_UNORM, 4, &kUnorm}, - {"UNORM", "R16G16B16A16_UNORM", DXGI_FORMAT_R16G16B16A16_UNORM, 8, &kUnorm}, - {"SNORM", "R8_SNORM", DXGI_FORMAT_R8_SNORM, 1, &kSnorm}, - {"SNORM", "R8G8_SNORM", DXGI_FORMAT_R8G8_SNORM, 2, &kSnorm}, - {"SNORM", "R8G8B8A8_SNORM", DXGI_FORMAT_R8G8B8A8_SNORM, 4, &kSnorm}, - {"SNORM", "R16_SNORM", DXGI_FORMAT_R16_SNORM, 2, &kSnorm}, - {"SNORM", "R16G16_SNORM", DXGI_FORMAT_R16G16_SNORM, 4, &kSnorm}, - {"SNORM", "R16G16B16A16_SNORM", DXGI_FORMAT_R16G16B16A16_SNORM, 8, &kSnorm}, - {"SRGB", "R8G8B8A8_UNORM_SRGB", DXGI_FORMAT_R8G8B8A8_UNORM_SRGB, 4, &kUnorm}, - {"SRGB", "B8G8R8A8_UNORM_SRGB", DXGI_FORMAT_B8G8R8A8_UNORM_SRGB, 4, &kUnorm}, - {"FLOAT", "R16_FLOAT", DXGI_FORMAT_R16_FLOAT, 2, &kFloat}, - {"FLOAT", "R16G16_FLOAT", DXGI_FORMAT_R16G16_FLOAT, 4, &kFloat}, - {"FLOAT", "R16G16B16A16_FLOAT", DXGI_FORMAT_R16G16B16A16_FLOAT, 8, &kFloat}, - {"FLOAT", "R32_FLOAT", DXGI_FORMAT_R32_FLOAT, 4, &kFloat}, - {"FLOAT", "R32G32_FLOAT", DXGI_FORMAT_R32G32_FLOAT, 8, &kFloat}, - {"FLOAT", "R32G32B32A32_FLOAT", DXGI_FORMAT_R32G32B32A32_FLOAT, 16, &kFloat}, - {"FLOAT", "R11G11B10_FLOAT", DXGI_FORMAT_R11G11B10_FLOAT, 4, &kFloat}, - {"UINT", "R8_UINT", DXGI_FORMAT_R8_UINT, 1, &kUint}, - {"UINT", "R8G8_UINT", DXGI_FORMAT_R8G8_UINT, 2, &kUint}, - {"UINT", "R16_UINT", DXGI_FORMAT_R16_UINT, 2, &kUint}, - {"UINT", "R16G16_UINT", DXGI_FORMAT_R16G16_UINT, 4, &kUint}, - {"UINT", "R8G8B8A8_UINT", DXGI_FORMAT_R8G8B8A8_UINT, 4, &kUint}, - {"UINT", "R10G10B10A2_UINT", DXGI_FORMAT_R10G10B10A2_UINT, 4, &kUint}, - {"UINT", "R16G16B16A16_UINT", DXGI_FORMAT_R16G16B16A16_UINT, 8, &kUint}, - {"UINT", "R32_UINT", DXGI_FORMAT_R32_UINT, 4, &kUint}, - {"UINT", "R32G32_UINT", DXGI_FORMAT_R32G32_UINT, 8, &kUint}, - {"UINT", "R32G32B32A32_UINT", DXGI_FORMAT_R32G32B32A32_UINT, 16, &kUint}, - {"SINT", "R8_SINT", DXGI_FORMAT_R8_SINT, 1, &kSint}, - {"SINT", "R8G8_SINT", DXGI_FORMAT_R8G8_SINT, 2, &kSint}, - {"SINT", "R16_SINT", DXGI_FORMAT_R16_SINT, 2, &kSint}, - {"SINT", "R16G16_SINT", DXGI_FORMAT_R16G16_SINT, 4, &kSint}, - {"SINT", "R8G8B8A8_SINT", DXGI_FORMAT_R8G8B8A8_SINT, 4, &kSint}, - {"SINT", "R16G16B16A16_SINT", DXGI_FORMAT_R16G16B16A16_SINT, 8, &kSint}, - {"SINT", "R32_SINT", DXGI_FORMAT_R32_SINT, 4, &kSint}, - {"SINT", "R32G32_SINT", DXGI_FORMAT_R32G32_SINT, 8, &kSint}, - {"SINT", "R32G32B32A32_SINT", DXGI_FORMAT_R32G32B32A32_SINT, 16, &kSint}, - // A TYPELESS resource cleared through the typed view its default maps to. A view that changes the class (UINT or - // SINT view of a TYPELESS resource) is not covered: the layer ignores the RTV's format, so the clear converts - // for the resource's class. - {"TYPELESS", "R8_TYPELESS as UNORM", DXGI_FORMAT_R8_UNORM, 1, &kUnorm, DXGI_FORMAT_R8_TYPELESS}, - {"TYPELESS", "R8G8_TYPELESS as UNORM", DXGI_FORMAT_R8G8_UNORM, 2, &kUnorm, DXGI_FORMAT_R8G8_TYPELESS}, - {"TYPELESS", "R16G16_TYPELESS as FLOAT", DXGI_FORMAT_R16G16_FLOAT, 4, &kFloat, DXGI_FORMAT_R16G16_TYPELESS}, - {"TYPELESS", "R32G32_TYPELESS as FLOAT", DXGI_FORMAT_R32G32_FLOAT, 8, &kFloat, DXGI_FORMAT_R32G32_TYPELESS}, -}; - -struct DepthCase { - const char* name; - DXGI_FORMAT format; - bool stencil; - unsigned depth_bytes; -}; - -const DepthCase kDepthCases[] = { - {"D16_UNORM", DXGI_FORMAT_D16_UNORM, false, 2}, - {"D32_FLOAT", DXGI_FORMAT_D32_FLOAT, false, 4}, - {"D24_UNORM_S8_UINT", DXGI_FORMAT_D24_UNORM_S8_UINT, true, 4}, - {"D32_FLOAT_S8X24_UINT", DXGI_FORMAT_D32_FLOAT_S8X24_UINT, true, 4}, -}; - -const DepthValues kDepthValues[] = {{0.25f, 0x5A, 0.75f, 0xA5}, {1.0f, 0xFF, 0.0f, 0x00}, - {0.3333f, 0x01, 0.9999f, 0x80}, {0.5f, 0x7F, 0.0001f, 0x10}}; - -struct Tally { - unsigned matched = 0, differ = 0, not_exposed = 0, failed = 0, skipped = 0; -}; - -// Names the first byte that differs. -void report(const char* group, const char* name, unsigned index, const char* what, - const std::vector& actual, const std::vector& expected) { - for (std::size_t b = 0; b < actual.size() && b < expected.size(); ++b) { - if (actual[b] != expected[b]) { - std::printf("DIFF %-6s %-22s case %u %s byte %zu: layer %02x, WARP %02x\n", group, name, index, what, b, - unsigned(actual[b]), unsigned(expected[b])); - return; - } - } - std::printf("DIFF %-6s %-22s case %u %s: sizes %zu and %zu\n", group, name, index, what, actual.size(), - expected.size()); -} -} // namespace - -int main() { - vktest::Device vk; - const auto device_status = vk.initialize(); - if (device_status == vktest::DeviceStatus::unavailable) return 77; // no Vulkan GPU: ctest skips - if (device_status != vktest::DeviceStatus::ready) return 1; - const unsigned errors_before = vk.validation_errors(); - Tally tally; - { - Ref ours, host; - rt::d3d12::VulkanDeviceInfo info{}; - info.get_instance_proc = vk.instance_proc; - info.instance = vk.instance; - info.physical = vk.physical; - info.device = vk.device; - info.queue = vk.queue; - info.queue_family = vk.family; - if (FAILED(rt::d3d12::create_vulkan_device(info, IID_PPV_ARGS(&ours.p)))) return 1; - if (hostwine::host_is_wine()) return 77; // every clear is compared with WARP, and Wine keeps no separate WARP - Ref factory; - Ref warp; - if (FAILED(CreateDXGIFactory1(IID_PPV_ARGS(&factory.p))) || - FAILED(factory->EnumWarpAdapter(IID_PPV_ARGS(&warp.p))) || - FAILED(D3D12CreateDevice(warp.p, D3D_FEATURE_LEVEL_11_0, IID_PPV_ARGS(&host.p)))) { - std::fprintf(stderr, "WARP reference unavailable: differential test cannot run\n"); - return 1; - } - for (const ColorCase& c : kColorCases) { - const auto& colors = *c.colors; - bool reported_exposure = false; - for (unsigned i = 0; i < colors.size(); ++i) { - // Different colours outside and inside the rectangle exercise both Vulkan clear paths. - const Color& full = colors[i]; - const Color& part = colors[(i + 1) % colors.size()]; - std::vector actual, expected; - const Result want = clear_color(host.p, c.format, c.resource, c.bytes, full, part, expected); - if (want != Result::ok) { - ++tally.skipped; // WARP itself does not offer the format as a render target here - continue; - } - const Result got = clear_color(ours.p, c.format, c.resource, c.bytes, full, part, actual); - if (got == Result::not_created) { - ++tally.not_exposed; - if (!reported_exposure) std::printf("not exposed: %-6s %s\n", c.group, c.name); - reported_exposure = true; - continue; - } - if (got != Result::ok) { - ++tally.failed; - std::printf("FAIL %-6s %-22s case %u: the layer could not run it\n", c.group, c.name, i); - } else if (actual != expected) { - ++tally.differ; - report(c.group, c.name, i, "colour", actual, expected); - } else { - ++tally.matched; - } - } - } - for (const DepthCase& c : kDepthCases) { - bool reported_exposure = false; - for (unsigned i = 0; i < std::size(kDepthValues); ++i) { - std::vector actual[2], expected[2]; - const Result want = clear_depth(host.p, c.format, c.stencil, c.depth_bytes, kDepthValues[i], expected); - if (want != Result::ok) { - ++tally.skipped; - continue; - } - const Result got = clear_depth(ours.p, c.format, c.stencil, c.depth_bytes, kDepthValues[i], actual); - if (got == Result::not_created) { - ++tally.not_exposed; - if (!reported_exposure) std::printf("not exposed: DEPTH %s\n", c.name); - reported_exposure = true; - continue; - } - if (got != Result::ok) { - ++tally.failed; - std::printf("FAIL DEPTH %-22s case %u: the layer could not run it\n", c.name, i); - continue; - } - bool same = true; - for (int plane = 0; plane < (c.stencil ? 2 : 1); ++plane) { - if (actual[plane] != expected[plane]) { - same = false; - report("DEPTH", c.name, i, plane ? "stencil" : "depth", actual[plane], expected[plane]); - } - } - if (same) ++tally.matched; - else ++tally.differ; - } - } - } // Destroy the D3D12 objects before checking the Vulkan validation counter. - std::printf("clears: %u matched WARP, %u differ, %u failed, %u in formats the layer does not expose, " - "%u skipped (WARP does not offer the format)\n", - tally.matched, tally.differ, tally.failed, tally.not_exposed, tally.skipped); - if (tally.differ || tally.failed) return 1; - if (vk.validation_errors() != errors_before) return 1; - return 0; -} diff --git a/runtime/test/d3d12_clear_test.cpp b/runtime/test/d3d12_clear_test.cpp deleted file mode 100644 index 9e7555c76..000000000 --- a/runtime/test/d3d12_clear_test.cpp +++ /dev/null @@ -1,690 +0,0 @@ - -// Compare render-target and depth-stencil clears against native Windows D3D12/WARP, through D3D12 clear/copy/Map on -// both sides. Covers UNORM/SNORM/FLOAT/UINT/SINT render targets and depth/stencil, full and rectangle clears, and RTVs -// through castable-format lists in the other channel order. -// No game data or shaders. Run explicitly (needs Vulkan hardware); LEONIDA_VK_VALIDATION=1 checks Vulkan usage. -#include "vk_test_device.h" -#include "host_wine.h" -#include "../shims/d3d12_com.h" -#include -#include -#include -#include -#include -#include -#include -#define CHECK(condition) do { \ - if (!(condition)) { std::fprintf(stderr, "line %d: %s\n", __LINE__, #condition); return false; } \ -} while (0) - -namespace { -template -struct Ref { - T* p = nullptr; - ~Ref() { if (p) p->Release(); } - T* operator->() const { return p; } -}; -struct Event { - HANDLE handle = CreateEventW(nullptr, FALSE, FALSE, nullptr); - ~Event() { if (handle) CloseHandle(handle); } -}; - -// With `cast` set, the texture lists it as its castable format (CreateCommittedResource3) and the clears go through an -// RTV in it. -bool clear_and_read(ID3D12Device* device, DXGI_FORMAT format, unsigned bytes, const FLOAT* full, const FLOAT* part, - std::vector& pixels, bool volume = false, DXGI_FORMAT cast = DXGI_FORMAT_UNKNOWN) { - Ref queue; - Ref allocator; - Ref list; - Ref fence; - D3D12_COMMAND_QUEUE_DESC queue_desc{}; - CHECK(SUCCEEDED(device->CreateCommandQueue(&queue_desc, IID_PPV_ARGS(&queue.p)))); - CHECK(SUCCEEDED(device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&allocator.p)))); - CHECK(SUCCEEDED(device->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, allocator.p, nullptr, - IID_PPV_ARGS(&list.p)))); - CHECK(SUCCEEDED(device->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&fence.p)))); - - Ref image, readback; - D3D12_HEAP_PROPERTIES heap_properties{}; - heap_properties.Type = D3D12_HEAP_TYPE_DEFAULT; - D3D12_RESOURCE_DESC texture{}; - texture.Dimension = volume ? D3D12_RESOURCE_DIMENSION_TEXTURE3D : D3D12_RESOURCE_DIMENSION_TEXTURE2D; - texture.Width = volume ? 8 : 5; - texture.Height = volume ? 6 : 3; - texture.DepthOrArraySize = volume ? 12 : 1; - texture.MipLevels = volume ? 2 : 1; - texture.Format = format; - texture.SampleDesc.Count = 1; - texture.Flags = D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET; - if (cast == DXGI_FORMAT_UNKNOWN) { - CHECK(SUCCEEDED(device->CreateCommittedResource(&heap_properties, D3D12_HEAP_FLAG_NONE, &texture, - D3D12_RESOURCE_STATE_RENDER_TARGET, nullptr, IID_PPV_ARGS(&image.p)))); - } else { - Ref device10; - CHECK(SUCCEEDED(device->QueryInterface(IID_PPV_ARGS(&device10.p)))); - D3D12_RESOURCE_DESC1 texture1{}; - texture1.Dimension = texture.Dimension; - texture1.Width = texture.Width; - texture1.Height = texture.Height; - texture1.DepthOrArraySize = texture.DepthOrArraySize; - texture1.MipLevels = texture.MipLevels; - texture1.Format = texture.Format; - texture1.SampleDesc = texture.SampleDesc; - texture1.Flags = texture.Flags; - CHECK(SUCCEEDED(device10->CreateCommittedResource3(&heap_properties, D3D12_HEAP_FLAG_NONE, &texture1, - D3D12_BARRIER_LAYOUT_RENDER_TARGET, nullptr, nullptr, 1, &cast, IID_PPV_ARGS(&image.p)))); - } - D3D12_PLACED_SUBRESOURCE_FOOTPRINT placed[2]{}; - UINT64 total = 0; - device->GetCopyableFootprints(&texture, 0, texture.MipLevels, 0, placed, nullptr, nullptr, &total); - D3D12_RESOURCE_DESC buffer{}; - buffer.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER; - buffer.Width = total; - buffer.Height = buffer.SampleDesc.Count = 1; - buffer.DepthOrArraySize = buffer.MipLevels = 1; - buffer.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; - heap_properties.Type = D3D12_HEAP_TYPE_READBACK; - CHECK(SUCCEEDED(device->CreateCommittedResource(&heap_properties, D3D12_HEAP_FLAG_NONE, &buffer, - D3D12_RESOURCE_STATE_COPY_DEST, nullptr, IID_PPV_ARGS(&readback.p)))); - Ref heap; - const D3D12_DESCRIPTOR_HEAP_DESC desc{D3D12_DESCRIPTOR_HEAP_TYPE_RTV, 1, D3D12_DESCRIPTOR_HEAP_FLAG_NONE, 0}; - CHECK(SUCCEEDED(device->CreateDescriptorHeap(&desc, IID_PPV_ARGS(&heap.p)))); - const auto handle = heap->GetCPUDescriptorHandleForHeapStart(); - if (cast == DXGI_FORMAT_UNKNOWN) { - device->CreateRenderTargetView(image.p, nullptr, handle); - } else { - D3D12_RENDER_TARGET_VIEW_DESC listed{}; - listed.Format = cast; - listed.ViewDimension = D3D12_RTV_DIMENSION_TEXTURE2D; - device->CreateRenderTargetView(image.p, &listed, handle); - } - list->ClearRenderTargetView(handle, full, 0, nullptr); - const D3D12_RECT rect{1, 1, 4, 3}; - if (volume) { - D3D12_RENDER_TARGET_VIEW_DESC view{}; - view.Format = format; - view.ViewDimension = D3D12_RTV_DIMENSION_TEXTURE3D; - const auto clear = [&](UINT first, UINT count, const FLOAT* color, const D3D12_RECT* area) { - view.Texture3D = {1, first, count}; - device->CreateRenderTargetView(image.p, &view, handle); - list->ClearRenderTargetView(handle, color, area ? 1 : 0, area); - }; - const FLOAT blue[4]{0, 0, 1, 1}; - const FLOAT yellow[4]{1, 1, 0, 0}; - clear(0, UINT_MAX, blue, nullptr); - clear(1, 2, part, nullptr); - clear(2, UINT_MAX, yellow, &rect); - } else { - list->ClearRenderTargetView(handle, part, 1, &rect); - } - D3D12_RESOURCE_BARRIER barrier{}; - barrier.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION; - barrier.Transition.pResource = image.p; - barrier.Transition.Subresource = D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES; - barrier.Transition.StateBefore = D3D12_RESOURCE_STATE_RENDER_TARGET; - barrier.Transition.StateAfter = D3D12_RESOURCE_STATE_COPY_SOURCE; - list->ResourceBarrier(1, &barrier); - D3D12_TEXTURE_COPY_LOCATION src{}, dst{}; - src.pResource = image.p; - src.Type = D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX; - dst.pResource = readback.p; - dst.Type = D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT; - for (UINT mip = 0; mip < texture.MipLevels; ++mip) { - src.SubresourceIndex = mip; - dst.PlacedFootprint = placed[mip]; - list->CopyTextureRegion(&dst, 0, 0, 0, &src, nullptr); - } - CHECK(SUCCEEDED(list->Close())); - ID3D12CommandList* lists[] = {list.p}; - queue->ExecuteCommandLists(1, lists); - CHECK(SUCCEEDED(queue->Signal(fence.p, 1))); - Event event; - CHECK(event.handle); - CHECK(SUCCEEDED(fence->SetEventOnCompletion(1, event.handle))); - CHECK(WaitForSingleObject(event.handle, 5000) == WAIT_OBJECT_0); - void* mapped = nullptr; - const D3D12_RANGE range{0, SIZE_T(total)}; - CHECK(SUCCEEDED(readback->Map(0, &range, &mapped)) && mapped); - pixels.clear(); - for (UINT mip = 0; mip < texture.MipLevels; ++mip) { - const auto& fp = placed[mip].Footprint; - for (UINT row = 0; row < fp.Height * fp.Depth; ++row) { - const auto* start = static_cast(mapped) + placed[mip].Offset + row * fp.RowPitch; - pixels.insert(pixels.end(), start, start + fp.Width * bytes); - } - } - const D3D12_RANGE none{}; - readback->Unmap(0, &none); - return true; -} - -// Clears a depth-stencil target fully and a rectangle, then reads the depth plane (and the stencil plane, when the -// format has one) back. depth_bytes is the depth plane's bytes per pixel (2 for D16, 4 for D32); has_stencil selects -// the separate stencil plane (subresource 1) of a combined format. full_flags / part_flags override the clear flags -// of the two clears (0: DEPTH, plus STENCIL when the format has a stencil plane). -bool clear_depth_and_read(ID3D12Device* device, DXGI_FORMAT format, unsigned depth_bytes, bool has_stencil, - FLOAT depth_full, UINT8 stencil_full, FLOAT depth_part, UINT8 stencil_part, - std::vector& depth_pixels, std::vector& stencil_pixels, - D3D12_CLEAR_FLAGS full_flags = D3D12_CLEAR_FLAGS(0), - D3D12_CLEAR_FLAGS part_flags = D3D12_CLEAR_FLAGS(0), bool part_no_flags = false) { - Ref queue; - Ref allocator; - Ref list; - Ref fence; - D3D12_COMMAND_QUEUE_DESC queue_desc{}; - CHECK(SUCCEEDED(device->CreateCommandQueue(&queue_desc, IID_PPV_ARGS(&queue.p)))); - CHECK(SUCCEEDED(device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&allocator.p)))); - CHECK(SUCCEEDED(device->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, allocator.p, nullptr, - IID_PPV_ARGS(&list.p)))); - CHECK(SUCCEEDED(device->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&fence.p)))); - - constexpr UINT width = 5, height = 3; - Ref image, readback; - D3D12_HEAP_PROPERTIES heap_properties{}; - heap_properties.Type = D3D12_HEAP_TYPE_DEFAULT; - D3D12_RESOURCE_DESC texture{}; - texture.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D; - texture.Width = width; - texture.Height = height; - texture.DepthOrArraySize = texture.MipLevels = 1; - texture.Format = format; - texture.SampleDesc.Count = 1; - texture.Flags = D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL; - CHECK(SUCCEEDED(device->CreateCommittedResource(&heap_properties, D3D12_HEAP_FLAG_NONE, &texture, - D3D12_RESOURCE_STATE_DEPTH_WRITE, nullptr, IID_PPV_ARGS(&image.p)))); - const UINT subresources = has_stencil ? 2u : 1u; - D3D12_PLACED_SUBRESOURCE_FOOTPRINT placed[2]{}; - UINT64 total = 0; - device->GetCopyableFootprints(&texture, 0, subresources, 0, placed, nullptr, nullptr, &total); - D3D12_RESOURCE_DESC buffer{}; - buffer.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER; - buffer.Width = total; - buffer.Height = buffer.SampleDesc.Count = 1; - buffer.DepthOrArraySize = buffer.MipLevels = 1; - buffer.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; - heap_properties.Type = D3D12_HEAP_TYPE_READBACK; - CHECK(SUCCEEDED(device->CreateCommittedResource(&heap_properties, D3D12_HEAP_FLAG_NONE, &buffer, - D3D12_RESOURCE_STATE_COPY_DEST, nullptr, IID_PPV_ARGS(&readback.p)))); - Ref heap; - const D3D12_DESCRIPTOR_HEAP_DESC desc{D3D12_DESCRIPTOR_HEAP_TYPE_DSV, 1, D3D12_DESCRIPTOR_HEAP_FLAG_NONE, 0}; - CHECK(SUCCEEDED(device->CreateDescriptorHeap(&desc, IID_PPV_ARGS(&heap.p)))); - const auto handle = heap->GetCPUDescriptorHandleForHeapStart(); - device->CreateDepthStencilView(image.p, nullptr, handle); - const D3D12_CLEAR_FLAGS flags = - static_cast((has_stencil ? D3D12_CLEAR_FLAG_STENCIL : 0) | D3D12_CLEAR_FLAG_DEPTH); - list->ClearDepthStencilView(handle, full_flags ? full_flags : flags, depth_full, stencil_full, 0, nullptr); - const D3D12_RECT rect{1, 1, 4, 3}; - list->ClearDepthStencilView(handle, part_no_flags ? D3D12_CLEAR_FLAGS(0) : (part_flags ? part_flags : flags), - depth_part, stencil_part, 1, &rect); - D3D12_RESOURCE_BARRIER barrier{}; - barrier.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION; - barrier.Transition.pResource = image.p; - barrier.Transition.Subresource = D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES; - barrier.Transition.StateBefore = D3D12_RESOURCE_STATE_DEPTH_WRITE; - barrier.Transition.StateAfter = D3D12_RESOURCE_STATE_COPY_SOURCE; - list->ResourceBarrier(1, &barrier); - for (UINT i = 0; i < subresources; ++i) { - D3D12_TEXTURE_COPY_LOCATION src{}, dst{}; - src.pResource = image.p; - src.Type = D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX; - src.SubresourceIndex = i; - dst.pResource = readback.p; - dst.Type = D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT; - dst.PlacedFootprint = placed[i]; - list->CopyTextureRegion(&dst, 0, 0, 0, &src, nullptr); - } - CHECK(SUCCEEDED(list->Close())); - ID3D12CommandList* lists[] = {list.p}; - queue->ExecuteCommandLists(1, lists); - CHECK(SUCCEEDED(queue->Signal(fence.p, 1))); - Event event; - CHECK(event.handle); - CHECK(SUCCEEDED(fence->SetEventOnCompletion(1, event.handle))); - CHECK(WaitForSingleObject(event.handle, 5000) == WAIT_OBJECT_0); - void* mapped = nullptr; - const D3D12_RANGE range{0, SIZE_T(total)}; - CHECK(SUCCEEDED(readback->Map(0, &range, &mapped)) && mapped); - const auto* base = static_cast(mapped); - depth_pixels.resize(width * height * depth_bytes); - for (UINT y = 0; y < height; ++y) - std::memcpy(depth_pixels.data() + y * width * depth_bytes, - base + placed[0].Offset + y * placed[0].Footprint.RowPitch, width * depth_bytes); - if (has_stencil) { - stencil_pixels.resize(width * height); - for (UINT y = 0; y < height; ++y) - std::memcpy(stencil_pixels.data() + y * width, - base + placed[1].Offset + y * placed[1].Footprint.RowPitch, width); - } - const D3D12_RANGE none{}; - readback->Unmap(0, &none); - return true; -} - -bool check_shared_exponent_target(ID3D12Device* device) { - constexpr auto format = DXGI_FORMAT_R9G9B9E5_SHAREDEXP; - const FLOAT full[]{1, 2, 4, 0}, rect[]{4, 2, 1, 0}; - std::vector pixels; - CHECK(clear_and_read(device, format, 4, full, rect, pixels)); - for (unsigned y = 0; y < 3; ++y) { - for (unsigned x = 0; x < 5; ++x) { - uint32_t got; - std::memcpy(&got, pixels.data() + (5 * y + x) * 4, 4); - const uint32_t expected = (y >= 1 && x >= 1 && x < 4) ? 0x91010100u : 0x94010040u; - if (got != expected) { - std::fprintf(stderr, "RGB9E5 (%u,%u): got %08x, expected %08x\n", x, y, got, expected); - return false; - } - } - } - std::puts("RGB9E5 RTV: full and rectangle clears match all 15 packed texels"); - return true; -} - -bool check_volume_rtvs(ID3D12Device* host, ID3D12Device* ours) { - const FLOAT red[4]{1, 0, 0, 1}, green[4]{0, 1, 0, 1}; - std::vector expected; - // Mip 0 stays red. Mip 1 starts blue; W 1 and 2 are green, with a yellow rectangle on W 2 through 5. - for (UINT mip = 0; mip < 2; ++mip) - for (UINT z = 0; z < (12u >> mip); ++z) - for (UINT y = 0; y < (6u >> mip); ++y) - for (UINT x = 0; x < (8u >> mip); ++x) { - if (mip == 0) expected.insert(expected.end(), {255, 0, 0, 255}); - else if (z >= 2 && x >= 1 && y >= 1) expected.insert(expected.end(), {255, 255, 0, 0}); - else if (z == 1 || z == 2) expected.insert(expected.end(), {0, 255, 0, 255}); - else expected.insert(expected.end(), {0, 0, 255, 255}); - } - const auto verify = [&](ID3D12Device* device, const char* backend) { - std::vector pixels; - if (!clear_and_read(device, DXGI_FORMAT_R8G8B8A8_UNORM, 4, red, green, pixels, true)) return false; - CHECK(pixels.size() == expected.size()); - size_t wrong = 0; - for (size_t offset = 0; offset < pixels.size(); offset += 4) - if (std::memcmp(pixels.data() + offset, expected.data() + offset, 4)) ++wrong; - if (wrong) std::fprintf(stderr, "%s: %zu of %zu volume texels differ\n", backend, wrong, pixels.size() / 4); - return wrong == 0; - }; - if (!verify(host, "WARP") || !verify(ours, "Vulkan")) return false; - std::printf("3D RTVs: %zu RGBA texels match WARP and expected slice colours\n", expected.size() / 4); - return true; -} - -// A texture with a castable list takes an RTV in its own format and in the listed one, and none in a format the -// list doesn't name (the descriptor stays empty): in the other channel order, across B8G8R8X8 and B8G8R8A8, or the -// texture's own sRGB format. Typed R8G8B8A8, B8G8R8A8 and B8G8R8X8 textures refuse alike. -bool check_unlisted_rtvs(ID3D12Device* device) { - Ref device10; - CHECK(SUCCEEDED(device->QueryInterface(IID_PPV_ARGS(&device10.p)))); - const D3D12_HEAP_PROPERTIES heap_properties{D3D12_HEAP_TYPE_DEFAULT}; - Ref heap; - const D3D12_DESCRIPTOR_HEAP_DESC heap_desc{D3D12_DESCRIPTOR_HEAP_TYPE_RTV, 1}; - CHECK(SUCCEEDED(device->CreateDescriptorHeap(&heap_desc, IID_PPV_ARGS(&heap.p)))); - const auto handle = heap->GetCPUDescriptorHandleForHeapStart(); - struct Listed { - DXGI_FORMAT resource, listed; - VkFormat listed_view; - std::array unlisted; - }; - const Listed textures[] = { - {DXGI_FORMAT_R8G8B8A8_UNORM, DXGI_FORMAT_B8G8R8A8_UNORM, VK_FORMAT_B8G8R8A8_UNORM, - {DXGI_FORMAT_B8G8R8A8_UNORM_SRGB, DXGI_FORMAT_B8G8R8X8_UNORM, DXGI_FORMAT_R8G8B8A8_UNORM_SRGB}}, - {DXGI_FORMAT_B8G8R8A8_UNORM, DXGI_FORMAT_R8G8B8A8_UNORM, VK_FORMAT_R8G8B8A8_UNORM, - {DXGI_FORMAT_B8G8R8A8_UNORM_SRGB, DXGI_FORMAT_B8G8R8X8_UNORM, DXGI_FORMAT_R8G8B8A8_UNORM_SRGB}}, - {DXGI_FORMAT_B8G8R8X8_UNORM, DXGI_FORMAT_B8G8R8A8_UNORM, VK_FORMAT_B8G8R8A8_UNORM, - {DXGI_FORMAT_B8G8R8X8_UNORM_SRGB, DXGI_FORMAT_B8G8R8A8_UNORM_SRGB, DXGI_FORMAT_R8G8B8A8_UNORM}}, - }; - const leonida::TargetView none{}; - unsigned refused = 0; - for (const Listed& t : textures) { - D3D12_RESOURCE_DESC1 texture{}; - texture.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D; - texture.Width = texture.Height = 4; - texture.DepthOrArraySize = 1; - texture.MipLevels = 1; - texture.Format = t.resource; - texture.SampleDesc.Count = 1; - texture.Flags = D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET; - Ref image; - CHECK(SUCCEEDED(device10->CreateCommittedResource3(&heap_properties, D3D12_HEAP_FLAG_NONE, &texture, - D3D12_BARRIER_LAYOUT_RENDER_TARGET, nullptr, nullptr, 1, &t.listed, IID_PPV_ARGS(&image.p)))); - const auto rtv = [&](DXGI_FORMAT format) { - D3D12_RENDER_TARGET_VIEW_DESC desc{}; - desc.Format = format; - desc.ViewDimension = D3D12_RTV_DIMENSION_TEXTURE2D; - std::memset(reinterpret_cast(handle.ptr), 0x55, sizeof(leonida::TargetView)); - device->CreateRenderTargetView(image.p, &desc, handle); - leonida::TargetView view{}; - std::memcpy(&view, reinterpret_cast(handle.ptr), sizeof(view)); - return view; - }; - CHECK(rtv(t.resource).resource); - const leonida::TargetView listed_view = rtv(t.listed); - CHECK(listed_view.resource && listed_view.format == static_cast(t.listed_view)); - for (const DXGI_FORMAT unlisted : t.unlisted) { - const leonida::TargetView view = rtv(unlisted); - if (std::memcmp(&view, &none, sizeof(view)) != 0) { - std::fprintf(stderr, "castable RTVs: format %d {%d} took an RTV in unlisted format %d\n", - int(t.resource), int(t.listed), int(unlisted)); - return false; - } - ++refused; - } - } - std::printf("castable RTVs: %zu textures take their own and the listed format, and refuse %u formats their " - "lists don't name\n", std::size(textures), refused); - return true; -} -} // namespace - -// ClearDepthStencilView values at the edge of what D3D12 accepts: on a D32_FLOAT target a depth outside [0, 1] and a -// NaN are stored exactly as given, and flags that name no plane clear nothing (the target keeps the value of the clear -// before it). WARP shows both in the read-back, and the layer must show the same texels; a call the layer refuses fails -// Close() inside clear_depth_and_read. -bool check_depth_clear_edge_values(ID3D12Device* host, ID3D12Device* ours) { - constexpr UINT width = 5, height = 3; - const auto read = [](ID3D12Device* device, FLOAT depth_full, FLOAT depth_part, bool part_no_flags, - std::vector& depth) { - std::vector stencil; // D32_FLOAT has no stencil plane - return clear_depth_and_read(device, DXGI_FORMAT_D32_FLOAT, 4, false, depth_full, 0, depth_part, 0, depth, - stencil, D3D12_CLEAR_FLAG_DEPTH, D3D12_CLEAR_FLAGS(0), part_no_flags); - }; - const auto compare = [&](const char* what, FLOAT depth_full, FLOAT depth_part, bool part_no_flags, FLOAT outside, - FLOAT inside) { - std::vector expected, got; - if (!read(host, depth_full, depth_part, part_no_flags, expected)) return false; - if (!read(ours, depth_full, depth_part, part_no_flags, got)) return false; - CHECK(expected.size() == width * height * 4 && got.size() == expected.size()); - size_t wrong = 0; - for (UINT y = 0; y < height; ++y) - for (UINT x = 0; x < width; ++x) { - const size_t at = (width * y + x) * 4; - const FLOAT want = (x >= 1 && x < 4 && y >= 1) ? inside : outside; - if (std::memcmp(expected.data() + at, &want, 4)) { - FLOAT warp_value; - std::memcpy(&warp_value, expected.data() + at, 4); - std::fprintf(stderr, "%s (%u,%u): WARP cleared %g, expected %g\n", what, x, y, warp_value, want); - ++wrong; - } else if (std::memcmp(got.data() + at, expected.data() + at, 4)) { - FLOAT warp_value, layer_value; - std::memcpy(&warp_value, expected.data() + at, 4); - std::memcpy(&layer_value, got.data() + at, 4); - std::fprintf(stderr, "%s (%u,%u): layer cleared %g, WARP %g\n", what, x, y, layer_value, - warp_value); - ++wrong; - } - } - if (wrong) return false; - std::printf("%s: %ux%u depth texels match WARP\n", what, width, height); - return true; - }; - if (!compare("depth 1.5 and -0.5 are stored as given", 1.5f, -0.5f, false, 1.5f, -0.5f)) return false; - // NaN is likewise not clamped away; WARP stores the quiet NaN it was given. - const FLOAT nan = std::numeric_limits::quiet_NaN(); - if (!compare("a NaN depth stays NaN", nan, nan, false, nan, nan)) return false; - return compare("flags 0 leaves the target alone", 0.25f, 0.75f, true, 0.25f, 0.25f); -} - -int main(int argc, char** argv) { - const bool volume_only = argc == 2 && std::strcmp(argv[1], "--volume") == 0; - const bool rgb9e5_only = argc == 2 && std::strcmp(argv[1], "--rgb9e5") == 0; - if (argc != 1 && !volume_only && !rgb9e5_only) { - std::fprintf(stderr, "usage: d3d12_clear_test [--volume|--rgb9e5]\n"); - return 2; - } - vktest::Device vk; - const auto device_status = vk.initialize(); - if (device_status == vktest::DeviceStatus::unavailable) return 77; // no Vulkan GPU: ctest skips - if (device_status != vktest::DeviceStatus::ready) return 1; - const unsigned errors_before = vk.validation_errors(); - unsigned cases_checked = 0; - const auto compare = [&]() -> int { - Ref ours, host; - rt::d3d12::VulkanDeviceInfo info{}; - info.get_instance_proc = vk.instance_proc; - info.instance = vk.instance; - info.physical = vk.physical; - info.device = vk.device; - info.queue = vk.queue; - info.queue_family = vk.family; - if (FAILED(rt::d3d12::create_vulkan_device(info, IID_PPV_ARGS(&ours.p)))) return 1; - if (rgb9e5_only) { - D3D12_FEATURE_DATA_FORMAT_SUPPORT fs{DXGI_FORMAT_R9G9B9E5_SHAREDEXP}; - if (FAILED(ours->CheckFeatureSupport(D3D12_FEATURE_FORMAT_SUPPORT, &fs, sizeof(fs)))) return 1; - VkFormatProperties properties{}; - auto query = vk.instance_fn("vkGetPhysicalDeviceFormatProperties"); - query(vk.physical, VK_FORMAT_E5B9G9R9_UFLOAT_PACK32, &properties); - const bool native_rtv = properties.optimalTilingFeatures & VK_FORMAT_FEATURE_COLOR_ATTACHMENT_BIT; - if (native_rtv != bool(fs.Support1 & D3D12_FORMAT_SUPPORT1_RENDER_TARGET)) { - std::fprintf(stderr, "RGB9E5 render-target support disagrees with the native attachment capability\n"); - return 1; - } - if (!(fs.Support1 & D3D12_FORMAT_SUPPORT1_RENDER_TARGET)) { - std::puts("RGB9E5 render targets unavailable on this adapter"); - return 77; - } - return check_shared_exponent_target(ours.p) ? 0 : 1; - } - // Every readback below is compared with WARP, and Wine keeps no separate WARP (host_wine.h). The one check - // of the layer alone still runs there. - if (hostwine::host_is_wine()) { - if (!volume_only && !check_unlisted_rtvs(ours.p)) return 1; - return 77; - } - Ref factory; - Ref warp; - if (FAILED(CreateDXGIFactory1(IID_PPV_ARGS(&factory.p))) || - FAILED(factory->EnumWarpAdapter(IID_PPV_ARGS(&warp.p))) || - FAILED(D3D12CreateDevice(warp.p, D3D_FEATURE_LEVEL_11_0, IID_PPV_ARGS(&host.p)))) { - std::fprintf(stderr, "WARP reference unavailable: differential test cannot run\n"); - return 1; - } - if (!check_volume_rtvs(host.p, ours.p)) return 1; - if (volume_only) return 0; - if (!check_unlisted_rtvs(ours.p)) return 1; - if (!check_depth_clear_edge_values(host.p, ours.p)) return 1; - const float nan = std::numeric_limits::quiet_NaN(), inf = std::numeric_limits::infinity(); - // Integer-format values: negatives, fractions, NaN and overflow exercise the numeric float->int conversion. - const std::array int_values[] = { - {1, 2, 3, 4}, {1.5f, 2.5f, 3.5f, 4.5f}, {-1, -0.0f, 254.5f, 255.5f}, - {256, 65536, 16777216, 4294967296.0f}, {nan, inf, -inf, 0.5f}, - {0.499f, 0.501f, 1.499f, 1.501f}, {4294967040.0f, std::numeric_limits::max(), 255, 0}, - // Component-range boundaries for the 8-, 16-, 10- and 2-bit formats and the signed 32-bit limits. - {127.5f, 128, -128.5f, -129}, {32767.5f, 32768, -32768.5f, -32769}, - {65535.5f, 65536, 1023.5f, 1024}, {3.5f, 4, 2147483520.0f, -2147483648.0f} - }; - // Float-valued formats (UNORM/SNORM/FLOAT); out-of-range values exercise clamping. NaN/inf and SRGB are - // omitted: NaN/inf conversion is driver-defined, and the linear->sRGB encoding rounds differently at the .5 - // boundary on WARP vs Vulkan (a 1-ulp driver difference the shim cannot control). - const std::array float_values[] = { - {0, 0.25f, 0.5f, 1}, {1, 1, 1, 1}, {0.5f, 0.5f, 0.5f, 0.5f}, {-0.5f, 0, 1.5f, 2} - }; - struct ColorFormat { - DXGI_FORMAT format; const char* name; unsigned bytes; const std::array* values; unsigned count; - }; - const unsigned nf = unsigned(std::size(float_values)), ni = unsigned(std::size(int_values)); - const ColorFormat color_formats[] = { - {DXGI_FORMAT_R8G8B8A8_UNORM, "R8G8B8A8_UNORM", 4, float_values, nf}, - {DXGI_FORMAT_R8G8B8A8_SNORM, "R8G8B8A8_SNORM", 4, float_values, nf}, - // B8G8R8X8 is stored in a BGRA8 image; B8G8R8A8 next to it shows what the X byte changes. - {DXGI_FORMAT_B8G8R8A8_UNORM, "B8G8R8A8_UNORM", 4, float_values, nf}, - {DXGI_FORMAT_B8G8R8X8_UNORM, "B8G8R8X8_UNORM", 4, float_values, nf}, - {DXGI_FORMAT_R32G32B32A32_FLOAT, "R32G32B32A32_FLOAT", 16, float_values, nf}, - {DXGI_FORMAT_R8G8_UINT, "R8G8_UINT", 2, int_values, ni}, - {DXGI_FORMAT_R8G8B8A8_UINT, "R8G8B8A8_UINT", 4, int_values, ni}, - {DXGI_FORMAT_R16G16_UINT, "R16G16_UINT", 4, int_values, ni}, - {DXGI_FORMAT_R16G16B16A16_UINT, "R16G16B16A16_UINT", 8, int_values, ni}, - {DXGI_FORMAT_R32_UINT, "R32_UINT", 4, int_values, ni}, - {DXGI_FORMAT_R32G32_UINT, "R32G32_UINT", 8, int_values, ni}, - {DXGI_FORMAT_R32G32B32A32_UINT, "R32G32B32A32_UINT", 16, int_values, ni}, - {DXGI_FORMAT_R10G10B10A2_UINT, "R10G10B10A2_UINT", 4, int_values, ni}, - {DXGI_FORMAT_R8G8_SINT, "R8G8_SINT", 2, int_values, ni}, - {DXGI_FORMAT_R8G8B8A8_SINT, "R8G8B8A8_SINT", 4, int_values, ni}, - {DXGI_FORMAT_R16G16_SINT, "R16G16_SINT", 4, int_values, ni}, - {DXGI_FORMAT_R16G16B16A16_SINT, "R16G16B16A16_SINT", 8, int_values, ni}, - {DXGI_FORMAT_R32_SINT, "R32_SINT", 4, int_values, ni}, - {DXGI_FORMAT_R32G32_SINT, "R32G32_SINT", 8, int_values, ni}, - {DXGI_FORMAT_R32G32B32A32_SINT, "R32G32B32A32_SINT", 16, int_values, ni}, - }; - unsigned format_failures = 0; - for (const auto& cf : color_formats) { - for (unsigned i = 0; i < cf.count; ++i) { - // Different colours outside and inside the rectangle exercise both Vulkan clear paths. - const auto& full = cf.values[i]; - const auto& part = cf.values[(i + 1) % cf.count]; - std::vector actual, expected; - if (!clear_and_read(ours.p, cf.format, cf.bytes, full.data(), part.data(), actual) || - !clear_and_read(host.p, cf.format, cf.bytes, full.data(), part.data(), expected)) { - std::fprintf(stderr, "%s case %u: clear or readback failed\n", cf.name, i); - return 1; - } - if (actual != expected) { - for (std::size_t b = 0; b < actual.size(); ++b) { - if (actual[b] != expected[b]) { - std::fprintf(stderr, "%s case %u byte %zu: Vulkan %02x, WARP %02x\n", - cf.name, i, b, unsigned(actual[b]), unsigned(expected[b])); - break; - } - } - ++format_failures; - break; // first mismatch per format; keep checking the other formats - } - ++cases_checked; - } - } - // RTVs through a castable-format list in another channel order or family, or a typed BGRA8 texture's sRGB - // view: the clear is stored in the view's channel order and encoding, as WARP and AMD's D3D12 driver store - // it. An X8 view leaves its X byte undefined (WARP and AMD's driver differ), so it isn't compared. The bytes - // are compared within 1: drivers round the 0.5 tie differently (WARP 128, NVIDIA 127), and Intel's encodes - // sRGB 1 off WARP in places (its own D3D12 driver stores the same bytes as the layer there); a wrong channel - // order or a missing sRGB encoding is many steps off. - // A host that can't take a castable-format list (Windows 10's d3d12.dll has no ID3D12Device10; the in-box WARP - // 10.0.22621.5415 on Windows 11 23H2 reports RelaxedFormatCastingSupported = 0 and CreateCommittedResource3 - // fails) clears a texture in the view's own format instead: the bytes are stored in the view's channel order - // and encoding either way, so the expected readback is the same. The layer still goes through the list. - bool host_casts = false; - { - Ref host10; - D3D12_FEATURE_DATA_D3D12_OPTIONS12 options12{}; - host_casts = SUCCEEDED(host.p->QueryInterface(IID_PPV_ARGS(&host10.p))) && - SUCCEEDED(host.p->CheckFeatureSupport(D3D12_FEATURE_D3D12_OPTIONS12, &options12, - sizeof(options12))) && - options12.RelaxedFormatCastingSupported; - } - if (!host_casts) - std::printf("castable-format clears: host has no relaxed format casting; WARP clears the view's format\n"); - struct CastFormat { DXGI_FORMAT resource, view; const char* name; }; - const CastFormat cast_formats[] = { - {DXGI_FORMAT_R8G8B8A8_UNORM, DXGI_FORMAT_B8G8R8A8_UNORM, "R8G8B8A8_UNORM{B8G8R8A8_UNORM}"}, - {DXGI_FORMAT_B8G8R8A8_UNORM, DXGI_FORMAT_R8G8B8A8_UNORM, "B8G8R8A8_UNORM{R8G8B8A8_UNORM}"}, - {DXGI_FORMAT_R8G8B8A8_UNORM, DXGI_FORMAT_B8G8R8A8_UNORM_SRGB, "R8G8B8A8_UNORM{B8G8R8A8_UNORM_SRGB}"}, - {DXGI_FORMAT_B8G8R8A8_UNORM, DXGI_FORMAT_R8G8B8A8_UNORM_SRGB, "B8G8R8A8_UNORM{R8G8B8A8_UNORM_SRGB}"}, - {DXGI_FORMAT_B8G8R8A8_UNORM, DXGI_FORMAT_B8G8R8A8_UNORM_SRGB, "B8G8R8A8_UNORM{B8G8R8A8_UNORM_SRGB}"}, - {DXGI_FORMAT_B8G8R8A8_UNORM, DXGI_FORMAT_B8G8R8X8_UNORM, "B8G8R8A8_UNORM{B8G8R8X8_UNORM}"}, - {DXGI_FORMAT_B8G8R8X8_UNORM, DXGI_FORMAT_B8G8R8A8_UNORM, "B8G8R8X8_UNORM{B8G8R8A8_UNORM}"}, - {DXGI_FORMAT_R8G8B8A8_UNORM, DXGI_FORMAT_B8G8R8X8_UNORM, "R8G8B8A8_UNORM{B8G8R8X8_UNORM}"}, - }; - for (const auto& cf : cast_formats) { - for (unsigned i = 0; i < nf; ++i) { - const auto& full = float_values[i]; - const auto& part = float_values[(i + 1) % nf]; - std::vector actual, expected; - if (!clear_and_read(ours.p, cf.resource, 4, full.data(), part.data(), actual, false, cf.view) || - !(host_casts - ? clear_and_read(host.p, cf.resource, 4, full.data(), part.data(), expected, false, cf.view) - : clear_and_read(host.p, cf.view, 4, full.data(), part.data(), expected))) { - std::fprintf(stderr, "%s case %u: clear or readback failed\n", cf.name, i); - ++format_failures; - break; - } - if (cf.view == DXGI_FORMAT_B8G8R8X8_UNORM) { - for (std::size_t b = 3; b < actual.size() && b < expected.size(); b += 4) actual[b] = expected[b] = 0; - } - bool close = actual.size() == expected.size(); - std::size_t off = 0; - for (; close && off < actual.size(); ++off) - if (std::abs(int(actual[off]) - int(expected[off])) > 1) { close = false; break; } - if (!close) { - if (actual.size() == expected.size()) - std::fprintf(stderr, "%s case %u byte %zu: Vulkan %02x, WARP %02x\n", - cf.name, i, off, unsigned(actual[off]), unsigned(expected[off])); - else - std::fprintf(stderr, "%s case %u: readback sizes differ\n", cf.name, i); - ++format_failures; - break; - } - ++cases_checked; - } - } - // Color mismatches are reported at the end so depth/stencil and the validation counter still run. - // Depth (and stencil) clears, full and rectangle. Depth is [0,1]; stencil is a byte. - struct DepthFormat { DXGI_FORMAT format; unsigned depth_bytes; bool has_stencil; }; - const DepthFormat depth_formats[] = { - {DXGI_FORMAT_D32_FLOAT, 4, false}, - {DXGI_FORMAT_D16_UNORM, 2, false}, - {DXGI_FORMAT_D32_FLOAT_S8X24_UINT, 4, true}, - }; - const float depths[] = {0, 0.25f, 0.5f, 1}; - for (const auto& df : depth_formats) { - for (unsigned i = 0; i < std::size(depths); ++i) { - const float full = depths[i], part = depths[(i + 1) % std::size(depths)]; - const std::uint8_t stencil_full = std::uint8_t(i * 0x40 + 0x11); - const std::uint8_t stencil_part = std::uint8_t(i * 0x40 + 0x22); - std::vector actual, expected, actual_stencil, expected_stencil; - if (!clear_depth_and_read(ours.p, df.format, df.depth_bytes, df.has_stencil, full, stencil_full, part, - stencil_part, actual, actual_stencil) || - !clear_depth_and_read(host.p, df.format, df.depth_bytes, df.has_stencil, full, stencil_full, part, - stencil_part, expected, expected_stencil)) - return 1; - if (actual != expected || actual_stencil != expected_stencil) { - std::size_t b = 0; - while (b < actual.size() && b < expected.size() && actual[b] == expected[b]) ++b; - if (b < actual.size() && b < expected.size()) - std::fprintf(stderr, "depth format %d case %u byte %zu: Vulkan %02x, WARP %02x\n", - int(df.format), i, b, unsigned(actual[b]), unsigned(expected[b])); - else - std::fprintf(stderr, "depth format %d case %u: stencil readback mismatch\n", int(df.format), i); - ++format_failures; - break; // first mismatch per format; keep checking the other formats - } - ++cases_checked; - } - } - // D3D-437: STENCIL on a depth-only D32_FLOAT view. The PC runtime (WARP) ignores the absent plane: DEPTH | - // STENCIL clears the depth and STENCIL alone clears nothing; the layer used to drop the whole list instead. - struct PlaneCase { D3D12_CLEAR_FLAGS full, part; float depth_full, depth_part; }; - const PlaneCase plane_cases[] = { - {D3D12_CLEAR_FLAG_DEPTH | D3D12_CLEAR_FLAG_STENCIL, D3D12_CLEAR_FLAG_DEPTH, 0.5f, 0.875f}, - {D3D12_CLEAR_FLAG_DEPTH, D3D12_CLEAR_FLAG_STENCIL, 0.25f, 0.75f}, - {D3D12_CLEAR_FLAG_DEPTH, D3D12_CLEAR_FLAG_DEPTH | D3D12_CLEAR_FLAG_STENCIL, 0.375f, 1.0f}, - }; - for (unsigned i = 0; i < std::size(plane_cases); ++i) { - const auto& pc = plane_cases[i]; - std::vector actual, expected, no_stencil_a, no_stencil_e; - if (!clear_depth_and_read(ours.p, DXGI_FORMAT_D32_FLOAT, 4, false, pc.depth_full, 0x11, pc.depth_part, 0x22, - actual, no_stencil_a, pc.full, pc.part) || - !clear_depth_and_read(host.p, DXGI_FORMAT_D32_FLOAT, 4, false, pc.depth_full, 0x11, pc.depth_part, 0x22, - expected, no_stencil_e, pc.full, pc.part)) - return 1; - if (actual != expected) { - std::fprintf(stderr, "D32_FLOAT stencil-flag case %u: depth readback differs from WARP\n", i); - ++format_failures; - continue; - } - ++cases_checked; - } - if (format_failures) { - std::fprintf(stderr, "d3d12_clear_test: %u color/depth format(s) differ from WARP\n", format_failures); - return 1; - } - return 0; - }; // Destroy the D3D12 objects before checking the Vulkan validation counter. - const int compare_failed = compare(); - const auto validation_errors = vk.validation_errors() - errors_before; - if (validation_errors) - std::fprintf(stderr, "d3d12_clear_test: %llu new Vulkan validation error(s)\n", - static_cast(validation_errors)); - if (validation_errors) return 1; - if (compare_failed) return compare_failed; - if (volume_only || rgb9e5_only) return 0; - std::printf("RTV and DSV clears: %u full/rectangle readbacks matched WARP\n", cases_checked); - return 0; -} diff --git a/runtime/test/d3d12_close_parity_test.cpp b/runtime/test/d3d12_close_parity_test.cpp deleted file mode 100644 index 4e47a74c5..000000000 --- a/runtime/test/d3d12_close_parity_test.cpp +++ /dev/null @@ -1,578 +0,0 @@ -// What ID3D12GraphicsCommandList::Close returns after one recorded call, on the layer and on Windows' own D3D12 over -// WARP (no debug layer). Each case records its calls on a fresh allocator and direct list, then closes it; nothing is -// executed. The layer is held to WARP's verdict (Close succeeds or fails; the code is printed but not compared, since -// the layer answers every refused list with E_INVALIDARG where the PC runtime also uses E_FAIL). -// -// Where the two disagree today the case is marked as a known difference, and the test checks that the difference is -// still there: a change that makes such a case match fails here until its mark is removed, so the table stays an -// accurate list of the gap. Two kinds: -// layer_stricter WARP closes the list, the layer fails it. Since one failed list fails the whole -// ExecuteCommandLists, each of these drops a submission D3D12 would run. -// layer_looser WARP fails the list, the layer closes it. -// The `warp_ok` column is WARP's verdict as measured on Windows 11 26200 (d3d10warp.dll 10.0.26100.9818); it is -// the reference when no WARP device can be made (Wine, whose vkd3d answers differently, or a machine without WARP), -// and a live WARP answer that differs from it is printed. Calls that crash the PC runtime (ExecuteIndirect with a -// null command signature) are left out. No game data. -#include "vk_test_device.h" -#include "d3d12_test_shaders.h" -#include "host_wine.h" -#include "../shims/d3d12_com.h" - -#include - -#include -#include -#include -#include -#include - -#define CHECK(condition) do { \ - if (!(condition)) { std::fprintf(stderr, "line %d: %s\n", __LINE__, #condition); return false; } \ -} while (0) - -#define REQUIRE(condition) do { \ - if (!(condition)) { std::fprintf(stderr, "line %d: %s\n", __LINE__, #condition); return 1; } \ -} while (0) - -using namespace d3d12test; - -namespace { - -constexpr HRESULT not_run = HRESULT(0x7fff0000); // the case needs an interface the device does not give - -struct Env { - ID3D12Device* device = nullptr; - Ref buffer, upload, readback, target, target2, depth, msaa, tex, mips; - Ref rtv_heap, dsv_heap; - D3D12_CPU_DESCRIPTOR_HANDLE rtv{}, dsv{}; - Ref occlusion; - Ref closed_bundle_allocator; - Ref closed_bundle; - // The list being recorded, and the same list as ID3D12GraphicsCommandList2 (null when not given). - ID3D12GraphicsCommandList* list = nullptr; - ID3D12GraphicsCommandList2* list2 = nullptr; - - bool init(ID3D12Device* d) { - device = d; - const D3D12_HEAP_PROPERTIES default_heap{D3D12_HEAP_TYPE_DEFAULT}, upload_heap{D3D12_HEAP_TYPE_UPLOAD}, - readback_heap{D3D12_HEAP_TYPE_READBACK}; - const auto create = [&](const D3D12_HEAP_PROPERTIES& heap, const D3D12_RESOURCE_DESC& desc, - D3D12_RESOURCE_STATES state, Ref& out) { - return SUCCEEDED(device->CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &desc, state, nullptr, - IID_PPV_ARGS(&out.p))); - }; - const auto texture = [](DXGI_FORMAT format, D3D12_RESOURCE_FLAGS flags, UINT samples = 1, UINT16 mip_levels = 1, - UINT16 layers = 1) { - D3D12_RESOURCE_DESC desc{}; - desc.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D; - desc.Width = desc.Height = 64; - desc.DepthOrArraySize = layers; - desc.MipLevels = mip_levels; - desc.Format = format; - desc.SampleDesc.Count = samples; - desc.Flags = flags; - return desc; - }; - const DXGI_FORMAT rgba = DXGI_FORMAT_R8G8B8A8_UNORM; - CHECK(create(default_heap, buffer_desc(65536), D3D12_RESOURCE_STATE_COMMON, buffer)); - CHECK(create(upload_heap, buffer_desc(1 << 20), D3D12_RESOURCE_STATE_GENERIC_READ, upload)); - CHECK(create(readback_heap, buffer_desc(1 << 20), D3D12_RESOURCE_STATE_COPY_DEST, readback)); - CHECK(create(default_heap, texture(rgba, D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET), D3D12_RESOURCE_STATE_COMMON, - target)); - CHECK(create(default_heap, texture(rgba, D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET), D3D12_RESOURCE_STATE_COMMON, - target2)); - CHECK(create(default_heap, texture(rgba, D3D12_RESOURCE_FLAG_NONE), D3D12_RESOURCE_STATE_COMMON, tex)); - CHECK(create(default_heap, texture(rgba, D3D12_RESOURCE_FLAG_NONE, 1, 4, 3), D3D12_RESOURCE_STATE_COMMON, - mips)); - CHECK(create(default_heap, texture(DXGI_FORMAT_D32_FLOAT_S8X24_UINT, D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL), - D3D12_RESOURCE_STATE_DEPTH_WRITE, depth)); - CHECK(create(default_heap, texture(rgba, D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET, 4), - D3D12_RESOURCE_STATE_COMMON, msaa)); - const D3D12_DESCRIPTOR_HEAP_DESC rtv_desc{D3D12_DESCRIPTOR_HEAP_TYPE_RTV, 1, D3D12_DESCRIPTOR_HEAP_FLAG_NONE, - 0}; - const D3D12_DESCRIPTOR_HEAP_DESC dsv_desc{D3D12_DESCRIPTOR_HEAP_TYPE_DSV, 1, D3D12_DESCRIPTOR_HEAP_FLAG_NONE, - 0}; - CHECK(SUCCEEDED(device->CreateDescriptorHeap(&rtv_desc, IID_PPV_ARGS(&rtv_heap.p)))); - CHECK(SUCCEEDED(device->CreateDescriptorHeap(&dsv_desc, IID_PPV_ARGS(&dsv_heap.p)))); - rtv = rtv_heap->GetCPUDescriptorHandleForHeapStart(); - dsv = dsv_heap->GetCPUDescriptorHandleForHeapStart(); - device->CreateRenderTargetView(target.p, nullptr, rtv); - device->CreateDepthStencilView(depth.p, nullptr, dsv); - const D3D12_QUERY_HEAP_DESC query_desc{D3D12_QUERY_HEAP_TYPE_OCCLUSION, 8, 0}; - CHECK(SUCCEEDED(device->CreateQueryHeap(&query_desc, IID_PPV_ARGS(&occlusion.p)))); - CHECK(SUCCEEDED(device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_BUNDLE, - IID_PPV_ARGS(&closed_bundle_allocator.p)))); - CHECK(SUCCEEDED(device->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_BUNDLE, closed_bundle_allocator.p, - nullptr, IID_PPV_ARGS(&closed_bundle.p)))); - CHECK(SUCCEEDED(closed_bundle->Close())); - return true; - } -}; - -D3D12_RESOURCE_BARRIER barrier(ID3D12Resource* resource, D3D12_RESOURCE_STATES before, D3D12_RESOURCE_STATES after, - UINT subresource = D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES, - D3D12_RESOURCE_BARRIER_FLAGS flags = D3D12_RESOURCE_BARRIER_FLAG_NONE) { - D3D12_RESOURCE_BARRIER b = transition(resource, before, after); - b.Transition.Subresource = subresource; - b.Flags = flags; - return b; -} - -D3D12_TEXTURE_COPY_LOCATION subresource(ID3D12Resource* resource, UINT index) { - D3D12_TEXTURE_COPY_LOCATION location{}; - location.pResource = resource; - location.Type = D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX; - location.SubresourceIndex = index; - return location; -} - -D3D12_TEXTURE_COPY_LOCATION footprint(ID3D12Resource* resource, UINT64 offset, UINT row_pitch, - DXGI_FORMAT format = DXGI_FORMAT_R8G8B8A8_UNORM) { - D3D12_TEXTURE_COPY_LOCATION location{}; - location.pResource = resource; - location.Type = D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT; - location.PlacedFootprint.Offset = offset; - location.PlacedFootprint.Footprint = {format, 64, 64, 1, row_pitch}; - return location; -} - -enum class Known { match, layer_stricter, layer_looser }; - -// Records the case's calls on e.list; false when it needs an interface the device does not give. -using Recorder = std::function; - -struct Case { - const char* name; - bool warp_ok; // WARP's Close verdict, measured - Known known; - Recorder record; - // The case copies from a placed footprint whose offset or row pitch is not aligned: warp_ok and known are for - // a WARP that reports UnrestrictedBufferTextureCopyPitchSupported. One that does not must refuse the list. - bool unaligned_footprint = false; -}; - -#define CALLS(...) [](Env& e) { __VA_ARGS__; return true; } -#define RECORD_COPY(dst_location, x, src_location, box) do { \ - const auto d = dst_location; const auto s = src_location; e.list->CopyTextureRegion(&d, x, 0, 0, &s, box); \ -} while (0) - -constexpr auto common = D3D12_RESOURCE_STATE_COMMON; -constexpr auto copy_dest = D3D12_RESOURCE_STATE_COPY_DEST; -constexpr auto all = D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES; -constexpr auto begin_only = D3D12_RESOURCE_BARRIER_FLAG_BEGIN_ONLY; -constexpr auto end_only = D3D12_RESOURCE_BARRIER_FLAG_END_ONLY; -constexpr DXGI_FORMAT rgba = DXGI_FORMAT_R8G8B8A8_UNORM; -constexpr auto stricter = Known::layer_stricter; -constexpr auto looser = Known::layer_looser; -constexpr auto match = Known::match; - -std::vector cases() { - return { - {"empty list", true, match, [](Env&) { return true; }}, - {"ResourceBarrier(0, nullptr)", true, match, CALLS(e.list->ResourceBarrier(0, nullptr))}, - // Resource barriers - {"transition COMMON -> COMMON", false, looser, - CALLS(const auto b = barrier(e.tex.p, common, common); e.list->ResourceBarrier(1, &b))}, - {"transition COPY_DEST -> COPY_DEST", false, looser, - CALLS(const auto a = barrier(e.tex.p, common, copy_dest); - const auto b = barrier(e.tex.p, copy_dest, copy_dest); - e.list->ResourceBarrier(1, &a); e.list->ResourceBarrier(1, &b))}, - {"transition with BEGIN_ONLY | END_ONLY", false, match, - CALLS(const auto b = barrier(e.tex.p, common, copy_dest, all, begin_only | end_only); - e.list->ResourceBarrier(1, &b))}, - {"split transition: BEGIN_ONLY then END_ONLY", true, match, - CALLS(auto b = barrier(e.tex.p, common, copy_dest, all, begin_only); e.list->ResourceBarrier(1, &b); - b.Flags = end_only; e.list->ResourceBarrier(1, &b); - const auto c = barrier(e.tex.p, copy_dest, common); e.list->ResourceBarrier(1, &c))}, - {"split transition: END_ONLY without BEGIN_ONLY", true, match, - CALLS(const auto b = barrier(e.tex.p, common, copy_dest, all, end_only); e.list->ResourceBarrier(1, &b))}, - {"transition of a null resource", false, match, - CALLS(const auto b = barrier(nullptr, common, copy_dest); e.list->ResourceBarrier(1, &b))}, - {"transition of subresource 99 of a 1-subresource texture", false, looser, - CALLS(const auto b = barrier(e.tex.p, common, copy_dest, 99); e.list->ResourceBarrier(1, &b))}, - {"transition to COPY_DEST | COPY_SOURCE (write and read)", false, looser, - CALLS(const auto b = barrier(e.tex.p, common, copy_dest | D3D12_RESOURCE_STATE_COPY_SOURCE); - e.list->ResourceBarrier(1, &b))}, - {"UAV barrier of a null resource", true, match, - CALLS(D3D12_RESOURCE_BARRIER b{}; b.Type = D3D12_RESOURCE_BARRIER_TYPE_UAV; e.list->ResourceBarrier(1, &b))}, - {"UAV barrier with BEGIN_ONLY", false, match, - CALLS(D3D12_RESOURCE_BARRIER b{}; b.Type = D3D12_RESOURCE_BARRIER_TYPE_UAV; b.Flags = begin_only; - e.list->ResourceBarrier(1, &b))}, - {"aliasing barrier null -> null", true, match, - CALLS(D3D12_RESOURCE_BARRIER b{}; b.Type = D3D12_RESOURCE_BARRIER_TYPE_ALIASING; - e.list->ResourceBarrier(1, &b))}, - {"barrier type 7", false, match, - CALLS(D3D12_RESOURCE_BARRIER b{}; b.Type = D3D12_RESOURCE_BARRIER_TYPE(7); e.list->ResourceBarrier(1, &b))}, - // CopyBufferRegion - {"CopyBufferRegion of 0 bytes", true, match, CALLS(e.list->CopyBufferRegion(e.buffer.p, 0, e.upload.p, 0, 0))}, - {"CopyBufferRegion past the end of the destination", false, looser, - CALLS(e.list->CopyBufferRegion(e.buffer.p, 65000, e.upload.p, 0, 4096))}, - {"CopyBufferRegion within one buffer, disjoint", true, match, - CALLS(e.list->CopyBufferRegion(e.buffer.p, 0, e.buffer.p, 4096, 1024))}, - {"CopyBufferRegion within one buffer, overlapping", true, match, - CALLS(e.list->CopyBufferRegion(e.buffer.p, 0, e.buffer.p, 512, 1024))}, - {"CopyBufferRegion from a null source", false, match, - CALLS(e.list->CopyBufferRegion(e.buffer.p, 0, nullptr, 0, 16))}, - {"CopyBufferRegion into a texture", false, looser, - CALLS(e.list->CopyBufferRegion(e.tex.p, 0, e.upload.p, 0, 16))}, - // CopyTextureRegion - {"CopyTextureRegion upload, offset 0, row pitch 256", true, match, - CALLS(RECORD_COPY(subresource(e.tex.p, 0), 0, footprint(e.upload.p, 0, 256), nullptr))}, - {"CopyTextureRegion upload, offset 16 (not 512-aligned)", true, stricter, - CALLS(RECORD_COPY(subresource(e.tex.p, 0), 0, footprint(e.upload.p, 16, 256), nullptr)), true}, - {"CopyTextureRegion upload, offset 4 (not 512-aligned)", true, stricter, - CALLS(RECORD_COPY(subresource(e.tex.p, 0), 0, footprint(e.upload.p, 4, 256), nullptr)), true}, - {"CopyTextureRegion upload, row pitch 260 (not 256-aligned)", true, stricter, - CALLS(RECORD_COPY(subresource(e.tex.p, 0), 0, footprint(e.upload.p, 0, 260), nullptr)), true}, - {"CopyTextureRegion upload, row pitch 128 (shorter than a row)", false, match, - CALLS(RECORD_COPY(subresource(e.tex.p, 0), 0, footprint(e.upload.p, 0, 128), nullptr))}, - {"CopyTextureRegion upload, footprint format UNKNOWN", false, looser, - CALLS(RECORD_COPY(subresource(e.tex.p, 0), 0, footprint(e.upload.p, 0, 256, DXGI_FORMAT_UNKNOWN), nullptr))}, - {"CopyTextureRegion upload, footprint R32_FLOAT into RGBA8", false, looser, - CALLS(RECORD_COPY(subresource(e.tex.p, 0), 0, footprint(e.upload.p, 0, 256, DXGI_FORMAT_R32_FLOAT), nullptr))}, - {"CopyTextureRegion upload, footprint RGBA8_SRGB into RGBA8", true, match, - CALLS(RECORD_COPY(subresource(e.tex.p, 0), 0, - footprint(e.upload.p, 0, 256, DXGI_FORMAT_R8G8B8A8_UNORM_SRGB), nullptr))}, - {"CopyTextureRegion upload with an empty box", true, match, - CALLS(const D3D12_BOX box{4, 4, 0, 4, 8, 1}; - RECORD_COPY(subresource(e.tex.p, 0), 0, footprint(e.upload.p, 0, 256), &box))}, - {"CopyTextureRegion upload with an inverted box", true, match, - CALLS(const D3D12_BOX box{8, 4, 0, 4, 8, 1}; - RECORD_COPY(subresource(e.tex.p, 0), 0, footprint(e.upload.p, 0, 256), &box))}, - {"CopyTextureRegion upload past the texture's edge (x 32 of 64)", false, looser, - CALLS(RECORD_COPY(subresource(e.tex.p, 0), 32, footprint(e.upload.p, 0, 256), nullptr))}, - {"CopyTextureRegion into a readback footprint", true, match, - CALLS(RECORD_COPY(footprint(e.readback.p, 0, 256), 0, subresource(e.tex.p, 0), nullptr))}, - {"CopyTextureRegion footprint to footprint", true, stricter, - CALLS(RECORD_COPY(footprint(e.readback.p, 0, 256), 0, footprint(e.upload.p, 0, 256), nullptr))}, - {"CopyTextureRegion into subresource 5 of a 1-subresource texture", false, looser, - CALLS(RECORD_COPY(subresource(e.tex.p, 5), 0, footprint(e.upload.p, 0, 256), nullptr))}, - {"CopyTextureRegion between two subresources of one texture", true, match, - CALLS(RECORD_COPY(subresource(e.mips.p, 1), 0, subresource(e.mips.p, 5), nullptr))}, - {"CopyTextureRegion within one subresource, disjoint", true, match, - CALLS(const D3D12_BOX box{0, 0, 0, 8, 8, 1}; - RECORD_COPY(subresource(e.tex.p, 0), 32, subresource(e.tex.p, 0), &box))}, - {"CopyTextureRegion into a null location", false, match, - CALLS(const auto s = subresource(e.tex.p, 0); e.list->CopyTextureRegion(nullptr, 0, 0, 0, &s, nullptr))}, - // CopyResource - {"CopyResource with the destination as the source", true, match, - CALLS(e.list->CopyResource(e.tex.p, e.tex.p))}, - {"CopyResource buffer to texture", true, match, CALLS(e.list->CopyResource(e.tex.p, e.buffer.p))}, - {"CopyResource between buffers of different sizes", false, looser, - CALLS(e.list->CopyResource(e.upload.p, e.buffer.p))}, - {"CopyResource texture to texture", true, match, CALLS(e.list->CopyResource(e.target2.p, e.target.p))}, - // Clears and discards - {"ClearRenderTargetView with an inverted rectangle", true, match, - CALLS(const FLOAT red[4] = {1, 0, 0, 1}; const D3D12_RECT r{10, 10, 5, 5}; - e.list->ClearRenderTargetView(e.rtv, red, 1, &r))}, - {"ClearRenderTargetView with a rectangle past the target", true, match, - CALLS(const FLOAT red[4] = {1, 0, 0, 1}; const D3D12_RECT r{-8, -8, 4096, 4096}; - e.list->ClearRenderTargetView(e.rtv, red, 1, &r))}, - {"ClearRenderTargetView with NaN, infinite and negative channels", true, match, - CALLS(const FLOAT c[4] = {std::numeric_limits::quiet_NaN(), std::numeric_limits::infinity(), - -1, 2}; - e.list->ClearRenderTargetView(e.rtv, c, 0, nullptr))}, - // A depth outside [0, 1] (NaN included) is stored as given and a clear that names no plane clears nothing: - // WARP closes both lists (d3d12_clear_test reads the texels back). - {"ClearDepthStencilView with flags 0", true, match, - CALLS(e.list->ClearDepthStencilView(e.dsv, D3D12_CLEAR_FLAGS(0), 1, 0, 0, nullptr))}, - {"ClearDepthStencilView depth 1.5", true, match, - CALLS(e.list->ClearDepthStencilView(e.dsv, D3D12_CLEAR_FLAG_DEPTH, 1.5f, 0, 0, nullptr))}, - {"ClearDepthStencilView depth -0.5", true, match, - CALLS(e.list->ClearDepthStencilView(e.dsv, D3D12_CLEAR_FLAG_DEPTH, -0.5f, 0, 0, nullptr))}, - {"ClearDepthStencilView depth NaN", true, match, - CALLS(e.list->ClearDepthStencilView(e.dsv, D3D12_CLEAR_FLAG_DEPTH, - std::numeric_limits::quiet_NaN(), 0, 0, - nullptr))}, - {"ClearDepthStencilView stencil only, depth 7 (not used)", true, match, - CALLS(e.list->ClearDepthStencilView(e.dsv, D3D12_CLEAR_FLAG_STENCIL, 7.0f, 3, 0, nullptr))}, - {"ClearDepthStencilView with flags 7 (an unknown bit)", true, stricter, - CALLS(e.list->ClearDepthStencilView(e.dsv, D3D12_CLEAR_FLAGS(7), 1, 0, 0, nullptr))}, - {"DiscardResource with no region", true, match, CALLS(e.list->DiscardResource(e.target.p, nullptr))}, - {"DiscardResource of 0 subresources", true, match, - CALLS(const D3D12_DISCARD_REGION r{0, nullptr, 0, 0}; e.list->DiscardResource(e.target.p, &r))}, - {"DiscardResource of a texture that is no target", true, match, - CALLS(e.list->DiscardResource(e.tex.p, nullptr))}, - // ResolveSubresource - {"ResolveSubresource 4x -> 1x", true, match, - CALLS(e.list->ResolveSubresource(e.target.p, 0, e.msaa.p, 0, rgba))}, - {"ResolveSubresource with format UNKNOWN", false, looser, - CALLS(e.list->ResolveSubresource(e.target.p, 0, e.msaa.p, 0, DXGI_FORMAT_UNKNOWN))}, - {"ResolveSubresource as RGBA8_SRGB of RGBA8 textures", true, match, - CALLS(e.list->ResolveSubresource(e.target.p, 0, e.msaa.p, 0, DXGI_FORMAT_R8G8B8A8_UNORM_SRGB))}, - {"ResolveSubresource as R32_FLOAT of RGBA8 textures", false, looser, - CALLS(e.list->ResolveSubresource(e.target.p, 0, e.msaa.p, 0, DXGI_FORMAT_R32_FLOAT))}, - {"ResolveSubresource from a single-sampled texture", false, looser, - CALLS(e.list->ResolveSubresource(e.target.p, 0, e.target2.p, 0, rgba))}, - {"ResolveSubresource with the destination as the source", false, match, - CALLS(e.list->ResolveSubresource(e.msaa.p, 0, e.msaa.p, 0, rgba))}, - // Input assembler, rasterizer, output merger - {"IASetVertexBuffers(30, 4): slots past 31", true, stricter, - CALLS(const D3D12_VERTEX_BUFFER_VIEW v[4] = {}; e.list->IASetVertexBuffers(30, 4, v))}, - {"IASetVertexBuffers(0, 0, nullptr)", true, match, CALLS(e.list->IASetVertexBuffers(0, 0, nullptr))}, - {"IASetIndexBuffer(nullptr)", true, match, CALLS(e.list->IASetIndexBuffer(nullptr))}, - {"IASetIndexBuffer as R16_UINT", true, match, - CALLS(const D3D12_INDEX_BUFFER_VIEW v{e.buffer->GetGPUVirtualAddress(), 64, DXGI_FORMAT_R16_UINT}; - e.list->IASetIndexBuffer(&v))}, - {"IASetIndexBuffer as R32_UINT", true, match, - CALLS(const D3D12_INDEX_BUFFER_VIEW v{e.buffer->GetGPUVirtualAddress(), 64, DXGI_FORMAT_R32_UINT}; - e.list->IASetIndexBuffer(&v))}, - {"IASetIndexBuffer as UNKNOWN, size 0", true, match, - CALLS(const D3D12_INDEX_BUFFER_VIEW v{0, 0, DXGI_FORMAT_UNKNOWN}; e.list->IASetIndexBuffer(&v))}, - {"IASetIndexBuffer as UNKNOWN, size 64", true, match, - CALLS(const D3D12_INDEX_BUFFER_VIEW v{e.buffer->GetGPUVirtualAddress(), 64, DXGI_FORMAT_UNKNOWN}; - e.list->IASetIndexBuffer(&v))}, - {"IASetIndexBuffer as R8_UINT", true, match, - CALLS(const D3D12_INDEX_BUFFER_VIEW v{e.buffer->GetGPUVirtualAddress(), 64, DXGI_FORMAT_R8_UINT}; - e.list->IASetIndexBuffer(&v))}, - {"IASetIndexBuffer as R32_FLOAT", true, match, - CALLS(const D3D12_INDEX_BUFFER_VIEW v{e.buffer->GetGPUVirtualAddress(), 64, DXGI_FORMAT_R32_FLOAT}; - e.list->IASetIndexBuffer(&v))}, - {"IASetPrimitiveTopology(UNDEFINED)", true, match, - CALLS(e.list->IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_UNDEFINED))}, - {"IASetPrimitiveTopology(TRIANGLELIST)", true, match, - CALLS(e.list->IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST))}, - {"IASetPrimitiveTopology(7) (gap value)", true, match, - CALLS(e.list->IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY(7)))}, - {"IASetPrimitiveTopology(32_CONTROL_POINT_PATCHLIST)", true, match, - CALLS(e.list->IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_32_CONTROL_POINT_PATCHLIST))}, - {"IASetPrimitiveTopology(65) (past 32-cp patch)", true, match, - CALLS(e.list->IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY(65)))}, - {"IASetPrimitiveTopology(99)", true, match, CALLS(e.list->IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY(99)))}, - {"OMSetBlendFactor", true, match, - CALLS(const FLOAT factor[4] = {0.25f, 0.5f, 0.75f, 1.0f}; e.list->OMSetBlendFactor(factor))}, - {"OMSetStencilRef(7)", true, match, CALLS(e.list->OMSetStencilRef(7))}, - {"ExecuteBundle after post-close state calls on bundle", true, match, - CALLS(const FLOAT factor[4] = {0.25f, 0.5f, 0.75f, 1.0f}; - e.closed_bundle->IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST); - e.closed_bundle->IASetIndexBuffer(nullptr); - e.closed_bundle->OMSetBlendFactor(factor); - e.closed_bundle->OMSetStencilRef(9); - e.closed_bundle->ClearState(nullptr); - e.list->ExecuteBundle(e.closed_bundle.p))}, - {"RSSetViewports(0, nullptr)", true, match, CALLS(e.list->RSSetViewports(0, nullptr))}, - {"RSSetViewports(17)", true, stricter, - CALLS(D3D12_VIEWPORT v[17]; for (auto& x : v) x = {0, 0, 8, 8, 0, 1}; e.list->RSSetViewports(17, v))}, - {"RSSetViewports with MinDepth -1", true, match, - CALLS(const D3D12_VIEWPORT v{0, 0, 8, 8, -1, 1}; e.list->RSSetViewports(1, &v))}, - {"RSSetViewports with a negative width", true, match, - CALLS(const D3D12_VIEWPORT v{0, 0, -8, 8, 0, 1}; e.list->RSSetViewports(1, &v))}, - {"RSSetViewports with a negative height", true, match, - CALLS(const D3D12_VIEWPORT v{0, 8, 8, -8, 0, 1}; e.list->RSSetViewports(1, &v))}, - {"RSSetViewports at x -40000", true, match, - CALLS(const D3D12_VIEWPORT v{-40000, 0, 8, 8, 0, 1}; e.list->RSSetViewports(1, &v))}, - {"RSSetScissorRects(0, nullptr)", true, match, CALLS(e.list->RSSetScissorRects(0, nullptr))}, - {"RSSetScissorRects(17)", true, match, CALLS(const D3D12_RECT r[17] = {}; e.list->RSSetScissorRects(17, r))}, - {"RSSetScissorRects inverted", true, match, - CALLS(const D3D12_RECT r{10, 10, 5, 5}; e.list->RSSetScissorRects(1, &r))}, - {"OMSetRenderTargets(9)", false, match, - CALLS(D3D12_CPU_DESCRIPTOR_HANDLE h[9]; for (auto& x : h) x = e.rtv; - e.list->OMSetRenderTargets(9, h, FALSE, nullptr))}, - {"OMSetRenderTargets(0, nullptr, depth)", true, match, - CALLS(e.list->OMSetRenderTargets(0, nullptr, FALSE, &e.dsv))}, - // Draws, dispatches and root arguments with nothing set - {"DrawInstanced(3) with nothing set", true, stricter, CALLS(e.list->DrawInstanced(3, 1, 0, 0))}, - {"DrawInstanced(0) with nothing set", true, stricter, CALLS(e.list->DrawInstanced(0, 1, 0, 0))}, - {"Dispatch(1, 1, 1) with nothing set", true, stricter, CALLS(e.list->Dispatch(1, 1, 1))}, - {"Dispatch(0, 0, 0) with nothing set", true, stricter, CALLS(e.list->Dispatch(0, 0, 0))}, - {"SetGraphicsRoot32BitConstant before a root signature", true, stricter, - CALLS(e.list->SetGraphicsRoot32BitConstant(0, 1, 0))}, - {"SetGraphicsRootConstantBufferView before a root signature", true, stricter, - CALLS(e.list->SetGraphicsRootConstantBufferView(0, e.buffer->GetGPUVirtualAddress()))}, - {"SetGraphicsRootDescriptorTable before a root signature", true, stricter, - CALLS(e.list->SetGraphicsRootDescriptorTable(0, {}))}, - {"SetGraphicsRootSignature(nullptr)", true, match, CALLS(e.list->SetGraphicsRootSignature(nullptr))}, - {"SetDescriptorHeaps(0, nullptr)", true, match, CALLS(e.list->SetDescriptorHeaps(0, nullptr))}, - {"ClearState(nullptr)", true, match, CALLS(e.list->ClearState(nullptr))}, - // Predication and queries - {"SetPredication(nullptr)", true, match, - CALLS(e.list->SetPredication(nullptr, 0, D3D12_PREDICATION_OP_EQUAL_ZERO))}, - {"SetPredication at offset 4", false, match, - CALLS(e.list->SetPredication(e.buffer.p, 4, D3D12_PREDICATION_OP_EQUAL_ZERO); - e.list->SetPredication(nullptr, 0, D3D12_PREDICATION_OP_EQUAL_ZERO))}, - {"SetPredication with operation 7", false, match, - CALLS(e.list->SetPredication(e.buffer.p, 0, D3D12_PREDICATION_OP(7)); - e.list->SetPredication(nullptr, 0, D3D12_PREDICATION_OP_EQUAL_ZERO))}, - {"BeginQuery without EndQuery", false, match, - CALLS(e.list->BeginQuery(e.occlusion.p, D3D12_QUERY_TYPE_OCCLUSION, 0))}, - {"EndQuery without BeginQuery", false, match, - CALLS(e.list->EndQuery(e.occlusion.p, D3D12_QUERY_TYPE_OCCLUSION, 0))}, - {"BeginQuery twice on one index", false, match, - CALLS(e.list->BeginQuery(e.occlusion.p, D3D12_QUERY_TYPE_OCCLUSION, 0); - e.list->BeginQuery(e.occlusion.p, D3D12_QUERY_TYPE_OCCLUSION, 0); - e.list->EndQuery(e.occlusion.p, D3D12_QUERY_TYPE_OCCLUSION, 0))}, - {"BeginQuery and EndQuery at index 100 of 8", false, looser, - CALLS(e.list->BeginQuery(e.occlusion.p, D3D12_QUERY_TYPE_OCCLUSION, 100); - e.list->EndQuery(e.occlusion.p, D3D12_QUERY_TYPE_OCCLUSION, 100))}, - {"BeginQuery OCCLUSION, EndQuery BINARY_OCCLUSION", true, stricter, - CALLS(e.list->BeginQuery(e.occlusion.p, D3D12_QUERY_TYPE_OCCLUSION, 0); - e.list->EndQuery(e.occlusion.p, D3D12_QUERY_TYPE_BINARY_OCCLUSION, 0))}, - {"ResolveQueryData of 0 queries", true, match, - CALLS(e.list->ResolveQueryData(e.occlusion.p, D3D12_QUERY_TYPE_OCCLUSION, 0, 0, e.readback.p, 0))}, - {"ResolveQueryData at offset 4", false, match, - CALLS(e.list->ResolveQueryData(e.occlusion.p, D3D12_QUERY_TYPE_OCCLUSION, 0, 1, e.readback.p, 4))}, - {"ResolveQueryData of a query never begun", true, match, - CALLS(e.list->ResolveQueryData(e.occlusion.p, D3D12_QUERY_TYPE_OCCLUSION, 3, 1, e.readback.p, 0))}, - // Markers and immediate writes - {"EndEvent without BeginEvent", true, match, CALLS(e.list->EndEvent())}, - {"SetMarker(0, nullptr, 0)", true, match, CALLS(e.list->SetMarker(0, nullptr, 0))}, - {"WriteBufferImmediate of 0 values", true, match, - [](Env& e) { - if (!e.list2) return false; - e.list2->WriteBufferImmediate(0, nullptr, nullptr); - return true; - }}, - {"WriteBufferImmediate at an address that is not 4-aligned", true, stricter, - [](Env& e) { - if (!e.list2) return false; - const D3D12_WRITEBUFFERIMMEDIATE_PARAMETER p{e.buffer->GetGPUVirtualAddress() + 2, 7}; - e.list2->WriteBufferImmediate(1, &p, nullptr); - return true; - }}, - }; -} - -// Records one case on a fresh allocator and list of `env`'s device and returns what Close says. -bool run_case(Env& env, const Case& c, HRESULT& close) { - Ref allocator; - Ref list; - Ref list2; - CHECK(SUCCEEDED(env.device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&allocator.p)))); - CHECK(SUCCEEDED(env.device->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, allocator.p, nullptr, - IID_PPV_ARGS(&list.p)))); - if (FAILED(list->QueryInterface(IID_PPV_ARGS(&list2.p)))) list2.p = nullptr; - env.list = list.p; - env.list2 = list2.p; - const bool recorded = c.record(env); - close = recorded ? list->Close() : not_run; - if (!recorded) list->Close(); - env.list = nullptr; - env.list2 = nullptr; - return true; -} - -std::string text(HRESULT hr) { - if (hr == not_run) return "n/a"; - char out[16]; - std::snprintf(out, sizeof(out), "0x%08lx", static_cast(hr)); - return out; -} - -} // namespace - -int main() { - std::setvbuf(stdout, nullptr, _IONBF, 0); - vktest::Device vk; - const auto device_status = vk.initialize(); - if (device_status == vktest::DeviceStatus::unavailable) { - std::fprintf(stderr, "SKIP: no usable Vulkan 1.3 device\n"); - return 77; - } - REQUIRE(device_status == vktest::DeviceStatus::ready); - const auto table = cases(); - const unsigned errors_before = vk.validation_errors(); - - std::vector layer(table.size(), not_run), warp(table.size(), not_run); - { - rt::d3d12::VulkanDeviceInfo info{}; - info.get_instance_proc = vk.instance_proc; - info.instance = vk.instance; - info.physical = vk.physical; - info.device = vk.device; - info.queue = vk.queue; - info.queue_family = vk.family; - info.buffer_device_address = true; - Ref ours; - REQUIRE(SUCCEEDED(rt::d3d12::create_vulkan_device(info, IID_PPV_ARGS(&ours.p)))); - Env env; - REQUIRE(env.init(ours.p)); - for (std::size_t i = 0; i < table.size(); ++i) REQUIRE(run_case(env, table[i], layer[i])); - } - - bool warp_ran = false; - // Whether the live WARP reports UnrestrictedBufferTextureCopyPitchSupported; an older runtime that does not know - // D3D12_FEATURE_D3D12_OPTIONS13 answers E_INVALIDARG, which counts as not reported. - bool warp_unrestricted_pitch = false; - if (!hostwine::host_is_wine()) { - Ref factory; - Ref adapter; - Ref host; - if (SUCCEEDED(CreateDXGIFactory1(IID_PPV_ARGS(&factory.p))) && - SUCCEEDED(factory->EnumWarpAdapter(IID_PPV_ARGS(&adapter.p))) && - SUCCEEDED(D3D12CreateDevice(adapter.p, D3D_FEATURE_LEVEL_11_0, IID_PPV_ARGS(&host.p)))) { - Env env; - REQUIRE(env.init(host.p)); - for (std::size_t i = 0; i < table.size(); ++i) REQUIRE(run_case(env, table[i], warp[i])); - D3D12_FEATURE_DATA_D3D12_OPTIONS13 options13{}; - warp_unrestricted_pitch = - SUCCEEDED(host->CheckFeatureSupport(D3D12_FEATURE_D3D12_OPTIONS13, &options13, sizeof(options13))) && - options13.UnrestrictedBufferTextureCopyPitchSupported; - // Nothing is executed, so nothing should remove the device; if something did, its answers are suspect. - REQUIRE(host->GetDeviceRemovedReason() == S_OK); - warp_ran = true; - } else { - std::printf("no WARP device: the layer is compared with the measured WARP column\n"); - } - } - - unsigned failures = 0, matched = 0, known_stricter = 0, known_looser = 0, warp_changed = 0, skipped = 0; - unsigned aligned_only = 0; // unaligned-footprint cases a WARP without the unrestricted-pitch capability refuses - std::printf("%-62s | %-10s | %-10s | %s\n", "case", "layer", "WARP", "expected"); - for (std::size_t i = 0; i < table.size(); ++i) { - const Case& c = table[i]; - const bool live = warp_ran && warp[i] != not_run; - // D3D12 wants a placed footprint's offset a multiple of 512 and its row pitch a multiple of 256 unless the - // device reports UnrestrictedBufferTextureCopyPitchSupported. A WARP that does not report it refuses the - // list (d3d10warp.dll 10.0.19041.3636 on Windows 10 22H2: Close is E_INVALIDARG), which is what the layer - // does, so the difference the table records does not exist there and the layer has to agree. - const bool aligned_only_warp = c.unaligned_footprint && live && !warp_unrestricted_pitch && FAILED(warp[i]); - const Known known = aligned_only_warp ? Known::match : c.known; - const char* expected = known == Known::match ? "match" - : known == Known::layer_stricter ? "layer stricter (known)" - : "layer looser (known)"; - std::printf("%-62s | %-10s | %-10s | %s\n", c.name, text(layer[i]).c_str(), - live ? text(warp[i]).c_str() : (c.warp_ok ? "(S_OK)" : "(failure)"), expected); - if (layer[i] == not_run) { - ++skipped; - continue; - } - if (live && SUCCEEDED(warp[i]) != c.warp_ok) { - std::printf(" WARP's verdict here differs from the measured column (%s): compared with the live answer\n", - c.warp_ok ? "S_OK" : "a failure"); - ++warp_changed; - } - if (aligned_only_warp) { - std::printf(" this WARP does not report UnrestrictedBufferTextureCopyPitchSupported and refuses the " - "list, so the layer has to agree with it\n"); - ++aligned_only; - } - const bool reference_ok = live ? SUCCEEDED(warp[i]) : c.warp_ok; - const bool layer_ok = SUCCEEDED(layer[i]); - const bool want_layer_ok = known == Known::match ? reference_ok : !reference_ok; - if (layer_ok != want_layer_ok) { - if (known == Known::match) - std::fprintf(stderr, "FAIL %s: layer Close %s, WARP %s\n", c.name, text(layer[i]).c_str(), - reference_ok ? "succeeds" : "fails"); - else - std::fprintf(stderr, "FAIL %s: now matches WARP; mark it Known::match in the table\n", c.name); - ++failures; - continue; - } - if (known == Known::match) ++matched; - else if (known == Known::layer_stricter) ++known_stricter; - else ++known_looser; - } - const unsigned validation_errors = vk.validation_errors() - errors_before; - if (validation_errors) { - std::fprintf(stderr, "%u Vulkan validation errors\n", validation_errors); - ++failures; - } - if (aligned_only) - std::printf("close parity: %u unaligned-footprint cases counted as matches, not as known layer-stricter: this " - "WARP does not report UnrestrictedBufferTextureCopyPitchSupported\n", aligned_only); - std::printf("close parity: %zu cases, %u match %s, %u known layer-stricter, %u known layer-looser, %u not run, " - "%u where WARP differs from the measured column, %u failures\n", - table.size(), matched, warp_ran ? "WARP" : "the measured WARP column", known_stricter, known_looser, - skipped, warp_changed, failures); - return failures ? 1 : 0; -} diff --git a/runtime/test/d3d12_com_test.cpp b/runtime/test/d3d12_com_test.cpp deleted file mode 100644 index d1d4bf3a6..000000000 --- a/runtime/test/d3d12_com_test.cpp +++ /dev/null @@ -1,413 +0,0 @@ -// End to end through the D3D12 COM surface: an ID3D12GraphicsCommandList7 records clears (whole and rectangles), -// legacy and enhanced barriers; an ID3D12CommandQueue executes it on Vulkan behind a queue Wait on a fence the CPU -// signals later; an ID3D12Fence1 event reports completion; the images are read back. No shaders or game data. -// Set LEONIDA_VK_VALIDATION=1 to run under VK_LAYER_KHRONOS_validation; any validation error fails the test. -#include "vk_test_device.h" -#include "../shims/d3d12_com.h" -#include "../shims/d3d12_trace.h" -#include "../src/gfx10_descriptors.h" - -#include -#include -#include - -#define EXPECT(condition) do { \ - if (!(condition)) { std::fprintf(stderr, "line %d: %s\n", __LINE__, #condition); return 1; } \ -} while (0) - -namespace { - -template -struct Ref { - T* p = nullptr; - ~Ref() { - if (p) p->Release(); - } - T* operator->() const { return p; } - void** out() { return reinterpret_cast(&p); } -}; - -} // namespace - -static_assert(std::is_move_constructible_v); -static_assert(std::is_move_assignable_v); -static_assert(sizeof(leonida::DrawViews::render_targets) == sizeof(leonida::TargetView) * 8); -static_assert(sizeof(leonida::DrawViews::vertex_buffers) == sizeof(leonida::VertexBufferView) * 32); -// The views stay out of the variant: a recorded command is sized by its largest member, Draw included. -static_assert(sizeof(leonida::Draw) < sizeof(leonida::DrawViews)); - -int main(int argc, char** argv) { - if (argc == 2 && std::strcmp(argv[1], "--trace-d3d12") == 0) rt::d3d12_trace::set_enabled(true); - else if (argc != 1) return 2; - using namespace leonida; - vktest::Device d; - const auto device_status = d.initialize(); - if (device_status == vktest::DeviceStatus::unavailable) return 77; // no Vulkan GPU: ctest skips - if (device_status != vktest::DeviceStatus::ready) return 1; - VulkanContext context(d.device_proc, d.device, true); - EXPECT(context.loaded()); - - constexpr std::uint32_t size = 4, texels = size * size; - const VkImage rt = d.image(VK_FORMAT_R8G8B8A8_UNORM, size, size, 1, VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT); - const VkImage ds = d.image(VK_FORMAT_D32_SFLOAT_S8_UINT, size, size, 1, VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT); - void* mapped = nullptr; - constexpr VkDeviceSize depth_offset = texels * 4, stencil_offset = depth_offset + texels * 4; - const VkBuffer buffer = d.buffer(stencil_offset + texels, VK_BUFFER_USAGE_TRANSFER_DST_BIT, &mapped); - EXPECT(rt && ds && buffer && d.depth_format_usable(VK_FORMAT_D32_SFLOAT_S8_UINT)); - EXPECT(d.run([&](VkCommandBuffer cb) { - d.initial_layout(cb, rt, VK_IMAGE_ASPECT_COLOR_BIT, 1, VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL); - d.initial_layout(cb, ds, depth_stencil_aspects, 1, VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL); - return true; - })); - - // Stand-ins for the device: resources are identified by their ID3D12Resource pointer, which the layer never - // dereferences, and RTV/DSV handles point at TargetViews. - auto* rt_resource = reinterpret_cast(std::uintptr_t{0x1000}); - auto* ds_resource = reinterpret_cast(std::uintptr_t{0x2000}); - ResourceBinding rt_binding{}; - rt_binding.image = rt; - rt_binding.format = VK_FORMAT_R8G8B8A8_UNORM; - rt_binding.width = rt_binding.height = size; - ResourceBinding ds_binding = rt_binding; - ds_binding.image = ds; - ds_binding.format = VK_FORMAT_D32_SFLOAT_S8_UINT; - ds_binding.aspects = depth_stencil_aspects; - context.add_resource(rt::d3d12::resource_id(rt_resource), rt_binding, VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL); - context.add_resource(rt::d3d12::resource_id(ds_resource), ds_binding, - VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL); - const TargetView rtv{rt::d3d12::resource_id(rt_resource), 0, 0, 1}; - const TargetView dsv{rt::d3d12::resource_id(ds_resource), 0, 0, 1}; - const D3D12_CPU_DESCRIPTOR_HANDLE rtv_handle{reinterpret_cast(&rtv)}; - const D3D12_CPU_DESCRIPTOR_HANDLE dsv_handle{reinterpret_cast(&dsv)}; - - { - D3D12_COMMAND_QUEUE_DESC queue_desc{}; - queue_desc.Type = D3D12_COMMAND_LIST_TYPE_DIRECT; - Ref queue; - Ref allocator; - Ref list; - Ref done, gate; - EXPECT(SUCCEEDED(rt::d3d12::create_command_queue(context, d.queue, d.family, queue_desc, - IID_PPV_ARGS(&queue.p)))); - EXPECT(SUCCEEDED(rt::d3d12::create_command_allocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&allocator.p)))); - EXPECT(SUCCEEDED(rt::d3d12::create_command_list(D3D12_COMMAND_LIST_TYPE_DIRECT, allocator.p, - IID_PPV_ARGS(&list.p)))); - EXPECT(SUCCEEDED(rt::d3d12::create_fence(context, 0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&done.p)))); - EXPECT(SUCCEEDED(rt::d3d12::create_fence(context, 0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&gate.p)))); - - // COM identity: the public chain answers, an unknown IID is refused (and logged). - { - Ref base; - Ref device; - EXPECT(SUCCEEDED(list->QueryInterface(IID_PPV_ARGS(&base.p))) && base.p == list.p); - EXPECT(list->QueryInterface(IID_PPV_ARGS(&device.p)) == E_NOINTERFACE && !device.p); - } - EXPECT(queue->GetDesc().Type == D3D12_COMMAND_LIST_TYPE_DIRECT); - EXPECT(list->GetType() == D3D12_COMMAND_LIST_TYPE_DIRECT); - - // ExecuteBundle: a closed bundle's state calls play on the parent, so what the bundle set stays there. - Ref list8; - EXPECT(SUCCEEDED(list->QueryInterface(IID_PPV_ARGS(&list8.p)))); - list8->OMSetFrontAndBackStencilRef(1, 2); - Ref bundle_allocator; - Ref bundle; - EXPECT(SUCCEEDED(rt::d3d12::create_command_allocator(D3D12_COMMAND_LIST_TYPE_BUNDLE, - IID_PPV_ARGS(&bundle_allocator.p)))); - EXPECT(SUCCEEDED(rt::d3d12::create_command_list(D3D12_COMMAND_LIST_TYPE_BUNDLE, bundle_allocator.p, - IID_PPV_ARGS(&bundle.p)))); - EXPECT(bundle->GetType() == D3D12_COMMAND_LIST_TYPE_BUNDLE); - - // A command list and its allocator must have the same D3D12 type. - Ref wrong_allocator; - Ref wrong_bundle; - EXPECT(SUCCEEDED(rt::d3d12::create_command_allocator(D3D12_COMMAND_LIST_TYPE_DIRECT, - IID_PPV_ARGS(&wrong_allocator.p)))); - EXPECT(rt::d3d12::create_command_list(D3D12_COMMAND_LIST_TYPE_BUNDLE, wrong_allocator.p, - IID_PPV_ARGS(&wrong_bundle.p)) == E_INVALIDARG); - EXPECT(!wrong_bundle.p); - bundle->OMSetFrontAndBackStencilRef(7, 9); - EXPECT(bundle->Close() == S_OK); - list8->ExecuteBundle(bundle.p); - UINT front = 0, back = 0; - EXPECT(rt::d3d12::front_back_stencil_ref(list8.p, front, back) && front == 7 && back == 9); - - // An untouched bundle inherits the parent's current sticky state; its default values must not overwrite it. - Ref untouched_allocator; - Ref untouched_bundle; - EXPECT(SUCCEEDED(rt::d3d12::create_command_allocator(D3D12_COMMAND_LIST_TYPE_BUNDLE, - IID_PPV_ARGS(&untouched_allocator.p)))); - EXPECT(SUCCEEDED(rt::d3d12::create_command_list(D3D12_COMMAND_LIST_TYPE_BUNDLE, untouched_allocator.p, - IID_PPV_ARGS(&untouched_bundle.p)))); - EXPECT(untouched_bundle->Close() == S_OK); - list8->ExecuteBundle(untouched_bundle.p); - EXPECT(rt::d3d12::front_back_stencil_ref(list8.p, front, back) && front == 7 && back == 9); - list8->ExecuteBundle(bundle.p); // the same closed bundle can be executed repeatedly - - ID3D12CommandList* bundle_submission[] = {bundle.p}; - queue->ExecuteCommandLists(1, bundle_submission); // bundles are executed only inside direct lists - EXPECT(rt::d3d12::last_execute_result(queue.p) == ReplayResult::unsupported); - - // Runtime validation failures are deferred to Close, matching D3D12. - Ref bad_parent_allocator, direct_callee_allocator; - Ref bad_parent, direct_callee; - EXPECT(SUCCEEDED(rt::d3d12::create_command_allocator(D3D12_COMMAND_LIST_TYPE_DIRECT, - IID_PPV_ARGS(&bad_parent_allocator.p)))); - EXPECT(SUCCEEDED(rt::d3d12::create_command_list(D3D12_COMMAND_LIST_TYPE_DIRECT, bad_parent_allocator.p, - IID_PPV_ARGS(&bad_parent.p)))); - EXPECT(SUCCEEDED(rt::d3d12::create_command_allocator(D3D12_COMMAND_LIST_TYPE_DIRECT, - IID_PPV_ARGS(&direct_callee_allocator.p)))); - EXPECT(SUCCEEDED(rt::d3d12::create_command_list(D3D12_COMMAND_LIST_TYPE_DIRECT, direct_callee_allocator.p, - IID_PPV_ARGS(&direct_callee.p)))); - EXPECT(direct_callee->Close() == S_OK); - bad_parent->ExecuteBundle(direct_callee.p); // callee must be a bundle - EXPECT(bad_parent->Close() == E_INVALIDARG); - EXPECT(direct_callee->Reset(bundle_allocator.p, nullptr) == E_INVALIDARG); - EXPECT(SUCCEEDED(direct_callee->Reset(direct_callee_allocator.p, nullptr))); - EXPECT(direct_callee->Close() == S_OK); - - Ref open_parent_allocator, open_bundle_allocator; - Ref open_parent, open_bundle; - EXPECT(SUCCEEDED(rt::d3d12::create_command_allocator(D3D12_COMMAND_LIST_TYPE_DIRECT, - IID_PPV_ARGS(&open_parent_allocator.p)))); - EXPECT(SUCCEEDED(rt::d3d12::create_command_list(D3D12_COMMAND_LIST_TYPE_DIRECT, open_parent_allocator.p, - IID_PPV_ARGS(&open_parent.p)))); - EXPECT(SUCCEEDED(rt::d3d12::create_command_allocator(D3D12_COMMAND_LIST_TYPE_BUNDLE, - IID_PPV_ARGS(&open_bundle_allocator.p)))); - EXPECT(SUCCEEDED(rt::d3d12::create_command_list(D3D12_COMMAND_LIST_TYPE_BUNDLE, open_bundle_allocator.p, - IID_PPV_ARGS(&open_bundle.p)))); - open_parent->ExecuteBundle(open_bundle.p); // callee must already be closed - EXPECT(open_parent->Close() == E_INVALIDARG); - EXPECT(open_bundle->Close() == S_OK); - - Ref bundle_parent_allocator; - Ref bundle_parent; - EXPECT(SUCCEEDED(rt::d3d12::create_command_allocator(D3D12_COMMAND_LIST_TYPE_BUNDLE, - IID_PPV_ARGS(&bundle_parent_allocator.p)))); - EXPECT(SUCCEEDED(rt::d3d12::create_command_list(D3D12_COMMAND_LIST_TYPE_BUNDLE, bundle_parent_allocator.p, - IID_PPV_ARGS(&bundle_parent.p)))); - bundle_parent->ExecuteBundle(bundle.p); // caller must be a direct list - EXPECT(bundle_parent->Close() == E_INVALIDARG); - - // Clear calls are forbidden in bundles; a failed bundle also invalidates its caller. - Ref invalid_bundle_allocator, invalid_caller_allocator; - Ref invalid_bundle, invalid_caller; - EXPECT(SUCCEEDED(rt::d3d12::create_command_allocator(D3D12_COMMAND_LIST_TYPE_BUNDLE, - IID_PPV_ARGS(&invalid_bundle_allocator.p)))); - EXPECT(SUCCEEDED(rt::d3d12::create_command_list(D3D12_COMMAND_LIST_TYPE_BUNDLE, invalid_bundle_allocator.p, - IID_PPV_ARGS(&invalid_bundle.p)))); - const FLOAT forbidden_clear[4] = {0, 0, 0, 1}; - invalid_bundle->ClearRenderTargetView(rtv_handle, forbidden_clear, 0, nullptr); - EXPECT(invalid_bundle->Close() == E_INVALIDARG); - EXPECT(SUCCEEDED(rt::d3d12::create_command_allocator(D3D12_COMMAND_LIST_TYPE_DIRECT, - IID_PPV_ARGS(&invalid_caller_allocator.p)))); - EXPECT(SUCCEEDED(rt::d3d12::create_command_list(D3D12_COMMAND_LIST_TYPE_DIRECT, invalid_caller_allocator.p, - IID_PPV_ARGS(&invalid_caller.p)))); - invalid_caller->ExecuteBundle(invalid_bundle.p); - EXPECT(invalid_caller->Close() == E_INVALIDARG); - constexpr GUID kTestData{0x0badf00d, 0x1, 0x2, {3, 4, 5, 6, 7, 8, 9, 10}}; - const std::uint32_t tag = 0x1234abcd; - std::uint32_t read = 0; - UINT read_size = sizeof(read); - EXPECT(SUCCEEDED(queue->SetPrivateData(kTestData, sizeof(tag), &tag))); - EXPECT(SUCCEEDED(queue->GetPrivateData(kTestData, &read_size, &read)) && read == tag); - - // An open list is rejected by ExecuteCommandLists and nothing is submitted. - ID3D12CommandList* lists[] = {list.p}; - queue->ExecuteCommandLists(1, lists); - EXPECT(rt::d3d12::last_execute_result(queue.p) == ReplayResult::list_open); - - const FLOAT red[4] = {1, 0, 0, 1}, blue[4] = {0, 0, 1, 1}; - const D3D12_RECT square{1, 1, 3, 3}; - list->ClearRenderTargetView(rtv_handle, red, 0, nullptr); - list->ClearRenderTargetView(rtv_handle, blue, 1, &square); - list->ClearDepthStencilView(dsv_handle, D3D12_CLEAR_FLAG_DEPTH | D3D12_CLEAR_FLAG_STENCIL, 0.5f, 0x33, 0, - nullptr); - D3D12_RESOURCE_BARRIER transition{}; - transition.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION; - transition.Transition.pResource = rt_resource; - transition.Transition.Subresource = D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES; - transition.Transition.StateBefore = D3D12_RESOURCE_STATE_RENDER_TARGET; - transition.Transition.StateAfter = D3D12_RESOURCE_STATE_COPY_SOURCE; - list->ResourceBarrier(1, &transition); - D3D12_TEXTURE_BARRIER texture{}; - texture.SyncBefore = D3D12_BARRIER_SYNC_DEPTH_STENCIL; - texture.SyncAfter = D3D12_BARRIER_SYNC_COPY; - texture.AccessBefore = D3D12_BARRIER_ACCESS_DEPTH_STENCIL_WRITE; - texture.AccessAfter = D3D12_BARRIER_ACCESS_COPY_SOURCE; - texture.LayoutBefore = D3D12_BARRIER_LAYOUT_DEPTH_STENCIL_WRITE; - texture.LayoutAfter = D3D12_BARRIER_LAYOUT_COPY_SOURCE; - texture.pResource = ds_resource; - texture.Subresources = {0xffffffff, 0, 0, 0, 0, 0}; - D3D12_BARRIER_GROUP group{}; - group.Type = D3D12_BARRIER_TYPE_TEXTURE; - group.NumBarriers = 1; - group.pTextureBarriers = &texture; - - // Each currently implemented bundle-forbidden method independently invalidates the bundle. - const FLOAT bundle_clear_color[4] = {0, 1, 0, 1}; - auto invalid_bundle_call = [&](auto record) { - Ref test_allocator; - Ref test_bundle; - if (FAILED(rt::d3d12::create_command_allocator(D3D12_COMMAND_LIST_TYPE_BUNDLE, - IID_PPV_ARGS(&test_allocator.p)))) - return false; - if (FAILED(rt::d3d12::create_command_list(D3D12_COMMAND_LIST_TYPE_BUNDLE, test_allocator.p, - IID_PPV_ARGS(&test_bundle.p)))) - return false; - record(test_bundle.p); - return test_bundle->Close() == E_INVALIDARG; - }; - EXPECT(invalid_bundle_call([&](auto* b) { b->ResourceBarrier(1, &transition); })); - EXPECT(invalid_bundle_call([&](auto* b) { b->Barrier(1, &group); })); - EXPECT(invalid_bundle_call([&](auto* b) { b->CopyBufferRegion(rt_resource, 0, ds_resource, 0, 16); })); - D3D12_TEXTURE_COPY_LOCATION copy_dst{}; - copy_dst.pResource = rt_resource; - copy_dst.Type = D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX; - D3D12_TEXTURE_COPY_LOCATION copy_src{}; - copy_src.pResource = ds_resource; - copy_src.Type = D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX; - EXPECT(invalid_bundle_call([&](auto* b) { b->CopyTextureRegion(©_dst, 0, 0, 0, ©_src, nullptr); })); - EXPECT(invalid_bundle_call([&](auto* b) { b->CopyResource(rt_resource, ds_resource); })); - EXPECT(invalid_bundle_call([&](auto* b) { b->ResolveSubresource(rt_resource, 0, ds_resource, 0, - DXGI_FORMAT_R8G8B8A8_UNORM); })); - EXPECT(invalid_bundle_call([&](auto* b) { b->ResolveSubresourceRegion(rt_resource, 0, 0, 0, ds_resource, - 0, nullptr, - DXGI_FORMAT_R8G8B8A8_UNORM, - D3D12_RESOLVE_MODE_AVERAGE); })); - EXPECT(invalid_bundle_call([&](auto* b) { b->ClearRenderTargetView(rtv_handle, bundle_clear_color, 0, nullptr); })); - EXPECT(invalid_bundle_call([&](auto* b) { b->ClearDepthStencilView(dsv_handle, D3D12_CLEAR_FLAG_DEPTH, - 0.5f, 0, 0, nullptr); })); - // A valid texture UAV descriptor, which a direct list would accept: only the bundle refuses the clear. - const UINT uav_uint[4] = {}; - const FLOAT uav_float[4] = {}; - leonida::gfx10::Image uav_image{}; - uav_image.format = leonida::gfx10::format_from_vulkan(VK_FORMAT_R8G8B8A8_UNORM); - uav_image.width = uav_image.height = 4; - const auto uav_words = leonida::gfx10::encode(uav_image); - const D3D12_CPU_DESCRIPTOR_HANDLE uav_view{reinterpret_cast(uav_words.data())}; - EXPECT(invalid_bundle_call([&](auto* b) { - b->ClearUnorderedAccessViewUint({}, uav_view, rt_resource, uav_uint, 0, nullptr); })); - EXPECT(invalid_bundle_call([&](auto* b) { - b->ClearUnorderedAccessViewFloat({}, uav_view, rt_resource, uav_float, 0, nullptr); })); - EXPECT(invalid_bundle_call([&](auto* b) { b->SetPredication(nullptr, 0, D3D12_PREDICATION_OP_EQUAL_ZERO); })); - // Measured on the PC runtime (default adapter and WARP, d3d12_bundle_forbidden_test): these fail a bundle's Close. - const D3D12_VIEWPORT bundle_viewport{0, 0, 4, 4, 0, 1}; - const D3D12_RECT bundle_scissor{0, 0, 4, 4}; - EXPECT(invalid_bundle_call([&](auto* b) { b->RSSetViewports(1, &bundle_viewport); })); - EXPECT(invalid_bundle_call([&](auto* b) { b->RSSetScissorRects(1, &bundle_scissor); })); - EXPECT(invalid_bundle_call([&](auto* b) { b->OMSetRenderTargets(1, &rtv_handle, FALSE, nullptr); })); - EXPECT(invalid_bundle_call([&](auto* b) { b->ClearState(nullptr); })); - // D3D-26: DiscardResource and the atomic copies are not allowed in a bundle; WriteBufferImmediate is - // ("Recording command lists and bundles", the bundle restrictions and the API restrictions table). - EXPECT(invalid_bundle_call([&](auto* b) { b->DiscardResource(rt_resource, nullptr); })); - ID3D12Resource* const bundle_dependents[] = {ds_resource}; - const D3D12_SUBRESOURCE_RANGE_UINT64 bundle_ranges[] = {{0, {0, 8}}}; - EXPECT(invalid_bundle_call([&](auto* b) { - b->AtomicCopyBufferUINT(rt_resource, 0, ds_resource, 0, 1, bundle_dependents, bundle_ranges); })); - EXPECT(invalid_bundle_call([&](auto* b) { - b->AtomicCopyBufferUINT64(rt_resource, 0, ds_resource, 0, 1, bundle_dependents, bundle_ranges); })); - EXPECT(!invalid_bundle_call([&](auto* b) { - const D3D12_WRITEBUFFERIMMEDIATE_PARAMETER write{0x1000, 1}; - b->WriteBufferImmediate(1, &write, nullptr); })); - - list->Barrier(1, &group); - // Not implemented: reported once by its generated stub, recording continues. - list->SetProtectedResourceSession(nullptr); - EXPECT(list->Close() == S_OK); - EXPECT(list->Close() == E_FAIL); // already closed - - // The queue waits for `gate`, which only the CPU signals, so the work cannot have run before that. - EXPECT(SUCCEEDED(queue->Wait(gate.p, 1))); - queue->ExecuteCommandLists(1, lists); - EXPECT(rt::d3d12::last_execute_result(queue.p) == ReplayResult::success); - EXPECT(SUCCEEDED(queue->Signal(done.p, 1))); - Sleep(50); - EXPECT(done->GetCompletedValue() == 0); - const HANDLE event = CreateEventW(nullptr, FALSE, FALSE, nullptr); - EXPECT(event); - EXPECT(SUCCEEDED(done->SetEventOnCompletion(1, event))); - EXPECT(WaitForSingleObject(event, 0) == WAIT_TIMEOUT); - EXPECT(SUCCEEDED(gate->Signal(1))); - EXPECT(WaitForSingleObject(event, 5000) == WAIT_OBJECT_0); - CloseHandle(event); - EXPECT(done->GetCompletedValue() == 1); - EXPECT(SUCCEEDED(done->Signal(1))); // not above the current value: reported and dropped - EXPECT(done->GetCompletedValue() == 1); - - EXPECT(context.layout(rt::d3d12::resource_id(rt_resource), 0) == VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL); - EXPECT(context.layout(rt::d3d12::resource_id(ds_resource), 0) == VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL); - EXPECT(context.layout(rt::d3d12::resource_id(ds_resource), 1) == VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL); - - // A depth outside [0, 1] is recorded as given and the list closes, as on WARP (3ce953ae8; - // d3d12_close_parity_test "ClearDepthStencilView depth 1.5", d3d12_clear_test reads the texels back). - EXPECT(SUCCEEDED(allocator->Reset())); - EXPECT(SUCCEEDED(list->Reset(allocator.p, nullptr))); - list->ClearDepthStencilView(dsv_handle, D3D12_CLEAR_FLAG_DEPTH, 2.0f, 0, 0, nullptr); - EXPECT(list->Close() == S_OK); - - // State-setting calls on a closed direct list or bundle are ignored and do not mutate recorded state. - EXPECT(SUCCEEDED(allocator->Reset())); - EXPECT(SUCCEEDED(list->Reset(allocator.p, nullptr))); - list->OMSetStencilRef(5); - EXPECT(list->Close() == S_OK); - EXPECT(rt::d3d12::front_back_stencil_ref(list8.p, front, back) && front == 5 && back == 5); - const FLOAT post_close_factor[4] = {0.1f, 0.2f, 0.3f, 0.4f}; - list->OMSetStencilRef(99); - list->OMSetBlendFactor(post_close_factor); - list->IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST); - list->IASetIndexBuffer(nullptr); - list->SetPipelineState(nullptr); - list->ClearState(nullptr); - list->ExecuteBundle(bundle.p); - EXPECT(rt::d3d12::front_back_stencil_ref(list8.p, front, back) && front == 5 && back == 5); - EXPECT(list->Close() == E_FAIL); - - // Post-close state calls on a closed bundle do not append calls or invalidate the bundle. - bundle->OMSetStencilRef(99); - bundle->OMSetBlendFactor(post_close_factor); - bundle->IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_LINELIST); - bundle->IASetIndexBuffer(nullptr); - bundle->SetPipelineState(nullptr); - bundle->ClearState(nullptr); - bundle->ExecuteBundle(untouched_bundle.p); - EXPECT(SUCCEEDED(allocator->Reset())); - EXPECT(SUCCEEDED(list->Reset(allocator.p, nullptr))); - list->ExecuteBundle(bundle.p); - EXPECT(rt::d3d12::front_back_stencil_ref(list8.p, front, back) && front == 7 && back == 9); - EXPECT(list->Close() == S_OK); - } - - EXPECT(d.run([&](VkCommandBuffer cb) { - d.read_back(cb, rt, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, VK_IMAGE_ASPECT_COLOR_BIT, size, size, 1, buffer, 0); - d.read_back(cb, ds, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, VK_IMAGE_ASPECT_DEPTH_BIT, size, size, 1, buffer, - depth_offset); - d.read_back(cb, ds, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, VK_IMAGE_ASPECT_STENCIL_BIT, size, size, 1, buffer, - stencil_offset); - return true; - })); - const auto* data = static_cast(mapped); - unsigned mismatches = 0; - for (std::uint32_t row = 0; row < size; ++row) { - for (std::uint32_t col = 0; col < size; ++col) { - const std::uint32_t i = row * size + col; - const bool inside = col >= 1 && col < 3 && row >= 1 && row < 3; - const std::array want = inside ? std::array{0, 0, 255, 255} - : std::array{255, 0, 0, 255}; - float depth; - std::memcpy(&depth, data + depth_offset + i * 4, 4); - if (!std::equal(want.begin(), want.end(), data + i * 4) || depth != 0.5f || data[stencil_offset + i] != 0x33) { - if (mismatches++ < 4) - std::fprintf(stderr, "texel %u: colour %u,%u,%u,%u depth %f stencil 0x%02x\n", i, - unsigned(data[i * 4]), unsigned(data[i * 4 + 1]), unsigned(data[i * 4 + 2]), - unsigned(data[i * 4 + 3]), depth, unsigned(data[stencil_offset + i])); - } - } - } - EXPECT(!mismatches); - if (d.validation_errors()) { - std::fprintf(stderr, "%u validation errors\n", d.validation_errors()); - return 1; - } - std::printf("COM list/queue/fence: %u colour, depth and stencil texels matched; queue wait held the GPU\n", texels); - return 0; -} diff --git a/runtime/test/d3d12_compute_test.cpp b/runtime/test/d3d12_compute_test.cpp deleted file mode 100644 index 5ba3ded52..000000000 --- a/runtime/test/d3d12_compute_test.cpp +++ /dev/null @@ -1,1026 +0,0 @@ -// The compute path end to end, through the Xbox-ABI proxy over the Vulkan device: -// - a root signature serialized by the PC runtime, created with CreateRootSignature; -// - a compute PSO created through device slot 62 (the Xbox shape) from a shader container shaped like the -// game's (DXBC, DXIL, XDAT 0x0D, XBCH, zlib), found by the SHA-256 of its FSSM program in a translator index; -// - buffers and a shader-visible descriptor heap in the GPU address arena, an upload buffer reached through its -// biased console VA; -// - root constants, a root UAV and a descriptor table set on the command list, two dispatches that each keep the -// arguments they were recorded with, and the results copied to a readback buffer. -// The shader (test/glsl/cs_user_data.comp) is written to the translator's push-constant and address contract. -// No game data. Set LEONIDA_VK_VALIDATION=1 to run under VK_LAYER_KHRONOS_validation. -#include "shader_fixture_path.h" -#include "test_temp_dir.h" -#include "vk_test_device.h" -#include "host_wine.h" -#include "../shims/d3d12_com.h" -#include "../src/gfx10_descriptors.h" -#include "../src/cached_pso.h" -#include "../src/shader_library.h" -#include "../shims/d3d12_xs_device.h" - -#include - -#include -#include -#include -#include -#include - -#ifndef LEONIDA_TEST_CS_SPV -#error "LEONIDA_TEST_CS_SPV must name the compiled test shader" -#endif - -#define EXPECT(condition) do { \ - if (!(condition)) { std::fprintf(stderr, "line %d: %s\n", __LINE__, #condition); return 1; } \ -} while (0) - -namespace { - -using XboxHeapHandleFn = std::uint64_t(WINAPI*)(void* heap); // heap slots 9/10: handle in RAX -// Device slot 62 as XboxBvhBuilder.dll calls it on 1.0.2.1: (desc, 0, 0, riid, out) (main's 28cf235). -using XboxComputePipelineFn = HRESULT(WINAPI*)(void* device, const D3D12_COMPUTE_PIPELINE_STATE_DESC*, std::uint64_t, - std::uint64_t, const IID*, void**); -// Device slot 67 as amd_fidelityfx_upscaler_xbox.dll calls it: (desc, riid, out). -using XboxNativeComputePipelineFn = HRESULT(WINAPI*)(void* device, const void*, const IID*, void**); -using SerializeFn = HRESULT(WINAPI*)(const D3D12_VERSIONED_ROOT_SIGNATURE_DESC*, ID3DBlob**, ID3DBlob**); - -template -struct Ref { - T* p = nullptr; - ~Ref() { reset(); } - void reset() { - if (p) p->Release(); - p = nullptr; - } - T* operator->() const { return p; } -}; - -void* slot(void* object, unsigned index) { return (*reinterpret_cast(object))[index]; } - -void put32(std::vector& out, std::uint32_t v) { - for (int i = 0; i < 4; ++i) out.push_back(std::uint8_t(v >> (8 * i))); -} - -// zlib with one stored block (RFC 1950/1951), enough to wrap a test program. -std::vector zlib_stored(const std::vector& data) { - std::vector out = {0x78, 0x01, 0x01}; - const auto length = std::uint16_t(data.size()); - out.insert(out.end(), {std::uint8_t(length), std::uint8_t(length >> 8), std::uint8_t(~length), - std::uint8_t(~length >> 8)}); - out.insert(out.end(), data.begin(), data.end()); - std::uint32_t a = 1, b = 0; - for (const std::uint8_t x : data) { - a = (a + x) % 65521; - b = (b + a) % 65521; - } - const std::uint32_t adler = (b << 16) | a; - out.insert(out.end(), {std::uint8_t(adler >> 24), std::uint8_t(adler >> 16), std::uint8_t(adler >> 8), - std::uint8_t(adler)}); - return out; -} - -// DXBC { DXIL { stub, XDAT { 0x0D: XBCH + zlib(fssm) } } }, the layout tools/fssm_unpack.py reads. -std::vector shader_container(const std::vector& fssm) { - const auto stream = zlib_stored(fssm); - std::vector xbch = {'X', 'B', 'C', 'H'}; - for (const std::uint32_t v : {1u, std::uint32_t(stream.size()), 0u, std::uint32_t(fssm.size()), 0u}) put32(xbch, v); - xbch.insert(xbch.end(), stream.begin(), stream.end()); - std::vector dxil(16, 0); - dxil.insert(dxil.end(), {'X', 'D', 'A', 'T'}); - put32(dxil, 1); - put32(dxil, 12); - put32(dxil, 0x0d); - put32(dxil, 16 + 12 + 12); - put32(dxil, std::uint32_t(xbch.size())); - dxil.insert(dxil.end(), xbch.begin(), xbch.end()); - std::vector out = {'D', 'X', 'B', 'C'}; - out.resize(28, 0); - put32(out, 1); - put32(out, 36); - out.insert(out.end(), {'D', 'X', 'I', 'L'}); - put32(out, std::uint32_t(dxil.size())); - out.insert(out.end(), dxil.begin(), dxil.end()); - return out; -} - -std::vector serialize(const D3D12_VERSIONED_ROOT_SIGNATURE_DESC& desc) { - const HMODULE d3d12 = LoadLibraryExA("d3d12.dll", nullptr, LOAD_LIBRARY_SEARCH_SYSTEM32); - const auto fn = d3d12 ? reinterpret_cast( - reinterpret_cast(GetProcAddress(d3d12, "D3D12SerializeVersionedRootSignature"))) - : nullptr; - std::vector out; - ID3DBlob* blob = nullptr; - if (fn && SUCCEEDED(fn(&desc, &blob, nullptr)) && blob) { - const auto* p = static_cast(blob->GetBufferPointer()); - out.assign(p, p + blob->GetBufferSize()); - blob->Release(); - } - return out; -} - -D3D12_RESOURCE_DESC buffer_desc(UINT64 bytes, D3D12_RESOURCE_FLAGS flags) { - D3D12_RESOURCE_DESC desc{}; - desc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER; - desc.Width = bytes; - desc.Height = 1; - desc.DepthOrArraySize = 1; - desc.MipLevels = 1; - desc.SampleDesc.Count = 1; - desc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; - desc.Flags = flags; - return desc; -} - -D3D12_RESOURCE_BARRIER transition(ID3D12Resource* resource, D3D12_RESOURCE_STATES before, - D3D12_RESOURCE_STATES after) { - D3D12_RESOURCE_BARRIER barrier{}; - barrier.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION; - barrier.Transition.pResource = resource; - barrier.Transition.Subresource = D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES; - barrier.Transition.StateBefore = before; - barrier.Transition.StateAfter = after; - return barrier; -} - -// The CachedPSO cases both devices answer, in this order: the same description, another Flags, an equal root -// signature object, a root signature with other content, a truncated blob, a blob of junk, its first, middle and last -// byte changed, a pointer with size 0, a null pointer with a size. -constexpr int cached_case_count = 11; - -template -std::vector cached_pso_cases(Device* device, D3D12_COMPUTE_PIPELINE_STATE_DESC desc, - const std::vector& root_blob, - const std::vector& other_root_blob) { - std::vector out; - auto create = [&](D3D12_COMPUTE_PIPELINE_STATE_DESC d, const void* p, SIZE_T n) { - d.CachedPSO = {p, n}; - ID3D12PipelineState* made = nullptr; - HRESULT hr = device->CreateComputePipelineState(&d, IID_PPV_ARGS(&made)); - if (SUCCEEDED(hr) != (made != nullptr)) hr = E_UNEXPECTED; // a result and its object disagree - if (made) made->Release(); - return hr; - }; - ID3D12PipelineState* pso = nullptr; - if (FAILED(device->CreateComputePipelineState(&desc, IID_PPV_ARGS(&pso)))) return out; - ID3DBlob* blob = nullptr; - const HRESULT got = pso->GetCachedBlob(&blob); - const HRESULT got_null = pso->GetCachedBlob(nullptr); - pso->Release(); - if (FAILED(got) || !blob || got_null != S_OK) { - if (blob) blob->Release(); - return out; - } - const auto* p = static_cast(blob->GetBufferPointer()); - std::vector bytes(p, p + blob->GetBufferSize()); - blob->Release(); - ID3D12RootSignature* same_root = nullptr; - ID3D12RootSignature* other_root = nullptr; - device->CreateRootSignature(0, root_blob.data(), root_blob.size(), IID_PPV_ARGS(&same_root)); - device->CreateRootSignature(0, other_root_blob.data(), other_root_blob.size(), IID_PPV_ARGS(&other_root)); - if (!same_root || !other_root) return out; - - out.push_back(create(desc, bytes.data(), bytes.size())); - D3D12_COMPUTE_PIPELINE_STATE_DESC flags = desc; - flags.Flags = D3D12_PIPELINE_STATE_FLAG_TOOL_DEBUG; - out.push_back(create(flags, bytes.data(), bytes.size())); - D3D12_COMPUTE_PIPELINE_STATE_DESC same = desc; - same.pRootSignature = same_root; - out.push_back(create(same, bytes.data(), bytes.size())); - D3D12_COMPUTE_PIPELINE_STATE_DESC other = desc; - other.pRootSignature = other_root; - out.push_back(create(other, bytes.data(), bytes.size())); - out.push_back(create(desc, bytes.data(), bytes.size() / 2)); - const std::vector junk(bytes.size(), 0xab); - out.push_back(create(desc, junk.data(), junk.size())); - for (const std::size_t at : {std::size_t(0), bytes.size() / 2, bytes.size() - 1}) { - bytes[at] ^= 0xff; - out.push_back(create(desc, bytes.data(), bytes.size())); - bytes[at] ^= 0xff; - } - out.push_back(create(desc, bytes.data(), 0)); - out.push_back(create(desc, nullptr, 16)); - same_root->Release(); - other_root->Release(); - return out; -} - -// The same cases on the PC runtime, with an empty compute shader from d3dcompiler_47: the default adapter, then WARP. -// Empty when the host has no D3D12 device or no compiler, or is Wine's, which the caller reports as a skip: vkd3d has -// both, but its GetCachedBlob is a stub, so every host answered nothing and the comparison failed on each run. -std::vector> host_cached_pso_cases(const std::vector& root_blob, - const std::vector& other_root_blob) { - if (hostwine::host_is_wine()) return {}; - using CompileFn = HRESULT(WINAPI*)(LPCVOID, SIZE_T, LPCSTR, const void*, void*, LPCSTR, LPCSTR, UINT, UINT, - ID3DBlob**, ID3DBlob**); - using CreateDeviceFn = decltype(&::D3D12CreateDevice); - std::vector> out; - const HMODULE compiler = LoadLibraryExA("d3dcompiler_47.dll", nullptr, LOAD_LIBRARY_SEARCH_SYSTEM32); - const HMODULE d3d12 = LoadLibraryExA("d3d12.dll", nullptr, LOAD_LIBRARY_SEARCH_SYSTEM32); - const HMODULE dxgi = LoadLibraryExA("dxgi.dll", nullptr, LOAD_LIBRARY_SEARCH_SYSTEM32); - if (!compiler || !d3d12 || !dxgi) return out; - const auto compile = reinterpret_cast(reinterpret_cast(GetProcAddress(compiler, "D3DCompile"))); - const auto create_device = - reinterpret_cast(reinterpret_cast(GetProcAddress(d3d12, "D3D12CreateDevice"))); - using FactoryFn = HRESULT(WINAPI*)(REFIID, void**); - const auto create_factory = - reinterpret_cast(reinterpret_cast(GetProcAddress(dxgi, "CreateDXGIFactory1"))); - if (!compile || !create_device || !create_factory) return out; - static const char source[] = "[numthreads(1, 1, 1)] void main() {}"; - ID3DBlob* shader = nullptr; - if (FAILED(compile(source, sizeof(source) - 1, nullptr, nullptr, nullptr, "main", "cs_5_0", 0, 0, &shader, - nullptr)) || !shader) - return out; - IDXGIFactory4* factory = nullptr; - if (SUCCEEDED(create_factory(IID_PPV_ARGS(&factory)))) { - IDXGIAdapter* warp = nullptr; - factory->EnumWarpAdapter(IID_PPV_ARGS(&warp)); - for (IUnknown* adapter : {static_cast(nullptr), static_cast(warp)}) { - ID3D12Device* host = nullptr; - if (FAILED(create_device(adapter, D3D_FEATURE_LEVEL_11_0, IID_PPV_ARGS(&host)))) continue; - ID3D12RootSignature* root = nullptr; - if (SUCCEEDED(host->CreateRootSignature(0, root_blob.data(), root_blob.size(), IID_PPV_ARGS(&root)))) { - D3D12_COMPUTE_PIPELINE_STATE_DESC desc{}; - desc.pRootSignature = root; - desc.CS = {shader->GetBufferPointer(), shader->GetBufferSize()}; - out.push_back(cached_pso_cases(host, desc, root_blob, other_root_blob)); - root->Release(); - } - host->Release(); - } - if (warp) warp->Release(); - factory->Release(); - } - shader->Release(); - return out; -} - -} // namespace - -int main() { - vktest::Device d; - const auto device_status = d.initialize(); - if (device_status == vktest::DeviceStatus::unavailable) { - std::fprintf(stderr, "SKIP: no usable Vulkan 1.3 device\n"); - return 77; - } - EXPECT(device_status == vktest::DeviceStatus::ready); - - // The shader program the PSO carries, and a translator index that maps its hash to the test module. - constexpr std::uint32_t code_word = 5000; - std::vector fssm = {'F', 'S', 'S', 'M'}; - put32(fssm, code_word); - for (std::uint32_t i = 0; i < 14; ++i) put32(fssm, 0xbf810000u + i); // filler, s_endpgm-like words - const auto container = shader_container(fssm); - EXPECT(leonida::fssm_program(container) == fssm); - const testfiles::ScratchDir scratch("leonida_compute_test"); - const auto& library = scratch.path(); - EXPECT(testfiles::copy_file(vktest::shader_fixture_path(LEONIDA_TEST_CS_SPV), library / "cs_user_data.spv")); - { - std::ofstream index(library / "index.json", std::ios::binary); - // An entry for the same program with set-0 bindings comes first, as in one group of the corpus: the PSO - // must take the binding-free entry, which needs no set 0 (the bound one has no module either). - index << "{\"cs_user_data_bound\": {\"stage\": \"cs\", \"fssm_sha256\": \"" << leonida::sha256_hex(fssm) - << "\", \"bindings\": [{\"binding\": 0}], \"push_constant_bytes\": 144, \"local_size\": [64, 1, 1]},\n" - " \"cs_user_data\": {\"stage\": \"cs\", \"fssm_sha256\": \"" << leonida::sha256_hex(fssm) - << "\", \"bindings\": [], \"push_constant_bytes\": 144, \"local_size\": [64, 1, 1], " - "\"uses_code_base\": true, \"wave64\": false}}"; - } - // A second program whose only translation is in /bvh/index.json, where make_game.py puts the programs - // of XboxBvhBuilder.dll (docs/embedded_shaders.md): the same container shape and the same key, another folder. - auto builder_fssm = fssm; - builder_fssm[4] ^= 0x40; // another code word, so another hash - const auto builder_container = shader_container(builder_fssm); - std::filesystem::create_directories(library / "bvh"); - EXPECT(testfiles::copy_file(vktest::shader_fixture_path(LEONIDA_TEST_CS_SPV), - library / "bvh" / "BuilderProgram.spv")); - { - std::ofstream index(library / "bvh" / "index.json", std::ios::binary); - index << "{\"BuilderProgram\": {\"stage\": \"cs\", \"fssm_sha256\": \"" << leonida::sha256_hex(builder_fssm) - << "\", \"bindings\": [], \"push_constant_bytes\": 144, \"local_size\": [64, 1, 1], " - "\"uses_code_base\": true, \"wave64\": false}}"; - } - - constexpr UINT elements = 64, bytes = elements * 4; - const std::uint32_t table_values[4] = {1000, 2000, 3000, 4000}; - std::vector first(elements), second(elements), third(elements); - std::vector cbv_a_out(elements), cbv_oob_out(elements), cbv_b_out(elements), cbv_null_out(elements); - std::vector srv_raw_a(elements), srv_raw_b(elements), srv_struct_a(elements), - srv_struct_b(elements), srv_typed(elements), srv_null(elements); - { - rt::d3d12::VulkanDeviceInfo info{}; - info.get_instance_proc = d.instance_proc; - info.instance = d.instance; - info.physical = d.physical; - info.device = d.device; - info.queue = d.queue; - info.queue_family = d.family; - info.buffer_device_address = true; - info.subgroup = d.subgroup; - info.shader_dir = library.string(); - ID3D12Device* inner = nullptr; - EXPECT(SUCCEEDED(rt::d3d12::create_vulkan_device(info, IID_PPV_ARGS(&inner)))); - Ref device; - EXPECT(SUCCEEDED(rt::d3d12_xs::create_device_proxy(inner, __uuidof(ID3D12Device), - reinterpret_cast(&device.p)))); - rt::d3d12::set_device_outer(inner, device.p); - - // Root signature: [0] two constants (s4, s5), [1] a root UAV (s6:s7), [2] a one-CBV table (s8, its 32-bit VA): - // the console compute layout (rt::rootsig::pack_stage, D3D-448). - D3D12_DESCRIPTOR_RANGE range{D3D12_DESCRIPTOR_RANGE_TYPE_CBV, 1, 1, 0, 0}; - D3D12_ROOT_PARAMETER params[3] = {}; - params[0].ParameterType = D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS; - params[0].Constants = {0, 0, 2}; - params[1].ParameterType = D3D12_ROOT_PARAMETER_TYPE_UAV; - params[1].Descriptor = {0, 0}; - params[2].ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE; - params[2].DescriptorTable = {1, &range}; - D3D12_VERSIONED_ROOT_SIGNATURE_DESC root_desc{}; - root_desc.Version = D3D_ROOT_SIGNATURE_VERSION_1_0; - root_desc.Desc_1_0 = {3, params, 0, nullptr, D3D12_ROOT_SIGNATURE_FLAG_NONE}; - const auto root_blob = serialize(root_desc); - EXPECT(!root_blob.empty()); - Ref root; - EXPECT(SUCCEEDED(device->CreateRootSignature(0, root_blob.data(), root_blob.size(), IID_PPV_ARGS(&root.p)))); - Ref junk; - EXPECT(device->CreateRootSignature(0, "junk", 4, IID_PPV_ARGS(&junk.p)) == E_INVALIDARG && !junk.p); - - // The PSO through slot 62, the Xbox call shape; an unknown program is refused. - D3D12_COMPUTE_PIPELINE_STATE_DESC pso_desc{}; - pso_desc.pRootSignature = root.p; - pso_desc.CS = {container.data(), container.size()}; - const IID pso_iid = __uuidof(ID3D12PipelineState); - Ref pso, unknown; - EXPECT(SUCCEEDED(reinterpret_cast(slot(device.p, 62))( - device.p, &pso_desc, 0, 0, &pso_iid, reinterpret_cast(&pso.p)))); - auto other = fssm; - other[8] ^= 1; - const auto other_container = shader_container(other); - pso_desc.CS = {other_container.data(), other_container.size()}; - EXPECT(device->CreateComputePipelineState(&pso_desc, IID_PPV_ARGS(&unknown.p)) == E_INVALIDARG && !unknown.p); - { - // XboxBvhBuilder.dll's call: slot 62 with a container whose program is translated in /bvh. - Ref builder_pso; - pso_desc.CS = {builder_container.data(), builder_container.size()}; - EXPECT(SUCCEEDED(reinterpret_cast(slot(device.p, 62))( - device.p, &pso_desc, 0, 0, &pso_iid, reinterpret_cast(&builder_pso.p)))); - EXPECT(builder_pso.p && builder_pso.p != pso.p); - } - pso_desc.CS = {container.data(), container.size()}; - - // The PSO through slot 67, compute pipeline from native code; maps to CreateComputePipelineState. - struct XboxNativeComputeDesc { - ID3D12RootSignature* root_signature; - const void* kind0; - std::uint64_t kind0_size; - const void* kind1; - std::uint64_t kind1_size; - const void* kind6; - std::uint64_t kind6_size; - const void* kind7; - std::uint64_t kind7_size; - } native_desc{}; - native_desc.root_signature = root.p; - native_desc.kind6 = fssm.data(); - native_desc.kind6_size = fssm.size(); - Ref pso67, unknown67; - EXPECT(SUCCEEDED(reinterpret_cast(slot(device.p, 67))( - device.p, &native_desc, &pso_iid, reinterpret_cast(&pso67.p)))); - EXPECT(pso67.p != nullptr); - native_desc.kind6 = other.data(); - native_desc.kind6_size = other.size(); - EXPECT(reinterpret_cast(slot(device.p, 67))( - device.p, &native_desc, &pso_iid, reinterpret_cast(&unknown67.p)) == E_INVALIDARG && !unknown67.p); - void* out_null = reinterpret_cast(0x1111); - EXPECT(reinterpret_cast(slot(device.p, 67))( - device.p, nullptr, &pso_iid, &out_null) == E_INVALIDARG && !out_null); - out_null = reinterpret_cast(0x1111); - native_desc.kind6 = fssm.data(); - native_desc.kind6_size = fssm.size(); - EXPECT(reinterpret_cast(slot(device.p, 67))( - device.p, &native_desc, nullptr, &out_null) == E_POINTER && !out_null); - EXPECT(reinterpret_cast(slot(device.p, 67))( - device.p, &native_desc, &pso_iid, nullptr) == E_POINTER); - // GetCachedBlob and CachedPSO answer as the PC runtime does (src/cached_pso.h). - { - D3D12_VERSIONED_ROOT_SIGNATURE_DESC other_desc = root_desc; - other_desc.Desc_1_0.NumParameters = 2; - const auto other_root_blob = serialize(other_desc); - EXPECT(!other_root_blob.empty()); - const std::vector layer = cached_pso_cases(device.p, pso_desc, root_blob, other_root_blob); - EXPECT(int(layer.size()) == cached_case_count); - const std::vector expected = {S_OK, S_OK, S_OK, E_INVALIDARG, - E_INVALIDARG, E_INVALIDARG, E_INVALIDARG, E_INVALIDARG, - E_INVALIDARG, E_INVALIDARG, S_OK}; - EXPECT(layer == expected); - const auto hosts = host_cached_pso_cases(root_blob, other_root_blob); - if (hosts.empty()) - std::printf("SKIP: no host D3D12 reference (Wine, or no device or compiler) for the CachedPSO " - "comparison\n"); - for (const auto& host : hosts) EXPECT(host == layer); - if (!hosts.empty()) std::printf("cached PSO: %zu host adapter(s) gave the same %d answers\n", hosts.size(), cached_case_count); - - // Every byte of the blob counts, and the adapter and driver fields give the runtime's own errors. - Ref blob; - EXPECT(pso->GetCachedBlob(&blob.p) == S_OK && blob.p); - const auto* p = static_cast(blob->GetBufferPointer()); - std::vector blob_bytes(p, p + blob->GetBufferSize()); - auto attempt = [&](const std::vector& b) { - D3D12_COMPUTE_PIPELINE_STATE_DESC d = pso_desc; - d.CachedPSO = {b.data(), b.size()}; - Ref made; - return device->CreateComputePipelineState(&d, IID_PPV_ARGS(&made.p)); - }; - for (std::size_t at = 0; at < blob_bytes.size(); ++at) { - auto changed = blob_bytes; - changed[at] ^= 0x01; - EXPECT(attempt(changed) == E_INVALIDARG); - } - auto resealed = [](std::vector b, std::size_t at) { - b[at] ^= 0x01; - const std::uint32_t sum = leonida::cached_pso::fnv1a(b.data(), b.size() - 4); - for (int i = 0; i < 4; ++i) b[b.size() - 4 + i] = std::uint8_t(sum >> (8 * i)); - return b; - }; - EXPECT(attempt(resealed(blob_bytes, 8)) == D3D12_ERROR_ADAPTER_NOT_FOUND); // vendor - EXPECT(attempt(resealed(blob_bytes, 12)) == D3D12_ERROR_ADAPTER_NOT_FOUND); // device - EXPECT(attempt(resealed(blob_bytes, 16)) == D3D12_ERROR_DRIVER_VERSION_MISMATCH); - EXPECT(attempt(resealed(blob_bytes, 20)) == D3D12_ERROR_DRIVER_VERSION_MISMATCH); // pipelineCacheUUID - EXPECT(attempt(resealed(blob_bytes, 4)) == E_INVALIDARG); // version - } - - // A device whose maxPushConstantsSize is the Vulkan minimum (128 bytes) cannot hold the 144-byte block, so - // its PSOs are refused instead of creating a pipeline layout the spec forbids (#224's fallback flag). - { - rt::d3d12::VulkanDeviceInfo limited_info = info; - limited_info.max_push_constants_size = 128; - limited_info.push_constants_need_fallback = true; - Ref limited; - EXPECT(SUCCEEDED(rt::d3d12::create_vulkan_device(limited_info, IID_PPV_ARGS(&limited.p)))); - EXPECT(rt::d3d12::device_push_constants_need_fallback(limited.p)); - Ref limited_root; - EXPECT(SUCCEEDED(limited->CreateRootSignature(0, root_blob.data(), root_blob.size(), - IID_PPV_ARGS(&limited_root.p)))); - D3D12_COMPUTE_PIPELINE_STATE_DESC limited_desc = pso_desc; - limited_desc.pRootSignature = limited_root.p; - Ref refused; - EXPECT(limited->CreateComputePipelineState(&limited_desc, IID_PPV_ARGS(&refused.p)) == E_NOTIMPL && !refused.p); - } - - // The GPU address arena is no larger than the device's maxBufferSize and maxMemoryAllocationSize - // (src/arena_size.h), whatever LEONIDA_ARENA_MB asks for: with LEONIDA_ARENA_MB=3000 on a GPU that reports - // 2 GiB (RX 6800), a run under LEONIDA_VK_VALIDATION=1 has no vkAllocateMemory error. A device that reports - // a 32 MiB maxMemoryAllocationSize (simulated) gets at most 32 MiB from the default 256, and a buffer past - // that is refused. - { - VkPhysicalDeviceMaintenance4Properties m4{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MAINTENANCE_4_PROPERTIES}; - VkPhysicalDeviceMaintenance3Properties m3{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MAINTENANCE_3_PROPERTIES, &m4}; - VkPhysicalDeviceProperties2 properties{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROPERTIES_2, &m3}; - d.instance_fn("vkGetPhysicalDeviceProperties2")(d.physical, &properties); - const std::uint64_t arena = rt::d3d12::device_arena_size(device.p); - EXPECT(arena > 0 && arena <= m4.maxBufferSize && arena <= m3.maxMemoryAllocationSize); - - constexpr std::uint64_t capped_limit = 32ull << 20; - rt::d3d12::VulkanDeviceInfo capped_info = info; - capped_info.max_memory_allocation_size = capped_limit; - Ref capped; - EXPECT(SUCCEEDED(rt::d3d12::create_vulkan_device(capped_info, IID_PPV_ARGS(&capped.p)))); - const std::uint64_t capped_arena = rt::d3d12::device_arena_size(capped.p); - EXPECT(capped_arena > 0 && capped_arena <= capped_limit); - const D3D12_HEAP_PROPERTIES heap{D3D12_HEAP_TYPE_DEFAULT}; - const auto fits = buffer_desc(1u << 20, D3D12_RESOURCE_FLAG_NONE); - const auto too_large = buffer_desc(capped_limit + (1u << 20), D3D12_RESOURCE_FLAG_NONE); - Ref inside, past; - EXPECT(SUCCEEDED(capped->CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &fits, - D3D12_RESOURCE_STATE_COMMON, nullptr, - IID_PPV_ARGS(&inside.p)))); - EXPECT(inside->GetGPUVirtualAddress() + (1u << 20) <= capped_arena); - EXPECT(capped->CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &too_large, D3D12_RESOURCE_STATE_COMMON, - nullptr, IID_PPV_ARGS(&past.p)) == E_OUTOFMEMORY && !past.p); - std::printf("arena: %llu MiB (device limits: maxBufferSize %llu MiB, maxMemoryAllocationSize %llu MiB); " - "%llu MiB with a simulated 32 MiB maxMemoryAllocationSize\n", - static_cast(arena >> 20), - static_cast(m4.maxBufferSize >> 20), - static_cast(m3.maxMemoryAllocationSize >> 20), - static_cast(capped_arena >> 20)); - } - - // Buffers in the arena, an upload buffer outside it, a readback buffer for the results. - const D3D12_HEAP_PROPERTIES default_heap{D3D12_HEAP_TYPE_DEFAULT}; - const D3D12_HEAP_PROPERTIES upload_heap{D3D12_HEAP_TYPE_UPLOAD}; - const D3D12_HEAP_PROPERTIES readback_heap{D3D12_HEAP_TYPE_READBACK}; - Ref out_a, out_b, out_c, constants, readback; - const auto uav = buffer_desc(bytes, D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS); - EXPECT(SUCCEEDED(device->CreateCommittedResource(&default_heap, D3D12_HEAP_FLAG_NONE, &uav, - D3D12_RESOURCE_STATE_UNORDERED_ACCESS, nullptr, - IID_PPV_ARGS(&out_a.p)))); - EXPECT(SUCCEEDED(device->CreateCommittedResource(&default_heap, D3D12_HEAP_FLAG_NONE, &uav, - D3D12_RESOURCE_STATE_UNORDERED_ACCESS, nullptr, - IID_PPV_ARGS(&out_b.p)))); - EXPECT(SUCCEEDED(device->CreateCommittedResource(&default_heap, D3D12_HEAP_FLAG_NONE, &uav, - D3D12_RESOURCE_STATE_UNORDERED_ACCESS, nullptr, - IID_PPV_ARGS(&out_c.p)))); - const auto constants_desc = buffer_desc(256, D3D12_RESOURCE_FLAG_NONE); - EXPECT(SUCCEEDED(device->CreateCommittedResource(&upload_heap, D3D12_HEAP_FLAG_NONE, &constants_desc, - D3D12_RESOURCE_STATE_GENERIC_READ, nullptr, - IID_PPV_ARGS(&constants.p)))); - const auto readback_desc = buffer_desc(3 * bytes, D3D12_RESOURCE_FLAG_NONE); - EXPECT(SUCCEEDED(device->CreateCommittedResource(&readback_heap, D3D12_HEAP_FLAG_NONE, &readback_desc, - D3D12_RESOURCE_STATE_COPY_DEST, nullptr, - IID_PPV_ARGS(&readback.p)))); - const D3D12_GPU_VIRTUAL_ADDRESS va_a = out_a->GetGPUVirtualAddress(), va_b = out_b->GetGPUVirtualAddress(), - va_c = out_c->GetGPUVirtualAddress(); - EXPECT(va_a >= 0x10000 && va_b >= 0x10000 && va_c >= 0x10000 && va_a != va_b && va_a != va_c && va_b != va_c && - va_a < (1ull << 32) && va_b < (1ull << 32) && va_c < (1ull << 32)); - EXPECT(va_a % D3D12_DEFAULT_RESOURCE_PLACEMENT_ALIGNMENT == 0); - EXPECT(constants->GetGPUVirtualAddress() != 0); // device address - heap base: wraps, still valid - void* mapped = nullptr; - EXPECT(SUCCEEDED(constants->Map(0, nullptr, &mapped))); - std::memcpy(mapped, table_values, sizeof(table_values)); - - // A shader-visible heap in the arena; its first slot gets the upload buffer's VA, written as raw bytes. - const D3D12_DESCRIPTOR_HEAP_DESC heap_desc{D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, 8, - D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE, 0}; - Ref heap; - EXPECT(SUCCEEDED(device->CreateDescriptorHeap(&heap_desc, IID_PPV_ARGS(&heap.p)))); - const std::uint64_t cpu = reinterpret_cast(slot(heap.p, 9))(heap.p); - const std::uint64_t gpu = reinterpret_cast(slot(heap.p, 10))(heap.p); - EXPECT(cpu && gpu >= 0x10000 && gpu < (1ull << 32)); - const std::uint64_t target = constants->GetGPUVirtualAddress(); - std::memcpy(reinterpret_cast(cpu), &target, sizeof(target)); - - D3D12_COMMAND_QUEUE_DESC queue_desc{}; - Ref queue; - Ref allocator; - Ref list; - Ref fence; - EXPECT(SUCCEEDED(device->CreateCommandQueue(&queue_desc, IID_PPV_ARGS(&queue.p)))); - EXPECT(SUCCEEDED(device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&allocator.p)))); - EXPECT(SUCCEEDED(device->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, allocator.p, nullptr, - IID_PPV_ARGS(&list.p)))); - EXPECT(SUCCEEDED(device->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&fence.p)))); - - // Misuse is reported by Close: a dispatch without a pipeline, a root view set on a constants parameter. - list->Dispatch(1, 1, 1); - EXPECT(list->Close() == E_INVALIDARG); - EXPECT(SUCCEEDED(list->Reset(allocator.p, pso.p))); - list->SetComputeRootSignature(root.p); - list->SetComputeRootUnorderedAccessView(0, va_a); - EXPECT(list->Close() == E_INVALIDARG); - - // Two dispatches: the second changes s4 and the UAV; each must keep what it was recorded with. - EXPECT(SUCCEEDED(list->Reset(allocator.p, nullptr))); - ID3D12DescriptorHeap* heaps[] = {heap.p}; - list->SetDescriptorHeaps(1, heaps); - // This root signature and PSO are released right after being set, as D3D12 allows: the list keeps them, - // so the arguments below still have a layout and ExecuteCommandLists still finds the pipeline. - ID3D12RootSignature* held_root = nullptr; - { - Ref own_root; - EXPECT(SUCCEEDED(device->CreateRootSignature(0, root_blob.data(), root_blob.size(), - IID_PPV_ARGS(&own_root.p)))); - D3D12_COMPUTE_PIPELINE_STATE_DESC own_desc = pso_desc; - own_desc.pRootSignature = own_root.p; - Ref own_pso; - EXPECT(SUCCEEDED(device->CreateComputePipelineState(&own_desc, IID_PPV_ARGS(&own_pso.p)))); - list->SetComputeRootSignature(own_root.p); - list->SetPipelineState(own_pso.p); - held_root = own_root.p; // still alive: the list holds it - } - // Setting the bound root signature again keeps the arguments, as D3D12 does (TEST-280), and setting a - // graphics root signature does not disturb the compute root arguments. - const std::uint32_t base_and_step[2] = {7, 3}; - list->SetComputeRoot32BitConstant(0, base_and_step[0], 0); - list->SetComputeRootSignature(held_root); - list->SetComputeRoot32BitConstant(0, base_and_step[1], 1); - list->SetComputeRootUnorderedAccessView(1, va_a); - list->SetComputeRootDescriptorTable(2, D3D12_GPU_DESCRIPTOR_HANDLE{gpu}); - list->SetComputeRootSignature(held_root); - list->SetGraphicsRootSignature(root.p); - list->SetGraphicsRoot32BitConstant(0, 999, 0); - list->SetGraphicsRootSignature(root.p); - list->SetGraphicsRoot32BitConstant(0, 888, 1); - list->Dispatch(1, 1, 1); - list->SetComputeRoot32BitConstant(0, 100, 0); - list->SetComputeRootUnorderedAccessView(1, va_b); - list->Dispatch(1, 1, 1); - // Switching to a different root-signature object (root.p != held_root) resets the bound arguments to zero - // (clearing s0 = 100 to 0), whereas rebinding root.p afterwards keeps the arguments set on it (s1 = 5). - list->SetComputeRootSignature(root.p); - list->SetComputeRoot32BitConstant(0, 5, 1); // offset 1 (s1 = 5); offset 0 (s0) stays 0 from the switch - list->SetComputeRootUnorderedAccessView(1, va_c); - list->SetComputeRootDescriptorTable(2, D3D12_GPU_DESCRIPTOR_HANDLE{gpu}); - list->SetComputeRootSignature(root.p); - list->Dispatch(1, 1, 1); - D3D12_RESOURCE_BARRIER barriers[3] = { - transition(out_a.p, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_COPY_SOURCE), - transition(out_b.p, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_COPY_SOURCE), - transition(out_c.p, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_COPY_SOURCE)}; - list->ResourceBarrier(3, barriers); - list->CopyBufferRegion(readback.p, 0, out_a.p, 0, bytes); - list->CopyBufferRegion(readback.p, bytes, out_b.p, 0, bytes); - list->CopyBufferRegion(readback.p, 2 * bytes, out_c.p, 0, bytes); - EXPECT(list->Close() == S_OK); - ID3D12CommandList* lists[] = {list.p}; - queue->ExecuteCommandLists(1, lists); - EXPECT(rt::d3d12::last_execute_result(queue.p) == leonida::ReplayResult::success); - EXPECT(SUCCEEDED(queue->Signal(fence.p, 1))); - EXPECT(SUCCEEDED(fence->SetEventOnCompletion(1, nullptr))); - - void* results = nullptr; - EXPECT(SUCCEEDED(readback->Map(0, nullptr, &results))); - std::memcpy(first.data(), results, bytes); - std::memcpy(second.data(), static_cast(results) + bytes, bytes); - std::memcpy(third.data(), static_cast(results) + 2 * bytes, bytes); - - // CreateConstantBufferView: populate shader-visible descriptor heap slots with GFX10 V# descriptors for a - // 512-byte arena constant buffer (two 256-byte CBVs: A at +0, B at +256) and null CBVs. - { - const UINT inc = device->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV); - EXPECT(inc == 32); - const auto cb_desc = buffer_desc(512, D3D12_RESOURCE_FLAG_NONE); - Ref cb_upload, cb_default, cb_readback; - EXPECT(SUCCEEDED(device->CreateCommittedResource(&upload_heap, D3D12_HEAP_FLAG_NONE, &cb_desc, - D3D12_RESOURCE_STATE_GENERIC_READ, nullptr, - IID_PPV_ARGS(&cb_upload.p)))); - EXPECT(SUCCEEDED(device->CreateCommittedResource(&default_heap, D3D12_HEAP_FLAG_NONE, &cb_desc, - D3D12_RESOURCE_STATE_COPY_DEST, nullptr, - IID_PPV_ARGS(&cb_default.p)))); - const auto cb_rb_desc = buffer_desc(4 * bytes, D3D12_RESOURCE_FLAG_NONE); - EXPECT(SUCCEEDED(device->CreateCommittedResource(&readback_heap, D3D12_HEAP_FLAG_NONE, &cb_rb_desc, - D3D12_RESOURCE_STATE_COPY_DEST, nullptr, - IID_PPV_ARGS(&cb_readback.p)))); - void* cb_mapped = nullptr; - EXPECT(SUCCEEDED(cb_upload->Map(0, nullptr, &cb_mapped))); - auto* cb_words = static_cast(cb_mapped); - for (UINT i = 0; i < elements; ++i) { - cb_words[i] = 0x10000u + i; - cb_words[elements + i] = 0x20000u + i; - } - const D3D12_GPU_VIRTUAL_ADDRESS cb_va = cb_default->GetGPUVirtualAddress(); - EXPECT(cb_va >= 0x10000 && cb_va < (1ull << 32)); - - const auto slot_cpu = [&](UINT idx) { return D3D12_CPU_DESCRIPTOR_HANDLE{SIZE_T(cpu + idx * inc)}; }; - const auto slot_gpu = [&](UINT idx) { return D3D12_GPU_DESCRIPTOR_HANDLE{gpu + idx * inc}; }; - - // Pre-fill slot 3 with non-zero bytes to prove null CBV zeroes the entire 32-byte slot. - std::memset(reinterpret_cast(slot_cpu(3).ptr), 0xA5, inc); - device->CreateConstantBufferView(nullptr, slot_cpu(3)); - std::uint8_t zeros[32] = {}; - EXPECT(std::memcmp(reinterpret_cast(slot_cpu(3).ptr), zeros, sizeof(zeros)) == 0); - - // Zero BufferLocation or zero SizeInBytes also produces a zeroed null V#. - const D3D12_CONSTANT_BUFFER_VIEW_DESC zero_loc{0, 256}; - std::memset(reinterpret_cast(slot_cpu(3).ptr), 0x5A, inc); - device->CreateConstantBufferView(&zero_loc, slot_cpu(3)); - EXPECT(std::memcmp(reinterpret_cast(slot_cpu(3).ptr), zeros, sizeof(zeros)) == 0); - const D3D12_CONSTANT_BUFFER_VIEW_DESC zero_size{cb_va, 0}; - std::memset(reinterpret_cast(slot_cpu(3).ptr), 0x5A, inc); - device->CreateConstantBufferView(&zero_size, slot_cpu(3)); - EXPECT(std::memcmp(reinterpret_cast(slot_cpu(3).ptr), zeros, sizeof(zeros)) == 0); - - const D3D12_CONSTANT_BUFFER_VIEW_DESC cbv_a{cb_va, 256}; - const D3D12_CONSTANT_BUFFER_VIEW_DESC cbv_b{cb_va + 256, 256}; - device->CreateConstantBufferView(&cbv_a, slot_cpu(1)); - device->CreateConstantBufferView(&cbv_b, slot_cpu(2)); - - // Decode the written V# in slots 1 and 2 and verify every field + zeroed trailing 16 bytes. - for (const auto& [slot_idx, expected_va] : - {std::pair{1u, std::uint64_t(cb_va)}, std::pair{2u, std::uint64_t(cb_va + 256)}}) { - leonida::gfx10::BufferWords raw{}; - std::memcpy(raw.data(), reinterpret_cast(slot_cpu(slot_idx).ptr), sizeof(raw)); - leonida::gfx10::Buffer decoded{}; - EXPECT(leonida::gfx10::decode(raw, decoded)); - EXPECT(decoded.address == expected_va); - EXPECT(decoded.stride == 0); - EXPECT(decoded.num_records == 256); - EXPECT(decoded.format == leonida::gfx10::format_from_vulkan(VK_FORMAT_R32_UINT)); - EXPECT(decoded.swizzle == leonida::gfx10::identity_swizzle); - EXPECT(decoded.oob_select == leonida::gfx10::OobSelect::raw); - EXPECT(std::memcmp(reinterpret_cast(slot_cpu(slot_idx).ptr) + 16, zeros, 16) == 0); - } - - // Copy CBV data into the arena buffer, then run 4 dispatches: - // 1) CBV A at byte offset 0 (all 64 dwords in-bounds) - // 2) CBV A at byte offset 128 (dwords 0..31 in-bounds, dwords 32..63 OOB -> 0) - // 3) CBV B at byte offset 0 (negative control: all 64 dwords flip to 0x20000 + i) - // 4) Null CBV at byte offset 0 (negative control: all 64 dwords become 0) - EXPECT(SUCCEEDED(allocator->Reset()) && SUCCEEDED(list->Reset(allocator.p, pso.p))); - list->CopyBufferRegion(cb_default.p, 0, cb_upload.p, 0, 512); - const D3D12_RESOURCE_BARRIER cb_ready[] = { - transition(cb_default.p, D3D12_RESOURCE_STATE_COPY_DEST, - D3D12_RESOURCE_STATE_VERTEX_AND_CONSTANT_BUFFER), - transition(out_a.p, D3D12_RESOURCE_STATE_COPY_SOURCE, D3D12_RESOURCE_STATE_UNORDERED_ACCESS), - }; - list->ResourceBarrier(2, cb_ready); - list->SetDescriptorHeaps(1, heaps); - list->SetComputeRootSignature(root.p); - list->SetComputeRootUnorderedAccessView(1, va_a); - - const struct CbvDispatch { - UINT byte_offset; - UINT slot_idx; - UINT readback_offset; - } cbv_dispatches[] = { - {0, 1, 0 * bytes}, - {128, 1, 1 * bytes}, - {0, 2, 2 * bytes}, - {0, 3, 3 * bytes}, - }; - for (const auto& d_cfg : cbv_dispatches) { - const std::uint32_t rc[2] = {d_cfg.byte_offset, 0}; // s1 == 0 selects CBV V# mode - list->SetComputeRoot32BitConstants(0, 2, rc, 0); - list->SetComputeRootDescriptorTable(2, slot_gpu(d_cfg.slot_idx)); - list->Dispatch(1, 1, 1); - const auto to_src = - transition(out_a.p, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_COPY_SOURCE); - list->ResourceBarrier(1, &to_src); - list->CopyBufferRegion(cb_readback.p, d_cfg.readback_offset, out_a.p, 0, bytes); - const auto to_uav = - transition(out_a.p, D3D12_RESOURCE_STATE_COPY_SOURCE, D3D12_RESOURCE_STATE_UNORDERED_ACCESS); - list->ResourceBarrier(1, &to_uav); - } - EXPECT(list->Close() == S_OK); - queue->ExecuteCommandLists(1, lists); - EXPECT(rt::d3d12::last_execute_result(queue.p) == leonida::ReplayResult::success); - EXPECT(SUCCEEDED(queue->Signal(fence.p, 2))); - EXPECT(SUCCEEDED(fence->SetEventOnCompletion(2, nullptr))); - - void* cb_res = nullptr; - EXPECT(SUCCEEDED(cb_readback->Map(0, nullptr, &cb_res))); - const auto* src_bytes = static_cast(cb_res); - std::memcpy(cbv_a_out.data(), src_bytes + 0 * bytes, bytes); - std::memcpy(cbv_oob_out.data(), src_bytes + 1 * bytes, bytes); - std::memcpy(cbv_b_out.data(), src_bytes + 2 * bytes, bytes); - std::memcpy(cbv_null_out.data(), src_bytes + 3 * bytes, bytes); - } - - // CreateShaderResourceView(buffer): raw, structured, and typed GFX10 V# descriptors in the shader-visible heap. - { - const UINT inc = device->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV); - EXPECT(inc == 32); - // 1024-byte arena buffer = 256 uint32 words = 64 16-byte structs / float4 elements. - constexpr UINT buf_bytes = 1024; - const auto srv_buf_desc = buffer_desc(buf_bytes, D3D12_RESOURCE_FLAG_NONE); - const auto deny_buf_desc = buffer_desc(256, D3D12_RESOURCE_FLAG_DENY_SHADER_RESOURCE); - Ref srv_upload, srv_default, srv_deny, srv_readback; - EXPECT(SUCCEEDED(device->CreateCommittedResource(&upload_heap, D3D12_HEAP_FLAG_NONE, &srv_buf_desc, - D3D12_RESOURCE_STATE_GENERIC_READ, nullptr, - IID_PPV_ARGS(&srv_upload.p)))); - EXPECT(SUCCEEDED(device->CreateCommittedResource(&default_heap, D3D12_HEAP_FLAG_NONE, &srv_buf_desc, - D3D12_RESOURCE_STATE_COPY_DEST, nullptr, - IID_PPV_ARGS(&srv_default.p)))); - EXPECT(SUCCEEDED(device->CreateCommittedResource(&default_heap, D3D12_HEAP_FLAG_NONE, &deny_buf_desc, - D3D12_RESOURCE_STATE_COMMON, nullptr, - IID_PPV_ARGS(&srv_deny.p)))); - const auto srv_rb_desc = buffer_desc(6 * bytes, D3D12_RESOURCE_FLAG_NONE); - EXPECT(SUCCEEDED(device->CreateCommittedResource(&readback_heap, D3D12_HEAP_FLAG_NONE, &srv_rb_desc, - D3D12_RESOURCE_STATE_COPY_DEST, nullptr, - IID_PPV_ARGS(&srv_readback.p)))); - void* srv_mapped = nullptr; - EXPECT(SUCCEEDED(srv_upload->Map(0, nullptr, &srv_mapped))); - auto* words = static_cast(srv_mapped); - for (UINT w = 0; w < buf_bytes / 4; ++w) words[w] = 0x50000u + w; - const D3D12_GPU_VIRTUAL_ADDRESS srv_va = srv_default->GetGPUVirtualAddress(); - EXPECT(srv_va >= 0x10000 && srv_va < (1ull << 32)); - - const auto slot_cpu = [&](UINT idx) { return D3D12_CPU_DESCRIPTOR_HANDLE{SIZE_T(cpu + idx * inc)}; }; - const auto slot_gpu = [&](UINT idx) { return D3D12_GPU_DESCRIPTOR_HANDLE{gpu + idx * inc}; }; - std::uint8_t zeros[32] = {}; - - // Slot 1: Raw buffer SRV A (FirstElement = 0, NumElements = 32 -> 128 bytes; words 32..63 must read 0). - D3D12_SHADER_RESOURCE_VIEW_DESC raw_a{}; - raw_a.Format = DXGI_FORMAT_R32_TYPELESS; - raw_a.ViewDimension = D3D12_SRV_DIMENSION_BUFFER; - raw_a.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; - raw_a.Buffer = {0, 32, 0, D3D12_BUFFER_SRV_FLAG_RAW}; - device->CreateShaderResourceView(srv_default.p, &raw_a, slot_cpu(1)); - - // Slot 2: Raw buffer SRV B (FirstElement = 64, NumElements = 32 -> negative control shifted by +64 dwords). - D3D12_SHADER_RESOURCE_VIEW_DESC raw_b = raw_a; - raw_b.Buffer.FirstElement = 64; - device->CreateShaderResourceView(srv_default.p, &raw_b, slot_cpu(2)); - - // Slot 3: Structured buffer SRV A (stride 16, FirstElement = 0, NumElements = 32 -> elements 32..63 OOB). - D3D12_SHADER_RESOURCE_VIEW_DESC struct_a{}; - struct_a.Format = DXGI_FORMAT_UNKNOWN; - struct_a.ViewDimension = D3D12_SRV_DIMENSION_BUFFER; - struct_a.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; - struct_a.Buffer = {0, 32, 16, D3D12_BUFFER_SRV_FLAG_NONE}; - device->CreateShaderResourceView(srv_default.p, &struct_a, slot_cpu(3)); - - // Slot 4: Structured buffer SRV B (stride 16, FirstElement = 16, NumElements = 32 -> shifted +16 structs). - D3D12_SHADER_RESOURCE_VIEW_DESC struct_b = struct_a; - struct_b.Buffer.FirstElement = 16; - device->CreateShaderResourceView(srv_default.p, &struct_b, slot_cpu(4)); - - // Slot 5: Typed buffer SRV (R32G32B32A32_FLOAT, stride 16, FirstElement = 8, NumElements = 24, custom swizzle). - D3D12_SHADER_RESOURCE_VIEW_DESC typed_desc{}; - typed_desc.Format = DXGI_FORMAT_R32G32B32A32_FLOAT; - typed_desc.ViewDimension = D3D12_SRV_DIMENSION_BUFFER; - typed_desc.Shader4ComponentMapping = D3D12_ENCODE_SHADER_4_COMPONENT_MAPPING(2, 1, 0, 5); // B,G,R,1 - typed_desc.Buffer = {8, 24, 0, D3D12_BUFFER_SRV_FLAG_NONE}; - device->CreateShaderResourceView(srv_default.p, &typed_desc, slot_cpu(5)); - - // Slot 6: Typed RGB96 buffer SRV (R32G32B32_FLOAT, stride 12, FirstElement = 2, NumElements = 10). - D3D12_SHADER_RESOURCE_VIEW_DESC rgb96_desc{}; - rgb96_desc.Format = DXGI_FORMAT_R32G32B32_FLOAT; - rgb96_desc.ViewDimension = D3D12_SRV_DIMENSION_BUFFER; - rgb96_desc.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; - rgb96_desc.Buffer = {2, 10, 0, D3D12_BUFFER_SRV_FLAG_NONE}; - device->CreateShaderResourceView(srv_default.p, &rgb96_desc, slot_cpu(6)); - - // CPU V# decode verification for slots 1..6. - const auto decode_slot = [&](UINT idx, leonida::gfx10::Buffer& dec) -> bool { - leonida::gfx10::BufferWords rw{}; - std::memcpy(rw.data(), reinterpret_cast(slot_cpu(idx).ptr), sizeof(rw)); - return leonida::gfx10::decode(rw, dec) && - std::memcmp(reinterpret_cast(slot_cpu(idx).ptr) + 16, zeros, 16) == 0; - }; - { - leonida::gfx10::Buffer d1{}, d2{}, d3{}, d4{}, d5{}, d6{}; - EXPECT(decode_slot(1, d1)); - EXPECT(d1.address == srv_va && d1.stride == 0 && d1.num_records == 128 && - d1.format == leonida::gfx10::format_from_vulkan(VK_FORMAT_R32_UINT) && - d1.oob_select == leonida::gfx10::OobSelect::raw); - EXPECT(decode_slot(2, d2)); - EXPECT(d2.address == srv_va + 256 && d2.stride == 0 && d2.num_records == 128 && - d2.oob_select == leonida::gfx10::OobSelect::raw); - EXPECT(decode_slot(3, d3)); - EXPECT(d3.address == srv_va && d3.stride == 16 && d3.num_records == 32 && - d3.format == leonida::gfx10::format_from_vulkan(VK_FORMAT_R32_UINT) && - d3.oob_select == leonida::gfx10::OobSelect::structured); - EXPECT(decode_slot(4, d4)); - EXPECT(d4.address == srv_va + 256 && d4.stride == 16 && d4.num_records == 32 && - d4.oob_select == leonida::gfx10::OobSelect::structured); - EXPECT(decode_slot(5, d5)); - const leonida::gfx10::Swizzle want_swz = {leonida::gfx10::select_z, leonida::gfx10::select_y, - leonida::gfx10::select_x, leonida::gfx10::select_one}; - EXPECT(d5.address == srv_va + 8 * 16 && d5.stride == 16 && d5.num_records == 24 && - d5.format == leonida::gfx10::format_from_vulkan(VK_FORMAT_R32G32B32A32_SFLOAT) && - d5.swizzle == want_swz && d5.oob_select == leonida::gfx10::OobSelect::structured); - EXPECT(decode_slot(6, d6)); - EXPECT(d6.address == srv_va + 2 * 12 && d6.stride == 12 && d6.num_records == 10 && - d6.format == leonida::gfx10::format_from_vulkan(VK_FORMAT_R32G32B32_SFLOAT) && - d6.oob_select == leonida::gfx10::OobSelect::structured); - } - - // Invalid/refused buffer SRVs must all leave slot 7 zeroed. - const auto expect_zero_srv = [&](ID3D12Resource* res, const D3D12_SHADER_RESOURCE_VIEW_DESC* d) -> bool { - std::memset(reinterpret_cast(slot_cpu(7).ptr), 0xA5, inc); - device->CreateShaderResourceView(res, d, slot_cpu(7)); - return std::memcmp(reinterpret_cast(slot_cpu(7).ptr), zeros, sizeof(zeros)) == 0; - }; - EXPECT(expect_zero_srv(srv_default.p, nullptr)); // null desc on buffer - EXPECT(expect_zero_srv(srv_deny.p, &raw_a)); // DENY_SHADER_RESOURCE - auto bad = raw_a; - bad.Format = DXGI_FORMAT_R32_UINT; - EXPECT(expect_zero_srv(srv_default.p, &bad)); // RAW requires R32_TYPELESS - bad = raw_a; - bad.Buffer.StructureByteStride = 4; - EXPECT(expect_zero_srv(srv_default.p, &bad)); // RAW requires stride 0 - bad = struct_a; - bad.Format = DXGI_FORMAT_R32_FLOAT; - EXPECT(expect_zero_srv(srv_default.p, &bad)); // structured requires DXGI_FORMAT_UNKNOWN - bad = struct_a; - bad.Buffer.FirstElement = 60; - bad.Buffer.NumElements = 10; - EXPECT(expect_zero_srv(srv_default.p, &bad)); // out of bounds (70 * 16 > 1024) - EXPECT(expect_zero_srv(nullptr, &raw_a)); // null resource -> null V# - - // Upload buffer contents to arena and dispatch 6 GPU passes through the shader-visible descriptor table. - // out_a is already in D3D12_RESOURCE_STATE_UNORDERED_ACCESS at the end of the CBV pass. - EXPECT(SUCCEEDED(allocator->Reset()) && SUCCEEDED(list->Reset(allocator.p, pso.p))); - list->CopyBufferRegion(srv_default.p, 0, srv_upload.p, 0, buf_bytes); - const auto srv_ready = transition(srv_default.p, D3D12_RESOURCE_STATE_COPY_DEST, - D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE); - list->ResourceBarrier(1, &srv_ready); - list->SetDescriptorHeaps(1, heaps); - list->SetComputeRootSignature(root.p); - list->SetComputeRootUnorderedAccessView(1, va_a); - - const struct SrvDispatch { - UINT slot_idx; - UINT readback_offset; - } srv_dispatches[] = { - {1, 0 * bytes}, - {2, 1 * bytes}, - {3, 2 * bytes}, - {4, 3 * bytes}, - {5, 4 * bytes}, - {7, 5 * bytes}, - }; - const std::uint32_t srv_mode[2] = {0u, 0xFFFFFFFFu}; // s1 == 0xFFFFFFFF selects buffer SRV V# mode - list->SetComputeRoot32BitConstants(0, 2, srv_mode, 0); - for (const auto& cfg : srv_dispatches) { - list->SetComputeRootDescriptorTable(2, slot_gpu(cfg.slot_idx)); - list->Dispatch(1, 1, 1); - const auto to_src = - transition(out_a.p, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_COPY_SOURCE); - list->ResourceBarrier(1, &to_src); - list->CopyBufferRegion(srv_readback.p, cfg.readback_offset, out_a.p, 0, bytes); - const auto to_uav = - transition(out_a.p, D3D12_RESOURCE_STATE_COPY_SOURCE, D3D12_RESOURCE_STATE_UNORDERED_ACCESS); - list->ResourceBarrier(1, &to_uav); - } - EXPECT(list->Close() == S_OK); - queue->ExecuteCommandLists(1, lists); - EXPECT(rt::d3d12::last_execute_result(queue.p) == leonida::ReplayResult::success); - EXPECT(SUCCEEDED(queue->Signal(fence.p, 3))); - EXPECT(SUCCEEDED(fence->SetEventOnCompletion(3, nullptr))); - - void* srv_res = nullptr; - EXPECT(SUCCEEDED(srv_readback->Map(0, nullptr, &srv_res))); - const auto* rb = static_cast(srv_res); - std::memcpy(srv_raw_a.data(), rb + 0 * bytes, bytes); - std::memcpy(srv_raw_b.data(), rb + 1 * bytes, bytes); - std::memcpy(srv_struct_a.data(), rb + 2 * bytes, bytes); - std::memcpy(srv_struct_b.data(), rb + 3 * bytes, bytes); - std::memcpy(srv_typed.data(), rb + 4 * bytes, bytes); - std::memcpy(srv_null.data(), rb + 5 * bytes, bytes); - } - - for (auto* r : {&out_a, &out_b, &out_c, &constants, &readback}) r->reset(); - pso67.reset(); - unknown67.reset(); - pso.reset(); - pso67.reset(); // the slot-67 PSO holds the device like any other; released before the count is checked - unknown.reset(); - unknown67.reset(); - junk.reset(); - root.reset(); - heap.reset(); - list.reset(); - allocator.reset(); - queue.reset(); - fence.reset(); - EXPECT(rt::d3d12_xs::device_proxy_ref_count(device.p) == 1); - } - - unsigned mismatches = 0; - for (std::uint32_t i = 0; i < elements; ++i) { - const std::uint32_t a = 7 + 3 * i + table_values[i % 4] + code_word; - const std::uint32_t b = 100 + 3 * i + table_values[i % 4] + code_word; - const std::uint32_t c = 5 * i + table_values[i % 4] + code_word; - if ((first[i] != a || second[i] != b || third[i] != c) && mismatches++ < 4) - std::fprintf(stderr, "element %u: got %u, %u and %u, want %u, %u and %u\n", i, first[i], second[i], - third[i], a, b, c); - } - EXPECT(!mismatches); - UINT cbv_b_diff = 0, cbv_null_diff = 0; - for (std::uint32_t i = 0; i < elements; ++i) { - const std::uint32_t want_a = 0x10000u + i; - const std::uint32_t want_oob = i < 32 ? (0x10000u + 32u + i) : 0u; - const std::uint32_t want_b = 0x20000u + i; - if (cbv_a_out[i] != want_a && mismatches++ < 4) - std::fprintf(stderr, "CBV A[%u]: got 0x%x want 0x%x\n", i, cbv_a_out[i], want_a); - if (cbv_oob_out[i] != want_oob && mismatches++ < 4) - std::fprintf(stderr, "CBV OOB[%u]: got 0x%x want 0x%x\n", i, cbv_oob_out[i], want_oob); - if (cbv_b_out[i] != want_b && mismatches++ < 4) - std::fprintf(stderr, "CBV B[%u]: got 0x%x want 0x%x\n", i, cbv_b_out[i], want_b); - if (cbv_null_out[i] != 0u && mismatches++ < 4) - std::fprintf(stderr, "CBV null[%u]: got 0x%x want 0\n", i, cbv_null_out[i]); - if (cbv_b_out[i] != cbv_a_out[i]) ++cbv_b_diff; - if (cbv_null_out[i] != cbv_a_out[i]) ++cbv_null_diff; - } - EXPECT(!mismatches); - EXPECT(cbv_b_diff == elements && cbv_null_diff == elements); - std::printf("CreateConstantBufferView: 64/64 dwords matched for CBV A, 32 in-bounds + 32 OOB-zero matched at " - "+128, negative controls flipped %u/%u (CBV B) and %u/%u (null CBV)\n", - cbv_b_diff, elements, cbv_null_diff, elements); - UINT raw_diff = 0, struct_diff = 0, null_diff = 0; - for (std::uint32_t i = 0; i < elements; ++i) { - const std::uint32_t want_raw_a = i < 32 ? (0x50000u + i) : 0u; - const std::uint32_t want_raw_b = i < 32 ? (0x50000u + 64u + i) : 0u; - const std::uint32_t want_struct_a = i < 32 ? (0x50000u + i * 4u) : 0u; - const std::uint32_t want_struct_b = i < 32 ? (0x50000u + (16u + i) * 4u) : 0u; - const std::uint32_t want_typed = i < 24 ? (0x50000u + (8u + i) * 4u) : 0u; - if (srv_raw_a[i] != want_raw_a && mismatches++ < 4) - std::fprintf(stderr, "SRV raw A[%u]: got 0x%x want 0x%x\n", i, srv_raw_a[i], want_raw_a); - if (srv_raw_b[i] != want_raw_b && mismatches++ < 4) - std::fprintf(stderr, "SRV raw B[%u]: got 0x%x want 0x%x\n", i, srv_raw_b[i], want_raw_b); - if (srv_struct_a[i] != want_struct_a && mismatches++ < 4) - std::fprintf(stderr, "SRV struct A[%u]: got 0x%x want 0x%x\n", i, srv_struct_a[i], want_struct_a); - if (srv_struct_b[i] != want_struct_b && mismatches++ < 4) - std::fprintf(stderr, "SRV struct B[%u]: got 0x%x want 0x%x\n", i, srv_struct_b[i], want_struct_b); - if (srv_typed[i] != want_typed && mismatches++ < 4) - std::fprintf(stderr, "SRV typed[%u]: got 0x%x want 0x%x\n", i, srv_typed[i], want_typed); - if (srv_null[i] != 0u && mismatches++ < 4) - std::fprintf(stderr, "SRV null[%u]: got 0x%x want 0\n", i, srv_null[i]); - if (srv_raw_b[i] != srv_raw_a[i]) ++raw_diff; - if (srv_struct_b[i] != srv_struct_a[i]) ++struct_diff; - if (srv_null[i] != srv_raw_a[i]) ++null_diff; - } - EXPECT(!mismatches); - EXPECT(raw_diff == 32 && struct_diff == 32 && null_diff == 32); - std::printf("CreateShaderResourceView(buffer): raw (32 in-bounds + 32 OOB-zero), structured (32 + 32 OOB-zero), " - "typed (24 + 40 OOB-zero) matched; negative controls flipped %u/32 (raw B), %u/32 (struct B), %u/32 " - "(null)\n", - raw_diff, struct_diff, null_diff); - if (d.validation_errors()) { - std::fprintf(stderr, "%u validation errors\n", d.validation_errors()); - return 1; - } - std::printf("compute: root constants, a root UAV and a descriptor table reached the shader through the GPU " - "address arena; %u elements matched in each of three dispatches\n", elements); - return 0; -} diff --git a/runtime/test/d3d12_conservative_raster_test.cpp b/runtime/test/d3d12_conservative_raster_test.cpp deleted file mode 100644 index 7524f1638..000000000 --- a/runtime/test/d3d12_conservative_raster_test.cpp +++ /dev/null @@ -1,410 +0,0 @@ -// Synthetic D3D12/Vulkan conservative coverage. Required/forbidden pixels come from geometric clipping, -// not a driver snapshot: Tier 1 may over-cover by half a pixel, so uncertain pixels are not compared exactly. -#include "vk_test_device.h" -#include "d3d12_copy_compare.h" -#include "d3d12_test_shaders.h" -#include "host_wine.h" -#include "test_temp_dir.h" -#include "../src/conservative_raster.h" -#include "../src/shader_library.h" -#include -#include -#include -#include - -#define CHECK(x) do { if (!(x)) { std::fprintf(stderr, "line %d: %s\n", __LINE__, #x); return false; } } while (0) -namespace { -constexpr UINT width = 32, height = 32, pitch = 256; -struct Point { double x, y; }; -using Triangle = std::array; -using Mask = std::array; -struct Fixture { - copycmp::Run run; - copycmp::Ptr root; - D3D12_SHADER_BYTECODE vs{}, ps{}; -}; - -bool setup(Fixture& f, ID3D12Device* device, bool ours, D3D12_SHADER_BYTECODE vs, D3D12_SHADER_BYTECODE ps) { - f.vs = vs; f.ps = ps; - CHECK(f.run.init(device, ours)); - D3D12_VERSIONED_ROOT_SIGNATURE_DESC desc{}; - desc.Version = D3D_ROOT_SIGNATURE_VERSION_1_0; - desc.Desc_1_0.Flags = D3D12_ROOT_SIGNATURE_FLAG_ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT; - const auto bytes = d3d12test::serialize_root_signature(desc); - CHECK(!bytes.empty()); - CHECK(SUCCEEDED(device->CreateRootSignature(0, bytes.data(), bytes.size(), IID_PPV_ARGS(&f.root.p)))); - return true; -} - -D3D12_GRAPHICS_PIPELINE_STATE_DESC description(const Fixture& f, bool conservative, UINT samples, bool variant) { - static const D3D12_INPUT_ELEMENT_DESC element{ - "POSITION", 0, DXGI_FORMAT_R32G32_FLOAT, 0, 0, D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0}; - D3D12_GRAPHICS_PIPELINE_STATE_DESC d{}; - d.pRootSignature = f.root.p; - d.VS = f.vs; d.PS = f.ps; - d.InputLayout = {&element, 1}; - d.RasterizerState.FillMode = D3D12_FILL_MODE_SOLID; - d.RasterizerState.CullMode = D3D12_CULL_MODE_NONE; - d.RasterizerState.DepthClipEnable = TRUE; - d.RasterizerState.MultisampleEnable = samples > 1; - d.RasterizerState.ConservativeRaster = conservative ? D3D12_CONSERVATIVE_RASTERIZATION_MODE_ON - : D3D12_CONSERVATIVE_RASTERIZATION_MODE_OFF; - d.PrimitiveTopologyType = D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE; - d.NumRenderTargets = variant ? 2 : 1; - d.RTVFormats[0] = DXGI_FORMAT_R8G8B8A8_UNORM; - if (variant) d.RTVFormats[1] = DXGI_FORMAT_R8G8B8A8_UNORM; - d.BlendState.RenderTarget[0].RenderTargetWriteMask = D3D12_COLOR_WRITE_ENABLE_ALL; - d.SampleDesc.Count = samples; - d.SampleMask = UINT_MAX; - return d; -} - -// Clip the triangle to a pixel rectangle and return its intersection area. -double area(const Triangle& triangle, double left, double top, double right, double bottom, bool* intersects = nullptr) { - std::vector p(triangle.begin(), triangle.end()); - for (unsigned side = 0; side < 4 && !p.empty(); ++side) { - const auto distance = [&](Point v) { - return side == 0 ? v.x - left : side == 1 ? right - v.x : side == 2 ? v.y - top : bottom - v.y; - }; - std::vector out; - Point a = p.back(); double da = distance(a); - for (const Point b : p) { - const double db = distance(b); - if ((da >= 0) != (db >= 0)) { - const double t = da / (da - db); - out.push_back({a.x + t * (b.x - a.x), a.y + t * (b.y - a.y)}); - } - if (db >= 0) out.push_back(b); - a = b; da = db; - } - p = std::move(out); - } - double sum = 0; - if (intersects) *intersects = !p.empty(); // a degenerate triangle may cover pixels despite having zero area - for (std::size_t i = 0; i < p.size(); ++i) { - const Point a = p[i], b = p[(i + 1) % p.size()]; - sum += a.x * b.y - a.y * b.x; - } - return std::abs(sum) * 0.5; -} - -bool render(Fixture& f, const Triangle& triangle, bool conservative, UINT samples, bool variant, - const D3D12_RECT& scissor, Mask& mask, D3D12_CULL_MODE cull = D3D12_CULL_MODE_NONE) { - auto& r = f.run; - auto desc = description(f, conservative, samples, variant); - desc.RasterizerState.CullMode = cull; - copycmp::Ptr pso; - const auto created = r.device->CreateGraphicsPipelineState(&desc, IID_PPV_ARGS(&pso.p)); - if (FAILED(created)) { - std::fprintf(stderr, "%s CreateGraphicsPipelineState=%08x conservative=%d samples=%u variant=%d\n", - r.ours ? "Vulkan" : "host", unsigned(created), int(conservative), samples, int(variant)); - return false; - } - D3D12_RESOURCE_DESC tex{}; - tex.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D; - tex.Width = width; tex.Height = height; - tex.DepthOrArraySize = tex.MipLevels = 1; - tex.Format = DXGI_FORMAT_R8G8B8A8_UNORM; - tex.SampleDesc.Count = samples; - tex.Flags = D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET; - copycmp::Ptr target, resolved, vertices, readback; - CHECK(r.texture(tex, D3D12_RESOURCE_STATE_RENDER_TARGET, target)); - if (samples > 1) { - tex.SampleDesc.Count = 1; tex.Flags = D3D12_RESOURCE_FLAG_NONE; - CHECK(r.texture(tex, D3D12_RESOURCE_STATE_RESOLVE_DEST, resolved)); - } - CHECK(r.buffer(D3D12_HEAP_TYPE_UPLOAD, 24, D3D12_RESOURCE_STATE_GENERIC_READ, vertices)); - CHECK(r.buffer(D3D12_HEAP_TYPE_READBACK, pitch * height, D3D12_RESOURCE_STATE_COPY_DEST, readback)); - void* data = nullptr; - const D3D12_RANGE none{}; - CHECK(SUCCEEDED(vertices->Map(0, &none, &data))); - auto* positions = static_cast(data); - for (unsigned i = 0; i < 3; ++i) { - positions[i * 2] = float(triangle[i].x * 2 / width - 1); - positions[i * 2 + 1] = float(1 - triangle[i].y * 2 / height); - } - vertices->Unmap(0, nullptr); - copycmp::Ptr heap; - const D3D12_DESCRIPTOR_HEAP_DESC hd{D3D12_DESCRIPTOR_HEAP_TYPE_RTV, 1}; - CHECK(SUCCEEDED(r.device->CreateDescriptorHeap(&hd, IID_PPV_ARGS(&heap.p)))); - const auto handle = heap->GetCPUDescriptorHandleForHeapStart(); - r.device->CreateRenderTargetView(target.p, nullptr, handle); - r.begin(); - const float clear[4] = {}; - r.list->ClearRenderTargetView(handle, clear, 0, nullptr); - r.list->OMSetRenderTargets(1, &handle, FALSE, nullptr); - r.list->SetGraphicsRootSignature(f.root.p); - r.list->SetPipelineState(pso.p); - const D3D12_VIEWPORT viewport{0, 0, float(width), float(height), 0, 1}; - r.list->RSSetViewports(1, &viewport); - r.list->RSSetScissorRects(1, &scissor); - const D3D12_VERTEX_BUFFER_VIEW vb{vertices->GetGPUVirtualAddress(), 24, 8}; - r.list->IASetVertexBuffers(0, 1, &vb); - r.list->IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST); - r.list->DrawInstanced(3, 1, 0, 0); - ID3D12Resource* source = target.p; - if (samples > 1) { - r.barrier(target.p, D3D12_RESOURCE_STATE_RENDER_TARGET, D3D12_RESOURCE_STATE_RESOLVE_SOURCE); - r.list->ResolveSubresource(resolved.p, 0, target.p, 0, tex.Format); - r.barrier(resolved.p, D3D12_RESOURCE_STATE_RESOLVE_DEST, D3D12_RESOURCE_STATE_COPY_SOURCE); - source = resolved.p; - } else r.barrier(target.p, D3D12_RESOURCE_STATE_RENDER_TARGET, D3D12_RESOURCE_STATE_COPY_SOURCE); - D3D12_TEXTURE_COPY_LOCATION from{}, to{}; - from.pResource = source; from.Type = D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX; - to.pResource = readback.p; to.Type = D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT; - to.PlacedFootprint.Footprint = {tex.Format, width, height, 1, pitch}; - r.list->CopyTextureRegion(&to, 0, 0, 0, &from, nullptr); - const auto error = r.submit(); - if (!error.empty()) { std::fprintf(stderr, "%s\n", error.c_str()); return false; } - CHECK(SUCCEEDED(readback->Map(0, nullptr, &data))); - const auto* pixels = static_cast(data); - for (UINT y = 0; y < height; ++y) for (UINT x = 0; x < width; ++x) { - const auto* p = pixels + y * pitch + x * 4; - CHECK(p[1] == 0 && p[2] == 0 && p[0] == p[3]); - if (conservative) CHECK(p[0] == 0 || p[0] == 255); // every MSAA sample is covered - mask[y * width + x] = p[0] != 0; - } - readback->Unmap(0, &none); - return true; -} - -bool coverage(const Triangle& triangle, const D3D12_RECT& scissor, const Mask& mask) { - constexpr double epsilon = 1.0 / 256; - for (UINT y = 0; y < height; ++y) for (UINT x = 0; x < width; ++x) { - const bool in = LONG(x) >= scissor.left && LONG(x) < scissor.right && LONG(y) >= scissor.top && LONG(y) < scissor.bottom; - const bool required = in && area(triangle, x + epsilon, y + epsilon, x + 1 - epsilon, y + 1 - epsilon) > 1e-9; - bool intersects = false; - area(triangle, x - 0.5 - epsilon, y - 0.5 - epsilon, x + 1.5 + epsilon, y + 1.5 + epsilon, &intersects); - const bool allowed = in && intersects; - if ((required && !mask[y * width + x]) || (!allowed && mask[y * width + x])) { - std::fprintf(stderr, "coverage (%u,%u): required=%d allowed=%d actual=%d\n", x, y, - int(required), int(allowed), int(mask[y * width + x])); - return false; - } - } - return true; -} - -bool rejected_states(Fixture& f, bool enabled) { - auto desc = description(f, true, 1, false); - copycmp::Ptr pso; - if (!enabled) { - CHECK(f.run.device->CreateGraphicsPipelineState(&desc, IID_PPV_ARGS(&pso.p)) == E_INVALIDARG); - desc.RasterizerState.ConservativeRaster = D3D12_CONSERVATIVE_RASTERIZATION_MODE_OFF; - CHECK(SUCCEEDED(f.run.device->CreateGraphicsPipelineState(&desc, IID_PPV_ARGS(&pso.p)))); - return true; - } - desc.RasterizerState.FillMode = D3D12_FILL_MODE_WIREFRAME; - CHECK(f.run.device->CreateGraphicsPipelineState(&desc, IID_PPV_ARGS(&pso.p)) == E_INVALIDARG); - desc.RasterizerState.FillMode = D3D12_FILL_MODE_SOLID; - desc.PrimitiveTopologyType = D3D12_PRIMITIVE_TOPOLOGY_TYPE_LINE; - CHECK(f.run.device->CreateGraphicsPipelineState(&desc, IID_PPV_ARGS(&pso.p)) == E_INVALIDARG); - desc.PrimitiveTopologyType = D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE; - desc.RasterizerState.ForcedSampleCount = 4; - CHECK(f.run.device->CreateGraphicsPipelineState(&desc, IID_PPV_ARGS(&pso.p)) == E_NOTIMPL); - desc.RasterizerState.ForcedSampleCount = 0; - desc.RasterizerState.ConservativeRaster = D3D12_CONSERVATIVE_RASTERIZATION_MODE(7); - CHECK(f.run.device->CreateGraphicsPipelineState(&desc, IID_PPV_ARGS(&pso.p)) == E_INVALIDARG); - return true; -} - -bool owned_device_caps() { - copycmp::Ptr device; - CHECK(SUCCEEDED(rt::d3d12::create_vulkan_device_standalone(IID_PPV_ARGS(&device.p)))); - const auto* info = rt::d3d12::vulkan_device_info(device.p); - CHECK(info); - const auto enumerate = reinterpret_cast( - info->get_instance_proc(info->instance, "vkEnumerateDeviceExtensionProperties")); - UINT count = 0; - CHECK(enumerate(info->physical, nullptr, &count, nullptr) == VK_SUCCESS); - std::vector extensions(count); - CHECK(enumerate(info->physical, nullptr, &count, extensions.data()) == VK_SUCCESS); - const bool available = std::any_of(extensions.begin(), extensions.end(), [](const auto& e) { - return std::strcmp(e.extensionName, VK_EXT_CONSERVATIVE_RASTERIZATION_EXTENSION_NAME) == 0; - }); - CHECK(info->conservative_rasterization == available); - VkPhysicalDeviceConservativeRasterizationPropertiesEXT conservative{ - VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_CONSERVATIVE_RASTERIZATION_PROPERTIES_EXT}; - VkPhysicalDeviceProperties2 properties{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROPERTIES_2}; - if (available) properties.pNext = &conservative; - reinterpret_cast(info->get_instance_proc(info->instance, - "vkGetPhysicalDeviceProperties2"))(info->physical, &properties); - const auto expected = leonida::conservative_raster::tier(available, - properties.properties.limits.subPixelPrecisionBits, conservative.primitiveOverestimationSize, - conservative.degenerateTrianglesRasterized == VK_TRUE); - D3D12_FEATURE_DATA_D3D12_OPTIONS options{}; - CHECK(SUCCEEDED(device->CheckFeatureSupport(D3D12_FEATURE_D3D12_OPTIONS, &options, sizeof(options)))); - CHECK(unsigned(options.ConservativeRasterizationTier) == expected); - return true; -} -} // namespace - -int main(int argc, char** argv) { - const bool compare_warp_msaa4 = argc == 2 && std::strcmp(argv[1], "--warp-msaa4") == 0; - if (argc != 1 && !compare_warp_msaa4) return 2; - if (hostwine::host_is_wine()) return 77; - vktest::Device vk; - vk.request_buffer_device_address = true; - const auto status = vk.initialize(); - if (status == vktest::DeviceStatus::unavailable) return 77; - if (status != vktest::DeviceStatus::ready) return 1; - VkPhysicalDeviceConservativeRasterizationPropertiesEXT conservative_properties{ - VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_CONSERVATIVE_RASTERIZATION_PROPERTIES_EXT}; - VkPhysicalDeviceProperties2 properties{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROPERTIES_2}; - if (vk.conservative_rasterization) properties.pNext = &conservative_properties; - reinterpret_cast(vk.instance_proc(vk.instance, "vkGetPhysicalDeviceProperties2"))( - vk.physical, &properties); - if (!vk.buffer_device_address || properties.properties.limits.maxPushConstantsSize < 144) { - std::puts("SKIP: current graphics path needs bufferDeviceAddress and 144 push-constant bytes"); return 77; - } - const auto vs_program = d3d12test::fssm_program({0x43525653, 0xbf810000}); - const auto ps_program = d3d12test::fssm_program({0x43525053, 0xbf810000}); - const auto vs_bytes = d3d12test::shader_container(vs_program), ps_bytes = d3d12test::shader_container(ps_program); - const auto directory = std::filesystem::temp_directory_path() / ("leonida_conservative_" + std::to_string(GetCurrentProcessId())); - std::filesystem::create_directories(directory); - if (!testfiles::copy_file(LEONIDA_CONSERVATIVE_VS, directory / "vs.spv") || - !testfiles::copy_file(LEONIDA_CONSERVATIVE_PS, directory / "ps.spv")) - return 1; - { - std::ofstream index(directory / "index.json", std::ios::binary); - index << "{\"vs\":{\"stage\":\"vs\",\"fssm_sha256\":\"" << leonida::sha256_hex(vs_program) - << "\",\"bindings\":[],\"push_constant_bytes\":0,\"input_signature\":[{\"semantic\":\"POSITION\",\"semantic_index\":0,\"register\":0,\"mask\":3,\"rw_mask\":3,\"system_value\":0,\"component_type\":\"float\"}]}," - "\"ps\":{\"stage\":\"ps\",\"fssm_sha256\":\"" << leonida::sha256_hex(ps_program) - << "\",\"bindings\":[],\"push_constant_bytes\":0,\"outputs\":[0]}}"; - } - rt::d3d12::VulkanDeviceInfo info{}; - info.get_instance_proc = vk.instance_proc; info.instance = vk.instance; info.physical = vk.physical; - info.device = vk.device; info.queue = vk.queue; info.queue_family = vk.family; - info.buffer_device_address = vk.buffer_device_address; - info.conservative_rasterization = vk.conservative_rasterization; - info.shader_dir = directory.string(); - copycmp::Ptr ours, host; - if (FAILED(rt::d3d12::create_vulkan_device(info, IID_PPV_ARGS(&ours.p)))) return 1; - D3D12_FEATURE_DATA_D3D12_OPTIONS options{}; - if (FAILED(ours->CheckFeatureSupport(D3D12_FEATURE_D3D12_OPTIONS, &options, sizeof(options)))) return 1; - const auto expected_tier = leonida::conservative_raster::tier(vk.conservative_rasterization, - properties.properties.limits.subPixelPrecisionBits, conservative_properties.primitiveOverestimationSize, - conservative_properties.degenerateTrianglesRasterized == VK_TRUE); - if (unsigned(options.ConservativeRasterizationTier) != expected_tier) return 1; - if (options.ConservativeRasterizationTier == D3D12_CONSERVATIVE_RASTERIZATION_TIER_NOT_SUPPORTED) { - std::puts("SKIP: Vulkan device does not meet conservative raster Tier 1 requirements"); return 77; - } - if (options.ConservativeRasterizationTier > D3D12_CONSERVATIVE_RASTERIZATION_TIER_2) return 1; - if (!owned_device_caps()) return 1; - std::string adapter; - if (!copycmp::create_host(host, adapter)) return 1; - copycmp::Ptr factory; - copycmp::Ptr host_adapter; - if (FAILED(CreateDXGIFactory1(IID_PPV_ARGS(&factory.p))) || - FAILED(factory->EnumAdapterByLuid(host->GetAdapterLuid(), IID_PPV_ARGS(&host_adapter.p)))) return 1; - DXGI_ADAPTER_DESC1 adapter_desc{}; - if (FAILED(host_adapter->GetDesc1(&adapter_desc))) return 1; - const bool software_reference = (adapter_desc.Flags & DXGI_ADAPTER_FLAG_SOFTWARE) != 0; - if (FAILED(host->CheckFeatureSupport(D3D12_FEATURE_D3D12_OPTIONS, &options, sizeof(options)))) return 1; - if (options.ConservativeRasterizationTier == D3D12_CONSERVATIVE_RASTERIZATION_TIER_NOT_SUPPORTED) return 77; - copycmp::Ptr vs, ps, error; - const HMODULE compiler = LoadLibraryExA("d3dcompiler_47.dll", nullptr, LOAD_LIBRARY_SEARCH_SYSTEM32); - const auto compile = compiler ? reinterpret_cast(reinterpret_cast( - GetProcAddress(compiler, "D3DCompile"))) : nullptr; - if (!compile) { std::puts("SKIP: d3dcompiler_47 is needed for the native reference shaders"); return 77; } - const char* hlsl = "float4 vs(float2 p:POSITION):SV_Position{return float4(p,0.5,1);} float4 ps():SV_Target{return float4(1,0,0,1);}"; - if (FAILED(compile(hlsl, std::strlen(hlsl), nullptr, nullptr, nullptr, "vs", "vs_5_0", 0, 0, &vs.p, &error.p)) || - FAILED(compile(hlsl, std::strlen(hlsl), nullptr, nullptr, nullptr, "ps", "ps_5_0", 0, 0, &ps.p, nullptr))) return 1; - Fixture a, b; - if (!setup(a, ours.p, true, {vs_bytes.data(), vs_bytes.size()}, {ps_bytes.data(), ps_bytes.size()}) || - !setup(b, host.p, false, {vs->GetBufferPointer(), vs->GetBufferSize()}, {ps->GetBufferPointer(), ps->GetBufferSize()})) return 1; - if (!rejected_states(a, true)) return 1; - { - info.conservative_rasterization = false; - copycmp::Ptr disabled; - if (FAILED(rt::d3d12::create_vulkan_device(info, IID_PPV_ARGS(&disabled.p)))) return 1; - if (FAILED(disabled->CheckFeatureSupport(D3D12_FEATURE_D3D12_OPTIONS, &options, sizeof(options))) || - options.ConservativeRasterizationTier != D3D12_CONSERVATIVE_RASTERIZATION_TIER_NOT_SUPPORTED) return 1; - Fixture f; - if (!setup(f, disabled.p, true, {vs_bytes.data(), vs_bytes.size()}, {ps_bytes.data(), ps_bytes.size()}) || - !rejected_states(f, false)) return 1; - } - bool msaa4 = true; - for (auto* device : {ours.p, host.p}) { - D3D12_FEATURE_DATA_MULTISAMPLE_QUALITY_LEVELS levels{DXGI_FORMAT_R8G8B8A8_UNORM, 4}; - if (FAILED(device->CheckFeatureSupport(D3D12_FEATURE_MULTISAMPLE_QUALITY_LEVELS, &levels, sizeof(levels))) || - !levels.NumQualityLevels) msaa4 = false; - } - const Triangle scenes[] = { - {{{3.0625,3.0625},{3.3125,3.0625},{3.0625,3.3125}}}, - {{{2.125,5.125},{25.125,6.125},{2.125,5.25}}}, - {{{4.125,4.125},{24.125,4.125},{4.125,24.125}}}, - {{{-0.25,2.125},{5.125,2.125},{2.125,15.125}}}, - {{{4.125,24.125},{24.125,4.125},{4.125,4.125}}}, - {{{3.0625,3.0625},{3.3125,3.0625},{3.0625,3.0625}}}, // Tier 1 permits degenerate triangles to be culled - }; - unsigned comparisons = 0, host_comparisons = 0, host_not_comparable = 0; - const auto count = [](const Mask& m) { return unsigned(std::count(m.begin(), m.end(), true)); }; - for (const UINT samples : {1u, 4u}) { - if (samples == 4 && !msaa4) continue; - // WARP's 4x path was observed to cover outside the Tier 1 uncertainty bound for the subpixel fixture. - // Keep Vulkan's 4x geometric oracle strict; use 1x for the ordinary software-reference comparisons. - // --warp-msaa4 explicitly reproduces that reference discrepancy without weakening either oracle. - const bool compare_host = samples == 1 || !software_reference || compare_warp_msaa4; - for (const bool variant : {false, true}) - for (const auto scissor : {D3D12_RECT{0,0,32,32}, D3D12_RECT{4,4,20,20}}) - for (const auto& triangle : scenes) { - Mask normal_a{}, normal_b{}, conservative_a{}, conservative_b{}; - if (!render(a, triangle, false, samples, variant, scissor, normal_a) || - (compare_host && !render(b, triangle, false, samples, variant, scissor, normal_b)) || - !render(a, triangle, true, samples, variant, scissor, conservative_a) || - (compare_host && !render(b, triangle, true, samples, variant, scissor, conservative_b))) return 1; - const bool ours_ok = coverage(triangle, scissor, conservative_a); - if (!ours_ok) { - std::fprintf(stderr, "scene %zu samples %u variant %d scissor-left %ld: Vulkan fails the oracle\n", - std::size_t(&triangle - scenes), samples, int(variant), scissor.left); - return 1; - } - // The oracle is geometric, so the layer is judged by it alone. A native D3D12 render that fails it - // (TEST-907: an RTX 5060 Ti on Windows 10 drew nothing for scene 4 with conservative raster on) is - // reported, with both of its masks, and that scenario is not compared with the host. - bool host_ok = compare_host && coverage(triangle, scissor, conservative_b); - if (compare_host && !host_ok && compare_warp_msaa4) { - // --warp-msaa4 exists to reproduce WARP's known 4x discrepancy, so there it stays a failure. - std::fprintf(stderr, "scene %zu samples %u variant %d scissor-left %ld: host fails the oracle\n", - std::size_t(&triangle - scenes), samples, int(variant), scissor.left); - return 1; - } - if (compare_host && !host_ok) { - unsigned normal_only = 0; - for (unsigned i = 0; i < normal_b.size(); ++i) normal_only += normal_b[i] && !conservative_b[i]; - std::printf("host not comparable: scene %zu samples %u variant %d scissor-left %ld: host normal " - "mask %u pixels, conservative %u (%u normal pixels missing), Vulkan conservative %u\n", - std::size_t(&triangle - scenes), samples, int(variant), scissor.left, count(normal_b), - count(conservative_b), normal_only, count(conservative_a)); - ++host_not_comparable; - } - for (unsigned i = 0; i < normal_a.size(); ++i) - if ((normal_a[i] && !conservative_a[i]) || (host_ok && normal_b[i] && !conservative_b[i])) return 1; - if (&triangle == &scenes[0] && samples == 1 && scissor.left == 0) { - if (std::any_of(normal_a.begin(), normal_a.end(), [](bool x) { return x; }) || - (host_ok && std::any_of(normal_b.begin(), normal_b.end(), [](bool x) { return x; })) || - !std::any_of(conservative_a.begin(), conservative_a.end(), [](bool x) { return x; }) || - (host_ok && !std::any_of(conservative_b.begin(), conservative_b.end(), [](bool x) { return x; }))) return 1; - } - ++comparisons; - if (host_ok) ++host_comparisons; - } - } - for (auto* f : {&a, &b}) { - Mask front{}, back{}, all{}; - const D3D12_RECT full{0,0,32,32}; - if (!render(*f, scenes[2], true, 1, false, full, all) || - !render(*f, scenes[2], true, 1, false, full, front, D3D12_CULL_MODE_FRONT) || - !render(*f, scenes[2], true, 1, false, full, back, D3D12_CULL_MODE_BACK)) return 1; - for (unsigned i = 0; i < all.size(); ++i) if ((front[i] && back[i]) || ((front[i] || back[i]) != all[i])) return 1; - } - std::printf("conservative raster: %u Vulkan and %u %s scenario pairs; geometric bounds, culling, scissor, variants, rejections; Vulkan 4x MSAA %s\n", - comparisons, host_comparisons, adapter.c_str(), msaa4 ? "checked" : "unavailable"); - if (host_not_comparable) - std::printf("%u scenarios not compared: the %s render fails the geometric oracle there (listed above)\n", - host_not_comparable, adapter.c_str()); - if (software_reference && !compare_warp_msaa4) - std::puts("WARP comparison is 1x; --warp-msaa4 separately checks its observed 4x coverage discrepancy"); - return vk.validation_errors() ? 1 : 0; -} diff --git a/runtime/test/d3d12_conservative_tier2_test.cpp b/runtime/test/d3d12_conservative_tier2_test.cpp deleted file mode 100644 index 6d2efb8bd..000000000 --- a/runtime/test/d3d12_conservative_tier2_test.cpp +++ /dev/null @@ -1,215 +0,0 @@ -// Tier 2: tight uncertainty, exact and post-snap degenerates. RGB independently encodes varying colour, -// constant depth and facing. No game data. -#include "conservative_raster_fixture.h" -using namespace conservative_test; - -namespace { -double cross(const Triangle& t) { - return (t[1].x-t[0].x)*(t[2].y-t[0].y) - (t[1].y-t[0].y)*(t[2].x-t[0].x); -} - -bool tight_coverage(const Triangle& original, const Triangle* snapped, const D3D12_RECT& scissor, - const Mask& mask, bool log = true) { - constexpr double epsilon = 1e-7, uncertainty = 1.0 / 256; - unsigned required_count = 0, covered = 0; - for (UINT y=0;y=scissor.left && LONG(x)=scissor.top && LONG(y) 1e-12); - area(original,x-uncertainty-epsilon,y-uncertainty-epsilon, - x+1+uncertainty+epsilon,y+1+uncertainty+epsilon,&hits); - const bool allowed = in && hits; - if ((required && !mask[y*width+x]) || (!allowed && mask[y*width+x])) { - if (log) std::fprintf(stderr,"Tier 2 coverage (%u,%u): required=%d allowed=%d actual=%d\n", - x,y,int(required),int(allowed),int(mask[y*width+x])); - return false; - } - required_count += unsigned(required); covered += unsigned(mask[y*width+x]); - } - // A snapped point on a pixel corner has no required open-pixel intersection, but must cover at least one - // adjacent pixel. Its particular edge/corner tie-breaking is not asserted. - if (snapped && !required_count && !covered && log) std::fprintf(stderr,"snapped corner produced no fragments\n"); - return !snapped || required_count || covered; -} - -VertexInput vertices(const std::vector& points, std::vector indices, - D3D_PRIMITIVE_TOPOLOGY topology) { - // Keep depth planar: native D3D12 and Vulkan may extrapolate SV_Position.z for screen-space degenerates. - static constexpr float depths[] = {0.375f,0.375f,0.375f,0.375f}; - static constexpr float markers[] = {0.25f,0.75f,0.375f,0.875f}; - VertexInput out; out.indices=std::move(indices); out.topology=topology; - for (std::size_t i=0;i& rgba, unsigned provoking) { - static constexpr std::array expected[] = { - {64,96,0,255},{191,96,0,255},{96,96,0,255},{223,96,0,255}}; - for (unsigned i=0;i1e-12; - CHECK(tight_coverage(triangle,nullptr,full,mask)); - mask[8*width+7]=true; // within Tier 1's half-pixel margin, outside Tier 2's 1/256 margin - CHECK(coverage(triangle,full,mask)); - CHECK(!tight_coverage(triangle,nullptr,full,mask,false)); - return true; -} -} // namespace - -int main(int argc, char** argv) { - const bool warp_corner = argc > 1 && std::strcmp(argv[1], "--warp-corner") == 0; - if (!oracle_control()) return 1; - if (hostwine::host_is_wine()) return 77; - vktest::Device vk; vk.request_buffer_device_address=true; - const auto status=vk.initialize(); - if(status==vktest::DeviceStatus::unavailable)return 77; - if(status!=vktest::DeviceStatus::ready)return 1; - VkPhysicalDeviceConservativeRasterizationPropertiesEXT cr{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_CONSERVATIVE_RASTERIZATION_PROPERTIES_EXT}; - VkPhysicalDeviceProperties2 properties{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROPERTIES_2}; - if(vk.conservative_rasterization)properties.pNext=&cr; - reinterpret_cast(vk.instance_proc(vk.instance,"vkGetPhysicalDeviceProperties2"))(vk.physical,&properties); - const auto tier=leonida::conservative_raster::tier(vk.conservative_rasterization, - properties.properties.limits.subPixelPrecisionBits,cr.primitiveOverestimationSize,cr.degenerateTrianglesRasterized==VK_TRUE); - if(!vk.buffer_device_address||properties.properties.limits.maxPushConstantsSize<144)return 77; - const auto vs_program=d3d12test::fssm_program({0x54325653,0xbf810000}); - const auto ps_program=d3d12test::fssm_program({0x54325053,0xbf810000}); - const auto vs_bytes=d3d12test::shader_container(vs_program),ps_bytes=d3d12test::shader_container(ps_program); - const auto directory=std::filesystem::temp_directory_path()/("leonida_conservative_tier2_"+std::to_string(GetCurrentProcessId())); - std::filesystem::create_directories(directory); - if(!testfiles::copy_file(LEONIDA_CONSERVATIVE_TIER2_VS,directory/"vs.spv")|| - !testfiles::copy_file(LEONIDA_CONSERVATIVE_TIER2_PS,directory/"ps.spv")) return 1; - { - std::ofstream index(directory/"index.json",std::ios::binary); - index<<"{\"vs\":{\"stage\":\"vs\",\"fssm_sha256\":\""< ours,host; - if(FAILED(rt::d3d12::create_vulkan_device(info,IID_PPV_ARGS(&ours.p))))return 1; - D3D12_FEATURE_DATA_D3D12_OPTIONS options{}; - if(FAILED(ours->CheckFeatureSupport(D3D12_FEATURE_D3D12_OPTIONS,&options,sizeof(options)))||unsigned(options.ConservativeRasterizationTier)!=tier)return 1; - if(tier<2){std::puts("SKIP: device does not meet conservative raster Tier 2 requirements");return 77;} - std::string adapter;if(!copycmp::create_host(host,adapter))return 1; - if(FAILED(host->CheckFeatureSupport(D3D12_FEATURE_D3D12_OPTIONS,&options,sizeof(options))))return 1; - if(options.ConservativeRasterizationTier(reinterpret_cast(GetProcAddress(compiler,"D3DCompile"))):nullptr; - if(!compile)return 77; - const char* hlsl="struct O{float4 p:SV_Position;float m:COLOR;}; O vs(float3 p:POSITION,float m:COLOR){O o;o.p=float4(p,1);o.m=m;return o;} float4 ps(O o,bool front:SV_IsFrontFace):SV_Target{return float4(o.m,o.p.z,front?1:0,1);}"; - copycmp::Ptr vs,ps,error; - if(FAILED(compile(hlsl,std::strlen(hlsl),nullptr,nullptr,nullptr,"vs","vs_5_0",0,0,&vs.p,&error.p))|| - FAILED(compile(hlsl,std::strlen(hlsl),nullptr,nullptr,nullptr,"ps","ps_5_0",0,0,&ps.p,nullptr)))return 1; - Fixture a,b; - if(!setup(a,ours.p,true,{vs_bytes.data(),vs_bytes.size()},{ps_bytes.data(),ps_bytes.size()})|| - !setup(b,host.p,false,{vs->GetBufferPointer(),vs->GetBufferSize()},{ps->GetBufferPointer(),ps->GetBufferSize()}))return 1; - const D3D12_INPUT_ELEMENT_DESC elements[]={ - {"POSITION",0,DXGI_FORMAT_R32G32B32_FLOAT,0,0,D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA,0}, - {"COLOR",0,DXGI_FORMAT_R32_FLOAT,0,12,D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA,0}}; - a.input=b.input=elements; - const D3D12_RECT full{0,0,32,32},inset{8,8,24,24}; - unsigned tight_cases=0,degenerate_cases=0; - const Triangle tight_scenes[]={ - {{{8.015625,4.25},{9.25,4.25},{8.015625,24.25}}}, - {{{3.125,8.001953125},{28.125,8.005859375},{3.125,9.125}}}, - {{{3.125,3.125},{28.125,28.125},{3.125,3.140625}}}, - {{{-0.125,8.125},{12.125,8.125},{8.125,28.125}}}, - }; - for(auto* fixture:{&a,&b})for(const auto& triangle:tight_scenes)for(const auto scissor:{full,inset}) { - Mask mask{};std::vector rgba; - const auto input=vertices(std::vector(triangle.begin(),triangle.end()),{0,1,2},D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST); - if(!render(*fixture,triangle,true,1,false,scissor,mask,D3D12_CULL_MODE_NONE,&input,&rgba)|| - !tight_coverage(triangle,nullptr,scissor,mask))return 1; - ++tight_cases; - } - constexpr double delta=1.0/(1u<<20); - const std::vector> collapsed={ - {{16.125,16.125},{16.125+delta,16.125},{16.125,16.125+delta}}, - {{4.125,16.125},{24.125,16.125},{4.125,16.125+delta}}, - {{4.125,4.125},{24.125,24.125},{4.125,4.125+delta}}, - {{16,16},{16+delta,16},{16,16+delta}}, - {{4.125,16.125},{24.125,16.125},{12.125,16.125}}, - {{16.125,16.125},{16.125,16.125},{16.125,16.125}}, - {{16.125,16.125},{16.125+delta,16.125},{16.125,16.125+delta},{16.125+delta,16.125+delta}}, - }; - for(auto* fixture:{&a,&b})for(const auto& points:collapsed) - for(const auto scissor:{full,inset})for(const bool variant:{false,true}) { - std::vector> orders=points.size()==4 - ?std::vector>{{0,1,2,3},{3,2,1,0}} - :std::vector>{{0,1,2},{2,1,0},{1,2,0}}; - // WARP drops the exact pixel-corner fixture; retain a strict opt-in reproducer. - if (!fixture->run.ours && adapter.find("Microsoft Basic") != std::string::npos && points[0].x == 16 && !warp_corner) { - std::puts("WARP reference: corner fixture excluded (use --warp-corner to reproduce); Vulkan still checks it"); - continue; - } - for(const auto& order:orders) { - const bool strip=points.size()==4; - const auto input=vertices(points,order,strip?D3D_PRIMITIVE_TOPOLOGY_TRIANGLESTRIP:D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST); - const auto triangle=actual_triangle(input); - const auto snapped=quantized(triangle,properties.properties.limits.subPixelPrecisionBits); - const bool must_have_area = points.size() == 4 || points[2].y != points[0].y; - if (cross(snapped) != 0 || (must_have_area && cross(triangle) == 0)) { - std::fprintf(stderr,"fixture lost its intended pre/post-snap area\n"); return 1; - } - for(const auto cull:{D3D12_CULL_MODE_NONE,D3D12_CULL_MODE_FRONT,D3D12_CULL_MODE_BACK}) { - Mask mask{};std::vector rgba; - if(!render(*fixture,triangle,true,1,variant,scissor,mask,cull,&input,&rgba))return 1; - if(cull==D3D12_CULL_MODE_BACK) { - if(std::any_of(mask.begin(),mask.end(),[](bool x){return x;})){std::fprintf(stderr,"post-snap degenerate was not back-facing\n");return 1;} - } else if(!tight_coverage(triangle,&snapped,scissor,mask)||!attributes(mask,rgba,order[strip?1:0])) { - std::fprintf(stderr,"%s degenerate points=%zu first=%u strip=%d cull=%u\n", - fixture->run.ours?"Vulkan":adapter.c_str(),points.size(),order[0],int(strip),unsigned(cull)); std::fprintf(stderr,"point=(%.9f,%.9f) scissor=%ld variant=%d\n",points[0].x,points[0].y,scissor.left,int(variant));return 1; - } - ++degenerate_cases; - } - } - } - std::printf("Tier 2: %u tight-bound scenes and %u degenerate draw cases across Vulkan and %s; colour/constant-depth/facing, index permutations, strips, culling, scissor and variants checked\n", - tight_cases,degenerate_cases,adapter.c_str()); - return vk.validation_errors()?1:0; -} diff --git a/runtime/test/d3d12_conservative_tier3_reference_test.cpp b/runtime/test/d3d12_conservative_tier3_reference_test.cpp deleted file mode 100644 index c29d86b22..000000000 --- a/runtime/test/d3d12_conservative_tier3_reference_test.cpp +++ /dev/null @@ -1,320 +0,0 @@ -// Native D3D12 reference for SV_InnerCoverage and the matching Vulkan capability report. -#include "vk_test_device.h" -#include "d3d12_copy_compare.h" -#include "d3d12_test_shaders.h" -#include "host_wine.h" - -#include -#include -#include -#include -#include -#include -#include - -#define CHECK(x) do { if (!(x)) { std::fprintf(stderr, "line %d: %s\n", __LINE__, #x); return false; } } while (0) - -namespace { -constexpr UINT width = 32, height = 32, pitch = 256; -constexpr double required_margin = 1.0 / 64.0; -const D3D12_RECT full_scissor{0, 0, LONG(width), LONG(height)}; - -struct Point { - double x, y; -}; -using Triangle = std::array; -using VertexData = std::array; - -struct Fixture { - copycmp::Run run; - copycmp::Ptr root; - D3D12_SHADER_BYTECODE vs{}, ps{}; -}; - -double cross(Point a, Point b, Point p) { - return (b.x - a.x) * (p.y - a.y) - (b.y - a.y) * (p.x - a.x); -} - -bool pixel_inside(const Triangle& triangle, UINT x, UINT y, double margin) { - const double winding = cross(triangle[0], triangle[1], triangle[2]); - if (std::abs(winding) < 1e-12) return false; - const double orientation = winding > 0 ? 1.0 : -1.0; - const Point corners[] = {{double(x), double(y)}, {double(x + 1), double(y)}, - {double(x), double(y + 1)}, {double(x + 1), double(y + 1)}}; - for (unsigned edge = 0; edge < 3; ++edge) { - const Point a = triangle[edge], b = triangle[(edge + 1) % 3]; - const double length = std::hypot(b.x - a.x, b.y - a.y); - if (length == 0) return false; - for (const Point corner : corners) - if (orientation * cross(a, b, corner) / length <= margin) return false; - } - return true; -} - -VertexData vertex_data(const Triangle& triangle) { - VertexData out{}; - for (unsigned i = 0; i < 3; ++i) { - out[i * 2] = float(triangle[i].x * 2 / width - 1); - out[i * 2 + 1] = float(1 - triangle[i].y * 2 / height); - } - return out; -} - -Triangle actual_triangle(const VertexData& input) { - Triangle triangle{}; - for (unsigned i = 0; i < 3; ++i) - triangle[i] = {(double(input[i * 2]) + 1) * width / 2, - (1 - double(input[i * 2 + 1])) * height / 2}; - return triangle; -} - -bool compile_shader(pD3DCompile compile, const char* source, const char* entry, const char* profile, - copycmp::Ptr& code) { - copycmp::Ptr error; - const HRESULT result = compile(source, std::strlen(source), nullptr, nullptr, nullptr, entry, profile, 0, 0, - &code.p, &error.p); - if (SUCCEEDED(result)) return true; - std::fprintf(stderr, "D3DCompile %s failed: 0x%08x", entry, unsigned(result)); - if (error.p) std::fprintf(stderr, ": %.*s", int(error->GetBufferSize()), - static_cast(error->GetBufferPointer())); - std::fputc('\n', stderr); - return false; -} - -bool setup(Fixture& fixture, ID3D12Device* device, D3D12_SHADER_BYTECODE vs, D3D12_SHADER_BYTECODE ps) { - fixture.vs = vs; - fixture.ps = ps; - if (!fixture.run.init(device, false)) return false; - - D3D12_VERSIONED_ROOT_SIGNATURE_DESC desc{}; - desc.Version = D3D_ROOT_SIGNATURE_VERSION_1_0; - desc.Desc_1_0.Flags = D3D12_ROOT_SIGNATURE_FLAG_ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT; - const auto bytes = d3d12test::serialize_root_signature(desc); - CHECK(!bytes.empty()); - CHECK(SUCCEEDED(device->CreateRootSignature(0, bytes.data(), bytes.size(), IID_PPV_ARGS(&fixture.root.p)))); - return true; -} - -bool render(Fixture& fixture, const Triangle& triangle, std::vector& rgba) { - static const D3D12_INPUT_ELEMENT_DESC element{ - "POSITION", 0, DXGI_FORMAT_R32G32_FLOAT, 0, 0, D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0}; - D3D12_GRAPHICS_PIPELINE_STATE_DESC desc{}; - desc.pRootSignature = fixture.root.p; - desc.VS = fixture.vs; - desc.PS = fixture.ps; - desc.InputLayout = {&element, 1}; - desc.RasterizerState.FillMode = D3D12_FILL_MODE_SOLID; - desc.RasterizerState.CullMode = D3D12_CULL_MODE_NONE; - desc.RasterizerState.DepthClipEnable = TRUE; - desc.RasterizerState.ConservativeRaster = D3D12_CONSERVATIVE_RASTERIZATION_MODE_ON; - desc.PrimitiveTopologyType = D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE; - desc.NumRenderTargets = 1; - desc.RTVFormats[0] = DXGI_FORMAT_R8G8B8A8_UNORM; - desc.BlendState.RenderTarget[0].RenderTargetWriteMask = D3D12_COLOR_WRITE_ENABLE_ALL; - desc.SampleDesc.Count = 1; - desc.SampleMask = UINT_MAX; - - copycmp::Ptr pso; - const HRESULT pipeline_result = fixture.run.device->CreateGraphicsPipelineState(&desc, IID_PPV_ARGS(&pso.p)); - if (FAILED(pipeline_result)) { - std::fprintf(stderr, "CreateGraphicsPipelineState failed: 0x%08x\n", unsigned(pipeline_result)); - return false; - } - - D3D12_RESOURCE_DESC tex{}; - tex.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D; - tex.Width = width; - tex.Height = height; - tex.DepthOrArraySize = tex.MipLevels = 1; - tex.Format = DXGI_FORMAT_R8G8B8A8_UNORM; - tex.SampleDesc.Count = 1; - tex.Flags = D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET; - copycmp::Ptr target, vertices, readback; - CHECK(fixture.run.texture(tex, D3D12_RESOURCE_STATE_RENDER_TARGET, target)); - CHECK(fixture.run.buffer(D3D12_HEAP_TYPE_UPLOAD, sizeof(VertexData), D3D12_RESOURCE_STATE_GENERIC_READ, vertices)); - CHECK(fixture.run.buffer(D3D12_HEAP_TYPE_READBACK, pitch * height, D3D12_RESOURCE_STATE_COPY_DEST, readback)); - - const VertexData input = vertex_data(triangle); - void* data = nullptr; - const D3D12_RANGE none{}; - CHECK(SUCCEEDED(vertices->Map(0, &none, &data))); - std::memcpy(data, input.data(), sizeof(input)); - vertices->Unmap(0, nullptr); - - copycmp::Ptr heap; - const D3D12_DESCRIPTOR_HEAP_DESC heap_desc{D3D12_DESCRIPTOR_HEAP_TYPE_RTV, 1}; - CHECK(SUCCEEDED(fixture.run.device->CreateDescriptorHeap(&heap_desc, IID_PPV_ARGS(&heap.p)))); - const auto handle = heap->GetCPUDescriptorHandleForHeapStart(); - fixture.run.device->CreateRenderTargetView(target.p, nullptr, handle); - - fixture.run.begin(); - const float clear[4] = {}; - fixture.run.list->ClearRenderTargetView(handle, clear, 0, nullptr); - fixture.run.list->OMSetRenderTargets(1, &handle, FALSE, nullptr); - fixture.run.list->SetGraphicsRootSignature(fixture.root.p); - fixture.run.list->SetPipelineState(pso.p); - const D3D12_VIEWPORT viewport{0, 0, float(width), float(height), 0, 1}; - fixture.run.list->RSSetViewports(1, &viewport); - fixture.run.list->RSSetScissorRects(1, &full_scissor); - const D3D12_VERTEX_BUFFER_VIEW vb{vertices->GetGPUVirtualAddress(), sizeof(input), 8}; - fixture.run.list->IASetVertexBuffers(0, 1, &vb); - fixture.run.list->IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST); - fixture.run.list->DrawInstanced(3, 1, 0, 0); - fixture.run.barrier(target.p, D3D12_RESOURCE_STATE_RENDER_TARGET, D3D12_RESOURCE_STATE_COPY_SOURCE); - - D3D12_TEXTURE_COPY_LOCATION from{}, to{}; - from.pResource = target.p; - from.Type = D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX; - to.pResource = readback.p; - to.Type = D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT; - to.PlacedFootprint.Footprint = {tex.Format, width, height, 1, pitch}; - fixture.run.list->CopyTextureRegion(&to, 0, 0, 0, &from, nullptr); - const std::string error = fixture.run.submit(); - if (!error.empty()) { - std::fprintf(stderr, "%s\n", error.c_str()); - return false; - } - - const D3D12_RANGE read_range{0, pitch * height}; - CHECK(SUCCEEDED(readback->Map(0, &read_range, &data))); - const auto* pixels = static_cast(data); - rgba.resize(width * height * 4); - for (UINT y = 0; y < height; ++y) - std::copy_n(pixels + y * pitch, width * 4, rgba.begin() + y * width * 4); - readback->Unmap(0, &none); - return true; -} -} // namespace - -int main() { - if (hostwine::host_is_wine()) return 77; - - vktest::Device vk; - const auto vk_status = vk.initialize(); - if (vk_status == vktest::DeviceStatus::unavailable) return 77; - if (vk_status != vktest::DeviceStatus::ready) return 1; - - VkPhysicalDeviceConservativeRasterizationPropertiesEXT conservative{ - VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_CONSERVATIVE_RASTERIZATION_PROPERTIES_EXT}; - VkPhysicalDeviceIDProperties id{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_ID_PROPERTIES}; - id.pNext = vk.conservative_rasterization ? &conservative : nullptr; - VkPhysicalDeviceProperties2 properties{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROPERTIES_2, &id}; - const auto get_properties2 = reinterpret_cast( - vk.instance_proc(vk.instance, "vkGetPhysicalDeviceProperties2")); - if (!get_properties2) return 1; - get_properties2(vk.physical, &properties); - - std::printf("Vulkan adapter: %s; VK_EXT_conservative_rasterization=%s; " - "fullyCoveredFragmentShaderInputVariable=%s; subPixelPrecisionBits=%u\n", - properties.properties.deviceName, vk.conservative_rasterization ? "yes" : "no", - vk.conservative_rasterization - ? (conservative.fullyCoveredFragmentShaderInputVariable ? "true" : "false") - : "unavailable", - properties.properties.limits.subPixelPrecisionBits); - - if (!id.deviceLUIDValid) { - std::puts("SKIP: Vulkan did not expose a device LUID to match its native D3D12 adapter"); - return 77; - } - static_assert(sizeof(LUID) == VK_LUID_SIZE); - LUID luid{}; - std::memcpy(&luid, id.deviceLUID, sizeof(luid)); - copycmp::Ptr device; - std::string adapter; - if (!copycmp::try_create_host(device, adapter, &luid)) { - std::puts("SKIP: no native D3D12 device for the selected Vulkan adapter"); - return 77; - } - - D3D12_FEATURE_DATA_D3D12_OPTIONS options{}; - if (FAILED(device->CheckFeatureSupport(D3D12_FEATURE_D3D12_OPTIONS, &options, sizeof(options)))) return 1; - std::printf("Native D3D12 adapter: %s; ConservativeRasterizationTier=%u\n", - adapter.c_str(), unsigned(options.ConservativeRasterizationTier)); - if (options.ConservativeRasterizationTier < D3D12_CONSERVATIVE_RASTERIZATION_TIER_3) { - std::puts("SKIP: native D3D12 Tier 3 is required for the SV_InnerCoverage reference"); - return 77; - } - - const HMODULE compiler_module = LoadLibraryExA("d3dcompiler_47.dll", nullptr, LOAD_LIBRARY_SEARCH_SYSTEM32); - const auto compile = compiler_module ? reinterpret_cast( - reinterpret_cast(GetProcAddress(compiler_module, "D3DCompile"))) : nullptr; - if (!compile) { - std::puts("SKIP: d3dcompiler_47.dll is required for the synthetic reference shader"); - return 77; - } - const char* hlsl = - "float4 vs(float2 p:POSITION):SV_Position{return float4(p,0.5,1);}" - "float4 ps(uint inner:SV_InnerCoverage):SV_Target0{" - "return float4(1,(inner&1u)?1:0,inner==0u?1:0,1);}"; - copycmp::Ptr vs, ps; - if (!compile_shader(compile, hlsl, "vs", "vs_5_0", vs) || - !compile_shader(compile, hlsl, "ps", "ps_5_0", ps)) return 1; - - Fixture fixture; - if (!setup(fixture, device.p, {vs->GetBufferPointer(), vs->GetBufferSize()}, - {ps->GetBufferPointer(), ps->GetBufferSize()})) return 1; - - const Triangle scenes[] = { - {{{3.125, 3.125}, {28.125, 3.125}, {3.125, 28.125}}}, - {{{3.125, 6.125}, {27.125, 11.125}, {8.125, 28.125}}}, - {{{4.125, 24.125}, {27.125, 6.125}, {27.125, 25.125}}}, - {{{3.125, 8.125}, {28.125, 8.625}, {16.125, 25.125}}}, - }; - unsigned required_pixels = 0, inner_pixels = 0, fragments = 0; - for (const Triangle& scene : scenes) { - const VertexData input = vertex_data(scene); - const Triangle triangle = actual_triangle(input); - std::vector rgba; - if (!render(fixture, triangle, rgba)) return 1; - - unsigned scene_required = 0; - for (UINT y = 0; y < height; ++y) { - for (UINT x = 0; x < width; ++x) { - const std::size_t pixel = (std::size_t(y) * width + x) * 4; - const bool ran = rgba[pixel] == 255; - const bool inner = rgba[pixel + 1] == 255; - const bool zero = rgba[pixel + 2] == 255; - if (!ran) { - if (inner || zero || rgba[pixel + 3]) { - std::fprintf(stderr, "background pixel (%u,%u) was unexpectedly written\n", x, y); - return 1; - } - continue; - } - if (rgba[pixel + 3] != 255) { - std::fprintf(stderr, "fragment at (%u,%u) did not write alpha\n", x, y); - return 1; - } - ++fragments; - if (inner == zero) { - std::fprintf(stderr, "SV_InnerCoverage encoding at (%u,%u) is not false=0 / true=odd\n", x, y); - return 1; - } - if (inner) { - if (!pixel_inside(triangle, x, y, -1e-10)) { - std::fprintf(stderr, "false positive InnerCoverage at (%u,%u)\n", x, y); - return 1; - } - ++inner_pixels; - } - if (pixel_inside(triangle, x, y, required_margin)) { - ++scene_required; - if (!inner) { - std::fprintf(stderr, "missing guaranteed InnerCoverage at (%u,%u)\n", x, y); - return 1; - } - } - } - } - if (!scene_required) { - std::fprintf(stderr, "reference scene has no pixels beyond the inner uncertainty margin\n"); - return 1; - } - required_pixels += scene_required; - } - - std::printf("SV_InnerCoverage reference: %u scenes, %u conservative fragments, %u inner pixels, " - "%u guaranteed interior pixels checked; no false positives\n", - unsigned(std::size(scenes)), fragments, inner_pixels, required_pixels); - return 0; -} diff --git a/runtime/test/d3d12_conservative_tier3_test.cpp b/runtime/test/d3d12_conservative_tier3_test.cpp deleted file mode 100644 index a5a7be2be..000000000 --- a/runtime/test/d3d12_conservative_tier3_test.cpp +++ /dev/null @@ -1,192 +0,0 @@ -// Explicit FullyCoveredEXT library contract versus native SV_InnerCoverage. Synthetic data only. -#include "conservative_raster_fixture.h" -using namespace conservative_test; - -namespace { -double cross(Point a, Point b, Point p) { - return (b.x-a.x)*(p.y-a.y)-(b.y-a.y)*(p.x-a.x); -} - -// Same geometric construction as #3970. The conservative margin avoids implementation-dependent edge pixels. -bool inside(const Triangle& t, UINT x, UINT y, double margin) { - const double winding = cross(t[0],t[1],t[2]); - if (std::abs(winding)<1e-12) return false; - const double sign = winding>0 ? 1.0 : -1.0; - const Point corners[]={{double(x),double(y)},{double(x+1),double(y)}, - {double(x),double(y+1)},{double(x+1),double(y+1)}}; - for (unsigned i=0;i<3;++i) { - const Point a=t[i], b=t[(i+1)%3]; - const double length=std::hypot(b.x-a.x,b.y-a.y); - if (!length) return false; - for (const auto p:corners) if (sign*cross(a,b,p)/length<=margin) return false; - } - return true; -} - -bool oracle(const Triangle& t, const D3D12_RECT& scissor, const Mask& mask, - const std::vector& rgba, bool log=true) { - for (UINT y=0;y=scissor.left && LONG(x)=scissor.top && LONG(y) rgba(width*height*4); - for (UINT y=0;y device; - CHECK(SUCCEEDED(rt::d3d12::create_vulkan_device(info,IID_PPV_ARGS(&device.p)))); - D3D12_FEATURE_DATA_D3D12_OPTIONS options{}; - CHECK(SUCCEEDED(device->CheckFeatureSupport(D3D12_FEATURE_D3D12_OPTIONS,&options,sizeof(options)))); - CHECK(unsigned(options.ConservativeRasterizationTier)==expected_tier); - Fixture fixture; CHECK(setup(fixture,device.p,true,vs,ps)); - for (const bool conservative:{false,true}) { - auto desc=description(fixture,conservative,1,false); - copycmp::Ptr pso; - CHECK(device->CreateGraphicsPipelineState(&desc,IID_PPV_ARGS(&pso.p))==E_NOTIMPL); - CHECK(!pso.p); - } - return true; -} -} // namespace - -int main(int argc, char** argv) { - if (!oracle_controls()) return 1; - if (argc>1 && std::strcmp(argv[1],"--oracle-only")==0) return 0; - const bool guards_only=argc>1 && std::strcmp(argv[1],"--guards-only")==0; - const bool native_only=argc>1 && std::strcmp(argv[1],"--native-only")==0; - if (hostwine::host_is_wine()) return 77; - vktest::Device vk; vk.request_buffer_device_address=true; - const auto status=vk.initialize(); - if (status==vktest::DeviceStatus::unavailable) return 77; - if (status!=vktest::DeviceStatus::ready) return 1; - VkPhysicalDeviceConservativeRasterizationPropertiesEXT cr{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_CONSERVATIVE_RASTERIZATION_PROPERTIES_EXT}; - VkPhysicalDeviceIDProperties id{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_ID_PROPERTIES}; - id.pNext=vk.conservative_rasterization?&cr:nullptr; - VkPhysicalDeviceProperties2 properties{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROPERTIES_2,&id}; - const auto get_properties=reinterpret_cast(vk.instance_proc(vk.instance,"vkGetPhysicalDeviceProperties2")); - if (!get_properties) return 1; - get_properties(vk.physical,&properties); - if (!vk.buffer_device_address || properties.properties.limits.maxPushConstantsSize<144) return 77; - const auto vs_program=d3d12test::fssm_program({0x54335653,0xbf810000}); - const auto ps_program=d3d12test::fssm_program({0x54335053,0xbf810000}); - const auto vs_bytes=d3d12test::shader_container(vs_program), ps_bytes=d3d12test::shader_container(ps_program); - const auto dir=std::filesystem::temp_directory_path()/("leonida_conservative_tier3_"+std::to_string(GetCurrentProcessId())); - std::filesystem::create_directories(dir); - if(!testfiles::copy_file(LEONIDA_CONSERVATIVE_VS,dir/"vs.spv")|| - !testfiles::copy_file(LEONIDA_CONSERVATIVE_TIER3_PS,dir/"ps.spv")) return 1; - { - // Omit optional capability metadata deliberately: the actual SPIR-V must enforce the unsupported guard. - std::ofstream out(dir/"index.json",std::ios::binary); - out<<"{\"vs\":{\"stage\":\"vs\",\"fssm_sha256\":\""< host,ours; std::string adapter; - if (!copycmp::try_create_host(host,adapter,&luid)) return 77; - D3D12_FEATURE_DATA_D3D12_OPTIONS options{}; - if (FAILED(host->CheckFeatureSupport(D3D12_FEATURE_D3D12_OPTIONS,&options,sizeof(options)))) return 1; - if (options.ConservativeRasterizationTier(reinterpret_cast(GetProcAddress(dll,"D3DCompile"))):nullptr; - if (!compile) return 77; - const char* hlsl="float4 vs(float2 p:POSITION):SV_Position{return float4(p,0.5,1);}" - "float4 ps(uint inner:SV_InnerCoverage):SV_Target0{return float4(1,(inner&1u)?1:0,inner==0u?1:0,1);}"; - copycmp::Ptr vs,ps,error; - if (FAILED(compile(hlsl,std::strlen(hlsl),nullptr,nullptr,nullptr,"vs","vs_5_0",0,0,&vs.p,&error.p)) || - FAILED(compile(hlsl,std::strlen(hlsl),nullptr,nullptr,nullptr,"ps","ps_5_0",0,0,&ps.p,nullptr))) return 1; - Fixture a,b; - if (!native_only) { - if (FAILED(rt::d3d12::create_vulkan_device(info,IID_PPV_ARGS(&ours.p)))) return 1; - if (FAILED(ours->CheckFeatureSupport(D3D12_FEATURE_D3D12_OPTIONS,&options,sizeof(options))) || - options.ConservativeRasterizationTier!=D3D12_CONSERVATIVE_RASTERIZATION_TIER_3) return 1; - if (!setup(a,ours.p,true,vs_code,ps_code)) return 1; - } - if (!setup(b,host.p,false,{vs->GetBufferPointer(),vs->GetBufferSize()},{ps->GetBufferPointer(),ps->GetBufferSize()})) return 1; - const Triangle scenes[]={ - {{{3.125,3.125},{28.125,3.125},{3.125,28.125}}}, - {{{3.125,6.125},{27.125,11.125},{8.125,28.125}}}, - {{{4.125,24.125},{27.125,6.125},{27.125,25.125}}}, - {{{3.125,8.125},{28.125,8.625},{16.125,25.125}}}, - {{{3.0625,3.0625},{3.3125,3.0625},{3.0625,3.3125}}}, - {{{4.125,16.125},{24.125,16.125},{12.125,16.125}}}, - }; - unsigned comparisons=0; - for (const auto& triangle:scenes) for (const UINT samples:{1u,4u}) - for (const bool variant:{false,true}) for (const D3D12_RECT scissor:{D3D12_RECT{0,0,32,32},D3D12_RECT{8,8,24,24}}) { - // InnerCoverage is undefined in D3D12 when conservative rasterization is off: no off-mode oracle. - for (auto* fixture:{&a,&b}) { - if (native_only && fixture==&a) continue; - Mask mask{}; std::vector rgba; - if (!render(*fixture,triangle,true,samples,variant,scissor,mask,D3D12_CULL_MODE_NONE,nullptr,&rgba) || - !coverage(triangle,scissor,mask) || !oracle(triangle,scissor,mask,rgba)) { - std::fprintf(stderr,"%s Tier 3 scene=%zu samples=%u variant=%d scissor=%ld\n", - fixture->run.ours?"Vulkan":adapter.c_str(),std::size_t(&triangle-scenes),samples,int(variant),scissor.left); - return 1; - } - } - ++comparisons; - } - std::printf("Tier 3 explicit ABI: %u %s %s scenarios; inner positives/negatives, 1x/4x, scissor and variants\n", - comparisons,native_only?"native-only":"Vulkan/native paired",adapter.c_str()); - return vk.validation_errors()?1:0; -} diff --git a/runtime/test/d3d12_console_descriptor_heap_test.cpp b/runtime/test/d3d12_console_descriptor_heap_test.cpp deleted file mode 100644 index ed2d901f4..000000000 --- a/runtime/test/d3d12_console_descriptor_heap_test.cpp +++ /dev/null @@ -1,156 +0,0 @@ -// Console Xbox CreateDescriptorHeap (issue #313 comment 7107265058) passes a 16-byte PC -// D3D12_DESCRIPTOR_HEAP_DESC followed by address at +0x10 and size at +0x18. The title asserts -// GetCPUDescriptorHandleForHeapStart() == address. This tests the explicit Leonida console-heap -// creation path used by the Xbox device proxy slot 14. It does not cover title-memory aliasing / -// section 3.3 backing. -#include "vk_test_device.h" -#include "../shims/d3d12_com.h" -#include "../shims/d3d12_xs_device.h" - -#include -#include - -namespace { - -template -struct Ref { - T* p = nullptr; - ~Ref() { if (p) p->Release(); } - T** put() { - if (p) { - p->Release(); - p = nullptr; - } - return &p; - } - T* get() const { return p; } - T* operator->() const { return p; } -}; - -bool check_console_addressed_heap(ID3D12Device* device) { - D3D12_DESCRIPTOR_HEAP_DESC desc{}; - desc.Type = D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV; - desc.NumDescriptors = 8; - desc.Flags = D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE; - desc.NodeMask = 0; - const D3D12_GPU_VIRTUAL_ADDRESS address = 0x112233440000ull; - const std::uint64_t size = 8ull * 32ull; - - Ref heap; - const HRESULT hr = rt::d3d12::create_console_descriptor_heap( - device, &desc, address, size, IID_PPV_ARGS(heap.put())); - if (FAILED(hr) || !heap.get()) { - std::fprintf(stderr, "create_console_descriptor_heap failed: 0x%08lx\n", static_cast(hr)); - return false; - } - const auto cpu = heap->GetCPUDescriptorHandleForHeapStart(); - if (cpu.ptr != static_cast(address)) { - std::fprintf(stderr, "CPU heap start mismatch: got 0x%llx want 0x%llx\n", - static_cast(cpu.ptr), static_cast(address)); - return false; - } - const auto gpu = heap->GetGPUDescriptorHandleForHeapStart(); - if (gpu.ptr != address) { - std::fprintf(stderr, "GPU heap start mismatch: got 0x%llx want 0x%llx\n", - static_cast(gpu.ptr), static_cast(address)); - return false; - } - const D3D12_DESCRIPTOR_HEAP_DESC got = heap->GetDesc(); - if (got.Type != desc.Type || got.NumDescriptors != desc.NumDescriptors || got.Flags != desc.Flags || - got.NodeMask != 1) { - std::fprintf(stderr, "GetDesc mismatch\n"); - return false; - } - return true; -} - -bool check_xs_proxy_slot14(ID3D12Device* real_device) { - Ref proxy; - real_device->AddRef(); // create_device_proxy takes ownership of one reference on success - if (FAILED(rt::d3d12_xs::create_device_proxy(real_device, IID_PPV_ARGS(&proxy.p))) || !proxy.p) { - real_device->Release(); // the caller keeps its reference on failure - std::fprintf(stderr, "create_device_proxy failed\n"); - return false; - } - - struct ConsoleDescriptorHeapDesc { - D3D12_DESCRIPTOR_HEAP_DESC desc{}; - std::uint64_t address = 0; - std::uint64_t size = 0; - } console{}; - console.desc.Type = D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV; - console.desc.NumDescriptors = 4; - console.desc.Flags = D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE; - console.address = 0x556677880000ull; - console.size = 4ull * 32ull; - - Ref heap; - const HRESULT hr = proxy->CreateDescriptorHeap(&console.desc, IID_PPV_ARGS(heap.put())); - if (FAILED(hr) || !heap.get()) { - std::fprintf(stderr, "proxy CreateDescriptorHeap(console) failed: 0x%08lx\n", - static_cast(hr)); - return false; - } - // The proxy's own GetCPUDescriptorHandleForHeapStart answers the console (RAX) convention; this test is a PC - // caller, so read the wrapped heap's PC method. The address proves slot 14 passed the console VA through. - ID3D12DescriptorHeap* real = rt::d3d12_xs::heap_proxy_real_heap(heap.p); - if (!real) { - std::fprintf(stderr, "heap proxy has no real heap\n"); - return false; - } - const auto cpu = real->GetCPUDescriptorHandleForHeapStart(); - if (cpu.ptr != static_cast(console.address)) { - std::fprintf(stderr, "proxy CPU heap start mismatch: got 0x%llx want 0x%llx\n", - static_cast(cpu.ptr), - static_cast(console.address)); - return false; - } - return true; -} - -bool check_normal_heap_unchanged(ID3D12Device* device) { - D3D12_DESCRIPTOR_HEAP_DESC desc{}; - desc.Type = D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV; - desc.NumDescriptors = 4; - desc.Flags = D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE; - Ref heap; - const HRESULT hr = device->CreateDescriptorHeap(&desc, IID_PPV_ARGS(heap.put())); - if (FAILED(hr) || !heap.get()) { - std::fprintf(stderr, "CreateDescriptorHeap(normal) failed: 0x%08lx\n", static_cast(hr)); - return false; - } - const auto cpu = heap->GetCPUDescriptorHandleForHeapStart(); - if (cpu.ptr == 0) { - std::fprintf(stderr, "normal heap CPU start is null\n"); - return false; - } - return true; -} - -} // namespace - -int main() { - vktest::Device vk; - const auto status = vk.initialize(); - if (status == vktest::DeviceStatus::unavailable) return 77; - if (status != vktest::DeviceStatus::ready) return 1; - - Ref device; - rt::d3d12::VulkanDeviceInfo info{}; - info.get_instance_proc = vk.instance_proc; - info.instance = vk.instance; - info.physical = vk.physical; - info.device = vk.device; - info.queue = vk.queue; - info.queue_family = vk.family; - if (FAILED(rt::d3d12::create_vulkan_device(info, IID_PPV_ARGS(device.put()))) || !device.get()) { - std::fprintf(stderr, "create_vulkan_device failed\n"); - return 1; - } - - if (!check_normal_heap_unchanged(device.get())) return 1; - if (!check_console_addressed_heap(device.get())) return 1; - if (!check_xs_proxy_slot14(device.get())) return 1; - std::fprintf(stderr, "ok\n"); - return 0; -} diff --git a/runtime/test/d3d12_copy_compare.h b/runtime/test/d3d12_copy_compare.h deleted file mode 100644 index 6a9a83118..000000000 --- a/runtime/test/d3d12_copy_compare.h +++ /dev/null @@ -1,750 +0,0 @@ -// D3D-46: copies compared with the host PC runtime (or WARP). Included by d3d12_vulkan_device_test.cpp. -// The same scenario runs on the layer's device and on a host D3D12 device: textures are filled from an upload -// buffer with deterministic bytes, copied with CopyResource / CopyTextureRegion (whole subresources, boxes, -// destination offsets, other array slices, placed footprints in both directions) and CopyBufferRegion, read back -// into a readback buffer prefilled with 0xcd, and the bytes are compared. Only the texels a footprint row holds are -// compared (row padding is the driver's); everything else, including the 0xcd around a partial copy, must match. -// Layouts come from the host's GetCopyableFootprints for both sides (those are compared separately). -// LEONIDA_HOST_ADAPTER picks the host side: "warp", or part of an adapter name; unset is the layer's own adapter when -// the test has set layer_adapter(), else the default adapter. -#pragma once -#include -#include -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include "../shims/d3d12_com.h" -#include "host_adapter.h" - -namespace copycmp { - -template -struct Ptr { - T* p = nullptr; - Ptr() = default; - Ptr(const Ptr&) = delete; - ~Ptr() { reset(); } - void reset() { - if (p) p->Release(); - p = nullptr; - } - T* operator->() const { return p; } -}; - -// True under Wine, where there is no host to compare with: the comparisons take Microsoft's d3d12.dll as the -// reference, and Wine's (vkd3d) lays out depth-stencil formats in one plane, rejects R9G9B9E5 and BC footprints, -// accepts descriptions Microsoft's runtime refuses and answers shader model 5.1. Its device also shares the process's -// Vulkan with ours (winevulkan asserted in vkBindBufferMemory). Says so once. -inline bool host_is_wine() { - static const bool wine = GetProcAddress(GetModuleHandleW(L"ntdll.dll"), "wine_get_version") != nullptr; - static bool said = false; - if (wine && !said) std::printf("host D3D12 is Wine's, not Microsoft's: comparisons with the host are skipped\n"); - said = true; - return wine; -} - -// An explicit adapter LUID takes precedence over LEONIDA_HOST_ADAPTER for same-adapter comparisons. -inline bool try_create_host(Ptr& host, std::string& name, const LUID* luid = nullptr) { - if (host_is_wine()) return false; - const HMODULE d3d12 = LoadLibraryExA("d3d12.dll", nullptr, LOAD_LIBRARY_SEARCH_SYSTEM32); - const HMODULE dxgi = LoadLibraryExA("dxgi.dll", nullptr, LOAD_LIBRARY_SEARCH_SYSTEM32); - if (!d3d12 || !dxgi) return false; - const auto create = reinterpret_cast( - reinterpret_cast(GetProcAddress(d3d12, "D3D12CreateDevice"))); - using CreateFactory = HRESULT(WINAPI*)(REFIID, void**); - const auto create_factory = - reinterpret_cast(reinterpret_cast(GetProcAddress(dxgi, "CreateDXGIFactory1"))); - if (!create || !create_factory) return false; - Ptr factory; - if (FAILED(create_factory(IID_PPV_ARGS(&factory.p)))) return false; - // The variable and the name match are host_adapter.h's, shared with the tests that create their host devices - // themselves. - const std::string needle = hostadapter::wanted(); - Ptr adapter; - if (luid) { - if (FAILED(factory->EnumAdapterByLuid(*luid, IID_PPV_ARGS(&adapter.p)))) return false; - } else if (needle == "warp") { - if (FAILED(factory->EnumWarpAdapter(IID_PPV_ARGS(&adapter.p)))) return false; - } else if (!needle.empty()) { - adapter.p = hostadapter::named(factory.p, needle); - if (!adapter.p) return false; - } - if (FAILED(create(adapter.p, D3D_FEATURE_LEVEL_11_0, IID_PPV_ARGS(&host.p)))) return false; - Ptr used; - if (adapter.p) { - used.p = adapter.p; - used.p->AddRef(); - } else { - Ptr base; - if (SUCCEEDED(factory->EnumAdapterByLuid(host->GetAdapterLuid(), IID_PPV_ARGS(&base.p)))) - base->QueryInterface(IID_PPV_ARGS(&used.p)); - } - name = "unknown adapter"; - if (used.p) { - DXGI_ADAPTER_DESC1 desc{}; - used->GetDesc1(&desc); - name.clear(); - for (const wchar_t* c = desc.Description; *c; ++c) name += char(*c < 128 ? *c : '?'); - } - return true; -} - -// The adapter behind the layer's Vulkan device (VkPhysicalDeviceIDProperties::deviceLUID), for a test that knows it. -// On a PC with two GPUs D3D12's default adapter can be the other one, whose driver accepts other formats (an AMD -// layer device accepts an R9G9B9E5 render target that the NVIDIA host refuses), so the comparison would be between -// two GPUs instead of between the layer and the host runtime. -inline std::optional& layer_adapter() { - static std::optional luid; - return luid; -} - -// A host device, or false when there is none (the comparisons are then skipped). Without LEONIDA_HOST_ADAPTER it is -// on the layer's own adapter when that is set and has a D3D12 device, else on the default adapter. When -// LEONIDA_HOST_ADAPTER names an adapter that cannot be had, the run fails: a typo must not turn the comparisons into a -// silent pass. -inline bool create_host(Ptr& host, std::string& name) { - const std::string needle = hostadapter::wanted(); - const bool named = !needle.empty(); - if (!named && layer_adapter() && try_create_host(host, name, &*layer_adapter())) return true; - if (try_create_host(host, name)) return true; - if (named) { - std::fprintf(stderr, "LEONIDA_HOST_ADAPTER=%s: no such adapter, or no D3D12 device on it\n", needle.c_str()); - std::exit(1); - } - return false; -} - -struct Region { - std::string label; - size_t offset = 0, pitch = 0, row_bytes = 0, rows = 0, depth = 1; - bool x8 = false; // D24 depth plane: every fourth byte is the unspecified X8 (the host writes 0, Vulkan leaves it) -}; - -struct Outcome { - std::vector bytes; - std::vector regions; - std::string error; -}; - -struct TexCase { - const char* name; - D3D12_RESOURCE_DIMENSION dim; - DXGI_FORMAT format; - UINT width, height, depth_or_layers; - UINT16 mips; - bool floaty; // bytes stay small so floats are finite - bool ds; // depth-stencil: whole-subresource copies only - bool bc; -}; - -// One device with a direct queue, an allocator, a list and a fence. -struct Run { - ID3D12Device* device = nullptr; - bool ours = false; - Ptr queue; - Ptr allocator; - Ptr list; - Ptr fence; - UINT64 value = 0; - bool refused = false; // the last submit failed at Close or in the layer's replay: the list was rejected - - bool init(ID3D12Device* d, bool is_ours) { - device = d; - ours = is_ours; - D3D12_COMMAND_QUEUE_DESC qd{}; - qd.Type = D3D12_COMMAND_LIST_TYPE_DIRECT; - const auto check_setup = [is_ours](const char* call, HRESULT hr) { - if (SUCCEEDED(hr)) return true; - std::fprintf(stderr, "copy setup: %s %s failed (HRESULT 0x%08x)\n", - is_ours ? "Vulkan" : "host", call, static_cast(hr)); - return false; - }; - return check_setup("CreateCommandQueue", d->CreateCommandQueue(&qd, IID_PPV_ARGS(&queue.p))) && - check_setup("CreateCommandAllocator", - d->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&allocator.p))) && - check_setup("CreateCommandList", d->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, allocator.p, - nullptr, IID_PPV_ARGS(&list.p))) && - check_setup("CreateFence", d->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&fence.p))); - } - // Starts another scenario on the same queue: the list and allocator are reset (a list that failed at Close can be). - bool used = false; - void begin() { - if (used && refused) { // a rejected list is dropped with its allocator rather than reset - list.reset(); - allocator.reset(); - device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&allocator.p)); - device->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, allocator.p, nullptr, IID_PPV_ARGS(&list.p)); - } else if (used) { - allocator->Reset(); - list->Reset(allocator.p, nullptr); - } - refused = false; - used = true; - } - bool buffer(D3D12_HEAP_TYPE heap,UINT64 bytes, D3D12_RESOURCE_STATES state, Ptr& out) { - D3D12_HEAP_PROPERTIES hp{}; - hp.Type = heap; - D3D12_RESOURCE_DESC desc{}; - desc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER; - desc.Width = bytes; - desc.Height = desc.DepthOrArraySize = desc.MipLevels = 1; - desc.SampleDesc.Count = 1; - desc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; - return SUCCEEDED(device->CreateCommittedResource(&hp, D3D12_HEAP_FLAG_NONE, &desc, state, nullptr, - IID_PPV_ARGS(&out.p))); - } - bool texture(const D3D12_RESOURCE_DESC& desc, D3D12_RESOURCE_STATES state, Ptr& out) { - D3D12_HEAP_PROPERTIES hp{}; - hp.Type = D3D12_HEAP_TYPE_DEFAULT; - return SUCCEEDED(device->CreateCommittedResource(&hp, D3D12_HEAP_FLAG_NONE, &desc, state, nullptr, - IID_PPV_ARGS(&out.p))); - } - void barrier(ID3D12Resource* r, D3D12_RESOURCE_STATES before, D3D12_RESOURCE_STATES after) { - D3D12_RESOURCE_BARRIER b{}; - b.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION; - b.Transition.pResource = r; - b.Transition.Subresource = D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES; - b.Transition.StateBefore = before; - b.Transition.StateAfter = after; - list->ResourceBarrier(1, &b); - } - // Close, execute, wait. Returns an error text, or an empty string. - std::string submit() { - if (const HRESULT hr = list->Close(); FAILED(hr)) { refused = true; return "Close failed 0x" + hex(hr); } - ID3D12CommandList* lists[] = {list.p}; - queue->ExecuteCommandLists(1, lists); - if (ours) { - const auto result = rt::d3d12::last_execute_result(queue.p); - if (result != leonida::ReplayResult::success) { - refused = true; - return "the layer refused the list (ReplayResult " + std::to_string(int(result)) + ")"; - } - } - if (FAILED(queue->Signal(fence.p, ++value)) || FAILED(fence->SetEventOnCompletion(value, nullptr))) - return "fence wait failed"; - if (fence->GetCompletedValue() < value) return "fence did not complete"; - if (const HRESULT hr = device->GetDeviceRemovedReason(); FAILED(hr)) return "device removed 0x" + hex(hr); - return {}; - } - static std::string hex(HRESULT hr) { - char text[16]; - std::snprintf(text, sizeof(text), "%08x", static_cast(hr)); - return text; - } -}; - -inline std::uint8_t fill_byte(unsigned seed, size_t index, bool floaty) { - std::uint32_t x = std::uint32_t(index) * 2654435761u ^ seed * 0x9E3779B1u; - x ^= x >> 15; - x *= 0x85ebca6bu; - x ^= x >> 13; - x *= 0xc2b2ae35u; - x ^= x >> 16; - return std::uint8_t(x >> 8) & (floaty ? 0x3f : 0xff); -} - -using Placed = D3D12_PLACED_SUBRESOURCE_FOOTPRINT; - -struct Layout { - std::vector placed; - std::vector rows; - std::vector row_bytes; - UINT64 total = 0; -}; - -inline D3D12_TEXTURE_COPY_LOCATION sub_loc(ID3D12Resource* r, UINT index) { - D3D12_TEXTURE_COPY_LOCATION l{}; - l.pResource = r; - l.Type = D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX; - l.SubresourceIndex = index; - return l; -} - -inline D3D12_TEXTURE_COPY_LOCATION foot_loc(ID3D12Resource* r, const Placed& p) { - D3D12_TEXTURE_COPY_LOCATION l{}; - l.pResource = r; - l.Type = D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT; - l.PlacedFootprint = p; - return l; -} - -// One texture case on one device. `host` supplies the layouts. -inline void run_texture(Run& run, ID3D12Device* host, const TexCase& tc, Outcome& out) { - D3D12_RESOURCE_DESC desc{}; - desc.Dimension = tc.dim; - desc.Width = tc.width; - desc.Height = tc.height; - desc.DepthOrArraySize = UINT16(tc.depth_or_layers); - desc.MipLevels = tc.mips; - desc.Format = tc.format; - desc.SampleDesc.Count = 1; - if (tc.ds) desc.Flags = D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL; - const bool volume = tc.dim == D3D12_RESOURCE_DIMENSION_TEXTURE3D; - const UINT layers = volume ? 1 : tc.depth_or_layers; - D3D12_FEATURE_DATA_FORMAT_INFO info{tc.format, 1}; - host->CheckFeatureSupport(D3D12_FEATURE_FORMAT_INFO, &info, sizeof(info)); - const UINT n = UINT(tc.mips) * layers * info.PlaneCount; - const UINT bw = tc.bc ? 4 : 1; - - // Sets: 0 A (source), 1 B, 2 C, 3 D (prefilled), then readbacks R, B, C, D, A, P. - constexpr int sets = 6; - Layout layout[sets]; - UINT64 total_one = 0; - host->GetCopyableFootprints(&desc, 0, n, 0, nullptr, nullptr, nullptr, &total_one); - const UINT64 stride = (total_one + 511) / 512 * 512; - for (int k = 0; k < sets; ++k) { - Layout& l = layout[k]; - l.placed.resize(n); - l.rows.resize(n); - l.row_bytes.resize(n); - host->GetCopyableFootprints(&desc, 0, n, stride * k, l.placed.data(), l.rows.data(), l.row_bytes.data(), &l.total); - } - - Ptr up, rb, A, B, C, D, R; - constexpr auto copy_dest = D3D12_RESOURCE_STATE_COPY_DEST, copy_source = D3D12_RESOURCE_STATE_COPY_SOURCE; - if (!run.buffer(D3D12_HEAP_TYPE_UPLOAD, stride * 4, D3D12_RESOURCE_STATE_GENERIC_READ, up) || - !run.buffer(D3D12_HEAP_TYPE_READBACK, stride * sets, copy_dest, rb) || - !run.texture(desc, copy_dest, A) || !run.texture(desc, copy_dest, B) || !run.texture(desc, copy_dest, C) || - !run.texture(desc, copy_dest, D) || !run.texture(desc, copy_dest, R)) { - out.error = "resource creation failed"; - return; - } - std::uint8_t *upm = nullptr, *rbm = nullptr; - if (FAILED(up->Map(0, nullptr, reinterpret_cast(&upm))) || - FAILED(rb->Map(0, nullptr, reinterpret_cast(&rbm)))) { - out.error = "Map failed"; - return; - } - std::memset(upm, 0, size_t(stride) * 4); - std::memset(rbm, 0xcd, size_t(stride) * sets); - for (int k = 0; k < 4; ++k) - for (UINT i = 0; i < n; ++i) { - const Placed& p = layout[k].placed[i]; - for (UINT z = 0; z < p.Footprint.Depth; ++z) - for (UINT row = 0; row < layout[k].rows[i]; ++row) - for (UINT64 col = 0; col < layout[k].row_bytes[i]; ++col) { - const size_t at = size_t(p.Offset) + (size_t(z) * layout[k].rows[i] + row) * p.Footprint.RowPitch + size_t(col); - // The X8 byte of D24's depth plane is unspecified; the host stores 0 there, so upload 0. - const bool x8 = tc.format == DXGI_FORMAT_D24_UNORM_S8_UINT && i < UINT(tc.mips) * layers && col % 4 == 3; - std::uint8_t value = x8 ? 0 : fill_byte(unsigned(k + 1) * 7919u + i, (size_t(z) * 4099 + row) * 131 + size_t(col), tc.floaty); - // Float depth: keep every value a normal float (hardware flushes denormal depth on copies). - if (tc.ds && tc.floaty && i < UINT(tc.mips) * layers && col % 4 == 3) value |= 0x20; - upm[at] = value; - } - } - - // Mip dimensions and the inner box of a subresource. - struct Inner { UINT ix, iy, iz, wi, hi, di; bool inset; }; - const auto inner = [&](UINT sub) { - const UINT mip = sub % tc.mips; - const UINT w = std::max(1u, tc.width >> mip), h = std::max(1u, tc.height >> mip); - const UINT d = volume ? std::max(1u, tc.depth_or_layers >> mip) : 1u; - Inner r{0, 0, 0, w, h, d, false}; - if (tc.ds) return r; - const UINT wb = (w + bw - 1) / bw, hb = (h + bw - 1) / bw; - if (wb >= 3) { r.ix = bw; r.wi = (wb - 2) * bw; r.inset = true; } - if (hb >= 3) { r.iy = bw; r.hi = (hb - 2) * bw; r.inset = true; } - if (r.inset && tc.bc) { // a block-compressed box is whole blocks on every axis - if (wb < 3) r.wi = wb * bw; - if (hb < 3) r.hi = hb * bw; - } - if (d >= 3) { r.iz = 1; r.di = d - 2; r.inset = true; } - return r; - }; - const auto swapped = [&](UINT sub) { // the same mip and plane in the next array slice - const UINT mip = sub % tc.mips, slice = (sub / tc.mips) % layers, plane = sub / (tc.mips * layers); - return mip + ((slice + 1) % layers) * tc.mips + plane * tc.mips * layers; - }; - - // Uploads, whole. - Ptr* targets[4] = {&A, &B, &C, &D}; - for (int k = 0; k < 4; ++k) - for (UINT i = 0; i < n; ++i) { - const auto dst = sub_loc(targets[k]->p, i); - const auto src = foot_loc(up.p, layout[k].placed[i]); - run.list->CopyTextureRegion(&dst, 0, 0, 0, &src, nullptr); - } - run.barrier(A.p, copy_dest, copy_source); - // The partial copies below write the textures the uploads just wrote: a round trip through COPY_SOURCE orders them. - for (auto* t : {&B, &C, &D}) { - run.barrier(t->p, copy_dest, copy_source); - run.barrier(t->p, copy_source, copy_dest); - } - run.list->CopyResource(R.p, A.p); - for (UINT i = 0; i < n; ++i) { - const Inner in = inner(i); - const D3D12_BOX inner_box{in.ix, in.iy, in.iz, in.ix + in.wi, in.iy + in.hi, in.iz + in.di}; - const D3D12_BOX origin_box{0, 0, 0, in.wi, in.hi, in.di}; - const D3D12_BOX* box = tc.ds || !in.inset ? nullptr : &inner_box; - const auto from = sub_loc(A.p, i); - { // B: the inner box to the origin - const auto dst = sub_loc(B.p, i); - run.list->CopyTextureRegion(&dst, 0, 0, 0, &from, box); - } - { // C: the origin box into another slice at the inset - const auto dst = sub_loc(C.p, swapped(i)); - run.list->CopyTextureRegion(&dst, in.ix, in.iy, in.iz, &from, tc.ds || !in.inset ? nullptr : &origin_box); - } - { // D: the inner box of the uploaded footprint to the inset - const auto dst = sub_loc(D.p, i); - const auto src = foot_loc(up.p, layout[0].placed[i]); - run.list->CopyTextureRegion(&dst, in.ix, in.iy, in.iz, &src, box); - } - { // P: the inner box of A into a footprint, at the inset - const auto dst = foot_loc(rb.p, layout[5].placed[i]); - run.list->CopyTextureRegion(&dst, in.ix, in.iy, in.iz, &from, box); - } - } - for (auto* t : {&B, &C, &D, &R}) run.barrier(t->p, copy_dest, copy_source); - Ptr* readers[5] = {&R, &B, &C, &D, &A}; - for (int k = 0; k < 5; ++k) - for (UINT i = 0; i < n; ++i) { - const auto dst = foot_loc(rb.p, layout[k].placed[i]); - const auto src = sub_loc(readers[k]->p, i); - run.list->CopyTextureRegion(&dst, 0, 0, 0, &src, nullptr); - } - out.error = run.submit(); - if (!out.error.empty()) return; - out.bytes.assign(rbm, rbm + size_t(stride) * sets); - static const char* names[sets] = {"R (CopyResource)", "B (box to origin)", "C (box to other slice)", - "D (footprint box to texture)", "A (source)", "P (texture box to footprint)"}; - for (int k = 0; k < sets; ++k) - for (UINT i = 0; i < n; ++i) { - const Placed& p = layout[k].placed[i]; - const UINT mip = i % tc.mips, slice = (i / tc.mips) % layers, plane = i / (tc.mips * layers); - char label[96]; - std::snprintf(label, sizeof(label), "%s sub %u (mip %u slice %u plane %u)", names[k], i, mip, slice, plane); - out.regions.push_back({label, size_t(p.Offset), p.Footprint.RowPitch, size_t(layout[k].row_bytes[i]), - layout[k].rows[i], p.Footprint.Depth, tc.format == DXGI_FORMAT_D24_UNORM_S8_UINT && plane == 0}); - } - up->Unmap(0, nullptr); - rb->Unmap(0, nullptr); -} - -// Buffer copies: odd offsets and sizes, CopyResource of a buffer, an upload straight into a readback buffer. -inline void run_buffers(Run& run, Outcome& out) { - constexpr UINT64 kb = 4096; - constexpr auto copy_dest = D3D12_RESOURCE_STATE_COPY_DEST, copy_source = D3D12_RESOURCE_STATE_COPY_SOURCE; - Ptr up, rb, A, B, C, D, E; - if (!run.buffer(D3D12_HEAP_TYPE_UPLOAD, kb * 3, D3D12_RESOURCE_STATE_GENERIC_READ, up) || - !run.buffer(D3D12_HEAP_TYPE_READBACK, kb * 4 + 256, copy_dest, rb) || - !run.buffer(D3D12_HEAP_TYPE_DEFAULT, kb, copy_dest, A) || !run.buffer(D3D12_HEAP_TYPE_DEFAULT, kb, copy_dest, B) || - !run.buffer(D3D12_HEAP_TYPE_DEFAULT, kb, copy_dest, C) || !run.buffer(D3D12_HEAP_TYPE_DEFAULT, 4093, copy_dest, D) || - !run.buffer(D3D12_HEAP_TYPE_DEFAULT, 4093, copy_dest, E)) { - out.error = "resource creation failed"; - return; - } - std::uint8_t *upm = nullptr, *rbm = nullptr; - if (FAILED(up->Map(0, nullptr, reinterpret_cast(&upm))) || FAILED(rb->Map(0, nullptr, reinterpret_cast(&rbm)))) { - out.error = "Map failed"; - return; - } - for (size_t i = 0; i < kb * 3; ++i) upm[i] = fill_byte(unsigned(i / kb) + 1, i % kb, false); - std::memset(rbm, 0xcd, size_t(kb) * 4 + 256); - auto& l = *run.list.p; - l.CopyBufferRegion(A.p, 0, up.p, 0, kb); - l.CopyBufferRegion(B.p, 0, up.p, kb, kb); - l.CopyBufferRegion(E.p, 0, up.p, 2 * kb, 4093); - run.barrier(A.p, copy_dest, copy_source); - run.barrier(B.p, copy_dest, copy_source); // orders B's upload before the partial copies into it - run.barrier(B.p, copy_source, copy_dest); - l.CopyBufferRegion(B.p, 1, A.p, 3, 1); - l.CopyBufferRegion(B.p, 7, A.p, 100, 5); - l.CopyBufferRegion(B.p, 64, A.p, 0, 256); - l.CopyBufferRegion(B.p, 1000, A.p, 513, 777); - l.CopyBufferRegion(B.p, 4095, A.p, 4095, 1); - l.CopyResource(C.p, A.p); - run.barrier(E.p, copy_dest, copy_source); - l.CopyResource(D.p, E.p); - l.CopyBufferRegion(rb.p, kb * 4 + 3, up.p, 11, 17); - for (auto* r : {&B, &C, &D}) run.barrier(r->p, copy_dest, copy_source); - l.CopyBufferRegion(rb.p, 0, B.p, 0, kb); - l.CopyBufferRegion(rb.p, kb, C.p, 0, kb); - l.CopyBufferRegion(rb.p, 2 * kb, D.p, 0, 4093); - l.CopyBufferRegion(rb.p, 3 * kb, A.p, 0, kb); - out.error = run.submit(); - if (!out.error.empty()) return; - out.bytes.assign(rbm, rbm + size_t(kb) * 4 + 256); - const std::pair parts[] = {{"B (partial copies)", kb}, {"C (CopyResource)", kb}, - {"D (CopyResource, 4093 bytes)", kb}, {"A (source)", kb}, - {"upload to readback, 17 bytes at 3", 256}}; - size_t at = 0; - for (const auto& [label, size] : parts) { - out.regions.push_back({label, at, size, size, 1, 1, false}); - at += size; - } - up->Unmap(0, nullptr); - rb->Unmap(0, nullptr); -} - -// Texture to texture between different mips of one 24x24 texture (mips 24, 12, 6, 3, 1): sizes that are not block -// multiples, boxes that run to a padded edge, and boxes that do not fit the destination (which must be refused). -struct MixCase { - const char* name; - UINT src_mip, dst_mip; - bool has_box; - D3D12_BOX box; - UINT dx, dy; -}; - -// Copies one subresource of A into one of D (both prefilled), reads D back. `out.error` is set when the list was -// rejected (`run.refused`). -inline void run_mixed(Run& run, ID3D12Device* host, DXGI_FORMAT format, const MixCase& mc, Outcome& out) { - D3D12_RESOURCE_DESC desc{}; - desc.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D; - desc.Width = desc.Height = 24; - desc.DepthOrArraySize = 1; - desc.MipLevels = 5; - desc.Format = format; - desc.SampleDesc.Count = 1; - constexpr UINT n = 5; - Layout layout[3]; - UINT64 total_one = 0; - host->GetCopyableFootprints(&desc, 0, n, 0, nullptr, nullptr, nullptr, &total_one); - const UINT64 stride = (total_one + 511) / 512 * 512; - for (int k = 0; k < 3; ++k) { - layout[k].placed.resize(n); - layout[k].rows.resize(n); - layout[k].row_bytes.resize(n); - host->GetCopyableFootprints(&desc, 0, n, k == 2 ? 0 : stride * k, layout[k].placed.data(), layout[k].rows.data(), - layout[k].row_bytes.data(), &layout[k].total); - } - constexpr auto copy_dest = D3D12_RESOURCE_STATE_COPY_DEST, copy_source = D3D12_RESOURCE_STATE_COPY_SOURCE; - Ptr up, rb, A, D; - if (!run.buffer(D3D12_HEAP_TYPE_UPLOAD, stride * 2, D3D12_RESOURCE_STATE_GENERIC_READ, up) || - !run.buffer(D3D12_HEAP_TYPE_READBACK, stride, copy_dest, rb) || !run.texture(desc, copy_dest, A) || - !run.texture(desc, copy_dest, D)) { - out.error = "resource creation failed"; - return; - } - std::uint8_t *upm = nullptr, *rbm = nullptr; - if (FAILED(up->Map(0, nullptr, reinterpret_cast(&upm))) || FAILED(rb->Map(0, nullptr, reinterpret_cast(&rbm)))) { - out.error = "Map failed"; - return; - } - std::memset(upm, 0, size_t(stride) * 2); - std::memset(rbm, 0xcd, size_t(stride)); - for (int k = 0; k < 2; ++k) - for (UINT i = 0; i < n; ++i) { - const Placed& p = layout[k].placed[i]; - for (UINT row = 0; row < layout[k].rows[i]; ++row) - for (UINT64 col = 0; col < layout[k].row_bytes[i]; ++col) - upm[size_t(p.Offset) + size_t(row) * p.Footprint.RowPitch + size_t(col)] = - fill_byte(unsigned(k + 11) * 104729u + i, size_t(row) * 131 + size_t(col), false); - const auto dst = sub_loc(k ? D.p : A.p, i); - const auto src = foot_loc(up.p, p); - run.list->CopyTextureRegion(&dst, 0, 0, 0, &src, nullptr); - } - run.barrier(A.p, copy_dest, copy_source); - run.barrier(D.p, copy_dest, copy_source); // orders the upload before the partial copy - run.barrier(D.p, copy_source, copy_dest); - { - const auto dst = sub_loc(D.p, mc.dst_mip), src = sub_loc(A.p, mc.src_mip); - run.list->CopyTextureRegion(&dst, mc.dx, mc.dy, 0, &src, mc.has_box ? &mc.box : nullptr); - } - run.barrier(D.p, copy_dest, copy_source); - for (UINT i = 0; i < n; ++i) { - const auto dst = foot_loc(rb.p, layout[2].placed[i]); - const auto src = sub_loc(D.p, i); - run.list->CopyTextureRegion(&dst, 0, 0, 0, &src, nullptr); - } - out.error = run.submit(); - if (!out.error.empty()) return; - out.bytes.assign(rbm, rbm + size_t(stride)); - for (UINT i = 0; i < n; ++i) { - const Placed& p = layout[2].placed[i]; - char label[64]; - std::snprintf(label, sizeof(label), "D sub %u (mip %u)", i, i); - out.regions.push_back({label, size_t(p.Offset), p.Footprint.RowPitch, size_t(layout[2].row_bytes[i]), - layout[2].rows[i], p.Footprint.Depth, false}); - } - up->Unmap(0, nullptr); - rb->Unmap(0, nullptr); -} - -// Compares two outcomes; returns 1 on a mismatch (and says what and where), else 0. -inline int compare(const char* name, const Outcome& ours, const Outcome& host) { - if (!host.error.empty()) { - std::fprintf(stderr, "copy case %s: the HOST run failed (%s); fix the case\n", name, host.error.c_str()); - return 1; - } - if (!ours.error.empty()) { - std::fprintf(stderr, "copy case %s: layer run failed: %s\n", name, ours.error.c_str()); - return 1; - } - int bad_regions = 0; - for (const Region& r : host.regions) { - size_t differing = 0, first = 0, padding = 0, first_row = 0, first_col = 0; - for (size_t z = 0; z < r.depth; ++z) - for (size_t row = 0; row < r.rows; ++row) { - const size_t base = r.offset + (z * r.rows + row) * r.pitch; - for (size_t col = 0; col < r.pitch; ++col) { - if (ours.bytes[base + col] == host.bytes[base + col]) continue; - if (r.x8 && col % 4 == 3 && col < r.row_bytes) continue; - if (col >= r.row_bytes) { ++padding; continue; } - if (!differing++) { first = base + col; first_row = z * r.rows + row; first_col = col; } - } - } - if (differing && bad_regions++ < 3) - std::fprintf(stderr, "copy case %s: %s: %zu bytes differ, first at row %zu col %zu: ours %02x host %02x\n", - name, r.label.c_str(), differing, first_row, first_col, ours.bytes[first], host.bytes[first]); - if (padding && !differing) - std::printf("copy case %s: %s: %zu row-padding bytes differ (not compared)\n", name, r.label.c_str(), padding); - } - if (bad_regions > 3) std::fprintf(stderr, "copy case %s: %d regions differ in all\n", name, bad_regions); - return bad_regions ? 1 : 0; -} - -// Runs every case; returns the number of cases that differ, or -1 with no host device. -inline int compare_copies(ID3D12Device* ours, bool bc_supported) { - Ptr host; - std::string adapter; - if (!create_host(host, adapter)) return -1; - std::printf("copy comparison: host side is %s\n", adapter.c_str()); - using D = D3D12_RESOURCE_DIMENSION; - constexpr D t2 = D3D12_RESOURCE_DIMENSION_TEXTURE2D, t3 = D3D12_RESOURCE_DIMENSION_TEXTURE3D; - std::vector cases; - const auto color = [&](const char* name, DXGI_FORMAT f, bool floaty = false) { - cases.push_back({name, t2, f, 36, 20, 3, 6, floaty, false, false}); - }; - color("R8_UNORM", DXGI_FORMAT_R8_UNORM); - color("R8G8_SNORM", DXGI_FORMAT_R8G8_SNORM); - color("R8G8B8A8_UNORM", DXGI_FORMAT_R8G8B8A8_UNORM); - color("R8G8B8A8_UNORM_SRGB", DXGI_FORMAT_R8G8B8A8_UNORM_SRGB); - color("R8G8B8A8_TYPELESS", DXGI_FORMAT_R8G8B8A8_TYPELESS); - color("B8G8R8A8_UNORM", DXGI_FORMAT_B8G8R8A8_UNORM); - color("R16_UNORM", DXGI_FORMAT_R16_UNORM); - color("R16G16_FLOAT", DXGI_FORMAT_R16G16_FLOAT, true); - color("R16G16B16A16_FLOAT", DXGI_FORMAT_R16G16B16A16_FLOAT, true); - color("R32_UINT", DXGI_FORMAT_R32_UINT); - color("R32G32_UINT", DXGI_FORMAT_R32G32_UINT); - color("R32G32B32A32_FLOAT", DXGI_FORMAT_R32G32B32A32_FLOAT, true); - color("R10G10B10A2_UNORM", DXGI_FORMAT_R10G10B10A2_UNORM); - color("R11G11B10_FLOAT", DXGI_FORMAT_R11G11B10_FLOAT, true); - color("R9G9B9E5_SHAREDEXP", DXGI_FORMAT_R9G9B9E5_SHAREDEXP); - color("B5G6R5_UNORM", DXGI_FORMAT_B5G6R5_UNORM); - color("B5G5R5A1_UNORM", DXGI_FORMAT_B5G5R5A1_UNORM); - cases.push_back({"3D R8G8B8A8_UNORM", t3, DXGI_FORMAT_R8G8B8A8_UNORM, 20, 12, 9, 4, false, false, false}); - cases.push_back({"3D R32_FLOAT", t3, DXGI_FORMAT_R32_FLOAT, 9, 5, 6, 4, true, false, false}); - cases.push_back({"single mip, single slice R8G8B8A8_UNORM", t2, DXGI_FORMAT_R8G8B8A8_UNORM, 16, 16, 1, 1, false, false, false}); - const auto depth = [&](const char* name, DXGI_FORMAT f, bool floaty) { - cases.push_back({name, t2, f, 20, 12, 2, 3, floaty, true, false}); - }; - depth("D16_UNORM", DXGI_FORMAT_D16_UNORM, false); - depth("D32_FLOAT", DXGI_FORMAT_D32_FLOAT, true); - depth("D24_UNORM_S8_UINT", DXGI_FORMAT_D24_UNORM_S8_UINT, false); - // Without a native D24 the layer stores D32_SFLOAT_S8_UINT and converts the depth plane of an upload and a readback - // (depth24.h); the random 24-bit values here must come back exactly, as on the host. - depth("D32_FLOAT_S8X24_UINT", DXGI_FORMAT_D32_FLOAT_S8X24_UINT, true); - if (bc_supported) { - const auto bc = [&](const char* name, DXGI_FORMAT f) { - cases.push_back({name, t2, f, 36, 20, 3, 6, false, false, true}); - }; - bc("BC1_UNORM", DXGI_FORMAT_BC1_UNORM); - bc("BC1_UNORM_SRGB", DXGI_FORMAT_BC1_UNORM_SRGB); - bc("BC2_UNORM", DXGI_FORMAT_BC2_UNORM); - bc("BC3_UNORM", DXGI_FORMAT_BC3_UNORM); - bc("BC4_UNORM", DXGI_FORMAT_BC4_UNORM); - bc("BC4_SNORM", DXGI_FORMAT_BC4_SNORM); - bc("BC5_UNORM", DXGI_FORMAT_BC5_UNORM); - bc("BC5_SNORM", DXGI_FORMAT_BC5_SNORM); - bc("BC6H_UF16", DXGI_FORMAT_BC6H_UF16); - bc("BC6H_SF16", DXGI_FORMAT_BC6H_SF16); - bc("BC7_UNORM", DXGI_FORMAT_BC7_UNORM); - bc("BC7_UNORM_SRGB", DXGI_FORMAT_BC7_UNORM_SRGB); - cases.push_back({"3D BC1_UNORM", t3, DXGI_FORMAT_BC1_UNORM, 16, 8, 6, 3, false, false, true}); - cases.push_back({"BC7_UNORM, 4x4 (one block)", t2, DXGI_FORMAT_BC7_UNORM, 4, 4, 2, 1, false, false, true}); - } else { - std::printf("copy comparison: no textureCompressionBC, BC cases skipped\n"); - } - - int bad = 0, total = 0; - const auto both = [&](const char* name, const std::function& scenario) { - ++total; - Outcome a, b; - Run ours_run, host_run; - if (!ours_run.init(ours, true) || !host_run.init(host.p, false)) { - std::fprintf(stderr, "copy case %s: could not create the queue and list\n", name); - ++bad; - return; - } - scenario(ours_run, a); - scenario(host_run, b); - const int r = compare(name, a, b); - bad += r; - if (!r) std::printf("copy case %s: matches the host (%zu regions)\n", name, b.regions.size()); - }; - for (const TexCase& tc : cases) both(tc.name, [&](Run& r, Outcome& o) { run_texture(r, host.p, tc, o); }); - both("buffers", [&](Run& r, Outcome& o) { run_buffers(r, o); }); - - // Different mips of one texture. Both sides must refuse what does not fit; what the host copies the layer must - // copy the same. A block-compressed copy whose mip edge falls inside a block on one side only is staged through - // transfer scratch by the layer (vulkan_replay.h, prepare_texture_copy). - constexpr D3D12_BOX no_box{}; - const MixCase mixes[] = { - {"mip 0 box 12x12 into mip 1", 0, 1, true, {0, 0, 0, 12, 12, 1}, 0, 0}, - {"mip 1 into mip 0 at 8,8", 1, 0, false, no_box, 8, 8}, - {"mip 1 box 4..12 into mip 0", 1, 0, true, {4, 4, 0, 12, 12, 1}, 0, 0}, - {"mip 0 box 8x8 into the 6x6 mip 2", 0, 2, true, {0, 0, 0, 8, 8, 1}, 0, 0}, - {"mip 2 (6x6) into mip 0 at 4,4", 2, 0, false, no_box, 4, 4}, - {"mip 2 (6x6) into mip 1", 2, 1, false, no_box, 0, 0}, - {"mip 0 box 4x4 into the 3x3 mip 3", 0, 3, true, {0, 0, 0, 4, 4, 1}, 0, 0}, - // The source's mip edge inside the block: the box 4..8 of the 6x6 mip 2 (2x2 texels) into the 3x3 mip 3. - {"mip 2 (6x6) box 4..8 into the 3x3 mip 3", 2, 3, true, {4, 4, 0, 8, 8, 1}, 0, 0}, - // Both mip edges inside one block, at an offset: the 3x3 mip 3 into the 6x6 mip 2 at 4,4 (2x2 texels land). - {"mip 3 (3x3) into mip 2 at 4,4", 3, 2, false, no_box, 4, 4}, - {"mip 0 box 16x16 into the 3x3 mip 3 (does not fit)", 0, 3, true, {0, 0, 0, 16, 16, 1}, 0, 0}, - {"mip 0 box 16x16 into the 6x6 mip 2 (does not fit)", 0, 2, true, {0, 0, 0, 16, 16, 1}, 0, 0}, - {"mip 1 into mip 0 at 16,16 (does not fit)", 1, 0, false, no_box, 16, 16}, - }; - Run ours_run, host_run; // one queue each for every mixed-mip case - const bool ours_ok = ours_run.init(ours, true), host_ok = host_run.init(host.p, false); - if (!ours_ok || !host_ok) { - std::fprintf(stderr, "copy cases with mixed mips: could not create the queue and list on %s\n", - ours_ok ? "the host" : "the layer"); - return bad + 1; - } - for (const DXGI_FORMAT format : {DXGI_FORMAT_R8G8B8A8_UNORM, DXGI_FORMAT_BC1_UNORM, DXGI_FORMAT_BC7_UNORM}) { - const bool bc = format != DXGI_FORMAT_R8G8B8A8_UNORM; - if (bc && !bc_supported) continue; - for (const MixCase& mc : mixes) { - ++total; - const std::string name = std::string(bc ? "BC " : "RGBA8 ") + mc.name; - Outcome a, b; - ours_run.begin(); - host_run.begin(); - run_mixed(ours_run, host.p, format, mc, a); - run_mixed(host_run, host.p, format, mc, b); - if (!host_run.refused && !b.error.empty()) { - std::fprintf(stderr, "copy case %s: the HOST run failed (%s); fix the case\n", name.c_str(), b.error.c_str()); - ++bad; - } else if (host_run.refused != ours_run.refused) { - std::fprintf(stderr, "copy case %s: the host %s the copy, the layer %s it (%s)\n", name.c_str(), - host_run.refused ? "refuses" : "does", ours_run.refused ? "refuses" : "does", - ours_run.refused ? a.error.c_str() : "accepted"); - ++bad; - } else if (!host_run.refused) { - const int r = compare(name.c_str(), a, b); - bad += r; - if (!r) std::printf("copy case %s: matches the host\n", name.c_str()); - } else { - std::printf("copy case %s: refused by both (host: %s; layer: %s)\n", name.c_str(), b.error.c_str(), - a.error.c_str()); - } - } - } - std::printf("copy comparison: %d of %d cases differ from the host\n", bad, total); - return bad; -} - -} // namespace copycmp diff --git a/runtime/test/d3d12_copy_xfmt_test.cpp b/runtime/test/d3d12_copy_xfmt_test.cpp deleted file mode 100644 index e4b22868c..000000000 --- a/runtime/test/d3d12_copy_xfmt_test.cpp +++ /dev/null @@ -1,311 +0,0 @@ -// Copies between two formats of one D3D12 copy family (depth <-> colour of the same size, BC <-> its uncompressed -// equivalent), on the Vulkan-backed device and on host D3D12 (the layer's own adapter and WARP). Bytes read back -// compared. -#include "vk_test_device.h" -#include "host_adapter.h" -#include "host_wine.h" -#include "../shims/d3d12_com.h" -#include -#include -#include -#include -#include - -namespace { -template -struct Ref { - T* p = nullptr; - ~Ref() { if (p) p->Release(); } - T* operator->() const { return p; } -}; - -D3D12_RESOURCE_DESC tex(DXGI_FORMAT f, UINT w, UINT h, D3D12_RESOURCE_FLAGS flags = D3D12_RESOURCE_FLAG_NONE) { - D3D12_RESOURCE_DESC d{}; - d.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D; - d.Width = w; - d.Height = h; - d.DepthOrArraySize = d.MipLevels = 1; - d.Format = f; - d.SampleDesc.Count = 1; - d.Flags = flags; - return d; -} - -D3D12_RESOURCE_DESC mips(D3D12_RESOURCE_DESC d, UINT16 levels) { - d.MipLevels = levels; - return d; -} - -D3D12_RESOURCE_DESC buf(UINT64 bytes) { - D3D12_RESOURCE_DESC d{}; - d.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER; - d.Width = bytes; - d.Height = d.DepthOrArraySize = d.MipLevels = 1; - d.SampleDesc.Count = 1; - d.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; - return d; -} - -struct Case { - const char* name; - D3D12_RESOURCE_DESC src, dst; - bool whole; // CopyResource, else CopyTextureRegion - bool depth_values; // also marks the depth <-> colour cases, counted apart from the BC ones (both fail the test) - UINT x = 0, y = 0; // CopyTextureRegion destination offset - bool has_box = false; - D3D12_BOX box{}; - UINT dst_mip = 0; - bool check_edge_bytes = false; -}; - -D3D12_RESOURCE_BARRIER transition(ID3D12Resource* r, D3D12_RESOURCE_STATES a, D3D12_RESOURCE_STATES b) { - D3D12_RESOURCE_BARRIER x{}; - x.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION; - x.Transition.pResource = r; - x.Transition.Subresource = D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES; - x.Transition.StateBefore = a; - x.Transition.StateAfter = b; - return x; -} - -unsigned char upload_byte(UINT64 index) { - return static_cast(index * 7 + 3); -} - -// Pack the destination footprint rows for the copied mip, or every mip for CopyResource. -bool run(ID3D12Device* dev, const Case& c, std::vector& out, HRESULT& close_hr) { - D3D12_COMMAND_QUEUE_DESC qd{}; - Ref q; - Ref a; - Ref l; - Ref fence; - if (FAILED(dev->CreateCommandQueue(&qd, IID_PPV_ARGS(&q.p))) || - FAILED(dev->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&a.p))) || - FAILED(dev->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, a.p, nullptr, IID_PPV_ARGS(&l.p))) || - FAILED(dev->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&fence.p)))) - return false; - // One array layer. Upload every source mip so both copy calls have initialized input. - const UINT ns = c.src.MipLevels, nd = c.dst.MipLevels; - D3D12_PLACED_SUBRESOURCE_FOOTPRINT sf[16]{}, df[16]{}; - UINT rows[16]{}; - UINT64 row_bytes[16]{}; - UINT64 sbytes = 0, dbytes = 0; - dev->GetCopyableFootprints(&c.src, 0, ns, 0, sf, nullptr, nullptr, &sbytes); - dev->GetCopyableFootprints(&c.dst, 0, nd, 0, df, rows, row_bytes, &dbytes); - D3D12_HEAP_PROPERTIES def{D3D12_HEAP_TYPE_DEFAULT}, up{D3D12_HEAP_TYPE_UPLOAD}, rb{D3D12_HEAP_TYPE_READBACK}; - Ref src, dst, upload, readback; - const D3D12_RESOURCE_DESC ub = buf(sbytes), rbd = buf(dbytes); - if (FAILED(dev->CreateCommittedResource(&def, D3D12_HEAP_FLAG_NONE, &c.src, D3D12_RESOURCE_STATE_COPY_DEST, nullptr, - IID_PPV_ARGS(&src.p))) || - FAILED(dev->CreateCommittedResource(&def, D3D12_HEAP_FLAG_NONE, &c.dst, D3D12_RESOURCE_STATE_COPY_DEST, nullptr, - IID_PPV_ARGS(&dst.p))) || - FAILED(dev->CreateCommittedResource(&up, D3D12_HEAP_FLAG_NONE, &ub, D3D12_RESOURCE_STATE_GENERIC_READ, nullptr, - IID_PPV_ARGS(&upload.p))) || - FAILED(dev->CreateCommittedResource(&rb, D3D12_HEAP_FLAG_NONE, &rbd, D3D12_RESOURCE_STATE_COPY_DEST, nullptr, - IID_PPV_ARGS(&readback.p)))) - return false; - unsigned char* p = nullptr; - if (FAILED(upload->Map(0, nullptr, reinterpret_cast(&p)))) return false; - for (UINT64 i = 0; i < sbytes; ++i) p[i] = upload_byte(i); - if (c.depth_values) // normal floats in [0, 1): a host driver may flush denormals - for (UINT64 i = 0; i + 4 <= sbytes; i += 4) { - const float v = float((i / 4) % 1000) / 1000.0f; - std::memcpy(p + i, &v, 4); - } - if (c.check_edge_bytes) { - // The edge fixtures copy whole R32G32_UINT source rows, one eight-byte texel per BC1 block. - // Count the data bytes, excluding padding, so each row contains a different pattern. - const UINT64 bytes_per_row = c.src.Width * 8; - for (UINT y = 0; y < c.src.Height; ++y) { - auto* row = p + sf[0].Offset + UINT64(y) * sf[0].Footprint.RowPitch; - for (UINT64 x = 0; x < bytes_per_row; ++x) row[x] = upload_byte(y * bytes_per_row + x); - } - } - upload->Unmap(0, nullptr); - if (FAILED(readback->Map(0, nullptr, reinterpret_cast(&p)))) return false; - std::memset(p, 0xcd, size_t(dbytes)); - readback->Unmap(0, nullptr); - - for (UINT i = 0; i < ns; ++i) { - D3D12_TEXTURE_COPY_LOCATION from{upload.p, D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT}, to{src.p}; - from.PlacedFootprint = sf[i]; - to.SubresourceIndex = i; - l->CopyTextureRegion(&to, 0, 0, 0, &from, nullptr); - } - D3D12_RESOURCE_BARRIER b = transition(src.p, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_COPY_SOURCE); - l->ResourceBarrier(1, &b); - if (c.whole) { - l->CopyResource(dst.p, src.p); - } else { - D3D12_TEXTURE_COPY_LOCATION s{src.p}, d{dst.p}; - d.SubresourceIndex = c.dst_mip; - l->CopyTextureRegion(&d, c.x, c.y, 0, &s, c.has_box ? &c.box : nullptr); - } - b = transition(dst.p, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_COPY_SOURCE); - l->ResourceBarrier(1, &b); - const UINT first_mip = c.whole ? 0 : c.dst_mip, end_mip = c.whole ? nd : c.dst_mip + 1; - for (UINT i = first_mip; i < end_mip; ++i) { - D3D12_TEXTURE_COPY_LOCATION rs{dst.p}, rd{readback.p, D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT}; - rs.SubresourceIndex = i; - rd.PlacedFootprint = df[i]; - l->CopyTextureRegion(&rd, 0, 0, 0, &rs, nullptr); - } - close_hr = l->Close(); - if (FAILED(close_hr)) return false; - ID3D12CommandList* lists[] = {l.p}; - q->ExecuteCommandLists(1, lists); - q->Signal(fence.p, 1); - HANDLE e = CreateEventW(nullptr, FALSE, FALSE, nullptr); - fence->SetEventOnCompletion(1, e); - WaitForSingleObject(e, 10000); - CloseHandle(e); - if (FAILED(readback->Map(0, nullptr, reinterpret_cast(&p)))) return false; - // Compare the bytes inside the rows and leave footprint padding out. - out.clear(); - for (UINT i = first_mip; i < end_mip; ++i) - for (UINT r = 0; r < rows[i]; ++r) { - const unsigned char* row = p + df[i].Offset + r * df[i].Footprint.RowPitch; - out.insert(out.end(), row, row + row_bytes[i]); - } - readback->Unmap(0, nullptr); - return true; -} - -void drain(ID3D12Device* host) { - Ref iq; - if (FAILED(host->QueryInterface(IID_PPV_ARGS(&iq.p)))) return; - for (UINT64 i = 0; i < iq->GetNumStoredMessages(); ++i) { - SIZE_T n = 0; - iq->GetMessage(i, nullptr, &n); - std::vector m(n); - auto* msg = reinterpret_cast(m.data()); - iq->GetMessage(i, msg, &n); - if (msg->Severity <= D3D12_MESSAGE_SEVERITY_WARNING) std::fprintf(stderr, " host debug: %s\n", msg->pDescription); - } - iq->ClearStoredMessages(); -} -} // namespace - -int main() { - vktest::Device vk; - if (!vk.create()) return 77; - Ref debug; - const bool debug_on = SUCCEEDED(D3D12GetDebugInterface(IID_PPV_ARGS(&debug.p))); - if (debug_on) debug->EnableDebugLayer(); - std::printf("host debug layer: %s\n", debug_on ? "enabled" : "NOT available"); - Ref ours; - rt::d3d12::VulkanDeviceInfo info{}; - info.get_instance_proc = vk.instance_proc; - info.instance = vk.instance; - info.physical = vk.physical; - info.device = vk.device; - info.queue = vk.queue; - info.queue_family = vk.family; - if (FAILED(rt::d3d12::create_vulkan_device(info, IID_PPV_ARGS(&ours.p)))) return 1; - - constexpr auto ds = D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL; - const Case cases[] = { - {"CopyResource D32_FLOAT -> R32_FLOAT", tex(DXGI_FORMAT_D32_FLOAT, 16, 16, ds), tex(DXGI_FORMAT_R32_FLOAT, 16, 16), true, true}, - {"CopyTextureRegion D32_FLOAT -> R32_FLOAT", tex(DXGI_FORMAT_D32_FLOAT, 16, 16, ds), tex(DXGI_FORMAT_R32_FLOAT, 16, 16), false, true}, - {"CopyResource R32_FLOAT -> D32_FLOAT", tex(DXGI_FORMAT_R32_FLOAT, 16, 16), tex(DXGI_FORMAT_D32_FLOAT, 16, 16, ds), true, true}, - {"CopyResource D16_UNORM -> R16_UNORM", tex(DXGI_FORMAT_D16_UNORM, 16, 16, ds), tex(DXGI_FORMAT_R16_UNORM, 16, 16), true, true}, - {"CopyResource R16_UNORM -> D16_UNORM", tex(DXGI_FORMAT_R16_UNORM, 16, 16), tex(DXGI_FORMAT_D16_UNORM, 16, 16, ds), true, true}, - {"CopyTextureRegion D32_FLOAT -> R32_UINT", tex(DXGI_FORMAT_D32_FLOAT, 16, 16, ds), tex(DXGI_FORMAT_R32_UINT, 16, 16), false, true}, - // A depth-stencil side is copied whole (no box, offset 0), as D3D12 requires of CopyTextureRegion. - {"CopyTextureRegion R16_UNORM -> D16_UNORM", tex(DXGI_FORMAT_R16_UNORM, 16, 16), tex(DXGI_FORMAT_D16_UNORM, 16, 16, ds), false, true}, - {"CopyResource D16_UNORM -> R16_UINT", tex(DXGI_FORMAT_D16_UNORM, 16, 16, ds), tex(DXGI_FORMAT_R16_UINT, 16, 16), true, true}, - {"CopyTextureRegion R16_SNORM -> D16_UNORM", tex(DXGI_FORMAT_R16_SNORM, 16, 16), tex(DXGI_FORMAT_D16_UNORM, 16, 16, ds), false, true}, - {"CopyResource D32_FLOAT -> R32_FLOAT, 3 mips", mips(tex(DXGI_FORMAT_D32_FLOAT, 16, 16, ds), 3), mips(tex(DXGI_FORMAT_R32_FLOAT, 16, 16), 3), true, true}, - {"negative control: CopyResource D32_FLOAT -> R16_UNORM", tex(DXGI_FORMAT_D32_FLOAT, 16, 16, ds), tex(DXGI_FORMAT_R16_UNORM, 16, 16), true, true}, - {"CopyTextureRegion R32G32_UINT 4x4 -> BC1 16x16", tex(DXGI_FORMAT_R32G32_UINT, 4, 4), tex(DXGI_FORMAT_BC1_UNORM, 16, 16), false, false}, - {"CopyTextureRegion BC1 16x16 -> R32G32_UINT 4x4", tex(DXGI_FORMAT_BC1_UNORM, 16, 16), tex(DXGI_FORMAT_R32G32_UINT, 4, 4), false, false}, - {"negative control: CopyResource R32_FLOAT -> R16_FLOAT", tex(DXGI_FORMAT_R32_FLOAT, 16, 16), tex(DXGI_FORMAT_R16_FLOAT, 16, 16), true, false}, - {"negative control: CopyResource R32_FLOAT 16x16 -> R32_FLOAT 8x8", tex(DXGI_FORMAT_R32_FLOAT, 16, 16), tex(DXGI_FORMAT_R32_FLOAT, 8, 8), true, false}, - {"CopyTextureRegion BC7 16x16 -> R32G32B32A32_UINT 4x4", tex(DXGI_FORMAT_BC7_UNORM, 16, 16), tex(DXGI_FORMAT_R32G32B32A32_UINT, 4, 4), false, false}, - {"CopyTextureRegion BC1 box 4..12 x 8..16 -> R16G16B16A16_UINT 8x8 at (3, 1)", tex(DXGI_FORMAT_BC1_UNORM, 16, 16), tex(DXGI_FORMAT_R16G16B16A16_UINT, 8, 8), false, false, 3, 1, true, {4, 8, 0, 12, 16, 1}}, - {"CopyTextureRegion BC1 10x6 (padded box) -> R32G32_UINT 3x2", tex(DXGI_FORMAT_BC1_UNORM, 10, 6), tex(DXGI_FORMAT_R32G32_UINT, 3, 2), false, false}, - {.name = "CopyTextureRegion R32G32_UINT 3x2 -> BC1 10x6", - .src = tex(DXGI_FORMAT_R32G32_UINT, 3, 2), .dst = tex(DXGI_FORMAT_BC1_UNORM, 10, 6), - .whole = false, .depth_values = false, .check_edge_bytes = true}, - {.name = "CopyTextureRegion R32G32_UINT 2x1 -> BC1 12x8 mip 1 (6x4)", - .src = tex(DXGI_FORMAT_R32G32_UINT, 2, 1), .dst = mips(tex(DXGI_FORMAT_BC1_UNORM, 12, 8), 2), - .whole = false, .depth_values = false, .dst_mip = 1, .check_edge_bytes = true}, - {"CopyTextureRegion R32G32_UINT 2x2 -> BC1 16x16 at (8, 4)", tex(DXGI_FORMAT_R32G32_UINT, 2, 2), tex(DXGI_FORMAT_BC1_UNORM, 16, 16), false, false, 8, 4}, - {"negative control: CopyTextureRegion R32_UINT 4x4 -> BC1 16x16", tex(DXGI_FORMAT_R32_UINT, 4, 4), tex(DXGI_FORMAT_BC1_UNORM, 16, 16), false, false}, - {"negative control: CopyTextureRegion R32G32_UINT 4x4 -> BC1 16x16 at (12, 0)", tex(DXGI_FORMAT_R32G32_UINT, 4, 4), tex(DXGI_FORMAT_BC1_UNORM, 16, 16), false, false, 12, 0}, - {"CopyResource BC7 16x16 -> R32G32B32A32_UINT 4x4", tex(DXGI_FORMAT_BC7_UNORM, 16, 16), tex(DXGI_FORMAT_R32G32B32A32_UINT, 4, 4), true, false}, - {"CopyResource BC1 12x8 -> R32G32_UINT 3x2", tex(DXGI_FORMAT_BC1_UNORM, 12, 8), tex(DXGI_FORMAT_R32G32_UINT, 3, 2), true, false}, - {"CopyResource R32G32B32A32_UINT 4x4 -> BC7 16x16, 3 mips", mips(tex(DXGI_FORMAT_R32G32B32A32_UINT, 4, 4), 3), mips(tex(DXGI_FORMAT_BC7_UNORM, 16, 16), 3), true, false}, - {"CopyResource BC7 16x16 -> R32G32B32A32_UINT 4x4, 3 mips", mips(tex(DXGI_FORMAT_BC7_UNORM, 16, 16), 3), mips(tex(DXGI_FORMAT_R32G32B32A32_UINT, 4, 4), 3), true, false}, - {"negative control: CopyResource BC1 12x8 -> R32G32_UINT 3x2, 2 mips", mips(tex(DXGI_FORMAT_BC1_UNORM, 12, 8), 2), mips(tex(DXGI_FORMAT_R32G32_UINT, 3, 2), 2), true, false}, - {"CopyResource R32G32_UINT 3x2 -> BC1 12x8, 2 mips", mips(tex(DXGI_FORMAT_R32G32_UINT, 3, 2), 2), mips(tex(DXGI_FORMAT_BC1_UNORM, 12, 8), 2), true, false}, - {"CopyResource R32G32B32A32_UINT 4x4 -> BC7 16x16", tex(DXGI_FORMAT_R32G32B32A32_UINT, 4, 4), tex(DXGI_FORMAT_BC7_UNORM, 16, 16), true, false}, - }; - - if (hostwine::host_is_wine()) return 77; // vkd3d runs copies WARP refuses, so the controls can't hold - Ref factory; - if (FAILED(CreateDXGIFactory1(IID_PPV_ARGS(&factory.p)))) return 1; - unsigned differ = 0, differ_depth = 0, compared = 0; - for (const bool warp : {false, true}) { - for (const Case& c : cases) { - // Check the full output of the partial-edge fixtures against the upload bytes on every available - // Vulkan device. Compare the same cases against native D3D12 using WARP when available. - if (!warp && (c.check_edge_bytes || std::strncmp(c.name, "negative", 8) == 0)) continue; - std::vector h, o; - HRESULT hh = S_OK, oh = S_OK; - if (c.check_edge_bytes) { - std::vector expected(size_t(c.src.Width) * c.src.Height * 8); - for (size_t i = 0; i < expected.size(); ++i) expected[i] = upload_byte(i); - const bool ours_ok = run(ours.p, c, o, oh); - if (!ours_ok || o != expected) { - std::fprintf(stderr, "%s: expected %zu upload bytes (read %zu bytes, Close 0x%08lx)\n", - c.name, expected.size(), o.size(), (unsigned long)oh); - ++differ; - continue; - } - std::printf("%s: matches %zu upload bytes\n", c.name, expected.size()); - } - // A fresh device per case: an invalid copy removes the host device. - Ref adapter; - Ref host; - std::string adapter_name; - if (!hostadapter::reference(factory.p, vk, warp, &adapter.p, adapter_name)) continue; - const char* hn = adapter_name.c_str(); - if (FAILED(D3D12CreateDevice(adapter.p, D3D_FEATURE_LEVEL_11_0, IID_PPV_ARGS(&host.p)))) continue; - const bool host_ok = run(host.p, c, h, hh); - drain(host.p); - if (!host_ok) { - std::printf("%s: %s refuses it (Close 0x%08lx, removed reason 0x%08lx), skipped\n", c.name, hn, - (unsigned long)hh, (unsigned long)host->GetDeviceRemovedReason()); - if (c.check_edge_bytes) continue; // the layer's output was already checked against the upload - // The layer must refuse it too (at Close or execution), never write out of bounds (validation). - const unsigned before = vk.validation_errors(); - run(ours.p, c, o, oh); - std::printf(" ours: Close 0x%08lx, %u new Vulkan validation errors\n", (unsigned long)oh, - vk.validation_errors() - before); - continue; - } - const bool ours_ok = c.check_edge_bytes || run(ours.p, c, o, oh); - ++compared; - if (ours_ok && o == h) { - std::printf("%s: matches %s\n", c.name, hn); - continue; - } - ++(c.depth_values ? differ_depth : differ); - size_t first = 0; - while (first < o.size() && first < h.size() && o[first] == h[first]) ++first; - bool untouched = !o.empty(); - for (unsigned char x : o) untouched = untouched && x == 0xcd; - std::printf("%s: DIFFERS from %s (ours %s%s, Close 0x%08lx; first differing byte %zu: ours 0x%02x host 0x%02x)\n", - c.name, hn, ours_ok ? "submitted" : "refused", untouched ? ", readback untouched: the copy was refused at execution" : "", (unsigned long)oh, first, - first < o.size() ? o[first] : 0, first < h.size() ? h[first] : 0); - } - } - std::printf("%u compared, %u differ (BC <-> uncompressed, controls), %u depth <-> colour differ\n", compared, - differ, differ_depth); - if (vk.validation_errors()) { - std::printf("%u Vulkan validation errors\n", vk.validation_errors()); - return 1; - } - return differ || differ_depth ? 1 : 0; -} diff --git a/runtime/test/d3d12_cross_device_validation_test.cpp b/runtime/test/d3d12_cross_device_validation_test.cpp deleted file mode 100644 index 2e32ec0f1..000000000 --- a/runtime/test/d3d12_cross_device_validation_test.cpp +++ /dev/null @@ -1,333 +0,0 @@ -// Cross-device ownership validation across D3D12 COM objects on two distinct Vulkan-backed devices: -// CommandQueue::Signal, CommandQueue::Wait, ID3D12Device1::SetEventOnMultipleFenceCompletion (event and blocking, -// ALL and ANY, pure-foreign and mixed arrays), CommandQueue::ExecuteCommandLists (single foreign list and mixed -// batch), and GraphicsCommandList::ExecuteBundle. Also verifies the blocking path of -// set_event_on_multiple_fence_completion returns DXGI_ERROR_DEVICE_REMOVED when the device is already lost, and -// checks exact E_INVALIDARG parity against the live Windows D3D12 runtime (hardware adapter + WARP, skipped under -// Wine) for Signal, Wait, and SetEventOnMultipleFenceCompletion. -// No game files; exits 77 without a Vulkan device. -#include "host_wine.h" -#include "vk_test_device.h" -#include "../shims/d3d12_com.h" - -#include - -#include -#include -#include - -namespace { - -template -struct Ref { - T* p = nullptr; - ~Ref() { - if (p) p->Release(); - } - T* operator->() const { return p; } -}; - -struct Event { - HANDLE h = CreateEventW(nullptr, FALSE, FALSE, nullptr); - ~Event() { - if (h) CloseHandle(h); - } - bool set_within(DWORD ms) const { return WaitForSingleObject(h, ms) == WAIT_OBJECT_0; } -}; - -int failures = 0; - -void check(bool ok, const char* what) { - std::printf("%s %s\n", ok ? "PASS" : "FAIL", what); - if (!ok) ++failures; -} - -HRESULT make_buffer(ID3D12Device* device, D3D12_HEAP_TYPE heap, D3D12_RESOURCE_STATES state, ID3D12Resource** out) { - D3D12_HEAP_PROPERTIES props{}; - props.Type = heap; - D3D12_RESOURCE_DESC desc{}; - desc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER; - desc.Width = 256; - desc.Height = desc.DepthOrArraySize = desc.MipLevels = 1; - desc.SampleDesc.Count = 1; - desc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; - return device->CreateCommittedResource(&props, D3D12_HEAP_FLAG_NONE, &desc, state, nullptr, IID_PPV_ARGS(out)); -} - -bool wait_idle(ID3D12Device* device, ID3D12CommandQueue* queue) { - Ref fence; - if (FAILED(device->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&fence.p)))) return false; - return SUCCEEDED(queue->Signal(fence.p, 1)) && SUCCEEDED(fence->SetEventOnCompletion(1, nullptr)); -} - -void check_host_parity() { - if (hostwine::host_is_wine()) { - std::printf("SKIP host parity under Wine\n"); - return; - } - Ref factory; - if (FAILED(CreateDXGIFactory2(0, IID_PPV_ARGS(&factory.p)))) { - std::printf("SKIP host parity: CreateDXGIFactory2 failed\n"); - return; - } - Ref hw; - for (UINT i = 0;; ++i) { - Ref cand; - if (factory->EnumAdapters1(i, &cand.p) == DXGI_ERROR_NOT_FOUND) break; - DXGI_ADAPTER_DESC1 desc{}; - if (SUCCEEDED(cand->GetDesc1(&desc)) && !(desc.Flags & DXGI_ADAPTER_FLAG_SOFTWARE)) { - hw.p = cand.p; - cand.p = nullptr; - break; - } - } - Ref warp; - if (!hw.p || FAILED(factory->EnumWarpAdapter(IID_PPV_ARGS(&warp.p)))) { - std::printf("SKIP host parity: need both hardware and WARP adapters\n"); - return; - } - - Ref dev_a, dev_b; - if (FAILED(D3D12CreateDevice(hw.p, D3D_FEATURE_LEVEL_11_0, IID_PPV_ARGS(&dev_a.p))) || - FAILED(D3D12CreateDevice(warp.p, D3D_FEATURE_LEVEL_11_0, IID_PPV_ARGS(&dev_b.p))) || dev_a.p == dev_b.p) { - std::printf("SKIP host parity: could not create two distinct host D3D12 devices\n"); - return; - } - - D3D12_COMMAND_QUEUE_DESC qdesc{}; - qdesc.Type = D3D12_COMMAND_LIST_TYPE_DIRECT; - Ref q_a; - Ref f_a, f_b; - if (FAILED(dev_a->CreateCommandQueue(&qdesc, IID_PPV_ARGS(&q_a.p))) || - FAILED(dev_a->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&f_a.p))) || - FAILED(dev_b->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&f_b.p)))) { - std::printf("SKIP host parity: could not create host queue/fences\n"); - return; - } - - check(q_a->Signal(f_b.p, 1) == E_INVALIDARG, "host: queue_A->Signal(fence_B) == E_INVALIDARG"); - check(f_b->GetCompletedValue() == 0, "host: fence_B unchanged after rejected Signal"); - check(q_a->Wait(f_b.p, 1) == E_INVALIDARG, "host: queue_A->Wait(fence_B) == E_INVALIDARG"); - - Event ev; - ID3D12Fence* foreign_only[] = {f_b.p}; - ID3D12Fence* mixed[] = {f_a.p, f_b.p}; - const UINT64 v1[] = {1}; - const UINT64 v2[] = {1, 1}; - constexpr auto ALL = D3D12_MULTIPLE_FENCE_WAIT_FLAG_ALL; - constexpr auto ANY = D3D12_MULTIPLE_FENCE_WAIT_FLAG_ANY; - check(dev_a->SetEventOnMultipleFenceCompletion(foreign_only, v1, 1, ALL, ev.h) == E_INVALIDARG, - "host: dev_A->SetEventOnMultipleFenceCompletion({f_B}, ALL, ev) == E_INVALIDARG"); - check(dev_a->SetEventOnMultipleFenceCompletion(foreign_only, v1, 1, ALL, nullptr) == E_INVALIDARG, - "host: dev_A->SetEventOnMultipleFenceCompletion({f_B}, ALL, null) == E_INVALIDARG"); - check(dev_a->SetEventOnMultipleFenceCompletion(mixed, v2, 2, ALL, ev.h) == E_INVALIDARG, - "host: dev_A->SetEventOnMultipleFenceCompletion({f_A,f_B}, ALL, ev) == E_INVALIDARG"); - check(dev_a->SetEventOnMultipleFenceCompletion(mixed, v2, 2, ANY, ev.h) == E_INVALIDARG, - "host: dev_A->SetEventOnMultipleFenceCompletion({f_A,f_B}, ANY, ev) == E_INVALIDARG"); - check(dev_a->SetEventOnMultipleFenceCompletion(mixed, v2, 2, ALL, nullptr) == E_INVALIDARG, - "host: dev_A->SetEventOnMultipleFenceCompletion({f_A,f_B}, ALL, null) == E_INVALIDARG"); - // Note: cross-device ExecuteCommandLists and ExecuteBundle fault on retail host D3D12 without the debug layer, - // so only the HRESULT-returning fence paths are run on the host; the layer safely refuses all five. -} - -void check_device_lost_blocking_multi_fence() { - vktest::Device d; - if (d.initialize() != vktest::DeviceStatus::ready) return; - leonida::VulkanContext ctx(d.device_proc, d.device, true); - if (!ctx.loaded()) { - check(false, "device-lost check: VulkanContext loaded"); - return; - } - Ref fence; - if (FAILED(rt::d3d12::create_fence(ctx, 0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&fence.p)))) { - check(false, "device-lost check: create_fence"); - return; - } - ctx.mark_device_lost(); - ID3D12Fence* fences[] = {fence.p}; - const UINT64 values[] = {42}; - const HRESULT hr = rt::d3d12::set_event_on_multiple_fence_completion( - ctx, fences, values, 1, D3D12_MULTIPLE_FENCE_WAIT_FLAG_ALL, nullptr); - check(hr == DXGI_ERROR_DEVICE_REMOVED, - "layer: blocking SetEventOnMultipleFenceCompletion on lost device returns DXGI_ERROR_DEVICE_REMOVED"); -} - -} // namespace - -int main() { - Ref dev_a, dev_b; - if (FAILED(rt::d3d12::create_vulkan_device_standalone(IID_PPV_ARGS(&dev_a.p)))) return 77; - if (FAILED(rt::d3d12::create_vulkan_device_standalone(IID_PPV_ARGS(&dev_b.p)))) return 77; - - Ref dev_a1, dev_b1; - check(SUCCEEDED(dev_a->QueryInterface(IID_PPV_ARGS(&dev_a1.p))), "dev_A supports ID3D12Device1"); - check(SUCCEEDED(dev_b->QueryInterface(IID_PPV_ARGS(&dev_b1.p))), "dev_B supports ID3D12Device1"); - - D3D12_COMMAND_QUEUE_DESC qdesc{}; - qdesc.Type = D3D12_COMMAND_LIST_TYPE_DIRECT; - Ref q_a, q_b; - if (FAILED(dev_a->CreateCommandQueue(&qdesc, IID_PPV_ARGS(&q_a.p))) || - FAILED(dev_b->CreateCommandQueue(&qdesc, IID_PPV_ARGS(&q_b.p)))) - return 1; - - Ref f_a, f_a2, f_b; - if (FAILED(dev_a->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&f_a.p))) || - FAILED(dev_a->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&f_a2.p))) || - FAILED(dev_b->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&f_b.p)))) - return 1; - - // 1. CommandQueue::Signal cross-device rejection + same-device positive control. - check(q_a->Signal(f_b.p, 1) == E_INVALIDARG, "layer: queue_A->Signal(fence_B) == E_INVALIDARG"); - check(f_b->GetCompletedValue() == 0, "layer: fence_B unchanged after rejected queue_A->Signal"); - check(q_b->Signal(f_a.p, 1) == E_INVALIDARG, "layer: queue_B->Signal(fence_A) == E_INVALIDARG"); - check(f_a->GetCompletedValue() == 0, "layer: fence_A unchanged after rejected queue_B->Signal"); - check(SUCCEEDED(q_a->Signal(f_a.p, 1)) && SUCCEEDED(f_a->SetEventOnCompletion(1, nullptr)) && - f_a->GetCompletedValue() == 1, - "layer: same-device queue_A->Signal(fence_A, 1) completes"); - check(SUCCEEDED(q_b->Signal(f_b.p, 1)) && SUCCEEDED(f_b->SetEventOnCompletion(1, nullptr)) && - f_b->GetCompletedValue() == 1, - "layer: same-device queue_B->Signal(fence_B, 1) completes"); - - // 2. CommandQueue::Wait cross-device rejection + same-device positive control. - check(q_a->Wait(f_b.p, 99) == E_INVALIDARG, "layer: queue_A->Wait(fence_B) == E_INVALIDARG"); - // A rejected foreign wait must not block subsequent work on queue_A. - check(SUCCEEDED(q_a->Signal(f_a.p, 2)) && SUCCEEDED(f_a->SetEventOnCompletion(2, nullptr)) && - f_a->GetCompletedValue() == 2, - "layer: queue_A stays unblocked after rejected foreign Wait"); - check(SUCCEEDED(q_a->Wait(f_a2.p, 1)) && SUCCEEDED(q_a->Signal(f_a.p, 3)) && SUCCEEDED(f_a2->Signal(1)) && - SUCCEEDED(f_a->SetEventOnCompletion(3, nullptr)) && f_a->GetCompletedValue() == 3, - "layer: same-device queue_A->Wait(fence_A2) unblocks on CPU signal"); - - // 3. SetEventOnMultipleFenceCompletion cross-device rejection + same-device positive control. - { - Event ev; - ID3D12Fence* foreign_only[] = {f_b.p}; - ID3D12Fence* mixed[] = {f_a.p, f_b.p}; - const UINT64 v1[] = {10}; - const UINT64 v2[] = {3, 10}; - constexpr auto ALL = D3D12_MULTIPLE_FENCE_WAIT_FLAG_ALL; - constexpr auto ANY = D3D12_MULTIPLE_FENCE_WAIT_FLAG_ANY; - - check(dev_a1->SetEventOnMultipleFenceCompletion(foreign_only, v1, 1, ALL, ev.h) == E_INVALIDARG, - "layer: dev_A->SetEventOnMultipleFenceCompletion({f_B}, ALL, ev) == E_INVALIDARG"); - check(dev_a1->SetEventOnMultipleFenceCompletion(foreign_only, v1, 1, ANY, ev.h) == E_INVALIDARG, - "layer: dev_A->SetEventOnMultipleFenceCompletion({f_B}, ANY, ev) == E_INVALIDARG"); - check(dev_a1->SetEventOnMultipleFenceCompletion(foreign_only, v1, 1, ALL, nullptr) == E_INVALIDARG, - "layer: dev_A->SetEventOnMultipleFenceCompletion({f_B}, ALL, null) == E_INVALIDARG"); - check(dev_a1->SetEventOnMultipleFenceCompletion(mixed, v2, 2, ALL, ev.h) == E_INVALIDARG, - "layer: dev_A->SetEventOnMultipleFenceCompletion({f_A,f_B}, ALL, ev) == E_INVALIDARG"); - check(dev_a1->SetEventOnMultipleFenceCompletion(mixed, v2, 2, ANY, ev.h) == E_INVALIDARG, - "layer: dev_A->SetEventOnMultipleFenceCompletion({f_A,f_B}, ANY, ev) == E_INVALIDARG"); - check(dev_a1->SetEventOnMultipleFenceCompletion(mixed, v2, 2, ALL, nullptr) == E_INVALIDARG, - "layer: dev_A->SetEventOnMultipleFenceCompletion({f_A,f_B}, ALL, null) == E_INVALIDARG"); - check(!ev.set_within(20), "layer: event not signaled by rejected multi-fence waits"); - - ID3D12Fence* same[] = {f_a.p, f_a2.p}; - const UINT64 vsame[] = {3, 2}; - check(SUCCEEDED(dev_a1->SetEventOnMultipleFenceCompletion(same, vsame, 2, ALL, ev.h)), - "layer: same-device SetEventOnMultipleFenceCompletion({f_A,f_A2}, ALL, ev) succeeds"); - check(!ev.set_within(20), "layer: same-device multi-fence wait holds until f_A2 reaches 2"); - check(SUCCEEDED(f_a2->Signal(2)) && ev.set_within(5000), - "layer: same-device multi-fence wait signals when f_A2 reaches 2"); - check(SUCCEEDED(dev_a1->SetEventOnMultipleFenceCompletion(same, vsame, 2, ALL, nullptr)), - "layer: same-device blocking SetEventOnMultipleFenceCompletion returns S_OK"); - } - - // 4. CommandQueue::ExecuteCommandLists cross-device rejection (single + mixed batch) + positive control. - { - Ref upload_a, readback_a; - if (FAILED(make_buffer(dev_a.p, D3D12_HEAP_TYPE_UPLOAD, D3D12_RESOURCE_STATE_GENERIC_READ, &upload_a.p)) || - FAILED(make_buffer(dev_a.p, D3D12_HEAP_TYPE_READBACK, D3D12_RESOURCE_STATE_COPY_DEST, &readback_a.p))) - return 1; - const std::uint32_t marker = 0x4c454f4e; - void* mapped = nullptr; - if (FAILED(upload_a->Map(0, nullptr, &mapped))) return 1; - std::memcpy(mapped, &marker, sizeof marker); - upload_a->Unmap(0, nullptr); - if (FAILED(readback_a->Map(0, nullptr, &mapped))) return 1; - std::memset(mapped, 0, sizeof marker); - readback_a->Unmap(0, nullptr); - - auto read_word = [&] { - std::uint32_t word = 0; - const D3D12_RANGE range{0, sizeof word}; - if (SUCCEEDED(readback_a->Map(0, &range, &mapped))) { - std::memcpy(&word, mapped, sizeof word); - const D3D12_RANGE none{0, 0}; - readback_a->Unmap(0, &none); - } - return word; - }; - - Ref alloc_a, alloc_b; - Ref copy_a, list_b; - if (FAILED(dev_a->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&alloc_a.p))) || - FAILED(dev_a->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, alloc_a.p, nullptr, - IID_PPV_ARGS(©_a.p))) || - FAILED(dev_b->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&alloc_b.p))) || - FAILED(dev_b->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, alloc_b.p, nullptr, - IID_PPV_ARGS(&list_b.p)))) - return 1; - copy_a->CopyBufferRegion(readback_a.p, 0, upload_a.p, 0, sizeof marker); - if (FAILED(copy_a->Close()) || FAILED(list_b->Close())) return 1; - - ID3D12CommandList* single_foreign[] = {list_b.p}; - q_a->ExecuteCommandLists(1, single_foreign); - check(rt::d3d12::last_execute_result(q_a.p) == leonida::ReplayResult::unsupported, - "layer: queue_A->ExecuteCommandLists({list_B}) refused"); - - ID3D12CommandList* mixed_batch[] = {copy_a.p, list_b.p}; - q_a->ExecuteCommandLists(2, mixed_batch); - check(rt::d3d12::last_execute_result(q_a.p) == leonida::ReplayResult::unsupported, - "layer: queue_A->ExecuteCommandLists({copy_A, list_B}) refused"); - check(wait_idle(dev_a.p, q_a.p) && read_word() == 0, - "layer: mixed batch refusal executed neither list"); - - ID3D12CommandList* valid_batch[] = {copy_a.p}; - q_a->ExecuteCommandLists(1, valid_batch); - check(rt::d3d12::last_execute_result(q_a.p) == leonida::ReplayResult::success && - wait_idle(dev_a.p, q_a.p) && read_word() == marker, - "layer: same-device queue_A->ExecuteCommandLists({copy_A}) runs and copies marker"); - } - - // 5. GraphicsCommandList::ExecuteBundle cross-device rejection + same-device positive control. - { - Ref direct_alloc_a, bundle_alloc_a, bundle_alloc_b; - Ref list_a, bundle_a, bundle_b; - if (FAILED(dev_a->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&direct_alloc_a.p))) || - FAILED(dev_a->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_BUNDLE, IID_PPV_ARGS(&bundle_alloc_a.p))) || - FAILED(dev_b->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_BUNDLE, IID_PPV_ARGS(&bundle_alloc_b.p))) || - FAILED(dev_a->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, direct_alloc_a.p, nullptr, - IID_PPV_ARGS(&list_a.p))) || - FAILED(dev_a->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_BUNDLE, bundle_alloc_a.p, nullptr, - IID_PPV_ARGS(&bundle_a.p))) || - FAILED(dev_b->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_BUNDLE, bundle_alloc_b.p, nullptr, - IID_PPV_ARGS(&bundle_b.p)))) - return 1; - if (FAILED(bundle_a->Close()) || FAILED(bundle_b->Close())) return 1; - - list_a->ExecuteBundle(bundle_b.p); - check(list_a->Close() == E_INVALIDARG, "layer: list_A->ExecuteBundle(bundle_B) makes Close() return E_INVALIDARG"); - ID3D12CommandList* invalid_batch[] = {list_a.p}; - q_a->ExecuteCommandLists(1, invalid_batch); - check(rt::d3d12::last_execute_result(q_a.p) == leonida::ReplayResult::unsupported, - "layer: executing list_A invalidated by foreign bundle is refused"); - - check(SUCCEEDED(list_a->Reset(direct_alloc_a.p, nullptr)), "layer: list_A resets cleanly"); - list_a->ExecuteBundle(bundle_a.p); - check(SUCCEEDED(list_a->Close()), "layer: same-device list_A->ExecuteBundle(bundle_A) closes S_OK"); - ID3D12CommandList* ok_batch[] = {list_a.p}; - q_a->ExecuteCommandLists(1, ok_batch); - check(rt::d3d12::last_execute_result(q_a.p) == leonida::ReplayResult::success && wait_idle(dev_a.p, q_a.p), - "layer: same-device ExecuteBundle list executes cleanly"); - } - - // 6. Blocking SetEventOnMultipleFenceCompletion when device is already lost. - check_device_lost_blocking_multi_fence(); - - // 7. Live Windows D3D12 host parity checks. - check_host_parity(); - - std::printf("%d failure(s)\n", failures); - return failures ? 1 : 0; -} diff --git a/runtime/test/d3d12_d24_support_test.cpp b/runtime/test/d3d12_d24_support_test.cpp deleted file mode 100644 index 7ba13112b..000000000 --- a/runtime/test/d3d12_d24_support_test.cpp +++ /dev/null @@ -1,115 +0,0 @@ -// CheckFeatureSupport for the D24 family must describe what CreateCommittedResource does. -// -// A GPU without Vulkan D24_UNORM_S8_UINT (AMD) gets D32_SFLOAT_S8_UINT behind a D24 texture (#737). The layer's -// FORMAT_SUPPORT asked the D24 format itself and reported Support1 = 0 for D24_UNORM_S8_UINT and R24G8_TYPELESS -// on an RX 9070 XT, and MULTISAMPLE_QUALITY_LEVELS reported 0 levels for R24G8_TYPELESS at every count, while -// creating the depth-stencil resources succeeded (found by @zneel, #1380). This checks the layer against itself on -// whatever GPU runs it, native D24 or not: -// * a 1x ALLOW_DEPTH_STENCIL texture is creatable exactly when FORMAT_SUPPORT reports DEPTH_STENCIL (and then -// TEXTURE2D); -// * at 2x, 4x and 8x a quality level is reported exactly when a multisampled depth-stencil texture is creatable. -// -// Synthetic resources only; no game files. -#include "vk_test_device.h" -#include "../shims/d3d12_com.h" - -#include - -namespace { - -int g_failures = 0; - -void check(bool ok, const char* what, DXGI_FORMAT format, UINT samples = 1) { - std::printf("%s %s (format %d, %ux)\n", ok ? "PASS" : "FAIL", what, static_cast(format), samples); - if (!ok) ++g_failures; -} - -bool creatable(ID3D12Device* device, DXGI_FORMAT format, UINT samples) { - D3D12_HEAP_PROPERTIES heap{D3D12_HEAP_TYPE_DEFAULT}; - D3D12_RESOURCE_DESC desc{}; - desc.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D; - desc.Width = 64; - desc.Height = 64; - desc.DepthOrArraySize = 1; - desc.MipLevels = 1; - desc.Format = format; - desc.SampleDesc.Count = samples; - desc.Flags = D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL; - D3D12_CLEAR_VALUE clear{}; - clear.Format = format == DXGI_FORMAT_R24G8_TYPELESS ? DXGI_FORMAT_D24_UNORM_S8_UINT : format; - clear.DepthStencil.Depth = 1.0f; - ID3D12Resource* resource = nullptr; - const HRESULT hr = device->CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &desc, D3D12_RESOURCE_STATE_DEPTH_WRITE, - &clear, IID_PPV_ARGS(&resource)); - if (resource) resource->Release(); - return SUCCEEDED(hr); -} - -} // namespace - -int main() { - vktest::Device d; - const auto status = d.initialize(); - if (status == vktest::DeviceStatus::unavailable) return 77; - if (status != vktest::DeviceStatus::ready) return 1; - - VkFormatProperties d24{}; - d.instance_fn("vkGetPhysicalDeviceFormatProperties")( - d.physical, VK_FORMAT_D24_UNORM_S8_UINT, &d24); - const bool native_d24 = (d24.optimalTilingFeatures & VK_FORMAT_FEATURE_DEPTH_STENCIL_ATTACHMENT_BIT) != 0; - std::printf("Vulkan D24_UNORM_S8_UINT depth attachment: %s\n", - native_d24 ? "native" : "no (D24 is stored as D32_SFLOAT_S8_UINT)"); - - rt::d3d12::VulkanDeviceInfo info{}; - info.get_instance_proc = d.instance_proc; - info.instance = d.instance; - info.physical = d.physical; - info.device = d.device; - info.queue = d.queue; - info.queue_family = d.family; - info.bindless = d.bindless; - info.bindless_partially_bound = d.partially_bound; - info.image_view_min_lod = d.image_view_min_lod; - info.host_image_copy = d.host_image_copy; - ID3D12Device* device = nullptr; - if (FAILED(rt::d3d12::create_vulkan_device(info, IID_PPV_ARGS(&device))) || !device) { - std::printf("FAIL Vulkan-backed D3D12 device created\n"); - return 1; - } - - for (const DXGI_FORMAT format : {DXGI_FORMAT_D24_UNORM_S8_UINT, DXGI_FORMAT_R24G8_TYPELESS}) { - D3D12_FEATURE_DATA_FORMAT_SUPPORT fs{format}; - const HRESULT hr = device->CheckFeatureSupport(D3D12_FEATURE_FORMAT_SUPPORT, &fs, sizeof(fs)); - const bool reported_ds = SUCCEEDED(hr) && (fs.Support1 & D3D12_FORMAT_SUPPORT1_DEPTH_STENCIL); - std::printf("format %d: FORMAT_SUPPORT hr=0x%08lx Support1=0x%08x Support2=0x%08x\n", static_cast(format), - static_cast(hr), fs.Support1, fs.Support2); - // A TYPELESS member can be created with ALLOW_DEPTH_STENCIL, but D3D12 reports DEPTH_STENCIL only for its - // typed depth format: on an RTX 4060 Ti and WARP, R24G8_TYPELESS gives Support1 0x001010b0 and - // D24_UNORM_S8_UINT 0x003110b0 (the DEPTH_STENCIL bit is 0x00010000). - const bool typeless = format == DXGI_FORMAT_R24G8_TYPELESS; - const bool made = creatable(device, format, 1); - check(made, "a 1x ALLOW_DEPTH_STENCIL texture is created", format); - check(reported_ds == (made && !typeless), - "FORMAT_SUPPORT reports DEPTH_STENCIL exactly when creation succeeds, for the typed format only", format); - if (made) check((fs.Support1 & D3D12_FORMAT_SUPPORT1_TEXTURE2D) != 0, "FORMAT_SUPPORT reports TEXTURE2D", format); - - for (const UINT samples : {2u, 4u, 8u}) { - D3D12_FEATURE_DATA_MULTISAMPLE_QUALITY_LEVELS levels{format, samples}; - device->CheckFeatureSupport(D3D12_FEATURE_MULTISAMPLE_QUALITY_LEVELS, &levels, sizeof(levels)); - const bool ms_made = creatable(device, format, samples); - std::printf("format %d %ux: quality levels %u, created %s\n", static_cast(format), samples, - levels.NumQualityLevels, ms_made ? "yes" : "no"); - check((levels.NumQualityLevels > 0) == ms_made, - "a quality level is reported exactly when the multisampled depth-stencil texture is created", - format, samples); - } - } - device->Release(); - - if (g_failures) { - std::printf("d3d12_d24_support_test: %d checks failed\n", g_failures); - return 1; - } - std::printf("d3d12_d24_support_test: OK\n"); - return 0; -} diff --git a/runtime/test/d3d12_debug_markers_test.cpp b/runtime/test/d3d12_debug_markers_test.cpp deleted file mode 100644 index a87fd030f..000000000 --- a/runtime/test/d3d12_debug_markers_test.cpp +++ /dev/null @@ -1,365 +0,0 @@ -// D3D-24 on a GPU: SetMarker/BeginEvent/EndEvent on command lists and queues become VK_EXT_debug_utils labels, -// and private data (SetPrivateData, SetPrivateDataInterface, SetName) works on every object of the Vulkan device. -// The device is built behind the Xbox-ABI proxy, as in d3d12_vulkan_device_test, on a vkGetInstanceProcAddr that -// records every label call before forwarding it to the driver, so the test sees exactly what reached Vulkan. -// Without VK_EXT_debug_utils the label part is skipped; the no-extension path (markers are no-ops) and private -// data always run. No shaders or game data. Set LEONIDA_VK_VALIDATION=1 to run under VK_LAYER_KHRONOS_validation; -// any validation error fails the test. -#include "vk_test_device.h" -#include "../shims/d3d12_com.h" -#include "../shims/d3d12_xs_device.h" - -#include -#include -#include -#include - -#define EXPECT(condition) do { \ - if (!(condition)) { std::fprintf(stderr, "line %d: %s\n", __LINE__, #condition); return 1; } \ -} while (0) - -namespace { - -template -struct Ref { - T* p = nullptr; - ~Ref() { reset(); } - void reset() { - if (p) p->Release(); - p = nullptr; - } - T* operator->() const { return p; } -}; - -// Every label call the layer made, in order: "cmd insert / does not exist - const ShaderEntry* found = loaded ? relative.find("cs", entry->fssm_sha256) : nullptr; - const bool read = found && relative.spirv(*found).size() == 5; - std::filesystem::current_path(cwd); - std::error_code ec; - CHECK(loaded && relative.directory().is_absolute() && - std::filesystem::equivalent(relative.directory(), dir, ec)); - CHECK(read); - } - CHECK(!library.load((dir / "missing").string(), &error) && !error.empty()); - { - std::ofstream index(dir / "index.json", std::ios::binary | std::ios::trunc); - index << "{\"bad\": {\"stage\": \"cs\", \"fssm_sha256\": \"00\", \"push_constant_bytes\": -}}"; - } - error.clear(); - CHECK(!library.load(dir.string(), &error) && !error.empty()); // refused, not thrown - std::filesystem::remove_all(dir); - - if (const int line = fspx_checks()) return line; - - // FSPX entries: found by fspx_code_sha256, in the main index or in /fspx/index.json (named "fspx/"). - { - const auto code = fspx_code(0x1000), other = fspx_code(0x2000); - const std::string code_hash = sha256_hex(code), other_hash = sha256_hex(other); - std::filesystem::create_directories(dir / "fspx"); - { - std::ofstream index(dir / "index.json", std::ios::binary); - index << "{\"cs_game\": {\"stage\": \"cs\", \"fssm_sha256\": \"" << hash << "\"},\n" - " \"cs_fspx_main\": {\"stage\": \"cs\", \"fspx_code_sha256\": \"" << other_hash << "\"}}"; - std::ofstream sub(dir / "fspx" / "index.json", std::ios::binary); - // fspx_payload's kind 0 is 28 bytes of 0x11. - sub << "{\"upscaler_00\": {\"stage\": \"cs\", \"fspx_code_sha256\": \"" << code_hash - << "\", \"fspx_state_sha256\": \"" << sha256_hex(std::vector(28, 0x11)) - << "\", \"bindings\": [], \"local_size\": [8, 8, 1], \"wave64\": true}}"; - std::ofstream spv(dir / "fspx" / "upscaler_00.spv", std::ios::binary); - const std::uint32_t words[5] = {0x07230203, 0x00010500, 0, 1, 0}; - spv.write(reinterpret_cast(words), sizeof(words)); - } - ShaderLibrary fspx; - CHECK(fspx.load(dir.string(), &error) && fspx.size() == 3 && fspx.fspx_size() == 1); - const auto found = fspx.fspx_candidates("cs", code_hash); - CHECK(found.size() == 1 && found[0]->name == "fspx/upscaler_00" && found[0]->local_size[0] == 8 && - found[0]->wave64 && found[0]->fssm_sha256.empty()); - CHECK(fspx.spirv(*found[0]).size() == 5); // /fspx/upscaler_00.spv - // The key computed both ways finds the entry: from the container slot 62 gets, from the bare program. - CHECK(fspx.program_candidates("cs", compute_program(accc_container(fspx_payload(code)))) == found); - CHECK(fspx.program_candidates("cs", compute_program(code)) == found); - CHECK(fspx.program_candidates("cs", compute_program(other)).at(0)->name == "cs_fspx_main"); - // The two keys do not mix: an FSPX hash is not an FSSM hash and the other way round. - CHECK(fspx.candidates("cs", code_hash).empty() && fspx.fspx_candidates("cs", hash).empty()); - CHECK(fspx.find("cs", hash) && fspx.find("cs", hash)->name == "cs_game"); - CHECK(fspx.fspx_candidates("vs", code_hash).empty()); - CHECK(fspx.program_candidates("cs", compute_program(fspx_code(0x3000))).empty()); // not translated - CHECK(fspx.program_candidates("cs", ComputeProgram{}).empty()); - // A broken fspx/index.json leaves the main index loaded; a missing one is not an error either. - { - std::ofstream sub(dir / "fspx" / "index.json", std::ios::binary | std::ios::trunc); - sub << "{broken"; - } - CHECK(fspx.load(dir.string(), &error) && fspx.size() == 2 && fspx.fspx_size() == 0 && - fspx.fspx_candidates("cs", code_hash).empty()); - std::filesystem::remove(dir / "fspx" / "index.json"); - CHECK(fspx.load(dir.string(), &error) && fspx.size() == 2 && fspx.fspx_size() == 0 && fspx.find("cs", hash)); - std::filesystem::remove_all(dir); - } - - // Pipeline-library entries: the compute programs of the library in shaders.rpf, translated by make_game.py into - // /library/index.json (named "library/"), are found by the same two keys as the DLL's FSPX programs, - // next to /fspx/. The executable's slot-67 description carries kind 0 (the record's state blob) and kind 6. - { - const auto code = fspx_code(0x5000); - const auto shared_code = fspx_code(0x7000); - std::vector state(28, 0), other_state(28, 0); - state[12] = 64; // word 3: NumThreadsX - other_state[12] = 32; - const auto n = std::uint32_t(code.size()); - const auto payload = [&](const std::vector& kind0) { - std::vector body = kind0; - body.insert(body.end(), code.begin(), code.end()); - return fspx_payload({{0, 48, 28}, {6, 48 + 28, n}}, body); - }; - std::filesystem::create_directories(dir / "fspx"); - std::filesystem::create_directories(dir / "library"); - { - std::ofstream index(dir / "index.json", std::ios::binary | std::ios::trunc); - index << "{\"cs_game\": {\"stage\": \"cs\", \"fssm_sha256\": \"" << hash << "\"}}"; - std::ofstream dll(dir / "fspx" / "index.json", std::ios::binary | std::ios::trunc); - dll << "{\"upscaler_00\": {\"stage\": \"cs\", \"fspx_code_sha256\": \"" << sha256_hex(fspx_code(0x6000)) - << "\"}, \"shared_dll\": {\"stage\": \"cs\", \"fspx_code_sha256\": \"" << sha256_hex(shared_code) - << "\"}}"; - std::ofstream lib(dir / "library" / "index.json", std::ios::binary | std::ios::trunc); - lib << "{\"lib_cs_00007\": {\"stage\": \"cs\", \"fspx_code_sha256\": \"" << sha256_hex(code) - << "\", \"fspx_state_sha256\": \"" << sha256_hex(state) - << "\", \"bindings\": [], \"local_size\": [64, 1, 1]}, " - << "\"lib_cs_shared\": {\"stage\": \"cs\", \"fspx_code_sha256\": \"" << sha256_hex(shared_code) - << "\"}}"; - std::ofstream spv(dir / "library" / "lib_cs_00007.spv", std::ios::binary); - const std::uint32_t words[5] = {0x07230203, 0x00010500, 7, 1, 0}; - spv.write(reinterpret_cast(words), sizeof(words)); - } - ShaderLibrary library; - CHECK(library.load(dir.string(), &error) && library.size() == 5 && library.fspx_size() == 4); - const auto found = library.fspx_candidates("cs", sha256_hex(code)); - CHECK(found.size() == 1 && found[0]->name == "library/lib_cs_00007" && found[0]->local_size[0] == 64 && - found[0]->fssm_sha256.empty()); - CHECK(library.spirv(*found[0]).size() == 5); // /library/lib_cs_00007.spv - // fspx/ loads before library/, so shared code keys preserve fspx/ entries ahead of library/ entries. - const auto shared = library.fspx_candidates("cs", sha256_hex(shared_code)); - CHECK(shared.size() == 2 && shared[0]->name == "fspx/shared_dll" && shared[1]->name == "library/lib_cs_shared"); - // As slot 67 passes it: kind 0 and kind 6 in one payload. The record's state finds it; another state doesn't. - bool ambiguous = true; - CHECK(library.program_candidates("cs", compute_program(payload(state)), &ambiguous) == found && !ambiguous); - CHECK(library.program_candidates("cs", compute_program(payload(other_state)), &ambiguous).empty()); - // The DLL's entries are still there, and the game's own by FSSM hash. - CHECK(library.fspx_candidates("cs", sha256_hex(fspx_code(0x6000))).at(0)->name == "fspx/upscaler_00"); - CHECK(library.find("cs", hash) && library.find("cs", hash)->name == "cs_game"); - // A broken library index leaves the others loaded; a missing one is not an error either. - { - std::ofstream lib(dir / "library" / "index.json", std::ios::binary | std::ios::trunc); - lib << "{broken"; - } - CHECK(library.load(dir.string(), &error) && library.size() == 3 && library.fspx_size() == 2 && - library.fspx_candidates("cs", sha256_hex(code)).empty()); - std::filesystem::remove(dir / "library" / "index.json"); - CHECK(library.load(dir.string(), &error) && library.size() == 3 && library.fspx_size() == 2); - std::filesystem::remove_all(dir); - } - - // XboxBvhBuilder.dll's programs (docs/embedded_shaders.md): FSSM in a DXIL container like the game's shaders, - // translated into /bvh (entries named "bvh/") and found by fssm_sha256, the game shaders' key. - { - const auto builder = container({{fixed, 25}}); // what the DLL passes to slot 62: the whole container - const auto untranslated = container({{stored, 40}}); - const std::string builder_hash = sha256_hex(bytes("hello hello hello leonida")); - const auto code = fspx_code(0x5000); - const std::uint32_t words[5] = {0x07230203, 0x00010500, 0, 1, 0}; - const auto write = [&](const std::filesystem::path& file, const std::string& text) { - std::ofstream out(file, std::ios::binary | std::ios::trunc); - out << text; - }; - const std::string game = "\"cs_game\": {\"stage\": \"cs\", \"fssm_sha256\": \"" + hash + "\"}"; - const std::string program_entry = - "{\"stage\": \"cs\", \"fssm_sha256\": \"" + builder_hash + - "\", \"bindings\": [], \"push_constant_bytes\": 144, \"local_size\": [64, 1, 1], \"lds_bytes\": 32768, " - "\"uses_code_base\": true, \"wave64\": true, \"subgroup_size\": 64}"; - std::filesystem::create_directories(dir / "bvh"); - std::filesystem::create_directories(dir / "fspx"); - write(dir / "index.json", "{" + game + "}"); - write(dir / "fspx" / "index.json", - "{\"upscaler_00\": {\"stage\": \"cs\", \"fspx_code_sha256\": \"" + sha256_hex(code) + "\"}}"); - // The second entry is a program whose metadata failed: no key, so nothing can find it and it is not counted. - write(dir / "bvh" / "index.json", - "{\"BuilderProgram\": " + program_entry + ",\n \"NoKey\": {\"error\": \"ValueError: synthetic\"}}"); - { - std::ofstream spv(dir / "bvh" / "BuilderProgram.spv", std::ios::binary); - spv.write(reinterpret_cast(words), sizeof(words)); - } - ShaderLibrary bvh; - CHECK(bvh.load(dir.string(), &error) && bvh.size() == 3 && bvh.bvh_size() == 1 && bvh.fspx_size() == 1); - const ComputeProgram program = compute_program(builder); - CHECK(program.kind == ComputeProgram::Kind::fssm && sha256_hex(program.bytes) == builder_hash); - const auto found = bvh.program_candidates("cs", program); - CHECK(found.size() == 1 && found[0]->name == "bvh/BuilderProgram" && found[0] == bvh.find("cs", builder_hash)); - CHECK(found[0]->lds_bytes == 32768 && found[0]->wave64 && found[0]->subgroup_size == 64 && - found[0]->uses_code_base && found[0]->local_size[0] == 64 && found[0]->fspx_code_sha256.empty()); - CHECK(bvh.spirv(*found[0]).size() == 5); // /bvh/BuilderProgram.spv - // The other indexes are untouched: the game's shader and the FSPX program are found as before, each by its - // own key, and a builder program is neither an FSPX program nor a shader of another stage. - CHECK(bvh.find("cs", hash) && bvh.find("cs", hash)->name == "cs_game"); - CHECK(bvh.program_candidates("cs", compute_program(code)).at(0)->name == "fspx/upscaler_00"); - CHECK(bvh.fspx_candidates("cs", builder_hash).empty() && bvh.candidates("vs", builder_hash).empty()); - // A program the translator left out (Box16Rehydration today) has no entry: nothing is found, and no other - // program's module stands in for it. - CHECK(compute_program(untranslated).kind == ComputeProgram::Kind::fssm); - CHECK(bvh.program_candidates("cs", compute_program(untranslated)).empty()); - // The same program in the game's index too: both entries, the game's first (index order). - write(dir / "index.json", "{" + game + ",\n \"cs_same\": " + program_entry + "}"); - CHECK(bvh.load(dir.string(), &error) && bvh.size() == 4 && bvh.bvh_size() == 1); - const auto both = bvh.candidates("cs", builder_hash); - CHECK(both.size() == 2 && both[0]->name == "cs_same" && both[1]->name == "bvh/BuilderProgram"); - write(dir / "index.json", "{" + game + "}"); - // A broken bvh/index.json leaves the main index and the FSPX one loaded; a missing one is not an error - // either, and neither is a broken fspx/index.json for the builder's programs. - write(dir / "bvh" / "index.json", "{broken"); - CHECK(bvh.load(dir.string(), &error) && bvh.size() == 2 && bvh.bvh_size() == 0 && bvh.fspx_size() == 1 && - bvh.program_candidates("cs", program).empty() && bvh.find("cs", hash)); - std::filesystem::remove(dir / "bvh" / "index.json"); - CHECK(bvh.load(dir.string(), &error) && bvh.size() == 2 && bvh.bvh_size() == 0 && bvh.find("cs", hash)); - write(dir / "bvh" / "index.json", "{\"BuilderProgram\": " + program_entry + "}"); - write(dir / "fspx" / "index.json", "{broken"); - CHECK(bvh.load(dir.string(), &error) && bvh.size() == 2 && bvh.bvh_size() == 1 && bvh.fspx_size() == 0 && - bvh.program_candidates("cs", program).size() == 1); - std::filesystem::remove_all(dir); - } - - // The review case on #1911: one kind-6 program in two containers whose kind-0 entries differ (32x1x1 and - // 64x1x1), translated to two different modules. A container picks its own entry by fspx_state_sha256; a bare - // kind-6 program cannot tell them apart and is refused as ambiguous; with one module for the key it is accepted. - { - const auto code = fspx_code(0x4000); - std::vector state32(28, 0), state64(28, 0), state16(28, 0); - state32[12] = 32; // word 3: NumThreadsX - state64[12] = 64; - state16[12] = 16; - const auto n = std::uint32_t(code.size()); - const auto wrapped = [&](const std::vector& state) { - std::vector body = state; - body.insert(body.end(), code.begin(), code.end()); - return accc_container(fspx_payload({{0, 48, 28}, {6, 48 + 28, n}}, body)); - }; - const auto module = [](std::uint32_t generator) { - return std::vector{0x07230203, 0x00010500, generator, 1, 0}; - }; - const auto write = [&](const std::string& name, const std::vector& words) { - std::ofstream spv(dir / "fspx" / (name + ".spv"), std::ios::binary); - spv.write(reinterpret_cast(words.data()), std::streamsize(words.size() * 4)); - }; - const auto index = [&](const std::vector*>>& entries, - bool different_layout = false) { - std::ofstream main(dir / "index.json", std::ios::binary | std::ios::trunc); - main << "{}"; - std::ofstream sub(dir / "fspx" / "index.json", std::ios::binary | std::ios::trunc); - sub << "{"; - for (std::size_t i = 0; i < entries.size(); ++i) - sub << (i ? ",\n" : "") << "\"" << entries[i].first << "\": {\"stage\": \"cs\", \"fspx_code_sha256\": \"" - << sha256_hex(code) << "\", \"fspx_state_sha256\": \"" << sha256_hex(*entries[i].second) << "\"" - << (i == 1 && different_layout ? ", \"push_constant_bytes\": 16" : "") << "}"; - sub << "}"; - }; - std::filesystem::create_directories(dir / "fspx"); - write("pair_32", module(1)); - write("pair_64", module(2)); - index({{"pair_32", &state32}, {"pair_64", &state64}}); - ShaderLibrary pair; - CHECK(pair.load(dir.string(), &error) && pair.size() == 2); - CHECK(pair.fspx_candidates("cs", sha256_hex(code)).size() == 2); - bool ambiguous = true; - const auto by32 = pair.program_candidates("cs", compute_program(wrapped(state32)), &ambiguous); - CHECK(by32.size() == 1 && by32[0]->name == "fspx/pair_32" && !ambiguous); - const auto by64 = pair.program_candidates("cs", compute_program(wrapped(state64)), &ambiguous); - CHECK(by64.size() == 1 && by64[0]->name == "fspx/pair_64" && !ambiguous); - CHECK(pair.program_candidates("cs", compute_program(wrapped(state16)), &ambiguous).empty() && !ambiguous); - CHECK(pair.program_candidates("cs", compute_program(code), &ambiguous).empty() && ambiguous); - // Slot 67 with all four pairs (RT-99): the payload the proxy builds carries kind 0, so each program finds - // its own translation, where the bare kind-6 program above is ambiguous. - { - const std::vector kind1(20, 0x22), kind7(24, 0x77); - for (const auto* state : {&state32, &state64}) { - const FspxPart parts[] = {{0, state->data(), state->size()}, {1, kind1.data(), kind1.size()}, - {6, code.data(), code.size()}, {7, kind7.data(), kind7.size()}}; - const auto built = fspx_payload_from_parts(parts); - const ComputeProgram program = compute_program(built); - CHECK(program.kind == ComputeProgram::Kind::fspx && program.bytes == code && program.state == *state); - const auto found = pair.program_candidates("cs", program, &ambiguous); - CHECK(found.size() == 1 && !ambiguous && - found[0]->name == (state == &state32 ? "fspx/pair_32" : "fspx/pair_64")); - } - } - // The same two keys with one module (a duplicate container) is not ambiguous for the bare program. - write("pair_64", module(1)); - CHECK(pair.program_candidates("cs", compute_program(code), &ambiguous).size() == 2 && !ambiguous); - // Equal words with conflicting layout metadata are ambiguous until kind 0 selects one entry. - index({{"pair_32", &state32}, {"pair_64", &state64}}, true); - CHECK(pair.load(dir.string(), &error)); - CHECK(pair.program_candidates("cs", compute_program(code), &ambiguous).empty() && ambiguous); - const auto by_layout = pair.program_candidates("cs", compute_program(wrapped(state64)), &ambiguous); - CHECK(by_layout.size() == 1 && by_layout[0]->push_constant_bytes == 16 && !ambiguous); - // One translation for the code key: the bare program takes it. - index({{"pair_32", &state32}}); - CHECK(pair.load(dir.string(), &error) && pair.size() == 1); - const auto bare = pair.program_candidates("cs", compute_program(code), &ambiguous); - CHECK(bare.size() == 1 && bare[0]->name == "fspx/pair_32" && !ambiguous); - std::filesystem::remove_all(dir); - } - - // fspx_payload_from_parts: the slot-67 pairs as one payload, and every inconsistent pair refused before a read. - { - const auto code = fspx_code(0x5000); - const std::vector state(28, 0x11), kind1(20, 0x22), kind7(24, 0x77); - const auto build = [&](std::initializer_list parts) { - return fspx_payload_from_parts(std::span(parts.begin(), parts.size())); - }; - const auto full = build({{0, state.data(), 28}, {1, kind1.data(), 20}, {6, code.data(), code.size()}, - {7, kind7.data(), 24}}); - CHECK(!full.empty() && full.size() % 16 == 0); - const FspxParts parsed = fspx_parts(full); - CHECK(std::vector(parsed.code.begin(), parsed.code.end()) == code); - CHECK(std::vector(parsed.state.begin(), parsed.state.end()) == state); - // Kinds 1 and 7 are optional (null pointer and zero size), as in the DLL's reader. - CHECK(compute_program(build({{0, state.data(), 28}, {1, nullptr, 0}, {6, code.data(), code.size()}, - {7, nullptr, 0}})).state == state); - // A wild pointer with a size that is refused is never read; neither is anything after a refused pair. - const void* wild = reinterpret_cast(std::uintptr_t(0x10)); - CHECK(build({{0, state.data(), 28}, {6, code.data(), code.size()}, {7, wild, kFspxPartLimit + 1}}).empty()); - CHECK(build({{0, state.data(), 28}, {6, nullptr, code.size()}}).empty()); // size without pointer - CHECK(build({{0, state.data(), 28}, {6, code.data(), 0}}).empty()); // pointer without size - CHECK(build({{0, state.data(), 28}, {1, wild, 0}, {6, code.data(), code.size()}}).empty()); - CHECK(build({{0, nullptr, 0}, {6, code.data(), code.size()}}).empty()); // no kind 0 - CHECK(build({{0, state.data(), 28}, {7, kind7.data(), 24}}).empty()); // no kind 6 - CHECK(build({{0, state.data(), 28}, {6, code.data(), code.size()}, {6, code.data(), code.size()}}).empty()); - CHECK(build({{0, state.data(), 28}, {6, code.data(), code.size()}, {5, kind7.data(), 24}}).empty()); - CHECK(build({{0, state.data(), 28}, {6, code.data(), code.size()}, {99, kind7.data(), 24}}).empty()); - } - - CHECK(huffman_lut_checks() == 0); - - std::printf("SHA-256, inflate (stored/fixed/dynamic), JSON, FSSM extraction, FSPX programs and index lookup OK\n"); - return 0; -} diff --git a/runtime/test/shaders/build.py b/runtime/test/shaders/build.py deleted file mode 100644 index c9fd70e4a..000000000 --- a/runtime/test/shaders/build.py +++ /dev/null @@ -1,276 +0,0 @@ -"""Build the hand-written test shaders in this folder into SPIR-V. - - python3 -I runtime/test/shaders/build.py [name ...] - -Each .asm is RDNA2 assembly. It is assembled with llvm-mc (LLVM 21+ with the AMDGPU target; set LLVM_MC to its -path or to a whole command, as for the shaders stage). Listings, synthetic FSSM headers and DXBC containers are -staged in a temporary directory. After validation, the build writes /spirv/.spv and the translator -metadata. - -Compute shaders can override the default header with leading "; group: X,Y,Z" and "; rsrc2: 0x..." comments. -A shader whose header has "; fssm-at: 0xOFFSET" and "; fssm-data: 0xWORD ..." comments also gets a synthetic -FSSM program (the magic, zeros up to OFFSET, then the words): it is published as /fssm/.fssm and its -SHA-256 goes into the index as fssm_sha256, which is what the layer looks a PSO's shader up by (the translator -hashes /fssm/.fssm for the game's programs, and compute shaders here already). A test builds the shader container from that file. The words -are also what a shader reads through s_getpc_b64 (the code base) at that offset. -The stage comes from the name's prefix. Mesh shaders (ms_) also need a DXBC container with their PSV0, which this -doesn't make; geometry shaders (gs_) get gs_tri's signatures (gs_container). -The comment at the top of each .asm says which test program to run on the result and what it should print. -With LEONIDA_FMA=khr (or glsl, or exact), the fused multiply-adds are translated with --fma khr (OpFmaKHR, which needs -VK_KHR_shader_fma; the test programs enable it when the device has it, else they exit 77), --fma glsl, or --fma exact -(a single rounding built from plain f32 ops, for a driver that splits GLSL Fma and has no VK_KHR_shader_fma). -With LEONIDA_BARY_FALLBACK=1, pixel shaders that read raw barycentrics are translated with --bary-fallback, and -each gets a pass-through geometry shader, .bary_gs.spv, that check.py draws it with (tools/bary_fallback_gs.py). -With the variable unset, build.py/check.py follow the Mesa ANV probe automatically. -Under that or LEONIDA_F16_INTERP_FALLBACK=1, ps_ij_computed isn't built: its computed I/J pair needs PerVertexKHR -inputs, and check.py reports it as SKIP. -With LEONIDA_PC_TAIL_UBO=1, every shader is translated with --pc-tail-ubo (s0..s31 in 128 push-constant bytes, the -heap base and code base in a uniform block at set 1), for devices whose maxPushConstantsSize is 128; set it for -check.py too, whose test programs then bind that block (runtime/test/vk_pc_tail.h). -""" -import json -import os -import re -import struct -import subprocess -import sys -import tempfile -from pathlib import Path - -HERE = os.path.dirname(os.path.abspath(__file__)) -TOOLS = os.path.join(HERE, "..", "..", "..", "tools") -TRANSLATOR = os.path.join(TOOLS, "rdna2spirv.py") -sys.path.insert(0, TOOLS) -import mc_command # noqa: E402 - -MC = mc_command.mc_command() -RSRC2, GROUP = 0x8088, (64, 1, 1) -# Not built under LEONIDA_BARY_FALLBACK=1 or LEONIDA_F16_INTERP_FALLBACK=1 (see main). -NEEDS_PER_VERTEX_INPUTS = ("ps_ij_computed",) -sys.path.insert(0, HERE) # this script is also run with python -I -from compute_fixture import compute_header, shift_user_data, user_data_shift # noqa: E402 - - -def barycentric_fallback_override(): - v = (os.environ.get("LEONIDA_BARY_FALLBACK") or "").strip().lower() - if v in ("1", "true", "yes", "on"): - return True - if v in ("0", "false", "no", "off"): - return False - return None - - -def barycentric_fallback(): - override = barycentric_fallback_override() - if override is not None: - return override - try: - r = subprocess.run([sys.executable, "-I", os.path.join(TOOLS, "vk_subgroup_info.py")], - capture_output=True, text=True, timeout=60) - answer = json.loads(r.stdout.strip().splitlines()[-1]) - return answer.get("barycentric_fallback") is True - except (OSError, ValueError, IndexError, subprocess.SubprocessError): - return False - - -def asm_mattr(path): - for ln in Path(path).read_text(encoding="utf-8").splitlines(): - s = ln.strip() - if not s: - continue - if not s.startswith(";"): - break - m = re.match(r";\s*mattr:\s*(\S+)", s) - if m: - return m.group(1) - return None - - -CLIP_CASES = {"vs_clip": 1, "vs_clip_param4": 4, "vs_clip_undeclared": 1} - - -def asm_fssm_fields(path): - """(offset, words) of the "fssm-at" and "fssm-data" header comments, (None, []) without them.""" - at, words = None, [] - for ln in Path(path).read_text(encoding="utf-8").splitlines(): - s = ln.strip() - if s and not s.startswith(";"): - break - m = re.match(r";\s*fssm-at:\s*(0x[0-9a-fA-F]+|\d+)", s) - if m: - at = int(m.group(1), 0) - m = re.match(r";\s*fssm-data:\s*(.*)", s) - if m: - words += [int(w, 0) for w in m.group(1).split()] - return at, words - - -def asm_fssm(path): - """The synthetic FSSM program a vs_/ps_ shader's header asks for, or None.""" - at, words = asm_fssm_fields(path) - if at is None or not words or at < 4 or at % 4: - return None - return b"FSSM" + bytes(at - 4) + b"".join(struct.pack(".bary_gs.spv). - import bary_fallback_gs - bary_fallback_gs.build_for_index(str(spirv)) - return 0 - - -if __name__ == "__main__": - sys.exit(main()) diff --git a/runtime/test/shaders/check.py b/runtime/test/shaders/check.py deleted file mode 100644 index 7b3777287..000000000 --- a/runtime/test/shaders/check.py +++ /dev/null @@ -1,1900 +0,0 @@ -"""Run the test shaders that build.py made on this machine's GPU and compare with what each one must give. - - python -I runtime/test/shaders/check.py [dir with the test programs] - -The test programs are vk_compute_test, vk_store_test, vk_harness, vk_texture_test, vk_bindless_test and vk_sampler_test -(runtime/build by default). With -the Visual Studio generator they are in runtime/build/RelWithDebInfo, Release and so on: that subfolder is found by -itself (the newest complete one if there are several) and its name is printed. -Each line is one shader: ok, or what came back instead. The wave32 test ps_bitmask_perm checks every pixel, including -the second 32-lane half when a GPU runs fragment shaders in 64-wide subgroups. -The two whole-wave mask checks are skipped when the device cannot provide a full 64-wide compute subgroup. -The cs_w64x_* / ms_w64x_* cross-half tests (lanes 32-63 against lanes 0-31, see their .asm headers) are skipped there -too. With LEONIDA_W64_EMULATE=1 they run without that requirement, on a device whose subgroups are narrower (NVIDIA), -to check a translator that emulates wave64 on them. scripts/run_gpu_tests.py builds the mesh fixtures and -fs_passthru.spv; here the mesh checks run when those files are in /spirv. -ps_tex is skipped when the device lacks a feature the bindless set or the shader needs, ps_ssharp when it lacks one -vk_sampler_test needs. -ps_texoff (texel offsets, on vk_texture_test's texture) is skipped on a device without VK_KHR_maintenance8. -""" -import collections -import json -import math -import os -import re -import struct -import subprocess -import sys -import tempfile -from pathlib import Path - -HERE = os.path.dirname(os.path.abspath(__file__)) -EXE = ".exe" if os.name == "nt" else "" -UNSUPPORTED = 77 # a test tool exits with this when the device lacks a feature - - -def barycentric_fallback_override(): - v = (os.environ.get("LEONIDA_BARY_FALLBACK") or "").strip().lower() - if v in ("1", "true", "yes", "on"): - return True - if v in ("0", "false", "no", "off"): - return False - return None - - -def barycentric_fallback(): - override = barycentric_fallback_override() - if override is not None: - return override - try: - tools = os.path.abspath(os.path.join(HERE, "..", "..", "..", "tools")) - r = subprocess.run([sys.executable, "-I", os.path.join(tools, "vk_subgroup_info.py")], - capture_output=True, text=True, timeout=60) - answer = json.loads(r.stdout.strip().splitlines()[-1]) - return answer.get("barycentric_fallback") is True - except (OSError, ValueError, IndexError, subprocess.SubprocessError): - return False - -# The programs every run needs. Multi-config CMake generators (Visual Studio, Xcode, Ninja Multi-Config) put each of -# them in build/ instead of build/ (TEST-38). -TEST_PROGRAMS = ("vk_compute_test", "vk_store_test", "vk_harness") -CONFIG_DIRS = ("RelWithDebInfo", "Release", "Debug", "MinSizeRel") - - -def complete_build_dirs(build, programs): - """`build` and its configuration subfolders, in that order, that hold all of `programs` (file names with extension).""" - return [d for d in (build, *(os.path.join(build, c) for c in CONFIG_DIRS)) - if all(os.path.isfile(os.path.join(d, n)) for n in programs)] - - -def resolve_build_dir(build, programs): - """The folder that holds all of `programs`. - - Makefile and Ninja builds leave them in `build`. With the Visual Studio generator they land in build/RelWithDebInfo, - build/Release and so on. `build` itself wins when it has them all; otherwise the configuration folder that has them - all and was built last. If none has them, `build` is returned, so a "not found" message names the folder given.""" - found = complete_build_dirs(build, programs) - if not found or found[0] == build: - return build - return max(found, key=lambda d: max(os.path.getmtime(os.path.join(d, n)) for n in programs)) - - -def pick_build_dir(build, programs): - """resolve_build_dir, and say which folder was picked when it is a configuration subfolder, so a report can name - the build it ran and a stale pick is visible.""" - chosen = resolve_build_dir(build, programs) - if chosen != build: - names = [os.path.basename(d) for d in complete_build_dirs(build, programs)] - print(f"test programs: {chosen}" + (f" (newest of {', '.join(names)})" if len(names) > 1 else "")) - return chosen - - -def not_found_message(build, missing): - return (f"Test programs not found in {build}: {', '.join(missing)}\n" - f"(its {', '.join(CONFIG_DIRS)} subfolders were searched too)\n" - "Build them with cmake -S runtime -B runtime/build, then cmake --build runtime/build.\n" - "CMake only builds them when it finds Vulkan. If it printed \"Vulkan SDK not found\", install the " - "Vulkan headers (vulkan-headers on Arch) and configure again.") - -COMPUTE = [("cs_lds", "4", "mirror64"), ("cs_exec64", "1", "exec64"), ("cs_bvh", "1", "bvh"), - ("cs_workgroup_yz", "2x3x4", "workgroup_yz")] -COMPUTE += [("cs_bvh32", "1", "bvh")] # TEST-184: image_bvh_intersect_ray, the 32-bit node pointer; same scene and words -CS_STORE = [0x400080ff, 0xe00003ff, 0x3c004000, 0xeeeeeeee, 0x40003c00, 0xbc003800, 0x40ff8000, 0x3ff00000] -CS_SMEM = [0x5eed0024, 0x5eed0028, 0x5eed002c, 0x5eed0030, 0x5eed0010, 0x5eed0014, 0x5eed0018, 0x5eed001c] -# -0, and NaN checks that need SignedZeroInfNanPreserve (cs_signed_zero_nan.asm); 0 in out[4..7] means it's missing -SIGNED_ZERO_NAN = [0x80000000, 0x80000000, 0x80008000, 0x00008000, 1, 1, 1, 0x00007c00] -WAVE32_DUMPS = ("cs_store", "cs_signed_zero_nan", "cs_smem_soffset_imm", "cs_wqm_w32", "cs_w32_lane_wrap", "cs_movrelsd_2", "cs_w32_permute", - "cs_barrier_divergent", "cs_barrier_early_end", "cs_barrier_loop", "cs_w32_lds_u8_d16", "cs_bpermute32", - "cs_w32_lds_subdword", "cs_w32_lds_wide", - "cs_w32_partial_scmp", "cs_w32_partial_permute", "cs_exec_const", "cs_w32_mask_imm", "cs_w32_int_ext", - "cs_w32_salu64", "cs_w32_misc_ext", "cs_w32_new_ops", "cs_w32_sincos", "cs_lds_b64_cmpst", "cs_lds_xchg64_ext", "cs_lds_atomics_ext", "cs_w32_andn2_exec", - "cs_mask_vgpr_exec", "cs_w32_buffer_sub16", "cs_w32_buffer_store_sub", "cs_w32_fcmpswap", "cs_w32_permlane_fi", - "cs_w32_exec_computed") -# Wave32 lane-mask dumps: their EXEC/VCC masks and lane selects cover 32 lanes, so a device whose widest subgroup is -# narrower (Mesa llvmpipe: 8) can't produce their words. They are skipped there, as ps_bitmask_perm is. They run with -# 32 lanes requested (WAVE32_LANE_ENV), as run_gpu_tests.py does: a device with a range like 8..32 (Intel ANV) may -# otherwise pick a narrower size and return different words (#774). -WAVE32_LANE_ENV = {"VKC_SUBGROUP_SIZE": "32"} -WAVE32_LANE_DUMPS = ("cs_wqm_w32", "cs_w32_lane_wrap", "cs_w32_permute", "cs_bpermute32", "cs_w32_partial_scmp", "cs_w32_partial_permute", "cs_exec_const", - "cs_w32_mask_imm", "cs_lds_b64_cmpst", "cs_lds_xchg64_ext", "cs_lds_atomics_ext", "cs_w32_andn2_exec", "cs_mask_vgpr_exec", "cs_w32_permlane_fi", - "cs_w32_exec_computed") -CS_DPP = [("cs_dpp", [1, 0, 3, 2, 5, 4, 7, 6]), - ("cs_dpp_row", [0, 0, 1, 2, 3, 4, 5, 6]), - ("cs_dpp_mask", [1, 0, 3, 2, 0xeeeeeeee, 0xeeeeeeee, 0xeeeeeeee, 0xeeeeeeee]), - ("cs_dpp8", [7, 6, 5, 4, 3, 2, 1, 0]), - ("cs_dpp_ops", [100, 10, 11, 12, 13, 14, 15, 16]), - ("cs_dpp_bound", [10, 10, 11, 12, 13, 14, 15, 16]), - ("cs_dpp_bank", [0xffffffff, 0xfffffffe, 0xfffffffd, 0xfffffffc, 7, 7, 7, 7]), - ("cs_dpp_fi", [1, 2, 3, 0x7777, 5, 6, 7, 0x7777])] -WAVE32_DUMPS += tuple(n for n, _ in CS_DPP) -WAVE32_LANE_DUMPS += tuple(n for n, _ in CS_DPP) -CS_DUMPS = [*CS_DPP, ("cs_store", CS_STORE), ("cs_smem_soffset_imm", CS_SMEM), - # SHADER-52: wave32 lane select is & 31; lane 40 wraps to 8 - ("cs_w32_lane_wrap", [25, 16, 777, 777]), - # v_movrelsd_2_b32: VGPR[D + M0[25:16]] = VGPR[S0 + M0[9:0]] - ("cs_movrelsd_2", [11, 33, 33, 55, 1717, 77, 1515, 1717]), - # SHADER-90: ds_permute_b32, the forward (scatter) permute; unwritten lane 0, EXEC gates the destination - ("cs_w32_permute", [218, 29, 8, 211, 0, 15, 99, 15]), - # integer ops with CPU-only checks until now (derivations in cs_w32_int_ext.asm) - ("cs_w32_int_ext", [1, 27, 1, 0x33332222, 0xC0000000, 0x4000, 18, 0x20304050]), - # 64-bit scalar data ops and v_mad_u64_u32 (derivations in cs_w32_salu64.asm) - # more ops with CPU-only checks until now (derivations in cs_w32_misc_ext.asm) - # ops merged on 2026-11-22 with CPU-only checks (derivations in cs_w32_new_ops.asm) - # plain 8/16-bit MUBUF stores, one crossing a dword (cs_w32_buffer_store_sub.asm) - ("cs_w32_buffer_store_sub", [0x1122AB44, 0xCDEF7788, 0x34AABBCC, 0xDDDDDD12, 0x0102035A, 0x05061234, 0xAB, 0xFFFFCDEF]), - # 8/16-bit MUBUF d16 loads and stores (cs_w32_buffer_sub16.asm) - ("cs_w32_buffer_sub16", [0xBEEF00AA, 0x00AA1234, 0xBEEFFFAA, 0xFFAA1234, 0xBEEF8899, 0x88991234, 0x1122CD44, 0xABCD7788]), - # ds_cmpst_f32 and buffer_atomic_fcmpswap: float compare (cs_w32_fcmpswap.asm) - ("cs_w32_fcmpswap", [0, 0x3F800000, 0x7FC00000, 0x3F800000, 0x80000000, 0x40400000, 0x3F800000, 0x7FC00000]), - ("cs_w32_new_ops", [0x55, 0x8001, 0xC0000000, 0x80014000, 0x4000FFFF, 0x77, 0x99, 0x1234]), - ("cs_w32_misc_ext", [0x0FFF0FFF, 0xE2C4A688, 0x0007FFFF, 0x7FFF8000, 0xFFFE0002, 0xFFFF0005, 0x509, 0xCAFEF00D]), - ("cs_w32_salu64", [0x1E6A2C48, 0x1234, 0xFFFFFFFF, 0x100, 47, 48, 0xFFFF8000, 0xFFFFFFFE]), - # SHADER-85: 8-bit LDS reads into one half of a VGPR, the other half kept - ("cs_w32_lds_u8_d16", [0xBEEF00FF, 0x00FF1234, 0xBEEFFF80, 0xFF801234, 0xBEEF007F, 0x007F1234, 0xBEEF0080, 0xFFFF1234]), - # 8/16-bit LDS writes (incl. _d16_hi) and sign/zero-extending reads - ("cs_w32_lds_subdword", [0x11B2D444, 0xA1B2C3D4, 0xFFFFFFB2, 0x000000B2, 0x00000011, 0xFFFFA1B2, 0x0000A1B2, 0xFFFFC3D4]), - # 64/96/128-bit LDS accesses and ds_read2st64_b32 - ("cs_w32_lds_wide", [0xCAFEF00D, 0xFEEDFACE, 0x600DD00D, 0x00000000, 0x8BADF00D, 0xDEADC0DE, 0x12345678, 0x9ABCDEF0]), - # ds_cmpst_b32 and the b64 2-address forms (cs_lds_b64_cmpst.asm header) - ("cs_lds_b64_cmpst", [0x11110001, 0x22220002, 0x33330003, 0x44440004, - 0xCCCC000C, 0x44440004, 0xBBBB000B, 0x3579BADC]), - # ds_wrxchg*_rtn_b64, ds_or_rtn_b64, ds_min_f32, ds_max_rtn_f32 (cs_lds_xchg64_ext.asm header) - ("cs_lds_xchg64_ext", [0x11110003, 0x33333333, 0xF00FF000, 0x04030201, - 0x40302010, 0x70500705, 0x3FC00000, 0x80000000]), - # ds_mskor, ds_and/xor_b64, ds_add_rtn_f32, ds_inc/dec/rsub_u32 (cs_lds_atomics_ext.asm header) - ("cs_lds_atomics_ext", [0xF0F11234, 0xAB34CD78, 0x12345678, 0xF0F00F0F, - 0xA5A55A5A, 0x00AA00AA, 0x7FB00000, 0xFE090700]), - # constant EXEC: each lane takes its own bit (Intel got 16-bit constants wrong for lanes 16-31) - ("cs_exec_const", [16, 8, 2, 16, 0, 16]), - # a constant lane mask (saveexec, wrexec, s_and/s_not/s_mov_b64 into EXEC or VCC) gives lane L its bit L, - # not bit 0 for every lane; word = set lanes | lowest lane << 8 (derivations in each .asm header) - ("cs_w32_mask_imm", [2056, 20, 2, 6152, 2050, 4112, 258, 32]), - ("cs_w64_mask_imm", [2056, 1084, 828, 2052, 319, 2104, 516, 2064]), - # SHADER-99: -0 and NaN survive translation (SignedZeroInfNanPreserve); words 0, 2, 3 on Apple: see below - ("cs_signed_zero_nan", SIGNED_ZERO_NAN), - # s_andn2_saveexec_b32 / s_andn2_wrexec_b32: EXEC = S0 & ~EXEC, D old / new EXEC, SCC (cs_w32_andn2_exec.asm) - ("cs_w32_andn2_exec", [1, 8, 16, 2064, 2068, 3, 20, 1544]), - # SHADER-1264: a computed value written to exec_lo / exec_hi gives each lane its own bit, not the - # whole half for a non-zero value (cs_w32_exec_computed.asm / cs_w64_exec_computed.asm headers) - ("cs_w32_exec_computed", [259, 1028, 3088, 7682, 512, 4100, 0, 3]), - ("cs_w64_exec_computed", [291, 1028, 11264, 771, 8192, 4132, 0, 3]), - ("cs_wave64_ballot", [32, 16, 24, 40, 8, 48]), - ("cs_wm_half_ops", [32, 16, 16, 0, 16]), ("cs_wm_half_cmp", [1, 0, 1, 1]), - ("cs_wm_bfm64", [16, 8, 8, 40]), ("cs_wm_scc_rfl", [55, 48]), - # mask-only wave64: s_bcnt1_i32_b64 on ordinary SGPRs, no WAVE64_RE EXEC markers (#210 / SHADER-28) - ("cs_w64_mask_detect", [48]), - ("cs_wqm_w64", [20, 4, 12, 8, 1, 0, 15728895, 20]), ("cs_wqm_w32", [12, 1, 4, 0, 8, 15728880, 4, 32]), - ("cs_bpermute32", [0, 50, 162, 99, 36, 218, 183, 15]), - ("cs_w32_partial_scmp", [0, 1, 1, 0, 1, 1, 1, 1]), # a 20-thread wave32: s_cmp mask, -1 - # ds_permute_b32 in a 20-thread wave32: a source lane that was never launched sends nothing - ("cs_w32_partial_permute", [0, 29, 127, 0, 1, 0, 134, 113]), - # SHADER-88: v_sin/v_cos reduce the angle in turns (a regression guard, tolerance 1e-3) - ("cs_w32_sincos", [1, 1, 1, 1, 1, 1]), - # SHADER-74: v_permlane16/x16 with the source lane off in EXEC (FI / BOUND_CTRL) - ("cs_w32_permlane_fi", [1000, 0, 4, 1, 1000, 0, 52, 49]), - ("cs_wqm_w64_half", [11, 14, 0, 1, 6, 8, 12, 2]), - # SHADER-91: two s_barrier sites in wave-uniform branches meet like one barrier; wave 0 reads wave 3 - ("cs_barrier_divergent", [127, 126, 125, 124, 123, 122, 121, 120]), - # SHADER-91: waves that end without an s_barrier don't hold the barrier of the ones still running - ("cs_barrier_early_end", [127, 126, 125, 124, 123, 122, 121, 120]), - # SHADER-91: a barrier in a loop with a per-wave trip count; the k-th one waits for the waves still running - ("cs_barrier_loop", [128, 96, 64, 32, 128, 96, 64, 0xEEEEEEEE]), - # SHADER-21 part 2: a mask copied to a VGPR with v_mov_b32 respects EXEC (inactive lanes keep the old VGPR) - ("cs_mask_vgpr_exec", [0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, - 0xDEADBEEF, 0xDEADBEEF, 0xDEADBEEF, 0xDEADBEEF])] -# num_records bounds check (cs_bounds.asm): one thread, so no 64-wide subgroup requirement. -# The SMEM and raw MUBUF rules measured on an RX 6800 (derivations in each .asm header): one thread too. -# Never run cs_smem_sload_neg with a translator that zero-extends the s_load immediate: it reads 4 GiB past the heap. -BOUNDS = [("cs_bounds", [0x12345678, 0x12345678, 0x00000000, 0xEEEEEEEE]), - ("cs_smem_bounds", [0, 0x5eed0010, 0x5eed000c, 0, 0x5eed000c, 0x5eed0010, 0, 0]), - ("cs_smem_stride_align", [0x5eed0010, 0, 0, 0x5eed0000, 0x5eed0000, 0x5eed0000, 0x5eed0000, 0x5eed0004]), - # SHADER-328: a constant SGPR offset gives what the run-time one gives (no 32-bit wrap) - ("cs_smem_sconst_off", [0, 0x5eed0018, 0x5eed0018, 0x5eed0014]), - ("cs_smem_sload_neg", [0x5eed0004, 0x5eed0000, 0x5eed0004, 0x5eed0004, 0x5eed0008, 0x5eed000c, - 0xeeeeeeee, 0xeeeeeeee]), - ("cs_buf_tail", [0, 0x5eed000c, 0x5eed0008, 0x5eed000c, 0, 0, 0x5eed0010, 0]), - # V# OOB_SELECT 0..3 (literal and run-time V#s), the RDNA2 rules of docs/buffer_bounds.md, derived in the .asm header - ("cs_oob_select", [0x5eed000c, 0, 0x5eed0014, 0, 0x5eed0018, 0xeeeeeeee, 0, 0]), - # the end of an access decides (a start check, Mesa's GFX10 column, reads more); x4 loads and stores per dword, typed all or nothing - ("cs_oob_tail", [0, 0, 0x5eed0010, 0, 0xbeef0000, 0xeeeeeeee, 0, 0x5eed0010]), - # swizzled MUBUF addressing (measured natively on gfx1036) and ADD_TID_ENABLE on lanes 0 and 1, derived in the .asm header - ("cs_buf_swizzle", [0x5eed0024, 0x5eed0044, 0x5eed004c, 0x5eed0008, 0x5eed000c, 0, 0xbeef0000, 0xbeef0001])] -CMPX_CLASS_WORDS = [0xEEEEEEEE] * 3 + [0x22] + [0x11] * 4 -# cs_fmt_1010102.asm: descriptor loads, immediate-format load, raw input words and the two packed stores. -FMT_1010102_WORDS = [0, 0x3F800000, 0, 0x3F800000, 0x3F800000, 0, 0x3F800000, 0, - 0, 0x3F800000, 0, 0x3F800000, 0xC00FFC00, 0x003FF003, 0xE00003FF, 0xFFE00003] -# cs_fmt_int_narrow.asm: 8- and 16-bit UINT/SINT typed buffer loads and stores (layout in the .asm header). The -# words are the same program's output on gfx1036 run natively (tools/hw_oracle, wave32 and wave64 identical). -FMT_INT_NARROW_WORDS = [ - 0x00000080, 0x00000080, 0x00000080, 0x00000080, 0xFFFFFF80, 0xFFFFFF80, 0xFFFFFF80, 0xFFFFFF80, - 0x0000FF80, 0x0000FF80, 0x0000FF80, 0x0000FF80, 0xFFFFFF80, 0xFFFFFF80, 0xFFFFFF80, 0xFFFFFF80, - 0x00000080, 0x000000FF, 0x00000080, 0x000000FF, 0xFFFFFF80, 0xFFFFFFFF, 0xFFFFFF80, 0xFFFFFFFF, - 0xFFFFFF80, 0x00007F01, 0xFFFFFF80, 0x00007F01, 0xFFFFFF80, 0xFFFFFFFF, 0x00000001, 0x0000007F, - 0xFFFFFF80, 0x00007F01, 0xFFFFFFFF, 0xFFFF8000, 0xFFFFFF80, 0x00000000, 0x00000001, 0x00000001, - 0x0000FF80, 0x00000000, 0x00000001, 0x00000001, 0xFF80FF80, 0xFF80FF80, 0xFFFFFF80, 0x007F0001, - 0x7F01FF80, 0x8000FFFF, 0xEEEEEEEE, 0xEEEEEEEE, 0xEEEEEEEE, 0xEEEEEEEE, 0xEEEEEEEE, 0xEEEEEEEE, - 0xEEEEEEEE, 0xEEEEEEEE, 0xEEEEEEEE, 0xEEEEEEEE, 0xEEEEEEEE, 0xEEEEEEEE, 0xEEEEEEEE, 0xEEEEEEEE, - 0xEEEEEE7F, 0xEEEEEEEE, 0xEEEEEE7F, 0xEEEEEEEE, 0xEEEE7FFF, 0xEEEEEEEE, 0xEEEE7FFF, 0xEEEEEEEE, - 0xEEEE807F, 0xEEEEEEEE, 0xEEEE7F7F, 0xEEEEEEEE, 0x7FFF7FFF, 0xEEEEEEEE, 0x80807F7F, 0xEEEEEEEE, - 0x7FFF7FFF, 0x80008000, 0xEEEEEEEE, 0xEEEEEEEE, 0xEEEEEEEE, 0xEEEEEEEE, 0xEEEEEEEE, 0xEEEEEEEE, - 0xEEEEEEEE, 0xEEEEEEEE, 0xEEEEEEEE, 0xEEEEEEEE, 0xEEEEEEEE, 0xEEEEEEEE, 0xEEEEEEEE, 0xEEEEEEEE, - 0xEEEEEEEE, 0xEEEEEEEE, 0xEEEEEEEE, 0xEEEEEEEE, 0xEEEEEEEE, 0xEEEEEEEE, 0xEEEEEEEE, 0xEEEEEEEE, - 0xEEEEEEEE, 0xEEEEEEEE, 0xEEEEEEEE, 0xEEEEEEEE, 0xEEEEEEEE, 0xEEEEEEEE, 0xEEEEEEEE, 0xEEEEEEEE, - 0xEEEEEEEE, 0xEEEEEEEE, 0xEEEEEEEE, 0xEEEEEEEE, 0xEEEEEEEE, 0xEEEEEEEE, 0xEEEEEEEE, 0xEEEEEEEE, - 0xEEEEEEEE, 0xEEEEEEEE, 0xEEEEEEEE, 0xEEEEEEEE, 0xEEEEEEEE, 0xEEEEEEEE, 0xEEEEEEEE, 0xEEEEEEEE, - 0x7F01FF80, 0x8000FFFF, 0x12345678, 0x9ABCDEF0, 0xEEEEEEEE, 0xEEEEEEEE, 0xEEEEEEEE, 0xEEEEEEEE, -] -# cs_fmt_sint32.asm: hand-derived full-width and D16 load results, inputs, stores, and untouched words. -FMT_SINT32_WORDS = [ - 0x80000000, 0x7FFFFFFF, 0x80000000, 1, - 0x80000000, 0x7FFFFFFF, 0xFFFFFFFD, 0x80000000, - 0x80000000, 0x7FFFFFFF, 0xFFFFFFFD, 17, - 0x80000000, 0x7FFFFFFF, 0, 0, - 0x80000000, 0x7FFFFFFF, 0xFFFFFFFD, 0, - 0x80000000, 0x7FFFFFFF, 0xFFFFFFFD, 17, - 0x7FFF8000, 0x0011FFFD, 0x7FFF8000, 0x0011FFFD, - 0xFFFFFFFD, 0xFFFFFFFD, 0xEEEEEEEE, 0xEEEEEEEE, - 0x80000000, 0x7FFFFFFF, 0xFFFFFFFD, 17, - 0x80000000, 0x7FFFFFFF, 0xEEEEEEEE, 0xEEEEEEEE, - 0x80000000, 0x7FFFFFFF, 0xFFFFFFFD, 0xEEEEEEEE, - 0x80000000, 0x7FFFFFFF, 0xFFFFFFFD, 17, - 0xFFFFFFFD, 0xFFFF8000, 0xFFFFFFFD, *[0xEEEEEEEE] * 13, -] -# cs_fmt_all.asm: 32 typed loads of the SCALED, SINT, small-float and 10:10:10:2 formats (29 through a V# FORMAT, 3 through -# tbuffer's own), their 16-byte inputs, and 20 typed stores; the words are tools/buffer_format_fuzz.py's MODEL, which the -# Radeon 880M (gfx1150) and a real RDNA2 (gfx1036, @AwkGrep256, #2022) reproduced for every format here. Layout and rules in -# the .asm header. -FMT_ALL_WORDS = [ - 0x000000ff, 0x000000ff, 0x000000ff, 0x000000ff, 0xffffff80, 0xffffff80, 0xffffff80, 0xffffff80, 0x43480000, - 0x43480000, 0x43480000, 0x43480000, 0xc2c80000, 0xc2c80000, 0xc2c80000, 0xc2c80000, 0xffff8000, 0xffff8000, - 0xffff8000, 0xffff8000, 0x476a6000, 0x476a6000, 0x476a6000, 0x476a6000, 0xc47a0000, 0xc47a0000, 0xc47a0000, - 0xc47a0000, 0x0000007f, 0xffffff80, 0x0000007f, 0xffffff80, 0x3f800000, 0x437f0000, 0x3f800000, 0x437f0000, - 0x00000001, 0xffffffff, 0xffffff80, 0x0000007f, 0x00000000, 0x3f800000, 0x43000000, 0x437f0000, 0x00000000, - 0x3f800000, 0xc3000000, 0xbf800000, 0x00007fff, 0xffff8000, 0x00007fff, 0xffff8000, 0x3f800000, 0x477fff00, - 0x3f800000, 0x477fff00, 0xc7000000, 0x46fffe00, 0x3f800000, 0xbf800000, 0x3f800000, 0x40000000, 0x3f000000, - 0x3f800000, 0x7f800000, 0x7f820000, 0x36000000, 0x7f800000, 0x477e0000, 0x387c0000, 0x7ffc0000, 0x477e0000, - 0x3f800000, 0x40000000, 0x477e0000, 0x3f800000, 0x3f800000, 0xbf800000, 0x3f800000, 0xbf800000, 0xfffffffe, - 0xfffffe00, 0x000001ff, 0xffffffff, 0xbf800000, 0x3f800000, 0xbf800000, 0x3f800000, 0x447fc000, 0x00000000, - 0x44000000, 0x40400000, 0xc4000000, 0x43ff8000, 0xbf800000, 0xc0000000, 0xfffffe00, 0x000001ff, 0xffffffff, - 0xfffffffe, 0x3f800000, 0x40c00000, 0x7ffe0000, 0x00000000, 0x00000001, 0xffffffff, 0xffffff80, 0x0000007f, - 0x00007fff, 0xffff8000, 0x00000000, 0x00000000, 0x00000000, 0x3f800000, 0x3f800000, 0x00000000, 0xbf800000, - 0x3f800000, 0xbf800000, 0xbf800000, 0x000007ff, 0x00000001, 0x000003ff, 0x000007ff, 0xffffffff, 0xfffffc00, - 0xffffffff, 0xffffffff, 0x000000ff, 0x00000000, 0x00000000, 0x00000000, 0x00000080, 0x00000000, 0x00000000, - 0x00000000, 0x000000c8, 0x00000000, 0x00000000, 0x00000000, 0x0000009c, 0x00000000, 0x00000000, 0x00000000, - 0x00008000, 0x00000000, 0x00000000, 0x00000000, 0x0000ea60, 0x00000000, 0x00000000, 0x00000000, 0x0000fc18, - 0x00000000, 0x00000000, 0x00000000, 0x0000807f, 0x00000000, 0x00000000, 0x00000000, 0x0000ff01, 0x00000000, - 0x00000000, 0x00000000, 0x7f80ff01, 0x00000000, 0x00000000, 0x00000000, 0xff800100, 0x00000000, 0x00000000, - 0x00000000, 0xff800100, 0x00000000, 0x00000000, 0x00000000, 0x80007fff, 0x00000000, 0x00000000, 0x00000000, - 0xffff0001, 0x00000000, 0x00000000, 0x00000000, 0x7fff8000, 0xffff0001, 0x00000000, 0x00000000, 0x702003c0, - 0x00000000, 0x00000000, 0x00000000, 0x007e0fc0, 0x00000000, 0x00000000, 0x00000000, 0xffc1ffbf, 0x00000000, - 0x00000000, 0x00000000, 0xf7f001e0, 0x00000000, 0x00000000, 0x00000000, 0x805ff801, 0x00000000, 0x00000000, - 0x00000000, 0xffdff802, 0x00000000, 0x00000000, 0x00000000, 0x6017fe00, 0x00000000, 0x00000000, 0x00000000, - 0xe00003ff, 0x00000000, 0x00000000, 0x00000000, 0xbff7fe00, 0x00000000, 0x00000000, 0x00000000, 0xbff7fe00, - 0x00000000, 0x00000000, 0x00000000, 0xfff181e0, 0x00000000, 0x00000000, 0x00000000, 0x7f80ff01, 0x00000000, - 0x00000000, 0x00000000, 0x80007fff, 0x00000000, 0x00000000, 0x00000000, 0xfffff800, 0x00000000, 0x00000000, - 0x00000000, 0x800ffe00, 0x00000000, 0x00000000, 0x00000000, 0xffc00fff, 0x00000000, 0x00000000, 0x00000000, - 0xfff003ff, 0x00000000, 0x00000000, 0x00000000, 0xeeeeee7f, 0xeeeeeeee, 0xeeeeeeee, 0xeeeeeeee, 0xeeeeee80, - 0xeeeeeeee, 0xeeeeeeee, 0xeeeeeeee, 0xeeeeeeff, 0xeeeeeeee, 0xeeeeeeee, 0xeeeeeeee, 0xeeeeeeff, 0xeeeeeeee, - 0xeeeeeeee, 0xeeeeeeee, 0xeeee7fff, 0xeeeeeeee, 0xeeeeeeee, 0xeeeeeeee, 0x80007fff, 0xeeeeeeee, 0xeeeeeeee, - 0xeeeeeeee, 0xeeeebfff, 0xeeeeeeee, 0xeeeeeeee, 0xeeeeeeee, 0x7fd00401, 0xeeeeeeee, 0xeeeeeeee, 0xeeeeeeee, - 0xffe017ff, 0xeeeeeeee, 0xeeeeeeee, 0xeeeeeeee, 0x37ff7bff, 0x80007c01, 0xeeeeeeee, 0xeeeeeeee, 0x00004ccd, - 0xeeeeeeee, 0xeeeeeeee, 0xeeeeeeee, 0xc040817f, 0xeeeeeeee, 0xeeeeeeee, 0xeeeeeeee, 0x702003c0, 0xeeeeeeee, - 0xeeeeeeee, 0xeeeeeeee, 0xf7fe0000, 0xeeeeeeee, 0xeeeeeeee, 0xeeeeeeee, 0xf83efde0, 0xeeeeeeee, 0xeeeeeeee, - 0xeeeeeeee, 0x265ff805, 0xeeeeeeee, 0xeeeeeeee, 0xeeeeeeee, 0xd00803ff, 0xeeeeeeee, 0xeeeeeeee, 0xeeeeeeee, - 0x405801ff, 0xeeeeeeee, 0xeeeeeeee, 0xeeeeeeee, 0x027ff017, 0xeeeeeeee, 0xeeeeeeee, 0xeeeeeeee, 0x7fff8000, - 0xffff7fff, 0xeeeeeeee, 0xeeeeeeee, -] -# cs_fmt_xy_xyz.asm (TEST-185): 12 xy/xyz loads, then the 9 store regions read back, as a Radeon 680M (gfx1035) gives -# them natively, with the updated UINT saturation case checked on gfx1036. Layout and rules in the .asm header. -FMT_XY_XYZ_WORDS = [ - 0x3F800000, 0x40000000, 0x5A5A0008, 0x5A5A000C, 0x3F800000, 0x40000000, 0x40400000, 0x5A5A001C, - 0x3F800000, 0x40000000, 0x5A5A0028, 0x5A5A002C, 0x3F800000, 0x40000000, 0x40400000, 0x5A5A003C, - 0x3F800000, 0x40000000, 0x3F800000, 0x5A5A004C, 0x3F800000, 0x3F800000, 0x5A5A0058, 0x5A5A005C, - 0x3F800000, 0x40000000, 0x5A5A0068, 0x5A5A006C, 0x3F800000, 0x40000000, 0x40400000, 0x5A5A007C, - 0x00000000, 0x00000000, 0x5A5A0088, 0x5A5A008C, 0x00000000, 0x00000000, 0x00000000, 0x5A5A009C, - 0x3F800000, 0x40000000, 0x5A5A00A8, 0x5A5A00AC, 0x00000000, 0x00000000, 0x00000000, 0x5A5A00BC, - 0x3F800000, 0x40000000, 0x00000000, 0x00000000, 0x3F800000, 0x40000000, 0x40400000, 0x00000000, - 0x40003C00, 0x00000000, 0xA5A50268, 0xA5A5026C, 0x40003C00, 0x00004200, 0xA5A50278, 0xA5A5027C, - 0x3F800000, 0xA5A50284, 0xA5A50288, 0xA5A5028C, 0x0000FFFF, 0xA5A50294, 0xA5A50298, 0xA5A5029C, - 0x0003FF01, 0xA5A502A4, 0xA5A502A8, 0xA5A502AC, 0xA5A502B0, 0xA5A502B4, 0xA5A502B8, 0xA5A502BC, - 0xA5A502C0, 0xA5A502C4, 0xA5A502C8, 0xA5A502CC] -# cs_tbuffer_store.asm: 13 tbuffer_store_format_* regions read back, as a Radeon 680M (gfx1035) gives them -# natively. Layout and rules in the .asm header. -TBUFFER_STORE_WORDS = [ - 0x3F800000, 0x40000000, 0x40400000, 0x40800000, 0x40003C00, 0x00000000, 0xA5A50218, 0xA5A5021C, - 0x00030201, 0xA5A50224, 0xA5A50228, 0xA5A5022C, 0xA5A5FF30, 0xA5A50234, 0xA5A50238, 0xA5A5023C, - 0x40000240, 0xA5A50244, 0xA5A50248, 0xA5A5024C, 0xD00003FF, 0xA5A50254, 0xA5A50258, 0xA5A5025C, - 0x3F800000, 0x40000000, 0xA5A50268, 0xA5A5026C, 0x40003C00, 0xA5A50274, 0xA5A50278, 0xA5A5027C, - 0xFF0080FF, 0xA5A50284, 0xA5A50288, 0xA5A5028C, 0xA5A50290, 0xA5A50294, 0xA5A50298, 0xA5A5029C, - 0xA5A502FF, 0xA5A502A4, 0xA5A502A8, 0xA5A502AC, 0x3F800000, 0xA5A502B4, 0xA5A502B8, 0xA5A502BC, - 0xA5A502C0, 0xA5A502C4, 0xA5A502C8, 0xA5A502CC] -# cs_fmt_d16_xyz.asm: d16_xyz / d16_xy typed-buffer loads (out[0..10]), the two d16_xyz stores (out[16..18] and -# out[20..22]) and the inputs at 0x100 (out[64..72]); everything else is the untouched fill. Derivation in the header. -FMT_D16_XYZ_WORDS = [ - 0xABCD1234, 0xA5A57FFF, 0xFFFF0005, 0x1234FFFF, 0xC0003C00, 0xC0003C00, 0xBEEF3555, 0x00003C00, - 0xCAFE3C00, 0xFFFF0005, 0x0BADFFFF, *[0xEEEEEEEE] * 5, - 0x00000007, 0x00008001, 0x0000FFFE, 0xEEEEEEEE, 0x3F800000, 0xC0000000, 0x3F000000, 0xEEEEEEEE, - *[0xEEEEEEEE] * 40, - 0xABCD1234, 0x55557FFF, 0xC0003C00, 0x7BFF3555, 5, 0x10000, 0xFFFFFFFF, 0, 0x80FF00FF, *[0xEEEEEEEE] * 7] -# Negative global_load/global_store offsets (cs_global_neg_offset.asm): 40 groups make a 0x2800-byte heap that holds -# both the right addresses and the 4096-lower ones; only group 0 thread 0 runs, so no wave64 requirement. -GLOBAL_OFFSET = [("cs_global_neg_offset", "40", [0x5EED1FFC, 0x8BAD1800, 0x5EED1FF0, 0x5EED1FF4, - 0x0000009E, 0xFFFF8BAD, 0x57023FFC, 0xEEEEEEEE]), - # global/buffer atomics, 8/16-bit global stores and d16 loads with CPU-only checks until now - ("cs_global_mem_ext", "40", [0x5, 0xC, 0x977, 0xFFF00000, 0xEDCB5678, 0xEF332211, 0x887766BE, 0xFF801234])] -# cs_heap_init.asm: vk_compute_test's VKC_HEAP_INIT copies this file (zeros, then four words at 0x100) to the start -# of the heap; the shader copies the four words to 0, and out[4..7] are the file's zeros, not the 0xEE fill. -HEAP_INIT_WORDS = [0x1BADB002, 0xCAFEF00D, 0x80000001, 0x0000FFFF] -HEAP_INIT_FILE = bytes(0x100) + struct.pack("<4I", *HEAP_INIT_WORDS) -HEAP_INIT_EXPECTED = HEAP_INIT_WORDS + [0] * 4 - - -def heap_init_env(): - """vk_compute_test's environment for cs_heap_init: the init file (written to the temp folder) and a buffer big - enough to hold it (68 words for its 0x110 bytes; one group's default is 64).""" - path = os.path.join(tempfile.gettempdir(), "leonida_cs_heap_init.bin") - with open(path, "wb") as f: - f.write(HEAP_INIT_FILE) - return {"VKC_HEAP_INIT": path, "VKC_OUT_WORDS": str(len(HEAP_INIT_FILE) // 4)} - - -# cs_user_sgprs.asm: vk_compute_test puts these words in s4..s7 and the shader stores them back. -USER_SGPRS = [0x4F000000, 0xDEADBEEF, 7, 0xFFFFFFFF] -USER_SGPRS_ENV = {"VKC_SGPRS": ",".join(hex(w) for w in USER_SGPRS)} -USER_SGPRS_WORDS = USER_SGPRS + [0xEEEEEEEE] * 4 -# cs_fma_fused.asm: single-rounded f32 multiply-adds (and one f16). The operands arrive in s4..s7 so no driver can fold -# them; FMA_FUSED are the exact single-rounded words and FMA_SPLIT are the exact split-rounded words (derivations in -# the .asm header; out[7] is f16 round-to-odd, never GLSL Fma, so it is always 0x7351). Under --fma khr -# (LEONIDA_FMA=khr, shaderFmaFloat32 in index.json) every word must match FMA_FUSED; under default --fma glsl a -# spec-compliant driver (e.g. Mesa RADV 26.2.6) may legally split GLSL.std.450 Fma. -FMA_FUSED_ENV = {"VKC_SGPRS": "0x3f800800,0x3f800001,0x3f7ffffe,0xbf800002"} -FMA_FUSED = [0x33800000, 0xa8800000, 0x3a000400, 0x33800000, 0x33800000, 0x33800000, 0x28800000, 0x00007351] -FMA_SPLIT = [0x00000000, 0x00000000, 0x3a000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00007351] -# cs_cvt_f32_sat.asm (#300): s4 is a binary32 input, out[0] = v_cvt_u32_f32, out[1] = v_cvt_i32_f32 (truncate, -# saturate, NaN -> 0). One dispatch per input through VKC_SGPRS; the inputs of tests/semantic/test_float_to_int.py. -CVT_F32_SAT_CASES = ( - (0x00000000, 0, 0), (0x80000000, 0, 0), (0x00000001, 0, 0), (0x3FC00000, 1, 1), (0xBFC00000, 0, 0xFFFFFFFF), - (0x4EFFFFFF, 0x7FFFFF80, 0x7FFFFF80), (0x4F000000, 0x80000000, 0x7FFFFFFF), (0x4F7FFFFF, 0xFFFFFF00, 0x7FFFFFFF), - (0x4F800000, 0xFFFFFFFF, 0x7FFFFFFF), (0xCEFFFFFF, 0, 0x80000080), (0xCF000000, 0, 0x80000000), - (0xCF000001, 0, 0x80000000), (0x7F800000, 0xFFFFFFFF, 0x7FFFFFFF), (0xFF800000, 0, 0x80000000), - (0x7F800001, 0, 0), (0xFFC00000, 0, 0)) -# v_cvt_pk_u8_f32 (cs_cvt_pk_u8.asm), measured natively on RDNA2 (gfx1036): halves round to even, NaN gives 0. -CVT_PK_U8_WORDS = [0x1122330C, 0x11220E44, 0x11003344, 0xFE223344, 0x1122330D, 0x11220044, 0x11FF3344, 0x00223344] -# v_pk_mul_lo_u16 with a constant operand (cs_pk_mul_lo_const.asm), measured natively on RDNA2 (gfx1036); lanes 0 and 1. -PK_MUL_LO_WORDS = [0x00009E88, 0x03675433, 0x00230000, 0x00077F6C] * 2 -# Wave64-only dump tests (mostly the x = cross-half checks): exact results need 64 lanes, or an emulation of them -# on narrower subgroups. cs_dpp_w64 is not cross-half, but its lane id needs both halves. -W64_EMULATED = os.environ.get("LEONIDA_W64_EMULATE") == "1" -# LEONIDA_BARY_FALLBACK=1/0 overrides the device probe for raw barycentrics. Unset, Mesa ANV selects the fallback. -BARY_FALLBACK = barycentric_fallback() -# LEONIDA_F16_INTERP_FALLBACK=1 (as build.py reads it): *_f16 interps were translated from decoded-half inputs, with no -# PerVertexKHR inputs at all, so the translator refuses a computed I/J pair (ps_ij_computed) there. -F16_HALVES = os.environ.get("LEONIDA_F16_INTERP_FALLBACK") == "1" -W64X_DUMPS = [("cs_dpp_w64", [1, 0, 3, 2, 5, 4, 7, 6]), - ("cs_w64x_readlane", [121, 121, 16, 97, 16, 100, 100, 121]), - ("cs_w64x_writelane", [4660, 77, 99, 2748, 0, 0, 4660, 99]), - ("cs_w64x_readfirstlane", [140, 140, 163, 132, 100, 105, 133, 48]), - ("cs_w64x_bpermute", [36, 316, 253, 218, 435, 225, 0, 442]), - # SHADER-90: ds_permute_b32 on each wave32 half; unwritten lane 0, EXEC gates the destination - ("cs_w64x_permute", [218, 442, 435, 239, 0, 99, 239, 232]), - ("cs_w64x_branch", [0, 0, 0, 0, 5, 5, 9, 9]), - ("cs_w64x_mask_reuse", [8, 40, 8, 40, 2, 20, 10, 64]), - ("cs_w64x_mask_reuse2", [10, 20, 8, 8, 5, 2, 132, 131]), - ("cs_w64x_chain_barrier", [564, 563, 500, 627]), # 128-thread group - ("cs_w64x_ballot", [2053, 2061, 2069, 2077, 2085, 2093, 2101, 2109]), - ("cs_w64x_wg128_branches", [121, 121, 343, 343, 14, 31, 19812, 22728]), # 128-thread group - ("cs_w64x_lds_raw", [132, 137, 100, 108, 131, 101, 149, 118]), - ("cs_w64x_lds_war", [1032, 1063, 1000, 1031, 2032, 2063, 2000, 2031]), - ("cs_w64x_sbarrier", [605, 605, 686, 686, 3032, 3013, 3032, 3031]), # 128-thread group - ("cs_w64x_load_ballot_load", [43, 74, 75, 42, 42, 18, 41, 32]), - # s_andn2_saveexec_b64 / s_andn2_wrexec_b64: EXEC = S0 & ~EXEC over both halves, D old / new EXEC, SCC - ("cs_w64x_andn2_exec", [1, 16, 32, 4144, 2052, 3, 8, 1544]), - # s_and/s_or_saveexec_b64 (VCC and SGPR-pair sources), s_andn2_saveexec/wrexec_b64 (SGPR pair): D, EXEC, SCC - ("cs_w64x_saveexec_b64", [6160, 12304, 5120, 2088, 6168, 8192, 7176, 1837171])] -# A 40-thread group (one partial wave) cannot use --require-wave64 (full subgroups), so it asks for subgroup size 64. -W64X_PARTIAL = [("cs_w64x_partial", [40, 40, 528, 0, 0, 532, 539, 524820]), - ("cs_w64x_partial_scmp", [0, 1, 0, 1, 1, 1, 1, 0])] -PIXEL_BITS = {"ps_clip_color": (0x3e800000, 0x3f000000, 0x3f400000, 0x3f800000), - # exp mrt0 done (no vm) with every lane on, EXEC off afterwards: written (.asm header, measured on gfx1036) - "ps_exp_color_mask": (0x40000000, 0x40800000, 0x40000000, 0x40800000), - "ps_legacy_mul": (0, 0, 0, 0x40c00000), - "ps_mul_legacy_denorm": (0, 0, 0, 0x80000000), - "ps_mul_legacy_denorm_mods": (0, 0, 0, 0x40400000), - "ps_ops": (0x48804300, 5, 7, 0xbffffffc), "ps_ops2": (0xabcd4400, 0x46001234, 0xbffffffa, 7), - "ps_ops3": (0xbffffffa, 0x44660066, 0x44aabbcc, 16), "ps_ops4": (0x34000010, 0x00120800, 0xbeef0000, 0x12343c00), - "ps_ops5": (0x12340010, 0xbeef0800, 0xaaaaffff, 0xdeadbc00), - "ps_ops6": (0xf800ffff, 0x01000010, 0x00800800, 0x8000fff0), - "ps_ops7": (0x00ff8077, 0xff0000ff, 0x89abcdef, 0x00070003), - "ps_ops8": (0x80000000, 0xbfffffff, 0x000f100e, 0x0f0f0f1f), - "ps_f32_mods": (0xc0256a01, 0x3f800000, 0x41e00000, 0x3fc00000), - "ps_scc": (1, 1, 3, 0x80000000), "ps_sdwa": (0x000000f1, 0xbffefff2, 0x3c003344, 0xbff70000), - # 16-bit SDWA results with dst_sel:DWORD zero the high half (.asm header, measured on gfx1036) - "ps_sdwa_dword_hi": (0x00004000, 0x00000003, 0x00004700, 0x0000c000), - "ps_vcc_x2": (0x11223344, 0x55667788, 0, 0), - # v_cmpx_{eq,gt,le,lt,ngt,nle}_f32, f_i32, t_u32, {eq,gt,le}_i64, {ge,lt,ne}_u64 (.asm header) - "ps_vcmpx_forms": (0xf05b2a48, 0xf05e8a12, 0xb174be18, 0x15550000), - # v_cmp_{eq,ne,lt,le,gt,ge,f,t}_{u32,i32}, e32 and e64, constants and literals (.asm header) - "ps_vcmp_int32": (0x963e52e8, 0x984dcee8, 0xb9458ee8, 0xb73612e8), - "ps_med3_mods": (0x3f800000, 0x40400000, 0x40c00000, 0x3f400000), - "ps_scc_minmax": (0x00030205, 0x00030207, 0x00030209, 0x00030203), - "ps_scc_logic32": (0x0fff0fff, 0x000f000f, 0xf00ff00f, 0x36), - "ps_scc_logic64": (0x0fff0fff, 0xff000000, 0xff0000ff, 0x16), - "ps_fma_literal": (0x41b80000, 0x41800000, 0x40e00000, 0x41a40000), - "ps_f64_mods": (0x40040000, 0x3ff00000, 0x3fe40000, 0x3ff00000), - "ps_f64_round": (0xc12af665, 0x3fe7ffff, 0xbfffffff, 0xc12af666), - "ps_outmods_f16": (0xaaaa3c00, 0xaaaa3e00, 0x7c000000, 0x3c000000), - # f16 op_sel, partial writes, inline constants: words measured on RDNA2 hardware (.asm headers) - "ps_f16_med3_opsel": (0xaaaa4100, 0xaaaa4200, 0xaaaa3e00, 0x40005555), - "ps_f16_med3_mods": (0x41005555, 0x3c005555, 0x41003800, 0xaaaaba00), - "ps_f16_vop2": (0xaaaa4000, 0xaaaac000, 0xaaaa3a00, 0x42003f00), - "ps_f16_vop2b": (0xaaaa3e00, 0xaaaab800, 0xaaaa3c00, 0x42003400), - "ps_f16_vop1": (0xaaaa4000, 0xaaaabc00, 0xaaaac000, 0xaaaa8000), - "ps_f16_vop1b": (0xaaaa3400, 0xaaaa4000, 0xaaaab400, 0xaaaa3800), - "ps_f16_const": (0xaaaa3d00, 0x38005555, 0xaaaa3800, 0x3f000000), - "ps_f16_const2": (0x42003d00, 0x3d004200, 0xaaaabc00, 3), - "ps_f16_pack": (0x34003c00, 0x38003400, 0x34000000, 0x44004200), - # v_pack_b32_f16 neg/abs on the selected half: a sign flip / clear before packing (SHADER-260) - "ps_f16_pack_mods": (0x4400b400, 0xc4003400, 0x4400c200, 0xb400b400), - # SDWA src_sel on a float inline constant in an f16 op (measured on gfx1036) - "ps_sdwa_f16_const": (0xaaaa3800, 0xaaaa1c00, 0xaaaa3e00, 0xaaaa73f0), - "ps_sff_imm": (2, 1, 20, 16), - "ps_fnan_med3": (0x40a00000, 0xc0200000, 0xc0200000, 0x40600000), - "ps_fnan_fract": (0x3f7fffff, 0x00003bff, 0xc0200000, 0xc0200000), - # v_med3 with a NaN in S2 or in two operands, by the same measured rule (derivations in the .asm headers) - "ps_fnan_med3_s2": (0x40a00000, 0x40a00000, 0xc0200000, 0x40e00000), - "ps_f16_fnan_med3": (0xaaaa4500, 0xaaaa4500, 0xaaaac100, 0xaaaa4700), - # TEST-175: docs/design.md rules that were checked on the CPU only (derivations in the .asm headers) - "ps_cmp_nlg": (0x40000037, 0x40000007, 0x40000001, 0x3f800000), - # far branches: s_getpc/s_add|s_sub/s_addc|s_subb/s_setpc forward, backward loops, conditional (.asm header) - "ps_far_branch": (0x00000007, 0x00000013, 0x00000051, 0x0000000b), - # 16-bit float v_cmp, all 16 predicates, e32 and e64 with swapped operands (.asm headers) - "ps_vcmp_f16": (0x48a12080, 0x4ce9b1a2, 0x4ba72c98, 0x4fefbdba), - "ps_vcmp_f16_e64": (0x44c11100, 0x4cf171c1, 0x47c71d18, 0x4ff77dd9), - # 16-bit float v_cmpx, all 16 predicates, EXEC result with VCC kept (.asm headers) - "ps_vcmpx_f16": (0x68a12080, 0x6ce9b1a2, 0x6ba72c98, 0x6fefbdba), - "ps_vcmpx_f16_e64": (0x64c11100, 0x6cf171c1, 0x67c71d18, 0x6ff77dd9), - "ps_cvt_off": (0xbf000000, 0x3ee00000, 0xbe800000, 0x3f800000), - "ps_fmac_f16_mods": (0xaaaa3c00, 0xaaaa3a00, 0xaaaa0000, 0xaaaa4400), - "ps_vop3_const_mods": (0xc0000000, 0xbf800000, 0x3f800000, 0xaaaabc00), - "ps_cndmask_sign_mods": (0xff800001, 0x7f800001, 0x80000001, 0x7f800001), - "ps_interp_f32_mods": (0x3f800000, 0x00000000, 0x3f400000, 0x3f800000), - "ps_interp_mov_mods": (0x3f800000, 0x3fc00000, 0x40000000, 0x3f400000), - # v_mad_u32_u16 / v_mad_i32_i16 and v_subrev_f16, which had CPU checks only (derivations in the .asm headers) - "ps_valu16_mad": (0x00000002, 0x00030002, 0x00008000, 0x00000004), - # op_sel on S2 / D and clamp, measured on gfx1036 (EGEN-HW-MAD-U32-U16) - "ps_valu16_mad_sel": (0x00008003, 0xdb880000, 0xffffffff, 0x80000000), - "ps_valu16_subrev": (0xaaaabc00, 0xaaaac000, 0xaaaa3c00, 0x42003800), - # f32 VOPC ordered/unordered with a NaN, 64-bit integer VOPC (derivations in the .asm headers) - "ps_vcmp_f32_nan": (0x0000376c, 0x0000fd5b, 0x0000d36c, 0x00000fe7), - "ps_vcmp_64": (0x0000b3c4, 0x000091e6, 0x00006787, 0x00007c93), - # 32-bit integer VALU ops on the VINT_ENV heap: 24-bit sign extension, shifts of 32+, signed vs unsigned - # min/max (derivations in the .asm headers) - "ps_vint_logic3": (0xfffffffe, 0xbbb05070, 0x1d3b5977, 0x123f5f7e), - "ps_vint_bits": (0xfffffffe, 0x40000000, 0x1e6a2c48, 0x000001d5), - "ps_vint_mul24": (0x13345678, 0xfffffffd, 0x00007fff, 0x0000ffff), - "ps_vint_minmax": (0x7ffffffe, 0x80000001, 0x80000001, 0x7ffffffe), - "ps_vint_minmax3": (0xf0f0f0f0, 0xab800000, 0xf0f0f0f0, 0xab800000), - # v_readlane_b32 across both halves of a wave64 (the .asm header derives the words) - "ps_w64x_readlane": (0x40000079, 0x40000010, 0x40000064, 0x400000be)} -# Pixel shaders that are exact only when the pixel stage really ran 64 lanes wide. vk_harness says so when it chained -# a required subgroup size onto the fragment stage ("fragment subgroup size: N", the whole line; a device that could -# not take the size gets "fragment subgroup size: N not available" or no line). A device that cannot -# require 64 there (NVIDIA: 32 only; llvmpipe: 8) has no frame to judge: the test is skipped, not failed. -WIDE_PIXEL_TESTS = {"ps_w64x_readlane": 64} -# h0..h7 of the ps_vint_* fixtures: 24-bit fields with bit 23 set and garbage above, 33 (a shift of 32+), a -# negative i32 that is a large u32, and plain bit patterns. -VINT_ENV = {"VKH_SGPRS": "0x1000,0,32,0", - "VKH_HEAP": "0x1000=0xab800000,0x1004=0x12fffffe,0x1008=0x00000021,0x100c=0x80000001," - "0x1010=0x7ffffffe,0x1014=0xf0f0f0f0,0x1018=0x12345678,0x101c=0xffffffff"} -# Pixel shaders that read memory: vk_harness puts this V# in s[0:3] and seeds the heap it points at, as -# tests/semantic/test_value_semantics.py does for the interpreter. -PIXEL_ENV = {"ps_vcc_x2": {"VKH_SGPRS": "0x1000,0,16,0", "VKH_HEAP": "0x1000=0x11223344,0x1004=0x55667788"}, - # the 14 v_cmpx forms: f32 and 64-bit operands from memory (derivations in the .asm header) - "ps_vcmpx_forms": {"VKH_SGPRS": "0x1000,0,96,0", - "VKH_HEAP": "0x1000=0x7fc10001,0x1004=0x3f800000,0x1008=0x40000000,0x100c=0x80000000," - "0x1010=0,0x1014=0xff800000,0x1018=0,0x101c=0,0x1020=0x80000000,0x1024=0," - "0x1028=0x1,0x102c=0,0x1030=0x7,0x1034=0x80000000,0x1038=0x7,0x103c=0," - "0x1040=0x1,0x1044=0x5,0x1048=0x80000000,0x104c=0x5,0x1050=0x7,0x1054=0x5," - "0x1058=0x7,0x105c=0x5"}, - # 32-bit integer compares: operands from memory (derivations in the .asm header) - "ps_vcmp_int32": {"VKH_SGPRS": "0x1000,0,32,0", - "VKH_HEAP": "0x1000=0x1,0x1004=0,0x1008=0x80000000,0x100c=0x12345678,0x1010=0x3," - "0x1014=0x5,0x1018=0,0x101c=0"}, - # float NaN / fract rows measured on RDNA2 hardware (see the .asm headers) - "ps_fnan_med3": {"VKH_SGPRS": "0x1000,0,32,0", - "VKH_HEAP": "0x1000=0x7fc10001,0x1004=0x40e00000,0x1008=0x40a00000," - "0x100c=0x7fc10001,0x1010=0x40600000,0x1014=0xc0200000"}, - "ps_fnan_fract": {"VKH_SGPRS": "0x1000,0,16,0", - "VKH_HEAP": "0x1000=0xaedbe6ff,0x1004=0x00008800,0x1008=0x7fc10001,0x100c=0xc0200000"}, - "ps_fnan_med3_s2": {"VKH_SGPRS": "0x1000,0,16,0", - "VKH_HEAP": "0x1000=0x40a00000,0x1004=0x40e00000,0x1008=0x7fc10001,0x100c=0xc0200000"}, - "ps_f16_fnan_med3": {"VKH_SGPRS": "0x1000,0,16,0", - "VKH_HEAP": "0x1000=0x00004500,0x1004=0x00004700,0x1008=0x00007e01,0x100c=0x0000c100"}, - # f32 VOPC with a NaN, 64-bit integer VOPC: inputs from memory (derivations in the .asm headers) - "ps_vcmp_f32_nan": {"VKH_SGPRS": "0x1000,0,16,0", - "VKH_HEAP": "0x1000=0x7fc10001,0x1004=0x3f800000,0x1008=0x40000000"}, - "ps_vcmp_64": {"VKH_SGPRS": "0x1000,0,64,0", - "VKH_HEAP": "0x1000=0x80000000,0x1004=0,0x1008=1,0x100c=0,0x1010=0xffffffff," - "0x1014=0xffffffff,0x1018=1,0x101c=0,0x1020=1,0x1024=0,0x1028=0x80000000," - "0x102c=0,0x1030=7,0x1034=5,0x1038=7,0x103c=5"}, - # the ps_vint_* integer fixtures share one heap, h0..h7 (see their .asm headers) - "ps_vint_logic3": VINT_ENV, - "ps_vint_bits": VINT_ENV, - "ps_vint_mul24": VINT_ENV, - "ps_vint_minmax": VINT_ENV, - "ps_vint_minmax3": VINT_ENV} -# ps_gather_wrap.asm (SHADER-36): image_gather4_l_o under each S# address mode, run by vk_texture_test (the 8x8 gradient -# texture); the expected channels are derived in the .asm header. -TEXTURE_CONSTANTS = { - "ps_gather_wrap": (5090733.0, 14942181.0, 258623.0, 9702309.0), - "ps_gather_border": (32776.0, 34935.0, 34680.0, 28679.0), # SHADER-348: border modes 6 and 7, derived in the .asm - "ps_gather4_c_l": (6.0, 9.0, 17459.0, 9.0), # image_gather4_c_l / _c_l_o / _cl / _c_b_cl_o d16 - "ps_array_resinfo": (8.0, 8.0, 12.0, 1.0), # binding 3, index 1: two 6-face cubes, one mip -} -CLIP_TESTS = ("vs_clip", "vs_clip_param4", "vs_clip_undeclared") -NAN_PAYLOAD_TEST = "ps_nan_payload" -# One definition: a later assignment used to drop ps_texoff (and any entry added by an earlier assignment) from -# the standalone run. Keep every pixel fixture in this tuple. -PIXEL_TESTS = sorted((*PIXEL_BITS, "ps_bary", "ps_persp_bary", "ps_flat", "ps_bitmask_perm", "ps_texoff", - "ps_texoff_implicit", "ps_texoff_forms", "ps_cbv_modulate", - "ps_uniform_branch", "ps_wqm", "ps_scc_mask32", "ps_interp_f16_high", "ps_ij_computed", - "ps_mandelbrot", NAN_PAYLOAD_TEST)) -# Pixel fixtures drawn with another vertex shader than vs_ids. -PIXEL_VERTEX = {"ps_interp_f16_high": "vs_f16_pack", "ps_persp_bary": "vs_persp", - "ps_interp_f32_mods": "vs_interp_consts", "ps_interp_mov_mods": "vs_interp_consts"} -# vs_persp's triangle (see vs_persp.asm): screen positions, clip w and attr0.xy of its three vertices. -PERSP_SCREEN = ((5.0, 8.0), (57.0, 16.0), (21.0, 55.0)) -PERSP_W = (1.0, 2.0, 4.0) -PERSP_ATTR = ((0.25, -0.5), (2.25, 0.75), (-1.0, 3.0)) -TEXOFF_ARGS = ("2", "92", "0", "0", "0") # ps_texoff: T# pointer in s2, then the shader's literal S# -TEXTURE_MIP_TEST = "ps_texture_mip0" -SIGNED_MIP_TEST = "ps_sample_implicit_sint" -UINT_MIP_TEST = "ps_sample_implicit_uint" -GATHER_LOD_TEST = "ps_gather_sampler_lod" -TEXTURE_MIP_DEPENDENCIES = ("vs_ids", "ps_texture_sample") -# Each pair of draws expects mip 0, then mip 1. S# word 1 is minLOD[11:0], maxLOD[23:12], unsigned 4.8. -MIP_TEST_PASSES = { - TEXTURE_MIP_TEST: ((TEXTURE_MIP_TEST, "c00000"), ("ps_texture_sample", "c00000")), - GATHER_LOD_TEST: ((GATHER_LOD_TEST, "40000"), (GATHER_LOD_TEST, "1000c0")), - SIGNED_MIP_TEST: ((SIGNED_MIP_TEST, "0"), (SIGNED_MIP_TEST, "100000")), - UINT_MIP_TEST: ((UINT_MIP_TEST, "0"), (UINT_MIP_TEST, "100000")), -} -# The integer fixtures sample the same two-mip image through the signed or unsigned view the harness binds for them. -MIP_TEST_MODES = {SIGNED_MIP_TEST: "--two-mip-sint", UINT_MIP_TEST: "--two-mip-uint"} - -# TEST-184: vk_store_test "words" fills the r32 uint image with 100 + i, the r32 sint image with -2i (texel -# i = 8y + x) and the r32 uint volume with 200 + i (texel i = 16z + 4y + x), and prints the three after the dispatch. -# Per fixture: the words it changes, {word index: value}, in the uint image, the sint image and the volume, as -# derived in the .asm header. Every other word must still hold its fill. -STORE_IMAGES = ("uint", "sint", "volume") -STORE_FILL = (lambda i: 100 + i, lambda i: -2 * i & 0xFFFFFFFF, lambda i: 200 + i) -STORE_WORDS = { - # 2D image atomics: the texel afterwards (uint image) and the data register afterwards (sint image) of cases - # 0..15, then the texel 64 threads each added 1 to - "cs_imgatomic": (dict(enumerate([0x54, 0xFFFFFF9D, 0x06, 0xF067, 0x97, 0xFFFFFFF0, 0x6A, 0x6B, - 0xC8, 0x6D, 0x05, 0xFFFFFFF0, 0x70, 0xC0FFEE, 0x72, 0x7A, 0xB4])), - dict(enumerate([*range(100, 115), 7])), {}), - # 3D image atomics: the data register afterwards (sint image) and the six texels afterwards (volume) - "cs_imgatomic3d": ({}, dict(enumerate([0x101, 0xDB, 0xF4, 0xCE, 0xE6, 0xFF])), - {57: 0x111, 19: 3, 44: 0xF4, 6: 0xD00D, 30: 0xE6, 39: 0x10}), - # image_get_resinfo on a 16x4 image with five levels: (width, height, depth, levels) of levels 0, 1 and 3, then - # width and height of level 2 and an untouched register, height and levels of level 1, the levels alone, and - # level 5, past the last (2D depth 0 and the past-the-end zeros measured on RDNA2, SHADER-388) - "cs_resinfo": ({**dict(enumerate([16, 4, 0, 5, 8, 2, 0, 5, 2, 1, 0, 5, 4, 1, 0xABCD])), 16: 2, 17: 5, 18: 5, - 20: 0, 21: 0, 22: 0, 23: 5}, - {}, {}), -} -# TEST-184: image_get_lod on vk_texture_test's textures. Per fixture, its draws: S# word 1 (MIN_LOD [11:0], MAX_LOD -# [23:12], 4.8 fixed point), whether the two-mip texture is drawn, and mrt0, as derived in the .asm header: -# ps_get_lod = (clamped LOD, calculated LOD, calculated LOD at 4u, clamped LOD at 4u) on the two-mip texture, -# ps_get_lod_array = (clamped, calculated LOD at 32u, clamped, calculated LOD) on the one-level 2D array. -# A device may keep as few as four fraction bits of LOD (Vulkan's smallest mipmapPrecisionBits), hence the tolerance. -GET_LOD_TESTS = { - "ps_get_lod": (("c00000", True, (1.0, 1.0, 3.0, 1.0)), ("40000", True, (0.0, 1.0, 3.0, 0.0))), - "ps_get_lod_array": (("c00000", False, (0.0, 2.0, 0.0, -3.0)),), -} -GET_LOD_TOLERANCE = 1 / 16 - - -# Windows error codes for a program the system refuses to start, and who refused it. -BLOCKED_BY = {4551: "Windows Application Control (Smart App Control or an App Control policy)", - 1260: "a Windows software restriction policy", - 225: "Microsoft Defender, which reported it as a threat"} - - -def start_failure(exe, err): - """One result line for a test program that could not be started, instead of a traceback that ends the run. - Smart App Control blocks unsigned programs it has no reputation for, so a fresh build can be refused.""" - name = os.path.basename(str(exe)) - who = BLOCKED_BY.get(getattr(err, "winerror", None)) - if who is None: - return f"could not start {name}: {err}" - return (f"could not start {name}: blocked by {who}. A freshly built test program has no reputation yet: " - "allow it, or turn Smart App Control off (Windows Security > App & browser control), and run again") - - -# A test program that hangs (a driver deadlock, e.g. a barrier not every invocation reaches) must not stall the whole -# suite: each run gets a time limit, is killed when it runs out, and counts as a failure. LEONIDA_GPU_TEST_TIMEOUT -# sets the limit in seconds; 0 turns it off. -DEFAULT_GPU_TEST_TIMEOUT = 120.0 - - -def gpu_test_timeout(): - """Seconds one GPU test program may run (LEONIDA_GPU_TEST_TIMEOUT), or None for no limit.""" - text = (os.environ.get("LEONIDA_GPU_TEST_TIMEOUT") or "").strip() - if not text: - return DEFAULT_GPU_TEST_TIMEOUT - error = f"LEONIDA_GPU_TEST_TIMEOUT must be a finite number of seconds (0 = no limit), not {text!r}" - try: - limit = float(text) - except ValueError: - sys.exit(error) - if not math.isfinite(limit): - sys.exit(error) - return None if limit <= 0 else limit - - -def timed_out(name, limit): - return (f"timed out after {limit:g} s: {os.path.basename(str(name))} was killed (a GPU hang?); " - "LEONIDA_GPU_TEST_TIMEOUT sets the limit") - - -def run(*cmd, env=None, cwd=None): - limit = gpu_test_timeout() - try: - r = subprocess.run(cmd, capture_output=True, text=True, env=env, timeout=limit, cwd=cwd) - except subprocess.TimeoutExpired: - return 1, timed_out(cmd[0], limit) - except OSError as e: - if isinstance(e, FileNotFoundError): - tools = os.path.abspath(os.path.dirname(cmd[0])) - missing = [t + EXE for t in TEST_PROGRAMS if not os.path.isfile(os.path.join(tools, t + EXE))] - if missing: - sys.exit(not_found_message(tools, missing)) - return 1, start_failure(cmd[0], e) - return r.returncode, r.stdout + r.stderr - - -def run_readback(path, launch, *args, **kwargs): - """Require this invocation to write its framebuffer before comparing it.""" - path = Path(path) - try: - path.unlink(missing_ok=True) - except OSError as err: - return 1, f"could not remove the previous readback {path.name}: {err}" - code, output = launch(*args, **kwargs) - if code == 0 and not path.is_file(): - return 1, f"{output.rstrip()}\nmissing readback: {path.name}".lstrip() - return code, output - - -def compute_unsupported(code, output): - """A Skip quoting vk_compute_test's "unsupported: ..." line when it exited UNSUPPORTED because the module needs a - feature the device lacks (Int64, Float64, OpFmaKHR), in any run mode; None otherwise. Its --require-wave64 - refusal prints no such line and keeps the callers' own handling, and a 77 without a reason stays a failure.""" - m = re.search(r"^unsupported: .*", output, re.MULTILINE) if code == UNSUPPORTED else None - return Skip(f"SKIP ({m.group(0)})") if m else None - - -def failure(code, output, lines): - details = "\n".join(output.strip().splitlines()[-lines:]) - return f"exit {code}: {details or 'no test output'}" - - -def dump_test(tools, spirv, name, want, words, env=None): - """Run one group with a heap of `words` words and compare the first len(want) words of the whole dump. The - console dump stops at word 7.""" - with tempfile.TemporaryDirectory(prefix="leonida-fmt-") as tmp: - dump = Path(tmp) / "out.bin" - # VKC_OUT_WORDS sets a minimum. Pin this dispatch to exactly `words` words. - child = dict(os.environ if env is None else env, VKC_DUMP=str(dump), VKC_OUT_WORDS=str(words)) - code, out = run(os.path.join(tools, "vk_compute_test" + EXE), os.path.join(spirv, name + ".spv"), - "1", "dump", env=child) - if skip := compute_unsupported(code, out): - return skip - if code: - return failure(code, out, 3) - if not dump.is_file(): - return "no VKC_DUMP file written" - data = dump.read_bytes() - if len(data) != 4 * words: - return f"expected {4 * words} dump bytes, got {len(data)}" - for i, (expected, got) in enumerate(zip(want, struct.unpack(f"<{words}I", data))): - if got != expected: - return f"word {i}: expected {expected:#010x}, got {got:#010x}" - return "" - - -def fmt_1010102_test(tools, spirv, env=None): - """Check both packed stores and the untouched tail of a single group's 64 words.""" - return dump_test(tools, spirv, "cs_fmt_1010102", FMT_1010102_WORDS + [0xEEEEEEEE] * 48, 64, env) - - -def fmt_int_narrow_test(tools, spirv, env=None): - return dump_test(tools, spirv, "cs_fmt_int_narrow", FMT_INT_NARROW_WORDS, len(FMT_INT_NARROW_WORDS), env) - - -def fmt_sint32_test(tools, spirv, env=None): - return dump_test(tools, spirv, "cs_fmt_sint32", FMT_SINT32_WORDS, len(FMT_SINT32_WORDS), env) - - -def fmt_all_test(tools, spirv, env=None): - """cs_fmt_all: 28 loads, the inputs, 15 stores, and the untouched words between (316 words in all). Wave32, one - thread: the translator recorded 32 for it, so the run is pinned to a 32-wide subgroup like compute_test does.""" - env = dict(os.environ if env is None else env) - env.setdefault("VKC_SUBGROUP_SIZE", str(subgroup_size(spirv, "cs_fmt_all") or 32)) - return dump_test(tools, spirv, "cs_fmt_all", FMT_ALL_WORDS, len(FMT_ALL_WORDS), env) - - -def fmt_xy_xyz_test(tools, spirv, env=None): - """TEST-185: the 84 result words and the untouched words after them, up to the inputs at 0x200. The heap needs - 0x2d0 bytes, so it is 192 words.""" - return dump_test(tools, spirv, "cs_fmt_xy_xyz", FMT_XY_XYZ_WORDS + [0xEEEEEEEE] * 44, 192, env) - - -def tbuffer_store_test(tools, spirv, env=None): - """The 52 region words tbuffer_store_format_* leaves and the untouched words after them, up to the regions at - 0x200. The heap needs 0x2d0 bytes, so it is 192 words.""" - return dump_test(tools, spirv, "cs_tbuffer_store", TBUFFER_STORE_WORDS + [0xEEEEEEEE] * 76, 192, env) - - -def fmt_d16_xyz_test(tools, spirv, env=None): - """The d16_xyz/d16_xy loads and d16_xyz stores of cs_fmt_d16_xyz.asm: the whole 80-word heap.""" - return dump_test(tools, spirv, "cs_fmt_d16_xyz", FMT_D16_XYZ_WORDS, len(FMT_D16_XYZ_WORDS), env) - - -class Skip(str): - """A result that is neither a pass nor a failure: the device can't run the test.""" - - -def check_mesh_v5(data): - if len(data) != 24 * 16: - return f"expected 24 RGBA32F pixels (384 bytes), got {len(data)} bytes" - pixels = iter(struct.iter_unpack("<4f", data)) - errors = [] - for z in range(4): - for y in range(3): - for x in range(2): - pixel = next(pixels) - # v5 = linear group index * NumThreads + lane (#209); the shader records lanes 0, 1 and 31 of 32 - g = x + 2*y + 6*z - want = (32 * g, 32 * g + 1, 32 * g + 31, 1) - if pixel != want: - errors.append(f"({x},{y},{z}): got {pixel}, expected {want}") - return f"{len(errors)}/24 mismatches; first {errors[0]}" if errors else "" - - -# LEONIDA_MESH_COMPUTE=1 (for run_gpu_tests.py, which builds the mesh fixtures): the mesh shaders were translated -# with rdna2spirv.py --mesh-compute, and vk_harness dispatches each as compute and draws its slots with the vertex -# shader tools/mesh_compute_vs.py wrote (.mesh_vs.spv), so they run without VK_EXT_mesh_shader. -MESH_COMPUTE = os.environ.get("LEONIDA_MESH_COMPUTE") == "1" - - -def mesh_env(spirv, name, base=None): - """vk_harness environment for mesh shader `name`: VKH_MESH=1, or under LEONIDA_MESH_COMPUTE=1 the - --mesh-compute variables (vertex shader, slot bytes and primitive count from index.json's mesh_compute).""" - env = dict(base if base is not None else os.environ) - if MESH_COMPUTE: - vs = Path(spirv) / f"{name}.mesh_vs.spv" - try: - with open(Path(spirv) / "index.json", encoding="utf-8") as f: - lay = json.load(f).get(name, {}).get("mesh_compute") - except (OSError, ValueError): - lay = None - if lay and vs.is_file(): - env.update(VKH_MESH_COMPUTE=str(vs), VKH_MESH_SLOT=str(lay["slot_bytes"]), - VKH_MESH_PRIMS=str(lay["max_primitives"])) - return env - env["VKH_MESH"] = "1" - return env - - -def mesh_v5_test(tools, spirv, raw): - shader = Path(spirv) / "ms_v5_workgroup.spv" - if not shader.is_file(): - return Skip("SKIP (build the mesh fixture with scripts/run_gpu_tests.py)") - fs = Path(spirv) / "fs_passthru.spv" - if not fs.is_file(): - return "missing fs_passthru.spv" - code, out = run_readback(raw, run, os.path.join(tools, "vk_harness" + EXE), shader, fs, raw, - "--mesh-group-readback", "2", "3", "4", env=mesh_env(spirv, "ms_v5_workgroup")) - if code == UNSUPPORTED: - return Skip("SKIP (mesh shading unavailable)") - if code: - return failure(code, out, 3) - return check_mesh_v5(raw.read_bytes()) - - -def partial_wave_test(tools, spirv, name, expected_words): - """A group smaller than a wave: run with subgroup size 64 requested (no full subgroups); None if the device - has no 64-wide subgroup. With LEONIDA_W64_EMULATE=1 it asks for 32 instead, the width the emulation is for, so - a device that defaults to 64 (AMD) runs the emulated path at 32 too (#166).""" - shader = os.path.join(spirv, name + ".spv") - if not os.path.isfile(shader): - return f"missing {name}.spv" - old = os.environ.get("VKC_SUBGROUP_SIZE") - os.environ["VKC_SUBGROUP_SIZE"] = "32" if W64_EMULATED else "64" - try: - code, out = run(os.path.join(tools, "vk_compute_test" + EXE), shader, "1", "dump") - finally: - if old is None: - os.environ.pop("VKC_SUBGROUP_SIZE", None) - else: - os.environ["VKC_SUBGROUP_SIZE"] = old - if code != 0: - return failure(code, out, 2) - if not W64_EMULATED and not any(int(x) >= 64 for x in re.findall(r"subgroup \d+\.\.(\d+)", out)): - return None - m = re.search(r"^out\[0\.\.7\] = ((?:[0-9]+ ){7}[0-9]+)$", out, re.MULTILINE) - if m and [int(x) for x in m.group(1).split()] == expected_words: - return "" - return failure(code, out, 2) - - -def narrow_subgroup_skip(out): - """A Skip when vk_compute_test's "device: ... (subgroup MIN..MAX)" line says MAX is below 32 lanes, else None.""" - m = re.search(r"subgroup \d+\.\.(\d+)", out) - if m and int(m.group(1)) < 32: - return Skip(f"SKIP (subgroup {m.group(1)} is narrower than 32 lanes)") - return None - - -def unpinned_subgroup_skip(out): - """A Skip when vk_compute_test says the VKC_SUBGROUP_SIZE it was given can't be pinned on this device, else None. - Output without the line (an older vk_compute_test) is judged as before. "compute subgroup size: 32 (observed: ...)" - (MoltenVK: not requirable, but its probe saw 32 lanes) is judged, and "observed wrong" comes with exit 1, a - failure.""" - m = re.search(r"^compute subgroup size: (\d+) not available$", out, re.MULTILINE) - if m: - return Skip(f"SKIP (the device can't run this shader at {m.group(1)} lanes on request)") - return None - - -def wave32_lane_skip(out): - """The skip rule for WAVE32_LANE_DUMPS, shared with run_gpu_tests.py.""" - return narrow_subgroup_skip(out) or unpinned_subgroup_skip(out) - - -def bitmask_perm_narrow_skip(out, px): - """A Skip when ps_bitmask_perm ran narrower than 32 lanes on a device whose subgroup range permits it (#618). - Requires every lane 0..width-1 of a power-of-two width in [min, 32), so a broken v_mbcnt still fails.""" - m = re.search(r"subgroup (\d+)\.\.(\d+)", out) - if not m or len(px) != 64 * 64: - return None - lo, hi = int(m.group(1)), int(m.group(2)) - if lo >= 32: - return None - lanes = {p[0] for p in px} - width = max(lanes) + 1 - # "pippi" reads lane ^ 9. Where that lane runs (every lane at 16 wide, none at 8) the word is defined and has - # to be right: a narrow run excuses only the sources that aren't there. - if any(a != lane ^ 9 for lane, a, _, _ in px if lane ^ 9 < width): - return None - if lo <= width < 32 and width & (width - 1) == 0 and lanes == set(range(width)): - return Skip(f"SKIP (fragment subgroup ran at {width} lanes on {lo}..{hi} device; needs 32)") - return None - - -def vcmpx_forms_narrow_skip(out): - """A Skip when ps_vcmpx_forms cannot be judged at 32-lane EXEC (TEST-205 / #618). - - The shader packs v_cmpx EXEC results into constant mrt0 words and does not write lane IDs, so unlike - bitmask_perm_narrow_skip the width cannot be read back from the frame. On devices with minSubgroupSize < 32, - requiredSubgroupSizeStages typically omits FRAGMENT (#1318), so vk_harness cannot pin the stage and the - driver runs it narrower (Intel UHD 770: 4096/4096 mismatches, last word looking like a lane mask).""" - m = re.search(r"subgroup (\d+)\.\.(\d+)", out) - if not m: - return Skip("SKIP (vk_harness reported no subgroup width)") - lo, hi = int(m.group(1)), int(m.group(2)) - if hi < 32: - return Skip(f"SKIP (subgroup {hi} is narrower than 32 lanes)") - if lo < 32: - return Skip(f"SKIP (fragment subgroup may run narrower than 32 on {lo}..{hi} device; needs 32)") - return None - - -# Dump words a driver gets wrong with or without SignedZeroInfNanPreserve, by the first word of the device name on -# vk_compute_test's "device: ..." line. Only these words go unjudged there. Shared with run_gpu_tests.py. -# - Apple GPUs (MoltenVK) return +0 for cs_signed_zero_nan's -0 products, words 0, 2 and 3 (v_mul_f32, v_pk_mul_f16, -# v_mul_f16; #1203, SHADER-182). -# - Mesa llvmpipe returns 0 in word 5, the NaN check of 0 * inf (an inline-constant 0), while its other NaN checks give -# 1 (#664, Mesa with LLVM 21.1.8). The CI runs the GPU tests on llvmpipe. -UNJUDGED_WORDS = {"Apple": {"cs_signed_zero_nan": (0, 2, 3)}, - "llvmpipe": {"cs_signed_zero_nan": (5,)}} - - -def judged_words(name, out, words): - """The expected words with None where nothing is judged: UNJUDGED_WORDS for the device that vk_compute_test's - "device: ..." line names, else every word as given.""" - m = re.search(r"^device: (\S+)", out, re.MULTILINE) - unjudged = UNJUDGED_WORDS.get(m.group(1), {}).get(name, ()) if m else () - return [None if i in unjudged else w for i, w in enumerate(words)] - - -def words_match(got, want): - """The dump's words against want, which may be shorter; a None in want is not judged.""" - return len(got) >= len(want) and all(w is None or g == w for g, w in zip(got, want)) - - -def compute_test(tools, spirv, name, groups, mode, *, require_wave64=False, expected_words=None, needs_32_lanes=False, - env=None): - """Return an empty string for a pass, None for unsupported wave64, a Skip for a wave32 lane-mask test on a device - narrower than 32 lanes (needs_32_lanes) or a module the device lacks a feature for, or a failure diagnostic. `env` adds variables for vk_compute_test - (VKC_SGPRS).""" - shader = os.path.join(spirv, name + ".spv") - args = [] - if require_wave64: - if not os.path.isfile(shader): - return f"missing {name}.spv" - args.append("--require-wave64") - if needs_32_lanes: - env = {**WAVE32_LANE_ENV, **(env or {})} - # Run at the wave size the translator recorded, as run_gpu_tests.py does: a wave32 test left to the device's - # default runs 64-wide on AMD (subgroups 32..64), and cs_barrier_loop's four waves of 32 became two. - sg = None if "VKC_SUBGROUP_SIZE" in (env or {}) else subgroup_size(spirv, name) - if sg: - env = {**(env or {}), "VKC_SUBGROUP_SIZE": str(sg)} - extra = {"env": dict(os.environ, **env)} if env else {} - code, out = run(os.path.join(tools, "vk_compute_test" + EXE), shader, groups, mode, *args, **extra) - if skip := compute_unsupported(code, out): - return skip - if require_wave64 and code == 77: # vk_compute_test: the device cannot run a 64-wide compute subgroup - return None - if needs_32_lanes: - if code == UNSUPPORTED: - return Skip(f"SKIP ({out.strip() or 'unsupported device'})") - if code == 0 and (skip := wave32_lane_skip(out)): - return skip - if sg and (skip := unpinned_subgroup_skip(out)): - return skip - if code != 0: - return failure(code, out, 2) - if require_wave64 and "compute subgroup size: 64" not in out.splitlines(): - return "64-wide subgroup was not confirmed (rebuild vk_compute_test)" - if mode == "workgroup_yz": - if "2x3x4 workgroup Y/Z: 0 mismatches" in out.splitlines(): - return "" - elif expected_words is not None: - m = re.search(r"^out\[0\.\.7\] = ((?:[0-9]+ ){7}[0-9]+)$", out, re.MULTILINE) - if m and words_match([int(x) for x in m.group(1).split()], judged_words(name, out, expected_words)): - return "" - else: - m = re.search(r"(\d+) mismatches", out) - if m and m.group(1) == "0": - return "" - return failure(code, out, 2) - - -def shader_features(spirv, name): - """The Vulkan feature names recorded for a shader in index.json, or an empty set.""" - try: - with open(os.path.join(spirv, "index.json"), encoding="utf-8") as f: - feats = json.load(f).get(name, {}).get("features") or () - return set(feats) - except (OSError, ValueError, TypeError): - return set() - - -def shader_fma_mode(spirv, name): - """How the translator emitted fused multiply-adds for a shader ('glsl', 'khr' or 'exact'), or '' if unrecorded. - - Older indexes have no field: callers must fall back to the capability and LEONIDA_FMA as before. - """ - try: - with open(os.path.join(spirv, "index.json"), encoding="utf-8") as f: - mode = json.load(f).get(name, {}).get("fma") or "" - return mode if mode in ("glsl", "khr", "exact") else "" - except (OSError, ValueError, TypeError): - return "" - - -def judge_fma_fused(words, khr, exact=False): - """Judge cs_fma_fused's 8 words: (ok, detail). Under --fma khr every word must be exact fused; under --fma glsl - each of the 7 f32 words may be either fused or exact split (Vulkan allows splitting GLSL.std.450 Fma), while the - f16 round-to-odd word out[7] must always be exact 0x00007351.""" - if not words or len(words) < 8: - return False, "missing out[0..7] dump" - if khr or exact: - label = "OpFmaKHR" if khr else "--fma exact" - for i, (got, want) in enumerate(zip(words, FMA_FUSED)): - if got != want: - return False, (f"word {i}: got {got:#010x}, want fused {want:#010x} " - "(single-rounded FMA: OpFmaKHR or --fma exact)") - return True, "8/8 fused exact (single-rounded FMA: OpFmaKHR or --fma exact)" - if words[7] != FMA_FUSED[7]: - return False, f"word 7 (f16): got {words[7]:#010x}, want {FMA_FUSED[7]:#010x}" - n_split = 0 - for i in range(7): - got, fused, split = words[i], FMA_FUSED[i], FMA_SPLIT[i] - if got == fused: - continue - if got == split: - n_split += 1 - continue - return False, f"word {i}: got {got:#010x}, want fused {fused:#010x} or split {split:#010x}" - if n_split == 0: - return True, "8/8 fused exact (GLSL Fma)" - return True, f"{7 - n_split}/7 f32 fused, {n_split}/7 split (GLSL Fma; LEONIDA_FMA=khr for OpFmaKHR), f16 exact" - - -def fma_fused_test(tools, spirv): - """Run cs_fma_fused and judge against FMA_FUSED (strict under --fma khr and --fma exact, fused-or-split f32 under - --fma glsl).""" - shader = os.path.join(spirv, "cs_fma_fused.spv") - # --fma exact also guarantees single rounding (built from NoContraction ops), but records no KHR capability. - # Without the index field a fresh shell cannot tell it from the default GLSL Fma (TEST-1147). - mode = shader_fma_mode(spirv, "cs_fma_fused") - if mode: - # A recorded mode is authoritative: a stale LEONIDA_FMA from the build shell must not override it. - strict = mode in ("khr", "exact") - else: - # An older index has no mode field: capability and environment are the only remaining signals. - strict = ("shaderFmaFloat32" in shader_features(spirv, "cs_fma_fused") - or os.environ.get("LEONIDA_FMA") in ("khr", "exact")) - code, out = run(os.path.join(tools, "vk_compute_test" + EXE), shader, "1", "dump", - env=dict(os.environ, **FMA_FUSED_ENV)) - if code == UNSUPPORTED: - m = re.search(r"unsupported: .*", out) - return Skip(f"SKIP ({m.group(0) if m else 'unsupported device'})") - if code != 0: - return failure(code, out, 2) - m = re.search(r"^out\[0\.\.7\] = ((?:[0-9]+ ){7}[0-9]+)$", out, re.MULTILINE) - if not m: - return failure(code, out, 2) - words = [int(x) for x in m.group(1).split()] - ok, detail = judge_fma_fused(words, khr=strict) - return "" if ok else detail - - -def cvt_f32_sat_test(tools, spirv): - """cs_cvt_f32_sat once per input of CVT_F32_SAT_CASES: an empty string when every pair of words is exact.""" - wrong = [] - for bits, unsigned, signed in CVT_F32_SAT_CASES: - problem = compute_test(tools, spirv, "cs_cvt_f32_sat", "1", "dump", expected_words=[unsigned, signed], - env={"VKC_SGPRS": f"{bits:#010x}"}) - if problem is None or isinstance(problem, Skip): - return problem # the device can't run it as recorded (wave size not pinnable): the same for every input - if problem: - wrong.append(f"{bits:#010x}: {problem}") - return f"{len(wrong)} of {len(CVT_F32_SAT_CASES)} inputs wrong, first {wrong[0]}" if wrong else "" - - -def mesh_w64x_test(tools, spirv, name): - """ms_w64x_ballot: ms_tri's picture, blue 0.5 only if the ballot/mbcnt compaction was exact across both halves. - ms_wave_info_s3 draws the same picture; its wave id is LocalInvocationIndex >> 6, so it is judged on any - subgroup width, as run_gpu_tests.py does.""" - shader, fs = os.path.join(spirv, name + ".spv"), os.path.join(spirv, "fs_passthru.spv") - if not (os.path.isfile(shader) and os.path.isfile(fs)): - return Skip("SKIP (mesh shader: build it with scripts/run_gpu_tests.py, build.py does not)") - env = mesh_env(spirv, name) - if not W64_EMULATED: - env["VKH_SUBGROUP_SIZE"] = "64" - with tempfile.TemporaryDirectory(prefix="leonida-mesh-") as tmp: - raw = Path(tmp) / "pixels.raw" - harness = os.path.join(tools, "vk_harness" + EXE) - limit = gpu_test_timeout() - try: - r = subprocess.run([harness, shader, fs, raw], capture_output=True, text=True, env=env, timeout=limit) - except subprocess.TimeoutExpired: - return timed_out(harness, limit) - except OSError as e: - return start_failure(harness, e) - if r.returncode == UNSUPPORTED: # vk_harness: the device has no VK_EXT_mesh_shader - m = re.search(r"unsupported: .*", r.stderr) - return Skip(f"SKIP ({m.group(0) if m else 'unsupported device'})") - if r.returncode or not raw.is_file(): - return failure(r.returncode, r.stdout + r.stderr, 2) - data = raw.read_bytes() - if len(data) != 64 * 64 * 16: - return "vk_harness returned an unexpected pixel count" - px = list(struct.iter_unpack("<4f", data)) - if (name == "ms_w64x_ballot" and not W64_EMULATED - and 64 not in [int(x) for x in re.findall(r"subgroup \d+\.\.(\d+)", r.stderr)]): - return None # the device has no 64-wide subgroups - # A NaN fails every comparison, so each component must be within the tolerance, not merely not outside it. - wrong = sum(not all(abs(v - w) <= 1e-3 for v, w in zip(p, (((i % 64) + .5) / 64, ((i // 64) + .5) / 64, .5, 1))) - for i, p in enumerate(px)) - return "" if not wrong else f"{wrong} of {len(px)} pixels differ (blue {px[0][2]:.3g} at pixel 0, want 0.5)" - - -def subgroup_size(spirv, name): - """The wave size the translator recorded for a shader (index.json), or None.""" - try: - with open(os.path.join(spirv, "index.json"), encoding="utf-8") as f: - return json.load(f).get(name, {}).get("subgroup_size") - except (OSError, ValueError): - return None - - -def bindless_test(tools, spirv, pixel="ps_tex"): - """ps_tex: a texture found through the descriptor hash table and the bindless set (vk_bindless_test). - ps_imgatomic: image atomics in a pixel shader through the set's r32ui storage arrays, checked per texel.""" - shaders = [os.path.join(spirv, name + ".spv") for name in ("vs_ids", pixel)] - for path in shaders: - if not os.path.isfile(path): - return f"missing {os.path.basename(path)}" - code, out = run(os.path.join(tools, "vk_bindless_test" + EXE), *shaders) - if code == UNSUPPORTED: - m = re.search(r"unsupported: .*", out) - return Skip(f"SKIP ({m.group(0) if m else 'unsupported device'})") - if pixel == "ps_imgatomic": - m = re.search(r"ps_imgatomic: (\d+) of \d+ texels wrong.*; (\d+) of \d+ render-target pixels wrong", out) - return "" if code == 0 and m and m.group(1) == "0" and m.group(2) == "0" else failure(code, out, 3) - m = re.search(r"(\d+) draws read back, (\d+) bad pixels", out) - return "" if code == 0 and m and m.group(2) == "0" else failure(code, out, 3) - - -# Samples with a16 coordinates after whole-VGPR arguments (gradients, a bias, a clamp). On the 8x8 gradient every -# pixel must be the texel its own (u, v) reads. ps_texture_grad_cl_a16 draws on the two-mip texture instead, where its -# clamp picks mip 0 left of x = 32 and mip 1 from there on. -GRADIENT_TESTS = ("ps_texture_grad_a16", "ps_texture_bias_a16", "ps_texture_grad_cl_a16", "ps_texture_cl", "ps_texture_b_cl") -# ps_texture_cl / ps_texture_b_cl (image_sample_cl / _b_cl) draw on the two-mip texture too: the left half reads mip 0 (red, -# the top-left quadrant), the right half mip 1 (cyan) where the clamp is 1. -CLAMP_TESTS = ("ps_texture_cl", "ps_texture_b_cl") - - -def table_fetch_test(tools, spirv): - tool = os.path.abspath(os.path.join(tools, "vk_texture_test" + EXE)) - with tempfile.TemporaryDirectory(prefix="table-fetch-") as tmp: - for mode in ("fetch-sint", "fetch-uint", "fetch-miss"): - raw = os.path.join(tmp, mode + ".raw") - code, output = run_readback(raw, run, tool, mode, raw, cwd=spirv) - if code == UNSUPPORTED: - return Skip(output.strip()) - if code or f"{mode}: 4096 exact pixels" not in output: - return failure(code, output, 3) - return "" - - -def texture_gradient_a16_test(tools: str, spirv: str, name: str = "ps_texture_grad_a16") -> str: - """Check every pixel of one of the GRADIENT_TESTS samples.""" - vs = os.path.join(spirv, "vs_ids.spv") - fs = os.path.join(spirv, name + ".spv") - two_mip = name == "ps_texture_grad_cl_a16" or name in CLAMP_TESTS - with tempfile.TemporaryDirectory(prefix="leonida-texture-") as tmp: - raw = Path(tmp) / "pixels.raw" - code, out = run(os.path.join(tools, "vk_texture_test" + EXE), vs, fs, raw, - "0", "92", "c00000", "14500000", "0", *(["--two-mip"] if two_mip else [])) - if code == UNSUPPORTED: # vk_texture_test: e.g. no shaderResourceMinLod for the d_cl clamp - m = re.search(r"unsupported: .*", out) - return Skip(f"SKIP ({m.group(0) if m else 'unsupported device'})") - if code or not raw.is_file(): - return failure(code, out, 3) - data = raw.read_bytes() - if len(data) != 64 * 64 * 16: - return "vk_texture_test returned an unexpected pixel count" - wrong = 0 - first = "" - for index, pixel in enumerate(struct.iter_unpack("<4f", data)): - x, y = index % 64, index // 64 - if name in CLAMP_TESTS: # mip 1 (cyan) where the clamp is 1, else mip 0's top-left quadrant (red) - want = (0.0, 1.0, 1.0, 1.0) if x >= 32 else (1.0, 0.0, 0.0, 1.0) - elif two_mip: # mip 1 (cyan) where the clamp is 1, else mip 0's red and blue quadrants - want = (0.0, 1.0, 1.0, 1.0) if x >= 32 else (1.0, 0.0, 0.0, 1.0) if y < 32 else (0.0, 0.0, 1.0, 1.0) - else: - want = (32 * (x // 8) / 255, 32 * (y // 8) / 255, 128 / 255, 1.0) - if any(not math.isclose(actual, expected, rel_tol=0, abs_tol=1e-6) - for actual, expected in zip(pixel, want)): - if not wrong: - first = f"at ({x},{y}): got {pixel}, expected {want}" - wrong += 1 - return f"{wrong} of 4096 pixels differ; {first}" if wrong else "" - - -def ssharp_words(mip_filter, min_lod=0.0, max_lod=15.0, bias=0.0): - """An S# with point min/mag filters, clamp-to-last-texel addressing and the given mip fields. Positions as - Mesa's gfx10-rsrc.json has them: WORD0 CLAMP_X/Y/Z [8:0], WORD1 MIN_LOD [11:0] and MAX_LOD [23:12] (4.8 fixed), - WORD2 LOD_BIAS [13:0] (signed 5.8 fixed) and MIP_FILTER [27:26] (0 none, 1 point, 2 linear).""" - clamp = 2 | 2 << 3 | 2 << 6 - return (clamp, round(min_lod * 256) | round(max_lod * 256) << 12, - (round(bias * 256) & 0x3fff) | mip_filter << 26, 0) - - -# (name, S#, (BASE_LEVEL, LAST_LEVEL) of the T#). Expected levels, explicit LOD 0 / implicit LOD 1: -SAMPLER_CASES = [("point", ssharp_words(1), (0, 1)), # 0 / 1 - ("point max_lod 0", ssharp_words(1, max_lod=0), (0, 1)), # 0 / 0 - ("point min_lod 1", ssharp_words(1, min_lod=1), (0, 1)), # 1 / 1: MIN_LOD clamps an explicit LOD too - ("point bias +1", ssharp_words(1, bias=1), (0, 1)), # 1 / 1: the S# bias applies to an explicit LOD - ("point bias -1", ssharp_words(1, bias=-1), (0, 1)), # 0 / 0 - ("none", ssharp_words(0), (0, 1)), # 0 / 0: MIP_FILTER_NONE reads the base level - ("none min_lod 1", ssharp_words(0, min_lod=1), (0, 1)), # 0 / 0: and ignores the LOD clamp - ("point base 1", ssharp_words(1), (1, 1))] # 1 / 1: the T#'s BASE_LEVEL starts the view -SAMPLER_SIZE = 64 # the target; the texture is twice as wide, so implicit sampling sees LOD 1 -GREY = 128 / 255 - - -def sampler_level(words, view, lod): - """The texture level one sample reads, from the S# fields and the T# view alone (not from gfx10_descriptors.h). - MIP_FILTER_NONE reads the view's base level whatever the LOD. Otherwise the LOD plus LOD_BIAS is clamped to - [MIN_LOD, MAX_LOD], a point mip filter takes the nearest level (ceil(lod + 0.5) - 1, as Vulkan's - VK_SAMPLER_MIPMAP_MODE_NEAREST does) and the result stays inside the view.""" - base, last = view - if (words[2] >> 26) & 3 == 0: - return base - bias = ((words[2] & 0x3fff) ^ 0x2000) - 0x2000 - lo, hi = (words[1] & 0xfff) / 256, (words[1] >> 12 & 0xfff) / 256 - level = math.ceil(min(max(lod + bias / 256, lo), hi) + 0.5) - 1 - return base + min(max(level, 0), last - base) - - -def sampler_texel(level, x, y): - """(r, g) of the texel under pixel (x, y): level 0 is red, green, blue and yellow quadrants, level 1 grey.""" - if level: - return (GREY, GREY) - half = SAMPLER_SIZE // 2 - return ((1.0, 0.0), (0.0, 1.0), (0.0, 0.0), (1.0, 1.0))[2 * (y >= half) + (x >= half)] - - -def sampler_mismatch(data, words, view): - """The first pixel whose (lz.r, lz.g, implicit.r, implicit.g) is not what the S# and T# select, or "".""" - if len(data) != SAMPLER_SIZE ** 2 * 16: - return f"expected {SAMPLER_SIZE ** 2} RGBA32F pixels, got {len(data)} bytes" - explicit, implicit = sampler_level(words, view, 0), sampler_level(words, view, 1) - for i, got in enumerate(struct.iter_unpack("<4f", data)): - y, x = divmod(i, SAMPLER_SIZE) - want = sampler_texel(explicit, x, y) + sampler_texel(implicit, x, y) - if any(not math.isclose(g, w, rel_tol=0, abs_tol=1e-6) for g, w in zip(got, want)): - return f"({x},{y}): {tuple(round(g, 4) for g in got)} != {tuple(round(w, 4) for w in want)}" - return "" - - -def sampler_test(tools, spirv): - """ps_ssharp: every SAMPLER_CASES S#/T# pair drawn with vk_sampler_test and judged per pixel by sampler_level. - A grey level-1 texel differs from every level-0 texel in both channels, so a wrong level fails at each pixel.""" - shaders = [os.path.join(spirv, name + ".spv") for name in ("vs_ids", "ps_ssharp")] - for path in shaders: - if not os.path.isfile(path): - return f"missing {os.path.basename(path)}" - with tempfile.TemporaryDirectory(prefix="leonida-sampler-") as tmp: - for name, words, view in SAMPLER_CASES: - raw = Path(tmp) / "pixels.raw" - raw.unlink(missing_ok=True) - code, out = run(os.path.join(tools, "vk_sampler_test" + EXE), *shaders, raw, - *(f"{w:x}" for w in words), *(str(v) for v in view)) - if code == UNSUPPORTED: - m = re.search(r"unsupported: .*", out) - return Skip(f"SKIP ({m.group(0) if m else 'unsupported device'})") - if code or not raw.is_file(): - return f"{name}: {failure(code, out, 3)}" - problem = sampler_mismatch(raw.read_bytes(), words, view) - if problem: - return f"{name}: {problem}" - return "" - - -def bary_persp_problem(px): - """ps_persp_bary drawn with vs_persp: "" when every pixel matches the perspective-correct CPU reference, else what - differs. At a pixel centre with screen-space weights l0, l1, l2, the weights are p_k = (l_k / w_k) / sum(l_m / w_m); - mrt0 = (attr0.xy interpolated with p, p1, p2), and pixels outside the triangle keep the clear value (-1). Coverage - comes from edge functions at doubled coordinates, which are exact integers: no centre lies on an edge, so every - pixel is judged whatever the rasterization rule. The affine weights (l1, l2) must differ from (p1, p2) by more than - 100 times the tolerance on every covered pixel, so a NoPerspective regression can't pass by accident.""" - tol = 1e-5 - (x0, y0), (x1, y1), (x2, y2) = (tuple(int(c) for c in v) for v in PERSP_SCREEN) - area2 = 2 * ((x1 - x0) * (y2 - y0) - (x2 - x0) * (y1 - y0)) # twice the area, in doubled coordinates - covered, wrong, first, gap = 0, 0, "", math.inf - for i, pixel in enumerate(px): - x, y = 2 * (i % 64) + 1, 2 * (i // 64) + 1 # the pixel centre, doubled - e1 = (x - 2 * x0) * (y2 - y0) - (x2 - x0) * (y - 2 * y0) - e2 = (x1 - x0) * (y - 2 * y0) - (x - 2 * x0) * (y1 - y0) - e = (area2 - e1 - e2, e1, e2) - if 0 in e: - return f"test geometry: pixel centre ({i % 64},{i // 64}) lies on an edge" - if min(e) < 0: - want = (-1.0, -1.0, -1.0, -1.0) - else: - l = [ek / area2 for ek in e] - p = [lk / wk for lk, wk in zip(l, PERSP_W)] - p = [pk / sum(p) for pk in p] - want = (sum(pk * a[0] for pk, a in zip(p, PERSP_ATTR)), sum(pk * a[1] for pk, a in zip(p, PERSP_ATTR)), - p[1], p[2]) - gap = min(gap, max(abs(p[1] - l[1]), abs(p[2] - l[2]))) - covered += 1 - if not all(math.isfinite(v) and abs(v - w) <= tol for v, w in zip(pixel, want)): - if not wrong: - got, exp = (tuple(round(v, 6) for v in t) for t in (pixel, want)) - first = f"at ({i % 64},{i // 64}): got {got}, want {exp}" - wrong += 1 - if gap <= 100 * tol: - return f"test geometry: perspective and affine weights only {gap:.3g} apart" - return f"{wrong} pixels off the perspective-correct reference ({covered} covered); {first}" if wrong else "" - - -def pixels(tools, spirv, name, fmt, vertex="vs_ids", *, settings=None): - # Draw at the shader's own wave size, as run_gpu_tests.py does (#146): a wave32 pixel shader run as wave64 - # (RADV's default on RDNA1) reads lanes it was never written for. - sg = subgroup_size(spirv, name) - env = dict(os.environ, VKH_SUBGROUP_SIZE=str(sg)) if sg else None - if settings is None: - settings = PIXEL_ENV.get(name) - if settings: - env = dict(env or os.environ, **settings) - gs = os.path.join(spirv, name + ".bary_gs.spv") - if BARY_FALLBACK and os.path.isfile(gs): - env = dict(env or os.environ, VKH_GS=gs, VKH_GS_HELPER="1") - with tempfile.TemporaryDirectory(prefix="leonida-pixels-") as tmp: - raw = Path(tmp) / "pixels.raw" - code, out = run(os.path.join(tools, "vk_harness" + EXE), os.path.join(spirv, vertex + ".spv"), - os.path.join(spirv, name + ".spv"), raw, env=env) - if code == UNSUPPORTED: # vk_harness: the shader needs a device feature this GPU lacks - return Skip(""), out - if code or not raw.is_file(): - return None, out - data = raw.read_bytes() - if len(data) != 64 * 64 * 16: # default harness viewport, four 32-bit components per pixel - return None, out - return list(struct.iter_unpack(fmt, data)), out - - -def cbv_modulate_test(tools, spirv): - # Both buffers are in bounds. Word zero of each is a decoy for a lost member offset. - # A third buffer (gain 2) makes reading descriptor 0 observable in either draw. - heap = ("0x1000=0x4000,0x1008=32,0x1018=32," - "0x2000=0x3f800000,0x2010=0x3f000000," - "0x3000=0x3f800000,0x3010=0,0x4010=0x40000000") - for address, gain in ((0x2000, 0.5), (0x3000, 0.0)): - settings = {"VKH_SGPRS": "0x1000,0", "VKH_HEAP": f"{heap},0x1010={address}"} - px, out = pixels(tools, spirv, "ps_cbv_modulate", "<4f", settings=settings) - if isinstance(px, Skip): - return Skip(out.strip() or "unsupported device") - if not px: - return f"gain {gain}: {out.strip() or 'no complete readback'}" - for i, rgba in enumerate(px): - y, x = divmod(i, 64) - expected = ((x + 0.5) / 64 * gain, (y + 0.5) / 64 * gain, gain, 1.0) - # Interpolated colors use the same tolerance as ps_flat. Black, gain and alpha are exact. - tolerance = 1e-6 if gain else 0.0 - if not (abs(rgba[0] - expected[0]) <= tolerance and abs(rgba[1] - expected[1]) <= tolerance - and rgba[2:] == expected[2:]): - return f"gain {gain} at ({x},{y}): got {rgba}, expected {expected}" - return "" - - -def texture_constant_test(tools, spirv, name): - """Compare every pixel returned through vk_texture_test with the fixture reference.""" - expected = TEXTURE_CONSTANTS[name] - shader = os.path.join(spirv, name + ".spv") - if not os.path.isfile(shader): - return f"missing {name}.spv" - with tempfile.TemporaryDirectory(prefix="leonida-gather-") as tmp: - raw = Path(tmp) / "gather.raw" - code, out = run(os.path.join(tools, "vk_texture_test" + EXE), os.path.join(spirv, "vs_ids.spv"), shader, raw, - "0", "92", "c00000", "14500000", "0") - data = raw.read_bytes() if code == 0 and raw.is_file() else b"" - if len(data) != 64 * 64 * 16: - return failure(code, out, 3) - wrong = sum(p != expected for p in struct.iter_unpack("<4f", data)) - return "" if not wrong else f"{wrong} of 4096 pixels differ from {expected}" - - -def texoff_words(px, py, name="ps_texoff"): - """ps_texoff's mrt0 words at pixel (px, py), from the rule in docs/design.md (derivation in ps_texoff.asm). - ps_texoff_forms (image_sample_o, image_sample_b_o, image_gather4_l_o) puts the per-pixel sample in .x and .y and - the same two gathers in .z and .w (derivation in ps_texoff_forms.asm).""" - bx, by = px >> 3, py >> 3 # per-pixel offset (bx - 4, by - 4) from texel (4, 4) - x0, y0 = max(bx - 1, 0), max(by - 1, 0) # gather footprint 3..4 moved by the offset, clamped at 0 - sample = bx | by << 4 - return (sample, sample if name == "ps_texoff_forms" else 0x0761, x0 | bx << 4 | bx << 8 | x0 << 12, - by | by << 4 | y0 << 8 | y0 << 12) - - -# LEONIDA_TEXOFF_FALLBACK=1 (set for build.py too): image_sample*_o was translated with --texel-offset-fallback, so -# ps_texoff runs without VK_KHR_maintenance8 and every offset is defined, whatever the device's texel offset limits. -TEXOFF_FALLBACK = os.environ.get("LEONIDA_TEXOFF_FALLBACK") == "1" - - -def texoff_problem(data, output, all_offsets=None, name="ps_texoff"): - """Judge ps_texoff's 64x64 RGBA32 dump: (failure text or "", what was covered). The +16 / -32 sample (bits 8-15 - of .y) is only defined, and so only judged, where vk_texture_test printed texel offset limits that cover it.""" - m = re.search(r"texel offset limits: (-?\d+)\.\.(-?\d+)", output) - wide = bool(m) and int(m.group(1)) <= -32 and int(m.group(2)) >= 16 - if TEXOFF_FALLBACK if all_offsets is None else all_offsets: - wide = True # the offset is a coordinate shift: no device limit applies - if len(data) != 64 * 64 * 16: - return "vk_texture_test returned an unexpected pixel count", "" - if name == "ps_texoff_forms": - wide = True # every offset there is in -4..3, inside Vulkan's guaranteed -8..7 - keep = (0xFFFFFFFF, 0xFFFFFFFF if wide else 0xFFFF00FF, 0xFFFFFFFF, 0xFFFFFFFF) - px = list(struct.iter_unpack("<4I", data)) - bad = [(i, got) for i, got in enumerate(px) - if any((g ^ w) & k for g, w, k in zip(got, texoff_words(i % 64, i // 64, name), keep))] - limits = f"{m.group(1)}..{m.group(2)}" if m else "unknown" - covered = ("offsets +16/-32 judged" + (" (texel offset fallback)" if wide and not ( - bool(m) and int(m.group(1)) <= -32 and int(m.group(2)) >= 16) else "")) if wide else f"offsets +16/-32 not judged (device texel offset limits {limits})" - if name == "ps_texoff_forms": - covered = "offsets -4..3 on image_sample_o, image_sample_b_o and image_gather4_l_o" - if not bad: - return "", covered - i, got = bad[0] - return (f"{len(bad)} of {len(px)} pixels differ; first at ({i % 64},{i // 64}): got {[hex(x) for x in got]}, " - f"want {[hex(x) for x in texoff_words(i % 64, i // 64, name)]} ({covered})"), covered - - -def texoff_env(base=None): - """vk_texture_test environment for ps_texoff: it needs VK_KHR_maintenance8 unless translated with the fallback.""" - env = dict(base if base is not None else os.environ) - if not TEXOFF_FALLBACK: - env["VKT_NEED_MAINTENANCE8"] = "1" - return env - - -def texoff_test(tools, spirv, name): - """ps_texoff on vk_texture_test (it binds the texture, sampler and descriptor table); vs_ids supplies attr0.""" - with tempfile.TemporaryDirectory(prefix="leonida-pixels-") as tmp: - raw = Path(tmp) / "pixels.raw" - code, out = run(os.path.join(tools, "vk_texture_test" + EXE), os.path.join(spirv, "vs_ids.spv"), - os.path.join(spirv, name + ".spv"), raw, *TEXOFF_ARGS, - env=texoff_env()) - if code == UNSUPPORTED: # vk_texture_test: no VK_KHR_maintenance8 (a non-constant Offset outside gather) - m = re.search(r"unsupported: .*", out) - return Skip(f"SKIP ({m.group(0) if m else 'unsupported device'})") - if code or not raw.is_file(): - return failure(code, out, 2) - return texoff_problem(raw.read_bytes(), out, name=name)[0] - - -def store_words(name): - """The 64 words STORE_WORDS[name] expects in each of STORE_IMAGES: its changes over the tool's fill.""" - return tuple([changed.get(i, fill(i)) for i in range(64)] for changed, fill in zip(STORE_WORDS[name], STORE_FILL)) - - -def store_words_problem(output, name): - """Judge what vk_store_test printed in "words" mode: "" when every image holds store_words(name).""" - for image, want in zip(STORE_IMAGES, store_words(name)): - m = re.search(rf"^{image} words:((?: 0x[0-9a-f]{{8}}){{64}})$", output, re.MULTILINE) - if not m: - return f"vk_store_test printed no {image} words" - got = [int(word, 16) for word in m.group(1).split()] - bad = [i for i in range(64) if got[i] != want[i]] - if bad: - i = bad[0] - return (f"{len(bad)} of 64 {image} words differ; first word {i}: got {got[i]:#010x}, " - f"expected {want[i]:#010x}") - return "" - - -def store_words_test(tools, spirv, name): - """A STORE_WORDS fixture through vk_store_test's "words" mode (it binds the images and prints them).""" - shader = os.path.join(spirv, name + ".spv") - if not os.path.isfile(shader): - return f"missing {name}.spv" - code, out = run(os.path.join(tools, "vk_store_test" + EXE), shader, "words") - if code == UNSUPPORTED: # vk_store_test: the device lacks a feature its images need - m = re.search(r"unsupported: .*", out) - return Skip(f"SKIP ({m.group(0) if m else 'unsupported device'})") - return store_words_problem(out, name) if code == 0 else failure(code, out, 3) - - -def get_lod_problem(data, want): - """Judge one image_get_lod frame: "" when all 4096 RGBA32F pixels are within GET_LOD_TOLERANCE of `want`.""" - if len(data) != 64 * 64 * 16: - return f"expected 4096 RGBA32F pixels, got {len(data)} bytes" - bad, first = 0, "" - for i, pixel in enumerate(struct.iter_unpack("<4f", data)): - if not all(abs(got - expected) <= GET_LOD_TOLERANCE for got, expected in zip(pixel, want)): # a NaN too - if not bad: - first = f"first at ({i % 64},{i // 64}): got {pixel}" - bad += 1 - return f"{bad} of 4096 pixels differ from {want}; {first}" if bad else "" - - -def get_lod_test(tools, spirv, name): - """A GET_LOD_TESTS fixture on vk_texture_test (it binds the textures and the sampler), once per draw.""" - tool = os.path.join(tools, "vk_texture_test" + EXE) - shaders = [os.path.join(spirv, shader + ".spv") for shader in ("vs_ids", name)] - for path in (tool, *shaders): - if not os.path.isfile(path): - return f"missing {os.path.basename(path)}" - with tempfile.TemporaryDirectory(prefix="leonida-lod-") as tmp: - for limits, two_mip, want in GET_LOD_TESTS[name]: - raw = Path(tmp) / f"lod_{limits}.raw" - code, out = run(tool, *shaders, raw, "0", "92", limits, "14500000", "0", - *(["--two-mip"] if two_mip else [])) - if code == UNSUPPORTED: # vk_texture_test: e.g. fewer push constant bytes than the texture tests need - m = re.search(r"unsupported: .*", out) - return Skip(f"SKIP ({m.group(0) if m else 'unsupported device'})") - if code or not raw.is_file(): - return f"S# word 1 {limits}: {failure(code, out, 3)}" - problem = get_lod_problem(raw.read_bytes(), want) - if problem: - return f"S# word 1 {limits}: {problem}" - return "" - - -def texture_mip_mismatch(data: bytes, mip: int, *, transpose_uv: bool = False) -> str: - width = 64 - if len(data) != width**2 * 16: - return f"expected {width**2} RGBA32F pixels, got {len(data)} bytes" - one = 0x3f800000 - quadrants = ((one, 0, 0, one), (0, one, 0, one), - (0, 0, one, one), (one, one, 0, 0)) - for i, actual in enumerate(struct.iter_unpack("<4I", data)): - y, x = divmod(i, width) - # The normalized UV at each pixel center lies within the same quadrant of mip 0. - u, v = (y, x) if transpose_uv else (x, y) - expected = (0, one, one, one) if mip == 1 else quadrants[2 * (v >= width // 2) + (u >= width // 2)] - if actual != expected: - return f"({x},{y}): RGBA32F bits {actual} != {expected}" - return "" - - -def texture_mip_test(tools: str, spirv: str, test: str = TEXTURE_MIP_TEST) -> str: - tool = Path(tools) / ("vk_texture_test" + EXE) - if not tool.is_file(): - return f"missing {tool}" - shaders = Path(spirv) - vertex = shaders / "vs_ids.spv" - with tempfile.TemporaryDirectory(prefix="leonida-mip-") as tmp: - for mip, (name, limits) in enumerate(MIP_TEST_PASSES[test]): - fragment = shaders / (name + ".spv") - for shader in (vertex, fragment): - if not shader.is_file(): - return f"missing {shader}" - raw = Path(tmp) / f"mip{mip}.raw" - mode = MIP_TEST_MODES.get(test, "--two-mip") - code, output = run(tool, vertex, fragment, raw, "0", "92", limits, "14500000", "0", mode) - if code == UNSUPPORTED: - return Skip(f"SKIP (texture mip test: {output.strip() or 'unsupported device'})") - if code or not raw.is_file(): - return f"{name}: {failure(code, output, 4)}" - data = raw.read_bytes() - mismatch = texture_mip_mismatch(data, mip) - if mismatch: - return f"{name}: {mismatch}" - if not texture_mip_mismatch(data, 1 - mip).startswith("(0,0):"): - return f"{name}: wrong mip control missed the expected first pixel" - if mip == 0 and not texture_mip_mismatch(data, mip, transpose_uv=True).startswith("(32,0):"): - return f"{name}: transposed UV control missed the expected first pixel" - return "" - - -def ij_computed_problem(px): - """ps_ij_computed.asm: (snapped 0.5, zeroed pair 0.0, v/2 from (i, j/2), 0.5 control) per pixel; "" when right. - Shared with scripts/run_gpu_tests.py.""" - w = 64 - if len(px) != w * w: - return f"{len(px)} pixels, expected {w * w}" - wrong, err = 0, 0.0 - for i, (a, b, c, d) in enumerate(px): - v_over_two = struct.unpack("= f32(zx2 + zy2): - break - xy = f32(zx * zy) - zx, zy = f32(f32(zx2 - zy2) + cx), f32(f32(xy + xy) + cy) - n += 1 - counts.append(n) - return counts - - -def mandelbrot_problem(px): - """ps_mandelbrot: channel 3 is the lane's iteration count. A lane that leaves EXEC too early or late, or a loop - that ends on the wrong branch, changes counts; the colour channels are only for looking at the frame.""" - w = int(len(px) ** 0.5) - if w * w != len(px): - return f"{len(px)} pixels is not a square frame" - want = mandelbrot_counts(w) - wrong = [(i, p[3], e) for i, (p, e) in enumerate(zip(px, want)) if p[3] != e] - if not wrong: - return "" - i, got, e = wrong[0] - return f"{len(wrong)} of {len(px)} iteration counts differ, e.g. pixel ({i % w}, {i // w}) {got} instead of {e}" - - -def barycentric_problem(px: list[tuple[float, float, float, float]], abs_tol: float) -> str: - """Check ps_bary over the 64-by-64 frame covered by the vs_ids triangle.""" - if len(px) != 64 * 64: - return f"expected 4096 pixels, got {len(px)}" - for index, pixel in enumerate(px): - a, b, _, _ = pixel - if not all(math.isfinite(v) for v in pixel): - return "barycentrics contain non-finite values" - y, x = divmod(index, 64) - # vs_ids exports (0,0), (2,0), (0,2) at the vertices. Check that gradient - # independently so a failure that zeros both interpolation paths is visible. - u, v = (x + 0.5) / 64, (y + 0.5) / 64 - expected = (u, v, a / 2, b / 2) - if any(abs(got - want) > abs_tol for got, want in zip(pixel, expected)): - return f"at ({x},{y}): got {pixel}, expected {expected}" - return "" - - -def nan_payload_problem(px, out): - """Check the exact words, except for the measured KosmicKrisp RGBA32F canonicalization (#3125).""" - if len(px) != 64 * 64: - return f"expected 4096 pixels, got {len(px)}" - want = (0x7fc12345, 0xffc54321, 0x3f800000, 0x3f000000) - canonicalizes = "driver: KosmicKrisp" in out.splitlines() - for i, p in enumerate(px): - if any(actual != expected and not (canonicalizes and c < 2 and actual == 0x7fc00000) - for c, (actual, expected) in enumerate(zip(p, want))): - return f"pixel ({i % 64},{i // 64}) has unexpected words: {[hex(x) for x in p]}" - return "" - - -def pixel_test(tools, spirv, name): - path = os.path.join(spirv, name + ".spv") - if name == "ps_ij_computed" and (BARY_FALLBACK or F16_HALVES): - # Before the .spv check: without PerVertexKHR inputs the translator refuses a computed I/J pair (no .spv). - return Skip("SKIP (computed I/J pairs need PerVertexKHR inputs: no --bary-fallback / --f16-interp-fallback)") - if not os.path.isfile(path): - return f"missing {name}.spv" - if name == "ps_cbv_modulate": - return cbv_modulate_test(tools, spirv) - if name in ("ps_texoff", "ps_texoff_implicit", "ps_texoff_forms"): - return texoff_test(tools, spirv, name) - if name == "ps_interp_f16_high" and BARY_FALLBACK and not F16_HALVES: # with F16_HALVES it reads decoded halves - return Skip("SKIP (per-vertex interpolants need VK_KHR_fragment_shader_barycentric)") - fmt = "<4f" if name in ("ps_bary", "ps_persp_bary") else "<2I2f" if name in ("ps_flat", "ps_uniform_branch", "ps_scc_mask32") else "<4I" - px, out = pixels(tools, spirv, name, fmt, PIXEL_VERTEX.get(name, "vs_ids")) - if isinstance(px, Skip): # exit 77: the device cannot run this shader (e.g. no barycentrics) - m = re.search(r"unsupported: .*", out) - return Skip(f"SKIP ({m.group(0) if m else 'unsupported device'})") - if name == "ps_bitmask_perm": - # Decide from the reported width before the pixel count: a narrow device's frame can be short, and with no - # width line the lanes 0-31 this shader writes are not known to exist. - m = re.search(r"subgroup \d+\.\.(\d+)", out) - if not m: - return Skip("SKIP (vk_harness reported no subgroup width)") - if int(m.group(1)) < 32: - return Skip(f"SKIP (subgroup {m.group(1)} is narrower than 32 lanes)") - if skip := wide_pixel_skip(name, out): - return skip - if name == "ps_vcmpx_forms": - if skip := vcmpx_forms_narrow_skip(out): - return skip - if not px: - return out if out.startswith("could not start") else "vk_harness failed or returned no pixels" - n = len(px) - if name == NAN_PAYLOAD_TEST: - return nan_payload_problem(px, out) - if name in PIXEL_BITS: - wrong = sum(p != PIXEL_BITS[name] for p in px) - return "" if not wrong else f"{wrong} of {n} pixels differ, e.g. {[hex(x) for x in next(p for p in px if p != PIXEL_BITS[name])]}" - if name == "ps_bary": - return barycentric_problem(px, 1e-6) - if name == "ps_persp_bary": - return bary_persp_problem(px) - if name == "ps_flat": - if any(not math.isfinite(v) for p in px for v in p[2:]): - return "UVs contain non-finite values" - w = int(n ** 0.5) - wrong = sum((a, b) != (0x101, 0x102) for a, b, _, _ in px) - err = max(max(abs(u - (i % w + 0.5) / w), abs(v - (i // w + 0.5) / w)) for i, (_, _, u, v) in enumerate(px)) - return "" if not wrong and err < 1e-6 else f"{wrong} pixels without the first vertex's value, uv off by {err:.3g}" - if name == "ps_interp_f16_high": - return interp_f16_high_problem(px) - if name == "ps_ij_computed": - return ij_computed_problem(px) - if name == "ps_bitmask_perm": - if skip := bitmask_perm_narrow_skip(out, px): - return skip - wrong = sum(not (a == lane ^ 9 and b == ((lane & 5) | 16) ^ 1) for lane, a, b, _ in px) - return "" if px and not wrong else f"{wrong} of {len(px)} pixels wrong" - if name == "ps_wqm": # (wqm, own, wqm, own) per pixel, ps_wqm.asm - w = int(n ** 0.5) - wrong = sum(p != (int(i % w % 4 < 2 and i // w % 4 >= 2), int(i % w % 4 == 1 and i // w % 4 == 2)) * 2 for i, p in - enumerate(px)) - return "" if not wrong else f"{wrong} of {n} pixels differ from the whole-quad expectation" - if name in ("ps_uniform_branch", "ps_scc_mask32"): # (s5, own VCC bit): 8 wherever the bit is set, never 7 there - c = collections.Counter((a, b) for a, b, _, _ in px) - fine = c[(8, 1)] and c[(8, 0)] and c[(7, 0)] and set(c) <= {(8, 1), (8, 0), (7, 0)} - return "" if fine else f"(s5, bit) counts {dict(c)}" - if name == "ps_mandelbrot": - return mandelbrot_problem(px) - return "no check written for this shader" - - -def clip_test(tools, spirv, name): - with tempfile.TemporaryDirectory(prefix="leonida-clip-") as tmp: - raw = Path(tmp) / "pixels.raw" - for clip_x, clip_y in ((False, False), (True, False), (False, True), (True, True)): - code, output = run(os.path.join(tools, "vk_harness" + EXE), os.path.join(spirv, name + ".spv"), - os.path.join(spirv, "ps_clip_color.spv"), raw, "64", "64", - "0" if clip_x else "4", "0" if clip_y else "4") - if code == UNSUPPORTED: - return Skip("SKIP (shaderClipDistance unavailable)") - if code: - return failure(code, output, 2) - if not raw.is_file(): - return "missing framebuffer" - data = raw.read_bytes() - raw.unlink() - if len(data) != 64 * 64 * 16: - return "incomplete framebuffer" - clear = (0xbf800000,) * 4 - wrong = 0 - for i, pixel in enumerate(struct.iter_unpack("<4I", data)): - inside = (not clip_x or i % 64 < 32) and (not clip_y or i // 64 < 16) - drawn = inside or name == "vs_clip_undeclared" - wrong += pixel != (PIXEL_BITS["ps_clip_color"] if drawn else clear) - if wrong: - return f"x={clip_x} y={clip_y}: {wrong} of 4096 pixels differ" - return "" - - -def main(): - if any(arg in ("-h", "--help") for arg in sys.argv[1:]): - print(__doc__) - return 0 - if len(sys.argv) < 2: - sys.exit(__doc__) - spirv = os.path.join(sys.argv[1], "spirv") - tools = sys.argv[2] if len(sys.argv) > 2 else os.path.join(HERE, "..", "..", "build") - tools = pick_build_dir(os.path.abspath(tools), tuple(t + EXE for t in TEST_PROGRAMS)) - results = [] - for name, groups, expect in COMPUTE: - results.append((name, compute_test(tools, spirv, name, groups, expect))) - results.append(("cs_wavemask", compute_test(tools, spirv, "cs_wavemask", "1", "wavemask", - require_wave64=not W64_EMULATED))) - for name, want in CS_DUMPS: # all but cs_store need a 64-wide subgroup unless wave64 is emulated - results.append((name, compute_test(tools, spirv, name, "1", "dump", - require_wave64=name not in WAVE32_DUMPS and not W64_EMULATED, - expected_words=want, needs_32_lanes=name in WAVE32_LANE_DUMPS))) - for name, want in BOUNDS: - results.append((name, compute_test(tools, spirv, name, "1", "dump", expected_words=want))) - results.append(("cs_cmpx_class_f32", compute_test(tools, spirv, "cs_cmpx_class_f32", "1", "dump", - expected_words=CMPX_CLASS_WORDS))) - results.append(("cs_fmt_1010102", fmt_1010102_test(tools, spirv))) - results.append(("cs_fmt_sint32", fmt_sint32_test(tools, spirv))) - results.append(("cs_fmt_int_narrow", fmt_int_narrow_test(tools, spirv))) - results.append(("cs_fmt_xy_xyz", fmt_xy_xyz_test(tools, spirv))) - results.append(("cs_fmt_all", fmt_all_test(tools, spirv))) - results.append(("cs_tbuffer_store", tbuffer_store_test(tools, spirv))) - results.append(("cs_fmt_d16_xyz", fmt_d16_xyz_test(tools, spirv))) - for name, groups, want in GLOBAL_OFFSET: - results.append((name, compute_test(tools, spirv, name, groups, "dump", expected_words=want))) - results.append(("cs_user_sgprs", compute_test(tools, spirv, "cs_user_sgprs", "1", "dump", - expected_words=USER_SGPRS_WORDS, env=USER_SGPRS_ENV))) - results.append(("cs_heap_init", compute_test(tools, spirv, "cs_heap_init", "1", "dump", - expected_words=HEAP_INIT_EXPECTED, env=heap_init_env()))) - results.append(("cs_cvt_f32_sat", cvt_f32_sat_test(tools, spirv))) - results.append(("cs_fma_fused", fma_fused_test(tools, spirv))) - results.append(("cs_cvt_pk_u8", compute_test(tools, spirv, "cs_cvt_pk_u8", "1", "dump", - expected_words=CVT_PK_U8_WORDS))) - results.append(("cs_pk_mul_lo_const", compute_test(tools, spirv, "cs_pk_mul_lo_const", "1", "dump", - expected_words=PK_MUL_LO_WORDS))) - for name, want in W64X_DUMPS: # without --require-wave64 when LEONIDA_W64_EMULATE=1 - results.append((name, compute_test(tools, spirv, name, "1", "dump", require_wave64=not W64_EMULATED, - expected_words=want))) - for name, want in W64X_PARTIAL: - results.append((name, partial_wave_test(tools, spirv, name, want))) - results.append(("ms_w64x_ballot", mesh_w64x_test(tools, spirv, "ms_w64x_ballot"))) - results.append(("ms_wave_info_s3", mesh_w64x_test(tools, spirv, "ms_wave_info_s3"))) - with tempfile.TemporaryDirectory(prefix="leonida-mesh-") as tmp: - results.append(("ms_v5_workgroup", mesh_v5_test(tools, spirv, Path(tmp) / "groups.raw"))) - for name, args in (("cs_imgstore", []), ("cs_imgload", ["load"]), ("cs_imgload_tfe", ["load"]), - ("cs_imgload_d16", ["load-d16"]), ("cs_imgload_d16_tfe", ["load-d16"]), - ("cs_sample_lz_int_d16", ["load-d16"])): - code, out = run(os.path.join(tools, "vk_store_test" + EXE), os.path.join(spirv, name + ".spv"), *args) - if code == UNSUPPORTED: # vk_store_test: the device lacks a feature this test needs - m = re.search(r"unsupported: .*", out) - results.append((name, Skip(f"SKIP ({m.group(0) if m else 'unsupported device'})"))) - continue - bad = re.findall(r"(\d+) bad", out) - results.append((name, "" if code == 0 and len(bad) == 3 and set(bad) == {"0"} else failure(code, out, 3))) - for name in STORE_WORDS: # TEST-184: image atomics and image_get_resinfo - results.append((name, store_words_test(tools, spirv, name))) - for name in GET_LOD_TESTS: # TEST-184: image_get_lod, 2D and 2D array - results.append((name, get_lod_test(tools, spirv, name))) - for name in CLIP_TESTS: - results.append((name, clip_test(tools, spirv, name))) - for name in PIXEL_TESTS: - results.append((name, pixel_test(tools, spirv, name))) - for name in TEXTURE_CONSTANTS: - results.append((name, texture_constant_test(tools, spirv, name))) - results.append(("vs_base_ids", base_ids_test(tools, spirv))) - results.append(("ps_tex", bindless_test(tools, spirv))) - results.append(("ps_ssharp", sampler_test(tools, spirv))) - results.append(("ps_imgatomic", bindless_test(tools, spirv, "ps_imgatomic"))) - for name in MIP_TEST_PASSES: - results.append((name, texture_mip_test(tools, spirv, name))) - results.append(("ps_table_fetch", table_fetch_test(tools, spirv))) - for name in GRADIENT_TESTS: - results.append((name, texture_gradient_a16_test(tools, spirv, name))) - for name, problem in results: - if problem is None: - problem = "SKIP (full 64-wide compute subgroups unavailable)" - print(f"{name:20} {'ok' if not problem else problem}") - skipped = sum(p is None or isinstance(p, Skip) for _, p in results) - failed = sum(bool(p) for _, p in results) - sum(isinstance(p, Skip) for _, p in results) - print(f"{len(results) - failed - skipped} of {len(results)} pass, {skipped} skipped") - return 1 if failed else 0 - - -if __name__ == "__main__": - sys.exit(main()) diff --git a/runtime/test/shaders/compute_fixture.py b/runtime/test/shaders/compute_fixture.py deleted file mode 100644 index 9934da957..000000000 --- a/runtime/test/shaders/compute_fixture.py +++ /dev/null @@ -1,102 +0,0 @@ -"""Synthetic FSSM compute headers shared by both GPU test runners.""" -import os -import re -import struct -from pathlib import Path - - -def compute_header(asm_path, shift=0): - # Default: four user SGPRs (V#), TGID_X, 512 bytes LDS, 64 threads. `shift`: see shift_user_data. - rsrc2, group = 0x8088, (64, 1, 1) - for line in Path(asm_path).read_text(encoding="utf-8").splitlines(): - line = line.strip() - if not line: - continue - if not line.startswith(";"): - break - size = re.match(r";\s*group:\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)", line) - if size: - group = tuple(map(int, size.groups())) - elif line[1:].lstrip().startswith("rsrc2:"): - rsrc2 = int(line.split(":", 1)[1].strip(), 0) - header = bytearray(0x148) - struct.pack_into("<4I", header, 0x138, shifted_rsrc2(rsrc2, shift), *group) - return header - - -SGPR_LIMIT = 106 # s0..s105 on GFX10 -_SGPR = re.compile(r"\bs(\d+)\b") -_SGPR_RANGE = re.compile(r"\bs\[(\d+):(\d+)\]") - - -def shift_user_data(text, shift): - """The asm text with every scalar register moved up by `shift` (s[0:3] -> s[4:7] for 4), comments untouched. - - The fixtures here read their user data from s0 (the standalone harnesses push it there). In a D3D12 compute PSO - the console layout starts the root arguments at s4 (rt::rootsig::pack_stage, D3D-448), so a D3D12 test that - reuses such a fixture builds it with LEONIDA_USER_DATA_SHIFT=4: the same program, its user data 4 SGPRs up, and - shifted_rsrc2 moves the user count and the thread-group ids that follow it. Named registers (vcc, exec, m0, - ttmp) don't move. Raises ValueError when a register would pass s105.""" - if shift == 0: - return text - - def one(m): - n = int(m.group(1)) + shift - if n >= SGPR_LIMIT: - raise ValueError(f"s{m.group(1)} + {shift} is past s{SGPR_LIMIT - 1}") - return f"s{n}" - - def pair(m): - lo, hi = int(m.group(1)) + shift, int(m.group(2)) + shift - if hi >= SGPR_LIMIT: - raise ValueError(f"s[{m.group(1)}:{m.group(2)}] + {shift} is past s{SGPR_LIMIT - 1}") - return f"s[{lo}:{hi}]" - - out = [] - for line in text.splitlines(keepends=True): - code, sep, comment = line.partition(";") - code = _SGPR.sub(one, _SGPR_RANGE.sub(pair, code)) - out.append(code + sep + comment) - return "".join(out) - - -def shifted_rsrc2(rsrc2, shift): - """COMPUTE_PGM_RSRC2 with USER_SGPR [5:1] raised by `shift` (the enabled thread-group ids follow it).""" - user = ((rsrc2 >> 1) & 31) + shift - if not 0 <= user <= 31: - raise ValueError(f"USER_SGPR {user} does not fit RSRC2's 5-bit field") - return (rsrc2 & ~(31 << 1)) | (user << 1) - - -def user_data_shift(): - """LEONIDA_USER_DATA_SHIFT as an int (0 when unset); see shift_user_data.""" - text = (os.environ.get("LEONIDA_USER_DATA_SHIFT") or "0").strip() - try: - shift = int(text) - except ValueError: - raise ValueError(f"LEONIDA_USER_DATA_SHIFT must be a whole number, not {text!r}") from None - if not 0 <= shift <= 27: - raise ValueError(f"LEONIDA_USER_DATA_SHIFT {shift} is outside 0..27") - return shift - - -def unpinned_subgroup(out): - """The lane count vk_compute_test was asked for with VKC_SUBGROUP_SIZE and could not pin on this device, or None. - - vk_compute_test then prints "compute subgroup size: N not available" and runs at whatever size the driver picks - (#774); Mesa llvmpipe's only size is 8. A wave32 program's words from such a run say nothing about the translator, - so the fuzzers skip it, as check.py's unpinned_subgroup_skip does for its lane-mask dumps. Output without the line - (the size was pinned, none was asked for, or an older vk_compute_test) gives None.""" - m = re.search(r"^compute subgroup size: (\d+) not available$", out, re.MULTILINE) - return int(m.group(1)) if m else None - - -def find_test_program(build, name): - """The folder holding test program `name`: `build` itself (Ninja, Makefiles) or the RelWithDebInfo/Release - subfolder a Visual Studio build puts it in, as run_gpu_tests.py's find_test_programs looks. None if not built. - A Debug configuration isn't searched (neither does run_gpu_tests.py): GPU fuzzing wants an optimized harness.""" - exe = name + (".exe" if os.name == "nt" else "") - for folder in (build, os.path.join(build, "RelWithDebInfo"), os.path.join(build, "Release")): - if os.path.isfile(os.path.join(folder, exe)): - return folder - return None diff --git a/runtime/test/shaders/cs_barrier_divergent.asm b/runtime/test/shaders/cs_barrier_divergent.asm deleted file mode 100644 index ba89f2e1e..000000000 --- a/runtime/test/shaders/cs_barrier_divergent.asm +++ /dev/null @@ -1,25 +0,0 @@ -; group: 128,1,1 -; SHADER-91: s_barrier in divergent (but wave-uniform) control flow. Wave32, 128 threads = 4 waves. Every thread -; writes its id to LDS[id]; wave 0 then takes one branch with an s_barrier and waves 1-3 another branch with their -; own s_barrier. On RDNA every s_barrier counts against the same workgroup barrier, so the two sites meet and wave 0 -; reads what wave 3 wrote: out[i] = LDS[127 - i] = 127 - i for i = 0..7. In SPIR-V, an OpControlBarrier that not -; every invocation of the workgroup reaches is undefined, which is what the barrier-only scheduler avoids. -; Branch: s_cbranch_scc1 skips the 10 dwords of wave 0's path (checked with llvm-mc -show-encoding). -; Run: vk_compute_test cs_barrier_divergent.spv 1 dump -; Expect: out[0..7] = 127 126 125 124 123 122 121 120 -v_lshlrev_b32_e32 v2, 2, v0 -ds_write_b32 v2, v0 -s_waitcnt lgkmcnt(0) -v_readfirstlane_b32 s5, v0 -s_lshr_b32 s5, s5, 5 -s_cmp_lg_u32 s5, 0 -s_cbranch_scc1 10 -s_barrier -v_sub_nc_u32_e32 v3, 0x1fc, v2 -ds_read_b32 v4, v3 -s_waitcnt lgkmcnt(0) -v_cmpx_gt_u32_e32 8, v0 -buffer_store_dword v4, v2, s[0:3], 0 offen -s_endpgm -s_barrier -s_endpgm diff --git a/runtime/test/shaders/cs_barrier_early_end.asm b/runtime/test/shaders/cs_barrier_early_end.asm deleted file mode 100644 index 9144134d0..000000000 --- a/runtime/test/shaders/cs_barrier_early_end.asm +++ /dev/null @@ -1,22 +0,0 @@ -; group: 128,1,1 -; SHADER-91: a wave that has ended no longer counts at s_barrier. Wave32, 128 threads = 4 waves. Every thread -; writes its id to LDS[id]; waves 1-3 then end without an s_barrier, and wave 0 waits at one. On RDNA the barrier -; releases once the other waves have ended, and wave 0 reads what wave 3 wrote: out[i] = LDS[127 - i] = 127 - i. -; Translated, the s_barrier sits in a branch that only wave 0 takes: Intel's driver loses the device on that -; (an OpControlBarrier outside uniform control flow); barrier rounds keep the barrier at the top level. -; Run: vk_compute_test cs_barrier_early_end.spv 1 dump -; Expect: out[0..7] = 127 126 125 124 123 122 121 120 -v_lshlrev_b32_e32 v2, 2, v0 -ds_write_b32 v2, v0 -s_waitcnt lgkmcnt(0) -v_readfirstlane_b32 s5, v0 -s_lshr_b32 s5, s5, 5 -s_cmp_lg_u32 s5, 0 -s_cbranch_scc1 9 -s_barrier -v_sub_nc_u32_e32 v3, 0x1fc, v2 -ds_read_b32 v4, v3 -s_waitcnt lgkmcnt(0) -v_cmpx_gt_u32_e32 8, v0 -buffer_store_dword v4, v2, s[0:3], 0 offen -s_endpgm diff --git a/runtime/test/shaders/cs_barrier_loop.asm b/runtime/test/shaders/cs_barrier_loop.asm deleted file mode 100644 index 29826d619..000000000 --- a/runtime/test/shaders/cs_barrier_loop.asm +++ /dev/null @@ -1,37 +0,0 @@ -; group: 128,1,1 -; SHADER-91: s_barrier in a loop whose trip count differs per wave. Wave32, 128 threads = 4 waves; wave w runs -; w + 1 iterations. Iteration k adds 1 to LDS[k] from each of the wave's 32 lanes, waits at s_barrier, then -; reads LDS[k] and stores it to out[4 * (3 - w) + k]. On RDNA every s_barrier counts against the same barrier -; and a wave that has ended no longer counts, so the k-th barrier releases once every wave still running has -; added to LDS[k]: LDS[k] = 32 * (4 - k) when read. Wave 3 stores out[0..3] and wave 2 out[4..6]; out[7] would -; be wave 2's fourth iteration, which it doesn't run, so it keeps the sentinel 0xeeeeeeee. -; Run: vk_compute_test cs_barrier_loop.spv 1 dump -; Expect: out[0..7] = 128 96 64 32 128 96 64 4008636142 -v_lshlrev_b32_e32 v2, 2, v0 -v_mov_b32_e32 v3, 0 -v_cmpx_gt_u32_e32 4, v0 -ds_write_b32 v2, v3 -s_mov_b32 exec_lo, -1 -s_waitcnt lgkmcnt(0) -s_barrier -v_readfirstlane_b32 s5, v0 -s_lshr_b32 s5, s5, 5 -s_add_u32 s6, s5, 1 -s_sub_u32 s9, 3, s5 -s_lshl_b32 s9, s9, 4 -s_mov_b32 s7, 0 -v_mov_b32_e32 v5, 1 -v_mov_b32_e32 v1, s7 -ds_add_u32 v1, v5 -s_waitcnt lgkmcnt(0) -s_barrier -ds_read_b32 v4, v1 -s_waitcnt lgkmcnt(0) -s_add_u32 s10, s9, s7 -v_mov_b32_e32 v6, s10 -buffer_store_dword v4, v6, s[0:3], 0 offen -s_add_u32 s7, s7, 4 -s_sub_u32 s6, s6, 1 -s_cmp_lg_u32 s6, 0 -s_cbranch_scc1 -16 -s_endpgm diff --git a/runtime/test/shaders/cs_bench_mix.asm b/runtime/test/shaders/cs_bench_mix.asm deleted file mode 100644 index 111c505b6..000000000 --- a/runtime/test/shaders/cs_bench_mix.asm +++ /dev/null @@ -1,44 +0,0 @@ -; Benchmark (not a pass/fail test): a realistic wave64 mix, timed by scripts/bench_wave64.py. Per lane: a hash, a ballot + -; v_mbcnt_lo/hi stream-compaction slot and s_bcnt1 count, v_readlane of lane 37, three wave branches (vcc / exec), an LDS -; write then a read of a neighbour's slot with no barrier in between (same wave), then one store of the result. -; Every dispatch writes the same bytes: out[g*64 + lane], so the output of any configuration can be compared with another. -; Run: vk_compute_test cs_bench_mix.spv 16384 dump (VKC_BENCH=N adds N timed dispatches) -; mattr: +wavefrontsize64,-wavefrontsize32 -v_mbcnt_lo_u32_b32 v1, -1, 0 -v_mbcnt_hi_u32_b32 v1, -1, v1 -v_lshl_add_u32 v10, s4, 6, v1 -v_mul_lo_u32 v2, v10, 0x9e3779b1 -v_xor_b32_e32 v2, v2, v10 -v_and_b32_e32 v3, 3, v2 -v_cmp_eq_u32_e64 s[6:7], 1, v3 -s_bcnt1_i32_b64 s8, s[6:7] -v_mbcnt_lo_u32_b32 v4, s6, 0 -v_mbcnt_hi_u32_b32 v4, s7, v4 -v_readlane_b32 s9, v2, 37 -v_add_nc_u32_e32 v5, v4, v2 -v_add_nc_u32_e32 v5, s9, v5 -v_add_nc_u32_e32 v5, s8, v5 -v_lshlrev_b32_e32 v6, 2, v1 -ds_write_b32 v6, v5 -s_waitcnt lgkmcnt(0) -v_xor_b32_e32 v8, 1, v1 -v_lshlrev_b32_e32 v8, 2, v8 -ds_read_b32 v7, v8 -s_waitcnt lgkmcnt(0) -v_add_nc_u32_e32 v5, v5, v7 -v_cmp_gt_u32_e32 vcc, 0x80000000, v2 -s_cbranch_vccz 2 -v_add_nc_u32_e32 v5, 1, v5 -v_add_nc_u32_e32 v5, 2, v5 -v_cmp_gt_u32_e32 vcc, 0x7fffffff, v5 -s_cbranch_vccnz 1 -v_xor_b32_e32 v5, 5, v5 -v_cmp_lt_u32_e64 s[10:11], 0x40000000, v2 -s_and_saveexec_b64 s[12:13], s[10:11] -s_cbranch_execz 2 -v_add_nc_u32_e32 v5, 7, v5 -v_xor_b32_e32 v5, v5, v10 -s_mov_b64 exec, s[12:13] -v_lshlrev_b32_e32 v9, 2, v10 -buffer_store_dword v5, v9, s[0:3], 0 offen -s_endpgm diff --git a/runtime/test/shaders/cs_bounds.asm b/runtime/test/shaders/cs_bounds.asm deleted file mode 100644 index 124a0c68b..000000000 --- a/runtime/test/shaders/cs_bounds.asm +++ /dev/null @@ -1,25 +0,0 @@ -; regen_fixtures: this source has a translator fixture in tests/semantic/fixtures/disasm -; num_records bounds checking: s[0:3] has base 0, stride 0, num_records = 16 (bytes 0..15), word3 0x31016fac (OOB_SELECT RAW). -; Thread 0 writes 0x12345678 to offset 0 (in-bounds), attempts write 0xdeadbeef to offset 16 (OOB, ignored), -; loads offset 0 (0x12345678) into offset 4, and loads offset 16 (OOB -> 0) into offset 8. -; Run: vk_compute_test cs_bounds.spv 1 dump -> out[0..3] = 0x12345678 0x12345678 0x00000000 0xeeeeeeee -v_cmpx_eq_u32_e32 0, v0 -s_mov_b32 s4, 0 -s_mov_b32 s5, 0 -s_mov_b32 s6, 16 -s_mov_b32 s7, 0x31016fac -v_mov_b32 v1, 0x12345678 -v_mov_b32 v2, 0 -buffer_store_dword v1, v2, s[4:7], 0 offen -v_mov_b32 v3, 0xdeadbeef -v_mov_b32 v4, 16 -buffer_store_dword v3, v4, s[4:7], 0 offen -s_waitcnt vmcnt(0) -buffer_load_dword v5, v2, s[4:7], 0 offen -buffer_load_dword v6, v4, s[4:7], 0 offen -s_waitcnt vmcnt(0) -v_mov_b32 v7, 4 -v_mov_b32 v8, 8 -buffer_store_dword v5, v7, s[0:3], 0 offen -buffer_store_dword v6, v8, s[0:3], 0 offen -s_endpgm diff --git a/runtime/test/shaders/cs_bpermute32.asm b/runtime/test/shaders/cs_bpermute32.asm deleted file mode 100644 index a9578c2b5..000000000 --- a/runtime/test/shaders/cs_bpermute32.asm +++ /dev/null @@ -1,66 +0,0 @@ -; Wave32 ds_bpermute_b32: RDNA2 ISA 10.4.4 - EXEC is honoured for both reading the source and writing the destination, -; reading from a disabled lane returns zero, and only index bits [6:2] are used (src lane = (addr / 4) & 31). -; A translator that shuffles the raw value hands a disabled source lane's data to the reader instead of 0. -; v2 = 7 * lane + 1 (data), v6 preset to 99. -; (a) EXEC = all but lanes 8-15, addr = (lane + 3) * 4, src = (lane + 3) & 31: -; lane 6 -> 9 (disabled) -> 0. Lane 4 -> 7 -> 50. Lane 20 -> 23 -> 162. Lane 2 -> 5 -> 36. -; Lane 31 -> 34 & 31 = 2 -> 15. Lane 10 is disabled: its destination keeps 99. -; (b) full EXEC, addr = (63 - lane) * 4, index 32..63 wraps: src = 31 - lane. Lane 0 -> 31 -> 218. Lane 5 -> 26 -> 183. -; out[0..7] = (a) lane 6, 4, 20; (a) lane 10; (a) lane 2; (b) lane 0, 5; (a) lane 31. -; Run: vk_compute_test cs_bpermute32.spv 1 dump -; -> out[0..7] = 0 50 162 99 36 218 183 15 -; mattr: -wavefrontsize64,+wavefrontsize32 -; group: 32,1,1 -v_mbcnt_lo_u32_b32 v1, -1, 0 -v_mad_u32_u24 v2, v1, 7, 1 -v_add_nc_u32_e32 v3, 3, v1 -v_lshlrev_b32_e32 v3, 2, v3 -v_sub_nc_u32_e32 v5, 63, v1 -v_lshlrev_b32_e32 v5, 2, v5 -v_mov_b32_e32 v6, 99 -s_mov_b32 exec_lo, 0xffff00ff -ds_bpermute_b32 v6, v3, v2 -s_waitcnt lgkmcnt(0) -s_mov_b32 exec_lo, -1 -ds_bpermute_b32 v7, v5, v2 -s_waitcnt lgkmcnt(0) -v_cmpx_eq_u32_e32 6, v1 -v_mov_b32_e32 v20, v6 -v_mov_b32_e32 v21, 0 -buffer_store_dword v20, v21, s[0:3], 0 offen -s_mov_b32 exec_lo, -1 -v_cmpx_eq_u32_e32 4, v1 -v_mov_b32_e32 v20, v6 -v_mov_b32_e32 v21, 4 -buffer_store_dword v20, v21, s[0:3], 0 offen -s_mov_b32 exec_lo, -1 -v_cmpx_eq_u32_e32 20, v1 -v_mov_b32_e32 v20, v6 -v_mov_b32_e32 v21, 8 -buffer_store_dword v20, v21, s[0:3], 0 offen -s_mov_b32 exec_lo, -1 -v_cmpx_eq_u32_e32 10, v1 -v_mov_b32_e32 v20, v6 -v_mov_b32_e32 v21, 12 -buffer_store_dword v20, v21, s[0:3], 0 offen -s_mov_b32 exec_lo, -1 -v_cmpx_eq_u32_e32 2, v1 -v_mov_b32_e32 v20, v6 -v_mov_b32_e32 v21, 16 -buffer_store_dword v20, v21, s[0:3], 0 offen -s_mov_b32 exec_lo, -1 -v_cmpx_eq_u32_e32 0, v1 -v_mov_b32_e32 v20, v7 -v_mov_b32_e32 v21, 20 -buffer_store_dword v20, v21, s[0:3], 0 offen -s_mov_b32 exec_lo, -1 -v_cmpx_eq_u32_e32 5, v1 -v_mov_b32_e32 v20, v7 -v_mov_b32_e32 v21, 24 -buffer_store_dword v20, v21, s[0:3], 0 offen -s_mov_b32 exec_lo, -1 -v_cmpx_eq_u32_e32 31, v1 -v_mov_b32_e32 v20, v6 -v_mov_b32_e32 v21, 28 -buffer_store_dword v20, v21, s[0:3], 0 offen -s_endpgm diff --git a/runtime/test/shaders/cs_buf_counter.asm b/runtime/test/shaders/cs_buf_counter.asm deleted file mode 100644 index af5268034..000000000 --- a/runtime/test/shaders/cs_buf_counter.asm +++ /dev/null @@ -1,43 +0,0 @@ -; group: 64,1,1 -; rsrc2: 0x808c -; fssm-at: 0x150 -; fssm-data: 0x4e554f43 0x3d524554 -; UAV counters (D3D12 CreateUnorderedAccessView with pCounterResource): AppendStructuredBuffer and -; ConsumeStructuredBuffer as hand-written RDNA2, the way docs/d3d12_vulkan.md section 3.4 describes the contract: -; the counter is a second, raw 4-byte V# in the upper 16 bytes of the view's descriptor slot, and append and consume -; are buffer atomics on it. Run: d3d12_buffer_uav_test (a compute PSO found by the SHA-256 of its synthetic FSSM header). -; The branch skips the 10 dwords of the append path (checked with llvm-mc -show-encoding). -; User data, from the root signature: [0] four 32-bit constants, [1] a descriptor table of six UAVs, TGID_X in s6: -; s0 = mode: 0 append, 1 consume s[4:5] = console VA of the table's first slot (32 bytes a slot) -; slot 0 (+0x00): V#, structured buffer, stride 8, 256 records; the counter V# in +0x10 (raw, 4 bytes) -; slot 1 (+0x20): V#, raw buffer, 128 records of 8 bytes (written by consume) -; D3D12 build: runtime/cmake/d3d12_vulkan.cmake builds this with LEONIDA_USER_DATA_SHIFT=4, so in the PSO every SGPR -; named here is 4 higher (the console compute layout starts the root arguments at s4, D3D-448). The table pointer -; then reads s[8:9]: s8 is the table's 32-bit VA and s9 a user dword the runtime leaves zero. -; g = 64 * group + lane -; append: i = counter++ (buffer_atomic_add, glc returns the old value); record i = { g, g * 3 + 1 } -; consume: i = --counter (the old value of buffer_atomic_sub, minus one); out[g] = record i -s_load_dwordx8 s[8:15], s[4:5], 0x0 -s_load_dwordx4 s[16:19], s[4:5], 0x20 -s_lshl_b32 s7, s6, 6 -s_waitcnt lgkmcnt(0) -v_add_nc_u32_e32 v1, s7, v0 -v_mov_b32_e32 v2, 1 -s_cmp_eq_u32 s0, 0 -s_cbranch_scc0 10 -buffer_atomic_add v2, off, s[12:15], 0 glc -s_waitcnt vmcnt(0) -v_mul_lo_u32 v6, v1, 3 -v_add_nc_u32_e32 v6, 1, v6 -v_mov_b32_e32 v5, v1 -buffer_store_dwordx2 v[5:6], v2, s[8:11], 0 idxen -s_endpgm -; consume: -buffer_atomic_sub v2, off, s[12:15], 0 glc -s_waitcnt vmcnt(0) -v_add_nc_u32_e32 v2, -1, v2 -buffer_load_dwordx2 v[5:6], v2, s[8:11], 0 idxen -s_waitcnt vmcnt(0) -v_lshlrev_b32_e32 v7, 3, v1 -buffer_store_dwordx2 v[5:6], v7, s[16:19], 0 offen -s_endpgm diff --git a/runtime/test/shaders/cs_buf_fmt8.asm b/runtime/test/shaders/cs_buf_fmt8.asm deleted file mode 100644 index 120eba435..000000000 --- a/runtime/test/shaders/cs_buf_fmt8.asm +++ /dev/null @@ -1,46 +0,0 @@ -; TEST-510: GFX10_FORMAT_8_UINT (code 5) loads on the GPU (docs/design.md, "Sub-dword MUBUF loads and -; GFX10_FORMAT_8_UINT"; CPU-checked by tests/semantic/test_buffer_load_sub.py). Thread 0 seeds heap bytes 0x40..0x43 -; with 7f 80 ff 01. Every V# has base 0x40, stride 0, NUM_RECORDS 4 and OOB_SELECT 3 (RAW). Words, in out[0..7]: -; 0..3 tbuffer_load_format_x format:[BUF_FMT_8_UINT] at 0..3, V# format 20 (32_UINT): the instruction's own format -; is used, one byte zero-extended: 0x7f 0x80 0xff 0x01 -; 4 the same at 4: 4 + 1 > 4 -> 0 -; 5 the same at 1 with V# format 0 (INVALID): an MTBUF load of an invalid V# reads 0 even in range -; 6, 7 buffer_load_format_xyzw at 2 with V# format 5 (8_UINT) and DST_SEL (X, 0, 1, 1): x = 0xff and w = integer 1 -; (not 1.0f, 0x3f800000) -; One thread, no wave64 requirement. -; Run: vk_compute_test cs_buf_fmt8.spv 1 dump -> out[0..7] = 0x0000007f 0x00000080 0x000000ff 0x00000001 0x00000000 -; 0x00000000 0x000000ff 0x00000001 (127 128 255 1 0 0 255 1). -v_cmpx_eq_u32_e32 0, v0 -v_mov_b32 v1, 0x01ff807f -buffer_store_dword v1, off, s[0:3], 0 offset:64 -s_waitcnt vmcnt(0) -s_mov_b32 s4, 0x40 -s_mov_b32 s5, 0 -s_mov_b32 s6, 4 -s_mov_b32 s7, 0x31014fac -s_mov_b32 s8, 0x40 -s_mov_b32 s9, 0 -s_mov_b32 s10, 4 -s_mov_b32 s11, 0x31000fac -s_mov_b32 s12, 0x40 -s_mov_b32 s13, 0 -s_mov_b32 s14, 4 -s_mov_b32 s15, 0x31005244 -v_mov_b32 v20, 0 -v_mov_b32 v21, 1 -v_mov_b32 v22, 2 -v_mov_b32 v23, 3 -v_mov_b32 v24, 4 -tbuffer_load_format_x v10, v20, s[4:7], 0 format:[BUF_FMT_8_UINT] offen -tbuffer_load_format_x v11, v21, s[4:7], 0 format:[BUF_FMT_8_UINT] offen -tbuffer_load_format_x v12, v22, s[4:7], 0 format:[BUF_FMT_8_UINT] offen -tbuffer_load_format_x v13, v23, s[4:7], 0 format:[BUF_FMT_8_UINT] offen -tbuffer_load_format_x v14, v24, s[4:7], 0 format:[BUF_FMT_8_UINT] offen -tbuffer_load_format_x v15, v21, s[8:11], 0 format:[BUF_FMT_8_UINT] offen -buffer_load_format_xyzw v[30:33], v22, s[12:15], 0 offen -s_waitcnt vmcnt(0) -v_mov_b32 v16, v30 -v_mov_b32 v17, v33 -buffer_store_dwordx4 v[10:13], off, s[0:3], 0 -buffer_store_dwordx4 v[14:17], off, s[0:3], 0 offset:16 -s_endpgm diff --git a/runtime/test/shaders/cs_buf_load_sub.asm b/runtime/test/shaders/cs_buf_load_sub.asm deleted file mode 100644 index 48ffd4e47..000000000 --- a/runtime/test/shaders/cs_buf_load_sub.asm +++ /dev/null @@ -1,44 +0,0 @@ -; TEST-510: sub-dword MUBUF loads on the GPU (docs/design.md, "Sub-dword MUBUF loads and GFX10_FORMAT_8_UINT"; -; CPU-checked by tests/semantic/test_buffer_load_sub.py). Thread 0 seeds heap bytes 0x40..0x47 with 7f 80 ff 01 ab cd -; 00 fe; the heap is 0xee-filled past them. The V# has base 0x40, stride 0, NUM_RECORDS 8 and OOB_SELECT 3 (RAW: an -; element is in range when offset + size <= NUM_RECORDS; out of range reads 0 without touching memory). Words, in -; out[0..7]: -; 0 buffer_load_ubyte at 1: 0x80 zero-extended -; 1 buffer_load_sbyte at 1: 0x80 -> 0xffffff80 sign-extended -; 2 buffer_load_ushort at 2: ff 01 -> 0x01ff -; 3 buffer_load_sshort at 0: 7f 80 -> 0xffff807f -; 4 buffer_load_ushort at 3: 01 ab -> 0xab01 crosses into the next dword (3 + 2 <= 8) -; 5 buffer_load_sshort at 5: cd 00 -> 0x000000cd positive, no sign bits -; 6 buffer_load_ubyte at 8: 8 + 1 > 8 -> 0 -; 7 buffer_load_ushort at 7: 7 + 2 > 8 -> 0 a start-only check would read fe ee -> 0xeefe -; One thread, no wave64 requirement. -; Run: vk_compute_test cs_buf_load_sub.spv 1 dump -> out[0..7] = 0x00000080 0xffffff80 0x000001ff 0xffff807f -; 0x0000ab01 0x000000cd 0x00000000 0x00000000 (128 4294967168 511 4294934655 43777 205 0 0). -v_cmpx_eq_u32_e32 0, v0 -v_mov_b32 v1, 0x01ff807f -v_mov_b32 v2, 0xfe00cdab -buffer_store_dwordx2 v[1:2], off, s[0:3], 0 offset:64 -s_waitcnt vmcnt(0) -s_mov_b32 s4, 0x40 -s_mov_b32 s5, 0 -s_mov_b32 s6, 8 -s_mov_b32 s7, 0x31016fac -v_mov_b32 v20, 1 -v_mov_b32 v21, 2 -v_mov_b32 v22, 0 -v_mov_b32 v23, 3 -v_mov_b32 v24, 5 -v_mov_b32 v25, 8 -v_mov_b32 v26, 7 -buffer_load_ubyte v10, v20, s[4:7], 0 offen -buffer_load_sbyte v11, v20, s[4:7], 0 offen -buffer_load_ushort v12, v21, s[4:7], 0 offen -buffer_load_sshort v13, v22, s[4:7], 0 offen -buffer_load_ushort v14, v23, s[4:7], 0 offen -buffer_load_sshort v15, v24, s[4:7], 0 offen -buffer_load_ubyte v16, v25, s[4:7], 0 offen -buffer_load_ushort v17, v26, s[4:7], 0 offen -s_waitcnt vmcnt(0) -buffer_store_dwordx4 v[10:13], off, s[0:3], 0 -buffer_store_dwordx4 v[14:17], off, s[0:3], 0 offset:16 -s_endpgm diff --git a/runtime/test/shaders/cs_buf_swizzle.asm b/runtime/test/shaders/cs_buf_swizzle.asm deleted file mode 100644 index acfb09ac9..000000000 --- a/runtime/test/shaders/cs_buf_swizzle.asm +++ /dev/null @@ -1,90 +0,0 @@ -; regen_fixtures: this source has a translator fixture in tests/semantic/fixtures/disasm -; Swizzled MUBUF addressing and ADD_TID_ENABLE (docs/design.md, Swizzled buffer addressing). Measured natively on -; RDNA2 (gfx1036, wave32 & wave64): SWIZZLE_ENABLE = word1 bit 31, STRIDE = word1 [29:16], INDEX_STRIDE = word3 [22:21] -; (IS = 8 << n), ADD_TID_ENABLE = word3 bit 23: -; index = idxen ? vindex : (ADD_TID_ENABLE ? lane : 0), offset = uint32((offen ? vaddr : 0) + inst_offset) -; buffer_offset = (index / IS * stride + (offset & ~3)) * IS + (index % IS) * 4 + (offset & 3), address = base + -; soffset + buffer_offset (IS = index_stride). With idxen=1, multi-dword accesses step linearly by +4 bytes; with -; idxen=0 and ADD_TID_ENABLE=1 (scratch swizzle), raw multi-dword accesses step by 4 * IS. OOB_SELECT 3 with active -; swizzle and stride != 0 checks (index + soffset) >= NUM_RECORDS or offset + payload > stride. -; Thread 0 seeds heap bytes 0x40..0x8f (region offset X = byte 0x40 + X) with 0x5eed0000 + X; the heap is 0xee-filled, -; so an in-range access past the seed reads 0xeeeeeeee. V# A (s[4:7], literal): base 0x40, swizzled, stride 8, NR 16, -; IS 8, OOB_SELECT 3. V# B (s[8:11], words 1 and 3 or-ed at run time): base 0x40, swizzled, stride 8, NR 8, IS 16, -; OOB_SELECT 0. V# C (s[12:15], literal): base 0x18 (out[6]), linear, stride 4, NR 2, ADD_TID, OOB_SELECT 1. -; Words, in out[0..7] (in brackets what an unswizzled translation reads): -; 0 A, idx 1, off 4: (0 * 8 + 4) * 8 + 1 * 4 = X 0x24: 0x5eed0024 [X 0xc] -; 1 A, idx 9, off 0: (1 * 8 + 0) * 8 + 1 * 4 = X 0x44: 0x5eed0044 [X 0x48] -; 2 B, idx 3, off 4: (0 * 8 + 4) * 16 + 3 * 4 = X 0x4c: 0x5eed004c [X 0x1c] -; 3 A x2, idx 2, off 0, dword 0: 0 * 8 + 2 * 4 = X 0x8: 0x5eed0008 [X 0x10] -; 4 A x2, idx 2, dword 1 (idxen=1 steps linearly +4): X 0x8 + 4 = X 0xc: 0x5eed000c [X 0x14] -; 5 A, idx 16, off 0: 16 >= NR 16 -> 0 (the raw check, 4 <= 16, reads X 0x80 past the seed: 0xeeeeeeee) -; 6, 7 lanes 0 and 1 store 0xbeef0000 + lane through C: address 0x18 + lane * 4 -> 0xbeef0000 0xbeef0001 -; (without ADD_TID both lanes store to out[6], and out[7] keeps 0xeeeeeeee) -; Lanes 0 and 1 only store (no lane reads what another wrote); thread 0 alone seeds and loads. No wave64 requirement. -; Run: vk_compute_test cs_buf_swizzle.spv 1 dump -> out[0..7] = 0x5eed0024 0x5eed0044 0x5eed004c 0x5eed0008 -; 0x5eed000c 0x00000000 0xbeef0000 0xbeef0001 (1592590372 1592590404 1592590412 1592590344 1592590348 0 3203334144 -; 3203334145). -v_cmpx_gt_u32_e32 2, v0 -s_mov_b32 s12, 0x18 -s_mov_b32 s13, 0x40000 -s_mov_b32 s14, 2 -s_mov_b32 s15, 0x11816fac -v_or_b32_e32 v40, 0xbeef0000, v0 -buffer_store_dword v40, off, s[12:15], 0 -s_waitcnt vmcnt(0) -v_cmpx_eq_u32_e32 0, v0 -v_mov_b32 v1, 0x5eed0000 -v_mov_b32 v2, 0x5eed0004 -v_mov_b32 v3, 0x5eed0008 -v_mov_b32 v4, 0x5eed000c -buffer_store_dwordx4 v[1:4], off, s[0:3], 0 offset:64 -v_mov_b32 v1, 0x5eed0010 -v_mov_b32 v2, 0x5eed0014 -v_mov_b32 v3, 0x5eed0018 -v_mov_b32 v4, 0x5eed001c -buffer_store_dwordx4 v[1:4], off, s[0:3], 0 offset:80 -v_mov_b32 v1, 0x5eed0020 -v_mov_b32 v2, 0x5eed0024 -v_mov_b32 v3, 0x5eed0028 -v_mov_b32 v4, 0x5eed002c -buffer_store_dwordx4 v[1:4], off, s[0:3], 0 offset:96 -v_mov_b32 v1, 0x5eed0030 -v_mov_b32 v2, 0x5eed0034 -v_mov_b32 v3, 0x5eed0038 -v_mov_b32 v4, 0x5eed003c -buffer_store_dwordx4 v[1:4], off, s[0:3], 0 offset:112 -v_mov_b32 v1, 0x5eed0040 -v_mov_b32 v2, 0x5eed0044 -v_mov_b32 v3, 0x5eed0048 -v_mov_b32 v4, 0x5eed004c -buffer_store_dwordx4 v[1:4], off, s[0:3], 0 offset:128 -s_waitcnt vmcnt(0) -s_mov_b32 s4, 0x40 -s_mov_b32 s5, 0x80080000 -s_mov_b32 s6, 16 -s_mov_b32 s7, 0x31016fac -s_mov_b32 s8, 0x40 -s_mov_b32 s9, 0x80000 -s_mov_b32 s20, 0x80000000 -s_or_b32 s9, s9, s20 -s_mov_b32 s10, 8 -s_mov_b32 s11, 0x01216fac -s_mov_b32 s21, 0 -s_or_b32 s11, s11, s21 -v_mov_b32 v20, 1 -v_mov_b32 v21, 4 -v_mov_b32 v22, 9 -v_mov_b32 v23, 0 -v_mov_b32 v24, 3 -v_mov_b32 v25, 4 -v_mov_b32 v26, 2 -v_mov_b32 v27, 16 -buffer_load_dword v10, v[20:21], s[4:7], 0 idxen offen -buffer_load_dword v11, v[22:23], s[4:7], 0 idxen offen -buffer_load_dword v12, v[24:25], s[8:11], 0 idxen offen -buffer_load_dwordx2 v[13:14], v26, s[4:7], 0 idxen -buffer_load_dword v15, v27, s[4:7], 0 idxen -s_waitcnt vmcnt(0) -buffer_store_dwordx4 v[10:13], off, s[0:3], 0 -buffer_store_dwordx2 v[14:15], off, s[0:3], 0 offset:16 -s_endpgm diff --git a/runtime/test/shaders/cs_buf_tail.asm b/runtime/test/shaders/cs_buf_tail.asm deleted file mode 100644 index 353711d4a..000000000 --- a/runtime/test/shaders/cs_buf_tail.asm +++ /dev/null @@ -1,46 +0,0 @@ -; regen_fixtures: this source has a translator fixture in tests/semantic/fixtures/disasm -; Raw MUBUF loads (stride 0) check every dword against NUM_RECORDS on its own: dword i of a load at byte offset -; O = inst_offset + soffset + vaddr is data when O + 4*i + 4 <= NUM_RECORDS, else 0. Measured on an AMD Radeon -; RX 6800 (gfx1030) as a raw compute kernel with V# word3 OOB_SELECT 3 (docs/design.md, Buffer bounds checking). -; Only dword-aligned offsets here: the unaligned rows of the measurement are in tests/semantic. -; Thread 0 seeds heap bytes 0x40..0x5f (region offset X = byte 0x40 + X) with 0x5eed0000 + X, then loads through -; V#s it builds itself (base 0x40, stride 0, word3 0x31016fac): -; buffer_load_dword v10, v5=0x10 offen, NR 0x12 -> 0x14 > 0x12: 0 (start-only check: 0x5eed0010) -; buffer_load_dword v11, v6=0xc offen, NR 0x12 -> 0x10 <= 0x12: 0x5eed000c -; buffer_load_dwordx4 v[12:15], v7=8 offen, NR 0x12 -> 8, 0xc in; 0x10, 0x14 out: data, data, 0, 0 -; buffer_load_dwordx2 v[16:17], off, s20=4 offset:0xc, NR 0x17 -> O 0x10: 0x14 <= 0x17 data, 0x18 > 0x17: 0 -; and writes v10..v17 to out[0..7]. -; Run: vk_compute_test cs_buf_tail.spv 1 dump -> out[0..7] = 0x00000000 0x5eed000c 0x5eed0008 0x5eed000c -; 0x00000000 0x00000000 0x5eed0010 0x00000000 (0 1592590348 1592590344 1592590348 0 0 1592590352 0). -v_cmpx_eq_u32_e32 0, v0 -v_mov_b32 v1, 0x5eed0000 -v_mov_b32 v2, 0x5eed0004 -v_mov_b32 v3, 0x5eed0008 -v_mov_b32 v4, 0x5eed000c -buffer_store_dwordx4 v[1:4], off, s[0:3], 0 offset:64 -v_mov_b32 v1, 0x5eed0010 -v_mov_b32 v2, 0x5eed0014 -v_mov_b32 v3, 0x5eed0018 -v_mov_b32 v4, 0x5eed001c -buffer_store_dwordx4 v[1:4], off, s[0:3], 0 offset:80 -s_waitcnt vmcnt(0) -s_mov_b32 s4, 0x40 -s_mov_b32 s5, 0 -s_mov_b32 s6, 0x12 -s_mov_b32 s7, 0x31016fac -s_mov_b32 s8, 0x40 -s_mov_b32 s9, 0 -s_mov_b32 s10, 0x17 -s_mov_b32 s11, 0x31016fac -s_mov_b32 s20, 4 -v_mov_b32 v5, 0x10 -v_mov_b32 v6, 0xc -v_mov_b32 v7, 8 -buffer_load_dword v10, v5, s[4:7], 0 offen -buffer_load_dword v11, v6, s[4:7], 0 offen -buffer_load_dwordx4 v[12:15], v7, s[4:7], 0 offen -buffer_load_dwordx2 v[16:17], off, s[8:11], s20 offset:12 -s_waitcnt vmcnt(0) -buffer_store_dwordx4 v[10:13], off, s[0:3], 0 -buffer_store_dwordx4 v[14:17], off, s[0:3], 0 offset:16 -s_endpgm diff --git a/runtime/test/shaders/cs_buf_typed.asm b/runtime/test/shaders/cs_buf_typed.asm deleted file mode 100644 index fc6ac1172..000000000 --- a/runtime/test/shaders/cs_buf_typed.asm +++ /dev/null @@ -1,66 +0,0 @@ -; group: 64,1,1 -; rsrc2: 0x808c -; fssm-at: 0x150 -; fssm-data: 0x44505954 0x3d424655 -; Typed buffer UAVs (D3D12 CreateUnorderedAccessView with a Format on a BUFFER view): hand-written RDNA2 the way a -; translated `RWBuffer` shader reads and writes them. Run: d3d12_buffer_uav_test (a compute PSO found by the -; SHA-256 of its synthetic FSSM header, as for the other cs_ shaders). -; User data, from the root signature: [0] four 32-bit constants, [1] a descriptor table of six UAVs. RSRC2 0x808c = -; D3D12 build: runtime/cmake/d3d12_vulkan.cmake builds this with LEONIDA_USER_DATA_SHIFT=4, so in the PSO every SGPR -; named here is 4 higher (the console compute layout starts the root arguments at s4, D3D-448). The table pointer -; then reads s[8:9]: s8 is the table's 32-bit VA and s9 a user dword the runtime leaves zero. -; six user SGPRs and TGID_X, so the group index is s6: -; s0 = seed s1 = multiplier s[4:5] = console VA of the table's first slot (a slot is 32 bytes, a V# in its first 16) -; slot 0 (+0x00): V#, typed R32_UINT, 240 elements of a 256-element buffer (written, then atomically added to) -; slot 1 (+0x20): V#, typed R16G16B16A16_FLOAT, 256 elements (written) -; slot 2 (+0x40): V#, typed R8G8B8A8_UNORM, 256 elements from element 16 of the buffer (written) -; slot 3 (+0x60): V#, typed R32G32B32A32_UINT, 256 elements (written) -; slot 4 (+0x80): V#, typed R32_FLOAT, 250 elements of a 256-element buffer (read) -; slot 5 (+0xa0): V#, typed R32_SINT, 256 elements (written) -; g = 64 * group + lane, 0..255 (an index past a view's NUM_RECORDS is out of range: a load gives 0, a store or an -; atomic touches nothing): -; slot 0: element g = g * mul + seed, then += g -; slot 1: element g = { f16(g), f16(g + 0.5), f16(-1 - g), f16(0.25) } -; slot 2: element g = unorm8 { (g & 255) / 255, (255 - (g & 255)) / 255, 0, 1 } -; slot 3: element g = { g, g ^ 0xffff, g * 7, 0xa5 } -; slot 5: element g = (int)(2 * input[g]), input[g] = g - 100.5 -s_load_dwordx4 s[8:11], s[4:5], 0x0 -s_load_dwordx4 s[12:15], s[4:5], 0x20 -s_load_dwordx4 s[16:19], s[4:5], 0x40 -s_load_dwordx4 s[20:23], s[4:5], 0x60 -s_load_dwordx4 s[24:27], s[4:5], 0x80 -s_load_dwordx4 s[28:31], s[4:5], 0xa0 -s_lshl_b32 s7, s6, 6 -s_waitcnt lgkmcnt(0) -v_add_nc_u32_e32 v1, s7, v0 -v_mul_lo_u32 v2, v1, s1 -v_add_nc_u32_e32 v2, s0, v2 -buffer_store_format_x v2, v1, s[8:11], 0 idxen -v_mov_b32_e32 v3, v1 -buffer_atomic_add v3, v1, s[8:11], 0 idxen -v_cvt_f32_u32_e32 v4, v1 -v_add_f32_e32 v5, 0.5, v4 -v_sub_f32_e32 v6, -1.0, v4 -v_mov_b32_e32 v7, 0x3e800000 -buffer_store_format_xyzw v[4:7], v1, s[12:15], 0 idxen -v_and_b32_e32 v8, 255, v1 -v_cvt_f32_ubyte0_e32 v9, v8 -v_mov_b32_e32 v10, 0x3b808081 -v_mul_f32_e32 v11, v9, v10 -v_sub_nc_u32_e32 v12, 255, v8 -v_cvt_f32_ubyte0_e32 v12, v12 -v_mul_f32_e32 v12, v12, v10 -v_mov_b32_e32 v13, 0 -v_mov_b32_e32 v14, 1.0 -buffer_store_format_xyzw v[11:14], v1, s[16:19], 0 idxen -v_mov_b32_e32 v15, v1 -v_xor_b32_e32 v16, 0xffff, v1 -v_mul_lo_u32 v17, v1, 7 -v_mov_b32_e32 v18, 0xa5 -buffer_store_format_xyzw v[15:18], v1, s[20:23], 0 idxen -buffer_load_format_x v19, v1, s[24:27], 0 idxen -s_waitcnt vmcnt(0) -v_add_f32_e32 v19, v19, v19 -v_cvt_i32_f32_e32 v19, v19 -buffer_store_format_x v19, v1, s[28:31], 0 idxen -s_endpgm diff --git a/runtime/test/shaders/cs_bvh.asm b/runtime/test/shaders/cs_bvh.asm deleted file mode 100644 index 465816a6c..000000000 --- a/runtime/test/shaders/cs_bvh.asm +++ /dev/null @@ -1,30 +0,0 @@ -; image_bvh64_intersect_ray emulation: vk_compute_test writes an AMD-format BVH into the heap (box32 root 0x100 -> triangle -; z=10 node 0x40, triangle z=5 node 0x48, missed box, box 0x68 with a NaN min.x). Ray (0.25,0.25,0) +z. Run: -; vk_compute_test cs_bvh.spv 1 bvh -; -> box result 0x68 0x48 0x40 0xffffffff (sorted; RDNA2 skips the NaN plane and enters box 0x68 at t = 0, SHADER-650), -; triangle result -10 -1 -0.25 -0.25 (t = 10, bary 0.25/0.25). -v_cmpx_eq_u32_e32 0, v0 -v_mov_b32_e32 v1, 0x25 -v_mov_b32_e32 v2, 0 -v_mov_b32_e32 v3, 0x42c80000 -v_mov_b32_e32 v4, 0.25 -v_mov_b32_e32 v5, 0.25 -v_mov_b32_e32 v6, 0 -v_mov_b32_e32 v7, 0 -v_mov_b32_e32 v8, 0 -v_mov_b32_e32 v9, 1.0 -v_mov_b32_e32 v10, 0x7f800000 -v_mov_b32_e32 v11, 0x7f800000 -v_mov_b32_e32 v12, 1.0 -s_mov_b32 s4, 0 -s_mov_b32 s5, 0x80000000 -s_mov_b32 s6, -1 -s_mov_b32 s7, 0x81000000 -image_bvh64_intersect_ray v[20:23], [v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12], s[4:7] -v_mov_b32_e32 v30, 0 -buffer_store_dwordx4 v[20:23], v30, s[0:3], 0 offen -v_mov_b32_e32 v1, 0x40 -image_bvh64_intersect_ray v[24:27], [v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12], s[4:7] -v_mov_b32_e32 v30, 16 -buffer_store_dwordx4 v[24:27], v30, s[0:3], 0 offen -s_endpgm diff --git a/runtime/test/shaders/cs_bvh32.asm b/runtime/test/shaders/cs_bvh32.asm deleted file mode 100644 index 2edfb8414..000000000 --- a/runtime/test/shaders/cs_bvh32.asm +++ /dev/null @@ -1,44 +0,0 @@ -; image_bvh_intersect_ray, the form with a 32-bit node pointer (cs_bvh.asm runs image_bvh64_intersect_ray). Its address -; is 11 dwords: node, ray extent (t max), origin xyz, direction xyz, inverse direction xyz. The 64-bit form has the -; node's high dword after the low one, so read with that layout every operand here would be one register off. -; Same scene and ray as cs_bvh.asm: vk_compute_test writes an AMD-format BVH into the heap (box32 root at 0x100 -> -; triangle z=10 node 0x40, triangle z=5 node 0x48, a box the ray misses, a box with a NaN min.x). Ray origin -; (0.25, 0.25, 0), direction +z, t max 100. Run: vk_compute_test cs_bvh32.spv 1 bvh -; Expected, from the "Ray tracing" row of docs/design.md (one traversal step; the box test as measured on RDNA2, -; SHADER-650, and RADV's software triangle test): -; box node 0x25 (address 0x100 >> 3 | type 5): along +z the ray enters a box that contains its x and y at the -; box's near z, so child 0x40 (z = 10) at 10 and child 0x48 (z = 5) at 5. The third box lies at x in [5, 6], which -; the ray never reaches: 0xffffffff. The fourth (0x68) has min.x = NaN; the hardware skips a NaN plane, so the box -; is x <= 1, y and z in [0, 1], which the ray is in at t = 0. box_sort_enable (descriptor bit 63, set in s5) orders -; the children by entry distance clamped to 0: out[0..3] = 0x68 0x48 0x40 0xffffffff (native gfx1030 gives the same). -; triangle node 0x40 (address 0x200, vertices (0,0,10) (1,0,10) (0,1,10)): the ray runs along z, so the vertices -; relative to the origin project onto xy unsheared: A = (-0.25, -0.25), B = (0.75, -0.25), C = (-0.25, 0.75). The -; edge functions are u = Cx By - Cy Bx = -0.5, v = Ax Cy - Ay Cx = -0.25 and w = Bx Ay - By Ax = -0.25, all of one -; sign (a hit); det = u + v + w = -1 and T = 10 (u + v + w) = -10. The result, as RDNA2 returns it, is -; k (T, det, v, w) with k = |d.z|^3 = 1, so (-10, -1, -0.25, -0.25): out[4..7] = 0xc1200000 0xbf800000 0xbe800000 -; 0xbe800000 (the same words natively on gfx1030, tests/semantic/test_image_bvh_tri_hw.py's cs_bvh row). The shader's -; division by the second word gives t = 10 and the barycentrics 0.25, 0.25. -v_cmpx_eq_u32_e32 0, v0 -v_mov_b32_e32 v2, 0x25 -v_mov_b32_e32 v3, 0x42c80000 -v_mov_b32_e32 v4, 0.25 -v_mov_b32_e32 v5, 0.25 -v_mov_b32_e32 v6, 0 -v_mov_b32_e32 v7, 0 -v_mov_b32_e32 v8, 0 -v_mov_b32_e32 v9, 1.0 -v_mov_b32_e32 v10, 0x7f800000 -v_mov_b32_e32 v11, 0x7f800000 -v_mov_b32_e32 v12, 1.0 -s_mov_b32 s4, 0 -s_mov_b32 s5, 0x80000000 -s_mov_b32 s6, -1 -s_mov_b32 s7, 0x81000000 -image_bvh_intersect_ray v[20:23], [v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12], s[4:7] -v_mov_b32_e32 v30, 0 -buffer_store_dwordx4 v[20:23], v30, s[0:3], 0 offen -v_mov_b32_e32 v2, 0x40 -image_bvh_intersect_ray v[24:27], [v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12], s[4:7] -v_mov_b32_e32 v30, 16 -buffer_store_dwordx4 v[24:27], v30, s[0:3], 0 offen -s_endpgm diff --git a/runtime/test/shaders/cs_cmpx_class_f32.asm b/runtime/test/shaders/cs_cmpx_class_f32.asm deleted file mode 100644 index 75dcdd4be..000000000 --- a/runtime/test/shaders/cs_cmpx_class_f32.asm +++ /dev/null @@ -1,28 +0,0 @@ -; group: 8,1,1 -; mattr: +wavefrontsize32,-wavefrontsize64 -; CMPX class keeps qNaN and +0 across both compares. E32 (mask 0x242) drops -0, E64 (mask 0x62) -; drops +infinity. Neither compare can reactivate lane 0, which was disabled even though it holds qNaN. -; VCC selects the distinctive value in lane 3 and must survive both EXEC-only compares. -; Run: vk_compute_test cs_cmpx_class_f32.spv 1 dump -; out[0..7] = EEEEEEEE EEEEEEEE EEEEEEEE 00000022 00000011 00000011 00000011 00000011 (hex) -v_mov_b32_e32 v1, 0x7fc00000 -v_mov_b32_e32 v2, 0x7f800000 -v_cmp_eq_u32_e32 vcc_lo, 1, v0 -v_cndmask_b32_e32 v1, v1, v2, vcc_lo -v_mov_b32_e32 v2, 0x80000000 -v_cmp_eq_u32_e32 vcc_lo, 2, v0 -v_cndmask_b32_e32 v1, v1, v2, vcc_lo -v_mov_b32_e32 v2, 0 -v_cmp_eq_u32_e32 vcc_lo, 3, v0 -v_cndmask_b32_e32 v1, v1, v2, vcc_lo -v_mov_b32_e32 v2, 0x242 -v_mov_b32_e32 v7, 0x62 -v_mov_b32_e32 v3, 0x11 -v_mov_b32_e32 v4, 0x22 -v_lshlrev_b32_e32 v5, 2, v0 -v_cmpx_ne_u32_e32 0, v0 -v_cmpx_class_f32_e32 v1, v2 -v_cmpx_class_f32_e64 v1, v7 -v_cndmask_b32_e32 v6, v3, v4, vcc_lo -buffer_store_dword v6, v5, s[0:3], 0 offen -s_endpgm diff --git a/runtime/test/shaders/cs_cvt_f32_sat.asm b/runtime/test/shaders/cs_cvt_f32_sat.asm deleted file mode 100644 index df53d3abb..000000000 --- a/runtime/test/shaders/cs_cvt_f32_sat.asm +++ /dev/null @@ -1,14 +0,0 @@ -; regen_fixtures: this source has a translator fixture in tests/semantic/fixtures/disasm -; s[0:3] is the output V#, s4 is one binary32 input as a raw word. -; RDNA 2 ISA, VOP1 opcodes 7 and 8: truncate toward zero, saturate to -; the destination range, and return zero for NaN. -; At offset 0: unsigned result. At offset 4: signed result, as raw bits. -; Example s4 = 0x4f000000 (+2^31): out = 0x80000000, 0x7fffffff. -; group: 1,1,1 -; rsrc2: 0x808a -v_mov_b32_e32 v0, s4 -v_mov_b32_e32 v1, 0 -v_cvt_u32_f32_e32 v2, v0 -v_cvt_i32_f32_e32 v3, v0 -buffer_store_dwordx2 v[2:3], v1, s[0:3], 0 offen -s_endpgm diff --git a/runtime/test/shaders/cs_cvt_pk_u8.asm b/runtime/test/shaders/cs_cvt_pk_u8.asm deleted file mode 100644 index 7891d8b33..000000000 --- a/runtime/test/shaders/cs_cvt_pk_u8.asm +++ /dev/null @@ -1,37 +0,0 @@ -; regen_fixtures: this source has a translator fixture in tests/semantic/fixtures/disasm -; group: 8,1,1 -; mattr: +wavefrontsize32,-wavefrontsize64 -; v_cvt_pk_u8_f32 (VOP3 opcode 0x15e): lane i converts one binary32 value into byte (i & 3) of 0x11223344. -; Inputs by lane: 12.5, 13.5, 0.5, 254.5, 12.75, NaN (0x7fc00000), 300.0, -1.0. -; Measured natively on RDNA2 (gfx1036, Ryzen 7 9800X3D iGPU, AMD driver 25.10): halves round to even, -; NaN and negative values give 0, values above 255 give 255, and the other three bytes are kept. -; Run: vk_compute_test cs_cvt_pk_u8.spv 1 dump -; out[0..7] = 1122330C 11220E44 11003344 FE223344 1122330D 11220044 11FF3344 00223344 (hex) -v_mov_b32_e32 v1, 0x41480000 -v_mov_b32_e32 v2, 0x41580000 -v_cmp_eq_u32_e32 vcc_lo, 1, v0 -v_cndmask_b32_e32 v1, v1, v2, vcc_lo -v_mov_b32_e32 v2, 0x3f000000 -v_cmp_eq_u32_e32 vcc_lo, 2, v0 -v_cndmask_b32_e32 v1, v1, v2, vcc_lo -v_mov_b32_e32 v2, 0x437e8000 -v_cmp_eq_u32_e32 vcc_lo, 3, v0 -v_cndmask_b32_e32 v1, v1, v2, vcc_lo -v_mov_b32_e32 v2, 0x414c0000 -v_cmp_eq_u32_e32 vcc_lo, 4, v0 -v_cndmask_b32_e32 v1, v1, v2, vcc_lo -v_mov_b32_e32 v2, 0x7fc00000 -v_cmp_eq_u32_e32 vcc_lo, 5, v0 -v_cndmask_b32_e32 v1, v1, v2, vcc_lo -v_mov_b32_e32 v2, 0x43960000 -v_cmp_eq_u32_e32 vcc_lo, 6, v0 -v_cndmask_b32_e32 v1, v1, v2, vcc_lo -v_mov_b32_e32 v2, 0xbf800000 -v_cmp_eq_u32_e32 vcc_lo, 7, v0 -v_cndmask_b32_e32 v1, v1, v2, vcc_lo -v_and_b32_e32 v3, 3, v0 -v_mov_b32_e32 v4, 0x11223344 -v_cvt_pk_u8_f32 v5, v1, v3, v4 -v_lshlrev_b32_e32 v6, 2, v0 -buffer_store_dword v5, v6, s[0:3], 0 offen -s_endpgm diff --git a/runtime/test/shaders/cs_div_fmas_f64.asm b/runtime/test/shaders/cs_div_fmas_f64.asm deleted file mode 100644 index 41b594752..000000000 --- a/runtime/test/shaders/cs_div_fmas_f64.asm +++ /dev/null @@ -1,16 +0,0 @@ -; group: 1,1,1 -; v_div_fmas_f64 with VCC = 0 is a binary64 multiply-add with ONE rounding (RDNA2 ISA, VOP3). Low word first. -; a = 1 + 2^-30 (0x3ff00000_00400000), c = -(1 + 2^-29) (0xbff00000_00800000): a*a = 1 + 2^-29 + 2^-60 exactly, so -; fma(a, a, c) = 2^-60 = 0x3c300000_00000000 fused; rounding a*a first gives 1 + 2^-29 and a result of 0 ("split"). -; out[0..1] = 0x00000000 0x3c300000 (split: 0x00000000 0x00000000). Under --fma khr (LEONIDA_FMA=khr) the translator -; emits OpFmaKHR on doubles (feature shaderFmaFloat64) and only the fused words pass; under the default GLSL Fma a -; driver may split (NVIDIA RTX 4090, 621.24, does). -s_mov_b64 vcc, 0 -v_mov_b32 v0, 0x00400000 -v_mov_b32 v1, 0x3ff00000 -v_mov_b32 v2, 0x00800000 -v_mov_b32 v3, 0xbff00000 -v_div_fmas_f64 v[4:5], v[0:1], v[0:1], v[2:3] -v_mov_b32 v6, 0 -buffer_store_dwordx2 v[4:5], v6, s[0:3], 0 offen -s_endpgm diff --git a/runtime/test/shaders/cs_dpp.asm b/runtime/test/shaders/cs_dpp.asm deleted file mode 100644 index 29a5bfa10..000000000 --- a/runtime/test/shaders/cs_dpp.asm +++ /dev/null @@ -1,8 +0,0 @@ -; DPP quad_perm: v_mov_b32_dpp v1, v0 quad_perm:[1,0,3,2], with v0 = lane id. Lanes 0-7 store -; [1,0,3,2,5,4,7,6] to out[0..7]. Same FSSM header as cs_lds. -; Run: vk_compute_test cs_dpp.spv 1 dump -> out[0..7] = 1 0 3 2 5 4 7 6 -v_mbcnt_lo_u32_b32 v0, -1, 0 -v_mov_b32_dpp v1, v0 quad_perm:[1,0,3,2] row_mask:0xf bank_mask:0xf -v_lshlrev_b32 v2, 2, v0 -buffer_store_dword v1, v2, s[0:3], 0 offen -s_endpgm diff --git a/runtime/test/shaders/cs_dpp8.asm b/runtime/test/shaders/cs_dpp8.asm deleted file mode 100644 index f4979be51..000000000 --- a/runtime/test/shaders/cs_dpp8.asm +++ /dev/null @@ -1,8 +0,0 @@ -; DPP8 reverse within 8-lane groups: dpp8:[7,6,5,4,3,2,1,0], fi:1. Lanes 0-7 store -; [7,6,5,4,3,2,1,0] to out[0..7]. -; Run: vk_compute_test cs_dpp8.spv 1 dump -> out[0..7] = 7 6 5 4 3 2 1 0 -v_mbcnt_lo_u32_b32 v0, -1, 0 -v_mov_b32_dpp v1, v0 dpp8:[7,6,5,4,3,2,1,0] fi:1 -v_lshlrev_b32 v2, 2, v0 -buffer_store_dword v1, v2, s[0:3], 0 offen -s_endpgm diff --git a/runtime/test/shaders/cs_dpp_bank.asm b/runtime/test/shaders/cs_dpp_bank.asm deleted file mode 100644 index 569185099..000000000 --- a/runtime/test/shaders/cs_dpp_bank.asm +++ /dev/null @@ -1,9 +0,0 @@ -; DPP bank_mask on a VOP1 op: bank 0 is enabled, so lanes 0-3 compute ~lane; lanes 4-7 are not written and -; keep 7. Lanes 0-7 store [0xffffffff,0xfffffffe,0xfffffffd,0xfffffffc,7,7,7,7] to out[0..7]. -; Run: vk_compute_test cs_dpp_bank.spv 1 dump -> out[0..7] = 4294967295 4294967294 4294967293 4294967292 7 7 7 7 -v_mbcnt_lo_u32_b32 v0, -1, 0 -v_mov_b32 v10, 7 -v_not_b32_dpp v10, v0 quad_perm:[0,1,2,3] row_mask:0xf bank_mask:0x1 -v_lshlrev_b32 v2, 2, v0 -buffer_store_dword v10, v2, s[0:3], 0 offen -s_endpgm diff --git a/runtime/test/shaders/cs_dpp_bound.asm b/runtime/test/shaders/cs_dpp_bound.asm deleted file mode 100644 index 9ac5ba86f..000000000 --- a/runtime/test/shaders/cs_dpp_bound.asm +++ /dev/null @@ -1,10 +0,0 @@ -; DPP on a VOP2 op with an invalid source and bound_ctrl:1: lane 0 uses 0 as src0, so it writes op(0, 10); -; the other lanes use the lane below them. Lanes 0-7 store [10,10,11,12,13,14,15,16] to out[0..7]. -; Run: vk_compute_test cs_dpp_bound.spv 1 dump -> out[0..7] = 10 10 11 12 13 14 15 16 -v_mbcnt_lo_u32_b32 v0, -1, 0 -v_mov_b32 v1, 10 -v_mov_b32 v10, 100 -v_add_nc_u32_dpp v10, v0, v1 row_shr:1 row_mask:0xf bank_mask:0xf bound_ctrl:1 -v_lshlrev_b32 v2, 2, v0 -buffer_store_dword v10, v2, s[0:3], 0 offen -s_endpgm diff --git a/runtime/test/shaders/cs_dpp_fi.asm b/runtime/test/shaders/cs_dpp_fi.asm deleted file mode 100644 index dbfd202c6..000000000 --- a/runtime/test/shaders/cs_dpp_fi.asm +++ /dev/null @@ -1,11 +0,0 @@ -; DPP16 fi:1 with EXEC 0x77777777 (lane 3 of each quad off). lane 2 reads the inactive lane 3; lane 3 is -; itself inactive and keeps 0x7777. Lanes 0-7 store [1,2,3,0x7777,5,6,7,0x7777] to out[0..7]. -; Run: vk_compute_test cs_dpp_fi.spv 1 dump -> out[0..7] = 1 2 3 30583 5 6 7 30583 -v_mbcnt_lo_u32_b32 v0, -1, 0 -v_mov_b32 v10, 0x7777 -s_mov_b32 exec_lo, 0x77777777 -v_mov_b32_dpp v10, v0 quad_perm:[1,2,3,0] row_mask:0xf bank_mask:0xf fi:1 -s_mov_b32 exec_lo, -1 -v_lshlrev_b32 v2, 2, v0 -buffer_store_dword v10, v2, s[0:3], 0 offen -s_endpgm diff --git a/runtime/test/shaders/cs_dpp_mask.asm b/runtime/test/shaders/cs_dpp_mask.asm deleted file mode 100644 index 3eb6b8ca6..000000000 --- a/runtime/test/shaders/cs_dpp_mask.asm +++ /dev/null @@ -1,9 +0,0 @@ -; DPP row_mask/bank_mask: quad_perm:[1,0,3,2] with row 0 and bank 0 enabled only. Lanes 0-3 get the -; permutation; lanes 4-7 keep the output buffer's initial 0xEE. Lanes 0-3 store to out[0..3] only. -; Run: vk_compute_test cs_dpp_mask.spv 1 dump -> out[0..7] = 1 0 3 2 4008636142 4008636142 4008636142 4008636142 -v_mbcnt_lo_u32_b32 v0, -1, 0 -v_mov_b32_dpp v1, v0 quad_perm:[1,0,3,2] row_mask:0x1 bank_mask:0x1 -v_lshlrev_b32 v2, 2, v0 -v_cmpx_lt_u32 v0, 4 -buffer_store_dword v1, v2, s[0:3], 0 offen -s_endpgm diff --git a/runtime/test/shaders/cs_dpp_ops.asm b/runtime/test/shaders/cs_dpp_ops.asm deleted file mode 100644 index a9214f53f..000000000 --- a/runtime/test/shaders/cs_dpp_ops.asm +++ /dev/null @@ -1,11 +0,0 @@ -; DPP on a VOP2 op with an invalid source and no bound_ctrl: lane 0 reads outside its row, so it must not be -; written and keeps 100. The other lanes compute op(source lane, 10). Lanes 0-7 store -; [100,10,11,12,13,14,15,16] to out[0..7]. -; Run: vk_compute_test cs_dpp_ops.spv 1 dump -> out[0..7] = 100 10 11 12 13 14 15 16 -v_mbcnt_lo_u32_b32 v0, -1, 0 -v_mov_b32 v1, 10 -v_mov_b32 v10, 100 -v_add_nc_u32_dpp v10, v0, v1 row_shr:1 row_mask:0xf bank_mask:0xf -v_lshlrev_b32 v2, 2, v0 -buffer_store_dword v10, v2, s[0:3], 0 offen -s_endpgm diff --git a/runtime/test/shaders/cs_dpp_row.asm b/runtime/test/shaders/cs_dpp_row.asm deleted file mode 100644 index 3109485a8..000000000 --- a/runtime/test/shaders/cs_dpp_row.asm +++ /dev/null @@ -1,8 +0,0 @@ -; DPP row_shr:1 with bound_ctrl:1: each lane reads the lane below it in its 16-lane row; lane 0 (and lane 16, -; 32, 48) has an invalid source and reads zero. Lanes 0-7 store [0,0,1,2,3,4,5,6] to out[0..7]. -; Run: vk_compute_test cs_dpp_row.spv 1 dump -> out[0..7] = 0 0 1 2 3 4 5 6 -v_mbcnt_lo_u32_b32 v0, -1, 0 -v_mov_b32_dpp v1, v0 row_shr:1 row_mask:0xf bank_mask:0xf bound_ctrl:1 -v_lshlrev_b32 v2, 2, v0 -buffer_store_dword v1, v2, s[0:3], 0 offen -s_endpgm diff --git a/runtime/test/shaders/cs_dpp_w64.asm b/runtime/test/shaders/cs_dpp_w64.asm deleted file mode 100644 index 29394e2a4..000000000 --- a/runtime/test/shaders/cs_dpp_w64.asm +++ /dev/null @@ -1,9 +0,0 @@ -; Wave64 DPP: the lane id needs both halves, so this is a wave64 shader. Without emulation it needs a 64-wide -; subgroup; LEONIDA_W64_EMULATE=1 sends the DPP source/EXEC exchange through %x_buf and runs on any subgroup. -; Run: vk_compute_test cs_dpp_w64.spv 1 dump -> out[0..7] = 1 0 3 2 5 4 7 6. -v_mbcnt_lo_u32_b32 v0, -1, 0 -v_mbcnt_hi_u32_b32 v0, -1, v0 -v_mov_b32_dpp v1, v0 quad_perm:[1,0,3,2] row_mask:0xf bank_mask:0xf -v_lshlrev_b32 v2, 2, v0 -buffer_store_dword v1, v2, s[0:3], 0 offen -s_endpgm diff --git a/runtime/test/shaders/cs_exec64.asm b/runtime/test/shaders/cs_exec64.asm deleted file mode 100644 index 0694a4cfd..000000000 --- a/runtime/test/shaders/cs_exec64.asm +++ /dev/null @@ -1,13 +0,0 @@ -; Wave64 compute: constant EXEC halves (exec_lo = 0xffff0000 -> lanes 16-31, exec_hi = 0xffff -> lanes 32-47), lane from -; v_mbcnt_lo/hi. Run: vk_compute_test cs_exec64.spv 1 exec64 -> out[t] = 7 for t in 16..47, else 0. -v_mbcnt_lo_u32_b32 v1, -1, 0 -v_mbcnt_hi_u32_b32 v1, -1, v1 -v_mov_b32_e32 v2, 0 -s_mov_b32 exec_lo, 0xffff0000 -s_mov_b32 exec_hi, 0xffff -v_mov_b32_e32 v2, 7 -s_mov_b32 exec_lo, -1 -s_mov_b32 exec_hi, -1 -v_lshlrev_b32_e32 v3, 2, v1 -buffer_store_dword v2, v3, s[0:3], 0 offen -s_endpgm diff --git a/runtime/test/shaders/cs_exec_const.asm b/runtime/test/shaders/cs_exec_const.asm deleted file mode 100644 index 890f26d88..000000000 --- a/runtime/test/shaders/cs_exec_const.asm +++ /dev/null @@ -1,54 +0,0 @@ -; Constant EXEC masks in wave32: s_mov_b32 exec_lo, turns on exactly the lanes whose bit is set. -; v0 = lane (LocalInvocationId.x, 0..31). For each mask a VALU write marks the lanes that ran it; a later full-EXEC -; v_cmp turns the marks back into a lane mask, and lane 0 stores its lane count (s_bcnt1) and lowest lane (s_ff1). -; Three constants fit in 16 bits (0xffff, 0xff, 0x8001), which is the case Intel's Windows driver -; (UHD 770 / Xe-LP, 32.0.101.6129) got wrong for a per-lane OpBitFieldUExtract of the constant: it took the lane -; index mod 16, so lanes 16-31 copied lanes 0-15 (0xffff ran all 32 lanes). 0xffff0000 does not fit and was right. -; Lane 0 stores: out[0..3] = set lanes of 0xffff 0xff 0x8001 0xffff0000 = 16 8 2 16; out[4..5] = lowest lane of -; 0x8001 and of 0xffff0000 = 0 16. With the lane taken mod 16 (the Intel bug) it was 32 16 4 16 0 16. -; group: 32,1,1 -; Run: vk_compute_test cs_exec_const.spv 1 dump -> out[0..5] = 16 8 2 16 0 16 -; mattr: +wavefrontsize32,-wavefrontsize64 -v_mov_b32_e32 v10, 0 -v_mov_b32_e32 v11, 0 -v_mov_b32_e32 v12, 0 -v_mov_b32_e32 v13, 0 -s_mov_b32 exec_lo, 0xffff -v_mov_b32_e32 v10, 1 -s_mov_b32 exec_lo, 0xff -v_mov_b32_e32 v11, 1 -s_mov_b32 exec_lo, 0x8001 -v_mov_b32_e32 v12, 1 -s_mov_b32 exec_lo, 0xffff0000 -v_mov_b32_e32 v13, 1 -s_mov_b32 exec_lo, -1 -v_cmp_ne_u32_e32 vcc_lo, 0, v10 -s_bcnt1_i32_b32 s6, vcc_lo -v_cmp_ne_u32_e32 vcc_lo, 0, v11 -s_bcnt1_i32_b32 s7, vcc_lo -v_cmp_ne_u32_e32 vcc_lo, 0, v12 -s_bcnt1_i32_b32 s8, vcc_lo -s_ff1_i32_b32 s10, vcc_lo -v_cmp_ne_u32_e32 vcc_lo, 0, v13 -s_bcnt1_i32_b32 s9, vcc_lo -s_ff1_i32_b32 s11, vcc_lo -v_cmpx_eq_u32_e32 0, v0 -v_mov_b32_e32 v1, s6 -v_mov_b32_e32 v2, 0 -buffer_store_dword v1, v2, s[0:3], 0 offen -v_mov_b32_e32 v1, s7 -v_mov_b32_e32 v2, 4 -buffer_store_dword v1, v2, s[0:3], 0 offen -v_mov_b32_e32 v1, s8 -v_mov_b32_e32 v2, 8 -buffer_store_dword v1, v2, s[0:3], 0 offen -v_mov_b32_e32 v1, s9 -v_mov_b32_e32 v2, 12 -buffer_store_dword v1, v2, s[0:3], 0 offen -v_mov_b32_e32 v1, s10 -v_mov_b32_e32 v2, 16 -buffer_store_dword v1, v2, s[0:3], 0 offen -v_mov_b32_e32 v1, s11 -v_mov_b32_e32 v2, 20 -buffer_store_dword v1, v2, s[0:3], 0 offen -s_endpgm diff --git a/runtime/test/shaders/cs_f64_add.asm b/runtime/test/shaders/cs_f64_add.asm deleted file mode 100644 index 4dbba4123..000000000 --- a/runtime/test/shaders/cs_f64_add.asm +++ /dev/null @@ -1,10 +0,0 @@ -; group: 1,1,1 -; Store binary64 (0.75 + 0.5) * 2 = 2.5 as low/high words: 0x00000000, 0x40040000. -v_mov_b32 v0, 0 -v_mov_b32 v1, 0x3fe80000 -v_mov_b32 v2, 0 -v_mov_b32 v3, 0x3fe00000 -v_add_f64 v[4:5], v[0:1], v[2:3] mul:2 -v_mov_b32 v6, 0 -buffer_store_dwordx2 v[4:5], v6, s[0:3], 0 offen -s_endpgm diff --git a/runtime/test/shaders/cs_fma_fused.asm b/runtime/test/shaders/cs_fma_fused.asm deleted file mode 100644 index 31282c47a..000000000 --- a/runtime/test/shaders/cs_fma_fused.asm +++ /dev/null @@ -1,56 +0,0 @@ -; s[0:3] is the output V#. One thread, eight words: each is an f32 multiply-add whose single-rounded (fused) result -; differs from a multiply followed by an add. RDNA 2 v_fma_f32, v_fmac_f32, v_fmaak_f32 and v_fmamk_f32 round once, -; so every word below is the exact fused result (derived by hand in the comments; measured on gfx1150 by -; tools/f32_fuzz.py --oracle hw, 72 of 72 cancel probes fused). A translation whose multiply-add rounds twice -; (a driver may split GLSL.std.450 Fma: the Vulkan environment says "inherited from OpFMul followed by OpFAdd") -; gives the "split" value instead. rdna2spirv.py --fma khr emits OpFmaKHR (SPV_KHR_fma, correctly rounded). -; -; a = 1 + 2^-12 (0x3f800800), a*a = 1 + 2^-11 + 2^-24 exactly. That is a tie between 1 + 2^-11 and -; 1 + 2^-11 + 2^-23; ties-to-even picks p = 1 + 2^-11 (0x3f801000), so a*a - p = 2^-24 is the product's rounding error. -; out[0] v_fma_f32 a, a, -p 2^-24 = 0x33800000 split 0x00000000 -; out[1] v_fma_f32 (1+2^-23), (1-2^-23), -1: -; the product is 1 - 2^-46 -2^-46 = 0xa8800000 split 0x00000000 -; out[2] v_fma_f32 a, a, -1.0 2^-11 + 2^-24 = 0x3a000400 split 0x3a000000 -; out[3] v_fmaak_f32 a, a, K = -p 2^-24 = 0x33800000 split 0x00000000 -; out[4] v_fmamk_f32 a * K + (-p), K = a 2^-24 = 0x33800000 split 0x00000000 -; out[5] v_fmac_f32 d = -p; d += a*a 2^-24 = 0x33800000 split 0x00000000 -; out[6] v_fma_f32 (1+2^-23)^2, -(1+2^-22): (1+2^-23)^2 = 1 + 2^-22 + 2^-46, so 2^-46 = 0x28800000 split 0x00000000 -; out[7] v_fma_f16 0x6ce1 * 0x4200 + 0x8004 (the f16 triple of tests/semantic/test_f16_fma_rounding.py where -; rounding the exact result to f32 and then to f16 is one step off): 0x00007351; f32-then-f16 gives 0x7352. -; The f16 form does not use Fma at all (round-to-odd, Gen.fma_f16_odd), so it must be the same with -; --fma glsl and --fma khr. -; The operands come in through s4..s7 (VKC_SGPRS=0x3f800800,0x3f800001,0x3f7ffffe,0xbf800002: a, 1+2^-23, 1-2^-23, -; -(1+2^-22)), so a driver cannot fold the multiply-adds at compile time; only the fmaak/fmamk constants are literals. -; Run: VKC_SGPRS=0x3f800800,0x3f800001,0x3f7ffffe,0xbf800002 vk_compute_test cs_fma_fused.spv 1 dump -; out[0..7] = 33800000 a8800000 3a000400 33800000 33800000 33800000 28800000 00007351 (hex) -; group: 1,1,1 -; rsrc2: 0x8090 -v_mov_b32_e32 v0, s4 -v_mul_f32_e32 v3, v0, v0 -v_mov_b32_e32 v20, 0 -v_fma_f32 v4, v0, v0, -v3 -buffer_store_dword v4, v20, s[0:3], 0 offen -v_mov_b32_e32 v5, s5 -v_mov_b32_e32 v6, s6 -v_fma_f32 v7, v5, v6, -1.0 -buffer_store_dword v7, v20, s[0:3], 0 offen offset:4 -v_fma_f32 v8, v0, v0, -1.0 -buffer_store_dword v8, v20, s[0:3], 0 offen offset:8 -v_fmaak_f32 v9, v0, v0, 0xbf801000 -buffer_store_dword v9, v20, s[0:3], 0 offen offset:12 -v_sub_f32_e32 v10, 0, v3 -v_fmamk_f32 v11, v0, 0x3f800800, v10 -buffer_store_dword v11, v20, s[0:3], 0 offen offset:16 -v_mov_b32_e32 v12, v10 -v_fmac_f32_e32 v12, v0, v0 -buffer_store_dword v12, v20, s[0:3], 0 offen offset:20 -v_mov_b32_e32 v13, s7 -v_fma_f32 v14, v5, v5, v13 -buffer_store_dword v14, v20, s[0:3], 0 offen offset:24 -v_mov_b32_e32 v15, 0x6ce1 -v_mov_b32_e32 v16, 0x4200 -v_mov_b32_e32 v17, 0x8004 -v_fma_f16 v18, v15, v16, v17 -v_and_b32_e32 v18, 0xffff, v18 -buffer_store_dword v18, v20, s[0:3], 0 offen offset:28 -s_endpgm diff --git a/runtime/test/shaders/cs_fmt_1010102.asm b/runtime/test/shaders/cs_fmt_1010102.asm deleted file mode 100644 index 351e5dc3d..000000000 --- a/runtime/test/shaders/cs_fmt_1010102.asm +++ /dev/null @@ -1,41 +0,0 @@ -; regen_fixtures: this source has a translator fixture in tests/semantic/fixtures/disasm -; 10:10:10:2 typed buffers. Format names list the channel widths from the top bit: 2_10_10_10 (50) is R10G10B10A2 -; with x in bits 9:0, and 10_10_10_2 (44) has a 2-bit x in bits 1:0. out[12..13] = 0xc00ffc00 0x003ff003 (raw), -; out[0..3] = out[12] read as 50, out[4..7] = out[13] read as 44, out[8..11] = out[12] read by tbuffer as 50 through -; a V# that says 44, out[14..15] = (1, 0, 0.5, 1) stored as 50 and 44 = 0xe00003ff 0xffe00003. -; Run: vk_compute_test cs_fmt_1010102.spv 1 dump -> out[0..7] = 0 0x3f800000 0 0x3f800000 0x3f800000 0 0x3f800000 0 -v_cmpx_eq_u32_e32 0, v0 -v_mov_b32_e32 v1, 0xc00ffc00 -v_mov_b32_e32 v2, 0x3ff003 -v_mov_b32_e32 v3, 48 -buffer_store_dwordx2 v[1:2], v3, s[0:3], 0 offen -s_waitcnt_vscnt null, 0x0 -s_mov_b32 s4, s0 -s_mov_b32 s5, s1 -s_mov_b32 s6, s2 -s_mov_b32 s7, 0x31032fac -buffer_load_format_xyzw v[4:7], v3, s[4:7], 0 offen -s_waitcnt vmcnt(0) -v_mov_b32_e32 v8, 0 -buffer_store_dwordx4 v[4:7], v8, s[0:3], 0 offen -s_mov_b32 s7, 0x3102cfac -v_mov_b32_e32 v9, 52 -buffer_load_format_xyzw v[4:7], v9, s[4:7], 0 offen -s_waitcnt vmcnt(0) -v_mov_b32_e32 v8, 16 -buffer_store_dwordx4 v[4:7], v8, s[0:3], 0 offen -tbuffer_load_format_xyzw v[4:7], v3, s[4:7], 0 format:[BUF_FMT_2_10_10_10_UNORM] offen -s_waitcnt vmcnt(0) -v_mov_b32_e32 v8, 32 -buffer_store_dwordx4 v[4:7], v8, s[0:3], 0 offen -v_mov_b32_e32 v10, 1.0 -v_mov_b32_e32 v11, 0 -v_mov_b32_e32 v12, 0.5 -v_mov_b32_e32 v13, 1.0 -s_mov_b32 s7, 0x31032fac -v_mov_b32_e32 v9, 56 -buffer_store_format_xyzw v[10:13], v9, s[4:7], 0 offen -s_mov_b32 s7, 0x3102cfac -v_mov_b32_e32 v9, 60 -buffer_store_format_xyzw v[10:13], v9, s[4:7], 0 offen -s_endpgm diff --git a/runtime/test/shaders/cs_fmt_all.asm b/runtime/test/shaders/cs_fmt_all.asm deleted file mode 100644 index c6f459e8e..000000000 --- a/runtime/test/shaders/cs_fmt_all.asm +++ /dev/null @@ -1,539 +0,0 @@ -; Typed buffer formats added for the SCALED, SINT, 10_11_11 / 11_11_10 and 2_10_10_10 / 10_10_10_2 families, and the older -; ones' stores that now follow the hardware (tools/buffer_format_fuzz.py, docs/buffer_formats.md). One thread. Words 0..127: 32 loads, 4 words each, -; of the 16-byte inputs written at 0x200 (words 128..255): 29 through a V# whose FORMAT is the code, 3 through tbuffer's -; own format; a channel the format lacks repeats component (c mod n) through the V# and is 0 through tbuffer. Words 256..335: -; 20 buffer_store_format_xyzw into 0x400.., the rest of each 16 bytes left at 0xeeeeeeee. A two-component format takes -; channels x and w through a V#; 16-bit float stores round toward zero and saturate at 65504; NORM stores round the exact product. -; The expected words are the MODEL of tools/buffer_format_fuzz.py, which the Radeon 880M (gfx1150, RDNA3.5) and a real RDNA2 (gfx1036, -; @AwkGrep256, #2022) both reproduced: 1,330,469 elements of the 63 formats GFX11 has, and 199,144 of the 14 codes only GFX10 has. -; Run: VKC_OUT_WORDS=336 VKC_DUMP= vk_compute_test cs_fmt_all.spv 1 dump; check.py compares all 336 words. -v_cmpx_eq_u32_e32 0, v0 -v_mov_b32_e32 v8, 0xff -v_mov_b32_e32 v9, 0x0 -v_mov_b32_e32 v10, 0x0 -v_mov_b32_e32 v11, 0x0 -v_mov_b32_e32 v2, 0x200 -buffer_store_dwordx4 v[8:11], v2, s[0:3], 0 offen -v_mov_b32_e32 v8, 0x80 -v_mov_b32_e32 v9, 0x0 -v_mov_b32_e32 v10, 0x0 -v_mov_b32_e32 v11, 0x0 -v_mov_b32_e32 v2, 0x210 -buffer_store_dwordx4 v[8:11], v2, s[0:3], 0 offen -v_mov_b32_e32 v8, 0xc8 -v_mov_b32_e32 v9, 0x0 -v_mov_b32_e32 v10, 0x0 -v_mov_b32_e32 v11, 0x0 -v_mov_b32_e32 v2, 0x220 -buffer_store_dwordx4 v[8:11], v2, s[0:3], 0 offen -v_mov_b32_e32 v8, 0x9c -v_mov_b32_e32 v9, 0x0 -v_mov_b32_e32 v10, 0x0 -v_mov_b32_e32 v11, 0x0 -v_mov_b32_e32 v2, 0x230 -buffer_store_dwordx4 v[8:11], v2, s[0:3], 0 offen -v_mov_b32_e32 v8, 0x8000 -v_mov_b32_e32 v9, 0x0 -v_mov_b32_e32 v10, 0x0 -v_mov_b32_e32 v11, 0x0 -v_mov_b32_e32 v2, 0x240 -buffer_store_dwordx4 v[8:11], v2, s[0:3], 0 offen -v_mov_b32_e32 v8, 0xea60 -v_mov_b32_e32 v9, 0x0 -v_mov_b32_e32 v10, 0x0 -v_mov_b32_e32 v11, 0x0 -v_mov_b32_e32 v2, 0x250 -buffer_store_dwordx4 v[8:11], v2, s[0:3], 0 offen -v_mov_b32_e32 v8, 0xfc18 -v_mov_b32_e32 v9, 0x0 -v_mov_b32_e32 v10, 0x0 -v_mov_b32_e32 v11, 0x0 -v_mov_b32_e32 v2, 0x260 -buffer_store_dwordx4 v[8:11], v2, s[0:3], 0 offen -v_mov_b32_e32 v8, 0x807f -v_mov_b32_e32 v9, 0x0 -v_mov_b32_e32 v10, 0x0 -v_mov_b32_e32 v11, 0x0 -v_mov_b32_e32 v2, 0x270 -buffer_store_dwordx4 v[8:11], v2, s[0:3], 0 offen -v_mov_b32_e32 v8, 0xff01 -v_mov_b32_e32 v9, 0x0 -v_mov_b32_e32 v10, 0x0 -v_mov_b32_e32 v11, 0x0 -v_mov_b32_e32 v2, 0x280 -buffer_store_dwordx4 v[8:11], v2, s[0:3], 0 offen -v_mov_b32_e32 v8, 0x7f80ff01 -v_mov_b32_e32 v9, 0x0 -v_mov_b32_e32 v10, 0x0 -v_mov_b32_e32 v11, 0x0 -v_mov_b32_e32 v2, 0x290 -buffer_store_dwordx4 v[8:11], v2, s[0:3], 0 offen -v_mov_b32_e32 v8, 0xff800100 -v_mov_b32_e32 v9, 0x0 -v_mov_b32_e32 v10, 0x0 -v_mov_b32_e32 v11, 0x0 -v_mov_b32_e32 v2, 0x2a0 -buffer_store_dwordx4 v[8:11], v2, s[0:3], 0 offen -v_mov_b32_e32 v8, 0xff800100 -v_mov_b32_e32 v9, 0x0 -v_mov_b32_e32 v10, 0x0 -v_mov_b32_e32 v11, 0x0 -v_mov_b32_e32 v2, 0x2b0 -buffer_store_dwordx4 v[8:11], v2, s[0:3], 0 offen -v_mov_b32_e32 v8, 0x80007fff -v_mov_b32_e32 v9, 0x0 -v_mov_b32_e32 v10, 0x0 -v_mov_b32_e32 v11, 0x0 -v_mov_b32_e32 v2, 0x2c0 -buffer_store_dwordx4 v[8:11], v2, s[0:3], 0 offen -v_mov_b32_e32 v8, 0xffff0001 -v_mov_b32_e32 v9, 0x0 -v_mov_b32_e32 v10, 0x0 -v_mov_b32_e32 v11, 0x0 -v_mov_b32_e32 v2, 0x2d0 -buffer_store_dwordx4 v[8:11], v2, s[0:3], 0 offen -v_mov_b32_e32 v8, 0x7fff8000 -v_mov_b32_e32 v9, 0xffff0001 -v_mov_b32_e32 v10, 0x0 -v_mov_b32_e32 v11, 0x0 -v_mov_b32_e32 v2, 0x2e0 -buffer_store_dwordx4 v[8:11], v2, s[0:3], 0 offen -v_mov_b32_e32 v8, 0x702003c0 -v_mov_b32_e32 v9, 0x0 -v_mov_b32_e32 v10, 0x0 -v_mov_b32_e32 v11, 0x0 -v_mov_b32_e32 v2, 0x2f0 -buffer_store_dwordx4 v[8:11], v2, s[0:3], 0 offen -v_mov_b32_e32 v8, 0x7e0fc0 -v_mov_b32_e32 v9, 0x0 -v_mov_b32_e32 v10, 0x0 -v_mov_b32_e32 v11, 0x0 -v_mov_b32_e32 v2, 0x300 -buffer_store_dwordx4 v[8:11], v2, s[0:3], 0 offen -v_mov_b32_e32 v8, 0xffc1ffbf -v_mov_b32_e32 v9, 0x0 -v_mov_b32_e32 v10, 0x0 -v_mov_b32_e32 v11, 0x0 -v_mov_b32_e32 v2, 0x310 -buffer_store_dwordx4 v[8:11], v2, s[0:3], 0 offen -v_mov_b32_e32 v8, 0xf7f001e0 -v_mov_b32_e32 v9, 0x0 -v_mov_b32_e32 v10, 0x0 -v_mov_b32_e32 v11, 0x0 -v_mov_b32_e32 v2, 0x320 -buffer_store_dwordx4 v[8:11], v2, s[0:3], 0 offen -v_mov_b32_e32 v8, 0x805ff801 -v_mov_b32_e32 v9, 0x0 -v_mov_b32_e32 v10, 0x0 -v_mov_b32_e32 v11, 0x0 -v_mov_b32_e32 v2, 0x330 -buffer_store_dwordx4 v[8:11], v2, s[0:3], 0 offen -v_mov_b32_e32 v8, 0xffdff802 -v_mov_b32_e32 v9, 0x0 -v_mov_b32_e32 v10, 0x0 -v_mov_b32_e32 v11, 0x0 -v_mov_b32_e32 v2, 0x340 -buffer_store_dwordx4 v[8:11], v2, s[0:3], 0 offen -v_mov_b32_e32 v8, 0x6017fe00 -v_mov_b32_e32 v9, 0x0 -v_mov_b32_e32 v10, 0x0 -v_mov_b32_e32 v11, 0x0 -v_mov_b32_e32 v2, 0x350 -buffer_store_dwordx4 v[8:11], v2, s[0:3], 0 offen -v_mov_b32_e32 v8, 0xe00003ff -v_mov_b32_e32 v9, 0x0 -v_mov_b32_e32 v10, 0x0 -v_mov_b32_e32 v11, 0x0 -v_mov_b32_e32 v2, 0x360 -buffer_store_dwordx4 v[8:11], v2, s[0:3], 0 offen -v_mov_b32_e32 v8, 0xbff7fe00 -v_mov_b32_e32 v9, 0x0 -v_mov_b32_e32 v10, 0x0 -v_mov_b32_e32 v11, 0x0 -v_mov_b32_e32 v2, 0x370 -buffer_store_dwordx4 v[8:11], v2, s[0:3], 0 offen -v_mov_b32_e32 v8, 0xbff7fe00 -v_mov_b32_e32 v9, 0x0 -v_mov_b32_e32 v10, 0x0 -v_mov_b32_e32 v11, 0x0 -v_mov_b32_e32 v2, 0x380 -buffer_store_dwordx4 v[8:11], v2, s[0:3], 0 offen -v_mov_b32_e32 v8, 0xfff181e0 -v_mov_b32_e32 v9, 0x0 -v_mov_b32_e32 v10, 0x0 -v_mov_b32_e32 v11, 0x0 -v_mov_b32_e32 v2, 0x390 -buffer_store_dwordx4 v[8:11], v2, s[0:3], 0 offen -v_mov_b32_e32 v8, 0x7f80ff01 -v_mov_b32_e32 v9, 0x0 -v_mov_b32_e32 v10, 0x0 -v_mov_b32_e32 v11, 0x0 -v_mov_b32_e32 v2, 0x3a0 -buffer_store_dwordx4 v[8:11], v2, s[0:3], 0 offen -v_mov_b32_e32 v8, 0x80007fff -v_mov_b32_e32 v9, 0x0 -v_mov_b32_e32 v10, 0x0 -v_mov_b32_e32 v11, 0x0 -v_mov_b32_e32 v2, 0x3b0 -buffer_store_dwordx4 v[8:11], v2, s[0:3], 0 offen -v_mov_b32_e32 v8, 0xfffff800 -v_mov_b32_e32 v9, 0x0 -v_mov_b32_e32 v10, 0x0 -v_mov_b32_e32 v11, 0x0 -v_mov_b32_e32 v2, 0x3c0 -buffer_store_dwordx4 v[8:11], v2, s[0:3], 0 offen -v_mov_b32_e32 v8, 0x800ffe00 -v_mov_b32_e32 v9, 0x0 -v_mov_b32_e32 v10, 0x0 -v_mov_b32_e32 v11, 0x0 -v_mov_b32_e32 v2, 0x3d0 -buffer_store_dwordx4 v[8:11], v2, s[0:3], 0 offen -v_mov_b32_e32 v8, 0xffc00fff -v_mov_b32_e32 v9, 0x0 -v_mov_b32_e32 v10, 0x0 -v_mov_b32_e32 v11, 0x0 -v_mov_b32_e32 v2, 0x3e0 -buffer_store_dwordx4 v[8:11], v2, s[0:3], 0 offen -v_mov_b32_e32 v8, 0xfff003ff -v_mov_b32_e32 v9, 0x0 -v_mov_b32_e32 v10, 0x0 -v_mov_b32_e32 v11, 0x0 -v_mov_b32_e32 v2, 0x3f0 -buffer_store_dwordx4 v[8:11], v2, s[0:3], 0 offen -s_waitcnt_vscnt null, 0x0 -s_mov_b32 s4, s0 -s_mov_b32 s5, s1 -s_mov_b32 s6, s2 -v_mov_b32_e32 v3, 0x200 -s_mov_b32 s7, 0x31005fac -buffer_load_format_xyzw v[4:7], v3, s[4:7], 0 offen -s_waitcnt vmcnt(0) -v_mov_b32_e32 v8, 0x0 -buffer_store_dwordx4 v[4:7], v8, s[0:3], 0 offen -v_mov_b32_e32 v3, 0x210 -s_mov_b32 s7, 0x31006fac -buffer_load_format_xyzw v[4:7], v3, s[4:7], 0 offen -s_waitcnt vmcnt(0) -v_mov_b32_e32 v8, 0x10 -buffer_store_dwordx4 v[4:7], v8, s[0:3], 0 offen -v_mov_b32_e32 v3, 0x220 -s_mov_b32 s7, 0x31003fac -buffer_load_format_xyzw v[4:7], v3, s[4:7], 0 offen -s_waitcnt vmcnt(0) -v_mov_b32_e32 v8, 0x20 -buffer_store_dwordx4 v[4:7], v8, s[0:3], 0 offen -v_mov_b32_e32 v3, 0x230 -s_mov_b32 s7, 0x31004fac -buffer_load_format_xyzw v[4:7], v3, s[4:7], 0 offen -s_waitcnt vmcnt(0) -v_mov_b32_e32 v8, 0x30 -buffer_store_dwordx4 v[4:7], v8, s[0:3], 0 offen -v_mov_b32_e32 v3, 0x240 -s_mov_b32 s7, 0x3100cfac -buffer_load_format_xyzw v[4:7], v3, s[4:7], 0 offen -s_waitcnt vmcnt(0) -v_mov_b32_e32 v8, 0x40 -buffer_store_dwordx4 v[4:7], v8, s[0:3], 0 offen -v_mov_b32_e32 v3, 0x250 -s_mov_b32 s7, 0x31009fac -buffer_load_format_xyzw v[4:7], v3, s[4:7], 0 offen -s_waitcnt vmcnt(0) -v_mov_b32_e32 v8, 0x50 -buffer_store_dwordx4 v[4:7], v8, s[0:3], 0 offen -v_mov_b32_e32 v3, 0x260 -s_mov_b32 s7, 0x3100afac -buffer_load_format_xyzw v[4:7], v3, s[4:7], 0 offen -s_waitcnt vmcnt(0) -v_mov_b32_e32 v8, 0x60 -buffer_store_dwordx4 v[4:7], v8, s[0:3], 0 offen -v_mov_b32_e32 v3, 0x270 -s_mov_b32 s7, 0x31013fac -buffer_load_format_xyzw v[4:7], v3, s[4:7], 0 offen -s_waitcnt vmcnt(0) -v_mov_b32_e32 v8, 0x70 -buffer_store_dwordx4 v[4:7], v8, s[0:3], 0 offen -v_mov_b32_e32 v3, 0x280 -s_mov_b32 s7, 0x31010fac -buffer_load_format_xyzw v[4:7], v3, s[4:7], 0 offen -s_waitcnt vmcnt(0) -v_mov_b32_e32 v8, 0x80 -buffer_store_dwordx4 v[4:7], v8, s[0:3], 0 offen -v_mov_b32_e32 v3, 0x290 -s_mov_b32 s7, 0x3103dfac -buffer_load_format_xyzw v[4:7], v3, s[4:7], 0 offen -s_waitcnt vmcnt(0) -v_mov_b32_e32 v8, 0x90 -buffer_store_dwordx4 v[4:7], v8, s[0:3], 0 offen -v_mov_b32_e32 v3, 0x2a0 -s_mov_b32 s7, 0x3103afac -buffer_load_format_xyzw v[4:7], v3, s[4:7], 0 offen -s_waitcnt vmcnt(0) -v_mov_b32_e32 v8, 0xa0 -buffer_store_dwordx4 v[4:7], v8, s[0:3], 0 offen -v_mov_b32_e32 v3, 0x2b0 -s_mov_b32 s7, 0x3103bfac -buffer_load_format_xyzw v[4:7], v3, s[4:7], 0 offen -s_waitcnt vmcnt(0) -v_mov_b32_e32 v8, 0xb0 -buffer_store_dwordx4 v[4:7], v8, s[0:3], 0 offen -v_mov_b32_e32 v3, 0x2c0 -s_mov_b32 s7, 0x3101cfac -buffer_load_format_xyzw v[4:7], v3, s[4:7], 0 offen -s_waitcnt vmcnt(0) -v_mov_b32_e32 v8, 0xc0 -buffer_store_dwordx4 v[4:7], v8, s[0:3], 0 offen -v_mov_b32_e32 v3, 0x2d0 -s_mov_b32 s7, 0x31019fac -buffer_load_format_xyzw v[4:7], v3, s[4:7], 0 offen -s_waitcnt vmcnt(0) -v_mov_b32_e32 v8, 0xd0 -buffer_store_dwordx4 v[4:7], v8, s[0:3], 0 offen -v_mov_b32_e32 v3, 0x2e0 -s_mov_b32 s7, 0x31044fac -buffer_load_format_xyzw v[4:7], v3, s[4:7], 0 offen -s_waitcnt vmcnt(0) -v_mov_b32_e32 v8, 0xe0 -buffer_store_dwordx4 v[4:7], v8, s[0:3], 0 offen -v_mov_b32_e32 v3, 0x2f0 -s_mov_b32 s7, 0x31024fac -buffer_load_format_xyzw v[4:7], v3, s[4:7], 0 offen -s_waitcnt vmcnt(0) -v_mov_b32_e32 v8, 0xf0 -buffer_store_dwordx4 v[4:7], v8, s[0:3], 0 offen -v_mov_b32_e32 v3, 0x300 -s_mov_b32 s7, 0x31024fac -buffer_load_format_xyzw v[4:7], v3, s[4:7], 0 offen -s_waitcnt vmcnt(0) -v_mov_b32_e32 v8, 0x100 -buffer_store_dwordx4 v[4:7], v8, s[0:3], 0 offen -v_mov_b32_e32 v3, 0x310 -s_mov_b32 s7, 0x31024fac -buffer_load_format_xyzw v[4:7], v3, s[4:7], 0 offen -s_waitcnt vmcnt(0) -v_mov_b32_e32 v8, 0x110 -buffer_store_dwordx4 v[4:7], v8, s[0:3], 0 offen -v_mov_b32_e32 v3, 0x320 -s_mov_b32 s7, 0x3102bfac -buffer_load_format_xyzw v[4:7], v3, s[4:7], 0 offen -s_waitcnt vmcnt(0) -v_mov_b32_e32 v8, 0x120 -buffer_store_dwordx4 v[4:7], v8, s[0:3], 0 offen -v_mov_b32_e32 v3, 0x330 -s_mov_b32 s7, 0x3102dfac -buffer_load_format_xyzw v[4:7], v3, s[4:7], 0 offen -s_waitcnt vmcnt(0) -v_mov_b32_e32 v8, 0x130 -buffer_store_dwordx4 v[4:7], v8, s[0:3], 0 offen -v_mov_b32_e32 v3, 0x340 -s_mov_b32 s7, 0x31031fac -buffer_load_format_xyzw v[4:7], v3, s[4:7], 0 offen -s_waitcnt vmcnt(0) -v_mov_b32_e32 v8, 0x140 -buffer_store_dwordx4 v[4:7], v8, s[0:3], 0 offen -v_mov_b32_e32 v3, 0x350 -s_mov_b32 s7, 0x31033fac -buffer_load_format_xyzw v[4:7], v3, s[4:7], 0 offen -s_waitcnt vmcnt(0) -v_mov_b32_e32 v8, 0x150 -buffer_store_dwordx4 v[4:7], v8, s[0:3], 0 offen -v_mov_b32_e32 v3, 0x360 -s_mov_b32 s7, 0x31034fac -buffer_load_format_xyzw v[4:7], v3, s[4:7], 0 offen -s_waitcnt vmcnt(0) -v_mov_b32_e32 v8, 0x160 -buffer_store_dwordx4 v[4:7], v8, s[0:3], 0 offen -v_mov_b32_e32 v3, 0x370 -s_mov_b32 s7, 0x31035fac -buffer_load_format_xyzw v[4:7], v3, s[4:7], 0 offen -s_waitcnt vmcnt(0) -v_mov_b32_e32 v8, 0x170 -buffer_store_dwordx4 v[4:7], v8, s[0:3], 0 offen -v_mov_b32_e32 v3, 0x380 -s_mov_b32 s7, 0x31037fac -buffer_load_format_xyzw v[4:7], v3, s[4:7], 0 offen -s_waitcnt vmcnt(0) -v_mov_b32_e32 v8, 0x180 -buffer_store_dwordx4 v[4:7], v8, s[0:3], 0 offen -v_mov_b32_e32 v3, 0x390 -s_mov_b32 s7, 0x31016fac -tbuffer_load_format_xyzw v[4:7], v3, s[4:7], 0 format:[BUF_FMT_11_11_10_FLOAT] offen -s_waitcnt vmcnt(0) -v_mov_b32_e32 v8, 0x190 -buffer_store_dwordx4 v[4:7], v8, s[0:3], 0 offen -v_mov_b32_e32 v3, 0x3a0 -s_mov_b32 s7, 0x31016fac -tbuffer_load_format_xyzw v[4:7], v3, s[4:7], 0 format:[BUF_FMT_8_8_8_8_SINT] offen -s_waitcnt vmcnt(0) -v_mov_b32_e32 v8, 0x1a0 -buffer_store_dwordx4 v[4:7], v8, s[0:3], 0 offen -v_mov_b32_e32 v3, 0x3b0 -s_mov_b32 s7, 0x31016fac -tbuffer_load_format_xyzw v[4:7], v3, s[4:7], 0 format:[BUF_FMT_16_16_SINT] offen -s_waitcnt vmcnt(0) -v_mov_b32_e32 v8, 0x1b0 -buffer_store_dwordx4 v[4:7], v8, s[0:3], 0 offen -v_mov_b32_e32 v3, 0x3c0 -s_mov_b32 s7, 0x3101efac -buffer_load_format_xyzw v[4:7], v3, s[4:7], 0 offen -s_waitcnt vmcnt(0) -v_mov_b32_e32 v8, 0x1c0 -buffer_store_dwordx4 v[4:7], v8, s[0:3], 0 offen -v_mov_b32_e32 v3, 0x3d0 -s_mov_b32 s7, 0x31026fac -buffer_load_format_xyzw v[4:7], v3, s[4:7], 0 offen -s_waitcnt vmcnt(0) -v_mov_b32_e32 v8, 0x1d0 -buffer_store_dwordx4 v[4:7], v8, s[0:3], 0 offen -v_mov_b32_e32 v3, 0x3e0 -s_mov_b32 s7, 0x31022fac -buffer_load_format_xyzw v[4:7], v3, s[4:7], 0 offen -s_waitcnt vmcnt(0) -v_mov_b32_e32 v8, 0x1e0 -buffer_store_dwordx4 v[4:7], v8, s[0:3], 0 offen -v_mov_b32_e32 v3, 0x3f0 -s_mov_b32 s7, 0x3102afac -buffer_load_format_xyzw v[4:7], v3, s[4:7], 0 offen -s_waitcnt vmcnt(0) -v_mov_b32_e32 v8, 0x1f0 -buffer_store_dwordx4 v[4:7], v8, s[0:3], 0 offen -v_mov_b32_e32 v4, 0x100 -v_mov_b32_e32 v5, 0x0 -v_mov_b32_e32 v6, 0x0 -v_mov_b32_e32 v7, 0x0 -s_mov_b32 s7, 0x31006fac -v_mov_b32_e32 v9, 0x400 -buffer_store_format_xyzw v[4:7], v9, s[4:7], 0 offen -v_mov_b32_e32 v4, 0xffffff00 -v_mov_b32_e32 v5, 0x0 -v_mov_b32_e32 v6, 0x0 -v_mov_b32_e32 v7, 0x0 -s_mov_b32 s7, 0x31006fac -v_mov_b32_e32 v9, 0x410 -buffer_store_format_xyzw v[4:7], v9, s[4:7], 0 offen -v_mov_b32_e32 v4, 0x1ff -v_mov_b32_e32 v5, 0x0 -v_mov_b32_e32 v6, 0x0 -v_mov_b32_e32 v7, 0x0 -s_mov_b32 s7, 0x31005fac -v_mov_b32_e32 v9, 0x420 -buffer_store_format_xyzw v[4:7], v9, s[4:7], 0 offen -v_mov_b32_e32 v4, 0x3f800000 -v_mov_b32_e32 v5, 0x0 -v_mov_b32_e32 v6, 0x0 -v_mov_b32_e32 v7, 0x0 -s_mov_b32 s7, 0x31003fac -v_mov_b32_e32 v9, 0x430 -buffer_store_format_xyzw v[4:7], v9, s[4:7], 0 offen -v_mov_b32_e32 v4, 0x8000 -v_mov_b32_e32 v5, 0x0 -v_mov_b32_e32 v6, 0x0 -v_mov_b32_e32 v7, 0x0 -s_mov_b32 s7, 0x3100cfac -v_mov_b32_e32 v9, 0x440 -buffer_store_format_xyzw v[4:7], v9, s[4:7], 0 offen -v_mov_b32_e32 v4, 0x12345 -v_mov_b32_e32 v5, 0xffff0000 -v_mov_b32_e32 v6, 0x7 -v_mov_b32_e32 v7, 0xffff8000 -s_mov_b32 s7, 0x3101cfac -v_mov_b32_e32 v9, 0x450 -buffer_store_format_xyzw v[4:7], v9, s[4:7], 0 offen -v_mov_b32_e32 v4, 0x3f800000 -v_mov_b32_e32 v5, 0x3f000000 -v_mov_b32_e32 v6, 0x3e800000 -v_mov_b32_e32 v7, 0x3f400000 -s_mov_b32 s7, 0x31010fac -v_mov_b32_e32 v9, 0x460 -buffer_store_format_xyzw v[4:7], v9, s[4:7], 0 offen -v_mov_b32_e32 v4, 0xbf800000 -v_mov_b32_e32 v5, 0x3f000000 -v_mov_b32_e32 v6, 0x3f800000 -v_mov_b32_e32 v7, 0x0 -s_mov_b32 s7, 0x3101ffac -v_mov_b32_e32 v9, 0x470 -buffer_store_format_xyzw v[4:7], v9, s[4:7], 0 offen -v_mov_b32_e32 v4, 0x7ff -v_mov_b32_e32 v5, 0x5 -v_mov_b32_e32 v6, 0xffffffff -v_mov_b32_e32 v7, 0x0 -s_mov_b32 s7, 0x31029fac -v_mov_b32_e32 v9, 0x480 -buffer_store_format_xyzw v[4:7], v9, s[4:7], 0 offen -v_mov_b32_e32 v4, 0x7149f2ca -v_mov_b32_e32 v5, 0x3effffff -v_mov_b32_e32 v6, 0x7f800001 -v_mov_b32_e32 v7, 0x80000000 -s_mov_b32 s7, 0x31047fac -v_mov_b32_e32 v9, 0x490 -buffer_store_format_xyzw v[4:7], v9, s[4:7], 0 offen -v_mov_b32_e32 v4, 0x3e99999a -v_mov_b32_e32 v5, 0x37c000c0 -v_mov_b32_e32 v6, 0x0 -v_mov_b32_e32 v7, 0x0 -s_mov_b32 s7, 0x31017fac -v_mov_b32_e32 v9, 0x4a0 -buffer_store_format_xyzw v[4:7], v9, s[4:7], 0 offen -v_mov_b32_e32 v4, 0x3f800000 -v_mov_b32_e32 v5, 0xbf800000 -v_mov_b32_e32 v6, 0x3f000000 -v_mov_b32_e32 v7, 0xbf000000 -s_mov_b32 s7, 0x3103bfac -v_mov_b32_e32 v9, 0x4b0 -buffer_store_format_xyzw v[4:7], v9, s[4:7], 0 offen -v_mov_b32_e32 v4, 0x3f800000 -v_mov_b32_e32 v5, 0x40000000 -v_mov_b32_e32 v6, 0x3f000000 -v_mov_b32_e32 v7, 0x0 -s_mov_b32 s7, 0x31024fac -v_mov_b32_e32 v9, 0x4c0 -buffer_store_format_xyzw v[4:7], v9, s[4:7], 0 offen -v_mov_b32_e32 v4, 0xbf800000 -v_mov_b32_e32 v5, 0x7f800000 -v_mov_b32_e32 v6, 0x47ffe000 -v_mov_b32_e32 v7, 0x0 -s_mov_b32 s7, 0x31024fac -v_mov_b32_e32 v9, 0x4d0 -buffer_store_format_xyzw v[4:7], v9, s[4:7], 0 offen -v_mov_b32_e32 v4, 0x3f800000 -v_mov_b32_e32 v5, 0x477fe000 -v_mov_b32_e32 v6, 0x7f800001 -v_mov_b32_e32 v7, 0x0 -s_mov_b32 s7, 0x3102bfac -v_mov_b32_e32 v9, 0x4e0 -buffer_store_format_xyzw v[4:7], v9, s[4:7], 0 offen -v_mov_b32_e32 v4, 0x3f000000 -v_mov_b32_e32 v5, 0xbf800000 -v_mov_b32_e32 v6, 0x3f800000 -v_mov_b32_e32 v7, 0x3e99999a -s_mov_b32 s7, 0x3102dfac -v_mov_b32_e32 v9, 0x4f0 -buffer_store_format_xyzw v[4:7], v9, s[4:7], 0 offen -v_mov_b32_e32 v4, 0x3f800000 -v_mov_b32_e32 v5, 0x3f000000 -v_mov_b32_e32 v6, 0x3e800000 -v_mov_b32_e32 v7, 0x3f800000 -s_mov_b32 s7, 0x31034fac -v_mov_b32_e32 v9, 0x500 -buffer_store_format_xyzw v[4:7], v9, s[4:7], 0 offen -v_mov_b32_e32 v4, 0x7fffffff -v_mov_b32_e32 v5, 0x80000000 -v_mov_b32_e32 v6, 0x5 -v_mov_b32_e32 v7, 0x5 -s_mov_b32 s7, 0x31037fac -v_mov_b32_e32 v9, 0x510 -buffer_store_format_xyzw v[4:7], v9, s[4:7], 0 offen -v_mov_b32_e32 v4, 0x3ff -v_mov_b32_e32 v5, 0x5 -v_mov_b32_e32 v6, 0x7d0 -v_mov_b32_e32 v7, 0x9 -s_mov_b32 s7, 0x31030fac -v_mov_b32_e32 v9, 0x520 -buffer_store_format_xyzw v[4:7], v9, s[4:7], 0 offen -v_mov_b32_e32 v4, 0xffff8000 -v_mov_b32_e32 v5, 0x8000 -v_mov_b32_e32 v6, 0x7fff -v_mov_b32_e32 v7, 0xffffffff -s_mov_b32 s7, 0x31046fac -v_mov_b32_e32 v9, 0x530 -buffer_store_format_xyzw v[4:7], v9, s[4:7], 0 offen -s_endpgm diff --git a/runtime/test/shaders/cs_fmt_d16_xyz.asm b/runtime/test/shaders/cs_fmt_d16_xyz.asm deleted file mode 100644 index 1f309b50c..000000000 --- a/runtime/test/shaders/cs_fmt_d16_xyz.asm +++ /dev/null @@ -1,99 +0,0 @@ -; regen_fixtures: this source has a translator fixture in tests/semantic/fixtures/disasm -; The d16 typed-buffer forms no other test runs: buffer_load_format_d16_xyz, tbuffer_load_format_d16_xy, -; tbuffer_load_format_d16_xyz and buffer_store_format_d16_xyz. One thread (lane 0) does everything. -; RDNA2 ISA (MUBUF/MTBUF): a d16 load converts each component to 16 bits (f16 for float and normalized formats, the -; integer saturated to 16 bits for UINT/SINT) and packs two per VGPR, X in bits 15:0 and Y in 31:16 of the first, Z -; in 15:0 of the second. docs/design.md (d16 and f16 format narrowing): an odd final component (d16_x, d16_xyz) -; writes only the low 16 bits of its VGPR and the high half keeps its bits; unsigned 32-bit channels clamp to 65535. -; A d16 store takes the components from the same halves and encodes them in the V# format (an f16 widened to the -; f32 of a 32_FLOAT channel, a 16-bit integer zero-extended into a 32_UINT channel). -; MUBUF uses the V# format (word3 bits 18:12) and DST_SEL (bits 11:0, here X Y Z W); MTBUF uses the instruction's -; format and identity selectors with a bound V# (32_FLOAT). V# word3 = 0x31000fac | format << 12. -; Inputs, written first by lane 0: -; 0x100: 0xabcd1234 0x55557fff 16_16_16_16 X=0x1234 Y=0xabcd Z=0x7fff W=0x5555 -; 0x108: 0xc0003c00 0x7bff3555 f16 X=1.0 (0x3c00) Y=-2.0 (0xc000) Z=0x3555 (0.33325) W=0x7bff -; 0x110: 5 0x10000 0xffffffff 0 32-bit X Y Z (and a zero pad) -; 0x120: 0x80ff00ff 8_8_8_8 X=0xff Y=0x00 Z=0xff W=0x80 -; Loads (the second VGPR of each _xyz is seeded first; its high half must survive): -; L1 buffer_load_format_d16_xyz v[8:9] @0x100, V# 16_16_16_16_UINT (69): X, Y, Z fit in 16 bits. -; v8 = 0xabcd1234; v9 = 0xa5a5 << 16 | 0x7fff = 0xa5a57fff (seed 0xa5a55a5a) -; L2 buffer_load_format_d16_xyz v[10:11] @0x110, V# 32_32_32_UINT (72): 5, min(0x10000, 65535) = 0xffff, -; min(0xffffffff, 65535) = 0xffff. v10 = 0xffff0005; v11 = 0x1234ffff (seed 0x12345678) -; L3 tbuffer_load_format_d16_xy v12 @0x108, BUF_FMT_16_16_FLOAT: the f16 bits as they are. v12 = 0xc0003c00 -; L4 tbuffer_load_format_d16_xyz v[13:14] @0x108, BUF_FMT_16_16_16_16_FLOAT: v13 = 0xc0003c00; -; v14 = 0xbeef3555 (seed 0xbeef7777) -; L5 tbuffer_load_format_d16_xyz v[15:16] @0x120, BUF_FMT_8_8_8_8_UNORM: 255/255 = 1.0 -> 0x3c00, 0/255 = 0, -; 255/255 = 1.0 -> 0x3c00 (exact, no rounding). v15 = 0x00003c00; v16 = 0xcafe3c00 (seed 0xcafe1111) -; L6 tbuffer_load_format_d16_xyz v[17:18] @0x110, BUF_FMT_32_32_32_UINT: as L2. v17 = 0xffff0005; -; v18 = 0x0badffff (seed 0x0bad0bad) -; v8..v18 go to out[0..10] (0x00..0x28); out[11..15] are untouched (0xeeeeeeee). -; Stores (the fourth word of each 16-byte region stays untouched): -; S1 buffer_store_format_d16_xyz v[20:21] @0x40, V# 32_32_32_UINT (72): v20 = 0x80010007, v21 = 0xdeadfffe -; -> X = 0x0007, Y = 0x8001, Z = 0xfffe (v21's high half is not a component), zero-extended: -; out[16..19] = 0x00000007 0x00008001 0x0000fffe 0xeeeeeeee -; S2 buffer_store_format_d16_xyz v[22:23] @0x50, V# 32_32_32_FLOAT (74): v22 = 0xc0003c00, v23 = 0x12343800 -; -> 1.0, -2.0, 0.5 (0x3800) as f32: out[20..23] = 0x3f800000 0xc0000000 0x3f000000 0xeeeeeeee -; out[24..63] are untouched except the inputs at out[64..72] (0x100..0x120); the dump is 80 words. -; Run: VKC_OUT_WORDS=80 VKC_DUMP= vk_compute_test cs_fmt_d16_xyz.spv 1 dump -v_cmpx_eq_u32_e32 0, v0 -s_mov_b32 s4, s0 -s_mov_b32 s5, s1 -s_mov_b32 s6, s2 -v_mov_b32_e32 v1, 0xabcd1234 -v_mov_b32_e32 v2, 0x55557fff -v_mov_b32_e32 v3, 0xc0003c00 -v_mov_b32_e32 v4, 0x7bff3555 -v_mov_b32_e32 v5, 0x100 -buffer_store_dwordx4 v[1:4], v5, s[0:3], 0 offen -v_mov_b32_e32 v1, 5 -v_mov_b32_e32 v2, 0x10000 -v_mov_b32_e32 v3, -1 -v_mov_b32_e32 v4, 0 -v_mov_b32_e32 v5, 0x110 -buffer_store_dwordx4 v[1:4], v5, s[0:3], 0 offen -v_mov_b32_e32 v1, 0x80ff00ff -v_mov_b32_e32 v5, 0x120 -buffer_store_dword v1, v5, s[0:3], 0 offen -s_waitcnt vmcnt(0) -; L1 -s_mov_b32 s7, 0x31045fac -v_mov_b32_e32 v5, 0x100 -v_mov_b32_e32 v9, 0xa5a55a5a -buffer_load_format_d16_xyz v[8:9], v5, s[4:7], 0 offen -; L2 -s_mov_b32 s7, 0x31048fac -v_mov_b32_e32 v5, 0x110 -v_mov_b32_e32 v11, 0x12345678 -buffer_load_format_d16_xyz v[10:11], v5, s[4:7], 0 offen -; L3..L6: MTBUF with a bound 32_FLOAT V# -s_mov_b32 s7, 0x31016fac -v_mov_b32_e32 v5, 0x108 -tbuffer_load_format_d16_xy v12, v5, s[4:7], 0 format:[BUF_FMT_16_16_FLOAT] offen -v_mov_b32_e32 v14, 0xbeef7777 -tbuffer_load_format_d16_xyz v[13:14], v5, s[4:7], 0 format:[BUF_FMT_16_16_16_16_FLOAT] offen -v_mov_b32_e32 v5, 0x120 -v_mov_b32_e32 v16, 0xcafe1111 -tbuffer_load_format_d16_xyz v[15:16], v5, s[4:7], 0 format:[BUF_FMT_8_8_8_8_UNORM] offen -v_mov_b32_e32 v5, 0x110 -v_mov_b32_e32 v18, 0x0bad0bad -tbuffer_load_format_d16_xyz v[17:18], v5, s[4:7], 0 format:[BUF_FMT_32_32_32_UINT] offen -s_waitcnt vmcnt(0) -v_mov_b32_e32 v6, 0 -buffer_store_dwordx4 v[8:11], v6, s[0:3], 0 offen -v_mov_b32_e32 v6, 0x10 -buffer_store_dwordx4 v[12:15], v6, s[0:3], 0 offen -v_mov_b32_e32 v6, 0x20 -buffer_store_dwordx3 v[16:18], v6, s[0:3], 0 offen -; S1 -s_mov_b32 s7, 0x31048fac -v_mov_b32_e32 v20, 0x80010007 -v_mov_b32_e32 v21, 0xdeadfffe -v_mov_b32_e32 v6, 0x40 -buffer_store_format_d16_xyz v[20:21], v6, s[4:7], 0 offen -; S2 -s_mov_b32 s7, 0x3104afac -v_mov_b32_e32 v22, 0xc0003c00 -v_mov_b32_e32 v23, 0x12343800 -v_mov_b32_e32 v6, 0x50 -buffer_store_format_d16_xyz v[22:23], v6, s[4:7], 0 offen -s_endpgm diff --git a/runtime/test/shaders/cs_fmt_int_narrow.asm b/runtime/test/shaders/cs_fmt_int_narrow.asm deleted file mode 100644 index f73f7e588..000000000 --- a/runtime/test/shaders/cs_fmt_int_narrow.asm +++ /dev/null @@ -1,127 +0,0 @@ -; regen_fixtures: this source has a translator fixture in tests/semantic/fixtures/disasm -; Narrow integer typed buffers: 8/16-bit UINT and SINT formats 5, 6, 11, 12, 18, 19, 28, 61 and 70. -; Lane 0 writes the source dwords 0x7f01ff80 0x8000ffff 0x12345678 0x9abcdef0 at byte 0x200, then: -; out[0..35]: buffer_load_format_xyzw with DST_SEL XYZW, four words per format in the order above; -; out[36..43]: DST_SEL X011 for 8_SINT and 16_UINT (0 and integer 1); -; out[44..49]: buffer_load_format_d16_xyzw for 8_SINT, 8_8_8_8_SINT and 16_16_16_16_SINT; -; out[64..81]: buffer_store_format_xyzw of 0x7f, 0x80, -128, -129 (8-bit formats) or 0x7fff, 0x8000, -32768, -; -32769 (16-bit) at a dword pair per format, with the runtime's selectors (X001, XY01, XYZW); SINT clamps -; signed, UINT saturates, and a 1-2 byte element keeps the 0xee fill of the rest of its dword. -; The expected words (check.py FMT_INT_NARROW_WORDS) are this program's output on gfx1036, run natively. -v_cmpx_eq_u32_e32 0, v0 -v_mov_b32_e32 v1, 0x7f01ff80 -v_mov_b32_e32 v2, 0x8000ffff -v_mov_b32_e32 v3, 0x12345678 -v_mov_b32_e32 v4, 0x9abcdef0 -v_mov_b32_e32 v5, 0x200 -buffer_store_dwordx4 v[1:4], v5, s[0:3], 0 offen -s_waitcnt_vscnt null, 0x0 -s_mov_b32 s4, s0 -s_mov_b32 s5, s1 -s_mov_b32 s6, s2 -s_mov_b32 s7, 0x31005fac -buffer_load_format_xyzw v[8:11], v5, s[4:7], 0 offen -s_waitcnt vmcnt(0) -v_mov_b32_e32 v6, 0x0 -buffer_store_dwordx4 v[8:11], v6, s[0:3], 0 offen -s_mov_b32 s7, 0x31006fac -buffer_load_format_xyzw v[8:11], v5, s[4:7], 0 offen -s_waitcnt vmcnt(0) -v_mov_b32_e32 v6, 0x10 -buffer_store_dwordx4 v[8:11], v6, s[0:3], 0 offen -s_mov_b32 s7, 0x3100bfac -buffer_load_format_xyzw v[8:11], v5, s[4:7], 0 offen -s_waitcnt vmcnt(0) -v_mov_b32_e32 v6, 0x20 -buffer_store_dwordx4 v[8:11], v6, s[0:3], 0 offen -s_mov_b32 s7, 0x3100cfac -buffer_load_format_xyzw v[8:11], v5, s[4:7], 0 offen -s_waitcnt vmcnt(0) -v_mov_b32_e32 v6, 0x30 -buffer_store_dwordx4 v[8:11], v6, s[0:3], 0 offen -s_mov_b32 s7, 0x31012fac -buffer_load_format_xyzw v[8:11], v5, s[4:7], 0 offen -s_waitcnt vmcnt(0) -v_mov_b32_e32 v6, 0x40 -buffer_store_dwordx4 v[8:11], v6, s[0:3], 0 offen -s_mov_b32 s7, 0x31013fac -buffer_load_format_xyzw v[8:11], v5, s[4:7], 0 offen -s_waitcnt vmcnt(0) -v_mov_b32_e32 v6, 0x50 -buffer_store_dwordx4 v[8:11], v6, s[0:3], 0 offen -s_mov_b32 s7, 0x3101cfac -buffer_load_format_xyzw v[8:11], v5, s[4:7], 0 offen -s_waitcnt vmcnt(0) -v_mov_b32_e32 v6, 0x60 -buffer_store_dwordx4 v[8:11], v6, s[0:3], 0 offen -s_mov_b32 s7, 0x3103dfac -buffer_load_format_xyzw v[8:11], v5, s[4:7], 0 offen -s_waitcnt vmcnt(0) -v_mov_b32_e32 v6, 0x70 -buffer_store_dwordx4 v[8:11], v6, s[0:3], 0 offen -s_mov_b32 s7, 0x31046fac -buffer_load_format_xyzw v[8:11], v5, s[4:7], 0 offen -s_waitcnt vmcnt(0) -v_mov_b32_e32 v6, 0x80 -buffer_store_dwordx4 v[8:11], v6, s[0:3], 0 offen -s_mov_b32 s7, 0x31006244 -buffer_load_format_xyzw v[8:11], v5, s[4:7], 0 offen -s_waitcnt vmcnt(0) -v_mov_b32_e32 v6, 0x90 -buffer_store_dwordx4 v[8:11], v6, s[0:3], 0 offen -s_mov_b32 s7, 0x3100b244 -buffer_load_format_xyzw v[8:11], v5, s[4:7], 0 offen -s_waitcnt vmcnt(0) -v_mov_b32_e32 v6, 0xa0 -buffer_store_dwordx4 v[8:11], v6, s[0:3], 0 offen -s_mov_b32 s7, 0x31006fac -buffer_load_format_d16_xyzw v[8:9], v5, s[4:7], 0 offen -s_waitcnt vmcnt(0) -v_mov_b32_e32 v6, 0xb0 -buffer_store_dwordx2 v[8:9], v6, s[0:3], 0 offen -s_mov_b32 s7, 0x3103dfac -buffer_load_format_d16_xyzw v[8:9], v5, s[4:7], 0 offen -s_waitcnt vmcnt(0) -v_mov_b32_e32 v6, 0xb8 -buffer_store_dwordx2 v[8:9], v6, s[0:3], 0 offen -s_mov_b32 s7, 0x31046fac -buffer_load_format_d16_xyzw v[8:9], v5, s[4:7], 0 offen -s_waitcnt vmcnt(0) -v_mov_b32_e32 v6, 0xc0 -buffer_store_dwordx2 v[8:9], v6, s[0:3], 0 offen -v_mov_b32_e32 v12, 0x7f -v_mov_b32_e32 v13, 0x80 -v_mov_b32_e32 v14, 0xffffff80 -v_mov_b32_e32 v15, 0xffffff7f -v_mov_b32_e32 v16, 0x7fff -v_mov_b32_e32 v17, 0x8000 -v_mov_b32_e32 v18, 0xffff8000 -v_mov_b32_e32 v19, 0xffff7fff -s_mov_b32 s7, 0x31005204 -v_mov_b32_e32 v6, 0x100 -buffer_store_format_xyzw v[12:15], v6, s[4:7], 0 offen -s_mov_b32 s7, 0x31006204 -v_mov_b32_e32 v6, 0x108 -buffer_store_format_xyzw v[12:15], v6, s[4:7], 0 offen -s_mov_b32 s7, 0x3100b204 -v_mov_b32_e32 v6, 0x110 -buffer_store_format_xyzw v[16:19], v6, s[4:7], 0 offen -s_mov_b32 s7, 0x3100c204 -v_mov_b32_e32 v6, 0x118 -buffer_store_format_xyzw v[16:19], v6, s[4:7], 0 offen -s_mov_b32 s7, 0x3101222c -v_mov_b32_e32 v6, 0x120 -buffer_store_format_xyzw v[12:15], v6, s[4:7], 0 offen -s_mov_b32 s7, 0x3101322c -v_mov_b32_e32 v6, 0x128 -buffer_store_format_xyzw v[12:15], v6, s[4:7], 0 offen -s_mov_b32 s7, 0x3101c22c -v_mov_b32_e32 v6, 0x130 -buffer_store_format_xyzw v[16:19], v6, s[4:7], 0 offen -s_mov_b32 s7, 0x3103dfac -v_mov_b32_e32 v6, 0x138 -buffer_store_format_xyzw v[12:15], v6, s[4:7], 0 offen -s_mov_b32 s7, 0x31046fac -v_mov_b32_e32 v6, 0x140 -buffer_store_format_xyzw v[16:19], v6, s[4:7], 0 offen -s_endpgm diff --git a/runtime/test/shaders/cs_fmt_sint32.asm b/runtime/test/shaders/cs_fmt_sint32.asm deleted file mode 100644 index 740675682..000000000 --- a/runtime/test/shaders/cs_fmt_sint32.asm +++ /dev/null @@ -1,91 +0,0 @@ -; regen_fixtures: this source has a translator fixture in tests/semantic/fixtures/disasm -; SHADER-257: GFX10 32-bit signed typed buffers. Lane 0 writes [-2147483648, 2147483647, -3, 17] at 0x80. -; MUBUF loads at out[0..11] test integer DST_SEL=1 for format 63 (X,Y,X,1) and raw words for 73/76. -; MTBUF loads at out[12..23] use a bound 32_FLOAT descriptor and take width and identity selectors from the -; instruction (XY00, XYZ0, XYZW). D16 loads at out[24..27] check signed saturation, including -3, for both forms. -; Single-channel SINT MUBUF/MTBUF loads place -3 in out[28..29]. -; MUBUF stores at 0x90/0xa0/0xb0 write the low 2/3/4 original words. The D16 store at 0xc0 sign-extends -; 0xfffd and 0x8000 to dwords. The single-channel store at 0xc8 writes -3. Unwritten words retain 0xeeeeeeee. -v_cmpx_eq_u32_e32 0, v0 -v_mov_b32_e32 v1, 0x80000000 -v_mov_b32_e32 v2, 0x7fffffff -v_mov_b32_e32 v3, -3 -v_mov_b32_e32 v4, 17 -v_mov_b32_e32 v5, 0x80 -buffer_store_dwordx4 v[1:4], v5, s[0:3], 0 offen -s_mov_b32 s4, s0 -s_mov_b32 s5, s1 -s_mov_b32 s6, s2 - -; MUBUF load via format 63. -s_mov_b32 s7, 0x3103f32c -buffer_load_format_xyzw v[8:11], v5, s[4:7], 0 offen -v_mov_b32_e32 v6, 0x0 -buffer_store_dwordx4 v[8:11], v6, s[0:3], 0 offen - -; MUBUF load via format 73. -s_mov_b32 s7, 0x31049fac -buffer_load_format_xyzw v[8:11], v5, s[4:7], 0 offen -v_mov_b32_e32 v6, 0x10 -buffer_store_dwordx4 v[8:11], v6, s[0:3], 0 offen - -; MUBUF load via format 76. -s_mov_b32 s7, 0x3104cfac -buffer_load_format_xyzw v[8:11], v5, s[4:7], 0 offen -v_mov_b32_e32 v6, 0x20 -buffer_store_dwordx4 v[8:11], v6, s[0:3], 0 offen - -; A bound FLOAT descriptor with a different size and selectors from each instruction. -s_mov_b32 s7, 0x31016000 -tbuffer_load_format_xyzw v[8:11], v5, s[4:7], 0 format:[BUF_FMT_32_32_SINT] offen -v_mov_b32_e32 v6, 0x30 -buffer_store_dwordx4 v[8:11], v6, s[0:3], 0 offen -tbuffer_load_format_xyzw v[8:11], v5, s[4:7], 0 format:[BUF_FMT_32_32_32_SINT] offen -v_mov_b32_e32 v6, 0x40 -buffer_store_dwordx4 v[8:11], v6, s[0:3], 0 offen -tbuffer_load_format_xyzw v[8:11], v5, s[4:7], 0 format:[BUF_FMT_32_32_32_32_SINT] offen -v_mov_b32_e32 v6, 0x50 -buffer_store_dwordx4 v[8:11], v6, s[0:3], 0 offen - -; Packs (0x8000, 0x7fff) and (0xfffd, 0x0011). -s_mov_b32 s7, 0x3104cfac -buffer_load_format_d16_xyzw v[8:9], v5, s[4:7], 0 offen -v_mov_b32_e32 v6, 0x60 -buffer_store_dwordx2 v[8:9], v6, s[0:3], 0 offen -s_mov_b32 s7, 0x31016000 -tbuffer_load_format_d16_xyzw v[8:9], v5, s[4:7], 0 format:[BUF_FMT_32_32_32_32_SINT] offen -v_mov_b32_e32 v6, 0x68 -buffer_store_dwordx2 v[8:9], v6, s[0:3], 0 offen - -; Single-component 32_SINT at 0x88, with a bound FLOAT descriptor for the MTBUF case. -s_mov_b32 s7, 0x31015004 -buffer_load_format_x v8, v5, s[4:7], 0 offen offset:8 -s_mov_b32 s7, 0x31016000 -tbuffer_load_format_x v9, v5, s[4:7], 0 format:[BUF_FMT_32_SINT] offen offset:8 -v_mov_b32_e32 v6, 0x70 -buffer_store_dwordx2 v[8:9], v6, s[0:3], 0 offen - -; MUBUF store via format 63 (DST_SEL XY01, standard 2-component RG). -s_mov_b32 s7, 0x3103f22c -v_mov_b32_e32 v6, 0x90 -buffer_store_format_xy v[1:2], v6, s[4:7], 0 offen - -; MUBUF store via format 73. -s_mov_b32 s7, 0x31049fac -v_mov_b32_e32 v6, 0xa0 -buffer_store_format_xyz v[1:3], v6, s[4:7], 0 offen - -; MUBUF store via format 76. -s_mov_b32 s7, 0x3104cfac -v_mov_b32_e32 v6, 0xb0 -buffer_store_format_xyzw v[1:4], v6, s[4:7], 0 offen - -; A signed packed store must extend both halves. -s_mov_b32 s7, 0x3103f22c -v_mov_b32_e32 v6, 0xc0 -v_mov_b32_e32 v7, 0x8000fffd -buffer_store_format_d16_xy v7, v6, s[4:7], 0 offen -s_mov_b32 s7, 0x31015004 -v_mov_b32_e32 v6, 0xc8 -buffer_store_format_x v3, v6, s[4:7], 0 offen -s_endpgm diff --git a/runtime/test/shaders/cs_fmt_xy_xyz.asm b/runtime/test/shaders/cs_fmt_xy_xyz.asm deleted file mode 100644 index 0df5f8ca4..000000000 --- a/runtime/test/shaders/cs_fmt_xy_xyz.asm +++ /dev/null @@ -1,353 +0,0 @@ -; buffer_load_format_xy/xyz, tbuffer_load_format_xy/xyz and buffer_store_format_xy/xyz (TEST-185). Every expected -; word in the original fixture was measured by running its body natively on a Radeon 680M (gfx1035, RDNA2) through tools/hw_oracle's kernel -; wrapper, with s[0:3] set to the V# vk_compute_test passes; wave32 and wave64 gave the same 84 words. One thread runs. -; The updated UINT store at 0x2a0 and all 84 current words were checked on gfx1036 in both wave sizes. -; - Loads write only their 2 or 3 VGPRs; the next ones keep 0x5a5a00xx. A missing channel repeats one the format has -; (component c reads c mod n, SHADER-86): 32_32 xyz gives (x, y, x), 32 xy gives (x, x). -; - tbuffer loads take the instruction's format, not the V#'s. -; - Bounds: the whole element must end inside num_records (OOB_SELECT 3), even when the loaded components do: with -; NR 0x208, an xy load of a 16-byte element at 0x200 reads 0, 0. A 32_32_32_32 element that fits reads normally. -; - Stores write the whole element: x, y (or x, y, z) and 0 for the format's other components (xy into 32_32_32_32 -; leaves z = w = 0, xyz into 16_16_16_16 leaves w = 0). Into a one-channel format only x is written. A store whose -; element ends past num_records writes nothing. -; Inputs: RGBA32F (1, 2, 3, 4) at 0x200, RGBA16F (1, 2, 3, 4) at 0x210. Store regions 0x240..0x2cf start as -; 0xa5a50000 | address. out[0..47] are the 12 loads, out[48..83] the 9 store regions read back, in source order. -; Run: VKC_OUT_WORDS=192 VKC_DUMP= vk_compute_test cs_fmt_xy_xyz.spv 1 dump; check.py compares words 0..127 of -; the dump with FMT_XY_XYZ_WORDS and 44 untouched 0xeeeeeeee words. -v_cmpx_eq_u32_e32 0, v0 -; inputs: RGBA32F (1, 2, 3, 4) at 0x200, RGBA16F (1, 2, 3, 4) at 0x210 -v_mov_b32_e32 v1, 1.0 -v_mov_b32_e32 v2, 2.0 -v_mov_b32_e32 v3, 0x40400000 -v_mov_b32_e32 v4, 4.0 -v_mov_b32_e32 v5, 0x200 -buffer_store_dwordx4 v[1:4], v5, s[0:3], 0 offen -v_mov_b32_e32 v1, 0x40003c00 -v_mov_b32_e32 v2, 0x44004200 -v_mov_b32_e32 v5, 0x210 -buffer_store_dwordx2 v[1:2], v5, s[0:3], 0 offen -; the store regions 0x240..0x2cf hold 0xa5a50000 | their address -v_mov_b32_e32 v1, 0xa5a50240 -v_mov_b32_e32 v2, 0xa5a50244 -v_mov_b32_e32 v3, 0xa5a50248 -v_mov_b32_e32 v4, 0xa5a5024c -v_mov_b32_e32 v5, 0x240 -buffer_store_dwordx4 v[1:4], v5, s[0:3], 0 offen -v_mov_b32_e32 v1, 0xa5a50250 -v_mov_b32_e32 v2, 0xa5a50254 -v_mov_b32_e32 v3, 0xa5a50258 -v_mov_b32_e32 v4, 0xa5a5025c -v_mov_b32_e32 v5, 0x250 -buffer_store_dwordx4 v[1:4], v5, s[0:3], 0 offen -v_mov_b32_e32 v1, 0xa5a50260 -v_mov_b32_e32 v2, 0xa5a50264 -v_mov_b32_e32 v3, 0xa5a50268 -v_mov_b32_e32 v4, 0xa5a5026c -v_mov_b32_e32 v5, 0x260 -buffer_store_dwordx4 v[1:4], v5, s[0:3], 0 offen -v_mov_b32_e32 v1, 0xa5a50270 -v_mov_b32_e32 v2, 0xa5a50274 -v_mov_b32_e32 v3, 0xa5a50278 -v_mov_b32_e32 v4, 0xa5a5027c -v_mov_b32_e32 v5, 0x270 -buffer_store_dwordx4 v[1:4], v5, s[0:3], 0 offen -v_mov_b32_e32 v1, 0xa5a50280 -v_mov_b32_e32 v2, 0xa5a50284 -v_mov_b32_e32 v3, 0xa5a50288 -v_mov_b32_e32 v4, 0xa5a5028c -v_mov_b32_e32 v5, 0x280 -buffer_store_dwordx4 v[1:4], v5, s[0:3], 0 offen -v_mov_b32_e32 v1, 0xa5a50290 -v_mov_b32_e32 v2, 0xa5a50294 -v_mov_b32_e32 v3, 0xa5a50298 -v_mov_b32_e32 v4, 0xa5a5029c -v_mov_b32_e32 v5, 0x290 -buffer_store_dwordx4 v[1:4], v5, s[0:3], 0 offen -v_mov_b32_e32 v1, 0xa5a502a0 -v_mov_b32_e32 v2, 0xa5a502a4 -v_mov_b32_e32 v3, 0xa5a502a8 -v_mov_b32_e32 v4, 0xa5a502ac -v_mov_b32_e32 v5, 0x2a0 -buffer_store_dwordx4 v[1:4], v5, s[0:3], 0 offen -v_mov_b32_e32 v1, 0xa5a502b0 -v_mov_b32_e32 v2, 0xa5a502b4 -v_mov_b32_e32 v3, 0xa5a502b8 -v_mov_b32_e32 v4, 0xa5a502bc -v_mov_b32_e32 v5, 0x2b0 -buffer_store_dwordx4 v[1:4], v5, s[0:3], 0 offen -v_mov_b32_e32 v1, 0xa5a502c0 -v_mov_b32_e32 v2, 0xa5a502c4 -v_mov_b32_e32 v3, 0xa5a502c8 -v_mov_b32_e32 v4, 0xa5a502cc -v_mov_b32_e32 v5, 0x2c0 -buffer_store_dwordx4 v[1:4], v5, s[0:3], 0 offen -s_waitcnt_vscnt null, 0x0 -s_mov_b32 s4, s0 -s_mov_b32 s5, s1 -; out[0..3]: buffer_load_format_xy, 32_32_32_32_FLOAT -v_mov_b32_e32 v10, 0x5a5a0000 -v_mov_b32_e32 v11, 0x5a5a0004 -v_mov_b32_e32 v12, 0x5a5a0008 -v_mov_b32_e32 v13, 0x5a5a000c -s_mov_b32 s6, 0xffffffff -s_mov_b32 s7, 0x3104dfac -v_mov_b32_e32 v5, 0x200 -buffer_load_format_xy v[10:11], v5, s[4:7], 0 offen -s_waitcnt vmcnt(0) -v_mov_b32_e32 v6, 0x0 -buffer_store_dwordx4 v[10:13], v6, s[0:3], 0 offen -; out[4..7]: buffer_load_format_xyz, 32_32_32_32_FLOAT -v_mov_b32_e32 v10, 0x5a5a0010 -v_mov_b32_e32 v11, 0x5a5a0014 -v_mov_b32_e32 v12, 0x5a5a0018 -v_mov_b32_e32 v13, 0x5a5a001c -s_mov_b32 s6, 0xffffffff -s_mov_b32 s7, 0x3104dfac -v_mov_b32_e32 v5, 0x200 -buffer_load_format_xyz v[10:12], v5, s[4:7], 0 offen -s_waitcnt vmcnt(0) -v_mov_b32_e32 v6, 0x10 -buffer_store_dwordx4 v[10:13], v6, s[0:3], 0 offen -; out[8..11]: buffer_load_format_xy, 16_16_16_16_FLOAT -v_mov_b32_e32 v10, 0x5a5a0020 -v_mov_b32_e32 v11, 0x5a5a0024 -v_mov_b32_e32 v12, 0x5a5a0028 -v_mov_b32_e32 v13, 0x5a5a002c -s_mov_b32 s6, 0xffffffff -s_mov_b32 s7, 0x31047fac -v_mov_b32_e32 v5, 0x210 -buffer_load_format_xy v[10:11], v5, s[4:7], 0 offen -s_waitcnt vmcnt(0) -v_mov_b32_e32 v6, 0x20 -buffer_store_dwordx4 v[10:13], v6, s[0:3], 0 offen -; out[12..15]: buffer_load_format_xyz, 16_16_16_16_FLOAT -v_mov_b32_e32 v10, 0x5a5a0030 -v_mov_b32_e32 v11, 0x5a5a0034 -v_mov_b32_e32 v12, 0x5a5a0038 -v_mov_b32_e32 v13, 0x5a5a003c -s_mov_b32 s6, 0xffffffff -s_mov_b32 s7, 0x31047fac -v_mov_b32_e32 v5, 0x210 -buffer_load_format_xyz v[10:12], v5, s[4:7], 0 offen -s_waitcnt vmcnt(0) -v_mov_b32_e32 v6, 0x30 -buffer_store_dwordx4 v[10:13], v6, s[0:3], 0 offen -; out[16..19]: buffer_load_format_xyz, 32_32_FLOAT (z repeats x) -v_mov_b32_e32 v10, 0x5a5a0040 -v_mov_b32_e32 v11, 0x5a5a0044 -v_mov_b32_e32 v12, 0x5a5a0048 -v_mov_b32_e32 v13, 0x5a5a004c -s_mov_b32 s6, 0xffffffff -s_mov_b32 s7, 0x31040fac -v_mov_b32_e32 v5, 0x200 -buffer_load_format_xyz v[10:12], v5, s[4:7], 0 offen -s_waitcnt vmcnt(0) -v_mov_b32_e32 v6, 0x40 -buffer_store_dwordx4 v[10:13], v6, s[0:3], 0 offen -; out[20..23]: buffer_load_format_xy, 32_FLOAT (y repeats x) -v_mov_b32_e32 v10, 0x5a5a0050 -v_mov_b32_e32 v11, 0x5a5a0054 -v_mov_b32_e32 v12, 0x5a5a0058 -v_mov_b32_e32 v13, 0x5a5a005c -s_mov_b32 s6, 0xffffffff -s_mov_b32 s7, 0x31016fac -v_mov_b32_e32 v5, 0x200 -buffer_load_format_xy v[10:11], v5, s[4:7], 0 offen -s_waitcnt vmcnt(0) -v_mov_b32_e32 v6, 0x50 -buffer_store_dwordx4 v[10:13], v6, s[0:3], 0 offen -; out[24..27]: tbuffer_load_format_xy, instruction 32_32_32_32_FLOAT over a V# that says 32_FLOAT -v_mov_b32_e32 v10, 0x5a5a0060 -v_mov_b32_e32 v11, 0x5a5a0064 -v_mov_b32_e32 v12, 0x5a5a0068 -v_mov_b32_e32 v13, 0x5a5a006c -s_mov_b32 s6, 0xffffffff -s_mov_b32 s7, 0x31016fac -v_mov_b32_e32 v5, 0x200 -tbuffer_load_format_xy v[10:11], v5, s[4:7], 0 format:[BUF_FMT_32_32_32_32_FLOAT] offen -s_waitcnt vmcnt(0) -v_mov_b32_e32 v6, 0x60 -buffer_store_dwordx4 v[10:13], v6, s[0:3], 0 offen -; out[28..31]: tbuffer_load_format_xyz, instruction 16_16_16_16_FLOAT over a V# that says 32_FLOAT -v_mov_b32_e32 v10, 0x5a5a0070 -v_mov_b32_e32 v11, 0x5a5a0074 -v_mov_b32_e32 v12, 0x5a5a0078 -v_mov_b32_e32 v13, 0x5a5a007c -s_mov_b32 s6, 0xffffffff -s_mov_b32 s7, 0x31016fac -v_mov_b32_e32 v5, 0x210 -tbuffer_load_format_xyz v[10:12], v5, s[4:7], 0 format:[BUF_FMT_16_16_16_16_FLOAT] offen -s_waitcnt vmcnt(0) -v_mov_b32_e32 v6, 0x70 -buffer_store_dwordx4 v[10:13], v6, s[0:3], 0 offen -; out[32..35]: buffer_load_format_xy, 32_32_32_32_FLOAT, NR 0x208: x,y end at 0x208, the element at 0x210 -v_mov_b32_e32 v10, 0x5a5a0080 -v_mov_b32_e32 v11, 0x5a5a0084 -v_mov_b32_e32 v12, 0x5a5a0088 -v_mov_b32_e32 v13, 0x5a5a008c -s_mov_b32 s6, 0x208 -s_mov_b32 s7, 0x3104dfac -v_mov_b32_e32 v5, 0x200 -buffer_load_format_xy v[10:11], v5, s[4:7], 0 offen -s_waitcnt vmcnt(0) -v_mov_b32_e32 v6, 0x80 -buffer_store_dwordx4 v[10:13], v6, s[0:3], 0 offen -; out[36..39]: buffer_load_format_xyz, 32_32_32_32_FLOAT, NR 0x20c: x,y,z end at 0x20c, the element at 0x210 -v_mov_b32_e32 v10, 0x5a5a0090 -v_mov_b32_e32 v11, 0x5a5a0094 -v_mov_b32_e32 v12, 0x5a5a0098 -v_mov_b32_e32 v13, 0x5a5a009c -s_mov_b32 s6, 0x20c -s_mov_b32 s7, 0x3104dfac -v_mov_b32_e32 v5, 0x200 -buffer_load_format_xyz v[10:12], v5, s[4:7], 0 offen -s_waitcnt vmcnt(0) -v_mov_b32_e32 v6, 0x90 -buffer_store_dwordx4 v[10:13], v6, s[0:3], 0 offen -; out[40..43]: buffer_load_format_xy, 32_32_32_32_FLOAT, NR 0x210: the whole element in range -v_mov_b32_e32 v10, 0x5a5a00a0 -v_mov_b32_e32 v11, 0x5a5a00a4 -v_mov_b32_e32 v12, 0x5a5a00a8 -v_mov_b32_e32 v13, 0x5a5a00ac -s_mov_b32 s6, 0x210 -s_mov_b32 s7, 0x3104dfac -v_mov_b32_e32 v5, 0x200 -buffer_load_format_xy v[10:11], v5, s[4:7], 0 offen -s_waitcnt vmcnt(0) -v_mov_b32_e32 v6, 0xa0 -buffer_store_dwordx4 v[10:13], v6, s[0:3], 0 offen -; out[44..47]: tbuffer_load_format_xyz, 16_16_16_16_FLOAT, NR 0x216: x,y,z end at 0x216, the element at 0x218 -v_mov_b32_e32 v10, 0x5a5a00b0 -v_mov_b32_e32 v11, 0x5a5a00b4 -v_mov_b32_e32 v12, 0x5a5a00b8 -v_mov_b32_e32 v13, 0x5a5a00bc -s_mov_b32 s6, 0x216 -s_mov_b32 s7, 0x31016fac -v_mov_b32_e32 v5, 0x210 -tbuffer_load_format_xyz v[10:12], v5, s[4:7], 0 format:[BUF_FMT_16_16_16_16_FLOAT] offen -s_waitcnt vmcnt(0) -v_mov_b32_e32 v6, 0xb0 -buffer_store_dwordx4 v[10:13], v6, s[0:3], 0 offen -; 0x240: buffer_store_format_xy, 32_32_32_32_FLOAT -v_mov_b32_e32 v20, 0x3f800000 -v_mov_b32_e32 v21, 0x40000000 -s_mov_b32 s6, 0xffffffff -s_mov_b32 s7, 0x3104dfac -v_mov_b32_e32 v5, 0x240 -buffer_store_format_xy v[20:21], v5, s[4:7], 0 offen -; 0x250: buffer_store_format_xyz, 32_32_32_32_FLOAT -v_mov_b32_e32 v20, 0x3f800000 -v_mov_b32_e32 v21, 0x40000000 -v_mov_b32_e32 v22, 0x40400000 -s_mov_b32 s6, 0xffffffff -s_mov_b32 s7, 0x3104dfac -v_mov_b32_e32 v5, 0x250 -buffer_store_format_xyz v[20:22], v5, s[4:7], 0 offen -; 0x260: buffer_store_format_xy, 16_16_16_16_FLOAT -v_mov_b32_e32 v20, 0x3f800000 -v_mov_b32_e32 v21, 0x40000000 -s_mov_b32 s6, 0xffffffff -s_mov_b32 s7, 0x31047fac -v_mov_b32_e32 v5, 0x260 -buffer_store_format_xy v[20:21], v5, s[4:7], 0 offen -; 0x270: buffer_store_format_xyz, 16_16_16_16_FLOAT -v_mov_b32_e32 v20, 0x3f800000 -v_mov_b32_e32 v21, 0x40000000 -v_mov_b32_e32 v22, 0x40400000 -s_mov_b32 s6, 0xffffffff -s_mov_b32 s7, 0x31047fac -v_mov_b32_e32 v5, 0x270 -buffer_store_format_xyz v[20:22], v5, s[4:7], 0 offen -; 0x280: buffer_store_format_xy, 32_FLOAT (one channel) -v_mov_b32_e32 v20, 0x3f800000 -v_mov_b32_e32 v21, 0x40000000 -s_mov_b32 s6, 0xffffffff -s_mov_b32 s7, 0x31016fac -v_mov_b32_e32 v5, 0x280 -buffer_store_format_xy v[20:21], v5, s[4:7], 0 offen -; 0x290: buffer_store_format_xy, 8_8_8_8_UNORM, y = 2.0 clamps -v_mov_b32_e32 v20, 0x3f800000 -v_mov_b32_e32 v21, 0x40000000 -s_mov_b32 s6, 0xffffffff -s_mov_b32 s7, 0x31038fac -v_mov_b32_e32 v5, 0x290 -buffer_store_format_xy v[20:21], v5, s[4:7], 0 offen -; 0x2a0: buffer_store_format_xyz, 8_8_8_8_UINT; y = 258 saturates to 255 -v_mov_b32_e32 v20, 0x1 -v_mov_b32_e32 v21, 0x102 -v_mov_b32_e32 v22, 0x3 -s_mov_b32 s6, 0xffffffff -s_mov_b32 s7, 0x3103cfac -v_mov_b32_e32 v5, 0x2a0 -buffer_store_format_xyz v[20:22], v5, s[4:7], 0 offen -; 0x2b0: buffer_store_format_xy, 32_32_32_32_FLOAT, NR 0x2b8: x,y end at 0x2b8, the element at 0x2c0 -v_mov_b32_e32 v20, 0x3f800000 -v_mov_b32_e32 v21, 0x40000000 -s_mov_b32 s6, 0x2b8 -s_mov_b32 s7, 0x3104dfac -v_mov_b32_e32 v5, 0x2b0 -buffer_store_format_xy v[20:21], v5, s[4:7], 0 offen -; 0x2c0: buffer_store_format_xyz, 32_32_32_32_FLOAT, NR 0x2cc: x,y,z end at 0x2cc, the element at 0x2d0 -v_mov_b32_e32 v20, 0x3f800000 -v_mov_b32_e32 v21, 0x40000000 -v_mov_b32_e32 v22, 0x40400000 -s_mov_b32 s6, 0x2cc -s_mov_b32 s7, 0x3104dfac -v_mov_b32_e32 v5, 0x2c0 -buffer_store_format_xyz v[20:22], v5, s[4:7], 0 offen -s_waitcnt_vscnt null, 0x0 -; out[48..51]: the 16 bytes at 0x240 -v_mov_b32_e32 v5, 0x240 -buffer_load_dwordx4 v[10:13], v5, s[0:3], 0 offen -s_waitcnt vmcnt(0) -v_mov_b32_e32 v6, 0xc0 -buffer_store_dwordx4 v[10:13], v6, s[0:3], 0 offen -; out[52..55]: the 16 bytes at 0x250 -v_mov_b32_e32 v5, 0x250 -buffer_load_dwordx4 v[10:13], v5, s[0:3], 0 offen -s_waitcnt vmcnt(0) -v_mov_b32_e32 v6, 0xd0 -buffer_store_dwordx4 v[10:13], v6, s[0:3], 0 offen -; out[56..59]: the 16 bytes at 0x260 -v_mov_b32_e32 v5, 0x260 -buffer_load_dwordx4 v[10:13], v5, s[0:3], 0 offen -s_waitcnt vmcnt(0) -v_mov_b32_e32 v6, 0xe0 -buffer_store_dwordx4 v[10:13], v6, s[0:3], 0 offen -; out[60..63]: the 16 bytes at 0x270 -v_mov_b32_e32 v5, 0x270 -buffer_load_dwordx4 v[10:13], v5, s[0:3], 0 offen -s_waitcnt vmcnt(0) -v_mov_b32_e32 v6, 0xf0 -buffer_store_dwordx4 v[10:13], v6, s[0:3], 0 offen -; out[64..67]: the 16 bytes at 0x280 -v_mov_b32_e32 v5, 0x280 -buffer_load_dwordx4 v[10:13], v5, s[0:3], 0 offen -s_waitcnt vmcnt(0) -v_mov_b32_e32 v6, 0x100 -buffer_store_dwordx4 v[10:13], v6, s[0:3], 0 offen -; out[68..71]: the 16 bytes at 0x290 -v_mov_b32_e32 v5, 0x290 -buffer_load_dwordx4 v[10:13], v5, s[0:3], 0 offen -s_waitcnt vmcnt(0) -v_mov_b32_e32 v6, 0x110 -buffer_store_dwordx4 v[10:13], v6, s[0:3], 0 offen -; out[72..75]: the 16 bytes at 0x2a0 -v_mov_b32_e32 v5, 0x2a0 -buffer_load_dwordx4 v[10:13], v5, s[0:3], 0 offen -s_waitcnt vmcnt(0) -v_mov_b32_e32 v6, 0x120 -buffer_store_dwordx4 v[10:13], v6, s[0:3], 0 offen -; out[76..79]: the 16 bytes at 0x2b0 -v_mov_b32_e32 v5, 0x2b0 -buffer_load_dwordx4 v[10:13], v5, s[0:3], 0 offen -s_waitcnt vmcnt(0) -v_mov_b32_e32 v6, 0x130 -buffer_store_dwordx4 v[10:13], v6, s[0:3], 0 offen -; out[80..83]: the 16 bytes at 0x2c0 -v_mov_b32_e32 v5, 0x2c0 -buffer_load_dwordx4 v[10:13], v5, s[0:3], 0 offen -s_waitcnt vmcnt(0) -v_mov_b32_e32 v6, 0x140 -buffer_store_dwordx4 v[10:13], v6, s[0:3], 0 offen -s_endpgm diff --git a/runtime/test/shaders/cs_global_mem_ext.asm b/runtime/test/shaders/cs_global_mem_ext.asm deleted file mode 100644 index d1ea33136..000000000 --- a/runtime/test/shaders/cs_global_mem_ext.asm +++ /dev/null @@ -1,95 +0,0 @@ -; regen_fixtures: this source has a translator fixture in tests/semantic/fixtures/disasm -; Memory ops merged with CPU-only checks (#1633's global_atomic_*, #1643 buffer_atomic_*_x2, #1666 8/16-bit global -; stores and d16 loads, global_atomic_*_x2), run once on a GPU. As cs_global_neg_offset: 40 groups make a 0x2800-byte -; heap, only group 0 thread 0 runs, global addresses are heap offsets (s[20:21] = P = 0x2000, v30 = 0). -; Seeds (MUBUF stores through the V# in s[0:3], base 0): -; 0x2000 5 0x2004 9 0x2008 0x0000000F 0x200c 0x00F00000 0x2010 0x12345678 0x2014 0x9ABCDEF0 -; 0x2018 0x00000080 0x2020 0x44332211 0x2024 0x88776655 -; Operations and the words stored to out[0..7]: -; out[0] global_atomic_add glc at P+0, DATA 7: the returned old value = 5 -; out[1] the dword at P+0 after it = 12 -; out[2] global_atomic_cmpswap glc at P+4 {DATA 0x77, CMP 9}: (old << 8) | the dword after = 0x977 -; out[3] global_atomic_or_x2 at P+8 with 0xFF000000_000000F0: high dword after = 0xFFF00000 -; out[4] buffer_atomic_xor_x2 glc at 0x2010 with 0x0000FFFF_FFFF0000: low dword after = 0xEDCB5678 -; out[5] global_store_short 0xBEEF at P+0x23 (crosses into the next dword): the dword at 0x2020 = 0xEF332211 -; out[6] the dword at 0x2024 after it = 0x887766BE -; out[7] global_load_sbyte_d16_hi of the byte 0x80 at P+0x18 into 0x00001234 = 0xFF801234 -; Run: vk_compute_test cs_global_mem_ext.spv 40 dump -> out[0..7] = 0x5 0xc 0x977 0xfff00000 0xedcb5678 -; 0xef332211 0x887766be 0xff801234. Same FSSM header as cs_global_neg_offset. -v_or_b32_e32 v1, s4, v0 -v_cmpx_eq_u32_e32 0, v1 -v_mov_b32 v1, 5 -v_mov_b32 v2, 0x2000 -buffer_store_dword v1, v2, s[0:3], 0 offen -v_mov_b32 v1, 9 -v_mov_b32 v2, 0x2004 -buffer_store_dword v1, v2, s[0:3], 0 offen -v_mov_b32 v1, 15 -v_mov_b32 v2, 0x2008 -buffer_store_dword v1, v2, s[0:3], 0 offen -v_mov_b32 v1, 0xf00000 -v_mov_b32 v2, 0x200c -buffer_store_dword v1, v2, s[0:3], 0 offen -v_mov_b32 v1, 0x12345678 -v_mov_b32 v2, 0x2010 -buffer_store_dword v1, v2, s[0:3], 0 offen -v_mov_b32 v1, 0x9abcdef0 -v_mov_b32 v2, 0x2014 -buffer_store_dword v1, v2, s[0:3], 0 offen -v_mov_b32 v1, 0x80 -v_mov_b32 v2, 0x2018 -buffer_store_dword v1, v2, s[0:3], 0 offen -v_mov_b32 v1, 0x44332211 -v_mov_b32 v2, 0x2020 -buffer_store_dword v1, v2, s[0:3], 0 offen -v_mov_b32 v1, 0x88776655 -v_mov_b32 v2, 0x2024 -buffer_store_dword v1, v2, s[0:3], 0 offen -s_waitcnt vmcnt(0) -s_mov_b32 s20, 0x2000 -s_mov_b32 s21, 0 -v_mov_b32 v30, 0 -v_mov_b32 v3, 7 -global_atomic_add v10, v30, v3, s[20:21] glc -s_waitcnt vmcnt(0) -global_load_dword v11, v30, s[20:21] -v_mov_b32 v4, 0x77 -v_mov_b32 v5, 9 -global_atomic_cmpswap v12, v30, v[4:5], s[20:21] offset:4 glc -s_waitcnt vmcnt(0) -global_load_dword v13, v30, s[20:21] offset:4 -v_mov_b32 v6, 0xf0 -v_mov_b32 v7, 0xff000000 -global_atomic_or_x2 v30, v[6:7], s[20:21] offset:8 -v_mov_b32 v8, 0xffff0000 -v_mov_b32 v9, 0xffff -v_mov_b32 v2, 0x2010 -buffer_atomic_xor_x2 v[8:9], v2, s[0:3], 0 offen glc -v_mov_b32 v14, 0xbeef -global_store_short v30, v14, s[20:21] offset:35 -v_mov_b32 v15, 0x1234 -global_load_sbyte_d16_hi v15, v30, s[20:21] offset:24 -s_waitcnt vmcnt(0) -global_load_dword v16, v30, s[20:21] offset:12 -global_load_dword v17, v30, s[20:21] offset:16 -global_load_dword v18, v30, s[20:21] offset:32 -global_load_dword v19, v30, s[20:21] offset:36 -s_waitcnt vmcnt(0) -v_lshl_or_b32 v12, v12, 8, v13 -v_mov_b32 v20, 0 -buffer_store_dword v10, v20, s[0:3], 0 offen -v_mov_b32 v20, 4 -buffer_store_dword v11, v20, s[0:3], 0 offen -v_mov_b32 v20, 8 -buffer_store_dword v12, v20, s[0:3], 0 offen -v_mov_b32 v20, 12 -buffer_store_dword v16, v20, s[0:3], 0 offen -v_mov_b32 v20, 16 -buffer_store_dword v17, v20, s[0:3], 0 offen -v_mov_b32 v20, 20 -buffer_store_dword v18, v20, s[0:3], 0 offen -v_mov_b32 v20, 24 -buffer_store_dword v19, v20, s[0:3], 0 offen -v_mov_b32 v20, 28 -buffer_store_dword v15, v20, s[0:3], 0 offen -s_endpgm diff --git a/runtime/test/shaders/cs_global_neg_offset.asm b/runtime/test/shaders/cs_global_neg_offset.asm deleted file mode 100644 index 7869e13ea..000000000 --- a/runtime/test/shaders/cs_global_neg_offset.asm +++ /dev/null @@ -1,91 +0,0 @@ -; global_load/global_store with a negative instruction offset: address = base + offset, the offset a signed 12-bit -; value as llvm-mc prints it (offset:-4 is the field 0xffc). Measured on an AMD Radeon RX 6800 (gfx1030) as a raw -; compute kernel, dword at byte n = 0x10000000+n, pointer 0x1000: offset:-4 reads 0x10000ffc, -2048 0x10000800, -; 2044 0x100017fc. A translator that subtracts 0x1000 again lands 4096 bytes lower. -; Run with 40 groups so the heap is 40*256 = 0x2800 bytes: both the right addresses and the 4096-lower ones are -; inside it. Only group 0 thread 0 runs (s4 is the workgroup id: 4 user SGPRs, then TGID_X). Pointer P = 0x2000. -; Seeds (MUBUF stores through the V# in s[0:3], base 0), right addresses then the 4096-lower ones: -; 0x1ff0 0x5eed1ff0 0x1ff4 0x5eed1ff4 0x1ffc 0x5eed1ffc 0x1800 0x8bad1800 0x27fc 0x9e5e27fc -; 0x0ff0 0xbad00ff0 0x0ff4 0xbad00ff4 0x0ffc 0xbad00ffc 0x0800 0xbad00800 -; Loads and the store: -; out[0] global_load_dword v10, v30(0), s[20:21](P) offset:-4 byte 0x1ffc -> 0x5eed1ffc -; out[1] global_load_dword v11, v31(0x800), s[22:23](0x1800) offset:-2048 byte 0x1800 -> 0x8bad1800 -; out[2,3] global_load_dwordx2 v[12:13], v[2:3](P), off offset:-16 bytes 0x1ff0, 0x1ff4 -; out[4] global_load_ubyte v14, v[2:3](P), off offset:2047 byte 0x27ff = top byte of 0x9e5e27fc -> 0x9e -; out[5] global_load_sshort v15, v30(0), s[20:21](P) offset:-2046 bytes 0x1802..3 = 0x8bad -> 0xffff8bad -; global_store_dword v[4:5](0x2400), 0x57023ffc, off offset:-4 -> byte 0x23fc; out[6] reads 0x23fc back and -; out[7] reads 0x13fc (4096 lower, never written: the 0xee fill) through MUBUF. -; Run: vk_compute_test cs_global_neg_offset.spv 40 dump -> out[0..7] = 0x5eed1ffc 0x8bad1800 0x5eed1ff0 0x5eed1ff4 -; 0x0000009e 0xffff8bad 0x57023ffc 0xeeeeeeee (1592598524 2343376896 1592598512 1592598516 158 4294937517 1459765244 -; 4008636142). Same FSSM header as cs_lds. -v_or_b32_e32 v1, s4, v0 -v_cmpx_eq_u32_e32 0, v1 -v_mov_b32 v1, 0x5eed1ff0 -v_mov_b32 v2, 0x1ff0 -buffer_store_dword v1, v2, s[0:3], 0 offen -v_mov_b32 v1, 0x5eed1ff4 -v_mov_b32 v2, 0x1ff4 -buffer_store_dword v1, v2, s[0:3], 0 offen -v_mov_b32 v1, 0x5eed1ffc -v_mov_b32 v2, 0x1ffc -buffer_store_dword v1, v2, s[0:3], 0 offen -v_mov_b32 v1, 0x8bad1800 -v_mov_b32 v2, 0x1800 -buffer_store_dword v1, v2, s[0:3], 0 offen -v_mov_b32 v1, 0x9e5e27fc -v_mov_b32 v2, 0x27fc -buffer_store_dword v1, v2, s[0:3], 0 offen -v_mov_b32 v1, 0xbad00ff0 -v_mov_b32 v2, 0xff0 -buffer_store_dword v1, v2, s[0:3], 0 offen -v_mov_b32 v1, 0xbad00ff4 -v_mov_b32 v2, 0xff4 -buffer_store_dword v1, v2, s[0:3], 0 offen -v_mov_b32 v1, 0xbad00ffc -v_mov_b32 v2, 0xffc -buffer_store_dword v1, v2, s[0:3], 0 offen -v_mov_b32 v1, 0xbad00800 -v_mov_b32 v2, 0x800 -buffer_store_dword v1, v2, s[0:3], 0 offen -s_waitcnt_vscnt null, 0x0 -s_mov_b32 s20, 0x2000 -s_mov_b32 s21, 0 -s_mov_b32 s22, 0x1800 -s_mov_b32 s23, 0 -v_mov_b32 v30, 0 -v_mov_b32 v31, 0x800 -v_mov_b32 v2, 0x2000 -v_mov_b32 v3, 0 -v_mov_b32 v4, 0x2400 -v_mov_b32 v5, 0 -global_load_dword v10, v30, s[20:21] offset:-4 -global_load_dword v11, v31, s[22:23] offset:-2048 -global_load_dwordx2 v[12:13], v[2:3], off offset:-16 -global_load_ubyte v14, v[2:3], off offset:2047 -global_load_sshort v15, v30, s[20:21] offset:-2046 -v_mov_b32 v1, 0x57023ffc -global_store_dword v[4:5], v1, off offset:-4 -s_waitcnt vmcnt(0) -s_waitcnt_vscnt null, 0x0 -v_mov_b32 v2, 0x23fc -buffer_load_dword v16, v2, s[0:3], 0 offen -v_mov_b32 v2, 0x13fc -buffer_load_dword v17, v2, s[0:3], 0 offen -s_waitcnt vmcnt(0) -v_mov_b32 v2, 0 -buffer_store_dword v10, v2, s[0:3], 0 offen -v_mov_b32 v2, 4 -buffer_store_dword v11, v2, s[0:3], 0 offen -v_mov_b32 v2, 8 -buffer_store_dword v12, v2, s[0:3], 0 offen -v_mov_b32 v2, 12 -buffer_store_dword v13, v2, s[0:3], 0 offen -v_mov_b32 v2, 16 -buffer_store_dword v14, v2, s[0:3], 0 offen -v_mov_b32 v2, 20 -buffer_store_dword v15, v2, s[0:3], 0 offen -v_mov_b32 v2, 24 -buffer_store_dword v16, v2, s[0:3], 0 offen -v_mov_b32 v2, 28 -buffer_store_dword v17, v2, s[0:3], 0 offen -s_endpgm diff --git a/runtime/test/shaders/cs_heap_init.asm b/runtime/test/shaders/cs_heap_init.asm deleted file mode 100644 index fdd670763..000000000 --- a/runtime/test/shaders/cs_heap_init.asm +++ /dev/null @@ -1,14 +0,0 @@ -; group: 1,1,1 -; rsrc2: 0x8090 -; vk_compute_test's VKC_HEAP_INIT copies a file to the start of the heap before the dispatch. Both runners write a -; 0x110-byte file (zeros, then the words 0x1badb002, 0xcafef00d, 0x80000001, 0x0000ffff at 0x100) and pass -; VKC_OUT_WORDS=68 so it fits. One thread loads the four words through the output V# and stores them at 0, so -; out[0..3] are the seeded words and out[4..7] the file's zeros at 0x10..0x1f (not the 0xEE fill): the whole file was -; copied. Without VKC_HEAP_INIT every word reads 0xEEEEEEEE. -; Run: VKC_OUT_WORDS=68 VKC_HEAP_INIT=init.bin vk_compute_test cs_heap_init.spv 1 dump -; out[0..7] = 1BADB002 CAFEF00D 80000001 0000FFFF 00000000 00000000 00000000 00000000 (hex) -v_mov_b32_e32 v1, 0 -buffer_load_dwordx4 v[2:5], v1, s[0:3], 0 offen offset:256 -s_waitcnt vmcnt(0) -buffer_store_dwordx4 v[2:5], v1, s[0:3], 0 offen -s_endpgm diff --git a/runtime/test/shaders/cs_imgatomic.asm b/runtime/test/shaders/cs_imgatomic.asm deleted file mode 100644 index 147666b28..000000000 --- a/runtime/test/shaders/cs_imgatomic.asm +++ /dev/null @@ -1,135 +0,0 @@ -; Image atomics on a 2D r32 uint image: image_atomic_add, sub, and, or, xor, smin, smax, umin, umax and cmpswap. -; RDNA2 ISA (MIMG): each one reads the texel, writes OP(texel, data) back and, with glc, returns the previous texel in -; the data register; without glc the data register is left alone. cmpswap takes two data registers, the new value -; and the comparand, and writes the new value only where the texel equals the comparand. A lane that EXEC turns off -; does nothing: only thread 0 is on for cases 0 to 15, so an op the other 63 lanes also ran would show (an add -; applied 64 times). Case 16 runs before that, with all 64 threads on, each adding 1 to the same texel. -; Run: vk_store_test cs_imgatomic.spv words -; The tool fills the uint image (T# 0x2000..., what the atomics address) with M = 100 + i at texel i = 8y + x and -; the sint image (T# 0x3000...) with -2i. Case c uses texel c, and stores what its data register holds afterwards -; into texel c of the sint image. A = 0xfffffff0 is -16 signed and 4294967280 unsigned, so it tells the signed -; min and max from the unsigned ones; each of those four also has a case that goes the other way. -; c op data M uint word c afterwards sint word c (data register) -; 0 add A 100 100 + A mod 2^32 = 0x00000054 0x00000064 -; 1 sub 200 101 101 - 200 mod 2^32 = 0xffffff9d 0x00000065 -; 2 and 0x0f0f0f0f 102 0x66 & 0x0f0f0f0f = 0x00000006 0x00000066 -; 3 or 0xf000 103 0x67 | 0xf000 = 0x0000f067 0x00000067 -; 4 xor 0xff 104 0x68 ^ 0xff = 0x00000097 0x00000068 -; 5 smin A 105 -16 < 105: 0xfffffff0 0x00000069 -; 6 smin 200 106 106 < 200: 0x0000006a 0x0000006a -; 7 smax A 107 107 > -16: 0x0000006b 0x0000006b -; 8 smax 200 108 200 > 108: 0x000000c8 0x0000006c -; 9 umin A 109 109 < 4294967280: 0x0000006d 0x0000006d -; 10 umin 5 110 5 < 110: 0x00000005 0x0000006e -; 11 umax A 111 4294967280 > 111: 0xfffffff0 0x0000006f -; 12 umax 5 112 112 > 5: 0x00000070 0x00000070 -; 13 cmpswap 0xc0ffee, 113 113 equal, swapped: 0x00c0ffee 0x00000071 -; 14 cmpswap 0xbad, 115 114 not equal, kept: 0x00000072 0x00000072 -; 15 add 7, no glc 115 115 + 7 = 0x0000007a 0x00000007 (the data, not the old texel) -; 16 add 1, 64 threads 116 116 + 64 = 0x000000b4 (nothing stored: -2 * 16 = 0xffffffe0) -; Every other texel keeps its fill: uint word i = 100 + i for i = 17..63 and sint word i = -2i for i = 16..63. -s_mov_b32 s16, 0x2000 -s_mov_b32 s17, 0x1400000 -s_mov_b32 s18, 0x22 -s_mov_b32 s19, 0x22 -s_mov_b32 s20, 0x22 -s_mov_b32 s21, 0x22 -s_mov_b32 s22, 0x22 -s_mov_b32 s23, 0x22 -s_mov_b32 s24, 0x3000 -s_mov_b32 s25, 0x1500000 -s_mov_b32 s26, 0x33 -s_mov_b32 s27, 0x33 -s_mov_b32 s28, 0x33 -s_mov_b32 s29, 0x33 -s_mov_b32 s30, 0x33 -s_mov_b32 s31, 0x33 -v_mov_b32_e32 v1, 0 -v_mov_b32_e32 v2, 2 -v_mov_b32_e32 v3, 1 -image_atomic_add v3, v[1:2], s[16:23] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm -v_cmpx_eq_u32_e32 0, v0 -v_mov_b32_e32 v2, 0 -v_mov_b32_e32 v1, 0 -v_mov_b32_e32 v3, 0xfffffff0 -image_atomic_add v3, v[1:2], s[16:23] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm glc -s_waitcnt vmcnt(0) -image_store v3, v[1:2], s[24:31] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm -v_mov_b32_e32 v1, 1 -v_mov_b32_e32 v3, 200 -image_atomic_sub v3, v[1:2], s[16:23] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm glc -s_waitcnt vmcnt(0) -image_store v3, v[1:2], s[24:31] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm -v_mov_b32_e32 v1, 2 -v_mov_b32_e32 v3, 0x0f0f0f0f -image_atomic_and v3, v[1:2], s[16:23] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm glc -s_waitcnt vmcnt(0) -image_store v3, v[1:2], s[24:31] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm -v_mov_b32_e32 v1, 3 -v_mov_b32_e32 v3, 0xf000 -image_atomic_or v3, v[1:2], s[16:23] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm glc -s_waitcnt vmcnt(0) -image_store v3, v[1:2], s[24:31] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm -v_mov_b32_e32 v1, 4 -v_mov_b32_e32 v3, 0xff -image_atomic_xor v3, v[1:2], s[16:23] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm glc -s_waitcnt vmcnt(0) -image_store v3, v[1:2], s[24:31] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm -v_mov_b32_e32 v1, 5 -v_mov_b32_e32 v3, 0xfffffff0 -image_atomic_smin v3, v[1:2], s[16:23] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm glc -s_waitcnt vmcnt(0) -image_store v3, v[1:2], s[24:31] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm -v_mov_b32_e32 v1, 6 -v_mov_b32_e32 v3, 200 -image_atomic_smin v3, v[1:2], s[16:23] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm glc -s_waitcnt vmcnt(0) -image_store v3, v[1:2], s[24:31] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm -v_mov_b32_e32 v1, 7 -v_mov_b32_e32 v3, 0xfffffff0 -image_atomic_smax v3, v[1:2], s[16:23] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm glc -s_waitcnt vmcnt(0) -image_store v3, v[1:2], s[24:31] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm -v_mov_b32_e32 v2, 1 -v_mov_b32_e32 v1, 0 -v_mov_b32_e32 v3, 200 -image_atomic_smax v3, v[1:2], s[16:23] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm glc -s_waitcnt vmcnt(0) -image_store v3, v[1:2], s[24:31] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm -v_mov_b32_e32 v1, 1 -v_mov_b32_e32 v3, 0xfffffff0 -image_atomic_umin v3, v[1:2], s[16:23] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm glc -s_waitcnt vmcnt(0) -image_store v3, v[1:2], s[24:31] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm -v_mov_b32_e32 v1, 2 -v_mov_b32_e32 v3, 5 -image_atomic_umin v3, v[1:2], s[16:23] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm glc -s_waitcnt vmcnt(0) -image_store v3, v[1:2], s[24:31] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm -v_mov_b32_e32 v1, 3 -v_mov_b32_e32 v3, 0xfffffff0 -image_atomic_umax v3, v[1:2], s[16:23] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm glc -s_waitcnt vmcnt(0) -image_store v3, v[1:2], s[24:31] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm -v_mov_b32_e32 v1, 4 -v_mov_b32_e32 v3, 5 -image_atomic_umax v3, v[1:2], s[16:23] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm glc -s_waitcnt vmcnt(0) -image_store v3, v[1:2], s[24:31] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm -v_mov_b32_e32 v1, 5 -v_mov_b32_e32 v3, 0xc0ffee -v_mov_b32_e32 v4, 113 -image_atomic_cmpswap v[3:4], v[1:2], s[16:23] dmask:0x3 dim:SQ_RSRC_IMG_2D unorm glc -s_waitcnt vmcnt(0) -image_store v3, v[1:2], s[24:31] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm -v_mov_b32_e32 v1, 6 -v_mov_b32_e32 v3, 0xbad -v_mov_b32_e32 v4, 115 -image_atomic_cmpswap v[3:4], v[1:2], s[16:23] dmask:0x3 dim:SQ_RSRC_IMG_2D unorm glc -s_waitcnt vmcnt(0) -image_store v3, v[1:2], s[24:31] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm -v_mov_b32_e32 v1, 7 -v_mov_b32_e32 v3, 7 -image_atomic_add v3, v[1:2], s[16:23] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm -image_store v3, v[1:2], s[24:31] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm -s_endpgm diff --git a/runtime/test/shaders/cs_imgatomic3d.asm b/runtime/test/shaders/cs_imgatomic3d.asm deleted file mode 100644 index 29f4477a4..000000000 --- a/runtime/test/shaders/cs_imgatomic3d.asm +++ /dev/null @@ -1,83 +0,0 @@ -; Image atomics on a 3D r32 uint image (dim:SQ_RSRC_IMG_3D, three coordinates): the same RDNA2 ISA rules as in -; cs_imgatomic.asm, which runs every op on a 2D image; these six cases cover the 3D addressing with an arithmetic op, -; an unsigned and a signed compare, cmpswap both ways and an op without glc. -; Run: vk_store_test cs_imgatomic3d.spv words -; The tool fills a 4x4x4 volume (T# 0x5000...) with V = 200 + i at texel i = 16z + 4y + x. The three coordinates of -; a case all differ, so a swapped pair lands on another texel. Case c stores what its data register holds -; afterwards into texel c of the sint image (T# 0x3000...). A = 0xfffffff0 is -16 signed. -; c op data (x, y, z) i V volume word i afterwards sint word c -; 0 add 0x10 (1, 2, 3) 57 257 257 + 16 = 0x00000111 0x00000101 -; 1 umin 3 (3, 0, 1) 19 219 3 < 219: 0x00000003 0x000000db -; 2 smax A (0, 3, 2) 44 244 244 > -16: 0x000000f4 0x000000f4 -; 3 cmpswap 0xd00d, 206 (2, 1, 0) 6 206 equal, swapped: 0x0000d00d 0x000000ce -; 4 cmpswap 0xbad, 0 (2, 3, 1) 30 230 not equal, kept: 0x000000e6 0x000000e6 -; 5 xor 0xff, no glc (3, 1, 2) 39 239 0xef ^ 0xff = 0x00000010 0x000000ff (the data) -; Every other word keeps its fill: volume word i = 200 + i, sint word i = -2i for i = 6..63, uint word i = 100 + i. -v_cmpx_eq_u32_e32 0, v0 -s_mov_b32 s16, 0x5000 -s_mov_b32 s17, 0x1400000 -s_mov_b32 s18, 0x55 -s_mov_b32 s19, 0x55 -s_mov_b32 s20, 0x55 -s_mov_b32 s21, 0x55 -s_mov_b32 s22, 0x55 -s_mov_b32 s23, 0x55 -s_mov_b32 s24, 0x3000 -s_mov_b32 s25, 0x1500000 -s_mov_b32 s26, 0x33 -s_mov_b32 s27, 0x33 -s_mov_b32 s28, 0x33 -s_mov_b32 s29, 0x33 -s_mov_b32 s30, 0x33 -s_mov_b32 s31, 0x33 -v_mov_b32_e32 v6, 0 -v_mov_b32_e32 v1, 1 -v_mov_b32_e32 v2, 2 -v_mov_b32_e32 v3, 3 -v_mov_b32_e32 v4, 0x10 -image_atomic_add v4, v[1:3], s[16:23] dmask:0x1 dim:SQ_RSRC_IMG_3D unorm glc -s_waitcnt vmcnt(0) -v_mov_b32_e32 v5, 0 -image_store v4, v[5:6], s[24:31] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm -v_mov_b32_e32 v1, 3 -v_mov_b32_e32 v2, 0 -v_mov_b32_e32 v3, 1 -v_mov_b32_e32 v4, 3 -image_atomic_umin v4, v[1:3], s[16:23] dmask:0x1 dim:SQ_RSRC_IMG_3D unorm glc -s_waitcnt vmcnt(0) -v_mov_b32_e32 v5, 1 -image_store v4, v[5:6], s[24:31] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm -v_mov_b32_e32 v1, 0 -v_mov_b32_e32 v2, 3 -v_mov_b32_e32 v3, 2 -v_mov_b32_e32 v4, 0xfffffff0 -image_atomic_smax v4, v[1:3], s[16:23] dmask:0x1 dim:SQ_RSRC_IMG_3D unorm glc -s_waitcnt vmcnt(0) -v_mov_b32_e32 v5, 2 -image_store v4, v[5:6], s[24:31] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm -v_mov_b32_e32 v1, 2 -v_mov_b32_e32 v2, 1 -v_mov_b32_e32 v3, 0 -v_mov_b32_e32 v7, 0xd00d -v_mov_b32_e32 v8, 206 -image_atomic_cmpswap v[7:8], v[1:3], s[16:23] dmask:0x3 dim:SQ_RSRC_IMG_3D unorm glc -s_waitcnt vmcnt(0) -v_mov_b32_e32 v5, 3 -image_store v7, v[5:6], s[24:31] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm -v_mov_b32_e32 v1, 2 -v_mov_b32_e32 v2, 3 -v_mov_b32_e32 v3, 1 -v_mov_b32_e32 v7, 0xbad -v_mov_b32_e32 v8, 0 -image_atomic_cmpswap v[7:8], v[1:3], s[16:23] dmask:0x3 dim:SQ_RSRC_IMG_3D unorm glc -s_waitcnt vmcnt(0) -v_mov_b32_e32 v5, 4 -image_store v7, v[5:6], s[24:31] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm -v_mov_b32_e32 v1, 3 -v_mov_b32_e32 v2, 1 -v_mov_b32_e32 v3, 2 -v_mov_b32_e32 v4, 0xff -image_atomic_xor v4, v[1:3], s[16:23] dmask:0x1 dim:SQ_RSRC_IMG_3D unorm -v_mov_b32_e32 v5, 5 -image_store v4, v[5:6], s[24:31] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm -s_endpgm diff --git a/runtime/test/shaders/cs_imgload.asm b/runtime/test/shaders/cs_imgload.asm deleted file mode 100644 index d8c1fca0b..000000000 --- a/runtime/test/shaders/cs_imgload.asm +++ /dev/null @@ -1,47 +0,0 @@ -; Typed image_load (SHADER-151): vk_store_test fills the r32 uint image with 100 + 8y + x and the r32 sint image with -; -2 (8y + x) before the dispatch. Each thread loads both of its texels with image_load, which the translator fetches -; through the uint and sint aliases of the sampled array (no storage image read, so no read-without-format), and -; stores their sum into the sint image; the rgba8 image is stored as in cs_imgstore. Nothing is read back after a -; write in the same dispatch. Run: vk_store_test cs_imgload.spv load -> sint = 100 - (8y + x), uint unchanged. -v_and_b32_e32 v1, 7, v0 -v_lshrrev_b32_e32 v2, 3, v0 -v_cvt_f32_u32_e32 v3, v1 -v_cvt_f32_u32_e32 v4, v2 -v_mul_f32_e32 v3, 0x3e124925, v3 -v_mul_f32_e32 v4, 0x3e124925, v4 -v_mov_b32_e32 v5, 0.5 -v_mov_b32_e32 v6, 1.0 -s_mov_b32 s8, 0x1000 -s_mov_b32 s9, 0x3800000 -s_mov_b32 s10, 0x11 -s_mov_b32 s11, 0x11 -s_mov_b32 s12, 0x11 -s_mov_b32 s13, 0x11 -s_mov_b32 s14, 0x11 -s_mov_b32 s15, 0x11 -image_store v[3:6], v[1:2], s[8:15] dmask:0xf dim:SQ_RSRC_IMG_2D unorm -s_mov_b32 s16, 0x2000 -s_mov_b32 s17, 0x1400000 -s_mov_b32 s18, 0x22 -s_mov_b32 s19, 0x22 -s_mov_b32 s20, 0x22 -s_mov_b32 s21, 0x22 -s_mov_b32 s22, 0x22 -s_mov_b32 s23, 0x22 -image_load v7, v[1:2], s[16:23] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm -s_mov_b32 s24, 0x3000 -s_mov_b32 s25, 0x1500000 -s_mov_b32 s26, 0x33 -s_mov_b32 s27, 0x33 -s_mov_b32 s28, 0x33 -s_mov_b32 s29, 0x33 -s_mov_b32 s30, 0x33 -s_mov_b32 s31, 0x33 -image_load v11, v[1:2], s[24:31] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm -s_waitcnt vmcnt(0) -v_add_nc_u32_e32 v11, v7, v11 -v_mov_b32_e32 v12, 0 -v_mov_b32_e32 v13, 0 -v_mov_b32_e32 v14, 0 -image_store v[11:14], v[1:2], s[24:31] dmask:0xf dim:SQ_RSRC_IMG_2D unorm -s_endpgm diff --git a/runtime/test/shaders/cs_imgload_d16.asm b/runtime/test/shaders/cs_imgload_d16.asm deleted file mode 100644 index 1ab44a2b7..000000000 --- a/runtime/test/shaders/cs_imgload_d16.asm +++ /dev/null @@ -1,46 +0,0 @@ -; Read R32 UINT/SINT through D16, unpack their low halves and store the signed sum. In vk_store_test load-d16 -; the final row covers integer saturation at both signed limits and the unsigned upper limit. -v_and_b32_e32 v1, 7, v0 -v_lshrrev_b32_e32 v2, 3, v0 -v_cvt_f32_u32_e32 v3, v1 -v_cvt_f32_u32_e32 v4, v2 -v_mul_f32_e32 v3, 0x3e124925, v3 -v_mul_f32_e32 v4, 0x3e124925, v4 -v_mov_b32_e32 v5, 0.5 -v_mov_b32_e32 v6, 1.0 -s_mov_b32 s8, 0x1000 -s_mov_b32 s9, 0x3800000 -s_mov_b32 s10, 0x11 -s_mov_b32 s11, 0x11 -s_mov_b32 s12, 0x11 -s_mov_b32 s13, 0x11 -s_mov_b32 s14, 0x11 -s_mov_b32 s15, 0x11 -image_store v[3:6], v[1:2], s[8:15] dmask:0xf dim:SQ_RSRC_IMG_2D unorm -s_mov_b32 s16, 0x2000 -s_mov_b32 s17, 0x1400000 -s_mov_b32 s18, 0x22 -s_mov_b32 s19, 0x22 -s_mov_b32 s20, 0x22 -s_mov_b32 s21, 0x22 -s_mov_b32 s22, 0x22 -s_mov_b32 s23, 0x22 -image_load v7, v[1:2], s[16:23] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm d16 -s_mov_b32 s24, 0x3000 -s_mov_b32 s25, 0x1500000 -s_mov_b32 s26, 0x33 -s_mov_b32 s27, 0x33 -s_mov_b32 s28, 0x33 -s_mov_b32 s29, 0x33 -s_mov_b32 s30, 0x33 -s_mov_b32 s31, 0x33 -image_load v11, v[1:2], s[24:31] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm d16 -s_waitcnt vmcnt(0) -v_and_b32_e32 v7, 0xffff, v7 -v_bfe_i32 v11, v11, 0, 16 -v_add_nc_u32_e32 v11, v7, v11 -v_mov_b32_e32 v12, 0 -v_mov_b32_e32 v13, 0 -v_mov_b32_e32 v14, 0 -image_store v[11:14], v[1:2], s[24:31] dmask:0xf dim:SQ_RSRC_IMG_2D unorm -s_endpgm diff --git a/runtime/test/shaders/cs_imgload_d16_tfe.asm b/runtime/test/shaders/cs_imgload_d16_tfe.asm deleted file mode 100644 index 0739810d1..000000000 --- a/runtime/test/shaders/cs_imgload_d16_tfe.asm +++ /dev/null @@ -1,53 +0,0 @@ -; tfe status VGPR on a d16 image_load (SHADER-1266): cs_imgload_d16 with tfe on both loads. Under d16 one -; component fills one VGPR, and with tfe the fetch status follows it, so vdata is v[7:8] and v[11:12]. Every texel is -; resident, so the status is 0. Each status VGPR is seeded with 1000 and added into the result, so a stale status -; moves every texel by 2000. The unpacking and the result are cs_imgload_d16's, checked by vk_store_test load-d16 -; (including its saturation row). Suggested by @nnonno91, who ran the same companion on gfx1036 and an RTX 5090 in #8968. -v_and_b32_e32 v1, 7, v0 -v_lshrrev_b32_e32 v2, 3, v0 -v_cvt_f32_u32_e32 v3, v1 -v_cvt_f32_u32_e32 v4, v2 -v_mul_f32_e32 v3, 0x3e124925, v3 -v_mul_f32_e32 v4, 0x3e124925, v4 -v_mov_b32_e32 v5, 0.5 -v_mov_b32_e32 v6, 1.0 -s_mov_b32 s8, 0x1000 -s_mov_b32 s9, 0x3800000 -s_mov_b32 s10, 0x11 -s_mov_b32 s11, 0x11 -s_mov_b32 s12, 0x11 -s_mov_b32 s13, 0x11 -s_mov_b32 s14, 0x11 -s_mov_b32 s15, 0x11 -image_store v[3:6], v[1:2], s[8:15] dmask:0xf dim:SQ_RSRC_IMG_2D unorm -s_mov_b32 s16, 0x2000 -s_mov_b32 s17, 0x1400000 -s_mov_b32 s18, 0x22 -s_mov_b32 s19, 0x22 -s_mov_b32 s20, 0x22 -s_mov_b32 s21, 0x22 -s_mov_b32 s22, 0x22 -s_mov_b32 s23, 0x22 -v_mov_b32_e32 v8, 0x3e8 -image_load v[7:8], v[1:2], s[16:23] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm tfe d16 -s_mov_b32 s24, 0x3000 -s_mov_b32 s25, 0x1500000 -s_mov_b32 s26, 0x33 -s_mov_b32 s27, 0x33 -s_mov_b32 s28, 0x33 -s_mov_b32 s29, 0x33 -s_mov_b32 s30, 0x33 -s_mov_b32 s31, 0x33 -v_mov_b32_e32 v12, 0x3e8 -image_load v[11:12], v[1:2], s[24:31] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm tfe d16 -s_waitcnt vmcnt(0) -v_and_b32_e32 v7, 0xffff, v7 -v_bfe_i32 v11, v11, 0, 16 -v_add_nc_u32_e32 v11, v7, v11 -v_add_nc_u32_e32 v11, v8, v11 -v_add_nc_u32_e32 v11, v12, v11 -v_mov_b32_e32 v12, 0 -v_mov_b32_e32 v13, 0 -v_mov_b32_e32 v14, 0 -image_store v[11:14], v[1:2], s[24:31] dmask:0xf dim:SQ_RSRC_IMG_2D unorm -s_endpgm diff --git a/runtime/test/shaders/cs_imgload_tfe.asm b/runtime/test/shaders/cs_imgload_tfe.asm deleted file mode 100644 index 63ad9dc71..000000000 --- a/runtime/test/shaders/cs_imgload_tfe.asm +++ /dev/null @@ -1,52 +0,0 @@ -; tfe status VGPR on image_load (SHADER-1266): cs_imgload with tfe on both loads. With tfe an MIMG read returns one -; more dword after its data, the fetch status, at vdata[data_count] (RDNA2 ISA, MIMG TFE/LWE). Every texel here is -; resident, so the status is 0. Each status VGPR is seeded with 1000 before its load and added into the result, so a -; status that keeps its old value moves every texel by 1000 or 2000. vk_store_test fills the r32 uint image with -; 100 + 8y + x and the r32 sint image with -2 (8y + x) before the dispatch; the rgba8 image is stored as in -; cs_imgstore. Run: vk_store_test cs_imgload_tfe.spv load -> sint = 100 - (8y + x), uint unchanged. -v_and_b32_e32 v1, 7, v0 -v_lshrrev_b32_e32 v2, 3, v0 -v_cvt_f32_u32_e32 v3, v1 -v_cvt_f32_u32_e32 v4, v2 -v_mul_f32_e32 v3, 0x3e124925, v3 -v_mul_f32_e32 v4, 0x3e124925, v4 -v_mov_b32_e32 v5, 0.5 -v_mov_b32_e32 v6, 1.0 -s_mov_b32 s8, 0x1000 -s_mov_b32 s9, 0x3800000 -s_mov_b32 s10, 0x11 -s_mov_b32 s11, 0x11 -s_mov_b32 s12, 0x11 -s_mov_b32 s13, 0x11 -s_mov_b32 s14, 0x11 -s_mov_b32 s15, 0x11 -image_store v[3:6], v[1:2], s[8:15] dmask:0xf dim:SQ_RSRC_IMG_2D unorm -s_mov_b32 s16, 0x2000 -s_mov_b32 s17, 0x1400000 -s_mov_b32 s18, 0x22 -s_mov_b32 s19, 0x22 -s_mov_b32 s20, 0x22 -s_mov_b32 s21, 0x22 -s_mov_b32 s22, 0x22 -s_mov_b32 s23, 0x22 -v_mov_b32_e32 v8, 0x3e8 -image_load v[7:8], v[1:2], s[16:23] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm tfe -s_mov_b32 s24, 0x3000 -s_mov_b32 s25, 0x1500000 -s_mov_b32 s26, 0x33 -s_mov_b32 s27, 0x33 -s_mov_b32 s28, 0x33 -s_mov_b32 s29, 0x33 -s_mov_b32 s30, 0x33 -s_mov_b32 s31, 0x33 -v_mov_b32_e32 v12, 0x3e8 -image_load v[11:12], v[1:2], s[24:31] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm tfe -s_waitcnt vmcnt(0) -v_add_nc_u32_e32 v11, v7, v11 -v_add_nc_u32_e32 v11, v8, v11 -v_add_nc_u32_e32 v11, v12, v11 -v_mov_b32_e32 v12, 0 -v_mov_b32_e32 v13, 0 -v_mov_b32_e32 v14, 0 -image_store v[11:14], v[1:2], s[24:31] dmask:0xf dim:SQ_RSRC_IMG_2D unorm -s_endpgm diff --git a/runtime/test/shaders/cs_imgstore.asm b/runtime/test/shaders/cs_imgstore.asm deleted file mode 100644 index d0d30a89a..000000000 --- a/runtime/test/shaders/cs_imgstore.asm +++ /dev/null @@ -1,47 +0,0 @@ -; Typed image_store: three T#s built in SGPRs (FORMAT 56 rgba8 unorm, 20 r32 uint, 21 r32 sint), 64 threads store to -; (t & 7, t >> 3). Run: vk_store_test cs_imgstore.spv (checks every texel of all three images). Same FSSM header as cs_lds. -v_and_b32_e32 v1, 7, v0 -v_lshrrev_b32_e32 v2, 3, v0 -v_cvt_f32_u32_e32 v3, v1 -v_cvt_f32_u32_e32 v4, v2 -v_mul_f32_e32 v3, 0x3e124925, v3 -v_mul_f32_e32 v4, 0x3e124925, v4 -v_mov_b32_e32 v5, 0.5 -v_mov_b32_e32 v6, 1.0 -s_mov_b32 s8, 0x1000 -s_mov_b32 s9, 0x3800000 -s_mov_b32 s10, 0x11 -s_mov_b32 s11, 0x11 -s_mov_b32 s12, 0x11 -s_mov_b32 s13, 0x11 -s_mov_b32 s14, 0x11 -s_mov_b32 s15, 0x11 -image_store v[3:6], v[1:2], s[8:15] dmask:0xf dim:SQ_RSRC_IMG_2D unorm -v_lshl_add_u32 v7, v2, 3, v1 -v_add_nc_u32_e32 v7, 100, v7 -v_mov_b32_e32 v8, 0 -v_mov_b32_e32 v9, 0 -v_mov_b32_e32 v10, 0 -s_mov_b32 s16, 0x2000 -s_mov_b32 s17, 0x1400000 -s_mov_b32 s18, 0x22 -s_mov_b32 s19, 0x22 -s_mov_b32 s20, 0x22 -s_mov_b32 s21, 0x22 -s_mov_b32 s22, 0x22 -s_mov_b32 s23, 0x22 -image_store v[7:10], v[1:2], s[16:23] dmask:0xf dim:SQ_RSRC_IMG_2D unorm -v_sub_nc_u32_e32 v11, 0, v0 -v_mov_b32_e32 v12, 0 -v_mov_b32_e32 v13, 0 -v_mov_b32_e32 v14, 0 -s_mov_b32 s24, 0x3000 -s_mov_b32 s25, 0x1500000 -s_mov_b32 s26, 0x33 -s_mov_b32 s27, 0x33 -s_mov_b32 s28, 0x33 -s_mov_b32 s29, 0x33 -s_mov_b32 s30, 0x33 -s_mov_b32 s31, 0x33 -image_store v[11:14], v[1:2], s[24:31] dmask:0xf dim:SQ_RSRC_IMG_2D unorm -s_endpgm diff --git a/runtime/test/shaders/cs_lds.asm b/runtime/test/shaders/cs_lds.asm deleted file mode 100644 index 800d7937e..000000000 --- a/runtime/test/shaders/cs_lds.asm +++ /dev/null @@ -1,14 +0,0 @@ -; Compute: workgroup id in s4 (RSRC2 0x8088: 4 user SGPRs, TGID_X, 512 B LDS; group 64x1x1), thread id in v0, -; LDS exchange across the two waves of a group behind s_barrier, buffer store through V# s[0:3] (base 0 = heap). -; Run: vk_compute_test cs_lds.spv 4 mirror64 (out[g*64+t] == g*64 + 63 - t) -v_lshl_add_u32 v1, s4, 6, v0 -v_lshlrev_b32_e32 v2, 2, v0 -ds_write_b32 v2, v1 -s_waitcnt lgkmcnt(0) -s_barrier -v_sub_nc_u32_e32 v3, 0xfc, v2 -ds_read_b32 v4, v3 -s_waitcnt lgkmcnt(0) -v_lshlrev_b32_e32 v5, 2, v1 -buffer_store_dword v4, v5, s[0:3], 0 offen -s_endpgm diff --git a/runtime/test/shaders/cs_lds_atomics_ext.asm b/runtime/test/shaders/cs_lds_atomics_ext.asm deleted file mode 100644 index 4d599930e..000000000 --- a/runtime/test/shaders/cs_lds_atomics_ext.asm +++ /dev/null @@ -1,138 +0,0 @@ -; GPU test for four LDS atomic families that docs/design.md lists as not GPU-verified (their translations were -; CPU-checked and the instructions measured with tools/hw_oracle, but the translated SPIR-V never ran on a GPU): -; ds_mskor_b32 / ds_mskor_rtn_b32, ds_and_b64 / ds_xor_rtn_b64, ds_add_rtn_f32, ds_inc_rtn_u32 / ds_dec_u32 / -; ds_rsub_u32. -; -; LDS 4 KiB (RSRC2 0x40088), group 32x1x1, only lane 0 runs. The output words follow the design.md rows (which -; quote the RDNA2 ISA pseudocode): -; -; out[0] ds_mskor_b32 at 0x10: M 0xF0F0F0F0, DATA 0x0000FFFF, DATA2 0x00011234 (bit 16 lies outside DATA and is -; ORed in, it is not a masked insert): (M & ~DATA) | DATA2 = 0xF0F11234 -; out[1] ds_mskor_rtn_b32 at 0x14: M 0x12345678, DATA 0xFF00FF00, DATA2 0xAB00CD00: the word left, 0xAB34CD78 -; out[2] the same op's returned pre-op word, 0x12345678 -; out[3] ds_xor_rtn_b64 at 0x20: M 0xAAAA5555_0F0F0F0F, DATA 0x0000FFFF_FFFF0000: low dword left, 0xF0F00F0F -; out[4] the same op's returned pair, low XOR high: 0x0F0F0F0F ^ 0xAAAA5555 = 0xA5A55A5A -; out[5] ds_and_b64 on that element with DATA 0x00FF00FF_FFFFFFFF: high dword left, 0xAAAAAAAA & 0x00FF00FF -; = 0x00AA00AA (its low dword is unchanged) -; out[6] ds_add_rtn_f32 at 0x30: M 1.5 (0x3FC00000), DATA 2.25 (0x40100000): the word left (3.75, 0x40700000) -; XOR the returned 1.5: 0x7FB00000 -; out[7] packed bytes: [7:0] ds_inc_rtn_u32 at 0x34 with M 7, DATA 7 (M >= DATA, so 0); [15:8] its returned 7; -; [23:16] ds_dec_u32 at 0x38 with M 0, DATA 9 (M == 0, so DATA); [31:24] the low byte of ds_rsub_u32 at -; 0x3C with M 5, DATA 3 (DATA - M wraps to 0xFFFFFFFE): 0xFE090700 -; -; Run: vk_compute_test cs_lds_atomics_ext.spv 1 dump -; -> out[0..7] = 0xF0F11234 0xAB34CD78 0x12345678 0xF0F00F0F -; 0xA5A55A5A 0x00AA00AA 0x7FB00000 0xFE090700 -; rsrc2: 0x40088 -; group: 32,1,1 -; mattr: +wavefrontsize32,-wavefrontsize64 -v_cmpx_eq_u32_e32 0, v0 - -; --- ds_mskor_b32: non-returning, DATA2 bit outside DATA --- -v_mov_b32_e32 v1, 0x10 -v_mov_b32_e32 v3, 0xF0F0F0F0 -ds_write_b32 v1, v3 -s_waitcnt lgkmcnt(0) -v_mov_b32_e32 v3, 0x0000FFFF -v_mov_b32_e32 v4, 0x00011234 -ds_mskor_b32 v1, v3, v4 -s_waitcnt lgkmcnt(0) -ds_read_b32 v10, v1 -s_waitcnt lgkmcnt(0) -v_mov_b32_e32 v21, 0 -buffer_store_dword v10, v21, s[0:3], 0 offen - -; --- ds_mskor_rtn_b32: memory and returned word --- -v_mov_b32_e32 v1, 0x14 -v_mov_b32_e32 v3, 0x12345678 -ds_write_b32 v1, v3 -s_waitcnt lgkmcnt(0) -v_mov_b32_e32 v3, 0xFF00FF00 -v_mov_b32_e32 v4, 0xAB00CD00 -ds_mskor_rtn_b32 v11, v1, v3, v4 -s_waitcnt lgkmcnt(0) -ds_read_b32 v10, v1 -s_waitcnt lgkmcnt(0) -v_mov_b32_e32 v21, 4 -buffer_store_dword v10, v21, s[0:3], 0 offen -v_mov_b32_e32 v21, 8 -buffer_store_dword v11, v21, s[0:3], 0 offen - -; --- ds_xor_rtn_b64, then ds_and_b64 on the same element --- -v_mov_b32_e32 v1, 0x20 -v_mov_b32_e32 v4, 0x0F0F0F0F -v_mov_b32_e32 v5, 0xAAAA5555 -ds_write_b64 v1, v[4:5] -s_waitcnt lgkmcnt(0) -v_mov_b32_e32 v6, 0xFFFF0000 -v_mov_b32_e32 v7, 0x0000FFFF -ds_xor_rtn_b64 v[12:13], v1, v[6:7] -s_waitcnt lgkmcnt(0) -ds_read_b32 v10, v1 -s_waitcnt lgkmcnt(0) -v_mov_b32_e32 v21, 12 -buffer_store_dword v10, v21, s[0:3], 0 offen -v_xor_b32_e32 v14, v12, v13 -v_mov_b32_e32 v21, 16 -buffer_store_dword v14, v21, s[0:3], 0 offen -v_mov_b32_e32 v6, 0xFFFFFFFF -v_mov_b32_e32 v7, 0x00FF00FF -ds_and_b64 v1, v[6:7] -s_waitcnt lgkmcnt(0) -ds_read_b32 v10, v1 offset:4 -s_waitcnt lgkmcnt(0) -v_mov_b32_e32 v21, 20 -buffer_store_dword v10, v21, s[0:3], 0 offen - -; --- ds_add_rtn_f32: 1.5 + 2.25 --- -v_mov_b32_e32 v1, 0x30 -v_mov_b32_e32 v3, 0x3FC00000 -ds_write_b32 v1, v3 -s_waitcnt lgkmcnt(0) -v_mov_b32_e32 v3, 0x40100000 -ds_add_rtn_f32 v11, v1, v3 -s_waitcnt lgkmcnt(0) -ds_read_b32 v10, v1 -s_waitcnt lgkmcnt(0) -v_xor_b32_e32 v14, v10, v11 -v_mov_b32_e32 v21, 24 -buffer_store_dword v14, v21, s[0:3], 0 offen - -; --- ds_inc_rtn_u32 (M 7, DATA 7), ds_dec_u32 (M 0, DATA 9), ds_rsub_u32 (M 5, DATA 3) --- -v_mov_b32_e32 v1, 0x34 -v_mov_b32_e32 v3, 7 -ds_write_b32 v1, v3 -v_mov_b32_e32 v1, 0x38 -v_mov_b32_e32 v3, 0 -ds_write_b32 v1, v3 -v_mov_b32_e32 v1, 0x3C -v_mov_b32_e32 v3, 5 -ds_write_b32 v1, v3 -s_waitcnt lgkmcnt(0) -v_mov_b32_e32 v1, 0x34 -v_mov_b32_e32 v3, 7 -ds_inc_rtn_u32 v11, v1, v3 -v_mov_b32_e32 v1, 0x38 -v_mov_b32_e32 v3, 9 -ds_dec_u32 v1, v3 -v_mov_b32_e32 v1, 0x3C -v_mov_b32_e32 v3, 3 -ds_rsub_u32 v1, v3 -s_waitcnt lgkmcnt(0) -v_mov_b32_e32 v1, 0x34 -ds_read_b32 v10, v1 -v_mov_b32_e32 v1, 0x38 -ds_read_b32 v12, v1 -v_mov_b32_e32 v1, 0x3C -ds_read_b32 v13, v1 -s_waitcnt lgkmcnt(0) -v_and_b32_e32 v10, 0xFF, v10 -v_lshlrev_b32_e32 v11, 8, v11 -v_or_b32_e32 v10, v10, v11 -v_lshlrev_b32_e32 v12, 16, v12 -v_or_b32_e32 v10, v10, v12 -v_lshlrev_b32_e32 v13, 24, v13 -v_or_b32_e32 v10, v10, v13 -v_mov_b32_e32 v21, 28 -buffer_store_dword v10, v21, s[0:3], 0 offen -s_endpgm diff --git a/runtime/test/shaders/cs_lds_b64_cmpst.asm b/runtime/test/shaders/cs_lds_b64_cmpst.asm deleted file mode 100644 index 0998d8576..000000000 --- a/runtime/test/shaders/cs_lds_b64_cmpst.asm +++ /dev/null @@ -1,132 +0,0 @@ -; GPU test for the two LDS families that docs/design.md lists as not GPU-verified: -; ds_cmpst_b32 (the non-returning compare-and-store) and the b64 2-address forms -; (ds_read2_b64 / ds_write2_b64 and their st64 variants). -; -; LDS 4 KiB (RSRC2 0x40088), group 32x1x1, only lane 0 runs. The output words are -; derived from the RDNA2 ISA's 2-address and DS_CMPST_B32 pseudocode: -; -; out[0..3] ds_write2_b64 then ds_read2_b64 at base 0x20, offset0:1 offset1:3, -; writes A at 0x28 and B at 0x38 (unit 8), reads the same two elements: -; A.lo A.hi B.lo B.hi -; out[4] ds_read2st64_b64 at base 0x100, offset0:0 offset1:1 (unit 512): -; XOR of the four dwords seeded at 0x100 and 0x300 -; out[5] ds_write2st64_b64 at base 0x100, offset0:0 offset1:1, then plain -; ds_read_b32 at 0x100/0x104/0x300/0x304: XOR of the four dwords -; out[6] ds_read2_b64 v[2:5], v2 at base 0x200 (vdst overlaps vaddr): the -; second element's low dword, 0xBBBB000B, read before v2 is overwritten -; out[7] ds_cmpst_b32 hit (mem 0x13572468 -> 0x2468ABCD) XOR the miss case's -; unchanged word (0x11111111): 0x3579BADC -; -; Run: vk_compute_test cs_lds_b64_cmpst.spv 1 dump -; -> out[0..7] = 0x11110001 0x22220002 0x33330003 0x44440004 -; 0xCCCC000C 0x44440004 0xBBBB000B 0x3579BADC -; rsrc2: 0x40088 -; group: 32,1,1 -; mattr: +wavefrontsize32,-wavefrontsize64 -v_cmpx_eq_u32_e32 0, v0 - -; --- ds_write2_b64 / ds_read2_b64, unit 8 bytes --- -v_mov_b32_e32 v2, 0x20 -v_mov_b32_e32 v4, 0x11110001 -v_mov_b32_e32 v5, 0x22220002 -v_mov_b32_e32 v6, 0x33330003 -v_mov_b32_e32 v7, 0x44440004 -ds_write2_b64 v2, v[4:5], v[6:7] offset0:1 offset1:3 -s_waitcnt lgkmcnt(0) -ds_read2_b64 v[10:13], v2 offset0:1 offset1:3 -s_waitcnt lgkmcnt(0) -v_mov_b32_e32 v21, 0 -buffer_store_dword v10, v21, s[0:3], 0 offen -v_mov_b32_e32 v21, 4 -buffer_store_dword v11, v21, s[0:3], 0 offen -v_mov_b32_e32 v21, 8 -buffer_store_dword v12, v21, s[0:3], 0 offen -v_mov_b32_e32 v21, 12 -buffer_store_dword v13, v21, s[0:3], 0 offen - -; --- ds_read2st64_b64, unit 512 bytes: seed 0x100 and 0x300 --- -v_mov_b32_e32 v1, 0x100 -v_mov_b32_e32 v3, 0x55550005 -ds_write_b32 v1, v3 -v_mov_b32_e32 v1, 0x104 -v_mov_b32_e32 v3, 0x66660006 -ds_write_b32 v1, v3 -v_mov_b32_e32 v1, 0x300 -v_mov_b32_e32 v3, 0x77770007 -ds_write_b32 v1, v3 -v_mov_b32_e32 v1, 0x304 -v_mov_b32_e32 v3, 0x88880008 -ds_write_b32 v1, v3 -s_waitcnt lgkmcnt(0) -v_mov_b32_e32 v2, 0x100 -ds_read2st64_b64 v[10:13], v2 offset0:0 offset1:1 -s_waitcnt lgkmcnt(0) -v_xor_b32_e32 v14, v10, v11 -v_xor_b32_e32 v14, v14, v12 -v_xor_b32_e32 v14, v14, v13 -v_mov_b32_e32 v21, 16 -buffer_store_dword v14, v21, s[0:3], 0 offen - -; --- ds_write2st64_b64, unit 512 bytes: A at 0x100, B at 0x300 --- -v_mov_b32_e32 v2, 0x100 -ds_write2st64_b64 v2, v[4:5], v[6:7] offset0:0 offset1:1 -s_waitcnt lgkmcnt(0) -v_mov_b32_e32 v1, 0x100 -ds_read_b32 v10, v1 -v_mov_b32_e32 v1, 0x104 -ds_read_b32 v11, v1 -v_mov_b32_e32 v1, 0x300 -ds_read_b32 v12, v1 -v_mov_b32_e32 v1, 0x304 -ds_read_b32 v13, v1 -s_waitcnt lgkmcnt(0) -v_xor_b32_e32 v15, v10, v11 -v_xor_b32_e32 v15, v15, v12 -v_xor_b32_e32 v15, v15, v13 -v_mov_b32_e32 v21, 20 -buffer_store_dword v15, v21, s[0:3], 0 offen - -; --- ds_read2_b64 with vdst overlapping vaddr: v[2:5] <- base v2 --- -v_mov_b32_e32 v1, 0x200 -v_mov_b32_e32 v3, 0x99990009 -ds_write_b32 v1, v3 -v_mov_b32_e32 v1, 0x204 -v_mov_b32_e32 v3, 0xAAAA000A -ds_write_b32 v1, v3 -v_mov_b32_e32 v1, 0x208 -v_mov_b32_e32 v3, 0xBBBB000B -ds_write_b32 v1, v3 -v_mov_b32_e32 v1, 0x20C -v_mov_b32_e32 v3, 0xCCCC000C -ds_write_b32 v1, v3 -s_waitcnt lgkmcnt(0) -v_mov_b32_e32 v2, 0x200 -ds_read2_b64 v[2:5], v2 offset0:0 offset1:1 -s_waitcnt lgkmcnt(0) -v_mov_b32_e32 v21, 24 -buffer_store_dword v4, v21, s[0:3], 0 offen - -; --- ds_cmpst_b32: hit at 0x400, miss at 0x404 --- -v_mov_b32_e32 v1, 0x400 -v_mov_b32_e32 v3, 0x13572468 -ds_write_b32 v1, v3 -v_mov_b32_e32 v1, 0x404 -v_mov_b32_e32 v3, 0x11111111 -ds_write_b32 v1, v3 -s_waitcnt lgkmcnt(0) -v_mov_b32_e32 v1, 0x400 -v_mov_b32_e32 v3, 0x13572468 -v_mov_b32_e32 v4, 0x2468ABCD -ds_cmpst_b32 v1, v3, v4 -s_waitcnt lgkmcnt(0) -ds_read_b32 v10, v1 -v_mov_b32_e32 v1, 0x404 -v_mov_b32_e32 v3, 0 -v_mov_b32_e32 v4, 0xFFFFFFFF -ds_cmpst_b32 v1, v3, v4 -s_waitcnt lgkmcnt(0) -ds_read_b32 v11, v1 -v_xor_b32_e32 v16, v10, v11 -v_mov_b32_e32 v21, 28 -buffer_store_dword v16, v21, s[0:3], 0 offen -s_endpgm diff --git a/runtime/test/shaders/cs_lds_xchg64_ext.asm b/runtime/test/shaders/cs_lds_xchg64_ext.asm deleted file mode 100644 index 8a89d4280..000000000 --- a/runtime/test/shaders/cs_lds_xchg64_ext.asm +++ /dev/null @@ -1,152 +0,0 @@ -; GPU test for the LDS forms docs/design.md lists as not GPU-verified that cs_lds_atomics_ext.asm leaves out (their -; translations were CPU-checked and the instructions measured on gfx1100, but the translated SPIR-V never ran on a -; GPU): ds_wrxchg_rtn_b64, ds_wrxchg2_rtn_b64, ds_wrxchg2st64_rtn_b64, ds_or_rtn_b64, ds_min_f32, ds_max_rtn_f32. -; -; LDS 4 KiB (RSRC2 0x40088), group 32x1x1, only lane 0 runs. The output words follow the design.md rows (which quote -; the RDNA2 ISA pseudocode); pairs are (low dword, high dword): -; -; out[0] ds_wrxchg_rtn_b64 at 0x40: M (0x11111111, 0x22222222) <- (0xAAAA0001, 0xBBBB0002); the element left, -; low ^ high: 0xAAAA0001 ^ 0xBBBB0002 -> 0x11110003 -; out[1] the old pair it returned, low ^ high: 0x11111111 ^ 0x22222222 -> 0x33333333 -; out[2] ds_or_rtn_b64 at 0x700: (0x0F0F0000, 0x000000F0) | (0x0000F0F0, 0xFF000000) leaves -; (0x0F0FF0F0, 0xFF0000F0); low ^ high -> 0xF00FF000 -; out[3] ds_wrxchg2_rtn_b64 at base 0x80, offset0:0 offset1:2 (unit 8: 0x80 and 0x90), seeded (1, 2) and -; (3, 4), data (0x10, 0x20) and (0x30, 0x40): the four old dwords in vdst, one byte each -> 0x04030201 -; out[4] the four dwords at 0x80, 0x84, 0x90, 0x94 after it, one byte each -> 0x40302010 -; out[5] ds_wrxchg2st64_rtn_b64 at base 0x100, offset0:1 offset1:2 (unit 512: 0x300 and 0x500), seeded -; (5, 6) and (7, 8), data (0x50, ..) and (0x70, ..): bytes = old low dword of each element, then the -; new low dword of each -> 0x70500705 -; out[6] ds_min_f32 at 0x600: M qNaN (0x7FC00000), DATA 1.5: NMin keeps the non-NaN operand -> 0x3FC00000 -; out[7] ds_max_rtn_f32 at 0x604: M -0.0, DATA +0.0: -0.0 orders below +0.0, so the word left is +0.0; it XOR -; the returned -0.0 -> 0x80000000 -; -; Run: vk_compute_test cs_lds_xchg64_ext.spv 1 dump -; -> out[0..7] = 0x11110003 0x33333333 0xF00FF000 0x04030201 -; 0x40302010 0x70500705 0x3FC00000 0x80000000 -; rsrc2: 0x40088 -; group: 32,1,1 -; mattr: +wavefrontsize32,-wavefrontsize64 -v_cmpx_eq_u32_e32 0, v0 - -; --- ds_wrxchg_rtn_b64 at 0x40 --- -v_mov_b32_e32 v1, 0x40 -v_mov_b32_e32 v4, 0x11111111 -v_mov_b32_e32 v5, 0x22222222 -ds_write_b64 v1, v[4:5] -s_waitcnt lgkmcnt(0) -v_mov_b32_e32 v4, 0xAAAA0001 -v_mov_b32_e32 v5, 0xBBBB0002 -ds_wrxchg_rtn_b64 v[12:13], v1, v[4:5] -s_waitcnt lgkmcnt(0) -ds_read_b64 v[10:11], v1 -s_waitcnt lgkmcnt(0) -v_xor_b32_e32 v10, v10, v11 -v_mov_b32_e32 v21, 0 -buffer_store_dword v10, v21, s[0:3], 0 offen -v_xor_b32_e32 v12, v12, v13 -v_mov_b32_e32 v21, 4 -buffer_store_dword v12, v21, s[0:3], 0 offen - -; --- ds_or_rtn_b64 at 0x700 --- -v_mov_b32_e32 v1, 0x700 -v_mov_b32_e32 v4, 0x0F0F0000 -v_mov_b32_e32 v5, 0x000000F0 -ds_write_b64 v1, v[4:5] -s_waitcnt lgkmcnt(0) -v_mov_b32_e32 v4, 0x0000F0F0 -v_mov_b32_e32 v5, 0xFF000000 -ds_or_rtn_b64 v[12:13], v1, v[4:5] -s_waitcnt lgkmcnt(0) -ds_read_b64 v[10:11], v1 -s_waitcnt lgkmcnt(0) -v_xor_b32_e32 v10, v10, v11 -v_mov_b32_e32 v21, 8 -buffer_store_dword v10, v21, s[0:3], 0 offen - -; --- ds_wrxchg2_rtn_b64 at base 0x80, elements at 0x80 and 0x90 --- -v_mov_b32_e32 v1, 0x80 -v_mov_b32_e32 v4, 1 -v_mov_b32_e32 v5, 2 -ds_write_b64 v1, v[4:5] -v_mov_b32_e32 v2, 0x90 -v_mov_b32_e32 v4, 3 -v_mov_b32_e32 v5, 4 -ds_write_b64 v2, v[4:5] -s_waitcnt lgkmcnt(0) -v_mov_b32_e32 v4, 0x10 -v_mov_b32_e32 v5, 0x20 -v_mov_b32_e32 v6, 0x30 -v_mov_b32_e32 v7, 0x40 -ds_wrxchg2_rtn_b64 v[12:15], v1, v[4:5], v[6:7] offset0:0 offset1:2 -s_waitcnt lgkmcnt(0) -v_lshlrev_b32_e32 v13, 8, v13 -v_or_b32_e32 v12, v12, v13 -v_lshlrev_b32_e32 v14, 16, v14 -v_or_b32_e32 v12, v12, v14 -v_lshlrev_b32_e32 v15, 24, v15 -v_or_b32_e32 v12, v12, v15 -v_mov_b32_e32 v21, 12 -buffer_store_dword v12, v21, s[0:3], 0 offen -ds_read_b64 v[10:11], v1 -ds_read_b64 v[12:13], v2 -s_waitcnt lgkmcnt(0) -v_lshlrev_b32_e32 v11, 8, v11 -v_or_b32_e32 v10, v10, v11 -v_lshlrev_b32_e32 v12, 16, v12 -v_or_b32_e32 v10, v10, v12 -v_lshlrev_b32_e32 v13, 24, v13 -v_or_b32_e32 v10, v10, v13 -v_mov_b32_e32 v21, 16 -buffer_store_dword v10, v21, s[0:3], 0 offen - -; --- ds_wrxchg2st64_rtn_b64 at base 0x100, elements at 0x300 and 0x500 --- -v_mov_b32_e32 v2, 0x300 -v_mov_b32_e32 v4, 5 -v_mov_b32_e32 v5, 6 -ds_write_b64 v2, v[4:5] -v_mov_b32_e32 v3, 0x500 -v_mov_b32_e32 v4, 7 -v_mov_b32_e32 v5, 8 -ds_write_b64 v3, v[4:5] -s_waitcnt lgkmcnt(0) -v_mov_b32_e32 v1, 0x100 -v_mov_b32_e32 v4, 0x50 -v_mov_b32_e32 v5, 0x60 -v_mov_b32_e32 v6, 0x70 -v_mov_b32_e32 v7, 0x80 -ds_wrxchg2st64_rtn_b64 v[12:15], v1, v[4:5], v[6:7] offset0:1 offset1:2 -s_waitcnt lgkmcnt(0) -ds_read_b32 v10, v2 -ds_read_b32 v11, v3 -s_waitcnt lgkmcnt(0) -v_lshlrev_b32_e32 v14, 8, v14 -v_or_b32_e32 v12, v12, v14 -v_lshlrev_b32_e32 v10, 16, v10 -v_or_b32_e32 v12, v12, v10 -v_lshlrev_b32_e32 v11, 24, v11 -v_or_b32_e32 v12, v12, v11 -v_mov_b32_e32 v21, 20 -buffer_store_dword v12, v21, s[0:3], 0 offen - -; --- ds_min_f32 (qNaN vs 1.5) and ds_max_rtn_f32 (-0.0 vs +0.0) --- -v_mov_b32_e32 v1, 0x600 -v_mov_b32_e32 v3, 0x7FC00000 -ds_write_b32 v1, v3 -v_mov_b32_e32 v2, 0x604 -v_mov_b32_e32 v3, 0x80000000 -ds_write_b32 v2, v3 -s_waitcnt lgkmcnt(0) -v_mov_b32_e32 v3, 0x3FC00000 -ds_min_f32 v1, v3 -v_mov_b32_e32 v3, 0 -ds_max_rtn_f32 v11, v2, v3 -s_waitcnt lgkmcnt(0) -ds_read_b32 v10, v1 -ds_read_b32 v12, v2 -s_waitcnt lgkmcnt(0) -v_mov_b32_e32 v21, 24 -buffer_store_dword v10, v21, s[0:3], 0 offen -v_xor_b32_e32 v12, v12, v11 -v_mov_b32_e32 v21, 28 -buffer_store_dword v12, v21, s[0:3], 0 offen -s_endpgm diff --git a/runtime/test/shaders/cs_m4_fill.asm b/runtime/test/shaders/cs_m4_fill.asm deleted file mode 100644 index 76ad114a9..000000000 --- a/runtime/test/shaders/cs_m4_fill.asm +++ /dev/null @@ -1,54 +0,0 @@ -; group: 64,1,1 -; rsrc2: 0x808c -; fssm-at: 0x150 -; fssm-data: 0x4c4c4946 0x3d344d5f -; M4 compute shader 1: fills a structured UAV buffer and a typed UAV image from a raw input buffer, and writes the -; arguments of the next (indirect) dispatch. Run: d3d12_m4_compute_test (a compute PSO found by the SHA-256 of its -; synthetic FSSM header, as for the other cs_ shaders). -; User data, from the root signature: [0] four 32-bit constants, [1] a descriptor table of five UAVs. RSRC2 0x808c = -; D3D12 build: runtime/cmake/d3d12_vulkan.cmake builds this with LEONIDA_USER_DATA_SHIFT=4, so in the PSO every SGPR -; named here is 4 higher (the console compute layout starts the root arguments at s4, D3D-448). The table pointer -; then reads s[8:9]: s8 is the table's 32-bit VA and s9 a user dword the runtime leaves zero. -; six user SGPRs and TGID_X, so the group index is s6: -; s0 = seed s1 = multiplier s2 = group count of the indirect dispatch s3 = unused -; s[4:5] = console VA of the table's first slot. A slot is 32 bytes: a V# in its first 16 bytes or a T# in all 32. -; slot 0 (+0x00): V#, structured buffer, stride 16, 256 records (written) -; slot 1 (+0x20): V#, raw buffer, the arguments of the indirect dispatch (written) -; slot 2 (+0x40): T#, 16x16 R32_UINT image (written) -; slot 3 (+0x60): V#, raw buffer, 256 input words (read) -; slot 4 (+0x80): V#, raw buffer, the second shader's output (not used here) -; g = 64 * group + lane, 0..255: in = input[g] -; record g = { in + seed, g * mul, in ^ (g << 8), rotr(in, 13) } -; image(x = g & 15, y = g >> 4) = in * 3 + x * 0x10001 + y -; g == 0 also writes the arguments { s2, 1, 1, 0xc0de0001 } -s_load_dwordx4 s[8:11], s[4:5], 0x0 -s_load_dwordx4 s[12:15], s[4:5], 0x20 -s_load_dwordx8 s[16:23], s[4:5], 0x40 -s_load_dwordx4 s[24:27], s[4:5], 0x60 -s_lshl_b32 s7, s6, 6 -s_waitcnt lgkmcnt(0) -v_add_nc_u32_e32 v1, s7, v0 -v_lshlrev_b32_e32 v2, 2, v1 -buffer_load_dword v3, v2, s[24:27], 0 offen -s_waitcnt vmcnt(0) -v_add_nc_u32_e32 v4, s0, v3 -v_mul_lo_u32 v5, v1, s1 -v_lshlrev_b32_e32 v6, 8, v1 -v_xor_b32_e32 v6, v3, v6 -v_alignbit_b32 v7, v3, v3, 13 -buffer_store_dwordx4 v[4:7], v1, s[8:11], 0 idxen -v_and_b32_e32 v8, 15, v1 -v_lshrrev_b32_e32 v9, 4, v1 -v_mul_u32_u24_e32 v10, 0x10001, v8 -v_mul_lo_u32 v11, v3, 3 -v_add_nc_u32_e32 v10, v10, v11 -v_add_nc_u32_e32 v10, v10, v9 -image_store v10, v[8:9], s[16:23] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm -v_cmpx_eq_u32_e32 0, v1 -v_mov_b32_e32 v12, 0 -v_mov_b32_e32 v13, s2 -v_mov_b32_e32 v14, 1 -v_mov_b32_e32 v15, 1 -v_mov_b32_e32 v16, 0xc0de0001 -buffer_store_dwordx4 v[13:16], v12, s[12:15], 0 offen -s_endpgm diff --git a/runtime/test/shaders/cs_m4_indirect.asm b/runtime/test/shaders/cs_m4_indirect.asm deleted file mode 100644 index e85a6d4d5..000000000 --- a/runtime/test/shaders/cs_m4_indirect.asm +++ /dev/null @@ -1,31 +0,0 @@ -; group: 64,1,1 -; rsrc2: 0x808c -; fssm-at: 0x150 -; fssm-data: 0x44444e49 0x3d344d5f -; M4 compute shader 2: runs under ExecuteIndirect with the arguments cs_m4_fill wrote ({ groups, 1, 1 }), reads the -; structured buffer and the image the first dispatch wrote, and writes a raw output buffer. Run: -; d3d12_m4_compute_test. Same root signature, user data and table as cs_m4_fill (see there): -; slot 0: structured buffer (read) slot 2: R32_UINT image (read, image_load) slot 4: raw output (written) -; D3D12 build: runtime/cmake/d3d12_vulkan.cmake builds this with LEONIDA_USER_DATA_SHIFT=4, so in the PSO every SGPR -; named here is 4 higher (the console compute layout starts the root arguments at s4, D3D-448). The table pointer -; then reads s[8:9]: s8 is the table's 32-bit VA and s9 a user dword the runtime leaves zero. -; g = 64 * group + lane; t = image(g & 15, g >> 4); record g = { w0, w1, w2, w3 } -; out[g] = { (w0 + t) ^ w3, (w2 ^ t) + w1 } at byte offset 8 * g -s_load_dwordx4 s[8:11], s[4:5], 0x0 -s_load_dwordx8 s[16:23], s[4:5], 0x40 -s_load_dwordx4 s[12:15], s[4:5], 0x80 -s_lshl_b32 s7, s6, 6 -s_waitcnt lgkmcnt(0) -v_add_nc_u32_e32 v1, s7, v0 -buffer_load_dwordx4 v[4:7], v1, s[8:11], 0 idxen -v_and_b32_e32 v8, 15, v1 -v_lshrrev_b32_e32 v9, 4, v1 -image_load v10, v[8:9], s[16:23] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm -s_waitcnt vmcnt(0) -v_add_nc_u32_e32 v11, v4, v10 -v_xor_b32_e32 v11, v11, v7 -v_xor_b32_e32 v12, v6, v10 -v_add_nc_u32_e32 v12, v12, v5 -v_lshlrev_b32_e32 v13, 3, v1 -buffer_store_dwordx2 v[11:12], v13, s[12:15], 0 offen -s_endpgm diff --git a/runtime/test/shaders/cs_mask_vgpr_exec.asm b/runtime/test/shaders/cs_mask_vgpr_exec.asm deleted file mode 100644 index 13e0bc0d9..000000000 --- a/runtime/test/shaders/cs_mask_vgpr_exec.asm +++ /dev/null @@ -1,15 +0,0 @@ -; group: 32,1,1 -; Part-2 test (SHADER-21 follow-up): a lane mask written to a VGPR under partial EXEC. -; Hardware: inactive lanes keep their old VGPR value. -; If the translator's write_all_lanes ignores EXEC, inactive lanes get the mask word instead. -v_mbcnt_lo_u32_b32 v1, -1, 0 -v_mov_b32_e32 v2, 0xdeadbeef -v_mov_b32_e32 v5, 1 -v_mov_b32_e32 v6, 2 -v_cmp_lt_u32_e64 vcc_lo, v5, v6 -s_mov_b32 exec_lo, 0x0000000f -v_mov_b32_e32 v2, vcc_lo -s_mov_b32 exec_lo, -1 -v_lshlrev_b32_e32 v3, 2, v1 -buffer_store_dword v2, v3, s[0:3], 0 offen -s_endpgm diff --git a/runtime/test/shaders/cs_movrelsd_2.asm b/runtime/test/shaders/cs_movrelsd_2.asm deleted file mode 100644 index 2d1ade2b0..000000000 --- a/runtime/test/shaders/cs_movrelsd_2.asm +++ /dev/null @@ -1,43 +0,0 @@ -; v_movrelsd_2_b32: VGPR[D + M0[25:16]] = VGPR[S0 + M0[9:0]] (RDNA2 ISA, VOP1 opcode 72). Unlike v_movrelsd_b32, -; each side has its own 10-bit M0 field, and M0[15:10] and M0[31:26] are ignored. -; v1..v8 = 11, 22, ..., 88; v15 = 1515, v17 = 1717, v25 = 0. -; 1. m0 = 0xFC03FC02 (dst 3, src 2, ignored bits set): v_movrelsd_2_b32 v1, v1 -> v4 = v3 = 33. -; 2. m0 = (20 << 16) | 10 (the ISA's example): v_movrelsd_2_b32 v5, v7 -> v25 = v17 = 1717. -; v15 (v5 + the source offset) keeps 1515: a translator that offset both sides by M0[9:0] would write it. -; Lane 0 stores: out[0..7] = v1 v3 v4 v5 v25 v7 v15 v17 = 11 33 33 55 1717 77 1515 1717. -; group: 32,1,1 -; Run: vk_compute_test cs_movrelsd_2.spv 1 dump -> out[0..7] = 11 33 33 55 1717 77 1515 1717 -; mattr: +wavefrontsize32,-wavefrontsize64 -v_mov_b32_e32 v1, 11 -v_mov_b32_e32 v2, 22 -v_mov_b32_e32 v3, 33 -v_mov_b32_e32 v4, 44 -v_mov_b32_e32 v5, 55 -v_mov_b32_e32 v6, 0x42 -v_mov_b32_e32 v7, 0x4d -v_mov_b32_e32 v8, 0x58 -v_mov_b32_e32 v15, 0x5eb -v_mov_b32_e32 v17, 0x6b5 -v_mov_b32_e32 v25, 0 -s_mov_b32 m0, 0xfc03fc02 -v_movrelsd_2_b32 v1, v1 -s_mov_b32 m0, 0x14000a -v_movrelsd_2_b32 v5, v7 -v_cmpx_eq_u32_e32 0, v0 -v_mov_b32_e32 v21, 0 -buffer_store_dword v1, v21, s[0:3], 0 offen -v_mov_b32_e32 v21, 4 -buffer_store_dword v3, v21, s[0:3], 0 offen -v_mov_b32_e32 v21, 8 -buffer_store_dword v4, v21, s[0:3], 0 offen -v_mov_b32_e32 v21, 12 -buffer_store_dword v5, v21, s[0:3], 0 offen -v_mov_b32_e32 v21, 16 -buffer_store_dword v25, v21, s[0:3], 0 offen -v_mov_b32_e32 v21, 20 -buffer_store_dword v7, v21, s[0:3], 0 offen -v_mov_b32_e32 v21, 24 -buffer_store_dword v15, v21, s[0:3], 0 offen -v_mov_b32_e32 v21, 28 -buffer_store_dword v17, v21, s[0:3], 0 offen -s_endpgm diff --git a/runtime/test/shaders/cs_oob_select.asm b/runtime/test/shaders/cs_oob_select.asm deleted file mode 100644 index 7644d27f7..000000000 --- a/runtime/test/shaders/cs_oob_select.asm +++ /dev/null @@ -1,91 +0,0 @@ -; regen_fixtures: this source has a translator fixture in tests/semantic/fixtures/disasm -; V# OOB_SELECT (word3 bits 29:28) picks the MUBUF bounds check (docs/design.md, Buffer bounds checking). RDNA2 rules -; (measured on gfx1036, docs/buffer_bounds.md; Mesa's GFX11 column): idx = vindex (0 without idxen), off = -; inst_offset + vaddr offset, offs = off + soffset, a dword access: -; 0 STRUCTURED_WITH_OFFSET: out of range if idx >= NUM_RECORDS || off + 4 > STRIDE -; 1 STRUCTURED: out of range if idx >= NUM_RECORDS -; 2 DISABLED: out of range if NUM_RECORDS == 0 -; 3 RAW: out of range if offs + 4 > NUM_RECORDS (idx * stride is in the address, not in the check) -; Out of range reads 0. Thread 0 seeds heap bytes 0x40..0x5f (region offset X = byte 0x40 + X) with 0x5eed0000 + X; -; every V# has base 0x40. The heap is 0xee-filled, so an access that is in range but beyond the seed reads 0xeeeeeeee. -; Literal V#s (s_mov_b32 of word3) fold the mode at translation time; the three with an s_or_b32 of word3 are run-time -; V#s and select it with OpSelect. One thread, no wave64 requirement. Words, in out[0..7]: -; 0 mode 0 literal, stride 8, NR 4, idx 1 + off 4: idx < 4, 4 + 4 <= 8 -> X = 8 + 4 = 0xc: 0x5eed000c -; 1 mode 0 literal, idx 1 + off 8: 8 + 4 > 8 -> 0 (mode 1 or the stride check alone reads X 0x10) -; 2 mode 1 literal, stride 8, NR 4, idx 1 + off 12: idx < 4 only -> X = 8 + 12 = 0x14: 0x5eed0014 -; 3 mode 1 literal, idx 4 + off 0: 4 >= 4 -> 0 -; 4 mode 2 run-time, stride 0, NR 4, off 0x18: NR != 0 -> X 0x18: 0x5eed0018 (RAW would give 0) -; 5 mode 3 run-time, stride 8, NR 0x10, idx 7 + off 4: offs 4 < 0x10 -> X = 56 + 4 = 0x3c, beyond the seed: 0xeeeeeeee -; (a check of idx against NUM_RECORDS would give 0) -; 6 mode 3 literal, stride 8, NR 0x10, off 0x10 (offen only): 0x10 + 4 > 0x10 -> 0 (mode 1 reads X 0x10) -; 7 mode 0 run-time, stride 8, NR 4, off 0x10 (offen only): 0x10 + 4 > 8 -> 0 -; The expected words are derived from those rules; the probes avoid an access that straddles an edge, so a start-based -; check predicts the same words; cs_oob_tail.asm is the one that tells the two apart. -; Run: vk_compute_test cs_oob_select.spv 1 dump -> out[0..7] = 0x5eed000c 0x00000000 0x5eed0014 0x00000000 -; 0x5eed0018 0xeeeeeeee 0x00000000 0x00000000 (1592590348 0 1592590356 0 1592590360 4008636142 0 0). -v_cmpx_eq_u32_e32 0, v0 -v_mov_b32 v1, 0x5eed0000 -v_mov_b32 v2, 0x5eed0004 -v_mov_b32 v3, 0x5eed0008 -v_mov_b32 v4, 0x5eed000c -buffer_store_dwordx4 v[1:4], off, s[0:3], 0 offset:64 -v_mov_b32 v1, 0x5eed0010 -v_mov_b32 v2, 0x5eed0014 -v_mov_b32 v3, 0x5eed0018 -v_mov_b32 v4, 0x5eed001c -buffer_store_dwordx4 v[1:4], off, s[0:3], 0 offset:80 -s_waitcnt vmcnt(0) -s_mov_b32 s4, 0x40 -s_mov_b32 s5, 0x80000 -s_mov_b32 s6, 4 -s_mov_b32 s7, 0x01016fac -s_mov_b32 s8, 0x40 -s_mov_b32 s9, 0x80000 -s_mov_b32 s10, 4 -s_mov_b32 s11, 0x11016fac -s_mov_b32 s12, 0x40 -s_mov_b32 s13, 0 -s_mov_b32 s14, 4 -s_mov_b32 s15, 0x01016fac -s_mov_b32 s20, 0x20000000 -s_or_b32 s15, s15, s20 -s_mov_b32 s16, 0x40 -s_mov_b32 s17, 0x80000 -s_mov_b32 s18, 0x10 -s_mov_b32 s19, 0x01016fac -s_mov_b32 s21, 0x30000000 -s_or_b32 s19, s19, s21 -s_mov_b32 s24, 0x40 -s_mov_b32 s25, 0x80000 -s_mov_b32 s26, 0x10 -s_mov_b32 s27, 0x31016fac -s_mov_b32 s28, 0x40 -s_mov_b32 s29, 0x80000 -s_mov_b32 s30, 4 -s_mov_b32 s31, 0x01016fac -s_mov_b32 s22, 0 -s_or_b32 s31, s31, s22 -v_mov_b32 v20, 1 -v_mov_b32 v21, 4 -v_mov_b32 v22, 1 -v_mov_b32 v23, 8 -v_mov_b32 v24, 1 -v_mov_b32 v25, 12 -v_mov_b32 v26, 4 -v_mov_b32 v27, 0 -v_mov_b32 v28, 0x18 -v_mov_b32 v29, 7 -v_mov_b32 v30, 4 -v_mov_b32 v31, 0x10 -buffer_load_dword v10, v[20:21], s[4:7], 0 idxen offen -buffer_load_dword v11, v[22:23], s[4:7], 0 idxen offen -buffer_load_dword v12, v[24:25], s[8:11], 0 idxen offen -buffer_load_dword v13, v[26:27], s[8:11], 0 idxen offen -buffer_load_dword v14, v28, s[12:15], 0 offen -buffer_load_dword v15, v[29:30], s[16:19], 0 idxen offen -buffer_load_dword v16, v31, s[24:27], 0 offen -buffer_load_dword v17, v31, s[28:31], 0 offen -s_waitcnt vmcnt(0) -buffer_store_dwordx4 v[10:13], off, s[0:3], 0 -buffer_store_dwordx4 v[14:17], off, s[0:3], 0 offset:16 -s_endpgm diff --git a/runtime/test/shaders/cs_oob_tail.asm b/runtime/test/shaders/cs_oob_tail.asm deleted file mode 100644 index 81e3ffc62..000000000 --- a/runtime/test/shaders/cs_oob_tail.asm +++ /dev/null @@ -1,77 +0,0 @@ -; regen_fixtures: this source has a translator fixture in tests/semantic/fixtures/disasm -; The end of an access decides, not its start (docs/design.md, Buffer bounds checking; measured on a Radeon 880M -; (gfx1150), a valid proxy for RDNA2: gfx1036 follows the same column, docs/buffer_bounds.md). Mesa's GFX10 column, which -; compares only the start, gives different words for out[0], out[1] and out[6]. Thread 0 seeds heap bytes -; 0x40..0x5f (region offset X = byte 0x40 + X) with 0x5eed0000 + X; every V# has base 0x40, the heap is 0xee-filled. -; 0 mode 3 (RAW), NR 10, b32 at off 8: ends at 12 > 10 -> 0 (a start check reads X 8) -; 1 mode 0, stride 10, NR 4, idx 0, b32 at off 8: 8 + 4 > 10 -> 0 (a start check reads X 8) -; 2 mode 3, NR 20, x4 load at off 8, dword 2: ends at 20 <= 20 -> X 0x10: 0x5eed0010 -; 3 same load, dword 3: ends at 24 > 20 -> 0 (per dword, not per load) -; 4 mode 3, NR 32, x2 store at off 0x1c, read back X 0x1c (through a V# with NR 256): first dword ends at 32 -> 0xbeef0000 -; 5 same store, read X 0x20 (its second dword): ends at 36 > 32, dropped -> 0xeeeeeeee -; 6 mode 3, NR 32, buffer_load_format_xyzw 32_32_32_32_UINT at off 0x14, x: element ends at 36 > 32 -> 0 (all or nothing) -; 7 same load at off 0x10, x: ends at 32 <= 32 -> X 0x10: 0x5eed0010 -; Run: vk_compute_test cs_oob_tail.spv 1 dump -> out[0..7] = 0x00000000 0x00000000 0x5eed0010 0x00000000 0xbeef0000 -; 0xeeeeeeee 0x00000000 0x5eed0010 (0 0 1592590352 0 3203334144 4008636142 0 1592590352). -v_cmpx_eq_u32_e32 0, v0 -v_mov_b32 v1, 0x5eed0000 -v_mov_b32 v2, 0x5eed0004 -v_mov_b32 v3, 0x5eed0008 -v_mov_b32 v4, 0x5eed000c -buffer_store_dwordx4 v[1:4], off, s[0:3], 0 offset:64 -v_mov_b32 v1, 0x5eed0010 -v_mov_b32 v2, 0x5eed0014 -v_mov_b32 v3, 0x5eed0018 -v_mov_b32 v4, 0x5eed001c -buffer_store_dwordx4 v[1:4], off, s[0:3], 0 offset:80 -s_waitcnt vmcnt(0) -s_mov_b32 s4, 0x40 -s_mov_b32 s5, 0 -s_mov_b32 s6, 10 -s_mov_b32 s7, 0x31016fac -s_mov_b32 s8, 0x40 -s_mov_b32 s9, 0xa0000 -s_mov_b32 s10, 4 -s_mov_b32 s11, 0x01016fac -s_mov_b32 s12, 0x40 -s_mov_b32 s13, 0 -s_mov_b32 s14, 20 -s_mov_b32 s15, 0x31016fac -s_mov_b32 s16, 0x40 -s_mov_b32 s17, 0 -s_mov_b32 s18, 32 -s_mov_b32 s19, 0x31016fac -s_mov_b32 s28, 0x40 -s_mov_b32 s29, 0 -s_mov_b32 s30, 0x100 -s_mov_b32 s31, 0x31016fac -s_mov_b32 s24, 0x40 -s_mov_b32 s25, 0 -s_mov_b32 s26, 32 -s_mov_b32 s27, 0x3104bfac -v_mov_b32 v1, 8 -v_mov_b32 v5, 0x1c -v_mov_b32 v6, 0x20 -v_mov_b32 v7, 0x14 -v_mov_b32 v8, 0x10 -v_mov_b32 v24, 0xbeef0000 -v_mov_b32 v25, 0xbeef0001 -buffer_load_dword v10, v1, s[4:7], 0 offen -buffer_load_dword v11, v1, s[8:11], 0 offen -buffer_load_dwordx4 v[20:23], v1, s[12:15], 0 offen -buffer_store_dwordx2 v[24:25], v5, s[16:19], 0 offen -s_waitcnt vmcnt(0) -buffer_load_dword v26, v5, s[28:31], 0 offen -buffer_load_dword v27, v6, s[28:31], 0 offen -buffer_load_format_xyzw v[28:31], v7, s[24:27], 0 offen -buffer_load_format_xyzw v[32:35], v8, s[24:27], 0 offen -s_waitcnt vmcnt(0) -buffer_store_dword v10, off, s[0:3], 0 -buffer_store_dword v11, off, s[0:3], 0 offset:4 -buffer_store_dword v22, off, s[0:3], 0 offset:8 -buffer_store_dword v23, off, s[0:3], 0 offset:12 -buffer_store_dword v26, off, s[0:3], 0 offset:16 -buffer_store_dword v27, off, s[0:3], 0 offset:20 -buffer_store_dword v28, off, s[0:3], 0 offset:24 -buffer_store_dword v32, off, s[0:3], 0 offset:28 -s_endpgm diff --git a/runtime/test/shaders/cs_pk_mul_lo_const.asm b/runtime/test/shaders/cs_pk_mul_lo_const.asm deleted file mode 100644 index d7312cd48..000000000 --- a/runtime/test/shaders/cs_pk_mul_lo_const.asm +++ /dev/null @@ -1,38 +0,0 @@ -; regen_fixtures: this source has a translator fixture in tests/semantic/fixtures/disasm -; group: 32,1,1 -; v_pk_mul_lo_u16 with a constant operand (an SGPR, a literal, an inline constant), one half of the constant 0 or -; small, the other operand computed at run time from the output buffer's 0xEEEEEEEE fill (so no compiler can fold it). -; Each 16-bit half of D is the low 16 bits of the product of the selected source halves (RDNA2 ISA, V_PK_MUL_LO_U16; -; op_sel picks the half of each source for the low result, op_sel_hi for the high one; defaults [0,0] and [1,1]): -; 0: v_pk_mul_lo_u16 v30, v3, s8 op_sel:[0,1] op_sel_hi:[0,0] v3.lo = 0x1234, s8 = 0xaaaa0000 -; lo = 0x1234 * 0xaaaa & 0xffff = 0x9e88, hi = 0x1234 * 0x0000 = 0 -> 0x00009E88 -; 1: v_pk_mul_lo_u16 v31, s7, v15 op_sel_hi:[1,0] s7 = 0x0003ffff, v15.lo = 0xabcd -; lo = 0xffff * 0xabcd & 0xffff, hi = 0x0003 * 0xabcd & 0xffff -> 0x03675433 -; 2: v_pk_mul_lo_u16 v32, v2, 0x00050000 v2 = 0x0007beef: lo = 0xbeef * 0 = 0, -; hi = 0x0007 * 0x0005 = 0x23 -> 0x00230000 -; 3: v_pk_mul_lo_u16 v33, v3, 7 op_sel_hi:[1,0] v3 = 0x00011234: lo = 0x1234 * 7, -; hi = v3.hi * 7.lo (op_sel_hi[1] = 0: the low half of the constant 7) -> 0x00077F6C -; Measured natively on RDNA2 (gfx1036, Ryzen 9 9950X3D iGPU, driver 26.10.1) through tools/hw_oracle (raw HIP kernel). -; On the AMD Windows driver the translated (x * y) & 0xffff of case 0 came out 0x0c229e88: the mask was dropped when the -; other half was a constant 0. The translator now computes the low 16 bits as ((x << 16) * y) >> 16. -; Run: vk_compute_test cs_pk_mul_lo_const.spv 1 dump -; out[0..7] = 00009E88 03675433 00230000 00077F6C 00009E88 03675433 00230000 00077F6C (hex) -s_mov_b32 exec_lo, -1 -v_mov_b32_e32 v20, v0 -v_lshlrev_b32_e32 v21, 4, v20 -buffer_load_dword v22, v21, s[0:3], 0 offen -s_waitcnt vmcnt(0) -v_xor_b32_e32 v3, 0xeeeffcda, v22 -v_xor_b32_e32 v15, 0xfcda4523, v22 -v_xor_b32_e32 v2, 0xeee95001, v22 -s_mov_b32 s8, 0xaaaa0000 -s_mov_b32 s7, 0x0003ffff -v_pk_mul_lo_u16 v30, v3, s8 op_sel:[0,1] op_sel_hi:[0,0] -v_pk_mul_lo_u16 v31, s7, v15 op_sel_hi:[1,0] -v_pk_mul_lo_u16 v32, v2, 0x00050000 -v_pk_mul_lo_u16 v33, v3, 7 op_sel_hi:[1,0] -buffer_store_dword v30, v21, s[0:3], 0 offen -buffer_store_dword v31, v21, s[0:3], 0 offen offset:4 -buffer_store_dword v32, v21, s[0:3], 0 offen offset:8 -buffer_store_dword v33, v21, s[0:3], 0 offen offset:12 -s_endpgm diff --git a/runtime/test/shaders/cs_resinfo.asm b/runtime/test/shaders/cs_resinfo.asm deleted file mode 100644 index 88be15028..000000000 --- a/runtime/test/shaders/cs_resinfo.asm +++ /dev/null @@ -1,110 +0,0 @@ -; image_get_resinfo on a 16x4 image with five mip levels. RDNA2 ISA (MIMG): the address register holds a mip level, -; there is no sampler, and the result is four integers, {num_mip_levels, depth, height, width} in VGPRs 3..0, of -; which dmask keeps some and packs them into consecutive registers. Width and height are those of the level asked -; for (halved per level, never below 1), the depth word is 0 for a 2D image (not the T#'s DEPTH field + 1), and the -; level count is that of the view; past the last level width, height and depth are 0 (both measured on RDNA2 gfx1036 -; with tools/image_query_probe.py, SHADER-388). -; Run: vk_store_test cs_resinfo.spv words -; The T# in s[8:15] is the one of that image, as Mesa's gfx10 register database lays it out (and as -; runtime/src/gfx10_descriptors.h writes it): word 1 = FORMAT 56 (rgba8 unorm) << 20 | (width - 1 = 15) low two bits -; << 30, word 2 = (15 >> 2) | (height - 1 = 3) << 14, word 3 = DST_SEL x, y, z, w (0xfac) | LAST_LEVEL 4 << 16 | -; TYPE 9 (2D) << 28, word 5 = MAX_MIP 4 << 4. vk_store_test binds a 16x4 rgba8 image with five levels behind exactly -; these eight words. Thread 0 stores each result word into its own texel of the uint image (T# 0x2000...), texel -; i = 8y + x: -; level 0, dmask 0xf -> words 0..3 = 16 4 0 5 -; level 1, dmask 0xf -> words 4..7 = 8 2 0 5 -; level 3, dmask 0xf -> words 8..11 = 2 1 0 5 (4 >> 3 would be 0: the height stays 1) -; level 2, dmask 0x3 -> words 12..13 = 4 1 width and height -; word 14 = 0xabcd the register after them is not written -; level 1, dmask 0xa -> words 16..17 = 2 5 height and level count, packed into two registers -; level 4, dmask 0x8 -> word 18 = 5 the level count alone -; level 5, dmask 0xf -> words 20..23 = 0 0 0 5 past the last level -; Every other word keeps the tool's fill, 100 + i, and the sint image its -2i. -v_cmpx_eq_u32_e32 0, v0 -s_mov_b32 s8, 0x4000 -s_mov_b32 s9, 0xc3800000 -s_mov_b32 s10, 0xc003 -s_mov_b32 s11, 0x90040fac -s_mov_b32 s12, 0 -s_mov_b32 s13, 0x40 -s_mov_b32 s14, 0 -s_mov_b32 s15, 0 -s_mov_b32 s16, 0x2000 -s_mov_b32 s17, 0x1400000 -s_mov_b32 s18, 0x22 -s_mov_b32 s19, 0x22 -s_mov_b32 s20, 0x22 -s_mov_b32 s21, 0x22 -s_mov_b32 s22, 0x22 -s_mov_b32 s23, 0x22 -v_mov_b32_e32 v3, 0 -image_get_resinfo v[4:7], v3, s[8:15] dmask:0xf dim:SQ_RSRC_IMG_2D -s_waitcnt vmcnt(0) -v_mov_b32_e32 v2, 0 -v_mov_b32_e32 v1, 0 -image_store v4, v[1:2], s[16:23] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm -v_mov_b32_e32 v1, 1 -image_store v5, v[1:2], s[16:23] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm -v_mov_b32_e32 v1, 2 -image_store v6, v[1:2], s[16:23] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm -v_mov_b32_e32 v1, 3 -image_store v7, v[1:2], s[16:23] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm -v_mov_b32_e32 v3, 1 -image_get_resinfo v[4:7], v3, s[8:15] dmask:0xf dim:SQ_RSRC_IMG_2D -s_waitcnt vmcnt(0) -v_mov_b32_e32 v1, 4 -image_store v4, v[1:2], s[16:23] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm -v_mov_b32_e32 v1, 5 -image_store v5, v[1:2], s[16:23] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm -v_mov_b32_e32 v1, 6 -image_store v6, v[1:2], s[16:23] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm -v_mov_b32_e32 v1, 7 -image_store v7, v[1:2], s[16:23] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm -v_mov_b32_e32 v3, 3 -image_get_resinfo v[4:7], v3, s[8:15] dmask:0xf dim:SQ_RSRC_IMG_2D -s_waitcnt vmcnt(0) -v_mov_b32_e32 v2, 1 -v_mov_b32_e32 v1, 0 -image_store v4, v[1:2], s[16:23] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm -v_mov_b32_e32 v1, 1 -image_store v5, v[1:2], s[16:23] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm -v_mov_b32_e32 v1, 2 -image_store v6, v[1:2], s[16:23] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm -v_mov_b32_e32 v1, 3 -image_store v7, v[1:2], s[16:23] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm -v_mov_b32_e32 v3, 2 -v_mov_b32_e32 v10, 0xabcd -image_get_resinfo v[8:9], v3, s[8:15] dmask:0x3 dim:SQ_RSRC_IMG_2D -s_waitcnt vmcnt(0) -v_mov_b32_e32 v1, 4 -image_store v8, v[1:2], s[16:23] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm -v_mov_b32_e32 v1, 5 -image_store v9, v[1:2], s[16:23] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm -v_mov_b32_e32 v1, 6 -image_store v10, v[1:2], s[16:23] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm -v_mov_b32_e32 v3, 1 -image_get_resinfo v[11:12], v3, s[8:15] dmask:0xa dim:SQ_RSRC_IMG_2D -s_waitcnt vmcnt(0) -v_mov_b32_e32 v2, 2 -v_mov_b32_e32 v1, 0 -image_store v11, v[1:2], s[16:23] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm -v_mov_b32_e32 v1, 1 -image_store v12, v[1:2], s[16:23] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm -v_mov_b32_e32 v3, 4 -image_get_resinfo v13, v3, s[8:15] dmask:0x8 dim:SQ_RSRC_IMG_2D -s_waitcnt vmcnt(0) -v_mov_b32_e32 v1, 2 -image_store v13, v[1:2], s[16:23] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm -v_mov_b32_e32 v3, 5 -image_get_resinfo v[4:7], v3, s[8:15] dmask:0xf dim:SQ_RSRC_IMG_2D -s_waitcnt vmcnt(0) -v_mov_b32_e32 v2, 2 -v_mov_b32_e32 v1, 4 -image_store v4, v[1:2], s[16:23] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm -v_mov_b32_e32 v1, 5 -image_store v5, v[1:2], s[16:23] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm -v_mov_b32_e32 v1, 6 -image_store v6, v[1:2], s[16:23] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm -v_mov_b32_e32 v1, 7 -image_store v7, v[1:2], s[16:23] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm -s_endpgm diff --git a/runtime/test/shaders/cs_sample_lz_int_d16.asm b/runtime/test/shaders/cs_sample_lz_int_d16.asm deleted file mode 100644 index f1fc24775..000000000 --- a/runtime/test/shaders/cs_sample_lz_int_d16.asm +++ /dev/null @@ -1,56 +0,0 @@ -; Point-sample the R32_UINT and R32_SINT images at each texel centre and add the D16 results. -; vk_store_test load-d16 checks the signed/unsigned saturation boundaries in the last row, -; the sum (100 - 8y - x) elsewhere, and the untouched UINT image. -; The unregistered S# selects the harness's nearest, clamp-to-edge sampler. -v_and_b32_e32 v1, 7, v0 -v_lshrrev_b32_e32 v2, 3, v0 -v_cvt_f32_u32_e32 v3, v1 -v_cvt_f32_u32_e32 v4, v2 -v_add_f32_e32 v8, 0.5, v3 -v_add_f32_e32 v9, 0.5, v4 -v_mul_f32_e32 v8, 0x3e000000, v8 -v_mul_f32_e32 v9, 0x3e000000, v9 -s_mov_b32 s32, 0 -s_mov_b32 s33, 0 -s_mov_b32 s34, 0 -s_mov_b32 s35, 0 -v_mul_f32_e32 v3, 0x3e124925, v3 -v_mul_f32_e32 v4, 0x3e124925, v4 -v_mov_b32_e32 v5, 0.5 -v_mov_b32_e32 v6, 1.0 -s_mov_b32 s8, 0x1000 -s_mov_b32 s9, 0x3800000 -s_mov_b32 s10, 0x11 -s_mov_b32 s11, 0x11 -s_mov_b32 s12, 0x11 -s_mov_b32 s13, 0x11 -s_mov_b32 s14, 0x11 -s_mov_b32 s15, 0x11 -image_store v[3:6], v[1:2], s[8:15] dmask:0xf dim:SQ_RSRC_IMG_2D unorm -s_mov_b32 s16, 0x2000 -s_mov_b32 s17, 0x1400000 -s_mov_b32 s18, 0x22 -s_mov_b32 s19, 0x22 -s_mov_b32 s20, 0x22 -s_mov_b32 s21, 0x22 -s_mov_b32 s22, 0x22 -s_mov_b32 s23, 0x22 -image_sample_lz v7, v[8:9], s[16:23], s[32:35] dmask:0x1 dim:SQ_RSRC_IMG_2D d16 -s_mov_b32 s24, 0x3000 -s_mov_b32 s25, 0x1500000 -s_mov_b32 s26, 0x33 -s_mov_b32 s27, 0x33 -s_mov_b32 s28, 0x33 -s_mov_b32 s29, 0x33 -s_mov_b32 s30, 0x33 -s_mov_b32 s31, 0x33 -image_sample_lz v11, v[8:9], s[24:31], s[32:35] dmask:0x1 dim:SQ_RSRC_IMG_2D d16 -s_waitcnt vmcnt(0) -v_and_b32_e32 v7, 0xffff, v7 -v_bfe_i32 v11, v11, 0, 16 -v_add_nc_u32_e32 v11, v7, v11 -v_mov_b32_e32 v12, 0 -v_mov_b32_e32 v13, 0 -v_mov_b32_e32 v14, 0 -image_store v[11:14], v[1:2], s[24:31] dmask:0xf dim:SQ_RSRC_IMG_2D unorm -s_endpgm diff --git a/runtime/test/shaders/cs_signed_zero_nan.asm b/runtime/test/shaders/cs_signed_zero_nan.asm deleted file mode 100644 index 3dd8555cc..000000000 --- a/runtime/test/shaders/cs_signed_zero_nan.asm +++ /dev/null @@ -1,63 +0,0 @@ -; group: 8,1,1 -; mattr: +wavefrontsize32,-wavefrontsize64 -; NaN, infinity and -0 come out of RDNA2 float ops as computed (IEEE). The translator declares -; SignedZeroInfNanPreserve so the driver may not assume they don't occur. Without it, on an RX 9070 XT (AMD -; 26.11.2) this test gets 0 in out[4..7]: the x != x NaN checks fold to false and the NaN conversion is lost. The -; f16 fuzzer there also saw -0 products come back +0, and NaN results narrowed with integer ops never stored. -; Apple GPUs (MoltenVK) return +0 in out[0], out[2] and out[3] with or without the mode (#1203, SHADER-182), so -; check.py and run_gpu_tests.py don't judge those three words on an Apple device; the other five still count. -; Mesa llvmpipe returns 0 in out[5] (the 0 * inf check) with or without the mode, while its other NaN checks give 1 -; (#664), so out[5] isn't judged there; the other seven still count (UNJUDGED_WORDS in check.py). -; Thread 0 stores eight words: -; out[0] v_mul_f32 -0.0 * 1.0 = 0x80000000 -; out[1] v_add_f32 -0.0 + -0.0 = 0x80000000 -; out[2] v_pk_mul_f16 (-0, -0) * (1.0, 1.0) = 0x80008000 -; out[3] v_mul_f16 -0 * 1.0, high half kept (0) = 0x00008000 -; out[4] v_cmp_neq_f32 x, x with x = inf - inf (NaN) = 0x00000001 -; out[5] v_cmp_neq_f32 x, x with x = 0 * inf (NaN) = 0x00000001 -; out[6] v_cmp_neq_f16 x, x with x = f16 inf - inf (NaN) = 0x00000001 -; out[7] v_cvt_f16_f32 of NaN, exponent bits (& 0x7c00) = 0x00007c00 -; Run: vk_compute_test cs_signed_zero_nan.spv 1 dump -; out[0..7] = 80000000 80000000 80008000 00008000 00000001 00000001 00000001 00007c00 (hex) -v_cmpx_eq_u32_e32 0, v0 -v_mov_b32_e32 v1, 0x80000000 -v_mov_b32_e32 v2, 1.0 -v_mul_f32_e32 v10, v1, v2 -v_add_f32_e32 v11, v1, v1 -v_mov_b32_e32 v3, 0x80008000 -v_mov_b32_e32 v4, 0x3c003c00 -v_pk_mul_f16 v12, v3, v4 -v_mov_b32_e32 v13, 0 -v_mul_f16_e32 v13, v3, v4 -v_mov_b32_e32 v5, 0x7f800000 -v_sub_f32_e32 v6, v5, v5 -v_cmp_neq_f32_e32 vcc_lo, v6, v6 -v_cndmask_b32_e64 v14, 0, 1, vcc_lo -v_mov_b32_e32 v7, 0 -v_mul_f32_e32 v8, v7, v5 -v_cmp_neq_f32_e32 vcc_lo, v8, v8 -v_cndmask_b32_e64 v15, 0, 1, vcc_lo -v_mov_b32_e32 v9, 0x7c00 -v_sub_f16_e32 v16, v9, v9 -v_cmp_neq_f16_e32 vcc_lo, v16, v16 -v_cndmask_b32_e64 v17, 0, 1, vcc_lo -v_mov_b32_e32 v18, 0 -v_cvt_f16_f32_e32 v18, v6 -v_and_b32_e32 v18, 0x7c00, v18 -v_mov_b32_e32 v30, 0 -buffer_store_dword v10, v30, s[0:3], 0 offen -v_mov_b32_e32 v30, 4 -buffer_store_dword v11, v30, s[0:3], 0 offen -v_mov_b32_e32 v30, 8 -buffer_store_dword v12, v30, s[0:3], 0 offen -v_mov_b32_e32 v30, 12 -buffer_store_dword v13, v30, s[0:3], 0 offen -v_mov_b32_e32 v30, 16 -buffer_store_dword v14, v30, s[0:3], 0 offen -v_mov_b32_e32 v30, 20 -buffer_store_dword v15, v30, s[0:3], 0 offen -v_mov_b32_e32 v30, 24 -buffer_store_dword v17, v30, s[0:3], 0 offen -v_mov_b32_e32 v30, 28 -buffer_store_dword v18, v30, s[0:3], 0 offen -s_endpgm diff --git a/runtime/test/shaders/cs_smem_bounds.asm b/runtime/test/shaders/cs_smem_bounds.asm deleted file mode 100644 index 43980bcb6..000000000 --- a/runtime/test/shaders/cs_smem_bounds.asm +++ /dev/null @@ -1,63 +0,0 @@ -; regen_fixtures: this source has a translator fixture in tests/semantic/fixtures/disasm -; s_buffer_load NUM_RECORDS bound, per dword, on the 4-truncated offset. Rule measured on an AMD Radeon RX 6800 -; (gfx1030) as a raw compute kernel (docs/design.md, Scalar/buffer memory): off = (soffset & ~3) + (imm & ~3); -; dword i at o = off + 4*i is 0 when o + 4 > limit (limit = NUM_RECORDS bytes for stride 0), else the dword at -; (base & ~3) + o. -; Thread 0 seeds heap bytes 0x40..0x5f (region offset X = byte 0x40 + X) with 0x5eed0000 + X, then loads through -; V#s it builds itself (base 0x40, stride 0, word3 0x31016fac = OOB_SELECT 3 as measured) with four NUM_RECORDS: -; s_buffer_load_dword s24, NR 0x12, 0x10 -> 0x10 + 4 > 0x12: 0 (no bound: 0x5eed0010) -; s_buffer_load_dword s25, NR 0x15, 0x13 -> off 0x10, 0x14 <= 0x15: 0x5eed0010 -; s_buffer_load_dword s26, NR 0x10, s20=0xe offset:0x2 -> off 0xc + 0, 0x10 <= 0x10: 0x5eed000c -; (truncating the sum 0x10 would give 0) -; s_buffer_load_dword s27, NR 0x14, s21=0x10 offset:0x4 -> off 0x14, 0x18 > 0x14: 0 -; s_buffer_load_dwordx4 s[28:31], NR 0x15, 0xc -> 0xc, 0x10 in; 0x14, 0x18 out: data, data, 0, 0 -; and writes s24..s31 to out[0..7]. -; Run: vk_compute_test cs_smem_bounds.spv 1 dump -> out[0..7] = 0x00000000 0x5eed0010 0x5eed000c 0x00000000 -; 0x5eed000c 0x5eed0010 0x00000000 0x00000000 (0 1592590352 1592590348 0 1592590348 1592590352 0 0). -v_cmpx_eq_u32_e32 0, v0 -v_mov_b32 v1, 0x5eed0000 -v_mov_b32 v2, 0x5eed0004 -v_mov_b32 v3, 0x5eed0008 -v_mov_b32 v4, 0x5eed000c -buffer_store_dwordx4 v[1:4], off, s[0:3], 0 offset:64 -v_mov_b32 v1, 0x5eed0010 -v_mov_b32 v2, 0x5eed0014 -v_mov_b32 v3, 0x5eed0018 -v_mov_b32 v4, 0x5eed001c -buffer_store_dwordx4 v[1:4], off, s[0:3], 0 offset:80 -s_waitcnt vmcnt(0) -s_mov_b32 s4, 0x40 -s_mov_b32 s5, 0 -s_mov_b32 s6, 0x12 -s_mov_b32 s7, 0x31016fac -s_mov_b32 s8, 0x40 -s_mov_b32 s9, 0 -s_mov_b32 s10, 0x15 -s_mov_b32 s11, 0x31016fac -s_mov_b32 s12, 0x40 -s_mov_b32 s13, 0 -s_mov_b32 s14, 0x10 -s_mov_b32 s15, 0x31016fac -s_mov_b32 s16, 0x40 -s_mov_b32 s17, 0 -s_mov_b32 s18, 0x14 -s_mov_b32 s19, 0x31016fac -s_mov_b32 s20, 0xe -s_mov_b32 s21, 0x10 -s_buffer_load_dword s24, s[4:7], 0x10 -s_buffer_load_dword s25, s[8:11], 0x13 -s_buffer_load_dword s26, s[12:15], s20 offset:0x2 -s_buffer_load_dword s27, s[16:19], s21 offset:0x4 -s_buffer_load_dwordx4 s[28:31], s[8:11], 0xc -s_waitcnt lgkmcnt(0) -v_mov_b32 v1, s24 -v_mov_b32 v2, s25 -v_mov_b32 v3, s26 -v_mov_b32 v4, s27 -buffer_store_dwordx4 v[1:4], off, s[0:3], 0 -v_mov_b32 v1, s28 -v_mov_b32 v2, s29 -v_mov_b32 v3, s30 -v_mov_b32 v4, s31 -buffer_store_dwordx4 v[1:4], off, s[0:3], 0 offset:16 -s_endpgm diff --git a/runtime/test/shaders/cs_smem_sconst_off.asm b/runtime/test/shaders/cs_smem_sconst_off.asm deleted file mode 100644 index 8c1ae02fe..000000000 --- a/runtime/test/shaders/cs_smem_sconst_off.asm +++ /dev/null @@ -1,48 +0,0 @@ -; regen_fixtures: this source has a translator fixture in tests/semantic/fixtures/disasm -; SHADER-328: an s_buffer_load SGPR offset the translator can see as a constant gives what the same offset gives at run -; time. The rule (docs/design.md, Scalar/buffer memory): off = zext(soffset & ~3) + (imm & ~3) in 64 bits, and the -; dword is 0 when off + 4 > limit. #1686 folded a constant soffset as a 32-bit sum, so 0xfffffffc + 20 wrapped to 16 -; and read data; gfx1036 (tools/hw_oracle, #1686) reads 0. -; Thread 0 seeds heap bytes 0x40..0x5f (region offset X = byte 0x40 + X) with 0x5eed0000 + X and byte 0x60 with -; 4, then loads through a V# it builds itself (base 0x40, stride 0, NUM_RECORDS 0x40, word3 0x31016fac): -; s_buffer_load_dword s24, s8=-4 offset:20 (constant) -> 0xfffffffc + 0x14 > 0x40: 0 (32-bit wrap: 0x5eed0010) -; s_buffer_load_dword s25, s9=4 offset:20 (from heap 0x60) -> run time, in range: 0x5eed0018, as s26 -; s_buffer_load_dword s26, s10=4 offset:20 (constant) -> 0x18: 0x5eed0018 -; s_buffer_load_dword s27, s11=0x10 offset:4 (constant) -> 0x14: 0x5eed0014 -; and writes s24..s27 to out[0..3]. The run-time load stays in range: an out-of-range run-time sOFF (-4) made llvmpipe -; (Mesa 26.0.8) do the guarded load anyway and segfault (#1938 review); the CPU tests cover that path. -; Run: vk_compute_test cs_smem_sconst_off.spv 1 dump -> out[0..3] = 0x00000000 0x5eed0018 0x5eed0018 0x5eed0014. -v_cmpx_eq_u32_e32 0, v0 -v_mov_b32 v1, 0x5eed0000 -v_mov_b32 v2, 0x5eed0004 -v_mov_b32 v3, 0x5eed0008 -v_mov_b32 v4, 0x5eed000c -buffer_store_dwordx4 v[1:4], off, s[0:3], 0 offset:64 -v_mov_b32 v1, 0x5eed0010 -v_mov_b32 v2, 0x5eed0014 -v_mov_b32 v3, 0x5eed0018 -v_mov_b32 v4, 0x5eed001c -buffer_store_dwordx4 v[1:4], off, s[0:3], 0 offset:80 -v_mov_b32 v5, 4 -buffer_store_dword v5, off, s[0:3], 0 offset:96 -s_waitcnt vmcnt(0) -s_mov_b32 s4, 0x40 -s_mov_b32 s5, 0 -s_mov_b32 s6, 0x40 -s_mov_b32 s7, 0x31016fac -s_mov_b32 s8, -4 -s_buffer_load_dword s9, s[0:3], 0x60 -s_mov_b32 s10, 4 -s_mov_b32 s11, 0x10 -s_waitcnt lgkmcnt(0) -s_buffer_load_dword s24, s[4:7], s8 offset:0x14 -s_buffer_load_dword s25, s[4:7], s9 offset:0x14 -s_buffer_load_dword s26, s[4:7], s10 offset:0x14 -s_buffer_load_dword s27, s[4:7], s11 offset:0x4 -s_waitcnt lgkmcnt(0) -v_mov_b32 v1, s24 -v_mov_b32 v2, s25 -v_mov_b32 v3, s26 -v_mov_b32 v4, s27 -buffer_store_dwordx4 v[1:4], off, s[0:3], 0 -s_endpgm diff --git a/runtime/test/shaders/cs_smem_sload_neg.asm b/runtime/test/shaders/cs_smem_sload_neg.asm deleted file mode 100644 index fa979565c..000000000 --- a/runtime/test/shaders/cs_smem_sload_neg.asm +++ /dev/null @@ -1,52 +0,0 @@ -; regen_fixtures: this source has a translator fixture in tests/semantic/fixtures/disasm -; s_load with a soffset and a negative immediate: the immediate is sign-extended (21 bits) and truncated to a -; multiple of 4 on its own, soffset likewise, and both are added to the 4-truncated 64-bit pointer. Measured on an -; AMD Radeon RX 6800 (gfx1030) as a raw compute kernel, only with soffset + imm >= 0 (docs/design.md, Scalar/buffer -; memory); every row here keeps that sum non-negative. -; Thread 0 seeds heap bytes 0x40..0x5f (region offset X = byte 0x40 + X) with 0x5eed0000 + X, then (ptr 0x40 in -; s[4:5], ptr 0x43 in s[6:7]): -; s_load_dword s24, s[4:5], s20=8 offset:-0x4 -> 8 - 4: 0x5eed0004 (zero-extended imm: +4 GiB) -; s_load_dword s25, s[4:5], s20=8 offset:-0x8 -> 0: 0x5eed0000 -; s_load_dword s26, s[4:5], s21=0xb offset:-0x1 -> 8 + -4: 0x5eed0004 (truncating the sum 0xa: +8) -; s_load_dword s27, s[6:7], s21=0xb offset:-0x1 -> 0x40 + 4: 0x5eed0004 -; s_load_dwordx2 s[28:29], s[4:5], s22=0x10 offset:-0x8 -> 8, 0xc: 0x5eed0008 0x5eed000c -; and writes s24..s29 to out[0..5]; out[6..7] keep the 0xee fill. -; With a translator that zero-extends the immediate the first four reads go 4 GiB past the heap: do not run this -; test on a GPU with such a translator (it can fault the device). -; Run: vk_compute_test cs_smem_sload_neg.spv 1 dump -> out[0..7] = 0x5eed0004 0x5eed0000 0x5eed0004 0x5eed0004 -; 0x5eed0008 0x5eed000c 0xeeeeeeee 0xeeeeeeee (1592590340 1592590336 1592590340 1592590340 1592590344 1592590348 -; 4008636142 4008636142). -v_cmpx_eq_u32_e32 0, v0 -v_mov_b32 v1, 0x5eed0000 -v_mov_b32 v2, 0x5eed0004 -v_mov_b32 v3, 0x5eed0008 -v_mov_b32 v4, 0x5eed000c -buffer_store_dwordx4 v[1:4], off, s[0:3], 0 offset:64 -v_mov_b32 v1, 0x5eed0010 -v_mov_b32 v2, 0x5eed0014 -v_mov_b32 v3, 0x5eed0018 -v_mov_b32 v4, 0x5eed001c -buffer_store_dwordx4 v[1:4], off, s[0:3], 0 offset:80 -s_waitcnt vmcnt(0) -s_mov_b32 s4, 0x40 -s_mov_b32 s5, 0 -s_mov_b32 s6, 0x43 -s_mov_b32 s7, 0 -s_mov_b32 s20, 8 -s_mov_b32 s21, 0xb -s_mov_b32 s22, 0x10 -s_load_dword s24, s[4:5], s20 offset:-0x4 -s_load_dword s25, s[4:5], s20 offset:-0x8 -s_load_dword s26, s[4:5], s21 offset:-0x1 -s_load_dword s27, s[6:7], s21 offset:-0x1 -s_load_dwordx2 s[28:29], s[4:5], s22 offset:-0x8 -s_waitcnt lgkmcnt(0) -v_mov_b32 v1, s24 -v_mov_b32 v2, s25 -v_mov_b32 v3, s26 -v_mov_b32 v4, s27 -buffer_store_dwordx4 v[1:4], off, s[0:3], 0 -v_mov_b32 v1, s28 -v_mov_b32 v2, s29 -buffer_store_dwordx2 v[1:2], off, s[0:3], 0 offset:16 -s_endpgm diff --git a/runtime/test/shaders/cs_smem_soffset_imm.asm b/runtime/test/shaders/cs_smem_soffset_imm.asm deleted file mode 100644 index 399de1860..000000000 --- a/runtime/test/shaders/cs_smem_soffset_imm.asm +++ /dev/null @@ -1,61 +0,0 @@ -; SMEM loads that carry a register offset AND an immediate (llvm-mc: "sOFF offset:IMM"): address = base + soffset + imm. -; Measured on an AMD Radeon RX 6800 (gfx1030) by running s_buffer_load_dword/x2/x4/x8 as a raw compute kernel: -; soffset 8 + imm 4 reads the dword at +12. s_load_dword shares the SMEM encoding; applying the rule to it is an inference. -; Thread 0 seeds heap bytes 0x10..0x30 with 0x5eed0000 + byte offset, then loads with s8 = 0x10: -; s_buffer_load_dword s9, s[0:3], s8 offset:0x14 -> byte 0x24 (imm dropped: 0x10, s8 dropped: 0x14) -; s_load_dword s10, s[4:5], s8 offset:0x18 -> byte 0x28 (imm dropped: 0x10, s8 dropped: 0x18) -; s_buffer_load_dwordx2 s[12:13], s[0:3], s8 offset:0x1c -> bytes 0x2c, 0x30 (imm dropped: 0x10, 0x14; s8 dropped: 0x1c, 0x20) -; and writes s9, s10, s12, s13 to out[0..3]; out[4..7] keep the seeds of bytes 0x10..0x1c. -; All offsets are multiples of 4 and inside the buffer, so alignment and num_records play no part. -; Run: vk_compute_test cs_smem_soffset_imm.spv 1 dump -> out[0..7] = 0x5eed0024 0x5eed0028 0x5eed002c 0x5eed0030 -; 0x5eed0010 0x5eed0014 0x5eed0018 0x5eed001c (1592590372 1592590376 1592590380 1592590384 1592590352 1592590356 -; 1592590360 1592590364). Same FSSM header as cs_lds. -v_cmpx_eq_u32_e32 0, v0 -v_mov_b32 v1, 0x5eed0010 -v_mov_b32 v2, 0x10 -buffer_store_dword v1, v2, s[0:3], 0 offen -v_mov_b32 v1, 0x5eed0014 -v_mov_b32 v2, 0x14 -buffer_store_dword v1, v2, s[0:3], 0 offen -v_mov_b32 v1, 0x5eed0018 -v_mov_b32 v2, 0x18 -buffer_store_dword v1, v2, s[0:3], 0 offen -v_mov_b32 v1, 0x5eed001c -v_mov_b32 v2, 0x1c -buffer_store_dword v1, v2, s[0:3], 0 offen -v_mov_b32 v1, 0x5eed0020 -v_mov_b32 v2, 0x20 -buffer_store_dword v1, v2, s[0:3], 0 offen -v_mov_b32 v1, 0x5eed0024 -v_mov_b32 v2, 0x24 -buffer_store_dword v1, v2, s[0:3], 0 offen -v_mov_b32 v1, 0x5eed0028 -v_mov_b32 v2, 0x28 -buffer_store_dword v1, v2, s[0:3], 0 offen -v_mov_b32 v1, 0x5eed002c -v_mov_b32 v2, 0x2c -buffer_store_dword v1, v2, s[0:3], 0 offen -v_mov_b32 v1, 0x5eed0030 -v_mov_b32 v2, 0x30 -buffer_store_dword v1, v2, s[0:3], 0 offen -s_waitcnt vmcnt(0) -s_mov_b32 s4, 0 -s_mov_b32 s5, 0 -s_mov_b32 s8, 0x10 -s_buffer_load_dword s9, s[0:3], s8 offset:0x14 -s_load_dword s10, s[4:5], s8 offset:0x18 -s_buffer_load_dwordx2 s[12:13], s[0:3], s8 offset:0x1c -s_waitcnt lgkmcnt(0) -v_mov_b32 v1, s9 -v_mov_b32 v2, 0 -buffer_store_dword v1, v2, s[0:3], 0 offen -v_mov_b32 v1, s10 -v_mov_b32 v2, 4 -buffer_store_dword v1, v2, s[0:3], 0 offen -v_mov_b32 v1, s12 -v_mov_b32 v2, 8 -buffer_store_dword v1, v2, s[0:3], 0 offen -v_mov_b32 v1, s13 -v_mov_b32 v2, 12 -buffer_store_dword v1, v2, s[0:3], 0 offen -s_endpgm diff --git a/runtime/test/shaders/cs_smem_stride_align.asm b/runtime/test/shaders/cs_smem_stride_align.asm deleted file mode 100644 index 05491e7ef..000000000 --- a/runtime/test/shaders/cs_smem_stride_align.asm +++ /dev/null @@ -1,67 +0,0 @@ -; regen_fixtures: this source has a translator fixture in tests/semantic/fixtures/disasm -; s_buffer_load with a stride (limit = NUM_RECORDS * stride bytes) and SMEM address truncation: base, soffset and -; imm are each truncated to a multiple of 4 before they are added. Rules measured on an AMD Radeon RX 6800 (gfx1030) -; as a raw compute kernel (docs/design.md, Scalar/buffer memory). -; Thread 0 seeds heap bytes 0x40..0x5f (region offset X = byte 0x40 + X) with 0x5eed0000 + X, then: -; s_buffer_load_dword s24, stride 4, NR 5, 0x10 -> limit 20, 0x14 <= 20: 0x5eed0010 (NR as bytes would give 0) -; s_buffer_load_dword s25, stride 4, NR 5, 0x14 -> 0x18 > 20: 0 -; s_buffer_load_dword s26, stride 1, NR 17, 0x10 -> limit 17, 0x14 > 17: 0 (index 16 < 17 would read) -; s_buffer_load_dword s27, base 0x41, 0x3 -> (0x41 & ~3) + 0: 0x5eed0000 (unaligned sum 0x44: 0x5eed0004) -; s_load_dword s28, ptr 0x41, 0x1 -> 0x40: 0x5eed0000 -; s_buffer_load_dword s29, base 0x41, s20=3 offset:0x3 -> 0 + 0: 0x5eed0000 (sum 6 truncated would be 4) -; s_load_dword s30, ptr 0x40, s20=3 offset:0x3 -> 0x5eed0000 -; s_buffer_load_dword s31, base 0x41, s21=2 offset:0x6 -> 0 + 4: 0x5eed0004 (sum 8 would be 8) -; (V#s with base 0x41 have NR 0x100, word3 0x31016fac = OOB_SELECT 3 everywhere) and writes s24..s31 to out[0..7]. -; Run: vk_compute_test cs_smem_stride_align.spv 1 dump -> out[0..7] = 0x5eed0010 0x00000000 0x00000000 0x5eed0000 -; 0x5eed0000 0x5eed0000 0x5eed0000 0x5eed0004 (1592590352 0 0 1592590336 1592590336 1592590336 1592590336 -; 1592590340). -v_cmpx_eq_u32_e32 0, v0 -v_mov_b32 v1, 0x5eed0000 -v_mov_b32 v2, 0x5eed0004 -v_mov_b32 v3, 0x5eed0008 -v_mov_b32 v4, 0x5eed000c -buffer_store_dwordx4 v[1:4], off, s[0:3], 0 offset:64 -v_mov_b32 v1, 0x5eed0010 -v_mov_b32 v2, 0x5eed0014 -v_mov_b32 v3, 0x5eed0018 -v_mov_b32 v4, 0x5eed001c -buffer_store_dwordx4 v[1:4], off, s[0:3], 0 offset:80 -s_waitcnt vmcnt(0) -s_mov_b32 s4, 0x40 -s_mov_b32 s5, 0x40000 -s_mov_b32 s6, 5 -s_mov_b32 s7, 0x31016fac -s_mov_b32 s8, 0x40 -s_mov_b32 s9, 0x10000 -s_mov_b32 s10, 17 -s_mov_b32 s11, 0x31016fac -s_mov_b32 s12, 0x41 -s_mov_b32 s13, 0 -s_mov_b32 s14, 0x100 -s_mov_b32 s15, 0x31016fac -s_mov_b32 s16, 0x41 -s_mov_b32 s17, 0 -s_mov_b32 s18, 0x40 -s_mov_b32 s19, 0 -s_mov_b32 s20, 3 -s_mov_b32 s21, 2 -s_buffer_load_dword s24, s[4:7], 0x10 -s_buffer_load_dword s25, s[4:7], 0x14 -s_buffer_load_dword s26, s[8:11], 0x10 -s_buffer_load_dword s27, s[12:15], 0x3 -s_load_dword s28, s[16:17], 0x1 -s_buffer_load_dword s29, s[12:15], s20 offset:0x3 -s_load_dword s30, s[18:19], s20 offset:0x3 -s_buffer_load_dword s31, s[12:15], s21 offset:0x6 -s_waitcnt lgkmcnt(0) -v_mov_b32 v1, s24 -v_mov_b32 v2, s25 -v_mov_b32 v3, s26 -v_mov_b32 v4, s27 -buffer_store_dwordx4 v[1:4], off, s[0:3], 0 -v_mov_b32 v1, s28 -v_mov_b32 v2, s29 -v_mov_b32 v3, s30 -v_mov_b32 v4, s31 -buffer_store_dwordx4 v[1:4], off, s[0:3], 0 offset:16 -s_endpgm diff --git a/runtime/test/shaders/cs_store.asm b/runtime/test/shaders/cs_store.asm deleted file mode 100644 index f450598eb..000000000 --- a/runtime/test/shaders/cs_store.asm +++ /dev/null @@ -1,40 +0,0 @@ -; buffer_store_format encoder: rgba8 unorm (56), 2_10_10_10 unorm (50), two r16f (13) halves of one dword (atomic merge), -; d16 rgba16f (71), BGRA UNORM stores (56, 50). Run: vk_compute_test cs_store.spv 1 dump -> out[0..7] = -; 0x400080ff 0xe00003ff 0x3c004000 0xeeeeeeee (untouched) 0x40003c00 0xbc003800 0x40ff8000 0x3ff00000. Same FSSM header as cs_lds. OOB_SELECT 3 in word3 (the output V# is raw). -v_cmpx_eq_u32_e32 0, v0 -v_mov_b32_e32 v1, 1.0 -v_mov_b32_e32 v2, 0.5 -v_mov_b32_e32 v3, 0 -v_mov_b32_e32 v4, 0x3e800000 -v_mov_b32_e32 v5, 0 -s_mov_b32 s3, 0x31038fac -buffer_store_format_xyzw v[1:4], v5, s[0:3], 0 offen -v_mov_b32_e32 v6, 1.0 -v_mov_b32_e32 v7, 0 -v_mov_b32_e32 v8, 0.5 -v_mov_b32_e32 v9, 1.0 -v_mov_b32_e32 v5, 4 -s_mov_b32 s3, 0x31032fac -buffer_store_format_xyzw v[6:9], v5, s[0:3], 0 offen -s_mov_b32 s3, 0x3100d000 -v_mov_b32_e32 v10, 2.0 -v_mov_b32_e32 v5, 8 -buffer_store_format_x v10, v5, s[0:3], 0 offen -v_mov_b32_e32 v10, 1.0 -v_mov_b32_e32 v5, 10 -buffer_store_format_x v10, v5, s[0:3], 0 offen -s_mov_b32 s3, 0x31047000 -v_mov_b32_e32 v11, 0x40003c00 -v_mov_b32_e32 v12, 0xbc003800 -v_mov_b32_e32 v5, 16 -buffer_store_format_d16_xyzw v[11:12], v5, s[0:3], 0 offen -; The first store's values (1, .5, 0, .25), now with Z,Y,X,W selectors. -s_mov_b32 s3, 0x31038f2e -v_mov_b32_e32 v5, 24 -buffer_store_format_xyzw v[1:4], v5, s[0:3], 0 offen -; The low half contains 1.0. A single red component fills the third 10-bit field. -s_mov_b32 s3, 0x31032f2e -v_mov_b32_e32 v11, 0x3c00 -v_mov_b32_e32 v5, 28 -buffer_store_format_d16_x v11, v5, s[0:3], 0 offen -s_endpgm diff --git a/runtime/test/shaders/cs_tbuffer_store.asm b/runtime/test/shaders/cs_tbuffer_store.asm deleted file mode 100644 index 40b74b8af..000000000 --- a/runtime/test/shaders/cs_tbuffer_store.asm +++ /dev/null @@ -1,276 +0,0 @@ -; regen_fixtures: this source has a translator fixture in tests/semantic/fixtures/disasm -; tbuffer_store_format_* and its d16 forms. Every expected word was measured by running this body natively on a Radeon -; 680M (gfx1035, RDNA2) through tools/hw_oracle's kernel wrapper, with s[0:3] set to the V# vk_compute_test passes; -; wave32 and wave64 gave the same 52 words. One thread runs. -; - The instruction's format replaces the V#'s, for the encoding, the element size and the bounds check alike. No -; format modifier means GFX10's default, BUF_FMT_8_UNORM: one byte, its neighbours kept. -; - A store writes its format's whole element: components the format has but the instruction doesn't give are 0 -; (xy into 16_16_16_16 leaves z = w = 0); components the format doesn't have are dropped (xyzw into 32_32 writes -; x, y; into 32 only x). -; - d16 data is two 16-bit values per VGPR, low half first. -; - Bounds (OOB_SELECT 3): the instruction's element must end inside num_records. With NR 0x298, an xy store of a -; 16-byte element at 0x290 writes nothing, though a V# that says 32_FLOAT has a 4-byte element; with NR 0x2a1, an -; 8_UNORM byte at 0x2a0 is written, though the V#'s 16-byte element would not fit. -; - A V# whose FORMAT is 0 (INVALID) disables the store, though the instruction brings its own format. -; Store regions 0x200..0x2cf start as 0xa5a50000 | address; out[0..51] are the 13 regions read back, in source order. -; Run: VKC_OUT_WORDS=192 VKC_DUMP= vk_compute_test cs_tbuffer_store.spv 1 dump; check.py compares words 0..127 of -; the dump with TBUFFER_STORE_WORDS and 76 untouched 0xeeeeeeee words. -v_cmpx_eq_u32_e32 0, v0 -; the store regions 0x200..0x2cf hold 0xa5a50000 | their address -v_mov_b32_e32 v1, 0xa5a50200 -v_mov_b32_e32 v2, 0xa5a50204 -v_mov_b32_e32 v3, 0xa5a50208 -v_mov_b32_e32 v4, 0xa5a5020c -v_mov_b32_e32 v5, 0x200 -buffer_store_dwordx4 v[1:4], v5, s[0:3], 0 offen -v_mov_b32_e32 v1, 0xa5a50210 -v_mov_b32_e32 v2, 0xa5a50214 -v_mov_b32_e32 v3, 0xa5a50218 -v_mov_b32_e32 v4, 0xa5a5021c -v_mov_b32_e32 v5, 0x210 -buffer_store_dwordx4 v[1:4], v5, s[0:3], 0 offen -v_mov_b32_e32 v1, 0xa5a50220 -v_mov_b32_e32 v2, 0xa5a50224 -v_mov_b32_e32 v3, 0xa5a50228 -v_mov_b32_e32 v4, 0xa5a5022c -v_mov_b32_e32 v5, 0x220 -buffer_store_dwordx4 v[1:4], v5, s[0:3], 0 offen -v_mov_b32_e32 v1, 0xa5a50230 -v_mov_b32_e32 v2, 0xa5a50234 -v_mov_b32_e32 v3, 0xa5a50238 -v_mov_b32_e32 v4, 0xa5a5023c -v_mov_b32_e32 v5, 0x230 -buffer_store_dwordx4 v[1:4], v5, s[0:3], 0 offen -v_mov_b32_e32 v1, 0xa5a50240 -v_mov_b32_e32 v2, 0xa5a50244 -v_mov_b32_e32 v3, 0xa5a50248 -v_mov_b32_e32 v4, 0xa5a5024c -v_mov_b32_e32 v5, 0x240 -buffer_store_dwordx4 v[1:4], v5, s[0:3], 0 offen -v_mov_b32_e32 v1, 0xa5a50250 -v_mov_b32_e32 v2, 0xa5a50254 -v_mov_b32_e32 v3, 0xa5a50258 -v_mov_b32_e32 v4, 0xa5a5025c -v_mov_b32_e32 v5, 0x250 -buffer_store_dwordx4 v[1:4], v5, s[0:3], 0 offen -v_mov_b32_e32 v1, 0xa5a50260 -v_mov_b32_e32 v2, 0xa5a50264 -v_mov_b32_e32 v3, 0xa5a50268 -v_mov_b32_e32 v4, 0xa5a5026c -v_mov_b32_e32 v5, 0x260 -buffer_store_dwordx4 v[1:4], v5, s[0:3], 0 offen -v_mov_b32_e32 v1, 0xa5a50270 -v_mov_b32_e32 v2, 0xa5a50274 -v_mov_b32_e32 v3, 0xa5a50278 -v_mov_b32_e32 v4, 0xa5a5027c -v_mov_b32_e32 v5, 0x270 -buffer_store_dwordx4 v[1:4], v5, s[0:3], 0 offen -v_mov_b32_e32 v1, 0xa5a50280 -v_mov_b32_e32 v2, 0xa5a50284 -v_mov_b32_e32 v3, 0xa5a50288 -v_mov_b32_e32 v4, 0xa5a5028c -v_mov_b32_e32 v5, 0x280 -buffer_store_dwordx4 v[1:4], v5, s[0:3], 0 offen -v_mov_b32_e32 v1, 0xa5a50290 -v_mov_b32_e32 v2, 0xa5a50294 -v_mov_b32_e32 v3, 0xa5a50298 -v_mov_b32_e32 v4, 0xa5a5029c -v_mov_b32_e32 v5, 0x290 -buffer_store_dwordx4 v[1:4], v5, s[0:3], 0 offen -v_mov_b32_e32 v1, 0xa5a502a0 -v_mov_b32_e32 v2, 0xa5a502a4 -v_mov_b32_e32 v3, 0xa5a502a8 -v_mov_b32_e32 v4, 0xa5a502ac -v_mov_b32_e32 v5, 0x2a0 -buffer_store_dwordx4 v[1:4], v5, s[0:3], 0 offen -v_mov_b32_e32 v1, 0xa5a502b0 -v_mov_b32_e32 v2, 0xa5a502b4 -v_mov_b32_e32 v3, 0xa5a502b8 -v_mov_b32_e32 v4, 0xa5a502bc -v_mov_b32_e32 v5, 0x2b0 -buffer_store_dwordx4 v[1:4], v5, s[0:3], 0 offen -v_mov_b32_e32 v1, 0xa5a502c0 -v_mov_b32_e32 v2, 0xa5a502c4 -v_mov_b32_e32 v3, 0xa5a502c8 -v_mov_b32_e32 v4, 0xa5a502cc -v_mov_b32_e32 v5, 0x2c0 -buffer_store_dwordx4 v[1:4], v5, s[0:3], 0 offen -s_waitcnt_vscnt null, 0x0 -s_mov_b32 s4, s0 -s_mov_b32 s5, s1 -; 0x200: tbuffer_store_format_xyzw, xyzw, 32_32_32_32_FLOAT over a V# that says 32_FLOAT: all four dwords -v_mov_b32_e32 v20, 0x3f800000 -v_mov_b32_e32 v21, 0x40000000 -v_mov_b32_e32 v22, 0x40400000 -v_mov_b32_e32 v23, 0x40800000 -s_mov_b32 s6, 0xffffffff -s_mov_b32 s7, 0x31016fac -v_mov_b32_e32 v5, 0x200 -tbuffer_store_format_xyzw v[20:23], v5, s[4:7], 0 format:[BUF_FMT_32_32_32_32_FLOAT] offen -; 0x210: tbuffer_store_format_xy, xy, 16_16_16_16_FLOAT over a V# that says 32_32_32_32_FLOAT: the 8-byte element, z = w = 0 -v_mov_b32_e32 v20, 0x3f800000 -v_mov_b32_e32 v21, 0x40000000 -s_mov_b32 s6, 0xffffffff -s_mov_b32 s7, 0x3104dfac -v_mov_b32_e32 v5, 0x210 -tbuffer_store_format_xy v[20:21], v5, s[4:7], 0 format:[BUF_FMT_16_16_16_16_FLOAT] offen -; 0x220: tbuffer_store_format_xyz, xyz, 8_8_8_8_UINT over a V# that says 32_FLOAT -v_mov_b32_e32 v20, 0x1 -v_mov_b32_e32 v21, 0x2 -v_mov_b32_e32 v22, 0x3 -s_mov_b32 s6, 0xffffffff -s_mov_b32 s7, 0x31016fac -v_mov_b32_e32 v5, 0x220 -tbuffer_store_format_xyz v[20:22], v5, s[4:7], 0 format:[BUF_FMT_8_8_8_8_UINT] offen -; 0x230: tbuffer_store_format_x, x, no format modifier (GFX10 default 8_UNORM) at byte 1, over a V# that says 32_32_32_32_FLOAT -v_mov_b32_e32 v20, 0x3f800000 -s_mov_b32 s6, 0xffffffff -s_mov_b32 s7, 0x3104dfac -v_mov_b32_e32 v5, 0x231 -tbuffer_store_format_x v20, v5, s[4:7], 0 offen -; 0x240: tbuffer_store_format_x, x, 16_FLOAT at byte 2 (the high half) -v_mov_b32_e32 v20, 0x40000000 -s_mov_b32 s6, 0xffffffff -s_mov_b32 s7, 0x31016fac -v_mov_b32_e32 v5, 0x242 -tbuffer_store_format_x v20, v5, s[4:7], 0 format:[BUF_FMT_16_FLOAT] offen -; 0x250: tbuffer_store_format_xyzw, xyzw, 2_10_10_10_UNORM (1.0, 0.0, 0.25, 1.0) -v_mov_b32_e32 v20, 0x3f800000 -v_mov_b32_e32 v21, 0x0 -v_mov_b32_e32 v22, 0x3e800000 -v_mov_b32_e32 v23, 0x3f800000 -s_mov_b32 s6, 0xffffffff -s_mov_b32 s7, 0x31016fac -v_mov_b32_e32 v5, 0x250 -tbuffer_store_format_xyzw v[20:23], v5, s[4:7], 0 format:[BUF_FMT_2_10_10_10_UNORM] offen -; 0x260: tbuffer_store_format_xyzw, xyzw into 32_32_FLOAT: only x, y -v_mov_b32_e32 v20, 0x3f800000 -v_mov_b32_e32 v21, 0x40000000 -v_mov_b32_e32 v22, 0x40400000 -v_mov_b32_e32 v23, 0x40800000 -s_mov_b32 s6, 0xffffffff -s_mov_b32 s7, 0x3104dfac -v_mov_b32_e32 v5, 0x260 -tbuffer_store_format_xyzw v[20:23], v5, s[4:7], 0 format:[BUF_FMT_32_32_FLOAT] offen -; 0x270: tbuffer_store_format_d16_xy, d16_xy, 16_16_FLOAT (packed 1.0, 2.0) -v_mov_b32_e32 v20, 0x40003c00 -s_mov_b32 s6, 0xffffffff -s_mov_b32 s7, 0x3104dfac -v_mov_b32_e32 v5, 0x270 -tbuffer_store_format_d16_xy v20, v5, s[4:7], 0 format:[BUF_FMT_16_16_FLOAT] offen -; 0x280: tbuffer_store_format_d16_xyzw, d16_xyzw, 8_8_8_8_UNORM (packed 1.0, 0.5, 0.0, 1.0) -v_mov_b32_e32 v20, 0x38003c00 -v_mov_b32_e32 v21, 0x3c000000 -s_mov_b32 s6, 0xffffffff -s_mov_b32 s7, 0x31016fac -v_mov_b32_e32 v5, 0x280 -tbuffer_store_format_d16_xyzw v[20:21], v5, s[4:7], 0 format:[BUF_FMT_8_8_8_8_UNORM] offen -; 0x290: tbuffer_store_format_xy, xy, 32_32_32_32_FLOAT, NR 0x298 over a V# that says 32_FLOAT: x, y end at 0x298, the element at 0x2a0 -v_mov_b32_e32 v20, 0x3f800000 -v_mov_b32_e32 v21, 0x40000000 -s_mov_b32 s6, 0x298 -s_mov_b32 s7, 0x31016fac -v_mov_b32_e32 v5, 0x290 -tbuffer_store_format_xy v[20:21], v5, s[4:7], 0 format:[BUF_FMT_32_32_32_32_FLOAT] offen -; 0x2a0: tbuffer_store_format_x, x, 8_UNORM, NR 0x2a1 over a V# that says 32_32_32_32_FLOAT: the byte fits, the V#'s element would not -v_mov_b32_e32 v20, 0x3f800000 -s_mov_b32 s6, 0x2a1 -s_mov_b32 s7, 0x3104dfac -v_mov_b32_e32 v5, 0x2a0 -tbuffer_store_format_x v20, v5, s[4:7], 0 format:[BUF_FMT_8_UNORM] offen -; 0x2b0: tbuffer_store_format_xyzw, xyzw into 32_FLOAT (one channel) over a V# that says 32_32_32_32_FLOAT: only x -v_mov_b32_e32 v20, 0x3f800000 -v_mov_b32_e32 v21, 0x40000000 -v_mov_b32_e32 v22, 0x40400000 -v_mov_b32_e32 v23, 0x40800000 -s_mov_b32 s6, 0xffffffff -s_mov_b32 s7, 0x3104dfac -v_mov_b32_e32 v5, 0x2b0 -tbuffer_store_format_xyzw v[20:23], v5, s[4:7], 0 format:[BUF_FMT_32_FLOAT] offen -; 0x2c0: tbuffer_store_format_xy, xy, 32_32_FLOAT over a V# whose FORMAT is 0 (INVALID): nothing -v_mov_b32_e32 v20, 0x3f800000 -v_mov_b32_e32 v21, 0x40000000 -s_mov_b32 s6, 0xffffffff -s_mov_b32 s7, 0x31000fac -v_mov_b32_e32 v5, 0x2c0 -tbuffer_store_format_xy v[20:21], v5, s[4:7], 0 format:[BUF_FMT_32_32_FLOAT] offen -s_waitcnt_vscnt null, 0x0 -; out[0..3]: the 16 bytes at 0x200 -v_mov_b32_e32 v5, 0x200 -buffer_load_dwordx4 v[10:13], v5, s[0:3], 0 offen -s_waitcnt vmcnt(0) -v_mov_b32_e32 v6, 0x0 -buffer_store_dwordx4 v[10:13], v6, s[0:3], 0 offen -; out[4..7]: the 16 bytes at 0x210 -v_mov_b32_e32 v5, 0x210 -buffer_load_dwordx4 v[10:13], v5, s[0:3], 0 offen -s_waitcnt vmcnt(0) -v_mov_b32_e32 v6, 0x10 -buffer_store_dwordx4 v[10:13], v6, s[0:3], 0 offen -; out[8..11]: the 16 bytes at 0x220 -v_mov_b32_e32 v5, 0x220 -buffer_load_dwordx4 v[10:13], v5, s[0:3], 0 offen -s_waitcnt vmcnt(0) -v_mov_b32_e32 v6, 0x20 -buffer_store_dwordx4 v[10:13], v6, s[0:3], 0 offen -; out[12..15]: the 16 bytes at 0x230 -v_mov_b32_e32 v5, 0x230 -buffer_load_dwordx4 v[10:13], v5, s[0:3], 0 offen -s_waitcnt vmcnt(0) -v_mov_b32_e32 v6, 0x30 -buffer_store_dwordx4 v[10:13], v6, s[0:3], 0 offen -; out[16..19]: the 16 bytes at 0x240 -v_mov_b32_e32 v5, 0x240 -buffer_load_dwordx4 v[10:13], v5, s[0:3], 0 offen -s_waitcnt vmcnt(0) -v_mov_b32_e32 v6, 0x40 -buffer_store_dwordx4 v[10:13], v6, s[0:3], 0 offen -; out[20..23]: the 16 bytes at 0x250 -v_mov_b32_e32 v5, 0x250 -buffer_load_dwordx4 v[10:13], v5, s[0:3], 0 offen -s_waitcnt vmcnt(0) -v_mov_b32_e32 v6, 0x50 -buffer_store_dwordx4 v[10:13], v6, s[0:3], 0 offen -; out[24..27]: the 16 bytes at 0x260 -v_mov_b32_e32 v5, 0x260 -buffer_load_dwordx4 v[10:13], v5, s[0:3], 0 offen -s_waitcnt vmcnt(0) -v_mov_b32_e32 v6, 0x60 -buffer_store_dwordx4 v[10:13], v6, s[0:3], 0 offen -; out[28..31]: the 16 bytes at 0x270 -v_mov_b32_e32 v5, 0x270 -buffer_load_dwordx4 v[10:13], v5, s[0:3], 0 offen -s_waitcnt vmcnt(0) -v_mov_b32_e32 v6, 0x70 -buffer_store_dwordx4 v[10:13], v6, s[0:3], 0 offen -; out[32..35]: the 16 bytes at 0x280 -v_mov_b32_e32 v5, 0x280 -buffer_load_dwordx4 v[10:13], v5, s[0:3], 0 offen -s_waitcnt vmcnt(0) -v_mov_b32_e32 v6, 0x80 -buffer_store_dwordx4 v[10:13], v6, s[0:3], 0 offen -; out[36..39]: the 16 bytes at 0x290 -v_mov_b32_e32 v5, 0x290 -buffer_load_dwordx4 v[10:13], v5, s[0:3], 0 offen -s_waitcnt vmcnt(0) -v_mov_b32_e32 v6, 0x90 -buffer_store_dwordx4 v[10:13], v6, s[0:3], 0 offen -; out[40..43]: the 16 bytes at 0x2a0 -v_mov_b32_e32 v5, 0x2a0 -buffer_load_dwordx4 v[10:13], v5, s[0:3], 0 offen -s_waitcnt vmcnt(0) -v_mov_b32_e32 v6, 0xa0 -buffer_store_dwordx4 v[10:13], v6, s[0:3], 0 offen -; out[44..47]: the 16 bytes at 0x2b0 -v_mov_b32_e32 v5, 0x2b0 -buffer_load_dwordx4 v[10:13], v5, s[0:3], 0 offen -s_waitcnt vmcnt(0) -v_mov_b32_e32 v6, 0xb0 -buffer_store_dwordx4 v[10:13], v6, s[0:3], 0 offen -; out[48..51]: the 16 bytes at 0x2c0 -v_mov_b32_e32 v5, 0x2c0 -buffer_load_dwordx4 v[10:13], v5, s[0:3], 0 offen -s_waitcnt vmcnt(0) -v_mov_b32_e32 v6, 0xc0 -buffer_store_dwordx4 v[10:13], v6, s[0:3], 0 offen -s_endpgm diff --git a/runtime/test/shaders/cs_user_sgprs.asm b/runtime/test/shaders/cs_user_sgprs.asm deleted file mode 100644 index 20f85857b..000000000 --- a/runtime/test/shaders/cs_user_sgprs.asm +++ /dev/null @@ -1,14 +0,0 @@ -; group: 1,1,1 -; rsrc2: 0x8090 -; Eight user SGPRs: s[0:3] are the output V#, s4..s7 are input words seeded by vk_compute_test's VKC_SGPRS (both -; runners pass 0x4f000000,0xdeadbeef,7,0xffffffff). One thread stores them back, so a compute test can read an -; input word (#300's cs_cvt_f32_sat takes its float in s4). Without VKC_SGPRS they read 0. -; Run: VKC_SGPRS=0x4f000000,0xdeadbeef,7,0xffffffff vk_compute_test cs_user_sgprs.spv 1 dump -; out[0..7] = 4F000000 DEADBEEF 00000007 FFFFFFFF EEEEEEEE EEEEEEEE EEEEEEEE EEEEEEEE (hex) -v_mov_b32_e32 v1, 0 -v_mov_b32_e32 v2, s4 -v_mov_b32_e32 v3, s5 -v_mov_b32_e32 v4, s6 -v_mov_b32_e32 v5, s7 -buffer_store_dwordx4 v[2:5], v1, s[0:3], 0 offen -s_endpgm diff --git a/runtime/test/shaders/cs_w32_andn2_exec.asm b/runtime/test/shaders/cs_w32_andn2_exec.asm deleted file mode 100644 index 3b723df73..000000000 --- a/runtime/test/shaders/cs_w32_andn2_exec.asm +++ /dev/null @@ -1,82 +0,0 @@ -; regen_fixtures: this source has a translator fixture in tests/semantic/fixtures/disasm -; s_andn2_saveexec_b32 and s_andn2_wrexec_b32 in a 32-thread wave32 (v0 = lane 0..31). Neither had a test. -; RDNA2 ISA: s_andn2_saveexec_b32: D = EXEC; EXEC = S0 & ~EXEC; SCC = (EXEC != 0) -; s_andn2_wrexec_b32: EXEC = S0 & ~EXEC; D = EXEC; SCC = (EXEC != 0) (D gets the new EXEC) -; S0 is a compare result in VCC, written with all 32 lanes on. The masks are only looked at through mask-aware -; instructions (s_bcnt1, s_ff1, EXEC writes), not read as data. -; 1) VCC = lanes with bit 3 clear = 0x00ff00ff; EXEC = 0x0000ffff. saveexec: D = 0x0000ffff, -; EXEC = 0x00ff00ff & 0xffff0000 = 0x00ff0000 (lanes 16..23), SCC 1. -; out[0] = s_cselect 1/2 = 1; out[1] = s_bcnt1(EXEC) = 8; out[2] = s_bcnt1(EXEC after EXEC = D) = 16; -; v1 = 1 under the new EXEC only, so the lanes with v1 != 0 are 16..23: out[3] = bcnt << 8 | ff1 = 8 << 8 | 16 = 2064. -; 2) VCC = lanes 16..31 = 0xffff0000; EXEC = 0x0f0f0f0f. wrexec: EXEC = 0xffff0000 & 0xf0f0f0f0 = 0xf0f00000 -; (lanes 20-23, 28-31), D = 0xf0f00000, SCC 1. -; out[4] = bcnt << 8 | ff1 of EXEC = 8 << 8 | 20 = 2068; out[5] = s_cselect 3/4 = 3; -; out[6] = s_ff1(D) = 20 (D = the old EXEC 0x0f0f0f0f would give 0). -; 3) VCC = lanes 0..7. EXEC = 0x0000ffff, saveexec: EXEC = 0x000000ff & 0xffff0000 = 0, SCC 0 -> s_cselect 5/6 = 6; -; EXEC = -1, wrexec: EXEC = 0x000000ff & 0 = 0, SCC 0 -> s_cselect 7/8 = 8. out[7] = 6 << 8 | 8 = 1544. -; Lane 0 stores the eight words. -; group: 32,1,1 -; Run: VKC_SUBGROUP_SIZE=32 vk_compute_test cs_w32_andn2_exec.spv 1 dump -> out[0..7] = 1 8 16 2064 2068 3 20 1544 -; mattr: +wavefrontsize32,-wavefrontsize64 -v_mov_b32_e32 v1, 0 -v_and_b32_e32 v2, 8, v0 -v_cmp_eq_u32_e32 vcc_lo, 0, v2 -s_mov_b32 exec_lo, 0xffff -s_andn2_saveexec_b32 s7, vcc_lo -s_cselect_b32 s8, 1, 2 -s_bcnt1_i32_b32 s9, exec_lo -v_mov_b32_e32 v1, 1 -s_mov_b32 exec_lo, s7 -s_bcnt1_i32_b32 s10, exec_lo -s_mov_b32 exec_lo, -1 -v_cmp_ne_u32_e32 vcc_lo, 0, v1 -s_bcnt1_i32_b32 s11, vcc_lo -s_ff1_i32_b32 s12, vcc_lo -s_lshl_b32 s11, s11, 8 -s_or_b32 s11, s11, s12 -v_cmp_le_u32_e32 vcc_lo, 16, v0 -s_mov_b32 exec_lo, 0xf0f0f0f -s_andn2_wrexec_b32 s13, vcc_lo -s_cselect_b32 s14, 3, 4 -s_bcnt1_i32_b32 s15, exec_lo -s_ff1_i32_b32 s16, exec_lo -s_lshl_b32 s15, s15, 8 -s_or_b32 s15, s15, s16 -s_mov_b32 exec_lo, -1 -s_ff1_i32_b32 s17, s13 -v_cmp_gt_u32_e32 vcc_lo, 8, v0 -s_mov_b32 exec_lo, 0xffff -s_andn2_saveexec_b32 s18, vcc_lo -s_cselect_b32 s19, 5, 6 -s_mov_b32 exec_lo, -1 -s_andn2_wrexec_b32 s20, vcc_lo -s_cselect_b32 s21, 7, 8 -s_mov_b32 exec_lo, -1 -s_lshl_b32 s19, s19, 8 -s_or_b32 s19, s19, s21 -v_cmpx_eq_u32_e32 0, v0 -v_mov_b32_e32 v20, s8 -v_mov_b32_e32 v21, 0 -buffer_store_dword v20, v21, s[0:3], 0 offen -v_mov_b32_e32 v20, s9 -v_mov_b32_e32 v21, 4 -buffer_store_dword v20, v21, s[0:3], 0 offen -v_mov_b32_e32 v20, s10 -v_mov_b32_e32 v21, 8 -buffer_store_dword v20, v21, s[0:3], 0 offen -v_mov_b32_e32 v20, s11 -v_mov_b32_e32 v21, 12 -buffer_store_dword v20, v21, s[0:3], 0 offen -v_mov_b32_e32 v20, s15 -v_mov_b32_e32 v21, 16 -buffer_store_dword v20, v21, s[0:3], 0 offen -v_mov_b32_e32 v20, s14 -v_mov_b32_e32 v21, 20 -buffer_store_dword v20, v21, s[0:3], 0 offen -v_mov_b32_e32 v20, s17 -v_mov_b32_e32 v21, 24 -buffer_store_dword v20, v21, s[0:3], 0 offen -v_mov_b32_e32 v20, s19 -v_mov_b32_e32 v21, 28 -buffer_store_dword v20, v21, s[0:3], 0 offen -s_endpgm diff --git a/runtime/test/shaders/cs_w32_buffer_store_sub.asm b/runtime/test/shaders/cs_w32_buffer_store_sub.asm deleted file mode 100644 index 83be61fad..000000000 --- a/runtime/test/shaders/cs_w32_buffer_store_sub.asm +++ /dev/null @@ -1,87 +0,0 @@ -; regen_fixtures: this source has a translator fixture in tests/semantic/fixtures/disasm -; Plain 8/16-bit MUBUF stores (#1864): buffer_store_byte / buffer_store_short, the forms docs/embedded_shaders.md names -; as Box16Rehydration's blocker (cs_w32_buffer_sub16 covers the d16 forms; @YaBulochka on #1864). On the output V# -; (base 0, num_records 0xFFFFFFFF) lane 0 seeds dwords 0x40..0x54, stores into them and reads them back. A store writes -; only its own bytes; a short at byte 3 of a dword writes its high byte into the next one. Eight dwords: -; out[0] = dword 0x40 (0x11223344) after buffer_store_byte 0xAB to byte 0x41 = 0x1122AB44 -; out[1] = dword 0x44 (0x55667788) after buffer_store_short 0xCDEF to byte 0x46 = 0xCDEF7788 -; out[2] = dword 0x48 (0x99AABBCC) after buffer_store_short 0x1234 to byte 0x4B: its low byte = 0x34AABBCC -; out[3] = dword 0x4C (0xDDDDDDDD) after the same store: the high byte crossed into byte 0x4C = 0xDDDDDD12 -; out[4] = dword 0x50 (0x01020304) after buffer_store_byte of 0xFFFFFF5A to byte 0x50 (low byte) = 0x0102035A -; out[5] = dword 0x54 (0x05060708) after buffer_store_short of 0xABCD1234 to byte 0x54 (low half) = 0x05061234 -; out[6] = buffer_load_ubyte of byte 0x41 afterwards = 0x000000AB -; out[7] = buffer_load_sshort of bytes 0x46..0x47 afterwards (0xCDEF, sign-extended) = 0xFFFFCDEF -; EXEC is cut to lane 0 first (one address per op). -; group: 32,1,1 -; Run: vk_compute_test cs_w32_buffer_store_sub.spv 1 dump -> out[0..7] = 287484740 3455022984 883604428 3722304786 16909146 84283956 171 4294954479 -; mattr: +wavefrontsize32,-wavefrontsize64 -v_cmpx_eq_u32_e32 0, v0 -v_mov_b32_e32 v20, 0x40 -v_mov_b32_e32 v21, 0x11223344 -buffer_store_dword v21, v20, s[0:3], 0 offen -v_mov_b32_e32 v20, 0x44 -v_mov_b32_e32 v21, 0x55667788 -buffer_store_dword v21, v20, s[0:3], 0 offen -v_mov_b32_e32 v20, 0x48 -v_mov_b32_e32 v21, 0x99aabbcc -buffer_store_dword v21, v20, s[0:3], 0 offen -v_mov_b32_e32 v20, 0x4c -v_mov_b32_e32 v21, 0xdddddddd -buffer_store_dword v21, v20, s[0:3], 0 offen -v_mov_b32_e32 v20, 0x50 -v_mov_b32_e32 v21, 0x1020304 -buffer_store_dword v21, v20, s[0:3], 0 offen -v_mov_b32_e32 v20, 0x54 -v_mov_b32_e32 v21, 0x5060708 -buffer_store_dword v21, v20, s[0:3], 0 offen -s_waitcnt_vscnt null, 0 -v_mov_b32_e32 v20, 0x41 -v_mov_b32_e32 v21, 0xab -buffer_store_byte v21, v20, s[0:3], 0 offen -v_mov_b32_e32 v20, 0x46 -v_mov_b32_e32 v21, 0xcdef -buffer_store_short v21, v20, s[0:3], 0 offen -v_mov_b32_e32 v20, 0x4b -v_mov_b32_e32 v21, 0x1234 -buffer_store_short v21, v20, s[0:3], 0 offen -v_mov_b32_e32 v20, 0x50 -v_mov_b32_e32 v21, 0xffffff5a -buffer_store_byte v21, v20, s[0:3], 0 offen -v_mov_b32_e32 v20, 0x54 -v_mov_b32_e32 v21, 0xabcd1234 -buffer_store_short v21, v20, s[0:3], 0 offen -s_waitcnt_vscnt null, 0 -v_mov_b32_e32 v20, 0x40 -buffer_load_dword v10, v20, s[0:3], 0 offen -v_mov_b32_e32 v20, 0x44 -buffer_load_dword v11, v20, s[0:3], 0 offen -v_mov_b32_e32 v20, 0x48 -buffer_load_dword v12, v20, s[0:3], 0 offen -v_mov_b32_e32 v20, 0x4c -buffer_load_dword v13, v20, s[0:3], 0 offen -v_mov_b32_e32 v20, 0x50 -buffer_load_dword v14, v20, s[0:3], 0 offen -v_mov_b32_e32 v20, 0x54 -buffer_load_dword v15, v20, s[0:3], 0 offen -v_mov_b32_e32 v20, 0x41 -buffer_load_ubyte v16, v20, s[0:3], 0 offen -v_mov_b32_e32 v20, 0x46 -buffer_load_sshort v17, v20, s[0:3], 0 offen -s_waitcnt vmcnt(0) -v_mov_b32_e32 v20, 0 -buffer_store_dword v10, v20, s[0:3], 0 offen -v_mov_b32_e32 v20, 4 -buffer_store_dword v11, v20, s[0:3], 0 offen -v_mov_b32_e32 v20, 8 -buffer_store_dword v12, v20, s[0:3], 0 offen -v_mov_b32_e32 v20, 12 -buffer_store_dword v13, v20, s[0:3], 0 offen -v_mov_b32_e32 v20, 16 -buffer_store_dword v14, v20, s[0:3], 0 offen -v_mov_b32_e32 v20, 20 -buffer_store_dword v15, v20, s[0:3], 0 offen -v_mov_b32_e32 v20, 24 -buffer_store_dword v16, v20, s[0:3], 0 offen -v_mov_b32_e32 v20, 28 -buffer_store_dword v17, v20, s[0:3], 0 offen -s_endpgm diff --git a/runtime/test/shaders/cs_w32_buffer_sub16.asm b/runtime/test/shaders/cs_w32_buffer_sub16.asm deleted file mode 100644 index bb1c7d43b..000000000 --- a/runtime/test/shaders/cs_w32_buffer_sub16.asm +++ /dev/null @@ -1,71 +0,0 @@ -; regen_fixtures: this source has a translator fixture in tests/semantic/fixtures/disasm -; 8/16-bit MUBUF d16 loads and stores (#1864, BUFFER_SUB16), on the output V# (base 0, num_records 0xFFFFFFFF). Lane 0 -; seeds dword 0x40 = 0x8899AABB, 0x50 = 0x11223344, 0x60 = 0x55667788, and loads into a register holding 0xBEEF1234, so -; each d16 load shows the half it writes and the half it keeps. Eight dwords: -; out[0] = buffer_load_ubyte_d16 of byte 0x41 (0xAA): low half 0x00AA, high kept = 0xBEEF00AA -; out[1] = buffer_load_ubyte_d16_hi of byte 0x41: high half 0x00AA, low kept = 0x00AA1234 -; out[2] = buffer_load_sbyte_d16 of byte 0x41: 0xAA sign-extended to 16 bits = 0xBEEFFFAA -; out[3] = buffer_load_sbyte_d16_hi of byte 0x41 = 0xFFAA1234 -; out[4] = buffer_load_short_d16 of bytes 0x42..0x43 (0x8899) = 0xBEEF8899 -; out[5] = buffer_load_short_d16_hi of bytes 0x42..0x43 = 0x88991234 -; out[6] = dword 0x50 after buffer_store_byte_d16_hi of 0x00CD0000 to byte 0x51: bits 23:16 = 0x1122CD44 -; out[7] = dword 0x60 after buffer_store_short_d16_hi of 0xABCD0000 to byte 0x62: bits 31:16 = 0xABCD7788 -; EXEC is cut to lane 0 first (one address per op). -; group: 32,1,1 -; Run: vk_compute_test cs_w32_buffer_sub16.spv 1 dump -> out[0..7] = 3203334314 11145780 3203399594 4289335860 3203369113 2291733044 287493444 2882369416 -; mattr: +wavefrontsize32,-wavefrontsize64 -v_cmpx_eq_u32_e32 0, v0 -v_mov_b32_e32 v20, 0x40 -v_mov_b32_e32 v21, 0x8899aabb -buffer_store_dword v21, v20, s[0:3], 0 offen -v_mov_b32_e32 v20, 0x50 -v_mov_b32_e32 v21, 0x11223344 -buffer_store_dword v21, v20, s[0:3], 0 offen -v_mov_b32_e32 v20, 0x60 -v_mov_b32_e32 v21, 0x55667788 -buffer_store_dword v21, v20, s[0:3], 0 offen -s_waitcnt_vscnt null, 0 -v_mov_b32_e32 v1, 0x41 -v_mov_b32_e32 v2, 0x42 -v_mov_b32_e32 v10, 0xbeef1234 -v_mov_b32_e32 v11, 0xbeef1234 -v_mov_b32_e32 v12, 0xbeef1234 -v_mov_b32_e32 v13, 0xbeef1234 -v_mov_b32_e32 v14, 0xbeef1234 -v_mov_b32_e32 v15, 0xbeef1234 -buffer_load_ubyte_d16 v10, v1, s[0:3], 0 offen -buffer_load_ubyte_d16_hi v11, v1, s[0:3], 0 offen -buffer_load_sbyte_d16 v12, v1, s[0:3], 0 offen -buffer_load_sbyte_d16_hi v13, v1, s[0:3], 0 offen -buffer_load_short_d16 v14, v2, s[0:3], 0 offen -buffer_load_short_d16_hi v15, v2, s[0:3], 0 offen -v_mov_b32_e32 v20, 0x51 -v_mov_b32_e32 v21, 0xcd0000 -buffer_store_byte_d16_hi v21, v20, s[0:3], 0 offen -v_mov_b32_e32 v20, 0x62 -v_mov_b32_e32 v21, 0xabcd0000 -buffer_store_short_d16_hi v21, v20, s[0:3], 0 offen -s_waitcnt vmcnt(0) -s_waitcnt_vscnt null, 0 -v_mov_b32_e32 v20, 0x50 -buffer_load_dword v16, v20, s[0:3], 0 offen -v_mov_b32_e32 v20, 0x60 -buffer_load_dword v17, v20, s[0:3], 0 offen -s_waitcnt vmcnt(0) -v_mov_b32_e32 v20, 0 -buffer_store_dword v10, v20, s[0:3], 0 offen -v_mov_b32_e32 v20, 4 -buffer_store_dword v11, v20, s[0:3], 0 offen -v_mov_b32_e32 v20, 8 -buffer_store_dword v12, v20, s[0:3], 0 offen -v_mov_b32_e32 v20, 12 -buffer_store_dword v13, v20, s[0:3], 0 offen -v_mov_b32_e32 v20, 16 -buffer_store_dword v14, v20, s[0:3], 0 offen -v_mov_b32_e32 v20, 20 -buffer_store_dword v15, v20, s[0:3], 0 offen -v_mov_b32_e32 v20, 24 -buffer_store_dword v16, v20, s[0:3], 0 offen -v_mov_b32_e32 v20, 28 -buffer_store_dword v17, v20, s[0:3], 0 offen -s_endpgm diff --git a/runtime/test/shaders/cs_w32_ds_append.asm b/runtime/test/shaders/cs_w32_ds_append.asm deleted file mode 100644 index a6a2b1026..000000000 --- a/runtime/test/shaders/cs_w32_ds_append.asm +++ /dev/null @@ -1,64 +0,0 @@ -; regen_fixtures: this source has a translator fixture in tests/semantic/fixtures/disasm -; ds_append / ds_consume (LDS): one add (append) or subtract (consume) of the number of lanes on in EXEC, for the whole -; wave, at the byte address in the offset field; every active lane gets the value before the op, inactive lanes keep -; vD. Measured natively on RDNA2 gfx1036 (tools/hw_oracle raw kernels): EXEC 0xf0 appends 4 and returns the old 100 -; to lanes 4-7 only; M0 (0x4, 0x100, 0x10000, 0x40000, 0x80000) does not move the address. Until this change both -; raised Unsupported. -; LDS words: [0] = 100, [2] (byte 8) = 200, written by every lane first. -; EXEC = 0xf0f0 (8 lanes): ds_append v8 -> v8 = 100 in lanes 4-7, 12-15; LDS[0] = 108 -; EXEC = 0x7 (3 lanes): ds_consume v9 offset:8 -> v9 = 200 in lanes 0-2; LDS[2] = 197 -; EXEC = all (32 lanes): ds_append v10 -> v10 = 108 everywhere; LDS[0] = 140 -; Lane 0 stores: -; out[0] v8 of lane 4 = 100 out[1] v8 of lane 0 (off) = 0xdead out[2] v9 of lane 2 = 200 -; out[3] v9 of lane 3 (off) = 0xdead out[4] LDS[0] read by lane 4 after its append = 108 -; out[5] LDS[2] read by lane 0 after its consume = 197 out[6] v10 of lane 31 = 108 out[7] LDS[0] = 140 -; Done once per lane instead of once per wave, the first append alone would leave 100 + 8 * 8. -; rsrc2: 0x40088 -; group: 32,1,1 -; Run: vk_compute_test cs_w32_ds_append.spv 1 dump -> out[0..7] = 100 57005 200 57005 108 197 108 140 -; mattr: +wavefrontsize32,-wavefrontsize64 -v_mov_b32_e32 v8, 0xdead -v_mov_b32_e32 v9, 0xdead -v_mov_b32_e32 v1, 0 -v_mov_b32_e32 v2, 100 -v_mov_b32_e32 v3, 200 -ds_write_b32 v1, v2 -ds_write_b32 v1, v3 offset:8 -s_waitcnt lgkmcnt(0) -s_mov_b32 exec_lo, 0xf0f0 -ds_append v8 -s_waitcnt lgkmcnt(0) -ds_read_b32 v11, v1 -s_waitcnt lgkmcnt(0) -s_mov_b32 exec_lo, 7 -ds_consume v9 offset:8 -s_waitcnt lgkmcnt(0) -ds_read_b32 v12, v1 offset:8 -s_waitcnt lgkmcnt(0) -s_mov_b32 exec_lo, -1 -ds_append v10 -s_waitcnt lgkmcnt(0) -ds_read_b32 v13, v1 -s_waitcnt lgkmcnt(0) -v_readlane_b32 s20, v8, 4 -v_readlane_b32 s21, v8, 0 -v_readlane_b32 s22, v9, 2 -v_readlane_b32 s23, v9, 3 -v_readlane_b32 s24, v11, 4 -v_readlane_b32 s25, v12, 0 -v_readlane_b32 s26, v10, 31 -v_readlane_b32 s27, v13, 0 -v_mov_b32_e32 v14, s20 -v_mov_b32_e32 v15, s21 -v_mov_b32_e32 v16, s22 -v_mov_b32_e32 v17, s23 -v_mov_b32_e32 v18, s24 -v_mov_b32_e32 v19, s25 -v_mov_b32_e32 v20, s26 -v_mov_b32_e32 v21, s27 -v_cmpx_eq_u32_e32 0, v0 -v_mov_b32_e32 v22, 0 -buffer_store_dwordx4 v[14:17], v22, s[0:3], 0 offen -v_mov_b32_e32 v22, 16 -buffer_store_dwordx4 v[18:21], v22, s[0:3], 0 offen -s_endpgm diff --git a/runtime/test/shaders/cs_w32_exec_computed.asm b/runtime/test/shaders/cs_w32_exec_computed.asm deleted file mode 100644 index a13717573..000000000 --- a/runtime/test/shaders/cs_w32_exec_computed.asm +++ /dev/null @@ -1,108 +0,0 @@ -; regen_fixtures: this source has a translator fixture in tests/semantic/fixtures/disasm -; SHADER-1264: a computed 32-bit value written to exec_lo in a 32-thread wave32 (v0 = lane 0..31) turns on exactly -; the lanes whose bit is set, like a constant does (cs_exec_const.asm). It is a plain number, not a lane mask, so -; testing it for non-zero turns on every lane. The base value comes from v_readfirstlane_b32 (s4 = lane 0's v0 = 0), -; so the translator can't fold the writes into constants. For each case a VALU write marks the lanes that ran it; -; with EXEC = -1 again, a v_cmp turns the marks into a lane mask and the word is s_bcnt1 << 8 | s_ff1. -; 1) s5 = s4 + 3; s_lshl_b32 exec_lo, 1, s5 = 0x00000008: lane 3. out[0] = 1 << 8 | 3 = 259 -; 2) s_add_u32 exec_lo, s4, 0xf0 = 0x000000f0: lanes 4..7. out[1] = 4 << 8 | 4 = 1028 -; 3) s_bfm_b32 exec_lo, s6 = 12, s7 = 16 = 0x0fff0000: lanes 16..27. out[2] = 12 << 8 | 16 = 3088 -; 4) s_not_b32 exec_lo, s5 = ~3 = 0xfffffffc: lanes 2..31. out[3] = 30 << 8 | 2 = 7682 -; 5) s_mov_b32 exec_lo, s9 with s9 = s4 + 0x81 (a number, not a mask): lanes 0, 7. out[4] = 2 << 8 | 0 = 512 -; 6) a lane mask AND a number: VCC = lanes 0..19 (0x000fffff), s8 = s4 + 0xffff0; -; s_and_b32 exec_lo, vcc_lo, s8 = 0x000ffff0: lanes 4..19. out[5] = 16 << 8 | 4 = 4100 -; out[6] = s4 = 0 and out[7] = s5 = 3 check the base values. -; Testing the value for non-zero instead (main before SHADER-1264) runs all 32 lanes in 1-3: 8192 8192 8192 -; (measured on an RTX 5070). Cases 4-6 were right before the fix (s_not_b32, a plain s_mov_b32 and s_and_b32 with a -; lane mask take other paths); they check that a fix keeps them right. -; Lane 0 stores the eight words. -; group: 32,1,1 -; Run: VKC_SUBGROUP_SIZE=32 vk_compute_test cs_w32_exec_computed.spv 1 dump -> out[0..7] = 259 1028 3088 7682 512 4100 0 3 -; mattr: +wavefrontsize32,-wavefrontsize64 -v_mov_b32_e32 v10, 0 -v_mov_b32_e32 v11, 0 -v_mov_b32_e32 v12, 0 -v_mov_b32_e32 v13, 0 -v_mov_b32_e32 v14, 0 -v_mov_b32_e32 v15, 0 -v_readfirstlane_b32 s4, v0 -s_add_u32 s5, s4, 3 -s_add_u32 s6, s4, 12 -s_add_u32 s7, s4, 16 -s_add_u32 s8, s4, 0xffff0 -s_add_u32 s9, s4, 0x81 -s_lshl_b32 exec_lo, 1, s5 -v_mov_b32_e32 v10, 1 -s_mov_b32 exec_lo, -1 -s_add_u32 exec_lo, s4, 0xf0 -v_mov_b32_e32 v11, 1 -s_mov_b32 exec_lo, -1 -s_bfm_b32 exec_lo, s6, s7 -v_mov_b32_e32 v12, 1 -s_mov_b32 exec_lo, -1 -s_not_b32 exec_lo, s5 -v_mov_b32_e32 v13, 1 -s_mov_b32 exec_lo, -1 -s_mov_b32 exec_lo, s9 -v_mov_b32_e32 v14, 1 -s_mov_b32 exec_lo, -1 -v_cmp_gt_u32_e32 vcc_lo, 20, v0 -s_and_b32 exec_lo, vcc_lo, s8 -v_mov_b32_e32 v15, 1 -s_mov_b32 exec_lo, -1 -v_cmp_ne_u32_e32 vcc_lo, 0, v10 -s_bcnt1_i32_b32 s10, vcc_lo -s_ff1_i32_b32 s11, vcc_lo -s_lshl_b32 s10, s10, 8 -s_or_b32 s10, s10, s11 -v_cmp_ne_u32_e32 vcc_lo, 0, v11 -s_bcnt1_i32_b32 s12, vcc_lo -s_ff1_i32_b32 s11, vcc_lo -s_lshl_b32 s12, s12, 8 -s_or_b32 s12, s12, s11 -v_cmp_ne_u32_e32 vcc_lo, 0, v12 -s_bcnt1_i32_b32 s13, vcc_lo -s_ff1_i32_b32 s11, vcc_lo -s_lshl_b32 s13, s13, 8 -s_or_b32 s13, s13, s11 -v_cmp_ne_u32_e32 vcc_lo, 0, v13 -s_bcnt1_i32_b32 s14, vcc_lo -s_ff1_i32_b32 s11, vcc_lo -s_lshl_b32 s14, s14, 8 -s_or_b32 s14, s14, s11 -v_cmp_ne_u32_e32 vcc_lo, 0, v14 -s_bcnt1_i32_b32 s15, vcc_lo -s_ff1_i32_b32 s11, vcc_lo -s_lshl_b32 s15, s15, 8 -s_or_b32 s15, s15, s11 -v_cmp_ne_u32_e32 vcc_lo, 0, v15 -s_bcnt1_i32_b32 s16, vcc_lo -s_ff1_i32_b32 s11, vcc_lo -s_lshl_b32 s16, s16, 8 -s_or_b32 s16, s16, s11 -v_cmpx_eq_u32_e32 0, v0 -v_mov_b32_e32 v20, s10 -v_mov_b32_e32 v21, 0 -buffer_store_dword v20, v21, s[0:3], 0 offen -v_mov_b32_e32 v20, s12 -v_mov_b32_e32 v21, 4 -buffer_store_dword v20, v21, s[0:3], 0 offen -v_mov_b32_e32 v20, s13 -v_mov_b32_e32 v21, 8 -buffer_store_dword v20, v21, s[0:3], 0 offen -v_mov_b32_e32 v20, s14 -v_mov_b32_e32 v21, 12 -buffer_store_dword v20, v21, s[0:3], 0 offen -v_mov_b32_e32 v20, s15 -v_mov_b32_e32 v21, 16 -buffer_store_dword v20, v21, s[0:3], 0 offen -v_mov_b32_e32 v20, s16 -v_mov_b32_e32 v21, 20 -buffer_store_dword v20, v21, s[0:3], 0 offen -v_mov_b32_e32 v20, s4 -v_mov_b32_e32 v21, 24 -buffer_store_dword v20, v21, s[0:3], 0 offen -v_mov_b32_e32 v20, s5 -v_mov_b32_e32 v21, 28 -buffer_store_dword v20, v21, s[0:3], 0 offen -s_endpgm diff --git a/runtime/test/shaders/cs_w32_fcmpswap.asm b/runtime/test/shaders/cs_w32_fcmpswap.asm deleted file mode 100644 index 679925e4d..000000000 --- a/runtime/test/shaders/cs_w32_fcmpswap.asm +++ /dev/null @@ -1,85 +0,0 @@ -; regen_fixtures: this source has a translator fixture in tests/semantic/fixtures/disasm -; ds_cmpst_f32 / ds_cmpst_rtn_f32 and buffer_atomic_fcmpswap (#3153): a float compare, so -0 matches +0 and a NaN -; never matches, not even its own bits. Lane 0 of a wave32 group stores eight dwords: -; out[0] = ds_cmpst_rtn_f32 old value (LDS +0, CMP -0, DATA 1.0) = 0x00000000 -; out[1] = the LDS word after it: -0 == +0, so DATA is stored = 0x3F800000 -; out[2] = the LDS word after ds_cmpst_rtn_f32 (LDS NaN, CMP the same NaN, DATA 1.0) = 0x7FC00000 -; out[3] = the LDS word after ds_cmpst_f32 (LDS 1.0, CMP 2.0, DATA 3.0): no match = 0x3F800000 -; out[4] = buffer_atomic_fcmpswap glc old value (M -0 at byte 0x40, DATA 3.0, CMP +0) = 0x80000000 -; out[5] = the word at byte 0x40 after it: -0 == +0 = 0x40400000 -; out[6] = the word at byte 0x44 after fcmpswap (M 1.0, DATA 2.0, CMP 0x3F800001) = 0x3F800000 -; out[7] = buffer_atomic_fcmpswap glc old value (M NaN at byte 0x48, DATA 1.0, CMP NaN) = 0x7FC00000 -; The atomic words are seeded with buffer_store_dword first. EXEC is cut to lane 0 before any memory op (one address -; per op, #1850). -; group: 32,1,1 -; Run: vk_compute_test cs_w32_fcmpswap.spv 1 dump -> out[0..7] = 0 1065353216 2143289344 1065353216 2147483648 1077936128 1065353216 2143289344 -; mattr: +wavefrontsize32,-wavefrontsize64 -v_cmpx_eq_u32_e32 0, v0 -v_mov_b32_e32 v10, 0x40 -v_mov_b32_e32 v11, 0 -ds_write_b32 v10, v11 -s_waitcnt lgkmcnt(0) -v_mov_b32_e32 v12, 0x80000000 -v_mov_b32_e32 v13, 1.0 -ds_cmpst_rtn_f32 v14, v10, v12, v13 -s_waitcnt lgkmcnt(0) -ds_read_b32 v15, v10 -v_mov_b32_e32 v16, 0x80 -v_mov_b32_e32 v17, 0x7fc00000 -ds_write_b32 v16, v17 -s_waitcnt lgkmcnt(0) -ds_cmpst_rtn_f32 v18, v16, v17, v13 -s_waitcnt lgkmcnt(0) -ds_read_b32 v18, v16 -v_mov_b32_e32 v19, 0xc0 -ds_write_b32 v19, v13 -s_waitcnt lgkmcnt(0) -v_mov_b32_e32 v12, 2.0 -v_mov_b32_e32 v11, 0x40400000 -ds_cmpst_f32 v19, v12, v11 -s_waitcnt lgkmcnt(0) -ds_read_b32 v21, v19 -s_waitcnt lgkmcnt(0) -v_mov_b32_e32 v20, 0x40 -v_mov_b32_e32 v22, 0x80000000 -buffer_store_dword v22, v20, s[0:3], 0 offen -v_mov_b32_e32 v20, 0x44 -buffer_store_dword v13, v20, s[0:3], 0 offen -v_mov_b32_e32 v20, 0x48 -buffer_store_dword v17, v20, s[0:3], 0 offen -s_waitcnt_vscnt null, 0 -v_mov_b32_e32 v20, 0x40 -v_mov_b32_e32 v2, 0x40400000 -v_mov_b32_e32 v3, 0 -buffer_atomic_fcmpswap v[2:3], v20, s[0:3], 0 offen glc -v_mov_b32_e32 v20, 0x44 -v_mov_b32_e32 v4, 2.0 -v_mov_b32_e32 v5, 0x3f800001 -buffer_atomic_fcmpswap v[4:5], v20, s[0:3], 0 offen -v_mov_b32_e32 v20, 0x48 -v_mov_b32_e32 v6, 1.0 -v_mov_b32_e32 v7, 0x7fc00000 -buffer_atomic_fcmpswap v[6:7], v20, s[0:3], 0 offen glc -s_waitcnt vmcnt(0) -v_mov_b32_e32 v20, 0x40 -buffer_load_dword v8, v20, s[0:3], 0 offen glc -v_mov_b32_e32 v20, 0x44 -buffer_load_dword v9, v20, s[0:3], 0 offen glc -s_waitcnt vmcnt(0) -v_mov_b32_e32 v20, 0 -buffer_store_dword v14, v20, s[0:3], 0 offen -v_mov_b32_e32 v20, 4 -buffer_store_dword v15, v20, s[0:3], 0 offen -v_mov_b32_e32 v20, 8 -buffer_store_dword v18, v20, s[0:3], 0 offen -v_mov_b32_e32 v20, 12 -buffer_store_dword v21, v20, s[0:3], 0 offen -v_mov_b32_e32 v20, 16 -buffer_store_dword v2, v20, s[0:3], 0 offen -v_mov_b32_e32 v20, 20 -buffer_store_dword v8, v20, s[0:3], 0 offen -v_mov_b32_e32 v20, 24 -buffer_store_dword v9, v20, s[0:3], 0 offen -v_mov_b32_e32 v20, 28 -buffer_store_dword v6, v20, s[0:3], 0 offen -s_endpgm diff --git a/runtime/test/shaders/cs_w32_int_ext.asm b/runtime/test/shaders/cs_w32_int_ext.asm deleted file mode 100644 index b4fd287d3..000000000 --- a/runtime/test/shaders/cs_w32_int_ext.asm +++ /dev/null @@ -1,57 +0,0 @@ -; regen_fixtures: this source has a translator fixture in tests/semantic/fixtures/disasm -; Integer ops added with CPU-only checks (#445 #448 #449 #440 #544 #577), run once on a GPU. -; Lane 0 of a wave32 group computes one result per op and stores eight dwords: -; out[0] = s_absdiff_i32(0x7FFFFFFF, 0x80000000) = 1 (the 32-bit difference wraps to -1 first) -; out[1] = s_lshl2_add_u32(5, 7) = 27 ((5 << 2) + 7) -; out[2] = SCC of s_lshl1_add_u32(0x80000000, 0) = 1 (the bit shifted out of S0 is a carry) -; out[3] = s_pack_lh_b32_b16(0x11112222, 0x33334444) = 0x33332222 (S0 low half, S1 high half) -; out[4] = s_mul_hi_i32(0x80000000, 0x7FFFFFFF) = 0xC0000000 (-2^31 * (2^31-1), high word) -; out[5] = v_mul_hi_i32_i24(0x800000, 0x800000) = 0x4000 ((-2^23)^2 = 2^46, high word) -; out[6] = v_sad_u8(0x01020304, 0x04030201, 10) = 18 (10 + 3 + 1 + 1 + 3) -; out[7] = v_lerp_u8(0x10203040, 0x30405060, 0x01010101) = 0x20304050 (per byte (a + b + 1) >> 1) -; group: 32,1,1 -; Run: vk_compute_test cs_w32_int_ext.spv 1 dump -> out[0..7] = 1 27 1 858989090 3221225472 16384 18 540033104 -; mattr: +wavefrontsize32,-wavefrontsize64 -s_mov_b32 s6, 0x7fffffff -s_mov_b32 s7, 0x80000000 -s_absdiff_i32 s8, s6, s7 -s_mov_b32 s9, 5 -s_lshl2_add_u32 s9, s9, 7 -s_lshl1_add_u32 s10, s7, 0 -s_cselect_b32 s10, 1, 0 -s_mov_b32 s11, 0x11112222 -s_mov_b32 s12, 0x33334444 -s_pack_lh_b32_b16 s11, s11, s12 -s_mul_hi_i32 s12, s7, s6 -v_mov_b32_e32 v2, 0x800000 -v_mul_hi_i32_i24_e64 v3, v2, v2 -v_mov_b32_e32 v4, 0x1020304 -v_mov_b32_e32 v5, 0x4030201 -v_sad_u8 v4, v4, v5, 10 -v_mov_b32_e32 v5, 0x10203040 -v_mov_b32_e32 v6, 0x30405060 -v_mov_b32_e32 v7, 0x1010101 -v_lerp_u8 v5, v5, v6, v7 -v_cmpx_eq_u32_e32 0, v0 -v_mov_b32_e32 v20, s8 -v_mov_b32_e32 v21, 0 -buffer_store_dword v20, v21, s[0:3], 0 offen -v_mov_b32_e32 v20, s9 -v_mov_b32_e32 v21, 4 -buffer_store_dword v20, v21, s[0:3], 0 offen -v_mov_b32_e32 v20, s10 -v_mov_b32_e32 v21, 8 -buffer_store_dword v20, v21, s[0:3], 0 offen -v_mov_b32_e32 v20, s11 -v_mov_b32_e32 v21, 12 -buffer_store_dword v20, v21, s[0:3], 0 offen -v_mov_b32_e32 v20, s12 -v_mov_b32_e32 v21, 16 -buffer_store_dword v20, v21, s[0:3], 0 offen -v_mov_b32_e32 v21, 20 -buffer_store_dword v3, v21, s[0:3], 0 offen -v_mov_b32_e32 v21, 24 -buffer_store_dword v4, v21, s[0:3], 0 offen -v_mov_b32_e32 v21, 28 -buffer_store_dword v5, v21, s[0:3], 0 offen -s_endpgm diff --git a/runtime/test/shaders/cs_w32_lane_wrap.asm b/runtime/test/shaders/cs_w32_lane_wrap.asm deleted file mode 100644 index 8ad2c0523..000000000 --- a/runtime/test/shaders/cs_w32_lane_wrap.asm +++ /dev/null @@ -1,32 +0,0 @@ -; regen_fixtures: this source has a translator fixture in tests/semantic/fixtures/disasm -; SHADER-52: wave32 v_readlane_b32 / v_writelane_b32 mask the lane select with 31 (S1[4:0]), not 63. -; v0 = LocalInvocationId.x (0..31). v2 = 3 * lane + 1. -; readlane(v2, 40) must equal lane (40 & 31) = 8 -> 3*8+1 = 25. With & 63 the shuffle asks for lane 40 -; (outside a 32-wide subgroup) and fails. -; writelane 777 into lane 40 lands on lane 8; readlane of 8 and of 40 both return 777. -; Lane 0 stores: out[0]=25 out[1]=16 (readlane 5) out[2]=777 out[3]=777. -; group: 32,1,1 -; Run: vk_compute_test cs_w32_lane_wrap.spv 1 dump -> out[0..3] = 25 16 777 777 -; mattr: +wavefrontsize32,-wavefrontsize64 -v_mad_u32_u24 v2, v0, 3, 1 -v_readlane_b32 s6, v2, 40 -v_readlane_b32 s7, v2, 5 -v_mov_b32_e32 v10, 0 -s_mov_b32 s8, 777 -v_writelane_b32 v10, s8, 40 -v_readlane_b32 s9, v10, 8 -v_readlane_b32 s10, v10, 40 -v_cmpx_eq_u32_e32 0, v0 -v_mov_b32_e32 v20, s6 -v_mov_b32_e32 v21, 0 -buffer_store_dword v20, v21, s[0:3], 0 offen -v_mov_b32_e32 v20, s7 -v_mov_b32_e32 v21, 4 -buffer_store_dword v20, v21, s[0:3], 0 offen -v_mov_b32_e32 v20, s9 -v_mov_b32_e32 v21, 8 -buffer_store_dword v20, v21, s[0:3], 0 offen -v_mov_b32_e32 v20, s10 -v_mov_b32_e32 v21, 12 -buffer_store_dword v20, v21, s[0:3], 0 offen -s_endpgm diff --git a/runtime/test/shaders/cs_w32_lds_subdword.asm b/runtime/test/shaders/cs_w32_lds_subdword.asm deleted file mode 100644 index cb2f94243..000000000 --- a/runtime/test/shaders/cs_w32_lds_subdword.asm +++ /dev/null @@ -1,58 +0,0 @@ -; regen_fixtures: this source has a translator fixture in tests/semantic/fixtures/disasm -; ds_write_b8 / ds_write_b8_d16_hi / ds_write_b16 / ds_write_b16_d16_hi and ds_read_u8 / ds_read_i8 / ds_read_u16 / -; ds_read_i16 (RDNA2 ISA, "Data Share Instructions"). ADDR = vaddr + offset: (bytes). -; ds_write_b8 MEM[ADDR][7:0] = DATA[7:0] ds_write_b8_d16_hi MEM[ADDR][7:0] = DATA[23:16] -; ds_write_b16 MEM[ADDR][15:0] = DATA[15:0] ds_write_b16_d16_hi MEM[ADDR][15:0] = DATA[31:16] -; ds_read_u8/i8 D = zero/sign-extend 8 -> 32 of MEM[ADDR][7:0] -; ds_read_u16/i16 D = zero/sign-extend 16 -> 32 of MEM[ADDR][15:0] -; LDS dword 0 = 0x11223344, dword 1 = 0x55667788; DATA = 0xA1B2C3D4. The narrow writes give -; dword 0 = 0x11B2D444 (byte 1 = 0xD4 from b8, byte 2 = 0xB2 from b8_d16_hi; bytes 0 and 3 kept) -; dword 1 = 0xA1B2C3D4 (low half 0xC3D4 from b16, high half 0xA1B2 from b16_d16_hi) -; out[0] ds_read_b32 offset:0 -> 0x11B2D444 out[1] ds_read_b32 offset:4 -> 0xA1B2C3D4 -; out[2] ds_read_i8 offset:2 -> 0xFFFFFFB2 out[3] ds_read_u8 offset:2 -> 0x000000B2 -; out[4] ds_read_i8 offset:3 -> 0x00000011 out[5] ds_read_i16 offset:6 -> 0xFFFFA1B2 -; out[6] ds_read_u16 offset:6 -> 0x0000A1B2 out[7] ds_read_i16 offset:4 -> 0xFFFFC3D4 -; Every lane writes the same bytes, so the result does not depend on lane order. -; group: 32,1,1 -; Run: vk_compute_test cs_w32_lds_subdword.spv 1 dump -; -> out[0..7] = 0x11B2D444 0xA1B2C3D4 0xFFFFFFB2 0x000000B2 0x00000011 0xFFFFA1B2 0x0000A1B2 0xFFFFC3D4 -; mattr: +wavefrontsize32,-wavefrontsize64 -v_mov_b32_e32 v2, 0 -v_mov_b32_e32 v4, 0x11223344 -v_mov_b32_e32 v5, 0x55667788 -ds_write_b32 v2, v4 -ds_write_b32 v2, v5 offset:4 -s_waitcnt lgkmcnt(0) -v_mov_b32_e32 v3, 0xa1b2c3d4 -ds_write_b8 v2, v3 offset:1 -ds_write_b8_d16_hi v2, v3 offset:2 -ds_write_b16 v2, v3 offset:4 -ds_write_b16_d16_hi v2, v3 offset:6 -s_waitcnt lgkmcnt(0) -ds_read_b32 v10, v2 -ds_read_b32 v11, v2 offset:4 -ds_read_i8 v12, v2 offset:2 -ds_read_u8 v13, v2 offset:2 -ds_read_i8 v14, v2 offset:3 -ds_read_i16 v15, v2 offset:6 -ds_read_u16 v16, v2 offset:6 -ds_read_i16 v17, v2 offset:4 -s_waitcnt lgkmcnt(0) -v_cmpx_eq_u32_e32 0, v0 -v_mov_b32_e32 v21, 0 -buffer_store_dword v10, v21, s[0:3], 0 offen -v_mov_b32_e32 v21, 4 -buffer_store_dword v11, v21, s[0:3], 0 offen -v_mov_b32_e32 v21, 8 -buffer_store_dword v12, v21, s[0:3], 0 offen -v_mov_b32_e32 v21, 12 -buffer_store_dword v13, v21, s[0:3], 0 offen -v_mov_b32_e32 v21, 16 -buffer_store_dword v14, v21, s[0:3], 0 offen -v_mov_b32_e32 v21, 20 -buffer_store_dword v15, v21, s[0:3], 0 offen -v_mov_b32_e32 v21, 24 -buffer_store_dword v16, v21, s[0:3], 0 offen -v_mov_b32_e32 v21, 28 -buffer_store_dword v17, v21, s[0:3], 0 offen -s_endpgm diff --git a/runtime/test/shaders/cs_w32_lds_u8_d16.asm b/runtime/test/shaders/cs_w32_lds_u8_d16.asm deleted file mode 100644 index 70ba5568e..000000000 --- a/runtime/test/shaders/cs_w32_lds_u8_d16.asm +++ /dev/null @@ -1,56 +0,0 @@ -; regen_fixtures: this source has a translator fixture in tests/semantic/fixtures/disasm -; SHADER-85: ds_read_u8_d16 / ds_read_u8_d16_hi / ds_read_i8_d16 / ds_read_i8_d16_hi (RDNA2 ISA, DS opcodes 162-165). -; An 8-bit LDS read lands in ONE 16-bit half of the destination VGPR and the other half is kept: -; u8_d16 D[15:0] = zext16(byte) D[31:16] kept u8_d16_hi D[31:16] = zext16(byte) D[15:0] kept -; i8_d16 D[15:0] = sext16(byte) D[31:16] kept i8_d16_hi D[31:16] = sext16(byte) D[15:0] kept -; LDS dword 0 = 0x7F80FF01, so the bytes at byte address 0..3 are 01 FF 80 7F (512 B LDS from the default header). -; Every destination starts as 0xBEEF1234; the address is v1 (0, or 1 for the last read) plus the offset: field. -; out[0] u8_d16 offset:1 (0xFF) -> 0xBEEF00FF out[1] u8_d16_hi offset:1 (0xFF) -> 0x00FF1234 -; out[2] i8_d16 offset:2 (0x80) -> 0xBEEFFF80 out[3] i8_d16_hi offset:2 (0x80) -> 0xFF801234 -; out[4] i8_d16 offset:3 (0x7F) -> 0xBEEF007F out[5] i8_d16_hi offset:3 (0x7F) -> 0x007F1234 -; out[6] u8_d16 offset:2 (0x80) -> 0xBEEF0080 out[7] i8_d16_hi v1=1, no offset (byte 1, 0xFF) -> 0xFFFF1234 -; group: 32,1,1 -; Run: vk_compute_test cs_w32_lds_u8_d16.spv 1 dump -; -> out[0..7] = 0xBEEF00FF 0x00FF1234 0xBEEFFF80 0xFF801234 0xBEEF007F 0x007F1234 0xBEEF0080 0xFFFF1234 -; mattr: +wavefrontsize32,-wavefrontsize64 -v_mov_b32_e32 v2, 0 -v_mov_b32_e32 v3, 0x7f80ff01 -ds_write_b32 v2, v3 -s_waitcnt lgkmcnt(0) -v_mov_b32_e32 v1, 0 -v_mov_b32_e32 v10, 0xbeef1234 -v_mov_b32_e32 v11, 0xbeef1234 -v_mov_b32_e32 v12, 0xbeef1234 -v_mov_b32_e32 v13, 0xbeef1234 -v_mov_b32_e32 v14, 0xbeef1234 -v_mov_b32_e32 v15, 0xbeef1234 -v_mov_b32_e32 v16, 0xbeef1234 -v_mov_b32_e32 v17, 0xbeef1234 -ds_read_u8_d16 v10, v1 offset:1 -ds_read_u8_d16_hi v11, v1 offset:1 -ds_read_i8_d16 v12, v1 offset:2 -ds_read_i8_d16_hi v13, v1 offset:2 -ds_read_i8_d16 v14, v1 offset:3 -ds_read_i8_d16_hi v15, v1 offset:3 -ds_read_u8_d16 v16, v1 offset:2 -v_mov_b32_e32 v1, 1 -ds_read_i8_d16_hi v17, v1 -s_waitcnt lgkmcnt(0) -v_cmpx_eq_u32_e32 0, v0 -v_mov_b32_e32 v21, 0 -buffer_store_dword v10, v21, s[0:3], 0 offen -v_mov_b32_e32 v21, 4 -buffer_store_dword v11, v21, s[0:3], 0 offen -v_mov_b32_e32 v21, 8 -buffer_store_dword v12, v21, s[0:3], 0 offen -v_mov_b32_e32 v21, 12 -buffer_store_dword v13, v21, s[0:3], 0 offen -v_mov_b32_e32 v21, 16 -buffer_store_dword v14, v21, s[0:3], 0 offen -v_mov_b32_e32 v21, 20 -buffer_store_dword v15, v21, s[0:3], 0 offen -v_mov_b32_e32 v21, 24 -buffer_store_dword v16, v21, s[0:3], 0 offen -v_mov_b32_e32 v21, 28 -buffer_store_dword v17, v21, s[0:3], 0 offen -s_endpgm diff --git a/runtime/test/shaders/cs_w32_lds_wide.asm b/runtime/test/shaders/cs_w32_lds_wide.asm deleted file mode 100644 index b36b16b71..000000000 --- a/runtime/test/shaders/cs_w32_lds_wide.asm +++ /dev/null @@ -1,58 +0,0 @@ -; regen_fixtures: this source has a translator fixture in tests/semantic/fixtures/disasm -; ds_write_b64 / ds_write_b96 / ds_write_b128, ds_read_b64 / ds_read_b96 / ds_read_b128 and ds_read2st64_b32 -; (RDNA2 ISA, "Data Share Instructions"). ADDR = vaddr + offset: (bytes); an N-dword access covers -; MEM[ADDR .. ADDR + 4N - 1], lowest register first. ds_read2st64_b32 reads MEM[ADDR + offset0 * 256] and -; MEM[ADDR + offset1 * 256] (offsets count 64 dwords). -; v[30:33] = A B C D, v[34:35] = E F (values below). Writes: -; b128 v[30:33] at byte 16, b32 0 at byte 60 then b96 v[30:32] at byte 48 (byte 60 stays 0), -; b64 v[34:35] at byte 64, b32 G at byte 0 and b32 H at byte 256 (LDS is 512 B, the default header). -; out[0] b128 at 16, first reg -> A 0xCAFEF00D out[1] b128 at 16, last reg -> D 0xFEEDFACE -; out[2] b96 at 48, last reg -> C 0x600DD00D out[3] b32 at 60 (after b96) -> 0x00000000 -; out[4] b64 at 64, low reg -> E 0x8BADF00D out[5] b64 at 64, high reg -> F 0xDEADC0DE -; out[6] read2st64 offset0:0 -> G 0x12345678 out[7] read2st64 offset1:1 -> H 0x9ABCDEF0 -; Every lane writes the same dwords, so the result does not depend on lane order. -; group: 32,1,1 -; Run: vk_compute_test cs_w32_lds_wide.spv 1 dump -; -> out[0..7] = 0xCAFEF00D 0xFEEDFACE 0x600DD00D 0x00000000 0x8BADF00D 0xDEADC0DE 0x12345678 0x9ABCDEF0 -; mattr: +wavefrontsize32,-wavefrontsize64 -v_mov_b32_e32 v2, 0 -v_mov_b32_e32 v30, 0xcafef00d -v_mov_b32_e32 v31, 0x0badbeef -v_mov_b32_e32 v32, 0x600dd00d -v_mov_b32_e32 v33, 0xfeedface -v_mov_b32_e32 v34, 0x8badf00d -v_mov_b32_e32 v35, 0xdeadc0de -v_mov_b32_e32 v4, 0x12345678 -v_mov_b32_e32 v5, 0x9abcdef0 -ds_write_b128 v2, v[30:33] offset:16 -ds_write_b32 v2, v2 offset:60 -s_waitcnt lgkmcnt(0) -ds_write_b96 v2, v[30:32] offset:48 -ds_write_b64 v2, v[34:35] offset:64 -ds_write_b32 v2, v4 -ds_write_b32 v2, v5 offset:256 -s_waitcnt lgkmcnt(0) -ds_read_b128 v[40:43], v2 offset:16 -ds_read_b96 v[44:46], v2 offset:48 -ds_read_b32 v47, v2 offset:60 -ds_read_b64 v[48:49], v2 offset:64 -ds_read2st64_b32 v[50:51], v2 offset1:1 -s_waitcnt lgkmcnt(0) -v_cmpx_eq_u32_e32 0, v0 -v_mov_b32_e32 v21, 0 -buffer_store_dword v40, v21, s[0:3], 0 offen -v_mov_b32_e32 v21, 4 -buffer_store_dword v43, v21, s[0:3], 0 offen -v_mov_b32_e32 v21, 8 -buffer_store_dword v46, v21, s[0:3], 0 offen -v_mov_b32_e32 v21, 12 -buffer_store_dword v47, v21, s[0:3], 0 offen -v_mov_b32_e32 v21, 16 -buffer_store_dword v48, v21, s[0:3], 0 offen -v_mov_b32_e32 v21, 20 -buffer_store_dword v49, v21, s[0:3], 0 offen -v_mov_b32_e32 v21, 24 -buffer_store_dword v50, v21, s[0:3], 0 offen -v_mov_b32_e32 v21, 28 -buffer_store_dword v51, v21, s[0:3], 0 offen -s_endpgm diff --git a/runtime/test/shaders/cs_w32_mask_imm.asm b/runtime/test/shaders/cs_w32_mask_imm.asm deleted file mode 100644 index 31634bd52..000000000 --- a/runtime/test/shaders/cs_w32_mask_imm.asm +++ /dev/null @@ -1,120 +0,0 @@ -; regen_fixtures: this source has a translator fixture in tests/semantic/fixtures/disasm -; Constant lane masks in wave32 (s_and/or/andn2_saveexec_b32, s_andn2_wrexec_b32). -; A constant read as a lane mask gives lane L its bit L (RDNA2 ISA: EXEC is one bit per lane, and an inline -; constant or literal source of these 32-bit ops is that mask; -16 is 0xfffffff0). Until 2026-11-22 the translator -; gave every lane bit 0 of the constant (Gen.mask_src), so 0xff00 turned all lanes off and 5 turned all 32 on. -; v0 = lane (LocalInvocationId.x, 0..31). Each case sets EXEC, runs the op and marks the lanes it leaves on (a VALU -; write under the new EXEC); with EXEC back to all lanes, v_cmp turns the marks into a lane mask and lane 0 stores -; word = (set lanes) | (lowest set lane) << 8, from s_bcnt1 and s_ff1 of that mask (no lane: 0xffffff00). -; out[0] EXEC=all, s_and_saveexec_b32 0xff00 -> 0x0000ff00 = lanes 8-15 8 | 8<<8 = 2056 -; out[1] EXEC=0xff, s_or_saveexec_b32 0x55555555 -> 0x555555ff (4+4+4+8 lanes) 20 | 0 = 20 -; out[2] EXEC=all, s_and_saveexec_b32 5 (inline) -> lanes 0, 2 2 | 0 = 2 -; out[3] EXEC=0xffff, s_andn2_saveexec_b32 0xff00ff00 -> & ~0xffff = 0xff000000, lanes 24-31 8 | 24<<8 = 6152 -; out[4] EXEC=0xff, s_andn2_wrexec_b32 0x3ff -> 0x3ff & ~0xff = lanes 8, 9 2 | 8<<8 = 2050 -; out[5] EXEC=0xffff, s_andn2_saveexec_b32 -16 -> 0xfffffff0 & ~0xffff = lanes 16-31 16 | 16<<8 = 4112 -; out[6] EXEC=0, s_or_saveexec_b32 0x80000002 -> lanes 1, 31 2 | 1<<8 = 258 -; out[7] EXEC=15, s_or_saveexec_b32 -1 -> all 32 lanes (as before the fix) 32 | 0 = 32 -; Bit 0 for every lane (the old translation) gives 0xffffff00 32 32 0xffffff00 2072 0xffffff00 0xffffff00 32. -; group: 32,1,1 -; Run: VKC_SUBGROUP_SIZE=32 vk_compute_test cs_w32_mask_imm.spv 1 dump -; -> out[0..7] = 2056 20 2 6152 2050 4112 258 32 -; mattr: +wavefrontsize32,-wavefrontsize64 -v_mov_b32_e32 v10, 0 -v_mov_b32_e32 v11, 0 -v_mov_b32_e32 v12, 0 -v_mov_b32_e32 v13, 0 -v_mov_b32_e32 v14, 0 -v_mov_b32_e32 v15, 0 -v_mov_b32_e32 v16, 0 -v_mov_b32_e32 v17, 0 -s_mov_b32 exec_lo, -1 -s_and_saveexec_b32 s7, 0xff00 -v_mov_b32_e32 v10, 1 -s_mov_b32 exec_lo, 0xff -s_or_saveexec_b32 s7, 0x55555555 -v_mov_b32_e32 v11, 1 -s_mov_b32 exec_lo, -1 -s_and_saveexec_b32 s7, 5 -v_mov_b32_e32 v12, 1 -s_mov_b32 exec_lo, 0xffff -s_andn2_saveexec_b32 s7, 0xff00ff00 -v_mov_b32_e32 v13, 1 -s_mov_b32 exec_lo, 0xff -s_andn2_wrexec_b32 s7, 0x3ff -v_mov_b32_e32 v14, 1 -s_mov_b32 exec_lo, 0xffff -s_andn2_saveexec_b32 s7, -16 -v_mov_b32_e32 v15, 1 -s_mov_b32 exec_lo, 0 -s_or_saveexec_b32 s7, 0x80000002 -v_mov_b32_e32 v16, 1 -s_mov_b32 exec_lo, 15 -s_or_saveexec_b32 s7, -1 -v_mov_b32_e32 v17, 1 -s_mov_b32 exec_lo, -1 -v_cmp_ne_u32_e32 vcc_lo, 0, v10 -s_bcnt1_i32_b32 s20, vcc_lo -s_ff1_i32_b32 s21, vcc_lo -s_lshl_b32 s21, s21, 8 -s_or_b32 s20, s20, s21 -v_cmp_ne_u32_e32 vcc_lo, 0, v11 -s_bcnt1_i32_b32 s22, vcc_lo -s_ff1_i32_b32 s23, vcc_lo -s_lshl_b32 s23, s23, 8 -s_or_b32 s22, s22, s23 -v_cmp_ne_u32_e32 vcc_lo, 0, v12 -s_bcnt1_i32_b32 s24, vcc_lo -s_ff1_i32_b32 s25, vcc_lo -s_lshl_b32 s25, s25, 8 -s_or_b32 s24, s24, s25 -v_cmp_ne_u32_e32 vcc_lo, 0, v13 -s_bcnt1_i32_b32 s26, vcc_lo -s_ff1_i32_b32 s27, vcc_lo -s_lshl_b32 s27, s27, 8 -s_or_b32 s26, s26, s27 -v_cmp_ne_u32_e32 vcc_lo, 0, v14 -s_bcnt1_i32_b32 s28, vcc_lo -s_ff1_i32_b32 s29, vcc_lo -s_lshl_b32 s29, s29, 8 -s_or_b32 s28, s28, s29 -v_cmp_ne_u32_e32 vcc_lo, 0, v15 -s_bcnt1_i32_b32 s30, vcc_lo -s_ff1_i32_b32 s31, vcc_lo -s_lshl_b32 s31, s31, 8 -s_or_b32 s30, s30, s31 -v_cmp_ne_u32_e32 vcc_lo, 0, v16 -s_bcnt1_i32_b32 s32, vcc_lo -s_ff1_i32_b32 s33, vcc_lo -s_lshl_b32 s33, s33, 8 -s_or_b32 s32, s32, s33 -v_cmp_ne_u32_e32 vcc_lo, 0, v17 -s_bcnt1_i32_b32 s34, vcc_lo -s_ff1_i32_b32 s35, vcc_lo -s_lshl_b32 s35, s35, 8 -s_or_b32 s34, s34, s35 -v_cmpx_eq_u32_e32 0, v0 -v_mov_b32_e32 v1, s20 -v_mov_b32_e32 v2, 0 -buffer_store_dword v1, v2, s[0:3], 0 offen -v_mov_b32_e32 v1, s22 -v_mov_b32_e32 v2, 4 -buffer_store_dword v1, v2, s[0:3], 0 offen -v_mov_b32_e32 v1, s24 -v_mov_b32_e32 v2, 8 -buffer_store_dword v1, v2, s[0:3], 0 offen -v_mov_b32_e32 v1, s26 -v_mov_b32_e32 v2, 12 -buffer_store_dword v1, v2, s[0:3], 0 offen -v_mov_b32_e32 v1, s28 -v_mov_b32_e32 v2, 16 -buffer_store_dword v1, v2, s[0:3], 0 offen -v_mov_b32_e32 v1, s30 -v_mov_b32_e32 v2, 20 -buffer_store_dword v1, v2, s[0:3], 0 offen -v_mov_b32_e32 v1, s32 -v_mov_b32_e32 v2, 24 -buffer_store_dword v1, v2, s[0:3], 0 offen -v_mov_b32_e32 v1, s34 -v_mov_b32_e32 v2, 28 -buffer_store_dword v1, v2, s[0:3], 0 offen -s_endpgm diff --git a/runtime/test/shaders/cs_w32_misc_ext.asm b/runtime/test/shaders/cs_w32_misc_ext.asm deleted file mode 100644 index bbb4bc0e3..000000000 --- a/runtime/test/shaders/cs_w32_misc_ext.asm +++ /dev/null @@ -1,72 +0,0 @@ -; regen_fixtures: this source has a translator fixture in tests/semantic/fixtures/disasm -; Ops merged with CPU-only checks (#1471 #825 #828 #814 #810), run once on a GPU. -; Lane 0 of a wave32 group computes one result per op and stores eight dwords: -; out[0] = high word of s_nand_b64(0xF0F0F0F0_12345678, 0xFF00FF00_FFFFFFFF) = 0x0FFF0FFF (~(S0 & S1)) -; out[1] = low word of s_xnor_b64(0xF0F0F0F0_12345678, 0xFF00FF00_0F0F0F0F) = 0xE2C4A688 (~(S0 ^ S1)) -; out[2] = v_cvt_pk_u16_u32(0x12345, 7) = 0x0007FFFF (low half saturated to 0xFFFF) -; out[3] = v_cvt_pk_i16_i32(-40000, 40000) = 0x7FFF8000 (each half saturated to i16) -; out[4] = v_mad_u32_u16(0xFFFF, 0xFFFF, 1) = 0xFFFE0002 -; out[5] = v_mad_i32_i16(0x8000, 2, 5) = 0xFFFF0005 (-32768 * 2 + 5) -; out[6] = (ds_cmpst_rtn_b32 old << 8) | LDS after = 0x509 (LDS 5, compare 5, store 9) -; out[7] = high dword of the second ds_read2_b64 element = 0xCAFEF00D (written by ds_write2_b64 offset1:3) -; EXEC is cut to lane 0 before the LDS ops: 32 lanes on one LDS address would race (which lane's -; ds_cmpst / ds_wrxchg2 runs first is up to the hardware), as #1850 showed for ds_xor_b64. -; group: 32,1,1 -; Run: vk_compute_test cs_w32_misc_ext.spv 1 dump -> out[0..7] = 268374015 3804538504 524287 2147450880 4294836226 4294901765 1289 3405705229 -; mattr: +wavefrontsize32,-wavefrontsize64 -s_mov_b32 s6, 0x12345678 -s_mov_b32 s7, 0xf0f0f0f0 -s_mov_b32 s10, -1 -s_mov_b32 s11, 0xff00ff00 -s_nand_b64 s[8:9], s[6:7], s[10:11] -s_mov_b32 s10, 0xf0f0f0f -s_xnor_b64 s[12:13], s[6:7], s[10:11] -v_mov_b32_e32 v1, 0x12345 -v_mov_b32_e32 v2, 7 -v_cvt_pk_u16_u32 v3, v1, v2 -v_mov_b32_e32 v1, 0xffff63c0 -v_mov_b32_e32 v2, 0x9c40 -v_cvt_pk_i16_i32 v4, v1, v2 -v_mov_b32_e32 v1, 0xffff -v_mad_u32_u16 v5, v1, v1, 1 -v_mov_b32_e32 v1, 0x8000 -v_mad_i32_i16 v6, v1, 2, 5 -v_cmpx_eq_u32_e32 0, v0 -v_mov_b32_e32 v10, 0x10 -v_mov_b32_e32 v11, 5 -v_mov_b32_e32 v12, 9 -ds_write_b32 v10, v11 -s_waitcnt lgkmcnt(0) -ds_cmpst_rtn_b32 v13, v10, v11, v12 -s_waitcnt lgkmcnt(0) -ds_read_b32 v14, v10 -s_waitcnt lgkmcnt(0) -v_lshl_or_b32 v7, v13, 8, v14 -v_mov_b32_e32 v10, 0x40 -v_mov_b32_e32 v16, 0x11111111 -v_mov_b32_e32 v17, 0x22222222 -v_mov_b32_e32 v18, 0x33333333 -v_mov_b32_e32 v19, 0xcafef00d -ds_write2_b64 v10, v[16:17], v[18:19] offset0:1 offset1:3 -s_waitcnt lgkmcnt(0) -ds_read2_b64 v[20:23], v10 offset0:1 offset1:3 -s_waitcnt lgkmcnt(0) -v_mov_b32_e32 v24, s9 -v_mov_b32_e32 v25, 0 -buffer_store_dword v24, v25, s[0:3], 0 offen -v_mov_b32_e32 v24, s12 -v_mov_b32_e32 v25, 4 -buffer_store_dword v24, v25, s[0:3], 0 offen -v_mov_b32_e32 v25, 8 -buffer_store_dword v3, v25, s[0:3], 0 offen -v_mov_b32_e32 v25, 12 -buffer_store_dword v4, v25, s[0:3], 0 offen -v_mov_b32_e32 v25, 16 -buffer_store_dword v5, v25, s[0:3], 0 offen -v_mov_b32_e32 v25, 20 -buffer_store_dword v6, v25, s[0:3], 0 offen -v_mov_b32_e32 v25, 24 -buffer_store_dword v7, v25, s[0:3], 0 offen -v_mov_b32_e32 v25, 28 -buffer_store_dword v23, v25, s[0:3], 0 offen -s_endpgm diff --git a/runtime/test/shaders/cs_w32_new_ops.asm b/runtime/test/shaders/cs_w32_new_ops.asm deleted file mode 100644 index e7d4e452b..000000000 --- a/runtime/test/shaders/cs_w32_new_ops.asm +++ /dev/null @@ -1,67 +0,0 @@ -; regen_fixtures: this source has a translator fixture in tests/semantic/fixtures/disasm -; Ops merged with CPU-only checks (#1479 #1496 #1510 #1514), run once on a GPU. -; Lane 0 of a wave32 group computes one result per op and stores eight dwords: -; out[0] = s_quadmask_b32(0x01020408) = 0x55 (quads 0, 2, 4, 6 non-zero) -; out[1] = low word of s_quadmask_b64(0x80000000_00000001) = 0x8001 (quads 0 and 15) -; out[2] = high word of s_bitreplicate_b64_b32(0x80000001) = 0xC0000000 (bit 31 -> bits 63:62) -; out[3] = v_cvt_pknorm_i16_f32(0.5, -1.0) = 0x80014000 (16383.5 -> 16384 even; -32767) -; out[4] = v_cvt_pknorm_u16_f32(1.0, 0.25) = 0x4000FFFF (65535; 16383.75 -> 16384) -; out[5] = ds_wrxchg2_rtn_b32 old word at offset0:2 = 0x77 (LDS seeded 0x77) -; out[6] = LDS word at offset1:5 after the exchange = 0x99 (DATA2) -; out[7] = v7 after ds_nop and v_clrexcp = 0x1234 (no effect) -; EXEC is cut to lane 0 before the LDS ops: 32 lanes on one LDS address would race (which lane's -; ds_cmpst / ds_wrxchg2 runs first is up to the hardware), as #1850 showed for ds_xor_b64. -; group: 32,1,1 -; Run: vk_compute_test cs_w32_new_ops.spv 1 dump -> out[0..7] = 85 32769 3221225472 2147565568 1073807359 119 153 4660 -; mattr: +wavefrontsize32,-wavefrontsize64 -s_mov_b32 s6, 0x1020408 -s_quadmask_b32 s8, s6 -s_mov_b32 s6, 1 -s_mov_b32 s7, 0x80000000 -s_quadmask_b64 s[10:11], s[6:7] -s_mov_b32 s6, 0x80000001 -s_bitreplicate_b64_b32 s[12:13], s6 -v_mov_b32_e32 v1, 0.5 -v_mov_b32_e32 v2, -1.0 -v_cvt_pknorm_i16_f32 v3, v1, v2 -v_mov_b32_e32 v1, 1.0 -v_mov_b32_e32 v2, 0.25 -v_cvt_pknorm_u16_f32 v4, v1, v2 -v_cmpx_eq_u32_e32 0, v0 -v_mov_b32_e32 v10, 0x20 -v_mov_b32_e32 v11, 0x28 -v_mov_b32_e32 v12, 0x34 -v_mov_b32_e32 v13, 0x77 -v_mov_b32_e32 v14, 0x66 -ds_write_b32 v11, v13 -ds_write_b32 v12, v14 -s_waitcnt lgkmcnt(0) -v_mov_b32_e32 v15, 0x88 -v_mov_b32_e32 v16, 0x99 -ds_wrxchg2_rtn_b32 v[5:6], v10, v15, v16 offset0:2 offset1:5 -s_waitcnt lgkmcnt(0) -ds_read_b32 v6, v12 -s_waitcnt lgkmcnt(0) -v_mov_b32_e32 v7, 0x1234 -ds_nop -v_clrexcp -v_mov_b32_e32 v24, s8 -v_mov_b32_e32 v25, 0 -buffer_store_dword v24, v25, s[0:3], 0 offen -v_mov_b32_e32 v24, s10 -v_mov_b32_e32 v25, 4 -buffer_store_dword v24, v25, s[0:3], 0 offen -v_mov_b32_e32 v24, s13 -v_mov_b32_e32 v25, 8 -buffer_store_dword v24, v25, s[0:3], 0 offen -v_mov_b32_e32 v25, 12 -buffer_store_dword v3, v25, s[0:3], 0 offen -v_mov_b32_e32 v25, 16 -buffer_store_dword v4, v25, s[0:3], 0 offen -v_mov_b32_e32 v25, 20 -buffer_store_dword v5, v25, s[0:3], 0 offen -v_mov_b32_e32 v25, 24 -buffer_store_dword v6, v25, s[0:3], 0 offen -v_mov_b32_e32 v25, 28 -buffer_store_dword v7, v25, s[0:3], 0 offen -s_endpgm diff --git a/runtime/test/shaders/cs_w32_partial_permute.asm b/runtime/test/shaders/cs_w32_partial_permute.asm deleted file mode 100644 index 7f0737920..000000000 --- a/runtime/test/shaders/cs_w32_partial_permute.asm +++ /dev/null @@ -1,72 +0,0 @@ -; Partial wave32 ds_permute_b32: a 20x1x1 group is one wave32 with lanes 0-19 launched and lanes 20-31 never -; launched. A lane that doesn't exist sends nothing, so a launched lane whose only source is a missing lane gets 0, -; and a launched lane's send to a missing lane goes nowhere. cs_w32_permute.asm covers full waves; the translator -; shuffles from every source lane of the subgroup, so here some of those reads name lanes that were never launched. -; v1 = lane (0..19), v2 = 7 * lane + 1 (data). Each case has one source per destination: -; (A) addr = (lane + 1) * 4: lane l writes lane l + 1. Lane 0's source is lane 31 (missing): 0. -; Lane 5 <- lane 4 = 29. Lane 19 <- lane 18 = 127 (lane 19's own send, to lane 20, is lost). -; (B) addr = (lane + 12) * 4: lane l writes lane (l + 12) mod 32. Lanes 0-7 write lanes 12-19; lanes 8-19 write -; the missing lanes 20-31. Lane 3's source is lane 23 (missing): 0. Lane 12 <- lane 0 = 1. -; (C) addr = (31 - lane) * 4: lane l writes lane 31 - l. Lanes 0-11 write the missing lanes 31-20; lanes 12-19 -; write lanes 19-12. Lane 0's source is lane 31 (missing): 0. Lane 12 <- lane 19 = 134, lane 15 <- lane 16 = 113. -; Stores: out[0..7] = A0 A5 A19 B3 B12 C0 C12 C15 = 0 29 127 0 1 0 134 113. -; Same words from a raw 20-thread wave32 kernel on gfx1036 hardware (tools/hw_oracle, AMD Windows driver -; 32.0.13036.4). -; Run: VKC_SUBGROUP_SIZE=32 vk_compute_test cs_w32_partial_permute.spv 1 dump -; -> out[0..7] = 0 29 127 0 1 0 134 113 -; mattr: -wavefrontsize64,+wavefrontsize32 -; group: 20,1,1 -v_mbcnt_lo_u32_b32 v1, -1, 0 -s_mov_b32 s6, exec_lo -v_mad_u32_u24 v2, v1, 7, 1 -v_add_nc_u32_e32 v3, 1, v1 -v_lshlrev_b32_e32 v3, 2, v3 -ds_permute_b32 v10, v3, v2 -v_add_nc_u32_e32 v4, 12, v1 -v_lshlrev_b32_e32 v4, 2, v4 -ds_permute_b32 v11, v4, v2 -v_sub_nc_u32_e32 v5, 31, v1 -v_lshlrev_b32_e32 v5, 2, v5 -ds_permute_b32 v12, v5, v2 -s_waitcnt lgkmcnt(0) -v_cmpx_eq_u32_e32 0, v1 -v_mov_b32_e32 v20, v10 -v_mov_b32_e32 v21, 0 -buffer_store_dword v20, v21, s[0:3], 0 offen -s_mov_b32 exec_lo, s6 -v_cmpx_eq_u32_e32 5, v1 -v_mov_b32_e32 v20, v10 -v_mov_b32_e32 v21, 4 -buffer_store_dword v20, v21, s[0:3], 0 offen -s_mov_b32 exec_lo, s6 -v_cmpx_eq_u32_e32 19, v1 -v_mov_b32_e32 v20, v10 -v_mov_b32_e32 v21, 8 -buffer_store_dword v20, v21, s[0:3], 0 offen -s_mov_b32 exec_lo, s6 -v_cmpx_eq_u32_e32 3, v1 -v_mov_b32_e32 v20, v11 -v_mov_b32_e32 v21, 12 -buffer_store_dword v20, v21, s[0:3], 0 offen -s_mov_b32 exec_lo, s6 -v_cmpx_eq_u32_e32 12, v1 -v_mov_b32_e32 v20, v11 -v_mov_b32_e32 v21, 16 -buffer_store_dword v20, v21, s[0:3], 0 offen -s_mov_b32 exec_lo, s6 -v_cmpx_eq_u32_e32 0, v1 -v_mov_b32_e32 v20, v12 -v_mov_b32_e32 v21, 20 -buffer_store_dword v20, v21, s[0:3], 0 offen -s_mov_b32 exec_lo, s6 -v_cmpx_eq_u32_e32 12, v1 -v_mov_b32_e32 v20, v12 -v_mov_b32_e32 v21, 24 -buffer_store_dword v20, v21, s[0:3], 0 offen -s_mov_b32 exec_lo, s6 -v_cmpx_eq_u32_e32 15, v1 -v_mov_b32_e32 v20, v12 -v_mov_b32_e32 v21, 28 -buffer_store_dword v20, v21, s[0:3], 0 offen -s_mov_b32 exec_lo, s6 -s_endpgm diff --git a/runtime/test/shaders/cs_w32_partial_scmp.asm b/runtime/test/shaders/cs_w32_partial_scmp.asm deleted file mode 100644 index 24a54ff8c..000000000 --- a/runtime/test/shaders/cs_w32_partial_scmp.asm +++ /dev/null @@ -1,65 +0,0 @@ -; Partial wave32: s_cmp of a lane mask against -1 (all ones) compares the real mask word, not a vote. -; A 20x1x1 group is one wave32 with lanes 0-19 enabled and lanes 20-31 never launched. -; vcc_lo = v_cmp_eq(v1, v1) has a bit per launched lane only, so vcc_lo = 0x000fffff, and EXEC_LO = 0x000fffff. -; A vote over the launched lanes would call both "all ones". -; Lane 0 stores SCC as 0/1 for each compare: -; out[0] s_cmp_eq_u32 vcc_lo, -1 = 0 (0xfffff != 0xffffffff) -; out[1] s_cmp_lg_u32 vcc_lo, 0 = 1 -; out[2] s_cmp_eq_u32 vcc_lo, s14 = 1 (s14 = 0xfffff) -; out[3] s_cmp_eq_u32 exec_lo, -1 = 0 -; out[4] s_cmp_lg_u32 vcc_lo, -1 = 1 -; out[5] s_cmp_eq_u32 vcc_lo, exec_lo = 1 -; out[6] s_cmp_lg_u32 exec_lo, -1 = 1 -; out[7] s_cmp_eq_u32 exec_lo, s14 = 1 -; Until 2026-11-22 the compares with -1 were a vote: out[0] and out[3] read 1, out[4] and out[6] read 0. -; Run: VKC_SUBGROUP_SIZE=32 vk_compute_test cs_w32_partial_scmp.spv 1 dump -; -> out[0..7] = 0 1 1 0 1 1 1 1 -; mattr: -wavefrontsize64,+wavefrontsize32 -; group: 20,1,1 -v_mbcnt_lo_u32_b32 v1, -1, 0 -s_mov_b32 s6, exec_lo -v_cmp_eq_u32_e32 vcc_lo, v1, v1 -s_mov_b32 s14, 0xfffff -s_cmp_eq_u32 vcc_lo, -1 -s_cselect_b32 s20, 1, 0 -s_cmp_lg_u32 vcc_lo, 0 -s_cselect_b32 s21, 1, 0 -s_cmp_eq_u32 vcc_lo, s14 -s_cselect_b32 s22, 1, 0 -s_cmp_eq_u32 exec_lo, -1 -s_cselect_b32 s23, 1, 0 -s_cmp_lg_u32 vcc_lo, -1 -s_cselect_b32 s24, 1, 0 -s_cmp_eq_u32 vcc_lo, exec_lo -s_cselect_b32 s25, 1, 0 -s_cmp_lg_u32 exec_lo, -1 -s_cselect_b32 s26, 1, 0 -s_cmp_eq_u32 exec_lo, s14 -s_cselect_b32 s27, 1, 0 -v_cmpx_eq_u32_e32 0, v1 -v_mov_b32_e32 v20, s20 -v_mov_b32_e32 v21, 0 -buffer_store_dword v20, v21, s[0:3], 0 offen -v_mov_b32_e32 v20, s21 -v_mov_b32_e32 v21, 4 -buffer_store_dword v20, v21, s[0:3], 0 offen -v_mov_b32_e32 v20, s22 -v_mov_b32_e32 v21, 8 -buffer_store_dword v20, v21, s[0:3], 0 offen -v_mov_b32_e32 v20, s23 -v_mov_b32_e32 v21, 12 -buffer_store_dword v20, v21, s[0:3], 0 offen -v_mov_b32_e32 v20, s24 -v_mov_b32_e32 v21, 16 -buffer_store_dword v20, v21, s[0:3], 0 offen -v_mov_b32_e32 v20, s25 -v_mov_b32_e32 v21, 20 -buffer_store_dword v20, v21, s[0:3], 0 offen -v_mov_b32_e32 v20, s26 -v_mov_b32_e32 v21, 24 -buffer_store_dword v20, v21, s[0:3], 0 offen -v_mov_b32_e32 v20, s27 -v_mov_b32_e32 v21, 28 -buffer_store_dword v20, v21, s[0:3], 0 offen -s_mov_b32 exec_lo, s6 -s_endpgm diff --git a/runtime/test/shaders/cs_w32_permlane_fi.asm b/runtime/test/shaders/cs_w32_permlane_fi.asm deleted file mode 100644 index 53e753982..000000000 --- a/runtime/test/shaders/cs_w32_permlane_fi.asm +++ /dev/null @@ -1,66 +0,0 @@ -; regen_fixtures: this source has a translator fixture in tests/semantic/fixtures/disasm -; SHADER-74: v_permlane16_b32 / v_permlanex16_b32 with the SOURCE lane off in EXEC (wave32). Hardware measurement on -; RDNA2 by aslan2142 (issue #374): op_sel:[FI, BOUND_CTRL] (LLVM: llvm.amdgcn.permlane16 -> op_sel -; bits 0, 1). FI=1: the value of the off source lane. FI=0, BC=0: the destination lane is not written. FI=0, BC=1: -; the destination lane gets 0. A source lane that is on gives its value whatever FI / BC are. -; EXEC = 0x55555555 (even lanes on). v2 = 3 * lane + 1, destinations start as 1000 + lane. s4/s5 select lane -; (i + 1) & 15 of the row (an odd lane: off), s6/s7 select the lane itself (even: on). Lane 0 stores: -; out[0] permlane16 FI=0 BC=0, source lane 1 (off) -> 1000 (not written) -; out[1] permlane16 FI=0 BC=1, source lane 1 (off) -> 0 -; out[2] permlane16 FI=1 BC=0, source lane 1 (off) -> 4 (3*1+1) -; out[3] permlane16 FI=0 BC=0, source lane 0 (on) -> 1 -; out[4] permlanex16 FI=0 BC=0, source lane 17 (off) -> 1000 (not written) -; out[5] permlanex16 FI=0 BC=1, source lane 17 (off) -> 0 -; out[6] permlanex16 FI=1 BC=0, source lane 17 (off) -> 52 (3*17+1) -; out[7] permlanex16 FI=0 BC=0, source lane 16 (on) -> 49 (3*16+1) -; group: 32,1,1 -; Run: vk_compute_test cs_w32_permlane_fi.spv 1 dump -> out[0..7] = 1000 0 4 1 1000 0 52 49 -; mattr: +wavefrontsize32,-wavefrontsize64 -v_mad_u32_u24 v2, v0, 3, 1 -v_add_nc_u32_e32 v10, 1000, v0 -v_add_nc_u32_e32 v11, 1000, v0 -v_add_nc_u32_e32 v12, 1000, v0 -v_add_nc_u32_e32 v13, 1000, v0 -v_add_nc_u32_e32 v14, 1000, v0 -v_add_nc_u32_e32 v15, 1000, v0 -v_add_nc_u32_e32 v16, 1000, v0 -v_add_nc_u32_e32 v17, 1000, v0 -s_mov_b32 s4, 0x87654321 -s_mov_b32 s5, 0x0fedcba9 -s_mov_b32 s6, 0x76543210 -s_mov_b32 s7, 0xfedcba98 -s_mov_b32 exec_lo, 0x55555555 -v_permlane16_b32 v10, v2, s4, s5 -v_permlane16_b32 v11, v2, s4, s5 op_sel:[0,1] -v_permlane16_b32 v12, v2, s4, s5 op_sel:[1,0] -v_permlane16_b32 v13, v2, s6, s7 -v_permlanex16_b32 v14, v2, s4, s5 -v_permlanex16_b32 v15, v2, s4, s5 op_sel:[0,1] -v_permlanex16_b32 v16, v2, s4, s5 op_sel:[1,0] -v_permlanex16_b32 v17, v2, s6, s7 -v_cmpx_eq_u32_e32 0, v0 -v_mov_b32_e32 v20, v10 -v_mov_b32_e32 v21, 0 -buffer_store_dword v20, v21, s[0:3], 0 offen -v_mov_b32_e32 v20, v11 -v_mov_b32_e32 v21, 4 -buffer_store_dword v20, v21, s[0:3], 0 offen -v_mov_b32_e32 v20, v12 -v_mov_b32_e32 v21, 8 -buffer_store_dword v20, v21, s[0:3], 0 offen -v_mov_b32_e32 v20, v13 -v_mov_b32_e32 v21, 12 -buffer_store_dword v20, v21, s[0:3], 0 offen -v_mov_b32_e32 v20, v14 -v_mov_b32_e32 v21, 16 -buffer_store_dword v20, v21, s[0:3], 0 offen -v_mov_b32_e32 v20, v15 -v_mov_b32_e32 v21, 20 -buffer_store_dword v20, v21, s[0:3], 0 offen -v_mov_b32_e32 v20, v16 -v_mov_b32_e32 v21, 24 -buffer_store_dword v20, v21, s[0:3], 0 offen -v_mov_b32_e32 v20, v17 -v_mov_b32_e32 v21, 28 -buffer_store_dword v20, v21, s[0:3], 0 offen -s_endpgm diff --git a/runtime/test/shaders/cs_w32_permute.asm b/runtime/test/shaders/cs_w32_permute.asm deleted file mode 100644 index fdd066ed5..000000000 --- a/runtime/test/shaders/cs_w32_permute.asm +++ /dev/null @@ -1,80 +0,0 @@ -; regen_fixtures: this source has a translator fixture in tests/semantic/fixtures/disasm -; SHADER-90: ds_permute_b32 vD, vAddr, vData [offset:N], the forward (scatter) permute (RDNA2 ISA, DS opcode 178). -; Every lane that is on in EXEC sends vData to lane ((vAddr + offset) / 4) mod 32; a destination lane nobody sends -; to gets 0 (the ISA's tmp[0..63] = 0), and only lanes that are on in EXEC are written (VDST of the others is kept). -; v0 = lane (LocalInvocationId.x, 0..31), v2 = 7 * lane + 1 (data). Cases with ONE source per destination only: -; (A) addr = (lane + 1) * 4, a rotation: lane l writes lane l + 1, so lane d holds data[d - 1]. -; lane 0 <- lane 31 = 218, lane 5 <- lane 4 = 29. -; (B) addr = (31 - lane) * 4, offset:8, a reversal shifted by two lanes: lane l writes lane (33 - l) mod 32. -; lane 0 <- lane 1 = 8, lane 3 <- lane 30 = 211. -; (C) EXEC = lanes 0-15 (v12 preset to 99), addr = lane * 8: lane l writes lane 2 * l, 0 <= l < 16. -; lane 3 is on but no source targets it: 0 (not its old 99). Lane 4 <- lane 2 = 15. Lane 20 is off in EXEC -; and keeps 99, although lane 10 targets it (data would be 71). -; (D) EXEC = even lanes (v13 preset to 99): an even lane l writes l + 2, an odd lane l writes l + 1 (but is off, -; so it sends nothing). Lane 4 <- lane 2 = 15; the off lane 3, which also targets lane 4, must not win (22). -; Lane 0 and a few others store: out[0..7] = A0 A5 B0 B3 C3 C4 C20 D4 = 218 29 8 211 0 15 99 15. -; group: 32,1,1 -; Run: vk_compute_test cs_w32_permute.spv 1 dump -> out[0..7] = 218 29 8 211 0 15 99 15 -; mattr: +wavefrontsize32,-wavefrontsize64 -v_mad_u32_u24 v2, v0, 7, 1 -v_add_nc_u32_e32 v3, 1, v0 -v_lshlrev_b32_e32 v3, 2, v3 -ds_permute_b32 v10, v3, v2 -v_sub_nc_u32_e32 v4, 31, v0 -v_lshlrev_b32_e32 v4, 2, v4 -ds_permute_b32 v11, v4, v2 offset:8 -v_mov_b32_e32 v12, 99 -v_lshlrev_b32_e32 v5, 3, v0 -s_mov_b32 exec_lo, 0xffff -ds_permute_b32 v12, v5, v2 -s_waitcnt lgkmcnt(0) -s_mov_b32 exec_lo, -1 -v_and_b32_e32 v6, 1, v0 -v_sub_nc_u32_e32 v6, 2, v6 -v_add_nc_u32_e32 v6, v0, v6 -v_lshlrev_b32_e32 v6, 2, v6 -v_mov_b32_e32 v13, 99 -s_mov_b32 exec_lo, 0x55555555 -ds_permute_b32 v13, v6, v2 -s_waitcnt lgkmcnt(0) -s_mov_b32 exec_lo, -1 -v_cmpx_eq_u32_e32 0, v0 -v_mov_b32_e32 v20, v10 -v_mov_b32_e32 v21, 0 -buffer_store_dword v20, v21, s[0:3], 0 offen -s_mov_b32 exec_lo, -1 -v_cmpx_eq_u32_e32 5, v0 -v_mov_b32_e32 v20, v10 -v_mov_b32_e32 v21, 4 -buffer_store_dword v20, v21, s[0:3], 0 offen -s_mov_b32 exec_lo, -1 -v_cmpx_eq_u32_e32 0, v0 -v_mov_b32_e32 v20, v11 -v_mov_b32_e32 v21, 8 -buffer_store_dword v20, v21, s[0:3], 0 offen -s_mov_b32 exec_lo, -1 -v_cmpx_eq_u32_e32 3, v0 -v_mov_b32_e32 v20, v11 -v_mov_b32_e32 v21, 12 -buffer_store_dword v20, v21, s[0:3], 0 offen -s_mov_b32 exec_lo, -1 -v_cmpx_eq_u32_e32 3, v0 -v_mov_b32_e32 v20, v12 -v_mov_b32_e32 v21, 16 -buffer_store_dword v20, v21, s[0:3], 0 offen -s_mov_b32 exec_lo, -1 -v_cmpx_eq_u32_e32 4, v0 -v_mov_b32_e32 v20, v12 -v_mov_b32_e32 v21, 20 -buffer_store_dword v20, v21, s[0:3], 0 offen -s_mov_b32 exec_lo, -1 -v_cmpx_eq_u32_e32 20, v0 -v_mov_b32_e32 v20, v12 -v_mov_b32_e32 v21, 24 -buffer_store_dword v20, v21, s[0:3], 0 offen -s_mov_b32 exec_lo, -1 -v_cmpx_eq_u32_e32 4, v0 -v_mov_b32_e32 v20, v13 -v_mov_b32_e32 v21, 28 -buffer_store_dword v20, v21, s[0:3], 0 offen -s_endpgm diff --git a/runtime/test/shaders/cs_w32_salu64.asm b/runtime/test/shaders/cs_w32_salu64.asm deleted file mode 100644 index 049e92bd8..000000000 --- a/runtime/test/shaders/cs_w32_salu64.asm +++ /dev/null @@ -1,68 +0,0 @@ -; regen_fixtures: this source has a translator fixture in tests/semantic/fixtures/disasm -; 64-bit scalar data ops and v_mad_u64_u32 (#723 #726 #729 #733 #549 #613 #546), run once on a GPU. -; Lane 0 of a wave32 group computes one result per op and stores eight dwords: -; out[0] = low word of s_brev_b64(0x12345678_0000000F) = 0x1E6A2C48 (reverse(S0.hi)) -; out[1] = low word of s_bfe_u64(0x00000123_45678000, w16 o28) = 0x1234 (bits 43..28) -; out[2] = high word of s_bfe_i64(0x00000001_80000000, w2 o31) = 0xFFFFFFFF (field 0b11 = -1, sign-extended) -; out[3] = high word of s_bitset1_b64(0, 40) = 0x100 (bit 40) -; out[4] = s_flbit_i32_b64(0x00000000_00010000) = 47 (zeros above bit 16) -; out[5] = s_flbit_i32_i64(0xFFFFFFFF_FFFF0000) = 48 (first bit unlike the sign: 15) -; out[6] = s_cmov_b32 (SCC = 1) of s_sext_i32_i16(0x00018000) = 0xFFFF8000 -; out[7] = high word of v_mad_u64_u32(0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF_FFFFFFFF) = 0xFFFFFFFE (carry dropped) -; group: 32,1,1 -; Run: vk_compute_test cs_w32_salu64.spv 1 dump -> out[0..7] = 510274632 4660 4294967295 256 47 48 4294934528 4294967294 -; mattr: +wavefrontsize32,-wavefrontsize64 -s_mov_b32 s6, 15 -s_mov_b32 s7, 0x12345678 -s_brev_b64 s[8:9], s[6:7] -s_mov_b32 s6, 0x45678000 -s_mov_b32 s7, 0x123 -s_mov_b32 s10, 0x10001c -s_bfe_u64 s[10:11], s[6:7], s10 -s_mov_b32 s6, 0x80000000 -s_mov_b32 s7, 1 -s_mov_b32 s12, 0x2001f -s_bfe_i64 s[12:13], s[6:7], s12 -s_mov_b32 s14, 0 -s_mov_b32 s15, 0 -s_bitset1_b64 s[14:15], 40 -s_mov_b32 s6, 0x10000 -s_mov_b32 s7, 0 -s_flbit_i32_b64 s16, s[6:7] -s_mov_b32 s6, 0xffff0000 -s_mov_b32 s7, -1 -s_flbit_i32_i64 s17, s[6:7] -s_mov_b32 s19, 0x18000 -s_sext_i32_i16 s18, s19 -s_mov_b32 s20, 0x5eed -s_cmp_eq_u32 s19, 0x18000 -s_cmov_b32 s20, s18 -v_mov_b32_e32 v4, -1 -v_mov_b32_e32 v6, -1 -v_mov_b32_e32 v7, -1 -v_mad_u64_u32 v[2:3], s22, v4, v4, v[6:7] -v_cmpx_eq_u32_e32 0, v0 -v_mov_b32_e32 v20, s8 -v_mov_b32_e32 v21, 0 -buffer_store_dword v20, v21, s[0:3], 0 offen -v_mov_b32_e32 v20, s10 -v_mov_b32_e32 v21, 4 -buffer_store_dword v20, v21, s[0:3], 0 offen -v_mov_b32_e32 v20, s13 -v_mov_b32_e32 v21, 8 -buffer_store_dword v20, v21, s[0:3], 0 offen -v_mov_b32_e32 v20, s15 -v_mov_b32_e32 v21, 12 -buffer_store_dword v20, v21, s[0:3], 0 offen -v_mov_b32_e32 v20, s16 -v_mov_b32_e32 v21, 16 -buffer_store_dword v20, v21, s[0:3], 0 offen -v_mov_b32_e32 v20, s17 -v_mov_b32_e32 v21, 20 -buffer_store_dword v20, v21, s[0:3], 0 offen -v_mov_b32_e32 v20, s20 -v_mov_b32_e32 v21, 24 -buffer_store_dword v20, v21, s[0:3], 0 offen -v_mov_b32_e32 v21, 28 -buffer_store_dword v3, v21, s[0:3], 0 offen -s_endpgm diff --git a/runtime/test/shaders/cs_w32_sincos.asm b/runtime/test/shaders/cs_w32_sincos.asm deleted file mode 100644 index 6777867da..000000000 --- a/runtime/test/shaders/cs_w32_sincos.asm +++ /dev/null @@ -1,60 +0,0 @@ -; SHADER-88: v_sin_f32 / v_cos_f32 take the angle in turns and must reduce it in turns before scaling by 2*pi. -; Six large-angle cases (254.25, 254.5, -200.75, 100.3, 254.51, -254.51 turns); each stores 1 when -; |result - reference| < 1e-3 (the reference is sin/cos(2*pi*x) in double; a Vulkan Sin/Cos is only guaranteed to -; 2^-11 = 4.9e-4 in [-pi, pi], so the shader compares with a tolerance and stores a flag, not the float). -; Lane 0 stores out[0..5] = 1 1 1 1 1 1. (Expected references, f32 bits: 1.0, -1.0, 1.0, 0xbe9e39de, -; 0xbd808642, 0xbf7f7ed2.) -; group: 32,1,1 -; Run: vk_compute_test cs_w32_sincos.spv 1 dump -> out[0..5] = 1 1 1 1 1 1 -; mattr: +wavefrontsize32,-wavefrontsize64 -v_mov_b32_e32 v9, 0x3a83126f -v_cmpx_eq_u32_e32 0, v0 -v_mov_b32_e32 v1, 0x437e4000 -v_sin_f32_e32 v2, v1 -v_sub_f32_e32 v2, 0x3f800000, v2 -v_and_b32_e32 v2, 0x7fffffff, v2 -v_cmp_gt_f32_e32 vcc_lo, v9, v2 -v_cndmask_b32_e64 v20, 0, 1, vcc_lo -v_mov_b32_e32 v21, 0 -buffer_store_dword v20, v21, s[0:3], 0 offen -v_mov_b32_e32 v1, 0x437e8000 -v_cos_f32_e32 v2, v1 -v_sub_f32_e32 v2, 0xbf800000, v2 -v_and_b32_e32 v2, 0x7fffffff, v2 -v_cmp_gt_f32_e32 vcc_lo, v9, v2 -v_cndmask_b32_e64 v20, 0, 1, vcc_lo -v_mov_b32_e32 v21, 4 -buffer_store_dword v20, v21, s[0:3], 0 offen -v_mov_b32_e32 v1, 0xc348c000 -v_sin_f32_e32 v2, v1 -v_sub_f32_e32 v2, 0x3f800000, v2 -v_and_b32_e32 v2, 0x7fffffff, v2 -v_cmp_gt_f32_e32 vcc_lo, v9, v2 -v_cndmask_b32_e64 v20, 0, 1, vcc_lo -v_mov_b32_e32 v21, 8 -buffer_store_dword v20, v21, s[0:3], 0 offen -v_mov_b32_e32 v1, 0x42c8999a -v_cos_f32_e32 v2, v1 -v_sub_f32_e32 v2, 0xbe9e39de, v2 -v_and_b32_e32 v2, 0x7fffffff, v2 -v_cmp_gt_f32_e32 vcc_lo, v9, v2 -v_cndmask_b32_e64 v20, 0, 1, vcc_lo -v_mov_b32_e32 v21, 12 -buffer_store_dword v20, v21, s[0:3], 0 offen -v_mov_b32_e32 v1, 0x437e828f -v_sin_f32_e32 v2, v1 -v_sub_f32_e32 v2, 0xbd808642, v2 -v_and_b32_e32 v2, 0x7fffffff, v2 -v_cmp_gt_f32_e32 vcc_lo, v9, v2 -v_cndmask_b32_e64 v20, 0, 1, vcc_lo -v_mov_b32_e32 v21, 16 -buffer_store_dword v20, v21, s[0:3], 0 offen -v_mov_b32_e32 v1, 0xc37e828f -v_cos_f32_e32 v2, v1 -v_sub_f32_e32 v2, 0xbf7f7ed2, v2 -v_and_b32_e32 v2, 0x7fffffff, v2 -v_cmp_gt_f32_e32 vcc_lo, v9, v2 -v_cndmask_b32_e64 v20, 0, 1, vcc_lo -v_mov_b32_e32 v21, 20 -buffer_store_dword v20, v21, s[0:3], 0 offen -s_endpgm diff --git a/runtime/test/shaders/cs_w64_ds_append.asm b/runtime/test/shaders/cs_w64_ds_append.asm deleted file mode 100644 index a837f1bc8..000000000 --- a/runtime/test/shaders/cs_w64_ds_append.asm +++ /dev/null @@ -1,65 +0,0 @@ -; regen_fixtures: this source has a translator fixture in tests/semantic/fixtures/disasm -; ds_append / ds_consume (LDS) in a wave64: one add / subtract of the wave's active-lane count (both halves) at the -; offset address, the old value to every active lane. Measured natively on RDNA2 gfx1036 (tools/hw_oracle raw -; kernels): EXEC = lanes 0, 32 and 63 appends 3 and returns 100 to those three lanes. The translator has the first -; active lane do it and sends the old value to the others (a subgroup shuffle on a 64-wide subgroup, an exchange -; round under --wave64-emulate). Until this change both raised Unsupported. -; LDS words: [0] = 100, [2] (byte 8) = 200, written by every lane first. -; EXEC = lanes 0, 32, 63: ds_append v8 -> v8 = 100 in those lanes; LDS[0] = 103 -; EXEC = lane 33: ds_consume v9 offset:8 -> v9 = 200 in lane 33; LDS[2] = 199 -; EXEC = all (64 lanes): ds_append v10 -> v10 = 103 everywhere; LDS[0] = 167 -; Lane 0 stores: -; out[0] v8 of lane 63 = 100 out[1] v8 of lane 32 = 100 out[2] v8 of lane 1 (off) = 0xdead -; out[3] LDS[0] read by lane 0 after its append = 103 out[4] v9 of lane 33 = 200 -; out[5] LDS[2] read by lane 33 after its consume = 199 out[6] v10 of lane 40 = 103 out[7] LDS[0] = 167 -; rsrc2: 0x40088 -; Run: VKC_SUBGROUP_SIZE=64 vk_compute_test cs_w64_ds_append.spv 1 dump --require-wave64 -; (or translated with --wave64-emulate, on any subgroup size) -> out[0..7] = 100 100 57005 103 200 199 103 167 -; mattr: +wavefrontsize64,-wavefrontsize32 -v_mov_b32_e32 v8, 0xdead -v_mov_b32_e32 v9, 0xdead -v_mov_b32_e32 v1, 0 -v_mov_b32_e32 v2, 100 -v_mov_b32_e32 v3, 200 -ds_write_b32 v1, v2 -ds_write_b32 v1, v3 offset:8 -s_waitcnt lgkmcnt(0) -s_mov_b32 exec_lo, 1 -s_mov_b32 exec_hi, 0x80000001 -ds_append v8 -s_waitcnt lgkmcnt(0) -ds_read_b32 v11, v1 -s_waitcnt lgkmcnt(0) -s_mov_b32 exec_lo, 0 -s_mov_b32 exec_hi, 2 -ds_consume v9 offset:8 -s_waitcnt lgkmcnt(0) -ds_read_b32 v12, v1 offset:8 -s_waitcnt lgkmcnt(0) -s_mov_b64 exec, -1 -ds_append v10 -s_waitcnt lgkmcnt(0) -ds_read_b32 v13, v1 -s_waitcnt lgkmcnt(0) -v_readlane_b32 s20, v8, 63 -v_readlane_b32 s21, v8, 32 -v_readlane_b32 s22, v8, 1 -v_readlane_b32 s23, v11, 0 -v_readlane_b32 s24, v9, 33 -v_readlane_b32 s25, v12, 33 -v_readlane_b32 s26, v10, 40 -v_readlane_b32 s27, v13, 0 -v_mov_b32_e32 v14, s20 -v_mov_b32_e32 v15, s21 -v_mov_b32_e32 v16, s22 -v_mov_b32_e32 v17, s23 -v_mov_b32_e32 v18, s24 -v_mov_b32_e32 v19, s25 -v_mov_b32_e32 v20, s26 -v_mov_b32_e32 v21, s27 -v_cmpx_eq_u32_e32 0, v0 -v_mov_b32_e32 v22, 0 -buffer_store_dwordx4 v[14:17], v22, s[0:3], 0 offen -v_mov_b32_e32 v22, 16 -buffer_store_dwordx4 v[18:21], v22, s[0:3], 0 offen -s_endpgm diff --git a/runtime/test/shaders/cs_w64_exec_computed.asm b/runtime/test/shaders/cs_w64_exec_computed.asm deleted file mode 100644 index 013b2c190..000000000 --- a/runtime/test/shaders/cs_w64_exec_computed.asm +++ /dev/null @@ -1,114 +0,0 @@ -; regen_fixtures: this source has a translator fixture in tests/semantic/fixtures/disasm -; SHADER-1264, wave64: a computed 32-bit value written to exec_lo or exec_hi in a 64-thread wave (v0 = lane 0..63) -; turns on exactly the lanes of that half whose bit is set (lane L of exec_hi takes bit L - 32), and leaves the other -; half alone. The wave32 form is cs_w32_exec_computed.asm. The base value comes from v_readfirstlane_b32 (s4 = 0), so -; the translator can't fold the writes into constants. For each case a VALU write marks the lanes that ran it; with -; EXEC = all lanes again, a v_cmp turns the marks into a lane mask and the word is s_bcnt1_i32_b64 << 8 | s_ff1_i32_b64. -; 1) exec_lo = 0; s_lshl_b32 exec_hi, 1, s5 (= 3): lane 35. out[0] = 1 << 8 | 35 = 291 -; 2) exec_hi = 0; s_add_u32 exec_lo, s4, 0xf0: lanes 4..7. out[1] = 4 << 8 | 4 = 1028 -; 3) exec_lo = -1; s_bfm_b32 exec_hi, s6 = 12, s7 = 16 (0x0fff0000): lanes 0..31, 48..59. out[2] = 44 << 8 | 0 = 11264 -; 4) s_lshl_b32 exec_lo, 1, s5; s_add_u32 exec_hi, s4, 0x81: lanes 3, 32, 39. out[3] = 3 << 8 | 3 = 771 -; 5) s_mov_b32 exec_lo, s9 (= 0x81, a number); s_not_b32 exec_hi, s5 (= 0xfffffffc): -; lanes 0, 7 and 34..63. out[4] = 32 << 8 | 0 = 8192 -; 6) a lane mask AND a number: VCC = lanes 0..51 (vcc_hi = 0x000fffff), exec_lo = 0, -; s_and_b32 exec_hi, vcc_hi, s8 (= 0xffff0) = 0x000ffff0: lanes 36..51. out[5] = 16 << 8 | 36 = 4132 -; out[6] = s4 = 0 and out[7] = s5 = 3 check the base values. -; Testing the value for non-zero instead (main before SHADER-1264) turns on the whole half in 1-4: -; 8224 8192 16384 16384 (measured with --wave64-emulate on an RTX 5070). Cases 5-6 were right before the fix. -; Lane 0 stores the eight words. -; group: 64,1,1 -; Run: VKC_SUBGROUP_SIZE=64 vk_compute_test cs_w64_exec_computed.spv 1 dump --require-wave64 -; (or translated with --wave64-emulate, on any subgroup size) -> out[0..7] = 291 1028 11264 771 8192 4132 0 3 -; mattr: +wavefrontsize64,-wavefrontsize32 -v_mov_b32_e32 v10, 0 -v_mov_b32_e32 v11, 0 -v_mov_b32_e32 v12, 0 -v_mov_b32_e32 v13, 0 -v_mov_b32_e32 v14, 0 -v_mov_b32_e32 v15, 0 -v_readfirstlane_b32 s4, v0 -s_add_u32 s5, s4, 3 -s_add_u32 s6, s4, 12 -s_add_u32 s7, s4, 16 -s_add_u32 s8, s4, 0xffff0 -s_add_u32 s9, s4, 0x81 -s_mov_b32 exec_lo, 0 -s_lshl_b32 exec_hi, 1, s5 -v_mov_b32_e32 v10, 1 -s_mov_b64 exec, -1 -s_mov_b32 exec_hi, 0 -s_add_u32 exec_lo, s4, 0xf0 -v_mov_b32_e32 v11, 1 -s_mov_b64 exec, -1 -s_bfm_b32 exec_hi, s6, s7 -v_mov_b32_e32 v12, 1 -s_mov_b64 exec, -1 -s_lshl_b32 exec_lo, 1, s5 -s_add_u32 exec_hi, s4, 0x81 -v_mov_b32_e32 v13, 1 -s_mov_b64 exec, -1 -s_mov_b32 exec_lo, s9 -s_not_b32 exec_hi, s5 -v_mov_b32_e32 v14, 1 -s_mov_b64 exec, -1 -v_cmp_gt_u32_e32 vcc, 52, v0 -s_mov_b32 exec_lo, 0 -s_and_b32 exec_hi, vcc_hi, s8 -v_mov_b32_e32 v15, 1 -s_mov_b64 exec, -1 -v_cmp_ne_u32_e32 vcc, 0, v10 -s_bcnt1_i32_b64 s10, vcc -s_ff1_i32_b64 s11, vcc -s_lshl_b32 s10, s10, 8 -s_or_b32 s10, s10, s11 -v_cmp_ne_u32_e32 vcc, 0, v11 -s_bcnt1_i32_b64 s12, vcc -s_ff1_i32_b64 s11, vcc -s_lshl_b32 s12, s12, 8 -s_or_b32 s12, s12, s11 -v_cmp_ne_u32_e32 vcc, 0, v12 -s_bcnt1_i32_b64 s13, vcc -s_ff1_i32_b64 s11, vcc -s_lshl_b32 s13, s13, 8 -s_or_b32 s13, s13, s11 -v_cmp_ne_u32_e32 vcc, 0, v13 -s_bcnt1_i32_b64 s14, vcc -s_ff1_i32_b64 s11, vcc -s_lshl_b32 s14, s14, 8 -s_or_b32 s14, s14, s11 -v_cmp_ne_u32_e32 vcc, 0, v14 -s_bcnt1_i32_b64 s15, vcc -s_ff1_i32_b64 s11, vcc -s_lshl_b32 s15, s15, 8 -s_or_b32 s15, s15, s11 -v_cmp_ne_u32_e32 vcc, 0, v15 -s_bcnt1_i32_b64 s16, vcc -s_ff1_i32_b64 s11, vcc -s_lshl_b32 s16, s16, 8 -s_or_b32 s16, s16, s11 -v_cmpx_eq_u32_e32 0, v0 -v_mov_b32_e32 v20, s10 -v_mov_b32_e32 v21, 0 -buffer_store_dword v20, v21, s[0:3], 0 offen -v_mov_b32_e32 v20, s12 -v_mov_b32_e32 v21, 4 -buffer_store_dword v20, v21, s[0:3], 0 offen -v_mov_b32_e32 v20, s13 -v_mov_b32_e32 v21, 8 -buffer_store_dword v20, v21, s[0:3], 0 offen -v_mov_b32_e32 v20, s14 -v_mov_b32_e32 v21, 12 -buffer_store_dword v20, v21, s[0:3], 0 offen -v_mov_b32_e32 v20, s15 -v_mov_b32_e32 v21, 16 -buffer_store_dword v20, v21, s[0:3], 0 offen -v_mov_b32_e32 v20, s16 -v_mov_b32_e32 v21, 20 -buffer_store_dword v20, v21, s[0:3], 0 offen -v_mov_b32_e32 v20, s4 -v_mov_b32_e32 v21, 24 -buffer_store_dword v20, v21, s[0:3], 0 offen -v_mov_b32_e32 v20, s5 -v_mov_b32_e32 v21, 28 -buffer_store_dword v20, v21, s[0:3], 0 offen -s_endpgm diff --git a/runtime/test/shaders/cs_w64_mask_detect.asm b/runtime/test/shaders/cs_w64_mask_detect.asm deleted file mode 100644 index 249e89a9f..000000000 --- a/runtime/test/shaders/cs_w64_mask_detect.asm +++ /dev/null @@ -1,16 +0,0 @@ -; Wave64 detection from a 64-bit lane-mask op alone (#210 part 2 / SHADER-28). -; mattr: +wavefrontsize64,-wavefrontsize32 -; No exec_hi / mbcnt_hi / *_saveexec_b64 / *_wrexec_b64 and no _b64 op on exec/vcc: only s_bcnt1_i32_b64 -; on an ordinary SGPR pair. Lanes where (lane & 5) != 0: 48 of 64. A wave32 mis-detect counts 24. -; Run: VKC_SUBGROUP_SIZE=64 vk_compute_test cs_w64_mask_detect.spv 1 dump --require-wave64 -; -> out[0] = 48 -; With LEONIDA_W64_EMULATE=1 the same on a 32-wide subgroup. -; Every lane stores the count at lane * 4, so the 64 lanes fill the 256 bytes vk_compute_test gives one group. (At -; lane * 64, lanes 4-63 wrote past the buffer through its device address: the V# allows any offset.) -v_and_b32_e32 v5, 5, v0 -v_cmp_ne_u32_e64 s[20:21], 0, v5 -s_bcnt1_i32_b64 s30, s[20:21] -v_mov_b32 v1, s30 -v_lshlrev_b32_e32 v13, 2, v0 -buffer_store_dword v1, v13, s[0:3], 0 offen -s_endpgm diff --git a/runtime/test/shaders/cs_w64_mask_imm.asm b/runtime/test/shaders/cs_w64_mask_imm.asm deleted file mode 100644 index 353daf363..000000000 --- a/runtime/test/shaders/cs_w64_mask_imm.asm +++ /dev/null @@ -1,117 +0,0 @@ -; regen_fixtures: this source has a translator fixture in tests/semantic/fixtures/disasm -; Constant lane masks in wave64 (s_and/or/andn2_saveexec_b64, s_andn2_wrexec_b64, s_and_b64 / s_not_b64 into EXEC, -; s_mov_b64 exec/vcc) and s_bcnt1_i32_b64 of a constant. A constant read as a 64-bit lane mask gives lane L bit L -; of the 64-bit value: an inline constant is sign-extended (-16 = lanes 4-63), a literal is the low word with a -; zero high word (as Gen.src64_data reads 64-bit constants; the literals here are below 0x80000000, so a -; sign-extending reading would give the same words). Until 2026-11-22 the translator gave every lane bit 0 of the -; constant (Gen.mask_src), and s_bcnt1_i32_b64 counted that lane's copy. -; Each case sets EXEC, runs the op and marks the lanes it leaves on; with EXEC back to all lanes, v_cmp turns the -; marks into a lane mask and lane 0 stores word = (set lanes) | (lowest set lane) << 8 (no lane: 0xffffff00). -; out[0] EXEC=all, s_and_saveexec_b64 0xff00 -> lanes 8-15 8 | 8<<8 = 2056 -; out[1] EXEC=all, s_and_b64 exec, exec, -16 -> lanes 4-63 60 | 4<<8 = 1084 -; out[2] s_mov_b64 exec, 0x10; s_andn2_saveexec_b64 -8 -> bits 3-63 & ~bit 4 = 3, 5-63 60 | 3<<8 = 828 -; out[3] s_mov_b64 exec, 0xf0f0; s_andn2_wrexec_b64 0xff00 -> 0x0f00 = lanes 8-11 4 | 8<<8 = 2052 -; out[4] s_mov_b64 exec, 0; s_or_saveexec_b64 -2 -> lanes 1-63 63 | 1<<8 = 319 -; out[5] s_not_b64 exec, 0xff -> lanes 8-63 56 | 8<<8 = 2104 -; out[6] s_mov_b64 vcc, 0x3c; v_cndmask_b32_e32 v, 0, v(=1), vcc -> lanes 2-5 4 | 2<<8 = 516 -; out[7] s_bcnt1_i32_b64 0xff00ff | s_ff1_i32_b64 0xff00 << 8 (scalar data) 16 | 8<<8 = 2064 -; Bit 0 for every lane (the old translation) gives 0xffffff00 in out[0..6] and 2080 in out[7]. -; (llvm-mc rejects a constant as the lane-mask operand of v_cndmask_b32_e64 / v_add_co_ci_u32_e64, and prints one -; it decodes as "Invalid immediate", so those VALU forms never reach the translator with a constant.) -; Run: VKC_SUBGROUP_SIZE=64 vk_compute_test cs_w64_mask_imm.spv 1 dump --require-wave64 -; (or translated with --wave64-emulate, on any subgroup size) -> out[0..7] = 2056 1084 828 2052 319 2104 516 2064 -; mattr: +wavefrontsize64,-wavefrontsize32 -v_mov_b32_e32 v10, 0 -v_mov_b32_e32 v11, 0 -v_mov_b32_e32 v12, 0 -v_mov_b32_e32 v13, 0 -v_mov_b32_e32 v14, 0 -v_mov_b32_e32 v15, 0 -v_mov_b32_e32 v16, 0 -s_mov_b64 exec, -1 -s_and_saveexec_b64 s[8:9], 0xff00 -v_mov_b32_e32 v10, 1 -s_mov_b64 exec, -1 -s_and_b64 exec, exec, -16 -v_mov_b32_e32 v11, 1 -s_mov_b64 exec, 0x10 -s_andn2_saveexec_b64 s[8:9], -8 -v_mov_b32_e32 v12, 1 -s_mov_b64 exec, 0xf0f0 -s_andn2_wrexec_b64 s[8:9], 0xff00 -v_mov_b32_e32 v13, 1 -s_mov_b64 exec, 0 -s_or_saveexec_b64 s[8:9], -2 -v_mov_b32_e32 v14, 1 -s_not_b64 exec, 0xff -v_mov_b32_e32 v15, 1 -s_mov_b64 exec, -1 -s_mov_b64 vcc, 0x3c -v_mov_b32_e32 v18, 1 -v_cndmask_b32_e32 v16, 0, v18, vcc -s_mov_b64 exec, -1 -v_cmp_ne_u32_e32 vcc, 0, v10 -s_bcnt1_i32_b64 s20, vcc -s_ff1_i32_b64 s21, vcc -s_lshl_b32 s21, s21, 8 -s_or_b32 s20, s20, s21 -v_cmp_ne_u32_e32 vcc, 0, v11 -s_bcnt1_i32_b64 s22, vcc -s_ff1_i32_b64 s23, vcc -s_lshl_b32 s23, s23, 8 -s_or_b32 s22, s22, s23 -v_cmp_ne_u32_e32 vcc, 0, v12 -s_bcnt1_i32_b64 s24, vcc -s_ff1_i32_b64 s25, vcc -s_lshl_b32 s25, s25, 8 -s_or_b32 s24, s24, s25 -v_cmp_ne_u32_e32 vcc, 0, v13 -s_bcnt1_i32_b64 s26, vcc -s_ff1_i32_b64 s27, vcc -s_lshl_b32 s27, s27, 8 -s_or_b32 s26, s26, s27 -v_cmp_ne_u32_e32 vcc, 0, v14 -s_bcnt1_i32_b64 s28, vcc -s_ff1_i32_b64 s29, vcc -s_lshl_b32 s29, s29, 8 -s_or_b32 s28, s28, s29 -v_cmp_ne_u32_e32 vcc, 0, v15 -s_bcnt1_i32_b64 s30, vcc -s_ff1_i32_b64 s31, vcc -s_lshl_b32 s31, s31, 8 -s_or_b32 s30, s30, s31 -v_cmp_ne_u32_e32 vcc, 0, v16 -s_bcnt1_i32_b64 s32, vcc -s_ff1_i32_b64 s33, vcc -s_lshl_b32 s33, s33, 8 -s_or_b32 s32, s32, s33 -s_bcnt1_i32_b64 s34, 0xff00ff -s_ff1_i32_b64 s35, 0xff00 -s_lshl_b32 s35, s35, 8 -s_or_b32 s34, s34, s35 -v_cmpx_eq_u32_e32 0, v0 -v_mov_b32_e32 v1, s20 -v_mov_b32_e32 v2, 0 -buffer_store_dword v1, v2, s[0:3], 0 offen -v_mov_b32_e32 v1, s22 -v_mov_b32_e32 v2, 4 -buffer_store_dword v1, v2, s[0:3], 0 offen -v_mov_b32_e32 v1, s24 -v_mov_b32_e32 v2, 8 -buffer_store_dword v1, v2, s[0:3], 0 offen -v_mov_b32_e32 v1, s26 -v_mov_b32_e32 v2, 12 -buffer_store_dword v1, v2, s[0:3], 0 offen -v_mov_b32_e32 v1, s28 -v_mov_b32_e32 v2, 16 -buffer_store_dword v1, v2, s[0:3], 0 offen -v_mov_b32_e32 v1, s30 -v_mov_b32_e32 v2, 20 -buffer_store_dword v1, v2, s[0:3], 0 offen -v_mov_b32_e32 v1, s32 -v_mov_b32_e32 v2, 24 -buffer_store_dword v1, v2, s[0:3], 0 offen -v_mov_b32_e32 v1, s34 -v_mov_b32_e32 v2, 28 -buffer_store_dword v1, v2, s[0:3], 0 offen -s_endpgm diff --git a/runtime/test/shaders/cs_w64x_andn2_exec.asm b/runtime/test/shaders/cs_w64x_andn2_exec.asm deleted file mode 100644 index ac0cbd31b..000000000 --- a/runtime/test/shaders/cs_w64x_andn2_exec.asm +++ /dev/null @@ -1,89 +0,0 @@ -; regen_fixtures: this source has a translator fixture in tests/semantic/fixtures/disasm -; s_andn2_saveexec_b64 and s_andn2_wrexec_b64 in one 64-lane wave (v1 = lane 0..63). Neither had a test; the _b32 -; forms are in cs_w32_andn2_exec.asm. -; RDNA2 ISA: s_andn2_saveexec_b64: D = EXEC; EXEC = S0 & ~EXEC; SCC = (EXEC != 0) -; s_andn2_wrexec_b64: EXEC = S0 & ~EXEC; D = EXEC; SCC = (EXEC != 0) (D gets the new EXEC) -; S0 is a compare result in VCC, written with all 64 lanes on. The masks are only looked at through mask-aware -; instructions (s_bcnt1, s_ff1, EXEC writes), not read as data. Each result has lanes in one half of the wave -; only, so an EXEC or an SCC taken from the other half alone shows. -; 1) VCC = lanes 40..63; EXEC = lanes 16..47 (exec_lo 0xffff0000, exec_hi 0x0000ffff). -; saveexec: D = lanes 16..47, EXEC = lanes 40..63 without 16..47 = lanes 48..63 (the low half is empty), SCC 1. -; out[0] = s_cselect 1/2 = 1; out[1] = s_bcnt1(EXEC) = 16; out[2] = s_bcnt1(EXEC after EXEC = D) = 32; -; v2 = 1 under the new EXEC only, so the lanes with v2 != 0 are 48..63: out[3] = bcnt << 8 | ff1 = 16 << 8 | 48 = 4144. -; 2) VCC = lanes with bit 3 clear (0x00ff00ff in each half); EXEC = exec_lo 0x0f0f0f0f, exec_hi 0xffffffff. -; wrexec: EXEC = lanes 4-7 and 20-23 (0x00f000f0; the high half is empty), D = the same, SCC 1. -; out[4] = bcnt << 8 | ff1 of EXEC = 8 << 8 | 4 = 2052; out[5] = s_cselect 3/4 = 3; -; out[6] = s_bcnt1(D) = 8 (D = the old EXEC would give 48). -; 3) VCC = lanes 0..7. EXEC = lanes 0..47, saveexec: EXEC = 0, SCC 0 -> s_cselect 5/6 = 6; -; EXEC = all 64, wrexec: EXEC = 0, SCC 0 -> s_cselect 7/8 = 8. out[7] = 6 << 8 | 8 = 1544. -; Lane 0 stores the eight words. -; Run: vk_compute_test cs_w64x_andn2_exec.spv 1 dump --require-wave64 -; -> out[0..7] = 1 16 32 4144 2052 3 8 1544 -; mattr: +wavefrontsize64,-wavefrontsize32 -v_mbcnt_lo_u32_b32 v1, -1, 0 -v_mbcnt_hi_u32_b32 v1, -1, v1 -v_mov_b32_e32 v2, 0 -v_cmp_le_u32_e32 vcc, 40, v1 -s_mov_b32 exec_lo, 0xffff0000 -s_mov_b32 exec_hi, 0xffff -s_andn2_saveexec_b64 s[6:7], vcc -s_cselect_b32 s8, 1, 2 -s_bcnt1_i32_b64 s9, exec -v_mov_b32_e32 v2, 1 -s_mov_b64 exec, s[6:7] -s_bcnt1_i32_b64 s10, exec -s_mov_b64 exec, -1 -v_cmp_ne_u32_e32 vcc, 0, v2 -s_bcnt1_i32_b64 s11, vcc -s_ff1_i32_b64 s12, vcc -s_lshl_b32 s11, s11, 8 -s_or_b32 s11, s11, s12 -v_and_b32_e32 v3, 8, v1 -v_cmp_eq_u32_e32 vcc, 0, v3 -s_mov_b32 exec_lo, 0xf0f0f0f -s_mov_b32 exec_hi, -1 -s_andn2_wrexec_b64 s[14:15], vcc -s_cselect_b32 s16, 3, 4 -s_bcnt1_i32_b64 s17, exec -s_ff1_i32_b64 s18, exec -s_lshl_b32 s17, s17, 8 -s_or_b32 s17, s17, s18 -s_mov_b64 exec, -1 -s_bcnt1_i32_b64 s19, s[14:15] -v_cmp_gt_u32_e32 vcc, 8, v1 -s_mov_b32 exec_lo, -1 -s_mov_b32 exec_hi, 0xffff -s_andn2_saveexec_b64 s[20:21], vcc -s_cselect_b32 s22, 5, 6 -s_mov_b64 exec, -1 -s_andn2_wrexec_b64 s[24:25], vcc -s_cselect_b32 s23, 7, 8 -s_mov_b64 exec, -1 -s_lshl_b32 s22, s22, 8 -s_or_b32 s22, s22, s23 -v_cmpx_eq_u32_e32 0, v1 -v_mov_b32_e32 v20, s8 -v_mov_b32_e32 v21, 0 -buffer_store_dword v20, v21, s[0:3], 0 offen -v_mov_b32_e32 v20, s9 -v_mov_b32_e32 v21, 4 -buffer_store_dword v20, v21, s[0:3], 0 offen -v_mov_b32_e32 v20, s10 -v_mov_b32_e32 v21, 8 -buffer_store_dword v20, v21, s[0:3], 0 offen -v_mov_b32_e32 v20, s11 -v_mov_b32_e32 v21, 12 -buffer_store_dword v20, v21, s[0:3], 0 offen -v_mov_b32_e32 v20, s17 -v_mov_b32_e32 v21, 16 -buffer_store_dword v20, v21, s[0:3], 0 offen -v_mov_b32_e32 v20, s16 -v_mov_b32_e32 v21, 20 -buffer_store_dword v20, v21, s[0:3], 0 offen -v_mov_b32_e32 v20, s19 -v_mov_b32_e32 v21, 24 -buffer_store_dword v20, v21, s[0:3], 0 offen -v_mov_b32_e32 v20, s22 -v_mov_b32_e32 v21, 28 -buffer_store_dword v20, v21, s[0:3], 0 offen -s_endpgm diff --git a/runtime/test/shaders/cs_w64x_ballot.asm b/runtime/test/shaders/cs_w64x_ballot.asm deleted file mode 100644 index cd616f878..000000000 --- a/runtime/test/shaders/cs_w64x_ballot.asm +++ /dev/null @@ -1,22 +0,0 @@ -; regen_fixtures: this source has a translator fixture in tests/semantic/fixtures/disasm -; Wave64 ballot + v_mbcnt prefix-count stream compaction across both halves. Selected lanes: (lane & 7) == 5, that -; is lanes 5, 13, 21, 29 (low half) and 37, 45, 53, 61 (upper half). The ballot is v_cmp_*_e64 into s[4:5]; s_bcnt1 -; of it = 8 (a 32-wide subgroup sees one half: 4). The slot of a selected lane = v_mbcnt_lo(s4) + v_mbcnt_hi(s5) = -; selected lanes below it = lane >> 3 (upper lanes must count the 4 low-half lanes too). Each selected lane stores -; lane + (bcnt << 8) = lane + 0x800 into out[slot]: -; out[0..7] = 0x805 0x80d 0x815 0x81d 0x825 0x82d 0x835 0x83d = 2053 2061 2069 2077 2085 2093 2101 2109 -; Run: vk_compute_test cs_w64x_ballot.spv 1 dump --require-wave64 -; mattr: +wavefrontsize64,-wavefrontsize32 -v_mbcnt_lo_u32_b32 v1, -1, 0 -v_mbcnt_hi_u32_b32 v1, -1, v1 -v_and_b32_e32 v2, 7, v1 -v_cmp_eq_u32_e64 s[4:5], 5, v2 -s_bcnt1_i32_b64 s6, s[4:5] -v_mbcnt_lo_u32_b32 v3, s4, 0 -v_mbcnt_hi_u32_b32 v3, s5, v3 -v_lshlrev_b32_e32 v4, 2, v3 -s_lshl_b32 s7, s6, 8 -v_add_nc_u32_e32 v5, s7, v1 -s_mov_b64 exec, s[4:5] -buffer_store_dword v5, v4, s[0:3], 0 offen -s_endpgm diff --git a/runtime/test/shaders/cs_w64x_bpermute.asm b/runtime/test/shaders/cs_w64x_bpermute.asm deleted file mode 100644 index 29e8a9d3d..000000000 --- a/runtime/test/shaders/cs_w64x_bpermute.asm +++ /dev/null @@ -1,76 +0,0 @@ -; regen_fixtures: this source has a translator fixture in tests/semantic/fixtures/disasm -; Wave64 ds_bpermute_b32: RDNA2 ISA 10.4.4 - it works on each 32-lane half as two independent wave32s (only index -; bits [6:2] are used, a half references its own lanes 0-31) and reads from a disabled lane return 0. So there is NO -; cross-half read: src lane = (lane & 32) | ((addr / 4) & 31). Crosses: the upper half must read from ITS OWN half -; (a translator that shuffles to idx & 31 of the subgroup reads the low half there), an index >= 32 wraps inside -; the half, and a source lane that is inactive in EXEC gives 0. -; v2 = 7 * lane + 1 (data). -; (a) addr = (lane + 5) * 4: src = half | ((lane + 5) & 31). Lane 0 -> 5 -> 36. Lane 40 -> 32 | 13 = 45 -> 316. -; Lane 63 -> 32 | (68 & 31 = 4) = 36 -> 253. -; (b) addr = (63 - (lane & 31)) * 4, index 32..63 wraps: src = half | (31 - (lane & 31)). Lane 0 -> 31 -> 218. -; Lane 33 -> 32 | 30 = 62 -> 435. Lane 63 -> 32 | 0 = 32 -> 225. -; (c) EXEC = all but lanes 32-47 (v6 preset to 99), addr = (lane + 14) * 4: lane 50 -> 32 | (64 & 31 = 0) = 32, inactive -; -> 0. Lane 49 -> 32 | (63 & 31 = 31) = 63, active -> 442. -; out[0..7] = (a) lane 0, 40, 63; (b) lane 0, 33, 63; (c) lane 50, 49. -; Run: vk_compute_test cs_w64x_bpermute.spv 1 dump --require-wave64 -; -> out[0..7] = 36 316 253 218 435 225 0 442 -; mattr: +wavefrontsize64,-wavefrontsize32 -v_mbcnt_lo_u32_b32 v1, -1, 0 -v_mbcnt_hi_u32_b32 v1, -1, v1 -v_mad_u32_u24 v2, v1, 7, 1 -v_add_nc_u32_e32 v3, 5, v1 -v_lshlrev_b32_e32 v3, 2, v3 -ds_bpermute_b32 v4, v3, v2 -v_and_b32_e32 v5, 31, v1 -v_sub_nc_u32_e32 v5, 63, v5 -v_lshlrev_b32_e32 v5, 2, v5 -ds_bpermute_b32 v5, v5, v2 -s_waitcnt lgkmcnt(0) -v_mov_b32_e32 v6, 99 -v_add_nc_u32_e32 v7, 14, v1 -v_lshlrev_b32_e32 v7, 2, v7 -s_mov_b32 exec_lo, -1 -s_mov_b32 exec_hi, 0xffff0000 -ds_bpermute_b32 v6, v7, v2 -s_waitcnt lgkmcnt(0) -s_mov_b64 exec, -1 -v_cmpx_eq_u32_e32 0, v1 -v_mov_b32_e32 v20, v4 -v_mov_b32_e32 v21, 0 -buffer_store_dword v20, v21, s[0:3], 0 offen -s_mov_b64 exec, -1 -v_cmpx_eq_u32_e32 40, v1 -v_mov_b32_e32 v20, v4 -v_mov_b32_e32 v21, 4 -buffer_store_dword v20, v21, s[0:3], 0 offen -s_mov_b64 exec, -1 -v_cmpx_eq_u32_e32 63, v1 -v_mov_b32_e32 v20, v4 -v_mov_b32_e32 v21, 8 -buffer_store_dword v20, v21, s[0:3], 0 offen -s_mov_b64 exec, -1 -v_cmpx_eq_u32_e32 0, v1 -v_mov_b32_e32 v20, v5 -v_mov_b32_e32 v21, 12 -buffer_store_dword v20, v21, s[0:3], 0 offen -s_mov_b64 exec, -1 -v_cmpx_eq_u32_e32 33, v1 -v_mov_b32_e32 v20, v5 -v_mov_b32_e32 v21, 16 -buffer_store_dword v20, v21, s[0:3], 0 offen -s_mov_b64 exec, -1 -v_cmpx_eq_u32_e32 63, v1 -v_mov_b32_e32 v20, v5 -v_mov_b32_e32 v21, 20 -buffer_store_dword v20, v21, s[0:3], 0 offen -s_mov_b64 exec, -1 -v_cmpx_eq_u32_e32 50, v1 -v_mov_b32_e32 v20, v6 -v_mov_b32_e32 v21, 24 -buffer_store_dword v20, v21, s[0:3], 0 offen -s_mov_b64 exec, -1 -v_cmpx_eq_u32_e32 49, v1 -v_mov_b32_e32 v20, v6 -v_mov_b32_e32 v21, 28 -buffer_store_dword v20, v21, s[0:3], 0 offen -s_endpgm diff --git a/runtime/test/shaders/cs_w64x_branch.asm b/runtime/test/shaders/cs_w64x_branch.asm deleted file mode 100644 index 61548deb5..000000000 --- a/runtime/test/shaders/cs_w64x_branch.asm +++ /dev/null @@ -1,74 +0,0 @@ -; Wave64 wave-wide branches decided by one half only. VCC / EXEC are wave registers, so s_cbranch_* is taken by the -; whole wave: both halves must run (or skip) the same scalar instructions. A 32-wide subgroup decides per half. -; (A) VCC = lane 40 only (upper half), s_cbranch_vccnz taken -> `s_mov_b32 s6, 1` is skipped in ALL lanes: s6 = 0. -; (per-half: the low half sees VCC = 0, falls through, s6 = 1 there) -; (B) VCC = lane 3 only (low half), s_cbranch_vccnz taken -> s7 = 0 everywhere (upper half would fall through). -; (C) EXEC = lanes 32-39 (exec_lo = 0, exec_hi = 0xff), s_cbranch_execz NOT taken (EXEC != 0) -> `s_mov_b32 s9, 5` runs -; in all lanes: s9 = 5 (per-half: the low half has EXEC = 0, takes the branch, s9 = 0 there) -; (D) VCC = lane 40 only, s_cbranch_vccz NOT taken -> s10 = 9 everywhere (low half would take it, s10 = 0) -; Stores: out[0] lane 0 s6, out[1] lane 40 s6, out[2] lane 40 s7, out[3] lane 63 s7, out[4] lane 0 s9, out[5] lane 40 s9, -; out[6] lane 0 s10, out[7] lane 63 s10. -; Run: vk_compute_test cs_w64x_branch.spv 1 dump --require-wave64 -; -> out[0..7] = 0 0 0 0 5 5 9 9 -; mattr: +wavefrontsize64,-wavefrontsize32 -v_mbcnt_lo_u32_b32 v1, -1, 0 -v_mbcnt_hi_u32_b32 v1, -1, v1 -s_mov_b32 s6, 0 -v_cmp_eq_u32_e32 vcc, 40, v1 -s_cbranch_vccnz 1 -s_mov_b32 s6, 1 -s_mov_b32 s7, 0 -v_cmp_eq_u32_e32 vcc, 3, v1 -s_cbranch_vccnz 1 -s_mov_b32 s7, 1 -s_mov_b32 s9, 0 -s_mov_b32 exec_lo, 0 -s_mov_b32 exec_hi, 0xff -s_cbranch_execz 1 -s_mov_b32 s9, 5 -s_mov_b64 exec, -1 -s_mov_b32 s10, 0 -v_cmp_eq_u32_e32 vcc, 40, v1 -s_cbranch_vccz 1 -s_mov_b32 s10, 9 -s_mov_b64 exec, -1 -v_cmpx_eq_u32_e32 0, v1 -v_mov_b32_e32 v20, s6 -v_mov_b32_e32 v21, 0 -buffer_store_dword v20, v21, s[0:3], 0 offen -s_mov_b64 exec, -1 -v_cmpx_eq_u32_e32 40, v1 -v_mov_b32_e32 v20, s6 -v_mov_b32_e32 v21, 4 -buffer_store_dword v20, v21, s[0:3], 0 offen -s_mov_b64 exec, -1 -v_cmpx_eq_u32_e32 40, v1 -v_mov_b32_e32 v20, s7 -v_mov_b32_e32 v21, 8 -buffer_store_dword v20, v21, s[0:3], 0 offen -s_mov_b64 exec, -1 -v_cmpx_eq_u32_e32 63, v1 -v_mov_b32_e32 v20, s7 -v_mov_b32_e32 v21, 12 -buffer_store_dword v20, v21, s[0:3], 0 offen -s_mov_b64 exec, -1 -v_cmpx_eq_u32_e32 0, v1 -v_mov_b32_e32 v20, s9 -v_mov_b32_e32 v21, 16 -buffer_store_dword v20, v21, s[0:3], 0 offen -s_mov_b64 exec, -1 -v_cmpx_eq_u32_e32 40, v1 -v_mov_b32_e32 v20, s9 -v_mov_b32_e32 v21, 20 -buffer_store_dword v20, v21, s[0:3], 0 offen -s_mov_b64 exec, -1 -v_cmpx_eq_u32_e32 0, v1 -v_mov_b32_e32 v20, s10 -v_mov_b32_e32 v21, 24 -buffer_store_dword v20, v21, s[0:3], 0 offen -s_mov_b64 exec, -1 -v_cmpx_eq_u32_e32 63, v1 -v_mov_b32_e32 v20, s10 -v_mov_b32_e32 v21, 28 -buffer_store_dword v20, v21, s[0:3], 0 offen -s_endpgm diff --git a/runtime/test/shaders/cs_w64x_chain_barrier.asm b/runtime/test/shaders/cs_w64x_chain_barrier.asm deleted file mode 100644 index f997fac3d..000000000 --- a/runtime/test/shaders/cs_w64x_chain_barrier.asm +++ /dev/null @@ -1,40 +0,0 @@ -; 128 threads = two wave64s. Every thread writes LDS[tid] = 500 + tid and waits for it, then the block ends in a voted -; branch (s_cbranch_vccnz, not taken) whose successor starts with s_barrier (--wave64-emulate runs that successor in the -; round that reads the vote). After the barrier every thread reads LDS[tid ^ 64], the other wave's word. -; t0 -> 500 + 64 = 564, t127 -> 500 + 63 = 563, t64 -> 500, t63 -> 500 + 127 = 627. -; Stores: out[0] t0, out[1] t127, out[2] t64, out[3] t63. -; Run: vk_compute_test cs_w64x_chain_barrier.spv 1 dump --require-wave64 -; -> out[0..7] = 564 563 500 627 and out[4..7] untouched (0xeeeeeeee) -; mattr: +wavefrontsize64,-wavefrontsize32 -; group: 128,1,1 -v_add_nc_u32_e32 v6, 500, v0 -v_lshlrev_b32_e32 v7, 2, v0 -ds_write_b32 v7, v6 -s_waitcnt lgkmcnt(0) -v_xor_b32_e32 v8, 64, v0 -v_lshlrev_b32_e32 v8, 2, v8 -v_cmp_lt_u32_e32 vcc, 1000, v0 -s_cbranch_vccnz 1 -s_barrier -ds_read_b32 v9, v8 -s_waitcnt lgkmcnt(0) -v_cmpx_eq_u32_e32 0, v0 -v_mov_b32_e32 v20, v9 -v_mov_b32_e32 v21, 0 -buffer_store_dword v20, v21, s[0:3], 0 offen -s_mov_b64 exec, -1 -v_cmpx_eq_u32_e32 127, v0 -v_mov_b32_e32 v20, v9 -v_mov_b32_e32 v21, 4 -buffer_store_dword v20, v21, s[0:3], 0 offen -s_mov_b64 exec, -1 -v_cmpx_eq_u32_e32 64, v0 -v_mov_b32_e32 v20, v9 -v_mov_b32_e32 v21, 8 -buffer_store_dword v20, v21, s[0:3], 0 offen -s_mov_b64 exec, -1 -v_cmpx_eq_u32_e32 63, v0 -v_mov_b32_e32 v20, v9 -v_mov_b32_e32 v21, 12 -buffer_store_dword v20, v21, s[0:3], 0 offen -s_endpgm diff --git a/runtime/test/shaders/cs_w64x_lds_raw.asm b/runtime/test/shaders/cs_w64x_lds_raw.asm deleted file mode 100644 index 05bfa75de..000000000 --- a/runtime/test/shaders/cs_w64x_lds_raw.asm +++ /dev/null @@ -1,60 +0,0 @@ -; Wave64 LDS read-after-write across the halves of ONE wave, no s_barrier: LDS operations of a wave execute in -; order, so a ds_read issued after a ds_write sees every lane's write, including the other half's. A wave64 run as -; two 32-wide subgroups needs the halves ordered (or a barrier) for this to hold. -; v2 = 100 + lane, ds_write_b32 LDS[lane * 4] = v2, then ds_read_b32 v5 = LDS[(lane ^ 32) * 4] = 100 + (lane ^ 32). -; out[0] lane 0 -> 132 out[1] lane 5 -> 137 out[2] lane 32 -> 100 out[3] lane 40 -> 108 -; out[4] lane 63 -> 131 out[5] lane 33 -> 101 out[6] lane 17 -> 149 out[7] lane 50 -> 118 -; (A buffer_store/buffer_load variant is not included: the 64-word output buffer holds only the observed words.) -; Run: vk_compute_test cs_w64x_lds_raw.spv 1 dump --require-wave64 -; -> out[0..7] = 132 137 100 108 131 101 149 118 -; mattr: +wavefrontsize64,-wavefrontsize32 -v_mbcnt_lo_u32_b32 v1, -1, 0 -v_mbcnt_hi_u32_b32 v1, -1, v1 -v_add_nc_u32_e32 v2, 100, v1 -v_lshlrev_b32_e32 v3, 2, v1 -ds_write_b32 v3, v2 -v_xor_b32_e32 v4, 32, v1 -v_lshlrev_b32_e32 v4, 2, v4 -ds_read_b32 v5, v4 -s_waitcnt lgkmcnt(0) -s_mov_b64 exec, -1 -v_cmpx_eq_u32_e32 0, v1 -v_mov_b32_e32 v20, v5 -v_mov_b32_e32 v21, 0 -buffer_store_dword v20, v21, s[0:3], 0 offen -s_mov_b64 exec, -1 -v_cmpx_eq_u32_e32 5, v1 -v_mov_b32_e32 v20, v5 -v_mov_b32_e32 v21, 4 -buffer_store_dword v20, v21, s[0:3], 0 offen -s_mov_b64 exec, -1 -v_cmpx_eq_u32_e32 32, v1 -v_mov_b32_e32 v20, v5 -v_mov_b32_e32 v21, 8 -buffer_store_dword v20, v21, s[0:3], 0 offen -s_mov_b64 exec, -1 -v_cmpx_eq_u32_e32 40, v1 -v_mov_b32_e32 v20, v5 -v_mov_b32_e32 v21, 12 -buffer_store_dword v20, v21, s[0:3], 0 offen -s_mov_b64 exec, -1 -v_cmpx_eq_u32_e32 63, v1 -v_mov_b32_e32 v20, v5 -v_mov_b32_e32 v21, 16 -buffer_store_dword v20, v21, s[0:3], 0 offen -s_mov_b64 exec, -1 -v_cmpx_eq_u32_e32 33, v1 -v_mov_b32_e32 v20, v5 -v_mov_b32_e32 v21, 20 -buffer_store_dword v20, v21, s[0:3], 0 offen -s_mov_b64 exec, -1 -v_cmpx_eq_u32_e32 17, v1 -v_mov_b32_e32 v20, v5 -v_mov_b32_e32 v21, 24 -buffer_store_dword v20, v21, s[0:3], 0 offen -s_mov_b64 exec, -1 -v_cmpx_eq_u32_e32 50, v1 -v_mov_b32_e32 v20, v5 -v_mov_b32_e32 v21, 28 -buffer_store_dword v20, v21, s[0:3], 0 offen -s_endpgm diff --git a/runtime/test/shaders/cs_w64x_lds_war.asm b/runtime/test/shaders/cs_w64x_lds_war.asm deleted file mode 100644 index 94915445d..000000000 --- a/runtime/test/shaders/cs_w64x_lds_war.asm +++ /dev/null @@ -1,67 +0,0 @@ -; Wave64 LDS write-after-read, the warp-synchronous shift idiom: LDS[lane] = 1000 + lane; then in one wave -; v5 = LDS[(lane + 32) & 63] (ds_read_b32) LDS[lane] = 2000 + lane (ds_write_b32, issued right after) -; The read of the whole wave executes before the write of the whole wave, so lanes 0-31 read the OLD values of -; lanes 32-63 (and lanes 32-63 the old values of lanes 0-31). Run as two 32-wide subgroups, the upper half's -; write can land before the lower half's read. A second read of the same addresses sees the new values. -; v5 = 1000 + ((lane + 32) & 63): out[0] lane 0 -> 1032 out[1] lane 31 -> 1063 out[2] lane 32 -> 1000 -; out[3] lane 63 -> 1031 -; v8 = 2000 + ((lane + 32) & 63): out[4] lane 0 -> 2032 out[5] lane 31 -> 2063 out[6] lane 32 -> 2000 -; out[7] lane 63 -> 2031 -; Run: vk_compute_test cs_w64x_lds_war.spv 1 dump --require-wave64 -; -> out[0..7] = 1032 1063 1000 1031 2032 2063 2000 2031 -; mattr: +wavefrontsize64,-wavefrontsize32 -v_mbcnt_lo_u32_b32 v1, -1, 0 -v_mbcnt_hi_u32_b32 v1, -1, v1 -v_add_nc_u32_e32 v2, 1000, v1 -v_lshlrev_b32_e32 v3, 2, v1 -ds_write_b32 v3, v2 -v_add_nc_u32_e32 v4, 32, v1 -v_and_b32_e32 v4, 63, v4 -v_lshlrev_b32_e32 v4, 2, v4 -ds_read_b32 v5, v4 -v_add_nc_u32_e32 v6, 2000, v1 -ds_write_b32 v3, v6 -s_waitcnt lgkmcnt(0) -ds_read_b32 v8, v4 -s_waitcnt lgkmcnt(0) -s_mov_b64 exec, -1 -v_cmpx_eq_u32_e32 0, v1 -v_mov_b32_e32 v20, v5 -v_mov_b32_e32 v21, 0 -buffer_store_dword v20, v21, s[0:3], 0 offen -s_mov_b64 exec, -1 -v_cmpx_eq_u32_e32 31, v1 -v_mov_b32_e32 v20, v5 -v_mov_b32_e32 v21, 4 -buffer_store_dword v20, v21, s[0:3], 0 offen -s_mov_b64 exec, -1 -v_cmpx_eq_u32_e32 32, v1 -v_mov_b32_e32 v20, v5 -v_mov_b32_e32 v21, 8 -buffer_store_dword v20, v21, s[0:3], 0 offen -s_mov_b64 exec, -1 -v_cmpx_eq_u32_e32 63, v1 -v_mov_b32_e32 v20, v5 -v_mov_b32_e32 v21, 12 -buffer_store_dword v20, v21, s[0:3], 0 offen -s_mov_b64 exec, -1 -v_cmpx_eq_u32_e32 0, v1 -v_mov_b32_e32 v20, v8 -v_mov_b32_e32 v21, 16 -buffer_store_dword v20, v21, s[0:3], 0 offen -s_mov_b64 exec, -1 -v_cmpx_eq_u32_e32 31, v1 -v_mov_b32_e32 v20, v8 -v_mov_b32_e32 v21, 20 -buffer_store_dword v20, v21, s[0:3], 0 offen -s_mov_b64 exec, -1 -v_cmpx_eq_u32_e32 32, v1 -v_mov_b32_e32 v20, v8 -v_mov_b32_e32 v21, 24 -buffer_store_dword v20, v21, s[0:3], 0 offen -s_mov_b64 exec, -1 -v_cmpx_eq_u32_e32 63, v1 -v_mov_b32_e32 v20, v8 -v_mov_b32_e32 v21, 28 -buffer_store_dword v20, v21, s[0:3], 0 offen -s_endpgm diff --git a/runtime/test/shaders/cs_w64x_load_ballot_load.asm b/runtime/test/shaders/cs_w64x_load_ballot_load.asm deleted file mode 100644 index 87ed123e4..000000000 --- a/runtime/test/shaders/cs_w64x_load_ballot_load.asm +++ /dev/null @@ -1,74 +0,0 @@ -; regen_fixtures: this source has a translator fixture in tests/semantic/fixtures/disasm -; buffer_load, then a ballot + s_bcnt1, then a second buffer_load, then a store, all in one basic block (this -; sequence once produced invalid SPIR-V under --wave64-emulate), with a checked result. The loads read the other -; half's stores of the same wave (out[lane] = 10 + lane, then the stores are waited for). -; v4 = out[lane ^ 32] = 10 + (lane ^ 32) ballot (v4 > 41), i.e. lane ^ 32 >= 32, i.e. lanes 0-31: s6 = 32 -; v5 = out[(lane + 1) & 63] = 10 + ((lane + 1) & 63) v6 = v5 + s6 -; v6: lane 0 -> 10 + 1 + 32 = 43, lane 31 -> 10 + 32 + 32 = 74, lane 32 -> 10 + 33 + 32 = 75, -; lane 63 -> 10 + 0 + 32 = 42. v4: lane 0 -> 42, lane 40 -> 10 + 8 = 18, lane 63 -> 10 + 31 = 41. s6 = 32. -; Stores: out[0] lane 0 v6, out[1] lane 31 v6, out[2] lane 32 v6, out[3] lane 63 v6, out[4] lane 0 v4, -; out[5] lane 40 v4, out[6] lane 63 v4, out[7] lane 5 s6. -; Run: vk_compute_test cs_w64x_load_ballot_load.spv 1 dump --require-wave64 -; -> out[0..7] = 43 74 75 42 42 18 41 32 -; mattr: +wavefrontsize64,-wavefrontsize32 -v_mbcnt_lo_u32_b32 v1, -1, 0 -v_mbcnt_hi_u32_b32 v1, -1, v1 -v_add_nc_u32_e32 v2, 10, v1 -v_lshlrev_b32_e32 v3, 2, v1 -buffer_store_dword v2, v3, s[0:3], 0 offen -s_waitcnt_vscnt null, 0x0 -s_waitcnt vmcnt(0) -v_xor_b32_e32 v7, 32, v1 -v_lshlrev_b32_e32 v7, 2, v7 -buffer_load_dword v4, v7, s[0:3], 0 offen -s_waitcnt vmcnt(0) -v_cmp_gt_u32_e64 s[4:5], v4, 41 -s_bcnt1_i32_b64 s6, s[4:5] -v_add_nc_u32_e32 v8, 1, v1 -v_and_b32_e32 v8, 63, v8 -v_lshlrev_b32_e32 v8, 2, v8 -buffer_load_dword v5, v8, s[0:3], 0 offen -s_waitcnt vmcnt(0) -v_add_nc_u32_e32 v6, s6, v5 -buffer_store_dword v6, v3, s[0:3], 0 offen -s_mov_b64 exec, -1 -v_cmpx_eq_u32_e32 0, v1 -v_mov_b32_e32 v20, v6 -v_mov_b32_e32 v21, 0 -buffer_store_dword v20, v21, s[0:3], 0 offen -s_mov_b64 exec, -1 -v_cmpx_eq_u32_e32 31, v1 -v_mov_b32_e32 v20, v6 -v_mov_b32_e32 v21, 4 -buffer_store_dword v20, v21, s[0:3], 0 offen -s_mov_b64 exec, -1 -v_cmpx_eq_u32_e32 32, v1 -v_mov_b32_e32 v20, v6 -v_mov_b32_e32 v21, 8 -buffer_store_dword v20, v21, s[0:3], 0 offen -s_mov_b64 exec, -1 -v_cmpx_eq_u32_e32 63, v1 -v_mov_b32_e32 v20, v6 -v_mov_b32_e32 v21, 12 -buffer_store_dword v20, v21, s[0:3], 0 offen -s_mov_b64 exec, -1 -v_cmpx_eq_u32_e32 0, v1 -v_mov_b32_e32 v20, v4 -v_mov_b32_e32 v21, 16 -buffer_store_dword v20, v21, s[0:3], 0 offen -s_mov_b64 exec, -1 -v_cmpx_eq_u32_e32 40, v1 -v_mov_b32_e32 v20, v4 -v_mov_b32_e32 v21, 20 -buffer_store_dword v20, v21, s[0:3], 0 offen -s_mov_b64 exec, -1 -v_cmpx_eq_u32_e32 63, v1 -v_mov_b32_e32 v20, v4 -v_mov_b32_e32 v21, 24 -buffer_store_dword v20, v21, s[0:3], 0 offen -s_mov_b64 exec, -1 -v_cmpx_eq_u32_e32 5, v1 -v_mov_b32_e32 v20, s6 -v_mov_b32_e32 v21, 28 -buffer_store_dword v20, v21, s[0:3], 0 offen -s_endpgm diff --git a/runtime/test/shaders/cs_w64x_mask_reuse.asm b/runtime/test/shaders/cs_w64x_mask_reuse.asm deleted file mode 100644 index d5108223e..000000000 --- a/runtime/test/shaders/cs_w64x_mask_reuse.asm +++ /dev/null @@ -1,57 +0,0 @@ -; The same lane mask read twice, then rewritten, then read again: --wave64-emulate exchanges a mask once per value, so -; a stale reuse after the register or EXEC changed would show here. -; s[4:5] = lanes with (lane & 7) == 5 (8 lanes): s6 = s_bcnt1 = 8, v3 = v_mbcnt_lo/hi of it = selected lanes below. -; s[4:5] = lanes < 40 (v_cmp_gt_u32 40, lane): s7 = s_bcnt1 = 40, v4 = v_mbcnt_lo/hi of it = min(lane, 40). -; EXEC: s8 = popcount(exec) = 64, v_cmpx lane < 10 -> s9 = 10, exec = -1 again -> s10 = 64. -; Stores: out[0] s6, out[1] s7, out[2] lane 63 v3 (= 8), out[3] lane 63 v4 (= 40), out[4] lane 20 v3 (= 2), -; out[5] lane 20 v4 (= 20), out[6] s9, out[7] s10. -; Run: vk_compute_test cs_w64x_mask_reuse.spv 1 dump --require-wave64 -; -> out[0..7] = 8 40 8 40 2 20 10 64 -; mattr: +wavefrontsize64,-wavefrontsize32 -v_mbcnt_lo_u32_b32 v1, -1, 0 -v_mbcnt_hi_u32_b32 v1, -1, v1 -v_and_b32_e32 v2, 7, v1 -v_cmp_eq_u32_e64 s[4:5], 5, v2 -s_bcnt1_i32_b64 s6, s[4:5] -v_mbcnt_lo_u32_b32 v3, s4, 0 -v_mbcnt_hi_u32_b32 v3, s5, v3 -s_bcnt1_i32_b64 s11, s[4:5] -v_cmp_gt_u32_e64 s[4:5], 40, v1 -s_bcnt1_i32_b64 s7, s[4:5] -v_mbcnt_lo_u32_b32 v4, s4, 0 -v_mbcnt_hi_u32_b32 v4, s5, v4 -s_bcnt1_i32_b64 s8, exec -v_cmpx_gt_u32_e32 10, v1 -s_bcnt1_i32_b64 s9, exec -s_mov_b64 exec, -1 -s_bcnt1_i32_b64 s10, exec -v_cmpx_eq_u32_e32 0, v1 -v_mov_b32_e32 v20, s6 -v_mov_b32_e32 v21, 0 -buffer_store_dword v20, v21, s[0:3], 0 offen -v_mov_b32_e32 v20, s7 -v_mov_b32_e32 v21, 4 -buffer_store_dword v20, v21, s[0:3], 0 offen -v_mov_b32_e32 v20, s9 -v_mov_b32_e32 v21, 24 -buffer_store_dword v20, v21, s[0:3], 0 offen -v_mov_b32_e32 v20, s10 -v_mov_b32_e32 v21, 28 -buffer_store_dword v20, v21, s[0:3], 0 offen -s_mov_b64 exec, -1 -v_cmpx_eq_u32_e32 63, v1 -v_mov_b32_e32 v20, v3 -v_mov_b32_e32 v21, 8 -buffer_store_dword v20, v21, s[0:3], 0 offen -v_mov_b32_e32 v20, v4 -v_mov_b32_e32 v21, 12 -buffer_store_dword v20, v21, s[0:3], 0 offen -s_mov_b64 exec, -1 -v_cmpx_eq_u32_e32 20, v1 -v_mov_b32_e32 v20, v3 -v_mov_b32_e32 v21, 16 -buffer_store_dword v20, v21, s[0:3], 0 offen -v_mov_b32_e32 v20, v4 -v_mov_b32_e32 v21, 20 -buffer_store_dword v20, v21, s[0:3], 0 offen -s_endpgm diff --git a/runtime/test/shaders/cs_w64x_mask_reuse2.asm b/runtime/test/shaders/cs_w64x_mask_reuse2.asm deleted file mode 100644 index bb2de1441..000000000 --- a/runtime/test/shaders/cs_w64x_mask_reuse2.asm +++ /dev/null @@ -1,71 +0,0 @@ -; More on exchanging a lane mask once per value (--wave64-emulate), see cs_w64x_mask_reuse.asm: -; 1. EXEC read twice without a change in between (s_bcnt1 exec): both give 10 (lanes < 10), s6 + s7 = 20. -; 2. s[4:5] = lanes with (lane & 7) == 5 (8 lanes): s9 = s_bcnt1 = 8; a buffer_store (it opens labels in the translation) -; and the same mask read again: s10 = 8. -; 3. One half of the pair rewritten from another mask, the other kept: s5 = s5 & s13 (s[12:13] = lanes < 40), then -; v_mbcnt_lo(s4) + v_mbcnt_hi(s5). s4 selects lanes 5, 13, 21, 29, s5 now only lane 37: lane 63 -> 4 + 1, lane 20 -> 2. -; 4. A block that ends in a voted branch (s_cbranch_vccnz, not taken) and a successor whose first instruction is a -; load of the OTHER half's store from before the vote: out[lane] = 100 + lane, then v9 = out[lane ^ 32]. -; lane 0 -> 132, lane 63 -> 131. -; Stores: out[0] s6, out[1] s6 + s7, out[2] s9, out[3] s10, out[4] lane 63 v5, out[5] lane 20 v5, out[6] lane 0 v9, -; out[7] lane 63 v9. -; Run: vk_compute_test cs_w64x_mask_reuse2.spv 1 dump --require-wave64 -; -> out[0..7] = 10 20 8 8 5 2 132 131 -; mattr: +wavefrontsize64,-wavefrontsize32 -v_mbcnt_lo_u32_b32 v1, -1, 0 -v_mbcnt_hi_u32_b32 v1, -1, v1 -v_cmpx_gt_u32_e32 10, v1 -s_bcnt1_i32_b64 s6, exec -s_bcnt1_i32_b64 s7, exec -s_mov_b64 exec, -1 -s_add_u32 s8, s6, s7 -v_and_b32_e32 v2, 7, v1 -v_cmp_eq_u32_e64 s[4:5], 5, v2 -s_bcnt1_i32_b64 s9, s[4:5] -v_lshlrev_b32_e32 v7, 2, v1 -buffer_store_dword v1, v7, s[0:3], 0 offen -s_waitcnt_vscnt null, 0x0 -s_bcnt1_i32_b64 s10, s[4:5] -v_cmp_gt_u32_e64 s[12:13], 40, v1 -s_and_b32 s5, s5, s13 -v_mbcnt_lo_u32_b32 v5, s4, 0 -v_mbcnt_hi_u32_b32 v5, s5, v5 -v_add_nc_u32_e32 v6, 100, v1 -buffer_store_dword v6, v7, s[0:3], 0 offen -s_waitcnt_vscnt null, 0x0 -v_xor_b32_e32 v8, 32, v1 -v_lshlrev_b32_e32 v8, 2, v8 -v_cmp_lt_u32_e32 vcc, 100, v1 -s_cbranch_vccnz 2 -buffer_load_dword v9, v8, s[0:3], 0 offen -s_waitcnt vmcnt(0) -v_cmpx_eq_u32_e32 0, v1 -v_mov_b32_e32 v20, s6 -v_mov_b32_e32 v21, 0 -buffer_store_dword v20, v21, s[0:3], 0 offen -v_mov_b32_e32 v20, s8 -v_mov_b32_e32 v21, 4 -buffer_store_dword v20, v21, s[0:3], 0 offen -v_mov_b32_e32 v20, s9 -v_mov_b32_e32 v21, 8 -buffer_store_dword v20, v21, s[0:3], 0 offen -v_mov_b32_e32 v20, s10 -v_mov_b32_e32 v21, 12 -buffer_store_dword v20, v21, s[0:3], 0 offen -v_mov_b32_e32 v20, v9 -v_mov_b32_e32 v21, 24 -buffer_store_dword v20, v21, s[0:3], 0 offen -s_mov_b64 exec, -1 -v_cmpx_eq_u32_e32 63, v1 -v_mov_b32_e32 v20, v5 -v_mov_b32_e32 v21, 16 -buffer_store_dword v20, v21, s[0:3], 0 offen -v_mov_b32_e32 v20, v9 -v_mov_b32_e32 v21, 28 -buffer_store_dword v20, v21, s[0:3], 0 offen -s_mov_b64 exec, -1 -v_cmpx_eq_u32_e32 20, v1 -v_mov_b32_e32 v20, v5 -v_mov_b32_e32 v21, 20 -buffer_store_dword v20, v21, s[0:3], 0 offen -s_endpgm diff --git a/runtime/test/shaders/cs_w64x_partial.asm b/runtime/test/shaders/cs_w64x_partial.asm deleted file mode 100644 index 4e8f7f089..000000000 --- a/runtime/test/shaders/cs_w64x_partial.asm +++ /dev/null @@ -1,80 +0,0 @@ -; regen_fixtures: this source has a translator fixture in tests/semantic/fixtures/disasm -; Partial wave64: a 40x1x1 group is one wave with lanes 0-39 enabled, lanes 40-63 disabled (EXEC = 0xff_ffffffff). -; Only what the ISA defines is asserted (no readlane of a nonexistent lane): EXEC and ballot counts, ds_bpermute -; reads from a disabled lane return 0, readfirstlane on the enabled lanes of the upper half. -; v2 = 500 + lane (data). s6:s7 = EXEC at entry. -; s8 = s_bcnt1 of EXEC = 40. s11 = s_bcnt1 of v_cmp_eq(v1, v1) = 40 (the ballot has no bits of disabled lanes). -; v4 = ds_bpermute with addr = (lane + 8) * 4, src = half | ((lane + 8) & 31): -; lane 20 -> 28 -> 528; lane 33 -> 32 | 9 = 41 (disabled) -> 0; lane 39 -> 32 | 15 = 47 (disabled) -> 0. -; v5 = ds_bpermute with addr = (lane ^ 1) * 4: lane 33 -> 32 -> 532; lane 38 -> 39 -> 539. -; Then EXEC = lanes 32-39 (v_cmpx 31 < lane): s9 = v_readfirstlane(v2) = v2[32] = 532, s10 = s_bcnt1 EXEC = 8, -; packed s9 + (s10 << 16) = 532 + 524288 = 524820. -; Stores: out[0] lane 0 s8, out[1] lane 39 s11, out[2] lane 20 v4, out[3] lane 33 v4, out[4] lane 39 v4, -; out[5] lane 33 v5, out[6] lane 38 v5, out[7] lane 2 s9. -; The group has 40 threads, so --require-wave64 (full subgroups) cannot be used; check.py asks for subgroup size 64 -; with VKC_SUBGROUP_SIZE=64 instead. -; Run: VKC_SUBGROUP_SIZE=64 vk_compute_test cs_w64x_partial.spv 1 dump -; -> out[0..7] = 40 40 528 0 0 532 539 524820 -; mattr: +wavefrontsize64,-wavefrontsize32 -; group: 40,1,1 -v_mbcnt_lo_u32_b32 v1, -1, 0 -v_mbcnt_hi_u32_b32 v1, -1, v1 -v_add_nc_u32_e32 v2, 500, v1 -s_mov_b64 s[6:7], exec -s_bcnt1_i32_b64 s8, exec -v_cmp_eq_u32_e64 s[4:5], v1, v1 -s_bcnt1_i32_b64 s11, s[4:5] -v_add_nc_u32_e32 v3, 8, v1 -v_lshlrev_b32_e32 v3, 2, v3 -ds_bpermute_b32 v4, v3, v2 -v_xor_b32_e32 v6, 1, v1 -v_lshlrev_b32_e32 v6, 2, v6 -ds_bpermute_b32 v5, v6, v2 -s_waitcnt lgkmcnt(0) -v_cmpx_lt_u32_e32 31, v1 -v_readfirstlane_b32 s9, v2 -s_bcnt1_i32_b64 s10, exec -s_mov_b64 exec, s[6:7] -s_lshl_b32 s10, s10, 16 -s_add_u32 s9, s9, s10 -s_mov_b64 exec, s[6:7] -v_cmpx_eq_u32_e32 0, v1 -v_mov_b32_e32 v20, s8 -v_mov_b32_e32 v21, 0 -buffer_store_dword v20, v21, s[0:3], 0 offen -s_mov_b64 exec, s[6:7] -v_cmpx_eq_u32_e32 39, v1 -v_mov_b32_e32 v20, s11 -v_mov_b32_e32 v21, 4 -buffer_store_dword v20, v21, s[0:3], 0 offen -s_mov_b64 exec, s[6:7] -v_cmpx_eq_u32_e32 20, v1 -v_mov_b32_e32 v20, v4 -v_mov_b32_e32 v21, 8 -buffer_store_dword v20, v21, s[0:3], 0 offen -s_mov_b64 exec, s[6:7] -v_cmpx_eq_u32_e32 33, v1 -v_mov_b32_e32 v20, v4 -v_mov_b32_e32 v21, 12 -buffer_store_dword v20, v21, s[0:3], 0 offen -s_mov_b64 exec, s[6:7] -v_cmpx_eq_u32_e32 39, v1 -v_mov_b32_e32 v20, v4 -v_mov_b32_e32 v21, 16 -buffer_store_dword v20, v21, s[0:3], 0 offen -s_mov_b64 exec, s[6:7] -v_cmpx_eq_u32_e32 33, v1 -v_mov_b32_e32 v20, v5 -v_mov_b32_e32 v21, 20 -buffer_store_dword v20, v21, s[0:3], 0 offen -s_mov_b64 exec, s[6:7] -v_cmpx_eq_u32_e32 38, v1 -v_mov_b32_e32 v20, v5 -v_mov_b32_e32 v21, 24 -buffer_store_dword v20, v21, s[0:3], 0 offen -s_mov_b64 exec, s[6:7] -v_cmpx_eq_u32_e32 2, v1 -v_mov_b32_e32 v20, s9 -v_mov_b32_e32 v21, 28 -buffer_store_dword v20, v21, s[0:3], 0 offen -s_endpgm diff --git a/runtime/test/shaders/cs_w64x_partial_scmp.asm b/runtime/test/shaders/cs_w64x_partial_scmp.asm deleted file mode 100644 index 3892d8ab9..000000000 --- a/runtime/test/shaders/cs_w64x_partial_scmp.asm +++ /dev/null @@ -1,70 +0,0 @@ -; Partial wave64: s_cmp of a lane mask against -1 (all ones) compares the real mask word, not a vote. -; A 40x1x1 group is one wave with lanes 0-39 enabled and lanes 40-63 never launched (as cs_w64x_partial). -; vcc = v_cmp_eq(v1, v1) has a bit per launched lane only, so vcc_lo = 0xffffffff and vcc_hi = 0x000000ff; -; EXEC = 0x000000ff_ffffffff. A vote over the launched lanes would call vcc_hi and vcc "all ones". -; Lane 0 stores SCC as 0/1 for each compare: -; out[0] s_cmp_eq_u32 vcc_hi, -1 = 0 (0xff != 0xffffffff) -; out[1] s_cmp_eq_u32 vcc_lo, -1 = 1 -; out[2] s_cmp_eq_u64 vcc, -1 = 0 -; out[3] s_cmp_lg_u64 vcc, 0 = 1 -; out[4] s_cmp_eq_u32 vcc_hi, s14 = 1 (s14 = 0xff) -; out[5] s_cmp_eq_u64 vcc, s[12:13] = 1 (s[12:13] = 0x000000ff_ffffffff) -; out[6] s_cmp_lg_u32 vcc_hi, -1 = 1 -; out[7] s_cmp_eq_u64 exec, -1 = 0 -; Until 2026-11-22 the compares with -1 were a vote: out[0], out[2] and out[7] read 1 and out[6] read 0. -; The group has 40 threads, so --require-wave64 (full subgroups) cannot be used; check.py asks for subgroup size 64 -; with VKC_SUBGROUP_SIZE=64 instead. -; Run: VKC_SUBGROUP_SIZE=64 vk_compute_test cs_w64x_partial_scmp.spv 1 dump -; -> out[0..7] = 0 1 0 1 1 1 1 0 -; mattr: +wavefrontsize64,-wavefrontsize32 -; group: 40,1,1 -v_mbcnt_lo_u32_b32 v1, -1, 0 -v_mbcnt_hi_u32_b32 v1, -1, v1 -s_mov_b64 s[6:7], exec -v_cmp_eq_u32_e32 vcc, v1, v1 -s_mov_b32 s14, 0xff -s_mov_b32 s12, -1 -s_mov_b32 s13, 0xff -s_cmp_eq_u32 vcc_hi, -1 -s_cselect_b32 s20, 1, 0 -s_cmp_eq_u32 vcc_lo, -1 -s_cselect_b32 s21, 1, 0 -s_cmp_eq_u64 vcc, -1 -s_cselect_b32 s22, 1, 0 -s_cmp_lg_u64 vcc, 0 -s_cselect_b32 s23, 1, 0 -s_cmp_eq_u32 vcc_hi, s14 -s_cselect_b32 s24, 1, 0 -s_cmp_eq_u64 vcc, s[12:13] -s_cselect_b32 s25, 1, 0 -s_cmp_lg_u32 vcc_hi, -1 -s_cselect_b32 s26, 1, 0 -s_cmp_eq_u64 exec, -1 -s_cselect_b32 s27, 1, 0 -v_cmpx_eq_u32_e32 0, v1 -v_mov_b32_e32 v20, s20 -v_mov_b32_e32 v21, 0 -buffer_store_dword v20, v21, s[0:3], 0 offen -v_mov_b32_e32 v20, s21 -v_mov_b32_e32 v21, 4 -buffer_store_dword v20, v21, s[0:3], 0 offen -v_mov_b32_e32 v20, s22 -v_mov_b32_e32 v21, 8 -buffer_store_dword v20, v21, s[0:3], 0 offen -v_mov_b32_e32 v20, s23 -v_mov_b32_e32 v21, 12 -buffer_store_dword v20, v21, s[0:3], 0 offen -v_mov_b32_e32 v20, s24 -v_mov_b32_e32 v21, 16 -buffer_store_dword v20, v21, s[0:3], 0 offen -v_mov_b32_e32 v20, s25 -v_mov_b32_e32 v21, 20 -buffer_store_dword v20, v21, s[0:3], 0 offen -v_mov_b32_e32 v20, s26 -v_mov_b32_e32 v21, 24 -buffer_store_dword v20, v21, s[0:3], 0 offen -v_mov_b32_e32 v20, s27 -v_mov_b32_e32 v21, 28 -buffer_store_dword v20, v21, s[0:3], 0 offen -s_mov_b64 exec, s[6:7] -s_endpgm diff --git a/runtime/test/shaders/cs_w64x_permute.asm b/runtime/test/shaders/cs_w64x_permute.asm deleted file mode 100644 index 916f434e4..000000000 --- a/runtime/test/shaders/cs_w64x_permute.asm +++ /dev/null @@ -1,79 +0,0 @@ -; regen_fixtures: this source has a translator fixture in tests/semantic/fixtures/disasm -; SHADER-90: wave64 ds_permute_b32. Like ds_bpermute_b32 it runs as two independent wave32 halves (RDNA2 ISA 10.4.4): a -; source lane writes lane ((vAddr + offset) / 4) mod 32 of ITS OWN half, a destination nobody writes gets 0, and -; EXEC gates source and destination. v0 = lane 0..63, v2 = 7 * lane + 1 (data), v10..v13 start at 99. -; (A) addr = (lane + 1) * 4: a rotation inside each half. Lane 0 <- lane 31 = 218. Lane 32 <- lane 63 = 442 (NOT lane -; 31: a half never writes the other). Lane 63 <- lane 62 = 435. -; (B) addr = (31 - (lane & 31)) * 4, offset:8: lane l writes rel (33 - rel) mod 32 of its half. Lane 32 <- lane 33 = 232. -; (C) EXEC = lanes 0-15 and 32-47, addr = lane * 8: lane l writes rel 2 * rel. Lane 36 <- lane 34 = 239. Lane 35 is on -; and nobody writes it: 0. Lane 52 is off: 99. -; (D) EXEC = even lanes, an even lane l writes l + 2, an odd lane l writes l + 1: lane 36 <- lane 34 = 239; the off -; lane 35, which also targets lane 36, must not win (it would give 246). -; out[0..7] = A0 A32 A63 C36 C35 C52 D36 B32 = 218 442 435 239 0 99 239 232 -; Run: vk_compute_test cs_w64x_permute.spv 1 dump --require-wave64 -> out[0..7] = 218 442 435 239 0 99 239 232 -; mattr: +wavefrontsize64,-wavefrontsize32 -v_mad_u32_u24 v2, v0, 7, 1 -v_add_nc_u32_e32 v3, 1, v0 -v_lshlrev_b32_e32 v3, 2, v3 -ds_permute_b32 v10, v3, v2 -v_and_b32_e32 v4, 31, v0 -v_sub_nc_u32_e32 v4, 31, v4 -v_lshlrev_b32_e32 v4, 2, v4 -ds_permute_b32 v11, v4, v2 offset:8 -v_mov_b32_e32 v12, 99 -v_lshlrev_b32_e32 v5, 3, v0 -s_mov_b32 exec_lo, 0xffff -s_mov_b32 exec_hi, 0xffff -ds_permute_b32 v12, v5, v2 -s_waitcnt lgkmcnt(0) -s_mov_b64 exec, -1 -v_and_b32_e32 v6, 1, v0 -v_sub_nc_u32_e32 v6, 2, v6 -v_add_nc_u32_e32 v6, v0, v6 -v_lshlrev_b32_e32 v6, 2, v6 -v_mov_b32_e32 v13, 99 -s_mov_b32 exec_lo, 0x55555555 -s_mov_b32 exec_hi, 0x55555555 -ds_permute_b32 v13, v6, v2 -s_waitcnt lgkmcnt(0) -s_mov_b64 exec, -1 -v_cmpx_eq_u32_e32 0, v0 -v_mov_b32_e32 v20, v10 -v_mov_b32_e32 v21, 0 -buffer_store_dword v20, v21, s[0:3], 0 offen -s_mov_b64 exec, -1 -v_cmpx_eq_u32_e32 32, v0 -v_mov_b32_e32 v20, v10 -v_mov_b32_e32 v21, 4 -buffer_store_dword v20, v21, s[0:3], 0 offen -s_mov_b64 exec, -1 -v_cmpx_eq_u32_e32 63, v0 -v_mov_b32_e32 v20, v10 -v_mov_b32_e32 v21, 8 -buffer_store_dword v20, v21, s[0:3], 0 offen -s_mov_b64 exec, -1 -v_cmpx_eq_u32_e32 36, v0 -v_mov_b32_e32 v20, v12 -v_mov_b32_e32 v21, 12 -buffer_store_dword v20, v21, s[0:3], 0 offen -s_mov_b64 exec, -1 -v_cmpx_eq_u32_e32 35, v0 -v_mov_b32_e32 v20, v12 -v_mov_b32_e32 v21, 16 -buffer_store_dword v20, v21, s[0:3], 0 offen -s_mov_b64 exec, -1 -v_cmpx_eq_u32_e32 52, v0 -v_mov_b32_e32 v20, v12 -v_mov_b32_e32 v21, 20 -buffer_store_dword v20, v21, s[0:3], 0 offen -s_mov_b64 exec, -1 -v_cmpx_eq_u32_e32 36, v0 -v_mov_b32_e32 v20, v13 -v_mov_b32_e32 v21, 24 -buffer_store_dword v20, v21, s[0:3], 0 offen -s_mov_b64 exec, -1 -v_cmpx_eq_u32_e32 32, v0 -v_mov_b32_e32 v20, v11 -v_mov_b32_e32 v21, 28 -buffer_store_dword v20, v21, s[0:3], 0 offen -s_endpgm diff --git a/runtime/test/shaders/cs_w64x_readfirstlane.asm b/runtime/test/shaders/cs_w64x_readfirstlane.asm deleted file mode 100644 index cd192e02b..000000000 --- a/runtime/test/shaders/cs_w64x_readfirstlane.asm +++ /dev/null @@ -1,85 +0,0 @@ -; regen_fixtures: this source has a translator fixture in tests/semantic/fixtures/disasm -; Wave64 v_readfirstlane_b32 with the first active lane in the upper half (lowest set EXEC bit; lane 0 if EXEC = 0). -; A 32-wide subgroup sees only its own half's EXEC bits and returns lane 0 of the low half instead. -; v2 = lane + 100, v1 = lane. EXEC (hi:lo) and result: -; s6: lanes 40-63 (0xffffff00:0) -> v2[40] = 140 s7: lane 63 only (0x80000000:0) -> v2[63] = 163 -; s8: lane 32 only (1:0) -> v2[32] = 132 s9: EXEC = 0 -> lane 0 -> v2[0] = 100 -; s10: lanes 5,33,34,35 (0xe:0x20) -> v2[5] = 105 (control: lowest lane is in the low half) -; s11: lanes 33-35 (0xe:0) -> v2[33] = 133 s12: lanes 48-63, v1 -> 48 -; Stores (EXEC restored, one lane per word): out[0] lane 0 s6, out[1] lane 63 s6, out[2] lane 5 s7, out[3] lane 63 s8, -; out[4] lane 40 s9, out[5] lane 34 s10, out[6] lane 0 s11, out[7] lane 49 s12. -; Run: vk_compute_test cs_w64x_readfirstlane.spv 1 dump --require-wave64 -; -> out[0..7] = 140 140 163 132 100 105 133 48 -; mattr: +wavefrontsize64,-wavefrontsize32 -v_mbcnt_lo_u32_b32 v1, -1, 0 -v_mbcnt_hi_u32_b32 v1, -1, v1 -v_add_nc_u32_e32 v2, 100, v1 -s_mov_b32 exec_lo, 0 -s_mov_b32 exec_hi, 0xffffff00 -v_readfirstlane_b32 s6, v2 -s_mov_b64 exec, -1 -s_mov_b32 exec_lo, 0 -s_mov_b32 exec_hi, 0x80000000 -v_readfirstlane_b32 s7, v2 -s_mov_b64 exec, -1 -s_mov_b32 exec_lo, 0 -s_mov_b32 exec_hi, 1 -v_readfirstlane_b32 s8, v2 -s_mov_b64 exec, -1 -s_mov_b32 exec_lo, 0 -s_mov_b32 exec_hi, 0 -v_readfirstlane_b32 s9, v2 -s_mov_b64 exec, -1 -s_mov_b32 exec_lo, 0x20 -s_mov_b32 exec_hi, 0xe -v_readfirstlane_b32 s10, v2 -s_mov_b64 exec, -1 -s_mov_b32 exec_lo, 0 -s_mov_b32 exec_hi, 0xe -v_readfirstlane_b32 s11, v2 -s_mov_b64 exec, -1 -s_mov_b32 exec_lo, 0 -s_mov_b32 exec_hi, 0xffff0000 -v_readfirstlane_b32 s12, v1 -s_mov_b64 exec, -1 -s_mov_b64 exec, -1 -v_cmpx_eq_u32_e32 0, v1 -v_mov_b32_e32 v20, s6 -v_mov_b32_e32 v21, 0 -buffer_store_dword v20, v21, s[0:3], 0 offen -s_mov_b64 exec, -1 -v_cmpx_eq_u32_e32 63, v1 -v_mov_b32_e32 v20, s6 -v_mov_b32_e32 v21, 4 -buffer_store_dword v20, v21, s[0:3], 0 offen -s_mov_b64 exec, -1 -v_cmpx_eq_u32_e32 5, v1 -v_mov_b32_e32 v20, s7 -v_mov_b32_e32 v21, 8 -buffer_store_dword v20, v21, s[0:3], 0 offen -s_mov_b64 exec, -1 -v_cmpx_eq_u32_e32 63, v1 -v_mov_b32_e32 v20, s8 -v_mov_b32_e32 v21, 12 -buffer_store_dword v20, v21, s[0:3], 0 offen -s_mov_b64 exec, -1 -v_cmpx_eq_u32_e32 40, v1 -v_mov_b32_e32 v20, s9 -v_mov_b32_e32 v21, 16 -buffer_store_dword v20, v21, s[0:3], 0 offen -s_mov_b64 exec, -1 -v_cmpx_eq_u32_e32 34, v1 -v_mov_b32_e32 v20, s10 -v_mov_b32_e32 v21, 20 -buffer_store_dword v20, v21, s[0:3], 0 offen -s_mov_b64 exec, -1 -v_cmpx_eq_u32_e32 0, v1 -v_mov_b32_e32 v20, s11 -v_mov_b32_e32 v21, 24 -buffer_store_dword v20, v21, s[0:3], 0 offen -s_mov_b64 exec, -1 -v_cmpx_eq_u32_e32 49, v1 -v_mov_b32_e32 v20, s12 -v_mov_b32_e32 v21, 28 -buffer_store_dword v20, v21, s[0:3], 0 offen -s_endpgm diff --git a/runtime/test/shaders/cs_w64x_readlane.asm b/runtime/test/shaders/cs_w64x_readlane.asm deleted file mode 100644 index 59e509cdd..000000000 --- a/runtime/test/shaders/cs_w64x_readlane.asm +++ /dev/null @@ -1,62 +0,0 @@ -; regen_fixtures: this source has a translator fixture in tests/semantic/fixtures/disasm -; Wave64 cross-half v_readlane_b32 (RDNA2 ISA: lane = S1 % 64, EXEC ignored). Crosses: lane >= 32 sources read by -; lanes of both halves, and a lane < 32 source read by an upper-half lane. A 32-wide subgroup wraps the lane -; select modulo 32 (the issue #94 symptom), so lane 40 would return lane 8's value. -; v2 = 3 * lane + 1. s6 = v2[40] = 121, s7 = v2[5] = 16, s8 = v2[32] = 97, s9 = v2[97 % 64 = 33] = 100. -; Each word is stored by one lane (v_cmpx), so both halves observe the scalar: -; out[0] lane 0 stores s6 = 121 out[1] lane 33 stores s6 = 121 out[2] lane 63 stores s7 = 16 -; out[3] lane 0 stores s8 = 97 out[4] lane 45 stores s7 = 16 out[5] lane 7 stores s9 = 100 -; out[6] lane 60 stores s9 = 100 out[7] EXEC = lane 63 only, readlane of lane 40 (inactive): 121 (EXEC ignored) -; Same FSSM header as cs_lds. Run: vk_compute_test cs_w64x_readlane.spv 1 dump --require-wave64 -; -> out[0..7] = 121 121 16 97 16 100 100 121 -; mattr: +wavefrontsize64,-wavefrontsize32 -v_mbcnt_lo_u32_b32 v1, -1, 0 -v_mbcnt_hi_u32_b32 v1, -1, v1 -v_mad_u32_u24 v2, v1, 3, 1 -v_readlane_b32 s6, v2, 40 -v_readlane_b32 s7, v2, 5 -v_readlane_b32 s8, v2, 32 -s_mov_b32 s10, 97 -v_readlane_b32 s9, v2, s10 -s_mov_b64 exec, -1 -v_cmpx_eq_u32_e32 0, v1 -v_mov_b32_e32 v20, s6 -v_mov_b32_e32 v21, 0 -buffer_store_dword v20, v21, s[0:3], 0 offen -s_mov_b64 exec, -1 -v_cmpx_eq_u32_e32 33, v1 -v_mov_b32_e32 v20, s6 -v_mov_b32_e32 v21, 4 -buffer_store_dword v20, v21, s[0:3], 0 offen -s_mov_b64 exec, -1 -v_cmpx_eq_u32_e32 63, v1 -v_mov_b32_e32 v20, s7 -v_mov_b32_e32 v21, 8 -buffer_store_dword v20, v21, s[0:3], 0 offen -s_mov_b64 exec, -1 -v_cmpx_eq_u32_e32 0, v1 -v_mov_b32_e32 v20, s8 -v_mov_b32_e32 v21, 12 -buffer_store_dword v20, v21, s[0:3], 0 offen -s_mov_b64 exec, -1 -v_cmpx_eq_u32_e32 45, v1 -v_mov_b32_e32 v20, s7 -v_mov_b32_e32 v21, 16 -buffer_store_dword v20, v21, s[0:3], 0 offen -s_mov_b64 exec, -1 -v_cmpx_eq_u32_e32 7, v1 -v_mov_b32_e32 v20, s9 -v_mov_b32_e32 v21, 20 -buffer_store_dword v20, v21, s[0:3], 0 offen -s_mov_b64 exec, -1 -v_cmpx_eq_u32_e32 60, v1 -v_mov_b32_e32 v20, s9 -v_mov_b32_e32 v21, 24 -buffer_store_dword v20, v21, s[0:3], 0 offen -s_mov_b64 exec, -1 -v_cmpx_eq_u32_e32 63, v1 -v_readlane_b32 s11, v2, 40 -v_mov_b32_e32 v20, s11 -v_mov_b32_e32 v21, 28 -buffer_store_dword v20, v21, s[0:3], 0 offen -s_endpgm diff --git a/runtime/test/shaders/cs_w64x_saveexec_b64.asm b/runtime/test/shaders/cs_w64x_saveexec_b64.asm deleted file mode 100644 index 51ab51a2e..000000000 --- a/runtime/test/shaders/cs_w64x_saveexec_b64.asm +++ /dev/null @@ -1,167 +0,0 @@ -; regen_fixtures: this source has a translator fixture in tests/semantic/fixtures/disasm -; s_and_saveexec_b64 and s_or_saveexec_b64 with a compare result in VCC or in an SGPR pair, and s_andn2_saveexec_b64 / -; s_andn2_wrexec_b64 with an SGPR-pair source (their VCC form is in cs_w64x_andn2_exec.asm; constant sources are in -; cs_w64_mask_imm.asm), in one 64-lane wave (v1 = lane 0..63). -; RDNA2 ISA: s_and_saveexec_b64: D = EXEC; EXEC = S0 & EXEC; SCC = (EXEC != 0) -; s_or_saveexec_b64: D = EXEC; EXEC = S0 | EXEC; SCC = (EXEC != 0) -; s_andn2_saveexec_b64: D = EXEC; EXEC = S0 & ~EXEC; SCC = (EXEC != 0) -; s_andn2_wrexec_b64: EXEC = S0 & ~EXEC; D = EXEC; SCC = (EXEC != 0) (D gets the new EXEC) -; S0 is written by a v_cmp with all 64 lanes on. The masks are only looked at through mask-aware instructions -; (s_bcnt1, s_ff1, v_cmp into VCC), not read as data. A mask is reported as bcnt << 8 | ff1 (population count, -; lowest lane). Old EXEC and S0 differ between the two halves in every case, so a swap of the halves moves the -; lowest lane and a result cut to 32 bits loses lanes. EXEC is measured per lane: v2 = 1 under the new EXEC, then -; with all lanes on, the lanes with v2 != 0. -; 1) s_and_saveexec_b64 s[20:21], s[10:11]: S0 = lanes 0..39 (v_cmp_gt_u32_e64 40 > lane); -; old EXEC = lanes 16..63 (exec_lo 0xffff0000, exec_hi 0xffffffff). -; EXEC = lanes 16..39 (24 lanes, lowest 16): out[0] = 24 << 8 | 16 = 6160. SCC 1. -; D = lanes 16..63 (48 lanes, lowest 16): out[1] = 48 << 8 | 16 = 12304. -; 2) s_or_saveexec_b64 s[22:23], vcc: S0 = lanes 0..11 (v_cmp_gt_u32_e32 12 > lane); -; old EXEC = lanes 40..47 (exec_lo 0, exec_hi 0x0000ff00). -; EXEC = lanes 0..11 and 40..47 (20 lanes, lowest 0): out[2] = 20 << 8 = 5120. SCC 1. -; (halves swapped: lanes 8..15 and 32..43, lowest 8; the low word only: 12 lanes.) -; D = lanes 40..47: out[3] = 8 << 8 | 40 = 2088. -; 3a) s_or_saveexec_b64 s[24:25], s[12:13]: S0 = no lane (0 > lane), old EXEC = 0: EXEC = 0, SCC 0. -; 3b) s_and_saveexec_b64 s[26:27], vcc: S0 = lanes 0..31, old EXEC = lanes 32..63: EXEC = 0, SCC 0 -; (with the halves of either swapped it would be 32 lanes, SCC 1). -; 3c) s_and_saveexec_b64 s[34:35], vcc: S0 = lanes 48..63, old EXEC = lanes 0..15 and 32..63: -; EXEC = lanes 48..63 (the low half is empty), SCC 1 (an SCC from the low word alone would be 0). -; 4a) s_andn2_saveexec_b64 s[28:29], s[14:15]: S0 = lanes 24..63 (v_cmp_le_u32_e64 24 <= lane); -; old EXEC = lanes 0..15 and 48..63 (exec_lo 0xffff, exec_hi 0xffff0000), ~EXEC = lanes 16..47. -; EXEC = lanes 24..47 (24 lanes, lowest 24): out[4] = 24 << 8 | 24 = 6168. SCC 1. -; D = the old EXEC (32 lanes, lowest 0): out[5] = 32 << 8 = 8192. -; 4b) s_andn2_wrexec_b64 s[30:31], s[16:17]: S0 = lanes 0..35 (v_cmp_gt_u32_e64 36 > lane); -; old EXEC = lanes 0..7 (exec_lo 0xff, exec_hi 0). EXEC = lanes 8..35 (28 lanes, lowest 8), SCC 1. -; D = the new EXEC: out[6] = 28 << 8 | 8 = 7176 (the old EXEC would give 8 << 8 = 2048). -; out[7] = SCC bits (1: case 1, 2: case 2, 4: 3a, 8: 3b, 16: 3c, 32: 4a, 64: 4b) = 1 + 2 + 16 + 32 + 64 = 115, -; plus (bcnt << 8 | ff1 of EXEC after 4b, read with s_bcnt1/s_ff1 on exec) << 8 = 7176 << 8: -; 115 + 1837056 = 1837171. -; Lane 0 stores the eight words. -; Run: vk_compute_test cs_w64x_saveexec_b64.spv 1 dump --require-wave64 -; -> out[0..7] = 6160 12304 5120 2088 6168 8192 7176 1837171 -; mattr: +wavefrontsize64,-wavefrontsize32 -v_mbcnt_lo_u32_b32 v1, -1, 0 -v_mbcnt_hi_u32_b32 v1, -1, v1 -v_mov_b32_e32 v2, 0 -; 1) s_and_saveexec_b64, SGPR-pair source -v_cmp_gt_u32_e64 s[10:11], 40, v1 -s_mov_b32 exec_lo, 0xffff0000 -s_mov_b32 exec_hi, -1 -s_and_saveexec_b64 s[20:21], s[10:11] -s_cselect_b32 s40, 1, 0 -v_mov_b32_e32 v2, 1 -s_mov_b64 exec, -1 -v_cmp_ne_u32_e32 vcc, 0, v2 -s_bcnt1_i32_b64 s41, vcc -s_ff1_i32_b64 s42, vcc -s_lshl_b32 s41, s41, 8 -s_or_b32 s41, s41, s42 -s_bcnt1_i32_b64 s43, s[20:21] -s_ff1_i32_b64 s44, s[20:21] -s_lshl_b32 s43, s43, 8 -s_or_b32 s43, s43, s44 -v_mov_b32_e32 v2, 0 -; 2) s_or_saveexec_b64, VCC source -v_cmp_gt_u32_e32 vcc, 12, v1 -s_mov_b32 exec_lo, 0 -s_mov_b32 exec_hi, 0xff00 -s_or_saveexec_b64 s[22:23], vcc -s_cselect_b32 s45, 2, 0 -v_mov_b32_e32 v2, 1 -s_mov_b64 exec, -1 -v_cmp_ne_u32_e32 vcc, 0, v2 -s_bcnt1_i32_b64 s46, vcc -s_ff1_i32_b64 s47, vcc -s_lshl_b32 s46, s46, 8 -s_or_b32 s46, s46, s47 -s_bcnt1_i32_b64 s48, s[22:23] -s_ff1_i32_b64 s49, s[22:23] -s_lshl_b32 s48, s48, 8 -s_or_b32 s48, s48, s49 -v_mov_b32_e32 v2, 0 -s_or_b32 s40, s40, s45 -; 3a) s_or_saveexec_b64 to an empty EXEC -v_cmp_gt_u32_e64 s[12:13], 0, v1 -s_mov_b32 exec_lo, 0 -s_mov_b32 exec_hi, 0 -s_or_saveexec_b64 s[24:25], s[12:13] -s_cselect_b32 s45, 4, 0 -s_mov_b64 exec, -1 -s_or_b32 s40, s40, s45 -; 3b) s_and_saveexec_b64 of two halves that do not meet -v_cmp_gt_u32_e32 vcc, 32, v1 -s_mov_b32 exec_lo, 0 -s_mov_b32 exec_hi, -1 -s_and_saveexec_b64 s[26:27], vcc -s_cselect_b32 s45, 8, 0 -s_mov_b64 exec, -1 -s_or_b32 s40, s40, s45 -; 3c) s_and_saveexec_b64 with a result in the high half only -v_cmp_le_u32_e32 vcc, 48, v1 -s_mov_b32 exec_lo, 0xffff -s_mov_b32 exec_hi, -1 -s_and_saveexec_b64 s[34:35], vcc -s_cselect_b32 s45, 16, 0 -s_mov_b64 exec, -1 -s_or_b32 s40, s40, s45 -; 4a) s_andn2_saveexec_b64, SGPR-pair source -v_cmp_le_u32_e64 s[14:15], 24, v1 -s_mov_b32 exec_lo, 0xffff -s_mov_b32 exec_hi, 0xffff0000 -s_andn2_saveexec_b64 s[28:29], s[14:15] -s_cselect_b32 s45, 32, 0 -v_mov_b32_e32 v2, 1 -s_mov_b64 exec, -1 -s_or_b32 s40, s40, s45 -v_cmp_ne_u32_e32 vcc, 0, v2 -s_bcnt1_i32_b64 s50, vcc -s_ff1_i32_b64 s51, vcc -s_lshl_b32 s50, s50, 8 -s_or_b32 s50, s50, s51 -s_bcnt1_i32_b64 s52, s[28:29] -s_ff1_i32_b64 s53, s[28:29] -s_lshl_b32 s52, s52, 8 -s_or_b32 s52, s52, s53 -; 4b) s_andn2_wrexec_b64, SGPR-pair source -v_cmp_gt_u32_e64 s[16:17], 36, v1 -s_mov_b32 exec_lo, 0xff -s_mov_b32 exec_hi, 0 -s_andn2_wrexec_b64 s[30:31], s[16:17] -s_cselect_b32 s45, 64, 0 -s_bcnt1_i32_b64 s54, exec -s_ff1_i32_b64 s55, exec -s_mov_b64 exec, -1 -s_or_b32 s40, s40, s45 -s_lshl_b32 s54, s54, 8 -s_or_b32 s54, s54, s55 -s_lshl_b32 s54, s54, 8 -s_or_b32 s40, s40, s54 -s_bcnt1_i32_b64 s56, s[30:31] -s_ff1_i32_b64 s57, s[30:31] -s_lshl_b32 s56, s56, 8 -s_or_b32 s56, s56, s57 -v_cmpx_eq_u32_e32 0, v1 -v_mov_b32_e32 v20, s41 -v_mov_b32_e32 v21, 0 -buffer_store_dword v20, v21, s[0:3], 0 offen -v_mov_b32_e32 v20, s43 -v_mov_b32_e32 v21, 4 -buffer_store_dword v20, v21, s[0:3], 0 offen -v_mov_b32_e32 v20, s46 -v_mov_b32_e32 v21, 8 -buffer_store_dword v20, v21, s[0:3], 0 offen -v_mov_b32_e32 v20, s48 -v_mov_b32_e32 v21, 12 -buffer_store_dword v20, v21, s[0:3], 0 offen -v_mov_b32_e32 v20, s50 -v_mov_b32_e32 v21, 16 -buffer_store_dword v20, v21, s[0:3], 0 offen -v_mov_b32_e32 v20, s52 -v_mov_b32_e32 v21, 20 -buffer_store_dword v20, v21, s[0:3], 0 offen -v_mov_b32_e32 v20, s56 -v_mov_b32_e32 v21, 24 -buffer_store_dword v20, v21, s[0:3], 0 offen -v_mov_b32_e32 v20, s40 -v_mov_b32_e32 v21, 28 -buffer_store_dword v20, v21, s[0:3], 0 offen -s_endpgm diff --git a/runtime/test/shaders/cs_w64x_sbarrier.asm b/runtime/test/shaders/cs_w64x_sbarrier.asm deleted file mode 100644 index 74af08c04..000000000 --- a/runtime/test/shaders/cs_w64x_sbarrier.asm +++ /dev/null @@ -1,86 +0,0 @@ -; 128 threads = two wave64s around s_barrier. Wave 0 runs a loop of 5 trips with a cross-half v_readlane (lane 40) -; BEFORE the barrier; wave 1 runs a loop of 2 trips (readlane of lane 50), then writes LDS[lane] = 3000 + lane -; and waits for it (s_waitcnt lgkmcnt(0)). Both reach the one s_barrier, then every lane reads -; LDS[lane ^ 32] (wave 0 reads what wave 1 wrote; its own half-crossing readlane loop must not deadlock or -; desynchronise the barrier). v3 = 3 * tid + 1. -; wave 0: s21 = 5 * v3[lane 40] = 5 * (3 * 40 + 1) = 605 -; wave 1: s21 = 2 * v3[lane 50] = 2 * (3 * (64 + 50) + 1) = 686 -; v10 = 3000 + (lane ^ 32): t0 -> 3032, t45 -> 3000 + 13 = 3013, t64 (lane 0) -> 3032, t127 (lane 63) -> 3031. -; Stores (by thread id): out[0] t0 s21, out[1] t45 s21, out[2] t64 s21, out[3] t127 s21, -; out[4] t0 v10, out[5] t45 v10, out[6] t64 v10, out[7] t127 v10. -; Run: vk_compute_test cs_w64x_sbarrier.spv 1 dump --require-wave64 -; -> out[0..7] = 605 605 686 686 3032 3013 3032 3031 -; mattr: +wavefrontsize64,-wavefrontsize32 -; group: 128,1,1 -v_mbcnt_lo_u32_b32 v1, -1, 0 -v_mbcnt_hi_u32_b32 v1, -1, v1 -v_lshrrev_b32_e32 v2, 6, v0 -v_readfirstlane_b32 s6, v2 -v_mad_u32_u24 v3, v0, 3, 1 -s_cmp_eq_u32 s6, 0 -s_cbranch_scc0 9 -s_mov_b32 s20, 0 -s_mov_b32 s21, 0 -v_readlane_b32 s22, v3, 40 -s_add_u32 s21, s21, s22 -s_add_u32 s20, s20, 1 -s_cmp_lt_u32 s20, 5 -s_cbranch_scc1 -6 -s_branch 14 -s_mov_b32 s20, 0 -s_mov_b32 s21, 0 -v_readlane_b32 s22, v3, 50 -s_add_u32 s21, s21, s22 -s_add_u32 s20, s20, 1 -s_cmp_lt_u32 s20, 2 -s_cbranch_scc1 -6 -v_add_nc_u32_e32 v9, 3000, v1 -v_lshlrev_b32_e32 v8, 2, v1 -ds_write_b32 v8, v9 -s_waitcnt lgkmcnt(0) -s_barrier -v_xor_b32_e32 v11, 32, v1 -v_lshlrev_b32_e32 v11, 2, v11 -ds_read_b32 v10, v11 -s_waitcnt lgkmcnt(0) -s_mov_b64 exec, -1 -v_cmpx_eq_u32_e32 0, v0 -v_mov_b32_e32 v20, s21 -v_mov_b32_e32 v21, 0 -buffer_store_dword v20, v21, s[0:3], 0 offen -s_mov_b64 exec, -1 -v_cmpx_eq_u32_e32 45, v0 -v_mov_b32_e32 v20, s21 -v_mov_b32_e32 v21, 4 -buffer_store_dword v20, v21, s[0:3], 0 offen -s_mov_b64 exec, -1 -v_cmpx_eq_u32_e32 64, v0 -v_mov_b32_e32 v20, s21 -v_mov_b32_e32 v21, 8 -buffer_store_dword v20, v21, s[0:3], 0 offen -s_mov_b64 exec, -1 -v_cmpx_eq_u32_e32 127, v0 -v_mov_b32_e32 v20, s21 -v_mov_b32_e32 v21, 12 -buffer_store_dword v20, v21, s[0:3], 0 offen -s_mov_b64 exec, -1 -v_cmpx_eq_u32_e32 0, v0 -v_mov_b32_e32 v20, v10 -v_mov_b32_e32 v21, 16 -buffer_store_dword v20, v21, s[0:3], 0 offen -s_mov_b64 exec, -1 -v_cmpx_eq_u32_e32 45, v0 -v_mov_b32_e32 v20, v10 -v_mov_b32_e32 v21, 20 -buffer_store_dword v20, v21, s[0:3], 0 offen -s_mov_b64 exec, -1 -v_cmpx_eq_u32_e32 64, v0 -v_mov_b32_e32 v20, v10 -v_mov_b32_e32 v21, 24 -buffer_store_dword v20, v21, s[0:3], 0 offen -s_mov_b64 exec, -1 -v_cmpx_eq_u32_e32 127, v0 -v_mov_b32_e32 v20, v10 -v_mov_b32_e32 v21, 28 -buffer_store_dword v20, v21, s[0:3], 0 offen -s_endpgm diff --git a/runtime/test/shaders/cs_w64x_wg128_branches.asm b/runtime/test/shaders/cs_w64x_wg128_branches.asm deleted file mode 100644 index 589c4e5a8..000000000 --- a/runtime/test/shaders/cs_w64x_wg128_branches.asm +++ /dev/null @@ -1,81 +0,0 @@ -; 128-thread workgroup = two wave64s (v0 = thread id 0-127, v1 = lane in its wave). The waves take DIFFERENT -; wave-uniform branches (s6 = wave id from v_readfirstlane of v0 >> 6, s_cmp_eq + s_cbranch_scc0) and each does -; cross-half work INSIDE its branch. v3 = 3 * tid + 1, v10 = 0. -; Wave 0: s8 = readlane(v3, 40) = 3 * 40 + 1 = 121; ballot (49 < lane) = lanes 50-63 -> s9 = 14; -; v_writelane(v10, 77, lane 44) then readlane(v10, 44) = 77; s10 = 100 + (77 << 8) = 19812. -; Wave 1: s8 = readlane(v3, 50) = 3 * (64 + 50) + 1 = 343; ballot (32 < lane) = lanes 33-63 -> s9 = 31; -; writelane 88 into lane 55, readlane -> 88; s10 = 200 + (88 << 8) = 22728. -; Stores (by thread id): out[0] t0 s8 = 121, out[1] t45 s8 = 121, out[2] t64 s8 = 343, out[3] t127 s8 = 343, -; out[4] t33 s9 = 14, out[5] t100 s9 = 31, out[6] t1 s10 = 19812, out[7] t127 s10 = 22728. -; A wave decided per 32-lane half, or a readlane >= 32 that wraps, changes these. Needs a 128x1x1 group header -; (the group directive below; build.py and run_gpu_tests.py read it). -; Run: vk_compute_test cs_w64x_wg128_branches.spv 1 dump --require-wave64 -; -> out[0..7] = 121 121 343 343 14 31 19812 22728 -; mattr: +wavefrontsize64,-wavefrontsize32 -; group: 128,1,1 -v_mbcnt_lo_u32_b32 v1, -1, 0 -v_mbcnt_hi_u32_b32 v1, -1, v1 -v_lshrrev_b32_e32 v2, 6, v0 -v_readfirstlane_b32 s6, v2 -v_mad_u32_u24 v3, v0, 3, 1 -v_mov_b32_e32 v10, 0 -s_cmp_eq_u32 s6, 0 -s_cbranch_scc0 14 -v_readlane_b32 s8, v3, 40 -v_cmp_lt_u32_e64 s[4:5], 49, v1 -s_bcnt1_i32_b64 s9, s[4:5] -s_mov_b32 s11, 77 -v_writelane_b32 v10, s11, 44 -v_readlane_b32 s12, v10, 44 -s_mov_b32 s10, 100 -s_branch 13 -v_readlane_b32 s8, v3, 50 -v_cmp_lt_u32_e64 s[4:5], 32, v1 -s_bcnt1_i32_b64 s9, s[4:5] -s_mov_b32 s11, 88 -v_writelane_b32 v10, s11, 55 -v_readlane_b32 s12, v10, 55 -s_mov_b32 s10, 200 -s_lshl_b32 s12, s12, 8 -s_add_u32 s10, s10, s12 -s_mov_b64 exec, -1 -v_cmpx_eq_u32_e32 0, v0 -v_mov_b32_e32 v20, s8 -v_mov_b32_e32 v21, 0 -buffer_store_dword v20, v21, s[0:3], 0 offen -s_mov_b64 exec, -1 -v_cmpx_eq_u32_e32 45, v0 -v_mov_b32_e32 v20, s8 -v_mov_b32_e32 v21, 4 -buffer_store_dword v20, v21, s[0:3], 0 offen -s_mov_b64 exec, -1 -v_cmpx_eq_u32_e32 64, v0 -v_mov_b32_e32 v20, s8 -v_mov_b32_e32 v21, 8 -buffer_store_dword v20, v21, s[0:3], 0 offen -s_mov_b64 exec, -1 -v_cmpx_eq_u32_e32 127, v0 -v_mov_b32_e32 v20, s8 -v_mov_b32_e32 v21, 12 -buffer_store_dword v20, v21, s[0:3], 0 offen -s_mov_b64 exec, -1 -v_cmpx_eq_u32_e32 33, v0 -v_mov_b32_e32 v20, s9 -v_mov_b32_e32 v21, 16 -buffer_store_dword v20, v21, s[0:3], 0 offen -s_mov_b64 exec, -1 -v_cmpx_eq_u32_e32 100, v0 -v_mov_b32_e32 v20, s9 -v_mov_b32_e32 v21, 20 -buffer_store_dword v20, v21, s[0:3], 0 offen -s_mov_b64 exec, -1 -v_cmpx_eq_u32_e32 1, v0 -v_mov_b32_e32 v20, s10 -v_mov_b32_e32 v21, 24 -buffer_store_dword v20, v21, s[0:3], 0 offen -s_mov_b64 exec, -1 -v_cmpx_eq_u32_e32 127, v0 -v_mov_b32_e32 v20, s10 -v_mov_b32_e32 v21, 28 -buffer_store_dword v20, v21, s[0:3], 0 offen -s_endpgm diff --git a/runtime/test/shaders/cs_w64x_writelane.asm b/runtime/test/shaders/cs_w64x_writelane.asm deleted file mode 100644 index eaca7c8a2..000000000 --- a/runtime/test/shaders/cs_w64x_writelane.asm +++ /dev/null @@ -1,66 +0,0 @@ -; regen_fixtures: this source has a translator fixture in tests/semantic/fixtures/disasm -; Wave64 cross-half v_writelane_b32 (writes lane S1 % 64 of the VGPR, EXEC ignored). Crosses: writes into lanes -; >= 32 (a 32-wide subgroup never matches lane select >= 32, so those writes are lost), the dynamic lane select -; 96 % 64 = 32 (first lane of the upper half), and a readlane of the written upper lanes from the low half. -; v10 = 0 everywhere, then v10[40] = 0x1234 (4660), v10[3] = 77, v10[63] = 99, v10[96 % 64 = 32] = 0xabc (2748). -; out[0] lane 40 stores v10 = 4660 out[1] lane 3 stores v10 = 77 out[2] lane 63 stores v10 = 99 -; out[3] lane 32 stores v10 = 2748 out[4] lane 39 stores v10 = 0 out[5] lane 41 stores v10 = 0 (neighbours untouched) -; out[6] lane 0 stores readlane(v10, 40) = 4660 out[7] lane 8 stores readlane(v10, 63) = 99 -; Run: vk_compute_test cs_w64x_writelane.spv 1 dump --require-wave64 -; -> out[0..7] = 4660 77 99 2748 0 0 4660 99 -; mattr: +wavefrontsize64,-wavefrontsize32 -v_mbcnt_lo_u32_b32 v1, -1, 0 -v_mbcnt_hi_u32_b32 v1, -1, v1 -v_mov_b32_e32 v10, 0 -s_mov_b32 s6, 0x1234 -s_mov_b32 s7, 77 -s_mov_b32 s8, 99 -s_mov_b32 s11, 0xabc -s_mov_b32 s9, 96 -v_writelane_b32 v10, s6, 40 -v_writelane_b32 v10, s7, 3 -v_writelane_b32 v10, s8, 63 -v_writelane_b32 v10, s11, s9 -v_readlane_b32 s12, v10, 40 -v_readlane_b32 s13, v10, 63 -s_mov_b64 exec, -1 -v_cmpx_eq_u32_e32 40, v1 -v_mov_b32_e32 v20, v10 -v_mov_b32_e32 v21, 0 -buffer_store_dword v20, v21, s[0:3], 0 offen -s_mov_b64 exec, -1 -v_cmpx_eq_u32_e32 3, v1 -v_mov_b32_e32 v20, v10 -v_mov_b32_e32 v21, 4 -buffer_store_dword v20, v21, s[0:3], 0 offen -s_mov_b64 exec, -1 -v_cmpx_eq_u32_e32 63, v1 -v_mov_b32_e32 v20, v10 -v_mov_b32_e32 v21, 8 -buffer_store_dword v20, v21, s[0:3], 0 offen -s_mov_b64 exec, -1 -v_cmpx_eq_u32_e32 32, v1 -v_mov_b32_e32 v20, v10 -v_mov_b32_e32 v21, 12 -buffer_store_dword v20, v21, s[0:3], 0 offen -s_mov_b64 exec, -1 -v_cmpx_eq_u32_e32 39, v1 -v_mov_b32_e32 v20, v10 -v_mov_b32_e32 v21, 16 -buffer_store_dword v20, v21, s[0:3], 0 offen -s_mov_b64 exec, -1 -v_cmpx_eq_u32_e32 41, v1 -v_mov_b32_e32 v20, v10 -v_mov_b32_e32 v21, 20 -buffer_store_dword v20, v21, s[0:3], 0 offen -s_mov_b64 exec, -1 -v_cmpx_eq_u32_e32 0, v1 -v_mov_b32_e32 v20, s12 -v_mov_b32_e32 v21, 24 -buffer_store_dword v20, v21, s[0:3], 0 offen -s_mov_b64 exec, -1 -v_cmpx_eq_u32_e32 8, v1 -v_mov_b32_e32 v20, s13 -v_mov_b32_e32 v21, 28 -buffer_store_dword v20, v21, s[0:3], 0 offen -s_endpgm diff --git a/runtime/test/shaders/cs_wave64_ballot.asm b/runtime/test/shaders/cs_wave64_ballot.asm deleted file mode 100644 index 545e5c11d..000000000 --- a/runtime/test/shaders/cs_wave64_ballot.asm +++ /dev/null @@ -1,40 +0,0 @@ -; regen_fixtures: this source has a translator fixture in tests/semantic/fixtures/disasm -; Wave64 ballot: s_bcnt1_i32_b64 and s_ff1_i32_b64 on 64-lane comparison masks and EXEC. -; mattr: +wavefrontsize64,-wavefrontsize32 -; Case 1: lanes 16..47 -> s[4:5] -> bcnt=32, ff1=16 -; Case 2: lanes 40..63 (strictly upper half) -> s[10:11] -> bcnt=24, ff1=40 -; Case 3: exec = lanes 48..55 -> bcnt=8, ff1=48 -; Run: VKC_SUBGROUP_SIZE=64 vk_compute_test cs_wave64_ballot.spv 1 dump --require-wave64 -> out[0..5] = 32, 16, 24, 40, 8, 48 -v_cmp_ge_u32_e64 s[4:5], v0, 16 -v_cmp_lt_u32_e64 s[6:7], v0, 48 -s_and_b64 s[4:5], s[4:5], s[6:7] -s_bcnt1_i32_b64 s8, s[4:5] -s_ff1_i32_b64 s9, s[4:5] -v_cmp_ge_u32_e64 s[10:11], v0, 40 -s_bcnt1_i32_b64 s12, s[10:11] -s_ff1_i32_b64 s13, s[10:11] -s_mov_b32 exec_lo, 0 -s_mov_b32 exec_hi, 0x00ff0000 -s_bcnt1_i32_b64 s14, exec -s_ff1_i32_b64 s15, exec -s_mov_b64 exec, -1 -v_cmpx_eq_u32_e32 0, v0 -v_mov_b32_e32 v1, s8 -v_mov_b32_e32 v2, s9 -v_mov_b32_e32 v3, s12 -v_mov_b32_e32 v4, s13 -v_mov_b32_e32 v5, s14 -v_mov_b32_e32 v6, s15 -v_mov_b32_e32 v10, 0 -v_mov_b32_e32 v11, 4 -v_mov_b32_e32 v12, 8 -v_mov_b32_e32 v13, 12 -v_mov_b32_e32 v14, 16 -v_mov_b32_e32 v15, 20 -buffer_store_dword v1, v10, s[0:3], 0 offen -buffer_store_dword v2, v11, s[0:3], 0 offen -buffer_store_dword v3, v12, s[0:3], 0 offen -buffer_store_dword v4, v13, s[0:3], 0 offen -buffer_store_dword v5, v14, s[0:3], 0 offen -buffer_store_dword v6, v15, s[0:3], 0 offen -s_endpgm diff --git a/runtime/test/shaders/cs_wavemask.asm b/runtime/test/shaders/cs_wavemask.asm deleted file mode 100644 index 1eefd2ac1..000000000 --- a/runtime/test/shaders/cs_wavemask.asm +++ /dev/null @@ -1,65 +0,0 @@ -; regen_fixtures: this source has a translator fixture in tests/semantic/fixtures/disasm -; Wave64 compute: instructions that read a lane mask as a whole, on a partly active wave. EXEC = lanes 16-47 -; (exec_lo = 0xffff0000, exec_hi = 0xffff), saved in s[6:7]. s_bcnt1 of EXEC and of the saved pair = 32 each, -; s_ff1 of EXEC = 16, s_bcnt1 of a compare result (lane < 24: lanes 16-23, VCC is clear outside EXEC) = 8, -; v_mbcnt_lo/hi of the saved pair = set lanes below this one = t - 16. Scalars are wave-wide: every lane stores them. -; s_cmp_lg_u32 of the low half with 0 is true for the wave (+1), s_cmp_eq_u64 of the pair with 0 is false (+0). -; Then the saved pair is parked in lanes 0 and 1 of v10 (v_writelane, as a shader out of SGPRs does), fetched back -; with all lanes on, and moved into EXEC: lanes 16-47 again, which set bit 7 of the top byte. A second copy goes -; through the vector unit (v_mov_b32 / v_or3_b32 / v_readfirstlane_b32, the way three SGPRs get ORed) into s[12:13] -; and into EXEC: the same lanes set bit 6. -; Same FSSM header as cs_lds. Run: vk_compute_test cs_wavemask.spv 1 wavemask --require-wave64 -; -> out[t] = 65 | 16 << 8 | 8 << 16 | (0xc0 + t - 16 for t in 16..47, else 0) << 24 -v_mbcnt_lo_u32_b32 v1, -1, 0 -v_mbcnt_hi_u32_b32 v1, -1, v1 -v_lshlrev_b32_e32 v3, 2, v1 -v_mov_b32_e32 v4, 0 -s_mov_b32 exec_lo, 0xffff0000 -s_mov_b32 exec_hi, 0xffff -s_mov_b64 s[6:7], exec -s_bcnt1_i32_b64 s8, exec -s_bcnt1_i32_b64 s10, s[6:7] -s_add_i32 s8, s8, s10 -s_cmp_lg_u32 s6, 0 -s_cselect_b32 s14, 1, 0 -s_add_i32 s8, s8, s14 -s_cmp_eq_u64 s[6:7], 0 -s_cselect_b32 s14, 2, 0 -s_add_i32 s8, s8, s14 -s_ff1_i32_b64 s9, exec -v_cmp_gt_u32_e32 vcc_lo, 24, v1 -s_bcnt1_i32_b64 s11, vcc -v_mbcnt_lo_u32_b32 v4, s6, 0 -v_mbcnt_hi_u32_b32 v4, s7, v4 -v_mov_b32_e32 v6, s6 -v_or3_b32 v6, s6, s6, v6 -v_readfirstlane_b32 s12, v6 -v_mov_b32_e32 v6, s7 -v_readfirstlane_b32 s13, v6 -v_writelane_b32 v10, s6, 0 -v_writelane_b32 v10, s7, 1 -s_mov_b32 exec_lo, -1 -s_mov_b32 exec_hi, -1 -s_mov_b32 s6, 0 -s_mov_b32 s7, 0 -v_mov_b32_e32 v5, 0 -v_readlane_b32 s6, v10, 0 -v_readlane_b32 s7, v10, 1 -s_mov_b64 exec, s[6:7] -v_mov_b32_e32 v5, 0x80 -s_mov_b32 exec_lo, -1 -s_mov_b32 exec_hi, -1 -v_mov_b32_e32 v7, 0 -s_mov_b64 exec, s[12:13] -v_mov_b32_e32 v7, 0x40 -s_mov_b32 exec_lo, -1 -s_mov_b32 exec_hi, -1 -s_lshl_b32 s9, s9, 8 -s_lshl_b32 s11, s11, 16 -s_or_b32 s8, s8, s9 -s_or_b32 s8, s8, s11 -v_or3_b32 v4, v4, v5, v7 -v_lshlrev_b32_e32 v4, 24, v4 -v_or_b32_e32 v2, s8, v4 -buffer_store_dword v2, v3, s[0:3], 0 offen -s_endpgm diff --git a/runtime/test/shaders/cs_wm_bfm64.asm b/runtime/test/shaders/cs_wm_bfm64.asm deleted file mode 100644 index 4bd27f205..000000000 --- a/runtime/test/shaders/cs_wm_bfm64.asm +++ /dev/null @@ -1,26 +0,0 @@ -; regen_fixtures: this source has a translator fixture in tests/semantic/fixtures/disasm -; Wave64 s_bfm_b64 lane-mask tracking (low half and high half bitfields). -; Assemble (as scripts/run_gpu_tests.py / build.py do): llvm-mc -triple=amdgcn--amdpal -mcpu=gfx1013 -show-encoding (wave64 is inferred by the translator from exec_hi/_b64 EXEC use) -; Run: VKC_SUBGROUP_SIZE=64 vk_compute_test cs_wm_bfm64.spv 1 dump -; Expect: out[0..3] = 16 8 8 40 -s_mov_b64 exec, -1 -s_bfm_b64 s[6:7], 16, 8 -s_bcnt1_i32_b64 s8, s[6:7] -s_ff1_i32_b64 s9, s[6:7] -s_bfm_b64 s[10:11], 8, 40 -s_bcnt1_i32_b64 s12, s[10:11] -s_ff1_i32_b64 s13, s[10:11] -v_cmpx_eq_u32_e32 0, v0 -v_mov_b32_e32 v1, s8 -v_mov_b32_e32 v2, 0 -buffer_store_dword v1, v2, s[0:3], 0 offen -v_mov_b32_e32 v1, s9 -v_mov_b32_e32 v2, 4 -buffer_store_dword v1, v2, s[0:3], 0 offen -v_mov_b32_e32 v1, s12 -v_mov_b32_e32 v2, 8 -buffer_store_dword v1, v2, s[0:3], 0 offen -v_mov_b32_e32 v1, s13 -v_mov_b32_e32 v2, 12 -buffer_store_dword v1, v2, s[0:3], 0 offen -s_endpgm diff --git a/runtime/test/shaders/cs_wm_half_cmp.asm b/runtime/test/shaders/cs_wm_half_cmp.asm deleted file mode 100644 index fe284a4f1..000000000 --- a/runtime/test/shaders/cs_wm_half_cmp.asm +++ /dev/null @@ -1,31 +0,0 @@ -; regen_fixtures: this source has a translator fixture in tests/semantic/fixtures/disasm -; Wave64 32-bit scalar compare on a zero low half / non-zero high half. -; Assemble (as scripts/run_gpu_tests.py / build.py do): llvm-mc -triple=amdgcn--amdpal -mcpu=gfx1013 -show-encoding (wave64 is inferred by the translator from exec_hi/_b64 EXEC use) -; Run: VKC_SUBGROUP_SIZE=64 vk_compute_test cs_wm_half_cmp.spv 1 dump -; Expect: out[0..3] = 1 0 1 1 -s_mov_b32 exec_lo, 0 -s_mov_b32 exec_hi, 0xffff -s_mov_b64 s[6:7], exec -s_cmp_eq_u32 s6, 0 -s_cselect_b32 s8, 1, 0 -s_cmp_lg_u32 s6, 0 -s_cselect_b32 s9, 1, 0 -s_cmp_lg_u32 s7, 0 -s_cselect_b32 s10, 1, 0 -s_cmp_eq_u32 exec_lo, 0 -s_cselect_b32 s11, 1, 0 -s_mov_b64 exec, -1 -v_cmpx_eq_u32_e32 0, v0 -v_mov_b32_e32 v1, s8 -v_mov_b32_e32 v2, 0 -buffer_store_dword v1, v2, s[0:3], 0 offen -v_mov_b32_e32 v1, s9 -v_mov_b32_e32 v2, 4 -buffer_store_dword v1, v2, s[0:3], 0 offen -v_mov_b32_e32 v1, s10 -v_mov_b32_e32 v2, 8 -buffer_store_dword v1, v2, s[0:3], 0 offen -v_mov_b32_e32 v1, s11 -v_mov_b32_e32 v2, 12 -buffer_store_dword v1, v2, s[0:3], 0 offen -s_endpgm diff --git a/runtime/test/shaders/cs_wm_half_ops.asm b/runtime/test/shaders/cs_wm_half_ops.asm deleted file mode 100644 index d81d69cad..000000000 --- a/runtime/test/shaders/cs_wm_half_ops.asm +++ /dev/null @@ -1,31 +0,0 @@ -; Wave64 half-mask bcnt1/ff1 and cross-BB mask survival. -; Assemble (as scripts/run_gpu_tests.py / build.py do): llvm-mc -triple=amdgcn--amdpal -mcpu=gfx1013 -show-encoding (wave64 is inferred by the translator from exec_hi/_b64 EXEC use) -; Run: VKC_SUBGROUP_SIZE=64 vk_compute_test cs_wm_half_ops.spv 1 dump -; Expect: out[0..4] = 32 16 16 0 16 -s_mov_b32 exec_lo, 0xffff0000 -s_mov_b32 exec_hi, 0xffff -s_mov_b64 s[6:7], exec -s_branch 0 ; to the next instruction: starts a new basic block -s_bcnt1_i32_b64 s8, s[6:7] -s_ff1_i32_b64 s9, s[6:7] -s_bcnt1_i32_b32 s10, exec_lo -s_ff1_i32_b32 s11, exec_hi -s_bcnt1_i32_b32 s12, s7 -s_mov_b64 exec, -1 -v_cmpx_eq_u32_e32 0, v0 -v_mov_b32_e32 v1, s8 -v_mov_b32_e32 v2, 0 -buffer_store_dword v1, v2, s[0:3], 0 offen -v_mov_b32_e32 v1, s9 -v_mov_b32_e32 v2, 4 -buffer_store_dword v1, v2, s[0:3], 0 offen -v_mov_b32_e32 v1, s10 -v_mov_b32_e32 v2, 8 -buffer_store_dword v1, v2, s[0:3], 0 offen -v_mov_b32_e32 v1, s11 -v_mov_b32_e32 v2, 12 -buffer_store_dword v1, v2, s[0:3], 0 offen -v_mov_b32_e32 v1, s12 -v_mov_b32_e32 v2, 16 -buffer_store_dword v1, v2, s[0:3], 0 offen -s_endpgm diff --git a/runtime/test/shaders/cs_wm_scc_rfl.asm b/runtime/test/shaders/cs_wm_scc_rfl.asm deleted file mode 100644 index 92bd096fb..000000000 --- a/runtime/test/shaders/cs_wm_scc_rfl.asm +++ /dev/null @@ -1,25 +0,0 @@ -; Wave64 uniform SCC after s_and_saveexec_b64 and v_readfirstlane_b32 broadcast. -; Assemble (as scripts/run_gpu_tests.py / build.py do): llvm-mc -triple=amdgcn--amdpal -mcpu=gfx1013 -show-encoding (wave64 is inferred by the translator from exec_hi/_b64 EXEC use) -; Run: VKC_SUBGROUP_SIZE=64 vk_compute_test cs_wm_scc_rfl.spv 1 dump -; Expect: out[0..1] = 55 48 -s_mov_b32 s14, 0 -v_cmp_gt_u32_e32 vcc_lo, 16, v0 -s_and_saveexec_b64 s[6:7], vcc -s_cbranch_scc0 1 ; skip the one-dword s_mov_b32 s14, 55 -s_mov_b32 s14, 55 -s_mov_b64 exec, -1 -v_add_nc_u32_e32 v4, 32, v0 -s_mov_b32 exec_lo, 0xffff0000 -s_mov_b32 exec_hi, 0xffff -v_readfirstlane_b32 s15, v4 -s_mov_b64 exec, -1 -v_cmpx_eq_u32_e32 32, v0 -v_mov_b32_e32 v1, s14 -v_mov_b32_e32 v2, 0 -buffer_store_dword v1, v2, s[0:3], 0 offen -s_mov_b64 exec, -1 -v_cmpx_eq_u32_e32 0, v0 -v_mov_b32_e32 v1, s15 -v_mov_b32_e32 v2, 4 -buffer_store_dword v1, v2, s[0:3], 0 offen -s_endpgm diff --git a/runtime/test/shaders/cs_workgroup_yz.asm b/runtime/test/shaders/cs_workgroup_yz.asm deleted file mode 100644 index 119c8b2eb..000000000 --- a/runtime/test/shaders/cs_workgroup_yz.asm +++ /dev/null @@ -1,15 +0,0 @@ -; group: 1,1,1 -; rsrc2: 0x308 -; Run: vk_compute_test cs_workgroup_yz.spv 2x3x4 workgroup_yz -; One invocation per group. RSRC2 0x308 enables Y and Z only, so s4 = group Y, s5 = group Z. -; Each (Y, Z) bin must receive two increments, one per X group. Overflow bins must stay zero. -; A single group dispatched at a known base must increment only that base's (Y, Z) bin. -s_min_u32 s6, s4, 3 -s_min_u32 s7, s5, 4 -s_lshl_b32 s7, s7, 2 -s_add_u32 s6, s7, s6 -s_lshl_b32 s6, s6, 2 -v_mov_b32_e32 v0, s6 -v_mov_b32_e32 v1, 1 -buffer_atomic_add v1, v0, s[0:3], 0 offen -s_endpgm diff --git a/runtime/test/shaders/cs_wqm_w32.asm b/runtime/test/shaders/cs_wqm_w32.asm deleted file mode 100644 index 8f6a1d10f..000000000 --- a/runtime/test/shaders/cs_wqm_w32.asm +++ /dev/null @@ -1,59 +0,0 @@ -; Wave32 whole-quad mode (s_wqm_b32) on EXEC, on VCC, on data. A quad is 4 aligned lanes. Derivation (bits are lanes): -; exec_lo = 0x80000240 (lanes 6, 9, 31): WQM = quad 1 0xF0 | quad 2 0xF00 | quad 7 0xF0000000 = 0xF0000FF0 -; out0 = s_bcnt1_i32_b32 exec_lo after s_wqm_b32 exec_lo, exec_lo (EXEC as destination) = 12 -; out1 = SCC after it (cselect) = 1 -; out2 = VCC = lane 5 only (v_cmp_eq) -> s_wqm_b32 vcc_lo, vcc_lo -> quad 1 (lanes 4-7) -> s_bcnt1_i32_b32 = 4 -; out3 = SCC after s_wqm_b32 of an empty mask (exec_lo = 0) = 0 -; out4 = exec_lo = 0x18 (lanes 3 and 4, two different quads, neighbours across the quad edge): WQM = 0xFF -> bcnt 8 -; out5 = data (not a mask): s20 = 0x00800010 (bit 4, bit 23) -> 0x00F000F0 = 15728880 -; out6 = s_ff1_i32_b32 of the exec result of out0 (lowest lane of 0xF0000FF0) = 4 -; out7 = s_wqm_b32 of an all-ones mask -> s_bcnt1_i32_b32 = 32 -; Assemble (as scripts/run_gpu_tests.py / build.py do): llvm-mc -triple=amdgcn--amdpal -mcpu=gfx1013 -show-encoding (wave32: only exec_lo and 32-bit operations) -; Run: vk_compute_test cs_wqm_w32.spv 1 dump -; Expect: out[0..7] = 12 1 4 0 8 15728880 4 32 -s_mov_b32 exec_lo, 0x80000240 -s_wqm_b32 exec_lo, exec_lo -s_cselect_b32 s9, 1, 0 -s_bcnt1_i32_b32 s8, exec_lo -s_ff1_i32_b32 s14, exec_lo -s_mov_b32 exec_lo, -1 -v_cmp_eq_u32_e32 vcc_lo, 5, v0 -s_wqm_b32 vcc_lo, vcc_lo -s_bcnt1_i32_b32 s10, vcc_lo -s_mov_b32 exec_lo, 0 -s_wqm_b32 s11, exec_lo -s_cselect_b32 s12, 1, 0 -s_mov_b32 exec_lo, 0x18 -s_wqm_b32 s16, exec_lo -s_bcnt1_i32_b32 s13, s16 -s_mov_b32 s20, 0x00800010 -s_wqm_b32 s21, s20 -s_mov_b32 exec_lo, -1 -s_wqm_b32 s17, exec_lo -s_bcnt1_i32_b32 s15, s17 -v_cmpx_eq_u32_e32 0, v0 -v_mov_b32_e32 v1, s8 -v_mov_b32_e32 v2, 0 -buffer_store_dword v1, v2, s[0:3], 0 offen -v_mov_b32_e32 v1, s9 -v_mov_b32_e32 v2, 4 -buffer_store_dword v1, v2, s[0:3], 0 offen -v_mov_b32_e32 v1, s10 -v_mov_b32_e32 v2, 8 -buffer_store_dword v1, v2, s[0:3], 0 offen -v_mov_b32_e32 v1, s12 -v_mov_b32_e32 v2, 12 -buffer_store_dword v1, v2, s[0:3], 0 offen -v_mov_b32_e32 v1, s13 -v_mov_b32_e32 v2, 16 -buffer_store_dword v1, v2, s[0:3], 0 offen -v_mov_b32_e32 v1, s21 -v_mov_b32_e32 v2, 20 -buffer_store_dword v1, v2, s[0:3], 0 offen -v_mov_b32_e32 v1, s14 -v_mov_b32_e32 v2, 24 -buffer_store_dword v1, v2, s[0:3], 0 offen -v_mov_b32_e32 v1, s15 -v_mov_b32_e32 v2, 28 -buffer_store_dword v1, v2, s[0:3], 0 offen -s_endpgm diff --git a/runtime/test/shaders/cs_wqm_w64.asm b/runtime/test/shaders/cs_wqm_w64.asm deleted file mode 100644 index 38ad5e738..000000000 --- a/runtime/test/shaders/cs_wqm_w64.asm +++ /dev/null @@ -1,69 +0,0 @@ -; Wave64 whole-quad mode (s_wqm_b64 / s_wqm_b32) on lane masks and on data. A quad is 4 aligned lanes (4n..4n+3), so it -; never crosses lane 31/32. Derivation (bits are lanes): -; mask lo = 0x80000240 (lanes 6, 9, 31), hi = 0x00000102 (lanes 33, 40) -; WQM lo: lane 6 -> quad 1 (4-7) 0xF0, lane 9 -> quad 2 (8-11) 0xF00, lane 31 -> quad 7 (28-31) 0xF0000000 = 0xF0000FF0 -; WQM hi: lane 33 = bit 1 -> quad 0 0xF, lane 40 = bit 8 -> quad 2 0xF00 = 0x00000F0F -; out0 = s_bcnt1_i32_b64 of the b64 result = 12 + 8 = 20, out1 = s_ff1_i32_b64 = 4 (lane 4) -; out2 = s_bcnt1_i32_b32 of s_wqm_b32 on the low half = 12, out3 = same on the high half = 8 -; out4 = SCC after s_wqm_b64 of a mask with only lane 40 set, read by lane 0 whose own quad is empty = 1 (wave-wide any) -; out5 = SCC after s_wqm_b64 of an empty mask (vcc from a v_cmp no lane satisfies) = 0 -; data (not a lane mask): s20 = 0x00800010 (bit 4, bit 23), s21 = 1: WQM = 0x00F000F0 and 0xF -> out6 = s22 + s23 = 15728895 -; out7 = s_bcnt1_i32_b64 after s_wqm_b64 exec, exec (EXEC as destination) = 20 -; Assemble (as scripts/run_gpu_tests.py / build.py do): llvm-mc -triple=amdgcn--amdpal -mcpu=gfx1013 -show-encoding (wave64 is inferred by the translator from exec_hi/_b64 EXEC use) -; Run: VKC_SUBGROUP_SIZE=64 vk_compute_test cs_wqm_w64.spv 1 dump -; Expect: out[0..7] = 20 4 12 8 1 0 15728895 20 -s_mov_b32 exec_lo, 0x80000240 -s_mov_b32 exec_hi, 0x102 -s_mov_b64 s[6:7], exec -s_wqm_b64 s[8:9], s[6:7] -s_bcnt1_i32_b64 s10, s[8:9] -s_ff1_i32_b64 s11, s[8:9] -s_mov_b32 s16, exec_lo -s_mov_b32 s17, exec_hi -s_wqm_b32 s18, s16 -s_bcnt1_i32_b32 s12, s18 -s_wqm_b32 s19, s17 -s_bcnt1_i32_b32 s13, s19 -s_mov_b32 exec_lo, 0 -s_mov_b32 exec_hi, 0x100 -s_mov_b64 s[24:25], exec -s_wqm_b64 s[26:27], s[24:25] -s_cselect_b32 s14, 1, 0 -v_cmp_lt_u32_e32 vcc_lo, 99, v0 -s_wqm_b64 s[30:31], vcc -s_cselect_b32 s15, 1, 0 -s_mov_b32 s20, 0x00800010 -s_mov_b32 s21, 1 -s_wqm_b64 s[22:23], s[20:21] -s_add_u32 s32, s22, s23 -s_mov_b32 exec_lo, 0x80000240 -s_mov_b32 exec_hi, 0x102 -s_wqm_b64 exec, exec -s_bcnt1_i32_b64 s33, exec -s_mov_b64 exec, -1 -v_cmpx_eq_u32_e32 0, v0 -v_mov_b32_e32 v1, s10 -v_mov_b32_e32 v2, 0 -buffer_store_dword v1, v2, s[0:3], 0 offen -v_mov_b32_e32 v1, s11 -v_mov_b32_e32 v2, 4 -buffer_store_dword v1, v2, s[0:3], 0 offen -v_mov_b32_e32 v1, s12 -v_mov_b32_e32 v2, 8 -buffer_store_dword v1, v2, s[0:3], 0 offen -v_mov_b32_e32 v1, s13 -v_mov_b32_e32 v2, 12 -buffer_store_dword v1, v2, s[0:3], 0 offen -v_mov_b32_e32 v1, s14 -v_mov_b32_e32 v2, 16 -buffer_store_dword v1, v2, s[0:3], 0 offen -v_mov_b32_e32 v1, s15 -v_mov_b32_e32 v2, 20 -buffer_store_dword v1, v2, s[0:3], 0 offen -v_mov_b32_e32 v1, s32 -v_mov_b32_e32 v2, 24 -buffer_store_dword v1, v2, s[0:3], 0 offen -v_mov_b32_e32 v1, s33 -v_mov_b32_e32 v2, 28 -buffer_store_dword v1, v2, s[0:3], 0 offen -s_endpgm diff --git a/runtime/test/shaders/cs_wqm_w64_half.asm b/runtime/test/shaders/cs_wqm_w64_half.asm deleted file mode 100644 index e066f1775..000000000 --- a/runtime/test/shaders/cs_wqm_w64_half.asm +++ /dev/null @@ -1,58 +0,0 @@ -; Wave64 s_wqm_b32 on one half of EXEC: it changes only its own 32 lanes and SCC is the any over that half only. -; Bits are lanes. exec_lo = 0x80000240 (lanes 6, 9, 31), exec_hi = 0x00000102 (lanes 33, 40). -; WQM of lo = 0xF0000FF0 (12 lanes, see cs_wqm_w64.asm), WQM of hi = 0x00000F0F (8 lanes). -; Case 1: s_wqm_b32 exec_hi, exec_hi -> exec = lo unchanged (3 lanes) + hi 8 lanes: -; out0 = s_bcnt1_i32_b64 exec = 11, out4 = s_ff1_i32_b64 exec = 6 (lane 6, lo untouched), out5 = s_bcnt1_i32_b32 exec_hi = 8 -; Case 2: exec as at the start, s_wqm_b32 exec_lo, exec_lo -> lo 12 lanes + hi unchanged (2 lanes): -; out1 = s_bcnt1_i32_b64 exec = 14, out6 = s_bcnt1_i32_b32 exec_lo = 12, out7 = s_bcnt1_i32_b32 exec_hi = 2 -; SCC (read right after the instruction), exec_lo = 0 and exec_hi = 0x100 (lane 40 only): -; out2 = SCC after s_wqm_b32 of exec_lo (the low half is empty; a wave-wide any would say 1) = 0 -; out3 = SCC after s_wqm_b32 of exec_hi = 1 -; Assemble (as scripts/run_gpu_tests.py / build.py do): llvm-mc -triple=amdgcn--amdpal -mcpu=gfx1013 -show-encoding (wave64 is inferred by the translator from exec_hi/_b64 EXEC use) -; Run: VKC_SUBGROUP_SIZE=64 vk_compute_test cs_wqm_w64_half.spv 1 dump -; Expect: out[0..7] = 11 14 0 1 6 8 12 2 -s_mov_b32 exec_lo, 0x80000240 -s_mov_b32 exec_hi, 0x102 -s_wqm_b32 exec_hi, exec_hi -s_bcnt1_i32_b64 s8, exec -s_ff1_i32_b64 s13, exec -s_bcnt1_i32_b32 s14, exec_hi -s_mov_b32 exec_lo, 0x80000240 -s_mov_b32 exec_hi, 0x102 -s_wqm_b32 exec_lo, exec_lo -s_bcnt1_i32_b64 s9, exec -s_bcnt1_i32_b32 s15, exec_lo -s_bcnt1_i32_b32 s16, exec_hi -s_mov_b32 exec_lo, 0 -s_mov_b32 exec_hi, 0x100 -s_wqm_b32 s11, exec_lo -s_cselect_b32 s10, 1, 0 -s_wqm_b32 s12, exec_hi -s_cselect_b32 s17, 1, 0 -s_mov_b64 exec, -1 -v_cmpx_eq_u32_e32 0, v0 -v_mov_b32_e32 v1, s8 -v_mov_b32_e32 v2, 0 -buffer_store_dword v1, v2, s[0:3], 0 offen -v_mov_b32_e32 v1, s9 -v_mov_b32_e32 v2, 4 -buffer_store_dword v1, v2, s[0:3], 0 offen -v_mov_b32_e32 v1, s10 -v_mov_b32_e32 v2, 8 -buffer_store_dword v1, v2, s[0:3], 0 offen -v_mov_b32_e32 v1, s17 -v_mov_b32_e32 v2, 12 -buffer_store_dword v1, v2, s[0:3], 0 offen -v_mov_b32_e32 v1, s13 -v_mov_b32_e32 v2, 16 -buffer_store_dword v1, v2, s[0:3], 0 offen -v_mov_b32_e32 v1, s14 -v_mov_b32_e32 v2, 20 -buffer_store_dword v1, v2, s[0:3], 0 offen -v_mov_b32_e32 v1, s15 -v_mov_b32_e32 v2, 24 -buffer_store_dword v1, v2, s[0:3], 0 offen -v_mov_b32_e32 v1, s16 -v_mov_b32_e32 v2, 28 -buffer_store_dword v1, v2, s[0:3], 0 offen -s_endpgm diff --git a/runtime/test/shaders/gs_tri.asm b/runtime/test/shaders/gs_tri.asm deleted file mode 100644 index c0951fdc2..000000000 --- a/runtime/test/shaders/gs_tri.asm +++ /dev/null @@ -1,42 +0,0 @@ -; Legacy (LDS-ring) geometry shader idioms: s_bfm_b64/s_cselect EXEC prologue, input vertex offsets from v0/v1 (SDWA), -; LDS reads of SV_Position (reg 0) and TEXCOORD0 (reg 1), output slots of 2 registers (8 dwords), EMIT x3, CUT, DONE. -; Needs a DXBC with ISG1/OSG1 = {SV_Position reg 0, TEXCOORD0 reg 1}. Run: VKH_GS=gs_tri.spv vk_harness vs_attrs.spv -; fs_loc1.spv out.raw (fs_loc1 = fs_passthru reading location 1) -> every pixel = ((x+0.5)/64, (y+0.5)/64, 0, 0). -s_bfe_i32 s0, s3, 0x80008 -s_bfm_b64 exec, s0, 0 -s_cmp_eq_u32 s0, 64 -s_cselect_b64 exec, -1, exec -v_lshlrev_b32_e32 v3, 2, v0 -v_and_b32_e32 v10, 0x3fffc, v3 -s_mov_b32 s1, 2 -v_lshlrev_b32_sdwa v8, s1, v0 dst_sel:DWORD dst_unused:UNUSED_PAD src0_sel:DWORD src1_sel:WORD_1 -v_lshlrev_b32_e32 v1, 2, v1 -v_and_b32_e32 v6, 0x3fffc, v1 -v_mov_b32_e32 v12, 0 -ds_read2_b32 v[20:21], v10 offset1:1 -ds_read2_b32 v[22:23], v10 offset0:2 offset1:3 -ds_read2_b32 v[24:25], v10 offset0:4 offset1:5 -s_waitcnt lgkmcnt(0) -ds_write2_b32 v12, v20, v21 offset0:0 offset1:1 -ds_write2_b32 v12, v22, v23 offset0:2 offset1:3 -ds_write2_b32 v12, v24, v25 offset0:4 offset1:5 -s_sendmsg sendmsg(MSG_GS, GS_OP_EMIT, 0) -ds_read2_b32 v[20:21], v8 offset1:1 -ds_read2_b32 v[22:23], v8 offset0:2 offset1:3 -ds_read2_b32 v[24:25], v8 offset0:4 offset1:5 -s_waitcnt lgkmcnt(0) -ds_write2_b32 v12, v20, v21 offset0:8 offset1:9 -ds_write2_b32 v12, v22, v23 offset0:10 offset1:11 -ds_write2_b32 v12, v24, v25 offset0:12 offset1:13 -s_sendmsg sendmsg(MSG_GS, GS_OP_EMIT, 0) -ds_read2_b32 v[20:21], v6 offset1:1 -ds_read2_b32 v[22:23], v6 offset0:2 offset1:3 -ds_read2_b32 v[24:25], v6 offset0:4 offset1:5 -s_waitcnt lgkmcnt(0) -ds_write2_b32 v12, v20, v21 offset0:16 offset1:17 -ds_write2_b32 v12, v22, v23 offset0:18 offset1:19 -ds_write2_b32 v12, v24, v25 offset0:20 offset1:21 -s_sendmsg sendmsg(MSG_GS, GS_OP_EMIT, 0) -s_sendmsg sendmsg(MSG_GS, GS_OP_CUT, 0) -s_sendmsg sendmsg(MSG_GS_DONE, GS_OP_NOP) -s_endpgm diff --git a/runtime/test/shaders/gs_w64_a_ring.asm b/runtime/test/shaders/gs_w64_a_ring.asm deleted file mode 100644 index bda97d545..000000000 --- a/runtime/test/shaders/gs_w64_a_ring.asm +++ /dev/null @@ -1,40 +0,0 @@ -; TEST-251 (SHADER-10 tier A, geometry stage): the lane number forms only the GSVS address. A legacy GS writes each -; emitted vertex to its lane's GSVS area; here that area's base is lane id * 96 (v_mbcnt_lo/hi of -1), the shape a -; hardware GS has. The translator maps an LDS write to an output slot from its offset alone and drops the VGPR address -; (rdna2spirv.py, gs_ds), so the lane id reaches no output and the program is partition invariant: after spirv-opt -O -; its SPIR-V is the same as without the base. Drawn with vs_ids (param1 = 0x101 + vertex index): triangle -; p = (TEXCOORD0.x of input vertex 0 - 0x101) / 3. Each invocation stores (p, 3 * p + 1, 77, 0) to its record at heap -; 0x1000 + 16 * p through the V# in s[4:7], and emits one vertex (no primitive) through the lane-based ring address. -; Needs a DXBC with ISG1/OSG1 = {SV_Position reg 0, TEXCOORD0 reg 1} (build.py makes it for gs_*). -; Run: VKH_GS=gs_w64_a_ring.spv VKH_VERTICES=960 VKH_SGPRS=0,0,0,0,0,0,65536,0x30000000 VKH_HEAP=0=0 -; VKH_HEAP_DUMP=heap.raw vk_harness vs_ids.spv out.raw, with and without RADV_PERFTEST=gewave32: -; equal records, and equal to the expected words. -; mattr: +wavefrontsize64,-wavefrontsize32 -s_bfe_i32 s0, s3, 0x80008 -s_bfm_b64 exec, s0, 0 -s_cmp_eq_u32 s0, 64 -s_cselect_b64 exec, -1, exec -v_lshlrev_b32_e32 v3, 2, v0 -v_and_b32_e32 v10, 0x3fffc, v3 -ds_read_b32 v20, v10 offset:16 -s_waitcnt lgkmcnt(0) -v_subrev_nc_u32_e32 v20, 0x101, v20 -v_mul_hi_u32 v21, v20, 0xaaaaaaab -v_lshrrev_b32_e32 v21, 1, v21 -v_mov_b32_e32 v6, v21 -v_lshl_add_u32 v7, v21, 1, v21 -v_add_nc_u32_e32 v7, 1, v7 -v_mov_b32_e32 v8, 0x4d -v_mov_b32_e32 v9, 0 -v_lshlrev_b32_e32 v12, 4, v21 -v_add_nc_u32_e32 v12, 0x1000, v12 -buffer_store_dwordx4 v[6:9], v12, s[4:7], 0 offen -v_mbcnt_lo_u32_b32 v13, -1, 0 -v_mbcnt_hi_u32_b32 v13, -1, v13 -v_mul_u32_u24_e32 v13, 0x60, v13 -v_mov_b32_e32 v14, 0 -ds_write2_b32 v13, v14, v14 offset0:0 offset1:1 -s_sendmsg sendmsg(MSG_GS, GS_OP_EMIT, 0) -s_sendmsg sendmsg(MSG_GS, GS_OP_CUT, 0) -s_sendmsg sendmsg(MSG_GS_DONE, GS_OP_NOP) -s_endpgm diff --git a/runtime/test/shaders/gs_w64_c_lane_id.asm b/runtime/test/shaders/gs_w64_c_lane_id.asm deleted file mode 100644 index 2043c484d..000000000 --- a/runtime/test/shaders/gs_w64_c_lane_id.asm +++ /dev/null @@ -1,36 +0,0 @@ -; TEST-251 (SHADER-10 tier C, geometry stage): the raw lane number (v_mbcnt_lo/hi of -1) used as data, in a legacy -; (LDS-ring) wave64 geometry shader with gs_tri's EXEC prologue. Drawn with vs_ids, whose param1 is the integer -; 0x101 + vertex index: the GS reads it from its first input vertex (signature register 1, TEXCOORD0.x, dword 4), -; so triangle p = (that - 0x101) / 3. Each GS invocation stores (lane id, lane id & 31, p, 0) to its record at heap -; 0x1000 + 16 * p through the V# in s[4:7] (the translator sets s3 for the prologue), then emits one vertex, which -; makes no primitive. In a wave64 GS some invocations get lanes 32..63, in a wave32 one none do, so r0 and r1 depend on -; the wave size and r2 does not. w64_graphics.py uses it as the probe of the GS wave size. -; Needs a DXBC with ISG1/OSG1 = {SV_Position reg 0, TEXCOORD0 reg 1} (build.py makes it for gs_*). -; Run: VKH_GS=gs_w64_c_lane_id.spv VKH_VERTICES=960 VKH_SGPRS=0,0,0,0,0,0,65536,0x30000000 VKH_HEAP=0=0 -; VKH_HEAP_DUMP=heap.raw vk_harness vs_ids.spv out.raw, with and without RADV_PERFTEST=gewave32. -; mattr: +wavefrontsize64,-wavefrontsize32 -s_bfe_i32 s0, s3, 0x80008 -s_bfm_b64 exec, s0, 0 -s_cmp_eq_u32 s0, 64 -s_cselect_b64 exec, -1, exec -v_lshlrev_b32_e32 v3, 2, v0 -v_and_b32_e32 v10, 0x3fffc, v3 -ds_read_b32 v20, v10 offset:16 -s_waitcnt lgkmcnt(0) -v_subrev_nc_u32_e32 v20, 0x101, v20 -v_mul_hi_u32 v21, v20, 0xaaaaaaab -v_lshrrev_b32_e32 v21, 1, v21 -v_mbcnt_lo_u32_b32 v6, -1, 0 -v_mbcnt_hi_u32_b32 v6, -1, v6 -v_and_b32_e32 v7, 31, v6 -v_mov_b32_e32 v8, v21 -v_mov_b32_e32 v9, 0 -v_lshlrev_b32_e32 v12, 4, v21 -v_add_nc_u32_e32 v12, 0x1000, v12 -buffer_store_dwordx4 v[6:9], v12, s[4:7], 0 offen -v_mov_b32_e32 v13, 0 -ds_write2_b32 v13, v13, v13 offset0:0 offset1:1 -s_sendmsg sendmsg(MSG_GS, GS_OP_EMIT, 0) -s_sendmsg sendmsg(MSG_GS, GS_OP_CUT, 0) -s_sendmsg sendmsg(MSG_GS_DONE, GS_OP_NOP) -s_endpgm diff --git a/runtime/test/shaders/ms_clip.asm b/runtime/test/shaders/ms_clip.asm deleted file mode 100644 index 09162b2a0..000000000 --- a/runtime/test/shaders/ms_clip.asm +++ /dev/null @@ -1,27 +0,0 @@ -; Mesh shader (NGG, wave64, 128 threads): fullscreen triangle like ms_tri, plus SV_ClipDistance[0] = NDC x -; exported in pos1.x (`exp pos1 v1, off, off, off done`). Clips the left half of the 64x64 viewport (x < 0): -; expected covered pixels = 2048/4096 (right half x in [32..63], left half untouched clear color -1). -; Needs a DXBC with PSV0 (128 threads, 64/64 outputs, triangles) and OSG1 declaring SV_ClipDistance (mask 0x1). -v_mbcnt_lo_u32_b32 v0, -1, 0 -v_mbcnt_hi_u32_b32 v0, -1, v0 -s_bfe_u32 s4, s3, 0x40018 -v_lshl_add_u32 v0, s4, 6, v0 -v_cmp_eq_u32_e32 vcc_lo, 1, v0 -v_cndmask_b32_e64 v1, -1.0, 0x40400000, vcc_lo -v_cndmask_b32_e64 v3, 0, 2.0, vcc_lo -v_cmp_eq_u32_e32 vcc_lo, 2, v0 -v_cndmask_b32_e64 v2, -1.0, 0x40400000, vcc_lo -v_cndmask_b32_e64 v4, 0, 2.0, vcc_lo -v_mov_b32_e32 v6, 0 -v_mov_b32_e32 v7, 1.0 -v_mov_b32_e32 v8, 0.5 -s_mov_b32 m0, 0x1003 -s_sendmsg sendmsg(MSG_GS_ALLOC_REQ) -v_cmpx_gt_u32_e32 3, v0 -exp pos0 v1, v2, v6, v7 -exp pos1 v1, off, off, off done -exp param0 v3, v4, v8, v7 -v_cmpx_eq_u32_e32 0, v0 -v_mov_b32_e32 v9, 0x200400 -exp prim v9, off, off, off done -s_endpgm diff --git a/runtime/test/shaders/ms_f16_pack.asm b/runtime/test/shaders/ms_f16_pack.asm deleted file mode 100644 index 4832c9a18..000000000 --- a/runtime/test/shaders/ms_f16_pack.asm +++ /dev/null @@ -1,29 +0,0 @@ -; Mesh-shader producer for ps_interp_f16_high: ms_tri's triangle (NGG, wave64, 128 threads, threads 0-2 export -; the vertices, thread 0 the primitive) with vs_f16_pack's params, two f16 packed per 32-bit channel: -; param0.x = f16(u) | f16(v) << 16, param0.y = f16(v) | f16(u) << 16, param1 = (u, v, 0.5, 1) as f32. -; Run: VKH_MESH=1 vk_harness ms_f16_pack.spv ps_interp_f16_high.spv out.raw; checked as ps_interp_f16_high is. -v_mbcnt_lo_u32_b32 v0, -1, 0 -v_mbcnt_hi_u32_b32 v0, -1, v0 -s_bfe_u32 s4, s3, 0x40018 -v_lshl_add_u32 v0, s4, 6, v0 -v_cmp_eq_u32_e32 vcc_lo, 1, v0 -v_cndmask_b32_e64 v1, -1.0, 0x40400000, vcc_lo -v_cndmask_b32_e64 v3, 0, 2.0, vcc_lo -v_cmp_eq_u32_e32 vcc_lo, 2, v0 -v_cndmask_b32_e64 v2, -1.0, 0x40400000, vcc_lo -v_cndmask_b32_e64 v4, 0, 2.0, vcc_lo -v_mov_b32_e32 v6, 0 -v_mov_b32_e32 v7, 1.0 -v_mov_b32_e32 v8, 0.5 -v_cvt_pkrtz_f16_f32_e32 v10, v3, v4 -v_cvt_pkrtz_f16_f32_e32 v11, v4, v3 -s_mov_b32 m0, 0x1003 -s_sendmsg sendmsg(MSG_GS_ALLOC_REQ) -v_cmpx_gt_u32_e32 3, v0 -exp pos0 v1, v2, v6, v7 done -exp param0 v10, v11, v8, v7 -exp param1 v3, v4, v8, v7 -v_cmpx_eq_u32_e32 0, v0 -v_mov_b32_e32 v9, 0x200400 -exp prim v9, off, off, off done -s_endpgm diff --git a/runtime/test/shaders/ms_tri.asm b/runtime/test/shaders/ms_tri.asm deleted file mode 100644 index f95eecf32..000000000 --- a/runtime/test/shaders/ms_tri.asm +++ /dev/null @@ -1,28 +0,0 @@ -; Mesh shader (NGG, wave64, 128 threads): thread id = s3[27:24]*64 + mbcnt; GS_ALLOC_REQ m0 = 1 prim << 12 | 3 verts; -; threads 0-2 export the vk_harness triangle and attr0, thread 0 exports prim (0,1,2). Needs a DXBC with PSV0 -; (128 threads, 64/64 outputs, triangles). Run: VKH_MESH=1 vk_harness ms_tri.spv fs_passthru.spv out.raw -> -; every pixel = ((x+0.5)/64, (y+0.5)/64, 0.5, 1). -; Both waves send the same allocation. Its counts must survive the barrier before the exports. -v_mbcnt_lo_u32_b32 v0, -1, 0 -v_mbcnt_hi_u32_b32 v0, -1, v0 -s_bfe_u32 s4, s3, 0x40018 -v_lshl_add_u32 v0, s4, 6, v0 -v_cmp_eq_u32_e32 vcc_lo, 1, v0 -v_cndmask_b32_e64 v1, -1.0, 0x40400000, vcc_lo -v_cndmask_b32_e64 v3, 0, 2.0, vcc_lo -v_cmp_eq_u32_e32 vcc_lo, 2, v0 -v_cndmask_b32_e64 v2, -1.0, 0x40400000, vcc_lo -v_cndmask_b32_e64 v4, 0, 2.0, vcc_lo -v_mov_b32_e32 v6, 0 -v_mov_b32_e32 v7, 1.0 -v_mov_b32_e32 v8, 0.5 -s_mov_b32 m0, 0x1003 -s_sendmsg sendmsg(MSG_GS_ALLOC_REQ) -s_barrier -v_cmpx_gt_u32_e32 3, v0 -exp pos0 v1, v2, v6, v7 done -exp param0 v3, v4, v8, v7 -v_cmpx_eq_u32_e32 0, v0 -v_mov_b32_e32 v9, 0x200400 -exp prim v9, off, off, off done -s_endpgm diff --git a/runtime/test/shaders/ms_v5_workgroup.asm b/runtime/test/shaders/ms_v5_workgroup.asm deleted file mode 100644 index 0c30140dc..000000000 --- a/runtime/test/shaders/ms_v5_workgroup.asm +++ /dev/null @@ -1,33 +0,0 @@ -; One full-screen triangle per mesh workgroup. RGB records incoming v5 from local lanes 0, 1 and 31. -; With --mesh-group-readback 2 3 4, pixel g = x + 2*y + 6*z must be (32g, 32g+1, 32g+31, 1): v5 = group index * -; NumThreads + lane (#209; the game's mesh entry shifts v5 right by 7 on lane 0 with 128 threads). -; Stencil selects the workgroup independently of its color. PSV0: 32 threads, 128 bytes LDS, 3 vertices, 1 triangle. -v_mbcnt_lo_u32_b32 v0, -1, 0 -; Exchange through group memory so the probe also works when a host subgroup has fewer than 32 lanes. -v_lshlrev_b32_e32 v11, 2, v0 -ds_write_b32 v11, v5 -s_waitcnt lgkmcnt(0) -s_barrier -v_mov_b32_e32 v11, 0 -ds_read_b32 v8, v11 -ds_read_b32 v9, v11 offset:4 -ds_read_b32 v10, v11 offset:124 -s_waitcnt lgkmcnt(0) -v_cvt_f32_u32_e32 v8, v8 -v_cvt_f32_u32_e32 v9, v9 -v_cvt_f32_u32_e32 v10, v10 -v_cmp_eq_u32_e32 vcc_lo, 1, v0 -v_cndmask_b32_e64 v1, -1.0, 0x40400000, vcc_lo -v_cmp_eq_u32_e32 vcc_lo, 2, v0 -v_cndmask_b32_e64 v2, -1.0, 0x40400000, vcc_lo -v_mov_b32_e32 v6, 0 -v_mov_b32_e32 v7, 1.0 -s_mov_b32 m0, 0x1003 -s_sendmsg sendmsg(MSG_GS_ALLOC_REQ) -v_cmpx_gt_u32_e32 3, v0 -exp pos0 v1, v2, v6, v7 done -exp param0 v8, v9, v10, v7 -v_cmpx_eq_u32_e32 0, v0 -v_mov_b32_e32 v9, 0x200400 -exp prim v9, off, off, off done -s_endpgm diff --git a/runtime/test/shaders/ms_w64x_ballot.asm b/runtime/test/shaders/ms_w64x_ballot.asm deleted file mode 100644 index c6de13562..000000000 --- a/runtime/test/shaders/ms_w64x_ballot.asm +++ /dev/null @@ -1,46 +0,0 @@ -; Mesh shader (NGG, wave64, 128 threads): ms_tri's triangle, but the blue channel of param0 is 0.5 only when a -; ballot + v_mbcnt compaction over BOTH halves of the wave is exact, 0 otherwise. Selected lanes: (lane & 7) == 5 -; (lanes 5, 13, 21, 29 | 37, 45, 53, 61). s10 = s_bcnt1 of the ballot = 8 (one half would see 4). Each lane's -; compaction slot = v_mbcnt_lo(s6) + v_mbcnt_hi(s7) must equal lane >> 3 (upper lanes count the 4 low-half -; lanes); s11 = bcnt of the selected lanes whose slot is right = 8. s10 + s11 == 16 -> blue = 0.5, else 0. -; Run like ms_tri (needs a DXBC with PSV0, 128 threads, 64/64 outputs, triangles; see scripts/run_gpu_tests.py): -; VKH_MESH=1 vk_harness ms_w64x_ballot.spv fs_passthru.spv out.raw -; -> every pixel = ((x+0.5)/64, (y+0.5)/64, 0.5, 1), identical to ms_tri. -; mattr: +wavefrontsize64,-wavefrontsize32 -v_mbcnt_lo_u32_b32 v0, -1, 0 -v_mbcnt_hi_u32_b32 v0, -1, v0 -v_mov_b32_e32 v11, v0 -s_bfe_u32 s4, s3, 0x40018 -v_lshl_add_u32 v0, s4, 6, v0 -v_and_b32_e32 v12, 7, v11 -v_cmp_eq_u32_e64 s[6:7], 5, v12 -s_bcnt1_i32_b64 s10, s[6:7] -v_mbcnt_lo_u32_b32 v13, s6, 0 -v_mbcnt_hi_u32_b32 v13, s7, v13 -v_lshrrev_b32_e32 v14, 3, v11 -v_cmp_eq_u32_e64 s[8:9], v14, v13 -s_and_b64 s[8:9], s[8:9], s[6:7] -s_bcnt1_i32_b64 s11, s[8:9] -s_add_u32 s12, s10, s11 -s_cmp_eq_u32 s12, 16 -s_cselect_b32 s13, 1, 0 -v_cvt_f32_u32_e32 v15, s13 -v_mul_f32_e32 v15, 0.5, v15 -v_cmp_eq_u32_e32 vcc, 1, v0 -v_cndmask_b32_e64 v1, -1.0, 0x40400000, vcc -v_cndmask_b32_e64 v3, 0, 2.0, vcc -v_cmp_eq_u32_e32 vcc, 2, v0 -v_cndmask_b32_e64 v2, -1.0, 0x40400000, vcc -v_cndmask_b32_e64 v4, 0, 2.0, vcc -v_mov_b32_e32 v6, 0 -v_mov_b32_e32 v7, 1.0 -v_mov_b32_e32 v8, v15 -s_mov_b32 m0, 0x1003 -s_sendmsg sendmsg(MSG_GS_ALLOC_REQ) -v_cmpx_gt_u32_e32 3, v0 -exp pos0 v1, v2, v6, v7 done -exp param0 v3, v4, v8, v7 -v_cmpx_eq_u32_e32 0, v0 -v_mov_b32_e32 v9, 0x200400 -exp prim v9, off, off, off done -s_endpgm diff --git a/runtime/test/shaders/ms_wave_info_s3.asm b/runtime/test/shaders/ms_wave_info_s3.asm deleted file mode 100644 index 36746c602..000000000 --- a/runtime/test/shaders/ms_wave_info_s3.asm +++ /dev/null @@ -1,56 +0,0 @@ -; Mesh shader (NGG, wave64, 128 threads = 2 waves): verifies s3[27:24] == local_index / 64 across all 128 lanes. -; Every lane extracts wave_id = s_bfe_u32(s3, 0x40018) and atomically increments LDS[min(wave_id, 2)]: -; LDS[0] = count of lanes seeing wave_id == 0 (must be 64) -; LDS[1] = count of lanes seeing wave_id == 1 (must be 64) -; LDS[2] = count of lanes seeing wave_id >= 2 (must be 0) -; Only wave 1 sends the mesh allocation. Both waves meet at the barrier before wave 0 exports the triangle. -; Threads 0..2 export ms_tri's fullscreen triangle with param0.b = 0.5 iff LDS[0]==64 && LDS[1]==64 && LDS[2]==0, -; else 0.0. Needs DXBC with PSV0 (128x1x1 threads, 64/64 outputs, triangles; see scripts/run_gpu_tests.py): -; VKH_MESH=1 vk_harness ms_wave_info_s3.spv fs_passthru.spv out.raw -; -> every pixel = ((x+0.5)/64, (y+0.5)/64, 0.5, 1.0). -; mattr: +wavefrontsize64,-wavefrontsize32 -v_mbcnt_lo_u32_b32 v0, -1, 0 -v_mbcnt_hi_u32_b32 v0, -1, v0 -s_bfe_u32 s4, s3, 0x40018 -v_lshl_add_u32 v0, s4, 6, v0 -v_mov_b32_e32 v10, 0 -v_cmpx_eq_u32_e32 0, v0 -ds_write_b32 v10, v10 offset:0 -ds_write_b32 v10, v10 offset:4 -ds_write_b32 v10, v10 offset:8 -s_mov_b64 exec, -1 -s_barrier -s_min_u32 s5, s4, 2 -s_lshl_b32 s5, s5, 2 -v_mov_b32_e32 v11, s5 -v_mov_b32_e32 v12, 1 -ds_add_u32 v11, v12 -s_barrier -ds_read_b32 v13, v10 offset:0 -ds_read_b32 v14, v10 offset:4 -ds_read_b32 v15, v10 offset:8 -v_xor_b32_e32 v13, 64, v13 -v_xor_b32_e32 v14, 64, v14 -v_or3_b32 v13, v13, v14, v15 -v_cmp_eq_u32_e32 vcc, 0, v13 -v_cndmask_b32_e64 v8, 0, 0.5, vcc -v_cmp_eq_u32_e32 vcc, 1, v0 -v_cndmask_b32_e64 v1, -1.0, 0x40400000, vcc -v_cndmask_b32_e64 v3, 0, 2.0, vcc -v_cmp_eq_u32_e32 vcc, 2, v0 -v_cndmask_b32_e64 v2, -1.0, 0x40400000, vcc -v_cndmask_b32_e64 v4, 0, 2.0, vcc -v_mov_b32_e32 v6, 0 -v_mov_b32_e32 v7, 1.0 -s_mov_b32 m0, 0x1003 -s_cmp_eq_u32 s4, 0 -s_cbranch_scc1 1 -s_sendmsg sendmsg(MSG_GS_ALLOC_REQ) -s_barrier -v_cmpx_gt_u32_e32 3, v0 -exp pos0 v1, v2, v6, v7 done -exp param0 v3, v4, v8, v7 -v_cmpx_eq_u32_e32 0, v0 -v_mov_b32_e32 v9, 0x200400 -exp prim v9, off, off, off done -s_endpgm diff --git a/runtime/test/shaders/mullit_readback.py b/runtime/test/shaders/mullit_readback.py deleted file mode 100644 index 007b516b1..000000000 --- a/runtime/test/shaders/mullit_readback.py +++ /dev/null @@ -1,122 +0,0 @@ -"""Check the ps_mullit semantic fixture with runtime SGPR inputs and RGBA32F readback. - -python -I runtime/test/shaders/build.py vs_ids ps_mullit -python -I runtime/test/shaders/mullit_readback.py -""" -import argparse -import itertools -import os -from pathlib import Path -import random -import struct -import sys -import tempfile - -sys.path.insert(0, str(Path(__file__).resolve().parent)) -from check import EXE, run - -SIGN = 0x80000000 -INF = 0x7f800000 -MIN_NORMAL = 0x00800000 -ONE = 0x3f800000 -LIGHT_OFF = 0xff7fffff -PAYLOAD_MASK = 0x40000000 - - -def lighting_product(x, y, gate): - """Return the expected f32 word using integer significands throughout.""" - ax, ay = x & ~SIGN, y & ~SIGN - if not MIN_NORMAL <= gate <= INF or y in (LIGHT_OFF, SIGN | INF) or ay > INF: - return LIGHT_OFF - if min(ax, ay) < MIN_NORMAL: - return 0 - if ax > INF: - return x - sign = (x ^ y) & SIGN - if INF in (ax, ay): - return sign | INF - - product = (MIN_NORMAL + ax % MIN_NORMAL) * (MIN_NORMAL + ay % MIN_NORMAL) - shift = product.bit_length() - 24 - unit = 1 << shift - mantissa, remainder = divmod(product, unit) - if 2 * remainder > unit or (2 * remainder == unit and mantissa % 2): - mantissa += 1 - exponent = (ax >> 23) + (ay >> 23) - 127 + shift - 23 - if mantissa == 2 * MIN_NORMAL: - mantissa //= 2 - exponent += 1 - # Round before flushing. A product just below MIN_NORMAL can carry into it. - if exponent <= 0: - return sign - if exponent >= 255: - return sign | INF - return sign | (exponent << 23) | (mantissa - MIN_NORMAL) - - -def operand_triples(): - gates = (ONE, INF, MIN_NORMAL, 1, MIN_NORMAL - 1, 0, SIGN, SIGN | ONE, 0x7fc23456, 0xffa54321) - yield from ((0x40400000, 0xc0200000, gate) for gate in gates) - yield from itertools.product( - (0, SIGN, 1, SIGN | (MIN_NORMAL - 1), 0x7fa12345, 0xffc12345, INF), - (0, SIGN | 1, LIGHT_OFF, INF, SIGN | INF, 0x7fc09876, ONE), (ONE,)) - yield from itertools.product( - (ONE - 4, ONE - 3, ONE - 2, ONE - 1, ONE, SIGN | ONE, 0xbf7ffffe, 0xbf7fffff), - (MIN_NORMAL, MIN_NORMAL + 1, MIN_NORMAL + 2), (ONE,)) - for x, y in ((INF - 1, 0x40000000), (LIGHT_OFF, 0x40000000), (INF - 1, MIN_NORMAL), - (MIN_NORMAL, 0x3f000000), (SIGN | MIN_NORMAL, 0x3f000000), - (INF, SIGN | ONE), (ONE, LIGHT_OFF - 1)): - yield x, y, ONE - # Halfway products round up to 0x3fc00002 and down to 0x3fc00004. - yield 0x3fc00000, ONE + 1, ONE - yield 0x3fc00000, ONE + 3, ONE - rng = random.Random(578) - for _ in range(28): - x = rng.randrange(MIN_NORMAL, INF) | rng.choice((0, SIGN)) - y = rng.randrange(MIN_NORMAL, INF) | rng.choice((0, SIGN)) - yield x, y, ONE - - -def mismatch(data, x, y, gate): - result = lighting_product(x, y, gate) - modified = lighting_product(x ^ SIGN, y & ~SIGN, gate) - expected = (result, modified, LIGHT_OFF, result ^ PAYLOAD_MASK) - if len(data) != 4 * 4 * 16: - return f"expected 256 bytes, got {len(data)}" - for i, pixel in enumerate(struct.iter_unpack("<4I", data)): - for channel, want, got in zip("RGBA", expected, pixel): - # A float attachment can change a NaN payload. Alpha exposes the raw - # R payload as a finite word in exactly those cases. - if want & ~SIGN > INF and got & ~SIGN > INF: - continue - if got != want: - return f"pixel {i} {channel}: got {got:#010x}, expected {want:#010x}" - return None - - -def main(): - parser = argparse.ArgumentParser(description=__doc__) - parser.add_argument("work", type=Path) - parser.add_argument("build", type=Path) - args = parser.parse_args() - spirv = args.work / "spirv" - cases = dict.fromkeys(operand_triples()) - with tempfile.TemporaryDirectory() as tmp: - raw = Path(tmp) / "pixels.raw" - for inputs in cases: - raw.unlink(missing_ok=True) - words = ",".join(map(hex, inputs)) - code, output = run(args.build / ("vk_harness" + EXE), spirv / "vs_ids.spv", - spirv / "ps_mullit.spv", raw, "4", "4", env=dict(os.environ, VKH_SGPRS=words)) - if code: - print(f"{words}: vk_harness exited {code}\n{output}", file=sys.stderr) - return code - problem = mismatch(raw.read_bytes(), *inputs) if raw.is_file() else "missing readback" - if problem: - sys.exit(f"{words}: {problem}") - print(f"{len(cases)} operand triples, {16 * len(cases)} pixels matched") - return 0 - - -if __name__ == "__main__": - sys.exit(main()) diff --git a/runtime/test/shaders/probe_signed_zero.py b/runtime/test/shaders/probe_signed_zero.py deleted file mode 100644 index 132476111..000000000 --- a/runtime/test/shaders/probe_signed_zero.py +++ /dev/null @@ -1,71 +0,0 @@ -"""Run the SHADER-605 direct OpImageWrite probe with the supplied vk_store_test binary.""" - -import argparse -from pathlib import Path -import subprocess -import tempfile - - -# Hand-written compute shader. Only the image format changes between runs. -MODULE = """OpCapability Shader -OpCapability StorageImageWriteWithoutFormat -OpCapability SignedZeroInfNanPreserve -OpMemoryModel Logical GLSL450 -OpEntryPoint GLCompute %main "main" %image -OpExecutionMode %main LocalSize 1 1 1 -OpExecutionMode %main SignedZeroInfNanPreserve 32 -OpDecorate %image DescriptorSet 0 -OpDecorate %image Binding 8 -%void = OpTypeVoid -%fn = OpTypeFunction %void -%i = OpTypeInt 32 1 -%f = OpTypeFloat 32 -%xy = OpTypeVector %i 2 -%rgba = OpTypeVector %f 4 -%img = OpTypeImage %f 2D 0 0 0 2 {image_format} -%ptr = OpTypePointer UniformConstant %img -%image = OpVariable %ptr UniformConstant -%zero = OpConstant %i 0 -%one = OpConstant %i 1 -%two = OpConstant %i 2 -%a = OpConstantComposite %xy %zero %zero -%b = OpConstantComposite %xy %one %zero -%c = OpConstantComposite %xy %two %zero -%n = OpConstant %f -0.0 -%p = OpConstant %f 0.0 -%f1 = OpConstant %f 1.0 -%va = OpConstantComposite %rgba %n %p %p %p -%vb = OpConstantComposite %rgba %n %f1 %p %p -%vc = OpConstantComposite %rgba %n %n %p %p -%main = OpFunction %void None %fn -%entry = OpLabel -%handle = OpLoad %img %image -OpImageWrite %handle %a %va -OpImageWrite %handle %b %vb -OpImageWrite %handle %c %vc -OpReturn -OpFunctionEnd -""" - - -def main(): - parser = argparse.ArgumentParser(description=__doc__) - parser.add_argument("harness", type=Path) - args = parser.parse_args() - results = [] - with tempfile.TemporaryDirectory() as scratch: - for image_format in ("Unknown", "Rgba32f"): - print(image_format, flush=True) - source = Path(scratch) / f"{image_format}.spvasm" - binary = source.with_suffix(".spv") - source.write_text(MODULE.format(image_format=image_format), encoding="utf-8", newline="\n") - subprocess.run(["spirv-as", "--target-env", "vulkan1.2", source, "-o", binary], check=True) - subprocess.run(["spirv-val", "--target-env", "vulkan1.2", binary], check=True) - results.append(subprocess.run([args.harness.resolve(), binary, "signed-zero"]).returncode) - if any(code not in (0, 77) for code in results): - return 1 - return 77 if 77 in results else 0 - - -if __name__ == "__main__": - raise SystemExit(main()) diff --git a/runtime/test/shaders/ps_array_resinfo.asm b/runtime/test/shaders/ps_array_resinfo.asm deleted file mode 100644 index 681f87734..000000000 --- a/runtime/test/shaders/ps_array_resinfo.asm +++ /dev/null @@ -1,13 +0,0 @@ -; vk_texture_test exposes an 8x8 array view of two cubes (12 layers) with one mip. -; The 2D image at the same descriptor index has one layer, so selecting it changes B. -s_load_dwordx8 s[8:15], s[0:1], 0 -s_waitcnt lgkmcnt(0) -v_mov_b32_e32 v0, 0 -image_get_resinfo v[4:7], v0, s[8:15] dmask:0xf dim:SQ_RSRC_IMG_2D_ARRAY -s_waitcnt vmcnt(0) -v_cvt_f32_u32_e32 v4, v4 -v_cvt_f32_u32_e32 v5, v5 -v_cvt_f32_u32_e32 v6, v6 -v_cvt_f32_u32_e32 v7, v7 -exp mrt0 v4, v5, v6, v7 done vm -s_endpgm diff --git a/runtime/test/shaders/ps_bary.asm b/runtime/test/shaders/ps_bary.asm deleted file mode 100644 index 0a7f20ac1..000000000 --- a/runtime/test/shaders/ps_bary.asm +++ /dev/null @@ -1,11 +0,0 @@ -; regen_fixtures: this source has a translator fixture in tests/semantic/fixtures/disasm -; Raw barycentric reads (v0 = i, v1 = j) next to v_interp. With vk_harness geometry, raw i/j must equal -; the interpolated attr0.xy / 2 on every pixel (attr0 = (0,0), (2,0), (0,2) at the three vertices). -v_interp_p1_f32_e32 v2, v0, attr0.x -v_interp_p2_f32_e32 v2, v1, attr0.x -v_interp_p1_f32_e32 v3, v0, attr0.y -v_interp_p2_f32_e32 v3, v1, attr0.y -v_mov_b32 v4, v0 -v_mov_b32 v5, v1 -exp mrt0 v2, v3, v4, v5 done vm -s_endpgm diff --git a/runtime/test/shaders/ps_bitmask_perm.asm b/runtime/test/shaders/ps_bitmask_perm.asm deleted file mode 100644 index f1d62a1cd..000000000 --- a/runtime/test/shaders/ps_bitmask_perm.asm +++ /dev/null @@ -1,7 +0,0 @@ -; ds_swizzle BITMASK_PERM: v1 must equal lane ^ 9 ("pippi"), v2 must equal ((lane & 5) | 16) ^ 1 ("10p0i") on every pixel. -v_mbcnt_lo_u32_b32 v0, -1, 0 -ds_swizzle_b32 v1, v0 offset:swizzle(BITMASK_PERM,"pippi") -ds_swizzle_b32 v2, v0 offset:swizzle(BITMASK_PERM,"10p0i") -v_mov_b32_e32 v3, 0 -exp mrt0 v0, v1, v2, v3 done vm -s_endpgm diff --git a/runtime/test/shaders/ps_cbv_modulate.asm b/runtime/test/shaders/ps_cbv_modulate.asm deleted file mode 100644 index 4dbb66256..000000000 --- a/runtime/test/shaders/ps_cbv_modulate.asm +++ /dev/null @@ -1,18 +0,0 @@ -; vs_ids supplies (u,v) at pixel centers across the full-screen triangle. -; s0:s1 points to a table of two buffer descriptors. Read the multiplier -; at byte 16 of the buffer selected by descriptor 1. Descriptor 0 is a decoy. -; With gain 0.5 expect (u/2, v/2, 0.5, 1); with gain 0 expect (0, 0, 0, 1). -s_load_dwordx4 s[8:11], s[0:1], 0x10 -s_waitcnt lgkmcnt(0) -s_buffer_load_dword s12, s[8:11], 0x10 -s_waitcnt lgkmcnt(0) -v_interp_p1_f32_e32 v2, v0, attr0.x -v_interp_p2_f32_e32 v2, v1, attr0.x -v_interp_p1_f32_e32 v3, v0, attr0.y -v_interp_p2_f32_e32 v3, v1, attr0.y -v_mov_b32_e32 v4, s12 -v_mul_legacy_f32 v2, v2, v4 -v_mul_legacy_f32 v3, v3, v4 -v_mov_b32_e32 v5, 1.0 -exp mrt0 v2, v3, v4, v5 done vm -s_endpgm diff --git a/runtime/test/shaders/ps_clip_color.asm b/runtime/test/shaders/ps_clip_color.asm deleted file mode 100644 index 7c354cbce..000000000 --- a/runtime/test/shaders/ps_clip_color.asm +++ /dev/null @@ -1,12 +0,0 @@ -; Dedicated fragment shader for vertex clipping tests. -; Export finite, exactly representable RGBA32F values so -; NaN payload canonicalization cannot affect clip validation. -; Expected mrt0 bits: 0x3e800000, 0x3f000000, -; 0x3f400000, 0x3f800000 - -v_mov_b32 v0, 0x3e800000 -v_mov_b32 v1, 0x3f000000 -v_mov_b32 v2, 0x3f400000 -v_mov_b32 v3, 0x3f800000 -exp mrt0 v0, v1, v2, v3 done vm -s_endpgm diff --git a/runtime/test/shaders/ps_cmp_nlg.asm b/runtime/test/shaders/ps_cmp_nlg.asm deleted file mode 100644 index ac1cd96e3..000000000 --- a/runtime/test/shaders/ps_cmp_nlg.asm +++ /dev/null @@ -1,85 +0,0 @@ -; regen_fixtures: this source has a translator fixture in tests/semantic/fixtures/disasm -; v_cmp_nlg / v_cmpx_nlg (docs/design.md "Constant and ordered VOPC"): nlg ("not less or greater") is true when -; x == y or either source is NaN (unordered equal). Each case ORs its bit into a mask; channels are mask | 0x40000000. -; x, f32 cases: bit0 1.0 vs 1.0 (1), bit1 +0 vs -0 (1), bit2 quiet NaN vs 1.0 (1), bit3 1.0 vs 2.5 (0), -; bit4 signalling NaN 0x7f800001 vs 1.0 (1), bit5 +inf vs +inf (1), bit6 -inf vs +inf (0): mask 0x37 -; y, f16 cases (high halves 0xABCD / 0x1234 must be ignored): bit0 1.0h vs 1.0h (1), bit1 +0h vs -0h (1), -; bit2 NaN 0x7e00 vs 1.0h (1), bit3 1.0h vs 2.5h (0): mask 0x7 -; z, the e64 form with source modifiers: bit0 nlg(-|-1.0|, -1.0) (1), bit1 nlg(|x|, 2.5) with x = -1.0 (0): mask 0x1 -; w: v_cmpx_nlg_f32 and _f16 on equal, +-0 and NaN operands keep every lane, so the pixel is still written: 1.0 -; Expected mrt0 bits: 0x40000037, 0x40000007, 0x40000001, 0x3f800000 -v_mov_b32_e32 v10, 0 -v_mov_b32_e32 v0, 1.0 -v_cmp_nlg_f32_e32 vcc_lo, 1.0, v0 -v_cndmask_b32_e64 v1, 0, 1, vcc_lo -v_or_b32_e32 v10, v10, v1 -v_mov_b32_e32 v0, 0x80000000 -v_cmp_nlg_f32_e32 vcc_lo, 0, v0 -v_cndmask_b32_e64 v1, 0, 2, vcc_lo -v_or_b32_e32 v10, v10, v1 -v_mov_b32_e32 v0, 0x7fc00000 -v_cmp_nlg_f32_e32 vcc_lo, 1.0, v0 -v_cndmask_b32_e64 v1, 0, 4, vcc_lo -v_or_b32_e32 v10, v10, v1 -v_mov_b32_e32 v0, 0x40200000 -v_cmp_nlg_f32_e32 vcc_lo, 1.0, v0 -v_cndmask_b32_e64 v1, 0, 8, vcc_lo -v_or_b32_e32 v10, v10, v1 -v_mov_b32_e32 v0, 0x7f800001 -v_cmp_nlg_f32_e32 vcc_lo, 1.0, v0 -v_cndmask_b32_e64 v1, 0, 16, vcc_lo -v_or_b32_e32 v10, v10, v1 -v_mov_b32_e32 v0, 0x7f800000 -v_mov_b32_e32 v2, 0x7f800000 -v_cmp_nlg_f32_e32 vcc_lo, v2, v0 -v_cndmask_b32_e64 v1, 0, 32, vcc_lo -v_or_b32_e32 v10, v10, v1 -v_mov_b32_e32 v2, 0xff800000 -v_cmp_nlg_f32_e32 vcc_lo, v2, v0 -v_cndmask_b32_e64 v1, 0, 64, vcc_lo -v_or_b32_e32 v10, v10, v1 -v_or_b32_e32 v10, 0x40000000, v10 -v_mov_b32_e32 v11, 0 -v_mov_b32_e32 v0, 0xabcd3c00 -v_mov_b32_e32 v2, 0x12343c00 -v_cmp_nlg_f16_e32 vcc_lo, v0, v2 -v_cndmask_b32_e64 v1, 0, 1, vcc_lo -v_or_b32_e32 v11, v11, v1 -v_mov_b32_e32 v0, 0xabcd0000 -v_mov_b32_e32 v2, 0x12348000 -v_cmp_nlg_f16_e32 vcc_lo, v0, v2 -v_cndmask_b32_e64 v1, 0, 2, vcc_lo -v_or_b32_e32 v11, v11, v1 -v_mov_b32_e32 v0, 0xabcd7e00 -v_mov_b32_e32 v2, 0x12343c00 -v_cmp_nlg_f16_e32 vcc_lo, v0, v2 -v_cndmask_b32_e64 v1, 0, 4, vcc_lo -v_or_b32_e32 v11, v11, v1 -v_mov_b32_e32 v0, 0xabcd3c00 -v_mov_b32_e32 v2, 0x12344100 -v_cmp_nlg_f16_e32 vcc_lo, v0, v2 -v_cndmask_b32_e64 v1, 0, 8, vcc_lo -v_or_b32_e32 v11, v11, v1 -v_or_b32_e32 v11, 0x40000000, v11 -v_mov_b32_e32 v12, 0 -v_mov_b32_e32 v0, -1.0 -v_cmp_nlg_f32_e64 s1, -|v0|, v0 -v_cndmask_b32_e64 v1, 0, 1, s1 -v_or_b32_e32 v12, v12, v1 -v_mov_b32_e32 v2, 0x40200000 -v_cmp_nlg_f32_e64 s1, |v0|, v2 -v_cndmask_b32_e64 v1, 0, 2, s1 -v_or_b32_e32 v12, v12, v1 -v_or_b32_e32 v12, 0x40000000, v12 -v_mov_b32_e32 v0, 1.0 -v_cmpx_nlg_f32_e32 1.0, v0 -v_mov_b32_e32 v0, 0x80000000 -v_cmpx_nlg_f32_e32 0, v0 -v_mov_b32_e32 v0, 0x7fc00000 -v_cmpx_nlg_f32_e32 1.0, v0 -v_mov_b32_e32 v0, 0x7e00 -v_mov_b32_e32 v2, 0x3c00 -v_cmpx_nlg_f16_e32 v0, v2 -v_mov_b32_e32 v13, 1.0 -exp mrt0 v10, v11, v12, v13 done vm -s_endpgm diff --git a/runtime/test/shaders/ps_cndmask_sign_mods.asm b/runtime/test/shaders/ps_cndmask_sign_mods.asm deleted file mode 100644 index fa5ff6972..000000000 --- a/runtime/test/shaders/ps_cndmask_sign_mods.asm +++ /dev/null @@ -1,18 +0,0 @@ -; v_cndmask_b32_e64 source modifiers are sign-bit moves (docs/design.md "v_cndmask_b32 source modifiers"): abs clears -; bit 31 and neg flips it on the raw bits, so a signalling NaN stays signalling and a denormal isn't flushed. -; x: s4 = 0 selects src0, -v1 of the sNaN 0x7f800001 = 0xff800001 (a float negate may quiet it to 0xffc00001) -; y: s4 = 0 selects src0, |v6| of the sNaN 0xff800001 = 0x7f800001 -; z: s4 = 0 selects src0, -|v7| of the denormal 0x00000001 = 0x80000001 (a flushing float op gives 0x80000000) -; w: s5 = all lanes selects src1, -v6 of 0xff800001 = 0x7f800001 -; Expected mrt0 bits: 0xff800001, 0x7f800001, 0x80000001, 0x7f800001 -v_mov_b32_e32 v1, 0x7f800001 -v_mov_b32_e32 v6, 0xff800001 -v_mov_b32_e32 v7, 1 -s_mov_b32 s4, 0 -s_mov_b32 s5, -1 -v_cndmask_b32_e64 v2, -v1, v6, s4 -v_cndmask_b32_e64 v3, |v6|, v1, s4 -v_cndmask_b32_e64 v4, -|v7|, v1, s4 -v_cndmask_b32_e64 v5, v1, -v6, s5 -exp mrt0 v2, v3, v4, v5 done vm -s_endpgm diff --git a/runtime/test/shaders/ps_cube_sample.asm b/runtime/test/shaders/ps_cube_sample.asm deleted file mode 100644 index 8ce4d7c5d..000000000 --- a/runtime/test/shaders/ps_cube_sample.asm +++ /dev/null @@ -1,29 +0,0 @@ -; Cube sampling test: direction (2u - 1, 2v - 1, -0.6) from attr0, cube face coordinates the way the hardware takes -; them (s, t = sc, tc / |cubema| + 1.5; face + 8 * slice for slice 1 of a cube array), then image_sample dim:CUBE. -; T# at s[8:15] loaded via s[0:1], literal S# (nearest, clamp to edge) at s[16:19]. -; Run: vk_texture_test cube -> every pixel is the texel a cube sample of its direction reads from the second cube -v_interp_p1_f32_e32 v2, v0, attr0.x -v_interp_p2_f32_e32 v2, v1, attr0.x -v_interp_p1_f32_e32 v3, v0, attr0.y -v_interp_p2_f32_e32 v3, v1, attr0.y -v_fma_f32 v2, v2, 2.0, -1.0 -v_fma_f32 v3, v3, 2.0, -1.0 -v_mov_b32_e32 v4, 0xbf19999a -v_cubema_f32 v5, v2, v3, v4 -v_rcp_f32_e64 v5, |v5| -v_cubesc_f32 v6, v2, v3, v4 -v_cubetc_f32 v7, v2, v3, v4 -v_fmaak_f32 v6, v6, v5, 0x3fc00000 -v_fmaak_f32 v7, v7, v5, 0x3fc00000 -v_cubeid_f32 v8, v2, v3, v4 -v_add_f32_e32 v8, 0x41000000, v8 -s_load_dwordx8 s[8:15], s[0:1], 0x0 -s_waitcnt lgkmcnt(0) -s_mov_b32 s16, 0x92 -s_mov_b32 s17, 0xc00000 -s_mov_b32 s18, 0x14500000 -s_mov_b32 s19, 0 -image_sample v[9:12], v[6:8], s[8:15], s[16:19] dmask:0xf dim:SQ_RSRC_IMG_CUBE -s_waitcnt vmcnt(0) -exp mrt0 v9, v10, v11, v12 done vm -s_endpgm diff --git a/runtime/test/shaders/ps_cvt_off.asm b/runtime/test/shaders/ps_cvt_off.asm deleted file mode 100644 index 4e8490278..000000000 --- a/runtime/test/shaders/ps_cvt_off.asm +++ /dev/null @@ -1,18 +0,0 @@ -; regen_fixtures: this source has a translator fixture in tests/semantic/fixtures/disasm -; v_cvt_off_f32_i4 (docs/design.md "Constant and ordered VOPC, ..."): D = sext(S0[3:0]) / 16, the ISA's CVT_OFF table -; (0 .. 0.4375, then -0.5 .. -0.0625); bits 4-31 are ignored and the VOP3 output modifiers apply, omod before clamp. -; x: S0 = 0x12345678, low nibble 8: -0.5 -; y: S0 = 7: 0.4375 -; z: S0 = 0xF with mul:4: -0.0625 * 4 = -0.25 -; w: S0 = 7 with mul:4 clamp: 1.75 clamped to 1.0 (clamping first would give 1.75) -; Expected mrt0 bits: 0xbf000000, 0x3ee00000, 0xbe800000, 0x3f800000 -v_mov_b32_e32 v0, 0x12345678 -v_cvt_off_f32_i4_e32 v2, v0 -v_mov_b32_e32 v0, 7 -v_cvt_off_f32_i4_e32 v3, v0 -v_mov_b32_e32 v0, 15 -v_cvt_off_f32_i4_e64 v4, v0 mul:4 -v_mov_b32_e32 v0, 7 -v_cvt_off_f32_i4_e64 v5, v0 clamp mul:4 -exp mrt0 v2, v3, v4, v5 done vm -s_endpgm diff --git a/runtime/test/shaders/ps_exp_color_mask.asm b/runtime/test/shaders/ps_exp_color_mask.asm deleted file mode 100644 index b53961df6..000000000 --- a/runtime/test/shaders/ps_exp_color_mask.asm +++ /dev/null @@ -1,17 +0,0 @@ -; regen_fixtures: this source has a translator fixture in tests/semantic/fixtures/disasm -; A pixel shader's color export has its own lane mask: EXEC at that export. This program exports mrt0 from every -; lane with `done` and no `vm`, waits for the export, and only then turns every lane off. Measured on RDNA2 -; (gfx1036, ps_oracle.py of #3061): every pixel is written with the exported words. A path without a `vm` export -; goes by EXEC at the color export, not by EXEC at the end; until 2026-11-23 the translator discarded every pixel -; here. (The opposite order, EXEC off at the export and back on afterwards, leaves the pixel unwritten on -; hardware; that half is in tests/semantic/test_export_valid_mask.py, where a discard can be asserted.) -; The s_waitcnt matters on hardware: an export is asynchronous, and without it the EXEC write that follows is -; what the hardware sees. -; Expected mrt0 bits, every pixel: 0x40000000 (2.0), 0x40800000 (4.0), 0x40000000, 0x40800000. -v_mov_b32 v2, 2.0 -v_mov_b32 v3, 4.0 -v_mov_b32 v1, 1 -exp mrt0 v2, v3, v2, v3 done -s_waitcnt expcnt(0) -v_cmpx_eq_u32 0, v1 -s_endpgm diff --git a/runtime/test/shaders/ps_f16_const.asm b/runtime/test/shaders/ps_f16_const.asm deleted file mode 100644 index 9c0fc61de..000000000 --- a/runtime/test/shaders/ps_f16_const.asm +++ /dev/null @@ -1,20 +0,0 @@ -; Inline float constants in f16 ops are f16 values: the constant sits in the low half of the operand and the high -; half is zero (so the high half that op_sel selects from a constant reads +0.0). They are not f32 bit patterns. -; v0 = 0.25 | 3.0 << 16 (low | high half); destinations start as 0xaaaa5555. -; v_add_f16 1.0 + 0.25 = 1.25 -; v_med3_f16 v0, -4.0, 0.5 [1,0,0,1]: med(3, -4, 0.5) = 0.5 into the high half -; v_fma_f16 v0, 2.0, 0.5 [0,0,1,0]: 0.25 * 2 + (high half of the constant = 0) = 0.5 -; v_cvt_f32_f16 0.5 = 0x3f000000 -; The words are the ones an RX 6800 (gfx1030) gave for this body run as a raw kernel, wave32 and wave64. -; Expected mrt0 bits: 0xaaaa3d00, 0x38005555, 0xaaaa3800, 0x3f000000 -v_mov_b32 v0, 0x42003400 -v_mov_b32 v2, 0xaaaa5555 -v_mov_b32 v3, 0xaaaa5555 -v_mov_b32 v4, 0xaaaa5555 -v_mov_b32 v5, 0xaaaa5555 -v_add_f16 v2, 1.0, v0 -v_med3_f16 v3, v0, -4.0, 0.5 op_sel:[1,0,0,1] -v_fma_f16 v4, v0, 2.0, 0.5 op_sel:[0,0,1,0] -v_cvt_f32_f16 v5, 0.5 -exp mrt0 v2, v3, v4, v5 done vm -s_endpgm diff --git a/runtime/test/shaders/ps_f16_const2.asm b/runtime/test/shaders/ps_f16_const2.asm deleted file mode 100644 index 3180ab7d4..000000000 --- a/runtime/test/shaders/ps_f16_const2.asm +++ /dev/null @@ -1,18 +0,0 @@ -; Inline float constants in packed f16 ops, v_cos_f16 and an f16 compare: an f16 value in the low half of the -; operand, zero in the high half (see ps_f16_const). -; v0 = 0.25 | 3.0 << 16 (low | high half). -; v_pk_add_f16 1.0, v0: low 1.0 + 0.25 = 1.25, high 0 + 3.0 = 3.0 -; the same with op_sel:[1,1] op_sel_hi:[0,0]: low 0 + 3.0 = 3.0, high 1.0 + 0.25 = 1.25 -; v_cos_f16 0.5 (turns) = -1.0, high half of 0xaaaa5555 kept -; v_cmp_lt_f16 0.5 < 0.25 is false, so v_cndmask_b32 picks 3 (it would pick 7 if the constant were read as 0.0) -; The words are the ones an RX 6800 (gfx1030) gave for this body run as a raw kernel, wave32 and wave64. -; Expected mrt0 bits: 0x42003d00, 0x3d004200, 0xaaaabc00, 3 -v_mov_b32 v0, 0x42003400 -v_mov_b32 v4, 0xaaaa5555 -v_pk_add_f16 v2, 1.0, v0 -v_pk_add_f16 v3, 1.0, v0 op_sel:[1,1] op_sel_hi:[0,0] -v_cos_f16 v4, 0.5 -v_cmp_lt_f16_e64 s1, 0.5, v0 -v_cndmask_b32_e64 v5, 3, 7, s1 -exp mrt0 v2, v3, v4, v5 done vm -s_endpgm diff --git a/runtime/test/shaders/ps_f16_fnan_med3.asm b/runtime/test/shaders/ps_f16_fnan_med3.asm deleted file mode 100644 index ed0d73a00..000000000 --- a/runtime/test/shaders/ps_f16_fnan_med3.asm +++ /dev/null @@ -1,30 +0,0 @@ -; regen_fixtures: this source has a translator fixture in tests/semantic/fixtures/disasm -; v_med3_f16 with a quiet NaN in S2, or in two operands: the f16 form of ps_fnan_med3_s2. Inputs are read from memory -; at run time; each word holds one f16 in its low half. The V# in s[0:3] points at 0x1000 (num_records 16); the test -; seeds 0x1000..0x100c with a..d = 0x00004500 0x00004700 0x00007e01 0x0000c100 (5.0, 7.0, NaN, -2.5 as f16). -; v_med3_f16 (op_sel 0) writes the low half of its destination and keeps the high half (docs/design.md, "16-bit -; results"); destinations start as 0xaaaa5555. -; Expected words, from the rule measured on RDNA2 hardware (docs/design.md, "Float min/max/med3 with NaN": with any -; NaN operand the result is min3(s0, s1, s2); min/max: one NaN operand gives the other, both NaN give src0): -; med3(5.0, 7.0, NaN) = 5.0 0x4500 -; med3(NaN, NaN, 5.0) = 5.0 0x4500 -; med3(NaN, -2.5, NaN) = -2.5 0xc100 -; med3(7.0, NaN, NaN) = 7.0 0x4700 -; Expected mrt0 bits: 0xaaaa4500, 0xaaaa4500, 0xaaaac100, 0xaaaa4700 -; The all-NaN case is left out: its NaN payload is not modelled (docs/design.md). -s_buffer_load_dwordx4 s[4:7], s[0:3], 0 -s_waitcnt lgkmcnt(0) -v_mov_b32_e32 v1, s4 -v_mov_b32_e32 v2, s5 -v_mov_b32_e32 v3, s6 -v_mov_b32_e32 v4, s7 -v_mov_b32 v5, 0xaaaa5555 -v_mov_b32 v6, 0xaaaa5555 -v_mov_b32 v7, 0xaaaa5555 -v_mov_b32 v8, 0xaaaa5555 -v_med3_f16 v5, v1, v2, v3 -v_med3_f16 v6, v3, v3, v1 -v_med3_f16 v7, v3, v4, v3 -v_med3_f16 v8, v2, v3, v3 -exp mrt0 v5, v6, v7, v8 done vm -s_endpgm diff --git a/runtime/test/shaders/ps_f16_med3_mods.asm b/runtime/test/shaders/ps_f16_med3_mods.asm deleted file mode 100644 index 269534f82..000000000 --- a/runtime/test/shaders/ps_f16_med3_mods.asm +++ /dev/null @@ -1,21 +0,0 @@ -; v_med3_f16 op_sel with neg/abs (they apply to the selected half), clamp, and a destination that is also a source. -; v0 = 0.5 | -2.5 << 16, v1 = 2.0 | -8.0 << 16, v2 = 1.0 | 0.75 << 16 (low | high half). -; -v0, |v1|, v2 [1,1,0,1] med(2.5, 8, 1) = 2.5 into the high half of 0xaaaa5555 -; |v0|, |v1|, v2 [1,1,1,1] clamp med(2.5, 8, 0.75) = 2.5, clamped to 1.0, into the high half of 0xaaaa5555 -; v5 = v0; -v5, v1, |v1| [1,0,1,1] med(2.5, 2, 8) = 2.5 into the high half of v5, which was just read; low half kept -; v0, v1, -|v2| [0,1,1,0] med(0.5, -8, -0.75) = -0.75 into the low half of 0xaaaa5555 -; The words are the ones an RX 6800 (gfx1030) gave for this body run as a raw kernel, wave32 and wave64. -; Expected mrt0 bits: 0x41005555, 0x3c005555, 0x41003800, 0xaaaaba00 -v_mov_b32 v0, 0xc1003800 -v_mov_b32 v1, 0xc8004000 -v_mov_b32 v2, 0x3a003c00 -v_mov_b32 v3, 0xaaaa5555 -v_mov_b32 v4, 0xaaaa5555 -v_mov_b32 v5, v0 -v_mov_b32 v6, 0xaaaa5555 -v_med3_f16 v3, -v0, |v1|, v2 op_sel:[1,1,0,1] -v_med3_f16 v4, |v0|, |v1|, v2 op_sel:[1,1,1,1] clamp -v_med3_f16 v5, -v5, v1, |v1| op_sel:[1,0,1,1] -v_med3_f16 v6, v0, v1, -|v2| op_sel:[0,1,1,0] -exp mrt0 v3, v4, v5, v6 done vm -s_endpgm diff --git a/runtime/test/shaders/ps_f16_med3_opsel.asm b/runtime/test/shaders/ps_f16_med3_opsel.asm deleted file mode 100644 index e9d49d790..000000000 --- a/runtime/test/shaders/ps_f16_med3_opsel.asm +++ /dev/null @@ -1,20 +0,0 @@ -; v_med3_f16 op_sel, one bit at a time: bit i reads the high half of source i, the last bit writes the high half -; of the destination; the other half of the destination is kept. -; v0 = 1.0 | 2.5 << 16, v1 = 2.0 | 8.0 << 16, v2 = 3.0 | 1.5 << 16 (low | high half); destinations start as 0xaaaa5555. -; [1,0,0,0] med(2.5, 2, 3) = 2.5 [0,1,0,0] med(1, 8, 3) = 3 [0,0,1,0] med(1, 2, 1.5) = 1.5 -; [0,0,0,1] med(1, 2, 3) = 2 into the high half -; The words are the ones an RX 6800 (gfx1030) gave for this body run as a raw kernel, wave32 and wave64. -; Expected mrt0 bits: 0xaaaa4100, 0xaaaa4200, 0xaaaa3e00, 0x40005555 -v_mov_b32 v0, 0x41003c00 -v_mov_b32 v1, 0x48004000 -v_mov_b32 v2, 0x3e004200 -v_mov_b32 v3, 0xaaaa5555 -v_mov_b32 v4, 0xaaaa5555 -v_mov_b32 v5, 0xaaaa5555 -v_mov_b32 v6, 0xaaaa5555 -v_med3_f16 v3, v0, v1, v2 op_sel:[1,0,0,0] -v_med3_f16 v4, v0, v1, v2 op_sel:[0,1,0,0] -v_med3_f16 v5, v0, v1, v2 op_sel:[0,0,1,0] -v_med3_f16 v6, v0, v1, v2 op_sel:[0,0,0,1] -exp mrt0 v3, v4, v5, v6 done vm -s_endpgm diff --git a/runtime/test/shaders/ps_f16_pack.asm b/runtime/test/shaders/ps_f16_pack.asm deleted file mode 100644 index 00535f367..000000000 --- a/runtime/test/shaders/ps_f16_pack.asm +++ /dev/null @@ -1,16 +0,0 @@ -; v_pack_b32_f16 with inline float constants and op_sel: dst = half of src0 | half of src1 << 16. A constant is -; an f16 value in the low half of the operand with a zero high half (see ps_f16_const). -; v0 = 0.25 | 3.0 << 16, v1 = 4.0 | 0.25 << 16 (low | high half). -; 1.0, v0: 0x3c00 | 0x3400 << 16 v0, 0.5: 0x3400 | 0x3800 << 16 -; 2.0, v0 op_sel:[1,0,0]: the high half of the constant (0) | 0x3400 << 16 -; v0, v1 op_sel:[1,0,0]: the high half of v0 (0x4200) | the low half of v1 (0x4400) << 16 -; The words are the ones an RX 6800 (gfx1030) gave for this body run as a raw kernel, wave32 and wave64. -; Expected mrt0 bits: 0x34003c00, 0x38003400, 0x34000000, 0x44004200 -v_mov_b32 v0, 0x42003400 -v_mov_b32 v1, 0x34004400 -v_pack_b32_f16 v2, 1.0, v0 -v_pack_b32_f16 v3, v0, 0.5 -v_pack_b32_f16 v4, 2.0, v0 op_sel:[1,0,0] -v_pack_b32_f16 v5, v0, v1 op_sel:[1,0,0] -exp mrt0 v2, v3, v4, v5 done vm -s_endpgm diff --git a/runtime/test/shaders/ps_f16_pack_mods.asm b/runtime/test/shaders/ps_f16_pack_mods.asm deleted file mode 100644 index 65ee757c1..000000000 --- a/runtime/test/shaders/ps_f16_pack_mods.asm +++ /dev/null @@ -1,20 +0,0 @@ -; regen_fixtures: this source has a translator fixture in tests/semantic/fixtures/disasm -; v_pack_b32_f16 with NEG and ABS on a source: each acts on the selected 16-bit half as a plain bit move -; (ABS clears bit 15, NEG flips it, ABS first), before the half is packed. The rule and its words were measured -; on a Radeon 680M (gfx1036, RDNA2 iGPU, AMD Windows driver 32.0.21044.64) with raw kernels: -v0 turned 0x7c01 -; into 0xfe01 under IEEE mode 1 and 0xfc01 under mode 0, in either half and with op_sel (#1548 SHADER-260). -; Quieting an sNaN half under IEEE mode 1 is not modelled (SHADER-190); the values below are not NaNs. -; v0 = 0.25 | 3.0 << 16, v1 = 4.0 | 0.25 << 16 (low | high half). -; -v0, |v1|: -0x3400 | 0x4400 << 16 -; v0, -v1: 0x3400 | -0x4400 << 16 -; -|v0|, v1 op_sel:[1,0,0]: -(0x4200) | 0x4400 << 16 -; -v0, -|v1| op_sel:[0,1,0]: -0x3400 | -(0x3400) << 16 -; Expected mrt0 bits: 0x4400b400, 0xc4003400, 0x4400c200, 0xb400b400 -v_mov_b32 v0, 0x42003400 -v_mov_b32 v1, 0x34004400 -v_pack_b32_f16 v2, -v0, |v1| -v_pack_b32_f16 v3, v0, -v1 -v_pack_b32_f16 v4, -|v0|, v1 op_sel:[1,0,0] -v_pack_b32_f16 v5, -v0, -|v1| op_sel:[0,1,0] -exp mrt0 v2, v3, v4, v5 done vm -s_endpgm diff --git a/runtime/test/shaders/ps_f16_vop1.asm b/runtime/test/shaders/ps_f16_vop1.asm deleted file mode 100644 index 123f29b01..000000000 --- a/runtime/test/shaders/ps_f16_vop1.asm +++ /dev/null @@ -1,18 +0,0 @@ -; f16 unary (VOP1) rounding ops read the low half and keep the high half of the destination. -; v0 = 2.5 | -1.5 << 16, v1 = -0.75 | 3.5 << 16 (low | high half); destinations start as 0xaaaa5555. -; v_rndne_f16 2.5 -> 2.0 (ties to even) v_floor_f16 -0.75 -> -1.0 v_ceil_f16_e64 -v0: ceil(-2.5) = -2.0 -; v_trunc_f16 -0.75 -> -0.0 (0x8000: the zero keeps the sign) -; The words are the ones an RX 6800 (gfx1030) gave for this body run as a raw kernel, wave32 and wave64. -; Expected mrt0 bits: 0xaaaa4000, 0xaaaabc00, 0xaaaac000, 0xaaaa8000 -v_mov_b32 v0, 0xbe004100 -v_mov_b32 v1, 0x4300ba00 -v_mov_b32 v2, 0xaaaa5555 -v_mov_b32 v3, 0xaaaa5555 -v_mov_b32 v4, 0xaaaa5555 -v_mov_b32 v5, 0xaaaa5555 -v_rndne_f16 v2, v0 -v_floor_f16 v3, v1 -v_ceil_f16_e64 v4, -v0 -v_trunc_f16 v5, v1 -exp mrt0 v2, v3, v4, v5 done vm -s_endpgm diff --git a/runtime/test/shaders/ps_f16_vop1b.asm b/runtime/test/shaders/ps_f16_vop1b.asm deleted file mode 100644 index 891f564b7..000000000 --- a/runtime/test/shaders/ps_f16_vop1b.asm +++ /dev/null @@ -1,18 +0,0 @@ -; f16 unary (VOP1) ops read the low half and keep the high half of the destination. -; v0 = 4.0 | 0.25 << 16, v1 = -2.75 | 1.5 << 16 (low | high half); destinations start as 0xaaaa5555. -; v_fract_f16 -2.75 - floor(-2.75) = 0.25 v_sqrt_f16 sqrt(4) = 2.0 v_rcp_f16_e64 -v0: 1 / -4 = -0.25 -; v_rsq_f16 1 / sqrt(4) = 0.5 -; The words are the ones an RX 6800 (gfx1030) gave for this body run as a raw kernel, wave32 and wave64. -; Expected mrt0 bits: 0xaaaa3400, 0xaaaa4000, 0xaaaab400, 0xaaaa3800 -v_mov_b32 v0, 0x34004400 -v_mov_b32 v1, 0x3e00c180 -v_mov_b32 v2, 0xaaaa5555 -v_mov_b32 v3, 0xaaaa5555 -v_mov_b32 v4, 0xaaaa5555 -v_mov_b32 v5, 0xaaaa5555 -v_fract_f16 v2, v1 -v_sqrt_f16 v3, v0 -v_rcp_f16_e64 v4, -v0 -v_rsq_f16 v5, v0 -exp mrt0 v2, v3, v4, v5 done vm -s_endpgm diff --git a/runtime/test/shaders/ps_f16_vop2.asm b/runtime/test/shaders/ps_f16_vop2.asm deleted file mode 100644 index b98cda812..000000000 --- a/runtime/test/shaders/ps_f16_vop2.asm +++ /dev/null @@ -1,20 +0,0 @@ -; regen_fixtures: this source has a translator fixture in tests/semantic/fixtures/disasm -; f16 VOP2 ops read the low halves and are partial writes: the high half of the destination is kept. The VOP3 -; (_e64) form adds neg/abs. The accumulator of v_fmac_f16 is the low half of its destination. -; v0 = 1.5 | 4.0 << 16, v1 = 0.5 | 2.0 << 16 (low | high half); destinations start as 0xaaaa5555, v5 as 1.0 | 3.0 << 16. -; v_add_f16 1.5 + 0.5 = 2.0 v_sub_f16_e64 -v0, |v1|: -1.5 - 0.5 = -2.0 v_mul_f16 1.5 * 0.5 = 0.75 -; v_fmac_f16 1.5 * 0.5 + 1.0 = 1.75 -; The words are the ones an RX 6800 (gfx1030) gave for this body run as a raw kernel, wave32 and wave64. -; Expected mrt0 bits: 0xaaaa4000, 0xaaaac000, 0xaaaa3a00, 0x42003f00 -v_mov_b32 v0, 0x44003e00 -v_mov_b32 v1, 0x40003800 -v_mov_b32 v2, 0xaaaa5555 -v_mov_b32 v3, 0xaaaa5555 -v_mov_b32 v4, 0xaaaa5555 -v_mov_b32 v5, 0x42003c00 -v_add_f16 v2, v0, v1 -v_sub_f16_e64 v3, -v0, |v1| -v_mul_f16 v4, v0, v1 -v_fmac_f16 v5, v0, v1 -exp mrt0 v2, v3, v4, v5 done vm -s_endpgm diff --git a/runtime/test/shaders/ps_f16_vop2b.asm b/runtime/test/shaders/ps_f16_vop2b.asm deleted file mode 100644 index 4ab4b5e41..000000000 --- a/runtime/test/shaders/ps_f16_vop2b.asm +++ /dev/null @@ -1,18 +0,0 @@ -; More f16 VOP2 ops: low halves in, high half of the destination kept; neg/abs and clamp in the VOP3 (_e64) form. -; v0 = 1.5 | 4.0 << 16, v1 = 0.5 | 2.0 << 16 (low | high half); destinations start as 0xaaaa5555, v5 as 1.0 | 3.0 << 16. -; v_max_f16 max(1.5, 0.5) = 1.5 v_min_f16_e64 v0, -v1: min(1.5, -0.5) = -0.5 -; v_add_f16_e64 clamp: 2.0 clamped to 1.0 v_fmac_f16_e64 -v0, |v1|: -1.5 * 0.5 + 1.0 = 0.25 -; The words are the ones an RX 6800 (gfx1030) gave for this body run as a raw kernel, wave32 and wave64. -; Expected mrt0 bits: 0xaaaa3e00, 0xaaaab800, 0xaaaa3c00, 0x42003400 -v_mov_b32 v0, 0x44003e00 -v_mov_b32 v1, 0x40003800 -v_mov_b32 v2, 0xaaaa5555 -v_mov_b32 v3, 0xaaaa5555 -v_mov_b32 v4, 0xaaaa5555 -v_mov_b32 v5, 0x42003c00 -v_max_f16 v2, v0, v1 -v_min_f16_e64 v3, v0, -v1 -v_add_f16_e64 v4, v0, v1 clamp -v_fmac_f16_e64 v5, -v0, |v1| -exp mrt0 v2, v3, v4, v5 done vm -s_endpgm diff --git a/runtime/test/shaders/ps_f32_mods.asm b/runtime/test/shaders/ps_f32_mods.asm deleted file mode 100644 index 245750e82..000000000 --- a/runtime/test/shaders/ps_f32_mods.asm +++ /dev/null @@ -1,20 +0,0 @@ -; regen_fixtures: this source has a translator fixture in tests/semantic/fixtures/disasm -; v_mac_f32 is the VOP2 form of v_mad_f32: the product is rounded before the add (not fused). VOP3 clamp and -; output modifiers on conversions: v_cvt_f32_ubyte1 with clamp, v_cvt_f32_u32 with mul:4, v_cvt_f32_f16 with -; div:2 and v_rcp_iflag_f32 with mul:4, the last two summed (0.5 + 1.0; each modifier missing gives a different sum). -; Expected mrt0 bits: 0xc0256a01, 0x3f800000, 0x41e00000, 0x3fc00000 -v_mov_b32_e32 v0, 0xbc500c59 -v_mov_b32_e32 v1, 0x435a2099 -v_mov_b32_e32 v2, 0x3e3db015 -v_mac_f32_e32 v2, v0, v1 -v_mov_b32_e32 v3, 0x12347856 -v_cvt_f32_ubyte1_e64 v4, v3 clamp -v_mov_b32_e32 v5, 7 -v_cvt_f32_u32_e64 v6, v5 mul:4 -v_mov_b32_e32 v7, 0x3c00 -v_cvt_f32_f16_e64 v9, v7 div:2 -v_mov_b32_e32 v8, 0x40800000 -v_rcp_iflag_f32_e64 v10, v8 mul:4 -v_add_f32_e32 v11, v9, v10 -exp mrt0 v2, v4, v6, v11 done vm -s_endpgm diff --git a/runtime/test/shaders/ps_f64_mods.asm b/runtime/test/shaders/ps_f64_mods.asm deleted file mode 100644 index 2fb197e60..000000000 --- a/runtime/test/shaders/ps_f64_mods.asm +++ /dev/null @@ -1,17 +0,0 @@ -; regen_fixtures: this source has a translator fixture in tests/semantic/fixtures/disasm -; Output modifiers on v_add_f64 (VOP3_Profile: clamp and omod): omod scales, then clamp to [0, 1]. -; a = 0.75, b = 0.5 as doubles (low word first); each export is the high word of one double result (low words are 0). -; mul:2 (a+b)*2 = 2.5, clamp min(a+b, 1) = 1.0, div:2 clamp (a+b)/2 = 0.625 (clamp before scaling would give 0.5), -; mul:4 (a-b)*4 = 1.0. Without the modifiers every word would be 0x3ff40000 (1.25) or 0x3fd00000 (0.25). -; Needs shaderFloat64; vk_harness exits 77 (SKIP) on a device without it. -; Expected mrt0 bits: 0x40040000, 0x3ff00000, 0x3fe40000, 0x3ff00000 -v_mov_b32 v0, 0 -v_mov_b32 v1, 0x3fe80000 -v_mov_b32 v2, 0 -v_mov_b32 v3, 0x3fe00000 -v_add_f64 v[4:5], v[0:1], v[2:3] mul:2 -v_add_f64 v[6:7], v[0:1], v[2:3] clamp -v_add_f64 v[8:9], v[0:1], v[2:3] clamp div:2 -v_add_f64 v[10:11], v[0:1], -v[2:3] mul:4 -exp mrt0 v5, v7, v9, v11 done vm -s_endpgm diff --git a/runtime/test/shaders/ps_f64_round.asm b/runtime/test/shaders/ps_f64_round.asm deleted file mode 100644 index 41cb8b247..000000000 --- a/runtime/test/shaders/ps_f64_round.asm +++ /dev/null @@ -1,25 +0,0 @@ -; v_add_f64 under MODE.FP_ROUND[3:2] (3 = toward zero, 0 = nearest even) with extreme magnitudes near +-DBL_MAX. -; Expected mrt0 bits: 0xc12af665, 0x3fe7ffff, 0xbfffffff, 0xc12af666 -; -; mrt0.x: 0x7fdd9bb47daa1333 + 0xffefffffffffffff (RTZ) -> 0xffe13225:c12af665; low word 0xc12af665 (#2891; RNE 0xc12af666) -; mrt0.y: 0xffcffffffffffffe + 0x7fefffffffffffff (RTZ) -> 0x7fe7ffff:ffffffff (borrow across lo=0); hi ^ 0x40000000 = 0x3fe7ffff -; mrt0.z: 0x7fefffffffffffff + 0x7fefffffffffffff (RTZ) -> 0x7fefffff:ffffffff (finite overflow -> +DBL_MAX); lo ^ 0x40000000 = 0xbfffffff -; mrt0.w: 0x7fdd9bb47daa1333 + 0xffefffffffffffff after switching back to RNE (0) -> low word 0xc12af666 -s_setreg_imm32_b32 hwreg(HW_REG_MODE, 2, 2), 3 -v_mov_b32_e32 v0, 0x7daa1333 -v_mov_b32_e32 v1, 0x7fdd9bb4 -v_mov_b32_e32 v2, 0xffffffff -v_mov_b32_e32 v3, 0xffefffff -v_add_f64 v[4:5], v[0:1], v[2:3] -v_mov_b32_e32 v6, 0xfffffffe -v_mov_b32_e32 v7, 0xffcfffff -v_mov_b32_e32 v8, 0xffffffff -v_mov_b32_e32 v9, 0x7fefffff -v_add_f64 v[10:11], v[6:7], v[8:9] -v_xor_b32_e32 v11, 0x40000000, v11 -v_add_f64 v[12:13], v[8:9], v[8:9] -v_xor_b32_e32 v12, 0x40000000, v12 -s_setreg_imm32_b32 hwreg(HW_REG_MODE, 2, 2), 0 -v_add_f64 v[14:15], v[0:1], v[2:3] -exp mrt0 v4, v11, v12, v14 done vm -s_endpgm diff --git a/runtime/test/shaders/ps_far_branch.asm b/runtime/test/shaders/ps_far_branch.asm deleted file mode 100644 index 15f807291..000000000 --- a/runtime/test/shaders/ps_far_branch.asm +++ /dev/null @@ -1,321 +0,0 @@ -; Far branches: the idiom s_getpc_b64 s[a:a+1]; s_add_u32 sa, sa, K; s_addc_u32 sa+1, sa+1, 0|-1; s_setpc_b64 s[a:a+1] (and the -; s_sub_u32/s_subb_u32 form), which jumps beyond the +-32K dwords an s_branch reaches. docs/design.md "Far branches": the -; translator folds the four instructions into one branch. RDNA2 ISA: S_GETPC_B64 returns the address of the next -; instruction; S_ADD_U32 / S_ADDC_U32 add K to that 64-bit address (carry through SCC; the high word is 0 for a forward -; K and 0xffffffff, as -1, with K = 2^32 - |K| for a backward one; S_SUB_U32 / S_SUBB_U32 subtract |K|); S_SETPC_B64 -; sets PC. K is in bytes from the instruction after s_getpc. The block between a far branch and its target holds -; "poison" ORs that must never run, and 40 s_nop (4 bytes each, 160 bytes) so that K > 64 is a 32-bit literal. -; Sizes (bytes): s_nop 4, s_or_b32 with an inline constant 4, with a literal 8, s_add_u32/s_sub_u32/s_cmp with a literal 8. -; x (s10 = 1 to start): two forward far branches, one through s[4:5], one through s[8:9]: -; K = add (8) + addc (4) + setpc (4) + poison s_or literal (8) + 40 nops (160) = 184 = 0xb8, landing on "s_or s10, 2"; -; the poison ORs 0x100 / 0x200 are skipped, the targets OR 2 and 4: x = 1 | 2 | 4 = 0x00000007. -; y (s11 = 0): a backward loop with s_sub_u32 / s_subb_u32 (hi = 0). The body is s_add_u32 s11, 1 (4) + 40 nops (160) + -; s_cmp_ge_u32 s11, 3 (4) + s_cbranch_scc1 (4) + s_getpc (4) = 176 bytes from the loop top to the instruction after -; s_getpc, so K = 176 = 0xb0. The far branch back is taken after iterations 1 and 2 and not after iteration 3 -; (scc = 1 jumps over it), so s11 counts 3; then s_or s11, 0x10: y = 0x00000013. -; z (s12 = 0): a backward loop with s_add_u32 K / s_addc_u32 -1, K = -180 = 0xffffff4c: body s_add_u32 s12, 0x10 (4) + -; 40 nops (160) + s_cmp_ge_u32 s12, 0x50 (literal, 8) + s_cbranch_scc1 (4) + s_getpc (4) = 180. s12 steps by 0x10 and -; the loop leaves when s12 >= 0x50, after 5 iterations (the far branch back taken 4 times): s12 = 0x50, then -; s_or s12, 1: z = 0x00000051. -; w (s13 = 0): a far forward branch behind a conditional branch that skips it (s_cbranch_scc0 over the 5 dwords of the -; sequence), run twice. First scc = (s13 == 1) = 0: the sequence is skipped, the code after it runs: s13 |= 1, then -; the target ORs 2 (K = 8+4+4 + 4 + 160 = 180 = 0xb4), s13 = 3. Second scc = (s13 == 3) = 1: the sequence runs, it -; jumps over "s_or s13, 4" and the nops to the target: s13 |= 8: w = 0x0000000b. -; A translation that folded a far branch to the wrong target runs a poison OR (x gains 0x300), repeats or skips a -; loop iteration (y, z), or mishandles the conditional case (w). The loops count on s11/s12, so a wrong target shows -; as a different count, not just a hang. -; Expected mrt0 bits: 0x00000007, 0x00000013, 0x00000051, 0x0000000b -s_mov_b32 s10, 1 -s_getpc_b64 s[4:5] -s_add_u32 s4, s4, 184 -s_addc_u32 s5, s5, 0 -s_setpc_b64 s[4:5] -s_or_b32 s10, s10, 0x100 -s_nop 0 -s_nop 0 -s_nop 0 -s_nop 0 -s_nop 0 -s_nop 0 -s_nop 0 -s_nop 0 -s_nop 0 -s_nop 0 -s_nop 0 -s_nop 0 -s_nop 0 -s_nop 0 -s_nop 0 -s_nop 0 -s_nop 0 -s_nop 0 -s_nop 0 -s_nop 0 -s_nop 0 -s_nop 0 -s_nop 0 -s_nop 0 -s_nop 0 -s_nop 0 -s_nop 0 -s_nop 0 -s_nop 0 -s_nop 0 -s_nop 0 -s_nop 0 -s_nop 0 -s_nop 0 -s_nop 0 -s_nop 0 -s_nop 0 -s_nop 0 -s_nop 0 -s_nop 0 -s_or_b32 s10, s10, 2 -s_getpc_b64 s[8:9] -s_add_u32 s8, s8, 184 -s_addc_u32 s9, s9, 0 -s_setpc_b64 s[8:9] -s_or_b32 s10, s10, 0x200 -s_nop 0 -s_nop 0 -s_nop 0 -s_nop 0 -s_nop 0 -s_nop 0 -s_nop 0 -s_nop 0 -s_nop 0 -s_nop 0 -s_nop 0 -s_nop 0 -s_nop 0 -s_nop 0 -s_nop 0 -s_nop 0 -s_nop 0 -s_nop 0 -s_nop 0 -s_nop 0 -s_nop 0 -s_nop 0 -s_nop 0 -s_nop 0 -s_nop 0 -s_nop 0 -s_nop 0 -s_nop 0 -s_nop 0 -s_nop 0 -s_nop 0 -s_nop 0 -s_nop 0 -s_nop 0 -s_nop 0 -s_nop 0 -s_nop 0 -s_nop 0 -s_nop 0 -s_nop 0 -s_or_b32 s10, s10, 4 -s_mov_b32 s11, 0 -s_add_u32 s11, s11, 1 -s_nop 0 -s_nop 0 -s_nop 0 -s_nop 0 -s_nop 0 -s_nop 0 -s_nop 0 -s_nop 0 -s_nop 0 -s_nop 0 -s_nop 0 -s_nop 0 -s_nop 0 -s_nop 0 -s_nop 0 -s_nop 0 -s_nop 0 -s_nop 0 -s_nop 0 -s_nop 0 -s_nop 0 -s_nop 0 -s_nop 0 -s_nop 0 -s_nop 0 -s_nop 0 -s_nop 0 -s_nop 0 -s_nop 0 -s_nop 0 -s_nop 0 -s_nop 0 -s_nop 0 -s_nop 0 -s_nop 0 -s_nop 0 -s_nop 0 -s_nop 0 -s_nop 0 -s_nop 0 -s_cmp_ge_u32 s11, 3 -s_cbranch_scc1 5 -s_getpc_b64 s[6:7] -s_sub_u32 s6, s6, 176 -s_subb_u32 s7, s7, 0 -s_setpc_b64 s[6:7] -s_or_b32 s11, s11, 0x10 -s_mov_b32 s12, 0 -s_add_u32 s12, s12, 0x10 -s_nop 0 -s_nop 0 -s_nop 0 -s_nop 0 -s_nop 0 -s_nop 0 -s_nop 0 -s_nop 0 -s_nop 0 -s_nop 0 -s_nop 0 -s_nop 0 -s_nop 0 -s_nop 0 -s_nop 0 -s_nop 0 -s_nop 0 -s_nop 0 -s_nop 0 -s_nop 0 -s_nop 0 -s_nop 0 -s_nop 0 -s_nop 0 -s_nop 0 -s_nop 0 -s_nop 0 -s_nop 0 -s_nop 0 -s_nop 0 -s_nop 0 -s_nop 0 -s_nop 0 -s_nop 0 -s_nop 0 -s_nop 0 -s_nop 0 -s_nop 0 -s_nop 0 -s_nop 0 -s_cmp_ge_u32 s12, 0x50 -s_cbranch_scc1 5 -s_getpc_b64 s[8:9] -s_add_u32 s8, s8, 0xffffff4c -s_addc_u32 s9, s9, -1 -s_setpc_b64 s[8:9] -s_or_b32 s12, s12, 1 -s_mov_b32 s13, 0 -s_cmp_eq_u32 s13, 1 -s_cbranch_scc0 5 -s_getpc_b64 s[4:5] -s_add_u32 s4, s4, 180 -s_addc_u32 s5, s5, 0 -s_setpc_b64 s[4:5] -s_or_b32 s13, s13, 1 -s_nop 0 -s_nop 0 -s_nop 0 -s_nop 0 -s_nop 0 -s_nop 0 -s_nop 0 -s_nop 0 -s_nop 0 -s_nop 0 -s_nop 0 -s_nop 0 -s_nop 0 -s_nop 0 -s_nop 0 -s_nop 0 -s_nop 0 -s_nop 0 -s_nop 0 -s_nop 0 -s_nop 0 -s_nop 0 -s_nop 0 -s_nop 0 -s_nop 0 -s_nop 0 -s_nop 0 -s_nop 0 -s_nop 0 -s_nop 0 -s_nop 0 -s_nop 0 -s_nop 0 -s_nop 0 -s_nop 0 -s_nop 0 -s_nop 0 -s_nop 0 -s_nop 0 -s_nop 0 -s_or_b32 s13, s13, 2 -s_cmp_eq_u32 s13, 3 -s_cbranch_scc0 5 -s_getpc_b64 s[4:5] -s_add_u32 s4, s4, 180 -s_addc_u32 s5, s5, 0 -s_setpc_b64 s[4:5] -s_or_b32 s13, s13, 4 -s_nop 0 -s_nop 0 -s_nop 0 -s_nop 0 -s_nop 0 -s_nop 0 -s_nop 0 -s_nop 0 -s_nop 0 -s_nop 0 -s_nop 0 -s_nop 0 -s_nop 0 -s_nop 0 -s_nop 0 -s_nop 0 -s_nop 0 -s_nop 0 -s_nop 0 -s_nop 0 -s_nop 0 -s_nop 0 -s_nop 0 -s_nop 0 -s_nop 0 -s_nop 0 -s_nop 0 -s_nop 0 -s_nop 0 -s_nop 0 -s_nop 0 -s_nop 0 -s_nop 0 -s_nop 0 -s_nop 0 -s_nop 0 -s_nop 0 -s_nop 0 -s_nop 0 -s_nop 0 -s_or_b32 s13, s13, 8 -v_mov_b32_e32 v10, s10 -v_mov_b32_e32 v11, s11 -v_mov_b32_e32 v12, s12 -v_mov_b32_e32 v13, s13 -exp mrt0 v10, v11, v12, v13 done vm -s_endpgm diff --git a/runtime/test/shaders/ps_flat.asm b/runtime/test/shaders/ps_flat.asm deleted file mode 100644 index 1bcf3c9e1..000000000 --- a/runtime/test/shaders/ps_flat.asm +++ /dev/null @@ -1,14 +0,0 @@ -; regen_fixtures: this source has a translator fixture in tests/semantic/fixtures/disasm -; Flat inputs: attr1.x is read only with v_interp_mov (the provoking vertex's value), so its location is declared -; Flat. vs_ids gives the three vertices 0x101, 0x102 and 0x103 there; every pixel must see vertex 0's, 0x101, and -; integer maths on it must work (0x101 + 1). Interpolated, those bits come back as something else. attr0 next to -; it is interpolated as usual. Run: vk_harness vs_ids.spv ps_flat.spv out.raw -; -> mrt0 bits = 0x101, 0x102 on every pixel (0, 1 without Flat); mrt0.zw = ((x + 0.5) / 64, (y + 0.5) / 64) as floats -v_interp_mov_f32_e32 v2, p0, attr1.x -v_add_nc_u32_e32 v3, 1, v2 -v_interp_p1_f32_e32 v4, v0, attr0.x -v_interp_p2_f32_e32 v4, v1, attr0.x -v_interp_p1_f32_e32 v5, v0, attr0.y -v_interp_p2_f32_e32 v5, v1, attr0.y -exp mrt0 v2, v3, v4, v5 done vm -s_endpgm diff --git a/runtime/test/shaders/ps_fma_literal.asm b/runtime/test/shaders/ps_fma_literal.asm deleted file mode 100644 index 014b3aaf2..000000000 --- a/runtime/test/shaders/ps_fma_literal.asm +++ /dev/null @@ -1,15 +0,0 @@ -; regen_fixtures: this source has a translator fixture in tests/semantic/fixtures/disasm -; Which operand the literal K multiplies. v_fmamk_f32/v_madmk_f32 (printed vdst, src0, K, vsrc1): D = S0 * K + S1. -; v_fmaak_f32/v_madak_f32 (printed vdst, src0, vsrc1, K): D = S0 * S1 + K. All values are exact in f32, and each -; word changes if K and vsrc1 trade places: fmamk 2*10+3 = 23, fmaak 2*3+10 = 16, madmk 4*0.5+5 = 7, madak 4*5+0.5 = 20.5. -; Expected mrt0 bits: 0x41b80000, 0x41800000, 0x40e00000, 0x41a40000 -v_mov_b32 v1, 2.0 -v_mov_b32 v3, 0x40400000 -v_fmamk_f32 v5, v1, 0x41200000, v3 -v_fmaak_f32 v6, v1, v3, 0x41200000 -v_mov_b32 v2, 4.0 -v_mov_b32 v4, 0x40a00000 -v_madmk_f32 v7, v2, 0x3f000000, v4 -v_madak_f32 v8, v2, v4, 0x3f000000 -exp mrt0 v5, v6, v7, v8 done vm -s_endpgm diff --git a/runtime/test/shaders/ps_fmac_f16_mods.asm b/runtime/test/shaders/ps_fmac_f16_mods.asm deleted file mode 100644 index 209fd91b4..000000000 --- a/runtime/test/shaders/ps_fmac_f16_mods.asm +++ /dev/null @@ -1,19 +0,0 @@ -; regen_fixtures: this source has a translator fixture in tests/semantic/fixtures/disasm -; VOP3 output modifiers on v_fmac_f16_e64 (docs/design.md "v_fmac_f16, v_interp_p2/mov_f32 output modifiers"): -; On RDNA2 with denorms kept (default MODE), omod (mul:2 / mul:4 / div:2) is ignored on f16; -; clamp to [0, 1] applies; the destination's high half (0xAAAA) is kept. -; x: 1.0 + 1.0 * 1.0 = 2.0, clamp: 1.0 (0x3c00) -; y: 0.5 + 0.5 * 0.5 = 0.75, mul:2 ignored: 0.75 (0x3a00) -; z: -1.0 + 0.5 * 0.5 = -0.75, clamp: 0.0 (0x0000) -; w: 2.0 + 1.0 * 2.0 = 4.0, div:2 ignored: 4.0 (0x4400) -; Expected mrt0 bits: 0xaaaa3c00, 0xaaaa3a00, 0xaaaa0000, 0xaaaa4400 -v_mov_b32_e32 v2, 0xaaaa3c00 -v_fmac_f16_e64 v2, 1.0, 1.0 clamp -v_mov_b32_e32 v3, 0xaaaa3800 -v_fmac_f16_e64 v3, 0.5, 0.5 mul:2 -v_mov_b32_e32 v4, 0xaaaabc00 -v_fmac_f16_e64 v4, 0.5, 0.5 clamp -v_mov_b32_e32 v5, 0xaaaa4000 -v_fmac_f16_e64 v5, 1.0, 2.0 div:2 -exp mrt0 v2, v3, v4, v5 done vm -s_endpgm diff --git a/runtime/test/shaders/ps_fnan_fract.asm b/runtime/test/shaders/ps_fnan_fract.asm deleted file mode 100644 index 85808c159..000000000 --- a/runtime/test/shaders/ps_fnan_fract.asm +++ /dev/null @@ -1,24 +0,0 @@ -; regen_fixtures: this source has a translator fixture in tests/semantic/fixtures/disasm -; v_fract_f32 / v_fract_f16 next to 1.0 and v_max_f32 / v_min_f32 with a quiet-NaN operand, inputs read from memory -; at run time (not inline constants, which the driver could fold). The V# in s[0:3] points at 0x1000 -; (num_records 16); the test seeds 0x1000..0x100c with a..d = 0xaedbe6ff 0x00008800 0x7fc10001 0xc0200000 -; (-1e-10, f16 -2^-13 in the low half, NaN, -2.5). -; Expected words, measured on RDNA2 hardware (AMD Radeon RX 6800, gfx1030, hw-oracle tool from the AnyPS5 -; project, all four IEEE/DX10_CLAMP mode combinations, wave32 and wave64): -; fract_f32(-1e-10) = 0x3f7fffff (1 - 1e-10 rounds to 1.0; the hardware gives the largest float below 1) -; fract_f16(-2^-13) = 0x3bff (likewise in f16; the high half of the destination, 0, is kept) -; max_f32(NaN, -2.5) = 0xc0200000 (a NaN operand gives the other operand) -; min_f32(-2.5, NaN) = 0xc0200000 -; Expected mrt0 bits: 0x3f7fffff, 0x00003bff, 0xc0200000, 0xc0200000 -s_buffer_load_dwordx4 s[4:7], s[0:3], 0 -s_waitcnt lgkmcnt(0) -v_mov_b32_e32 v1, s4 -v_mov_b32_e32 v2, s5 -v_mov_b32_e32 v3, s6 -v_mov_b32_e32 v4, s7 -v_fract_f32_e32 v5, v1 -v_fract_f16_e32 v2, v2 -v_max_f32_e32 v6, v3, v4 -v_min_f32_e32 v7, v4, v3 -exp mrt0 v5, v2, v6, v7 done vm -s_endpgm diff --git a/runtime/test/shaders/ps_fnan_med3.asm b/runtime/test/shaders/ps_fnan_med3.asm deleted file mode 100644 index 97efb2ad1..000000000 --- a/runtime/test/shaders/ps_fnan_med3.asm +++ /dev/null @@ -1,27 +0,0 @@ -; regen_fixtures: this source has a translator fixture in tests/semantic/fixtures/disasm -; v_med3_f32 / v_min3_f32 / v_max3_f32 with a quiet-NaN operand, inputs read from memory at run time (not inline -; constants, which the driver could fold). The V# in s[0:3] points at 0x1000 (num_records 32); the test seeds -; 0x1000..0x1014 with a..f = 0x7fc10001 0x40e00000 0x40a00000 0x7fc10001 0x40600000 0xc0200000 -; (NaN, 7.0, 5.0, NaN, 3.5, -2.5). -; Expected words, measured on RDNA2 hardware (AMD Radeon RX 6800, gfx1030, hw-oracle tool from the AnyPS5 -; project, all four IEEE/DX10_CLAMP mode combinations, wave32 and wave64): -; med3(NaN, 7.0, 5.0) = 0x40a00000 (any NaN operand: min3 of the operands, NaN ignored) -; med3(NaN, 3.5, -2.5) = 0xc0200000 -; min3(NaN, -2.5, 3.5) = 0xc0200000 (min/max: a NaN operand gives the other operand) -; max3(NaN, -2.5, 3.5) = 0x40600000 -; Expected mrt0 bits: 0x40a00000, 0xc0200000, 0xc0200000, 0x40600000 -; The translator before the med3 NaN rule gave 0x40e00000 and 0x40600000 for the two med3 words on an RX 6800. -s_buffer_load_dwordx8 s[4:11], s[0:3], 0 -s_waitcnt lgkmcnt(0) -v_mov_b32_e32 v1, s4 -v_mov_b32_e32 v2, s5 -v_mov_b32_e32 v3, s6 -v_mov_b32_e32 v4, s7 -v_mov_b32_e32 v5, s8 -v_mov_b32_e32 v6, s9 -v_med3_f32 v7, v1, v2, v3 -v_med3_f32 v8, v4, v5, v6 -v_min3_f32 v9, v1, v6, v5 -v_max3_f32 v10, v1, v6, v5 -exp mrt0 v7, v8, v9, v10 done vm -s_endpgm diff --git a/runtime/test/shaders/ps_fnan_med3_s2.asm b/runtime/test/shaders/ps_fnan_med3_s2.asm deleted file mode 100644 index aef780b3f..000000000 --- a/runtime/test/shaders/ps_fnan_med3_s2.asm +++ /dev/null @@ -1,26 +0,0 @@ -; regen_fixtures: this source has a translator fixture in tests/semantic/fixtures/disasm -; v_med3_f32 with a quiet NaN in S2, or in two operands: the cases ps_fnan_med3 does not reach (it puts the NaN in S0 -; only). Inputs are read from memory at run time (not inline constants, which the driver could fold). The V# in s[0:3] -; points at 0x1000 (num_records 16); the test seeds 0x1000..0x100c with a..d = 0x40a00000 0x40e00000 0x7fc10001 -; 0xc0200000 (5.0, 7.0, NaN, -2.5). -; Expected words, from the rule measured on RDNA2 hardware (docs/design.md, "Float min/max/med3 with NaN": with any -; NaN operand the result is min3(s0, s1, s2); min/max: one NaN operand gives the other, both NaN give src0): -; med3(5.0, 7.0, NaN) = min(min(5.0, 7.0), NaN) = 5.0 0x40a00000 -; med3(NaN, NaN, 5.0) = min(min(NaN, NaN), 5.0) = 5.0 0x40a00000 -; med3(NaN, -2.5, NaN) = min(min(NaN, -2.5), NaN) = -2.5 0xc0200000 -; med3(7.0, NaN, NaN) = min(min(7.0, NaN), NaN) = 7.0 0x40e00000 -; Expected mrt0 bits: 0x40a00000, 0x40a00000, 0xc0200000, 0x40e00000 -; The first two rows are the ones suggested in the #2029 review. The all-NaN case is left out: its NaN payload is not -; modelled (docs/design.md). -s_buffer_load_dwordx4 s[4:7], s[0:3], 0 -s_waitcnt lgkmcnt(0) -v_mov_b32_e32 v1, s4 -v_mov_b32_e32 v2, s5 -v_mov_b32_e32 v3, s6 -v_mov_b32_e32 v4, s7 -v_med3_f32 v5, v1, v2, v3 -v_med3_f32 v6, v3, v3, v1 -v_med3_f32 v7, v3, v4, v3 -v_med3_f32 v8, v2, v3, v3 -exp mrt0 v5, v6, v7, v8 done vm -s_endpgm diff --git a/runtime/test/shaders/ps_gather4_c_l.asm b/runtime/test/shaders/ps_gather4_c_l.asm deleted file mode 100644 index e69def495..000000000 --- a/runtime/test/shaders/ps_gather4_c_l.asm +++ /dev/null @@ -1,80 +0,0 @@ -; Depth-compare and clamped/biased image_gather4 variants on the 8x8 RGBA gradient texture (R = 32x/255, G = 32y/255). -; Run: vk_texture_test out.raw 0 92 c00000 14500000 0 -> RGBA32F pixels, all identical. -; At u = v = 0.5 the 2x2 gather footprint is (3,4) (4,4) (4,3) (3,3) in gather order. -; r: image_gather4_c_l, literal S# DEPTH_COMPARE_FUNC=1 (LESS, 0x1092), ref=0.45: -; R = (3,4,4,3)*32/255 = (0.3765,0.5020,0.5020,0.3765); 0.45 < R -> (0,1,1,0) -> base 2 = 6.0 -; g: image_gather4_c_l_o, run-time S# DEPTH_COMPARE_FUNC=6 (GREATER_EQUAL, 0x6092), offset x=+2, ref=0.7: -; R = (5,6,6,5)*32/255 = (0.6275,0.7529,0.7529,0.6275); 0.7 >= R -> (1,0,0,1) -> base 2 = 9.0 -; b: image_gather4_cl, dmask:0x2 (G), clamp=0.0: -; G = (4,4,3,3)*32/255 -> scaled by 255/32 and rounded -> (4,4,3,3) -> base 16 = 17459.0 -; a: image_gather4_c_b_cl_o d16, literal S# DEPTH_COMPARE_FUNC=4 (GREATER, 0x4092), offset x=-1, bias=0, ref=0.3, clamp=0: -; R = (2,3,3,2)*32/255 = (0.2510,0.3765,0.3765,0.2510); 0.3 > R -> (1,0,0,1) packed f16 -> base 2 = 9.0 -s_load_dwordx8 s[8:15], s[0:1], 0x0 -s_waitcnt lgkmcnt(0) -; r: image_gather4_c_l (literal S#, LESS) -s_mov_b32 s16, 0x1092 -s_mov_b32 s17, 0 -s_mov_b32 s18, 0 -s_mov_b32 s19, 0 -v_mov_b32_e32 v20, 0x3ee66666 -v_mov_b32_e32 v21, 0.5 -v_mov_b32_e32 v22, 0.5 -v_mov_b32_e32 v23, 0 -image_gather4_c_l v[8:11], v[20:23], s[8:15], s[16:19] dmask:0x1 dim:SQ_RSRC_IMG_2D -s_waitcnt vmcnt(0) -v_fma_f32 v16, v8, 2.0, v9 -v_fma_f32 v16, v16, 2.0, v10 -v_fma_f32 v4, v16, 2.0, v11 -; g: image_gather4_c_l_o (run-time S# word 0 loaded from descriptor heap, GREATER_EQUAL, offset x=+2) -s_load_dword s16, s[0:1], 0x20 -s_waitcnt lgkmcnt(0) -s_or_b32 s16, s16, 0x6000 -v_mov_b32_e32 v19, 2 -v_mov_b32_e32 v20, 0x3f333333 -v_mov_b32_e32 v21, 0.5 -v_mov_b32_e32 v22, 0.5 -v_mov_b32_e32 v23, 0 -image_gather4_c_l_o v[8:11], v[19:23], s[8:15], s[16:19] dmask:0x1 dim:SQ_RSRC_IMG_2D -s_waitcnt vmcnt(0) -v_fma_f32 v16, v8, 2.0, v9 -v_fma_f32 v16, v16, 2.0, v10 -v_fma_f32 v5, v16, 2.0, v11 -; b: image_gather4_cl (dmask:0x2 G channel, clamp=0.0) -s_mov_b32 s16, 0x92 -v_mov_b32_e32 v20, 0.5 -v_mov_b32_e32 v21, 0.5 -v_mov_b32_e32 v22, 0 -image_gather4_cl v[8:11], v[20:22], s[8:15], s[16:19] dmask:0x2 dim:SQ_RSRC_IMG_2D -s_waitcnt vmcnt(0) -v_mul_f32 v8, 0x40ff0000, v8 -v_rndne_f32 v8, v8 -v_mul_f32 v9, 0x40ff0000, v9 -v_rndne_f32 v9, v9 -v_mul_f32 v10, 0x40ff0000, v10 -v_rndne_f32 v10, v10 -v_mul_f32 v11, 0x40ff0000, v11 -v_rndne_f32 v11, v11 -v_fma_f32 v16, v8, 0x41800000, v9 -v_fma_f32 v16, v16, 0x41800000, v10 -v_fma_f32 v6, v16, 0x41800000, v11 -; a: image_gather4_c_b_cl_o d16 (literal S#, GREATER, offset x=-1, bias=0, ref=0.3, clamp=0) -s_mov_b32 s16, 0x4092 -v_mov_b32_e32 v18, 0x3f -v_mov_b32_e32 v19, 0 -v_mov_b32_e32 v20, 0x3e99999a -v_mov_b32_e32 v21, 0.5 -v_mov_b32_e32 v22, 0.5 -v_mov_b32_e32 v23, 0 -image_gather4_c_b_cl_o v[8:9], v[18:23], s[8:15], s[16:19] dmask:0x1 dim:SQ_RSRC_IMG_2D d16 -s_waitcnt vmcnt(0) -v_cvt_f32_f16_e32 v12, v8 -v_lshrrev_b32_e32 v8, 16, v8 -v_cvt_f32_f16_e32 v13, v8 -v_cvt_f32_f16_e32 v14, v9 -v_lshrrev_b32_e32 v9, 16, v9 -v_cvt_f32_f16_e32 v15, v9 -v_fma_f32 v16, v12, 2.0, v13 -v_fma_f32 v16, v16, 2.0, v14 -v_fma_f32 v7, v16, 2.0, v15 -exp mrt0 v4, v5, v6, v7 done vm -s_endpgm diff --git a/runtime/test/shaders/ps_gather_border.asm b/runtime/test/shaders/ps_gather_border.asm deleted file mode 100644 index 63c7d988d..000000000 --- a/runtime/test/shaders/ps_gather_border.asm +++ /dev/null @@ -1,101 +0,0 @@ -; image_gather4_l_o under the S# border address modes (SHADER-348): 6 clamp border, 7 mirror once border. The 2x2 footprint -; is four OpImageFetch, so a tap outside the image takes the S# border colour's channel instead of a texel: -; BORDER_COLOR_TYPE = S# word 3 [31:30], 0 transparent black, 1 opaque black, 2 opaque white (Mesa gfx10-rsrc.json for -; the field, SQ_TEX_BORDER_COLOR_* in gfx6.json for the values). Word 3 keeps BORDER_COLOR_PTR = 0x100 so it stays an -; integer literal (0x80000000 alone is the inline float -2.0, which the translator reads at run time). -; Cases r and g use a literal S#; b and a add 0 to s16 and s19 first, so mode and border type are read at run time. -; Run: vk_texture_test out.raw 0 92 c00000 14500000 0 -> RGBA32F pixels, all the same. -; The harness image is the 8x8 gradient R = 32x/255, G = 32y/255 (as in ps_gather_wrap). u = v = 0.5 puts the footprint's -; lower corner at texel (3, 3), moved by the signed 6-bit texel offset in the first address dword (x [5:0], y [13:8]). -; Each tap is scaled by 255/32 and rounded, so a texel gives its column (R) or row (G) and a border of 1.0 gives 8; the -; four taps, in gather order (x0,y1) (x1,y1) (x1,y0) (x0,y0), are packed in base 16 (exact in f32). -; r: modes 6,6, opaque white, R, offset x -4: x0 = -1 (out: 8), x1 = 0 -> (8,0,0,8) = 32776 -; g: modes 6,6, opaque white, G, offset y +4: y0 = 7, y1 = 8 (out: 8) -> (8,8,7,7) = 34935 -; b: modes 7,7 at run time, opaque white, R, offset x -12: x0 = -9 mirrors to 8 (out: 8), x1 = -8 mirrors to 7 -; -> (8,7,7,8) = 34680 -; a: modes 6,6 at run time, transparent black, R, offset x +4: x0 = 7, x1 = 8 (out: 0) -> (7,0,0,7) = 28679 -; Clamp to edge (the run-time treatment of modes 6 and 7 before) gives (0,0,0,0), (7,7,7,7), (0,0,0,0) and (7,7,7,7): -; every case differs. -v_mov_b32_e32 v21, 0.5 -v_mov_b32_e32 v22, 0.5 -v_mov_b32_e32 v23, 0 -s_load_dwordx8 s[8:15], s[0:1], 0x0 -s_waitcnt lgkmcnt(0) -s_mov_b32 s16, 0x36 -s_mov_b32 s17, 0 -s_mov_b32 s18, 0 -s_mov_b32 s19, 0x80000100 -v_mov_b32 v20, 0x3c -image_gather4_l_o v[8:11], v[20:23], s[8:15], s[16:19] dmask:0x1 dim:SQ_RSRC_IMG_2D -s_waitcnt vmcnt(0) -v_mul_f32 v8, 0x40ff0000, v8 -v_rndne_f32 v8, v8 -v_mul_f32 v9, 0x40ff0000, v9 -v_rndne_f32 v9, v9 -v_mul_f32 v10, 0x40ff0000, v10 -v_rndne_f32 v10, v10 -v_mul_f32 v11, 0x40ff0000, v11 -v_rndne_f32 v11, v11 -v_fma_f32 v16, v8, 0x41800000, v9 -v_fma_f32 v16, v16, 0x41800000, v10 -v_fma_f32 v4, v16, 0x41800000, v11 -s_mov_b32 s16, 0x36 -s_mov_b32 s17, 0 -s_mov_b32 s18, 0 -s_mov_b32 s19, 0x80000100 -v_mov_b32 v20, 0x400 -image_gather4_l_o v[8:11], v[20:23], s[8:15], s[16:19] dmask:0x2 dim:SQ_RSRC_IMG_2D -s_waitcnt vmcnt(0) -v_mul_f32 v8, 0x40ff0000, v8 -v_rndne_f32 v8, v8 -v_mul_f32 v9, 0x40ff0000, v9 -v_rndne_f32 v9, v9 -v_mul_f32 v10, 0x40ff0000, v10 -v_rndne_f32 v10, v10 -v_mul_f32 v11, 0x40ff0000, v11 -v_rndne_f32 v11, v11 -v_fma_f32 v16, v8, 0x41800000, v9 -v_fma_f32 v16, v16, 0x41800000, v10 -v_fma_f32 v5, v16, 0x41800000, v11 -s_mov_b32 s16, 0x3f -s_mov_b32 s17, 0 -s_mov_b32 s18, 0 -s_mov_b32 s19, 0x80000100 -s_add_u32 s16, s16, 0 -s_add_u32 s19, s19, 0 -v_mov_b32 v20, 0x34 -image_gather4_l_o v[8:11], v[20:23], s[8:15], s[16:19] dmask:0x1 dim:SQ_RSRC_IMG_2D -s_waitcnt vmcnt(0) -v_mul_f32 v8, 0x40ff0000, v8 -v_rndne_f32 v8, v8 -v_mul_f32 v9, 0x40ff0000, v9 -v_rndne_f32 v9, v9 -v_mul_f32 v10, 0x40ff0000, v10 -v_rndne_f32 v10, v10 -v_mul_f32 v11, 0x40ff0000, v11 -v_rndne_f32 v11, v11 -v_fma_f32 v16, v8, 0x41800000, v9 -v_fma_f32 v16, v16, 0x41800000, v10 -v_fma_f32 v6, v16, 0x41800000, v11 -s_mov_b32 s16, 0x36 -s_mov_b32 s17, 0 -s_mov_b32 s18, 0 -s_mov_b32 s19, 0x100 -s_add_u32 s16, s16, 0 -s_add_u32 s19, s19, 0 -v_mov_b32 v20, 0x4 -image_gather4_l_o v[8:11], v[20:23], s[8:15], s[16:19] dmask:0x1 dim:SQ_RSRC_IMG_2D -s_waitcnt vmcnt(0) -v_mul_f32 v8, 0x40ff0000, v8 -v_rndne_f32 v8, v8 -v_mul_f32 v9, 0x40ff0000, v9 -v_rndne_f32 v9, v9 -v_mul_f32 v10, 0x40ff0000, v10 -v_rndne_f32 v10, v10 -v_mul_f32 v11, 0x40ff0000, v11 -v_rndne_f32 v11, v11 -v_fma_f32 v16, v8, 0x41800000, v9 -v_fma_f32 v16, v16, 0x41800000, v10 -v_fma_f32 v7, v16, 0x41800000, v11 -exp mrt0 v4, v5, v6, v7 done vm -s_endpgm diff --git a/runtime/test/shaders/ps_gather_sampler_lod.asm b/runtime/test/shaders/ps_gather_sampler_lod.asm deleted file mode 100644 index 765c35963..000000000 --- a/runtime/test/shaders/ps_gather_sampler_lod.asm +++ /dev/null @@ -1,20 +0,0 @@ -; In --two-mip mode the 128x128 base level has four colored quadrants and mip 1 is opaque cyan. -; Request LOD U across the draw. With max LOD 0.25 every pixel must use the base; -; with min LOD 0.75 every pixel must use mip 1. The misplaced half of the frame reveals a dropped bound. -; Each 2x2 gather footprint stays within its quadrant. Export the first tap of R, G, B and A. -v_interp_p1_f32_e32 v2, v0, attr0.x -v_interp_p2_f32_e32 v2, v1, attr0.x -v_interp_p1_f32_e32 v3, v0, attr0.y -v_interp_p2_f32_e32 v3, v1, attr0.y -v_mov_b32_e32 v4, v2 -v_mov_b32_e32 v1, 0 ; zero offset for the _l_o path used by the alpha gather -s_load_dwordx8 s[8:15], s[0:1], 0 -s_load_dwordx4 s[16:19], s[0:1], 0x20 -s_waitcnt lgkmcnt(0) -image_gather4_l v[8:11], v[2:4], s[8:15], s[16:19] dmask:0x1 dim:SQ_RSRC_IMG_2D -image_gather4_l v[12:15], v[2:4], s[8:15], s[16:19] dmask:0x2 dim:SQ_RSRC_IMG_2D -image_gather4_l v[16:19], v[2:4], s[8:15], s[16:19] dmask:0x4 dim:SQ_RSRC_IMG_2D -image_gather4_l_o v[20:23], v[1:4], s[8:15], s[16:19] dmask:0x8 dim:SQ_RSRC_IMG_2D -s_waitcnt vmcnt(0) -exp mrt0 v8, v12, v16, v20 done vm -s_endpgm diff --git a/runtime/test/shaders/ps_gather_wrap.asm b/runtime/test/shaders/ps_gather_wrap.asm deleted file mode 100644 index 10fa5e239..000000000 --- a/runtime/test/shaders/ps_gather_wrap.asm +++ /dev/null @@ -1,213 +0,0 @@ -; image_gather4_l_o at the image border under each S# address mode (SHADER-36). The 2x2 gather footprint is built from four -; OpImageFetch (core Vulkan has no explicit-LOD gather), so the translator runs every texel coordinate through the S#'s own -; CLAMP_X/CLAMP_Y. S# word0: CLAMP_X = [2:0], CLAMP_Y = [5:3]; 0 wrap, 1 mirror, 2 clamp to last texel, 3 mirror once -; (Mesa src/amd/registers/gfx10-rsrc.json for the fields, SQ_TEX_* in gfx6.json for the values, as RADV's radv_tex_wrap maps Vulkan address modes onto them). Cases 1, 3, 5 use a literal S# -; (the translator reads the mode at translation time); cases 2, 4, 6 add 0 to s16 first, so the mode is read from the SGPR -; at run time. -; Run: vk_texture_test out.raw 0 92 c00000 14500000 0 -> RGBA32F pixels, all the same. -; The T# is loaded from the heap as in ps_texture_sample; the harness image is the 8x8 gradient R = 32x/255, G = 32y/255, -; so the R gather returns texel columns and the G gather texel rows (x, y = 0..7). u = v = 0.5 is texel position (4.0, 4.0), -; the footprint's lower corner is (3, 3), moved by the signed 6-bit texel offset in the first address dword (x [5:0], y [13:8]). -; Gather order: (x0,y1) (x1,y1) (x1,y0) (x0,y0). Texel indices are scaled back by 255/32 and rounded, then packed in base 8, -; so every channel is an exact integer below 2^24. -; out.r: interior case x0=2 y0=5 (S# 0x12). R gather = 2 3 3 2 -> 1242, G gather = 6 6 5 5 -> 3501; -; 1242*4096 + 3501 = 5090733 (0x4dadad) -; out.g, out.b, out.a: two cases each as first*4096 + second; a case is ((x0'*8 + x1')*8 + y0')*8 + y1', x0' x1' y0' y1' -; being the texel indices the coordinates map to: -; case 1 W,M x0=-1 y0=7 : x -1->7 0->0 ; y 7->7 8->7 (mirror) -> (7,0,7,7) = 3647 -; case 2 M,W x0=7 y0=-12: x 7->7 8->7 ; y -12->4 -11->5 (wrap) -> (7,7,4,5) = 4069 -; case 3 C,O x0=-3 y0=-12: x 0,0 ; y once(-12)=11->7, once(-11)=10->7 -> (0,0,7,7) = 63 -; case 4 O,C x0=-2 y0=7 : x once(-2)=1, once(-1)=0 ; y clamp 7,8->7 -> (1,0,7,7) = 575 -; case 5 M,O x0=20 y0=-1 : x 20 mod 16=4->4, 21->5 ; y once(-1)=0, 0->0 -> (4,5,0,0) = 2368 -; case 6 W,M x0=13 y0=-12: x 13->5, 14->6 ; y -12 mod 16=4->4, -11->5 -> (5,6,4,5) = 2981 -; out.g = 3647*4096 + 4069 = 14942181 (0xe3ffe5); out.b = 63*4096 + 575 = 258623 (0x3f23f); -; out.a = 2368*4096 + 2981 = 9702309 (0x940ba5) -; A clamp-to-edge gather gives 0,0,7,7 for case 1 (x: -1,0 -> 0,0), so the cases tell wrap, mirror and mirror-once from clamp. -v_mov_b32_e32 v21, 0.5 -v_mov_b32_e32 v22, 0.5 -v_mov_b32_e32 v23, 0 -s_load_dwordx8 s[8:15], s[0:1], 0x0 -s_waitcnt lgkmcnt(0) -s_mov_b32 s16, 0x12 -s_mov_b32 s17, 0 -s_mov_b32 s18, 0 -s_mov_b32 s19, 0 -v_mov_b32 v20, 0x23f -image_gather4_l_o v[8:11], v[20:23], s[8:15], s[16:19] dmask:0x1 dim:SQ_RSRC_IMG_2D -image_gather4_l_o v[12:15], v[20:23], s[8:15], s[16:19] dmask:0x2 dim:SQ_RSRC_IMG_2D -s_waitcnt vmcnt(0) -v_mul_f32 v8, 0x40ff0000, v8 -v_rndne_f32 v8, v8 -v_mul_f32 v9, 0x40ff0000, v9 -v_rndne_f32 v9, v9 -v_mul_f32 v10, 0x40ff0000, v10 -v_rndne_f32 v10, v10 -v_mul_f32 v11, 0x40ff0000, v11 -v_rndne_f32 v11, v11 -v_mul_f32 v12, 0x40ff0000, v12 -v_rndne_f32 v12, v12 -v_mul_f32 v13, 0x40ff0000, v13 -v_rndne_f32 v13, v13 -v_mul_f32 v14, 0x40ff0000, v14 -v_rndne_f32 v14, v14 -v_mul_f32 v15, 0x40ff0000, v15 -v_rndne_f32 v15, v15 -v_fma_f32 v16, v8, 8.0, v9 -v_fma_f32 v16, v16, 8.0, v10 -v_fma_f32 v16, v16, 8.0, v11 -v_fma_f32 v17, v12, 8.0, v13 -v_fma_f32 v17, v17, 8.0, v14 -v_fma_f32 v17, v17, 8.0, v15 -v_fma_f32 v4, v16, 0x45800000, v17 -s_mov_b32 s16, 0x8 -s_mov_b32 s17, 0 -s_mov_b32 s18, 0 -s_mov_b32 s19, 0 -v_mov_b32 v20, 0x43c -image_gather4_l_o v[8:11], v[20:23], s[8:15], s[16:19] dmask:0x1 dim:SQ_RSRC_IMG_2D -image_gather4_l_o v[12:15], v[20:23], s[8:15], s[16:19] dmask:0x2 dim:SQ_RSRC_IMG_2D -s_waitcnt vmcnt(0) -v_mul_f32 v8, 0x40ff0000, v8 -v_rndne_f32 v8, v8 -v_mul_f32 v9, 0x40ff0000, v9 -v_rndne_f32 v9, v9 -v_mul_f32 v12, 0x40ff0000, v12 -v_rndne_f32 v12, v12 -v_mul_f32 v15, 0x40ff0000, v15 -v_rndne_f32 v15, v15 -v_fma_f32 v18, v8, 8.0, v9 -v_fma_f32 v18, v18, 8.0, v15 -v_fma_f32 v18, v18, 8.0, v12 -v_mov_b32 v19, v18 -s_mov_b32 s16, 0x1 -s_mov_b32 s17, 0 -s_mov_b32 s18, 0 -s_mov_b32 s19, 0 -s_add_u32 s16, s16, 0 -v_mov_b32 v20, 0x3104 -image_gather4_l_o v[8:11], v[20:23], s[8:15], s[16:19] dmask:0x1 dim:SQ_RSRC_IMG_2D -image_gather4_l_o v[12:15], v[20:23], s[8:15], s[16:19] dmask:0x2 dim:SQ_RSRC_IMG_2D -s_waitcnt vmcnt(0) -v_mul_f32 v8, 0x40ff0000, v8 -v_rndne_f32 v8, v8 -v_mul_f32 v9, 0x40ff0000, v9 -v_rndne_f32 v9, v9 -v_mul_f32 v12, 0x40ff0000, v12 -v_rndne_f32 v12, v12 -v_mul_f32 v15, 0x40ff0000, v15 -v_rndne_f32 v15, v15 -v_fma_f32 v18, v8, 8.0, v9 -v_fma_f32 v18, v18, 8.0, v15 -v_fma_f32 v18, v18, 8.0, v12 -v_mov_b32 v24, v18 -v_fma_f32 v5, v19, 0x45800000, v24 -s_mov_b32 s16, 0x1a -s_mov_b32 s17, 0 -s_mov_b32 s18, 0 -s_mov_b32 s19, 0 -v_mov_b32 v20, 0x313a -image_gather4_l_o v[8:11], v[20:23], s[8:15], s[16:19] dmask:0x1 dim:SQ_RSRC_IMG_2D -image_gather4_l_o v[12:15], v[20:23], s[8:15], s[16:19] dmask:0x2 dim:SQ_RSRC_IMG_2D -s_waitcnt vmcnt(0) -v_mul_f32 v8, 0x40ff0000, v8 -v_rndne_f32 v8, v8 -v_mul_f32 v9, 0x40ff0000, v9 -v_rndne_f32 v9, v9 -v_mul_f32 v12, 0x40ff0000, v12 -v_rndne_f32 v12, v12 -v_mul_f32 v15, 0x40ff0000, v15 -v_rndne_f32 v15, v15 -v_fma_f32 v18, v8, 8.0, v9 -v_fma_f32 v18, v18, 8.0, v15 -v_fma_f32 v18, v18, 8.0, v12 -v_mov_b32 v19, v18 -s_mov_b32 s16, 0x13 -s_mov_b32 s17, 0 -s_mov_b32 s18, 0 -s_mov_b32 s19, 0 -s_add_u32 s16, s16, 0 -v_mov_b32 v20, 0x43b -image_gather4_l_o v[8:11], v[20:23], s[8:15], s[16:19] dmask:0x1 dim:SQ_RSRC_IMG_2D -image_gather4_l_o v[12:15], v[20:23], s[8:15], s[16:19] dmask:0x2 dim:SQ_RSRC_IMG_2D -s_waitcnt vmcnt(0) -v_mul_f32 v8, 0x40ff0000, v8 -v_rndne_f32 v8, v8 -v_mul_f32 v9, 0x40ff0000, v9 -v_rndne_f32 v9, v9 -v_mul_f32 v12, 0x40ff0000, v12 -v_rndne_f32 v12, v12 -v_mul_f32 v15, 0x40ff0000, v15 -v_rndne_f32 v15, v15 -v_fma_f32 v18, v8, 8.0, v9 -v_fma_f32 v18, v18, 8.0, v15 -v_fma_f32 v18, v18, 8.0, v12 -v_mov_b32 v24, v18 -v_fma_f32 v6, v19, 0x45800000, v24 -s_mov_b32 s16, 0x19 -s_mov_b32 s17, 0 -s_mov_b32 s18, 0 -s_mov_b32 s19, 0 -v_mov_b32 v20, 0x3c11 -image_gather4_l_o v[8:11], v[20:23], s[8:15], s[16:19] dmask:0x1 dim:SQ_RSRC_IMG_2D -image_gather4_l_o v[12:15], v[20:23], s[8:15], s[16:19] dmask:0x2 dim:SQ_RSRC_IMG_2D -s_waitcnt vmcnt(0) -v_mul_f32 v8, 0x40ff0000, v8 -v_rndne_f32 v8, v8 -v_mul_f32 v9, 0x40ff0000, v9 -v_rndne_f32 v9, v9 -v_mul_f32 v12, 0x40ff0000, v12 -v_rndne_f32 v12, v12 -v_mul_f32 v15, 0x40ff0000, v15 -v_rndne_f32 v15, v15 -v_fma_f32 v18, v8, 8.0, v9 -v_fma_f32 v18, v18, 8.0, v15 -v_fma_f32 v18, v18, 8.0, v12 -v_mov_b32 v19, v18 -s_mov_b32 s16, 0x8 -s_mov_b32 s17, 0 -s_mov_b32 s18, 0 -s_mov_b32 s19, 0 -s_add_u32 s16, s16, 0 -v_mov_b32 v20, 0x310a -image_gather4_l_o v[8:11], v[20:23], s[8:15], s[16:19] dmask:0x1 dim:SQ_RSRC_IMG_2D -image_gather4_l_o v[12:15], v[20:23], s[8:15], s[16:19] dmask:0x2 dim:SQ_RSRC_IMG_2D -s_waitcnt vmcnt(0) -v_mul_f32 v8, 0x40ff0000, v8 -v_rndne_f32 v8, v8 -v_mul_f32 v9, 0x40ff0000, v9 -v_rndne_f32 v9, v9 -v_mul_f32 v12, 0x40ff0000, v12 -v_rndne_f32 v12, v12 -v_mul_f32 v15, 0x40ff0000, v15 -v_rndne_f32 v15, v15 -v_fma_f32 v18, v8, 8.0, v9 -v_fma_f32 v18, v18, 8.0, v15 -v_fma_f32 v18, v18, 8.0, v12 -v_mov_b32 v24, v18 -v_fma_f32 v7, v19, 0x45800000, v24 -; At UV (0.5,0.5), gather red from x=3,4 at LOD zero: the four bytes are (96,128,128,96). -; Gather green with offset (0,-1): (96,96,64,64). As binary16, 64/255 = 0x3404, -; 96/255 = 0x3606 and 128/255 = 0x3804. Each gather must write just two packed VGPRs. -v_mov_b32 v19, 0x3f00 -v_mov_b32 v20, 0.5 -v_mov_b32 v21, 0.5 -v_mov_b32 v22, 0 -v_mov_b32 v10, 0 -v_mov_b32 v14, 0 -image_gather4_l v[8:9], v[20:22], s[8:15], s[16:19] dmask:0x1 dim:SQ_RSRC_IMG_2D d16 -image_gather4_l_o v[12:13], v[19:22], s[8:15], s[16:19] dmask:0x2 dim:SQ_RSRC_IMG_2D d16 -s_waitcnt vmcnt(0) -v_xor_b32 v8, 0x38043606, v8 -v_xor_b32 v9, 0x36063804, v9 -v_or_b32 v8, v8, v9 -v_or_b32 v8, v8, v10 -v_cmp_eq_u32_e32 vcc_lo, 0, v8 -v_cndmask_b32_e32 v4, 0, v4, vcc_lo -v_xor_b32 v12, 0x36063606, v12 -v_xor_b32 v13, 0x34043404, v13 -v_or_b32 v12, v12, v13 -v_or_b32 v12, v12, v14 -v_cmp_eq_u32_e32 vcc_lo, 0, v12 -v_cndmask_b32_e32 v5, 0, v5, vcc_lo -exp mrt0 v4, v5, v6, v7 done vm -s_endpgm diff --git a/runtime/test/shaders/ps_get_lod.asm b/runtime/test/shaders/ps_get_lod.asm deleted file mode 100644 index acc31f905..000000000 --- a/runtime/test/shaders/ps_get_lod.asm +++ /dev/null @@ -1,32 +0,0 @@ -; image_get_lod: the LOD an implicit sample at these coordinates would use. RDNA2 ISA (MIMG): the result is -; {rawLOD, clampedLOD} in VGPRs 1..0, so the first register gets the clamped LOD (after the sampler's and the image's -; limits) and the second the calculated one before any clamp; dmask keeps one or both, packed. -; Run: vk_texture_test vs_ids.spv ps_get_lod.spv out.raw 0 92 14500000 0 --two-mip, twice. -; --two-mip draws 64x64 pixels over a 128x128 texture that has two levels, and vs_ids runs u and v from 0 to 1 over -; the image, so a pixel step is two texels each way: the calculated LOD is log2(2) = 1. The second and third query -; scale u by 4: eight texels a pixel along x, two along y, and the larger one counts: log2(8) = 3, which no level -; of this image reaches, so its clamped LOD stops at the last level, 1. The S# is read from the heap behind the T#; -; its word 1 holds MIN_LOD [11:0] and MAX_LOD [23:12] in 4.8 fixed point, and its mip filter is point (word 2). -; mrt0 = (clamped LOD, calculated LOD at (u, v); calculated LOD alone at (4u, v); clamped LOD alone at (4u, v)) -; S# word 1 = 0xc00000 (LOD 0..12): 1.0 1.0 3.0 1.0 -; S# word 1 = 0x40000 (LOD 0..0.25): 0.0 1.0 3.0 0.0 MAX_LOD limits the clamped LOD to 0.25, and a point-filtered -; sample at 0.25 uses level 0; the calculated LOD is not limited -; Every pixel must hold these within 1/16 (a device may keep as few as four fraction bits of LOD). -; The second range is not 0..0: Mesa llvmpipe 26.3.1 does not apply a sampler whose minimum and maximum LOD are equal -; to an LOD query (it gives 1.0 there, where RADV gives 0.0), which says nothing about the translation. -; Not shown by this test: u and v taken in the wrong order. The texture is square, where the LOD is the same either way. -v_interp_p1_f32_e32 v2, v0, attr0.x -v_interp_p2_f32_e32 v2, v1, attr0.x -v_interp_p1_f32_e32 v3, v0, attr0.y -v_interp_p2_f32_e32 v3, v1, attr0.y -s_load_dwordx8 s[8:15], s[0:1], 0 -s_load_dwordx4 s[16:19], s[0:1], 0x20 -s_waitcnt lgkmcnt(0) -image_get_lod v[4:5], v[2:3], s[8:15], s[16:19] dmask:0x3 dim:SQ_RSRC_IMG_2D -v_mul_f32_e32 v8, 4.0, v2 -v_mov_b32_e32 v9, v3 -image_get_lod v6, v[8:9], s[8:15], s[16:19] dmask:0x2 dim:SQ_RSRC_IMG_2D -image_get_lod v7, v[8:9], s[8:15], s[16:19] dmask:0x1 dim:SQ_RSRC_IMG_2D -s_waitcnt vmcnt(0) -exp mrt0 v4, v5, v6, v7 done vm -s_endpgm diff --git a/runtime/test/shaders/ps_get_lod_array.asm b/runtime/test/shaders/ps_get_lod_array.asm deleted file mode 100644 index d07fc23bf..000000000 --- a/runtime/test/shaders/ps_get_lod_array.asm +++ /dev/null @@ -1,27 +0,0 @@ -; image_get_lod on a 2D array (dim:SQ_RSRC_IMG_2D_ARRAY: s, t and the slice; ps_get_lod.asm has the plain 2D form and -; the rules). The slice takes no part in the LOD. -; Run: vk_texture_test vs_ids.spv ps_get_lod_array.spv out.raw 0 92 c00000 14500000 0 -; The tool's 2D array (set 0 binding 3) is 8x8 with one level, drawn over 64x64 pixels with u and v from 0 to 1: a -; pixel step is 1/8 texel, so the calculated LOD is log2(1/8) = -3. The first query scales u by 32: four texels a -; pixel along x, log2(4) = 2. With a single level the clamped LOD is 0 for both. -; mrt0 = (clamped, calculated LOD at (32u, v); clamped, calculated LOD at (u, v)) = 0.0 2.0 0.0 -3.0 -; on every pixel, within 1/16 (a device may keep as few as four fraction bits of LOD). -v_interp_p1_f32_e32 v2, v0, attr0.x -v_interp_p2_f32_e32 v2, v1, attr0.x -v_interp_p1_f32_e32 v3, v0, attr0.y -v_interp_p2_f32_e32 v3, v1, attr0.y -v_mov_b32_e32 v4, 2.0 -s_load_dwordx8 s[8:15], s[0:1], 0 -s_waitcnt lgkmcnt(0) -s_mov_b32 s16, 0x92 -s_mov_b32 s17, 0xc00000 -s_mov_b32 s18, 0x14500000 -s_mov_b32 s19, 0 -v_mul_f32_e32 v8, 0x42000000, v2 -v_mov_b32_e32 v9, v3 -v_mov_b32_e32 v10, v4 -image_get_lod v[12:13], v[8:10], s[8:15], s[16:19] dmask:0x3 dim:SQ_RSRC_IMG_2D_ARRAY -image_get_lod v[14:15], v[2:4], s[8:15], s[16:19] dmask:0x3 dim:SQ_RSRC_IMG_2D_ARRAY -s_waitcnt vmcnt(0) -exp mrt0 v12, v13, v14, v15 done vm -s_endpgm diff --git a/runtime/test/shaders/ps_ij_computed.asm b/runtime/test/shaders/ps_ij_computed.asm deleted file mode 100644 index 70fe9d26d..000000000 --- a/runtime/test/shaders/ps_ij_computed.asm +++ /dev/null @@ -1,28 +0,0 @@ -; SHADER-177: interpolation through a barycentric pair the program computed. Drawn with vs_ids -; (attr0 = (u, v, 0, 1), u = 2i and v = 2j running 0..1 over the image). -; Hardware weights v_interp with the values the operand registers hold (Vonsek's #1224 rows: zeroed -; sources interpolate to P0, swapped copies to (v,u)); the translator now models the computed pair: -; mrt0.x = attr0.x with I' = J' = 0.25 -> the snapped point 0.5 * P0 + 0.25 * P1 + 0.25 * P2 = 0.5 -; mrt0.y = attr0.y with I' = J' = 0 -> the provoking vertex's value, 0.0 -; mrt0.z = attr0.y with I' = i, J' = j/2 -> v / 2 = (y + 0.5) / 128 (evaluate-at-half-offset in j) -; mrt0.w = mrt0.x again (control) -; On main (operand ignored) this rendered (u, v, v, 0.5): x, y and z wrong on 4,096 of 4,096 pixels. -; No integer-bits row here: attr1's words are f32 denormals, which the weighting arithmetic may flush -; (the mov path keeps them exact; that is ps_flat's). Run: vk_harness vs_ids.spv ps_ij_computed.spv out.raw -v_mov_b32_e32 v10, v0 -v_mov_b32_e32 v11, v1 -v_mov_b32_e32 v0, 0.25 -v_mov_b32_e32 v1, 0.25 -v_interp_p1_f32_e32 v2, v0, attr0.x -v_interp_p2_f32_e32 v2, v1, attr0.x -v_mov_b32_e32 v0, 0 -v_mov_b32_e32 v1, 0 -v_interp_p1_f32_e32 v3, v0, attr0.y -v_interp_p2_f32_e32 v3, v1, attr0.y -v_mul_f32_e32 v11, 0.5, v11 -v_mov_b32_e32 v0, v10 -v_mov_b32_e32 v1, v11 -v_interp_p1_f32_e32 v4, v0, attr0.y -v_interp_p2_f32_e32 v4, v1, attr0.y -exp mrt0 v2, v3, v4, v2 done vm -s_endpgm diff --git a/runtime/test/shaders/ps_imgatomic.asm b/runtime/test/shaders/ps_imgatomic.asm deleted file mode 100644 index b8f888c13..000000000 --- a/runtime/test/shaders/ps_imgatomic.asm +++ /dev/null @@ -1,44 +0,0 @@ -; Image atomics in a pixel shader, the forms the game uses (1,018 of its 1,038 image-atomic shaders are pixel shaders: -; image_atomic_or / umin / umax on a 2D image and umax on a 3D one), through the descriptor table and the set-0 -; r32ui storage arrays (binding 4 for 2D, 7 for 3D). User data s2:s3 is the console VA of a table of four T#s: -; +0x00 the 2D umax image, +0x20 the 2D umin image, +0x40 the 2D or image, +0x60 the 3D umax image (any 8 dwords: -; only the key matters). Each of the 64x64 pixels computes px, py from attr0 (vs_ids runs it 0..1 over the target), -; its id = px + 64 * py, and its texel tx = px >> 3, ty = py >> 3, so 64 pixels contend for each texel of the 8x8 -; images: -; umax2d[ty][tx] = max(id), umin2d[ty][tx] = min(id), or2d[ty][tx] |= 1 << (id & 31), -; umax3d[px & 3][ty >> 1][tx >> 1] = max(id) (a 4x4x4 image) -; After its atomics, every odd px is discarded (v_cmpx). The atomics of a pixel that is discarded afterwards still -; count, as on hardware: the expected values above are over all 4096 pixels. Even pixels export 1.0. -; Run: vk_bindless_test vs_ids.spv ps_imgatomic.spv (images cleared to 0, umin to 0xffffffff; checked per texel) -s_load_dwordx8 s[8:15], s[2:3], 0x0 -s_load_dwordx8 s[16:23], s[2:3], 0x20 -s_load_dwordx8 s[24:31], s[2:3], 0x40 -s_load_dwordx8 s[32:39], s[2:3], 0x60 -s_waitcnt lgkmcnt(0) -v_interp_p1_f32_e32 v2, v0, attr0.x -v_interp_p2_f32_e32 v2, v1, attr0.x -v_interp_p1_f32_e32 v3, v0, attr0.y -v_interp_p2_f32_e32 v3, v1, attr0.y -v_mul_f32_e32 v2, 0x42800000, v2 -v_mul_f32_e32 v3, 0x42800000, v3 -v_cvt_u32_f32_e32 v4, v2 -v_cvt_u32_f32_e32 v5, v3 -v_lshlrev_b32_e32 v6, 6, v5 -v_add_nc_u32_e32 v6, v6, v4 -v_lshrrev_b32_e32 v7, 3, v4 -v_lshrrev_b32_e32 v8, 3, v5 -image_atomic_umax v6, v[7:8], s[8:15] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm -image_atomic_umin v6, v[7:8], s[16:23] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm -v_and_b32_e32 v9, 31, v6 -v_lshlrev_b32_e64 v9, v9, 1 -image_atomic_or v9, v[7:8], s[24:31] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm -v_lshrrev_b32_e32 v10, 1, v7 -v_lshrrev_b32_e32 v11, 1, v8 -v_and_b32_e32 v12, 3, v4 -image_atomic_umax v6, v[10:12], s[32:39] dmask:0x1 dim:SQ_RSRC_IMG_3D unorm -s_waitcnt vmcnt(0) -v_and_b32_e32 v13, 1, v4 -v_cmpx_eq_u32_e32 0, v13 -v_mov_b32_e32 v14, 1.0 -exp mrt0 v14, v14, v14, v14 done vm -s_endpgm diff --git a/runtime/test/shaders/ps_interp_f16_high.asm b/runtime/test/shaders/ps_interp_f16_high.asm deleted file mode 100644 index c9ef3ee33..000000000 --- a/runtime/test/shaders/ps_interp_f16_high.asm +++ /dev/null @@ -1,14 +0,0 @@ -; 16-bit interpolation of both halves of a packed channel, drawn with vs_f16_pack (param0.x = u | v << 16, -; param0.y = v | u << 16). Without `high` v_interp_p1ll_f16 / v_interp_p2_f16 read the low half, with it the high -; half (Mesa ACO emit_interp_instr passes high_16bits to both). The low halves of mrt0.xyz must be f16 of u, v and -; u at the pixel centre, and mrt0.w the f32 v interpolated from attr1.y (control). -v_interp_p1ll_f16 v2, v0, attr0.x -v_interp_p2_f16 v2, v1, attr0.x, v2 -v_interp_p1ll_f16 v3, v0, attr0.x high -v_interp_p2_f16 v3, v1, attr0.x, v3 high -v_interp_p1ll_f16 v4, v0, attr0.y high -v_interp_p2_f16 v4, v1, attr0.y, v4 high -v_interp_p1_f32_e32 v5, v0, attr1.y -v_interp_p2_f32_e32 v5, v1, attr1.y -exp mrt0 v2, v3, v4, v5 done vm -s_endpgm diff --git a/runtime/test/shaders/ps_interp_f32_mods.asm b/runtime/test/shaders/ps_interp_f32_mods.asm deleted file mode 100644 index 64a56ee5d..000000000 --- a/runtime/test/shaders/ps_interp_f32_mods.asm +++ /dev/null @@ -1,17 +0,0 @@ -; regen_fixtures: this source has a translator fixture in tests/semantic/fixtures/disasm -; VOP3 output modifiers on v_interp_p2_f32_e64 (docs/design.md "v_fmac_f16, v_interp_p2/mov_f32 output modifiers"), -; omod before clamp. Drawn with vs_interp_consts: attr0 = (1.5, -0.25, 0.375, 0.625) at every pixel. -; x: clamp(1.5) = 1.0; y: clamp(-0.25) = 0.0; z: 0.375 mul:2 = 0.75; w: 0.625 mul:2 = 1.25, clamp: 1.0 -; (clamping before the multiply would give 1.25) -; Run: vk_harness vs_interp_consts.spv ps_interp_f32_mods.spv out.raw -; Expected mrt0 bits: 0x3f800000, 0x00000000, 0x3f400000, 0x3f800000 -v_interp_p1_f32_e32 v2, v0, attr0.x -v_interp_p2_f32_e64 v2, v1, attr0.x clamp -v_interp_p1_f32_e32 v3, v0, attr0.y -v_interp_p2_f32_e64 v3, v1, attr0.y clamp -v_interp_p1_f32_e32 v4, v0, attr0.z -v_interp_p2_f32_e64 v4, v1, attr0.z mul:2 -v_interp_p1_f32_e32 v5, v0, attr0.w -v_interp_p2_f32_e64 v5, v1, attr0.w clamp mul:2 -exp mrt0 v2, v3, v4, v5 done vm -s_endpgm diff --git a/runtime/test/shaders/ps_interp_mov_mods.asm b/runtime/test/shaders/ps_interp_mov_mods.asm deleted file mode 100644 index 501b8868f..000000000 --- a/runtime/test/shaders/ps_interp_mov_mods.asm +++ /dev/null @@ -1,16 +0,0 @@ -; regen_fixtures: this source has a translator fixture in tests/semantic/fixtures/disasm -; VOP3 output modifiers on v_interp_p2_f32_e64 and v_interp_mov_f32_e64 (docs/design.md "v_fmac_f16, -; v_interp_p2/mov_f32 output modifiers"). Drawn with vs_interp_consts: attr2 = (0.25, 3.0, 0, 0) interpolated, -; attr1 = (1.5, -0.5, 0.25, 4.0) read only with v_interp_mov (so its location is Flat). -; x: interp 0.25 mul:4 = 1.0; y: interp 3.0 div:2 = 1.5; z: mov 4.0 div:2 = 2.0; -; w: mov 1.5 div:2 = 0.75, then clamp (clamping first would give 0.5) -; Run: vk_harness vs_interp_consts.spv ps_interp_mov_mods.spv out.raw -; Expected mrt0 bits: 0x3f800000, 0x3fc00000, 0x40000000, 0x3f400000 -v_interp_p1_f32_e32 v2, v0, attr2.x -v_interp_p2_f32_e64 v2, v1, attr2.x mul:4 -v_interp_p1_f32_e32 v3, v0, attr2.y -v_interp_p2_f32_e64 v3, v1, attr2.y div:2 -v_interp_mov_f32_e64 v4, p0, attr1.w div:2 -v_interp_mov_f32_e64 v5, p0, attr1.x clamp div:2 -exp mrt0 v2, v3, v4, v5 done vm -s_endpgm diff --git a/runtime/test/shaders/ps_legacy_mul.asm b/runtime/test/shaders/ps_legacy_mul.asm deleted file mode 100644 index 334e83c41..000000000 --- a/runtime/test/shaders/ps_legacy_mul.asm +++ /dev/null @@ -1,16 +0,0 @@ -; regen_fixtures: this source has a translator fixture in tests/semantic/fixtures/disasm -; v_mul_legacy_f32: 0 * anything (inf, -inf, NaN) == 0, finite * finite == normal multiply. -; Expected mrt0 bits: 0, 0, 0, 0x40c00000 -v_mov_b32 v0, 0 -v_mov_b32 v1, 0x80000000 -v_mov_b32 v2, 0x7f800000 -v_mov_b32 v3, 0xff800000 -v_mov_b32 v4, 0x7fc00000 -v_mov_b32 v5, 2.0 -v_mov_b32 v6, 3.0 -v_mul_legacy_f32 v7, v0, v2 -v_mul_legacy_f32 v8, v0, v4 -v_mul_legacy_f32 v9, v1, v3 -v_mul_legacy_f32 v10, v5, v6 -exp mrt0 v7, v8, v9, v10 done vm -s_endpgm diff --git a/runtime/test/shaders/ps_live_width.asm b/runtime/test/shaders/ps_live_width.asm deleted file mode 100644 index ee02e4bf7..000000000 --- a/runtime/test/shaders/ps_live_width.asm +++ /dev/null @@ -1,11 +0,0 @@ -; The live width of the pixel stage: how many invocations of a fragment subgroup are alive, as the shader's own EXEC -; shows it (the translator makes EXEC the subgroup ballot of the live invocations). Every pixel writes -; popcount(exec_lo) to all four words of mrt0, so the largest word of the frame is the width a full subgroup has. -; It is not gl_SubgroupSize: a driver can report 32 and run 16 invocations (Intel UHD 770: reported 32, 16 live, -; lane ids 0..15; a read of lane L ^ 16 returns garbage), and w64_graphics.py skips the pixel fixtures that need -; 32 live lanes on a device that measures less. -; Run: vk_harness vs_ids.spv ps_live_width.spv out.raw; it is a probe, no expected words. -s_bcnt1_i32_b32 s4, exec_lo -v_mov_b32_e32 v2, s4 -exp mrt0 v2, v2, v2, v2 done vm -s_endpgm diff --git a/runtime/test/shaders/ps_m15.asm b/runtime/test/shaders/ps_m15.asm deleted file mode 100644 index 4c924a72f..000000000 --- a/runtime/test/shaders/ps_m15.asm +++ /dev/null @@ -1,36 +0,0 @@ -; M1.5 pixel shader: interpolates param0 (a colour), scales it by four floats that sit in the shader's own code -; blob and are read through the code base (s_getpc_b64), and adds a root constant. Run: d3d12_translated_draw_test. -; -; The first instruction is s_getpc_b64, so the address it returns is the blob's code base + 4 (the push-constant -; code base, dwords 34-35, is the console VA of the FSSM program the layer uploaded). The table of four floats is at -; blob offset 0x100: 0x100 - 4 = 0xfc. build.py writes that blob (fssm-at / fssm-data below) next to the SPIR-V, and -; adds its SHA-256 to the index, as the translator's --fssm-dir does for the game's programs. -; scale = (0.5, 2.0, 1.0, 1.0) s4 = bias, a float from the root constants (s2, s3 are the VS offset) -; mrt0 = (r * 0.5 + bias, g * 2.0 + bias, b * 1.0 + bias, a * 1.0) -; The test draws colour (0.25, 0.5, 0.75, 1) with bias 0 and 0.125, and colour (1, 0, 0.5, 1) with bias 0.25. Every -; value is a short binary fraction, so the float render target holds the exact result, bit for bit: -; (0.25, 0.5, 0.75, 1) bias 0 -> (0.125, 1.0, 0.75, 1) -; (0.25, 0.5, 0.75, 1) bias 0.125 -> (0.25, 1.125, 0.875, 1) -; (1.0, 0.0, 0.5, 1) bias 0.25 -> (0.75, 0.25, 0.75, 1) -; The header of vs_m15.asm describes the vertex data; runtime/test/d3d12_translated_draw_test.cpp the three draws. -; fssm-at: 0x100 -; fssm-data: 0x3f000000 0x40000000 0x3f800000 0x3f800000 -s_getpc_b64 s[6:7] -s_add_u32 s6, s6, 0xfc -s_addc_u32 s7, s7, 0 -s_load_dwordx4 s[8:11], s[6:7], 0x0 -v_interp_p1_f32_e32 v2, v0, attr0.x -v_interp_p2_f32_e32 v2, v1, attr0.x -v_interp_p1_f32_e32 v3, v0, attr0.y -v_interp_p2_f32_e32 v3, v1, attr0.y -v_interp_p1_f32_e32 v4, v0, attr0.z -v_interp_p2_f32_e32 v4, v1, attr0.z -v_interp_p1_f32_e32 v5, v0, attr0.w -v_interp_p2_f32_e32 v5, v1, attr0.w -s_waitcnt lgkmcnt(0) -v_fma_f32 v2, v2, s8, s4 -v_fma_f32 v3, v3, s9, s4 -v_fma_f32 v4, v4, s10, s4 -v_mul_f32_e32 v5, s11, v5 -exp mrt0 v2, v3, v4, v5 done vm -s_endpgm diff --git a/runtime/test/shaders/ps_m2.asm b/runtime/test/shaders/ps_m2.asm deleted file mode 100644 index 0f23cefa3..000000000 --- a/runtime/test/shaders/ps_m2.asm +++ /dev/null @@ -1,20 +0,0 @@ -; M2 pixel shader: samples a texture found through two root descriptor tables. Run: d3d12_m2_textured_test. -; User data from the root signature ([0] a table holding one SRV, [1] a table holding one sampler): -; s[0:1] = console VA of the SRV table's first slot: the 32 bytes of the T# CreateShaderResourceView wrote -; s[2:3] = console VA of the sampler table's first slot: the 16 bytes of the S# CreateSampler wrote -; The translator hashes the T# and the S# the shader loads and looks both up in the descriptor hash table (set 0, -; binding 2); the indices pick the image (binding 0) and the sampler (binding 1) in the bindless set. -; attr0.xy = (u, v), 0..1 over the quad. mrt0 = the texel under the pixel. -; fssm-at: 0x10 -; fssm-data: 0x324d5350 0x20535020 -s_load_dwordx8 s[8:15], s[0:1], 0x0 -s_load_dwordx4 s[16:19], s[2:3], 0x0 -s_waitcnt lgkmcnt(0) -v_interp_p1_f32_e32 v2, v0, attr0.x -v_interp_p2_f32_e32 v2, v1, attr0.x -v_interp_p1_f32_e32 v3, v0, attr0.y -v_interp_p2_f32_e32 v3, v1, attr0.y -image_sample v[4:7], v[2:3], s[8:15], s[16:19] dmask:0xf dim:SQ_RSRC_IMG_2D -s_waitcnt vmcnt(0) -exp mrt0 v4, v5, v6, v7 done vm -s_endpgm diff --git a/runtime/test/shaders/ps_m2_array.asm b/runtime/test/shaders/ps_m2_array.asm deleted file mode 100644 index 96260bd0a..000000000 --- a/runtime/test/shaders/ps_m2_array.asm +++ /dev/null @@ -1,18 +0,0 @@ -; M2 pixel shader for a 2D array view: ps_m2.asm with dim:SQ_RSRC_IMG_2D_ARRAY and slice coordinate 1.0. Run: -; d3d12_m2_formats_test. User data as in ps_m2.asm ([0] a table holding one SRV, [1] a table holding one sampler). -; The slice is relative to the view: a view of slices 0..2 reads slice 1, a view of slices 1..2 reads slice 2. -; attr0.xy = (u, v), 0..1 over the quad. mrt0 = the texel under the pixel. -; fssm-at: 0x10 -; fssm-data: 0x324d5350 0x59525241 -s_load_dwordx8 s[8:15], s[0:1], 0x0 -s_load_dwordx4 s[16:19], s[2:3], 0x0 -s_waitcnt lgkmcnt(0) -v_interp_p1_f32_e32 v2, v0, attr0.x -v_interp_p2_f32_e32 v2, v1, attr0.x -v_interp_p1_f32_e32 v3, v0, attr0.y -v_interp_p2_f32_e32 v3, v1, attr0.y -v_mov_b32 v4, 1.0 -image_sample v[5:8], v[2:4], s[8:15], s[16:19] dmask:0xf dim:SQ_RSRC_IMG_2D_ARRAY -s_waitcnt vmcnt(0) -exp mrt0 v5, v6, v7, v8 done vm -s_endpgm diff --git a/runtime/test/shaders/ps_m2_literal.asm b/runtime/test/shaders/ps_m2_literal.asm deleted file mode 100644 index f77ef197f..000000000 --- a/runtime/test/shaders/ps_m2_literal.asm +++ /dev/null @@ -1,21 +0,0 @@ -; M2 literal sampler: ps_m2.asm with its S# built from immediates instead of loaded from the sampler table, as game -; shaders do (docs/design.md, Literal samplers): CLAMP_LAST_TEXEL on all axes, bilinear min/mag, point mip, MAX_LOD -; 12. No heap slot names this S#, so the layer registers it when a pipeline uses the shader; otherwise the shader's -; hash lookup finds the fallback sampler. Run: d3d12_m2_textured_test. -; s[0:1] = console VA of the SRV table's first slot (the T#). attr0.xy = (u, v). mrt0 = the sampled texel. -; fssm-at: 0x10 -; fssm-data: 0x324d5350 0x4c544c20 -s_load_dwordx8 s[8:15], s[0:1], 0x0 -s_movk_i32 s16, 0x92 -s_mov_b32 s17, 0xc00000 -s_mov_b32 s18, 0x14500000 -s_mov_b32 s19, 0 -s_waitcnt lgkmcnt(0) -v_interp_p1_f32_e32 v2, v0, attr0.x -v_interp_p2_f32_e32 v2, v1, attr0.x -v_interp_p1_f32_e32 v3, v0, attr0.y -v_interp_p2_f32_e32 v3, v1, attr0.y -image_sample v[4:7], v[2:3], s[8:15], s[16:19] dmask:0xf dim:SQ_RSRC_IMG_2D -s_waitcnt vmcnt(0) -exp mrt0 v4, v5, v6, v7 done vm -s_endpgm diff --git a/runtime/test/shaders/ps_m2_uoff.asm b/runtime/test/shaders/ps_m2_uoff.asm deleted file mode 100644 index 1c96f50d5..000000000 --- a/runtime/test/shaders/ps_m2_uoff.asm +++ /dev/null @@ -1,21 +0,0 @@ -; M2 sampler control: ps_m2.asm with 1.0 added to U immediately before image_sample. With U in range a CLAMP, a WRAP -; and the fallback sampler give the same pixels; with U + 1 the CLAMP sampler returns the last column and the WRAP one -; the same texel as without the offset, so the pixels tell which sampler the draw used. Idea and measurements by -; @Vonsek (#1489). Run: d3d12_m2_textured_test. -; The same unbounded SRV table stays bound across both draws. Root constants s4 and s5 hold -; the descriptor index and byte stride, respectively. -; fssm-at: 0x10 -; fssm-data: 0x324d5350 0x4f465520 -s_mul_i32 s20, s4, s5 -s_load_dwordx8 s[8:15], s[0:1], s20 -s_load_dwordx4 s[16:19], s[2:3], 0x0 -s_waitcnt lgkmcnt(0) -v_interp_p1_f32_e32 v2, v0, attr0.x -v_interp_p2_f32_e32 v2, v1, attr0.x -v_interp_p1_f32_e32 v3, v0, attr0.y -v_interp_p2_f32_e32 v3, v1, attr0.y -v_add_f32_e32 v2, 1.0, v2 -image_sample v[4:7], v[2:3], s[8:15], s[16:19] dmask:0xf dim:SQ_RSRC_IMG_2D -s_waitcnt vmcnt(0) -exp mrt0 v4, v5, v6, v7 done vm -s_endpgm diff --git a/runtime/test/shaders/ps_m3.asm b/runtime/test/shaders/ps_m3.asm deleted file mode 100644 index be2a59e2d..000000000 --- a/runtime/test/shaders/ps_m3.asm +++ /dev/null @@ -1,14 +0,0 @@ -; M3 pixel shader, pass 1: two render targets from root constants. Run: d3d12_m3_frame_test. -; User data (the root signature of vs_m3.asm, [0], eight 32-bit constants): s5, s6, s7 = c0, c1, c2 (floats, k/255). -; mrt0 = (c0, c1, c2, 1.0) an R8G8B8A8_UNORM target -; mrt1 = (c1 + c2) an R32_FLOAT target: one float add, so the CPU gets the same bits -; fssm-at: 0x10 -; fssm-data: 0x33535350 0x20535020 -v_mov_b32_e32 v2, s5 -v_mov_b32_e32 v3, s6 -v_mov_b32_e32 v4, s7 -v_mov_b32_e32 v5, 1.0 -v_add_f32_e32 v6, s6, v4 -exp mrt0 v2, v3, v4, v5 -exp mrt1 v6, off, off, off done vm -s_endpgm diff --git a/runtime/test/shaders/ps_m3_post.asm b/runtime/test/shaders/ps_m3_post.asm deleted file mode 100644 index 848803058..000000000 --- a/runtime/test/shaders/ps_m3_post.asm +++ /dev/null @@ -1,20 +0,0 @@ -; M3 pixel shader, pass 2: samples the first render target of pass 1 (read through an SRV in a descriptor table) and -; swaps red and blue. Run: d3d12_m3_frame_test. -; User data from the root signature ([0] a table of one SRV, [1] a table of one sampler, [2] one 32-bit constant): -; s[0:1] = console VA of the SRV table's first slot (the T#); s[2:3] = console VA of the sampler table's slot (the S#) -; s4 = the output's alpha, a float (changes every frame) -; attr0.xy = (u, v), 0..1 over the target. mrt0 = (texel.b, texel.g, texel.r, s4) -; fssm-at: 0x10 -; fssm-data: 0x33505350 0x20535020 -s_load_dwordx8 s[8:15], s[0:1], 0x0 -s_load_dwordx4 s[16:19], s[2:3], 0x0 -s_waitcnt lgkmcnt(0) -v_interp_p1_f32_e32 v2, v0, attr0.x -v_interp_p2_f32_e32 v2, v1, attr0.x -v_interp_p1_f32_e32 v3, v0, attr0.y -v_interp_p2_f32_e32 v3, v1, attr0.y -image_sample v[4:7], v[2:3], s[8:15], s[16:19] dmask:0xf dim:SQ_RSRC_IMG_2D -s_waitcnt vmcnt(0) -v_mov_b32_e32 v8, s4 -exp mrt0 v6, v5, v4, v8 done vm -s_endpgm diff --git a/runtime/test/shaders/ps_m3_query.asm b/runtime/test/shaders/ps_m3_query.asm deleted file mode 100644 index 0693cf5e2..000000000 --- a/runtime/test/shaders/ps_m3_query.asm +++ /dev/null @@ -1,12 +0,0 @@ -; M3 occlusion probe: one color export, with all framebuffer writes disabled by the PSO. -; Same root constants as ps_m3.asm; no depth export, discard or memory side effects. -; Vulkan permits occlusion counts multiplied by the number of written color outputs, even with PRECISE. -; Keep the probe single-output so its count can be compared exactly with the CPU's visible rectangle area. -; fssm-at: 0x10 -; fssm-data: 0x33515350 0x20535020 -v_mov_b32_e32 v2, s5 -v_mov_b32_e32 v3, s6 -v_mov_b32_e32 v4, s7 -v_mov_b32_e32 v5, 1.0 -exp mrt0 v2, v3, v4, v5 done vm -s_endpgm diff --git a/runtime/test/shaders/ps_mandelbrot.asm b/runtime/test/shaders/ps_mandelbrot.asm deleted file mode 100644 index 98c70f6cc..000000000 --- a/runtime/test/shaders/ps_mandelbrot.asm +++ /dev/null @@ -1,46 +0,0 @@ -; Mandelbrot set: a divergent backward loop with EXEC masking. Each lane iterates z = z^2 + c until |z|^2 > 4 or -; 64 iterations, with c from attr0.xy (u, v 0..1 over the image) mapped to [-2.25, 0.75] x [-1.5, 1.5]. A lane that -; escapes drops out of EXEC (s_and_b32 exec_lo, exec_lo, vcc_lo); s_cbranch_execz leaves the loop once every lane has -; escaped, else the uniform counter s10 ends it after 64 rounds. EXEC is restored from s20 before the export. -; Only v_mul/v_add/v_sub (no FMA), so a float32 model on the CPU gives the same counts. -; Branch offsets are dwords from the next instruction: execz +9 forward to the restore, scc1 -15 back to the loop top. -; Run: vk_harness vs_ids.spv ps_mandelbrot.spv out.raw -; -> mrt0 = (sqrt(t), t*t, 4t(1-t), iteration count as raw bits) with t = count / 64 -v_interp_p1_f32_e32 v2, v0, attr0.x -v_interp_p2_f32_e32 v2, v1, attr0.x -v_interp_p1_f32_e32 v3, v0, attr0.y -v_interp_p2_f32_e32 v3, v1, attr0.y -v_mul_f32_e32 v4, 0x40400000, v2 -v_add_f32_e32 v4, 0xc0100000, v4 -v_mul_f32_e32 v5, 0x40400000, v3 -v_add_f32_e32 v5, 0xbfc00000, v5 -v_mov_b32_e32 v6, 0 -v_mov_b32_e32 v7, 0 -v_mov_b32_e32 v8, 0 -s_mov_b32 s10, 0 -s_mov_b32 s20, exec_lo -v_mul_f32_e32 v9, v6, v6 -v_mul_f32_e32 v10, v7, v7 -v_add_f32_e32 v11, v9, v10 -v_cmp_ge_f32_e32 vcc_lo, 4.0, v11 -s_and_b32 exec_lo, exec_lo, vcc_lo -s_cbranch_execz 9 -v_sub_f32_e32 v12, v9, v10 -v_mul_f32_e32 v13, v6, v7 -v_add_f32_e32 v13, v13, v13 -v_add_f32_e32 v6, v12, v4 -v_add_f32_e32 v7, v13, v5 -v_add_nc_u32_e32 v8, 1, v8 -s_add_u32 s10, s10, 1 -s_cmp_lt_u32 s10, 64 -s_cbranch_scc1 -15 -s_mov_b32 exec_lo, s20 -v_cvt_f32_u32_e32 v14, v8 -v_mul_f32_e32 v14, 0x3c800000, v14 -v_sqrt_f32_e32 v15, v14 -v_mul_f32_e32 v16, v14, v14 -v_sub_f32_e32 v17, 1.0, v14 -v_mul_f32_e32 v17, v14, v17 -v_mul_f32_e32 v17, 4.0, v17 -exp mrt0 v15, v16, v17, v8 done vm -s_endpgm diff --git a/runtime/test/shaders/ps_med3_mods.asm b/runtime/test/shaders/ps_med3_mods.asm deleted file mode 100644 index 683ec71cf..000000000 --- a/runtime/test/shaders/ps_med3_mods.asm +++ /dev/null @@ -1,12 +0,0 @@ -; v_med3_f32 of (2.0, 0.5, 1.5) yields 1.5. Each channel uses a different output modifier. -; Expected mrt0 bits: 0x3f800000, 0x40400000, 0x40c00000, 0x3f400000 (1, 3, 6, 0.75). -; Alpha divides by two before clamping. Reversing that order gives 0.5. -v_mov_b32 v10, 0x40000000 -v_mov_b32 v11, 0x3f000000 -v_mov_b32 v12, 0x3fc00000 -v_med3_f32 v0, v10, v11, v12 clamp -v_med3_f32 v1, v10, v11, v12 mul:2 -v_med3_f32 v2, v10, v11, v12 mul:4 -v_med3_f32 v3, v10, v11, v12 clamp div:2 -exp mrt0 v0, v1, v2, v3 done vm -s_endpgm diff --git a/runtime/test/shaders/ps_mul_legacy_denorm.asm b/runtime/test/shaders/ps_mul_legacy_denorm.asm deleted file mode 100644 index fcca28896..000000000 --- a/runtime/test/shaders/ps_mul_legacy_denorm.asm +++ /dev/null @@ -1,16 +0,0 @@ -; v_mul_legacy_f32 in the inferred f32 denorm-mode 0 (flush input and output). -; The two input denormals become signed zero, then DX9 0*x overrides the sign to +0. -; A finite, nonzero product that underflows keeps its sign when flushed. -; Expected mrt0 bits: 0x00000000 0x00000000 0x00000000 0x80000000 -v_mov_b32 v0, 0x00000001 -v_mov_b32 v1, 0x4b800000 -v_mul_legacy_f32 v4, v0, v1 -v_mov_b32 v0, 0x80000001 -v_mul_legacy_f32 v5, v0, v1 -v_mov_b32 v0, 0x00800000 -v_mov_b32 v1, 0x3f000000 -v_mul_legacy_f32 v6, v0, v1 -v_mov_b32 v0, 0x80800000 -v_mul_legacy_f32 v7, v0, v1 -exp mrt0 v4, v5, v6, v7 done vm -s_endpgm diff --git a/runtime/test/shaders/ps_mul_legacy_denorm_mods.asm b/runtime/test/shaders/ps_mul_legacy_denorm_mods.asm deleted file mode 100644 index 641eaecb3..000000000 --- a/runtime/test/shaders/ps_mul_legacy_denorm_mods.asm +++ /dev/null @@ -1,18 +0,0 @@ -; The product is flushed before VOP3 output modifiers, and the modified result is flushed again. -; A subnormal scaled to a normal number by mul:2 or mul:4 must already be zero. -; On native RDNA2 with IEEE off an omod changes -0 into +0. An ordinary normal product can still -; be modified. Legacy -0 * -inf gives +0. -; Expected mrt0 bits: 0x00000000 0x00000000 0x00000000 0x40400000 -v_mov_b32 v0, 0x00800000 -v_mov_b32 v1, 0x3f000000 -v_mul_legacy_f32_e64 v4, v0, v1 mul:2 -v_mov_b32 v2, 0x80800000 -v_mul_legacy_f32_e64 v5, v2, v1 mul:4 -v_mov_b32 v3, 0xff800000 -v_mov_b32 v6, 0x80000000 -v_mul_legacy_f32 v7, v6, v3 -v_mov_b32 v9, 0x40000000 -v_mov_b32 v10, 0x40400000 -v_mul_legacy_f32_e64 v8, v9, v10 div:2 -exp mrt0 v4, v5, v7, v8 done vm -s_endpgm diff --git a/runtime/test/shaders/ps_nan_payload.asm b/runtime/test/shaders/ps_nan_payload.asm deleted file mode 100644 index 67e5f6f8d..000000000 --- a/runtime/test/shaders/ps_nan_payload.asm +++ /dev/null @@ -1,10 +0,0 @@ -; Export two non-canonical f32 quiet NaNs and two finite controls to RGBA32F. -; Expected mrt0 words: 0x7fc12345, 0xffc54321, 0x3f800000, 0x3f000000. -; Only KosmicKrisp may return the canonical 0x7fc00000 for the NaNs (#3125). - -v_mov_b32 v0, 0x7fc12345 -v_mov_b32 v1, 0xffc54321 -v_mov_b32 v2, 0x3f800000 -v_mov_b32 v3, 0x3f000000 -exp mrt0 v0, v1, v2, v3 done vm -s_endpgm diff --git a/runtime/test/shaders/ps_ops.asm b/runtime/test/shaders/ps_ops.asm deleted file mode 100644 index f834eb5ea..000000000 --- a/runtime/test/shaders/ps_ops.asm +++ /dev/null @@ -1,16 +0,0 @@ -; regen_fixtures: this source has a translator fixture in tests/semantic/fixtures/disasm -; Packed f16 FMA, integer min3/max3 and signed bitfield extract. Expected mrt0 bits: 0x48804300, 5, 7, 0xbffffffc -; XOR bit 30 before export to encode the integer result as a finite RGBA32F value. -v_mov_b32 v0, 0x40003c00 -v_mov_b32 v1, 0x44004200 -v_mov_b32 v2, 0x3c003800 -v_pk_fma_f16 v3, v0, v1, v2 -v_mov_b32 v5, 7 -v_mov_b32 v6, 0xfffffff0 -v_mov_b32 v7, 5 -v_min3_u32 v4, v5, v6, v7 -v_max3_i32 v8, v5, v6, v7 -v_bfe_i32 v9, v6, 2, 4 -v_xor_b32_e32 v9, 0x40000000, v9 -exp mrt0 v3, v4, v8, v9 done vm -s_endpgm diff --git a/runtime/test/shaders/ps_ops2.asm b/runtime/test/shaders/ps_ops2.asm deleted file mode 100644 index 6a64ac6fc..000000000 --- a/runtime/test/shaders/ps_ops2.asm +++ /dev/null @@ -1,21 +0,0 @@ -; regen_fixtures: this source has a translator fixture in tests/semantic/fixtures/disasm -; v_fma_f16 op_sel (source and destination halves), v_subrev_co_ci_u32 with borrow, 64-bit v_cmp/v_cmpx. -; Expected mrt0 bits: 0xabcd4400, 0x46001234, 0xbffffffa, 7 -; XOR bit 30 before export to encode the integer result as a finite RGBA32F value. -v_mov_b32 v0, 0x40003c00 -v_mov_b32 v1, 0x44004200 -v_mov_b32 v2, 0xabcd0000 -v_mov_b32 v3, 0x00001234 -v_fma_f16 v2, v0, v1, 0 op_sel:[0,1,0,0] -v_fma_f16 v3, v0, v1, 0 op_sel:[1,0,0,1] -v_mov_b32 v4, 5 -s_mov_b32 vcc_lo, -1 -v_subrev_co_ci_u32_e64 v5, s0, 10, v4, vcc_lo -v_mov_b32 v6, 0 -v_mov_b32 v7, 0 -v_cmp_eq_u64_e64 s1, 0, v[6:7] -v_cndmask_b32_e64 v8, 0, 7, s1 -v_cmpx_eq_u64_e32 0, v[6:7] -v_xor_b32_e32 v5, 0x40000000, v5 -exp mrt0 v2, v3, v5, v8 done vm -s_endpgm diff --git a/runtime/test/shaders/ps_ops3.asm b/runtime/test/shaders/ps_ops3.asm deleted file mode 100644 index d6f10c2e4..000000000 --- a/runtime/test/shaders/ps_ops3.asm +++ /dev/null @@ -1,16 +0,0 @@ -; regen_fixtures: this source has a translator fixture in tests/semantic/fixtures/disasm -; v_mul_i32_i24, v_alignbyte_b32, v_xnor_b32, v_ffbh_i32, v_swap_b32. Expected mrt0 bits: 0xbffffffa, 0x44660066, 0x44aabbcc, 16 -; XOR bit 30 before export to encode the integer result as a finite RGBA32F value. -v_mov_b32 v0, 0x00fffffe -v_mov_b32 v1, 3 -v_mul_i32_i24_e32 v2, v0, v1 -v_mov_b32 v3, 0x11223344 -v_mov_b32 v4, 0xaabbccdd -v_alignbyte_b32 v5, v3, v4, 1 -v_xnor_b32_e32 v6, v3, v4 -v_mov_b32 v7, 0x0000ffff -v_ffbh_i32_e32 v8, v7 -v_swap_b32 v5, v6 -v_xor_b32_e32 v2, 0x40000000, v2 -exp mrt0 v2, v5, v6, v8 done vm -s_endpgm diff --git a/runtime/test/shaders/ps_ops4.asm b/runtime/test/shaders/ps_ops4.asm deleted file mode 100644 index 8c1f59ef2..000000000 --- a/runtime/test/shaders/ps_ops4.asm +++ /dev/null @@ -1,16 +0,0 @@ -; regen_fixtures: this source has a translator fixture in tests/semantic/fixtures/disasm -; v_pk_lshlrev_b16 / v_pk_lshrrev_b16 (per-half shift amounts), v_add_nc_u16 (keeps dst high half), v_sin_f16 (turns). -; Expected mrt0 bits: 0x34000010, 0x00120800, 0xbeef0000, 0x12343c00 -v_mov_b32_e32 v0, 0x12348001 -v_mov_b32_e32 v2, 0x80004 -v_pk_lshlrev_b16 v1, v2, v0 -v_pk_lshrrev_b16 v3, v2, v0 -v_mov_b32_e32 v4, 0xbeef0000 -v_mov_b32_e32 v5, 0xaaaa0001 -v_mov_b32_e32 v6, 0xffff -v_add_nc_u16 v4, v5, v6 -v_mov_b32_e32 v7, 0x12340000 -v_mov_b32_e32 v8, 0x3400 -v_sin_f16_e32 v7, v8 -exp mrt0 v1, v3, v4, v7 done vm -s_endpgm diff --git a/runtime/test/shaders/ps_ops5.asm b/runtime/test/shaders/ps_ops5.asm deleted file mode 100644 index c39f71b4d..000000000 --- a/runtime/test/shaders/ps_ops5.asm +++ /dev/null @@ -1,19 +0,0 @@ -; regen_fixtures: this source has a translator fixture in tests/semantic/fixtures/disasm -; Scalar b16 shifts (VOP3, high half kept) and v_cos_f16 (turns). -; Expected mrt0 bits: 0x12340010, 0xbeef0800, 0xaaaaffff, 0xdeadbc00 -v_mov_b32_e32 v0, 0x12348001 -v_mov_b32_e32 v1, 0x12340000 -v_mov_b32_e32 v2, 4 -v_lshlrev_b16_e64 v1, v2, v0 -v_mov_b32_e32 v3, 0xbeef8001 -v_mov_b32_e32 v4, 0xbeef0000 -v_lshrrev_b16_e64 v4, v2, v3 -v_mov_b32_e32 v5, 0xfff0 -v_mov_b32_e32 v6, 4 -v_mov_b32_e32 v7, 0xaaaa0000 -v_ashrrev_i16_e64 v7, v6, v5 -v_mov_b32_e32 v8, 0x3800 -v_mov_b32_e32 v9, 0xdead0000 -v_cos_f16_e32 v9, v8 -exp mrt0 v1, v4, v7, v9 done vm -s_endpgm diff --git a/runtime/test/shaders/ps_ops6.asm b/runtime/test/shaders/ps_ops6.asm deleted file mode 100644 index dac11e878..000000000 --- a/runtime/test/shaders/ps_ops6.asm +++ /dev/null @@ -1,16 +0,0 @@ -; regen_fixtures: this source has a translator fixture in tests/semantic/fixtures/disasm -; Packed b16 shifts with op_sel: independent per-half shift amounts and source halves. -; Expected mrt0 bits: 0xf800ffff, 0x01000010, 0x00800800, 0x8000fff0 -v_mov_b32_e32 v0, 0x00040004 -v_mov_b32_e32 v1, 0x8000fff0 -v_pk_ashrrev_i16 v2, v0, v1 -v_mov_b32_e32 v3, 0x00040008 -v_mov_b32_e32 v4, 0x12348001 -v_pk_lshlrev_b16 v5, v3, v4 op_sel:[1,0,0] op_sel_hi:[0,0,0] -v_mov_b32_e32 v6, 0x00040008 -v_mov_b32_e32 v7, 0xbeef8001 -v_pk_lshrrev_b16 v8, v6, v7 op_sel:[1,0,0] op_sel_hi:[0,0,0] -v_mov_b32_e32 v9, 0 -v_pk_ashrrev_i16 v10, v9, v1 -exp mrt0 v2, v5, v8, v10 done vm -s_endpgm diff --git a/runtime/test/shaders/ps_ops7.asm b/runtime/test/shaders/ps_ops7.asm deleted file mode 100644 index 40c676754..000000000 --- a/runtime/test/shaders/ps_ops7.asm +++ /dev/null @@ -1,19 +0,0 @@ -; regen_fixtures: this source has a translator fixture in tests/semantic/fixtures/disasm -; v_perm_b32 (byte selects 0-7, 12 = 0x00, >= 13 = 0xff, 8-11 = sign of bytes 1/3/5/7 of {S0, S1}), -; v_alignbit_b32 (shift taken mod 32), v_med3_i32 vs v_med3_u32 on the same operands. -; Expected mrt0 bits: 0x00ff8077, 0xff0000ff, 0x89abcdef, 0x00070003 -v_mov_b32_e32 v0, 0x80112233 -v_mov_b32_e32 v1, 0x4455e677 -v_mov_b32_e32 v2, 0x0c0d0700 -v_perm_b32 v3, v0, v1, v2 -v_mov_b32_e32 v2, 0x0b0a0908 -v_perm_b32 v4, v0, v1, v2 -v_mov_b32_e32 v5, 0x12345678 -v_mov_b32_e32 v6, 0x9abcdef0 -v_alignbit_b32 v7, v5, v6, 36 -v_mov_b32_e32 v8, -5 -v_med3_i32 v9, v8, 7, 3 -v_med3_u32 v10, v8, 7, 3 -v_lshl_add_u32 v11, v10, 16, v9 -exp mrt0 v3, v4, v7, v11 done vm -s_endpgm diff --git a/runtime/test/shaders/ps_ops8.asm b/runtime/test/shaders/ps_ops8.asm deleted file mode 100644 index 2c24ea5ff..000000000 --- a/runtime/test/shaders/ps_ops8.asm +++ /dev/null @@ -1,26 +0,0 @@ -; regen_fixtures: this source has a translator fixture in tests/semantic/fixtures/disasm -; v_mul_hi_u32 / v_mul_hi_i32, v_bcnt_u32_b32 with an accumulator, v_ffbl_b32 / v_ffbh_u32 (and v_ffbh_u32 of 0 -; = 0xffffffff), v_xad_u32 and v_add3_u32 wrapping. -; Expected mrt0 bits: 0x80000000, 0xbfffffff, 0x000f100e, 0x0f0f0f1f -; XOR bit 30 before export to encode the integer result as a finite RGBA32F value. -v_mov_b32_e32 v0, 0x80000001 -v_mov_b32_e32 v1, -1 -v_mul_hi_u32 v2, v0, v1 -v_mov_b32_e32 v3, -2 -v_mov_b32_e32 v4, 0x40000000 -v_mul_hi_i32 v5, v3, v4 -v_mov_b32_e32 v6, 0xf0f00001 -v_bcnt_u32_b32 v7, v6, 5 -v_mov_b32_e32 v8, 0x00010000 -v_ffbl_b32_e32 v9, v8 -v_ffbh_u32_e32 v10, v8 -v_lshl_add_u32 v11, v9, 8, v7 -v_lshl_add_u32 v11, v10, 16, v11 -v_mov_b32_e32 v12, 0xf0f0f0f0 -v_xad_u32 v13, v12, -1, 1 -v_mov_b32_e32 v14, 0 -v_ffbh_u32_e32 v15, v14 -v_add3_u32 v16, v13, 16, v15 -v_xor_b32_e32 v5, 0x40000000, v5 -exp mrt0 v2, v5, v11, v16 done vm -s_endpgm diff --git a/runtime/test/shaders/ps_outmods_f16.asm b/runtime/test/shaders/ps_outmods_f16.asm deleted file mode 100644 index 92dec15ef..000000000 --- a/runtime/test/shaders/ps_outmods_f16.asm +++ /dev/null @@ -1,34 +0,0 @@ -; regen_fixtures: this source has a translator fixture in tests/semantic/fixtures/disasm -; VOP3 output modifiers on v_cvt_f16_f32, in the order an RX 6800 applies them (@shelbykb2, #718): round to f16, then -; omod, then clamp. With an omod a zero or denormal f16 gives +0. The destination's high half is kept. -; 1.5 clamp -> 1.0 (0x3c00), high half 0xaaaa kept 0.375 mul:4 -> 1.5 (0x3e00) -; 2^-15 mul:2 -> +0 (the f16 is a denormal) 65520 div:2 -> inf (65520 rounds to inf first) -; -0 mul:2 -> +0 2.0 mul:2 clamp -> 1.0 (omod before clamp) -; Words 2 and 3 hold two results each, low half first. On the RX 6800 1.5 clamp gave 0x3c00 in every float mode, and -; 0.375 mul:4, 2^-15 mul:2, 65520 div:2 and -0 mul:2 gave these halves with IEEE off and f16 denormals flushed, the -; mode an omod implies (with f16 denormals kept the omod is ignored). 2.0 mul:2 clamp wasn't measured as such. -; With the modifiers dropped the words are 0xaaaa3e00, 0xaaaa3600, 0x7c000200, 0x40008000; scaled before the -; rounding, as the f16 ALU results are, words 2 and 3 are 0x78000400 and 0x3c008000. -; Expected mrt0 bits: 0xaaaa3c00, 0xaaaa3e00, 0x7c000000, 0x3c000000 -v_mov_b32 v0, 1.5 -v_mov_b32 v1, 0x3ec00000 -v_mov_b32 v2, 0xaaaa5555 -v_mov_b32 v3, 0xaaaa5555 -v_cvt_f16_f32_e64 v2, v0 clamp -v_cvt_f16_f32_e64 v3, v1 mul:4 -v_mov_b32 v8, 0x38000000 -v_mov_b32 v9, 0x477ff000 -v_mov_b32 v10, 0x80000000 -v_mov_b32 v11, 2.0 -v_mov_b32 v4, 0 -v_mov_b32 v5, 0 -v_mov_b32 v6, 0 -v_mov_b32 v7, 0 -v_cvt_f16_f32_e64 v4, v8 mul:2 -v_cvt_f16_f32_e64 v5, v9 div:2 -v_cvt_f16_f32_e64 v6, v10 mul:2 -v_cvt_f16_f32_e64 v7, v11 clamp mul:2 -v_lshl_or_b32 v4, v5, 16, v4 -v_lshl_or_b32 v5, v7, 16, v6 -exp mrt0 v2, v3, v4, v5 done vm -s_endpgm diff --git a/runtime/test/shaders/ps_persp_bary.asm b/runtime/test/shaders/ps_persp_bary.asm deleted file mode 100644 index ebdae6711..000000000 --- a/runtime/test/shaders/ps_persp_bary.asm +++ /dev/null @@ -1,12 +0,0 @@ -; ps_bary's code, drawn with vs_persp (clip w = 1, 2, 4) instead of vs_ids (w = 1): attr0.xy and the raw i/j -; (v0, v1) must follow the perspective-correct weights. At a pixel centre with screen-space weights l0, l1, l2 of the -; three vertices, p_k = (l_k / w_k) / sum(l_m / w_m); mrt0 = (sum p_k attr0_k.x, sum p_k attr0_k.y, p1, p2). The -; affine weights (l1, l2) differ by at least 0.007 on every covered pixel, so NoPerspective interpolation fails it. -v_interp_p1_f32_e32 v2, v0, attr0.x -v_interp_p2_f32_e32 v2, v1, attr0.x -v_interp_p1_f32_e32 v3, v0, attr0.y -v_interp_p2_f32_e32 v3, v1, attr0.y -v_mov_b32 v4, v0 -v_mov_b32 v5, v1 -exp mrt0 v2, v3, v4, v5 done vm -s_endpgm diff --git a/runtime/test/shaders/ps_sample_c.asm b/runtime/test/shaders/ps_sample_c.asm deleted file mode 100644 index 8d6616cdc..000000000 --- a/runtime/test/shaders/ps_sample_c.asm +++ /dev/null @@ -1,25 +0,0 @@ -; Depth-compare sampling with implicit LOD: image_sample_c of an 8x8 D32 texture whose texel x holds depth (x + 0.5) / 8, -; reference 0.5 against a LESS_OR_EQUAL compare sampler (S# DEPTH_COMPARE_FUNC 3 at s[16:19]), at u, v from attr0 (a -; pixel shader, so the LOD comes from the derivatives: OpImageSampleDrefImplicitLod). Address v[4:6] = (z-compare, -; u, v). The same sample without and with d16; the d16 result (an f16 in the low half) is widened with v_cvt_f32_f16. -; The one-level texture makes the LOD 0 whatever the derivatives. mrt0 = (f32 result, widened d16 result, u, v). -; Run: vk_texture_test dref_c -> every pixel's first two components are 1.0 where its texel has x >= 4, else 0.0 -v_interp_p1_f32_e32 v2, v0, attr0.x -v_interp_p2_f32_e32 v2, v1, attr0.x -v_interp_p1_f32_e32 v3, v0, attr0.y -v_interp_p2_f32_e32 v3, v1, attr0.y -v_mov_b32_e32 v4, 0.5 -v_mov_b32_e32 v5, v2 -v_mov_b32_e32 v6, v3 -s_load_dwordx8 s[8:15], s[0:1], 0x0 -s_waitcnt lgkmcnt(0) -s_mov_b32 s16, 0x3092 -s_mov_b32 s17, 0xc00000 -s_mov_b32 s18, 0x14500000 -s_mov_b32 s19, 0 -image_sample_c v9, v[4:6], s[8:15], s[16:19] dmask:0x1 dim:SQ_RSRC_IMG_2D -image_sample_c v10, v[4:6], s[8:15], s[16:19] dmask:0x1 dim:SQ_RSRC_IMG_2D d16 -s_waitcnt vmcnt(0) -v_cvt_f32_f16_e32 v11, v10 -exp mrt0 v9, v11, v2, v3 done vm -s_endpgm diff --git a/runtime/test/shaders/ps_sample_c_b.asm b/runtime/test/shaders/ps_sample_c_b.asm deleted file mode 100644 index ad86f20df..000000000 --- a/runtime/test/shaders/ps_sample_c_b.asm +++ /dev/null @@ -1,25 +0,0 @@ -; Depth-compare sampling with a LOD bias: image_sample_c_b, as ps_sample_c with the bias 1.0 in front of the z-compare -; (address v[4:7] = bias, z-compare 0.5, u, v). A bias read as the reference (1.0 compares false everywhere) or the -; reference as the bias would change every result; on the one-level texture the bias itself has no other effect. -; mrt0 = (f32 result, widened d16 result, u, v). -; Run: vk_texture_test dref_c_b -> every pixel's first two components are 1.0 where its texel has x >= 4, else 0.0 -v_interp_p1_f32_e32 v2, v0, attr0.x -v_interp_p2_f32_e32 v2, v1, attr0.x -v_interp_p1_f32_e32 v3, v0, attr0.y -v_interp_p2_f32_e32 v3, v1, attr0.y -v_mov_b32_e32 v4, 1.0 -v_mov_b32_e32 v5, 0.5 -v_mov_b32_e32 v6, v2 -v_mov_b32_e32 v7, v3 -s_load_dwordx8 s[8:15], s[0:1], 0x0 -s_waitcnt lgkmcnt(0) -s_mov_b32 s16, 0x3092 -s_mov_b32 s17, 0xc00000 -s_mov_b32 s18, 0x14500000 -s_mov_b32 s19, 0 -image_sample_c_b v9, v[4:7], s[8:15], s[16:19] dmask:0x1 dim:SQ_RSRC_IMG_2D -image_sample_c_b v10, v[4:7], s[8:15], s[16:19] dmask:0x1 dim:SQ_RSRC_IMG_2D d16 -s_waitcnt vmcnt(0) -v_cvt_f32_f16_e32 v11, v10 -exp mrt0 v9, v11, v2, v3 done vm -s_endpgm diff --git a/runtime/test/shaders/ps_sample_c_lz.asm b/runtime/test/shaders/ps_sample_c_lz.asm deleted file mode 100644 index 75438a3a5..000000000 --- a/runtime/test/shaders/ps_sample_c_lz.asm +++ /dev/null @@ -1,24 +0,0 @@ -; Depth-compare sampling test: image_sample_c_lz of an 8x8 D32 texture whose texel x holds depth (x + 0.5) / 8, with -; the reference 0.5 against a LESS_OR_EQUAL compare sampler (S# DEPTH_COMPARE_FUNC 3 at s[16:19]), at u, v from attr0. -; The same sample without and with d16; the d16 result (an f16 in the low half) is widened with v_cvt_f32_f16. -; T# at s[8:15] loaded via s[0:1]. mrt0 = (f32 result, widened d16 result, u, v). -; Run: vk_texture_test dref -> every pixel's first two components are 1.0 where its texel has x >= 4, else 0.0 -v_interp_p1_f32_e32 v2, v0, attr0.x -v_interp_p2_f32_e32 v2, v1, attr0.x -v_interp_p1_f32_e32 v3, v0, attr0.y -v_interp_p2_f32_e32 v3, v1, attr0.y -v_mov_b32_e32 v4, 0.5 -v_mov_b32_e32 v5, v2 -v_mov_b32_e32 v6, v3 -s_load_dwordx8 s[8:15], s[0:1], 0x0 -s_waitcnt lgkmcnt(0) -s_mov_b32 s16, 0x3092 -s_mov_b32 s17, 0xc00000 -s_mov_b32 s18, 0x14500000 -s_mov_b32 s19, 0 -image_sample_c_lz v9, v[4:6], s[8:15], s[16:19] dmask:0x1 dim:SQ_RSRC_IMG_2D -image_sample_c_lz v10, v[4:6], s[8:15], s[16:19] dmask:0x1 dim:SQ_RSRC_IMG_2D d16 -s_waitcnt vmcnt(0) -v_cvt_f32_f16_e32 v11, v10 -exp mrt0 v9, v11, v2, v3 done vm -s_endpgm diff --git a/runtime/test/shaders/ps_sample_c_lz_a16.asm b/runtime/test/shaders/ps_sample_c_lz_a16.asm deleted file mode 100644 index 388adff08..000000000 --- a/runtime/test/shaders/ps_sample_c_lz_a16.asm +++ /dev/null @@ -1,22 +0,0 @@ -; Depth-compare sampling with a16: as ps_sample_c_lz (the same D32 texture, reference 0.5, LESS_OR_EQUAL sampler), but -; the z-compare keeps a whole VGPR as an f32 and only u, v after it are packed f16. Read as pairs, the reference -; would be the low half of 0.5 (0.0) and the coordinates a half early. mrt0 = (f32 result, widened d16 result, u, v). -; Run: vk_texture_test dref_a16 -> every pixel's first two components are 1.0 where its texel has x >= 4, else 0.0 -v_interp_p1_f32_e32 v2, v0, attr0.x -v_interp_p2_f32_e32 v2, v1, attr0.x -v_interp_p1_f32_e32 v3, v0, attr0.y -v_interp_p2_f32_e32 v3, v1, attr0.y -v_mov_b32_e32 v4, 0.5 -v_cvt_pkrtz_f16_f32 v5, v2, v3 -s_load_dwordx8 s[8:15], s[0:1], 0x0 -s_waitcnt lgkmcnt(0) -s_mov_b32 s16, 0x3092 -s_mov_b32 s17, 0xc00000 -s_mov_b32 s18, 0x14500000 -s_mov_b32 s19, 0 -image_sample_c_lz v9, v[4:5], s[8:15], s[16:19] dmask:0x1 dim:SQ_RSRC_IMG_2D a16 -image_sample_c_lz v10, v[4:5], s[8:15], s[16:19] dmask:0x1 dim:SQ_RSRC_IMG_2D a16 d16 -s_waitcnt vmcnt(0) -v_cvt_f32_f16_e32 v11, v10 -exp mrt0 v9, v11, v2, v3 done vm -s_endpgm diff --git a/runtime/test/shaders/ps_sample_implicit_sint.asm b/runtime/test/shaders/ps_sample_implicit_sint.asm deleted file mode 100644 index 3723ce4bf..000000000 --- a/runtime/test/shaders/ps_sample_implicit_sint.asm +++ /dev/null @@ -1,30 +0,0 @@ -; The 128x128 signed view minifies to mip 1 on the 64x64 target. First clamp the sampler to mip 0, -; then permit mip 1. Every input byte is 0 or 128, so a signed D16 sample must produce 0 or -128. -; Divide each signed channel by -128 to compare all output components with the shared 0/1 color reference. -v_interp_p1_f32_e32 v2, v0, attr0.x -v_interp_p2_f32_e32 v2, v1, attr0.x -v_interp_p1_f32_e32 v3, v0, attr0.y -v_interp_p2_f32_e32 v3, v1, attr0.y -s_load_dwordx8 s[8:15], s[0:1], 0 -s_load_dwordx4 s[16:19], s[0:1], 0x20 -s_waitcnt lgkmcnt(0) -image_sample v[4:5], v[2:3], s[8:15], s[16:19] dmask:0xf dim:SQ_RSRC_IMG_2D d16 -s_waitcnt vmcnt(0) -v_bfe_i32 v7, v5, 16, 16 -v_bfe_i32 v6, v5, 0, 16 -v_bfe_i32 v5, v4, 16, 16 -v_bfe_i32 v4, v4, 0, 16 -v_sub_nc_u32_e32 v4, 0, v4 -v_cvt_f32_i32_e32 v4, v4 -v_sub_nc_u32_e32 v5, 0, v5 -v_cvt_f32_i32_e32 v5, v5 -v_sub_nc_u32_e32 v6, 0, v6 -v_cvt_f32_i32_e32 v6, v6 -v_sub_nc_u32_e32 v7, 0, v7 -v_cvt_f32_i32_e32 v7, v7 -v_mul_f32_e32 v4, 0x3c000000, v4 -v_mul_f32_e32 v5, 0x3c000000, v5 -v_mul_f32_e32 v6, 0x3c000000, v6 -v_mul_f32_e32 v7, 0x3c000000, v7 -exp mrt0 v4,v5,v6,v7 done vm -s_endpgm diff --git a/runtime/test/shaders/ps_sample_implicit_uint.asm b/runtime/test/shaders/ps_sample_implicit_uint.asm deleted file mode 100644 index cc51eabca..000000000 --- a/runtime/test/shaders/ps_sample_implicit_uint.asm +++ /dev/null @@ -1,26 +0,0 @@ -; The 128x128 unsigned view minifies to mip 1 on the 64x64 target. First clamp the sampler to mip 0, -; then permit mip 1. Every input byte is 0 or 255, so an unsigned D16 sample must produce 0 or 255. -; Divide each channel by 255 to compare all output components with the shared 0/1 color reference. -v_interp_p1_f32_e32 v2, v0, attr0.x -v_interp_p2_f32_e32 v2, v1, attr0.x -v_interp_p1_f32_e32 v3, v0, attr0.y -v_interp_p2_f32_e32 v3, v1, attr0.y -s_load_dwordx8 s[8:15], s[0:1], 0 -s_load_dwordx4 s[16:19], s[0:1], 0x20 -s_waitcnt lgkmcnt(0) -image_sample v[4:5], v[2:3], s[8:15], s[16:19] dmask:0xf dim:SQ_RSRC_IMG_2D d16 -s_waitcnt vmcnt(0) -v_bfe_u32 v7, v5, 16, 16 -v_bfe_u32 v6, v5, 0, 16 -v_bfe_u32 v5, v4, 16, 16 -v_bfe_u32 v4, v4, 0, 16 -v_cvt_f32_u32_e32 v4, v4 -v_cvt_f32_u32_e32 v5, v5 -v_cvt_f32_u32_e32 v6, v6 -v_cvt_f32_u32_e32 v7, v7 -v_mul_f32_e32 v4, 0x3b808081, v4 -v_mul_f32_e32 v5, 0x3b808081, v5 -v_mul_f32_e32 v6, 0x3b808081, v6 -v_mul_f32_e32 v7, 0x3b808081, v7 -exp mrt0 v4,v5,v6,v7 done vm -s_endpgm diff --git a/runtime/test/shaders/ps_scc.asm b/runtime/test/shaders/ps_scc.asm deleted file mode 100644 index 1556d33f5..000000000 --- a/runtime/test/shaders/ps_scc.asm +++ /dev/null @@ -1,22 +0,0 @@ -; SCC from s_and_b32 (zero -> 0), s_add_i32 (signed overflow -> 1), s_max_u32 (S0 > S1 -> 1), each followed by a branch. -; Expected mrt0 bits: 1, 1, 3, 0x80000000 -s_mov_b32 s0, 0x80 -s_and_b32 s1, s0, 0x7f -s_mov_b32 s2, 1 -s_cbranch_scc0 1 -s_mov_b32 s2, 2 -s_mov_b32 s7, 0x7fffffff -s_add_i32 s3, s7, 1 -s_mov_b32 s4, 1 -s_cbranch_scc1 1 -s_mov_b32 s4, 2 -s_max_u32 s5, 5, 3 -s_mov_b32 s6, 1 -s_cbranch_scc0 1 -s_mov_b32 s6, 3 -v_mov_b32_e32 v0, s2 -v_mov_b32_e32 v1, s4 -v_mov_b32_e32 v2, s6 -v_mov_b32_e32 v3, s3 -exp mrt0 v0, v1, v2, v3 done vm -s_endpgm diff --git a/runtime/test/shaders/ps_scc_logic32.asm b/runtime/test/shaders/ps_scc_logic32.asm deleted file mode 100644 index 3b36f1362..000000000 --- a/runtime/test/shaders/ps_scc_logic32.asm +++ /dev/null @@ -1,44 +0,0 @@ -; s_nand_b32, s_nor_b32, s_xnor_b32: D = ~(S0 op S1), SCC = (D != 0). Values by hand from the RDNA2 ISA SOP2 text. -; s2 = 0xf0f0f0f0, s3 = 0xff00ff00: and = 0xf000f000, or = 0xfff0fff0, xor = 0x0ff00ff0. -; Expected mrt0 bits: nand 0x0fff0fff, nor 0x000f000f, xnor 0xf00ff00f, and an SCC word, bit n = SCC after case n: -; 0 nand(-1, -1) = 0 -> 0 1 nor(0, 0) = -1 -> 1 2 xnor(x, x) = -1 -> 1 -; 3 xnor(x, ~x) = 0 -> 0 4 nor(0xfffffff0, 0) = 0xf -> 1 5 nand(0x80000000, -1) = 0x7fffffff -> 1 -; so the SCC word is 0x36. -s_mov_b32 s2, 0xf0f0f0f0 -s_mov_b32 s3, 0xff00ff00 -s_nand_b32 s4, s2, s3 -s_nor_b32 s5, s2, s3 -s_xnor_b32 s6, s2, s3 -s_mov_b32 s8, -1 -s_mov_b32 s9, 0 -s_mov_b32 s10, 0x0f0f0f0f -s_mov_b32 s11, 0xfffffff0 -s_mov_b32 s12, 0x80000000 -s_nand_b32 s13, s8, s8 -s_cselect_b32 s20, 1, 0 -s_nor_b32 s13, s9, s9 -s_cselect_b32 s21, 1, 0 -s_xnor_b32 s13, s2, s2 -s_cselect_b32 s22, 1, 0 -s_xnor_b32 s13, s2, s10 -s_cselect_b32 s23, 1, 0 -s_nor_b32 s13, s11, s9 -s_cselect_b32 s24, 1, 0 -s_nand_b32 s13, s12, s8 -s_cselect_b32 s25, 1, 0 -s_lshl_b32 s21, s21, 1 -s_lshl_b32 s22, s22, 2 -s_lshl_b32 s23, s23, 3 -s_lshl_b32 s24, s24, 4 -s_lshl_b32 s25, s25, 5 -s_or_b32 s20, s20, s21 -s_or_b32 s20, s20, s22 -s_or_b32 s20, s20, s23 -s_or_b32 s20, s20, s24 -s_or_b32 s20, s20, s25 -v_mov_b32_e32 v0, s4 -v_mov_b32_e32 v1, s5 -v_mov_b32_e32 v2, s6 -v_mov_b32_e32 v3, s20 -exp mrt0 v0, v1, v2, v3 done vm -s_endpgm diff --git a/runtime/test/shaders/ps_scc_logic64.asm b/runtime/test/shaders/ps_scc_logic64.asm deleted file mode 100644 index 3ffb677ae..000000000 --- a/runtime/test/shaders/ps_scc_logic64.asm +++ /dev/null @@ -1,49 +0,0 @@ -; s_nand_b64, s_nor_b64, s_xnor_b64 on plain SGPR pairs: D = ~(S0 op S1), SCC = ((D.lo | D.hi) != 0). By hand from the RDNA2 ISA. -; A = s[2:3] = (lo 0xf0f0f0f0, hi 0x0000ffff), B = s[4:5] = (lo 0xff00ff00, hi 0x00ff00ff). -; Expected mrt0 bits: nand.lo 0x0fff0fff, nor.hi 0xff000000 (A.hi | B.hi = 0x00ffffff), xnor.hi 0xff0000ff (A.hi ^ B.hi = 0x00ffff00), -; and an SCC word, bit n = SCC after case n (X = (-1, 0), Y = (0, -1)): -; 0 nand(ones, ones) = 0 -> 0 1 nor(X, 0) = (0, -1), only the high dword set -> 1 -; 2 xnor(X, X) = all ones -> 1 3 xnor(X, Y) = 0 -> 0 -; 4 nor(Y, (0xfffffff0, 0)) = (0xf, 0), only the low dword set -> 1 -; so the SCC word is 0x16. -s_mov_b32 s2, 0xf0f0f0f0 -s_mov_b32 s3, 0x0000ffff -s_mov_b32 s4, 0xff00ff00 -s_mov_b32 s5, 0x00ff00ff -s_nand_b64 s[6:7], s[2:3], s[4:5] -s_nor_b64 s[8:9], s[2:3], s[4:5] -s_xnor_b64 s[10:11], s[2:3], s[4:5] -s_mov_b32 s12, -1 -s_mov_b32 s13, -1 -s_mov_b32 s14, -1 -s_mov_b32 s15, 0 -s_mov_b32 s16, 0 -s_mov_b32 s17, -1 -s_mov_b32 s18, 0 -s_mov_b32 s19, 0 -s_mov_b32 s24, 0xfffffff0 -s_mov_b32 s25, 0 -s_nand_b64 s[30:31], s[12:13], s[12:13] -s_cselect_b32 s40, 1, 0 -s_nor_b64 s[30:31], s[14:15], s[18:19] -s_cselect_b32 s41, 1, 0 -s_xnor_b64 s[30:31], s[14:15], s[14:15] -s_cselect_b32 s42, 1, 0 -s_xnor_b64 s[30:31], s[14:15], s[16:17] -s_cselect_b32 s43, 1, 0 -s_nor_b64 s[30:31], s[16:17], s[24:25] -s_cselect_b32 s44, 1, 0 -s_lshl_b32 s41, s41, 1 -s_lshl_b32 s42, s42, 2 -s_lshl_b32 s43, s43, 3 -s_lshl_b32 s44, s44, 4 -s_or_b32 s40, s40, s41 -s_or_b32 s40, s40, s42 -s_or_b32 s40, s40, s43 -s_or_b32 s40, s40, s44 -v_mov_b32_e32 v0, s6 -v_mov_b32_e32 v1, s9 -v_mov_b32_e32 v2, s11 -v_mov_b32_e32 v3, s40 -exp mrt0 v0, v1, v2, v3 done vm -s_endpgm diff --git a/runtime/test/shaders/ps_scc_mask32.asm b/runtime/test/shaders/ps_scc_mask32.asm deleted file mode 100644 index 965c66e08..000000000 --- a/runtime/test/shaders/ps_scc_mask32.asm +++ /dev/null @@ -1,14 +0,0 @@ -; Wave32 SCC from a 32-bit lane-mask op: lanes with i > 0.27 set VCC, and s_and_b32 of VCC_LO with EXEC_LO sets -; SCC = (the wave's mask != 0), one value for the whole wave. A wave with any set lane runs the scalar add in all -; its lanes. Expected, as for ps_uniform_branch: bit=1 pixels export s5 = 8; some bit=0 pixels (same wave) also 8; -; the rest 7. Before 2026-11-22 each lane took its own bit as SCC, so no bit=0 pixel got 8 (found by FUZZ-8, -; tools/cf_diff.py). -v_cmp_lt_f32 vcc_lo, 0x3e8a3d71, v0 -s_mov_b32 s5, 7 -s_and_b32 s6, vcc_lo, exec_lo -s_cbranch_scc0 1 -s_add_u32 s5, s5, 1 -v_mov_b32 v3, s5 -v_cndmask_b32_e64 v4, 0, 1, vcc_lo -exp mrt0 v3, v4, v0, v0 done vm -s_endpgm diff --git a/runtime/test/shaders/ps_scc_minmax.asm b/runtime/test/shaders/ps_scc_minmax.asm deleted file mode 100644 index 479288310..000000000 --- a/runtime/test/shaders/ps_scc_minmax.asm +++ /dev/null @@ -1,48 +0,0 @@ -; regen_fixtures: this source has a translator fixture in tests/semantic/fixtures/disasm -; SCC from s_min_i32/s_max_i32 (signed) and s_min_u32/s_max_u32: 1 only when S0 is strictly smaller (min) or larger -; (max), since D = S0 < S1 ? S0 : S1 picks S1 on a tie. Per word: byte 0 = the op's result on equal operands, -; byte 1 = s_cselect 1/2 after that tie (2: SCC 0), byte 2 = s_cselect 3/4 after a pair that -1 vs 1 decides by -; signedness (3: SCC 1). A tie that set SCC gives byte 1 = 1, a compare of the wrong signedness byte 2 = 4. -; Expected mrt0 bits: 0x00030205, 0x00030207, 0x00030209, 0x00030203 -s_mov_b32 s0, 5 -s_min_i32 s1, s0, 5 -s_cselect_b32 s2, 1, 2 -s_min_i32 s3, -1, 1 -s_cselect_b32 s4, 3, 4 -s_lshl_b32 s2, s2, 8 -s_lshl_b32 s4, s4, 16 -s_or_b32 s1, s1, s2 -s_or_b32 s1, s1, s4 -s_mov_b32 s0, 7 -s_max_i32 s5, s0, 7 -s_cselect_b32 s6, 1, 2 -s_max_i32 s7, 1, -1 -s_cselect_b32 s8, 3, 4 -s_lshl_b32 s6, s6, 8 -s_lshl_b32 s8, s8, 16 -s_or_b32 s5, s5, s6 -s_or_b32 s5, s5, s8 -s_mov_b32 s0, 9 -s_min_u32 s9, s0, 9 -s_cselect_b32 s10, 1, 2 -s_min_u32 s11, 1, -1 -s_cselect_b32 s12, 3, 4 -s_lshl_b32 s10, s10, 8 -s_lshl_b32 s12, s12, 16 -s_or_b32 s9, s9, s10 -s_or_b32 s9, s9, s12 -s_mov_b32 s0, 3 -s_max_u32 s13, s0, 3 -s_cselect_b32 s14, 1, 2 -s_max_u32 s15, -1, 1 -s_cselect_b32 s16, 3, 4 -s_lshl_b32 s14, s14, 8 -s_lshl_b32 s16, s16, 16 -s_or_b32 s13, s13, s14 -s_or_b32 s13, s13, s16 -v_mov_b32_e32 v0, s1 -v_mov_b32_e32 v1, s5 -v_mov_b32_e32 v2, s9 -v_mov_b32_e32 v3, s13 -exp mrt0 v0, v1, v2, v3 done vm -s_endpgm diff --git a/runtime/test/shaders/ps_sdwa.asm b/runtime/test/shaders/ps_sdwa.asm deleted file mode 100644 index 5a84a54e9..000000000 --- a/runtime/test/shaders/ps_sdwa.asm +++ /dev/null @@ -1,16 +0,0 @@ -; regen_fixtures: this source has a translator fixture in tests/semantic/fixtures/disasm -; SDWA GPU check. Assemble with llvm-mc -mcpu=gfx1013 -show-encoding, translate, run with vk_harness. -; Expected mrt0 bits: 0x000000f1, 0xbffefff2, 0x3c003344, 0xbff70000 -; XOR bit 30 before export to encode the integer result as a finite RGBA32F value. -v_mov_b32 v0, 0x8081f0f7 -v_mov_b32 v1, 0x00010005 -v_add_nc_u32_sdwa v2, v0, v1 dst_sel:DWORD dst_unused:UNUSED_PAD src0_sel:BYTE_1 src1_sel:WORD_1 -v_subrev_nc_u32_sdwa v3, v1, sext(v0) dst_sel:DWORD dst_unused:UNUSED_PAD src0_sel:DWORD src1_sel:BYTE_0 -v_mov_b32 v4, 0x11223344 -v_mov_b32 v5, 1.0 -v_cvt_f16_f32_sdwa v4, v5 dst_sel:WORD_1 dst_unused:UNUSED_PRESERVE src0_sel:DWORD -v_or_b32_sdwa v6, v0, v1 dst_sel:BYTE_2 dst_unused:UNUSED_SEXT src0_sel:BYTE_0 src1_sel:BYTE_0 -v_xor_b32_e32 v3, 0x40000000, v3 -v_xor_b32_e32 v6, 0x40000000, v6 -exp mrt0 v2, v3, v4, v6 done vm -s_endpgm diff --git a/runtime/test/shaders/ps_sdwa_dword_hi.asm b/runtime/test/shaders/ps_sdwa_dword_hi.asm deleted file mode 100644 index b35696332..000000000 --- a/runtime/test/shaders/ps_sdwa_dword_hi.asm +++ /dev/null @@ -1,28 +0,0 @@ -; regen_fixtures: this source has a translator fixture in tests/semantic/fixtures/disasm -; 16-bit SDWA results written with dst_sel:DWORD. The non-SDWA f16 VOP1/VOP2 forms keep the destination's high -; half (docs/design.md, 16-bit results), but an SDWA destination with dst_sel:DWORD takes the whole dword: the -; 16-bit result zero-extended, whatever dst_unused says. Measured natively on an AMD Radeon iGPU (gfx1036, RDNA2, -; Windows driver 26.10.1) through tools/hw_oracle with this exact program: 0x00004000, 0x00000003, 0x00004700, -; 0x0000c000; the same four ops with dst_sel:WORD_0 dst_unused:UNUSED_PRESERVE gave 0xdead4000, 0xdead0003, -; 0xdead4700, 0xdeadc000 (the high half kept), so the zero comes from dst_sel:DWORD. -; Every destination starts as 0xdeadbeef. Sources: v2 = 0x12343c00 (WORD_0 = 1.0), v4 = 0xc0004200 (WORD_0 = 3.0, -; WORD_1 = -2.0), v6 = 0x00070000 (WORD_1 = 7). -; x: v_add_f16 1.0 + 1.0 = 2.0 = 0x4000, UNUSED_PRESERVE -> 0x00004000 -; y: v_cvt_u16_f16 of 3.0 = 3 = 0x0003, UNUSED_PAD -> 0x00000003 -; z: v_cvt_f16_u16 of 7 = 7.0 = 0x4700 (exact), UNUSED_PRESERVE -> 0x00004700 -; w: v_mul_f16 1.0 * -2.0 = -2.0 = 0xc000, UNUSED_SEXT -> 0x0000c000 (no sign copies above it) -; All four are small positive denormal floats, kept bit-exact by the RGBA32F target (as 0x000000f1 in ps_sdwa). -; Expected mrt0 bits: 0x00004000, 0x00000003, 0x00004700, 0x0000c000 -v_mov_b32 v1, 0xdeadbeef -v_mov_b32 v2, 0x12343c00 -v_mov_b32 v3, 0xdeadbeef -v_mov_b32 v4, 0xc0004200 -v_mov_b32 v5, 0xdeadbeef -v_mov_b32 v6, 0x70000 -v_mov_b32 v7, 0xdeadbeef -v_add_f16_sdwa v1, v2, v2 dst_sel:DWORD dst_unused:UNUSED_PRESERVE src0_sel:WORD_0 src1_sel:WORD_0 -v_cvt_u16_f16_sdwa v3, v4 dst_sel:DWORD dst_unused:UNUSED_PAD src0_sel:WORD_0 -v_cvt_f16_u16_sdwa v5, v6 dst_sel:DWORD dst_unused:UNUSED_PRESERVE src0_sel:WORD_1 -v_mul_f16_sdwa v7, v2, v4 dst_sel:DWORD dst_unused:UNUSED_SEXT src0_sel:WORD_0 src1_sel:WORD_1 -exp mrt0 v1, v3, v5, v7 done vm -s_endpgm diff --git a/runtime/test/shaders/ps_sdwa_f16_const.asm b/runtime/test/shaders/ps_sdwa_f16_const.asm deleted file mode 100644 index d60d9cbdd..000000000 --- a/runtime/test/shaders/ps_sdwa_f16_const.asm +++ /dev/null @@ -1,33 +0,0 @@ -; regen_fixtures: this source has a translator fixture in tests/semantic/fixtures/disasm -; SDWA source select on a float inline constant in an f16 op. Assemble with llvm-mc -mcpu=gfx1013 -show-encoding, -; translate, run with vk_harness. In a 16-bit float op an inline float constant is the f16 value in bits 15:0 over a -; zero high half (docs/design.md, "f16 inline constants"); SDWA src_sel then narrows those 32 bits like a -; register's (zero-extended), before the op. An SGPR source and an integer op reading the f32 bits of 1.0 are -; narrowed the same way. dst_sel:WORD_0 with UNUSED_PRESERVE keeps the destination's 0xaaaa high half. -; v1 = 0.5 | 1024.0 << 16 (0x64003800), s8 = 0x3c000000 (1.0 in the high half), v2..v5 start as 0xaaaa5555. -; x: v_add_f16_sdwa v2, 1.0, v1 src0_sel:WORD_1 src1_sel:WORD_0 -; 1.0 = 0x00003c00, WORD_1 = 0x0000 = +0.0; +0.0 + 0.5 = 0.5 = 0x3800 -> 0xaaaa3800 -; (the unselected constant would give 1.5 = 0x3e00) -; y: v_mul_f16_sdwa v3, 2.0, v1 src0_sel:BYTE_1 src1_sel:WORD_1 -; 2.0 = 0x00004000, BYTE_1 = 0x0040 = 64 * 2^-24 = 2^-18 (f16 denormal); * 1024.0 = 2^-8 = 0x1c00 -; -> 0xaaaa1c00 (the unselected constant would give 2048.0 = 0x6800) -; z: v_add_f16_sdwa v4, s8, v1 src0_sel:WORD_1 src1_sel:WORD_0 -; s8 WORD_1 = 0x3c00 = 1.0; 1.0 + 0.5 = 1.5 = 0x3e00 -> 0xaaaa3e00 -; w: v_cvt_f16_u16_sdwa v5, 1.0 src0_sel:WORD_1 (integer source: the f32 bits 0x3f800000) -; WORD_1 = 0x3f80 = 16256 = 2^13 * (1 + 1008/1024) -> f16 exponent 13 + 15 = 28: 0x7000 | 0x3f0 = 0x73f0 -; -> 0xaaaa73f0 -; Expected mrt0 bits: 0xaaaa3800, 0xaaaa1c00, 0xaaaa3e00, 0xaaaa73f0 -; Measured: the same four words on an AMD Radeon iGPU (gfx1036, Ryzen 9 9950X3D, driver 26.10.1) through -; tools/hw_oracle (raw HIP kernel, wave32), the same instructions writing v8..v11. -v_mov_b32 v1, 0x64003800 -v_mov_b32 v2, 0xaaaa5555 -v_mov_b32 v3, 0xaaaa5555 -v_mov_b32 v4, 0xaaaa5555 -v_mov_b32 v5, 0xaaaa5555 -s_mov_b32 s8, 0x3c000000 -v_add_f16_sdwa v2, 1.0, v1 dst_sel:WORD_0 dst_unused:UNUSED_PRESERVE src0_sel:WORD_1 src1_sel:WORD_0 -v_mul_f16_sdwa v3, 2.0, v1 dst_sel:WORD_0 dst_unused:UNUSED_PRESERVE src0_sel:BYTE_1 src1_sel:WORD_1 -v_add_f16_sdwa v4, s8, v1 dst_sel:WORD_0 dst_unused:UNUSED_PRESERVE src0_sel:WORD_1 src1_sel:WORD_0 -v_cvt_f16_u16_sdwa v5, 1.0 dst_sel:WORD_0 dst_unused:UNUSED_PRESERVE src0_sel:WORD_1 -exp mrt0 v2, v3, v4, v5 done vm -s_endpgm diff --git a/runtime/test/shaders/ps_sff_imm.asm b/runtime/test/shaders/ps_sff_imm.asm deleted file mode 100644 index 325607581..000000000 --- a/runtime/test/shaders/ps_sff_imm.asm +++ /dev/null @@ -1,15 +0,0 @@ -; regen_fixtures: this source has a translator fixture in tests/semantic/fixtures/disasm -; SHADER-46: s_ff1_i32_b32 / s_ff0_i32_b32 on an inline constant or literal read it as a value, not as a lane mask. -; Lowest set (ff1) or clear (ff0) bit of S0, -1 if none. 4 -> ff1 2; 61 = 0b111101 -> ff0 1; 0x00100000 -> ff1 20; -; 0x0000ffff -> ff0 16. Reading each source as a lane mask (all ones or zero from bit 0) gives -1 in every word. -; Expected mrt0 bits: 2, 1, 20, 16 -s_ff1_i32_b32 s0, 4 -s_ff0_i32_b32 s1, 61 -s_ff1_i32_b32 s2, 0x00100000 -s_ff0_i32_b32 s3, 0x0000ffff -v_mov_b32_e32 v0, s0 -v_mov_b32_e32 v1, s1 -v_mov_b32_e32 v2, s2 -v_mov_b32_e32 v3, s3 -exp mrt0 v0, v1, v2, v3 done vm -s_endpgm diff --git a/runtime/test/shaders/ps_ssharp.asm b/runtime/test/shaders/ps_ssharp.asm deleted file mode 100644 index b68315872..000000000 --- a/runtime/test/shaders/ps_ssharp.asm +++ /dev/null @@ -1,19 +0,0 @@ -; The S# and T# mip fields through the descriptor path. s0:s1 is the console VA of a T# (8 dwords) with the S# -; (4 dwords) 32 bytes after it; the translator hashes both and looks them up in the descriptor hash table. -; Run: vk_sampler_test vs_ids.spv ps_ssharp.spv out.raw [ ] (check.py: SAMPLER_CASES) -; vs_ids runs UV 0..1 over the 64x64 target and the texture is 128x128 with two levels, so the implicit sample -; sees LOD 1 and image_sample_lz LOD 0, before the S# and the T# clamp them. -; -> mrt0 = (lz.r, lz.g, implicit.r, implicit.g). Level 0 is four quadrants, red (1,0), green (0,1), blue (0,0) and -; yellow (1,1) in r,g; level 1 is grey (128/255, 128/255). -s_load_dwordx8 s[8:15], s[0:1], 0x0 -s_load_dwordx4 s[16:19], s[0:1], 0x20 -s_waitcnt lgkmcnt(0) -v_interp_p1_f32_e32 v2, v0, attr0.x -v_interp_p2_f32_e32 v2, v1, attr0.x -v_interp_p1_f32_e32 v3, v0, attr0.y -v_interp_p2_f32_e32 v3, v1, attr0.y -image_sample v[6:7], v[2:3], s[8:15], s[16:19] dmask:0x3 dim:SQ_RSRC_IMG_2D -image_sample_lz v[4:5], v[2:3], s[8:15], s[16:19] dmask:0x3 dim:SQ_RSRC_IMG_2D -s_waitcnt vmcnt(0) -exp mrt0 v4, v5, v6, v7 done vm -s_endpgm diff --git a/runtime/test/shaders/ps_table_fetch.asm b/runtime/test/shaders/ps_table_fetch.asm deleted file mode 100644 index fad9cb9ee..000000000 --- a/runtime/test/shaders/ps_table_fetch.asm +++ /dev/null @@ -1,15 +0,0 @@ -; vk_texture_test fetch-sint / fetch-uint / fetch-miss. Texel (0,0) holds bytes -; 82 22 f8 4d: expect (-126,34,-8,77) or (130,34,248,77). A key mismatch -; fetches magenta UNORM at index zero. Convert raw integer words for RGBA32F output. -s_load_dwordx8 s[8:15], s[0:1], 0 -s_waitcnt lgkmcnt(0) -v_mov_b32_e32 v0, 0 -v_mov_b32_e32 v1, 0 -image_load v[4:7], v[0:1], s[8:15] dmask:0xf dim:SQ_RSRC_IMG_2D -s_waitcnt vmcnt(0) -v_cvt_f32_i32_e32 v4, v4 -v_cvt_f32_i32_e32 v5, v5 -v_cvt_f32_i32_e32 v6, v6 -v_cvt_f32_i32_e32 v7, v7 -exp mrt0 v4, v5, v6, v7 done vm -s_endpgm diff --git a/runtime/test/shaders/ps_tex.asm b/runtime/test/shaders/ps_tex.asm deleted file mode 100644 index 976ac9234..000000000 --- a/runtime/test/shaders/ps_tex.asm +++ /dev/null @@ -1,18 +0,0 @@ -; A texture found through a descriptor table. User data s2:s3 is the console VA of the table: a T# (8 dwords) at -; +0 and an S# (4 dwords) at +32, read at heap base + VA. The translator hashes each and looks it up in the -; descriptor hash table (set 0, binding 2); the indices pick the image (binding 0) and the sampler (binding 1). -; The texture is sampled at attr0.xy, which vs_ids runs 0..1 over the image. -; Run: vk_bindless_test vs_ids.spv ps_tex.spv -; -> mrt0 = the texel under each pixel: an 8x8 gradient (x / 8, y / 8, 0.5, 1) through a nearest sampler, also -; after the table has grown; the fallback image at index 0 (zeros) when the table does not hold the T#. -s_load_dwordx8 s[8:15], s[2:3], 0x0 -s_load_dwordx4 s[16:19], s[2:3], 0x20 -s_waitcnt lgkmcnt(0) -v_interp_p1_f32_e32 v2, v0, attr0.x -v_interp_p2_f32_e32 v2, v1, attr0.x -v_interp_p1_f32_e32 v3, v0, attr0.y -v_interp_p2_f32_e32 v3, v1, attr0.y -image_sample v[4:7], v[2:3], s[8:15], s[16:19] dmask:0xf dim:SQ_RSRC_IMG_2D -s_waitcnt vmcnt(0) -exp mrt0 v4, v5, v6, v7 done vm -s_endpgm diff --git a/runtime/test/shaders/ps_texoff.asm b/runtime/test/shaders/ps_texoff.asm deleted file mode 100644 index bd4d7ace4..000000000 --- a/runtime/test/shaders/ps_texoff.asm +++ /dev/null @@ -1,141 +0,0 @@ -; Texel offsets (image_sample*_o, image_gather4_lz_o) on a real texture. docs/design.md, "Texel offsets": the first -; address dword packs signed 6-bit offsets, x = [5:0], y = [13:8]; the translator turns them into the SPIR-V Offset -; operand (always a run-time value there, also when the shader loads the dword from an immediate: VK_KHR_maintenance8 -; outside gather, shaderImageGatherExtended for gather). -; Run: vk_texture_test ps_texoff.spv out.raw 2 92 0 0 0 (VKT_NEED_MAINTENANCE8=1: exit 77 without the extension) -; The tool puts a T# at heap VA 256 (s[2:3] points at it), binds an 8x8 RGBA8 texture whose texel (x, y) is -; r = 32x/255, g = 32y/255, with a point (nearest) sampler that clamps to the edge (S# 0x92, 0, 0, 0: clamp x/y/z, -; point filters), and draws 64x64 pixels with attr0.xy = ((px + 0.5) / 64, (py + 0.5) / 64). -; Each sampled channel c is turned back into its texel coordinate with rndne(c * 255/32) (255/32 = 7.96875 exactly), -; so a sample of texel (x, y) reads as the integers x, y. The 1x1 fallback texture (a descriptor miss) reads as 8, 0. -; -; Expected mrt0 words for pixel (px, py), bx = px >> 3, by = py >> 3 (0..7), derived from the rule above and the -; texture, not from a run: -; .x image_sample_lz_o, offset computed per pixel: ox = bx - 4, oy = by - 4 (-4..3, so the dword is -; (ox & 63) | (oy & 63) << 8, e.g. -4 -> 0x3c, -1 -> 0x3f), at uv = (4.5/8, 4.5/8) = the centre of texel -; (4, 4). Texel read = (4 + ox, 4 + oy) = (bx, by): all 64 offset pairs, each a different texel, none clamped. -; word = bx | by << 4. Offset dropped: 0x44 everywhere. x and y swapped: by | bx << 4. -; .y two samples with the offset dword loaded from an immediate, both at the centre of texel (4, 4): -; A = image_sample_l_o (LOD 0.0), dword 0x023d: x = 0x3d = -3, y = 0x02 = +2 -> texel (1, 6) -; B = image_sample_lz_o, dword 0x2010: x = 0x10 = +16, y = 0x20 = -32 -> texel (20, -28), which the sampler -; clamps to (7, 0). This one tells the field widths apart: a 4-bit field gives (4, 4), a 5-bit signed -; field (0, 4). It is only defined on a device whose minTexelOffset..maxTexelOffset covers -32..16 -; (Vulkan guarantees -8..7); check.py and run_gpu_tests.py judge B only there. -; word = A.x | A.y << 4 | B.x << 8 | B.y << 12 = 1 | 6 << 4 | 7 << 8 | 0 << 12 = 0x0761 -; .z image_gather4_lz_o of red (dmask 1), the per-pixel offset dword of .x, at uv = (0.5, 0.5) = the corner shared -; by texels (3..4, 3..4): the footprint is i0 = 3, i1 = 4 in both axes, moved by the offset and clamped: -; X0 = max(bx - 1, 0), X1 = bx, Y0 = max(by - 1, 0), Y1 = by. Gather order (Vulkan and D3D, component k -> -; v[d + k]): (i0, j1), (i1, j1), (i1, j0), (i0, j0); red holds x. -; word = X0 | X1 << 4 | X1 << 8 | X0 << 12 -; .w the same gather of green (dmask 2), which holds y: word = Y1 | Y1 << 4 | Y0 << 8 | Y0 << 12 -; Examples: pixel (0, 0): 0x00, 0x0761, 0x0000, 0x0000. Pixel (20, 50) (bx 2, by 6): 0x62, 0x0761, 0x1221, 0x5566. -; pixel (63, 63): 0x77, 0x0761, 0x6776, 0x6677. -; Not seen by this test on an AMD Radeon RX 6800 (driver 26.11.2): fields read unsigned. In theory that reads 7 where -; an offset is negative and (7, 7) for B, but there Offset 60..63 sampled as -4..-1 and +32 as -32, so the same words -; came back. The sign extension is checked on the SPIR-V text by tests/test_texel_offsets.py. The gather offsets stay -; in -4..3, so the gather field width is not tested here either (4-bit and 5-bit gather fields pass). -s_load_dwordx8 s[8:15], s[2:3], 0 -s_mov_b32 s16, 0x92 -s_mov_b32 s17, 0 -s_mov_b32 s18, 0 -s_mov_b32 s19, 0 -v_interp_p1_f32_e32 v2, v0, attr0.x -v_interp_p2_f32_e32 v2, v1, attr0.x -v_interp_p1_f32_e32 v3, v0, attr0.y -v_interp_p2_f32_e32 v3, v1, attr0.y -v_mul_f32_e32 v2, 0x41000000, v2 -v_mul_f32_e32 v3, 0x41000000, v3 -v_cvt_u32_f32_e32 v2, v2 -v_cvt_u32_f32_e32 v3, v3 -v_add_nc_u32_e32 v2, -4, v2 -v_add_nc_u32_e32 v3, -4, v3 -v_and_b32_e32 v2, 63, v2 -v_and_b32_e32 v3, 63, v3 -v_lshl_or_b32 v10, v3, 8, v2 -v_mov_b32_e32 v11, 0x3f100000 -v_mov_b32_e32 v12, 0x3f100000 -image_sample_lz_o v[4:5], v[10:12], s[8:15], s[16:19] dmask:0x3 dim:SQ_RSRC_IMG_2D -v_mov_b32_e32 v24, 0x23d -v_mov_b32_e32 v25, 0x3f100000 -v_mov_b32_e32 v26, 0x3f100000 -v_mov_b32_e32 v27, 0 -image_sample_l_o v[6:7], v[24:27], s[8:15], s[16:19] dmask:0x3 dim:SQ_RSRC_IMG_2D -v_mov_b32_e32 v28, 0x2010 -v_mov_b32_e32 v29, 0x3f100000 -v_mov_b32_e32 v30, 0x3f100000 -image_sample_lz_o v[8:9], v[28:30], s[8:15], s[16:19] dmask:0x3 dim:SQ_RSRC_IMG_2D -v_mov_b32_e32 v13, v10 -v_mov_b32_e32 v14, 0.5 -v_mov_b32_e32 v15, 0.5 -image_gather4_lz_o v[16:19], v[13:15], s[8:15], s[16:19] dmask:0x1 dim:SQ_RSRC_IMG_2D -image_gather4_lz_o v[20:23], v[13:15], s[8:15], s[16:19] dmask:0x2 dim:SQ_RSRC_IMG_2D -; A16: preserve a whole offset dword and unpack U from the low and V from the high half. -; From texel (3,5), offsets (bx-3, by-5) reach the same (bx,by) as the full-precision sample in v4:5. -v_add_nc_u32_e32 v44, 1, v2 -v_add_nc_u32_e32 v45, -1, v3 -v_and_b32_e32 v44, 63, v44 -v_and_b32_e32 v45, 63, v45 -v_lshl_or_b32 v44, v45, 8, v44 -v_mov_b32_e32 v45, 0x39803700 -image_sample_lz_o v[46:47], v[44:45], s[8:15], s[16:19] dmask:0x3 dim:SQ_RSRC_IMG_2D a16 -s_waitcnt vmcnt(0) -v_xor_b32_e32 v46, v46, v4 -v_xor_b32_e32 v47, v47, v5 -v_or_b32_e32 v46, v46, v47 -v_mul_f32_e32 v4, 0x40ff0000, v4 -v_rndne_f32_e32 v4, v4 -v_cvt_u32_f32_e32 v4, v4 -v_mul_f32_e32 v5, 0x40ff0000, v5 -v_rndne_f32_e32 v5, v5 -v_cvt_u32_f32_e32 v5, v5 -v_mul_f32_e32 v6, 0x40ff0000, v6 -v_rndne_f32_e32 v6, v6 -v_cvt_u32_f32_e32 v6, v6 -v_mul_f32_e32 v7, 0x40ff0000, v7 -v_rndne_f32_e32 v7, v7 -v_cvt_u32_f32_e32 v7, v7 -v_mul_f32_e32 v8, 0x40ff0000, v8 -v_rndne_f32_e32 v8, v8 -v_cvt_u32_f32_e32 v8, v8 -v_mul_f32_e32 v9, 0x40ff0000, v9 -v_rndne_f32_e32 v9, v9 -v_cvt_u32_f32_e32 v9, v9 -v_mul_f32_e32 v16, 0x40ff0000, v16 -v_rndne_f32_e32 v16, v16 -v_cvt_u32_f32_e32 v16, v16 -v_mul_f32_e32 v17, 0x40ff0000, v17 -v_rndne_f32_e32 v17, v17 -v_cvt_u32_f32_e32 v17, v17 -v_mul_f32_e32 v18, 0x40ff0000, v18 -v_rndne_f32_e32 v18, v18 -v_cvt_u32_f32_e32 v18, v18 -v_mul_f32_e32 v19, 0x40ff0000, v19 -v_rndne_f32_e32 v19, v19 -v_cvt_u32_f32_e32 v19, v19 -v_mul_f32_e32 v20, 0x40ff0000, v20 -v_rndne_f32_e32 v20, v20 -v_cvt_u32_f32_e32 v20, v20 -v_mul_f32_e32 v21, 0x40ff0000, v21 -v_rndne_f32_e32 v21, v21 -v_cvt_u32_f32_e32 v21, v21 -v_mul_f32_e32 v22, 0x40ff0000, v22 -v_rndne_f32_e32 v22, v22 -v_cvt_u32_f32_e32 v22, v22 -v_mul_f32_e32 v23, 0x40ff0000, v23 -v_rndne_f32_e32 v23, v23 -v_cvt_u32_f32_e32 v23, v23 -v_lshl_or_b32 v40, v5, 4, v4 -v_lshl_or_b32 v41, v7, 4, v6 -v_lshl_or_b32 v41, v8, 8, v41 -v_lshl_or_b32 v41, v9, 12, v41 -v_lshl_or_b32 v42, v17, 4, v16 -v_lshl_or_b32 v42, v18, 8, v42 -v_lshl_or_b32 v42, v19, 12, v42 -v_lshl_or_b32 v43, v21, 4, v20 -v_lshl_or_b32 v43, v22, 8, v43 -v_lshl_or_b32 v43, v23, 12, v43 -; A16 mismatch marks .x outside its valid 0x00..0x77 range. -v_cmp_eq_u32_e32 vcc_lo, 0, v46 -v_cndmask_b32_e32 v40, -1, v40, vcc_lo -exp mrt0 v40, v41, v42, v43 done vm -s_endpgm diff --git a/runtime/test/shaders/ps_texoff_forms.asm b/runtime/test/shaders/ps_texoff_forms.asm deleted file mode 100644 index 9076e4a01..000000000 --- a/runtime/test/shaders/ps_texoff_forms.asm +++ /dev/null @@ -1,103 +0,0 @@ -; Texel offsets on the image_sample*_o forms ps_texoff does not run (SHADER-337): image_sample_o (implicit LOD), -; image_sample_b_o (LOD bias) and image_gather4_l_o (explicit LOD). docs/design.md, "Texel offsets": the first address -; dword packs signed 6-bit offsets, x = [5:0], y = [13:8]; the bias (_b) or the LOD (_l) follows the coordinates as -; the MIMG address order puts them: _b_o = {offset, bias, s, t}, _l_o = {offset, s, t, lod}. -; Run: vk_texture_test ps_texoff_forms.spv out.raw 2 92 0 0 0 (VKT_NEED_MAINTENANCE8=1: exit 77 without it) -; Same set-up as ps_texoff.asm: an 8x8 RGBA8 texture whose texel (x, y) is r = 32x/255, g = 32y/255, one mip, a -; point sampler that clamps to the edge (S# 0x92), 64x64 pixels with attr0.xy = ((px + 0.5) / 64, (py + 0.5) / 64). -; Each sampled channel c reads back as its texel coordinate through rndne(c * 255/32). -; -; Every sample uses the per-pixel offset of ps_texoff's .x: ox = bx - 4, oy = by - 4 (bx = px >> 3, by = py >> 3), -; all 64 pairs in -4..3, none clamped by the sample. Expected mrt0 words, derived from the rule and the texture: -; .x image_sample_o at the centre of texel (4, 4); the coordinates are the same in every pixel, so the implicit -; derivatives are 0 and the one mip is sampled: texel (bx, by), word = bx | by << 4. -; .y image_sample_b_o with bias 0.0 at the same point: word = bx | by << 4. -; .z image_gather4_l_o of red (dmask 1, LOD 0.0) at uv (0.5, 0.5), the corner of texels 3..4: X0 = max(bx - 1, 0), -; X1 = bx; gather order (i0, j1), (i1, j1), (i1, j0), (i0, j0): word = X0 | X1 << 4 | X1 << 8 | X0 << 12. -; .w the same gather of green: word = Y1 | Y1 << 4 | Y0 << 8 | Y0 << 12 (Y0 = max(by - 1, 0), Y1 = by). -; .z and .w are ps_texoff's gather words (check.py texoff_words). Dropping the offset gives 0x44 in .x and .y; x and y -; swapped give by | bx << 4. -s_load_dwordx8 s[8:15], s[2:3], 0 -s_mov_b32 s16, 0x92 -s_mov_b32 s17, 0 -s_mov_b32 s18, 0 -s_mov_b32 s19, 0 -v_interp_p1_f32_e32 v2, v0, attr0.x -v_interp_p2_f32_e32 v2, v1, attr0.x -v_interp_p1_f32_e32 v3, v0, attr0.y -v_interp_p2_f32_e32 v3, v1, attr0.y -v_mul_f32_e32 v2, 0x41000000, v2 -v_mul_f32_e32 v3, 0x41000000, v3 -v_cvt_u32_f32_e32 v2, v2 -v_cvt_u32_f32_e32 v3, v3 -v_add_nc_u32_e32 v2, -4, v2 -v_add_nc_u32_e32 v3, -4, v3 -v_and_b32_e32 v2, 63, v2 -v_and_b32_e32 v3, 63, v3 -v_lshl_or_b32 v10, v3, 8, v2 -v_mov_b32_e32 v11, 0x3f100000 -v_mov_b32_e32 v12, 0x3f100000 -s_waitcnt lgkmcnt(0) -image_sample_o v[4:5], v[10:12], s[8:15], s[16:19] dmask:0x3 dim:SQ_RSRC_IMG_2D -v_mov_b32_e32 v24, v10 -v_mov_b32_e32 v25, 0 -v_mov_b32_e32 v26, 0x3f100000 -v_mov_b32_e32 v27, 0x3f100000 -image_sample_b_o v[6:7], v[24:27], s[8:15], s[16:19] dmask:0x3 dim:SQ_RSRC_IMG_2D -v_mov_b32_e32 v13, v10 -v_mov_b32_e32 v14, 0.5 -v_mov_b32_e32 v15, 0.5 -v_mov_b32_e32 v28, 0 -v_mov_b32_e32 v29, v10 -v_mov_b32_e32 v30, 0.5 -v_mov_b32_e32 v31, 0.5 -v_mov_b32_e32 v32, 0 -image_gather4_l_o v[16:19], v[29:32], s[8:15], s[16:19] dmask:0x1 dim:SQ_RSRC_IMG_2D -image_gather4_l_o v[20:23], v[29:32], s[8:15], s[16:19] dmask:0x2 dim:SQ_RSRC_IMG_2D -s_waitcnt vmcnt(0) -v_mul_f32_e32 v4, 0x40ff0000, v4 -v_rndne_f32_e32 v4, v4 -v_cvt_u32_f32_e32 v4, v4 -v_mul_f32_e32 v5, 0x40ff0000, v5 -v_rndne_f32_e32 v5, v5 -v_cvt_u32_f32_e32 v5, v5 -v_mul_f32_e32 v6, 0x40ff0000, v6 -v_rndne_f32_e32 v6, v6 -v_cvt_u32_f32_e32 v6, v6 -v_mul_f32_e32 v7, 0x40ff0000, v7 -v_rndne_f32_e32 v7, v7 -v_cvt_u32_f32_e32 v7, v7 -v_mul_f32_e32 v16, 0x40ff0000, v16 -v_rndne_f32_e32 v16, v16 -v_cvt_u32_f32_e32 v16, v16 -v_mul_f32_e32 v17, 0x40ff0000, v17 -v_rndne_f32_e32 v17, v17 -v_cvt_u32_f32_e32 v17, v17 -v_mul_f32_e32 v18, 0x40ff0000, v18 -v_rndne_f32_e32 v18, v18 -v_cvt_u32_f32_e32 v18, v18 -v_mul_f32_e32 v19, 0x40ff0000, v19 -v_rndne_f32_e32 v19, v19 -v_cvt_u32_f32_e32 v19, v19 -v_mul_f32_e32 v20, 0x40ff0000, v20 -v_rndne_f32_e32 v20, v20 -v_cvt_u32_f32_e32 v20, v20 -v_mul_f32_e32 v21, 0x40ff0000, v21 -v_rndne_f32_e32 v21, v21 -v_cvt_u32_f32_e32 v21, v21 -v_mul_f32_e32 v22, 0x40ff0000, v22 -v_rndne_f32_e32 v22, v22 -v_cvt_u32_f32_e32 v22, v22 -v_mul_f32_e32 v23, 0x40ff0000, v23 -v_rndne_f32_e32 v23, v23 -v_cvt_u32_f32_e32 v23, v23 -v_lshl_or_b32 v40, v5, 4, v4 -v_lshl_or_b32 v41, v7, 4, v6 -v_lshl_or_b32 v42, v17, 4, v16 -v_lshl_or_b32 v42, v18, 8, v42 -v_lshl_or_b32 v42, v19, 12, v42 -v_lshl_or_b32 v43, v21, 4, v20 -v_lshl_or_b32 v43, v22, 8, v43 -v_lshl_or_b32 v43, v23, 12, v43 -exp mrt0 v40, v41, v42, v43 done vm -s_endpgm diff --git a/runtime/test/shaders/ps_texoff_implicit.asm b/runtime/test/shaders/ps_texoff_implicit.asm deleted file mode 100644 index 55e91b6ec..000000000 --- a/runtime/test/shaders/ps_texoff_implicit.asm +++ /dev/null @@ -1,147 +0,0 @@ -; ps_texoff with its per-pixel-offset sample (.x) as image_sample_o, the implicit-LOD form the corpus uses (all -; 31 texel-offset samples in the 4 PS that need VK_KHR_maintenance8 are image_sample_o). Same texture, sampler -; and expected words as ps_texoff below; checked by the same texoff_problem. With --texel-offset-fallback it -; covers the implicit path: Grad with the original coordinate's derivatives, level from OpImageQueryLod. -; The texture has one mip, so the level is 0 here; uv is constant, so the derivatives are 0. -; -; Texel offsets (image_sample*_o, image_gather4_lz_o) on a real texture. docs/design.md, "Texel offsets": the first -; address dword packs signed 6-bit offsets, x = [5:0], y = [13:8]; the translator turns them into the SPIR-V Offset -; operand (always a run-time value there, also when the shader loads the dword from an immediate: VK_KHR_maintenance8 -; outside gather, shaderImageGatherExtended for gather). -; Run: vk_texture_test ps_texoff.spv out.raw 2 92 0 0 0 (VKT_NEED_MAINTENANCE8=1: exit 77 without the extension) -; The tool puts a T# at heap VA 256 (s[2:3] points at it), binds an 8x8 RGBA8 texture whose texel (x, y) is -; r = 32x/255, g = 32y/255, with a point (nearest) sampler that clamps to the edge (S# 0x92, 0, 0, 0: clamp x/y/z, -; point filters), and draws 64x64 pixels with attr0.xy = ((px + 0.5) / 64, (py + 0.5) / 64). -; Each sampled channel c is turned back into its texel coordinate with rndne(c * 255/32) (255/32 = 7.96875 exactly), -; so a sample of texel (x, y) reads as the integers x, y. The 1x1 fallback texture (a descriptor miss) reads as 8, 0. -; -; Expected mrt0 words for pixel (px, py), bx = px >> 3, by = py >> 3 (0..7), derived from the rule above and the -; texture, not from a run: -; .x image_sample_lz_o, offset computed per pixel: ox = bx - 4, oy = by - 4 (-4..3, so the dword is -; (ox & 63) | (oy & 63) << 8, e.g. -4 -> 0x3c, -1 -> 0x3f), at uv = (4.5/8, 4.5/8) = the centre of texel -; (4, 4). Texel read = (4 + ox, 4 + oy) = (bx, by): all 64 offset pairs, each a different texel, none clamped. -; word = bx | by << 4. Offset dropped: 0x44 everywhere. x and y swapped: by | bx << 4. -; .y two samples with the offset dword loaded from an immediate, both at the centre of texel (4, 4): -; A = image_sample_l_o (LOD 0.0), dword 0x023d: x = 0x3d = -3, y = 0x02 = +2 -> texel (1, 6) -; B = image_sample_lz_o, dword 0x2010: x = 0x10 = +16, y = 0x20 = -32 -> texel (20, -28), which the sampler -; clamps to (7, 0). This one tells the field widths apart: a 4-bit field gives (4, 4), a 5-bit signed -; field (0, 4). It is only defined on a device whose minTexelOffset..maxTexelOffset covers -32..16 -; (Vulkan guarantees -8..7); check.py and run_gpu_tests.py judge B only there. -; word = A.x | A.y << 4 | B.x << 8 | B.y << 12 = 1 | 6 << 4 | 7 << 8 | 0 << 12 = 0x0761 -; .z image_gather4_lz_o of red (dmask 1), the per-pixel offset dword of .x, at uv = (0.5, 0.5) = the corner shared -; by texels (3..4, 3..4): the footprint is i0 = 3, i1 = 4 in both axes, moved by the offset and clamped: -; X0 = max(bx - 1, 0), X1 = bx, Y0 = max(by - 1, 0), Y1 = by. Gather order (Vulkan and D3D, component k -> -; v[d + k]): (i0, j1), (i1, j1), (i1, j0), (i0, j0); red holds x. -; word = X0 | X1 << 4 | X1 << 8 | X0 << 12 -; .w the same gather of green (dmask 2), which holds y: word = Y1 | Y1 << 4 | Y0 << 8 | Y0 << 12 -; Examples: pixel (0, 0): 0x00, 0x0761, 0x0000, 0x0000. Pixel (20, 50) (bx 2, by 6): 0x62, 0x0761, 0x1221, 0x5566. -; pixel (63, 63): 0x77, 0x0761, 0x6776, 0x6677. -; Not seen by this test on an AMD Radeon RX 6800 (driver 26.11.2): fields read unsigned. In theory that reads 7 where -; an offset is negative and (7, 7) for B, but there Offset 60..63 sampled as -4..-1 and +32 as -32, so the same words -; came back. The sign extension is checked on the SPIR-V text by tests/test_texel_offsets.py. The gather offsets stay -; in -4..3, so the gather field width is not tested here either (4-bit and 5-bit gather fields pass). -s_load_dwordx8 s[8:15], s[2:3], 0 -s_mov_b32 s16, 0x92 -s_mov_b32 s17, 0 -s_mov_b32 s18, 0 -s_mov_b32 s19, 0 -v_interp_p1_f32_e32 v2, v0, attr0.x -v_interp_p2_f32_e32 v2, v1, attr0.x -v_interp_p1_f32_e32 v3, v0, attr0.y -v_interp_p2_f32_e32 v3, v1, attr0.y -v_mul_f32_e32 v2, 0x41000000, v2 -v_mul_f32_e32 v3, 0x41000000, v3 -v_cvt_u32_f32_e32 v2, v2 -v_cvt_u32_f32_e32 v3, v3 -v_add_nc_u32_e32 v2, -4, v2 -v_add_nc_u32_e32 v3, -4, v3 -v_and_b32_e32 v2, 63, v2 -v_and_b32_e32 v3, 63, v3 -v_lshl_or_b32 v10, v3, 8, v2 -v_mov_b32_e32 v11, 0x3f100000 -v_mov_b32_e32 v12, 0x3f100000 -image_sample_o v[4:5], v[10:12], s[8:15], s[16:19] dmask:0x3 dim:SQ_RSRC_IMG_2D -v_mov_b32_e32 v24, 0x23d -v_mov_b32_e32 v25, 0x3f100000 -v_mov_b32_e32 v26, 0x3f100000 -v_mov_b32_e32 v27, 0 -image_sample_l_o v[6:7], v[24:27], s[8:15], s[16:19] dmask:0x3 dim:SQ_RSRC_IMG_2D -v_mov_b32_e32 v28, 0x2010 -v_mov_b32_e32 v29, 0x3f100000 -v_mov_b32_e32 v30, 0x3f100000 -image_sample_lz_o v[8:9], v[28:30], s[8:15], s[16:19] dmask:0x3 dim:SQ_RSRC_IMG_2D -v_mov_b32_e32 v13, v10 -v_mov_b32_e32 v14, 0.5 -v_mov_b32_e32 v15, 0.5 -image_gather4_lz_o v[16:19], v[13:15], s[8:15], s[16:19] dmask:0x1 dim:SQ_RSRC_IMG_2D -image_gather4_lz_o v[20:23], v[13:15], s[8:15], s[16:19] dmask:0x2 dim:SQ_RSRC_IMG_2D -; A16: preserve a whole offset dword and unpack U from the low and V from the high half. -; From texel (3,5), offsets (bx-3, by-5) reach the same (bx,by) as the full-precision sample in v4:5. -v_add_nc_u32_e32 v44, 1, v2 -v_add_nc_u32_e32 v45, -1, v3 -v_and_b32_e32 v44, 63, v44 -v_and_b32_e32 v45, 63, v45 -v_lshl_or_b32 v44, v45, 8, v44 -v_mov_b32_e32 v45, 0x39803700 -image_sample_lz_o v[46:47], v[44:45], s[8:15], s[16:19] dmask:0x3 dim:SQ_RSRC_IMG_2D a16 -s_waitcnt vmcnt(0) -v_xor_b32_e32 v46, v46, v4 -v_xor_b32_e32 v47, v47, v5 -v_or_b32_e32 v46, v46, v47 -v_mul_f32_e32 v4, 0x40ff0000, v4 -v_rndne_f32_e32 v4, v4 -v_cvt_u32_f32_e32 v4, v4 -v_mul_f32_e32 v5, 0x40ff0000, v5 -v_rndne_f32_e32 v5, v5 -v_cvt_u32_f32_e32 v5, v5 -v_mul_f32_e32 v6, 0x40ff0000, v6 -v_rndne_f32_e32 v6, v6 -v_cvt_u32_f32_e32 v6, v6 -v_mul_f32_e32 v7, 0x40ff0000, v7 -v_rndne_f32_e32 v7, v7 -v_cvt_u32_f32_e32 v7, v7 -v_mul_f32_e32 v8, 0x40ff0000, v8 -v_rndne_f32_e32 v8, v8 -v_cvt_u32_f32_e32 v8, v8 -v_mul_f32_e32 v9, 0x40ff0000, v9 -v_rndne_f32_e32 v9, v9 -v_cvt_u32_f32_e32 v9, v9 -v_mul_f32_e32 v16, 0x40ff0000, v16 -v_rndne_f32_e32 v16, v16 -v_cvt_u32_f32_e32 v16, v16 -v_mul_f32_e32 v17, 0x40ff0000, v17 -v_rndne_f32_e32 v17, v17 -v_cvt_u32_f32_e32 v17, v17 -v_mul_f32_e32 v18, 0x40ff0000, v18 -v_rndne_f32_e32 v18, v18 -v_cvt_u32_f32_e32 v18, v18 -v_mul_f32_e32 v19, 0x40ff0000, v19 -v_rndne_f32_e32 v19, v19 -v_cvt_u32_f32_e32 v19, v19 -v_mul_f32_e32 v20, 0x40ff0000, v20 -v_rndne_f32_e32 v20, v20 -v_cvt_u32_f32_e32 v20, v20 -v_mul_f32_e32 v21, 0x40ff0000, v21 -v_rndne_f32_e32 v21, v21 -v_cvt_u32_f32_e32 v21, v21 -v_mul_f32_e32 v22, 0x40ff0000, v22 -v_rndne_f32_e32 v22, v22 -v_cvt_u32_f32_e32 v22, v22 -v_mul_f32_e32 v23, 0x40ff0000, v23 -v_rndne_f32_e32 v23, v23 -v_cvt_u32_f32_e32 v23, v23 -v_lshl_or_b32 v40, v5, 4, v4 -v_lshl_or_b32 v41, v7, 4, v6 -v_lshl_or_b32 v41, v8, 8, v41 -v_lshl_or_b32 v41, v9, 12, v41 -v_lshl_or_b32 v42, v17, 4, v16 -v_lshl_or_b32 v42, v18, 8, v42 -v_lshl_or_b32 v42, v19, 12, v42 -v_lshl_or_b32 v43, v21, 4, v20 -v_lshl_or_b32 v43, v22, 8, v43 -v_lshl_or_b32 v43, v23, 12, v43 -; A16 mismatch marks .x outside its valid 0x00..0x77 range. -v_cmp_eq_u32_e32 vcc_lo, 0, v46 -v_cndmask_b32_e32 v40, -1, v40, vcc_lo -exp mrt0 v40, v41, v42, v43 done vm -s_endpgm diff --git a/runtime/test/shaders/ps_texture_b_cl.asm b/runtime/test/shaders/ps_texture_b_cl.asm deleted file mode 100644 index ba8970667..000000000 --- a/runtime/test/shaders/ps_texture_b_cl.asm +++ /dev/null @@ -1,23 +0,0 @@ -; image_sample_b_cl: as ps_texture_cl with a LOD bias of 0.0 in front of the coordinates (address v[3:6] = bias, -; u / 4, v / 4, clamp), so the bias and the clamp each have to come from their own VGPR. Left half mip 0 (red), right -; half mip 1 (cyan). A bias read from the clamp's register (1.0) would still give cyan on the right but also move the -; left half to mip 1; the clamp read as the bias would never clamp. -v_interp_p1_f32_e32 v2, v0, attr0.x -v_interp_p2_f32_e32 v2, v1, attr0.x -v_interp_p1_f32_e32 v3, v0, attr0.y -v_interp_p2_f32_e32 v3, v1, attr0.y -s_load_dwordx8 s[8:15], s[0:1], 0x0 -s_waitcnt lgkmcnt(0) -s_mov_b32 s16, 0x92 -s_mov_b32 s17, 0xc00000 -s_mov_b32 s18, 0x14500000 -s_mov_b32 s19, 0 -v_cmp_le_f32_e32 vcc_lo, 0.5, v2 -v_mul_f32_e32 v4, 0.25, v2 -v_mul_f32_e32 v5, 0.25, v3 -v_mov_b32_e32 v3, 0 -v_cndmask_b32_e64 v6, 0, 1.0, vcc_lo -image_sample_b_cl v[8:11], v[3:6], s[8:15], s[16:19] dmask:0xf dim:SQ_RSRC_IMG_2D -s_waitcnt vmcnt(0) -exp mrt0 v8, v9, v10, v11 done vm -s_endpgm diff --git a/runtime/test/shaders/ps_texture_bias_a16.asm b/runtime/test/shaders/ps_texture_bias_a16.asm deleted file mode 100644 index aadc5b635..000000000 --- a/runtime/test/shaders/ps_texture_bias_a16.asm +++ /dev/null @@ -1,20 +0,0 @@ -; Sample the synthetic 8x8 gradient in vk_texture_test with image_sample_b ... a16. The bias (+1.0, an f16 in the low -; half) keeps its own VGPR and only the two f16 coordinates after it are packed: read as pairs, the coordinates come -; out a half early. The texture has one mip, so the bias changes nothing. The expected RGBA at each pixel is -; (32*floor(x/8)/255, 32*floor(y/8)/255, 128/255, 1) over the 64x64 framebuffer. -v_interp_p1_f32_e32 v2, v0, attr0.x -v_interp_p2_f32_e32 v2, v1, attr0.x -v_interp_p1_f32_e32 v3, v0, attr0.y -v_interp_p2_f32_e32 v3, v1, attr0.y -s_load_dwordx8 s[8:15], s[0:1], 0x0 -s_waitcnt lgkmcnt(0) -s_mov_b32 s16, 0x92 -s_mov_b32 s17, 0xc00000 -s_mov_b32 s18, 0x14500000 -s_mov_b32 s19, 0 -v_mov_b32_e32 v8, 0x3c00 -v_cvt_pkrtz_f16_f32 v9, v2, v3 -image_sample_b v[4:7], v[8:9], s[8:15], s[16:19] dmask:0xf dim:SQ_RSRC_IMG_2D a16 -s_waitcnt vmcnt(0) -exp mrt0 v4, v5, v6, v7 done vm -s_endpgm diff --git a/runtime/test/shaders/ps_texture_cl.asm b/runtime/test/shaders/ps_texture_cl.asm deleted file mode 100644 index 932427c9d..000000000 --- a/runtime/test/shaders/ps_texture_cl.asm +++ /dev/null @@ -1,23 +0,0 @@ -; image_sample_cl on vk_texture_test's two-mip texture (--two-mip: 128x128 quadrants, solid cyan mip 1) drawn on 64x64: -; the coordinates are u / 4, v / 4, so the unclamped LOD is -1 (mip 0, the top-left quadrant, red). The min-LOD clamp -; after the coordinates is 0.0 left of x = 32 and 1.0 from there on: the left half must read mip 0 (red), the right half -; mip 1 (cyan). A clamp read from the wrong register, or ignored, makes the right half red too. -; Address v[4:6] = (u / 4, v / 4, clamp); MinLod on an implicit-LOD sample (OpImageSampleImplicitLod ... MinLod). -v_interp_p1_f32_e32 v2, v0, attr0.x -v_interp_p2_f32_e32 v2, v1, attr0.x -v_interp_p1_f32_e32 v3, v0, attr0.y -v_interp_p2_f32_e32 v3, v1, attr0.y -s_load_dwordx8 s[8:15], s[0:1], 0x0 -s_waitcnt lgkmcnt(0) -s_mov_b32 s16, 0x92 -s_mov_b32 s17, 0xc00000 -s_mov_b32 s18, 0x14500000 -s_mov_b32 s19, 0 -v_cmp_le_f32_e32 vcc_lo, 0.5, v2 -v_mul_f32_e32 v4, 0.25, v2 -v_mul_f32_e32 v5, 0.25, v3 -v_cndmask_b32_e64 v6, 0, 1.0, vcc_lo -image_sample_cl v[8:11], v[4:6], s[8:15], s[16:19] dmask:0xf dim:SQ_RSRC_IMG_2D -s_waitcnt vmcnt(0) -exp mrt0 v8, v9, v10, v11 done vm -s_endpgm diff --git a/runtime/test/shaders/ps_texture_grad_a16.asm b/runtime/test/shaders/ps_texture_grad_a16.asm deleted file mode 100644 index f9a3bf9f0..000000000 --- a/runtime/test/shaders/ps_texture_grad_a16.asm +++ /dev/null @@ -1,22 +0,0 @@ -; Sample the synthetic 8x8 gradient in vk_texture_test. image_sample_d with a16 keeps the four -; derivatives as f32 and packs only the two f16 coordinates. The expected RGBA at each pixel is -; (32*floor(x/8)/255, 32*floor(y/8)/255, 128/255, 1) over the 64x64 framebuffer. -v_interp_p1_f32_e32 v2, v0, attr0.x -v_interp_p2_f32_e32 v2, v1, attr0.x -v_interp_p1_f32_e32 v3, v0, attr0.y -v_interp_p2_f32_e32 v3, v1, attr0.y -s_load_dwordx8 s[8:15], s[0:1], 0x0 -s_waitcnt lgkmcnt(0) -s_mov_b32 s16, 0x92 -s_mov_b32 s17, 0xc00000 -s_mov_b32 s18, 0x14500000 -s_mov_b32 s19, 0 -v_mov_b32_e32 v8, 0x3c800000 ; du/dx = 1/64 -v_mov_b32_e32 v9, 0 ; dv/dx -v_mov_b32_e32 v10, 0 ; du/dy -v_mov_b32_e32 v11, 0x3c800000 ; dv/dy = 1/64 -v_cvt_pkrtz_f16_f32 v12, v2, v3 -image_sample_d v[4:7], v[8:12], s[8:15], s[16:19] dmask:0xf dim:SQ_RSRC_IMG_2D a16 -s_waitcnt vmcnt(0) -exp mrt0 v4, v5, v6, v7 done vm -s_endpgm diff --git a/runtime/test/shaders/ps_texture_grad_cl_a16.asm b/runtime/test/shaders/ps_texture_grad_cl_a16.asm deleted file mode 100644 index c18991979..000000000 --- a/runtime/test/shaders/ps_texture_grad_cl_a16.asm +++ /dev/null @@ -1,29 +0,0 @@ -; Sample vk_texture_test's two-mip texture (--two-mip: 128x128 quadrants, solid cyan mip 1) with -; image_sample_d_cl ... a16: the four derivatives stay f32 (1/128, so the unclamped LOD is 0), then the two f16 -; coordinates and the f16 min-LOD clamp are packed, with an f16 pad of 1.0 after the clamp. The clamp is 0.0 left of -; x = 32 and 1.0 from there on, so the left half must read mip 0 (red over blue) and the right half mip 1 (cyan). -; Taken from the pad the clamp would be 1.0 everywhere, and read as pairs the derivatives and coordinates would come -; from the wrong words. -v_interp_p1_f32_e32 v2, v0, attr0.x -v_interp_p2_f32_e32 v2, v1, attr0.x -v_interp_p1_f32_e32 v3, v0, attr0.y -v_interp_p2_f32_e32 v3, v1, attr0.y -s_load_dwordx8 s[8:15], s[0:1], 0x0 -s_waitcnt lgkmcnt(0) -s_mov_b32 s16, 0x92 -s_mov_b32 s17, 0xc00000 -s_mov_b32 s18, 0x14500000 -s_mov_b32 s19, 0 -v_mov_b32_e32 v8, 0x3c000000 ; du/dx = 1/128 -v_mov_b32_e32 v9, 0 ; dv/dx -v_mov_b32_e32 v10, 0 ; du/dy -v_mov_b32_e32 v11, 0x3c000000 ; dv/dy = 1/128 -v_cvt_pkrtz_f16_f32 v12, v2, v3 -v_mov_b32_e32 v14, 0x3c000000 ; clamp 0.0, pad 1.0 -v_mov_b32_e32 v15, 0x3c003c00 ; clamp 1.0, pad 1.0 -v_cmp_le_f32_e32 vcc_lo, 0.5, v2 -v_cndmask_b32_e32 v13, v14, v15, vcc_lo -image_sample_d_cl v[4:7], v[8:13], s[8:15], s[16:19] dmask:0xf dim:SQ_RSRC_IMG_2D a16 -s_waitcnt vmcnt(0) -exp mrt0 v4, v5, v6, v7 done vm -s_endpgm diff --git a/runtime/test/shaders/ps_texture_mip0.asm b/runtime/test/shaders/ps_texture_mip0.asm deleted file mode 100644 index 7b3a2bea5..000000000 --- a/runtime/test/shaders/ps_texture_mip0.asm +++ /dev/null @@ -1,18 +0,0 @@ -; Explicit mip-zero sampling, paired with the implicit ps_texture_sample test. -; vk_texture_test --two-mip draws 64x64 pixels from a 128x128 base level and 64x64 mip 1. -; This shader must yield red, green, blue and transparent yellow in the four base-level quadrants. -; The implicit pass must yield opaque cyan across mip 1. -v_interp_p1_f32_e32 v2, v0, attr0.x -v_interp_p2_f32_e32 v2, v1, attr0.x -v_interp_p1_f32_e32 v3, v0, attr0.y -v_interp_p2_f32_e32 v3, v1, attr0.y -s_load_dwordx8 s[8:15], s[0:1], 0x0 -s_waitcnt lgkmcnt(0) -s_mov_b32 s16, 0x92 -s_mov_b32 s17, 0xc00000 -s_mov_b32 s18, 0x14500000 -s_mov_b32 s19, 0 -image_sample_lz v[4:7], v[2:3], s[8:15], s[16:19] dmask:0xf dim:SQ_RSRC_IMG_2D -s_waitcnt vmcnt(0) -exp mrt0 v4, v5, v6, v7 done vm -s_endpgm diff --git a/runtime/test/shaders/ps_texture_sample.asm b/runtime/test/shaders/ps_texture_sample.asm deleted file mode 100644 index 35e3c6ddb..000000000 --- a/runtime/test/shaders/ps_texture_sample.asm +++ /dev/null @@ -1,22 +0,0 @@ -; Texture sampling test: samples a 2D texture (T# at s[8:15] loaded via s[0:1], S# at s[16:19]) -; using normalized UV coordinates from attr0, outputs sampled color to mrt0. -; Run: vk_texture_test (autonomously, or with vs.spv fs.spv out.raw ptr_sgpr s0 s1 s2 s3) -; -> verifies center pixel = gradient color (0.5, 0.5, 0.5, 1.0) sampled via descriptor table -; s[0:1] = 64-bit pointer to T# in GPU heap -; s[8:15] = 8-dword T# (image descriptor) -; s[16:19] = 4-dword S# (sampler descriptor) -; v[0:1] = barycentric UV coordinates -v_interp_p1_f32_e32 v2, v0, attr0.x -v_interp_p2_f32_e32 v2, v1, attr0.x -v_interp_p1_f32_e32 v3, v0, attr0.y -v_interp_p2_f32_e32 v3, v1, attr0.y -s_load_dwordx8 s[8:15], s[0:1], 0x0 -s_waitcnt lgkmcnt(0) -s_mov_b32 s16, 0x92 -s_mov_b32 s17, 0xc00000 -s_mov_b32 s18, 0x14500000 -s_mov_b32 s19, 0 -image_sample v[4:7], v[2:3], s[8:15], s[16:19] dmask:0xf dim:SQ_RSRC_IMG_2D -s_waitcnt vmcnt(0) -exp mrt0 v4, v5, v6, v7 done vm -s_endpgm diff --git a/runtime/test/shaders/ps_texture_sample_d16.asm b/runtime/test/shaders/ps_texture_sample_d16.asm deleted file mode 100644 index 1e9030a96..000000000 --- a/runtime/test/shaders/ps_texture_sample_d16.asm +++ /dev/null @@ -1,24 +0,0 @@ -; Texture sampling test with d16: samples a 2D texture into packed f16 pairs (v4=r|g<<16, v5=b|a<<16), -; then unpacks the four f16 halves back to f32 and outputs to mrt0. -; Run: vk_texture_test vs_ids.spv ps_texture_sample_d16.spv out.raw 0 0 0 0 0 -; -> 64x64 RGBA32F readback: each component is the nearest gradient texel's UNORM8 value rounded to f16, then widened. -v_interp_p1_f32_e32 v2, v0, attr0.x -v_interp_p2_f32_e32 v2, v1, attr0.x -v_interp_p1_f32_e32 v3, v0, attr0.y -v_interp_p2_f32_e32 v3, v1, attr0.y -s_load_dwordx8 s[8:15], s[0:1], 0x0 -s_waitcnt lgkmcnt(0) -s_mov_b32 s16, 0x92 -s_mov_b32 s17, 0xc00000 -s_mov_b32 s18, 0x14500000 -s_mov_b32 s19, 0 -image_sample v[4:5], v[2:3], s[8:15], s[16:19] dmask:0xf dim:SQ_RSRC_IMG_2D d16 -s_waitcnt vmcnt(0) -v_cvt_f32_f16_e32 v6, v4 -v_lshrrev_b32_e32 v7, 16, v4 -v_cvt_f32_f16_e32 v7, v7 -v_cvt_f32_f16_e32 v8, v5 -v_lshrrev_b32_e32 v9, 16, v5 -v_cvt_f32_f16_e32 v9, v9 -exp mrt0 v6, v7, v8, v9 done vm -s_endpgm diff --git a/runtime/test/shaders/ps_uniform_branch.asm b/runtime/test/shaders/ps_uniform_branch.asm deleted file mode 100644 index d14d2d260..000000000 --- a/runtime/test/shaders/ps_uniform_branch.asm +++ /dev/null @@ -1,10 +0,0 @@ -; Wave-uniform s_cbranch_vccz: lanes with i > 0.27 set VCC; a wave with any set lane runs the scalar add for -; all its lanes. Expected: bit=1 pixels export s5 = 8; some bit=0 pixels (same wave) also 8; the rest 7. -v_cmp_lt_f32 vcc_lo, 0x3e8a3d71, v0 -s_mov_b32 s5, 7 -s_cbranch_vccz 1 -s_add_u32 s5, s5, 1 -v_mov_b32 v3, s5 -v_cndmask_b32_e64 v4, 0, 1, vcc_lo -exp mrt0 v3, v4, v0, v0 done vm -s_endpgm diff --git a/runtime/test/shaders/ps_valu16_mad.asm b/runtime/test/shaders/ps_valu16_mad.asm deleted file mode 100644 index 7ac0ff2d5..000000000 --- a/runtime/test/shaders/ps_valu16_mad.asm +++ /dev/null @@ -1,32 +0,0 @@ -; regen_fixtures: this source has a translator fixture in tests/semantic/fixtures/disasm -; v_mad_u32_u16 / v_mad_i32_i16 (VOP3-only on GFX10): D = S0.half * S1.half + S2, wrapping at 32 bits. The halves -; are zero-extended (u16) or sign-extended (i16); op_sel bit 0 / 1 picks the high half of S0 / S1. S2 and D are whole -; dwords, so D is written in full: the destinations start as 0xaaaa5555 and none of that may survive. The source -; high halves hold other values, so a read of the wrong half shows up. RDNA2 ISA pseudocode: -; v_mad_u32_u16: D.u32 = S0.u16 * S1.u16 + S2.u32 v_mad_i32_i16: D.i32 = S0.i16 * S1.i16 + S2.i32 -; v0 = 0x1234ffff (low 0xffff = -1 as i16), v1 = 0x5678fffe (low 0xfffe = -2), v3 = 0x00030000 -; v5 = 0x00018000 (low 0x8000 = -32768, high 0x0001), v6 = 0xffff7fff (low 0x7fff = 32767, high 0xffff = -1) -; v7 = 0x40000000 -; x: v_mad_u32_u16 v2, v0, v1, v3: 0xffff * 0xfffe = 0xfffd0002; + 0x00030000 = 0x1_00000002, wraps to 0x00000002 -; y: v_mad_i32_i16 v4, v0, v1, v3: (-1) * (-2) = 2; + 0x00030000 = 0x00030002 (zero-extending would give 0x00000002) -; z: v_mad_i32_i16 v8, v5, v6, v7: -32768 * 32767 = -1073709056 = 0xc0008000; + 0x40000000 = 0x00008000 -; (zero-extending: 0x3fff8000 + 0x40000000 = 0x7fff8000) -; w: v_mad_i32_i16 v9, v5, v6, 5 op_sel:[1,1,0,0]: high halves 1 * (-1) = -1; + 5 = 0x00000004 -; (zero-extended high halves: 0xffff + 5 = 0x00010004; low halves: 0xc0008005) -; Expected mrt0 bits: 0x00000002, 0x00030002, 0x00008000, 0x00000004 -v_mov_b32 v0, 0x1234ffff -v_mov_b32 v1, 0x5678fffe -v_mov_b32 v3, 0x00030000 -v_mov_b32 v5, 0x00018000 -v_mov_b32 v6, 0xffff7fff -v_mov_b32 v7, 0x40000000 -v_mov_b32 v2, 0xaaaa5555 -v_mov_b32 v4, 0xaaaa5555 -v_mov_b32 v8, 0xaaaa5555 -v_mov_b32 v9, 0xaaaa5555 -v_mad_u32_u16 v2, v0, v1, v3 -v_mad_i32_i16 v4, v0, v1, v3 -v_mad_i32_i16 v8, v5, v6, v7 -v_mad_i32_i16 v9, v5, v6, 5 op_sel:[1,1,0,0] -exp mrt0 v2, v4, v8, v9 done vm -s_endpgm diff --git a/runtime/test/shaders/ps_valu16_mad_sel.asm b/runtime/test/shaders/ps_valu16_mad_sel.asm deleted file mode 100644 index 8ce104b3e..000000000 --- a/runtime/test/shaders/ps_valu16_mad_sel.asm +++ /dev/null @@ -1,36 +0,0 @@ -; regen_fixtures: this source has a translator fixture in tests/semantic/fixtures/disasm -; v_mad_u32_u16 / v_mad_i32_i16 with op_sel on S2 or D and with clamp, the forms the translator used to refuse. -; Measured on an AMD Radeon iGPU (gfx1036, RDNA2, Windows driver 26.10.1) with raw kernels through tools/hw_oracle, -; wave32 and wave64 alike (EGEN-HW-MAD-U32-U16): -; op_sel bit 2 (S2) adds S2[31:16] zero-extended, in the i16 op too (S2 = 0xffff8000 adds 0xffff, not -1); -; op_sel bit 3 (D) writes the 32-bit result shifted left by 16: its low half to D's high half, 0 to D's low half; -; clamp saturates the 32-bit sum, to [0, 0xffffffff] (u16) or [0x80000000, 0x7fffffff] (i16), before that shift. -; Otherwise as ps_valu16_mad: D = S0.half * S1.half + S2 mod 2^32, the halves zero- (u16) or sign-extended (i16), -; op_sel bit 0 / 1 picks the high half of S0 / S1; the destinations' 0xaaaa5555 is never kept. -; v0 = 0x1234ffff, v1 = 0x5678fffe, v3 = 0x8001fff0 (high half 0x8001: negative as an i16) -; v5 = 0x00018000 (low -32768), v6 = 0xffff7fff (low 32767), v7 = 0x80000000 -; x: v_mad_i32_i16 v2, v0, v1, v3 op_sel:[0,0,1,0]: (-1) * (-2) = 2; + 0x8001 = 0x00008003 -; (S2 high half sign-extended: 0xffff8003; whole S2: 0x8001fff2) -; y: v_mad_u32_u16 v4, v0, v1, v3 op_sel:[1,0,0,1]: 0x1234 * 0xfffe = 0x1233db98; + 0x8001fff0 = 0x9235db88; -; << 16 = 0xdb880000 -; z: v_mad_u32_u16 v8, v0, v0, v3 clamp: 0xffff * 0xffff = 0xfffe0001; + 0x8001fff0 = 0x1_7ffffff1 > 0xffffffff, -; so 0xffffffff (wrapping: 0x7ffffff1) -; w: v_mad_i32_i16 v9, v5, v6, v7 clamp: -32768 * 32767 = -1073709056; + (-2^31) < -2^31, so 0x80000000 -; (wrapping: 0x40008000) -; Expected mrt0 bits: 0x00008003, 0xdb880000, 0xffffffff, 0x80000000 -v_mov_b32 v0, 0x1234ffff -v_mov_b32 v1, 0x5678fffe -v_mov_b32 v3, 0x8001fff0 -v_mov_b32 v5, 0x00018000 -v_mov_b32 v6, 0xffff7fff -v_mov_b32 v7, 0x80000000 -v_mov_b32 v2, 0xaaaa5555 -v_mov_b32 v4, 0xaaaa5555 -v_mov_b32 v8, 0xaaaa5555 -v_mov_b32 v9, 0xaaaa5555 -v_mad_i32_i16 v2, v0, v1, v3 op_sel:[0,0,1,0] -v_mad_u32_u16 v4, v0, v1, v3 op_sel:[1,0,0,1] -v_mad_u32_u16 v8, v0, v0, v3 clamp -v_mad_i32_i16 v9, v5, v6, v7 clamp -exp mrt0 v2, v4, v8, v9 done vm -s_endpgm diff --git a/runtime/test/shaders/ps_valu16_subrev.asm b/runtime/test/shaders/ps_valu16_subrev.asm deleted file mode 100644 index 3f571342e..000000000 --- a/runtime/test/shaders/ps_valu16_subrev.asm +++ /dev/null @@ -1,23 +0,0 @@ -; regen_fixtures: this source has a translator fixture in tests/semantic/fixtures/disasm -; v_subrev_f16 (VOP2 0x34 on GFX10): D.f16 = S1.f16 - S0.f16. Like the other f16 VOP2 ops it is a partial write -; (docs/design.md, "16-bit results", from Mesa ACO): the low halves are read, the result goes to the low half and the -; high half of the destination is kept, in the VOP2 (_e32) and the VOP3 (_e64) form. neg/clamp in the _e64 form. -; v0 = 1.5 | 4.0 << 16 (0x44003e00), v1 = 0.5 | 2.0 << 16 (0x40003800); v2..v4 start as 0xaaaa5555, -; v5 as 1.0 | 3.0 << 16 (0x42003c00). -; x: v_subrev_f16 v2, v0, v1: 0.5 - 1.5 = -1.0 = 0xbc00 -> 0xaaaabc00 (v_sub order would give 0x3c00) -; y: v_subrev_f16_e64 v3, v0, -v1: -0.5 - 1.5 = -2.0 = 0xc000 -> 0xaaaac000 -; z: v_subrev_f16_e64 v4, -v0, v1 clamp: 0.5 - (-1.5) = 2.0, clamped to 1.0 = 0x3c00 -> 0xaaaa3c00 -; w: v_subrev_f16 v5, v5, v0 (dst = src0): 1.5 - 1.0 = 0.5 = 0x3800, high half 3.0 kept -> 0x42003800 -; Expected mrt0 bits: 0xaaaabc00, 0xaaaac000, 0xaaaa3c00, 0x42003800 -v_mov_b32 v0, 0x44003e00 -v_mov_b32 v1, 0x40003800 -v_mov_b32 v2, 0xaaaa5555 -v_mov_b32 v3, 0xaaaa5555 -v_mov_b32 v4, 0xaaaa5555 -v_mov_b32 v5, 0x42003c00 -v_subrev_f16 v2, v0, v1 -v_subrev_f16_e64 v3, v0, -v1 -v_subrev_f16_e64 v4, -v0, v1 clamp -v_subrev_f16 v5, v5, v0 -exp mrt0 v2, v3, v4, v5 done vm -s_endpgm diff --git a/runtime/test/shaders/ps_vcc_x2.asm b/runtime/test/shaders/ps_vcc_x2.asm deleted file mode 100644 index b79590bc2..000000000 --- a/runtime/test/shaders/ps_vcc_x2.asm +++ /dev/null @@ -1,11 +0,0 @@ -; regen_fixtures: this source has a translator fixture in tests/semantic/fixtures/disasm -; s_buffer_load_dwordx2 into VCC: the low dword lands in vcc_lo, the high dword in vcc_hi. -; The V# in s[0:3] points at 0x1000; the test seeds memory with 0x11223344 and 0x55667788 there. -; Expected mrt0 bits: 0x11223344, 0x55667788, 0, 0 -s_buffer_load_dwordx2 vcc, s[0:3], 0 -s_waitcnt vmcnt(0) -v_mov_b32_e32 v1, vcc_lo -v_mov_b32_e32 v2, vcc_hi -v_mov_b32_e32 v3, 0 -exp mrt0 v1, v2, v3, v3 done vm -s_endpgm diff --git a/runtime/test/shaders/ps_vcmp_64.asm b/runtime/test/shaders/ps_vcmp_64.asm deleted file mode 100644 index 2573b46e7..000000000 --- a/runtime/test/shaders/ps_vcmp_64.asm +++ /dev/null @@ -1,284 +0,0 @@ -; regen_fixtures: this source has a translator fixture in tests/semantic/fixtures/disasm -; 64-bit integer VOPC compares: v_cmp_{lt,le,gt,ge}_{u64,i64}, v_cmp_ne_u64, v_cmp_{eq,ne}_i64 (e32 VCC and e64 -; SGPR destination) and v_cmpx_{lt,ge,ne}_i64 / v_cmpx_{gt,le}_u64 (EXEC copied out and put back after each one). -; Only v_cmp_eq_u64 / v_cmpx_eq_u64 had a test. Inputs read from memory at run time: the V# in s[0:3] points at -; 0x1000 (num_records 64) and the test seeds 16 dwords, four pairs (A, B) as A.lo A.hi B.lo B.hi: -; Q0: A = 0x00000000_80000000 B = 0x00000000_00000001 (equal high words; low words differ in bit 31) -; Q1: A = 0xffffffff_ffffffff B = 0x00000000_00000001 (high words decide; -1 < 1 signed, > unsigned) -; Q2: A = 0x00000000_00000001 B = 0x00000000_80000000 (Q0 swapped) -; Q3: A = 0x00000005_00000007 B = 0x00000005_00000007 (equal) -; RDNA2 ISA: _U64 compares S0.u64 with S1.u64, _I64 compares S0.i64 with S1.i64 (whole 64-bit values; the low word -; is never signed, so Q0 is A > B for both). Bit 4*k + i of a word is op k of that word on pair Qi: -; Q0: u A>B, s A>B Q1: u A>B, s A S1; LG: S0 <> S1 (less or greater); -; GE: S0 >= S1; O: !isNAN(S0) && !isNAN(S1); U: isNAN(S0) || isNAN(S1); NGE = !(S0 >= S1); NLG = !(S0 <> S1); -; NGT = !(S0 > S1); NLE = !(S0 <= S1); NEQ = !(S0 == S1); NLT = !(S0 < S1). -; Every ordered compare with a NaN operand is false, so the N* forms (negations) are true for an unordered pair; +0 == -0; -; the f16 denormals 0x0001 and 0x0002 are kept (they are different numbers, 0x0001 < 0x0002). Cases (A = src0, B = src1, -; the VGPR operand is shown as junk:value, junk = high half that must be ignored): -; k0: A = inline 1.0 (0x3c00), B = 0x1234:0x4000 (2.0) less -; k1: A = inline 2.0 (0x4000), B = 0xabcd:0x3c00 (1.0) greater -; k2: A = inline 0 (+0), B = 0xffff:0x8000 (-0) equal -; k3: A = 0xffff:0x7e00 (qNaN), B = 0x0001:0x3c00 (1.0) unordered -; k4: A = 0x5555:0x3c00 (1.0), B = 0x7c00:0x7c01 (sNaN) unordered -; k5: A = 0x0001:0x7c00 (+inf), B = 0xbeef:0xfc00 (-inf) greater -; k6: A = 0xdead:0x0001 (denormal), B = 0x8000:0x0002 (denormal) less -; Relation sets: LESS = {k0,k6} = 0x41, GREATER = {k1,k5} = 0x22, EQUAL = {k2} = 0x04, UNORDERED = {k3,k4} = 0x18. -; Mask of an op (bit k = result on case k) is the union of the sets it is true for: -; f 0x00 lt 0x41 eq 0x04 le 0x45 gt 0x22 lg 0x63 ge 0x26 o 0x67 -; u 0x18 nge 0x59 nlg 0x1c ngt 0x5d nle 0x3a neq 0x7b nlt 0x3e tru 0x7f -; Word w holds ops 4w..4w+3 (the order above), op j of the word at bit 7*j + k, plus bit 30 so the float export never -; sees a denormal or NaN pattern: -; word 0 = 0x40000000 | 0x00 | 0x41<<7 | 0x04<<14 | 0x45<<21 = 0x40000000 + 0x2080 + 0x10000 + 0x8a00000 = 0x48a12080 -; word 1 = 0x40000000 | 0x22 | 0x63<<7 | 0x26<<14 | 0x67<<21 = 0x40000000 + 0x31a2 + 0x98000 + 0xce00000 = 0x4ce9b1a2 -; word 2 = 0x40000000 | 0x18 | 0x59<<7 | 0x1c<<14 | 0x5d<<21 = 0x40000000 + 0x2c98 + 0x70000 + 0xba00000 = 0x4ba72c98 -; word 3 = 0x40000000 | 0x3a | 0x7b<<7 | 0x3e<<14 | 0x7f<<21 = 0x40000000 + 0x3dba + 0xf8000 + 0xfe00000 = 0x4fefbdba -; A translation that compared the whole 32-bit registers, flushed the denormals (k6 would become equal), ordered a NaN -; (k3, k4 true for lt/gt/le/ge...), or took -0 below +0 (k2) moves bits in the words. -; Expected mrt0 bits: 0x48a12080, 0x4ce9b1a2, 0x4ba72c98, 0x4fefbdba -v_mov_b32_e32 v8, 0x12344000 -v_mov_b32_e32 v9, 0xabcd3c00 -v_mov_b32_e32 v10, 0xffff8000 -v_mov_b32_e32 v4, 0xffff7e00 -v_mov_b32_e32 v11, 0x00013c00 -v_mov_b32_e32 v5, 0x55553c00 -v_mov_b32_e32 v12, 0x7c007c01 -v_mov_b32_e32 v6, 0x00017c00 -v_mov_b32_e32 v13, 0xbeeffc00 -v_mov_b32_e32 v7, 0xdead0001 -v_mov_b32_e32 v14, 0x80000002 -v_mov_b32_e32 v40, 0x40000000 -v_cmp_f_f16_e32 vcc_lo, 1.0, v8 -v_cndmask_b32_e64 v20, 0, 1, vcc_lo -v_lshl_or_b32 v40, v20, 0, v40 -v_cmp_f_f16_e32 vcc_lo, 2.0, v9 -v_cndmask_b32_e64 v20, 0, 1, vcc_lo -v_lshl_or_b32 v40, v20, 1, v40 -v_cmp_f_f16_e32 vcc_lo, 0, v10 -v_cndmask_b32_e64 v20, 0, 1, vcc_lo -v_lshl_or_b32 v40, v20, 2, v40 -v_cmp_f_f16_e32 vcc_lo, v4, v11 -v_cndmask_b32_e64 v20, 0, 1, vcc_lo -v_lshl_or_b32 v40, v20, 3, v40 -v_cmp_f_f16_e32 vcc_lo, v5, v12 -v_cndmask_b32_e64 v20, 0, 1, vcc_lo -v_lshl_or_b32 v40, v20, 4, v40 -v_cmp_f_f16_e32 vcc_lo, v6, v13 -v_cndmask_b32_e64 v20, 0, 1, vcc_lo -v_lshl_or_b32 v40, v20, 5, v40 -v_cmp_f_f16_e32 vcc_lo, v7, v14 -v_cndmask_b32_e64 v20, 0, 1, vcc_lo -v_lshl_or_b32 v40, v20, 6, v40 -v_cmp_lt_f16_e32 vcc_lo, 1.0, v8 -v_cndmask_b32_e64 v20, 0, 1, vcc_lo -v_lshl_or_b32 v40, v20, 7, v40 -v_cmp_lt_f16_e32 vcc_lo, 2.0, v9 -v_cndmask_b32_e64 v20, 0, 1, vcc_lo -v_lshl_or_b32 v40, v20, 8, v40 -v_cmp_lt_f16_e32 vcc_lo, 0, v10 -v_cndmask_b32_e64 v20, 0, 1, vcc_lo -v_lshl_or_b32 v40, v20, 9, v40 -v_cmp_lt_f16_e32 vcc_lo, v4, v11 -v_cndmask_b32_e64 v20, 0, 1, vcc_lo -v_lshl_or_b32 v40, v20, 10, v40 -v_cmp_lt_f16_e32 vcc_lo, v5, v12 -v_cndmask_b32_e64 v20, 0, 1, vcc_lo -v_lshl_or_b32 v40, v20, 11, v40 -v_cmp_lt_f16_e32 vcc_lo, v6, v13 -v_cndmask_b32_e64 v20, 0, 1, vcc_lo -v_lshl_or_b32 v40, v20, 12, v40 -v_cmp_lt_f16_e32 vcc_lo, v7, v14 -v_cndmask_b32_e64 v20, 0, 1, vcc_lo -v_lshl_or_b32 v40, v20, 13, v40 -v_cmp_eq_f16_e32 vcc_lo, 1.0, v8 -v_cndmask_b32_e64 v20, 0, 1, vcc_lo -v_lshl_or_b32 v40, v20, 14, v40 -v_cmp_eq_f16_e32 vcc_lo, 2.0, v9 -v_cndmask_b32_e64 v20, 0, 1, vcc_lo -v_lshl_or_b32 v40, v20, 15, v40 -v_cmp_eq_f16_e32 vcc_lo, 0, v10 -v_cndmask_b32_e64 v20, 0, 1, vcc_lo -v_lshl_or_b32 v40, v20, 16, v40 -v_cmp_eq_f16_e32 vcc_lo, v4, v11 -v_cndmask_b32_e64 v20, 0, 1, vcc_lo -v_lshl_or_b32 v40, v20, 17, v40 -v_cmp_eq_f16_e32 vcc_lo, v5, v12 -v_cndmask_b32_e64 v20, 0, 1, vcc_lo -v_lshl_or_b32 v40, v20, 18, v40 -v_cmp_eq_f16_e32 vcc_lo, v6, v13 -v_cndmask_b32_e64 v20, 0, 1, vcc_lo -v_lshl_or_b32 v40, v20, 19, v40 -v_cmp_eq_f16_e32 vcc_lo, v7, v14 -v_cndmask_b32_e64 v20, 0, 1, vcc_lo -v_lshl_or_b32 v40, v20, 20, v40 -v_cmp_le_f16_e32 vcc_lo, 1.0, v8 -v_cndmask_b32_e64 v20, 0, 1, vcc_lo -v_lshl_or_b32 v40, v20, 21, v40 -v_cmp_le_f16_e32 vcc_lo, 2.0, v9 -v_cndmask_b32_e64 v20, 0, 1, vcc_lo -v_lshl_or_b32 v40, v20, 22, v40 -v_cmp_le_f16_e32 vcc_lo, 0, v10 -v_cndmask_b32_e64 v20, 0, 1, vcc_lo -v_lshl_or_b32 v40, v20, 23, v40 -v_cmp_le_f16_e32 vcc_lo, v4, v11 -v_cndmask_b32_e64 v20, 0, 1, vcc_lo -v_lshl_or_b32 v40, v20, 24, v40 -v_cmp_le_f16_e32 vcc_lo, v5, v12 -v_cndmask_b32_e64 v20, 0, 1, vcc_lo -v_lshl_or_b32 v40, v20, 25, v40 -v_cmp_le_f16_e32 vcc_lo, v6, v13 -v_cndmask_b32_e64 v20, 0, 1, vcc_lo -v_lshl_or_b32 v40, v20, 26, v40 -v_cmp_le_f16_e32 vcc_lo, v7, v14 -v_cndmask_b32_e64 v20, 0, 1, vcc_lo -v_lshl_or_b32 v40, v20, 27, v40 -v_mov_b32_e32 v41, 0x40000000 -v_cmp_gt_f16_e32 vcc_lo, 1.0, v8 -v_cndmask_b32_e64 v20, 0, 1, vcc_lo -v_lshl_or_b32 v41, v20, 0, v41 -v_cmp_gt_f16_e32 vcc_lo, 2.0, v9 -v_cndmask_b32_e64 v20, 0, 1, vcc_lo -v_lshl_or_b32 v41, v20, 1, v41 -v_cmp_gt_f16_e32 vcc_lo, 0, v10 -v_cndmask_b32_e64 v20, 0, 1, vcc_lo -v_lshl_or_b32 v41, v20, 2, v41 -v_cmp_gt_f16_e32 vcc_lo, v4, v11 -v_cndmask_b32_e64 v20, 0, 1, vcc_lo -v_lshl_or_b32 v41, v20, 3, v41 -v_cmp_gt_f16_e32 vcc_lo, v5, v12 -v_cndmask_b32_e64 v20, 0, 1, vcc_lo -v_lshl_or_b32 v41, v20, 4, v41 -v_cmp_gt_f16_e32 vcc_lo, v6, v13 -v_cndmask_b32_e64 v20, 0, 1, vcc_lo -v_lshl_or_b32 v41, v20, 5, v41 -v_cmp_gt_f16_e32 vcc_lo, v7, v14 -v_cndmask_b32_e64 v20, 0, 1, vcc_lo -v_lshl_or_b32 v41, v20, 6, v41 -v_cmp_lg_f16_e32 vcc_lo, 1.0, v8 -v_cndmask_b32_e64 v20, 0, 1, vcc_lo -v_lshl_or_b32 v41, v20, 7, v41 -v_cmp_lg_f16_e32 vcc_lo, 2.0, v9 -v_cndmask_b32_e64 v20, 0, 1, vcc_lo -v_lshl_or_b32 v41, v20, 8, v41 -v_cmp_lg_f16_e32 vcc_lo, 0, v10 -v_cndmask_b32_e64 v20, 0, 1, vcc_lo -v_lshl_or_b32 v41, v20, 9, v41 -v_cmp_lg_f16_e32 vcc_lo, v4, v11 -v_cndmask_b32_e64 v20, 0, 1, vcc_lo -v_lshl_or_b32 v41, v20, 10, v41 -v_cmp_lg_f16_e32 vcc_lo, v5, v12 -v_cndmask_b32_e64 v20, 0, 1, vcc_lo -v_lshl_or_b32 v41, v20, 11, v41 -v_cmp_lg_f16_e32 vcc_lo, v6, v13 -v_cndmask_b32_e64 v20, 0, 1, vcc_lo -v_lshl_or_b32 v41, v20, 12, v41 -v_cmp_lg_f16_e32 vcc_lo, v7, v14 -v_cndmask_b32_e64 v20, 0, 1, vcc_lo -v_lshl_or_b32 v41, v20, 13, v41 -v_cmp_ge_f16_e32 vcc_lo, 1.0, v8 -v_cndmask_b32_e64 v20, 0, 1, vcc_lo -v_lshl_or_b32 v41, v20, 14, v41 -v_cmp_ge_f16_e32 vcc_lo, 2.0, v9 -v_cndmask_b32_e64 v20, 0, 1, vcc_lo -v_lshl_or_b32 v41, v20, 15, v41 -v_cmp_ge_f16_e32 vcc_lo, 0, v10 -v_cndmask_b32_e64 v20, 0, 1, vcc_lo -v_lshl_or_b32 v41, v20, 16, v41 -v_cmp_ge_f16_e32 vcc_lo, v4, v11 -v_cndmask_b32_e64 v20, 0, 1, vcc_lo -v_lshl_or_b32 v41, v20, 17, v41 -v_cmp_ge_f16_e32 vcc_lo, v5, v12 -v_cndmask_b32_e64 v20, 0, 1, vcc_lo -v_lshl_or_b32 v41, v20, 18, v41 -v_cmp_ge_f16_e32 vcc_lo, v6, v13 -v_cndmask_b32_e64 v20, 0, 1, vcc_lo -v_lshl_or_b32 v41, v20, 19, v41 -v_cmp_ge_f16_e32 vcc_lo, v7, v14 -v_cndmask_b32_e64 v20, 0, 1, vcc_lo -v_lshl_or_b32 v41, v20, 20, v41 -v_cmp_o_f16_e32 vcc_lo, 1.0, v8 -v_cndmask_b32_e64 v20, 0, 1, vcc_lo -v_lshl_or_b32 v41, v20, 21, v41 -v_cmp_o_f16_e32 vcc_lo, 2.0, v9 -v_cndmask_b32_e64 v20, 0, 1, vcc_lo -v_lshl_or_b32 v41, v20, 22, v41 -v_cmp_o_f16_e32 vcc_lo, 0, v10 -v_cndmask_b32_e64 v20, 0, 1, vcc_lo -v_lshl_or_b32 v41, v20, 23, v41 -v_cmp_o_f16_e32 vcc_lo, v4, v11 -v_cndmask_b32_e64 v20, 0, 1, vcc_lo -v_lshl_or_b32 v41, v20, 24, v41 -v_cmp_o_f16_e32 vcc_lo, v5, v12 -v_cndmask_b32_e64 v20, 0, 1, vcc_lo -v_lshl_or_b32 v41, v20, 25, v41 -v_cmp_o_f16_e32 vcc_lo, v6, v13 -v_cndmask_b32_e64 v20, 0, 1, vcc_lo -v_lshl_or_b32 v41, v20, 26, v41 -v_cmp_o_f16_e32 vcc_lo, v7, v14 -v_cndmask_b32_e64 v20, 0, 1, vcc_lo -v_lshl_or_b32 v41, v20, 27, v41 -v_mov_b32_e32 v42, 0x40000000 -v_cmp_u_f16_e32 vcc_lo, 1.0, v8 -v_cndmask_b32_e64 v20, 0, 1, vcc_lo -v_lshl_or_b32 v42, v20, 0, v42 -v_cmp_u_f16_e32 vcc_lo, 2.0, v9 -v_cndmask_b32_e64 v20, 0, 1, vcc_lo -v_lshl_or_b32 v42, v20, 1, v42 -v_cmp_u_f16_e32 vcc_lo, 0, v10 -v_cndmask_b32_e64 v20, 0, 1, vcc_lo -v_lshl_or_b32 v42, v20, 2, v42 -v_cmp_u_f16_e32 vcc_lo, v4, v11 -v_cndmask_b32_e64 v20, 0, 1, vcc_lo -v_lshl_or_b32 v42, v20, 3, v42 -v_cmp_u_f16_e32 vcc_lo, v5, v12 -v_cndmask_b32_e64 v20, 0, 1, vcc_lo -v_lshl_or_b32 v42, v20, 4, v42 -v_cmp_u_f16_e32 vcc_lo, v6, v13 -v_cndmask_b32_e64 v20, 0, 1, vcc_lo -v_lshl_or_b32 v42, v20, 5, v42 -v_cmp_u_f16_e32 vcc_lo, v7, v14 -v_cndmask_b32_e64 v20, 0, 1, vcc_lo -v_lshl_or_b32 v42, v20, 6, v42 -v_cmp_nge_f16_e32 vcc_lo, 1.0, v8 -v_cndmask_b32_e64 v20, 0, 1, vcc_lo -v_lshl_or_b32 v42, v20, 7, v42 -v_cmp_nge_f16_e32 vcc_lo, 2.0, v9 -v_cndmask_b32_e64 v20, 0, 1, vcc_lo -v_lshl_or_b32 v42, v20, 8, v42 -v_cmp_nge_f16_e32 vcc_lo, 0, v10 -v_cndmask_b32_e64 v20, 0, 1, vcc_lo -v_lshl_or_b32 v42, v20, 9, v42 -v_cmp_nge_f16_e32 vcc_lo, v4, v11 -v_cndmask_b32_e64 v20, 0, 1, vcc_lo -v_lshl_or_b32 v42, v20, 10, v42 -v_cmp_nge_f16_e32 vcc_lo, v5, v12 -v_cndmask_b32_e64 v20, 0, 1, vcc_lo -v_lshl_or_b32 v42, v20, 11, v42 -v_cmp_nge_f16_e32 vcc_lo, v6, v13 -v_cndmask_b32_e64 v20, 0, 1, vcc_lo -v_lshl_or_b32 v42, v20, 12, v42 -v_cmp_nge_f16_e32 vcc_lo, v7, v14 -v_cndmask_b32_e64 v20, 0, 1, vcc_lo -v_lshl_or_b32 v42, v20, 13, v42 -v_cmp_nlg_f16_e32 vcc_lo, 1.0, v8 -v_cndmask_b32_e64 v20, 0, 1, vcc_lo -v_lshl_or_b32 v42, v20, 14, v42 -v_cmp_nlg_f16_e32 vcc_lo, 2.0, v9 -v_cndmask_b32_e64 v20, 0, 1, vcc_lo -v_lshl_or_b32 v42, v20, 15, v42 -v_cmp_nlg_f16_e32 vcc_lo, 0, v10 -v_cndmask_b32_e64 v20, 0, 1, vcc_lo -v_lshl_or_b32 v42, v20, 16, v42 -v_cmp_nlg_f16_e32 vcc_lo, v4, v11 -v_cndmask_b32_e64 v20, 0, 1, vcc_lo -v_lshl_or_b32 v42, v20, 17, v42 -v_cmp_nlg_f16_e32 vcc_lo, v5, v12 -v_cndmask_b32_e64 v20, 0, 1, vcc_lo -v_lshl_or_b32 v42, v20, 18, v42 -v_cmp_nlg_f16_e32 vcc_lo, v6, v13 -v_cndmask_b32_e64 v20, 0, 1, vcc_lo -v_lshl_or_b32 v42, v20, 19, v42 -v_cmp_nlg_f16_e32 vcc_lo, v7, v14 -v_cndmask_b32_e64 v20, 0, 1, vcc_lo -v_lshl_or_b32 v42, v20, 20, v42 -v_cmp_ngt_f16_e32 vcc_lo, 1.0, v8 -v_cndmask_b32_e64 v20, 0, 1, vcc_lo -v_lshl_or_b32 v42, v20, 21, v42 -v_cmp_ngt_f16_e32 vcc_lo, 2.0, v9 -v_cndmask_b32_e64 v20, 0, 1, vcc_lo -v_lshl_or_b32 v42, v20, 22, v42 -v_cmp_ngt_f16_e32 vcc_lo, 0, v10 -v_cndmask_b32_e64 v20, 0, 1, vcc_lo -v_lshl_or_b32 v42, v20, 23, v42 -v_cmp_ngt_f16_e32 vcc_lo, v4, v11 -v_cndmask_b32_e64 v20, 0, 1, vcc_lo -v_lshl_or_b32 v42, v20, 24, v42 -v_cmp_ngt_f16_e32 vcc_lo, v5, v12 -v_cndmask_b32_e64 v20, 0, 1, vcc_lo -v_lshl_or_b32 v42, v20, 25, v42 -v_cmp_ngt_f16_e32 vcc_lo, v6, v13 -v_cndmask_b32_e64 v20, 0, 1, vcc_lo -v_lshl_or_b32 v42, v20, 26, v42 -v_cmp_ngt_f16_e32 vcc_lo, v7, v14 -v_cndmask_b32_e64 v20, 0, 1, vcc_lo -v_lshl_or_b32 v42, v20, 27, v42 -v_mov_b32_e32 v43, 0x40000000 -v_cmp_nle_f16_e32 vcc_lo, 1.0, v8 -v_cndmask_b32_e64 v20, 0, 1, vcc_lo -v_lshl_or_b32 v43, v20, 0, v43 -v_cmp_nle_f16_e32 vcc_lo, 2.0, v9 -v_cndmask_b32_e64 v20, 0, 1, vcc_lo -v_lshl_or_b32 v43, v20, 1, v43 -v_cmp_nle_f16_e32 vcc_lo, 0, v10 -v_cndmask_b32_e64 v20, 0, 1, vcc_lo -v_lshl_or_b32 v43, v20, 2, v43 -v_cmp_nle_f16_e32 vcc_lo, v4, v11 -v_cndmask_b32_e64 v20, 0, 1, vcc_lo -v_lshl_or_b32 v43, v20, 3, v43 -v_cmp_nle_f16_e32 vcc_lo, v5, v12 -v_cndmask_b32_e64 v20, 0, 1, vcc_lo -v_lshl_or_b32 v43, v20, 4, v43 -v_cmp_nle_f16_e32 vcc_lo, v6, v13 -v_cndmask_b32_e64 v20, 0, 1, vcc_lo -v_lshl_or_b32 v43, v20, 5, v43 -v_cmp_nle_f16_e32 vcc_lo, v7, v14 -v_cndmask_b32_e64 v20, 0, 1, vcc_lo -v_lshl_or_b32 v43, v20, 6, v43 -v_cmp_neq_f16_e32 vcc_lo, 1.0, v8 -v_cndmask_b32_e64 v20, 0, 1, vcc_lo -v_lshl_or_b32 v43, v20, 7, v43 -v_cmp_neq_f16_e32 vcc_lo, 2.0, v9 -v_cndmask_b32_e64 v20, 0, 1, vcc_lo -v_lshl_or_b32 v43, v20, 8, v43 -v_cmp_neq_f16_e32 vcc_lo, 0, v10 -v_cndmask_b32_e64 v20, 0, 1, vcc_lo -v_lshl_or_b32 v43, v20, 9, v43 -v_cmp_neq_f16_e32 vcc_lo, v4, v11 -v_cndmask_b32_e64 v20, 0, 1, vcc_lo -v_lshl_or_b32 v43, v20, 10, v43 -v_cmp_neq_f16_e32 vcc_lo, v5, v12 -v_cndmask_b32_e64 v20, 0, 1, vcc_lo -v_lshl_or_b32 v43, v20, 11, v43 -v_cmp_neq_f16_e32 vcc_lo, v6, v13 -v_cndmask_b32_e64 v20, 0, 1, vcc_lo -v_lshl_or_b32 v43, v20, 12, v43 -v_cmp_neq_f16_e32 vcc_lo, v7, v14 -v_cndmask_b32_e64 v20, 0, 1, vcc_lo -v_lshl_or_b32 v43, v20, 13, v43 -v_cmp_nlt_f16_e32 vcc_lo, 1.0, v8 -v_cndmask_b32_e64 v20, 0, 1, vcc_lo -v_lshl_or_b32 v43, v20, 14, v43 -v_cmp_nlt_f16_e32 vcc_lo, 2.0, v9 -v_cndmask_b32_e64 v20, 0, 1, vcc_lo -v_lshl_or_b32 v43, v20, 15, v43 -v_cmp_nlt_f16_e32 vcc_lo, 0, v10 -v_cndmask_b32_e64 v20, 0, 1, vcc_lo -v_lshl_or_b32 v43, v20, 16, v43 -v_cmp_nlt_f16_e32 vcc_lo, v4, v11 -v_cndmask_b32_e64 v20, 0, 1, vcc_lo -v_lshl_or_b32 v43, v20, 17, v43 -v_cmp_nlt_f16_e32 vcc_lo, v5, v12 -v_cndmask_b32_e64 v20, 0, 1, vcc_lo -v_lshl_or_b32 v43, v20, 18, v43 -v_cmp_nlt_f16_e32 vcc_lo, v6, v13 -v_cndmask_b32_e64 v20, 0, 1, vcc_lo -v_lshl_or_b32 v43, v20, 19, v43 -v_cmp_nlt_f16_e32 vcc_lo, v7, v14 -v_cndmask_b32_e64 v20, 0, 1, vcc_lo -v_lshl_or_b32 v43, v20, 20, v43 -v_cmp_tru_f16_e32 vcc_lo, 1.0, v8 -v_cndmask_b32_e64 v20, 0, 1, vcc_lo -v_lshl_or_b32 v43, v20, 21, v43 -v_cmp_tru_f16_e32 vcc_lo, 2.0, v9 -v_cndmask_b32_e64 v20, 0, 1, vcc_lo -v_lshl_or_b32 v43, v20, 22, v43 -v_cmp_tru_f16_e32 vcc_lo, 0, v10 -v_cndmask_b32_e64 v20, 0, 1, vcc_lo -v_lshl_or_b32 v43, v20, 23, v43 -v_cmp_tru_f16_e32 vcc_lo, v4, v11 -v_cndmask_b32_e64 v20, 0, 1, vcc_lo -v_lshl_or_b32 v43, v20, 24, v43 -v_cmp_tru_f16_e32 vcc_lo, v5, v12 -v_cndmask_b32_e64 v20, 0, 1, vcc_lo -v_lshl_or_b32 v43, v20, 25, v43 -v_cmp_tru_f16_e32 vcc_lo, v6, v13 -v_cndmask_b32_e64 v20, 0, 1, vcc_lo -v_lshl_or_b32 v43, v20, 26, v43 -v_cmp_tru_f16_e32 vcc_lo, v7, v14 -v_cndmask_b32_e64 v20, 0, 1, vcc_lo -v_lshl_or_b32 v43, v20, 27, v43 -exp mrt0 v40, v41, v42, v43 done vm -s_endpgm diff --git a/runtime/test/shaders/ps_vcmp_f16_e64.asm b/runtime/test/shaders/ps_vcmp_f16_e64.asm deleted file mode 100644 index 54492079a..000000000 --- a/runtime/test/shaders/ps_vcmp_f16_e64.asm +++ /dev/null @@ -1,370 +0,0 @@ -; regen_fixtures: this source has a translator fixture in tests/semantic/fixtures/disasm -; 16-bit float VOPC compares, e64 form (SGPR destination) with swapped operands: v_cmp_{f,lt,eq,le,gt,lg,ge,o,u,nge,nlg, -; ngt,nle,neq,nlt,tru}_f16_e64 s4, B, A. Same seven operand pairs as ps_vcmp_f16 (see its header for the ISA rules and -; the case list), but src0 is the VGPR B and src1 is A (the inline constant for k0..k2, the VGPR otherwise), so each -; op sees the mirrored relation: less <-> greater, equal and unordered unchanged. -; Cases (A to B as in ps_vcmp_f16): k0 1.0/2.0, k1 2.0/1.0, k2 +0/-0, k3 qNaN/1.0, k4 1.0/sNaN, -; k5 +inf/-inf, k6 denormal 0x0001/0x0002; the high halves of the VGPR operands hold junk. -; Relation of B (src0) to A (src1): LESS = {k1,k5} = 0x22, GREATER = {k0,k6} = 0x41, -; EQUAL = {k2} = 0x04, UNORDERED = {k3,k4} = 0x18. Masks (bit k = result on case k): -; f 0x00 lt 0x22 eq 0x04 le 0x26 gt 0x41 lg 0x63 ge 0x45 o 0x67 -; u 0x18 nge 0x3a nlg 0x1c ngt 0x3e nle 0x59 neq 0x7b nlt 0x5d tru 0x7f -; Word w holds ops 4w..4w+3, op j at bit 7*j + k, plus bit 30 (no denormal or NaN export pattern): -; word 0 = 0x40000000 | 0x00 | 0x22<<7 | 0x04<<14 | 0x26<<21 = 0x40000000 + 0x1100 + 0x10000 + 0x4c00000 = 0x44c11100 -; word 1 = 0x40000000 | 0x41 | 0x63<<7 | 0x45<<14 | 0x67<<21 = 0x40000000 + 0x31c1 + 0x114000 + 0xce00000 = 0x4cf171c1 -; word 2 = 0x40000000 | 0x18 | 0x3a<<7 | 0x1c<<14 | 0x3e<<21 = 0x40000000 + 0x1d18 + 0x70000 + 0x7c00000 = 0x47c71d18 -; word 3 = 0x40000000 | 0x59 | 0x7b<<7 | 0x5d<<14 | 0x7f<<21 = 0x40000000 + 0x3dd9 + 0x174000 + 0xfe00000 = 0x4ff77dd9 -; Expected mrt0 bits: 0x44c11100, 0x4cf171c1, 0x47c71d18, 0x4ff77dd9 -v_mov_b32_e32 v8, 0x12344000 -v_mov_b32_e32 v9, 0xabcd3c00 -v_mov_b32_e32 v10, 0xffff8000 -v_mov_b32_e32 v4, 0xffff7e00 -v_mov_b32_e32 v11, 0x00013c00 -v_mov_b32_e32 v5, 0x55553c00 -v_mov_b32_e32 v12, 0x7c007c01 -v_mov_b32_e32 v6, 0x00017c00 -v_mov_b32_e32 v13, 0xbeeffc00 -v_mov_b32_e32 v7, 0xdead0001 -v_mov_b32_e32 v14, 0x80000002 -v_mov_b32_e32 v40, 0x40000000 -v_cmp_f_f16_e64 s4, v8, 1.0 -v_cndmask_b32_e64 v20, 0, 1, s4 -v_lshl_or_b32 v40, v20, 0, v40 -v_cmp_f_f16_e64 s4, v9, 2.0 -v_cndmask_b32_e64 v20, 0, 1, s4 -v_lshl_or_b32 v40, v20, 1, v40 -v_cmp_f_f16_e64 s4, v10, 0 -v_cndmask_b32_e64 v20, 0, 1, s4 -v_lshl_or_b32 v40, v20, 2, v40 -v_cmp_f_f16_e64 s4, v11, v4 -v_cndmask_b32_e64 v20, 0, 1, s4 -v_lshl_or_b32 v40, v20, 3, v40 -v_cmp_f_f16_e64 s4, v12, v5 -v_cndmask_b32_e64 v20, 0, 1, s4 -v_lshl_or_b32 v40, v20, 4, v40 -v_cmp_f_f16_e64 s4, v13, v6 -v_cndmask_b32_e64 v20, 0, 1, s4 -v_lshl_or_b32 v40, v20, 5, v40 -v_cmp_f_f16_e64 s4, v14, v7 -v_cndmask_b32_e64 v20, 0, 1, s4 -v_lshl_or_b32 v40, v20, 6, v40 -v_cmp_lt_f16_e64 s4, v8, 1.0 -v_cndmask_b32_e64 v20, 0, 1, s4 -v_lshl_or_b32 v40, v20, 7, v40 -v_cmp_lt_f16_e64 s4, v9, 2.0 -v_cndmask_b32_e64 v20, 0, 1, s4 -v_lshl_or_b32 v40, v20, 8, v40 -v_cmp_lt_f16_e64 s4, v10, 0 -v_cndmask_b32_e64 v20, 0, 1, s4 -v_lshl_or_b32 v40, v20, 9, v40 -v_cmp_lt_f16_e64 s4, v11, v4 -v_cndmask_b32_e64 v20, 0, 1, s4 -v_lshl_or_b32 v40, v20, 10, v40 -v_cmp_lt_f16_e64 s4, v12, v5 -v_cndmask_b32_e64 v20, 0, 1, s4 -v_lshl_or_b32 v40, v20, 11, v40 -v_cmp_lt_f16_e64 s4, v13, v6 -v_cndmask_b32_e64 v20, 0, 1, s4 -v_lshl_or_b32 v40, v20, 12, v40 -v_cmp_lt_f16_e64 s4, v14, v7 -v_cndmask_b32_e64 v20, 0, 1, s4 -v_lshl_or_b32 v40, v20, 13, v40 -v_cmp_eq_f16_e64 s4, v8, 1.0 -v_cndmask_b32_e64 v20, 0, 1, s4 -v_lshl_or_b32 v40, v20, 14, v40 -v_cmp_eq_f16_e64 s4, v9, 2.0 -v_cndmask_b32_e64 v20, 0, 1, s4 -v_lshl_or_b32 v40, v20, 15, v40 -v_cmp_eq_f16_e64 s4, v10, 0 -v_cndmask_b32_e64 v20, 0, 1, s4 -v_lshl_or_b32 v40, v20, 16, v40 -v_cmp_eq_f16_e64 s4, v11, v4 -v_cndmask_b32_e64 v20, 0, 1, s4 -v_lshl_or_b32 v40, v20, 17, v40 -v_cmp_eq_f16_e64 s4, v12, v5 -v_cndmask_b32_e64 v20, 0, 1, s4 -v_lshl_or_b32 v40, v20, 18, v40 -v_cmp_eq_f16_e64 s4, v13, v6 -v_cndmask_b32_e64 v20, 0, 1, s4 -v_lshl_or_b32 v40, v20, 19, v40 -v_cmp_eq_f16_e64 s4, v14, v7 -v_cndmask_b32_e64 v20, 0, 1, s4 -v_lshl_or_b32 v40, v20, 20, v40 -v_cmp_le_f16_e64 s4, v8, 1.0 -v_cndmask_b32_e64 v20, 0, 1, s4 -v_lshl_or_b32 v40, v20, 21, v40 -v_cmp_le_f16_e64 s4, v9, 2.0 -v_cndmask_b32_e64 v20, 0, 1, s4 -v_lshl_or_b32 v40, v20, 22, v40 -v_cmp_le_f16_e64 s4, v10, 0 -v_cndmask_b32_e64 v20, 0, 1, s4 -v_lshl_or_b32 v40, v20, 23, v40 -v_cmp_le_f16_e64 s4, v11, v4 -v_cndmask_b32_e64 v20, 0, 1, s4 -v_lshl_or_b32 v40, v20, 24, v40 -v_cmp_le_f16_e64 s4, v12, v5 -v_cndmask_b32_e64 v20, 0, 1, s4 -v_lshl_or_b32 v40, v20, 25, v40 -v_cmp_le_f16_e64 s4, v13, v6 -v_cndmask_b32_e64 v20, 0, 1, s4 -v_lshl_or_b32 v40, v20, 26, v40 -v_cmp_le_f16_e64 s4, v14, v7 -v_cndmask_b32_e64 v20, 0, 1, s4 -v_lshl_or_b32 v40, v20, 27, v40 -v_mov_b32_e32 v41, 0x40000000 -v_cmp_gt_f16_e64 s4, v8, 1.0 -v_cndmask_b32_e64 v20, 0, 1, s4 -v_lshl_or_b32 v41, v20, 0, v41 -v_cmp_gt_f16_e64 s4, v9, 2.0 -v_cndmask_b32_e64 v20, 0, 1, s4 -v_lshl_or_b32 v41, v20, 1, v41 -v_cmp_gt_f16_e64 s4, v10, 0 -v_cndmask_b32_e64 v20, 0, 1, s4 -v_lshl_or_b32 v41, v20, 2, v41 -v_cmp_gt_f16_e64 s4, v11, v4 -v_cndmask_b32_e64 v20, 0, 1, s4 -v_lshl_or_b32 v41, v20, 3, v41 -v_cmp_gt_f16_e64 s4, v12, v5 -v_cndmask_b32_e64 v20, 0, 1, s4 -v_lshl_or_b32 v41, v20, 4, v41 -v_cmp_gt_f16_e64 s4, v13, v6 -v_cndmask_b32_e64 v20, 0, 1, s4 -v_lshl_or_b32 v41, v20, 5, v41 -v_cmp_gt_f16_e64 s4, v14, v7 -v_cndmask_b32_e64 v20, 0, 1, s4 -v_lshl_or_b32 v41, v20, 6, v41 -v_cmp_lg_f16_e64 s4, v8, 1.0 -v_cndmask_b32_e64 v20, 0, 1, s4 -v_lshl_or_b32 v41, v20, 7, v41 -v_cmp_lg_f16_e64 s4, v9, 2.0 -v_cndmask_b32_e64 v20, 0, 1, s4 -v_lshl_or_b32 v41, v20, 8, v41 -v_cmp_lg_f16_e64 s4, v10, 0 -v_cndmask_b32_e64 v20, 0, 1, s4 -v_lshl_or_b32 v41, v20, 9, v41 -v_cmp_lg_f16_e64 s4, v11, v4 -v_cndmask_b32_e64 v20, 0, 1, s4 -v_lshl_or_b32 v41, v20, 10, v41 -v_cmp_lg_f16_e64 s4, v12, v5 -v_cndmask_b32_e64 v20, 0, 1, s4 -v_lshl_or_b32 v41, v20, 11, v41 -v_cmp_lg_f16_e64 s4, v13, v6 -v_cndmask_b32_e64 v20, 0, 1, s4 -v_lshl_or_b32 v41, v20, 12, v41 -v_cmp_lg_f16_e64 s4, v14, v7 -v_cndmask_b32_e64 v20, 0, 1, s4 -v_lshl_or_b32 v41, v20, 13, v41 -v_cmp_ge_f16_e64 s4, v8, 1.0 -v_cndmask_b32_e64 v20, 0, 1, s4 -v_lshl_or_b32 v41, v20, 14, v41 -v_cmp_ge_f16_e64 s4, v9, 2.0 -v_cndmask_b32_e64 v20, 0, 1, s4 -v_lshl_or_b32 v41, v20, 15, v41 -v_cmp_ge_f16_e64 s4, v10, 0 -v_cndmask_b32_e64 v20, 0, 1, s4 -v_lshl_or_b32 v41, v20, 16, v41 -v_cmp_ge_f16_e64 s4, v11, v4 -v_cndmask_b32_e64 v20, 0, 1, s4 -v_lshl_or_b32 v41, v20, 17, v41 -v_cmp_ge_f16_e64 s4, v12, v5 -v_cndmask_b32_e64 v20, 0, 1, s4 -v_lshl_or_b32 v41, v20, 18, v41 -v_cmp_ge_f16_e64 s4, v13, v6 -v_cndmask_b32_e64 v20, 0, 1, s4 -v_lshl_or_b32 v41, v20, 19, v41 -v_cmp_ge_f16_e64 s4, v14, v7 -v_cndmask_b32_e64 v20, 0, 1, s4 -v_lshl_or_b32 v41, v20, 20, v41 -v_cmp_o_f16_e64 s4, v8, 1.0 -v_cndmask_b32_e64 v20, 0, 1, s4 -v_lshl_or_b32 v41, v20, 21, v41 -v_cmp_o_f16_e64 s4, v9, 2.0 -v_cndmask_b32_e64 v20, 0, 1, s4 -v_lshl_or_b32 v41, v20, 22, v41 -v_cmp_o_f16_e64 s4, v10, 0 -v_cndmask_b32_e64 v20, 0, 1, s4 -v_lshl_or_b32 v41, v20, 23, v41 -v_cmp_o_f16_e64 s4, v11, v4 -v_cndmask_b32_e64 v20, 0, 1, s4 -v_lshl_or_b32 v41, v20, 24, v41 -v_cmp_o_f16_e64 s4, v12, v5 -v_cndmask_b32_e64 v20, 0, 1, s4 -v_lshl_or_b32 v41, v20, 25, v41 -v_cmp_o_f16_e64 s4, v13, v6 -v_cndmask_b32_e64 v20, 0, 1, s4 -v_lshl_or_b32 v41, v20, 26, v41 -v_cmp_o_f16_e64 s4, v14, v7 -v_cndmask_b32_e64 v20, 0, 1, s4 -v_lshl_or_b32 v41, v20, 27, v41 -v_mov_b32_e32 v42, 0x40000000 -v_cmp_u_f16_e64 s4, v8, 1.0 -v_cndmask_b32_e64 v20, 0, 1, s4 -v_lshl_or_b32 v42, v20, 0, v42 -v_cmp_u_f16_e64 s4, v9, 2.0 -v_cndmask_b32_e64 v20, 0, 1, s4 -v_lshl_or_b32 v42, v20, 1, v42 -v_cmp_u_f16_e64 s4, v10, 0 -v_cndmask_b32_e64 v20, 0, 1, s4 -v_lshl_or_b32 v42, v20, 2, v42 -v_cmp_u_f16_e64 s4, v11, v4 -v_cndmask_b32_e64 v20, 0, 1, s4 -v_lshl_or_b32 v42, v20, 3, v42 -v_cmp_u_f16_e64 s4, v12, v5 -v_cndmask_b32_e64 v20, 0, 1, s4 -v_lshl_or_b32 v42, v20, 4, v42 -v_cmp_u_f16_e64 s4, v13, v6 -v_cndmask_b32_e64 v20, 0, 1, s4 -v_lshl_or_b32 v42, v20, 5, v42 -v_cmp_u_f16_e64 s4, v14, v7 -v_cndmask_b32_e64 v20, 0, 1, s4 -v_lshl_or_b32 v42, v20, 6, v42 -v_cmp_nge_f16_e64 s4, v8, 1.0 -v_cndmask_b32_e64 v20, 0, 1, s4 -v_lshl_or_b32 v42, v20, 7, v42 -v_cmp_nge_f16_e64 s4, v9, 2.0 -v_cndmask_b32_e64 v20, 0, 1, s4 -v_lshl_or_b32 v42, v20, 8, v42 -v_cmp_nge_f16_e64 s4, v10, 0 -v_cndmask_b32_e64 v20, 0, 1, s4 -v_lshl_or_b32 v42, v20, 9, v42 -v_cmp_nge_f16_e64 s4, v11, v4 -v_cndmask_b32_e64 v20, 0, 1, s4 -v_lshl_or_b32 v42, v20, 10, v42 -v_cmp_nge_f16_e64 s4, v12, v5 -v_cndmask_b32_e64 v20, 0, 1, s4 -v_lshl_or_b32 v42, v20, 11, v42 -v_cmp_nge_f16_e64 s4, v13, v6 -v_cndmask_b32_e64 v20, 0, 1, s4 -v_lshl_or_b32 v42, v20, 12, v42 -v_cmp_nge_f16_e64 s4, v14, v7 -v_cndmask_b32_e64 v20, 0, 1, s4 -v_lshl_or_b32 v42, v20, 13, v42 -v_cmp_nlg_f16_e64 s4, v8, 1.0 -v_cndmask_b32_e64 v20, 0, 1, s4 -v_lshl_or_b32 v42, v20, 14, v42 -v_cmp_nlg_f16_e64 s4, v9, 2.0 -v_cndmask_b32_e64 v20, 0, 1, s4 -v_lshl_or_b32 v42, v20, 15, v42 -v_cmp_nlg_f16_e64 s4, v10, 0 -v_cndmask_b32_e64 v20, 0, 1, s4 -v_lshl_or_b32 v42, v20, 16, v42 -v_cmp_nlg_f16_e64 s4, v11, v4 -v_cndmask_b32_e64 v20, 0, 1, s4 -v_lshl_or_b32 v42, v20, 17, v42 -v_cmp_nlg_f16_e64 s4, v12, v5 -v_cndmask_b32_e64 v20, 0, 1, s4 -v_lshl_or_b32 v42, v20, 18, v42 -v_cmp_nlg_f16_e64 s4, v13, v6 -v_cndmask_b32_e64 v20, 0, 1, s4 -v_lshl_or_b32 v42, v20, 19, v42 -v_cmp_nlg_f16_e64 s4, v14, v7 -v_cndmask_b32_e64 v20, 0, 1, s4 -v_lshl_or_b32 v42, v20, 20, v42 -v_cmp_ngt_f16_e64 s4, v8, 1.0 -v_cndmask_b32_e64 v20, 0, 1, s4 -v_lshl_or_b32 v42, v20, 21, v42 -v_cmp_ngt_f16_e64 s4, v9, 2.0 -v_cndmask_b32_e64 v20, 0, 1, s4 -v_lshl_or_b32 v42, v20, 22, v42 -v_cmp_ngt_f16_e64 s4, v10, 0 -v_cndmask_b32_e64 v20, 0, 1, s4 -v_lshl_or_b32 v42, v20, 23, v42 -v_cmp_ngt_f16_e64 s4, v11, v4 -v_cndmask_b32_e64 v20, 0, 1, s4 -v_lshl_or_b32 v42, v20, 24, v42 -v_cmp_ngt_f16_e64 s4, v12, v5 -v_cndmask_b32_e64 v20, 0, 1, s4 -v_lshl_or_b32 v42, v20, 25, v42 -v_cmp_ngt_f16_e64 s4, v13, v6 -v_cndmask_b32_e64 v20, 0, 1, s4 -v_lshl_or_b32 v42, v20, 26, v42 -v_cmp_ngt_f16_e64 s4, v14, v7 -v_cndmask_b32_e64 v20, 0, 1, s4 -v_lshl_or_b32 v42, v20, 27, v42 -v_mov_b32_e32 v43, 0x40000000 -v_cmp_nle_f16_e64 s4, v8, 1.0 -v_cndmask_b32_e64 v20, 0, 1, s4 -v_lshl_or_b32 v43, v20, 0, v43 -v_cmp_nle_f16_e64 s4, v9, 2.0 -v_cndmask_b32_e64 v20, 0, 1, s4 -v_lshl_or_b32 v43, v20, 1, v43 -v_cmp_nle_f16_e64 s4, v10, 0 -v_cndmask_b32_e64 v20, 0, 1, s4 -v_lshl_or_b32 v43, v20, 2, v43 -v_cmp_nle_f16_e64 s4, v11, v4 -v_cndmask_b32_e64 v20, 0, 1, s4 -v_lshl_or_b32 v43, v20, 3, v43 -v_cmp_nle_f16_e64 s4, v12, v5 -v_cndmask_b32_e64 v20, 0, 1, s4 -v_lshl_or_b32 v43, v20, 4, v43 -v_cmp_nle_f16_e64 s4, v13, v6 -v_cndmask_b32_e64 v20, 0, 1, s4 -v_lshl_or_b32 v43, v20, 5, v43 -v_cmp_nle_f16_e64 s4, v14, v7 -v_cndmask_b32_e64 v20, 0, 1, s4 -v_lshl_or_b32 v43, v20, 6, v43 -v_cmp_neq_f16_e64 s4, v8, 1.0 -v_cndmask_b32_e64 v20, 0, 1, s4 -v_lshl_or_b32 v43, v20, 7, v43 -v_cmp_neq_f16_e64 s4, v9, 2.0 -v_cndmask_b32_e64 v20, 0, 1, s4 -v_lshl_or_b32 v43, v20, 8, v43 -v_cmp_neq_f16_e64 s4, v10, 0 -v_cndmask_b32_e64 v20, 0, 1, s4 -v_lshl_or_b32 v43, v20, 9, v43 -v_cmp_neq_f16_e64 s4, v11, v4 -v_cndmask_b32_e64 v20, 0, 1, s4 -v_lshl_or_b32 v43, v20, 10, v43 -v_cmp_neq_f16_e64 s4, v12, v5 -v_cndmask_b32_e64 v20, 0, 1, s4 -v_lshl_or_b32 v43, v20, 11, v43 -v_cmp_neq_f16_e64 s4, v13, v6 -v_cndmask_b32_e64 v20, 0, 1, s4 -v_lshl_or_b32 v43, v20, 12, v43 -v_cmp_neq_f16_e64 s4, v14, v7 -v_cndmask_b32_e64 v20, 0, 1, s4 -v_lshl_or_b32 v43, v20, 13, v43 -v_cmp_nlt_f16_e64 s4, v8, 1.0 -v_cndmask_b32_e64 v20, 0, 1, s4 -v_lshl_or_b32 v43, v20, 14, v43 -v_cmp_nlt_f16_e64 s4, v9, 2.0 -v_cndmask_b32_e64 v20, 0, 1, s4 -v_lshl_or_b32 v43, v20, 15, v43 -v_cmp_nlt_f16_e64 s4, v10, 0 -v_cndmask_b32_e64 v20, 0, 1, s4 -v_lshl_or_b32 v43, v20, 16, v43 -v_cmp_nlt_f16_e64 s4, v11, v4 -v_cndmask_b32_e64 v20, 0, 1, s4 -v_lshl_or_b32 v43, v20, 17, v43 -v_cmp_nlt_f16_e64 s4, v12, v5 -v_cndmask_b32_e64 v20, 0, 1, s4 -v_lshl_or_b32 v43, v20, 18, v43 -v_cmp_nlt_f16_e64 s4, v13, v6 -v_cndmask_b32_e64 v20, 0, 1, s4 -v_lshl_or_b32 v43, v20, 19, v43 -v_cmp_nlt_f16_e64 s4, v14, v7 -v_cndmask_b32_e64 v20, 0, 1, s4 -v_lshl_or_b32 v43, v20, 20, v43 -v_cmp_tru_f16_e64 s4, v8, 1.0 -v_cndmask_b32_e64 v20, 0, 1, s4 -v_lshl_or_b32 v43, v20, 21, v43 -v_cmp_tru_f16_e64 s4, v9, 2.0 -v_cndmask_b32_e64 v20, 0, 1, s4 -v_lshl_or_b32 v43, v20, 22, v43 -v_cmp_tru_f16_e64 s4, v10, 0 -v_cndmask_b32_e64 v20, 0, 1, s4 -v_lshl_or_b32 v43, v20, 23, v43 -v_cmp_tru_f16_e64 s4, v11, v4 -v_cndmask_b32_e64 v20, 0, 1, s4 -v_lshl_or_b32 v43, v20, 24, v43 -v_cmp_tru_f16_e64 s4, v12, v5 -v_cndmask_b32_e64 v20, 0, 1, s4 -v_lshl_or_b32 v43, v20, 25, v43 -v_cmp_tru_f16_e64 s4, v13, v6 -v_cndmask_b32_e64 v20, 0, 1, s4 -v_lshl_or_b32 v43, v20, 26, v43 -v_cmp_tru_f16_e64 s4, v14, v7 -v_cndmask_b32_e64 v20, 0, 1, s4 -v_lshl_or_b32 v43, v20, 27, v43 -exp mrt0 v40, v41, v42, v43 done vm -s_endpgm diff --git a/runtime/test/shaders/ps_vcmp_f32_nan.asm b/runtime/test/shaders/ps_vcmp_f32_nan.asm deleted file mode 100644 index 8f528a1cf..000000000 --- a/runtime/test/shaders/ps_vcmp_f32_nan.asm +++ /dev/null @@ -1,293 +0,0 @@ -; regen_fixtures: this source has a translator fixture in tests/semantic/fixtures/disasm -; f32 VOPC compares with a quiet NaN, inputs read from memory at run time (not inline constants, which the driver -; could fold): v_cmp_{ge,lg,neq,nge}_f32 (e32, VCC), v_cmp_{ngt,nle,nlt,tru}_f32 (e64, SGPR destination) and -; v_cmpx_{ge,lg,nge,nlt,neq,o,tru,f}_f32 (EXEC is copied out and put back after each one). None of these had a test. -; The V# in s[0:3] points at 0x1000 (num_records 16); the test seeds 0x1000..0x1008 with 0x7fc10001 0x3f800000 -; 0x40000000, so v1 = NaN, v2 = 1.0, v3 = 2.0. -; Each compare runs on four pairs; bit 4*k + i of a word is op k of that word on pair i: -; P0 = (NaN, 1.0) P1 = (1.0, 2.0) P2 = (2.0, 1.0) P3 = (1.0, 1.0) -; RDNA2 ISA VOPC definitions: GE = S0 >= S1, LG = S0 <> S1 (ordered: false on NaN), O = !isNan(S0) && !isNan(S1), -; F = 0, TRU = 1; the N forms are the negations, so true on NaN: NGE = !(S0 >= S1), NGT = !(S0 > S1), -; NLE = !(S0 <= S1), NLT = !(S0 < S1), NEQ = !(S0 == S1). Nibble per op, bits P3 P2 P1 P0: -; ge P2 P3 = 0b1100 = 0xc ngt P0 P1 P3 = 0b1011 = 0xb -; lg P1 P2 = 0b0110 = 0x6 nle P0 P2 = 0b0101 = 0x5 -; neq P0 P1 P2 = 0b0111 = 0x7 nlt P0 P2 P3 = 0b1101 = 0xd -; nge P0 P1 = 0b0011 = 0x3 tru all = 0xf -; o P1 P2 P3 = 0b1110 = 0xe f none = 0x0 -; word 0 = ge | lg<<4 | neq<<8 | nge<<12 = 0xc | 0x60 | 0x700 | 0x3000 = 0x0000376c -; word 1 = ngt | nle<<4 | nlt<<8 | tru<<12 = 0xb | 0x50 | 0xd00 | 0xf000 = 0x0000fd5b -; word 2 = cmpx ge | lg<<4 | nge<<8 | nlt<<12 = 0xc | 0x60 | 0x300 | 0xd000 = 0x0000d36c -; word 3 = cmpx neq | o<<4 | tru<<8 | f<<12 = 0x7 | 0xe0 | 0xf00 | 0x0000 = 0x00000fe7 -; Expected mrt0 bits: 0x0000376c, 0x0000fd5b, 0x0000d36c, 0x00000fe7 -s_buffer_load_dwordx4 s[4:7], s[0:3], 0 -s_waitcnt lgkmcnt(0) -v_mov_b32_e32 v1, s4 -v_mov_b32_e32 v2, s5 -v_mov_b32_e32 v3, s6 -s_mov_b32 s20, exec_lo -; word 0: ge, lg, neq, nge -v_mov_b32_e32 v40, 0 -v_cmp_ge_f32_e32 vcc_lo, v1, v2 -v_cndmask_b32_e64 v20, 0, 1, vcc_lo -v_lshl_or_b32 v40, v20, 0, v40 -v_cmp_ge_f32_e32 vcc_lo, v2, v3 -v_cndmask_b32_e64 v20, 0, 1, vcc_lo -v_lshl_or_b32 v40, v20, 1, v40 -v_cmp_ge_f32_e32 vcc_lo, v3, v2 -v_cndmask_b32_e64 v20, 0, 1, vcc_lo -v_lshl_or_b32 v40, v20, 2, v40 -v_cmp_ge_f32_e32 vcc_lo, v2, v2 -v_cndmask_b32_e64 v20, 0, 1, vcc_lo -v_lshl_or_b32 v40, v20, 3, v40 -v_cmp_lg_f32_e32 vcc_lo, v1, v2 -v_cndmask_b32_e64 v20, 0, 1, vcc_lo -v_lshl_or_b32 v40, v20, 4, v40 -v_cmp_lg_f32_e32 vcc_lo, v2, v3 -v_cndmask_b32_e64 v20, 0, 1, vcc_lo -v_lshl_or_b32 v40, v20, 5, v40 -v_cmp_lg_f32_e32 vcc_lo, v3, v2 -v_cndmask_b32_e64 v20, 0, 1, vcc_lo -v_lshl_or_b32 v40, v20, 6, v40 -v_cmp_lg_f32_e32 vcc_lo, v2, v2 -v_cndmask_b32_e64 v20, 0, 1, vcc_lo -v_lshl_or_b32 v40, v20, 7, v40 -v_cmp_neq_f32_e32 vcc_lo, v1, v2 -v_cndmask_b32_e64 v20, 0, 1, vcc_lo -v_lshl_or_b32 v40, v20, 8, v40 -v_cmp_neq_f32_e32 vcc_lo, v2, v3 -v_cndmask_b32_e64 v20, 0, 1, vcc_lo -v_lshl_or_b32 v40, v20, 9, v40 -v_cmp_neq_f32_e32 vcc_lo, v3, v2 -v_cndmask_b32_e64 v20, 0, 1, vcc_lo -v_lshl_or_b32 v40, v20, 10, v40 -v_cmp_neq_f32_e32 vcc_lo, v2, v2 -v_cndmask_b32_e64 v20, 0, 1, vcc_lo -v_lshl_or_b32 v40, v20, 11, v40 -v_cmp_nge_f32_e32 vcc_lo, v1, v2 -v_cndmask_b32_e64 v20, 0, 1, vcc_lo -v_lshl_or_b32 v40, v20, 12, v40 -v_cmp_nge_f32_e32 vcc_lo, v2, v3 -v_cndmask_b32_e64 v20, 0, 1, vcc_lo -v_lshl_or_b32 v40, v20, 13, v40 -v_cmp_nge_f32_e32 vcc_lo, v3, v2 -v_cndmask_b32_e64 v20, 0, 1, vcc_lo -v_lshl_or_b32 v40, v20, 14, v40 -v_cmp_nge_f32_e32 vcc_lo, v2, v2 -v_cndmask_b32_e64 v20, 0, 1, vcc_lo -v_lshl_or_b32 v40, v20, 15, v40 -; word 1: ngt, nle, nlt, tru -v_mov_b32_e32 v41, 0 -v_cmp_ngt_f32_e64 s22, v1, v2 -v_cndmask_b32_e64 v20, 0, 1, s22 -v_lshl_or_b32 v41, v20, 0, v41 -v_cmp_ngt_f32_e64 s22, v2, v3 -v_cndmask_b32_e64 v20, 0, 1, s22 -v_lshl_or_b32 v41, v20, 1, v41 -v_cmp_ngt_f32_e64 s22, v3, v2 -v_cndmask_b32_e64 v20, 0, 1, s22 -v_lshl_or_b32 v41, v20, 2, v41 -v_cmp_ngt_f32_e64 s22, v2, v2 -v_cndmask_b32_e64 v20, 0, 1, s22 -v_lshl_or_b32 v41, v20, 3, v41 -v_cmp_nle_f32_e64 s22, v1, v2 -v_cndmask_b32_e64 v20, 0, 1, s22 -v_lshl_or_b32 v41, v20, 4, v41 -v_cmp_nle_f32_e64 s22, v2, v3 -v_cndmask_b32_e64 v20, 0, 1, s22 -v_lshl_or_b32 v41, v20, 5, v41 -v_cmp_nle_f32_e64 s22, v3, v2 -v_cndmask_b32_e64 v20, 0, 1, s22 -v_lshl_or_b32 v41, v20, 6, v41 -v_cmp_nle_f32_e64 s22, v2, v2 -v_cndmask_b32_e64 v20, 0, 1, s22 -v_lshl_or_b32 v41, v20, 7, v41 -v_cmp_nlt_f32_e64 s22, v1, v2 -v_cndmask_b32_e64 v20, 0, 1, s22 -v_lshl_or_b32 v41, v20, 8, v41 -v_cmp_nlt_f32_e64 s22, v2, v3 -v_cndmask_b32_e64 v20, 0, 1, s22 -v_lshl_or_b32 v41, v20, 9, v41 -v_cmp_nlt_f32_e64 s22, v3, v2 -v_cndmask_b32_e64 v20, 0, 1, s22 -v_lshl_or_b32 v41, v20, 10, v41 -v_cmp_nlt_f32_e64 s22, v2, v2 -v_cndmask_b32_e64 v20, 0, 1, s22 -v_lshl_or_b32 v41, v20, 11, v41 -v_cmp_tru_f32_e64 s22, v1, v2 -v_cndmask_b32_e64 v20, 0, 1, s22 -v_lshl_or_b32 v41, v20, 12, v41 -v_cmp_tru_f32_e64 s22, v2, v3 -v_cndmask_b32_e64 v20, 0, 1, s22 -v_lshl_or_b32 v41, v20, 13, v41 -v_cmp_tru_f32_e64 s22, v3, v2 -v_cndmask_b32_e64 v20, 0, 1, s22 -v_lshl_or_b32 v41, v20, 14, v41 -v_cmp_tru_f32_e64 s22, v2, v2 -v_cndmask_b32_e64 v20, 0, 1, s22 -v_lshl_or_b32 v41, v20, 15, v41 -; word 2: x:ge, x:lg, x:nge, x:nlt -v_mov_b32_e32 v42, 0 -v_cmpx_ge_f32_e32 v1, v2 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v20, 0, 1, s21 -v_lshl_or_b32 v42, v20, 0, v42 -v_cmpx_ge_f32_e32 v2, v3 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v20, 0, 1, s21 -v_lshl_or_b32 v42, v20, 1, v42 -v_cmpx_ge_f32_e32 v3, v2 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v20, 0, 1, s21 -v_lshl_or_b32 v42, v20, 2, v42 -v_cmpx_ge_f32_e32 v2, v2 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v20, 0, 1, s21 -v_lshl_or_b32 v42, v20, 3, v42 -v_cmpx_lg_f32_e32 v1, v2 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v20, 0, 1, s21 -v_lshl_or_b32 v42, v20, 4, v42 -v_cmpx_lg_f32_e32 v2, v3 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v20, 0, 1, s21 -v_lshl_or_b32 v42, v20, 5, v42 -v_cmpx_lg_f32_e32 v3, v2 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v20, 0, 1, s21 -v_lshl_or_b32 v42, v20, 6, v42 -v_cmpx_lg_f32_e32 v2, v2 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v20, 0, 1, s21 -v_lshl_or_b32 v42, v20, 7, v42 -v_cmpx_nge_f32_e32 v1, v2 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v20, 0, 1, s21 -v_lshl_or_b32 v42, v20, 8, v42 -v_cmpx_nge_f32_e32 v2, v3 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v20, 0, 1, s21 -v_lshl_or_b32 v42, v20, 9, v42 -v_cmpx_nge_f32_e32 v3, v2 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v20, 0, 1, s21 -v_lshl_or_b32 v42, v20, 10, v42 -v_cmpx_nge_f32_e32 v2, v2 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v20, 0, 1, s21 -v_lshl_or_b32 v42, v20, 11, v42 -v_cmpx_nlt_f32_e32 v1, v2 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v20, 0, 1, s21 -v_lshl_or_b32 v42, v20, 12, v42 -v_cmpx_nlt_f32_e32 v2, v3 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v20, 0, 1, s21 -v_lshl_or_b32 v42, v20, 13, v42 -v_cmpx_nlt_f32_e32 v3, v2 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v20, 0, 1, s21 -v_lshl_or_b32 v42, v20, 14, v42 -v_cmpx_nlt_f32_e32 v2, v2 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v20, 0, 1, s21 -v_lshl_or_b32 v42, v20, 15, v42 -; word 3: x:neq, x:o, x:tru, x:f -v_mov_b32_e32 v43, 0 -v_cmpx_neq_f32_e32 v1, v2 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v20, 0, 1, s21 -v_lshl_or_b32 v43, v20, 0, v43 -v_cmpx_neq_f32_e32 v2, v3 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v20, 0, 1, s21 -v_lshl_or_b32 v43, v20, 1, v43 -v_cmpx_neq_f32_e32 v3, v2 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v20, 0, 1, s21 -v_lshl_or_b32 v43, v20, 2, v43 -v_cmpx_neq_f32_e32 v2, v2 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v20, 0, 1, s21 -v_lshl_or_b32 v43, v20, 3, v43 -v_cmpx_o_f32_e32 v1, v2 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v20, 0, 1, s21 -v_lshl_or_b32 v43, v20, 4, v43 -v_cmpx_o_f32_e32 v2, v3 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v20, 0, 1, s21 -v_lshl_or_b32 v43, v20, 5, v43 -v_cmpx_o_f32_e32 v3, v2 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v20, 0, 1, s21 -v_lshl_or_b32 v43, v20, 6, v43 -v_cmpx_o_f32_e32 v2, v2 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v20, 0, 1, s21 -v_lshl_or_b32 v43, v20, 7, v43 -v_cmpx_tru_f32_e32 v1, v2 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v20, 0, 1, s21 -v_lshl_or_b32 v43, v20, 8, v43 -v_cmpx_tru_f32_e32 v2, v3 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v20, 0, 1, s21 -v_lshl_or_b32 v43, v20, 9, v43 -v_cmpx_tru_f32_e32 v3, v2 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v20, 0, 1, s21 -v_lshl_or_b32 v43, v20, 10, v43 -v_cmpx_tru_f32_e32 v2, v2 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v20, 0, 1, s21 -v_lshl_or_b32 v43, v20, 11, v43 -v_cmpx_f_f32_e32 v1, v2 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v20, 0, 1, s21 -v_lshl_or_b32 v43, v20, 12, v43 -v_cmpx_f_f32_e32 v2, v3 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v20, 0, 1, s21 -v_lshl_or_b32 v43, v20, 13, v43 -v_cmpx_f_f32_e32 v3, v2 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v20, 0, 1, s21 -v_lshl_or_b32 v43, v20, 14, v43 -v_cmpx_f_f32_e32 v2, v2 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v20, 0, 1, s21 -v_lshl_or_b32 v43, v20, 15, v43 -exp mrt0 v40, v41, v42, v43 done vm -s_endpgm diff --git a/runtime/test/shaders/ps_vcmp_int32.asm b/runtime/test/shaders/ps_vcmp_int32.asm deleted file mode 100644 index b90cb522a..000000000 --- a/runtime/test/shaders/ps_vcmp_int32.asm +++ /dev/null @@ -1,436 +0,0 @@ -; regen_fixtures: this source has a translator fixture in tests/semantic/fixtures/disasm -; 32-bit integer VOPC compares: v_cmp_{eq,ne,lt,le,gt,ge,f,t}_{u32,i32}, in the e32 form (VCC) and the e64 form -; (SGPR destination), with inline constants and literals as operands, on values where signed and unsigned disagree. -; The cmpx forms are in ps_vcmpx_forms; 64-bit and 16-bit compares are not covered here. -; RDNA2 ISA: _U32 compares S0.u32 with S1.u32, _I32 compares S0.i32 with S1.i32 (two's complement), per lane; -; EQ = S0 == S1, NE = S0 != S1, LT = S0 < S1, LE = S0 <= S1, GT = S0 > S1, GE = S0 >= S1, F = 0, T = 1. The result -; goes to VCC (e32) or to the SGPR pair named by VDST (e64). Inputs: the V# in s[0:3] points at 0x1000 (num_records -; 32), the test seeds 8 dwords that become v1..v6: 1, 0, 0x80000000, 0x12345678, 3, 5 (then two unused zeros). -; Five pairs (A, B) with A as src0 in e32; A is a constant or VGPR, B is a VGPR: -; P0: A = literal 0x80000000, B = v1 = 1 unsigned A > B, signed A < B -; P1: A = inline -1, B = v2 = 0 unsigned A > B (0xffffffff), signed A < B -; P2: A = inline 1, B = v3 = 0x80000000 unsigned A < B, signed A > B -; P3: A = literal 0x12345678, B = v4 = 0x12345678 equal -; P4: A = v5 = 3, B = v6 = 5 A < B both ways -; Result bit 5*k + i of a word is op k (eq, ne, lt, le, gt, ge = 0..5) on pair Pi; bit 30 is v_cmp_f on P3 (must be -; 0) and bit 31 is v_cmp_t on P0 (must be 1). The five-bit masks (bit i = Pi): -; unsigned: eq P3 = 0x08 ne P0 P1 P2 P4 = 0x17 lt P2 P4 = 0x14 le P2 P3 P4 = 0x1c -; gt P0 P1 = 0x03 ge P0 P1 P3 = 0x0b -; signed: eq P3 = 0x08 ne P0 P1 P2 P4 = 0x17 lt P0 P1 P4 = 0x13 le P0 P1 P3 P4 = 0x1b -; gt P2 = 0x04 ge P2 P3 = 0x0c -; word 0 (e32, u32) = 0x08 | 0x17<<5 | 0x14<<10 | 0x1c<<15 | 0x03<<20 | 0x0b<<25 | 1<<31 -; = 0x8 + 0x2e0 + 0x5000 + 0xe0000 + 0x300000 + 0x16000000 + 0x80000000 = 0x963e52e8 -; word 1 (e32, i32) = 0x08 | 0x17<<5 | 0x13<<10 | 0x1b<<15 | 0x04<<20 | 0x0c<<25 | 1<<31 -; = 0x8 + 0x2e0 + 0x4c00 + 0xd8000 + 0x400000 + 0x18000000 + 0x80000000 = 0x984dcee8 -; words 2 and 3 are the e64 forms with the operands swapped: src0 is the VGPR B, src1 is the constant (or v5 for -; P4), so "op(B, A)" is the mirrored relation of op(A, B): lt <-> gt and le <-> ge, eq and ne are unchanged. The -; masks by position k = eq, ne, lt, le, gt, ge are therefore the unsigned (resp. signed) masks of eq, ne, gt, ge, lt, le: -; word 2 (e64, u32) = 0x08 | 0x17<<5 | 0x03<<10 | 0x0b<<15 | 0x14<<20 | 0x1c<<25 | 1<<31 -; = 0x8 + 0x2e0 + 0xc00 + 0x58000 + 0x1400000 + 0x38000000 + 0x80000000 = 0xb9458ee8 -; word 3 (e64, i32) = 0x08 | 0x17<<5 | 0x04<<10 | 0x0c<<15 | 0x13<<20 | 0x1b<<25 | 1<<31 -; = 0x8 + 0x2e0 + 0x1000 + 0x60000 + 0x1300000 + 0x36000000 + 0x80000000 = 0xb73612e8 -; A translation that compared one of the _u32 forms signed would clear the P0/P1 ge and gt bits and set the P2 ones; -; one that compared an _i32 form unsigned would do the opposite; a v_cmp_f that returned true sets bit 30. -; Expected mrt0 bits: 0x963e52e8, 0x984dcee8, 0xb9458ee8, 0xb73612e8 -s_buffer_load_dwordx8 s[4:11], s[0:3], 0 -s_waitcnt lgkmcnt(0) -v_mov_b32_e32 v1, s4 -v_mov_b32_e32 v2, s5 -v_mov_b32_e32 v3, s6 -v_mov_b32_e32 v4, s7 -v_mov_b32_e32 v5, s8 -v_mov_b32_e32 v6, s9 -; word 0: v_cmp_*_u32_e32 -v_mov_b32_e32 v40, 0 -v_cmp_eq_u32_e32 vcc_lo, 0x80000000, v1 -v_cndmask_b32_e64 v20, 0, 1, vcc_lo -v_lshl_or_b32 v40, v20, 0, v40 -v_cmp_eq_u32_e32 vcc_lo, -1, v2 -v_cndmask_b32_e64 v20, 0, 1, vcc_lo -v_lshl_or_b32 v40, v20, 1, v40 -v_cmp_eq_u32_e32 vcc_lo, 1, v3 -v_cndmask_b32_e64 v20, 0, 1, vcc_lo -v_lshl_or_b32 v40, v20, 2, v40 -v_cmp_eq_u32_e32 vcc_lo, 0x12345678, v4 -v_cndmask_b32_e64 v20, 0, 1, vcc_lo -v_lshl_or_b32 v40, v20, 3, v40 -v_cmp_eq_u32_e32 vcc_lo, v5, v6 -v_cndmask_b32_e64 v20, 0, 1, vcc_lo -v_lshl_or_b32 v40, v20, 4, v40 -v_cmp_ne_u32_e32 vcc_lo, 0x80000000, v1 -v_cndmask_b32_e64 v20, 0, 1, vcc_lo -v_lshl_or_b32 v40, v20, 5, v40 -v_cmp_ne_u32_e32 vcc_lo, -1, v2 -v_cndmask_b32_e64 v20, 0, 1, vcc_lo -v_lshl_or_b32 v40, v20, 6, v40 -v_cmp_ne_u32_e32 vcc_lo, 1, v3 -v_cndmask_b32_e64 v20, 0, 1, vcc_lo -v_lshl_or_b32 v40, v20, 7, v40 -v_cmp_ne_u32_e32 vcc_lo, 0x12345678, v4 -v_cndmask_b32_e64 v20, 0, 1, vcc_lo -v_lshl_or_b32 v40, v20, 8, v40 -v_cmp_ne_u32_e32 vcc_lo, v5, v6 -v_cndmask_b32_e64 v20, 0, 1, vcc_lo -v_lshl_or_b32 v40, v20, 9, v40 -v_cmp_lt_u32_e32 vcc_lo, 0x80000000, v1 -v_cndmask_b32_e64 v20, 0, 1, vcc_lo -v_lshl_or_b32 v40, v20, 10, v40 -v_cmp_lt_u32_e32 vcc_lo, -1, v2 -v_cndmask_b32_e64 v20, 0, 1, vcc_lo -v_lshl_or_b32 v40, v20, 11, v40 -v_cmp_lt_u32_e32 vcc_lo, 1, v3 -v_cndmask_b32_e64 v20, 0, 1, vcc_lo -v_lshl_or_b32 v40, v20, 12, v40 -v_cmp_lt_u32_e32 vcc_lo, 0x12345678, v4 -v_cndmask_b32_e64 v20, 0, 1, vcc_lo -v_lshl_or_b32 v40, v20, 13, v40 -v_cmp_lt_u32_e32 vcc_lo, v5, v6 -v_cndmask_b32_e64 v20, 0, 1, vcc_lo -v_lshl_or_b32 v40, v20, 14, v40 -v_cmp_le_u32_e32 vcc_lo, 0x80000000, v1 -v_cndmask_b32_e64 v20, 0, 1, vcc_lo -v_lshl_or_b32 v40, v20, 15, v40 -v_cmp_le_u32_e32 vcc_lo, -1, v2 -v_cndmask_b32_e64 v20, 0, 1, vcc_lo -v_lshl_or_b32 v40, v20, 16, v40 -v_cmp_le_u32_e32 vcc_lo, 1, v3 -v_cndmask_b32_e64 v20, 0, 1, vcc_lo -v_lshl_or_b32 v40, v20, 17, v40 -v_cmp_le_u32_e32 vcc_lo, 0x12345678, v4 -v_cndmask_b32_e64 v20, 0, 1, vcc_lo -v_lshl_or_b32 v40, v20, 18, v40 -v_cmp_le_u32_e32 vcc_lo, v5, v6 -v_cndmask_b32_e64 v20, 0, 1, vcc_lo -v_lshl_or_b32 v40, v20, 19, v40 -v_cmp_gt_u32_e32 vcc_lo, 0x80000000, v1 -v_cndmask_b32_e64 v20, 0, 1, vcc_lo -v_lshl_or_b32 v40, v20, 20, v40 -v_cmp_gt_u32_e32 vcc_lo, -1, v2 -v_cndmask_b32_e64 v20, 0, 1, vcc_lo -v_lshl_or_b32 v40, v20, 21, v40 -v_cmp_gt_u32_e32 vcc_lo, 1, v3 -v_cndmask_b32_e64 v20, 0, 1, vcc_lo -v_lshl_or_b32 v40, v20, 22, v40 -v_cmp_gt_u32_e32 vcc_lo, 0x12345678, v4 -v_cndmask_b32_e64 v20, 0, 1, vcc_lo -v_lshl_or_b32 v40, v20, 23, v40 -v_cmp_gt_u32_e32 vcc_lo, v5, v6 -v_cndmask_b32_e64 v20, 0, 1, vcc_lo -v_lshl_or_b32 v40, v20, 24, v40 -v_cmp_ge_u32_e32 vcc_lo, 0x80000000, v1 -v_cndmask_b32_e64 v20, 0, 1, vcc_lo -v_lshl_or_b32 v40, v20, 25, v40 -v_cmp_ge_u32_e32 vcc_lo, -1, v2 -v_cndmask_b32_e64 v20, 0, 1, vcc_lo -v_lshl_or_b32 v40, v20, 26, v40 -v_cmp_ge_u32_e32 vcc_lo, 1, v3 -v_cndmask_b32_e64 v20, 0, 1, vcc_lo -v_lshl_or_b32 v40, v20, 27, v40 -v_cmp_ge_u32_e32 vcc_lo, 0x12345678, v4 -v_cndmask_b32_e64 v20, 0, 1, vcc_lo -v_lshl_or_b32 v40, v20, 28, v40 -v_cmp_ge_u32_e32 vcc_lo, v5, v6 -v_cndmask_b32_e64 v20, 0, 1, vcc_lo -v_lshl_or_b32 v40, v20, 29, v40 -v_cmp_f_u32_e32 vcc_lo, 0x12345678, v4 -v_cndmask_b32_e64 v20, 0, 1, vcc_lo -v_lshl_or_b32 v40, v20, 30, v40 -v_cmp_t_u32_e32 vcc_lo, 0x80000000, v1 -v_cndmask_b32_e64 v20, 0, 1, vcc_lo -v_lshl_or_b32 v40, v20, 31, v40 -; word 1: v_cmp_*_i32_e32 -v_mov_b32_e32 v41, 0 -v_cmp_eq_i32_e32 vcc_lo, 0x80000000, v1 -v_cndmask_b32_e64 v20, 0, 1, vcc_lo -v_lshl_or_b32 v41, v20, 0, v41 -v_cmp_eq_i32_e32 vcc_lo, -1, v2 -v_cndmask_b32_e64 v20, 0, 1, vcc_lo -v_lshl_or_b32 v41, v20, 1, v41 -v_cmp_eq_i32_e32 vcc_lo, 1, v3 -v_cndmask_b32_e64 v20, 0, 1, vcc_lo -v_lshl_or_b32 v41, v20, 2, v41 -v_cmp_eq_i32_e32 vcc_lo, 0x12345678, v4 -v_cndmask_b32_e64 v20, 0, 1, vcc_lo -v_lshl_or_b32 v41, v20, 3, v41 -v_cmp_eq_i32_e32 vcc_lo, v5, v6 -v_cndmask_b32_e64 v20, 0, 1, vcc_lo -v_lshl_or_b32 v41, v20, 4, v41 -v_cmp_ne_i32_e32 vcc_lo, 0x80000000, v1 -v_cndmask_b32_e64 v20, 0, 1, vcc_lo -v_lshl_or_b32 v41, v20, 5, v41 -v_cmp_ne_i32_e32 vcc_lo, -1, v2 -v_cndmask_b32_e64 v20, 0, 1, vcc_lo -v_lshl_or_b32 v41, v20, 6, v41 -v_cmp_ne_i32_e32 vcc_lo, 1, v3 -v_cndmask_b32_e64 v20, 0, 1, vcc_lo -v_lshl_or_b32 v41, v20, 7, v41 -v_cmp_ne_i32_e32 vcc_lo, 0x12345678, v4 -v_cndmask_b32_e64 v20, 0, 1, vcc_lo -v_lshl_or_b32 v41, v20, 8, v41 -v_cmp_ne_i32_e32 vcc_lo, v5, v6 -v_cndmask_b32_e64 v20, 0, 1, vcc_lo -v_lshl_or_b32 v41, v20, 9, v41 -v_cmp_lt_i32_e32 vcc_lo, 0x80000000, v1 -v_cndmask_b32_e64 v20, 0, 1, vcc_lo -v_lshl_or_b32 v41, v20, 10, v41 -v_cmp_lt_i32_e32 vcc_lo, -1, v2 -v_cndmask_b32_e64 v20, 0, 1, vcc_lo -v_lshl_or_b32 v41, v20, 11, v41 -v_cmp_lt_i32_e32 vcc_lo, 1, v3 -v_cndmask_b32_e64 v20, 0, 1, vcc_lo -v_lshl_or_b32 v41, v20, 12, v41 -v_cmp_lt_i32_e32 vcc_lo, 0x12345678, v4 -v_cndmask_b32_e64 v20, 0, 1, vcc_lo -v_lshl_or_b32 v41, v20, 13, v41 -v_cmp_lt_i32_e32 vcc_lo, v5, v6 -v_cndmask_b32_e64 v20, 0, 1, vcc_lo -v_lshl_or_b32 v41, v20, 14, v41 -v_cmp_le_i32_e32 vcc_lo, 0x80000000, v1 -v_cndmask_b32_e64 v20, 0, 1, vcc_lo -v_lshl_or_b32 v41, v20, 15, v41 -v_cmp_le_i32_e32 vcc_lo, -1, v2 -v_cndmask_b32_e64 v20, 0, 1, vcc_lo -v_lshl_or_b32 v41, v20, 16, v41 -v_cmp_le_i32_e32 vcc_lo, 1, v3 -v_cndmask_b32_e64 v20, 0, 1, vcc_lo -v_lshl_or_b32 v41, v20, 17, v41 -v_cmp_le_i32_e32 vcc_lo, 0x12345678, v4 -v_cndmask_b32_e64 v20, 0, 1, vcc_lo -v_lshl_or_b32 v41, v20, 18, v41 -v_cmp_le_i32_e32 vcc_lo, v5, v6 -v_cndmask_b32_e64 v20, 0, 1, vcc_lo -v_lshl_or_b32 v41, v20, 19, v41 -v_cmp_gt_i32_e32 vcc_lo, 0x80000000, v1 -v_cndmask_b32_e64 v20, 0, 1, vcc_lo -v_lshl_or_b32 v41, v20, 20, v41 -v_cmp_gt_i32_e32 vcc_lo, -1, v2 -v_cndmask_b32_e64 v20, 0, 1, vcc_lo -v_lshl_or_b32 v41, v20, 21, v41 -v_cmp_gt_i32_e32 vcc_lo, 1, v3 -v_cndmask_b32_e64 v20, 0, 1, vcc_lo -v_lshl_or_b32 v41, v20, 22, v41 -v_cmp_gt_i32_e32 vcc_lo, 0x12345678, v4 -v_cndmask_b32_e64 v20, 0, 1, vcc_lo -v_lshl_or_b32 v41, v20, 23, v41 -v_cmp_gt_i32_e32 vcc_lo, v5, v6 -v_cndmask_b32_e64 v20, 0, 1, vcc_lo -v_lshl_or_b32 v41, v20, 24, v41 -v_cmp_ge_i32_e32 vcc_lo, 0x80000000, v1 -v_cndmask_b32_e64 v20, 0, 1, vcc_lo -v_lshl_or_b32 v41, v20, 25, v41 -v_cmp_ge_i32_e32 vcc_lo, -1, v2 -v_cndmask_b32_e64 v20, 0, 1, vcc_lo -v_lshl_or_b32 v41, v20, 26, v41 -v_cmp_ge_i32_e32 vcc_lo, 1, v3 -v_cndmask_b32_e64 v20, 0, 1, vcc_lo -v_lshl_or_b32 v41, v20, 27, v41 -v_cmp_ge_i32_e32 vcc_lo, 0x12345678, v4 -v_cndmask_b32_e64 v20, 0, 1, vcc_lo -v_lshl_or_b32 v41, v20, 28, v41 -v_cmp_ge_i32_e32 vcc_lo, v5, v6 -v_cndmask_b32_e64 v20, 0, 1, vcc_lo -v_lshl_or_b32 v41, v20, 29, v41 -v_cmp_f_i32_e32 vcc_lo, 0x12345678, v4 -v_cndmask_b32_e64 v20, 0, 1, vcc_lo -v_lshl_or_b32 v41, v20, 30, v41 -v_cmp_t_i32_e32 vcc_lo, 0x80000000, v1 -v_cndmask_b32_e64 v20, 0, 1, vcc_lo -v_lshl_or_b32 v41, v20, 31, v41 -; word 2: v_cmp_*_u32_e64 -v_mov_b32_e32 v42, 0 -v_cmp_eq_u32_e64 s22, v1, 0x80000000 -v_cndmask_b32_e64 v20, 0, 1, s22 -v_lshl_or_b32 v42, v20, 0, v42 -v_cmp_eq_u32_e64 s22, v2, -1 -v_cndmask_b32_e64 v20, 0, 1, s22 -v_lshl_or_b32 v42, v20, 1, v42 -v_cmp_eq_u32_e64 s22, v3, 1 -v_cndmask_b32_e64 v20, 0, 1, s22 -v_lshl_or_b32 v42, v20, 2, v42 -v_cmp_eq_u32_e64 s22, v4, 0x12345678 -v_cndmask_b32_e64 v20, 0, 1, s22 -v_lshl_or_b32 v42, v20, 3, v42 -v_cmp_eq_u32_e64 s22, v6, v5 -v_cndmask_b32_e64 v20, 0, 1, s22 -v_lshl_or_b32 v42, v20, 4, v42 -v_cmp_ne_u32_e64 s22, v1, 0x80000000 -v_cndmask_b32_e64 v20, 0, 1, s22 -v_lshl_or_b32 v42, v20, 5, v42 -v_cmp_ne_u32_e64 s22, v2, -1 -v_cndmask_b32_e64 v20, 0, 1, s22 -v_lshl_or_b32 v42, v20, 6, v42 -v_cmp_ne_u32_e64 s22, v3, 1 -v_cndmask_b32_e64 v20, 0, 1, s22 -v_lshl_or_b32 v42, v20, 7, v42 -v_cmp_ne_u32_e64 s22, v4, 0x12345678 -v_cndmask_b32_e64 v20, 0, 1, s22 -v_lshl_or_b32 v42, v20, 8, v42 -v_cmp_ne_u32_e64 s22, v6, v5 -v_cndmask_b32_e64 v20, 0, 1, s22 -v_lshl_or_b32 v42, v20, 9, v42 -v_cmp_lt_u32_e64 s22, v1, 0x80000000 -v_cndmask_b32_e64 v20, 0, 1, s22 -v_lshl_or_b32 v42, v20, 10, v42 -v_cmp_lt_u32_e64 s22, v2, -1 -v_cndmask_b32_e64 v20, 0, 1, s22 -v_lshl_or_b32 v42, v20, 11, v42 -v_cmp_lt_u32_e64 s22, v3, 1 -v_cndmask_b32_e64 v20, 0, 1, s22 -v_lshl_or_b32 v42, v20, 12, v42 -v_cmp_lt_u32_e64 s22, v4, 0x12345678 -v_cndmask_b32_e64 v20, 0, 1, s22 -v_lshl_or_b32 v42, v20, 13, v42 -v_cmp_lt_u32_e64 s22, v6, v5 -v_cndmask_b32_e64 v20, 0, 1, s22 -v_lshl_or_b32 v42, v20, 14, v42 -v_cmp_le_u32_e64 s22, v1, 0x80000000 -v_cndmask_b32_e64 v20, 0, 1, s22 -v_lshl_or_b32 v42, v20, 15, v42 -v_cmp_le_u32_e64 s22, v2, -1 -v_cndmask_b32_e64 v20, 0, 1, s22 -v_lshl_or_b32 v42, v20, 16, v42 -v_cmp_le_u32_e64 s22, v3, 1 -v_cndmask_b32_e64 v20, 0, 1, s22 -v_lshl_or_b32 v42, v20, 17, v42 -v_cmp_le_u32_e64 s22, v4, 0x12345678 -v_cndmask_b32_e64 v20, 0, 1, s22 -v_lshl_or_b32 v42, v20, 18, v42 -v_cmp_le_u32_e64 s22, v6, v5 -v_cndmask_b32_e64 v20, 0, 1, s22 -v_lshl_or_b32 v42, v20, 19, v42 -v_cmp_gt_u32_e64 s22, v1, 0x80000000 -v_cndmask_b32_e64 v20, 0, 1, s22 -v_lshl_or_b32 v42, v20, 20, v42 -v_cmp_gt_u32_e64 s22, v2, -1 -v_cndmask_b32_e64 v20, 0, 1, s22 -v_lshl_or_b32 v42, v20, 21, v42 -v_cmp_gt_u32_e64 s22, v3, 1 -v_cndmask_b32_e64 v20, 0, 1, s22 -v_lshl_or_b32 v42, v20, 22, v42 -v_cmp_gt_u32_e64 s22, v4, 0x12345678 -v_cndmask_b32_e64 v20, 0, 1, s22 -v_lshl_or_b32 v42, v20, 23, v42 -v_cmp_gt_u32_e64 s22, v6, v5 -v_cndmask_b32_e64 v20, 0, 1, s22 -v_lshl_or_b32 v42, v20, 24, v42 -v_cmp_ge_u32_e64 s22, v1, 0x80000000 -v_cndmask_b32_e64 v20, 0, 1, s22 -v_lshl_or_b32 v42, v20, 25, v42 -v_cmp_ge_u32_e64 s22, v2, -1 -v_cndmask_b32_e64 v20, 0, 1, s22 -v_lshl_or_b32 v42, v20, 26, v42 -v_cmp_ge_u32_e64 s22, v3, 1 -v_cndmask_b32_e64 v20, 0, 1, s22 -v_lshl_or_b32 v42, v20, 27, v42 -v_cmp_ge_u32_e64 s22, v4, 0x12345678 -v_cndmask_b32_e64 v20, 0, 1, s22 -v_lshl_or_b32 v42, v20, 28, v42 -v_cmp_ge_u32_e64 s22, v6, v5 -v_cndmask_b32_e64 v20, 0, 1, s22 -v_lshl_or_b32 v42, v20, 29, v42 -v_cmp_f_u32_e64 s22, v4, 0x12345678 -v_cndmask_b32_e64 v20, 0, 1, s22 -v_lshl_or_b32 v42, v20, 30, v42 -v_cmp_t_u32_e64 s22, v1, 0x80000000 -v_cndmask_b32_e64 v20, 0, 1, s22 -v_lshl_or_b32 v42, v20, 31, v42 -; word 3: v_cmp_*_i32_e64 -v_mov_b32_e32 v43, 0 -v_cmp_eq_i32_e64 s22, v1, 0x80000000 -v_cndmask_b32_e64 v20, 0, 1, s22 -v_lshl_or_b32 v43, v20, 0, v43 -v_cmp_eq_i32_e64 s22, v2, -1 -v_cndmask_b32_e64 v20, 0, 1, s22 -v_lshl_or_b32 v43, v20, 1, v43 -v_cmp_eq_i32_e64 s22, v3, 1 -v_cndmask_b32_e64 v20, 0, 1, s22 -v_lshl_or_b32 v43, v20, 2, v43 -v_cmp_eq_i32_e64 s22, v4, 0x12345678 -v_cndmask_b32_e64 v20, 0, 1, s22 -v_lshl_or_b32 v43, v20, 3, v43 -v_cmp_eq_i32_e64 s22, v6, v5 -v_cndmask_b32_e64 v20, 0, 1, s22 -v_lshl_or_b32 v43, v20, 4, v43 -v_cmp_ne_i32_e64 s22, v1, 0x80000000 -v_cndmask_b32_e64 v20, 0, 1, s22 -v_lshl_or_b32 v43, v20, 5, v43 -v_cmp_ne_i32_e64 s22, v2, -1 -v_cndmask_b32_e64 v20, 0, 1, s22 -v_lshl_or_b32 v43, v20, 6, v43 -v_cmp_ne_i32_e64 s22, v3, 1 -v_cndmask_b32_e64 v20, 0, 1, s22 -v_lshl_or_b32 v43, v20, 7, v43 -v_cmp_ne_i32_e64 s22, v4, 0x12345678 -v_cndmask_b32_e64 v20, 0, 1, s22 -v_lshl_or_b32 v43, v20, 8, v43 -v_cmp_ne_i32_e64 s22, v6, v5 -v_cndmask_b32_e64 v20, 0, 1, s22 -v_lshl_or_b32 v43, v20, 9, v43 -v_cmp_lt_i32_e64 s22, v1, 0x80000000 -v_cndmask_b32_e64 v20, 0, 1, s22 -v_lshl_or_b32 v43, v20, 10, v43 -v_cmp_lt_i32_e64 s22, v2, -1 -v_cndmask_b32_e64 v20, 0, 1, s22 -v_lshl_or_b32 v43, v20, 11, v43 -v_cmp_lt_i32_e64 s22, v3, 1 -v_cndmask_b32_e64 v20, 0, 1, s22 -v_lshl_or_b32 v43, v20, 12, v43 -v_cmp_lt_i32_e64 s22, v4, 0x12345678 -v_cndmask_b32_e64 v20, 0, 1, s22 -v_lshl_or_b32 v43, v20, 13, v43 -v_cmp_lt_i32_e64 s22, v6, v5 -v_cndmask_b32_e64 v20, 0, 1, s22 -v_lshl_or_b32 v43, v20, 14, v43 -v_cmp_le_i32_e64 s22, v1, 0x80000000 -v_cndmask_b32_e64 v20, 0, 1, s22 -v_lshl_or_b32 v43, v20, 15, v43 -v_cmp_le_i32_e64 s22, v2, -1 -v_cndmask_b32_e64 v20, 0, 1, s22 -v_lshl_or_b32 v43, v20, 16, v43 -v_cmp_le_i32_e64 s22, v3, 1 -v_cndmask_b32_e64 v20, 0, 1, s22 -v_lshl_or_b32 v43, v20, 17, v43 -v_cmp_le_i32_e64 s22, v4, 0x12345678 -v_cndmask_b32_e64 v20, 0, 1, s22 -v_lshl_or_b32 v43, v20, 18, v43 -v_cmp_le_i32_e64 s22, v6, v5 -v_cndmask_b32_e64 v20, 0, 1, s22 -v_lshl_or_b32 v43, v20, 19, v43 -v_cmp_gt_i32_e64 s22, v1, 0x80000000 -v_cndmask_b32_e64 v20, 0, 1, s22 -v_lshl_or_b32 v43, v20, 20, v43 -v_cmp_gt_i32_e64 s22, v2, -1 -v_cndmask_b32_e64 v20, 0, 1, s22 -v_lshl_or_b32 v43, v20, 21, v43 -v_cmp_gt_i32_e64 s22, v3, 1 -v_cndmask_b32_e64 v20, 0, 1, s22 -v_lshl_or_b32 v43, v20, 22, v43 -v_cmp_gt_i32_e64 s22, v4, 0x12345678 -v_cndmask_b32_e64 v20, 0, 1, s22 -v_lshl_or_b32 v43, v20, 23, v43 -v_cmp_gt_i32_e64 s22, v6, v5 -v_cndmask_b32_e64 v20, 0, 1, s22 -v_lshl_or_b32 v43, v20, 24, v43 -v_cmp_ge_i32_e64 s22, v1, 0x80000000 -v_cndmask_b32_e64 v20, 0, 1, s22 -v_lshl_or_b32 v43, v20, 25, v43 -v_cmp_ge_i32_e64 s22, v2, -1 -v_cndmask_b32_e64 v20, 0, 1, s22 -v_lshl_or_b32 v43, v20, 26, v43 -v_cmp_ge_i32_e64 s22, v3, 1 -v_cndmask_b32_e64 v20, 0, 1, s22 -v_lshl_or_b32 v43, v20, 27, v43 -v_cmp_ge_i32_e64 s22, v4, 0x12345678 -v_cndmask_b32_e64 v20, 0, 1, s22 -v_lshl_or_b32 v43, v20, 28, v43 -v_cmp_ge_i32_e64 s22, v6, v5 -v_cndmask_b32_e64 v20, 0, 1, s22 -v_lshl_or_b32 v43, v20, 29, v43 -v_cmp_f_i32_e64 s22, v4, 0x12345678 -v_cndmask_b32_e64 v20, 0, 1, s22 -v_lshl_or_b32 v43, v20, 30, v43 -v_cmp_t_i32_e64 s22, v1, 0x80000000 -v_cndmask_b32_e64 v20, 0, 1, s22 -v_lshl_or_b32 v43, v20, 31, v43 -exp mrt0 v40, v41, v42, v43 done vm -s_endpgm diff --git a/runtime/test/shaders/ps_vcmpx_f16.asm b/runtime/test/shaders/ps_vcmpx_f16.asm deleted file mode 100644 index 604a3bd5a..000000000 --- a/runtime/test/shaders/ps_vcmpx_f16.asm +++ /dev/null @@ -1,654 +0,0 @@ -; regen_fixtures: this source has a translator fixture in tests/semantic/fixtures/disasm -; 16-bit float v_cmpx, e32 form: v_cmpx_{f,lt,eq,le,gt,lg,ge,o,u,nge,nlg,ngt,nle,neq,nlt,tru}_f16 on the seven operand -; pairs of ps_vcmp_f16 (see that header for the case list and the ISA rules of the 16 predicates: bits 15:0 of the -; operands only, ordered compares false for a NaN, +0 == -0, denormals kept). A v_cmpx writes the result to EXEC -; (EXEC = EXEC & compare, per lane) and to nothing else, so VCC is kept. Each compare runs alone: EXEC is copied out -; and put back after it (s20 holds the EXEC the shader started with, s21 the copy), so a lane that was true shows as 1 -; and every lane has the same operands. Cases (A = src0, B = src1; the junk is the high half that must be ignored): -; k0: A = inline 1.0, B = 0x1234:2.0 less k4: A = 0x5555:1.0, B = 0x7c00:sNaN 0x7c01 unordered -; k1: A = inline 2.0, B = 0xabcd:1.0 greater k5: A = 0x0001:+inf, B = 0xbeef:-inf greater -; k2: A = inline 0, B = 0xffff:-0 equal k6: A = 0xdead:0x0001, B = 0x8000:0x0002 less (denormals) -; k3: A = 0xffff:qNaN 0x7e00, B = 0x0001:1.0 unordered -; Relation sets: LESS = {k0,k6} = 0x41, GREATER = {k1,k5} = 0x22, EQUAL = {k2} = 0x04, UNORDERED = {k3,k4} = 0x18; the -; mask of an op (bit k = result on case k) is the union of the sets it is true for: -; f 0x00 lt 0x41 eq 0x04 le 0x45 gt 0x22 lg 0x63 ge 0x26 o 0x67 -; u 0x18 nge 0x59 nlg 0x1c ngt 0x5d nle 0x3a neq 0x7b nlt 0x3e tru 0x7f -; Word w holds ops 4w..4w+3 (the order above), op j at bit 7*j + k. Three more bits per word, from one op of the form: -; bit 30: always 1 (keeps the float export away from denormal and NaN patterns). -; bit 29: VCC = 1 in every lane (v_cmp_tru_f16 v8, v8), then v_cmpx_f_f16 empties EXEC; after EXEC is restored VCC -; must still be 1, because a v_cmpx writes EXEC only: the bit is 1. -; bit 28: v_cmpx_f_f16 empties EXEC, the v_cmpx_tru_f16 after it is true in every lane, but v_cmpx only ANDs into -; EXEC, so no lane comes back: the bit is 0. -; word 0 = 0x60000000 | 0x00 | 0x41<<7 | 0x04<<14 | 0x45<<21 = 0x60000000 + 0x2080 + 0x10000 + 0x8a00000 = 0x68a12080 -; word 1 = 0x60000000 | 0x22 | 0x63<<7 | 0x26<<14 | 0x67<<21 = 0x60000000 + 0x31a2 + 0x98000 + 0xce00000 = 0x6ce9b1a2 -; word 2 = 0x60000000 | 0x18 | 0x59<<7 | 0x1c<<14 | 0x5d<<21 = 0x60000000 + 0x2c98 + 0x70000 + 0xba00000 = 0x6ba72c98 -; word 3 = 0x60000000 | 0x3a | 0x7b<<7 | 0x3e<<14 | 0x7f<<21 = 0x60000000 + 0x3dba + 0xf8000 + 0xfe00000 = 0x6fefbdba -; A v_cmpx that wrote VCC, or did not AND with the old EXEC, flips bit 29 or bit 28; one that ordered a NaN, flushed a -; denormal, took -0 below +0 or read the high halves moves bits in the words. -; Expected mrt0 bits: 0x68a12080, 0x6ce9b1a2, 0x6ba72c98, 0x6fefbdba -v_mov_b32_e32 v8, 0x12344000 -v_mov_b32_e32 v9, 0xabcd3c00 -v_mov_b32_e32 v10, 0xffff8000 -v_mov_b32_e32 v4, 0xffff7e00 -v_mov_b32_e32 v11, 0x00013c00 -v_mov_b32_e32 v5, 0x55553c00 -v_mov_b32_e32 v12, 0x7c007c01 -v_mov_b32_e32 v6, 0x00017c00 -v_mov_b32_e32 v13, 0xbeeffc00 -v_mov_b32_e32 v7, 0xdead0001 -v_mov_b32_e32 v14, 0x80000002 -s_mov_b32 s20, exec_lo -v_mov_b32_e32 v40, 0x40000000 -v_cmp_tru_f16_e32 vcc_lo, v8, v8 -v_cmpx_f_f16_e32 v8, v8 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, vcc_lo -v_lshl_or_b32 v40, v30, 29, v40 -v_cmpx_f_f16_e32 v8, v8 -v_cmpx_tru_f16_e32 v8, v8 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v40, v30, 28, v40 -v_cmpx_f_f16_e32 1.0, v8 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v40, v30, 0, v40 -v_cmpx_f_f16_e32 2.0, v9 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v40, v30, 1, v40 -v_cmpx_f_f16_e32 0, v10 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v40, v30, 2, v40 -v_cmpx_f_f16_e32 v4, v11 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v40, v30, 3, v40 -v_cmpx_f_f16_e32 v5, v12 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v40, v30, 4, v40 -v_cmpx_f_f16_e32 v6, v13 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v40, v30, 5, v40 -v_cmpx_f_f16_e32 v7, v14 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v40, v30, 6, v40 -v_cmpx_lt_f16_e32 1.0, v8 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v40, v30, 7, v40 -v_cmpx_lt_f16_e32 2.0, v9 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v40, v30, 8, v40 -v_cmpx_lt_f16_e32 0, v10 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v40, v30, 9, v40 -v_cmpx_lt_f16_e32 v4, v11 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v40, v30, 10, v40 -v_cmpx_lt_f16_e32 v5, v12 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v40, v30, 11, v40 -v_cmpx_lt_f16_e32 v6, v13 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v40, v30, 12, v40 -v_cmpx_lt_f16_e32 v7, v14 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v40, v30, 13, v40 -v_cmpx_eq_f16_e32 1.0, v8 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v40, v30, 14, v40 -v_cmpx_eq_f16_e32 2.0, v9 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v40, v30, 15, v40 -v_cmpx_eq_f16_e32 0, v10 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v40, v30, 16, v40 -v_cmpx_eq_f16_e32 v4, v11 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v40, v30, 17, v40 -v_cmpx_eq_f16_e32 v5, v12 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v40, v30, 18, v40 -v_cmpx_eq_f16_e32 v6, v13 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v40, v30, 19, v40 -v_cmpx_eq_f16_e32 v7, v14 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v40, v30, 20, v40 -v_cmpx_le_f16_e32 1.0, v8 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v40, v30, 21, v40 -v_cmpx_le_f16_e32 2.0, v9 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v40, v30, 22, v40 -v_cmpx_le_f16_e32 0, v10 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v40, v30, 23, v40 -v_cmpx_le_f16_e32 v4, v11 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v40, v30, 24, v40 -v_cmpx_le_f16_e32 v5, v12 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v40, v30, 25, v40 -v_cmpx_le_f16_e32 v6, v13 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v40, v30, 26, v40 -v_cmpx_le_f16_e32 v7, v14 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v40, v30, 27, v40 -v_mov_b32_e32 v41, 0x40000000 -v_cmp_tru_f16_e32 vcc_lo, v8, v8 -v_cmpx_f_f16_e32 v8, v8 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, vcc_lo -v_lshl_or_b32 v41, v30, 29, v41 -v_cmpx_f_f16_e32 v8, v8 -v_cmpx_tru_f16_e32 v8, v8 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v41, v30, 28, v41 -v_cmpx_gt_f16_e32 1.0, v8 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v41, v30, 0, v41 -v_cmpx_gt_f16_e32 2.0, v9 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v41, v30, 1, v41 -v_cmpx_gt_f16_e32 0, v10 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v41, v30, 2, v41 -v_cmpx_gt_f16_e32 v4, v11 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v41, v30, 3, v41 -v_cmpx_gt_f16_e32 v5, v12 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v41, v30, 4, v41 -v_cmpx_gt_f16_e32 v6, v13 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v41, v30, 5, v41 -v_cmpx_gt_f16_e32 v7, v14 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v41, v30, 6, v41 -v_cmpx_lg_f16_e32 1.0, v8 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v41, v30, 7, v41 -v_cmpx_lg_f16_e32 2.0, v9 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v41, v30, 8, v41 -v_cmpx_lg_f16_e32 0, v10 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v41, v30, 9, v41 -v_cmpx_lg_f16_e32 v4, v11 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v41, v30, 10, v41 -v_cmpx_lg_f16_e32 v5, v12 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v41, v30, 11, v41 -v_cmpx_lg_f16_e32 v6, v13 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v41, v30, 12, v41 -v_cmpx_lg_f16_e32 v7, v14 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v41, v30, 13, v41 -v_cmpx_ge_f16_e32 1.0, v8 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v41, v30, 14, v41 -v_cmpx_ge_f16_e32 2.0, v9 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v41, v30, 15, v41 -v_cmpx_ge_f16_e32 0, v10 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v41, v30, 16, v41 -v_cmpx_ge_f16_e32 v4, v11 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v41, v30, 17, v41 -v_cmpx_ge_f16_e32 v5, v12 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v41, v30, 18, v41 -v_cmpx_ge_f16_e32 v6, v13 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v41, v30, 19, v41 -v_cmpx_ge_f16_e32 v7, v14 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v41, v30, 20, v41 -v_cmpx_o_f16_e32 1.0, v8 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v41, v30, 21, v41 -v_cmpx_o_f16_e32 2.0, v9 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v41, v30, 22, v41 -v_cmpx_o_f16_e32 0, v10 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v41, v30, 23, v41 -v_cmpx_o_f16_e32 v4, v11 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v41, v30, 24, v41 -v_cmpx_o_f16_e32 v5, v12 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v41, v30, 25, v41 -v_cmpx_o_f16_e32 v6, v13 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v41, v30, 26, v41 -v_cmpx_o_f16_e32 v7, v14 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v41, v30, 27, v41 -v_mov_b32_e32 v42, 0x40000000 -v_cmp_tru_f16_e32 vcc_lo, v8, v8 -v_cmpx_f_f16_e32 v8, v8 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, vcc_lo -v_lshl_or_b32 v42, v30, 29, v42 -v_cmpx_f_f16_e32 v8, v8 -v_cmpx_tru_f16_e32 v8, v8 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v42, v30, 28, v42 -v_cmpx_u_f16_e32 1.0, v8 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v42, v30, 0, v42 -v_cmpx_u_f16_e32 2.0, v9 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v42, v30, 1, v42 -v_cmpx_u_f16_e32 0, v10 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v42, v30, 2, v42 -v_cmpx_u_f16_e32 v4, v11 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v42, v30, 3, v42 -v_cmpx_u_f16_e32 v5, v12 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v42, v30, 4, v42 -v_cmpx_u_f16_e32 v6, v13 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v42, v30, 5, v42 -v_cmpx_u_f16_e32 v7, v14 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v42, v30, 6, v42 -v_cmpx_nge_f16_e32 1.0, v8 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v42, v30, 7, v42 -v_cmpx_nge_f16_e32 2.0, v9 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v42, v30, 8, v42 -v_cmpx_nge_f16_e32 0, v10 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v42, v30, 9, v42 -v_cmpx_nge_f16_e32 v4, v11 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v42, v30, 10, v42 -v_cmpx_nge_f16_e32 v5, v12 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v42, v30, 11, v42 -v_cmpx_nge_f16_e32 v6, v13 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v42, v30, 12, v42 -v_cmpx_nge_f16_e32 v7, v14 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v42, v30, 13, v42 -v_cmpx_nlg_f16_e32 1.0, v8 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v42, v30, 14, v42 -v_cmpx_nlg_f16_e32 2.0, v9 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v42, v30, 15, v42 -v_cmpx_nlg_f16_e32 0, v10 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v42, v30, 16, v42 -v_cmpx_nlg_f16_e32 v4, v11 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v42, v30, 17, v42 -v_cmpx_nlg_f16_e32 v5, v12 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v42, v30, 18, v42 -v_cmpx_nlg_f16_e32 v6, v13 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v42, v30, 19, v42 -v_cmpx_nlg_f16_e32 v7, v14 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v42, v30, 20, v42 -v_cmpx_ngt_f16_e32 1.0, v8 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v42, v30, 21, v42 -v_cmpx_ngt_f16_e32 2.0, v9 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v42, v30, 22, v42 -v_cmpx_ngt_f16_e32 0, v10 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v42, v30, 23, v42 -v_cmpx_ngt_f16_e32 v4, v11 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v42, v30, 24, v42 -v_cmpx_ngt_f16_e32 v5, v12 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v42, v30, 25, v42 -v_cmpx_ngt_f16_e32 v6, v13 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v42, v30, 26, v42 -v_cmpx_ngt_f16_e32 v7, v14 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v42, v30, 27, v42 -v_mov_b32_e32 v43, 0x40000000 -v_cmp_tru_f16_e32 vcc_lo, v8, v8 -v_cmpx_f_f16_e32 v8, v8 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, vcc_lo -v_lshl_or_b32 v43, v30, 29, v43 -v_cmpx_f_f16_e32 v8, v8 -v_cmpx_tru_f16_e32 v8, v8 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v43, v30, 28, v43 -v_cmpx_nle_f16_e32 1.0, v8 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v43, v30, 0, v43 -v_cmpx_nle_f16_e32 2.0, v9 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v43, v30, 1, v43 -v_cmpx_nle_f16_e32 0, v10 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v43, v30, 2, v43 -v_cmpx_nle_f16_e32 v4, v11 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v43, v30, 3, v43 -v_cmpx_nle_f16_e32 v5, v12 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v43, v30, 4, v43 -v_cmpx_nle_f16_e32 v6, v13 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v43, v30, 5, v43 -v_cmpx_nle_f16_e32 v7, v14 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v43, v30, 6, v43 -v_cmpx_neq_f16_e32 1.0, v8 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v43, v30, 7, v43 -v_cmpx_neq_f16_e32 2.0, v9 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v43, v30, 8, v43 -v_cmpx_neq_f16_e32 0, v10 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v43, v30, 9, v43 -v_cmpx_neq_f16_e32 v4, v11 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v43, v30, 10, v43 -v_cmpx_neq_f16_e32 v5, v12 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v43, v30, 11, v43 -v_cmpx_neq_f16_e32 v6, v13 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v43, v30, 12, v43 -v_cmpx_neq_f16_e32 v7, v14 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v43, v30, 13, v43 -v_cmpx_nlt_f16_e32 1.0, v8 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v43, v30, 14, v43 -v_cmpx_nlt_f16_e32 2.0, v9 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v43, v30, 15, v43 -v_cmpx_nlt_f16_e32 0, v10 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v43, v30, 16, v43 -v_cmpx_nlt_f16_e32 v4, v11 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v43, v30, 17, v43 -v_cmpx_nlt_f16_e32 v5, v12 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v43, v30, 18, v43 -v_cmpx_nlt_f16_e32 v6, v13 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v43, v30, 19, v43 -v_cmpx_nlt_f16_e32 v7, v14 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v43, v30, 20, v43 -v_cmpx_tru_f16_e32 1.0, v8 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v43, v30, 21, v43 -v_cmpx_tru_f16_e32 2.0, v9 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v43, v30, 22, v43 -v_cmpx_tru_f16_e32 0, v10 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v43, v30, 23, v43 -v_cmpx_tru_f16_e32 v4, v11 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v43, v30, 24, v43 -v_cmpx_tru_f16_e32 v5, v12 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v43, v30, 25, v43 -v_cmpx_tru_f16_e32 v6, v13 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v43, v30, 26, v43 -v_cmpx_tru_f16_e32 v7, v14 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v43, v30, 27, v43 -exp mrt0 v40, v41, v42, v43 done vm -s_endpgm diff --git a/runtime/test/shaders/ps_vcmpx_f16_e64.asm b/runtime/test/shaders/ps_vcmpx_f16_e64.asm deleted file mode 100644 index 5bfe410c3..000000000 --- a/runtime/test/shaders/ps_vcmpx_f16_e64.asm +++ /dev/null @@ -1,640 +0,0 @@ -; regen_fixtures: this source has a translator fixture in tests/semantic/fixtures/disasm -; 16-bit float v_cmpx, e64 form with swapped operands: v_cmpx_{f,lt,eq,le,gt,lg,ge,o,u,nge,nlg,ngt,nle,neq,nlt,tru}_f16_e64 -; B, A (no SDST: the VOP3 form of v_cmpx writes EXEC). Same seven operand pairs, EXEC copy-out/restore and VCC/AND bits -; as ps_vcmpx_f16 (see its header), but src0 is the VGPR B and src1 is A (the inline constant for k0..k2), so each op -; sees the mirrored relation: LESS = {k1,k5} = 0x22, GREATER = {k0,k6} = 0x41, EQUAL = {k2} = 0x04, -; UNORDERED = {k3,k4} = 0x18. Masks (bit k = result on case k): -; f 0x00 lt 0x22 eq 0x04 le 0x26 gt 0x41 lg 0x63 ge 0x45 o 0x67 -; u 0x18 nge 0x3a nlg 0x1c ngt 0x3e nle 0x59 neq 0x7b nlt 0x5d tru 0x7f -; Word w holds ops 4w..4w+3, op j at bit 7*j + k; bit 30 = 1, bit 29 = 1 (VCC kept), bit 28 = 0 (AND into EXEC): -; word 0 = 0x60000000 | 0x00 | 0x22<<7 | 0x04<<14 | 0x26<<21 = 0x60000000 + 0x1100 + 0x10000 + 0x4c00000 = 0x64c11100 -; word 1 = 0x60000000 | 0x41 | 0x63<<7 | 0x45<<14 | 0x67<<21 = 0x60000000 + 0x31c1 + 0x114000 + 0xce00000 = 0x6cf171c1 -; word 2 = 0x60000000 | 0x18 | 0x3a<<7 | 0x1c<<14 | 0x3e<<21 = 0x60000000 + 0x1d18 + 0x70000 + 0x7c00000 = 0x67c71d18 -; word 3 = 0x60000000 | 0x59 | 0x7b<<7 | 0x5d<<14 | 0x7f<<21 = 0x60000000 + 0x3dd9 + 0x174000 + 0xfe00000 = 0x6ff77dd9 -; Expected mrt0 bits: 0x64c11100, 0x6cf171c1, 0x67c71d18, 0x6ff77dd9 -v_mov_b32_e32 v8, 0x12344000 -v_mov_b32_e32 v9, 0xabcd3c00 -v_mov_b32_e32 v10, 0xffff8000 -v_mov_b32_e32 v4, 0xffff7e00 -v_mov_b32_e32 v11, 0x00013c00 -v_mov_b32_e32 v5, 0x55553c00 -v_mov_b32_e32 v12, 0x7c007c01 -v_mov_b32_e32 v6, 0x00017c00 -v_mov_b32_e32 v13, 0xbeeffc00 -v_mov_b32_e32 v7, 0xdead0001 -v_mov_b32_e32 v14, 0x80000002 -s_mov_b32 s20, exec_lo -v_mov_b32_e32 v40, 0x40000000 -v_cmp_tru_f16_e32 vcc_lo, v8, v8 -v_cmpx_f_f16_e64 v8, v8 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, vcc_lo -v_lshl_or_b32 v40, v30, 29, v40 -v_cmpx_f_f16_e64 v8, v8 -v_cmpx_tru_f16_e64 v8, v8 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v40, v30, 28, v40 -v_cmpx_f_f16_e64 v8, 1.0 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v40, v30, 0, v40 -v_cmpx_f_f16_e64 v9, 2.0 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v40, v30, 1, v40 -v_cmpx_f_f16_e64 v10, 0 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v40, v30, 2, v40 -v_cmpx_f_f16_e64 v11, v4 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v40, v30, 3, v40 -v_cmpx_f_f16_e64 v12, v5 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v40, v30, 4, v40 -v_cmpx_f_f16_e64 v13, v6 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v40, v30, 5, v40 -v_cmpx_f_f16_e64 v14, v7 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v40, v30, 6, v40 -v_cmpx_lt_f16_e64 v8, 1.0 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v40, v30, 7, v40 -v_cmpx_lt_f16_e64 v9, 2.0 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v40, v30, 8, v40 -v_cmpx_lt_f16_e64 v10, 0 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v40, v30, 9, v40 -v_cmpx_lt_f16_e64 v11, v4 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v40, v30, 10, v40 -v_cmpx_lt_f16_e64 v12, v5 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v40, v30, 11, v40 -v_cmpx_lt_f16_e64 v13, v6 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v40, v30, 12, v40 -v_cmpx_lt_f16_e64 v14, v7 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v40, v30, 13, v40 -v_cmpx_eq_f16_e64 v8, 1.0 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v40, v30, 14, v40 -v_cmpx_eq_f16_e64 v9, 2.0 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v40, v30, 15, v40 -v_cmpx_eq_f16_e64 v10, 0 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v40, v30, 16, v40 -v_cmpx_eq_f16_e64 v11, v4 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v40, v30, 17, v40 -v_cmpx_eq_f16_e64 v12, v5 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v40, v30, 18, v40 -v_cmpx_eq_f16_e64 v13, v6 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v40, v30, 19, v40 -v_cmpx_eq_f16_e64 v14, v7 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v40, v30, 20, v40 -v_cmpx_le_f16_e64 v8, 1.0 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v40, v30, 21, v40 -v_cmpx_le_f16_e64 v9, 2.0 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v40, v30, 22, v40 -v_cmpx_le_f16_e64 v10, 0 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v40, v30, 23, v40 -v_cmpx_le_f16_e64 v11, v4 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v40, v30, 24, v40 -v_cmpx_le_f16_e64 v12, v5 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v40, v30, 25, v40 -v_cmpx_le_f16_e64 v13, v6 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v40, v30, 26, v40 -v_cmpx_le_f16_e64 v14, v7 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v40, v30, 27, v40 -v_mov_b32_e32 v41, 0x40000000 -v_cmp_tru_f16_e32 vcc_lo, v8, v8 -v_cmpx_f_f16_e64 v8, v8 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, vcc_lo -v_lshl_or_b32 v41, v30, 29, v41 -v_cmpx_f_f16_e64 v8, v8 -v_cmpx_tru_f16_e64 v8, v8 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v41, v30, 28, v41 -v_cmpx_gt_f16_e64 v8, 1.0 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v41, v30, 0, v41 -v_cmpx_gt_f16_e64 v9, 2.0 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v41, v30, 1, v41 -v_cmpx_gt_f16_e64 v10, 0 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v41, v30, 2, v41 -v_cmpx_gt_f16_e64 v11, v4 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v41, v30, 3, v41 -v_cmpx_gt_f16_e64 v12, v5 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v41, v30, 4, v41 -v_cmpx_gt_f16_e64 v13, v6 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v41, v30, 5, v41 -v_cmpx_gt_f16_e64 v14, v7 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v41, v30, 6, v41 -v_cmpx_lg_f16_e64 v8, 1.0 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v41, v30, 7, v41 -v_cmpx_lg_f16_e64 v9, 2.0 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v41, v30, 8, v41 -v_cmpx_lg_f16_e64 v10, 0 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v41, v30, 9, v41 -v_cmpx_lg_f16_e64 v11, v4 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v41, v30, 10, v41 -v_cmpx_lg_f16_e64 v12, v5 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v41, v30, 11, v41 -v_cmpx_lg_f16_e64 v13, v6 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v41, v30, 12, v41 -v_cmpx_lg_f16_e64 v14, v7 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v41, v30, 13, v41 -v_cmpx_ge_f16_e64 v8, 1.0 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v41, v30, 14, v41 -v_cmpx_ge_f16_e64 v9, 2.0 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v41, v30, 15, v41 -v_cmpx_ge_f16_e64 v10, 0 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v41, v30, 16, v41 -v_cmpx_ge_f16_e64 v11, v4 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v41, v30, 17, v41 -v_cmpx_ge_f16_e64 v12, v5 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v41, v30, 18, v41 -v_cmpx_ge_f16_e64 v13, v6 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v41, v30, 19, v41 -v_cmpx_ge_f16_e64 v14, v7 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v41, v30, 20, v41 -v_cmpx_o_f16_e64 v8, 1.0 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v41, v30, 21, v41 -v_cmpx_o_f16_e64 v9, 2.0 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v41, v30, 22, v41 -v_cmpx_o_f16_e64 v10, 0 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v41, v30, 23, v41 -v_cmpx_o_f16_e64 v11, v4 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v41, v30, 24, v41 -v_cmpx_o_f16_e64 v12, v5 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v41, v30, 25, v41 -v_cmpx_o_f16_e64 v13, v6 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v41, v30, 26, v41 -v_cmpx_o_f16_e64 v14, v7 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v41, v30, 27, v41 -v_mov_b32_e32 v42, 0x40000000 -v_cmp_tru_f16_e32 vcc_lo, v8, v8 -v_cmpx_f_f16_e64 v8, v8 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, vcc_lo -v_lshl_or_b32 v42, v30, 29, v42 -v_cmpx_f_f16_e64 v8, v8 -v_cmpx_tru_f16_e64 v8, v8 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v42, v30, 28, v42 -v_cmpx_u_f16_e64 v8, 1.0 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v42, v30, 0, v42 -v_cmpx_u_f16_e64 v9, 2.0 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v42, v30, 1, v42 -v_cmpx_u_f16_e64 v10, 0 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v42, v30, 2, v42 -v_cmpx_u_f16_e64 v11, v4 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v42, v30, 3, v42 -v_cmpx_u_f16_e64 v12, v5 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v42, v30, 4, v42 -v_cmpx_u_f16_e64 v13, v6 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v42, v30, 5, v42 -v_cmpx_u_f16_e64 v14, v7 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v42, v30, 6, v42 -v_cmpx_nge_f16_e64 v8, 1.0 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v42, v30, 7, v42 -v_cmpx_nge_f16_e64 v9, 2.0 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v42, v30, 8, v42 -v_cmpx_nge_f16_e64 v10, 0 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v42, v30, 9, v42 -v_cmpx_nge_f16_e64 v11, v4 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v42, v30, 10, v42 -v_cmpx_nge_f16_e64 v12, v5 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v42, v30, 11, v42 -v_cmpx_nge_f16_e64 v13, v6 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v42, v30, 12, v42 -v_cmpx_nge_f16_e64 v14, v7 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v42, v30, 13, v42 -v_cmpx_nlg_f16_e64 v8, 1.0 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v42, v30, 14, v42 -v_cmpx_nlg_f16_e64 v9, 2.0 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v42, v30, 15, v42 -v_cmpx_nlg_f16_e64 v10, 0 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v42, v30, 16, v42 -v_cmpx_nlg_f16_e64 v11, v4 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v42, v30, 17, v42 -v_cmpx_nlg_f16_e64 v12, v5 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v42, v30, 18, v42 -v_cmpx_nlg_f16_e64 v13, v6 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v42, v30, 19, v42 -v_cmpx_nlg_f16_e64 v14, v7 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v42, v30, 20, v42 -v_cmpx_ngt_f16_e64 v8, 1.0 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v42, v30, 21, v42 -v_cmpx_ngt_f16_e64 v9, 2.0 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v42, v30, 22, v42 -v_cmpx_ngt_f16_e64 v10, 0 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v42, v30, 23, v42 -v_cmpx_ngt_f16_e64 v11, v4 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v42, v30, 24, v42 -v_cmpx_ngt_f16_e64 v12, v5 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v42, v30, 25, v42 -v_cmpx_ngt_f16_e64 v13, v6 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v42, v30, 26, v42 -v_cmpx_ngt_f16_e64 v14, v7 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v42, v30, 27, v42 -v_mov_b32_e32 v43, 0x40000000 -v_cmp_tru_f16_e32 vcc_lo, v8, v8 -v_cmpx_f_f16_e64 v8, v8 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, vcc_lo -v_lshl_or_b32 v43, v30, 29, v43 -v_cmpx_f_f16_e64 v8, v8 -v_cmpx_tru_f16_e64 v8, v8 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v43, v30, 28, v43 -v_cmpx_nle_f16_e64 v8, 1.0 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v43, v30, 0, v43 -v_cmpx_nle_f16_e64 v9, 2.0 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v43, v30, 1, v43 -v_cmpx_nle_f16_e64 v10, 0 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v43, v30, 2, v43 -v_cmpx_nle_f16_e64 v11, v4 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v43, v30, 3, v43 -v_cmpx_nle_f16_e64 v12, v5 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v43, v30, 4, v43 -v_cmpx_nle_f16_e64 v13, v6 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v43, v30, 5, v43 -v_cmpx_nle_f16_e64 v14, v7 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v43, v30, 6, v43 -v_cmpx_neq_f16_e64 v8, 1.0 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v43, v30, 7, v43 -v_cmpx_neq_f16_e64 v9, 2.0 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v43, v30, 8, v43 -v_cmpx_neq_f16_e64 v10, 0 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v43, v30, 9, v43 -v_cmpx_neq_f16_e64 v11, v4 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v43, v30, 10, v43 -v_cmpx_neq_f16_e64 v12, v5 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v43, v30, 11, v43 -v_cmpx_neq_f16_e64 v13, v6 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v43, v30, 12, v43 -v_cmpx_neq_f16_e64 v14, v7 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v43, v30, 13, v43 -v_cmpx_nlt_f16_e64 v8, 1.0 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v43, v30, 14, v43 -v_cmpx_nlt_f16_e64 v9, 2.0 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v43, v30, 15, v43 -v_cmpx_nlt_f16_e64 v10, 0 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v43, v30, 16, v43 -v_cmpx_nlt_f16_e64 v11, v4 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v43, v30, 17, v43 -v_cmpx_nlt_f16_e64 v12, v5 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v43, v30, 18, v43 -v_cmpx_nlt_f16_e64 v13, v6 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v43, v30, 19, v43 -v_cmpx_nlt_f16_e64 v14, v7 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v43, v30, 20, v43 -v_cmpx_tru_f16_e64 v8, 1.0 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v43, v30, 21, v43 -v_cmpx_tru_f16_e64 v9, 2.0 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v43, v30, 22, v43 -v_cmpx_tru_f16_e64 v10, 0 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v43, v30, 23, v43 -v_cmpx_tru_f16_e64 v11, v4 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v43, v30, 24, v43 -v_cmpx_tru_f16_e64 v12, v5 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v43, v30, 25, v43 -v_cmpx_tru_f16_e64 v13, v6 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v43, v30, 26, v43 -v_cmpx_tru_f16_e64 v14, v7 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v43, v30, 27, v43 -exp mrt0 v40, v41, v42, v43 done vm -s_endpgm diff --git a/runtime/test/shaders/ps_vcmpx_forms.asm b/runtime/test/shaders/ps_vcmpx_forms.asm deleted file mode 100644 index 49b2f6931..000000000 --- a/runtime/test/shaders/ps_vcmpx_forms.asm +++ /dev/null @@ -1,711 +0,0 @@ -; regen_fixtures: this source has a translator fixture in tests/semantic/fixtures/disasm -; The 14 v_cmpx forms no test ran: v_cmpx_{eq,gt,le,lt,ngt,nle}_f32, v_cmpx_f_i32, v_cmpx_t_u32, -; v_cmpx_{eq,gt,le}_i64 and v_cmpx_{ge,lt,ne}_u64. RDNA2 ISA: EXEC = EXEC & compare(S0, S1), per lane; a v_cmpx -; writes EXEC only, so VCC is kept. Each one runs alone: EXEC is copied out and put back after it (s20 holds the -; EXEC the shader started with). Inputs are read from memory at run time, not inline constants, which the driver -; could fold. The V# in s[0:3] points at 0x1000 (num_records 96); the test seeds 24 dwords: -; 0x1000: 0x7fc10001 0x3f800000 0x40000000 0x80000000 0x00000000 0xff800000 (then two unused zeros) -; v1 = NaN v2 = 1.0 v3 = 2.0 v4 = -0.0 v5 = +0.0 v6 = -infinity -; 0x1020: four 64-bit pairs (A, B) as A.lo A.hi B.lo B.hi, in v[8:9], v[10:11] ... v[20:21], v[22:23]: -; Q0: A = 0x00000000_80000000 B = 0x00000000_00000001 equal high words, low words differ in bit 31 -; Q1: A = 0x80000000_00000007 B = 0x00000000_00000007 equal low words; A > B unsigned, A < B signed -; Q2: A = 0x00000005_00000001 B = 0x00000005_80000000 the low words of Q0 swapped, under a non-zero high word -; Q3: A = 0x00000005_00000007 B = 0x00000005_00000007 equal -; ISA compare definitions: EQ = S0 == S1, GT = S0 > S1, LE = S0 <= S1, LT = S0 < S1 (ordered: false when a source -; is NaN; -0 == +0), NGT = !(S0 > S1), NLE = !(S0 <= S1) (true when a source is NaN), F = 0, T = 1. _U64 / _I64 -; compare the whole 64-bit values unsigned / signed (the low word is never signed). -; Bit 4*k + i of words 0..2 is op k of that word on pair i. -; word 0, e32, f32 pairs P0 = (NaN, 1.0) P1 = (1.0, 2.0) P2 = (2.0, 1.0) P3 = (1.0, 1.0). Nibbles, bits P3..P0: -; eq P3 = 0x8 gt P2 = 0x4 le P1 P3 = 0xa lt P1 = 0x2 -; ngt P0 P1 P3 = 0xb nle P0 P2 = 0x5 f_i32 none = 0x0 t_u32 all = 0xf -; 0x8 | 0x40 | 0xa00 | 0x2000 | 0xb0000 | 0x500000 | 0x0000000 | 0xf0000000 = 0xf05b2a48 -; word 1, e64 (VOP3), f32 pairs P4 = (2.0, 1.0) P5 = (-0.0, +0.0) P6 = (NaN, NaN) P7 = (-infinity, 1.0): -; eq P5 = 0x2 gt P4 = 0x1 le P5 P7 = 0xa lt P7 = 0x8 -; ngt P5 P6 P7 = 0xe nle P4 P6 = 0x5 f_i32 none = 0x0 t_u32 all = 0xf -; 0x2 | 0x10 | 0xa00 | 0x8000 | 0xe0000 | 0x500000 | 0x0000000 | 0xf0000000 = 0xf05e8a12 -; word 2, 64-bit pairs Q0..Q3 (Q0: A > B both ways, Q1: A > B unsigned and A < B signed, Q2: A < B both ways): -; eq_i64 Q3 = 0x8 gt_i64 Q0 = 0x1 le_i64 Q1 Q2 Q3 = 0xe -; ge_u64 Q0 Q1 Q3 = 0xb lt_u64 Q2 = 0x4 ne_u64 Q0 Q1 Q2 = 0x7 then e64: gt_i64 = 0x1, ge_u64 = 0xb -; 0x8 | 0x10 | 0xe00 | 0xb000 | 0x40000 | 0x700000 | 0x1000000 | 0xb0000000 = 0xb174be18 -; A translation that compared only the low words would call Q1 equal; one that compared only the high words -; would call Q0 and Q2 equal; one that took the low word as signed would swap Q0 and Q2. -; word 3, the 14 ops in the order above (k = 0..13), all e32: -; bit k: EXEC is emptied first (v_cmpx_ne_u32 of equal values), then op k runs with operands that make it true -; (f_i32 never is). v_cmpx only ANDs into EXEC, so no lane comes back: 0 for every k. -; bit 16 + k: VCC is kept. Even k: VCC = 1, then op k with operands that make it false; the bit is VCC = 1. -; Odd k: VCC = 0, then op k with operands that make it true; the bit is VCC = 0. A v_cmpx that also wrote -; its result to VCC would flip every one of these bits. -; bits 16, 18, ... 28 = 0x15550000 -; Expected mrt0 bits: 0xf05b2a48, 0xf05e8a12, 0xb174be18, 0x15550000 -s_buffer_load_dwordx8 s[4:11], s[0:3], 0 -s_waitcnt lgkmcnt(0) -v_mov_b32_e32 v1, s4 -v_mov_b32_e32 v2, s5 -v_mov_b32_e32 v3, s6 -v_mov_b32_e32 v4, s7 -v_mov_b32_e32 v5, s8 -v_mov_b32_e32 v6, s9 -s_buffer_load_dwordx16 s[4:19], s[0:3], 0x20 -s_waitcnt lgkmcnt(0) -v_mov_b32_e32 v8, s4 -v_mov_b32_e32 v9, s5 -v_mov_b32_e32 v10, s6 -v_mov_b32_e32 v11, s7 -v_mov_b32_e32 v12, s8 -v_mov_b32_e32 v13, s9 -v_mov_b32_e32 v14, s10 -v_mov_b32_e32 v15, s11 -v_mov_b32_e32 v16, s12 -v_mov_b32_e32 v17, s13 -v_mov_b32_e32 v18, s14 -v_mov_b32_e32 v19, s15 -v_mov_b32_e32 v20, s16 -v_mov_b32_e32 v21, s17 -v_mov_b32_e32 v22, s18 -v_mov_b32_e32 v23, s19 -s_mov_b32 s20, exec_lo -; word 0: e32 eq, gt, le, lt, ngt, nle _f32 on P0..P3, then f_i32 and t_u32 -v_mov_b32_e32 v40, 0 -v_cmpx_eq_f32_e32 v1, v2 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v40, v30, 0, v40 -v_cmpx_eq_f32_e32 v2, v3 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v40, v30, 1, v40 -v_cmpx_eq_f32_e32 v3, v2 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v40, v30, 2, v40 -v_cmpx_eq_f32_e32 v2, v2 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v40, v30, 3, v40 -v_cmpx_gt_f32_e32 v1, v2 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v40, v30, 4, v40 -v_cmpx_gt_f32_e32 v2, v3 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v40, v30, 5, v40 -v_cmpx_gt_f32_e32 v3, v2 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v40, v30, 6, v40 -v_cmpx_gt_f32_e32 v2, v2 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v40, v30, 7, v40 -v_cmpx_le_f32_e32 v1, v2 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v40, v30, 8, v40 -v_cmpx_le_f32_e32 v2, v3 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v40, v30, 9, v40 -v_cmpx_le_f32_e32 v3, v2 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v40, v30, 10, v40 -v_cmpx_le_f32_e32 v2, v2 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v40, v30, 11, v40 -v_cmpx_lt_f32_e32 v1, v2 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v40, v30, 12, v40 -v_cmpx_lt_f32_e32 v2, v3 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v40, v30, 13, v40 -v_cmpx_lt_f32_e32 v3, v2 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v40, v30, 14, v40 -v_cmpx_lt_f32_e32 v2, v2 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v40, v30, 15, v40 -v_cmpx_ngt_f32_e32 v1, v2 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v40, v30, 16, v40 -v_cmpx_ngt_f32_e32 v2, v3 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v40, v30, 17, v40 -v_cmpx_ngt_f32_e32 v3, v2 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v40, v30, 18, v40 -v_cmpx_ngt_f32_e32 v2, v2 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v40, v30, 19, v40 -v_cmpx_nle_f32_e32 v1, v2 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v40, v30, 20, v40 -v_cmpx_nle_f32_e32 v2, v3 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v40, v30, 21, v40 -v_cmpx_nle_f32_e32 v3, v2 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v40, v30, 22, v40 -v_cmpx_nle_f32_e32 v2, v2 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v40, v30, 23, v40 -v_cmpx_f_i32_e32 v1, v2 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v40, v30, 24, v40 -v_cmpx_f_i32_e32 v2, v3 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v40, v30, 25, v40 -v_cmpx_f_i32_e32 v3, v2 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v40, v30, 26, v40 -v_cmpx_f_i32_e32 v2, v2 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v40, v30, 27, v40 -v_cmpx_t_u32_e32 v1, v2 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v40, v30, 28, v40 -v_cmpx_t_u32_e32 v2, v3 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v40, v30, 29, v40 -v_cmpx_t_u32_e32 v3, v2 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v40, v30, 30, v40 -v_cmpx_t_u32_e32 v2, v2 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v40, v30, 31, v40 -; word 1: the same eight in the e64 (VOP3) encoding, on P4..P7 -v_mov_b32_e32 v41, 0 -v_cmpx_eq_f32_e64 v3, v2 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v41, v30, 0, v41 -v_cmpx_eq_f32_e64 v4, v5 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v41, v30, 1, v41 -v_cmpx_eq_f32_e64 v1, v1 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v41, v30, 2, v41 -v_cmpx_eq_f32_e64 v6, v2 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v41, v30, 3, v41 -v_cmpx_gt_f32_e64 v3, v2 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v41, v30, 4, v41 -v_cmpx_gt_f32_e64 v4, v5 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v41, v30, 5, v41 -v_cmpx_gt_f32_e64 v1, v1 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v41, v30, 6, v41 -v_cmpx_gt_f32_e64 v6, v2 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v41, v30, 7, v41 -v_cmpx_le_f32_e64 v3, v2 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v41, v30, 8, v41 -v_cmpx_le_f32_e64 v4, v5 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v41, v30, 9, v41 -v_cmpx_le_f32_e64 v1, v1 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v41, v30, 10, v41 -v_cmpx_le_f32_e64 v6, v2 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v41, v30, 11, v41 -v_cmpx_lt_f32_e64 v3, v2 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v41, v30, 12, v41 -v_cmpx_lt_f32_e64 v4, v5 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v41, v30, 13, v41 -v_cmpx_lt_f32_e64 v1, v1 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v41, v30, 14, v41 -v_cmpx_lt_f32_e64 v6, v2 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v41, v30, 15, v41 -v_cmpx_ngt_f32_e64 v3, v2 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v41, v30, 16, v41 -v_cmpx_ngt_f32_e64 v4, v5 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v41, v30, 17, v41 -v_cmpx_ngt_f32_e64 v1, v1 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v41, v30, 18, v41 -v_cmpx_ngt_f32_e64 v6, v2 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v41, v30, 19, v41 -v_cmpx_nle_f32_e64 v3, v2 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v41, v30, 20, v41 -v_cmpx_nle_f32_e64 v4, v5 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v41, v30, 21, v41 -v_cmpx_nle_f32_e64 v1, v1 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v41, v30, 22, v41 -v_cmpx_nle_f32_e64 v6, v2 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v41, v30, 23, v41 -v_cmpx_f_i32_e64 v3, v2 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v41, v30, 24, v41 -v_cmpx_f_i32_e64 v4, v5 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v41, v30, 25, v41 -v_cmpx_f_i32_e64 v1, v1 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v41, v30, 26, v41 -v_cmpx_f_i32_e64 v6, v2 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v41, v30, 27, v41 -v_cmpx_t_u32_e64 v3, v2 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v41, v30, 28, v41 -v_cmpx_t_u32_e64 v4, v5 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v41, v30, 29, v41 -v_cmpx_t_u32_e64 v1, v1 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v41, v30, 30, v41 -v_cmpx_t_u32_e64 v6, v2 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v41, v30, 31, v41 -; word 2: e32 eq, gt, le _i64 and ge, lt, ne _u64 on Q0..Q3, then e64 gt_i64 and ge_u64 -v_mov_b32_e32 v42, 0 -v_cmpx_eq_i64_e32 v[8:9], v[10:11] -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v42, v30, 0, v42 -v_cmpx_eq_i64_e32 v[12:13], v[14:15] -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v42, v30, 1, v42 -v_cmpx_eq_i64_e32 v[16:17], v[18:19] -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v42, v30, 2, v42 -v_cmpx_eq_i64_e32 v[20:21], v[22:23] -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v42, v30, 3, v42 -v_cmpx_gt_i64_e32 v[8:9], v[10:11] -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v42, v30, 4, v42 -v_cmpx_gt_i64_e32 v[12:13], v[14:15] -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v42, v30, 5, v42 -v_cmpx_gt_i64_e32 v[16:17], v[18:19] -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v42, v30, 6, v42 -v_cmpx_gt_i64_e32 v[20:21], v[22:23] -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v42, v30, 7, v42 -v_cmpx_le_i64_e32 v[8:9], v[10:11] -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v42, v30, 8, v42 -v_cmpx_le_i64_e32 v[12:13], v[14:15] -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v42, v30, 9, v42 -v_cmpx_le_i64_e32 v[16:17], v[18:19] -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v42, v30, 10, v42 -v_cmpx_le_i64_e32 v[20:21], v[22:23] -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v42, v30, 11, v42 -v_cmpx_ge_u64_e32 v[8:9], v[10:11] -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v42, v30, 12, v42 -v_cmpx_ge_u64_e32 v[12:13], v[14:15] -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v42, v30, 13, v42 -v_cmpx_ge_u64_e32 v[16:17], v[18:19] -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v42, v30, 14, v42 -v_cmpx_ge_u64_e32 v[20:21], v[22:23] -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v42, v30, 15, v42 -v_cmpx_lt_u64_e32 v[8:9], v[10:11] -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v42, v30, 16, v42 -v_cmpx_lt_u64_e32 v[12:13], v[14:15] -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v42, v30, 17, v42 -v_cmpx_lt_u64_e32 v[16:17], v[18:19] -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v42, v30, 18, v42 -v_cmpx_lt_u64_e32 v[20:21], v[22:23] -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v42, v30, 19, v42 -v_cmpx_ne_u64_e32 v[8:9], v[10:11] -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v42, v30, 20, v42 -v_cmpx_ne_u64_e32 v[12:13], v[14:15] -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v42, v30, 21, v42 -v_cmpx_ne_u64_e32 v[16:17], v[18:19] -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v42, v30, 22, v42 -v_cmpx_ne_u64_e32 v[20:21], v[22:23] -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v42, v30, 23, v42 -v_cmpx_gt_i64_e64 v[8:9], v[10:11] -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v42, v30, 24, v42 -v_cmpx_gt_i64_e64 v[12:13], v[14:15] -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v42, v30, 25, v42 -v_cmpx_gt_i64_e64 v[16:17], v[18:19] -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v42, v30, 26, v42 -v_cmpx_gt_i64_e64 v[20:21], v[22:23] -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v42, v30, 27, v42 -v_cmpx_ge_u64_e64 v[8:9], v[10:11] -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v42, v30, 28, v42 -v_cmpx_ge_u64_e64 v[12:13], v[14:15] -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v42, v30, 29, v42 -v_cmpx_ge_u64_e64 v[16:17], v[18:19] -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v42, v30, 30, v42 -v_cmpx_ge_u64_e64 v[20:21], v[22:23] -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v42, v30, 31, v42 -; word 3, bits 0..13: EXEC emptied first, then op k with operands that make it true (f_i32 never is) -v_mov_b32_e32 v43, 0 -v_cmpx_ne_u32_e32 v2, v2 -v_cmpx_eq_f32_e32 v2, v2 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v43, v30, 0, v43 -v_cmpx_ne_u32_e32 v2, v2 -v_cmpx_gt_f32_e32 v3, v2 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v43, v30, 1, v43 -v_cmpx_ne_u32_e32 v2, v2 -v_cmpx_le_f32_e32 v2, v3 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v43, v30, 2, v43 -v_cmpx_ne_u32_e32 v2, v2 -v_cmpx_lt_f32_e32 v2, v3 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v43, v30, 3, v43 -v_cmpx_ne_u32_e32 v2, v2 -v_cmpx_ngt_f32_e32 v1, v2 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v43, v30, 4, v43 -v_cmpx_ne_u32_e32 v2, v2 -v_cmpx_nle_f32_e32 v1, v2 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v43, v30, 5, v43 -v_cmpx_ne_u32_e32 v2, v2 -v_cmpx_f_i32_e32 v2, v2 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v43, v30, 6, v43 -v_cmpx_ne_u32_e32 v2, v2 -v_cmpx_t_u32_e32 v2, v3 -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v43, v30, 7, v43 -v_cmpx_ne_u32_e32 v2, v2 -v_cmpx_eq_i64_e32 v[20:21], v[22:23] -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v43, v30, 8, v43 -v_cmpx_ne_u32_e32 v2, v2 -v_cmpx_gt_i64_e32 v[8:9], v[10:11] -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v43, v30, 9, v43 -v_cmpx_ne_u32_e32 v2, v2 -v_cmpx_le_i64_e32 v[12:13], v[14:15] -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v43, v30, 10, v43 -v_cmpx_ne_u32_e32 v2, v2 -v_cmpx_ge_u64_e32 v[12:13], v[14:15] -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v43, v30, 11, v43 -v_cmpx_ne_u32_e32 v2, v2 -v_cmpx_lt_u64_e32 v[16:17], v[18:19] -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v43, v30, 12, v43 -v_cmpx_ne_u32_e32 v2, v2 -v_cmpx_ne_u64_e32 v[12:13], v[14:15] -s_mov_b32 s21, exec_lo -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, s21 -v_lshl_or_b32 v43, v30, 13, v43 -; word 3, bits 16..29: VCC is kept. Even k: VCC = 1, op k false; odd k: VCC = 0, op k true -v_cmp_eq_u32_e32 vcc_lo, v2, v2 -v_cmpx_eq_f32_e32 v1, v1 -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, vcc_lo -v_lshl_or_b32 v43, v30, 16, v43 -v_cmp_ne_u32_e32 vcc_lo, v2, v2 -v_cmpx_gt_f32_e32 v3, v2 -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, vcc_lo -v_lshl_or_b32 v43, v30, 17, v43 -v_cmp_eq_u32_e32 vcc_lo, v2, v2 -v_cmpx_le_f32_e32 v3, v2 -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, vcc_lo -v_lshl_or_b32 v43, v30, 18, v43 -v_cmp_ne_u32_e32 vcc_lo, v2, v2 -v_cmpx_lt_f32_e32 v2, v3 -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, vcc_lo -v_lshl_or_b32 v43, v30, 19, v43 -v_cmp_eq_u32_e32 vcc_lo, v2, v2 -v_cmpx_ngt_f32_e32 v3, v2 -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, vcc_lo -v_lshl_or_b32 v43, v30, 20, v43 -v_cmp_ne_u32_e32 vcc_lo, v2, v2 -v_cmpx_nle_f32_e32 v1, v2 -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, vcc_lo -v_lshl_or_b32 v43, v30, 21, v43 -v_cmp_eq_u32_e32 vcc_lo, v2, v2 -v_cmpx_f_i32_e32 v2, v2 -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, vcc_lo -v_lshl_or_b32 v43, v30, 22, v43 -v_cmp_ne_u32_e32 vcc_lo, v2, v2 -v_cmpx_t_u32_e32 v2, v3 -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, vcc_lo -v_lshl_or_b32 v43, v30, 23, v43 -v_cmp_eq_u32_e32 vcc_lo, v2, v2 -v_cmpx_eq_i64_e32 v[12:13], v[14:15] -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, vcc_lo -v_lshl_or_b32 v43, v30, 24, v43 -v_cmp_ne_u32_e32 vcc_lo, v2, v2 -v_cmpx_gt_i64_e32 v[8:9], v[10:11] -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, vcc_lo -v_lshl_or_b32 v43, v30, 25, v43 -v_cmp_eq_u32_e32 vcc_lo, v2, v2 -v_cmpx_le_i64_e32 v[8:9], v[10:11] -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, vcc_lo -v_lshl_or_b32 v43, v30, 26, v43 -v_cmp_ne_u32_e32 vcc_lo, v2, v2 -v_cmpx_ge_u64_e32 v[12:13], v[14:15] -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, vcc_lo -v_lshl_or_b32 v43, v30, 27, v43 -v_cmp_eq_u32_e32 vcc_lo, v2, v2 -v_cmpx_lt_u64_e32 v[12:13], v[14:15] -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, vcc_lo -v_lshl_or_b32 v43, v30, 28, v43 -v_cmp_ne_u32_e32 vcc_lo, v2, v2 -v_cmpx_ne_u64_e32 v[12:13], v[14:15] -s_mov_b32 exec_lo, s20 -v_cndmask_b32_e64 v30, 0, 1, vcc_lo -v_lshl_or_b32 v43, v30, 29, v43 -exp mrt0 v40, v41, v42, v43 done vm -s_endpgm diff --git a/runtime/test/shaders/ps_vint_bits.asm b/runtime/test/shaders/ps_vint_bits.asm deleted file mode 100644 index 482ab7cbf..000000000 --- a/runtime/test/shaders/ps_vint_bits.asm +++ /dev/null @@ -1,36 +0,0 @@ -; regen_fixtures: this source has a translator fixture in tests/semantic/fixtures/disasm -; Bit-field mask and bit reverse: v_bfm_b32 (VOP3), v_bfrev_b32. vN holds hN. -; Inputs come from memory at run time (not inline constants, which the driver could fold). The V# in s[0:3] -; points at 0x1000 (num_records 32); the test seeds 0x1000..0x101c with h0..h7 = -; h0 0xab800000 bit 23 set, bits 24-31 garbage: i24 = -2^23, u24 = 0x800000 -; h1 0x12fffffe i24 = -2, u24 = 0xfffffe -; h2 0x00000021 33: a shift or field size of 32 or more, taken mod 32 (= 1) -; h3 0x80000001 negative as i32, large as u32 -; h4 0x7ffffffe positive either way -; h5 0xf0f0f0f0 -; h6 0x12345678 -; h7 0xffffffff -; Each word is derived by hand from the RDNA2 ISA pseudocode quoted next to it, never from the translator. -; v_bfm_b32 D = ((1 << S0[4:0]) - 1) << S1[4:0] (S0 the field size, S1 the offset) -; size h7, offset h2 = size 0xffffffff & 31 = 31, offset 33 & 31 = 1: 0x7fffffff << 1 = 0xfffffffe -; size h2, offset h1 = size 33 & 31 = 1, offset 0x12fffffe & 31 = 30: 1 << 30 = 0x40000000 -; v_bfrev_b32 D[31:0] = S0[0:31] -; h6 = 0001 0010 0011 0100 0101 0110 0111 1000 reversed = 0001 1110 0110 1010 0010 1100 0100 1000 = 0x1e6a2c48 -; h0 = 0xab800000: its top nine bits 1010 1011 1 land in bits 0..8 reversed, 1 1101 0101 = 0x000001d5 -; Expected mrt0 bits: 0xfffffffe, 0x40000000, 0x1e6a2c48, 0x000001d5 -s_buffer_load_dwordx8 s[4:11], s[0:3], 0 -s_waitcnt lgkmcnt(0) -v_mov_b32_e32 v0, s4 -v_mov_b32_e32 v1, s5 -v_mov_b32_e32 v2, s6 -v_mov_b32_e32 v3, s7 -v_mov_b32_e32 v4, s8 -v_mov_b32_e32 v5, s9 -v_mov_b32_e32 v6, s10 -v_mov_b32_e32 v7, s11 -v_bfm_b32 v8, v7, v2 -v_bfm_b32 v9, v2, v1 -v_bfrev_b32_e32 v10, v6 -v_bfrev_b32_e32 v11, v0 -exp mrt0 v8, v9, v10, v11 done vm -s_endpgm diff --git a/runtime/test/shaders/ps_vint_logic3.asm b/runtime/test/shaders/ps_vint_logic3.asm deleted file mode 100644 index 9c36e03a7..000000000 --- a/runtime/test/shaders/ps_vint_logic3.asm +++ /dev/null @@ -1,39 +0,0 @@ -; regen_fixtures: this source has a translator fixture in tests/semantic/fixtures/disasm -; Three-operand integer logic (VOP3): v_add_lshl_u32, v_and_or_b32, v_xor3_b32, v_bfi_b32. vN holds hN. -; Inputs come from memory at run time (not inline constants, which the driver could fold). The V# in s[0:3] -; points at 0x1000 (num_records 32); the test seeds 0x1000..0x101c with h0..h7 = -; h0 0xab800000 bit 23 set, bits 24-31 garbage: i24 = -2^23, u24 = 0x800000 -; h1 0x12fffffe i24 = -2, u24 = 0xfffffe -; h2 0x00000021 33: a shift or field size of 32 or more, taken mod 32 (= 1) -; h3 0x80000001 negative as i32, large as u32 -; h4 0x7ffffffe positive either way -; h5 0xf0f0f0f0 -; h6 0x12345678 -; h7 0xffffffff -; Each word is derived by hand from the RDNA2 ISA pseudocode quoted next to it, never from the translator. -; v_add_lshl_u32 D = (S0 + S1) << S2[4:0] -; (h3 + h4) << h2 = (0x80000001 + 0x7ffffffe) << (33 & 31) = 0xffffffff << 1 = 0xfffffffe -; (shifting before adding gives 0x80000000; an unmasked shift by 33 is undefined in SPIR-V) -; v_and_or_b32 D = (S0 & S1) | S2 -; (h6 & h5) | h0 = (0x12345678 & 0xf0f0f0f0) | 0xab800000 = 0x10305070 | 0xab800000 = 0xbbb05070 -; v_xor3_b32 D = S0 ^ S1 ^ S2 -; h5 ^ h6 ^ h7 = 0xf0f0f0f0 ^ 0x12345678 ^ 0xffffffff = 0xe2c4a688 ^ 0xffffffff = 0x1d3b5977 -; v_bfi_b32 D = (S0 & S1) | (~S0 & S2), S0 the mask -; (h5 & h6) | (~h5 & h1) = 0x10305070 | (0x0f0f0f0f & 0x12fffffe) = 0x10305070 | 0x020f0f0e = 0x123f5f7e -; Expected mrt0 bits: 0xfffffffe, 0xbbb05070, 0x1d3b5977, 0x123f5f7e -s_buffer_load_dwordx8 s[4:11], s[0:3], 0 -s_waitcnt lgkmcnt(0) -v_mov_b32_e32 v0, s4 -v_mov_b32_e32 v1, s5 -v_mov_b32_e32 v2, s6 -v_mov_b32_e32 v3, s7 -v_mov_b32_e32 v4, s8 -v_mov_b32_e32 v5, s9 -v_mov_b32_e32 v6, s10 -v_mov_b32_e32 v7, s11 -v_add_lshl_u32 v8, v3, v4, v2 -v_and_or_b32 v9, v6, v5, v0 -v_xor3_b32 v10, v5, v6, v7 -v_bfi_b32 v11, v5, v6, v1 -exp mrt0 v8, v9, v10, v11 done vm -s_endpgm diff --git a/runtime/test/shaders/ps_vint_minmax.asm b/runtime/test/shaders/ps_vint_minmax.asm deleted file mode 100644 index f0c83a175..000000000 --- a/runtime/test/shaders/ps_vint_minmax.asm +++ /dev/null @@ -1,36 +0,0 @@ -; regen_fixtures: this source has a translator fixture in tests/semantic/fixtures/disasm -; Two-operand integer min/max (VOP2), signed and unsigned on the same pair. vN holds hN. -; Inputs come from memory at run time (not inline constants, which the driver could fold). The V# in s[0:3] -; points at 0x1000 (num_records 32); the test seeds 0x1000..0x101c with h0..h7 = -; h0 0xab800000 bit 23 set, bits 24-31 garbage: i24 = -2^23, u24 = 0x800000 -; h1 0x12fffffe i24 = -2, u24 = 0xfffffe -; h2 0x00000021 33: a shift or field size of 32 or more, taken mod 32 (= 1) -; h3 0x80000001 negative as i32, large as u32 -; h4 0x7ffffffe positive either way -; h5 0xf0f0f0f0 -; h6 0x12345678 -; h7 0xffffffff -; Each word is derived by hand from the RDNA2 ISA pseudocode quoted next to it, never from the translator. -; v_max_i32 D = S0.i >= S1.i ? S0 : S1 v_min_i32 D = S0.i < S1.i ? S0 : S1 -; v_max_u32 D = S0.u >= S1.u ? S0 : S1 v_min_u32 D = S0.u < S1.u ? S0 : S1 -; S0 = h3 = 0x80000001 (-2147483647 signed, 2147483649 unsigned), S1 = h4 = 0x7ffffffe (2147483646 either way) -; v_max_i32 = h4 = 0x7ffffffe v_min_i32 = h3 = 0x80000001 -; v_max_u32 = h3 = 0x80000001 v_min_u32 = h4 = 0x7ffffffe -; (a signed/unsigned mix-up swaps the words of each pair) -; Expected mrt0 bits: 0x7ffffffe, 0x80000001, 0x80000001, 0x7ffffffe -s_buffer_load_dwordx8 s[4:11], s[0:3], 0 -s_waitcnt lgkmcnt(0) -v_mov_b32_e32 v0, s4 -v_mov_b32_e32 v1, s5 -v_mov_b32_e32 v2, s6 -v_mov_b32_e32 v3, s7 -v_mov_b32_e32 v4, s8 -v_mov_b32_e32 v5, s9 -v_mov_b32_e32 v6, s10 -v_mov_b32_e32 v7, s11 -v_max_i32_e32 v8, v3, v4 -v_min_i32_e32 v9, v3, v4 -v_max_u32_e32 v10, v3, v4 -v_min_u32_e32 v11, v3, v4 -exp mrt0 v8, v9, v10, v11 done vm -s_endpgm diff --git a/runtime/test/shaders/ps_vint_minmax3.asm b/runtime/test/shaders/ps_vint_minmax3.asm deleted file mode 100644 index 93c2541d2..000000000 --- a/runtime/test/shaders/ps_vint_minmax3.asm +++ /dev/null @@ -1,40 +0,0 @@ -; regen_fixtures: this source has a translator fixture in tests/semantic/fixtures/disasm -; Three-operand integer min/max (VOP3): v_max3_u32, v_min3_i32. vN holds hN. -; Inputs come from memory at run time (not inline constants, which the driver could fold). The V# in s[0:3] -; points at 0x1000 (num_records 32); the test seeds 0x1000..0x101c with h0..h7 = -; h0 0xab800000 bit 23 set, bits 24-31 garbage: i24 = -2^23, u24 = 0x800000 -; h1 0x12fffffe i24 = -2, u24 = 0xfffffe -; h2 0x00000021 33: a shift or field size of 32 or more, taken mod 32 (= 1) -; h3 0x80000001 negative as i32, large as u32 -; h4 0x7ffffffe positive either way -; h5 0xf0f0f0f0 -; h6 0x12345678 -; h7 0xffffffff -; Each word is derived by hand from the RDNA2 ISA pseudocode quoted next to it, never from the translator. -; v_max3_u32 D = max(S0.u, S1.u, S2.u) v_min3_i32 D = min(S0.i, S1.i, S2.i) -; max3_u32(h4, h3, h5) = max(0x7ffffffe, 0x80000001, 0xf0f0f0f0) = 0xf0f0f0f0 -; (signed: 0x7ffffffe) -; max3_u32(h0, h6, h3) = max(0xab800000, 0x12345678, 0x80000001) = 0xab800000 -; (signed: 0x12345678) -; min3_i32(h5, h4, h6): 0xf0f0f0f0 = -252645136 is the only negative one = 0xf0f0f0f0 -; (unsigned: 0x12345678) -; min3_i32(h7, h6, h0): -1, 0x12345678, 0xab800000 = -1417674752 = 0xab800000 -; (unsigned: 0x12345678) -; The extreme operand sits in S2, S0, S0 and S2. -; Expected mrt0 bits: 0xf0f0f0f0, 0xab800000, 0xf0f0f0f0, 0xab800000 -s_buffer_load_dwordx8 s[4:11], s[0:3], 0 -s_waitcnt lgkmcnt(0) -v_mov_b32_e32 v0, s4 -v_mov_b32_e32 v1, s5 -v_mov_b32_e32 v2, s6 -v_mov_b32_e32 v3, s7 -v_mov_b32_e32 v4, s8 -v_mov_b32_e32 v5, s9 -v_mov_b32_e32 v6, s10 -v_mov_b32_e32 v7, s11 -v_max3_u32 v8, v4, v3, v5 -v_max3_u32 v9, v0, v6, v3 -v_min3_i32 v10, v5, v4, v6 -v_min3_i32 v11, v7, v6, v0 -exp mrt0 v8, v9, v10, v11 done vm -s_endpgm diff --git a/runtime/test/shaders/ps_vint_mul24.asm b/runtime/test/shaders/ps_vint_mul24.asm deleted file mode 100644 index 27026a152..000000000 --- a/runtime/test/shaders/ps_vint_mul24.asm +++ /dev/null @@ -1,40 +0,0 @@ -; regen_fixtures: this source has a translator fixture in tests/semantic/fixtures/disasm -; 24-bit multiplies: v_mad_i32_i24 (VOP3, no clamp), v_mul_hi_u32_u24 (VOP2). vN holds hN. -; Inputs come from memory at run time (not inline constants, which the driver could fold). The V# in s[0:3] -; points at 0x1000 (num_records 32); the test seeds 0x1000..0x101c with h0..h7 = -; h0 0xab800000 bit 23 set, bits 24-31 garbage: i24 = -2^23, u24 = 0x800000 -; h1 0x12fffffe i24 = -2, u24 = 0xfffffe -; h2 0x00000021 33: a shift or field size of 32 or more, taken mod 32 (= 1) -; h3 0x80000001 negative as i32, large as u32 -; h4 0x7ffffffe positive either way -; h5 0xf0f0f0f0 -; h6 0x12345678 -; h7 0xffffffff -; Each word is derived by hand from the RDNA2 ISA pseudocode quoted next to it, never from the translator. -; v_mad_i32_i24 D = S0.i[23:0] * S1.i[23:0] + S2.i, the 24-bit fields sign-extended from bit 23, low 32 bits -; h0, h1, h6: (-2^23) * (-2) + 0x12345678 = 0x01000000 + 0x12345678 = 0x13345678 -; (zero-extended fields give 0x800000 * 0xfffffe = 0x7fffff000000, low word 0xff000000 + h6 = 0x11345678) -; h4, h3, h7: i24(0x7ffffffe) = -2, i24(0x80000001) = 1: -2 * 1 + (-1) = -3 = 0xfffffffd -; (zero-extended: 0xfffffe + 0xffffffff = 0x00fffffd) -; v_mul_hi_u32_u24 D = (S0.u[23:0] * S1.u[23:0]) >> 32, the 24-bit fields zero-extended -; h0, h1: 0x800000 * 0xfffffe = 0x7fffff000000, >> 32 = 0x00007fff -; (sign-extended fields give (-2^23) * (-2) = 2^24, high word 0) -; h7, h7: 0xffffff * 0xffffff = 0xfffffe000001, >> 32 = 0x0000ffff -; (sign-extended: (-1) * (-1) = 1, high word 0) -; Expected mrt0 bits: 0x13345678, 0xfffffffd, 0x00007fff, 0x0000ffff -s_buffer_load_dwordx8 s[4:11], s[0:3], 0 -s_waitcnt lgkmcnt(0) -v_mov_b32_e32 v0, s4 -v_mov_b32_e32 v1, s5 -v_mov_b32_e32 v2, s6 -v_mov_b32_e32 v3, s7 -v_mov_b32_e32 v4, s8 -v_mov_b32_e32 v5, s9 -v_mov_b32_e32 v6, s10 -v_mov_b32_e32 v7, s11 -v_mad_i32_i24 v8, v0, v1, v6 -v_mad_i32_i24 v9, v4, v3, v7 -v_mul_hi_u32_u24_e32 v10, v0, v1 -v_mul_hi_u32_u24_e32 v11, v7, v7 -exp mrt0 v8, v9, v10, v11 done vm -s_endpgm diff --git a/runtime/test/shaders/ps_vop3_const_mods.asm b/runtime/test/shaders/ps_vop3_const_mods.asm deleted file mode 100644 index 3f5df7add..000000000 --- a/runtime/test/shaders/ps_vop3_const_mods.asm +++ /dev/null @@ -1,15 +0,0 @@ -; regen_fixtures: this source has a translator fixture in tests/semantic/fixtures/disasm -; VOP3 FP source modifiers on constants (docs/design.md "VOP3 FP modifiers on constants"): on an inline constant or a -; literal, abs clears the sign bit first and neg flips it second; neg on a literal is not an integer negation. -; x: v_add_f32_e64 0 + -|-2.0| = -2.0 (folding - into the constant first gave +2.0) -; y: v_add_f32_e64 0 + neg(0x3f800000) = -1.0 (two's-complement negation gave 0xc0800000, -4.0) -; z: v_add_f32_e64 0 + |0xbf800000| = 1.0 (dropping abs gave -1.0) -; w: v_add_f16_e64 0 + -|0x3c00| = -1.0h in the low half, the destination's high half 0xAAAA kept -; Expected mrt0 bits: 0xc0000000, 0xbf800000, 0x3f800000, 0xaaaabc00 -v_add_f32_e64 v2, 0, -|-2.0| -v_add_f32_e64 v3, 0, neg(0x3f800000) -v_add_f32_e64 v4, 0, |0xbf800000| -v_mov_b32_e32 v5, 0xaaaa1234 -v_add_f16_e64 v5, 0, -|0x3c00| -exp mrt0 v2, v3, v4, v5 done vm -s_endpgm diff --git a/runtime/test/shaders/ps_w64_a_bpermute.asm b/runtime/test/shaders/ps_w64_a_bpermute.asm deleted file mode 100644 index 90b8f1435..000000000 --- a/runtime/test/shaders/ps_w64_a_bpermute.asm +++ /dev/null @@ -1,44 +0,0 @@ -; SHADER-10, GPU check of ds_bpermute_b32 in a wave64 pixel shader: a wave64 ds_bpermute runs as two wave32 halves -; (ISA 10.4.4; tests/semantic/test_wave64_cross_half.py), so an address taken from the lane id reads the same lane -; whether the lane id is counted in the wave (0..63) or in a half (0..31): only address bits 2..6 are used. -; p = y * 64 + x (x = floor(u * 64), y = floor(v * 64) on the 64x64 target of vs_ids). The words depend only on the -; 2x2 quad layout of fragment lanes (lane 4k+0 top-left, +1 top-right, +2 bottom-left, +3 bottom-right): -; r0 = ds_bpermute from lane ^ 1: the right/left neighbour, (x ^ 1) + 64 * y. -; r1 = ds_bpermute from lane ^ 3: the diagonal pixel, (x ^ 1) + 64 * (y ^ 1). -; r2 = ds_bpermute from lane ^ 16, twice: back to the own pixel, p. -; r3 = ds_bpermute from lane & ~3 + 2 (the quad's bottom-left lane): (x & ~1) + 64 * (y | 1). -; The reads that go out and come back also need the partner lane to hold a pixel: vs_ids' full-screen triangle on -; the 64x64 target fills every wave. -; Run: vk_harness vs_ids.spv ps_w64_a_bpermute.spv out.raw with VKH_SUBGROUP_SIZE=64 and 32: equal images, equal to -; the derived words. -; mattr: +wavefrontsize64,-wavefrontsize32 -v_interp_p1_f32_e32 v2, v0, attr0.x -v_interp_p2_f32_e32 v2, v1, attr0.x -v_interp_p1_f32_e32 v3, v0, attr0.y -v_interp_p2_f32_e32 v3, v1, attr0.y -v_mul_f32_e32 v2, 0x42800000, v2 -v_mul_f32_e32 v3, 0x42800000, v3 -v_cvt_u32_f32_e32 v2, v2 -v_cvt_u32_f32_e32 v3, v3 -v_lshl_add_u32 v4, v3, 6, v2 -s_mov_b64 s[10:11], exec -v_mbcnt_lo_u32_b32 v10, -1, 0 -v_mbcnt_hi_u32_b32 v10, -1, v10 -v_xor_b32_e32 v11, 1, v10 -v_lshlrev_b32_e32 v11, 2, v11 -ds_bpermute_b32 v6, v11, v4 -v_xor_b32_e32 v11, 3, v10 -v_lshlrev_b32_e32 v11, 2, v11 -ds_bpermute_b32 v7, v11, v4 -v_xor_b32_e32 v11, 16, v10 -v_lshlrev_b32_e32 v11, 2, v11 -ds_bpermute_b32 v5, v11, v4 -s_waitcnt lgkmcnt(0) -ds_bpermute_b32 v8, v11, v5 -v_and_b32_e32 v11, -4, v10 -v_or_b32_e32 v11, 2, v11 -v_lshlrev_b32_e32 v11, 2, v11 -ds_bpermute_b32 v9, v11, v4 -s_waitcnt lgkmcnt(0) -exp mrt0 v6, v7, v8, v9 done vm -s_endpgm diff --git a/runtime/test/shaders/ps_w64_a_discard.asm b/runtime/test/shaders/ps_w64_a_discard.asm deleted file mode 100644 index b8f4c16a5..000000000 --- a/runtime/test/shaders/ps_w64_a_discard.asm +++ /dev/null @@ -1,65 +0,0 @@ -; SHADER-10 tier A (docs/design.md, "Wave64 graphics: partition invariance"): the early exit of a pixel kill. A wave64 -; pixel shader whose 32-lane halves can lose every pixel while the other half lives on gives the same image when its -; 64 lanes are cut into two 32-lane subgroups. x = floor(u * 64), y = floor(v * 64) are the pixel's coordinates on -; the 64x64 target (u, v = attr0.xy of vs_ids), so every expected word is a function of (x, y) and not of the lane -; the pixel landed on. -; Three kills, each `s_andn2_b64 live, live, ` then `s_cbranch_scc0` to its own exit block, which only -; sets EXEC from the (empty) live mask, exports null with done vm and ends (an exit shared by several kills reads a -; mask redefined behind the earlier votes: tier C tainted-exec, a stale scalar). The run side narrows EXEC into the -; whole quads of the live mask (s_wqm_b64, s_and_b64 exec) and never widens it. -; (1) x < 30, through v_cmpx (EXEC = the pixels to kill); (2) y >= 50, through VCC; (3) x % 4 == 3 and y odd -; ((y & 1) * 4 + (x & 3) == 7), through VCC. -; The first two discard large regions: whole waves and, at x = 30 and y = 50, halves whose pixels are all dead -; next to halves that live (for a wave tiled as 8x8 cut into 8x4 or 4x8 halves, among others). -; Before the export EXEC is narrowed to the live mask itself, so the helper lanes of the quads are discarded. -; Live pixel: r0 = 7 * y + x, r1 = 1, r2 = 2000 + y, r3 = x % 4 + 1. A discarded pixel keeps the harness clear -; value, -1.0f in every word (0xbf800000). -; Run: vk_harness vs_ids.spv ps_w64_a_discard.spv out.raw, once with VKH_SUBGROUP_SIZE=64 and once with 32: the two -; images must be equal (and equal to the expected words). Output is raw bits (r0, r1, r2, r3) per pixel. -; mattr: +wavefrontsize64,-wavefrontsize32 -v_interp_p1_f32_e32 v2, v0, attr0.x -v_interp_p2_f32_e32 v2, v1, attr0.x -v_interp_p1_f32_e32 v3, v0, attr0.y -v_interp_p2_f32_e32 v3, v1, attr0.y -v_mul_f32_e32 v2, 0x42800000, v2 -v_mul_f32_e32 v3, 0x42800000, v3 -v_cvt_u32_f32_e32 v2, v2 -v_cvt_u32_f32_e32 v3, v3 -s_mov_b64 s[10:11], exec -s_mov_b64 s[20:21], exec -v_cmpx_gt_u32_e32 30, v2 -s_andn2_b64 s[20:21], s[20:21], exec -s_cbranch_scc0 34 -s_wqm_b64 s[22:23], s[20:21] -s_and_b64 exec, s[10:11], s[22:23] -v_cmp_lt_u32_e32 vcc, 49, v3 -s_andn2_b64 s[20:21], s[20:21], vcc -s_cbranch_scc0 25 -s_wqm_b64 s[22:23], s[20:21] -s_and_b64 exec, exec, s[22:23] -v_and_b32_e32 v4, 3, v2 -v_and_b32_e32 v5, 1, v3 -v_lshlrev_b32_e32 v5, 2, v5 -v_add_nc_u32_e32 v5, v5, v4 -v_cmp_eq_u32_e32 vcc, 7, v5 -s_andn2_b64 s[20:21], s[20:21], vcc -s_cbranch_scc0 12 -s_wqm_b64 s[22:23], s[20:21] -s_and_b64 exec, exec, s[22:23] -v_mul_u32_u24_e32 v6, 7, v3 -v_add_nc_u32_e32 v6, v6, v2 -v_mov_b32_e32 v7, 1 -v_add_nc_u32_e32 v8, 0x7d0, v3 -v_add_nc_u32_e32 v9, 1, v4 -s_and_b64 exec, exec, s[20:21] -exp mrt0 v6, v7, v8, v9 done vm -s_endpgm -s_mov_b64 exec, s[20:21] -exp null off, off, off, off done vm -s_endpgm -s_mov_b64 exec, s[20:21] -exp null off, off, off, off done vm -s_endpgm -s_mov_b64 exec, s[20:21] -exp null off, off, off, off done vm -s_endpgm diff --git a/runtime/test/shaders/ps_w64_a_one_lane.asm b/runtime/test/shaders/ps_w64_a_one_lane.asm deleted file mode 100644 index ce9be6cde..000000000 --- a/runtime/test/shaders/ps_w64_a_one_lane.asm +++ /dev/null @@ -1,44 +0,0 @@ -; SHADER-10 tier A, the case where one half votes and the other does not: only the pixel (5, 7) (x = floor(u * 64), -; y = floor(v * 64) on the 64x64 target of vs_ids) is "on" (v4 == 0). Every other wave, and on 32-lane subgroups every -; half that does not hold the pixel, votes "no". The three regions are skips of lane-masked work whose "no" side is -; the join itself, so a half that votes no does exactly what its lanes did in the 64-lane wave: -; (1) s_cbranch_execz over a VGPR def: r0 = 7777 for the pixel, 1000 + x elsewhere. -; (2) s_cbranch_vccz whose run side starts by narrowing EXEC to the vote's VCC: r1 = 3000 + 11 for the pixel. -; (3) s_cbranch_vccnz to the run side, whose fall-through is only a jump to the join: r2 = 4000 + y + 13 for the pixel. -; r3 = x % 4. Run: vk_harness vs_ids.spv ps_w64_a_one_lane.spv out.raw with VKH_SUBGROUP_SIZE=64 and 32: equal images, -; equal to the derived words. -; mattr: +wavefrontsize64,-wavefrontsize32 -v_interp_p1_f32_e32 v2, v0, attr0.x -v_interp_p2_f32_e32 v2, v1, attr0.x -v_interp_p1_f32_e32 v3, v0, attr0.y -v_interp_p2_f32_e32 v3, v1, attr0.y -v_mul_f32_e32 v2, 0x42800000, v2 -v_mul_f32_e32 v3, 0x42800000, v3 -v_cvt_u32_f32_e32 v2, v2 -v_cvt_u32_f32_e32 v3, v3 -s_mov_b64 s[10:11], exec -v_xor_b32_e32 v4, 5, v2 -v_xor_b32_e32 v5, 7, v3 -v_or_b32_e32 v4, v4, v5 -v_add_nc_u32_e32 v6, 0x3e8, v2 -v_cmp_eq_u32_e32 vcc, 0, v4 -s_and_saveexec_b64 s[12:13], vcc -s_cbranch_execz 2 -v_mov_b32_e32 v6, 0x1e61 -s_or_b64 exec, exec, s[12:13] -v_mov_b32_e32 v7, 0xbb8 -v_cmp_eq_u32_e32 vcc, 0, v4 -s_cbranch_vccz 3 -s_and_saveexec_b64 s[16:17], vcc -v_add_nc_u32_e32 v7, 11, v7 -s_or_b64 exec, exec, s[16:17] -v_add_nc_u32_e32 v8, 0xfa0, v3 -v_cmp_eq_u32_e32 vcc, 0, v4 -s_cbranch_vccnz 1 -s_branch 3 -s_and_saveexec_b64 s[16:17], vcc -v_add_nc_u32_e32 v8, 13, v8 -s_or_b64 exec, exec, s[16:17] -v_and_b32_e32 v9, 3, v2 -exp mrt0 v6, v7, v8, v9 done vm -s_endpgm diff --git a/runtime/test/shaders/ps_w64_a_permlane.asm b/runtime/test/shaders/ps_w64_a_permlane.asm deleted file mode 100644 index b89a6383f..000000000 --- a/runtime/test/shaders/ps_w64_a_permlane.asm +++ /dev/null @@ -1,42 +0,0 @@ -; SHADER-10 tier A, GPU check of v_permlane16_b32 and v_permlanex16_b32 in a wave64 pixel shader (they never leave a -; 32-lane half: permlane16 reads within the lane's row of 16, permlanex16 from the other row of the same half). -; p = y * 64 + x is the pixel number (x = floor(u * 64), y = floor(v * 64) on the 64x64 target of vs_ids). The words -; must not depend on how the rasterizer packs pixels into lanes, only on the 2x2 quad layout of fragment lanes (lane -; 4k+0 top-left, +1 top-right, +2 bottom-left, +3 bottom-right), so every read stays in the lane's quad or comes back: -; r0 = permlane16 with selects lane ^ 1 (0x67452301, 0xefcdab89): the right/left neighbour, (x ^ 1) + 64 * y. -; r1 = permlane16 with selects lane ^ 2 (0x54761032, 0xdcfe98ba): the pixel below/above, x + 64 * (y ^ 1). -; r2 = permlanex16 with the identity selects (0x76543210, 0xfedcba98) twice: lane L reads lane L ^ 16 of its half, -; then back, so r2 = p. -; r3 = permlanex16 with selects lane ^ 3 (0x45670123, 0xcdef89ab) of a value already read from lane ^ 3 of the other -; row (the same selects with permlanex16), so r3 = p again, through a non-identity mapping. -; The reads that go out and come back also need the partner lane to hold a pixel: vs_ids' full-screen triangle on -; the 64x64 target fills every wave. -; Run: vk_harness vs_ids.spv ps_w64_a_permlane.spv out.raw with VKH_SUBGROUP_SIZE=64 and 32: equal images, equal to -; the derived words. -; mattr: +wavefrontsize64,-wavefrontsize32 -v_interp_p1_f32_e32 v2, v0, attr0.x -v_interp_p2_f32_e32 v2, v1, attr0.x -v_interp_p1_f32_e32 v3, v0, attr0.y -v_interp_p2_f32_e32 v3, v1, attr0.y -v_mul_f32_e32 v2, 0x42800000, v2 -v_mul_f32_e32 v3, 0x42800000, v3 -v_cvt_u32_f32_e32 v2, v2 -v_cvt_u32_f32_e32 v3, v3 -v_lshl_add_u32 v4, v3, 6, v2 -s_mov_b64 s[10:11], exec -s_mov_b32 s20, 0x67452301 -s_mov_b32 s21, 0xefcdab89 -v_permlane16_b32 v6, v4, s20, s21 -s_mov_b32 s22, 0x54761032 -s_mov_b32 s23, 0xdcfe98ba -v_permlane16_b32 v7, v4, s22, s23 -s_mov_b32 s24, 0x76543210 -s_mov_b32 s25, 0xfedcba98 -v_permlanex16_b32 v5, v4, s24, s25 -v_permlanex16_b32 v8, v5, s24, s25 -s_mov_b32 s26, 0x45670123 -s_mov_b32 s27, 0xcdef89ab -v_permlanex16_b32 v5, v4, s26, s27 -v_permlanex16_b32 v9, v5, s26, s27 -exp mrt0 v6, v7, v8, v9 done vm -s_endpgm diff --git a/runtime/test/shaders/ps_w64_a_skip.asm b/runtime/test/shaders/ps_w64_a_skip.asm deleted file mode 100644 index 4de0b0137..000000000 --- a/runtime/test/shaders/ps_w64_a_skip.asm +++ /dev/null @@ -1,51 +0,0 @@ -; SHADER-10 tier A (docs/design.md, "Wave64 graphics: partition invariance"): a wave64 pixel shader that gives the same -; exports when its 64 lanes are cut into two 32-lane subgroups. x = floor(u * 64), y = floor(v * 64) are the pixel's -; coordinates on the 64x64 target (u, v = attr0.xy of vs_ids), so every expected word is a function of (x, y) and not -; of the lane the pixel landed on. -; (1) a skip region behind s_cbranch_execz: only lanes with x % 4 == 1 run it (EXEC narrowed by s_and_saveexec_b64); -; it defines VGPRs only. r0 = x % 4 == 1 ? 7 * y + x : 1000 + x. -; (2) s_wqm_b64 of the mask x % 4 == 1: a quad is 4 consecutive lanes and never crosses lane 32, so the whole-quad -; mask is the same inside a half. r1 = x % 4 < 2 (the 2x2 quad of pixel x holds columns x & ~1 and (x & ~1) + 1). -; (3) s_cbranch_vccz whose region starts by narrowing EXEC to the very VCC it voted on (y % 4 == 2); VGPR defs only. -; r2 = 2000 + y + (y % 4 == 2 ? 9 : 0). -; (4) a divergent loop closed by s_cbranch_execnz, (x % 4) + 1 iterations of v9 += 1, no scalar state carried. -; r3 = x % 4 + 1. -; Run: vk_harness vs_ids.spv ps_w64_a_skip.spv out.raw, once with VKH_SUBGROUP_SIZE=64 and once with 32: the two images -; must be equal (and equal to the expected words). Output is raw bits (r0, r1, r2, r3) per pixel. -; mattr: +wavefrontsize64,-wavefrontsize32 -v_interp_p1_f32_e32 v2, v0, attr0.x -v_interp_p2_f32_e32 v2, v1, attr0.x -v_interp_p1_f32_e32 v3, v0, attr0.y -v_interp_p2_f32_e32 v3, v1, attr0.y -v_mul_f32_e32 v2, 0x42800000, v2 -v_mul_f32_e32 v3, 0x42800000, v3 -v_cvt_u32_f32_e32 v2, v2 -v_cvt_u32_f32_e32 v3, v3 -s_mov_b64 s[10:11], exec -v_add_nc_u32_e32 v6, 0x3e8, v2 -v_and_b32_e32 v4, 3, v2 -v_cmp_eq_u32_e32 vcc, 1, v4 -s_and_saveexec_b64 s[12:13], vcc -s_cbranch_execz 2 -v_mul_u32_u24_e32 v6, 7, v3 -v_add_nc_u32_e32 v6, v6, v2 -s_or_b64 exec, exec, s[12:13] -v_cmp_eq_u32_e32 vcc, 1, v4 -s_wqm_b64 s[14:15], vcc -v_cndmask_b32_e64 v7, 0, 1, s[14:15] -v_and_b32_e32 v5, 3, v3 -v_add_nc_u32_e32 v8, 0x7d0, v3 -v_cmp_eq_u32_e32 vcc, 2, v5 -s_cbranch_vccz 3 -s_and_saveexec_b64 s[16:17], vcc -v_add_nc_u32_e32 v8, 9, v8 -s_or_b64 exec, exec, s[16:17] -v_add_nc_u32_e32 v10, 1, v4 -v_mov_b32_e32 v9, 0 -v_add_nc_u32_e32 v9, 1, v9 -v_cmp_lt_u32_e32 vcc, v9, v10 -s_and_b64 exec, exec, vcc -s_cbranch_execnz -4 -s_mov_b64 exec, s[10:11] -exp mrt0 v6, v7, v8, v9 done vm -s_endpgm diff --git a/runtime/test/shaders/ps_w64_a_swizzle.asm b/runtime/test/shaders/ps_w64_a_swizzle.asm deleted file mode 100644 index 26c71fa02..000000000 --- a/runtime/test/shaders/ps_w64_a_swizzle.asm +++ /dev/null @@ -1,35 +0,0 @@ -; SHADER-10 tier A, GPU check of ds_swizzle_b32 in a wave64 pixel shader (the swizzle works on groups of 32 lanes, so -; it never leaves a half). p = y * 64 + x is the pixel number (x = floor(u * 64), y = floor(v * 64) on the 64x64 target -; of vs_ids). The words depend only on the 2x2 quad layout of fragment lanes (lane 4k+0 top-left, +1 top-right, -; +2 bottom-left, +3 bottom-right), not on how pixels are packed into lanes: -; r0 = quad-permute mode, selects 3, 2, 1, 0 (offset 0x801b, swizzle(QUAD_PERM,3,2,1,0)): the diagonal pixel, -; (x ^ 1) + 64 * (y ^ 1). -; r1 = bitmask mode, and 0x1f, xor 1 (offset 0x041f, swizzle(SWAP,1)): the right/left neighbour, (x ^ 1) + 64 * y. -; r2 = bitmask mode, and 0x1f, xor 0x10 (offset 0x401f, swizzle(SWAP,16)) twice: lane L reads lane L ^ 16, then -; back, so r2 = p. -; r3 = bitmask mode, and 0x1c (offset 0x001c, swizzle(BROADCAST,4,0)): every lane reads its quad's first lane, -; (x & ~1) + 64 * (y & ~1). -; The reads that go out and come back also need the partner lane to hold a pixel: vs_ids' full-screen triangle on -; the 64x64 target fills every wave. -; Run: vk_harness vs_ids.spv ps_w64_a_swizzle.spv out.raw with VKH_SUBGROUP_SIZE=64 and 32: equal images, equal to -; the derived words. -; mattr: +wavefrontsize64,-wavefrontsize32 -v_interp_p1_f32_e32 v2, v0, attr0.x -v_interp_p2_f32_e32 v2, v1, attr0.x -v_interp_p1_f32_e32 v3, v0, attr0.y -v_interp_p2_f32_e32 v3, v1, attr0.y -v_mul_f32_e32 v2, 0x42800000, v2 -v_mul_f32_e32 v3, 0x42800000, v3 -v_cvt_u32_f32_e32 v2, v2 -v_cvt_u32_f32_e32 v3, v3 -v_lshl_add_u32 v4, v3, 6, v2 -s_mov_b64 s[10:11], exec -ds_swizzle_b32 v6, v4 offset:0x801b -ds_swizzle_b32 v7, v4 offset:0x41f -ds_swizzle_b32 v5, v4 offset:0x401f -s_waitcnt lgkmcnt(0) -ds_swizzle_b32 v8, v5 offset:0x401f -ds_swizzle_b32 v9, v4 offset:0x1c -s_waitcnt lgkmcnt(0) -exp mrt0 v6, v7, v8, v9 done vm -s_endpgm diff --git a/runtime/test/shaders/ps_w64_a_uniform_vote.asm b/runtime/test/shaders/ps_w64_a_uniform_vote.asm deleted file mode 100644 index 5b155ba59..000000000 --- a/runtime/test/shaders/ps_w64_a_uniform_vote.asm +++ /dev/null @@ -1,48 +0,0 @@ -; SHADER-10 tier A: votes on a wave-uniform compare (docs/design.md, "Wave64 graphics: partition invariance"). s4 is a -; user SGPR (the test sets it to 9 with VKH_SGPRS=0,0,0,0,9), copied to a VGPR while EXEC is the launch mask, so every -; lane holds 9 and a v_cmp on it gives every launch lane or none: each 32-lane half votes as the whole wave does, and -; both sides of each branch may have code of their own, scalars included. x = floor(u * 64) on the 64x64 target of -; vs_ids. -; (1) s_cbranch_vccz if/else on 5 < s4 (yes): the yes side sets v6 = 7 and s20 = 11, the no side v6 = 5 and s20 = 22; -; both are read after the join. r0 = x + 7, r1 = 11. -; (2) the LLVM form v_cmp_e64 s[14:15] + s_and_b64 vcc, exec, s[14:15] + s_cbranch_vccnz on 50 < s4 (no): the no -; side sets v8 = 3 and s21 = 33, the yes side v8 = 4 and s21 = 44. r2 = s21 + v8 = 36. -; (3) a loop whose back edge is s_cbranch_vccnz on s22 < s4 (s22 the trip count, an SGPR carried across the back -; edge): s4 = 9 iterations of v9 += 2, then v9 += s22. r3 = 2 * 9 + 9 = 27. -; Run: VKH_SGPRS=0,0,0,0,9 vk_harness vs_ids.spv ps_w64_a_uniform_vote.spv out.raw with VKH_SUBGROUP_SIZE=64 and 32: -; equal, and equal to the expected words (x + 7, 11, 36, 27). -; mattr: +wavefrontsize64,-wavefrontsize32 -v_interp_p1_f32_e32 v2, v0, attr0.x -v_interp_p2_f32_e32 v2, v1, attr0.x -v_mul_f32_e32 v2, 0x42800000, v2 -v_cvt_u32_f32_e32 v2, v2 -s_mov_b64 s[10:11], exec -v_mov_b32_e32 v5, s4 -v_cmp_lt_u32_e32 vcc, 5, v5 -s_cbranch_vccz 3 -v_mov_b32_e32 v6, 7 -s_mov_b32 s20, 11 -s_branch 2 -v_mov_b32_e32 v6, 5 -s_mov_b32 s20, 22 -v_add_nc_u32_e32 v6, v6, v2 -v_mov_b32_e32 v7, s20 -v_cmp_lt_u32_e64 s[14:15], 50, v5 -s_and_b64 vcc, exec, s[14:15] -s_cbranch_vccnz 3 -v_mov_b32_e32 v8, 3 -s_mov_b32 s21, 33 -s_branch 2 -v_mov_b32_e32 v8, 4 -s_mov_b32 s21, 44 -v_add_nc_u32_e32 v8, s21, v8 -s_mov_b32 s22, 0 -v_mov_b32_e32 v9, 0 -s_add_u32 s22, s22, 1 -v_add_nc_u32_e32 v9, 2, v9 -v_mov_b32_e32 v11, s22 -v_cmp_gt_u32_e32 vcc, s4, v11 -s_cbranch_vccnz -5 -v_add_nc_u32_e32 v9, s22, v9 -exp mrt0 v6, v7, v8, v9 done vm -s_endpgm diff --git a/runtime/test/shaders/ps_w64_b_ballot_atomic.asm b/runtime/test/shaders/ps_w64_b_ballot_atomic.asm deleted file mode 100644 index 101577f5c..000000000 --- a/runtime/test/shaders/ps_w64_b_ballot_atomic.asm +++ /dev/null @@ -1,45 +0,0 @@ -; SHADER-10 tier B: a wave-aggregated atomic in a wave64 pixel shader, the compaction idiom of a ballot, a count, one -; atomic from an elected lane and a rank. Pixels with x % 4 == 1 (x = floor(u * 64), y = floor(v * 64) on the 64x64 -; target of vs_ids) are the "wanted" lanes. EXEC = the wanted lanes; n = s_bcnt1_i32_b64 exec; rank = v_mbcnt_lo/hi of -; EXEC; the lane of rank 0 does buffer_atomic_add of n to the counter at heap offset 0 and gets the old value back; -; v_readfirstlane (EXEC is the wanted lanes again, and the first of them is the elected lane) broadcasts it as the -; base; every wanted lane stores its pixel number (y * 64 + x + 1) at heap offset 0x100 + 4 * (base + rank). -; On one wave of 64 or on two of 32 every wanted lane gets a slot of its own and the counter ends at the number of -; wanted pixels, 4096 / 4 = 1024. Which pixel gets which slot depends on the partition (allocation order), so the -; expected result is a set: the counter word is 1024 and the 1024 slot words are exactly the numbers y * 64 + x + 1 of -; the pixels with x % 4 == 1, each once. -; Run: VKH_SGPRS=0,0,65536,0x30000000 VKH_HEAP=0=0 VKH_HEAP_DUMP=heap.raw vk_harness vs_ids.spv ps_w64_b_ballot_atomic.spv -; out.raw, with VKH_SUBGROUP_SIZE=64 and 32. Image: (r0 = x % 4 == 1, 0, 0, 0) per pixel, equal in both runs. -; mattr: +wavefrontsize64,-wavefrontsize32 -v_interp_p1_f32_e32 v2, v0, attr0.x -v_interp_p2_f32_e32 v2, v1, attr0.x -v_interp_p1_f32_e32 v3, v0, attr0.y -v_interp_p2_f32_e32 v3, v1, attr0.y -v_mul_f32_e32 v2, 0x42800000, v2 -v_mul_f32_e32 v3, 0x42800000, v3 -v_cvt_u32_f32_e32 v2, v2 -v_cvt_u32_f32_e32 v3, v3 -v_and_b32_e32 v4, 3, v2 -s_mov_b64 s[10:11], exec -v_cmp_eq_u32_e32 vcc, 1, v4 -v_cndmask_b32_e64 v15, 0, 1, vcc -s_and_saveexec_b64 s[12:13], vcc -s_bcnt1_i32_b64 s6, exec -v_mbcnt_lo_u32_b32 v10, exec_lo, 0 -v_mbcnt_hi_u32_b32 v10, exec_hi, v10 -v_cmp_eq_u32_e32 vcc, 0, v10 -s_and_saveexec_b64 s[14:15], vcc -v_mov_b32_e32 v11, s6 -v_mov_b32_e32 v12, 0 -buffer_atomic_add v11, v12, s[0:3], 0 offen glc -s_or_b64 exec, exec, s[14:15] -v_readfirstlane_b32 s7, v11 -v_add_nc_u32_e32 v13, s7, v10 -v_lshlrev_b32_e32 v13, 2, v13 -v_lshl_add_u32 v14, v3, 6, v2 -v_add_nc_u32_e32 v14, 1, v14 -buffer_store_dword v14, v13, s[0:3], 0 offen offset:256 -s_mov_b64 exec, s[10:11] -v_mov_b32_e32 v16, 0 -exp mrt0 v15, v16, v16, v16 done vm -s_endpgm diff --git a/runtime/test/shaders/ps_w64_b_readfirstlane.asm b/runtime/test/shaders/ps_w64_b_readfirstlane.asm deleted file mode 100644 index c53485c65..000000000 --- a/runtime/test/shaders/ps_w64_b_readfirstlane.asm +++ /dev/null @@ -1,23 +0,0 @@ -; SHADER-10 tier B: v_readfirstlane_b32 of a wave-uniform value in a wave64 pixel shader. s4 is a user SGPR (the test -; sets it to 123 with VKH_SGPRS=0,0,0,0,123), copied to a VGPR and read back; so is a constant. The scalar is the -; same whatever lane is first in the wave or in a 32-lane half. x = floor(u * 64) on the 64x64 target of vs_ids. -; r0 = x + 123, r1 = 77 * 2 + 123 (= 277), r2 = r3 = 0. -; Run: VKH_SGPRS=0,0,0,0,123 vk_harness vs_ids.spv ps_w64_b_readfirstlane.spv out.raw with VKH_SUBGROUP_SIZE=64 and -; 32: equal, and equal to the expected words. -; mattr: +wavefrontsize64,-wavefrontsize32 -v_interp_p1_f32_e32 v2, v0, attr0.x -v_interp_p2_f32_e32 v2, v1, attr0.x -v_mul_f32_e32 v2, 0x42800000, v2 -v_cvt_u32_f32_e32 v2, v2 -s_mov_b64 s[10:11], exec -v_mov_b32_e32 v5, s4 -v_readfirstlane_b32 s20, v5 -v_add_nc_u32_e32 v6, s20, v2 -v_mov_b32_e32 v7, 77 -v_readfirstlane_b32 s21, v7 -s_lshl_b32 s22, s21, 1 -s_add_u32 s22, s22, s20 -v_mov_b32_e32 v7, s22 -v_mov_b32_e32 v8, 0 -exp mrt0 v6, v7, v8, v8 done vm -s_endpgm diff --git a/runtime/test/shaders/ps_w64_b_readlane_uniform.asm b/runtime/test/shaders/ps_w64_b_readlane_uniform.asm deleted file mode 100644 index b3c2b51e0..000000000 --- a/runtime/test/shaders/ps_w64_b_readlane_uniform.asm +++ /dev/null @@ -1,24 +0,0 @@ -; SHADER-10 tier B: v_readlane_b32 of a value that is the same in every lane, at lanes that a 32-lane subgroup does not -; have. s4 is a user SGPR (the test sets it to 123 with VKH_SGPRS=0,0,0,0,123); v5 = s4 and v7 = 77 are written while -; EXEC is the launch mask, so every lane holds them. Reading lane 40 of v5 and lane 63 of v7 gives 123 and 77 on a -; wave64 and, since the value is the same everywhere, the lane's own copy is the exact answer on a 32-lane subgroup -; (a shuffle from lane 40 of a 32-wide subgroup is undefined: the translator rewrites the read, docs/design.md). -; x = floor(u * 64) on the 64x64 target of vs_ids. r0 = x + 123, r1 = 123 + 77 = 200, r2 = r3 = 0. -; Run: VKH_SGPRS=0,0,0,0,123 vk_harness vs_ids.spv ps_w64_b_readlane_uniform.spv out.raw with VKH_SUBGROUP_SIZE=64 -; and 32: equal, and equal to the expected words. -; mattr: +wavefrontsize64,-wavefrontsize32 -v_interp_p1_f32_e32 v2, v0, attr0.x -v_interp_p2_f32_e32 v2, v1, attr0.x -v_mul_f32_e32 v2, 0x42800000, v2 -v_cvt_u32_f32_e32 v2, v2 -s_mov_b64 s[10:11], exec -v_mov_b32_e32 v5, s4 -v_mov_b32_e32 v7, 77 -v_readlane_b32 s20, v5, 40 -v_readlane_b32 s21, v7, 63 -v_add_nc_u32_e32 v6, s20, v2 -s_add_u32 s22, s20, s21 -v_mov_b32_e32 v7, s22 -v_mov_b32_e32 v8, 0 -exp mrt0 v6, v7, v8, v8 done vm -s_endpgm diff --git a/runtime/test/shaders/ps_w64_b_readlane_uniform_lane.asm b/runtime/test/shaders/ps_w64_b_readlane_uniform_lane.asm deleted file mode 100644 index 839daec1c..000000000 --- a/runtime/test/shaders/ps_w64_b_readlane_uniform_lane.asm +++ /dev/null @@ -1,23 +0,0 @@ -; SHADER-314 tier B: v_readlane_b32 of a uniform VGPR (same value in every lane) with a tainted lane selector -; (s_ff1_i32_b64 / s_bcnt1_i32_b64 of EXEC). Because v5 = s4 and v7 = 77 are uniform across all lanes, the -; readlane result is invariant across 32-lane halves regardless of which lane index s6/s7 selects. -; x = floor(u * 64) on the 64x64 target of vs_ids. r0 = x + 123, r1 = 123 + 77 = 200, r2 = r3 = 0. -; Run: VKH_SGPRS=0,0,0,0,123 vk_harness vs_ids.spv ps_w64_b_readlane_uniform_lane.spv out.raw. -; mattr: +wavefrontsize64,-wavefrontsize32 -v_interp_p1_f32_e32 v2, v0, attr0.x -v_interp_p2_f32_e32 v2, v1, attr0.x -v_mul_f32_e32 v2, 0x42800000, v2 -v_cvt_u32_f32_e32 v2, v2 -s_mov_b64 s[10:11], exec -v_mov_b32_e32 v5, s4 -v_mov_b32_e32 v7, 77 -s_ff1_i32_b64 s6, exec -s_bcnt1_i32_b64 s7, exec -v_readlane_b32 s20, v5, s6 -v_readlane_b32 s21, v7, s7 -v_add_nc_u32_e32 v6, s20, v2 -s_add_u32 s22, s20, s21 -v_mov_b32_e32 v7, s22 -v_mov_b32_e32 v8, 0 -exp mrt0 v6, v7, v8, v8 done vm -s_endpgm diff --git a/runtime/test/shaders/ps_w64_b_waterfall.asm b/runtime/test/shaders/ps_w64_b_waterfall.asm deleted file mode 100644 index cb5cba37e..000000000 --- a/runtime/test/shaders/ps_w64_b_waterfall.asm +++ /dev/null @@ -1,33 +0,0 @@ -; SHADER-10 tier B: a waterfall loop in a wave64 pixel shader. a = (x % 4) + 4 * (y % 4) is a per-pixel index into 16 -; distinct values (x = floor(u * 64), y = floor(v * 64), pixel coordinates on the 64x64 target of vs_ids). Each trip -; reads the first active lane's a (v_readfirstlane_b32), keeps the lanes whose a equals it, runs the body for them -; with the scalar (s21 = 17 * a, v6 = s21 + x) and takes them out of EXEC; the loop ends when EXEC is empty. The -; scalars are only used inside the body, so a lane's result is 17 * its own a + x however the lanes are grouped -; (one wave of 64 or two of 32). r0 = 17 * a + x; r1 = a; r2 = r3 = 0. -; Run: vk_harness vs_ids.spv ps_w64_b_waterfall.spv out.raw with VKH_SUBGROUP_SIZE=64 and 32: equal, and equal to -; the expected words. -; mattr: +wavefrontsize64,-wavefrontsize32 -v_interp_p1_f32_e32 v2, v0, attr0.x -v_interp_p2_f32_e32 v2, v1, attr0.x -v_interp_p1_f32_e32 v3, v0, attr0.y -v_interp_p2_f32_e32 v3, v1, attr0.y -v_mul_f32_e32 v2, 0x42800000, v2 -v_mul_f32_e32 v3, 0x42800000, v3 -v_cvt_u32_f32_e32 v2, v2 -v_cvt_u32_f32_e32 v3, v3 -v_and_b32_e32 v4, 3, v2 -v_and_b32_e32 v5, 3, v3 -v_lshl_add_u32 v4, v5, 2, v4 -v_mov_b32_e32 v6, 0 -s_mov_b64 s[10:11], exec -v_readfirstlane_b32 s20, v4 -v_cmp_eq_u32_e32 vcc, s20, v4 -s_and_saveexec_b64 s[12:13], vcc -s_mul_i32 s21, s20, 17 -v_add_nc_u32_e32 v6, s21, v2 -s_xor_b64 exec, exec, s[12:13] -s_cbranch_execnz -7 -s_mov_b64 exec, s[10:11] -v_mov_b32_e32 v7, 0 -exp mrt0 v6, v4, v7, v7 done vm -s_endpgm diff --git a/runtime/test/shaders/ps_w64_c_bcnt_export.asm b/runtime/test/shaders/ps_w64_c_bcnt_export.asm deleted file mode 100644 index 02964ca08..000000000 --- a/runtime/test/shaders/ps_w64_c_bcnt_export.asm +++ /dev/null @@ -1,18 +0,0 @@ -; SHADER-10 tier C: a lane count exported as data. Pixels with x % 4 == 1 (x = floor(u * 64) on the 64x64 target of -; vs_ids) set VCC; s_bcnt1_i32_b64 of it counts them in the whole wave (16 for a full wave of 64 pixels in which a -; quarter of the columns match) and in one 32-lane half only half as many. r0 = the count; r1 = x % 4 == 1. -; Run: vk_harness vs_ids.spv ps_w64_c_bcnt_export.spv out.raw with VKH_SUBGROUP_SIZE=64 and 32: r1 equal, r0 -; differs (the detector must call this shader tier C). -; mattr: +wavefrontsize64,-wavefrontsize32 -v_interp_p1_f32_e32 v2, v0, attr0.x -v_interp_p2_f32_e32 v2, v1, attr0.x -v_mul_f32_e32 v2, 0x42800000, v2 -v_cvt_u32_f32_e32 v2, v2 -v_and_b32_e32 v4, 3, v2 -v_cmp_eq_u32_e32 vcc, 1, v4 -s_bcnt1_i32_b64 s6, vcc -v_mov_b32_e32 v6, s6 -v_cndmask_b32_e64 v7, 0, 1, vcc -v_mov_b32_e32 v8, 0 -exp mrt0 v6, v7, v8, v8 done vm -s_endpgm diff --git a/runtime/test/shaders/ps_w64_c_execz_sgpr.asm b/runtime/test/shaders/ps_w64_c_execz_sgpr.asm deleted file mode 100644 index ccfa9501c..000000000 --- a/runtime/test/shaders/ps_w64_c_execz_sgpr.asm +++ /dev/null @@ -1,33 +0,0 @@ -; SHADER-10 tier C: the EXEC-zero side of an s_cbranch_execz writes an SGPR that is exported afterwards. Only the pixel -; (5, 7) is "on" (v4 == 0). s_cbranch_execz is taken when no lane of the WAVE is active: on a wave64 the pixel's wave -; runs the active side and every pixel of it reads s5 = 7; the 63 other waves take the branch and read 9. On two 32-lane -; subgroups the half without the pixel takes it as well and reads 9. r0 = s5 (7 for the pixel, else partition -; dependent), r1 = the pixel. -; Run: vk_harness vs_ids.spv ps_w64_c_execz_sgpr.spv out.raw with VKH_SUBGROUP_SIZE=64 and 32: r1 equal, r0 differs -; in the pixels of the other half (the detector must call this shader tier C). -; mattr: +wavefrontsize64,-wavefrontsize32 -v_interp_p1_f32_e32 v2, v0, attr0.x -v_interp_p2_f32_e32 v2, v1, attr0.x -v_interp_p1_f32_e32 v3, v0, attr0.y -v_interp_p2_f32_e32 v3, v1, attr0.y -v_mul_f32_e32 v2, 0x42800000, v2 -v_mul_f32_e32 v3, 0x42800000, v3 -v_cvt_u32_f32_e32 v2, v2 -v_cvt_u32_f32_e32 v3, v3 -s_mov_b64 s[10:11], exec -v_xor_b32_e32 v4, 5, v2 -v_xor_b32_e32 v5, 7, v3 -v_or_b32_e32 v4, v4, v5 -s_mov_b32 s5, 7 -v_cmp_eq_u32_e32 vcc, 0, v4 -v_cndmask_b32_e64 v7, 0, 1, vcc -s_and_saveexec_b64 s[12:13], vcc -s_cbranch_execz 2 -v_mov_b32_e32 v8, 5 -s_branch 1 -s_mov_b32 s5, 9 -s_or_b64 exec, exec, s[12:13] -v_mov_b32_e32 v6, s5 -v_mov_b32_e32 v8, 0 -exp mrt0 v6, v7, v8, v8 done vm -s_endpgm diff --git a/runtime/test/shaders/ps_w64_c_lane_id.asm b/runtime/test/shaders/ps_w64_c_lane_id.asm deleted file mode 100644 index a8bd7743b..000000000 --- a/runtime/test/shaders/ps_w64_c_lane_id.asm +++ /dev/null @@ -1,17 +0,0 @@ -; SHADER-10 tier C: the raw lane number 0..63 (v_mbcnt_lo/hi of -1) used as data. On a 64-lane subgroup the pixels of a -; wave get 0..63 in lane order; on 32-lane subgroups 0..31 twice. r0 = lane id, r1 = lane id & 31 (inside a half the -; same everywhere), r2 = x = floor(u * 64) on the 64x64 target of vs_ids. -; Run: vk_harness vs_ids.spv ps_w64_c_lane_id.spv out.raw with VKH_SUBGROUP_SIZE=64 and 32: r1 and r2 equal, r0 -; differs (the detector must call this shader tier C). -; mattr: +wavefrontsize64,-wavefrontsize32 -v_interp_p1_f32_e32 v2, v0, attr0.x -v_interp_p2_f32_e32 v2, v1, attr0.x -v_mul_f32_e32 v2, 0x42800000, v2 -v_cvt_u32_f32_e32 v2, v2 -s_mov_b64 s[10:11], exec -v_mbcnt_lo_u32_b32 v6, -1, 0 -v_mbcnt_hi_u32_b32 v6, -1, v6 -v_and_b32_e32 v7, 31, v6 -v_mov_b32_e32 v8, 0 -exp mrt0 v6, v7, v2, v8 done vm -s_endpgm diff --git a/runtime/test/shaders/ps_w64_c_readlane.asm b/runtime/test/shaders/ps_w64_c_readlane.asm deleted file mode 100644 index fea299919..000000000 --- a/runtime/test/shaders/ps_w64_c_readlane.asm +++ /dev/null @@ -1,26 +0,0 @@ -; SHADER-10 tier C: v_readlane_b32 of a varying value. p = y * 64 + x is the pixel number (x = floor(u * 64), -; y = floor(v * 64) on the 64x64 target of vs_ids), different for every lane. s6 = lane 40's p: lane 40 does not exist -; in a 32-lane subgroup, so it cannot be the same there. s7 = lane 7's p: it looks harmless (lane 7 exists in a -; half) but it is not: on a wave64 every lane gets the value of hardware lane 7, in two 32-lane halves the upper half -; gets the value of its own lane 7 (hardware lane 39). Only a readlane of a value that is the same in every lane is -; invariant. r0 = s6, r1 = the own p (equal everywhere), r2 = s7. -; Run: vk_harness vs_ids.spv ps_w64_c_readlane.spv out.raw with VKH_SUBGROUP_SIZE=64 and 32: r1 equal, r0 and r2 -; differ (the detector must call this shader tier C, whichever of the two reads it looks at). -; mattr: +wavefrontsize64,-wavefrontsize32 -v_interp_p1_f32_e32 v2, v0, attr0.x -v_interp_p2_f32_e32 v2, v1, attr0.x -v_interp_p1_f32_e32 v3, v0, attr0.y -v_interp_p2_f32_e32 v3, v1, attr0.y -v_mul_f32_e32 v2, 0x42800000, v2 -v_mul_f32_e32 v3, 0x42800000, v3 -v_cvt_u32_f32_e32 v2, v2 -v_cvt_u32_f32_e32 v3, v3 -v_lshl_add_u32 v4, v3, 6, v2 -s_mov_b64 s[10:11], exec -v_readlane_b32 s6, v4, 40 -v_readlane_b32 s7, v4, 7 -v_mov_b32_e32 v6, s6 -v_mov_b32_e32 v7, s7 -v_mov_b32_e32 v8, 0 -exp mrt0 v6, v4, v7, v8 done vm -s_endpgm diff --git a/runtime/test/shaders/ps_w64_c_scc_vote.asm b/runtime/test/shaders/ps_w64_c_scc_vote.asm deleted file mode 100644 index e9f43ec1a..000000000 --- a/runtime/test/shaders/ps_w64_c_scc_vote.asm +++ /dev/null @@ -1,27 +0,0 @@ -; SHADER-10 tier C: the SCC of a wave-wide vote read as data. Only the pixel (5, 7) is "on" (v4 == 0). -; s_cmp_lg_u64 vcc, 0 sets SCC when any lane of the wave voted; s_cselect_b32 turns it into a number: on a wave64 -; every pixel of the pixel's wave reads 1, on two 32-lane subgroups only the half that holds the pixel does. -; r0 = SCC (partition dependent, 1 for the pixel), r1 = the pixel. -; Run: vk_harness vs_ids.spv ps_w64_c_scc_vote.spv out.raw with VKH_SUBGROUP_SIZE=64 and 32: r1 equal, r0 differs -; in the pixels of the other half (the detector must call this shader tier C). -; mattr: +wavefrontsize64,-wavefrontsize32 -v_interp_p1_f32_e32 v2, v0, attr0.x -v_interp_p2_f32_e32 v2, v1, attr0.x -v_interp_p1_f32_e32 v3, v0, attr0.y -v_interp_p2_f32_e32 v3, v1, attr0.y -v_mul_f32_e32 v2, 0x42800000, v2 -v_mul_f32_e32 v3, 0x42800000, v3 -v_cvt_u32_f32_e32 v2, v2 -v_cvt_u32_f32_e32 v3, v3 -s_mov_b64 s[10:11], exec -v_xor_b32_e32 v4, 5, v2 -v_xor_b32_e32 v5, 7, v3 -v_or_b32_e32 v4, v4, v5 -v_cmp_eq_u32_e32 vcc, 0, v4 -s_cmp_lg_u64 vcc, 0 -s_cselect_b32 s5, 1, 0 -v_mov_b32_e32 v6, s5 -v_cndmask_b32_e64 v7, 0, 1, vcc -v_mov_b32_e32 v8, 0 -exp mrt0 v6, v7, v8, v8 done vm -s_endpgm diff --git a/runtime/test/shaders/ps_w64_c_vote_else.asm b/runtime/test/shaders/ps_w64_c_vote_else.asm deleted file mode 100644 index 1294555eb..000000000 --- a/runtime/test/shaders/ps_w64_c_vote_else.asm +++ /dev/null @@ -1,32 +0,0 @@ -; SHADER-10 tier C: the "no" side of a vote has code of its own. Only the pixel (5, 7) votes yes (v4 == 0). -; s_cbranch_vccnz goes to the run side (EXEC narrowed to the vote, v6 = 7) when some lane of the WAVE voted yes; the -; fall-through (v6 = 5) runs when none did. On a wave64 the other 63 pixels of the pixel's wave keep v6 = 0; on two -; 32-lane subgroups the half without the pixel runs the fall-through and gets 5. r0 = 7 for the pixel, else -; partition dependent; r1 = the pixel. -; Run: vk_harness vs_ids.spv ps_w64_c_vote_else.spv out.raw with VKH_SUBGROUP_SIZE=64 and 32: r1 equal, r0 differs -; in the pixels of the other half (the detector must call this shader tier C). -; mattr: +wavefrontsize64,-wavefrontsize32 -v_interp_p1_f32_e32 v2, v0, attr0.x -v_interp_p2_f32_e32 v2, v1, attr0.x -v_interp_p1_f32_e32 v3, v0, attr0.y -v_interp_p2_f32_e32 v3, v1, attr0.y -v_mul_f32_e32 v2, 0x42800000, v2 -v_mul_f32_e32 v3, 0x42800000, v3 -v_cvt_u32_f32_e32 v2, v2 -v_cvt_u32_f32_e32 v3, v3 -s_mov_b64 s[10:11], exec -v_xor_b32_e32 v4, 5, v2 -v_xor_b32_e32 v5, 7, v3 -v_or_b32_e32 v4, v4, v5 -v_mov_b32_e32 v6, 0 -v_cmp_eq_u32_e32 vcc, 0, v4 -v_cndmask_b32_e64 v7, 0, 1, vcc -s_cbranch_vccnz 2 -v_mov_b32_e32 v6, 5 -s_branch 3 -s_and_saveexec_b64 s[16:17], vcc -v_mov_b32_e32 v6, 7 -s_or_b64 exec, exec, s[16:17] -v_mov_b32_e32 v8, 0 -exp mrt0 v6, v7, v8, v8 done vm -s_endpgm diff --git a/runtime/test/shaders/ps_w64_c_vote_stale.asm b/runtime/test/shaders/ps_w64_c_vote_stale.asm deleted file mode 100644 index 64b70655f..000000000 --- a/runtime/test/shaders/ps_w64_c_vote_stale.asm +++ /dev/null @@ -1,27 +0,0 @@ -; SHADER-10 tier C: scalar state defined behind a wave-wide vote and read afterwards (the wave64 form of -; ps_uniform_branch). Only the pixel (0, 0) (x = floor(u * 64) = 0, y = floor(v * 64) = 0 on the 64x64 target of -; vs_ids) sets VCC. s_cbranch_vccz is a vote over the wave: on a wave64 the 63 other pixels of that pixel's wave -; run `s_add_u32 s5, s5, 1` as well and read 8; on two 32-lane subgroups the half without pixel (0, 0) votes "no" and -; keeps s5 = 7. r0 = s5, r1 = pixel (0, 0). -; Run: vk_harness vs_ids.spv ps_w64_c_vote_stale.spv out.raw with VKH_SUBGROUP_SIZE=64 and 32: r1 equal, r0 differs -; in the pixels of the other half (the detector must call this shader tier C). -; mattr: +wavefrontsize64,-wavefrontsize32 -v_interp_p1_f32_e32 v2, v0, attr0.x -v_interp_p2_f32_e32 v2, v1, attr0.x -v_interp_p1_f32_e32 v3, v0, attr0.y -v_interp_p2_f32_e32 v3, v1, attr0.y -v_mul_f32_e32 v2, 0x42800000, v2 -v_mul_f32_e32 v3, 0x42800000, v3 -v_cvt_u32_f32_e32 v2, v2 -v_cvt_u32_f32_e32 v3, v3 -s_mov_b64 s[10:11], exec -v_or_b32_e32 v4, v2, v3 -v_cmp_eq_u32_e32 vcc, 0, v4 -s_mov_b32 s5, 7 -s_cbranch_vccz 1 -s_add_u32 s5, s5, 1 -v_mov_b32_e32 v6, s5 -v_cndmask_b32_e64 v7, 0, 1, vcc -v_mov_b32_e32 v8, 0 -exp mrt0 v6, v7, v8, v8 done vm -s_endpgm diff --git a/runtime/test/shaders/ps_w64_c_waterfall_count.asm b/runtime/test/shaders/ps_w64_c_waterfall_count.asm deleted file mode 100644 index fba4bb844..000000000 --- a/runtime/test/shaders/ps_w64_c_waterfall_count.asm +++ /dev/null @@ -1,36 +0,0 @@ -; SHADER-10 tier C, the negative twin of ps_w64_b_waterfall: the same waterfall loop over a = (x % 8) + 8 * (y % 8) -; (64 distinct values per 8x8 tile of pixels, x = floor(u * 64), y = floor(v * 64) on the 64x64 target of vs_ids), -; but it also counts the trips in s22 and exports the count after the loop. On a wave64 the loop runs once per -; distinct a in the whole wave, on two 32-lane subgroups once per distinct a in each half, so the exported count -; changes with the partition: a wave of 64 pixels from one 8x8 tile gives 64, a half of it 32 or fewer. -; r0 = 17 * a + x (exact either way), r1 = the trip count s22 (not exact on 32-wide subgroups). -; Run: vk_harness vs_ids.spv ps_w64_c_waterfall_count.spv out.raw with VKH_SUBGROUP_SIZE=64 and 32: r0 equal, r1 -; differs in some pixel (the detector must call this shader tier C). -; mattr: +wavefrontsize64,-wavefrontsize32 -v_interp_p1_f32_e32 v2, v0, attr0.x -v_interp_p2_f32_e32 v2, v1, attr0.x -v_interp_p1_f32_e32 v3, v0, attr0.y -v_interp_p2_f32_e32 v3, v1, attr0.y -v_mul_f32_e32 v2, 0x42800000, v2 -v_mul_f32_e32 v3, 0x42800000, v3 -v_cvt_u32_f32_e32 v2, v2 -v_cvt_u32_f32_e32 v3, v3 -v_and_b32_e32 v4, 7, v2 -v_and_b32_e32 v5, 7, v3 -v_lshl_add_u32 v4, v5, 3, v4 -v_mov_b32_e32 v6, 0 -s_mov_b32 s22, 0 -s_mov_b64 s[10:11], exec -v_readfirstlane_b32 s20, v4 -v_cmp_eq_u32_e32 vcc, s20, v4 -s_and_saveexec_b64 s[12:13], vcc -s_mul_i32 s21, s20, 17 -v_add_nc_u32_e32 v6, s21, v2 -s_add_u32 s22, s22, 1 -s_xor_b64 exec, exec, s[12:13] -s_cbranch_execnz -8 -s_mov_b64 exec, s[10:11] -v_mov_b32_e32 v7, s22 -v_mov_b32_e32 v8, 0 -exp mrt0 v6, v7, v8, v8 done vm -s_endpgm diff --git a/runtime/test/shaders/ps_w64x_readlane.asm b/runtime/test/shaders/ps_w64x_readlane.asm deleted file mode 100644 index 895254471..000000000 --- a/runtime/test/shaders/ps_w64x_readlane.asm +++ /dev/null @@ -1,27 +0,0 @@ -; Wave64 pixel shader with v_readlane_b32 across both halves of the wave (RDNA2 ISA: lane = S1 % 64, EXEC ignored). -; The translator's pixel path takes the lane from SubgroupLocalInvocationId, which is the hardware lane only in a -; 64-wide subgroup; in a 32-wide one the lane select wraps (lane 40 reads lane 8), so the words below differ. -; v2 = 3 * lane + 1. Every lane of a full wave reads the same scalars: -; s6 = v2[40] = 121, s7 = v2[5] = 16, s8 = v2[33] = 100, s9 = v2[63] = 190 -; Each is or'ed with 0x40000000 so the export is a normal float (a float render target keeps bit patterns, but a -; denormal could be flushed). Export mrt0 = (0x40000079, 0x40000010, 0x40000064, 0x400000be) for every covered -; pixel of a full wave; draw a triangle that covers the whole target so every wave is full. -; Run: d3d12_subgroup_test (the PS through a D3D12 graphics PSO, R32G32B32A32_FLOAT target). -; mattr: +wavefrontsize64,-wavefrontsize32 -v_mbcnt_lo_u32_b32 v1, -1, 0 -v_mbcnt_hi_u32_b32 v1, -1, v1 -v_mad_u32_u24 v2, v1, 3, 1 -v_readlane_b32 s6, v2, 40 -v_readlane_b32 s7, v2, 5 -v_readlane_b32 s8, v2, 33 -v_readlane_b32 s9, v2, 63 -s_or_b32 s6, s6, 0x40000000 -s_or_b32 s7, s7, 0x40000000 -s_or_b32 s8, s8, 0x40000000 -s_or_b32 s9, s9, 0x40000000 -v_mov_b32 v3, s6 -v_mov_b32 v4, s7 -v_mov_b32 v5, s8 -v_mov_b32 v6, s9 -exp mrt0 v3, v4, v5, v6 done vm -s_endpgm diff --git a/runtime/test/shaders/ps_wqm.asm b/runtime/test/shaders/ps_wqm.asm deleted file mode 100644 index 4e0fc98e9..000000000 --- a/runtime/test/shaders/ps_wqm.asm +++ /dev/null @@ -1,26 +0,0 @@ -; Whole-quad mode in a pixel shader. x = floor(u * 64), y = floor(v * 64) are the pixel's coordinates on the 64x64 -; target (u, v = attr0.xy of vs_ids, 0..1 over the image). Own mask: x % 4 == 1 and y % 4 == 2, one pixel in 16. -; s_wqm_b32 of it must light the whole 2x2 quad that pixel belongs to: x % 4 in {0,1} and y % 4 in {2,3}, so pixel -; (x, y) is in the WQM mask iff ((x >> 1) & 1) == 0 and ((y >> 1) & 1) == 1, and each pixel's own bit is contained -; in it. The target is fully covered, so no quad has a helper lane. Assumption: a hardware quad (4 consecutive lanes -; of the pixel wave) is the 2x2 pixel quad Vulkan's quad operations use. -; Run: vk_harness vs_ids.spv ps_wqm.spv out.raw. Per pixel (x, y) the words are (wqm, own, wqm, own) with -; wqm = 1 iff x % 4 < 2 and y % 4 >= 2, own = 1 iff x % 4 == 1 and y % 4 == 2. -v_interp_p1_f32_e32 v2, v0, attr0.x -v_interp_p2_f32_e32 v2, v1, attr0.x -v_interp_p1_f32_e32 v3, v0, attr0.y -v_interp_p2_f32_e32 v3, v1, attr0.y -v_mul_f32_e32 v2, 0x42800000, v2 -v_mul_f32_e32 v3, 0x42800000, v3 -v_cvt_u32_f32_e32 v2, v2 -v_cvt_u32_f32_e32 v3, v3 -v_and_b32_e32 v4, 3, v2 -v_and_b32_e32 v5, 3, v3 -v_cmp_eq_u32_e32 vcc_lo, 1, v4 -v_cmp_eq_u32_e64 s6, 2, v5 -s_and_b32 s7, vcc_lo, s6 -s_wqm_b32 s8, s7 -v_cndmask_b32_e64 v6, 0, 1, s8 -v_cndmask_b32_e64 v7, 0, 1, s7 -exp mrt0 v6, v7, v6, v7 done vm -s_endpgm diff --git a/runtime/test/shaders/vs_base_ids.asm b/runtime/test/shaders/vs_base_ids.asm deleted file mode 100644 index 27e905aea..000000000 --- a/runtime/test/shaders/vs_base_ids.asm +++ /dev/null @@ -1,24 +0,0 @@ -; Vertex shader for the base-vertex / base-instance test. On AMD hardware the VS input VGPRs are zero-based: v0 is -; the vertex id without the draw's first vertex (Mesa: ac.vertex_id = load_vertex_id_zero_base, the base comes in -; the base_vertex SGPR), and v3 the instance id without its first instance (ac.instance_id = load_instance_id, the -; base in start_instance). Vulkan's VertexIndex / InstanceIndex include firstVertex / firstInstance. -; Same full-screen triangle as vs_ids (from v0's low bits), param0 = (u, v, 0, 1), and param1.x = -; 0x101 + v0 + 0x1000 * v3 as raw bits, so ps_flat (attr1.x from the provoking vertex) shows both ids. -; Run: VKH_DRAW=16,7 vk_harness vs_base_ids.spv ps_flat.spv out.raw -; -> mrt0 bits = 0x101, 0x102 on every pixel (vertex 0 of instance 0); 0x7111 means firstVertex/firstInstance -; leaked into v0 / v3. With VKH_DRAW unset (0,0) both read 0x101, as vs_ids. -v_lshlrev_b32_e32 v8, 12, v3 -v_lshlrev_b32_e32 v1, 1, v0 -v_and_b32_e32 v1, 2, v1 -v_and_b32_e32 v2, 2, v0 -v_cvt_f32_u32_e32 v1, v1 -v_cvt_f32_u32_e32 v2, v2 -v_fma_f32 v3, v1, 2.0, -1.0 -v_fma_f32 v4, v2, 2.0, -1.0 -v_mov_b32_e32 v5, 0 -v_mov_b32_e32 v6, 1.0 -exp pos0 v3, v4, v5, v6 done -exp param0 v1, v2, v5, v6 -v_add3_u32 v7, v0, v8, 0x101 -exp param1 v7, v7, v7, v7 -s_endpgm diff --git a/runtime/test/shaders/vs_clip.asm b/runtime/test/shaders/vs_clip.asm deleted file mode 100644 index 0e8495768..000000000 --- a/runtime/test/shaders/vs_clip.asm +++ /dev/null @@ -1,28 +0,0 @@ -; Full-screen triangle. At pixel centers the two signed distances are positive -; left of column 32 and above row 16 in a 64x64 target. Adding 4 via s0 or s1 -; makes that plane positive everywhere. Expected masks: 4096, 2048, 1024, 512. -; The varying location changes between builds; pos1 supplies the clip values. -v_lshlrev_b32_e32 v1, 1, v0 -v_and_b32_e32 v1, 2, v1 -v_and_b32_e32 v2, 2, v0 -v_cvt_f32_u32_e32 v1, v1 -v_cvt_f32_u32_e32 v2, v2 -v_fma_f32 v3, v1, 2.0, -1.0 -v_fma_f32 v4, v2, 2.0, -1.0 -v_mov_b32_e32 v5, 0 -v_mov_b32_e32 v6, 1.0 -v_sub_f32_e32 v7, 0.5, v1 -v_sub_f32_e32 v8, 0x3e800000, v2 -v_add_f32_e32 v7, s0, v7 -v_add_f32_e32 v8, s1, v8 -exp pos0 v3, v4, v5, v6 -exp pos1 v7, v8, v5, v6 done -.ifndef PARAM_SLOT -.set PARAM_SLOT, 1 -.endif -.if PARAM_SLOT == 4 -exp param4 v7, v8, v5, v6 -.else -exp param1 v7, v8, v5, v6 -.endif -s_endpgm diff --git a/runtime/test/shaders/vs_f16_pack.asm b/runtime/test/shaders/vs_f16_pack.asm deleted file mode 100644 index 492299a32..000000000 --- a/runtime/test/shaders/vs_f16_pack.asm +++ /dev/null @@ -1,18 +0,0 @@ -; Vertex shader for ps_interp_f16_high: the vs_ids triangle (u and v run 0..1 over the image) with two f16 values -; packed in each 32-bit param channel, as Mesa's prerast export packs 16-bit varyings (low half, high half): -; param0.x = f16(u) | f16(v) << 16, param0.y = f16(v) | f16(u) << 16, and param1 = (u, v, 0, 1) as f32. -v_lshlrev_b32_e32 v1, 1, v0 -v_and_b32_e32 v1, 2, v1 -v_and_b32_e32 v2, 2, v0 -v_cvt_f32_u32_e32 v1, v1 -v_cvt_f32_u32_e32 v2, v2 -v_fma_f32 v3, v1, 2.0, -1.0 -v_fma_f32 v4, v2, 2.0, -1.0 -v_mov_b32_e32 v5, 0 -v_mov_b32_e32 v6, 1.0 -exp pos0 v3, v4, v5, v6 done -v_cvt_pkrtz_f16_f32_e32 v7, v1, v2 -v_cvt_pkrtz_f16_f32_e32 v8, v2, v1 -exp param0 v7, v8, v5, v6 -exp param1 v1, v2, v5, v6 -s_endpgm diff --git a/runtime/test/shaders/vs_ids.asm b/runtime/test/shaders/vs_ids.asm deleted file mode 100644 index 17bd2e81a..000000000 --- a/runtime/test/shaders/vs_ids.asm +++ /dev/null @@ -1,17 +0,0 @@ -; Vertex shader for the pixel tests that need more than one input: a full-screen triangle from the vertex index -; (v0), param0 = (u, v, 0, 1) with u and v running 0..2 over the triangle (0..1 over the image), and -; param1 = the integer 0x101 + vertex index in all four components, as raw bits. -v_lshlrev_b32_e32 v1, 1, v0 -v_and_b32_e32 v1, 2, v1 -v_and_b32_e32 v2, 2, v0 -v_cvt_f32_u32_e32 v1, v1 -v_cvt_f32_u32_e32 v2, v2 -v_fma_f32 v3, v1, 2.0, -1.0 -v_fma_f32 v4, v2, 2.0, -1.0 -v_mov_b32_e32 v5, 0 -v_mov_b32_e32 v6, 1.0 -exp pos0 v3, v4, v5, v6 done -exp param0 v1, v2, v5, v6 -v_add_nc_u32_e32 v7, 0x101, v0 -exp param1 v7, v7, v7, v7 -s_endpgm diff --git a/runtime/test/shaders/vs_interp_consts.asm b/runtime/test/shaders/vs_interp_consts.asm deleted file mode 100644 index 29217e82d..000000000 --- a/runtime/test/shaders/vs_interp_consts.asm +++ /dev/null @@ -1,26 +0,0 @@ -; Vertex shader for ps_interp_f32_mods and ps_interp_mov_mods: the vs_ids full-screen triangle, with the same constant -; in each param channel at all three vertices, so interpolation gives that constant at every pixel: -; param0 = (1.5, -0.25, 0.375, 0.625), param1 = (1.5, -0.5, 0.25, 4.0), param2 = (0.25, 3.0, 0, 0). -v_lshlrev_b32_e32 v1, 1, v0 -v_and_b32_e32 v1, 2, v1 -v_and_b32_e32 v2, 2, v0 -v_cvt_f32_u32_e32 v1, v1 -v_cvt_f32_u32_e32 v2, v2 -v_fma_f32 v3, v1, 2.0, -1.0 -v_fma_f32 v4, v2, 2.0, -1.0 -v_mov_b32_e32 v5, 0 -v_mov_b32_e32 v6, 1.0 -exp pos0 v3, v4, v5, v6 done -v_mov_b32_e32 v7, 0x3fc00000 -v_mov_b32_e32 v8, 0xbe800000 -v_mov_b32_e32 v9, 0x3ec00000 -v_mov_b32_e32 v10, 0x3f200000 -exp param0 v7, v8, v9, v10 -v_mov_b32_e32 v8, -0.5 -v_mov_b32_e32 v9, 0.25 -v_mov_b32_e32 v10, 4.0 -exp param1 v7, v8, v9, v10 -v_mov_b32_e32 v7, 0.25 -v_mov_b32_e32 v8, 0x40400000 -exp param2 v7, v8, v5, v5 -s_endpgm diff --git a/runtime/test/shaders/vs_m15.asm b/runtime/test/shaders/vs_m15.asm deleted file mode 100644 index 3ac449b0b..000000000 --- a/runtime/test/shaders/vs_m15.asm +++ /dev/null @@ -1,25 +0,0 @@ -; M1.5 vertex shader: vertex fetch through a V# the application wrote into a descriptor-table slot, the way the -; translated game VS that fetch without the driver's fetch program do. Run: d3d12_translated_draw_test (the VS through -; a D3D12 graphics PSO found by the SHA-256 of its FSSM program). -; -; User data, from the root signature [0] descriptor table, [1] four 32-bit constants (docs/d3d12_vulkan.md 3.5): -; s[0:1] = console VA of the table's first slot: the 16 bytes of a V# (base VA, stride 32, 9 records) -; s2, s3 = the draw's clip-space offset (x, y) as floats; s4, s5 = used by the pixel shader (s4: bias) -; v0 = VertexIndex. The draw has BaseVertex 0 and BaseInstance 0, so v0 is the same with and without the translator's -; zero-based ids (PR 436): both give 0, 1, 2, ... for DrawInstanced(n, 1, 0, 0). A non-zero StartVertexLocation would -; make the two differ (hardware: zero-based, base in an SGPR), so the test never uses one. -; Vertex record, 32 bytes: position xyzw at 0, colour rgba at 16 (both float). -; pos0 = (position.x + s2, position.y + s3, position.z, position.w) -; param0 = colour -; fssm-at: 0x10 -; fssm-data: 0x35314d56 0x20535620 -s_load_dwordx4 s[8:11], s[0:1], 0x0 -s_waitcnt lgkmcnt(0) -buffer_load_dwordx4 v[4:7], v0, s[8:11], 0 idxen -buffer_load_dwordx4 v[8:11], v0, s[8:11], 0 idxen offset:16 -s_waitcnt vmcnt(0) -v_add_f32_e32 v4, s2, v4 -v_add_f32_e32 v5, s3, v5 -exp pos0 v4, v5, v6, v7 done -exp param0 v8, v9, v10, v11 -s_endpgm diff --git a/runtime/test/shaders/vs_m2.asm b/runtime/test/shaders/vs_m2.asm deleted file mode 100644 index 6798c6310..000000000 --- a/runtime/test/shaders/vs_m2.asm +++ /dev/null @@ -1,18 +0,0 @@ -; M2 vertex shader: a quad from the vertex index, no vertex input. Run: d3d12_m2_textured_test (found by the SHA-256 -; of its FSSM program, as vs_m15 is). -; v0 = VertexIndex, 0..3 (the test draws indices 0 1 2 2 1 3 with DrawIndexedInstanced and base vertex 0): -; u = v0 & 1, v = (v0 >> 1) & 1; pos0 = (2u - 1, 1 - 2v, 0, 1) (clip y up: v = 0 is the top row); param0 = (u, v, 0, 1) -; fssm-at: 0x10 -; fssm-data: 0x32534d56 0x20535620 -v_and_b32_e32 v1, 1, v0 -v_and_b32_e32 v2, 2, v0 -v_cvt_f32_u32_e32 v1, v1 -v_cvt_f32_u32_e32 v2, v2 -v_mul_f32_e32 v2, 0.5, v2 -v_fma_f32 v3, v1, 2.0, -1.0 -v_fma_f32 v4, v2, -2.0, 1.0 -v_mov_b32_e32 v5, 0 -v_mov_b32_e32 v6, 1.0 -exp pos0 v3, v4, v5, v6 done -exp param0 v1, v2, v5, v6 -s_endpgm diff --git a/runtime/test/shaders/vs_m3.asm b/runtime/test/shaders/vs_m3.asm deleted file mode 100644 index 3bcc2278e..000000000 --- a/runtime/test/shaders/vs_m3.asm +++ /dev/null @@ -1,27 +0,0 @@ -; M3 vertex shader: a rectangle from the vertex index, placed and set at a depth by root constants. Run: -; d3d12_m3_frame_test (found by the SHA-256 of its FSSM program, as vs_m15 and vs_m2 are). -; User data, from the root signature [0], eight 32-bit constants (floats) = s0..s7: -; s0, s1 = clip-space x, y of the first corner; s2, s3 = x, y of the opposite corner; s4 = depth (clip z) -; s5, s6, s7 = used by the pixel shader -; v0 = VertexIndex, 0..3 (the test draws indices 0 1 2 2 1 3 with DrawIndexedInstanced and base vertex 0): -; u = v0 & 1, v = (v0 >> 1) & 1; pos0 = (x0 + u * (x1 - x0), y0 + v * (y1 - y0), z, 1) -; The corners are multiples of 1/32 and the depths are dyadic, so every operation here is exact however it is fused. -; fssm-at: 0x10 -; fssm-data: 0x33534d56 0x20535620 -v_and_b32_e32 v1, 1, v0 -v_and_b32_e32 v2, 2, v0 -v_cvt_f32_u32_e32 v1, v1 -v_cvt_f32_u32_e32 v2, v2 -v_mul_f32_e32 v2, 0.5, v2 -v_mov_b32_e32 v7, s0 -v_mov_b32_e32 v8, s1 -v_mov_b32_e32 v9, s2 -v_mov_b32_e32 v10, s3 -v_sub_f32_e32 v9, v9, v7 -v_sub_f32_e32 v10, v10, v8 -v_fma_f32 v3, v1, v9, v7 -v_fma_f32 v4, v2, v10, v8 -v_mov_b32_e32 v5, s4 -v_mov_b32_e32 v6, 1.0 -exp pos0 v3, v4, v5, v6 done -s_endpgm diff --git a/runtime/test/shaders/vs_persp.asm b/runtime/test/shaders/vs_persp.asm deleted file mode 100644 index c3ec3461e..000000000 --- a/runtime/test/shaders/vs_persp.asm +++ /dev/null @@ -1,36 +0,0 @@ -; Vertex shader for ps_persp_bary: one triangle with a different clip w per vertex, so interpolation is -; perspective-correct only if it divides by w. Vertex k (VertexIndex v0) lands at screen (5,8), (57,16), (21,55) of -; the 64x64 viewport with clip w = 1, 2, 4, and exports param0 = attr0 = (0.25,-0.5), (2.25,0.75), (-1,3), 0, 1. -; Clip position = ((sx/32 - 1) w, (sy/32 - 1) w, 0, w). Checked by check.py's bary_persp_problem (suggested in #794). -v_mov_b32_e32 v1, 0xbf580000 -v_mov_b32_e32 v2, 0xbf400000 -v_mov_b32_e32 v3, 0x3f800000 -v_mov_b32_e32 v4, 0x3e800000 -v_mov_b32_e32 v5, 0xbf000000 -v_cmp_eq_u32_e32 vcc_lo, 1, v0 -s_mov_b32 s10, 0x3fc80000 -v_cndmask_b32_e64 v1, v1, s10, vcc_lo -s_mov_b32 s10, 0xbf800000 -v_cndmask_b32_e64 v2, v2, s10, vcc_lo -s_mov_b32 s10, 0x40000000 -v_cndmask_b32_e64 v3, v3, s10, vcc_lo -s_mov_b32 s10, 0x40100000 -v_cndmask_b32_e64 v4, v4, s10, vcc_lo -s_mov_b32 s10, 0x3f400000 -v_cndmask_b32_e64 v5, v5, s10, vcc_lo -v_cmp_eq_u32_e32 vcc_lo, 2, v0 -s_mov_b32 s10, 0xbfb00000 -v_cndmask_b32_e64 v1, v1, s10, vcc_lo -s_mov_b32 s10, 0x40380000 -v_cndmask_b32_e64 v2, v2, s10, vcc_lo -s_mov_b32 s10, 0x40800000 -v_cndmask_b32_e64 v3, v3, s10, vcc_lo -s_mov_b32 s10, 0xbf800000 -v_cndmask_b32_e64 v4, v4, s10, vcc_lo -s_mov_b32 s10, 0x40400000 -v_cndmask_b32_e64 v5, v5, s10, vcc_lo -v_mov_b32_e32 v6, 0 -v_mov_b32_e32 v7, 1.0 -exp pos0 v1, v2, v6, v3 done -exp param0 v4, v5, v6, v7 -s_endpgm diff --git a/runtime/test/shaders/vs_w64_a_skip.asm b/runtime/test/shaders/vs_w64_a_skip.asm deleted file mode 100644 index dac0d885e..000000000 --- a/runtime/test/shaders/vs_w64_a_skip.asm +++ /dev/null @@ -1,45 +0,0 @@ -; TEST-251 (SHADER-10 tier A, vertex stage): the skip regions and the loop of ps_w64_a_skip in a wave64 vertex shader, -; without its whole-quad mask (vertex quads are lanes, not pixels). Vertex v (v0 = vertex index) has x = v & 63 and -; y = v >> 6, so every word is a function of v and not of the lane the vertex landed on. It stores (r0, r1, r2, r3) -; to its record at heap 0x1000 + 16 * v through the V# in s[0:3]. -; (1) a skip region behind s_cbranch_execz: only lanes with x % 4 == 1 run it. r0 = x % 4 == 1 ? 7 * y + x : 1000 + x. -; (2) r1 = x % 4 == 1 (the VCC of (1), per lane). -; (3) s_cbranch_vccz over a region that narrows EXEC to that VCC. r2 = 2000 + y + (y % 4 == 2 ? 9 : 0). -; (4) a loop closed by s_cbranch_execnz, no scalar state carried. r3 = x % 4 + 1. -; Run: VKH_VERTICES=960 VKH_SGPRS=0,0,65536,0x30000000 VKH_HEAP=0=0 VKH_HEAP_DUMP=heap.raw vk_harness -; vs_w64_a_skip.spv out.raw, with and without RADV_PERFTEST=gewave32: equal records, and equal -; to the expected words. -; mattr: +wavefrontsize64,-wavefrontsize32 -v_and_b32_e32 v2, 63, v0 -v_lshrrev_b32_e32 v3, 6, v0 -s_mov_b64 s[10:11], exec -v_add_nc_u32_e32 v6, 0x3e8, v2 -v_and_b32_e32 v4, 3, v2 -v_cmp_eq_u32_e32 vcc, 1, v4 -v_cndmask_b32_e64 v7, 0, 1, vcc -s_and_saveexec_b64 s[12:13], vcc -s_cbranch_execz 2 -v_mul_u32_u24_e32 v6, 7, v3 -v_add_nc_u32_e32 v6, v6, v2 -s_or_b64 exec, exec, s[12:13] -v_and_b32_e32 v5, 3, v3 -v_add_nc_u32_e32 v8, 0x7d0, v3 -v_cmp_eq_u32_e32 vcc, 2, v5 -s_cbranch_vccz 3 -s_and_saveexec_b64 s[16:17], vcc -v_add_nc_u32_e32 v8, 9, v8 -s_or_b64 exec, exec, s[16:17] -v_add_nc_u32_e32 v10, 1, v4 -v_mov_b32_e32 v9, 0 -v_add_nc_u32_e32 v9, 1, v9 -v_cmp_lt_u32_e32 vcc, v9, v10 -s_and_b64 exec, exec, vcc -s_cbranch_execnz -4 -s_mov_b64 exec, s[10:11] -v_lshlrev_b32_e32 v12, 4, v0 -v_add_nc_u32_e32 v12, 0x1000, v12 -buffer_store_dwordx4 v[6:9], v12, s[0:3], 0 offen -v_mov_b32_e32 v5, 0 -exp pos0 v5, v5, v5, v5 done -exp param0 v5, v5, v5, v5 -s_endpgm diff --git a/runtime/test/shaders/vs_w64_b_ballot_atomic.asm b/runtime/test/shaders/vs_w64_b_ballot_atomic.asm deleted file mode 100644 index f718c25f8..000000000 --- a/runtime/test/shaders/vs_w64_b_ballot_atomic.asm +++ /dev/null @@ -1,42 +0,0 @@ -; TEST-251 (SHADER-10 tier B, vertex stage): the wave-aggregated atomic of ps_w64_b_ballot_atomic in a wave64 vertex -; shader. Vertex v (v0 = vertex index) has x = v & 63; vertices with x % 4 == 1 are the "wanted" lanes. EXEC = the -; wanted lanes; n = s_bcnt1_i32_b64 exec; rank = v_mbcnt_lo/hi of EXEC; the lane of rank 0 does buffer_atomic_add of n -; to the counter at heap offset 0 and gets the old value back; v_readfirstlane broadcasts it as the base; every wanted -; vertex stores v + 1 at heap offset 0x100 + 4 * (base + rank). Whatever the wave size and the packing, every wanted -; vertex gets a slot of its own and the counter ends at the number of wanted vertices (240 of 960); which vertex gets -; which slot depends on the packing, so the slots are compared as a set. Its record at heap 0x1000 + 16 * v holds -; (x % 4 == 1, 0, 0, 0). -; Run: VKH_VERTICES=960 VKH_SGPRS=0,0,65536,0x30000000 VKH_HEAP=0=0 VKH_HEAP_DUMP=heap.raw vk_harness -; vs_w64_b_ballot_atomic.spv out.raw, with and without RADV_PERFTEST=gewave32. -; mattr: +wavefrontsize64,-wavefrontsize32 -v_and_b32_e32 v2, 63, v0 -v_and_b32_e32 v4, 3, v2 -s_mov_b64 s[10:11], exec -v_cmp_eq_u32_e32 vcc, 1, v4 -v_cndmask_b32_e64 v6, 0, 1, vcc -s_and_saveexec_b64 s[12:13], vcc -s_bcnt1_i32_b64 s6, exec -v_mbcnt_lo_u32_b32 v10, exec_lo, 0 -v_mbcnt_hi_u32_b32 v10, exec_hi, v10 -v_cmp_eq_u32_e32 vcc, 0, v10 -s_and_saveexec_b64 s[14:15], vcc -v_mov_b32_e32 v11, s6 -v_mov_b32_e32 v13, 0 -buffer_atomic_add v11, v13, s[0:3], 0 offen glc -s_or_b64 exec, exec, s[14:15] -v_readfirstlane_b32 s7, v11 -v_add_nc_u32_e32 v13, s7, v10 -v_lshlrev_b32_e32 v13, 2, v13 -v_add_nc_u32_e32 v14, 1, v0 -buffer_store_dword v14, v13, s[0:3], 0 offen offset:256 -s_mov_b64 exec, s[10:11] -v_mov_b32_e32 v7, 0 -v_mov_b32_e32 v8, 0 -v_mov_b32_e32 v9, 0 -v_lshlrev_b32_e32 v12, 4, v0 -v_add_nc_u32_e32 v12, 0x1000, v12 -buffer_store_dwordx4 v[6:9], v12, s[0:3], 0 offen -v_mov_b32_e32 v5, 0 -exp pos0 v5, v5, v5, v5 done -exp param0 v5, v5, v5, v5 -s_endpgm diff --git a/runtime/test/shaders/vs_w64_b_readlane_uniform.asm b/runtime/test/shaders/vs_w64_b_readlane_uniform.asm deleted file mode 100644 index 0fb85008d..000000000 --- a/runtime/test/shaders/vs_w64_b_readlane_uniform.asm +++ /dev/null @@ -1,33 +0,0 @@ -; TEST-251 (SHADER-10 tier B, vertex stage): v_readfirstlane and v_readlane (lanes 40 and 63) of wave-uniform VGPRs -; in a wave64 vertex shader, the vertex twin of ps_w64_b_readfirstlane and ps_w64_b_readlane_uniform. s4 is a user -; SGPR (VKH_SGPRS sets it to 123), copied to a VGPR and read back; so is the constant 77. Every lane holds the same -; value, so the scalar does not depend on which lane is read, on the wave size or on how many vertices a wave got. -; Vertex v (v0 = vertex index) has x = v & 63. r0 = x + 123 (readfirstlane), r1 = 123 + 77 (readlane 40 and 63), -; r2 = x + 123 (readlane 40), r3 = 77 * 2 + 123 (readfirstlane), stored to its record at heap 0x1000 + 16 * v -; through the V# in s[0:3]. -; Run: VKH_VERTICES=960 VKH_SGPRS=0,0,65536,0x30000000,123 VKH_HEAP=0=0 VKH_HEAP_DUMP=heap.raw vk_harness -; vs_w64_b_readlane_uniform.spv out.raw, with and without RADV_PERFTEST=gewave32: equal, and -; equal to the expected words. -; mattr: +wavefrontsize64,-wavefrontsize32 -v_and_b32_e32 v2, 63, v0 -s_mov_b64 s[10:11], exec -v_mov_b32_e32 v5, s4 -v_mov_b32_e32 v4, 77 -v_readfirstlane_b32 s20, v5 -v_add_nc_u32_e32 v6, s20, v2 -v_readlane_b32 s21, v5, 40 -v_readlane_b32 s22, v4, 63 -s_add_u32 s23, s21, s22 -v_mov_b32_e32 v7, s23 -v_add_nc_u32_e32 v8, s21, v2 -v_readfirstlane_b32 s24, v4 -s_lshl_b32 s24, s24, 1 -s_add_u32 s24, s24, s20 -v_mov_b32_e32 v9, s24 -v_lshlrev_b32_e32 v12, 4, v0 -v_add_nc_u32_e32 v12, 0x1000, v12 -buffer_store_dwordx4 v[6:9], v12, s[0:3], 0 offen -v_mov_b32_e32 v5, 0 -exp pos0 v5, v5, v5, v5 done -exp param0 v5, v5, v5, v5 -s_endpgm diff --git a/runtime/test/shaders/vs_w64_b_waterfall.asm b/runtime/test/shaders/vs_w64_b_waterfall.asm deleted file mode 100644 index 814259842..000000000 --- a/runtime/test/shaders/vs_w64_b_waterfall.asm +++ /dev/null @@ -1,35 +0,0 @@ -; TEST-251 (SHADER-10 tier B, vertex stage): the waterfall loop of ps_w64_b_waterfall in a wave64 vertex shader. -; Vertex v (v0 = vertex index) has x = v & 63, y = v >> 6 and the key a = x % 4 + 4 * (y % 4). The loop takes -; v_readfirstlane of the key, runs the lanes holding it (v_cmp_eq, s_and_saveexec), retires them (s_xor exec) and -; repeats while lanes are left (s_cbranch_execnz); the scalar is used only inside the body. It runs once per distinct -; key of the wave or of the 32-lane subgroup, and every vertex ends with r0 = 17 * a + x, r1 = a, r2 = r3 = 0, stored -; to its record at heap 0x1000 + 16 * v through the V# in s[0:3]. -; Run: VKH_VERTICES=960 VKH_SGPRS=0,0,65536,0x30000000 VKH_HEAP=0=0 VKH_HEAP_DUMP=heap.raw vk_harness -; vs_w64_b_waterfall.spv out.raw, with and without RADV_PERFTEST=gewave32: equal, and equal to -; the expected words. -; mattr: +wavefrontsize64,-wavefrontsize32 -v_and_b32_e32 v2, 63, v0 -v_lshrrev_b32_e32 v3, 6, v0 -v_and_b32_e32 v4, 3, v2 -v_and_b32_e32 v5, 3, v3 -v_lshl_add_u32 v4, v5, 2, v4 -v_mov_b32_e32 v6, 0 -s_mov_b64 s[10:11], exec -v_readfirstlane_b32 s20, v4 -v_cmp_eq_u32_e32 vcc, s20, v4 -s_and_saveexec_b64 s[12:13], vcc -s_mul_i32 s21, s20, 17 -v_add_nc_u32_e32 v6, s21, v2 -s_xor_b64 exec, exec, s[12:13] -s_cbranch_execnz -7 -s_mov_b64 exec, s[10:11] -v_mov_b32_e32 v7, v4 -v_mov_b32_e32 v8, 0 -v_mov_b32_e32 v9, 0 -v_lshlrev_b32_e32 v12, 4, v0 -v_add_nc_u32_e32 v12, 0x1000, v12 -buffer_store_dwordx4 v[6:9], v12, s[0:3], 0 offen -v_mov_b32_e32 v5, 0 -exp pos0 v5, v5, v5, v5 done -exp param0 v5, v5, v5, v5 -s_endpgm diff --git a/runtime/test/shaders/vs_w64_c_bcnt_export.asm b/runtime/test/shaders/vs_w64_c_bcnt_export.asm deleted file mode 100644 index 84dd9bf53..000000000 --- a/runtime/test/shaders/vs_w64_c_bcnt_export.asm +++ /dev/null @@ -1,23 +0,0 @@ -; TEST-251 (SHADER-10 tier C, vertex stage): a lane count used as data. Vertex v (v0 = vertex index) has x = v & 63; -; s_bcnt1_i32_b64 counts the lanes of its wave with x % 4 == 1, which depends on the wave size and on how many -; vertices the driver put in the wave. r0 = that count (partition dependent), r1 = x % 4 == 1, r2 = r3 = 0, stored to -; its record at heap 0x1000 + 16 * v through the V# in s[0:3]. -; Run: VKH_VERTICES=960 VKH_SGPRS=0,0,65536,0x30000000 VKH_HEAP=0=0 VKH_HEAP_DUMP=heap.raw vk_harness -; vs_w64_c_bcnt_export.spv out.raw, with and without RADV_PERFTEST=gewave32: r1 equal, r0 -; differs. -; mattr: +wavefrontsize64,-wavefrontsize32 -v_and_b32_e32 v2, 63, v0 -v_and_b32_e32 v4, 3, v2 -v_cmp_eq_u32_e32 vcc, 1, v4 -s_bcnt1_i32_b64 s6, vcc -v_mov_b32_e32 v6, s6 -v_cndmask_b32_e64 v7, 0, 1, vcc -v_mov_b32_e32 v8, 0 -v_mov_b32_e32 v9, 0 -v_lshlrev_b32_e32 v12, 4, v0 -v_add_nc_u32_e32 v12, 0x1000, v12 -buffer_store_dwordx4 v[6:9], v12, s[0:3], 0 offen -v_mov_b32_e32 v5, 0 -exp pos0 v5, v5, v5, v5 done -exp param0 v5, v5, v5, v5 -s_endpgm diff --git a/runtime/test/shaders/vs_w64_c_lane_id.asm b/runtime/test/shaders/vs_w64_c_lane_id.asm deleted file mode 100644 index c69850333..000000000 --- a/runtime/test/shaders/vs_w64_c_lane_id.asm +++ /dev/null @@ -1,21 +0,0 @@ -; TEST-251 (SHADER-10 tier C, vertex stage): the raw lane number (v_mbcnt_lo/hi of -1) used as data. Each vertex v -; (v0 = vertex index) stores (lane id, lane id & 31, v, 0) to its record at heap 0x1000 + 16 * v through the V# in -; s[0:3]. In a wave64 VS some vertices get lanes 32..63; in a wave32 VS none do, so r0 and r1 depend on how the driver -; packed the vertices into waves and r2 does not. w64_graphics.py also uses it as its probe: the largest r0 shows the -; wave size the driver picked (63 by default on RADV GFX12, 31 with RADV_PERFTEST=gewave32). -; Run: VKH_VERTICES=960 VKH_SGPRS=0,0,65536,0x30000000 VKH_HEAP=0=0 VKH_HEAP_DUMP=heap.raw vk_harness -; vs_w64_c_lane_id.spv out.raw, with and without RADV_PERFTEST=gewave32 (the triangles have -; zero area, so nothing is drawn). -; mattr: +wavefrontsize64,-wavefrontsize32 -v_mbcnt_lo_u32_b32 v6, -1, 0 -v_mbcnt_hi_u32_b32 v6, -1, v6 -v_and_b32_e32 v7, 31, v6 -v_mov_b32_e32 v8, v0 -v_mov_b32_e32 v9, 0 -v_lshlrev_b32_e32 v12, 4, v0 -v_add_nc_u32_e32 v12, 0x1000, v12 -buffer_store_dwordx4 v[6:9], v12, s[0:3], 0 offen -v_mov_b32_e32 v5, 0 -exp pos0 v5, v5, v5, v5 done -exp param0 v5, v5, v5, v5 -s_endpgm diff --git a/runtime/test/shaders/vs_w64_c_readlane.asm b/runtime/test/shaders/vs_w64_c_readlane.asm deleted file mode 100644 index d472b1ee5..000000000 --- a/runtime/test/shaders/vs_w64_c_readlane.asm +++ /dev/null @@ -1,23 +0,0 @@ -; TEST-251 (SHADER-10 tier C, vertex stage): v_readlane of a varying value (the vertex index) at lanes 40 and 7. In a -; wave64 VS every lane gets the vertex in hardware lane 40 (or 7) of its wave; in a wave32 VS lane 40 wraps or is -; undefined and lane 7 is the vertex of another wave. Vertex v (v0 = vertex index): r0 = readlane 40, r1 = v, -; r2 = readlane 7 (both partition dependent), r3 = 0, stored to its record at heap 0x1000 + 16 * v through the V# in -; s[0:3]. -; Run: VKH_VERTICES=960 VKH_SGPRS=0,0,65536,0x30000000 VKH_HEAP=0=0 VKH_HEAP_DUMP=heap.raw vk_harness -; vs_w64_c_readlane.spv out.raw, with and without RADV_PERFTEST=gewave32: r1 equal, r2 differs. -; mattr: +wavefrontsize64,-wavefrontsize32 -s_mov_b64 s[10:11], exec -v_mov_b32_e32 v4, v0 -v_readlane_b32 s6, v4, 40 -v_readlane_b32 s7, v4, 7 -v_mov_b32_e32 v6, s6 -v_mov_b32_e32 v7, v4 -v_mov_b32_e32 v8, s7 -v_mov_b32_e32 v9, 0 -v_lshlrev_b32_e32 v12, 4, v0 -v_add_nc_u32_e32 v12, 0x1000, v12 -buffer_store_dwordx4 v[6:9], v12, s[0:3], 0 offen -v_mov_b32_e32 v5, 0 -exp pos0 v5, v5, v5, v5 done -exp param0 v5, v5, v5, v5 -s_endpgm diff --git a/runtime/test/shaders/w64_graphics.py b/runtime/test/shaders/w64_graphics.py deleted file mode 100644 index 649fc4630..000000000 --- a/runtime/test/shaders/w64_graphics.py +++ /dev/null @@ -1,478 +0,0 @@ -"""SHADER-10 GPU checks: wave64 pixel and vertex shaders on 32-lane subgroups (docs/design.md, "Wave64 graphics: -partition invariance"). - - python3 -I runtime/test/shaders/w64_graphics.py [tools dir] [name ...] - -A wave64 pixel shader is exact on 32-wide subgroups when its outputs do not change if the wave is cut into two -32-lane halves. The test draws each ps_w64_* fixture with the fragment stage's required subgroup size set to 64 (one -hardware wave, the reference) and to 32 (the halves) through VKH_SUBGROUP_SIZE of vk_harness, and compares: - - tier A, B both images equal, and equal to the words the fixture's header derives (tier B's atomic compaction - compares the set of stored slots, not their order) - tier C the words the header names differ between the two sizes, which shows the translator's detector is - right to flag the shader (the other words stay equal) - -A device that can require only one size (NVIDIA: 32 only) cannot run the comparison. There the default-size image is -checked against the derived words (tiers A, B), the tier C check is skipped, and two environment variables let a -second device stand in for the missing size: W64G_SAVE_REF= stores the 64-lane run after its available checks -pass, including on devices with 64 as their only size (AMD GCN). W64G_REF= compares every run of the other -device with those files (equal for A and B, different for C). - -A device whose subgroups can be narrower than 32 (Intel: 8..32) and that could not be held to 32 or 64 skips the tier -A and B pixel fixtures: its fragment stage may run fewer live lanes than 32 (Intel UHD 770 reports 32 but runs 16 live -invocations), and tiers A and B assume 32 or 64 live lanes (TEST-433). -A fixture -listed in NEEDS_LIVE_LANES (it reads lanes beyond the first 16) runs where ps_live_width measures that many live lanes -per fragment subgroup and skips, naming the width, where it is less. The measured width is not gl_SubgroupSize: the Intel UHD 770 reports 32 and -runs 16 live lanes (lane ids 0..15), so a read of lane L ^ 16 returns garbage there. - -The vs_w64_* fixtures (TEST-251) are vertex shaders: Vulkan cannot require a vertex subgroup size, so the two sizes -come from RADV, which runs the VS stage as wave64 by default and as wave32 with RADV_PERFTEST=gewave32 (GFX10+). -Each draws 960 vertices with zero area (VKH_VERTICES) and stores four words per vertex to the heap; vs_w64_c_lane_id -doubles as the probe that the wave size really changed, and without RADV only the default-size checks run. RADV packs -62 or 64 vertices into a wave64 and 30 or 32 into a wave32, so the 32-lane run is a repacking, not the two halves of -the 64-lane waves: a stricter test of tiers A and B, which key every word on the vertex index. - -The gs_w64_* fixtures are legacy geometry shaders, switched the same way (gewave32 covers the whole NGG stage). Each is -drawn after vs_ids with VKH_GS, finds its triangle from the vertex number vs_ids passes in TEXCOORD0, and stores four -words per triangle to the heap; gs_w64_c_lane_id is the geometry probe. RADV puts at most 42 GS invocations in a wave64. -""" -import os -import re -import struct -import subprocess -import sys -import tempfile -from pathlib import Path - -EXE = ".exe" if os.name == "nt" else "" -UNSUPPORTED = 77 -W = H = 64 - - -class Skip(str): - """Neither a pass nor a failure.""" - - -def _x(i): - return i % W - - -def _y(i): - return i // W - - -def _a_skip(i): - x, y = _x(i), _y(i) - return (7 * y + x if x % 4 == 1 else 1000 + x, int(x % 4 < 2), 2000 + y + (9 if y % 4 == 2 else 0), x % 4 + 1) - - -def _a_uniform_vote(i): - return (_x(i) + 7, 11, 36, 27) - -CLEAR = 0xBF800000 # the harness clears the target to -1.0f: the words of a pixel no shader wrote - - -def _a_discard(i): - x, y = _x(i), _y(i) - if x < 30 or y >= 50 or (x % 4 == 3 and y % 2 == 1): - return (CLEAR,) * 4 - return (7 * y + x, 1, 2000 + y, x % 4 + 1) - - -def _b_waterfall(i): - x, y = _x(i), _y(i) - a = x % 4 + 4 * (y % 4) - return (17 * a + x, a, 0, 0) - - -def _b_readfirstlane(i): - return (_x(i) + 123, 277, 0, 0) - - -def _b_readlane_uniform(i): - return (_x(i) + 123, 200, 0, 0) - - -def _b_ballot(i): - return (int(_x(i) % 4 == 1), 0, 0, 0) - - -def _c_waterfall_count(i): - x, y = _x(i), _y(i) - return (17 * (x % 8 + 8 * (y % 8)) + x, None, 0, 0) # None: the trip count, partition dependent - - -def _c_bcnt(i): - return (None, int(_x(i) % 4 == 1), 0, 0) - - -def _c_readlane(i): - return (None, _y(i) * W + _x(i), None, 0) # r2 = lane 7 of the wave: also partition dependent - - -def _c_lane_id(i): - return (None, None, _x(i), 0) # r1 = lane id & 31 depends on the lane a pixel got - - -def _c_vote_stale(i): - return (None, int(_x(i) == 0 and _y(i) == 0), 0, 0) - - -def _on(i): - return int(_x(i) == 5 and _y(i) == 7) - - -def _a_one_lane(i): - x, y, on = _x(i), _y(i), _on(i) - return (7777 if on else 1000 + x, 3000 + 11 * on, 4000 + y + 13 * on, x % 4) - - -def _a_permlane(i): - x, y = _x(i), _y(i) - return ((x ^ 1) + 64 * y, x + 64 * (y ^ 1), 64 * y + x, 64 * y + x) - - -def _a_swizzle(i): - x, y = _x(i), _y(i) - return ((x ^ 1) + 64 * (y ^ 1), (x ^ 1) + 64 * y, 64 * y + x, (x & ~1) + 64 * (y & ~1)) - - -def _a_bpermute(i): - x, y = _x(i), _y(i) - return ((x ^ 1) + 64 * y, (x ^ 1) + 64 * (y ^ 1), 64 * y + x, (x & ~1) + 64 * (y | 1)) - - -def _c_vote_else(i): - return (7 if _on(i) else None, _on(i), 0, 0) # r0 of the other pixels: 0 or 5 by the partition - - -def _c_scc_vote(i): - return (1 if _on(i) else None, _on(i), 0, 0) # r0 = SCC of the vote: the wave's or the half's - - -def _c_execz_sgpr(i): - return (7 if _on(i) else None, _on(i), 0, 0) # r0 = s5: 7 only where the active side ran - - -# vs_w64_* fixtures: i is the vertex index, x = i % 64 and y = i // 64 as for a pixel. -def _vs_a_skip(i): - x, y = _x(i), _y(i) - return (7 * y + x if x % 4 == 1 else 1000 + x, int(x % 4 == 1), 2000 + y + (9 if y % 4 == 2 else 0), x % 4 + 1) - - -def _vs_b_readlane_uniform(i): - return (_x(i) + 123, 200, _x(i) + 123, 277) - - -def _vs_c_lane_id(i): - return (None, None, i, 0) # r0, r1 = the lane the vertex got (gs_: the triangle) - - -def _gs_a_ring(i): # gs_w64_* fixtures: i is the triangle - return (i, 3 * i + 1, 77, 0) - - -VS_ENV = {"VKH_SGPRS": "0,0,65536,0x30000000", "VKH_HEAP": "0=0"} -VS_VERTICES = 960 # 15 rows of 64 vertices: several waves at either size, and partial ones -VS_RECORDS = 0x1000 // 4 # heap word of vertex 0's record (4 words per vertex); below it, the atomic's counter and slots -GS_ENV = {"VKH_SGPRS": "0,0,0,0,0,0,65536,0x30000000", "VKH_HEAP": "0=0"} # V# in s[4:7]: the GS entry sets s3 - - -# name -> (tier, expected words per pixel (None = not fixed), environment of the draw) -FIXTURES = { - "ps_w64_a_skip": ("A", _a_skip, {}), - "ps_w64_a_one_lane": ("A", _a_one_lane, {}), - "ps_w64_a_permlane": ("A", _a_permlane, {}), - "ps_w64_a_swizzle": ("A", _a_swizzle, {}), - "ps_w64_a_bpermute": ("A", _a_bpermute, {}), - "ps_w64_a_uniform_vote": ("A", _a_uniform_vote, {"VKH_SGPRS": "0,0,0,0,9"}), - - "ps_w64_a_discard": ("A", _a_discard, {}), - "ps_w64_b_waterfall": ("B", _b_waterfall, {}), - "ps_w64_b_readfirstlane": ("B", _b_readfirstlane, {"VKH_SGPRS": "0,0,0,0,123"}), - "ps_w64_b_readlane_uniform": ("B", _b_readlane_uniform, {"VKH_SGPRS": "0,0,0,0,123"}), - "ps_w64_b_readlane_uniform_lane": ("B", _b_readlane_uniform, {"VKH_SGPRS": "0,0,0,0,123"}), - "ps_w64_b_ballot_atomic": ("B", _b_ballot, {"VKH_SGPRS": "0,0,65536,0x30000000", "VKH_HEAP": "0=0"}), - "ps_w64_c_waterfall_count": ("C", _c_waterfall_count, {}), - "ps_w64_c_bcnt_export": ("C", _c_bcnt, {}), - "ps_w64_c_readlane": ("C", _c_readlane, {}), - "ps_w64_c_lane_id": ("C", _c_lane_id, {}), - "ps_w64_c_vote_stale": ("C", _c_vote_stale, {}), - "ps_w64_c_vote_else": ("C", _c_vote_else, {}), - "ps_w64_c_scc_vote": ("C", _c_scc_vote, {}), - "ps_w64_c_execz_sgpr": ("C", _c_execz_sgpr, {}), - "vs_w64_a_skip": ("A", _vs_a_skip, VS_ENV), - "vs_w64_b_waterfall": ("B", _b_waterfall, VS_ENV), - "vs_w64_b_readlane_uniform": ("B", _vs_b_readlane_uniform, dict(VS_ENV, VKH_SGPRS=VS_ENV["VKH_SGPRS"] + ",123")), - "vs_w64_b_ballot_atomic": ("B", _b_ballot, VS_ENV), - "vs_w64_c_bcnt_export": ("C", _c_bcnt, VS_ENV), - "vs_w64_c_readlane": ("C", _c_readlane, VS_ENV), - "vs_w64_c_lane_id": ("C", _vs_c_lane_id, VS_ENV), - "gs_w64_a_ring": ("A", _gs_a_ring, GS_ENV), - "gs_w64_c_lane_id": ("C", _vs_c_lane_id, GS_ENV), -} - -PROBES = {"vs": "vs_w64_c_lane_id", "gs": "gs_w64_c_lane_id"} # per stage: the largest lane id shows the wave size -_applied = {} - - -def _radv_perftest(size): - """RADV_PERFTEST for a vertex draw at `size`. Vulkan cannot require a vertex subgroup size (requiredSubgroupSizeStages - has no VERTEX on RADV or on the AMD driver), but RADV runs the VS/GS (NGG) stage as wave32 with gewave32 and as - wave64 without it on GFX10+. Other drivers ignore the variable; the probe then finds no change.""" - flags = [f for f in os.environ.get("RADV_PERFTEST", "").split(",") if f and f != "gewave32"] - return ",".join(flags + ["gewave32"] * (size == 32)) - - -def _wave_size(tools, spirv, stage, size, tmp): - """Whether a vertex or geometry draw at `size` really ran at that wave size: the largest lane id of the stage's - probe is 32..63 in a wave64 and below 32 in a wave32. Size 32 also needs size 64 to work, so the draws differ.""" - if (stage, size) not in _applied: - def top(s): - words, problem = _draw_heap(tools, spirv, PROBES[stage], s, tmp) - if words is None and not problem.startswith("unsupported"): - return None, f"{s}-wide {stage} subgroup probe: {problem}" - return (None if words is None else max(w[0] for w in words)), None - lane64, problem = top(64) - if problem: - return False, problem - lane32, problem = top(32) - if problem: - return False, problem - _applied[stage, 64] = lane64 is not None and 32 <= lane64 < 64 - _applied[stage, 32] = _applied[stage, 64] and lane32 is not None and lane32 < 32 - return _applied[stage, size], None - - -def _draw_heap(tools, spirv, name, size, tmp): - """(records, heap) of one vs_/gs_ draw at `size` (None: as the environment says), or (None, message). A vertex - fixture stores one record per vertex; a geometry fixture, drawn after vs_ids, one per triangle.""" - env = dict(os.environ, **FIXTURES[name][2]) - if size: - env["RADV_PERFTEST"] = _radv_perftest(size) - raw, heap = Path(tmp) / f"{name}.{size}.raw", Path(tmp) / f"{name}.{size}.heap" - env.update(VKH_VERTICES=str(VS_VERTICES), VKH_HEAP_DUMP=str(heap)) - env.pop("VKH_SUBGROUP_SIZE", None) - vs, records = os.path.join(spirv, name + ".spv"), VS_VERTICES - if name.startswith("gs_"): - env["VKH_GS"] = vs - vs, records = os.path.join(spirv, "vs_ids.spv"), VS_VERTICES // 3 - # The triangles have zero area (a GS fixture emits no primitive), so no pixel is drawn and any fragment shader does. - cmd = [os.path.join(tools, "vk_harness" + EXE), vs, os.path.join(spirv, "ps_w64_a_skip.spv"), str(raw)] - r = subprocess.run(cmd, capture_output=True, text=True, env=env, timeout=120) - out = r.stdout + r.stderr - if r.returncode == UNSUPPORTED: - return None, "unsupported: " + out.strip().splitlines()[-1] - if r.returncode or not heap.is_file(): - return None, f"exit {r.returncode}: {' | '.join(out.strip().splitlines()[-3:])}" - words = list(struct.unpack("<%dI" % (65536 // 4), heap.read_bytes())) - return [tuple(words[VS_RECORDS + 4 * v:VS_RECORDS + 4 * v + 4]) for v in range(records)], words - - -_device_min = [None] # the smallest subgroup size vk_harness reported for the device - - -# Pixel fixtures that read lanes beyond the first 16 (a half-wave exchange, lane L ^ 16), and how many live lanes per -# fragment subgroup they need. Empty on purpose: every fixture here passes at 16 live lanes (Intel UHD 770). The -# permute fixtures of TEST-319 (ps_w64_a_permlane, _a_swizzle, _a_bpermute) go in as {name: 32}. -NEEDS_LIVE_LANES = {} - - -def live_width(tools, spirv, tmp): - """The most live invocations a fragment subgroup has on this device (ps_live_width.asm: popcount of EXEC over the - frame), or None when the probe could not run. Not gl_SubgroupSize: an Intel iGPU reports 32 and runs 16.""" - raw = Path(tmp) / "live_width.raw" - cmd = [os.path.join(tools, "vk_harness" + EXE), os.path.join(spirv, "vs_ids.spv"), - os.path.join(spirv, "ps_live_width.spv"), str(raw)] - env = dict(os.environ) - env.pop("VKH_SUBGROUP_SIZE", None) - r = subprocess.run(cmd, capture_output=True, text=True, env=env, timeout=120) - if r.returncode or not raw.is_file() or raw.stat().st_size != W * H * 16: - return None - return max(struct.unpack("<%dI" % (W * H * 4), raw.read_bytes())) - - -def draw(tools, spirv, name, size, tmp): - """(words per pixel, heap words or None, applied) of one draw. `applied`: the required size took effect (size - None: no size asked, applied is None). The words are None when the draw failed; then `heap` is the message.""" - tier, expect, extra = FIXTURES[name] - if name.startswith(("vs_", "gs_")): - words, heap = _draw_heap(tools, spirv, name, size, tmp) - if words is None: - return None, heap, None - if size: - applied, problem = _wave_size(tools, spirv, name[:2], size, tmp) - if problem: - return None, problem, None - return words, heap, applied - return words, heap, None - env = dict(os.environ, **extra) - env.pop("VKH_SUBGROUP_SIZE", None) - if size: - env["VKH_SUBGROUP_SIZE"] = str(size) - raw, heap = Path(tmp) / f"{name}.{size}.raw", Path(tmp) / f"{name}.{size}.heap" - if "VKH_HEAP" in extra: - env["VKH_HEAP_DUMP"] = str(heap) - cmd = [os.path.join(tools, "vk_harness" + EXE), os.path.join(spirv, "vs_ids.spv"), os.path.join(spirv, name + ".spv"), - str(raw)] - r = subprocess.run(cmd, capture_output=True, text=True, env=env, timeout=120) - out = r.stdout + r.stderr - if r.returncode == UNSUPPORTED: - return None, "unsupported: " + out.strip().splitlines()[-1], None - if r.returncode or not raw.is_file(): - return None, f"exit {r.returncode}: {' | '.join(out.strip().splitlines()[-3:])}", None - data = raw.read_bytes() - if len(data) != W * H * 16: - return None, f"{len(data)} bytes of pixels, expected {W * H * 16}", None - m = re.search(r"subgroup (\d+)\.\.(\d+)", out) - if m: - _device_min[0] = int(m.group(1)) - applied = None - if size: - applied = f"fragment subgroup size: {size}\n" in out.replace("\r", "") - words = list(struct.iter_unpack("<4I", data)) - words_heap = None - if "VKH_HEAP" in extra: - words_heap = list(struct.unpack("<%dI" % (65536 // 4), heap.read_bytes())) - return words, words_heap, applied - - -def expected_problem(name, words, heap): - """'' when the words (and heap) are what the fixture's header derives, else the first discrepancy.""" - tier, expect, _ = FIXTURES[name] - wrong = [] - for i, w in enumerate(words): - want = expect(i) - if any(g is not None and g != v for g, v in zip(want, w)): - wrong.append((i, w, want)) - if wrong: - i, w, want = wrong[0] - return f"{len(wrong)} of {len(words)} pixels differ from the derived words, first ({_x(i)},{_y(i)}): got {w}, want {want}" - if name.endswith("_b_ballot_atomic"): - want = sorted(i + 1 for i in range(len(words)) if _x(i) % 4 == 1) - n = len(want) - if heap[0] != n: - return f"counter is {heap[0]}, want {n}" - slots = heap[64:64 + n] - if sorted(slots) != want: - return f"slot words are not the {n} wanted pixel numbers once each ({len(set(slots))} distinct)" - end = VS_RECORDS if name.startswith("vs_") else len(heap) # the vertex records follow the slots - if any(heap[64 + n:end]) or any(heap[1:64]): - return "words outside the counter and the slots were written" - return "" - - -def comparable(name, words, heap): - """What two draws of the same fixture must share when the shader is partition invariant.""" - stable = [tuple(0 if g is None else v for g, v in zip(FIXTURES[name][1](i), w)) for i, w in enumerate(words)] - if name.endswith("_b_ballot_atomic"): - return stable, sorted(heap[64:64 + heap[0]]), heap[0] - return stable, None, None - - -def partition_dependent(name, a, b): - """Whether the words the fixture's header names as partition dependent differ between two draws.""" - return any(any(g is None and x != y for g, x, y in zip(FIXTURES[name][1](i), p, q)) - for i, (p, q) in enumerate(zip(a, b))) - - -def check(tools, spirv, name): - """"" when `name` behaves as its tier says on this device, a Skip when the device cannot run the comparison.""" - tier = FIXTURES[name][0] - if not os.path.isfile(os.path.join(spirv, name + ".spv")): - return f"missing {name}.spv" - save, ref = os.environ.get("W64G_SAVE_REF"), os.environ.get("W64G_REF") - with tempfile.TemporaryDirectory(prefix="leonida-w64g-") as tmp: - runs = {} - for size in (64, 32, None): - words, heap, applied = draw(tools, spirv, name, size, tmp) - if words is None: - if heap.startswith("unsupported"): - return Skip("SKIP (" + heap + ")") - return f"{size or 'default'}: {heap}" - if size is None or applied: - runs[size] = (words, heap) - compared = False - # Tiers A and B mean exact on 32 or 64 live lanes. A device whose subgroups can be narrower than 32 (Intel: - # 8..32) and that could not be held to 32 or 64 may run fewer live lanes than it reports (UHD 770: 16 live - # behind a reported 32): reads across them return garbage. - if tier in ("A", "B") and name.startswith("ps_") and 64 not in runs and 32 not in runs \ - and _device_min[0] is not None and _device_min[0] < 32: - return Skip(f"SKIP (the fragment stage may run fewer live lanes than 32 here ({_device_min[0]}..) " - "and 32 or 64 could not be required: tiers A and B assume 32 or 64 live lanes)") - # A fixture that reads a lane beyond the quad or the first 16 (NEEDS_LIVE_LANES) is judged only where the - # measured live width is enough: the stage can report a subgroup size it does not fill (Intel: 32 reported, - # 16 live, so a read of lane L ^ 16 is undefined). A required size (64 or 32 applied) is the device saying - # the lanes are there, so then nothing is measured. - need = NEEDS_LIVE_LANES.get(name) - if need and 64 not in runs and 32 not in runs: - live = live_width(tools, spirv, tmp) - if live is not None and live < need: - return Skip(f"SKIP (the fragment stage has {live} live lanes per subgroup here, measured with " - f"ps_live_width; this fixture needs {need})") - if tier in ("A", "B"): - for size, (words, heap) in runs.items(): - if size is None and len(runs) > 1: - continue # the default draw repeats one of the forced sizes - p = expected_problem(name, words, heap) - if p: - return f"{size or 'default size'}: {p}" - if 64 in runs and 32 in runs and comparable(name, *runs[64]) != comparable(name, *runs[32]): - return "the images at required subgroup size 64 and 32 differ" - elif 64 in runs and 32 in runs: - if comparable(name, *runs[64]) != comparable(name, *runs[32]): - return "a word that must not depend on the partition differs between 64 and 32" - if not partition_dependent(name, runs[64][0], runs[32][0]): - return "tier C but the images at required subgroup size 64 and 32 are equal: the detector is wrong" - compared = True - if ref and (Path(ref) / (name + ".ref64.raw")).is_file(): - data = (Path(ref) / (name + ".ref64.raw")).read_bytes() - ref_words = list(struct.iter_unpack("<4I", data)) - for size, (words, heap) in runs.items(): - if size == 64: - continue - if tier == "C" and comparable(name, ref_words, None) != comparable(name, words, None): - return "a partition-invariant word differs from the 64-lane reference" - if tier == "C": - if comparable(name, ref_words, None) != comparable(name, words, None): - return "a word that must not depend on the partition differs from the 64-lane reference" - if not partition_dependent(name, ref_words, words): - return "tier C but the run equals the 64-lane reference: the detector is wrong" - compared = True - elif not name.endswith("_b_ballot_atomic") and comparable(name, ref_words, None) != comparable(name, words, None): - return "the run differs from the 64-lane reference" - # Save after all available checks. A 64-only device can still supply a tier C reference for another device. - if save and 64 in runs: - Path(save).mkdir(parents=True, exist_ok=True) - (Path(save) / (name + ".ref64.raw")).write_bytes(b"".join(struct.pack("<4I", *w) for w in runs[64][0])) - if tier == "C" and not compared: - return Skip("SKIP (tier C needs a device that can require both 64 and 32, or W64G_REF)") - return "" - - -def main(argv): - if not argv: - sys.exit(__doc__) - spirv = os.path.join(argv[0], "spirv") - tools = argv[1] if len(argv) > 1 and os.path.isdir(argv[1]) else os.path.join(os.path.dirname(__file__), "..", "..", "build") - start = 2 if len(argv) > 1 and os.path.isdir(argv[1]) else 1 - requested = argv[start:] - unknown = [a for a in requested if a not in FIXTURES] - if unknown: - print(f"Unknown fixture name{'s' if len(unknown) > 1 else ''}: {', '.join(unknown)}", file=sys.stderr) - return 1 - names = requested or sorted(FIXTURES) - failed = 0 - for name in names: - try: - problem = check(os.path.abspath(tools), spirv, name) - except subprocess.TimeoutExpired as e: # a hung draw fails this fixture; the rest still run - problem = f"vk_harness timed out after {e.timeout:g} s" - print(f"{name:28} {FIXTURES[name][0]} {'ok' if not problem else problem}") - failed += bool(problem) and not isinstance(problem, Skip) - return 1 if failed else 0 - - -if __name__ == "__main__": - sys.exit(main(sys.argv[1:])) diff --git a/runtime/test/spirv_capability.h b/runtime/test/spirv_capability.h deleted file mode 100644 index db7232197..000000000 --- a/runtime/test/spirv_capability.h +++ /dev/null @@ -1,49 +0,0 @@ -// What a SPIR-V module declares, read before the device is created, so a test tool enables only the optional features -// the module needs and reports 77 (unsupported) when the device lacks one, instead of asking for every feature a -// translated shader might use. rdna2spirv.py lowers buffer addresses to 32-bit pairs (SHADER-423), so most memory -// shaders no longer declare Int64; asking for shaderInt64 regardless made the tools fail on devices without it (Intel -// UHD/Arc) before the shader ran (TEST-468). -#pragma once - -#include -#include -#include -#include - -namespace leonida::vk_test { - -// Capability numbers from spirv/unified1/spirv.h. -inline constexpr std::uint32_t spirv_capability_float64 = 10; -inline constexpr std::uint32_t spirv_capability_int64 = 11; -inline constexpr std::uint32_t spirv_capability_int64_atomics = 12; - -// Whether the module declares capability `cap`. OpCapability instructions (2 words each) come first, right after the -// 5-word header, so the scan stops at the first other instruction. `bytes` may be any length; a partial word is ignored. -inline bool declares_capability(const void* code, std::size_t bytes, std::uint32_t cap) { - const auto* p = static_cast(code); - const std::size_t words = bytes / 4; - auto word = [&](std::size_t i) { - std::uint32_t w; - std::memcpy(&w, p + 4 * i, 4); - return w; - }; - for (std::size_t i = 5; i + 1 < words && word(i) == (2u << 16 | 17u); i += 2) // OpCapability - if (word(i + 1) == cap) return true; - return false; -} - -inline bool declares_capability(const std::vector& spv, std::uint32_t cap) { - return declares_capability(spv.data(), spv.size() * 4, cap); -} - -// 64-bit integer types need shaderInt64: the Int64 capability, or Int64Atomics, which implicitly declares it. -inline bool needs_shader_int64(const void* code, std::size_t bytes) { - return declares_capability(code, bytes, spirv_capability_int64) || - declares_capability(code, bytes, spirv_capability_int64_atomics); -} - -inline bool needs_shader_int64(const std::vector& spv) { - return needs_shader_int64(spv.data(), spv.size() * 4); -} - -} // namespace leonida::vk_test diff --git a/runtime/test/spirv_capability_test.cpp b/runtime/test/spirv_capability_test.cpp deleted file mode 100644 index 37de4ace2..000000000 --- a/runtime/test/spirv_capability_test.cpp +++ /dev/null @@ -1,71 +0,0 @@ -// CPU-only tests for spirv_capability.h, which the standalone GPU tools use to enable shaderInt64 only for modules -// with 64-bit integers (TEST-468). The modules are hand-built word lists; no Vulkan instance or GPU is needed. -#include "spirv_capability.h" - -#include -#include -#include -#include -#include - -namespace { - -int failures = 0; - -void expect(const char* what, bool got, bool want) { - if (got == want) return; - std::fprintf(stderr, "FAIL %s: got %d, expected %d\n", what, got, want); - ++failures; -} - -// A 5-word header, one OpCapability per entry of `caps`, then OpMemoryModel Logical GLSL450. -std::vector module(std::initializer_list caps) { - std::vector w{0x07230203u, 0x00010000u, 0u, 1u, 0u}; - for (std::uint32_t c : caps) { - w.push_back(2u << 16 | 17u); // OpCapability - w.push_back(c); - } - w.push_back(3u << 16 | 14u); // OpMemoryModel - w.push_back(0u); - w.push_back(1u); - return w; -} - -} // namespace - -int main() { - using namespace leonida::vk_test; - constexpr std::uint32_t shader = 1, physical_storage_buffer = 5347; - - // SHADER-423's output: buffer addresses as 32-bit pairs, PhysicalStorageBufferAddresses but no Int64. - expect("address pairs need no shaderInt64", needs_shader_int64(module({shader, physical_storage_buffer})), false); - expect("Int64 needs shaderInt64", needs_shader_int64(module({shader, spirv_capability_int64})), true); - expect("Int64 after other capabilities", needs_shader_int64(module({shader, physical_storage_buffer, 10, 11})), true); - expect("Int64Atomics implicitly declares Int64", needs_shader_int64(module({shader, spirv_capability_int64_atomics})), - true); - // cs_f64_add (vk_compute_test enables shaderFloat64 for it): Float64 without Int64. - const std::vector f64 = module({shader, spirv_capability_float64}); - expect("Float64", declares_capability(f64, spirv_capability_float64), true); - expect("Float64 needs no shaderInt64", needs_shader_int64(f64), false); - - // Only the leading OpCapability run counts: a later word equal to 11 is an operand, not a capability. - std::vector later = module({shader}); - later.push_back(2u << 16 | 17u); - later.push_back(spirv_capability_int64); - expect("a capability after OpMemoryModel is ignored", needs_shader_int64(later), false); - - // A short or empty file (a missing module reads as empty) declares nothing and doesn't read past its end. - expect("empty", needs_shader_int64(std::vector{}), false); - const std::vector truncated{0x07230203u, 0x00010000u, 0u, 1u, 0u, 2u << 16 | 17u}; - expect("truncated OpCapability", needs_shader_int64(truncated), false); - - // The byte form the tools use for std::vector, including a trailing partial word. - const std::vector m = module({shader, spirv_capability_int64}); - std::vector bytes(m.size() * 4 + 3, 0); - std::memcpy(bytes.data(), m.data(), m.size() * 4); - expect("bytes with a partial word", needs_shader_int64(bytes.data(), bytes.size()), true); - - if (failures) return 1; - std::printf("spirv_capability: all checks passed\n"); - return 0; -} diff --git a/runtime/test/spirv_f16_halves_test.cpp b/runtime/test/spirv_f16_halves_test.cpp deleted file mode 100644 index 61604f14a..000000000 --- a/runtime/test/spirv_f16_halves_test.cpp +++ /dev/null @@ -1,424 +0,0 @@ -// Pure-CPU tests for runtime/src/spirv_f16_halves.h (SHADER-378): -// - fast path when PS has no f16_halves or VS already matches all PS half locations; -// - in-place relocation when VS already emits the requested params at different locations; -// - 16-param VS (param0..param15, static halves only for 0..6) paired with a corpus-style PS (raw 0..14, -// f16 on 0, 4, 5, 6, 7): unused static halves demoted to Private, reused halves relocated, missing param 7 -// synthesized with OpLoad + 4x UnpackHalf2x16 + OpStore before OpReturn; -// - PS relocation when a PS half location collides with an unread raw VS output; -// - SPIR-V 1.3 vs 1.4+ OpEntryPoint interface rules for demoted Private variables; -// - clean failure on genuine >30 location budget overflow (leaving input buffers untouched). -// No GPU or game files required. -#include "../src/spirv_f16_halves.h" - -#include -#include -#include -#include -#include -#include - -#define CHECK(cond) do { \ - if (!(cond)) { std::fprintf(stderr, "line %d: %s\n", __LINE__, #cond); return 1; } \ -} while (0) - -namespace { - -using namespace leonida::spirv_detail; - -void append_inst(std::vector& w, std::uint16_t op, std::initializer_list args) { - w.push_back((std::uint32_t(1 + args.size()) << 16) | op); - for (std::uint32_t a : args) w.push_back(a); -} - -void append_inst_vec(std::vector& w, std::uint16_t op, const std::vector& args) { - w.push_back((std::uint32_t(1 + args.size()) << 16) | op); - w.insert(w.end(), args.begin(), args.end()); -} - -// Build a minimal valid Vertex SPIR-V module with `num_raw_params` Output vec4 params (Location 0..num_raw_params-1) -// and optional static f16_halves Output vec4 vars at the given locations. -std::vector build_vs(std::uint32_t version, std::uint32_t num_raw_params, - const std::map>& static_halves) { - // IDs: - // 1 = %void, 2 = %fn, 3 = %float, 4 = %v4float, 5 = %ptr_out_v4, 6 = %null_v4, 7 = %main, 8 = %entry - // 9 = %out_pos (BuiltIn Position) - // 10.. = raw param vars, then static half vars (lo, hi) - std::uint32_t next_id = 10; - std::vector raw_vars; - for (std::uint32_t p = 0; p < num_raw_params; ++p) raw_vars.push_back(next_id++); - std::vector> half_vars; // (var_id, loc) - for (const auto& [param, pair] : static_halves) { - half_vars.push_back({next_id++, pair[0]}); - half_vars.push_back({next_id++, pair[1]}); - } - - std::vector w = {kSpirvMagic, version, 0, next_id, 0}; - append_inst(w, kOpCapability, {1}); // Shader - append_inst(w, kOpMemoryModel, {0, 1}); // Logical GLSL450 - std::vector ep = {kExecModelVertex, 7, 0x6e69616du, 0x00000000u, 9}; // "main\0" - for (std::uint32_t v : raw_vars) ep.push_back(v); - for (const auto& [v, loc] : half_vars) ep.push_back(v); - append_inst_vec(w, kOpEntryPoint, ep); - - append_inst(w, kOpDecorate, {9, 11, 0}); // BuiltIn Position - for (std::uint32_t p = 0; p < num_raw_params; ++p) append_inst(w, kOpDecorate, {raw_vars[p], kDecorationLocation, p}); - for (const auto& [v, loc] : half_vars) append_inst(w, kOpDecorate, {v, kDecorationLocation, loc}); - - append_inst(w, 19, {1}); // OpTypeVoid - append_inst(w, 33, {2, 1}); // OpTypeFunction %void - append_inst(w, kOpTypeFloat, {3, 32}); - append_inst(w, kOpTypeVector, {4, 3, 4}); - append_inst(w, kOpTypePointer, {5, kStorageOutput, 4}); - append_inst(w, kOpConstantNull, {4, 6}); - append_inst(w, kOpVariable, {5, 9, kStorageOutput}); - for (std::uint32_t v : raw_vars) append_inst(w, kOpVariable, {5, v, kStorageOutput}); - for (const auto& [v, loc] : half_vars) append_inst(w, kOpVariable, {5, v, kStorageOutput}); - - append_inst(w, kOpFunction, {1, 7, 0, 2}); - append_inst(w, 248, {8}); // OpLabel - append_inst(w, kOpStore, {9, 6}); - for (std::uint32_t v : raw_vars) append_inst(w, kOpStore, {v, 6}); - for (const auto& [v, loc] : half_vars) append_inst(w, kOpStore, {v, 6}); - append_inst(w, kOpReturn, {}); - append_inst(w, kOpFunctionEnd, {}); - return w; -} - -// Build a minimal valid Fragment SPIR-V module with `raw_in_locs` and `half_in_locs` Input vec4 variables. -std::vector build_ps(std::uint32_t version, const std::vector& raw_in_locs, - const std::map>& f16_halves) { - // 1 = %void, 2 = %fn, 3 = %float, 4 = %v4float, 5 = %ptr_in_v4, 6 = %ptr_out_v4, 7 = %null_v4, 8 = %out0, - // 9 = %main, 10 = %entry - std::uint32_t next_id = 11; - std::vector> in_vars; // (var_id, loc) - for (std::uint32_t loc : raw_in_locs) in_vars.push_back({next_id++, loc}); - for (const auto& [param, pair] : f16_halves) { - in_vars.push_back({next_id++, pair[0]}); - in_vars.push_back({next_id++, pair[1]}); - } - - std::vector w = {kSpirvMagic, version, 0, next_id, 0}; - append_inst(w, kOpCapability, {1}); - append_inst(w, kOpMemoryModel, {0, 1}); - std::vector ep = {kExecModelFragment, 9, 0x6e69616du, 0x00000000u, 8}; - for (const auto& [v, loc] : in_vars) ep.push_back(v); - append_inst_vec(w, kOpEntryPoint, ep); - append_inst(w, kOpExecutionMode, {9, 7}); // OriginUpperLeft - - append_inst(w, kOpDecorate, {8, kDecorationLocation, 0}); - for (const auto& [v, loc] : in_vars) append_inst(w, kOpDecorate, {v, kDecorationLocation, loc}); - - append_inst(w, 19, {1}); - append_inst(w, 33, {2, 1}); - append_inst(w, kOpTypeFloat, {3, 32}); - append_inst(w, kOpTypeVector, {4, 3, 4}); - append_inst(w, kOpTypePointer, {5, kStorageInput, 4}); - append_inst(w, kOpTypePointer, {6, kStorageOutput, 4}); - append_inst(w, kOpConstantNull, {4, 7}); - append_inst(w, kOpVariable, {6, 8, kStorageOutput}); - for (const auto& [v, loc] : in_vars) append_inst(w, kOpVariable, {5, v, kStorageInput}); - - append_inst(w, kOpFunction, {1, 9, 0, 2}); - append_inst(w, 248, {10}); - append_inst(w, kOpStore, {8, 7}); - append_inst(w, kOpReturn, {}); - append_inst(w, kOpFunctionEnd, {}); - return w; -} - -// Verify basic SPIR-V structural invariants: valid section ordering, all IDs < bound, unique Locations per storage. -bool verify_spirv_structure(const std::vector& words, std::uint32_t storage_class, - std::map& out_loc_to_var, int& out_unpack_count, - int& out_private_vars, std::set& out_ep_iface) { - Module mod; - if (!mod.parse(words)) return false; - out_loc_to_var.clear(); - out_unpack_count = 0; - out_private_vars = 0; - out_ep_iface.clear(); - - // Check section order: pre-type -> types/globals -> functions, and every defined type appears before its use. - int section = 0; // 0 = pre-type, 1 = types/globals, 2 = functions - std::set defined_types; - std::map var_storage; - std::uint32_t glsl_id = 0; - for (const Inst& inst : mod.insts) { - if (inst.opcode == kOpExtInstImport && inst.words.size() >= 3 && - decode_literal_string(std::span(inst.words).subspan(2)) == "GLSL.std.450") { - glsl_id = inst.words[1]; - } - if (inst.opcode == kOpEntryPoint) { - const std::size_t s = entry_point_interface_start(inst); - for (std::size_t i = s; i < inst.words.size(); ++i) out_ep_iface.insert(inst.words[i]); - } - if (inst.opcode == kOpFunction) { - section = 2; - } else if (section == 0 && !is_pre_type_opcode(inst.opcode)) { - section = 1; - } else if (section == 1 && is_pre_type_opcode(inst.opcode)) { - return false; // annotation/header appeared after types started - } - if (section == 1) { - if (inst.opcode == 19 || inst.opcode == 33 || inst.opcode == kOpTypeInt || inst.opcode == kOpTypeFloat || - inst.opcode == kOpTypeVector || inst.opcode == kOpTypePointer) { - defined_types.insert(inst.words[1]); - if (inst.words[1] >= mod.header[3]) return false; - } - if (inst.opcode == kOpVariable) { - if (!defined_types.count(inst.words[1])) return false; // pointer type must precede OpVariable - if (inst.words[2] >= mod.header[3]) return false; - var_storage[inst.words[2]] = inst.words[3]; - if (inst.words[3] == kStoragePrivate) ++out_private_vars; - } - } - if (inst.opcode == kOpExtInst && inst.words.size() >= 6 && inst.words[3] == glsl_id && - inst.words[4] == kGlslUnpackHalf2x16) { - ++out_unpack_count; - if (inst.words[2] >= mod.header[3]) return false; - } - } - for (const Inst& inst : mod.insts) { - if (inst.opcode == kOpDecorate && inst.words.size() >= 3) { - const auto it = var_storage.find(inst.words[1]); - const std::uint32_t dec = inst.words[2]; - if (dec == kDecorationLocation && inst.words.size() >= 4) { - if (it != var_storage.end() && it->second == storage_class) { - if (!out_loc_to_var.emplace(inst.words[3], inst.words[1]).second) return false; // duplicate Location - } - } - if (it != var_storage.end() && it->second == kStoragePrivate && - (dec == 13 || dec == 14 || dec == 15 || dec == 16 || dec == 17 || dec == 18 || - dec == kDecorationLocation || dec == 31)) { - return false; // Private cannot carry interface-only decorations (Flat/NoPerspective/Location/Component/...) - } - } - } - return true; -} - -} // namespace - -int main() { - using namespace leonida; - - // 1. Fast path: already matching static f16_halves -> both modules untouched. - { - ShaderEntry vs_e, ps_e; - vs_e.f16_halves = {{0, {28, 29}}, {1, {26, 27}}}; - ps_e.f16_halves = {{0, {28, 29}}}; - auto vs_w = build_vs(0x00010500u, 2, vs_e.f16_halves); - auto ps_w = build_ps(0x00010500u, {0, 1}, ps_e.f16_halves); - const auto vs_orig = vs_w, ps_orig = ps_w; - std::string err; - CHECK(link_f16_halves(vs_w, vs_e, ps_w, ps_e, &err)); - CHECK(vs_w == vs_orig && ps_w == ps_orig); - } - - // 2. Corpus pattern (SHADER-378): 16-param VS (param0..param15, static halves only for 0..6) paired with a PS - // reading raw attrs 0..14 and f16 attrs {0, 4, 5, 6, 7} packed at 20..29. - // Expected: params 1,2,3 demoted to Private (6 Private vars), params 0,4,5,6 relocated, param 7 synthesized - // with 4 UnpackHalf2x16 ops at Locations 20 & 21; PS unchanged. - { - ShaderEntry vs_e, ps_e; - for (std::uint32_t n = 0; n <= 6; ++n) vs_e.f16_halves[n] = {28 - 2 * n, 29 - 2 * n}; - ps_e.f16_halves = {{0, {28, 29}}, {4, {26, 27}}, {5, {24, 25}}, {6, {22, 23}}, {7, {20, 21}}}; - std::vector ps_raw; - for (std::uint32_t a = 0; a < 15; ++a) ps_raw.push_back(a); - - auto vs_w = build_vs(0x00010500u, 16, vs_e.f16_halves); - auto ps_w = build_ps(0x00010500u, ps_raw, ps_e.f16_halves); - const auto ps_orig = ps_w; - std::string err; - CHECK(link_f16_halves(vs_w, vs_e, ps_w, ps_e, &err)); - CHECK(ps_w == ps_orig); // PS locations 20..29 do not collide with VS raw 0..15 - - std::map vs_locs; - int unpacks = 0, privs = 0; - std::set ep_iface; - CHECK(verify_spirv_structure(vs_w, kStorageOutput, vs_locs, unpacks, privs, ep_iface)); - CHECK(privs == 6); // 3 unneeded static half pairs (params 1, 2, 3) demoted to Private - CHECK(unpacks == 4); // 1 missing param (param 7) * 4 vec4 channels - for (std::uint32_t loc = 0; loc < 16; ++loc) CHECK(vs_locs.count(loc) == 1); - for (std::uint32_t loc = 20; loc <= 29; ++loc) { - CHECK(vs_locs.count(loc) == 1); - CHECK(ep_iface.count(vs_locs[loc]) == 1); - } - CHECK(vs_locs.size() == 26); // 16 raw + 10 decoded halves; all <= 29 - CHECK(vs_locs.rbegin()->first == 29); - } - - // 3. PS relocation: VS exports raw param0..param15, PS only read raw attr0..13 so PS placed attr7 at [14, 15] - // (colliding with VS's raw param14/param15). Both VS and PS must relocate attr7 to [28, 29]. - { - ShaderEntry vs_e, ps_e; - ps_e.f16_halves = {{7, {14, 15}}}; - std::vector ps_raw; - for (std::uint32_t a = 0; a < 14; ++a) ps_raw.push_back(a); - - auto vs_w = build_vs(0x00010500u, 16, {}); - auto ps_w = build_ps(0x00010500u, ps_raw, ps_e.f16_halves); - std::string err; - CHECK(link_f16_halves(vs_w, vs_e, ps_w, ps_e, &err)); - - std::map vs_locs, ps_locs; - int vs_unpacks = 0, vs_privs = 0, ps_unpacks = 0, ps_privs = 0; - std::set vs_ep, ps_ep; - CHECK(verify_spirv_structure(vs_w, kStorageOutput, vs_locs, vs_unpacks, vs_privs, vs_ep)); - CHECK(verify_spirv_structure(ps_w, kStorageInput, ps_locs, ps_unpacks, ps_privs, ps_ep)); - CHECK(vs_unpacks == 4); - CHECK(vs_locs.count(28) == 1 && vs_locs.count(29) == 1); - CHECK(ps_locs.count(28) == 1 && ps_locs.count(29) == 1); - CHECK(!ps_locs.count(14) && !ps_locs.count(15)); - } - - // 4. SPIR-V 1.3 OpEntryPoint drops demoted Private variables from interface list (SPIR-V 1.4+ keeps them). - { - ShaderEntry vs_e, ps_e; - vs_e.f16_halves = {{0, {28, 29}}, {1, {26, 27}}}; - ps_e.f16_halves = {{0, {26, 27}}}; // force patching; param 1 is demoted - auto vs_13 = build_vs(0x00010300u, 2, vs_e.f16_halves); - auto ps_13 = build_ps(0x00010300u, {0, 1}, ps_e.f16_halves); - std::string err; - CHECK(link_f16_halves(vs_13, vs_e, ps_13, ps_e, &err)); - std::map locs; - int unpacks = 0, privs = 0; - std::set ep_iface; - CHECK(verify_spirv_structure(vs_13, kStorageOutput, locs, unpacks, privs, ep_iface)); - CHECK(privs == 2); - // Position (9) + 2 raw (10,11) + 2 reused halves (12,13) = 5 interface vars; demoted 14,15 dropped in v1.3. - CHECK(ep_iface.size() == 5); - } - - // 5. Genuine budget overflow (>30 locations needed): returns false, leaves modules unchanged. - { - ShaderEntry vs_e, ps_e; - ps_e.f16_halves = {{0, {28, 29}}}; - auto vs_w = build_vs(0x00010500u, 29, {}); // 29 raw outputs (0..28) -> only location 29 is free (< 2 needed) - auto ps_w = build_ps(0x00010500u, {0}, ps_e.f16_halves); - const auto vs_orig = vs_w, ps_orig = ps_w; - std::string err; - CHECK(!link_f16_halves(vs_w, vs_e, ps_w, ps_e, &err)); - CHECK(!err.empty()); - CHECK(vs_w == vs_orig && ps_w == ps_orig); - } - - // 6. Fast-path top_location enforcement: matching VS/PS static halves above top_location must be relocated (or - // rejected when they do not fit), not silently passed through unchanged. - { - ShaderEntry vs_e, ps_e; - vs_e.f16_halves = {{0, {28, 29}}, {1, {26, 27}}}; - ps_e.f16_halves = {{0, {28, 29}}}; - auto vs_w = build_vs(0x00010500u, 2, vs_e.f16_halves); - auto ps_w = build_ps(0x00010500u, {0, 1}, ps_e.f16_halves); - std::string err; - // 64-component Vulkan minimum limit -> top_location = 14; both VS and PS must relocate param 0 into <= 14 - // and demote unused param 1 (at 26, 27) to Private. - CHECK(link_f16_halves(vs_w, vs_e, ps_w, ps_e, &err, 14)); - std::map vs_locs, ps_locs; - int vs_unpacks = 0, vs_privs = 0, ps_unpacks = 0, ps_privs = 0; - std::set vs_ep, ps_ep; - CHECK(verify_spirv_structure(vs_w, kStorageOutput, vs_locs, vs_unpacks, vs_privs, vs_ep)); - CHECK(verify_spirv_structure(ps_w, kStorageInput, ps_locs, ps_unpacks, ps_privs, ps_ep)); - CHECK(vs_privs == 2); - CHECK(vs_locs.rbegin()->first <= 14); - CHECK(ps_locs.rbegin()->first <= 14); - CHECK(vs_locs.count(13) == 1 && vs_locs.count(14) == 1); - CHECK(ps_locs.count(13) == 1 && ps_locs.count(14) == 1); - } - - // 7. Empty ps_entry.f16_halves with out-of-budget VS static halves: unused VS halves > top_location must be - // demoted to Private instead of returning early and failing pipeline creation on a <124-component device. - { - ShaderEntry vs_e, ps_e; - vs_e.f16_halves = {{0, {28, 29}}}; - auto vs_w = build_vs(0x00010500u, 2, vs_e.f16_halves); - auto ps_w = build_ps(0x00010500u, {0, 1}, {}); - const auto ps_orig = ps_w; - std::string err; - CHECK(link_f16_halves(vs_w, vs_e, ps_w, ps_e, &err, 14)); - CHECK(ps_w == ps_orig); - std::map vs_locs; - int unpacks = 0, privs = 0; - std::set ep_iface; - CHECK(verify_spirv_structure(vs_w, kStorageOutput, vs_locs, unpacks, privs, ep_iface)); - CHECK(privs == 2); - CHECK(vs_locs.size() == 2 && vs_locs.rbegin()->first == 1); - } - - // 8. Unused VS static half colliding with a raw PS input: fast path must not leave the unused VS half at a - // Location the PS reads as a raw input. - { - ShaderEntry vs_e, ps_e; - vs_e.f16_halves = {{0, {28, 29}}, {1, {26, 27}}}; - ps_e.f16_halves = {{0, {28, 29}}}; - auto vs_w = build_vs(0x00010500u, 2, vs_e.f16_halves); - auto ps_w = build_ps(0x00010500u, {0, 1, 26}, ps_e.f16_halves); - std::string err; - CHECK(link_f16_halves(vs_w, vs_e, ps_w, ps_e, &err, 29)); - std::map vs_locs; - int unpacks = 0, privs = 0; - std::set ep_iface; - CHECK(verify_spirv_structure(vs_w, kStorageOutput, vs_locs, unpacks, privs, ep_iface)); - CHECK(privs == 2); - CHECK(!vs_locs.count(26) && !vs_locs.count(27)); - CHECK(vs_locs.count(28) == 1 && vs_locs.count(29) == 1); - } - - // 9. Demoting a static VS half variable strips non-Location interface-only decorations (e.g. Flat, Component) - // so the resulting Private variable remains valid SPIR-V. - { - ShaderEntry vs_e, ps_e; - vs_e.f16_halves = {{0, {28, 29}}, {1, {26, 27}}}; - ps_e.f16_halves = {{0, {26, 27}}}; // forces param 1 (IDs 14, 15) to be demoted to Private - auto vs_w = build_vs(0x00010500u, 2, vs_e.f16_halves); - // Inject OpDecorate 14 Flat and OpDecorate 15 Component 0 right after OpDecorate 15 Location 27. - Module m; - CHECK(m.parse(vs_w)); - std::vector patched; - for (const Inst& inst : m.insts) { - patched.push_back(inst); - if (inst.opcode == kOpDecorate && inst.words.size() >= 4 && inst.words[2] == kDecorationLocation && - inst.words[3] == 27) { - patched.push_back(make_inst(kOpDecorate, {inst.words[1] - 1, 14})); // Flat - patched.push_back(make_inst(kOpDecorate, {inst.words[1], 31, 0})); // Component 0 - } - } - m.insts = std::move(patched); - vs_w = m.serialize(); - - auto ps_w = build_ps(0x00010500u, {0, 1}, ps_e.f16_halves); - std::string err; - CHECK(link_f16_halves(vs_w, vs_e, ps_w, ps_e, &err)); - std::map vs_locs; - int unpacks = 0, privs = 0; - std::set ep_iface; - CHECK(verify_spirv_structure(vs_w, kStorageOutput, vs_locs, unpacks, privs, ep_iface)); - CHECK(privs == 2); - } - - // 10. Device-limit helper f16_half_top_location() and out-of-budget fast-path rejection. - { - CHECK(f16_half_top_location(128, 128) == 29); - CHECK(f16_half_top_location(124, 128) == 29); - CHECK(f16_half_top_location(120, 120) == 28); - CHECK(f16_half_top_location(64, 64) == 14); - CHECK(f16_half_top_location(64, 128) == 14); - CHECK(f16_half_top_location(4, 64) == 0); - - // Matching VS/PS static halves at [28, 29], but 14 raw VS outputs (0..13) leave only location 14 free (< 2): - // must fail cleanly instead of taking the fast path with out-of-range locations. - ShaderEntry vs_e, ps_e; - vs_e.f16_halves = {{0, {28, 29}}}; - ps_e.f16_halves = {{0, {28, 29}}}; - auto vs_w = build_vs(0x00010500u, 14, vs_e.f16_halves); - auto ps_w = build_ps(0x00010500u, {0}, ps_e.f16_halves); - const auto vs_orig = vs_w, ps_orig = ps_w; - std::string err; - CHECK(!link_f16_halves(vs_w, vs_e, ps_w, ps_e, &err, 14)); - CHECK(!err.empty()); - CHECK(vs_w == vs_orig && ps_w == ps_orig); - } - - std::printf("spirv_f16_halves_test: all checks passed\n"); - return 0; -} diff --git a/runtime/test/spirv_stores_test.cpp b/runtime/test/spirv_stores_test.cpp deleted file mode 100644 index 1916d9bc7..000000000 --- a/runtime/test/spirv_stores_test.cpp +++ /dev/null @@ -1,204 +0,0 @@ -// leonida::spirv_declares_writable_storage (src/spirv_stores.h) over hand-built SPIR-V declarations: which modules -// need fragmentStoresAndAtomics / vertexPipelineStoresAndAtomics outside a compute shader. No Vulkan, no GPU, no -// shader files: only the instructions the rule looks at (types, pointers, variables, decorations) after a header. -#include "../src/spirv_stores.h" - -#include -#include -#include - -namespace { - -int failures = 0; - -void check(bool ok, const char* what) { - if (!ok) { - std::fprintf(stderr, "spirv_stores_test: FAILED: %s\n", what); - ++failures; - } -} - -using Words = std::vector; - -Words header() { return {0x07230203, 0x00010600, 0, 100, 0}; } - -void inst(Words& words, std::uint16_t op, std::initializer_list operands) { - words.push_back((static_cast(operands.size() + 1) << 16) | op); - words.insert(words.end(), operands); -} - -// Opcodes and enumerants, from the SPIR-V specification. -constexpr std::uint16_t OpTypeInt = 21, OpTypeImage = 25, OpTypeRuntimeArray = 29, OpTypeStruct = 30, OpTypePointer = 32, - OpTypeArray = 28, OpVariable = 59, OpDecorate = 71, OpMemberDecorate = 72, OpDecorationGroup = 73, - OpGroupDecorate = 74, OpGroupMemberDecorate = 75; -constexpr std::uint32_t Dim2D = 1, DimSubpassData = 6; -constexpr std::uint32_t Block = 2, BufferBlock = 3, NonWritable = 24; -constexpr std::uint32_t UniformConstant = 0, Uniform = 2, StorageBuffer = 12; -// ids -constexpr std::uint32_t uint_t = 1, image_t = 2, array_t = 3, pointer_t = 4, var = 5, struct_t = 6, length_c = 7; - -// %image = OpTypeImage %uint 0 0 0 ; `sampled` 2 is a storage image (or, with SubpassData, an -// input attachment), 1 a sampled one. -Words image_module(std::uint32_t sampled, bool arrayed, bool runtime, bool non_writable, std::uint32_t dim = Dim2D) { - Words w = header(); - if (non_writable) inst(w, OpDecorate, {var, NonWritable}); - inst(w, OpTypeInt, {uint_t, 32, 0}); - inst(w, OpTypeImage, {image_t, uint_t, dim, 0, 0, 0, sampled, dim == DimSubpassData ? 0u : 33u}); - std::uint32_t pointee = image_t; - if (arrayed) { - if (runtime) { - inst(w, OpTypeRuntimeArray, {array_t, image_t}); - } else { - inst(w, OpTypeArray, {array_t, image_t, length_c}); - } - pointee = array_t; - } - inst(w, OpTypePointer, {pointer_t, UniformConstant, pointee}); - inst(w, OpVariable, {pointer_t, var, UniformConstant}); - return w; -} - -// A two-member block in `storage_class`, decorated Block or BufferBlock, with `read_only_members` of its members -// (and optionally the variable itself) NonWritable. -Words buffer_module(std::uint32_t storage_class, std::uint32_t block_decoration, unsigned read_only_members, - bool variable_non_writable) { - Words w = header(); - inst(w, OpDecorate, {struct_t, block_decoration}); - for (std::uint32_t member = 0; member < read_only_members; ++member) - inst(w, OpMemberDecorate, {struct_t, member, NonWritable}); - if (variable_non_writable) inst(w, OpDecorate, {var, NonWritable}); - inst(w, OpTypeInt, {uint_t, 32, 0}); - inst(w, OpTypeStruct, {struct_t, uint_t, uint_t}); - inst(w, OpTypePointer, {pointer_t, storage_class, struct_t}); - inst(w, OpVariable, {pointer_t, var, storage_class}); - return w; -} - -} // namespace - -int main() { - using leonida::spirv_declares_writable_storage; - - // Storage images: the translator's form (no decoration), read-only, and inside arrays, as set 0 declares them. - check(spirv_declares_writable_storage(image_module(2, false, false, false)), "a storage image needs the feature"); - check(!spirv_declares_writable_storage(image_module(2, false, false, true)), "a NonWritable storage image does not"); - check(spirv_declares_writable_storage(image_module(2, true, true, false)), - "a runtime array of storage images needs it"); - check(spirv_declares_writable_storage(image_module(2, true, false, false)), "a sized array of storage images too"); - check(!spirv_declares_writable_storage(image_module(2, true, true, true)), - "a NonWritable array of storage images does not"); - check(!spirv_declares_writable_storage(image_module(1, false, false, false)), "a sampled image does not"); - check(!spirv_declares_writable_storage(image_module(1, true, true, false)), "an array of sampled images does not"); - // An input attachment (subpassInput) is Sampled 2 with Dim SubpassData, and read-only: no feature. - check(!spirv_declares_writable_storage(image_module(2, false, false, false, DimSubpassData)), - "an input attachment does not"); - check(!spirv_declares_writable_storage(image_module(2, true, false, false, DimSubpassData)), - "an array of input attachments does not"); - - // NonWritable through a decoration group (OpDecorationGroup + OpGroupDecorate) counts like a direct one. - { - constexpr std::uint32_t group = 20; - const auto grouped = [&](std::uint32_t target) { - Words w = header(); - inst(w, OpDecorate, {group, NonWritable}); - inst(w, OpDecorationGroup, {group}); - inst(w, OpGroupDecorate, {group, target}); - inst(w, OpTypeInt, {uint_t, 32, 0}); - inst(w, OpTypeImage, {image_t, uint_t, Dim2D, 0, 0, 0, 2, 33}); - inst(w, OpTypePointer, {pointer_t, UniformConstant, image_t}); - inst(w, OpVariable, {pointer_t, var, UniformConstant}); - return w; - }; - check(!spirv_declares_writable_storage(grouped(var)), - "a storage image made NonWritable through a decoration group does not"); - check(spirv_declares_writable_storage(grouped(var + 100)), - "a group that targets another id does not cover the variable"); - } - // And OpGroupMemberDecorate for every member of a storage buffer block. - { - constexpr std::uint32_t group = 20; - Words w = header(); - inst(w, OpDecorate, {group, NonWritable}); - inst(w, OpDecorationGroup, {group}); - inst(w, OpDecorate, {struct_t, Block}); - inst(w, OpGroupMemberDecorate, {group, struct_t, 0, struct_t, 1}); - inst(w, OpTypeInt, {uint_t, 32, 0}); - inst(w, OpTypeStruct, {struct_t, uint_t, uint_t}); - inst(w, OpTypePointer, {pointer_t, StorageBuffer, struct_t}); - inst(w, OpVariable, {pointer_t, var, StorageBuffer}); - check(!spirv_declares_writable_storage(w), "a block whose members are NonWritable through a group does not"); - } - - // Storage buffers: read-only when the variable or every member is. - check(spirv_declares_writable_storage(buffer_module(StorageBuffer, Block, 0, false)), - "a storage buffer block needs the feature"); - check(spirv_declares_writable_storage(buffer_module(StorageBuffer, Block, 1, false)), - "a block with one writable member still needs it"); - // Out-of-range member decorations must not satisfy the count for an undecorated writable member. - { - Words w = header(); - inst(w, OpDecorate, {struct_t, Block}); - inst(w, OpMemberDecorate, {struct_t, 0, NonWritable}); - inst(w, OpMemberDecorate, {struct_t, 5, NonWritable}); - inst(w, OpTypeInt, {uint_t, 32, 0}); - inst(w, OpTypeStruct, {struct_t, uint_t, uint_t}); - inst(w, OpTypePointer, {pointer_t, StorageBuffer, struct_t}); - inst(w, OpVariable, {pointer_t, var, StorageBuffer}); - check(spirv_declares_writable_storage(w), - "an out-of-range OpMemberDecorate cannot hide a writable member"); - } - { - constexpr std::uint32_t group = 20; - Words w = header(); - inst(w, OpDecorate, {group, NonWritable}); - inst(w, OpDecorationGroup, {group}); - inst(w, OpDecorate, {struct_t, Block}); - inst(w, OpGroupMemberDecorate, {group, struct_t, 0, struct_t, 2}); - inst(w, OpTypeInt, {uint_t, 32, 0}); - inst(w, OpTypeStruct, {struct_t, uint_t, uint_t}); - inst(w, OpTypePointer, {pointer_t, StorageBuffer, struct_t}); - inst(w, OpVariable, {pointer_t, var, StorageBuffer}); - check(spirv_declares_writable_storage(w), - "an out-of-range OpGroupMemberDecorate cannot hide a writable member"); - } - check(!spirv_declares_writable_storage(buffer_module(StorageBuffer, Block, 2, false)), - "a block whose members are all NonWritable does not (GLSL `readonly buffer`)"); - check(!spirv_declares_writable_storage(buffer_module(StorageBuffer, Block, 0, true)), - "a NonWritable variable does not (the translator's descriptor map)"); - check(spirv_declares_writable_storage(buffer_module(Uniform, BufferBlock, 0, false)), - "the SPIR-V 1.0 form of a storage buffer (Uniform + BufferBlock) needs it"); - check(!spirv_declares_writable_storage(buffer_module(Uniform, BufferBlock, 2, false)), - "and does not when it is read-only"); - check(!spirv_declares_writable_storage(buffer_module(Uniform, Block, 0, false)), "a uniform buffer does not"); - - // Not a module: nothing to need. - check(!spirv_declares_writable_storage({}), "no words"); - Words bad_magic = image_module(2, false, false, false); - bad_magic[0] = 0; - check(!spirv_declares_writable_storage(bad_magic), "a wrong magic"); - Words truncated = image_module(2, false, false, false); - truncated.pop_back(); // the OpVariable now runs past the end - check(!spirv_declares_writable_storage(truncated), "an instruction that runs past the end"); - Words zero_length = header(); - zero_length.push_back(OpVariable); // word count 0 - check(!spirv_declares_writable_storage(zero_length), "an instruction of length 0"); - check(!spirv_declares_writable_storage(header()), "a header with no instructions"); - // An array type that names itself as its element: the walk through array types stops instead of spinning. - Words self_array = header(); - inst(self_array, OpTypeRuntimeArray, {array_t, array_t}); - inst(self_array, OpTypePointer, {pointer_t, UniformConstant, array_t}); - inst(self_array, OpVariable, {pointer_t, var, UniformConstant}); - check(!spirv_declares_writable_storage(self_array), "a self-referential array type ends, and needs nothing"); - // The same module with a real storage image declared after it is still seen. - Words mixed = self_array; - inst(mixed, OpTypeInt, {uint_t, 32, 0}); - inst(mixed, OpTypeImage, {image_t, uint_t, 1, 0, 0, 0, 2, 33}); - inst(mixed, OpTypePointer, {struct_t, UniformConstant, image_t}); - inst(mixed, OpVariable, {struct_t, length_c, UniformConstant}); - check(spirv_declares_writable_storage(mixed), "a storage image after a malformed array is still found"); - - if (failures) return 1; - std::printf("spirv_stores_test: OK (storage images, arrays of them, storage buffers in both forms, framing, a " - "self-referential array, input attachments, decoration groups)\n"); - return 0; -} diff --git a/runtime/test/startup_trace_test.cpp b/runtime/test/startup_trace_test.cpp deleted file mode 100644 index 336f957eb..000000000 --- a/runtime/test/startup_trace_test.cpp +++ /dev/null @@ -1,296 +0,0 @@ -// Tests for the startup trace (gta6rt --trace FILE, shims/startup_trace.h). -// -// Everything is synthetic: the test writes a small x86-64 DLL image with two imports, one that binds to nothing -// (an unimplemented thunk) and kernel32!OutputDebugStringA (bound to the host), plus three functions in its .text: -// 0x1200 calls the unimplemented import -// 0x1210 calls OutputDebugStringA with the caller's rcx -// 0x1220 reads address 0 (an access violation the test catches) -// The loader maps it with the trace open, the test calls the three functions, closes the trace and checks the lines: -// map, unimplemented_call with the caller as module+RVA, debug_string with the text, exception with the faulting -// RVA and access kind. No game data and no GPU are involved. -// LEONIDA_TEST_DIR names the folder for the image and the trace, as for loader_test; the default is the temp folder. -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include "../shims/shims.h" -#include "../shims/startup_trace.h" -#include "../src/pe_loader.h" - -namespace { - -namespace fs = std::filesystem; - -int g_checks = 0; -int g_failed = 0; - -void check(bool ok, const std::string& what) { - ++g_checks; - std::printf("%s %s\n", ok ? "ok " : "FAIL ", what.c_str()); - if (!ok) ++g_failed; -} - -struct Import { - const char* dll; - const char* name; -}; -const Import kImports[2] = {{"leonida_trace_probe.dll", "TraceProbeMissing"}, {"kernel32.dll", "OutputDebugStringA"}}; -constexpr uint32_t kTextRva = 0x1000; -constexpr uint32_t kCallerBase = kTextRva + 0x200; // caller i at kCallerBase + 0x10 * i -constexpr uint32_t kCallRetOffset = 10; // sub rsp,0x28 (4) + call [rip+disp] (6) -constexpr uint32_t kFaultRva = kTextRva + 0x220; -constexpr const char* kImageName = "trace_image.bin"; -constexpr const char* kDebugText = "leonida trace probe \"quoted\""; -constexpr const char* kAnsiText = "caf\xe9 probe"; // 0xE9: 'é' in code page 1252, never valid alone in UTF-8 - -uint32_t caller_rva(int i) { return kCallerBase + 0x10u * static_cast(i); } -uint32_t return_rva(int i) { return caller_rva(i) + kCallRetOffset; } - -std::vector make_image() { - std::vector b(0x600, 0); - auto* dos = reinterpret_cast(b.data()); - dos->e_magic = IMAGE_DOS_SIGNATURE; - dos->e_lfanew = 0x80; - auto* nt = reinterpret_cast(b.data() + dos->e_lfanew); - nt->Signature = IMAGE_NT_SIGNATURE; - nt->FileHeader.Machine = IMAGE_FILE_MACHINE_AMD64; - nt->FileHeader.NumberOfSections = 1; - nt->FileHeader.SizeOfOptionalHeader = sizeof(IMAGE_OPTIONAL_HEADER64); - nt->FileHeader.Characteristics = IMAGE_FILE_EXECUTABLE_IMAGE | IMAGE_FILE_DLL | IMAGE_FILE_LARGE_ADDRESS_AWARE; - nt->OptionalHeader.Magic = IMAGE_NT_OPTIONAL_HDR64_MAGIC; - nt->OptionalHeader.ImageBase = 0x180000000; - nt->OptionalHeader.SizeOfHeaders = 0x200; - nt->OptionalHeader.SizeOfImage = 0x2000; - nt->OptionalHeader.Subsystem = IMAGE_SUBSYSTEM_WINDOWS_CUI; - nt->OptionalHeader.NumberOfRvaAndSizes = IMAGE_NUMBEROF_DIRECTORY_ENTRIES; // the loader reads no directory past it - auto* sec = IMAGE_FIRST_SECTION(nt); - std::memcpy(sec->Name, ".text", 6); - sec->VirtualAddress = kTextRva; - sec->Misc.VirtualSize = 0x400; - sec->PointerToRawData = 0x200; - sec->SizeOfRawData = 0x400; - sec->Characteristics = IMAGE_SCN_CNT_CODE | IMAGE_SCN_MEM_EXECUTE | IMAGE_SCN_MEM_READ; - - uint8_t* text = b.data() + 0x200; - for (int i = 0; i < 2; ++i) { - const uint32_t name_off = 0x040 + 0x30u * i, lookup_off = 0x0A0 + 0x20u * i, iat_off = 0x0E0 + 0x20u * i, - hint_off = 0x120 + 0x40u * i; - auto* d = reinterpret_cast(text) + i; - d->Name = kTextRva + name_off; - d->OriginalFirstThunk = kTextRva + lookup_off; - d->FirstThunk = kTextRva + iat_off; - std::strcpy(reinterpret_cast(text + name_off), kImports[i].dll); - *reinterpret_cast(text + lookup_off) = kTextRva + hint_off; - std::strcpy(reinterpret_cast(text + hint_off + 2), kImports[i].name); - - const uint8_t code[] = {0x48, 0x83, 0xEC, 0x28, // sub rsp, 0x28 - 0xFF, 0x15, 0, 0, 0, 0, // call [rip + disp32] - 0x48, 0x83, 0xC4, 0x28, // add rsp, 0x28 - 0xC3}; // ret - uint8_t* fn = text + (caller_rva(i) - kTextRva); - std::memcpy(fn, code, sizeof code); - const int32_t disp = static_cast((kTextRva + iat_off) - return_rva(i)); - std::memcpy(fn + 6, &disp, 4); - } - const uint8_t fault[] = {0x48, 0x8B, 0x04, 0x25, 0, 0, 0, 0, // mov rax, [0] - 0xC3}; // ret - std::memcpy(text + (kFaultRva - kTextRva), fault, sizeof fault); - auto& dir = nt->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT]; - dir.VirtualAddress = kTextRva; - dir.Size = 3 * sizeof(IMAGE_IMPORT_DESCRIPTOR); - return b; -} - -fs::path test_dir() { - const char* env = std::getenv("LEONIDA_TEST_DIR"); - fs::path dir = (env && *env ? fs::path(env) : fs::temp_directory_path()) / - ("leonida_startup_trace_" + std::to_string(GetCurrentProcessId())); - fs::create_directories(dir); - return dir; -} - -fs::path write_file(const fs::path& p, const std::vector& bytes) { - std::ofstream out(p, std::ios::binary); - out.write(reinterpret_cast(bytes.data()), static_cast(bytes.size())); - if (!out) throw std::runtime_error("cannot write " + p.string()); - return p; -} - -using VoidFn = uint64_t(__cdecl*)(const char*); - -// Separate function: __try cannot share a frame with objects that have destructors. -bool call_faulting(void* fn) { - __try { - reinterpret_cast(fn)(); - } __except (GetExceptionCode() == EXCEPTION_ACCESS_VIOLATION ? EXCEPTION_EXECUTE_HANDLER - : EXCEPTION_CONTINUE_SEARCH) { - return true; - } - return false; -} - -void raise_bad_dbg_print() { - __try { - ULONG_PTR args[2] = {5, 0x1000}; // invalid string pointer in DBG_PRINTEXCEPTION_C - RaiseException(0x40010006, 0, 2, args); - } __except (EXCEPTION_EXECUTE_HANDLER) { - } -} - -std::string hex_rva(uint32_t rva) { - char b[16]; - std::snprintf(b, sizeof b, "+0x%x", rva); - return b; -} - -std::vector read_lines(const fs::path& p) { - std::ifstream in(p, std::ios::binary); - std::vector lines; - for (std::string l; std::getline(in, l);) lines.push_back(l); - return lines; -} - -const std::string* find_line(const std::vector& lines, const std::string& kind) { - const std::string tag = "\"kind\":\"" + kind + "\""; - for (auto& l : lines) - if (l.find(tag) != std::string::npos) return &l; - return nullptr; -} - -bool has(const std::string* line, const std::string& what) { return line && line->find(what) != std::string::npos; } - -void test_disabled_is_silent() { - check(!rt::startup_trace::enabled(), "trace is off until open()"); - rt::startup_trace::event("never"); // must not crash with no file - check(rt::startup_trace::quote("a\"b\\c\n\x01") == "\"a\\\"b\\\\c\\n\\u0001\"", "JSON string escaping"); -} - -// --trace runs before the loader reads anything, so it must never replace an existing file (an input such as the -// image itself could be named by mistake): open() refuses it with EEXIST and leaves its bytes as they were. -void test_existing_file_is_kept(const fs::path& dir) { - const std::vector bytes = {'M', 'Z', 0x90, 0x00, 'k', 'e', 'e', 'p'}; - const fs::path existing = write_file(dir / "existing_input.bin", bytes); - int error = 0; - check(!rt::startup_trace::open(existing.c_str(), &error), "open() refuses a file that already exists"); - check(error == EEXIST, "the refusal reports EEXIST"); - check(!rt::startup_trace::enabled(), "the trace stays off after a refused open()"); - std::ifstream in(existing, std::ios::binary); - const std::vector after((std::istreambuf_iterator(in)), std::istreambuf_iterator()); - check(after == bytes, "the existing file's bytes survive"); -} - -// What a strict reader expects for OutputDebugStringA text: the ANSI code page converted to UTF-8. -std::string ansi_as_utf8(const char* a) { - const int len = static_cast(std::strlen(a)); - const int chars = MultiByteToWideChar(CP_ACP, 0, a, len, nullptr, 0); - std::wstring w(static_cast(chars), L'\0'); - MultiByteToWideChar(CP_ACP, 0, a, len, w.data(), chars); - const int bytes = WideCharToMultiByte(CP_UTF8, 0, w.data(), chars, nullptr, 0, nullptr, nullptr); - std::string s(static_cast(bytes), '\0'); - WideCharToMultiByte(CP_UTF8, 0, w.data(), chars, s.data(), bytes, nullptr, nullptr); - return s; -} - -bool valid_utf8(const fs::path& p) { - std::ifstream in(p, std::ios::binary); - const std::string all((std::istreambuf_iterator(in)), std::istreambuf_iterator()); - return all.empty() || - MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, all.data(), static_cast(all.size()), nullptr, 0) > 0; -} - -void test_trace(const fs::path& dir) { - const fs::path image = write_file(dir / kImageName, make_image()); - const fs::path trace = dir / "trace.jsonl"; - check(rt::startup_trace::open(trace.c_str()), "open the trace file"); - { - rt::Loader loader(dir); - rt::Module& m = loader.load(image); - reinterpret_cast(m.base + caller_rva(0))(nullptr); // unimplemented import - reinterpret_cast(m.base + caller_rva(0))(nullptr); // second call: no second event - reinterpret_cast(m.base + caller_rva(1))(kDebugText); - reinterpret_cast(m.base + caller_rva(1))(kAnsiText); - raise_bad_dbg_print(); - OutputDebugStringA("after_bad_dbg_print"); - OutputDebugStringW(L"wide probe \u00e9\u4e2d"); // its ANSI fallback must not be a second, lossy line - OutputDebugStringA("after_wide_probe"); - check(call_faulting(m.base + kFaultRva), "the access violation reached the test's handler"); - rt::startup_trace::event("exit", "\"code\":0"); - } - rt::startup_trace::close(); - - const auto lines = read_lines(trace); - const std::string mod = std::string("\"") + kImageName; - check(lines.size() >= 5, "the trace has at least 5 lines (got " + std::to_string(lines.size()) + ")"); - bool all_objects = true; - for (auto& l : lines) all_objects &= !l.empty() && l.front() == '{' && l.back() == '}'; - check(all_objects, "every line is one JSON object"); - check(find_line(lines, "trace_open") == &lines.front(), "trace_open comes first"); - - const std::string* map = find_line(lines, "map"); - check(has(map, "\"module\":" + mod + "\"") && has(map, "\"size\":\"0x2000\""), "map names the image and its size"); - - int unimplemented = 0; - for (auto& l : lines) unimplemented += l.find("\"kind\":\"unimplemented_call\"") != std::string::npos; - const std::string* u = find_line(lines, "unimplemented_call"); - check(unimplemented == 1, "one unimplemented_call for two calls of the same import"); - check(has(u, "\"import\":\"leonida_trace_probe.dll!TraceProbeMissing\""), "unimplemented_call names the import"); - check(has(u, "\"caller\":" + mod + hex_rva(return_rva(0)) + "\""), "unimplemented_call caller is module+RVA"); - - const std::string* d = find_line(lines, "debug_string"); - check(has(d, "\"text\":\"leonida trace probe \\\"quoted\\\"\""), "debug_string carries the escaped text"); - const std::string ansi = "\"text\":\"" + ansi_as_utf8(kAnsiText) + "\""; - bool ansi_found = false; - for (auto& l : lines) ansi_found |= l.find("\"kind\":\"debug_string\"") != std::string::npos && l.find(ansi) != std::string::npos; - check(ansi_found, "an ANSI debug string with a byte above 0x7f is written as UTF-8"); - bool after_bad_found = false; - for (auto& l : lines) - after_bad_found |= - l.find("\"kind\":\"debug_string\"") != std::string::npos && l.find("after_bad_dbg_print") != std::string::npos; - check(after_bad_found, "an SEH fault inside the VEH does not leave in_handler stuck true"); - int wide_lines = 0, wide_utf8 = 0, after_wide = 0; - for (auto& l : lines) { - wide_lines += l.find("wide probe") != std::string::npos; - wide_utf8 += l.find("\"text\":\"wide probe \xc3\xa9\xe4\xb8\xad\"") != std::string::npos; - after_wide += l.find("\"text\":\"after_wide_probe\"") != std::string::npos; - } - check(wide_lines == 1 && wide_utf8 == 1, "OutputDebugStringW gives one debug_string, in UTF-8 (got " + - std::to_string(wide_lines) + ")"); - check(after_wide == 1, "an OutputDebugStringA after it is still logged"); - check(valid_utf8(trace), "the whole trace is valid UTF-8"); - - const std::string* e = find_line(lines, "exception"); - check(has(e, "\"code\":\"0xc0000005\""), "exception code"); - check(has(e, "\"at\":" + mod + hex_rva(kFaultRva) + "\""), "exception address is module+RVA"); - check(has(e, "\"access\":\"read\"") && has(e, "\"address\":\"0x0\""), "access kind and faulting address"); - check(has(e, "\"stack\":[" + mod.substr(0) + hex_rva(kFaultRva)), "stack starts at the faulting instruction"); - - check(find_line(lines, "exit") == &lines.back(), "exit comes last"); -} - -} // namespace - -int wmain() { - try { - const fs::path dir = test_dir(); - test_disabled_is_silent(); - test_existing_file_is_kept(dir); - test_trace(dir); - std::error_code ec; - fs::remove_all(dir, ec); - } catch (const std::exception& e) { - std::printf("FAIL exception: %s\n", e.what()); - ++g_failed; - } - std::printf("%d check(s), %d failed\n", g_checks, g_failed); - return g_failed ? 1 : 0; -} diff --git a/runtime/test/subgroup_size_test.cpp b/runtime/test/subgroup_size_test.cpp deleted file mode 100644 index d20e9e5e1..000000000 --- a/runtime/test/subgroup_size_test.cpp +++ /dev/null @@ -1,266 +0,0 @@ -// The subgroup-size decision of pipeline creation (src/subgroup_size.h) without a GPU: synthetic shader index -// entries against synthetic device properties, and the VkPipelineShaderStageCreateInfo chain that results. -// The devices are the three shapes known so far: -// - AMD, Windows driver (measured on a Radeon 880M, 26.11.2) and current Mesa RADV on GFX10+: sizes 32..64, the -// stages FRAGMENT | COMPUTE | TASK | MESH can be required; -// - NVIDIA: every stage can be required, but the only size is 32; -// - an old RADV: sizes 32..64, COMPUTE only. -// No game data. -#include "../src/subgroup_size.h" - -#include -#include - -#define CHECK(condition) do { \ - if (!(condition)) { \ - std::fprintf(stderr, "line %d: %s\n", __LINE__, #condition); \ - return 1; \ - } \ -} while (0) - -using namespace leonida; - -namespace { - -constexpr VkShaderStageFlags amd_stages = VK_SHADER_STAGE_FRAGMENT_BIT | VK_SHADER_STAGE_COMPUTE_BIT | - VK_SHADER_STAGE_TASK_BIT_EXT | VK_SHADER_STAGE_MESH_BIT_EXT; -constexpr VkShaderStageFlags all_stages = VK_SHADER_STAGE_ALL_GRAPHICS | VK_SHADER_STAGE_COMPUTE_BIT | - VK_SHADER_STAGE_TASK_BIT_EXT | VK_SHADER_STAGE_MESH_BIT_EXT; - -SubgroupSizeCaps amd() { - SubgroupSizeCaps c; - c.subgroup_size_control = c.compute_full_subgroups = true; - c.min_size = 32; - c.max_size = 64; - c.default_size = 64; - c.max_compute_workgroup_subgroups = 16; - c.required_stages = amd_stages; - return c; -} - -SubgroupSizeCaps nvidia() { - SubgroupSizeCaps c; - c.subgroup_size_control = c.compute_full_subgroups = true; - c.min_size = c.max_size = c.default_size = 32; - c.max_compute_workgroup_subgroups = 32; - c.required_stages = all_stages; - return c; -} - -SubgroupSizeCaps old_radv() { - SubgroupSizeCaps c = amd(); - c.required_stages = VK_SHADER_STAGE_COMPUTE_BIT; - return c; -} - -// An index entry as the translator writes it: `wave64` shaders carry subgroup_size 64, the rest 32, and a shader -// translated with --wave64-emulate has no size and a wave64_exchange. -ShaderEntry entry(const char* stage, bool wave64, std::array local = {64, 1, 1}, - bool emulated = false) { - ShaderEntry e; - e.name = std::string(stage) + (wave64 ? "_w64" : "_w32") + (emulated ? "_emu" : ""); - e.stage = stage; - e.wave64 = wave64; - e.subgroup_size = emulated ? 0 : (wave64 ? 64 : 32); - if (emulated) e.wave64_exchange = "workgroup"; - e.local_size = local; - return e; -} - -} // namespace - -int main() { - // --- AMD-like ------------------------------------------------------------------------------------------- - { - const SubgroupSizeCaps caps = amd(); - // Native wave64 compute: 64, plus full subgroups when X is a multiple of 64. - auto r = decide_subgroup_size(entry("cs", true), caps); - CHECK(r.outcome == SubgroupOutcome::required && r.size == 64 && r.wanted == 64); - CHECK(r.stage == VK_SHADER_STAGE_COMPUTE_BIT); - CHECK(r.flags == VK_PIPELINE_SHADER_STAGE_CREATE_REQUIRE_FULL_SUBGROUPS_BIT); - r = decide_subgroup_size(entry("cs", true, {128, 2, 1}), caps); - CHECK(r.size == 64 && (r.flags & VK_PIPELINE_SHADER_STAGE_CREATE_REQUIRE_FULL_SUBGROUPS_BIT)); - // X not a multiple of 64 (32x2): 64 is still required, full subgroups are not (-pNext-02757). - r = decide_subgroup_size(entry("cs", true, {32, 2, 1}), caps); - CHECK(r.outcome == SubgroupOutcome::required && r.size == 64 && r.flags == 0); - r = decide_subgroup_size(entry("cs", true, {96, 1, 1}), caps); - CHECK(r.size == 64 && r.flags == 0); - // A wave32 compute shader on a 32..64 device: 32 (the default is 64 here), full subgroups when X % 32 == 0. - r = decide_subgroup_size(entry("cs", false, {96, 1, 1}), caps); - CHECK(r.outcome == SubgroupOutcome::required && r.size == 32 && - r.flags == VK_PIPELINE_SHADER_STAGE_CREATE_REQUIRE_FULL_SUBGROUPS_BIT); - r = decide_subgroup_size(entry("cs", false, {48, 1, 1}), caps); - CHECK(r.size == 32 && r.flags == 0); - // Pixel shaders can be required on AMD: wave64 gets 64, wave32 gets 32, never a full-subgroups flag. - r = decide_subgroup_size(entry("ps", true), caps); - CHECK(r.outcome == SubgroupOutcome::required && r.size == 64 && r.flags == 0 && - r.stage == VK_SHADER_STAGE_FRAGMENT_BIT); - r = decide_subgroup_size(entry("ps", false), caps); - CHECK(r.outcome == SubgroupOutcome::required && r.size == 32 && r.flags == 0); - // Mesh: wave64 by construction, 64 and no flag (the flag is only asked of compute). - r = decide_subgroup_size(entry("ms", true, {128, 1, 1}), caps); - CHECK(r.outcome == SubgroupOutcome::required && r.size == 64 && r.flags == 0 && - r.stage == VK_SHADER_STAGE_MESH_BIT_EXT); - // Vertex and geometry stages are not in the list: a wave64 VS cannot be given 64, but the default is 64, so it - // works as it is (device_default); there is no emulation for it. - r = decide_subgroup_size(entry("vs", true), caps); - CHECK(r.outcome == SubgroupOutcome::device_default && r.size == 0 && r.wanted == 64); - r = decide_subgroup_size(entry("gs", true), caps); - CHECK(r.outcome == SubgroupOutcome::device_default); - // A wave32 VS on a 64-wide default is wrong too. - r = decide_subgroup_size(entry("vs", false), caps); - CHECK(r.outcome == SubgroupOutcome::unavailable && r.wanted == 32); - // Emulated shaders ask for nothing, whatever the stage. - r = decide_subgroup_size(entry("cs", true, {64, 1, 1}, true), caps); - CHECK(r.outcome == SubgroupOutcome::emulated && r.size == 0 && r.flags == 0); - r = decide_subgroup_size(entry("ms", true, {128, 1, 1}, true), caps); - CHECK(r.outcome == SubgroupOutcome::emulated && r.size == 0 && r.flags == 0); - auto native = entry("cs", true, {64, 1, 1}); - native.wave64_exchange = "halves"; - r = decide_subgroup_size(native, caps); - CHECK(r.outcome == SubgroupOutcome::required && r.size == 64); - } - - // --- NVIDIA-like: 32 only ---------------------------------------------------------------------------------- - { - const SubgroupSizeCaps caps = nvidia(); - // Wave32 is what the device does: nothing to chain, in any stage. - for (const char* stage : {"cs", "ps", "vs", "gs", "ms"}) { - const auto r = decide_subgroup_size(entry(stage, false), caps); - CHECK(r.outcome == SubgroupOutcome::device_fixed && r.size == 0 && r.flags == 0); - } - // Wave64 cannot be had (64 > max): native wave64 is reported in every stage, emulated is fine. - for (const char* stage : {"cs", "ps", "vs", "gs", "ms"}) { - const auto r = decide_subgroup_size(entry(stage, true), caps); - CHECK(r.outcome == SubgroupOutcome::unavailable && r.size == 0 && r.flags == 0 && r.wanted == 64); - } - const auto emulated = decide_subgroup_size(entry("cs", true, {64, 1, 1}, true), caps); - CHECK(emulated.outcome == SubgroupOutcome::emulated && emulated.size == 0); - } - - // --- An old RADV: COMPUTE only ---------------------------------------------------------------------------------- - { - const SubgroupSizeCaps caps = old_radv(); - auto r = decide_subgroup_size(entry("cs", true), caps); - CHECK(r.outcome == SubgroupOutcome::required && r.size == 64 && - r.flags == VK_PIPELINE_SHADER_STAGE_CREATE_REQUIRE_FULL_SUBGROUPS_BIT); - // Pixel shaders cannot be required, and the default is 64: a wave32 PS is wrong, a wave64 PS works as it is - // (device_default: nothing guarantees the default, min != max). - r = decide_subgroup_size(entry("ps", false), caps); - CHECK(r.outcome == SubgroupOutcome::unavailable && r.size == 0); - r = decide_subgroup_size(entry("ps", true), caps); - CHECK(r.outcome == SubgroupOutcome::device_default && r.size == 0); - r = decide_subgroup_size(entry("ms", true, {128, 1, 1}), caps); - CHECK(r.outcome == SubgroupOutcome::device_default); - } - - // --- Feature, limit and index edge cases ------------------------------------------------------------------------- - { - SubgroupSizeCaps caps = amd(); - // computeFullSubgroups off: the size is still required, the flag is not set. - caps.compute_full_subgroups = false; - auto r = decide_subgroup_size(entry("cs", true), caps); - CHECK(r.outcome == SubgroupOutcome::required && r.size == 64 && r.flags == 0); - // subgroupSizeControl not enabled: the chain would break VUID -pNext-02755, so it is not asked for. - caps = amd(); - caps.subgroup_size_control = false; - r = decide_subgroup_size(entry("cs", true), caps); - CHECK(r.outcome == SubgroupOutcome::device_default && r.size == 0 && r.flags == 0); - // The workgroup must fit size * maxComputeWorkgroupSubgroups (-pNext-02756): 1024 > 64 * 8. - caps = amd(); - caps.max_compute_workgroup_subgroups = 8; - r = decide_subgroup_size(entry("cs", true, {1024, 1, 1}), caps); - CHECK(r.outcome == SubgroupOutcome::device_default); - r = decide_subgroup_size(entry("cs", true, {512, 1, 1}), caps); - CHECK(r.outcome == SubgroupOutcome::required && r.size == 64); - r = decide_subgroup_size(entry("cs", true, {16, 8, 8}), caps); // 1024 invocations too - CHECK(r.outcome == SubgroupOutcome::device_default); - // Large dimensions whose 3-way product wraps uint64_t must not bypass maxComputeWorkgroupSubgroups. - r = decide_subgroup_size(entry("cs", true, {0x1000000u, 0x1000000u, 0x10000u}), amd()); - CHECK(r.outcome == SubgroupOutcome::device_default && r.size == 0 && r.flags == 0); - // Zero local_size X (malformed/unknown index entry) must not enable REQUIRE_FULL_SUBGROUPS_BIT. - r = decide_subgroup_size(entry("cs", true, {0, 1, 1}), amd()); - CHECK(r.flags == 0); - // The limit is for compute and mesh; a pixel shader is not subject to it. - r = decide_subgroup_size(entry("ps", true), caps); - CHECK(r.outcome == SubgroupOutcome::required); - // A size that is not a power of two, or outside [min, max], is not chained. - caps = amd(); - ShaderEntry odd = entry("cs", true); - odd.subgroup_size = 48; - CHECK(decide_subgroup_size(odd, caps).outcome == SubgroupOutcome::unavailable); - odd.subgroup_size = 128; - CHECK(decide_subgroup_size(odd, caps).outcome == SubgroupOutcome::unavailable); - odd.subgroup_size = 16; - CHECK(decide_subgroup_size(odd, caps).outcome == SubgroupOutcome::unavailable); - // An entry without subgroup_size (an index from an older translator) follows `wave64`. - ShaderEntry bare = entry("cs", true); - bare.subgroup_size = 0; - CHECK(decide_subgroup_size(bare, amd()).size == 64); - bare.wave64 = false; - CHECK(decide_subgroup_size(bare, amd()).size == 32); - // Device sizes that were never queried: nothing is asked for and nothing is reported. - CHECK(decide_subgroup_size(entry("cs", true), SubgroupSizeCaps{}).outcome == SubgroupOutcome::unknown_device); - // A stage this layer has no pipeline for. - CHECK(decide_subgroup_size(entry("rt", true), amd()).outcome == SubgroupOutcome::unknown_stage); - // A device that only has 64 runs a wave64 shader as it is. - caps = amd(); - caps.min_size = caps.max_size = caps.default_size = 64; - CHECK(decide_subgroup_size(entry("ps", true), caps).outcome == SubgroupOutcome::device_fixed); - CHECK(decide_subgroup_size(entry("ps", false), caps).outcome == SubgroupOutcome::unavailable); - } - - // --- The create-info chain ------------------------------------------------------------------------------------- - { - const SubgroupSizeCaps caps = amd(); - VkPipelineShaderStageRequiredSubgroupSizeCreateInfo storage{}; - VkPipelineShaderStageCreateInfo stage{VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO}; - stage.stage = VK_SHADER_STAGE_COMPUTE_BIT; - apply_subgroup_request(decide_subgroup_size(entry("cs", true), caps), storage, stage); - CHECK(stage.flags == VK_PIPELINE_SHADER_STAGE_CREATE_REQUIRE_FULL_SUBGROUPS_BIT); - CHECK(stage.pNext == &storage); - CHECK(storage.sType == VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_REQUIRED_SUBGROUP_SIZE_CREATE_INFO); - CHECK(storage.requiredSubgroupSize == 64 && storage.pNext == nullptr); - - // It goes in front of what the stage already chains. - VkPipelineShaderStageRequiredSubgroupSizeCreateInfo other{}; - VkPipelineShaderStageCreateInfo chained{VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO}; - chained.pNext = &other; - apply_subgroup_request(decide_subgroup_size(entry("ps", false), caps), storage, chained); - CHECK(chained.pNext == &storage && storage.pNext == &other && storage.requiredSubgroupSize == 32); - CHECK(chained.flags == 0); - - // A request for nothing leaves the stage alone, whatever the reason. - for (const auto& e : {entry("cs", true, {64, 1, 1}, true), entry("vs", true)}) { - VkPipelineShaderStageCreateInfo untouched{VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO}; - VkPipelineShaderStageRequiredSubgroupSizeCreateInfo unused{}; - apply_subgroup_request(decide_subgroup_size(e, caps), unused, untouched); - CHECK(untouched.pNext == nullptr && untouched.flags == 0 && unused.sType == 0); - } - } - - // --- Querying the device ---------------------------------------------------------------------------------------- - { - VkPhysicalDevice device = reinterpret_cast(std::uintptr_t(0x1000)); - VkPhysicalDevice seen = VK_NULL_HANDLE; - const auto fake = [&](VkPhysicalDevice physical, VkPhysicalDeviceProperties2* properties) { - seen = physical; - auto* subgroup = static_cast(properties->pNext); - auto* control = static_cast(subgroup->pNext); - subgroup->subgroupSize = 64; - control->minSubgroupSize = 32; - control->maxSubgroupSize = 64; - control->maxComputeWorkgroupSubgroups = 16; - control->requiredSubgroupSizeStages = amd_stages; - }; - SubgroupSizeCaps caps; - CHECK(query_subgroup_size_caps(fake, device, true, false, caps)); - CHECK(seen == device); - CHECK(caps.default_size == 64 && caps.min_size == 32 && caps.max_size == 64 && - caps.max_compute_workgroup_subgroups == 16 && caps.required_stages == amd_stages); - CHECK(caps.subgroup_size_control && !caps.compute_full_subgroups); - } - - std::printf("subgroup size decision: AMD-like, NVIDIA-like, old RADV, limits, create-info chain and query OK\n"); - return 0; -} diff --git a/runtime/test/test_pe_loader_bounds.cpp b/runtime/test/test_pe_loader_bounds.cpp deleted file mode 100644 index cdb9816f1..000000000 --- a/runtime/test/test_pe_loader_bounds.cpp +++ /dev/null @@ -1,970 +0,0 @@ -#define _CRT_SECURE_NO_WARNINGS - -#include -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#if __has_include("../src/pe_loader.h") -#include "../src/pe_loader.h" -#elif __has_include("pe_loader.h") -#include "pe_loader.h" -#endif - -#include "free_image_base.h" - -#if __has_include("../shims/shims.h") -#include "../shims/shims.h" -#elif __has_include("shims.h") -#include "shims.h" -#endif - -namespace { - -int g_checks = 0; -int g_failures = 0; -unsigned g_file_seq = 0; -std::filesystem::path g_temp_dir; - -void pass(const char* what) { - ++g_checks; - std::printf("PASS %s\n", what); -} - -void fail(const char* what, const std::string& why) { - ++g_checks; - ++g_failures; - std::printf("FAIL %s: %s\n", what, why.c_str()); -} - -void check_condition(bool condition, const char* what, const std::string& why_failed = "") { - if (condition) { - pass(what); - } else { - fail(what, why_failed.empty() ? "condition not met" : why_failed); - } -} - -// --------------------------------------------------------------------------- -// Pure boundary validation logic tests (arithmetic, wrapping, null checks) -// --------------------------------------------------------------------------- - -// Replicating require_range semantics to verify arithmetic wrapping invariants directly -bool check_range_safe(uint64_t rva, uint64_t len, uint32_t image_size) { - if (rva > image_size || len > image_size - rva) { - return false; - } - return true; -} - -// Replicating read_string length and null termination validation directly -bool check_string_null_terminated(const char* buffer, size_t buffer_len) { - return std::memchr(buffer, 0, buffer_len) != nullptr; -} - -void test_range_wrapping_arithmetic() { - std::printf("\n--- Direct Virtual Address Range Wrapping and Boundary Arithmetic ---\n"); - - const uint32_t image_size = 0x2000; - - // Normal valid ranges - check_condition(check_range_safe(0, 0x2000, image_size), - "Range covering entire image [0, 0x2000) is valid"); - check_condition(check_range_safe(0x1000, 0x200, image_size), - "Range [0x1000, 0x1200) inside image is valid"); - check_condition(check_range_safe(0x2000, 0, image_size), - "Zero-length range at exact image end [0x2000, 0x2000) is valid"); - - // Boundary overflow without wrapping - check_condition(!check_range_safe(0x2001, 0, image_size), - "RVA 0x2001 past image size is rejected"); - check_condition(!check_range_safe(0x1000, 0x1001, image_size), - "Range [0x1000, 0x2001) exceeding image size is rejected"); - check_condition(!check_range_safe(0x2000, 1, image_size), - "1-byte range at image end [0x2000, 0x2001) is rejected"); - - // 32-bit integer wrapping cases: - // If evaluated with 32-bit addition (uint32_t)(0xFFFFF000 + 0x2000) == 0x1000 <= 0x2000 - // check_range_safe uses uint64_t and image_size - rva to prevent wrapping bypass. - const uint64_t wrap_rva_32 = 0xFFFFF000ull; - const uint64_t wrap_len_32 = 0x2000ull; - check_condition(!check_range_safe(wrap_rva_32, wrap_len_32, image_size), - "32-bit wrapping RVA 0xFFFFF000 + 0x2000 is rejected by rva > image_size"); - - const uint64_t max_u32 = 0xFFFFFFFFull; - check_condition(!check_range_safe(max_u32, 8, image_size), - "RVA 0xFFFFFFFF with length 8 is rejected"); - check_condition(!check_range_safe(0x1000, max_u32, image_size), - "RVA 0x1000 with length 0xFFFFFFFF is rejected by len > image_size - rva"); - - // 64-bit integer wrapping cases: - // rva + len would overflow 64-bit integer - const uint64_t max_u64 = 0xFFFFFFFFFFFFFFFFull; - check_condition(!check_range_safe(max_u64, 1, image_size), - "RVA 0xFFFFFFFFFFFFFFFF is rejected"); - check_condition(!check_range_safe(0x1000, max_u64, image_size), - "Length 0xFFFFFFFFFFFFFFFF is rejected"); - check_condition(!check_range_safe(max_u64 - 10, 20, image_size), - "64-bit wrapping sum (0xFFFFFFFFFFFFFFF5 + 20) is rejected"); -} - -void test_string_null_termination_direct() { - std::printf("\n--- Direct String Null Termination Validation ---\n"); - - // Valid null-terminated strings - char terminated_early[] = "hello\0world"; - check_condition(check_string_null_terminated(terminated_early, sizeof(terminated_early)), - "String with early null terminator is accepted"); - - char empty_string[] = "\0"; - check_condition(check_string_null_terminated(empty_string, 1), - "Empty null-terminated string at index 0 is accepted"); - - char terminated_at_last_byte[16] = "123456789012345"; - terminated_at_last_byte[15] = '\0'; - check_condition(check_string_null_terminated(terminated_at_last_byte, 16), - "String null-terminated at exact buffer boundary is accepted"); - - // Unterminated strings - char unterminated[16]; - std::memset(unterminated, 'A', sizeof(unterminated)); - check_condition(!check_string_null_terminated(unterminated, sizeof(unterminated)), - "Buffer filled entirely with non-zero bytes is rejected as unterminated"); - - char zero_length_buf[1] = {'X'}; - check_condition(!check_string_null_terminated(zero_length_buf, 0), - "Zero-length buffer scan rejects unterminated string"); -} - -// --------------------------------------------------------------------------- -// Synthetic PE Image Helpers (Zero Game Data) -// --------------------------------------------------------------------------- - -std::vector make_base_image(uint32_t image_size = 0x2000, uint32_t file_size = 0x400) { - std::vector bytes(file_size, 0); - auto* dos = reinterpret_cast(bytes.data()); - dos->e_magic = IMAGE_DOS_SIGNATURE; - dos->e_lfanew = 0x80; - - auto* nt = reinterpret_cast(bytes.data() + dos->e_lfanew); - nt->Signature = IMAGE_NT_SIGNATURE; - nt->FileHeader.Machine = IMAGE_FILE_MACHINE_AMD64; - nt->FileHeader.NumberOfSections = 1; - nt->FileHeader.SizeOfOptionalHeader = sizeof(IMAGE_OPTIONAL_HEADER64); - nt->OptionalHeader.Magic = IMAGE_NT_OPTIONAL_HDR64_MAGIC; - nt->OptionalHeader.ImageBase = leonida_test::free_image_base(0x140000000); - nt->OptionalHeader.AddressOfEntryPoint = 0x1000; - nt->OptionalHeader.SizeOfHeaders = 0x200; - nt->OptionalHeader.SizeOfImage = image_size; - nt->OptionalHeader.Subsystem = IMAGE_SUBSYSTEM_WINDOWS_CUI; - nt->OptionalHeader.NumberOfRvaAndSizes = IMAGE_NUMBEROF_DIRECTORY_ENTRIES; - - auto* sec = IMAGE_FIRST_SECTION(nt); - std::memcpy(sec->Name, ".text", 6); - sec->VirtualAddress = 0x1000; - sec->Misc.VirtualSize = 0x200; - sec->PointerToRawData = 0x200; - sec->SizeOfRawData = 0x200; - sec->Characteristics = IMAGE_SCN_CNT_CODE | IMAGE_SCN_MEM_EXECUTE | IMAGE_SCN_MEM_READ; - - for (size_t i = 0x200; i < file_size && i < 0x400; ++i) { - bytes[i] = static_cast(i & 0xFF); - } - return bytes; -} - -IMAGE_NT_HEADERS64* nt_header_of(std::vector& bytes) { - auto* dos = reinterpret_cast(bytes.data()); - return reinterpret_cast(bytes.data() + dos->e_lfanew); -} - -std::filesystem::path write_temp_image(const std::vector& bytes) { - auto path = g_temp_dir / ("pe_bound_" + std::to_string(++g_file_seq) + ".bin"); - std::ofstream out(path, std::ios::binary); - if (!out) { - throw std::runtime_error("failed to write test fixture to " + path.string()); - } - out.write(reinterpret_cast(bytes.data()), static_cast(bytes.size())); - return path; -} - -bool expect_loader_rejection(const char* test_name, const std::vector& bytes, - const char* expected_err_substring = nullptr) { - auto file_path = write_temp_image(bytes); - try { - rt::Loader loader(g_temp_dir); - loader.load(file_path); - fail(test_name, "expected image rejection, but Loader::load succeeded"); - return false; - } catch (const std::exception& e) { - const std::string msg = e.what(); - if (expected_err_substring && msg.find(expected_err_substring) == std::string::npos) { - fail(test_name, "rejected with unexpected message: '" + msg + - "', expected substring: '" + expected_err_substring + "'"); - return false; - } - pass(test_name); - return true; - } -} - -bool expect_loader_success(const char* test_name, const std::vector& bytes) { - auto file_path = write_temp_image(bytes); - try { - rt::Loader loader(g_temp_dir); - rt::Module& m = loader.load(file_path); - if (!m.base) { - fail(test_name, "module mapped with null base"); - return false; - } - pass(test_name); - return true; - } catch (const std::exception& e) { - fail(test_name, std::string("expected success, but load failed: ") + e.what()); - return false; - } -} - -// --------------------------------------------------------------------------- -// Import Table Null Termination Tests -// --------------------------------------------------------------------------- - -void test_import_table_null_termination() { - std::printf("\n--- Import Table and Descriptor Null Termination Tests ---\n"); - - // Case 1: Import directory table has no terminating null IMAGE_IMPORT_DESCRIPTOR. - // The descriptors run off the end of the image. - { - auto img = make_base_image(0x1200, 0x400); - auto* nt = nt_header_of(img); - auto& dir = nt->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT]; - // Descriptor sits at 0x11EC (20 bytes, ending at 0x1200 == SizeOfImage). - // Next descriptor begins at 0x1200 and runs past image. - dir.VirtualAddress = 0x11EC; - dir.Size = sizeof(IMAGE_IMPORT_DESCRIPTOR) * 2; - - std::fill(img.begin() + 0x200, img.end(), uint8_t{0}); - std::memcpy(img.data() + 0x240, "xmem.dll\0", 9); - - // Put a valid descriptor at file offset 0x3EC (RVA 0x11EC) - auto* d = reinterpret_cast(img.data() + 0x3EC); - d->Name = 0x1040; - d->FirstThunk = 0x1060; - d->OriginalFirstThunk = 0x1060; // points to a zero thunk, so bind_thunks returns immediately - - expect_loader_rejection("Import descriptor list lacking null terminator descriptor", - img, "the import table runs past the image"); - } - - // Case 2: Import lookup thunk table (OriginalFirstThunk) has no terminating null entry. - // Thunks run past the end of the image. - { - auto img = make_base_image(0x1200, 0x400); - auto* nt = nt_header_of(img); - auto& dir = nt->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT]; - dir.VirtualAddress = 0x1000; - dir.Size = sizeof(IMAGE_IMPORT_DESCRIPTOR); - - std::fill(img.begin() + 0x200, img.end(), uint8_t{0}); - auto* d = reinterpret_cast(img.data() + 0x200); - std::memcpy(img.data() + 0x240, "xmem.dll\0", 9); - d->Name = 0x1040; - d->FirstThunk = 0x11F8; // exactly 1 slot before image size 0x1200 - d->OriginalFirstThunk = 0x11F8; - - // Put a non-zero AddressOfData at RVA 0x11F8 (file offset 0x3F8) - auto* thunk = reinterpret_cast(img.data() + 0x3F8); - thunk->u1.AddressOfData = 0x1040; - - expect_loader_rejection("Import lookup table lacking null terminator thunk", - img, "an import lookup table runs past the image"); - } - - // Case 3: Imported DLL name string has no null terminator before image end. - { - auto img = make_base_image(0x1200, 0x400); - auto* nt = nt_header_of(img); - auto& dir = nt->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT]; - dir.VirtualAddress = 0x1000; - dir.Size = sizeof(IMAGE_IMPORT_DESCRIPTOR); - - std::fill(img.begin() + 0x200, img.end(), uint8_t{0}); - auto* d = reinterpret_cast(img.data() + 0x200); - d->Name = 0x11F0; // 16 bytes before image end 0x1200 - d->FirstThunk = 0; - d->OriginalFirstThunk = 0; - - // Fill bytes from 0x11F0 to 0x1200 (file offset 0x3F0..0x3FF) with non-zero characters - std::memset(img.data() + 0x3F0, 'D', 0x10); - - expect_loader_rejection("Imported DLL name missing null terminator within image", - img, "an imported DLL name isn't terminated inside the image"); - } - - // Case 4: Imported function name string (IMAGE_IMPORT_BY_NAME) has no null terminator. - { - auto img = make_base_image(0x1200, 0x400); - auto* nt = nt_header_of(img); - auto& dir = nt->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT]; - dir.VirtualAddress = 0x1000; - dir.Size = sizeof(IMAGE_IMPORT_DESCRIPTOR); - - std::fill(img.begin() + 0x200, img.end(), uint8_t{0}); - auto* d = reinterpret_cast(img.data() + 0x200); - std::memcpy(img.data() + 0x240, "xmem.dll\0", 9); - d->Name = 0x1040; - d->FirstThunk = 0x1080; - d->OriginalFirstThunk = 0x1080; - - // Thunk points to RVA 0x11F0 for IMAGE_IMPORT_BY_NAME - auto* thunk = reinterpret_cast(img.data() + 0x280); - thunk[0].u1.AddressOfData = 0x11F0; - thunk[1].u1.AddressOfData = 0; // thunk table is null-terminated - - // Hint at 0x11F0 (file offset 0x3F0) is 2 bytes; string starts at 0x11F2 (0x3F2) - // Fill 0x3F2..0x3FF (14 bytes) with non-zero characters without null terminator - std::memset(img.data() + 0x3F0, 0, 2); - std::memset(img.data() + 0x3F2, 'F', 0xE); - - expect_loader_rejection("Imported function name missing null terminator within image", - img, "an import name isn't terminated inside the image"); - } - - // Case 5: Delay-import descriptor table lacking null terminator descriptor. - { - auto img = make_base_image(0x1200, 0x400); - auto* nt = nt_header_of(img); - auto& dir = nt->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_DELAY_IMPORT]; - // Descriptor at 0x11DC (32 bytes, ending at 0x11FC < 0x1200). - // Next descriptor at 0x11FC runs past 0x1200. - dir.VirtualAddress = 0x11DC; - dir.Size = sizeof(IMAGE_DELAYLOAD_DESCRIPTOR) * 2; - - std::fill(img.begin() + 0x200, img.end(), uint8_t{0}); - std::memcpy(img.data() + 0x240, "xmem.dll\0", 9); - - auto* d = reinterpret_cast(img.data() + 0x3DC); - d->Attributes.RvaBased = 1; - d->DllNameRVA = 0x1040; - d->ImportAddressTableRVA = 0x1060; - d->ImportNameTableRVA = 0x1060; // points to zero thunk at 0x1060 - - expect_loader_rejection("Delay-import descriptor table lacking null terminator", - img, "the delay-import table runs past the image"); - } - - // Case 6: Delay-imported DLL name string lacking null terminator. - { - auto img = make_base_image(0x1200, 0x400); - auto* nt = nt_header_of(img); - auto& dir = nt->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_DELAY_IMPORT]; - dir.VirtualAddress = 0x1000; - dir.Size = sizeof(IMAGE_DELAYLOAD_DESCRIPTOR); - - std::fill(img.begin() + 0x200, img.end(), uint8_t{0}); - auto* d = reinterpret_cast(img.data() + 0x200); - d->Attributes.RvaBased = 1; - d->ImportAddressTableRVA = 0x1080; - d->DllNameRVA = 0x11F0; - - std::memset(img.data() + 0x3F0, 'Z', 0x10); // no null terminator up to 0x1200 - - expect_loader_rejection("Delay-imported DLL name lacking null terminator", - img, "a delay-imported DLL name isn't terminated inside the image"); - } -} - -// --------------------------------------------------------------------------- -// Virtual Address Range Wrapping and Boundary Tests -// --------------------------------------------------------------------------- - -void test_virtual_address_range_wrapping() { - std::printf("\n--- Virtual Address Range Wrapping and Boundary Validation Tests ---\n"); - - // Case 1: Section VirtualAddress wrapping around 32-bit boundary. - // If VirtualAddress = 0xFFFFF000 and VirtualSize = 0x2000, 32-bit addition wraps to 0x1000. - // The loader must reject this before mapping or copying memory. - { - auto img = make_base_image(0x2000, 0x400); - auto* nt = nt_header_of(img); - auto* sec = IMAGE_FIRST_SECTION(nt); - sec->VirtualAddress = 0xFFFFF000u; - sec->Misc.VirtualSize = 0x2000u; - - expect_loader_rejection("Section VirtualAddress 32-bit wrapping (0xFFFFF000 + 0x2000)", - img, "a section's data runs past the image"); - } - - // Case 2: Section PointerToRawData wrapping around 32-bit boundary. - // PointerToRawData = 0xFFFFFF00 with SizeOfRawData = 0x200. - { - auto img = make_base_image(0x2000, 0x400); - auto* nt = nt_header_of(img); - auto* sec = IMAGE_FIRST_SECTION(nt); - sec->PointerToRawData = 0xFFFFFF00u; - sec->SizeOfRawData = 0x200u; - - expect_loader_rejection("Section PointerToRawData 32-bit overflow reads past file end", - img, "reads past the end of the file"); - } - - // Case 3: Relocation directory VirtualAddress wrapping around 32-bit boundary. - { - auto img = make_base_image(0x2000, 0x400); - auto* nt = nt_header_of(img); - nt->OptionalHeader.ImageBase = 0; // Force relocation - auto& dir = nt->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_BASERELOC]; - dir.VirtualAddress = 0xFFFFFFF0u; - dir.Size = 0x20u; - - expect_loader_rejection("Relocation table directory VirtualAddress 32-bit wrapping", - img, "the relocation table runs past the image"); - } - - // Case 4: Base relocation block entry with offset wrapping past image boundary. - // block->VirtualAddress = 0x1FFC, DIR64 entry writes 8 bytes crossing image size 0x2000. - { - auto img = make_base_image(0x2000, 0x400); - auto* nt = nt_header_of(img); - nt->OptionalHeader.ImageBase = 0; - auto& dir = nt->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_BASERELOC]; - dir.VirtualAddress = 0x1000; - dir.Size = 0x0A; - - auto* block = reinterpret_cast(img.data() + 0x200); - block->VirtualAddress = 0x1FFC; // 0x1FFC + 8 = 0x2004 > 0x2000 - block->SizeOfBlock = 0x0A; - auto* entries = reinterpret_cast(block + 1); - entries[0] = static_cast(IMAGE_REL_BASED_DIR64 << 12); - - expect_loader_rejection("Relocation entry DIR64 wrapping past image end", - img, "a relocation runs past the image"); - } - - // Case 5: Export directory tables with wrapping VirtualAddress pointers. - // AddressOfFunctions, AddressOfNames, AddressOfNameOrdinals wrapping 32-bit space. - { - auto img = make_base_image(0x2000, 0x400); - auto* nt = nt_header_of(img); - auto& dir = nt->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT]; - dir.VirtualAddress = 0x1000; - dir.Size = sizeof(IMAGE_EXPORT_DIRECTORY); - - auto* ed = reinterpret_cast(img.data() + 0x200); - ed->NumberOfFunctions = 10; - ed->AddressOfFunctions = 0xFFFFFF80u; // wraps 32-bit - - expect_loader_rejection("Export AddressOfFunctions wrapping 32-bit space", - img, "the export address table runs past the image"); - } - - // Case 6: Export AddressOfNames wrapping 32-bit space. - { - auto img = make_base_image(0x2000, 0x400); - auto* nt = nt_header_of(img); - auto& dir = nt->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT]; - dir.VirtualAddress = 0x1000; - dir.Size = sizeof(IMAGE_EXPORT_DIRECTORY); - - auto* ed = reinterpret_cast(img.data() + 0x200); - ed->NumberOfFunctions = 1; - ed->AddressOfFunctions = 0x1100; - ed->NumberOfNames = 10; - ed->AddressOfNames = 0xFFFFFFC0u; - - expect_loader_rejection("Export AddressOfNames wrapping 32-bit space", - img, "the export name table runs past the image"); - } - - // Case 7: Export AddressOfNameOrdinals wrapping 32-bit space. - { - auto img = make_base_image(0x2000, 0x400); - auto* nt = nt_header_of(img); - auto& dir = nt->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT]; - dir.VirtualAddress = 0x1000; - dir.Size = sizeof(IMAGE_EXPORT_DIRECTORY); - - auto* ed = reinterpret_cast(img.data() + 0x200); - ed->NumberOfFunctions = 1; - ed->AddressOfFunctions = 0x1100; - ed->NumberOfNames = 10; - ed->AddressOfNames = 0x1120; - ed->AddressOfNameOrdinals = 0xFFFFFFE0u; - - expect_loader_rejection("Export AddressOfNameOrdinals wrapping 32-bit space", - img, "the export ordinal table runs past the image"); - } - - // Case 8: TLS Directory virtual address wrapping. - // StartAddressOfRawData preceding or wrapping. - { - auto img = make_base_image(0x2000, 0x400); - auto* nt = nt_header_of(img); - auto& dir = nt->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_TLS]; - dir.VirtualAddress = 0x1000; - dir.Size = sizeof(IMAGE_TLS_DIRECTORY64); - - auto* tls = reinterpret_cast(img.data() + 0x200); - tls->StartAddressOfRawData = 0x140001100ull; - tls->EndAddressOfRawData = 0x140001000ull; // End precedes start - - expect_loader_rejection("TLS EndAddressOfRawData precedes StartAddressOfRawData", - img, "TLS template end precedes its start"); - } - - // Case 9: TLS total size wrapping 32-bit integer (> 0xFFFFFFFF). - { - auto img = make_base_image(0x2000, 0x400); - auto* nt = nt_header_of(img); - auto& dir = nt->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_TLS]; - dir.VirtualAddress = 0x1000; - dir.Size = sizeof(IMAGE_TLS_DIRECTORY64); - - auto* tls = reinterpret_cast(img.data() + 0x200); - tls->StartAddressOfRawData = 0x140001000ull; - tls->EndAddressOfRawData = 0x140001100ull; // raw = 0x100 - tls->SizeOfZeroFill = 0xFFFFFFFFu; // raw + zero > 0xFFFFFFFF - - expect_loader_rejection("TLS total size 64-bit integer overflow check", - img, "TLS block is too large"); - } - - // Case 10: Exception directory (.pdata) boundary and overlap checks. - // Unwind entry EndAddress past image size. - { - auto img = make_base_image(0x2000, 0x400); - auto* nt = nt_header_of(img); - auto& dir = nt->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXCEPTION]; - dir.VirtualAddress = 0x1000; - dir.Size = sizeof(RUNTIME_FUNCTION); - - auto* fn = reinterpret_cast(img.data() + 0x200); - fn->BeginAddress = 0x1000; - fn->EndAddress = 0x2001; // exceeds m.size 0x2000 - fn->UnwindData = 0x1100; - - expect_loader_rejection("Exception entry EndAddress exceeding image size", - img, "covers code outside the image"); - } - - // Case 11: Exception entries out of order (wrapping / overlap). - { - auto img = make_base_image(0x2000, 0x400); - auto* nt = nt_header_of(img); - auto& dir = nt->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXCEPTION]; - dir.VirtualAddress = 0x1000; - dir.Size = sizeof(RUNTIME_FUNCTION) * 2; - - auto* fn = reinterpret_cast(img.data() + 0x200); - fn[0].BeginAddress = 0x1100; - fn[0].EndAddress = 0x1200; - fn[0].UnwindData = 0x1300; - - fn[1].BeginAddress = 0x1050; // out of order, overlaps fn[0] - fn[1].EndAddress = 0x1150; - fn[1].UnwindData = 0x1300; - - expect_loader_rejection("Exception entries out of order or overlapping", - img, "is out of order or overlaps the one before it"); - } -} - -// --------------------------------------------------------------------------- -// Boundary Stress and Exact Fits -// --------------------------------------------------------------------------- - -void test_boundary_exact_fits() { - std::printf("\n--- Boundary Stress and Exact Fit Scenarios ---\n"); - - // Case 1: Valid image with section filling exactly up to SizeOfImage - { - auto img = make_base_image(0x2000, 0x400); - auto* nt = nt_header_of(img); - auto* sec = IMAGE_FIRST_SECTION(nt); - sec->VirtualAddress = 0x1000; - sec->Misc.VirtualSize = 0x1000; // 0x1000 + 0x1000 == 0x2000 (exact image size) - sec->SizeOfRawData = 0x200; - sec->PointerToRawData = 0x200; - - expect_loader_success("Section ending at exact SizeOfImage boundary maps successfully", img); - } - - // Case 2: Section VirtualAddress + VirtualSize exceeding SizeOfImage by exactly 1 byte - { - auto img = make_base_image(0x2000, 0x400); - auto* nt = nt_header_of(img); - auto* sec = IMAGE_FIRST_SECTION(nt); - sec->VirtualAddress = 0x1000; - sec->Misc.VirtualSize = 0x1001; // 0x1000 + 0x1001 == 0x2001 > 0x2000 - sec->SizeOfRawData = 0x1001; - sec->PointerToRawData = 0x200; - img.resize(0x200 + 0x1001); - - expect_loader_rejection("Section exceeding SizeOfImage by 1 byte is rejected", - img, "a section's data runs past the image"); - } - - // Case 3: Empty string (null at first byte) in imported DLL name is rejected as outside or empty - { - auto img = make_base_image(0x2000, 0x400); - auto* nt = nt_header_of(img); - auto& dir = nt->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT]; - dir.VirtualAddress = 0x1000; - dir.Size = sizeof(IMAGE_IMPORT_DESCRIPTOR); - - std::fill(img.begin() + 0x200, img.end(), uint8_t{0}); - auto* d = reinterpret_cast(img.data() + 0x200); - d->Name = 0x2000; // exactly SizeOfImage: first byte is out of range - - expect_loader_rejection("Imported DLL name starting at exact SizeOfImage is outside image", - img, "an imported DLL name is outside the image"); - } -} - -// HIGHLOW (type 3) relocations: a 32-bit absolute address, which the x64 Windows loader applies too. The image -// prefers base 0x10000, the lowest address VirtualAlloc hands out; the test holds that address so the loader has to -// map the image higher, which makes the delta positive. The relocation table sits at the start of .text (RVA 0x1000) -// and fixes up the dword at RVA 0x1100. -std::vector make_highlow_image(uint32_t stored, uint16_t type = IMAGE_REL_BASED_HIGHLOW, - uint64_t image_base = 0x10000) { - auto img = make_base_image(0x2000, 0x400); - std::fill(img.begin() + 0x200, img.end(), uint8_t{0}); - auto* nt = nt_header_of(img); - nt->OptionalHeader.ImageBase = image_base; - auto& dir = nt->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_BASERELOC]; - dir.VirtualAddress = 0x1000; - dir.Size = sizeof(IMAGE_BASE_RELOCATION) + 2 * sizeof(uint16_t); - auto* block = reinterpret_cast(img.data() + 0x200); - block->VirtualAddress = 0x1000; - block->SizeOfBlock = dir.Size; - auto* entries = reinterpret_cast(block + 1); - entries[0] = static_cast((type << 12) | 0x100); - entries[1] = static_cast(IMAGE_REL_BASED_ABSOLUTE << 12); // padding, as linkers write it - std::memcpy(img.data() + 0x300, &stored, sizeof(stored)); // RVA 0x1100 - return img; -} - -void test_highlow_relocations() { - std::printf("\n--- HIGHLOW (32-bit) base relocations ---\n"); - // Hold the preferred base. If something else already holds it, the image is relocated all the same. - void* hold = VirtualAlloc(reinterpret_cast(0x10000), 0x2000, MEM_RESERVE, PAGE_NOACCESS); - - // Case 1: the dword names RVA 0x1100 of an image at 0x10000. After the move it must name RVA 0x1100 of the new - // base when that fits in 32 bits; otherwise the load must be refused rather than truncated. - { - auto file_path = write_temp_image(make_highlow_image(0x10000 + 0x1100)); - try { - rt::Loader loader(g_temp_dir); - rt::Module& m = loader.load(file_path); - const uint64_t want = reinterpret_cast(m.base) + 0x1100; - check_condition(m.relocated, "HIGHLOW image was relocated away from its held base"); - check_condition(want <= 0xFFFFFFFFull, "HIGHLOW image mapped low enough for a 32-bit address", - "mapped at " + std::to_string(reinterpret_cast(m.base)) + " yet accepted"); - uint32_t got = 0; - std::memcpy(&got, m.base + 0x1100, sizeof(got)); - check_condition(got == static_cast(want), "HIGHLOW dword now names RVA 0x1100 of the new base", - "got " + std::to_string(got) + ", want " + std::to_string(want)); - } catch (const std::exception& e) { - const std::string msg = e.what(); - // Only acceptable when the new base is too high for the 32-bit address. - check_condition(msg.find("does not fit at this base") != std::string::npos, - "HIGHLOW image mapped above 4 GiB is refused with the 32-bit message", "threw: " + msg); - } - } - - // Case 2: a dword near the top of the 32-bit range overflows for any base above 0x10000: refused, not wrapped. - expect_loader_rejection("HIGHLOW relocation past 4 GiB is refused, not truncated", make_highlow_image(0xFFFFFFF0u), - "does not fit at this base"); - - // Case 3: other 32-bit forms (HIGH, type 1) are still refused by name. - expect_loader_rejection("HIGH (type 1) relocation is still unsupported", - make_highlow_image(0, IMAGE_REL_BASED_HIGH), "unsupported relocation type 1"); - - // Case 4: the fix-up itself, whatever the address space looks like. The preferred base is a region this test - // holds, so the image lands elsewhere but usually near it; the delta is then small, and a dword in the middle of - // the 32-bit range must move by exactly that delta. (A delta too large for it must be refused, as in case 2.) - if (void* near_hold = VirtualAlloc(nullptr, 0x2000, MEM_RESERVE, PAGE_NOACCESS)) { - const uint64_t preferred = reinterpret_cast(near_hold); - constexpr uint32_t stored = 0x80000000u; - auto file_path = write_temp_image(make_highlow_image(stored, IMAGE_REL_BASED_HIGHLOW, preferred)); - try { - rt::Loader loader(g_temp_dir); - rt::Module& m = loader.load(file_path); - const int64_t delta = static_cast(reinterpret_cast(m.base) - preferred); - const int64_t want = static_cast(stored) + delta; - uint32_t got = 0; - std::memcpy(&got, m.base + 0x1100, sizeof(got)); - check_condition(m.relocated && want >= 0 && want <= 0xFFFFFFFFll, - "HIGHLOW fix-up: relocated by a delta that fits", "delta " + std::to_string(delta)); - check_condition(got == static_cast(want), "HIGHLOW fix-up: the dword moved by exactly the delta", - "got " + std::to_string(got) + ", want " + std::to_string(want) + ", delta " + - std::to_string(delta)); - } catch (const std::exception& e) { - const std::string msg = e.what(); - check_condition(msg.find("does not fit at this base") != std::string::npos, - "HIGHLOW fix-up: only a too-large delta is refused", "threw: " + msg); - } - VirtualFree(near_hold, 0, MEM_RELEASE); - } - - if (hold) VirtualFree(hold, 0, MEM_RELEASE); -} - -// PE/COFF spec, optional header: NumberOfRvaAndSizes is "the number of data-directory entries in the remainder of -// the optional header". Entries past it are not directories, whatever bytes they hold. -void test_directory_count() { - std::printf("\n--- NumberOfRvaAndSizes bounds the data directories ---\n"); - auto img = make_base_image(0x2000, 0x400); - auto* nt = nt_header_of(img); - nt->OptionalHeader.NumberOfRvaAndSizes = IMAGE_DIRECTORY_ENTRY_IMPORT; // only the export entry is a directory - nt->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT] = {0xFFFFF000u, sizeof(IMAGE_IMPORT_DESCRIPTOR)}; - nt->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_DELAY_IMPORT] = {0xFFFFF000u, 0x20}; - expect_loader_success("Stale entries past NumberOfRvaAndSizes are not read as directories", img); -} - -// A forwarder "kernel32.#65537" names an ordinal no export table can hold (ordinals are 16 bits). It must not be -// truncated to ordinal 1 and bound to whatever kernel32 exports there. -void test_forwarder_ordinal_range() { - std::printf("\n--- Forwarder ordinal range ---\n"); - auto dll = make_base_image(0x2000, 0x400); - std::fill(dll.begin() + 0x200, dll.end(), uint8_t{0}); - auto* dnt = nt_header_of(dll); - dnt->OptionalHeader.ImageBase = leonida_test::free_image_base(0x150000000ull); - dnt->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT] = {0x1000, 0x100}; - auto* ed = reinterpret_cast(dll.data() + 0x200); // RVA 0x1000 - ed->Base = 1; - ed->NumberOfFunctions = 1; - ed->NumberOfNames = 1; - ed->AddressOfFunctions = 0x1040; - ed->AddressOfNames = 0x1050; - ed->AddressOfNameOrdinals = 0x1060; - const uint32_t forwarder_rva = 0x1080, name_rva = 0x10C0; - std::memcpy(dll.data() + 0x240, &forwarder_rva, 4); - std::memcpy(dll.data() + 0x250, &name_rva, 4); - std::memcpy(dll.data() + 0x280, "kernel32.#65537", 16); - std::memcpy(dll.data() + 0x2C0, "F", 2); - { - std::ofstream out(g_temp_dir / "fwd_ord.dll", std::ios::binary); - out.write(reinterpret_cast(dll.data()), static_cast(dll.size())); - } - - auto exe = make_base_image(0x2000, 0x400); - std::fill(exe.begin() + 0x200, exe.end(), uint8_t{0}); - auto* ent = nt_header_of(exe); - ent->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT] = {0x1000, 2 * sizeof(IMAGE_IMPORT_DESCRIPTOR)}; - auto* d = reinterpret_cast(exe.data() + 0x200); - d->OriginalFirstThunk = 0x1040; - d->Name = 0x1080; - d->FirstThunk = 0x1060; - const uint64_t hint_name = 0x1090; - std::memcpy(exe.data() + 0x240, &hint_name, 8); - std::memcpy(exe.data() + 0x260, &hint_name, 8); - std::memcpy(exe.data() + 0x280, "fwd_ord.dll", 12); - std::memcpy(exe.data() + 0x292, "F", 2); // after the 2-byte hint - - auto path = write_temp_image(exe); - try { - rt::Loader loader(g_temp_dir); - rt::Module& m = loader.load(path); - const bool one = m.imports.size() == 1; - check_condition(one && m.imports[0].binding == rt::Binding::Unimplemented, - "Forwarder to ordinal 65537 is not truncated to a host ordinal", - one ? "bound as " + std::to_string(static_cast(m.imports[0].binding)) - : std::to_string(m.imports.size()) + " imports"); - } catch (const std::exception& e) { - fail("Forwarder to ordinal 65537 is not truncated to a host ordinal", e.what()); - } -} - -void test_headers_and_reloc_tail_bounds() { - std::printf("\n--- Headers vs SizeOfHeaders and Truncated Relocation Block Header ---\n"); - - // 1. e_lfanew + sizeof(IMAGE_NT_HEADERS64) > SizeOfImage with SizeOfHeaders < e_lfanew. - // Previously passed map_image() checks and crashed dereferencing m->base + e_lfanew. - { - std::vector bytes(0x2000, 0); - auto* dos = reinterpret_cast(bytes.data()); - dos->e_magic = IMAGE_DOS_SIGNATURE; - dos->e_lfanew = 0x1000; - auto* nt = reinterpret_cast(bytes.data() + dos->e_lfanew); - nt->Signature = IMAGE_NT_SIGNATURE; - nt->FileHeader.Machine = IMAGE_FILE_MACHINE_AMD64; - nt->FileHeader.NumberOfSections = 0; - nt->FileHeader.SizeOfOptionalHeader = sizeof(IMAGE_OPTIONAL_HEADER64); - nt->OptionalHeader.Magic = IMAGE_NT_OPTIONAL_HDR64_MAGIC; - nt->OptionalHeader.ImageBase = 0x140000000ull; - nt->OptionalHeader.SectionAlignment = 0x1000; - nt->OptionalHeader.FileAlignment = 0x200; - nt->OptionalHeader.SizeOfImage = 0x1000; - nt->OptionalHeader.SizeOfHeaders = 0x200; - nt->OptionalHeader.NumberOfRvaAndSizes = IMAGE_NUMBEROF_DIRECTORY_ENTRIES; - - auto path = write_temp_image(bytes); - bool threw = false; - try { - rt::Loader loader(g_temp_dir); - loader.load(path); - } catch (const std::runtime_error&) { - threw = true; - } - check_condition(threw, "NT headers past SizeOfHeaders/SizeOfImage are rejected cleanly"); - } - - // 2. SizeOfHeaders covers NT headers but truncates the section table. - { - auto bytes = make_base_image(0x2000, 0x400); - auto* nt = nt_header_of(bytes); - // e_lfanew(0x80) + sizeof(IMAGE_NT_HEADERS64)(0x108) = 0x188; section header ends at 0x1B0. - nt->OptionalHeader.SizeOfHeaders = 0x190; - auto path = write_temp_image(bytes); - bool threw = false; - try { - rt::Loader loader(g_temp_dir); - loader.load(path); - } catch (const std::runtime_error&) { - threw = true; - } - check_condition(threw, "Section table extending past SizeOfHeaders is rejected cleanly"); - } - - // 3. Relocation directory with < 8 bytes remaining at the exact end of SizeOfImage (forced relocation). - { - void* occupied = VirtualAlloc(nullptr, 0x2000, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE); - check_condition(occupied != nullptr, "Reserved preferred base for truncated reloc test"); - if (occupied) { - auto bytes = make_base_image(0x2000, 0x400); - auto* nt = nt_header_of(bytes); - nt->OptionalHeader.ImageBase = reinterpret_cast(occupied); - nt->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_BASERELOC] = {0x1FFC, 4}; - auto path = write_temp_image(bytes); - bool threw = false; - try { - rt::Loader loader(g_temp_dir); - loader.load(path); - } catch (const std::runtime_error&) { - threw = true; - } - VirtualFree(occupied, 0, MEM_RELEASE); - check_condition(threw, "Truncated 4-byte relocation block at end of image is rejected cleanly"); - } - } - - // 4. Valid 8-byte relocation block followed by 4 trailing bytes (remaining < sizeof(IMAGE_BASE_RELOCATION)). - { - void* occupied = VirtualAlloc(nullptr, 0x2000, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE); - check_condition(occupied != nullptr, "Reserved preferred base for trailing reloc bytes test"); - if (occupied) { - auto bytes = make_base_image(0x2000, 0x1400); - auto* nt = nt_header_of(bytes); - nt->OptionalHeader.ImageBase = reinterpret_cast(occupied); - auto* sec = IMAGE_FIRST_SECTION(nt); - sec->VirtualAddress = 0x1000; - sec->Misc.VirtualSize = 0x1000; - sec->PointerToRawData = 0x400; - sec->SizeOfRawData = 0x1000; - // Place a 12-byte reloc dir at RVA 0x1FF4 (raw offset 0x13F4): 8-byte block + 4 trailing bytes. - nt->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_BASERELOC] = {0x1FF4, 12}; - IMAGE_BASE_RELOCATION hdr{}; - hdr.VirtualAddress = 0x1000; - hdr.SizeOfBlock = sizeof(IMAGE_BASE_RELOCATION); - std::memcpy(bytes.data() + 0x13F4, &hdr, sizeof(hdr)); - auto path = write_temp_image(bytes); - bool threw = false; - try { - rt::Loader loader(g_temp_dir); - loader.load(path); - } catch (const std::runtime_error&) { - threw = true; - } - VirtualFree(occupied, 0, MEM_RELEASE); - check_condition(threw, "Trailing 4 bytes after valid relocation block are rejected cleanly"); - } - } - - { - auto bytes = make_base_image(0x2000, 0x400); - IMAGE_FIRST_SECTION(nt_header_of(bytes))->VirtualAddress = 0; - std::memcpy(bytes.data() + 0x200, bytes.data(), 0x200); - reinterpret_cast(bytes.data() + 0x200)->e_lfanew = 0x7FFF0000; - expect_loader_rejection("Section below SizeOfHeaders is rejected", bytes, "section 0 overlaps the headers"); - } - - { - auto bytes = make_base_image(0x2000, 0x400); - auto* nt = nt_header_of(bytes); - nt->OptionalHeader.ImageBase = 0; - nt->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_BASERELOC] = {0x1000, 0x0A}; - auto* block = reinterpret_cast(bytes.data() + 0x200); - block->VirtualAddress = 0; - block->SizeOfBlock = 0x0A; - reinterpret_cast(block + 1)[0] = static_cast(IMAGE_REL_BASED_DIR64 << 12 | 0x3C); - expect_loader_rejection("Relocation inside the headers is rejected", bytes, "a relocation lands in the headers"); - } - - { - auto bytes = make_base_image(0x400, 0x400); - auto* nt = nt_header_of(bytes); - nt->OptionalHeader.SectionAlignment = 0x200; - nt->OptionalHeader.FileAlignment = 0x200; - nt->OptionalHeader.AddressOfEntryPoint = 0x200; - IMAGE_FIRST_SECTION(nt)->VirtualAddress = 0x200; - expect_loader_success("Section starting exactly at SizeOfHeaders maps successfully", bytes); - - nt->OptionalHeader.ImageBase = 0; - nt->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_BASERELOC] = {0x300, 0x0A}; - auto* block = reinterpret_cast(bytes.data() + 0x300); - block->VirtualAddress = 0; - block->SizeOfBlock = 0x0A; - reinterpret_cast(block + 1)[0] = static_cast(IMAGE_REL_BASED_DIR64 << 12 | 0x200); - expect_loader_success("DIR64 relocation at exactly SizeOfHeaders is accepted", bytes); - } -} - -} // namespace - -int main() { - std::printf("test_pe_loader_bounds: PE Loader boundary checks, virtual address range wrapping, and import table null termination\n"); - - const char* env_dir = std::getenv("LEONIDA_TEST_DIR"); - g_temp_dir = env_dir ? std::filesystem::path(env_dir) - : std::filesystem::temp_directory_path() / - ("leonida_pe_bounds_test_" + std::to_string(GetCurrentProcessId())); - std::filesystem::create_directories(g_temp_dir); - - try { - test_range_wrapping_arithmetic(); - test_string_null_termination_direct(); - test_import_table_null_termination(); - test_virtual_address_range_wrapping(); - test_boundary_exact_fits(); - test_highlow_relocations(); - test_directory_count(); - test_forwarder_ordinal_range(); - test_headers_and_reloc_tail_bounds(); - } catch (const std::exception& e) { - std::printf("FATAL: Unhandled exception during test execution: %s\n", e.what()); - ++g_failures; - } - - std::error_code ec; - std::filesystem::remove_all(g_temp_dir, ec); - - std::printf("\n============================================================\n"); - if (g_failures == 0) { - std::printf("test_pe_loader_bounds: ALL %d CHECKS PASSED\n", g_checks); - return 0; - } else { - std::printf("test_pe_loader_bounds: FAILED (%d checks, %d failure%s)\n", - g_checks, g_failures, g_failures == 1 ? "" : "s"); - return 1; - } -} diff --git a/runtime/test/test_runtime_types.cpp b/runtime/test/test_runtime_types.cpp deleted file mode 100644 index a71deb000..000000000 --- a/runtime/test/test_runtime_types.cpp +++ /dev/null @@ -1,604 +0,0 @@ -// Unit tests verifying D3D12 and XMem ABI type alignment and structure sizes against the Windows SDK. -// -// These tests verify that the guest Xbox Series ABI assumptions made by Leonida's runtime shims -// (d3d12_xs, xmem, registry) match the Windows SDK type definitions, packing, member offsets, -// and calling conventions on x86-64. - -#include -#include -#include -#include -#include - -#include -#include -#include -#include -#include -#include - -#if __has_include("d3d12_xs_rootsig.h") -#include "d3d12_xs_rootsig.h" -#elif __has_include("../shims/d3d12_xs_rootsig.h") -#include "../shims/d3d12_xs_rootsig.h" -#endif - -namespace { - -int g_checks = 0; -int g_failures = 0; - -void check(bool condition, const char* what) { - ++g_checks; - std::printf("%s %s\n", condition ? "PASS" : "FAIL", what); - if (!condition) { - ++g_failures; - } -} - -// --------------------------------------------------------------------------- -// Compile-time ABI assertions: Type sizes, alignments, and member offsets -// --------------------------------------------------------------------------- - -// Architecture verification -static_assert(sizeof(void*) == 8, "Target architecture must be 64-bit"); -static_assert(sizeof(size_t) == 8, "size_t must be 8 bytes on x64"); -static_assert(sizeof(uintptr_t) == 8, "uintptr_t must be 8 bytes on x64"); - -// D3D12 Root Constants -static_assert(sizeof(D3D12_ROOT_CONSTANTS) == 12, "D3D12_ROOT_CONSTANTS size must be 12 bytes"); -static_assert(alignof(D3D12_ROOT_CONSTANTS) == 4, "D3D12_ROOT_CONSTANTS alignment must be 4 bytes"); -static_assert(offsetof(D3D12_ROOT_CONSTANTS, ShaderRegister) == 0); -static_assert(offsetof(D3D12_ROOT_CONSTANTS, RegisterSpace) == 4); -static_assert(offsetof(D3D12_ROOT_CONSTANTS, Num32BitValues) == 8); - -// D3D12 Descriptor Ranges (1.0) -static_assert(sizeof(D3D12_DESCRIPTOR_RANGE) == 20, "D3D12_DESCRIPTOR_RANGE size must be 20 bytes"); -static_assert(alignof(D3D12_DESCRIPTOR_RANGE) == 4, "D3D12_DESCRIPTOR_RANGE alignment must be 4 bytes"); -static_assert(offsetof(D3D12_DESCRIPTOR_RANGE, RangeType) == 0); -static_assert(offsetof(D3D12_DESCRIPTOR_RANGE, NumDescriptors) == 4); -static_assert(offsetof(D3D12_DESCRIPTOR_RANGE, BaseShaderRegister) == 8); -static_assert(offsetof(D3D12_DESCRIPTOR_RANGE, RegisterSpace) == 12); -static_assert(offsetof(D3D12_DESCRIPTOR_RANGE, OffsetInDescriptorsFromTableStart) == 16); - -// D3D12 Descriptor Ranges (1.1) -static_assert(sizeof(D3D12_DESCRIPTOR_RANGE1) == 24, "D3D12_DESCRIPTOR_RANGE1 size must be 24 bytes"); -static_assert(alignof(D3D12_DESCRIPTOR_RANGE1) == 4, "D3D12_DESCRIPTOR_RANGE1 alignment must be 4 bytes"); -static_assert(offsetof(D3D12_DESCRIPTOR_RANGE1, RangeType) == 0); -static_assert(offsetof(D3D12_DESCRIPTOR_RANGE1, NumDescriptors) == 4); -static_assert(offsetof(D3D12_DESCRIPTOR_RANGE1, BaseShaderRegister) == 8); -static_assert(offsetof(D3D12_DESCRIPTOR_RANGE1, RegisterSpace) == 12); -static_assert(offsetof(D3D12_DESCRIPTOR_RANGE1, Flags) == 16); -static_assert(offsetof(D3D12_DESCRIPTOR_RANGE1, OffsetInDescriptorsFromTableStart) == 20); - -// D3D12 Root Descriptor Table -static_assert(sizeof(D3D12_ROOT_DESCRIPTOR_TABLE) == 16, "D3D12_ROOT_DESCRIPTOR_TABLE size must be 16 bytes"); -static_assert(alignof(D3D12_ROOT_DESCRIPTOR_TABLE) == 8, "D3D12_ROOT_DESCRIPTOR_TABLE alignment must be 8 bytes"); -static_assert(offsetof(D3D12_ROOT_DESCRIPTOR_TABLE, NumDescriptorRanges) == 0); -static_assert(offsetof(D3D12_ROOT_DESCRIPTOR_TABLE, pDescriptorRanges) == 8); - -static_assert(sizeof(D3D12_ROOT_DESCRIPTOR_TABLE1) == 16, "D3D12_ROOT_DESCRIPTOR_TABLE1 size must be 16 bytes"); -static_assert(alignof(D3D12_ROOT_DESCRIPTOR_TABLE1) == 8, "D3D12_ROOT_DESCRIPTOR_TABLE1 alignment must be 8 bytes"); -static_assert(offsetof(D3D12_ROOT_DESCRIPTOR_TABLE1, NumDescriptorRanges) == 0); -static_assert(offsetof(D3D12_ROOT_DESCRIPTOR_TABLE1, pDescriptorRanges) == 8); - -// D3D12 Root Descriptors -static_assert(sizeof(D3D12_ROOT_DESCRIPTOR) == 8, "D3D12_ROOT_DESCRIPTOR size must be 8 bytes"); -static_assert(alignof(D3D12_ROOT_DESCRIPTOR) == 4, "D3D12_ROOT_DESCRIPTOR alignment must be 4 bytes"); -static_assert(offsetof(D3D12_ROOT_DESCRIPTOR, ShaderRegister) == 0); -static_assert(offsetof(D3D12_ROOT_DESCRIPTOR, RegisterSpace) == 4); - -static_assert(sizeof(D3D12_ROOT_DESCRIPTOR1) == 12, "D3D12_ROOT_DESCRIPTOR1 size must be 12 bytes"); -static_assert(alignof(D3D12_ROOT_DESCRIPTOR1) == 4, "D3D12_ROOT_DESCRIPTOR1 alignment must be 4 bytes"); -static_assert(offsetof(D3D12_ROOT_DESCRIPTOR1, ShaderRegister) == 0); -static_assert(offsetof(D3D12_ROOT_DESCRIPTOR1, RegisterSpace) == 4); -static_assert(offsetof(D3D12_ROOT_DESCRIPTOR1, Flags) == 8); - -// D3D12 Root Parameters -static_assert(sizeof(D3D12_ROOT_PARAMETER) == 32, "D3D12_ROOT_PARAMETER size must be 32 bytes"); -static_assert(alignof(D3D12_ROOT_PARAMETER) == 8, "D3D12_ROOT_PARAMETER alignment must be 8 bytes"); -static_assert(offsetof(D3D12_ROOT_PARAMETER, ParameterType) == 0); -static_assert(offsetof(D3D12_ROOT_PARAMETER, DescriptorTable) == 8); -static_assert(offsetof(D3D12_ROOT_PARAMETER, Constants) == 8); -static_assert(offsetof(D3D12_ROOT_PARAMETER, Descriptor) == 8); -static_assert(offsetof(D3D12_ROOT_PARAMETER, ShaderVisibility) == 24); - -static_assert(sizeof(D3D12_ROOT_PARAMETER1) == 32, "D3D12_ROOT_PARAMETER1 size must be 32 bytes"); -static_assert(alignof(D3D12_ROOT_PARAMETER1) == 8, "D3D12_ROOT_PARAMETER1 alignment must be 8 bytes"); -static_assert(offsetof(D3D12_ROOT_PARAMETER1, ParameterType) == 0); -static_assert(offsetof(D3D12_ROOT_PARAMETER1, DescriptorTable) == 8); -static_assert(offsetof(D3D12_ROOT_PARAMETER1, Constants) == 8); -static_assert(offsetof(D3D12_ROOT_PARAMETER1, Descriptor) == 8); -static_assert(offsetof(D3D12_ROOT_PARAMETER1, ShaderVisibility) == 24); - -// D3D12 Static Sampler -static_assert(sizeof(D3D12_STATIC_SAMPLER_DESC) == 52, "D3D12_STATIC_SAMPLER_DESC size must be 52 bytes"); -static_assert(alignof(D3D12_STATIC_SAMPLER_DESC) == 4, "D3D12_STATIC_SAMPLER_DESC alignment must be 4 bytes"); -static_assert(offsetof(D3D12_STATIC_SAMPLER_DESC, Filter) == 0); -static_assert(offsetof(D3D12_STATIC_SAMPLER_DESC, AddressU) == 4); -static_assert(offsetof(D3D12_STATIC_SAMPLER_DESC, AddressV) == 8); -static_assert(offsetof(D3D12_STATIC_SAMPLER_DESC, AddressW) == 12); -static_assert(offsetof(D3D12_STATIC_SAMPLER_DESC, MipLODBias) == 16); -static_assert(offsetof(D3D12_STATIC_SAMPLER_DESC, MaxAnisotropy) == 20); -static_assert(offsetof(D3D12_STATIC_SAMPLER_DESC, ComparisonFunc) == 24); -static_assert(offsetof(D3D12_STATIC_SAMPLER_DESC, BorderColor) == 28); -static_assert(offsetof(D3D12_STATIC_SAMPLER_DESC, MinLOD) == 32); -static_assert(offsetof(D3D12_STATIC_SAMPLER_DESC, MaxLOD) == 36); -static_assert(offsetof(D3D12_STATIC_SAMPLER_DESC, ShaderRegister) == 40); -static_assert(offsetof(D3D12_STATIC_SAMPLER_DESC, RegisterSpace) == 44); -static_assert(offsetof(D3D12_STATIC_SAMPLER_DESC, ShaderVisibility) == 48); - -// D3D12 Root Signature Descriptors -static_assert(sizeof(D3D12_ROOT_SIGNATURE_DESC) == 40, "D3D12_ROOT_SIGNATURE_DESC size must be 40 bytes"); -static_assert(alignof(D3D12_ROOT_SIGNATURE_DESC) == 8, "D3D12_ROOT_SIGNATURE_DESC alignment must be 8 bytes"); -static_assert(offsetof(D3D12_ROOT_SIGNATURE_DESC, NumParameters) == 0); -static_assert(offsetof(D3D12_ROOT_SIGNATURE_DESC, pParameters) == 8); -static_assert(offsetof(D3D12_ROOT_SIGNATURE_DESC, NumStaticSamplers) == 16); -static_assert(offsetof(D3D12_ROOT_SIGNATURE_DESC, pStaticSamplers) == 24); -static_assert(offsetof(D3D12_ROOT_SIGNATURE_DESC, Flags) == 32); - -static_assert(sizeof(D3D12_ROOT_SIGNATURE_DESC1) == 40, "D3D12_ROOT_SIGNATURE_DESC1 size must be 40 bytes"); -static_assert(alignof(D3D12_ROOT_SIGNATURE_DESC1) == 8, "D3D12_ROOT_SIGNATURE_DESC1 alignment must be 8 bytes"); -static_assert(offsetof(D3D12_ROOT_SIGNATURE_DESC1, NumParameters) == 0); -static_assert(offsetof(D3D12_ROOT_SIGNATURE_DESC1, pParameters) == 8); -static_assert(offsetof(D3D12_ROOT_SIGNATURE_DESC1, NumStaticSamplers) == 16); -static_assert(offsetof(D3D12_ROOT_SIGNATURE_DESC1, pStaticSamplers) == 24); -static_assert(offsetof(D3D12_ROOT_SIGNATURE_DESC1, Flags) == 32); - -static_assert(sizeof(D3D12_VERSIONED_ROOT_SIGNATURE_DESC) == 48, - "D3D12_VERSIONED_ROOT_SIGNATURE_DESC size must be 48 bytes"); -static_assert(alignof(D3D12_VERSIONED_ROOT_SIGNATURE_DESC) == 8, - "D3D12_VERSIONED_ROOT_SIGNATURE_DESC alignment must be 8 bytes"); -static_assert(offsetof(D3D12_VERSIONED_ROOT_SIGNATURE_DESC, Version) == 0); -static_assert(offsetof(D3D12_VERSIONED_ROOT_SIGNATURE_DESC, Desc_1_0) == 8); -static_assert(offsetof(D3D12_VERSIONED_ROOT_SIGNATURE_DESC, Desc_1_1) == 8); - -// D3D12 Descriptor Handles and Heap -static_assert(sizeof(D3D12_CPU_DESCRIPTOR_HANDLE) == 8, "D3D12_CPU_DESCRIPTOR_HANDLE size must be 8 bytes"); -static_assert(alignof(D3D12_CPU_DESCRIPTOR_HANDLE) == 8, "D3D12_CPU_DESCRIPTOR_HANDLE alignment must be 8 bytes"); -static_assert(offsetof(D3D12_CPU_DESCRIPTOR_HANDLE, ptr) == 0); -static_assert(std::is_standard_layout_v); -static_assert(std::is_trivially_copyable_v); - -static_assert(sizeof(D3D12_GPU_DESCRIPTOR_HANDLE) == 8, "D3D12_GPU_DESCRIPTOR_HANDLE size must be 8 bytes"); -static_assert(alignof(D3D12_GPU_DESCRIPTOR_HANDLE) == 8, "D3D12_GPU_DESCRIPTOR_HANDLE alignment must be 8 bytes"); -static_assert(offsetof(D3D12_GPU_DESCRIPTOR_HANDLE, ptr) == 0); -static_assert(std::is_standard_layout_v); -static_assert(std::is_trivially_copyable_v); - -static_assert(sizeof(D3D12_DESCRIPTOR_HEAP_DESC) == 16, "D3D12_DESCRIPTOR_HEAP_DESC size must be 16 bytes"); -static_assert(alignof(D3D12_DESCRIPTOR_HEAP_DESC) == 4, "D3D12_DESCRIPTOR_HEAP_DESC alignment must be 4 bytes"); - -// D3D12 Resources and Views -static_assert(sizeof(D3D12_RESOURCE_DESC) == 56, "D3D12_RESOURCE_DESC size must be 56 bytes"); -static_assert(alignof(D3D12_RESOURCE_DESC) == 8, "D3D12_RESOURCE_DESC alignment must be 8 bytes"); -static_assert(offsetof(D3D12_RESOURCE_DESC, Dimension) == 0); -static_assert(offsetof(D3D12_RESOURCE_DESC, Alignment) == 8); -static_assert(offsetof(D3D12_RESOURCE_DESC, Width) == 16); -static_assert(offsetof(D3D12_RESOURCE_DESC, Height) == 24); -static_assert(offsetof(D3D12_RESOURCE_DESC, DepthOrArraySize) == 28); -static_assert(offsetof(D3D12_RESOURCE_DESC, MipLevels) == 30); -static_assert(offsetof(D3D12_RESOURCE_DESC, Format) == 32); -static_assert(offsetof(D3D12_RESOURCE_DESC, SampleDesc) == 36); -static_assert(offsetof(D3D12_RESOURCE_DESC, Layout) == 44); -static_assert(offsetof(D3D12_RESOURCE_DESC, Flags) == 48); - -static_assert(sizeof(D3D12_CLEAR_VALUE) == 20, "D3D12_CLEAR_VALUE size must be 20 bytes"); -static_assert(alignof(D3D12_CLEAR_VALUE) == 4, "D3D12_CLEAR_VALUE alignment must be 4 bytes"); -static_assert(sizeof(D3D12_BOX) == 24, "D3D12_BOX size must be 24 bytes"); -static_assert(alignof(D3D12_BOX) == 4, "D3D12_BOX alignment must be 4 bytes"); -static_assert(sizeof(D3D12_VIEWPORT) == 24, "D3D12_VIEWPORT size must be 24 bytes"); -static_assert(alignof(D3D12_VIEWPORT) == 4, "D3D12_VIEWPORT alignment must be 4 bytes"); -static_assert(sizeof(D3D12_RECT) == 16, "D3D12_RECT size must be 16 bytes"); -static_assert(alignof(D3D12_RECT) == 4, "D3D12_RECT alignment must be 4 bytes"); - -static_assert(sizeof(D3D12_SUBRESOURCE_DATA) == 24, "D3D12_SUBRESOURCE_DATA size must be 24 bytes"); -static_assert(alignof(D3D12_SUBRESOURCE_DATA) == 8, "D3D12_SUBRESOURCE_DATA alignment must be 8 bytes"); -static_assert(offsetof(D3D12_SUBRESOURCE_DATA, pData) == 0); -static_assert(offsetof(D3D12_SUBRESOURCE_DATA, RowPitch) == 8); -static_assert(offsetof(D3D12_SUBRESOURCE_DATA, SlicePitch) == 16); - -static_assert(sizeof(D3D12_MEMCPY_DEST) == 24, "D3D12_MEMCPY_DEST size must be 24 bytes"); -static_assert(alignof(D3D12_MEMCPY_DEST) == 8, "D3D12_MEMCPY_DEST alignment must be 8 bytes"); - -static_assert(sizeof(D3D12_RESOURCE_BARRIER) == 32, "D3D12_RESOURCE_BARRIER size must be 32 bytes"); -static_assert(alignof(D3D12_RESOURCE_BARRIER) == 8, "D3D12_RESOURCE_BARRIER alignment must be 8 bytes"); -static_assert(offsetof(D3D12_RESOURCE_BARRIER, Type) == 0); -static_assert(offsetof(D3D12_RESOURCE_BARRIER, Flags) == 4); -static_assert(offsetof(D3D12_RESOURCE_BARRIER, Transition) == 8); - -static_assert(sizeof(D3D12_CONSTANT_BUFFER_VIEW_DESC) == 16, - "D3D12_CONSTANT_BUFFER_VIEW_DESC size must be 16 bytes"); -static_assert(alignof(D3D12_CONSTANT_BUFFER_VIEW_DESC) == 8, - "D3D12_CONSTANT_BUFFER_VIEW_DESC alignment must be 8 bytes"); -static_assert(offsetof(D3D12_CONSTANT_BUFFER_VIEW_DESC, BufferLocation) == 0); -static_assert(offsetof(D3D12_CONSTANT_BUFFER_VIEW_DESC, SizeInBytes) == 8); - -static_assert(sizeof(D3D12_SHADER_RESOURCE_VIEW_DESC) == 40, - "D3D12_SHADER_RESOURCE_VIEW_DESC size must be 40 bytes"); -static_assert(alignof(D3D12_SHADER_RESOURCE_VIEW_DESC) == 8, - "D3D12_SHADER_RESOURCE_VIEW_DESC alignment must be 8 bytes"); - -static_assert(sizeof(D3D12_UNORDERED_ACCESS_VIEW_DESC) == 40, - "D3D12_UNORDERED_ACCESS_VIEW_DESC size must be 40 bytes"); -static_assert(alignof(D3D12_UNORDERED_ACCESS_VIEW_DESC) == 8, - "D3D12_UNORDERED_ACCESS_VIEW_DESC alignment must be 8 bytes"); - -static_assert(sizeof(D3D12_RENDER_TARGET_VIEW_DESC) == 24, - "D3D12_RENDER_TARGET_VIEW_DESC size must be 24 bytes"); -static_assert(alignof(D3D12_RENDER_TARGET_VIEW_DESC) == 8, - "D3D12_RENDER_TARGET_VIEW_DESC alignment must be 8 bytes"); - -static_assert(sizeof(D3D12_DEPTH_STENCIL_VIEW_DESC) == 24, - "D3D12_DEPTH_STENCIL_VIEW_DESC size must be 24 bytes"); -static_assert(alignof(D3D12_DEPTH_STENCIL_VIEW_DESC) == 4, - "D3D12_DEPTH_STENCIL_VIEW_DESC alignment must be 4 bytes"); - -static_assert(sizeof(D3D12_COMPUTE_PIPELINE_STATE_DESC) == 56, - "D3D12_COMPUTE_PIPELINE_STATE_DESC size must be 56 bytes"); -static_assert(alignof(D3D12_COMPUTE_PIPELINE_STATE_DESC) == 8, - "D3D12_COMPUTE_PIPELINE_STATE_DESC alignment must be 8 bytes"); -static_assert(offsetof(D3D12_COMPUTE_PIPELINE_STATE_DESC, pRootSignature) == 0); -static_assert(offsetof(D3D12_COMPUTE_PIPELINE_STATE_DESC, CS) == 8); -static_assert(offsetof(D3D12_COMPUTE_PIPELINE_STATE_DESC, NodeMask) == 24); -static_assert(offsetof(D3D12_COMPUTE_PIPELINE_STATE_DESC, CachedPSO) == 32); -static_assert(offsetof(D3D12_COMPUTE_PIPELINE_STATE_DESC, Flags) == 48); - -static_assert(sizeof(D3D12_SHADER_BYTECODE) == 16, "D3D12_SHADER_BYTECODE size must be 16 bytes"); -static_assert(alignof(D3D12_SHADER_BYTECODE) == 8, "D3D12_SHADER_BYTECODE alignment must be 8 bytes"); -static_assert(offsetof(D3D12_SHADER_BYTECODE, pShaderBytecode) == 0); -static_assert(offsetof(D3D12_SHADER_BYTECODE, BytecodeLength) == 8); - -// Memory / XMem Subsystem Types -static_assert(sizeof(MEMORY_BASIC_INFORMATION) == 48, "MEMORY_BASIC_INFORMATION size must be 48 bytes on x64"); -static_assert(alignof(MEMORY_BASIC_INFORMATION) == 8, "MEMORY_BASIC_INFORMATION alignment must be 8 bytes"); -static_assert(offsetof(MEMORY_BASIC_INFORMATION, BaseAddress) == 0); -static_assert(offsetof(MEMORY_BASIC_INFORMATION, AllocationBase) == 8); -static_assert(offsetof(MEMORY_BASIC_INFORMATION, AllocationProtect) == 16); -static_assert(offsetof(MEMORY_BASIC_INFORMATION, PartitionId) == 20); -static_assert(offsetof(MEMORY_BASIC_INFORMATION, RegionSize) == 24); -static_assert(offsetof(MEMORY_BASIC_INFORMATION, State) == 32); -static_assert(offsetof(MEMORY_BASIC_INFORMATION, Protect) == 36); -static_assert(offsetof(MEMORY_BASIC_INFORMATION, Type) == 40); - -static_assert(sizeof(PROCESS_MEMORY_COUNTERS) == 72, "PROCESS_MEMORY_COUNTERS size must be 72 bytes on x64"); -static_assert(alignof(PROCESS_MEMORY_COUNTERS) == 8, "PROCESS_MEMORY_COUNTERS alignment must be 8 bytes"); -static_assert(offsetof(PROCESS_MEMORY_COUNTERS, cb) == 0); -static_assert(offsetof(PROCESS_MEMORY_COUNTERS, PageFaultCount) == 4); -static_assert(offsetof(PROCESS_MEMORY_COUNTERS, PeakWorkingSetSize) == 8); -static_assert(offsetof(PROCESS_MEMORY_COUNTERS, WorkingSetSize) == 16); -static_assert(offsetof(PROCESS_MEMORY_COUNTERS, QuotaPeakPagedPoolUsage) == 24); -static_assert(offsetof(PROCESS_MEMORY_COUNTERS, QuotaPagedPoolUsage) == 32); -static_assert(offsetof(PROCESS_MEMORY_COUNTERS, QuotaPeakNonPagedPoolUsage) == 40); -static_assert(offsetof(PROCESS_MEMORY_COUNTERS, QuotaNonPagedPoolUsage) == 48); -static_assert(offsetof(PROCESS_MEMORY_COUNTERS, PagefileUsage) == 56); -static_assert(offsetof(PROCESS_MEMORY_COUNTERS, PeakPagefileUsage) == 64); - -static_assert(sizeof(PROCESS_MEMORY_COUNTERS_EX) == 80, "PROCESS_MEMORY_COUNTERS_EX size must be 80 bytes on x64"); -static_assert(offsetof(PROCESS_MEMORY_COUNTERS_EX, PrivateUsage) == 72); - -// XMem ABI Constants & Contracts from xmem.cpp -constexpr size_t kXMemAllocAlignment = 64; -constexpr size_t kXMemVirtualQueryOutSize = 64; -static_assert(sizeof(MEMORY_BASIC_INFORMATION) <= kXMemVirtualQueryOutSize, - "the 64-byte XMemVirtualQuery output buffer must accommodate MEMORY_BASIC_INFORMATION"); -static_assert(kXMemVirtualQueryOutSize - sizeof(MEMORY_BASIC_INFORMATION) == 16, - "the trailing unknown area in the 64-byte buffer is exactly 16 bytes"); - -// D3D12 Xbox root signature flag mask contract -constexpr uint32_t kXboxRootSigFlagMask = 0xFF000000u; -constexpr uint32_t kObservedXboxRootSigFlag = 0x03000000u; - -// Function pointer signatures for XMem exports -using XMemAllocFn = void*(__stdcall*)(size_t, uint64_t); -using XMemFreeFn = void(__stdcall*)(void*, uint64_t); -using XMemVirtualQueryFn = SIZE_T(__stdcall*)(HANDLE, const void*, void*); -using XMemGetWorkingSetStatisticsFn = BOOL(__stdcall*)(uint32_t, void*); - -// Function pointer signatures for D3D12 exports -using D3D12SerializeVersionedRootSignatureFn = - HRESULT(WINAPI*)(const D3D12_VERSIONED_ROOT_SIGNATURE_DESC*, ID3DBlob**, ID3DBlob**); -using D3D12SerializeRootSignatureFn = - HRESULT(WINAPI*)(const D3D12_ROOT_SIGNATURE_DESC*, D3D_ROOT_SIGNATURE_VERSION, ID3DBlob**, ID3DBlob**); -using D3D12CreateRootSignatureDeserializerFn = - HRESULT(WINAPI*)(const void*, SIZE_T, REFIID, void**); -using D3D12XboxCreateDeviceFn = - HRESULT(WINAPI*)(IUnknown*, const void*, const IID*, void**); - -// --------------------------------------------------------------------------- -// Runtime Test Procedures -// --------------------------------------------------------------------------- - -void test_d3d12_root_signature_abi() { - std::printf("\n--- Testing D3D12 Root Signature ABI Types ---\n"); - - check(sizeof(D3D12_ROOT_CONSTANTS) == 12 && alignof(D3D12_ROOT_CONSTANTS) == 4, - "D3D12_ROOT_CONSTANTS matches Windows SDK size 12 and alignment 4"); - - check(sizeof(D3D12_DESCRIPTOR_RANGE) == 20 && alignof(D3D12_DESCRIPTOR_RANGE) == 4, - "D3D12_DESCRIPTOR_RANGE matches Windows SDK size 20 and alignment 4"); - - check(sizeof(D3D12_DESCRIPTOR_RANGE1) == 24 && alignof(D3D12_DESCRIPTOR_RANGE1) == 4, - "D3D12_DESCRIPTOR_RANGE1 matches Windows SDK size 24 and alignment 4"); - - check(sizeof(D3D12_ROOT_DESCRIPTOR_TABLE) == 16 && alignof(D3D12_ROOT_DESCRIPTOR_TABLE) == 8, - "D3D12_ROOT_DESCRIPTOR_TABLE matches Windows SDK size 16 and alignment 8"); - - check(sizeof(D3D12_ROOT_DESCRIPTOR_TABLE1) == 16 && alignof(D3D12_ROOT_DESCRIPTOR_TABLE1) == 8, - "D3D12_ROOT_DESCRIPTOR_TABLE1 matches Windows SDK size 16 and alignment 8"); - - check(sizeof(D3D12_ROOT_DESCRIPTOR) == 8 && alignof(D3D12_ROOT_DESCRIPTOR) == 4, - "D3D12_ROOT_DESCRIPTOR matches Windows SDK size 8 and alignment 4"); - - check(sizeof(D3D12_ROOT_DESCRIPTOR1) == 12 && alignof(D3D12_ROOT_DESCRIPTOR1) == 4, - "D3D12_ROOT_DESCRIPTOR1 matches Windows SDK size 12 and alignment 4"); - - check(sizeof(D3D12_ROOT_PARAMETER) == 32 && alignof(D3D12_ROOT_PARAMETER) == 8, - "D3D12_ROOT_PARAMETER matches Windows SDK size 32 and alignment 8"); - - check(sizeof(D3D12_ROOT_PARAMETER1) == 32 && alignof(D3D12_ROOT_PARAMETER1) == 8, - "D3D12_ROOT_PARAMETER1 matches Windows SDK size 32 and alignment 8"); - - check(sizeof(D3D12_STATIC_SAMPLER_DESC) == 52 && alignof(D3D12_STATIC_SAMPLER_DESC) == 4, - "D3D12_STATIC_SAMPLER_DESC matches Windows SDK size 52 and alignment 4"); - - check(sizeof(D3D12_ROOT_SIGNATURE_DESC) == 40 && alignof(D3D12_ROOT_SIGNATURE_DESC) == 8, - "D3D12_ROOT_SIGNATURE_DESC matches Windows SDK size 40 and alignment 8"); - - check(sizeof(D3D12_ROOT_SIGNATURE_DESC1) == 40 && alignof(D3D12_ROOT_SIGNATURE_DESC1) == 8, - "D3D12_ROOT_SIGNATURE_DESC1 matches Windows SDK size 40 and alignment 8"); - - check(sizeof(D3D12_VERSIONED_ROOT_SIGNATURE_DESC) == 48 && - alignof(D3D12_VERSIONED_ROOT_SIGNATURE_DESC) == 8, - "D3D12_VERSIONED_ROOT_SIGNATURE_DESC matches Windows SDK size 48 and alignment 8"); - - // Dynamic layout check: verify union offset and flag masking behavior - D3D12_VERSIONED_ROOT_SIGNATURE_DESC versioned{}; - versioned.Version = D3D_ROOT_SIGNATURE_VERSION_1_1; - versioned.Desc_1_1.NumParameters = 1; - versioned.Desc_1_1.Flags = static_cast( - kObservedXboxRootSigFlag | D3D12_ROOT_SIGNATURE_FLAG_ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT); - - check(versioned.Desc_1_1.Flags & kObservedXboxRootSigFlag, - "Xbox root signature flags set high byte bit 0x03000000"); - - const uint32_t cleared_flags = - static_cast(versioned.Desc_1_1.Flags) & ~kXboxRootSigFlagMask; - check(cleared_flags == D3D12_ROOT_SIGNATURE_FLAG_ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT, - "Clearing high flag byte 0xFF000000 preserves legitimate Windows SDK flags"); -} - -void test_d3d12_handles_and_views_abi() { - std::printf("\n--- Testing D3D12 Descriptors, Handles, and Views ABI Types ---\n"); - - check(sizeof(D3D12_CPU_DESCRIPTOR_HANDLE) == 8 && alignof(D3D12_CPU_DESCRIPTOR_HANDLE) == 8, - "D3D12_CPU_DESCRIPTOR_HANDLE size is 8 bytes with 8-byte alignment"); - - check(sizeof(D3D12_GPU_DESCRIPTOR_HANDLE) == 8 && alignof(D3D12_GPU_DESCRIPTOR_HANDLE) == 8, - "D3D12_GPU_DESCRIPTOR_HANDLE size is 8 bytes with 8-byte alignment"); - - // Check register-return ABI contract: handles fit cleanly inside RAX - D3D12_CPU_DESCRIPTOR_HANDLE cpu_handle{0xDEADBEEF00001234ull}; - uint64_t cpu_raw = 0; - std::memcpy(&cpu_raw, &cpu_handle, sizeof(cpu_raw)); - check(cpu_raw == 0xDEADBEEF00001234ull, - "D3D12_CPU_DESCRIPTOR_HANDLE round-trips into 64-bit register representation"); - - D3D12_GPU_DESCRIPTOR_HANDLE gpu_handle{0xCAFEF00D56789A00ull}; - uint64_t gpu_raw = 0; - std::memcpy(&gpu_raw, &gpu_handle, sizeof(gpu_raw)); - check(gpu_raw == 0xCAFEF00D56789A00ull, - "D3D12_GPU_DESCRIPTOR_HANDLE round-trips into 64-bit register representation"); - - check(sizeof(D3D12_DESCRIPTOR_HEAP_DESC) == 16 && alignof(D3D12_DESCRIPTOR_HEAP_DESC) == 4, - "D3D12_DESCRIPTOR_HEAP_DESC size 16 bytes and alignment 4"); - - check(sizeof(D3D12_CONSTANT_BUFFER_VIEW_DESC) == 16 && - alignof(D3D12_CONSTANT_BUFFER_VIEW_DESC) == 8, - "D3D12_CONSTANT_BUFFER_VIEW_DESC size 16 bytes and alignment 8"); - - check(sizeof(D3D12_SHADER_RESOURCE_VIEW_DESC) == 40 && - alignof(D3D12_SHADER_RESOURCE_VIEW_DESC) == 8, - "D3D12_SHADER_RESOURCE_VIEW_DESC size 40 bytes and alignment 8"); - - check(sizeof(D3D12_UNORDERED_ACCESS_VIEW_DESC) == 40 && - alignof(D3D12_UNORDERED_ACCESS_VIEW_DESC) == 8, - "D3D12_UNORDERED_ACCESS_VIEW_DESC size 40 bytes and alignment 8"); - - check(sizeof(D3D12_RENDER_TARGET_VIEW_DESC) == 24 && - alignof(D3D12_RENDER_TARGET_VIEW_DESC) == 8, - "D3D12_RENDER_TARGET_VIEW_DESC size 24 bytes and alignment 8"); - - check(sizeof(D3D12_DEPTH_STENCIL_VIEW_DESC) == 24 && - alignof(D3D12_DEPTH_STENCIL_VIEW_DESC) == 4, - "D3D12_DEPTH_STENCIL_VIEW_DESC size 24 bytes and alignment 4"); -} - -void test_d3d12_resources_and_pipeline_abi() { - std::printf("\n--- Testing D3D12 Resources, Barriers, and Pipeline State ABI Types ---\n"); - - check(sizeof(D3D12_RESOURCE_DESC) == 56 && alignof(D3D12_RESOURCE_DESC) == 8, - "D3D12_RESOURCE_DESC size 56 bytes and alignment 8"); - - check(sizeof(D3D12_CLEAR_VALUE) == 20 && alignof(D3D12_CLEAR_VALUE) == 4, - "D3D12_CLEAR_VALUE size 20 bytes and alignment 4"); - - check(sizeof(D3D12_BOX) == 24 && alignof(D3D12_BOX) == 4, - "D3D12_BOX size 24 bytes and alignment 4"); - - check(sizeof(D3D12_VIEWPORT) == 24 && alignof(D3D12_VIEWPORT) == 4, - "D3D12_VIEWPORT size 24 bytes and alignment 4"); - - check(sizeof(D3D12_RECT) == 16 && alignof(D3D12_RECT) == 4, - "D3D12_RECT size 16 bytes and alignment 4"); - - check(sizeof(D3D12_SUBRESOURCE_DATA) == 24 && alignof(D3D12_SUBRESOURCE_DATA) == 8, - "D3D12_SUBRESOURCE_DATA size 24 bytes and alignment 8"); - - check(sizeof(D3D12_MEMCPY_DEST) == 24 && alignof(D3D12_MEMCPY_DEST) == 8, - "D3D12_MEMCPY_DEST size 24 bytes and alignment 8"); - - check(sizeof(D3D12_RESOURCE_BARRIER) == 32 && alignof(D3D12_RESOURCE_BARRIER) == 8, - "D3D12_RESOURCE_BARRIER size 32 bytes and alignment 8"); - - check(sizeof(D3D12_COMPUTE_PIPELINE_STATE_DESC) == 56 && - alignof(D3D12_COMPUTE_PIPELINE_STATE_DESC) == 8, - "D3D12_COMPUTE_PIPELINE_STATE_DESC size 56 bytes and alignment 8"); - - check(sizeof(D3D12_SHADER_BYTECODE) == 16 && alignof(D3D12_SHADER_BYTECODE) == 8, - "D3D12_SHADER_BYTECODE size 16 bytes and alignment 8"); -} - -void test_xmem_alloc_alignment_and_types() { - std::printf("\n--- Testing XMem Allocator ABI Types and Alignment Constraints ---\n"); - - check(kXMemAllocAlignment == 64, "XMem allocation alignment requirement is 64 bytes"); - - // Test alignment predicate with simulated pointers - alignas(64) uint8_t buffer[128]; - const uintptr_t aligned_addr = reinterpret_cast(buffer); - check((aligned_addr & (kXMemAllocAlignment - 1)) == 0, - "64-byte aligned address satisfies (ptr & 63) == 0 constraint"); - - const uintptr_t unaligned_addr = aligned_addr + 8; - check((unaligned_addr & (kXMemAllocAlignment - 1)) != 0, - "Non-64-byte aligned offset is correctly identified"); - - // Check function pointer type sizes and standard layout - check(sizeof(XMemAllocFn) == 8 && sizeof(XMemFreeFn) == 8, - "XMemAlloc and XMemFree function pointers are 8 bytes on x64"); - - check(sizeof(XMemVirtualQueryFn) == 8 && sizeof(XMemGetWorkingSetStatisticsFn) == 8, - "XMemVirtualQuery and XMemGetWorkingSetStatistics function pointers are 8 bytes on x64"); -} - -void test_xmem_virtual_query_abi_layout() { - std::printf("\n--- Testing XMem VirtualQuery Output Buffer Layout ---\n"); - - check(sizeof(MEMORY_BASIC_INFORMATION) == 48 && alignof(MEMORY_BASIC_INFORMATION) == 8, - "MEMORY_BASIC_INFORMATION size 48 bytes with 8-byte alignment"); - - check(kXMemVirtualQueryOutSize == 64, - "XMemVirtualQuery output buffer contract is 64 bytes"); - - // Exercise VirtualQuery with actual Windows SDK call into a 64-byte output buffer - alignas(64) uint8_t out64[kXMemVirtualQueryOutSize]; - std::memset(out64, 0xA5, sizeof(out64)); - - MEMORY_BASIC_INFORMATION mbi{}; - const SIZE_T written = VirtualQuery(&mbi, &mbi, sizeof(mbi)); - check(written == sizeof(mbi), "VirtualQuery returns exact MEMORY_BASIC_INFORMATION size (48)"); - - std::memcpy(out64, &mbi, sizeof(mbi)); - std::memset(out64 + sizeof(mbi), 0, kXMemVirtualQueryOutSize - sizeof(mbi)); - - // Verify prefix matches MEMORY_BASIC_INFORMATION - MEMORY_BASIC_INFORMATION readback{}; - std::memcpy(&readback, out64, sizeof(readback)); - check(readback.BaseAddress == mbi.BaseAddress && - readback.RegionSize == mbi.RegionSize && - readback.State == mbi.State, - "Output buffer prefix exactly holds MEMORY_BASIC_INFORMATION fields"); - - // Verify trailing 16 bytes are cleanly zeroed - bool tail_is_zero = true; - for (size_t i = sizeof(mbi); i < kXMemVirtualQueryOutSize; ++i) { - if (out64[i] != 0) { - tail_is_zero = false; - break; - } - } - check(tail_is_zero, "Output buffer trailing 16 bytes are zero-filled"); -} - -void test_xmem_working_set_statistics_abi_layout() { - std::printf("\n--- Testing XMem Working Set Statistics ABI Layout ---\n"); - - check(sizeof(PROCESS_MEMORY_COUNTERS) == 72 && alignof(PROCESS_MEMORY_COUNTERS) == 8, - "PROCESS_MEMORY_COUNTERS size 72 bytes with 8-byte alignment"); - - check(offsetof(PROCESS_MEMORY_COUNTERS, WorkingSetSize) == 16, - "PROCESS_MEMORY_COUNTERS WorkingSetSize is at offset 16"); - - PROCESS_MEMORY_COUNTERS pmc{}; - const BOOL ok = GetProcessMemoryInfo(GetCurrentProcess(), &pmc, sizeof(pmc)); - check(ok != FALSE && pmc.WorkingSetSize > 0, - "GetProcessMemoryInfo succeeds and returns non-zero WorkingSetSize"); - - // Verify FidelityFX / XMem layout contract (RT-220): - // The measured FSR sites establish argument shape, kind and the +8 working-set read; +0's title-total memory - // limit is inferred from other Series implementations (xcl, xbox-emulator). - // stats[0..7] = TotalMemoryLimit (uint64_t), stats[8..15] = WorkingSetSize (uint64_t) - alignas(64) uint8_t stats[64]; - std::memset(stats, 0xA5, sizeof(stats)); - - std::memset(stats, 0, 16); - MEMORYSTATUSEX ms{sizeof(ms)}; - uint64_t total_memory = 12ULL * 1024 * 1024 * 1024; - if (GlobalMemoryStatusEx(&ms) && ms.ullTotalPhys != 0) { - total_memory = ms.ullTotalPhys; - } - std::memcpy(stats + 0, &total_memory, sizeof(total_memory)); - const uint64_t working_set = static_cast(pmc.WorkingSetSize); - std::memcpy(stats + 8, &working_set, sizeof(working_set)); - - uint64_t prefix0 = 0; - std::memcpy(&prefix0, stats, sizeof(prefix0)); - check(prefix0 == total_memory && prefix0 >= working_set, - "Working set statistics total memory at +0 holds title memory limit >= working set"); - - uint64_t extracted_ws = 0; - std::memcpy(&extracted_ws, stats + 8, sizeof(extracted_ws)); - check(extracted_ws == working_set, - "Working set statistics size at +8 holds 64-bit working set bytes"); - - bool tail_untouched = true; - for (size_t i = 16; i < sizeof(stats); ++i) { - if (stats[i] != 0xA5) { - tail_untouched = false; - break; - } - } - check(tail_untouched, "Working set statistics buffer bytes 16..63 remain untouched"); -} - -void test_d3d12_xbox_create_device_params_abi() { - std::printf("\n--- Testing D3D12XboxCreateDevice Parameter Layout ABI ---\n"); - - // Measured parameter block in d3d12_xs is 24 32-bit words (96 bytes) - constexpr size_t kWordCount = 24; - constexpr size_t kParamsSize = kWordCount * sizeof(uint32_t); - check(kParamsSize == 96, "D3D12XboxCreateDevice params block is 24 words (96 bytes)"); - - std::array params{}; - for (size_t i = 0; i < kWordCount; ++i) { - params[i] = static_cast(0x1000 + i); - } - - check(params[0] == 0x1000 && params[23] == 0x1017, - "Parameter block words are indexed contiguously as 32-bit integers"); -} - -} // namespace - -int main() { - std::printf("test_runtime_types: verifying D3D12/XMem ABI type alignment and structure sizes\n"); - - test_d3d12_root_signature_abi(); - test_d3d12_handles_and_views_abi(); - test_d3d12_resources_and_pipeline_abi(); - test_xmem_alloc_alignment_and_types(); - test_xmem_virtual_query_abi_layout(); - test_xmem_working_set_statistics_abi_layout(); - test_d3d12_xbox_create_device_params_abi(); - - std::printf("\n------------------------------------------------------------\n"); - if (g_failures == 0) { - std::printf("test_runtime_types: OK (%d checks)\n", g_checks); - return 0; - } else { - std::printf("test_runtime_types: FAILED (%d checks, %d failure%s)\n", - g_checks, g_failures, g_failures == 1 ? "" : "s"); - return 1; - } -} diff --git a/runtime/test/test_temp_dir.h b/runtime/test/test_temp_dir.h deleted file mode 100644 index 3bc9712d3..000000000 --- a/runtime/test/test_temp_dir.h +++ /dev/null @@ -1,83 +0,0 @@ -// Scratch folders for tests that write files (a translator-style shader library, an index) under the temp directory. -// -// The folder name carries the process id. Under one fixed name, every copy of a test running at the same time (ctest -// -j, or two suites sharing one Wine prefix or one TMPDIR) used the same folder, and one copy's remove_all deleted the -// modules another copy was still loading: with four copies of d3d12_compute at once, 6 of 40 runs failed at PSO -// creation or in copy_file, while 125 runs one at a time all passed (Apple M3 Max, MoltenVK 1.4.3 under Wine 11). -#pragma once - -#include -#include -#include -#include -#include - -#ifdef _WIN32 -// Not every includer is built with these (shader_library_test and mods_test are not, and use std::min). -#ifndef WIN32_LEAN_AND_MEAN -#define WIN32_LEAN_AND_MEAN -#endif -#ifndef NOMINMAX -#define NOMINMAX -#endif -#include - -#include -#else -#include -#endif - -namespace testfiles { - -// /_: a folder no other running process uses. -inline std::filesystem::path process_temp_dir(std::string_view name) { -#ifdef _WIN32 - const long pid = long(_getpid()); -#else - const long pid = long(getpid()); -#endif - return std::filesystem::temp_directory_path() / (std::string(name) + "_" + std::to_string(pid)); -} - -// process_temp_dir(name), emptied and created on construction (a crashed run may have left the same name behind) and -// removed with its contents on destruction, so early returns don't leave one folder per failed run. -class ScratchDir { -public: - explicit ScratchDir(std::string_view name) : path_(process_temp_dir(name)) { - std::error_code ec; - std::filesystem::remove_all(path_, ec); - std::filesystem::create_directories(path_, ec); - if (ec) std::fprintf(stderr, "cannot create %s: %s\n", path_.string().c_str(), ec.message().c_str()); - } - ~ScratchDir() { - std::error_code ec; - std::filesystem::remove_all(path_, ec); - } - ScratchDir(const ScratchDir&) = delete; - ScratchDir& operator=(const ScratchDir&) = delete; - - const std::filesystem::path& path() const { return path_; } - -private: - std::filesystem::path path_; -}; - -// Copies `from` (a file the build compiled into the test, LEONIDA_TEST_*_SPV) to `to`, overwriting it. Returns false -// and says why when it can't: std::filesystem::copy_file would throw instead, and the uncaught exception ends the -// test without a message (abort; exit code 3 under Wine), which reads as a crash rather than a missing file. -inline bool copy_file(const std::filesystem::path& from, const std::filesystem::path& to) { - std::error_code ec; -#ifdef _WIN32 - // CopyFileW, not std::filesystem::copy_file: MSVC's copy_file calls CopyFile2, which Wine 9 doesn't implement. - // The call aborts the test there and starts Wine's debugger, which waits until the test's time limit. - if (!CopyFileW(from.c_str(), to.c_str(), FALSE)) - ec.assign(static_cast(GetLastError()), std::system_category()); -#else - std::filesystem::copy_file(from, to, std::filesystem::copy_options::overwrite_existing, ec); -#endif - if (ec) std::fprintf(stderr, "cannot copy %s to %s: %s\n", from.string().c_str(), to.string().c_str(), - ec.message().c_str()); - return !ec; -} - -} // namespace testfiles diff --git a/runtime/test/tiny_game_abort_test.cpp b/runtime/test/tiny_game_abort_test.cpp deleted file mode 100644 index 06f28b01f..000000000 --- a/runtime/test/tiny_game_abort_test.cpp +++ /dev/null @@ -1,86 +0,0 @@ -// Check that abort() from a mapped guest raises SIGABRT when the guest installed a handler, and keeps gta6rt's -// recorded abort code (3) for the default, ignored and returning-handler cases. Each mode runs natively too: the -// handler case must match, while the other three intentionally differ (current UCRT fail-fasts with 0xC0000409 -// after the raise, where gta6rt ends the run with its documented code). Wine's ucrtbase (9.0, the wine of Ubuntu -// 24.04 LTS) ends those three native runs with _exit(3) instead, so the native reference also accepts 3 there. -// No game files. -#include - -#include -#include -#include - -namespace { -int failures = 0; - -constexpr DWORD kFailFast = 0xC0000409; // STATUS_STACK_BUFFER_OVERRUN: __fastfail, as current UCRT's abort() ends -constexpr DWORD kAbortExit = 3; // abort()'s documented _exit(3), which Wine's ucrtbase still uses - -// `also` is a second exit code that counts as the expected one (the same as `want` when there is none). -bool run(const std::wstring& exe, const std::wstring& args, const char* what, DWORD want, DWORD also) { - std::wstring command = L"\"" + exe + L"\" " + args; - STARTUPINFOW startup{}; - startup.cb = sizeof(startup); - PROCESS_INFORMATION child{}; - if (!CreateProcessW(exe.c_str(), command.data(), nullptr, nullptr, TRUE, 0, nullptr, nullptr, &startup, &child)) { - std::fprintf(stderr, "FAIL %s: could not start (Win32 error %lu)\n", what, GetLastError()); - ++failures; - return false; - } - CloseHandle(child.hThread); - DWORD code = 0; - const DWORD wait = WaitForSingleObject(child.hProcess, 30000); - const bool exited = wait == WAIT_OBJECT_0 && GetExitCodeProcess(child.hProcess, &code); - if (wait == WAIT_TIMEOUT) TerminateProcess(child.hProcess, 1); - CloseHandle(child.hProcess); - if (!exited) { - std::fprintf(stderr, "FAIL %s: could not collect the exit code (wait %#lx)\n", what, wait); - ++failures; - return false; - } - if (code != want && code != also) { - if (also != want) - std::fprintf(stderr, "FAIL %s: exit code %lu, expected %lu or %lu\n", what, code, want, also); - else - std::fprintf(stderr, "FAIL %s: exit code %lu, expected %lu\n", what, code, want); - ++failures; - return false; - } - std::printf("PASS %s (exit %lu)\n", what, code); - return true; -} -} // namespace - -int wmain(int argc, wchar_t** argv) { - if (argc != 3) { - std::fprintf(stderr, "usage: tiny_game_abort_test \n"); - return 1; - } - struct Case { - const char* mode; - DWORD native_code; - DWORD loader_code; - }; - static const Case cases[] = { - {"abort-handler", 43, 43}, // the handler ends the run itself, so abort cannot overwrite its code - {"abort-crt-exit", 43, 43}, // the same through the guest's shimmed exit() import - {"abort-return", kFailFast, kAbortExit}, - {"abort-ignore", kFailFast, kAbortExit}, - {"abort-default", kFailFast, kAbortExit}, - }; - for (const Case& c : cases) { - const std::wstring mode(c.mode, c.mode + std::strlen(c.mode)); - const std::wstring guest = L"hello 42 " + mode; - const std::string native = std::string("native ") + c.mode; - const std::string loaded = std::string("gta6rt ") + c.mode; - run(argv[2], guest, native.c_str(), c.native_code, c.native_code == kFailFast ? kAbortExit : c.native_code); - run(argv[1], L"--run \"" + std::wstring(argv[2]) + L"\" -- " + guest, loaded.c_str(), c.loader_code, - c.loader_code); - } - if (failures) { - std::fprintf(stderr, "%d abort exit-code check(s) failed\n", failures); - return 1; - } - std::printf("all abort exit-code checks passed\n"); - return 0; -} diff --git a/runtime/test/tiny_game_exit_code_test.cpp b/runtime/test/tiny_game_exit_code_test.cpp deleted file mode 100644 index 8e8bc5e57..000000000 --- a/runtime/test/tiny_game_exit_code_test.cpp +++ /dev/null @@ -1,227 +0,0 @@ -// Check the exact process exit code returned by gta6rt after the synthetic guest exits. -#include - -#include -#include -#include - -namespace { - -constexpr DWORD kProcessWaitTimeoutMs = 30000; - -enum class ExitQueryStatus { - exited, - timed_out, - wait_failed, - unexpected_wait_result, - exit_code_failed, -}; - -struct ExitQueryResult { - ExitQueryStatus status; - DWORD wait_result; - DWORD win32_error; - DWORD exit_code; -}; - -struct ProcessApi { - DWORD(WINAPI* wait)(HANDLE, DWORD); - BOOL(WINAPI* get_exit_code)(HANDLE, LPDWORD); - DWORD(WINAPI* last_error)(); -}; - -struct FakeProcessApiState { - DWORD wait_result = WAIT_OBJECT_0; - BOOL get_exit_code_succeeds = TRUE; - DWORD error = ERROR_SUCCESS; - DWORD exit_code = 42; - unsigned wait_calls = 0; - unsigned get_exit_code_calls = 0; - unsigned last_error_calls = 0; - unsigned last_operation = 0; - unsigned last_error_observed_after = 0; -}; - -FakeProcessApiState g_fake_api_state; - -DWORD WINAPI fake_wait(HANDLE, DWORD) { - ++g_fake_api_state.wait_calls; - g_fake_api_state.last_operation = 1; - if (g_fake_api_state.wait_result == WAIT_FAILED) { - g_fake_api_state.error = ERROR_INVALID_HANDLE; - } - return g_fake_api_state.wait_result; -} - -BOOL WINAPI fake_get_exit_code(HANDLE, LPDWORD exit_code) { - ++g_fake_api_state.get_exit_code_calls; - g_fake_api_state.last_operation = 2; - if (!g_fake_api_state.get_exit_code_succeeds) { - g_fake_api_state.error = ERROR_ACCESS_DENIED; - return FALSE; - } - *exit_code = g_fake_api_state.exit_code; - return TRUE; -} - -DWORD WINAPI fake_last_error() { - ++g_fake_api_state.last_error_calls; - g_fake_api_state.last_error_observed_after = g_fake_api_state.last_operation; - return g_fake_api_state.error; -} - -ExitQueryResult query_exit_code(HANDLE process, const ProcessApi& api) { - const DWORD wait_result = api.wait(process, kProcessWaitTimeoutMs); - if (wait_result == WAIT_TIMEOUT) { - return {ExitQueryStatus::timed_out, wait_result, ERROR_SUCCESS, 0}; - } - if (wait_result == WAIT_FAILED) { - return {ExitQueryStatus::wait_failed, wait_result, api.last_error(), 0}; - } - if (wait_result != WAIT_OBJECT_0) { - return {ExitQueryStatus::unexpected_wait_result, wait_result, ERROR_SUCCESS, 0}; - } - - DWORD exit_code = 0; - if (!api.get_exit_code(process, &exit_code)) { - return {ExitQueryStatus::exit_code_failed, wait_result, api.last_error(), 0}; - } - return {ExitQueryStatus::exited, wait_result, ERROR_SUCCESS, exit_code}; -} - -std::string format_exit_query_failure(const ExitQueryResult& result) { - char message[160]{}; - switch (result.status) { - case ExitQueryStatus::timed_out: - std::snprintf(message, sizeof(message), "timed out waiting for gta6rt after %lu ms (wait result %#lx)\n", - kProcessWaitTimeoutMs, result.wait_result); - break; - case ExitQueryStatus::wait_failed: - std::snprintf(message, sizeof(message), "WaitForSingleObject failed with Win32 error %lu (wait result %#lx)\n", - result.win32_error, result.wait_result); - break; - case ExitQueryStatus::exit_code_failed: - std::snprintf(message, sizeof(message), "GetExitCodeProcess failed with Win32 error %lu after wait result %#lx\n", - result.win32_error, result.wait_result); - break; - case ExitQueryStatus::unexpected_wait_result: - std::snprintf(message, sizeof(message), "WaitForSingleObject returned unexpected wait result %#lx\n", - result.wait_result); - break; - case ExitQueryStatus::exited: - break; - } - return message; -} - -bool expect(bool condition, std::string_view description) { - if (condition) { - return true; - } - std::fprintf(stderr, "exit-code diagnostic self-test failed: %.*s\n", static_cast(description.size()), - description.data()); - return false; -} - -void reset_fake_api() { - g_fake_api_state = {}; -} - -bool run_diagnostic_self_tests() { - bool passed = true; - const ProcessApi fake_api{fake_wait, fake_get_exit_code, fake_last_error}; - - reset_fake_api(); - g_fake_api_state.wait_result = WAIT_FAILED; - ExitQueryResult result = query_exit_code(nullptr, fake_api); - passed &= expect(result.status == ExitQueryStatus::wait_failed, "WAIT_FAILED is classified as a wait failure"); - passed &= expect(result.win32_error == ERROR_INVALID_HANDLE, "wait failure preserves GetLastError"); - passed &= expect(g_fake_api_state.get_exit_code_calls == 0, "exit code is not queried after a wait failure"); - passed &= expect(g_fake_api_state.last_error_calls == 1 && g_fake_api_state.last_error_observed_after == 1, - "wait error is captured immediately after WaitForSingleObject"); - passed &= expect(format_exit_query_failure(result) == - "WaitForSingleObject failed with Win32 error 6 (wait result 0xffffffff)\n", - "wait failure diagnostic names the failing API and error"); - - reset_fake_api(); - g_fake_api_state.get_exit_code_succeeds = FALSE; - result = query_exit_code(nullptr, fake_api); - passed &= expect(result.status == ExitQueryStatus::exit_code_failed, - "GetExitCodeProcess failure is classified separately"); - passed &= expect(result.win32_error == ERROR_ACCESS_DENIED, "exit code failure preserves GetLastError"); - passed &= expect(g_fake_api_state.last_error_calls == 1 && g_fake_api_state.last_error_observed_after == 2, - "exit code error is captured immediately after GetExitCodeProcess"); - passed &= expect(format_exit_query_failure(result) == - "GetExitCodeProcess failed with Win32 error 5 after wait result 0\n", - "exit code failure diagnostic names the failing API and error"); - - reset_fake_api(); - g_fake_api_state.wait_result = WAIT_TIMEOUT; - result = query_exit_code(nullptr, fake_api); - passed &= expect(result.status == ExitQueryStatus::timed_out, "timeout remains distinct from API failure"); - passed &= expect(g_fake_api_state.get_exit_code_calls == 0 && g_fake_api_state.last_error_calls == 0, - "timeout neither queries the exit code nor reports a stale Win32 error"); - passed &= expect(format_exit_query_failure(result) == - "timed out waiting for gta6rt after 30000 ms (wait result 0x102)\n", - "timeout diagnostic retains its duration and wait result"); - - reset_fake_api(); - g_fake_api_state.wait_result = WAIT_ABANDONED; - result = query_exit_code(nullptr, fake_api); - passed &= expect(result.status == ExitQueryStatus::unexpected_wait_result, - "unexpected wait results are not reported as API failures"); - passed &= expect(g_fake_api_state.get_exit_code_calls == 0 && g_fake_api_state.last_error_calls == 0, - "unexpected wait results do not query the exit code or report a stale Win32 error"); - passed &= expect(format_exit_query_failure(result) == "WaitForSingleObject returned unexpected wait result 0x80\n", - "unexpected wait diagnostic includes the returned value"); - - reset_fake_api(); - result = query_exit_code(nullptr, fake_api); - passed &= expect(result.status == ExitQueryStatus::exited && result.exit_code == 42, - "successful wait returns the process exit code"); - passed &= expect(g_fake_api_state.last_error_calls == 0, "successful query does not read a stale Win32 error"); - return passed; -} - -} // namespace - -int wmain(int argc, wchar_t** argv) { - if (!run_diagnostic_self_tests()) { - return 1; - } - if (argc == 2 && std::wstring_view(argv[1]) == L"--self-test") { - return 0; - } - if (argc != 3) { - std::fprintf(stderr, "usage: tiny_game_exit_code_test \n"); - return 1; - } - - std::wstring command = L"\"" + std::wstring(argv[1]) + L"\" --run \"" + argv[2] + L"\" -- hello 42 exit-code"; - STARTUPINFOW startup{}; - startup.cb = sizeof(startup); - PROCESS_INFORMATION child{}; - if (!CreateProcessW(argv[1], command.data(), nullptr, nullptr, TRUE, 0, nullptr, nullptr, &startup, &child)) { - std::fprintf(stderr, "could not start gta6rt (Win32 error %lu)\n", GetLastError()); - return 1; - } - CloseHandle(child.hThread); - - const ProcessApi process_api{WaitForSingleObject, GetExitCodeProcess, GetLastError}; - const ExitQueryResult result = query_exit_code(child.hProcess, process_api); - if (result.status == ExitQueryStatus::timed_out) { - TerminateProcess(child.hProcess, 1); - } - CloseHandle(child.hProcess); - if (result.status != ExitQueryStatus::exited) { - const std::string message = format_exit_query_failure(result); - std::fputs(message.c_str(), stderr); - return 1; - } - if (result.exit_code != 42) { - std::fprintf(stderr, "gta6rt exited with code %lu, expected guest exit code 42\n", result.exit_code); - return 1; - } - std::printf("gta6rt returned the expected guest exit code 42\n"); - return 0; -} diff --git a/runtime/test/typeless_rtv_test.cpp b/runtime/test/typeless_rtv_test.cpp deleted file mode 100644 index c3368766d..000000000 --- a/runtime/test/typeless_rtv_test.cpp +++ /dev/null @@ -1,346 +0,0 @@ -// CPU-only replay tests for typed RGBA8 views. No Vulkan loader, GPU or game data. -#include "../src/vulkan_replay.h" -#include -#include -#include -#include - -#define EXPECT(condition) do { \ - if (!(condition)) { std::fprintf(stderr, "line %d: %s\n", __LINE__, #condition); return 1; } \ -} while (0) - -namespace { -unsigned image_clears = 0, attachment_clears = 0; -VkFormat requested_format = VK_FORMAT_UNDEFINED; -VkClearColorValue captured{}; -VkClearRect captured_rect{}; -VkRect2D render_area{}; -VkImageSubresourceRange requested_range{}; -unsigned rendering_layers = 0; -VKAPI_ATTR void VKAPI_CALL barrier(VkCommandBuffer, VkPipelineStageFlags, VkPipelineStageFlags, VkDependencyFlags, - std::uint32_t, const VkMemoryBarrier*, std::uint32_t, const VkBufferMemoryBarrier*, - std::uint32_t, const VkImageMemoryBarrier*) {} -VKAPI_ATTR void VKAPI_CALL clear(VkCommandBuffer, VkImage, VkImageLayout, const VkClearColorValue* value, - std::uint32_t, const VkImageSubresourceRange*) { captured = *value; ++image_clears; } -VKAPI_ATTR void VKAPI_CALL begin(VkCommandBuffer, const VkRenderingInfo* info) { - render_area = info->renderArea; - rendering_layers = info->layerCount; -} -VKAPI_ATTR void VKAPI_CALL end(VkCommandBuffer) {} -VKAPI_ATTR void VKAPI_CALL attachments(VkCommandBuffer, std::uint32_t n, const VkClearAttachment* values, - std::uint32_t count, const VkClearRect* rects) { - if (n == 1 && count == 1) { captured = values[0].clearValue.color; captured_rect = rects[0]; ++attachment_clears; } -} -leonida::ReplayFunctions functions() { - leonida::ReplayFunctions vk{}; - vk.pipeline_barrier = barrier; - vk.clear_color_image = clear; - vk.begin_rendering = begin; - vk.end_rendering = end; - vk.clear_attachments = attachments; - vk.image_view = [](const auto& binding, const auto& range) { - requested_range = range; - requested_format = binding.format; - return reinterpret_cast(std::uintptr_t{1}); - }; - return vk; -} -leonida::ResourceBinding resource() { - leonida::ResourceBinding r{}; - r.image = reinterpret_cast(std::uintptr_t{1}); - r.format = VK_FORMAT_R8G8B8A8_UNORM; - r.width = 5; r.height = 3; - r.typeless = true; - return r; -} -void reset_counters() { - image_clears = attachment_clears = 0; - requested_format = VK_FORMAT_UNDEFINED; - captured = {}; captured_rect = {}; render_area = {}; - requested_range = {}; rendering_layers = 0; -} -leonida::ReplayResult run(const leonida::CommandList& list, const leonida::ResourceBinding& resource, - const leonida::ReplayFunctions& vk) { - reset_counters(); - return leonida::replay(list, VK_NULL_HANDLE, [&](auto) { return &resource; }, vk); -} -} // namespace - -int main() { - using namespace leonida; - const auto vk = functions(); - const auto binding = resource(); - const ClearColor color{1.5f, 2.5f, 256, -1}; - const Rect rectangle{1, 1, 4, 3}; - const std::pair formats[] = { - {ColorViewFormat::rgba8_unorm, VK_FORMAT_R8G8B8A8_UNORM}, - {ColorViewFormat::rgba8_srgb, VK_FORMAT_R8G8B8A8_SRGB}, - {ColorViewFormat::rgba8_uint, VK_FORMAT_R8G8B8A8_UINT}, - {ColorViewFormat::rgba8_sint, VK_FORMAT_R8G8B8A8_SINT}, - {ColorViewFormat::rgba8_snorm, VK_FORMAT_R8G8B8A8_SNORM}, - }; - unsigned checks = 0; - for (const auto& [format, expected] : formats) { - for (const bool rect : {false, true}) { - CommandList list; - TargetView target{1, 0, 0, 1, format}; - EXPECT(list.clear_render_target(target, color, rect ? std::span(&rectangle, 1) : std::span{})); - target.format = ColorViewFormat::resource; // Mutating the descriptor must not change the recorded format. - EXPECT(list.close()); - EXPECT(run(list, binding, vk) == ReplayResult::success); - const bool attachment = rect || format != ColorViewFormat::rgba8_unorm; - EXPECT(image_clears == unsigned(!attachment) && attachment_clears == unsigned(attachment)); - if (attachment) { - EXPECT(requested_format == expected); - EXPECT(render_area.extent.width == 5 && render_area.extent.height == 3); - EXPECT(captured_rect.rect.offset.x == (rect ? 1 : 0)); - EXPECT(captured_rect.rect.offset.y == (rect ? 1 : 0)); - EXPECT(captured_rect.rect.extent.width == (rect ? 3u : 5u)); - EXPECT(captured_rect.rect.extent.height == (rect ? 2u : 3u)); - } - if (format == ColorViewFormat::rgba8_uint) { - EXPECT(captured.uint32[0] == 1 && captured.uint32[1] == 2 && captured.uint32[2] == 255 && captured.uint32[3] == 0); - } else if (format == ColorViewFormat::rgba8_sint) { - EXPECT(captured.int32[0] == 1 && captured.int32[1] == 2 && captured.int32[2] == 127 && captured.int32[3] == -1); - } else { - // UNORM and sRGB views round and clamp like D3D (render_target_clear_color): 1.5 and 256 are 1.0, -1 is 0. - const VkClearColorValue converted = leonida::detail::render_target_clear_color(expected, color); - EXPECT(std::memcmp(captured.float32, converted.float32, sizeof(captured)) == 0); - } - ++checks; - } - } - // Whole-view clears must keep main's predication attachment path, including same-format UNORM. - auto conditional = vk; - conditional.begin_conditional_rendering = +[](VkCommandBuffer, const VkConditionalRenderingBeginInfoEXT*) {}; - conditional.end_conditional_rendering = end; - conditional.prepare_predicate = [](VkBuffer source, VkDeviceSize offset, PredicateCapture& out) { - out = {source, offset, reinterpret_cast(std::uintptr_t{3}), 0, VK_NULL_HANDLE}; return true; - }; - conditional.capture_predicate = [](VkCommandBuffer, const PredicateCapture&) {}; - ResourceBinding predicate{}; - predicate.buffer = reinterpret_cast(std::uintptr_t{2}); - predicate.size = 8; - for (const auto& [format, expected] : formats) { - CommandList predicated; - EXPECT(predicated.set_predication({2, 0, d3d12_predication::equal_zero})); - EXPECT(predicated.clear_render_target({1, 0, 0, 1, format}, color) && predicated.close()); - PreparedList prepared; - reset_counters(); - const auto resolve = [&](ResourceId id) { return id == 2 ? &predicate : &binding; }; - EXPECT(prepare(predicated, resolve, conditional, prepared) == ReplayResult::success); - EXPECT(prepared.commands[1].rects.size() == 1); - EXPECT(prepared.commands[1].rects[0].rect.extent.width == binding.width); - EXPECT(prepared.commands[1].rects[0].rect.extent.height == binding.height); - EXPECT(requested_format == expected); - ++checks; - } - // Eight bytes, not just the low word, must fit; missing/rejected preparation cannot emit any clears. - { - CommandList list; - EXPECT(list.set_predication({2, 0, d3d12_predication::equal_zero})); - EXPECT(list.clear_render_target({1, 0, 0, 1, ColorViewFormat::rgba8_uint}, color) && list.close()); - auto short_buffer = predicate; short_buffer.size = 4; - PreparedList prepared; - auto resolve = [&](ResourceId id) { return id == 2 ? &short_buffer : &binding; }; - EXPECT(prepare(list, resolve, conditional, prepared) == ReplayResult::invalid_predication); - short_buffer.size = 8; - EXPECT(prepare(list, resolve, conditional, prepared) == ReplayResult::success); - auto unavailable = conditional; unavailable.prepare_predicate = {}; - EXPECT(prepare(list, resolve, unavailable, prepared) == ReplayResult::unsupported); - unavailable = conditional; - unavailable.prepare_predicate = [](VkBuffer, VkDeviceSize, PredicateCapture&) { return false; }; - EXPECT(prepare(list, resolve, unavailable, prepared) == ReplayResult::unsupported); - checks += 4; - } - { - QueryPool statistics{}; - statistics.pool = reinterpret_cast(std::uintptr_t{4}); - statistics.heap_type = d3d12_query_heap::pipeline_statistics; statistics.count = 1; - auto queries = conditional; - queries.reset_query_pool = +[](VkCommandBuffer, VkQueryPool, std::uint32_t, std::uint32_t) {}; - queries.begin_query = +[](VkCommandBuffer, VkQueryPool, std::uint32_t, VkQueryControlFlags) {}; - queries.end_query = +[](VkCommandBuffer, VkQueryPool, std::uint32_t) {}; - queries.write_timestamp = +[](VkCommandBuffer, VkPipelineStageFlagBits, VkQueryPool, std::uint32_t) {}; - queries.copy_query_pool_results = +[](VkCommandBuffer, VkQueryPool, std::uint32_t, std::uint32_t, - VkBuffer, VkDeviceSize, VkDeviceSize, VkQueryResultFlags) {}; - queries.fill_buffer = +[](VkCommandBuffer, VkBuffer, VkDeviceSize, VkDeviceSize, std::uint32_t) {}; - queries.query_pool = [&](QueryHeapId) { return &statistics; }; - for (bool inside : {false, true}) { - CommandList list; - if (!inside) EXPECT(list.set_predication({2, 0, d3d12_predication::equal_zero})); - EXPECT(list.begin_query({3, d3d12_query::pipeline_statistics, 0})); - if (inside) EXPECT(list.set_predication({2, 0, d3d12_predication::equal_zero})); - EXPECT(list.end_query({3, d3d12_query::pipeline_statistics, 0}) && list.close()); - PreparedList prepared; - const auto resolve = [&](ResourceId id) { return id == 2 ? &predicate : &binding; }; - EXPECT(prepare(list, resolve, queries, prepared) == - (inside ? ReplayResult::unsupported : ReplayResult::success)); - EXPECT(prepare(list, resolve, queries, prepared, true) == ReplayResult::success); - EXPECT(prepared.statistics_segment_count == (inside ? 2u : 0u)); - ++checks; - } - } - auto layered = binding; - layered.mip_levels = 3; layered.array_layers = 4; - for (const auto& [format, expected] : formats) { - for (unsigned mip = 0; mip < 3; ++mip) { - CommandList subresources; - const Rect oversized{-2, -3, 20, 30}; - EXPECT(subresources.clear_render_target({1, mip, 1, 2, format}, color, {&oversized, 1})); - EXPECT(subresources.close() && run(subresources, layered, vk) == ReplayResult::success); - EXPECT(requested_format == expected); - EXPECT(requested_range.baseMipLevel == mip && requested_range.levelCount == 1); - EXPECT(requested_range.baseArrayLayer == 1 && requested_range.layerCount == 2); - EXPECT(rendering_layers == 2 && captured_rect.baseArrayLayer == 0 && captured_rect.layerCount == 2); - EXPECT(render_area.extent.width == std::max(1u, 5u >> mip)); - EXPECT(render_area.extent.height == std::max(1u, 3u >> mip)); - EXPECT(captured_rect.rect.extent.width == render_area.extent.width); - EXPECT(captured_rect.rect.extent.height == render_area.extent.height); - ++checks; - } - } - // A predicate must preserve the selected mip/range and use attachments even for a whole UNORM view. - for (const auto& [format, expected] : formats) { - for (unsigned mip = 0; mip < 3; ++mip) { - for (bool partial : {false, true}) { - CommandList list; - const Rect oversized{-1, -1, 8, 8}; - EXPECT(list.set_predication({2, 0, d3d12_predication::equal_zero})); - EXPECT(list.clear_render_target({1, mip, 1, 2, format}, color, - partial ? std::span(&oversized, 1) : std::span{})); - EXPECT(list.close()); - const auto resolve = [&](ResourceId id) { return id == 2 ? &predicate : &layered; }; - reset_counters(); - EXPECT(replay(list, VK_NULL_HANDLE, resolve, conditional) == ReplayResult::success); - EXPECT(image_clears == 0 && attachment_clears == 1); - EXPECT(requested_format == expected && requested_range.baseMipLevel == mip); - EXPECT(requested_range.baseArrayLayer == 1 && requested_range.layerCount == 2); - EXPECT(render_area.extent.width == std::max(1u, 5u >> mip)); - EXPECT(render_area.extent.height == std::max(1u, 3u >> mip)); - EXPECT(rendering_layers == 2 && captured_rect.baseArrayLayer == 0 && captured_rect.layerCount == 2); - EXPECT(captured_rect.rect.offset.x == 0 && captured_rect.rect.offset.y == 0); - EXPECT(captured_rect.rect.extent.width == render_area.extent.width); - EXPECT(captured_rect.rect.extent.height == render_area.extent.height); - ++checks; - } - } - } - const auto rejects = [&](ResourceBinding r, TargetView view, ReplayResult expected = ReplayResult::invalid_clear) { - CommandList list; - if (!list.clear_render_target(view, color) || !list.close()) return false; - return run(list, r, vk) == expected && !image_clears && !attachment_clears; - }; - EXPECT(rejects(binding, {1, 0, 0, 1})); // A typeless resource has no default typed RTV format. - EXPECT(rejects(binding, {1, 0, 0, 1, static_cast(99)})); - for (const TargetView view : { - TargetView{1, 3, 0, 1, ColorViewFormat::rgba8_uint}, - TargetView{1, UINT32_MAX, 0, 1, ColorViewFormat::rgba8_uint}, - TargetView{1, 0, 4, 1, ColorViewFormat::rgba8_uint}, - TargetView{1, 0, 3, 2, ColorViewFormat::rgba8_uint}, - TargetView{1, 0, 1, UINT32_MAX, ColorViewFormat::rgba8_uint}, - TargetView{1, 0, UINT32_MAX, 2, ColorViewFormat::rgba8_uint}}) { - EXPECT(rejects(layered, view, ReplayResult::invalid_subresource)); - ++checks; - } - CommandList empty_range; - EXPECT(!empty_range.clear_render_target({1, 0, 0, 0, ColorViewFormat::rgba8_uint}, color)); - ++checks; - // Both a range ending at the last layer and the complete layer range remain valid. - for (const TargetView view : {TargetView{1, 2, 3, 1, ColorViewFormat::rgba8_uint}, - TargetView{1, 2, 0, 4, ColorViewFormat::rgba8_uint}}) { - CommandList list; - const Rect whole{0, 0, 1, 1}; - EXPECT(list.clear_render_target(view, color, {&whole, 1}) && list.close()); - EXPECT(run(list, layered, vk) == ReplayResult::success); - EXPECT(requested_range.baseMipLevel == 2 && requested_range.baseArrayLayer == view.first_layer); - EXPECT(requested_range.layerCount == view.layer_count && rendering_layers == view.layer_count); - ++checks; - } - auto wrong = binding; wrong.typeless = false; - EXPECT(rejects(wrong, {1, 0, 0, 1, ColorViewFormat::rgba8_srgb})); - wrong = binding; wrong.format = VK_FORMAT_R32_SFLOAT; - EXPECT(rejects(wrong, {1, 0, 0, 1, ColorViewFormat::rgba8_uint})); - wrong = binding; wrong.mip_levels = 2; - EXPECT(rejects(wrong, {1, 2, 0, 1, ColorViewFormat::rgba8_uint}, ReplayResult::invalid_subresource)); - wrong = binding; wrong.array_layers = 2; - EXPECT(rejects(wrong, {1, 0, 1, 2, ColorViewFormat::rgba8_srgb}, ReplayResult::invalid_subresource)); - wrong = binding; wrong.volume = true; - EXPECT(rejects(wrong, {1, 0, 0, 1, ColorViewFormat::rgba8_srgb})); - // A castable RGBA8 or BGRA8 image clears through a view in the other channel order (the device checked that the - // list names it); without a castable list, or for a UINT image, the other order stays refused. - { - const auto bgra8_unorm = static_cast(VK_FORMAT_B8G8R8A8_UNORM); - const auto bgra8_srgb = static_cast(VK_FORMAT_B8G8R8A8_SRGB); - auto castable = binding; castable.typeless = false; castable.castable_view_formats = true; - auto castable_bgra = castable; castable_bgra.format = VK_FORMAT_B8G8R8A8_UNORM; - const std::tuple crossings[] = { - {castable, bgra8_unorm, VK_FORMAT_B8G8R8A8_UNORM}, - {castable, bgra8_srgb, VK_FORMAT_B8G8R8A8_SRGB}, - {castable_bgra, ColorViewFormat::rgba8_unorm, VK_FORMAT_R8G8B8A8_UNORM}, - {castable_bgra, ColorViewFormat::rgba8_srgb, VK_FORMAT_R8G8B8A8_SRGB}, - }; - for (const auto& [image, format, expected] : crossings) { - CommandList cross; - EXPECT(cross.clear_render_target({1, 0, 0, 1, format}, color) && cross.close()); - EXPECT(run(cross, image, vk) == ReplayResult::success); - EXPECT(image_clears == 0 && attachment_clears == 1 && requested_format == expected); - ++checks; - } - auto typed = castable; typed.castable_view_formats = false; - EXPECT(rejects(typed, {1, 0, 0, 1, bgra8_unorm})); - EXPECT(rejects(binding, {1, 0, 0, 1, bgra8_unorm})); // typeless RGBA8: another typeless family - auto uint_image = castable; uint_image.format = VK_FORMAT_R8G8B8A8_UINT; - EXPECT(rejects(uint_image, {1, 0, 0, 1, bgra8_unorm})); - checks += 3; - } - { - auto msaa = binding; msaa.samples = 4; - for (const auto [format, expected] : formats) { - CommandList ms_list; - EXPECT(ms_list.clear_render_target({1, 0, 0, 1, format}, color) && ms_list.close()); - EXPECT(run(ms_list, msaa, vk) == ReplayResult::success); - const bool attachment = format != ColorViewFormat::rgba8_unorm; - EXPECT(image_clears == (attachment ? 0u : 1u) && attachment_clears == (attachment ? 1u : 0u)); - EXPECT(!attachment || (requested_format == expected && rendering_layers == 1)); - ++checks; - } - auto msaa_layered = layered; msaa_layered.mip_levels = 1; msaa_layered.samples = 4; - CommandList ms_layer_list; - EXPECT(ms_layer_list.clear_render_target({1, 0, 1, 2, ColorViewFormat::rgba8_srgb}, color) && - ms_layer_list.close()); - EXPECT(run(ms_layer_list, msaa_layered, vk) == ReplayResult::success); - EXPECT(attachment_clears == 1 && requested_format == VK_FORMAT_R8G8B8A8_SRGB); - EXPECT(requested_range.baseArrayLayer == 1 && requested_range.layerCount == 2 && rendering_layers == 2); - ++checks; - } - checks += 7; - CommandList list; - EXPECT(list.clear_render_target({1, 0, 0, 1, ColorViewFormat::rgba8_srgb}, color) && list.close()); - auto unavailable = vk; unavailable.begin_rendering = nullptr; - EXPECT(run(list, binding, unavailable) == ReplayResult::unsupported && !image_clears && !attachment_clears); - CommandList same_format; - EXPECT(same_format.clear_render_target({1, 0, 0, 1, ColorViewFormat::rgba8_unorm}, color) && same_format.close()); - EXPECT(run(same_format, binding, unavailable) == ReplayResult::success && image_clears == 1 && !attachment_clears); - ++checks; - auto legacy = binding; - legacy.typeless = false; - legacy.format = VK_FORMAT_UNDEFINED; // Existing ownerless float-only replay clients omit this metadata. - CommandList legacy_list; - EXPECT(legacy_list.clear_render_target({1, 0, 0, 1}, color) && legacy_list.close()); - EXPECT(run(legacy_list, legacy, unavailable) == ReplayResult::success && image_clears == 1 && !attachment_clears); - EXPECT(std::memcmp(captured.float32, color.data(), sizeof(captured)) == 0); - ++checks; - CommandList clipped; - const Rect outside{20, 20, 30, 30}; - EXPECT(clipped.clear_render_target({1, 0, 0, 1, ColorViewFormat::rgba8_srgb}, color, {&outside, 1}) && clipped.close()); - EXPECT(run(clipped, binding, vk) == ReplayResult::success && !image_clears && !attachment_clears); - EXPECT(requested_format == VK_FORMAT_UNDEFINED); - CommandList invalid_batch; - EXPECT(invalid_batch.clear_render_target({1, 0, 0, 1, ColorViewFormat::rgba8_srgb}, color)); - EXPECT(invalid_batch.clear_render_target({1, 0, 0, 1, static_cast(99)}, color) && invalid_batch.close()); - EXPECT(run(invalid_batch, binding, vk) == ReplayResult::invalid_clear && !image_clears && !attachment_clears); - checks += 3; - std::printf("typeless_rtv_test: %u format, snapshot, whole/rectangle and rejection scenarios passed\n", checks); - return 0; -} diff --git a/runtime/test/unimplemented_policy_test.cpp b/runtime/test/unimplemented_policy_test.cpp deleted file mode 100644 index 894190129..000000000 --- a/runtime/test/unimplemented_policy_test.cpp +++ /dev/null @@ -1,501 +0,0 @@ -// Tests for LEONIDA_UNIMPLEMENTED (log | fail | stop), the return policy of imports that have no binding. -// -// Everything is synthetic: the test writes a small x86-64 DLL image whose two imports exist nowhere (one named like a -// D3D12 factory, so it is classified as returning an HRESULT; one in an unknown DLL, so it is not), plus a caller -// function per import in its .text. The loader maps it, binds both imports to unimplemented thunks, and the test -// calls the image's callers the way the game would. No game data and no GPU are involved. -// -// in-process log and fail: return value (0 / E_NOTIMPL), an out-parameter that must stay untouched, and xmm0 = 0 -// for a caller that expects a float result. -// subprocess the test starts itself, because `stop` ends the process and the variable is read once per process: -// --stop-child stop mode: exit code, the message (import, caller as module+RVA, rcx..r9) -// --env-child prints the results for whatever LEONIDA_UNIMPLEMENTED the parent set, which pins -// the default (unset = log), case-insensitivity and the response to a bad value. -// LEONIDA_TEST_DIR names the folder for the image, as for loader_test; the default is the temp directory. -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include "../shims/shims.h" -#include "../src/pe_loader.h" -#include "free_image_base.h" - -namespace { - -namespace fs = std::filesystem; -using rt::shims::ReturnClass; -using rt::shims::UnimplementedPolicy; - -int g_checks = 0; -int g_failed = 0; - -void check(bool ok, const std::string& what) { - ++g_checks; - std::printf("%s %s\n", ok ? "ok " : "FAIL ", what.c_str()); - if (!ok) ++g_failed; -} - -struct Import { - const char* dll; - const char* name; -}; -// Index 0 is classified as HRESULT-returning (a D3D12 factory name no host d3d12 exports), index 1 is not. -const Import kImports[2] = {{"d3d12_xs.dll", "D3D12CreateLeonidaPolicyProbe"}, - {"leonida_policy_probe.dll", "PolicyProbeOther"}}; -constexpr uint32_t kTextRva = 0x1000; -constexpr uint32_t kCallerBase = kTextRva + 0x200; // caller i is at kCallerBase + 0x10 * i -constexpr uint32_t kCallRetOffset = 10; // sub rsp,0x28 (4) + call [rip+disp] (6): the return address -constexpr const char* kImageName = "policy_image.bin"; - -uint32_t caller_rva(int i) { return kCallerBase + 0x10u * static_cast(i); } -uint32_t return_rva(int i) { return caller_rva(i) + kCallRetOffset; } - -// A valid PE32+ DLL image with the two imports above. Layout, as offsets into .text (RVA 0x1000, 0x400 bytes): -// 0x000 import descriptors 0x040/0x070 DLL names 0x0A0/0x0C0 lookup tables 0x0E0/0x100 address tables -// 0x120/0x160 hint/name 0x200.. one caller per import: sub rsp,0x28; call [iat]; add rsp,0x28; ret -std::vector make_image() { - std::vector b(0x600, 0); - auto* dos = reinterpret_cast(b.data()); - dos->e_magic = IMAGE_DOS_SIGNATURE; - dos->e_lfanew = 0x80; - auto* nt = reinterpret_cast(b.data() + dos->e_lfanew); - nt->Signature = IMAGE_NT_SIGNATURE; - nt->FileHeader.Machine = IMAGE_FILE_MACHINE_AMD64; - nt->FileHeader.NumberOfSections = 1; - nt->FileHeader.SizeOfOptionalHeader = sizeof(IMAGE_OPTIONAL_HEADER64); - nt->FileHeader.Characteristics = IMAGE_FILE_EXECUTABLE_IMAGE | IMAGE_FILE_DLL | IMAGE_FILE_LARGE_ADDRESS_AWARE; - nt->OptionalHeader.Magic = IMAGE_NT_OPTIONAL_HDR64_MAGIC; - nt->OptionalHeader.ImageBase = leonida_test::free_image_base(0x180000000); - nt->OptionalHeader.AddressOfEntryPoint = 0; - nt->OptionalHeader.SizeOfHeaders = 0x200; - nt->OptionalHeader.SizeOfImage = 0x2000; - nt->OptionalHeader.Subsystem = IMAGE_SUBSYSTEM_WINDOWS_CUI; - nt->OptionalHeader.NumberOfRvaAndSizes = IMAGE_NUMBEROF_DIRECTORY_ENTRIES; - auto* sec = IMAGE_FIRST_SECTION(nt); - std::memcpy(sec->Name, ".text", 6); - sec->VirtualAddress = kTextRva; - sec->Misc.VirtualSize = 0x400; - sec->PointerToRawData = 0x200; - sec->SizeOfRawData = 0x400; - sec->Characteristics = IMAGE_SCN_CNT_CODE | IMAGE_SCN_MEM_EXECUTE | IMAGE_SCN_MEM_READ; - - uint8_t* text = b.data() + 0x200; - for (int i = 0; i < 2; ++i) { - const uint32_t name_off = 0x040 + 0x30u * i, lookup_off = 0x0A0 + 0x20u * i, iat_off = 0x0E0 + 0x20u * i, - hint_off = 0x120 + 0x40u * i; - auto* d = reinterpret_cast(text) + i; - d->Name = kTextRva + name_off; - d->OriginalFirstThunk = kTextRva + lookup_off; - d->FirstThunk = kTextRva + iat_off; - std::strcpy(reinterpret_cast(text + name_off), kImports[i].dll); - *reinterpret_cast(text + lookup_off) = kTextRva + hint_off; - std::strcpy(reinterpret_cast(text + hint_off + 2), kImports[i].name); - - const uint8_t code[] = {0x48, 0x83, 0xEC, 0x28, // sub rsp, 0x28 - 0xFF, 0x15, 0, 0, 0, 0, // call [rip + disp32] - 0x48, 0x83, 0xC4, 0x28, // add rsp, 0x28 - 0xC3}; // ret - uint8_t* fn = text + (caller_rva(i) - kTextRva); - std::memcpy(fn, code, sizeof code); - const int32_t disp = static_cast((kTextRva + iat_off) - return_rva(i)); - std::memcpy(fn + 6, &disp, 4); - } - auto& dir = nt->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT]; - dir.VirtualAddress = kTextRva; - dir.Size = 3 * sizeof(IMAGE_IMPORT_DESCRIPTOR); - return b; -} - -fs::path test_dir() { - const char* env = std::getenv("LEONIDA_TEST_DIR"); - fs::path dir = (env && *env ? fs::path(env) : fs::temp_directory_path()) / - ("leonida_unimplemented_policy_" + std::to_string(GetCurrentProcessId())); - fs::create_directories(dir); - return dir; -} - -fs::path write_image(const fs::path& dir) { - const auto bytes = make_image(); - const fs::path p = dir / kImageName; - std::ofstream out(p, std::ios::binary); - out.write(reinterpret_cast(bytes.data()), static_cast(bytes.size())); - if (!out) throw std::runtime_error("cannot write " + p.string()); - return p; -} - -using CallFn = uint64_t(__cdecl*)(uint64_t*, uint64_t, uint64_t, uint64_t); -using FloatFn = double(__cdecl*)(double); - -CallFn caller_of(const rt::Module& m, int i) { return reinterpret_cast(m.base + caller_rva(i)); } - -// ---- subprocess helpers --------------------------------------------------------------------------------------- - -struct ChildResult { - DWORD exit_code = 0xFFFFFFFF; - std::string output; // stdout and stderr, interleaved -}; - -// Runs this executable with `args`; `env` is LEONIDA_UNIMPLEMENTED for the child (nullptr = unset). -ChildResult run_child(const std::wstring& args, const wchar_t* env) { - wchar_t exe[MAX_PATH]; - GetModuleFileNameW(nullptr, exe, MAX_PATH); - SetEnvironmentVariableW(L"LEONIDA_UNIMPLEMENTED", env); - - SECURITY_ATTRIBUTES sa{sizeof sa, nullptr, TRUE}; - HANDLE read = nullptr, write = nullptr; - CreatePipe(&read, &write, &sa, 0); - SetHandleInformation(read, HANDLE_FLAG_INHERIT, 0); - STARTUPINFOW si{}; - si.cb = sizeof si; - si.dwFlags = STARTF_USESTDHANDLES; - si.hStdOutput = write; - si.hStdError = write; - si.hStdInput = GetStdHandle(STD_INPUT_HANDLE); - PROCESS_INFORMATION pi{}; - std::wstring cmd = L"\"" + std::wstring(exe) + L"\" " + args; - ChildResult r; - if (CreateProcessW(nullptr, cmd.data(), nullptr, nullptr, TRUE, 0, nullptr, nullptr, &si, &pi)) { - CloseHandle(write); - char buf[4096]; - DWORD n; - while (ReadFile(read, buf, sizeof buf, &n, nullptr) && n) r.output.append(buf, n); - WaitForSingleObject(pi.hProcess, 30000); - GetExitCodeProcess(pi.hProcess, &r.exit_code); - CloseHandle(pi.hProcess); - CloseHandle(pi.hThread); - } else { - CloseHandle(write); - } - CloseHandle(read); - SetEnvironmentVariableW(L"LEONIDA_UNIMPLEMENTED", nullptr); - return r; -} - -bool contains(const std::string& s, const std::string& what) { return s.find(what) != std::string::npos; } - -std::string hex(uint64_t v) { - char b[32]; - std::snprintf(b, sizeof b, "%llx", static_cast(v)); - return b; -} - -// ---- child modes ---------------------------------------------------------------------------------------------- - -int stop_child(const fs::path& dir, int which) { - rt::Loader loader(dir); - rt::Module& m = loader.load(write_image(dir)); - uint64_t out = 0x5A5A5A5A5A5A5A5Aull; - std::printf("out_address=%llx\n", static_cast(reinterpret_cast(&out))); - std::fflush(stdout); - caller_of(m, which)(&out, 0x2222, 0x3333, 0x4444); - std::printf("RETURNED: stop did not stop\n"); - return 0; -} - -int env_child(const fs::path& dir) { - rt::Loader loader(dir); - rt::Module& m = loader.load(write_image(dir)); - uint64_t out = 0x5A5A5A5A5A5A5A5Aull; - const uint64_t a = caller_of(m, 0)(&out, 1, 2, 3); - const uint64_t b = caller_of(m, 1)(&out, 1, 2, 3); - std::printf("hresult=%08llx other=%08llx out=%llx\n", static_cast(a), - static_cast(b), static_cast(out)); - return 0; -} - -// ---- tests ---------------------------------------------------------------------------------------------------- - -void test_classification() { - auto cls = [](const char* dll, const char* name) { return rt::shims::classify_import(dll, name); }; - check(cls("d3d12_xs.dll", "D3D12CreateLeonidaPolicyProbe") == ReturnClass::HResult, "D3D12Create* is hresult"); - check(cls("D3D12.dll", "D3D12CreateDevice") == ReturnClass::HResult, "the DLL name is case-insensitive"); - check(cls("d3d12.dll", "D3D12SerializeRootSignature") == ReturnClass::HResult, "D3D12Serialize* is hresult"); - check(cls("dxgi.dll", "CreateDXGIFactory2") == ReturnClass::HResult, "CreateDXGIFactory2 is hresult"); - check(cls("dxgi.dll", "DXGIGetDebugInterface1") == ReturnClass::HResult, "DXGIGetDebugInterface1 is hresult"); - check(cls("d3d12_xs.dll", "D3D12XboxCreateSyntheticDevice") == ReturnClass::HResult, - "the console CreateSyntheticDevice is hresult"); - check(cls("d3d12_xs.dll", "D3D12XboxSetProcessDebugFlags") == ReturnClass::Other, - "unmeasured console function is other"); - check(cls("xaudio2_9.dll", "XAudio2Create") == ReturnClass::HResult, "XAudio2Create is hresult"); - check(cls("xaudio2_9redist.dll", "XAudio2Create") == ReturnClass::HResult, - "the redist name gets the same class"); - check(cls("gameinput.dll", "GameInputCreate") == ReturnClass::HResult, "GameInputCreate is hresult"); - check(cls("dstorage_xs.dll", "DStorageGetFactory") == ReturnClass::HResult, - "the console dstorage name is hresult"); - check(cls("xg_xs.dll", "XGCreateTexture2DComputer") == ReturnClass::Other, "unmeasured xg_xs import is other"); - check(cls("acphal.dll", "AcpHalCreate") == ReturnClass::HResult, "AcpHalCreate is hresult"); - check(cls("acphal.dll", "ApuFree") == ReturnClass::Other, "ApuFree returns void"); - check(cls("acphal.dll", "ApuMapVirtualAddress") == ReturnClass::Other, "ApuMapVirtualAddress returns uint32_t"); - check(cls("xgameruntime.dll", "XGameRuntimeInitialize") == ReturnClass::HResult, "XGameRuntimeInitialize"); - check(cls("xgameruntime.dll", "XUserAddAsync") == ReturnClass::HResult, "XUser* is hresult"); - check(cls("xgameruntime.dll", "XTaskQueueCreate") == ReturnClass::HResult, "XTaskQueueCreate is hresult"); - check(cls("xgameruntime.dll", "XAsyncGetStatus") == ReturnClass::HResult, "XAsyncGetStatus is hresult"); - check(cls("xgameruntime.dll", "XTaskQueueDispatch") == ReturnClass::Other, "XTaskQueueDispatch returns bool"); - check(cls("xgameruntime.dll", "XUserCloseHandle") == ReturnClass::Other, "XUserCloseHandle returns void"); - check(cls("xgameruntime.dll", "XStoreIsLicenseValid") == ReturnClass::Other, "XStoreIsLicenseValid returns bool"); - check(cls("xgameruntime.dll", "XSystemGetDeviceType") == ReturnClass::Other, "XSystem* is not listed"); - check(cls("xgameruntime.dll", "XGameRuntimeUninitialize") == ReturnClass::Other, "XGameRuntimeUninitialize"); - check(cls("kernel32.dll", "XUserAddAsync") == ReturnClass::Other, "the DLL matters"); - check(cls("leonida_policy_probe.dll", "PolicyProbeOther") == ReturnClass::Other, "unknown import is other"); - - bool valid = true; - check(rt::shims::parse_unimplemented_policy("fail", &valid) == UnimplementedPolicy::Fail && valid, "parse fail"); - check(rt::shims::parse_unimplemented_policy("STOP", &valid) == UnimplementedPolicy::Stop && valid, "parse STOP"); - check(rt::shims::parse_unimplemented_policy(nullptr, &valid) == UnimplementedPolicy::Log && valid, "null is log"); - check(rt::shims::parse_unimplemented_policy("", &valid) == UnimplementedPolicy::Log && valid, "empty is log"); - check(rt::shims::parse_unimplemented_policy("bogus", &valid) == UnimplementedPolicy::Log && !valid, - "a bad value is log and invalid"); -} - -void test_in_process(const fs::path& dir) { - rt::Loader loader(dir); - rt::Module& m = loader.load(write_image(dir)); - - int unimplemented = 0, hresult = 0; - for (auto& r : m.imports) { - if (r.binding != rt::Binding::Unimplemented) continue; - ++unimplemented; - hresult += rt::shims::classify_import(r.dll, r.name) == ReturnClass::HResult; - } - check(unimplemented == 2 && hresult == 1, "the image binds 2 unimplemented imports, 1 of them hresult (" + - std::to_string(unimplemented) + ", " + std::to_string(hresult) + ")"); - - struct Case { - UnimplementedPolicy policy; - const char* name; - uint64_t want_hresult; - } cases[] = {{UnimplementedPolicy::Log, "log", 0}, {UnimplementedPolicy::Fail, "fail", rt::shims::kENotImpl}}; - for (const auto& c : cases) { - rt::shims::set_unimplemented_policy(c.policy); - for (int i = 0; i < 2; ++i) { - const uint64_t want = i == 0 ? c.want_hresult : 0; - const std::string tag = std::string(c.name) + ", " + (i == 0 ? "hresult" : "other") + " import: "; - uint64_t out = 0x5A5A5A5A5A5A5A5Aull; - const uint64_t got = caller_of(m, i)(&out, 0x2222, 0x3333, 0x4444); - check(got == want, tag + "returns 0x" + hex(want) + " (got 0x" + hex(got) + ")"); - check(out == 0x5A5A5A5A5A5A5A5Aull, tag + "out-parameter is untouched"); - - // A caller that expects a float or double sees 0.0, whatever rax holds. - const double f = reinterpret_cast(m.base + caller_rva(i))(3.5); - check(f == 0.0, tag + "xmm0 is 0.0 for a floating-point caller"); - } - } - // The same call again, to see that the stub leaves the stack and callee-saved state as it found them. - rt::shims::set_unimplemented_policy(UnimplementedPolicy::Fail); - uint64_t out = 0; - bool stable = true; - for (int n = 0; n < 1000; ++n) stable &= caller_of(m, 0)(&out, 1, 2, 3) == rt::shims::kENotImpl; - check(stable, "1000 repeated calls return the same value"); - rt::shims::set_unimplemented_policy(UnimplementedPolicy::Log); -} - -// ---- stack alignment, stack walk and register preservation --------------------------------------------------- - -struct HookState { - int calls = 0; - uintptr_t slot_mod = 0; // address of rt_unimplemented's return-address slot, mod 16 - std::vector rips; // the frames from the hook up to the first one with no unwind data - int frames_with_unwind_data = 0; -} g_hook; - -// Runs inside rt_unimplemented. At function entry rsp is 8 mod 16 when the caller's rsp was 16-byte aligned at the -// call, so a slot address of 8 mod 16 proves the stub aligned the stack. Then it walks the stack the way a debugger or -// the exception dispatcher would, through rt_unimplemented and the common stub, into the caller. -void unwind_hook(const void* return_address_slot) { - ++g_hook.calls; - g_hook.slot_mod = reinterpret_cast(return_address_slot) & 15; - g_hook.rips.clear(); - g_hook.frames_with_unwind_data = 0; - CONTEXT ctx; - RtlCaptureContext(&ctx); - for (int depth = 0; depth < 16; ++depth) { - g_hook.rips.push_back(ctx.Rip); - DWORD64 image_base = 0; - RUNTIME_FUNCTION* rf = RtlLookupFunctionEntry(ctx.Rip, &image_base, nullptr); - if (!rf) break; // code with no unwind data (the synthetic image): the walk ends in the caller - ++g_hook.frames_with_unwind_data; - void* handler_data = nullptr; - DWORD64 establisher = 0; - RtlVirtualUnwind(UNW_FLAG_NHANDLER, image_base, ctx.Rip, rf, &ctx, &handler_data, &establisher, nullptr); - } -} - -bool walk_contains(DWORD64 rip) { - for (DWORD64 r : g_hook.rips) - if (r == rip) return true; - return false; -} - -#ifdef LEONIDA_HAVE_ABI_PROBE -struct alignas(16) AbiProbe { - uint64_t gpr_in[8]; - uint8_t xmm_in[10][16]; - uint8_t pad[32]; - uint64_t gpr_out[8]; - uint8_t xmm_out[10][16]; - uint64_t result; - uint64_t spare; // rounds the size up to the 16-byte alignment -}; -static_assert(offsetof(AbiProbe, xmm_in) == 0x40 && offsetof(AbiProbe, gpr_out) == 0x100 && - offsetof(AbiProbe, xmm_out) == 0x140 && offsetof(AbiProbe, result) == 0x1E0, "abi_probe.asm layout"); -extern "C" uint64_t abi_probe_call(AbiProbe* p, void* fn); - -void fill_probe(AbiProbe& p) { - std::memset(&p, 0, sizeof p); - for (int i = 0; i < 8; ++i) p.gpr_in[i] = 0xA5A5000000000000ull | (0x1111ull * (i + 1)); - for (int i = 0; i < 10; ++i) - for (int b = 0; b < 16; ++b) p.xmm_in[i][b] = static_cast(0x10 * (i + 1) + b + 1); -} - -int probe_mismatches(const AbiProbe& p) { - int bad = 0; - for (int i = 0; i < 8; ++i) bad += p.gpr_out[i] != p.gpr_in[i]; - for (int i = 0; i < 10; ++i) bad += std::memcmp(p.xmm_out[i], p.xmm_in[i], 16) != 0; - return bad; -} -#endif - -void test_abi(const fs::path& dir) { - rt::Loader loader(dir); - rt::Module& m = loader.load(write_image(dir)); - const DWORD64 expect_return[2] = {reinterpret_cast(m.base) + return_rva(0), - reinterpret_cast(m.base) + return_rva(1)}; - - rt::shims::set_unimplemented_test_hook(&unwind_hook); - rt::shims::set_unimplemented_policy(UnimplementedPolicy::Fail); - for (int i = 0; i < 2; ++i) { - const std::string tag = std::string("caller ") + (i == 0 ? "of the hresult" : "of the other") + " import: "; - g_hook = {}; - uint64_t out = 0; - caller_of(m, i)(&out, 1, 2, 3); - check(g_hook.calls == 1, tag + "the test hook ran once"); - check(g_hook.slot_mod == 8, tag + "rt_unimplemented is entered with rsp = 8 mod 16, so the call was aligned (" + - std::to_string(g_hook.slot_mod) + ")"); - check(walk_contains(expect_return[i]), - tag + "RtlVirtualUnwind from inside rt_unimplemented reaches the caller's return address"); - check(g_hook.frames_with_unwind_data >= 3, - tag + "the walk passes the hook, rt_unimplemented and the stub (" + - std::to_string(g_hook.frames_with_unwind_data) + " frames with unwind data)"); - } - -#ifdef LEONIDA_HAVE_ABI_PROBE - AbiProbe p; - void* const thunk0 = *reinterpret_cast(m.base + kTextRva + 0x0E0); // IAT slot of import 0 - for (auto policy : {UnimplementedPolicy::Fail, UnimplementedPolicy::Log}) { - const std::string tag = std::string("abi_probe via ") + (policy == UnimplementedPolicy::Fail ? "fail" : "log") + ": "; - rt::shims::set_unimplemented_policy(policy); - fill_probe(p); - g_hook = {}; - const uint64_t r = abi_probe_call(&p, thunk0); - check(r == (policy == UnimplementedPolicy::Fail ? rt::shims::kENotImpl : 0), tag + "returns the policy's value"); - check(probe_mismatches(p) == 0, - tag + "rbx rbp rdi rsi r12-r15 and xmm6-xmm15 are unchanged by the call (" + - std::to_string(probe_mismatches(p)) + " differ)"); - check(g_hook.slot_mod == 8, tag + "aligned at the call into rt_unimplemented"); - DWORD64 fn = reinterpret_cast(&abi_probe_call); - if (*reinterpret_cast(fn) == 0xE9) // a linker jump thunk: follow it to the function - fn += 5 + *reinterpret_cast(fn + 1); - bool in_probe = false; - for (DWORD64 rip : g_hook.rips) in_probe |= rip > fn && rip < fn + 0x200; - if (!in_probe) { - std::printf("fn=%llx rips:", fn); - for (DWORD64 x : g_hook.rips) std::printf(" %llx", x); - std::printf("\n"); - } - check(in_probe, tag + "the stack walk reaches the calling function (unwinds through the stub)"); - } - - // Negative control: the harness must see a callee that breaks the ABI. - { - const uint8_t clobber[] = {0x31, 0xDB, // xor ebx, ebx - 0x0F, 0x57, 0xF6, // xorps xmm6, xmm6 - 0xC3}; - void* code = VirtualAlloc(nullptr, 0x1000, MEM_RESERVE | MEM_COMMIT, PAGE_EXECUTE_READWRITE); - std::memcpy(code, clobber, sizeof clobber); - fill_probe(p); - abi_probe_call(&p, code); - check(p.gpr_out[0] != p.gpr_in[0] && std::memcmp(p.xmm_out[0], p.xmm_in[0], 16) != 0, - "abi_probe notices a callee that clobbers rbx and xmm6 (control)"); - VirtualFree(code, 0, MEM_RELEASE); - } -#else - std::printf("skip register preservation: built without ml64\n"); -#endif - rt::shims::set_unimplemented_test_hook(nullptr); - rt::shims::set_unimplemented_policy(UnimplementedPolicy::Log); -} - -void test_env_and_default(const fs::path& dir) { - const std::wstring args = L"--env-child \"" + dir.wstring() + L"\""; - struct Case { - const wchar_t* env; - const char* label; - const char* expect; - bool warns; - } cases[] = { - {nullptr, "unset (the default) behaves as log", "hresult=00000000 other=00000000", false}, - {L"log", "log", "hresult=00000000 other=00000000", false}, - {L"fail", "fail", "hresult=80004001 other=00000000", false}, - {L"FAIL", "FAIL is case-insensitive", "hresult=80004001 other=00000000", false}, - {L"bogus", "a bad value falls back to log with a warning", "hresult=00000000 other=00000000", true}, - }; - for (const auto& c : cases) { - const ChildResult r = run_child(args, c.env); - const std::string tag = std::string("LEONIDA_UNIMPLEMENTED ") + c.label + ": "; - check(r.exit_code == 0, tag + "child exits 0 (" + std::to_string(r.exit_code) + ")"); - check(contains(r.output, c.expect), tag + "results '" + c.expect + "'"); - check(contains(r.output, "out=5a5a5a5a5a5a5a5a"), tag + "out-parameter untouched"); - check(contains(r.output, "expected log, fail or stop") == c.warns, tag + (c.warns ? "warns" : "does not warn")); - } -} - -void test_stop(const fs::path& dir) { - for (int i = 0; i < 2; ++i) { - const std::string tag = std::string("stop, ") + (i == 0 ? "hresult" : "other") + " import: "; - const ChildResult r = run_child(L"--stop-child \"" + dir.wstring() + L"\" " + std::to_wstring(i), L"stop"); - const std::string import = std::string(kImports[i].dll) + "!" + kImports[i].name; - check(r.exit_code == 3, tag + "the process ends with exit code 3 (" + std::to_string(r.exit_code) + ")"); - check(!contains(r.output, "RETURNED"), tag + "the call does not return"); - check(contains(r.output, "unimplemented import " + import + " called"), tag + "names the import"); - check(contains(r.output, std::string(" = ") + kImageName + "+0x" + hex(return_rva(i))), - tag + "caller resolves to " + kImageName + "+0x" + hex(return_rva(i))); - const auto at = r.output.find("out_address="); - const std::string out_address = at == std::string::npos ? "?" : r.output.substr(at + 12, r.output.find_first_of("\r\n", at) - at - 12); - check(contains(r.output, "rcx=0x" + out_address + " rdx="), tag + "prints rcx as passed (the out pointer " + out_address + ")"); - check(contains(r.output, "rdx=0x2222 r8=0x3333 r9=0x4444"), tag + "prints rdx, r8 and r9 as passed"); - check(contains(r.output, i == 0 ? "return class: hresult" : "return class: other"), tag + "prints the class"); - check(contains(r.output, "no debugger attached"), tag + "says why it ended"); - } -} - -} // namespace - -int wmain(int argc, wchar_t** argv) { - try { - if (argc >= 4 && std::wstring(argv[1]) == L"--stop-child") return stop_child(argv[2], _wtoi(argv[3])); - if (argc >= 3 && std::wstring(argv[1]) == L"--env-child") return env_child(argv[2]); - - const fs::path dir = test_dir(); - test_classification(); - test_in_process(dir); - test_abi(dir); - test_env_and_default(dir); - test_stop(dir); - std::error_code ec; - fs::remove_all(dir, ec); - } catch (const std::exception& e) { - std::printf("FAIL exception: %s\n", e.what()); - return 1; - } - std::printf("\n%d checks, %d failed\n", g_checks, g_failed); - return g_failed ? 1 : 0; -} diff --git a/runtime/test/vk_bc_zero_init_test.cpp b/runtime/test/vk_bc_zero_init_test.cpp deleted file mode 100644 index 6edc36fcb..000000000 --- a/runtime/test/vk_bc_zero_init_test.cpp +++ /dev/null @@ -1,388 +0,0 @@ -// Committed block-compressed (BC*) texture zero-initialization regression (D3D-220, #1725): -// D3D12 committed textures start zeroed unless D3D12_HEAP_FLAG_CREATE_NOT_ZEROED is set. Vulkan forbids -// vkCmdClearColorImage on BC formats, so detail::initialize() must zero-fill them via vkCmdCopyBufferToImage -// from either the device zero page (vk.zero_buffer) or a zeroed transfer-scratch chunk (vk.copy_scratch). -// -// Cases (all on explicitly poisoned 0x5A backing memory when host-visible, plus default device memory): -// 1. Path A (vk.zero_buffer): CopyTextureRegion R32G32_UINT 2x2 -> BC1 16x16 at (8, 4) — untouched blocks are 0x00. -// 2. Path A (vk.zero_buffer): CopyResource R32G32_UINT 3x2 -> BC1 12x8, 2 mips — mip 1 untouched block (bytes 56..63) is 0x00. -// 3. Path A (tiny 32-byte vk.zero_buffer): 32x32 BC7 image tiled in multiple row/column chunks — all 1024 bytes are 0x00. -// 4. Path B (enable_copy_scratch, no zero_buffer — matches d3d12_copy_xfmt): both D3D-220 cases match bit for bit. -// 5. not_zeroed = true (CREATE_NOT_ZEROED): zero-fill is skipped. -// Skips with exit code 77 when no Vulkan 1.3 device with textureCompressionBC is available. No game data. -#include "vk_test_device.h" -#include "../src/vulkan_backend.h" - -#include -#include -#include -#include -#include - -#define EXPECT(condition) do { \ - if (!(condition)) { std::fprintf(stderr, "line %d: %s\n", __LINE__, #condition); return 1; } \ -} while (0) - -namespace { - -struct OwnedImage { - VkDevice device = VK_NULL_HANDLE; - PFN_vkDestroyImage destroy_image = nullptr; - PFN_vkFreeMemory free_memory = nullptr; - VkImage image = VK_NULL_HANDLE; - VkDeviceMemory memory = VK_NULL_HANDLE; - bool poisoned = false; - - ~OwnedImage() { - if (image && destroy_image) destroy_image(device, image, nullptr); - if (memory && free_memory) free_memory(device, memory, nullptr); - } - OwnedImage(const OwnedImage&) = delete; - OwnedImage& operator=(const OwnedImage&) = delete; - OwnedImage() = default; -}; - -bool create_image(const vktest::Device& d, VkFormat format, std::uint32_t width, std::uint32_t height, - std::uint32_t mips, VkBuffer poison_buf, OwnedImage& out) { - out.device = d.device; - out.destroy_image = d.fn("vkDestroyImage"); - out.free_memory = d.fn("vkFreeMemory"); - - VkImageCreateInfo info{VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO}; - info.imageType = VK_IMAGE_TYPE_2D; - info.format = format; - info.extent = {width, height, 1}; - info.mipLevels = mips; - info.arrayLayers = 1; - info.samples = VK_SAMPLE_COUNT_1_BIT; - info.tiling = VK_IMAGE_TILING_OPTIMAL; - info.usage = VK_IMAGE_USAGE_TRANSFER_SRC_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT | VK_IMAGE_USAGE_SAMPLED_BIT; - if (d.fn("vkCreateImage")(d.device, &info, nullptr, &out.image) != VK_SUCCESS) return false; - - VkMemoryRequirements req{}; - d.fn("vkGetImageMemoryRequirements")(d.device, out.image, &req); - VkPhysicalDeviceMemoryProperties mp{}; - d.instance_fn("vkGetPhysicalDeviceMemoryProperties")(d.physical, &mp); - - std::uint32_t type = UINT32_MAX; - for (std::uint32_t i = 0; i < mp.memoryTypeCount; ++i) { - if (!(req.memoryTypeBits & (1u << i))) continue; - if (type == UINT32_MAX) type = i; - if (mp.memoryTypes[i].propertyFlags & VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT) { - type = i; - break; - } - } - if (type == UINT32_MAX) return false; - - VkMemoryAllocateInfo alloc{VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO}; - alloc.allocationSize = req.size; - alloc.memoryTypeIndex = type; - if (d.fn("vkAllocateMemory")(d.device, &alloc, nullptr, &out.memory) != VK_SUCCESS) - return false; - if (d.fn("vkBindImageMemory")(d.device, out.image, out.memory, 0) != VK_SUCCESS) - return false; - - // Pre-fill every mip on the GPU with 0x5A so stale recycled VRAM is modeled deterministically on every GPU - // (discrete and integrated alike), before registering the image in LayoutTracker as UNDEFINED. - if (poison_buf) { - const bool ok = const_cast(d).run([&](VkCommandBuffer cb) { - VkImageMemoryBarrier to_dst{VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER}; - to_dst.dstAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT; - to_dst.oldLayout = VK_IMAGE_LAYOUT_UNDEFINED; - to_dst.newLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL; - to_dst.srcQueueFamilyIndex = to_dst.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; - to_dst.image = out.image; - to_dst.subresourceRange = {VK_IMAGE_ASPECT_COLOR_BIT, 0, mips, 0, 1}; - d.fn("vkCmdPipelineBarrier")(cb, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, - VK_PIPELINE_STAGE_TRANSFER_BIT, 0, 0, nullptr, 0, - nullptr, 1, &to_dst); - std::vector regions; - for (std::uint32_t m = 0; m < mips; ++m) { - VkBufferImageCopy r{}; - r.imageSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, m, 0, 1}; - r.imageExtent = {std::max(1u, width >> m), std::max(1u, height >> m), 1}; - regions.push_back(r); - } - d.fn("vkCmdCopyBufferToImage")( - cb, poison_buf, out.image, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, std::uint32_t(regions.size()), - regions.data()); - return true; - }); - if (!ok) return false; - out.poisoned = true; - } - return true; -} - -VkDeviceMemory allocate_device_local(const vktest::Device& d, const VkMemoryRequirements& req) { - VkPhysicalDeviceMemoryProperties mp{}; - d.instance_fn("vkGetPhysicalDeviceMemoryProperties")(d.physical, &mp); - std::uint32_t chosen = UINT32_MAX; - for (std::uint32_t i = 0; i < mp.memoryTypeCount; ++i) { - if (!(req.memoryTypeBits & (1u << i))) continue; - if (chosen == UINT32_MAX) chosen = i; - if (mp.memoryTypes[i].propertyFlags & VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT) { - chosen = i; - break; - } - } - if (chosen == UINT32_MAX) return VK_NULL_HANDLE; - VkMemoryAllocateInfo info{VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO}; - info.allocationSize = req.size; - info.memoryTypeIndex = chosen; - VkDeviceMemory mem = VK_NULL_HANDLE; - if (d.fn("vkAllocateMemory")(d.device, &info, nullptr, &mem) != VK_SUCCESS) - return VK_NULL_HANDLE; - return mem; -} - -// Runs the two D3D-220 partial uncompressed -> BC1 copies on a given context/queue: -// (a) CopyTextureRegion R32G32_UINT 2x2 -> BC1 16x16 at (8, 4) -// (b) CopyResource R32G32_UINT 3x2 -> BC1 12x8, 2 mips -int run_d3d220_cases(const vktest::Device& d, leonida::VulkanContext& ctx, leonida::VulkanQueue& q, - VkBuffer poison_buf, VkBuffer up_buf, void* up_ptr, VkBuffer rb_buf, void* rb_ptr, - const char* label) { - using namespace leonida; - - auto* up = static_cast(up_ptr); - auto* rb = static_cast(rb_ptr); - for (std::size_t i = 0; i < 4096; ++i) up[i] = static_cast(i * 7 + 3); - - // Case (a): CopyTextureRegion R32G32_UINT 2x2 -> BC1 16x16 at (8, 4). - // Destination has 4x4 BC1 blocks (8 bytes/block). Only blocks (2,1), (3,1), (2,2), (3,2) are written; - // the other 12 blocks (including block (0,0) at byte 0) must be 0x00. - { - OwnedImage src_img, dst_img; - EXPECT(create_image(d, VK_FORMAT_R32G32_UINT, 2, 2, 1, VK_NULL_HANDLE, src_img)); - EXPECT(create_image(d, VK_FORMAT_BC1_RGBA_UNORM_BLOCK, 16, 16, 1, poison_buf, dst_img)); - - ResourceBinding src_rb{}; - src_rb.image = src_img.image; - src_rb.format = VK_FORMAT_R32G32_UINT; - src_rb.aspects = VK_IMAGE_ASPECT_COLOR_BIT; - src_rb.width = 2; src_rb.height = 2; src_rb.mip_levels = 1; src_rb.array_layers = 1; src_rb.depth = 1; src_rb.samples = 1; - - ResourceBinding dst_rb{}; - dst_rb.image = dst_img.image; - dst_rb.format = VK_FORMAT_BC1_RGBA_UNORM_BLOCK; - dst_rb.aspects = VK_IMAGE_ASPECT_COLOR_BIT; - dst_rb.width = 16; dst_rb.height = 16; dst_rb.mip_levels = 1; dst_rb.array_layers = 1; dst_rb.depth = 1; dst_rb.samples = 1; - - ctx.add_resource(10, src_rb, VK_IMAGE_LAYOUT_UNDEFINED); - ctx.add_resource(11, dst_rb, VK_IMAGE_LAYOUT_UNDEFINED); - std::memset(rb, 0xCD, 4096); - - CommandList list; - CopyLocation up_loc{1, true, 0, 0, 2, 2, 1, 256}; - CopyLocation src_loc{10, false, 0, 0, 0, 0, 0, 0}; - CopyLocation dst_loc{11, false, 0, 0, 0, 0, 0, 0}; - CopyLocation rb_loc{2, true, 0, 0, 16, 16, 1, 256}; - EXPECT(list.copy_texture({src_loc, 0, 0, 0, up_loc, false, {}})); - EXPECT(list.transition({10, all_subresources, d3d12_state::copy_dest, d3d12_state::copy_source})); - EXPECT(list.copy_texture({dst_loc, 8, 4, 0, src_loc, false, {}})); - EXPECT(list.transition({11, all_subresources, d3d12_state::copy_dest, d3d12_state::copy_source})); - EXPECT(list.copy_texture({rb_loc, 0, 0, 0, dst_loc, false, {}})); - EXPECT(list.close()); - - const CommandList* ptr = &list; - EXPECT(q.execute({&ptr, 1}) == ReplayResult::success); - EXPECT(q.idle()); - - // Check every 8-byte block across the 4x4 block grid (row pitch 256). - for (std::uint32_t by = 0; by < 4; ++by) { - for (std::uint32_t bx = 0; bx < 4; ++bx) { - const std::uint8_t* got = rb + std::size_t(by) * 256 + std::size_t(bx) * 8; - if (bx >= 2 && bx < 4 && by >= 1 && by < 3) { - const std::uint8_t* want = up + std::size_t(by - 1) * 256 + std::size_t(bx - 2) * 8; - EXPECT(std::memcmp(got, want, 8) == 0); - } else { - for (int k = 0; k < 8; ++k) EXPECT(got[k] == 0x00); - } - } - } - ctx.remove_resource(10); - ctx.remove_resource(11); - } - - // Case (b): CopyResource R32G32_UINT 3x2 -> BC1 12x8, 2 mips. - // Mip 0: 3x2 -> 12x8 (3x2 = 6 blocks written). - // Mip 1: 1x1 -> 6x4 (2x1 = 2 blocks; block 0 is written, block 1 at bytes 8..15 of mip 1 is untouched -> 0x00). - { - OwnedImage src_img, dst_img; - EXPECT(create_image(d, VK_FORMAT_R32G32_UINT, 3, 2, 2, VK_NULL_HANDLE, src_img)); - EXPECT(create_image(d, VK_FORMAT_BC1_RGBA_UNORM_BLOCK, 12, 8, 2, poison_buf, dst_img)); - - ResourceBinding src_rb{}; - src_rb.image = src_img.image; - src_rb.format = VK_FORMAT_R32G32_UINT; - src_rb.aspects = VK_IMAGE_ASPECT_COLOR_BIT; - src_rb.width = 3; src_rb.height = 2; src_rb.mip_levels = 2; src_rb.array_layers = 1; src_rb.depth = 1; src_rb.samples = 1; - - ResourceBinding dst_rb{}; - dst_rb.image = dst_img.image; - dst_rb.format = VK_FORMAT_BC1_RGBA_UNORM_BLOCK; - dst_rb.aspects = VK_IMAGE_ASPECT_COLOR_BIT; - dst_rb.width = 12; dst_rb.height = 8; dst_rb.mip_levels = 2; dst_rb.array_layers = 1; dst_rb.depth = 1; dst_rb.samples = 1; - - ctx.add_resource(12, src_rb, VK_IMAGE_LAYOUT_UNDEFINED); - ctx.add_resource(13, dst_rb, VK_IMAGE_LAYOUT_UNDEFINED); - std::memset(rb, 0xCD, 4096); - - // Upload mip 0 at offset 0 (2 rows * 256 = 512 bytes) and mip 1 at offset 512 (1 row * 256). - CommandList list; - CopyLocation up0{1, true, 0, 0, 3, 2, 1, 256}; - CopyLocation up1{1, true, 0, 512, 1, 1, 1, 256}; - CopyLocation src0{12, false, 0, 0, 0, 0, 0, 0}; - CopyLocation src1{12, false, 1, 0, 0, 0, 0, 0}; - CopyLocation dst0{13, false, 0, 0, 0, 0, 0, 0}; - CopyLocation dst1{13, false, 1, 0, 0, 0, 0, 0}; - CopyLocation rb0{2, true, 0, 0, 12, 8, 1, 256}; - CopyLocation rb1{2, true, 0, 512, 6, 4, 1, 256}; - EXPECT(list.copy_texture({src0, 0, 0, 0, up0, false, {}})); - EXPECT(list.copy_texture({src1, 0, 0, 0, up1, false, {}})); - EXPECT(list.transition({12, all_subresources, d3d12_state::copy_dest, d3d12_state::copy_source})); - EXPECT(list.copy_resource({13, 12})); - EXPECT(list.transition({13, all_subresources, d3d12_state::copy_dest, d3d12_state::copy_source})); - EXPECT(list.copy_texture({rb0, 0, 0, 0, dst0, false, {}})); - EXPECT(list.copy_texture({rb1, 0, 0, 0, dst1, false, {}})); - EXPECT(list.close()); - - const CommandList* ptr = &list; - EXPECT(q.execute({&ptr, 1}) == ReplayResult::success); - EXPECT(q.idle()); - - // Mip 0: 2 rows of 3 blocks (24 bytes per row). - EXPECT(std::memcmp(rb + 0, up + 0, 24) == 0); - EXPECT(std::memcmp(rb + 256, up + 256, 24) == 0); - // Mip 1: block 0 (bytes 0..7) matches up + 512; untouched block 1 (bytes 8..15) must be 0x00. - EXPECT(std::memcmp(rb + 512, up + 512, 8) == 0); - for (int k = 8; k < 16; ++k) EXPECT(rb[512 + k] == 0x00); - - ctx.remove_resource(12); - ctx.remove_resource(13); - } - - (void)up_buf; - (void)rb_buf; - std::printf("bc zero-init (%s): partial CopyTextureRegion and 2-mip CopyResource ok\n", label); - return 0; -} - -} // namespace - -int main() { - using namespace leonida; - - vktest::Device d; - if (!d.create(false) || !d.bc) { - std::fprintf(stderr, "vk_bc_zero_init_test: no Vulkan 1.3 device with BC support, skipped\n"); - return 77; - } - - void* up_ptr = nullptr; - void* rb_ptr = nullptr; - void* zero_ptr = nullptr; - void* poison_ptr = nullptr; - const VkBuffer up_buf = d.buffer(4096, VK_BUFFER_USAGE_TRANSFER_SRC_BIT, &up_ptr); - const VkBuffer rb_buf = d.buffer(8192, VK_BUFFER_USAGE_TRANSFER_DST_BIT, &rb_ptr); - const VkBuffer zero_buf = d.buffer(65536, VK_BUFFER_USAGE_TRANSFER_SRC_BIT, &zero_ptr); - const VkBuffer poison_buf = d.buffer(4096, VK_BUFFER_USAGE_TRANSFER_SRC_BIT, &poison_ptr); - EXPECT(up_buf && rb_buf && zero_buf && poison_buf); - std::memset(zero_ptr, 0, 65536); - std::memset(poison_ptr, 0x5A, 4096); - - ResourceBinding up_rb{}; - up_rb.buffer = up_buf; - up_rb.size = 4096; - ResourceBinding rb_rb{}; - rb_rb.buffer = rb_buf; - rb_rb.size = 8192; - rb_rb.host_readable = true; - - // Path A: device arena zero page (vk.zero_buffer). - { - VulkanContext ctx(d.device_proc, d.device, true); - EXPECT(ctx.loaded()); - ctx.set_zero_page(zero_buf, 0, 65536); - ctx.add_resource(1, up_rb); - ctx.add_resource(2, rb_rb); - VulkanQueue q(ctx, d.queue, d.family); - EXPECT(q.ok()); - EXPECT(run_d3d220_cases(d, ctx, q, poison_buf, up_buf, up_ptr, rb_buf, rb_ptr, "zero_buffer") == 0); - - // Multi-tile chunking: shrink zero_page to 32 bytes (2 BC7 blocks) and zero-init a 32x32 BC7 image (64 blocks). - ctx.set_zero_page(zero_buf, 16, 32); - OwnedImage bc7_img; - EXPECT(create_image(d, VK_FORMAT_BC7_UNORM_BLOCK, 32, 32, 1, poison_buf, bc7_img)); - ResourceBinding bc7_rb{}; - bc7_rb.image = bc7_img.image; - bc7_rb.format = VK_FORMAT_BC7_UNORM_BLOCK; - bc7_rb.aspects = VK_IMAGE_ASPECT_COLOR_BIT; - bc7_rb.width = 32; bc7_rb.height = 32; bc7_rb.mip_levels = 1; bc7_rb.array_layers = 1; bc7_rb.depth = 1; bc7_rb.samples = 1; - ctx.add_resource(20, bc7_rb, VK_IMAGE_LAYOUT_UNDEFINED); - std::memset(rb_ptr, 0xCD, 8192); - - CommandList list; - EXPECT(list.transition({20, all_subresources, d3d12_state::copy_dest, d3d12_state::copy_source})); - CopyLocation bc7_loc{20, false, 0, 0, 0, 0, 0, 0}; - CopyLocation rb_loc{2, true, 0, 0, 32, 32, 1, 256}; - EXPECT(list.copy_texture({rb_loc, 0, 0, 0, bc7_loc, false, {}})); - EXPECT(list.close()); - const CommandList* ptr = &list; - EXPECT(q.execute({&ptr, 1}) == ReplayResult::success); - EXPECT(q.idle()); - - auto* rb = static_cast(rb_ptr); - for (std::uint32_t row = 0; row < 8; ++row) - for (std::uint32_t x = 0; x < 8 * 16; ++x) - EXPECT(rb[row * 256 + x] == 0x00); - ctx.remove_resource(20); - std::printf("bc zero-init (tiny 32-byte zero_buffer chunking on 32x32 BC7): ok\n"); - - // CREATE_NOT_ZEROED (not_zeroed = true) must skip zero-fill. - ctx.set_zero_page(zero_buf, 0, 65536); - OwnedImage nz_img; - EXPECT(create_image(d, VK_FORMAT_BC1_RGBA_UNORM_BLOCK, 16, 16, 1, poison_buf, nz_img)); - EXPECT(nz_img.poisoned); - ResourceBinding nz_rb{}; - nz_rb.image = nz_img.image; - nz_rb.format = VK_FORMAT_BC1_RGBA_UNORM_BLOCK; - nz_rb.aspects = VK_IMAGE_ASPECT_COLOR_BIT; - nz_rb.width = 16; nz_rb.height = 16; nz_rb.mip_levels = 1; nz_rb.array_layers = 1; nz_rb.depth = 1; nz_rb.samples = 1; - nz_rb.not_zeroed = true; - ctx.add_resource(21, nz_rb, VK_IMAGE_LAYOUT_UNDEFINED); - std::memset(rb_ptr, 0xCD, 8192); - - CommandList nz_list; - EXPECT(nz_list.transition({21, all_subresources, d3d12_state::copy_dest, d3d12_state::copy_source})); - CopyLocation nz_loc{21, false, 0, 0, 0, 0, 0, 0}; - CopyLocation nz_rb_loc{2, true, 0, 0, 16, 16, 1, 256}; - EXPECT(nz_list.copy_texture({nz_rb_loc, 0, 0, 0, nz_loc, false, {}})); - EXPECT(nz_list.close()); - const CommandList* nz_ptr = &nz_list; - EXPECT(q.execute({&nz_ptr, 1}) == ReplayResult::success); - EXPECT(q.idle()); - EXPECT(rb[0] == 0x5A); - ctx.remove_resource(21); - std::printf("bc zero-init (not_zeroed = true skips zero-fill): ok\n"); - } - - // Path B: copy_scratch + vkCmdFillBuffer fallback (no zero_buffer, matching d3d12_copy_xfmt without BDA). - { - VulkanContext ctx(d.device_proc, d.device, true); - EXPECT(ctx.loaded()); - ctx.enable_copy_scratch(d.device_proc, [&](const VkMemoryRequirements& req) { - return allocate_device_local(d, req); - }); - ctx.add_resource(1, up_rb); - ctx.add_resource(2, rb_rb); - VulkanQueue q(ctx, d.queue, d.family); - EXPECT(q.ok()); - EXPECT(run_d3d220_cases(d, ctx, q, poison_buf, up_buf, up_ptr, rb_buf, rb_ptr, "copy_scratch") == 0); - } - - EXPECT(d.validation_errors() == 0); - std::printf("vk_bc_zero_init_test: ok\n"); - return 0; -} diff --git a/runtime/test/vk_binary_occlusion_test.cpp b/runtime/test/vk_binary_occlusion_test.cpp deleted file mode 100644 index ff6c62e05..000000000 --- a/runtime/test/vk_binary_occlusion_test.cpp +++ /dev/null @@ -1,319 +0,0 @@ -#include "predicated_copy_controls.h" -// Seed an occlusion heap with independent Vulkan draws, then resolve it through the D3D12 replay queue. -// This exercises the real GPU query copy and normalization without needing D3D12 draw commands. -#include "vk_test_device.h" -#include "../src/vulkan_backend.h" - -#include -#include - -#define EXPECT(condition) do { \ - if (!(condition)) { std::fprintf(stderr, "line %d: %s\n", __LINE__, #condition); return 1; } \ -} while (0) - -namespace { - -using namespace leonida; -constexpr std::uint32_t side = 8; -constexpr std::uint32_t first_visible = 2, visible_count = 1026; -constexpr std::uint32_t last_gap = first_visible + visible_count; -constexpr std::uint32_t ordinary_index = last_gap + 1, query_count = ordinary_index + 1; - -VkShaderModule load_shader(vktest::Device& d, const char* path) { - std::ifstream file(path, std::ios::binary | std::ios::ate); - const std::streamoff bytes = file.tellg(); - if (bytes <= 0 || bytes % 4 != 0) return VK_NULL_HANDLE; - std::vector code(static_cast(bytes) / 4); - file.seekg(0); - if (!file.read(reinterpret_cast(code.data()), bytes)) return VK_NULL_HANDLE; - VkShaderModuleCreateInfo info{VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO}; - info.codeSize = static_cast(bytes); - info.pCode = code.data(); - VkShaderModule module = VK_NULL_HANDLE; - if (d.fn("vkCreateShaderModule")(d.device, &info, nullptr, &module) != VK_SUCCESS) - return VK_NULL_HANDLE; - return module; -} - -struct Fixture { - vktest::Device& d; - VkShaderModule vs = VK_NULL_HANDLE, fs = VK_NULL_HANDLE; - VkPipelineLayout layout = VK_NULL_HANDLE; - VkPipeline pipeline = VK_NULL_HANDLE; - VkQueryPool occlusion = VK_NULL_HANDLE, statistics = VK_NULL_HANDLE; - - ~Fixture() { - const auto destroy_pool = d.fn("vkDestroyQueryPool"); - const auto destroy_shader = d.fn("vkDestroyShaderModule"); - if (statistics) destroy_pool(d.device, statistics, nullptr); - if (occlusion) destroy_pool(d.device, occlusion, nullptr); - if (pipeline) d.fn("vkDestroyPipeline")(d.device, pipeline, nullptr); - if (layout) d.fn("vkDestroyPipelineLayout")(d.device, layout, nullptr); - if (fs) destroy_shader(d.device, fs, nullptr); - if (vs) destroy_shader(d.device, vs, nullptr); - } - - bool create(const char* vertex, const char* fragment) { - vs = load_shader(d, vertex); - fs = load_shader(d, fragment); - if (!vs || !fs) return false; - VkPipelineLayoutCreateInfo layout_info{VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO}; - if (d.fn("vkCreatePipelineLayout")(d.device, &layout_info, nullptr, &layout) != - VK_SUCCESS) - return false; - const VkPipelineShaderStageCreateInfo stages[] = { - {VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO, nullptr, 0, VK_SHADER_STAGE_VERTEX_BIT, vs, "main"}, - {VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO, nullptr, 0, VK_SHADER_STAGE_FRAGMENT_BIT, fs, "main"}, - }; - const VkPipelineVertexInputStateCreateInfo vi{VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO}; - VkPipelineInputAssemblyStateCreateInfo ia{VK_STRUCTURE_TYPE_PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO}; - ia.topology = VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST; - const VkViewport vp{0, 0, float(side), float(side), 0, 1}; - const VkRect2D scissor{{}, {side, side}}; - VkPipelineViewportStateCreateInfo viewport{VK_STRUCTURE_TYPE_PIPELINE_VIEWPORT_STATE_CREATE_INFO}; - viewport.viewportCount = viewport.scissorCount = 1; - viewport.pViewports = &vp; - viewport.pScissors = &scissor; - VkPipelineRasterizationStateCreateInfo raster{VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_STATE_CREATE_INFO}; - raster.lineWidth = 1; - VkPipelineMultisampleStateCreateInfo ms{VK_STRUCTURE_TYPE_PIPELINE_MULTISAMPLE_STATE_CREATE_INFO}; - ms.rasterizationSamples = VK_SAMPLE_COUNT_1_BIT; - const VkPipelineColorBlendStateCreateInfo blend{VK_STRUCTURE_TYPE_PIPELINE_COLOR_BLEND_STATE_CREATE_INFO}; - const VkPipelineRenderingCreateInfo rendering{VK_STRUCTURE_TYPE_PIPELINE_RENDERING_CREATE_INFO}; - VkGraphicsPipelineCreateInfo info{VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO, &rendering}; - info.stageCount = 2; - info.pStages = stages; - info.pVertexInputState = &vi; - info.pInputAssemblyState = &ia; - info.pViewportState = &viewport; - info.pRasterizationState = &raster; - info.pMultisampleState = &ms; - info.pColorBlendState = &blend; - info.layout = layout; - if (d.fn("vkCreateGraphicsPipelines")( - d.device, VK_NULL_HANDLE, 1, &info, nullptr, &pipeline) != VK_SUCCESS) - return false; - const auto pool = d.fn("vkCreateQueryPool"); - VkQueryPoolCreateInfo query{VK_STRUCTURE_TYPE_QUERY_POOL_CREATE_INFO}; - query.queryType = VK_QUERY_TYPE_OCCLUSION; - query.queryCount = query_count; - if (pool(d.device, &query, nullptr, &occlusion) != VK_SUCCESS) return false; - if (d.pipeline_statistics_query) { - query.queryType = VK_QUERY_TYPE_PIPELINE_STATISTICS; - query.queryCount = 2; - query.pipelineStatistics = 0x7ff; // the same counters as the D3D12 heap - if (pool(d.device, &query, nullptr, &statistics) != VK_SUCCESS) return false; - } - return true; - } - - bool draw() { - const auto begin = d.fn("vkCmdBeginQuery"); - const auto end = d.fn("vkCmdEndQuery"); - const auto draw = d.fn("vkCmdDraw"); - return d.run([&](VkCommandBuffer cb) { - d.fn("vkCmdResetQueryPool")(cb, occlusion, 0, query_count); - VkRenderingInfo rendering{VK_STRUCTURE_TYPE_RENDERING_INFO}; - rendering.renderArea.extent = {side, side}; - rendering.layerCount = 1; - d.fn("vkCmdBeginRendering")(cb, &rendering); - d.fn("vkCmdBindPipeline")(cb, VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline); - begin(cb, occlusion, 1, 0); - end(cb, occlusion, 1); - for (std::uint32_t index = first_visible; index < last_gap; ++index) { - begin(cb, occlusion, index, 0); - draw(cb, 3, 1, 0, 0); - end(cb, occlusion, index); - } - begin(cb, occlusion, ordinary_index, d.occlusion_query_precise ? VK_QUERY_CONTROL_PRECISE_BIT : 0); - draw(cb, 3, 1, 0, 0); - end(cb, occlusion, ordinary_index); - d.fn("vkCmdEndRendering")(cb); - return true; - }); - } -}; - -int run(vktest::Device& d, const char* vertex, const char* fragment) { - std::uint32_t family_count = 0; - const auto families = d.instance_fn( - "vkGetPhysicalDeviceQueueFamilyProperties"); - families(d.physical, &family_count, nullptr); - std::vector queues(family_count); - families(d.physical, &family_count, queues.data()); - if (!(queues[d.family].queueFlags & VK_QUEUE_COMPUTE_BIT)) { - std::puts("the graphics queue does not support compute"); - return 77; - } - Fixture fixture{d}; - EXPECT(fixture.create(vertex, fragment)); - EXPECT(fixture.draw()); - - VulkanContext context(d.device_proc, d.device, true, d.conditional_rendering); - EXPECT(context.loaded()); - VkPhysicalDeviceMemoryProperties memory{}; - d.instance_fn("vkGetPhysicalDeviceMemoryProperties")(d.physical, - &memory); - context.set_occlusion_resolve_memory(memory); - VkPhysicalDeviceProperties properties{}; - d.instance_fn("vkGetPhysicalDeviceProperties")(d.physical, &properties); - context.configure_predication(d.device_proc, memory, properties.limits.maxStorageBufferRange, d.family); - PredicatedCopyControl copy_control; - EXPECT(copy_control.create(d, context, properties.limits)); - VulkanQueue queue(context, d.queue, d.family); - EXPECT(queue.ok()); - constexpr QueryHeapId query_id = 1, stats_id = 2; - QueryPool heap{fixture.occlusion, d3d12_query_heap::occlusion, query_count, d.occlusion_query_precise, - std::vector(query_count, true)}; - heap.ended[0] = heap.ended[last_gap] = false; - context.add_query_pool(query_id, heap); - constexpr ResourceId destination_id = 3, predicate_id = 4, misaligned_id = 5; - constexpr VkDeviceSize binding_offset = 24, range_offset = 16, result_size = sizeof(std::uint64_t); - constexpr VkDeviceSize ordinary_offset = range_offset + (last_gap + 2) * result_size; - constexpr VkDeviceSize ordinary_zero_offset = ordinary_offset + 2 * result_size; - constexpr VkDeviceSize rerun_offset = ordinary_zero_offset + 2 * result_size; - constexpr VkDeviceSize bytes = binding_offset + rerun_offset + 6 * result_size; - void* mapped = nullptr; - const VkBuffer dst = d.buffer(bytes, VK_BUFFER_USAGE_TRANSFER_DST_BIT, &mapped); - EXPECT(dst && mapped); - std::memset(mapped, 0xcd, bytes); - ResourceBinding destination{}; - destination.buffer = dst; - destination.buffer_offset = binding_offset; - destination.size = bytes - binding_offset; - destination.host_readable = true; // ResolveQueryData writes results that the CPU reads below. - context.add_resource(destination_id, destination); - - ResourceBinding misaligned = destination; - misaligned.buffer_offset += 4; - misaligned.size -= 4; - context.add_resource(misaligned_id, misaligned); - CommandList invalid; - EXPECT(invalid.resolve_queries({query_id, d3d12_query::binary_occlusion, first_visible, 1, misaligned_id, 0})); - EXPECT(invalid.close()); - const CommandList* invalid_list = &invalid; - EXPECT(queue.execute({&invalid_list, 1}) == ReplayResult::invalid_query); - - CommandList binary; - if (d.conditional_rendering) { - void* predicate_mapping = nullptr; - ResourceBinding predicate{}; - predicate.size = 8; - predicate.buffer = d.buffer(predicate.size, VK_BUFFER_USAGE_CONDITIONAL_RENDERING_BIT_EXT | VK_BUFFER_USAGE_TRANSFER_SRC_BIT, - &predicate_mapping); - EXPECT(predicate.buffer && predicate_mapping); - std::memset(predicate_mapping, 0, predicate.size); - context.add_resource(predicate_id, predicate); - // A zero predicate suppresses dispatch, but it must not suppress a query resolve. - EXPECT(binary.set_predication({predicate_id, 0, d3d12_predication::equal_zero})); - } - EXPECT(binary.resolve_queries({query_id, d3d12_query::binary_occlusion, 0, last_gap + 1, destination_id, - range_offset})); - EXPECT(binary.resolve_queries({query_id, d3d12_query::occlusion, ordinary_index, 1, destination_id, - ordinary_offset})); - // An ordinary un-ended query zeroed via vkCmdFillBuffer must also run unconditionally under a false predicate. - EXPECT(binary.resolve_queries({query_id, d3d12_query::occlusion, 0, 1, destination_id, ordinary_zero_offset})); - EXPECT(copy_control.record(binary)); - EXPECT(binary.close()); - CommandList rerun; - EXPECT(rerun.resolve_queries({query_id, d3d12_query::binary_occlusion, first_visible + 1, 3, destination_id, - rerun_offset})); - EXPECT(rerun.close()); - const CommandList* binary_list = &binary; - const CommandList* rerun_list = &rerun; - EXPECT(queue.execute({&binary_list, 1}) == ReplayResult::success); - EXPECT(queue.execute({&rerun_list, 1}) == ReplayResult::success); // same scratch, consecutive submissions - EXPECT(queue.idle()); - - std::uint64_t raw = 0; - EXPECT(d.fn("vkGetQueryPoolResults")( - d.device, fixture.occlusion, ordinary_index, 1, sizeof(raw), &raw, sizeof(raw), - VK_QUERY_RESULT_64_BIT | VK_QUERY_RESULT_WAIT_BIT) == VK_SUCCESS); - EXPECT(raw > 0 && (!d.occlusion_query_precise || raw == side * side)); - for (VkDeviceSize offset = 0; offset < bytes; offset += result_size) { - const VkDeviceSize range = binding_offset + range_offset; - const VkDeviceSize rerun_begin = binding_offset + rerun_offset; - std::uint64_t expected = 0xcdcdcdcdcdcdcdcd; - if (offset >= range && offset < range + (last_gap + 1) * result_size) { - const auto index = (offset - range) / result_size; - expected = index >= first_visible && index < last_gap ? 1 : 0; - } else if (offset == binding_offset + ordinary_offset) { - expected = raw; - } else if (offset == binding_offset + ordinary_zero_offset) { - expected = 0; - } else if (offset >= rerun_begin && offset < rerun_begin + 3 * result_size) { - expected = 1; - } - std::uint64_t actual; - std::memcpy(&actual, static_cast(mapped) + offset, sizeof(actual)); - if (actual != expected) { - std::fprintf(stderr, "offset %llu: got %llu, expected %llu\n", - static_cast(offset), static_cast(actual), - static_cast(expected)); - return 1; - } - } - if (fixture.statistics) { - // D3D-162: the normalisation dispatch of a binary resolve inside a pipeline-statistics query, and then the - // statistics sum of that split query inside a second one. Neither helper dispatch may reach the - // application's counters, and nothing else runs inside the queries, so every counter of both is 0. - constexpr auto statistics = d3d12_query::pipeline_statistics; - constexpr VkDeviceSize statistics_result = 11 * sizeof(std::uint64_t); - context.add_query_pool(stats_id, {fixture.statistics, d3d12_query_heap::pipeline_statistics, 2, false, - {false, false}}); - constexpr ResourceId statistics_id = 6; - void* statistics_mapping = nullptr; - ResourceBinding statistics_dst{}; - statistics_dst.size = 3 * statistics_result; - statistics_dst.buffer = d.buffer(statistics_dst.size, VK_BUFFER_USAGE_TRANSFER_DST_BIT, &statistics_mapping); - EXPECT(statistics_dst.buffer && statistics_mapping); - std::memset(statistics_mapping, 0xcd, statistics_dst.size); - context.add_resource(statistics_id, statistics_dst); - CommandList overlap; - EXPECT(overlap.begin_query({stats_id, statistics, 0})); - EXPECT(overlap.resolve_queries({query_id, d3d12_query::binary_occlusion, first_visible, 1, destination_id, 0})); - EXPECT(overlap.end_query({stats_id, statistics, 0})); - EXPECT(overlap.close()); - CommandList nested; - EXPECT(nested.begin_query({stats_id, statistics, 1})); - EXPECT(nested.resolve_queries({stats_id, statistics, 0, 1, statistics_id, 0})); - EXPECT(nested.end_query({stats_id, statistics, 1})); - EXPECT(nested.resolve_queries({stats_id, statistics, 0, 2, statistics_id, statistics_result})); - EXPECT(nested.close()); - const CommandList* overlap_list = &overlap; - const CommandList* nested_list = &nested; - EXPECT(queue.execute({&overlap_list, 1}) == ReplayResult::success); - EXPECT(queue.execute({&nested_list, 1}) == ReplayResult::success); - EXPECT(queue.idle()); - std::uint64_t visible = 0; - std::memcpy(&visible, static_cast(mapped) + binding_offset, sizeof(visible)); - EXPECT(visible == 1); - for (VkDeviceSize offset = 0; offset < statistics_dst.size; offset += 8) { - std::uint64_t counter = 0; - std::memcpy(&counter, static_cast(statistics_mapping) + offset, sizeof(counter)); - if (counter != 0) { - std::fprintf(stderr, "statistics byte %llu: got %llu, expected 0\n", - static_cast(offset), static_cast(counter)); - return 1; - } - } - std::puts("binary and statistics resolves inside pipeline-statistics queries: every counter 0"); - } - std::printf("binary occlusion: %u visible, 3 zero, 3 repeated; ordinary result %llu; offsets and sentinels exact\n", - visible_count, static_cast(raw)); - EXPECT(copy_control.check()); - return 0; -} - -} // namespace - -int main(int argc, char** argv) { - EXPECT(argc == 3); - vktest::Device device; - const auto status = device.initialize(); - if (status == vktest::DeviceStatus::unavailable) return 77; - EXPECT(status == vktest::DeviceStatus::ready); - const int result = run(device, argv[1], argv[2]); - EXPECT(device.validation_errors() == 0); - return result; -} diff --git a/runtime/test/vk_bindless_test.cpp b/runtime/test/vk_bindless_test.cpp deleted file mode 100644 index d6276d8ad..000000000 --- a/runtime/test/vk_bindless_test.cpp +++ /dev/null @@ -1,1115 +0,0 @@ -// GPU test of the bindless set (src/vulkan_bindless.h) and the descriptor hash table (src/descriptor_table.h) with -// a translated shader. ps_tex.asm reads a T# and an S# from a descriptor table in the heap, looks both up in the -// table at set 0 binding 2 and samples the image and sampler the indices name. -// -// vk_bindless_test -// -// A full-screen triangle is drawn into 64x64 RGBA32F and read back, eight times: -// 1. the T# and S# are in the table behind keys that share the T#'s first slot, so the shader has to probe: -// every pixel is the texel of an 8x8 gradient under it; -// 2. the T# is erased: every pixel is the fallback at index 0 (zeros); -// 3. the T# is back among 200 more keys and the table has grown into a new buffer: the gradient again; -// 4. the T# is rebound to the decoy index: that image's colour; -// 5. the T# is rebound to the original index: the gradient again; -// 6. the T# is rebound again, but the command buffer that carried the upload is never submitted and the set is -// told so: the retry still has to show the decoy's colour, not the old mapping; -// 7. the original index is given another view: the decoy image's colour; -// 8. the original index is removed: the fallback. -// This runs with the descriptor-indexing flags the device has (update after bind, partially bound) and again -// without any. Exit 77 with "unsupported: ..." when the device lacks a feature the shaders need. -// LEONIDA_VK_VALIDATION=1 runs under VK_LAYER_KHRONOS_validation; a validation error fails the test. -#define VK_NO_PROTOTYPES -#include "vulkan_loader.h" -#include "vk_device_pick.h" -#include "vk_shader_fma.h" -#include "vk_pc_tail.h" -#include "spirv_capability.h" -#include "../src/spirv_words.h" -#include "../src/vulkan_bindless.h" - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#define CHECK(x) \ - do { \ - VkResult r_ = (x); \ - if (r_ != VK_SUCCESS) { \ - std::fprintf(stderr, "FAILED %s -> %d (line %d)\n", #x, r_, __LINE__); \ - return 1; \ - } \ - } while (0) -#define EXPECT(condition) \ - do { \ - if (!(condition)) { \ - std::fprintf(stderr, "line %d: %s\n", __LINE__, #condition); \ - return 1; \ - } \ - } while (0) - -namespace { - -using namespace leonida; - -constexpr int unsupported = 77; -unsigned g_validation_errors = 0; - -VKAPI_ATTR VkBool32 VKAPI_CALL on_message(VkDebugUtilsMessageSeverityFlagBitsEXT severity, - VkDebugUtilsMessageTypeFlagsEXT types, - const VkDebugUtilsMessengerCallbackDataEXT* data, void*) { - // Only validation-type errors count: a broken third-party layer must not fail the test. - if ((severity & VK_DEBUG_UTILS_MESSAGE_SEVERITY_ERROR_BIT_EXT) && (types & VK_DEBUG_UTILS_MESSAGE_TYPE_VALIDATION_BIT_EXT)) - ++g_validation_errors; - std::fprintf(stderr, "validation: %s\n", data && data->pMessage ? data->pMessage : "(no message)"); - return VK_FALSE; -} - -std::vector read_spv(const char* path) { - std::ifstream f(path, std::ios::binary | std::ios::ate); - if (!f) return {}; - return leonida::read_spirv_words(f, f.tellg()); -} - -// Expected RGBA values in this test are finite. Report the worst channel error per pixel. -float pixel_error(const float* pixel, const float* want) { - float error = 0; - for (int c = 0; c < 4; ++c) { - if (!std::isfinite(pixel[c])) return std::numeric_limits::infinity(); - error = std::max(error, std::fabs(pixel[c] - want[c])); - } - return error; -} - -DescriptorKey numbered(std::uint32_t n) { - return {n, 0x9e3779b9u * n, n ^ 0x55555555u, n >> 3, 7, n * n, 0x80000000u, ~n}; -} - -// How many slots the shader reads before it finds `key` (8: it does not), from the buffer contents alone. -std::uint32_t probe_depth(std::span table, const DescriptorKey& key) { - const std::uint32_t h = hash_descriptor_key(key), mask = table[0]; - for (std::uint32_t k = 0; k < 8; ++k) { - const std::uint32_t base = ((h + k) & mask) * 10; - bool match = true; - for (int j = 0; j < 8; ++j) match = match && table[base + 1 + j] == key[j]; - if (match) return k; - } - return 8; -} - -} // namespace - -int main(int argc, char** argv) { - if (argc < 3) { - std::fprintf(stderr, "usage: vk_bindless_test \n"); - return 2; - } - // A bad readback in a single channel must still fail when all three others match. - const float black[4]{}; - for (int c = 0; c < 4; ++c) { - float pixel[4]{}; - pixel[c] = std::numeric_limits::quiet_NaN(); - EXPECT(std::isinf(pixel_error(pixel, black))); - } - const std::vector shader_code[] = {read_spv(argv[1]), read_spv(argv[2])}; - for (int stage = 0; stage < 2; ++stage) { - if (shader_code[stage].empty()) { - std::fprintf(stderr, "cannot read %s\n", argv[1 + stage]); - return 1; - } - } - constexpr std::uint32_t W = 64, H = 64, TW = 8; - constexpr std::uint32_t table_va = 256; // console VA of the descriptor table: T# at +0, S# at +32 - // Any 8 dwords as the lookup key, except FORMAT (word 1 [28:20]): the translator picks the float, uint or sint - // view of the image from it, and every view this test binds is R8G8B8A8_UNORM, so it is 56 (8_8_8_8_UNORM). - // 0x22222222 had 34 (10_11_11_UINT): every sample went through the uint alias of a UNORM view, which Vulkan - // leaves undefined (VUID-vkCmdDraw-format-07753, reported by GPU-assisted validation). - constexpr std::uint32_t tsharp_word1 = (0x22222222u & ~(0x1FFu << 20)) | (56u << 20); - static_assert(((tsharp_word1 >> 20) & 0x1FF) == 56, "the T#'s FORMAT must be 8_8_8_8_UNORM"); - const DescriptorKey tsharp{0x11111111, tsharp_word1, 0x33333333, 0x44444444, - 0x55555555, 0x66666666, 0x77777777, 0x88888888}; - const std::array ssharp{0x5a5a0001, 0x00000002, 0x00000003, 0x00000004}; - - const PFN_vkGetInstanceProcAddr gipa = load_vulkan(); - if (!gipa) return 1; - VkInstance inst = VK_NULL_HANDLE; -#define LI(n) const auto n = reinterpret_cast(gipa(inst, #n)) - LI(vkCreateInstance); - LI(vkEnumerateInstanceLayerProperties); - const char* env = std::getenv("LEONIDA_VK_VALIDATION"); - const bool validation = env && std::strcmp(env, "0") != 0; - const char* layer = "VK_LAYER_KHRONOS_validation"; - const char* debug_utils = VK_EXT_DEBUG_UTILS_EXTENSION_NAME; - VkDebugUtilsMessengerCreateInfoEXT messenger_info{VK_STRUCTURE_TYPE_DEBUG_UTILS_MESSENGER_CREATE_INFO_EXT}; - messenger_info.messageSeverity = VK_DEBUG_UTILS_MESSAGE_SEVERITY_WARNING_BIT_EXT | VK_DEBUG_UTILS_MESSAGE_SEVERITY_ERROR_BIT_EXT; - messenger_info.messageType = VK_DEBUG_UTILS_MESSAGE_TYPE_GENERAL_BIT_EXT | VK_DEBUG_UTILS_MESSAGE_TYPE_VALIDATION_BIT_EXT; - messenger_info.pfnUserCallback = on_message; - VkApplicationInfo app{VK_STRUCTURE_TYPE_APPLICATION_INFO}; - app.apiVersion = VK_API_VERSION_1_2; - VkInstanceCreateInfo ici{VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO}; - ici.pApplicationInfo = &app; - if (validation) { - std::uint32_t count = 0; - vkEnumerateInstanceLayerProperties(&count, nullptr); - std::vector layers(count); - vkEnumerateInstanceLayerProperties(&count, layers.data()); - bool found = false; - for (const auto& properties : layers) found = found || std::strcmp(properties.layerName, layer) == 0; - if (!found) { - std::fprintf(stderr, "LEONIDA_VK_VALIDATION is set but %s is not installed\n", layer); - return 1; - } - ici.pNext = &messenger_info; - ici.enabledLayerCount = 1; - ici.ppEnabledLayerNames = &layer; - ici.enabledExtensionCount = 1; - ici.ppEnabledExtensionNames = &debug_utils; - } - CHECK(vkCreateInstance(&ici, nullptr, &inst)); - VkDebugUtilsMessengerEXT messenger = VK_NULL_HANDLE; - if (validation) { - LI(vkCreateDebugUtilsMessengerEXT); - CHECK(vkCreateDebugUtilsMessengerEXT(inst, &messenger_info, nullptr, &messenger)); - } - LI(vkEnumeratePhysicalDevices); LI(vkGetPhysicalDeviceProperties); LI(vkGetPhysicalDeviceQueueFamilyProperties); - LI(vkGetPhysicalDeviceMemoryProperties); LI(vkGetPhysicalDeviceFeatures2); LI(vkGetPhysicalDeviceProperties2); - LI(vkCreateDevice); LI(vkGetDeviceProcAddr); - std::uint32_t n = 0; - vkEnumeratePhysicalDevices(inst, &n, nullptr); - std::vector pds(n); - vkEnumeratePhysicalDevices(inst, &n, pds.data()); - // The same choice as the other tools (vk_device_pick.h): the best-ranked Vulkan 1.2 device that LEONIDA_VK_DEVICE - // allows. It used to rank every device and ignore the filter, so a run meant for one GPU took another (TEST-469). - // A filter that matches nothing fails, as in vk_compute_test and vk_test_device.h (as #2657 does it). - std::vector candidates; - std::vector eligible; - for (auto d : pds) { - VkPhysicalDeviceProperties p; - vkGetPhysicalDeviceProperties(d, &p); - if (p.apiVersion < VK_API_VERSION_1_2) continue; - candidates.push_back(p); - eligible.push_back(d); - } - const std::size_t chosen = leonida::vk_test::pick_device(candidates); - VkPhysicalDevice pd = chosen < eligible.size() ? eligible[chosen] : VK_NULL_HANDLE; - if (!pd) { - if (!leonida::vulkan_device_filter().empty()) { - leonida::vk_test::report_no_device(); - return 1; - } - std::printf("unsupported: no Vulkan 1.2 device\n"); - return unsupported; - } - VkPhysicalDeviceVulkan12Properties props12{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_2_PROPERTIES}; - VkPhysicalDeviceVulkan11Properties props11{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_1_PROPERTIES, &props12}; - VkPhysicalDeviceProperties2 props{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROPERTIES_2, &props11}; - vkGetPhysicalDeviceProperties2(pd, &props); - std::printf("device: %s%s\n", props.properties.deviceName, validation ? " (validation on)" : ""); - // The pipeline layout pushes the 144-byte translated user-data block. A device with fewer push constant bytes - // (128 on Intel Arc and some AMD drivers) can't create it: a device limit, not a wrong result (TEST-149). - // LEONIDA_PC_TAIL_UBO=1 (rdna2spirv.py --pc-tail-ubo): s0..s31 only, 128 bytes; the heap base, if a stage reads - // it, is in a uniform block at set 1 (vk_pc_tail.h). - const bool pc_tail = leonida::vk_test::pc_tail_requested(); - const std::uint32_t push_bytes = pc_tail ? 128u : 144u; - if (props.properties.limits.maxPushConstantsSize < push_bytes) { - std::printf("unsupported: need %u push constant bytes, device has %u\n", push_bytes, - props.properties.limits.maxPushConstantsSize); - return unsupported; - } - - // The features ps_tex's metadata names (bufferDeviceAddress, runtimeDescriptorArray), dynamic indexing of the - // image array, and whichever descriptor-indexing flags the set can use. shaderInt64 only when a stage has 64-bit - // integers: SHADER-423's address pairs need none (TEST-468). - VkPhysicalDeviceVulkan11Features have11{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_1_FEATURES}; - VkPhysicalDeviceVulkan12Features have12{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_2_FEATURES, &have11}; - VkPhysicalDeviceFeatures2 have{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2, &have12}; - vkGetPhysicalDeviceFeatures2(pd, &have); - const bool int64 = leonida::vk_test::needs_shader_int64(read_spv(argv[1])) || - leonida::vk_test::needs_shader_int64(read_spv(argv[2])); - if (!have12.bufferDeviceAddress || !have12.runtimeDescriptorArray || (int64 && !have.features.shaderInt64) || - !have.features.shaderSampledImageArrayDynamicIndexing) { - std::printf("unsupported: the device lacks bufferDeviceAddress, runtimeDescriptorArray, %s" - "shaderSampledImageArrayDynamicIndexing\n", int64 ? "shaderInt64 (a stage declares Int64) or " : ""); - return unsupported; - } - BindlessFeatures device_flags; - device_flags.update_after_bind = have12.descriptorBindingSampledImageUpdateAfterBind && - have12.descriptorBindingStorageImageUpdateAfterBind && - have12.descriptorBindingStorageBufferUpdateAfterBind; - device_flags.partially_bound = have12.descriptorBindingPartiallyBound == VK_TRUE; - // Translated vertex shaders read BaseVertex / BaseInstance (DrawParameters) for the zero-based v0 / v3. - VkPhysicalDeviceVulkan11Features enable11{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_1_FEATURES}; - enable11.shaderDrawParameters = have11.shaderDrawParameters; - VkPhysicalDeviceVulkan12Features enable12{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_2_FEATURES, &enable11}; - enable12.bufferDeviceAddress = VK_TRUE; - enable12.runtimeDescriptorArray = VK_TRUE; - enable12.descriptorIndexing = have12.descriptorIndexing; - enable12.descriptorBindingSampledImageUpdateAfterBind = device_flags.update_after_bind; - enable12.descriptorBindingStorageImageUpdateAfterBind = device_flags.update_after_bind; - enable12.descriptorBindingStorageBufferUpdateAfterBind = device_flags.update_after_bind; - enable12.descriptorBindingPartiallyBound = device_flags.partially_bound; - VkPhysicalDeviceFeatures2 enable{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2, &enable12}; - enable.features.shaderInt64 = int64 ? VK_TRUE : VK_FALSE; - enable.features.shaderSampledImageArrayDynamicIndexing = VK_TRUE; - bool dynamic_storage = false; - for (int stage = 0; stage < 2; ++stage) { - const auto& code = shader_code[stage]; - dynamic_storage = dynamic_storage || leonida::vk_test::spirv_declares_capability( - code.data(), code.size() * sizeof(code[0]), leonida::vk_test::spv_storage_image_array_dynamic_indexing); - } - if (dynamic_storage && !have.features.shaderStorageImageArrayDynamicIndexing) { - std::printf("unsupported: shaderStorageImageArrayDynamicIndexing\n"); - return unsupported; - } - enable.features.shaderStorageImageArrayDynamicIndexing = dynamic_storage; - // ps_imgatomic: image atomics in a pixel shader need fragment stores and atomics. - const bool atomic_mode = std::strstr(argv[2], "imgatomic") != nullptr; - if (atomic_mode) { - if (!have.features.fragmentStoresAndAtomics) { - std::printf("unsupported: fragmentStoresAndAtomics (image atomics in a pixel shader)\n"); - return unsupported; - } - enable.features.fragmentStoresAndAtomics = VK_TRUE; - } - - std::uint32_t qn = 0; - vkGetPhysicalDeviceQueueFamilyProperties(pd, &qn, nullptr); - std::vector qf(qn); - vkGetPhysicalDeviceQueueFamilyProperties(pd, &qn, qf.data()); - std::uint32_t qi = 0; - while (qi < qn && !(qf[qi].queueFlags & VK_QUEUE_GRAPHICS_BIT)) ++qi; - EXPECT(qi < qn); - const float priority = 1; - VkDeviceQueueCreateInfo qci{VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO}; - qci.queueFamilyIndex = qi; - qci.queueCount = 1; - qci.pQueuePriorities = &priority; - leonida::vk_test::ShaderFma fma; // OpFmaKHR (rdna2spirv.py --fma khr), when the device has it - fma.query(gipa, inst, pd); - // A device without VK_KHR_shader_fma cannot create a pipeline from a stage that uses OpFmaKHR: skip the pair. - if (!fma.accepts_file(argv[1]) || !fma.accepts_file(argv[2])) return 77; - fma.link_after(&enable); - const char* fma_extension = fma.extension(); - VkDeviceCreateInfo dci{VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO, &enable}; - dci.queueCreateInfoCount = 1; - dci.pQueueCreateInfos = &qci; - if (fma.supported()) { dci.enabledExtensionCount = 1; dci.ppEnabledExtensionNames = &fma_extension; } - VkDevice dev = VK_NULL_HANDLE; - CHECK(vkCreateDevice(pd, &dci, nullptr, &dev)); -#define LD(n) const auto n = reinterpret_cast(vkGetDeviceProcAddr(dev, #n)) - LD(vkGetDeviceQueue); LD(vkCreateImage); LD(vkGetImageMemoryRequirements); LD(vkAllocateMemory); - LD(vkBindImageMemory); LD(vkCreateImageView); LD(vkCreateRenderPass); LD(vkCreateFramebuffer); - LD(vkCreateShaderModule); LD(vkCreatePipelineLayout); LD(vkCreateGraphicsPipelines); LD(vkCreateCommandPool); - LD(vkAllocateCommandBuffers); LD(vkBeginCommandBuffer); LD(vkCmdBeginRenderPass); LD(vkCmdBindPipeline); - LD(vkCmdDraw); LD(vkCmdEndRenderPass); LD(vkCmdCopyImageToBuffer); LD(vkCmdCopyBufferToImage); - LD(vkEndCommandBuffer); LD(vkQueueSubmit); LD(vkQueueWaitIdle); LD(vkCreateBuffer); LD(vkResetCommandBuffer); - LD(vkGetBufferMemoryRequirements); LD(vkBindBufferMemory); LD(vkMapMemory); LD(vkGetBufferDeviceAddress); - LD(vkCreateSampler); LD(vkCmdBindDescriptorSets); LD(vkCmdPushConstants); LD(vkCmdPipelineBarrier); - LD(vkDeviceWaitIdle); LD(vkDestroyPipeline); LD(vkDestroyPipelineLayout); - LD(vkDestroyCommandPool); LD(vkDestroyShaderModule); LD(vkDestroyFramebuffer); LD(vkDestroyRenderPass); - LD(vkDestroySampler); LD(vkDestroyImageView); LD(vkDestroyImage); LD(vkDestroyBuffer); - LD(vkFreeMemory); LD(vkDestroyDevice); LD(vkCmdClearColorImage); - VkQueue queue = VK_NULL_HANDLE; - vkGetDeviceQueue(dev, qi, 0, &queue); - VkPhysicalDeviceMemoryProperties mp; - vkGetPhysicalDeviceMemoryProperties(pd, &mp); - const auto memtype = [&](std::uint32_t bits, VkMemoryPropertyFlags want) { - for (std::uint32_t i = 0; i < mp.memoryTypeCount; i++) - if ((bits & (1u << i)) && (mp.memoryTypes[i].propertyFlags & want) == want) return i; - return 0u; - }; - std::vector allocations; - const auto make_buffer = [&](VkDeviceSize size, VkBufferUsageFlags usage, VkBuffer* b, void** map) { - VkBufferCreateInfo bi{VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO}; - bi.size = size; - bi.usage = usage; - VkResult r = vkCreateBuffer(dev, &bi, nullptr, b); - if (r) return r; - VkMemoryRequirements mr; - vkGetBufferMemoryRequirements(dev, *b, &mr); - VkMemoryAllocateFlagsInfo fi{VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_FLAGS_INFO}; - fi.flags = VK_MEMORY_ALLOCATE_DEVICE_ADDRESS_BIT; - VkMemoryAllocateInfo ai{VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO}; - ai.pNext = (usage & VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT) ? &fi : nullptr; - ai.allocationSize = mr.size; - ai.memoryTypeIndex = memtype(mr.memoryTypeBits, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT); - VkDeviceMemory m; - r = vkAllocateMemory(dev, &ai, nullptr, &m); - if (r) return r; - allocations.push_back(m); - r = vkBindBufferMemory(dev, *b, m, 0); - if (r) return r; - return vkMapMemory(dev, m, 0, size, 0, map); - }; - const auto make_image = [&](VkFormat format, std::uint32_t w, std::uint32_t h, VkImageUsageFlags usage, VkImage* image, - VkImageView* view) { - VkImageCreateInfo ii{VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO}; - ii.imageType = VK_IMAGE_TYPE_2D; - ii.format = format; - ii.extent = {w, h, 1}; - ii.mipLevels = 1; - ii.arrayLayers = 1; - ii.samples = VK_SAMPLE_COUNT_1_BIT; - ii.usage = usage; - VkResult r = vkCreateImage(dev, &ii, nullptr, image); - if (r) return r; - VkMemoryRequirements mr; - vkGetImageMemoryRequirements(dev, *image, &mr); - VkMemoryAllocateInfo ai{VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO}; - ai.allocationSize = mr.size; - ai.memoryTypeIndex = memtype(mr.memoryTypeBits, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT); - VkDeviceMemory m; - r = vkAllocateMemory(dev, &ai, nullptr, &m); - if (r) return r; - allocations.push_back(m); - r = vkBindImageMemory(dev, *image, m, 0); - if (r) return r; - VkImageViewCreateInfo vi{VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO}; - vi.image = *image; - vi.viewType = VK_IMAGE_VIEW_TYPE_2D; - vi.format = format; - vi.subresourceRange = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1}; - return vkCreateImageView(dev, &vi, nullptr, view); - }; - - // The heap (the console's GPU address window): zeros, with the descriptor table at table_va. - VkBuffer heap; - void* heap_map; - CHECK(make_buffer(65536, VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT, &heap, &heap_map)); - std::memset(heap_map, 0, 65536); - std::memcpy(static_cast(heap_map) + table_va, tsharp.data(), 32); - std::memcpy(static_cast(heap_map) + table_va + 32, ssharp.data(), 16); - VkBufferDeviceAddressInfo address_info{VK_STRUCTURE_TYPE_BUFFER_DEVICE_ADDRESS_INFO}; - address_info.buffer = heap; - const VkDeviceAddress heap_base = vkGetBufferDeviceAddress(dev, &address_info); - - // Textures: an 8x8 gradient (r = x / 8, g = y / 8, b = 0.5, a = 1 in steps of 32/255), a 1x1 orange decoy, and - // a 1x1 image with storage usage to go through the storage bindings. - constexpr VkImageUsageFlags sampled_usage = VK_IMAGE_USAGE_SAMPLED_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT; - VkImage gradient, decoy, stored; - VkImageView gradient_view, decoy_view, stored_view; - CHECK(make_image(VK_FORMAT_R8G8B8A8_UNORM, TW, TW, sampled_usage, &gradient, &gradient_view)); - CHECK(make_image(VK_FORMAT_R8G8B8A8_UNORM, 1, 1, sampled_usage, &decoy, &decoy_view)); - CHECK(make_image(VK_FORMAT_R8G8B8A8_UNORM, 1, 1, sampled_usage | VK_IMAGE_USAGE_STORAGE_BIT, &stored, &stored_view)); - std::vector texels(TW * TW); - for (std::uint32_t y = 0; y < TW; y++) - for (std::uint32_t x = 0; x < TW; x++) texels[y * TW + x] = (x * 32u) | ((y * 32u) << 8) | (128u << 16) | (255u << 24); - constexpr std::uint32_t orange = 0xff0080ffu; // r = 255, g = 128, b = 0, a = 255 - VkBuffer upload; - void* upload_map; - CHECK(make_buffer(4096, VK_BUFFER_USAGE_TRANSFER_SRC_BIT, &upload, &upload_map)); - std::memcpy(upload_map, texels.data(), texels.size() * 4); - std::memcpy(static_cast(upload_map) + 1024, &orange, 4); - VkSamplerCreateInfo sci{VK_STRUCTURE_TYPE_SAMPLER_CREATE_INFO}; - sci.magFilter = sci.minFilter = VK_FILTER_NEAREST; - sci.addressModeU = sci.addressModeV = sci.addressModeW = VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE; - VkSampler nearest; - CHECK(vkCreateSampler(dev, &sci, nullptr, &nearest)); - - // Render target, pass and framebuffer. - constexpr VkFormat target_format = VK_FORMAT_R32G32B32A32_SFLOAT; - VkImage target; - VkImageView target_view; - CHECK(make_image(target_format, W, H, VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | VK_IMAGE_USAGE_TRANSFER_SRC_BIT, &target, - &target_view)); - VkAttachmentDescription ad{}; - ad.format = target_format; - ad.samples = VK_SAMPLE_COUNT_1_BIT; - ad.loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR; - ad.storeOp = VK_ATTACHMENT_STORE_OP_STORE; - ad.stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE; - ad.stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE; - ad.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED; - ad.finalLayout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL; - const VkAttachmentReference ar{0, VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL}; - VkSubpassDescription sd{}; - sd.pipelineBindPoint = VK_PIPELINE_BIND_POINT_GRAPHICS; - sd.colorAttachmentCount = 1; - sd.pColorAttachments = &ar; - // The read back that follows the pass waits for its last write and its final layout transition. - VkSubpassDependency after{}; - after.srcSubpass = 0; - after.dstSubpass = VK_SUBPASS_EXTERNAL; - after.srcStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT; - after.dstStageMask = VK_PIPELINE_STAGE_TRANSFER_BIT; - after.srcAccessMask = VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT; - after.dstAccessMask = VK_ACCESS_TRANSFER_READ_BIT; - VkRenderPassCreateInfo rpi{VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO}; - rpi.attachmentCount = 1; - rpi.pAttachments = &ad; - rpi.subpassCount = 1; - rpi.pSubpasses = &sd; - rpi.dependencyCount = 1; - rpi.pDependencies = &after; - VkRenderPass pass; - CHECK(vkCreateRenderPass(dev, &rpi, nullptr, &pass)); - VkFramebufferCreateInfo fbi{VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO}; - fbi.renderPass = pass; - fbi.attachmentCount = 1; - fbi.pAttachments = &target_view; - fbi.width = W; - fbi.height = H; - fbi.layers = 1; - VkFramebuffer framebuffer; - CHECK(vkCreateFramebuffer(dev, &fbi, nullptr, &framebuffer)); - VkBuffer readback; - void* readback_map; - CHECK(make_buffer(VkDeviceSize(W) * H * 16, VK_BUFFER_USAGE_TRANSFER_DST_BIT, &readback, &readback_map)); - - VkShaderModule vs, fs; - bool tail_block = false; - for (int stage = 0; stage < 2; ++stage) { - const auto& code = shader_code[stage]; - if (pc_tail && leonida::vk_test::spirv_declares_set(code.data(), code.size() * 4, leonida::vk_test::pc_tail_set)) - tail_block = true; - VkShaderModuleCreateInfo smi{VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO}; - smi.codeSize = code.size() * 4; - smi.pCode = code.data(); - CHECK(vkCreateShaderModule(dev, &smi, nullptr, stage ? &fs : &vs)); - } - // One tail block for every variant below: each draw's tail is the same heap base. - leonida::vk_test::PcTail tail; - if (tail_block && !tail.create(vkGetDeviceProcAddr, dev, mp, props.properties.limits.minUniformBufferOffsetAlignment, - VK_SHADER_STAGE_VERTEX_BIT | VK_SHADER_STAGE_FRAGMENT_BIT, 1)) { - std::fprintf(stderr, "FAILED creating the --pc-tail-ubo block\n"); - return 1; - } - auto bind_tail = [&](VkCommandBuffer cb, VkPipelineLayout layout, const std::uint32_t* block) { - if (!tail_block) return; - tail.write(0, block, 4); - const std::uint32_t offset = tail.offset(0); - vkCmdBindDescriptorSets(cb, VK_PIPELINE_BIND_POINT_GRAPHICS, layout, leonida::vk_test::pc_tail_set, 1, &tail.set, - 1, &offset); - }; - VkCommandPoolCreateInfo cpi{VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO}; - cpi.flags = VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT; - cpi.queueFamilyIndex = qi; - VkCommandPool pool; - CHECK(vkCreateCommandPool(dev, &cpi, nullptr, &pool)); - VkCommandBufferAllocateInfo cai{VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO}; - cai.commandPool = pool; - cai.commandBufferCount = 1; - VkCommandBuffer cmd; - CHECK(vkAllocateCommandBuffers(dev, &cai, &cmd)); - const VkCommandBufferBeginInfo begin{VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO}; - const auto submit = [&]() { - VkResult r = vkEndCommandBuffer(cmd); - if (r) return r; - VkSubmitInfo si{VK_STRUCTURE_TYPE_SUBMIT_INFO}; - si.commandBufferCount = 1; - si.pCommandBuffers = &cmd; - r = vkQueueSubmit(queue, 1, &si, VK_NULL_HANDLE); - return r ? r : vkQueueWaitIdle(queue); - }; - - // Upload the textures. The sampled ones end in SHADER_READ_ONLY_OPTIMAL, the storage one in GENERAL. - CHECK(vkBeginCommandBuffer(cmd, &begin)); - const struct { VkImage image; std::uint32_t size; VkDeviceSize offset; VkImageLayout layout; } uploads[] = { - {gradient, TW, 0, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL}, - {decoy, 1, 1024, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL}, - {stored, 1, 0, VK_IMAGE_LAYOUT_GENERAL}}; - for (const auto& u : uploads) { - VkImageMemoryBarrier ib{VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER}; - ib.oldLayout = VK_IMAGE_LAYOUT_UNDEFINED; - ib.newLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL; - ib.image = u.image; - ib.subresourceRange = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1}; - ib.dstAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT; - ib.srcQueueFamilyIndex = ib.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; - vkCmdPipelineBarrier(cmd, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, 0, 0, nullptr, 0, nullptr, 1, &ib); - VkBufferImageCopy c{}; - c.bufferOffset = u.offset; - c.imageSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1}; - c.imageExtent = {u.size, u.size, 1}; - vkCmdCopyBufferToImage(cmd, upload, u.image, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, &c); - ib.oldLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL; - ib.newLayout = u.layout; - ib.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT; - ib.dstAccessMask = VK_ACCESS_SHADER_READ_BIT; - vkCmdPipelineBarrier(cmd, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT, 0, 0, nullptr, 0, nullptr, 1, &ib); - } - CHECK(submit()); - - // An adapter at the original 5632 sampled-image limit must keep the original set. The per-stage - // resource budget can also leave room for just one class (9985 original resources + 512). - constexpr auto ms_classes = [](std::uint32_t sampled, std::uint32_t total) { - BindlessFeatures f{}; - f.ms_samples.fill(VK_SAMPLE_COUNT_4_BIT); - bindless::limit_ms_bindings(f, sampled, total); - return f.ms_samples; - }; - static_assert(ms_classes(5632, 20000) == - std::array{VK_SAMPLE_COUNT_1_BIT, VK_SAMPLE_COUNT_1_BIT, VK_SAMPLE_COUNT_1_BIT}); - static_assert(ms_classes(7168, 10497) == - std::array{VK_SAMPLE_COUNT_4_BIT, VK_SAMPLE_COUNT_1_BIT, VK_SAMPLE_COUNT_1_BIT}); - - // Does a set with these flags fit the device? Every binding is visible to every stage. - const auto descriptors = [](VkDescriptorType type, const BindlessFeatures& f) { - std::uint32_t count = 0; - for (std::uint32_t b = 0; b < bindless::bindings.size(); ++b) - if (bindless::bindings[b].type == type && bindless::binding_enabled(b, f)) - count += f.counts[b]; - return count; - }; - const auto fits = [&](const BindlessFeatures& f) { - const auto sampled_total = descriptors(VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE, f); - const auto sampler_total = descriptors(VK_DESCRIPTOR_TYPE_SAMPLER, f); - const auto storage_total = descriptors(VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, f); - const auto stage_resources = sampled_total + storage_total + 2; // table buffer and fragment output - const VkPhysicalDeviceLimits& l = props.properties.limits; - if (f.update_after_bind) - return props12.maxPerStageDescriptorUpdateAfterBindSampledImages >= sampled_total && - props12.maxPerStageDescriptorUpdateAfterBindSamplers >= sampler_total && - props12.maxPerStageDescriptorUpdateAfterBindStorageImages >= storage_total && - props12.maxPerStageUpdateAfterBindResources >= stage_resources && - props12.maxUpdateAfterBindDescriptorsInAllPools >= sampled_total + sampler_total + storage_total + 1 && - props12.maxDescriptorSetUpdateAfterBindSampledImages >= sampled_total && - props12.maxDescriptorSetUpdateAfterBindSamplers >= sampler_total && - props12.maxDescriptorSetUpdateAfterBindStorageImages >= storage_total; - return l.maxPerStageDescriptorSampledImages >= sampled_total && l.maxPerStageDescriptorSamplers >= sampler_total && - l.maxPerStageDescriptorStorageImages >= storage_total && - l.maxPerStageResources >= stage_resources && - l.maxDescriptorSetSampledImages >= sampled_total && l.maxDescriptorSetSamplers >= sampler_total && - l.maxDescriptorSetStorageImages >= storage_total; - }; - - unsigned mismatches = 0, runs = 0, readbacks = 0; - float worst = 0; - // What the 64x64 target must hold: the texel under each pixel, or one colour everywhere. - const auto compare = [&](const char* what, const float* colour) { - ++readbacks; - const float* got = static_cast(readback_map); - for (std::uint32_t y = 0; y < H; ++y) { - for (std::uint32_t x = 0; x < W; ++x) { - const float gradient_texel[4] = {float(x * TW / W * 32) / 255.0f, float(y * TW / H * 32) / 255.0f, 128.0f / 255.0f, 1.0f}; - const float* want = colour ? colour : gradient_texel; - const float* pixel = got + (std::size_t(y) * W + x) * 4; - const float error = pixel_error(pixel, want); - worst = std::max(worst, error); - if (error <= 1e-6f) continue; - if (mismatches++ < 6) - std::fprintf(stderr, "%s pixel (%u, %u): got %g %g %g %g, want %g %g %g %g\n", what, x, y, pixel[0], - pixel[1], pixel[2], pixel[3], want[0], want[1], want[2], want[3]); - } - } - }; - - BindlessFeatures configurations[2] = {device_flags, {}}; - const int configuration_count = (device_flags.update_after_bind || device_flags.partially_bound) ? 2 : 1; - for (int configuration = 0; configuration < configuration_count; ++configuration) { - BindlessFeatures flags = configurations[configuration]; - flags.ms_samples[0] = VK_SAMPLE_COUNT_4_BIT; - // A device below the default counts gets a smaller set; this test needs at least those. - const bool full = bindless::size_bindings(flags, props.properties.limits, props11, props12); - const char* name = flags.update_after_bind && flags.partially_bound ? "update after bind, partially bound" - : flags.update_after_bind ? "update after bind" : flags.partially_bound ? "partially bound" : "no flags"; - if (!full || !fits(flags)) { - std::printf("%s: skipped, the set does not fit this device's descriptor limits\n", name); - continue; - } - BindlessSet set(vkGetDeviceProcAddr, dev, mp, flags); - EXPECT(set.ok() && set.layout() && set.set()); - - const VkPushConstantRange push{VK_SHADER_STAGE_VERTEX_BIT | VK_SHADER_STAGE_FRAGMENT_BIT, 0, push_bytes}; - const VkDescriptorSetLayout set_layout = set.layout(); - VkPipelineLayoutCreateInfo pli{VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO}; - pli.setLayoutCount = 1; - pli.pSetLayouts = &set_layout; - pli.pushConstantRangeCount = 1; - pli.pPushConstantRanges = &push; - const VkDescriptorSetLayout set_layouts[] = {set_layout, tail.set_layout}; - if (tail_block) { pli.setLayoutCount = 2; pli.pSetLayouts = set_layouts; } - VkPipelineLayout pipeline_layout; - CHECK(vkCreatePipelineLayout(dev, &pli, nullptr, &pipeline_layout)); - VkPipelineShaderStageCreateInfo stages[2]{{VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO}, - {VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO}}; - stages[0].stage = VK_SHADER_STAGE_VERTEX_BIT; - stages[0].module = vs; - stages[0].pName = "main"; - stages[1].stage = VK_SHADER_STAGE_FRAGMENT_BIT; - stages[1].module = fs; - stages[1].pName = "main"; - const VkPipelineVertexInputStateCreateInfo vertex_input{VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO}; - VkPipelineInputAssemblyStateCreateInfo assembly{VK_STRUCTURE_TYPE_PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO}; - assembly.topology = VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST; - const VkViewport viewport{0, 0, float(W), float(H), 0, 1}; - const VkRect2D scissor{{0, 0}, {W, H}}; - VkPipelineViewportStateCreateInfo viewports{VK_STRUCTURE_TYPE_PIPELINE_VIEWPORT_STATE_CREATE_INFO}; - viewports.viewportCount = 1; - viewports.pViewports = &viewport; - viewports.scissorCount = 1; - viewports.pScissors = &scissor; - VkPipelineRasterizationStateCreateInfo raster{VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_STATE_CREATE_INFO}; - raster.cullMode = VK_CULL_MODE_NONE; - raster.lineWidth = 1; - VkPipelineMultisampleStateCreateInfo multisample{VK_STRUCTURE_TYPE_PIPELINE_MULTISAMPLE_STATE_CREATE_INFO}; - multisample.rasterizationSamples = VK_SAMPLE_COUNT_1_BIT; - VkPipelineColorBlendAttachmentState blend_attachment{}; - blend_attachment.colorWriteMask = 0xf; - VkPipelineColorBlendStateCreateInfo blend{VK_STRUCTURE_TYPE_PIPELINE_COLOR_BLEND_STATE_CREATE_INFO}; - blend.attachmentCount = 1; - blend.pAttachments = &blend_attachment; - VkGraphicsPipelineCreateInfo gpi{VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO}; - gpi.stageCount = 2; - gpi.pStages = stages; - gpi.pVertexInputState = &vertex_input; - gpi.pInputAssemblyState = &assembly; - gpi.pViewportState = &viewports; - gpi.pRasterizationState = &raster; - gpi.pMultisampleState = &multisample; - gpi.pColorBlendState = &blend; - gpi.layout = pipeline_layout; - gpi.renderPass = pass; - VkPipeline pipeline; - CHECK(vkCreateGraphicsPipelines(dev, VK_NULL_HANDLE, 1, &gpi, nullptr, &pipeline)); - - // One draw and read back. The first also initialises the set's fallback images. - const auto draw = [&]() { - vkResetCommandBuffer(cmd, 0); - VkResult r = vkBeginCommandBuffer(cmd, &begin); - if (r) return r; - if (!set.fallbacks_ready()) set.record_fallback_init(cmd); - VkClearValue clear{}; - for (float& channel : clear.color.float32) channel = 0.25f; // neither a texel nor the fallback - VkRenderPassBeginInfo rbi{VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO}; - rbi.renderPass = pass; - rbi.framebuffer = framebuffer; - rbi.renderArea = scissor; - rbi.clearValueCount = 1; - rbi.pClearValues = &clear; - vkCmdBeginRenderPass(cmd, &rbi, VK_SUBPASS_CONTENTS_INLINE); - vkCmdBindPipeline(cmd, VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline); - const VkDescriptorSet bound = set.set(); - vkCmdBindDescriptorSets(cmd, VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline_layout, 0, 1, &bound, 0, nullptr); - std::uint32_t block[36] = {}; - block[2] = table_va; // s2:s3 = console VA of the descriptor table - block[32] = std::uint32_t(heap_base); - block[33] = std::uint32_t(heap_base >> 32); - vkCmdPushConstants(cmd, pipeline_layout, VK_SHADER_STAGE_VERTEX_BIT | VK_SHADER_STAGE_FRAGMENT_BIT, 0, push_bytes, block); - bind_tail(cmd, pipeline_layout, block); - vkCmdDraw(cmd, 3, 1, 0, 0); - vkCmdEndRenderPass(cmd); - VkBufferImageCopy rc{}; - rc.imageSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1}; - rc.imageExtent = {W, H, 1}; - vkCmdCopyImageToBuffer(cmd, target, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, readback, 1, &rc); - return submit(); - }; - - // Uploads the table where the device does: the copy and its barrier are recorded in a command buffer that - // runs before the draws that read binding 2. - const auto flush = [&]() { - vkResetCommandBuffer(cmd, 0); - if (const VkResult r = vkBeginCommandBuffer(cmd, &begin); r != VK_SUCCESS) return false; - // Ticket 1: what a flush that replaces the table stamps its retired generation with; release_retired(0) - // below must keep it, as the owner's completed ticket 0 means nothing has finished. - const bool ok = set.flush(cmd, 1); - return submit() == VK_SUCCESS && ok; - }; - - // Index spaces. An image with storage views gets an index the storage arrays hold; one without goes above - // them where the dimension has room. A dimension that is full gives 0, and removed indices come back. - StorageViews as_storage; - as_storage.as_float = stored_view; - const std::uint32_t stored_index = set.add_image(ImageDimension::dim_2d, stored_view, VK_IMAGE_LAYOUT_GENERAL, as_storage); - const std::uint32_t decoy_index = set.add_image(ImageDimension::dim_2d, decoy_view, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL); - const std::uint32_t gradient_index = set.add_image(ImageDimension::dim_2d, gradient_view, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL); - EXPECT(stored_index >= 1 && stored_index < set.storage_capacity(ImageDimension::dim_2d)); - EXPECT(decoy_index >= set.storage_capacity(ImageDimension::dim_2d) && gradient_index > decoy_index); - EXPECT(gradient_index < set.image_capacity(ImageDimension::dim_2d)); - std::vector filled; - for (std::uint32_t i = 1; i < set.image_capacity(ImageDimension::dim_1d); ++i) - filled.push_back(set.add_image(ImageDimension::dim_1d, VK_NULL_HANDLE, VK_IMAGE_LAYOUT_GENERAL)); - EXPECT(filled.front() == 1 && filled.back() == set.image_capacity(ImageDimension::dim_1d) - 1); - EXPECT(set.free_images(ImageDimension::dim_1d) == 0); - EXPECT(set.add_image(ImageDimension::dim_1d, VK_NULL_HANDLE, VK_IMAGE_LAYOUT_GENERAL) == 0); - set.remove_image(ImageDimension::dim_1d, 7); - EXPECT(set.add_image(ImageDimension::dim_1d, VK_NULL_HANDLE, VK_IMAGE_LAYOUT_GENERAL) == 7); - for (const std::uint32_t index : filled) set.remove_image(ImageDimension::dim_1d, index); - EXPECT(set.free_images(ImageDimension::dim_1d) == set.image_capacity(ImageDimension::dim_1d) - 1); - EXPECT(set.free_samplers() == set.sampler_capacity() - 1); - const std::uint32_t decoy_sampler = set.add_sampler(nearest); - const std::uint32_t sampler_index = set.add_sampler(nearest); - EXPECT(decoy_sampler == 1 && sampler_index == 2 && set.free_samplers() == set.sampler_capacity() - 3); - - if (atomic_mode) { - // ps_imgatomic.asm: image_atomic_umax/umin/or on three 8x8 r32ui images and umax on a 4x4x4 one, from - // every pixel of the 64x64 draw (64 pixels per 2D texel), each found through its own T# key. Odd - // pixels are discarded after their atomics, which still count. - constexpr std::uint32_t atomic_va = 1024, AW = 8, A3 = 4; - const std::array keys{{{0xa1, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7, 0xa8}, - {0xb1, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6, 0xb7, 0xb8}, - {0xc1, 0xc2, 0xc3, 0xc4, 0xc5, 0xc6, 0xc7, 0xc8}, - {0xd1, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, 0xd8}}}; - for (std::uint32_t k = 0; k < 4; ++k) - std::memcpy(static_cast(heap_map) + atomic_va + 32 * k, keys[k].data(), 32); - const VkImageUsageFlags atomic_usage = - VK_IMAGE_USAGE_STORAGE_BIT | VK_IMAGE_USAGE_SAMPLED_BIT | VK_IMAGE_USAGE_TRANSFER_SRC_BIT | - VK_IMAGE_USAGE_TRANSFER_DST_BIT; - VkImage images[4]; - VkImageView views[4]; - for (int k = 0; k < 3; ++k) CHECK(make_image(VK_FORMAT_R32_UINT, AW, AW, atomic_usage, &images[k], &views[k])); - { // the 3D image - VkImageCreateInfo ii{VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO}; - ii.imageType = VK_IMAGE_TYPE_3D; - ii.format = VK_FORMAT_R32_UINT; - ii.extent = {A3, A3, A3}; - ii.mipLevels = 1; - ii.arrayLayers = 1; - ii.samples = VK_SAMPLE_COUNT_1_BIT; - ii.usage = atomic_usage; - CHECK(vkCreateImage(dev, &ii, nullptr, &images[3])); - VkMemoryRequirements mr; - vkGetImageMemoryRequirements(dev, images[3], &mr); - VkMemoryAllocateInfo ai{VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO}; - ai.allocationSize = mr.size; - ai.memoryTypeIndex = memtype(mr.memoryTypeBits, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT); - VkDeviceMemory m; - CHECK(vkAllocateMemory(dev, &ai, nullptr, &m)); - allocations.push_back(m); - CHECK(vkBindImageMemory(dev, images[3], m, 0)); - VkImageViewCreateInfo vi{VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO}; - vi.image = images[3]; - vi.viewType = VK_IMAGE_VIEW_TYPE_3D; - vi.format = VK_FORMAT_R32_UINT; - vi.subresourceRange = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1}; - CHECK(vkCreateImageView(dev, &vi, nullptr, &views[3])); - } - std::uint32_t indices[4]; - for (int k = 0; k < 4; ++k) { - StorageViews storage; - storage.as_uint = views[k]; - storage.r32ui = views[k]; - indices[k] = set.add_image(k == 3 ? ImageDimension::dim_3d : ImageDimension::dim_2d, views[k], - VK_IMAGE_LAYOUT_GENERAL, storage); - EXPECT(indices[k] != 0); - EXPECT(set.insert_key(keys[k], indices[k])); - } - EXPECT(flush()); - - // Clear: umax and or start at 0, umin at all ones; then GENERAL for the shader's atomics. - CHECK(vkResetCommandBuffer(cmd, 0)); - CHECK(vkBeginCommandBuffer(cmd, &begin)); - if (!set.fallbacks_ready()) set.record_fallback_init(cmd); - for (int k = 0; k < 4; ++k) { - VkImageMemoryBarrier b{VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER}; - b.dstAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT; - b.oldLayout = VK_IMAGE_LAYOUT_UNDEFINED; - b.newLayout = VK_IMAGE_LAYOUT_GENERAL; - b.srcQueueFamilyIndex = b.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; - b.image = images[k]; - b.subresourceRange = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1}; - vkCmdPipelineBarrier(cmd, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, 0, 0, - nullptr, 0, nullptr, 1, &b); - VkClearColorValue value{}; - for (auto& c : value.uint32) c = k == 1 ? 0xFFFFFFFFu : 0u; - vkCmdClearColorImage(cmd, images[k], VK_IMAGE_LAYOUT_GENERAL, &value, 1, &b.subresourceRange); - b.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT; - b.dstAccessMask = VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT; - b.oldLayout = b.newLayout = VK_IMAGE_LAYOUT_GENERAL; - vkCmdPipelineBarrier(cmd, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT, 0, 0, - nullptr, 0, nullptr, 1, &b); - } - CHECK(submit()); - - // The draw, then the images and the render target read back. - const VkDeviceSize image_bytes = 3 * AW * AW * 4 + A3 * A3 * A3 * 4; - VkBuffer atomic_readback; - void* atomic_map; - CHECK(make_buffer(image_bytes, VK_BUFFER_USAGE_TRANSFER_DST_BIT, &atomic_readback, &atomic_map)); - CHECK(vkResetCommandBuffer(cmd, 0)); - CHECK(vkBeginCommandBuffer(cmd, &begin)); - VkClearValue clear{}; - for (float& channel : clear.color.float32) channel = 0.25f; - VkRenderPassBeginInfo rbi{VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO}; - rbi.renderPass = pass; - rbi.framebuffer = framebuffer; - rbi.renderArea = scissor; - rbi.clearValueCount = 1; - rbi.pClearValues = &clear; - vkCmdBeginRenderPass(cmd, &rbi, VK_SUBPASS_CONTENTS_INLINE); - vkCmdBindPipeline(cmd, VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline); - const VkDescriptorSet bound = set.set(); - vkCmdBindDescriptorSets(cmd, VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline_layout, 0, 1, &bound, 0, nullptr); - std::uint32_t block[36] = {}; - block[2] = atomic_va; - block[32] = std::uint32_t(heap_base); - block[33] = std::uint32_t(heap_base >> 32); - vkCmdPushConstants(cmd, pipeline_layout, VK_SHADER_STAGE_VERTEX_BIT | VK_SHADER_STAGE_FRAGMENT_BIT, 0, - push_bytes, block); - bind_tail(cmd, pipeline_layout, block); - vkCmdDraw(cmd, 3, 1, 0, 0); - vkCmdEndRenderPass(cmd); - VkMemoryBarrier after{VK_STRUCTURE_TYPE_MEMORY_BARRIER}; - after.srcAccessMask = VK_ACCESS_SHADER_WRITE_BIT; - after.dstAccessMask = VK_ACCESS_TRANSFER_READ_BIT; - vkCmdPipelineBarrier(cmd, VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, 0, 1, &after, - 0, nullptr, 0, nullptr); - VkDeviceSize offset = 0; - for (int k = 0; k < 4; ++k) { - VkBufferImageCopy rc{}; - rc.bufferOffset = offset; - rc.imageSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1}; - rc.imageExtent = k == 3 ? VkExtent3D{A3, A3, A3} : VkExtent3D{AW, AW, 1}; - vkCmdCopyImageToBuffer(cmd, images[k], VK_IMAGE_LAYOUT_GENERAL, atomic_readback, 1, &rc); - offset += k == 3 ? A3 * A3 * A3 * 4 : AW * AW * 4; - } - VkBufferImageCopy tc{}; - tc.imageSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1}; - tc.imageExtent = {W, H, 1}; - vkCmdCopyImageToBuffer(cmd, target, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, readback, 1, &tc); - CHECK(submit()); - - // The model: every pixel's atomics, discarded or not. - std::vector want(3 * AW * AW + A3 * A3 * A3, 0); - for (std::uint32_t t = 0; t < AW * AW; ++t) want[AW * AW + t] = 0xFFFFFFFFu; - for (std::uint32_t py = 0; py < H; ++py) - for (std::uint32_t px = 0; px < W; ++px) { - const std::uint32_t id = px + 64 * py, t = (py >> 3) * AW + (px >> 3); - want[t] = std::max(want[t], id); - want[AW * AW + t] = std::min(want[AW * AW + t], id); - want[2 * AW * AW + t] |= 1u << (id & 31); - const std::uint32_t v = ((px & 3) * A3 + (py >> 4)) * A3 + (px >> 4); - want[3 * AW * AW + v] = std::max(want[3 * AW * AW + v], id); - } - const auto* got = static_cast(atomic_map); - const char* names[] = {"2D umax", "2D umin", "2D or", "3D umax"}; - unsigned wrong = 0; - for (std::size_t i = 0; i < want.size(); ++i) { - if (got[i] == want[i]) continue; - const int k = i < 3 * AW * AW ? int(i / (AW * AW)) : 3; - if (wrong++ < 8) - std::printf(" %s texel %zu: got 0x%08x, want 0x%08x\n", names[k], - k == 3 ? i - 3 * AW * AW : i % (AW * AW), got[i], want[i]); - } - const float* rt = static_cast(readback_map); - unsigned bad_rt = 0; - for (std::uint32_t py = 0; py < H; ++py) - for (std::uint32_t px = 0; px < W; ++px) - bad_rt += rt[(py * W + px) * 4] != ((px & 1) ? 0.25f : 1.0f); - std::printf("ps_imgatomic: %u of %zu texels wrong (2D umax/umin/or 8x8 each, 3D umax 4x4x4); " - "%u of %u render-target pixels wrong (odd columns discarded)\n", - wrong, want.size(), bad_rt, W * H); - vkDeviceWaitIdle(dev); - if (g_validation_errors) { - std::printf("ps_imgatomic: %u validation errors\n", g_validation_errors); - return 1; - } - return wrong || bad_rt ? 1 : 0; - } - - // A view that comes and goes before the set is flushed is never written: a texture created and destroyed - // between two submissions. Its slots are written once, with the fallback; a write of the destroyed view - // would be a validation error. - { - VkImageViewCreateInfo vi{VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO}; - vi.image = stored; - vi.viewType = VK_IMAGE_VIEW_TYPE_2D; - vi.format = VK_FORMAT_R8G8B8A8_UNORM; - vi.subresourceRange = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1}; - VkImageView brief = VK_NULL_HANDLE; - CHECK(vkCreateImageView(dev, &vi, nullptr, &brief)); - StorageViews brief_storage; - brief_storage.as_float = brief; - const std::uint32_t brief_index = set.add_image(ImageDimension::dim_2d, brief, VK_IMAGE_LAYOUT_GENERAL, brief_storage); - EXPECT(brief_index >= 1 && brief_index < set.storage_capacity(ImageDimension::dim_2d) && - brief_index != stored_index); - set.remove_image(ImageDimension::dim_2d, brief_index); - vkDestroyImageView(dev, brief, nullptr); - } - - const DescriptorTable& table = set.table(); - const auto slot_count = [&] { return std::uint32_t(table.capacity()); }; - const std::uint32_t slots = slot_count(), home = hash_descriptor_key(tsharp) & (slots - 1); - // Fill eight adjacent home slots across the end of the table. The ninth key - // shares the first home and can fit only by moving a resident already on the GPU. - { - std::array keys{}; - for (std::uint32_t i = 0; i < keys.size(); ++i) { - auto& key = keys[i]; - key[0] = i + 1; - const auto target = (slots - 4 + i % kDescriptorProbes) & (slots - 1); - while ((hash_descriptor_key(key) & (slots - 1)) != target) ++key[7]; - } - for (std::uint32_t i = 0; i < kDescriptorProbes; ++i) set.insert_key(keys[i], decoy_index); - EXPECT(!set.flush_replaces_table() && flush()); - EXPECT(set.insert_key(keys.back(), gradient_index)); - EXPECT(slot_count() == slots && set.flush_replaces_table()); - EXPECT(flush() && !set.flush_replaces_table()); - for (const auto& key : keys) { - EXPECT(table.lookup(key) == (key == keys.back() ? gradient_index : decoy_index)); - EXPECT(set.erase_key(key)); - } - EXPECT(table.size() == 0 && flush()); - } - - // 1. The T# behind three keys that share its first slot, the S#, and other keys that name the decoy. - std::uint32_t ahead = 0; - for (std::uint32_t k = 1; ahead < 3; ++k) { - if ((hash_descriptor_key(numbered(k)) & (slots - 1)) != home) continue; - set.insert_key(numbered(k), decoy_index); - ++ahead; - } - set.insert_key(tsharp, gradient_index); - set.insert_key(make_ssharp_key(ssharp.data()), sampler_index); - for (std::uint32_t k = 100000; k < 100006; ++k) set.insert_key(numbered(k), decoy_index); - const std::uint32_t depth = probe_depth(table.build_gpu_buffer(), tsharp); - EXPECT(slot_count() == slots && depth == 3 && !set.flush_replaces_table()); - EXPECT(flush()); - CHECK(draw()); - compare("1 gradient", nullptr); - - // 2. Without its key the T# is a miss: index 0, the fallback image of zeros. - const float zeros[4] = {0, 0, 0, 0}; - EXPECT(set.erase_key(tsharp) && !set.erase_key(tsharp)); - EXPECT(!set.flush_replaces_table()); // erasing empties its slot only: the three keys ahead stay where they are - EXPECT(flush() && !set.flush_replaces_table()); - CHECK(draw()); - compare("2 miss", zeros); - - // 3. The table grows: a new, larger buffer behind binding 2. - set.insert_key(tsharp, gradient_index); - EXPECT(!set.flush_replaces_table()); // one more entry, in place - for (std::uint32_t k = 200000; k < 200200; ++k) set.insert_key(numbered(k), decoy_index); - EXPECT(slot_count() > slots && table.lookup(tsharp) == gradient_index && set.flush_replaces_table()); - const VkDescriptorSet before_growth = set.set(); - const std::uint64_t made_before = set.generations_made(); - EXPECT(flush()); - // A new generation: another descriptor set (every descriptor written so far copied into it) and table, the - // old one retired but intact until released (D3D-314). - EXPECT(set.set() != before_growth && set.generations_made() == made_before + 1 && set.retired_count() >= 1); - CHECK(draw()); - compare("3 grown", nullptr); - set.release_retired(0); // a ticket past what completed (nothing): keeps the generation - EXPECT(set.retired_count() >= 1); - set.release_retired(); - EXPECT(set.retired_count() == 0); - - const float orange_colour[4] = {1.0f, 128.0f / 255.0f, 0.0f, 1.0f}; - // Rewriting the same mapping is a no-op. Changing it makes a new generation even with no table growth. - const std::uint32_t grown_slots = slot_count(); - EXPECT(set.insert_key(tsharp, gradient_index) && !set.flush_replaces_table()); - EXPECT(set.insert_key(tsharp, decoy_index) && slot_count() == grown_slots && set.flush_replaces_table()); - EXPECT(flush() && !set.flush_replaces_table()); - CHECK(draw()); - compare("4 rebound", orange_colour); - EXPECT(set.insert_key(tsharp, gradient_index) && set.flush_replaces_table()); - EXPECT(flush()); - CHECK(draw()); - compare("5 restored", nullptr); - - // A submit that never reached the queue must keep the table upload pending: the retry has to see the new - // mapping instead of the fallback or the old index (a recovered submit failure, the case a device reports - // through table_upload_result(false)). - EXPECT(set.insert_key(tsharp, decoy_index) && set.flush_replaces_table()); - vkResetCommandBuffer(cmd, 0); - CHECK(vkBeginCommandBuffer(cmd, &begin)); - EXPECT(set.flush(cmd, 1)); // recorded in a command buffer that is never submitted - CHECK(vkEndCommandBuffer(cmd)); - set.table_upload_result(false); - EXPECT(set.flush_replaces_table()); // the retry rewrites the whole table, in a new generation - EXPECT(flush()); - CHECK(draw()); - compare("6 rebound after a failed submit", orange_colour); - EXPECT(set.insert_key(tsharp, gradient_index) && set.flush_replaces_table()); - EXPECT(flush()); - - // Another view at the same index, then removal of the index. - set.update_image(ImageDimension::dim_2d, gradient_index, decoy_view, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL); - EXPECT(flush()); - CHECK(draw()); - compare("7 other view", orange_colour); - set.remove_image(ImageDimension::dim_2d, gradient_index); - EXPECT(flush()); - CHECK(draw()); - compare("8 removed", zeros); - EXPECT(set.add_image(ImageDimension::dim_2d, gradient_view, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL) == gradient_index); - - // 9. More than 4096 2D images and more than a full D3D12 sampler heap (2048): the gradient and the S# - // through the last indices of both arrays, where the device's limits gave the set room for them. - std::uint32_t far_image = 0, far_sampler = 0; - if (set.image_capacity(ImageDimension::dim_2d) > 5000 + 8 && set.sampler_capacity() > 2100 + 8) { - for (std::uint32_t i = 0; i < 5000; ++i) - EXPECT(set.add_image(ImageDimension::dim_2d, VK_NULL_HANDLE, VK_IMAGE_LAYOUT_GENERAL) != 0); - far_image = set.add_image(ImageDimension::dim_2d, gradient_view, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL); - for (std::uint32_t i = 0; i < 2100; ++i) far_sampler = set.add_sampler(nearest); - EXPECT(far_image > 5000 && far_sampler > 2100); - set.insert_key(tsharp, far_image); - set.insert_key(make_ssharp_key(ssharp.data()), far_sampler); - EXPECT(flush()); - CHECK(draw()); - compare("9 past 4096 images and 2048 samplers", nullptr); - - // Keep another high slot live while the sampled slot is removed and then reused. - const auto neighbour = set.add_image(ImageDimension::dim_2d, decoy_view, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL); - EXPECT(neighbour > 5000 && neighbour != far_image); - set.remove_image(ImageDimension::dim_2d, far_image); - EXPECT(flush()); - CHECK(draw()); - compare("10 freed high slot", zeros); - - const auto replacement = set.add_image(ImageDimension::dim_2d, stored_view, VK_IMAGE_LAYOUT_GENERAL); - EXPECT(replacement == far_image); - EXPECT(flush()); - CHECK(draw()); - const float blue[4] = {0, 0, 128.0f / 255.0f, 1}; // stored image uses the first gradient texel - compare("11 reused high slot", blue); - - EXPECT(set.insert_key(tsharp, neighbour)); - EXPECT(flush()); - CHECK(draw()); - compare("12 live neighbour", orange_colour); - } else { - std::printf("%s: no room past 5000 2D images and 2100 samplers on this device; step 9 skipped\n", name); - } - - std::printf("%s: descriptor table in %s memory\n", name, - set.table_in_device_local_memory() ? "device-local" : "host-visible"); - std::printf("%s: gradient at the %uth slot probed, miss, table grown %u -> %u slots, rebound, restored, " - "other view, removed, index %u of %u 2D images and %u of %u samplers\n", name, depth + 1, slots, - slot_count(), far_image, set.image_capacity(ImageDimension::dim_2d), far_sampler, - set.sampler_capacity()); - ++runs; - vkDeviceWaitIdle(dev); - vkDestroyPipeline(dev, pipeline, nullptr); - vkDestroyPipelineLayout(dev, pipeline_layout, nullptr); - } - - // Let validation observe resource and device destruction before reporting its final error count. - vkDestroyCommandPool(dev, pool, nullptr); - vkDestroyFramebuffer(dev, framebuffer, nullptr); - vkDestroyRenderPass(dev, pass, nullptr); - vkDestroyShaderModule(dev, fs, nullptr); - vkDestroyShaderModule(dev, vs, nullptr); - vkDestroySampler(dev, nearest, nullptr); - for (const auto view : {target_view, stored_view, decoy_view, gradient_view}) - vkDestroyImageView(dev, view, nullptr); - for (const auto image : {target, stored, decoy, gradient}) vkDestroyImage(dev, image, nullptr); - for (const auto buffer : {readback, upload, heap}) vkDestroyBuffer(dev, buffer, nullptr); - for (const auto memory : allocations) vkFreeMemory(dev, memory, nullptr); - tail.destroy(vkGetDeviceProcAddr, dev); // the --pc-tail-ubo block, when the shaders use one - vkDestroyDevice(dev, nullptr); - if (messenger) { - LI(vkDestroyDebugUtilsMessengerEXT); - vkDestroyDebugUtilsMessengerEXT(inst, messenger, nullptr); - } - LI(vkDestroyInstance); - vkDestroyInstance(inst, nullptr); - - if (!runs) { - std::printf("unsupported: the bindless set does not fit this device's descriptor limits\n"); - return unsupported; - } - std::printf("bindless: %u draws read back, %u bad pixels, largest error %g\n", readbacks, mismatches, double(worst)); - if (g_validation_errors) { - std::fprintf(stderr, "%u validation errors\n", g_validation_errors); - return 1; - } - return mismatches ? 1 : 0; -} diff --git a/runtime/test/vk_buffer_registration_oom_test.cpp b/runtime/test/vk_buffer_registration_oom_test.cpp deleted file mode 100644 index 69302b2a5..000000000 --- a/runtime/test/vk_buffer_registration_oom_test.cpp +++ /dev/null @@ -1,222 +0,0 @@ -// Buffer registration keeps bindings, VA lookups, and sparse ownership in step when host allocation fails. -// Public runtime classes with fake Vulkan procedures: no loader, GPU, or game data. -#include "../src/vulkan_backend.h" - -#include -#include -#include -#include -#include -#include -#include -#include - -namespace { -long fail_after = -1; -int failures = 0; -int destroyed_sparse_buffers = 0; -VkBuffer updated_buffer = VK_NULL_HANDLE; - -void expect(bool ok, const char* what) { - if (!ok) { std::fprintf(stderr, "FAIL: %s\n", what); ++failures; } -} - -template Handle handle(std::uintptr_t value) { - if constexpr (std::is_pointer_v) return reinterpret_cast(value); - else return static_cast(value); -} - -leonida::ResourceBinding buffer(std::uintptr_t value, std::uint64_t va, std::uint64_t size = 64) { - leonida::ResourceBinding b{}; - b.buffer = handle(value); - b.va = va; - b.size = size; - return b; -} - -VkResult VKAPI_CALL create_pool(VkDevice, const VkCommandPoolCreateInfo*, const VkAllocationCallbacks*, VkCommandPool* out) { - *out = handle(1); return VK_SUCCESS; -} -void VKAPI_CALL destroy_pool(VkDevice, VkCommandPool, const VkAllocationCallbacks*) {} -VkResult VKAPI_CALL create_semaphore(VkDevice, const VkSemaphoreCreateInfo*, const VkAllocationCallbacks*, VkSemaphore* out) { - *out = handle(1); return VK_SUCCESS; -} -void VKAPI_CALL destroy_semaphore(VkDevice, VkSemaphore, const VkAllocationCallbacks*) {} -void VKAPI_CALL destroy_buffer(VkDevice, VkBuffer, const VkAllocationCallbacks*) { ++destroyed_sparse_buffers; } -VkResult VKAPI_CALL counter(VkDevice, VkSemaphore, std::uint64_t* out) { *out = UINT64_MAX; return VK_SUCCESS; } -VkResult VKAPI_CALL idle(VkQueue) { return VK_SUCCESS; } -VkResult VKAPI_CALL allocate_commands(VkDevice, const VkCommandBufferAllocateInfo*, VkCommandBuffer* out) { - *out = handle(1); return VK_SUCCESS; -} -VkResult VKAPI_CALL reset_command(VkCommandBuffer, VkCommandBufferResetFlags) { return VK_SUCCESS; } -VkResult VKAPI_CALL begin_command(VkCommandBuffer, const VkCommandBufferBeginInfo*) { return VK_SUCCESS; } -VkResult VKAPI_CALL end_command(VkCommandBuffer) { return VK_SUCCESS; } -VkResult VKAPI_CALL submit(VkQueue, std::uint32_t, const VkSubmitInfo*, VkFence) { return VK_SUCCESS; } -void VKAPI_CALL record_barrier(VkCommandBuffer, VkPipelineStageFlags, VkPipelineStageFlags, VkDependencyFlags, - std::uint32_t, const VkMemoryBarrier*, std::uint32_t, const VkBufferMemoryBarrier*, - std::uint32_t, const VkImageMemoryBarrier*) {} -void VKAPI_CALL record_update(VkCommandBuffer, VkBuffer buffer, VkDeviceSize, VkDeviceSize, const void*) { - updated_buffer = buffer; -} -PFN_vkVoidFunction VKAPI_CALL queue_proc(VkDevice, const char* name) { -#define PROC(vk_name, implementation) \ - if (std::strcmp(name, #vk_name) == 0) return reinterpret_cast(implementation) - PROC(vkCreateCommandPool, create_pool); PROC(vkDestroyCommandPool, destroy_pool); - PROC(vkCreateSemaphore, create_semaphore); PROC(vkDestroySemaphore, destroy_semaphore); - PROC(vkGetSemaphoreCounterValue, counter); PROC(vkQueueWaitIdle, idle); - PROC(vkAllocateCommandBuffers, allocate_commands); PROC(vkResetCommandBuffer, reset_command); - PROC(vkBeginCommandBuffer, begin_command); PROC(vkEndCommandBuffer, end_command); - PROC(vkQueueSubmit, submit); PROC(vkCmdPipelineBarrier, record_barrier); - PROC(vkCmdUpdateBuffer, record_update); -#undef PROC - return nullptr; -} - -struct Observation { leonida::ReplayResult result; VkBuffer buffer; }; -Observation observe(leonida::VulkanContext& ctx, std::uint64_t va) { - leonida::CommandList list; - expect(list.write_immediate({va, 0x12345678, leonida::write_immediate_mode::normal}) && list.close(), - "VA observation command list invalid"); - updated_buffer = VK_NULL_HANDLE; - leonida::VulkanQueue queue(ctx, handle(1), 0); - expect(queue.ok(), "fake observation queue did not initialize"); - const leonida::CommandList* commands[] = {&list}; - const auto result = queue.execute(commands); - return {result, updated_buffer}; -} -bool resolves(leonida::VulkanContext& ctx, std::uint64_t va, VkBuffer expected) { - const auto result = observe(ctx, va); - return result.result == leonida::ReplayResult::success && result.buffer == expected; -} -bool misses(leonida::VulkanContext& ctx, std::uint64_t va) { - return observe(ctx, va).buffer == VK_NULL_HANDLE; -} - -void ordinary_new_id() { - int caught = 0, succeeded = 0; - for (long n = 0; n < 8; ++n) { - leonida::VulkanContext ctx(queue_proc, handle(1), false); - const auto b = buffer(100 + n, 0x4000); - fail_after = n; - bool threw = false; - try { ctx.add_resource(21, b); } - catch (const std::bad_alloc&) { threw = true; } - fail_after = -1; - if (threw) { - ++caught; - expect(!ctx.has_resource(21), "failed new buffer registration retained its binding"); - ctx.add_resource(21, b); - } else ++succeeded; - expect(resolves(ctx, b.va, b.buffer), "new buffer registration or retry lost its VA lookup"); - } - expect(caught >= 2 && succeeded >= 1, "new-ID sweep missed allocation failures or success"); -} - -void ordinary_replacement() { - int caught = 0, succeeded = 0; - for (long n = 0; n < 7; ++n) { - leonida::VulkanContext ctx(queue_proc, handle(1), false); - const auto old = buffer(201, 0x5000); - const auto next = buffer(202, 0x6000); - ctx.add_resource(22, old); - expect(resolves(ctx, old.va, old.buffer), "old buffer VA control failed"); - fail_after = n; - bool threw = false; - try { ctx.add_resource(22, next); } - catch (const std::bad_alloc&) { threw = true; } - fail_after = -1; - if (threw) { - ++caught; - expect(resolves(ctx, old.va, old.buffer), "failed replacement lost the old buffer VA binding"); - expect(misses(ctx, next.va), "failed replacement exposed the new buffer VA"); - ctx.add_resource(22, next); - } else ++succeeded; - expect(resolves(ctx, next.va, next.buffer) && misses(ctx, old.va), - "replacement or retry did not move the VA lookup"); - } - expect(caught >= 1 && succeeded >= 1, "moved-VA sweep missed failure or success"); -} - -void same_va_replacement() { - int caught = 0, succeeded = 0; - for (long n = 0; n < 5; ++n) { - leonida::VulkanContext ctx(queue_proc, handle(1), false); - const auto old = buffer(301, 0x7000, 64); - const auto next = buffer(302, 0x7000, 16); - ctx.add_resource(23, old); - fail_after = n; - bool threw = false; - try { ctx.add_resource(23, next); } - catch (const std::bad_alloc&) { threw = true; } - fail_after = -1; - if (threw) { - ++caught; - expect(resolves(ctx, old.va + 32, old.buffer), "failed same-VA resize lost old range"); - ctx.add_resource(23, next); - } else ++succeeded; - expect(resolves(ctx, next.va, next.buffer) && misses(ctx, next.va + 32), - "same-VA resize or retry did not replace the old range"); - } - expect(caught >= 1 && succeeded >= 1, "same-VA sweep missed failure or success"); -} - -void sparse_buffer_ownership() { - int caught = 0, succeeded = 0; - for (long n = 0; n < 10; ++n) { - const int before = destroyed_sparse_buffers; - bool threw = false; - { - leonida::VulkanContext ctx(queue_proc, handle(1), false); - ctx.vk.vkDestroyBuffer = destroy_buffer; - auto sparse = std::make_shared(ctx.device(), ctx.vk); - sparse->buffer = handle(400 + n); - const auto b = buffer(400 + n, 0x8000); - fail_after = n; - try { ctx.add_sparse_resource(24, b, std::move(sparse)); } - catch (const std::bad_alloc&) { threw = true; } - fail_after = -1; - if (threw) { - ++caught; - expect(!ctx.has_resource(24), "failed sparse buffer registration retained a dangling binding"); - expect(destroyed_sparse_buffers == before + 1, "failed sparse buffer was not released once"); - auto retry = std::make_shared(ctx.device(), ctx.vk); - retry->buffer = handle(500 + n); - const auto retry_binding = buffer(500 + n, 0x8000); - ctx.add_sparse_resource(24, retry_binding, std::move(retry)); - expect(resolves(ctx, retry_binding.va, retry_binding.buffer), "sparse retry lost VA lookup"); - } else { - ++succeeded; - expect(resolves(ctx, b.va, b.buffer), "successful sparse buffer lost VA lookup"); - } - } - expect(destroyed_sparse_buffers == before + (threw ? 2 : 1), - "sparse failure, retry, or teardown destroyed a buffer incorrectly"); - } - expect(caught >= 3 && succeeded >= 1, "sparse sweep missed owner, binding, or index failure and success"); -} -} // namespace - -void* operator new(std::size_t size) { - // Arm after context construction. Ignore MSVC Debug's small noexcept iterator-proxy allocations. - if (size > 2 * sizeof(void*)) { - if (fail_after == 0) { fail_after = -1; throw std::bad_alloc{}; } - if (fail_after > 0) --fail_after; - } - if (void* p = std::malloc(size ? size : 1)) return p; - throw std::bad_alloc{}; -} -void* operator new[](std::size_t size) { return operator new(size); } -void operator delete(void* p) noexcept { std::free(p); } -void operator delete[](void* p) noexcept { std::free(p); } -void operator delete(void* p, std::size_t) noexcept { std::free(p); } -void operator delete[](void* p, std::size_t) noexcept { std::free(p); } - -int main() { - ordinary_new_id(); - ordinary_replacement(); - same_va_replacement(); - sparse_buffer_ownership(); - if (failures) return 1; - std::puts("vk_buffer_registration_oom_test: ok"); - return 0; -} diff --git a/runtime/test/vk_command_replay_test.cpp b/runtime/test/vk_command_replay_test.cpp deleted file mode 100644 index 9769e70be..000000000 --- a/runtime/test/vk_command_replay_test.cpp +++ /dev/null @@ -1,1287 +0,0 @@ -// Replays recorded command lists on offscreen images and reads them back. No shaders or game data. -// Part A uses only Vulkan 1.0 functions and no layout tracker. Part B uses the tracker with separate depth/stencil -// layouts: rectangle clears, a depth clear while the stencil plane is in another state, a texture used after -// implicit promotion from common, and enhanced barriers. Part C copies a volume (footprint, box and whole) and -// resolves a multisampled target. Part D records every D3D12 sync/access pair as enhanced barriers, which the -// validation layer must accept. Part E (where VK_EXT_conditional_rendering is available) checks SetPredication. -// Part F (D3D-26) runs immediate buffer writes, atomic copies and discards. Part G copies one subresource twice in one -// list, which D3D12 orders on the queue and needs an explicit dependency for on Vulkan. Part H copies depth to colour -// and back (D32_FLOAT <-> R32_FLOAT), which the replay stages through a scratch buffer. Part I resolves a depth -// rectangle (MIN) and checks that the texels around it keep their values. Part J copies between disjoint regions -// of one texture subresource. -// Set LEONIDA_VK_VALIDATION=1 to run under VK_LAYER_KHRONOS_validation; any validation error fails the test. -#include "vk_test_device.h" -#include "../src/vulkan_replay.h" - -#include -#include -#include -#include -#include - -#define EXPECT(condition) do { \ - if (!(condition)) { std::fprintf(stderr, "line %d: %s\n", __LINE__, #condition); return 1; } \ -} while (0) - -namespace { - -using namespace leonida; -namespace s = d3d12_state; - -using Rgba = std::array; -constexpr Rgba red{255, 0, 0, 255}, green{0, 255, 0, 255}, blue{0, 0, 255, 255}; - -unsigned g_mismatches = 0; - -void expect_rgba(const char* what, const std::uint8_t* data, std::uint32_t index, const Rgba& expected) { - if (std::equal(expected.begin(), expected.end(), data + index * 4)) return; - if (g_mismatches++ < 8) - std::fprintf(stderr, "%s texel %u: got %u,%u,%u,%u\n", what, index, unsigned(data[index * 4]), - unsigned(data[index * 4 + 1]), unsigned(data[index * 4 + 2]), unsigned(data[index * 4 + 3])); -} - -void expect_depth(const char* what, const std::uint8_t* data, std::uint32_t index, float expected) { - float depth; - std::memcpy(&depth, data + index * 4, 4); - if (depth != expected && g_mismatches++ < 8) - std::fprintf(stderr, "%s texel %u: got %f, want %f\n", what, index, depth, expected); -} - -void expect_byte(const char* what, const std::uint8_t* data, std::uint32_t index, std::uint8_t expected) { - if (data[index] != expected && g_mismatches++ < 8) - std::fprintf(stderr, "%s texel %u: got 0x%02x, want 0x%02x\n", what, index, unsigned(data[index]), - unsigned(expected)); -} - -struct Views { - vktest::Device& device; - std::map, VkImageView> views; - ~Views() { - const auto destroy = device.fn("vkDestroyImageView"); - for (const auto& [key, view] : views) destroy(device.device, view, nullptr); - } - VkImageView operator()(const ResourceBinding& r, const VkImageSubresourceRange& range) { - auto& view = views[{r.image, range.aspectMask, range.baseMipLevel, range.baseArrayLayer, range.layerCount}]; - if (view) return view; - VkImageViewCreateInfo info{VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO}; - info.image = r.image; - info.viewType = VK_IMAGE_VIEW_TYPE_2D_ARRAY; - info.format = r.format; - info.subresourceRange = range; - device.fn("vkCreateImageView")(device.device, &info, nullptr, &view); - return view; - } -}; - -int part_a(vktest::Device& d) { - const bool has_stencil = d.depth_format_usable(VK_FORMAT_D32_SFLOAT_S8_UINT); - const VkFormat depth_format = has_stencil ? VK_FORMAT_D32_SFLOAT_S8_UINT : VK_FORMAT_D32_SFLOAT; - const VkImageAspectFlags depth_aspects = VK_IMAGE_ASPECT_DEPTH_BIT | (has_stencil ? VK_IMAGE_ASPECT_STENCIL_BIT : 0); - constexpr std::uint32_t width = 4, height = 4, layers = 2, texels = width * height; - const VkImage color = d.image(VK_FORMAT_R8G8B8A8_UNORM, width, height, layers, VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT); - const VkImage depth = d.image(depth_format, width, height, 1, VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT); - constexpr VkDeviceSize depth_offset = texels * layers * 4, stencil_offset = depth_offset + texels * 4; - void* mapped = nullptr; - const VkBuffer buffer = d.buffer(stencil_offset + texels, VK_BUFFER_USAGE_TRANSFER_DST_BIT, &mapped); - EXPECT(color && depth && buffer); - - ResourceBinding color_binding{}; - color_binding.image = color; - color_binding.array_layers = layers; - ResourceBinding depth_binding{}; - depth_binding.image = depth; - depth_binding.aspects = depth_aspects; - constexpr ResourceId color_id = 1, depth_id = 2, missing_id = 3; - const auto resolve = [&](ResourceId id) -> const ResourceBinding* { - if (id == color_id) return &color_binding; - if (id == depth_id) return &depth_binding; - return nullptr; - }; - ReplayFunctions vk{}; - vk.pipeline_barrier = d.fn("vkCmdPipelineBarrier"); - vk.clear_color_image = d.fn("vkCmdClearColorImage"); - vk.clear_depth_stencil_image = d.fn("vkCmdClearDepthStencilImage"); - - CommandList list; - TargetView descriptor{color_id, 0, 0, 1}; - EXPECT(list.clear_render_target(descriptor, {0, 0, 1, 1})); - descriptor = {color_id, 0, 1, 1}; // the CPU descriptor slot is reused; the first clear keeps its own view - EXPECT(list.clear_render_target(descriptor, {1, 0, 0, 1})); - EXPECT(list.clear_render_target(descriptor, {0, 1, 0, 1})); - const TargetView depth_view{depth_id, 0, 0, 1}; - EXPECT(list.clear_depth_stencil(depth_view, clear_depth | (has_stencil ? clear_stencil : 0), 0.25f, 0x5a)); - EXPECT(list.clear_depth_stencil(depth_view, clear_depth, 0.75f, 0)); // stencil keeps 0x5a - EXPECT(list.uav_barrier({0})); - EXPECT(list.aliasing_barrier({0, 0})); - EXPECT(list.transition({color_id, all_subresources, s::render_target, s::copy_source}, barrier_begin_only)); - EXPECT(list.transition({color_id, all_subresources, s::render_target, s::copy_source}, barrier_end_only)); - EXPECT(list.transition({depth_id, all_subresources, s::depth_write, s::copy_source})); - EXPECT(list.close()); - - bool ok = d.run([&](VkCommandBuffer cb) { - d.initial_layout(cb, color, VK_IMAGE_ASPECT_COLOR_BIT, layers, VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL); - d.initial_layout(cb, depth, depth_aspects, 1, VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL); - - // Rejected lists write nothing to the command buffer. - CommandList bad; - if (!bad.clear_render_target({color_id, 0, 0, 1}, {1, 1, 1, 1})) return false; - if (replay(bad, cb, resolve, vk) != ReplayResult::list_open) return false; - const auto rejected = [&](auto&& record, ReplayResult expected) { - bad.close(); - bad.reset(); - record(); - bad.close(); - const ReplayResult got = replay(bad, cb, resolve, vk); - if (got != expected) std::fprintf(stderr, "rejected list: got %d, want %d\n", int(got), int(expected)); - return got == expected; - }; - const Rect rect{0, 0, 1, 1}; - if (!rejected([&] { bad.transition({missing_id, 0, s::common, s::copy_dest}); }, ReplayResult::unresolved_resource) || - !rejected([&] { bad.transition({color_id, layers, s::render_target, s::copy_source}); }, - ReplayResult::invalid_subresource) || - !rejected([&] { bad.clear_render_target({color_id, 0, 1, 2}, {1, 1, 1, 1}); }, - ReplayResult::invalid_subresource) || - !rejected([&] { bad.clear_render_target({depth_id, 0, 0, 1}, {1, 1, 1, 1}); }, ReplayResult::invalid_clear) || - !rejected([&] { bad.clear_depth_stencil({color_id, 0, 0, 1}, clear_depth, 1.0f, 0); }, - ReplayResult::invalid_clear) || - // Rectangle clears and enhanced barriers need the Vulkan 1.3 functions this part does not pass. - !rejected([&] { bad.clear_render_target({color_id, 0, 0, 1}, {1, 1, 1, 1}, {&rect, 1}); }, - ReplayResult::unsupported) || - !rejected([&] { bad.barrier(GlobalBarrier{d3d12_sync::all, d3d12_sync::all, 0, 0}); }, - ReplayResult::unsupported)) - return false; - LayoutTracker separate(true); - if (replay(list, cb, resolve, vk, &separate) != ReplayResult::unsupported) return false; // flag mismatch - - if (replay(list, cb, resolve, vk) != ReplayResult::success) return false; - d.read_back(cb, color, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, VK_IMAGE_ASPECT_COLOR_BIT, width, height, layers, - buffer, 0); - d.read_back(cb, depth, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, VK_IMAGE_ASPECT_DEPTH_BIT, width, height, 1, - buffer, depth_offset); - if (has_stencil) - d.read_back(cb, depth, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, VK_IMAGE_ASPECT_STENCIL_BIT, width, height, 1, - buffer, stencil_offset); - return true; - }); - EXPECT(ok); - const auto* data = static_cast(mapped); - for (std::uint32_t i = 0; i < texels * layers; ++i) expect_rgba("A colour", data, i, i < texels ? blue : green); - for (std::uint32_t i = 0; i < texels; ++i) { - expect_depth("A depth", data + depth_offset, i, 0.75f); - if (has_stencil) expect_byte("A stencil", data + stencil_offset, i, 0x5a); - } - std::printf("A: %u colour texels across two layers, %u depth%s texels\n", texels * layers, texels, - has_stencil ? "/stencil" : ""); - return 0; -} - -int part_b(vktest::Device& d) { - if (!d.depth_format_usable(VK_FORMAT_D32_SFLOAT_S8_UINT)) { - std::printf("B: skipped, no D32_SFLOAT_S8_UINT\n"); - return 0; - } - constexpr std::uint32_t size = 8, texels = size * size; - const VkImage rt = d.image(VK_FORMAT_R8G8B8A8_UNORM, size, size, 1, VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT); - const VkImage ds = d.image(VK_FORMAT_D32_SFLOAT_S8_UINT, size, size, 1, VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT); - const VkImage promoted = d.image(VK_FORMAT_R8G8B8A8_UNORM, size, size, 1, VK_IMAGE_USAGE_SAMPLED_BIT); - const VkImage discarded = d.image(VK_FORMAT_R8G8B8A8_UNORM, size, size, 1, VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT); - constexpr VkDeviceSize depth_offset = texels * 4, stencil_offset = depth_offset + texels * 4, - discard_offset = stencil_offset + texels; - void* mapped = nullptr; - const VkBuffer buffer = d.buffer(discard_offset + texels * 4, VK_BUFFER_USAGE_TRANSFER_DST_BIT, &mapped); - EXPECT(rt && ds && promoted && discarded && buffer); - - const auto binding = [&](VkImage image, VkFormat format, VkImageAspectFlags aspects) { - ResourceBinding b{}; - b.image = image; - b.format = format; - b.aspects = aspects; - b.width = b.height = size; - return b; - }; - constexpr ResourceId rt_id = 10, ds_id = 11, promoted_id = 12, buffer_id = 13, discarded_id = 14; - const std::map bindings{ - {rt_id, binding(rt, VK_FORMAT_R8G8B8A8_UNORM, VK_IMAGE_ASPECT_COLOR_BIT)}, - {ds_id, binding(ds, VK_FORMAT_D32_SFLOAT_S8_UINT, depth_stencil_aspects)}, - {promoted_id, binding(promoted, VK_FORMAT_R8G8B8A8_UNORM, VK_IMAGE_ASPECT_COLOR_BIT)}, - {buffer_id, ResourceBinding{}}, // a buffer: no image - {discarded_id, binding(discarded, VK_FORMAT_R8G8B8A8_UNORM, VK_IMAGE_ASPECT_COLOR_BIT)}, - }; - const auto resolve = [&](ResourceId id) -> const ResourceBinding* { - const auto it = bindings.find(id); - return it == bindings.end() ? nullptr : &it->second; - }; - - Views views{d, {}}; - ReplayFunctions vk{}; - vk.pipeline_barrier = d.fn("vkCmdPipelineBarrier"); - vk.clear_color_image = d.fn("vkCmdClearColorImage"); - vk.clear_depth_stencil_image = d.fn("vkCmdClearDepthStencilImage"); - vk.pipeline_barrier2 = d.fn("vkCmdPipelineBarrier2"); - vk.begin_rendering = d.fn("vkCmdBeginRendering"); - vk.end_rendering = d.fn("vkCmdEndRendering"); - vk.clear_attachments = d.fn("vkCmdClearAttachments"); - vk.image_view = [&](const ResourceBinding& r, const VkImageSubresourceRange& range) { return views(r, range); }; - vk.separate_depth_stencil_layouts = true; - - LayoutTracker tracker(true); - tracker.track(rt_id, bindings.at(rt_id), VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL); // render_target - tracker.track(ds_id, bindings.at(ds_id), VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL); // depth_write - tracker.track(promoted_id, bindings.at(promoted_id), VK_IMAGE_LAYOUT_GENERAL); // common - tracker.track(discarded_id, bindings.at(discarded_id), VK_IMAGE_LAYOUT_GENERAL); // common - - CommandList list; - // Rectangle clears: the inner square, a rectangle clipped at the edge, and an empty one that clears nothing. - const Rect inner{2, 2, 6, 6}, clipped{6, 6, 20, 20}, empty{3, 3, 3, 9}; - const Rect rects[] = {inner, empty}; - EXPECT(list.clear_render_target({rt_id, 0, 0, 1}, {1, 0, 0, 1})); - EXPECT(list.clear_render_target({rt_id, 0, 0, 1}, {0, 0, 1, 1}, rects)); - EXPECT(list.clear_render_target({rt_id, 0, 0, 1}, {0, 1, 0, 1}, {&clipped, 1})); - EXPECT(list.clear_render_target({rt_id, 0, 0, 1}, {1, 1, 1, 1}, {&empty, 1})); - - // Depth and stencil: clear both, move only the stencil plane (subresource 1) to depth_read, then clear depth - // twice (full view through a transfer, left half through rendering) while the stencil plane stays read-only. - const Rect left_half{0, 0, 4, 8}; - EXPECT(list.clear_depth_stencil({ds_id, 0, 0, 1}, clear_depth | clear_stencil, 1.0f, 0x11)); - EXPECT(list.transition({ds_id, 1, s::depth_write, s::depth_read | s::pixel_shader_resource})); - EXPECT(list.clear_depth_stencil({ds_id, 0, 0, 1}, clear_depth, 0.25f, 0)); - EXPECT(list.clear_depth_stencil({ds_id, 0, 0, 1}, clear_depth, 0.5f, 0, {&left_half, 1})); - EXPECT(list.transition({ds_id, 0, s::depth_write, s::copy_source})); - EXPECT(list.transition({ds_id, 1, s::depth_read | s::pixel_shader_resource, s::copy_source})); - - // Implicit promotion: the texture was created in common and a copy promoted it to copy_dest, so the application - // names copy_dest as `before`. The image is still in GENERAL; the tracker knows it. - EXPECT(list.transition({promoted_id, all_subresources, s::copy_dest, s::copy_source})); - - // Enhanced barriers. - namespace y = d3d12_sync; - namespace a = d3d12_access; - namespace l = d3d12_layout; - const BarrierSubresourceRange all{all_subresources, 0, 0, 0, 0, 0}; - const BarrierSubresourceRange first{0, 1, 0, 1, 0, 1}; - EXPECT(list.barrier(TextureBarrier{y::render_target, y::split, a::render_target, a::copy_source, l::render_target, - l::copy_source, rt_id, all, 0})); // split begin: dropped - EXPECT(list.barrier(TextureBarrier{y::split, y::copy, a::render_target, a::copy_source, l::render_target, - l::copy_source, rt_id, all, 0})); - EXPECT(list.barrier(TextureBarrier{y::none, y::render_target, a::no_access, a::render_target, l::undefined, - l::render_target, discarded_id, all, texture_barrier_discard})); - EXPECT(list.clear_render_target({discarded_id, 0, 0, 1}, {0, 1, 0, 1})); - EXPECT(list.barrier(TextureBarrier{y::render_target, y::copy, a::render_target, a::copy_source, l::render_target, - l::copy_source, discarded_id, first, 0})); - EXPECT(list.barrier(BufferBarrier{y::copy, y::pixel_shading, a::copy_dest, a::shader_resource, buffer_id})); - EXPECT(list.barrier(GlobalBarrier{y::all, y::all, a::common, a::common})); - EXPECT(list.close()); - - bool ok = d.run([&](VkCommandBuffer cb) { - d.initial_layout(cb, rt, VK_IMAGE_ASPECT_COLOR_BIT, 1, VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL); - d.initial_layout(cb, ds, depth_stencil_aspects, 1, VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL); - d.initial_layout(cb, promoted, VK_IMAGE_ASPECT_COLOR_BIT, 1, VK_IMAGE_LAYOUT_GENERAL); - d.initial_layout(cb, discarded, VK_IMAGE_ASPECT_COLOR_BIT, 1, VK_IMAGE_LAYOUT_GENERAL); - if (replay(list, cb, resolve, vk, &tracker) != ReplayResult::success) return false; - d.read_back(cb, rt, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, VK_IMAGE_ASPECT_COLOR_BIT, size, size, 1, buffer, 0); - d.read_back(cb, ds, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, VK_IMAGE_ASPECT_DEPTH_BIT, size, size, 1, buffer, - depth_offset); - d.read_back(cb, ds, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, VK_IMAGE_ASPECT_STENCIL_BIT, size, size, 1, buffer, - stencil_offset); - d.read_back(cb, discarded, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, VK_IMAGE_ASPECT_COLOR_BIT, size, size, 1, - buffer, discard_offset); - return true; - }); - EXPECT(ok); - - EXPECT(tracker.layout(rt_id, 0) == VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL); - EXPECT(tracker.layout(ds_id, 0) == VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL); - EXPECT(tracker.layout(ds_id, 1) == VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL); - EXPECT(tracker.layout(promoted_id, 0) == VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL); - EXPECT(tracker.layout(discarded_id, 0) == VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL); - - const auto* data = static_cast(mapped); - for (std::uint32_t row = 0; row < size; ++row) { - for (std::uint32_t col = 0; col < size; ++col) { - const std::uint32_t i = row * size + col; - const bool in_inner = col >= 2 && col < 6 && row >= 2 && row < 6; - const bool in_clipped = col >= 6 && row >= 6; - expect_rgba("B colour", data, i, in_clipped ? green : in_inner ? blue : red); - expect_depth("B depth", data + depth_offset, i, col < 4 ? 0.5f : 0.25f); - expect_byte("B stencil", data + stencil_offset, i, 0x11); - expect_rgba("B discard", data + discard_offset, i, green); - } - } - std::printf("B: rectangle clears, per-plane depth clears, promotion and enhanced barriers on %u texels\n", texels); - return 0; -} - -// Part C: volumes and resolves. A 4x4x4 volume is uploaded from a footprint whose slices lie `height` rows apart, -// copied in part (a 2x2x2 block) and whole, and read back; a 4x multisampled target is cleared and resolved. -// Nothing is transitioned before its first use: the images start in UNDEFINED and are zero-filled then. -int part_c(vktest::Device& d) { - constexpr std::uint32_t size = 4, wide = 8, pitch = 256, slice = size * pitch; - constexpr VkDeviceSize bytes = 16384, up_at = 512, back_at = 0, part_at = 4096, resolved_at = 8192; - constexpr VkFormat format = VK_FORMAT_R8G8B8A8_UNORM; - void *up_mapped = nullptr, *down_mapped = nullptr; - const VkBuffer up = d.buffer(bytes, VK_BUFFER_USAGE_TRANSFER_SRC_BIT, &up_mapped); - const VkBuffer down = d.buffer(bytes, VK_BUFFER_USAGE_TRANSFER_DST_BIT, &down_mapped); - const VkImage volume = d.image(format, size, size, 1, VK_IMAGE_USAGE_SAMPLED_BIT, size); - const VkImage part = d.image(format, size, size, 1, VK_IMAGE_USAGE_SAMPLED_BIT, size); - const VkImage whole = d.image(format, size, size, 1, VK_IMAGE_USAGE_SAMPLED_BIT, size); - const VkImage msaa = d.image(format, wide, wide, 1, VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT, 1, 4); - const VkImage resolved = d.image(format, wide, wide, 1, VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT); - EXPECT(up && down && volume && part && whole && msaa && resolved); - auto* u = static_cast(up_mapped); - const auto* r = static_cast(down_mapped); - const auto texel = [&](std::uint32_t x, std::uint32_t y, std::uint32_t z) { - return u + up_at + z * slice + y * pitch + x * 4; - }; - for (std::uint32_t z = 0; z < size; ++z) - for (std::uint32_t y = 0; y < size; ++y) - for (std::uint32_t x = 0; x < size; ++x) { - const Rgba value{std::uint8_t(x * 16 + y), std::uint8_t(z * 40 + 1), std::uint8_t(x ^ y ^ (z << 4)), 255}; - std::copy(value.begin(), value.end(), texel(x, y, z)); - } - - const auto image_binding = [&](VkImage image, std::uint32_t extent, std::uint32_t depth, std::uint32_t samples) { - ResourceBinding b{}; - b.image = image; - b.format = format; - b.width = b.height = extent; - b.depth = depth; - b.volume = depth > 1; - b.samples = samples; - return b; - }; - const auto buffer_binding = [&](VkBuffer buffer) { - ResourceBinding b{}; - b.buffer = buffer; - b.size = bytes; - return b; - }; - constexpr ResourceId up_id = 20, down_id = 21, volume_id = 22, part_id = 23, whole_id = 24, msaa_id = 25, - resolved_id = 26; - const std::map bindings{ - {up_id, buffer_binding(up)}, - {down_id, buffer_binding(down)}, - {volume_id, image_binding(volume, size, size, 1)}, - {part_id, image_binding(part, size, size, 1)}, - {whole_id, image_binding(whole, size, size, 1)}, - {msaa_id, image_binding(msaa, wide, 1, 4)}, - {resolved_id, image_binding(resolved, wide, 1, 1)}, - }; - const auto resolve = [&](ResourceId id) -> const ResourceBinding* { - const auto it = bindings.find(id); - return it == bindings.end() ? nullptr : &it->second; - }; - LayoutTracker tracker(true); - for (const ResourceId id : {volume_id, part_id, whole_id, msaa_id, resolved_id}) - tracker.track(id, bindings.at(id), VK_IMAGE_LAYOUT_UNDEFINED); - - ReplayFunctions vk{}; - vk.pipeline_barrier = d.fn("vkCmdPipelineBarrier"); - vk.clear_color_image = d.fn("vkCmdClearColorImage"); - vk.clear_depth_stencil_image = d.fn("vkCmdClearDepthStencilImage"); - vk.copy_buffer = d.fn("vkCmdCopyBuffer"); - vk.copy_buffer_to_image = d.fn("vkCmdCopyBufferToImage"); - vk.copy_image_to_buffer = d.fn("vkCmdCopyImageToBuffer"); - vk.copy_image = d.fn("vkCmdCopyImage"); - vk.separate_depth_stencil_layouts = true; - const ReplayFunctions without_resolve = vk; - vk.resolve_image = d.fn("vkCmdResolveImage"); - - const auto sub = [](ResourceId id) { return CopyLocation{id, false, 0, 0, 0, 0, 0, 0}; }; - const auto slices = [&](ResourceId id, VkDeviceSize offset, std::uint32_t depth) { - return CopyLocation{id, true, 0, offset, size, size, depth, pitch}; - }; - CommandList list; - EXPECT(list.copy_texture({sub(volume_id), 0, 0, 0, slices(up_id, up_at, size), false, {}})); // four slices up - EXPECT(list.transition({volume_id, 0, s::copy_dest, s::copy_source})); - EXPECT(list.copy_texture({sub(part_id), 2, 0, 1, sub(volume_id), true, {1, 1, 1, 3, 3, 3}})); // 2x2x2 to (2, 0, 1) - EXPECT(list.copy_resource({whole_id, volume_id})); - EXPECT(list.transition({part_id, 0, s::copy_dest, s::copy_source})); - EXPECT(list.transition({whole_id, 0, s::copy_dest, s::copy_source})); - // Slices 1 and 2 of the whole copy, to slice 1 of a footprint; then all of the partly written volume. - EXPECT(list.copy_texture({slices(down_id, back_at, size), 0, 0, 1, sub(whole_id), true, {0, 0, 1, size, size, 3}})); - EXPECT(list.copy_texture({slices(down_id, part_at, size), 0, 0, 0, sub(part_id), false, {}})); - EXPECT(list.clear_render_target({msaa_id, 0, 0, 1}, {0, 1, 0, 1})); - EXPECT(list.transition({msaa_id, 0, s::render_target, s::resolve_source})); - EXPECT(list.resolve_subresource({resolved_id, 0, msaa_id, 0})); - EXPECT(list.transition({resolved_id, 0, s::resolve_dest, s::copy_source})); - EXPECT(list.copy_texture({{down_id, true, 0, resolved_at, wide, wide, 1, pitch}, 0, 0, 0, sub(resolved_id), false, {}})); - EXPECT(list.close()); - - bool ok = d.run([&](VkCommandBuffer cb) { - // Rejected lists write nothing and leave the tracker alone. - CommandList bad; - const auto rejected = [&](auto&& record, ReplayResult expected, const ReplayFunctions& functions) { - if (!bad.closed()) bad.close(); - bad.reset(); - if (!record()) return false; - bad.close(); - const ReplayResult got = replay(bad, cb, resolve, functions, &tracker); - if (got != expected) std::fprintf(stderr, "rejected list: got %d, want %d\n", int(got), int(expected)); - return got == expected; - }; - const auto copy = [&](const CopyTexture& c) { return [&bad, c] { return bad.copy_texture(c); }; }; - const auto resolving = [&](const ResolveSubresource& c) { return [&bad, c] { return bad.resolve_subresource(c); }; }; - constexpr auto invalid = ReplayResult::invalid_copy; - if (!rejected(resolving({msaa_id, 0, resolved_id, 0}), invalid, vk) || // single-sampled source - !rejected(resolving({volume_id, 0, msaa_id, 0}), invalid, vk) || // another size - !rejected(resolving({resolved_id, 1, msaa_id, 0}), ReplayResult::invalid_subresource, vk) || - !rejected(resolving({resolved_id, 0, msaa_id, 0}), ReplayResult::unsupported, without_resolve) || - // Slices 3 and 4 of 4; a box deeper than its footprint; a footprint past the end of the buffer. - !rejected(copy({sub(part_id), 0, 0, 3, sub(volume_id), true, {0, 0, 0, size, size, 2}}), invalid, vk) || - !rejected(copy({sub(volume_id), 0, 0, 0, slices(up_id, up_at, 2), true, {0, 0, 0, size, size, 3}}), invalid, vk) || - !rejected(copy({sub(volume_id), 0, 0, 0, slices(up_id, 13312, size), false, {}}), invalid, vk) || - // A multisampled texture has no footprint and copies only to its own sample count. - !rejected(copy({{down_id, true, 0, 0, wide, wide, 1, pitch}, 0, 0, 0, sub(msaa_id), false, {}}), invalid, vk) || - !rejected(copy({sub(resolved_id), 0, 0, 0, sub(msaa_id), false, {}}), invalid, vk)) - return false; - if (tracker.layout(volume_id, 0) != VK_IMAGE_LAYOUT_UNDEFINED) return false; - return replay(list, cb, resolve, vk, &tracker) == ReplayResult::success; - }); - EXPECT(ok); - for (const ResourceId id : {volume_id, part_id, whole_id, msaa_id, resolved_id}) - EXPECT(tracker.layout(id, 0) == VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL); - - const auto expect_texel = [&](const char* what, const std::uint8_t* got, const std::uint8_t* want, std::uint32_t index) { - Rgba expected{}; - std::copy(want, want + 4, expected.begin()); - expect_rgba(what, got, index, expected); - }; - const std::uint8_t zero[4] = {}; - for (std::uint32_t z = 0; z < size; ++z) { - for (std::uint32_t y = 0; y < size; ++y) { - for (std::uint32_t x = 0; x < size; ++x) { - const std::uint32_t row = z * slice + y * pitch; - if (z == 1 || z == 2) expect_texel("C slices", r + back_at + row, texel(x, y, z), x); - // The block came from (1..2, 1..2, 1..2); the rest of the volume was zero-filled on first use. - const bool inside = x >= 2 && y < 2 && z >= 1 && z < 3; - expect_texel("C block", r + part_at + row, inside ? texel(x - 1, y + 1, z) : zero, x); - } - } - } - EXPECT(r[back_at] == 0xcd && r[back_at + 3 * slice] == 0xcd && r[back_at + slice + 16] == 0xcd); // not written - for (std::uint32_t row = 0; row < wide; ++row) - for (std::uint32_t col = 0; col < wide; ++col) expect_rgba("C resolve", r + resolved_at + row * pitch, col, green); - std::printf("C: a %ux%ux%u volume uploaded, copied in part and whole and read back; a 4x resolve of %u texels\n", - size, size, size, wide * wide); - return 0; -} - -// Part D: every D3D12 sync bit against every access bit, as global, buffer and texture barriers. Whatever pair the -// application names, the Vulkan barrier must be valid, so every access has a stage in its scope that can perform it -// (vulkan_barrier_scope). Under LEONIDA_VK_VALIDATION=1 a pair that breaks that rule is a validation error. The -// image is simultaneous-access, so it stays in GENERAL, which every access may use: only the stage/access rule is -// under test. -int part_d(vktest::Device& d) { - namespace y = d3d12_sync; - namespace a = d3d12_access; - namespace l = d3d12_layout; - const VkImage image = d.image(VK_FORMAT_R8G8B8A8_UNORM, 4, 4, 1, - VK_IMAGE_USAGE_SAMPLED_BIT | VK_IMAGE_USAGE_STORAGE_BIT | - VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT); - EXPECT(image); - constexpr ResourceId image_id = 30, buffer_id = 31; - ResourceBinding image_binding{}; - image_binding.image = image; - image_binding.format = VK_FORMAT_R8G8B8A8_UNORM; - image_binding.width = image_binding.height = 4; - image_binding.simultaneous_access = true; - const ResourceBinding buffer_binding{}; // a buffer: no image - const auto resolve = [&](ResourceId id) -> const ResourceBinding* { - if (id == image_id) return &image_binding; - return id == buffer_id ? &buffer_binding : nullptr; - }; - ReplayFunctions vk{}; - vk.pipeline_barrier = d.fn("vkCmdPipelineBarrier"); - vk.clear_color_image = d.fn("vkCmdClearColorImage"); - vk.clear_depth_stencil_image = d.fn("vkCmdClearDepthStencilImage"); - vk.pipeline_barrier2 = d.fn("vkCmdPipelineBarrier2"); - vk.separate_depth_stencil_layouts = true; - LayoutTracker tracker(true); - tracker.track(image_id, image_binding, VK_IMAGE_LAYOUT_GENERAL); - - // Ray-tracing, video and split syncs map to ALL_COMMANDS, which every access accepts; they are kept anyway. - const std::uint32_t syncs[] = {y::all, y::draw, y::index_input, y::vertex_shading, y::pixel_shading, - y::depth_stencil, y::render_target, y::compute_shading, y::raytracing, y::copy, - y::resolve, y::execute_indirect, y::all_shading, y::non_pixel_shading, - y::emit_raytracing_acceleration_structure_postbuild_info, - y::clear_unordered_access_view, y::video_decode, - y::build_raytracing_acceleration_structure}; - const std::uint32_t accesses[] = {a::common, a::vertex_buffer, a::constant_buffer, a::index_buffer, - a::render_target, a::unordered_access, a::depth_stencil_write, - a::depth_stencil_read, a::shader_resource, a::stream_output, - a::indirect_argument, a::copy_dest, a::copy_source, a::resolve_dest, - a::resolve_source, a::raytracing_acceleration_structure_read, - a::raytracing_acceleration_structure_write, a::shading_rate_source, - a::video_decode_read, a::no_access}; - const BarrierSubresourceRange all{all_subresources, 0, 0, 0, 0, 0}; - CommandList list; - unsigned pairs = 0; - for (const std::uint32_t sync : syncs) { - for (const std::uint32_t access : accesses) { - EXPECT(list.barrier(GlobalBarrier{sync, sync, access, access})); - EXPECT(list.barrier(BufferBarrier{sync, sync, access, access, buffer_id})); - EXPECT(list.barrier(TextureBarrier{sync, sync, access, access, l::common, l::common, image_id, all, 0})); - ++pairs; - } - } - EXPECT(list.close()); - const unsigned errors_before = d.validation_errors(); - const bool ok = d.run([&](VkCommandBuffer cb) { - d.initial_layout(cb, image, VK_IMAGE_ASPECT_COLOR_BIT, 1, VK_IMAGE_LAYOUT_GENERAL); - return replay(list, cb, resolve, vk, &tracker) == ReplayResult::success; - }); - EXPECT(ok); - const unsigned errors = d.validation_errors() - errors_before; - std::printf("D: %u sync/access pairs as global, buffer and texture barriers%s\n", pairs, - d.validation ? (errors ? ": validation errors" : ", no validation errors") : " (validation off)"); - return 0; -} - -// SetPredication on VK_EXT_conditional_rendering (D3D-18). One layer per case: a clear runs or is skipped by the -// 64-bit predicate value (0 or 1) and the op. Whole-view clears under a predicate go through vkCmdClearAttachments, -// which conditional rendering covers. A predicate still set at the end of the list must be ended by the replay. -int part_e(vktest::Device& d) { - if (!d.conditional_rendering) { - std::printf("E: skipped, no VK_EXT_conditional_rendering\n"); - return 0; - } - namespace pred = d3d12_predication; - constexpr std::uint32_t size = 4, layers = 5, texels = size * size; - const VkImage color = d.image(VK_FORMAT_R8G8B8A8_UNORM, size, size, layers, VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT); - void* predicate_words = nullptr; - const VkBuffer predicate = d.buffer(32, VK_BUFFER_USAGE_CONDITIONAL_RENDERING_BIT_EXT | VK_BUFFER_USAGE_TRANSFER_SRC_BIT, &predicate_words); - void* mapped = nullptr; - const VkBuffer readback = d.buffer(texels * layers * 4, VK_BUFFER_USAGE_TRANSFER_DST_BIT, &mapped); - EXPECT(color && predicate && readback); - // Offset 0: the 64-bit value 0. Offset 8: the 64-bit value 1. Written before the submit, so visible to it. - const std::uint32_t words[4] = {0, 0, 1, 0}; - std::memcpy(predicate_words, words, sizeof(words)); - - ResourceBinding color_binding{}; - color_binding.image = color; - color_binding.format = VK_FORMAT_R8G8B8A8_UNORM; - color_binding.width = color_binding.height = size; - color_binding.array_layers = layers; - ResourceBinding predicate_binding{}; - predicate_binding.buffer = predicate; - predicate_binding.size = 32; - constexpr ResourceId color_id = 20, predicate_id = 21, missing_id = 22; - const auto resolve = [&](ResourceId id) -> const ResourceBinding* { - if (id == color_id) return &color_binding; - if (id == predicate_id) return &predicate_binding; - return nullptr; - }; - - Views views{d, {}}; - ReplayFunctions vk{}; - vk.pipeline_barrier = d.fn("vkCmdPipelineBarrier"); - vk.clear_color_image = d.fn("vkCmdClearColorImage"); - vk.clear_depth_stencil_image = d.fn("vkCmdClearDepthStencilImage"); - vk.begin_rendering = d.fn("vkCmdBeginRendering"); - vk.end_rendering = d.fn("vkCmdEndRendering"); - vk.clear_attachments = d.fn("vkCmdClearAttachments"); - vk.copy_buffer = d.fn("vkCmdCopyBuffer"); - vk.copy_buffer_to_image = d.fn("vkCmdCopyBufferToImage"); - vk.copy_image_to_buffer = d.fn("vkCmdCopyImageToBuffer"); - vk.copy_image = d.fn("vkCmdCopyImage"); - vk.image_view = [&](const ResourceBinding& r, const VkImageSubresourceRange& range) { return views(r, range); }; - ReplayFunctions without_conditional = vk; - vk.begin_conditional_rendering = - d.fn("vkCmdBeginConditionalRenderingEXT"); - vk.end_conditional_rendering = d.fn("vkCmdEndConditionalRenderingEXT"); - EXPECT(vk.begin_conditional_rendering && vk.end_conditional_rendering); - VkPhysicalDeviceMemoryProperties memory{}; - d.instance_fn("vkGetPhysicalDeviceMemoryProperties")(d.physical, &memory); - VkPhysicalDeviceProperties properties{}; - d.instance_fn("vkGetPhysicalDeviceProperties")(d.physical, &properties); - PredicateReducer reducer(d.device_proc, d.device, memory, properties.limits.maxStorageBufferRange); - auto conditions = reducer.batch(32); - EXPECT(conditions); - vk.prepare_predicate = [&](VkBuffer source, VkDeviceSize offset, PredicateCapture& out) { - return conditions->prepare(source, offset, out); - }; - vk.capture_predicate = [&](VkCommandBuffer cb, const PredicateCapture& p) { reducer.capture(cb, p); }; - - // Lists that are rejected, and the count of copies Vulkan cannot predicate. Nothing is written by prepare(). - const auto prepared_with = [&](auto&& record, const ReplayFunctions& functions, PreparedList& out) { - CommandList bad; - record(bad); - bad.close(); - return prepare(bad, resolve, functions, out); - }; - PreparedList scratch; - const auto set = [](ResourceId buffer, std::uint64_t offset, std::uint32_t op) { - return [=](CommandList& l) { l.set_predication({buffer, offset, op}); }; - }; - EXPECT(prepared_with(set(predicate_id, 0, pred::equal_zero), without_conditional, scratch) == - ReplayResult::unsupported); - EXPECT(prepared_with(set(0, 0, 0), without_conditional, scratch) == ReplayResult::success); // off needs nothing - EXPECT(prepared_with(set(missing_id, 0, pred::equal_zero), vk, scratch) == ReplayResult::unresolved_resource); - EXPECT(prepared_with(set(predicate_id, 32, pred::equal_zero), vk, scratch) == ReplayResult::invalid_predication); - EXPECT(prepared_with(set(color_id, 0, pred::equal_zero), vk, scratch) == ReplayResult::invalid_predication); - const auto copies = [&](CommandList& l) { - l.copy_buffer({predicate_id, 16, predicate_id, 0, 8}); // before the predicate: counted 0 - l.set_predication({predicate_id, 0, pred::equal_zero}); - l.copy_buffer({predicate_id, 16, predicate_id, 0, 8}); // under it: counted - l.set_predication({0, 0, 0}); - l.copy_buffer({predicate_id, 16, predicate_id, 0, 8}); // after it: counted 0 - }; - EXPECT(prepared_with(copies, vk, scratch) == ReplayResult::unsupported); - ReplayFunctions copy_functions = vk; - // Preparation-only routing test; no fake descriptor set is ever submitted. - copy_functions.prepare_predicated_copy = [](VkBuffer, VkBuffer, VkDeviceSize, VkDeviceSize, VkDeviceSize bytes, - std::vector& out) { - out.push_back({VK_NULL_HANDLE, 0, 0, static_cast(bytes)}); - return true; - }; - copy_functions.emit_predicated_copy = [](VkCommandBuffer, const std::vector&) {}; - EXPECT(prepared_with(copies, copy_functions, scratch) == ReplayResult::success); - EXPECT(scratch.unpredicated_copies == 0); - - const Rect corner{0, 0, 2, 2}; - CommandList list; - EXPECT(list.clear_render_target({color_id, 0, 0, layers}, {1, 0, 0, 1})); // every layer red, unpredicated - EXPECT(list.set_predication({predicate_id, 0, pred::equal_zero})); // value 0: skipped - EXPECT(list.clear_render_target({color_id, 0, 0, 1}, {0, 1, 0, 1})); // layer 0, whole view - EXPECT(list.clear_render_target({color_id, 0, 0, 1}, {0, 0, 1, 1}, {&corner, 1})); // layer 0, rectangle - EXPECT(list.set_predication({predicate_id, 8, pred::equal_zero})); // value 1: runs - EXPECT(list.clear_render_target({color_id, 0, 1, 1}, {0, 1, 0, 1})); // layer 1 - EXPECT(list.set_predication({predicate_id, 8, pred::not_equal_zero})); // value 1: skipped - EXPECT(list.clear_render_target({color_id, 0, 2, 1}, {0, 1, 0, 1})); // layer 2 - EXPECT(list.set_predication({predicate_id, 0, pred::not_equal_zero})); // value 0: runs - EXPECT(list.clear_render_target({color_id, 0, 3, 1}, {0, 1, 0, 1})); // layer 3 - EXPECT(list.set_predication({predicate_id, 0, pred::equal_zero})); - EXPECT(list.set_predication({0, 0, 0})); // off again: runs - EXPECT(list.clear_render_target({color_id, 0, 4, 1}, {0, 1, 0, 1})); // layer 4 - EXPECT(list.transition({color_id, all_subresources, s::render_target, s::copy_source})); - EXPECT(list.set_predication({predicate_id, 0, pred::equal_zero})); // left set: the replay ends it - EXPECT(list.close()); - - const bool ok = d.run([&](VkCommandBuffer cb) { - d.initial_layout(cb, color, VK_IMAGE_ASPECT_COLOR_BIT, layers, VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL); - if (replay(list, cb, resolve, vk) != ReplayResult::success) return false; - d.read_back(cb, color, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, VK_IMAGE_ASPECT_COLOR_BIT, size, size, layers, - readback, 0); - return true; - }); - EXPECT(ok); - const auto* data = static_cast(mapped); - const Rgba expected[layers] = {red, green, red, green, green}; - for (std::uint32_t i = 0; i < texels * layers; ++i) expect_rgba("E predication", data, i, expected[i / texels]); - std::printf("E: predicated clears on %u layers (equal/not-equal zero, whole view and rectangle, off), " - "rejected predicates, %zu copy under a predicate counted\n", layers, scratch.unpredicated_copies); - return 0; -} - -// Part F (D3D-26): WriteBufferImmediate in its three modes, AtomicCopyBufferUINT/UINT64 and DiscardResource. -// Buffers carry console VAs; one binding is a range inside another buffer, as resources in the GPU address arena -// are. The writes and copies are ordered so that a missing barrier would let a copy read a stale or a later value. -// A colour target is cleared, discarded and cleared again; a second one is only discarded in part. -int part_f(vktest::Device& d) { - constexpr VkDeviceSize bytes = 256, c_offset = 128, c_size = 64; - constexpr std::uint64_t va_a = 0x10000, va_b = 0x20000, va_c = 0x30000; - constexpr std::uint32_t size = 8, texels = size * size; - constexpr VkBufferUsageFlags usage = VK_BUFFER_USAGE_TRANSFER_SRC_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT; - void *a_mapped = nullptr, *b_mapped = nullptr, *image_mapped = nullptr; - const VkBuffer a = d.buffer(bytes, usage, &a_mapped); - const VkBuffer b = d.buffer(bytes, usage, &b_mapped); - const VkBuffer pixels = d.buffer(texels * 4 * 2, VK_BUFFER_USAGE_TRANSFER_DST_BIT, &image_mapped); - const VkImage rt = d.image(VK_FORMAT_R8G8B8A8_UNORM, size, size, 1, VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT); - const VkImage kept = d.image(VK_FORMAT_R8G8B8A8_UNORM, size, size, 1, VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT); - EXPECT(a && b && pixels && rt && kept); - - const auto buffer_binding = [](VkBuffer buffer, VkDeviceSize offset, VkDeviceSize length, std::uint64_t va) { - ResourceBinding r{}; - r.buffer = buffer; - r.buffer_offset = offset; - r.size = length; - r.va = va; - return r; - }; - const auto image_binding = [&](VkImage image) { - ResourceBinding r{}; - r.image = image; - r.format = VK_FORMAT_R8G8B8A8_UNORM; - r.width = r.height = size; - return r; - }; - constexpr ResourceId a_id = 30, b_id = 31, c_id = 32, rt_id = 33, kept_id = 34, pred_id = 35; - std::map bindings{ - {a_id, buffer_binding(a, 0, bytes, va_a)}, - {b_id, buffer_binding(b, 0, c_offset, va_b)}, // the first half of b - {c_id, buffer_binding(b, c_offset, c_size, va_c)}, // a range at 128 in b - {rt_id, image_binding(rt)}, - {kept_id, image_binding(kept)}, - }; - void* pred_words = nullptr; - VkBuffer pred_buf = VK_NULL_HANDLE; - if (d.conditional_rendering) { - pred_buf = d.buffer(16, VK_BUFFER_USAGE_CONDITIONAL_RENDERING_BIT_EXT | VK_BUFFER_USAGE_TRANSFER_SRC_BIT, - &pred_words); - EXPECT(pred_buf && pred_words); - std::memset(pred_words, 0, 16); - bindings.emplace(pred_id, buffer_binding(pred_buf, 0, 16, 0)); - } - const auto resolve = [&](ResourceId id) -> const ResourceBinding* { - const auto it = bindings.find(id); - return it == bindings.end() ? nullptr : &it->second; - }; - LayoutTracker tracker(true); - tracker.track(rt_id, bindings.at(rt_id), VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL); - tracker.track(kept_id, bindings.at(kept_id), VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL); - - Views views{d, {}}; - ReplayFunctions vk{}; - vk.pipeline_barrier = d.fn("vkCmdPipelineBarrier"); - vk.clear_color_image = d.fn("vkCmdClearColorImage"); - vk.clear_depth_stencil_image = d.fn("vkCmdClearDepthStencilImage"); - vk.begin_rendering = d.fn("vkCmdBeginRendering"); - vk.end_rendering = d.fn("vkCmdEndRendering"); - vk.clear_attachments = d.fn("vkCmdClearAttachments"); - vk.image_view = [&](const ResourceBinding& r, const VkImageSubresourceRange& range) { return views(r, range); }; - vk.copy_buffer = d.fn("vkCmdCopyBuffer"); - vk.copy_buffer_to_image = d.fn("vkCmdCopyBufferToImage"); - vk.copy_image_to_buffer = d.fn("vkCmdCopyImageToBuffer"); - vk.copy_image = d.fn("vkCmdCopyImage"); - vk.separate_depth_stencil_layouts = true; - const ReplayFunctions without_update = vk; - vk.update_buffer = d.fn("vkCmdUpdateBuffer"); - VkPhysicalDeviceMemoryProperties memory{}; - d.instance_fn("vkGetPhysicalDeviceMemoryProperties")(d.physical, &memory); - VkPhysicalDeviceProperties properties{}; - d.instance_fn("vkGetPhysicalDeviceProperties")(d.physical, &properties); - PredicateReducer reducer(d.device_proc, d.device, memory, properties.limits.maxStorageBufferRange); - std::unique_ptr conditions; - if (d.conditional_rendering) { - vk.begin_conditional_rendering = - d.fn("vkCmdBeginConditionalRenderingEXT"); - vk.end_conditional_rendering = d.fn("vkCmdEndConditionalRenderingEXT"); - EXPECT(vk.begin_conditional_rendering && vk.end_conditional_rendering); - conditions = reducer.batch(4); - EXPECT(conditions); - vk.prepare_predicate = [&](VkBuffer source, VkDeviceSize offset, PredicateCapture& out) { - return conditions->prepare(source, offset, out); - }; - vk.capture_predicate = [&](VkCommandBuffer cb, const PredicateCapture& p) { reducer.capture(cb, p); }; - } - vk.buffer_at = [&](std::uint64_t va, std::uint64_t length, VkBuffer& buffer, VkDeviceSize& offset) { - for (const auto& [id, r] : bindings) { - if (r.image || !r.va || va < r.va || va - r.va >= r.size || length > r.size - (va - r.va)) continue; - buffer = r.buffer; - offset = r.buffer_offset + (va - r.va); - return true; - } - return false; - }; - - namespace m = write_immediate_mode; - CommandList list; - EXPECT(list.write_immediate({va_a, 0x11111111, m::normal})); - EXPECT(list.write_immediate({va_a + 4, 0x22222222, m::marker_in})); - EXPECT(list.write_immediate({va_c, 0x33333333, m::marker_out})); // lands at b + 128 - EXPECT(list.write_immediate({va_c + c_size - 4, 0x55555555, m::normal})); // the last word of c - // The copies wait for the writes before them (RAW on a); the MARKER_OUT write after them waits for them (WAR). - EXPECT(list.atomic_copy({b_id, 0, a_id, 4, 4, {{a_id, 0, 0, 8}}})); - EXPECT(list.atomic_copy({b_id, 8, a_id, 0, 8, {{a_id, 0, 0, 8}, {c_id, 0, 0, 4}}})); - EXPECT(list.write_immediate({va_a, 0x44444444, m::marker_out})); - EXPECT(list.atomic_copy({b_id, 16, a_id, 0, 4, {{a_id, 0, 0, 4}}})); - EXPECT(list.atomic_copy({c_id, 8, b_id, 0, 4, {{b_id, 0, 0, 4}}})); // into the range inside b - EXPECT(list.discard({a_id, 0, 0, false, true})); // a buffer: kept - // rt: red, discarded whole, then green over the whole view. kept: red, then a discard with rectangles. - EXPECT(list.clear_render_target({rt_id, 0, 0, 1}, {1, 0, 0, 1})); - EXPECT(list.discard({rt_id, 0, 0, false, true})); - EXPECT(list.clear_render_target({rt_id, 0, 0, 1}, {0, 1, 0, 1})); - EXPECT(list.transition({rt_id, 0, s::render_target, s::copy_source})); - EXPECT(list.clear_render_target({kept_id, 0, 0, 1}, {1, 0, 0, 1})); - EXPECT(list.discard({kept_id, 0, 1, true})); - if (d.conditional_rendering) { - // WriteBufferImmediate is unconditional on hardware D3D12 (all three modes); a subsequent clear under the - // same false predicate must stay suppressed so kept remains red. - EXPECT(list.set_predication({pred_id, 0, d3d12_predication::equal_zero})); - EXPECT(list.write_immediate({va_a + 16, 0x66666666, m::normal})); - EXPECT(list.write_immediate({va_a + 20, 0x77777777, m::marker_in})); - EXPECT(list.write_immediate({va_a + 24, 0x88888888, m::marker_out})); - EXPECT(list.clear_render_target({kept_id, 0, 0, 1}, {0, 0, 1, 1})); - EXPECT(list.set_predication({0, 0, 0})); - } - EXPECT(list.transition({kept_id, 0, s::render_target, s::copy_source})); - EXPECT(list.close()); - - bool ok = d.run([&](VkCommandBuffer cb) { - d.initial_layout(cb, rt, VK_IMAGE_ASPECT_COLOR_BIT, 1, VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL); - d.initial_layout(cb, kept, VK_IMAGE_ASPECT_COLOR_BIT, 1, VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL); - CommandList bad; - const auto rejected = [&](auto&& record, ReplayResult expected, const ReplayFunctions& functions) { - if (!bad.closed()) bad.close(); - bad.reset(); - if (!record()) return false; - bad.close(); - const ReplayResult got = replay(bad, cb, resolve, functions, &tracker); - if (got != expected) std::fprintf(stderr, "F rejected list: got %d, want %d\n", int(got), int(expected)); - return got == expected; - }; - const auto write = [&](std::uint64_t va) { return [&bad, va] { return bad.write_immediate({va, 1, 0}); }; }; - const auto atomic = [&](AtomicCopyBuffer c) { return [&bad, c] { return bad.atomic_copy(c); }; }; - const auto discard = [&](DiscardResource c) { return [&bad, c] { return bad.discard(c); }; }; - constexpr auto unresolved = ReplayResult::unresolved_resource; - if (!rejected(write(va_c + c_size), unresolved, vk) || // one past c - !rejected(write(0x40000), unresolved, vk) || // no resource there - !rejected(write(va_a), ReplayResult::unsupported, without_update) || - !rejected(atomic({b_id, c_offset, a_id, 0, 8, {{a_id, 0, 0, 8}}}), ReplayResult::invalid_copy, vk) || // past b - !rejected(atomic({b_id, 0, a_id, 0, 4, {{99, 0, 0, 4}}}), unresolved, vk) || - !rejected(atomic({b_id, 0, a_id, 0, 4, {{a_id, 0, 0, bytes + 4}}}), ReplayResult::invalid_copy, vk) || - !rejected(discard({rt_id, 1, 1, false}), ReplayResult::invalid_subresource, vk) || - !rejected(discard({a_id, 1, 1, false}), ReplayResult::invalid_subresource, vk) || - // An explicit count of UINT_MAX is a range, not the whole resource: it runs past rt and a. - !rejected(discard({rt_id, 0, all_subresources, false}), ReplayResult::invalid_subresource, vk) || - !rejected(discard({a_id, 0, all_subresources, false}), ReplayResult::invalid_subresource, vk)) - return false; - if (replay(list, cb, resolve, vk, &tracker) != ReplayResult::success) return false; - d.read_back(cb, rt, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, VK_IMAGE_ASPECT_COLOR_BIT, size, size, 1, pixels, 0); - d.read_back(cb, kept, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, VK_IMAGE_ASPECT_COLOR_BIT, size, size, 1, pixels, - texels * 4); - VkMemoryBarrier host{VK_STRUCTURE_TYPE_MEMORY_BARRIER}; - host.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT; - host.dstAccessMask = VK_ACCESS_HOST_READ_BIT; - vk.pipeline_barrier(cb, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_HOST_BIT, 0, 1, &host, 0, nullptr, 0, - nullptr); - return true; - }); - EXPECT(ok); - EXPECT(tracker.layout(rt_id, 0) == VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL); - EXPECT(tracker.layout(kept_id, 0) == VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL); - - const auto word = [](const void* base, VkDeviceSize offset) { - std::uint32_t value; - std::memcpy(&value, static_cast(base) + offset, 4); - return value; - }; - constexpr std::uint32_t untouched = 0xcdcdcdcd; - std::map want_a{{0, 0x44444444}, {4, 0x22222222}}; - if (d.conditional_rendering) { - want_a[16] = 0x66666666; - want_a[20] = 0x77777777; - want_a[24] = 0x88888888; - } - std::map want_b{{0, 0x22222222}, {8, 0x11111111}, - {12, 0x22222222}, {16, 0x44444444}, - {c_offset, 0x33333333}, {c_offset + 8, 0x22222222}, - {c_offset + c_size - 4, 0x55555555}}; - for (VkDeviceSize offset = 0; offset < bytes; offset += 4) { - for (const auto& [name, base, want] : {std::tuple{"F buffer a", a_mapped, &want_a}, - std::tuple{"F buffer b", b_mapped, &want_b}}) { - const auto it = want->find(offset); - const std::uint32_t expected = it == want->end() ? untouched : it->second; - const std::uint32_t got = word(base, offset); - if (got != expected && g_mismatches++ < 8) - std::fprintf(stderr, "%s +%llu: got 0x%08x, want 0x%08x\n", name, (unsigned long long)offset, got, - expected); - } - } - const auto* image_data = static_cast(image_mapped); - for (std::uint32_t i = 0; i < texels; ++i) { - expect_rgba("F discarded then cleared", image_data, i, green); - expect_rgba("F partly discarded", image_data + texels * 4, i, red); - } - std::printf("F: immediate writes in three modes, UINT and UINT64 atomic copies, buffer and texture discards\n"); - return 0; -} - -// A subresource copied twice in one command list, as d3d12_vulkan_device_test's BC7 copy case does. D3D12 orders -// back-to-back copies on the queue and leaves the image in COPY_DEST, so the second write needs no barrier from the -// application; on Vulkan a texture that keeps its layout gets no transition on the second copy, so the earlier -// transfer write has to be ordered explicitly or synchronization validation reports a write-after-write hazard. -// The texels must show the second copy. -int part_g(vktest::Device& d) { - constexpr std::uint32_t size = 4, texels = size * size, pitch = texture_data_pitch_alignment; - constexpr VkDeviceSize placed = VkDeviceSize(size) * pitch; // one footprint, in the upload buffer - constexpr VkDeviceSize bytes = VkDeviceSize(texels) * 4; // the readback holds tight rows - const VkImage image = d.image(VK_FORMAT_R8G8B8A8_UNORM, size, size, 1, VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT); - void* up_mapped = nullptr; - const VkBuffer up = d.buffer(placed * 2, VK_BUFFER_USAGE_TRANSFER_SRC_BIT, &up_mapped); - void* readback_mapped = nullptr; - const VkBuffer readback = d.buffer(bytes, VK_BUFFER_USAGE_TRANSFER_DST_BIT, &readback_mapped); - EXPECT(image && up && readback); - - auto* source = static_cast(up_mapped); - for (std::uint32_t row = 0; row < size; ++row) - for (std::uint32_t col = 0; col < size; ++col) { - std::copy(red.begin(), red.end(), source + row * pitch + col * 4); // first copy - std::copy(green.begin(), green.end(), source + placed + row * pitch + col * 4); // second copy - } - - ResourceBinding image_binding{}; - image_binding.image = image; - image_binding.format = VK_FORMAT_R8G8B8A8_UNORM; - image_binding.width = image_binding.height = size; - image_binding.depth = 1; - image_binding.samples = 1; - ResourceBinding up_binding{}; - up_binding.buffer = up; - up_binding.size = placed * 2; - constexpr ResourceId image_id = 30, up_id = 31; - const std::map bindings{{image_id, image_binding}, {up_id, up_binding}}; - const auto resolve = [&](ResourceId id) -> const ResourceBinding* { - const auto it = bindings.find(id); - return it == bindings.end() ? nullptr : &it->second; - }; - LayoutTracker tracker(true); - tracker.track(image_id, image_binding, VK_IMAGE_LAYOUT_UNDEFINED); - - ReplayFunctions vk{}; - vk.pipeline_barrier = d.fn("vkCmdPipelineBarrier"); - vk.pipeline_barrier2 = d.fn("vkCmdPipelineBarrier2"); - vk.clear_color_image = d.fn("vkCmdClearColorImage"); - vk.copy_buffer = d.fn("vkCmdCopyBuffer"); - vk.copy_buffer_to_image = d.fn("vkCmdCopyBufferToImage"); - vk.copy_image_to_buffer = d.fn("vkCmdCopyImageToBuffer"); - vk.copy_image = d.fn("vkCmdCopyImage"); - vk.separate_depth_stencil_layouts = true; // matches LayoutTracker - - const CopyLocation dst{image_id, false, 0, 0, 0, 0, 0, 0}; - const auto footprint = [&](VkDeviceSize offset) { - return CopyLocation{up_id, true, 0, offset, size, size, 1, pitch}; - }; - CommandList list; - EXPECT(list.copy_texture({dst, 0, 0, 0, footprint(0), false, {}})); - EXPECT(list.copy_texture({dst, 0, 0, 0, footprint(placed), false, {}})); // same subresource, no transition between - EXPECT(list.transition({image_id, 0, s::copy_dest, s::copy_source})); - EXPECT(list.close()); - - const unsigned errors_before = d.validation_errors(); - const bool ok = d.run([&](VkCommandBuffer cb) { - if (replay(list, cb, resolve, vk, &tracker) != ReplayResult::success) return false; - d.read_back(cb, image, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, VK_IMAGE_ASPECT_COLOR_BIT, size, size, 1, readback, - 0); - VkMemoryBarrier host{VK_STRUCTURE_TYPE_MEMORY_BARRIER}; - host.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT; - host.dstAccessMask = VK_ACCESS_HOST_READ_BIT; - vk.pipeline_barrier(cb, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_HOST_BIT, 0, 1, &host, 0, nullptr, 0, - nullptr); - return true; - }); - EXPECT(ok); - EXPECT(tracker.layout(image_id, 0) == VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL); - - const auto* texels_read = static_cast(readback_mapped); - for (std::uint32_t i = 0; i < texels; ++i) expect_rgba("G copied twice", texels_read, i, green); - const unsigned errors = d.validation_errors() - errors_before; - std::printf("G: one subresource copied twice in one list%s\n", - d.validation ? (errors ? ": validation errors" : ", no validation errors") : " (validation off)"); - return 0; -} - -// Part H: depth <-> colour copies. A D32 depth image is uploaded from floats, copied whole into an R32_SFLOAT colour -// image (CopyResource), and that into a second depth image (CopyTextureRegion); both are read back bit for bit. -// vkCmdCopyImage cannot mix a depth and a colour aspect, so the replay stages each copy through `copy_scratch`; with -// no scratch the list is refused as unsupported, before anything is written. -int part_h(vktest::Device& d) { - if (!d.depth_format_usable(VK_FORMAT_D32_SFLOAT)) { - std::printf("H: skipped, no D32_SFLOAT\n"); - return 0; - } - constexpr std::uint32_t size = 4, texels = size * size, pitch = texture_data_pitch_alignment; - constexpr VkDeviceSize bytes = VkDeviceSize(texels) * 4, scratch_bytes = 65536; - const VkImage depth = d.image(VK_FORMAT_D32_SFLOAT, size, size, 1, VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT); - const VkImage colour = d.image(VK_FORMAT_R32_SFLOAT, size, size, 1, VK_IMAGE_USAGE_SAMPLED_BIT); - const VkImage back = d.image(VK_FORMAT_D32_SFLOAT, size, size, 1, VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT); - void *up_mapped = nullptr, *down_mapped = nullptr, *scratch_mapped = nullptr; - const VkBuffer up = d.buffer(VkDeviceSize(size) * pitch, VK_BUFFER_USAGE_TRANSFER_SRC_BIT, &up_mapped); - const VkBuffer down = d.buffer(bytes * 2, VK_BUFFER_USAGE_TRANSFER_DST_BIT, &down_mapped); - const VkBuffer scratch = d.buffer(scratch_bytes, VK_BUFFER_USAGE_TRANSFER_SRC_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT, - &scratch_mapped); - EXPECT(depth && colour && back && up && down && scratch); - const auto value = [](std::uint32_t i) { return float(i * 7 % texels) / float(texels); }; // in [0, 1) - for (std::uint32_t i = 0; i < texels; ++i) { - const float v = value(i); - std::memcpy(static_cast(up_mapped) + (i / size) * pitch + (i % size) * 4, &v, 4); - } - - const auto image_binding = [&](VkImage image, VkFormat format, VkImageAspectFlags aspects) { - ResourceBinding b{}; - b.image = image; - b.format = format; - b.aspects = aspects; - b.width = b.height = size; - return b; - }; - ResourceBinding up_binding{}; - up_binding.buffer = up; - up_binding.size = VkDeviceSize(size) * pitch; - constexpr ResourceId depth_id = 40, colour_id = 41, back_id = 42, up_id = 43; - const std::map bindings{ - {depth_id, image_binding(depth, VK_FORMAT_D32_SFLOAT, VK_IMAGE_ASPECT_DEPTH_BIT)}, - {colour_id, image_binding(colour, VK_FORMAT_R32_SFLOAT, VK_IMAGE_ASPECT_COLOR_BIT)}, - {back_id, image_binding(back, VK_FORMAT_D32_SFLOAT, VK_IMAGE_ASPECT_DEPTH_BIT)}, - {up_id, up_binding}, - }; - const auto resolve = [&](ResourceId id) -> const ResourceBinding* { - const auto it = bindings.find(id); - return it == bindings.end() ? nullptr : &it->second; - }; - LayoutTracker tracker(true); - for (const ResourceId id : {depth_id, colour_id, back_id}) - tracker.track(id, bindings.at(id), VK_IMAGE_LAYOUT_UNDEFINED); - - ReplayFunctions vk{}; - vk.pipeline_barrier = d.fn("vkCmdPipelineBarrier"); - vk.clear_color_image = d.fn("vkCmdClearColorImage"); - vk.clear_depth_stencil_image = d.fn("vkCmdClearDepthStencilImage"); - vk.copy_buffer = d.fn("vkCmdCopyBuffer"); - vk.copy_buffer_to_image = d.fn("vkCmdCopyBufferToImage"); - vk.copy_image_to_buffer = d.fn("vkCmdCopyImageToBuffer"); - vk.copy_image = d.fn("vkCmdCopyImage"); - vk.separate_depth_stencil_layouts = true; // matches LayoutTracker - const ReplayFunctions without_scratch = vk; - VkDeviceSize scratch_used = 0; - vk.copy_scratch = [&](VkDeviceSize n, VkBuffer& buffer, VkDeviceSize& offset) { - if (n > scratch_bytes - scratch_used) return false; - buffer = scratch; - offset = scratch_used; - scratch_used += (n + 255) / 256 * 256; - return true; - }; - - const CopyLocation footprint{up_id, true, 0, 0, size, size, 1, pitch}; - const auto sub = [](ResourceId id) { return CopyLocation{id, false, 0, 0, 0, 0, 0, 0}; }; - CommandList list; - EXPECT(list.copy_texture({sub(depth_id), 0, 0, 0, footprint, false, {}})); - EXPECT(list.transition({depth_id, 0, s::copy_dest, s::copy_source})); - EXPECT(list.copy_resource({colour_id, depth_id})); // depth -> colour - EXPECT(list.transition({colour_id, 0, s::copy_dest, s::copy_source})); - EXPECT(list.copy_texture({sub(back_id), 0, 0, 0, sub(colour_id), false, {}})); // colour -> depth - EXPECT(list.transition({back_id, 0, s::copy_dest, s::copy_source})); - EXPECT(list.close()); - - const unsigned errors_before = d.validation_errors(); - const bool ok = d.run([&](VkCommandBuffer cb) { - if (replay(list, cb, resolve, without_scratch, &tracker) != ReplayResult::unsupported) return false; - if (tracker.layout(depth_id, 0) != VK_IMAGE_LAYOUT_UNDEFINED) return false; // refused before writing - if (replay(list, cb, resolve, vk, &tracker) != ReplayResult::success) return false; - d.read_back(cb, colour, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, VK_IMAGE_ASPECT_COLOR_BIT, size, size, 1, down, 0); - d.read_back(cb, back, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, VK_IMAGE_ASPECT_DEPTH_BIT, size, size, 1, down, - bytes); - return true; - }); - EXPECT(ok); - EXPECT(scratch_used > 0); - const auto* read = static_cast(down_mapped); - for (std::uint32_t i = 0; i < texels; ++i) { - float c = 0, b = 0; - std::memcpy(&c, read + i * 4, 4); - std::memcpy(&b, read + bytes + i * 4, 4); - if (c != value(i) || b != value(i)) { - std::fprintf(stderr, "H texel %u: colour %g, depth %g, expected %g\n", i, c, b, value(i)); - ++g_mismatches; - } - } - const unsigned errors = d.validation_errors() - errors_before; - std::printf("H: D32_FLOAT -> R32_FLOAT -> D32_FLOAT through scratch, %u texels%s\n", texels, - d.validation ? (errors ? ": validation errors" : ", no validation errors") : " (validation off)"); - return 0; -} - -// Part I: a depth MIN resolve of a rectangle (ResolveSubresourceRegion). A 4x D32 target cleared to 0.75 is resolved -// in its rectangle (2,1)-(7,5) into a 1x image cleared to 0.25; every texel outside the rectangle must keep 0.25. -// MoltenVK resolves the whole attachment whatever the render area, so the replay keeps the texels around the -// rectangle in `copy_scratch` across the resolve; with no scratch the list is refused as unsupported. -int part_i(vktest::Device& d) { - VkPhysicalDeviceDepthStencilResolveProperties modes{ - VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_DEPTH_STENCIL_RESOLVE_PROPERTIES}; - VkPhysicalDeviceProperties2 properties{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROPERTIES_2, &modes}; - d.instance_fn("vkGetPhysicalDeviceProperties2")(d.physical, &properties); - if (!d.depth_format_usable(VK_FORMAT_D32_SFLOAT) || !(modes.supportedDepthResolveModes & VK_RESOLVE_MODE_MIN_BIT)) { - std::printf("I: skipped, no D32_SFLOAT or no MIN depth resolve\n"); - return 0; - } - constexpr std::uint32_t width = 8, height = 6, texels = width * height; - constexpr VkDeviceSize scratch_bytes = 65536; - constexpr Rect rect{2, 1, 7, 5}; - const VkImage msaa = d.image(VK_FORMAT_D32_SFLOAT, width, height, 1, VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT, 1, 4); - const VkImage single = d.image(VK_FORMAT_D32_SFLOAT, width, height, 1, VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT); - void *down_mapped = nullptr, *scratch_mapped = nullptr; - const VkBuffer down = d.buffer(VkDeviceSize(texels) * 4, VK_BUFFER_USAGE_TRANSFER_DST_BIT, &down_mapped); - const VkBuffer scratch = d.buffer(scratch_bytes, VK_BUFFER_USAGE_TRANSFER_SRC_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT, - &scratch_mapped); - EXPECT(msaa && single && down && scratch); - - const auto image_binding = [&](VkImage image, std::uint32_t samples) { - ResourceBinding b{}; - b.image = image; - b.format = VK_FORMAT_D32_SFLOAT; - b.aspects = VK_IMAGE_ASPECT_DEPTH_BIT; - b.width = width; - b.height = height; - b.samples = samples; - return b; - }; - constexpr ResourceId msaa_id = 50, single_id = 51; - const std::map bindings{ - {msaa_id, image_binding(msaa, 4)}, - {single_id, image_binding(single, 1)}, - }; - const auto resolve = [&](ResourceId id) -> const ResourceBinding* { - const auto it = bindings.find(id); - return it == bindings.end() ? nullptr : &it->second; - }; - LayoutTracker tracker(true); - for (const ResourceId id : {msaa_id, single_id}) tracker.track(id, bindings.at(id), VK_IMAGE_LAYOUT_UNDEFINED); - - Views views{d, {}}; - ReplayFunctions vk{}; - vk.pipeline_barrier = d.fn("vkCmdPipelineBarrier"); - vk.clear_depth_stencil_image = d.fn("vkCmdClearDepthStencilImage"); - vk.copy_buffer_to_image = d.fn("vkCmdCopyBufferToImage"); - vk.copy_image_to_buffer = d.fn("vkCmdCopyImageToBuffer"); - vk.resolve_image = d.fn("vkCmdResolveImage"); - vk.begin_rendering = d.fn("vkCmdBeginRendering"); - vk.end_rendering = d.fn("vkCmdEndRendering"); - vk.image_view = [&](const ResourceBinding& r, const VkImageSubresourceRange& range) { return views(r, range); }; - vk.separate_depth_stencil_layouts = true; // matches LayoutTracker - const ReplayFunctions without_scratch = vk; - VkDeviceSize scratch_used = 0; - vk.copy_scratch = [&](VkDeviceSize n, VkBuffer& buffer, VkDeviceSize& offset) { - if (n > scratch_bytes - scratch_used) return false; - buffer = scratch; - offset = scratch_used; - scratch_used += (n + 255) / 256 * 256; - return true; - }; - - CommandList list; - EXPECT(list.clear_depth_stencil({msaa_id, 0, 0, 1}, clear_depth, 0.75f, 0)); - EXPECT(list.clear_depth_stencil({single_id, 0, 0, 1}, clear_depth, 0.25f, 0)); - EXPECT(list.transition({msaa_id, 0, s::depth_write, s::resolve_source})); - EXPECT(list.transition({single_id, 0, s::depth_write, s::resolve_dest})); - EXPECT(list.resolve_subresource( - {single_id, 0, msaa_id, 0, ResolveRegion{2, 1, rect, d3d12_resolve_mode::minimum}})); - EXPECT(list.transition({single_id, 0, s::resolve_dest, s::copy_source})); - EXPECT(list.close()); - - const unsigned errors_before = d.validation_errors(); - const bool ok = d.run([&](VkCommandBuffer cb) { - if (replay(list, cb, resolve, without_scratch, &tracker) != ReplayResult::unsupported) return false; - if (replay(list, cb, resolve, vk, &tracker) != ReplayResult::success) return false; - d.read_back(cb, single, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, VK_IMAGE_ASPECT_DEPTH_BIT, width, height, 1, down, - 0); - return true; - }); - EXPECT(ok); - EXPECT(scratch_used > 0); - const auto* read = static_cast(down_mapped); - unsigned outside_written = 0; - for (std::uint32_t i = 0; i < texels; ++i) { - const auto x = std::int32_t(i % width), y = std::int32_t(i / width); - const bool inside = x >= rect.left && x < rect.right && y >= rect.top && y < rect.bottom; - float got = 0; - std::memcpy(&got, read + i * 4, 4); - if (!inside && got != 0.25f) ++outside_written; - expect_depth("I resolve", read, i, inside ? 0.75f : 0.25f); - } - if (outside_written) { - std::fprintf(stderr, "I: %u texels outside the rectangle written\n", outside_written); - return 0; // counted in g_mismatches - } - const unsigned errors = d.validation_errors() - errors_before; - std::printf("I: a 4x D32 MIN resolve of a %dx%d rectangle, %u texels around it kept%s\n", rect.right - rect.left, - rect.bottom - rect.top, texels - unsigned((rect.right - rect.left) * (rect.bottom - rect.top)), - d.validation ? (errors ? ": validation errors" : ", no validation errors") : " (validation off)"); - return 0; -} - -int part_j(vktest::Device& d) { - constexpr std::uint32_t width = 4, height = 2, pitch = texture_data_pitch_alignment; - constexpr VkFormat format = VK_FORMAT_R8G8B8A8_UNORM; - const VkImage image = d.image(format, width, height, 1, 0); - void* upload_data = nullptr; - const VkBuffer upload = d.buffer(pitch * height, VK_BUFFER_USAGE_TRANSFER_SRC_BIT, &upload_data); - void* readback_data = nullptr; - const VkBuffer readback = d.buffer(width * height * 4, VK_BUFFER_USAGE_TRANSFER_DST_BIT, &readback_data); - EXPECT(image && upload && readback); - for (std::uint32_t y = 0; y < height; ++y) - std::memcpy(static_cast(upload_data) + pitch * y, (y ? green : red).data(), 4); - - constexpr ResourceId image_id = 40, upload_id = 41; - ResourceBinding image_binding{}, upload_binding{}; - image_binding.image = image; - image_binding.format = format; - image_binding.width = width; - image_binding.height = height; - upload_binding.buffer = upload; - upload_binding.size = pitch * height; - const auto resolve = [&](ResourceId id) -> const ResourceBinding* { - if (id == image_id) return &image_binding; - if (id == upload_id) return &upload_binding; - return nullptr; - }; - LayoutTracker tracker; - tracker.track(image_id, image_binding, VK_IMAGE_LAYOUT_UNDEFINED); - ReplayFunctions vk{}; - vk.pipeline_barrier = d.fn("vkCmdPipelineBarrier"); - vk.pipeline_barrier2 = d.fn("vkCmdPipelineBarrier2"); - vk.clear_color_image = d.fn("vkCmdClearColorImage"); - vk.copy_buffer = d.fn("vkCmdCopyBuffer"); - vk.copy_image_to_buffer = d.fn("vkCmdCopyImageToBuffer"); - vk.copy_buffer_to_image = d.fn("vkCmdCopyBufferToImage"); - vk.copy_image = d.fn("vkCmdCopyImage"); - - namespace a = d3d12_access; - namespace l = d3d12_layout; - namespace y = d3d12_sync; - const CopyLocation texture{image_id, false, 0, 0, 0, 0, 0, 0}; - const CopyLocation footprint{upload_id, true, 0, 0, 1, height, 1, pitch}; - const CopyBox column{0, 0, 0, 1, height, 1}; - const BarrierSubresourceRange all{all_subresources, 0, 0, 0, 0, 0}; - CommandList first; - EXPECT(first.copy_texture({texture, 2, 0, 0, texture, true, column})); - EXPECT(first.close()); - CommandList list; - EXPECT(list.barrier(TextureBarrier{y::copy, y::copy, a::copy_dest, a::copy_dest, - l::common, l::copy_dest, image_id, all, 0})); - EXPECT(list.copy_texture({texture, 0, 0, 0, footprint, false, {}})); - EXPECT(list.barrier(TextureBarrier{y::copy, y::copy, a::copy_dest, a::copy_source | a::copy_dest, - l::copy_dest, l::common, image_id, all, 0})); - EXPECT(list.copy_texture({texture, 1, 0, 0, texture, true, column})); // touching edges, not overlapping - EXPECT(list.barrier(TextureBarrier{y::copy, y::copy, a::copy_dest, a::copy_source, - l::common, l::copy_source, image_id, all, 0})); - EXPECT(list.close()); - CommandList overlap; - EXPECT(overlap.copy_texture({texture, 1, 0, 0, texture, true, {0, 0, 0, 2, height, 1}})); - EXPECT(overlap.close()); - EXPECT(d.run([&](VkCommandBuffer cb) { - if (replay(overlap, cb, resolve, vk, &tracker) != ReplayResult::invalid_copy) return false; - if (replay(first, cb, resolve, vk, &tracker) != ReplayResult::success || - tracker.layout(image_id, 0) != VK_IMAGE_LAYOUT_GENERAL) return false; - if (replay(list, cb, resolve, vk, &tracker) != ReplayResult::success) return false; - d.read_back(cb, image, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, VK_IMAGE_ASPECT_COLOR_BIT, width, height, 1, - readback, 0); - return true; - })); - const auto* pixels = static_cast(readback_data); - for (std::uint32_t y = 0; y < height; ++y) - for (std::uint32_t x = 0; x < width; ++x) - expect_rgba("J self-copy", pixels, y * width + x, x < 2 ? (y ? green : red) : Rgba{}); - std::printf("J: disjoint same-subresource copies, overlapping copy rejected\n"); - return 0; -} - -} // namespace - -int main() { - vktest::Device device; - const auto status = device.initialize(); - if (status == vktest::DeviceStatus::unavailable) { - std::printf("vk_command_replay_test: no Vulkan device, skipped\n"); - return 77; - } - EXPECT(status == vktest::DeviceStatus::ready); - if (part_a(device) || part_b(device) || part_c(device) || part_d(device) || part_e(device) || part_f(device) || - part_g(device) || part_h(device) || part_i(device) || part_j(device)) - return 1; - if (g_mismatches) return 1; - if (device.validation_errors()) { - std::fprintf(stderr, "%u validation errors\n", device.validation_errors()); - return 1; - } - return 0; -} diff --git a/runtime/test/vk_compute_test.cpp b/runtime/test/vk_compute_test.cpp deleted file mode 100644 index 5ac0bb1bb..000000000 --- a/runtime/test/vk_compute_test.cpp +++ /dev/null @@ -1,690 +0,0 @@ -// Headless Vulkan compute test for translated compute shaders. -// Usage: vk_compute_test cs.spv groups expect [--require-wave64] -// expect = "mirror64": out[g*64 + t] == g*64 + (63 - t) (runtime/test/shaders/cs_lds.asm) -// "workgroup_yz": pass 2x3x4 for groups; check the Y/Z histogram (cs_workgroup_yz.asm) -// "exec64", "wavemask", "bvh": see cs_exec64.asm, cs_wavemask.asm, cs_bvh.asm; anything else prints out[0..7] -// VKC_BENCH=N (env): dispatch N more times after the checked one and print the median / min / max wall time of one -// dispatch (submit to queue idle) as "bench ms: median=.. min=.. max=.. n=..". The buffer is not cleared in between. -// VKC_OUT_WORDS=N (env): make the output buffer at least N words (default groups * 64), so a single group can -// write more than one word per thread. VKC_DUMP= (env): write the whole buffer to after the dispatch. -// VKC_HEAP_INIT= (env): copy the file's bytes to the start of the buffer (Xbox VA 0) after the default fill -// and before the dispatch, so a program can read prepared inputs (a root table, descriptors, data) from the heap. -// The file must fit in the buffer (raise VKC_OUT_WORDS); bytes past it keep the fill. -// --require-wave64: require full 64-wide subgroups (local size X must be a multiple of 64), or exit 77. -// VKC_SUBGROUP_SIZE=N (env): run at N lanes. Where the device can't require a compute subgroup size but N is its -// default subgroupSize (MoltenVK: 32, and requiredSubgroupSizeStages 0), the size is still fixed for a SPIR-V 1.5 -// module (no varying subgroup size); cs_wave_probe.comp then checks, with the test's local size and flags, that every -// subgroup is N lanes wide (by its lane numbers and a ballot), or the test fails (exit 1) without running; N-lane -// subgroups not in invocation order print "not available", as a size that can't be pinned does. -// VKC_SGPRS=w4,w5,... (env): set s4, s5, ... (decimal or 0x hex, up to s31), the user SGPRs after the output V#, -// so a test can take input words (cs_user_sgprs.asm). They are zero otherwise. Same syntax as vk_harness's VKH_SGPRS. -// Contract (docs/design.md): push constants = s0..s31 (128 bytes), heap base lo/hi, code base lo/hi (144 bytes). -// LEONIDA_PC_TAIL_UBO=1 (modules from rdna2spirv.py --pc-tail-ubo): s0..s31 only, the rest at set 1 (vk_pc_tail.h). -// The output buffer is the "heap": Xbox VA 0 maps to its device address, and s[0:3] hold a V# with base 0. -// LEONIDA_VK_VALIDATION=1 (env): run under VK_LAYER_KHRONOS_validation; a validation error fails the run (exit 1), -// so scripts/run_gpu_tests.py reports it. The layer's own variables still apply, for example -// VK_KHRONOS_VALIDATION_GPUAV_ENABLE=1 for GPU-assisted validation of what the translated shader does. -#include "vulkan_loader.h" -#include "vk_device_pick.h" -#include "vk_shader_fma.h" -#include "vk_pc_tail.h" -#include "vk_validation.h" -#include "cs_wave_probe_spv.h" -#include "spirv_capability.h" - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -static PFN_vkGetInstanceProcAddr gipa; -#define CHECK(x) \ - do { \ - VkResult r_ = (x); \ - if (r_ != VK_SUCCESS) { \ - std::fprintf(stderr, "FAILED %s -> %d (line %d)\n", #x, r_, __LINE__); \ - return 1; \ - } \ - } while (0) - -// The same word list parser as vk_harness: decimal or 0x hex, no sign or space, and "1,2," is rejected. -static bool parse_u32(const char*& s, uint32_t& v) { - const bool hex = s[0] == '0' && (s[1] == 'x' || s[1] == 'X'); - const char* digits = hex ? s + 2 : s; - if (!(hex ? std::isxdigit(uint8_t(*digits)) : std::isdigit(uint8_t(*digits)))) return false; - char* end; - unsigned long long x = std::strtoull(digits, &end, hex ? 16 : 10); - if (x > 0xFFFFFFFFull) return false; - v = uint32_t(x); s = end; - return true; -} - -// The module's SPIR-V version and the OpExecutionMode LocalSize of its GLCompute entry point "main", the one the -// pipeline is made from. All zero when there is none (no such entry point, or LocalSizeId), and then the size is -// unknown: nothing that needs it (the subgroup probe, full subgroups) is done. -static uint32_t spirv_local_size(const std::vector& code, uint32_t local[3]) { - local[0] = local[1] = local[2] = 0; - const std::size_t n = code.size() / 4; - std::vector w(n); - if (n) std::memcpy(w.data(), code.data(), n * 4); - if (n < 5 || w[0] != 0x07230203u) return 0; - constexpr uint32_t kOpEntryPoint = 15, kOpExecutionMode = 16, kGLCompute = 5, kLocalSize = 17; - uint32_t main_id = 0; - bool have_main = false; - for (std::size_t i = 5; i < n;) { - const uint32_t len = w[i] >> 16, op = w[i] & 0xFFFFu; - if (!len || i + len > n) break; - // OpEntryPoint model id "name" ...: the name is a nul-terminated string packed little-endian into words. - if (op == kOpEntryPoint && len >= 4 && w[i + 1] == kGLCompute) { - const char* name = reinterpret_cast(&w[i + 3]); - if (std::strncmp(name, "main", 4 * (len - 3)) == 0 && std::memchr(name, 0, 4 * (len - 3))) { - main_id = w[i + 2]; - have_main = true; - } - } - if (op == kOpExecutionMode && len == 6 && have_main && w[i + 1] == main_id && w[i + 2] == kLocalSize) { - local[0] = w[i + 3]; local[1] = w[i + 4]; local[2] = w[i + 5]; - } - i += len; - } - return w[1]; -} - -static bool next_item(const char*& s) { - if (!*s) return true; - return *s++ == ',' && *s; -} - -// VKC_SGPRS: s4, s5, ... in order, at most s31 (s[0:3] stay the output V#). -static bool parse_user_sgprs(const char* s, uint32_t* pc) { - for (uint32_t i = 4; *s; i++) { - if (i == 32 || !parse_u32(s, pc[i]) || !next_item(s)) return false; - } - return true; -} - -static int run(int argc, char** argv) { - const bool require_wave64 = argc == 5 && !std::strcmp(argv[4], "--require-wave64"); - if (argc != 4 && !require_wave64) { - std::fprintf(stderr, "usage: vk_compute_test cs.spv groups expect [--require-wave64]\n"); - return 2; - } - uint32_t pc[36] = {}; - const char* sgprs_env = std::getenv("VKC_SGPRS"); - if (sgprs_env && !parse_user_sgprs(sgprs_env, pc)) { - std::fprintf(stderr, "VKC_SGPRS: expected up to 28 comma-separated words for s4..s31, got \"%s\"\n", sgprs_env); - return 2; - } - const bool workgroup_yz = !std::strcmp(argv[3], "workgroup_yz"); - if (workgroup_yz && std::strcmp(argv[2], "2x3x4")) { - std::fprintf(stderr, "workgroup_yz expects a 2x3x4 dispatch\n"); - return 2; - } - uint32_t groups = 2; - if (!workgroup_yz) { - const char* count = argv[2]; - if (!parse_u32(count, groups) || *count || !groups) { - std::fprintf(stderr, "groups: expected a positive 32-bit workgroup count, got \"%s\"\n", argv[2]); - return 2; - } - } - const uint32_t groups_y = workgroup_yz ? 3u : 1u, groups_z = workgroup_yz ? 4u : 1u; - const uint32_t yz_bins = (groups_y + 1) * (groups_z + 1); - const uint32_t origins = workgroup_yz ? groups * groups_y * groups_z : 0; - const char* out_words_env = std::getenv("VKC_OUT_WORDS"); - const char* dump_path = std::getenv("VKC_DUMP"); - const char* heap_init_path = std::getenv("VKC_HEAP_INIT"); - std::vector heap_init; - if (heap_init_path) { - std::ifstream f(heap_init_path, std::ios::binary); - if (!f) { - std::fprintf(stderr, "VKC_HEAP_INIT: could not read %s\n", heap_init_path); - return 2; - } - heap_init.assign(std::istreambuf_iterator(f), std::istreambuf_iterator()); - } - // VKC_HEAP_FILE=[@]: copy a file into the heap so a shader can read a buffer (a BVH, its - // descriptor blocks and the records) without the test hard-coding it. The offset is a decimal or 0x hex byte - // offset (no octal, sign or spaces); addresses the shader sees are Xbox VAs, i.e. heap offsets, as for every - // other heap buffer here. Two overlaps to keep in mind: "bvh" mode writes its synthetic scene after this copy, - // so a file at 0x100..0x264 is overwritten there, and the output V# starts at heap offset 0, so a file at @0 - // shares bytes with the dispatch's output. - const char* heap_file_env = std::getenv("VKC_HEAP_FILE"); - std::string heap_file_path; - uint64_t heap_file_at = 0; - std::vector heap_file; - if (heap_file_env) { - const std::string spec(heap_file_env); - const std::size_t at_sign = spec.rfind('@'); - heap_file_path = spec.substr(0, at_sign); - if (at_sign != std::string::npos) { - const char* digits = spec.c_str() + at_sign + 1; - const bool hex = digits[0] == '0' && (digits[1] == 'x' || digits[1] == 'X'); - const char* body = hex ? digits + 2 : digits; - const auto first = static_cast(*body); - if (!(hex ? std::isxdigit(first) : std::isdigit(first))) { - std::fprintf(stderr, "VKC_HEAP_FILE: expected [@], got \"%s\"\n", heap_file_env); - return 2; - } - char* end = nullptr; - const unsigned long long parsed = std::strtoull(body, &end, hex ? 16 : 10); - if (end == body || *end || parsed > (1ull << 32) || heap_file_path.empty()) { - std::fprintf(stderr, "VKC_HEAP_FILE: expected [@], got \"%s\"\n", heap_file_env); - return 2; - } - heap_file_at = parsed; - } - std::ifstream hf(heap_file_path, std::ios::binary); - heap_file.assign(std::istreambuf_iterator(hf), {}); - if (heap_file.empty()) { - std::fprintf(stderr, "VKC_HEAP_FILE: cannot read %s\n", heap_file_path.c_str()); - return 2; - } - } - uint32_t out_words = 0; - if (out_words_env) { - char* end; - const unsigned long n = std::strtoul(out_words_env, &end, 10); - if (*out_words_env < '0' || *out_words_env > '9' || *end || n == 0 || n > (1ul << 24)) { - std::fprintf(stderr, "VKC_OUT_WORDS: expected 1..16777216, got \"%s\"\n", out_words_env); - return 2; - } - out_words = uint32_t(n); - } - std::ifstream f(argv[1], std::ios::binary); - std::vector code((std::istreambuf_iterator(f)), {}); - uint32_t local[3]; - const uint32_t spirv_version = spirv_local_size(code, local); - gipa = load_vulkan(); - if (!gipa) return 1; -#define LOADI(name) auto name = reinterpret_cast(gipa(inst, #name)) - VkInstance inst = VK_NULL_HANDLE; - LOADI(vkCreateInstance); - VkApplicationInfo app{VK_STRUCTURE_TYPE_APPLICATION_INFO}; - app.apiVersion = VK_API_VERSION_1_3; - VkInstanceCreateInfo ici{VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO}; - ici.pApplicationInfo = &app; - leonida::vk_test::OptInValidation validation; // LEONIDA_VK_VALIDATION - if (!validation.prepare(gipa, ici)) return 1; - CHECK(vkCreateInstance(&ici, nullptr, &inst)); - CHECK(validation.attach(gipa, inst)); - LOADI(vkEnumeratePhysicalDevices); LOADI(vkGetPhysicalDeviceProperties); LOADI(vkCreateDevice); - LOADI(vkGetPhysicalDeviceProperties2); LOADI(vkGetPhysicalDeviceFeatures2); - LOADI(vkGetPhysicalDeviceQueueFamilyProperties); LOADI(vkGetDeviceProcAddr); - LOADI(vkGetPhysicalDeviceMemoryProperties); - uint32_t n = 0; - vkEnumeratePhysicalDevices(inst, &n, nullptr); - std::vector pds(n); - vkEnumeratePhysicalDevices(inst, &n, pds.data()); - std::vector candidates(pds.size()); - for (std::size_t i = 0; i < pds.size(); ++i) vkGetPhysicalDeviceProperties(pds[i], &candidates[i]); - const std::size_t chosen = leonida::vk_test::pick_device(candidates); - VkPhysicalDevice pd = chosen < pds.size() ? pds[chosen] : VK_NULL_HANDLE; - if (!pd) { - leonida::vk_test::report_no_device(); - return 1; - } - VkPhysicalDeviceProperties props; vkGetPhysicalDeviceProperties(pd, &props); - const uint32_t max_groups_x = props.limits.maxComputeWorkGroupCount[0]; - if (groups > max_groups_x) { - std::fprintf(stderr, "groups: %u exceeds the X dispatch limit of %u on %s\n", - groups, max_groups_x, props.deviceName); - return 2; - } - VkPhysicalDeviceSubgroupSizeControlProperties sgProps{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SUBGROUP_SIZE_CONTROL_PROPERTIES}; - VkPhysicalDeviceSubgroupProperties subgroup{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SUBGROUP_PROPERTIES}; - subgroup.pNext = &sgProps; - VkPhysicalDeviceProperties2 props2{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROPERTIES_2}; - props2.pNext = &subgroup; - vkGetPhysicalDeviceProperties2(pd, &props2); - std::fprintf(stderr, "device: %s (subgroup %u..%u)%s\n", props.deviceName, sgProps.minSubgroupSize, - sgProps.maxSubgroupSize, validation.enabled() ? " (validation on)" : ""); - // 144 push-constant bytes (s0..s31, heap base, code base), or 128 under LEONIDA_PC_TAIL_UBO=1 - // (rdna2spirv.py --pc-tail-ubo). A 128-byte device cannot declare a 144-byte range - // (VUID-VkPushConstantRange-size-00298): exit 77, as vk_harness and vk_texture_test do (D3D-14). - const bool pc_tail = leonida::vk_test::pc_tail_requested(); - const uint32_t pc_bytes = pc_tail ? 128u : 144u; - if (props.limits.maxPushConstantsSize < pc_bytes) { - std::fprintf(stderr, "unsupported: need %u push constant bytes, device has %u\n", pc_bytes, - props.limits.maxPushConstantsSize); - return 77; - } - uint32_t qn = 0; - vkGetPhysicalDeviceQueueFamilyProperties(pd, &qn, nullptr); - std::vector qf(qn); - vkGetPhysicalDeviceQueueFamilyProperties(pd, &qn, qf.data()); - uint32_t qi = 0; - while (qi < qn && !(qf[qi].queueFlags & VK_QUEUE_COMPUTE_BIT)) qi++; - float prio = 1; - VkDeviceQueueCreateInfo qci{VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO}; - qci.queueFamilyIndex = qi; qci.queueCount = 1; qci.pQueuePriorities = &prio; - VkPhysicalDeviceVulkan13Features f13q{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_3_FEATURES}; - VkPhysicalDeviceVulkan12Features f12q{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_2_FEATURES}; - f12q.pNext = &f13q; - VkPhysicalDeviceFeatures2 f2q{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2}; - f2q.pNext = &f12q; - vkGetPhysicalDeviceFeatures2(pd, &f2q); - const char* sg_env = std::getenv("VKC_SUBGROUP_SIZE"); - const uint32_t req_sg = require_wave64 ? 64u : (sg_env ? uint32_t(std::atoi(sg_env)) : 0u); - const bool can_request_size = req_sg > 0 && f13q.subgroupSizeControl && - req_sg >= sgProps.minSubgroupSize && req_sg <= sgProps.maxSubgroupSize && - (sgProps.requiredSubgroupSizeStages & VK_SHADER_STAGE_COMPUTE_BIT); - if (require_wave64 && (!f13q.computeFullSubgroups || (!can_request_size && subgroup.subgroupSize != 64))) { - std::fprintf(stderr, "full 64-wide compute subgroups unavailable\n"); - return 77; - } - // shaderFloat64 and shaderInt64 only for a module that declares them: SHADER-423's address pairs need no - // 64-bit integers (TEST-468). - const bool needs_float64 = leonida::vk_test::spirv_declares_capability(code.data(), code.size(), 10); // Float64 - if (needs_float64 && !f2q.features.shaderFloat64) { - std::fprintf(stderr, "unsupported: %s uses Float64 and the device has no shaderFloat64\n", argv[1]); - return 77; - } - // A size the device can't require but runs anyway: one min..max range (fixed), or its default subgroupSize in a - // module below SPIR-V 1.6 (Vulkan "Varying Subgroup Size": SubgroupSize then always equals subgroupSize), which - // cs_wave_probe checks before the test runs (observed). Full subgroups where local size X is a multiple of - // maxSubgroupSize (VUID-VkPipelineShaderStageCreateInfo-flags-02759). - const bool fixed = req_sg && sgProps.minSubgroupSize == sgProps.maxSubgroupSize && subgroup.subgroupSize == req_sg; - const uint32_t local_total = local[0] * local[1] * local[2]; - // The probe itself needs subgroup operations in compute: the basic built-ins and a ballot. - const bool probe_runs = (subgroup.supportedStages & VK_SHADER_STAGE_COMPUTE_BIT) && - (subgroup.supportedOperations & VK_SUBGROUP_FEATURE_BASIC_BIT) && - (subgroup.supportedOperations & VK_SUBGROUP_FEATURE_BALLOT_BIT); - const bool observed = req_sg && !require_wave64 && !can_request_size && !fixed && probe_runs && - subgroup.subgroupSize == req_sg && spirv_version && spirv_version < 0x00010600u && - local_total && local_total <= 1024; - const bool observed_full = observed && f13q.computeFullSubgroups && local[0] % sgProps.maxSubgroupSize == 0; - const bool int64 = leonida::vk_test::needs_shader_int64(code.data(), code.size()); - if (int64 && !f2q.features.shaderInt64) { - std::fprintf(stderr, "unsupported: %s declares Int64 and the device has no shaderInt64\n", argv[1]); - return 77; - } - // 64-bit atomics: the translator's are buffer atomics (rdna2spirv.py --int64-atomics, *_atomic_swap_x2 on - // PhysicalStorageBuffer memory), which need shaderBufferInt64Atomics. Without the check a device that lacks it - // (MoltenVK) failed the pipeline instead of reporting 77. A shared-memory one gets shaderSharedInt64Atomics too - // where the device has it. - const bool int64_atomics = leonida::vk_test::declares_capability(code.data(), code.size(), - leonida::vk_test::spirv_capability_int64_atomics); - if (int64_atomics && !f12q.shaderBufferInt64Atomics) { - std::fprintf(stderr, "unsupported: %s declares Int64Atomics and the device has no shaderBufferInt64Atomics\n", - argv[1]); - return 77; - } - VkPhysicalDeviceVulkan13Features f13{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_3_FEATURES}; - VkPhysicalDeviceVulkan12Features f12{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_2_FEATURES}; - f12.bufferDeviceAddress = VK_TRUE; - f12.shaderBufferInt64Atomics = int64_atomics ? VK_TRUE : VK_FALSE; - f12.shaderSharedInt64Atomics = int64_atomics && f12q.shaderSharedInt64Atomics ? VK_TRUE : VK_FALSE; - if (f13q.subgroupSizeControl || require_wave64) { - f13.subgroupSizeControl = f13q.subgroupSizeControl; - f13.computeFullSubgroups = require_wave64 || observed_full ? VK_TRUE : VK_FALSE; - f12.pNext = &f13; - } - VkPhysicalDeviceFeatures2 f2{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2}; - f2.features.shaderInt64 = int64 ? VK_TRUE : VK_FALSE; - f2.features.shaderFloat64 = needs_float64 ? VK_TRUE : VK_FALSE; - f2.pNext = &f12; - // OpFmaKHR (rdna2spirv.py --fma khr): VK_KHR_shader_fma, when the device has it. - leonida::vk_test::ShaderFma fma; - fma.query(gipa, inst, pd); - fma.link_after(&f2); - const char* fma_extension = fma.extension(); - VkDeviceCreateInfo dci{VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO}; - dci.queueCreateInfoCount = 1; dci.pQueueCreateInfos = &qci; dci.pNext = &f2; - if (fma.supported()) { dci.enabledExtensionCount = 1; dci.ppEnabledExtensionNames = &fma_extension; } - VkDevice dev; - CHECK(vkCreateDevice(pd, &dci, nullptr, &dev)); -#define LOADD(name) auto name = reinterpret_cast(vkGetDeviceProcAddr(dev, #name)) - LOADD(vkGetDeviceQueue); LOADD(vkCreateBuffer); LOADD(vkGetBufferMemoryRequirements); LOADD(vkAllocateMemory); - LOADD(vkBindBufferMemory); LOADD(vkMapMemory); LOADD(vkGetBufferDeviceAddress); LOADD(vkCreateShaderModule); - LOADD(vkCreatePipelineLayout); LOADD(vkCreateComputePipelines); LOADD(vkCreateCommandPool); - LOADD(vkAllocateCommandBuffers); LOADD(vkBeginCommandBuffer); LOADD(vkCmdBindPipeline); - LOADD(vkCmdPushConstants); LOADD(vkCmdDispatch); LOADD(vkEndCommandBuffer); LOADD(vkQueueSubmit); - LOADD(vkQueueWaitIdle); LOADD(vkCmdPipelineBarrier); LOADD(vkCmdDispatchBase); LOADD(vkCmdBindDescriptorSets); - VkQueue q; vkGetDeviceQueue(dev, qi, 0, &q); - - // Output buffer = heap. Host-visible so the result can be read back directly. - VkDeviceSize words = workgroup_yz ? yz_bins * (1 + origins) : VkDeviceSize(groups) * 64; - if (out_words > words) words = out_words; - // The heap file may need more than the dispatch's own output words; round its end up to a word. - if (!heap_file.empty()) { - const VkDeviceSize need = VkDeviceSize(heap_file_at + heap_file.size() + 3) / 4; - if (need > words) words = need; - } - // "bvh" writes its nodes at heap offsets 0x100 to 0x264 below, past the 256 bytes one group's 64 words give: the - // shader then read them through the device address outside the buffer (VUID-RuntimeSpirv-PhysicalStorageBuffer64-11819). - const bool bvh = !std::strcmp(argv[3], "bvh"); - if (bvh && words < 0x280 / sizeof(uint32_t)) words = 0x280 / sizeof(uint32_t); - const VkDeviceSize bytes = words * sizeof(uint32_t); - VkBufferCreateInfo bci{VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO}; - bci.size = bytes; - bci.usage = VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT; - VkBuffer buf; CHECK(vkCreateBuffer(dev, &bci, nullptr, &buf)); - VkMemoryRequirements mr; vkGetBufferMemoryRequirements(dev, buf, &mr); - VkPhysicalDeviceMemoryProperties mp; vkGetPhysicalDeviceMemoryProperties(pd, &mp); - uint32_t mt = 0; - for (; mt < mp.memoryTypeCount; mt++) - if ((mr.memoryTypeBits >> mt & 1) && (mp.memoryTypes[mt].propertyFlags & - (VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT)) == - (VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT)) break; - VkMemoryAllocateFlagsInfo maf{VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_FLAGS_INFO}; - maf.flags = VK_MEMORY_ALLOCATE_DEVICE_ADDRESS_BIT; - VkMemoryAllocateInfo mai{VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO}; - mai.allocationSize = mr.size; mai.memoryTypeIndex = mt; mai.pNext = &maf; - VkDeviceMemory mem; CHECK(vkAllocateMemory(dev, &mai, nullptr, &mem)); - CHECK(vkBindBufferMemory(dev, buf, mem, 0)); - void* map; CHECK(vkMapMemory(dev, mem, 0, bytes, 0, &map)); - std::memset(map, workgroup_yz || !std::strcmp(argv[3], "exec64") ? 0 : 0xEE, size_t(bytes)); - if (heap_init_path) { - if (heap_init.size() > size_t(bytes)) { - std::fprintf(stderr, "VKC_HEAP_INIT: %s is %zu bytes, the buffer %llu (raise VKC_OUT_WORDS)\n", - heap_init_path, heap_init.size(), static_cast(bytes)); - return 2; - } - if (!heap_init.empty()) std::memcpy(map, heap_init.data(), heap_init.size()); - } - if (!heap_file.empty()) { - std::memcpy(static_cast(map) + heap_file_at, heap_file.data(), heap_file.size()); - std::printf("heap file: %s at 0x%llx (%zu bytes)\n", heap_file_path.c_str(), - static_cast(heap_file_at), heap_file.size()); - } - if (!std::strcmp(argv[3], "bvh")) { - // AMD-format BVH in the heap (runtime/test/shaders/cs_bvh.asm): box32 root at 0x100 whose children are a - // triangle at z=10 (node 0x40, addr 0x200), a triangle at z=5 (node 0x48, addr 0x240), a box the ray - // misses, and a box with a NaN min.x that RDNA2 still enters at t = 0 (SHADER-650). Node id = address >> 3 | type. - auto f32 = [&](uint32_t at, float v) { std::memcpy(static_cast(map) + at, &v, 4); }; - auto u32 = [&](uint32_t at, uint32_t v) { std::memcpy(static_cast(map) + at, &v, 4); }; - u32(0x100, 0x40); u32(0x104, 0x48); u32(0x108, 0x60); u32(0x10C, 0x68); - const float boxes[4][6] = {{0, 0, 10, 1, 1, 10}, {0, 0, 5, 1, 1, 5}, {5, 0, 0, 6, 1, 1}, {NAN, 0, 0, 1, 1, 1}}; - for (int i = 0; i < 4; i++) for (int c = 0; c < 6; c++) f32(0x110 + 24 * i + 4 * c, boxes[i][c]); - const float tri[2][9] = {{0, 0, 10, 1, 0, 10, 0, 1, 10}, {0, 0, 5, 1, 0, 5, 0, 1, 5}}; - for (int t = 0; t < 2; t++) for (int c = 0; c < 9; c++) f32(0x200 + 0x40 * t + 4 * c, tri[t][c]); - // Triangle-ID word at node +60: byte 0 (TRI0) = 0x09 returns vertex 1's and vertex 2's weights, what a - // builder writes (AMD GPURT WriteTriangleIdField); the translator reads it since the remap fix. - for (int t = 0; t < 2; t++) u32(0x200 + 0x40 * t + 60, 0x09); - } - VkBufferDeviceAddressInfo bai{VK_STRUCTURE_TYPE_BUFFER_DEVICE_ADDRESS_INFO}; - bai.buffer = buf; - const uint64_t heap = vkGetBufferDeviceAddress(dev, &bai); - - if (!fma.accepts(code.data(), code.size(), argv[1])) return 77; - VkShaderModuleCreateInfo smi{VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO}; - smi.codeSize = code.size(); smi.pCode = reinterpret_cast(code.data()); - VkShaderModule sm; CHECK(vkCreateShaderModule(dev, &smi, nullptr, &sm)); - // 144 push-constant bytes: s0..s31, heap base, code base. With LEONIDA_PC_TAIL_UBO=1 (rdna2spirv.py - // --pc-tail-ubo) only s0..s31; the tail, if the module reads it, is a uniform block at set 1 (vk_pc_tail.h), one - // slot for the dispatch and one per workgroup_yz origin. - leonida::vk_test::PcTail tail; - const bool tail_block = pc_tail && - leonida::vk_test::spirv_declares_set(code.data(), code.size(), leonida::vk_test::pc_tail_set); - if (tail_block && !tail.create(vkGetDeviceProcAddr, dev, mp, props.limits.minUniformBufferOffsetAlignment, - VK_SHADER_STAGE_COMPUTE_BIT, 1 + origins)) { - std::fprintf(stderr, "FAILED creating the --pc-tail-ubo block\n"); - return 1; - } - VkPushConstantRange pcr{VK_SHADER_STAGE_COMPUTE_BIT, 0, pc_bytes}; - VkPipelineLayoutCreateInfo pli{VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO}; - pli.pushConstantRangeCount = 1; pli.pPushConstantRanges = &pcr; - const VkDescriptorSetLayout tail_layouts[] = {tail.empty_layout, tail.set_layout}; - if (tail_block) { pli.setLayoutCount = 2; pli.pSetLayouts = tail_layouts; } - VkPipelineLayout pl; CHECK(vkCreatePipelineLayout(dev, &pli, nullptr, &pl)); - VkComputePipelineCreateInfo cpi{VK_STRUCTURE_TYPE_COMPUTE_PIPELINE_CREATE_INFO}; - if (workgroup_yz) cpi.flags |= VK_PIPELINE_CREATE_DISPATCH_BASE_BIT; - cpi.stage = {VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO}; - cpi.stage.stage = VK_SHADER_STAGE_COMPUTE_BIT; cpi.stage.module = sm; cpi.stage.pName = "main"; - VkPipelineShaderStageRequiredSubgroupSizeCreateInfo reqSg{ - VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_REQUIRED_SUBGROUP_SIZE_CREATE_INFO}; - reqSg.requiredSubgroupSize = req_sg; - if (can_request_size) - cpi.stage.pNext = &reqSg; - if (require_wave64 || observed_full) - cpi.stage.flags = VK_PIPELINE_SHADER_STAGE_CREATE_REQUIRE_FULL_SUBGROUPS_BIT; - cpi.layout = pl; - VkPipeline pipe; CHECK(vkCreateComputePipelines(dev, VK_NULL_HANDLE, 1, &cpi, nullptr, &pipe)); - if (require_wave64) std::printf("compute subgroup size: 64\n"); - else if (req_sg) { - // VKC_SUBGROUP_SIZE: say whether the pipeline really runs at that size, so a runner can skip a test the device - // can't pin instead of judging words from whatever size the driver picked (#774). - if (can_request_size || fixed) std::printf("compute subgroup size: %u\n", req_sg); - else if (!observed) std::printf("compute subgroup size: %u not available\n", req_sg); - } - - pc[0] = 0; pc[1] = 0; pc[2] = 0xFFFFFFFFu; pc[3] = 0x31016FACu; // V#: base 0, stride 0, num_records max, OOB_SELECT 3 (raw) - pc[32] = uint32_t(heap); pc[33] = uint32_t(heap >> 32); // heap base - VkCommandPoolCreateInfo cpci{VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO}; - cpci.queueFamilyIndex = qi; - VkCommandPool pool; CHECK(vkCreateCommandPool(dev, &cpci, nullptr, &pool)); - VkCommandBufferAllocateInfo cai{VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO}; - cai.commandPool = pool; cai.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY; cai.commandBufferCount = 1; - VkCommandBuffer cmd; CHECK(vkAllocateCommandBuffers(dev, &cai, &cmd)); - if (observed) { - // cs_wave_probe with the test's local size and flags, one group, four words per invocation in its own buffer. - VkBufferCreateInfo pbi{VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO}; - pbi.size = VkDeviceSize(local_total) * 16; - pbi.usage = VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT; - VkBuffer pbuf; CHECK(vkCreateBuffer(dev, &pbi, nullptr, &pbuf)); - VkMemoryRequirements pmr; vkGetBufferMemoryRequirements(dev, pbuf, &pmr); - VkMemoryAllocateInfo pmai = mai; - pmai.allocationSize = pmr.size; - VkDeviceMemory pmem; CHECK(vkAllocateMemory(dev, &pmai, nullptr, &pmem)); - CHECK(vkBindBufferMemory(dev, pbuf, pmem, 0)); - void* pmap; CHECK(vkMapMemory(dev, pmem, 0, pbi.size, 0, &pmap)); - std::memset(pmap, 0xEE, size_t(pbi.size)); - VkBufferDeviceAddressInfo pbai{VK_STRUCTURE_TYPE_BUFFER_DEVICE_ADDRESS_INFO}; - pbai.buffer = pbuf; - const uint64_t paddr = vkGetBufferDeviceAddress(dev, &pbai); - VkShaderModuleCreateInfo psmi{VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO}; - psmi.codeSize = sizeof(leonida::vk_test::cs_wave_probe_spirv); - psmi.pCode = leonida::vk_test::cs_wave_probe_spirv; - VkShaderModule psm; CHECK(vkCreateShaderModule(dev, &psmi, nullptr, &psm)); - const VkSpecializationMapEntry entries[3] = {{0, 0, 4}, {1, 4, 4}, {2, 8, 4}}; - const VkSpecializationInfo spec{3, entries, sizeof(local), local}; - VkComputePipelineCreateInfo pcpi = cpi; - pcpi.flags = 0; - pcpi.stage.module = psm; - pcpi.stage.pSpecializationInfo = &spec; - VkPipeline ppipe; CHECK(vkCreateComputePipelines(dev, VK_NULL_HANDLE, 1, &pcpi, nullptr, &ppipe)); - const uint32_t ppc[2] = {uint32_t(paddr), uint32_t(paddr >> 32)}; // cs_wave_probe's buffer address - VkCommandBuffer pcmd; CHECK(vkAllocateCommandBuffers(dev, &cai, &pcmd)); - VkCommandBufferBeginInfo pcbi{VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO}; - CHECK(vkBeginCommandBuffer(pcmd, &pcbi)); - vkCmdBindPipeline(pcmd, VK_PIPELINE_BIND_POINT_COMPUTE, ppipe); - vkCmdPushConstants(pcmd, pl, VK_SHADER_STAGE_COMPUTE_BIT, 0, sizeof(ppc), ppc); - vkCmdDispatch(pcmd, 1, 1, 1); - VkMemoryBarrier pread{VK_STRUCTURE_TYPE_MEMORY_BARRIER}; - pread.srcAccessMask = VK_ACCESS_SHADER_WRITE_BIT; - pread.dstAccessMask = VK_ACCESS_HOST_READ_BIT; - vkCmdPipelineBarrier(pcmd, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, VK_PIPELINE_STAGE_HOST_BIT, 0, - 1, &pread, 0, nullptr, 0, nullptr); - CHECK(vkEndCommandBuffer(pcmd)); - VkSubmitInfo psi{VK_STRUCTURE_TYPE_SUBMIT_INFO}; - psi.commandBufferCount = 1; psi.pCommandBuffers = &pcmd; - CHECK(vkQueueSubmit(q, 1, &psi, VK_NULL_HANDLE)); - CHECK(vkQueueWaitIdle(q)); - // Width first, from what each invocation reports: every subgroup has N lanes (one may have the rest of a - // group that isn't a multiple of N), each lane once, and a ballot of the subgroup counts them all. A wrong - // width fails the test. Then the order: the translator takes a wave32 lane as LocalInvocationIndex % N, so - // invocation l must be lane l % N of subgroup l / N. Vulkan doesn't promise that mapping; where it differs, - // the size is reported as not available, as on a device that can't give N at all (the runners skip). - const uint32_t* pw = static_cast(pmap); - const uint32_t subgroups = (local_total + req_sg - 1) / req_sg, tail = local_total % req_sg; - std::vector count(subgroups, 0), seen(std::size_t(subgroups) * req_sg, 0); - std::vector bad(local_total, false); - for (uint32_t l = 0; l < local_total; l++) { - const uint32_t* w = pw + 4 * l; - if (w[0] == req_sg && w[2] < subgroups && w[1] < req_sg && !seen[std::size_t(w[2]) * req_sg + w[1]]++) - count[w[2]]++; - else - bad[l] = true; - } - uint32_t wrong = 0, first = 0, misplaced = 0, first_misplaced = 0, partial = 0; - for (uint32_t c : count) - if (c != req_sg) partial++; - for (uint32_t l = 0; l < local_total; l++) { - const uint32_t* w = pw + 4 * l; - if (bad[l] || w[3] != count[w[2]]) { - if (!wrong++) first = l; - } - if ((w[1] != l % req_sg || w[2] != l / req_sg) && !misplaced++) first_misplaced = l; - } - if (!wrong && partial > (tail ? 1u : 0u)) wrong = partial; // e.g. two half-filled subgroups - if (wrong) { - const uint32_t* w = pw + 4 * first; - std::printf("compute subgroup size: %u observed wrong in %u of %u invocations; invocation %u has " - "SubgroupSize %u, lane %u, subgroup %u, a ballot of %u lanes\n", req_sg, wrong, local_total, - first, w[0], w[1], w[2], w[3]); - return 1; - } - if (misplaced) { - const uint32_t* w = pw + 4 * first_misplaced; - std::fprintf(stderr, "%u-lane subgroups, but not in invocation order: invocation %u is lane %u of " - "subgroup %u\n", req_sg, first_misplaced, w[1], w[2]); - // As where the size can't be pinned at all: say so, run the test, and let the runner skip it. - std::printf("compute subgroup size: %u not available\n", req_sg); - } else { - std::printf("compute subgroup size: %u (observed: all %u invocations of a %ux%ux%u group%s)\n", req_sg, - local_total, local[0], local[1], local[2], observed_full ? ", full subgroups" : ""); - } - } - VkCommandBufferBeginInfo cbi{VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO}; - CHECK(vkBeginCommandBuffer(cmd, &cbi)); - vkCmdBindPipeline(cmd, VK_PIPELINE_BIND_POINT_COMPUTE, pipe); - vkCmdPushConstants(cmd, pl, VK_SHADER_STAGE_COMPUTE_BIT, 0, pc_bytes, pc); - auto bind_tail = [&](uint32_t slot) { - if (!tail_block) return; - tail.write(slot, pc, 4); - const uint32_t offset = tail.offset(slot); - vkCmdBindDescriptorSets(cmd, VK_PIPELINE_BIND_POINT_COMPUTE, pl, leonida::vk_test::pc_tail_set, 1, &tail.set, - 1, &offset); - }; - bind_tail(0); - vkCmdDispatch(cmd, groups, groups_y, groups_z); - // A permutation within one axis can leave the full-grid histogram unchanged. Dispatch one group at - // each known origin into its own histogram, selected by the host independently of the shader's SGPRs. - for (uint32_t g = 0; g < origins; ++g) { - const uint64_t base = heap + (g + 1) * yz_bins * sizeof(uint32_t); - const uint32_t address[] = {uint32_t(base), uint32_t(base >> 32)}; - if (pc_tail) { - pc[32] = address[0]; pc[33] = address[1]; // the heap base is the tail's dwords 0..1 - bind_tail(g + 1); - } else { - vkCmdPushConstants(cmd, pl, VK_SHADER_STAGE_COMPUTE_BIT, 32 * sizeof(uint32_t), sizeof(address), address); - } - vkCmdDispatchBase(cmd, g % groups, (g / groups) % groups_y, g / (groups * groups_y), 1, 1, 1); - } - VkMemoryBarrier readback{VK_STRUCTURE_TYPE_MEMORY_BARRIER}; - readback.srcAccessMask = VK_ACCESS_SHADER_WRITE_BIT; - readback.dstAccessMask = VK_ACCESS_HOST_READ_BIT; - vkCmdPipelineBarrier(cmd, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, VK_PIPELINE_STAGE_HOST_BIT, 0, - 1, &readback, 0, nullptr, 0, nullptr); - CHECK(vkEndCommandBuffer(cmd)); - VkSubmitInfo si{VK_STRUCTURE_TYPE_SUBMIT_INFO}; - si.commandBufferCount = 1; si.pCommandBuffers = &cmd; - CHECK(vkQueueSubmit(q, 1, &si, VK_NULL_HANDLE)); - CHECK(vkQueueWaitIdle(q)); - if (const char* b = std::getenv("VKC_BENCH")) { - std::vector ms; - for (int i = 0, n = std::atoi(b); i < n; i++) { - auto t0 = std::chrono::steady_clock::now(); - CHECK(vkQueueSubmit(q, 1, &si, VK_NULL_HANDLE)); - CHECK(vkQueueWaitIdle(q)); - ms.push_back(std::chrono::duration(std::chrono::steady_clock::now() - t0).count()); - } - if (!ms.empty()) { - std::sort(ms.begin(), ms.end()); - std::printf("bench ms: median=%.3f min=%.3f max=%.3f n=%zu\n", ms[ms.size() / 2], ms.front(), ms.back(), ms.size()); - } - uint32_t h = 2166136261u; // FNV-1a of the whole output buffer, to compare configurations - for (VkDeviceSize i = 0; i < bytes; i++) h = (h ^ static_cast(map)[i]) * 16777619u; - std::printf("bench out fnv1a: %08x\n", h); - } - - if (dump_path) { - std::ofstream dump(dump_path, std::ios::binary); - dump.write(static_cast(map), std::streamsize(bytes)); - dump.close(); - if (dump.fail()) { - std::fprintf(stderr, "VKC_DUMP: could not write %s\n", dump_path); - return 1; - } - } - - const uint32_t* out = static_cast(map); - uint32_t bad = 0, first_bad = ~0u; - if (workgroup_yz) { - // X is disabled in RSRC2. Both X groups must contribute to each valid (Y,Z) bin. - // The last column and row catch out-of-range register values without indexing past the buffer. - for (uint32_t z = 0; z <= groups_z; ++z) { - for (uint32_t y = 0; y <= groups_y; ++y) { - const uint32_t want = y < groups_y && z < groups_z ? groups : 0; - const uint32_t got = out[z * (groups_y + 1) + y]; - if (got != want) { - std::fprintf(stderr, "(Y=%u, Z=%u): got %u, expected %u\n", y, z, got, want); - ++bad; - } - } - } - std::printf("2x3x4 workgroup Y/Z: %u mismatches\n", bad); - uint32_t wrong_origins = 0; - for (uint32_t g = 0; g < origins; ++g) { - const uint32_t y = (g / groups) % groups_y, z = g / (groups * groups_y); - const uint32_t* histogram = out + (g + 1) * yz_bins; - for (uint32_t bin = 0; bin < yz_bins; ++bin) { - const uint32_t want = bin == z * (groups_y + 1) + y ? 1u : 0u; - if (histogram[bin] != want) { - std::fprintf(stderr, "origin (%u,%u,%u), bin %u: got %u, expected %u\n", - g % groups, y, z, bin, histogram[bin], want); - ++wrong_origins; - break; - } - } - } - std::printf("single-group origins: %u/%u matched\n", origins - wrong_origins, origins); - return bad || wrong_origins ? 1 : 0; - } - if (!std::strcmp(argv[3], "mirror64")) { - for (uint32_t g = 0; g < groups; g++) - for (uint32_t t = 0; t < 64; t++) { - uint32_t want = g * 64 + (63 - t), got = out[g * 64 + t]; - if (got != want) { if (!bad) first_bad = g * 64 + t; bad++; } - } - } - if (!std::strcmp(argv[3], "exec64")) { // runtime/test/shaders/cs_exec64.asm - for (uint32_t g = 0; g < groups; g++) - for (uint32_t t = 0; t < 64; t++) { - uint32_t want = (t >= 16 && t < 48) ? 7u : 0u, got = out[g * 64 + t]; - if (got != want) { if (!bad) first_bad = g * 64 + t; bad++; } - } - } - if (!std::strcmp(argv[3], "wavemask")) { // runtime/test/shaders/cs_wavemask.asm - for (uint32_t g = 0; g < groups; g++) - for (uint32_t t = 0; t < 64; t++) { - // lanes 16-47: on again after the parked mask (0x80) and after the one through a VGPR (0x40), - // plus how many set lanes are below this one - uint32_t top = (t >= 16 && t < 48) ? 0xc0u + t - 16 : 0; - uint32_t want = 65u | 16u << 8 | 8u << 16 | top << 24, got = out[g * 64 + t]; - if (got != want) { if (!bad) first_bad = g * 64 + t; bad++; } - } - } - if (!std::strcmp(argv[3], "bvh")) { - const uint32_t want[8] = {0x68, 0x48, 0x40, 0xFFFFFFFFu, 0xC1200000u, 0xBF800000u, 0xBE800000u, 0xBE800000u}; - for (int i = 0; i < 8; i++) if (out[i] != want[i]) { if (!bad) first_bad = i; bad++; } - std::printf("bvh out = %08x %08x %08x %08x | %08x %08x %08x %08x\n", out[0], out[1], out[2], out[3], out[4], out[5], out[6], out[7]); - } - std::printf("%u groups x 64: %u mismatches", groups, bad); - if (bad) std::printf(" (first at %u: got 0x%08x)", first_bad, out[first_bad]); - std::printf("\nout[0..7] = %u %u %u %u %u %u %u %u\n", out[0], out[1], out[2], out[3], out[4], out[5], out[6], out[7]); - return bad ? 1 : 0; -} - -int main(int argc, char** argv) { - // GPU-assisted validation reports what the shader did when the queue finishes, after the words were judged. - return leonida::vk_test::OptInValidation::exit_status(run(argc, argv)); -} diff --git a/runtime/test/vk_descriptor_bench.cpp b/runtime/test/vk_descriptor_bench.cpp deleted file mode 100644 index 3dd179268..000000000 --- a/runtime/test/vk_descriptor_bench.cpp +++ /dev/null @@ -1,2291 +0,0 @@ -// GPU micro-benchmark for the descriptor hash table (set 0, binding 2 contract, D3D-56). -// Measures T# and S# hash-table lookups at 1k, 10k, and 100k entries across wave-uniform and lane-divergent -// access patterns, hits and misses, and buffer memory placements (DEVICE_LOCAL vs HOST_VISIBLE vs ReBAR). -// -// The compute SPIR-V modules are built in memory using the exact FNV-1a + 8-slot linear probe loop emitted by -// tools/rdna2spirv.py (desc_probe), so this tool has no glslangValidator build dependency and checks every -// dispatch against CPU DescriptorTable::lookup() before timing. -// -// Usage: -// vk_descriptor_bench [--sizes 1000,10000,100000] [--groups 4096] [--iters 64] [--reps 25] [--warmup 5] [--warmup-ms 300] -// [--memory all|device|host|rebar] [--device N] [--list-devices] [--quick] [--csv] -// [--dump-spv PREFIX] [--self-test] -// LEONIDA_VK_VALIDATION=1 enables VK_LAYER_KHRONOS_validation; any validation error fails the run. -#define VK_NO_PROTOTYPES -#include "vulkan_loader.h" -#include "vk_device_pick.h" -#include "../src/descriptor_table.h" - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#define CHECK_VK(expr) \ - do { \ - const VkResult vk_res_ = (expr); \ - if (vk_res_ != VK_SUCCESS) { \ - std::fprintf(stderr, "FAILED %s -> %d (line %d)\n", #expr, int(vk_res_), __LINE__); \ - return 1; \ - } \ - } while (0) - -namespace { - -using namespace leonida; - -constexpr int kUnsupportedExit = 77; -constexpr std::uint32_t kWorkgroupSize = 64; -unsigned g_validation_errors = 0; - -VKAPI_ATTR VkBool32 VKAPI_CALL on_debug_message(VkDebugUtilsMessageSeverityFlagBitsEXT severity, - VkDebugUtilsMessageTypeFlagsEXT types, - const VkDebugUtilsMessengerCallbackDataEXT* data, void*) { - if ((severity & VK_DEBUG_UTILS_MESSAGE_SEVERITY_ERROR_BIT_EXT) && - (types & VK_DEBUG_UTILS_MESSAGE_TYPE_VALIDATION_BIT_EXT)) { - ++g_validation_errors; - } - std::fprintf(stderr, "validation: %s\n", data && data->pMessage ? data->pMessage : "(no message)"); - return VK_FALSE; -} - -// ---- SPIR-V 1.3 binary builder matching tools/rdna2spirv.py desc_probe ---- - -namespace spv_op { -constexpr std::uint32_t kMagic = 0x07230203u; -constexpr std::uint32_t kVersion13 = 0x00010300u; - -constexpr std::uint32_t kCapShader = 1u; -constexpr std::uint32_t kAddrLogical = 0u; -constexpr std::uint32_t kMemGlsl450 = 1u; -constexpr std::uint32_t kExecGLCompute = 5u; -constexpr std::uint32_t kExecModeLocalSize = 17u; - -constexpr std::uint32_t kScInput = 1u; -constexpr std::uint32_t kScFunction = 7u; -constexpr std::uint32_t kScPushConstant = 9u; -constexpr std::uint32_t kScStorageBuffer = 12u; - -constexpr std::uint32_t kDecBlock = 2u; -constexpr std::uint32_t kDecArrayStride = 6u; -constexpr std::uint32_t kDecBuiltIn = 11u; -constexpr std::uint32_t kDecNonWritable = 24u; -constexpr std::uint32_t kDecNonReadable = 25u; -constexpr std::uint32_t kDecBinding = 33u; -constexpr std::uint32_t kDecDescriptorSet = 34u; -constexpr std::uint32_t kDecOffset = 35u; -constexpr std::uint32_t kBuiltInGlobalInvocationId = 28u; - -constexpr std::uint32_t kOpMemoryModel = 14u; -constexpr std::uint32_t kOpEntryPoint = 15u; -constexpr std::uint32_t kOpExecutionMode = 16u; -constexpr std::uint32_t kOpCapability = 17u; -constexpr std::uint32_t kOpTypeVoid = 19u; -constexpr std::uint32_t kOpTypeBool = 20u; -constexpr std::uint32_t kOpTypeInt = 21u; -constexpr std::uint32_t kOpTypeVector = 23u; -constexpr std::uint32_t kOpTypeRuntimeArray = 29u; -constexpr std::uint32_t kOpTypeStruct = 30u; -constexpr std::uint32_t kOpTypePointer = 32u; -constexpr std::uint32_t kOpTypeFunction = 33u; -constexpr std::uint32_t kOpConstantTrue = 41u; -constexpr std::uint32_t kOpConstant = 43u; -constexpr std::uint32_t kOpFunction = 54u; -constexpr std::uint32_t kOpFunctionParameter = 55u; -constexpr std::uint32_t kOpFunctionEnd = 56u; -constexpr std::uint32_t kOpFunctionCall = 57u; -constexpr std::uint32_t kOpVariable = 59u; -constexpr std::uint32_t kOpLoad = 61u; -constexpr std::uint32_t kOpStore = 62u; -constexpr std::uint32_t kOpAccessChain = 65u; -constexpr std::uint32_t kOpDecorate = 71u; -constexpr std::uint32_t kOpMemberDecorate = 72u; -constexpr std::uint32_t kOpIAdd = 128u; -constexpr std::uint32_t kOpIMul = 132u; -constexpr std::uint32_t kOpLogicalAnd = 167u; -constexpr std::uint32_t kOpIEqual = 170u; -constexpr std::uint32_t kOpULessThan = 176u; -constexpr std::uint32_t kOpShiftRightLogical = 194u; -constexpr std::uint32_t kOpShiftLeftLogical = 196u; -constexpr std::uint32_t kOpBitwiseXor = 198u; -constexpr std::uint32_t kOpBitwiseAnd = 199u; -constexpr std::uint32_t kOpLoopMerge = 246u; -constexpr std::uint32_t kOpSelectionMerge = 247u; -constexpr std::uint32_t kOpLabel = 248u; -constexpr std::uint32_t kOpBranch = 249u; -constexpr std::uint32_t kOpBranchConditional = 250u; -constexpr std::uint32_t kOpReturn = 253u; -constexpr std::uint32_t kOpReturnValue = 254u; -} // namespace spv_op - -enum class ShaderKind { - Baseline, - SingleLookup, - PairTSLookup, -}; - -struct alignas(4) PushConstants { - std::uint32_t key_mask; // pc[0]: mask for T#/Miss ring (power of two minus 1) - std::uint32_t iters; // pc[1]: loop iterations per invocation - std::uint32_t group_stride; // pc[2]: start index delta per 64-invocation group - std::uint32_t lane_stride; // pc[3]: start index delta per lane (0 => wave-uniform, 1 => divergent) - std::uint32_t iter_stride; // pc[4]: index delta per loop iteration - std::uint32_t base_index; // pc[5]: starting key offset within bank - std::uint32_t dep_mask; // pc[6]: data-dependency mask from previous result into next key index - std::uint32_t t_base; // pc[7]: base key slot inside keys_buf for primary key - std::uint32_t s_base; // pc[8]: base key slot inside keys_buf for S# key (PairTSLookup) - std::uint32_t s_mask; // pc[9]: mask for S# ring (PairTSLookup) -}; -static_assert(sizeof(PushConstants) == 40); - -class SpirvBuilder { -public: - std::vector build(ShaderKind kind) { - const bool has_desc_map = kind != ShaderKind::Baseline; - - const std::uint32_t ty_void = id(); - const std::uint32_t ty_bool = id(); - const std::uint32_t ty_uint = id(); - const std::uint32_t ty_v3u = id(); - const std::uint32_t ty_rt_u = id(); - const std::uint32_t ty_buf = id(); - const std::uint32_t ty_pc = id(); - const std::uint32_t ptr_in_v3u = id(); - const std::uint32_t ptr_in_u = id(); - const std::uint32_t ptr_sb_buf = id(); - const std::uint32_t ptr_sb_u = id(); - const std::uint32_t ptr_pc = id(); - const std::uint32_t ptr_pc_u = id(); - const std::uint32_t ptr_fn_u = id(); - const std::uint32_t ty_fn_main = id(); - const std::uint32_t ty_fn_lookup = has_desc_map ? id() : 0u; - const std::uint32_t true_id = has_desc_map ? id() : 0u; - - const std::uint32_t gid_var = id(); - const std::uint32_t keys_var = id(); - const std::uint32_t map_var = has_desc_map ? id() : 0u; - const std::uint32_t out_var = id(); - const std::uint32_t pc_var = id(); - const std::uint32_t fn_lookup = has_desc_map ? id() : 0u; - const std::uint32_t fn_main = id(); - - // Prologue: Capability, MemoryModel, EntryPoint, ExecutionMode - emit(preamble_, spv_op::kOpCapability, {spv_op::kCapShader}); - emit(preamble_, spv_op::kOpMemoryModel, {spv_op::kAddrLogical, spv_op::kMemGlsl450}); - emit(preamble_, spv_op::kOpEntryPoint, - {spv_op::kExecGLCompute, fn_main, 0x6E69616Du, 0x00000000u, gid_var}); - emit(preamble_, spv_op::kOpExecutionMode, - {fn_main, spv_op::kExecModeLocalSize, kWorkgroupSize, 1u, 1u}); - - // Annotations - emit(decs_, spv_op::kOpDecorate, {gid_var, spv_op::kDecBuiltIn, spv_op::kBuiltInGlobalInvocationId}); - emit(decs_, spv_op::kOpDecorate, {ty_rt_u, spv_op::kDecArrayStride, 4u}); - emit(decs_, spv_op::kOpMemberDecorate, {ty_buf, 0u, spv_op::kDecOffset, 0u}); - emit(decs_, spv_op::kOpDecorate, {ty_buf, spv_op::kDecBlock}); - - emit(decs_, spv_op::kOpDecorate, {keys_var, spv_op::kDecDescriptorSet, 0u}); - emit(decs_, spv_op::kOpDecorate, {keys_var, spv_op::kDecBinding, 0u}); - emit(decs_, spv_op::kOpDecorate, {keys_var, spv_op::kDecNonWritable}); - - if (has_desc_map) { - emit(decs_, spv_op::kOpDecorate, {map_var, spv_op::kDecDescriptorSet, 0u}); - emit(decs_, spv_op::kOpDecorate, {map_var, spv_op::kDecBinding, 2u}); - emit(decs_, spv_op::kOpDecorate, {map_var, spv_op::kDecNonWritable}); - } - - emit(decs_, spv_op::kOpDecorate, {out_var, spv_op::kDecDescriptorSet, 0u}); - emit(decs_, spv_op::kOpDecorate, {out_var, spv_op::kDecBinding, 3u}); - emit(decs_, spv_op::kOpDecorate, {out_var, spv_op::kDecNonReadable}); - - for (std::uint32_t m = 0; m < 10u; ++m) { - emit(decs_, spv_op::kOpMemberDecorate, {ty_pc, m, spv_op::kDecOffset, m * 4u}); - } - emit(decs_, spv_op::kOpDecorate, {ty_pc, spv_op::kDecBlock}); - - // Types - emit(types_, spv_op::kOpTypeVoid, {ty_void}); - emit(types_, spv_op::kOpTypeBool, {ty_bool}); - emit(types_, spv_op::kOpTypeInt, {ty_uint, 32u, 0u}); - emit(types_, spv_op::kOpTypeVector, {ty_v3u, ty_uint, 3u}); - emit(types_, spv_op::kOpTypeRuntimeArray, {ty_rt_u, ty_uint}); - emit(types_, spv_op::kOpTypeStruct, {ty_buf, ty_rt_u}); - emit(types_, spv_op::kOpTypeStruct, - {ty_pc, ty_uint, ty_uint, ty_uint, ty_uint, ty_uint, ty_uint, ty_uint, ty_uint, ty_uint, ty_uint}); - emit(types_, spv_op::kOpTypePointer, {ptr_in_v3u, spv_op::kScInput, ty_v3u}); - emit(types_, spv_op::kOpTypePointer, {ptr_in_u, spv_op::kScInput, ty_uint}); - emit(types_, spv_op::kOpTypePointer, {ptr_sb_buf, spv_op::kScStorageBuffer, ty_buf}); - emit(types_, spv_op::kOpTypePointer, {ptr_sb_u, spv_op::kScStorageBuffer, ty_uint}); - emit(types_, spv_op::kOpTypePointer, {ptr_pc, spv_op::kScPushConstant, ty_pc}); - emit(types_, spv_op::kOpTypePointer, {ptr_pc_u, spv_op::kScPushConstant, ty_uint}); - emit(types_, spv_op::kOpTypePointer, {ptr_fn_u, spv_op::kScFunction, ty_uint}); - emit(types_, spv_op::kOpTypeFunction, {ty_fn_main, ty_void}); - if (has_desc_map) { - emit(types_, spv_op::kOpTypeFunction, - {ty_fn_lookup, ty_uint, ty_uint, ty_uint, ty_uint, ty_uint, ty_uint, ty_uint, ty_uint, ty_uint}); - emit(consts_, spv_op::kOpConstantTrue, {ty_bool, true_id}); - } - - // Global variables (placed after constants & pointer types) - emit(gvars_, spv_op::kOpVariable, {ptr_in_v3u, gid_var, spv_op::kScInput}); - emit(gvars_, spv_op::kOpVariable, {ptr_sb_buf, keys_var, spv_op::kScStorageBuffer}); - if (has_desc_map) { - emit(gvars_, spv_op::kOpVariable, {ptr_sb_buf, map_var, spv_op::kScStorageBuffer}); - } - emit(gvars_, spv_op::kOpVariable, {ptr_sb_buf, out_var, spv_op::kScStorageBuffer}); - emit(gvars_, spv_op::kOpVariable, {ptr_pc, pc_var, spv_op::kScPushConstant}); - - ty_bool_ = ty_bool; - ty_uint_ = ty_uint; - ptr_sb_u_ = ptr_sb_u; - ptr_fn_u_ = ptr_fn_u; - - // %desc_lookup_fn(w0..w7) -> uint: identical probe loop to tools/rdna2spirv.py desc_probe() - if (has_desc_map) { - emit_desc_lookup_fn(fn_lookup, ty_fn_lookup, map_var, true_id); - } - - // %main() - emit_main_fn(kind, fn_main, ty_void, ty_fn_main, ptr_in_u, ptr_pc_u, gid_var, keys_var, out_var, pc_var, - fn_lookup); - - std::vector spv; - spv.reserve(5 + preamble_.size() + decs_.size() + types_.size() + consts_.size() + gvars_.size() + funcs_.size()); - spv.push_back(spv_op::kMagic); - spv.push_back(spv_op::kVersion13); - spv.push_back(0u); - spv.push_back(next_id_); - spv.push_back(0u); - append(spv, preamble_); - append(spv, decs_); - append(spv, types_); - append(spv, consts_); - append(spv, gvars_); - append(spv, funcs_); - return spv; - } - -private: - std::uint32_t id() { - return next_id_++; - } - - std::uint32_t uconst(std::uint32_t value) { - const auto [it, inserted] = uconsts_.emplace(value, 0u); - if (inserted) { - it->second = id(); - emit(consts_, spv_op::kOpConstant, {ty_uint_, it->second, value}); - } - return it->second; - } - - static void emit(std::vector& dst, std::uint32_t opcode, std::initializer_list ops) { - const std::uint32_t words = static_cast(1 + ops.size()); - dst.push_back((words << 16) | opcode); - for (const std::uint32_t w : ops) dst.push_back(w); - } - - static void emit_vec(std::vector& dst, std::uint32_t opcode, const std::vector& ops) { - const std::uint32_t words = static_cast(1 + ops.size()); - dst.push_back((words << 16) | opcode); - for (const std::uint32_t w : ops) dst.push_back(w); - } - - static void append(std::vector& dst, const std::vector& src) { - dst.insert(dst.end(), src.begin(), src.end()); - } - - std::uint32_t binop(std::uint32_t opcode, std::uint32_t res_type, std::uint32_t a, std::uint32_t b) { - const std::uint32_t r = id(); - emit(funcs_, opcode, {res_type, r, a, b}); - return r; - } - - std::uint32_t load(std::uint32_t res_type, std::uint32_t ptr) { - const std::uint32_t r = id(); - emit(funcs_, spv_op::kOpLoad, {res_type, r, ptr}); - return r; - } - - std::uint32_t access2(std::uint32_t ptr_type, std::uint32_t base, std::uint32_t idx0, std::uint32_t idx1) { - const std::uint32_t r = id(); - emit(funcs_, spv_op::kOpAccessChain, {ptr_type, r, base, idx0, idx1}); - return r; - } - - void emit_desc_lookup_fn(std::uint32_t fn_id, std::uint32_t fn_type, std::uint32_t map_var, - std::uint32_t true_id) { - const std::uint32_t c0 = uconst(0u); - const std::uint32_t c1 = uconst(1u); - const std::uint32_t c8 = uconst(kDescriptorProbes); - const std::uint32_t c9 = uconst(9u); - const std::uint32_t c10 = uconst(10u); - const std::uint32_t c_offset = uconst(kFnvOffsetBasis); - const std::uint32_t c_prime = uconst(kFnvPrime); - - emit(funcs_, spv_op::kOpFunction, {ty_uint_, fn_id, 0u, fn_type}); - std::array params{}; - for (int i = 0; i < 8; ++i) { - params[i] = id(); - emit(funcs_, spv_op::kOpFunctionParameter, {ty_uint_, params[i]}); - } - - const std::uint32_t lbl_entry = id(); - const std::uint32_t lbl_head = id(); - const std::uint32_t lbl_body = id(); - const std::uint32_t lbl_hit = id(); - const std::uint32_t lbl_next = id(); - const std::uint32_t lbl_cont = id(); - const std::uint32_t lbl_end = id(); - - emit(funcs_, spv_op::kOpLabel, {lbl_entry}); - const std::uint32_t kv = id(); - const std::uint32_t iv = id(); - emit(funcs_, spv_op::kOpVariable, {ptr_fn_u_, kv, spv_op::kScFunction, c0}); - emit(funcs_, spv_op::kOpVariable, {ptr_fn_u_, iv, spv_op::kScFunction, c0}); - - std::uint32_t h = c_offset; - for (int i = 0; i < 8; ++i) { - const std::uint32_t x = binop(spv_op::kOpBitwiseXor, ty_uint_, h, params[i]); - h = binop(spv_op::kOpIMul, ty_uint_, x, c_prime); - } - const std::uint32_t mask_ptr = access2(ptr_sb_u_, map_var, c0, c0); - const std::uint32_t mask = load(ty_uint_, mask_ptr); - emit(funcs_, spv_op::kOpBranch, {lbl_head}); - - emit(funcs_, spv_op::kOpLabel, {lbl_head}); - emit(funcs_, spv_op::kOpLoopMerge, {lbl_end, lbl_cont, 0u}); - emit(funcs_, spv_op::kOpBranch, {lbl_body}); - - emit(funcs_, spv_op::kOpLabel, {lbl_body}); - const std::uint32_t k = load(ty_uint_, kv); - const std::uint32_t s = binop(spv_op::kOpIAdd, ty_uint_, h, k); - const std::uint32_t slot = binop(spv_op::kOpBitwiseAnd, ty_uint_, s, mask); - const std::uint32_t base = binop(spv_op::kOpIMul, ty_uint_, slot, c10); - std::uint32_t match = true_id; - for (std::uint32_t j = 0; j < 8u; ++j) { - const std::uint32_t off = binop(spv_op::kOpIAdd, ty_uint_, base, uconst(1u + j)); - const std::uint32_t p = access2(ptr_sb_u_, map_var, c0, off); - const std::uint32_t v = load(ty_uint_, p); - const std::uint32_t eq = binop(spv_op::kOpIEqual, ty_bool_, v, params[j]); - match = binop(spv_op::kOpLogicalAnd, ty_bool_, match, eq); - } - emit(funcs_, spv_op::kOpSelectionMerge, {lbl_next, 0u}); - emit(funcs_, spv_op::kOpBranchConditional, {match, lbl_hit, lbl_next}); - - emit(funcs_, spv_op::kOpLabel, {lbl_hit}); - const std::uint32_t idx_off = binop(spv_op::kOpIAdd, ty_uint_, base, c9); - const std::uint32_t idx_ptr = access2(ptr_sb_u_, map_var, c0, idx_off); - const std::uint32_t idx_val = load(ty_uint_, idx_ptr); - emit(funcs_, spv_op::kOpStore, {iv, idx_val}); - emit(funcs_, spv_op::kOpStore, {kv, c8}); - emit(funcs_, spv_op::kOpBranch, {lbl_next}); - - emit(funcs_, spv_op::kOpLabel, {lbl_next}); - emit(funcs_, spv_op::kOpBranch, {lbl_cont}); - - emit(funcs_, spv_op::kOpLabel, {lbl_cont}); - const std::uint32_t k2 = load(ty_uint_, kv); - const std::uint32_t k3 = binop(spv_op::kOpIAdd, ty_uint_, k2, c1); - emit(funcs_, spv_op::kOpStore, {kv, k3}); - const std::uint32_t more = binop(spv_op::kOpULessThan, ty_bool_, k3, c8); - emit(funcs_, spv_op::kOpBranchConditional, {more, lbl_head, lbl_end}); - - emit(funcs_, spv_op::kOpLabel, {lbl_end}); - const std::uint32_t ret = load(ty_uint_, iv); - emit(funcs_, spv_op::kOpReturnValue, {ret}); - emit(funcs_, spv_op::kOpFunctionEnd, {}); - } - - void emit_main_fn(ShaderKind kind, std::uint32_t fn_id, std::uint32_t ty_void, std::uint32_t ty_fn_main, - std::uint32_t ptr_in_u, std::uint32_t ptr_pc_u, std::uint32_t gid_var, std::uint32_t keys_var, - std::uint32_t out_var, std::uint32_t pc_var, std::uint32_t fn_lookup) { - const std::uint32_t c0 = uconst(0u); - const std::uint32_t c1 = uconst(1u); - const std::uint32_t c3 = uconst(3u); - const std::uint32_t c6 = uconst(6u); - const std::uint32_t c63 = uconst(63u); - const std::uint32_t c_offset = uconst(kFnvOffsetBasis); - const std::uint32_t c_prime = uconst(kFnvPrime); - const std::uint32_t c_ff = uconst(0xFFFFFFFFu); - - emit(funcs_, spv_op::kOpFunction, {ty_void, fn_id, 0u, ty_fn_main}); - const std::uint32_t lbl_entry = id(); - const std::uint32_t lbl_head = id(); - const std::uint32_t lbl_body = id(); - const std::uint32_t lbl_cont = id(); - const std::uint32_t lbl_end = id(); - - emit(funcs_, spv_op::kOpLabel, {lbl_entry}); - const std::uint32_t i_var = id(); - const std::uint32_t acc_var = id(); - const std::uint32_t prev_var = id(); - emit(funcs_, spv_op::kOpVariable, {ptr_fn_u_, i_var, spv_op::kScFunction, c0}); - emit(funcs_, spv_op::kOpVariable, {ptr_fn_u_, acc_var, spv_op::kScFunction, c_offset}); - emit(funcs_, spv_op::kOpVariable, {ptr_fn_u_, prev_var, spv_op::kScFunction, c0}); - - const std::uint32_t gid_ptr = id(); - emit(funcs_, spv_op::kOpAccessChain, {ptr_in_u, gid_ptr, gid_var, c0}); - const std::uint32_t gid_x = load(ty_uint_, gid_ptr); - - std::array pc{}; - for (std::uint32_t m = 0; m < 10u; ++m) { - const std::uint32_t p = id(); - emit(funcs_, spv_op::kOpAccessChain, {ptr_pc_u, p, pc_var, uconst(m)}); - pc[m] = load(ty_uint_, p); - } - - const std::uint32_t wg = binop(spv_op::kOpShiftRightLogical, ty_uint_, gid_x, c6); - const std::uint32_t lid = binop(spv_op::kOpBitwiseAnd, ty_uint_, gid_x, c63); - const std::uint32_t wg_term = binop(spv_op::kOpIMul, ty_uint_, wg, pc[2]); - const std::uint32_t lid_term = binop(spv_op::kOpIMul, ty_uint_, lid, pc[3]); - const std::uint32_t s0 = binop(spv_op::kOpIAdd, ty_uint_, pc[5], wg_term); - const std::uint32_t start = binop(spv_op::kOpIAdd, ty_uint_, s0, lid_term); - emit(funcs_, spv_op::kOpBranch, {lbl_head}); - - emit(funcs_, spv_op::kOpLabel, {lbl_head}); - const std::uint32_t iv = load(ty_uint_, i_var); - const std::uint32_t cond = binop(spv_op::kOpULessThan, ty_bool_, iv, pc[1]); - emit(funcs_, spv_op::kOpLoopMerge, {lbl_end, lbl_cont, 0u}); - emit(funcs_, spv_op::kOpBranchConditional, {cond, lbl_body, lbl_end}); - - emit(funcs_, spv_op::kOpLabel, {lbl_body}); - const std::uint32_t prev = load(ty_uint_, prev_var); - const std::uint32_t dep = binop(spv_op::kOpBitwiseAnd, ty_uint_, prev, pc[6]); - const std::uint32_t iter_delta = binop(spv_op::kOpIMul, ty_uint_, iv, pc[4]); - const std::uint32_t idx_base = binop(spv_op::kOpIAdd, ty_uint_, start, iter_delta); - const std::uint32_t idx1 = binop(spv_op::kOpIAdd, ty_uint_, idx_base, dep); - - const std::uint32_t masked_t = binop(spv_op::kOpBitwiseAnd, ty_uint_, idx1, pc[0]); - const std::uint32_t kidx = binop(spv_op::kOpIAdd, ty_uint_, pc[7], masked_t); - const std::uint32_t koff = binop(spv_op::kOpShiftLeftLogical, ty_uint_, kidx, c3); - - std::array w{}; - for (std::uint32_t j = 0; j < 8u; ++j) { - const std::uint32_t ko = binop(spv_op::kOpIAdd, ty_uint_, koff, uconst(j)); - const std::uint32_t kp = access2(ptr_sb_u_, keys_var, c0, ko); - w[j] = load(ty_uint_, kp); - } - - if (kind == ShaderKind::Baseline) { - std::uint32_t mix = w[0]; - for (int j = 1; j < 8; ++j) { - mix = binop(spv_op::kOpBitwiseXor, ty_uint_, mix, w[j]); - } - const std::uint32_t acc0 = load(ty_uint_, acc_var); - const std::uint32_t acc1 = binop(spv_op::kOpIMul, ty_uint_, acc0, c_prime); - const std::uint32_t acc2 = binop(spv_op::kOpBitwiseXor, ty_uint_, acc1, mix); - emit(funcs_, spv_op::kOpStore, {acc_var, acc2}); - emit(funcs_, spv_op::kOpStore, {prev_var, mix}); - } else if (kind == ShaderKind::SingleLookup) { - const std::uint32_t res = id(); - emit_vec(funcs_, spv_op::kOpFunctionCall, - {ty_uint_, res, fn_lookup, w[0], w[1], w[2], w[3], w[4], w[5], w[6], w[7]}); - const std::uint32_t acc0 = load(ty_uint_, acc_var); - const std::uint32_t acc1 = binop(spv_op::kOpIMul, ty_uint_, acc0, c_prime); - const std::uint32_t acc2 = binop(spv_op::kOpBitwiseXor, ty_uint_, acc1, res); - emit(funcs_, spv_op::kOpStore, {acc_var, acc2}); - emit(funcs_, spv_op::kOpStore, {prev_var, res}); - } else { - const std::uint32_t res_t = id(); - emit_vec(funcs_, spv_op::kOpFunctionCall, - {ty_uint_, res_t, fn_lookup, w[0], w[1], w[2], w[3], w[4], w[5], w[6], w[7]}); - const std::uint32_t masked_s = binop(spv_op::kOpBitwiseAnd, ty_uint_, idx1, pc[9]); - const std::uint32_t skidx = binop(spv_op::kOpIAdd, ty_uint_, pc[8], masked_s); - const std::uint32_t soff = binop(spv_op::kOpShiftLeftLogical, ty_uint_, skidx, c3); - std::array s{}; - for (std::uint32_t j = 0; j < 4u; ++j) { - const std::uint32_t so = binop(spv_op::kOpIAdd, ty_uint_, soff, uconst(j)); - const std::uint32_t sp = access2(ptr_sb_u_, keys_var, c0, so); - s[j] = load(ty_uint_, sp); - } - const std::uint32_t res_s = id(); - emit_vec(funcs_, spv_op::kOpFunctionCall, - {ty_uint_, res_s, fn_lookup, s[0], s[1], s[2], s[3], c_ff, c_ff, c_ff, c_ff}); - const std::uint32_t acc0 = load(ty_uint_, acc_var); - const std::uint32_t acc1 = binop(spv_op::kOpIMul, ty_uint_, acc0, c_prime); - const std::uint32_t acc2 = binop(spv_op::kOpBitwiseXor, ty_uint_, acc1, res_t); - const std::uint32_t acc3 = binop(spv_op::kOpIMul, ty_uint_, acc2, c_prime); - const std::uint32_t acc4 = binop(spv_op::kOpBitwiseXor, ty_uint_, acc3, res_s); - emit(funcs_, spv_op::kOpStore, {acc_var, acc4}); - emit(funcs_, spv_op::kOpStore, {prev_var, res_t}); - } - emit(funcs_, spv_op::kOpBranch, {lbl_cont}); - - emit(funcs_, spv_op::kOpLabel, {lbl_cont}); - const std::uint32_t i_cur = load(ty_uint_, i_var); - const std::uint32_t i_nxt = binop(spv_op::kOpIAdd, ty_uint_, i_cur, c1); - emit(funcs_, spv_op::kOpStore, {i_var, i_nxt}); - emit(funcs_, spv_op::kOpBranch, {lbl_head}); - - emit(funcs_, spv_op::kOpLabel, {lbl_end}); - const std::uint32_t final_acc = load(ty_uint_, acc_var); - const std::uint32_t out_ptr = access2(ptr_sb_u_, out_var, c0, gid_x); - emit(funcs_, spv_op::kOpStore, {out_ptr, final_acc}); - emit(funcs_, spv_op::kOpReturn, {}); - emit(funcs_, spv_op::kOpFunctionEnd, {}); - } - - std::uint32_t next_id_ = 1u; - std::uint32_t ty_bool_ = 0u; - std::uint32_t ty_uint_ = 0u; - std::uint32_t ptr_sb_u_ = 0u; - std::uint32_t ptr_fn_u_ = 0u; - std::map uconsts_; - std::vector preamble_; - std::vector decs_; - std::vector types_; - std::vector consts_; - std::vector gvars_; - std::vector funcs_; -}; - -std::vector build_bench_spv(ShaderKind kind) { - SpirvBuilder b; - return b.build(kind); -} - -bool check_spv_structure(const std::vector& words, const char* label) { - if (words.size() < 5u || words[0] != spv_op::kMagic || words[1] != spv_op::kVersion13 || words[3] < 2u) { - std::fprintf(stderr, "self-test: invalid SPIR-V header for %s\n", label); - return false; - } - const std::uint32_t bound = words[3]; - std::size_t idx = 5u; - int open_fns = 0; - bool seen_entry = false; - while (idx < words.size()) { - const std::uint32_t head = words[idx]; - const std::uint32_t wc = head >> 16; - const std::uint32_t op = head & 0xFFFFu; - if (wc == 0u || idx + wc > words.size()) { - std::fprintf(stderr, "self-test: truncated instruction in %s at word %zu\n", label, idx); - return false; - } - if (op == spv_op::kOpEntryPoint) seen_entry = true; - if (op == spv_op::kOpFunction) { - if (wc < 3u || words[idx + 2u] >= bound) return false; - ++open_fns; - } else if (op == spv_op::kOpFunctionEnd) { - if (open_fns <= 0) return false; - --open_fns; - } - idx += wc; - } - if (!seen_entry || open_fns != 0) { - std::fprintf(stderr, "self-test: malformed function or entry point in %s\n", label); - return false; - } - return true; -} - -bool write_spv_file(const std::string& path, const std::vector& words) { - std::ofstream f(path, std::ios::binary); - if (!f) { - std::fprintf(stderr, "could not open %s for writing\n", path.c_str()); - return false; - } - f.write(reinterpret_cast(words.data()), static_cast(words.size() * sizeof(std::uint32_t))); - if (f.fail()) { - std::fprintf(stderr, "failed writing %s\n", path.c_str()); - return false; - } - return true; -} - -// ---- Workload generation & exact CPU oracle ---- - -std::uint64_t splitmix64(std::uint64_t& state) { - state += 0x9E3779B97F4A7C15ULL; - std::uint64_t z = state; - z = (z ^ (z >> 30)) * 0xBF58476D1CE4E5B9ULL; - z = (z ^ (z >> 27)) * 0x94D049BB133111EBULL; - return z ^ (z >> 31); -} - -std::uint32_t next_pow2_u32(std::uint32_t n) { - std::uint32_t p = 1u; - while (p < n) p <<= 1; - return p; -} - -DescriptorKey make_bench_tsharp(std::uint32_t id) { - const std::uint64_t va = 0x0000010000000000ULL + static_cast(id) * 256ULL; - const std::uint32_t fmt = 10u + (id % 24u); - const std::uint32_t w = 63u + ((id * 37u) % 2048u); - const std::uint32_t h = 63u + ((id * 53u) % 2048u); - return { - static_cast(va >> 8), - (static_cast(va >> 40) & 0xFFu) | 0x2000u | (fmt << 20), - (w & 0x3FFFu) | ((h & 0x3FFFu) << 14), - 0x000AA688u ^ (id & 0xFFu), - id ^ 0x9E3779B9u, - (id * 0x85EBCA6Bu) & 0x00FFFFFFu, - 0x00000010u | ((id % 7u) << 12), - 0x80000000u ^ (id << 16), - }; -} - -DescriptorKey make_bench_ssharp(std::uint32_t id) { - const std::uint32_t raw[4] = { - 0x00000092u | ((id & 0x7u) << 20), - 0x00C00000u ^ (id << 8), - 0x14500000u | (id & 0xFFFu), - id ^ 0xA5A50001u, - }; - return make_ssharp_key(raw); -} - -DescriptorKey make_bench_miss(std::uint32_t id) { - return { - 0xDEAD0000u ^ (id * 0x9E3779B9u), - 0xBEEF0000u ^ id, - 0xCAFE0001u + id, - 0xBAAD0002u ^ (id << 3), - 0x13572468u, - 0x24681357u, - 0xFACEB00Cu, - 0x40000000u | ((id & 0xFFFFFFu) << 1), - }; -} - -// Mirrors the shader's exact probe loop against the exported storage buffer, returning {index, 1-based probe count}. -std::pair probe_gpu_table(const std::vector& table_buf, - const DescriptorKey& key) { - const std::uint32_t h = hash_descriptor_key(key); - const std::uint32_t mask = table_buf[0]; - for (std::uint32_t k = 0; k < kDescriptorProbes; ++k) { - const std::uint32_t base = ((h + k) & mask) * 10u; - bool match = true; - for (std::uint32_t j = 0; j < 8u; ++j) { - match = match && (table_buf[1u + base + j] == key[j]); - } - if (match) return {table_buf[base + 9u], k + 1u}; - } - return {0u, kDescriptorProbes}; -} - -struct TableDataset { - std::uint32_t entry_count = 0; - std::uint32_t t_count = 0; - std::uint32_t s_count = 0; - std::uint32_t capacity = 0; - double load_pct = 0.0; - double mean_probes = 0.0; - double probe1_pct = 0.0; - std::uint32_t max_probes = 0; - std::uint32_t t_pow2 = 0; - std::uint32_t s_pow2 = 0; - std::uint32_t t_base = 0; - std::uint32_t s_base = 0; - std::uint32_t miss_base = 0; - std::vector gpu_table; - std::vector keys_buf; // [T# (t_pow2) | S# (s_pow2) | Miss (t_pow2)] x 8 u32 - std::vector expected_baseline; // per key slot: XOR of 8 key words - std::vector expected_lookup; // per key slot: expected bindless index - std::vector slot_entry_id; // per key slot: unique entry index within its bank -}; - -bool build_dataset(std::uint32_t entry_count, TableDataset& out) { - out = TableDataset{}; - out.entry_count = entry_count; - out.s_count = std::min(entry_count / 2u, std::max(16u, entry_count / 10u)); - out.t_count = entry_count - out.s_count; - - DescriptorTable table(std::max(32u, next_pow2_u32(entry_count * 2u))); - std::vector t_keys(out.t_count); - std::vector s_keys(out.s_count); - - for (std::uint32_t i = 0; i < out.t_count; ++i) { - t_keys[i] = make_bench_tsharp(i + 1u); - table.insert(t_keys[i], 1u + i); - } - for (std::uint32_t i = 0; i < out.s_count; ++i) { - s_keys[i] = make_bench_ssharp(i + 1u); - table.insert(s_keys[i], 1u + out.t_count + i); - } - - out.capacity = static_cast(table.capacity()); - out.load_pct = 100.0 * static_cast(entry_count) / static_cast(out.capacity); - out.gpu_table = table.build_gpu_buffer(); - - std::uint64_t probe_sum = 0; - std::uint32_t probe1 = 0; - std::uint32_t max_p = 0; - auto check_live = [&](const DescriptorKey& k, std::uint32_t expected_idx) -> bool { - const auto [got, probes] = probe_gpu_table(out.gpu_table, k); - if (got != expected_idx || table.lookup(k) != expected_idx) { - std::fprintf(stderr, "table oracle mismatch: got=%u cpu=%u expected=%u\n", got, table.lookup(k), - expected_idx); - return false; - } - probe_sum += probes; - if (probes == 1u) ++probe1; - if (probes > max_p) max_p = probes; - return true; - }; - for (std::uint32_t i = 0; i < out.t_count; ++i) { - if (!check_live(t_keys[i], 1u + i)) return false; - } - for (std::uint32_t i = 0; i < out.s_count; ++i) { - if (!check_live(s_keys[i], 1u + out.t_count + i)) return false; - } - out.mean_probes = static_cast(probe_sum) / static_cast(entry_count); - out.probe1_pct = 100.0 * static_cast(probe1) / static_cast(entry_count); - out.max_probes = max_p; - - // Shuffle key rings deterministically so unit-stride walks visit scattered table slots across L2/DRAM. - std::uint64_t rng = 0x4C454F4E49444156ULL ^ static_cast(entry_count); - std::vector t_perm(out.t_count); - std::iota(t_perm.begin(), t_perm.end(), 0u); - for (std::uint32_t i = out.t_count; i > 1u; --i) { - const std::uint32_t j = static_cast(splitmix64(rng) % i); - std::swap(t_perm[i - 1u], t_perm[j]); - } - // Pin t_perm[0] to a depth-1 entry so uniform_hot_tsharp measures identical probe depth across sizes. - for (std::uint32_t k = 0; k < out.t_count; ++k) { - if (probe_gpu_table(out.gpu_table, t_keys[t_perm[k]]).second == 1u) { - std::swap(t_perm[0], t_perm[k]); - break; - } - } - std::vector s_perm(out.s_count); - std::iota(s_perm.begin(), s_perm.end(), 0u); - for (std::uint32_t i = out.s_count; i > 1u; --i) { - const std::uint32_t j = static_cast(splitmix64(rng) % i); - std::swap(s_perm[i - 1u], s_perm[j]); - } - - out.t_pow2 = next_pow2_u32(out.t_count); - out.s_pow2 = next_pow2_u32(out.s_count); - out.t_base = 0u; - out.s_base = out.t_pow2; - out.miss_base = out.t_pow2 + out.s_pow2; - - const std::uint32_t total_slots = out.t_pow2 + out.s_pow2 + out.t_pow2; - out.keys_buf.resize(static_cast(total_slots) * 8u); - out.expected_baseline.resize(total_slots); - out.expected_lookup.resize(total_slots); - out.slot_entry_id.resize(total_slots); - - const auto store_slot = [&](std::uint32_t slot, const DescriptorKey& key, std::uint32_t expected_idx, - std::uint32_t entry_id) { - std::uint32_t xor_mix = 0u; - for (std::uint32_t j = 0; j < 8u; ++j) { - out.keys_buf[static_cast(slot) * 8u + j] = key[j]; - xor_mix ^= key[j]; - } - out.expected_baseline[slot] = xor_mix; - out.expected_lookup[slot] = expected_idx; - out.slot_entry_id[slot] = entry_id; - }; - - for (std::uint32_t i = 0; i < out.t_pow2; ++i) { - const std::uint32_t idx = t_perm[i % out.t_count]; - store_slot(out.t_base + i, t_keys[idx], 1u + idx, idx); - } - for (std::uint32_t i = 0; i < out.s_pow2; ++i) { - const std::uint32_t idx = s_perm[i % out.s_count]; - store_slot(out.s_base + i, s_keys[idx], 1u + out.t_count + idx, idx); - } - std::uint32_t miss_seq = 0u; - for (std::uint32_t i = 0; i < out.t_pow2; ++i) { - DescriptorKey mk{}; - for (;;) { - mk = make_bench_miss(miss_seq++); - if (!table.contains(mk) && probe_gpu_table(out.gpu_table, mk).first == 0u) break; - } - store_slot(out.miss_base + i, mk, 0u, i); - } - return true; -} - -struct ScenarioSpec { - const char* name; - ShaderKind shader; - bool divergent; - bool group_stride_is_iters; - std::uint32_t group_stride; - std::uint32_t lane_stride; - std::uint32_t iter_stride; - bool dep_chain; - enum class Bank { TSharp, SSharp, Miss } bank; - double lookups_per_iter; -}; - -PushConstants make_push_constants(const ScenarioSpec& sc, const TableDataset& ds, std::uint32_t iters) { - PushConstants pc{}; - pc.iters = iters; - pc.group_stride = sc.group_stride_is_iters ? iters : sc.group_stride; - pc.lane_stride = sc.lane_stride; - pc.iter_stride = sc.iter_stride; - pc.base_index = 0u; - pc.s_base = ds.s_base; - pc.s_mask = ds.s_pow2 - 1u; - if (sc.bank == ScenarioSpec::Bank::TSharp) { - pc.t_base = ds.t_base; - pc.key_mask = ds.t_pow2 - 1u; - } else if (sc.bank == ScenarioSpec::Bank::SSharp) { - pc.t_base = ds.s_base; - pc.key_mask = ds.s_pow2 - 1u; - } else { - pc.t_base = ds.miss_base; - pc.key_mask = ds.t_pow2 - 1u; - } - pc.dep_mask = sc.dep_chain ? pc.key_mask : 0u; - return pc; -} - -std::uint32_t count_unique_keys(const ScenarioSpec& sc, const TableDataset& ds, const PushConstants& pc, - std::uint32_t eff_groups) { - const std::uint32_t primary_distinct = - (sc.bank == ScenarioSpec::Bank::TSharp) ? ds.t_count - : (sc.bank == ScenarioSpec::Bank::SSharp) ? ds.s_count - : ds.t_pow2; - const std::uint32_t eff_invocations = eff_groups * kWorkgroupSize; - if (sc.dep_chain) { - if (eff_invocations >= primary_distinct) return primary_distinct; - std::vector seen(primary_distinct, 0u); - std::uint32_t count = 0u; - for (std::uint32_t tid = 0; tid < eff_invocations; ++tid) { - const std::uint32_t wg = tid >> 6; - const std::uint32_t lid = tid & 63u; - const std::uint32_t start = pc.base_index + wg * pc.group_stride + lid * pc.lane_stride; - std::uint32_t prev = 0u; - for (std::uint32_t i = 0; i < pc.iters; ++i) { - const std::uint32_t idx1 = start + i * pc.iter_stride + (prev & pc.dep_mask); - const std::uint32_t kidx = pc.t_base + (idx1 & pc.key_mask); - const std::uint32_t eid = ds.slot_entry_id[kidx]; - if (!seen[eid]) { - seen[eid] = 1u; - ++count; - } - prev = ds.expected_lookup[kidx]; - } - } - return count; - } - - std::uint64_t span = 1u; - if (pc.group_stride == 0u && pc.lane_stride == 0u && pc.iter_stride == 0u) { - span = 1u; - } else if (pc.lane_stride == 0u && pc.iter_stride == 1u && pc.group_stride == pc.iters) { - span = static_cast(eff_groups) * static_cast(pc.iters); - } else if (pc.group_stride == kWorkgroupSize && pc.lane_stride == 1u && pc.iter_stride == 1u) { - span = static_cast(eff_groups) * kWorkgroupSize + pc.iters - 1u; - } else { - span = static_cast(eff_invocations) * static_cast(pc.iters); - } - - const std::uint32_t primary_seen = - static_cast(std::min(primary_distinct, span)); - if (sc.shader == ShaderKind::PairTSLookup) { - const std::uint32_t s_seen = static_cast(std::min(ds.s_count, span)); - return primary_seen + s_seen; - } - return primary_seen; -} - -std::uint32_t eval_invocation_oracle(const ScenarioSpec& sc, const TableDataset& ds, const PushConstants& pc, - std::uint32_t tid) { - const std::uint32_t wg = tid >> 6; - const std::uint32_t lid = tid & 63u; - const std::uint32_t start = pc.base_index + wg * pc.group_stride + lid * pc.lane_stride; - std::uint32_t acc = kFnvOffsetBasis; - std::uint32_t prev = 0u; - - for (std::uint32_t i = 0; i < pc.iters; ++i) { - const std::uint32_t dep = prev & pc.dep_mask; - const std::uint32_t idx1 = start + i * pc.iter_stride + dep; - const std::uint32_t kidx = pc.t_base + (idx1 & pc.key_mask); - if (sc.shader == ShaderKind::Baseline) { - const std::uint32_t mix = ds.expected_baseline[kidx]; - acc = (acc * kFnvPrime) ^ mix; - prev = mix; - } else if (sc.shader == ShaderKind::SingleLookup) { - const std::uint32_t res = ds.expected_lookup[kidx]; - acc = (acc * kFnvPrime) ^ res; - prev = res; - } else { - const std::uint32_t res_t = ds.expected_lookup[kidx]; - const std::uint32_t skidx = pc.s_base + (idx1 & pc.s_mask); - const std::uint32_t res_s = ds.expected_lookup[skidx]; - acc = (acc * kFnvPrime) ^ res_t; - acc = (acc * kFnvPrime) ^ res_s; - prev = res_t; - } - } - return acc; -} - -bool verify_gpu_output(const ScenarioSpec& sc, const TableDataset& ds, const PushConstants& pc, - const std::uint32_t* gpu_out, std::uint32_t total_invocations) { - const std::uint64_t total_work = static_cast(total_invocations) * pc.iters; - std::uint32_t mismatches = 0u; - auto check_tid = [&](std::uint32_t tid) { - const std::uint32_t want = eval_invocation_oracle(sc, ds, pc, tid); - const std::uint32_t got = gpu_out[tid]; - if (got != want) { - if (mismatches < 5u) { - std::fprintf(stderr, "mismatch %s tid=%u: got=0x%08x want=0x%08x\n", sc.name, tid, got, want); - } - ++mismatches; - } - }; - - if (total_work <= 4000000ULL) { - for (std::uint32_t tid = 0; tid < total_invocations; ++tid) check_tid(tid); - } else { - const std::uint32_t edge = std::min(512u, total_invocations); - for (std::uint32_t tid = 0; tid < edge; ++tid) check_tid(tid); - const std::uint32_t tail = total_invocations - edge; - for (std::uint32_t tid = std::max(edge, tail); tid < total_invocations; ++tid) check_tid(tid); - const std::uint32_t step = std::max(65u, total_invocations / 4096u); - for (std::uint32_t tid = edge; tid < tail; tid += step) check_tid(tid); - } - return mismatches == 0u; -} - -// ---- Vulkan helpers & CLI options ---- - -enum class MemoryFilter { All, Device, Host, Rebar }; - -struct Options { - std::vector sizes = {1000u, 10000u, 100000u}; - std::uint32_t groups = 4096u; - std::uint32_t iters = 64u; - std::uint32_t reps = 25u; - std::uint32_t warmup = 5u; - double max_dispatch_ms = 120.0; - double warmup_ms = 300.0; // keep running the timed dispatch until this much time has passed (0 = off) - std::optional device_index; - MemoryFilter mem_filter = MemoryFilter::All; - bool list_devices = false; - bool csv = false; - bool self_test = false; - std::string dump_spv_prefix; -}; - -void print_usage() { - std::printf( - "usage: vk_descriptor_bench [options]\n" - " --sizes LIST comma-separated table entry counts (default: 1000,10000,100000)\n" - " --groups N workgroups of 64 invocations per dispatch (default: 4096)\n" - " --iters N lookups per invocation per dispatch (default: 64)\n" - " --reps N timed repetitions per scenario (default: 25)\n" - " --warmup N warmup dispatches before timing (default: 5)\n" - " --warmup-ms F then keep dispatching until F ms have passed, so the GPU clocks are up before the\n" - " first timed run, 0=off (default: 300; --quick turns it off)\n" - " --max-dispatch-ms F auto-scale slow dispatches to avoid OS TDR, 0=off (default: 120)\n" - " --memory MODE all|device|host|rebar (default: all)\n" - " --device N select physical device index from --list-devices\n" - " --list-devices list Vulkan physical devices and exit\n" - " --quick fast check profile (sizes 1000,10000; groups 16; iters 4; reps 3)\n" - " --csv emit CSV with timing_status and empty fields for unavailable measurements\n" - " --dump-spv PREFIX write the 3 SPIR-V compute modules to PREFIX_*.spv and exit\n" - " --self-test CPU-only checks for CLI, SPIR-V encoding and descriptor lookup\n" - " --help print this message\n"); -} - -bool parse_u32(const char* s, std::uint32_t& out) { - if (!s || *s < '0' || *s > '9') return false; - char* end = nullptr; - const unsigned long long v = std::strtoull(s, &end, 10); - if (*end != '\0' || v > std::numeric_limits::max()) return false; - out = static_cast(v); - return true; -} - -bool parse_args(int argc, const char* const* argv, Options& opt, bool& show_help) { - show_help = false; - for (int i = 1; i < argc; ++i) { - const std::string_view arg(argv[i]); - auto need_val = [&](const char*& val) -> bool { - if (i + 1 >= argc) { - std::fprintf(stderr, "missing argument for %.*s\n", int(arg.size()), arg.data()); - return false; - } - val = argv[++i]; - return true; - }; - if (arg == "--help" || arg == "-h") { - show_help = true; - return true; - } else if (arg == "--self-test") { - opt.self_test = true; - } else if (arg == "--list-devices") { - opt.list_devices = true; - } else if (arg == "--csv") { - opt.csv = true; - } else if (arg == "--quick") { - opt.sizes = {1000u, 10000u}; - opt.groups = 16u; - opt.iters = 4u; - opt.warmup = 1u; - opt.warmup_ms = 0.0; - opt.reps = 3u; - } else if (arg == "--groups") { - const char* v = nullptr; - if (!need_val(v) || !parse_u32(v, opt.groups) || opt.groups == 0u) return false; - } else if (arg == "--iters") { - const char* v = nullptr; - if (!need_val(v) || !parse_u32(v, opt.iters) || opt.iters == 0u) return false; - } else if (arg == "--reps") { - const char* v = nullptr; - if (!need_val(v) || !parse_u32(v, opt.reps) || opt.reps == 0u) return false; - } else if (arg == "--warmup") { - const char* v = nullptr; - if (!need_val(v) || !parse_u32(v, opt.warmup)) return false; - } else if (arg == "--max-dispatch-ms") { - const char* v = nullptr; - if (!need_val(v)) return false; - char* end = nullptr; - const double val = std::strtod(v, &end); - if (*v == '\0' || *end != '\0' || !std::isfinite(val) || val < 0.0) return false; - opt.max_dispatch_ms = val; - } else if (arg == "--warmup-ms") { - const char* v = nullptr; - if (!need_val(v)) return false; - char* end = nullptr; - const double val = std::strtod(v, &end); - if (*v == '\0' || *end != '\0' || !std::isfinite(val) || val < 0.0) return false; - opt.warmup_ms = val; - } else if (arg == "--device") { - const char* v = nullptr; - std::uint32_t idx = 0u; - if (!need_val(v) || !parse_u32(v, idx)) return false; - opt.device_index = idx; - } else if (arg == "--dump-spv") { - const char* v = nullptr; - if (!need_val(v)) return false; - opt.dump_spv_prefix = v; - } else if (arg == "--memory") { - const char* v = nullptr; - if (!need_val(v)) return false; - const std::string_view mv(v); - if (mv == "all") opt.mem_filter = MemoryFilter::All; - else if (mv == "device") opt.mem_filter = MemoryFilter::Device; - else if (mv == "host") opt.mem_filter = MemoryFilter::Host; - else if (mv == "rebar") opt.mem_filter = MemoryFilter::Rebar; - else { - std::fprintf(stderr, "invalid --memory value: %s\n", v); - return false; - } - } else if (arg == "--sizes") { - const char* v = nullptr; - if (!need_val(v)) return false; - opt.sizes.clear(); - std::string_view sv(v); - while (!sv.empty()) { - const std::size_t comma = sv.find(','); - const std::string part(sv.substr(0, comma)); - std::uint32_t sz = 0u; - if (!parse_u32(part.c_str(), sz) || sz < 16u) { - std::fprintf(stderr, "invalid size in --sizes (must be >= 16): %s\n", part.c_str()); - return false; - } - opt.sizes.push_back(sz); - if (comma == std::string_view::npos) break; - sv.remove_prefix(comma + 1u); - } - if (opt.sizes.empty()) return false; - } else { - std::fprintf(stderr, "unknown option: %.*s\n", int(arg.size()), arg.data()); - return false; - } - } - return true; -} - -const char* device_type_name(VkPhysicalDeviceType t) { - switch (t) { - case VK_PHYSICAL_DEVICE_TYPE_DISCRETE_GPU: return "discrete"; - case VK_PHYSICAL_DEVICE_TYPE_INTEGRATED_GPU: return "integrated"; - case VK_PHYSICAL_DEVICE_TYPE_VIRTUAL_GPU: return "virtual"; - case VK_PHYSICAL_DEVICE_TYPE_CPU: return "cpu"; - default: return "other"; - } -} - -std::string format_mem_flags(VkMemoryPropertyFlags flags) { - std::string s; - auto add = [&](VkMemoryPropertyFlags bit, const char* name) { - if ((flags & bit) == bit) { - if (!s.empty()) s += '|'; - s += name; - } - }; - add(VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, "DEVICE_LOCAL"); - add(VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT, "HOST_VISIBLE"); - add(VK_MEMORY_PROPERTY_HOST_COHERENT_BIT, "HOST_COHERENT"); - add(VK_MEMORY_PROPERTY_HOST_CACHED_BIT, "HOST_CACHED"); - return s.empty() ? "NONE" : s; -} - -std::uint32_t pick_memory_type_exact_or_fallback(const VkPhysicalDeviceMemoryProperties& mp, std::uint32_t type_bits, - VkMemoryPropertyFlags req, VkMemoryPropertyFlags avoid) { - for (std::uint32_t i = 0; i < mp.memoryTypeCount; ++i) { - if (!(type_bits & (1u << i))) continue; - const VkMemoryPropertyFlags f = mp.memoryTypes[i].propertyFlags; - if ((f & req) == req && (f & avoid) == 0u) return i; - } - for (std::uint32_t i = 0; i < mp.memoryTypeCount; ++i) { - if (!(type_bits & (1u << i))) continue; - if ((mp.memoryTypes[i].propertyFlags & req) == req) return i; - } - return 0xFFFFFFFFu; -} - -struct GpuBuffer { - VkBuffer buffer = VK_NULL_HANDLE; - VkDeviceMemory memory = VK_NULL_HANDLE; - VkDeviceSize size = 0; - std::uint32_t memory_type_index = 0xFFFFFFFFu; - void* mapped = nullptr; -}; - -struct MemoryPlacement { - const char* label; - std::uint32_t memory_type_index; - std::uint32_t heap_index; - VkDeviceSize heap_size; - VkMemoryPropertyFlags flags; - bool use_staging; -}; - -int run_self_test() { - const char* const device_args[] = {"vk_descriptor_bench", "--device", "4294967295"}; - Options device_options; - bool show_help = false; - if (device_options.device_index.has_value() || !parse_args(3, device_args, device_options, show_help) || - device_options.device_index != std::numeric_limits::max()) { - std::fprintf(stderr, "self-test: explicit device index became automatic selection\n"); - return 1; - } - - { - const char* const ok_args[] = {"vk_descriptor_bench", "--warmup-ms", "0"}; - const char* const bad_args[] = {"vk_descriptor_bench", "--warmup-ms", "-1"}; - const char* const quick_args[] = {"vk_descriptor_bench", "--quick"}; - Options o_ok, o_bad, o_quick, o_default; - bool h = false; - if (o_default.warmup_ms != 300.0 || !parse_args(3, ok_args, o_ok, h) || o_ok.warmup_ms != 0.0 || - parse_args(3, bad_args, o_bad, h) || !parse_args(2, quick_args, o_quick, h) || o_quick.warmup_ms != 0.0) { - std::fprintf(stderr, "self-test: --warmup-ms parsing or its default is wrong\n"); - return 1; - } - } - - const struct { - const char* name; - ShaderKind kind; - } modules[3] = { - {"baseline", ShaderKind::Baseline}, - {"single", ShaderKind::SingleLookup}, - {"pair_ts", ShaderKind::PairTSLookup}, - }; - for (const auto& m : modules) { - const auto spv = build_bench_spv(m.kind); - if (!check_spv_structure(spv, m.name)) return 1; - } - - TableDataset ds; - if (!build_dataset(1000u, ds)) return 1; - if (ds.entry_count != 1000u || ds.capacity < 2048u || ds.max_probes > kDescriptorProbes) { - std::fprintf(stderr, "self-test: unexpected 1k table metrics\n"); - return 1; - } - const ScenarioSpec single_sc{"self_test", ShaderKind::SingleLookup, false, true, 0u, 0u, 1u, false, - ScenarioSpec::Bank::TSharp, 1.0}; - const PushConstants pc = make_push_constants(single_sc, ds, 8u); - if (eval_invocation_oracle(single_sc, ds, pc, 0u) == kFnvOffsetBasis) { - std::fprintf(stderr, "self-test: degenerate checksum on lane 0\n"); - return 1; - } - const ScenarioSpec hot_sc{"hot", ShaderKind::SingleLookup, false, false, 0u, 0u, 0u, false, - ScenarioSpec::Bank::TSharp, 1.0}; - const ScenarioSpec pair_sc{"pair", ShaderKind::PairTSLookup, false, true, 0u, 0u, 1u, false, - ScenarioSpec::Bank::TSharp, 2.0}; - const std::uint32_t hot_u = count_unique_keys(hot_sc, ds, make_push_constants(hot_sc, ds, 64u), 4096u); - const std::uint32_t q_u = count_unique_keys(single_sc, ds, make_push_constants(single_sc, ds, 4u), 16u); - const std::uint32_t full_u = count_unique_keys(single_sc, ds, make_push_constants(single_sc, ds, 64u), 4096u); - const std::uint32_t pair_u = count_unique_keys(pair_sc, ds, make_push_constants(pair_sc, ds, 64u), 4096u); - if (hot_u != 1u || q_u != 64u || full_u != ds.t_count || pair_u != ds.entry_count) { - std::fprintf(stderr, "self-test: unexpected unique_keys (%u, %u, %u, %u)\n", hot_u, q_u, full_u, pair_u); - return 1; - } - std::printf("vk_descriptor_bench self-test passed (1k table cap=%u, load=%.1f%%, mean_probes=%.3f, max=%u)\n", - ds.capacity, ds.load_pct, ds.mean_probes, ds.max_probes); - return 0; -} - -int run_dump_spv(const std::string& prefix) { - const struct { - const char* suffix; - ShaderKind kind; - } items[3] = { - {"_baseline.spv", ShaderKind::Baseline}, - {"_single.spv", ShaderKind::SingleLookup}, - {"_pair_ts.spv", ShaderKind::PairTSLookup}, - }; - for (const auto& item : items) { - const std::string path = prefix + item.suffix; - const auto spv = build_bench_spv(item.kind); - if (!check_spv_structure(spv, path.c_str()) || !write_spv_file(path, spv)) return 1; - std::printf("wrote %s (%zu bytes)\n", path.c_str(), spv.size() * sizeof(std::uint32_t)); - } - return 0; -} - -} // namespace - -int main(int argc, char** argv) { - Options opt; - bool show_help = false; - if (!parse_args(argc, argv, opt, show_help)) { - print_usage(); - return 2; - } - if (show_help) { - print_usage(); - return 0; - } - if (opt.self_test) return run_self_test(); - if (!opt.dump_spv_prefix.empty()) return run_dump_spv(opt.dump_spv_prefix); - - const PFN_vkGetInstanceProcAddr gipa = load_vulkan(); - if (!gipa) return 1; - -#define LI(n) const auto n = reinterpret_cast(gipa(inst, #n)) - VkInstance inst = VK_NULL_HANDLE; - LI(vkCreateInstance); - LI(vkEnumerateInstanceLayerProperties); - if (!vkCreateInstance) return 1; - - const char* val_env = std::getenv("LEONIDA_VK_VALIDATION"); - const bool validation = val_env && std::strcmp(val_env, "0") != 0 && *val_env != '\0'; - const char* layer = "VK_LAYER_KHRONOS_validation"; - const char* debug_utils = VK_EXT_DEBUG_UTILS_EXTENSION_NAME; - - VkDebugUtilsMessengerCreateInfoEXT messenger_info{VK_STRUCTURE_TYPE_DEBUG_UTILS_MESSENGER_CREATE_INFO_EXT}; - messenger_info.messageSeverity = - VK_DEBUG_UTILS_MESSAGE_SEVERITY_WARNING_BIT_EXT | VK_DEBUG_UTILS_MESSAGE_SEVERITY_ERROR_BIT_EXT; - messenger_info.messageType = - VK_DEBUG_UTILS_MESSAGE_TYPE_GENERAL_BIT_EXT | VK_DEBUG_UTILS_MESSAGE_TYPE_VALIDATION_BIT_EXT; - messenger_info.pfnUserCallback = on_debug_message; - - VkApplicationInfo app{VK_STRUCTURE_TYPE_APPLICATION_INFO}; - app.pApplicationName = "vk_descriptor_bench"; - app.apiVersion = VK_API_VERSION_1_2; - - VkInstanceCreateInfo ici{VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO}; - ici.pApplicationInfo = &app; - if (validation) { - std::uint32_t layer_count = 0; - vkEnumerateInstanceLayerProperties(&layer_count, nullptr); - std::vector layers(layer_count); - vkEnumerateInstanceLayerProperties(&layer_count, layers.data()); - bool found = false; - for (const auto& lp : layers) { - if (std::strcmp(lp.layerName, layer) == 0) found = true; - } - if (!found) { - std::fprintf(stderr, "LEONIDA_VK_VALIDATION is set but %s is not installed\n", layer); - return 1; - } - ici.pNext = &messenger_info; - ici.enabledLayerCount = 1; - ici.ppEnabledLayerNames = &layer; - ici.enabledExtensionCount = 1; - ici.ppEnabledExtensionNames = &debug_utils; - } - CHECK_VK(vkCreateInstance(&ici, nullptr, &inst)); - - LI(vkDestroyInstance); - LI(vkEnumeratePhysicalDevices); - LI(vkGetPhysicalDeviceProperties); - LI(vkGetPhysicalDeviceProperties2); - LI(vkGetPhysicalDeviceQueueFamilyProperties); - LI(vkGetPhysicalDeviceMemoryProperties); - LI(vkCreateDevice); - LI(vkGetDeviceProcAddr); - - VkDebugUtilsMessengerEXT messenger = VK_NULL_HANDLE; - PFN_vkDestroyDebugUtilsMessengerEXT vkDestroyDebugUtilsMessengerEXT = nullptr; - if (validation) { - LI(vkCreateDebugUtilsMessengerEXT); - vkDestroyDebugUtilsMessengerEXT = - reinterpret_cast(gipa(inst, "vkDestroyDebugUtilsMessengerEXT")); - CHECK_VK(vkCreateDebugUtilsMessengerEXT(inst, &messenger_info, nullptr, &messenger)); - } - - auto destroy_instance = [&]() { - if (validation && messenger && vkDestroyDebugUtilsMessengerEXT) { - vkDestroyDebugUtilsMessengerEXT(inst, messenger, nullptr); - } - if (inst && vkDestroyInstance) vkDestroyInstance(inst, nullptr); - }; - - std::uint32_t pd_count = 0; - vkEnumeratePhysicalDevices(inst, &pd_count, nullptr); - std::vector pds(pd_count); - if (pd_count > 0) vkEnumeratePhysicalDevices(inst, &pd_count, pds.data()); - - if (opt.list_devices) { - for (std::uint32_t i = 0; i < pd_count; ++i) { - VkPhysicalDeviceProperties p{}; - vkGetPhysicalDeviceProperties(pds[i], &p); - std::printf("[%u] %s (%s, vendor=0x%04x, device=0x%04x, api=%u.%u.%u)\n", i, p.deviceName, - device_type_name(p.deviceType), p.vendorID, p.deviceID, VK_API_VERSION_MAJOR(p.apiVersion), - VK_API_VERSION_MINOR(p.apiVersion), VK_API_VERSION_PATCH(p.apiVersion)); - } - destroy_instance(); - return 0; - } - - auto find_compute_queue = [&](VkPhysicalDevice cand, std::uint32_t& out_qi, - std::uint32_t& out_ts_bits) -> bool { - std::uint32_t qn = 0; - vkGetPhysicalDeviceQueueFamilyProperties(cand, &qn, nullptr); - std::vector qf(qn); - vkGetPhysicalDeviceQueueFamilyProperties(cand, &qn, qf.data()); - for (std::uint32_t i = 0; i < qn; ++i) { - if (qf[i].queueFlags & VK_QUEUE_COMPUTE_BIT) { - out_qi = i; - out_ts_bits = qf[i].timestampValidBits; - return true; - } - } - return false; - }; - - VkPhysicalDevice pd = VK_NULL_HANDLE; - VkPhysicalDeviceProperties pd_props{}; - std::uint32_t qi = 0; - std::uint32_t ts_valid_bits = 0; - bool filtered_out = false; // LEONIDA_VK_DEVICE left a device out - if (opt.device_index.has_value()) { - const std::uint32_t device_index = *opt.device_index; - if (device_index >= pd_count) { - std::fprintf(stderr, "invalid --device index %u (found %u devices)\n", device_index, pd_count); - destroy_instance(); - return 2; - } - VkPhysicalDevice cand = pds[device_index]; - VkPhysicalDeviceProperties p{}; - vkGetPhysicalDeviceProperties(cand, &p); - if (p.apiVersion < VK_API_VERSION_1_1 || !find_compute_queue(cand, qi, ts_valid_bits)) { - std::printf("unsupported: selected device lacks Vulkan 1.1 or compute queue\n"); - destroy_instance(); - return kUnsupportedExit; - } - pd = cand; - pd_props = p; - } else { - auto score = [](VkPhysicalDeviceType t, std::uint32_t vendor) -> int { - return leonida::vk_test::device_rank(t, vendor); - }; - int best_score = -1; - for (VkPhysicalDevice cand : pds) { - VkPhysicalDeviceProperties p{}; - vkGetPhysicalDeviceProperties(cand, &p); - // LEONIDA_VK_DEVICE names the GPU, as in the other harnesses (vk_device_pick.h, docs/testing.md). - if (!leonida::vulkan_device_wanted(p.deviceName)) { - filtered_out = true; - continue; - } - std::uint32_t c_qi = 0, c_ts = 0; - if (p.apiVersion < VK_API_VERSION_1_1 || !find_compute_queue(cand, c_qi, c_ts)) continue; - const int s = score(p.deviceType, p.vendorID); - if (s > best_score) { - best_score = s; - pd = cand; - pd_props = p; - qi = c_qi; - ts_valid_bits = c_ts; - } - } - } - - if (!pd && filtered_out) { // a filter that matches no usable device fails the run, it does not skip - leonida::vk_test::report_no_device(); - destroy_instance(); - return 1; - } - if (!pd) { - std::printf("unsupported: no Vulkan 1.1+ compute physical device\n"); - destroy_instance(); - return kUnsupportedExit; - } - - if (opt.groups > pd_props.limits.maxComputeWorkGroupCount[0]) { - std::fprintf(stderr, "--groups %u exceeds maxComputeWorkGroupCount[0] (%u)\n", opt.groups, - pd_props.limits.maxComputeWorkGroupCount[0]); - destroy_instance(); - return 2; - } - - std::uint32_t subgroup_size = 0; - std::string driver_desc = "unknown"; - if (vkGetPhysicalDeviceProperties2) { - VkPhysicalDeviceSubgroupProperties sg_props{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SUBGROUP_PROPERTIES}; - VkPhysicalDeviceVulkan12Properties vk12_props{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_2_PROPERTIES}; - VkPhysicalDeviceProperties2 props2{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROPERTIES_2}; - props2.pNext = &sg_props; - if (pd_props.apiVersion >= VK_API_VERSION_1_2) { - sg_props.pNext = &vk12_props; - } - vkGetPhysicalDeviceProperties2(pd, &props2); - subgroup_size = sg_props.subgroupSize; - if (pd_props.apiVersion >= VK_API_VERSION_1_2 && vk12_props.driverName[0] != '\0') { - driver_desc = vk12_props.driverName; - if (vk12_props.driverInfo[0] != '\0') { - driver_desc += " ("; - driver_desc += vk12_props.driverInfo; - driver_desc += ')'; - } - } - } - - const float q_prio = 1.0f; - VkDeviceQueueCreateInfo qci{VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO}; - qci.queueFamilyIndex = qi; - qci.queueCount = 1; - qci.pQueuePriorities = &q_prio; - VkDeviceCreateInfo dci{VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO}; - dci.queueCreateInfoCount = 1; - dci.pQueueCreateInfos = &qci; - - VkDevice dev = VK_NULL_HANDLE; - CHECK_VK(vkCreateDevice(pd, &dci, nullptr, &dev)); - -#define LD(n) const auto n = reinterpret_cast(vkGetDeviceProcAddr(dev, #n)) - LD(vkGetDeviceQueue); - LD(vkDeviceWaitIdle); - LD(vkDestroyDevice); - LD(vkCreateBuffer); - LD(vkDestroyBuffer); - LD(vkGetBufferMemoryRequirements); - LD(vkAllocateMemory); - LD(vkFreeMemory); - LD(vkBindBufferMemory); - LD(vkMapMemory); - LD(vkCreateShaderModule); - LD(vkDestroyShaderModule); - LD(vkCreateDescriptorSetLayout); - LD(vkDestroyDescriptorSetLayout); - LD(vkCreatePipelineLayout); - LD(vkDestroyPipelineLayout); - LD(vkCreateComputePipelines); - LD(vkDestroyPipeline); - LD(vkCreateDescriptorPool); - LD(vkDestroyDescriptorPool); - LD(vkAllocateDescriptorSets); - LD(vkUpdateDescriptorSets); - LD(vkCreateCommandPool); - LD(vkDestroyCommandPool); - LD(vkAllocateCommandBuffers); - LD(vkBeginCommandBuffer); - LD(vkEndCommandBuffer); - LD(vkResetCommandBuffer); - LD(vkCmdBindPipeline); - LD(vkCmdBindDescriptorSets); - LD(vkCmdPushConstants); - LD(vkCmdDispatch); - LD(vkCmdCopyBuffer); - LD(vkCmdPipelineBarrier); - LD(vkCreateFence); - LD(vkDestroyFence); - LD(vkWaitForFences); - LD(vkResetFences); - LD(vkQueueSubmit); - LD(vkCreateQueryPool); - LD(vkDestroyQueryPool); - LD(vkGetQueryPoolResults); - LD(vkCmdResetQueryPool); - LD(vkCmdWriteTimestamp); -#undef LD - - VkQueue queue = VK_NULL_HANDLE; - vkGetDeviceQueue(dev, qi, 0, &queue); - VkPhysicalDeviceMemoryProperties mp{}; - vkGetPhysicalDeviceMemoryProperties(pd, &mp); - - const bool use_gpu_timestamps = (ts_valid_bits > 0u) && (pd_props.limits.timestampPeriod > 0.0f) && - vkCreateQueryPool && vkCmdResetQueryPool && vkCmdWriteTimestamp && - vkGetQueryPoolResults; - - VkDescriptorSetLayout dsl = VK_NULL_HANDLE; - VkPipelineLayout pl = VK_NULL_HANDLE; - VkDescriptorPool dpool = VK_NULL_HANDLE; - VkDescriptorSet dset = VK_NULL_HANDLE; - VkCommandPool cpool = VK_NULL_HANDLE; - VkCommandBuffer util_cmd = VK_NULL_HANDLE; - VkCommandBuffer bench_cmd = VK_NULL_HANDLE; - VkFence fence = VK_NULL_HANDLE; - VkQueryPool qpool = VK_NULL_HANDLE; - std::array sms{}; - std::array pipes{}; - - auto destroy_buf = [&](GpuBuffer& b) { - if (b.buffer) vkDestroyBuffer(dev, b.buffer, nullptr); - if (b.memory) vkFreeMemory(dev, b.memory, nullptr); - b = GpuBuffer{}; - }; - - auto cleanup_device = [&]() { - if (dev && vkDeviceWaitIdle) vkDeviceWaitIdle(dev); - for (VkPipeline p : pipes) { - if (p) vkDestroyPipeline(dev, p, nullptr); - } - for (VkShaderModule m : sms) { - if (m) vkDestroyShaderModule(dev, m, nullptr); - } - if (qpool) vkDestroyQueryPool(dev, qpool, nullptr); - if (fence) vkDestroyFence(dev, fence, nullptr); - if (cpool) vkDestroyCommandPool(dev, cpool, nullptr); - if (dpool) vkDestroyDescriptorPool(dev, dpool, nullptr); - if (pl) vkDestroyPipelineLayout(dev, pl, nullptr); - if (dsl) vkDestroyDescriptorSetLayout(dev, dsl, nullptr); - if (dev) vkDestroyDevice(dev, nullptr); - destroy_instance(); - }; - - // Set 0 bindings: 0 = keys_buf, 2 = desc_map, 3 = out_buf - const std::array dsl_bindings{{ - {0u, VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, 1u, VK_SHADER_STAGE_COMPUTE_BIT, nullptr}, - {2u, VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, 1u, VK_SHADER_STAGE_COMPUTE_BIT, nullptr}, - {3u, VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, 1u, VK_SHADER_STAGE_COMPUTE_BIT, nullptr}, - }}; - VkDescriptorSetLayoutCreateInfo dsli{VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO}; - dsli.bindingCount = static_cast(dsl_bindings.size()); - dsli.pBindings = dsl_bindings.data(); - if (vkCreateDescriptorSetLayout(dev, &dsli, nullptr, &dsl) != VK_SUCCESS) { - cleanup_device(); - return 1; - } - - const VkPushConstantRange pcr{VK_SHADER_STAGE_COMPUTE_BIT, 0u, static_cast(sizeof(PushConstants))}; - VkPipelineLayoutCreateInfo pli{VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO}; - pli.setLayoutCount = 1u; - pli.pSetLayouts = &dsl; - pli.pushConstantRangeCount = 1u; - pli.pPushConstantRanges = &pcr; - if (vkCreatePipelineLayout(dev, &pli, nullptr, &pl) != VK_SUCCESS) { - cleanup_device(); - return 1; - } - - const std::array kinds{ShaderKind::Baseline, ShaderKind::SingleLookup, ShaderKind::PairTSLookup}; - for (std::size_t i = 0; i < kinds.size(); ++i) { - const auto spv = build_bench_spv(kinds[i]); - VkShaderModuleCreateInfo smi{VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO}; - smi.codeSize = spv.size() * sizeof(std::uint32_t); - smi.pCode = spv.data(); - if (vkCreateShaderModule(dev, &smi, nullptr, &sms[i]) != VK_SUCCESS) { - cleanup_device(); - return 1; - } - VkComputePipelineCreateInfo cpci{VK_STRUCTURE_TYPE_COMPUTE_PIPELINE_CREATE_INFO}; - cpci.stage.sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO; - cpci.stage.stage = VK_SHADER_STAGE_COMPUTE_BIT; - cpci.stage.module = sms[i]; - cpci.stage.pName = "main"; - cpci.layout = pl; - if (vkCreateComputePipelines(dev, VK_NULL_HANDLE, 1u, &cpci, nullptr, &pipes[i]) != VK_SUCCESS) { - cleanup_device(); - return 1; - } - } - - const VkDescriptorPoolSize pool_size{VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, 3u}; - VkDescriptorPoolCreateInfo dpi{VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO}; - dpi.maxSets = 1u; - dpi.poolSizeCount = 1u; - dpi.pPoolSizes = &pool_size; - if (vkCreateDescriptorPool(dev, &dpi, nullptr, &dpool) != VK_SUCCESS) { - cleanup_device(); - return 1; - } - VkDescriptorSetAllocateInfo dsai{VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO}; - dsai.descriptorPool = dpool; - dsai.descriptorSetCount = 1u; - dsai.pSetLayouts = &dsl; - if (vkAllocateDescriptorSets(dev, &dsai, &dset) != VK_SUCCESS) { - cleanup_device(); - return 1; - } - - VkCommandPoolCreateInfo cpci{VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO}; - cpci.flags = VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT; - cpci.queueFamilyIndex = qi; - if (vkCreateCommandPool(dev, &cpci, nullptr, &cpool) != VK_SUCCESS) { - cleanup_device(); - return 1; - } - VkCommandBuffer cmds[2] = {}; - VkCommandBufferAllocateInfo cbai{VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO}; - cbai.commandPool = cpool; - cbai.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY; - cbai.commandBufferCount = 2u; - if (vkAllocateCommandBuffers(dev, &cbai, cmds) != VK_SUCCESS) { - cleanup_device(); - return 1; - } - util_cmd = cmds[0]; - bench_cmd = cmds[1]; - - const VkFenceCreateInfo fci{VK_STRUCTURE_TYPE_FENCE_CREATE_INFO, nullptr, 0u}; - if (vkCreateFence(dev, &fci, nullptr, &fence) != VK_SUCCESS) { - cleanup_device(); - return 1; - } - if (use_gpu_timestamps) { - VkQueryPoolCreateInfo qpi{VK_STRUCTURE_TYPE_QUERY_POOL_CREATE_INFO}; - qpi.queryType = VK_QUERY_TYPE_TIMESTAMP; - qpi.queryCount = 2u; - if (vkCreateQueryPool(dev, &qpi, nullptr, &qpool) != VK_SUCCESS) { - cleanup_device(); - return 1; - } - } - - auto alloc_buffer_mt = [&](VkDeviceSize bytes, VkBufferUsageFlags usage, std::uint32_t mt_idx, bool map_mem, - GpuBuffer& out_buf) -> bool { - out_buf = GpuBuffer{}; - out_buf.size = bytes; - VkBufferCreateInfo bci{VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO}; - bci.size = bytes; - bci.usage = usage; - // Every failure says which call failed and with what result, so a run that stops is never silent. - if (const VkResult r = vkCreateBuffer(dev, &bci, nullptr, &out_buf.buffer); r != VK_SUCCESS) { - std::fprintf(stderr, "vkCreateBuffer (%llu bytes) failed: VkResult %d\n", - static_cast(bytes), static_cast(r)); - return false; - } - VkMemoryRequirements mr{}; - vkGetBufferMemoryRequirements(dev, out_buf.buffer, &mr); - if (mt_idx >= mp.memoryTypeCount || !(mr.memoryTypeBits & (1u << mt_idx))) { - std::fprintf(stderr, "memory type %u is not allowed for this buffer (memoryTypeBits 0x%x)\n", mt_idx, - mr.memoryTypeBits); - destroy_buf(out_buf); - return false; - } - out_buf.memory_type_index = mt_idx; - VkMemoryAllocateInfo mai{VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO}; - mai.allocationSize = mr.size; - mai.memoryTypeIndex = mt_idx; - if (const VkResult r = vkAllocateMemory(dev, &mai, nullptr, &out_buf.memory); r != VK_SUCCESS) { - std::fprintf(stderr, "vkAllocateMemory (%llu bytes, memory type %u) failed: VkResult %d\n", - static_cast(mr.size), mt_idx, static_cast(r)); - out_buf.memory = VK_NULL_HANDLE; - destroy_buf(out_buf); - return false; - } - if (const VkResult r = vkBindBufferMemory(dev, out_buf.buffer, out_buf.memory, 0u); r != VK_SUCCESS) { - std::fprintf(stderr, "vkBindBufferMemory failed: VkResult %d\n", static_cast(r)); - destroy_buf(out_buf); - return false; - } - if (map_mem) { - if (const VkResult r = vkMapMemory(dev, out_buf.memory, 0u, bytes, 0u, &out_buf.mapped); r != VK_SUCCESS) { - std::fprintf(stderr, "vkMapMemory (%llu bytes) failed: VkResult %d\n", - static_cast(bytes), static_cast(r)); - destroy_buf(out_buf); - return false; - } - } - return true; - }; - - auto alloc_typed_buffer = [&](VkDeviceSize bytes, VkBufferUsageFlags usage, VkMemoryPropertyFlags req, - VkMemoryPropertyFlags avoid, bool map_mem, GpuBuffer& out_buf) -> bool { - VkBuffer probe = VK_NULL_HANDLE; - VkBufferCreateInfo bci{VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO}; - bci.size = bytes; - bci.usage = usage; - if (vkCreateBuffer(dev, &bci, nullptr, &probe) != VK_SUCCESS) return false; - VkMemoryRequirements mr{}; - vkGetBufferMemoryRequirements(dev, probe, &mr); - vkDestroyBuffer(dev, probe, nullptr); - const std::uint32_t mt_idx = pick_memory_type_exact_or_fallback(mp, mr.memoryTypeBits, req, avoid); - return alloc_buffer_mt(bytes, usage, mt_idx, map_mem, out_buf); - }; - - auto submit_and_wait = [&](VkCommandBuffer cmd) -> bool { - VkResult r = vkResetFences(dev, 1u, &fence); - if (r != VK_SUCCESS) { - std::fprintf(stderr, "FAILED vkResetFences -> %d\n", int(r)); - return false; - } - VkSubmitInfo si{VK_STRUCTURE_TYPE_SUBMIT_INFO}; - si.commandBufferCount = 1u; - si.pCommandBuffers = &cmd; - r = vkQueueSubmit(queue, 1u, &si, fence); - if (r != VK_SUCCESS) { - std::fprintf(stderr, "FAILED vkQueueSubmit -> %d\n", int(r)); - return false; - } - r = vkWaitForFences(dev, 1u, &fence, VK_TRUE, std::numeric_limits::max()); - if (r != VK_SUCCESS) { - std::fprintf(stderr, "FAILED vkWaitForFences -> %d\n", int(r)); - return false; - } - return true; - }; - - auto upload_via_staging = [&](const void* src_data, VkDeviceSize bytes, GpuBuffer& dst_buf) -> bool { - GpuBuffer stage{}; - if (!alloc_typed_buffer(bytes, VK_BUFFER_USAGE_TRANSFER_SRC_BIT, - VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT, 0u, true, - stage)) { - return false; - } - std::memcpy(stage.mapped, src_data, static_cast(bytes)); - - if (vkResetCommandBuffer(util_cmd, 0u) != VK_SUCCESS) { - destroy_buf(stage); - return false; - } - VkCommandBufferBeginInfo bi{VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO}; - bi.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT; - if (vkBeginCommandBuffer(util_cmd, &bi) != VK_SUCCESS) { - destroy_buf(stage); - return false; - } - const VkBufferCopy copy{0u, 0u, bytes}; - vkCmdCopyBuffer(util_cmd, stage.buffer, dst_buf.buffer, 1u, ©); - VkMemoryBarrier mb{VK_STRUCTURE_TYPE_MEMORY_BARRIER}; - mb.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT; - mb.dstAccessMask = VK_ACCESS_SHADER_READ_BIT; - vkCmdPipelineBarrier(util_cmd, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, 0u, 1u, &mb, - 0u, nullptr, 0u, nullptr); - if (vkEndCommandBuffer(util_cmd) != VK_SUCCESS || !submit_and_wait(util_cmd)) { - destroy_buf(stage); - return false; - } - destroy_buf(stage); - return true; - }; - - const std::uint32_t total_invocations = opt.groups * kWorkgroupSize; - const VkDeviceSize out_bytes = static_cast(total_invocations) * sizeof(std::uint32_t); - - // Output buffer (device local when available) + host readback staging buffer - GpuBuffer out_buf{}; - GpuBuffer readback_buf{}; - if (!alloc_typed_buffer(out_bytes, VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_SRC_BIT, - VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT, false, - out_buf) || - !alloc_typed_buffer(out_bytes, VK_BUFFER_USAGE_TRANSFER_DST_BIT, - VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT, 0u, true, - readback_buf)) { - destroy_buf(out_buf); - destroy_buf(readback_buf); - cleanup_device(); - return 1; - } - - auto cleanup_all = [&](GpuBuffer& a, GpuBuffer& b) { - destroy_buf(a); - destroy_buf(b); - destroy_buf(out_buf); - destroy_buf(readback_buf); - cleanup_device(); - }; - - const double total_single_lookups = static_cast(total_invocations) * static_cast(opt.iters); - const std::uint64_t ts_mask = - (ts_valid_bits == 64u) ? ~0ULL : (ts_valid_bits == 0u ? 0ULL : ((1ULL << ts_valid_bits) - 1ULL)); - - if (!opt.csv) { - std::printf("device: %s (%s, vendor=0x%04x, device=0x%04x, subgroup=%u, driver=%s)\n", pd_props.deviceName, - device_type_name(pd_props.deviceType), pd_props.vendorID, pd_props.deviceID, subgroup_size, - driver_desc.c_str()); - if (use_gpu_timestamps) { - std::printf("timing: Vulkan GPU timestamps (valid_bits=%u, period=%.3f ns); validation=%s\n", ts_valid_bits, - pd_props.limits.timestampPeriod, validation ? "on" : "off"); - } else { - std::printf("timing: host wall-clock fallback; validation=%s\n", validation ? "on" : "off"); - } - std::printf("dispatch: %u workgroups x %u threads = %u invocations x %u iters = %.2fM single / %.2fM pair lookups " - "(warmup=%u, reps=%u)\n", - opt.groups, kWorkgroupSize, total_invocations, opt.iters, total_single_lookups / 1e6, - (total_single_lookups * 2.0) / 1e6, opt.warmup, opt.reps); - } else { - std::printf("# device,%s,%s\n", pd_props.deviceName, driver_desc.c_str()); - std::printf("entries,capacity,load_pct,size_bytes,mean_probes,max_probes,placement,mem_type,flags,scenario," - "groups,iters,reps,unique_keys,med_ms,min_ms,max_ms,us_per_1m_lk,net_us_per_1m_lk,glk_per_s,timing_status\n"); - } - - const std::array scenarios{{ - {"baseline_uniform", ShaderKind::Baseline, false, true, 0u, 0u, 1u, false, ScenarioSpec::Bank::TSharp, 0.0}, - {"baseline_divergent", ShaderKind::Baseline, true, false, 64u, 1u, 1u, false, ScenarioSpec::Bank::TSharp, 0.0}, - {"uniform_hot_tsharp", ShaderKind::SingleLookup, false, false, 0u, 0u, 0u, false, ScenarioSpec::Bank::TSharp, - 1.0}, - {"uniform_tsharp_hit", ShaderKind::SingleLookup, false, true, 0u, 0u, 1u, false, ScenarioSpec::Bank::TSharp, - 1.0}, - {"uniform_ssharp_hit", ShaderKind::SingleLookup, false, true, 0u, 0u, 1u, false, ScenarioSpec::Bank::SSharp, - 1.0}, - {"uniform_pair_ts", ShaderKind::PairTSLookup, false, true, 0u, 0u, 1u, false, ScenarioSpec::Bank::TSharp, 2.0}, - {"uniform_miss", ShaderKind::SingleLookup, false, true, 0u, 0u, 1u, false, ScenarioSpec::Bank::Miss, 1.0}, - {"divergent_tsharp_hit", ShaderKind::SingleLookup, true, false, 64u, 1u, 1u, false, ScenarioSpec::Bank::TSharp, - 1.0}, - {"divergent_pair_ts", ShaderKind::PairTSLookup, true, false, 64u, 1u, 1u, false, ScenarioSpec::Bank::TSharp, - 2.0}, - {"divergent_miss", ShaderKind::SingleLookup, true, false, 64u, 1u, 1u, false, ScenarioSpec::Bank::Miss, 1.0}, - {"latency_divergent", ShaderKind::SingleLookup, true, false, 64u, 1u, 1u, true, ScenarioSpec::Bank::TSharp, - 1.0}, - }}; - - bool seen_rebar = false; - for (const std::uint32_t entry_count : opt.sizes) { - TableDataset ds; - if (!build_dataset(entry_count, ds)) { - GpuBuffer unused_a{}, unused_b{}; - cleanup_all(unused_a, unused_b); - return 1; - } - const VkDeviceSize keys_bytes = static_cast(ds.keys_buf.size()) * sizeof(std::uint32_t); - const VkDeviceSize map_bytes = static_cast(ds.gpu_table.size()) * sizeof(std::uint32_t); - - if (map_bytes > pd_props.limits.maxStorageBufferRange || keys_bytes > pd_props.limits.maxStorageBufferRange) { - std::printf("unsupported: table (%llu bytes) exceeds maxStorageBufferRange (%u)\n", - static_cast(map_bytes), pd_props.limits.maxStorageBufferRange); - GpuBuffer unused_a{}, unused_b{}; - cleanup_all(unused_a, unused_b); - return kUnsupportedExit; - } - - // Upload keys_buf once per size into DEVICE_LOCAL (fallback HOST_VISIBLE). - GpuBuffer keys_buf{}; - GpuBuffer map_buf{}; - if (!alloc_typed_buffer(keys_bytes, VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT, - VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT, false, - keys_buf) || - !upload_via_staging(ds.keys_buf.data(), keys_bytes, keys_buf)) { - cleanup_all(keys_buf, map_buf); - return 1; - } - - // Query desc_map memoryRequirements to discover valid placements. - std::uint32_t map_type_bits = 0; - { - VkBuffer probe = VK_NULL_HANDLE; - VkBufferCreateInfo bci{VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO}; - bci.size = map_bytes; - bci.usage = VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT; - if (vkCreateBuffer(dev, &bci, nullptr, &probe) != VK_SUCCESS) { - cleanup_all(keys_buf, map_buf); - return 1; - } - VkMemoryRequirements mr{}; - vkGetBufferMemoryRequirements(dev, probe, &mr); - vkDestroyBuffer(dev, probe, nullptr); - map_type_bits = mr.memoryTypeBits; - } - - std::vector placements; - auto add_placement = [&](const char* label, std::uint32_t mt_idx, bool use_staging) { - if (mt_idx == 0xFFFFFFFFu) return; - for (const auto& existing : placements) { - if (existing.memory_type_index == mt_idx) { - if (!opt.csv) { - std::printf(" note: skipping placement %s (same memoryTypeIndex %u as %s)\n", label, mt_idx, - existing.label); - } - return; - } - } - const auto& mt = mp.memoryTypes[mt_idx]; - placements.push_back( - {label, mt_idx, mt.heapIndex, mp.memoryHeaps[mt.heapIndex].size, mt.propertyFlags, use_staging}); - }; - - if (opt.mem_filter == MemoryFilter::All || opt.mem_filter == MemoryFilter::Device) { - const std::uint32_t dev_mt = pick_memory_type_exact_or_fallback( - mp, map_type_bits, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT); - add_placement("device_local", dev_mt, true); - } - if (opt.mem_filter == MemoryFilter::All || opt.mem_filter == MemoryFilter::Host) { - // Exact BindlessSet::create() search order: first HOST_VISIBLE | HOST_COHERENT memory type. - const std::uint32_t bindless_mt = pick_memory_type_exact_or_fallback( - mp, map_type_bits, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT, 0u); - add_placement("host_visible", bindless_mt, false); - } - if (opt.mem_filter == MemoryFilter::All || opt.mem_filter == MemoryFilter::Rebar) { - std::uint32_t rebar_mt = 0xFFFFFFFFu; - const VkMemoryPropertyFlags want = - VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT | VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | - VK_MEMORY_PROPERTY_HOST_COHERENT_BIT; - for (std::uint32_t i = 0; i < mp.memoryTypeCount; ++i) { - if (!(map_type_bits & (1u << i))) continue; - if ((mp.memoryTypes[i].propertyFlags & want) != want) continue; - if (mp.memoryHeaps[mp.memoryTypes[i].heapIndex].size >= map_bytes * 2u) { - rebar_mt = i; - break; - } - } - if (rebar_mt != 0xFFFFFFFFu) { - seen_rebar = true; - add_placement("host_device_local", rebar_mt, false); - } - } - - if (!opt.csv) { - std::printf( - "\n=== entries=%u (T#=%u, S#=%u) | cap=%u | load=%.1f%% | size=%.2f MiB (%.1f KiB) | " - "probes mean=%.3f max=%u p1=%.1f%% ===\n", - ds.entry_count, ds.t_count, ds.s_count, ds.capacity, ds.load_pct, - static_cast(map_bytes) / (1024.0 * 1024.0), static_cast(map_bytes) / 1024.0, - ds.mean_probes, ds.max_probes, ds.probe1_pct); - } - - for (const auto& pl_cfg : placements) { - destroy_buf(map_buf); - const VkBufferUsageFlags map_usage = - VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | (pl_cfg.use_staging ? VK_BUFFER_USAGE_TRANSFER_DST_BIT : 0u); - if (!alloc_buffer_mt(map_bytes, map_usage, pl_cfg.memory_type_index, !pl_cfg.use_staging, map_buf)) { - // The ReBAR placement is optional: a driver can list a DEVICE_LOCAL | HOST_VISIBLE type yet refuse - // the allocation (RTX 4080 SUPER, Windows 617.14: VK_ERROR_OUT_OF_DEVICE_MEMORY for 160 KiB). - // Skip it, as when no such type exists, so the other placements and table sizes still run. - if (std::strcmp(pl_cfg.label, "host_device_local") == 0) { - if (!opt.csv) - std::printf(" note: skipping placement host_device_local (memory type %u can't be " - "allocated, see stderr)\n", pl_cfg.memory_type_index); - continue; - } - std::fprintf(stderr, "placement %s: allocating the %llu-byte table failed\n", pl_cfg.label, - static_cast(map_bytes)); - cleanup_all(keys_buf, map_buf); - return 1; - } - if (pl_cfg.use_staging) { - if (!upload_via_staging(ds.gpu_table.data(), map_bytes, map_buf)) { - cleanup_all(keys_buf, map_buf); - return 1; - } - } else { - std::memcpy(map_buf.mapped, ds.gpu_table.data(), static_cast(map_bytes)); - } - - const std::array buf_infos{{ - {keys_buf.buffer, 0u, keys_bytes}, - {map_buf.buffer, 0u, map_bytes}, - {out_buf.buffer, 0u, out_bytes}, - }}; - const std::array writes{{ - {VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET, nullptr, dset, 0u, 0u, 1u, - VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, nullptr, &buf_infos[0], nullptr}, - {VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET, nullptr, dset, 2u, 0u, 1u, - VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, nullptr, &buf_infos[1], nullptr}, - {VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET, nullptr, dset, 3u, 0u, 1u, - VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, nullptr, &buf_infos[2], nullptr}, - }}; - vkUpdateDescriptorSets(dev, static_cast(writes.size()), writes.data(), 0u, nullptr); - - if (!opt.csv) { - std::printf("-- placement: %s (type=%u, heap=%u %.0f MiB, flags=%s) --\n", pl_cfg.label, - pl_cfg.memory_type_index, pl_cfg.heap_index, - static_cast(pl_cfg.heap_size) / (1024.0 * 1024.0), - format_mem_flags(pl_cfg.flags).c_str()); - std::printf(" %-22s %7s %9s %9s %9s %11s %12s %9s\n", "scenario", "keys", "med_ms", "min_ms", - "max_ms", "us/1M_lk", "net_us/1M", "Glk/s"); - } - - double base_uniform_us_per_1m = 0.0; - double base_divergent_us_per_1m = 0.0; - - for (const auto& sc : scenarios) { - const VkPipeline pipe = pipes[static_cast(sc.shader)]; - - std::uint32_t eff_groups = opt.groups; - std::uint32_t eff_iters = opt.iters; - std::uint32_t eff_reps = opt.reps; - std::uint32_t eff_warmup = opt.warmup; - - // Probe slow scenarios on a small grid so heavy PCIe/sysram lookups stay well below Windows TDR. - if (opt.max_dispatch_ms > 0.0 && opt.groups > 64u) { - const std::uint32_t probe_groups = 64u; - const std::uint32_t probe_iters = std::min(opt.iters, 4u); - const PushConstants probe_pc = make_push_constants(sc, ds, probe_iters); - if (vkResetCommandBuffer(util_cmd, 0u) != VK_SUCCESS) { - cleanup_all(keys_buf, map_buf); - return 1; - } - VkCommandBufferBeginInfo bi{VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO}; - bi.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT; - if (vkBeginCommandBuffer(util_cmd, &bi) != VK_SUCCESS) { - cleanup_all(keys_buf, map_buf); - return 1; - } - if (use_gpu_timestamps) vkCmdResetQueryPool(util_cmd, qpool, 0u, 2u); - vkCmdBindPipeline(util_cmd, VK_PIPELINE_BIND_POINT_COMPUTE, pipe); - vkCmdBindDescriptorSets(util_cmd, VK_PIPELINE_BIND_POINT_COMPUTE, pl, 0u, 1u, &dset, 0u, nullptr); - vkCmdPushConstants(util_cmd, pl, VK_SHADER_STAGE_COMPUTE_BIT, 0u, - static_cast(sizeof(probe_pc)), &probe_pc); - if (use_gpu_timestamps) vkCmdWriteTimestamp(util_cmd, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, qpool, 0u); - vkCmdDispatch(util_cmd, probe_groups, 1u, 1u); - if (use_gpu_timestamps) { - vkCmdWriteTimestamp(util_cmd, VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT, qpool, 1u); - } - if (vkEndCommandBuffer(util_cmd) != VK_SUCCESS) { - cleanup_all(keys_buf, map_buf); - return 1; - } - const auto pt0 = std::chrono::steady_clock::now(); - if (!submit_and_wait(util_cmd)) { - cleanup_all(keys_buf, map_buf); - return 1; - } - const auto pt1 = std::chrono::steady_clock::now(); - double probe_ms = 0.0; - if (use_gpu_timestamps) { - std::uint64_t ts[2] = {}; - if (vkGetQueryPoolResults(dev, qpool, 0u, 2u, sizeof(ts), ts, sizeof(std::uint64_t), - VK_QUERY_RESULT_64_BIT | VK_QUERY_RESULT_WAIT_BIT) != VK_SUCCESS) { - cleanup_all(keys_buf, map_buf); - return 1; - } - const std::uint64_t ticks = (ts[1] - ts[0]) & ts_mask; - probe_ms = - static_cast(ticks) * static_cast(pd_props.limits.timestampPeriod) * 1e-6; - } else { - probe_ms = std::chrono::duration(pt1 - pt0).count(); - } - - const double est_full_ms = - std::max(0.0, probe_ms - 0.005) * - (static_cast(opt.groups) / static_cast(probe_groups)) * - (static_cast(opt.iters) / static_cast(probe_iters)); - if (est_full_ms > opt.max_dispatch_ms) { - const double target_ms = opt.max_dispatch_ms * 0.5; - const double work_scale = target_ms / est_full_ms; - const std::uint32_t min_iters = std::min(opt.iters, 4u); - const double max_iter_reduction = - static_cast(opt.iters) / static_cast(min_iters); - if (work_scale * max_iter_reduction >= 1.0) { - eff_iters = std::max( - min_iters, static_cast(std::floor(static_cast(opt.iters) * work_scale))); - } else { - eff_iters = min_iters; - const double rem_scale = work_scale * max_iter_reduction; - eff_groups = std::max( - 64u, static_cast(std::floor(static_cast(opt.groups) * rem_scale))); - } - eff_reps = std::min(opt.reps, 9u); - eff_warmup = std::min(opt.warmup, 2u); - } - } - - const PushConstants pc = make_push_constants(sc, ds, eff_iters); - const std::uint32_t eff_invocations = eff_groups * kWorkgroupSize; - const VkDeviceSize eff_out_bytes = static_cast(eff_invocations) * sizeof(std::uint32_t); - const double eff_single_lookups = static_cast(eff_invocations) * static_cast(eff_iters); - const bool was_scaled = (eff_groups != opt.groups || eff_iters != opt.iters); - const std::uint32_t unique_keys = count_unique_keys(sc, ds, pc, eff_groups); - - // Warmup + correctness verification with readback - for (std::uint32_t w = 0; w <= eff_warmup; ++w) { - const bool readback = (w == 0u); - if (vkResetCommandBuffer(util_cmd, 0u) != VK_SUCCESS) { - cleanup_all(keys_buf, map_buf); - return 1; - } - VkCommandBufferBeginInfo bi{VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO}; - bi.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT; - if (vkBeginCommandBuffer(util_cmd, &bi) != VK_SUCCESS) { - cleanup_all(keys_buf, map_buf); - return 1; - } - vkCmdBindPipeline(util_cmd, VK_PIPELINE_BIND_POINT_COMPUTE, pipe); - vkCmdBindDescriptorSets(util_cmd, VK_PIPELINE_BIND_POINT_COMPUTE, pl, 0u, 1u, &dset, 0u, nullptr); - vkCmdPushConstants(util_cmd, pl, VK_SHADER_STAGE_COMPUTE_BIT, 0u, - static_cast(sizeof(pc)), &pc); - vkCmdDispatch(util_cmd, eff_groups, 1u, 1u); - if (readback) { - VkMemoryBarrier b1{VK_STRUCTURE_TYPE_MEMORY_BARRIER}; - b1.srcAccessMask = VK_ACCESS_SHADER_WRITE_BIT; - b1.dstAccessMask = VK_ACCESS_TRANSFER_READ_BIT; - vkCmdPipelineBarrier(util_cmd, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, - VK_PIPELINE_STAGE_TRANSFER_BIT, 0u, 1u, &b1, 0u, nullptr, 0u, nullptr); - const VkBufferCopy copy{0u, 0u, eff_out_bytes}; - vkCmdCopyBuffer(util_cmd, out_buf.buffer, readback_buf.buffer, 1u, ©); - VkMemoryBarrier b2{VK_STRUCTURE_TYPE_MEMORY_BARRIER}; - b2.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT; - b2.dstAccessMask = VK_ACCESS_HOST_READ_BIT; - vkCmdPipelineBarrier(util_cmd, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_HOST_BIT, 0u, - 1u, &b2, 0u, nullptr, 0u, nullptr); - } - if (vkEndCommandBuffer(util_cmd) != VK_SUCCESS || !submit_and_wait(util_cmd)) { - cleanup_all(keys_buf, map_buf); - return 1; - } - if (readback) { - const auto* gpu_out = static_cast(readback_buf.mapped); - if (!verify_gpu_output(sc, ds, pc, gpu_out, eff_invocations)) { - cleanup_all(keys_buf, map_buf); - return 1; - } - } - } - - // Record reusable timed command buffer (dispatch + timestamps only) - if (vkResetCommandBuffer(bench_cmd, 0u) != VK_SUCCESS) { - cleanup_all(keys_buf, map_buf); - return 1; - } - { - const VkCommandBufferBeginInfo bi{VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO, nullptr, 0u, nullptr}; - if (vkBeginCommandBuffer(bench_cmd, &bi) != VK_SUCCESS) { - cleanup_all(keys_buf, map_buf); - return 1; - } - if (use_gpu_timestamps) vkCmdResetQueryPool(bench_cmd, qpool, 0u, 2u); - vkCmdBindPipeline(bench_cmd, VK_PIPELINE_BIND_POINT_COMPUTE, pipe); - vkCmdBindDescriptorSets(bench_cmd, VK_PIPELINE_BIND_POINT_COMPUTE, pl, 0u, 1u, &dset, 0u, nullptr); - vkCmdPushConstants(bench_cmd, pl, VK_SHADER_STAGE_COMPUTE_BIT, 0u, - static_cast(sizeof(pc)), &pc); - if (use_gpu_timestamps) vkCmdWriteTimestamp(bench_cmd, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, qpool, 0u); - vkCmdDispatch(bench_cmd, eff_groups, 1u, 1u); - if (use_gpu_timestamps) { - vkCmdWriteTimestamp(bench_cmd, VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT, qpool, 1u); - } - if (vkEndCommandBuffer(bench_cmd) != VK_SUCCESS) { - cleanup_all(keys_buf, map_buf); - return 1; - } - } - - // A handful of dispatches is not enough to bring the clocks up on every GPU: with --warmup 5 an idle - // RX 7600 measured the first placement ~1.8x slower than with --warmup 200, and the RTX 4050 ~1.3x - // (TEST-277). Keep running the command that is about to be timed for --warmup-ms. - if (opt.warmup_ms > 0.0) { - const auto w0 = std::chrono::steady_clock::now(); - for (;;) { - if (!submit_and_wait(bench_cmd)) { - cleanup_all(keys_buf, map_buf); - return 1; - } - const double spent = - std::chrono::duration(std::chrono::steady_clock::now() - w0).count(); - if (spent >= opt.warmup_ms) break; - } - } - - std::vector samples_ms; - samples_ms.reserve(eff_reps); - for (std::uint32_t r = 0; r < eff_reps; ++r) { - const auto t0 = std::chrono::steady_clock::now(); - if (!submit_and_wait(bench_cmd)) { - cleanup_all(keys_buf, map_buf); - return 1; - } - const auto t1 = std::chrono::steady_clock::now(); - if (use_gpu_timestamps) { - std::uint64_t ts[2] = {}; - if (vkGetQueryPoolResults(dev, qpool, 0u, 2u, sizeof(ts), ts, sizeof(std::uint64_t), - VK_QUERY_RESULT_64_BIT | VK_QUERY_RESULT_WAIT_BIT) != VK_SUCCESS) { - cleanup_all(keys_buf, map_buf); - return 1; - } - const std::uint64_t ticks = (ts[1] - ts[0]) & ts_mask; - const double ms = - static_cast(ticks) * static_cast(pd_props.limits.timestampPeriod) * 1e-6; - samples_ms.push_back(ms); - } else { - samples_ms.push_back(std::chrono::duration(t1 - t0).count()); - } - } - - std::sort(samples_ms.begin(), samples_ms.end()); - const double med_ms = samples_ms[samples_ms.size() / 2u]; - const double min_ms = samples_ms.front(); - const double max_ms = samples_ms.back(); - - const bool is_lookup = sc.lookups_per_iter > 0.0; - double& baseline_us = sc.divergent ? base_divergent_us_per_1m : base_uniform_us_per_1m; - if (!is_lookup) baseline_us = med_ms * 1e9 / eff_single_lookups; - - const bool have_times = max_ms > 0.0; - const bool have_rate = is_lookup && med_ms > 0.0; - const double total_lookups = eff_single_lookups * sc.lookups_per_iter; - const double us_per_1m = have_rate ? med_ms * 1e9 / total_lookups : 0.0; - const double net_us_per_1m = have_rate ? std::max(0.0, us_per_1m - baseline_us / sc.lookups_per_iter) : 0.0; - const double glk_s = med_ms > 1e-9 ? total_lookups / (med_ms * 1e6) : 0.0; - - const char* status = nullptr; - if (!have_times) status = use_gpu_timestamps ? "GPU timestamps did not advance" : "host clock did not advance"; - else if (med_ms == 0.0) status = "median below timer resolution"; - else if (is_lookup && baseline_us == 0.0) status = "baseline timing unavailable"; - - if (opt.csv) { - std::printf("%u,%u,%.2f,%llu,%.4f,%u,%s,%u,\"%s\",%s,%u,%u,%u,%u", ds.entry_count, ds.capacity, - ds.load_pct, static_cast(map_bytes), ds.mean_probes, ds.max_probes, - pl_cfg.label, pl_cfg.memory_type_index, format_mem_flags(pl_cfg.flags).c_str(), sc.name, - eff_groups, eff_iters, eff_reps, unique_keys); - } else { - std::printf(" %-22s %7u", sc.name, unique_keys); - } - const auto metric = [&](double value, bool available, int width, int precision, int csv_precision) { - if (opt.csv) { - std::putchar(','); - if (available) std::printf("%.*f", csv_precision, value); - } else if (available) { - std::printf(" %*.*f", width, precision, value); - } else { - std::printf(" %*s", width, "-"); - } - }; - metric(med_ms, have_times, 9, 4, 6); - metric(min_ms, have_times, 9, 4, 6); - metric(max_ms, have_times, 9, 4, 6); - metric(us_per_1m, have_rate, 11, 3, 4); - metric(net_us_per_1m, have_rate && baseline_us > 0.0, 12, 3, 4); - metric(glk_s, have_rate, 9, 2, 4); - if (opt.csv) { - std::printf(",%s", status ? status : "ok"); - } else { - if (was_scaled) std::printf(" [scaled %ux%u, n=%u]", eff_groups, eff_iters, eff_reps); - if (status) std::printf(" [%s]", status); - } - std::putchar('\n'); - std::fflush(stdout); - } - } - destroy_buf(keys_buf); - destroy_buf(map_buf); - } - - if (opt.mem_filter == MemoryFilter::Rebar && !seen_rebar) { - if (!opt.csv) { - std::printf("unsupported: no HOST_VISIBLE | DEVICE_LOCAL (ReBAR) memory type large enough for table\n"); - } - destroy_buf(out_buf); - destroy_buf(readback_buf); - cleanup_device(); - return kUnsupportedExit; - } - - destroy_buf(out_buf); - destroy_buf(readback_buf); - cleanup_device(); - - if (validation && g_validation_errors > 0u) { - std::fprintf(stderr, "%u Vulkan validation errors\n", g_validation_errors); - return 1; - } - return 0; -} diff --git a/runtime/test/vk_device_pick.h b/runtime/test/vk_device_pick.h deleted file mode 100644 index 1e1d8c502..000000000 --- a/runtime/test/vk_device_pick.h +++ /dev/null @@ -1,62 +0,0 @@ -// Chooses among enumerated Vulkan physical devices for the test harnesses. -// -// Windows can expose Mesa's Dozen (a Vulkan-on-D3D12 translation layer installed by the "OpenCL, OpenGL and Vulkan -// Compatibility Pack") next to the real GPU. Dozen reports VK_PHYSICAL_DEVICE_TYPE_DISCRETE_GPU, so the old -// "the last discrete device wins" loop picked the wrapper over the native driver and produced failures that looked -// like translator bugs (#915). Prefer a native ICD, then discrete > integrated > virtual > CPU > other, and keep the -// first device on a tie. -#pragma once - -#include - -#include "../src/vulkan_device_filter.h" - -#include -#include -#include -#include -#include - -namespace leonida::vk_test { - -// Microsoft is the vendor of the D3D12 translation layers Windows adds (Dozen and the Basic Render Driver); no -// native GPU driver uses it. Checking the vendor avoids depending on VkPhysicalDeviceDriverProperties. -inline constexpr std::uint32_t microsoft_vendor_id = leonida::microsoft_vulkan_vendor_id; - -static_assert(VK_PHYSICAL_DEVICE_TYPE_OTHER == 0 && VK_PHYSICAL_DEVICE_TYPE_INTEGRATED_GPU == 1 && - VK_PHYSICAL_DEVICE_TYPE_DISCRETE_GPU == 2 && VK_PHYSICAL_DEVICE_TYPE_VIRTUAL_GPU == 3 && - VK_PHYSICAL_DEVICE_TYPE_CPU == 4, - "vulkan_device_rank takes VkPhysicalDeviceType by value"); - -// The runtime's rank (runtime/src/vulkan_device_filter.h), so the harnesses and the runtime take the same GPU. -inline int device_rank(VkPhysicalDeviceType type, std::uint32_t vendor_id) { - return leonida::vulkan_device_rank(static_cast(type), vendor_id); -} - -// Index of the best candidate, or candidates.size() when there are none. Ties keep the earlier device. -inline std::size_t pick_device(const std::vector& candidates) { - std::size_t best = candidates.size(); - int best_rank = -1; - for (std::size_t i = 0; i < candidates.size(); ++i) { - if (!leonida::vulkan_device_wanted(candidates[i].deviceName)) continue; - const int rank = device_rank(candidates[i].deviceType, candidates[i].vendorID); - if (rank > best_rank) { - best = i; - best_rank = rank; - } - } - return best; -} - -// Why no device was chosen, naming LEONIDA_VK_DEVICE when its filter excluded every device (otherwise the list was -// empty). The tools call this instead of dereferencing a null device. -inline void report_no_device() { - const std::string filter = leonida::vulkan_device_filter(); - if (!filter.empty()) { - std::fprintf(stderr, "LEONIDA_VK_DEVICE=%s: no Vulkan physical device matches\n", filter.c_str()); - } else { - std::fprintf(stderr, "no Vulkan physical device found\n"); - } -} - -} // namespace leonida::vk_test diff --git a/runtime/test/vk_device_pick_test.cpp b/runtime/test/vk_device_pick_test.cpp deleted file mode 100644 index f4f4ba495..000000000 --- a/runtime/test/vk_device_pick_test.cpp +++ /dev/null @@ -1,121 +0,0 @@ -// CPU-only tests for the physical-device ranking the Vulkan harnesses use (#915). No Vulkan instance or GPU is -// needed: the rank is a pure function of the device type and vendor. -#include "vk_device_pick.h" - -#include -#include -#include -#include - -namespace { - -int failures = 0; - -VkPhysicalDeviceProperties device(VkPhysicalDeviceType type, std::uint32_t vendor, const char* name) { - VkPhysicalDeviceProperties properties{}; - properties.deviceType = type; - properties.vendorID = vendor; - std::snprintf(properties.deviceName, sizeof properties.deviceName, "%s", name); - return properties; -} - -void expect_index(const char* what, std::size_t got, std::size_t want) { - if (got == want) return; - std::fprintf(stderr, "FAIL %s: picked %zu, expected %zu\n", what, got, want); - ++failures; -} - -void set_filter(const char* value) { -#ifdef _WIN32 - _putenv_s("LEONIDA_VK_DEVICE", value); -#else - if (value[0] == '\0') { - unsetenv("LEONIDA_VK_DEVICE"); - } else { - setenv("LEONIDA_VK_DEVICE", value, 1); - } -#endif -} - -constexpr std::uint32_t nvidia = 0x10de; -constexpr std::uint32_t amd = 0x1002; -constexpr std::uint32_t intel = 0x8086; -constexpr std::uint32_t microsoft = leonida::vk_test::microsoft_vendor_id; - -} // namespace - -int main() { - using leonida::vk_test::pick_device; - - const char* saved = std::getenv("LEONIDA_VK_DEVICE"); - const std::string saved_value = saved ? saved : ""; - set_filter(""); - - // The enumeration from #915: native NVIDIA first, Dozen's wrapper second, Dozen's Basic Render Driver third. The - // old loop overwrote on every discrete device, so it selected index 1. - std::vector devices{ - device(VK_PHYSICAL_DEVICE_TYPE_DISCRETE_GPU, nvidia, "NVIDIA GeForce RTX 4060 Ti"), - device(VK_PHYSICAL_DEVICE_TYPE_DISCRETE_GPU, microsoft, "Microsoft Direct3D12 (NVIDIA GeForce RTX 4060 Ti)"), - device(VK_PHYSICAL_DEVICE_TYPE_CPU, microsoft, "Microsoft Direct3D12 (Microsoft Basic Render Driver)"), - }; - expect_index("native discrete before Dozen", pick_device(devices), 0); - - // Order must not matter: Dozen first, native GPU second. - std::swap(devices[0], devices[1]); - expect_index("native discrete after Dozen", pick_device(devices), 1); - - // A native integrated GPU is still a real driver and is preferred over a Dozen wrapper on a discrete card. - devices = { - device(VK_PHYSICAL_DEVICE_TYPE_DISCRETE_GPU, microsoft, "Microsoft Direct3D12 (NVIDIA GeForce RTX 4060 Ti)"), - device(VK_PHYSICAL_DEVICE_TYPE_INTEGRATED_GPU, amd, "AMD Radeon 780M"), - }; - expect_index("native integrated beats Dozen discrete", pick_device(devices), 1); - - // Among native devices, discrete wins over integrated and virtual. - devices = { - device(VK_PHYSICAL_DEVICE_TYPE_INTEGRATED_GPU, intel, "Intel UHD 770"), - device(VK_PHYSICAL_DEVICE_TYPE_DISCRETE_GPU, amd, "AMD Radeon RX 7900 XTX"), - device(VK_PHYSICAL_DEVICE_TYPE_VIRTUAL_GPU, amd, "virtual"), - }; - expect_index("native discrete wins", pick_device(devices), 1); - - // When only translator devices are present, classification still breaks the tie, and the first device wins an - // exact tie. - devices = { - device(VK_PHYSICAL_DEVICE_TYPE_CPU, microsoft, "Microsoft Direct3D12 (Microsoft Basic Render Driver)"), - device(VK_PHYSICAL_DEVICE_TYPE_DISCRETE_GPU, microsoft, "Microsoft Direct3D12 (other)"), - }; - expect_index("Dozen discrete beats Dozen CPU", pick_device(devices), 1); - - devices = { - device(VK_PHYSICAL_DEVICE_TYPE_DISCRETE_GPU, amd, "first"), - device(VK_PHYSICAL_DEVICE_TYPE_DISCRETE_GPU, amd, "second"), - }; - expect_index("tie keeps the first", pick_device(devices), 0); - - devices.clear(); - expect_index("empty list", pick_device(devices), devices.size()); - - // LEONIDA_VK_DEVICE narrows the candidates before ranking, so a match wins even when its type or vendor would - // otherwise lose, and a filter that matches nothing selects no device instead of falling back. - devices = { - device(VK_PHYSICAL_DEVICE_TYPE_DISCRETE_GPU, microsoft, "Microsoft Direct3D12 (NVIDIA GeForce RTX 4060 Ti)"), - device(VK_PHYSICAL_DEVICE_TYPE_INTEGRATED_GPU, amd, "AMD Radeon 780M"), - }; - set_filter("780m"); - expect_index("filter picks the integrated AMD", pick_device(devices), 1); - set_filter("microsoft"); - expect_index("filter picks the Dozen wrapper despite its rank", pick_device(devices), 0); - set_filter("no-such-gpu"); - expect_index("filter matches nothing", pick_device(devices), devices.size()); - set_filter(""); - - if (failures) { - std::fprintf(stderr, "%d device-pick test(s) failed\n", failures); - return 1; - } - set_filter(saved_value.c_str()); - - std::printf("device pick: all cases passed\n"); - return 0; -} diff --git a/runtime/test/vk_fence_dispatcher_sync_test.cpp b/runtime/test/vk_fence_dispatcher_sync_test.cpp deleted file mode 100644 index 56b1dd27c..000000000 --- a/runtime/test/vk_fence_dispatcher_sync_test.cpp +++ /dev/null @@ -1,371 +0,0 @@ -// FenceWaitDispatcher concurrency and device-lost regressions (runtime/src/vulkan_backend.h): -// 1. Completion callbacks in run() execute outside mutex_, so a callback can re-entrantly call -// enqueue_fence_callback() and cancel_fence_waits() without deadlocking. -// 2. Cancelled callbacks in cancel() execute outside mutex_, so a callback can re-entrantly enqueue another wait -// without deadlocking. -// 3. mark_device_lost() wakes a blocked vkWaitSemaphores() so pending waits complete and cancel()/stop() never hang. -// 4. vkGetSemaphoreCounterValue() returning VK_ERROR_DEVICE_LOST drains pending waits and marks device_lost_ instead -// of spinning forever. -// 5. cancel() blocks until a callback already dispatched for that semaphore has stopped using it. -// 6. A re-entrant cancel() for a later callback in the same ready batch skips that callback. -// Skips with exit code 77 when no Vulkan 1.3 device is available. No game data. -#include "vk_test_device.h" -#include "../src/vulkan_backend.h" - -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#define EXPECT(condition) do { \ - if (!(condition)) { std::fprintf(stderr, "line %d: %s\n", __LINE__, #condition); std::_Exit(1); } \ -} while (0) - -namespace { - -namespace driver { -PFN_vkGetDeviceProcAddr real_get_device = nullptr; -PFN_vkWaitSemaphores real_wait_semaphores = nullptr; -PFN_vkGetSemaphoreCounterValue real_get_counter = nullptr; - -std::atomic in_wait_semaphores{false}; -std::atomic fail_counter_device_lost{false}; -std::atomic counter_calls{0}; -std::atomic wait_sem_count{0}; - -VKAPI_ATTR VkResult VKAPI_CALL wait_semaphores(VkDevice device, const VkSemaphoreWaitInfo* info, std::uint64_t timeout) { - wait_sem_count.store(info->semaphoreCount, std::memory_order_release); - in_wait_semaphores.store(true, std::memory_order_release); - const VkResult res = real_wait_semaphores(device, info, timeout); - in_wait_semaphores.store(false, std::memory_order_release); - return res; -} - -VKAPI_ATTR VkResult VKAPI_CALL get_semaphore_counter_value(VkDevice device, VkSemaphore sem, std::uint64_t* value) { - counter_calls.fetch_add(1, std::memory_order_relaxed); - if (fail_counter_device_lost.load(std::memory_order_acquire)) return VK_ERROR_DEVICE_LOST; - return real_get_counter(device, sem, value); -} - -VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL get_device(VkDevice device, const char* name) { - const std::string_view n = name; - if (n == "vkWaitSemaphores") return reinterpret_cast(wait_semaphores); - if (n == "vkGetSemaphoreCounterValue") return reinterpret_cast(get_semaphore_counter_value); - return real_get_device(device, name); -} - -void install(PFN_vkGetDeviceProcAddr device_proc, VkDevice device) { - real_get_device = device_proc; - real_wait_semaphores = reinterpret_cast(device_proc(device, "vkWaitSemaphores")); - real_get_counter = - reinterpret_cast(device_proc(device, "vkGetSemaphoreCounterValue")); -} -} // namespace driver - -bool wait_flag(std::mutex& mu, std::condition_variable& cv, const bool& flag, int timeout_ms = 2000) { - std::unique_lock lk(mu); - return cv.wait_for(lk, std::chrono::milliseconds(timeout_ms), [&] { return flag; }); -} - -bool wait_until_in_vk_wait(int timeout_ms = 2000) { - const auto deadline = std::chrono::steady_clock::now() + std::chrono::milliseconds(timeout_ms); - while (!driver::in_wait_semaphores.load(std::memory_order_acquire)) { - if (std::chrono::steady_clock::now() >= deadline) return false; - std::this_thread::sleep_for(std::chrono::milliseconds(1)); - } - return true; -} - -// Waits until run() has re-armed vkWaitSemaphores with exactly `count` semaphores (wakeup + N pending waits). -bool wait_until_wait_sem_count(std::uint32_t count, int timeout_ms = 2000) { - const auto deadline = std::chrono::steady_clock::now() + std::chrono::milliseconds(timeout_ms); - while (driver::wait_sem_count.load(std::memory_order_acquire) != count) { - if (std::chrono::steady_clock::now() >= deadline) return false; - std::this_thread::sleep_for(std::chrono::milliseconds(1)); - } - return true; -} - -} // namespace - -int main() { - using namespace leonida; - - vktest::Device d; - if (!d.create(false)) { - std::fprintf(stderr, "vk_fence_dispatcher_sync_test: no Vulkan 1.3 device, skipped\n"); - return 77; - } - driver::install(d.device_proc, d.device); - - // 1. Re-entrant completion callback in run(): callback calls enqueue_fence_callback() and cancel_fence_waits(). - { - VulkanContext context(driver::get_device, d.device, true); - EXPECT(context.loaded()); - VulkanFence fence_a(context, 0); - VulkanFence fence_b(context, 0); - VulkanFence fence_c(context, 0); - EXPECT(fence_a.semaphore() != VK_NULL_HANDLE && fence_b.semaphore() != VK_NULL_HANDLE && - fence_c.semaphore() != VK_NULL_HANDLE); - - std::mutex mu; - std::condition_variable cv; - bool first_ran = false; - bool chained_ran = false; - bool c_cancelled = false; - - context.enqueue_fence_callback(fence_c.semaphore(), 99, [&] { - std::lock_guard lk(mu); - c_cancelled = true; - cv.notify_all(); - }); - context.enqueue_fence_callback(fence_a.semaphore(), 1, [&] { - context.enqueue_fence_callback(fence_b.semaphore(), 1, [&] { - std::lock_guard lk(mu); - chained_ran = true; - cv.notify_all(); - }); - context.cancel_fence_waits(fence_c.semaphore()); - std::lock_guard lk(mu); - first_ran = true; - cv.notify_all(); - }); - - EXPECT(fence_a.signal(1)); - EXPECT(wait_flag(mu, cv, first_ran)); - EXPECT(wait_flag(mu, cv, c_cancelled)); - EXPECT(fence_b.signal(1)); - EXPECT(wait_flag(mu, cv, chained_ran)); - - context.cancel_fence_waits(fence_a.semaphore()); - context.cancel_fence_waits(fence_b.semaphore()); - std::printf("fence dispatcher: re-entrant completion callback in run() ok\n"); - - // 2. Re-entrant callback in cancel(): cancelled callback calls enqueue_fence_callback() on another fence. - VulkanFence fence_d(context, 0); - VulkanFence fence_e(context, 0); - EXPECT(fence_d.semaphore() != VK_NULL_HANDLE && fence_e.semaphore() != VK_NULL_HANDLE); - - bool cancel_returned = false; - bool e_ran = false; - context.enqueue_fence_callback(fence_d.semaphore(), 50, [&] { - context.enqueue_fence_callback(fence_e.semaphore(), 1, [&] { - std::lock_guard lk(mu); - e_ran = true; - cv.notify_all(); - }); - }); - - std::thread cancel_thread([&] { - context.cancel_fence_waits(fence_d.semaphore()); - std::lock_guard lk(mu); - cancel_returned = true; - cv.notify_all(); - }); - const bool ok_cancel = wait_flag(mu, cv, cancel_returned); - EXPECT(ok_cancel); - cancel_thread.join(); - - EXPECT(fence_e.signal(1)); - EXPECT(wait_flag(mu, cv, e_ran)); - context.cancel_fence_waits(fence_e.semaphore()); - std::printf("fence dispatcher: re-entrant callback in cancel() ok\n"); - } - - // 3. mark_device_lost() wakes blocked vkWaitSemaphores(), completes pending waits, and stop()/cancel() never hang. - { - driver::in_wait_semaphores.store(false, std::memory_order_release); - std::mutex mu; - std::condition_variable cv; - bool callback_fired = false; - bool teardown_done = false; - - std::thread lost_test([&] { - VulkanContext lost_ctx(driver::get_device, d.device, true); - if (!lost_ctx.loaded()) std::_Exit(1); - VulkanFence stuck(lost_ctx, 0); - if (stuck.semaphore() == VK_NULL_HANDLE) std::_Exit(1); - - lost_ctx.enqueue_fence_callback(stuck.semaphore(), 100, [&] { - std::lock_guard lk(mu); - callback_fired = true; - cv.notify_all(); - }); - if (!wait_until_in_vk_wait()) std::_Exit(1); - - lost_ctx.mark_device_lost(); - if (!wait_flag(mu, cv, callback_fired)) std::_Exit(1); - - // cancel() and ~VulkanContext() -> stop() must return promptly even after device_lost_ is set. - lost_ctx.cancel_fence_waits(stuck.semaphore()); - }); - - std::thread joiner([&] { - lost_test.join(); - std::lock_guard lk(mu); - teardown_done = true; - cv.notify_all(); - }); - const bool ok_lost = wait_flag(mu, cv, teardown_done, 3000); - EXPECT(ok_lost); - joiner.join(); - EXPECT(callback_fired); - std::printf("fence dispatcher: mark_device_lost() wakes blocked wait and teardown completes ok\n"); - } - - // 4. vkGetSemaphoreCounterValue() returning VK_ERROR_DEVICE_LOST drains pending waits instead of spinning forever. - { - driver::in_wait_semaphores.store(false, std::memory_order_release); - driver::fail_counter_device_lost.store(false, std::memory_order_release); - driver::counter_calls.store(0, std::memory_order_release); - - std::mutex mu; - std::condition_variable cv; - bool drained = false; - bool done = false; - bool marked_lost = false; - std::uint32_t observed_calls = 0; - - std::thread err_test([&] { - VulkanContext err_ctx(driver::get_device, d.device, true); - if (!err_ctx.loaded()) std::_Exit(1); - VulkanFence sem(err_ctx, 0); - if (sem.semaphore() == VK_NULL_HANDLE) std::_Exit(1); - - err_ctx.enqueue_fence_callback(sem.semaphore(), 1, [&] { - std::lock_guard lk(mu); - drained = true; - cv.notify_all(); - }); - if (!wait_until_in_vk_wait()) std::_Exit(1); - - driver::fail_counter_device_lost.store(true, std::memory_order_release); - if (!sem.signal(1)) std::_Exit(1); - if (!wait_flag(mu, cv, drained, 1500)) std::_Exit(1); - - marked_lost = err_ctx.is_device_lost(); - observed_calls = driver::counter_calls.load(std::memory_order_acquire); - err_ctx.cancel_fence_waits(sem.semaphore()); - }); - - std::thread joiner([&] { - err_test.join(); - std::lock_guard lk(mu); - done = true; - cv.notify_all(); - }); - const bool ok_err = wait_flag(mu, cv, done, 3000); - driver::fail_counter_device_lost.store(false, std::memory_order_release); - EXPECT(ok_err); - joiner.join(); - EXPECT(drained); - EXPECT(marked_lost); - EXPECT(observed_calls >= 1 && observed_calls <= 4); - std::printf("fence dispatcher: vkGetSemaphoreCounterValue DEVICE_LOST drains without spin (%u calls) ok\n", - observed_calls); - } - - // 5. cancel() must not return while run() is dispatching a callback that still uses the semaphore. - { - VulkanContext context(driver::get_device, d.device, true); - EXPECT(context.loaded()); - VulkanFence fence(context, 0); - const VkSemaphore sem = fence.semaphore(); - EXPECT(sem != VK_NULL_HANDLE); - - std::mutex mu; - std::condition_variable cv; - bool entered = false, used = false, release = false, cancelled = false; - - context.enqueue_fence_callback(sem, 1, [&] { - { - std::unique_lock lk(mu); - entered = true; - cv.notify_all(); - cv.wait(lk, [&] { return release; }); - } - std::uint64_t value = 0; - driver::real_get_counter(d.device, sem, &value); - std::lock_guard lk(mu); - used = true; - cv.notify_all(); - }); - - EXPECT(fence.signal(1)); - EXPECT(wait_flag(mu, cv, entered)); - - std::thread cancel_thread([&] { - context.cancel_fence_waits(sem); - std::lock_guard lk(mu); - cancelled = true; - cv.notify_all(); - }); - { - std::unique_lock lk(mu); - EXPECT(!cv.wait_for(lk, std::chrono::milliseconds(150), [&] { return cancelled; })); - } - { - std::lock_guard lk(mu); - release = true; - } - cv.notify_all(); - EXPECT(wait_flag(mu, cv, cancelled)); - EXPECT(used); - cancel_thread.join(); - std::printf("fence dispatcher: cancel waits for an in-flight callback ok\n"); - } - - // 6. A re-entrant cancel() for a later callback in the same ready batch must skip that callback instead of - // returning while it is still going to run with a semaphore the caller has already destroyed. - { - driver::in_wait_semaphores.store(false, std::memory_order_release); - driver::wait_sem_count.store(0, std::memory_order_release); - VulkanContext context(driver::get_device, d.device, true); - EXPECT(context.loaded()); - VulkanFence fence_a(context, 0); - VulkanFence fence_b(context, 0); - const VkSemaphore sem_a = fence_a.semaphore(); - const VkSemaphore sem_b = fence_b.semaphore(); - EXPECT(sem_a != VK_NULL_HANDLE && sem_b != VK_NULL_HANDLE && sem_a != sem_b); - - std::mutex mu; - std::condition_variable cv; - bool a_done = false, cancel_returned = false, b_after_cancel = false; - - context.enqueue_fence_callback(sem_a, 1, [&] { - context.cancel_fence_waits(sem_b); - std::lock_guard lk(mu); - // B may legitimately run inside cancel() when it was still pending; it must not run after this point. - cancel_returned = true; - a_done = true; - cv.notify_all(); - }); - EXPECT(wait_until_wait_sem_count(2)); // wakeup + A - context.enqueue_fence_callback(sem_b, 1, [&] { - std::lock_guard lk(mu); - if (cancel_returned) b_after_cancel = true; - cv.notify_all(); - }); - EXPECT(wait_until_wait_sem_count(3)); // wakeup + A + B: one ready batch - - EXPECT(fence_a.signal(1)); - EXPECT(fence_b.signal(1)); - EXPECT(wait_flag(mu, cv, a_done)); - // Give the dispatcher time to walk the rest of the batch. - std::this_thread::sleep_for(std::chrono::milliseconds(100)); - EXPECT(!b_after_cancel); - - context.cancel_fence_waits(sem_a); - context.cancel_fence_waits(sem_b); - std::printf("fence dispatcher: re-entrant cancel skips later callback in the same batch ok\n"); - } - - EXPECT(d.validation_errors() == 0); - std::printf("vk_fence_dispatcher_sync_test: ok\n"); - return 0; -} diff --git a/runtime/test/vk_harness.cpp b/runtime/test/vk_harness.cpp deleted file mode 100644 index cd374e8b6..000000000 --- a/runtime/test/vk_harness.cpp +++ /dev/null @@ -1,1204 +0,0 @@ -// Headless Vulkan harness: draws one triangle (3 vertices, no vertex buffers) with a given VS + FS into a -// W x H RGBA32F image and writes the raw floats to a file. Used to check translated shaders on the real GPU. -// -// vk_harness [width height [clip-test-s0 clip-test-s1]] -// vk_harness --mesh-group-readback X Y Z -// The latter captures one full-screen triangle per mesh workgroup, in Vulkan rasterization order. -// -// Push constants follow the contract in docs/design.md: s0..s31, then the heap base lo/hi. They are zero unless -// VKH_SGPRS=w0,w1,... sets s0, s1, ... (decimal or 0x hex) -// VKH_GS_PRIMITIVES=1 reports "gs_primitives=N" on stderr for the VKH_GS draw (77 if unsupported) -// VKH_HEAP=addr=word,... allocates a zeroed 64 KiB heap (Xbox VA 0 = its device address), writes each word at -// its address and passes the heap base, so a V# in VKH_SGPRS can point into it. -// VKH_HEAP_DUMP= after the draw, writes the 64 KiB heap (needs VKH_HEAP, which may be empty-valued as -// "0=0"), so a test can read what the pixel shader stored or atomically added. -// VKH_DRAW_MESH= + VKH_VERTEX_LAYOUT=0:3f,1:2f -// draws an indexed mesh instead of the 3-vertex triangle. The file is u32 -// vertex_count, u32 index_count, vertex_count*stride bytes, index_count u32 -// indices; the layout lists location:float-components, one item per attribute. -// VKH_BINARY_OUT= writes the pipeline's VK_KHR_pipeline_binary data after building it -// VKH_BINARY_IN= builds the pipeline from such a file instead (tools/ps_oracle.py patches the pixel -// shader in it); both exit 77 without VK_KHR_pipeline_binary -// VKH_COLOR_FORMAT=: the color target's format and texel size (default RGBA32F, 16); out.raw -// holds the texels as stored; 77 when the format is no color attachment -// VKH_SUBGROUP_SIZE=32|64 requires that subgroup size of the fragment shader (or of the compute or geometry -// stage under test); stderr says "fragment subgroup size: N" when it took effect and -// "... not available" when the device cannot require it (exit code stays 0). -// VKH_TEX_RGBA= binds a 2D RGBA8 texture (u32 width, u32 height, width*height*4 bytes) at bindless -// set 0 image index 1 (with 1x1 magenta at index 0), writes a T# at VKH_TSHARP_VA -// (default 0x100) in the 64 KiB heap, and registers VKH_SSHARP (4 comma-separated -// dwords, default 0x92,0xc00000,0x14500000,0) at sampler index 1. -// -#define VK_NO_PROTOTYPES -#include "vulkan_loader.h" -#include "vk_device_pick.h" -#include "vk_shader_fma.h" -#include "vk_pc_tail.h" -#include "../src/descriptor_table.h" -#include "../src/gfx10_descriptors.h" -#include "spirv_capability.h" - -// VK_KHR_pipeline_binary is newer than some Vulkan header sets (CI images, an older SDK). Guard the feature so the -// harness still builds there; VKH_BINARY_OUT/VKH_BINARY_IN then report unsupported and exit 77. -#if defined(VK_KHR_pipeline_binary) && defined(VK_KHR_maintenance5) -#define VKH_PIPELINE_BINARY 1 -#else -#define VKH_PIPELINE_BINARY 0 -#endif - -#include -#include -#include -#include -#include -#include -#include -#include -#include - -static PFN_vkGetInstanceProcAddr gipa; -#define LOADI(name) auto name = reinterpret_cast(gipa(inst, #name)) -#define CHECK(x) \ - do { \ - VkResult r_ = (x); \ - if (r_ != VK_SUCCESS) { \ - std::fprintf(stderr, "FAILED %s -> %d (line %d)\n", #x, r_, __LINE__); \ - return 1; \ - } \ - } while (0) - -static std::vector read_spv(const char* path) { - std::ifstream f(path, std::ios::binary); - std::vector b((std::istreambuf_iterator(f)), {}); - std::vector w(b.size() / 4); - std::memcpy(w.data(), b.data(), w.size() * 4); - return w; -} - -static bool parse_u32(const char*& s, uint32_t& v) { - const bool hex = s[0] == '0' && (s[1] == 'x' || s[1] == 'X'); - const char* digits = hex ? s + 2 : s; - if (!(hex ? std::isxdigit(uint8_t(*digits)) : std::isdigit(uint8_t(*digits)))) return false; // no sign or space - char* end; - unsigned long long x = std::strtoull(digits, &end, hex ? 16 : 10); - if (x > 0xFFFFFFFFull) return false; - v = uint32_t(x); s = end; - return true; -} - -// A list separator must be followed by another item: "1,2," is rejected. -static bool next_item(const char*& s) { - if (!*s) return true; - return *s++ == ',' && *s; -} - -static bool parse_sgprs(const char* s, uint32_t* sgprs) { - for (uint32_t i = 0; *s; i++) { - if (i == 32 || !parse_u32(s, sgprs[i]) || !next_item(s)) return false; - } - return true; -} - -static bool parse_heap(const char* s, std::vector>& words, uint32_t heap_bytes) { - while (*s) { - uint32_t addr, word; - if (!parse_u32(s, addr) || *s++ != '=' || !parse_u32(s, word) || !next_item(s)) return false; - if (addr % 4 || addr > heap_bytes - 4) return false; - words.emplace_back(addr, word); - } - return true; -} - -// VKH_VERTEX_LAYOUT=0:3f,1:2f: one attribute per item, float components only. Location 0 is the first float3. -struct VertexAttr { - uint32_t location, components, offset; - VkFormat format; -}; - -static bool parse_vertex_layout(const char* s, VertexAttr* attrs, uint32_t& count, uint32_t& stride) { - count = 0; stride = 0; - while (*s) { - uint32_t loc, comps; - if (count == 8 || !parse_u32(s, loc) || *s++ != ':' || !parse_u32(s, comps) || - comps < 1 || comps > 4 || *s++ != 'f' || !next_item(s)) - return false; - static const VkFormat formats[4] = {VK_FORMAT_R32_SFLOAT, VK_FORMAT_R32G32_SFLOAT, - VK_FORMAT_R32G32B32_SFLOAT, VK_FORMAT_R32G32B32A32_SFLOAT}; - attrs[count++] = {loc, comps, stride, formats[comps - 1]}; - stride += comps * 4; - } - return count > 0; -} - -// VKH_DRAW_MESH file: u32 vertex_count, u32 index_count, vertex_count*stride bytes, index_count u32 indices. -static bool read_mesh(const char* path, uint32_t stride, std::vector& vertices, - std::vector& indices) { - std::ifstream f(path, std::ios::binary); - uint32_t vcount = 0, icount = 0; - f.read(reinterpret_cast(&vcount), 4); - f.read(reinterpret_cast(&icount), 4); - if (!f || vcount == 0 || icount == 0 || vcount > 10000000u || icount > 30000000u) return false; - vertices.resize(size_t(vcount) * stride); - indices.resize(icount); - f.read(reinterpret_cast(vertices.data()), std::streamsize(vertices.size())); - f.read(reinterpret_cast(indices.data()), std::streamsize(indices.size() * 4)); - return bool(f); -} - -int main(int argc, char** argv) { - if (argc < 4) { - std::fprintf(stderr, "usage: vk_harness vs.spv fs.spv out.raw [w h [clip-test-s0 clip-test-s1]]\n" - " vk_harness ms.spv fs.spv out.raw --mesh-group-readback X Y Z\n"); - return 2; - } - const bool group_readback = argc > 4 && !std::strcmp(argv[4], "--mesh-group-readback"); - const bool clip_shifts = !group_readback && argc == 8; - uint32_t groups[3] = {1, 1, 1}; - uint32_t W = 64, H = 64; - if (group_readback) { - if (argc != 8) { - std::fprintf(stderr, "--mesh-group-readback requires X Y Z\n"); - return 2; - } - W = H = 1; - for (unsigned i = 0; i < 3; ++i) { - char* end; - long n = std::strtol(argv[5 + i], &end, 10); - if (*end || n < 1 || n > 256 / W) { - std::fprintf(stderr, "mesh grid must contain 1..256 groups (8-bit stencil)\n"); - return 2; - } - groups[i] = uint32_t(n); - W *= groups[i]; - } - } else if (argc > 5) { - W = atoi(argv[4]); H = atoi(argv[5]); - } - // Push constants: s0..s31, heap base (32..33), code base (34..35), --mesh-compute output address (36..37). - uint32_t pc[38] = {}; - const char* draw_mesh_path = std::getenv("VKH_DRAW_MESH"); - if (draw_mesh_path && !*draw_mesh_path) draw_mesh_path = nullptr; - VertexAttr vertex_attrs[8]; - uint32_t vertex_attr_count = 0, vertex_stride = 0; - if (draw_mesh_path) { - const char* layout = std::getenv("VKH_VERTEX_LAYOUT"); - if (!layout || !parse_vertex_layout(layout, vertex_attrs, vertex_attr_count, vertex_stride)) { - std::fprintf(stderr, "VKH_VERTEX_LAYOUT: expected locations like 0:3f,1:2f with VKH_DRAW_MESH\n"); - return 2; - } - } - const char* sgprs_env = std::getenv("VKH_SGPRS"); - if (sgprs_env && !parse_sgprs(sgprs_env, pc)) { - std::fprintf(stderr, "VKH_SGPRS: expected up to 32 comma-separated words, got \"%s\"\n", sgprs_env); - return 2; - } - const uint32_t heap_bytes = 64 * 1024; - const char* heap_env = std::getenv("VKH_HEAP"); - if (heap_env && !*heap_env) heap_env = nullptr; - std::vector> heap_words; - if (heap_env && !parse_heap(heap_env, heap_words, heap_bytes)) { - std::fprintf(stderr, "VKH_HEAP: expected addr=word pairs, 4-byte aligned below 0x%x, got \"%s\"\n", - heap_bytes, heap_env); - return 2; - } - const char* tex_rgba_path = std::getenv("VKH_TEX_RGBA"); - if (tex_rgba_path && !*tex_rgba_path) tex_rgba_path = nullptr; - uint32_t tsharp_va = 0x100; - uint32_t ssharp[8] = {0x92, 0xc00000, 0x14500000, 0, - 0xFFFFFFFFu, 0xFFFFFFFFu, 0xFFFFFFFFu, 0xFFFFFFFFu}; - uint32_t tex_w = 0, tex_h = 0; - std::vector tex_pixels; - if (tex_rgba_path) { - if (const char* va_env = std::getenv("VKH_TSHARP_VA"); va_env && *va_env) { - const char* p = va_env; - if (!parse_u32(p, tsharp_va) || *p || (tsharp_va & 3u) || tsharp_va > heap_bytes - 32) { - std::fprintf(stderr, "VKH_TSHARP_VA: expected 4-byte aligned offset at most 0x%x, got \"%s\"\n", - heap_bytes - 32, va_env); - return 2; - } - } - if (const char* ss_env = std::getenv("VKH_SSHARP"); ss_env && *ss_env) { - const char* p = ss_env; - for (int i = 0; i < 4; ++i) { - if (i && *p++ != ',') { - std::fprintf(stderr, "VKH_SSHARP: expected 4 comma-separated dwords, got \"%s\"\n", ss_env); - return 2; - } - if (!parse_u32(p, ssharp[i])) { - std::fprintf(stderr, "VKH_SSHARP: expected 4 comma-separated dwords, got \"%s\"\n", ss_env); - return 2; - } - } - if (*p) { - std::fprintf(stderr, "VKH_SSHARP: expected 4 comma-separated dwords, got \"%s\"\n", ss_env); - return 2; - } - } - std::ifstream tf(tex_rgba_path, std::ios::binary); - uint32_t hdr[2] = {}; - if (!tf.read(reinterpret_cast(hdr), 8) || hdr[0] == 0 || hdr[1] == 0 || - uint64_t(hdr[0]) * uint64_t(hdr[1]) > (1ull << 26)) { - std::fprintf(stderr, "VKH_TEX_RGBA: invalid header in %s\n", tex_rgba_path); - return 1; - } - tex_w = hdr[0]; - tex_h = hdr[1]; - tex_pixels.resize(size_t(tex_w) * size_t(tex_h) * 4); - if (!tf.read(reinterpret_cast(tex_pixels.data()), std::streamsize(tex_pixels.size()))) { - std::fprintf(stderr, "VKH_TEX_RGBA: truncated pixel data in %s\n", tex_rgba_path); - return 1; - } - } - const bool need_heap = heap_env != nullptr || tex_rgba_path != nullptr; - gipa = load_vulkan(); - if (!gipa) return 1; - VkInstance inst = VK_NULL_HANDLE; - LOADI(vkCreateInstance); - VkApplicationInfo app{VK_STRUCTURE_TYPE_APPLICATION_INFO}; - app.apiVersion = VK_API_VERSION_1_3; - VkInstanceCreateInfo ici{VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO}; - ici.pApplicationInfo = &app; - CHECK(vkCreateInstance(&ici, nullptr, &inst)); - LOADI(vkEnumeratePhysicalDevices); LOADI(vkGetPhysicalDeviceProperties); - LOADI(vkGetPhysicalDeviceProperties2); LOADI(vkGetPhysicalDeviceFeatures2); - LOADI(vkGetPhysicalDeviceQueueFamilyProperties); LOADI(vkGetPhysicalDeviceMemoryProperties); - LOADI(vkCreateDevice); LOADI(vkGetDeviceProcAddr); - uint32_t n = 0; - vkEnumeratePhysicalDevices(inst, &n, nullptr); - std::vector pds(n); - vkEnumeratePhysicalDevices(inst, &n, pds.data()); - std::vector candidates(pds.size()); - for (std::size_t i = 0; i < pds.size(); ++i) vkGetPhysicalDeviceProperties(pds[i], &candidates[i]); - const std::size_t chosen = leonida::vk_test::pick_device(candidates); - VkPhysicalDevice pd = chosen < pds.size() ? pds[chosen] : VK_NULL_HANDLE; - if (!pd) { - leonida::vk_test::report_no_device(); - return 1; - } - VkPhysicalDeviceProperties props; vkGetPhysicalDeviceProperties(pd, &props); - VkPhysicalDeviceSubgroupSizeControlProperties sgProps{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SUBGROUP_SIZE_CONTROL_PROPERTIES}; - VkPhysicalDeviceDriverProperties driver{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_DRIVER_PROPERTIES}; - if (props.apiVersion >= VK_API_VERSION_1_2) sgProps.pNext = &driver; - VkPhysicalDeviceProperties2 props2{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROPERTIES_2}; - props2.pNext = &sgProps; - vkGetPhysicalDeviceProperties2(pd, &props2); - std::fprintf(stderr, "device: %s (subgroup %u..%u)\n", props.deviceName, sgProps.minSubgroupSize, sgProps.maxSubgroupSize); - if (driver.driverName[0]) std::fprintf(stderr, "driver: %s\n", driver.driverName); - uint32_t qn = 0; - vkGetPhysicalDeviceQueueFamilyProperties(pd, &qn, nullptr); - std::vector qf(qn); - vkGetPhysicalDeviceQueueFamilyProperties(pd, &qn, qf.data()); - uint32_t qi = 0; - while (qi < qn && !(qf[qi].queueFlags & VK_QUEUE_GRAPHICS_BIT)) qi++; - float prio = 1; - VkDeviceQueueCreateInfo qci{VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO}; - qci.queueFamilyIndex = qi; qci.queueCount = 1; qci.pQueuePriorities = &prio; - // Optional features some translated shaders need (enabled only when the device has them): - // raw barycentric reads (BaryCoordKHR), POPS ordering (pixel interlock), non-constant texel offsets (maintenance8). - auto vkEnumerateDeviceExtensionProperties = reinterpret_cast( - gipa(inst, "vkEnumerateDeviceExtensionProperties")); - uint32_t en = 0; - vkEnumerateDeviceExtensionProperties(pd, nullptr, &en, nullptr); - std::vector exts(en); - vkEnumerateDeviceExtensionProperties(pd, nullptr, &en, exts.data()); - auto has = [&](const char* e) { - for (auto& x : exts) if (!std::strcmp(x.extensionName, e)) return true; - return false; - }; - // A translated pixel shader that reads BaryCoordKHR aborts the driver when the device lacks barycentrics - // (llvmpipe and other software devices), so the suite reports it as unsupported instead. 77 is the existing - // "this device cannot run the test" code (runtime/test/shaders/check.py, scripts/run_gpu_tests.py). - const std::vector fs_code = read_spv(argv[2]); - bool needs_barycentric = false, needs_float64 = false; - for (std::size_t i = 5; i + 1 < fs_code.size();) { // instructions follow the 5-word SPIR-V header - const uint32_t words = fs_code[i] >> 16, op = fs_code[i] & 0xffffu; - if (!words) break; - if (op == 17 && fs_code[i + 1] == 5284) // OpCapability FragmentBarycentricKHR - needs_barycentric = true; - if (op == 17 && fs_code[i + 1] == 10) // OpCapability Float64 (v_add_f64 and friends) - needs_float64 = true; - i += words; - } - if (needs_barycentric && !has(VK_KHR_FRAGMENT_SHADER_BARYCENTRIC_EXTENSION_NAME)) { - std::fprintf(stderr, "unsupported: %s reads BaryCoordKHR and the device has no %s\n", - argv[2], VK_KHR_FRAGMENT_SHADER_BARYCENTRIC_EXTENSION_NAME); - return 77; - } - // OpFmaKHR (rdna2spirv.py --fma khr) needs VK_KHR_shader_fma; a module of ANY stage that needs it is refused - // (argv[1] is the vertex shader, or the mesh shader run as compute under VKH_MESH_COMPUTE). - leonida::vk_test::ShaderFma fma; - fma.query(gipa, inst, pd); - if (!fma.accepts(fs_code.data(), fs_code.size() * 4, argv[2])) return 77; - if (!fma.accepts_file(argv[1])) return 77; - if (!fma.accepts_file(std::getenv("VKH_MESH_COMPUTE"))) return 77; - std::vector enable; - void* chain = nullptr; - if (fma.supported()) { - enable.push_back(fma.extension()); -#ifdef VK_KHR_SHADER_FMA_EXTENSION_NAME // older Vulkan headers have no VkPhysicalDeviceShaderFmaFeaturesKHR - fma.features.pNext = chain; chain = &fma.features; -#endif - } - VkPhysicalDeviceFragmentShaderBarycentricFeaturesKHR bary{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FRAGMENT_SHADER_BARYCENTRIC_FEATURES_KHR}; - VkPhysicalDeviceFragmentShaderInterlockFeaturesEXT lock{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FRAGMENT_SHADER_INTERLOCK_FEATURES_EXT}; - if (has(VK_KHR_FRAGMENT_SHADER_BARYCENTRIC_EXTENSION_NAME)) { - enable.push_back(VK_KHR_FRAGMENT_SHADER_BARYCENTRIC_EXTENSION_NAME); - bary.fragmentShaderBarycentric = VK_TRUE; bary.pNext = chain; chain = &bary; - } - if (has(VK_EXT_FRAGMENT_SHADER_INTERLOCK_EXTENSION_NAME)) { - enable.push_back(VK_EXT_FRAGMENT_SHADER_INTERLOCK_EXTENSION_NAME); - lock.fragmentShaderPixelInterlock = VK_TRUE; lock.pNext = chain; chain = &lock; - } - // VKH_MESH_COMPUTE=: the first shader is a mesh shader translated with rdna2spirv.py --mesh-compute. - // It is dispatched as compute over the mesh grid (1x1x1, or --mesh-group-readback's), writing its slots to an - // output buffer (VKH_MESH_SLOT bytes per workgroup, address in push-constant dwords 36..37). Then - // vs.spv (tools/mesh_compute_vs.py) draws groups * VKH_MESH_PRIMS * 3 vertices with the fragment shader. No - // VK_EXT_mesh_shader is needed. - const char* mesh_vs_path = std::getenv("VKH_MESH_COMPUTE"); - if (mesh_vs_path && !*mesh_vs_path) mesh_vs_path = nullptr; - const bool mesh_compute = mesh_vs_path != nullptr; - uint64_t mesh_slot = 0; - uint32_t mesh_prims = 0; - if (mesh_compute) { - const char* slot_env = std::getenv("VKH_MESH_SLOT"); - const char* prims_env = std::getenv("VKH_MESH_PRIMS"); - mesh_slot = slot_env ? std::strtoull(slot_env, nullptr, 0) : 0; - mesh_prims = prims_env ? uint32_t(std::strtoul(prims_env, nullptr, 0)) : 0; - if (!mesh_slot || !mesh_prims) { - std::fprintf(stderr, "VKH_MESH_COMPUTE needs VKH_MESH_SLOT and VKH_MESH_PRIMS (index.json mesh_compute)\n"); - return 2; - } - } - // Translated shaders declare a 144-byte push-constant block (user SGPRs, heap base, code base; see VKH_SGPRS / - // VKH_HEAP); --mesh-compute modules and their vertex shaders add the output address (152 bytes). A device with - // fewer bytes (128, the Vulkan minimum, as on some Intel Arc drivers and AMD's Windows driver for RDNA2 iGPUs) - // cannot take that range: declaring it anyway is invalid, and there a shader reading past the limit crashed or - // hung the device. 77, as vk_texture_test and vk_bindless_test: a device limit, not a wrong result (D3D-14). - // LEONIDA_PC_TAIL_UBO=1 (rdna2spirv.py --pc-tail-ubo): s0..s31 only, 128 bytes, which every device has; the - // tail is a uniform block at set 1 (vk_pc_tail.h). tools/mesh_compute_vs.py's vertex shader still reads the - // --mesh-compute output address from push constants, so that combination isn't run. - const bool pc_tail = leonida::vk_test::pc_tail_requested(); - if (pc_tail && mesh_compute) { - std::fprintf(stderr, "unsupported: --mesh-compute's vertex shader reads the output address from push " - "constants, not from the --pc-tail-ubo block\n"); - return 77; - } - const uint32_t pc_bytes = pc_tail ? 128u : mesh_compute ? 152u : 144u; - if (props.limits.maxPushConstantsSize < pc_bytes) { - std::fprintf(stderr, "unsupported: need %u push constant bytes, device has %u\n", pc_bytes, - props.limits.maxPushConstantsSize); - return 77; - } - // VKH_MESH=1: the first shader is a mesh shader (VK_EXT_mesh_shader), drawn with vkCmdDrawMeshTasksEXT(1,1,1). - const bool mesh = !mesh_compute && (group_readback || std::getenv("VKH_MESH") != nullptr); - VkPhysicalDeviceMeshShaderFeaturesEXT meshf{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MESH_SHADER_FEATURES_EXT}; - if (mesh) { - // Query the feature, not just the extension. 77: the device cannot run this test (as vk_compute_test and - // vk_store_test), so the runners report SKIP. - VkPhysicalDeviceFeatures2 mesh_query{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2}; - mesh_query.pNext = &meshf; - vkGetPhysicalDeviceFeatures2(pd, &mesh_query); - if (!has(VK_EXT_MESH_SHADER_EXTENSION_NAME) || !meshf.meshShader) { - std::fprintf(stderr, "unsupported: no VK_EXT_mesh_shader\n"); - return 77; - } - enable.push_back(VK_EXT_MESH_SHADER_EXTENSION_NAME); - meshf = {VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MESH_SHADER_FEATURES_EXT}; - meshf.meshShader = VK_TRUE; meshf.pNext = chain; chain = &meshf; - } -#ifdef VK_KHR_MAINTENANCE_8_EXTENSION_NAME - VkPhysicalDeviceMaintenance8FeaturesKHR m8{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MAINTENANCE_8_FEATURES_KHR}; - if (has(VK_KHR_MAINTENANCE_8_EXTENSION_NAME)) { - enable.push_back(VK_KHR_MAINTENANCE_8_EXTENSION_NAME); - m8.maintenance8 = VK_TRUE; m8.pNext = chain; chain = &m8; - } -#endif - VkPhysicalDeviceVulkan11Features f11q{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_1_FEATURES}; - VkPhysicalDeviceVulkan12Features f12q{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_2_FEATURES}; - f12q.pNext = &f11q; - VkPhysicalDeviceVulkan13Features f13q{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_3_FEATURES}; - f13q.pNext = &f12q; - VkPhysicalDeviceFeatures2 f2q{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2}; - f2q.pNext = &f13q; - vkGetPhysicalDeviceFeatures2(pd, &f2q); - // Translated vertex shaders read BaseVertex / BaseInstance (DrawParameters) to give v0 / v3 the hardware's - // zero-based ids. - VkPhysicalDeviceVulkan11Features f11{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_1_FEATURES}; - if (f11q.shaderDrawParameters) { - f11.shaderDrawParameters = VK_TRUE; - f11.pNext = chain; - chain = &f11; - } - VkPhysicalDeviceVulkan13Features f13{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_3_FEATURES}; - if (f13q.subgroupSizeControl) { - f13.subgroupSizeControl = VK_TRUE; - f13.pNext = chain; - chain = &f13; - } - VkPhysicalDeviceVulkan12Features f12{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_2_FEATURES}; - if (need_heap || mesh_compute) { - // 77 is the "this device cannot run the test" code that check.py and run_gpu_tests.py report as SKIP. - if (!f12q.bufferDeviceAddress) { - std::fprintf(stderr, "unsupported: %s needs bufferDeviceAddress\n", - tex_rgba_path ? "VKH_TEX_RGBA" : heap_env ? "VKH_HEAP" : "VKH_MESH_COMPUTE"); - return 77; - } - f12.bufferDeviceAddress = VK_TRUE; - if (tex_rgba_path) { - if (!f12q.runtimeDescriptorArray || !f12q.descriptorIndexing) { - std::fprintf(stderr, "unsupported: VKH_TEX_RGBA needs runtimeDescriptorArray and descriptorIndexing\n"); - return 77; - } - f12.runtimeDescriptorArray = VK_TRUE; - f12.descriptorIndexing = VK_TRUE; - } - f12.pNext = chain; - chain = &f12; - } - // VKH_BINARY_OUT= / VKH_BINARY_IN=: VK_KHR_pipeline_binary. OUT writes the pipeline's binaries after - // it is built; IN builds the pipeline from such a file instead of compiling the shaders (tools/ps_oracle.py - // patches the pixel shader's code in it). File: u32 count, then per binary u32 key size, 32 key bytes, u64 data - // size, the data. - const char* bin_out = std::getenv("VKH_BINARY_OUT"); - const char* bin_in = std::getenv("VKH_BINARY_IN"); -#if VKH_PIPELINE_BINARY - VkPhysicalDevicePipelineBinaryFeaturesKHR pbf{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PIPELINE_BINARY_FEATURES_KHR}; - VkPhysicalDeviceMaintenance5FeaturesKHR m5{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MAINTENANCE_5_FEATURES_KHR}; -#endif - if (bin_out || bin_in) { -#if !VKH_PIPELINE_BINARY - std::fprintf(stderr, "unsupported: these Vulkan headers have no VK_KHR_pipeline_binary\n"); - return 77; -#else - VkPhysicalDeviceFeatures2 q{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2}; - VkPhysicalDevicePipelineBinaryFeaturesKHR pbq{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PIPELINE_BINARY_FEATURES_KHR}; - q.pNext = &pbq; - vkGetPhysicalDeviceFeatures2(pd, &q); - if (!has(VK_KHR_PIPELINE_BINARY_EXTENSION_NAME) || !has(VK_KHR_MAINTENANCE_5_EXTENSION_NAME) || - !pbq.pipelineBinaries) { - std::fprintf(stderr, "unsupported: no VK_KHR_pipeline_binary\n"); - return 77; - } - enable.push_back(VK_KHR_PIPELINE_BINARY_EXTENSION_NAME); - enable.push_back(VK_KHR_MAINTENANCE_5_EXTENSION_NAME); - pbf.pipelineBinaries = VK_TRUE; pbf.pNext = chain; chain = &pbf; - m5.maintenance5 = VK_TRUE; m5.pNext = chain; chain = &m5; -#endif - } - for (auto e : enable) std::fprintf(stderr, "enabled %s\n", e); - VkDeviceCreateInfo dci{VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO}; - dci.queueCreateInfoCount = 1; dci.pQueueCreateInfos = &qci; - dci.enabledExtensionCount = uint32_t(enable.size()); dci.ppEnabledExtensionNames = enable.data(); - dci.pNext = chain; - // VKH_GS=: insert a geometry stage between the vertex and fragment shaders. VKH_SUBGROUP_SIZE then - // applies to it, unless VKH_GS_HELPER=1 says the GS only feeds the pixel shader under test. - const char* gs_path = std::getenv("VKH_GS"); - const char* count_opt = std::getenv("VKH_GS_PRIMITIVES"); - const bool count_gs = count_opt && std::strcmp(count_opt, "1") == 0; - if (count_gs && (!gs_path || !*gs_path || mesh || mesh_compute)) { - std::fprintf(stderr, "VKH_GS_PRIMITIVES=1 requires a VS/GS/FS draw with VKH_GS\n"); - return 1; - } - if (gs_path && !f2q.features.geometryShader) { // MoltenVK: Metal has no geometry stage - std::fprintf(stderr, "unsupported: no geometryShader\n"); - return 77; - } - VkPhysicalDeviceFeatures feats{}; - if (count_gs && !f2q.features.pipelineStatisticsQuery) { - std::fprintf(stderr, "unsupported: no pipelineStatisticsQuery\n"); - return 77; - } - feats.pipelineStatisticsQuery = count_gs; - if (clip_shifts && !f2q.features.shaderClipDistance) { - std::fprintf(stderr, "unsupported: shaderClipDistance\n"); - return 77; - } - feats.geometryShader = gs_path ? VK_TRUE : VK_FALSE; - feats.shaderClipDistance = f2q.features.shaderClipDistance; - feats.shaderCullDistance = f2q.features.shaderCullDistance; - if (needs_float64) { - if (!f2q.features.shaderFloat64) { - std::fprintf(stderr, "unsupported: %s uses Float64 and the device has no shaderFloat64\n", argv[2]); - return 77; - } - feats.shaderFloat64 = VK_TRUE; - } - // shaderInt64 only when a stage has 64-bit integers. Heap and --mesh-compute addresses are 64-bit, but rdna2spirv.py - // builds them from 32-bit pairs unless the shader also does 64-bit arithmetic (SHADER-423), so the module decides, - // not VKH_HEAP (TEST-468). - bool needs_int64 = leonida::vk_test::needs_shader_int64(fs_code); - for (const char* p : std::initializer_list{argv[1], mesh_vs_path, gs_path}) - if (p && !needs_int64) needs_int64 = leonida::vk_test::needs_shader_int64(read_spv(p)); - if (needs_int64) { - if (!f2q.features.shaderInt64) { - std::fprintf(stderr, "unsupported: a stage declares Int64 and the device has no shaderInt64\n"); - return 77; - } - feats.shaderInt64 = VK_TRUE; - } - if (tex_rgba_path) { - if (!f2q.features.shaderSampledImageArrayDynamicIndexing) { - std::fprintf(stderr, "unsupported: VKH_TEX_RGBA needs shaderSampledImageArrayDynamicIndexing\n"); - return 77; - } - feats.shaderSampledImageArrayDynamicIndexing = VK_TRUE; - } - dci.pEnabledFeatures = &feats; - VkDevice dev; - CHECK(vkCreateDevice(pd, &dci, nullptr, &dev)); -#define LOADD(name) auto name = reinterpret_cast(vkGetDeviceProcAddr(dev, #name)) - LOADD(vkGetDeviceQueue); LOADD(vkCreateImage); LOADD(vkGetImageMemoryRequirements); LOADD(vkAllocateMemory); - LOADD(vkBindImageMemory); LOADD(vkCreateImageView); LOADD(vkCreateRenderPass); LOADD(vkCreateFramebuffer); - LOADD(vkCreateShaderModule); LOADD(vkCreatePipelineLayout); LOADD(vkCreateGraphicsPipelines); - LOADD(vkCreateCommandPool); LOADD(vkAllocateCommandBuffers); LOADD(vkBeginCommandBuffer); - LOADD(vkCmdBeginRenderPass); LOADD(vkCmdBindPipeline); LOADD(vkCmdDraw); LOADD(vkCmdEndRenderPass); - LOADD(vkCmdBindVertexBuffers); LOADD(vkCmdBindIndexBuffer); LOADD(vkCmdDrawIndexed); - LOADD(vkCmdPipelineBarrier); - LOADD(vkCmdCopyImageToBuffer); LOADD(vkEndCommandBuffer); LOADD(vkQueueSubmit); LOADD(vkQueueWaitIdle); - LOADD(vkCreateBuffer); LOADD(vkGetBufferMemoryRequirements); LOADD(vkBindBufferMemory); LOADD(vkMapMemory); - VkQueue q; vkGetDeviceQueue(dev, qi, 0, &q); - VkPhysicalDeviceMemoryProperties mp; vkGetPhysicalDeviceMemoryProperties(pd, &mp); - auto memtype = [&](uint32_t bits, VkMemoryPropertyFlags want) { - for (uint32_t i = 0; i < mp.memoryTypeCount; i++) - if ((bits & (1u << i)) && (mp.memoryTypes[i].propertyFlags & want) == want) return i; - return 0u; - }; - auto attachment = [&](VkFormat format, VkImageUsageFlags usage, VkImageAspectFlags aspect, - VkImage& image, VkImageView& view) -> int { - VkImageCreateInfo ii{VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO}; - ii.imageType = VK_IMAGE_TYPE_2D; ii.format = format; ii.extent = {W, H, 1}; ii.mipLevels = 1; ii.arrayLayers = 1; - ii.samples = VK_SAMPLE_COUNT_1_BIT; ii.tiling = VK_IMAGE_TILING_OPTIMAL; ii.usage = usage; - CHECK(vkCreateImage(dev, &ii, nullptr, &image)); - VkMemoryRequirements mr; vkGetImageMemoryRequirements(dev, image, &mr); - VkMemoryAllocateInfo mai{VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO}; - mai.allocationSize = mr.size; mai.memoryTypeIndex = memtype(mr.memoryTypeBits, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT); - VkDeviceMemory mem; CHECK(vkAllocateMemory(dev, &mai, nullptr, &mem)); - CHECK(vkBindImageMemory(dev, image, mem, 0)); - VkImageViewCreateInfo vi{VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO}; - vi.image = image; vi.viewType = VK_IMAGE_VIEW_TYPE_2D; vi.format = format; - vi.subresourceRange = {aspect, 0, 1, 0, 1}; - CHECK(vkCreateImageView(dev, &vi, nullptr, &view)); - return 0; - }; - // VKH_COLOR_FORMAT=:: the color target's format (default RGBA32F, 16 bytes); - // out.raw then holds the target's texels as they are (tools/ps_oracle.py --format). - VkFormat fmt = VK_FORMAT_R32G32B32A32_SFLOAT; - uint32_t texel_bytes = 16; - if (const char* cf = std::getenv("VKH_COLOR_FORMAT"); cf && *cf) { - char* end = nullptr; - fmt = VkFormat(std::strtoul(cf, &end, 0)); - texel_bytes = (end && *end == ':') ? uint32_t(std::strtoul(end + 1, nullptr, 0)) : 0; - if (!texel_bytes || texel_bytes > 16) { std::fprintf(stderr, "VKH_COLOR_FORMAT: want :\n"); return 2; } - auto get_fp = reinterpret_cast( - gipa(inst, "vkGetPhysicalDeviceFormatProperties")); - VkFormatProperties cp; get_fp(pd, fmt, &cp); - if (!(cp.optimalTilingFeatures & VK_FORMAT_FEATURE_COLOR_ATTACHMENT_BIT)) { - std::fprintf(stderr, "unsupported: format %u is not a color attachment\n", unsigned(fmt)); - return 77; - } - } - VkImage img; - VkImageView views[2]{}; - if (attachment(fmt, VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | VK_IMAGE_USAGE_TRANSFER_SRC_BIT, - VK_IMAGE_ASPECT_COLOR_BIT, img, views[0])) return 1; - VkAttachmentDescription attachments[2]{}; - auto& ad = attachments[0]; - ad.format = fmt; ad.samples = VK_SAMPLE_COUNT_1_BIT; ad.loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR; - ad.storeOp = VK_ATTACHMENT_STORE_OP_STORE; ad.stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE; - ad.stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE; ad.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED; - ad.finalLayout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL; - VkAttachmentReference ar{0, VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL}; - VkSubpassDescription sd{}; sd.pipelineBindPoint = VK_PIPELINE_BIND_POINT_GRAPHICS; - sd.colorAttachmentCount = 1; sd.pColorAttachments = &ar; - VkAttachmentReference stencil_ref{1, VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL}; - if (group_readback) { - LOADI(vkGetPhysicalDeviceFormatProperties); - auto& ds = attachments[1]; - for (auto format : {VK_FORMAT_S8_UINT, VK_FORMAT_D24_UNORM_S8_UINT, VK_FORMAT_D32_SFLOAT_S8_UINT}) { - VkFormatProperties fp; - vkGetPhysicalDeviceFormatProperties(pd, format, &fp); - if (fp.optimalTilingFeatures & VK_FORMAT_FEATURE_DEPTH_STENCIL_ATTACHMENT_BIT) { - ds.format = format; - break; - } - } - if (!ds.format) { std::fprintf(stderr, "no stencil attachment format\n"); return 1; } - VkImage stencil; - VkImageAspectFlags aspects = VK_IMAGE_ASPECT_STENCIL_BIT; - if (ds.format != VK_FORMAT_S8_UINT) aspects |= VK_IMAGE_ASPECT_DEPTH_BIT; - if (attachment(ds.format, VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT, aspects, stencil, views[1])) return 1; - ds.samples = VK_SAMPLE_COUNT_1_BIT; - ds.loadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE; ds.storeOp = VK_ATTACHMENT_STORE_OP_DONT_CARE; - ds.stencilLoadOp = VK_ATTACHMENT_LOAD_OP_CLEAR; ds.stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE; - ds.finalLayout = stencil_ref.layout; - sd.pDepthStencilAttachment = &stencil_ref; - } - VkRenderPassCreateInfo rpi{VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO}; - rpi.attachmentCount = group_readback ? 2 : 1; rpi.pAttachments = attachments; rpi.subpassCount = 1; rpi.pSubpasses = &sd; - VkSubpassDependency copy_dep{0, VK_SUBPASS_EXTERNAL, VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT, - VK_PIPELINE_STAGE_TRANSFER_BIT, VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT, VK_ACCESS_TRANSFER_READ_BIT}; - rpi.dependencyCount = 1; rpi.pDependencies = ©_dep; - VkRenderPass rp; CHECK(vkCreateRenderPass(dev, &rpi, nullptr, &rp)); - VkFramebufferCreateInfo fbi{VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO}; - fbi.renderPass = rp; fbi.attachmentCount = rpi.attachmentCount; fbi.pAttachments = views; fbi.width = W; fbi.height = H; fbi.layers = 1; - VkFramebuffer fb; CHECK(vkCreateFramebuffer(dev, &fbi, nullptr, &fb)); - bool tail_block = false; // some stage reads the --pc-tail-ubo block (declares set 1) - auto module = [&](const char* p, VkShaderModule* m) { - auto code = read_spv(p); - if (pc_tail && leonida::vk_test::spirv_declares_set(code.data(), code.size() * 4, leonida::vk_test::pc_tail_set)) - tail_block = true; - VkShaderModuleCreateInfo smi{VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO}; - smi.codeSize = code.size() * 4; smi.pCode = code.data(); - return vkCreateShaderModule(dev, &smi, nullptr, m); - }; - VkShaderModule vs, fs, csm = VK_NULL_HANDLE; - CHECK(module(mesh_compute ? mesh_vs_path : argv[1], &vs)); CHECK(module(argv[2], &fs)); - if (mesh_compute) CHECK(module(argv[1], &csm)); - VkPipelineShaderStageCreateInfo stages[3]{{VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO}, - {VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO}, - {VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO}}; - stages[0].stage = mesh ? VK_SHADER_STAGE_MESH_BIT_EXT : VK_SHADER_STAGE_VERTEX_BIT; - stages[0].module = vs; stages[0].pName = "main"; - stages[1].stage = VK_SHADER_STAGE_FRAGMENT_BIT; stages[1].module = fs; stages[1].pName = "main"; - uint32_t nstages = 2; - if (gs_path) { - VkShaderModule gsm; - CHECK(module(gs_path, &gsm)); - stages[2].stage = VK_SHADER_STAGE_GEOMETRY_BIT; stages[2].module = gsm; stages[2].pName = "main"; - nstages = 3; - } - const char* sg_env = std::getenv("VKH_SUBGROUP_SIZE"); - const uint32_t req_sg = sg_env ? uint32_t(atoi(sg_env)) : 0; - VkPipelineShaderStageRequiredSubgroupSizeCreateInfo reqSg{ - VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_REQUIRED_SUBGROUP_SIZE_CREATE_INFO}; - reqSg.requiredSubgroupSize = req_sg; - if (req_sg > 0 && f13q.subgroupSizeControl && - req_sg >= sgProps.minSubgroupSize && req_sg <= sgProps.maxSubgroupSize) { - // VKH_GS_HELPER=1: the geometry shader only feeds the pixel shader under test (the --bary-fallback - // pass-through), so the size still goes to the fragment stage. - const bool gs_tested = gs_path && !std::getenv("VKH_GS_HELPER"); - if (mesh && (sgProps.requiredSubgroupSizeStages & VK_SHADER_STAGE_MESH_BIT_EXT)) - stages[0].pNext = &reqSg; - else if (gs_tested && (sgProps.requiredSubgroupSizeStages & VK_SHADER_STAGE_GEOMETRY_BIT)) - stages[2].pNext = &reqSg; - else if (!mesh && !gs_tested && (sgProps.requiredSubgroupSizeStages & VK_SHADER_STAGE_FRAGMENT_BIT)) - stages[1].pNext = &reqSg; - // A device with one subgroup size runs every stage at it, required or not (AMD GCN: 64, with only COMPUTE - // in requiredSubgroupSizeStages), so the fragment stage of a plain draw already has the size asked for. - const bool fixed = !mesh && !gs_tested && sgProps.minSubgroupSize == sgProps.maxSubgroupSize; - if (stages[1].pNext == &reqSg || fixed) std::fprintf(stderr, "fragment subgroup size: %u\n", req_sg); - } else if (req_sg > 0) { - std::fprintf(stderr, "fragment subgroup size: %u not available\n", req_sg); - } - VkPipelineVertexInputStateCreateInfo vin{VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO}; - VkVertexInputBindingDescription vbind{0, vertex_stride, VK_VERTEX_INPUT_RATE_VERTEX}; - VkVertexInputAttributeDescription vattr[8]{}; - if (draw_mesh_path) { - for (uint32_t i = 0; i < vertex_attr_count; ++i) - vattr[i] = {vertex_attrs[i].location, 0, vertex_attrs[i].format, vertex_attrs[i].offset}; - vin.vertexBindingDescriptionCount = 1; - vin.pVertexBindingDescriptions = &vbind; - vin.vertexAttributeDescriptionCount = vertex_attr_count; - vin.pVertexAttributeDescriptions = vattr; - } - VkPipelineInputAssemblyStateCreateInfo ia{VK_STRUCTURE_TYPE_PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO}; - ia.topology = VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST; - VkViewport vp{0, 0, float(W), float(H), 0, 1}; VkRect2D sc{{0, 0}, {W, H}}; - VkPipelineViewportStateCreateInfo vps{VK_STRUCTURE_TYPE_PIPELINE_VIEWPORT_STATE_CREATE_INFO}; - vps.viewportCount = 1; vps.pViewports = &vp; vps.scissorCount = 1; vps.pScissors = ≻ - VkPipelineRasterizationStateCreateInfo rs{VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_STATE_CREATE_INFO}; - rs.cullMode = VK_CULL_MODE_NONE; rs.lineWidth = 1; - VkPipelineMultisampleStateCreateInfo ms{VK_STRUCTURE_TYPE_PIPELINE_MULTISAMPLE_STATE_CREATE_INFO}; - ms.rasterizationSamples = VK_SAMPLE_COUNT_1_BIT; - VkPipelineColorBlendAttachmentState cba{}; cba.colorWriteMask = 0xF; - VkPipelineColorBlendStateCreateInfo cb{VK_STRUCTURE_TYPE_PIPELINE_COLOR_BLEND_STATE_CREATE_INFO}; - cb.attachmentCount = 1; cb.pAttachments = &cba; - // The push-constant block (pc_bytes, checked against the device limit above). - const VkShaderStageFlags pcs = (mesh ? VK_SHADER_STAGE_MESH_BIT_EXT : VK_SHADER_STAGE_VERTEX_BIT) | - VK_SHADER_STAGE_FRAGMENT_BIT | (gs_path ? VK_SHADER_STAGE_GEOMETRY_BIT : 0) | - (mesh_compute ? VK_SHADER_STAGE_COMPUTE_BIT : 0); - VkDescriptorSetLayout dsl = VK_NULL_HANDLE; - VkDescriptorSet ds = VK_NULL_HANDLE; - VkImage tex_fallback_img = VK_NULL_HANDLE, tex_img = VK_NULL_HANDLE; - VkBuffer tex_staging = VK_NULL_HANDLE; - if (tex_rgba_path) { - LOADD(vkCreateDescriptorSetLayout); - VkDescriptorSetLayoutBinding dslb[3]{}; - dslb[0] = {0, VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE, 2, VK_SHADER_STAGE_ALL, nullptr}; - dslb[1] = {1, VK_DESCRIPTOR_TYPE_SAMPLER, 2, VK_SHADER_STAGE_ALL, nullptr}; - dslb[2] = {2, VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, 1, VK_SHADER_STAGE_ALL, nullptr}; - VkDescriptorSetLayoutCreateInfo dslci{VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO}; - dslci.bindingCount = 3; - dslci.pBindings = dslb; - CHECK(vkCreateDescriptorSetLayout(dev, &dslci, nullptr, &dsl)); - } - VkPushConstantRange pcr{pcs, 0, pc_bytes}; - VkPipelineLayoutCreateInfo pli{VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO}; - if (dsl) { - pli.setLayoutCount = 1; - pli.pSetLayouts = &dsl; - } - pli.pushConstantRangeCount = 1; pli.pPushConstantRanges = &pcr; - // --pc-tail-ubo: the tail block at set 1 (set 0 stays empty here), one slot for the one draw. - leonida::vk_test::PcTail tail; - if (tail_block && !tail.create(vkGetDeviceProcAddr, dev, mp, props.limits.minUniformBufferOffsetAlignment, pcs, 1)) { - std::fprintf(stderr, "FAILED creating the --pc-tail-ubo block\n"); - return 1; - } - const VkDescriptorSetLayout tail_layouts[] = {tail.empty_layout, tail.set_layout}; - if (tail_block) { pli.setLayoutCount = 2; pli.pSetLayouts = tail_layouts; } - VkPipelineLayout pl; CHECK(vkCreatePipelineLayout(dev, &pli, nullptr, &pl)); - VkGraphicsPipelineCreateInfo gpi{VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO}; - gpi.stageCount = nstages; gpi.pStages = stages; - gpi.pVertexInputState = mesh ? nullptr : &vin; gpi.pInputAssemblyState = mesh ? nullptr : &ia; - gpi.pViewportState = &vps; gpi.pRasterizationState = &rs; gpi.pMultisampleState = &ms; gpi.pColorBlendState = &cb; - VkPipelineDepthStencilStateCreateInfo ds_state{VK_STRUCTURE_TYPE_PIPELINE_DEPTH_STENCIL_STATE_CREATE_INFO}; - if (group_readback) { - // Pixel i starts at stencil i. Every triangle decrements it, but only the i-th sees zero and writes color. - ds_state.stencilTestEnable = VK_TRUE; - auto& face = ds_state.front; - face.compareOp = VK_COMPARE_OP_EQUAL; - face.compareMask = face.writeMask = 0xff; - face.failOp = face.passOp = VK_STENCIL_OP_DECREMENT_AND_WRAP; - ds_state.back = face; - gpi.pDepthStencilState = &ds_state; - } - gpi.layout = pl; gpi.renderPass = rp; -#if VKH_PIPELINE_BINARY - VkPipelineCreateFlags2CreateInfoKHR capture{VK_STRUCTURE_TYPE_PIPELINE_CREATE_FLAGS_2_CREATE_INFO_KHR}; - std::vector in_bins; - VkPipelineBinaryInfoKHR bin_info{VK_STRUCTURE_TYPE_PIPELINE_BINARY_INFO_KHR}; - if (bin_out) { - capture.flags = VK_PIPELINE_CREATE_2_CAPTURE_DATA_BIT_KHR; - gpi.pNext = &capture; - } - if (bin_in) { - auto vkCreatePipelineBinariesKHR = reinterpret_cast( - vkGetDeviceProcAddr(dev, "vkCreatePipelineBinariesKHR")); - std::ifstream f(bin_in, std::ios::binary); - std::vector all((std::istreambuf_iterator(f)), std::istreambuf_iterator()); - size_t at = 0; - auto take = [&](void* p, size_t n) { - if (at + n > all.size()) { std::fprintf(stderr, "%s: truncated\n", bin_in); std::exit(2); } - std::memcpy(p, all.data() + at, n); at += n; - }; - uint32_t count = 0; take(&count, 4); - std::vector keys(count, {VK_STRUCTURE_TYPE_PIPELINE_BINARY_KEY_KHR}); - std::vector datas(count); - std::vector> blobs(count); - for (uint32_t i = 0; i < count; i++) { - take(&keys[i].keySize, 4); take(keys[i].key, VK_MAX_PIPELINE_BINARY_KEY_SIZE_KHR); - uint64_t n = 0; take(&n, 8); - blobs[i].resize(size_t(n)); take(blobs[i].data(), size_t(n)); - datas[i].dataSize = size_t(n); datas[i].pData = blobs[i].data(); - } - VkPipelineBinaryKeysAndDataKHR kd{count, keys.data(), datas.data()}; - VkPipelineBinaryCreateInfoKHR bci{VK_STRUCTURE_TYPE_PIPELINE_BINARY_CREATE_INFO_KHR}; - bci.pKeysAndDataInfo = &kd; - in_bins.resize(count); - VkPipelineBinaryHandlesInfoKHR hi{VK_STRUCTURE_TYPE_PIPELINE_BINARY_HANDLES_INFO_KHR}; - hi.pipelineBinaryCount = count; hi.pPipelineBinaries = in_bins.data(); - CHECK(vkCreatePipelineBinariesKHR(dev, &bci, nullptr, &hi)); - bin_info.binaryCount = count; bin_info.pPipelineBinaries = in_bins.data(); - gpi.pNext = &bin_info; - std::fprintf(stderr, "pipeline from %u binaries in %s\n", count, bin_in); - } -#endif - VkPipeline pipe; CHECK(vkCreateGraphicsPipelines(dev, VK_NULL_HANDLE, 1, &gpi, nullptr, &pipe)); -#if VKH_PIPELINE_BINARY - if (bin_out) { - auto vkCreatePipelineBinariesKHR = reinterpret_cast( - vkGetDeviceProcAddr(dev, "vkCreatePipelineBinariesKHR")); - auto vkGetPipelineBinaryDataKHR = reinterpret_cast( - vkGetDeviceProcAddr(dev, "vkGetPipelineBinaryDataKHR")); - VkPipelineBinaryCreateInfoKHR bci{VK_STRUCTURE_TYPE_PIPELINE_BINARY_CREATE_INFO_KHR}; - bci.pipeline = pipe; - VkPipelineBinaryHandlesInfoKHR hi{VK_STRUCTURE_TYPE_PIPELINE_BINARY_HANDLES_INFO_KHR}; - CHECK(vkCreatePipelineBinariesKHR(dev, &bci, nullptr, &hi)); - std::vector bins(hi.pipelineBinaryCount); - hi.pPipelineBinaries = bins.data(); - CHECK(vkCreatePipelineBinariesKHR(dev, &bci, nullptr, &hi)); - std::ofstream f(bin_out, std::ios::binary); - uint32_t count = uint32_t(bins.size()); - f.write(reinterpret_cast(&count), 4); - for (auto b : bins) { - VkPipelineBinaryDataInfoKHR di{VK_STRUCTURE_TYPE_PIPELINE_BINARY_DATA_INFO_KHR}; - di.pipelineBinary = b; - VkPipelineBinaryKeyKHR key{VK_STRUCTURE_TYPE_PIPELINE_BINARY_KEY_KHR}; - size_t n = 0; - CHECK(vkGetPipelineBinaryDataKHR(dev, &di, &key, &n, nullptr)); - std::vector data(n); - CHECK(vkGetPipelineBinaryDataKHR(dev, &di, &key, &n, data.data())); - uint64_t n64 = n; - f.write(reinterpret_cast(&key.keySize), 4); - f.write(reinterpret_cast(key.key), VK_MAX_PIPELINE_BINARY_KEY_SIZE_KHR); - f.write(reinterpret_cast(&n64), 8); - f.write(data.data(), std::streamsize(n)); - } - f.close(); - if (!f) { - std::fprintf(stderr, "failed to write pipeline binaries to %s\n", bin_out); - return 1; - } - std::fprintf(stderr, "wrote %u pipeline binaries to %s\n", count, bin_out); - } -#endif - VkPipeline cpipe = VK_NULL_HANDLE; - if (mesh_compute) { - VkComputePipelineCreateInfo cpi{VK_STRUCTURE_TYPE_COMPUTE_PIPELINE_CREATE_INFO}; - cpi.stage = {VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO}; - cpi.stage.stage = VK_SHADER_STAGE_COMPUTE_BIT; cpi.stage.module = csm; cpi.stage.pName = "main"; - // VKH_SUBGROUP_SIZE goes to the mesh shader under test, now a compute stage. - if (req_sg > 0 && f13q.subgroupSizeControl && req_sg >= sgProps.minSubgroupSize && - req_sg <= sgProps.maxSubgroupSize && (sgProps.requiredSubgroupSizeStages & VK_SHADER_STAGE_COMPUTE_BIT)) - cpi.stage.pNext = &reqSg; - cpi.layout = pl; - LOADD(vkCreateComputePipelines); - CHECK(vkCreateComputePipelines(dev, VK_NULL_HANDLE, 1, &cpi, nullptr, &cpipe)); - } - VkBufferCreateInfo bi{VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO}; - bi.size = VkDeviceSize(W) * H * texel_bytes; bi.usage = VK_BUFFER_USAGE_TRANSFER_DST_BIT; - VkBuffer buf; CHECK(vkCreateBuffer(dev, &bi, nullptr, &buf)); - VkMemoryRequirements br; vkGetBufferMemoryRequirements(dev, buf, &br); - VkMemoryAllocateInfo bai{VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO}; - bai.allocationSize = br.size; - bai.memoryTypeIndex = memtype(br.memoryTypeBits, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT); - VkDeviceMemory bmem; CHECK(vkAllocateMemory(dev, &bai, nullptr, &bmem)); - CHECK(vkBindBufferMemory(dev, buf, bmem, 0)); - std::vector mesh_vertices; - std::vector mesh_indices; - VkBuffer vbo = VK_NULL_HANDLE, ibo = VK_NULL_HANDLE; - VkDeviceMemory vbo_mem = VK_NULL_HANDLE, ibo_mem = VK_NULL_HANDLE; - if (draw_mesh_path) { - if (!read_mesh(draw_mesh_path, vertex_stride, mesh_vertices, mesh_indices)) { - std::fprintf(stderr, "VKH_DRAW_MESH: cannot read %s\n", draw_mesh_path); - return 1; - } - auto host_buffer = [&](VkDeviceSize bytes, VkBufferUsageFlags usage, VkBuffer& b, - VkDeviceMemory& m, void*& p) -> bool { - VkBufferCreateInfo ci{VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO}; - ci.size = bytes; ci.usage = usage; - if (vkCreateBuffer(dev, &ci, nullptr, &b) != VK_SUCCESS) return false; - VkMemoryRequirements rq; vkGetBufferMemoryRequirements(dev, b, &rq); - VkMemoryAllocateInfo ai{VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO}; - ai.allocationSize = rq.size; - ai.memoryTypeIndex = memtype(rq.memoryTypeBits, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | - VK_MEMORY_PROPERTY_HOST_COHERENT_BIT); - return vkAllocateMemory(dev, &ai, nullptr, &m) == VK_SUCCESS && - vkBindBufferMemory(dev, b, m, 0) == VK_SUCCESS && - vkMapMemory(dev, m, 0, bytes, 0, &p) == VK_SUCCESS; - }; - void* vmap = nullptr; - void* imap = nullptr; - if (!host_buffer(VkDeviceSize(mesh_vertices.size()), VK_BUFFER_USAGE_VERTEX_BUFFER_BIT, vbo, vbo_mem, vmap) || - !host_buffer(VkDeviceSize(mesh_indices.size() * 4), VK_BUFFER_USAGE_INDEX_BUFFER_BIT, ibo, ibo_mem, imap)) { - std::fprintf(stderr, "VKH_DRAW_MESH: cannot create the vertex or index buffer\n"); - return 1; - } - std::memcpy(vmap, mesh_vertices.data(), mesh_vertices.size()); - std::memcpy(imap, mesh_indices.data(), mesh_indices.size() * 4); - } - void* heap_map = nullptr; - uint32_t tsharp[8] = {0x11111111, leonida::gfx10::format_from_vulkan(VK_FORMAT_R8G8B8A8_UNORM) << 20, 0x33333333, - 0x44444444, 0x55555555, 0x66666666, 0x77777777, 0x88888888}; - if (need_heap) { - LOADD(vkGetBufferDeviceAddress); - VkBufferCreateInfo hbi{VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO}; - hbi.size = heap_bytes; - hbi.usage = VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT; - VkBuffer heap; CHECK(vkCreateBuffer(dev, &hbi, nullptr, &heap)); - VkMemoryRequirements hr; vkGetBufferMemoryRequirements(dev, heap, &hr); - VkMemoryAllocateFlagsInfo haf{VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_FLAGS_INFO}; - haf.flags = VK_MEMORY_ALLOCATE_DEVICE_ADDRESS_BIT; - VkMemoryAllocateInfo hai{VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO}; - hai.pNext = &haf; hai.allocationSize = hr.size; - hai.memoryTypeIndex = memtype(hr.memoryTypeBits, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT); - VkDeviceMemory hmem; CHECK(vkAllocateMemory(dev, &hai, nullptr, &hmem)); - CHECK(vkBindBufferMemory(dev, heap, hmem, 0)); - void* hp; CHECK(vkMapMemory(dev, hmem, 0, heap_bytes, 0, &hp)); - heap_map = hp; - std::memset(hp, 0, heap_bytes); - if (tex_rgba_path) std::memcpy(static_cast(hp) + tsharp_va, tsharp, 32); - for (auto [addr, word] : heap_words) std::memcpy(static_cast(hp) + addr, &word, 4); - VkBufferDeviceAddressInfo hda{VK_STRUCTURE_TYPE_BUFFER_DEVICE_ADDRESS_INFO}; - hda.buffer = heap; - const uint64_t base = vkGetBufferDeviceAddress(dev, &hda); - pc[32] = uint32_t(base); pc[33] = uint32_t(base >> 32); - } - if (tex_rgba_path) { - LOADD(vkCreateSampler); LOADD(vkCreateDescriptorPool); LOADD(vkAllocateDescriptorSets); - LOADD(vkUpdateDescriptorSets); - leonida::DescriptorTable desc_table(16); - desc_table.insert(tsharp, 1); - desc_table.insert(ssharp, 1); - const auto table = desc_table.build_gpu_buffer(true); - VkBuffer tb = VK_NULL_HANDLE; - VkDeviceMemory tbm = VK_NULL_HANDLE; - void* tbp = nullptr; - { - VkBufferCreateInfo tbi{VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO}; - tbi.size = table.size() * 4; tbi.usage = VK_BUFFER_USAGE_STORAGE_BUFFER_BIT; - CHECK(vkCreateBuffer(dev, &tbi, nullptr, &tb)); - VkMemoryRequirements tmr; vkGetBufferMemoryRequirements(dev, tb, &tmr); - VkMemoryAllocateInfo tai{VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO}; - tai.allocationSize = tmr.size; - tai.memoryTypeIndex = memtype(tmr.memoryTypeBits, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT); - CHECK(vkAllocateMemory(dev, &tai, nullptr, &tbm)); - CHECK(vkBindBufferMemory(dev, tb, tbm, 0)); - CHECK(vkMapMemory(dev, tbm, 0, tbi.size, 0, &tbp)); - std::memcpy(tbp, table.data(), table.size() * 4); - } - auto make_sampled_tex = [&](uint32_t tw, uint32_t th, VkImage& out_img, VkImageView& out_view) -> int { - VkImageCreateInfo ii{VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO}; - ii.imageType = VK_IMAGE_TYPE_2D; ii.format = VK_FORMAT_R8G8B8A8_UNORM; ii.extent = {tw, th, 1}; - ii.mipLevels = 1; ii.arrayLayers = 1; ii.samples = VK_SAMPLE_COUNT_1_BIT; - ii.tiling = VK_IMAGE_TILING_OPTIMAL; - ii.usage = VK_IMAGE_USAGE_SAMPLED_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT; - CHECK(vkCreateImage(dev, &ii, nullptr, &out_img)); - VkMemoryRequirements mr; vkGetImageMemoryRequirements(dev, out_img, &mr); - VkMemoryAllocateInfo mai{VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO}; - mai.allocationSize = mr.size; - mai.memoryTypeIndex = memtype(mr.memoryTypeBits, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT); - VkDeviceMemory mem; CHECK(vkAllocateMemory(dev, &mai, nullptr, &mem)); - CHECK(vkBindImageMemory(dev, out_img, mem, 0)); - VkImageViewCreateInfo vi{VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO}; - vi.image = out_img; vi.viewType = VK_IMAGE_VIEW_TYPE_2D; vi.format = VK_FORMAT_R8G8B8A8_UNORM; - vi.subresourceRange = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1}; - CHECK(vkCreateImageView(dev, &vi, nullptr, &out_view)); - return 0; - }; - VkImageView tex_views[2]{}; - if (make_sampled_tex(1, 1, tex_fallback_img, tex_views[0]) || - make_sampled_tex(tex_w, tex_h, tex_img, tex_views[1])) return 1; - { - const VkDeviceSize stage_bytes = 4 + tex_pixels.size(); - VkBufferCreateInfo sbi{VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO}; - sbi.size = stage_bytes; sbi.usage = VK_BUFFER_USAGE_TRANSFER_SRC_BIT; - CHECK(vkCreateBuffer(dev, &sbi, nullptr, &tex_staging)); - VkMemoryRequirements smr; vkGetBufferMemoryRequirements(dev, tex_staging, &smr); - VkMemoryAllocateInfo sai{VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO}; - sai.allocationSize = smr.size; - sai.memoryTypeIndex = memtype(smr.memoryTypeBits, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT); - VkDeviceMemory smem; CHECK(vkAllocateMemory(dev, &sai, nullptr, &smem)); - CHECK(vkBindBufferMemory(dev, tex_staging, smem, 0)); - void* sp = nullptr; CHECK(vkMapMemory(dev, smem, 0, stage_bytes, 0, &sp)); - const uint32_t magenta = 0xFFFF00FFu; - std::memcpy(sp, &magenta, 4); - std::memcpy(static_cast(sp) + 4, tex_pixels.data(), tex_pixels.size()); - } - VkSampler samplers[2]{}; - VkSamplerCreateInfo def_sci{VK_STRUCTURE_TYPE_SAMPLER_CREATE_INFO}; - def_sci.magFilter = VK_FILTER_NEAREST; def_sci.minFilter = VK_FILTER_NEAREST; - CHECK(vkCreateSampler(dev, &def_sci, nullptr, &samplers[0])); - const leonida::gfx10::SamplerWords sw{ssharp[0], ssharp[1], ssharp[2], ssharp[3]}; - VkSamplerCreateInfo sci = leonida::gfx10::vulkan_sampler(leonida::gfx10::decode(sw)); - sci.anisotropyEnable = VK_FALSE; - CHECK(vkCreateSampler(dev, &sci, nullptr, &samplers[1])); - VkDescriptorPoolSize dps[3] = { - {VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE, 2}, - {VK_DESCRIPTOR_TYPE_SAMPLER, 2}, - {VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, 1}, - }; - VkDescriptorPoolCreateInfo dpci{VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO}; - dpci.maxSets = 1; dpci.poolSizeCount = 3; dpci.pPoolSizes = dps; - VkDescriptorPool dpool; CHECK(vkCreateDescriptorPool(dev, &dpci, nullptr, &dpool)); - VkDescriptorSetAllocateInfo dsai{VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO}; - dsai.descriptorPool = dpool; dsai.descriptorSetCount = 1; dsai.pSetLayouts = &dsl; - CHECK(vkAllocateDescriptorSets(dev, &dsai, &ds)); - VkDescriptorImageInfo img_infos[2] = { - {VK_NULL_HANDLE, tex_views[0], VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL}, - {VK_NULL_HANDLE, tex_views[1], VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL}, - }; - VkDescriptorImageInfo smp_infos[2] = { - {samplers[0], VK_NULL_HANDLE, VK_IMAGE_LAYOUT_UNDEFINED}, - {samplers[1], VK_NULL_HANDLE, VK_IMAGE_LAYOUT_UNDEFINED}, - }; - VkDescriptorBufferInfo tbl_info{tb, 0, VK_WHOLE_SIZE}; - VkWriteDescriptorSet writes[3]{}; - writes[0] = {VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET, nullptr, ds, 0, 0, 2, VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE, img_infos}; - writes[1] = {VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET, nullptr, ds, 1, 0, 2, VK_DESCRIPTOR_TYPE_SAMPLER, smp_infos}; - writes[2] = {VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET, nullptr, ds, 2, 0, 1, VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, nullptr, &tbl_info}; - vkUpdateDescriptorSets(dev, 3, writes, 0, nullptr); - } - const uint64_t mesh_groups = uint64_t(groups[0]) * groups[1] * groups[2]; - if (mesh_compute) { - LOADD(vkGetBufferDeviceAddress); - VkBufferCreateInfo obi{VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO}; - obi.size = mesh_groups * mesh_slot; - obi.usage = VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT; - VkBuffer obuf; CHECK(vkCreateBuffer(dev, &obi, nullptr, &obuf)); - VkMemoryRequirements orq; vkGetBufferMemoryRequirements(dev, obuf, &orq); - VkMemoryAllocateFlagsInfo oaf{VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_FLAGS_INFO}; - oaf.flags = VK_MEMORY_ALLOCATE_DEVICE_ADDRESS_BIT; - VkMemoryAllocateInfo oai{VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO}; - oai.pNext = &oaf; oai.allocationSize = orq.size; - oai.memoryTypeIndex = memtype(orq.memoryTypeBits, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT); - VkDeviceMemory omem; CHECK(vkAllocateMemory(dev, &oai, nullptr, &omem)); - CHECK(vkBindBufferMemory(dev, obuf, omem, 0)); - void* op; CHECK(vkMapMemory(dev, omem, 0, obi.size, 0, &op)); - std::memset(op, 0, size_t(obi.size)); // a workgroup that never writes its header draws nothing - VkBufferDeviceAddressInfo oda{VK_STRUCTURE_TYPE_BUFFER_DEVICE_ADDRESS_INFO}; - oda.buffer = obuf; - const uint64_t oaddr = vkGetBufferDeviceAddress(dev, &oda); - pc[36] = uint32_t(oaddr); pc[37] = uint32_t(oaddr >> 32); - std::fprintf(stderr, "mesh compute: %llu workgroups x %llu bytes, %u primitives each\n", - (unsigned long long)mesh_groups, (unsigned long long)mesh_slot, mesh_prims); - } - VkCommandPoolCreateInfo cpi{VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO}; cpi.queueFamilyIndex = qi; - VkCommandPool pool; CHECK(vkCreateCommandPool(dev, &cpi, nullptr, &pool)); - VkCommandBufferAllocateInfo cai{VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO}; - cai.commandPool = pool; cai.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY; cai.commandBufferCount = 1; - VkCommandBuffer cmd; CHECK(vkAllocateCommandBuffers(dev, &cai, &cmd)); - VkCommandBufferBeginInfo cbi{VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO}; - CHECK(vkBeginCommandBuffer(cmd, &cbi)); - VkQueryPool gs_query = VK_NULL_HANDLE; - if (count_gs) { - LOADD(vkCreateQueryPool); - LOADD(vkCmdResetQueryPool); - VkQueryPoolCreateInfo info{VK_STRUCTURE_TYPE_QUERY_POOL_CREATE_INFO}; - info.queryType = VK_QUERY_TYPE_PIPELINE_STATISTICS; - info.queryCount = 1; - info.pipelineStatistics = VK_QUERY_PIPELINE_STATISTIC_GEOMETRY_SHADER_PRIMITIVES_BIT; - CHECK(vkCreateQueryPool(dev, &info, nullptr, &gs_query)); - vkCmdResetQueryPool(cmd, gs_query, 0, 1); - } - VkClearValue clears[2]{}; - for (float& c : clears[0].color.float32) c = -1; // marks untouched pixels - if (clip_shifts) { - const float shifts[] = {float(std::atof(argv[6])), float(std::atof(argv[7]))}; - std::memcpy(pc, shifts, sizeof(shifts)); - } - auto push = reinterpret_cast(vkGetDeviceProcAddr(dev, "vkCmdPushConstants")); - if (tex_rgba_path) { - LOADD(vkCmdPipelineBarrier); LOADD(vkCmdCopyBufferToImage); - VkImageMemoryBarrier to_dst[2]{}; - for (int i = 0; i < 2; ++i) { - to_dst[i].sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER; - to_dst[i].dstAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT; - to_dst[i].oldLayout = VK_IMAGE_LAYOUT_UNDEFINED; - to_dst[i].newLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL; - to_dst[i].image = i == 0 ? tex_fallback_img : tex_img; - to_dst[i].subresourceRange = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1}; - } - vkCmdPipelineBarrier(cmd, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, 0, - 0, nullptr, 0, nullptr, 2, to_dst); - VkBufferImageCopy c0{}; - c0.bufferOffset = 0; c0.imageSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1}; c0.imageExtent = {1, 1, 1}; - vkCmdCopyBufferToImage(cmd, tex_staging, tex_fallback_img, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, &c0); - VkBufferImageCopy c1{}; - c1.bufferOffset = 4; c1.imageSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1}; c1.imageExtent = {tex_w, tex_h, 1}; - vkCmdCopyBufferToImage(cmd, tex_staging, tex_img, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, &c1); - VkImageMemoryBarrier to_ro[2]{}; - for (int i = 0; i < 2; ++i) { - to_ro[i].sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER; - to_ro[i].srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT; - to_ro[i].dstAccessMask = VK_ACCESS_SHADER_READ_BIT; - to_ro[i].oldLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL; - to_ro[i].newLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL; - to_ro[i].image = i == 0 ? tex_fallback_img : tex_img; - to_ro[i].subresourceRange = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1}; - } - vkCmdPipelineBarrier(cmd, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT, 0, - 0, nullptr, 0, nullptr, 2, to_ro); - } - if (mesh_compute) { - // The mesh shader as compute, then make its stores visible to the vertex shader's reads. - LOADD(vkCmdDispatch); - vkCmdBindPipeline(cmd, VK_PIPELINE_BIND_POINT_COMPUTE, cpipe); - push(cmd, pl, pcs, 0, pc_bytes, pc); - vkCmdDispatch(cmd, groups[0], groups[1], groups[2]); - VkMemoryBarrier mb{VK_STRUCTURE_TYPE_MEMORY_BARRIER}; - mb.srcAccessMask = VK_ACCESS_SHADER_WRITE_BIT; mb.dstAccessMask = VK_ACCESS_SHADER_READ_BIT; - vkCmdPipelineBarrier(cmd, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, VK_PIPELINE_STAGE_VERTEX_SHADER_BIT, 0, - 1, &mb, 0, nullptr, 0, nullptr); - } - VkRenderPassBeginInfo rbi{VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO}; - rbi.renderPass = rp; rbi.framebuffer = fb; rbi.renderArea = sc; rbi.clearValueCount = rpi.attachmentCount; rbi.pClearValues = clears; - vkCmdBeginRenderPass(cmd, &rbi, VK_SUBPASS_CONTENTS_INLINE); - if (group_readback) { - LOADD(vkCmdClearAttachments); - VkClearAttachment seed{VK_IMAGE_ASPECT_STENCIL_BIT}; - for (uint32_t i = 1; i < W; ++i) { - seed.clearValue.depthStencil.stencil = i; - VkClearRect pixel{{{int32_t(i), 0}, {1, 1}}, 0, 1}; - vkCmdClearAttachments(cmd, 1, &seed, 1, &pixel); - } - std::fprintf(stderr, "mesh workgroups: %u x %u x %u\n", groups[0], groups[1], groups[2]); - } - vkCmdBindPipeline(cmd, VK_PIPELINE_BIND_POINT_GRAPHICS, pipe); - if (ds) { - LOADD(vkCmdBindDescriptorSets); - vkCmdBindDescriptorSets(cmd, VK_PIPELINE_BIND_POINT_GRAPHICS, pl, 0, 1, &ds, 0, nullptr); - } - push(cmd, pl, pcs, 0, pc_bytes, pc); - if (tail_block) { - LOADD(vkCmdBindDescriptorSets); - tail.write(0, pc, 4); // heap base (VKH_HEAP) and code base, as pc[32..35] are without the flag - const uint32_t offset = tail.offset(0); - vkCmdBindDescriptorSets(cmd, VK_PIPELINE_BIND_POINT_GRAPHICS, pl, leonida::vk_test::pc_tail_set, 1, &tail.set, - 1, &offset); - } - // VKH_VERTICES=: draw n vertices instead of one triangle, so a vertex shader fills whole waves (TEST-251). - const char* vertices_env = std::getenv("VKH_VERTICES"); - if (count_gs) { - LOADD(vkCmdBeginQuery); - vkCmdBeginQuery(cmd, gs_query, 0, 0); - } - if (draw_mesh_path) { - VkDeviceSize offset = 0; - vkCmdBindVertexBuffers(cmd, 0, 1, &vbo, &offset); - vkCmdBindIndexBuffer(cmd, ibo, 0, VK_INDEX_TYPE_UINT32); - vkCmdDrawIndexed(cmd, uint32_t(mesh_indices.size()), 1, 0, 0, 0); - } else if (const unsigned vertices = vertices_env ? unsigned(std::strtoul(vertices_env, nullptr, 10)) : 0; - vertices && !mesh) - vkCmdDraw(cmd, vertices, 1, 0, 0); - else if (mesh_compute) - vkCmdDraw(cmd, uint32_t(mesh_groups * mesh_prims * 3), 1, 0, 0); - else if (mesh) - reinterpret_cast(vkGetDeviceProcAddr(dev, "vkCmdDrawMeshTasksEXT"))(cmd, groups[0], groups[1], groups[2]); - else { - // VKH_DRAW=,: draw the triangle with non-zero bases (vs_base_ids). - unsigned first_vertex = 0, first_instance = 0; - if (const char* d = std::getenv("VKH_DRAW")) std::sscanf(d, "%u,%u", &first_vertex, &first_instance); - vkCmdDraw(cmd, 3, 1, first_vertex, first_instance); - } - if (count_gs) { - LOADD(vkCmdEndQuery); - vkCmdEndQuery(cmd, gs_query, 0); - } - vkCmdEndRenderPass(cmd); - VkBufferImageCopy reg{}; reg.imageSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1}; reg.imageExtent = {W, H, 1}; - vkCmdCopyImageToBuffer(cmd, img, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, buf, 1, ®); - // Make the image copy and any shader writes to the heap visible to the host after the queue wait. - VkMemoryBarrier readback{VK_STRUCTURE_TYPE_MEMORY_BARRIER}; - readback.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT | VK_ACCESS_SHADER_WRITE_BIT; - readback.dstAccessMask = VK_ACCESS_HOST_READ_BIT; - vkCmdPipelineBarrier(cmd, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, VK_PIPELINE_STAGE_HOST_BIT, 0, - 1, &readback, 0, nullptr, 0, nullptr); - CHECK(vkEndCommandBuffer(cmd)); - VkSubmitInfo si{VK_STRUCTURE_TYPE_SUBMIT_INFO}; si.commandBufferCount = 1; si.pCommandBuffers = &cmd; - CHECK(vkQueueSubmit(q, 1, &si, VK_NULL_HANDLE)); - CHECK(vkQueueWaitIdle(q)); - if (count_gs) { - LOADD(vkGetQueryPoolResults); - LOADD(vkDestroyQueryPool); - uint64_t primitives = 0; - CHECK(vkGetQueryPoolResults(dev, gs_query, 0, 1, sizeof(primitives), &primitives, - sizeof(primitives), VK_QUERY_RESULT_64_BIT)); - vkDestroyQueryPool(dev, gs_query, nullptr); - std::fprintf(stderr, "gs_primitives=%llu\n", static_cast(primitives)); - } - void* p; CHECK(vkMapMemory(dev, bmem, 0, bi.size, 0, &p)); - std::ofstream output(argv[3], std::ios::binary); - output.write(static_cast(p), std::streamsize(bi.size)); - output.close(); - if (!output) { std::fprintf(stderr, "failed to write %s\n", argv[3]); return 1; } - if (const char* dump = std::getenv("VKH_HEAP_DUMP"); dump && *dump && heap_map) { - std::ofstream hf(dump, std::ios::binary); - hf.write(static_cast(heap_map), heap_bytes); - hf.close(); - if (!hf) { std::fprintf(stderr, "failed to write %s\n", dump); return 1; } - } - std::fprintf(stderr, "ok %ux%u -> %s\n", W, H, argv[3]); - return 0; -} diff --git a/runtime/test/vk_image_fuzz.cpp b/runtime/test/vk_image_fuzz.cpp deleted file mode 100644 index 52b59d6e0..000000000 --- a/runtime/test/vk_image_fuzz.cpp +++ /dev/null @@ -1,612 +0,0 @@ -// Headless fuzz harness for the translator's `image_load` path: -// vk_image_fuzz -// The generated fragment shader does `image_load ..., s[8:15]`, so push constants [8..15] carry the T#. -// A full-screen triangle is drawn into 64x64 RGBA32F and read back into . -// Exit 0 done, 1 error (`spec: ...` for spec errors), 77 when the device cannot do the work. -// LEONIDA_VK_VALIDATION=1 runs under VK_LAYER_KHRONOS_validation; a validation error fails the run. -#define VK_NO_PROTOTYPES -#include "vulkan_loader.h" -#include "../src/vulkan_device_filter.h" -#include "../src/vulkan_bindless.h" - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#define CHECK(x) \ - do { \ - VkResult r_ = (x); \ - if (r_ != VK_SUCCESS) { \ - std::fprintf(stderr, "FAILED %s -> %d (line %d)\n", #x, r_, __LINE__); \ - return 1; \ - } \ - } while (0) - -namespace { -using namespace leonida; -constexpr int unsupported = 77; -unsigned g_validation_errors = 0; -VKAPI_ATTR VkBool32 VKAPI_CALL on_message(VkDebugUtilsMessageSeverityFlagBitsEXT severity, - VkDebugUtilsMessageTypeFlagsEXT types, - const VkDebugUtilsMessengerCallbackDataEXT* data, void*) { - // Only validation-type errors count: a broken third-party layer must not fail the run. - if ((severity & VK_DEBUG_UTILS_MESSAGE_SEVERITY_ERROR_BIT_EXT) && (types & VK_DEBUG_UTILS_MESSAGE_TYPE_VALIDATION_BIT_EXT)) - ++g_validation_errors; - std::fprintf(stderr, "validation: %s\n", data && data->pMessage ? data->pMessage : "(no message)"); - return VK_FALSE; -} -std::vector read_spv(const char* path) { - std::ifstream f(path, std::ios::binary); - std::vector bytes((std::istreambuf_iterator(f)), {}); - std::vector words(bytes.size() / 4); - return std::memcpy(words.data(), bytes.data(), words.size() * 4), words; -} -std::string trim(const std::string& s) { - std::size_t b = s.find_first_not_of(" \t\r\n"), e = s.find_last_not_of(" \t\r\n"); - return b == std::string::npos ? "" : s.substr(b, e - b + 1); -} -// LEONIDA_PC_TAIL_UBO=1: shaders were translated with --pc-tail-ubo (128-byte push constants for s0..s31; the -// image_load fuzz shaders read neither heap base nor code base, so they declare no set-1 block). -bool pc_tail_requested() { - const char* v = std::getenv("LEONIDA_PC_TAIL_UBO"); - std::string s = trim(v ? v : ""); - for (char& c : s) c = char(std::tolower(static_cast(c))); - return s == "1" || s == "true" || s == "yes" || s == "on"; -} -// Decimal or 0x-prefixed hex, whole string, no exceptions (strtoul with base 0 handles both). -bool parse_u32(const std::string& text, std::uint32_t& out) { - if (text.empty() || text.find_first_of(" \t\r\n") != std::string::npos) return false; - char* end = nullptr; - const unsigned long v = std::strtoul(text.c_str(), &end, 0); - if (end == text.c_str() || *end || v > 0xfffffffful) return false; - return out = std::uint32_t(v), true; -} -struct Spec { - std::uint32_t width = 0, height = 0, bytes_per_texel = 0, tsharp[8] = {}; - VkFormat format = VK_FORMAT_UNDEFINED; - std::string format_name, texels_path; - bool has_width = false, has_height = false, has_format = false, has_texels = false, has_tsharp = false; -}; -bool parse_spec(const char* path, Spec& s, std::string& error) { - std::ifstream f(path); - if (!f) return error = "cannot open spec file", false; - std::string line; - for (unsigned lineno = 0; std::getline(f, line);) { - ++lineno; - std::string text = trim(line); - const std::size_t hash = text.find('#'); // '#' starts a comment, even trailing one - if (hash != std::string::npos) text = trim(text.substr(0, hash)); - if (text.empty()) continue; - const std::size_t eq = text.find('='); - if (eq == std::string::npos) return error = "line " + std::to_string(lineno) + ": missing '='", false; - const std::string key = trim(text.substr(0, eq)), value = trim(text.substr(eq + 1)); - const std::string where = "line " + std::to_string(lineno) + ": "; - if (key == "width" || key == "height") { - std::uint32_t v = 0; - if (!parse_u32(value, v) || v < 1 || v > 4096) return error = where + "width/height must be 1..4096", false; - if (key == "width") s.width = v, s.has_width = true; - else s.height = v, s.has_height = true; - } else if (key == "format") { - s.format_name = value; - if (value == "R8G8B8A8_UNORM") s.format = VK_FORMAT_R8G8B8A8_UNORM, s.bytes_per_texel = 4; - else if (value == "R16G16B16A16_SFLOAT") s.format = VK_FORMAT_R16G16B16A16_SFLOAT, s.bytes_per_texel = 8; - else if (value == "R32G32B32A32_SFLOAT") s.format = VK_FORMAT_R32G32B32A32_SFLOAT, s.bytes_per_texel = 16; - else if (value == "R32_SFLOAT") s.format = VK_FORMAT_R32_SFLOAT, s.bytes_per_texel = 4; - else if (value == "R8G8B8A8_UINT") s.format = VK_FORMAT_R8G8B8A8_UINT, s.bytes_per_texel = 4; - else if (value == "R8G8B8A8_SINT") s.format = VK_FORMAT_R8G8B8A8_SINT, s.bytes_per_texel = 4; - else return error = where + "unknown format '" + value + "'", false; - s.has_format = true; - } else if (key == "texels") { - s.texels_path = value, s.has_texels = true; - } else if (key == "tsharp") { - std::size_t start = 0; - for (int i = 0; i < 8; ++i) { - const std::size_t comma = i == 7 ? std::string::npos : value.find(',', start); - if ((i < 7) == (comma == std::string::npos)) return error = where + "tsharp needs 8 uint32", false; - if (!parse_u32(trim(value.substr(start, comma == std::string::npos ? comma : comma - start)), s.tsharp[i])) - return error = where + "tsharp needs 8 uint32 (decimal or 0x hex)", false; - if (comma != std::string::npos) start = comma + 1; - } - s.has_tsharp = true; - } else return error = where + "unknown key '" + key + "'", false; - } - if (!s.has_width || !s.has_height) error = "missing width/height"; - else if (!s.has_format) error = "missing format"; - else if (!s.has_texels) error = "missing texels"; - else if (!s.has_tsharp) error = "missing tsharp"; - else return true; - return false; -} -} // namespace - -int main(int argc, char** argv) { - if (argc != 5) { - std::fprintf(stderr, "usage: vk_image_fuzz \n"); - return 2; - } - Spec spec; - { - std::string error; - if (!parse_spec(argv[4], spec, error)) { - std::fprintf(stderr, "spec: %s\n", error.c_str()); - return 1; - } - } - std::vector texels; - { - std::ifstream f(spec.texels_path.c_str(), std::ios::binary); - if (!f) { - std::fprintf(stderr, "spec: cannot open texels '%s'\n", spec.texels_path.c_str()); - return 1; - } - texels.assign(std::istreambuf_iterator(f), {}); - const std::uint64_t want = std::uint64_t(spec.width) * spec.height * spec.bytes_per_texel; - if (std::uint64_t(texels.size()) != want) { - std::fprintf(stderr, "spec: texels '%s' is %llu bytes, want %llu\n", spec.texels_path.c_str(), - static_cast(texels.size()), static_cast(want)); - return 1; - } - } - constexpr std::uint32_t W = 64, H = 64; - const PFN_vkGetInstanceProcAddr gipa = load_vulkan(); - if (!gipa) return 1; - VkInstance inst = VK_NULL_HANDLE; -#define LI(n) const auto n = reinterpret_cast(gipa(inst, #n)) - LI(vkCreateInstance); LI(vkEnumerateInstanceLayerProperties); - const char* env = std::getenv("LEONIDA_VK_VALIDATION"); - const bool validation = env && std::strcmp(env, "0") != 0; - const char* layer = "VK_LAYER_KHRONOS_validation", *debug_utils = VK_EXT_DEBUG_UTILS_EXTENSION_NAME; - VkDebugUtilsMessengerCreateInfoEXT messenger_info{.sType = VK_STRUCTURE_TYPE_DEBUG_UTILS_MESSENGER_CREATE_INFO_EXT, - .messageSeverity = VK_DEBUG_UTILS_MESSAGE_SEVERITY_WARNING_BIT_EXT | - VK_DEBUG_UTILS_MESSAGE_SEVERITY_ERROR_BIT_EXT, - .messageType = VK_DEBUG_UTILS_MESSAGE_TYPE_GENERAL_BIT_EXT | - VK_DEBUG_UTILS_MESSAGE_TYPE_VALIDATION_BIT_EXT, - .pfnUserCallback = on_message}; - VkApplicationInfo app{.sType = VK_STRUCTURE_TYPE_APPLICATION_INFO, .apiVersion = VK_API_VERSION_1_2}; - VkInstanceCreateInfo ici{.sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO, .pApplicationInfo = &app}; - if (validation) { - std::uint32_t count = 0; - vkEnumerateInstanceLayerProperties(&count, nullptr); - std::vector layers(count); - vkEnumerateInstanceLayerProperties(&count, layers.data()); - bool found = false; - for (const auto& p : layers) found = found || std::strcmp(p.layerName, layer) == 0; - if (!found) { - std::fprintf(stderr, "LEONIDA_VK_VALIDATION is set but %s is not installed\n", layer); - return 1; - } - ici.pNext = &messenger_info, ici.enabledLayerCount = ici.enabledExtensionCount = 1; - ici.ppEnabledLayerNames = &layer, ici.ppEnabledExtensionNames = &debug_utils; - } - CHECK(vkCreateInstance(&ici, nullptr, &inst)); - VkDebugUtilsMessengerEXT messenger = VK_NULL_HANDLE; - if (validation) { - LI(vkCreateDebugUtilsMessengerEXT); - CHECK(vkCreateDebugUtilsMessengerEXT(inst, &messenger_info, nullptr, &messenger)); - } - LI(vkEnumeratePhysicalDevices); LI(vkGetPhysicalDeviceProperties); LI(vkGetPhysicalDeviceQueueFamilyProperties); - LI(vkGetPhysicalDeviceMemoryProperties); LI(vkGetPhysicalDeviceFeatures2); LI(vkGetPhysicalDeviceProperties2); - LI(vkCreateDevice); LI(vkGetDeviceProcAddr); LI(vkGetPhysicalDeviceFormatProperties); - std::uint32_t n = 0; - vkEnumeratePhysicalDevices(inst, &n, nullptr); - std::vector pds(n); - vkEnumeratePhysicalDevices(inst, &n, pds.data()); - VkPhysicalDevice pd = VK_NULL_HANDLE; - int best_rank = -1; - for (auto d : pds) { - VkPhysicalDeviceProperties p; - vkGetPhysicalDeviceProperties(d, &p); - if (p.apiVersion < VK_API_VERSION_1_2 || !leonida::vulkan_device_wanted(p.deviceName)) continue; - // the runtime's pick: the first device of the highest rank (native driver over Dozen, #915) - if (const int rank = leonida::vulkan_device_rank(static_cast(p.deviceType), p.vendorID); - rank > best_rank) { - best_rank = rank; - pd = d; - } - } - if (!pd && !leonida::vulkan_device_filter().empty()) { // a filter matching nothing fails, never skips - std::fprintf(stderr, "LEONIDA_VK_DEVICE=%s: no Vulkan 1.2 device matches\n", - leonida::vulkan_device_filter().c_str()); - return 1; - } - if (!pd) { - std::printf("unsupported: no Vulkan 1.2 device\n"); - return unsupported; - } - VkPhysicalDeviceVulkan12Properties props12{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_2_PROPERTIES}; - VkPhysicalDeviceProperties2 props{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROPERTIES_2, &props12}; - vkGetPhysicalDeviceProperties2(pd, &props); - std::printf("device: %s%s\n", props.properties.deviceName, validation ? " (validation on)" : ""); - // Every format, UINT/SINT included, is a sampled image: a translated image_load fetches it from the sampled - // array, through a uint/sint alias for integer formats (SHADER-151), as the runtime binds a read-only texture. - VkFormatProperties format_props{}; - vkGetPhysicalDeviceFormatProperties(pd, spec.format, &format_props); - if (!(format_props.optimalTilingFeatures & VK_FORMAT_FEATURE_SAMPLED_IMAGE_BIT)) { - std::printf("unsupported: %s lacks the required image feature\n", spec.format_name.c_str()); - return unsupported; - } - // The pipeline layout pushes the translated user-data block (144 bytes by default, or 128 bytes under - // LEONIDA_PC_TAIL_UBO=1 for rdna2spirv.py --pc-tail-ubo). A device with fewer push constant bytes (128 on - // Intel Arc and AMD's Windows driver for RDNA2 iGPUs) can't take 144: a device limit, not a wrong result (TEST-149). - const bool pc_tail = pc_tail_requested(); - const std::uint32_t push_bytes = pc_tail ? 128u : 144u; - if (props.properties.limits.maxPushConstantsSize < push_bytes) { - std::printf("unsupported: need %u push constant bytes, device has %u\n", push_bytes, - props.properties.limits.maxPushConstantsSize); - return unsupported; - } - VkPhysicalDeviceVulkan12Features have12{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_2_FEATURES}; - VkPhysicalDeviceFeatures2 have{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2, &have12}; - vkGetPhysicalDeviceFeatures2(pd, &have); - // Name the missing feature(s): one message per run is not enough to tell which one stopped it. - std::string missing; - const auto need = [&missing](bool present, const char* name) { - if (present) return; - if (!missing.empty()) missing += ", "; - missing += name; - }; - need(have12.bufferDeviceAddress, "bufferDeviceAddress"); - need(have12.runtimeDescriptorArray, "runtimeDescriptorArray"); - need(have.features.shaderInt64, "shaderInt64"); - need(have.features.shaderSampledImageArrayDynamicIndexing, "shaderSampledImageArrayDynamicIndexing"); - need(have.features.fragmentStoresAndAtomics, "fragmentStoresAndAtomics"); - // No without-format storage-image feature: a translated image_load fetches every format from the sampled - // arrays (SHADER-151), so Intel Xe-LP, which lacks shaderStorageImageReadWithoutFormat, runs these cases too. - if (!missing.empty()) { - std::printf("unsupported: the device lacks %s\n", missing.c_str()); - return unsupported; - } - BindlessFeatures device_flags{ - have12.descriptorBindingSampledImageUpdateAfterBind && have12.descriptorBindingStorageImageUpdateAfterBind && - have12.descriptorBindingStorageBufferUpdateAfterBind, - have12.descriptorBindingPartiallyBound == VK_TRUE}; - VkPhysicalDeviceVulkan12Features enable12{.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_2_FEATURES, - .descriptorIndexing = have12.descriptorIndexing, - .descriptorBindingSampledImageUpdateAfterBind = device_flags.update_after_bind, - .descriptorBindingStorageImageUpdateAfterBind = device_flags.update_after_bind, - .descriptorBindingStorageBufferUpdateAfterBind = device_flags.update_after_bind, - .descriptorBindingPartiallyBound = device_flags.partially_bound, - .runtimeDescriptorArray = VK_TRUE, - .bufferDeviceAddress = VK_TRUE}; - VkPhysicalDeviceFeatures2 enable{.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2, - .pNext = &enable12, - .features = {.fragmentStoresAndAtomics = VK_TRUE, - .shaderSampledImageArrayDynamicIndexing = VK_TRUE, - .shaderInt64 = VK_TRUE}}; - std::uint32_t qn = 0; - vkGetPhysicalDeviceQueueFamilyProperties(pd, &qn, nullptr); - std::vector qf(qn); - vkGetPhysicalDeviceQueueFamilyProperties(pd, &qn, qf.data()); - std::uint32_t qi = 0; - while (qi < qn && !(qf[qi].queueFlags & VK_QUEUE_GRAPHICS_BIT)) ++qi; - if (qi >= qn) { - std::fprintf(stderr, "FAILED graphics queue not found (line %d)\n", __LINE__); - return 1; - } - const float priority = 1; - VkDeviceQueueCreateInfo qci{.sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO, - .queueFamilyIndex = qi, - .queueCount = 1, - .pQueuePriorities = &priority}; - VkDeviceCreateInfo dci{.sType = VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO, .pNext = &enable, .queueCreateInfoCount = 1, .pQueueCreateInfos = &qci}; - VkDevice dev = VK_NULL_HANDLE; - CHECK(vkCreateDevice(pd, &dci, nullptr, &dev)); -#define LD(n) const auto n = reinterpret_cast(vkGetDeviceProcAddr(dev, #n)) - LD(vkGetDeviceQueue); LD(vkCreateImage); LD(vkGetImageMemoryRequirements); LD(vkAllocateMemory); LD(vkBindImageMemory); LD(vkCreateImageView); - LD(vkCreateRenderPass); LD(vkCreateFramebuffer); LD(vkCreateShaderModule); LD(vkCreatePipelineLayout); LD(vkCreateGraphicsPipelines); LD(vkCreateCommandPool); - LD(vkAllocateCommandBuffers); LD(vkBeginCommandBuffer); LD(vkCmdBeginRenderPass); LD(vkCmdBindPipeline); LD(vkCmdDraw); LD(vkCmdEndRenderPass); - LD(vkCmdCopyImageToBuffer); LD(vkCmdCopyBufferToImage); LD(vkEndCommandBuffer); LD(vkQueueSubmit); LD(vkQueueWaitIdle); LD(vkCreateBuffer); - LD(vkResetCommandBuffer); LD(vkGetBufferMemoryRequirements); LD(vkBindBufferMemory); LD(vkMapMemory); LD(vkCmdBindDescriptorSets); LD(vkCmdPushConstants); - LD(vkCmdPipelineBarrier); LD(vkDeviceWaitIdle); LD(vkDestroyPipeline); LD(vkDestroyPipelineLayout); LD(vkDestroyCommandPool); LD(vkDestroyShaderModule); - LD(vkDestroyFramebuffer); LD(vkDestroyRenderPass); LD(vkDestroyImageView); LD(vkDestroyImage); LD(vkDestroyBuffer); LD(vkFreeMemory); LD(vkDestroyDevice); - VkQueue queue = VK_NULL_HANDLE; - vkGetDeviceQueue(dev, qi, 0, &queue); - VkPhysicalDeviceMemoryProperties mp; - vkGetPhysicalDeviceMemoryProperties(pd, &mp); - const auto memtype = [&](std::uint32_t bits, VkMemoryPropertyFlags want) { - for (std::uint32_t i = 0; i < mp.memoryTypeCount; i++) - if ((bits & (1u << i)) && (mp.memoryTypes[i].propertyFlags & want) == want) return i; - return 0u; - }; - std::vector allocations; - const auto make_buffer = [&](VkDeviceSize size, VkBufferUsageFlags usage, VkBuffer* b, void** map) { - VkBufferCreateInfo bi{.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO, .size = size, .usage = usage}; - if (VkResult r = vkCreateBuffer(dev, &bi, nullptr, b)) return r; - VkMemoryRequirements mr; - vkGetBufferMemoryRequirements(dev, *b, &mr); - VkMemoryAllocateInfo ai{.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO, - .allocationSize = mr.size, - .memoryTypeIndex = memtype(mr.memoryTypeBits, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | - VK_MEMORY_PROPERTY_HOST_COHERENT_BIT)}; - VkDeviceMemory m; - if (VkResult r = vkAllocateMemory(dev, &ai, nullptr, &m)) return r; - allocations.push_back(m); - if (VkResult r = vkBindBufferMemory(dev, *b, m, 0)) return r; - return vkMapMemory(dev, m, 0, size, 0, map); - }; - const auto make_image = [&](VkFormat format, std::uint32_t w, std::uint32_t h, VkImageUsageFlags usage, - VkImage* image, VkImageView* view) { - VkImageCreateInfo ii{.sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO, - .imageType = VK_IMAGE_TYPE_2D, - .format = format, - .extent = {w, h, 1}, - .mipLevels = 1, - .arrayLayers = 1, - .samples = VK_SAMPLE_COUNT_1_BIT, - .tiling = VK_IMAGE_TILING_OPTIMAL, - .usage = usage}; - if (VkResult r = vkCreateImage(dev, &ii, nullptr, image)) return r; - VkMemoryRequirements mr; - vkGetImageMemoryRequirements(dev, *image, &mr); - VkMemoryAllocateInfo ai{.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO, - .allocationSize = mr.size, - .memoryTypeIndex = memtype(mr.memoryTypeBits, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT)}; - VkDeviceMemory m; - if (VkResult r = vkAllocateMemory(dev, &ai, nullptr, &m)) return r; - allocations.push_back(m); - if (VkResult r = vkBindImageMemory(dev, *image, m, 0)) return r; - VkImageViewCreateInfo vi{.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO, - .image = *image, - .viewType = VK_IMAGE_VIEW_TYPE_2D, - .format = format, - .subresourceRange = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1}}; - return vkCreateImageView(dev, &vi, nullptr, view); - }; - // The sampled image from the spec, uploaded through a staging buffer. - VkBuffer staging; - void* staging_map = nullptr; - CHECK(make_buffer(static_cast(texels.size()), VK_BUFFER_USAGE_TRANSFER_SRC_BIT, &staging, &staging_map)); - std::memcpy(staging_map, texels.data(), texels.size()); - VkImage image = VK_NULL_HANDLE; - VkImageView view = VK_NULL_HANDLE; - const VkImageLayout image_layout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL; - CHECK(make_image(spec.format, spec.width, spec.height, VK_IMAGE_USAGE_SAMPLED_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT, - &image, &view)); - // Render target, pass and framebuffer. - constexpr VkFormat target_format = VK_FORMAT_R32G32B32A32_SFLOAT; - VkImage target = VK_NULL_HANDLE; - VkImageView target_view = VK_NULL_HANDLE; - CHECK(make_image(target_format, W, H, VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | VK_IMAGE_USAGE_TRANSFER_SRC_BIT, &target, - &target_view)); - VkAttachmentDescription ad{.format = target_format, - .samples = VK_SAMPLE_COUNT_1_BIT, - .loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR, - .storeOp = VK_ATTACHMENT_STORE_OP_STORE, - .stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE, - .stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE, - .initialLayout = VK_IMAGE_LAYOUT_UNDEFINED, - .finalLayout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL}; - const VkAttachmentReference ar{.attachment = 0, .layout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL}; - VkSubpassDescription sd{.pipelineBindPoint = VK_PIPELINE_BIND_POINT_GRAPHICS, .colorAttachmentCount = 1, .pColorAttachments = &ar}; - // The read back that follows the pass waits for its last write and its final layout transition. - VkSubpassDependency after{.srcSubpass = 0, - .dstSubpass = VK_SUBPASS_EXTERNAL, - .srcStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT, - .dstStageMask = VK_PIPELINE_STAGE_TRANSFER_BIT, - .srcAccessMask = VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT, - .dstAccessMask = VK_ACCESS_TRANSFER_READ_BIT}; - VkRenderPassCreateInfo rpi{.sType = VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO, - .attachmentCount = 1, - .pAttachments = &ad, - .subpassCount = 1, - .pSubpasses = &sd, - .dependencyCount = 1, - .pDependencies = &after}; - VkRenderPass pass = VK_NULL_HANDLE; - CHECK(vkCreateRenderPass(dev, &rpi, nullptr, &pass)); - VkFramebufferCreateInfo fbi{.sType = VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO, - .renderPass = pass, - .attachmentCount = 1, - .pAttachments = &target_view, - .width = W, - .height = H, - .layers = 1}; - VkFramebuffer framebuffer = VK_NULL_HANDLE; - CHECK(vkCreateFramebuffer(dev, &fbi, nullptr, &framebuffer)); - VkBuffer readback = VK_NULL_HANDLE; - void* readback_map = nullptr; - CHECK(make_buffer(VkDeviceSize(W) * H * 16, VK_BUFFER_USAGE_TRANSFER_DST_BIT, &readback, &readback_map)); - VkShaderModule vs = VK_NULL_HANDLE, fs = VK_NULL_HANDLE; - for (int stage = 0; stage < 2; ++stage) { - const auto code = read_spv(argv[1 + stage]); - if (code.empty()) { - std::fprintf(stderr, "cannot read %s\n", argv[1 + stage]); - return 1; - } - VkShaderModuleCreateInfo smi{.sType = VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO, .codeSize = code.size() * 4, .pCode = code.data()}; - CHECK(vkCreateShaderModule(dev, &smi, nullptr, stage ? &fs : &vs)); - } - VkCommandPoolCreateInfo cpi{.sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO, - .flags = VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT, - .queueFamilyIndex = qi}; - VkCommandPool pool = VK_NULL_HANDLE; - CHECK(vkCreateCommandPool(dev, &cpi, nullptr, &pool)); - VkCommandBufferAllocateInfo cai{ - .sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO, .commandPool = pool, .commandBufferCount = 1}; - VkCommandBuffer cmd = VK_NULL_HANDLE; - CHECK(vkAllocateCommandBuffers(dev, &cai, &cmd)); - const VkCommandBufferBeginInfo begin{VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO}; - const auto submit = [&]() { - if (VkResult r = vkEndCommandBuffer(cmd)) return r; - VkSubmitInfo si{.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO, .commandBufferCount = 1, .pCommandBuffers = &cmd}; - if (VkResult r = vkQueueSubmit(queue, 1, &si, VK_NULL_HANDLE)) return r; - return vkQueueWaitIdle(queue); - }; - // Upload the texels, then transition to the layout used by the shader's descriptor. - CHECK(vkBeginCommandBuffer(cmd, &begin)); - { - VkImageMemoryBarrier ib{.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, - .dstAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT, - .oldLayout = VK_IMAGE_LAYOUT_UNDEFINED, - .newLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, - .srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED, - .dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED, - .image = image, - .subresourceRange = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1}}; - vkCmdPipelineBarrier(cmd, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, 0, 0, nullptr, 0, - nullptr, 1, &ib); - VkBufferImageCopy c{.imageSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1}, .imageExtent = {spec.width, spec.height, 1}}; - vkCmdCopyBufferToImage(cmd, staging, image, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, &c); - ib.oldLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, ib.newLayout = image_layout; - ib.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT, ib.dstAccessMask = VK_ACCESS_SHADER_READ_BIT; - vkCmdPipelineBarrier(cmd, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT, 0, 0, nullptr, - 0, nullptr, 1, &ib); - } - CHECK(submit()); - // Does a set with these flags fit the device? Every binding is visible to every stage. - constexpr std::uint32_t sampled_total = 4096 + 1024 + 256 + 256, sampler_total = 1024, storage_total = 1024 + 13 * 256; - const auto fits = [&](const BindlessFeatures& f) { - const VkPhysicalDeviceLimits& l = props.properties.limits; - if (f.update_after_bind) - return props12.maxPerStageDescriptorUpdateAfterBindSampledImages >= sampled_total && - props12.maxPerStageDescriptorUpdateAfterBindSamplers >= sampler_total && - props12.maxPerStageDescriptorUpdateAfterBindStorageImages >= storage_total && - props12.maxPerStageUpdateAfterBindResources >= sampled_total + sampler_total + storage_total + 1 && - props12.maxDescriptorSetUpdateAfterBindSampledImages >= sampled_total && - props12.maxDescriptorSetUpdateAfterBindSamplers >= sampler_total && - props12.maxDescriptorSetUpdateAfterBindStorageImages >= storage_total; - return l.maxPerStageDescriptorSampledImages >= sampled_total && l.maxPerStageDescriptorSamplers >= sampler_total && - l.maxPerStageDescriptorStorageImages >= storage_total && - l.maxPerStageResources >= sampled_total + sampler_total + storage_total + 1 && - l.maxDescriptorSetSampledImages >= sampled_total && l.maxDescriptorSetSamplers >= sampler_total && - l.maxDescriptorSetStorageImages >= storage_total; - }; - BindlessFeatures flags = device_flags; - if (!fits(flags)) flags = {}; - if (!fits(flags)) { - std::printf("unsupported: the bindless set does not fit this device's descriptor limits\n"); - return unsupported; - } - std::optional set; - set.emplace(vkGetDeviceProcAddr, dev, mp, flags); - if (!set->ok() || !set->layout() || !set->set()) { - std::printf("unsupported: cannot create the bindless set\n"); - return unsupported; - } - const std::uint32_t index = set->add_image(ImageDimension::dim_2d, view, image_layout); - if (index < 1) { - std::fprintf(stderr, "FAILED add_image -> 0 (line %d)\n", __LINE__); - return 1; - } - set->insert_key(make_tsharp_key(spec.tsharp), index); - const VkPushConstantRange push{.stageFlags = VK_SHADER_STAGE_VERTEX_BIT | VK_SHADER_STAGE_FRAGMENT_BIT, .size = push_bytes}; - const VkDescriptorSetLayout set_layout = set->layout(); - VkPipelineLayoutCreateInfo pli{.sType = VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO, - .setLayoutCount = 1, - .pSetLayouts = &set_layout, - .pushConstantRangeCount = 1, - .pPushConstantRanges = &push}; - VkPipelineLayout pipeline_layout = VK_NULL_HANDLE; - if (vkCreatePipelineLayout(dev, &pli, nullptr, &pipeline_layout) != VK_SUCCESS) { - std::printf("unsupported: cannot create the pipeline layout\n"); - return unsupported; - } - VkPipelineShaderStageCreateInfo stages[2]{{.sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO, - .stage = VK_SHADER_STAGE_VERTEX_BIT, - .module = vs, - .pName = "main"}, - {.sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO, - .stage = VK_SHADER_STAGE_FRAGMENT_BIT, - .module = fs, - .pName = "main"}}; - const VkPipelineVertexInputStateCreateInfo vertex_input{.sType = VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO}; - VkPipelineInputAssemblyStateCreateInfo assembly{.sType = VK_STRUCTURE_TYPE_PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO, - .topology = VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST}; - const VkViewport viewport{.x = 0, .y = 0, .width = float(W), .height = float(H), .maxDepth = 1}; - const VkRect2D scissor{.offset = {0, 0}, .extent = {W, H}}; - VkPipelineViewportStateCreateInfo viewports{.sType = VK_STRUCTURE_TYPE_PIPELINE_VIEWPORT_STATE_CREATE_INFO, - .viewportCount = 1, - .pViewports = &viewport, - .scissorCount = 1, - .pScissors = &scissor}; - VkPipelineRasterizationStateCreateInfo raster{.sType = VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_STATE_CREATE_INFO, - .cullMode = VK_CULL_MODE_NONE, - .lineWidth = 1}; - VkPipelineMultisampleStateCreateInfo multisample{.sType = VK_STRUCTURE_TYPE_PIPELINE_MULTISAMPLE_STATE_CREATE_INFO, - .rasterizationSamples = VK_SAMPLE_COUNT_1_BIT}; - VkPipelineColorBlendAttachmentState blend_attachment{.colorWriteMask = 0xf}; - VkPipelineColorBlendStateCreateInfo blend{.sType = VK_STRUCTURE_TYPE_PIPELINE_COLOR_BLEND_STATE_CREATE_INFO, - .attachmentCount = 1, - .pAttachments = &blend_attachment}; - VkGraphicsPipelineCreateInfo gpi{.sType = VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO, - .stageCount = 2, - .pStages = stages, - .pVertexInputState = &vertex_input, - .pInputAssemblyState = &assembly, - .pViewportState = &viewports, - .pRasterizationState = &raster, - .pMultisampleState = &multisample, - .pColorBlendState = &blend, - .layout = pipeline_layout, - .renderPass = pass}; - VkPipeline pipeline = VK_NULL_HANDLE; - CHECK(vkCreateGraphicsPipelines(dev, VK_NULL_HANDLE, 1, &gpi, nullptr, &pipeline)); - // Publish the image index and the table, then draw and read back. - vkResetCommandBuffer(cmd, 0); - CHECK(vkBeginCommandBuffer(cmd, &begin)); - if (!set->flush(cmd)) { - std::fprintf(stderr, "FAILED set->flush (line %d)\n", __LINE__); - return 1; - } - CHECK(submit()); - vkResetCommandBuffer(cmd, 0); - CHECK(vkBeginCommandBuffer(cmd, &begin)); - if (!set->fallbacks_ready()) set->record_fallback_init(cmd); - VkClearValue clear{}; - VkRenderPassBeginInfo rbi{.sType = VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO, - .renderPass = pass, - .framebuffer = framebuffer, - .renderArea = scissor, - .clearValueCount = 1, - .pClearValues = &clear}; - vkCmdBeginRenderPass(cmd, &rbi, VK_SUBPASS_CONTENTS_INLINE); - vkCmdBindPipeline(cmd, VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline); - const VkDescriptorSet bound = set->set(); - vkCmdBindDescriptorSets(cmd, VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline_layout, 0, 1, &bound, 0, nullptr); - std::uint32_t block[36] = {}; - std::memcpy(block + 8, spec.tsharp, sizeof(spec.tsharp)); // s[8:15]: the T# the fragment shader loads - vkCmdPushConstants(cmd, pipeline_layout, VK_SHADER_STAGE_VERTEX_BIT | VK_SHADER_STAGE_FRAGMENT_BIT, 0, push_bytes, block); - vkCmdDraw(cmd, 3, 1, 0, 0); - vkCmdEndRenderPass(cmd); - VkBufferImageCopy rc{.imageSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1}, .imageExtent = {W, H, 1}}; - vkCmdCopyImageToBuffer(cmd, target, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, readback, 1, &rc); - CHECK(submit()); - { - std::ofstream out(argv[3], std::ios::binary); - out.write(static_cast(readback_map), VkDeviceSize(W) * H * 16); - if (!out) { - std::fprintf(stderr, "cannot write %s\n", argv[3]); - return 1; - } - } - std::printf("vk_image_fuzz: %ux%u %s wrote %s\n", spec.width, spec.height, spec.format_name.c_str(), argv[3]); - // Let validation observe resource and device destruction before reporting its final error count. - vkDeviceWaitIdle(dev); - set.reset(); // its buffers and descriptor set must die before the device - vkDestroyPipeline(dev, pipeline, nullptr), vkDestroyPipelineLayout(dev, pipeline_layout, nullptr); - vkDestroyCommandPool(dev, pool, nullptr), vkDestroyFramebuffer(dev, framebuffer, nullptr); - vkDestroyRenderPass(dev, pass, nullptr), vkDestroyShaderModule(dev, fs, nullptr), vkDestroyShaderModule(dev, vs, nullptr); - vkDestroyImageView(dev, target_view, nullptr), vkDestroyImageView(dev, view, nullptr); - vkDestroyImage(dev, target, nullptr), vkDestroyImage(dev, image, nullptr); - vkDestroyBuffer(dev, readback, nullptr), vkDestroyBuffer(dev, staging, nullptr); - for (const auto memory : allocations) vkFreeMemory(dev, memory, nullptr); - vkDestroyDevice(dev, nullptr); - if (messenger) { - LI(vkDestroyDebugUtilsMessengerEXT); - vkDestroyDebugUtilsMessengerEXT(inst, messenger, nullptr); - } - LI(vkDestroyInstance); - vkDestroyInstance(inst, nullptr); - if (g_validation_errors) { - std::fprintf(stderr, "%u validation errors\n", g_validation_errors); - return 1; - } - return 0; -} diff --git a/runtime/test/vk_overlapping_occlusion_test.cpp b/runtime/test/vk_overlapping_occlusion_test.cpp deleted file mode 100644 index 9be436515..000000000 --- a/runtime/test/vk_overlapping_occlusion_test.cpp +++ /dev/null @@ -1,609 +0,0 @@ -#include "predicated_copy_controls.h" -// Record synthetic draws between the physical query boundaries emitted by the Leonida replay queue. -#include "vk_test_device.h" -#include "../src/vulkan_backend.h" - -#include -#include -#include -#include - -#define EXPECT(condition) do { \ - if (!(condition)) { std::fprintf(stderr, "line %d: %s\n", __LINE__, #condition); return 1; } \ -} while (0) - -namespace { - -using namespace leonida; -constexpr std::uint32_t side = 8; -constexpr std::uint32_t query_count = 10; -constexpr std::uint32_t statistics_count = 9; -constexpr std::uint32_t statistics_words = 11; // D3D12_QUERY_DATA_PIPELINE_STATISTICS - -VkShaderModule load_shader(vktest::Device& d, const char* path) { - std::ifstream file(path, std::ios::binary | std::ios::ate); - const std::streamoff bytes = file.tellg(); - if (bytes <= 0 || bytes % 4 != 0) return VK_NULL_HANDLE; - std::vector code(static_cast(bytes) / 4); - file.seekg(0); - if (!file.read(reinterpret_cast(code.data()), bytes)) return VK_NULL_HANDLE; - VkShaderModuleCreateInfo info{VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO}; - info.codeSize = static_cast(bytes); - info.pCode = code.data(); - VkShaderModule module = VK_NULL_HANDLE; - if (d.fn("vkCreateShaderModule")(d.device, &info, nullptr, &module) != VK_SUCCESS) - return VK_NULL_HANDLE; - return module; -} - -struct Fixture { - vktest::Device& d; - VkShaderModule vs = VK_NULL_HANDLE, fs = VK_NULL_HANDLE; - VkPipelineLayout layout = VK_NULL_HANDLE; - VkPipeline pipeline = VK_NULL_HANDLE; - VkQueryPool occlusion = VK_NULL_HANDLE, second = VK_NULL_HANDLE, statistics = VK_NULL_HANDLE; - - ~Fixture() { - const auto destroy_pool = d.fn("vkDestroyQueryPool"); - const auto destroy_shader = d.fn("vkDestroyShaderModule"); - if (statistics) destroy_pool(d.device, statistics, nullptr); - if (second) destroy_pool(d.device, second, nullptr); - if (occlusion) destroy_pool(d.device, occlusion, nullptr); - if (pipeline) d.fn("vkDestroyPipeline")(d.device, pipeline, nullptr); - if (layout) d.fn("vkDestroyPipelineLayout")(d.device, layout, nullptr); - if (fs) destroy_shader(d.device, fs, nullptr); - if (vs) destroy_shader(d.device, vs, nullptr); - } - - bool create(const char* vertex, const char* fragment) { - vs = load_shader(d, vertex); - fs = load_shader(d, fragment); - if (!vs || !fs) return false; - VkPipelineLayoutCreateInfo layout_info{VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO}; - if (d.fn("vkCreatePipelineLayout")(d.device, &layout_info, nullptr, &layout) != - VK_SUCCESS) - return false; - const VkPipelineShaderStageCreateInfo stages[] = { - {VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO, nullptr, 0, VK_SHADER_STAGE_VERTEX_BIT, vs, "main"}, - {VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO, nullptr, 0, VK_SHADER_STAGE_FRAGMENT_BIT, fs, "main"}, - }; - const VkPipelineVertexInputStateCreateInfo vi{VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO}; - VkPipelineInputAssemblyStateCreateInfo ia{VK_STRUCTURE_TYPE_PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO}; - ia.topology = VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST; - const VkViewport vp{0, 0, float(side), float(side), 0, 1}; - const VkRect2D scissor{{}, {side, side}}; - VkPipelineViewportStateCreateInfo viewport{VK_STRUCTURE_TYPE_PIPELINE_VIEWPORT_STATE_CREATE_INFO}; - viewport.viewportCount = viewport.scissorCount = 1; - viewport.pViewports = &vp; - viewport.pScissors = &scissor; - VkPipelineRasterizationStateCreateInfo raster{VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_STATE_CREATE_INFO}; - raster.lineWidth = 1; - VkPipelineMultisampleStateCreateInfo ms{VK_STRUCTURE_TYPE_PIPELINE_MULTISAMPLE_STATE_CREATE_INFO}; - ms.rasterizationSamples = VK_SAMPLE_COUNT_1_BIT; - const VkPipelineColorBlendStateCreateInfo blend{VK_STRUCTURE_TYPE_PIPELINE_COLOR_BLEND_STATE_CREATE_INFO}; - const VkPipelineRenderingCreateInfo rendering{VK_STRUCTURE_TYPE_PIPELINE_RENDERING_CREATE_INFO}; - const auto scissor_state = VK_DYNAMIC_STATE_SCISSOR; - VkPipelineDynamicStateCreateInfo dynamic{VK_STRUCTURE_TYPE_PIPELINE_DYNAMIC_STATE_CREATE_INFO}; - dynamic.dynamicStateCount = 1; - dynamic.pDynamicStates = &scissor_state; - VkGraphicsPipelineCreateInfo info{VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO, &rendering}; - info.stageCount = 2; - info.pStages = stages; - info.pVertexInputState = &vi; - info.pInputAssemblyState = &ia; - info.pViewportState = &viewport; - info.pRasterizationState = &raster; - info.pMultisampleState = &ms; - info.pColorBlendState = &blend; - info.pDynamicState = &dynamic; - info.layout = layout; - if (d.fn("vkCreateGraphicsPipelines")( - d.device, VK_NULL_HANDLE, 1, &info, nullptr, &pipeline) != VK_SUCCESS) - return false; - const auto pool = d.fn("vkCreateQueryPool"); - VkQueryPoolCreateInfo query{VK_STRUCTURE_TYPE_QUERY_POOL_CREATE_INFO}; - query.queryType = VK_QUERY_TYPE_OCCLUSION; - query.queryCount = query_count; - if (pool(d.device, &query, nullptr, &occlusion) != VK_SUCCESS || - pool(d.device, &query, nullptr, &second) != VK_SUCCESS) return false; - if (d.pipeline_statistics_query) { - query.queryType = VK_QUERY_TYPE_PIPELINE_STATISTICS; - query.queryCount = statistics_count; - query.pipelineStatistics = 0x7ff; // the same counters as the D3D12 heap - if (pool(d.device, &query, nullptr, &statistics) != VK_SUCCESS) return false; - } - return true; - } - - void draw(VkCommandBuffer cb, std::uint32_t extent) const { - VkRenderingInfo rendering{VK_STRUCTURE_TYPE_RENDERING_INFO}; - rendering.renderArea.extent = {side, side}; - rendering.layerCount = 1; - d.fn("vkCmdBeginRendering")(cb, &rendering); - d.fn("vkCmdBindPipeline")(cb, VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline); - const VkRect2D scissor{{}, {extent, extent}}; - d.fn("vkCmdSetScissor")(cb, 0, 1, &scissor); - d.fn("vkCmdDraw")(cb, 3, 1, 0, 0); - d.fn("vkCmdEndRendering")(cb); - } -}; - -// Main's replay has no D3D12 draws yet. Insert one native Vulkan draw while each actual query recorded -// by the queue is active, immediately before its end. Everything else goes to the real Vulkan driver. -struct Draws { - Fixture& fixture; - std::vector extents; - std::size_t next = 0; - bool overflow = false; - bool every = false; // --bisect: one 1x1 draw before every end, no schedule - bool no_draw = false; // --bisect --no-draw: no draws at all, every query stays empty -}; -Draws* draws = nullptr; - -VKAPI_ATTR void VKAPI_CALL end_query_with_draw(VkCommandBuffer cb, VkQueryPool pool, std::uint32_t index) { - if (draws->every) { - if (!draws->no_draw) draws->fixture.draw(cb, 1); - } else if (draws->next == draws->extents.size()) { - draws->overflow = true; - } else if (const auto extent = draws->extents[draws->next++]) { - draws->fixture.draw(cb, extent); - } - draws->fixture.d.fn("vkCmdEndQuery")(cb, pool, index); -} - -VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL get_device_proc(VkDevice device, const char* name) { - if (std::strcmp(name, "vkCmdEndQuery") == 0) return reinterpret_cast(end_query_with_draw); - return draws->fixture.d.device_proc(device, name); -} - -// --bisect (D3D-189, #1540): the test's query patterns one by one, each in its own submission. Ungated, each -// submission is waited for before the next, so the last "running" line before a hang or a lost device names the -// pattern. --gated queues them all behind one semaphore the CPU signals afterwards, as the full test does. Named -// phases run only those, in the order below. Only completion is checked, not values. -// Two switches separate the draw from the resolve: --no-draw leaves every query empty (no rendering scope inside -// it), --no-resolve records the queries but never copies or sums their results. -struct Bisect { - bool enabled = false; - bool gated = false; - bool no_draw = false; - bool no_resolve = false; - std::vector phases; - bool wants(const char* name) const { - return phases.empty() || std::find(phases.begin(), phases.end(), name) != phases.end(); - } -}; - -int run(vktest::Device& d, const char* vertex, const char* fragment, const Bisect& bisect) { - std::uint32_t family_count = 0; - const auto families = d.instance_fn( - "vkGetPhysicalDeviceQueueFamilyProperties"); - families(d.physical, &family_count, nullptr); - std::vector queues(family_count); - families(d.physical, &family_count, queues.data()); - if (!d.occlusion_query_precise || !(queues[d.family].queueFlags & VK_QUEUE_COMPUTE_BIT)) return 77; - - Fixture fixture{d}; - EXPECT(fixture.create(vertex, fragment)); - constexpr std::uint32_t bursts = 130; - Draws schedule{fixture, {8, 4, 2, 8, 4, 2, 3}}; - schedule.extents.insert(schedule.extents.end(), 2 * bursts + 1, 1); - // The statistics lists below: a split query (two segments), two unsplit references and a second split query. - if (d.pipeline_statistics_query) schedule.extents.insert(schedule.extents.end(), {3, 5, 3, 5, 3, 5}); - schedule.extents.insert(schedule.extents.end(), {2, 0, 0, 0, 1}); - // The D3D-252 lists: three crossing statistics segment ends, three statistics references with the same draws, - // then the kind overlap's three segment ends and three occlusion references carrying the same draws. - if (d.pipeline_statistics_query) schedule.extents.insert(schedule.extents.end(), {7, 9, 11, 7, 9, 11}); - schedule.extents.insert(schedule.extents.end(), {19, 21, 23, 19, 21, 23}); - schedule.every = bisect.enabled; - schedule.no_draw = bisect.no_draw; - draws = &schedule; - VulkanContext context(get_device_proc, d.device, true, d.conditional_rendering); - EXPECT(context.loaded()); - VkPhysicalDeviceMemoryProperties memory{}; - const auto get_memory = d.instance_fn("vkGetPhysicalDeviceMemoryProperties"); - get_memory(d.physical, &memory); - context.set_occlusion_resolve_memory(memory); - VkPhysicalDeviceProperties properties{}; - d.instance_fn("vkGetPhysicalDeviceProperties")(d.physical, &properties); - context.configure_predication(get_device_proc, memory, properties.limits.maxStorageBufferRange, d.family); - VulkanFence gate(context, 0); - PredicatedCopyControl copy_control; - EXPECT(copy_control.create(d, context, properties.limits)); - VulkanQueue queue(context, d.queue, d.family); - EXPECT(queue.ok() && gate.semaphore()); - // The gate stalls the GPU while the queue replays (the point of this test). A Wait on a fence with no submitted - // Signal is held on the CPU instead (queue_holds.h), so the gate is declared as having one: its Signal is - // "submitted" and the CPU completes it later, as a GPU-side signal behind long work would be. - context.holds().signaled(gate.semaphore(), 1); - struct OpenGate { VulkanFence& fence; ~OpenGate() { fence.signal(1); } } open_gate{gate}; - constexpr QueryHeapId a = 1, b = 2, stats = 3; - constexpr auto occ = d3d12_query::occlusion; - constexpr auto binary = d3d12_query::binary_occlusion; - for (const auto& [id, pool] : {std::pair{a, fixture.occlusion}, std::pair{b, fixture.second}}) - context.add_query_pool(id, {pool, d3d12_query_heap::occlusion, query_count, true, - std::vector(query_count, false)}); - - constexpr ResourceId dst_id = 4, predicate_id = 5; - constexpr VkDeviceSize binding_offset = 24, size = 256; - void* mapping = nullptr; - ResourceBinding dst{}; - dst.buffer = d.buffer(size, VK_BUFFER_USAGE_TRANSFER_DST_BIT, &mapping); - dst.buffer_offset = binding_offset; - dst.size = size - binding_offset; - dst.host_readable = true; // ResolveQueryData writes results that the CPU reads below. - EXPECT(dst.buffer && mapping); - std::memset(mapping, 0xcd, size); - context.add_resource(dst_id, dst); - if (d.conditional_rendering) { - void* words = nullptr; - ResourceBinding predicate{}; - predicate.size = 8; - predicate.buffer = d.buffer(8, VK_BUFFER_USAGE_CONDITIONAL_RENDERING_BIT_EXT | VK_BUFFER_USAGE_TRANSFER_SRC_BIT, &words); - EXPECT(predicate.buffer && words); - std::memset(words, 0, 8); - context.add_resource(predicate_id, predicate); - } - - if (bisect.enabled) { - std::vector> lists; - const auto add = [&](const char* name) -> CommandList* { - if (!bisect.wants(name)) return nullptr; - return &lists.emplace_back(name, CommandList{}).second; - }; - const auto resolve = [&](CommandList* l, const ResolveQueries& r) { - return bisect.no_resolve || l->resolve_queries(r); - }; - if (auto* l = add("crossing")) { // two queries of one heap overlap; resolve while one is active - EXPECT(l->begin_query({a, occ, 0}) && l->begin_query({a, occ, 1}) && l->end_query({a, occ, 0})); - EXPECT(resolve(l, {a, occ, 0, 1, dst_id, 8}) && l->end_query({a, occ, 1})); - EXPECT(resolve(l, {a, occ, 0, 2, dst_id, 24})); - } - if (auto* l = add("active")) { // a resolve inside one active query, without an overlap - EXPECT(l->begin_query({a, occ, 0}) && l->end_query({a, occ, 0}) && l->begin_query({a, occ, 3})); - EXPECT(resolve(l, {a, occ, 0, 1, dst_id, 128}) && l->end_query({a, occ, 3})); - } - if (auto* l = add("nested")) { // the same index in two heaps, one inside the other - EXPECT(l->begin_query({a, occ, 2}) && l->begin_query({b, occ, 2})); - EXPECT(l->end_query({b, occ, 2}) && l->end_query({a, occ, 2})); - EXPECT(resolve(l, {a, occ, 2, 1, dst_id, 40}) && resolve(l, {b, occ, 2, 1, dst_id, 48})); - } - if (auto* l = add("unwritten")) { // a query never begun: zero fill - EXPECT(resolve(l, {b, occ, 0, 1, dst_id, 56})); - } - if (auto* l = add("binary")) { // the binary-occlusion compute resolve - EXPECT(l->begin_query({a, binary, 3}) && l->end_query({a, binary, 3})); - EXPECT(resolve(l, {a, binary, 3, 1, dst_id, 64})); - } - if (d.conditional_rendering) { - if (auto* l = add("predicated")) { // both compute resolves under a false predicate - EXPECT(l->begin_query({a, binary, 3}) && l->end_query({a, binary, 3})); - EXPECT(l->set_predication({predicate_id, 0, d3d12_predication::equal_zero})); - EXPECT(resolve(l, {a, binary, 3, 1, dst_id, 64})); - EXPECT(resolve(l, {a, occ, 0, 1, dst_id, 72})); - EXPECT(resolve(l, {a, binary, 3, 1, dst_id, 80})); - EXPECT(copy_control.record(*l)); - } - } - if (auto* l = add("chunked")) { // 2 * bursts + 1 segments: the summing resolve takes two chunks - EXPECT(l->begin_query({a, occ, 3})); - for (std::uint32_t i = 0; i < bursts; ++i) EXPECT(l->begin_query({b, occ, 0}) && l->end_query({b, occ, 0})); - EXPECT(l->end_query({a, occ, 3})); - EXPECT(resolve(l, {a, occ, 3, 1, dst_id, 88}) && resolve(l, {b, occ, 0, 1, dst_id, 96})); - } - if (auto* l = add("replace")) { // every heap query begun and ended again, then resolved - for (const auto& [heap, index] : {std::pair{a, 0u}, std::pair{a, 1u}, std::pair{a, 2u}, std::pair{b, 2u}}) - EXPECT(l->begin_query({heap, occ, index}) && l->end_query({heap, occ, index})); - EXPECT(resolve(l, {a, occ, 0, 2, dst_id, 112})); - } - EXPECT(!lists.empty()); - std::printf("bisect:%s%s%s\n", bisect.gated ? " gated" : " ungated", bisect.no_draw ? " no-draw" : " draws", - bisect.no_resolve ? " no-resolve" : " resolves"); - // After a TDR, AMD's Windows driver lets vkQueueWaitIdle succeed (#1540); every timeline semaphore then reads - // UINT64_MAX, so the gate's value is checked as well as what the context has seen. - const auto get_value = d.fn("vkGetSemaphoreCounterValue"); - const auto lost = [&] { - std::uint64_t value = 0; - return context.is_device_lost() || get_value(d.device, gate.semaphore(), &value) != VK_SUCCESS || - value == UINT64_MAX; - }; - if (bisect.gated) queue.wait(gate.semaphore(), 1); - for (auto& [name, list] : lists) { - EXPECT(list.close()); - std::printf("running %s\n", name); - std::fflush(stdout); - const CommandList* submit[] = {&list}; - const ReplayResult result = queue.execute(submit); - if (result != ReplayResult::success) { - std::printf("%s: execute returned %d\n", name, int(result)); - return 1; - } - if (!bisect.gated && (!queue.idle() || lost())) { - std::printf("%s: device lost\n", name); - return 1; - } - } - if (bisect.gated) { - EXPECT(gate.signal(1)); - if (!queue.idle() || lost()) { - std::printf("gated: device lost\n"); - return 1; - } - } - std::printf("bisect: every phase completed%s\n", bisect.gated ? " (gated)" : ""); - return 0; - } - - CommandList crossing; - EXPECT(crossing.begin_query({a, occ, 0})); - EXPECT(crossing.begin_query({a, occ, 1})); - EXPECT(crossing.end_query({a, occ, 0})); - EXPECT(crossing.resolve_queries({a, occ, 0, 1, dst_id, 8})); // B is still active - EXPECT(crossing.end_query({a, occ, 1})); - EXPECT(crossing.close()); - CommandList nested; - EXPECT(nested.begin_query({a, occ, 2})); - EXPECT(nested.begin_query({b, occ, 2})); // same index, different logical heaps - EXPECT(nested.end_query({b, occ, 2})); - EXPECT(nested.end_query({a, occ, 2})); - EXPECT(nested.close()); - const CommandList* first[] = {&crossing, &nested}; - queue.wait(gate.semaphore(), 1); - EXPECT(queue.execute(first) == ReplayResult::success); - - CommandList later; - EXPECT(later.resolve_queries({a, occ, 0, 3, dst_id, 24})); - EXPECT(later.resolve_queries({b, occ, 2, 1, dst_id, 48})); - EXPECT(later.resolve_queries({b, occ, 0, 1, dst_id, 56})); // never begun - EXPECT(later.begin_query({a, binary, 3})); - EXPECT(later.end_query({a, binary, 3})); - if (d.conditional_rendering) EXPECT(later.set_predication({predicate_id, 0, d3d12_predication::equal_zero})); - // Alternate the two compute pipelines on the shared scratch buffer, all under the false predicate. - EXPECT(later.resolve_queries({a, binary, 3, 1, dst_id, 64})); - EXPECT(later.resolve_queries({a, occ, 0, 1, dst_id, 72})); - EXPECT(later.resolve_queries({a, binary, 3, 1, dst_id, 80})); - EXPECT(copy_control.record(later)); - EXPECT(later.close()); - const CommandList* second[] = {&later}; - EXPECT(queue.execute(second) == ReplayResult::success); - - CommandList chunked; - EXPECT(chunked.begin_query({a, occ, 3})); - for (std::uint32_t i = 0; i < bursts; ++i) { - EXPECT(chunked.begin_query({b, occ, 0})); - EXPECT(chunked.end_query({b, occ, 0})); - } - EXPECT(chunked.end_query({a, occ, 3})); - EXPECT(chunked.resolve_queries({a, occ, 3, 1, dst_id, 88})); - EXPECT(chunked.resolve_queries({b, occ, 0, 1, dst_id, 96})); - EXPECT(chunked.close()); - const CommandList* third[] = {&chunked}; - EXPECT(queue.execute(third) == ReplayResult::success); - - CommandList bundle; - EXPECT(bundle.begin_query({a, occ, 0})); - EXPECT(bundle.end_query({a, occ, 0})); - EXPECT(bundle.close()); - CommandList duplicate; - EXPECT(duplicate.begin_query({a, occ, 0})); - EXPECT(duplicate.execute_bundle(bundle)); - EXPECT(duplicate.end_query({a, occ, 0})); - EXPECT(duplicate.close()); - const CommandList* invalid[] = {&duplicate}; - EXPECT(queue.execute(invalid) == ReplayResult::invalid_query); - - // D3D-162: an occlusion sum inside a pipeline-statistics query. Its dispatch must not reach the application's - // counters, so the queue splits the statistics query around the resolve and sums the segments. Each segment - // gets one native draw before it ends (extents 3 and 5); two unsplit queries with the same draws are the - // reference, and CSInvocations stays 0 because no application compute runs. - constexpr ResourceId stats_dst_id = 6; - constexpr VkDeviceSize stats_result = statistics_words * sizeof(std::uint64_t), stats_slots = 10; - void* stats_mapping = nullptr; - ResourceBinding stats_dst{}; - if (fixture.statistics) { - constexpr auto pipeline_statistics = d3d12_query::pipeline_statistics; - context.add_query_pool(stats, {fixture.statistics, d3d12_query_heap::pipeline_statistics, statistics_count, - false, std::vector(statistics_count, false)}); - stats_dst.size = stats_slots * stats_result; - stats_dst.buffer = d.buffer(stats_dst.size, VK_BUFFER_USAGE_TRANSFER_DST_BIT, &stats_mapping); - EXPECT(stats_dst.buffer && stats_mapping); - std::memset(stats_mapping, 0xcd, stats_dst.size); - context.add_resource(stats_dst_id, stats_dst); - CommandList split; - EXPECT(split.begin_query({stats, pipeline_statistics, 0})); - EXPECT(split.resolve_queries({a, occ, 3, 1, dst_id, 0})); // 261 segments: a sum dispatch - EXPECT(split.end_query({stats, pipeline_statistics, 0})); - EXPECT(split.resolve_queries({stats, pipeline_statistics, 0, 1, stats_dst_id, 0})); - EXPECT(split.close()); - CommandList reference; - for (std::uint32_t index : {1u, 2u}) { - EXPECT(reference.begin_query({stats, pipeline_statistics, index})); - EXPECT(reference.end_query({stats, pipeline_statistics, index})); - } - EXPECT(reference.resolve_queries({stats, pipeline_statistics, 1, 2, stats_dst_id, stats_result})); - EXPECT(reference.close()); - // The statistics sum of query 0 is a helper dispatch too, inside query 3. - CommandList nested_sum; - EXPECT(nested_sum.begin_query({stats, pipeline_statistics, 3})); - EXPECT(nested_sum.resolve_queries({stats, pipeline_statistics, 0, 1, stats_dst_id, 4 * stats_result})); - EXPECT(nested_sum.end_query({stats, pipeline_statistics, 3})); - EXPECT(nested_sum.resolve_queries({stats, pipeline_statistics, 3, 1, stats_dst_id, 3 * stats_result})); - EXPECT(nested_sum.close()); - const CommandList* statistics_lists[] = {&split, &reference}; - EXPECT(queue.execute(statistics_lists) == ReplayResult::success); - const CommandList* nested_lists[] = {&nested_sum}; - EXPECT(queue.execute(nested_lists) == ReplayResult::success); - } - - // Overwrite every result from the first physical pool while the GPU is still gated. The first two - // submissions still refer to that pool and must be able to execute once the gate opens. - CommandList replace; - for (const auto& [heap, index] : {std::pair{a, 0u}, std::pair{a, 1u}, std::pair{a, 2u}, std::pair{b, 2u}}) { - EXPECT(replace.begin_query({heap, occ, index})); - EXPECT(replace.end_query({heap, occ, index})); - } - EXPECT(replace.resolve_queries({a, occ, 0, 2, dst_id, 112})); - EXPECT(replace.close()); - const CommandList* fourth[] = {&replace}; - EXPECT(queue.execute(fourth) == ReplayResult::success); - - // A resolve inside one active query, with no overlap. - CommandList single; - EXPECT(single.begin_query({a, occ, 3})); - EXPECT(single.resolve_queries({a, occ, 0, 1, dst_id, 128})); - EXPECT(single.end_query({a, occ, 3})); - EXPECT(single.close()); - const CommandList* fifth[] = {&single}; - EXPECT(queue.execute(fifth) == ReplayResult::success); - // D3D-252: overlapping pipeline-statistics queries and overlapping occlusion kinds. The hook's draw lands in - // the segment that is about to close, so each crossing query's sum covers its own intervals plus the shared - // intersection; the reference queries carry the same draws unsplit, and the sums must match them. - CommandList crossing_stats, stats_references, kind_overlap, kind_references; - if (d.pipeline_statistics_query) { - EXPECT(crossing_stats.begin_query({stats, d3d12_query::pipeline_statistics, 4})); - EXPECT(crossing_stats.begin_query({stats, d3d12_query::pipeline_statistics, 5})); - EXPECT(crossing_stats.end_query({stats, d3d12_query::pipeline_statistics, 4})); - EXPECT(crossing_stats.end_query({stats, d3d12_query::pipeline_statistics, 5})); - EXPECT(crossing_stats.resolve_queries({stats, d3d12_query::pipeline_statistics, 4, 1, stats_dst_id, - 5 * stats_result})); - EXPECT(crossing_stats.resolve_queries({stats, d3d12_query::pipeline_statistics, 5, 1, stats_dst_id, - 6 * stats_result})); - EXPECT(crossing_stats.close()); - for (std::uint32_t index : {6u, 7u, 8u}) { - EXPECT(stats_references.begin_query({stats, d3d12_query::pipeline_statistics, index})); - EXPECT(stats_references.end_query({stats, d3d12_query::pipeline_statistics, index})); - } - EXPECT(stats_references.resolve_queries({stats, d3d12_query::pipeline_statistics, 6, 3, stats_dst_id, - 7 * stats_result})); - EXPECT(stats_references.close()); - } - EXPECT(kind_overlap.begin_query({a, occ, 4})); - EXPECT(kind_overlap.begin_query({a, binary, 5})); - EXPECT(kind_overlap.end_query({a, binary, 5})); - EXPECT(kind_overlap.end_query({a, occ, 4})); - EXPECT(kind_overlap.resolve_queries({a, occ, 4, 1, dst_id, 168})); - EXPECT(kind_overlap.resolve_queries({a, binary, 5, 1, dst_id, 176})); - EXPECT(kind_overlap.close()); - for (std::uint32_t index : {6u, 7u, 8u}) { - EXPECT(kind_references.begin_query({b, occ, index})); - EXPECT(kind_references.end_query({b, occ, index})); - } - EXPECT(kind_references.resolve_queries({b, occ, 6, 3, dst_id, 184})); - EXPECT(kind_references.close()); - // The two statistics lists are recorded and closed only where the device has the feature, and execute() - // refuses a list that is not closed (list_open): MoltenVK has no pipelineStatisticsQuery. - std::vector overlap_lists; - if (d.pipeline_statistics_query) overlap_lists = {&crossing_stats, &stats_references}; - overlap_lists.insert(overlap_lists.end(), {&kind_overlap, &kind_references}); - EXPECT(queue.execute(overlap_lists) == ReplayResult::success); - EXPECT(!schedule.overflow && schedule.next == schedule.extents.size()); - EXPECT(gate.signal(1)); - EXPECT(queue.idle()); - - std::map expected = { - {8, 80}, {24, 80}, {32, 20}, {40, 84}, {48, 16}, {56, 0}, {64, 1}, {72, 80}, {80, 1}, - {88, 2 * bursts + 1}, {96, 1}, {112, 4}, {120, 0}, {128, 4}, - }; - if (fixture.statistics) expected[0] = 2 * bursts + 1; // the sum resolved inside the statistics query - { // D3D-252: the ordinary result covers three segments (draws 19, 21 and 23); the binary result is the - // shared segment's count normalized to 1. The reference queries carry the same draws unsplit, and their - // own results at 184, 192 and 200 are the expectation for the sums. - const auto word_at = [&](VkDeviceSize at) { - std::uint64_t value = 0; - std::memcpy(&value, static_cast(mapping) + binding_offset + at, sizeof(value)); - return value; - }; - const std::uint64_t first = word_at(184), shared = word_at(192), last = word_at(200); - expected[168] = first + shared + last; - expected[176] = 1; - expected[184] = first; - expected[192] = shared; - expected[200] = last; - } - for (VkDeviceSize offset = 0; offset < size; offset += 8) { - const auto it = expected.find(offset - binding_offset); - const auto want = it == expected.end() ? 0xcdcdcdcdcdcdcdcdULL : it->second; - std::uint64_t actual = 0; - std::memcpy(&actual, static_cast(mapping) + offset, sizeof(actual)); - if (actual != want) { - std::fprintf(stderr, "at byte %llu: got %llu, wanted %llu\n", static_cast(offset), - static_cast(actual), static_cast(want)); - return 1; - } - } - if (fixture.statistics) { - // Slots: 0 the split query, 1 and 2 the references, 3 the second split query, 4 query 0 summed inside it. - const auto word = [&](VkDeviceSize slot, std::uint32_t counter) { - std::uint64_t value = 0; - std::memcpy(&value, static_cast(stats_mapping) + slot * stats_result + counter * 8, 8); - return value; - }; - constexpr std::uint32_t cs_invocations = 10; - for (std::uint32_t counter = 0; counter < statistics_words; ++counter) { - const std::uint64_t want = word(1, counter) + word(2, counter); - for (VkDeviceSize slot : {0, 3, 4}) { - if (word(slot, counter) != want) { - std::fprintf(stderr, "statistics slot %llu counter %u: got %llu, wanted %llu\n", - static_cast(slot), counter, - static_cast(word(slot, counter)), - static_cast(want)); - return 1; - } - } - } - EXPECT(word(0, cs_invocations) == 0 && word(1, 0) != 0 && word(2, 0) != 0); - // D3D-252: the crossing statistics queries (slots 5 and 6) each cover one private interval plus the shared - // intersection; slots 7 to 9 are the references with the same draws unsplit. - for (std::uint32_t counter = 0; counter < statistics_words; ++counter) { - if (word(5, counter) != word(7, counter) + word(8, counter) || - word(6, counter) != word(8, counter) + word(9, counter)) { - std::fprintf(stderr, "crossing statistics counter %u: got %llu/%llu, wanted %llu/%llu\n", counter, - static_cast(word(5, counter)), - static_cast(word(6, counter)), - static_cast(word(7, counter) + word(8, counter)), - static_cast(word(8, counter) + word(9, counter))); - return 1; - } - } - EXPECT(word(5, cs_invocations) == 0 && word(6, cs_invocations) == 0); - std::printf("statistics split around a sum: IA vertices %llu, PS invocations %llu, CS invocations 0, " - "equal to two unsplit queries\n", - static_cast(word(0, 0)), static_cast(word(0, 7))); - std::printf("crossing statistics: IA vertices %llu/%llu, CS invocations 0, equal to the unsplit references\n", - static_cast(word(5, 0)), static_cast(word(6, 0))); - } - std::printf("crossing 80/20; nested 84/16; %u segments summed; alternating binary results 1/1; " - "resolve inside an active query 4; offsets and gated overwrites exact\n", - 2 * bursts + 1); - EXPECT(copy_control.check()); - return 0; -} - -} // namespace - -// vk_overlapping_occlusion_test [--no-statistics] -// [--bisect [--gated] [--no-draw] [--no-resolve] [phase...]] -// --no-statistics runs the test as a device without pipelineStatisticsQuery does (MoltenVK): no statistics pool, -// no statistics lists. It makes that path testable on a device that has the feature. -int main(int argc, char** argv) { - EXPECT(argc >= 3); - Bisect bisect; - bool no_statistics = false; - for (int i = 3; i < argc; ++i) { - if (std::strcmp(argv[i], "--no-statistics") == 0) no_statistics = true; - else if (std::strcmp(argv[i], "--bisect") == 0) bisect.enabled = true; - else if (std::strcmp(argv[i], "--gated") == 0) bisect.gated = true; - else if (std::strcmp(argv[i], "--no-draw") == 0) bisect.no_draw = true; - else if (std::strcmp(argv[i], "--no-resolve") == 0) bisect.no_resolve = true; - else bisect.phases.emplace_back(argv[i]); - } - EXPECT(argc == 3 + (no_statistics ? 1 : 0) || bisect.enabled); - vktest::Device device; - const auto status = device.initialize(); - if (status == vktest::DeviceStatus::unavailable) return 77; - EXPECT(status == vktest::DeviceStatus::ready); - if (no_statistics) device.pipeline_statistics_query = false; - std::printf("pipeline statistics: %s\n", device.pipeline_statistics_query ? "checked" : "not checked"); - const int result = run(device, argv[1], argv[2], bisect); - EXPECT(device.validation_errors() == 0); - return result; -} diff --git a/runtime/test/vk_pc_tail.h b/runtime/test/vk_pc_tail.h deleted file mode 100644 index 18cf97aab..000000000 --- a/runtime/test/vk_pc_tail.h +++ /dev/null @@ -1,142 +0,0 @@ -// --pc-tail-ubo for the test programs: shaders translated with `rdna2spirv.py --pc-tail-ubo` keep s0..s31 (128 bytes) -// in push constants and read the tail (heap base, code base; the --mesh-compute output address) from a uniform block -// at set 1, binding 0 (docs/design.md, "Push-constant tail as a uniform block"). LEONIDA_PC_TAIL_UBO=1 says the -// shaders were translated that way (build.py and run_gpu_tests.py pass the flag then). A test program then declares -// 128 push-constant bytes and, when the module declares set 1, binds a PcTail: a host-visible buffer of one slot per -// dispatch or draw, bound as a dynamic uniform buffer so each one can select its own tail. -#pragma once - -#include - -#include -#include -#include -#include -#include -#include -#include - -namespace leonida::vk_test { - -inline constexpr std::uint32_t pc_tail_set = 1; -inline constexpr std::uint32_t pc_tail_binding = 0; - -// LEONIDA_PC_TAIL_UBO=1: the shaders were translated with --pc-tail-ubo. The values run_gpu_tests.py accepts: -// 1/true/yes/on, any case, with the trailing space cmd.exe's `set VAR=1 &` leaves. -inline bool pc_tail_requested() { - const char* v = std::getenv("LEONIDA_PC_TAIL_UBO"); - std::string s = v ? v : ""; - while (!s.empty() && std::isspace(static_cast(s.back()))) s.pop_back(); - while (!s.empty() && std::isspace(static_cast(s.front()))) s.erase(s.begin()); - for (char& c : s) c = char(std::tolower(static_cast(c))); - return s == "1" || s == "true" || s == "yes" || s == "on"; -} - -// OpDecorate (71) DescriptorSet (34) : a --pc-tail-ubo module declares set 1 only when it reads the tail. -inline bool spirv_declares_set(const void* data, std::size_t bytes, std::uint32_t set) { - if (bytes < 20 || bytes % 4) return false; - std::vector words(bytes / 4); - std::memcpy(words.data(), data, bytes); - for (std::size_t i = 5; i < words.size() && (words[i] >> 16);) { - const std::uint32_t op = words[i] & 0xffff, count = words[i] >> 16; - if (op == 71 && count == 4 && i + 3 < words.size() && words[i + 2] == 34 && words[i + 3] == set) return true; - i += count; - } - return false; -} - -// The tail block, `slots` slots of up to 6 dwords each (the 24-byte --mesh-compute tail), each at a multiple of the -// device's minUniformBufferOffsetAlignment. create() returns false (and leaves what it made to the device's -// destruction, as the test programs do) if any call fails. set_layout goes at index pc_tail_set of the pipeline -// layout; a program with no set 0 of its own puts empty_layout at index 0. A program that destroys its objects -// before vkDestroyDevice (so the validation layer can count leaks) calls destroy(). -struct PcTail { - static constexpr VkDeviceSize slot_bytes = 6 * sizeof(std::uint32_t); - VkDescriptorSetLayout set_layout = VK_NULL_HANDLE; - VkDescriptorSetLayout empty_layout = VK_NULL_HANDLE; - VkDescriptorPool pool = VK_NULL_HANDLE; - VkDescriptorSet set = VK_NULL_HANDLE; - VkBuffer buffer = VK_NULL_HANDLE; - VkDeviceMemory mem = VK_NULL_HANDLE; - VkDeviceSize stride = 0; - std::uint32_t slots = 0; - std::uint8_t* map = nullptr; - - bool create(PFN_vkGetDeviceProcAddr gdpa, VkDevice dev, const VkPhysicalDeviceMemoryProperties& memory, - VkDeviceSize min_offset_alignment, VkShaderStageFlags stages, std::uint32_t slot_count) { -#define PC_TAIL_LOAD(f) auto f = reinterpret_cast(gdpa(dev, #f)); if (!f) return false - PC_TAIL_LOAD(vkCreateDescriptorSetLayout); PC_TAIL_LOAD(vkCreateDescriptorPool); - PC_TAIL_LOAD(vkAllocateDescriptorSets); PC_TAIL_LOAD(vkUpdateDescriptorSets); PC_TAIL_LOAD(vkCreateBuffer); - PC_TAIL_LOAD(vkGetBufferMemoryRequirements); PC_TAIL_LOAD(vkAllocateMemory); PC_TAIL_LOAD(vkBindBufferMemory); - PC_TAIL_LOAD(vkMapMemory); -#undef PC_TAIL_LOAD - const VkDeviceSize align = min_offset_alignment ? min_offset_alignment : 1; - stride = (slot_bytes + align - 1) / align * align; - slots = slot_count ? slot_count : 1; - - VkDescriptorSetLayoutBinding b{pc_tail_binding, VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC, 1, stages, nullptr}; - VkDescriptorSetLayoutCreateInfo li{VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO}; - li.bindingCount = 1; li.pBindings = &b; - if (vkCreateDescriptorSetLayout(dev, &li, nullptr, &set_layout) != VK_SUCCESS) return false; - VkDescriptorSetLayoutCreateInfo ei{VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO}; - if (vkCreateDescriptorSetLayout(dev, &ei, nullptr, &empty_layout) != VK_SUCCESS) return false; - VkDescriptorPoolSize ps{VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC, 1}; - VkDescriptorPoolCreateInfo pi{VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO}; - pi.maxSets = 1; pi.poolSizeCount = 1; pi.pPoolSizes = &ps; - if (vkCreateDescriptorPool(dev, &pi, nullptr, &pool) != VK_SUCCESS) return false; - VkDescriptorSetAllocateInfo ai{VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO}; - ai.descriptorPool = pool; ai.descriptorSetCount = 1; ai.pSetLayouts = &set_layout; - if (vkAllocateDescriptorSets(dev, &ai, &set) != VK_SUCCESS) return false; - - VkBufferCreateInfo bi{VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO}; - bi.size = stride * slots; bi.usage = VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT; - if (vkCreateBuffer(dev, &bi, nullptr, &buffer) != VK_SUCCESS) return false; - VkMemoryRequirements mr; vkGetBufferMemoryRequirements(dev, buffer, &mr); - constexpr VkMemoryPropertyFlags host = VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT; - std::uint32_t type = 0; - while (type < memory.memoryTypeCount && - !((mr.memoryTypeBits >> type & 1) && (memory.memoryTypes[type].propertyFlags & host) == host)) ++type; - if (type == memory.memoryTypeCount) return false; - VkMemoryAllocateInfo mi{VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO}; - mi.allocationSize = mr.size; mi.memoryTypeIndex = type; - if (vkAllocateMemory(dev, &mi, nullptr, &mem) != VK_SUCCESS) return false; - if (vkBindBufferMemory(dev, buffer, mem, 0) != VK_SUCCESS) return false; - void* p; - if (vkMapMemory(dev, mem, 0, VK_WHOLE_SIZE, 0, &p) != VK_SUCCESS) return false; - map = static_cast(p); - std::memset(map, 0, std::size_t(stride * slots)); - - VkDescriptorBufferInfo di{buffer, 0, slot_bytes}; - VkWriteDescriptorSet w{VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET}; - w.dstSet = set; w.dstBinding = pc_tail_binding; w.descriptorCount = 1; - w.descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC; w.pBufferInfo = &di; - vkUpdateDescriptorSets(dev, 1, &w, 0, nullptr); - return true; - } - - // The tail of slot `slot` from a push-constant array laid out as without the flag: words 32.. of `pc`, `words` - // of them (4, or 6 with --mesh-compute). - void write(std::uint32_t slot, const std::uint32_t* pc, std::uint32_t words) { - std::memcpy(map + stride * slot, pc + 32, words * sizeof(std::uint32_t)); - } - - std::uint32_t offset(std::uint32_t slot) const { return std::uint32_t(stride * slot); } - - // Destroys what create() made (the set goes with its pool; freeing the memory unmaps it). Null handles are - // skipped, so it is safe after a failed or skipped create(). - void destroy(PFN_vkGetDeviceProcAddr gdpa, VkDevice dev) { - const auto destroy_pool = reinterpret_cast(gdpa(dev, "vkDestroyDescriptorPool")); - const auto destroy_layout = - reinterpret_cast(gdpa(dev, "vkDestroyDescriptorSetLayout")); - const auto destroy_buffer = reinterpret_cast(gdpa(dev, "vkDestroyBuffer")); - const auto free_memory = reinterpret_cast(gdpa(dev, "vkFreeMemory")); - if (pool && destroy_pool) destroy_pool(dev, pool, nullptr); - if (buffer && destroy_buffer) destroy_buffer(dev, buffer, nullptr); - if (mem && free_memory) free_memory(dev, mem, nullptr); - for (const auto layout : {set_layout, empty_layout}) - if (layout && destroy_layout) destroy_layout(dev, layout, nullptr); - *this = PcTail{}; - } -}; - -} // namespace leonida::vk_test diff --git a/runtime/test/vk_pipeline_check.cpp b/runtime/test/vk_pipeline_check.cpp deleted file mode 100644 index 7b4f8d533..000000000 --- a/runtime/test/vk_pipeline_check.cpp +++ /dev/null @@ -1,2000 +0,0 @@ -// Driver-level check of the translated corpus: vk_pipeline_check [pipeline_cache.bin] -// Reads /index.json (written by tools/rdna2spirv.py) and checks module and pipeline creation for compatible -// entries with the translator's resource contract (set 0: sampled images 0, 3, 5, 6; samplers 1; descriptor hash -// table 2; storage images 4, 7 and 8..19; set 1 binding 0 dynamic UBO for --pc-tail-ubo shaders; push constants -// sized from push_constant_bytes, default 144 or 128 with pc_tail): -// - cs: compute pipeline via vkCreateComputePipelines, using the runtime layout and subgroup request for -// descriptor-free shaders with the standard push-constant range -// - ps/vs/ms/gs: graphics pipeline via vkCreateGraphicsPipelines (Vulkan 1.3 dynamic rendering, no render pass) -// paired with minimal partner stubs from /stubs/ (generated by tools/spirv_stubs.py) -// Only optional device extensions needed by the selected shaders (and supported by the GPU) are enabled. Shaders -// whose required features or partner stubs are unavailable are reported as skipped rather than failed. -// [cache.bin] loaded first if it exists (a stopped run resumes: cached pipelines are instant), saved every -// 10 minutes and at the end -// --jobs N compile on up to N worker threads (default: half the hardware threads) -// --large-module-bytes N modules larger than N bytes are "large" (default: 4194304; 0 disables the gate) -// --large-parallel N how many large modules may be in the driver at once: 0 (default) = as many as fit 3/4 of -// the memory available at start, at large_module_gate.h's estimate per module, up to --jobs, with the -// small ones compiling alongside; 1 = each large module alone, the other threads waiting (the -// behaviour before; also what 0 falls back to when the available memory can't be read) -// --start I --count N check only index entries [I, I+N) (sorted by name) -// --slow SEC print pipelines slower than SEC (default 30); compiles past 60 s are named while running -// --max-bytes N skip modules whose .spv is larger than N bytes (0 = no limit; names every skip) -// --stage S which stages to check: all (default), cs, or graphics (aliases: --compute-only, --graphics-only) -// --stats FILE write the driver's statistics for each translated shader (VK_KHR_pipeline_executable_properties: -// instructions, registers, spills, scratch, waves...) as CSV rows name,stage,statistic,value. Only -// the executable that runs the translated shader is written, not the partner stub's. Use without -// cache.bin: a pipeline loaded from the cache may come without statistics. -// --cache-feedback count each stage's successful pipelines by VkPipelineCreationFeedback: hits (VALID and -// APPLICATION_PIPELINE_CACHE_HIT), no hit reported (VALID only) and unavailable (no VALID bit, or a -// pre-1.3 device without VK_EXT_pipeline_creation_feedback). The three add up to the ok count. -// --isolate check in child processes, --isolate-batch modules at a time (default 256), so a module -// that kills the driver is recorded as failed ("MODULE CRASH") and the pass -// goes on. A crashed batch is bisected to the module. Children run one after the other and share -// cache.bin. Not compatible with --stats. -// --inflight-file F keep the modules that are in the driver in F, one "namephase" line each (phase: module -// while vkCreateShaderModule runs, pipeline while its pipeline is created), so whoever ran the check -// can tell which module was there when the process died. F is rewritten when a module over -// --large-module-bytes enters or leaves the driver (with --large-parallel 1 it is alone then, so F -// names exactly it; otherwise F names every module in flight and make_game.py retries each alone) -// and by the 5 s watchdog for the others, and emptied at the end. make_game.py's pipelines stage -// reads it. With --isolate, the active child writes the snapshot. -// --skip-file F modules named in F (one per line) are not compiled: each is reported as MODULE CRASH and counted -// as a failed pipeline, as --isolate does for a module that killed the driver. make_game.py writes F -// after a crash, so the next run checks everything else instead of dying on the same module. -// test hook VK_PIPELINE_CHECK_SIMULATE_CRASH=[:SIGNAL] simulates a process crash -// just before the pipeline of a matching module is created. For testing --isolate and the -// pipelines stage's retry. -#include "vulkan_loader.h" -#include "vk_device_pick.h" -#include "pipeline_cache_file.h" -#include "pipeline_cache_snapshot.h" -#include "large_module_gate.h" -#include "pipeline_summary.h" -#include "../src/spirv_words.h" -#include "../src/subgroup_size.h" - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#ifndef _WIN32 -#include -#include -#include -#endif - -static PFN_vkGetInstanceProcAddr gipa; - -struct VertexInputMeta { - uint32_t location = 0; - std::string type = "float"; -}; - -struct ShaderMeta { - std::string stage; - uint32_t subgroup_size = 0; - uint32_t lds_bytes = 0; - uint32_t push_constant_bytes = 0; // 0 = absent in index (128 with pc_tail, else 144) - uint32_t pc_tail_bytes = 0; // >0 = --pc-tail-ubo uniform block at set 1, binding 0 - bool no_set0_bindings = false; - bool wave64 = false; - std::array local_size{1, 1, 1}; - std::string wave64_exchange; - bool writes_depth = false; - bool needs_maintenance8 = false; - std::vector features; - std::vector float_controls; // VkPhysicalDeviceFloatControlsProperties members that must be true - std::vector inputs; - std::vector outputs; - std::vector params; - std::vector gs_inputs; - std::vector gs_outputs; - std::vector gs_input_locations; - std::vector gs_output_locations; - bool has_gs_input_locations = false; - bool has_gs_output_locations = false; - std::vector vertex_inputs; -}; - -// Minimal recursive-descent JSON reader for index.json (handles strings, numbers, bools, arrays, objects). -namespace { - -struct JsonParser { - const std::string& s; - size_t i = 0; - bool error = false; - std::string error_msg; - - void fail(const char* ctx) { - if (!error) { - error = true; - error_msg = std::string(ctx) + " at byte " + std::to_string(i); - } - } - void ws() { - while (i < s.size() && std::isspace(static_cast(s[i]))) i++; - } - bool consume(char c) { - ws(); - if (i < s.size() && s[i] == c) { i++; return true; } - return false; - } - std::string parse_string() { - ws(); - if (i >= s.size() || s[i] != '"') { fail("expected string"); return {}; } - i++; - std::string out; - while (i < s.size() && s[i] != '"') { - if (s[i] == '\\' && i + 1 < s.size()) { - i++; - out.push_back(s[i++]); - } else { - out.push_back(s[i++]); - } - } - if (i >= s.size() || s[i] != '"') { fail("unterminated string"); return out; } - i++; - return out; - } - uint32_t parse_u32() { - ws(); - const size_t start = i; - bool neg = false; - if (i < s.size() && s[i] == '-') { neg = true; i++; } - uint32_t v = 0; - const size_t digits_start = i; - while (i < s.size() && s[i] >= '0' && s[i] <= '9') { - v = v * 10 + uint32_t(s[i] - '0'); - i++; - } - if (i == digits_start) { i = start; fail("expected unsigned integer"); return 0u; } - while (i < s.size() && (s[i] == '.' || s[i] == 'e' || s[i] == 'E' || s[i] == '+' || s[i] == '-' || - (s[i] >= '0' && s[i] <= '9'))) i++; - return neg ? 0u : v; - } - bool parse_bool() { - ws(); - if (s.compare(i, 4, "true") == 0) { i += 4; return true; } - if (s.compare(i, 5, "false") == 0) { i += 5; return false; } - fail("expected boolean"); - return false; - } - void skip_value() { - ws(); - if (i >= s.size()) { fail("unexpected end of JSON"); return; } - char c = s[i]; - if (c == '"') { parse_string(); return; } - if (c == '{') { - i++; - while (!error && i < s.size()) { - if (consume('}')) return; - const size_t before = i; - parse_string(); - if (error) return; - if (!consume(':')) { fail("expected ':' in object"); return; } - skip_value(); - if (error) return; - if (consume('}')) return; - if (!consume(',') || i == before) { fail("expected ',' or '}' in object"); return; } - } - if (!error) fail("unterminated object"); - return; - } - if (c == '[') { - i++; - while (!error && i < s.size()) { - if (consume(']')) return; - const size_t before = i; - skip_value(); - if (error) return; - if (consume(']')) return; - if (!consume(',') || i == before) { fail("expected ',' or ']' in array"); return; } - } - if (!error) fail("unterminated array"); - return; - } - const size_t before = i; - while (i < s.size() && s[i] != ',' && s[i] != '}' && s[i] != ']' && - !std::isspace(static_cast(s[i]))) i++; - if (i == before) fail("unexpected token in value"); - } - std::vector parse_u32_array() { - std::vector out; - if (!consume('[')) { skip_value(); return out; } - while (!error && i < s.size()) { - if (consume(']')) return out; - const size_t before = i; - out.push_back(parse_u32()); - if (error) return out; - if (consume(']')) return out; - if (!consume(',') || i == before) { fail("expected ',' or ']' in u32 array"); return out; } - } - if (!error) fail("unterminated u32 array"); - return out; - } - void parse_local_size(std::array& out) { - if (!consume('[')) { skip_value(); return; } - for (size_t dim = 0; !error && i < s.size(); ++dim) { - if (consume(']')) return; - const char* start = s.data() + i; - skip_value(); - if (dim < out.size()) { - char* end = nullptr; - const double size = std::strtod(start, &end); - out[dim] = end == s.data() + i && size >= 0 && size <= UINT32_MAX ? uint32_t(size) : 0; - } - if (consume(']')) return; - if (!consume(',')) { fail("expected ',' or ']' in local size"); return; } - } - if (!error) fail("unterminated local size"); - } - std::vector parse_str_array() { - std::vector out; - if (!consume('[')) { skip_value(); return out; } - while (!error && i < s.size()) { - if (consume(']')) return out; - const size_t before = i; - out.push_back(parse_string()); - if (error) return out; - if (consume(']')) return out; - if (!consume(',') || i == before) { fail("expected ',' or ']' in string array"); return out; } - } - if (!error) fail("unterminated string array"); - return out; - } - std::vector parse_vertex_inputs() { - std::vector out; - if (!consume('[')) { skip_value(); return out; } - while (!error && i < s.size()) { - if (consume(']')) return out; - const size_t before = i; - VertexInputMeta vi; - if (consume('{')) { - while (!error && i < s.size()) { - if (consume('}')) break; - const size_t obj_before = i; - std::string k = parse_string(); - if (error) return out; - if (!consume(':')) { fail("expected ':' in vertex_inputs entry"); return out; } - if (k == "location") vi.location = parse_u32(); - else if (k == "type") vi.type = parse_string(); - else skip_value(); - if (error) return out; - if (consume('}')) break; - if (!consume(',') || i == obj_before) { fail("expected ',' or '}' in vertex_inputs entry"); return out; } - } - if (error) return out; - out.push_back(std::move(vi)); - } else { - skip_value(); - if (error) return out; - } - if (consume(']')) return out; - if (!consume(',') || i == before) { fail("expected ',' or ']' in vertex_inputs"); return out; } - } - if (!error) fail("unterminated vertex_inputs array"); - return out; - } - uint32_t parse_strict_u32(const char* what) { - ws(); - uint32_t v = 0; - const auto [end, ec] = std::from_chars(s.data() + i, s.data() + s.size(), v); - if (ec != std::errc{}) { fail(what); return 0u; } - i = static_cast(end - s.data()); - if (i < s.size() && (s[i] == '.' || s[i] == 'e' || s[i] == 'E')) { fail(what); return 0u; } - return v; - } - uint32_t parse_pc_tail_bytes() { - ws(); - if (s.compare(i, 4, "null") == 0) { i += 4; return 0u; } - if (!consume('{')) { fail("expected object for pc_tail"); return 0u; } - uint32_t bytes = 0; - while (!error && i < s.size()) { - if (consume('}')) return bytes; - const size_t before = i; - std::string k = parse_string(); - if (error) return bytes; - if (!consume(':')) { fail("expected ':' in pc_tail"); return bytes; } - if (k == "bytes") bytes = parse_strict_u32("expected unsigned 32-bit pc_tail.bytes"); - else skip_value(); - if (error) return bytes; - if (consume('}')) return bytes; - if (!consume(',') || i == before) { fail("expected ',' or '}' in pc_tail"); return bytes; } - } - if (!error) fail("unterminated pc_tail object"); - return bytes; - } - ShaderMeta parse_meta() { - ShaderMeta m; - if (!consume('{')) { skip_value(); return m; } - while (!error && i < s.size()) { - if (consume('}')) return m; - const size_t before = i; - std::string k = parse_string(); - if (error) return m; - if (!consume(':')) { fail("expected ':' in shader metadata"); return m; } - if (k == "stage") m.stage = parse_string(); - else if (k == "subgroup_size") { - // null: translated with --wave64-emulate, exact on any subgroup size, so request none (0) - ws(); - if (s.compare(i, 4, "null") == 0) { i += 4; m.subgroup_size = 0; } - else m.subgroup_size = parse_u32(); - } - else if (k == "lds_bytes") m.lds_bytes = parse_strict_u32("expected unsigned 32-bit lds_bytes"); - else if (k == "push_constant_bytes") - m.push_constant_bytes = parse_strict_u32("expected unsigned 32-bit push_constant_bytes"); - else if (k == "pc_tail") m.pc_tail_bytes = parse_pc_tail_bytes(); - else if (k == "bindings") { - const size_t start = i; - m.no_set0_bindings = consume('[') && consume(']'); - if (!m.no_set0_bindings) { - i = start; - skip_value(); - } - } - else if (k == "wave64") { - ws(); - if (s.compare(i, 4, "true") == 0 || s.compare(i, 5, "false") == 0) m.wave64 = parse_bool(); - else skip_value(); - } - else if (k == "wave64_exchange") { - ws(); - if (i < s.size() && s[i] == '"') m.wave64_exchange = parse_string(); - else skip_value(); - } - else if (k == "local_size") parse_local_size(m.local_size); - else if (k == "writes_depth") m.writes_depth = parse_bool(); - else if (k == "needs_maintenance8") m.needs_maintenance8 = parse_bool(); - else if (k == "features") m.features = parse_str_array(); - else if (k == "float_controls") m.float_controls = parse_str_array(); - else if (k == "inputs") m.inputs = parse_u32_array(); - else if (k == "outputs") m.outputs = parse_u32_array(); - else if (k == "params") m.params = parse_u32_array(); - else if (k == "gs_inputs") m.gs_inputs = parse_u32_array(); - else if (k == "gs_outputs") m.gs_outputs = parse_u32_array(); - else if (k == "gs_input_locations") { m.gs_input_locations = parse_u32_array(); m.has_gs_input_locations = true; } - else if (k == "gs_output_locations") { m.gs_output_locations = parse_u32_array(); m.has_gs_output_locations = true; } - else if (k == "vertex_inputs") m.vertex_inputs = parse_vertex_inputs(); - else skip_value(); - if (error) return m; - if (consume('}')) return m; - if (!consume(',') || i == before) { fail("expected ',' or '}' in shader metadata"); return m; } - } - if (!error) fail("unterminated shader metadata object"); - return m; - } -}; - -std::map read_index(const std::string& path, std::string& err, bool& unreadable) { - std::ifstream f(path, std::ios::binary); - std::map out; - unreadable = false; - if (!f) { err = "cannot open the file"; unreadable = true; return out; } // a missing index must not read as an empty corpus - // Read with read() so that a failure shows in the stream state (istreambuf_iterator bypasses it). - f.seekg(0, std::ios::end); - const std::streamoff size = f.tellg(); - f.seekg(0, std::ios::beg); - if (!f || size < 0) { err = "cannot determine the file size"; unreadable = true; return out; } - std::string s(static_cast(size), '\0'); - if (size > 0 && (!f.read(s.data(), size) || f.gcount() != size)) { err = "read error"; unreadable = true; return out; } - constexpr std::string_view utf8_bom = "\xef\xbb\xbf"; - JsonParser p{s, s.starts_with(utf8_bom) ? utf8_bom.size() : 0}; - p.ws(); - if (p.i >= s.size()) { err = "the file is empty (an intentionally empty index is {})"; return out; } - if (!p.consume('{')) { err = "expected '{' at byte " + std::to_string(p.i); return out; } - // After the closing '}' only whitespace may remain ({}garbage is malformed). - auto closed = [&] { - p.ws(); - if (p.i != s.size()) { err = "unexpected data after the top-level object at byte " + std::to_string(p.i); return std::map{}; } - return std::move(out); - }; - while (!p.error && p.i < s.size()) { - if (p.consume('}')) return closed(); - const size_t before = p.i; - std::string name = p.parse_string(); - if (p.error) break; - if (!p.consume(':')) { p.fail("expected ':' after shader name"); break; } - out[name] = p.parse_meta(); - if (p.error) break; - if (p.consume('}')) return closed(); - if (!p.consume(',') || p.i == before) { p.fail("expected ',' or '}' in index.json"); break; } - } - if (p.error) { err = p.error_msg; return {}; } - err = "unterminated top-level object at byte " + std::to_string(p.i); - return {}; -} - -std::string stub_filename(const char* kind, const std::vector& raw_locs) { - std::vector locs = raw_locs; - std::sort(locs.begin(), locs.end()); - locs.erase(std::unique(locs.begin(), locs.end()), locs.end()); - std::string out = std::string(kind) + "_"; - if (locs.empty()) { - out += "empty"; - } else { - for (size_t i = 0; i < locs.size(); i++) { - if (i) out += "_"; - out += std::to_string(locs[i]); - } - } - out += ".spv"; - return out; -} - -bool is_graphics_stage(const std::string& st) { - return st == "ps" || st == "vs" || st == "ms" || st == "gs"; -} - -std::string upper_stage(const std::string& st) { - std::string u = st; - for (char& c : u) c = static_cast(std::toupper(static_cast(c))); - return u; -} - -VkShaderStageFlagBits stage_bit(const std::string& st) { - if (st == "cs") return VK_SHADER_STAGE_COMPUTE_BIT; - if (st == "ps") return VK_SHADER_STAGE_FRAGMENT_BIT; - if (st == "vs") return VK_SHADER_STAGE_VERTEX_BIT; - if (st == "ms") return VK_SHADER_STAGE_MESH_BIT_EXT; - if (st == "gs") return VK_SHADER_STAGE_GEOMETRY_BIT; - return VkShaderStageFlagBits(0); -} - -struct StageStats { - uint32_t pipes_ok = 0; - uint32_t pipes_bad = 0; - uint32_t pipes_skipped = 0; - uint32_t crash_skipped = 0; // --skip-file: counted in pipes_bad, not compiled - uint32_t w32_ok = 0; - uint32_t w32_bad = 0; - uint32_t w32_unforced = 0; - uint32_t w64_ok = 0; - uint32_t w64_bad = 0; - uint32_t w64_unforced = 0; - uint32_t feedback[3] = {}; // --cache-feedback, successful pipelines only, indexed by feedback_outcome - double seconds = 0.0; - double max_sec = 0.0; - std::string max_name; - std::map skip_reasons; -}; - -constexpr std::pair shader_slice(size_t size, size_t start, size_t count) { - const size_t lo = std::min(start, size); - const size_t remaining = size - lo; - const size_t hi = count ? lo + std::min(count, remaining) : size; - return {lo, hi}; -} - -static_assert(shader_slice(7, 2, 3) == std::pair{2, 5}); -static_assert(shader_slice(7, 2, 0) == std::pair{2, 7}); -static_assert(shader_slice(7, 8, 3) == std::pair{7, 7}); -static_assert(shader_slice(7, 2, std::numeric_limits::max()) == std::pair{2, 7}); - -// Push-constant range size a shader needs: its index push_constant_bytes when recorded (128 with --pc-tail-ubo, -// 144 by default, 152 with --mesh-compute), or 128 when pc_tail is present, else 144. Rounded up to 4 bytes -// (Vulkan requires VkPushConstantRange::size to be a positive multiple of 4). -constexpr uint32_t required_push_bytes(uint32_t push_constant_bytes, uint32_t pc_tail_bytes) { - const uint32_t raw = push_constant_bytes ? push_constant_bytes : (pc_tail_bytes ? 128u : 144u); - return raw > (std::numeric_limits::max() - 3u) ? raw : ((raw + 3u) & ~3u); -} - -constexpr uint32_t runtime_compute_push_bytes = 144; // sizeof(leonida::ShaderUserData) - -bool uses_runtime_compute_layout(const ShaderMeta& meta) { - return meta.stage == "cs" && meta.no_set0_bindings && !meta.pc_tail_bytes && - required_push_bytes(meta.push_constant_bytes, meta.pc_tail_bytes) == runtime_compute_push_bytes; -} - -static_assert(required_push_bytes(0, 0) == 144); -static_assert(required_push_bytes(0, 16) == 128); -static_assert(required_push_bytes(128, 0) == 128); -static_assert(required_push_bytes(128, 16) == 128); -static_assert(required_push_bytes(144, 0) == 144); -static_assert(required_push_bytes(152, 0) == 152); - -// --cache-feedback class of a successful pipeline: 0 hit, 1 no hit reported, 2 unavailable. A hit counts only with -// VALID; the duration and base-pipeline bits are not classified. -constexpr int feedback_outcome(VkPipelineCreationFeedbackFlags f) { - if (!(f & VK_PIPELINE_CREATION_FEEDBACK_VALID_BIT)) return 2; - return (f & VK_PIPELINE_CREATION_FEEDBACK_APPLICATION_PIPELINE_CACHE_HIT_BIT) ? 0 : 1; -} - -static_assert(feedback_outcome(0) == 2); -static_assert(feedback_outcome(VK_PIPELINE_CREATION_FEEDBACK_APPLICATION_PIPELINE_CACHE_HIT_BIT) == 2); -static_assert(feedback_outcome(VK_PIPELINE_CREATION_FEEDBACK_VALID_BIT) == 1); -static_assert(feedback_outcome(VK_PIPELINE_CREATION_FEEDBACK_VALID_BIT | - VK_PIPELINE_CREATION_FEEDBACK_APPLICATION_PIPELINE_CACHE_HIT_BIT) == 0); - -// Test hook (see the header): VK_PIPELINE_CHECK_SIMULATE_CRASH=[:SIGNAL]. -struct SimulatedCrash { - bool enabled = false; - std::string pattern; - int sig = SIGFPE; -}; - -int signal_from_name(std::string n) { - for (char& c : n) c = static_cast(std::toupper(static_cast(c))); - if (n.rfind("SIG", 0) == 0) n = n.substr(3); - if (n == "FPE") return SIGFPE; - if (n == "SEGV") return SIGSEGV; - if (n == "ABRT") return SIGABRT; - if (n == "ILL") return SIGILL; - if (n == "TERM") return SIGTERM; -#ifndef _WIN32 - if (n == "BUS") return SIGBUS; - if (n == "KILL") return SIGKILL; -#endif - return 0; -} - -SimulatedCrash read_simulated_crash() { - SimulatedCrash c; - const char* env = std::getenv("VK_PIPELINE_CHECK_SIMULATE_CRASH"); - if (!env || !*env) return c; - std::string v = env; - const size_t colon = v.rfind(':'); - if (colon != std::string::npos) { - if (const int sig = signal_from_name(v.substr(colon + 1))) { - c.sig = sig; - v.resize(colon); - } - } - c.enabled = true; - c.pattern = v; - return c; -} - -#ifndef _WIN32 -std::string signal_label(int sig) { - switch (sig) { - case SIGFPE: return "SIGFPE"; - case SIGSEGV: return "SIGSEGV"; - case SIGABRT: return "SIGABRT"; - case SIGILL: return "SIGILL"; - case SIGBUS: return "SIGBUS"; - case SIGKILL: return "SIGKILL"; - case SIGTERM: return "SIGTERM"; - default: return "signal " + std::to_string(sig); - } -} -#endif - -// --isolate: one child run of this executable over [start, start + count) of the stage-filtered list. -struct ChildRun { - bool ready = false; // reached the work loop (ISO-READY): Vulkan and the cache were set up - bool done = false; // finished the pass and saved the cache (ISO-DONE) - bool cache_ok = true; - int sig = 0; // killed by this signal - uint32_t status = 0; // exit status when it exited (a full DWORD on Windows) - std::string runner_error; - std::string out; // its stdout -}; - -std::string child_exit_status(uint32_t status) { -#ifdef _WIN32 - if (status >= 0x80000000u) { - char hex[11]; - std::snprintf(hex, sizeof hex, "0x%08x", static_cast(status)); - return hex; - } -#endif - return std::to_string(status); -} - -std::filesystem::path self_executable(const char* argv0) { -#ifdef _WIN32 - (void)argv0; - std::wstring path(32768, L'\0'); - const DWORD len = GetModuleFileNameW(nullptr, path.data(), static_cast(path.size())); - if (!len || len == path.size()) return {}; - path.resize(len); - return path; -#else - std::error_code ec; - auto self = std::filesystem::read_symlink("/proc/self/exe", ec); - return ec ? std::filesystem::path(argv0) : self; -#endif -} - -#ifdef _WIN32 -// Quote one argument for the Windows CRT, including backslashes before quotes and at the end. -std::wstring quote_child_arg(std::wstring_view arg) { - std::wstring quoted = L"\""; - size_t slashes = 0; - for (wchar_t c : arg) { - if (c == L'\\') { - ++slashes; - } else { - if (c == L'\"') quoted.append(slashes + 1, L'\\'); - slashes = 0; - } - quoted += c; - } - return quoted.append(slashes, L'\\') + L"\""; -} - -void collect_child(const std::filesystem::path& exe, std::vector& args, ChildRun& r) { - const auto failed = [&](const char* api) { - const DWORD error = GetLastError(); - r.runner_error = std::string(api) + " failed (Win32 error " + std::to_string(error) + ")"; - }; - std::wstring command = quote_child_arg(exe.native()); - for (const auto& arg : args) { - // The checker uses narrow CRT argv. Round-trip the arguments through its active ANSI code page. - const int len = MultiByteToWideChar(CP_ACP, MB_ERR_INVALID_CHARS, arg.c_str(), -1, nullptr, 0); - if (!len) return failed("MultiByteToWideChar"); - std::wstring wide(len, L'\0'); - if (!MultiByteToWideChar(CP_ACP, MB_ERR_INVALID_CHARS, arg.c_str(), -1, wide.data(), len)) - return failed("MultiByteToWideChar"); - wide.pop_back(); - command += L' '; - command += quote_child_arg(wide); - } - - using Handle = std::unique_ptr; - SECURITY_ATTRIBUTES inherited{sizeof(inherited), nullptr, TRUE}; - HANDLE read_handle = nullptr, write_handle = nullptr; - if (!CreatePipe(&read_handle, &write_handle, &inherited, 0)) return failed("CreatePipe"); - Handle read_end(read_handle, CloseHandle), write_end(write_handle, CloseHandle); - if (!SetHandleInformation(read_end.get(), HANDLE_FLAG_INHERIT, 0)) return failed("SetHandleInformation"); - - // Only stdout is captured. Keep stderr live for driver diagnostics and give the child no interactive input. - const HANDLE nul_handle = CreateFileW(L"NUL", GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, - &inherited, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr); - if (nul_handle == INVALID_HANDLE_VALUE) return failed("CreateFileW(NUL)"); - Handle nul(nul_handle, CloseHandle), stderr_copy(nullptr, CloseHandle); - const HANDLE stderr_handle = GetStdHandle(STD_ERROR_HANDLE); - if (stderr_handle && stderr_handle != INVALID_HANDLE_VALUE) { - HANDLE duplicate = nullptr; - const HANDLE current = GetCurrentProcess(); - if (!DuplicateHandle(current, stderr_handle, current, &duplicate, 0, TRUE, DUPLICATE_SAME_ACCESS)) - return failed("DuplicateHandle(stderr)"); - stderr_copy.reset(duplicate); - } - - STARTUPINFOEXW startup{}; - startup.StartupInfo.cb = sizeof(startup); - startup.StartupInfo.dwFlags = STARTF_USESTDHANDLES; - startup.StartupInfo.hStdInput = nul.get(); - startup.StartupInfo.hStdOutput = write_end.get(); - startup.StartupInfo.hStdError = stderr_copy ? stderr_copy.get() : nul.get(); - // Inherit only the standard handles, even when the caller gave the parent other inheritable handles. - HANDLE child_handles[] = {nul.get(), write_end.get(), stderr_copy.get()}; - SIZE_T attr_bytes = 0; - InitializeProcThreadAttributeList(nullptr, 1, 0, &attr_bytes); - if (!attr_bytes) return failed("InitializeProcThreadAttributeList"); - std::vector attrs(attr_bytes); - startup.lpAttributeList = reinterpret_cast(attrs.data()); - if (!InitializeProcThreadAttributeList(startup.lpAttributeList, 1, 0, &attr_bytes)) - return failed("InitializeProcThreadAttributeList"); - std::fflush(nullptr); - const bool configured = UpdateProcThreadAttribute(startup.lpAttributeList, 0, PROC_THREAD_ATTRIBUTE_HANDLE_LIST, - child_handles, (stderr_copy ? 3 : 2) * sizeof(HANDLE), - nullptr, nullptr); - PROCESS_INFORMATION process{}; - const bool started = configured && CreateProcessW(exe.c_str(), command.data(), nullptr, nullptr, TRUE, - EXTENDED_STARTUPINFO_PRESENT, nullptr, nullptr, - &startup.StartupInfo, &process); - const DWORD start_error = started ? 0 : GetLastError(); - DeleteProcThreadAttributeList(startup.lpAttributeList); - if (!started) { - SetLastError(start_error); - return failed(configured ? "CreateProcessW" : "UpdateProcThreadAttribute"); - } - CloseHandle(process.hThread); - Handle child(process.hProcess, CloseHandle); - write_end.reset(); // EOF must depend on the child closing its write handle. - - char buffer[4096]; - DWORD bytes = 0; - while (ReadFile(read_end.get(), buffer, sizeof buffer, &bytes, nullptr)) { - if (bytes) r.out.append(buffer, bytes); - } - if (GetLastError() != ERROR_BROKEN_PIPE) failed("ReadFile(child stdout)"); - read_end.reset(); - if (WaitForSingleObject(child.get(), INFINITE) != WAIT_OBJECT_0) return failed("WaitForSingleObject"); - DWORD status = 0; - if (!GetExitCodeProcess(child.get(), &status)) return failed("GetExitCodeProcess"); - r.status = status; -} -#else -void collect_child(const std::filesystem::path& exe, std::vector& args, ChildRun& r) { - args.insert(args.begin(), exe.native()); - std::vector argv; - for (auto& a : args) argv.push_back(a.data()); - argv.push_back(nullptr); - int fds[2]; - if (pipe(fds) != 0) { r.status = 127; return; } - std::fflush(nullptr); - const pid_t pid = fork(); - if (pid < 0) { close(fds[0]); close(fds[1]); r.status = 127; return; } - if (pid == 0) { - dup2(fds[1], 1); - close(fds[0]); close(fds[1]); - execv(exe.c_str(), argv.data()); - _exit(127); - } - close(fds[1]); - char buf[4096]; - for (;;) { - const ssize_t n = read(fds[0], buf, sizeof buf); - if (n > 0) r.out.append(buf, size_t(n)); - else if (n < 0 && errno == EINTR) continue; - else break; - } - close(fds[0]); - int st = 0; - while (waitpid(pid, &st, 0) < 0 && errno == EINTR) {} - if (WIFSIGNALED(st)) r.sig = WTERMSIG(st); - else r.status = WIFEXITED(st) ? WEXITSTATUS(st) : 1; -} -#endif - -std::string_view next_child_line(std::string_view& output) { - const size_t end = output.find('\n'); - auto line = output.substr(0, end); - output.remove_prefix(end == std::string_view::npos ? output.size() : end + 1); - if (line.ends_with('\r')) line.remove_suffix(1); - return line; -} - -ChildRun run_child(const std::filesystem::path& exe, const std::string& dir, - const std::vector& pass, const std::string& cache_path, size_t start, size_t count) { - ChildRun r; - std::vector args = {dir}; - if (!cache_path.empty()) args.push_back(cache_path); - for (const auto& a : pass) args.push_back(a); - args.insert(args.end(), {"--isolate-child", "--start", std::to_string(start), "--count", std::to_string(count)}); - collect_child(exe, args, r); - std::string_view output = r.out; - while (!output.empty()) { - const auto line = next_child_line(output); - if (line == "ISO-READY") r.ready = true; - else if (line.rfind("ISO-DONE", 0) == 0) { r.done = true; r.cache_ok = line.find("cache_ok=0") == std::string_view::npos; } - } - return r; -} - -} // namespace - -int main(int argc, char** argv) { - if (argc < 2) { - std::fprintf(stderr, - "usage: vk_pipeline_check [cache.bin] [--jobs N] [--start I] [--count N] [--slow SEC] " - "[--max-bytes N] [--large-module-bytes N] [--large-parallel N] [--stage all|cs|graphics | --compute-only | --graphics-only] " - "[--stats FILE] [--cache-feedback] [--isolate [--isolate-batch N]] [--inflight-file F] " - "[--skip-file F]\n"); - return 2; - } - std::setvbuf(stdout, nullptr, _IOLBF, 1 << 16); // failures reach a redirected log as they happen - std::string dir = argv[1], cache_path, stats_path, inflight_path, skip_path; - bool cache_given = false; // an empty cache_path alone can't tell "not given" from an empty argument - uint32_t jobs = std::max(1u, std::thread::hardware_concurrency() / 2); - size_t start = 0, count = 0, max_bytes = 0; - size_t large_module_bytes = 4 * 1024 * 1024; - unsigned large_parallel = 0; // 0 = by the memory budget - double slow = 30.0; - std::string stage_filter = "all"; - bool cache_feedback = false, isolate = false, iso_child = false; - size_t isolate_batch = 256; - for (int i = 2; i < argc; i++) { - std::string a = argv[i]; - auto value = [&]() -> std::string_view { - if (i + 1 == argc || std::string_view(argv[i + 1]).starts_with("--")) return {}; - return argv[++i]; - }; - auto number = [&](auto& dest) { - const auto text = value(); - if (text.empty()) return false; - if constexpr (std::is_floating_point_v>) { - // Apple's libc++ has no floating-point from_chars overload. Parse the whole token with strtod, - // as shader_library.h does for JSON numbers; --slow also checks isfinite and >= 0 below. - const std::string token(text); - char* end = nullptr; - errno = 0; - const double parsed = std::strtod(token.c_str(), &end); - if (errno == ERANGE || end != token.c_str() + token.size()) return false; - dest = static_cast>(parsed); - return true; - } else { - const auto end = text.data() + text.size(); - const auto [ptr, ec] = std::from_chars(text.data(), end, dest); - return ec == std::errc{} && ptr == end; - } - }; - bool valid = true; - if (a == "--jobs") { - valid = number(jobs); - jobs = std::max(1u, jobs); - } else if (a == "--start") valid = number(start); - else if (a == "--count") valid = number(count); - else if (a == "--slow") valid = number(slow) && std::isfinite(slow) && slow >= 0.0; - else if (a == "--stage") valid = !(stage_filter = value()).empty(); - else if (a == "--compute-only") stage_filter = "cs"; - else if (a == "--graphics-only") stage_filter = "graphics"; - else if (a == "--max-bytes") valid = number(max_bytes); - else if (a == "--large-module-bytes") valid = number(large_module_bytes); - else if (a == "--large-parallel") valid = number(large_parallel); - else if (a == "--stats") valid = !(stats_path = value()).empty(); - else if (a == "--inflight-file") valid = !(inflight_path = value()).empty(); - else if (a == "--skip-file") valid = !(skip_path = value()).empty(); - else if (a == "--cache-feedback") cache_feedback = true; - else if (a == "--isolate") isolate = true; - else if (a == "--isolate-child") iso_child = true; // internal: the parent's child runs - else if (a == "--isolate-batch") { // parsed like the other numbers (#1735); at least one per batch - valid = number(isolate_batch); - isolate_batch = std::max(1, isolate_batch); - } - else if (a.starts_with("--")) { // not a cache path: an option this build doesn't know - std::fprintf(stderr, "unknown option %s\n", a.c_str()); - return 2; - } else if (!cache_given) { - cache_path = a; - cache_given = true; - } else { - std::fprintf(stderr, "unexpected argument '%s' (a cache path was already given: '%s')\n", a.c_str(), - cache_path.c_str()); - return 2; - } - if (!valid) { - std::fprintf(stderr, "%s requires a valid value\n", a.c_str()); - return 2; - } - } - if (stage_filter != "all" && stage_filter != "cs" && stage_filter != "graphics") { - std::fprintf(stderr, "unknown --stage '%s' (expected: all, cs, graphics)\n", stage_filter.c_str()); - return 2; - } - - if (isolate && !stats_path.empty()) { - std::fprintf(stderr, "--isolate cannot be combined with --stats\n"); - return 2; - } -#ifdef _WIN32 - if (iso_child) SetErrorMode(GetErrorMode() | SEM_FAILCRITICALERRORS | SEM_NOGPFAULTERRORBOX); -#endif - - const std::string index_path = dir + "/index.json"; - const auto same_file = [](const std::string& a, const std::string& b) { - std::error_code error; - return std::filesystem::equivalent(a, b, error); - }; - // These inputs already exist on a valid invocation. Compare file identity so aliases are also protected. - for (const auto& [option, output] : {std::pair{"cache path", &cache_path}, - std::pair{"--stats", &stats_path}, - std::pair{"--inflight-file", &inflight_path}}) { - if (output->empty()) continue; - const char* input = nullptr; - if (same_file(*output, index_path)) input = "index.json"; - else if (!skip_path.empty() && same_file(*output, skip_path)) input = "--skip-file"; - if (input) { - std::fprintf(stderr, "error: %s must not overwrite %s\n", option, input); - return 2; - } - } - - std::set skip_names; // --skip-file: modules that killed the driver in an earlier run - if (!skip_path.empty()) { - std::ifstream sf(skip_path); - if (!sf) { - std::fprintf(stderr, "error: cannot read --skip-file %s\n", skip_path.c_str()); - return 2; - } - for (std::string line; std::getline(sf, line);) { - while (!line.empty() && (line.back() == '\r' || line.back() == ' ')) line.pop_back(); - if (!line.empty()) skip_names.insert(line); - } - } - - std::string index_err; - bool index_unreadable = false; - auto index = read_index(index_path, index_err, index_unreadable); - if (!index_err.empty()) { - std::fprintf(stderr, index_unreadable ? "error: cannot read %s/index.json: %s\n" : "error: malformed JSON in %s/index.json: %s\n", - dir.c_str(), index_err.c_str()); - return 2; - } - std::fprintf(stderr, "%zu shaders in index\n", index.size()); - - // Build work list: index order (sorted by name), optionally filtered by stage, then [start, start + count). - using Item = std::pair; - std::vector all; - for (auto& [name, meta] : index) { - if (stage_filter == "cs" && meta.stage != "cs") continue; - if (stage_filter == "graphics" && !is_graphics_stage(meta.stage)) continue; - all.push_back({&name, &meta}); - } - const auto [lo, hi] = shader_slice(all.size(), start, count); - const std::vector work(all.begin() + lo, all.begin() + hi); - - if (isolate) { - // Parent: no Vulkan here. Run the check in child processes, one at a time, in batches of --isolate-batch - // modules. A child that dies mid-batch has its output discarded and the batch is bisected until the one - // module that kills the driver is found; the clean sub-runs partition the rest, so nothing is counted twice. - const auto exe = self_executable(argv[0]); - if (exe.empty()) { - std::fprintf(stderr, "error: could not find the executable for --isolate\n"); - return 1; - } - std::vector pass = {"--jobs", std::to_string(jobs), "--slow", std::to_string(slow), "--stage", stage_filter, - "--max-bytes", std::to_string(max_bytes), - "--large-module-bytes", std::to_string(large_module_bytes), - "--large-parallel", std::to_string(large_parallel)}; - if (cache_feedback) pass.push_back("--cache-feedback"); - if (!inflight_path.empty()) pass.insert(pass.end(), {"--inflight-file", inflight_path}); - if (!skip_path.empty()) pass.insert(pass.end(), {"--skip-file", skip_path}); - struct Agg { uint32_t mod_ok = 0, mod_bad = 0, pipe_ok = 0, pipe_bad = 0, pipe_skip = 0, big = 0, crashed = 0, fb[3] = {}; }; - std::map agg; - std::vector crashes; - bool cache_ok = true, setup_failed = false; - size_t unreproduced = 0; - const auto t_iso = std::chrono::steady_clock::now(); - std::fprintf(stderr, "isolating %zu shaders [%zu, %zu) (stage=%s) in child processes, %zu per batch\n", - work.size(), lo, hi, stage_filter.c_str(), isolate_batch); - auto commit = [&](const ChildRun& r) { - std::string_view output = r.out; - while (!output.empty()) { - const std::string line(next_child_line(output)); - // The parent prints one cache line at the end instead of one per child. - if (line == "ISO-READY" || line.rfind("ISO-DONE", 0) == 0 || line.rfind("pipeline cache: ", 0) == 0) continue; - if (line.rfind("ISO-RESULT ", 0) == 0) { - char st[16]; - unsigned v[9] = {}; - if (std::sscanf(line.c_str(), "ISO-RESULT %15s %u %u %u %u %u %u %u %u %u", st, v, v + 1, v + 2, v + 3, - v + 4, v + 5, v + 6, v + 7, v + 8) == 10) { - Agg& a = agg[st]; - a.mod_ok += v[0]; a.mod_bad += v[1]; a.pipe_ok += v[2]; a.pipe_bad += v[3]; a.pipe_skip += v[4]; - a.big += v[5]; a.fb[0] += v[6]; a.fb[1] += v[7]; a.fb[2] += v[8]; - } - continue; - } - std::printf("%s\n", line.c_str()); - } - std::fflush(stdout); - if (!r.cache_ok) cache_ok = false; - }; - // Returns the number of failures recorded for [s, s + n): crashed modules, or 1 for a crash that vanished. - auto bisect = [&](auto&& self, size_t s, size_t n) -> size_t { - if (setup_failed) return 0; - const ChildRun r = run_child(exe, dir, pass, cache_path, s, n); - if (!r.runner_error.empty()) { - std::fprintf(stderr, "error: could not run an isolation child: %s\n", r.runner_error.c_str()); - setup_failed = true; - return 0; - } - if (r.done) { commit(r); return 0; } - const std::string status = child_exit_status(r.status); -#ifndef _WIN32 - const std::string signal = r.sig ? signal_label(r.sig) : ""; -#else - const std::string signal; -#endif - if (!r.ready) { // died or exited before the work loop: not a module's fault - std::fputs(r.out.c_str(), stdout); - if (!signal.empty()) std::fprintf(stderr, "error: a child process died during setup (%s)\n", signal.c_str()); - else std::fprintf(stderr, "error: a child process failed during setup (exit status %s)\n", status.c_str()); - setup_failed = true; - return 0; - } - const std::string why = signal.empty() ? "driver exited with status " + status : "driver crashed: " + signal; - if (n == 1) { - const std::string& name = *all[s].first; - const std::string& st = all[s].second->stage; - std::printf("MODULE CRASH %s (%s, %s)\n", name.c_str(), st.c_str(), why.c_str()); - std::fflush(stdout); - crashes.push_back(name + " (" + st + ", " + why + ")"); - agg[st].pipe_bad++; - agg[st].crashed++; - return 1; - } - std::fprintf(stderr, "child over [%zu, %zu) died (%s); bisecting\n", s, s + n, why.c_str()); - const size_t half = n / 2; - size_t found = self(self, s, half); - found += self(self, s + half, n - half); - if (found == 0 && !setup_failed) { - std::printf("MODULE CRASH [%zu, %zu) not reproduced when split (%s); counted as failed\n", s, s + n, why.c_str()); - ++unreproduced; - return 1; - } - return found; - }; - for (size_t s = lo; s < hi && !setup_failed;) { - const size_t batch = std::min(isolate_batch, hi - s); - bisect(bisect, s, batch); - s += batch; - } - if (setup_failed) return 1; - bool failed = !crashes.empty() || unreproduced || !cache_ok; - for (const auto& [st, a] : agg) { - std::printf("%s: %u modules ok, %u failed\n", st.c_str(), a.mod_ok, a.mod_bad); - std::printf("%s pipelines: %u ok, %u failed, %u skipped\n", st.c_str(), a.pipe_ok, a.pipe_bad, a.pipe_skip); - if (a.crashed) std::printf(" %s crashed the driver: %u (counted as failed)\n", st.c_str(), a.crashed); - if (cache_feedback) - std::printf(" %s cache feedback: %u hits, %u no hit reported, %u unavailable\n", st.c_str(), a.fb[0], a.fb[1], a.fb[2]); - if (a.mod_bad || a.pipe_bad) failed = true; - } - uint32_t big_total = 0; - for (const auto& [st, a] : agg) big_total += a.big; - if (big_total) std::printf("big modules skipped: %u (limit %zu bytes)\n", big_total, max_bytes); - if (!crashes.empty()) { - std::printf("modules that crashed the driver: %zu\n", crashes.size()); - for (const auto& c : crashes) std::printf(" %s\n", c.c_str()); - } - if (unreproduced) std::printf("crashes not reproduced after splitting: %zu\n", unreproduced); - if (!cache_path.empty()) { - std::error_code ec; - const auto sz = std::filesystem::file_size(cache_path, ec); - if (!ec) std::printf("pipeline cache: %ju bytes -> %s\n", static_cast(sz), cache_path.c_str()); - } - std::printf("wall time: %.1fs (isolated)\n", - std::chrono::duration(std::chrono::steady_clock::now() - t_iso).count()); - return failed ? 1 : 0; - } - - // Scan selected shaders to request only the optional extensions they actually use. - bool want_mesh = false, want_bary = false, want_lock = false, want_m8 = false, want_fma = false, want_clock = false; - for (auto& [_, meta] : work) { - if (meta->stage == "ms") want_mesh = true; - if (meta->needs_maintenance8) want_m8 = true; - for (const auto& feat : meta->features) { - if (feat == "meshShader") want_mesh = true; - else if (feat == "fragmentShaderBarycentric") want_bary = true; - else if (feat == "fragmentShaderPixelInterlock") want_lock = true; - else if (feat == "shaderFmaFloat32" || feat == "shaderFmaFloat64") want_fma = true; // OpFmaKHR (--fma khr) - else if (feat == "shaderSubgroupClock" || feat == "shaderDeviceClock") want_clock = true; - } - } - - gipa = load_vulkan(); - if (!gipa) return 1; -#define LOADI(name) auto name = reinterpret_cast(gipa(inst, #name)) - VkInstance inst = VK_NULL_HANDLE; - LOADI(vkCreateInstance); - VkApplicationInfo app{VK_STRUCTURE_TYPE_APPLICATION_INFO}; - app.apiVersion = VK_API_VERSION_1_3; - VkInstanceCreateInfo ici{VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO}; - ici.pApplicationInfo = &app; - if (vkCreateInstance(&ici, nullptr, &inst)) return 1; - LOADI(vkEnumeratePhysicalDevices); LOADI(vkGetPhysicalDeviceProperties); LOADI(vkCreateDevice); - LOADI(vkGetPhysicalDeviceProperties2); - LOADI(vkGetDeviceProcAddr); LOADI(vkEnumerateDeviceExtensionProperties); LOADI(vkGetPhysicalDeviceFeatures2); - uint32_t n = 0; - vkEnumeratePhysicalDevices(inst, &n, nullptr); - if (n == 0) { std::fprintf(stderr, "no Vulkan physical devices found\n"); return 1; } - std::vector pds(n); - vkEnumeratePhysicalDevices(inst, &n, pds.data()); - std::vector candidates(pds.size()); - for (std::size_t i = 0; i < pds.size(); ++i) vkGetPhysicalDeviceProperties(pds[i], &candidates[i]); - const std::size_t chosen = leonida::vk_test::pick_device(candidates); - VkPhysicalDevice pd = chosen < pds.size() ? pds[chosen] : VK_NULL_HANDLE; - if (!pd) { - leonida::vk_test::report_no_device(); - return 1; - } - VkPhysicalDeviceProperties props; vkGetPhysicalDeviceProperties(pd, &props); - VkPhysicalDeviceSubgroupSizeControlProperties sgProps{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SUBGROUP_SIZE_CONTROL_PROPERTIES}; - VkPhysicalDeviceFloatControlsProperties fcProps{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FLOAT_CONTROLS_PROPERTIES}; - VkPhysicalDeviceProperties2 props2{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROPERTIES_2}; - props2.pNext = &sgProps; - sgProps.pNext = &fcProps; - vkGetPhysicalDeviceProperties2(pd, &props2); - std::fprintf(stderr, "device: %s (subgroup %u..%u)\n", props.deviceName, sgProps.minSubgroupSize, sgProps.maxSubgroupSize); - - uint32_t en = 0; - vkEnumerateDeviceExtensionProperties(pd, nullptr, &en, nullptr); - std::vector exts(en); - vkEnumerateDeviceExtensionProperties(pd, nullptr, &en, exts.data()); - auto has = [&](const char* e) { for (auto& x : exts) if (!std::strcmp(x.extensionName, e)) return true; return false; }; - std::vector enable; - - // Query what the GPU supports for core 1.2/1.3 and any optional extensions requested by `work`. - VkPhysicalDeviceMeshShaderFeaturesEXT mesh{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MESH_SHADER_FEATURES_EXT}; - VkPhysicalDeviceFragmentShaderBarycentricFeaturesKHR bary{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FRAGMENT_SHADER_BARYCENTRIC_FEATURES_KHR}; - VkPhysicalDeviceFragmentShaderInterlockFeaturesEXT lock{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FRAGMENT_SHADER_INTERLOCK_FEATURES_EXT}; -#ifdef VK_KHR_MAINTENANCE_8_EXTENSION_NAME - VkPhysicalDeviceMaintenance8FeaturesKHR m8{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MAINTENANCE_8_FEATURES_KHR}; -#endif - VkPhysicalDevicePipelineExecutablePropertiesFeaturesKHR exe{ - VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PIPELINE_EXECUTABLE_PROPERTIES_FEATURES_KHR}; - VkPhysicalDeviceVulkan11Features f11{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_1_FEATURES}; - VkPhysicalDeviceVulkan12Features f12{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_2_FEATURES}; - VkPhysicalDeviceVulkan13Features f13{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_3_FEATURES}; - void* chain = nullptr; - auto link = [&](void* s, VkBaseOutStructure* b, const char* ext, bool needed) -> bool { - if (!needed) return false; - if (ext && !has(ext)) return false; - if (ext) enable.push_back(ext); - b->pNext = static_cast(chain); chain = s; - return true; - }; - link(&f11, reinterpret_cast(&f11), nullptr, true); // shaderDrawParameters (VS v0/v3) - link(&f12, reinterpret_cast(&f12), nullptr, true); - link(&f13, reinterpret_cast(&f13), nullptr, true); - const bool ext_mesh = link(&mesh, reinterpret_cast(&mesh), VK_EXT_MESH_SHADER_EXTENSION_NAME, want_mesh); - const bool ext_bary = link(&bary, reinterpret_cast(&bary), VK_KHR_FRAGMENT_SHADER_BARYCENTRIC_EXTENSION_NAME, want_bary); - const bool ext_lock = link(&lock, reinterpret_cast(&lock), VK_EXT_FRAGMENT_SHADER_INTERLOCK_EXTENSION_NAME, want_lock); -#ifdef VK_KHR_MAINTENANCE_8_EXTENSION_NAME - const bool ext_m8 = link(&m8, reinterpret_cast(&m8), VK_KHR_MAINTENANCE_8_EXTENSION_NAME, want_m8); -#else - (void)want_m8; -#endif -#ifdef VK_KHR_SHADER_FMA_EXTENSION_NAME - VkPhysicalDeviceShaderFmaFeaturesKHR fma{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADER_FMA_FEATURES_KHR}; - const bool ext_fma = link(&fma, reinterpret_cast(&fma), VK_KHR_SHADER_FMA_EXTENSION_NAME, want_fma); -#else - const bool ext_fma = false; - (void)want_fma; -#endif - VkPhysicalDeviceShaderClockFeaturesKHR clock{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADER_CLOCK_FEATURES_KHR}; - const bool ext_clock = link(&clock, reinterpret_cast(&clock), VK_KHR_SHADER_CLOCK_EXTENSION_NAME, want_clock); - const bool ext_exe = link(&exe, reinterpret_cast(&exe), - VK_KHR_PIPELINE_EXECUTABLE_PROPERTIES_EXTENSION_NAME, !stats_path.empty()); - if (!stats_path.empty() && !ext_exe) { - std::fprintf(stderr, "--stats: the device has no %s\n", VK_KHR_PIPELINE_EXECUTABLE_PROPERTIES_EXTENSION_NAME); - return 1; - } - // --cache-feedback: core in Vulkan 1.3 (no feature bit). A pre-1.3 device needs VK_EXT_pipeline_creation_feedback; - // without it nothing is chained and every successful pipeline counts as unavailable. - const bool fb_ext = cache_feedback && props.apiVersion < VK_API_VERSION_1_3 && - has(VK_EXT_PIPELINE_CREATION_FEEDBACK_EXTENSION_NAME); - if (fb_ext) enable.push_back(VK_EXT_PIPELINE_CREATION_FEEDBACK_EXTENSION_NAME); - const bool feedback = cache_feedback && (props.apiVersion >= VK_API_VERSION_1_3 || fb_ext); - if (cache_feedback && !feedback) - std::fprintf(stderr, "note: --cache-feedback: no Vulkan 1.3 or %s; every pipeline is counted unavailable\n", - VK_EXT_PIPELINE_CREATION_FEEDBACK_EXTENSION_NAME); - VkPhysicalDeviceFeatures2 f2{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2}; - f2.pNext = chain; - vkGetPhysicalDeviceFeatures2(pd, &f2); // fills every linked struct with what's supported - VkPhysicalDeviceMeshShaderPropertiesEXT mesh_props{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MESH_SHADER_PROPERTIES_EXT}; - if (ext_mesh && mesh.meshShader) { - VkPhysicalDeviceProperties2 mesh_device_props{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROPERTIES_2}; - mesh_device_props.pNext = &mesh_props; - vkGetPhysicalDeviceProperties2(pd, &mesh_device_props); - } - if (ext_mesh) { - mesh.multiviewMeshShader = mesh.primitiveFragmentShadingRateMeshShader = mesh.meshShaderQueries = VK_FALSE; - mesh.taskShader = VK_FALSE; - } - float prio = 1; - VkDeviceQueueCreateInfo qci{VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO}; - qci.queueFamilyIndex = 0; qci.queueCount = 1; qci.pQueuePriorities = &prio; - VkDeviceCreateInfo dci{VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO}; - dci.queueCreateInfoCount = 1; dci.pQueueCreateInfos = &qci; dci.pNext = &f2; - dci.enabledExtensionCount = uint32_t(enable.size()); dci.ppEnabledExtensionNames = enable.data(); - VkDevice dev; - if (VkResult r = vkCreateDevice(pd, &dci, nullptr, &dev)) { std::fprintf(stderr, "vkCreateDevice %d\n", r); return 1; } - leonida::SubgroupSizeCaps runtime_subgroups; - leonida::query_subgroup_size_caps(vkGetPhysicalDeviceProperties2, pd, f13.subgroupSizeControl, - f13.computeFullSubgroups, runtime_subgroups); - auto can_require_sg = [&](uint32_t sg, VkShaderStageFlagBits bit) -> bool { - return f13.subgroupSizeControl && - sg >= sgProps.minSubgroupSize && - sg <= sgProps.maxSubgroupSize && - (sgProps.requiredSubgroupSizeStages & bit); - }; - auto runtime_compute_subgroup = [&](const ShaderMeta& meta) { - leonida::ShaderEntry entry; - entry.stage = meta.stage; - entry.subgroup_size = meta.subgroup_size; - entry.wave64 = meta.wave64; - entry.wave64_exchange = meta.wave64_exchange; - entry.local_size = meta.local_size; - return leonida::decide_subgroup_size(entry, runtime_subgroups); - }; - { - std::map> unforced_by_sg; - for (const auto& [_, meta] : work) { - if (uses_runtime_compute_layout(*meta)) { - const auto request = runtime_compute_subgroup(*meta); - if (request.outcome == leonida::SubgroupOutcome::unavailable) - unforced_by_sg[request.wanted].insert(meta->stage); - continue; - } - const VkShaderStageFlagBits bit = stage_bit(meta->stage); - if (bit && meta->subgroup_size > 0 && !can_require_sg(meta->subgroup_size, bit)) { - unforced_by_sg[meta->subgroup_size].insert(meta->stage); - } - } - for (const auto& [sg, stages] : unforced_by_sg) { - std::string list; - for (const auto& st : stages) { - if (!list.empty()) list += "/"; - list += st; - } - std::fprintf(stderr, - "note: %u-wide subgroups not supported for %s; those pipelines are compiled without a required subgroup size\n", - sg, list.c_str()); - } - } -#define LOADD(name) auto name = reinterpret_cast(vkGetDeviceProcAddr(dev, #name)) - LOADD(vkCreateShaderModule); LOADD(vkDestroyShaderModule); LOADD(vkCreateDescriptorSetLayout); - LOADD(vkCreatePipelineLayout); LOADD(vkCreateComputePipelines); LOADD(vkCreateGraphicsPipelines); - LOADD(vkDestroyPipeline); LOADD(vkCreatePipelineCache); LOADD(vkGetPipelineCacheData); - LOADD(vkGetPipelineExecutablePropertiesKHR); LOADD(vkGetPipelineExecutableStatisticsKHR); - const VkPipelineCreateFlags capture = stats_path.empty() ? 0 : VK_PIPELINE_CREATE_CAPTURE_STATISTICS_BIT_KHR; - - // These capability requirements apply as soon as the module is passed to Vulkan. - auto check_missing_module_feature = [&](const ShaderMeta& meta) -> std::string { - for (const auto& feat : meta.features) { - if (feat == "shaderSampledImageArrayDynamicIndexing" && !f2.features.shaderSampledImageArrayDynamicIndexing) - return "no " + feat; - if (feat == "shaderStorageImageArrayDynamicIndexing" && !f2.features.shaderStorageImageArrayDynamicIndexing) - return "no " + feat; - // A device without the OpFmaKHR width can reject the module itself, so skip before vkCreateShaderModule. - if (feat == "shaderFmaFloat32") { -#ifdef VK_KHR_SHADER_FMA_EXTENSION_NAME - if (!(ext_fma && fma.shaderFmaFloat32)) return "no VK_KHR_shader_fma (shaderFmaFloat32)"; -#else - return "no VK_KHR_shader_fma (shaderFmaFloat32)"; -#endif - } - if (feat == "shaderFmaFloat64") { -#ifdef VK_KHR_SHADER_FMA_EXTENSION_NAME - if (!(ext_fma && fma.shaderFmaFloat64)) return "no VK_KHR_shader_fma (shaderFmaFloat64)"; -#else - return "no VK_KHR_shader_fma (shaderFmaFloat64)"; -#endif - } - } - return {}; - }; - - // Keep the remaining pipeline compatibility checks after module creation. - auto check_missing_feature = [&](const ShaderMeta& meta) -> std::string { - const uint32_t need_pc = required_push_bytes(meta.push_constant_bytes, meta.pc_tail_bytes); - if (need_pc > props.limits.maxPushConstantsSize) { - return "needs " + std::to_string(need_pc) + " push-constant bytes, device has " + - std::to_string(props.limits.maxPushConstantsSize) + - (need_pc > 128 ? " (translate with --pc-tail-ubo)" : ""); - } - if (is_graphics_stage(meta.stage) && !f13.dynamicRendering) return "no dynamicRendering"; - if (meta.stage == "ms" && !(ext_mesh && mesh.meshShader)) return "no VK_EXT_mesh_shader"; - if (meta.stage == "gs" && !f2.features.geometryShader) return "no geometryShader"; - if (meta.needs_maintenance8) { -#ifdef VK_KHR_MAINTENANCE_8_EXTENSION_NAME - if (!(ext_m8 && m8.maintenance8)) return "no VK_KHR_maintenance8"; -#else - return "no VK_KHR_maintenance8"; -#endif - } - // Execution modes the translator declares (SignedZeroInfNanPreserve 32, and 64 with Float64; - // DenormPreserve 16) need a device property, not a feature. - for (const auto& fc : meta.float_controls) { - if (fc == "shaderSignedZeroInfNanPreserveFloat32") { - if (!fcProps.shaderSignedZeroInfNanPreserveFloat32) return "no " + fc; - } else if (fc == "shaderSignedZeroInfNanPreserveFloat64") { - if (!fcProps.shaderSignedZeroInfNanPreserveFloat64) return "no " + fc; - } else if (fc == "shaderDenormPreserveFloat16") { - if (!fcProps.shaderDenormPreserveFloat16) return "no " + fc; - } else { - return "unknown float control " + fc; - } - } - for (const auto& feat : meta.features) { - if (feat == "meshShader" && !(ext_mesh && mesh.meshShader)) return "no VK_EXT_mesh_shader"; - if (feat == "geometryShader" && !f2.features.geometryShader) return "no geometryShader"; - if (feat == "fragmentShaderBarycentric" && !(ext_bary && bary.fragmentShaderBarycentric)) return "no fragmentShaderBarycentric"; - if (feat == "fragmentShaderPixelInterlock" && !(ext_lock && lock.fragmentShaderPixelInterlock)) return "no fragmentShaderPixelInterlock"; - if (feat == "shaderSubgroupClock" && !(ext_clock && clock.shaderSubgroupClock)) return "no shaderSubgroupClock"; - if (feat == "shaderDeviceClock" && !(ext_clock && clock.shaderDeviceClock)) return "no shaderDeviceClock"; - if (feat == "shaderFloat64" && !f2.features.shaderFloat64) return "no shaderFloat64"; - if (feat == "shaderInt64" && !f2.features.shaderInt64) return "no shaderInt64"; - if (feat == "shaderDrawParameters" && !f11.shaderDrawParameters) return "no shaderDrawParameters"; - if (feat == "bufferDeviceAddress" && !f12.bufferDeviceAddress) return "no bufferDeviceAddress"; - if (feat == "runtimeDescriptorArray" && !f12.runtimeDescriptorArray) return "no runtimeDescriptorArray"; - if (feat == "shaderImageGatherExtended" && !f2.features.shaderImageGatherExtended) return "no shaderImageGatherExtended"; - if (feat == "shaderResourceMinLod" && !f2.features.shaderResourceMinLod) return "no shaderResourceMinLod"; - if (feat == "shaderStorageImageWriteWithoutFormat" && !f2.features.shaderStorageImageWriteWithoutFormat) - return "no shaderStorageImageWriteWithoutFormat"; - if (feat == "shaderStorageImageReadWithoutFormat" && !f2.features.shaderStorageImageReadWithoutFormat) - return "no shaderStorageImageReadWithoutFormat"; - } - return {}; - }; - - // Resource contract (docs/design.md): set 0, runtime-sized arrays as large bindless arrays. - std::vector b; - auto add = [&](uint32_t bind, VkDescriptorType t, uint32_t cnt) { - b.push_back({bind, t, cnt, VK_SHADER_STAGE_ALL, nullptr}); - }; - add(0, VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE, 4096); add(1, VK_DESCRIPTOR_TYPE_SAMPLER, 1024); - add(2, VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, 1); add(3, VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE, 1024); - add(4, VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, 1024); add(5, VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE, 256); - add(6, VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE, 256); add(7, VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, 256); - for (uint32_t i = 8; i <= 19; i++) add(i, VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, 256); - VkDescriptorSetLayoutCreateInfo dli{VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO}; - dli.bindingCount = uint32_t(b.size()); dli.pBindings = b.data(); - VkDescriptorSetLayout dsl; - if (VkResult r = vkCreateDescriptorSetLayout(dev, &dli, nullptr, &dsl)) { std::fprintf(stderr, "layout %d\n", r); return 1; } - // Set 1 of --pc-tail-ubo shaders (docs/design.md): dynamic uniform block at binding 0 holding heap/code base. - const VkDescriptorSetLayoutBinding tail_binding{0, VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC, 1, - VK_SHADER_STAGE_ALL, nullptr}; - VkDescriptorSetLayoutCreateInfo tail_dli{VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO}; - tail_dli.bindingCount = 1; tail_dli.pBindings = &tail_binding; - VkDescriptorSetLayout dsl_tail = VK_NULL_HANDLE; - if (VkResult r = vkCreateDescriptorSetLayout(dev, &tail_dli, nullptr, &dsl_tail)) { - std::fprintf(stderr, "tail layout %d\n", r); return 1; - } - // One VkPipelineLayout per (push_constant_bytes, has_pc_tail) needed by the selected shaders that fits - // maxPushConstantsSize; never declares a range above the device limit (VUID-VkPushConstantRange-size-00298). - std::map, VkPipelineLayout> layouts; - for (const auto& [_, meta] : work) { - const uint32_t need_pc = required_push_bytes(meta->push_constant_bytes, meta->pc_tail_bytes); - if (need_pc > props.limits.maxPushConstantsSize) continue; - const std::pair key{need_pc, meta->pc_tail_bytes != 0}; - if (layouts.count(key)) continue; - VkPushConstantRange pcr{VK_SHADER_STAGE_ALL, 0, need_pc}; - VkDescriptorSetLayout sets[2] = {dsl, dsl_tail}; - VkPipelineLayoutCreateInfo pli{VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO}; - pli.setLayoutCount = key.second ? 2u : 1u; - pli.pSetLayouts = sets; - pli.pushConstantRangeCount = 1; - pli.pPushConstantRanges = &pcr; - VkPipelineLayout pl = VK_NULL_HANDLE; - if (VkResult r = vkCreatePipelineLayout(dev, &pli, nullptr, &pl)) { - std::fprintf(stderr, "pipeline layout (%u bytes%s) %d\n", need_pc, key.second ? ", set 1" : "", r); - return 1; - } - layouts.emplace(key, pl); - } - auto layout_for = [&](const ShaderMeta& meta) -> VkPipelineLayout { - const uint32_t need_pc = required_push_bytes(meta.push_constant_bytes, meta.pc_tail_bytes); - return layouts.at({need_pc, meta.pc_tail_bytes != 0}); - }; - VkPipelineLayout runtime_compute_layout = VK_NULL_HANDLE; - if (runtime_compute_push_bytes <= props.limits.maxPushConstantsSize && - std::any_of(work.begin(), work.end(), [](const Item& item) { - return uses_runtime_compute_layout(*item.second); - })) { - const VkPushConstantRange push{VK_SHADER_STAGE_COMPUTE_BIT, 0, runtime_compute_push_bytes}; - VkPipelineLayoutCreateInfo info{VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO}; - info.pushConstantRangeCount = 1; - info.pPushConstantRanges = &push; - if (VkResult r = vkCreatePipelineLayout(dev, &info, nullptr, &runtime_compute_layout)) { - std::fprintf(stderr, "runtime compute pipeline layout %d\n", r); - return 1; - } - } - VkPipelineCacheCreateInfo pci{VK_STRUCTURE_TYPE_PIPELINE_CACHE_CREATE_INFO}; - std::vector seed; - if (!cache_path.empty()) { // resume: pipelines already in the cache compile instantly - std::ifstream cf(cache_path, std::ios::binary); - seed.assign(std::istreambuf_iterator(cf), {}); - if (!seed.empty()) std::fprintf(stderr, "seeded the pipeline cache with %zu bytes from %s\n", seed.size(), cache_path.c_str()); - } - pci.initialDataSize = seed.size(); pci.pInitialData = seed.empty() ? nullptr : seed.data(); - VkPipelineCache cache = VK_NULL_HANDLE; - if (vkCreatePipelineCache(dev, &pci, nullptr, &cache)) { // data from another driver: start empty - pci.initialDataSize = 0; pci.pInitialData = nullptr; - if (VkResult r = vkCreatePipelineCache(dev, &pci, nullptr, &cache)) { - std::fprintf(stderr, "vkCreatePipelineCache failed: %d\n", r); - return 1; - } - } - std::vector().swap(seed); // the driver has copied the seed; it can be several GiB - auto save_cache = [&](bool final_save) { - if (cache_path.empty()) return true; - try { - const auto data = pipeline_cache_snapshot([&](size_t* size, void* dest) { - return vkGetPipelineCacheData(dev, cache, size, dest); - }); - if (auto error = write_pipeline_cache_file(cache_path, data.data(), data.size())) - throw std::system_error(error); - if (final_save) std::printf("pipeline cache: %zu bytes -> %s\n", data.size(), cache_path.c_str()); - return true; - } catch (const std::exception& e) { - std::fprintf(stderr, "%s pipeline cache save to %s failed: %s\n", - final_save ? "final" : "periodic", cache_path.c_str(), e.what()); - return false; - } - }; - - const auto worker_count = static_cast(std::min(jobs, work.size())); - std::fprintf(stderr, "checking %zu shaders [%zu, %zu) (stage=%s) on %u threads\n", - work.size(), lo, hi, stage_filter.c_str(), worker_count); - - std::mutex mu; // guards counters, stdout, stub cache and in-flight table - std::shared_mutex compile_gate; // --large-parallel 1: large modules exclude other shader and pipeline work - size_t isolated_modules = 0; - // Otherwise large modules share a memory budget and the small ones are never held back (large_module_gate.h). - const uint64_t available_memory = leonida::available_memory_bytes(); - const bool large_exclusive = large_parallel == 1 || (large_parallel == 0 && available_memory == 0); - leonida::LargeModuleGate large_gate( - large_parallel == 0 ? available_memory / 4 * 3 : UINT64_MAX, - large_parallel == 0 ? jobs : std::min(large_parallel, jobs)); - if (large_module_bytes) { - if (large_exclusive) - std::fprintf(stderr, "large modules (over %zu bytes): one at a time, the other threads waiting\n", - large_module_bytes); - else if (large_parallel == 0) - std::fprintf(stderr, "large modules (over %zu bytes): up to %u at once within %.1f GB " - "(3/4 of the %.1f GB available)\n", large_module_bytes, large_gate.max_inflight(), - large_gate.budget() / 1e9, available_memory / 1e9); - else - std::fprintf(stderr, "large modules (over %zu bytes): up to %u at once\n", large_module_bytes, - large_gate.max_inflight()); - } - std::map modules_ok, modules_bad, big_skipped; - std::map stats; - std::map stub_cache; - std::atomic next{0}, done{0}; - std::atomic total_pipes_done{0}; - // What each worker is doing in the driver: creating the shader module, then creating its pipeline. - struct InFlight { - std::string name; - std::chrono::steady_clock::time_point since; - const char* phase; // "module" or "pipeline" - }; - std::map inflight; - // Publish a complete snapshot at the moments named in the header. This keeps the last full report if the - // process dies while staging the next one. Called with mu held. - auto write_inflight = [&] { - if (inflight_path.empty()) return; - std::string snapshot; - for (const auto& [tid, job] : inflight) { - snapshot += job.name; - snapshot += '\t'; - snapshot += job.phase; - snapshot += '\n'; - } - if (const auto error = write_pipeline_cache_file(inflight_path, snapshot.data(), snapshot.size())) - std::fprintf(stderr, "in-flight snapshot save to %s failed: %s\n", - inflight_path.c_str(), error.message().c_str()); - }; - const auto t_start = std::chrono::steady_clock::now(); - auto elapsed = [&] { return std::chrono::duration(std::chrono::steady_clock::now() - t_start).count(); }; - - auto load_stub = [&](const std::string& fname) -> VkShaderModule { - { - std::lock_guard g(mu); - auto it = stub_cache.find(fname); - if (it != stub_cache.end()) return it->second; - } - std::ifstream f(dir + "/stubs/" + fname, std::ios::binary | std::ios::ate); - const auto code = leonida::read_spirv_words(f, f.tellg()); - VkShaderModule mod = VK_NULL_HANDLE; - if (!code.empty()) { - VkShaderModuleCreateInfo smi{VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO}; - smi.codeSize = code.size() * sizeof(code.front()); - smi.pCode = code.data(); - if (vkCreateShaderModule(dev, &smi, nullptr, &mod) != VK_SUCCESS) mod = VK_NULL_HANDLE; - } - std::lock_guard g(mu); - auto [it, inserted] = stub_cache.emplace(fname, mod); - if (!inserted && mod) vkDestroyShaderModule(dev, mod, nullptr); - return it->second; - }; - - auto record_skip = [&](const std::string& name, const std::string& stage, const std::string& reason) { - std::lock_guard g(mu); - auto& st = stats[stage]; - st.pipes_skipped++; - st.skip_reasons[reason]++; - std::printf("SKIPPED %s (%s)\n", name.c_str(), reason.c_str()); - }; - - std::FILE* stats_out = stats_path.empty() ? nullptr : std::fopen(stats_path.c_str(), "w"); - if (!stats_path.empty() && !stats_out) { std::fprintf(stderr, "cannot write %s\n", stats_path.c_str()); return 1; } - if (stats_out) std::fprintf(stats_out, "name,stage,statistic,value\n"); - // --stats: one CSV row per statistic of the executable that runs the translated shader (stage bit `bit`). - auto write_stats = [&](const std::string& name, const std::string& stage, VkShaderStageFlagBits bit, VkPipeline p) { - if (!stats_out) return; - VkPipelineInfoKHR pi{VK_STRUCTURE_TYPE_PIPELINE_INFO_KHR}; - pi.pipeline = p; - uint32_t n = 0; - vkGetPipelineExecutablePropertiesKHR(dev, &pi, &n, nullptr); - std::vector exes(n, {VK_STRUCTURE_TYPE_PIPELINE_EXECUTABLE_PROPERTIES_KHR}); - vkGetPipelineExecutablePropertiesKHR(dev, &pi, &n, exes.data()); - for (uint32_t e = 0; e < n; e++) { - if (!(exes[e].stages & bit)) continue; - VkPipelineExecutableInfoKHR ei{VK_STRUCTURE_TYPE_PIPELINE_EXECUTABLE_INFO_KHR}; - ei.pipeline = p; ei.executableIndex = e; - uint32_t m = 0; - vkGetPipelineExecutableStatisticsKHR(dev, &ei, &m, nullptr); - std::vector st(m, {VK_STRUCTURE_TYPE_PIPELINE_EXECUTABLE_STATISTIC_KHR}); - vkGetPipelineExecutableStatisticsKHR(dev, &ei, &m, st.data()); - std::lock_guard g(mu); - for (auto& x : st) { - std::fprintf(stats_out, "%s,%s,%s,", name.c_str(), stage.c_str(), x.name); - switch (x.format) { - case VK_PIPELINE_EXECUTABLE_STATISTIC_FORMAT_BOOL32_KHR: std::fprintf(stats_out, "%u\n", x.value.b32); break; - case VK_PIPELINE_EXECUTABLE_STATISTIC_FORMAT_INT64_KHR: std::fprintf(stats_out, "%lld\n", (long long)x.value.i64); break; - case VK_PIPELINE_EXECUTABLE_STATISTIC_FORMAT_UINT64_KHR: std::fprintf(stats_out, "%llu\n", (unsigned long long)x.value.u64); break; - default: std::fprintf(stats_out, "%g\n", x.value.f64); break; - } - } - } - }; - - auto record_pipe = [&](const std::string& name, const std::string& stage, uint32_t sg, bool sg_forced, - VkResult r, double sec, VkPipelineCreationFeedbackFlags fb_flags) { - std::lock_guard g(mu); - inflight.erase(std::this_thread::get_id()); - if (inflight.empty()) write_inflight(); // a large module just finished (alone with --large-parallel 1) - auto& st = stats[stage]; - st.seconds += sec; - if (sec > st.max_sec) { st.max_sec = sec; st.max_name = name; } - if (sec > slow) std::printf("SLOW %s %s (w%u, %.1fs)\n", upper_stage(stage).c_str(), name.c_str(), sg, sec); - if (sg > 0 && !sg_forced) { - if (sg == 64) st.w64_unforced++; else st.w32_unforced++; - } - if (r) { - st.pipes_bad++; - if (sg == 64) st.w64_bad++; else st.w32_bad++; - std::printf("PIPELINE FAIL %s (%s w%u, %d)\n", name.c_str(), stage.c_str(), sg, r); - } else { - st.pipes_ok++; - if (cache_feedback) st.feedback[feedback_outcome(fb_flags)]++; - if (sg == 64) st.w64_ok++; else st.w32_ok++; - } - uint32_t n_done = ++total_pipes_done; - if (n_done % 250 == 0) std::fprintf(stderr, " pipelines %u (%.0fs elapsed)\n", n_done, elapsed()); - }; - - const SimulatedCrash sim_crash = read_simulated_crash(); - auto maybe_simulate_crash = [&](const std::string& name) { // test hook, see the header - if (sim_crash.enabled && name.find(sim_crash.pattern) != std::string::npos) { - std::fprintf(stderr, "simulating signal %d before the pipeline of %s\n", sim_crash.sig, name.c_str()); - std::fflush(nullptr); -#ifdef _WIN32 - if (sim_crash.sig == SIGFPE) TerminateProcess(GetCurrentProcess(), EXCEPTION_FLT_DIVIDE_BY_ZERO); - if (sim_crash.sig == SIGSEGV) TerminateProcess(GetCurrentProcess(), EXCEPTION_ACCESS_VIOLATION); -#endif - std::raise(sim_crash.sig); - } - }; - - auto worker = [&] { - for (size_t k; (k = next++) < work.size();) { - const std::string& name = *work[k].first; - const ShaderMeta& meta = *work[k].second; - const std::string& stage = meta.stage; - if (skip_names.count(name)) { // --skip-file: it killed the driver in an earlier run - { - std::lock_guard g(mu); - auto& st = stats[stage]; - st.pipes_bad++; - st.crash_skipped++; - std::printf("MODULE CRASH %s (%s, killed the driver in an earlier run; not retried)\n", - name.c_str(), stage.c_str()); - } - ++done; - continue; - } - std::ifstream f(dir + "/" + name + ".spv", std::ios::binary | std::ios::ate); - const std::streamoff file_size = f.tellg(); - if (max_bytes && std::cmp_greater(file_size, max_bytes)) { // multi-MB ray-tracing shaders (#108) - { - std::lock_guard g(mu); - big_skipped[stage]++; - std::printf("BIG SKIP %s (%lld bytes, limit %zu)\n", - name.c_str(), static_cast(file_size), max_bytes); - } - ++done; - continue; - } - uint32_t shared_memory_limit = 0; - if (stage == "cs") shared_memory_limit = props.limits.maxComputeSharedMemorySize; - else if (stage == "ms") shared_memory_limit = mesh_props.maxMeshSharedMemorySize; - if (shared_memory_limit && meta.lds_bytes > shared_memory_limit) { - const char* limit_name = stage == "cs" ? "maxComputeSharedMemorySize" : "maxMeshSharedMemorySize"; - std::lock_guard g(mu); - modules_bad[stage]++; - std::printf("MODULE FAIL %s (workgroup memory %u bytes exceeds %s %u)\n", - name.c_str(), meta.lds_bytes, limit_name, shared_memory_limit); - ++done; - continue; - } - if (const std::string miss = check_missing_module_feature(meta); !miss.empty()) { - // No module was attempted, so only the pipeline skip is counted. - record_skip(name, stage, miss); - ++done; - continue; - } - // Enter before reading the module: creation can also enter the driver. Hold until its pipeline and - // module have been destroyed, including on failure. The watchdog and cache writer don't take this lock. - const bool isolated = large_module_bytes && std::cmp_greater(file_size, large_module_bytes); - std::unique_lock exclusive(compile_gate, std::defer_lock); - std::shared_lock parallel(compile_gate, std::defer_lock); - leonida::LargeModuleGate::Ticket large_ticket; // left after the module and its pipeline are gone - if (large_exclusive) { - if (isolated) exclusive.lock(); - else if (large_module_bytes) parallel.lock(); - } else if (isolated) { - large_ticket = leonida::LargeModuleGate::Ticket(large_gate, - leonida::large_module_estimate(file_size)); - } - { // in flight from here: vkCreateShaderModule can also take long or die in the driver - std::lock_guard g(mu); - inflight[std::this_thread::get_id()] = {name, std::chrono::steady_clock::now(), "module"}; - if (isolated) write_inflight(); // a large module: name it now (alone with --large-parallel 1) - } - - const auto code = leonida::read_spirv_words(f, file_size); - VkShaderModule sm = VK_NULL_HANDLE; - bool mod_ok = false; - if (!code.empty()) { - VkShaderModuleCreateInfo smi{VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO}; - smi.codeSize = code.size() * sizeof(code.front()); - smi.pCode = code.data(); - mod_ok = vkCreateShaderModule(dev, &smi, nullptr, &sm) == VK_SUCCESS; - } - { - std::lock_guard g(mu); - if (isolated) ++isolated_modules; - if (mod_ok) modules_ok[stage]++; - else { modules_bad[stage]++; std::printf("MODULE FAIL %s\n", name.c_str()); } - } - if (mod_ok && stage == "cs") { - const std::string miss = check_missing_feature(meta); - if (!miss.empty()) { - record_skip(name, stage, miss); - } else { - VkPipelineShaderStageRequiredSubgroupSizeCreateInfo reqSg{}; - VkComputePipelineCreateInfo cpi{VK_STRUCTURE_TYPE_COMPUTE_PIPELINE_CREATE_INFO}; - cpi.stage = {VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO}; - cpi.stage.stage = VK_SHADER_STAGE_COMPUTE_BIT; cpi.stage.module = sm; cpi.stage.pName = "main"; - bool sg_forced = false; - if (uses_runtime_compute_layout(meta)) { - const auto request = runtime_compute_subgroup(meta); - leonida::apply_subgroup_request(request, reqSg, cpi.stage); - sg_forced = request.size != 0; - cpi.layout = runtime_compute_layout; - } else { - reqSg.sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_REQUIRED_SUBGROUP_SIZE_CREATE_INFO; - reqSg.requiredSubgroupSize = meta.subgroup_size; - sg_forced = can_require_sg(meta.subgroup_size, VK_SHADER_STAGE_COMPUTE_BIT); - if (sg_forced) cpi.stage.pNext = &reqSg; - cpi.layout = layout_for(meta); - } - cpi.flags = capture; - // Only whole-pipeline feedback is reported. - VkPipelineCreationFeedback fb{}; - VkPipelineCreationFeedbackCreateInfo fci{ - VK_STRUCTURE_TYPE_PIPELINE_CREATION_FEEDBACK_CREATE_INFO, nullptr, &fb, 0, nullptr}; - if (feedback) cpi.pNext = &fci; - const auto t0 = std::chrono::steady_clock::now(); - { - std::lock_guard g(mu); - inflight[std::this_thread::get_id()] = {name, t0, "pipeline"}; - if (isolated) write_inflight(); // a large module: name it now (alone with --large-parallel 1) - } - VkPipeline p = VK_NULL_HANDLE; - maybe_simulate_crash(name); - VkResult r = vkCreateComputePipelines(dev, cache, 1, &cpi, nullptr, &p); - const double sec = std::chrono::duration(std::chrono::steady_clock::now() - t0).count(); - if (r == VK_SUCCESS) write_stats(name, stage, VK_SHADER_STAGE_COMPUTE_BIT, p); - if (r == VK_SUCCESS) vkDestroyPipeline(dev, p, nullptr); - record_pipe(name, stage, meta.subgroup_size, sg_forced, r, sec, fb.flags); - } - } else if (mod_ok && is_graphics_stage(stage)) { - const std::string miss = check_missing_feature(meta); - if (!miss.empty()) { - record_skip(name, stage, miss); - } else { - std::vector stages; - VkPipelineShaderStageRequiredSubgroupSizeCreateInfo reqSg{ - VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_REQUIRED_SUBGROUP_SIZE_CREATE_INFO}; - reqSg.requiredSubgroupSize = meta.subgroup_size; - - bool sg_forced = false; - auto make_stage = [&](VkShaderStageFlagBits bit, VkShaderModule mod, bool real) { - VkPipelineShaderStageCreateInfo si{VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO}; - si.stage = bit; si.module = mod; si.pName = "main"; - if (real && can_require_sg(meta.subgroup_size, bit)) { - si.pNext = &reqSg; - sg_forced = true; - } - return si; - }; - - std::string skip_reason; - std::vector color_formats; - VkFormat depth_format = VK_FORMAT_UNDEFINED; - bool use_vertex_input = true; - - if (stage == "ps") { - std::string vs_fn = stub_filename("vs", meta.inputs); - VkShaderModule vs_mod = load_stub(vs_fn); - if (!vs_mod) { - skip_reason = "missing stub " + vs_fn; - } else { - uint32_t n_color = 0; - for (uint32_t loc : meta.outputs) n_color = std::max(n_color, loc + 1); - if (n_color > props.limits.maxColorAttachments) { - skip_reason = "exceeds maxColorAttachments"; - } else { - color_formats.assign(n_color, VK_FORMAT_R32G32B32A32_SFLOAT); - if (meta.writes_depth) depth_format = VK_FORMAT_D32_SFLOAT; - stages.push_back(make_stage(VK_SHADER_STAGE_VERTEX_BIT, vs_mod, false)); - stages.push_back(make_stage(VK_SHADER_STAGE_FRAGMENT_BIT, sm, true)); - } - } - } else if (stage == "vs") { - std::string ps_fn = stub_filename("ps", meta.outputs); - VkShaderModule ps_mod = load_stub(ps_fn); - if (!ps_mod) { - skip_reason = "missing stub " + ps_fn; - } else { - color_formats.push_back(VK_FORMAT_R32G32B32A32_SFLOAT); - stages.push_back(make_stage(VK_SHADER_STAGE_VERTEX_BIT, sm, true)); - stages.push_back(make_stage(VK_SHADER_STAGE_FRAGMENT_BIT, ps_mod, false)); - } - } else if (stage == "ms") { - use_vertex_input = false; - std::string ps_fn = stub_filename("ps", meta.params); - VkShaderModule ps_mod = load_stub(ps_fn); - if (!ps_mod) { - skip_reason = "missing stub " + ps_fn; - } else { - color_formats.push_back(VK_FORMAT_R32G32B32A32_SFLOAT); - stages.push_back(make_stage(VK_SHADER_STAGE_MESH_BIT_EXT, sm, true)); - stages.push_back(make_stage(VK_SHADER_STAGE_FRAGMENT_BIT, ps_mod, false)); - } - } else if (stage == "gs") { - const auto& gs_in = meta.has_gs_input_locations ? meta.gs_input_locations : meta.gs_inputs; - const auto& gs_out = meta.has_gs_output_locations ? meta.gs_output_locations : meta.gs_outputs; - std::string vs_fn = stub_filename("vs", gs_in); - std::string ps_fn = stub_filename("ps", gs_out); - VkShaderModule vs_mod = load_stub(vs_fn); - VkShaderModule ps_mod = load_stub(ps_fn); - if (!vs_mod) skip_reason = "missing stub " + vs_fn; - else if (!ps_mod) skip_reason = "missing stub " + ps_fn; - else { - color_formats.push_back(VK_FORMAT_R32G32B32A32_SFLOAT); - stages.push_back(make_stage(VK_SHADER_STAGE_VERTEX_BIT, vs_mod, false)); - stages.push_back(make_stage(VK_SHADER_STAGE_GEOMETRY_BIT, sm, true)); - stages.push_back(make_stage(VK_SHADER_STAGE_FRAGMENT_BIT, ps_mod, false)); - } - } - - if (!skip_reason.empty()) { - record_skip(name, stage, skip_reason); - } else { - VkVertexInputBindingDescription vbind{0, 16, VK_VERTEX_INPUT_RATE_VERTEX}; - std::vector vattrs; - if (stage == "vs") { - for (const auto& vi : meta.vertex_inputs) { - VkFormat fmt = VK_FORMAT_R32G32B32A32_SFLOAT; - if (vi.type == "uint") fmt = VK_FORMAT_R32G32B32A32_UINT; - else if (vi.type == "sint") fmt = VK_FORMAT_R32G32B32A32_SINT; - vattrs.push_back({vi.location, 0, fmt, 0}); - } - } - VkPipelineVertexInputStateCreateInfo vi_state{VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO}; - if (!vattrs.empty()) { - vi_state.vertexBindingDescriptionCount = 1; - vi_state.pVertexBindingDescriptions = &vbind; - vi_state.vertexAttributeDescriptionCount = uint32_t(vattrs.size()); - vi_state.pVertexAttributeDescriptions = vattrs.data(); - } - VkPipelineInputAssemblyStateCreateInfo ia_state{VK_STRUCTURE_TYPE_PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO}; - ia_state.topology = VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST; - - VkPipelineViewportStateCreateInfo vp_state{VK_STRUCTURE_TYPE_PIPELINE_VIEWPORT_STATE_CREATE_INFO}; - vp_state.viewportCount = 1; - vp_state.scissorCount = 1; - VkDynamicState dyn_states[] = {VK_DYNAMIC_STATE_VIEWPORT, VK_DYNAMIC_STATE_SCISSOR}; - VkPipelineDynamicStateCreateInfo dyn_state{VK_STRUCTURE_TYPE_PIPELINE_DYNAMIC_STATE_CREATE_INFO}; - dyn_state.dynamicStateCount = 2; - dyn_state.pDynamicStates = dyn_states; - - VkPipelineRasterizationStateCreateInfo rast{VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_STATE_CREATE_INFO}; - rast.polygonMode = VK_POLYGON_MODE_FILL; - rast.cullMode = VK_CULL_MODE_NONE; - rast.frontFace = VK_FRONT_FACE_COUNTER_CLOCKWISE; - rast.lineWidth = 1.0f; - - VkPipelineMultisampleStateCreateInfo msaa{VK_STRUCTURE_TYPE_PIPELINE_MULTISAMPLE_STATE_CREATE_INFO}; - msaa.rasterizationSamples = VK_SAMPLE_COUNT_1_BIT; - - VkPipelineDepthStencilStateCreateInfo ds{VK_STRUCTURE_TYPE_PIPELINE_DEPTH_STENCIL_STATE_CREATE_INFO}; - if (depth_format != VK_FORMAT_UNDEFINED) { - ds.depthTestEnable = VK_TRUE; - ds.depthWriteEnable = VK_TRUE; - ds.depthCompareOp = VK_COMPARE_OP_LESS; - } - - std::vector blend_atts(color_formats.size()); - for (auto& ba : blend_atts) ba.colorWriteMask = 0xF; - VkPipelineColorBlendStateCreateInfo blend{VK_STRUCTURE_TYPE_PIPELINE_COLOR_BLEND_STATE_CREATE_INFO}; - blend.attachmentCount = uint32_t(blend_atts.size()); - blend.pAttachments = blend_atts.empty() ? nullptr : blend_atts.data(); - - VkPipelineRenderingCreateInfo rend{VK_STRUCTURE_TYPE_PIPELINE_RENDERING_CREATE_INFO}; - rend.colorAttachmentCount = uint32_t(color_formats.size()); - rend.pColorAttachmentFormats = color_formats.empty() ? nullptr : color_formats.data(); - rend.depthAttachmentFormat = depth_format; - - VkGraphicsPipelineCreateInfo gpci{VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO}; - gpci.pNext = &rend; - gpci.stageCount = uint32_t(stages.size()); - gpci.pStages = stages.data(); - gpci.pVertexInputState = use_vertex_input ? &vi_state : nullptr; - gpci.pInputAssemblyState = use_vertex_input ? &ia_state : nullptr; - gpci.pViewportState = &vp_state; - gpci.pRasterizationState = &rast; - gpci.pMultisampleState = &msaa; - gpci.pDepthStencilState = &ds; - gpci.pColorBlendState = &blend; - gpci.pDynamicState = &dyn_state; - gpci.layout = layout_for(meta); - gpci.renderPass = VK_NULL_HANDLE; - gpci.flags = capture; - // Zeroed per call and read after it returns; per-stage entries are required but not reported. - VkPipelineCreationFeedback fb{}; - VkPipelineCreationFeedbackCreateInfo fci{ - VK_STRUCTURE_TYPE_PIPELINE_CREATION_FEEDBACK_CREATE_INFO, &rend, &fb, 0, nullptr}; - if (feedback) gpci.pNext = &fci; // keeps rend chained behind it - - const auto t0 = std::chrono::steady_clock::now(); - { - std::lock_guard g(mu); - inflight[std::this_thread::get_id()] = {name, t0, "pipeline"}; - if (isolated) write_inflight(); // a large module: name it now (alone with --large-parallel 1) - } - VkPipeline p = VK_NULL_HANDLE; - maybe_simulate_crash(name); - VkResult r = vkCreateGraphicsPipelines(dev, cache, 1, &gpci, nullptr, &p); - const double sec = std::chrono::duration(std::chrono::steady_clock::now() - t0).count(); - if (r == VK_SUCCESS) write_stats(name, stage, stage_bit(stage), p); - if (r == VK_SUCCESS) vkDestroyPipeline(dev, p, nullptr); - record_pipe(name, stage, meta.subgroup_size, sg_forced, r, sec, fb.flags); - } - } - } else if (mod_ok) { - record_skip(name, stage, "unsupported stage " + stage); - } - if (sm) vkDestroyShaderModule(dev, sm, nullptr); - { // out of the driver on every path (a pipeline, a skip, a failed module) - std::lock_guard g(mu); - if (inflight.erase(std::this_thread::get_id()) && inflight.empty()) write_inflight(); - } - if (++done % 1000 == 0) { - std::lock_guard g(mu); - std::fprintf(stderr, " %zu/%zu (%.0fs)\n", size_t(done), work.size(), elapsed()); - } - } - }; - if (iso_child) std::printf("ISO-READY\n"); - std::fflush(stdout); - std::vector pool; - for (unsigned t = 0; t < worker_count; t++) pool.emplace_back(worker); - // Watchdog: names every compile running past 60 s (about once a minute) and saves the cache every 10 minutes. - std::condition_variable watch_cv; - bool all_done = false; - std::thread watch([&] { - auto last_save = std::chrono::steady_clock::now(); - std::unique_lock g(mu); - while (!all_done) { - if (watch_cv.wait_for(g, std::chrono::seconds(5), [&] { return all_done; })) break; - const auto now = std::chrono::steady_clock::now(); - write_inflight(); // --inflight-file: the modules compiling right now - for (auto& [tid, job] : inflight) { - const double s = std::chrono::duration(now - job.since).count(); - if (s > 60 && int(s) % 60 < 5) - std::fprintf(stderr, " still %s %s after %.0fs\n", - job.phase[0] == 'm' ? "creating the shader module of" : "compiling", - job.name.c_str(), s); - } - if (now - last_save > std::chrono::minutes(10)) { - g.unlock(); - save_cache(false); - g.lock(); - last_save = now; - } - } - }); - for (auto& t : pool) t.join(); - { - std::lock_guard g(mu); - all_done = true; - inflight.clear(); - write_inflight(); // the pass finished: nothing was compiling when the process ended - } - watch_cv.notify_one(); - watch.join(); - - for (auto& [_, mod] : stub_cache) if (mod) vkDestroyShaderModule(dev, mod, nullptr); - - const std::set all_stages = - leonida::summary_stages(modules_ok, modules_bad, stats, big_skipped); - - if (iso_child) { // --isolate child: machine-readable counts; the parent prints the summary - for (const auto& st : all_stages) { - const StageStats* s = stats.count(st) ? &stats[st] : nullptr; - uint32_t big = big_skipped.count(st) ? big_skipped[st] : 0; - std::printf("ISO-RESULT %s %u %u %u %u %u %u %u %u %u\n", st.c_str(), modules_ok[st], modules_bad[st], - s ? s->pipes_ok : 0u, s ? s->pipes_bad : 0u, s ? s->pipes_skipped : 0u, big, - s ? s->feedback[0] : 0u, s ? s->feedback[1] : 0u, s ? s->feedback[2] : 0u); - } - const bool saved = save_cache(true); - std::printf("ISO-DONE cache_ok=%d\n", saved ? 1 : 0); - std::fflush(stdout); - return saved ? 0 : 1; - } - - bool check_failed = false; - for (const auto& st : all_stages) { - std::printf("%s: %u modules ok, %u failed\n", st.c_str(), modules_ok[st], modules_bad[st]); - if (modules_bad[st]) check_failed = true; - const auto it = stats.find(st); - if (it != stats.end()) { - const auto& s = it->second; - if (s.pipes_bad) check_failed = true; - const uint32_t compiled = s.pipes_ok + s.pipes_bad; - std::printf("%s pipelines: %u ok, %u failed, %u skipped\n", - st.c_str(), s.pipes_ok, s.pipes_bad, s.pipes_skipped); - if (cache_feedback) - std::printf(" %s cache feedback: %u hits, %u no hit reported, %u unavailable\n", - st.c_str(), s.feedback[0], s.feedback[1], s.feedback[2]); - if (s.crash_skipped) - std::printf(" %s not retried after killing the driver (--skip-file): %u (counted as failed)\n", - st.c_str(), s.crash_skipped); - if (!s.skip_reasons.empty()) { - for (const auto& [reason, cnt] : s.skip_reasons) - std::printf(" %s skipped (%s): %u\n", st.c_str(), reason.c_str(), cnt); - } - if (compiled > 0) { - auto fmt_unforced = [](uint32_t cnt) -> std::string { - return cnt ? (" (" + std::to_string(cnt) + " without required subgroup size)") : ""; - }; - std::printf(" %s wave32: %u ok, %u failed%s; wave64: %u ok, %u failed%s\n", - st.c_str(), - s.w32_ok, s.w32_bad, fmt_unforced(s.w32_unforced).c_str(), - s.w64_ok, s.w64_bad, fmt_unforced(s.w64_unforced).c_str()); - std::printf(" %s compile time: %.2fs total, %.3fs mean, slowest %s (%.2fs)\n", - st.c_str(), s.seconds, s.seconds / compiled, s.max_name.c_str(), s.max_sec); - } - } - } - uint32_t big_total = 0; - for (auto& [st, c] : big_skipped) big_total += c; - if (big_total) { - std::printf("big modules skipped: %u (limit %zu bytes)", big_total, max_bytes); - for (auto& [st, c] : big_skipped) std::printf(" %s=%u", st.c_str(), c); - std::printf("; checked %zu of %zu\n", work.size() - big_total, work.size()); - } - if (isolated_modules) - std::printf("large modules checked %s: %zu (over %zu bytes)\n", - large_exclusive ? "exclusively" : "within the memory budget", isolated_modules, - large_module_bytes); - std::printf("wall time: %.1fs on %u threads\n", elapsed(), worker_count); - const bool cache_saved = save_cache(true); // keep successful pipelines even if another entry failed - if (stats_out) { - const bool write_failed = std::ferror(stats_out) != 0; - const bool close_failed = std::fclose(stats_out) != 0; - if (write_failed || close_failed) { - std::fprintf(stderr, "cannot write pipeline statistics to %s\n", stats_path.c_str()); - check_failed = true; - } - } - return (check_failed || !cache_saved) ? 1 : 0; -} diff --git a/runtime/test/vk_predicate_capture_test.cpp b/runtime/test/vk_predicate_capture_test.cpp deleted file mode 100644 index 65a1eea57..000000000 --- a/runtime/test/vk_predicate_capture_test.cpp +++ /dev/null @@ -1,162 +0,0 @@ -// Synthetic GPU lifetime test: gate the queue so no predicate arena can retire before all submissions exist. -#include "vk_test_device.h" -#include "../src/vulkan_backend.h" -#include -#include -#include -#define EXPECT(x) do { if (!(x)) { std::fprintf(stderr, "line %d: %s\n", __LINE__, #x); return 1; } } while (0) -namespace { -PFN_vkCmdPipelineBarrier2 real_barrier2 = nullptr; -unsigned host_barriers = 0; -VkPipelineStageFlags2 host_source_stages = 0; -VKAPI_ATTR void VKAPI_CALL observe_barrier2(VkCommandBuffer cb, const VkDependencyInfo* info) { - for (std::uint32_t i = 0; i < info->memoryBarrierCount; ++i) { - const auto& barrier = info->pMemoryBarriers[i]; - if (barrier.dstStageMask & VK_PIPELINE_STAGE_2_HOST_BIT) { - ++host_barriers; - host_source_stages |= barrier.srcStageMask; - } - } - real_barrier2(cb, info); -} -} -int main() { - vktest::Device d; - const auto status = d.initialize(); - if (status == vktest::DeviceStatus::unavailable) { - std::printf("vk_predicate_capture_test: no Vulkan device, skipped\n"); - return 77; - } - if (status != vktest::DeviceStatus::ready) return 1; - if (!d.conditional_rendering) { std::puts("predicate capture: skipped (no conditional rendering)"); return 0; } - using namespace leonida; - VkPhysicalDeviceMemoryProperties memory{}; - d.instance_fn("vkGetPhysicalDeviceMemoryProperties")(d.physical, &memory); - VkPhysicalDeviceProperties properties{}; - d.instance_fn("vkGetPhysicalDeviceProperties")(d.physical, &properties); - PredicateReducer limits(d.device_proc, d.device, memory, 16); - EXPECT(!limits.batch(0) && !limits.batch(2)); - PredicateReducer missing(+[](VkDevice, const char*) -> PFN_vkVoidFunction { return nullptr; }, d.device, memory, 16); - EXPECT(!missing.batch(1)); - auto no_memory = memory; no_memory.memoryTypeCount = 0; - PredicateReducer allocation_failure(d.device_proc, d.device, no_memory, 16); - EXPECT(!allocation_failure.batch(1)); - VulkanContext context(d.device_proc, d.device, true, true); - context.configure_predication(d.device_proc, memory, properties.limits.maxStorageBufferRange, d.family); - VulkanQueue queue(context, d.queue, d.family); - VulkanFence gate(context, 0); - EXPECT(context.loaded() && queue.ok() && gate.semaphore()); - constexpr unsigned count = 32; - void* mapped = nullptr; - const VkBuffer predicate = d.buffer(16, VK_BUFFER_USAGE_TRANSFER_SRC_BIT, &mapped); - EXPECT(predicate && mapped); - const std::uint64_t values[] = {UINT64_C(1) << 32, 0}; - std::memcpy(mapped, values, sizeof(values)); - const VkImage image = d.image(VK_FORMAT_R8G8B8A8_UINT, 2, 1, count, VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT); - void* pixels = nullptr; - const VkBuffer readback = d.buffer(count * 8, VK_BUFFER_USAGE_TRANSFER_DST_BIT, &pixels); - EXPECT(image && readback && pixels); - ResourceBinding source{}; source.buffer = predicate; source.size = 16; - ResourceBinding target{}; target.image = image; target.format = VK_FORMAT_R8G8B8A8_UINT; - target.width = 2; target.height = 1; target.array_layers = count; - context.add_resource(1, source); - context.add_resource(2, target, VK_IMAGE_LAYOUT_UNDEFINED); - // Each list captures high-only -> zero -> high-only with two offsets, all while no prior batch can finish. - std::array lists; - queue.wait(gate.semaphore(), 1); - bool submitted = true; - for (unsigned i = 0; i < count; ++i) { - auto& list = lists[i]; - submitted = submitted && list.set_predication({1, 0, d3d12_predication::equal_zero}); - submitted = submitted && list.clear_render_target({2, 0, i, 1}, {7, 8, 9, 10}); - submitted = submitted && list.set_predication({1, 8, d3d12_predication::equal_zero}); - submitted = submitted && list.clear_render_target({2, 0, i, 1}, {99, 99, 99, 99}); - submitted = submitted && list.set_predication({1, 0, d3d12_predication::not_equal_zero}); - submitted = submitted && list.clear_render_target({2, 0, i, 1}, {100, 100, 100, 100}); - submitted = submitted && list.set_predication({0, 0, 0}); - const Rect right{1, 0, 2, 1}; - submitted = submitted && list.clear_render_target({2, 0, i, 1}, {float(i), 31, 73, 127}, {&right, 1}); - submitted = submitted && list.close(); - const CommandList* pointer = &list; - if (!submitted || queue.execute({&pointer, 1}) != ReplayResult::success) { submitted = false; break; } - } - // Always release the gate, including on failure, so destructors cannot wait forever on queued work. - EXPECT(gate.signal(1)); - EXPECT(queue.idle()); - EXPECT(submitted); - // Completed command-buffer slots must release their old arenas before being reused. - for (auto& list : lists) { - const CommandList* pointer = &list; - EXPECT(queue.execute({&pointer, 1}) == ReplayResult::success); - } - EXPECT(queue.idle()); - // Failed submissions must not commit their speculative layout transitions. - EXPECT(context.layout(2, 0) == VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL); - CommandList failed; - EXPECT(failed.transition({2, 0, d3d12_state::render_target, d3d12_state::copy_source}) && failed.close()); - const CommandList* failed_pointer = &failed; - const auto real_submit = context.vk.vkQueueSubmit; - context.vk.vkQueueSubmit = +[](VkQueue, std::uint32_t, const VkSubmitInfo*, VkFence) -> VkResult { - return VK_ERROR_OUT_OF_HOST_MEMORY; // no GPU work and no device loss - }; - const auto failed_result = queue.execute({&failed_pointer, 1}); - context.vk.vkQueueSubmit = real_submit; - EXPECT(failed_result == ReplayResult::unsupported); - EXPECT(context.layout(2, 0) == VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL); - - // Preserve main's readback-stage collection on every logical queue kind, using real transfer readbacks. - ResourceBinding output{}; output.buffer = readback; output.size = count * 8; output.host_readable = true; - context.add_resource(3, output); - CommandList copy, capture_only, empty; - EXPECT(copy.copy_buffer({3, 0, 1, 0, 16}) && copy.close()); - EXPECT(capture_only.set_predication({1, 0, d3d12_predication::equal_zero}) && capture_only.close()); - EXPECT(empty.close()); - real_barrier2 = context.vk.vkCmdPipelineBarrier2; - EXPECT(real_barrier2); - context.vk.vkCmdPipelineBarrier2 = observe_barrier2; - for (const auto kind : {VulkanQueue::QueueKind::direct, VulkanQueue::QueueKind::compute, VulkanQueue::QueueKind::copy}) { - VulkanQueue typed(context, d.queue, d.family, kind); - EXPECT(typed.ok()); - const CommandList* no_write = ∅ - host_barriers = 0; host_source_stages = 0; - EXPECT(typed.execute({&no_write, 1}) == ReplayResult::success); - EXPECT(host_barriers == 0); - const CommandList* capture = &capture_only; - EXPECT(typed.execute({&capture, 1}) == (kind == VulkanQueue::QueueKind::copy - ? ReplayResult::unsupported : ReplayResult::success)); - EXPECT(host_barriers == 0); - const CommandList* transfer = © - EXPECT(typed.execute({&transfer, 1}) == ReplayResult::success); - EXPECT(typed.idle()); - EXPECT(host_barriers == 1 && host_source_stages != 0); - EXPECT((host_source_stages & ~VulkanQueue::queue_supported_stages(kind)) == 0); - EXPECT((host_source_stages & ~(VK_PIPELINE_STAGE_2_COPY_BIT | VK_PIPELINE_STAGE_2_TRANSFER_BIT)) == 0); - EXPECT(std::memcmp(pixels, values, sizeof(values)) == 0); - } - context.vk.vkCmdPipelineBarrier2 = real_barrier2; - EXPECT(d.run([&](VkCommandBuffer cb) { - VkImageMemoryBarrier barrier{VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER}; - barrier.srcAccessMask = VK_ACCESS_MEMORY_WRITE_BIT; barrier.dstAccessMask = VK_ACCESS_TRANSFER_READ_BIT; - barrier.oldLayout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL; barrier.newLayout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL; - barrier.srcQueueFamilyIndex = barrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; - barrier.image = image; barrier.subresourceRange = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, count}; - context.vk.vkCmdPipelineBarrier(cb, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, - 0, 0, nullptr, 0, nullptr, 1, &barrier); - VkBufferImageCopy region{}; region.imageSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, count}; - region.imageExtent = {2, 1, 1}; - context.vk.vkCmdCopyImageToBuffer(cb, image, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, readback, 1, ®ion); - VkMemoryBarrier host{VK_STRUCTURE_TYPE_MEMORY_BARRIER}; - host.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT; host.dstAccessMask = VK_ACCESS_HOST_READ_BIT; - context.vk.vkCmdPipelineBarrier(cb, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_HOST_BIT, - 0, 1, &host, 0, nullptr, 0, nullptr); - return true; - })); - const auto* bytes = static_cast(pixels); - for (unsigned i = 0; i < count; ++i) { - EXPECT(bytes[i * 8] == 7 && bytes[i * 8 + 1] == 8 && bytes[i * 8 + 2] == 9 && bytes[i * 8 + 3] == 10); - EXPECT(bytes[i * 8 + 4] == i && bytes[i * 8 + 5] == 31 && bytes[i * 8 + 6] == 73 && bytes[i * 8 + 7] == 127); - } - EXPECT(d.validation_errors() == 0); - std::puts("predicate capture: 32 gated + 32 reused submissions, 192 snapshots, offset rebinding and reset passed"); - std::puts("predicate capture integration: failed-submit tracker rollback and direct/compute/copy readback stages passed"); -} diff --git a/runtime/test/vk_predicated_copy_test.cpp b/runtime/test/vk_predicated_copy_test.cpp deleted file mode 100644 index e5e9ff587..000000000 --- a/runtime/test/vk_predicated_copy_test.cpp +++ /dev/null @@ -1,145 +0,0 @@ -// Synthetic byte-copy, forced descriptor windows and pending-submit lifetime regression. No game data. -#include "vk_test_device.h" -#include "../src/vulkan_backend.h" -#include -#include -#include -#define EXPECT(x) do { if (!(x)) { std::fprintf(stderr,"line %d: %s\n",__LINE__,#x); return 1; } } while(0) -namespace { -PFN_vkCmdPipelineBarrier2 real_barrier2 = nullptr; -unsigned host_barriers = 0; -VkPipelineStageFlags2 host_stages = 0; -VKAPI_ATTR void VKAPI_CALL observe_host(VkCommandBuffer cb, const VkDependencyInfo* info) { - for (std::uint32_t i = 0; i < info->memoryBarrierCount; ++i) { - const auto& b = info->pMemoryBarriers[i]; - if (b.dstStageMask & VK_PIPELINE_STAGE_2_HOST_BIT) { ++host_barriers; host_stages |= b.srcStageMask; } - } - real_barrier2(cb, info); -} -} -int main() { - vktest::Device d; - const auto status = d.initialize(); - if (status == vktest::DeviceStatus::unavailable) { - std::printf("vk_predicated_copy_test: no Vulkan device, skipped\n"); - return 77; - } - if (status != vktest::DeviceStatus::ready) return 1; - if(!d.conditional_rendering || !d.storage_buffer_8bit) { - std::puts("predicated copy: skipped (requires conditional rendering and storageBuffer8BitAccess)"); return 0; - } - using namespace leonida; - VkPhysicalDeviceMemoryProperties memory{}; - d.instance_fn("vkGetPhysicalDeviceMemoryProperties")(d.physical,&memory); - VkPhysicalDeviceProperties properties{}; - d.instance_fn("vkGetPhysicalDeviceProperties")(d.physical,&properties); - auto limits=properties.limits; - // Smaller advertised limits force both dispatch and descriptor-window splits on ordinary GPUs. - limits.maxStorageBufferRange=static_cast(std::max(256,limits.minStorageBufferOffsetAlignment)); - limits.maxComputeWorkGroupCount[0]=1; - VulkanContext context(d.device_proc,d.device,true,true); - context.set_occlusion_resolve_memory(memory); - context.configure_predication(d.device_proc,memory,properties.limits.maxStorageBufferRange,d.family); - VulkanQueue queue(context,d.queue,d.family); - VulkanFence gate(context,0); - EXPECT(context.loaded() && queue.ok() && gate.semaphore()); - constexpr std::size_t bytes=8207; - constexpr auto usage=VK_BUFFER_USAGE_STORAGE_BUFFER_BIT|VK_BUFFER_USAGE_TRANSFER_SRC_BIT|VK_BUFFER_USAGE_TRANSFER_DST_BIT; - void *src_data=nullptr,*dst_data=nullptr,*pred_data=nullptr; - auto src=d.buffer(bytes,usage,&src_data),dst=d.buffer(bytes,usage,&dst_data); - auto pred=d.buffer(16,usage,&pred_data); - EXPECT(src&&dst&&pred&&src_data&&dst_data&&pred_data); - std::array input{},expected{}; - for(std::size_t i=0;i(37*i+11); expected[i]=static_cast(13*i+173); } - std::memcpy(src_data,input.data(),bytes); std::memcpy(dst_data,expected.data(),bytes); - const std::uint64_t predicates[]={UINT64_C(1)<<32,0}; std::memcpy(pred_data,predicates,sizeof(predicates)); - ResourceBinding a{};a.buffer=src;a.buffer_offset=1;a.size=bytes-1; - ResourceBinding b{};b.buffer=dst;b.buffer_offset=3;b.size=bytes-3;b.host_readable=true; - ResourceBinding p{};p.buffer=pred;p.size=16; - context.add_resource(1,a);context.add_resource(2,b);context.add_resource(3,p); - // D3D-162: capture/rebind and executing/suppressed copy dispatches inside one empty statistics query. - VkQueryPool statistics = VK_NULL_HANDLE; - void* statistics_data = nullptr; - if (d.pipeline_statistics_query) { - VkQueryPoolCreateInfo info{VK_STRUCTURE_TYPE_QUERY_POOL_CREATE_INFO}; - info.queryType = VK_QUERY_TYPE_PIPELINE_STATISTICS; info.queryCount = 1; info.pipelineStatistics = 0x7ff; - EXPECT(d.fn("vkCreateQueryPool")(d.device, &info, nullptr, &statistics) == VK_SUCCESS); - context.add_query_pool(4, {statistics, d3d12_query_heap::pipeline_statistics, 1, false, {false}, {}}); - ResourceBinding counters{}; counters.size = 88; counters.host_readable = true; - counters.buffer = d.buffer(counters.size, VK_BUFFER_USAGE_TRANSFER_DST_BIT, &statistics_data); - EXPECT(counters.buffer && statistics_data); - std::memset(statistics_data, 0xcd, 88); context.add_resource(5, counters); - } - CommandList list; - if (statistics) EXPECT(list.begin_query({4,d3d12_query::pipeline_statistics,0})); - EXPECT(list.set_predication({3,0,d3d12_predication::equal_zero})); - EXPECT(list.copy_buffer({2,4,1,2,4096})); // high-word-only condition; offsets include arena prefixes - EXPECT(list.copy_buffer({2,6000,2,4,33})); // dependent, non-overlapping copy within one VkBuffer - EXPECT(list.set_predication({3,8,d3d12_predication::equal_zero})); - EXPECT(list.copy_buffer({2,0,1,0,3})); // suppressed: preserves destination prefix exactly - EXPECT(list.set_predication({3,0,d3d12_predication::not_equal_zero})); - EXPECT(list.copy_buffer({2,7000,1,0,37}));// suppressed: high word must not be truncated - EXPECT(list.set_predication({0,0,0})); - EXPECT(list.copy_buffer({2,5000,1,0,17}));// reset restores ordinary transfer path - if (statistics) { - EXPECT(list.end_query({4,d3d12_query::pipeline_statistics,0})); - EXPECT(list.resolve_queries({4,d3d12_query::pipeline_statistics,0,1,5,0})); - } - EXPECT(list.close()); - std::memcpy(expected.data()+7,input.data()+3,4096); - std::memcpy(expected.data()+6003,expected.data()+7,33); - std::memcpy(expected.data()+5003,input.data()+1,17); - const CommandList* pointer=&list; - // A device without the helper must submit nothing, rather than run a transfer unconditionally. - EXPECT(queue.execute({&pointer,1})==ReplayResult::unsupported); - EXPECT(std::memcmp(dst_data,expected.data(),bytes)!=0); // expected includes the not-yet-executed copies - for(std::size_t i=0;i(dst_data)[i]==static_cast(13*i+173)); - context.configure_predicated_copy(d.device_proc,limits); - const auto real_submit=context.vk.vkQueueSubmit; - context.vk.vkQueueSubmit=+[](VkQueue,std::uint32_t,const VkSubmitInfo*,VkFence)->VkResult{return VK_ERROR_OUT_OF_HOST_MEMORY;}; - const auto rejected=queue.execute({&pointer,1}); - context.vk.vkQueueSubmit=real_submit; - EXPECT(rejected==ReplayResult::unsupported); - for(std::size_t i=0;i(dst_data)[i]==static_cast(13*i+173)); - queue.wait(gate.semaphore(),1); - bool submitted=true; - for(unsigned i=0;i<32;++i) if(queue.execute({&pointer,1})!=ReplayResult::success){submitted=false;break;} - // Release even on preparation failure, before any destructor can wait for the queue. - EXPECT(gate.signal(1));EXPECT(queue.idle());EXPECT(submitted); - EXPECT(std::memcmp(dst_data,expected.data(),bytes)==0 && std::memcmp(src_data,input.data(),bytes)==0); - for(unsigned i=0;i<32;++i) EXPECT(queue.execute({&pointer,1})==ReplayResult::success); - EXPECT(queue.idle()); - EXPECT(std::memcmp(dst_data,expected.data(),bytes)==0 && std::memcmp(src_data,input.data(),bytes)==0); - real_barrier2=context.vk.vkCmdPipelineBarrier2; EXPECT(real_barrier2); - context.vk.vkCmdPipelineBarrier2=observe_host; - CommandList ordinary; EXPECT(ordinary.copy_buffer({2,5000,1,0,17}) && ordinary.close()); - const CommandList* plain=&ordinary; - for(auto kind:{VulkanQueue::QueueKind::direct,VulkanQueue::QueueKind::compute,VulkanQueue::QueueKind::copy}) { - VulkanQueue typed(context,d.queue,d.family,kind); EXPECT(typed.ok()); - host_barriers=0;host_stages=0; - if(kind==VulkanQueue::QueueKind::copy) { - EXPECT(typed.execute({&pointer,1})==ReplayResult::unsupported && host_barriers==0); - EXPECT(typed.execute({&plain,1})==ReplayResult::success); - EXPECT(host_stages==VK_PIPELINE_STAGE_2_COPY_BIT); - } else { - EXPECT(typed.execute({&pointer,1})==ReplayResult::success); - EXPECT(host_stages==(VK_PIPELINE_STAGE_2_COMPUTE_SHADER_BIT|VK_PIPELINE_STAGE_2_COPY_BIT| - (statistics ? VK_PIPELINE_STAGE_2_TRANSFER_BIT : 0))); - } - EXPECT(typed.idle() && host_barriers==1); - EXPECT((host_stages & ~VulkanQueue::queue_supported_stages(kind))==0); - EXPECT(std::memcmp(dst_data,expected.data(),bytes)==0); - } - context.vk.vkCmdPipelineBarrier2=real_barrier2; - if (statistics) { - for (unsigned word=0; word<11; ++word) { - std::uint64_t value=UINT64_MAX; - std::memcpy(&value, static_cast(statistics_data)+8*word, 8); - EXPECT(value==0); - } - d.fn("vkDestroyQueryPool")(d.device,statistics,nullptr); - } - EXPECT(d.validation_errors()==0); - std::puts("predicated copy integration: failed-submit cleanup and direct/compute/copy host stages passed"); - std::puts("predicated copy: 32 gated + 32 reused submissions; byte offsets, forced windows, copy dependency, rebinding/reset and untouched bytes passed"); -} diff --git a/runtime/test/vk_presenter_capture_colour.h b/runtime/test/vk_presenter_capture_colour.h deleted file mode 100644 index 399b1df5e..000000000 --- a/runtime/test/vk_presenter_capture_colour.h +++ /dev/null @@ -1,32 +0,0 @@ -#pragma once - -#include -#include -#include -#include -#include - -inline bool presenter_capture_matches_rgb(std::span pixels, std::uint32_t width, - std::uint32_t height, bool bgra, - const std::array& rgb, int tolerance) { - const std::size_t pixel_count = pixels.size() / 4; - if (width == 0 || height == 0 || pixels.size() % 4 != 0 || - pixel_count / width != height || pixel_count % width != 0) - return false; - - for (std::size_t i = 0; i < pixels.size(); i += 4) { - const int r = pixels[i + (bgra ? 2 : 0)]; - const int g = pixels[i + 1]; - const int b = pixels[i + (bgra ? 0 : 2)]; - if (std::abs(r - rgb[0]) > tolerance || std::abs(g - rgb[1]) > tolerance || - std::abs(b - rgb[2]) > tolerance) - return false; - } - return true; -} - -// The capture in step 2 of vk_presenter_sync_test should contain one uniform clear colour. -inline bool presenter_capture_matches_clear(std::span pixels, std::uint32_t width, - std::uint32_t height, bool bgra) { - return presenter_capture_matches_rgb(pixels, width, height, bgra, {51, 153, 230}, 2); -} diff --git a/runtime/test/vk_presenter_capture_colour_test.cpp b/runtime/test/vk_presenter_capture_colour_test.cpp deleted file mode 100644 index 953ad056e..000000000 --- a/runtime/test/vk_presenter_capture_colour_test.cpp +++ /dev/null @@ -1,57 +0,0 @@ -#include "vk_presenter_capture_colour.h" - -#include -#include -#include -#include - -#define EXPECT(condition) do { \ - if (!(condition)) { std::fprintf(stderr, "line %d: %s\n", __LINE__, #condition); return 1; } \ -} while (0) - -int main() { - constexpr std::uint32_t width = 5, height = 3; - for (const bool bgra : {false, true}) { - const std::array clear = bgra ? std::array{230, 153, 51, 255} - : std::array{51, 153, 230, 255}; - std::vector good; - for (std::uint32_t i = 0; i < width * height; ++i) - good.insert(good.end(), clear.begin(), clear.end()); - EXPECT(presenter_capture_matches_clear(good, width, height, bgra)); - - auto stale_edge = good; - for (std::uint32_t y = 0; y < height; ++y) { - const auto offset = (y * width + width - 1) * 4; - stale_edge[offset] = stale_edge[offset + 1] = stale_edge[offset + 2] = 0; - } - EXPECT(!presenter_capture_matches_clear(stale_edge, width, height, bgra)); - - auto drift = good; - drift[1] += 2; - EXPECT(presenter_capture_matches_clear(drift, width, height, bgra)); - ++drift[1]; - EXPECT(!presenter_capture_matches_clear(drift, width, height, bgra)); - - EXPECT(!presenter_capture_matches_clear({}, width, height, bgra)); - EXPECT(!presenter_capture_matches_clear({}, 0, 0, bgra)); - good.pop_back(); - EXPECT(!presenter_capture_matches_clear(good, width, height, bgra)); - good.resize(good.size() - 3); - EXPECT(!presenter_capture_matches_clear(good, width, height, bgra)); - - const std::array green = bgra ? std::array{102, 204, 51, 255} - : std::array{51, 204, 102, 255}; - std::vector composed; - for (std::uint32_t i = 0; i < width * height; ++i) - composed.insert(composed.end(), green.begin(), green.end()); - constexpr std::array expected_green{51, 204, 102}; - const auto edge_green = composed.size() - 3; - composed[edge_green] -= 12; - EXPECT(presenter_capture_matches_rgb(composed, width, height, bgra, expected_green, 12)); - composed[edge_green] = clear[1]; - EXPECT(!presenter_capture_matches_rgb(composed, width, height, bgra, expected_green, 12)); - composed.resize(composed.size() - 4); - EXPECT(!presenter_capture_matches_rgb(composed, width, height, bgra, expected_green, 12)); - } - return 0; -} diff --git a/runtime/test/vk_presenter_sync_test.cpp b/runtime/test/vk_presenter_sync_test.cpp deleted file mode 100644 index a54bf6662..000000000 --- a/runtime/test/vk_presenter_sync_test.cpp +++ /dev/null @@ -1,532 +0,0 @@ -// VulkanPresenter synchronization regressions (runtime/src/vulkan_present.h): -// 1. A failed vkQueueSubmit rolls back LayoutTracker changes (an UNDEFINED back buffer stays UNDEFINED until a -// present actually submits its zero-fill). -// 2. With enable_capture(), every frame's vkCmdCopyImageToBuffer into the shared capture buffer is preceded by a -// TRANSFER_WRITE -> TRANSFER_WRITE barrier to prevent WRITE_AFTER_WRITE hazards across the two in-flight frames. -// A failed capture fence wait also leaves the caller's outputs untouched. -// 3. Concurrent present() + VulkanQueue::execute() + add_resource()/remove_resource() follows VulkanContext's -// resource_mutex_ -> tracker_mutex_ -> submit_mutex_ lock hierarchy without data races or deadlocks. -// 4. A swapchain-destroy WSI layer which calls vkDeviceWaitIdle cannot overlap vkQueueSubmit on another thread. -// Skips with exit code 77 when no Vulkan 1.3 device with Win32 presentation is available. No game data. -#ifndef WIN32_LEAN_AND_MEAN -#define WIN32_LEAN_AND_MEAN -#endif -#ifndef NOMINMAX -#define NOMINMAX -#endif -#define VK_USE_PLATFORM_WIN32_KHR -#include - -#include "vk_presenter_capture_colour.h" -#include "vk_test_device.h" -#include "../src/vulkan_present.h" - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#define EXPECT(condition) do { \ - if (!(condition)) { std::fprintf(stderr, "line %d: %s\n", __LINE__, #condition); return 1; } \ -} while (0) - -namespace { - -LRESULT CALLBACK window_proc(HWND window, UINT message, WPARAM w, LPARAM l) { - return DefWindowProcW(window, message, w, l); -} - -void pump() { - MSG message; - while (PeekMessageW(&message, nullptr, 0, 0, PM_REMOVE)) { - TranslateMessage(&message); - DispatchMessageW(&message); - } -} - -namespace driver { -PFN_vkGetInstanceProcAddr real_get_instance = nullptr; -PFN_vkGetDeviceProcAddr real_get_device = nullptr; -PFN_vkQueueSubmit real_submit = nullptr; -PFN_vkQueuePresentKHR real_present = nullptr; -PFN_vkWaitForFences real_wait = nullptr; -PFN_vkCmdPipelineBarrier real_barrier = nullptr; -PFN_vkCmdCopyImageToBuffer real_copy_i2b = nullptr; -PFN_vkDestroySwapchainKHR real_destroy_swapchain = nullptr; -PFN_vkDeviceWaitIdle real_device_wait_idle = nullptr; - -std::atomic fail_next_submit{VK_SUCCESS}; -std::atomic fail_next_wait{VK_SUCCESS}; -std::function on_next_present; -std::atomic observe_capture{false}; -std::atomic saw_capture_waw{false}; -std::atomic capture_copies{0}; -std::atomic capture_waw_barriers{0}; -std::atomic check_swapchain_destroy{false}; -std::atomic destroy_entered{false}; -std::atomic submit_entered{false}; -std::atomic overlap_detected{false}; -std::atomic unexpected_submit_error{false}; -std::mutex destroy_mutex; -std::condition_variable destroy_cv; -bool allow_destroy_finish = false; - -// Synthetic WSI layer: a destroy hook initiates vkDeviceWaitIdle, as a capture layer may do internally. -// Holding the hook behind a condition variable makes the concurrency window deterministic rather than dependent -// on the installed capture software or validation logging overhead. Only the test hook waits on this condition. -VKAPI_ATTR void VKAPI_CALL destroy_swapchain(VkDevice device, VkSwapchainKHR swapchain, - const VkAllocationCallbacks* alloc) { - if (check_swapchain_destroy.load(std::memory_order_relaxed)) { - destroy_entered.store(true, std::memory_order_release); - destroy_cv.notify_all(); - { - std::unique_lock lock(destroy_mutex); - destroy_cv.wait(lock, [] { return allow_destroy_finish; }); - } - overlap_detected.store(submit_entered.load(std::memory_order_acquire), std::memory_order_release); - if (real_device_wait_idle(device) != VK_SUCCESS) unexpected_submit_error.store(true); - } - real_destroy_swapchain(device, swapchain, alloc); -} - -VKAPI_ATTR VkResult VKAPI_CALL queue_submit(VkQueue queue, std::uint32_t count, const VkSubmitInfo* submits, - VkFence fence) { - submit_entered.store(true, std::memory_order_release); - const VkResult armed = fail_next_submit.exchange(VK_SUCCESS); - if (armed != VK_SUCCESS) return armed; - return real_submit(queue, count, submits, fence); -} - -VKAPI_ATTR VkResult VKAPI_CALL queue_present(VkQueue queue, const VkPresentInfoKHR* info) { - if (on_next_present) { - auto cb = std::move(on_next_present); - on_next_present = {}; - cb(); - } - return real_present(queue, info); -} - -VKAPI_ATTR VkResult VKAPI_CALL wait_for_fences(VkDevice device, std::uint32_t count, const VkFence* fences, - VkBool32 wait_all, std::uint64_t timeout) { - const VkResult armed = fail_next_wait.exchange(VK_SUCCESS); - if (armed != VK_SUCCESS) return armed; - return real_wait(device, count, fences, wait_all, timeout); -} - -VKAPI_ATTR void VKAPI_CALL cmd_pipeline_barrier(VkCommandBuffer cb, VkPipelineStageFlags src_stage, - VkPipelineStageFlags dst_stage, VkDependencyFlags flags, - std::uint32_t mem_count, const VkMemoryBarrier* mem, - std::uint32_t buf_count, const VkBufferMemoryBarrier* buf, - std::uint32_t img_count, const VkImageMemoryBarrier* img) { - if (observe_capture.load(std::memory_order_relaxed) && (src_stage & VK_PIPELINE_STAGE_TRANSFER_BIT) && - (dst_stage & VK_PIPELINE_STAGE_TRANSFER_BIT)) { - for (std::uint32_t i = 0; i < buf_count; ++i) { - if ((buf[i].srcAccessMask & VK_ACCESS_TRANSFER_WRITE_BIT) && - (buf[i].dstAccessMask & VK_ACCESS_TRANSFER_WRITE_BIT)) - saw_capture_waw.store(true, std::memory_order_relaxed); - } - for (std::uint32_t i = 0; i < mem_count; ++i) { - if ((mem[i].srcAccessMask & VK_ACCESS_TRANSFER_WRITE_BIT) && - (mem[i].dstAccessMask & VK_ACCESS_TRANSFER_WRITE_BIT)) - saw_capture_waw.store(true, std::memory_order_relaxed); - } - } - real_barrier(cb, src_stage, dst_stage, flags, mem_count, mem, buf_count, buf, img_count, img); -} - -VKAPI_ATTR void VKAPI_CALL cmd_copy_image_to_buffer(VkCommandBuffer cb, VkImage src, VkImageLayout layout, - VkBuffer dst, std::uint32_t count, - const VkBufferImageCopy* regions) { - if (observe_capture.load(std::memory_order_relaxed)) { - capture_copies.fetch_add(1, std::memory_order_relaxed); - if (saw_capture_waw.exchange(false, std::memory_order_relaxed)) - capture_waw_barriers.fetch_add(1, std::memory_order_relaxed); - } - real_copy_i2b(cb, src, layout, dst, count, regions); -} - -VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL get_device(VkDevice device, const char* name) { - const std::string_view n = name; - if (n == "vkDestroySwapchainKHR") return reinterpret_cast(destroy_swapchain); - if (n == "vkQueueSubmit") return reinterpret_cast(queue_submit); - if (n == "vkQueuePresentKHR") return reinterpret_cast(queue_present); - if (n == "vkWaitForFences") return reinterpret_cast(wait_for_fences); - if (n == "vkCmdPipelineBarrier") return reinterpret_cast(cmd_pipeline_barrier); - if (n == "vkCmdCopyImageToBuffer") return reinterpret_cast(cmd_copy_image_to_buffer); - return real_get_device(device, name); -} - -VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL get_instance(VkInstance instance, const char* name) { - if (std::string_view(name) == "vkGetDeviceProcAddr") return reinterpret_cast(get_device); - return real_get_instance(instance, name); -} - -void install(PFN_vkGetInstanceProcAddr instance_proc, VkInstance instance, VkDevice device) { - real_get_instance = instance_proc; - real_get_device = reinterpret_cast(instance_proc(instance, "vkGetDeviceProcAddr")); - real_destroy_swapchain = reinterpret_cast(real_get_device(device, "vkDestroySwapchainKHR")); - real_device_wait_idle = reinterpret_cast(real_get_device(device, "vkDeviceWaitIdle")); - real_submit = reinterpret_cast(real_get_device(device, "vkQueueSubmit")); - real_present = reinterpret_cast(real_get_device(device, "vkQueuePresentKHR")); - real_wait = reinterpret_cast(real_get_device(device, "vkWaitForFences")); - real_barrier = reinterpret_cast(real_get_device(device, "vkCmdPipelineBarrier")); - real_copy_i2b = reinterpret_cast(real_get_device(device, "vkCmdCopyImageToBuffer")); -} -} // namespace driver - -} // namespace - -int main() { - using namespace leonida; - - vktest::Device d; - if (!d.create(true)) { - std::fprintf(stderr, "vk_presenter_sync_test: no Vulkan device with presentation, skipped\n"); - return 77; - } - - WNDCLASSW wc{}; - wc.lpfnWndProc = window_proc; - wc.hInstance = GetModuleHandleW(nullptr); - wc.lpszClassName = L"LeonidaPresenterSyncTest"; - wc.hCursor = LoadCursorW(nullptr, reinterpret_cast(IDC_ARROW)); - EXPECT(RegisterClassW(&wc)); - constexpr std::uint32_t width = 128, height = 96; - RECT fr{0, 0, LONG(width), LONG(height)}; - AdjustWindowRect(&fr, WS_OVERLAPPEDWINDOW, FALSE); - HWND window = CreateWindowExW(0, wc.lpszClassName, L"Leonida presenter sync test", WS_OVERLAPPEDWINDOW, 80, 80, - fr.right - fr.left, fr.bottom - fr.top, nullptr, nullptr, wc.hInstance, nullptr); - EXPECT(window); - ShowWindow(window, SW_SHOWNOACTIVATE); - UpdateWindow(window); - pump(); - - driver::install(d.instance_proc, d.instance, d.device); - { - VulkanContext context(driver::get_device, d.device, true); - EXPECT(context.loaded()); - VulkanQueue queue(context, d.queue, d.family); - VulkanQueue worker_queue(context, d.queue, d.family); - EXPECT(queue.ok() && worker_queue.ok()); - - const VkImage back_img = d.image(VK_FORMAT_R8G8B8A8_UNORM, width, height, 1, - VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT | - VK_IMAGE_USAGE_TRANSFER_SRC_BIT); - const VkImage side_img = d.image(VK_FORMAT_R8G8B8A8_UNORM, 32, 32, 1, - VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT | - VK_IMAGE_USAGE_TRANSFER_SRC_BIT); - EXPECT(back_img != VK_NULL_HANDLE && side_img != VK_NULL_HANDLE); - - ResourceBinding back_rb{}; - back_rb.image = back_img; - back_rb.format = VK_FORMAT_R8G8B8A8_UNORM; - back_rb.aspects = VK_IMAGE_ASPECT_COLOR_BIT; - back_rb.width = width; - back_rb.height = height; - back_rb.mip_levels = 1; - back_rb.array_layers = 1; - back_rb.depth = 1; - back_rb.samples = 1; - back_rb.color_attachment = true; - context.add_resource(1, back_rb, VK_IMAGE_LAYOUT_UNDEFINED); - - ResourceBinding side_rb = back_rb; - side_rb.image = side_img; - side_rb.width = 32; - side_rb.height = 32; - - const auto create_surface = reinterpret_cast( - d.instance_proc(d.instance, "vkCreateWin32SurfaceKHR")); - EXPECT(create_surface); - VkWin32SurfaceCreateInfoKHR surface_info{VK_STRUCTURE_TYPE_WIN32_SURFACE_CREATE_INFO_KHR}; - surface_info.hinstance = GetModuleHandleW(nullptr); - surface_info.hwnd = window; - VkSurfaceKHR surface = VK_NULL_HANDLE; - EXPECT(create_surface(d.instance, &surface_info, nullptr, &surface) == VK_SUCCESS); - - VulkanPresenter presenter(context, driver::get_instance, d.instance, d.physical, d.queue, d.family, surface); - EXPECT(presenter.ok()); - EXPECT(presenter.enable_capture()); - - // 1. Failed vkQueueSubmit must NOT commit the UNDEFINED -> GENERAL transition in LayoutTracker (O(1) rollback - // even with many live tracked textures), and tracker_mutex_ must be released before vkQueuePresentKHR. - for (ResourceId extra = 1000; extra < 1512; ++extra) - context.add_resource(extra, side_rb, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL); - EXPECT(context.layout(1, 0) == VK_IMAGE_LAYOUT_UNDEFINED); - driver::fail_next_submit.store(VK_ERROR_OUT_OF_HOST_MEMORY); - EXPECT(presenter.present(1, true) == VK_ERROR_OUT_OF_HOST_MEMORY); - EXPECT(context.layout(1, 0) == VK_IMAGE_LAYOUT_UNDEFINED); - EXPECT(context.layout(1000, 0) == VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL); - - // Next present succeeds, runs the deferred zero-fill, commits GENERAL, and unlocks tracker_mutex_ before - // vkQueuePresentKHR so other threads' emit() / layout() calls are not blocked by presentation. - std::mutex sync_mutex; - std::condition_variable sync_cv; - bool reader_started = false; - bool read_done = false; - VkImageLayout seen_during_present = VK_IMAGE_LAYOUT_UNDEFINED; - bool unblocked_during_present = false; - std::thread reader; - driver::on_next_present = [&] { - reader = std::thread([&] { - { - std::lock_guard lk(sync_mutex); - reader_started = true; - } - sync_cv.notify_all(); - const VkImageLayout layout = context.layout(1, 0); - { - std::lock_guard lk(sync_mutex); - seen_during_present = layout; - read_done = true; - } - sync_cv.notify_all(); - }); - std::unique_lock lk(sync_mutex); - const bool started = sync_cv.wait_for(lk, std::chrono::seconds(2), [&] { return reader_started; }); - unblocked_during_present = - started && sync_cv.wait_for(lk, std::chrono::milliseconds(500), [&] { return read_done; }); - }; - const VkResult present_rc = presenter.present(1, true); - if (reader.joinable()) reader.join(); - EXPECT(present_rc == VK_SUCCESS); - EXPECT(unblocked_during_present); - EXPECT(seen_during_present == VK_IMAGE_LAYOUT_GENERAL); - EXPECT(context.layout(1, 0) == VK_IMAGE_LAYOUT_GENERAL); - for (ResourceId extra = 1000; extra < 1512; ++extra) context.remove_resource(extra); - std::vector pixels{0x7f}; - VkExtent2D ext{1, 2}; - VkFormat fmt = VK_FORMAT_R8_UNORM; - driver::fail_next_wait = VK_ERROR_DEVICE_LOST; - EXPECT(!presenter.read_back(pixels, &ext, &fmt)); - EXPECT(pixels.size() == 1 && pixels[0] == 0x7f); - EXPECT(ext.width == 1 && ext.height == 2 && fmt == VK_FORMAT_R8_UNORM); - EXPECT(presenter.read_back(pixels, &ext, &fmt)); - EXPECT(pixels.size() == std::size_t(ext.width) * ext.height * 4); - const std::size_t mid = (std::size_t(ext.height / 2) * ext.width + ext.width / 2) * 4; - EXPECT(pixels[mid + 0] == 0 && pixels[mid + 1] == 0 && pixels[mid + 2] == 0); - std::printf("presenter sync: failed-submit LayoutTracker rollback ok\n"); - - // 2. Capture-buffer WAW barrier before vkCmdCopyImageToBuffer on both present() and present_blank(). - { - CommandList clear_list; - EXPECT(clear_list.transition({1, 0, d3d12_state::common, d3d12_state::render_target})); - EXPECT(clear_list.clear_render_target({1, 0, 0, 1}, {0.2f, 0.6f, 0.9f, 1.0f})); - EXPECT(clear_list.transition({1, 0, d3d12_state::render_target, d3d12_state::common})); - EXPECT(clear_list.close()); - const CommandList* ptr = &clear_list; - EXPECT(queue.execute({&ptr, 1}) == ReplayResult::success); - } - driver::saw_capture_waw.store(false); - driver::capture_copies.store(0); - driver::capture_waw_barriers.store(0); - driver::observe_capture.store(true); - EXPECT(presenter.present(1, true) == VK_SUCCESS); - EXPECT(presenter.present(1, true) == VK_SUCCESS); - EXPECT(presenter.present_blank(true) == VK_SUCCESS); - EXPECT(presenter.present(1, true) == VK_SUCCESS); - driver::observe_capture.store(false); - EXPECT(driver::capture_copies.load() == 4); - EXPECT(driver::capture_waw_barriers.load() == 4); - - EXPECT(presenter.read_back(pixels, &ext, &fmt)); - const bool bgra = (fmt == VK_FORMAT_B8G8R8A8_UNORM || fmt == VK_FORMAT_B8G8R8A8_SRGB); - EXPECT(presenter_capture_matches_clear(pixels, ext.width, ext.height, bgra)); - std::printf("presenter sync: capture-buffer WAW barriers (4/4) and full-frame read_back ok\n"); - - // 2b. A Present behind held work shows what that work draws (queue_holds.h). The render waits for a gate with - // no submitted Signal, so the queue holds it; the presents are queued behind it instead of blitting the - // back buffers as they were. Three presents queue up and keep their order: a blit, a blank one (reads - // nothing) and a composed one (present_planes), whose frame is the last one shown, so a reordering - // would end on the black frame. - { - VulkanFence gate(context, 0); - EXPECT(gate.semaphore() != VK_NULL_HANDLE); - const VkImage plane_img = d.image(VK_FORMAT_R8G8B8A8_UNORM, 32, 32, 1, - VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | VK_IMAGE_USAGE_SAMPLED_BIT); - EXPECT(plane_img != VK_NULL_HANDLE); - ResourceBinding plane_rb = side_rb; - plane_rb.image = plane_img; - plane_rb.sampled = true; - context.add_resource(2, plane_rb, VK_IMAGE_LAYOUT_UNDEFINED); - CommandList red; - EXPECT(red.transition({1, 0, d3d12_state::common, d3d12_state::render_target})); - EXPECT(red.clear_render_target({1, 0, 0, 1}, {0.9f, 0.1f, 0.2f, 1.0f})); - EXPECT(red.transition({1, 0, d3d12_state::render_target, d3d12_state::common})); - EXPECT(red.transition({2, 0, d3d12_state::common, d3d12_state::render_target})); - EXPECT(red.clear_render_target({2, 0, 0, 1}, {0.2f, 0.8f, 0.4f, 1.0f})); - EXPECT(red.transition({2, 0, d3d12_state::render_target, d3d12_state::pixel_shader_resource})); - EXPECT(red.close()); - const CommandList* ptr = &red; - queue.wait(gate.semaphore(), 1); - EXPECT(queue.execute({&ptr, 1}) == ReplayResult::success); // held - const auto capture_matches = [&](const std::array& rgb, int tolerance) { - std::vector shot; - VkExtent2D e{}; - VkFormat f{}; - if (!presenter.read_back(shot, &e, &f)) return false; - const VkExtent2D current = presenter.extent(); - if (e.width != current.width || e.height != current.height) return false; - const bool bgr = (f == VK_FORMAT_B8G8R8A8_UNORM || f == VK_FORMAT_B8G8R8A8_SRGB); - return presenter_capture_matches_rgb(shot, e.width, e.height, bgr, rgb, tolerance); - }; - const std::uint64_t shown = presenter.presented(); - PresentPlanes planes; - planes.count = 1; - planes.plane[0].source = 2; - EXPECT(presenter.present(1, true) == VK_SUCCESS); // queued: returns at once - EXPECT(presenter.present_blank(true) == VK_SUCCESS); // queued behind the one before it - EXPECT(presenter.present_planes(planes, true) == VK_SUCCESS); - EXPECT(presenter.presented() == shown && !presenter.last_present_tore()); - EXPECT(capture_matches({51, 153, 230}, 2)); - EXPECT(gate.signal(1)); // releases the render, then the presents, in order, on this thread - EXPECT(queue.idle()); - EXPECT(presenter.presented() == shown + 3 && presenter.composed_presents() >= 1); - // The composed frame (0.2, 0.8, 0.4 in the plane) is the last one shown; a blank last would be black. - EXPECT(capture_matches({51, 204, 102}, 12)); - // The blit alone, with nothing held, is the plain path again and shows the red the render drew. - EXPECT(presenter.present(1, true) == VK_SUCCESS); - EXPECT(capture_matches({230, 26, 51}, 2)); - std::printf("presenter sync: three Presents queued behind held work ran in order\n"); - context.remove_resource(2); - } - - // 2c. A queue destroyed with held work lets the Presents queued behind it run (the work is dropped). - { - VulkanFence never(context, 0); - EXPECT(never.semaphore() != VK_NULL_HANDLE); - CommandList noop; - EXPECT(noop.transition({1, 0, d3d12_state::common, d3d12_state::render_target})); - EXPECT(noop.clear_render_target({1, 0, 0, 1}, {0.0f, 0.0f, 0.0f, 1.0f})); // never replayed - EXPECT(noop.transition({1, 0, d3d12_state::render_target, d3d12_state::common})); - EXPECT(noop.close()); - const CommandList* ptr = &noop; - const std::uint64_t shown = presenter.presented(); - { - VulkanQueue doomed(context, d.queue, d.family); - EXPECT(doomed.ok()); - doomed.wait(never.semaphore(), 1); - EXPECT(doomed.execute({&ptr, 1}) == ReplayResult::success); // held for good - EXPECT(presenter.present(1, true) == VK_SUCCESS); // queued behind it - EXPECT(presenter.presented() == shown); - } - EXPECT(presenter.presented() == shown + 1); - std::printf("presenter sync: Present queued behind a destroyed queue's held work ran\n"); - } - - // 3. Concurrent present() + VulkanQueue::execute() + add/remove_resource() hammering LayoutTracker. - std::atomic stop{false}; - std::atomic worker_failed{false}; - // The worker is paced: VulkanQueue::execute() has no back-pressure (it allocates a new command buffer whenever - // none has finished), so an unthrottled loop queues thousands of submissions on the shared VkQueue and - // present()'s frame fence is signalled only after all of them drain, while the worker keeps contending for - // submit_mutex_ and tracker_mutex_ at full CPU. A slow GPU (an iGPU, or several processes sharing one) then - // leaves present() stuck for tens of seconds. Draining every few rounds keeps the interleaving, not the backlog. - constexpr std::uint64_t drain_every = 8; - std::thread worker([&] { - std::uint64_t round = 0; - while (!stop.load(std::memory_order_relaxed)) { - const ResourceId base = 100 + (round % 8) * 32; - for (ResourceId i = 0; i < 32; ++i) - context.add_resource(base + i, side_rb, VK_IMAGE_LAYOUT_UNDEFINED); - CommandList list; - if (!list.clear_render_target({base, 0, 0, 1}, {0.1f, 0.2f, 0.3f, 1.0f}) || !list.close()) { - worker_failed.store(true); - break; - } - const CommandList* ptr = &list; - if (worker_queue.execute({&ptr, 1}) != ReplayResult::success) { - worker_failed.store(true); - break; - } - (void)context.layout(base, 0); - for (ResourceId i = 0; i < 32; ++i) context.remove_resource(base + i); - if (++round % drain_every == 0 && !worker_queue.idle()) { - worker_failed.store(true); - break; - } - } - }); - - VkResult present_err = VK_SUCCESS; - for (int i = 0; i < 40; ++i) { - pump(); - present_err = presenter.present(1, false); - if (present_err != VK_SUCCESS) break; - } - stop.store(true, std::memory_order_relaxed); - worker.join(); - EXPECT(present_err == VK_SUCCESS); - EXPECT(!worker_failed.load()); - EXPECT(queue.idle() && worker_queue.idle()); - std::printf("presenter sync: concurrent present + queue.execute + tracker mutations ok\n"); - - // 4. Emulate a WSI capture layer that performs device-idle inside vkDestroySwapchainKHR. - // The presenter first enters the destroy hook; a second thread then attempts a real queue submission. - // Once the hook is released, that submission must not have entered the Vulkan driver while the hook ran. - driver::destroy_entered.store(false); - driver::submit_entered.store(false); - driver::overlap_detected.store(false); - driver::unexpected_submit_error.store(false); - { - std::lock_guard lock(driver::destroy_mutex); - driver::allow_destroy_finish = false; - } - driver::check_swapchain_destroy.store(true); - VkResult recreated = VK_ERROR_UNKNOWN; - std::thread destroy_thread([&] { recreated = presenter.present(1, true); }); - bool entered = false; - { - std::unique_lock lock(driver::destroy_mutex); - entered = driver::destroy_cv.wait_for(lock, std::chrono::seconds(5), - [] { return driver::destroy_entered.load(); }); - } - std::atomic submit_started{false}; - ReplayResult submit_result = ReplayResult::unsupported; - std::thread submit_thread; - if (entered) { - submit_thread = std::thread([&] { - submit_started.store(true); - CommandList list; - if (!list.clear_render_target({1, 0, 0, 1}, {0.3f, 0.2f, 0.1f, 1.0f}) || !list.close()) return; - const CommandList* ptr = &list; - submit_result = worker_queue.execute({&ptr, 1}); - }); - for (int attempt = 0; attempt < 100 && !submit_started.load(); ++attempt) - std::this_thread::sleep_for(std::chrono::milliseconds(1)); - // Give the competing thread time to reach the submit point if no mutex is protecting destruction. - std::this_thread::sleep_for(std::chrono::milliseconds(50)); - } - { - std::lock_guard lock(driver::destroy_mutex); - driver::allow_destroy_finish = true; - } - driver::destroy_cv.notify_all(); - destroy_thread.join(); - if (submit_thread.joinable()) submit_thread.join(); - driver::check_swapchain_destroy.store(false); - EXPECT(entered); - EXPECT(recreated == VK_SUCCESS); - EXPECT(submit_started.load()); - EXPECT(submit_result == ReplayResult::success); - EXPECT(!driver::overlap_detected.load()); - EXPECT(!driver::unexpected_submit_error.load()); - EXPECT(queue.idle() && worker_queue.idle()); - std::printf("presenter sync: synthetic WSI device-idle during swapchain destruction serialized ok\n"); - } - - DestroyWindow(window); - UnregisterClassW(wc.lpszClassName, wc.hInstance); - - EXPECT(d.validation_errors() == 0); - std::printf("vk_presenter_sync_test: ok\n"); - return 0; -} diff --git a/runtime/test/vk_ps_sweep.cpp b/runtime/test/vk_ps_sweep.cpp deleted file mode 100644 index dc256030d..000000000 --- a/runtime/test/vk_ps_sweep.cpp +++ /dev/null @@ -1,813 +0,0 @@ -// Draws one translated pixel shader with the runtime's bindless set 0 and a host heap, on whichever GPU the loader -// gives it, and writes every colour target as raw RGBA32F. It is the per-shader worker of a corpus sweep: the -// vertex shader is a generated one that outputs vec4 varyings for the pixel shader's input locations -// (tools/ps_sweep.py), so any pixel shader can be drawn without its real vertex stage. -// -// vk_ps_sweep -// -// Inputs follow the contract in docs/design.md and are identical on every device: -// set 0 the BindlessSet of runtime/src/vulkan_bindless.h with only its fallbacks: an empty descriptor -// table, so every T# and S# the shader reads resolves to index 0 (a zero image, a nearest sampler) -// VKS_TEX=1 replaces the fallback (index 0) sampled images and sampler with an 8x8 gradient (r = x/8, g = y/8, -// b = 0.25 + 0.15 * z or layer, a = 1) in every sampled dimension (2D, 2D array of 6, 1D, 3D of -// depth 4) and a linear clamping sampler, so a shader whose T# and S# miss the table (a zeroed heap) -// samples texels; the storage bindings keep their 1x1 fallbacks -// VKS_TEX=sint|uint selects an RGBA8 integer view at 2D element zero for bounded constant texelFetch. -// --screen-integer checks applicability without initializing Vulkan. -// VKS_GS= -// a geometry shader between the two (tools/bary_fallback_gs.py's pass-through GS for a pixel shader -// translated with --bary-fallback: it writes the barycentric input that shader reads); needs the -// geometryShader feature -// push s0..s31 from VKS_SGPRS (like VKH_SGPRS), then the heap base -// heap VKS_HEAP_KB KiB (default 1024), zero unless VKS_HEAP_FILL=,, fills a range with -// floats in [0.25, 1) -// Output: the targets back to back, each width * height * 16 bytes, cleared to -1 so a pixel that was never -// written stays clear. --depth also writes .depth, one D32_SFLOAT word per pixel, cleared to 1. -// It enables precise occlusion counting, depth test ALWAYS, depth writes, and no stencil or depth bounds test. -// -// Exit codes: 0 drawn; 77 the device lacks a feature the module needs (stdout says which); 1 a Vulkan call failed -// (stderr says which); 3 the fence did not signal in VKS_TIMEOUT_S seconds (default 20); 4 the device was lost. -#define VK_NO_PROTOTYPES -#include "vulkan_loader.h" -#include "vk_device_pick.h" -#include "ps_sweep_integer_fetch.h" -#include "vk_shader_fma.h" -#include "../src/vulkan_bindless.h" - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -static PFN_vkGetInstanceProcAddr gipa; -#define CHECK(x) \ - do { \ - VkResult r_ = (x); \ - if (r_ == VK_ERROR_DEVICE_LOST) { \ - std::fprintf(stderr, "DEVICE_LOST %s (line %d)\n", #x, __LINE__); \ - return 4; \ - } \ - if (r_ != VK_SUCCESS) { \ - std::fprintf(stderr, "FAILED %s -> %d (line %d)\n", #x, int(r_), __LINE__); \ - return 1; \ - } \ - } while (0) - -static std::vector read_spv(const char* path) { - std::ifstream f(path, std::ios::binary); - std::vector b((std::istreambuf_iterator(f)), {}); - if (b.empty() || b.size() % 4) return {}; - std::vector w(b.size() / 4); - std::memcpy(w.data(), b.data(), w.size() * 4); - return w; -} - -static std::vector capabilities(const std::vector& code) { - std::vector caps; - for (std::size_t i = 5; i + 1 < code.size();) { - const uint32_t words = code[i] >> 16, op = code[i] & 0xffffu; - if (!words) break; - if (op == 17) caps.push_back(code[i + 1]); - i += words; - } - return caps; -} - -// VKS_MAX_RECONV=1: add SPV_KHR_maximal_reconvergence and OpExecutionMode MaximallyReconvergesKHR to the module. -static void add_maximal_reconvergence(std::vector& code) { - std::size_t ext_at = 0, mode_at = 0; - uint32_t entry = 0; - for (std::size_t i = 5; i < code.size();) { - const uint32_t words = code[i] >> 16, op = code[i] & 0xffffu; - if (!words) break; - if (!ext_at && (op == 11 || op == 14)) ext_at = i; // first OpExtInstImport / OpMemoryModel - if (op == 15) { entry = code[i + 2]; mode_at = i + words; } - i += words; - } - if (!ext_at || !mode_at) return; - const char ext[] = "SPV_KHR_maximal_reconvergence"; - std::vector name((sizeof(ext) + 3) / 4, 0); - std::memcpy(name.data(), ext, sizeof(ext)); - std::vector ins_ext{uint32_t((1 + name.size()) << 16 | 10)}; - ins_ext.insert(ins_ext.end(), name.begin(), name.end()); - const std::vector ins_mode{3u << 16 | 16u, entry, 6023u}; // MaximallyReconvergesKHR - code.insert(code.begin() + std::ptrdiff_t(mode_at), ins_mode.begin(), ins_mode.end()); // later position first - code.insert(code.begin() + std::ptrdiff_t(ext_at), ins_ext.begin(), ins_ext.end()); -} - -static bool parse_words(const char* s, uint32_t* out, uint32_t max) { - for (uint32_t i = 0; *s; ++i) { - if (i == max) return false; - char* end; - out[i] = uint32_t(std::strtoull(s, &end, 0)); - if (end == s) return false; - s = end; - if (*s == ',') ++s; - } - return true; -} - -static double now_s() { - using namespace std::chrono; - return duration(steady_clock::now().time_since_epoch()).count(); -} - -int main(int argc, char** argv) { - const double t_start = now_s(); - bool depth = false, occlusion = false; - float depth_clear = 1.0f; - if (argc == 3 && std::strcmp(argv[1], "--screen-integer") == 0) { - const char* kind = integer_fetch_type(read_spv(argv[2])); - std::puts(kind ? kind : "unsupported"); - return kind ? 0 : 77; - } - if (argc < 7) { - std::fprintf(stderr, "usage: vk_ps_sweep vs.spv ps.spv out.raw width height render-targets [--occlusion] [--depth | --depth-zero]\n"); - return 2; - } - for (int i = 7; i < argc; ++i) { - if (std::strcmp(argv[i], "--occlusion") == 0) occlusion = true; - else if (std::strcmp(argv[i], "--depth") == 0) depth = true; - else if (std::strcmp(argv[i], "--depth-zero") == 0) { - depth = true; - depth_clear = 0.0f; - } else return 2; - } - // Count surviving samples even when their depth equals the attachment clear. - occlusion |= depth; - const uint32_t W = uint32_t(std::atoi(argv[4])), H = uint32_t(std::atoi(argv[5])); - const uint32_t targets = uint32_t(std::atoi(argv[6])); - if (!W || !H || targets < 1 || targets > 8) return 2; - uint32_t pc[36] = {}; - if (const char* s = std::getenv("VKS_SGPRS"); s && !parse_words(s, pc, 32)) { - std::fprintf(stderr, "VKS_SGPRS: expected up to 32 comma-separated words\n"); - return 2; - } - const char* heap_kb_env = std::getenv("VKS_HEAP_KB"); - const uint64_t heap_bytes = (heap_kb_env && std::atoi(heap_kb_env) > 0 ? uint64_t(std::atoi(heap_kb_env)) : 1024u) << 10; - uint32_t fill[3] = {}; // offset, bytes, seed - bool fill_heap = false; - if (const char* s = std::getenv("VKS_HEAP_FILL"); s && *s) { - if (!parse_words(s, fill, 3) || fill[0] % 4 || fill[1] % 4 || uint64_t(fill[0]) + fill[1] > heap_bytes) { - std::fprintf(stderr, "VKS_HEAP_FILL: expected offset,bytes,seed inside the heap\n"); - return 2; - } - fill_heap = true; - } - const char* timeout_env = std::getenv("VKS_TIMEOUT_S"); - const uint64_t timeout_ns = (timeout_env && std::atoi(timeout_env) > 0 ? uint64_t(std::atoi(timeout_env)) : 20u) * 1000000000ull; - - auto fs_code = read_spv(argv[2]); - const char* tex_mode = std::getenv("VKS_TEX"); - const bool integer_tex = tex_mode && (!std::strcmp(tex_mode, "sint") || !std::strcmp(tex_mode, "uint")); - if (integer_tex) { - const char* kind = integer_fetch_type(fs_code); - if (!kind || std::strcmp(kind, tex_mode) || std::getenv("VKS_GS") || std::getenv("VKS_TEX_CONST")) { - std::puts("unsupported: integer texture needs a matching bounded 2D fetch and fixed fixture inputs"); - return 77; - } - } - gipa = load_vulkan(); - if (!gipa) return 1; - VkInstance inst = VK_NULL_HANDLE; -#define LOADI(name) auto name = reinterpret_cast(gipa(inst, #name)) - LOADI(vkCreateInstance); - VkApplicationInfo app{VK_STRUCTURE_TYPE_APPLICATION_INFO}; - app.apiVersion = VK_API_VERSION_1_3; - VkInstanceCreateInfo ici{VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO}; - ici.pApplicationInfo = &app; - CHECK(vkCreateInstance(&ici, nullptr, &inst)); - LOADI(vkEnumeratePhysicalDevices); LOADI(vkGetPhysicalDeviceProperties); LOADI(vkGetPhysicalDeviceProperties2); - LOADI(vkGetPhysicalDeviceFeatures2); LOADI(vkGetPhysicalDeviceQueueFamilyProperties); - LOADI(vkGetPhysicalDeviceMemoryProperties); LOADI(vkCreateDevice); LOADI(vkGetDeviceProcAddr); - LOADI(vkEnumerateDeviceExtensionProperties); - uint32_t n = 0; - vkEnumeratePhysicalDevices(inst, &n, nullptr); - std::vector pds(n); - vkEnumeratePhysicalDevices(inst, &n, pds.data()); - std::vector candidates(pds.size()); - for (std::size_t i = 0; i < pds.size(); ++i) vkGetPhysicalDeviceProperties(pds[i], &candidates[i]); - const std::size_t chosen = leonida::vk_test::pick_device(candidates); - if (chosen >= pds.size()) { - leonida::vk_test::report_no_device(); - return 1; - } - VkPhysicalDevice pd = pds[chosen]; - VkPhysicalDeviceVulkan11Properties props11{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_1_PROPERTIES}; - VkPhysicalDeviceVulkan12Properties props12{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_2_PROPERTIES}; - props11.pNext = &props12; - VkPhysicalDeviceProperties2 props{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROPERTIES_2, &props11}; - vkGetPhysicalDeviceProperties2(pd, &props); - std::fprintf(stderr, "device: %s\n", props.properties.deviceName); - constexpr uint32_t pc_bytes = 144; - if (props.properties.limits.maxPushConstantsSize < pc_bytes) { - std::printf("unsupported: push constants %u bytes\n", props.properties.limits.maxPushConstantsSize); - return 77; - } - uint32_t qn = 0; - vkGetPhysicalDeviceQueueFamilyProperties(pd, &qn, nullptr); - std::vector qf(qn); - vkGetPhysicalDeviceQueueFamilyProperties(pd, &qn, qf.data()); - uint32_t qi = 0; - while (qi < qn && !(qf[qi].queueFlags & VK_QUEUE_GRAPHICS_BIT)) qi++; - if (qi == qn) return 1; - - uint32_t en = 0; - vkEnumerateDeviceExtensionProperties(pd, nullptr, &en, nullptr); - std::vector exts(en); - vkEnumerateDeviceExtensionProperties(pd, nullptr, &en, exts.data()); - auto has_ext = [&](const char* e) { - for (auto& x : exts) if (!std::strcmp(x.extensionName, e)) return true; - return false; - }; - - // What the pixel shader declares, against what the device has. - const bool max_reconv = std::getenv("VKS_MAX_RECONV") != nullptr; - if (max_reconv && fs_code.size() >= 6) add_maximal_reconvergence(fs_code); - if (fs_code.size() < 6) { - std::fprintf(stderr, "cannot read %s\n", argv[2]); - return 1; - } - VkPhysicalDeviceFragmentShaderBarycentricFeaturesKHR bary_have{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FRAGMENT_SHADER_BARYCENTRIC_FEATURES_KHR}; - VkPhysicalDeviceFragmentShaderInterlockFeaturesEXT lock_have{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FRAGMENT_SHADER_INTERLOCK_FEATURES_EXT}; - VkPhysicalDeviceVulkan12Features have12{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_2_FEATURES}; - VkPhysicalDeviceFeatures2 have{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2}; - have.pNext = &have12; - have12.pNext = &lock_have; - lock_have.pNext = &bary_have; - vkGetPhysicalDeviceFeatures2(pd, &have); - VkPhysicalDeviceSubgroupProperties sub{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SUBGROUP_PROPERTIES}; - VkPhysicalDeviceProperties2 sub2{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROPERTIES_2, &sub}; - vkGetPhysicalDeviceProperties2(pd, &sub2); - - std::string missing; - auto need = [&](bool ok, const char* what) { - if (ok) return; - if (!missing.empty()) missing += ", "; - missing += what; - }; - VkPhysicalDeviceFeatures2 enable{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2}; - if (occlusion) { - need(have.features.occlusionQueryPrecise, "occlusionQueryPrecise"); - enable.features.occlusionQueryPrecise = VK_TRUE; - } - VkPhysicalDeviceVulkan12Features en12{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_2_FEATURES}; - VkPhysicalDeviceFragmentShaderBarycentricFeaturesKHR bary{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FRAGMENT_SHADER_BARYCENTRIC_FEATURES_KHR}; - VkPhysicalDeviceFragmentShaderInterlockFeaturesEXT lock{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FRAGMENT_SHADER_INTERLOCK_FEATURES_EXT}; - std::vector enable_exts; - uint32_t subgroup_ops = 0; - for (const uint32_t cap : capabilities(fs_code)) { - switch (cap) { - case 10: need(have.features.shaderFloat64, "shaderFloat64"); enable.features.shaderFloat64 = VK_TRUE; break; - case 11: need(have.features.shaderInt64, "shaderInt64"); enable.features.shaderInt64 = VK_TRUE; break; - case 42: need(have.features.shaderResourceMinLod, "shaderResourceMinLod"); enable.features.shaderResourceMinLod = VK_TRUE; break; - case 50: need(have.features.shaderImageGatherExtended, "shaderImageGatherExtended"); enable.features.shaderImageGatherExtended = VK_TRUE; break; - case 55: need(have.features.shaderStorageImageReadWithoutFormat, "shaderStorageImageReadWithoutFormat"); enable.features.shaderStorageImageReadWithoutFormat = VK_TRUE; break; - case 56: need(have.features.shaderStorageImageWriteWithoutFormat, "shaderStorageImageWriteWithoutFormat"); enable.features.shaderStorageImageWriteWithoutFormat = VK_TRUE; break; - case 61: subgroup_ops |= VK_SUBGROUP_FEATURE_BASIC_BIT; break; - case 62: subgroup_ops |= VK_SUBGROUP_FEATURE_VOTE_BIT; break; - case 63: subgroup_ops |= VK_SUBGROUP_FEATURE_ARITHMETIC_BIT; break; - case 64: subgroup_ops |= VK_SUBGROUP_FEATURE_BALLOT_BIT; break; - case 65: subgroup_ops |= VK_SUBGROUP_FEATURE_SHUFFLE_BIT; break; - case 66: subgroup_ops |= VK_SUBGROUP_FEATURE_SHUFFLE_RELATIVE_BIT; break; - case 67: subgroup_ops |= VK_SUBGROUP_FEATURE_CLUSTERED_BIT; break; - case 68: subgroup_ops |= VK_SUBGROUP_FEATURE_QUAD_BIT; break; - case 5284: // FragmentBarycentricKHR - need(has_ext(VK_KHR_FRAGMENT_SHADER_BARYCENTRIC_EXTENSION_NAME) && bary_have.fragmentShaderBarycentric, - "fragmentShaderBarycentric"); - break; - case 5378: // FragmentShaderPixelInterlockEXT - need(has_ext(VK_EXT_FRAGMENT_SHADER_INTERLOCK_EXTENSION_NAME) && lock_have.fragmentShaderPixelInterlock, - "fragmentShaderPixelInterlock"); - break; - } - } - const char* gs_path = std::getenv("VKS_GS"); - std::vector gs_code; - if (gs_path && *gs_path) { - gs_code = read_spv(gs_path); - if (gs_code.size() < 6) { - std::fprintf(stderr, "cannot read %s\n", gs_path); - return 1; - } - need(have.features.geometryShader, "geometryShader"); - enable.features.geometryShader = VK_TRUE; - } - if (std::getenv("VKS_NEED_MAINTENANCE8")) need(has_ext("VK_KHR_maintenance8"), "maintenance8"); - if (subgroup_ops) { - need((sub.supportedStages & VK_SHADER_STAGE_FRAGMENT_BIT) != 0, "subgroup operations in fragment shaders"); - need((sub.supportedOperations & subgroup_ops) == subgroup_ops, "a subgroup operation class"); - } - leonida::vk_test::ShaderFma fma; - fma.query(gipa, inst, pd); - if (!fma.accepts(fs_code.data(), fs_code.size() * 4, argv[2])) return 77; - need(have12.bufferDeviceAddress && have12.runtimeDescriptorArray, "bufferDeviceAddress or runtimeDescriptorArray"); - need(have.features.shaderInt64 && have.features.fragmentStoresAndAtomics && - have.features.shaderSampledImageArrayDynamicIndexing, - "shaderInt64, fragmentStoresAndAtomics or shaderSampledImageArrayDynamicIndexing"); - if (!missing.empty()) { - std::printf("unsupported: %s\n", missing.c_str()); - return 77; - } - enable.features.shaderInt64 = VK_TRUE; - enable.features.fragmentStoresAndAtomics = VK_TRUE; - enable.features.shaderSampledImageArrayDynamicIndexing = VK_TRUE; - enable.features.shaderStorageImageArrayDynamicIndexing = have.features.shaderStorageImageArrayDynamicIndexing; - // Optional extras the sweep leaves on when present, so a shader sees the same device state a runtime would give it. - if (has_ext(VK_KHR_FRAGMENT_SHADER_BARYCENTRIC_EXTENSION_NAME) && bary_have.fragmentShaderBarycentric) { - enable_exts.push_back(VK_KHR_FRAGMENT_SHADER_BARYCENTRIC_EXTENSION_NAME); - bary.fragmentShaderBarycentric = VK_TRUE; - } - if (has_ext(VK_EXT_FRAGMENT_SHADER_INTERLOCK_EXTENSION_NAME) && lock_have.fragmentShaderPixelInterlock) { - enable_exts.push_back(VK_EXT_FRAGMENT_SHADER_INTERLOCK_EXTENSION_NAME); - lock.fragmentShaderPixelInterlock = VK_TRUE; - } -#ifdef VK_KHR_MAINTENANCE_8_EXTENSION_NAME - VkPhysicalDeviceMaintenance8FeaturesKHR m8{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MAINTENANCE_8_FEATURES_KHR}; - const bool m8_on = has_ext(VK_KHR_MAINTENANCE_8_EXTENSION_NAME); - if (m8_on) { - enable_exts.push_back(VK_KHR_MAINTENANCE_8_EXTENSION_NAME); - m8.maintenance8 = VK_TRUE; - } -#else - const bool m8_on = false; -#endif - if (fma.supported()) enable_exts.push_back(fma.extension()); -#ifdef VK_KHR_SHADER_MAXIMAL_RECONVERGENCE_EXTENSION_NAME - VkPhysicalDeviceShaderMaximalReconvergenceFeaturesKHR mr{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADER_MAXIMAL_RECONVERGENCE_FEATURES_KHR}; - if (max_reconv) { - if (!has_ext(VK_KHR_SHADER_MAXIMAL_RECONVERGENCE_EXTENSION_NAME)) { - std::printf("unsupported: shaderMaximalReconvergence\n"); - return 77; - } - enable_exts.push_back(VK_KHR_SHADER_MAXIMAL_RECONVERGENCE_EXTENSION_NAME); - mr.shaderMaximalReconvergence = VK_TRUE; - } -#endif - leonida::BindlessFeatures flags{ - have12.descriptorBindingSampledImageUpdateAfterBind && have12.descriptorBindingStorageImageUpdateAfterBind && - have12.descriptorBindingStorageBufferUpdateAfterBind, - have12.descriptorBindingPartiallyBound == VK_TRUE}; - en12.descriptorIndexing = have12.descriptorIndexing; - en12.descriptorBindingSampledImageUpdateAfterBind = flags.update_after_bind; - en12.descriptorBindingStorageImageUpdateAfterBind = flags.update_after_bind; - en12.descriptorBindingStorageBufferUpdateAfterBind = flags.update_after_bind; - en12.descriptorBindingPartiallyBound = flags.partially_bound; - en12.runtimeDescriptorArray = VK_TRUE; - en12.bufferDeviceAddress = VK_TRUE; - // pNext chain: features2 -> vulkan12 -> [barycentric] -> [interlock] -> [maintenance8] -> [fma] - void** tail = &en12.pNext; - if (bary.fragmentShaderBarycentric) { *tail = &bary; tail = &bary.pNext; } - if (lock.fragmentShaderPixelInterlock) { *tail = &lock; tail = &lock.pNext; } -#ifdef VK_KHR_MAINTENANCE_8_EXTENSION_NAME - if (m8_on) { *tail = &m8; tail = &m8.pNext; } -#endif -#ifdef VK_KHR_SHADER_MAXIMAL_RECONVERGENCE_EXTENSION_NAME - if (max_reconv) { *tail = &mr; tail = &mr.pNext; } -#endif -#ifdef VK_KHR_SHADER_FMA_EXTENSION_NAME - if (fma.supported()) { *tail = &fma.features; tail = &fma.features.pNext; } -#endif - *tail = nullptr; - enable.pNext = &en12; - - float prio = 1; - VkDeviceQueueCreateInfo qci{VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO}; - qci.queueFamilyIndex = qi; qci.queueCount = 1; qci.pQueuePriorities = &prio; - VkDeviceCreateInfo dci{VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO}; - dci.pNext = &enable; - dci.queueCreateInfoCount = 1; dci.pQueueCreateInfos = &qci; - dci.enabledExtensionCount = uint32_t(enable_exts.size()); dci.ppEnabledExtensionNames = enable_exts.data(); - VkDevice dev; - CHECK(vkCreateDevice(pd, &dci, nullptr, &dev)); -#define LOADD(name) auto name = reinterpret_cast(vkGetDeviceProcAddr(dev, #name)) - LOADD(vkGetDeviceQueue); LOADD(vkCreateImage); LOADD(vkGetImageMemoryRequirements); LOADD(vkAllocateMemory); - LOADD(vkBindImageMemory); LOADD(vkCreateImageView); LOADD(vkCreateRenderPass); LOADD(vkCreateFramebuffer); - LOADD(vkCreateShaderModule); LOADD(vkCreatePipelineLayout); LOADD(vkCreateGraphicsPipelines); - LOADD(vkCreateCommandPool); LOADD(vkAllocateCommandBuffers); LOADD(vkBeginCommandBuffer); - LOADD(vkCmdBeginRenderPass); LOADD(vkCmdBindPipeline); LOADD(vkCmdDraw); LOADD(vkCmdEndRenderPass); - LOADD(vkCmdCopyImageToBuffer); LOADD(vkEndCommandBuffer); LOADD(vkQueueSubmit); LOADD(vkCreateBuffer); - LOADD(vkGetBufferMemoryRequirements); LOADD(vkBindBufferMemory); LOADD(vkMapMemory); - LOADD(vkGetBufferDeviceAddress); LOADD(vkCmdBindDescriptorSets); LOADD(vkCmdPushConstants); - LOADD(vkCreateFence); LOADD(vkWaitForFences); - VkQueue q; - vkGetDeviceQueue(dev, qi, 0, &q); - VkPhysicalDeviceMemoryProperties mp; - vkGetPhysicalDeviceMemoryProperties(pd, &mp); - auto memtype = [&](uint32_t bits, VkMemoryPropertyFlags want) { - for (uint32_t i = 0; i < mp.memoryTypeCount; i++) - if ((bits & (1u << i)) && (mp.memoryTypes[i].propertyFlags & want) == want) return i; - return 0u; - }; - - const double t_device = now_s(); - // Set 0. - constexpr uint32_t sampled_total = 4096 + 1024 + 256 + 256, sampler_total = 1024, storage_total = 1024 + 13 * 256; - const auto fits = [&](const leonida::BindlessFeatures& f) { - const VkPhysicalDeviceLimits& l = props.properties.limits; - if (f.update_after_bind) - return props12.maxPerStageDescriptorUpdateAfterBindSampledImages >= sampled_total && - props12.maxPerStageDescriptorUpdateAfterBindSamplers >= sampler_total && - props12.maxPerStageDescriptorUpdateAfterBindStorageImages >= storage_total && - props12.maxPerStageUpdateAfterBindResources >= sampled_total + sampler_total + storage_total + 1 && - props12.maxDescriptorSetUpdateAfterBindSampledImages >= sampled_total && - props12.maxDescriptorSetUpdateAfterBindSamplers >= sampler_total && - props12.maxDescriptorSetUpdateAfterBindStorageImages >= storage_total; - return l.maxPerStageDescriptorSampledImages >= sampled_total && l.maxPerStageDescriptorSamplers >= sampler_total && - l.maxPerStageDescriptorStorageImages >= storage_total && - l.maxPerStageResources >= sampled_total + sampler_total + storage_total + 1 && - l.maxDescriptorSetSampledImages >= sampled_total && l.maxDescriptorSetSamplers >= sampler_total && - l.maxDescriptorSetStorageImages >= storage_total; - }; - if (!fits(flags)) flags = {}; - if (!fits(flags)) { - // Fall back to the sizes the runtime would pick for this device. - flags.update_after_bind = en12.descriptorBindingSampledImageUpdateAfterBind; - flags.partially_bound = en12.descriptorBindingPartiallyBound; - leonida::bindless::size_bindings(flags, props.properties.limits, props11, props12); - } - std::optional set; - set.emplace(vkGetDeviceProcAddr, dev, mp, flags); - if (!set->ok() || !set->layout() || !set->set()) { - std::printf("unsupported: cannot create the bindless set\n"); - return 77; - } - - const double t_set = now_s(); - // Optional gradient textures behind the all-zero T# and S#. - struct Tex { VkImage img = VK_NULL_HANDLE; VkImageView view = VK_NULL_HANDLE; uint32_t w, h, d, layers; VkImageType type; VkImageViewType vt; uint32_t binding; }; - std::vector texs; - std::vector tex_offsets; - VkBuffer tex_stage = VK_NULL_HANDLE; - VkSampler tex_sampler = VK_NULL_HANDLE; - if (std::getenv("VKS_TEX")) { - const char* tc = std::getenv("VKS_TEX_CONST"); // all texels one RGBA8 value (hex, 0xAABBGGRR), for bisecting - const bool tex_const = tc && *tc; - const uint32_t tex_const_value = tex_const ? uint32_t(std::strtoul(tc, nullptr, 16)) : 0u; - LOADD(vkCreateSampler); LOADD(vkUpdateDescriptorSets); - texs = {{VK_NULL_HANDLE, VK_NULL_HANDLE, 8, 8, 1, 1, VK_IMAGE_TYPE_2D, VK_IMAGE_VIEW_TYPE_2D, 0}, - {VK_NULL_HANDLE, VK_NULL_HANDLE, 8, 8, 1, 6, VK_IMAGE_TYPE_2D, VK_IMAGE_VIEW_TYPE_2D_ARRAY, 3}, - {VK_NULL_HANDLE, VK_NULL_HANDLE, 8, 1, 1, 1, VK_IMAGE_TYPE_1D, VK_IMAGE_VIEW_TYPE_1D, 5}, - {VK_NULL_HANDLE, VK_NULL_HANDLE, 8, 8, 4, 1, VK_IMAGE_TYPE_3D, VK_IMAGE_VIEW_TYPE_3D, 6}}; - if (integer_tex) texs.resize(1); - std::vector texels; - std::vector offsets; - for (auto& t : texs) { - offsets.push_back(texels.size() * 4); - for (uint32_t z = 0; z < t.d * t.layers; ++z) - for (uint32_t y = 0; y < t.h; ++y) - for (uint32_t x = 0; x < t.w; ++x) - texels.push_back(integer_tex ? (128u + x) | ((31u + y) << 8) | ((250u - x) << 16) | ((80u - y) << 24) - : tex_const ? tex_const_value - : (x * 32u) | ((y * 32u) << 8) | ((64u + z * 40u) << 16) | (255u << 24)); - } - void* sp = nullptr; - VkDeviceMemory sm; - VkBufferCreateInfo sbi{VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO}; - sbi.size = texels.size() * 4; sbi.usage = VK_BUFFER_USAGE_TRANSFER_SRC_BIT; - CHECK(vkCreateBuffer(dev, &sbi, nullptr, &tex_stage)); - VkMemoryRequirements sr; - vkGetBufferMemoryRequirements(dev, tex_stage, &sr); - VkMemoryAllocateInfo sai{VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO}; - sai.allocationSize = sr.size; - sai.memoryTypeIndex = memtype(sr.memoryTypeBits, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT); - CHECK(vkAllocateMemory(dev, &sai, nullptr, &sm)); - CHECK(vkBindBufferMemory(dev, tex_stage, sm, 0)); - CHECK(vkMapMemory(dev, sm, 0, sbi.size, 0, &sp)); - std::memcpy(sp, texels.data(), texels.size() * 4); - for (std::size_t k = 0; k < texs.size(); ++k) { - Tex& t = texs[k]; - VkImageCreateInfo ii{VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO}; - ii.imageType = t.type; ii.format = integer_tex ? (!std::strcmp(tex_mode, "sint") ? VK_FORMAT_R8G8B8A8_SINT : VK_FORMAT_R8G8B8A8_UINT) - : VK_FORMAT_R8G8B8A8_UNORM; ii.extent = {t.w, t.h, t.d}; - ii.mipLevels = 1; ii.arrayLayers = t.layers; ii.samples = VK_SAMPLE_COUNT_1_BIT; ii.tiling = VK_IMAGE_TILING_OPTIMAL; - ii.usage = VK_IMAGE_USAGE_SAMPLED_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT; - CHECK(vkCreateImage(dev, &ii, nullptr, &t.img)); - VkMemoryRequirements mr; - vkGetImageMemoryRequirements(dev, t.img, &mr); - VkMemoryAllocateInfo ai{VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO}; - ai.allocationSize = mr.size; - ai.memoryTypeIndex = memtype(mr.memoryTypeBits, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT); - VkDeviceMemory m; - CHECK(vkAllocateMemory(dev, &ai, nullptr, &m)); - CHECK(vkBindImageMemory(dev, t.img, m, 0)); - VkImageViewCreateInfo vi{VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO}; - vi.image = t.img; vi.viewType = t.vt; vi.format = ii.format; - vi.subresourceRange = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, t.layers}; - CHECK(vkCreateImageView(dev, &vi, nullptr, &t.view)); - } - VkSamplerCreateInfo sci{VK_STRUCTURE_TYPE_SAMPLER_CREATE_INFO}; - sci.magFilter = sci.minFilter = integer_tex || std::getenv("VKS_TEX_NEAREST") ? VK_FILTER_NEAREST : VK_FILTER_LINEAR; - sci.mipmapMode = VK_SAMPLER_MIPMAP_MODE_NEAREST; - sci.addressModeU = sci.addressModeV = sci.addressModeW = VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE; - CHECK(vkCreateSampler(dev, &sci, nullptr, &tex_sampler)); - std::vector infos(texs.size() + 1); - std::vector writes(texs.size() + 1); - for (std::size_t k = 0; k < texs.size(); ++k) { - infos[k] = {VK_NULL_HANDLE, texs[k].view, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL}; - writes[k] = {VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET}; - writes[k].dstSet = set->set(); writes[k].dstBinding = texs[k].binding; writes[k].dstArrayElement = 0; - writes[k].descriptorCount = 1; writes[k].descriptorType = VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE; writes[k].pImageInfo = &infos[k]; - } - infos[texs.size()] = {tex_sampler, VK_NULL_HANDLE, VK_IMAGE_LAYOUT_UNDEFINED}; - VkWriteDescriptorSet& sw = writes[texs.size()]; - sw = {VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET}; - sw.dstSet = set->set(); sw.dstBinding = 1; sw.dstArrayElement = 0; sw.descriptorCount = 1; - sw.descriptorType = VK_DESCRIPTOR_TYPE_SAMPLER; sw.pImageInfo = &infos[texs.size()]; - vkUpdateDescriptorSets(dev, uint32_t(writes.size()), writes.data(), 0, nullptr); - tex_offsets = offsets; // used by the upload commands below - } - // Heap. - VkBufferCreateInfo hbi{VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO}; - hbi.size = heap_bytes; - hbi.usage = VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT; - VkBuffer heap; - CHECK(vkCreateBuffer(dev, &hbi, nullptr, &heap)); - VkMemoryRequirements hr; - vkGetBufferMemoryRequirements(dev, heap, &hr); - VkMemoryAllocateFlagsInfo haf{VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_FLAGS_INFO}; - haf.flags = VK_MEMORY_ALLOCATE_DEVICE_ADDRESS_BIT; - VkMemoryAllocateInfo hai{VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO}; - hai.pNext = &haf; hai.allocationSize = hr.size; - hai.memoryTypeIndex = memtype(hr.memoryTypeBits, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT); - VkDeviceMemory hmem; - CHECK(vkAllocateMemory(dev, &hai, nullptr, &hmem)); - CHECK(vkBindBufferMemory(dev, heap, hmem, 0)); - void* hp; - CHECK(vkMapMemory(dev, hmem, 0, heap_bytes, 0, &hp)); - std::memset(hp, 0, size_t(heap_bytes)); - if (fill_heap) { - uint32_t x = fill[2] * 2654435761u + 0x9e3779b9u; - for (uint32_t o = fill[0]; o < fill[0] + fill[1]; o += 4) { - x ^= x << 13; x ^= x >> 17; x ^= x << 5; - const uint32_t bits = 0x3e800000u + (x % 0x01000000u); // [0.25, 1) - std::memcpy(static_cast(hp) + o, &bits, 4); - } - } - VkBufferDeviceAddressInfo hda{VK_STRUCTURE_TYPE_BUFFER_DEVICE_ADDRESS_INFO}; - hda.buffer = heap; - const uint64_t base = vkGetBufferDeviceAddress(dev, &hda); - pc[32] = uint32_t(base); pc[33] = uint32_t(base >> 32); - - // Targets. - const VkFormat fmt = VK_FORMAT_R32G32B32A32_SFLOAT; - const uint32_t attachments = targets + uint32_t(depth); - if (depth) { - LOADI(vkGetPhysicalDeviceImageFormatProperties); - VkImageFormatProperties image{}; - const auto result = vkGetPhysicalDeviceImageFormatProperties(pd, VK_FORMAT_D32_SFLOAT, VK_IMAGE_TYPE_2D, - VK_IMAGE_TILING_OPTIMAL, VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT | VK_IMAGE_USAGE_TRANSFER_SRC_BIT, 0, &image); - if (result == VK_ERROR_FORMAT_NOT_SUPPORTED || (result == VK_SUCCESS && - (image.maxExtent.width < W || image.maxExtent.height < H || !(image.sampleCounts & VK_SAMPLE_COUNT_1_BIT)))) { - std::puts("unsupported: D32_SFLOAT depth attachment readback"); - return 77; - } - CHECK(result); - } - std::vector imgs(attachments); - std::vector views(attachments); - for (uint32_t t = 0; t < attachments; ++t) { - VkImageCreateInfo ii{VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO}; - ii.imageType = VK_IMAGE_TYPE_2D; ii.format = t == targets ? VK_FORMAT_D32_SFLOAT : fmt; ii.extent = {W, H, 1}; ii.mipLevels = 1; ii.arrayLayers = 1; - ii.samples = VK_SAMPLE_COUNT_1_BIT; ii.tiling = VK_IMAGE_TILING_OPTIMAL; - ii.usage = (t == targets ? VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT : VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT) | VK_IMAGE_USAGE_TRANSFER_SRC_BIT; - CHECK(vkCreateImage(dev, &ii, nullptr, &imgs[t])); - VkMemoryRequirements mr; - vkGetImageMemoryRequirements(dev, imgs[t], &mr); - VkMemoryAllocateInfo ai{VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO}; - ai.allocationSize = mr.size; - ai.memoryTypeIndex = memtype(mr.memoryTypeBits, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT); - VkDeviceMemory m; - CHECK(vkAllocateMemory(dev, &ai, nullptr, &m)); - CHECK(vkBindImageMemory(dev, imgs[t], m, 0)); - VkImageViewCreateInfo vi{VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO}; - vi.image = imgs[t]; vi.viewType = VK_IMAGE_VIEW_TYPE_2D; vi.format = ii.format; - vi.subresourceRange = {VkImageAspectFlags(t == targets ? VK_IMAGE_ASPECT_DEPTH_BIT : VK_IMAGE_ASPECT_COLOR_BIT), 0, 1, 0, 1}; - CHECK(vkCreateImageView(dev, &vi, nullptr, &views[t])); - } - std::vector ads(attachments); - std::vector refs(attachments); - for (uint32_t t = 0; t < attachments; ++t) { - ads[t] = {}; - ads[t].format = t == targets ? VK_FORMAT_D32_SFLOAT : fmt; ads[t].samples = VK_SAMPLE_COUNT_1_BIT; - ads[t].loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR; ads[t].storeOp = VK_ATTACHMENT_STORE_OP_STORE; - ads[t].stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE; ads[t].stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE; - ads[t].initialLayout = VK_IMAGE_LAYOUT_UNDEFINED; ads[t].finalLayout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL; - refs[t] = {t, t == targets ? VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL : VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL}; - } - VkSubpassDescription sd{}; - sd.pipelineBindPoint = VK_PIPELINE_BIND_POINT_GRAPHICS; sd.colorAttachmentCount = targets; sd.pColorAttachments = refs.data(); - if (depth) sd.pDepthStencilAttachment = &refs[targets]; - VkSubpassDependency dep{0, VK_SUBPASS_EXTERNAL, VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT, - VK_PIPELINE_STAGE_TRANSFER_BIT, VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT, VK_ACCESS_TRANSFER_READ_BIT}; - if (depth) { - dep.srcStageMask |= VK_PIPELINE_STAGE_EARLY_FRAGMENT_TESTS_BIT | VK_PIPELINE_STAGE_LATE_FRAGMENT_TESTS_BIT; - dep.srcAccessMask |= VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT; - } - VkRenderPassCreateInfo rpi{VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO}; - rpi.attachmentCount = attachments; rpi.pAttachments = ads.data(); rpi.subpassCount = 1; rpi.pSubpasses = &sd; - rpi.dependencyCount = 1; rpi.pDependencies = &dep; - VkRenderPass rp; - CHECK(vkCreateRenderPass(dev, &rpi, nullptr, &rp)); - VkFramebufferCreateInfo fbi{VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO}; - fbi.renderPass = rp; fbi.attachmentCount = attachments; fbi.pAttachments = views.data(); fbi.width = W; fbi.height = H; fbi.layers = 1; - VkFramebuffer fb; - CHECK(vkCreateFramebuffer(dev, &fbi, nullptr, &fb)); - - // Pipeline. - auto module = [&](const char* p, VkShaderModule* m) { - auto code = read_spv(p); - if (code.empty()) { - std::fprintf(stderr, "cannot read %s\n", p); - return VK_ERROR_INITIALIZATION_FAILED; - } - VkShaderModuleCreateInfo smi{VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO}; - smi.codeSize = code.size() * 4; smi.pCode = code.data(); - return vkCreateShaderModule(dev, &smi, nullptr, m); - }; - VkShaderModule vs, fs; - CHECK(module(argv[1], &vs)); - VkShaderModuleCreateInfo fsi{VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO}; - fsi.codeSize = fs_code.size() * 4; fsi.pCode = fs_code.data(); - CHECK(vkCreateShaderModule(dev, &fsi, nullptr, &fs)); - VkPipelineShaderStageCreateInfo stages[3]{{VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO}, - {VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO}, - {VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO}}; - uint32_t stage_count = 0; - stages[stage_count].stage = VK_SHADER_STAGE_VERTEX_BIT; stages[stage_count].module = vs; - stages[stage_count++].pName = "main"; - if (!gs_code.empty()) { - VkShaderModule gs; - VkShaderModuleCreateInfo gsi{VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO}; - gsi.codeSize = gs_code.size() * 4; gsi.pCode = gs_code.data(); - CHECK(vkCreateShaderModule(dev, &gsi, nullptr, &gs)); - stages[stage_count].stage = VK_SHADER_STAGE_GEOMETRY_BIT; stages[stage_count].module = gs; - stages[stage_count++].pName = "main"; - } - stages[stage_count].stage = VK_SHADER_STAGE_FRAGMENT_BIT; stages[stage_count].module = fs; - stages[stage_count++].pName = "main"; - VkPipelineVertexInputStateCreateInfo vin{VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO}; - VkPipelineInputAssemblyStateCreateInfo ia{VK_STRUCTURE_TYPE_PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO}; - ia.topology = VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST; - VkViewport vp{0, 0, float(W), float(H), 0, 1}; - VkRect2D sc{{0, 0}, {W, H}}; - VkPipelineViewportStateCreateInfo vps{VK_STRUCTURE_TYPE_PIPELINE_VIEWPORT_STATE_CREATE_INFO}; - vps.viewportCount = 1; vps.pViewports = &vp; vps.scissorCount = 1; vps.pScissors = ≻ - VkPipelineRasterizationStateCreateInfo rs{VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_STATE_CREATE_INFO}; - rs.cullMode = VK_CULL_MODE_NONE; rs.lineWidth = 1; - VkPipelineMultisampleStateCreateInfo ms{VK_STRUCTURE_TYPE_PIPELINE_MULTISAMPLE_STATE_CREATE_INFO}; - ms.rasterizationSamples = VK_SAMPLE_COUNT_1_BIT; - std::vector cbas(targets); - for (auto& a : cbas) { a = {}; a.colorWriteMask = 0xF; } - VkPipelineColorBlendStateCreateInfo cb{VK_STRUCTURE_TYPE_PIPELINE_COLOR_BLEND_STATE_CREATE_INFO}; - cb.attachmentCount = targets; cb.pAttachments = cbas.data(); - const VkShaderStageFlags pcs = VK_SHADER_STAGE_VERTEX_BIT | VK_SHADER_STAGE_FRAGMENT_BIT; - VkPushConstantRange pcr{pcs, 0, pc_bytes}; - const VkDescriptorSetLayout set_layout = set->layout(); - VkPipelineLayoutCreateInfo pli{VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO}; - pli.setLayoutCount = 1; pli.pSetLayouts = &set_layout; pli.pushConstantRangeCount = 1; pli.pPushConstantRanges = &pcr; - VkPipelineLayout pl; - CHECK(vkCreatePipelineLayout(dev, &pli, nullptr, &pl)); - VkGraphicsPipelineCreateInfo gpi{VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO}; - gpi.stageCount = stage_count; gpi.pStages = stages; gpi.pVertexInputState = &vin; gpi.pInputAssemblyState = &ia; - gpi.pViewportState = &vps; gpi.pRasterizationState = &rs; gpi.pMultisampleState = &ms; gpi.pColorBlendState = &cb; - VkPipelineDepthStencilStateCreateInfo ds_state{VK_STRUCTURE_TYPE_PIPELINE_DEPTH_STENCIL_STATE_CREATE_INFO}; - if (depth) { - ds_state.depthTestEnable = ds_state.depthWriteEnable = VK_TRUE; - ds_state.depthCompareOp = VK_COMPARE_OP_ALWAYS; - gpi.pDepthStencilState = &ds_state; - } - gpi.layout = pl; gpi.renderPass = rp; - VkPipeline pipe; - { - const VkResult r = vkCreateGraphicsPipelines(dev, VK_NULL_HANDLE, 1, &gpi, nullptr, &pipe); - if (r != VK_SUCCESS) { - std::fprintf(stderr, "PIPELINE %d\n", int(r)); - return r == VK_ERROR_DEVICE_LOST ? 4 : 5; - } - } - - const double t_pipe = now_s(); - // Readback buffer. - const VkDeviceSize target_bytes = VkDeviceSize(W) * H * 16; - VkBufferCreateInfo bi{VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO}; - const VkDeviceSize color_bytes = target_bytes * targets; - bi.size = color_bytes + (depth ? target_bytes / 4 : 0); bi.usage = VK_BUFFER_USAGE_TRANSFER_DST_BIT; - VkBuffer buf; - CHECK(vkCreateBuffer(dev, &bi, nullptr, &buf)); - VkMemoryRequirements br; - vkGetBufferMemoryRequirements(dev, buf, &br); - VkMemoryAllocateInfo bai{VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO}; - bai.allocationSize = br.size; - bai.memoryTypeIndex = memtype(br.memoryTypeBits, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT); - VkDeviceMemory bmem; - CHECK(vkAllocateMemory(dev, &bai, nullptr, &bmem)); - CHECK(vkBindBufferMemory(dev, buf, bmem, 0)); - - VkCommandPoolCreateInfo cpi{VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO}; - cpi.queueFamilyIndex = qi; - VkCommandPool pool; - CHECK(vkCreateCommandPool(dev, &cpi, nullptr, &pool)); - VkCommandBufferAllocateInfo cai{VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO}; - cai.commandPool = pool; cai.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY; cai.commandBufferCount = 1; - VkCommandBuffer cmd; - CHECK(vkAllocateCommandBuffers(dev, &cai, &cmd)); - VkCommandBufferBeginInfo cbi{VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO}; - CHECK(vkBeginCommandBuffer(cmd, &cbi)); - LOADD(vkCmdPipelineBarrier); LOADD(vkCmdCopyBufferToImage); - for (std::size_t k = 0; k < texs.size(); ++k) { - const Tex& t = texs[k]; - VkImageMemoryBarrier ib{VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER}; - ib.oldLayout = VK_IMAGE_LAYOUT_UNDEFINED; ib.newLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL; ib.image = t.img; - ib.subresourceRange = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, t.layers}; ib.dstAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT; - ib.srcQueueFamilyIndex = ib.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; - vkCmdPipelineBarrier(cmd, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, 0, 0, nullptr, 0, nullptr, 1, &ib); - VkBufferImageCopy c{}; - c.bufferOffset = tex_offsets[k]; c.imageSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, t.layers}; c.imageExtent = {t.w, t.h, t.d}; - vkCmdCopyBufferToImage(cmd, tex_stage, t.img, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, &c); - ib.oldLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL; ib.newLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL; - ib.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT; ib.dstAccessMask = VK_ACCESS_SHADER_READ_BIT; - vkCmdPipelineBarrier(cmd, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT, 0, 0, nullptr, 0, nullptr, 1, &ib); - } - if (!set->flush(cmd)) { - std::fprintf(stderr, "FAILED set->flush\n"); - return 1; - } - if (!set->fallbacks_ready()) set->record_fallback_init(cmd); - std::vector clears(attachments); - for (auto& c : clears) for (float& f : c.color.float32) f = -1; - if (depth) clears[targets].depthStencil = {depth_clear, 0}; - VkRenderPassBeginInfo rbi{VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO}; - rbi.renderPass = rp; rbi.framebuffer = fb; rbi.renderArea = sc; rbi.clearValueCount = attachments; rbi.pClearValues = clears.data(); - LOADD(vkCreateQueryPool); LOADD(vkDestroyQueryPool); LOADD(vkGetQueryPoolResults); - LOADD(vkCmdResetQueryPool); LOADD(vkCmdBeginQuery); LOADD(vkCmdEndQuery); - VkQueryPool query = VK_NULL_HANDLE; - if (occlusion) { - VkQueryPoolCreateInfo info{VK_STRUCTURE_TYPE_QUERY_POOL_CREATE_INFO}; - info.queryType = VK_QUERY_TYPE_OCCLUSION; - info.queryCount = 1; - CHECK(vkCreateQueryPool(dev, &info, nullptr, &query)); - vkCmdResetQueryPool(cmd, query, 0, 1); - } - vkCmdBeginRenderPass(cmd, &rbi, VK_SUBPASS_CONTENTS_INLINE); - vkCmdBindPipeline(cmd, VK_PIPELINE_BIND_POINT_GRAPHICS, pipe); - const VkDescriptorSet ds = set->set(); - vkCmdBindDescriptorSets(cmd, VK_PIPELINE_BIND_POINT_GRAPHICS, pl, 0, 1, &ds, 0, nullptr); - vkCmdPushConstants(cmd, pl, pcs, 0, pc_bytes, pc); - if (occlusion) vkCmdBeginQuery(cmd, query, 0, VK_QUERY_CONTROL_PRECISE_BIT); - vkCmdDraw(cmd, 3, 1, 0, 0); - if (occlusion) vkCmdEndQuery(cmd, query, 0); - vkCmdEndRenderPass(cmd); - for (uint32_t t = 0; t < attachments; ++t) { - VkBufferImageCopy reg{}; - reg.bufferOffset = target_bytes * t; - reg.imageSubresource = {VkImageAspectFlags(t == targets ? VK_IMAGE_ASPECT_DEPTH_BIT : VK_IMAGE_ASPECT_COLOR_BIT), 0, 0, 1}; - reg.imageExtent = {W, H, 1}; - vkCmdCopyImageToBuffer(cmd, imgs[t], VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, buf, 1, ®); - } - CHECK(vkEndCommandBuffer(cmd)); - VkFenceCreateInfo fci{VK_STRUCTURE_TYPE_FENCE_CREATE_INFO}; - VkFence fence; - CHECK(vkCreateFence(dev, &fci, nullptr, &fence)); - VkSubmitInfo si{VK_STRUCTURE_TYPE_SUBMIT_INFO}; - si.commandBufferCount = 1; si.pCommandBuffers = &cmd; - CHECK(vkQueueSubmit(q, 1, &si, fence)); - const VkResult waited = vkWaitForFences(dev, 1, &fence, VK_TRUE, timeout_ns); - if (waited == VK_TIMEOUT) { - std::fprintf(stderr, "TIMEOUT\n"); - return 3; - } - CHECK(waited); - if (occlusion) { - uint64_t samples = 0; - CHECK(vkGetQueryPoolResults(dev, query, 0, 1, sizeof(samples), &samples, sizeof(samples), VK_QUERY_RESULT_64_BIT)); - vkDestroyQueryPool(dev, query, nullptr); - std::printf("samples_passed %llu\n", static_cast(samples)); - } - const double t_draw = now_s(); - void* p; - CHECK(vkMapMemory(dev, bmem, 0, bi.size, 0, &p)); - std::ofstream output(argv[3], std::ios::binary); - output.write(static_cast(p), std::streamsize(color_bytes)); - if (depth) { - std::ofstream plane(std::string(argv[3]) + ".depth", std::ios::binary); - plane.write(static_cast(p) + color_bytes, std::streamsize(bi.size - color_bytes)); - plane.close(); - if (!plane) return 1; - } - output.close(); - if (!output) { - std::fprintf(stderr, "failed to write %s\n", argv[3]); - return 1; - } - std::fprintf(stderr, "ok %ux%u x%u -> %s (device %.2fs, set %.2fs, pipeline %.2fs, draw %.2fs)\n", W, H, targets, argv[3], - t_device - t_start, t_set - t_device, t_pipe - t_set, t_draw - t_pipe); - return 0; -} diff --git a/runtime/test/vk_queue_constructor_oom_test.cpp b/runtime/test/vk_queue_constructor_oom_test.cpp deleted file mode 100644 index dbd5d0a11..000000000 --- a/runtime/test/vk_queue_constructor_oom_test.cpp +++ /dev/null @@ -1,217 +0,0 @@ -// A failed QueueHolds registration must release VulkanQueue's command pool and timeline semaphore. -// Public runtime classes with fake Vulkan procedures: no loader, GPU, or game data. -#include "../src/vulkan_backend.h" - -#include -#include -#include -#include -#include -#include -#include - -namespace { -bool fail_next_new = false; -bool arm_after_semaphore = false; -bool fail_pool = false; -bool fail_semaphore = false; -int failures = 0; -std::uintptr_t next_handle = 100; - -template Handle handle() { - const auto value = ++next_handle; - if constexpr (std::is_pointer_v) return reinterpret_cast(value); - else return static_cast(value); -} -template std::uintptr_t number(Handle value) { - if constexpr (std::is_pointer_v) return reinterpret_cast(value); - else return static_cast(value); -} - -struct Handles { - std::array live{}; - int created = 0; - int destroyed = 0; - int invalid_destroy = 0; - void add(std::uintptr_t value) { live[created++] = value; } - void remove(std::uintptr_t value) { - for (auto& item : live) { - if (item == value) { - item = 0; - ++destroyed; - return; - } - } - ++invalid_destroy; - } - bool exact(int made, int freed) const { - return created == made && destroyed == freed && invalid_destroy == 0; - } -}; -Handles pools, semaphores; - -void expect(bool ok, const char* what) { - if (!ok) { - std::fprintf(stderr, "FAIL: %s\n", what); - ++failures; - } -} - -PFN_vkVoidFunction VKAPI_CALL no_proc(VkDevice, const char*) { return nullptr; } -VkResult VKAPI_CALL create_pool(VkDevice, const VkCommandPoolCreateInfo*, const VkAllocationCallbacks*, - VkCommandPool* out) { - *out = VK_NULL_HANDLE; - if (fail_pool) return VK_ERROR_OUT_OF_HOST_MEMORY; - *out = handle(); - pools.add(number(*out)); - return VK_SUCCESS; -} -void VKAPI_CALL destroy_pool(VkDevice, VkCommandPool pool, const VkAllocationCallbacks*) { - pools.remove(number(pool)); -} -VkResult VKAPI_CALL create_semaphore(VkDevice, const VkSemaphoreCreateInfo*, const VkAllocationCallbacks*, - VkSemaphore* out) { - *out = VK_NULL_HANDLE; - if (!fail_semaphore) { - *out = handle(); - semaphores.add(number(*out)); - } - // The next host allocation is QueueHolds::attach's holder-vector growth. Context and queue members already - // exist, so MSVC Debug's empty-container iterator proxies are constructed before injection is armed. - if (arm_after_semaphore) { - arm_after_semaphore = false; - fail_next_new = true; - } - return fail_semaphore ? VK_ERROR_OUT_OF_HOST_MEMORY : VK_SUCCESS; -} -void VKAPI_CALL destroy_semaphore(VkDevice, VkSemaphore semaphore, const VkAllocationCallbacks*) { - semaphores.remove(number(semaphore)); -} -VkResult VKAPI_CALL idle(VkQueue) { return VK_SUCCESS; } -VkResult VKAPI_CALL completed(VkDevice, VkSemaphore, std::uint64_t* out) { - *out = UINT64_MAX; - return VK_SUCCESS; -} -void install(leonida::VulkanContext& context) { - context.vk.vkCreateCommandPool = create_pool; - context.vk.vkDestroyCommandPool = destroy_pool; - context.vk.vkCreateSemaphore = create_semaphore; - context.vk.vkDestroySemaphore = destroy_semaphore; - context.vk.vkQueueWaitIdle = idle; - context.vk.vkGetSemaphoreCounterValue = completed; -} -void reset() { - pools = {}; - semaphores = {}; - fail_pool = fail_semaphore = arm_after_semaphore = fail_next_new = false; -} - -void initial_failure_and_retry() { - reset(); - { - leonida::VulkanContext context(no_proc, handle(), false); - install(context); - arm_after_semaphore = true; - bool threw = false; - try { leonida::VulkanQueue failed(context, handle(), 0); } - catch (const std::bad_alloc&) { threw = true; } - const bool consumed = !fail_next_new; - fail_next_new = false; - expect(threw && consumed, "first holder insertion did not reject the injected allocation"); - expect(pools.exact(1, 1) && semaphores.exact(1, 1), - "failed first queue did not clean both Vulkan handles exactly once"); - { - leonida::VulkanQueue retry(context, handle(), 0); - expect(retry.ok(), "retry in the same context did not construct a queue"); - } - } - expect(pools.exact(2, 2) && semaphores.exact(2, 2), "retry did not clean its handles exactly once"); -} - -void failure_with_live_queue() { - reset(); - { - leonida::VulkanContext context(no_proc, handle(), false); - install(context); - leonida::VulkanQueue first(context, handle(), 0); - expect(first.ok(), "first live queue failed to construct"); - arm_after_semaphore = true; - bool threw = false; - try { leonida::VulkanQueue failed(context, handle(), 0); } - catch (const std::bad_alloc&) { threw = true; } - const bool consumed = !fail_next_new; - fail_next_new = false; - expect(threw && consumed, "holder-vector growth did not reject the injected allocation"); - expect(pools.exact(2, 1) && semaphores.exact(2, 1), - "failed second queue did not clean its own handles while the first stayed live"); - { - leonida::VulkanQueue retry(context, handle(), 0); - expect(retry.ok(), "queue registration did not recover after failed growth"); - } - } - expect(pools.exact(3, 3) && semaphores.exact(3, 3), - "live and retried queues did not each clean their handles once"); -} - -void partial_creation_failures() { - reset(); - { - leonida::VulkanContext context(no_proc, handle(), false); - install(context); - fail_pool = true; - leonida::VulkanQueue failed(context, handle(), 0); - expect(!failed.ok(), "failed command-pool creation appeared usable"); - } - expect(pools.exact(0, 0) && semaphores.exact(0, 0), "pool failure touched an invalid handle"); - - reset(); - { - leonida::VulkanContext context(no_proc, handle(), false); - install(context); - fail_semaphore = true; - leonida::VulkanQueue failed(context, handle(), 0); - expect(!failed.ok(), "failed semaphore creation appeared usable"); - } - expect(pools.exact(1, 1) && semaphores.exact(0, 0), - "ordinary semaphore failure did not clean only its command pool"); - - reset(); - { - leonida::VulkanContext context(no_proc, handle(), false); - install(context); - fail_semaphore = true; - arm_after_semaphore = true; - bool threw = false; - try { leonida::VulkanQueue failed(context, handle(), 0); } - catch (const std::bad_alloc&) { threw = true; } - const bool consumed = !fail_next_new; - fail_next_new = false; - expect(threw && consumed, "partial creation did not reach the injected holder allocation"); - } - expect(pools.exact(1, 1) && semaphores.exact(0, 0), - "attach failure after semaphore failure did not clean only the command pool"); -} -} // namespace - -void* operator new(std::size_t size) { - if (fail_next_new) { - fail_next_new = false; - throw std::bad_alloc{}; - } - if (void* p = std::malloc(size ? size : 1)) return p; - throw std::bad_alloc{}; -} -void* operator new[](std::size_t size) { return operator new(size); } -void operator delete(void* p) noexcept { std::free(p); } -void operator delete[](void* p) noexcept { std::free(p); } -void operator delete(void* p, std::size_t) noexcept { std::free(p); } -void operator delete[](void* p, std::size_t) noexcept { std::free(p); } - -int main() { - initial_failure_and_retry(); - failure_with_live_queue(); - partial_creation_failures(); - if (failures) return 1; - std::puts("vk_queue_constructor_oom_test: ok"); - return 0; -} diff --git a/runtime/test/vk_queue_query_sync_test.cpp b/runtime/test/vk_queue_query_sync_test.cpp deleted file mode 100644 index 9aecd81cb..000000000 --- a/runtime/test/vk_queue_query_sync_test.cpp +++ /dev/null @@ -1,471 +0,0 @@ -// VulkanQueue / VulkanContext query-state synchronization and failed-submit wait preservation regressions -// (runtime/src/vulkan_backend.h): -// 1. VulkanContext::remove_query_pool() must serialize with tracker_mutex_ so an in-flight VulkanQueue::execute() -// that already unlocked resource_mutex_ cannot suffer a use-after-free in QueryReplay::commit(). -// 2. VulkanQueue::execute() must acquire tracker_mutex_ before QueryReplay::plan() so concurrent queues see -// submission-order query state (no data race on QueryPool::ended / QueryPool::occlusion and no stale zero-fill). -// 3. A transient vkQueueSubmit failure must preserve pending VulkanQueue::wait() timeline semaphores for the retry. -// 4. Concurrent multi-queue query End/Resolve + add/remove_query_pool stress with zero Vulkan validation errors. -// Skips with exit code 77 when no Vulkan 1.3 device is available. No game data. -#include "vk_test_device.h" -#include "../src/vulkan_backend.h" - -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#define EXPECT(condition) do { \ - if (!(condition)) { std::fprintf(stderr, "line %d: %s\n", __LINE__, #condition); return 1; } \ -} while (0) - -namespace { - -namespace driver { -PFN_vkGetDeviceProcAddr real_get_device = nullptr; -PFN_vkQueueSubmit real_submit = nullptr; -PFN_vkGetSemaphoreCounterValue real_counter = nullptr; -PFN_vkCmdCopyQueryPoolResults real_copy_queries = nullptr; -PFN_vkCmdFillBuffer real_fill_buffer = nullptr; - -std::atomic fail_next_submit{VK_SUCCESS}; -std::atomic fail_next_counter{VK_SUCCESS}; -std::atomic injected_counter_errors{0}; -std::thread::id counter_test_thread; -std::atomic capture_next_waits{false}; -std::atomic captured_wait_count{0}; -std::atomic captured_wait_sem{0}; -std::atomic captured_wait_val{0}; - -std::atomic count_resolves{false}; -std::atomic copy_query_calls{0}; -std::atomic fill_buffer_calls{0}; - -// Optional one-shot callback invoked inside vkQueueSubmit right before calling the real driver. -// Returning non-VK_SUCCESS short-circuits the submit with that status. -std::function on_next_submit; - -VKAPI_ATTR VkResult VKAPI_CALL queue_submit(VkQueue queue, std::uint32_t count, const VkSubmitInfo* submits, - VkFence fence) { - if (on_next_submit) { - auto cb = std::move(on_next_submit); - on_next_submit = {}; - const VkResult override_res = cb(); - if (override_res != VK_SUCCESS) return override_res; - } - const VkResult armed = fail_next_submit.exchange(VK_SUCCESS); - if (armed != VK_SUCCESS) return armed; - if (capture_next_waits.exchange(false) && count > 0 && submits) { - captured_wait_count.store(submits[0].waitSemaphoreCount); - if (submits[0].waitSemaphoreCount > 0 && submits[0].pWaitSemaphores) { - captured_wait_sem.store(reinterpret_cast(submits[0].pWaitSemaphores[0])); - const auto* timeline = reinterpret_cast(submits[0].pNext); - if (timeline && timeline->sType == VK_STRUCTURE_TYPE_TIMELINE_SEMAPHORE_SUBMIT_INFO && - timeline->waitSemaphoreValueCount > 0 && timeline->pWaitSemaphoreValues) { - captured_wait_val.store(timeline->pWaitSemaphoreValues[0]); - } - } - } - return real_submit(queue, count, submits, fence); -} - -VKAPI_ATTR VkResult VKAPI_CALL get_counter(VkDevice device, VkSemaphore semaphore, std::uint64_t* value) { - if (std::this_thread::get_id() == counter_test_thread) { - const VkResult result = fail_next_counter.exchange(VK_SUCCESS); - if (result != VK_SUCCESS) { - *value = 999; // failure output is undefined, so make accidental reuse detectable - injected_counter_errors.fetch_add(1); - return result; - } - } - return real_counter(device, semaphore, value); -} - -VKAPI_ATTR void VKAPI_CALL cmd_copy_query_pool_results(VkCommandBuffer cb, VkQueryPool pool, std::uint32_t first, - std::uint32_t count, VkBuffer dst, VkDeviceSize offset, - VkDeviceSize stride, VkQueryResultFlags flags) { - if (count_resolves.load(std::memory_order_relaxed)) copy_query_calls.fetch_add(1, std::memory_order_relaxed); - real_copy_queries(cb, pool, first, count, dst, offset, stride, flags); -} - -VKAPI_ATTR void VKAPI_CALL cmd_fill_buffer(VkCommandBuffer cb, VkBuffer dst, VkDeviceSize offset, VkDeviceSize size, - std::uint32_t data) { - if (count_resolves.load(std::memory_order_relaxed)) fill_buffer_calls.fetch_add(1, std::memory_order_relaxed); - real_fill_buffer(cb, dst, offset, size, data); -} - -VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL get_device(VkDevice device, const char* name) { - const std::string_view n = name; - if (n == "vkQueueSubmit") return reinterpret_cast(queue_submit); - if (n == "vkGetSemaphoreCounterValue") return reinterpret_cast(get_counter); - if (n == "vkCmdCopyQueryPoolResults") return reinterpret_cast(cmd_copy_query_pool_results); - if (n == "vkCmdFillBuffer") return reinterpret_cast(cmd_fill_buffer); - return real_get_device(device, name); -} - -void install(PFN_vkGetDeviceProcAddr device_proc, VkDevice device) { - real_get_device = device_proc; - real_submit = reinterpret_cast(device_proc(device, "vkQueueSubmit")); - real_counter = reinterpret_cast( - device_proc(device, "vkGetSemaphoreCounterValue")); - real_copy_queries = - reinterpret_cast(device_proc(device, "vkCmdCopyQueryPoolResults")); - real_fill_buffer = reinterpret_cast(device_proc(device, "vkCmdFillBuffer")); -} -} // namespace driver - -} // namespace - -int main() { - using namespace leonida; - - vktest::Device d; - if (!d.create(false)) { - std::fprintf(stderr, "vk_queue_query_sync_test: no Vulkan 1.3 device, skipped\n"); - return 77; - } - driver::install(d.device_proc, d.device); - driver::counter_test_thread = std::this_thread::get_id(); - - const auto create_query_pool = d.fn("vkCreateQueryPool"); - const auto destroy_query_pool = d.fn("vkDestroyQueryPool"); - EXPECT(create_query_pool && destroy_query_pool); - - auto make_occlusion_pool = [&](std::uint32_t count) -> VkQueryPool { - VkQueryPoolCreateInfo info{VK_STRUCTURE_TYPE_QUERY_POOL_CREATE_INFO}; - info.queryType = VK_QUERY_TYPE_OCCLUSION; - info.queryCount = count; - VkQueryPool pool = VK_NULL_HANDLE; - if (create_query_pool(d.device, &info, nullptr, &pool) != VK_SUCCESS) return VK_NULL_HANDLE; - return pool; - }; - - const VkQueryPool pool_uaf = make_occlusion_pool(2); - const VkQueryPool pool_race = make_occlusion_pool(2); - const VkQueryPool pool_stress = make_occlusion_pool(32); - EXPECT(pool_uaf && pool_race && pool_stress); - bool progress_loss_ok = true; // deferred verdict: release Vulkan query pools even when main is expected-red - - { - VulkanContext context(driver::get_device, d.device, true); - EXPECT(context.loaded()); - VulkanQueue queue_a(context, d.queue, d.family); - VulkanQueue queue_b(context, d.queue, d.family); - EXPECT(queue_a.ok() && queue_b.ok()); - - void* src_ptr = nullptr; - void* dst_ptr = nullptr; - void* res_ptr = nullptr; - const VkBuffer src_buf = d.buffer(64, VK_BUFFER_USAGE_TRANSFER_SRC_BIT, &src_ptr); - const VkBuffer dst_buf = d.buffer(64, VK_BUFFER_USAGE_TRANSFER_DST_BIT | VK_BUFFER_USAGE_TRANSFER_SRC_BIT, &dst_ptr); - const VkBuffer res_buf = d.buffer(64, VK_BUFFER_USAGE_TRANSFER_DST_BIT, &res_ptr); - EXPECT(src_buf && dst_buf && res_buf); - - ResourceBinding src_rb{}; - src_rb.buffer = src_buf; - src_rb.size = 64; - ResourceBinding dst_rb{}; - dst_rb.buffer = dst_buf; - dst_rb.size = 64; - dst_rb.host_readable = true; - ResourceBinding res_rb{}; - res_rb.buffer = res_buf; - res_rb.size = 64; - res_rb.host_readable = true; - context.add_resource(1, src_rb); - context.add_resource(2, dst_rb); - context.add_resource(3, res_rb); - - // 1. remove_query_pool() must block on tracker_mutex_ while execute() is between resource_lock.unlock() and - // QueryReplay::commit(), preventing a use-after-free on the QueryPool* stored in QueryReplay::pending_. - { - constexpr QueryHeapId heap_id = 77; - QueryPool qp{}; - qp.pool = pool_uaf; - qp.heap_type = d3d12_query_heap::occlusion; - qp.count = 2; - qp.ended.assign(2, false); - context.add_query_pool(heap_id, qp); - - CommandList list; - EXPECT(list.begin_query({heap_id, d3d12_query::occlusion, 0})); - EXPECT(list.end_query({heap_id, d3d12_query::occlusion, 0})); - EXPECT(list.close()); - const CommandList* ptr = &list; - - std::atomic removed{false}; - bool removed_during_submit = false; - std::thread remover; - driver::on_next_submit = [&]() -> VkResult { - remover = std::thread([&] { - context.remove_query_pool(heap_id); - removed.store(true, std::memory_order_release); - }); - std::this_thread::sleep_for(std::chrono::milliseconds(30)); - removed_during_submit = removed.load(std::memory_order_acquire); - // If remove_query_pool already erased the node, abort the submit so queries.commit() does not - // corrupt the heap before the EXPECT below reports the failure cleanly. - return removed_during_submit ? VK_ERROR_OUT_OF_HOST_MEMORY : VK_SUCCESS; - }; - const ReplayResult exec_res = queue_a.execute({&ptr, 1}); - if (remover.joinable()) remover.join(); - EXPECT(!removed_during_submit); - EXPECT(exec_res == ReplayResult::success); - EXPECT(removed.load(std::memory_order_acquire)); - EXPECT(context.query_heap_type(heap_id) == ~0u); - EXPECT(queue_a.idle()); - std::printf("queue/query sync: remove_query_pool serialized with QueryReplay::commit ok\n"); - } - - // 2. Concurrent queue_b.execute(ResolveQueries) must not run QueryReplay::plan() before queue_a commits - // EndQuery; otherwise queue_b sees ended[0] == false and emits vkCmdFillBuffer(0) instead of copying. - { - constexpr QueryHeapId heap_id = 88; - QueryPool qp{}; - qp.pool = pool_race; - qp.heap_type = d3d12_query_heap::occlusion; - qp.count = 2; - qp.ended.assign(2, false); - context.add_query_pool(heap_id, qp); - - CommandList end_list; - EXPECT(end_list.begin_query({heap_id, d3d12_query::occlusion, 0})); - EXPECT(end_list.end_query({heap_id, d3d12_query::occlusion, 0})); - EXPECT(end_list.close()); - const CommandList* end_ptr = &end_list; - - CommandList resolve_list; - EXPECT(resolve_list.resolve_queries({heap_id, d3d12_query::occlusion, 0, 1, 3, 0})); - EXPECT(resolve_list.close()); - const CommandList* resolve_ptr = &resolve_list; - - std::memset(res_ptr, 0xAB, 64); - driver::copy_query_calls.store(0); - driver::fill_buffer_calls.store(0); - driver::count_resolves.store(true); - - std::thread resolver; - ReplayResult resolve_res = ReplayResult::unsupported; - driver::on_next_submit = [&]() -> VkResult { - resolver = std::thread([&] { resolve_res = queue_b.execute({&resolve_ptr, 1}); }); - // Give queue_b ample time to run prepare() and reach QueryReplay::plan() while queue_a holds - // tracker_mutex_ (and has already unlocked resource_mutex_). - std::this_thread::sleep_for(std::chrono::milliseconds(40)); - return VK_SUCCESS; - }; - - const ReplayResult end_res = queue_a.execute({&end_ptr, 1}); - if (resolver.joinable()) resolver.join(); - driver::count_resolves.store(false); - EXPECT(end_res == ReplayResult::success); - EXPECT(resolve_res == ReplayResult::success); - EXPECT(queue_a.idle() && queue_b.idle()); - EXPECT(driver::copy_query_calls.load() == 1); - EXPECT(driver::fill_buffer_calls.load() == 0); - std::uint64_t resolved = 0xDEADBEEFULL; - std::memcpy(&resolved, res_ptr, sizeof(resolved)); - EXPECT(resolved == 0); // empty occlusion query resolves 0 via vkCmdCopyQueryPoolResults - context.remove_query_pool(heap_id); - std::printf("queue/query sync: cross-queue QueryReplay::plan serialized with commit ok\n"); - } - - // 3. A transient vkQueueSubmit failure must preserve pending VulkanQueue::wait() semaphores for the retry. - { - VulkanFence fence(context, 0); - EXPECT(fence.semaphore() != VK_NULL_HANDLE); - - const std::uint64_t pattern = 0x1122334455667788ULL; - std::memcpy(src_ptr, &pattern, sizeof(pattern)); - std::memset(dst_ptr, 0, sizeof(pattern)); - - CommandList copy_list; - EXPECT(copy_list.copy_buffer({2, 0, 1, 0, sizeof(pattern)})); - EXPECT(copy_list.close()); - const CommandList* ptr = ©_list; - - // The Signal comes first: a Wait with no submitted Signal holds the batch on the CPU (queue_holds.h) and - // never reaches vkQueueSubmit, so it could not fail there. - EXPECT(fence.signal(1)); - queue_a.wait(fence.semaphore(), 1); - driver::fail_next_submit.store(VK_ERROR_OUT_OF_HOST_MEMORY); - EXPECT(queue_a.execute({&ptr, 1}) == ReplayResult::unsupported); - - // Retry: the pending wait on (fence, 1) must still be attached to the next vkQueueSubmit. - driver::captured_wait_count.store(0); - driver::captured_wait_sem.store(0); - driver::captured_wait_val.store(0); - driver::capture_next_waits.store(true); - EXPECT(queue_a.execute({&ptr, 1}) == ReplayResult::success); - EXPECT(queue_a.idle()); - EXPECT(driver::captured_wait_count.load() == 1); - EXPECT(driver::captured_wait_sem.load() == reinterpret_cast(fence.semaphore())); - EXPECT(driver::captured_wait_val.load() == 1); - - std::uint64_t got = 0; - std::memcpy(&got, dst_ptr, sizeof(got)); - EXPECT(got == pattern); - std::printf("queue/query sync: pending Wait() preserved across failed vkQueueSubmit ok\n"); - } - - // 3b. The same for a batch held behind a Wait with no submitted Signal (queue_holds.h): its submission - // fails when the CPU Signal releases it, the failure is reported through take_held_failure(), and its - // waits stay for the next submission, as when the call is not held. A Signal queued behind the failed - // batch still runs. - { - VulkanFence gate(context, 0), after(context, 0); - EXPECT(gate.semaphore() != VK_NULL_HANDLE && after.semaphore() != VK_NULL_HANDLE); - const std::uint64_t pattern = 0x0badf00dcafe1234ULL; - std::memcpy(src_ptr, &pattern, sizeof(pattern)); - std::memset(dst_ptr, 0, sizeof(pattern)); - CommandList copy_list; - EXPECT(copy_list.copy_buffer({2, 0, 1, 0, sizeof(pattern)})); - EXPECT(copy_list.close()); - const CommandList* ptr = ©_list; - - queue_a.wait(gate.semaphore(), 1); - EXPECT(queue_a.execute({&ptr, 1}) == ReplayResult::success); // held: the Signal is not submitted yet - EXPECT(queue_a.signal(after.semaphore(), 1)); // held behind it - EXPECT(after.completed() == 0 && queue_a.take_held_failure() == ReplayResult::success); - driver::fail_next_submit.store(VK_ERROR_OUT_OF_HOST_MEMORY); - EXPECT(gate.signal(1)); // releases the batch on this thread - EXPECT(queue_a.take_held_failure() == ReplayResult::unsupported); - EXPECT(queue_a.take_held_failure() == ReplayResult::success); // reported once - EXPECT(queue_a.idle() && after.completed() == 1); // the Signal behind it still signaled - - driver::captured_wait_count.store(0); - driver::captured_wait_sem.store(0); - driver::captured_wait_val.store(0); - driver::capture_next_waits.store(true); - EXPECT(queue_a.execute({&ptr, 1}) == ReplayResult::success); - EXPECT(queue_a.idle()); - EXPECT(driver::captured_wait_count.load() == 1); // the failed batch's wait on (gate, 1) came along - EXPECT(driver::captured_wait_sem.load() == reinterpret_cast(gate.semaphore())); - EXPECT(driver::captured_wait_val.load() == 1); - std::uint64_t got = 0; - std::memcpy(&got, dst_ptr, sizeof(got)); - EXPECT(got == pattern); - std::printf("queue/query sync: failed held batch reported, its wait kept for the retry, Signal behind it ran\n"); - } - - // 3c. A Signal whose vkQueueSubmit fails signals nothing: a queue waiting for it stays held (the value is not - // counted as submitted), and the application's retry of the Signal goes through and releases it. - { - VulkanFence fence(context, 0); - EXPECT(fence.semaphore() != VK_NULL_HANDLE); - const std::uint64_t pattern = 0x5ca1ab1e0ddba11ULL; - std::memcpy(src_ptr, &pattern, sizeof(pattern)); - std::memset(dst_ptr, 0, sizeof(pattern)); - CommandList copy_list; - EXPECT(copy_list.copy_buffer({2, 0, 1, 0, sizeof(pattern)})); - EXPECT(copy_list.close()); - const CommandList* ptr = ©_list; - queue_b.wait(fence.semaphore(), 1); - EXPECT(queue_b.execute({&ptr, 1}) == ReplayResult::success); // held for the Signal - driver::fail_next_submit.store(VK_ERROR_OUT_OF_HOST_MEMORY); - EXPECT(!queue_a.signal(fence.semaphore(), 1)); // the submit fails - EXPECT(queue_b.idle() && fence.completed() == 0); - std::uint64_t got = 1; - std::memcpy(&got, dst_ptr, sizeof(got)); - EXPECT(got == 0); // the waiter did not run - EXPECT(queue_a.signal(fence.semaphore(), 1)); // the retry signals, and releases it - EXPECT(queue_b.idle() && queue_a.idle() && fence.completed() == 1); - std::memcpy(&got, dst_ptr, sizeof(got)); - EXPECT(got == pattern); - std::printf("queue/query sync: a failed Signal does not release its waiters; the retry does\n"); - } - - // 4. Concurrent multi-queue EndQuery + ResolveQueries + temporary query pool add/remove stress. - // Each iteration uses a distinct query slot so no slot is reset while another submission resolves it. - { - constexpr QueryHeapId main_heap = 99; - QueryPool qp{}; - qp.pool = pool_stress; - qp.heap_type = d3d12_query_heap::occlusion; - qp.count = 32; - qp.ended.assign(32, false); - context.add_query_pool(main_heap, qp); - - CommandList res_list; - EXPECT(res_list.resolve_queries({main_heap, d3d12_query::occlusion, 0, 1, 3, 0})); - EXPECT(res_list.close()); - const CommandList* res_ptr_cmd = &res_list; - - std::atomic stop{false}; - std::atomic worker_err{false}; - std::thread worker([&] { - for (std::uint64_t round = 0; !stop.load(std::memory_order_relaxed); ++round) { - if (queue_b.execute({&res_ptr_cmd, 1}) != ReplayResult::success || !queue_b.idle()) { - worker_err.store(true); - break; - } - const QueryHeapId temp_id = 1000 + (round % 16); - context.add_query_pool(temp_id, qp); - context.remove_query_pool(temp_id); - } - }); - - ReplayResult main_err = ReplayResult::success; - for (std::uint32_t i = 0; i < 32; ++i) { - CommandList end_list; - if (!end_list.begin_query({main_heap, d3d12_query::occlusion, i}) || - !end_list.end_query({main_heap, d3d12_query::occlusion, i}) || !end_list.close()) { - main_err = ReplayResult::invalid_query; - break; - } - const CommandList* end_ptr = &end_list; - main_err = queue_a.execute({&end_ptr, 1}); - if (main_err != ReplayResult::success) break; - } - stop.store(true, std::memory_order_relaxed); - worker.join(); - EXPECT(main_err == ReplayResult::success); - EXPECT(!worker_err.load()); - EXPECT(queue_a.idle() && queue_b.idle()); - context.remove_query_pool(main_heap); - std::printf("queue/query sync: concurrent multi-queue query stress ok\n"); - } - - // 5. A progress-semaphore query in acquire() can be the first Vulkan operation to discover - // device loss. A transient query failure must not poison a healthy queue, while DEVICE_LOST - // must prevent acquiring/recycling and submitting new command buffers. - { - EXPECT(!context.is_device_lost()); - CommandList empty; - EXPECT(empty.close()); - const CommandList* ptr = ∅ - EXPECT(queue_a.idle() && queue_b.idle()); - (void)context.completed_retire_ticket(); // drain old submits before faulting queue's own progress query - driver::fail_next_counter.store(VK_ERROR_OUT_OF_HOST_MEMORY); - const ReplayResult transient = queue_a.execute({&ptr, 1}); - const bool transient_ok = transient == ReplayResult::success && !context.is_device_lost() && - driver::injected_counter_errors.load() == 1; - - EXPECT(queue_a.idle()); - (void)context.completed_retire_ticket(); - driver::fail_next_counter.store(VK_ERROR_DEVICE_LOST); - const ReplayResult after_loss = queue_a.execute({&ptr, 1}); - const bool lost = context.is_device_lost(); - std::printf("queue/query sync: injected nonfatal execute=%d, device-loss execute=%d, " - "context_lost=%d, interceptions=%u\n", int(transient), int(after_loss), int(lost), - driver::injected_counter_errors.load()); - progress_loss_ok = transient_ok && after_loss == ReplayResult::unsupported && lost && - driver::injected_counter_errors.load() == 2; - std::printf("queue/query sync: progress counter device loss %s\n", - progress_loss_ok ? "marks context and rejects work" : "NOT propagated"); - } - } - - destroy_query_pool(d.device, pool_uaf, nullptr); - destroy_query_pool(d.device, pool_race, nullptr); - destroy_query_pool(d.device, pool_stress, nullptr); - - EXPECT(d.validation_errors() == 0); - EXPECT(progress_loss_ok); - std::printf("vk_queue_query_sync_test: ok\n"); - return 0; -} diff --git a/runtime/test/vk_queue_test.cpp b/runtime/test/vk_queue_test.cpp deleted file mode 100644 index 744adfab8..000000000 --- a/runtime/test/vk_queue_test.cpp +++ /dev/null @@ -1,398 +0,0 @@ -// D3D12 copy and compute queues on their own Vulkan queues, with cross-queue fences. No shaders or game data. -// -// The device gets a queue per D3D12 type (dedicated families when the GPU has them). A copy queue uploads a buffer -// and a texture, the way asset streaming does, signals a fence, and the direct queue waits on that fence on the GPU -// before reading both back. The compute queue does the same handoff the other way. A copy queue must refuse a -// render-target clear. Set LEONIDA_VK_VALIDATION=1 to run under VK_LAYER_KHRONOS_validation; any validation error -// fails the test. -#include "vk_test_device.h" -#include "../src/vulkan_backend.h" - -#include -#include -#include -#include -#include - -#define EXPECT(condition) do { \ - if (!(condition)) { std::fprintf(stderr, "line %d: %s\n", __LINE__, #condition); return 1; } \ -} while (0) - -namespace { - -using namespace leonida; -using Kind = VulkanQueue::QueueKind; - -// Counts the command buffers a queue allocates, for the backlog check in main(). -PFN_vkAllocateCommandBuffers real_allocate_command_buffers = nullptr; -std::uint32_t allocated_command_buffers = 0; - -VKAPI_ATTR VkResult VKAPI_CALL counting_allocate_command_buffers(VkDevice device, const VkCommandBufferAllocateInfo* info, - VkCommandBuffer* buffers) { - allocated_command_buffers += info->commandBufferCount; - return real_allocate_command_buffers(device, info, buffers); -} - -// Makes the queue's first kStalls waits for room time out at once, as on a GPU that stopped making progress. -// While hold_progress is set, timeline counter queries report 0 so a fast GPU cannot retire command buffers -// before the loop reaches kMaxQueuedCommandBuffers; once kStalls timeouts have been injected, real progress -// resumes and the wait completes normally. -constexpr std::uint32_t kStalls = 3; -PFN_vkGetSemaphoreCounterValue real_get_semaphore_counter_value = nullptr; -PFN_vkWaitSemaphores real_wait_semaphores = nullptr; -std::atomic injected_stalls{0}; -std::atomic hold_progress{false}; - -VKAPI_ATTR VkResult VKAPI_CALL holding_semaphore_counter(VkDevice device, VkSemaphore semaphore, - std::uint64_t* value) { - if (hold_progress.load()) { - *value = 0; - return VK_SUCCESS; - } - return real_get_semaphore_counter_value(device, semaphore, value); -} - -VKAPI_ATTR VkResult VKAPI_CALL stalling_wait_semaphores(VkDevice device, const VkSemaphoreWaitInfo* info, - std::uint64_t timeout) { - if (timeout == VulkanQueue::kQueuedWaitNs) { - if (injected_stalls.load() < kStalls) { - ++injected_stalls; - return VK_TIMEOUT; - } - hold_progress.store(false); - } - return real_wait_semaphores(device, info, timeout); -} - -const char* flags_text(VkQueueFlags f) { - static char buf[32]; - std::snprintf(buf, sizeof buf, "%s%s%s", f & VK_QUEUE_GRAPHICS_BIT ? "G" : "", f & VK_QUEUE_COMPUTE_BIT ? "C" : "", - f & VK_QUEUE_TRANSFER_BIT ? "T" : ""); - return buf; -} - -int check_picker() { - // Synthetic family layouts: the picker's choices don't depend on the GPU running the test. - auto fam = [](VkQueueFlags flags, std::uint32_t granularity = 1) { - VkQueueFamilyProperties p{}; - p.queueFlags = flags; - p.queueCount = 1; - p.minImageTransferGranularity = {granularity, granularity, granularity}; - return p; - }; - constexpr VkQueueFlags G = VK_QUEUE_GRAPHICS_BIT | VK_QUEUE_COMPUTE_BIT | VK_QUEUE_TRANSFER_BIT; - constexpr VkQueueFlags C = VK_QUEUE_COMPUTE_BIT | VK_QUEUE_TRANSFER_BIT; - constexpr VkQueueFlags T = VK_QUEUE_TRANSFER_BIT; - { - const std::array f{fam(G), fam(T), fam(C)}; // the common NVIDIA layout - const auto q = pick_queue_families(f, 0); - EXPECT(q.direct == 0 && q.compute == 2 && q.copy == 1); - } - { - const std::array f{fam(G)}; // one family for everything (integrated GPUs, llvmpipe) - const auto q = pick_queue_families(f, 0); - EXPECT(q.direct == 0 && q.compute == 0 && q.copy == 0); - } - { - const std::array f{fam(G), fam(C)}; // no DMA family: copies go to async compute - const auto q = pick_queue_families(f, 0); - EXPECT(q.compute == 1 && q.copy == 1); - } - { - const std::array f{fam(G), fam(T, 8), fam(C)}; // a coarse DMA family is skipped - const auto q = pick_queue_families(f, 0); - EXPECT(q.copy == 2); - } - // D3D12 tile mapping is legal on all queue kinds. Dedicated async queues that cannot - // bind sparse pages must use the graphics family when sparse buffers are offered. - { - constexpr VkQueueFlags S = VK_QUEUE_SPARSE_BINDING_BIT; - const std::array f{fam(G | S), fam(T), fam(C)}; - const auto preferred = pick_queue_families(f, 0); - EXPECT(preferred.compute == 2 && preferred.copy == 1); - const auto corrected = sparse_capable_queue_families(f, preferred, true); - EXPECT(corrected.direct == 0 && corrected.compute == 0 && corrected.copy == 0); - const auto no_sparse = sparse_capable_queue_families(f, preferred, false); - EXPECT(no_sparse.compute == 2 && no_sparse.copy == 1); - } - { - constexpr VkQueueFlags S = VK_QUEUE_SPARSE_BINDING_BIT; - const std::array f{fam(G | S), fam(T | S), fam(C | S)}; - const auto preferred = pick_queue_families(f, 0); - const auto corrected = sparse_capable_queue_families(f, preferred, true); - EXPECT(corrected.compute == 2 && corrected.copy == 1); // preserve dedicated queues - } - { - constexpr VkQueueFlags S = VK_QUEUE_SPARSE_BINDING_BIT; - const std::array f{fam(G | S), fam(T), fam(C | S)}; - const auto preferred = pick_queue_families(f, 0); - const auto corrected = sparse_capable_queue_families(f, preferred, true); - EXPECT(corrected.compute == 2 && corrected.copy == 0); // mixed capabilities - } - std::printf("queue family picker: 7 layouts ok\n"); - return 0; -} - -// Which VkQueue each new D3D12 queue leases (CreateCommandQueue): an unused one while there is one, its own family's -// first, then the one with the fewest D3D12 queues. `own` and `graphics` count the D3D12 queues on each VkQueue. -int check_queue_slots() { - const auto lease = [](std::vector& own, std::vector& graphics) { - const auto slot = pick_queue_slot({own, graphics}); - if (slot.pool != SIZE_MAX) ++(slot.pool == 0 ? own : graphics)[slot.index]; - return slot; - }; - { // Enough queues (an RTX 5080: 8 compute, 16 graphics): every COMPUTE queue gets a VkQueue of its own. - std::vector compute(8, 0), graphics(16, 0); - for (std::size_t i = 0; i < 8; ++i) { - const auto slot = lease(compute, graphics); - EXPECT(slot.pool == 0 && slot.index == i); - } - const auto ninth = lease(compute, graphics); - EXPECT(ninth.pool == 1 && ninth.index == 0); // then an unused graphics queue, not a shared compute one - } - { // One VkQueue per family (LEONIDA_VK_MAX_QUEUES_PER_FAMILY=1): DIRECT, COMPUTE, then they share. - std::vector none, compute(1, 0), graphics(1, 0); - EXPECT(lease(none, graphics).pool == 1); - EXPECT(lease(compute, graphics).pool == 0); - const auto second_compute = lease(compute, graphics); - EXPECT(second_compute.pool == 0 && compute[0] == 2); // a tie goes to the type's own family - const auto third_compute = lease(compute, graphics); - EXPECT(third_compute.pool == 1 && graphics[0] == 2); // then the queue with fewer D3D12 queues - --compute[0]; - --compute[0]; // two COMPUTE queues released - EXPECT(lease(compute, graphics).pool == 0); - } - { // A queue released by its last D3D12 queue is unused again and preferred to sharing. - std::vector none, graphics{3, 0, 2}; - const auto slot = lease(none, graphics); - EXPECT(slot.pool == 1 && slot.index == 1); - } - { // No VkQueue at all. - std::vector none; - EXPECT(pick_queue_slot({none, none}).pool == SIZE_MAX); - } - std::printf("queue slots: distinct while free, shared by fewest users after\n"); - return 0; -} - -constexpr std::uint32_t kSize = 64 * 1024; -constexpr std::uint32_t kTex = 64; // 64x64 RGBA8: row pitch 256, already aligned - -std::uint8_t pattern(std::uint32_t i, std::uint8_t seed) { return std::uint8_t(i * 31 + seed); } - -} // namespace - -int main() { - if (check_picker() || check_queue_slots()) return 1; - - vktest::Device d; - d.all_queue_types = true; - if (!d.create()) { - std::printf("SKIP: no usable Vulkan device\n"); - return 77; - } - std::printf("families: direct %u (%s)", d.family, flags_text(d.families[d.family].queueFlags)); - std::printf(", compute %u (%s)", d.compute_family, flags_text(d.families[d.compute_family].queueFlags)); - std::printf(", copy %u (%s)\n", d.copy_family, flags_text(d.families[d.copy_family].queueFlags)); - - VulkanContext context(d.device_proc, d.device, true); - EXPECT(context.loaded()); - VulkanQueue direct(context, d.queue, d.family, Kind::direct); - VulkanQueue compute(context, d.compute_queue, d.compute_family, Kind::compute); - VulkanQueue copy(context, d.copy_queue, d.copy_family, Kind::copy); - EXPECT(direct.ok() && compute.ok() && copy.ok()); - - // Buffers: an upload source, a GPU-side destination and a readback, all host-visible for the test. - void *upload_map = nullptr, *mid_map = nullptr, *readback_map = nullptr, *tex_readback_map = nullptr; - void* stale_src_map = nullptr; - const VkBufferUsageFlags usage = VK_BUFFER_USAGE_TRANSFER_SRC_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT; - VkBuffer upload = d.buffer(kSize, usage, &upload_map); - VkBuffer mid = d.buffer(kSize, usage, &mid_map); - VkBuffer readback = d.buffer(kSize, usage, &readback_map); - VkBuffer tex_readback = d.buffer(kTex * kTex * 4, usage, &tex_readback_map); - VkBuffer stale_src = d.buffer(kSize, usage, &stale_src_map); - VkImage texture = d.image(VK_FORMAT_R8G8B8A8_UNORM, kTex, kTex, 1, VK_IMAGE_USAGE_SAMPLED_BIT); - EXPECT(upload && mid && readback && tex_readback && stale_src && texture); - auto* up = static_cast(upload_map); - for (std::uint32_t i = 0; i < kSize; ++i) up[i] = pattern(i, 7); - - const ResourceId upload_id = 1, mid_id = 2, readback_id = 3, tex_id = 4, tex_readback_id = 5, stale_src_id = 7; - auto add_buffer = [&](ResourceId id, VkBuffer b, VkDeviceSize size) { - ResourceBinding r; - r.buffer = b; - r.size = size; - context.add_resource(id, r); - }; - add_buffer(upload_id, upload, kSize); - add_buffer(mid_id, mid, kSize); - add_buffer(readback_id, readback, kSize); - add_buffer(tex_readback_id, tex_readback, kTex * kTex * 4); - add_buffer(stale_src_id, stale_src, kSize); - ResourceBinding tex; - tex.image = texture; - tex.format = VK_FORMAT_R8G8B8A8_UNORM; - tex.width = kTex; - tex.height = kTex; - // As the device registers a texture: tracked, still undefined, in D3D12's common state. Its first use is the - // copy-queue upload, which can't zero-fill it first. - context.add_resource(tex_id, tex, VK_IMAGE_LAYOUT_UNDEFINED); - - VulkanFence fence(context, 0); - EXPECT(fence.semaphore()); - - // 1. Copy queue: buffer upload and a texture upload from the same staging buffer (footprint copy), then signal. - CommandList on_copy; - EXPECT(on_copy.copy_buffer({mid_id, 0, upload_id, 0, kSize})); - CopyTexture upload_tex{}; - upload_tex.dst = {tex_id, false, 0, 0, 0, 0, 0, 0}; - upload_tex.src = {upload_id, true, 0, 0, kTex, kTex, 1, kTex * 4}; - EXPECT(on_copy.copy_texture(upload_tex)); - EXPECT(on_copy.close()); - const CommandList* copy_lists[] = {&on_copy}; - EXPECT(copy.execute(copy_lists) == ReplayResult::success); - EXPECT(copy.signal(fence.semaphore(), 1)); - - // 2. Direct queue: wait for the copy queue on the GPU, then read both back. - direct.wait(fence.semaphore(), 1); - CommandList on_direct; - EXPECT(on_direct.copy_buffer({readback_id, 0, mid_id, 0, kSize})); - CopyTexture read_tex{}; - read_tex.dst = {tex_readback_id, true, 0, 0, kTex, kTex, 1, kTex * 4}; - read_tex.src = {tex_id, false, 0, 0, 0, 0, 0, 0}; - EXPECT(on_direct.copy_texture(read_tex)); - EXPECT(on_direct.close()); - const CommandList* direct_lists[] = {&on_direct}; - EXPECT(direct.execute(direct_lists) == ReplayResult::success); - EXPECT(direct.signal(fence.semaphore(), 2)); - EXPECT(fence.wait(2, 5'000'000'000ull)); - - std::uint32_t bad = 0; - auto* rb = static_cast(readback_map); - for (std::uint32_t i = 0; i < kSize; ++i) bad += rb[i] != pattern(i, 7); - auto* tr = static_cast(tex_readback_map); - for (std::uint32_t i = 0; i < kTex * kTex * 4; ++i) bad += tr[i] != pattern(i, 7); - std::printf("copy -> direct: buffer and texture upload read back, %u bad bytes\n", bad); - EXPECT(bad == 0); - - // 3. Compute queue the other way: wait for the direct queue, copy, signal; the host waits on the fence. - for (std::uint32_t i = 0; i < kSize; ++i) up[i] = pattern(i, 99); - CommandList on_direct2; - EXPECT(on_direct2.copy_buffer({mid_id, 0, upload_id, 0, kSize})); - EXPECT(on_direct2.close()); - const CommandList* direct_lists2[] = {&on_direct2}; - EXPECT(direct.execute(direct_lists2) == ReplayResult::success); - EXPECT(direct.signal(fence.semaphore(), 3)); - compute.wait(fence.semaphore(), 3); - CommandList on_compute; - EXPECT(on_compute.copy_buffer({readback_id, 0, mid_id, 0, kSize})); - EXPECT(on_compute.close()); - const CommandList* compute_lists[] = {&on_compute}; - EXPECT(compute.execute(compute_lists) == ReplayResult::success); - EXPECT(compute.signal(fence.semaphore(), 4)); - EXPECT(fence.wait(4, 5'000'000'000ull)); - bad = 0; - for (std::uint32_t i = 0; i < kSize; ++i) bad += rb[i] != pattern(i, 99); - std::printf("direct -> compute: %u bad bytes\n", bad); - EXPECT(bad == 0); - - // 3b. A smaller ExecuteCommandLists must keep the prepared storage but must not replay stale entries. - // Eight lists, each copying a non-overlapping chunk from a source that stays at 0xaa, grow prepared_ to eight. - // A one-list submission then copies only its own chunk from the upload source, now 0xbb. With resize() down and - // range-for over all entries, the seven stale copies run after that one and put 0xaa back into mid. - constexpr std::uint32_t kChunk = kSize / 8; - auto* old = static_cast(stale_src_map); - std::memset(old, 0xaa, kSize); - CommandList stale[8]; - const CommandList* many[8]; - for (std::uint32_t i = 0; i < 8; ++i) { - EXPECT(stale[i].copy_buffer({mid_id, i * kChunk, stale_src_id, i * kChunk, kChunk})); - EXPECT(stale[i].close()); - many[i] = &stale[i]; - } - EXPECT(direct.execute(many) == ReplayResult::success); - EXPECT(direct.signal(fence.semaphore(), 10)); - EXPECT(fence.wait(10, 5'000'000'000ull)); - auto* md = static_cast(mid_map); - std::memset(md, 0, kSize); - for (std::uint32_t i = 0; i < kSize; ++i) up[i] = 0xbb; - CommandList final_copy; - EXPECT(final_copy.copy_buffer({mid_id, 7 * kChunk, upload_id, 7 * kChunk, kChunk})); - EXPECT(final_copy.close()); - const CommandList* one[1] = {&final_copy}; - EXPECT(direct.execute(one) == ReplayResult::success); - EXPECT(direct.signal(fence.semaphore(), 11)); - EXPECT(fence.wait(11, 5'000'000'000ull)); - EXPECT(direct.prepared_entries() == 8); - bad = 0; - for (std::uint32_t i = 0; i < kSize; ++i) - bad += md[i] != (i >= 7 * kChunk ? 0xbb : 0x00); - std::printf("prepared storage: %zu entries kept, %u stale bytes\n", direct.prepared_entries(), bad); - EXPECT(bad == 0); - - // 4. A copy queue refuses a render-target clear and submits nothing. - VkImage rt_image = d.image(VK_FORMAT_R8G8B8A8_UNORM, 8, 8, 1, VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT); - ResourceBinding rt; - rt.image = rt_image; - rt.format = VK_FORMAT_R8G8B8A8_UNORM; - rt.width = rt.height = 8; - context.add_resource(6, rt, VK_IMAGE_LAYOUT_UNDEFINED); - CommandList clear; - TargetView view{}; - view.resource = 6; - view.layer_count = 1; - EXPECT(clear.clear_render_target(view, ClearColor{})); - EXPECT(clear.close()); - const CommandList* clear_lists[] = {&clear}; - EXPECT(copy.execute(clear_lists) == ReplayResult::unsupported); - EXPECT(compute.execute(clear_lists) == ReplayResult::unsupported); - std::printf("copy and compute queues refuse a render-target clear\n"); - - // 5. A caller that submits faster than the GPU finishes must not grow the queue's command buffers without bound: - // at the cap it waits for the oldest one. Big host-visible copies keep the GPU behind the submitting loop. The first - // waits time out (injected), as on a stalled GPU: the cap must hold through a timeout too. - { - constexpr VkDeviceSize kBig = 16u << 20; - constexpr std::uint32_t kSubmits = 4 * VulkanQueue::kMaxQueuedCommandBuffers; - void *src_map = nullptr, *dst_map = nullptr; - VkBuffer big_src = d.buffer(kBig, usage, &src_map); - VkBuffer big_dst = d.buffer(kBig, usage, &dst_map); - EXPECT(big_src && big_dst); - add_buffer(7, big_src, kBig); - add_buffer(8, big_dst, kBig); - std::memset(src_map, 0x5A, kBig); - CommandList big_copy; - EXPECT(big_copy.copy_buffer({8, 0, 7, 0, kBig})); - EXPECT(big_copy.close()); - const CommandList* big_lists[] = {&big_copy}; - - real_allocate_command_buffers = context.vk.vkAllocateCommandBuffers; - real_get_semaphore_counter_value = context.vk.vkGetSemaphoreCounterValue; - real_wait_semaphores = context.vk.vkWaitSemaphores; - context.vk.vkAllocateCommandBuffers = counting_allocate_command_buffers; - context.vk.vkGetSemaphoreCounterValue = holding_semaphore_counter; - context.vk.vkWaitSemaphores = stalling_wait_semaphores; - allocated_command_buffers = 0; - injected_stalls.store(0); - hold_progress.store(true); - for (std::uint32_t i = 0; i < kSubmits; ++i) EXPECT(direct.execute(big_lists) == ReplayResult::success); - hold_progress.store(false); - context.vk.vkAllocateCommandBuffers = real_allocate_command_buffers; - context.vk.vkGetSemaphoreCounterValue = real_get_semaphore_counter_value; - context.vk.vkWaitSemaphores = real_wait_semaphores; - EXPECT(direct.signal(fence.semaphore(), 5)); - EXPECT(fence.wait(5, 20'000'000'000ull)); - std::printf("backlog: %u submits, %u command buffers allocated (cap %zu), %u waits timed out\n", kSubmits, - allocated_command_buffers, VulkanQueue::kMaxQueuedCommandBuffers, injected_stalls.load()); - EXPECT(injected_stalls.load() == kStalls); // the queue did reach the cap and wait - EXPECT(allocated_command_buffers <= VulkanQueue::kMaxQueuedCommandBuffers); - EXPECT(static_cast(dst_map)[kBig - 1] == 0x5A); - } - - EXPECT(direct.idle() && compute.idle() && copy.idle()); - if (d.validation) { - std::printf("validation errors: %u\n", d.validation_errors()); - EXPECT(d.validation_errors() == 0); - } - std::printf("vk_queue_test: OK\n"); - return 0; -} diff --git a/runtime/test/vk_sampler_test.cpp b/runtime/test/vk_sampler_test.cpp deleted file mode 100644 index 98206931b..000000000 --- a/runtime/test/vk_sampler_test.cpp +++ /dev/null @@ -1,551 +0,0 @@ -// GPU test of the S# and T# mip fields as src/gfx10_descriptors.h maps them to Vulkan. The pixel shader -// (ps_ssharp.asm) loads a T# and an S# from the heap, the translator hashes both, and this program binds the image -// and sampler those keys name. Unlike vk_texture_test, which binds a fixed nearest sampler and one level, the -// VkSampler here is vulkan_sampler(decode(S#)) and the view's levels come from decode(T#). -// -// vk_sampler_test [ ] -// -// S# words are hex. The T# is encode() of a 128x128 RGBA8 image with two levels, with BASE_LEVEL and LAST_LEVEL as -// given (default 0 and 1). Level 0 has four solid quadrants: red, green, blue and yellow. Level 1 is solid grey -// (128/255). vs_ids runs UV 0..1 over the 64x64 target, so implicit sampling sees two level-0 texels per pixel -// (LOD 1) and image_sample_lz asks for LOD 0. The 64x64 RGBA32F result is written to ; check.py judges it. -// Exit 77 with "unsupported: ..." when the device lacks a feature the shader or sampler needs. -#define VK_NO_PROTOTYPES -#include "vulkan_loader.h" -#include "vk_shader_fma.h" -#include "../src/vulkan_device_filter.h" -#include "vk_pc_tail.h" -#include "vk_shader_fma.h" - -#include "../src/descriptor_table.h" -#include "../src/gfx10_descriptors.h" - -#include -#include -#include -#include -#include -#include -#include - -#define CHECK(x) \ - do { \ - VkResult r_ = (x); \ - if (r_ != VK_SUCCESS) { \ - std::fprintf(stderr, "FAILED %s -> %d (line %d)\n", #x, r_, __LINE__); \ - return 1; \ - } \ - } while (0) - -namespace { - -constexpr int unsupported = 77; - -std::vector read_spv(const char* path) { - std::ifstream f(path, std::ios::binary); - std::vector bytes((std::istreambuf_iterator(f)), {}); - std::vector words(bytes.size() / 4); - std::memcpy(words.data(), bytes.data(), words.size() * 4); - return words; -} - -} // namespace - -int main(int argc, char** argv) { - if (argc != 8 && argc != 10) { - std::fprintf(stderr, "usage: vk_sampler_test [ ]\n"); - return 2; - } - namespace gfx10 = leonida::gfx10; - constexpr std::uint32_t W = 64, H = 64, TW = 128, levels = 2; - constexpr std::uint32_t table_va = 256; // console VA of the T# (8 dwords); the S# follows at +32 - gfx10::SamplerWords ssharp{}; - for (int i = 0; i < 4; ++i) ssharp[i] = std::uint32_t(std::strtoul(argv[4 + i], nullptr, 16)); - gfx10::Image image; - image.address = 0x100000; - image.format = gfx10::format_from_vulkan(VK_FORMAT_R8G8B8A8_UNORM); - image.width = image.height = TW; - image.resource_mips = levels; - image.first_mip = argc == 10 ? std::uint32_t(std::atoi(argv[8])) : 0; - image.mip_count = (argc == 10 ? std::uint32_t(std::atoi(argv[9])) : levels - 1) - image.first_mip + 1; - const gfx10::ImageWords tsharp = gfx10::encode(image); - gfx10::Image view_of; - if (!gfx10::decode(tsharp, view_of) || view_of.first_mip + view_of.mip_count > levels) { - std::fprintf(stderr, "the T# does not decode to a view of the %u levels\n", levels); - return 2; - } - const VkSamplerCreateInfo sampler_info = gfx10::vulkan_sampler(gfx10::decode(ssharp)); - std::printf("S# %08x %08x %08x %08x: mipmapMode %d, minLod %g, maxLod %g, mipLodBias %g; view levels %u..%u\n", - ssharp[0], ssharp[1], ssharp[2], ssharp[3], int(sampler_info.mipmapMode), sampler_info.minLod, - sampler_info.maxLod, sampler_info.mipLodBias, view_of.first_mip, view_of.first_mip + view_of.mip_count - 1); - - const PFN_vkGetInstanceProcAddr gipa = load_vulkan(); - if (!gipa) { std::fprintf(stderr, "the Vulkan loader was not found\n"); return 1; } - VkInstance inst = VK_NULL_HANDLE; -#define LI(n) const auto n = reinterpret_cast(gipa(inst, #n)) - LI(vkCreateInstance); - VkApplicationInfo app{VK_STRUCTURE_TYPE_APPLICATION_INFO}; - app.apiVersion = VK_API_VERSION_1_2; - VkInstanceCreateInfo ici{VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO}; - ici.pApplicationInfo = &app; - CHECK(vkCreateInstance(&ici, nullptr, &inst)); - LI(vkEnumeratePhysicalDevices); LI(vkGetPhysicalDeviceProperties); LI(vkGetPhysicalDeviceQueueFamilyProperties); - LI(vkGetPhysicalDeviceMemoryProperties); LI(vkGetPhysicalDeviceFeatures2); LI(vkCreateDevice); LI(vkGetDeviceProcAddr); - std::uint32_t n = 0; - vkEnumeratePhysicalDevices(inst, &n, nullptr); - std::vector pds(n); - vkEnumeratePhysicalDevices(inst, &n, pds.data()); - VkPhysicalDevice pd = VK_NULL_HANDLE; - VkPhysicalDeviceProperties props{}; - int best_rank = -1; - for (auto d : pds) { - VkPhysicalDeviceProperties p; - vkGetPhysicalDeviceProperties(d, &p); - if (p.apiVersion < VK_API_VERSION_1_2 || !leonida::vulkan_device_wanted(p.deviceName)) continue; - // the runtime's pick: the first device of the highest rank (native driver over Dozen, #915) - if (const int rank = leonida::vulkan_device_rank(static_cast(p.deviceType), p.vendorID); - rank > best_rank) { - best_rank = rank; - pd = d; - props = p; - } - } - if (!pd && !leonida::vulkan_device_filter().empty()) { // a filter matching nothing fails, never skips - std::fprintf(stderr, "LEONIDA_VK_DEVICE=%s: no Vulkan 1.2 device matches\n", - leonida::vulkan_device_filter().c_str()); - return 1; - } - if (!pd) { std::printf("unsupported: no Vulkan 1.2 device\n"); return unsupported; } - std::printf("device: %s, driver 0x%x, Vulkan %u.%u.%u\n", props.deviceName, props.driverVersion, - VK_API_VERSION_MAJOR(props.apiVersion), VK_API_VERSION_MINOR(props.apiVersion), - VK_API_VERSION_PATCH(props.apiVersion)); - // 144 push-constant bytes by default, or 128 under LEONIDA_PC_TAIL_UBO=1 (rdna2spirv.py --pc-tail-ubo). - // A 128-byte device cannot declare a 144-byte range (VUID-VkPushConstantRange-size-00298): exit 77 (D3D-14). - const bool pc_tail = leonida::vk_test::pc_tail_requested(); - const std::uint32_t push_bytes = pc_tail ? 128u : 144u; - if (props.limits.maxPushConstantsSize < push_bytes) { - std::printf("unsupported: need %u push constant bytes, device has %u\n", push_bytes, - props.limits.maxPushConstantsSize); - return unsupported; - } - VkPhysicalDeviceVulkan11Features have11{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_1_FEATURES}; - VkPhysicalDeviceVulkan12Features have12{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_2_FEATURES, &have11}; - VkPhysicalDeviceFeatures2 have{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2, &have12}; - vkGetPhysicalDeviceFeatures2(pd, &have); - if (!have12.bufferDeviceAddress || !have12.runtimeDescriptorArray || !have.features.shaderInt64) { - std::printf("unsupported: the device lacks bufferDeviceAddress, runtimeDescriptorArray or shaderInt64\n"); - return unsupported; - } - const auto fragment_code = read_spv(argv[2]); - const bool dynamic_sampled = leonida::vk_test::spirv_declares_capability( - fragment_code.data(), fragment_code.size() * 4, leonida::vk_test::spv_sampled_image_array_dynamic_indexing); - if (dynamic_sampled && !have.features.shaderSampledImageArrayDynamicIndexing) { - std::printf("unsupported: shaderSampledImageArrayDynamicIndexing\n"); - return unsupported; - } - if (sampler_info.anisotropyEnable && !have.features.samplerAnisotropy) { - std::printf("unsupported: the S# asks for anisotropy and the device has no samplerAnisotropy\n"); - return unsupported; - } - std::uint32_t qn = 0; - vkGetPhysicalDeviceQueueFamilyProperties(pd, &qn, nullptr); - std::vector qf(qn); - vkGetPhysicalDeviceQueueFamilyProperties(pd, &qn, qf.data()); - std::uint32_t qi = 0; - while (qi < qn && !(qf[qi].queueFlags & VK_QUEUE_GRAPHICS_BIT)) ++qi; - if (qi == qn) { std::printf("unsupported: no graphics queue\n"); return unsupported; } - const float priority = 1; - VkDeviceQueueCreateInfo qci{VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO}; - qci.queueFamilyIndex = qi; - qci.queueCount = 1; - qci.pQueuePriorities = &priority; - VkPhysicalDeviceVulkan12Features enable12{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_2_FEATURES}; - enable12.bufferDeviceAddress = VK_TRUE; - enable12.runtimeDescriptorArray = VK_TRUE; - enable12.descriptorIndexing = have12.descriptorIndexing; - // The translated vs_ids reads BaseVertex / BaseInstance (DrawParameters) for the zero-based v0 / v3, as in - // vk_harness and vk_texture_test. Without the feature, creating its module breaks - // VUID-VkShaderModuleCreateInfo-pCode-08740. - VkPhysicalDeviceVulkan11Features enable11{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_1_FEATURES}; - enable11.shaderDrawParameters = have11.shaderDrawParameters; - enable12.pNext = &enable11; - VkPhysicalDeviceFeatures2 enable{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2, &enable12}; - enable.features.shaderInt64 = VK_TRUE; - enable.features.shaderSampledImageArrayDynamicIndexing = dynamic_sampled; - enable.features.samplerAnisotropy = sampler_info.anisotropyEnable; - leonida::vk_test::ShaderFma fma; // OpFmaKHR (rdna2spirv.py --fma khr), when the device has it - fma.query(gipa, inst, pd); - // A device without VK_KHR_shader_fma cannot create a pipeline from a stage that uses OpFmaKHR: skip the pair. - if (!fma.accepts_file(argv[1]) || !fma.accepts_file(argv[2])) return unsupported; - fma.link_after(&enable); - const char* fma_extension = fma.extension(); - VkDeviceCreateInfo dci{VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO, &enable}; - dci.queueCreateInfoCount = 1; - dci.pQueueCreateInfos = &qci; - if (fma.supported()) { dci.enabledExtensionCount = 1; dci.ppEnabledExtensionNames = &fma_extension; } - VkDevice dev = VK_NULL_HANDLE; - CHECK(vkCreateDevice(pd, &dci, nullptr, &dev)); -#define LD(n) const auto n = reinterpret_cast(vkGetDeviceProcAddr(dev, #n)) - LD(vkGetDeviceQueue); LD(vkCreateImage); LD(vkGetImageMemoryRequirements); LD(vkAllocateMemory); - LD(vkBindImageMemory); LD(vkCreateImageView); LD(vkCreateRenderPass); LD(vkCreateFramebuffer); - LD(vkCreateShaderModule); LD(vkCreatePipelineLayout); LD(vkCreateGraphicsPipelines); LD(vkCreateCommandPool); - LD(vkAllocateCommandBuffers); LD(vkBeginCommandBuffer); LD(vkCmdBeginRenderPass); LD(vkCmdBindPipeline); - LD(vkCmdDraw); LD(vkCmdEndRenderPass); LD(vkCmdCopyImageToBuffer); LD(vkCmdCopyBufferToImage); - LD(vkEndCommandBuffer); LD(vkQueueSubmit); LD(vkQueueWaitIdle); LD(vkCreateBuffer); - LD(vkGetBufferMemoryRequirements); LD(vkBindBufferMemory); LD(vkMapMemory); LD(vkGetBufferDeviceAddress); - LD(vkCreateSampler); LD(vkCreateDescriptorSetLayout); LD(vkCreateDescriptorPool); LD(vkAllocateDescriptorSets); - LD(vkUpdateDescriptorSets); LD(vkCmdBindDescriptorSets); LD(vkCmdPushConstants); LD(vkCmdPipelineBarrier); - VkQueue queue; - vkGetDeviceQueue(dev, qi, 0, &queue); - VkPhysicalDeviceMemoryProperties mp; - vkGetPhysicalDeviceMemoryProperties(pd, &mp); - const auto memtype = [&](std::uint32_t bits, VkMemoryPropertyFlags want) { - for (std::uint32_t i = 0; i < mp.memoryTypeCount; i++) - if ((bits & (1u << i)) && (mp.memoryTypes[i].propertyFlags & want) == want) return i; - return 0u; - }; - const auto make_buffer = [&](VkDeviceSize size, VkBufferUsageFlags usage, VkBuffer* b, void** map) { - VkBufferCreateInfo bi{VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO}; - bi.size = size; - bi.usage = usage; - VkResult r = vkCreateBuffer(dev, &bi, nullptr, b); - if (r) return r; - VkMemoryRequirements mr; - vkGetBufferMemoryRequirements(dev, *b, &mr); - VkMemoryAllocateFlagsInfo fi{VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_FLAGS_INFO}; - fi.flags = VK_MEMORY_ALLOCATE_DEVICE_ADDRESS_BIT; - VkMemoryAllocateInfo ai{VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO}; - ai.pNext = (usage & VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT) ? &fi : nullptr; - ai.allocationSize = mr.size; - ai.memoryTypeIndex = memtype(mr.memoryTypeBits, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT); - VkDeviceMemory m; - r = vkAllocateMemory(dev, &ai, nullptr, &m); - if (r) return r; - r = vkBindBufferMemory(dev, *b, m, 0); - if (r) return r; - return vkMapMemory(dev, m, 0, size, 0, map); - }; - const auto make_image = [&](VkFormat format, std::uint32_t w, std::uint32_t h, std::uint32_t mips, - VkImageUsageFlags usage, VkImage* img) { - VkImageCreateInfo ii{VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO}; - ii.imageType = VK_IMAGE_TYPE_2D; - ii.format = format; - ii.extent = {w, h, 1}; - ii.mipLevels = mips; - ii.arrayLayers = 1; - ii.samples = VK_SAMPLE_COUNT_1_BIT; - ii.usage = usage; - VkResult r = vkCreateImage(dev, &ii, nullptr, img); - if (r) return r; - VkMemoryRequirements mr; - vkGetImageMemoryRequirements(dev, *img, &mr); - VkMemoryAllocateInfo ai{VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO}; - ai.allocationSize = mr.size; - ai.memoryTypeIndex = memtype(mr.memoryTypeBits, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT); - VkDeviceMemory m; - r = vkAllocateMemory(dev, &ai, nullptr, &m); - return r ? r : vkBindImageMemory(dev, *img, m, 0); - }; - const auto make_view = [&](VkImage img, VkFormat format, std::uint32_t base, std::uint32_t count, VkImageView* view) { - VkImageViewCreateInfo vi{VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO}; - vi.image = img; - vi.viewType = VK_IMAGE_VIEW_TYPE_2D; - vi.format = format; - vi.subresourceRange = {VK_IMAGE_ASPECT_COLOR_BIT, base, count, 0, 1}; - return vkCreateImageView(dev, &vi, nullptr, view); - }; - - // The heap (the console's GPU address window): zeros, with the T# at table_va and the S# behind it. - VkBuffer heap; - void* heap_map; - CHECK(make_buffer(65536, VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT, &heap, &heap_map)); - std::memset(heap_map, 0, 65536); - std::memcpy(static_cast(heap_map) + table_va, tsharp.data(), 32); - std::memcpy(static_cast(heap_map) + table_va + 32, ssharp.data(), 16); - VkBufferDeviceAddressInfo address_info{VK_STRUCTURE_TYPE_BUFFER_DEVICE_ADDRESS_INFO}; - address_info.buffer = heap; - const VkDeviceAddress heap_base = vkGetBufferDeviceAddress(dev, &address_info); - // Descriptor hash table: the T# names image 1, the S# sampler 1. Index 0 of each is a magenta fallback. - leonida::DescriptorTable table(16); - table.insert(tsharp.data(), 1); - table.insert(leonida::make_ssharp_key(ssharp.data()).data(), 1); - const auto table_words = table.build_gpu_buffer(true); - VkBuffer table_buffer; - void* table_map; - CHECK(make_buffer(table_words.size() * 4, VK_BUFFER_USAGE_STORAGE_BUFFER_BIT, &table_buffer, &table_map)); - std::memcpy(table_map, table_words.data(), table_words.size() * 4); - - // Textures. RGBA8 in memory order; level 1 grey has r = g = 128/255, unlike every level-0 colour. - constexpr VkFormat texture_format = VK_FORMAT_R8G8B8A8_UNORM; - constexpr std::uint32_t quadrant[2][2] = {{0xff0000ffu, 0xff00ff00u}, {0xffff0000u, 0xff00ffffu}}; - constexpr std::uint32_t grey = 0xff808080u, magenta = 0xffff00ffu; - std::vector texels; - for (std::uint32_t y = 0; y < TW; y++) - for (std::uint32_t x = 0; x < TW; x++) texels.push_back(quadrant[y >= TW / 2][x >= TW / 2]); - texels.resize(texels.size() + (TW / 2) * (TW / 2), grey); - VkImage fallback, texture; - VkImageView fallback_view, texture_view; - CHECK(make_image(texture_format, 1, 1, 1, VK_IMAGE_USAGE_SAMPLED_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT, &fallback)); - CHECK(make_view(fallback, texture_format, 0, 1, &fallback_view)); - CHECK(make_image(texture_format, TW, TW, levels, VK_IMAGE_USAGE_SAMPLED_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT, &texture)); - CHECK(make_view(texture, gfx10::vulkan_format(view_of.format), view_of.first_mip, view_of.mip_count, &texture_view)); - VkBuffer upload; - void* upload_map; - const VkDeviceSize texture_offset = 256, texture_bytes = texels.size() * 4; - CHECK(make_buffer(texture_offset + texture_bytes, VK_BUFFER_USAGE_TRANSFER_SRC_BIT, &upload, &upload_map)); - std::memcpy(upload_map, &magenta, 4); - std::memcpy(static_cast(upload_map) + texture_offset, texels.data(), texture_bytes); - VkSampler samplers[2]; - VkSamplerCreateInfo fallback_sampler{VK_STRUCTURE_TYPE_SAMPLER_CREATE_INFO}; - CHECK(vkCreateSampler(dev, &fallback_sampler, nullptr, &samplers[0])); - CHECK(vkCreateSampler(dev, &sampler_info, nullptr, &samplers[1])); - - // Render target, pass and framebuffer. - constexpr VkFormat target_format = VK_FORMAT_R32G32B32A32_SFLOAT; - VkImage target; - VkImageView target_view; - CHECK(make_image(target_format, W, H, 1, VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | VK_IMAGE_USAGE_TRANSFER_SRC_BIT, &target)); - CHECK(make_view(target, target_format, 0, 1, &target_view)); - VkAttachmentDescription ad{}; - ad.format = target_format; - ad.samples = VK_SAMPLE_COUNT_1_BIT; - ad.loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR; - ad.storeOp = VK_ATTACHMENT_STORE_OP_STORE; - ad.stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE; - ad.stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE; - ad.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED; - ad.finalLayout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL; - const VkAttachmentReference ar{0, VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL}; - VkSubpassDescription sd{}; - sd.pipelineBindPoint = VK_PIPELINE_BIND_POINT_GRAPHICS; - sd.colorAttachmentCount = 1; - sd.pColorAttachments = &ar; - VkSubpassDependency after{}; - after.srcSubpass = 0; - after.dstSubpass = VK_SUBPASS_EXTERNAL; - after.srcStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT; - after.dstStageMask = VK_PIPELINE_STAGE_TRANSFER_BIT; - after.srcAccessMask = VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT; - after.dstAccessMask = VK_ACCESS_TRANSFER_READ_BIT; - VkRenderPassCreateInfo rpi{VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO}; - rpi.attachmentCount = 1; - rpi.pAttachments = &ad; - rpi.subpassCount = 1; - rpi.pSubpasses = &sd; - rpi.dependencyCount = 1; - rpi.pDependencies = &after; - VkRenderPass pass; - CHECK(vkCreateRenderPass(dev, &rpi, nullptr, &pass)); - VkFramebufferCreateInfo fbi{VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO}; - fbi.renderPass = pass; - fbi.attachmentCount = 1; - fbi.pAttachments = &target_view; - fbi.width = W; - fbi.height = H; - fbi.layers = 1; - VkFramebuffer framebuffer; - CHECK(vkCreateFramebuffer(dev, &fbi, nullptr, &framebuffer)); - - // Set 0 as the translator expects it: binding 0 images[], 1 samplers[], 2 the descriptor hash table. - VkDescriptorSetLayoutBinding b[3]{}; - b[0] = {0, VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE, 2, VK_SHADER_STAGE_FRAGMENT_BIT, nullptr}; - b[1] = {1, VK_DESCRIPTOR_TYPE_SAMPLER, 2, VK_SHADER_STAGE_FRAGMENT_BIT, nullptr}; - b[2] = {2, VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, 1, VK_SHADER_STAGE_FRAGMENT_BIT, nullptr}; - VkDescriptorSetLayoutCreateInfo dli{VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO}; - dli.bindingCount = 3; - dli.pBindings = b; - VkDescriptorSetLayout dsl; - CHECK(vkCreateDescriptorSetLayout(dev, &dli, nullptr, &dsl)); - const VkDescriptorPoolSize sizes[3]{{VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE, 2}, {VK_DESCRIPTOR_TYPE_SAMPLER, 2}, - {VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, 1}}; - VkDescriptorPoolCreateInfo dpi{VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO}; - dpi.maxSets = 1; - dpi.poolSizeCount = 3; - dpi.pPoolSizes = sizes; - VkDescriptorPool dp; - CHECK(vkCreateDescriptorPool(dev, &dpi, nullptr, &dp)); - VkDescriptorSetAllocateInfo dai{VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO}; - dai.descriptorPool = dp; - dai.descriptorSetCount = 1; - dai.pSetLayouts = &dsl; - VkDescriptorSet ds; - CHECK(vkAllocateDescriptorSets(dev, &dai, &ds)); - const VkDescriptorImageInfo images[2]{{VK_NULL_HANDLE, fallback_view, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL}, - {VK_NULL_HANDLE, texture_view, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL}}; - const VkDescriptorImageInfo sampler_infos[2]{{samplers[0]}, {samplers[1]}}; - const VkDescriptorBufferInfo table_info{table_buffer, 0, VK_WHOLE_SIZE}; - VkWriteDescriptorSet writes[3]{}; - for (auto& w : writes) { - w.sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET; - w.dstSet = ds; - } - writes[0].dstBinding = 0; writes[0].descriptorCount = 2; writes[0].descriptorType = VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE; - writes[0].pImageInfo = images; - writes[1].dstBinding = 1; writes[1].descriptorCount = 2; writes[1].descriptorType = VK_DESCRIPTOR_TYPE_SAMPLER; - writes[1].pImageInfo = sampler_infos; - writes[2].dstBinding = 2; writes[2].descriptorCount = 1; writes[2].descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER; - writes[2].pBufferInfo = &table_info; - vkUpdateDescriptorSets(dev, 3, writes, 0, nullptr); - - // Pipeline. - VkShaderModule modules[2]; - const auto vertex_code = read_spv(argv[1]); - // LEONIDA_PC_TAIL_UBO=1 (rdna2spirv.py --pc-tail-ubo): s0..s31 in 128 push-constant bytes; the heap base, if a - // stage reads it, in a uniform block at set 1 (vk_pc_tail.h). - bool tail_block = false; - for (int stage = 0; stage < 2; ++stage) { - const auto& code = stage == 0 ? vertex_code : fragment_code; - if (code.empty()) { - std::fprintf(stderr, "cannot read %s\n", argv[1 + stage]); - return 1; - } - if (pc_tail && leonida::vk_test::spirv_declares_set(code.data(), code.size() * 4, leonida::vk_test::pc_tail_set)) - tail_block = true; - VkShaderModuleCreateInfo smi{VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO}; - smi.codeSize = code.size() * 4; - smi.pCode = code.data(); - CHECK(vkCreateShaderModule(dev, &smi, nullptr, &modules[stage])); - } - VkPipelineShaderStageCreateInfo stages[2]{{VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO}, - {VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO}}; - stages[0].stage = VK_SHADER_STAGE_VERTEX_BIT; - stages[0].module = modules[0]; - stages[0].pName = "main"; - stages[1].stage = VK_SHADER_STAGE_FRAGMENT_BIT; - stages[1].module = modules[1]; - stages[1].pName = "main"; - const VkPushConstantRange push{VK_SHADER_STAGE_VERTEX_BIT | VK_SHADER_STAGE_FRAGMENT_BIT, 0, push_bytes}; - VkPipelineLayoutCreateInfo pli{VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO}; - pli.setLayoutCount = 1; - pli.pSetLayouts = &dsl; - pli.pushConstantRangeCount = 1; - pli.pPushConstantRanges = &push; - leonida::vk_test::PcTail tail; - if (tail_block && !tail.create(vkGetDeviceProcAddr, dev, mp, props.limits.minUniformBufferOffsetAlignment, - VK_SHADER_STAGE_VERTEX_BIT | VK_SHADER_STAGE_FRAGMENT_BIT, 1)) { - std::fprintf(stderr, "FAILED creating the --pc-tail-ubo block\n"); - return 1; - } - const VkDescriptorSetLayout set_layouts[] = {dsl, tail.set_layout}; - if (tail_block) { pli.setLayoutCount = 2; pli.pSetLayouts = set_layouts; } - VkPipelineLayout pipeline_layout; - CHECK(vkCreatePipelineLayout(dev, &pli, nullptr, &pipeline_layout)); - const VkPipelineVertexInputStateCreateInfo vertex_input{VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO}; - VkPipelineInputAssemblyStateCreateInfo assembly{VK_STRUCTURE_TYPE_PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO}; - assembly.topology = VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST; - const VkViewport viewport{0, 0, float(W), float(H), 0, 1}; - const VkRect2D scissor{{0, 0}, {W, H}}; - VkPipelineViewportStateCreateInfo viewports{VK_STRUCTURE_TYPE_PIPELINE_VIEWPORT_STATE_CREATE_INFO}; - viewports.viewportCount = 1; - viewports.pViewports = &viewport; - viewports.scissorCount = 1; - viewports.pScissors = &scissor; - VkPipelineRasterizationStateCreateInfo raster{VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_STATE_CREATE_INFO}; - raster.cullMode = VK_CULL_MODE_NONE; - raster.lineWidth = 1; - VkPipelineMultisampleStateCreateInfo multisample{VK_STRUCTURE_TYPE_PIPELINE_MULTISAMPLE_STATE_CREATE_INFO}; - multisample.rasterizationSamples = VK_SAMPLE_COUNT_1_BIT; - VkPipelineColorBlendAttachmentState blend_attachment{}; - blend_attachment.colorWriteMask = 0xf; - VkPipelineColorBlendStateCreateInfo blend{VK_STRUCTURE_TYPE_PIPELINE_COLOR_BLEND_STATE_CREATE_INFO}; - blend.attachmentCount = 1; - blend.pAttachments = &blend_attachment; - VkGraphicsPipelineCreateInfo gpi{VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO}; - gpi.stageCount = 2; - gpi.pStages = stages; - gpi.pVertexInputState = &vertex_input; - gpi.pInputAssemblyState = &assembly; - gpi.pViewportState = &viewports; - gpi.pRasterizationState = &raster; - gpi.pMultisampleState = &multisample; - gpi.pColorBlendState = &blend; - gpi.layout = pipeline_layout; - gpi.renderPass = pass; - VkPipeline pipeline; - CHECK(vkCreateGraphicsPipelines(dev, VK_NULL_HANDLE, 1, &gpi, nullptr, &pipeline)); - VkBuffer readback; - void* readback_map; - CHECK(make_buffer(VkDeviceSize(W) * H * 16, VK_BUFFER_USAGE_TRANSFER_DST_BIT, &readback, &readback_map)); - - // Upload every level, draw once, read back. - VkCommandPoolCreateInfo cpi{VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO}; - cpi.queueFamilyIndex = qi; - VkCommandPool pool; - CHECK(vkCreateCommandPool(dev, &cpi, nullptr, &pool)); - VkCommandBufferAllocateInfo cai{VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO}; - cai.commandPool = pool; - cai.commandBufferCount = 1; - VkCommandBuffer cmd; - CHECK(vkAllocateCommandBuffers(dev, &cai, &cmd)); - const VkCommandBufferBeginInfo begin{VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO}; - CHECK(vkBeginCommandBuffer(cmd, &begin)); - for (int t = 0; t < 2; ++t) { - const std::uint32_t mips = t ? levels : 1; - VkImageMemoryBarrier ib{VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER}; - ib.oldLayout = VK_IMAGE_LAYOUT_UNDEFINED; - ib.newLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL; - ib.image = t ? texture : fallback; - ib.subresourceRange = {VK_IMAGE_ASPECT_COLOR_BIT, 0, mips, 0, 1}; - ib.dstAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT; - ib.srcQueueFamilyIndex = ib.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; - vkCmdPipelineBarrier(cmd, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, 0, 0, nullptr, 0, nullptr, 1, &ib); - VkDeviceSize offset = t ? texture_offset : 0; - for (std::uint32_t level = 0; level < mips; ++level) { - const std::uint32_t side = t ? TW >> level : 1; - VkBufferImageCopy c{}; - c.bufferOffset = offset; - c.imageSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, level, 0, 1}; - c.imageExtent = {side, side, 1}; - vkCmdCopyBufferToImage(cmd, upload, ib.image, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, &c); - offset += VkDeviceSize(side) * side * 4; - } - ib.oldLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL; - ib.newLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL; - ib.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT; - ib.dstAccessMask = VK_ACCESS_SHADER_READ_BIT; - vkCmdPipelineBarrier(cmd, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT, 0, 0, nullptr, 0, nullptr, 1, &ib); - } - VkClearValue clear{}; - for (float& channel : clear.color.float32) channel = -1.0f; // no texel holds this - VkRenderPassBeginInfo rbi{VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO}; - rbi.renderPass = pass; - rbi.framebuffer = framebuffer; - rbi.renderArea = scissor; - rbi.clearValueCount = 1; - rbi.pClearValues = &clear; - vkCmdBeginRenderPass(cmd, &rbi, VK_SUBPASS_CONTENTS_INLINE); - vkCmdBindPipeline(cmd, VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline); - vkCmdBindDescriptorSets(cmd, VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline_layout, 0, 1, &ds, 0, nullptr); - std::uint32_t block[36] = {}; - block[0] = table_va; // s0:s1 = console VA of the T# (the shader's s1 stays 0) - block[32] = std::uint32_t(heap_base); - block[33] = std::uint32_t(heap_base >> 32); - vkCmdPushConstants(cmd, pipeline_layout, VK_SHADER_STAGE_VERTEX_BIT | VK_SHADER_STAGE_FRAGMENT_BIT, 0, push_bytes, block); - if (tail_block) { - tail.write(0, block, 4); - const std::uint32_t offset = tail.offset(0); - vkCmdBindDescriptorSets(cmd, VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline_layout, leonida::vk_test::pc_tail_set, 1, - &tail.set, 1, &offset); - } - vkCmdDraw(cmd, 3, 1, 0, 0); - vkCmdEndRenderPass(cmd); - VkBufferImageCopy rc{}; - rc.imageSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1}; - rc.imageExtent = {W, H, 1}; - vkCmdCopyImageToBuffer(cmd, target, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, readback, 1, &rc); - CHECK(vkEndCommandBuffer(cmd)); - VkSubmitInfo si{VK_STRUCTURE_TYPE_SUBMIT_INFO}; - si.commandBufferCount = 1; - si.pCommandBuffers = &cmd; - CHECK(vkQueueSubmit(queue, 1, &si, VK_NULL_HANDLE)); - CHECK(vkQueueWaitIdle(queue)); - std::ofstream output(argv[3], std::ios::binary); - output.write(static_cast(readback_map), std::streamsize(W) * H * 16); - output.close(); - if (!output) { - std::fprintf(stderr, "failed to write %s\n", argv[3]); - return 1; - } - std::printf("ok -> %s\n", argv[3]); - return 0; -} diff --git a/runtime/test/vk_sandbox.cpp b/runtime/test/vk_sandbox.cpp deleted file mode 100644 index 7ae9e8db6..000000000 --- a/runtime/test/vk_sandbox.cpp +++ /dev/null @@ -1,739 +0,0 @@ -// Real-shader sandbox: draws a tools/sandbox_scene.py scene through two translated game shaders. -// -// vk_sandbox --out [--size W H] [--cam x y z yaw pitch] [--fov deg] -// vk_sandbox --window [--size W H] [--cam ...] [--mode fly|walk|drive] (Windows only) -// --window --frames N --out : test run, the window shows without activation and quits after N frames -// -// The pair (chosen by tools/sandbox.py) is a transform VS with POSITION/NORMAL/TEXCOORD inputs and a textured PS, both reading user SGPR 8: -// a 32-bit pointer (high dword forced to 0) to one table of descriptors in the heap, laid out as the shaders load it: -// +0x00 V# of the object constants: world rows 0..2 at 0x00/0x10/0x20, translation at 0x30 -// +0x20 T# of the albedo texture (8 dwords) -// +0x40 V# of the view constants: light direction at 0xa0, view-projection rows at 0x160 (row-vector convention) -// +0x60 V# of the colour constants: rgba at 0x00 -// Every draw gets its own table and object constants; view and colour constants are shared. The PS samples with the -// S# literal in its own code, so the sampler is built from those words (gfx10::decode). Nothing here is game data: -// the scene file and the shaders come from the user's work folder. -// -// Window keys (only while the window has focus): WASD move, mouse with the right button held looks, Q/E down/up, -// Shift faster, 1 fly, 2 walk (eye 1.7 m over the ground under the camera), 3 drive (eye 1.2 m, accelerates), -// P writes sandbox_shot.ppm, Esc quits. -#define VK_NO_PROTOTYPES -#ifdef _WIN32 -#define VK_USE_PLATFORM_WIN32_KHR -#include -#endif -#include "vulkan_loader.h" -#include "vk_device_pick.h" - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include "../src/descriptor_table.h" -#include "../src/gfx10_descriptors.h" - -static PFN_vkGetInstanceProcAddr gipa; -#define CHECK(x) \ - do { \ - VkResult r_ = (x); \ - if (r_ != VK_SUCCESS) { \ - std::fprintf(stderr, "FAILED %s -> %d (line %d)\n", #x, r_, __LINE__); \ - return 1; \ - } \ - } while (0) - -namespace { - -struct Texture { uint32_t w, h; std::vector rgba; }; -struct Mesh { uint32_t first_vertex, vertex_count, first_index, index_count; }; -struct Draw { uint32_t mesh; int32_t texture; float rows[4][3]; }; -struct Scene { - std::vector textures; - std::vector meshes; - std::vector draws; - std::vector vertices; // 8 floats each - std::vector indices; - float center[3]; -}; - -bool load_scene(const char* path, Scene& s) { - std::ifstream f(path, std::ios::binary | std::ios::ate); - const uint64_t file_size = f ? uint64_t(f.tellg()) : 0; - f.seekg(0); - char magic[4]; - uint32_t hdr[4]; - if (!f.read(magic, 4) || std::memcmp(magic, "LSB1", 4) || !f.read(reinterpret_cast(hdr), 16) || - hdr[0] != 1 || !f.read(reinterpret_cast(s.center), 12)) - return false; - for (uint32_t i = 0; i < hdr[1]; ++i) { - Texture t; - f.read(reinterpret_cast(&t.w), 4).read(reinterpret_cast(&t.h), 4); - if (!f || !t.w || !t.h || t.w > 16384 || t.h > 16384 || uint64_t(t.w) * t.h * 4 > file_size) return false; - t.rgba.resize(size_t(t.w) * t.h * 4); - f.read(reinterpret_cast(t.rgba.data()), std::streamsize(t.rgba.size())); - s.textures.push_back(std::move(t)); - } - for (uint32_t i = 0; i < hdr[2]; ++i) { - uint32_t vc = 0, ic = 0; - f.read(reinterpret_cast(&vc), 4).read(reinterpret_cast(&ic), 4); - if (!f || uint64_t(vc) * 32 + uint64_t(ic) * 4 > file_size) return false; - Mesh m{uint32_t(s.vertices.size() / 8), vc, uint32_t(s.indices.size()), ic}; - s.vertices.resize(s.vertices.size() + size_t(vc) * 8); - s.indices.resize(s.indices.size() + ic); - f.read(reinterpret_cast(s.vertices.data() + size_t(m.first_vertex) * 8), std::streamsize(vc) * 32); - f.read(reinterpret_cast(s.indices.data() + m.first_index), std::streamsize(ic) * 4); - if (!f) return false; - for (uint32_t k = 0; k < ic; ++k) - if (s.indices[m.first_index + k] >= vc) return false; - s.meshes.push_back(m); - } - for (uint32_t i = 0; i < hdr[3]; ++i) { - Draw d; - f.read(reinterpret_cast(&d), sizeof(d)); - if (!f || d.mesh >= s.meshes.size() || d.texture >= int32_t(s.textures.size())) return false; - s.draws.push_back(d); - } - return bool(f); -} - -std::vector read_spv(const char* p) { - std::ifstream f(p, std::ios::binary); - std::vector b((std::istreambuf_iterator(f)), {}); - std::vector w(b.size() / 4); - std::memcpy(w.data(), b.data(), w.size() * 4); - return w; -} - -struct Camera { - float pos[3], yaw = 0, pitch = 0, fov = 70, speed = 0; - int mode = 0; // 0 fly, 1 walk, 2 drive - void forward(float f[3]) const { - f[0] = std::cos(pitch) * std::cos(yaw); f[1] = std::cos(pitch) * std::sin(yaw); f[2] = std::sin(pitch); - } -}; - -// clip = wx*row0 + wy*row1 + wz*row2 + row3 (D3D clip space: y up, z 0..1), stored as 16 floats. -void view_projection(const Camera& c, float aspect, float out[16]) { - float f[3]; c.forward(f); - float r[3] = {f[1], -f[0], 0}; - const float rl = std::sqrt(r[0] * r[0] + r[1] * r[1]); - if (rl < 1e-6f) { r[0] = std::sin(c.yaw); r[1] = -std::cos(c.yaw); } else { r[0] /= rl; r[1] /= rl; } - const float u[3] = {r[1] * f[2] - r[2] * f[1], r[2] * f[0] - r[0] * f[2], r[0] * f[1] - r[1] * f[0]}; - const float n = 0.1f, fa = 5000.f, sy = 1.f / std::tan(c.fov * 3.14159265f / 360.f), sx = sy / aspect; - const float A = fa / (fa - n), B = -n * fa / (fa - n); - // view = (dot(w - p, r), dot(w - p, u), dot(w - p, f)); clip = (vx*sx, vy*sy, vz*A + B, vz) - const float* axes[3] = {r, u, f}; - const float scale[4] = {sx, sy, A, 1}; - for (int k = 0; k < 4; ++k) { - const float* a = axes[k < 3 ? k : 2]; - for (int j = 0; j < 3; ++j) out[j * 4 + k] = a[j] * scale[k]; - out[12 + k] = -(a[0] * c.pos[0] + a[1] * c.pos[1] + a[2] * c.pos[2]) * scale[k] + (k == 2 ? B : 0); - } -} - -// Ground under a point: highest scene triangle below z + 1 at (x, y), from a 4 m grid built once. -struct Ground { - float cell = 4, x0 = 0, y0 = 0; - int nx = 0, ny = 0; - std::vector> tris; // per cell: 9 floats a triangle - void build(const Scene& s) { - float lo[2] = {1e30f, 1e30f}, hi[2] = {-1e30f, -1e30f}; - std::vector all; - for (const Draw& d : s.draws) { - const Mesh& m = s.meshes[d.mesh]; - for (uint32_t i = 0; i + 2 < m.index_count; i += 3) - for (int k = 0; k < 3; ++k) { - const float* v = &s.vertices[size_t(m.first_vertex + s.indices[m.first_index + i + k]) * 8]; - for (int j = 0; j < 3; ++j) { - const float w = v[0] * d.rows[0][j] + v[1] * d.rows[1][j] + v[2] * d.rows[2][j] + d.rows[3][j]; - all.push_back(w); - if (j < 2) { lo[j] = std::min(lo[j], w); hi[j] = std::max(hi[j], w); } - } - } - } - if (all.empty()) return; - x0 = lo[0]; y0 = lo[1]; - nx = std::min(4096, int((hi[0] - lo[0]) / cell) + 1); ny = std::min(4096, int((hi[1] - lo[1]) / cell) + 1); - tris.assign(size_t(nx) * ny, {}); - for (size_t t = 0; t < all.size(); t += 9) { - const float* p = &all[t]; - const float ax = std::min({p[0], p[3], p[6]}), bx = std::max({p[0], p[3], p[6]}); - const float ay = std::min({p[1], p[4], p[7]}), by = std::max({p[1], p[4], p[7]}); - if (bx - ax > 64 || by - ay > 64) continue; // skip huge sheets (skydomes, water planes) - for (int cy = std::max(0, int(std::floor((ay - y0) / cell))); cy <= std::min(ny - 1, int(std::floor((by - y0) / cell))); ++cy) - for (int cx = std::max(0, int(std::floor((ax - x0) / cell))); cx <= std::min(nx - 1, int(std::floor((bx - x0) / cell))); ++cx) - tris[size_t(cy) * nx + cx].insert(tris[size_t(cy) * nx + cx].end(), p, p + 9); - } - } - bool height(float x, float y, float below, float& out) const { - const int cx = int(std::floor((x - x0) / cell)), cy = int(std::floor((y - y0) / cell)); - if (cx < 0 || cy < 0 || cx >= nx || cy >= ny) return false; - bool hit = false; - const auto& v = tris[size_t(cy) * nx + cx]; - for (size_t t = 0; t < v.size(); t += 9) { - const float* p = &v[t]; - const float d = (p[3] - p[0]) * (p[7] - p[1]) - (p[6] - p[0]) * (p[4] - p[1]); - if (std::fabs(d) < 1e-9f) continue; - const float a = ((p[3] - x) * (p[7] - y) - (p[6] - x) * (p[4] - y)) / d; - const float b = ((p[6] - x) * (p[1] - y) - (p[0] - x) * (p[7] - y)) / d; - const float c = 1 - a - b; - if (a < 0 || b < 0 || c < 0) continue; - const float z = a * p[2] + b * p[5] + c * p[8]; - if (z <= below && (!hit || z > out)) { out = z; hit = true; } - } - return hit; - } -}; - -#ifdef _WIN32 -bool g_quit = false, g_look = false; -int g_mx = 0, g_my = 0, g_dx = 0, g_dy = 0; -LRESULT CALLBACK wndproc(HWND h, UINT m, WPARAM w, LPARAM l) { - switch (m) { - case WM_CLOSE: g_quit = true; return 0; - case WM_RBUTTONDOWN: g_look = true; g_mx = short(LOWORD(l)); g_my = short(HIWORD(l)); SetCapture(h); return 0; - case WM_RBUTTONUP: g_look = false; ReleaseCapture(); return 0; - case WM_MOUSEMOVE: - if (g_look) { const int x = short(LOWORD(l)), y = short(HIWORD(l)); g_dx += x - g_mx; g_dy += y - g_my; g_mx = x; g_my = y; } - return 0; - } - return DefWindowProcW(h, m, w, l); -} -#endif - -bool write_ppm(const char* path, const uint8_t* bgra_or_rgba, uint32_t w, uint32_t h, bool bgra) { - std::ofstream o(path, std::ios::binary); - o << "P6\n" << w << " " << h << "\n255\n"; - for (size_t i = 0; i < size_t(w) * h; ++i) { - const uint8_t* p = bgra_or_rgba + i * 4; - const char px[3] = {char(p[bgra ? 2 : 0]), char(p[1]), char(p[bgra ? 0 : 2])}; - o.write(px, 3); - } - return bool(o); -} - -} // namespace - -int main(int argc, char** argv) { - if (argc < 4) { - std::fprintf(stderr, "usage: vk_sandbox scene.bin vs.spv ps.spv (--out image.ppm | --window) [--size W H] " - "[--cam x y z yaw pitch] [--fov deg]\n"); - return 2; - } - Scene scene; - if (!load_scene(argv[1], scene)) { std::fprintf(stderr, "bad scene file %s\n", argv[1]); return 2; } - uint32_t W = 1280, H = 720; - const char* out_path = nullptr; - bool window = false; - int frames = 0; // --frames N: window test run, shown without activation, quits after N frames - Camera cam{}; - cam.pos[0] = scene.center[0] - 40; cam.pos[1] = scene.center[1] - 40; cam.pos[2] = scene.center[2] + 25; - cam.yaw = 0.785398f; cam.pitch = -0.35f; - for (int i = 4; i < argc; ++i) { - if (!std::strcmp(argv[i], "--out") && i + 1 < argc) out_path = argv[++i]; - else if (!std::strcmp(argv[i], "--window")) window = true; - else if (!std::strcmp(argv[i], "--frames") && i + 1 < argc) frames = std::atoi(argv[++i]); - else if (!std::strcmp(argv[i], "--mode") && i + 1 < argc) { - const char* m = argv[++i]; - cam.mode = !std::strcmp(m, "walk") ? 1 : !std::strcmp(m, "drive") ? 2 : 0; - } - else if (!std::strcmp(argv[i], "--size") && i + 2 < argc) { W = std::atoi(argv[++i]); H = std::atoi(argv[++i]); } - else if (!std::strcmp(argv[i], "--fov") && i + 1 < argc) cam.fov = float(std::atof(argv[++i])); - else if (!std::strcmp(argv[i], "--cam") && i + 5 < argc) { - for (int k = 0; k < 3; ++k) cam.pos[k] = float(std::atof(argv[++i])); - cam.yaw = float(std::atof(argv[++i])) * 3.14159265f / 180; cam.pitch = float(std::atof(argv[++i])) * 3.14159265f / 180; - } else { std::fprintf(stderr, "unknown argument %s\n", argv[i]); return 2; } - } -#ifndef _WIN32 - if (window) { std::fprintf(stderr, "--window needs Windows\n"); return 2; } -#endif - if (window && frames && !out_path) { std::fprintf(stderr, "--frames needs --out\n"); return 2; } - if (!out_path && !window) { std::fprintf(stderr, "give --out or --window\n"); return 2; } - std::fprintf(stderr, "scene: %zu draws, %zu meshes, %zu textures, %zu triangles\n", scene.draws.size(), - scene.meshes.size(), scene.textures.size(), scene.indices.size() / 3); - - gipa = load_vulkan(); - if (!gipa) { std::fprintf(stderr, "the Vulkan loader was not found\n"); return 77; } - VkInstance inst = VK_NULL_HANDLE; -#define LI(n) auto n = reinterpret_cast(gipa(inst, #n)) - LI(vkCreateInstance); - VkApplicationInfo app{VK_STRUCTURE_TYPE_APPLICATION_INFO}; app.apiVersion = VK_API_VERSION_1_2; - const char* inst_ext[2] = {"VK_KHR_surface", "VK_KHR_win32_surface"}; - VkInstanceCreateInfo ici{VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO}; ici.pApplicationInfo = &app; - if (window) { ici.enabledExtensionCount = 2; ici.ppEnabledExtensionNames = inst_ext; } - if (vkCreateInstance(&ici, nullptr, &inst) != VK_SUCCESS) { std::fprintf(stderr, "unsupported: no Vulkan instance\n"); return 77; } - LI(vkEnumeratePhysicalDevices); LI(vkGetPhysicalDeviceProperties); LI(vkGetPhysicalDeviceQueueFamilyProperties); - LI(vkGetPhysicalDeviceMemoryProperties); LI(vkCreateDevice); LI(vkGetDeviceProcAddr); - uint32_t n = 0; - CHECK(vkEnumeratePhysicalDevices(inst, &n, nullptr)); - if (!n) { std::fprintf(stderr, "unsupported: no Vulkan physical device\n"); return 77; } - std::vector pds(n); - CHECK(vkEnumeratePhysicalDevices(inst, &n, pds.data())); - // The shared pick, so LEONIDA_VK_DEVICE names the GPU here too (vk_device_pick.h, docs/testing.md). - std::vector candidates(n); - for (uint32_t i = 0; i < n; ++i) vkGetPhysicalDeviceProperties(pds[i], &candidates[i]); - const std::size_t chosen = leonida::vk_test::pick_device(candidates); - if (chosen == candidates.size()) { leonida::vk_test::report_no_device(); return 1; } - VkPhysicalDevice pd = pds[chosen]; - const VkPhysicalDeviceProperties props = candidates[chosen]; - constexpr uint32_t push_words = 36, push_bytes = push_words * 4; - if (props.limits.maxPushConstantsSize < push_bytes) { std::fprintf(stderr, "unsupported: push constants\n"); return 77; } - std::fprintf(stderr, "device: %s\n", props.deviceName); - uint32_t qn = 0; vkGetPhysicalDeviceQueueFamilyProperties(pd, &qn, nullptr); - std::vector qf(qn); vkGetPhysicalDeviceQueueFamilyProperties(pd, &qn, qf.data()); - uint32_t qi = 0; - while (qi < qn && !(qf[qi].queueFlags & VK_QUEUE_GRAPHICS_BIT)) ++qi; - if (qi == qn) { std::fprintf(stderr, "unsupported: no graphics queue\n"); return 77; } - -#ifdef _WIN32 - HWND hwnd = nullptr; - VkSurfaceKHR surface = VK_NULL_HANDLE; - if (window) { - WNDCLASSW wc{}; wc.lpfnWndProc = wndproc; wc.hInstance = GetModuleHandleW(nullptr); wc.lpszClassName = L"vk_sandbox"; - wc.hCursor = LoadCursor(nullptr, IDC_ARROW); - RegisterClassW(&wc); - RECT rc{0, 0, LONG(W), LONG(H)}; AdjustWindowRect(&rc, WS_OVERLAPPEDWINDOW, FALSE); - hwnd = CreateWindowExW(0, L"vk_sandbox", L"Leonida real-shader sandbox", WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, - CW_USEDEFAULT, rc.right - rc.left, rc.bottom - rc.top, nullptr, nullptr, wc.hInstance, nullptr); - ShowWindow(hwnd, frames ? SW_SHOWNOACTIVATE : SW_SHOWNORMAL); - LI(vkCreateWin32SurfaceKHR); - VkWin32SurfaceCreateInfoKHR sci{VK_STRUCTURE_TYPE_WIN32_SURFACE_CREATE_INFO_KHR}; - sci.hinstance = wc.hInstance; sci.hwnd = hwnd; - CHECK(vkCreateWin32SurfaceKHR(inst, &sci, nullptr, &surface)); - } -#endif - - float prio = 1; - VkDeviceQueueCreateInfo qci{VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO}; - qci.queueFamilyIndex = qi; qci.queueCount = 1; qci.pQueuePriorities = &prio; - VkPhysicalDeviceVulkan12Features f12{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_2_FEATURES}; - f12.bufferDeviceAddress = VK_TRUE; f12.runtimeDescriptorArray = VK_TRUE; f12.descriptorIndexing = VK_TRUE; - f12.shaderSampledImageArrayNonUniformIndexing = VK_TRUE; - VkPhysicalDeviceFeatures2 f2{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2}; f2.pNext = &f12; - f2.features.shaderInt64 = VK_TRUE; - const char* dev_ext[1] = {"VK_KHR_swapchain"}; - VkDeviceCreateInfo dci{VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO}; - dci.pNext = &f2; dci.queueCreateInfoCount = 1; dci.pQueueCreateInfos = &qci; - if (window) { dci.enabledExtensionCount = 1; dci.ppEnabledExtensionNames = dev_ext; } - VkDevice dev; CHECK(vkCreateDevice(pd, &dci, nullptr, &dev)); -#define LD(n) auto n = reinterpret_cast(vkGetDeviceProcAddr(dev, #n)) - LD(vkGetDeviceQueue); LD(vkCreateImage); LD(vkGetImageMemoryRequirements); LD(vkAllocateMemory); - LD(vkBindImageMemory); LD(vkCreateImageView); LD(vkCreateRenderPass); LD(vkCreateFramebuffer); - LD(vkCreateShaderModule); LD(vkCreatePipelineLayout); LD(vkCreateGraphicsPipelines); LD(vkCreateCommandPool); - LD(vkAllocateCommandBuffers); LD(vkBeginCommandBuffer); LD(vkCmdBeginRenderPass); LD(vkCmdBindPipeline); - LD(vkCmdDrawIndexed); LD(vkCmdEndRenderPass); LD(vkCmdCopyImageToBuffer); LD(vkCmdCopyBufferToImage); - LD(vkEndCommandBuffer); LD(vkQueueSubmit); LD(vkQueueWaitIdle); LD(vkCreateBuffer); LD(vkResetCommandBuffer); - LD(vkGetBufferMemoryRequirements); LD(vkBindBufferMemory); LD(vkMapMemory); LD(vkGetBufferDeviceAddress); - LD(vkCreateSampler); LD(vkCreateDescriptorSetLayout); LD(vkCreateDescriptorPool); LD(vkAllocateDescriptorSets); - LD(vkUpdateDescriptorSets); LD(vkCmdBindDescriptorSets); LD(vkCmdPushConstants); LD(vkCmdPipelineBarrier); - LD(vkCmdBindVertexBuffers); LD(vkCmdBindIndexBuffer); LD(vkCmdBlitImage); - VkQueue q; vkGetDeviceQueue(dev, qi, 0, &q); - VkPhysicalDeviceMemoryProperties mp; vkGetPhysicalDeviceMemoryProperties(pd, &mp); - auto memtype = [&](uint32_t bits, VkMemoryPropertyFlags want) { - for (uint32_t i = 0; i < mp.memoryTypeCount; i++) - if ((bits & (1u << i)) && (mp.memoryTypes[i].propertyFlags & want) == want) return i; - return 0u; - }; - auto make_buffer = [&](VkDeviceSize size, VkBufferUsageFlags usage, VkBuffer* b, void** map) { - VkBufferCreateInfo bi{VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO}; bi.size = size; bi.usage = usage; - VkResult r = vkCreateBuffer(dev, &bi, nullptr, b); if (r) return r; - VkMemoryRequirements mr; vkGetBufferMemoryRequirements(dev, *b, &mr); - VkMemoryAllocateFlagsInfo fi{VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_FLAGS_INFO}; fi.flags = VK_MEMORY_ALLOCATE_DEVICE_ADDRESS_BIT; - VkMemoryAllocateInfo ai{VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO}; ai.pNext = &fi; ai.allocationSize = mr.size; - ai.memoryTypeIndex = memtype(mr.memoryTypeBits, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT); - VkDeviceMemory m; r = vkAllocateMemory(dev, &ai, nullptr, &m); if (r) return r; - r = vkBindBufferMemory(dev, *b, m, 0); if (r) return r; - return vkMapMemory(dev, m, 0, size, 0, map); - }; - auto make_image = [&](uint32_t w, uint32_t h, VkFormat fmt, VkImageUsageFlags usage, VkImageAspectFlags aspect, - VkImage* img, VkImageView* view) { - VkImageCreateInfo ii{VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO}; - ii.imageType = VK_IMAGE_TYPE_2D; ii.format = fmt; ii.extent = {w, h, 1}; ii.mipLevels = 1; ii.arrayLayers = 1; - ii.samples = VK_SAMPLE_COUNT_1_BIT; ii.tiling = VK_IMAGE_TILING_OPTIMAL; ii.usage = usage; - VkResult r = vkCreateImage(dev, &ii, nullptr, img); if (r) return r; - VkMemoryRequirements mr; vkGetImageMemoryRequirements(dev, *img, &mr); - VkMemoryAllocateInfo ai{VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO}; ai.allocationSize = mr.size; - ai.memoryTypeIndex = memtype(mr.memoryTypeBits, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT); - VkDeviceMemory m; r = vkAllocateMemory(dev, &ai, nullptr, &m); if (r) return r; - r = vkBindImageMemory(dev, *img, m, 0); if (r) return r; - VkImageViewCreateInfo vi{VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO}; - vi.image = *img; vi.viewType = VK_IMAGE_VIEW_TYPE_2D; vi.format = fmt; vi.subresourceRange = {aspect, 0, 1, 0, 1}; - return vkCreateImageView(dev, &vi, nullptr, view); - }; - - // Heap: the Xbox GPU VA window. 0x1000 view constants, 0x1200 colour constants, then 0x80 per draw: the - // descriptor table at +0 (0x70 bytes used) and nothing else; object constants follow all tables. - const uint32_t view_va = 0x1000, colour_va = 0x1200, table_va = 0x2000; - const uint32_t ndraw = uint32_t(scene.draws.size()); - const uint32_t object_va = table_va + ndraw * 0x80; - const VkDeviceSize heap_bytes = object_va + VkDeviceSize(ndraw) * 0x40 + 0x1000; - VkBuffer heap; void* heapp; - CHECK(make_buffer(heap_bytes, VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT, &heap, &heapp)); - std::memset(heapp, 0, size_t(heap_bytes)); - auto heap_u32 = [&](uint32_t va) { return reinterpret_cast(static_cast(heapp) + va); }; - auto heap_f32 = [&](uint32_t va) { return reinterpret_cast(static_cast(heapp) + va); }; - VkBufferDeviceAddressInfo bdai{VK_STRUCTURE_TYPE_BUFFER_DEVICE_ADDRESS_INFO}; bdai.buffer = heap; - const VkDeviceAddress heap_base = vkGetBufferDeviceAddress(dev, &bdai); - // A raw V#: base in word0/word1[15:0], stride 0, NUM_RECORDS bytes, OOB_SELECT 3 (raw byte range). - auto vsharp = [&](uint32_t at, uint32_t base, uint32_t bytes) { - uint32_t* p = heap_u32(at); p[0] = base; p[1] = 0; p[2] = bytes; p[3] = 3u << 28; - }; - // T# keys: unique words per texture with the RGBA8 UNORM format in word 1 (the numeric type the shader reads). - const uint32_t fmt_word = leonida::gfx10::format_from_vulkan(VK_FORMAT_R8G8B8A8_UNORM) << 20; - auto tsharp = [&](uint32_t image) { - std::array t{0x5A000000u | image, fmt_word, 0x7FF7FFu, 0, 0, 0, 0, 0}; - return t; - }; - const uint32_t nimg = uint32_t(scene.textures.size()) + 1; // image 0: 1x1 white for untextured draws - leonida::DescriptorTable table(2 * (nimg + 2)); - for (uint32_t i = 0; i < nimg; ++i) table.insert(tsharp(i).data(), i); - uint32_t ssharp[8] = {1024, 12582912, 418381824, 0, 0xFFFFFFFFu, 0xFFFFFFFFu, 0xFFFFFFFFu, 0xFFFFFFFFu}; // the PS's literal S# - table.insert(ssharp, 0); - for (uint32_t d = 0; d < ndraw; ++d) { - const Draw& dr = scene.draws[d]; - const uint32_t t = table_va + d * 0x80, o = object_va + d * 0x40; - vsharp(t + 0x00, o, 0x40); - const auto ts = tsharp(dr.texture < 0 ? 0 : uint32_t(dr.texture) + 1); - std::memcpy(heap_u32(t + 0x20), ts.data(), 32); - vsharp(t + 0x40, view_va, 0x1a0); - vsharp(t + 0x60, colour_va, 0x10); - float* ob = heap_f32(o); - for (int r = 0; r < 4; ++r) for (int j = 0; j < 3; ++j) ob[r * 4 + j] = dr.rows[r][j]; - } - float* colour = heap_f32(colour_va); colour[0] = colour[1] = colour[2] = colour[3] = 1; - float* light = heap_f32(view_va + 0xa0); - { const float l[3] = {-0.55f, -0.45f, 0.7f}; const float ln = std::sqrt(l[0] * l[0] + l[1] * l[1] + l[2] * l[2]); - for (int k = 0; k < 3; ++k) light[k] = l[k] / ln; } - const auto gpu_table = table.build_gpu_buffer(true); - VkBuffer tb; void* tbp; - CHECK(make_buffer(gpu_table.size() * 4, VK_BUFFER_USAGE_STORAGE_BUFFER_BIT, &tb, &tbp)); - std::memcpy(tbp, gpu_table.data(), gpu_table.size() * 4); - - // Geometry. - VkBuffer vb, ib; void* vbp; void* ibp; - CHECK(make_buffer(std::max(32, scene.vertices.size() * 4), VK_BUFFER_USAGE_VERTEX_BUFFER_BIT, &vb, &vbp)); - CHECK(make_buffer(std::max(4, scene.indices.size() * 4), VK_BUFFER_USAGE_INDEX_BUFFER_BIT, &ib, &ibp)); - std::memcpy(vbp, scene.vertices.data(), scene.vertices.size() * 4); - std::memcpy(ibp, scene.indices.data(), scene.indices.size() * 4); - - // Textures. - std::vector timg(nimg); std::vector tview(nimg); - VkDeviceSize up_bytes = 4; - for (const auto& t : scene.textures) up_bytes += t.rgba.size(); - VkBuffer up; void* upp; - CHECK(make_buffer(up_bytes, VK_BUFFER_USAGE_TRANSFER_SRC_BIT, &up, &upp)); - std::vector up_off(nimg); - { const uint32_t white = 0xFFFFFFFFu; std::memcpy(upp, &white, 4); VkDeviceSize at = 4; - for (uint32_t i = 1; i < nimg; ++i) { up_off[i] = at; std::memcpy(static_cast(upp) + at, scene.textures[i - 1].rgba.data(), scene.textures[i - 1].rgba.size()); at += scene.textures[i - 1].rgba.size(); } } - for (uint32_t i = 0; i < nimg; ++i) - CHECK(make_image(i ? scene.textures[i - 1].w : 1, i ? scene.textures[i - 1].h : 1, VK_FORMAT_R8G8B8A8_UNORM, - VK_IMAGE_USAGE_SAMPLED_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT, VK_IMAGE_ASPECT_COLOR_BIT, &timg[i], &tview[i])); - VkSamplerCreateInfo sci = leonida::gfx10::vulkan_sampler(leonida::gfx10::decode( - leonida::gfx10::SamplerWords{ssharp[0], ssharp[1], ssharp[2], ssharp[3]})); - sci.maxLod = 0; // the scene stores mip 0 only - VkSampler smp; CHECK(vkCreateSampler(dev, &sci, nullptr, &smp)); - - // Targets: RGBA8 colour + D32 depth. - const VkFormat cfmt = VK_FORMAT_R8G8B8A8_UNORM, dfmt = VK_FORMAT_D32_SFLOAT; - VkImage rt, dt; VkImageView rtv, dtv; - CHECK(make_image(W, H, cfmt, VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | VK_IMAGE_USAGE_TRANSFER_SRC_BIT, VK_IMAGE_ASPECT_COLOR_BIT, &rt, &rtv)); - CHECK(make_image(W, H, dfmt, VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT, VK_IMAGE_ASPECT_DEPTH_BIT, &dt, &dtv)); - VkAttachmentDescription ad[2]{}; - ad[0].format = cfmt; ad[0].samples = VK_SAMPLE_COUNT_1_BIT; ad[0].loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR; - ad[0].storeOp = VK_ATTACHMENT_STORE_OP_STORE; ad[0].stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE; - ad[0].stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE; - ad[0].initialLayout = VK_IMAGE_LAYOUT_UNDEFINED; ad[0].finalLayout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL; - ad[1] = ad[0]; ad[1].format = dfmt; ad[1].storeOp = VK_ATTACHMENT_STORE_OP_DONT_CARE; - ad[1].finalLayout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL; - VkAttachmentReference car{0, VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL}, dar{1, VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL}; - VkSubpassDescription sd{}; sd.pipelineBindPoint = VK_PIPELINE_BIND_POINT_GRAPHICS; - sd.colorAttachmentCount = 1; sd.pColorAttachments = &car; sd.pDepthStencilAttachment = &dar; - VkSubpassDependency dep{0, VK_SUBPASS_EXTERNAL, VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT, - VK_PIPELINE_STAGE_TRANSFER_BIT, VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT, VK_ACCESS_TRANSFER_READ_BIT}; - VkRenderPassCreateInfo rpi{VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO}; - rpi.attachmentCount = 2; rpi.pAttachments = ad; rpi.subpassCount = 1; rpi.pSubpasses = &sd; - rpi.dependencyCount = 1; rpi.pDependencies = &dep; - VkRenderPass rp; CHECK(vkCreateRenderPass(dev, &rpi, nullptr, &rp)); - VkImageView fbv[2] = {rtv, dtv}; - VkFramebufferCreateInfo fbi{VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO}; - fbi.renderPass = rp; fbi.attachmentCount = 2; fbi.pAttachments = fbv; fbi.width = W; fbi.height = H; fbi.layers = 1; - VkFramebuffer fb; CHECK(vkCreateFramebuffer(dev, &fbi, nullptr, &fb)); - - // Descriptor set: binding 0 images[], 1 samplers[], 2 the descriptor hash table. - VkDescriptorSetLayoutBinding b[3]{}; - b[0] = {0, VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE, nimg, VK_SHADER_STAGE_FRAGMENT_BIT | VK_SHADER_STAGE_VERTEX_BIT, nullptr}; - b[1] = {1, VK_DESCRIPTOR_TYPE_SAMPLER, 1, VK_SHADER_STAGE_FRAGMENT_BIT | VK_SHADER_STAGE_VERTEX_BIT, nullptr}; - b[2] = {2, VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, 1, VK_SHADER_STAGE_FRAGMENT_BIT | VK_SHADER_STAGE_VERTEX_BIT, nullptr}; - VkDescriptorSetLayoutCreateInfo dli{VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO}; dli.bindingCount = 3; dli.pBindings = b; - VkDescriptorSetLayout dsl; CHECK(vkCreateDescriptorSetLayout(dev, &dli, nullptr, &dsl)); - VkDescriptorPoolSize ps[3]{{VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE, nimg}, {VK_DESCRIPTOR_TYPE_SAMPLER, 1}, {VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, 1}}; - VkDescriptorPoolCreateInfo dpi{VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO}; dpi.maxSets = 1; dpi.poolSizeCount = 3; dpi.pPoolSizes = ps; - VkDescriptorPool dp; CHECK(vkCreateDescriptorPool(dev, &dpi, nullptr, &dp)); - VkDescriptorSetAllocateInfo dai{VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO}; dai.descriptorPool = dp; dai.descriptorSetCount = 1; dai.pSetLayouts = &dsl; - VkDescriptorSet ds; CHECK(vkAllocateDescriptorSets(dev, &dai, &ds)); - std::vector iinfo(nimg); - for (uint32_t i = 0; i < nimg; ++i) iinfo[i] = {VK_NULL_HANDLE, tview[i], VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL}; - VkDescriptorImageInfo sinfo{smp}; - VkDescriptorBufferInfo tinfo{tb, 0, VK_WHOLE_SIZE}; - VkWriteDescriptorSet wr[3]{}; - for (auto& w : wr) { w.sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET; w.dstSet = ds; } - wr[0].dstBinding = 0; wr[0].descriptorCount = nimg; wr[0].descriptorType = VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE; wr[0].pImageInfo = iinfo.data(); - wr[1].dstBinding = 1; wr[1].descriptorCount = 1; wr[1].descriptorType = VK_DESCRIPTOR_TYPE_SAMPLER; wr[1].pImageInfo = &sinfo; - wr[2].dstBinding = 2; wr[2].descriptorCount = 1; wr[2].descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER; wr[2].pBufferInfo = &tinfo; - vkUpdateDescriptorSets(dev, 3, wr, 0, nullptr); - - // Pipeline: the translated VS and PS, vertices (pos, normal, uv) at locations 0..2, depth test, no culling. - auto module = [&](const char* p, VkShaderModule* m) { - auto code = read_spv(p); - if (code.empty()) { std::fprintf(stderr, "cannot read %s\n", p); return VK_ERROR_INITIALIZATION_FAILED; } - VkShaderModuleCreateInfo smi{VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO}; smi.codeSize = code.size() * 4; smi.pCode = code.data(); - return vkCreateShaderModule(dev, &smi, nullptr, m); - }; - VkShaderModule vs, fs; CHECK(module(argv[2], &vs)); CHECK(module(argv[3], &fs)); - VkPipelineShaderStageCreateInfo st[2]{{VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO}, {VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO}}; - st[0].stage = VK_SHADER_STAGE_VERTEX_BIT; st[0].module = vs; st[0].pName = "main"; - st[1].stage = VK_SHADER_STAGE_FRAGMENT_BIT; st[1].module = fs; st[1].pName = "main"; - VkPushConstantRange pcr{VK_SHADER_STAGE_FRAGMENT_BIT | VK_SHADER_STAGE_VERTEX_BIT, 0, push_bytes}; - VkPipelineLayoutCreateInfo pli{VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO}; - pli.setLayoutCount = 1; pli.pSetLayouts = &dsl; pli.pushConstantRangeCount = 1; pli.pPushConstantRanges = &pcr; - VkPipelineLayout pl; CHECK(vkCreatePipelineLayout(dev, &pli, nullptr, &pl)); - VkVertexInputBindingDescription vbd{0, 32, VK_VERTEX_INPUT_RATE_VERTEX}; - VkVertexInputAttributeDescription vad[3]{{0, 0, VK_FORMAT_R32G32B32_SFLOAT, 0}, {1, 0, VK_FORMAT_R32G32B32_SFLOAT, 12}, - {2, 0, VK_FORMAT_R32G32_SFLOAT, 24}}; - VkPipelineVertexInputStateCreateInfo vin{VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO}; - vin.vertexBindingDescriptionCount = 1; vin.pVertexBindingDescriptions = &vbd; - vin.vertexAttributeDescriptionCount = 3; vin.pVertexAttributeDescriptions = vad; - VkPipelineInputAssemblyStateCreateInfo ia{VK_STRUCTURE_TYPE_PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO}; ia.topology = VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST; - // D3D clip space has y up: a negative-height viewport (Vulkan 1.1) keeps the game's matrices unchanged. - VkViewport vp{0, float(H), float(W), -float(H), 0, 1}; VkRect2D sc{{0, 0}, {W, H}}; - VkPipelineViewportStateCreateInfo vps{VK_STRUCTURE_TYPE_PIPELINE_VIEWPORT_STATE_CREATE_INFO}; - vps.viewportCount = 1; vps.pViewports = &vp; vps.scissorCount = 1; vps.pScissors = ≻ - VkPipelineRasterizationStateCreateInfo rs{VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_STATE_CREATE_INFO}; rs.cullMode = VK_CULL_MODE_NONE; rs.lineWidth = 1; - VkPipelineMultisampleStateCreateInfo ms{VK_STRUCTURE_TYPE_PIPELINE_MULTISAMPLE_STATE_CREATE_INFO}; ms.rasterizationSamples = VK_SAMPLE_COUNT_1_BIT; - VkPipelineDepthStencilStateCreateInfo dss{VK_STRUCTURE_TYPE_PIPELINE_DEPTH_STENCIL_STATE_CREATE_INFO}; - dss.depthTestEnable = VK_TRUE; dss.depthWriteEnable = VK_TRUE; dss.depthCompareOp = VK_COMPARE_OP_LESS; - VkPipelineColorBlendAttachmentState cba{}; cba.colorWriteMask = 0xF; - VkPipelineColorBlendStateCreateInfo cb{VK_STRUCTURE_TYPE_PIPELINE_COLOR_BLEND_STATE_CREATE_INFO}; cb.attachmentCount = 1; cb.pAttachments = &cba; - VkGraphicsPipelineCreateInfo gpi{VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO}; - gpi.stageCount = 2; gpi.pStages = st; gpi.pVertexInputState = &vin; gpi.pInputAssemblyState = &ia; gpi.pViewportState = &vps; - gpi.pRasterizationState = &rs; gpi.pMultisampleState = &ms; gpi.pDepthStencilState = &dss; gpi.pColorBlendState = &cb; - gpi.layout = pl; gpi.renderPass = rp; - VkPipeline pipe; CHECK(vkCreateGraphicsPipelines(dev, VK_NULL_HANDLE, 1, &gpi, nullptr, &pipe)); - - VkCommandPoolCreateInfo cpi{VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO}; cpi.queueFamilyIndex = qi; - cpi.flags = VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT; - VkCommandPool pool; CHECK(vkCreateCommandPool(dev, &cpi, nullptr, &pool)); - VkCommandBufferAllocateInfo cai{VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO}; cai.commandPool = pool; cai.commandBufferCount = 1; - VkCommandBuffer cmd; CHECK(vkAllocateCommandBuffers(dev, &cai, &cmd)); - auto barrier = [&](VkImage img, VkImageLayout from, VkImageLayout to, VkAccessFlags sa, VkAccessFlags da, - VkPipelineStageFlags ss, VkPipelineStageFlags dst) { - VkImageMemoryBarrier ib{VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER}; - ib.oldLayout = from; ib.newLayout = to; ib.image = img; ib.subresourceRange = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1}; - ib.srcAccessMask = sa; ib.dstAccessMask = da; ib.srcQueueFamilyIndex = ib.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; - vkCmdPipelineBarrier(cmd, ss, dst, 0, 0, nullptr, 0, nullptr, 1, &ib); - }; - auto submit = [&]() { VkSubmitInfo si{VK_STRUCTURE_TYPE_SUBMIT_INFO}; si.commandBufferCount = 1; si.pCommandBuffers = &cmd; - VkResult r = vkQueueSubmit(q, 1, &si, VK_NULL_HANDLE); return r ? r : vkQueueWaitIdle(q); }; - { // Upload the textures once. - VkCommandBufferBeginInfo cbi{VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO}; CHECK(vkBeginCommandBuffer(cmd, &cbi)); - for (uint32_t i = 0; i < nimg; ++i) { - barrier(timg[i], VK_IMAGE_LAYOUT_UNDEFINED, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 0, VK_ACCESS_TRANSFER_WRITE_BIT, - VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT); - VkBufferImageCopy c{}; c.bufferOffset = up_off[i]; c.imageSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1}; - c.imageExtent = {i ? scene.textures[i - 1].w : 1, i ? scene.textures[i - 1].h : 1, 1}; - vkCmdCopyBufferToImage(cmd, up, timg[i], VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, &c); - barrier(timg[i], VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL, VK_ACCESS_TRANSFER_WRITE_BIT, - VK_ACCESS_SHADER_READ_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT); - } - CHECK(vkEndCommandBuffer(cmd)); CHECK(submit()); - } - // Records the scene into rt (left in TRANSFER_SRC_OPTIMAL). The caller ends and submits. - auto record = [&]() { - view_projection(cam, float(W) / float(H), heap_f32(view_va + 0x160)); - VkClearValue clear[2]{}; clear[0].color = {{0.55f, 0.68f, 0.85f, 1}}; clear[1].depthStencil = {1, 0}; - VkRenderPassBeginInfo rbi{VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO}; - rbi.renderPass = rp; rbi.framebuffer = fb; rbi.renderArea = sc; rbi.clearValueCount = 2; rbi.pClearValues = clear; - vkCmdBeginRenderPass(cmd, &rbi, VK_SUBPASS_CONTENTS_INLINE); - vkCmdBindPipeline(cmd, VK_PIPELINE_BIND_POINT_GRAPHICS, pipe); - vkCmdBindDescriptorSets(cmd, VK_PIPELINE_BIND_POINT_GRAPHICS, pl, 0, 1, &ds, 0, nullptr); - VkDeviceSize zero = 0; - vkCmdBindVertexBuffers(cmd, 0, 1, &vb, &zero); - vkCmdBindIndexBuffer(cmd, ib, 0, VK_INDEX_TYPE_UINT32); - uint32_t pc[push_words] = {}; - pc[32] = uint32_t(heap_base); pc[33] = uint32_t(heap_base >> 32); - for (uint32_t d = 0; d < ndraw; ++d) { - const Mesh& m = scene.meshes[scene.draws[d].mesh]; - pc[8] = table_va + d * 0x80; // s8: the descriptor table; s9 (the PS's M0) stays 0 - vkCmdPushConstants(cmd, pl, VK_SHADER_STAGE_FRAGMENT_BIT | VK_SHADER_STAGE_VERTEX_BIT, 0, push_bytes, pc); - vkCmdDrawIndexed(cmd, m.index_count, 1, m.first_index, int32_t(m.first_vertex), 0); - } - vkCmdEndRenderPass(cmd); - }; - VkBuffer rb; void* rbp; - CHECK(make_buffer(VkDeviceSize(W) * H * 4, VK_BUFFER_USAGE_TRANSFER_DST_BIT, &rb, &rbp)); - auto read_back = [&]() { - VkBufferImageCopy rc{}; rc.imageSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1}; rc.imageExtent = {W, H, 1}; - vkCmdCopyImageToBuffer(cmd, rt, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, rb, 1, &rc); - }; - - if (!window) { - VkCommandBufferBeginInfo cbi{VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO}; CHECK(vkBeginCommandBuffer(cmd, &cbi)); - record(); read_back(); - CHECK(vkEndCommandBuffer(cmd)); CHECK(submit()); - if (!write_ppm(out_path, static_cast(rbp), W, H, false)) { std::fprintf(stderr, "cannot write %s\n", out_path); return 1; } - // Coverage: pixels that differ from the clear colour were written by the translated PS. - const uint8_t* px = static_cast(rbp); - const uint8_t clear_px[3] = {uint8_t(0.55f * 255 + 0.5f), uint8_t(0.68f * 255 + 0.5f), uint8_t(0.85f * 255 + 0.5f)}; - size_t covered = 0; - for (size_t i = 0; i < size_t(W) * H; ++i) - covered += std::abs(px[i * 4] - clear_px[0]) > 1 || std::abs(px[i * 4 + 1] - clear_px[1]) > 1 || std::abs(px[i * 4 + 2] - clear_px[2]) > 1; - std::printf("vk_sandbox: %u draws, %zu of %u pixels covered -> %s\n", ndraw, covered, W * H, out_path); - return 0; - } - -#ifdef _WIN32 - LI(vkGetPhysicalDeviceSurfaceCapabilitiesKHR); LI(vkGetPhysicalDeviceSurfaceFormatsKHR); LI(vkGetPhysicalDeviceSurfaceSupportKHR); - LD(vkCreateSwapchainKHR); LD(vkDestroySwapchainKHR); LD(vkGetSwapchainImagesKHR); LD(vkAcquireNextImageKHR); - LD(vkQueuePresentKHR); LD(vkCreateSemaphore); - VkBool32 can_present = VK_FALSE; vkGetPhysicalDeviceSurfaceSupportKHR(pd, qi, surface, &can_present); - if (!can_present) { std::fprintf(stderr, "the graphics queue cannot present\n"); return 1; } - uint32_t nf = 0; vkGetPhysicalDeviceSurfaceFormatsKHR(pd, surface, &nf, nullptr); - std::vector sfs(nf); vkGetPhysicalDeviceSurfaceFormatsKHR(pd, surface, &nf, sfs.data()); - if (sfs.empty()) { std::fprintf(stderr, "the surface has no formats\n"); return 1; } - VkSurfaceFormatKHR sf = sfs[0]; // a UNORM format keeps the blit byte-exact with the headless render - for (const VkSurfaceFormatKHR& c : sfs) - if (c.format == VK_FORMAT_B8G8R8A8_UNORM || c.format == VK_FORMAT_R8G8B8A8_UNORM) { sf = c; break; } - VkSwapchainCreateInfoKHR swi{VK_STRUCTURE_TYPE_SWAPCHAIN_CREATE_INFO_KHR}; - VkSwapchainKHR swap = VK_NULL_HANDLE; - std::vector simg; - // (Re)creates the swapchain for the window's current size; false while it is minimised (extent 0). - auto make_swap = [&]() -> int { - VkSurfaceCapabilitiesKHR caps; - if (vkGetPhysicalDeviceSurfaceCapabilitiesKHR(pd, surface, &caps) != VK_SUCCESS) return -1; - if (!(caps.supportedUsageFlags & VK_IMAGE_USAGE_TRANSFER_DST_BIT)) return -1; - const VkExtent2D ext = caps.currentExtent.width != 0xFFFFFFFFu ? caps.currentExtent : VkExtent2D{W, H}; - if (!ext.width || !ext.height) return 0; - vkQueueWaitIdle(q); - swi.surface = surface; swi.minImageCount = std::max(2u, caps.minImageCount); - if (caps.maxImageCount) swi.minImageCount = std::min(swi.minImageCount, caps.maxImageCount); - swi.imageFormat = sf.format; swi.imageColorSpace = sf.colorSpace; swi.imageExtent = ext; - swi.imageArrayLayers = 1; swi.imageUsage = VK_IMAGE_USAGE_TRANSFER_DST_BIT; swi.preTransform = caps.currentTransform; - swi.compositeAlpha = VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR; swi.presentMode = VK_PRESENT_MODE_FIFO_KHR; swi.clipped = VK_TRUE; - swi.oldSwapchain = swap; - VkSwapchainKHR next; - if (vkCreateSwapchainKHR(dev, &swi, nullptr, &next) != VK_SUCCESS) return -1; - if (swap) vkDestroySwapchainKHR(dev, swap, nullptr); - swap = next; - uint32_t ns = 0; vkGetSwapchainImagesKHR(dev, swap, &ns, nullptr); - simg.resize(ns); vkGetSwapchainImagesKHR(dev, swap, &ns, simg.data()); - return 1; - }; - if (make_swap() < 0) { std::fprintf(stderr, "cannot create a swapchain (TRANSFER_DST unsupported?)\n"); return 1; } - VkSemaphoreCreateInfo semi{VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO}; - VkSemaphore acquired; CHECK(vkCreateSemaphore(dev, &semi, nullptr, &acquired)); - std::optional ground; - auto last = std::chrono::steady_clock::now(); - bool shot_held = false; - int frame = 0; - while (!g_quit) { - MSG msg; - while (PeekMessageW(&msg, nullptr, 0, 0, PM_REMOVE)) { TranslateMessage(&msg); DispatchMessageW(&msg); } - const auto now = std::chrono::steady_clock::now(); - const float dt = std::min(0.1f, std::chrono::duration(now - last).count()); last = now; - const bool focus = GetForegroundWindow() == hwnd; - auto key = [&](int vk) { return focus && (GetAsyncKeyState(vk) & 0x8000); }; - if (key(VK_ESCAPE)) break; - if (key('1')) cam.mode = 0; if (key('2')) cam.mode = 1; if (key('3')) cam.mode = 2; - cam.yaw -= g_dx * 0.004f; cam.pitch = std::clamp(cam.pitch - g_dy * 0.004f, -1.5f, 1.5f); g_dx = g_dy = 0; - float f[3]; cam.forward(f); - const float r[2] = {std::sin(cam.yaw), -std::cos(cam.yaw)}; - const float fwd = float(key('W')) - float(key('S')), side = float(key('D')) - float(key('A')); - if (cam.mode == 0) { - const float v = (key(VK_SHIFT) ? 60.f : 12.f) * dt; - for (int k = 0; k < 3; ++k) cam.pos[k] += f[k] * fwd * v; - cam.pos[0] += r[0] * side * v; cam.pos[1] += r[1] * side * v; - cam.pos[2] += (float(key('E')) - float(key('Q'))) * v; - } else { - if (!ground) { - ground.emplace().build(scene); - last = std::chrono::steady_clock::now(); // Exclude grid construction from the next movement step. - } - const float h = std::hypot(f[0], f[1]) > 1e-4f ? std::hypot(f[0], f[1]) : 1; - if (cam.mode == 1) cam.speed = fwd * (key(VK_SHIFT) ? 7.f : 2.5f); - else { cam.speed += fwd * 12.f * dt; cam.speed *= std::pow(0.6f, dt); cam.yaw -= side * dt * std::clamp(cam.speed / 10.f, -1.f, 1.f); } - cam.pos[0] += f[0] / h * cam.speed * dt; cam.pos[1] += f[1] / h * cam.speed * dt; - if (cam.mode == 1) { cam.pos[0] += r[0] * side * 2.5f * dt; cam.pos[1] += r[1] * side * 2.5f * dt; } - const float eye = cam.mode == 1 ? 1.7f : 1.2f; - float gz; - if (ground->height(cam.pos[0], cam.pos[1], cam.pos[2] - eye + 0.6f, gz)) cam.pos[2] = gz + eye; - } - uint32_t idx = 0; - if (!swap) { // minimised at start or since the last resize - const int made = make_swap(); - if (made < 0) { std::fprintf(stderr, "cannot recreate the swapchain\n"); return 1; } - if (!made) { Sleep(50); continue; } - } - const VkResult acq = vkAcquireNextImageKHR(dev, swap, UINT64_MAX, acquired, VK_NULL_HANDLE, &idx); - if (acq == VK_ERROR_OUT_OF_DATE_KHR) { - const int made = make_swap(); - if (made < 0) { std::fprintf(stderr, "cannot recreate the swapchain\n"); return 1; } - if (!made) { vkDestroySwapchainKHR(dev, swap, nullptr); swap = VK_NULL_HANDLE; Sleep(50); } - continue; - } - if (acq != VK_SUCCESS && acq != VK_SUBOPTIMAL_KHR) { std::fprintf(stderr, "vkAcquireNextImageKHR failed (%d)\n", int(acq)); return 1; } - CHECK(vkResetCommandBuffer(cmd, 0)); - VkCommandBufferBeginInfo cbi{VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO}; CHECK(vkBeginCommandBuffer(cmd, &cbi)); - record(); - const bool last_frame = frames && ++frame >= frames; - const bool shot = (key('P') && !shot_held) || last_frame; shot_held = key('P'); - if (shot) read_back(); - barrier(simg[idx], VK_IMAGE_LAYOUT_UNDEFINED, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 0, VK_ACCESS_TRANSFER_WRITE_BIT, - VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT); - VkImageBlit bl{}; bl.srcSubresource = bl.dstSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1}; - bl.srcOffsets[1] = {int32_t(W), int32_t(H), 1}; - bl.dstOffsets[1] = {int32_t(swi.imageExtent.width), int32_t(swi.imageExtent.height), 1}; - vkCmdBlitImage(cmd, rt, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, simg[idx], VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, &bl, VK_FILTER_LINEAR); - barrier(simg[idx], VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, VK_IMAGE_LAYOUT_PRESENT_SRC_KHR, VK_ACCESS_TRANSFER_WRITE_BIT, 0, - VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT); - CHECK(vkEndCommandBuffer(cmd)); - VkPipelineStageFlags wait_stage = VK_PIPELINE_STAGE_TRANSFER_BIT; - VkSubmitInfo si{VK_STRUCTURE_TYPE_SUBMIT_INFO}; si.waitSemaphoreCount = 1; si.pWaitSemaphores = &acquired; - si.pWaitDstStageMask = &wait_stage; si.commandBufferCount = 1; si.pCommandBuffers = &cmd; - CHECK(vkQueueSubmit(q, 1, &si, VK_NULL_HANDLE)); CHECK(vkQueueWaitIdle(q)); - if (shot) { - const char* path = last_frame ? out_path : "sandbox_shot.ppm"; - if (!write_ppm(path, static_cast(rbp), W, H, false)) { - std::fprintf(stderr, "cannot write %s\n", path); - if (last_frame) return 1; - } - } - VkPresentInfoKHR pi{VK_STRUCTURE_TYPE_PRESENT_INFO_KHR}; pi.swapchainCount = 1; pi.pSwapchains = &swap; pi.pImageIndices = &idx; - const VkResult pres = vkQueuePresentKHR(q, &pi); - if ((pres == VK_ERROR_OUT_OF_DATE_KHR || pres == VK_SUBOPTIMAL_KHR || acq == VK_SUBOPTIMAL_KHR) && !last_frame) { - const int made = make_swap(); - if (made < 0) { std::fprintf(stderr, "cannot recreate the swapchain\n"); return 1; } - if (!made) { vkDestroySwapchainKHR(dev, swap, nullptr); swap = VK_NULL_HANDLE; } - } - char title[160]; - std::snprintf(title, sizeof title, "Leonida real-shader sandbox [%s] %.0f %.0f %.0f %.0f fps", cam.mode == 0 ? "fly" : cam.mode == 1 ? "walk" : "drive", - cam.pos[0], cam.pos[1], cam.pos[2], 1.f / std::max(dt, 1e-4f)); - SetWindowTextA(hwnd, title); - if (last_frame) { - std::printf("vk_sandbox: window ran %d frames -> %s, camera %.2f %.2f %.2f\n", frame, out_path, - cam.pos[0], cam.pos[1], cam.pos[2]); - break; - } - } - vkQueueWaitIdle(q); -#endif - return 0; -} diff --git a/runtime/test/vk_shader_fma.h b/runtime/test/vk_shader_fma.h deleted file mode 100644 index 34691b2b2..000000000 --- a/runtime/test/vk_shader_fma.h +++ /dev/null @@ -1,150 +0,0 @@ -// VK_KHR_shader_fma for the test programs: translated shaders built with `rdna2spirv.py --fma khr` use OpFmaKHR -// (capability FMAKHR, SPV_KHR_fma), so the device must enable the extension and the shaderFmaFloat32 feature before -// the module can be created. A test program that creates a device calls query(), link_after() and extension() when -// supported(), and refuses a module that needs the capability on a device without it (exit 77, like every other -// missing device feature). -#pragma once - -#include - -#include -#include -#include -#include -#include -#include -#include -#include - -namespace leonida::vk_test { - -#ifdef VK_KHR_SHADER_FMA_EXTENSION_NAME -inline constexpr bool shader_fma_in_headers = true; -#else -inline constexpr bool shader_fma_in_headers = false; -#endif - -inline constexpr std::uint32_t spv_sampled_image_array_dynamic_indexing = 29; -inline constexpr std::uint32_t spv_storage_image_array_dynamic_indexing = 31; - -// Find OpCapability (17) in a binary module. -inline bool spirv_declares_capability(const void* data, std::size_t bytes, std::uint32_t capability) { - if (bytes < 20 || bytes % 4) return false; - std::vector words(bytes / 4); - std::memcpy(words.data(), data, bytes); - for (std::size_t i = 5; i < words.size() && (words[i] >> 16);) { - const std::uint32_t op = words[i] & 0xffff, count = words[i] >> 16; - if (op == 17 && count == 2 && i + 1 < words.size() && words[i + 1] == capability) return true; - i += count; - } - return false; -} - -// The float widths that the module's OpFmaKHR (4427) results have: OpTypeFloat (22) gives each float type's width, -// OpTypeVector (23) carries its component's, and an OpFmaKHR's result type (word 1) is one of them. A module with -// Float64 but only an f32 OpFmaKHR needs only shaderFmaFloat32, so the width comes from the instruction itself. -inline void spirv_fma_widths(const void* data, std::size_t bytes, bool& f32, bool& f64) { - f32 = f64 = false; - if (bytes < 20 || bytes % 4) return; - std::vector words(bytes / 4); - std::memcpy(words.data(), data, bytes); - std::vector> width; // float type id -> width (a few entries) - const auto width_of = [&](std::uint32_t id) -> std::uint32_t { - for (const auto& [t, w] : width) if (t == id) return w; - return 0; - }; - for (std::size_t i = 5; i < words.size() && (words[i] >> 16);) { - const std::uint32_t op = words[i] & 0xffff, count = words[i] >> 16; - if (i + count > words.size()) break; - if (op == 22 && count >= 3) width.emplace_back(words[i + 1], words[i + 2]); - else if (op == 23 && count >= 4 && width_of(words[i + 2])) width.emplace_back(words[i + 1], width_of(words[i + 2])); - else if (op == 4427 && count >= 3) (width_of(words[i + 1]) == 64 ? f64 : f32) = true; - i += count; - } -} - -struct ShaderFma { -#ifdef VK_KHR_SHADER_FMA_EXTENSION_NAME - VkPhysicalDeviceShaderFmaFeaturesKHR features{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADER_FMA_FEATURES_KHR}; -#endif - bool float32 = false; // the device lists the extension and reports shaderFmaFloat32 - bool float64 = false; // ... and shaderFmaFloat64 (OpFmaKHR on doubles: rdna2spirv.py --fma khr, v_div_fmas_f64) - - bool supported() const { return float32 || float64; } - - // Asks the physical device. Enables exactly what it reports (shaderFmaFloat16/32/64), so features never - // fail device creation. - void query(PFN_vkGetInstanceProcAddr gipa, VkInstance inst, VkPhysicalDevice pd) { -#ifdef VK_KHR_SHADER_FMA_EXTENSION_NAME - const auto enumerate = reinterpret_cast( - gipa(inst, "vkEnumerateDeviceExtensionProperties")); - const auto features2 = reinterpret_cast( - gipa(inst, "vkGetPhysicalDeviceFeatures2")); - if (!enumerate || !features2) return; - std::uint32_t count = 0; - enumerate(pd, nullptr, &count, nullptr); - std::vector extensions(count); - enumerate(pd, nullptr, &count, extensions.data()); - bool listed = false; - for (const auto& e : extensions) - if (!std::strcmp(e.extensionName, VK_KHR_SHADER_FMA_EXTENSION_NAME)) listed = true; - if (!listed) return; - features = {VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADER_FMA_FEATURES_KHR}; - VkPhysicalDeviceFeatures2 query{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2, &features}; - features2(pd, &query); - features.pNext = nullptr; - float32 = features.shaderFmaFloat32 == VK_TRUE; - float64 = features.shaderFmaFloat64 == VK_TRUE; -#else - (void)gipa; (void)inst; (void)pd; -#endif - } - - // Puts the features structure into the device pNext chain right after `base` (any structure in the chain). - void link_after(void* base) { -#ifdef VK_KHR_SHADER_FMA_EXTENSION_NAME - if (!supported()) return; - auto* b = static_cast(base); - features.pNext = b->pNext; - b->pNext = reinterpret_cast(&features); -#else - (void)base; -#endif - } - - // The extension name to add to ppEnabledExtensionNames when supported(). - static const char* extension() { -#ifdef VK_KHR_SHADER_FMA_EXTENSION_NAME - return VK_KHR_SHADER_FMA_EXTENSION_NAME; -#else - return "VK_KHR_shader_fma"; -#endif - } - - // True when the module can be used: it does not need FMAKHR, or the device enables the shaderFmaFloat32 / - // shaderFmaFloat64 that its OpFmaKHR result widths need. Otherwise says so and the caller returns 77. - bool accepts(const void* code, std::size_t bytes, const char* name) const { - if ((float32 && float64) || !spirv_declares_capability(code, bytes, 6030)) return true; // FMAKHR - bool need32 = false, need64 = false; - spirv_fma_widths(code, bytes, need32, need64); - if (!need32 && !need64) need32 = true; // FMAKHR declared but no OpFmaKHR found: keep the old requirement - const char* missing = need32 && !float32 ? "shaderFmaFloat32" : need64 && !float64 ? "shaderFmaFloat64" : nullptr; - if (!missing) return true; - std::fprintf(stderr, "unsupported: %s needs OpFmaKHR (VK_KHR_shader_fma, %s) and the device lacks it; " - "translate with --fma glsl\n", name, missing); - return false; - } - - // accepts() for every stage of a pipeline: a test that draws a translated pixel shader with a translated vertex - // shader must refuse the pair when EITHER stage needs FMAKHR, because the device then fails pipeline creation - // instead of skipping. A file that cannot be read is accepted here; the caller's own module loading reports it. - bool accepts_file(const char* path) const { - if ((float32 && float64) || !path || !*path) return true; - std::ifstream in(path, std::ios::binary); - if (!in) return true; - const std::vector bytes((std::istreambuf_iterator(in)), std::istreambuf_iterator()); - return accepts(bytes.data(), bytes.size(), path); - } -}; - -} // namespace leonida::vk_test diff --git a/runtime/test/vk_shader_fma_test.cpp b/runtime/test/vk_shader_fma_test.cpp deleted file mode 100644 index 2a9d01c52..000000000 --- a/runtime/test/vk_shader_fma_test.cpp +++ /dev/null @@ -1,78 +0,0 @@ -// Unit tests for the OpFmaKHR width gate in vk_shader_fma.h (no Vulkan instance, no GPU). A module built with -// `rdna2spirv.py --fma khr` needs shaderFmaFloat32 for an f32 OpFmaKHR and shaderFmaFloat64 for one on doubles; -// a module that declares Float64 for other doubles but has only f32 OpFmaKHRs needs only shaderFmaFloat32. -#include "vk_shader_fma.h" - -#include -#include -#include - -namespace { - -int failures = 0; - -void expect(bool ok, const char* what) { - if (ok) return; - std::fprintf(stderr, "FAIL %s\n", what); - ++failures; -} - -std::uint32_t word0(std::uint32_t op, std::uint32_t count) { return count << 16 | op; } - -// A minimal module: header, OpCapability FMAKHR (+ Float64), float types, and OpFmaKHRs of the given result types. -// Ids: 1 = f32, 2 = f64, 3 = v2f32, 4 = v2f64; FMA operands are ids 10..12 (never defined: the gate does not care). -std::vector module(bool fma_cap, bool float64_cap, const std::vector& fma_types) { - std::vector w = {0x07230203, 0x00010500, 0, 100, 0}; - if (fma_cap) w.insert(w.end(), {word0(17, 2), 6030}); - if (float64_cap) w.insert(w.end(), {word0(17, 2), 10}); - w.insert(w.end(), {word0(22, 3), 1, 32, word0(22, 3), 2, 64, word0(23, 4), 3, 1, 2, word0(23, 4), 4, 2, 2}); - std::uint32_t id = 20; - for (const std::uint32_t t : fma_types) w.insert(w.end(), {word0(4427, 6), t, id++, 10, 11, 12}); - return w; -} - -bool accepts(const leonida::vk_test::ShaderFma& fma, const std::vector& m) { - return fma.accepts(m.data(), m.size() * sizeof(m.front()), "test.spv"); -} - -} // namespace - -int main() { - using leonida::vk_test::ShaderFma; - using leonida::vk_test::spirv_fma_widths; - - bool f32 = false, f64 = false; - auto m = module(true, true, {1}); - spirv_fma_widths(m.data(), m.size() * 4, f32, f64); - expect(f32 && !f64, "an f32 OpFmaKHR is width 32"); - m = module(true, true, {2}); - spirv_fma_widths(m.data(), m.size() * 4, f32, f64); - expect(!f32 && f64, "an f64 OpFmaKHR is width 64"); - m = module(true, true, {4, 3}); - spirv_fma_widths(m.data(), m.size() * 4, f32, f64); - expect(f32 && f64, "vector results take their component width"); - - ShaderFma only32; - only32.float32 = true; - ShaderFma only64; - only64.float64 = true; - ShaderFma both; - both.float32 = both.float64 = true; - const ShaderFma none; - - expect(accepts(none, module(false, true, {})), "a module without FMAKHR needs nothing"); - expect(accepts(only32, module(true, false, {1})), "f32 OpFmaKHR on a shaderFmaFloat32 device"); - expect(accepts(only32, module(true, true, {1})), "Float64 elsewhere + f32 OpFmaKHR needs only shaderFmaFloat32"); - expect(!accepts(only32, module(true, true, {2})), "f64 OpFmaKHR is refused without shaderFmaFloat64"); - expect(!accepts(only32, module(true, true, {1, 2})), "mixed widths need both"); - expect(accepts(only64, module(true, true, {2})), "f64 OpFmaKHR on a shaderFmaFloat64 device"); - expect(!accepts(only64, module(true, false, {1})), "f32 OpFmaKHR is refused without shaderFmaFloat32"); - expect(accepts(both, module(true, true, {1, 2})), "both widths on a device with both"); - expect(!accepts(none, module(true, false, {1})), "no VK_KHR_shader_fma refuses any OpFmaKHR"); - expect(!accepts(only64, module(true, false, {})), "FMAKHR without an OpFmaKHR keeps needing shaderFmaFloat32"); - expect(only32.supported() && only64.supported() && !none.supported(), "supported() is either width"); - - if (failures) return 1; - std::puts("vk_shader_fma: all checks passed"); - return 0; -} diff --git a/runtime/test/vk_store_test.cpp b/runtime/test/vk_store_test.cpp deleted file mode 100644 index 5567511d0..000000000 --- a/runtime/test/vk_store_test.cpp +++ /dev/null @@ -1,562 +0,0 @@ -// Headless Vulkan test for translated typed image stores and loads (runtime/test/shaders/cs_imgstore.asm and -// cs_imgload.asm). -// Usage: vk_store_test cs.spv [load|load-d16|words|signed-zero] -// The shader builds three T#s (word1 FORMAT = 56 rgba8 unorm, 20 r32 uint, 21 r32 sint) and stores to three 8x8 -// images. The translator picks the float / uint / sint view (set 0, bindings 8 / 9 / 10 for 2D) from the FORMAT -// field, and the bindless index from the descriptor hash table (binding 2). As in the runtime, each image has its -// own index in the 2D arrays (1, 2, 3; index 0 is the fallback) and its view in its own format at that index of the -// sampled array (binding 0), which typed image_load fetches from. Checks every texel. -// "load" (cs_imgload.asm): the uint and sint images are filled before the dispatch, and the shader loads both -// texels with image_load and stores their sum into the sint image. The device is made without -// shaderStorageImageReadWithoutFormat, and a module that declares StorageImageReadWithoutFormat fails (SHADER-151). -// "words" (cs_imgatomic.asm, cs_imgatomic3d.asm, cs_resinfo.asm): the uint and sint images are filled as for "load" -// and a 4x4x4 r32 uint volume with 200 + i, and nothing is judged here: the 64 words of each are printed after the -// dispatch (texel (x, y) at i = 8y + x, (x, y, z) at i = 16z + 4y + x) for check.py to compare. Three things are -// bound for these shaders in every mode: the uint image as an r32ui storage image at set 0 binding 4 and the volume -// at binding 7, where 2D and 3D image atomics address their image, and at index 4 of the sampled array a 16x4 rgba8 -// image with all five mip levels (never read, only queried), behind the T# the runtime writes for such an image. -// "signed-zero" checks three direct float stores and all remaining RGBA32 guard words (SHADER-605). -#include "vulkan_loader.h" -#include "vk_device_pick.h" -#include "vk_shader_fma.h" -#include "vk_pc_tail.h" -#include "spirv_capability.h" -#include "../src/gfx10_descriptors.h" - -#include -#include -#include -#include -#include -#include - -static PFN_vkGetInstanceProcAddr gipa; -#define CHECK(x) \ - do { \ - VkResult r_ = (x); \ - if (r_ != VK_SUCCESS) { \ - std::fprintf(stderr, "FAILED %s -> %d (line %d)\n", #x, r_, __LINE__); \ - return 1; \ - } \ - } while (0) - -static uint32_t key_hash(const uint32_t k[8]) { // same FNV-1a as the translator's desc_lookup - uint32_t h = 2166136261u; - for (int i = 0; i < 8; i++) h = (h ^ k[i]) * 16777619u; - return h; -} - -static void table_insert(std::vector& t, const uint32_t key[8], uint32_t index) { - uint32_t mask = t[0], h = key_hash(key); - for (uint32_t k = 0; k < 8; k++) { - uint32_t base = ((h + k) & mask) * 10; - bool used = false; - for (int j = 0; j < 8; j++) used |= t[base + 1 + j] != 0; - if (used) continue; - for (int j = 0; j < 8; j++) t[base + 1 + j] = key[j]; - t[base + 9] = index; - return; - } -} - -int main(int argc, char** argv) { - if (argc < 2) { std::fprintf(stderr, "usage: vk_store_test cs.spv [load|load-d16|words|signed-zero]\n"); return 2; } - gipa = load_vulkan(); - if (!gipa) return 1; -#define LOADI(name) auto name = reinterpret_cast(gipa(inst, #name)) - VkInstance inst = VK_NULL_HANDLE; - LOADI(vkCreateInstance); - VkApplicationInfo app{VK_STRUCTURE_TYPE_APPLICATION_INFO}; - app.apiVersion = VK_API_VERSION_1_2; - VkInstanceCreateInfo ici{VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO}; - ici.pApplicationInfo = &app; - CHECK(vkCreateInstance(&ici, nullptr, &inst)); - LOADI(vkEnumeratePhysicalDevices); LOADI(vkGetPhysicalDeviceProperties); LOADI(vkCreateDevice); - LOADI(vkGetPhysicalDeviceQueueFamilyProperties); LOADI(vkGetDeviceProcAddr); - LOADI(vkGetPhysicalDeviceMemoryProperties); LOADI(vkGetPhysicalDeviceFeatures); - uint32_t n = 0; - vkEnumeratePhysicalDevices(inst, &n, nullptr); - std::vector pds(n); - vkEnumeratePhysicalDevices(inst, &n, pds.data()); - std::vector candidates(pds.size()); - for (std::size_t i = 0; i < pds.size(); ++i) vkGetPhysicalDeviceProperties(pds[i], &candidates[i]); - const std::size_t chosen = leonida::vk_test::pick_device(candidates); - VkPhysicalDevice pd = chosen < pds.size() ? pds[chosen] : VK_NULL_HANDLE; - if (!pd) { - leonida::vk_test::report_no_device(); - return 1; - } - VkPhysicalDeviceProperties props; vkGetPhysicalDeviceProperties(pd, &props); - std::fprintf(stderr, "device: %s\n", props.deviceName); - // 144 push-constant bytes by default, or 128 under LEONIDA_PC_TAIL_UBO=1 (rdna2spirv.py --pc-tail-ubo). - // A 128-byte device cannot declare a 144-byte range (VUID-VkPushConstantRange-size-00298): exit 77 (D3D-14). - const bool pc_tail = leonida::vk_test::pc_tail_requested(); - const uint32_t pc_bytes = pc_tail ? 128u : 144u; - if (props.limits.maxPushConstantsSize < pc_bytes) { - std::printf("unsupported: need %u push constant bytes, device has %u\n", pc_bytes, - props.limits.maxPushConstantsSize); - return 77; - } - uint32_t qn = 0; - vkGetPhysicalDeviceQueueFamilyProperties(pd, &qn, nullptr); - std::vector qf(qn); - vkGetPhysicalDeviceQueueFamilyProperties(pd, &qn, qf.data()); - uint32_t qi = 0; - while (qi < qn && !(qf[qi].queueFlags & VK_QUEUE_COMPUTE_BIT)) qi++; - float prio = 1; - VkDeviceQueueCreateInfo qci{VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO}; - qci.queueFamilyIndex = qi; qci.queueCount = 1; qci.pQueuePriorities = &prio; - // The typed stores need format-less storage image writes: without them, report that and exit 77 (unsupported, - // as vk_compute_test does) instead of failing vkCreateDevice. Typed loads need no storage image feature. - VkPhysicalDeviceFeatures have{}; - vkGetPhysicalDeviceFeatures(pd, &have); - if (!have.shaderStorageImageWriteWithoutFormat) { - std::printf("unsupported: shaderStorageImageWriteWithoutFormat=0\n"); - return 77; - } - VkPhysicalDeviceVulkan12Features f12{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_2_FEATURES}; - f12.runtimeDescriptorArray = VK_TRUE; f12.bufferDeviceAddress = VK_TRUE; - f12.shaderStorageImageArrayNonUniformIndexing = VK_TRUE; - f12.shaderSampledImageArrayNonUniformIndexing = VK_TRUE; - VkPhysicalDeviceFeatures2 f2{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2}; - f2.features.shaderStorageImageWriteWithoutFormat = VK_TRUE; - // "load" mode (cs_imgload.asm): the sint image receives the sum of the two texels read back with image_load. - const bool packed_load = argc > 2 && !std::strcmp(argv[2], "load-d16"); - const bool load_mode = packed_load || (argc > 2 && !std::strcmp(argv[2], "load")); - // "words" mode: the two images filled as for "load"; the shader's results are whatever it leaves in them. - const bool words_mode = argc > 2 && !std::strcmp(argv[2], "words"); - const bool signed_zero = argc > 2 && !std::strcmp(argv[2], "signed-zero"); - if (signed_zero) { - LOADI(vkGetPhysicalDeviceProperties2); - VkPhysicalDeviceFloatControlsProperties controls{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FLOAT_CONTROLS_PROPERTIES}; - VkPhysicalDeviceProperties2 properties{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROPERTIES_2}; - properties.pNext = &controls; - vkGetPhysicalDeviceProperties2(pd, &properties); - if (!controls.shaderSignedZeroInfNanPreserveFloat32) { - std::printf("unsupported: shaderSignedZeroInfNanPreserveFloat32=0\n"); - return 77; - } - } - const bool filled = load_mode || words_mode; - std::ifstream f(argv[1], std::ios::binary); - std::vector code((std::istreambuf_iterator(f)), {}); - if (code.size() < 20 || code.size() % 4) { std::fprintf(stderr, "%s: not a SPIR-V module\n", argv[1]); return 1; } - // shaderInt64 only for a module with 64-bit integers: SHADER-423's address pairs need none (TEST-468). - const bool int64 = leonida::vk_test::needs_shader_int64(code.data(), code.size()); - if (int64 && !have.shaderInt64) { - std::printf("unsupported: %s declares Int64 and the device has no shaderInt64\n", argv[1]); - return 77; - } - using leonida::vk_test::spirv_declares_capability; - const bool dynamic_sampled = spirv_declares_capability(code.data(), code.size(), - leonida::vk_test::spv_sampled_image_array_dynamic_indexing); - if (dynamic_sampled && !have.shaderSampledImageArrayDynamicIndexing) { - std::printf("unsupported: shaderSampledImageArrayDynamicIndexing\n"); - return 77; - } - f2.features.shaderSampledImageArrayDynamicIndexing = dynamic_sampled; - const bool dynamic_storage = spirv_declares_capability(code.data(), code.size(), - leonida::vk_test::spv_storage_image_array_dynamic_indexing); - if (dynamic_storage && !have.shaderStorageImageArrayDynamicIndexing) { - std::printf("unsupported: shaderStorageImageArrayDynamicIndexing\n"); - return 77; - } - f2.features.shaderStorageImageArrayDynamicIndexing = dynamic_storage; - // Typed image_load fetches through the sampled arrays without StorageImageReadWithoutFormat (55, SHADER-151). - if (filled && spirv_declares_capability(code.data(), code.size(), 55)) { - std::printf("FAILED: the module declares StorageImageReadWithoutFormat\n"); - return 1; - } - f2.features.shaderInt64 = int64 ? VK_TRUE : VK_FALSE; - f2.pNext = &f12; - leonida::vk_test::ShaderFma fma; // OpFmaKHR (rdna2spirv.py --fma khr) - fma.query(gipa, inst, pd); - if (!fma.accepts(code.data(), code.size(), argv[1])) return 77; - fma.link_after(&f2); - const char* fma_extension = fma.extension(); - VkDeviceCreateInfo dci{VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO}; - dci.queueCreateInfoCount = 1; dci.pQueueCreateInfos = &qci; dci.pNext = &f2; - if (fma.supported()) { dci.enabledExtensionCount = 1; dci.ppEnabledExtensionNames = &fma_extension; } - VkDevice dev; - CHECK(vkCreateDevice(pd, &dci, nullptr, &dev)); -#define LOADD(name) auto name = reinterpret_cast(vkGetDeviceProcAddr(dev, #name)) - LOADD(vkGetDeviceQueue); LOADD(vkCreateBuffer); LOADD(vkGetBufferMemoryRequirements); LOADD(vkAllocateMemory); - LOADD(vkBindBufferMemory); LOADD(vkMapMemory); LOADD(vkCreateShaderModule); LOADD(vkCreateImage); - LOADD(vkGetImageMemoryRequirements); LOADD(vkBindImageMemory); LOADD(vkCreateImageView); LOADD(vkCreateSampler); - LOADD(vkCreateDescriptorSetLayout); LOADD(vkCreatePipelineLayout); LOADD(vkCreateComputePipelines); - LOADD(vkCreateDescriptorPool); LOADD(vkAllocateDescriptorSets); LOADD(vkUpdateDescriptorSets); - LOADD(vkCreateCommandPool); LOADD(vkAllocateCommandBuffers); LOADD(vkBeginCommandBuffer); - LOADD(vkCmdBindPipeline); LOADD(vkCmdBindDescriptorSets); LOADD(vkCmdPushConstants); LOADD(vkCmdDispatch); - LOADD(vkCmdPipelineBarrier); LOADD(vkCmdCopyImageToBuffer); LOADD(vkCmdCopyBufferToImage); - LOADD(vkEndCommandBuffer); LOADD(vkQueueSubmit); - LOADD(vkQueueWaitIdle); - VkQueue q; vkGetDeviceQueue(dev, qi, 0, &q); - VkPhysicalDeviceMemoryProperties mp; vkGetPhysicalDeviceMemoryProperties(pd, &mp); - auto memtype = [&](uint32_t bits, VkMemoryPropertyFlags want) { - for (uint32_t i = 0; i < mp.memoryTypeCount; i++) - if ((bits >> i & 1) && (mp.memoryTypes[i].propertyFlags & want) == want) return i; - return 0u; - }; - auto make_buffer = [&](VkDeviceSize size, VkBufferUsageFlags usage, VkBuffer* b, void** map) { - VkBufferCreateInfo bi{VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO}; bi.size = size; bi.usage = usage; - VkResult r = vkCreateBuffer(dev, &bi, nullptr, b); - if (r) return r; - VkMemoryRequirements mr; vkGetBufferMemoryRequirements(dev, *b, &mr); - VkMemoryAllocateInfo mai{VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO}; - mai.allocationSize = mr.size; - mai.memoryTypeIndex = memtype(mr.memoryTypeBits, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT); - VkDeviceMemory m; - if ((r = vkAllocateMemory(dev, &mai, nullptr, &m))) return r; - if ((r = vkBindBufferMemory(dev, *b, m, 0))) return r; - return vkMapMemory(dev, m, 0, size, 0, map); - }; - - // T#s exactly as the shader builds them (cs_imgstore.asm): word0 = 0x1000 * (k + 1), word1 = FORMAT << 20, - // words 2..7 = 0x11 * (k + 1). - const uint32_t fmts[3] = {56, 20, 21}; - const VkFormat compact_formats[3] = {VK_FORMAT_R8G8B8A8_UNORM, VK_FORMAT_R32_UINT, VK_FORMAT_R32_SINT}; - const VkFormat rgba32_formats[3] = {VK_FORMAT_R32G32B32A32_SFLOAT, VK_FORMAT_R32G32B32A32_UINT, - VK_FORMAT_R32G32B32A32_SINT}; - const VkFormat* vkf = signed_zero ? rgba32_formats : compact_formats; - std::vector table(1 + 16 * 10 + 10, 0); - table[0] = 15; - for (uint32_t k = 0; k < 3; k++) { - uint32_t t[8] = {0x1000 * (k + 1), fmts[k] << 20}; - for (int j = 2; j < 8; j++) t[j] = 0x11 * (k + 1); - table_insert(table, t, k + 1); // its index in the 2D arrays; 0 is the fallback, as in the runtime - } - // Index 4: a 16x4 rgba8 image with its whole mip chain (16x4, 8x2, 4x1, 2x1, 1x1) for image_get_resinfo. Its key - // is the T# of exactly that image (gfx10_descriptors.h), which cs_resinfo.asm builds word for word. - const uint32_t WIDE_W = 16, WIDE_H = 4, WIDE_MIPS = 5; - leonida::gfx10::Image wide_desc{}; - wide_desc.address = 0x400000; wide_desc.format = fmts[0]; wide_desc.width = WIDE_W; wide_desc.height = WIDE_H; - wide_desc.mip_count = wide_desc.resource_mips = WIDE_MIPS; - const leonida::gfx10::ImageWords wide_key = leonida::gfx10::encode(wide_desc); - table_insert(table, wide_key.data(), 4); - // The volume of the 3D atomics: index 1 of the 3D arrays, behind a T# of the 2D images' pattern (k = 4). - const uint32_t VOL = 4; - { - uint32_t t[8] = {0x5000, fmts[1] << 20, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55}; - table_insert(table, t, 1); - } - VkBuffer tb; void* tbp; - CHECK(make_buffer(table.size() * 4, VK_BUFFER_USAGE_STORAGE_BUFFER_BIT, &tb, &tbp)); - std::memcpy(tbp, table.data(), table.size() * 4); - - const uint32_t W = 8; - VkImage img[3]; VkImageView view[3]; - for (int k = 0; k < 3; k++) { - VkImageCreateInfo ii{VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO}; - ii.imageType = VK_IMAGE_TYPE_2D; ii.format = vkf[k]; ii.extent = {W, W, 1}; ii.mipLevels = 1; ii.arrayLayers = 1; - ii.samples = VK_SAMPLE_COUNT_1_BIT; ii.tiling = VK_IMAGE_TILING_OPTIMAL; - ii.usage = VK_IMAGE_USAGE_STORAGE_BIT | VK_IMAGE_USAGE_SAMPLED_BIT | VK_IMAGE_USAGE_TRANSFER_SRC_BIT | - VK_IMAGE_USAGE_TRANSFER_DST_BIT; - CHECK(vkCreateImage(dev, &ii, nullptr, &img[k])); - VkMemoryRequirements mr; vkGetImageMemoryRequirements(dev, img[k], &mr); - VkMemoryAllocateInfo mai{VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO}; - mai.allocationSize = mr.size; mai.memoryTypeIndex = memtype(mr.memoryTypeBits, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT); - VkDeviceMemory m; CHECK(vkAllocateMemory(dev, &mai, nullptr, &m)); - CHECK(vkBindImageMemory(dev, img[k], m, 0)); - VkImageViewCreateInfo vi{VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO}; - vi.image = img[k]; vi.viewType = VK_IMAGE_VIEW_TYPE_2D; vi.format = vkf[k]; - vi.subresourceRange = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1}; - CHECK(vkCreateImageView(dev, &vi, nullptr, &view[k])); - } - VkImage wide; VkImageView wide_view; - { - VkImageCreateInfo ii{VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO}; - ii.imageType = VK_IMAGE_TYPE_2D; ii.format = vkf[0]; ii.extent = {WIDE_W, WIDE_H, 1}; - ii.mipLevels = WIDE_MIPS; ii.arrayLayers = 1; ii.samples = VK_SAMPLE_COUNT_1_BIT; - ii.tiling = VK_IMAGE_TILING_OPTIMAL; ii.usage = VK_IMAGE_USAGE_SAMPLED_BIT; - CHECK(vkCreateImage(dev, &ii, nullptr, &wide)); - VkMemoryRequirements mr; vkGetImageMemoryRequirements(dev, wide, &mr); - VkMemoryAllocateInfo mai{VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO}; - mai.allocationSize = mr.size; mai.memoryTypeIndex = memtype(mr.memoryTypeBits, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT); - VkDeviceMemory m; CHECK(vkAllocateMemory(dev, &mai, nullptr, &m)); - CHECK(vkBindImageMemory(dev, wide, m, 0)); - VkImageViewCreateInfo vi{VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO}; - vi.image = wide; vi.viewType = VK_IMAGE_VIEW_TYPE_2D; vi.format = vkf[0]; - vi.subresourceRange = {VK_IMAGE_ASPECT_COLOR_BIT, 0, WIDE_MIPS, 0, 1}; - CHECK(vkCreateImageView(dev, &vi, nullptr, &wide_view)); - } - VkImage vol; VkImageView vol_view; - { - VkImageCreateInfo ii{VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO}; - ii.imageType = VK_IMAGE_TYPE_3D; ii.format = vkf[1]; ii.extent = {VOL, VOL, VOL}; - ii.mipLevels = 1; ii.arrayLayers = 1; ii.samples = VK_SAMPLE_COUNT_1_BIT; ii.tiling = VK_IMAGE_TILING_OPTIMAL; - ii.usage = VK_IMAGE_USAGE_STORAGE_BIT | VK_IMAGE_USAGE_TRANSFER_SRC_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT; - CHECK(vkCreateImage(dev, &ii, nullptr, &vol)); - VkMemoryRequirements mr; vkGetImageMemoryRequirements(dev, vol, &mr); - VkMemoryAllocateInfo mai{VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO}; - mai.allocationSize = mr.size; mai.memoryTypeIndex = memtype(mr.memoryTypeBits, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT); - VkDeviceMemory m; CHECK(vkAllocateMemory(dev, &mai, nullptr, &m)); - CHECK(vkBindImageMemory(dev, vol, m, 0)); - VkImageViewCreateInfo vi{VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO}; - vi.image = vol; vi.viewType = VK_IMAGE_VIEW_TYPE_3D; vi.format = vkf[1]; - vi.subresourceRange = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1}; - CHECK(vkCreateImageView(dev, &vi, nullptr, &vol_view)); - } - VkSamplerCreateInfo sci{VK_STRUCTURE_TYPE_SAMPLER_CREATE_INFO}; - VkSampler sampler; CHECK(vkCreateSampler(dev, &sci, nullptr, &sampler)); - // Set 0: binding 0 = sampled images, 1 = samplers, 2 = hash table, 8/9/10 = float/uint/sint 2D storage image arrays. - // Five elements each: index 0 stands for the runtime's fallback, image k is at index k + 1 and the 16x4 image at - // index 4. Binding 0 holds each image's view in its own format (typed image_load reads the uint and sint ones - // through integer aliases); every element of a storage array holds the image of its class, so all of them are - // valid descriptors. Bindings 4 and 7 = the 2D and 3D r32ui storage images of the image atomics: the uint image - // and the volume, in every element. - constexpr uint32_t N = 5; - VkDescriptorSetLayoutBinding b[8]{}; - b[0] = {0, VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE, N, VK_SHADER_STAGE_COMPUTE_BIT, nullptr}; - b[1] = {1, VK_DESCRIPTOR_TYPE_SAMPLER, 1, VK_SHADER_STAGE_COMPUTE_BIT, nullptr}; - b[2] = {2, VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, 1, VK_SHADER_STAGE_COMPUTE_BIT, nullptr}; - for (int k = 0; k < 3; k++) b[3 + k] = {uint32_t(8 + k), VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, N, VK_SHADER_STAGE_COMPUTE_BIT, nullptr}; - b[6] = {4, VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, N, VK_SHADER_STAGE_COMPUTE_BIT, nullptr}; - b[7] = {7, VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, N, VK_SHADER_STAGE_COMPUTE_BIT, nullptr}; - VkDescriptorSetLayoutCreateInfo dli{VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO}; - dli.bindingCount = 8; dli.pBindings = b; - VkDescriptorSetLayout dsl; CHECK(vkCreateDescriptorSetLayout(dev, &dli, nullptr, &dsl)); - VkDescriptorPoolSize ps[4] = { - {VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE, N}, - {VK_DESCRIPTOR_TYPE_SAMPLER, 1}, - {VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, 1}, - {VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, 5 * N}, - }; - VkDescriptorPoolCreateInfo dpi{VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO}; - dpi.maxSets = 1; dpi.poolSizeCount = 4; dpi.pPoolSizes = ps; - VkDescriptorPool dp; CHECK(vkCreateDescriptorPool(dev, &dpi, nullptr, &dp)); - VkDescriptorSetAllocateInfo dai{VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO}; - dai.descriptorPool = dp; dai.descriptorSetCount = 1; dai.pSetLayouts = &dsl; - VkDescriptorSet ds; CHECK(vkAllocateDescriptorSets(dev, &dai, &ds)); - VkDescriptorBufferInfo tbi{tb, 0, VK_WHOLE_SIZE}; - VkDescriptorImageInfo sii[N] = {{VK_NULL_HANDLE, view[0], VK_IMAGE_LAYOUT_GENERAL}, - {VK_NULL_HANDLE, view[0], VK_IMAGE_LAYOUT_GENERAL}, - {VK_NULL_HANDLE, view[1], VK_IMAGE_LAYOUT_GENERAL}, - {VK_NULL_HANDLE, view[2], VK_IMAGE_LAYOUT_GENERAL}, - {VK_NULL_HANDLE, wide_view, VK_IMAGE_LAYOUT_GENERAL}}; - VkDescriptorImageInfo smpi{sampler, VK_NULL_HANDLE, VK_IMAGE_LAYOUT_UNDEFINED}; - VkDescriptorImageInfo dii[3][N]; - VkDescriptorImageInfo r32ui[N], r32ui_3d[N]; - VkWriteDescriptorSet wr[8]{}; - for (auto& w : wr) { w.sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET; w.dstSet = ds; w.descriptorCount = 1; } - wr[0].dstBinding = 0; wr[0].descriptorType = VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE; wr[0].pImageInfo = sii; - wr[0].descriptorCount = N; - wr[1].dstBinding = 1; wr[1].descriptorType = VK_DESCRIPTOR_TYPE_SAMPLER; wr[1].pImageInfo = &smpi; - wr[2].dstBinding = 2; wr[2].descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER; wr[2].pBufferInfo = &tbi; - for (int k = 0; k < 3; k++) { - for (uint32_t e = 0; e < N; e++) dii[k][e] = {VK_NULL_HANDLE, view[k], VK_IMAGE_LAYOUT_GENERAL}; - wr[3 + k].dstBinding = 8 + k; wr[3 + k].descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_IMAGE; - wr[3 + k].pImageInfo = dii[k]; wr[3 + k].descriptorCount = N; - } - for (uint32_t e = 0; e < N; e++) r32ui[e] = {VK_NULL_HANDLE, view[1], VK_IMAGE_LAYOUT_GENERAL}; - wr[6].dstBinding = 4; wr[6].descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_IMAGE; - wr[6].pImageInfo = r32ui; wr[6].descriptorCount = N; - for (uint32_t e = 0; e < N; e++) r32ui_3d[e] = {VK_NULL_HANDLE, vol_view, VK_IMAGE_LAYOUT_GENERAL}; - wr[7].dstBinding = 7; wr[7].descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_IMAGE; - wr[7].pImageInfo = r32ui_3d; wr[7].descriptorCount = N; - vkUpdateDescriptorSets(dev, 8, wr, 0, nullptr); - - VkShaderModuleCreateInfo smi{VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO}; - smi.codeSize = code.size(); smi.pCode = reinterpret_cast(code.data()); - VkShaderModule sm; CHECK(vkCreateShaderModule(dev, &smi, nullptr, &sm)); - // LEONIDA_PC_TAIL_UBO=1 (rdna2spirv.py --pc-tail-ubo): s0..s31 only, 128 bytes; a module that reads the tail - // gets it, all zero as without the flag, from a uniform block at set 1 (vk_pc_tail.h). - const bool tail_block = pc_tail && - leonida::vk_test::spirv_declares_set(code.data(), code.size(), leonida::vk_test::pc_tail_set); - leonida::vk_test::PcTail tail; - if (tail_block && !tail.create(vkGetDeviceProcAddr, dev, mp, props.limits.minUniformBufferOffsetAlignment, - VK_SHADER_STAGE_COMPUTE_BIT, 1)) { - std::fprintf(stderr, "FAILED creating the --pc-tail-ubo block\n"); - return 1; - } - VkPushConstantRange pcr{VK_SHADER_STAGE_COMPUTE_BIT, 0, pc_bytes}; - VkPipelineLayoutCreateInfo pli{VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO}; - pli.setLayoutCount = 1; pli.pSetLayouts = &dsl; pli.pushConstantRangeCount = 1; pli.pPushConstantRanges = &pcr; - const VkDescriptorSetLayout set_layouts[] = {dsl, tail.set_layout}; - if (tail_block) { pli.setLayoutCount = 2; pli.pSetLayouts = set_layouts; } - VkPipelineLayout pl; CHECK(vkCreatePipelineLayout(dev, &pli, nullptr, &pl)); - VkComputePipelineCreateInfo cpi{VK_STRUCTURE_TYPE_COMPUTE_PIPELINE_CREATE_INFO}; - cpi.stage = {VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO}; - cpi.stage.stage = VK_SHADER_STAGE_COMPUTE_BIT; cpi.stage.module = sm; cpi.stage.pName = "main"; - cpi.layout = pl; - VkPipeline pipe; CHECK(vkCreateComputePipelines(dev, VK_NULL_HANDLE, 1, &cpi, nullptr, &pipe)); - - const uint32_t image_words = W * W * (signed_zero ? 4 : 1); - VkBuffer rb[3]; void* rbp[3]; - for (int k = 0; k < 3; k++) CHECK(make_buffer(image_words * 4, VK_BUFFER_USAGE_TRANSFER_DST_BIT, &rb[k], &rbp[k])); - // Load and words modes: what the uint and sint images hold before the dispatch, texel (x, y) at i = 8y + x. - // The last row of the D16 fixture ("load-d16" only) exercises both sides of each 16-bit boundary. - struct PackedLoad { uint32_t u; int32_t s, sum; }; - constexpr PackedLoad boundary[] = { - {65535, 0, 65535}, {65536, 0, 65535}, {65537, 0, 65535}, {0, 32767, 32767}, - {0, 32768, 32767}, {0, -32768, -32768}, {0, -32769, -32768}, {65536, -32769, 32767}, - }; - static_assert(sizeof(boundary) / sizeof(boundary[0]) == W); - // Load/words modes seed the integer images. The signed-zero probe seeds every component of all three images. - const int first_fill = signed_zero ? 0 : filled ? 1 : 3; - VkBuffer fill[3]{}; - for (int k = first_fill; k < 3; ++k) { - void* mapped; - CHECK(make_buffer(image_words * 4, VK_BUFFER_USAGE_TRANSFER_SRC_BIT, &fill[k], &mapped)); - auto* words = static_cast(mapped); - for (uint32_t i = 0; i < image_words; ++i) { - const bool edge = packed_load && i / W == W - 1; - if (signed_zero) words[i] = 0x39000000u + k * image_words + i; - else if (k == 1) words[i] = edge ? boundary[i % W].u : 100 + i; - else words[i] = static_cast(edge ? boundary[i % W].s : -2 * int32_t(i)); - } - } - // The volume's fill and its read-back, used in words mode. - const uint32_t vol_texels = VOL * VOL * VOL; - VkBuffer vol_fill{}, vol_rb{}; void* vol_fillp = nullptr; void* vol_rbp = nullptr; - if (words_mode) { - CHECK(make_buffer(vol_texels * 4, VK_BUFFER_USAGE_TRANSFER_SRC_BIT, &vol_fill, &vol_fillp)); - CHECK(make_buffer(vol_texels * 4, VK_BUFFER_USAGE_TRANSFER_DST_BIT, &vol_rb, &vol_rbp)); - for (uint32_t i = 0; i < vol_texels; i++) static_cast(vol_fillp)[i] = 200 + i; - } - VkCommandPoolCreateInfo cpci{VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO}; cpci.queueFamilyIndex = qi; - VkCommandPool pool; CHECK(vkCreateCommandPool(dev, &cpci, nullptr, &pool)); - VkCommandBufferAllocateInfo cai{VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO}; - cai.commandPool = pool; cai.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY; cai.commandBufferCount = 1; - VkCommandBuffer cmd; CHECK(vkAllocateCommandBuffers(dev, &cai, &cmd)); - VkCommandBufferBeginInfo cbi{VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO}; - CHECK(vkBeginCommandBuffer(cmd, &cbi)); - VkImageMemoryBarrier ib[3]{}; - for (int k = 0; k < 3; k++) { - ib[k].sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER; ib[k].image = img[k]; - ib[k].oldLayout = VK_IMAGE_LAYOUT_UNDEFINED; ib[k].newLayout = VK_IMAGE_LAYOUT_GENERAL; - ib[k].dstAccessMask = VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT; - ib[k].srcQueueFamilyIndex = ib[k].dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; - ib[k].subresourceRange = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1}; - if (k >= first_fill) { // filled by a copy first - ib[k].newLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL; ib[k].dstAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT; - } - } - vkCmdPipelineBarrier(cmd, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, - VK_PIPELINE_STAGE_TRANSFER_BIT | VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, 0, 0, nullptr, 0, - nullptr, 3, ib); - VkImageMemoryBarrier wide_ib = ib[0]; // every level: the descriptor names the whole image in GENERAL - wide_ib.image = wide; wide_ib.newLayout = VK_IMAGE_LAYOUT_GENERAL; wide_ib.dstAccessMask = VK_ACCESS_SHADER_READ_BIT; - wide_ib.subresourceRange = {VK_IMAGE_ASPECT_COLOR_BIT, 0, WIDE_MIPS, 0, 1}; - vkCmdPipelineBarrier(cmd, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, 0, 0, nullptr, 0, - nullptr, 1, &wide_ib); - VkImageMemoryBarrier vol_ib = ib[0]; - vol_ib.image = vol; vol_ib.newLayout = VK_IMAGE_LAYOUT_GENERAL; - vol_ib.dstAccessMask = VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT; - const VkImageSubresourceLayers vol_layers{VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1}; - if (words_mode) { // filled by a copy first - vol_ib.newLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL; vol_ib.dstAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT; - vkCmdPipelineBarrier(cmd, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, 0, 0, nullptr, 0, - nullptr, 1, &vol_ib); - VkBufferImageCopy bic{}; - bic.imageSubresource = vol_layers; bic.imageExtent = {VOL, VOL, VOL}; - vkCmdCopyBufferToImage(cmd, vol_fill, vol, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, &bic); - vol_ib.oldLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL; vol_ib.newLayout = VK_IMAGE_LAYOUT_GENERAL; - vol_ib.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT; - vol_ib.dstAccessMask = VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT; - vkCmdPipelineBarrier(cmd, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, 0, 0, nullptr, 0, - nullptr, 1, &vol_ib); - } else { - vkCmdPipelineBarrier(cmd, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, 0, 0, nullptr, - 0, nullptr, 1, &vol_ib); - } - if (first_fill < 3) { - for (int k = first_fill; k < 3; k++) { - VkBufferImageCopy bic{}; - bic.imageSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1}; bic.imageExtent = {W, W, 1}; - vkCmdCopyBufferToImage(cmd, fill[k], img[k], VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, &bic); - ib[k].oldLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL; ib[k].newLayout = VK_IMAGE_LAYOUT_GENERAL; - ib[k].srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT; - ib[k].dstAccessMask = VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT; - } - vkCmdPipelineBarrier(cmd, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, 0, 0, - nullptr, 0, nullptr, 3 - first_fill, ib + first_fill); - } - vkCmdBindPipeline(cmd, VK_PIPELINE_BIND_POINT_COMPUTE, pipe); - vkCmdBindDescriptorSets(cmd, VK_PIPELINE_BIND_POINT_COMPUTE, pl, 0, 1, &ds, 0, nullptr); - uint32_t pc[36] = {}; - vkCmdPushConstants(cmd, pl, VK_SHADER_STAGE_COMPUTE_BIT, 0, pc_bytes, pc); - if (tail_block) { - const uint32_t offset = tail.offset(0); // PcTail starts zeroed: the tail stays all zero, as pushed before - vkCmdBindDescriptorSets(cmd, VK_PIPELINE_BIND_POINT_COMPUTE, pl, leonida::vk_test::pc_tail_set, 1, &tail.set, - 1, &offset); - } - vkCmdDispatch(cmd, 1, 1, 1); - for (int k = 0; k < 3; k++) { - ib[k].oldLayout = VK_IMAGE_LAYOUT_GENERAL; ib[k].newLayout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL; - ib[k].srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT | VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT; - ib[k].dstAccessMask = VK_ACCESS_TRANSFER_READ_BIT; - } - vkCmdPipelineBarrier(cmd, VK_PIPELINE_STAGE_TRANSFER_BIT | VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, - VK_PIPELINE_STAGE_TRANSFER_BIT, 0, 0, nullptr, 0, nullptr, 3, ib); - for (int k = 0; k < 3; k++) { - VkBufferImageCopy bic{}; - bic.imageSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1}; bic.imageExtent = {W, W, 1}; - vkCmdCopyImageToBuffer(cmd, img[k], VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, rb[k], 1, &bic); - } - if (words_mode) { - vol_ib.oldLayout = VK_IMAGE_LAYOUT_GENERAL; vol_ib.newLayout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL; - vol_ib.srcAccessMask = VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT; - vol_ib.dstAccessMask = VK_ACCESS_TRANSFER_READ_BIT; - vkCmdPipelineBarrier(cmd, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, 0, 0, nullptr, 0, - nullptr, 1, &vol_ib); - VkBufferImageCopy bic{}; - bic.imageSubresource = vol_layers; bic.imageExtent = {VOL, VOL, VOL}; - vkCmdCopyImageToBuffer(cmd, vol, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, vol_rb, 1, &bic); - } - // Make every copy's readback writes visible to the host before it reads the mapped buffers. - VkMemoryBarrier host{VK_STRUCTURE_TYPE_MEMORY_BARRIER}; - host.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT; - host.dstAccessMask = VK_ACCESS_HOST_READ_BIT; - vkCmdPipelineBarrier(cmd, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_HOST_BIT, - 0, 1, &host, 0, nullptr, 0, nullptr); - CHECK(vkEndCommandBuffer(cmd)); - VkSubmitInfo si{VK_STRUCTURE_TYPE_SUBMIT_INFO}; si.commandBufferCount = 1; si.pCommandBuffers = &cmd; - CHECK(vkQueueSubmit(q, 1, &si, VK_NULL_HANDLE)); - CHECK(vkQueueWaitIdle(q)); - - if (signed_zero) { - constexpr uint32_t neg = 0x80000000; - constexpr uint32_t stores[] = {neg, 0, 0, 0, neg, 0x3f800000, 0, 0, neg, neg, 0, 0}; - const uint32_t total = 3 * image_words; - uint32_t bad = 0; - for (uint32_t i = 0; i < total; ++i) { - const uint32_t expected = i < 12 ? stores[i] : 0x39000000u + i; - const uint32_t actual = static_cast(rbp[i / image_words])[i % image_words]; - if (actual != expected) { - std::printf("word %u: expected %08x, observed %08x\n", i, expected, actual); - ++bad; - } - } - std::printf("%u/%u words exact\n", total - bad, total); - return bad ? 1 : 0; - } - if (words_mode) { - const char* names[3] = {"uint", "sint", "volume"}; - const void* words[3] = {rbp[1], rbp[2], vol_rbp}; - static_assert(W * W == VOL * VOL * VOL, "64 words an image"); - for (int k = 0; k < 3; k++) { - std::printf("%s words:", names[k]); - for (uint32_t i = 0; i < W * W; i++) std::printf(" 0x%08x", static_cast(words[k])[i]); - std::printf("\n"); - } - return 0; - } - uint32_t bad[3] = {}; - for (uint32_t y = 0; y < W; y++) - for (uint32_t x = 0; x < W; x++) { - uint32_t i = y * W + x; - const uint8_t* c = static_cast(rbp[0]) + 4 * i; - int er = int(std::lround(x / 7.0 * 255)), eg = int(std::lround(y / 7.0 * 255)); - if (std::abs(c[0] - er) > 1 || std::abs(c[1] - eg) > 1 || std::abs(c[2] - 128) > 1 || c[3] != 255) bad[0]++; - const bool edge = packed_load && y == W - 1; - if (static_cast(rbp[1])[i] != (edge ? boundary[x].u : 100 + i)) bad[1]++; - // load: the uint texel (100 + 8y + x) plus the sint one (-2 (8y + x)), both read with image_load - const int32_t want_s = edge ? boundary[x].sum : load_mode ? 100 - int32_t(i) : -int32_t(i); - if (static_cast(rbp[2])[i] != want_s) bad[2]++; - } - const uint8_t* c = static_cast(rbp[0]) + 4 * (3 * W + 5); - std::printf("rgba8 unorm (float view): %u bad, texel(5,3) = %u %u %u %u\n", bad[0], c[0], c[1], c[2], c[3]); - std::printf("r32 uint (uint view): %u bad, texel(5,3) = %u\n", bad[1], static_cast(rbp[1])[3 * W + 5]); - std::printf("r32 sint (sint view): %u bad, texel(5,3) = %d\n", bad[2], static_cast(rbp[2])[3 * W + 5]); - return (bad[0] || bad[1] || bad[2]) ? 1 : 0; -} diff --git a/runtime/test/vk_sync_validation_selftest.cpp b/runtime/test/vk_sync_validation_selftest.cpp deleted file mode 100644 index 6b6cf380f..000000000 --- a/runtime/test/vk_sync_validation_selftest.cpp +++ /dev/null @@ -1,93 +0,0 @@ -// Proves that Vulkan synchronization validation reports hazards on this machine when LEONIDA_VK_VALIDATION=1, so a -// "0 validation errors" from the GPU tests means the layer looked, not that it was absent or silent. -// -// vk_test_device.h asks for VK_VALIDATION_FEATURE_ENABLE_SYNCHRONIZATION_VALIDATION_EXT whenever validation is on. -// This test records two vkCmdCopyBuffer into the same bytes: -// - without a barrier between them, synchronization validation must report the write-after-write hazard; -// - with a transfer -> transfer memory barrier, it must report nothing. -// The second half keeps the first honest: a layer that reported every copy would fail it. -// -// Exit codes: 0 pass; 1 the hazard was not reported, the barrier case was, or the device failed; -// 77 (ctest skip) when validation is not requested or there is no Vulkan device. No game files, no runtime code. -#include "vk_test_device.h" - -#include -#include -#include - -namespace { - -// Validation errors reported while recording and submitting the two copies, or ~0u when the copies could not run. -unsigned copy_twice(vktest::Device& d, bool barrier) { - void* mapped = nullptr; - const VkBuffer src = d.buffer(4096, VK_BUFFER_USAGE_TRANSFER_SRC_BIT, &mapped); - const VkBuffer dst = d.buffer(4096, VK_BUFFER_USAGE_TRANSFER_DST_BIT, &mapped); - if (!src || !dst) return ~0u; - const auto copy = d.fn("vkCmdCopyBuffer"); - const auto pipeline_barrier = d.fn("vkCmdPipelineBarrier"); - const unsigned before = d.validation_errors(); - const bool ran = d.run([&](VkCommandBuffer cb) { - const VkBufferCopy region{0, 0, 4096}; - copy(cb, src, dst, 1, ®ion); - if (barrier) { - VkMemoryBarrier memory{VK_STRUCTURE_TYPE_MEMORY_BARRIER}; - memory.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT; - memory.dstAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT; - pipeline_barrier(cb, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, 0, 1, &memory, 0, - nullptr, 0, nullptr); - } - copy(cb, src, dst, 1, ®ion); - return true; - }); - return ran ? d.validation_errors() - before : ~0u; -} - -bool validation_requested() { -#ifdef _MSC_VER -#pragma warning(push) -#pragma warning(disable : 4996) // getenv: read once, as vk_test_device.h does -#endif - const char* env = std::getenv("LEONIDA_VK_VALIDATION"); -#ifdef _MSC_VER -#pragma warning(pop) -#endif - return env && std::strcmp(env, "0") != 0; -} - -} // namespace - -int main() { - if (!validation_requested()) { - std::printf("SKIP vk_sync_validation_selftest: LEONIDA_VK_VALIDATION is not set, nothing to prove\n"); - return 77; - } - vktest::Device d; - const auto status = d.initialize(); // fails, with a message, when the Khronos layer is not installed - if (status == vktest::DeviceStatus::unavailable) { - std::printf("SKIP vk_sync_validation_selftest: no Vulkan device\n"); - return 77; - } - if (status != vktest::DeviceStatus::ready || !d.validation) { - std::fprintf(stderr, "vk_sync_validation_selftest: no validated Vulkan device\n"); - return 1; - } - const unsigned hazard = copy_twice(d, false); - const unsigned clean = copy_twice(d, true); - if (hazard == ~0u || clean == ~0u) { - std::fprintf(stderr, "vk_sync_validation_selftest: the copies could not be recorded or submitted\n"); - return 1; - } - std::printf("two copies into the same bytes: %u validation error(s) without a barrier, %u with one\n", hazard, - clean); - if (hazard == 0) { - std::fprintf(stderr, "vk_sync_validation_selftest: FAIL, the write-after-write hazard was not reported: " - "synchronization validation is not active, so 0 errors elsewhere proves nothing\n"); - return 1; - } - if (clean != 0) { - std::fprintf(stderr, "vk_sync_validation_selftest: FAIL, the synchronized copies were reported too\n"); - return 1; - } - std::printf("vk_sync_validation_selftest: PASS, synchronization validation is active\n"); - return 0; -} diff --git a/runtime/test/vk_test_device.h b/runtime/test/vk_test_device.h deleted file mode 100644 index 5cccd1836..000000000 --- a/runtime/test/vk_test_device.h +++ /dev/null @@ -1,786 +0,0 @@ -// Shared setup for the GPU tests of the D3D12 layer: a Vulkan 1.3 device (or 1.2 with VK_KHR_dynamic_rendering and -// VK_KHR_synchronization2) with dynamicRendering, synchronization2, timelineSemaphore and -// separateDepthStencilLayouts, images, buffers and one-shot submissions. -// Set LEONIDA_VK_VALIDATION=1 to run under VK_LAYER_KHRONOS_validation; Device::validation_errors() counts errors. -#pragma once - -#include "vulkan_loader.h" -#include "../src/queue_families.h" -#include "../src/vulkan_device_filter.h" -#include "../src/vulkan13_features.h" -#include "vk_device_pick.h" -#include "../src/subgroup_size.h" - -#include -#include -#include -#include -#include -#include -#include - -namespace vktest { - -inline unsigned& validation_error_count() { - static unsigned count = 0; - return count; -} - -inline unsigned& known_validation_error_count() { - static unsigned count = 0; - return count; -} - -// The NVIDIA validation layer checks an sRGB swapchain as if it also had VK_IMAGE_USAGE_STORAGE_BIT, which the -// presenter never requests and sRGB swapchain formats cannot support on that driver. Its VUID 01778 covers the -// first message and the max-layers/max-extent follow-ons, so match the VUID rather than only the first text. The -// presenter's own usage is checked against supportedUsageFlags before creation, so this VUID is the known false -// positive here. It is counted separately so a test can skip only when it is the sole validation error. -inline bool known_srgb_swapchain_storage_error(const VkDebugUtilsMessengerCallbackDataEXT* data) { - return data && data->pMessage && data->messageIdNumber == 0xc036022f; -} - -// Only validation-type errors fail a test. General messages come from the loader and the layers around the -// application: a third-party implicit layer that fails to load (an overlay or capture tool, for example) reports a -// general error that says nothing about this code, so it is printed but not counted. -inline VKAPI_ATTR VkBool32 VKAPI_CALL on_validation(VkDebugUtilsMessageSeverityFlagBitsEXT severity, - VkDebugUtilsMessageTypeFlagsEXT types, - const VkDebugUtilsMessengerCallbackDataEXT* data, void*) { - const bool validation = (types & VK_DEBUG_UTILS_MESSAGE_TYPE_VALIDATION_BIT_EXT) != 0; - const bool known = (severity & VK_DEBUG_UTILS_MESSAGE_SEVERITY_ERROR_BIT_EXT) && validation && - known_srgb_swapchain_storage_error(data); - if ((severity & VK_DEBUG_UTILS_MESSAGE_SEVERITY_ERROR_BIT_EXT) && validation) { - ++validation_error_count(); - if (known) ++known_validation_error_count(); - } - std::fprintf(stderr, "%s%s: %s\n", validation ? "validation" : "vulkan (not counted)", - known ? " (known sRGB swapchain check)" : "", - data && data->pMessage ? data->pMessage : "(no message)"); - return VK_FALSE; -} - -enum class DeviceStatus { ready, unavailable, failed }; - -template -VkResult enumerate_all(std::vector& entries, Enumerate enumerate) { - VkResult result; - do { - std::uint32_t count = 0; - result = enumerate(&count, nullptr); - if (result != VK_SUCCESS) return result; - entries.resize(count); - if (count == 0) return VK_SUCCESS; - result = enumerate(&count, entries.data()); - if (result == VK_SUCCESS) entries.resize(count); - } while (result == VK_INCOMPLETE); - return result; -} - -class Device { -public: - PFN_vkGetInstanceProcAddr instance_proc = nullptr; - PFN_vkGetDeviceProcAddr device_proc = nullptr; - VkInstance instance = VK_NULL_HANDLE; - VkPhysicalDevice physical = VK_NULL_HANDLE; - VkDevice device = VK_NULL_HANDLE; - VkQueue queue = VK_NULL_HANDLE; - std::uint32_t family = 0; - // Set before initialize(): how many queues of `family` to create (fewer if the family has fewer). `queues` holds the - // handles; queues[0] == queue. A test that wants distinct VkQueues for its D3D12 queues passes them on as - // VulkanDeviceInfo::command_queues when there is more than one. - std::uint32_t queue_count_wanted = 1; - std::uint32_t family_queue_count = 1; // the family's queueCount, known after the device is chosen - std::vector queues; - bool validation = false; - bool bc = false; // textureCompressionBC enabled - bool all_queue_types = false; - VkQueue compute_queue = VK_NULL_HANDLE, copy_queue = VK_NULL_HANDLE; - std::uint32_t compute_family = 0, copy_family = 0; - std::vector families; - VkPhysicalDeviceFeatures enabled{}; // the core features enabled on `device` - bool bindless = false; // the features the bindless set 0 needs are enabled - bool partially_bound = false; // and its slots can stay empty - bool image_view_min_lod = false; - bool sampler_filter_minmax = false; - bool vertex_attribute_divisor = false; - bool storage_buffer_8bit = false; // storageBuffer8BitAccess enabled - bool conditional_rendering = false; // VK_EXT_conditional_rendering enabled, where available - bool host_image_copy = false; // VK_EXT_host_image_copy and hostImageCopy enabled - // create(true) only: VK_KHR (else EXT) swapchain_maintenance1 and its feature enabled, with the surface half on the - // instance, so a vsync swapchain can switch to IMMEDIATE or FIFO_RELAXED per present. - bool swapchain_maintenance1 = false; - bool shader_fma = false; // VK_KHR_shader_fma and shaderFmaFloat32 enabled (OpFmaKHR, rdna2spirv.py --fma khr) - bool occlusion_query_precise = false; // occlusionQueryPrecise enabled - bool pipeline_statistics_query = false; // pipelineStatisticsQuery enabled - bool request_debug_utils = false; // set before create(): enable VK_EXT_debug_utils when the loader has it - bool request_buffer_device_address = false; // set before create(): enable bufferDeviceAddress where supported - bool buffer_device_address = false; // enabled: buffer() memory and buffers can be addressed (device_address()) - bool conservative_rasterization = false; // VK_EXT_conservative_rasterization enabled where available - bool request_mesh_shader = false; // set before create(): enable VK_EXT_mesh_shader (meshShader) where available - bool mesh_shader = false; // VK_EXT_mesh_shader and meshShader are enabled - bool debug_utils = false; // VK_EXT_debug_utils is enabled on the instance - // The subgroup sizes of the device, with subgroupSizeControl and computeFullSubgroups enabled where it has them. - leonida::SubgroupSizeCaps subgroup; - bool custom_border_color = false; // VK_EXT_custom_border_color and customBorderColors enabled - bool custom_border_color_without_format = false; - // VK_EXT_external_memory_host is enabled when non-zero: its minImportedHostPointerAlignment. - VkDeviceSize host_pointer_alignment = 0; - - Device() = default; - Device(const Device&) = delete; - Device& operator=(const Device&) = delete; - - ~Device() { - if (device) { - fn("vkDeviceWaitIdle")(device); - const auto destroy_image = fn("vkDestroyImage"); - const auto destroy_buffer = fn("vkDestroyBuffer"); - const auto free_memory = fn("vkFreeMemory"); - for (auto [image, memory] : images_) { - destroy_image(device, image, nullptr); - free_memory(device, memory, nullptr); - } - for (auto [buffer, memory] : buffers_) { - destroy_buffer(device, buffer, nullptr); - free_memory(device, memory, nullptr); - } - if (pool_) fn("vkDestroyCommandPool")(device, pool_, nullptr); - fn("vkDestroyDevice")(device, nullptr); - } - if (messenger_) { - reinterpret_cast( - instance_proc(instance, "vkDestroyDebugUtilsMessengerEXT"))(instance, messenger_, nullptr); - } - if (instance) - reinterpret_cast(instance_proc(instance, "vkDestroyInstance"))(instance, nullptr); - } - - // A Vulkan 1.3 function falls back to its KHR name on a 1.2 device. - template - F fn(const char* name) const { - return reinterpret_cast(leonida::device_proc_or_khr(device_proc, device, name)); - } - - template - F instance_fn(const char* name) const { - return reinterpret_cast(instance_proc(instance, name)); - } - - unsigned validation_errors() const { return validation_error_count(); } - unsigned known_validation_errors() const { return known_validation_error_count(); } - - // presentation: also enable VK_KHR_surface + VK_KHR_win32_surface and VK_KHR_swapchain (Windows only). - bool create(bool presentation = false) { return initialize(presentation) == DeviceStatus::ready; } - - DeviceStatus initialize(bool presentation = false) { - const auto failure = [](const char* call, VkResult result) { - std::fprintf(stderr, "%s failed (VkResult %d)\n", call, static_cast(result)); - return DeviceStatus::failed; - }; - instance_proc = load_vulkan(); - if (!instance_proc) return DeviceStatus::unavailable; - const auto create_instance = reinterpret_cast(instance_proc(nullptr, "vkCreateInstance")); - const auto enumerate_layers = reinterpret_cast( - instance_proc(nullptr, "vkEnumerateInstanceLayerProperties")); - -#ifdef _MSC_VER -#pragma warning(push) -#pragma warning(disable : 4996) // getenv: read once, at startup -#endif - const char* env = std::getenv("LEONIDA_VK_VALIDATION"); -#ifdef _MSC_VER -#pragma warning(pop) -#endif - validation = env && std::strcmp(env, "0") != 0; - const char* layer = "VK_LAYER_KHRONOS_validation"; - const char* debug_utils_name = VK_EXT_DEBUG_UTILS_EXTENSION_NAME; - VkDebugUtilsMessengerCreateInfoEXT messenger_info{VK_STRUCTURE_TYPE_DEBUG_UTILS_MESSENGER_CREATE_INFO_EXT}; - messenger_info.messageSeverity = - VK_DEBUG_UTILS_MESSAGE_SEVERITY_WARNING_BIT_EXT | VK_DEBUG_UTILS_MESSAGE_SEVERITY_ERROR_BIT_EXT; - messenger_info.messageType = VK_DEBUG_UTILS_MESSAGE_TYPE_VALIDATION_BIT_EXT; - messenger_info.pfnUserCallback = on_validation; - - const VkValidationFeatureEnableEXT sync_validation = - VK_VALIDATION_FEATURE_ENABLE_SYNCHRONIZATION_VALIDATION_EXT; - VkValidationFeaturesEXT validation_features{VK_STRUCTURE_TYPE_VALIDATION_FEATURES_EXT, &messenger_info}; - validation_features.enabledValidationFeatureCount = 1; - validation_features.pEnabledValidationFeatures = &sync_validation; - - VkApplicationInfo app{VK_STRUCTURE_TYPE_APPLICATION_INFO}; - app.apiVersion = VK_API_VERSION_1_3; - VkInstanceCreateInfo instance_info{VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO}; - instance_info.pApplicationInfo = &app; - std::vector instance_extensions; - bool surface_m1_khr = false, surface_m1_ext = false; - if (presentation) { - instance_extensions.push_back("VK_KHR_surface"); - instance_extensions.push_back("VK_KHR_win32_surface"); - const auto enumerate_instance = reinterpret_cast( - instance_proc(nullptr, "vkEnumerateInstanceExtensionProperties")); - std::uint32_t count = 0; - enumerate_instance(nullptr, &count, nullptr); - std::vector available(count); - enumerate_instance(nullptr, &count, available.data()); - bool caps2 = false; - for (const auto& e : available) // lists the HDR10 (ST.2084) surface formats, when the display has them - if (std::strcmp(e.extensionName, "VK_EXT_swapchain_colorspace") == 0) - instance_extensions.push_back("VK_EXT_swapchain_colorspace"); - for (const auto& e : available) { - caps2 = caps2 || std::strcmp(e.extensionName, "VK_KHR_get_surface_capabilities2") == 0; - surface_m1_khr = surface_m1_khr || std::strcmp(e.extensionName, "VK_KHR_surface_maintenance1") == 0; - surface_m1_ext = surface_m1_ext || std::strcmp(e.extensionName, "VK_EXT_surface_maintenance1") == 0; - } - if (caps2 && (surface_m1_khr || surface_m1_ext)) { - instance_extensions.push_back("VK_KHR_get_surface_capabilities2"); - if (surface_m1_khr) instance_extensions.push_back("VK_KHR_surface_maintenance1"); - if (surface_m1_ext) instance_extensions.push_back("VK_EXT_surface_maintenance1"); - } else { - surface_m1_khr = surface_m1_ext = false; - } - } - if (validation) { - std::vector layers; - const VkResult layer_result = enumerate_all(layers, enumerate_layers); - if (layer_result != VK_SUCCESS) return failure("vkEnumerateInstanceLayerProperties", layer_result); - bool found = false; - for (const auto& properties : layers) found = found || std::strcmp(properties.layerName, layer) == 0; - if (!found) { - std::fprintf(stderr, "LEONIDA_VK_VALIDATION is set but %s is not installed\n", layer); - return DeviceStatus::failed; - } - instance_info.pNext = &validation_features; - instance_info.enabledLayerCount = 1; - instance_info.ppEnabledLayerNames = &layer; - debug_utils = true; // the validation layer provides it - } else if (request_debug_utils) { - const auto enumerate = reinterpret_cast( - instance_proc(nullptr, "vkEnumerateInstanceExtensionProperties")); - std::uint32_t count = 0; - enumerate(nullptr, &count, nullptr); - std::vector extensions(count); - enumerate(nullptr, &count, extensions.data()); - for (const auto& e : extensions) - debug_utils = debug_utils || std::strcmp(e.extensionName, VK_EXT_DEBUG_UTILS_EXTENSION_NAME) == 0; - } - if (debug_utils) { - instance_extensions.push_back(debug_utils_name); - } - instance_info.enabledExtensionCount = std::uint32_t(instance_extensions.size()); - instance_info.ppEnabledExtensionNames = instance_extensions.data(); - VkResult result = create_instance(&instance_info, nullptr, &instance); - if (result == VK_ERROR_INCOMPATIBLE_DRIVER) return DeviceStatus::unavailable; - if (result != VK_SUCCESS) return failure("vkCreateInstance", result); - if (validation) { - const auto create_messenger = instance_fn("vkCreateDebugUtilsMessengerEXT"); - if (!create_messenger) return failure("vkCreateDebugUtilsMessengerEXT", VK_ERROR_EXTENSION_NOT_PRESENT); - result = create_messenger(instance, &messenger_info, nullptr, &messenger_); - if (result != VK_SUCCESS) return failure("vkCreateDebugUtilsMessengerEXT", result); - } - - const auto enumerate = instance_fn("vkEnumeratePhysicalDevices"); - const auto properties_of = instance_fn("vkGetPhysicalDeviceProperties"); - const auto families_of = - instance_fn("vkGetPhysicalDeviceQueueFamilyProperties"); - std::vector devices; - result = enumerate_all(devices, [&](std::uint32_t* count, VkPhysicalDevice* values) { - return enumerate(instance, count, values); - }); - if (result != VK_SUCCESS) return failure("vkEnumeratePhysicalDevices", result); - VkPhysicalDeviceProperties chosen{}; - int best_rank = -1; - const auto features2_of = instance_fn("vkGetPhysicalDeviceFeatures2"); - const auto device_extensions_of = - instance_fn("vkEnumerateDeviceExtensionProperties"); - leonida::Vulkan13Features candidate13; - for (auto candidate : devices) { - VkPhysicalDeviceProperties props{}; - properties_of(candidate, &props); - if (!leonida::vulkan_device_wanted(props.deviceName)) continue; - candidate13.query(candidate, props.apiVersion, features2_of, device_extensions_of); - if (!candidate13.usable()) continue; - std::uint32_t family_count = 0; - families_of(candidate, &family_count, nullptr); - std::vector candidate_families(family_count); - families_of(candidate, &family_count, candidate_families.data()); - for (std::uint32_t i = 0; i < family_count; ++i) { - if (!(candidate_families[i].queueFlags & VK_QUEUE_GRAPHICS_BIT)) continue; - if (const int rank = leonida::vk_test::device_rank(props.deviceType, props.vendorID); - rank > best_rank) { - physical = candidate; - family = i; - family_queue_count = candidate_families[i].queueCount; - chosen = props; - best_rank = rank; - v13_.choose(candidate13); - } - break; - } - } - if (!physical) { - if (const std::string filter = leonida::vulkan_device_filter(); !filter.empty()) { - // A filter that matches nothing fails the test instead of skipping it. - std::fprintf(stderr, - "LEONIDA_VK_DEVICE=%s: no Vulkan 1.3 device (or 1.2 with VK_KHR_dynamic_rendering and " - "VK_KHR_synchronization2) with a graphics queue matches\n", - filter.c_str()); - return DeviceStatus::failed; - } - std::fprintf(stderr, "no Vulkan 1.3 device (or 1.2 with VK_KHR_dynamic_rendering and " - "VK_KHR_synchronization2) with a graphics queue\n"); - return DeviceStatus::unavailable; - } - std::printf("device: %s%s%s\n", chosen.deviceName, v13_.core ? "" : " (Vulkan 1.2 + KHR extensions)", - validation ? " (validation on)" : ""); - - VkPhysicalDeviceVulkan11Features features11{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_1_FEATURES}; - VkPhysicalDeviceVulkan12Features features12{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_2_FEATURES, &features11}; - VkPhysicalDeviceFeatures2 features{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2, &features12}; - features2_of(physical, &features); - if (!features12.timelineSemaphore || !features12.separateDepthStencilLayouts || - !features12.bufferDeviceAddress) { - std::fprintf(stderr, "the device lacks dynamicRendering, synchronization2, timelineSemaphore or " - "separateDepthStencilLayouts\n"); - return DeviceStatus::unavailable; - } - // VK_EXT_conditional_rendering (SetPredication), where available. - { - const auto extensions_of = - instance_fn("vkEnumerateDeviceExtensionProperties"); - std::uint32_t extension_count = 0; - extensions_of(physical, nullptr, &extension_count, nullptr); - std::vector extensions(extension_count); - extensions_of(physical, nullptr, &extension_count, extensions.data()); - for (const auto& e : extensions) - if (!std::strcmp(e.extensionName, VK_EXT_CONDITIONAL_RENDERING_EXTENSION_NAME)) { - VkPhysicalDeviceConditionalRenderingFeaturesEXT supported{ - VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_CONDITIONAL_RENDERING_FEATURES_EXT}; - VkPhysicalDeviceFeatures2 query{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2, &supported}; - instance_fn("vkGetPhysicalDeviceFeatures2")(physical, &query); - conditional_rendering = supported.conditionalRendering == VK_TRUE; - } - } - VkPhysicalDeviceConditionalRenderingFeaturesEXT enable_conditional{ - VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_CONDITIONAL_RENDERING_FEATURES_EXT}; - enable_conditional.conditionalRendering = VK_TRUE; - - leonida::query_subgroup_size_caps(instance_fn("vkGetPhysicalDeviceProperties2"), - physical, v13_.subgroup_size_control, v13_.compute_full_subgroups, - subgroup); - std::printf("subgroup sizes: %u..%u (default %u), requirable in stages 0x%x, subgroupSizeControl %s, " - "computeFullSubgroups %s\n", - subgroup.min_size, subgroup.max_size, subgroup.default_size, unsigned(subgroup.required_stages), - subgroup.subgroup_size_control ? "on" : "off", subgroup.compute_full_subgroups ? "on" : "off"); - // shaderDrawParameters, where available: translated vertex shaders will read BaseVertex and BaseInstance once PR 436 - // (zero-based VS ids) is in; harmless before. - VkPhysicalDeviceVulkan11Features enable11{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_1_FEATURES, - v13_.enable(conditional_rendering ? &enable_conditional : nullptr)}; - enable11.shaderDrawParameters = features11.shaderDrawParameters; - VkPhysicalDeviceVulkan12Features enable12{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_2_FEATURES, &enable11}; - enable12.timelineSemaphore = VK_TRUE; - enable12.separateDepthStencilLayouts = VK_TRUE; - buffer_device_address = request_buffer_device_address && features12.bufferDeviceAddress == VK_TRUE; - enable12.bufferDeviceAddress = buffer_device_address; - storage_buffer_8bit = features12.storageBuffer8BitAccess == VK_TRUE; - enable12.storageBuffer8BitAccess = storage_buffer_8bit; - // What the bindless set 0 of the translated shaders needs, where the device has it: runtime arrays of - // images indexed dynamically, updated while the set is bound; and, to leave slots empty, partially bound - // bindings. - bindless = features12.runtimeDescriptorArray && features.features.shaderSampledImageArrayDynamicIndexing && - features.features.shaderStorageImageArrayDynamicIndexing && - features12.descriptorBindingSampledImageUpdateAfterBind && - features12.descriptorBindingStorageImageUpdateAfterBind && - features12.descriptorBindingStorageBufferUpdateAfterBind; - partially_bound = bindless && features12.descriptorBindingPartiallyBound; - enable12.runtimeDescriptorArray = bindless; - enable12.descriptorBindingSampledImageUpdateAfterBind = bindless; - enable12.descriptorBindingStorageImageUpdateAfterBind = bindless; - enable12.descriptorBindingStorageBufferUpdateAfterBind = bindless; - enable12.descriptorBindingPartiallyBound = partially_bound; - sampler_filter_minmax = features12.samplerFilterMinmax == VK_TRUE; - enable12.samplerFilterMinmax = sampler_filter_minmax; - enable12.bufferDeviceAddress = VK_TRUE; - - const std::uint32_t graphics_count = std::max(1u, std::min(queue_count_wanted, family_queue_count)); - const std::vector priority(graphics_count, 1.0f); - { - std::uint32_t family_count = 0; - families_of(physical, &family_count, nullptr); - families.resize(family_count); - families_of(physical, &family_count, families.data()); - } - compute_family = copy_family = family; - if (all_queue_types) { - const auto picked = leonida::pick_queue_families(families, family); - compute_family = picked.compute; - copy_family = picked.copy; - } - std::vector queue_infos; - for (std::uint32_t f : {family, compute_family, copy_family}) { - bool seen = false; - for (const auto& q : queue_infos) seen = seen || q.queueFamilyIndex == f; - if (seen) continue; - VkDeviceQueueCreateInfo q{VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO}; - q.queueFamilyIndex = f; - q.queueCount = f == family ? graphics_count : 1; - q.pQueuePriorities = priority.data(); - queue_infos.push_back(q); - sharing_.push_back(f); - } - VkPhysicalDeviceFeatures enable{}; - enable.textureCompressionBC = features.features.textureCompressionBC; // BC uploads, where available - enable.shaderInt64 = features.features.shaderInt64; // translated shaders declare Int64 (index features) - bc = features.features.textureCompressionBC == VK_TRUE; - enable.shaderSampledImageArrayDynamicIndexing = bindless; - enable.shaderStorageImageArrayDynamicIndexing = bindless; - enable.logicOp = features.features.logicOp; // d3d12_draw_test's logic-op draw, where available - enable.geometryShader = features.features.geometryShader; // d3d12_geometry_test, where available - enable.shaderInt64 = features.features.shaderInt64; // translated shaders declare Int64 for their addresses - const char* conditional_extension = VK_EXT_CONDITIONAL_RENDERING_EXTENSION_NAME; - - // VK_EXT_host_image_copy where the device has it, for the D3D12 layer's CPU texture copies. - const auto enumerate_extensions = - instance_fn("vkEnumerateDeviceExtensionProperties"); - std::uint32_t extension_count = 0; - enumerate_extensions(physical, nullptr, &extension_count, nullptr); - std::vector extensions(extension_count); - enumerate_extensions(physical, nullptr, &extension_count, extensions.data()); - VkPhysicalDeviceImageViewMinLodFeaturesEXT min_lod{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_IMAGE_VIEW_MIN_LOD_FEATURES_EXT}; - if (std::any_of(extensions.begin(), extensions.end(), [](const auto& e) { - return std::strcmp(e.extensionName, VK_EXT_IMAGE_VIEW_MIN_LOD_EXTENSION_NAME) == 0; - })) { - VkPhysicalDeviceFeatures2 query{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2, &min_lod}; - instance_fn("vkGetPhysicalDeviceFeatures2")(physical, &query); - image_view_min_lod = min_lod.minLod == VK_TRUE; - if (image_view_min_lod) { - min_lod.pNext = *v13_.next(); - *v13_.next() = &min_lod; - } - } - const char* divisor_extension = nullptr; - for (const char* name : - {VK_KHR_VERTEX_ATTRIBUTE_DIVISOR_EXTENSION_NAME, VK_EXT_VERTEX_ATTRIBUTE_DIVISOR_EXTENSION_NAME}) { - if (std::any_of(extensions.begin(), extensions.end(), - [&](const auto& e) { return std::strcmp(e.extensionName, name) == 0; })) { - divisor_extension = name; - break; - } - } - VkPhysicalDeviceVertexAttributeDivisorFeaturesKHR divisor_khr{ - VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VERTEX_ATTRIBUTE_DIVISOR_FEATURES_KHR}; - VkPhysicalDeviceVertexAttributeDivisorFeaturesEXT divisor_ext{ - VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VERTEX_ATTRIBUTE_DIVISOR_FEATURES_EXT}; - if (divisor_extension) { - const bool is_khr = std::strcmp(divisor_extension, VK_KHR_VERTEX_ATTRIBUTE_DIVISOR_EXTENSION_NAME) == 0; - VkPhysicalDeviceFeatures2 query{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2, - is_khr ? static_cast(&divisor_khr) : static_cast(&divisor_ext)}; - instance_fn("vkGetPhysicalDeviceFeatures2")(physical, &query); - vertex_attribute_divisor = (is_khr ? divisor_khr.vertexAttributeInstanceRateDivisor - : divisor_ext.vertexAttributeInstanceRateDivisor) == VK_TRUE; - if (vertex_attribute_divisor) { - if (is_khr) { - divisor_khr.pNext = *v13_.next(); - *v13_.next() = &divisor_khr; - } else { - divisor_ext.pNext = *v13_.next(); - *v13_.next() = &divisor_ext; - } - } - } - VkPhysicalDeviceHostImageCopyFeaturesEXT host_copy{ - VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_HOST_IMAGE_COPY_FEATURES_EXT}; - for (const auto& extension : extensions) { - if (std::strcmp(extension.extensionName, VK_EXT_HOST_IMAGE_COPY_EXTENSION_NAME) != 0) continue; - VkPhysicalDeviceFeatures2 query{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2, &host_copy}; - instance_fn("vkGetPhysicalDeviceFeatures2")(physical, &query); - host_image_copy = host_copy.hostImageCopy == VK_TRUE; - } - const char* host_image_copy_name = VK_EXT_HOST_IMAGE_COPY_EXTENSION_NAME; - if (host_image_copy) { - host_copy.pNext = *v13_.next(); // after the conditional rendering features, if any - *v13_.next() = &host_copy; - } - -#ifdef VK_KHR_SHADER_FMA_EXTENSION_NAME - // VK_KHR_shader_fma where the device has it: translated shaders built with --fma khr use OpFmaKHR. - VkPhysicalDeviceShaderFmaFeaturesKHR fma_features{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADER_FMA_FEATURES_KHR}; - if (std::any_of(extensions.begin(), extensions.end(), [](const auto& e) { - return std::strcmp(e.extensionName, VK_KHR_SHADER_FMA_EXTENSION_NAME) == 0; - })) { - VkPhysicalDeviceFeatures2 query{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2, &fma_features}; - instance_fn("vkGetPhysicalDeviceFeatures2")(physical, &query); - shader_fma = fma_features.shaderFmaFloat32 == VK_TRUE; - if (shader_fma) { - fma_features.pNext = *v13_.next(); - *v13_.next() = &fma_features; - } - } -#endif - // VK_EXT_mesh_shader (meshShader only), for the tests that ask for it. - VkPhysicalDeviceMeshShaderFeaturesEXT mesh_features{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MESH_SHADER_FEATURES_EXT}; - if (request_mesh_shader && std::any_of(extensions.begin(), extensions.end(), [](const auto& e) { - return std::strcmp(e.extensionName, VK_EXT_MESH_SHADER_EXTENSION_NAME) == 0; - })) { - VkPhysicalDeviceFeatures2 query{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2, &mesh_features}; - instance_fn("vkGetPhysicalDeviceFeatures2")(physical, &query); - mesh_shader = mesh_features.meshShader == VK_TRUE; - } - if (mesh_shader) { - mesh_features = {VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MESH_SHADER_FEATURES_EXT, *v13_.next()}; - mesh_features.meshShader = VK_TRUE; - *v13_.next() = &mesh_features; - } - enable.occlusionQueryPrecise = features.features.occlusionQueryPrecise; // query heaps, where available - enable.pipelineStatisticsQuery = features.features.pipelineStatisticsQuery; - occlusion_query_precise = features.features.occlusionQueryPrecise == VK_TRUE; - pipeline_statistics_query = features.features.pipelineStatisticsQuery == VK_TRUE; - - // VK_EXT_custom_border_color where the device has it. - VkPhysicalDeviceCustomBorderColorFeaturesEXT custom_border{ - VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_CUSTOM_BORDER_COLOR_FEATURES_EXT}; - for (const auto& extension : extensions) { - if (std::strcmp(extension.extensionName, VK_EXT_CUSTOM_BORDER_COLOR_EXTENSION_NAME) != 0) continue; - VkPhysicalDeviceFeatures2 query{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2, &custom_border}; - instance_fn("vkGetPhysicalDeviceFeatures2")(physical, &query); - custom_border_color = custom_border.customBorderColors == VK_TRUE; - custom_border_color_without_format = custom_border.customBorderColorWithoutFormat == VK_TRUE; - } - const char* custom_border_color_name = VK_EXT_CUSTOM_BORDER_COLOR_EXTENSION_NAME; - if (custom_border_color) { - custom_border.pNext = *v13_.next(); // where later feature structs go since #1706 - *v13_.next() = &custom_border; - } - - // VK_EXT_external_memory_host where the device has it (OpenExistingHeapFromAddress). - for (const auto& extension : extensions) { - if (std::strcmp(extension.extensionName, VK_EXT_EXTERNAL_MEMORY_HOST_EXTENSION_NAME) != 0) continue; - VkPhysicalDeviceExternalMemoryHostPropertiesEXT host_memory{ - VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_EXTERNAL_MEMORY_HOST_PROPERTIES_EXT}; - VkPhysicalDeviceProperties2 properties{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROPERTIES_2, &host_memory}; - instance_fn("vkGetPhysicalDeviceProperties2")(physical, &properties); - host_pointer_alignment = host_memory.minImportedHostPointerAlignment; - } - - VkDeviceCreateInfo device_info{VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO, &enable12}; - device_info.queueCreateInfoCount = std::uint32_t(queue_infos.size()); - device_info.pQueueCreateInfos = queue_infos.data(); - device_info.pEnabledFeatures = &enable; - enabled = enable; - std::vector device_extensions; - v13_.add_extensions(device_extensions); - conservative_rasterization = std::any_of(extensions.begin(), extensions.end(), [](const auto& e) { - return std::strcmp(e.extensionName, VK_EXT_CONSERVATIVE_RASTERIZATION_EXTENSION_NAME) == 0; - }); - if (conservative_rasterization) device_extensions.push_back(VK_EXT_CONSERVATIVE_RASTERIZATION_EXTENSION_NAME); - if (image_view_min_lod) device_extensions.push_back(VK_EXT_IMAGE_VIEW_MIN_LOD_EXTENSION_NAME); - if (vertex_attribute_divisor) device_extensions.push_back(divisor_extension); - if (conditional_rendering) device_extensions.push_back(conditional_extension); - if (host_image_copy) device_extensions.push_back(host_image_copy_name); - if (host_pointer_alignment) device_extensions.push_back(VK_EXT_EXTERNAL_MEMORY_HOST_EXTENSION_NAME); - const char* swapchain = "VK_KHR_swapchain"; - if (presentation) device_extensions.push_back(swapchain); -#if defined(VK_KHR_swapchain_maintenance1) - VkPhysicalDeviceSwapchainMaintenance1FeaturesKHR swapchain_m1{ - VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SWAPCHAIN_MAINTENANCE_1_FEATURES_KHR}; - if (presentation) { - const auto has = [&](const char* name) { - return std::any_of(extensions.begin(), extensions.end(), - [&](const auto& e) { return std::strcmp(e.extensionName, name) == 0; }); - }; - const char* name = surface_m1_khr && has("VK_KHR_swapchain_maintenance1") ? "VK_KHR_swapchain_maintenance1" - : surface_m1_ext && has("VK_EXT_swapchain_maintenance1") ? "VK_EXT_swapchain_maintenance1" - : nullptr; - if (name) { - VkPhysicalDeviceFeatures2 query{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2, &swapchain_m1}; - instance_fn("vkGetPhysicalDeviceFeatures2")(physical, &query); - if (swapchain_m1.swapchainMaintenance1 == VK_TRUE) { - swapchain_m1.pNext = *v13_.next(); - *v13_.next() = &swapchain_m1; - device_extensions.push_back(name); - swapchain_maintenance1 = true; - } - } - } -#endif -#ifdef VK_KHR_SHADER_FMA_EXTENSION_NAME - if (shader_fma) device_extensions.push_back(VK_KHR_SHADER_FMA_EXTENSION_NAME); -#endif - if (custom_border_color) device_extensions.push_back(custom_border_color_name); - if (mesh_shader) device_extensions.push_back(VK_EXT_MESH_SHADER_EXTENSION_NAME); - device_info.enabledExtensionCount = std::uint32_t(device_extensions.size()); - device_info.ppEnabledExtensionNames = device_extensions.data(); - result = instance_fn("vkCreateDevice")(physical, &device_info, nullptr, &device); - if (result != VK_SUCCESS) return failure("vkCreateDevice", result); - device_proc = instance_fn("vkGetDeviceProcAddr"); - queues.resize(graphics_count); - for (std::uint32_t i = 0; i < graphics_count; ++i) - fn("vkGetDeviceQueue")(device, family, i, &queues[i]); - queue = queues[0]; - fn("vkGetDeviceQueue")(device, compute_family, 0, &compute_queue); - fn("vkGetDeviceQueue")(device, copy_family, 0, ©_queue); - instance_fn("vkGetPhysicalDeviceMemoryProperties")(physical, - &memory_); - VkCommandPoolCreateInfo pool{VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO}; - pool.flags = VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT; - pool.queueFamilyIndex = family; - result = fn("vkCreateCommandPool")(device, &pool, nullptr, &pool_); - return result == VK_SUCCESS ? DeviceStatus::ready : failure("vkCreateCommandPool", result); - } - - bool depth_format_usable(VkFormat format) const { - VkFormatProperties properties{}; - instance_fn("vkGetPhysicalDeviceFormatProperties")(physical, format, - &properties); - constexpr VkFormatFeatureFlags needed = VK_FORMAT_FEATURE_DEPTH_STENCIL_ATTACHMENT_BIT | - VK_FORMAT_FEATURE_TRANSFER_SRC_BIT | VK_FORMAT_FEATURE_TRANSFER_DST_BIT; - return (properties.optimalTilingFeatures & needed) == needed; - } - - // depth > 1: a 3D image. samples > 1: a multisampled one. - VkImage image(VkFormat format, std::uint32_t width, std::uint32_t height, std::uint32_t layers, - VkImageUsageFlags usage, std::uint32_t depth = 1, std::uint32_t samples = 1) { - VkImageCreateInfo info{VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO}; - info.imageType = depth > 1 ? VK_IMAGE_TYPE_3D : VK_IMAGE_TYPE_2D; - info.format = format; - info.extent = {width, height, depth}; - info.mipLevels = 1; - info.arrayLayers = layers; - info.samples = VkSampleCountFlagBits(samples); - info.usage = usage | VK_IMAGE_USAGE_TRANSFER_SRC_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT; - share(info); - VkImage image = VK_NULL_HANDLE; - if (fn("vkCreateImage")(device, &info, nullptr, &image) != VK_SUCCESS) return VK_NULL_HANDLE; - VkMemoryRequirements requirements{}; - fn("vkGetImageMemoryRequirements")(device, image, &requirements); - const VkDeviceMemory memory = allocate(requirements, 0); - images_.push_back({image, memory}); - if (!memory || fn("vkBindImageMemory")(device, image, memory, 0) != VK_SUCCESS) - return VK_NULL_HANDLE; - return image; - } - - // A host-visible, coherent buffer, mapped; with `mapped` null, a device-local one the host can't see. - VkBuffer buffer(VkDeviceSize size, VkBufferUsageFlags usage, void** mapped) { - VkBufferCreateInfo info{VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO}; - info.size = size; - info.usage = usage | (buffer_device_address ? VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT : 0u); - share(info); - VkBuffer buffer = VK_NULL_HANDLE; - if (fn("vkCreateBuffer")(device, &info, nullptr, &buffer) != VK_SUCCESS) - return VK_NULL_HANDLE; - VkMemoryRequirements requirements{}; - fn("vkGetBufferMemoryRequirements")(device, buffer, &requirements); - const VkDeviceMemory memory = allocate(requirements, mapped ? VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | - VK_MEMORY_PROPERTY_HOST_COHERENT_BIT - : VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT); - buffers_.push_back({buffer, memory}); - if (!memory || fn("vkBindBufferMemory")(device, buffer, memory, 0) != VK_SUCCESS) - return VK_NULL_HANDLE; - if (!mapped) return buffer; - if (fn("vkMapMemory")(device, memory, 0, size, 0, mapped) != VK_SUCCESS) return VK_NULL_HANDLE; - std::memset(*mapped, 0xcd, size_t(size)); - return buffer; - } - - // The device address of a buffer from buffer(); 0 unless buffer_device_address is enabled. - std::uint64_t device_address(VkBuffer buffer) const { - if (!buffer_device_address) return 0; - VkBufferDeviceAddressInfo info{VK_STRUCTURE_TYPE_BUFFER_DEVICE_ADDRESS_INFO}; - info.buffer = buffer; - return fn("vkGetBufferDeviceAddress")(device, &info); - } - - // Records `body` into a one-shot command buffer, submits it and waits for the queue. - template - bool run(Body&& body) { - VkCommandBufferAllocateInfo info{VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO}; - info.commandPool = pool_; - info.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY; - info.commandBufferCount = 1; - VkCommandBuffer command_buffer = VK_NULL_HANDLE; - if (fn("vkAllocateCommandBuffers")(device, &info, &command_buffer) != VK_SUCCESS) - return false; - VkCommandBufferBeginInfo begin{VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO}; - begin.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT; - fn("vkBeginCommandBuffer")(command_buffer, &begin); - const bool recorded = body(command_buffer); - fn("vkEndCommandBuffer")(command_buffer); - VkSubmitInfo submit{VK_STRUCTURE_TYPE_SUBMIT_INFO}; - submit.commandBufferCount = 1; - submit.pCommandBuffers = &command_buffer; - const bool ok = recorded && fn("vkQueueSubmit")(queue, 1, &submit, VK_NULL_HANDLE) == VK_SUCCESS && - fn("vkQueueWaitIdle")(queue) == VK_SUCCESS; - fn("vkFreeCommandBuffers")(device, pool_, 1, &command_buffer); - return ok; - } - - // UNDEFINED -> layout for a whole image: what resource creation does for a D3D12 initial state. - void initial_layout(VkCommandBuffer command_buffer, VkImage image, VkImageAspectFlags aspects, - std::uint32_t layers, VkImageLayout layout) const { - VkImageMemoryBarrier barrier{VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER}; - barrier.dstAccessMask = VK_ACCESS_MEMORY_READ_BIT | VK_ACCESS_MEMORY_WRITE_BIT; - barrier.oldLayout = VK_IMAGE_LAYOUT_UNDEFINED; - barrier.newLayout = layout; - barrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; - barrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; - barrier.image = image; - barrier.subresourceRange = {aspects, 0, 1, 0, layers}; - fn("vkCmdPipelineBarrier")(command_buffer, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, - VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, 0, 0, nullptr, 0, - nullptr, 1, &barrier); - } - - // Copies one aspect of layers [0, layers) from an image in `layout` to buffer + offset, then makes it host-visible. - void read_back(VkCommandBuffer command_buffer, VkImage image, VkImageLayout layout, VkImageAspectFlags aspect, - std::uint32_t width, std::uint32_t height, std::uint32_t layers, VkBuffer buffer, - VkDeviceSize offset) const { - VkBufferImageCopy copy{}; - copy.bufferOffset = offset; - copy.imageSubresource = {aspect, 0, 0, layers}; - copy.imageExtent = {width, height, 1}; - fn("vkCmdCopyImageToBuffer")(command_buffer, image, layout, buffer, 1, ©); - VkMemoryBarrier host{VK_STRUCTURE_TYPE_MEMORY_BARRIER}; - host.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT; - host.dstAccessMask = VK_ACCESS_HOST_READ_BIT; - fn("vkCmdPipelineBarrier")(command_buffer, VK_PIPELINE_STAGE_TRANSFER_BIT, - VK_PIPELINE_STAGE_HOST_BIT, 0, 1, &host, 0, nullptr, 0, - nullptr); - } - -private: - std::vector sharing_; - - template - void share(Info& info) const { - if (sharing_.size() < 2) return; - info.sharingMode = VK_SHARING_MODE_CONCURRENT; - info.queueFamilyIndexCount = std::uint32_t(sharing_.size()); - info.pQueueFamilyIndices = sharing_.data(); - } - - VkDeviceMemory allocate(const VkMemoryRequirements& requirements, VkMemoryPropertyFlags flags) { - for (std::uint32_t i = 0; i < memory_.memoryTypeCount; ++i) { - if (!(requirements.memoryTypeBits & (1u << i))) continue; - if ((memory_.memoryTypes[i].propertyFlags & flags) != flags) continue; - VkMemoryAllocateFlagsInfo address_flags{VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_FLAGS_INFO}; - address_flags.flags = VK_MEMORY_ALLOCATE_DEVICE_ADDRESS_BIT; - VkMemoryAllocateInfo info{VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO}; - if (buffer_device_address) info.pNext = &address_flags; - info.allocationSize = requirements.size; - info.memoryTypeIndex = i; - VkDeviceMemory memory = VK_NULL_HANDLE; - if (fn("vkAllocateMemory")(device, &info, nullptr, &memory) == VK_SUCCESS) - return memory; - return VK_NULL_HANDLE; - } - return VK_NULL_HANDLE; - } - - VkDebugUtilsMessengerEXT messenger_ = VK_NULL_HANDLE; - VkCommandPool pool_ = VK_NULL_HANDLE; - VkPhysicalDeviceMemoryProperties memory_{}; - leonida::Vulkan13Features v13_; // the chosen device's dynamicRendering/synchronization2 path - std::vector> images_; - std::vector> buffers_; -}; - -} // namespace vktest diff --git a/runtime/test/vk_texture_test.cpp b/runtime/test/vk_texture_test.cpp deleted file mode 100644 index 3dafcaef6..000000000 --- a/runtime/test/vk_texture_test.cpp +++ /dev/null @@ -1,676 +0,0 @@ -// GPU test for translated texture-sampling pixel shaders, using the translator's runtime contract: -// push constants: s0..s31 user data, then the 64-bit heap base (host BDA of the Xbox GPU VA window) -// set 0: binding 0 = 2D images[], 1 = samplers[], 2 = descriptor hash table (storage buffer) -// The test puts a T# (8 dwords) at Xbox VA `tsharp_va` inside the heap, points user SGPR s[ptr_sgpr] at it, -// registers that T# -> image index 1 and the shader's literal S# -> sampler index 1, binds an 8x8 gradient at -// index 1 and a magenta fallback at index 0, draws a full-screen triangle and dumps the RGBA32F result. -// -// vk_texture_test [--two-mip|--two-mip-sint|--two-mip-uint] (S# words as hex) -// --two-mip: expose a 128x128 quadrant texture and its solid cyan mip 1 to the 64x64 draw; the SINT and UINT -// forms bind the same image as a signed or unsigned integer view instead of the default UNORM one. -// vk_texture_test cube [out.raw]: ps_cube_sample against two 8x8 cubes, a 12-layer 2D array at binding 3 (the -// translator's view of a cube array); every pixel must be the texel a cube sample of its direction reads. -// vk_texture_test dref [out.raw]: ps_sample_c_lz against an 8x8 D32 texture at index 1 (texel x holds depth -// (x + 0.5) / 8) and a LESS_OR_EQUAL compare sampler at index 1; both of its results, f32 and d16, must be the -// 1.0 or 0.0 the reference 0.5 gives against the texel each pixel reads. -// vk_texture_test dref_a16 [out.raw]: the same with ps_sample_c_lz_a16 (16-bit coordinates). -// vk_texture_test dref_c / dref_c_b [out.raw]: the same with ps_sample_c (implicit LOD) / ps_sample_c_b (LOD bias). -// VKT_HEAP_MB=: size of the heap in MiB (default 64 KiB) -// VKT_NEED_MAINTENANCE8=1: the shader has a non-constant texel Offset outside gather (image_sample*_o, see -// ps_texoff.asm); print "unsupported: ..." and exit 77 when VK_KHR_maintenance8 cannot be enabled. -// VK_KHR_maintenance8, shaderImageGatherExtended (a non-constant gather Offset) and shaderResourceMinLod (the MinLod -// clamp of image_sample_d_cl) are enabled when the device has them. A fragment shader that declares the MinLod -// capability on a device without shaderResourceMinLod prints "unsupported: ..." and exits 77. -#define VK_NO_PROTOTYPES -#include "vulkan_loader.h" -#include "vk_device_pick.h" -#include "vk_shader_fma.h" -#include "vk_pc_tail.h" -#include "spirv_capability.h" - -#include -#include -#include -#include -#include -#include -#include -#include - -static PFN_vkGetInstanceProcAddr gipa; -#define CHECK(x) \ - do { \ - VkResult r_ = (x); \ - if (r_ != VK_SUCCESS) { \ - std::fprintf(stderr, "FAILED %s -> %d (line %d)\n", #x, r_, __LINE__); \ - return 1; \ - } \ - } while (0) - -static std::vector read_spv(const char* p) { - std::ifstream f(p, std::ios::binary); - if (!f.good()) return {}; - std::vector b((std::istreambuf_iterator(f)), {}); - std::vector w(b.size() / 4); - std::memcpy(w.data(), b.data(), w.size() * 4); - return w; -} - -#include "../src/descriptor_table.h" -#include "../src/gfx10_descriptors.h" - -static bool cube_texel_matches(const float* pixel, int tx, int ty, int face) { - return std::fabs(pixel[0] - tx * 32 / 255.f) < 1e-3f && - std::fabs(pixel[1] - ty * 32 / 255.f) < 1e-3f && - std::fabs(pixel[2] - (6 + face) * 20 / 255.f) < 1e-3f && - std::fabs(pixel[3] - 1.0f) < 1e-3f; // The cube upload stores opaque alpha. -} - -static int cube_alpha_self_test() { - float pixel[4] = {64.0f / 255.0f, 96.0f / 255.0f, 200.0f / 255.0f, 1.0f}; - if (!cube_texel_matches(pixel, 2, 3, 4)) { - std::fprintf(stderr, "cube alpha self-test: rejected the expected RGBA texel\n"); - return 1; - } - for (const float alpha : {0.0f, std::numeric_limits::quiet_NaN()}) { - pixel[3] = alpha; - if (cube_texel_matches(pixel, 2, 3, 4)) { - std::fprintf(stderr, "cube alpha self-test: accepted incorrect alpha %g\n", alpha); - return 1; - } - } - return 0; -} - -int main(int argc, char** argv) { - if (argc == 2 && std::strcmp(argv[1], "--self-test-cube-alpha") == 0) - return cube_alpha_self_test(); - const uint32_t W = 64, H = 64, TW = 8; - const bool signed_mips = argc == 10 && std::strcmp(argv[9], "--two-mip-sint") == 0; - const bool uint_mips = argc == 10 && std::strcmp(argv[9], "--two-mip-uint") == 0; - const bool two_mip = signed_mips || uint_mips || (argc == 10 && std::strcmp(argv[9], "--two-mip") == 0); - // With vs_ids spanning UV [0,1] over the viewport, adjacent fragments differ by two base texels. - const uint32_t texture_side = two_mip ? 2 * W : TW; - const uint32_t levels = two_mip ? 2 : 1; - std::string vs_path, fs_path, out_path; - int ptr_sgpr = 0; - // Fixed shader only: fetch (0,0) is in bounds on both the fallback and the integer image. - const bool fetch_uint = argc >= 2 && !std::strcmp(argv[1], "fetch-uint"); - const bool fetch_miss = argc >= 2 && !std::strcmp(argv[1], "fetch-miss"); - const bool fetch = fetch_uint || fetch_miss || (argc >= 2 && !std::strcmp(argv[1], "fetch-sint")); - const bool cube = argc >= 2 && !std::strcmp(argv[1], "cube"); - // dref_c / dref_c_b: image_sample_c / image_sample_c_b (implicit LOD, bias), same texture and expected results. - const char* dref_ps = nullptr; - if (argc >= 2) { - if (!std::strcmp(argv[1], "dref")) dref_ps = "ps_sample_c_lz.spv"; - else if (!std::strcmp(argv[1], "dref_a16")) dref_ps = "ps_sample_c_lz_a16.spv"; - else if (!std::strcmp(argv[1], "dref_c")) dref_ps = "ps_sample_c.spv"; - else if (!std::strcmp(argv[1], "dref_c_b")) dref_ps = "ps_sample_c_b.spv"; - } - const bool dref = dref_ps != nullptr; - bool autonomous = false; - uint32_t ssharp[8] = {0x92, 0xc00000, 0x14500000, 0, - 0xFFFFFFFFu, 0xFFFFFFFFu, 0xFFFFFFFFu, 0xFFFFFFFFu}; - if (!fetch && (argc == 9 || two_mip)) { - vs_path = argv[1]; - fs_path = argv[2]; - out_path = argv[3]; - ptr_sgpr = std::atoi(argv[4]); - for (int i = 0; i < 4; ++i) ssharp[i] = (uint32_t)strtoul(argv[5 + i], 0, 16); - } else if (argc <= 2 || ((cube || dref || fetch) && argc == 3)) { - // Autonomous mode using synthetic hand-written shaders (no game files required) - autonomous = true; - auto find_spv = [](const char* name) -> std::string { - const char* candidates[] = { - "runtime/build/shaders/spirv/", - "runtime/test/shaders/spirv/", - "build/shaders/spirv/", - "shaders/spirv/", - "" - }; - for (const char* prefix : candidates) { - std::string p = std::string(prefix) + name; - std::ifstream f(p, std::ios::binary); - if (f.good()) return p; - } - return std::string("runtime/build/shaders/spirv/") + name; - }; - vs_path = find_spv("vs_ids.spv"); - fs_path = find_spv(fetch ? "ps_table_fetch.spv" : cube ? "ps_cube_sample.spv" : dref ? dref_ps : "ps_texture_sample.spv"); - const int out_arg = cube || dref || fetch ? 2 : 1; - out_path = argc > out_arg ? argv[out_arg] : "runtime/build/vk_texture_test_out.raw"; - ptr_sgpr = 0; - if (dref) - ssharp[0] |= 3u << 12; // the shader's S#: DEPTH_COMPARE_FUNC = LESSEQUAL - } else { - std::fprintf(stderr, "usage: vk_texture_test [cube|dref|dref_a16|dref_c|dref_c_b|fetch-uint|fetch-sint|fetch-miss] [out] | vs fs out ptr_sgpr s0 s1 s2 s3 [--two-mip|--two-mip-sint|--two-mip-uint]\n"); - return 2; - } - // Word 1 also selects the numeric type when the shader fetches through this key. Word 3 keeps BASE_LEVEL [15:12] - // at 0, as the views here start at level 0: image_get_resinfo minifies a 2D array's layers from BASE_LEVEL. - const VkFormat sampled_format = dref ? VK_FORMAT_D32_SFLOAT : - (uint_mips || fetch_uint) ? VK_FORMAT_R8G8B8A8_UINT : - (signed_mips || fetch) ? VK_FORMAT_R8G8B8A8_SINT : VK_FORMAT_R8G8B8A8_UNORM; - uint32_t tsharp[8] = {0x11111111, leonida::gfx10::format_from_vulkan(sampled_format) << 20, 0x33333333, 0x44440444, - 0x55555555, 0x66666666, 0x77777777, 0x88888888}; - const uint32_t tsharp_va = 256; - - gipa = load_vulkan(); - if (!gipa) { std::fprintf(stderr, "the Vulkan loader was not found\n"); return 77; } - VkInstance inst = VK_NULL_HANDLE; -#define LI(n) auto n = reinterpret_cast(gipa(inst, #n)) - LI(vkCreateInstance); - VkApplicationInfo app{VK_STRUCTURE_TYPE_APPLICATION_INFO}; app.apiVersion = VK_API_VERSION_1_2; - VkInstanceCreateInfo ici{VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO}; ici.pApplicationInfo = &app; - const VkResult instance_result = vkCreateInstance(&ici, nullptr, &inst); - if (instance_result == VK_ERROR_INCOMPATIBLE_DRIVER) return 77; // no ICD, as on a GPU-less runner - if (instance_result != VK_SUCCESS) { - std::fprintf(stderr, "FAILED vkCreateInstance -> %d (line %d)\n", instance_result, __LINE__); - return 1; - } - LI(vkEnumeratePhysicalDevices); LI(vkGetPhysicalDeviceProperties); LI(vkGetPhysicalDeviceQueueFamilyProperties); - LI(vkGetPhysicalDeviceMemoryProperties); LI(vkCreateDevice); LI(vkGetDeviceProcAddr); - uint32_t n = 0; - CHECK(vkEnumeratePhysicalDevices(inst, &n, nullptr)); - std::vector pds(n); - if (n) CHECK(vkEnumeratePhysicalDevices(inst, &n, pds.data())); - if (!n) { - std::fprintf(stderr, "unsupported: no Vulkan physical device\n"); - return 77; // a missing device is a skip in every texture-test mode - } - // LEONIDA_VK_DEVICE picks one GPU on a machine with several, as in the other test programs. - std::vector candidates(n); - for (uint32_t i = 0; i < n; ++i) vkGetPhysicalDeviceProperties(pds[i], &candidates[i]); - const size_t chosen = leonida::vk_test::pick_device(candidates); - if (chosen >= n) { - leonida::vk_test::report_no_device(); - return 1; - } - VkPhysicalDevice pd = pds[chosen]; - VkPhysicalDeviceProperties properties = candidates[chosen]; - constexpr uint32_t push_words = 36; - // LEONIDA_PC_TAIL_UBO=1 (rdna2spirv.py --pc-tail-ubo): s0..s31 only; the heap base is in a uniform block at set 1 - // (vk_pc_tail.h), so a 128-byte device runs these tests too. - const bool pc_tail = leonida::vk_test::pc_tail_requested(); - const uint32_t push_bytes = pc_tail ? 128u : push_words * uint32_t(sizeof(uint32_t)); - if (properties.limits.maxPushConstantsSize < push_bytes) { - std::fprintf(stderr, "unsupported: need %u push constant bytes, device has %u\n", - push_bytes, properties.limits.maxPushConstantsSize); - return 77; // a device limit, not a wrong result: every texture test skips (128-byte devices, D3D-14) - } - uint32_t qn = 0; vkGetPhysicalDeviceQueueFamilyProperties(pd, &qn, nullptr); - std::vector qf(qn); vkGetPhysicalDeviceQueueFamilyProperties(pd, &qn, qf.data()); - uint32_t qi = 0; - while (qi < qn && !(qf[qi].queueFlags & VK_QUEUE_GRAPHICS_BIT)) ++qi; - if (qi == qn) { - std::fprintf(stderr, "unsupported: no graphics queue family\n"); - return 77; // a missing queue is a skip in every texture-test mode - } - float prio = 1; - VkDeviceQueueCreateInfo qci{VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO}; - qci.queueFamilyIndex = qi; qci.queueCount = 1; qci.pQueuePriorities = &prio; - // Translated vertex shaders read BaseVertex / BaseInstance (DrawParameters) for the zero-based v0 / v3. - VkPhysicalDeviceVulkan11Features f11{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_1_FEATURES}; - f11.shaderDrawParameters = VK_TRUE; - VkPhysicalDeviceVulkan12Features f12{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_2_FEATURES}; - f12.pNext = &f11; - f12.bufferDeviceAddress = VK_TRUE; f12.runtimeDescriptorArray = VK_TRUE; f12.descriptorIndexing = VK_TRUE; - VkPhysicalDeviceFeatures2 f2{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2}; f2.pNext = &f12; - // Texel offsets: the limits the shader's Offset operands must stay inside, and the two optional features. - LI(vkEnumerateDeviceExtensionProperties); LI(vkGetPhysicalDeviceFeatures); - VkPhysicalDeviceProperties pdp; vkGetPhysicalDeviceProperties(pd, &pdp); - std::fprintf(stderr, "device: %s\ntexel offset limits: %d..%d, gather %d..%d\n", pdp.deviceName, - pdp.limits.minTexelOffset, int(pdp.limits.maxTexelOffset), - pdp.limits.minTexelGatherOffset, int(pdp.limits.maxTexelGatherOffset)); - VkPhysicalDeviceFeatures have; vkGetPhysicalDeviceFeatures(pd, &have); - const auto fragment_code = read_spv(fs_path.c_str()); - using leonida::vk_test::spirv_declares_capability; - const bool dynamic_sampled = spirv_declares_capability(fragment_code.data(), fragment_code.size() * 4, - leonida::vk_test::spv_sampled_image_array_dynamic_indexing); - if (dynamic_sampled && !have.shaderSampledImageArrayDynamicIndexing) { - std::printf("unsupported: shaderSampledImageArrayDynamicIndexing\n"); - return 77; - } - f2.features.shaderSampledImageArrayDynamicIndexing = dynamic_sampled; - f2.features.shaderImageGatherExtended = have.shaderImageGatherExtended; - f2.features.shaderResourceMinLod = have.shaderResourceMinLod; - // shaderInt64 only when a stage has 64-bit integers: SHADER-423's address pairs need none (TEST-468). - const bool int64 = leonida::vk_test::needs_shader_int64(read_spv(vs_path.c_str())) || - leonida::vk_test::needs_shader_int64(fragment_code); - if (int64 && !have.shaderInt64) { - std::printf("unsupported: shaderInt64 (a stage declares Int64)\n"); - return 77; - } - f2.features.shaderInt64 = int64 ? VK_TRUE : VK_FALSE; - if (spirv_declares_capability(fragment_code.data(), fragment_code.size() * 4, 42) && - !have.shaderResourceMinLod) { // 42 = MinLod - std::printf("unsupported: shaderResourceMinLod (the shader clamps its LOD with MinLod)\n"); - return 77; - } - std::vector enable; - leonida::vk_test::ShaderFma fma; // OpFmaKHR (rdna2spirv.py --fma khr), when the device has it - fma.query(gipa, inst, pd); - // A device without VK_KHR_shader_fma cannot create a pipeline from a stage that uses OpFmaKHR: skip the pair. - if (!fma.accepts_file(vs_path.c_str()) || !fma.accepts_file(fs_path.c_str())) return 77; - if (fma.supported()) { enable.push_back(fma.extension()); fma.link_after(&f2); } - bool m8_on = false; -#ifdef VK_KHR_MAINTENANCE_8_EXTENSION_NAME // the structure type is an enumerator: defined() never sees it - // Older Vulkan headers (as on some CI images) do not declare maintenance8; the test is then unsupported. - VkPhysicalDeviceMaintenance8FeaturesKHR m8{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MAINTENANCE_8_FEATURES_KHR}; - uint32_t en = 0; vkEnumerateDeviceExtensionProperties(pd, nullptr, &en, nullptr); - std::vector exts(en); vkEnumerateDeviceExtensionProperties(pd, nullptr, &en, exts.data()); - for (auto& x : exts) m8_on = m8_on || !std::strcmp(x.extensionName, VK_KHR_MAINTENANCE_8_EXTENSION_NAME); - if (m8_on) { - enable.push_back(VK_KHR_MAINTENANCE_8_EXTENSION_NAME); - m8.maintenance8 = VK_TRUE; f11.pNext = &m8; - std::fprintf(stderr, "enabled %s\n", VK_KHR_MAINTENANCE_8_EXTENSION_NAME); - } -#endif - if (std::getenv("VKT_NEED_MAINTENANCE8") && !m8_on) { - std::printf("unsupported: VK_KHR_maintenance8 (non-constant texel Offset)\n"); - return 77; - } - VkDeviceCreateInfo dci{VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO}; - dci.pNext = &f2; dci.queueCreateInfoCount = 1; dci.pQueueCreateInfos = &qci; - dci.enabledExtensionCount = uint32_t(enable.size()); dci.ppEnabledExtensionNames = enable.data(); - VkDevice dev; - VkResult created = vkCreateDevice(pd, &dci, nullptr, &dev); - if (two_mip && created == VK_ERROR_FEATURE_NOT_PRESENT) { - std::fprintf(stderr, "unsupported: device lacks a requested texture test feature\n"); - return 77; - } - CHECK(created); -#define LD(n) auto n = reinterpret_cast(vkGetDeviceProcAddr(dev, #n)) - LD(vkGetDeviceQueue); LD(vkCreateImage); LD(vkGetImageMemoryRequirements); LD(vkAllocateMemory); - LD(vkBindImageMemory); LD(vkCreateImageView); LD(vkCreateRenderPass); LD(vkCreateFramebuffer); - LD(vkCreateShaderModule); LD(vkCreatePipelineLayout); LD(vkCreateGraphicsPipelines); LD(vkCreateCommandPool); - LD(vkAllocateCommandBuffers); LD(vkBeginCommandBuffer); LD(vkCmdBeginRenderPass); LD(vkCmdBindPipeline); - LD(vkCmdDraw); LD(vkCmdEndRenderPass); LD(vkCmdCopyImageToBuffer); LD(vkCmdCopyBufferToImage); - LD(vkEndCommandBuffer); LD(vkQueueSubmit); LD(vkQueueWaitIdle); LD(vkCreateBuffer); - LD(vkGetBufferMemoryRequirements); LD(vkBindBufferMemory); LD(vkMapMemory); LD(vkGetBufferDeviceAddress); - LD(vkCreateSampler); LD(vkCreateDescriptorSetLayout); LD(vkCreateDescriptorPool); LD(vkAllocateDescriptorSets); - LD(vkUpdateDescriptorSets); LD(vkCmdBindDescriptorSets); LD(vkCmdPushConstants); LD(vkCmdPipelineBarrier); - VkQueue q; vkGetDeviceQueue(dev, qi, 0, &q); - VkPhysicalDeviceMemoryProperties mp; vkGetPhysicalDeviceMemoryProperties(pd, &mp); - auto memtype = [&](uint32_t bits, VkMemoryPropertyFlags want) { - for (uint32_t i = 0; i < mp.memoryTypeCount; i++) - if ((bits & (1u << i)) && (mp.memoryTypes[i].propertyFlags & want) == want) return i; - return 0u; - }; - auto make_buffer = [&](VkDeviceSize size, VkBufferUsageFlags usage, VkBuffer* b, VkDeviceMemory* m, void** map) { - VkBufferCreateInfo bi{VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO}; bi.size = size; bi.usage = usage; - VkResult r = vkCreateBuffer(dev, &bi, nullptr, b); if (r) return r; - VkMemoryRequirements mr; vkGetBufferMemoryRequirements(dev, *b, &mr); - VkMemoryAllocateFlagsInfo fi{VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_FLAGS_INFO}; - fi.flags = VK_MEMORY_ALLOCATE_DEVICE_ADDRESS_BIT; - VkMemoryAllocateInfo ai{VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO}; ai.pNext = &fi; ai.allocationSize = mr.size; - ai.memoryTypeIndex = memtype(mr.memoryTypeBits, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT); - r = vkAllocateMemory(dev, &ai, nullptr, m); if (r) return r; - r = vkBindBufferMemory(dev, *b, *m, 0); if (r) return r; - return vkMapMemory(dev, *m, 0, size, 0, map); - }; - // Heap (the Xbox GPU VA window) with the T# at tsharp_va. - VkBuffer heap; VkDeviceMemory heapm; void* heapp; - // 64 KiB of zeros unless VKT_HEAP_MB says otherwise. Buffer loads are not bounds-checked against the V#, so a - // shader that indexes with anything but the zeros it finds here reads past the end: a bigger heap keeps such - // reads inside defined memory. - const char* heap_mb = std::getenv("VKT_HEAP_MB"); - const VkDeviceSize heap_bytes = heap_mb && std::atoi(heap_mb) > 0 ? VkDeviceSize(std::atoi(heap_mb)) << 20 : 65536; - CHECK(make_buffer(heap_bytes, VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT, &heap, &heapm, &heapp)); - std::memset(heapp, 0, size_t(heap_bytes)); - std::memcpy(static_cast(heapp) + tsharp_va, tsharp, 32); - if (two_mip) // The gather test loads its S# from the four words just after the T#. - std::memcpy(static_cast(heapp) + tsharp_va + 32, ssharp, 16); - VkBufferDeviceAddressInfo bdai{VK_STRUCTURE_TYPE_BUFFER_DEVICE_ADDRESS_INFO}; bdai.buffer = heap; - VkDeviceAddress heap_base = vkGetBufferDeviceAddress(dev, &bdai); - // Descriptor hash table: 16 slots. - leonida::DescriptorTable desc_table(16); - // The heap already holds the original key. Change only the registered key for the miss control. - if (fetch_miss) tsharp[7] ^= 1; - desc_table.insert(tsharp, 1); - desc_table.insert(ssharp, 1); - const auto table = desc_table.build_gpu_buffer(true); - VkBuffer tb; VkDeviceMemory tbm; void* tbp; - CHECK(make_buffer(table.size() * 4, VK_BUFFER_USAGE_STORAGE_BUFFER_BIT, &tb, &tbm, &tbp)); - std::memcpy(tbp, table.data(), table.size() * 4); - // Textures: index 0 = 1x1 magenta fallback, index 1 = 8x8 gradient (r = x/8, g = y/8, b = 0.5, a = 1), or in dref - // mode an 8x8 D32 texture with depth (x + 0.5) / 8. Binding 3 (2D arrays) gets the same fallback and two 8x8 cubes - // as 12 layers: layer l = (x/8, y/8, 20l/255, 1). - auto aspect_of = [](VkFormat f) { - return f == VK_FORMAT_D32_SFLOAT ? VkImageAspectFlags(VK_IMAGE_ASPECT_DEPTH_BIT) - : VkImageAspectFlags(VK_IMAGE_ASPECT_COLOR_BIT); - }; - auto make_tex = [&](uint32_t w, uint32_t h, uint32_t mip_levels, uint32_t layers, VkImageViewType type, - VkFormat format, VkImage* img, VkImageView* view) { - VkImageCreateInfo ii{VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO}; - ii.imageType = VK_IMAGE_TYPE_2D; ii.format = format; ii.extent = {w, h, 1}; - ii.mipLevels = mip_levels; ii.arrayLayers = layers; ii.samples = VK_SAMPLE_COUNT_1_BIT; ii.tiling = VK_IMAGE_TILING_OPTIMAL; - ii.usage = VK_IMAGE_USAGE_SAMPLED_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT; - VkResult r = vkCreateImage(dev, &ii, nullptr, img); if (r) return r; - VkMemoryRequirements mr; vkGetImageMemoryRequirements(dev, *img, &mr); - VkMemoryAllocateInfo ai{VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO}; ai.allocationSize = mr.size; - ai.memoryTypeIndex = memtype(mr.memoryTypeBits, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT); - VkDeviceMemory m; r = vkAllocateMemory(dev, &ai, nullptr, &m); if (r) return r; - r = vkBindImageMemory(dev, *img, m, 0); if (r) return r; - VkImageViewCreateInfo vi{VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO}; - vi.image = *img; vi.viewType = type; vi.format = ii.format; - vi.subresourceRange = {aspect_of(format), 0, mip_levels, 0, layers}; - return vkCreateImageView(dev, &vi, nullptr, view); - }; - const uint32_t magenta = 0xFFFF00FFu; - // R8G8B8A8 in memory: red, green, blue, transparent yellow, then solid cyan in mip 1. - const uint32_t quadrants[2][2] = {{0xFF0000FFu, 0xFF00FF00u}, {0xFFFF0000u, 0x0000FFFFu}}; - std::vector texels(texture_side * texture_side + (two_mip ? (texture_side / 2) * (texture_side / 2) : 0), 0xFFFFFF00u); - for (uint32_t y = 0; y < texture_side; y++) { - for (uint32_t x = 0; x < texture_side; x++) { - texels[y * texture_side + x] = two_mip ? quadrants[y >= texture_side / 2][x >= texture_side / 2] - : (x * 32u) | ((y * 32u) << 8) | (128u << 16) | (255u << 24); - } - } - if (fetch) texels[0] = 0x4df82282u; - // The signed two-mip fixture uses 0 or -128 in each channel, including the alpha channel. - if (signed_mips) - for (auto& texel : texels) texel &= 0x80808080u; - if (dref) { // same size as the 8x8 gradient: one 32-bit word a texel - for (uint32_t y = 0; y < TW; y++) - for (uint32_t x = 0; x < TW; x++) { - const float depth = (x + 0.5f) / TW; - std::memcpy(&texels[y * TW + x], &depth, sizeof(depth)); - } - } - const uint32_t CUBE_LAYERS = 12; - std::vector cubes(CUBE_LAYERS * TW * TW); - for (uint32_t y = 0; y < TW; y++) - for (uint32_t x = 0; x < TW; x++) { - for (uint32_t l = 0; l < CUBE_LAYERS; l++) - cubes[(l * TW + y) * TW + x] = (x * 32u) | ((y * 32u) << 8) | ((l * 20u) << 16) | (255u << 24); - } - const VkFormat tfmt[4] = {VK_FORMAT_R8G8B8A8_UNORM, sampled_format, - VK_FORMAT_R8G8B8A8_UNORM, VK_FORMAT_R8G8B8A8_UNORM}; - VkImage timg[4]; VkImageView tview[4]; - CHECK(make_tex(1, 1, 1, 1, VK_IMAGE_VIEW_TYPE_2D, tfmt[0], &timg[0], &tview[0])); - CHECK(make_tex(texture_side, texture_side, levels, 1, VK_IMAGE_VIEW_TYPE_2D, tfmt[1], &timg[1], &tview[1])); - CHECK(make_tex(1, 1, 1, 1, VK_IMAGE_VIEW_TYPE_2D_ARRAY, tfmt[2], &timg[2], &tview[2])); - CHECK(make_tex(TW, TW, 1, CUBE_LAYERS, VK_IMAGE_VIEW_TYPE_2D_ARRAY, tfmt[3], &timg[3], &tview[3])); - VkBuffer up; VkDeviceMemory upm; void* upp; - const VkDeviceSize texture_offset = 256; - const VkDeviceSize texture_bytes = texels.size() * sizeof(uint32_t); - const VkDeviceSize cube_offset = texture_offset + texture_bytes; - CHECK(make_buffer(cube_offset + cubes.size() * sizeof(uint32_t), VK_BUFFER_USAGE_TRANSFER_SRC_BIT, &up, &upm, &upp)); - std::memcpy(upp, &magenta, sizeof(magenta)); - std::memcpy(static_cast(upp) + texture_offset, texels.data(), texture_bytes); - std::memcpy(static_cast(upp) + cube_offset, cubes.data(), cubes.size() * sizeof(uint32_t)); - VkSamplerCreateInfo sci{VK_STRUCTURE_TYPE_SAMPLER_CREATE_INFO}; - sci.magFilter = sci.minFilter = VK_FILTER_NEAREST; - sci.mipmapMode = VK_SAMPLER_MIPMAP_MODE_NEAREST; - sci.maxLod = float(levels - 1); - sci.addressModeU = sci.addressModeV = sci.addressModeW = VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE; - VkSamplerCreateInfo sci1 = sci; // index 1: the S# the shader names - if (two_mip) { - const leonida::gfx10::SamplerWords words{ssharp[0], ssharp[1], ssharp[2], ssharp[3]}; - const auto sampler = leonida::gfx10::decode(words); - sci1.minLod = sampler.min_lod; - sci1.maxLod = sampler.max_lod; - } - if (dref) { - sci1.compareEnable = VK_TRUE; - sci1.compareOp = VK_COMPARE_OP_LESS_OR_EQUAL; - } - VkSampler smp[2]; CHECK(vkCreateSampler(dev, &sci, nullptr, &smp[0])); CHECK(vkCreateSampler(dev, &sci1, nullptr, &smp[1])); - // Render target. - const VkFormat fmt = VK_FORMAT_R32G32B32A32_SFLOAT; - VkImage rt; VkImageView rtv; - { - VkImageCreateInfo ii{VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO}; - ii.imageType = VK_IMAGE_TYPE_2D; ii.format = fmt; ii.extent = {W, H, 1}; ii.mipLevels = 1; ii.arrayLayers = 1; - ii.samples = VK_SAMPLE_COUNT_1_BIT; ii.tiling = VK_IMAGE_TILING_OPTIMAL; - ii.usage = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | VK_IMAGE_USAGE_TRANSFER_SRC_BIT; - CHECK(vkCreateImage(dev, &ii, nullptr, &rt)); - VkMemoryRequirements mr; vkGetImageMemoryRequirements(dev, rt, &mr); - VkMemoryAllocateInfo ai{VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO}; ai.allocationSize = mr.size; - ai.memoryTypeIndex = memtype(mr.memoryTypeBits, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT); - VkDeviceMemory m; CHECK(vkAllocateMemory(dev, &ai, nullptr, &m)); vkBindImageMemory(dev, rt, m, 0); - VkImageViewCreateInfo vi{VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO}; - vi.image = rt; vi.viewType = VK_IMAGE_VIEW_TYPE_2D; vi.format = fmt; vi.subresourceRange = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1}; - CHECK(vkCreateImageView(dev, &vi, nullptr, &rtv)); - } - VkAttachmentDescription ad{}; ad.format = fmt; ad.samples = VK_SAMPLE_COUNT_1_BIT; - ad.loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR; ad.storeOp = VK_ATTACHMENT_STORE_OP_STORE; - ad.stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE; ad.stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE; - ad.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED; ad.finalLayout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL; - VkAttachmentReference ar{0, VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL}; - VkSubpassDescription sd{}; sd.pipelineBindPoint = VK_PIPELINE_BIND_POINT_GRAPHICS; sd.colorAttachmentCount = 1; sd.pColorAttachments = &ar; - VkRenderPassCreateInfo rpi{VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO}; - rpi.attachmentCount = 1; rpi.pAttachments = &ad; rpi.subpassCount = 1; rpi.pSubpasses = &sd; - VkSubpassDependency copy_dep{0, VK_SUBPASS_EXTERNAL, VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT, - VK_PIPELINE_STAGE_TRANSFER_BIT, VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT, VK_ACCESS_TRANSFER_READ_BIT}; - rpi.dependencyCount = 1; rpi.pDependencies = ©_dep; - VkRenderPass rp; CHECK(vkCreateRenderPass(dev, &rpi, nullptr, &rp)); - VkFramebufferCreateInfo fbi{VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO}; - fbi.renderPass = rp; fbi.attachmentCount = 1; fbi.pAttachments = &rtv; fbi.width = W; fbi.height = H; fbi.layers = 1; - VkFramebuffer fb; CHECK(vkCreateFramebuffer(dev, &fbi, nullptr, &fb)); - // Descriptor set: binding 0 images[2], 1 samplers[2], 2 hash table, 3 2D-array images[2]. - VkDescriptorSetLayoutBinding b[4]{}; - b[0] = {0, VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE, 2, VK_SHADER_STAGE_FRAGMENT_BIT, nullptr}; - b[1] = {1, VK_DESCRIPTOR_TYPE_SAMPLER, 2, VK_SHADER_STAGE_FRAGMENT_BIT, nullptr}; - b[2] = {2, VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, 1, VK_SHADER_STAGE_FRAGMENT_BIT, nullptr}; - b[3] = {3, VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE, 2, VK_SHADER_STAGE_FRAGMENT_BIT, nullptr}; - VkDescriptorSetLayoutCreateInfo dli{VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO}; dli.bindingCount = 4; dli.pBindings = b; - VkDescriptorSetLayout dsl; CHECK(vkCreateDescriptorSetLayout(dev, &dli, nullptr, &dsl)); - VkDescriptorPoolSize ps[3]{{VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE, 4}, {VK_DESCRIPTOR_TYPE_SAMPLER, 2}, {VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, 1}}; - VkDescriptorPoolCreateInfo dpi{VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO}; dpi.maxSets = 1; dpi.poolSizeCount = 3; dpi.pPoolSizes = ps; - VkDescriptorPool dp; CHECK(vkCreateDescriptorPool(dev, &dpi, nullptr, &dp)); - VkDescriptorSetAllocateInfo dai{VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO}; dai.descriptorPool = dp; dai.descriptorSetCount = 1; dai.pSetLayouts = &dsl; - VkDescriptorSet ds; CHECK(vkAllocateDescriptorSets(dev, &dai, &ds)); - VkDescriptorImageInfo ii2[2]{{VK_NULL_HANDLE, tview[0], VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL}, - {VK_NULL_HANDLE, tview[1], VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL}}; - VkDescriptorImageInfo ai2[2]{{VK_NULL_HANDLE, tview[2], VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL}, - {VK_NULL_HANDLE, tview[3], VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL}}; - VkDescriptorImageInfo si2[2]{{smp[0]}, {smp[1]}}; - VkDescriptorBufferInfo tbi{tb, 0, VK_WHOLE_SIZE}; - VkWriteDescriptorSet wr[4]{}; - for (auto& w : wr) { w.sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET; w.dstSet = ds; } - wr[0].dstBinding = 0; wr[0].descriptorCount = 2; wr[0].descriptorType = VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE; wr[0].pImageInfo = ii2; - wr[1].dstBinding = 1; wr[1].descriptorCount = 2; wr[1].descriptorType = VK_DESCRIPTOR_TYPE_SAMPLER; wr[1].pImageInfo = si2; - wr[2].dstBinding = 2; wr[2].descriptorCount = 1; wr[2].descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER; wr[2].pBufferInfo = &tbi; - wr[3].dstBinding = 3; wr[3].descriptorCount = 2; wr[3].descriptorType = VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE; wr[3].pImageInfo = ai2; - vkUpdateDescriptorSets(dev, 4, wr, 0, nullptr); - // Pipeline. - bool tail_block = false; // a stage reads the --pc-tail-ubo block (declares set 1) - auto module = [&](const char* p, VkShaderModule* m) { - auto code = read_spv(p); - if (code.empty()) { - std::fprintf(stderr, "failed to read shader module: %s\n", p); - return VK_ERROR_INITIALIZATION_FAILED; - } - if (pc_tail && leonida::vk_test::spirv_declares_set(code.data(), code.size() * 4, leonida::vk_test::pc_tail_set)) - tail_block = true; - VkShaderModuleCreateInfo smi{VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO}; smi.codeSize = code.size() * 4; smi.pCode = code.data(); - return vkCreateShaderModule(dev, &smi, nullptr, m); - }; - VkShaderModule vs, fs; CHECK(module(vs_path.c_str(), &vs)); CHECK(module(fs_path.c_str(), &fs)); - VkPipelineShaderStageCreateInfo st[2]{{VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO}, {VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO}}; - st[0].stage = VK_SHADER_STAGE_VERTEX_BIT; st[0].module = vs; st[0].pName = "main"; - st[1].stage = VK_SHADER_STAGE_FRAGMENT_BIT; st[1].module = fs; st[1].pName = "main"; - VkPushConstantRange pcr{VK_SHADER_STAGE_FRAGMENT_BIT | VK_SHADER_STAGE_VERTEX_BIT, 0, push_bytes}; - VkPipelineLayoutCreateInfo pli{VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO}; - pli.setLayoutCount = 1; pli.pSetLayouts = &dsl; pli.pushConstantRangeCount = 1; pli.pPushConstantRanges = &pcr; - leonida::vk_test::PcTail tail; - if (tail_block && !tail.create(vkGetDeviceProcAddr, dev, mp, properties.limits.minUniformBufferOffsetAlignment, - VK_SHADER_STAGE_FRAGMENT_BIT | VK_SHADER_STAGE_VERTEX_BIT, 1)) { - std::fprintf(stderr, "FAILED creating the --pc-tail-ubo block\n"); - return 1; - } - const VkDescriptorSetLayout set_layouts[] = {dsl, tail.set_layout}; - if (tail_block) { pli.setLayoutCount = 2; pli.pSetLayouts = set_layouts; } - VkPipelineLayout pl; CHECK(vkCreatePipelineLayout(dev, &pli, nullptr, &pl)); - VkPipelineVertexInputStateCreateInfo vin{VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO}; - VkPipelineInputAssemblyStateCreateInfo ia{VK_STRUCTURE_TYPE_PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO}; ia.topology = VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST; - VkViewport vp{0, 0, float(W), float(H), 0, 1}; VkRect2D sc{{0, 0}, {W, H}}; - VkPipelineViewportStateCreateInfo vps{VK_STRUCTURE_TYPE_PIPELINE_VIEWPORT_STATE_CREATE_INFO}; - vps.viewportCount = 1; vps.pViewports = &vp; vps.scissorCount = 1; vps.pScissors = ≻ - VkPipelineRasterizationStateCreateInfo rs{VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_STATE_CREATE_INFO}; rs.cullMode = VK_CULL_MODE_NONE; rs.lineWidth = 1; - VkPipelineMultisampleStateCreateInfo ms{VK_STRUCTURE_TYPE_PIPELINE_MULTISAMPLE_STATE_CREATE_INFO}; ms.rasterizationSamples = VK_SAMPLE_COUNT_1_BIT; - VkPipelineColorBlendAttachmentState cba{}; cba.colorWriteMask = 0xF; - VkPipelineColorBlendStateCreateInfo cb{VK_STRUCTURE_TYPE_PIPELINE_COLOR_BLEND_STATE_CREATE_INFO}; cb.attachmentCount = 1; cb.pAttachments = &cba; - VkGraphicsPipelineCreateInfo gpi{VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO}; - gpi.stageCount = 2; gpi.pStages = st; gpi.pVertexInputState = &vin; gpi.pInputAssemblyState = &ia; gpi.pViewportState = &vps; - gpi.pRasterizationState = &rs; gpi.pMultisampleState = &ms; gpi.pColorBlendState = &cb; gpi.layout = pl; gpi.renderPass = rp; - VkPipeline pipe; CHECK(vkCreateGraphicsPipelines(dev, VK_NULL_HANDLE, 1, &gpi, nullptr, &pipe)); - VkBuffer rb; VkDeviceMemory rbm; void* rbp; - CHECK(make_buffer(VkDeviceSize(W) * H * 16, VK_BUFFER_USAGE_TRANSFER_DST_BIT, &rb, &rbm, &rbp)); - // Commands: upload textures, draw, read back. - VkCommandPoolCreateInfo cpi{VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO}; cpi.queueFamilyIndex = qi; - VkCommandPool pool; CHECK(vkCreateCommandPool(dev, &cpi, nullptr, &pool)); - VkCommandBufferAllocateInfo cai{VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO}; cai.commandPool = pool; cai.commandBufferCount = 1; - VkCommandBuffer cmd; CHECK(vkAllocateCommandBuffers(dev, &cai, &cmd)); - VkCommandBufferBeginInfo cbi{VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO}; CHECK(vkBeginCommandBuffer(cmd, &cbi)); - const VkDeviceSize up_offset[4] = {0, texture_offset, 0, cube_offset}; - const uint32_t up_size[4] = {1, texture_side, 1, TW}, up_layers[4] = {1, 1, 1, CUBE_LAYERS}; - for (int t = 0; t < 4; t++) { - VkImageMemoryBarrier ib{VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER}; - ib.oldLayout = VK_IMAGE_LAYOUT_UNDEFINED; ib.newLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL; ib.image = timg[t]; - const uint32_t mip_levels = t == 1 ? levels : 1; - ib.subresourceRange = {aspect_of(tfmt[t]), 0, mip_levels, 0, up_layers[t]}; ib.dstAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT; - ib.srcQueueFamilyIndex = ib.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; - vkCmdPipelineBarrier(cmd, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, 0, 0, nullptr, 0, nullptr, 1, &ib); - VkDeviceSize offset = up_offset[t]; - for (uint32_t level = 0; level < mip_levels; ++level) { - const uint32_t side = up_size[t] >> level; - VkBufferImageCopy c{}; c.bufferOffset = offset; c.imageSubresource = {aspect_of(tfmt[t]), level, 0, up_layers[t]}; - c.imageExtent = {side, side, 1}; - vkCmdCopyBufferToImage(cmd, up, timg[t], VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, &c); - offset += VkDeviceSize(side) * side * up_layers[t] * sizeof(uint32_t); - } - ib.oldLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL; ib.newLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL; - ib.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT; ib.dstAccessMask = VK_ACCESS_SHADER_READ_BIT; - vkCmdPipelineBarrier(cmd, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT, 0, 0, nullptr, 0, nullptr, 1, &ib); - } - VkClearValue clear{}; for (int i = 0; i < 4; i++) clear.color.float32[i] = -1; - VkRenderPassBeginInfo rbi{VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO}; - rbi.renderPass = rp; rbi.framebuffer = fb; rbi.renderArea = sc; rbi.clearValueCount = 1; rbi.pClearValues = &clear; - vkCmdBeginRenderPass(cmd, &rbi, VK_SUBPASS_CONTENTS_INLINE); - vkCmdBindPipeline(cmd, VK_PIPELINE_BIND_POINT_GRAPHICS, pipe); - vkCmdBindDescriptorSets(cmd, VK_PIPELINE_BIND_POINT_GRAPHICS, pl, 0, 1, &ds, 0, nullptr); - uint32_t pc[push_words] = {}; - pc[ptr_sgpr] = tsharp_va; // pointer to the T# (low dword; the shader forces the high dword to 0) - pc[32] = uint32_t(heap_base); pc[33] = uint32_t(heap_base >> 32); - vkCmdPushConstants(cmd, pl, VK_SHADER_STAGE_FRAGMENT_BIT | VK_SHADER_STAGE_VERTEX_BIT, 0, push_bytes, pc); - if (tail_block) { - tail.write(0, pc, 4); - const uint32_t offset = tail.offset(0); - vkCmdBindDescriptorSets(cmd, VK_PIPELINE_BIND_POINT_GRAPHICS, pl, leonida::vk_test::pc_tail_set, 1, &tail.set, - 1, &offset); - } - vkCmdDraw(cmd, 3, 1, 0, 0); - vkCmdEndRenderPass(cmd); - VkBufferImageCopy rc{}; rc.imageSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1}; rc.imageExtent = {W, H, 1}; - vkCmdCopyImageToBuffer(cmd, rt, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, rb, 1, &rc); - VkBufferMemoryBarrier readback{VK_STRUCTURE_TYPE_BUFFER_MEMORY_BARRIER}; - readback.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT; - readback.dstAccessMask = VK_ACCESS_HOST_READ_BIT; - readback.srcQueueFamilyIndex = readback.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; - readback.buffer = rb; - readback.size = VK_WHOLE_SIZE; - vkCmdPipelineBarrier(cmd, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_HOST_BIT, - 0, 0, nullptr, 1, &readback, 0, nullptr); - CHECK(vkEndCommandBuffer(cmd)); - VkSubmitInfo si{VK_STRUCTURE_TYPE_SUBMIT_INFO}; si.commandBufferCount = 1; si.pCommandBuffers = &cmd; - CHECK(vkQueueSubmit(q, 1, &si, VK_NULL_HANDLE)); CHECK(vkQueueWaitIdle(q)); - std::ofstream output(out_path, std::ios::binary); - output.write(static_cast(rbp), std::streamsize(W) * H * 16); - output.close(); - if (!output) { std::fprintf(stderr, "failed to write %s\n", out_path.c_str()); return 1; } - std::fprintf(stderr, "ok -> %s (heap base 0x%llx)\n", out_path.c_str(), (unsigned long long)heap_base); - if (autonomous && cube) { - // Expected: the texel a cube sample of the pixel centre's direction reads from the second cube (layer 6 + face). - // Pixels on a face edge are skipped; the face chosen there depends on rounding. - const float* pixels = static_cast(rbp); - int checked = 0, wrong = 0; - for (uint32_t py = 0; py < H; py++) - for (uint32_t px = 0; px < W; px++) { - const float x = 2 * (px + 0.5f) / W - 1, y = 2 * (py + 0.5f) / H - 1, z = -0.6f; - const float ax = std::fabs(x), ay = std::fabs(y), az = std::fabs(z); - if (std::fabs(ax - ay) < 1e-3f || std::fabs(ax - az) < 1e-3f || std::fabs(ay - az) < 1e-3f) continue; - int face; - float sc, tc, ma; - if (az >= ax && az >= ay) { face = z < 0 ? 5 : 4; sc = z < 0 ? -x : x; tc = -y; ma = az; } - else if (ay >= ax) { face = y < 0 ? 3 : 2; sc = x; tc = y < 0 ? -z : z; ma = ay; } - else { face = x < 0 ? 1 : 0; sc = x < 0 ? z : -z; tc = -y; ma = ax; } - const float s = TW * 0.5f * (sc / ma + 1), t = TW * 0.5f * (tc / ma + 1); // in texels - const float* p = pixels + (py * W + px) * 4; - bool ok = false; - for (float ds : {-1e-3f, 1e-3f}) - for (float dt : {-1e-3f, 1e-3f}) { - const int tx = std::min(int(TW) - 1, int(s + ds)), ty = std::min(int(TW) - 1, int(t + dt)); - ok |= cube_texel_matches(p, tx, ty, face); - } - checked++; - wrong += !ok; - } - if (wrong) { - std::fprintf(stderr, "vk_texture_test cube: %d of %d pixels FAILED\n", wrong, checked); - return 1; - } - std::printf("vk_texture_test cube: PASSED (%d pixels, each the texel a cube sample of its direction reads)\n", - checked); - } - if (autonomous && dref) { - // Expected: pixel column px reads texel x = floor(8u) at u = (px + 0.5) / 64 (never on a texel edge), whose - // depth (x + 0.5) / 8 passes the reference 0.5 under LESS_OR_EQUAL from x = 4 on. Both results, the f32 one - // and the d16 one widened back to f32, are exactly that 1.0 or 0.0. - const float* pixels = static_cast(rbp); - int wrong_f32 = 0, wrong_d16 = 0; - for (uint32_t py = 0; py < H; py++) - for (uint32_t px = 0; px < W; px++) { - const uint32_t tx = std::min(TW - 1, uint32_t((px + 0.5f) / W * TW)); - const float want = 0.5f <= (tx + 0.5f) / TW ? 1.0f : 0.0f; - const float* p = pixels + (py * W + px) * 4; - wrong_f32 += p[0] != want; - wrong_d16 += p[1] != want; - } - if (wrong_f32 || wrong_d16) { - std::fprintf(stderr, "vk_texture_test dref: FAILED, %d pixels wrong in the f32 result and %d in the d16 one " - "(of %u)\n", wrong_f32, wrong_d16, W * H); - return 1; - } - std::printf("vk_texture_test dref: PASSED (%u pixels, f32 and d16 depth compares exact)\n", W * H); - } - if (fetch) { - // The PS converts each raw VGPR word as a signed integer. On a miss magenta's - // UNORM 1.0 channels therefore export float(0x3f800000). - const float fallback_one = static_cast(0x3f800000); - const float expected[] = { - fetch_miss ? fallback_one : fetch_uint ? 130.f : -126.f, - fetch_miss ? 0.f : 34.f, - fetch_miss ? fallback_one : fetch_uint ? 248.f : -8.f, - fetch_miss ? fallback_one : 77.f - }; - const auto* pixels = static_cast(rbp); - for (uint32_t i = 0; i < W * H * 4; ++i) { - if (pixels[i] != expected[i % 4]) { - std::fprintf(stderr, "%s pixel %u channel %u: got %g, expected %g\n", - argv[1], i / 4, i % 4, pixels[i], expected[i % 4]); - return 1; - } - } - std::printf("%s: %u exact pixels\n", argv[1], W * H); - } - if (autonomous && !cube && !dref && !fetch) { - const float* pixels = static_cast(rbp); - // Sample center pixel (32, 32) - int idx = (32 * W + 32) * 4; - float r = pixels[idx + 0]; - float g = pixels[idx + 1]; - float b = pixels[idx + 2]; - float a = pixels[idx + 3]; - if (std::abs(b - (128.0f / 255.0f)) > 0.05f || std::abs(a - 1.0f) > 0.05f) { - std::fprintf(stderr, "vk_texture_test: pixel check FAILED at (32,32): rgba=(%f, %f, %f, %f), expected gradient sample (~0.5, ~0.5, 0.5, 1.0)\n", - r, g, b, a); - return 1; - } - std::printf("vk_texture_test: PASSED (verified center pixel rgba=(%.3f, %.3f, %.3f, %.3f) from gradient texture via descriptor table)\n", - r, g, b, a); - } - return 0; -} diff --git a/runtime/test/vk_validation.h b/runtime/test/vk_validation.h deleted file mode 100644 index 20d2e0c9a..000000000 --- a/runtime/test/vk_validation.h +++ /dev/null @@ -1,100 +0,0 @@ -// Opt-in Khronos validation for the standalone Vulkan test programs. With LEONIDA_VK_VALIDATION set (and not "0") the -// instance enables VK_LAYER_KHRONOS_validation and VK_EXT_debug_utils, every message goes to stderr, and -// validation-type errors are counted so the program can fail on them (exit_status). The layer's own variables still -// apply, e.g. VK_KHRONOS_VALIDATION_GPUAV_ENABLE=1 for GPU-assisted validation of what a shader does at run time. -// Include after vulkan_loader.h (VK_NO_PROTOTYPES): every call goes through the vkGetInstanceProcAddr it loaded. -#pragma once - -#include - -#include -#include -#include -#include -#include - -namespace leonida::vk_test { - -class OptInValidation { -public: - // Before vkCreateInstance: adds the layer, the extension and a messenger that also covers instance creation to - // ici (keeping what it already enables). False, after a message, when validation was asked for but the layer - // isn't installed: the caller should fail instead of running unchecked. This object must outlive the call. - bool prepare(PFN_vkGetInstanceProcAddr gipa, VkInstanceCreateInfo& ici) { - const char* env = std::getenv("LEONIDA_VK_VALIDATION"); - on_ = env && std::strcmp(env, "0") != 0; - if (!on_) return true; - const auto enumerate = reinterpret_cast( - gipa(VK_NULL_HANDLE, "vkEnumerateInstanceLayerProperties")); - uint32_t count = 0; - if (enumerate) enumerate(&count, nullptr); - std::vector available(count); - if (count) enumerate(&count, available.data()); - bool found = false; - for (const auto& properties : available) found = found || !std::strcmp(properties.layerName, layer_); - if (!found) { - std::fprintf(stderr, "LEONIDA_VK_VALIDATION is set but %s is not installed\n", layer_); - return false; - } - layers_.assign(ici.ppEnabledLayerNames, ici.ppEnabledLayerNames + ici.enabledLayerCount); - layers_.push_back(layer_); - extensions_.assign(ici.ppEnabledExtensionNames, ici.ppEnabledExtensionNames + ici.enabledExtensionCount); - extensions_.push_back(VK_EXT_DEBUG_UTILS_EXTENSION_NAME); - info_.messageSeverity = VK_DEBUG_UTILS_MESSAGE_SEVERITY_WARNING_BIT_EXT | VK_DEBUG_UTILS_MESSAGE_SEVERITY_ERROR_BIT_EXT; - info_.messageType = VK_DEBUG_UTILS_MESSAGE_TYPE_GENERAL_BIT_EXT | VK_DEBUG_UTILS_MESSAGE_TYPE_VALIDATION_BIT_EXT; - info_.pfnUserCallback = on_message; - info_.pNext = ici.pNext; - ici.pNext = &info_; - ici.enabledLayerCount = uint32_t(layers_.size()); - ici.ppEnabledLayerNames = layers_.data(); - ici.enabledExtensionCount = uint32_t(extensions_.size()); - ici.ppEnabledExtensionNames = extensions_.data(); - return true; - } - - // After vkCreateInstance: the messenger for everything that follows. The program may exit without destroying it. - VkResult attach(PFN_vkGetInstanceProcAddr gipa, VkInstance instance) { - if (!on_) return VK_SUCCESS; - const auto create = reinterpret_cast( - gipa(instance, "vkCreateDebugUtilsMessengerEXT")); - if (!create) return VK_ERROR_EXTENSION_NOT_PRESENT; - info_.pNext = nullptr; - return create(instance, &info_, nullptr, &messenger_); - } - - bool enabled() const { return on_; } - static unsigned errors() { return error_count(); } - - // The exit status with validation counted: a run that reported a validation error fails (1) even when its own - // check passed or it reported itself unsupported (77); any other failure code is kept. - static int exit_status(int rc) { - if (!errors()) return rc; - std::fprintf(stderr, "%u validation errors\n", errors()); - return rc != 0 && rc != 77 ? rc : 1; - } - -private: - static unsigned& error_count() { - static unsigned count = 0; - return count; - } - - // Only validation-type errors count: a broken third-party layer must not fail the test. - static VKAPI_ATTR VkBool32 VKAPI_CALL on_message(VkDebugUtilsMessageSeverityFlagBitsEXT severity, - VkDebugUtilsMessageTypeFlagsEXT types, - const VkDebugUtilsMessengerCallbackDataEXT* data, void*) { - const bool validation = (types & VK_DEBUG_UTILS_MESSAGE_TYPE_VALIDATION_BIT_EXT) != 0; - if ((severity & VK_DEBUG_UTILS_MESSAGE_SEVERITY_ERROR_BIT_EXT) && validation) ++error_count(); - std::fprintf(stderr, "%s: %s\n", validation ? "validation" : "vulkan (not counted)", - data && data->pMessage ? data->pMessage : "(no message)"); - return VK_FALSE; - } - - bool on_ = false; - const char* layer_ = "VK_LAYER_KHRONOS_validation"; - std::vector layers_, extensions_; - VkDebugUtilsMessengerCreateInfoEXT info_{VK_STRUCTURE_TYPE_DEBUG_UTILS_MESSENGER_CREATE_INFO_EXT}; - VkDebugUtilsMessengerEXT messenger_ = VK_NULL_HANDLE; -}; - -} // namespace leonida::vk_test diff --git a/runtime/test/vk_xdxr_build_test.cpp b/runtime/test/vk_xdxr_build_test.cpp deleted file mode 100644 index a416a1e4d..000000000 --- a/runtime/test/vk_xdxr_build_test.cpp +++ /dev/null @@ -1,614 +0,0 @@ -// The XDXR BVH4 GPU builder (src/xdxr_build.comp, xdxr_build.h) on synthetic scenes. Each case is built on the -// device the Vulkan loader picks and written to /.bin, the acceleration structure as the GPU left it, -// with .json describing the scene: its address and the triangles (or instances) it was built from. -// `python -I tools/xdxr_bvh.py check-build ` then validates every structure and traces rays through it -// against brute force (ctest runs both; see cmake/vulkan_tools.cmake). -// -// Cases: one triangle; five (two levels); 1000 random triangles; an indexed R16 grid with a 16-byte vertex stride; -// R32 indices with R32G32 vertices; a geometry transform; two geometries with an inactive (NaN) triangle; no -// triangles; 5000 triangles (many radix-sort tiles); updates (refits) in place and into another buffer; clones and a -// compaction (CopyRaytracingAccelerationStructure) with the postbuild size; a TLAS of four instances (rotated and scaled, one with mask 0, one with no BLAS); -// BOX16 builds (blas_box16_*: half boxes, which check-build compares bit for bit with tools/xdxr_bvh.py encode_box16), -// including coordinates past the half range and below its smallest normal, and a refit; TRI1 pairing (blas_paired_*: -// sibling triangles that share an edge in one leaf), on grids, BOX16, a transform, inactive triangles, triangles that -// share an edge in the same direction or across geometries (never paired), and the radix-sort path. -// Exit 77 when there is no Vulkan device with bufferDeviceAddress. -// `vk_xdxr_build_test ` instead times BLAS builds of that many random triangles (wall clock of -// one submission each, after one warm-up; result and scratch in device-local memory), then in-place updates -// (refits) of the same structure, and writes nothing. -#include "vk_test_device.h" -#include "xdxr_build_output.h" -#include "../src/xdxr_build.h" - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#define EXPECT(condition) do { \ - if (!(condition)) { std::fprintf(stderr, "line %d: %s\n", __LINE__, #condition); return 1; } \ -} while (0) - -namespace { - -using namespace leonida; - -struct Tri { float v[3][3]; std::uint32_t geometry, primitive; }; - -struct Buffer { - VkBuffer buffer = VK_NULL_HANDLE; - void* map = nullptr; - std::uint64_t address = 0; -}; - -Buffer make(vktest::Device& gpu, std::size_t bytes, bool device_local = false) { - Buffer b; - b.buffer = gpu.buffer(bytes ? bytes : 4, VK_BUFFER_USAGE_STORAGE_BUFFER_BIT, device_local ? nullptr : &b.map); - if (b.buffer) b.address = gpu.device_address(b.buffer); - return b; -} - -void barrier_to_host(vktest::Device& gpu, VkCommandBuffer cb) { - VkMemoryBarrier host{VK_STRUCTURE_TYPE_MEMORY_BARRIER}; - host.srcAccessMask = VK_ACCESS_SHADER_WRITE_BIT; - host.dstAccessMask = VK_ACCESS_HOST_READ_BIT; - gpu.fn("vkCmdPipelineBarrier")(cb, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, - VK_PIPELINE_STAGE_HOST_BIT, 0, 1, &host, 0, nullptr, 0, - nullptr); -} - -std::string num(double x) { - if (std::isnan(x)) return "\"nan\""; - char s[64]; - std::snprintf(s, sizeof s, "%.9g", x); - return s; -} - -bool write_file(const std::string& path, const void* data, std::size_t bytes) { - std::ofstream f(path, std::ios::binary); - f.write(static_cast(data), std::streamsize(bytes)); - return bool(f); -} - -// The size a structure's header gives (totalSizeIn64BNodes does not count the header): the nodes the build wrote, -// at most the layout's size, which leaves room for the most a tree of that many elements can have. -std::size_t header_size(const void* structure) { - std::uint32_t units = 0; - std::memcpy(&units, static_cast(structure) + 4, 4); - return (std::size_t(units) + 1) * 64; -} - -std::string tris_json(const std::vector& tris) { - std::string s = "["; - for (std::size_t i = 0; i < tris.size(); ++i) { - const Tri& t = tris[i]; - s += i ? ",\n [" : "\n ["; - for (int k = 0; k < 3; ++k) - s += (k ? ", [" : "[") + num(t.v[k][0]) + ", " + num(t.v[k][1]) + ", " + num(t.v[k][2]) + "]"; - s += ", " + std::to_string(t.geometry) + ", " + std::to_string(t.primitive) + "]"; - } - return s + "]"; -} - -struct Geometry { - std::vector vertex_data; // as the buffer holds it (stride / 4 floats per vertex) - std::uint32_t stride = 12; - bool xy = false; - std::vector indices; // empty = none - bool u16 = false; - bool transform = false; - float m[12] = {}; - std::uint32_t triangle_count = 0; -}; - -// The world-space triangles a geometry describes, as the reference must see them. -void expand(const Geometry& g, std::uint32_t geometry, std::vector& out) { - const std::uint32_t floats = g.stride / 4; - for (std::uint32_t t = 0; t < g.triangle_count; ++t) { - Tri tri{}; - for (int k = 0; k < 3; ++k) { - const std::uint32_t v = g.indices.empty() ? 3 * t + k : g.indices[3 * t + k]; - float p[3] = {g.vertex_data[v * floats], g.vertex_data[v * floats + 1], - g.xy ? 0.0f : g.vertex_data[v * floats + 2]}; - for (int c = 0; c < 3; ++c) - tri.v[k][c] = g.transform ? g.m[4 * c] * p[0] + g.m[4 * c + 1] * p[1] + g.m[4 * c + 2] * p[2] + g.m[4 * c + 3] - : p[c]; - } - tri.geometry = geometry; - tri.primitive = t; - out.push_back(tri); - } -} - -struct Built { - std::uint64_t address = 0; - std::size_t size = 0; // as the header gives it - std::vector tris; -}; - -// With `moved` (the same geometries with new vertex positions) the BLAS is then updated: refitted in place, or with -// `into_other` into a second buffer, in which case the untouched source is written too, as _source. -// `box16`: BOX16 inner nodes. `pair`: TRI1 pairing; the case's JSON then asks check-build for at least one TRI1 -// node, or with `expect_no_pairs` for none. -int build_blas(vktest::Device& gpu, XdxrBuilder& builder, const std::string& dir, const std::string& name, - const std::vector& geometries, Built& built, unsigned rays = 0, - const std::vector* moved = nullptr, bool into_other = false, bool box16 = false, - bool pair = false, bool expect_no_pairs = false) { - std::vector keep, vertex_buffers; - std::vector descs; - std::uint32_t total = 0; - for (std::size_t g = 0; g < geometries.size(); ++g) { - const Geometry& geo = geometries[g]; - Buffer v = make(gpu, geo.vertex_data.size() * 4); - EXPECT(v.buffer); - std::memcpy(v.map, geo.vertex_data.data(), geo.vertex_data.size() * 4); - XdxrTriangles d; - d.vertices = v.address; - d.vertex_stride = geo.stride; - d.xy_only = geo.xy; - d.triangle_count = geo.triangle_count; - d.flags = 1; - keep.push_back(v); - vertex_buffers.push_back(v); - if (!geo.indices.empty()) { - Buffer ib = make(gpu, geo.indices.size() * 4); - EXPECT(ib.buffer); - if (geo.u16) { - auto* p = static_cast(ib.map); - for (std::size_t i = 0; i < geo.indices.size(); ++i) p[i] = std::uint16_t(geo.indices[i]); - } else { - std::memcpy(ib.map, geo.indices.data(), geo.indices.size() * 4); - } - d.indices = ib.address; - d.index_type = geo.u16 ? 1 : 2; - keep.push_back(ib); - } - if (geo.transform) { - Buffer tb = make(gpu, 48); - EXPECT(tb.buffer); - std::memcpy(tb.map, geo.m, 48); - d.transform = tb.address; - keep.push_back(tb); - } - descs.push_back(d); - expand(geo, std::uint32_t(g), built.tris); - total += geo.triangle_count; - } - XdxrLayout layout; - EXPECT(layout.compute(total, false, box16)); - Buffer dst = make(gpu, layout.size + 256), scratch = make(gpu, std::size_t(layout.scratch)); - EXPECT(dst.buffer && scratch.buffer); - const std::uint64_t base = (dst.address + 255) & ~std::uint64_t(255); // 256-byte aligned, as D3D12 requires - bool recorded = false; - EXPECT(gpu.run([&](VkCommandBuffer cb) { - recorded = builder.record_blas(cb, layout, descs, base, scratch.address, 0, pair); - barrier_to_host(gpu, cb); - return recorded; - })); - built.address = base; - built.size = header_size(static_cast(dst.map) + (base - dst.address)); - auto dump = [&](const std::string& case_name, const Buffer& buffer, std::uint64_t at, const std::vector& tris) { - const auto* bytes = static_cast(buffer.map) + (at - buffer.address); - const std::string json = "{\"kind\": \"blas\", \"address\": " + std::to_string(at) + - (rays ? ", \"rays\": " + std::to_string(rays) : std::string()) + - (pair && !moved ? (expect_no_pairs ? ", \"pairs\": false" : ", \"pairs\": true") - : "") + - (box16 ? ", \"box16\": true" : ", \"box16\": false") + - (name == "blas_paired_rotations" ? ", \"all_rotations\": true" : "") + - ", \"triangles\": " + tris_json(tris) + "}\n"; - const std::size_t size = header_size(bytes); - if (size > layout.size) return false; - return write_file(dir + "/" + case_name + ".bin", bytes, size) && - write_file(dir + "/" + case_name + ".json", json.data(), json.size()); - }; - if (!moved) { - EXPECT(dump(name, dst, base, built.tris)); - std::printf("%s: %u triangles, %u bytes, %u nodes\n", name.c_str(), total, layout.size, layout.nodes); - return 0; - } - // the update: new positions in the same vertex buffers, then a refit of the structure just built - EXPECT(moved->size() == geometries.size()); - std::vector moved_tris; - for (std::size_t g = 0; g < moved->size(); ++g) { - EXPECT((*moved)[g].vertex_data.size() == geometries[g].vertex_data.size()); - std::memcpy(vertex_buffers[g].map, (*moved)[g].vertex_data.data(), (*moved)[g].vertex_data.size() * 4); - expand((*moved)[g], std::uint32_t(g), moved_tris); - } - Buffer other = into_other ? make(gpu, layout.size + 256) : Buffer{}; - const std::uint64_t target = into_other ? (other.address + 255) & ~std::uint64_t(255) : base; - EXPECT(!into_other || other.buffer); - EXPECT(gpu.run([&](VkCommandBuffer cb) { - recorded = builder.record_blas(cb, layout, descs, target, scratch.address, base); - barrier_to_host(gpu, cb); - return recorded; - })); - if (into_other) EXPECT(dump(name + "_source", dst, base, built.tris)); // a refit must not touch its source - EXPECT(dump(name, into_other ? other : dst, target, moved_tris)); - built.tris = moved_tris; - built.address = target; - std::printf("%s: %u triangles refitted %s, %u bytes\n", name.c_str(), total, - into_other ? "into another buffer" : "in place", layout.size); - return 0; -} - -} // namespace - -int main(int argc, char** argv) { - if (argc < 2) { - std::fprintf(stderr, "usage: vk_xdxr_build_test \n"); - return 2; - } - const std::string dir = argv[1]; - if (const auto ec = prepare_xdxr_build_output(dir, argc > 2)) { - std::fprintf(stderr, "cannot create output directory %s: %s\n", dir.c_str(), ec.message().c_str()); - return 1; - } - vktest::Device gpu; - gpu.request_buffer_device_address = true; - const auto status = gpu.initialize(); - if (status == vktest::DeviceStatus::unavailable || (status == vktest::DeviceStatus::ready && !gpu.buffer_device_address)) { - std::printf("vk_xdxr_build_test: no Vulkan device with bufferDeviceAddress, skipped\n"); - return 77; - } - if (status != vktest::DeviceStatus::ready) return 1; - XdxrBuilder builder(gpu.device_proc, gpu.device); - EXPECT(builder.loaded()); - - if (argc > 2) { // timing only - const std::uint32_t n = std::uint32_t(std::strtoul(argv[2], nullptr, 10)); - EXPECT(n > 0); - std::mt19937 trng(3); - std::uniform_real_distribution u(-100.0f, 100.0f), j(-0.5f, 0.5f); - Buffer v = make(gpu, std::size_t(n) * 36); - EXPECT(v.buffer); - auto* f = static_cast(v.map); - for (std::uint32_t t = 0; t < n; ++t) { - const float c[3] = {u(trng), u(trng), u(trng)}; - for (int k = 0; k < 9; ++k) f[9 * t + k] = c[k % 3] + j(trng); - } - XdxrTriangles d; - d.vertices = v.address; - d.triangle_count = n; - XdxrLayout layout; - EXPECT(layout.compute(n, false)); - // in VRAM, where the layer keeps acceleration structures (host-visible memory on a discrete GPU is PCIe) - Buffer dst = make(gpu, layout.size, true), scratch = make(gpu, std::size_t(layout.scratch), true); - EXPECT(dst.buffer && scratch.buffer); - double best = 1e30; - for (int rep = 0; rep < 4; ++rep) { - const auto t0 = std::chrono::steady_clock::now(); - EXPECT(gpu.run([&](VkCommandBuffer cb) { return builder.record_blas(cb, layout, {d}, dst.address, scratch.address); })); - const double ms = std::chrono::duration(std::chrono::steady_clock::now() - t0).count(); - if (rep) best = std::min(best, ms); - } - double refit = 1e30; // an update of the structure just built, in place - for (int rep = 0; rep < 4; ++rep) { - const auto t0 = std::chrono::steady_clock::now(); - EXPECT(gpu.run([&](VkCommandBuffer cb) { - return builder.record_blas(cb, layout, {d}, dst.address, scratch.address, dst.address); - })); - const double ms = std::chrono::duration(std::chrono::steady_clock::now() - t0).count(); - if (rep) refit = std::min(refit, ms); - } - std::printf("%u triangles: %.2f ms (best of 3), refit %.2f ms, result %u bytes, scratch %llu bytes, sort size %u\n", - n, best, refit, layout.size, static_cast(layout.scratch), layout.sort_size); - return 0; - } - - std::mt19937 rng(7); - std::uniform_real_distribution spread(-4.0f, 4.0f), jitter(-0.6f, 0.6f); - auto soup = [&](std::uint32_t n) { - Geometry g; - g.triangle_count = n; - for (std::uint32_t t = 0; t < n; ++t) { - const float c[3] = {spread(rng), spread(rng), spread(rng)}; - for (int k = 0; k < 3; ++k) - for (int a = 0; a < 3; ++a) g.vertex_data.push_back(c[a] + jitter(rng)); - } - return g; - }; - auto grid = [&](std::uint32_t n, std::uint32_t floats_per_vertex, bool xy) { - Geometry g; - g.stride = 4 * floats_per_vertex; - g.xy = xy; - for (std::uint32_t j = 0; j <= n; ++j) - for (std::uint32_t i = 0; i <= n; ++i) { - const float p[4] = {float(i) - n * 0.5f, float(j) - n * 0.5f, xy ? 0.0f : 0.25f * float((i * 7 + j * 3) % 5), 9.0f}; - for (std::uint32_t f = 0; f < floats_per_vertex; ++f) g.vertex_data.push_back(p[f]); - } - for (std::uint32_t j = 0; j < n; ++j) - for (std::uint32_t i = 0; i < n; ++i) { - const std::uint32_t a = j * (n + 1) + i; - const std::uint32_t q[6] = {a, a + 1, a + n + 2, a, a + n + 2, a + n + 1}; - g.indices.insert(g.indices.end(), q, q + 6); - } - g.triangle_count = 2 * n * n; - return g; - }; - - Built one, five, random, grid16, xy32, moved, multi, empty; - if (build_blas(gpu, builder, dir, "blas_one", {soup(1)}, one)) return 1; - if (build_blas(gpu, builder, dir, "blas_five", {soup(5)}, five)) return 1; - if (build_blas(gpu, builder, dir, "blas_random", {soup(1000)}, random)) return 1; - Geometry g16 = grid(12, 4, false); - g16.u16 = true; - if (build_blas(gpu, builder, dir, "blas_grid_u16_stride16", {g16}, grid16)) return 1; - if (build_blas(gpu, builder, dir, "blas_grid_u32_xy", {grid(9, 2, true)}, xy32)) return 1; - Geometry gt = grid(6, 3, false); - gt.transform = true; - const float m[12] = {0, 2, 0, 1, 0, 0, 1, -2, 2, 0, 0, 3}; // exact in float: permute, scale by 2, translate - std::memcpy(gt.m, m, sizeof m); - if (build_blas(gpu, builder, dir, "blas_transform", {gt}, moved)) return 1; - Geometry a = soup(40), b = soup(25); - b.vertex_data[3 * 3 * 7] = std::nanf(""); // triangle 7 of geometry 1: inactive - if (build_blas(gpu, builder, dir, "blas_two_geometries", {a, b}, multi)) return 1; - if (build_blas(gpu, builder, dir, "blas_empty", {}, empty)) return 1; - // many radix-sort tiles (RADIX_TILE elements each), the last one partial (fewer rays: the brute force is slow) - Built tiles; - if (build_blas(gpu, builder, dir, "blas_three_sort_tiles", {soup(5000)}, tiles, 200)) return 1; - - // Updates. Every triangle moves (its own offset, and a stretch), so each box changes; the tree is kept. - auto move = [&](Geometry g, float amount) { - std::uniform_real_distribution d(-amount, amount); - const std::uint32_t floats = g.stride / 4; - for (std::size_t v = 0; v + 2 < g.vertex_data.size(); v += floats) { - const float dx = d(rng), dy = d(rng); - g.vertex_data[v] = g.vertex_data[v] * 1.25f + dx; - g.vertex_data[v + 1] = g.vertex_data[v + 1] * 0.8f + dy; - if (!g.xy) g.vertex_data[v + 2] += d(rng); - } - return g; - }; - { - Built refitted; - const Geometry big = soup(3000); // the radix-sort path - const std::vector after = {move(big, 1.5f)}; - if (build_blas(gpu, builder, dir, "blas_refit_in_place", {big}, refitted, 300, &after)) return 1; - Built copied; - const Geometry g = grid(12, 4, false); // R32 indices, stride 16; the small-sort path - const std::vector after_grid = {move(g, 0.3f)}; - if (build_blas(gpu, builder, dir, "blas_refit_into_other", {g}, copied, 0, &after_grid, true)) return 1; - } - - // BOX16 inner nodes: the same tree with half boxes rounded outward (64-byte nodes instead of 128). - { - Built h0, h1, h2, h3, h4; // build_blas appends to a Built's triangles - if (build_blas(gpu, builder, dir, "blas_box16_random", {soup(1000)}, h0, 0, nullptr, false, true)) return 1; - if (build_blas(gpu, builder, dir, "blas_box16_sort_tiles", {soup(5000)}, h1, 200, nullptr, false, true)) return 1; - Geometry a16 = soup(40), b16 = soup(25); - b16.vertex_data[3 * 3 * 3] = std::nanf(""); // an inactive triangle: an empty box - if (build_blas(gpu, builder, dir, "blas_box16_two_geometries", {a16, b16}, h2, 0, nullptr, false, true)) return 1; - // Coordinates the half format cannot hold: past 65504 (inf outward, HALF_MAX inward), between 2^-14 and - // 2^-24 and below (no denormal halves: 0 or +-2^-14), exact halves, and ordinary triangles the rays hit. - Geometry x = soup(24); - const float odd[][9] = { - {70000.0f, 1.0f, 2.0f, 70001.0f, 3.0f, 2.5f, 69999.0f, 2.0f, 1.5f}, - {-65520.0f, -65504.0f, 65504.0f, -65519.0f, -65500.0f, 65505.0f, -65000.0f, -65503.0f, 65490.0f}, - {3.0e-5f, -2.0e-6f, 1.0e-7f, 6.0e-5f, 4.0e-5f, -1.0e-9f, -3.0e-5f, 6.103515625e-5f, 0.0f}, - {-0.0f, 1.0e-30f, -1.0e-30f, 2.0f, 0.5f, 0.25f, 1.0f, -0.125f, 0.0f}, - {1e30f, -1e30f, 5.0f, 1e30f, -1e30f, 6.0f, -1e30f, 1e30f, 5.5f}, - {1.0009766f, -2.0019531f, 3.0f, 1.0f, -2.0f, 3.0029297f, 1.0004883f, -2.0f, 3.0f}, - }; - for (const auto& t : odd) x.vertex_data.insert(x.vertex_data.end(), t, t + 9); - x.triangle_count += sizeof odd / sizeof odd[0]; - if (build_blas(gpu, builder, dir, "blas_box16_extremes", {x}, h3, 0, nullptr, false, true)) return 1; - const Geometry big = soup(3000); - const std::vector after = {move(big, 1.5f)}; - if (build_blas(gpu, builder, dir, "blas_box16_refit_in_place", {big}, h4, 300, &after, false, true)) return 1; - } - - // TRI1 pairing: the same tree, with sibling triangles that share an edge in one leaf. - { - Built p0, p1, p2, p3, p4; - Geometry pg = grid(12, 4, false); - pg.u16 = true; - if (build_blas(gpu, builder, dir, "blas_paired_grid", {pg}, p0, 0, nullptr, false, false, true)) return 1; - if (build_blas(gpu, builder, dir, "blas_paired_grid_box16", {grid(9, 2, true)}, p1, 0, nullptr, false, true, - true)) - return 1; - Geometry ptf = grid(6, 3, false); - ptf.transform = true; - std::memcpy(ptf.m, m, sizeof m); - if (build_blas(gpu, builder, dir, "blas_paired_transform", {ptf}, p2, 0, nullptr, false, false, true)) return 1; - // A grid with a NaN vertex (its triangles are inactive); quads split across two geometries (each edge shared - // the right way, but a leaf holds one geometry, so a pair would report the wrong one); and triangle pairs that - // share an edge in the same direction (mirrored winding: not a valid pair). - Geometry holed = grid(8, 3, false); - holed.vertex_data[3 * 40] = std::nanf(""); - // Each pair is small and the pairs are spread through the volume, so a pair's two triangles have nearly the - // same Morton key and end up siblings: the rules, not the sort, must keep them apart. - Geometry cross_a, cross_b, same_dir; - for (int i = 0; i < 32; ++i) { - const float cx = spread(rng), cy = spread(rng), cz = spread(rng); - const float a[3] = {cx - 0.2f, cy, cz}, b[3] = {cx + 0.2f, cy, cz}; - const float up[3] = {cx, cy + 0.3f, cz + 0.05f}, down[3] = {cx, cy - 0.3f, cz - 0.05f}; - const float ta[9] = {a[0], a[1], a[2], b[0], b[1], b[2], up[0], up[1], up[2]}; // A -> B - const float tb[9] = {b[0], b[1], b[2], a[0], a[1], a[2], down[0], down[1], down[2]}; // B -> A - const float td[9] = {a[0], a[1], a[2], b[0], b[1], b[2], down[0], down[1], down[2]}; // A -> B again - if (i < 16) { // across two geometries, the reverse edge - cross_a.vertex_data.insert(cross_a.vertex_data.end(), ta, ta + 9); - cross_b.vertex_data.insert(cross_b.vertex_data.end(), tb, tb + 9); - } else { // one geometry, the same direction - same_dir.vertex_data.insert(same_dir.vertex_data.end(), ta, ta + 9); - same_dir.vertex_data.insert(same_dir.vertex_data.end(), td, td + 9); - } - } - cross_a.triangle_count = cross_b.triangle_count = 16; - same_dir.triangle_count = 32; - if (build_blas(gpu, builder, dir, "blas_paired_mixed", {holed, cross_a, cross_b, same_dir}, p3, 0, nullptr, - false, false, true)) - return 1; - // on their own, so that the triangles that must not pair are siblings: no TRI1 at all - Built q0, q1; - if (build_blas(gpu, builder, dir, "blas_unpaired_geometries", {cross_a, cross_b}, q0, 0, nullptr, false, false, - true, true)) - return 1; - if (build_blas(gpu, builder, dir, "blas_unpaired_same_direction", {same_dir}, q1, 0, nullptr, false, false, - true, true)) - return 1; - // Every triangle of a grid starts at another of its vertices (the same winding), so pairs come in all nine - // combinations of the first triangle's rotation k and the sibling's kd (check-build asserts it). - Geometry rotated = grid(16, 3, false); - for (std::size_t t = 0; t + 2 < rotated.indices.size(); t += 3) { - const std::uint32_t r = std::uint32_t((t / 3) * 7 / 3 % 3), i0 = rotated.indices[t], - i1 = rotated.indices[t + 1], i2 = rotated.indices[t + 2]; - const std::uint32_t v[3] = {i0, i1, i2}; - for (std::uint32_t k = 0; k < 3; ++k) rotated.indices[t + k] = v[(k + r) % 3]; - } - Built p5; - if (build_blas(gpu, builder, dir, "blas_paired_rotations", {rotated}, p5, 0, nullptr, false, false, true)) - return 1; - // 7,200 triangles: the radix-sort path - if (build_blas(gpu, builder, dir, "blas_paired_sort_tiles", {grid(60, 3, false)}, p4, 200, nullptr, false, - false, true)) - return 1; - } - - // TLAS: instances over blas_random and blas_grid_u16_stride16. An instance names its BLAS by a 40-bit address - // (256-byte units in 32 bits), as on the console; device addresses can be wider (llvmpipe's are host pointers). - // The instances hold application-style addresses, device address - bias, as the layer's address window does. - const std::uint64_t bias = (std::min(random.address, grid16.address) - 0x10000) & ~std::uint64_t(0xffff); - auto va = [&](std::uint64_t device) { return device ? device - bias : 0; }; - struct Inst { float m[12]; std::uint32_t id_mask; std::uint32_t contrib; std::uint64_t blas; int which; }; - const float c = std::cos(0.7f), s = std::sin(0.7f); - const Inst insts[] = { - {{1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0}, 0xff000000u | 10, 0, va(random.address), 0}, - {{c, -s, 0, 9, s, c, 0, -1, 0, 0, 1, 0.5f}, 0x01000000u | 11, 3, va(grid16.address), 1}, - {{2, 0, 0, -9, 0, 0.5f, 0, 2, 0, 0, 1.5f, 1}, 0x00000000u | 12, 0, va(random.address), 0}, // mask 0 - {{c, 0, s, 0, 0, 1, 0, 9, -s, 0, c, -2}, 0xff000000u | 13, 0, 0, -1}, // no BLAS - }; - const std::uint32_t count = sizeof insts / sizeof insts[0]; - for (const Inst& i : insts) EXPECT(i.blas < (std::uint64_t(1) << 40)); - Buffer descs = make(gpu, 64 * count); - EXPECT(descs.buffer); - for (std::uint32_t i = 0; i < count; ++i) { - auto* d = static_cast(descs.map) + 64 * i; - std::memcpy(d, insts[i].m, 48); - std::memcpy(d + 48, &insts[i].id_mask, 4); - std::memcpy(d + 52, &insts[i].contrib, 4); - std::memcpy(d + 56, &insts[i].blas, 8); - } - XdxrLayout layout; - EXPECT(layout.compute(count, true)); - Buffer dst = make(gpu, layout.size + 256), scratch = make(gpu, std::size_t(layout.scratch)); - EXPECT(dst.buffer && scratch.buffer); - const std::uint64_t base = (dst.address + 255) & ~std::uint64_t(255); - bool recorded = false; - EXPECT(gpu.run([&](VkCommandBuffer cb) { - recorded = builder.record_tlas(cb, layout, descs.address, base, scratch.address, bias); - barrier_to_host(gpu, cb); - return recorded; - })); - const char* tlas_bytes = static_cast(dst.map) + (base - dst.address); - EXPECT(header_size(tlas_bytes) <= layout.size); - EXPECT(write_file(dir + "/tlas.bin", tlas_bytes, header_size(tlas_bytes))); - std::string json = "{\"kind\": \"tlas\", \"address\": " + std::to_string(base) + ", \"bias\": " + - std::to_string(bias) + ", \"blas\": [\"blas_random\", " + - "\"blas_grid_u16_stride16\"], \"instances\": ["; - for (std::uint32_t i = 0; i < count; ++i) { - json += i ? ", {" : "{"; - json += "\"transform\": ["; - for (int k = 0; k < 12; ++k) json += (k ? ", " : "") + num(insts[i].m[k]); - json += "], \"mask\": " + std::to_string(insts[i].id_mask >> 24) + ", \"blas\": " + std::to_string(insts[i].which) + "}"; - } - json += "]}\n"; - EXPECT(write_file(dir + "/tlas.json", json.data(), json.size())); - - // The TLAS updated in place: every instance moves and turns; the masked and the BLAS-less ones stay so. - Inst moved_insts[sizeof insts / sizeof insts[0]]; - std::memcpy(moved_insts, insts, sizeof insts); - const float c2 = std::cos(1.9f), s2 = std::sin(1.9f); - const float turned[12] = {c2, 0, s2, 4, 0, 1, 0, -3, -s2, 0, c2, 2}; - std::memcpy(moved_insts[0].m, turned, sizeof turned); - moved_insts[1].m[3] -= 7; - moved_insts[1].m[7] += 5; - moved_insts[2].m[11] -= 4; - for (std::uint32_t i = 0; i < count; ++i) std::memcpy(static_cast(descs.map) + 64 * i, moved_insts[i].m, 48); - EXPECT(gpu.run([&](VkCommandBuffer cb) { - recorded = builder.record_tlas(cb, layout, descs.address, base, scratch.address, bias, base); - barrier_to_host(gpu, cb); - return recorded; - })); - EXPECT(write_file(dir + "/tlas_refit.bin", tlas_bytes, header_size(tlas_bytes))); - std::string json2 = "{\"kind\": \"tlas\", \"address\": " + std::to_string(base) + ", \"bias\": " + - std::to_string(bias) + ", \"blas\": [\"blas_random\", \"blas_grid_u16_stride16\"], \"instances\": ["; - for (std::uint32_t i = 0; i < count; ++i) { - json2 += i ? ", {" : "{"; - json2 += "\"transform\": ["; - for (int k = 0; k < 12; ++k) json2 += (k ? ", " : "") + num(moved_insts[i].m[k]); - json2 += "], \"mask\": " + std::to_string(moved_insts[i].id_mask >> 24) + ", \"blas\": " + - std::to_string(moved_insts[i].which) + "}"; - } - json2 += "]}\n"; - EXPECT(write_file(dir + "/tlas_refit.json", json2.data(), json2.size())); - - // CopyRaytracingAccelerationStructure: a clone of blas_random, its COMPACTED_SIZE (postbuild), a compaction into - // a buffer of exactly that size, and a clone of the refitted TLAS. The copies are position-independent. - { - XdxrLayout blas_layout; - EXPECT(blas_layout.compute(1000, false)); - Buffer clone = make(gpu, blas_layout.size + 256), info = make(gpu, 16); - EXPECT(clone.buffer && info.buffer); - const std::uint64_t clone_at = (clone.address + 255) & ~std::uint64_t(255); - std::memset(info.map, 0xab, 16); - EXPECT(gpu.run([&](VkCommandBuffer cb) { - const bool ok = builder.record_copy(cb, random.address, clone_at, blas_layout.size) && - builder.record_postbuild(cb, random.address, info.address) && - builder.record_postbuild(cb, clone_at, info.address + 8); - barrier_to_host(gpu, cb); - return ok; - })); - std::uint64_t compacted = 0, clone_size = 0; - std::memcpy(&compacted, info.map, 8); - std::memcpy(&clone_size, static_cast(info.map) + 8, 8); - // a build is already as small as it gets: the size its header gives, within the layout's room - EXPECT(compacted == random.size && compacted <= blas_layout.size); - EXPECT(clone_size == compacted); - auto dump_blas = [&](const std::string& name, const Buffer& b, std::uint64_t at, std::size_t bytes) { - const std::string j = "{\"kind\": \"blas\", \"address\": " + std::to_string(at) + - ", \"triangles\": " + tris_json(random.tris) + "}\n"; - return write_file(dir + "/" + name + ".bin", static_cast(b.map) + (at - b.address), bytes) && - write_file(dir + "/" + name + ".json", j.data(), j.size()); - }; - EXPECT(dump_blas("blas_clone", clone, clone_at, std::size_t(compacted))); - // COMPACT into exactly the compacted size; a guard word after it must survive - Buffer packed = make(gpu, std::size_t(compacted) + 256 + 4); - EXPECT(packed.buffer); - const std::uint64_t packed_at = (packed.address + 255) & ~std::uint64_t(255); - const std::uint32_t guard = 0x600dc0deu; - std::memcpy(static_cast(packed.map) + (packed_at - packed.address) + compacted, &guard, 4); - EXPECT(gpu.run([&](VkCommandBuffer cb) { - const bool ok = builder.record_copy(cb, clone_at, packed_at, compacted + 4); // more room than needed - barrier_to_host(gpu, cb); - return ok; - })); - std::uint32_t after = 0; - std::memcpy(&after, static_cast(packed.map) + (packed_at - packed.address) + compacted, 4); - EXPECT(after == guard); // the copy stops at the source's own size - EXPECT(dump_blas("blas_compacted", packed, packed_at, std::size_t(compacted))); - - Buffer tclone = make(gpu, layout.size + 256); - EXPECT(tclone.buffer); - const std::uint64_t tclone_at = (tclone.address + 255) & ~std::uint64_t(255); - EXPECT(gpu.run([&](VkCommandBuffer cb) { - const bool ok = builder.record_copy(cb, base, tclone_at, layout.size); - barrier_to_host(gpu, cb); - return ok; - })); - EXPECT(write_file(dir + "/tlas_refit_clone.bin", static_cast(tclone.map) + (tclone_at - tclone.address), - header_size(tlas_bytes))); - std::string json3 = json2; - json3.replace(json3.find(std::to_string(base)), std::to_string(base).size(), std::to_string(tclone_at)); - EXPECT(write_file(dir + "/tlas_refit_clone.json", json3.data(), json3.size())); - std::printf("copies: blas_clone, blas_compacted (%llu bytes), tlas_refit_clone\n", - static_cast(compacted)); - } - std::printf("tlas: %u instances, %u bytes\nvk_xdxr_build_test: built every case\n", count, layout.size); - return 0; -} diff --git a/runtime/test/vulkan13_features_test.cpp b/runtime/test/vulkan13_features_test.cpp deleted file mode 100644 index c9795ade5..000000000 --- a/runtime/test/vulkan13_features_test.cpp +++ /dev/null @@ -1,456 +0,0 @@ -// Unit tests for Vulkan13Features and device_proc_or_khr (runtime/src/vulkan13_features.h). CPU-only, no Vulkan -// instance and no GPU: synthetic callbacks exercise the 1.1 rejection, 1.2 KHR/EXT fallback, and 1.3 core paths. -#ifndef VK_NO_PROTOTYPES -#define VK_NO_PROTOTYPES -#endif -#include "../src/vulkan13_features.h" - -#include -#include -#include -#include -#include - -#define EXPECT(condition) do { \ - if (!(condition)) { std::fprintf(stderr, "line %d: %s\n", __LINE__, #condition); return 1; } \ -} while (0) - -using leonida::Vulkan13Features; -using leonida::device_proc_or_khr; - -namespace { - -struct FakeDevice { - std::vector extensions; - VkBool32 dynamic_rendering = VK_FALSE; - VkBool32 synchronization2 = VK_FALSE; - VkBool32 subgroup_size_control = VK_FALSE; - VkBool32 compute_full_subgroups = VK_FALSE; - VkBool32 eds = VK_FALSE; - VkBool32 eds2 = VK_FALSE; - int features2_calls = 0; - int enum_calls = 0; - std::vector queried_types; -}; - -FakeDevice* g_device = nullptr; - -VKAPI_ATTR VkResult VKAPI_CALL fake_enumerate_extensions( - VkPhysicalDevice, const char*, std::uint32_t* count, VkExtensionProperties* properties) { - ++g_device->enum_calls; - if (!properties) { - *count = static_cast(g_device->extensions.size()); - return VK_SUCCESS; - } - const std::uint32_t n = static_cast(g_device->extensions.size()); - const std::uint32_t write = *count < n ? *count : n; - for (std::uint32_t i = 0; i < write; ++i) { - std::memset(&properties[i], 0, sizeof(properties[i])); - const std::size_t len = std::min(std::strlen(g_device->extensions[i]), VK_MAX_EXTENSION_NAME_SIZE - 1); - std::memcpy(properties[i].extensionName, g_device->extensions[i], len); - } - *count = write; - return VK_SUCCESS; -} - -VKAPI_ATTR void VKAPI_CALL fake_get_features2(VkPhysicalDevice, VkPhysicalDeviceFeatures2* features) { - ++g_device->features2_calls; - g_device->queried_types.clear(); - for (auto* node = static_cast(features->pNext); node; node = node->pNext) { - g_device->queried_types.push_back(node->sType); - switch (node->sType) { - case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_3_FEATURES: { - auto* f = reinterpret_cast(node); - f->dynamicRendering = g_device->dynamic_rendering; - f->synchronization2 = g_device->synchronization2; - f->subgroupSizeControl = g_device->subgroup_size_control; - f->computeFullSubgroups = g_device->compute_full_subgroups; - break; - } - case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_DYNAMIC_RENDERING_FEATURES_KHR: - reinterpret_cast(node)->dynamicRendering = - g_device->dynamic_rendering; - break; - case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SYNCHRONIZATION_2_FEATURES_KHR: - reinterpret_cast(node)->synchronization2 = - g_device->synchronization2; - break; - case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SUBGROUP_SIZE_CONTROL_FEATURES_EXT: { - auto* f = reinterpret_cast(node); - f->subgroupSizeControl = g_device->subgroup_size_control; - f->computeFullSubgroups = g_device->compute_full_subgroups; - break; - } - case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_EXTENDED_DYNAMIC_STATE_FEATURES_EXT: - reinterpret_cast(node)->extendedDynamicState = - g_device->eds; - break; - case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_EXTENDED_DYNAMIC_STATE_2_FEATURES_EXT: - reinterpret_cast(node)->extendedDynamicState2 = - g_device->eds2; - break; - default: - break; - } - } -} - -std::vector chain_types(const void* head) { - std::vector types; - for (const auto* node = static_cast(head); node; node = node->pNext) { - types.push_back(node->sType); - } - return types; -} - -VKAPI_ATTR void VKAPI_CALL stub_core() {} -VKAPI_ATTR void VKAPI_CALL stub_khr() {} -VKAPI_ATTR void VKAPI_CALL stub_ext() {} - -struct ProcLookup { - const char* core_name = nullptr; - const char* khr_name = nullptr; - const char* ext_name = nullptr; - std::vector queries; -}; - -ProcLookup* g_proc = nullptr; - -VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL fake_get_device_proc(VkDevice, const char* name) { - g_proc->queries.emplace_back(name); - if (g_proc->core_name && std::strcmp(name, g_proc->core_name) == 0) return stub_core; - if (g_proc->khr_name && std::strcmp(name, g_proc->khr_name) == 0) return stub_khr; - if (g_proc->ext_name && std::strcmp(name, g_proc->ext_name) == 0) return stub_ext; - return nullptr; -} - -} // namespace - -int main() { - // Vulkan 1.3 core device: queries VkPhysicalDeviceVulkan13Features without enumerating extensions. - { - FakeDevice dev; - dev.dynamic_rendering = VK_TRUE; - dev.synchronization2 = VK_TRUE; - dev.subgroup_size_control = VK_TRUE; - dev.compute_full_subgroups = VK_FALSE; - g_device = &dev; - - Vulkan13Features v13; - v13.query(VK_NULL_HANDLE, VK_API_VERSION_1_3, fake_get_features2, nullptr); - EXPECT(dev.features2_calls == 1 && dev.enum_calls == 0); - EXPECT(dev.queried_types.size() == 1 && - dev.queried_types[0] == VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_3_FEATURES); - EXPECT(v13.core && v13.usable()); - EXPECT(v13.dynamic_rendering && v13.synchronization2); - EXPECT(v13.subgroup_size_control && !v13.compute_full_subgroups); - EXPECT(v13.extended_dynamic_state); - - VkBaseOutStructure tail{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2, nullptr}; - void* head = v13.enable(&tail); - const auto* enable13 = static_cast(head); - EXPECT(enable13->sType == VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_3_FEATURES); - EXPECT(enable13->dynamicRendering == VK_TRUE && enable13->synchronization2 == VK_TRUE); - EXPECT(enable13->subgroupSizeControl == VK_TRUE && enable13->computeFullSubgroups == VK_FALSE); - EXPECT(enable13->pNext == &tail); - - // Inserting a later feature struct through next() places it between enable13 and tail. - VkBaseOutStructure extra{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_1_FEATURES, nullptr}; - extra.pNext = static_cast(*v13.next()); - *v13.next() = &extra; - const auto types = chain_types(head); - EXPECT(types.size() == 3); - EXPECT(types[0] == VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_3_FEATURES); - EXPECT(types[1] == VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_1_FEATURES); - EXPECT(types[2] == VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2); - - // Core 1.3 needs no extra extensions. - std::vector exts = {"VK_KHR_swapchain"}; - v13.add_extensions(exts); - EXPECT(exts.size() == 1 && std::strcmp(exts[0], "VK_KHR_swapchain") == 0); - } - - // Vulkan 1.3 missing either required feature is not usable; Vulkan 1.4 still takes the core path. - { - FakeDevice dev; - dev.dynamic_rendering = VK_TRUE; - dev.synchronization2 = VK_FALSE; - g_device = &dev; - - Vulkan13Features v13; - v13.query(VK_NULL_HANDLE, VK_MAKE_API_VERSION(0, 1, 4, 0), fake_get_features2, nullptr); - EXPECT(v13.core && v13.dynamic_rendering && !v13.synchronization2 && !v13.usable()); - - dev.dynamic_rendering = VK_FALSE; - dev.synchronization2 = VK_TRUE; - v13.query(VK_NULL_HANDLE, VK_API_VERSION_1_3, fake_get_features2, nullptr); - EXPECT(v13.core && !v13.dynamic_rendering && v13.synchronization2 && !v13.usable()); - } - - // Vulkan 1.1 and null callbacks never qualify, and reset flags from an earlier query. - { - FakeDevice dev; - dev.dynamic_rendering = VK_TRUE; - dev.synchronization2 = VK_TRUE; - dev.subgroup_size_control = VK_TRUE; - g_device = &dev; - - Vulkan13Features v13; - v13.query(VK_NULL_HANDLE, VK_API_VERSION_1_3, fake_get_features2, nullptr); - EXPECT(v13.usable()); - - dev.features2_calls = 0; - v13.query(VK_NULL_HANDLE, VK_API_VERSION_1_1, fake_get_features2, fake_enumerate_extensions); - EXPECT(!v13.core && !v13.usable() && !v13.extended_dynamic_state && !v13.subgroup_size_control); - EXPECT(dev.features2_calls == 0 && dev.enum_calls == 0); - - v13.query(VK_NULL_HANDLE, VK_API_VERSION_1_3, nullptr, nullptr); - EXPECT(v13.core && !v13.usable() && !v13.extended_dynamic_state); - - v13.query(VK_NULL_HANDLE, VK_API_VERSION_1_2, fake_get_features2, nullptr); - EXPECT(!v13.core && !v13.usable() && dev.features2_calls == 0); - } - - // Vulkan 1.2 missing a required KHR extension returns before querying features2. - { - FakeDevice dev; - dev.extensions = {VK_KHR_DYNAMIC_RENDERING_EXTENSION_NAME}; - dev.dynamic_rendering = VK_TRUE; - dev.synchronization2 = VK_TRUE; - g_device = &dev; - - Vulkan13Features v13; - v13.query(VK_NULL_HANDLE, VK_API_VERSION_1_2, fake_get_features2, fake_enumerate_extensions); - EXPECT(!v13.core && !v13.usable()); - EXPECT(dev.enum_calls == 2 && dev.features2_calls == 0); - } - - // Vulkan 1.2 can pin subgroup size with the extension regardless of dynamic-state extensions. - { - FakeDevice dev; - dev.extensions = {VK_KHR_DYNAMIC_RENDERING_EXTENSION_NAME, VK_KHR_SYNCHRONIZATION_2_EXTENSION_NAME, - VK_EXT_SUBGROUP_SIZE_CONTROL_EXTENSION_NAME}; - dev.dynamic_rendering = dev.synchronization2 = dev.subgroup_size_control = VK_TRUE; - dev.compute_full_subgroups = VK_TRUE; - g_device = &dev; - Vulkan13Features v13; - v13.query(VK_NULL_HANDLE, VK_API_VERSION_1_2, fake_get_features2, fake_enumerate_extensions); - EXPECT(v13.usable() && v13.subgroup_size_control && v13.compute_full_subgroups); - std::vector extensions; - v13.add_extensions(extensions); - EXPECT(extensions.size() == 3 && std::strcmp(extensions.back(), VK_EXT_SUBGROUP_SIZE_CONTROL_EXTENSION_NAME) == 0); - VkBaseOutStructure tail{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2, nullptr}; - auto* head = static_cast(v13.enable(&tail)); - auto* sg = reinterpret_cast(head->pNext->pNext); - EXPECT(sg->sType == VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SUBGROUP_SIZE_CONTROL_FEATURES_EXT); - EXPECT(sg->subgroupSizeControl && sg->computeFullSubgroups && *v13.next() == &tail); - dev.subgroup_size_control = VK_FALSE; - v13.query(VK_NULL_HANDLE, VK_API_VERSION_1_2, fake_get_features2, fake_enumerate_extensions); - EXPECT(v13.usable() && !v13.subgroup_size_control && !v13.compute_full_subgroups); - } - - // Vulkan 1.2 with KHR dynamic_rendering + synchronization2, without extended_dynamic_state(2). - { - FakeDevice dev; - dev.extensions = {VK_KHR_DYNAMIC_RENDERING_EXTENSION_NAME, VK_KHR_SYNCHRONIZATION_2_EXTENSION_NAME}; - dev.dynamic_rendering = VK_TRUE; - dev.synchronization2 = VK_TRUE; - g_device = &dev; - - Vulkan13Features v13; - v13.query(VK_NULL_HANDLE, VK_API_VERSION_1_2, fake_get_features2, fake_enumerate_extensions); - EXPECT(!v13.core && v13.usable() && !v13.extended_dynamic_state); - EXPECT(!v13.subgroup_size_control && !v13.compute_full_subgroups); - EXPECT(dev.queried_types.size() == 2); - EXPECT(dev.queried_types[0] == VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_DYNAMIC_RENDERING_FEATURES_KHR); - EXPECT(dev.queried_types[1] == VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SYNCHRONIZATION_2_FEATURES_KHR); - - VkBaseOutStructure tail{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2, nullptr}; - void* head = v13.enable(&tail); - VkBaseOutStructure extra{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_1_FEATURES, nullptr}; - extra.pNext = static_cast(*v13.next()); - *v13.next() = &extra; - - const auto types = chain_types(head); - EXPECT(types.size() == 4); - EXPECT(types[0] == VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_DYNAMIC_RENDERING_FEATURES_KHR); - EXPECT(types[1] == VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SYNCHRONIZATION_2_FEATURES_KHR); - EXPECT(types[2] == VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_1_FEATURES); - EXPECT(types[3] == VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2); - - const auto* rendering = static_cast(head); - const auto* sync2 = static_cast(rendering->pNext); - EXPECT(rendering->dynamicRendering == VK_TRUE); - EXPECT(sync2->synchronization2 == VK_TRUE); - - std::vector exts; - v13.add_extensions(exts); - EXPECT(exts.size() == 2); - EXPECT(std::strcmp(exts[0], VK_KHR_DYNAMIC_RENDERING_EXTENSION_NAME) == 0); - EXPECT(std::strcmp(exts[1], VK_KHR_SYNCHRONIZATION_2_EXTENSION_NAME) == 0); - - // Extensions advertised, but each required feature bit cleared in turn after a successful query. - dev.features2_calls = 0; - dev.dynamic_rendering = VK_FALSE; - dev.synchronization2 = VK_TRUE; - v13.query(VK_NULL_HANDLE, VK_API_VERSION_1_2, fake_get_features2, fake_enumerate_extensions); - EXPECT(dev.features2_calls == 1); - EXPECT(!v13.core && !v13.dynamic_rendering && v13.synchronization2 && !v13.usable()); - - dev.dynamic_rendering = VK_TRUE; - dev.synchronization2 = VK_FALSE; - v13.query(VK_NULL_HANDLE, VK_API_VERSION_1_2, fake_get_features2, fake_enumerate_extensions); - EXPECT(dev.features2_calls == 2); - EXPECT(!v13.core && v13.dynamic_rendering && !v13.synchronization2 && !v13.usable()); - } - - // Vulkan 1.2 with only EDS1 (missing EDS2), or both extensions with one feature bit false: EDS stays off. - { - FakeDevice dev; - dev.extensions = { - VK_KHR_DYNAMIC_RENDERING_EXTENSION_NAME, - VK_KHR_SYNCHRONIZATION_2_EXTENSION_NAME, - VK_EXT_EXTENDED_DYNAMIC_STATE_EXTENSION_NAME, - }; - dev.dynamic_rendering = VK_TRUE; - dev.synchronization2 = VK_TRUE; - dev.eds = VK_TRUE; - dev.eds2 = VK_TRUE; - g_device = &dev; - - Vulkan13Features v13; - v13.query(VK_NULL_HANDLE, VK_API_VERSION_1_2, fake_get_features2, fake_enumerate_extensions); - EXPECT(v13.usable() && !v13.extended_dynamic_state); - EXPECT(dev.queried_types.size() == 3); - EXPECT(dev.queried_types[2] == VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_EXTENDED_DYNAMIC_STATE_FEATURES_EXT); - - dev.extensions.push_back(VK_EXT_EXTENDED_DYNAMIC_STATE_2_EXTENSION_NAME); - dev.eds2 = VK_FALSE; - v13.query(VK_NULL_HANDLE, VK_API_VERSION_1_2, fake_get_features2, fake_enumerate_extensions); - EXPECT(v13.usable() && !v13.extended_dynamic_state); - EXPECT(dev.queried_types.size() == 4); - } - - // Vulkan 1.2 with KHR + EDS1 + EDS2 all supported: enables all four structs and adds all four extensions. - { - FakeDevice dev; - dev.extensions = { - VK_KHR_DYNAMIC_RENDERING_EXTENSION_NAME, - VK_KHR_SYNCHRONIZATION_2_EXTENSION_NAME, - VK_EXT_EXTENDED_DYNAMIC_STATE_EXTENSION_NAME, - VK_EXT_EXTENDED_DYNAMIC_STATE_2_EXTENSION_NAME, - }; - dev.dynamic_rendering = VK_TRUE; - dev.synchronization2 = VK_TRUE; - dev.eds = VK_TRUE; - dev.eds2 = VK_TRUE; - g_device = &dev; - - Vulkan13Features candidate; - candidate.query(VK_NULL_HANDLE, VK_API_VERSION_1_2, fake_get_features2, fake_enumerate_extensions); - EXPECT(!candidate.core && candidate.usable() && candidate.extended_dynamic_state); - - // choose() preserves the winning device's flags even after candidate is overwritten. - Vulkan13Features chosen; - chosen.choose(candidate); - candidate.query(VK_NULL_HANDLE, VK_API_VERSION_1_1, fake_get_features2, fake_enumerate_extensions); - EXPECT(!candidate.usable()); - EXPECT(!chosen.core && chosen.usable() && chosen.extended_dynamic_state); - - VkBaseOutStructure tail{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2, nullptr}; - void* head = chosen.enable(&tail); - VkBaseOutStructure extra{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_1_FEATURES, nullptr}; - extra.pNext = static_cast(*chosen.next()); - *chosen.next() = &extra; - - const auto types = chain_types(head); - EXPECT(types.size() == 6); - EXPECT(types[0] == VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_DYNAMIC_RENDERING_FEATURES_KHR); - EXPECT(types[1] == VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SYNCHRONIZATION_2_FEATURES_KHR); - EXPECT(types[2] == VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_EXTENDED_DYNAMIC_STATE_FEATURES_EXT); - EXPECT(types[3] == VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_EXTENDED_DYNAMIC_STATE_2_FEATURES_EXT); - EXPECT(types[4] == VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_1_FEATURES); - EXPECT(types[5] == VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2); - - const auto* rendering = static_cast(head); - const auto* sync2 = static_cast(rendering->pNext); - const auto* eds = static_cast(sync2->pNext); - const auto* eds2 = static_cast(eds->pNext); - EXPECT(rendering->dynamicRendering == VK_TRUE); - EXPECT(sync2->synchronization2 == VK_TRUE); - EXPECT(eds->extendedDynamicState == VK_TRUE); - EXPECT(eds2->extendedDynamicState2 == VK_TRUE); - - std::vector exts; - chosen.add_extensions(exts); - EXPECT(exts.size() == 4); - EXPECT(std::strcmp(exts[0], VK_KHR_DYNAMIC_RENDERING_EXTENSION_NAME) == 0); - EXPECT(std::strcmp(exts[1], VK_KHR_SYNCHRONIZATION_2_EXTENSION_NAME) == 0); - EXPECT(std::strcmp(exts[2], VK_EXT_EXTENDED_DYNAMIC_STATE_EXTENSION_NAME) == 0); - EXPECT(std::strcmp(exts[3], VK_EXT_EXTENDED_DYNAMIC_STATE_2_EXTENSION_NAME) == 0); - } - - // choose() with a Vulkan 1.3 candidate preserves core=true and subgroup flags after source overwrite. - { - FakeDevice dev; - dev.dynamic_rendering = VK_TRUE; - dev.synchronization2 = VK_TRUE; - dev.subgroup_size_control = VK_TRUE; - dev.compute_full_subgroups = VK_TRUE; - g_device = &dev; - - Vulkan13Features candidate; - candidate.query(VK_NULL_HANDLE, VK_API_VERSION_1_3, fake_get_features2, nullptr); - EXPECT(candidate.core && candidate.usable()); - - Vulkan13Features chosen; - chosen.choose(candidate); - candidate.query(VK_NULL_HANDLE, VK_API_VERSION_1_1, fake_get_features2, fake_enumerate_extensions); - EXPECT(!candidate.core && !candidate.usable()); - EXPECT(chosen.core && chosen.usable() && chosen.extended_dynamic_state); - EXPECT(chosen.subgroup_size_control && chosen.compute_full_subgroups); - - VkBaseOutStructure tail{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2, nullptr}; - void* head = chosen.enable(&tail); - const auto* enable13 = static_cast(head); - EXPECT(enable13->sType == VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_3_FEATURES); - EXPECT(enable13->dynamicRendering == VK_TRUE && enable13->synchronization2 == VK_TRUE); - EXPECT(enable13->subgroupSizeControl == VK_TRUE && enable13->computeFullSubgroups == VK_TRUE); - EXPECT(enable13->pNext == &tail); - - std::vector exts; - chosen.add_extensions(exts); - EXPECT(exts.empty()); - } - - // device_proc_or_khr resolves core first, then KHR, then EXT, else null. - { - ProcLookup lookup; - g_proc = &lookup; - - lookup.core_name = "vkCmdPipelineBarrier2"; - lookup.khr_name = "vkCmdPipelineBarrier2KHR"; - lookup.ext_name = "vkCmdPipelineBarrier2EXT"; - EXPECT(device_proc_or_khr(fake_get_device_proc, VK_NULL_HANDLE, "vkCmdPipelineBarrier2") == stub_core); - EXPECT(lookup.queries.size() == 1 && lookup.queries[0] == "vkCmdPipelineBarrier2"); - - lookup.queries.clear(); - lookup.core_name = nullptr; - EXPECT(device_proc_or_khr(fake_get_device_proc, VK_NULL_HANDLE, "vkCmdPipelineBarrier2") == stub_khr); - EXPECT(lookup.queries.size() == 2 && lookup.queries[1] == "vkCmdPipelineBarrier2KHR"); - - lookup.queries.clear(); - lookup.khr_name = nullptr; - lookup.ext_name = "vkCmdSetPrimitiveTopologyEXT"; - EXPECT(device_proc_or_khr(fake_get_device_proc, VK_NULL_HANDLE, "vkCmdSetPrimitiveTopology") == stub_ext); - EXPECT(lookup.queries.size() == 3 && lookup.queries[2] == "vkCmdSetPrimitiveTopologyEXT"); - - lookup.queries.clear(); - lookup.ext_name = nullptr; - EXPECT(device_proc_or_khr(fake_get_device_proc, VK_NULL_HANDLE, "vkCmdBeginRendering") == nullptr); - EXPECT(lookup.queries.size() == 3); - } - - std::printf("vulkan13_features: all checks passed\n"); - return 0; -} diff --git a/runtime/test/vulkan_device_filter_test.cpp b/runtime/test/vulkan_device_filter_test.cpp deleted file mode 100644 index 95a0ef6df..000000000 --- a/runtime/test/vulkan_device_filter_test.cpp +++ /dev/null @@ -1,96 +0,0 @@ -// Unit tests for LEONIDA_VK_DEVICE name matching and the device rank (runtime/src/vulkan_device_filter.h). No Vulkan -// instance and no GPU: the filter is a pure function of the environment and a device name, the rank of type and vendor. -#include "vulkan_device_filter.h" - -#include -#include -#include -#include - -namespace { - -int failures = 0; - -void expect(bool ok, const char* what) { - if (ok) return; - std::fprintf(stderr, "FAIL %s\n", what); - ++failures; -} - -void set_filter(const char* value) { -#ifdef _WIN32 - _putenv_s("LEONIDA_VK_DEVICE", value); -#else - if (value[0] == '\0') { - unsetenv("LEONIDA_VK_DEVICE"); - } else { - setenv("LEONIDA_VK_DEVICE", value, 1); - } -#endif -} - -} // namespace - -int main() { - using leonida::vulkan_device_filter; - using leonida::vulkan_device_wanted; - - const char* saved = std::getenv("LEONIDA_VK_DEVICE"); - const std::string saved_value = saved ? saved : ""; - - // Unset (or empty) takes every device, including a null name. - set_filter(""); - expect(vulkan_device_filter().empty(), "empty filter"); - expect(vulkan_device_wanted("AMD Radeon RX 7900 XTX"), "unset matches a real name"); - expect(vulkan_device_wanted(""), "unset matches an empty name"); - expect(vulkan_device_wanted(nullptr), "unset matches a null name"); - - // A filter is a case-insensitive substring of the device name. - set_filter("RADEON"); - expect(vulkan_device_filter() == "radeon", "filter is lower-cased"); - expect(vulkan_device_wanted("AMD Radeon RX 7900 XTX"), "case-insensitive match"); - expect(vulkan_device_wanted("amd radeon graphics"), "lower-case name matches"); - expect(!vulkan_device_wanted("NVIDIA GeForce RTX 5070 Ti"), "different vendor does not match"); - - set_filter("rtx 5070"); - expect(vulkan_device_wanted("NVIDIA GeForce RTX 5070 Ti"), "substring with a space matches"); - expect(!vulkan_device_wanted("NVIDIA GeForce RTX 4070 Ti"), "other model does not match"); - - set_filter("7900"); - expect(vulkan_device_wanted("AMD Radeon RX 7900 XTX"), "model number matches"); - expect(!vulkan_device_wanted(nullptr), "a filter never matches a null name"); - expect(!vulkan_device_wanted(""), "a filter never matches an empty name"); - - // The rank the runtime and every harness pick by (VkPhysicalDeviceType values: OTHER 0, INTEGRATED 1, DISCRETE 2, - // VIRTUAL 3, CPU 4). A native driver beats Microsoft's layers of any type, so Dozen ("Microsoft Direct3D12 (...)", - // reported as discrete) never wins over the GPU it wraps, nor over a native integrated GPU (#915). - using leonida::vulkan_device_rank; - constexpr std::uint32_t amd = 0x1002, nvidia = 0x10de, microsoft = leonida::microsoft_vulkan_vendor_id; - expect(microsoft == 0x1414, "Microsoft's PCI vendor id"); - expect(vulkan_device_rank(2, amd) > vulkan_device_rank(1, amd), "discrete over integrated"); - expect(vulkan_device_rank(1, amd) > vulkan_device_rank(3, amd), "integrated over virtual"); - expect(vulkan_device_rank(3, amd) > vulkan_device_rank(4, amd), "virtual over CPU"); - expect(vulkan_device_rank(4, amd) > vulkan_device_rank(0, amd), "CPU over other"); - expect(vulkan_device_rank(0, amd) > vulkan_device_rank(2, microsoft), "any native device over Dozen"); - expect(vulkan_device_rank(2, microsoft) > vulkan_device_rank(4, microsoft), "among Microsoft's, discrete first"); - expect(vulkan_device_rank(2, amd) == vulkan_device_rank(2, nvidia), "vendors other than Microsoft tie"); - expect(vulkan_device_rank(99, amd) == vulkan_device_rank(0, amd), "an unknown type ranks as other"); - - // Do not leak the test's value into anything that runs later in this process. -#ifdef _WIN32 - _putenv_s("LEONIDA_VK_DEVICE", saved_value.c_str()); -#else - if (saved_value.empty()) { - unsetenv("LEONIDA_VK_DEVICE"); - } else { - setenv("LEONIDA_VK_DEVICE", saved_value.c_str(), 1); - } -#endif - - if (failures != 0) { - std::fprintf(stderr, "%d failure(s)\n", failures); - return 1; - } - std::printf("vulkan_device_filter: all checks passed\n"); - return 0; -} diff --git a/runtime/test/vulkan_loader.h b/runtime/test/vulkan_loader.h deleted file mode 100644 index a65ff2f8b..000000000 --- a/runtime/test/vulkan_loader.h +++ /dev/null @@ -1,57 +0,0 @@ -// Loads Vulkan at run time. The macOS test tools default to MoltenVK. -#pragma once - -#ifndef VK_NO_PROTOTYPES -#define VK_NO_PROTOTYPES -#endif -#include - -#include -#include - -#ifdef _WIN32 -#include -#else -#include -#endif - -inline PFN_vkGetInstanceProcAddr load_vulkan() { - // Keep the Vulkan library loaded for the lifetime of the tool. -#ifdef _WIN32 - constexpr auto library_name = "vulkan-1.dll"; - static const auto library = LoadLibraryA(library_name); - const auto entry = library ? GetProcAddress(library, "vkGetInstanceProcAddr") : nullptr; -#elif defined(__APPLE__) - static const auto entry = []() -> void* { - // MoltenVK compiles MSL with fast-math on by default, which lets Metal fold an f32 compare of a NaN with - // itself to "ordered" (v_cmpx_eq/le_f32 on (NaN, NaN) give true; ps_vcmpx_forms). Translated shaders need - // IEEE results, so turn it off before MoltenVK reads its configuration, unless the user set the variable - // (docs/design.md, "MoltenVK fast-math"). The same variable reaches MoltenVK behind the Vulkan loader. - setenv("MVK_CONFIG_FAST_MATH_ENABLED", "0", 0); - // The default is direct MoltenVK: a portability driver would otherwise require instance opt-in. - const char* requested = std::getenv("LEONIDA_VULKAN_LOADER"); - const bool overridden = requested && *requested; - const char* name = overridden ? requested : "libMoltenVK.dylib"; - auto library = dlopen(name, RTLD_NOW | RTLD_LOCAL); - if (!library && !overridden) { - name = "/opt/homebrew/lib/libMoltenVK.dylib"; - library = dlopen(name, RTLD_NOW | RTLD_LOCAL); - } - if (!library) { - std::fprintf(stderr, "could not load %s: %s\n", name, dlerror()); - return nullptr; - } - const auto symbol = dlsym(library, "vkGetInstanceProcAddr"); - if (!symbol) std::fprintf(stderr, "%s has no vkGetInstanceProcAddr\n", name); - return symbol; - }(); -#else - constexpr auto library_name = "libvulkan.so.1"; - static const auto library = dlopen(library_name, RTLD_NOW | RTLD_LOCAL); - const auto entry = library ? dlsym(library, "vkGetInstanceProcAddr") : nullptr; -#endif -#ifndef __APPLE__ - if (!entry) std::fprintf(stderr, "could not load vkGetInstanceProcAddr from %s\n", library_name); -#endif - return reinterpret_cast(entry); -} diff --git a/runtime/test/vulkan_mesh_limits_test.cpp b/runtime/test/vulkan_mesh_limits_test.cpp deleted file mode 100644 index bcb23b7c4..000000000 --- a/runtime/test/vulkan_mesh_limits_test.cpp +++ /dev/null @@ -1,81 +0,0 @@ -// leonida::mesh_limit_refusal with synthetic device limits: no GPU. A mesh PSO whose workgroup memory is over the -// device's mesh shared memory budget is refused before pipeline creation (a driver dies on that module), while one that -// fits, or a device whose limits were not read, is not. Mesh shared memory is a smaller budget than compute's. -#ifndef VK_NO_PROTOTYPES -#define VK_NO_PROTOTYPES -#endif -#include "../src/vulkan_mesh_limits.h" - -#include - -#define EXPECT(condition) do { \ - if (!(condition)) { std::fprintf(stderr, "line %d: %s\n", __LINE__, #condition); return 1; } \ -} while (0) - -using namespace leonida; - -namespace { - -// NVIDIA's mesh limits (maxMeshSharedMemorySize 28672; payload plus shared 28672). -VkPhysicalDeviceMeshShaderPropertiesEXT nvidia() { - VkPhysicalDeviceMeshShaderPropertiesEXT l{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MESH_SHADER_PROPERTIES_EXT}; - l.maxMeshOutputVertices = 256; - l.maxMeshOutputPrimitives = 256; - l.maxMeshWorkGroupInvocations = 128; - l.maxMeshWorkGroupSize[0] = 128; - l.maxMeshWorkGroupSize[1] = l.maxMeshWorkGroupSize[2] = 128; - l.maxMeshSharedMemorySize = 28672; - l.maxMeshPayloadAndSharedMemorySize = 28672; - return l; -} - -ShaderEntry mesh(std::uint32_t lds_bytes) { - ShaderEntry e; - e.name = "ms_big"; - e.stage = "ms"; - e.local_size = {64, 1, 1}; - e.max_vertices = 64; - e.max_primitives = 126; - e.lds_bytes = lds_bytes; - return e; -} - -} // namespace - -int main() { - const auto limits = nvidia(); - // At the budget: accepted. One word over: refused, naming the stage and both numbers. - EXPECT(mesh_limit_refusal(mesh(28672), limits).empty()); - const std::string over = mesh_limit_refusal(mesh(28676), limits); - EXPECT(over.find("ms_big") != std::string::npos && over.find("28676") != std::string::npos && - over.find("28672") != std::string::npos); - // A 32 KiB groupshared mesh (fits compute on RADV/AMD Windows) is over NVIDIA's mesh budget but fits a device that - // reports 32768 for both. - EXPECT(!mesh_limit_refusal(mesh(32768), limits).empty()); - auto roomy = limits; - roomy.maxMeshSharedMemorySize = roomy.maxMeshPayloadAndSharedMemorySize = 32768; - EXPECT(mesh_limit_refusal(mesh(32768), roomy).empty()); - // The smaller of the two limits counts: shared memory plus payload is bounded by the second. - auto tight = roomy; - tight.maxMeshPayloadAndSharedMemorySize = 16384; - EXPECT(!mesh_limit_refusal(mesh(20000), tight).empty()); - EXPECT(mesh_limit_refusal(mesh(16384), tight).empty()); - // No workgroup memory declared: never refused for it, whatever the limit. - EXPECT(mesh_limit_refusal(mesh(0), limits).empty()); - // Limits that were not read (all zero) give no number to refuse on for memory, so a shader without outputs passes. - VkPhysicalDeviceMeshShaderPropertiesEXT unread{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MESH_SHADER_PROPERTIES_EXT}; - ShaderEntry plain = mesh(4096); - plain.max_vertices = plain.max_primitives = 0; - plain.local_size = {0, 0, 0}; - EXPECT(mesh_limit_refusal(plain, unread).empty()); - // The checks that were already there still hold: too many vertices, a workgroup axis, total invocations. - ShaderEntry many = mesh(0); - many.max_vertices = 257; - EXPECT(!mesh_limit_refusal(many, limits).empty()); - many = mesh(0); - many.local_size = {129, 1, 1}; - EXPECT(!mesh_limit_refusal(many, limits).empty()); - many.local_size = {64, 4, 1}; // 256 invocations over the 128 allowed - EXPECT(!mesh_limit_refusal(many, limits).empty()); - return 0; -} diff --git a/runtime/test/vulkan_scratch_test.cpp b/runtime/test/vulkan_scratch_test.cpp deleted file mode 100644 index 8ca6a819a..000000000 --- a/runtime/test/vulkan_scratch_test.cpp +++ /dev/null @@ -1,294 +0,0 @@ -// Unit tests for ScratchBuffers (runtime/src/vulkan_scratch.h). CPU-only, no Vulkan instance and no GPU: -// synthetic device procs exercise alignment, minimum chunk size, failure cleanup, retire/collect/forget, and spare cap. -#ifndef VK_NO_PROTOTYPES -#define VK_NO_PROTOTYPES -#endif -#include "../src/vulkan_scratch.h" - -#include -#include -#include -#include -#include - -#define EXPECT(condition) do { \ - if (!(condition)) { std::fprintf(stderr, "line %d: %s\n", __LINE__, #condition); return 1; } \ -} while (0) - -using leonida::ScratchBuffers; - -namespace { - -template -Handle make_handle(std::uintptr_t id) { - return reinterpret_cast(id); -} - -struct FakeVulkan { - std::uintptr_t next_buffer = 1; - std::uintptr_t next_memory = 1; - std::unordered_map live_buffers; - std::unordered_set live_memory; - std::unordered_map semaphore_values; - - int create_buffer_calls = 0; - int destroy_buffer_calls = 0; - int allocate_calls = 0; - int free_memory_calls = 0; - int wait_idle_calls = 0; - int get_counter_calls = 0; - - VkResult create_buffer_result = VK_SUCCESS; - VkResult bind_result = VK_SUCCESS; - VkResult counter_result = VK_SUCCESS; - bool counter_write_on_error = false; - bool return_null_memory = false; - const char* omit_proc = nullptr; -}; - -FakeVulkan* g_vk = nullptr; -const VkDevice k_device = make_handle(0x100); - -VKAPI_ATTR VkResult VKAPI_CALL fake_create_buffer( - VkDevice, const VkBufferCreateInfo* info, const VkAllocationCallbacks*, VkBuffer* out) { - ++g_vk->create_buffer_calls; - if (g_vk->create_buffer_result != VK_SUCCESS) return g_vk->create_buffer_result; - const std::uintptr_t id = g_vk->next_buffer++; - g_vk->live_buffers[id] = info->size; - *out = make_handle(id); - return VK_SUCCESS; -} - -VKAPI_ATTR void VKAPI_CALL fake_destroy_buffer(VkDevice, VkBuffer buffer, const VkAllocationCallbacks*) { - ++g_vk->destroy_buffer_calls; - g_vk->live_buffers.erase(reinterpret_cast(buffer)); -} - -VKAPI_ATTR void VKAPI_CALL fake_get_buffer_memory_requirements( - VkDevice, VkBuffer buffer, VkMemoryRequirements* reqs) { - const auto it = g_vk->live_buffers.find(reinterpret_cast(buffer)); - reqs->size = it != g_vk->live_buffers.end() ? it->second : 0; - reqs->alignment = 256; - reqs->memoryTypeBits = 1; -} - -VKAPI_ATTR VkResult VKAPI_CALL fake_bind_buffer_memory(VkDevice, VkBuffer, VkDeviceMemory, VkDeviceSize) { - return g_vk->bind_result; -} - -VKAPI_ATTR void VKAPI_CALL fake_free_memory(VkDevice, VkDeviceMemory memory, const VkAllocationCallbacks*) { - ++g_vk->free_memory_calls; - g_vk->live_memory.erase(reinterpret_cast(memory)); -} - -VKAPI_ATTR VkResult VKAPI_CALL fake_get_semaphore_counter_value( - VkDevice, VkSemaphore semaphore, std::uint64_t* value) { - ++g_vk->get_counter_calls; - const auto it = g_vk->semaphore_values.find(reinterpret_cast(semaphore)); - const std::uint64_t current = it != g_vk->semaphore_values.end() ? it->second : 0; - if (g_vk->counter_result != VK_SUCCESS) { - if (g_vk->counter_write_on_error) *value = current; - return g_vk->counter_result; - } - *value = current; - return VK_SUCCESS; -} - -VKAPI_ATTR VkResult VKAPI_CALL fake_device_wait_idle(VkDevice) { - ++g_vk->wait_idle_calls; - return VK_SUCCESS; -} - -VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL fake_get_device_proc(VkDevice, const char* name) { - if (g_vk->omit_proc && std::strcmp(name, g_vk->omit_proc) == 0) return nullptr; - if (std::strcmp(name, "vkCreateBuffer") == 0) return reinterpret_cast(fake_create_buffer); - if (std::strcmp(name, "vkDestroyBuffer") == 0) return reinterpret_cast(fake_destroy_buffer); - if (std::strcmp(name, "vkGetBufferMemoryRequirements") == 0) - return reinterpret_cast(fake_get_buffer_memory_requirements); - if (std::strcmp(name, "vkBindBufferMemory") == 0) - return reinterpret_cast(fake_bind_buffer_memory); - if (std::strcmp(name, "vkFreeMemory") == 0) return reinterpret_cast(fake_free_memory); - if (std::strcmp(name, "vkGetSemaphoreCounterValue") == 0) - return reinterpret_cast(fake_get_semaphore_counter_value); - if (std::strcmp(name, "vkDeviceWaitIdle") == 0) - return reinterpret_cast(fake_device_wait_idle); - return nullptr; -} - -VkDeviceMemory fake_allocate(const VkMemoryRequirements&) { - ++g_vk->allocate_calls; - if (g_vk->return_null_memory) return VK_NULL_HANDLE; - const std::uintptr_t id = g_vk->next_memory++; - g_vk->live_memory.insert(id); - return make_handle(id); -} - -} // namespace - -int main() { - // Missing any required proc leaves loaded() false, refuses get(), and skips vkDeviceWaitIdle in ~ScratchBuffers(). - for (const char* missing : {"vkCreateBuffer", "vkGetSemaphoreCounterValue", "vkDeviceWaitIdle"}) { - FakeVulkan vk; - vk.omit_proc = missing; - g_vk = &vk; - { - ScratchBuffers scratch(fake_get_device_proc, k_device, fake_allocate); - EXPECT(!scratch.loaded()); - VkBuffer buf = VK_NULL_HANDLE; - VkDeviceSize off = 123; - EXPECT(!scratch.get(256, buf, off)); - EXPECT(buf == VK_NULL_HANDLE && off == 123); - } - EXPECT(vk.wait_idle_calls == 0 && vk.create_buffer_calls == 0); - } - - // Zero-byte request fails without allocating; sub-allocations align to 256 bytes inside a 4 MiB minimum chunk. - { - FakeVulkan vk; - g_vk = &vk; - constexpr VkDeviceSize k_4mib = 4u << 20; - { - ScratchBuffers scratch(fake_get_device_proc, k_device, fake_allocate); - EXPECT(scratch.loaded()); - - VkBuffer buf = VK_NULL_HANDLE; - VkDeviceSize off = 0; - EXPECT(!scratch.get(0, buf, off)); - EXPECT(vk.create_buffer_calls == 0); - - EXPECT(scratch.get(100, buf, off)); - const VkBuffer chunk1 = buf; - EXPECT(chunk1 != VK_NULL_HANDLE && off == 0); - EXPECT(vk.live_buffers[reinterpret_cast(chunk1)] == k_4mib); - - EXPECT(scratch.get(12, buf, off)); - EXPECT(buf == chunk1 && off == 256); - - EXPECT(scratch.get(256, buf, off)); - EXPECT(buf == chunk1 && off == 512); - - // Exact remaining space in chunk1 (used == 768 -> aligned start 768) fits without a new chunk. - EXPECT(scratch.get(k_4mib - 768, buf, off)); - EXPECT(buf == chunk1 && off == 768); - EXPECT(vk.create_buffer_calls == 1 && vk.allocate_calls == 1); - - // One more byte spills into a second 4 MiB chunk. - EXPECT(scratch.get(1, buf, off)); - EXPECT(buf != chunk1 && off == 0); - EXPECT(vk.create_buffer_calls == 2 && vk.allocate_calls == 2); - - // Requests larger than 4 MiB allocate a chunk of the requested size. - constexpr VkDeviceSize k_6mib = 6u << 20; - EXPECT(scratch.get(k_6mib, buf, off)); - EXPECT(off == 0); - EXPECT(vk.live_buffers[reinterpret_cast(buf)] == k_6mib); - EXPECT(vk.live_buffers.size() == 3 && vk.live_memory.size() == 3); - } - EXPECT(vk.wait_idle_calls == 1); - EXPECT(vk.live_buffers.empty() && vk.live_memory.empty()); - } - - // Allocation and bind failure paths clean up partial buffer/memory handles without leaking. - { - FakeVulkan vk; - g_vk = &vk; - { - ScratchBuffers scratch(fake_get_device_proc, k_device, fake_allocate); - VkBuffer buf = VK_NULL_HANDLE; - VkDeviceSize off = 0; - - vk.create_buffer_result = VK_ERROR_OUT_OF_DEVICE_MEMORY; - EXPECT(!scratch.get(256, buf, off)); - EXPECT(vk.allocate_calls == 0 && vk.live_buffers.empty() && vk.live_memory.empty()); - - vk.create_buffer_result = VK_SUCCESS; - vk.return_null_memory = true; - EXPECT(!scratch.get(256, buf, off)); - EXPECT(vk.destroy_buffer_calls == 1 && vk.live_buffers.empty() && vk.live_memory.empty()); - - vk.return_null_memory = false; - vk.bind_result = VK_ERROR_OUT_OF_DEVICE_MEMORY; - EXPECT(!scratch.get(256, buf, off)); - EXPECT(vk.destroy_buffer_calls == 2 && vk.free_memory_calls == 1); - EXPECT(vk.live_buffers.empty() && vk.live_memory.empty()); - } - { - ScratchBuffers no_alloc(fake_get_device_proc, k_device, nullptr); - VkBuffer buf = VK_NULL_HANDLE; - VkDeviceSize off = 0; - EXPECT(!no_alloc.get(256, buf, off)); - EXPECT(vk.live_buffers.empty() && vk.live_memory.empty()); - } - } - - // retire/collect: ticket 0 collects immediately, semaphore errors/incomplete tickets stay retired, and spare caps at 4. - { - FakeVulkan vk; - g_vk = &vk; - const VkSemaphore sem_a = make_handle(0x201); - const VkSemaphore sem_b = make_handle(0x202); - constexpr VkDeviceSize k_5mib = 5u << 20; - constexpr VkDeviceSize k_6mib = 6u << 20; - { - ScratchBuffers scratch(fake_get_device_proc, k_device, fake_allocate); - VkBuffer buf = VK_NULL_HANDLE; - VkDeviceSize off = 0; - - // Empty retire() is a no-op; ticket 0 collects without a timeline semaphore. - scratch.retire(sem_a, 1); - EXPECT(scratch.get(256, buf, off)); - const VkBuffer reused_4mib = buf; - scratch.retire(VK_NULL_HANDLE, 0); - scratch.collect(); - EXPECT(vk.get_counter_calls == 0); - EXPECT(vk.live_buffers.size() == 1); - - // Reusing from spare_ makes no new vkCreateBuffer or allocate call. - EXPECT(scratch.get(512, buf, off)); - EXPECT(buf == reused_4mib && off == 0 && vk.create_buffer_calls == 1); - - // Retire with ticket > 0 and null timeline cannot be collected. - scratch.retire(VK_NULL_HANDLE, 5); - scratch.collect(); - EXPECT(vk.live_buffers.size() == 1); - - // Non-VK_SUCCESS from vkGetSemaphoreCounterValue keeps the batch retired even if value >= ticket. - EXPECT(scratch.get(k_6mib, buf, off)); - const VkBuffer big_buf = buf; - scratch.retire(sem_a, 10); - vk.semaphore_values[reinterpret_cast(sem_a)] = 10; - vk.counter_result = VK_ERROR_DEVICE_LOST; - vk.counter_write_on_error = true; - scratch.collect(); - EXPECT(vk.live_buffers.size() == 2); - - // Once counter succeeds and reaches ticket, big_buf enters spare_ and satisfies a 5 MiB request directly. - vk.counter_result = VK_SUCCESS; - scratch.collect(); - EXPECT(scratch.get(k_5mib, buf, off)); - EXPECT(buf == big_buf && off == 0 && vk.create_buffer_calls == 2); - scratch.retire(sem_b, 20); - - // Create and retire 5 distinct 4 MiB chunks; collect() keeps 4 in spare_ and destroys the 5th. - for (int i = 0; i < 5; ++i) { - EXPECT(scratch.get(256, buf, off)); - scratch.retire(sem_a, 10 + static_cast(i) + 1); - } - vk.semaphore_values[reinterpret_cast(sem_a)] = 20; - // sem_b is still at 0 (< 20), so big_buf stays retired while the 5 sem_a chunks are collected. - scratch.collect(); - EXPECT(vk.destroy_buffer_calls == 1 && vk.free_memory_calls == 1); - // Live buffers: 1 null-timeline + 1 sem_b (retired) + 4 spare = 6. - EXPECT(vk.live_buffers.size() == 6); - - // forget(sem_b) frees only sem_b's retired batch and leaves the null-timeline batch and 4 spares intact. - scratch.forget(sem_b); - EXPECT(vk.live_buffers.find(reinterpret_cast(big_buf)) == vk.live_buffers.end()); - EXPECT(vk.live_buffers.size() == 5); - } - EXPECT(vk.live_buffers.empty() && vk.live_memory.empty()); - } - - std::printf("vulkan_scratch: all checks passed\n"); - return 0; -} diff --git a/runtime/test/wait_registration_test.cpp b/runtime/test/wait_registration_test.cpp deleted file mode 100644 index 2ebbac767..000000000 --- a/runtime/test/wait_registration_test.cpp +++ /dev/null @@ -1,478 +0,0 @@ -#include "pch.h" -#include "XTaskQueuePriv.h" -#include "TaskQueueP.h" -#include "TaskQueueImpl.h" - -#include -#include -#include -#ifdef _DEBUG -#include -#endif - -namespace -{ -constexpr auto work = XTaskQueuePort::Work; -constexpr auto manual = XTaskQueueDispatchMode::Manual; -constexpr auto immediate = XTaskQueueDispatchMode::Immediate; - -void Check(bool success, const char* step) -{ - std::fprintf(stderr, "%s %s\n", success ? "PASS" : "FAIL", step); - if (!success) std::exit(1); -} - -struct Waiter -{ - explicit Waiter(const wchar_t* name = nullptr) : - signal(CreateEventW(nullptr, FALSE, FALSE, name)) {} - - XTaskQueueHandle queue{}; - XTaskQueueRegistrationToken token{}; - HANDLE signal; - HANDLE published = CreateEvent(nullptr, TRUE, FALSE, nullptr); - HANDLE returned = CreateEvent(nullptr, TRUE, FALSE, nullptr); - std::atomic calls{0}; - std::atomic canceled{0}; - bool unregisterInCallback = false; - bool unregisterInMonitor = false; - bool closeInCallback = false; - bool holdCancellation = false; - HANDLE allowExit = nullptr; - std::atomic leavingCallback{false}; - Waiter* unregisterTarget = nullptr; - Waiter* peer = nullptr; - std::barrier<>* bothEntered = nullptr; - - void Register() - { - Check(signal && published && returned, "events created"); - Check(SUCCEEDED(XTaskQueueRegisterWaiter(queue, work, signal, this, - [](void* context, bool cancel) - { - auto& w = *static_cast(context); - ++w.calls; - if (cancel) ++w.canceled; - if (w.peer) - { - w.bothEntered->arrive_and_wait(); - XTaskQueueUnregisterWaiter(w.peer->queue, w.peer->token); - SetEvent(w.returned); - } - if (w.unregisterInCallback) - { - Check(w.token.token != 0, "public token visible inside callback"); - XTaskQueueUnregisterWaiter(w.queue, w.token); - SetEvent(w.returned); - if (w.allowExit) - { - Check(WaitForSingleObject(w.allowExit, 5000) == WAIT_OBJECT_0, "release running callback"); - w.leavingCallback = true; - } - } - if (w.unregisterTarget) - { - auto& target = *w.unregisterTarget; - XTaskQueueUnregisterWaiter(target.queue, target.token); - Check(target.calls == 1, "reentrant unregister observed physical entry"); - SetEvent(w.returned); - } - if (w.closeInCallback) - { - XTaskQueueCloseHandle(w.queue); - SetEvent(w.returned); - } - }, &token)), "waiter token published"); - } - - void CloseEvents() - { - if (signal) CloseHandle(signal); - CloseHandle(published); - CloseHandle(returned); - } -}; - -void CALLBACK Monitor(void* context, XTaskQueueHandle, XTaskQueuePort port) -{ - if (port != work) return; - auto& w = *static_cast(context); - if (w.unregisterInMonitor) - { - XTaskQueueUnregisterWaiter(w.queue, w.token); - SetEvent(w.returned); - } - SetEvent(w.published); - if (w.holdCancellation) - Check(WaitForSingleObject(w.returned, 5000) == WAIT_OBJECT_0, "cancellation monitor released"); -} - -void Await(HANDLE event, const char* step) -{ - Check(WaitForSingleObject(event, 5000) == WAIT_OBJECT_0, step); -} - -template -void AwaitCondition(Predicate predicate, const char* step) -{ - const auto deadline = GetTickCount64() + 5000; - while (!predicate()) - { - if (GetTickCount64() >= deadline) Check(false, step); - std::this_thread::yield(); - } - Check(true, step); -} -} - -struct WaitRegistrationTestAccess -{ - static TaskQueuePortImpl& Port(Waiter& waiter) - { - XTaskQueuePortHandle handle{}; - Check(SUCCEEDED(XTaskQueueGetPort(waiter.queue, work, &handle)), "local work port"); - return *static_cast(handle->m_port); - } - - static void HoldSnapshot(Waiter& waiter, const wchar_t* eventName) - { - auto& port = Port(waiter); - { - TaskQueuePortImpl::WaitSnapshot snapshot; - port.CaptureWaitSnapshot(snapshot); - Check(snapshot.registrations.count() == 1 && snapshot.epoch, "snapshot includes waiter and epoch"); - std::thread retire([&] { XTaskQueueUnregisterWaiter(waiter.queue, waiter.token); }); - retire.join(); - CloseHandle(waiter.signal); - waiter.signal = nullptr; - Check(SetEvent(snapshot.events[1]), "snapshot owns a usable handle after retirement"); - Check(WaitForSingleObject(snapshot.events[1], 0) == WAIT_OBJECT_0, "old snapshot consumed signal"); - port.ProcessWaitCallback(snapshot.registrations[0].get()); - } - Check(!XTaskQueueDispatch(waiter.queue, work, 0) && waiter.calls == 0, "old snapshot cannot deliver"); - HANDLE remaining = OpenEventW(SYNCHRONIZE, FALSE, eventName); - Check(!remaining && GetLastError() == ERROR_FILE_NOT_FOUND, "last snapshot released event"); - } - - static void CheckAdmission(Waiter& waiter, bool reentrant) - { - auto& port = Port(waiter); - struct Status : OS::ThreadPoolActionStatus - { - HANDLE admitted = CreateEvent(nullptr, TRUE, FALSE, nullptr); - HANDLE proceed = CreateEvent(nullptr, TRUE, FALSE, nullptr); - void Complete() override {} - void MayRunLong() override - { - SetEvent(admitted); - Await(proceed, "allowed to enter user code"); - } - ~Status() { CloseHandle(admitted); CloseHandle(proceed); } - } status; - Check(SetEvent(waiter.signal), "waiter signaled"); - Await(waiter.published, "ready for dispatch"); - TaskQueuePortImpl::WaitSnapshot snapshot; - port.CaptureWaitSnapshot(snapshot); - std::thread dispatch([&] { Check(port.DrainOneItem(status), "admitted entry dispatched"); }); - Await(status.admitted, "admitted before indirect call"); - Waiter caller; - if (reentrant) - { - caller.unregisterTarget = &waiter; - Check(SUCCEEDED(XTaskQueueCreate(manual, immediate, &caller.queue)), "reentrant caller queue"); - caller.Register(); - Check(SetEvent(caller.signal), "reentrant caller signaled"); - } - std::thread retire([&] { - if (reentrant) - { - Check(XTaskQueueDispatch(caller.queue, work, 5000), "reentrant caller dispatched"); - Await(caller.returned, "reentrant unregister returned"); - } - else XTaskQueueUnregisterWaiter(waiter.queue, waiter.token); - Check(waiter.calls == 1, "physical entry preceded unregister return"); - }); - { - std::unique_lock lock(port.m_lock); - Check(port.m_waitFinished.wait_for(lock, std::chrono::seconds(5), - [&] { return snapshot.registrations[0]->drained; }), "native drainage complete"); - Check(waiter.calls == 0, "admission alone did not invoke user"); - } - SetEvent(status.proceed); - dispatch.join(); - retire.join(); - if (reentrant) - { - XTaskQueueUnregisterWaiter(caller.queue, caller.token); - XTaskQueueCloseHandle(caller.queue); - } - caller.CloseEvents(); - } - - static void ExternalAfterSelf(Waiter& w) - { - auto& port = Port(w); - TaskQueuePortImpl::WaitSnapshot snapshot; - port.CaptureWaitSnapshot(snapshot); - auto* reg = snapshot.registrations[0].get(); - auto registry = reg->publicRegistry; - w.unregisterInCallback = true; - w.allowExit = CreateEvent(nullptr, TRUE, FALSE, nullptr); - Check(w.allowExit != nullptr, "exit barrier created"); - // Publish without a native worker so the reference baseline is stable. - port.ProcessWaitCallback(reg); - std::thread dispatch([&] { Check(XTaskQueueDispatch(w.queue, work, 0), "callback dispatched"); }); - Await(w.returned, "self-unregister returned while callback is held"); - Check(registry->Lookup(w.token).PortToken == reg->token, "public token still resolves after self-unregister"); - const auto refs = reg->refs.load(); - std::thread external([&] { - XTaskQueueUnregisterWaiter(w.queue, w.token); - Check(w.leavingCallback.load(), "external caller waited for callback"); - std::lock_guard guard(port.m_lock); - Check(!reg->running, "dispatch recorded physical return before external caller completed"); - }); - AwaitCondition([&] { return reg->refs.load() > refs; }, "external caller acquired retired registration via public token"); - SetEvent(w.allowExit); - dispatch.join(); - external.join(); - Check(!port.m_waits.count(reg->token), "port token retired after callback"); - Check(registry->Lookup(w.token).PortToken == 0, "public token retired after callback"); - CloseHandle(w.allowExit); - } - - static void TwoDispatchers(Waiter& w, bool replace) - { - auto& port = Port(w); - if (!replace) XTaskQueueUnregisterWaiter(w.queue, w.token); - // Drain the setup wake so both callers can stay in the same infinite wait. - Check(!XTaskQueueDispatch(w.queue, work, 0), "no initial work"); - std::atomic deliveries{0}; - auto dispatch = [&] { - if (XTaskQueueDispatch(w.queue, work, INFINITE)) ++deliveries; - }; - std::thread first(dispatch), second(dispatch); - auto awaitPair = [&] { - std::weak_ptr result; - AwaitCondition([&] { - std::lock_guard lock(port.m_lock); - if (port.m_waitEpoch.use_count() != 3) return false; - result = port.m_waitEpoch; - return true; - }, "two real dispatchers own snapshots of the current epoch"); - return result; - }; - auto epoch = awaitPair(); - // Also verify the signal on the exact kernel object. Merely seeing - // both threads return could pass because of unrelated work wakes. - auto oldEpoch = epoch.lock(); - Check(oldEpoch != nullptr, "captured live epoch for both dispatchers"); - auto verifyBroadcast = [&] { - Check(WaitForSingleObject(oldEpoch->handle, 0) == WAIT_OBJECT_0 && - WaitForSingleObject(oldEpoch->handle, 0) == WAIT_OBJECT_0, - "retired epoch stays signaled for late observers"); - oldEpoch.reset(); - }; - Waiter replacement; - if (replace) - { - XTaskQueueUnregisterWaiter(w.queue, w.token); - auto emptyEpoch = awaitPair(); - verifyBroadcast(); - Check(epoch.expired(), "both dispatchers released snapshots containing original waiter"); - oldEpoch = emptyEpoch.lock(); - replacement.queue = w.queue; - replacement.Register(); - epoch = awaitPair(); - verifyBroadcast(); - Check(emptyEpoch.expired(), "both dispatchers captured replacement"); - oldEpoch = epoch.lock(); - port.SuspendPort(); - auto suspendedEpoch = awaitPair(); - verifyBroadcast(); - Check(epoch.expired(), "both dispatchers renewed on suspension"); - epoch = suspendedEpoch; - Check(SetEvent(replacement.signal), "replacement signaled"); - AwaitCondition([&] { return port.m_readyEntries.load() == 1; }, "replacement entry queued while suspended"); - Check(deliveries == 0, "suspended port did not dispatch"); - port.ResumePort(); - AwaitCondition([&] { return deliveries.load() == 1; }, "one dispatcher delivered replacement"); - XTaskQueueUnregisterWaiter(w.queue, replacement.token); - } - Check(SUCCEEDED(XTaskQueueTerminate(w.queue, false, w.returned, - [](void* event) { SetEvent(static_cast(event)); })), "terminate manual port"); - first.join(); - second.join(); - Await(w.returned, "termination completed"); - if (!replace) verifyBroadcast(); - Check(epoch.expired() && w.calls == 0 && replacement.calls == (replace ? 1u : 0u) - && deliveries == replacement.calls, "both infinite waits ended with expected deliveries"); - replacement.CloseEvents(); - } -}; - -int main(int argc, char** argv) -{ - if (argc != 2) return 1; - std::string_view scenario(argv[1]); - PROCESS_MITIGATION_STRICT_HANDLE_CHECK_POLICY strict{}; - strict.RaiseExceptionOnInvalidHandleReference = 1; - strict.HandleExceptionsPermanentlyEnabled = 1; - Check(SetProcessMitigationPolicy(ProcessStrictHandleCheckPolicy, &strict, sizeof(strict)), - "strict Win32 handle checks enabled"); - wchar_t eventName[80]{}; - swprintf_s(eventName, L"Local\\LeonidaWaitRegistration-%lu", GetCurrentProcessId()); - Waiter w(eventName); - w.unregisterInCallback = scenario == "self" || scenario == "presignaled"; - w.unregisterInMonitor = scenario == "monitor"; - w.closeInCallback = scenario == "close"; - w.holdCancellation = scenario == "cancel_unregister"; - Check(SUCCEEDED(XTaskQueueCreate(w.unregisterInCallback || w.closeInCallback ? immediate : manual, - immediate, &w.queue)), "queue created"); - - XTaskQueueRegistrationToken monitor{}; - Check(SUCCEEDED(XTaskQueueRegisterMonitor(w.queue, &w, Monitor, &monitor)), "monitor registered"); - if (scenario == "presignaled") Check(SetEvent(w.signal), "event signaled before registration"); - w.Register(); - - if (w.holdCancellation) - { - HANDLE terminated = CreateEvent(nullptr, TRUE, FALSE, nullptr); - Check(terminated != nullptr, "termination event created"); - std::thread cancel([&] { - Check(SUCCEEDED(XTaskQueueTerminate(w.queue, false, terminated, - [](void* event) { SetEvent(static_cast(event)); })), "termination requested"); - }); - Await(w.published, "canceled entry published"); - XTaskQueueUnregisterWaiter(w.queue, w.token); - SetEvent(w.returned); - cancel.join(); - Check(!XTaskQueueDispatch(w.queue, work, 0), "suppressed canceled delivery"); - Await(terminated, "termination completed after unregister"); - Check(w.calls == 0, "no late canceled callback"); - CloseHandle(terminated); - } - else if (scenario == "held_snapshot") WaitRegistrationTestAccess::HoldSnapshot(w, eventName); - else if (scenario == "admission" || scenario == "reentrant_admission") - WaitRegistrationTestAccess::CheckAdmission(w, scenario == "reentrant_admission"); - else if (scenario == "reentrant_vs_external_unregister") WaitRegistrationTestAccess::ExternalAfterSelf(w); - else if (scenario == "multi_dispatcher_terminate" || scenario == "multi_dispatcher_unregister_replace") - WaitRegistrationTestAccess::TwoDispatchers(w, scenario == "multi_dispatcher_unregister_replace"); - else if (scenario == "cross") - { - Waiter peer; - Check(SUCCEEDED(XTaskQueueCreate(manual, immediate, &peer.queue)), "second manual port"); - peer.Register(); - std::barrier entered(2); - w.bothEntered = peer.bothEntered = &entered; - w.peer = &peer; - peer.peer = &w; - Check(SetEvent(w.signal) && SetEvent(peer.signal), "both waiters signaled"); - std::thread dispatcher([&] { Check(XTaskQueueDispatch(peer.queue, work, 5000), "peer dispatched"); }); - Check(XTaskQueueDispatch(w.queue, work, 5000), "owner dispatched"); - dispatcher.join(); - Await(w.returned, "first cross-unregister returned"); - Await(peer.returned, "second cross-unregister returned"); - Check(w.calls == 1 && peer.calls == 1, "single delivery per waiter"); - XTaskQueueCloseHandle(peer.queue); - peer.CloseEvents(); - } - else if (scenario == "concurrent") - { - Check(SetEvent(w.signal), "waiter signaled"); - Await(w.published, "entry published"); - std::barrier start(2); - auto retire = [&] { - start.arrive_and_wait(); - XTaskQueueUnregisterWaiter(w.queue, w.token); - }; - std::thread other(retire); - retire(); - other.join(); - CloseHandle(w.signal); - w.signal = nullptr; - HANDLE remaining = OpenEventW(SYNCHRONIZE, FALSE, eventName); - Check(!remaining && GetLastError() == ERROR_FILE_NOT_FOUND, "tombstone released event"); - Check(XTaskQueueIsEmpty(w.queue, work), "tombstone logically empty"); - Check(SUCCEEDED(XTaskQueueTerminate(w.queue, false, w.returned, - [](void* event) { SetEvent(static_cast(event)); })), "terminate with tombstone"); - Check(!XTaskQueueDispatch(w.queue, work, 0), "tombstone is not a delivery"); - Await(w.returned, "termination completed"); - Check(w.calls == 0, "suppressed callback stayed suppressed"); - } - else if (scenario == "snapshot") - { - // Exercise both the registration wake and timeout against a live waiter. - for (unsigned i = 0; i != 128; ++i) - if (XTaskQueueDispatch(w.queue, work, 0)) return 1; - Check(w.calls == 0, "polls timed out without delivery"); - XTaskQueueUnregisterWaiter(w.queue, w.token); - CloseHandle(w.signal); - w.signal = nullptr; - HANDLE remaining = OpenEventW(SYNCHRONIZE, FALSE, eventName); - Check(!remaining && GetLastError() == ERROR_FILE_NOT_FOUND, "last handle to snapshot event released"); - } - else if (scenario == "composite") - { - XTaskQueuePortHandle shared{}, completion{}; - Check(SUCCEEDED(XTaskQueueGetPort(w.queue, work, &shared)) && - SUCCEEDED(XTaskQueueGetPort(w.queue, XTaskQueuePort::Completion, &completion)), "ports obtained"); - Waiter sibling; - Check(SUCCEEDED(XTaskQueueCreateComposite(shared, completion, &sibling.queue)), "composite created"); - sibling.Register(); - Check(SUCCEEDED(XTaskQueueTerminate(sibling.queue, false, nullptr, nullptr)), "composite terminating"); - Check(XTaskQueueDispatch(w.queue, work, 0) && sibling.canceled == 1, "composite waiter canceled"); - Check(SetEvent(w.signal) != FALSE, "owner waiter signaled"); - Check(XTaskQueueDispatch(w.queue, work, 5000) && w.calls == 1 && w.canceled == 0, "owner waiter still active"); - XTaskQueueUnregisterWaiter(w.queue, w.token); - XTaskQueueCloseHandle(sibling.queue); - sibling.CloseEvents(); - } - else - { - if (scenario != "parked") - { - if (scenario != "presignaled") - Check(SetEvent(w.signal) != FALSE, "signaled after token publication"); - Await(w.published, "entry published on the work port"); - } - if (scenario == "terminate" || scenario == "parked") - { - Check(SUCCEEDED(XTaskQueueTerminate(w.queue, false, nullptr, nullptr)), "termination initiated"); - Check(XTaskQueueDispatch(w.queue, work, 0), "cancellation dispatched"); - Check(w.calls == 1 && w.canceled == 1, "single canceled callback"); - Check(!XTaskQueueDispatch(w.queue, work, 0), "no second delivery"); - } - else if (w.closeInCallback) - { - Await(w.returned, "last external queue handle closed in callback"); - Check(w.calls == 1, "one callback before rundown"); - } - else if (w.unregisterInCallback || w.unregisterInMonitor) - { - Await(w.returned, "reentrant unregister returned"); - XTaskQueueDispatch(w.queue, work, 0); - Check(w.calls == (w.unregisterInCallback ? 1u : 0u), "expected user callback count"); - } - else if (scenario == "unregister" || scenario == "undispatched") - { - XTaskQueueUnregisterWaiter(w.queue, w.token); - CloseHandle(w.signal); - w.signal = nullptr; - if (scenario == "unregister") XTaskQueueDispatch(w.queue, work, 0); - Check(w.calls == 0, "no user callback after unregister"); - } - else return 1; - } - - if (!w.closeInCallback) - { - XTaskQueueUnregisterMonitor(w.queue, monitor); - XTaskQueueCloseHandle(w.queue); - } - Check(XTaskQueueUninitialize(5000), "all queue and port references released"); - w.CloseEvents(); -#ifdef _DEBUG - Check(_CrtCheckMemory() != 0, "debug CRT heap intact after shutdown"); -#endif - return 0; -} diff --git a/runtime/test/window_station.h b/runtime/test/window_station.h deleted file mode 100644 index e196b94b0..000000000 --- a/runtime/test/window_station.h +++ /dev/null @@ -1,15 +0,0 @@ -// Whether the test runs where windows and outputs exist. From an SSH session or a service the process has a window -// station that is not visible: the host DXGI then answers DXGI_ERROR_NOT_CURRENTLY_AVAILABLE for EnumOutputs and -// CreateSwapChainForHwnd, and a window cannot be shown, so tests that need a desktop skip there. -#pragma once - -#include - -inline bool has_interactive_window_station() { - HWINSTA station = GetProcessWindowStation(); - if (!station) return true; // Unknown environment: let window creation report the real failure. - USEROBJECTFLAGS flags{}; - DWORD bytes = 0; - if (!GetUserObjectInformationW(station, UOI_FLAGS, &flags, sizeof(flags), &bytes)) return true; - return (flags.dwFlags & WSF_VISIBLE) != 0; -} diff --git a/runtime/test/winhttp_offline_test.cpp b/runtime/test/winhttp_offline_test.cpp deleted file mode 100644 index 00ba5326d..000000000 --- a/runtime/test/winhttp_offline_test.cpp +++ /dev/null @@ -1,653 +0,0 @@ -// Checks the offline WinHTTP the shims give a mapped title (runtime/shims/winhttp_offline.cpp). -// -// Every function is resolved through rt::shims::find under winhttp.dll, so the test runs against the table the -// runtime installs. Nothing here touches the network: the server names use the reserved .invalid top-level domain, and -// the only host WinHTTP call the shims make is WinHttpCrackUrl, which parses a string. -#include -#include -#include -#include -#include - -#include -#include -#include -#include -#include - -#include "shims.h" - -namespace { - -using OpenFn = HINTERNET(WINAPI*)(LPCWSTR, DWORD, LPCWSTR, LPCWSTR, DWORD); -using ConnectFn = HINTERNET(WINAPI*)(HINTERNET, LPCWSTR, INTERNET_PORT, DWORD); -using OpenRequestFn = HINTERNET(WINAPI*)(HINTERNET, LPCWSTR, LPCWSTR, LPCWSTR, LPCWSTR, LPCWSTR*, DWORD); -using SendRequestFn = BOOL(WINAPI*)(HINTERNET, LPCWSTR, DWORD, LPVOID, DWORD, DWORD, DWORD_PTR); -using ReceiveResponseFn = BOOL(WINAPI*)(HINTERNET, LPVOID); -using ReadDataFn = BOOL(WINAPI*)(HINTERNET, LPVOID, DWORD, LPDWORD); -using QueryHeadersFn = BOOL(WINAPI*)(HINTERNET, DWORD, LPCWSTR, LPVOID, LPDWORD, LPDWORD); -using AddRequestHeadersFn = BOOL(WINAPI*)(HINTERNET, LPCWSTR, DWORD, DWORD); -using SetTimeoutsFn = BOOL(WINAPI*)(HINTERNET, int, int, int, int); -using SetOptionFn = BOOL(WINAPI*)(HINTERNET, DWORD, LPVOID, DWORD); -using QueryOptionFn = BOOL(WINAPI*)(HINTERNET, DWORD, LPVOID, LPDWORD); -using SetStatusCallbackFn = WINHTTP_STATUS_CALLBACK(WINAPI*)(HINTERNET, WINHTTP_STATUS_CALLBACK, DWORD, DWORD_PTR); -using CloseHandleFn = BOOL(WINAPI*)(HINTERNET); -using CrackUrlFn = BOOL(WINAPI*)(LPCWSTR, DWORD, DWORD, LPURL_COMPONENTS); - -int g_checks = 0; -int g_failures = 0; - -void check(bool condition, const char* what) { - ++g_checks; - std::printf("%s %s\n", condition ? "PASS" : "FAIL", what); - if (!condition) ++g_failures; -} - -template -Fn resolve(const char* name) { - return reinterpret_cast(rt::shims::find("winhttp.dll", name)); -} - -struct StderrCapture { - int saved_fd = -1; - int read_fd = -1; - - StderrCapture() { - std::fflush(stderr); - const int stderr_fd = _fileno(stderr); - int fds[2] = {-1, -1}; - if (stderr_fd < 0 || _pipe(fds, 4096, _O_TEXT) != 0) return; - const int dup_saved = _dup(stderr_fd); - if (dup_saved < 0 || _dup2(fds[1], stderr_fd) != 0) { - if (dup_saved >= 0) _close(dup_saved); - _close(fds[0]); - _close(fds[1]); - return; - } - _close(fds[1]); - saved_fd = dup_saved; - read_fd = fds[0]; - } - - ~StderrCapture() { stop(); } - - std::string stop() { - std::string out; - if (saved_fd >= 0) { - std::fflush(stderr); - _dup2(saved_fd, _fileno(stderr)); - _close(saved_fd); - saved_fd = -1; - } - if (read_fd >= 0) { - char buf[512]; - for (;;) { - const int n = _read(read_fd, buf, static_cast(sizeof(buf))); - if (n <= 0) break; - out.append(buf, static_cast(n)); - } - _close(read_fd); - read_fd = -1; - } - return out; - } -}; - -struct CreatedRequestProbe { - OpenRequestFn open_request = nullptr; - SendRequestFn send = nullptr; - CloseHandleFn close = nullptr; - int created_calls = 0; - HINTERNET created_handle = nullptr; - HINTERNET request_handle = nullptr; - BOOL send_result = TRUE; - DWORD send_error = 0; - BOOL request_closed = FALSE; -}; -CreatedRequestProbe* g_created_probe = nullptr; - -void CALLBACK on_created_send_request(HINTERNET handle, DWORD_PTR, DWORD status, LPVOID, DWORD) { - if (status != WINHTTP_CALLBACK_STATUS_HANDLE_CREATED || !g_created_probe) return; - CreatedRequestProbe& p = *g_created_probe; - if (p.created_calls++ != 0) return; - p.created_handle = handle; - p.request_handle = p.open_request(handle, L"GET", L"/created", nullptr, WINHTTP_NO_REFERER, - WINHTTP_DEFAULT_ACCEPT_TYPES, 0); - if (p.request_handle) { - SetLastError(0); - p.send_result = p.send(p.request_handle, nullptr, 0, nullptr, 0, 0, 0); - p.send_error = GetLastError(); - p.request_closed = p.close(p.request_handle); - } -} - -struct CreatedCloseProbe { - CloseHandleFn close = nullptr; - int created_calls = 0; - int closing_calls = 0; - bool in_created = false; - bool closing_during_created = false; - HINTERNET created_handle = nullptr; - HINTERNET closing_handle = nullptr; - BOOL close_result = FALSE; -}; -CreatedCloseProbe* g_close_probe = nullptr; - -void CALLBACK on_created_close_handle(HINTERNET handle, DWORD_PTR, DWORD status, LPVOID info, DWORD length) { - if (!g_close_probe) return; - CreatedCloseProbe& p = *g_close_probe; - if (status == WINHTTP_CALLBACK_STATUS_HANDLE_CREATED) { - ++p.created_calls; - p.created_handle = handle; - p.in_created = true; - if (p.close) p.close_result = p.close(handle); - p.in_created = false; - } else if (status == WINHTTP_CALLBACK_STATUS_HANDLE_CLOSING && info && length == sizeof(HINTERNET) && - *static_cast(info) == handle) { - if (p.in_created) p.closing_during_created = true; - ++p.closing_calls; - p.closing_handle = handle; - } -} - -// What the status callback saw, for the asynchronous checks. -struct Seen { - std::atomic request_errors{0}; - std::atomic closing{0}; - std::atomic created{0}; - std::atomic api{0}; - std::atomic error{0}; - std::atomic context{0}; - std::atomic thread{0}; - std::atomic closing_after_error{true}; - HANDLE error_event = nullptr; - HANDLE closing_event = nullptr; - CloseHandleFn close_in_callback = nullptr; // when set, the error callback closes the request itself -}; -Seen* g_seen = nullptr; - -void CALLBACK on_status(HINTERNET handle, DWORD_PTR context, DWORD status, LPVOID info, DWORD length) { - Seen& s = *g_seen; - if (status == WINHTTP_CALLBACK_STATUS_HANDLE_CREATED) { - ++s.created; - } else if (status == WINHTTP_CALLBACK_STATUS_REQUEST_ERROR && info && length == sizeof(WINHTTP_ASYNC_RESULT)) { - const auto* result = static_cast(info); - s.api = static_cast(result->dwResult); - s.error = result->dwError; - s.context = context; - s.thread = GetCurrentThreadId(); - ++s.request_errors; - if (s.close_in_callback) s.close_in_callback(handle); - SetEvent(s.error_event); - } else if (status == WINHTTP_CALLBACK_STATUS_HANDLE_CLOSING) { - if (s.request_errors.load() == 0) s.closing_after_error = false; - if (info && length == sizeof(HINTERNET) && *static_cast(info) == handle) ++s.closing; - SetEvent(s.closing_event); - } -} - -double ms_since(std::chrono::steady_clock::time_point start) { - return std::chrono::duration(std::chrono::steady_clock::now() - start).count(); -} - -// HANDLE_CLOSING arrives on the callback thread, so a count read right after WinHttpCloseHandle can be short, and a -// notification that comes late lands in the next block's count (TEST-721). Waits up to two seconds for `n`. -bool wait_for_closing(const Seen& s, int n) { - for (int i = 0; i < 200 && s.closing.load() < n; ++i) Sleep(10); - return s.closing.load() >= n; -} - -} // namespace - -int main() { - const auto open = resolve("WinHttpOpen"); - const auto connect = resolve("WinHttpConnect"); - const auto open_request = resolve("WinHttpOpenRequest"); - const auto send = resolve("WinHttpSendRequest"); - const auto receive = resolve("WinHttpReceiveResponse"); - const auto read = resolve("WinHttpReadData"); - const auto query_headers = resolve("WinHttpQueryHeaders"); - const auto add_headers = resolve("WinHttpAddRequestHeaders"); - const auto set_timeouts = resolve("WinHttpSetTimeouts"); - const auto set_option = resolve("WinHttpSetOption"); - const auto query_option = resolve("WinHttpQueryOption"); - const auto set_callback = resolve("WinHttpSetStatusCallback"); - const auto close = resolve("WinHttpCloseHandle"); - const auto crack = resolve("WinHttpCrackUrl"); - check(open && connect && open_request && send && receive && read && query_headers && add_headers && - set_timeouts && set_option && query_option && set_callback && close && crack && - rt::shims::find("winhttp.dll", "WinHttpQueryDataAvailable") && - rt::shims::find("winhttp.dll", "WinHttpWriteData"), - "all 16 WinHTTP imports of the package resolve through the registry"); - check(rt::shims::owns_dll("winhttp.dll"), "winhttp.dll is a module the shims own (LoadLibrary gets a pseudo-handle)"); - if (!(open && connect && open_request && send && close && set_callback)) { - std::printf("%d check(s), %d failure(s)\n", g_checks, g_failures + 1); - return 1; - } - - // Synchronous: the send fails at once, nothing is resolved or connected. - { - const HINTERNET session = open(L"test", WINHTTP_ACCESS_TYPE_NO_PROXY, nullptr, nullptr, 0); - check(session != nullptr, "WinHttpOpen returns a session"); - const HINTERNET connection = connect(session, L"example.invalid", INTERNET_DEFAULT_HTTPS_PORT, 0); - check(connection != nullptr, "WinHttpConnect returns a connection without resolving the name"); - const HINTERNET request = - open_request(connection, L"GET", L"/x", nullptr, WINHTTP_NO_REFERER, WINHTTP_DEFAULT_ACCEPT_TYPES, - WINHTTP_FLAG_SECURE); - check(request != nullptr, "WinHttpOpenRequest returns a request"); - check(add_headers(request, L"X-Test: 1", static_cast(-1), WINHTTP_ADDREQ_FLAG_ADD) != FALSE, - "request headers are accepted"); - check(set_timeouts(request, 1000, 1000, 1000, 1000) != FALSE, "timeouts are accepted"); - - // The same answers the host's winhttp.dll gives (measured on Windows 11 26300). - const auto rejects = [](BOOL ok) { return ok == FALSE && GetLastError() == ERROR_INVALID_PARAMETER; }; - SetLastError(0); - check(rejects(add_headers(request, nullptr, 0, WINHTTP_ADDREQ_FLAG_ADD)), "a null header block is rejected"); - SetLastError(0); - check(rejects(add_headers(request, L"", static_cast(-1), WINHTTP_ADDREQ_FLAG_ADD)), - "an empty header block is rejected"); - SetLastError(0); - check(rejects(add_headers(request, L"nocolon", static_cast(-1), WINHTTP_ADDREQ_FLAG_ADD)), - "a header with no colon is rejected"); - SetLastError(0); - check(rejects(add_headers(request, L"X-C: b", 2, WINHTTP_ADDREQ_FLAG_ADD)), - "a length that cuts the header before its colon is rejected"); - check(add_headers(request, L"X-D: b", 6, WINHTTP_ADDREQ_FLAG_ADD) != FALSE, - "an explicit length that covers the colon is accepted"); - check(add_headers(request, L"X-A: 1\r\nX-B: 2\r\n", static_cast(-1), WINHTTP_ADDREQ_FLAG_ADD) != FALSE, - "a multi-line header block with valid lines is accepted"); - SetLastError(0); - check(rejects(add_headers(request, L"X-A: 1\r\nbadline\r\n", static_cast(-1), WINHTTP_ADDREQ_FLAG_ADD)), - "a multi-line header block with a colon-less line is rejected"); - SetLastError(0); - check(rejects(add_headers(request, L": v", static_cast(-1), WINHTTP_ADDREQ_FLAG_ADD)), - "a header with an empty name is rejected"); - SetLastError(0); - check(rejects(add_headers(request, L"X A: 1", static_cast(-1), WINHTTP_ADDREQ_FLAG_ADD)), - "a header with a space in its name is rejected"); - SetLastError(0); - check(rejects(add_headers(request, L"X;Y: 1", static_cast(-1), WINHTTP_ADDREQ_FLAG_ADD)), - "a header with a token separator in its name is rejected"); - SetLastError(0); - check(rejects(add_headers(request, L"X\u00e9: 1", static_cast(-1), WINHTTP_ADDREQ_FLAG_ADD)), - "a header with a non-ASCII character in its name is rejected"); - check(add_headers(request, L"\r\n", static_cast(-1), WINHTTP_ADDREQ_FLAG_ADD) != FALSE && - add_headers(request, L"\r\n\r\n", static_cast(-1), WINHTTP_ADDREQ_FLAG_ADD) != FALSE, - "blank-lines-only header blocks are accepted (matching host winhttp.dll)"); - check(set_timeouts(session, 1000, 1000, 1000, 1000) != FALSE, "timeouts on a session handle are accepted"); - SetLastError(0); - check(set_timeouts(connection, 1000, 1000, 1000, 1000) == FALSE && - GetLastError() == ERROR_WINHTTP_INCORRECT_HANDLE_TYPE, - "timeouts on a connect handle fail with ERROR_WINHTTP_INCORRECT_HANDLE_TYPE"); - check(set_timeouts(request, 0, 0, 0, 0) != FALSE && set_timeouts(request, -1, -1, -1, -1) != FALSE, - "timeouts of 0 and -1 (infinite) are accepted"); - for (int field = 0; field < 4; ++field) { - int t[4] = {0, 0, 0, 0}; - t[field] = -2; - SetLastError(0); - check(rejects(set_timeouts(request, t[0], t[1], t[2], t[3])), "a timeout below -1 is rejected"); - } - - SetLastError(0); - const auto start = std::chrono::steady_clock::now(); - const BOOL sent = send(request, WINHTTP_NO_ADDITIONAL_HEADERS, 0, WINHTTP_NO_REQUEST_DATA, 0, 0, 0); - const DWORD error = GetLastError(); - const double elapsed = ms_since(start); - check(sent == FALSE && error == ERROR_WINHTTP_CANNOT_CONNECT, - "WinHttpSendRequest fails with ERROR_WINHTTP_CANNOT_CONNECT"); - check(elapsed < 50.0, "and fails at once (under 50 ms)"); - SetLastError(0); - check(receive(request, nullptr) == FALSE && GetLastError() == ERROR_WINHTTP_INCORRECT_HANDLE_STATE, - "there is no response to receive"); - char buffer[16]; - DWORD got = 0; - SetLastError(0); - check(read(request, buffer, sizeof(buffer), &got) == FALSE && - GetLastError() == ERROR_WINHTTP_INCORRECT_HANDLE_STATE, - "and nothing to read"); - DWORD status = 0, size = sizeof(status); - SetLastError(0); - check(query_headers(request, WINHTTP_QUERY_STATUS_CODE | WINHTTP_QUERY_FLAG_NUMBER, WINHTTP_HEADER_NAME_BY_INDEX, - &status, &size, WINHTTP_NO_HEADER_INDEX) == FALSE && - GetLastError() == ERROR_WINHTTP_INCORRECT_HANDLE_STATE, - "and no status code"); - - // Options: the context value round-trips, the handle type is answered, the rest is refused when queried. - DWORD_PTR value = 0x1234; - check(set_option(request, WINHTTP_OPTION_CONTEXT_VALUE, &value, sizeof(value)) != FALSE, - "WINHTTP_OPTION_CONTEXT_VALUE can be set"); - DWORD_PTR back = 0; - DWORD back_size = sizeof(back); - check(query_option(request, WINHTTP_OPTION_CONTEXT_VALUE, &back, &back_size) != FALSE && back == 0x1234, - "and queried back"); - DWORD type = 0, type_size = sizeof(type); - check(query_option(connection, WINHTTP_OPTION_HANDLE_TYPE, &type, &type_size) != FALSE && - type == WINHTTP_HANDLE_TYPE_CONNECT, - "WINHTTP_OPTION_HANDLE_TYPE names a connection"); - DWORD needed = 0; - SetLastError(0); - check(query_option(request, WINHTTP_OPTION_CONTEXT_VALUE, nullptr, &needed) == FALSE && - GetLastError() == ERROR_INSUFFICIENT_BUFFER && needed == sizeof(DWORD_PTR), - "a query without a buffer reports the size it needs"); - DWORD flags = 0, flags_size = sizeof(flags); - SetLastError(0); - check(query_option(request, WINHTTP_OPTION_SECURITY_FLAGS, &flags, &flags_size) == FALSE && - GetLastError() == ERROR_WINHTTP_INVALID_OPTION, - "other options are not answered"); - DWORD protocols = WINHTTP_FLAG_SECURE_PROTOCOL_TLS1_2; - check(set_option(session, WINHTTP_OPTION_SECURE_PROTOCOLS, &protocols, sizeof(protocols)) != FALSE, - "but setting them is accepted"); - DWORD short_ctx = 0x1234; - SetLastError(0); - check(set_option(request, WINHTTP_OPTION_CONTEXT_VALUE, &short_ctx, sizeof(short_ctx)) == FALSE && - GetLastError() == ERROR_INSUFFICIENT_BUFFER, - "a 4-byte WINHTTP_OPTION_CONTEXT_VALUE fails with ERROR_INSUFFICIENT_BUFFER"); - SetLastError(0); - check(set_option(nullptr, WINHTTP_OPTION_CONTEXT_VALUE, &value, sizeof(value)) == FALSE && - GetLastError() == ERROR_WINHTTP_INCORRECT_HANDLE_TYPE, - "WINHTTP_OPTION_CONTEXT_VALUE on a NULL handle fails with ERROR_WINHTTP_INCORRECT_HANDLE_TYPE"); - SetLastError(0); - check(set_callback(nullptr, &on_status, WINHTTP_CALLBACK_FLAG_ALL_NOTIFICATIONS, 0) == - WINHTTP_INVALID_STATUS_CALLBACK && - GetLastError() == ERROR_WINHTTP_INCORRECT_HANDLE_TYPE, - "WinHttpSetStatusCallback on a NULL handle fails with ERROR_WINHTTP_INCORRECT_HANDLE_TYPE"); - - // Wrong handles. - SetLastError(0); - check(connect(request, L"example.invalid", 80, 0) == nullptr && - GetLastError() == ERROR_WINHTTP_INCORRECT_HANDLE_TYPE, - "a request is not a session"); - SetLastError(0); - check(send(connection, nullptr, 0, nullptr, 0, 0, 0) == FALSE && - GetLastError() == ERROR_WINHTTP_INCORRECT_HANDLE_TYPE, - "a connection is not a request"); - SetLastError(0); - check(connect(session, nullptr, 80, 0) == nullptr && GetLastError() == ERROR_INVALID_PARAMETER, - "a connection needs a server name"); - - check(close(request) != FALSE && close(connection) != FALSE && close(session) != FALSE, - "the handles close, children first"); - SetLastError(0); - check(close(request) == FALSE && GetLastError() == ERROR_INVALID_HANDLE, "a closed handle is gone"); - SetLastError(0); - check(send(request, nullptr, 0, nullptr, 0, 0, 0) == FALSE && GetLastError() == ERROR_INVALID_HANDLE, - "and cannot be used"); - } - - // WinHttpSendRequest's dwContext of 0 leaves the context set with WINHTTP_OPTION_CONTEXT_VALUE in place. The - // host's winhttp.dll (Windows 11, asynchronous session, loopback) kept it for WinHttpQueryOption, for the - // REQUEST_ERROR callback and for HANDLE_CLOSING. - { - static std::atomic error_context{0}; - static std::atomic closing_context{0}; - static HANDLE error_event = CreateEventW(nullptr, FALSE, FALSE, nullptr); - static HANDLE closing_event = CreateEventW(nullptr, FALSE, FALSE, nullptr); - const WINHTTP_STATUS_CALLBACK record = [](HINTERNET, DWORD_PTR context, DWORD status, LPVOID, DWORD) { - if (status == WINHTTP_CALLBACK_STATUS_REQUEST_ERROR) { - error_context = context; - SetEvent(error_event); - } else if (status == WINHTTP_CALLBACK_STATUS_HANDLE_CLOSING) { - closing_context = context; - SetEvent(closing_event); - } - }; - const auto context_of = [&](HINTERNET handle) -> DWORD_PTR { - DWORD_PTR value = ~DWORD_PTR{0}; - DWORD size = sizeof(value); - return query_option(handle, WINHTTP_OPTION_CONTEXT_VALUE, &value, &size) ? value : ~DWORD_PTR{0}; - }; - - // Synchronous: the send fails at once, and the context is still the one the option set. - const HINTERNET sync_session = open(L"test", WINHTTP_ACCESS_TYPE_NO_PROXY, nullptr, nullptr, 0); - const HINTERNET sync_connection = connect(sync_session, L"example.invalid", 80, 0); - const HINTERNET sync_request = open_request(sync_connection, L"GET", L"/c", nullptr, WINHTTP_NO_REFERER, - WINHTTP_DEFAULT_ACCEPT_TYPES, 0); - DWORD_PTR value = 0xBBB; - set_option(sync_request, WINHTTP_OPTION_CONTEXT_VALUE, &value, sizeof(value)); - send(sync_request, nullptr, 0, nullptr, 0, 0, 0); - check(context_of(sync_request) == 0xBBB, "a synchronous send with context 0 keeps the option's context"); - close(sync_request); - close(sync_connection); - close(sync_session); - - // Asynchronous: the error callback and HANDLE_CLOSING carry it too. - const HINTERNET session = open(L"test", WINHTTP_ACCESS_TYPE_NO_PROXY, nullptr, nullptr, WINHTTP_FLAG_ASYNC); - const HINTERNET connection = connect(session, L"example.invalid", 80, 0); - const HINTERNET request = open_request(connection, L"GET", L"/c", nullptr, WINHTTP_NO_REFERER, - WINHTTP_DEFAULT_ACCEPT_TYPES, 0); - set_callback(request, record, WINHTTP_CALLBACK_FLAG_REQUEST_ERROR | WINHTTP_CALLBACK_FLAG_HANDLES, 0); - value = 0xCCC; - set_option(request, WINHTTP_OPTION_CONTEXT_VALUE, &value, sizeof(value)); - check(send(request, nullptr, 0, nullptr, 0, 0, 0) != FALSE && - WaitForSingleObject(error_event, 2000) == WAIT_OBJECT_0 && error_context.load() == 0xCCC, - "an asynchronous send with context 0 reports its error with the option's context"); - check(context_of(request) == 0xCCC, "and WinHttpQueryOption still returns it"); - close(request); - check(WaitForSingleObject(closing_event, 2000) == WAIT_OBJECT_0 && closing_context.load() == 0xCCC, - "HANDLE_CLOSING carries it as well"); - close(connection); - close(session); - } - - // Asynchronous: the send returns TRUE, the failure arrives through the inherited callback on another thread with - // the request's context, and HANDLE_CLOSING comes last. - Seen seen; - seen.error_event = CreateEventW(nullptr, FALSE, FALSE, nullptr); - seen.closing_event = CreateEventW(nullptr, FALSE, FALSE, nullptr); - g_seen = &seen; - { - const HINTERNET session = open(L"test", WINHTTP_ACCESS_TYPE_NO_PROXY, nullptr, nullptr, WINHTTP_FLAG_ASYNC); - check(set_callback(session, &on_status, WINHTTP_CALLBACK_FLAG_ALL_NOTIFICATIONS, 0) == nullptr, - "WinHttpSetStatusCallback returns the previous callback (none)"); - const HINTERNET connection = connect(session, L"example.invalid", 443, 0); - const HINTERNET request = open_request(connection, L"POST", L"/y", nullptr, WINHTTP_NO_REFERER, - WINHTTP_DEFAULT_ACCEPT_TYPES, WINHTTP_FLAG_SECURE); - check(connection && request && seen.created.load() == 2, - "the callback is inherited and reports both new handles as created"); - - const auto start = std::chrono::steady_clock::now(); - const BOOL sent = send(request, WINHTTP_NO_ADDITIONAL_HEADERS, 0, WINHTTP_NO_REQUEST_DATA, 0, 0, 0xC0FFEE); - check(sent != FALSE, "an asynchronous WinHttpSendRequest returns TRUE"); - const bool fired = WaitForSingleObject(seen.error_event, 2000) == WAIT_OBJECT_0; - const double elapsed = ms_since(start); - check(fired && seen.request_errors.load() == 1, "WINHTTP_CALLBACK_STATUS_REQUEST_ERROR arrives once"); - check(seen.api.load() == API_SEND_REQUEST && seen.error.load() == ERROR_WINHTTP_CANNOT_CONNECT, - "for API_SEND_REQUEST with ERROR_WINHTTP_CANNOT_CONNECT"); - check(seen.context.load() == 0xC0FFEE, "with the context the request was sent with"); - check(seen.thread.load() != GetCurrentThreadId(), "on another thread"); - check(elapsed < 500.0, "within 500 ms"); - - check(close(request) != FALSE, "the request closes"); - check(WaitForSingleObject(seen.closing_event, 2000) == WAIT_OBJECT_0 && seen.closing.load() == 1 && - seen.closing_after_error.load(), - "and HANDLE_CLOSING follows once, after the error"); - close(connection); - close(session); - check(wait_for_closing(seen, 3) && seen.closing.load() == 3, "every handle reports HANDLE_CLOSING once"); - } - - // A callback that closes its request while handling the error, as libHttpClient-style code does. - { - seen.request_errors = 0; - seen.closing = 0; - seen.close_in_callback = close; - ResetEvent(seen.closing_event); - const HINTERNET session = open(L"test", WINHTTP_ACCESS_TYPE_NO_PROXY, nullptr, nullptr, WINHTTP_FLAG_ASYNC); - set_callback(session, &on_status, WINHTTP_CALLBACK_FLAG_ALL_NOTIFICATIONS, 0); - const HINTERNET connection = connect(session, L"example.invalid", 443, 0); - const HINTERNET request = open_request(connection, L"GET", L"/z", nullptr, WINHTTP_NO_REFERER, - WINHTTP_DEFAULT_ACCEPT_TYPES, 0); - check(send(request, nullptr, 0, nullptr, 0, 0, 7) != FALSE, "a second asynchronous send is queued"); - check(WaitForSingleObject(seen.error_event, 2000) == WAIT_OBJECT_0, "its error arrives"); - check(WaitForSingleObject(seen.closing_event, 2000) == WAIT_OBJECT_0 && seen.closing.load() == 1, - "closing the request inside the callback reports HANDLE_CLOSING once"); - seen.close_in_callback = nullptr; - close(connection); - close(session); - check(wait_for_closing(seen, 3) && seen.closing.load() == 3, - "the connection and the session report HANDLE_CLOSING before the next block counts its own"); - } - - // A request closed before its queued failure is delivered gets no error callback, only HANDLE_CLOSING. - { - seen.request_errors = 0; - seen.closing = 0; - const HINTERNET session = open(L"test", WINHTTP_ACCESS_TYPE_NO_PROXY, nullptr, nullptr, WINHTTP_FLAG_ASYNC); - set_callback(session, &on_status, WINHTTP_CALLBACK_FLAG_HANDLES, 0); // closing only - const HINTERNET connection = connect(session, L"example.invalid", 443, 0); - const HINTERNET request = open_request(connection, L"GET", L"/w", nullptr, WINHTTP_NO_REFERER, - WINHTTP_DEFAULT_ACCEPT_TYPES, 0); - send(request, nullptr, 0, nullptr, 0, 0, 0); - close(request); - close(connection); - close(session); - for (int i = 0; i < 100 && seen.closing.load() < 3; ++i) Sleep(10); - check(seen.request_errors.load() == 0 && seen.closing.load() == 3, - "notifications not asked for are not sent, and each handle still closes once"); - } - g_seen = nullptr; - CloseHandle(seen.error_event); - CloseHandle(seen.closing_event); - - // WINHTTP_OPTION_CONTEXT_VALUE is inherited like the callback: a handle starts with the context its parent has - // when it is created, and keeps it when the parent's changes later. The host's winhttp.dll gave these values. - { - struct Event { - HINTERNET handle; - DWORD status; - DWORD_PTR context; - }; - // The contexts are arbitrary and distinct. kNoContext is what the helpers return when there is no value. - constexpr DWORD_PTR kSessionContext = 7; - constexpr DWORD_PTR kRequestContext = 9; - constexpr DWORD_PTR kLaterSessionContext = 11; - constexpr DWORD_PTR kSendContext = 0x51; - constexpr DWORD_PTR kNoContext = ~DWORD_PTR{0}; - static std::vector events; // a synchronous session: every callback runs on this thread - events.clear(); - const WINHTTP_STATUS_CALLBACK record = [](HINTERNET handle, DWORD_PTR context, DWORD status, LPVOID, DWORD) { - events.push_back({handle, status, context}); - }; - const auto context_of = [&](HINTERNET handle) -> DWORD_PTR { - DWORD_PTR value = kNoContext; - DWORD size = sizeof(value); - return query_option(handle, WINHTTP_OPTION_CONTEXT_VALUE, &value, &size) ? value : kNoContext; - }; - const auto set_context = [&](HINTERNET handle, DWORD_PTR value) { - return set_option(handle, WINHTTP_OPTION_CONTEXT_VALUE, &value, sizeof(value)) != FALSE; - }; - const auto context_at = [&](HINTERNET handle, DWORD status) -> DWORD_PTR { - for (const Event& e : events) - if (e.handle == handle && e.status == status) return e.context; - return kNoContext; - }; - - const HINTERNET session = open(L"test", WINHTTP_ACCESS_TYPE_NO_PROXY, nullptr, nullptr, 0); - set_callback(session, record, WINHTTP_CALLBACK_FLAG_HANDLES, 0); - check(set_context(session, kSessionContext), "WINHTTP_OPTION_CONTEXT_VALUE can be set on a session"); - const HINTERNET connection = connect(session, L"127.0.0.1", 1, 0); - const HINTERNET request = open_request(connection, L"GET", L"/", nullptr, WINHTTP_NO_REFERER, - WINHTTP_DEFAULT_ACCEPT_TYPES, 0); - check(context_of(connection) == kSessionContext && context_of(request) == kSessionContext, - "a connection and a request start with the session's context"); - check(context_at(connection, WINHTTP_CALLBACK_STATUS_HANDLE_CREATED) == kSessionContext && - context_at(request, WINHTTP_CALLBACK_STATUS_HANDLE_CREATED) == kSessionContext, - "and their HANDLE_CREATED callbacks carry it"); - - check(set_context(request, kRequestContext) && context_of(request) == kRequestContext && - context_of(connection) == kSessionContext, - "a context set on the request replaces the inherited one for that request only"); - check(set_context(session, kLaterSessionContext) && context_of(connection) == kSessionContext && - context_of(request) == kRequestContext, - "a context set on the session later does not change handles that exist"); - const HINTERNET late = connect(session, L"127.0.0.1", 1, 0); - check(context_of(late) == kLaterSessionContext, "a connection made after that starts with the new one"); - - const HINTERNET sent = open_request(connection, L"GET", L"/", nullptr, WINHTTP_NO_REFERER, - WINHTTP_DEFAULT_ACCEPT_TYPES, 0); - check(context_of(sent) == kSessionContext, - "a request starts with its connection's context, not the session's"); - send(sent, WINHTTP_NO_ADDITIONAL_HEADERS, 0, WINHTTP_NO_REQUEST_DATA, 0, 0, kSendContext); - check(context_of(sent) == kSendContext, - "the context WinHttpSendRequest is given replaces the inherited one"); - - close(sent); - close(request); - close(late); - close(connection); - close(session); - check(context_at(sent, WINHTTP_CALLBACK_STATUS_HANDLE_CLOSING) == kSendContext && - context_at(request, WINHTTP_CALLBACK_STATUS_HANDLE_CLOSING) == kRequestContext && - context_at(late, WINHTTP_CALLBACK_STATUS_HANDLE_CLOSING) == kLaterSessionContext && - context_at(connection, WINHTTP_CALLBACK_STATUS_HANDLE_CLOSING) == kSessionContext, - "HANDLE_CLOSING carries each handle's own context"); - } - - // WinHttpCrackUrl is parsing only and stays the host's. - { - wchar_t host[64] = {}, path[64] = {}; - URL_COMPONENTS parts{}; - parts.dwStructSize = sizeof(parts); - parts.lpszHostName = host; - parts.dwHostNameLength = 64; - parts.lpszUrlPath = path; - parts.dwUrlPathLength = 64; - check(crack(L"https://example.invalid:8443/a/b", 0, 0, &parts) != FALSE && parts.nPort == 8443 && - parts.nScheme == INTERNET_SCHEME_HTTPS && std::wcscmp(host, L"example.invalid") == 0 && - std::wcscmp(path, L"/a/b") == 0, - "WinHttpCrackUrl parses a URL"); - } - - // Sending a request from inside HANDLE_CREATED must see the connection's server and port already initialized. - { - CreatedRequestProbe probe{open_request, send, close}; - g_created_probe = &probe; - const HINTERNET session = open(L"test", WINHTTP_ACCESS_TYPE_NO_PROXY, nullptr, nullptr, 0); - check(set_callback(session, &on_created_send_request, WINHTTP_CALLBACK_FLAG_HANDLES, 0) == nullptr, - "HANDLE_CREATED probe callback registers"); - StderrCapture capture; - const HINTERNET connection = connect(session, L"created-cb.invalid", 8443, 0); - const std::string logged = capture.stop(); - g_created_probe = nullptr; - check(connection != nullptr && probe.created_handle == connection && probe.request_handle != nullptr && - probe.send_result == FALSE && probe.send_error == ERROR_WINHTTP_CANNOT_CONNECT && - probe.request_closed != FALSE, - "request sent during connection HANDLE_CREATED fails with ERROR_WINHTTP_CANNOT_CONNECT"); - check(logged.find("[rt] winhttp: offline, refused created-cb.invalid:8443") != std::string::npos && - logged.find("[rt] winhttp: offline, refused :0") == std::string::npos, - "refused-server log inside HANDLE_CREATED records server:port instead of :0"); - close(connection); - close(session); - } - - // Closing the connection handle inside HANDLE_CREATED must not trigger a use-after-free, must report - // HANDLE_CLOSING after HANDLE_CREATED returns, and must fail WinHttpConnect with ERROR_WINHTTP_OPERATION_CANCELLED - // (measured against the host's winhttp.dll on Windows 11 26200). - { - CreatedCloseProbe probe{close}; - g_close_probe = &probe; - const HINTERNET session = open(L"test", WINHTTP_ACCESS_TYPE_NO_PROXY, nullptr, nullptr, 0); - check(set_callback(session, &on_created_close_handle, WINHTTP_CALLBACK_FLAG_HANDLES, 0) == nullptr, - "HANDLE_CREATED close callback registers"); - SetLastError(0); - const HINTERNET connection = connect(session, L"closed-in-handle-created-callback-long-host.invalid", 8443, 0); - const DWORD connect_error = GetLastError(); - g_close_probe = nullptr; - check(connection == nullptr && connect_error == ERROR_WINHTTP_OPERATION_CANCELLED && - probe.created_calls == 1 && probe.created_handle != nullptr && probe.close_result != FALSE && - !probe.closing_during_created && probe.closing_calls == 1 && - probe.closing_handle == probe.created_handle, - "closing connection handle inside HANDLE_CREATED reports HANDLE_CLOSING after HANDLE_CREATED and fails with ERROR_WINHTTP_OPERATION_CANCELLED"); - SetLastError(0); - check(close(probe.created_handle) == FALSE && GetLastError() == ERROR_INVALID_HANDLE, - "connection handle closed inside HANDLE_CREATED is already invalid after WinHttpConnect returns"); - g_close_probe = &probe; - const BOOL session_closed = close(session); - g_close_probe = nullptr; - check(session_closed != FALSE && probe.closing_calls == 2 && probe.closing_handle == session, - "closing session afterwards drops the last reference and reports HANDLE_CLOSING once"); - } - - std::printf("%d check(s), %d failure(s)\n", g_checks, g_failures); - return g_failures == 0 ? 0 : 1; -} diff --git a/runtime/test/xapu_chad_test.cpp b/runtime/test/xapu_chad_test.cpp deleted file mode 100644 index dffa74404..000000000 --- a/runtime/test/xapu_chad_test.cpp +++ /dev/null @@ -1,111 +0,0 @@ -// Checks the registered xapu.dll and chad.dll shims in the call shapes the executable uses (runtime/shims/xapu_chad.cpp): -// the connections succeed, the APU's shared buffer is zeroed and writable at the offsets the title reaches, commands -// are accepted, an open and a close each give one result and nothing else does, XDspActivate hands out zeroed status -// and stream memory, and both disconnect. -#include - -#include -#include -#include - -#include "shims.h" - -namespace { - -using XApuConnectFn = HRESULT(__stdcall*)(void*, void*, void**); -using XApuDisconnectFn = HRESULT(__stdcall*)(void*); -using XApuEnqueueCommandFn = HRESULT(__stdcall*)(void*, const uint32_t*, uint64_t); -using XApuGetResultCountFn = uint32_t(__stdcall*)(void*, uint64_t); -using XApuDequeueResultFn = HRESULT(__stdcall*)(void*, void*); -using XDspConnectFn = HRESULT(__stdcall*)(void*, uint32_t, uint32_t, uint32_t, uint32_t, void**); -using XDspActivateFn = HRESULT(__stdcall*)(void*, const void*, void**, void**); -using XDspDeactivateFn = HRESULT(__stdcall*)(void*, uint64_t, uint64_t, uint64_t); -using XDspDisconnectFn = HRESULT(__stdcall*)(void*); -using XDspSubmitCommandFn = HRESULT(__stdcall*)(void*, void*, uint32_t*); - -int g_checks = 0; -int g_failures = 0; - -void check(bool condition, const char* what) { - ++g_checks; - std::printf("%s %s\n", condition ? "PASS" : "FAIL", what); - if (!condition) ++g_failures; -} - -template -T get(const char* dll, const char* name) { - void* fn = rt::shims::find(dll, name); - check(fn != nullptr, name); - return reinterpret_cast(fn); -} - -} // namespace - -int main() { - std::printf("xapu_chad_test: registered xapu.dll and chad.dll shims\n"); - const auto connect = get("xapu.dll", "XApuConnect"); - const auto disconnect = get("xapu.dll", "XApuDisconnect"); - const auto enqueue = get("xapu.dll", "XApuEnqueueCommand"); - const auto count = get("xapu.dll", "XApuGetResultCount"); - const auto dequeue = get("xapu.dll", "XApuDequeueResult"); - const auto dsp_connect = get("chad.dll", "XDspConnectWithMaximumStreamLimit"); - const auto dsp_activate = get("chad.dll", "XDspActivate"); - const auto dsp_deactivate = get("chad.dll", "XDspDeactivate"); - const auto dsp_disconnect = get("chad.dll", "XDspDisconnect"); - const auto dsp_submit = get("chad.dll", "XDspSubmitCommand"); - check(rt::shims::owns_dll("xapu.dll") && rt::shims::owns_dll("chad.dll"), "the shims own xapu.dll and chad.dll"); - if (g_failures) return 1; - - // XApuConnect(block24*, out16*, handle*), success read as SUCCEEDED. - uint8_t out24[24]; - uint64_t out16[2] = {}; - std::memset(out24, 0xcc, sizeof out24); - void* apu = nullptr; - check(SUCCEEDED(connect(out24, out16, &apu)) && apu, "XApuConnect succeeds with a handle"); - check(out24[0] == 0xcc && out24[23] == 0xcc, "XApuConnect leaves the title's 24-byte block alone"); - auto* base = reinterpret_cast(out16[0]); - check(base != nullptr && out16[1] >= 0x14000 + 128 * 0x1E00, "XApuConnect returns the shared buffer and its size"); - if (base) { - const size_t last_output = 0x14000 + 127 * 0x1E00 + 0x1E00 - 1; // the end of slot 127's output - check(base[0] == 0 && base[last_output] == 0, "the shared buffer is zeroed"); - base[127 * 0x280] = 1; - base[last_output] = 1; - check(base[127 * 0x280] == 1 && base[last_output] == 1, "the shared buffer is writable at slot 127"); - } - check(connect(out24, out16, nullptr) == E_INVALIDARG, "XApuConnect without a handle pointer fails"); - - // Command types 1, 2 and 3 as the title builds them; the third argument is 0 at every site. - for (uint32_t type = 1; type <= 3; ++type) { - uint32_t command[16] = {type, 5}; - check(enqueue(apu, command, 0) == S_OK, "XApuEnqueueCommand accepts a command"); - } - check(count(apu, 0) == 2, "the open and the close each queued a result, the type 3 command none"); - for (uint32_t type = 1; type <= 2; ++type) { - uint32_t queued[0x50 / 4] = {}; - check(dequeue(apu, queued) == S_OK && queued[0] == type && queued[1] == 5 && queued[2] == 0 && queued[13] == 0, - "XApuDequeueResult returns the type and slot and leaves the rest zeroed"); - } - check(count(apu, 0) == 0, "XApuGetResultCount is 0 again"); - uint8_t result[0x50] = {}; - check(FAILED(dequeue(apu, result)), "XApuDequeueResult on the empty queue fails"); - check(disconnect(apu) == S_OK, "XApuDisconnect succeeds"); - - // XDspConnectWithMaximumStreamLimit(buffer, u32, u32, 0x80, 1, handle*), success read as a return of 0. - alignas(64) static uint8_t dsp_buffer[4096]; - void* dsp = nullptr; - check(dsp_connect(dsp_buffer, 0, 0, 0x80, 1, &dsp) == 0 && dsp, "XDspConnectWithMaximumStreamLimit returns 0 and a handle"); - const uint8_t description[0x1c] = {}; - uint32_t* status = nullptr; - void* stream = nullptr; - check(dsp_activate(dsp, description, reinterpret_cast(&status), &stream) == 0, "XDspActivate returns 0"); - check(status && stream && static_cast(status) != stream, "XDspActivate writes both outputs"); - uint32_t id = 0; - check(dsp_submit(stream, dsp_buffer, &id) == 0, "XDspSubmitCommand returns 0"); - // What the title's wait reads: no error at +0xc and the submitted id at +4. - check(status && status[3] == 0 && status[1] == id, "the status block reports the submitted command as done"); - check(dsp_deactivate(dsp, 0, 0, 0) == 0, "XDspDeactivate returns 0"); - check(dsp_disconnect(dsp) == 0, "XDspDisconnect returns 0"); - - std::printf("%d checks, %d failures\n", g_checks, g_failures); - return g_failures ? 1 : 0; -} diff --git a/runtime/test/xbox_present_readback_size.h b/runtime/test/xbox_present_readback_size.h deleted file mode 100644 index 6a33ca875..000000000 --- a/runtime/test/xbox_present_readback_size.h +++ /dev/null @@ -1,16 +0,0 @@ -#pragma once - -#include -#include - -inline bool xbox_present_readback_size_matches(std::size_t bytes, std::uint32_t width, - std::uint32_t height, std::uint32_t expected_width, - std::uint32_t expected_height) { - const std::size_t pixels = bytes / 4; - if (width == 0 || height == 0 || bytes % 4 != 0 || - pixels / width != height || pixels % width != 0) - return false; - - // A resize may still produce a complete frame at the previous extent. - return expected_width == 0 || (width == expected_width && height == expected_height); -} diff --git a/runtime/test/xbox_present_readback_size_test.cpp b/runtime/test/xbox_present_readback_size_test.cpp deleted file mode 100644 index 974e81dc6..000000000 --- a/runtime/test/xbox_present_readback_size_test.cpp +++ /dev/null @@ -1,25 +0,0 @@ -#include "xbox_present_readback_size.h" - -#include -#include - -#define EXPECT(condition) do { \ - if (!(condition)) { std::fprintf(stderr, "line %d: %s\n", __LINE__, #condition); return 1; } \ -} while (0) - -int main() { - constexpr std::array red_frame{255, 0, 0, 255, 255, 0, 0, 255}; - EXPECT(xbox_present_readback_size_matches(red_frame.size(), 2, 1, 2, 1)); - // While the resize settles, even the previous extent is valid if the frame is complete. - EXPECT(xbox_present_readback_size_matches(red_frame.size(), 2, 1, 0, 0)); - EXPECT(!xbox_present_readback_size_matches(red_frame.size(), 2, 1, 3, 2)); - - EXPECT(!xbox_present_readback_size_matches(0, 0, 0, 0, 0)); - EXPECT(!xbox_present_readback_size_matches(0, 2, 0, 0, 0)); - EXPECT(!xbox_present_readback_size_matches(0, 0, 1, 0, 0)); - EXPECT(!xbox_present_readback_size_matches(0, 2, 1, 0, 0)); - EXPECT(!xbox_present_readback_size_matches(4, 2, 1, 0, 0)); - EXPECT(!xbox_present_readback_size_matches(7, 2, 1, 2, 1)); - EXPECT(!xbox_present_readback_size_matches(12, 2, 1, 2, 1)); - return 0; -} diff --git a/runtime/test/xbox_present_test.cpp b/runtime/test/xbox_present_test.cpp deleted file mode 100644 index 1526f87a7..000000000 --- a/runtime/test/xbox_present_test.cpp +++ /dev/null @@ -1,1437 +0,0 @@ -// PresentX and the frame events (shims/xbox_present.h) on the Vulkan-backed device, checked on pixels: every case -// presents to a window and reads the swapchain image back (VulkanPresenter capture). The frame events run on a -// fake clock, so the test is fast and the order of tokens and presents is exact. -// -// Cases: 0 planes (blank), 1 plane (solid colour, two colours side by side, a source rectangle, an RGBA and a BGRA -// source, an sRGB source), 2 planes (SDR overlay), plane composition (placement, point/bilinear, premultiplied and -// straight alpha, HDR10 and PQ conversions, refusals) against a CPU model with the tolerances stated at each case, token -// errors (null, unknown, stale, repeated), suspend/resume with re-registration, statistics, and a real-time loop at -// 60 Hz. An HDR10 swapchain is only checked where the surface lists an ST.2084 format (else logged as skipped). -// Needs a window and a Vulkan GPU with presentation. -// Set LEONIDA_VK_VALIDATION=1 for VK_LAYER_KHRONOS_validation; any validation error fails the test, except that -// the NVIDIA layer's known sRGB-swapchain STORAGE check makes the run skip rather than pass or fail. -#include "vk_test_device.h" -#include "xbox_present_readback_size.h" -#include "../shims/d3d12_com.h" -#include "../shims/d3d12_xs_device.h" -#include "../shims/d3d12_trace.h" -#include "../shims/xbox_present.h" - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#define EXPECT(condition) do { \ - if (!(condition)) { std::fprintf(stderr, "line %d: %s\n", __LINE__, #condition); return 1; } \ -} while (0) - -namespace { - -using XboxHeapHandleFn = std::uint64_t(WINAPI*)(void* heap); // heap slot 9: 8-byte handle in RAX - -// Sends stderr (where the D3D12 trace goes) to a file while it lives, with the trace on or off. `redirected` is false -// when the file could not be opened (the capture then holds nothing, which must not read as "no trace line"). -struct TraceCapture { - std::filesystem::path path; - int saved = -1; - bool redirected = false; - TraceCapture(const std::filesystem::path& file, bool trace_on) : path(file) { - std::fflush(stderr); - std::FILE* out = nullptr; - if (_wfopen_s(&out, path.c_str(), L"wb") != 0) out = nullptr; // wide: a TEMP outside the ANSI code page - saved = _dup(2); - if (out && saved >= 0) redirected = _dup2(_fileno(out), 2) == 0; - if (out) std::fclose(out); - rt::d3d12_trace::set_enabled(trace_on); - } - std::string finish() { - rt::d3d12_trace::set_enabled(false); - std::fflush(stderr); - if (saved >= 0) { - _dup2(saved, 2); - _close(saved); - saved = -1; - } - std::ifstream in(path, std::ios::binary); - return {std::istreambuf_iterator(in), std::istreambuf_iterator()}; - } - ~TraceCapture() { finish(); } -}; - -int count_of(const std::string& text, const char* needle) { - int count = 0; - for (std::size_t at = text.find(needle); at != std::string::npos; at = text.find(needle, at + 1)) ++count; - return count; -} - -template -struct Ref { - T* p = nullptr; - ~Ref() { reset(); } - void reset() { - if (p) p->Release(); - p = nullptr; - } - T* operator->() const { return p; } -}; - -LRESULT CALLBACK window_proc(HWND window, UINT message, WPARAM w, LPARAM l) { - return DefWindowProcW(window, message, w, l); -} - -void pump() { - MSG message; - while (PeekMessageW(&message, nullptr, 0, 0, PM_REMOVE)) { - TranslateMessage(&message); - DispatchMessageW(&message); - } -} - -struct Px { - int r, g, b; -}; - -constexpr HRESULT invalid_state = HRESULT_FROM_WIN32(ERROR_INVALID_STATE); -constexpr UINT width = 320, height = 240; - -// The swapchain frame as RGB, whatever its channel order. -struct Frame { - std::vector bytes; - VkExtent2D extent{}; - VkFormat format = VK_FORMAT_UNDEFINED; - bool bgr() const { return format == VK_FORMAT_B8G8R8A8_UNORM || format == VK_FORMAT_B8G8R8A8_SRGB; } - bool srgb() const { return format == VK_FORMAT_B8G8R8A8_SRGB || format == VK_FORMAT_R8G8B8A8_SRGB; } - Px at(UINT x, UINT y) const { - const std::uint8_t* p = &bytes[(std::size_t(y) * extent.width + x) * 4]; - return bgr() ? Px{p[2], p[1], p[0]} : Px{p[0], p[1], p[2]}; - } -}; - -bool close_to(Px a, Px b, int tolerance) { - return std::abs(a.r - b.r) <= tolerance && std::abs(a.g - b.g) <= tolerance && std::abs(a.b - b.b) <= tolerance; -} - -// True when every pixel of the rectangle is within the tolerance of `want`. -bool region_is(const Frame& frame, UINT x0, UINT y0, UINT x1, UINT y1, Px want, int tolerance = 1) { - for (UINT y = y0; y < y1; ++y) - for (UINT x = x0; x < x1; ++x) - if (!close_to(frame.at(x, y), want, tolerance)) { - const Px got = frame.at(x, y); - std::fprintf(stderr, "pixel %u,%u is %d,%d,%d, expected %d,%d,%d\n", x, y, got.r, got.g, got.b, want.r, - want.g, want.b); - return false; - } - return true; -} - -// A CPU model of runtime/src/present_compose.comp, in double precision, written from the documented behaviour -// (docs/d3d12_vulkan.md section 4.5), not from the shader's code: planes scaled from a source rectangle to a -// destination rectangle (point: the texel containing the sample; bilinear: four texels clamped inside the source -// rectangle). SDR = piecewise sRGB (or G2.2, `gamma22`) Rec.709, HDR10 = PQ Rec.2020. Every texel is decoded to linear light, -// premultiplied, before it is weighted; the filtered plane is converted to the output's linear working space (HDR10 output: -// Rec.2020 nits with SDR white = `white` nits; SDR output: Rec.709 with SDR white = 1, HDR10 content tone mapped by -// extended Reinhard with its white point at `hdr_peak` nits), plane 1 is blended over plane 0 there and the sum is encoded once. -namespace xbox_present_ref { - -struct Tex { - UINT w = 0, h = 0; - std::vector> px; // 0..1, as stored -}; -struct Ref_plane { - const Tex* tex = nullptr; - double src[4]{}, dest[4]{}; // texels; output pixels - bool point = false, hdr = false, straight = false; -}; -using V3 = std::array; -bool gamma22 = false; // SDR EOTF: false piecewise sRGB, true pure 2.2 -double hdr_peak = 1000.0; // nits, the tone map's white point - -double pq_encode(double nits) { - const double m1 = 0.1593017578125, m2 = 78.84375, c1 = 0.8359375, c2 = 18.8515625, c3 = 18.6875; - const double y = std::pow(std::clamp(nits / 10000.0, 0.0, 1.0), m1); - return std::pow((c1 + c2 * y) / (1.0 + c3 * y), m2); -} -double pq_decode(double e) { - const double m1 = 0.1593017578125, m2 = 78.84375, c1 = 0.8359375, c2 = 18.8515625, c3 = 18.6875; - const double ep = std::pow(std::clamp(e, 0.0, 1.0), 1.0 / m2); - return 10000.0 * std::pow(std::max(ep - c1, 0.0) / (c2 - c3 * ep), 1.0 / m1); -} -double sdr_decode(double e) { - e = std::max(e, 0.0); - if (gamma22) return std::pow(e, 2.2); - return e <= 0.04045 ? e / 12.92 : std::pow((e + 0.055) / 1.055, 2.4); -} -double sdr_encode(double l) { - l = std::clamp(l, 0.0, 1.0); - if (gamma22) return std::pow(l, 1.0 / 2.2); - return l <= 0.0031308 ? l * 12.92 : 1.055 * std::pow(l, 1.0 / 2.4) - 0.055; -} -// The tone map's luminance curve, in units of SDR white: identity up to the knee (0.8), above it extended Reinhard on the -// excess (Reinhard et al. 2002, eq. 4) with value and slope continuous at the knee and the content peak mapped to 1.0. -double tone_y(double y, double white) { - const double knee = 0.8, t = 1.0 - knee; - if (y <= knee) return y; - const double lw = std::max(hdr_peak / white, 1.0), w = (lw - knee) / t, u = (y - knee) / t; - return knee + t * u * (1.0 + u / (w * w)) / (1.0 + u); -} -// v in linear Rec.709 with SDR white = 1: colour scaled by Yd / Y. -V3 tone_map(V3 v, double white) { - const double y = 0.2126 * v[0] + 0.7152 * v[1] + 0.0722 * v[2]; - const double s = y > 0.0 ? tone_y(y, white) / y : 1.0; - return {v[0] * s, v[1] * s, v[2] * s}; -} -// A premultiplied linear colour of alpha `a` from the plane's space to the output's working space. -V3 to_working(V3 lin, double a, bool plane_hdr, bool out_hdr, double white) { - if (plane_hdr == out_hdr) return lin; - if (!plane_hdr) // Rec.709 -> Rec.2020, SDR white at `white` nits - return {(0.627404 * lin[0] + 0.329283 * lin[1] + 0.043313 * lin[2]) * white, - (0.069097 * lin[0] + 0.919540 * lin[1] + 0.011362 * lin[2]) * white, - (0.016391 * lin[0] + 0.088013 * lin[1] + 0.895595 * lin[2]) * white}; - if (a <= 0.0) return {0, 0, 0}; - const double r = lin[0] / a, g = lin[1] / a, b = lin[2] / a; - V3 v{std::max((1.660491 * r - 0.587641 * g - 0.072850 * b) / white, 0.0), - std::max((-0.124550 * r + 1.132900 * g - 0.008349 * b) / white, 0.0), - std::max((-0.018151 * r - 0.100579 * g + 1.118730 * b) / white, 0.0)}; - v = tone_map(v, white); - return {v[0] * a, v[1] * a, v[2] * a}; -} -// The texel as linear premultiplied colour and alpha, in the plane's space. `opaque`: plane 0, whose alpha is ignored. -std::array decode_texel(const std::array& t, const Ref_plane& p, bool opaque) { - const double a = opaque ? 1.0 : std::clamp(t[3], 0.0, 1.0); - std::array out{0, 0, 0, a}; - for (int c = 0; c < 3; ++c) { - double e = t[c]; - if (!opaque && !p.straight) e = a > 0.0 ? e / a : 0.0; // premultiplied data is divided by alpha for the decode - out[c] = (p.hdr ? pq_decode(e) : sdr_decode(e)) * a; - } - return out; -} -std::array sample(const Ref_plane& p, bool opaque, int x, int y) { - const Tex& t = *p.tex; - const double u = (x + 0.5 - p.dest[0]) / (p.dest[2] - p.dest[0]), v = (y + 0.5 - p.dest[1]) / (p.dest[3] - p.dest[1]); - const double sx = p.src[0] + u * (p.src[2] - p.src[0]), sy = p.src[1] + v * (p.src[3] - p.src[1]); - const auto at = [&](int ix, int iy) { return decode_texel(t.px[std::size_t(iy) * t.w + ix], p, opaque); }; - if (p.point) - return at(int(std::clamp(std::floor(sx), p.src[0], p.src[2] - 1)), int(std::clamp(std::floor(sy), p.src[1], p.src[3] - 1))); - const double fx = std::clamp(sx - 0.5, p.src[0], p.src[2] - 1), fy = std::clamp(sy - 0.5, p.src[1], p.src[3] - 1); - const int x0 = int(std::floor(fx)), y0 = int(std::floor(fy)); - const int x1 = int(std::min(double(x0) + 1, p.src[2] - 1)), y1 = int(std::min(double(y0) + 1, p.src[3] - 1)); - const double wx = fx - x0, wy = fy - y0; - // Four decoded texels with their bilinear weights: linear light, premultiplied, so a transparent texel contributes no - // colour of its own. - const double weight[4] = {(1 - wx) * (1 - wy), wx * (1 - wy), (1 - wx) * wy, wx * wy}; - const std::array texel[4] = {at(x0, y0), at(x1, y0), at(x0, y1), at(x1, y1)}; - std::array out{}; - for (int i = 0; i < 4; ++i) - for (int c = 0; c < 4; ++c) out[c] += texel[i][c] * weight[i]; - return out; -} -V3 compose(const Ref_plane* planes, int count, bool out_hdr, double white, int x, int y) { - const auto inside = [&](const Ref_plane& p) { - return x + 0.5 >= p.dest[0] && x + 0.5 < p.dest[2] && y + 0.5 >= p.dest[1] && y + 0.5 < p.dest[3]; - }; - V3 base{0, 0, 0}; - if (inside(planes[0])) { - const auto c = sample(planes[0], true, x, y); - base = to_working({c[0], c[1], c[2]}, 1.0, planes[0].hdr, out_hdr, white); - } - if (count > 1 && inside(planes[1])) { - const auto c = sample(planes[1], false, x, y); - const V3 over = to_working({c[0], c[1], c[2]}, c[3], planes[1].hdr, out_hdr, white); - for (int i = 0; i < 3; ++i) base[i] = over[i] + (1 - c[3]) * base[i]; - } - for (double& v : base) v = out_hdr ? pq_encode(std::max(v, 0.0)) : sdr_encode(v); - return base; -} - -// The whole swapchain frame against the model; prints the first pixel that is off by more than `tolerance` levels. -bool frame_matches(const Frame& frame, const Ref_plane* planes, int count, bool out_hdr, double white, int tolerance) { - int worst = 0; - UINT bad = 0, first_x = 0, first_y = 0; - Px first_got{}, first_want{}; - for (UINT y = 0; y < frame.extent.height; ++y) - for (UINT x = 0; x < frame.extent.width; ++x) { - const V3 v = compose(planes, count, out_hdr, white, int(x), int(y)); - const Px want{int(std::lround(std::clamp(v[0], 0.0, 1.0) * 255)), int(std::lround(std::clamp(v[1], 0.0, 1.0) * 255)), - int(std::lround(std::clamp(v[2], 0.0, 1.0) * 255))}; - const Px got = frame.at(x, y); - const int err = std::max({std::abs(got.r - want.r), std::abs(got.g - want.g), std::abs(got.b - want.b)}); - worst = std::max(worst, err); - if (err > tolerance && bad++ == 0) { - first_x = x; - first_y = y; - first_got = got; - first_want = want; - } - } - if (bad) - std::fprintf(stderr, "%u pixels differ from the model by more than %d (worst %d); first at %u,%u is %d,%d,%d, model %d,%d,%d\n", bad, - tolerance, worst, first_x, first_y, first_got.r, first_got.g, first_got.b, first_want.r, first_want.g, - first_want.b); - return bad == 0; -} - -} // namespace xbox_present_ref - -} // namespace - -int main() { - { - // The callback's narrow exception must match the sRGB swapchain VUID, including its follow-ons, and nothing else. - VkDebugUtilsMessengerCallbackDataEXT data{}; - data.messageIdNumber = 0xc036022f; - data.pMessage = "vkCreateSwapchainKHR(): VK_IMAGE_USAGE_STORAGE_BIT is not supported"; - EXPECT(vktest::known_srgb_swapchain_storage_error(&data)); - data.pMessage = "vkCreateSwapchainKHR(): imageArrayLayers 1, but the maximum is 0"; - EXPECT(vktest::known_srgb_swapchain_storage_error(&data)); - data.messageIdNumber = 0x12345678; - data.pMessage = "vkCreateSwapchainKHR(): another validation error"; - EXPECT(!vktest::known_srgb_swapchain_storage_error(&data)); - } - vktest::Device d; - if (!d.create(true)) { // no Vulkan loader, device or presentation extensions: nothing to test (ctest: skipped) - std::printf("no Vulkan device with presentation: skipped\n"); - return 77; - } - - WNDCLASSW window_class{}; - window_class.lpfnWndProc = window_proc; - window_class.hInstance = GetModuleHandleW(nullptr); - window_class.lpszClassName = L"LeonidaXboxPresentTest"; - window_class.hCursor = LoadCursorW(nullptr, reinterpret_cast(IDC_ARROW)); - EXPECT(RegisterClassW(&window_class)); - RECT frame_rect{0, 0, int(width), int(height)}; - AdjustWindowRect(&frame_rect, WS_OVERLAPPEDWINDOW, FALSE); - HWND window = CreateWindowExW(0, window_class.lpszClassName, L"Leonida: PresentX on Vulkan", WS_OVERLAPPEDWINDOW, - 100, 100, frame_rect.right - frame_rect.left, frame_rect.bottom - frame_rect.top, - nullptr, nullptr, window_class.hInstance, nullptr); - EXPECT(window); - ShowWindow(window, SW_SHOWNOACTIVATE); - UpdateWindow(window); - pump(); - - { - // The real runtime's instance path (create_vulkan_device_standalone, not the test device): it must enable - // VK_EXT_swapchain_colorspace when the loader has it, or the HDR10 surface formats can never be listed. - Ref standalone; - if (SUCCEEDED(rt::d3d12::create_vulkan_device_standalone(IID_PPV_ARGS(&standalone.p)))) { - const auto enumerate = reinterpret_cast( - d.instance_proc(nullptr, "vkEnumerateInstanceExtensionProperties")); - std::uint32_t count = 0; - enumerate(nullptr, &count, nullptr); - std::vector available(count); - enumerate(nullptr, &count, available.data()); - bool loader_has = false; - for (const auto& e : available) loader_has = loader_has || !std::strcmp(e.extensionName, "VK_EXT_swapchain_colorspace"); - auto standalone_presenter = rt::d3d12::create_window_presenter(standalone.p, window); - if (standalone_presenter) { - const bool colorspace_enabled = rt::d3d12::device_has_swapchain_colorspace(standalone.p); - EXPECT(colorspace_enabled == loader_has); - // The presenter owns the remaining reference to the device and its Vulkan instance. - standalone.reset(); - EXPECT(standalone_presenter->enable_capture()); - EXPECT(SUCCEEDED(standalone_presenter->present_blank(1))); - Frame frame; - EXPECT(standalone_presenter->read_back(frame.bytes, &frame.extent, &frame.format)); - EXPECT(!frame.bytes.empty()); - std::printf("standalone device (real instance path): VK_EXT_swapchain_colorspace %s on the instance (loader has it: %s)\n", - colorspace_enabled ? "enabled" : "not enabled", loader_has ? "yes" : "no"); - std::printf("standalone presenter: frame captured after releasing the caller's device reference\n"); - } else { - std::printf("standalone device: no window presenter (skipped the instance-extension check)\n"); - } - } - } - - { - rt::d3d12::VulkanDeviceInfo info{}; - info.get_instance_proc = d.instance_proc; - info.instance = d.instance; - info.physical = d.physical; - info.device = d.device; - info.queue = d.queue; - info.queue_family = d.family; - info.presentation = true; - info.swapchain_maintenance1 = d.swapchain_maintenance1; - ID3D12Device* inner = nullptr; - EXPECT(SUCCEEDED(rt::d3d12::create_vulkan_device(info, IID_PPV_ARGS(&inner)))); - Ref device; - EXPECT(SUCCEEDED(rt::d3d12_xs::create_device_proxy(inner, __uuidof(ID3D12Device), - reinterpret_cast(&device.p)))); - rt::d3d12::set_device_outer(inner, device.p); - auto presenter = rt::d3d12::create_window_presenter(inner, window); - EXPECT(presenter); - EXPECT(presenter->enable_capture()); - - leonida::ManualFrameClock clock; - auto owner = std::make_unique(std::move(presenter), &clock); - rt::d3d12::XboxPresentation& xbox = *owner; - - D3D12_COMMAND_QUEUE_DESC queue_desc{}; - Ref queue; - Ref allocator; - Ref list; - Ref fence; - Ref rtv_heap; - EXPECT(SUCCEEDED(device->CreateCommandQueue(&queue_desc, IID_PPV_ARGS(&queue.p)))); - EXPECT(SUCCEEDED(device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&allocator.p)))); - EXPECT(SUCCEEDED(device->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, allocator.p, nullptr, - IID_PPV_ARGS(&list.p)))); - EXPECT(SUCCEEDED(list->Close())); - EXPECT(SUCCEEDED(device->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&fence.p)))); - constexpr UINT rtv_slots = 24; - const D3D12_DESCRIPTOR_HEAP_DESC heap_desc{D3D12_DESCRIPTOR_HEAP_TYPE_RTV, rtv_slots, - D3D12_DESCRIPTOR_HEAP_FLAG_NONE, 0}; - EXPECT(SUCCEEDED(device->CreateDescriptorHeap(&heap_desc, IID_PPV_ARGS(&rtv_heap.p)))); - const SIZE_T rtv_start = SIZE_T(reinterpret_cast( - (*reinterpret_cast(rtv_heap.p))[9])(rtv_heap.p)); - const UINT rtv_step = device->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_RTV); - - // A display-capable back buffer: committed, ALLOW_DISPLAY, in the PRESENT state, with a view in `slot`. - UINT slot_count = 0; - struct Source { - Ref resource; - D3D12_CPU_DESCRIPTOR_HANDLE rtv{}; - }; - const auto make_source = [&](DXGI_FORMAT format, Source& out, UINT w = width, UINT h = height) -> bool { - const D3D12_HEAP_PROPERTIES default_heap{D3D12_HEAP_TYPE_DEFAULT}; - D3D12_RESOURCE_DESC desc{}; - desc.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D; - desc.Width = w; - desc.Height = h; - desc.DepthOrArraySize = 1; - desc.MipLevels = 1; - desc.Format = format; - desc.SampleDesc.Count = 1; - desc.Flags = D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET; - if (slot_count >= rtv_slots) return false; - if (FAILED(device->CreateCommittedResource(&default_heap, D3D12_HEAP_FLAG_ALLOW_DISPLAY, &desc, - D3D12_RESOURCE_STATE_PRESENT, nullptr, - IID_PPV_ARGS(&out.resource.p)))) - return false; - out.rtv.ptr = rtv_start + SIZE_T(slot_count++) * rtv_step; - device->CreateRenderTargetView(out.resource.p, nullptr, out.rtv); - return true; - }; - UINT64 signalled = 0; - // Clears the whole resource to `colour`, or the given rectangles; leaves it in PRESENT. - const auto fill = [&](Source& s, const FLOAT colour[4], UINT rect_count = 0, const D3D12_RECT* rects = nullptr) -> bool { - if (FAILED(allocator->Reset()) || FAILED(list->Reset(allocator.p, nullptr))) return false; - D3D12_RESOURCE_BARRIER barrier{}; - barrier.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION; - barrier.Transition.pResource = s.resource.p; - barrier.Transition.Subresource = D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES; - barrier.Transition.StateBefore = D3D12_RESOURCE_STATE_PRESENT; - barrier.Transition.StateAfter = D3D12_RESOURCE_STATE_RENDER_TARGET; - list->ResourceBarrier(1, &barrier); - list->ClearRenderTargetView(s.rtv, colour, rect_count, rects); - barrier.Transition.StateBefore = D3D12_RESOURCE_STATE_RENDER_TARGET; - barrier.Transition.StateAfter = D3D12_RESOURCE_STATE_PRESENT; - list->ResourceBarrier(1, &barrier); - if (FAILED(list->Close())) return false; - ID3D12CommandList* lists[] = {list.p}; - queue->ExecuteCommandLists(1, lists); - if (rt::d3d12::last_execute_result(queue.p) != leonida::ReplayResult::success) return false; - return SUCCEEDED(queue->Signal(fence.p, ++signalled)) && - SUCCEEDED(fence->SetEventOnCompletion(signalled, nullptr)); - }; - - // The title's frame loop: wait for the origin, render (the caller did), PresentX with that token. - const UINT period = rt::d3d12::xbox_frame_interval_60hz_us; - EXPECT(SUCCEEDED(xbox.SetFrameIntervalX(nullptr, period, 1, 0))); - EXPECT(SUCCEEDED(xbox.ScheduleFrameEventX(rt::d3d12::xbox_frame_event_origin, 0, 0))); - const auto next_token = [&](std::uint64_t& token) -> bool { - clock.advance_us(period); - return xbox.WaitFrameEventX(rt::d3d12::xbox_frame_event_origin, 0, 0, &token) == S_OK; - }; - UINT want_w = width, want_h = height; // the client size the frames are expected at (the resize case changes it) - const auto grab = [&](Frame& frame) -> bool { - return xbox.presenter().read_back(frame.bytes, &frame.extent, &frame.format) && - xbox_present_readback_size_matches(frame.bytes.size(), frame.extent.width, frame.extent.height, - want_w, want_h); - }; - - const FLOAT blue_ish[4] = {0.2f, 0.6f, 0.9f, 1.0f}; // 51, 153, 230 - const FLOAT red[4] = {1, 0, 0, 1}, green[4] = {0, 1, 0, 1}, blue[4] = {0, 0, 1, 1}; - std::uint64_t token = 0; - Frame frame; - const auto plane_of = [&](Source& s, std::uint64_t t, const D3D12_RECT* rect = nullptr) { - return rt::d3d12::XboxPresentPlaneParameters{t, 1, &s.resource.p, rect, 0}; - }; - - // 1 plane, solid colour, RGBA8. - Source rgba; - EXPECT(make_source(DXGI_FORMAT_R8G8B8A8_UNORM, rgba)); - EXPECT(fill(rgba, blue_ish)); - EXPECT(next_token(token) && token == 1); - auto plane = plane_of(rgba, token); - EXPECT(xbox.PresentX(1, &plane, nullptr) == S_OK); - EXPECT(grab(frame)); - EXPECT(region_is(frame, 0, 0, width, height, {51, 153, 230})); - std::printf("1 plane, RGBA8 solid: ok (swapchain format %d)\n", int(frame.format)); - - // 0 planes: a black frame, and no token is needed. With the D3D12 trace on, each PresentX writes one line - // with its outcome, a refused call included; with it off, none. - { - std::error_code ignored; - const std::filesystem::path trace_file = - std::filesystem::temp_directory_path(ignored) / "leonida_xbox_present_trace.txt"; - std::string trace, untraced; - HRESULT blank = E_FAIL, refused = S_OK, refused_untraced = S_OK; - bool captured = false, captured_untraced = false; - { - TraceCapture capture(trace_file, true); - captured = capture.redirected; - blank = xbox.PresentX(0, nullptr, nullptr); - refused = xbox.PresentX(3, &plane, nullptr); // more than two planes: refused before anything is shown - trace = capture.finish(); - } - { - TraceCapture capture(trace_file, false); - captured_untraced = capture.redirected; - refused_untraced = xbox.PresentX(3, &plane, nullptr); - untraced = capture.finish(); - } - std::filesystem::remove(trace_file, ignored); - EXPECT(captured && captured_untraced); - EXPECT(blank == S_OK); - EXPECT(refused == E_INVALIDARG); - EXPECT(refused_untraced == E_INVALIDARG); - EXPECT(count_of(untraced, "[d3d12-trace]") == 0); - EXPECT(count_of(trace, " XboxPresentation::PresentX ok\n") == 1); - EXPECT(count_of(trace, " XboxPresentation::PresentX failed\n") == 1); - EXPECT(count_of(trace, "[d3d12-trace] #") == 2); - } - EXPECT(grab(frame)); - EXPECT(region_is(frame, 0, 0, width, height, {0, 0, 0}, 0)); - // (The blank frame is a frame in flight like any other: with latency 1 the next wait needs it shown first.) - EXPECT(xbox.pacer().frames_in_flight() == 2); // the first frame and the blank one - clock.advance_us(period); - std::printf("0 planes (blank): ok\n"); - - // Two colours side by side: left half red, right half blue; the swapchain shows them where they were. - Source split; - EXPECT(make_source(DXGI_FORMAT_R8G8B8A8_UNORM, split)); - const D3D12_RECT left_half{0, 0, LONG(width / 2), LONG(height)}, right_half{LONG(width / 2), 0, LONG(width), LONG(height)}; - EXPECT(fill(split, red, 1, &left_half)); - EXPECT(fill(split, blue, 1, &right_half)); - EXPECT(next_token(token)); - plane = plane_of(split, token); - EXPECT(xbox.PresentX(1, &plane, nullptr) == S_OK); - EXPECT(grab(frame)); - EXPECT(region_is(frame, 0, 0, width / 2 - 2, height, {255, 0, 0}, 0)); - EXPECT(region_is(frame, width / 2 + 2, 0, width, height, {0, 0, 255}, 0)); - std::printf("1 plane, two colours (orientation): ok\n"); - - // A source rectangle: only the right half (blue) is shown, stretched over the window. - EXPECT(next_token(token)); - plane = plane_of(split, token, &right_half); - EXPECT(xbox.PresentX(1, &plane, nullptr) == S_OK); - EXPECT(grab(frame)); - // (The blit filters bilinearly, so the outermost texel of the rectangle blends with its neighbour outside it: the - // border pixels are left out.) - EXPECT(region_is(frame, 2, 2, width - 2, height - 2, {0, 0, 255}, 0)); - // And a quarter in the middle that straddles the edge: the left part shows red, the right part blue. - const D3D12_RECT middle{LONG(width / 4), LONG(height / 4), LONG(width * 3 / 4), LONG(height * 3 / 4)}; - EXPECT(next_token(token)); - plane = plane_of(split, token, &middle); - EXPECT(xbox.PresentX(1, &plane, nullptr) == S_OK); - EXPECT(grab(frame)); - EXPECT(region_is(frame, 4, 4, width / 2 - 4, height - 4, {255, 0, 0}, 0)); - EXPECT(region_is(frame, width / 2 + 4, 4, width - 4, height - 4, {0, 0, 255}, 0)); - // Rectangles that are empty, inverted or outside the texture are refused and present nothing. - const std::uint64_t before = xbox.presents(); - const D3D12_RECT bad_rects[] = {{10, 10, 10, 20}, {20, 10, 10, 20}, {0, 0, LONG(width + 1), 10}, {-1, 0, 10, 10}}; - for (const D3D12_RECT& bad : bad_rects) { - clock.advance_us(4 * period); // let the queued frames show: with latency 1 the wait holds for them - EXPECT(next_token(token)); - plane = plane_of(split, token, &bad); - EXPECT(xbox.PresentX(1, &plane, nullptr) == E_INVALIDARG); - } - EXPECT(xbox.presents() == before); - std::printf("source rectangles (valid and invalid): ok\n"); - - // A BGRA source with a colour whose channels differ: red must stay red. - Source bgra; - EXPECT(make_source(DXGI_FORMAT_B8G8R8A8_UNORM, bgra)); - const FLOAT orange[4] = {1.0f, 0.5f, 0.0f, 1.0f}; - EXPECT(fill(bgra, orange)); - EXPECT(next_token(token)); // (the token from the refused rect presents is still unused, which is fine) - plane = plane_of(bgra, token); - EXPECT(xbox.PresentX(1, &plane, nullptr) == S_OK); - EXPECT(grab(frame)); - EXPECT(region_is(frame, 0, 0, width, height, {255, 128, 0}, 1)); - std::printf("1 plane, BGRA8 source: ok\n"); - - // An sRGB source: the clear value is linear, the stored (and shown) bytes are encoded: 0.5 -> 188. The - // swapchain follows the source's format, so those bytes go through unchanged. - Source srgb; - EXPECT(make_source(DXGI_FORMAT_R8G8B8A8_UNORM_SRGB, srgb)); - const FLOAT grey[4] = {0.5f, 0.5f, 0.5f, 1.0f}; - EXPECT(fill(srgb, grey)); - EXPECT(next_token(token)); - plane = plane_of(srgb, token); - EXPECT(xbox.PresentX(1, &plane, nullptr) == S_OK); - EXPECT(grab(frame)); - EXPECT(frame.srgb()); - EXPECT(region_is(frame, 0, 0, width, height, {188, 188, 188}, 1)); - // Back to UNORM: the swapchain goes back to a UNORM format. - EXPECT(next_token(token)); - plane = plane_of(rgba, token); - EXPECT(xbox.PresentX(1, &plane, nullptr) == S_OK); - EXPECT(grab(frame)); - EXPECT(!frame.srgb()); - EXPECT(region_is(frame, 0, 0, width, height, {51, 153, 230})); - std::printf("1 plane, sRGB source (swapchain follows): ok\n"); - - // 2 planes sharing a token, both SDR: plane 1 is an overlay (section 4.5), and an opaque one covers plane 0. - // (The plane composition has its own checks further down.) - Source second; - EXPECT(make_source(DXGI_FORMAT_R8G8B8A8_UNORM, second)); - EXPECT(fill(second, green)); - EXPECT(next_token(token)); - rt::d3d12::XboxPresentPlaneParameters two[2] = {plane_of(rgba, token), plane_of(second, token)}; - const std::uint64_t composed_before = xbox.presenter().composed_presents(); - EXPECT(xbox.PresentX(2, two, nullptr) == S_OK); - EXPECT(xbox.presenter().composed_presents() == composed_before); // plane 1 without the overlay flag: not composed - EXPECT(grab(frame)); - EXPECT(region_is(frame, 0, 0, width, height, {51, 153, 230})); // plane 0 only, by the plain blit - // Planes with different tokens, or more than two planes, are refused. - EXPECT(next_token(token)); - two[0] = plane_of(rgba, token); - two[1] = plane_of(second, token + 1); - EXPECT(xbox.PresentX(2, two, nullptr) == E_INVALIDARG); - rt::d3d12::XboxPresentPlaneParameters three[3] = {plane_of(rgba, token), plane_of(second, token), plane_of(second, token)}; - EXPECT(xbox.PresentX(3, three, nullptr) == E_INVALIDARG); - EXPECT(xbox.PresentX(1, nullptr, nullptr) == E_INVALIDARG); - { // ResourceCount above 1 (either plane, either path) is refused, nothing presented, the frame stays - ID3D12Resource* both[2] = {rgba.resource.p, second.resource.p}; - const std::uint64_t presents_before_count = xbox.presents(); - const auto count_two = [&](int color_space, UINT flags) { - rt::d3d12::XboxPresentPlaneParameters p{token, 2, both, nullptr, 0}; - p.ColorSpace = color_space; - p.Flags = flags; - return p; - }; - auto one_count = count_two(0, 0); - EXPECT(xbox.PresentX(1, &one_count, nullptr) == DXGI_ERROR_UNSUPPORTED); // plain blit path - one_count = count_two(rt::d3d12::xbox_color_space_g2084_p2020, 0); - EXPECT(xbox.PresentX(1, &one_count, nullptr) == DXGI_ERROR_UNSUPPORTED); // compose path - rt::d3d12::XboxPresentPlaneParameters pair_count[2] = {plane_of(rgba, token), count_two(0, rt::d3d12::xbox_plane_flag_overlay)}; - EXPECT(xbox.PresentX(2, pair_count, nullptr) == DXGI_ERROR_UNSUPPORTED); // plane 1 - EXPECT(xbox.presents() == presents_before_count); - std::printf("ResourceCount above 1 refused (plain, compose, plane 1): ok\n"); - } - std::printf("2 planes (SDR overlay over plane 0) and refused plane sets: ok\n"); - - // The parameters struct is accepted (ImmediateThresholdPercent is ignored). - const rt::d3d12::XboxPresentParameters params{50.0f}; - plane = plane_of(second, token); - EXPECT(xbox.PresentX(1, &plane, ¶ms) == S_OK); - EXPECT(grab(frame)); - EXPECT(region_is(frame, 0, 0, width, height, {0, 255, 0}, 0)); - - // Tokens: a token that was never handed out is refused and nothing is presented. A null, repeated or stale one - // is presented anyway (and logged once per kind, see the log lines above): alternate the sources so that - // each present shows on screen. - const std::uint64_t presented_before = xbox.presents(); - plane = plane_of(rgba, xbox.pacer().tokens_issued() + 1); - EXPECT(xbox.PresentX(1, &plane, nullptr) == E_INVALIDARG); - EXPECT(xbox.presents() == presented_before); - EXPECT(grab(frame)); - EXPECT(region_is(frame, 0, 0, width, height, {0, 255, 0}, 0)); // still the last frame - plane = plane_of(rgba, 0); // null token, as a loading screen might - EXPECT(xbox.PresentX(1, &plane, nullptr) == S_OK); - EXPECT(grab(frame)); - EXPECT(region_is(frame, 0, 0, width, height, {51, 153, 230})); - plane = plane_of(second, token); // repeated: the token of the last tokened present - EXPECT(xbox.PresentX(1, &plane, nullptr) == S_OK); - EXPECT(grab(frame)); - EXPECT(region_is(frame, 0, 0, width, height, {0, 255, 0}, 0)); - plane = plane_of(rgba, 1); // stale: long gone - EXPECT(xbox.PresentX(1, &plane, nullptr) == S_OK); - EXPECT(grab(frame)); - EXPECT(region_is(frame, 0, 0, width, height, {51, 153, 230})); - EXPECT(xbox.presents() == presented_before + 3); - - // Sources the GPU cannot blit are refused with DXGI_ERROR_UNSUPPORTED and present nothing: multisampled, - // integer and block-compressed. The last frame stays on screen and the token is still usable afterwards. - { - const D3D12_HEAP_PROPERTIES default_heap{D3D12_HEAP_TYPE_DEFAULT}; - const auto make_special = [&](DXGI_FORMAT format, UINT samples, D3D12_RESOURCE_FLAGS flags, - Ref& out) { - D3D12_RESOURCE_DESC desc{}; - desc.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D; - desc.Width = width; - desc.Height = height; - desc.DepthOrArraySize = 1; - desc.MipLevels = 1; - desc.Format = format; - desc.SampleDesc.Count = samples; - desc.Flags = flags; - return SUCCEEDED(device->CreateCommittedResource(&default_heap, D3D12_HEAP_FLAG_ALLOW_DISPLAY, &desc, - D3D12_RESOURCE_STATE_COMMON, nullptr, - IID_PPV_ARGS(&out.p))); - }; - Ref msaa, integer, bc; - EXPECT(make_special(DXGI_FORMAT_R8G8B8A8_UNORM, 4, D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET, msaa)); - EXPECT(make_special(DXGI_FORMAT_R8G8B8A8_UINT, 1, D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET, integer)); - EXPECT(make_special(DXGI_FORMAT_BC1_UNORM, 1, D3D12_RESOURCE_FLAG_NONE, bc)); - ID3D12Resource* unsupported[3] = {msaa.p, integer.p, bc.p}; - clock.advance_us(4 * period); // let the queued frames show: with latency 1 the wait holds for them - EXPECT(next_token(token)); - const std::uint64_t before_unsupported = xbox.presents(); - for (ID3D12Resource* resource : unsupported) { - const rt::d3d12::XboxPresentPlaneParameters p{token, 1, &resource, nullptr, 0}; - EXPECT(xbox.PresentX(1, &p, nullptr) == DXGI_ERROR_UNSUPPORTED); - } - EXPECT(xbox.presents() == before_unsupported); - EXPECT(grab(frame)); - EXPECT(region_is(frame, 0, 0, width, height, {51, 153, 230})); - plane = plane_of(second, token); - EXPECT(xbox.PresentX(1, &plane, nullptr) == S_OK); // the same token, now with a supported source - EXPECT(grab(frame)); - EXPECT(region_is(frame, 0, 0, width, height, {0, 255, 0}, 0)); - std::printf("unsupported sources (MSAA, integer, BC) refused: ok\n"); - } - - // ---- Plane composition (docs section 4.5), against a CPU model of the compose pass (xbox_present_ref below). ---- - // Exact (tolerance 0) for point filtering between SDR planes without alpha; 1 level for bilinear filtering and - // alpha blending (the pass works in float, stores RGBA16F and the copy rounds to 8 bits); 2 levels where PQ and - // gamma conversions are involved (GPU pow is not correctly rounded). - { - using namespace xbox_present_ref; - using rt::d3d12::XboxViewRect; - struct Painted { - Source source; - Tex tex; - }; - const auto make_painted = [&](Painted& p, UINT w, UINT h, DXGI_FORMAT format = DXGI_FORMAT_R8G8B8A8_UNORM) { - p.tex = Tex{w, h, std::vector>(std::size_t(w) * h, {0, 0, 0, 0})}; - const FLOAT zero[4] = {0, 0, 0, 0}; - return make_source(format, p.source, w, h) && fill(p.source, zero); - }; - // Paints a rectangle with 8-bit values (R8G8B8A8) in the texture and in the model. - const auto paint = [&](Painted& p, D3D12_RECT r, int R, int G, int B, int A) { - const FLOAT c[4] = {R / 255.0f, G / 255.0f, B / 255.0f, A / 255.0f}; - if (!fill(p.source, c, 1, &r)) return false; - for (LONG y = r.top; y < r.bottom; ++y) - for (LONG x = r.left; x < r.right; ++x) - p.tex.px[std::size_t(y) * p.tex.w + x] = {R / 255.0, G / 255.0, B / 255.0, A / 255.0}; - return true; - }; - // The same for R10G10B10A2 (10-bit codes; alpha 2 bits): the model keeps the quantised value. - const auto paint10 = [&](Painted& p, D3D12_RECT r, int R, int G, int B) { - const FLOAT c[4] = {R / 1023.0f, G / 1023.0f, B / 1023.0f, 1.0f}; - if (!fill(p.source, c, 1, &r)) return false; - for (LONG y = r.top; y < r.bottom; ++y) - for (LONG x = r.left; x < r.right; ++x) - p.tex.px[std::size_t(y) * p.tex.w + x] = {R / 1023.0, G / 1023.0, B / 1023.0, 1.0}; - return true; - }; - // R10G10B10A2 with a 2-bit alpha (0..3): stored colour is premultiplied by the caller. - const auto paint10a = [&](Painted& p, D3D12_RECT r, int R, int G, int B, int A) { - const FLOAT c[4] = {R / 1023.0f, G / 1023.0f, B / 1023.0f, A / 3.0f}; - if (!fill(p.source, c, 1, &r)) return false; - for (LONG y = r.top; y < r.bottom; ++y) - for (LONG x = r.left; x < r.right; ++x) - p.tex.px[std::size_t(y) * p.tex.w + x] = {R / 1023.0, G / 1023.0, B / 1023.0, A / 3.0}; - return true; - }; - // One PresentX of `count` planes, a fresh token for all; the swapchain frame is read back into `frame`. - const auto present_planes = [&](rt::d3d12::XboxPresentPlaneParameters* planes_, UINT count_, HRESULT want = S_OK) { - clock.advance_us(4 * period); - if (!next_token(token)) return false; - for (UINT i = 0; i < count_; ++i) planes_[i].Token = token; - if (xbox.PresentX(count_, planes_, nullptr) != want) return false; - return want != S_OK || grab(frame); - }; - const auto parameters = [&](Source& s, const XboxViewRect* place, int filter, int color_space = 0, - UINT flags = 0, const D3D12_RECT* rect = nullptr) { - rt::d3d12::XboxPresentPlaneParameters p = plane_of(s, 0, rect); - p.ColorSpace = color_space; - p.pDestPlacementBase = place; - p.ScaleFilter = filter; - p.Flags = flags; - return p; - }; - const auto model = [&](const Painted& p, const XboxViewRect* place, bool point, const D3D12_RECT* rect = nullptr, - bool hdr = false, bool straight = false) { - Ref_plane r; - r.tex = &p.tex; - r.src[0] = rect ? rect->left : 0; - r.src[1] = rect ? rect->top : 0; - r.src[2] = rect ? rect->right : double(p.tex.w); - r.src[3] = rect ? rect->bottom : double(p.tex.h); - const XboxViewRect whole{0, 0, 1, 1}; - const XboxViewRect& v = place ? *place : whole; - r.dest[0] = v.left * width; - r.dest[1] = v.top * height; - r.dest[2] = v.right * width; - r.dest[3] = v.bottom * height; - r.point = point; - r.hdr = hdr; - r.straight = straight; - return r; - }; - using rt::d3d12::xbox_scale_filter_linear; - using rt::d3d12::xbox_scale_filter_point; - const std::uint64_t composed_start = xbox.presenter().composed_presents(); - std::uint64_t composed_expected = composed_start; - const auto composed_ok = [&] { return xbox.presenter().composed_presents() == ++composed_expected; }; - // Fixed inputs whatever the machine says: SDR white 203 nits (not the Windows slider), piecewise sRGB (not - // LEONIDA_SDR_EOTF), peak 1000 nits. The query itself is checked on its own below. - xbox.set_sdr_white_nits(203.0f); - xbox.set_sdr_eotf(leonida::PresentPlanes::SdrEotf::srgb); - xbox.set_hdr_peak_nits(1000.0f); - xbox_present_ref::gamma22 = false; - xbox_present_ref::hdr_peak = 1000.0; - { - EXPECT(rt::d3d12::sdr_white_nits_from_level(1000) == 80.0f && rt::d3d12::sdr_white_nits_from_level(2500) == 200.0f && - rt::d3d12::sdr_white_nits_from_level(6000) == 480.0f); - // The query's cost: why PresentX does not run it (the layer caches it from a background thread). - float windows_white = 0.0f; - double total_us = 0, worst_us = 0; - const int queries = 50; - for (int q = 0; q < queries; ++q) { - const auto t0 = std::chrono::steady_clock::now(); - windows_white = xbox.presenter().display_sdr_white_nits(); // 0 when Windows has no answer - const double us = std::chrono::duration(std::chrono::steady_clock::now() - t0).count(); - total_us += us; - worst_us = std::max(worst_us, us); - } - std::printf("SDR white level query: %.0f us mean, %.0f us worst over %d calls\n", total_us / queries, worst_us, queries); - EXPECT(windows_white == 0.0f || (windows_white >= 80.0f && windows_white <= 480.0f)); - std::printf("SDR white level of this window's output from Windows: %s%.1f nits (hdr_active %d)\n", - windows_white > 0 ? "" : "unavailable, ", windows_white, int(xbox.presenter().hdr_active())); - } - - // A: one plane, scaled 2x to the middle of the output, point and linear; the rest of the output is black. - Painted quad; - EXPECT(make_painted(quad, 80, 60)); - EXPECT(paint(quad, {0, 0, 40, 30}, 255, 0, 0, 255) && paint(quad, {40, 0, 80, 30}, 0, 255, 0, 255)); - EXPECT(paint(quad, {0, 30, 40, 60}, 0, 0, 255, 255) && paint(quad, {40, 30, 80, 60}, 255, 255, 255, 255)); - const XboxViewRect middle_half{0.25f, 0.25f, 0.75f, 0.75f}; - auto one = parameters(quad.source, &middle_half, xbox_scale_filter_point); - EXPECT(present_planes(&one, 1) && composed_ok()); - EXPECT(frame.format == VK_FORMAT_B8G8R8A8_UNORM || frame.format == VK_FORMAT_R8G8B8A8_UNORM); - Ref_plane ref0 = model(quad, &middle_half, true); - EXPECT(frame_matches(frame, &ref0, 1, false, 203.0, 0)); - std::printf("compose: 1 plane, 80x60 -> dest placement 160x120, point: exact\n"); - one = parameters(quad.source, &middle_half, xbox_scale_filter_linear); - EXPECT(present_planes(&one, 1) && composed_ok()); - ref0 = model(quad, &middle_half, false); - EXPECT(frame_matches(frame, &ref0, 1, false, 203.0, 1)); - std::printf("compose: same, bilinear: within 1 level of the model\n"); - // A source rectangle (the right half) onto the whole output, point: no placement. - const D3D12_RECT right_half_of_quad{40, 0, 80, 60}; - one = parameters(quad.source, nullptr, xbox_scale_filter_point, 0, 0, &right_half_of_quad); - EXPECT(present_planes(&one, 1) && composed_ok()); - ref0 = model(quad, nullptr, true, &right_half_of_quad); - EXPECT(frame_matches(frame, &ref0, 1, false, 203.0, 0)); - // Bilinear with a source rectangle must not read outside it: the right half shows only green over white. - one = parameters(quad.source, nullptr, xbox_scale_filter_linear, 0, 0, &right_half_of_quad); - EXPECT(present_planes(&one, 1) && composed_ok()); - ref0 = model(quad, nullptr, false, &right_half_of_quad); - EXPECT(frame_matches(frame, &ref0, 1, false, 203.0, 1)); - std::printf("compose: source rectangle, point and bilinear (clamped inside it): ok\n"); - - // The compose pass with point filtering at 1:1 gives the very bytes of the plain blit. - plane = plane_of(split, 0); - clock.advance_us(4 * period); - EXPECT(next_token(token)); - plane.Token = token; - const std::uint64_t blits = xbox.presenter().composed_presents(); - EXPECT(xbox.PresentX(1, &plane, nullptr) == S_OK && xbox.presenter().composed_presents() == blits); - Frame blit_frame; - EXPECT(grab(blit_frame)); - one = parameters(split, nullptr, xbox_scale_filter_point); - EXPECT(present_planes(&one, 1) && composed_ok()); - EXPECT(frame.bytes == blit_frame.bytes); - std::printf("compose at 1:1 equals the plain blit byte for byte: ok\n"); - - // An sRGB source (0.5 linear is byte 188): the pass encodes it again, so the bytes come out as stored. - one = parameters(srgb, nullptr, xbox_scale_filter_point); - EXPECT(present_planes(&one, 1) && composed_ok()); - EXPECT(!frame.srgb()); - EXPECT(region_is(frame, 0, 0, width, height, {188, 188, 188}, 1)); - std::printf("compose: sRGB source, UNORM swapchain: ok\n"); - - // B: plane 1 over plane 0. Plane 0 is a solid; plane 1 (80x60, scaled 2x into the middle) has a half - // transparent red (premultiplied: 128,0,0 alpha 128), nothing, opaque green and 25% blue (0,0,64, alpha 64). - Painted solid; - EXPECT(make_painted(solid, width, height)); - EXPECT(paint(solid, {0, 0, LONG(width), LONG(height)}, 51, 153, 230, 255)); - Painted ui; - EXPECT(make_painted(ui, 80, 60)); - EXPECT(paint(ui, {0, 0, 40, 30}, 128, 0, 0, 128) && paint(ui, {0, 30, 40, 60}, 0, 255, 0, 255)); - EXPECT(paint(ui, {40, 30, 80, 60}, 0, 0, 64, 64)); - rt::d3d12::XboxPresentPlaneParameters pair[2]; - pair[0] = parameters(solid.source, nullptr, xbox_scale_filter_point); - pair[1] = parameters(ui.source, &middle_half, xbox_scale_filter_point, 0, rt::d3d12::xbox_plane_flag_overlay); - EXPECT(present_planes(pair, 2) && composed_ok()); - Ref_plane refs[2] = {model(solid, nullptr, true), model(ui, &middle_half, true)}; - EXPECT(frame_matches(frame, refs, 2, false, 203.0, 1)); - std::printf("compose: 2 planes, premultiplied alpha overlay, point: within 1 level of the model\n"); - pair[1] = parameters(ui.source, &middle_half, xbox_scale_filter_point, 0, rt::d3d12::xbox_plane_flag_overlay | rt::d3d12::xbox_plane_flag_straight_alpha); - EXPECT(present_planes(pair, 2) && composed_ok()); - refs[1] = model(ui, &middle_half, true, nullptr, false, true); - EXPECT(frame_matches(frame, refs, 2, false, 203.0, 1)); - std::printf("compose: 2 planes, straight alpha overlay: within 1 level of the model\n"); - pair[1] = parameters(ui.source, &middle_half, xbox_scale_filter_linear, 0, rt::d3d12::xbox_plane_flag_overlay); - EXPECT(present_planes(pair, 2) && composed_ok()); - refs[1] = model(ui, &middle_half, false); - EXPECT(frame_matches(frame, refs, 2, false, 203.0, 1)); - std::printf("compose: 2 planes, bilinear overlay: within 1 level of the model\n"); - // Straight alpha with bilinear filtering across a transparent edge: opaque white on the left, transparent black on the - // right. Colour is filtered premultiplied, so the edge is white at partial alpha, not grey (filtering the - // unassociated colour would also quarter the colour and quarter it again by the alpha). At output x=160 the sample - // is 0.75 of the way from the white texel to the transparent one: alpha 0.25, colour white, blended in linear light. - Painted edge; - EXPECT(make_painted(edge, 80, 60)); - EXPECT(paint(edge, {0, 0, 40, 60}, 255, 255, 255, 255) && paint(edge, {40, 0, 80, 60}, 0, 0, 0, 0)); - pair[1] = parameters(edge.source, &middle_half, xbox_scale_filter_linear, 0, - rt::d3d12::xbox_plane_flag_overlay | rt::d3d12::xbox_plane_flag_straight_alpha); - EXPECT(present_planes(pair, 2) && composed_ok()); - refs[1] = model(edge, &middle_half, false, nullptr, false, true); - EXPECT(frame_matches(frame, refs, 2, false, 203.0, 1)); - { - const Px edge_px = frame.at(160, 120); - // Linear light: red 0.25 + 0.75 * lin(51/255), blue 0.25 + 0.75 * lin(230/255), then encoded (piecewise sRGB: - // about 143 and 237); the unfiltered-colour result would be near 54 and blending the encoded values would give 102. - const auto expect_level = [](double base255) { - return int(std::lround(255 * xbox_present_ref::sdr_encode(0.25 + 0.75 * xbox_present_ref::sdr_decode(base255 / 255)))); - }; - EXPECT(std::abs(edge_px.r - expect_level(51)) <= 1 && std::abs(edge_px.b - expect_level(230)) <= 1); - std::printf("compose: edge pixel %d,%d,%d (linear-light model %d,%d)\n", edge_px.r, edge_px.g, edge_px.b, expect_level(51), expect_level(230)); - } - std::printf("compose: straight alpha, bilinear across a transparent edge (premultiplied filtering): ok\n"); - - // C: HDR10 (PQ, Rec.2020) planes. Plane 0 is 80x60 R10G10B10A2 (three bands: SDR white level, a bright - // colour above it, and a dim colour), shown 4x on the whole output. - Painted hdr; - EXPECT(make_painted(hdr, 80, 60, DXGI_FORMAT_R10G10B10A2_UNORM)); - const auto code = [](double nits) { return int(std::lround(pq_encode(nits) * 1023.0)); }; - EXPECT(paint10(hdr, {0, 0, 27, 60}, code(203), code(203), code(203))); - EXPECT(paint10(hdr, {27, 0, 54, 60}, code(600), code(150), code(20))); - EXPECT(paint10(hdr, {54, 0, 80, 60}, code(40), code(80), code(120))); - one = parameters(hdr.source, nullptr, xbox_scale_filter_point, rt::d3d12::xbox_color_space_g2084_p2020); - EXPECT(present_planes(&one, 1) && composed_ok()); - Ref_plane href = model(hdr, nullptr, true, nullptr, true); - const bool surface_hdr = xbox.presenter().hdr_active(); - if (!surface_hdr) { - EXPECT(frame_matches(frame, &href, 1, false, 203.0, 2)); - std::printf("compose: HDR10 plane to an SDR swapchain (tone mapped to SDR, white = 203 nits, peak 1000): within 2 levels of the model\n"); - } else { - // A real HDR10 swapchain: the 10-bit codes come out as they went in (plane 0, point, 1:1 PQ). Vulkan packing: - // A2B10G10R10 has R in bits 0-9 and B in 20-29, A2R10G10B10 the reverse; G is bits 10-19 in both. - EXPECT(frame.format == VK_FORMAT_A2B10G10R10_UNORM_PACK32 || frame.format == VK_FORMAT_A2R10G10B10_UNORM_PACK32); - const bool abgr = frame.format == VK_FORMAT_A2B10G10R10_UNORM_PACK32; - bool ok = true; - for (UINT y = 0; y < height && ok; y += 7) - for (UINT x = 0; x < width && ok; x += 5) { - std::uint32_t word; - std::memcpy(&word, &frame.bytes[(std::size_t(y) * frame.extent.width + x) * 4], 4); - const int lo = int(word & 1023), g = int((word >> 10) & 1023), hi = int((word >> 20) & 1023); - const int got[3] = {abgr ? lo : hi, g, abgr ? hi : lo}; - const auto src = hdr.tex.px[std::size_t(y / 4) * 80 + x / 4]; - int want[3]; - for (int c = 0; c < 3; ++c) { - want[c] = int(std::lround(src[c] * 1023.0)); - ok = ok && std::abs(got[c] - want[c]) <= 1; - } - if (!ok) - std::fprintf(stderr, "HDR10 pixel %u,%u is %d,%d,%d, expected %d,%d,%d\n", x, y, got[0], got[1], got[2], - want[0], want[1], want[2]); - } - EXPECT(ok); - std::printf("compose: HDR10 plane to an HDR10 (ST.2084) swapchain: R, G and B codes within 1 of the source: ok\n"); - } - // Same plane, conversions to the PQ encoding of an 8-bit swapchain (test hook): an SDR overlay over it. - xbox.presenter().force_hdr_encoding(true); - pair[0] = parameters(hdr.source, nullptr, xbox_scale_filter_point, rt::d3d12::xbox_color_space_g2084_p2020); - pair[1] = parameters(ui.source, &middle_half, xbox_scale_filter_point, 0, rt::d3d12::xbox_plane_flag_overlay); - EXPECT(present_planes(pair, 2) && composed_ok()); - Ref_plane hrefs[2] = {model(hdr, nullptr, true, nullptr, true), model(ui, &middle_half, true)}; - if (!surface_hdr) { - EXPECT(frame_matches(frame, hrefs, 2, true, 203.0, 2)); - std::printf("compose: HDR10 plane + SDR overlay in PQ encoding (8-bit, forced): within 2 levels of the model\n"); - } - // SDR planes into PQ: the SDR white of the quad's white corner goes to 203 nits. - pair[0] = parameters(quad.source, nullptr, xbox_scale_filter_point); - pair[1] = parameters(ui.source, &middle_half, xbox_scale_filter_point, 0, rt::d3d12::xbox_plane_flag_overlay); - EXPECT(present_planes(pair, 2) && composed_ok()); - Ref_plane srefs[2] = {model(quad, nullptr, true), model(ui, &middle_half, true)}; - if (!surface_hdr) { - EXPECT(frame_matches(frame, srefs, 2, true, 203.0, 2)); - std::printf("compose: SDR planes converted to PQ (forced): within 2 levels of the model\n"); - } - xbox.presenter().force_hdr_encoding(false); - // The HDR plane reaches the SDR swapchain again after an HDR request on a surface that has none. - if (!surface_hdr) { - xbox.set_sdr_white_nits(100.0f); - one = parameters(hdr.source, nullptr, xbox_scale_filter_point, rt::d3d12::xbox_color_space_g2084_p2020); - EXPECT(present_planes(&one, 1) && composed_ok()); - EXPECT(frame_matches(frame, &href, 1, false, 100.0, 2)); - xbox.set_sdr_white_nits(203.0f); - std::printf("compose: SDR white level 100 nits applies: ok\n"); - } else { - std::printf("compose: the surface has HDR10: the forced-encoding checks are skipped on it\n"); - } - if (!surface_hdr) - std::printf("compose: HDR10 swapchain: this surface/display lists no ST.2084 format, so only the SDR tone map and " - "the PQ encoder were run (HDR10 swapchain case skipped)\n"); - - // C2: linear-light blending and the SDR EOTF option. A 50% white overlay (premultiplied 128,128,128 alpha 128) over - // black is half the light: byte 188 with piecewise sRGB, 186 with gamma 2.2 (blending the encoded values would give - // 128), checked against the model and against these numbers. - { - Painted black, half_white; - EXPECT(make_painted(black, width, height)); - EXPECT(paint(black, {0, 0, LONG(width), LONG(height)}, 0, 0, 0, 255)); - EXPECT(make_painted(half_white, 8, 8)); - EXPECT(paint(half_white, {0, 0, 8, 8}, 128, 128, 128, 128)); - pair[0] = parameters(black.source, nullptr, xbox_scale_filter_point); - pair[1] = parameters(half_white.source, nullptr, xbox_scale_filter_point, 0, rt::d3d12::xbox_plane_flag_overlay); - Ref_plane lrefs[2] = {model(black, nullptr, true), model(half_white, nullptr, true)}; - const double alpha = 128.0 / 255.0; - for (const bool g22 : {false, true}) { - xbox.set_sdr_eotf(g22 ? leonida::PresentPlanes::SdrEotf::gamma22 : leonida::PresentPlanes::SdrEotf::srgb); - xbox_present_ref::gamma22 = g22; - EXPECT(present_planes(pair, 2) && composed_ok()); - EXPECT(frame_matches(frame, lrefs, 2, false, 203.0, 1)); - // the overlay's white, as light (premultiplied 128/255 over alpha 0.502 is white): 0.502 of full white - const int want = int(std::lround(255 * xbox_present_ref::sdr_encode(alpha))); - EXPECT(region_is(frame, 0, 0, width, height, {want, want, want}, 1)); - // independent of the model's formulas (hand calculation: 0.50196 as light is 187.8 and 186.4 in bytes) - EXPECT(region_is(frame, 0, 0, width, height, g22 ? Px{186, 186, 186} : Px{188, 188, 188}, 1)); - std::printf("compose: 50%% white over black, %s: byte %d (model %d, encoded-space blend would be 128)\n", - g22 ? "gamma 2.2" : "piecewise sRGB", frame.at(10, 10).r, want); - // an SDR plane 0 alone through the same EOTF: bytes come out as they went in - one = parameters(quad.source, nullptr, xbox_scale_filter_point); - EXPECT(present_planes(&one, 1) && composed_ok()); - Ref_plane q = model(quad, nullptr, true); - EXPECT(frame_matches(frame, &q, 1, false, 203.0, 0)); - } - xbox.set_sdr_eotf(leonida::PresentPlanes::SdrEotf::srgb); - xbox_present_ref::gamma22 = false; - std::printf("compose: SDR EOTF sRGB and gamma 2.2: linear blend matches the model, single planes unchanged: ok\n"); - } - - // C3: HDR10 -> SDR output is tone mapped, not clipped: identity on luminance up to 0.8 of SDR white (162 nits), then - // a Reinhard shoulder that maps the content peak to 1.0. Eight columns of grey (50, 100, 150, 203, 300, 500, 750, 1000 - // nits). The expected bytes are hand calculations (sRGB encode of the knee curve), not the model's code; 10-bit PQ - // codes make them good to 2. - { - // the curve itself: monotonic, identity below the knee, continuous in slope, peak -> 1 - for (const double white : {203.0, 100.0}) { - double previous = -1; - for (double y = 0; y <= 20; y += 0.01) { - const double d_y = xbox_present_ref::tone_y(y, white); - EXPECT(d_y >= previous); - EXPECT(y > 0.8 || d_y == y); - previous = d_y; - } - const double lw = xbox_present_ref::hdr_peak / white; - EXPECT(std::abs(xbox_present_ref::tone_y(std::max(lw, 1.0), white) - 1.0) < 1e-12); - const double e = 1e-6; - EXPECT(std::abs((xbox_present_ref::tone_y(0.8 + e, white) - 0.8) / e - 1.0) < 1e-3); - } - } - if (!surface_hdr) { - Painted ramp; - EXPECT(make_painted(ramp, 80, 60, DXGI_FORMAT_R10G10B10A2_UNORM)); - const double ramp_nits[8] = {50, 100, 150, 203, 300, 500, 750, 1000}; - const int want_1000[8] = {136, 186, 223, 243, 250, 253, 254, 255}; - const int want_600[8] = {136, 186, 223, 244, 250, 254, 255, 255}; - for (int i = 0; i < 8; ++i) - EXPECT(paint10(ramp, {10 * i, 0, 10 * i + 10, 60}, code(ramp_nits[i]), code(ramp_nits[i]), code(ramp_nits[i]))); - for (const float peak_nits : {1000.0f, 600.0f}) { - xbox.set_hdr_peak_nits(peak_nits); - xbox_present_ref::hdr_peak = peak_nits; - one = parameters(ramp.source, nullptr, xbox_scale_filter_point, rt::d3d12::xbox_color_space_g2084_p2020); - EXPECT(present_planes(&one, 1) && composed_ok()); - Ref_plane rref = model(ramp, nullptr, true, nullptr, true); - EXPECT(frame_matches(frame, &rref, 1, false, 203.0, 2)); - const int* want = peak_nits == 1000.0f ? want_1000 : want_600; - int previous = -1; - bool ok = true; - for (int i = 0; i < 8; ++i) { - const Px got = frame.at(UINT(i * 40 + 20), 10); - ok = ok && std::abs(got.r - want[i]) <= 2 && got.r >= previous; - previous = got.r; - } - EXPECT(ok); - // SDR-range content (100 and 150 nits are below the knee) is not touched by the tone map - EXPECT(std::abs(frame.at(60, 10).r - 186) <= 2 && std::abs(frame.at(100, 10).r - 223) <= 2); - std::printf("compose: HDR10 ramp tone mapped onto SDR, peak %.0f nits: bytes", peak_nits); - for (int i = 0; i < 8; ++i) std::printf(" %d", frame.at(UINT(i * 40 + 20), 10).r); - std::printf(" (hand calculation:"); - for (int i = 0; i < 8; ++i) std::printf(" %d", want[i]); - std::printf(")\n"); - } - xbox.set_hdr_peak_nits(1000.0f); - xbox_present_ref::hdr_peak = 1000.0; - } - - // C4: an HDR10 plane 1 over an SDR plane 0 (the reverse of the case above), on a forced HDR10 encoding and on the SDR - // output. Plane 1 is premultiplied grey of 400 nits at alpha 2/3 (stored code = PQ(400) * 2/3), plane 0 black. As - // light the result is 266.7 nits (PQ byte 155, hand calculation) on the HDR10 output; on the SDR output 400 nits is - // 1.97 of SDR white, shoulder-mapped to 0.973, times 2/3, sRGB encoded: byte 211. - if (!surface_hdr) { - Painted black4, hdr_ui; - EXPECT(make_painted(black4, width, height)); - EXPECT(paint(black4, {0, 0, LONG(width), LONG(height)}, 0, 0, 0, 255)); - EXPECT(make_painted(hdr_ui, 16, 16, DXGI_FORMAT_R10G10B10A2_UNORM)); - const int stored = int(std::lround(code(400) * 2.0 / 3.0)); - EXPECT(paint10a(hdr_ui, {0, 0, 16, 16}, stored, stored, stored, 2)); - pair[0] = parameters(black4.source, nullptr, xbox_scale_filter_point); - pair[1] = parameters(hdr_ui.source, nullptr, xbox_scale_filter_point, rt::d3d12::xbox_color_space_g2084_p2020, - rt::d3d12::xbox_plane_flag_overlay); - Ref_plane urefs[2] = {model(black4, nullptr, true), model(hdr_ui, nullptr, true, nullptr, true)}; - xbox.presenter().force_hdr_encoding(true); - EXPECT(present_planes(pair, 2) && composed_ok()); - EXPECT(frame_matches(frame, urefs, 2, true, 203.0, 2)); - const int hdr_byte = int(frame.at(5, 5).r); - EXPECT(region_is(frame, 0, 0, width, height, {155, 155, 155}, 3)); - xbox.presenter().force_hdr_encoding(false); - EXPECT(present_planes(pair, 2) && composed_ok()); - EXPECT(frame_matches(frame, urefs, 2, false, 203.0, 2)); - EXPECT(region_is(frame, 0, 0, width, height, {211, 211, 211}, 3)); - std::printf("compose: HDR10 plane 1 (premultiplied, alpha 2/3) over SDR plane 0: HDR10 output byte %d (hand 155), SDR output byte %d (hand 211): ok\n", - hdr_byte, int(frame.at(5, 5).r)); - } - - // D: an SDR plane 1 next to an HDR10 plane 0 that is not flagged an overlay is the GameDVR copy: not shown. - pair[0] = parameters(hdr.source, nullptr, xbox_scale_filter_point, rt::d3d12::xbox_color_space_g2084_p2020); - pair[1] = parameters(second, nullptr, xbox_scale_filter_point, 0); - EXPECT(present_planes(pair, 2) && composed_ok()); - if (!surface_hdr) EXPECT(frame_matches(frame, &href, 1, false, 203.0, 2)); - std::printf("compose: HDR10 plane 0 + unflagged SDR plane 1 (GameDVR copy) shows plane 0 only: ok\n"); - - // E: a placement that is not a sub-rectangle of the output (empty, inverted, outside, NaN), an unknown filter and - // extended descriptors are ignored (logged once): the plane is shown over the whole output, point filtered. - const float nan = std::numeric_limits::quiet_NaN(); - const XboxViewRect bad_places[] = {{0.5f, 0, 0.5f, 1}, {-0.1f, 0, 1, 1}, {0, 0, 1.5f, 1}, {0, 0.75f, 1, 0.25f}, {nan, 0, 1, 1}}; - for (const XboxViewRect& bad : bad_places) { - one = parameters(quad.source, &bad, xbox_scale_filter_point); - EXPECT(present_planes(&one, 1) && composed_ok()); - Ref_plane whole = model(quad, nullptr, true); - EXPECT(frame_matches(frame, &whole, 1, false, 203.0, 0)); - } - one = parameters(quad.source, nullptr, 77); // unknown filter: default (bilinear), plain blit path - one.ExtendedDescCount = 2; - EXPECT(present_planes(&one, 1)); - std::printf("compose: implausible placement, unknown filter, extended descriptors ignored (shown, not refused): ok\n"); - // Sources the pass cannot read (depth, multisampled) are refused: nothing is presented, the token still works. - const std::uint64_t presents_before = xbox.presents(); - { - const D3D12_HEAP_PROPERTIES default_heap{D3D12_HEAP_TYPE_DEFAULT}; - const auto make_special = [&](DXGI_FORMAT format, UINT samples, D3D12_RESOURCE_FLAGS flags, Ref& out) { - D3D12_RESOURCE_DESC desc{}; - desc.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D; - desc.Width = width; - desc.Height = height; - desc.DepthOrArraySize = 1; - desc.MipLevels = 1; - desc.Format = format; - desc.SampleDesc.Count = samples; - desc.Flags = flags; - return SUCCEEDED(device->CreateCommittedResource(&default_heap, D3D12_HEAP_FLAG_ALLOW_DISPLAY, &desc, - D3D12_RESOURCE_STATE_COMMON, nullptr, IID_PPV_ARGS(&out.p))); - }; - Ref depth_plane, msaa_plane; - EXPECT(make_special(DXGI_FORMAT_D32_FLOAT, 1, D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL | D3D12_RESOURCE_FLAG_DENY_SHADER_RESOURCE, depth_plane)); - EXPECT(make_special(DXGI_FORMAT_R8G8B8A8_UNORM, 4, D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET, msaa_plane)); - ID3D12Resource* cannot[2] = {depth_plane.p, msaa_plane.p}; - for (ID3D12Resource* resource : cannot) { - rt::d3d12::XboxPresentPlaneParameters p{0, 1, &resource, nullptr, 0}; - p.ScaleFilter = xbox_scale_filter_point; - EXPECT(present_planes(&p, 1, DXGI_ERROR_UNSUPPORTED)); - } - } - EXPECT(xbox.presents() == presents_before); - EXPECT(xbox.presenter().composed_presents() == composed_expected); - one = parameters(quad.source, &middle_half, xbox_scale_filter_point); - EXPECT(present_planes(&one, 1) && composed_ok()); // still working after the refusals - std::printf("compose: bad placements, depth and multisampled sources refused: ok\n"); - - // F: the window changes size between composed presents (the swapchain is recreated, possibly in the middle of a - // present after an out-of-date acquire): the compose target follows, pixels match the model at the new size. - const UINT sizes[][2] = {{400, 300}, {200, 150}, {width, height}}; - for (const auto& size : sizes) { - RECT outer{0, 0, LONG(size[0]), LONG(size[1])}; - AdjustWindowRect(&outer, WS_OVERLAPPEDWINDOW, FALSE); - SetWindowPos(window, nullptr, 0, 0, outer.right - outer.left, outer.bottom - outer.top, - SWP_NOMOVE | SWP_NOZORDER | SWP_NOACTIVATE); - pump(); - want_w = want_h = 0; // the first present after a resize may still be at the old size (suboptimal swapchain) - for (int round = 0; round < 3; ++round) { - one = parameters(quad.source, &middle_half, xbox_scale_filter_point); - // (A present the driver reports out of date right after the resize is not counted as shown, so the counter - // is not checked here; the frame is still composed and read back.) - EXPECT(present_planes(&one, 1)); - // Whatever size the frame has, it must be the composition at that size (no stale or mis-sized target). - Ref_plane resized = model(quad, &middle_half, true); - resized.dest[0] = middle_half.left * double(frame.extent.width); - resized.dest[1] = middle_half.top * double(frame.extent.height); - resized.dest[2] = middle_half.right * double(frame.extent.width); - resized.dest[3] = middle_half.bottom * double(frame.extent.height); - EXPECT(frame_matches(frame, &resized, 1, false, 203.0, 0)); - if (round == 2) EXPECT(frame.extent.width == size[0] && frame.extent.height == size[1]); - } - } - want_w = width; - want_h = height; - composed_expected = xbox.presenter().composed_presents(); - std::printf("compose: window resized 320x240 -> 400x300 -> 200x150 -> 320x240 between composed presents: ok\n"); - } - - // Skipping a frame (waiting twice, presenting the second token) is fine. - std::uint64_t skipped = 0; - clock.advance_us(4 * period); - EXPECT(next_token(skipped) && next_token(token) && token == skipped + 1); - plane = plane_of(rgba, token); - EXPECT(xbox.PresentX(1, &plane, nullptr) == S_OK); - std::printf("token validation: ok\n"); - - // Statistics for the frame just presented: event and present now, display after the next vblank. - UINT count = 3; - leonida::FrameStatistic stats[3]; - EXPECT(xbox.GetFrameStatisticsX(token, leonida::stat_frame_event | leonida::stat_present | leonida::stat_display, - &count, stats) == S_FALSE); - EXPECT(count == 2 && stats[0].type == leonida::stat_frame_event && stats[1].type == leonida::stat_present); - clock.advance_us(period); - count = 3; - EXPECT(xbox.GetFrameStatisticsX(token, leonida::stat_frame_event | leonida::stat_present | leonida::stat_display, - &count, stats) == S_OK); - EXPECT(count == 3 && stats[2].type == leonida::stat_display && stats[2].token == token); - count = 3; - EXPECT(xbox.GetFrameStatisticsX(99999, leonida::stat_display, &count, stats) == S_FALSE && count == 0); - std::printf("frame statistics: ok\n"); - - // Suspend: presents are refused and the registration is gone; after resume it has to be redone. - EXPECT(next_token(token)); - EXPECT(xbox.SuspendX(0) == S_OK); - plane = plane_of(rgba, token); - EXPECT(xbox.PresentX(1, &plane, nullptr) == invalid_state); - EXPECT(xbox.PresentX(0, nullptr, nullptr) == invalid_state); - EXPECT(xbox.WaitFrameEventX(rt::d3d12::xbox_frame_event_origin, 0, 0, &token) == invalid_state); - EXPECT(xbox.ResumeX() == S_OK); - EXPECT(xbox.WaitFrameEventX(rt::d3d12::xbox_frame_event_origin, 0, 0, &token) == invalid_state); // not re-registered - EXPECT(xbox.PresentX(0, nullptr, nullptr) == S_OK); // a blank present needs no registration - EXPECT(SUCCEEDED(xbox.SetFrameIntervalX(nullptr, period, 1, 0))); - EXPECT(SUCCEEDED(xbox.ScheduleFrameEventX(rt::d3d12::xbox_frame_event_origin, 0, 0))); - const std::uint64_t before_resume = xbox.pacer().tokens_issued(); - EXPECT(next_token(token) && token == before_resume + 1); - plane = plane_of(rgba, token); - EXPECT(xbox.PresentX(1, &plane, nullptr) == S_OK); - EXPECT(grab(frame)); - EXPECT(region_is(frame, 0, 0, width, height, {51, 153, 230})); - std::printf("suspend/resume with re-registration: ok\n"); - - // ImmediateThresholdPercent: a frame that missed its vblank by less than the threshold is shown at once (mid-scan, - // IMMEDIATE or FIFO_RELAXED), else it waits; the decision is the pacer's lateness on the fake clock, and the - // display statistic and immediate_presents() tell which way it went. Without VK_*_swapchain_maintenance1 (or - // an IMMEDIATE/FIFO_RELAXED mode the swapchain can switch to) the frame always waits. - { - const bool can_tear = xbox.presenter().tear_supported(); - std::printf("tearing present mode available: %s (device swapchain_maintenance1: %s)\n", - can_tear ? "yes" : "no", d.swapchain_maintenance1 ? "yes" : "no"); - EXPECT(d.swapchain_maintenance1 || !can_tear); - clock.advance_us(4 * period); // everything in flight is shown - EXPECT(SUCCEEDED(xbox.SetFrameIntervalX(nullptr, period, 1, 0))); - EXPECT(SUCCEEDED(xbox.ScheduleFrameEventX(rt::d3d12::xbox_frame_event_origin, 0, 0))); - EXPECT(xbox.pacer().frames_in_flight() == 0); - const std::uint64_t grid_epoch = clock.now_us(); // vblanks are at grid_epoch + n * period - const std::uint64_t tears_before = xbox.immediate_presents(); - std::uint64_t expected_tears = tears_before; - // One frame: wait for its origin, spend `late_us` after the vblank it was due at, present with `threshold`. - // Checks the pixels, whether it was shown at once and the display statistic. - const auto frame_with = [&](std::uint64_t late_us, float threshold, bool pass_params, bool expect_tear) -> bool { - std::uint64_t t = 0; - const std::uint64_t now = clock.now_us(); // to the next vblank: origin n - clock.advance_us(grid_epoch + ((now - grid_epoch) / period + 1) * period - now); - if (xbox.WaitFrameEventX(rt::d3d12::xbox_frame_event_origin, 0, 0, &t) != S_OK) return false; - clock.advance_us(period + late_us); // due at vblank n + 1; now = due + late_us - rt::d3d12::XboxPresentParameters params{threshold}; - auto p = plane_of(rgba, t); - if (xbox.PresentX(1, &p, pass_params ? ¶ms : nullptr) != S_OK) return false; - if (!grab(frame) || !region_is(frame, 0, 0, width, height, {51, 153, 230})) return false; - if (expect_tear) ++expected_tears; - if (xbox.immediate_presents() != expected_tears) { - std::fprintf(stderr, "late %llu us, threshold %g: immediate_presents %llu, expected %llu\n", - static_cast(late_us), double(threshold), - static_cast(xbox.immediate_presents()), - static_cast(expected_tears)); - return false; - } - // The display statistic: at once (display time = present time, scan position = lateness) or at a vblank. - clock.advance_us(period); // past the next vblank: shown either way - leonida::FrameStatistic stats[2]; - UINT count = 2; - if (xbox.GetFrameStatisticsX(t, leonida::stat_present | leonida::stat_display, &count, stats) != S_OK || - count != 2) - return false; - const bool at_once = stats[1].time_us == stats[0].time_us; - if (at_once != expect_tear) { - std::fprintf(stderr, "late %llu us, threshold %g: shown at once = %d, expected %d\n", - static_cast(late_us), double(threshold), int(at_once), int(expect_tear)); - return false; - } - const float want_percent = expect_tear ? 100.0f * float(late_us) / float(period) : 0.0f; - return std::fabs(stats[1].percent_scanned - want_percent) < 0.01f; - }; - const bool t = can_tear; - // The period is 16667 us: 8000 us is 48% of it, 2000 us 12%, 1000 us 6%. - EXPECT(frame_with(8000, 60.0f, true, t)); // 48% scanned, threshold 60%: shown at once - EXPECT(frame_with(8000, 49.0f, true, t)); // just inside the threshold - EXPECT(frame_with(8000, 47.0f, true, false)); // the scan is past 47%: waits for the vblank - EXPECT(frame_with(8000, 0.0f, true, false)); // threshold 0 disables it - EXPECT(frame_with(8000, 0.0f, false, false)); // no parameters: the same - EXPECT(frame_with(8000, -10.0f, true, false)); - EXPECT(frame_with(0, 100.0f, true, false)); // on time: nothing to tear - EXPECT(frame_with(1000, 100.0f, true, t)); // 100: a late flip anywhere in the scan - EXPECT(frame_with(15000, 100.0f, true, t)); - EXPECT(frame_with(2000, 10.0f, true, false)); // 12% scanned, threshold 10 - EXPECT(frame_with(2000, 13.0f, true, t)); - EXPECT(xbox.immediate_presents() == expected_tears); - std::printf("ImmediateThresholdPercent (%s): ok, %llu of 11 frames shown at once\n", - can_tear ? "tearing present mode in use" : "unsupported here, frames wait", - static_cast(xbox.immediate_presents() - tears_before)); - if (can_tear) EXPECT(xbox.presenter().tear_presents() == xbox.immediate_presents() - tears_before); - } - - owner.reset(); // one swapchain per window: the first presenter goes - // Kill switch: LEONIDA_PRESENT_NO_TEAR=1 keeps the swapchain FIFO-only, so a late frame with a threshold waits. - { - _putenv_s("LEONIDA_PRESENT_NO_TEAR", "1"); - auto no_tear = rt::d3d12::create_window_presenter(inner, window); - _putenv_s("LEONIDA_PRESENT_NO_TEAR", ""); - EXPECT(no_tear && no_tear->enable_capture()); - EXPECT(!no_tear->tear_supported()); - leonida::ManualFrameClock fake; - rt::d3d12::XboxPresentation fifo_only(std::move(no_tear), &fake); - EXPECT(SUCCEEDED(fifo_only.SetFrameIntervalX(nullptr, period, 1, 0))); - EXPECT(SUCCEEDED(fifo_only.ScheduleFrameEventX(rt::d3d12::xbox_frame_event_origin, 0, 0))); - fake.advance_us(period); - std::uint64_t t = 0; - EXPECT(fifo_only.WaitFrameEventX(rt::d3d12::xbox_frame_event_origin, 0, 0, &t) == S_OK); - fake.advance_us(period + 8000); // half an interval late - rt::d3d12::XboxPresentParameters fifo_params{100.0f}; - auto p = plane_of(rgba, t); - EXPECT(fifo_only.PresentX(1, &p, &fifo_params) == S_OK); - EXPECT(fifo_only.immediate_presents() == 0 && fifo_only.pacer().frames_in_flight() == 1); - EXPECT(fifo_only.presenter().read_back(frame.bytes, &frame.extent, &frame.format)); - EXPECT(region_is(frame, 0, 0, width, height, {51, 153, 230})); - std::printf("no tearing mode (LEONIDA_PRESENT_NO_TEAR): late frame waits for the vblank: ok\n"); - } - // The device a title holds is the Xbox-ABI proxy, not `inner`: the presenter comes from it all the same - // (D3D-414: it used to be null, with nothing in the log). - { - auto from_proxy = rt::d3d12::create_window_presenter(device.p, window); - EXPECT(from_proxy && from_proxy->enable_capture()); - EXPECT(SUCCEEDED(from_proxy->present_blank(1))); - std::printf("presenter from the Xbox device proxy: created, a blank frame presented: ok\n"); - } - // Real time, 60 Hz: 30 frames cycling through three colours; tokens count up one per wait, each frame shows - // the colour that was presented, and the loop takes about 30 vblanks. - auto presenter2 = rt::d3d12::create_window_presenter(inner, window); - EXPECT(presenter2 && presenter2->enable_capture()); - rt::d3d12::XboxPresentation real(std::move(presenter2)); // the real clock - Source colours[3]; - const FLOAT* wanted[3] = {red, green, blue}; - const Px expect_rgb[3] = {{255, 0, 0}, {0, 255, 0}, {0, 0, 255}}; - for (int i = 0; i < 3; ++i) EXPECT(make_source(DXGI_FORMAT_R8G8B8A8_UNORM, colours[i]) && fill(colours[i], wanted[i])); - EXPECT(SUCCEEDED(real.SetFrameIntervalX(nullptr, period, 1, 0))); - EXPECT(SUCCEEDED(real.ScheduleFrameEventX(rt::d3d12::xbox_frame_event_origin, 0, 0))); - constexpr int frames = 30; - const auto start = std::chrono::steady_clock::now(); - std::uint64_t last = 0; - // One real-time frame: wait for the origin, present colour `c`. True with `shown` false when the present was - // skipped because the window is minimised (PresentX still S_OK, nothing on screen, nothing to read back). - const auto real_frame = [&](int c, bool& shown) -> bool { - pump(); - std::uint64_t t = 0; - if (real.WaitFrameEventX(rt::d3d12::xbox_frame_event_origin, 1000, 0, &t) != S_OK || t != last + 1) { - std::fprintf(stderr, "real time: token %llu after %llu\n", static_cast(t), - static_cast(last)); - return false; - } - last = t; - auto p = plane_of(colours[c], t); - if (real.PresentX(1, &p, nullptr) != S_OK) return false; - shown = real.presenter().read_back(frame.bytes, &frame.extent, &frame.format); - if (!shown) return IsIconic(window) != FALSE; // skipped only while minimised - const Px got = frame.at(width / 2, height / 2); - if (close_to(got, expect_rgb[c], 0)) return true; - std::fprintf(stderr, "real time: centre %d,%d,%d, presented %d,%d,%d\n", got.r, got.g, got.b, expect_rgb[c].r, - expect_rgb[c].g, expect_rgb[c].b); - return false; - }; - // Someone at the desktop can minimise the window during the loop (Win+D in the middle of a CTest run): those - // presents are skipped, and the window is restored so the rest of the loop is seen again. - int unseen = 0; - for (int i = 0; i < frames; ++i) { - bool shown = false; - EXPECT(real_frame(i % 3, shown)); - if (!shown) { - ++unseen; - ShowWindow(window, SW_RESTORE); - } - } - const auto ms = std::chrono::duration_cast(std::chrono::steady_clock::now() - start).count(); - std::printf("real time: %d frames at 60 Hz in %lld ms (ideal %d), %d skipped while minimised\n", frames, - static_cast(ms), frames * int(period) / 1000, unseen); - EXPECT(ms >= (frames - 1) * int(period) / 1000 * 9 / 10 && ms < 5000); - EXPECT(unseen < frames); - - // Minimised on purpose: the surface is 0x0 (VK_KHR_win32_surface), so PresentX succeeds without showing the - // frame, and read_back must say so rather than hand out the frame before it (TEST-378: the real-time loop - // above once compared that older frame). Each colour differs from the one shown last, so a stale frame fails. - // Restored, the next frame is shown and read back again. - { - ShowWindow(window, SW_MINIMIZE); - int skipped_presents = 0; - for (int i = 0; i < 3; ++i) { // the first present can still reach the old swapchain (then out of date) - bool shown = true; - EXPECT(real_frame(i, shown)); - if (!shown) ++skipped_presents; - } - EXPECT(skipped_presents > 0); - ShowWindow(window, SW_RESTORE); - bool shown = false; - for (int i = 0; i < 3 && !shown; ++i) EXPECT(real_frame((i + 1) % 3, shown)); // stale, then recreated - EXPECT(shown); - std::printf("minimised: %d of 3 presents skipped and not read back; restored: shown again\n", skipped_presents); - } - EXPECT(real.PresentX(0, nullptr, nullptr) == S_OK); // the shutdown blank - } - DestroyWindow(window); - UnregisterClassW(window_class.lpszClassName, window_class.hInstance); - - const unsigned validation_errors = d.validation_errors(); - const unsigned known_errors = d.known_validation_errors(); - if (validation_errors != known_errors) { - std::fprintf(stderr, "%u validation errors (%u known sRGB swapchain checks)\n", validation_errors, - known_errors); - return 1; - } - if (known_errors) { - std::fprintf(stderr, "%u known sRGB swapchain STORAGE validation errors; skipped\n", known_errors); - return 77; - } - std::printf("xbox_present_test: all cases pass\n"); - return 0; -} diff --git a/runtime/test/xdxr_build_output.h b/runtime/test/xdxr_build_output.h deleted file mode 100644 index 8693ecad5..000000000 --- a/runtime/test/xdxr_build_output.h +++ /dev/null @@ -1,18 +0,0 @@ -#pragma once - -#include - -inline std::error_code prepare_xdxr_build_output(const std::filesystem::path& dir, bool timing_only) { - if (timing_only) return {}; - - std::error_code ec; - std::filesystem::create_directories(dir, ec); - if (ec) return ec; - - // A failed run must not leave the previous run's cases for the checker to pass. - for (const auto& entry : std::filesystem::directory_iterator(dir, ec)) { - const auto ext = entry.path().extension(); - if (ext == ".bin" || ext == ".json") std::filesystem::remove(entry.path(), ec); - } - return {}; -} diff --git a/runtime/test/xdxr_build_output_test.cpp b/runtime/test/xdxr_build_output_test.cpp deleted file mode 100644 index 9113a3866..000000000 --- a/runtime/test/xdxr_build_output_test.cpp +++ /dev/null @@ -1,43 +0,0 @@ -// Exercise the fixture's output preparation without initializing Vulkan. -#include "xdxr_build_output.h" - -#include -#include -#include -#include - -namespace fs = std::filesystem; - -#define CHECK(condition) do { \ - if (!(condition)) { std::fprintf(stderr, "line %d: %s\n", __LINE__, #condition); return 1; } \ -} while (0) - -int main() { - const auto suffix = std::chrono::steady_clock::now().time_since_epoch().count(); - const auto root = fs::temp_directory_path() / ("leonida-xdxr-output-" + std::to_string(suffix)); - CHECK(fs::create_directory(root)); - struct Cleanup { - fs::path path; - ~Cleanup() { std::error_code ec; fs::remove_all(path, ec); } - } cleanup{root}; - - const auto output = root / "relocated" / "xdxr_build_cases"; - CHECK(!prepare_xdxr_build_output(output, true)); - CHECK(!fs::exists(output.parent_path())); - - CHECK(!prepare_xdxr_build_output(output, false)); - CHECK(fs::is_directory(output)); - CHECK(bool(std::ofstream(output / "old.json") << "{}")); - CHECK(bool(std::ofstream(output / "old.bin") << "case")); - CHECK(bool(std::ofstream(output / "keep.txt") << "keep")); - - CHECK(!prepare_xdxr_build_output(output, true)); - CHECK(fs::is_regular_file(output / "old.json")); - CHECK(fs::is_regular_file(output / "old.bin")); - - CHECK(!prepare_xdxr_build_output(output, false)); - CHECK(!fs::exists(output / "old.json")); - CHECK(!fs::exists(output / "old.bin")); - CHECK(fs::is_regular_file(output / "keep.txt")); - CHECK(prepare_xdxr_build_output(output / "keep.txt", false)); -} diff --git a/runtime/test/xdxr_descs_test.cpp b/runtime/test/xdxr_descs_test.cpp deleted file mode 100644 index 209fd4fcc..000000000 --- a/runtime/test/xdxr_descs_test.cpp +++ /dev/null @@ -1,156 +0,0 @@ -// src/xdxr_descs.h: the XDXR build descriptions measured in XboxBvhBuilder.dll (docs/xdxr.md). The layouts are -// static_asserts in the header; this checks the stream lookup and the flag defaults against the DLL's measured -// behaviour, and, where the Windows SDK is available, that the public part matches d3d12.h. No GPU, no game files. -#include "../src/xdxr_descs.h" - -#include -#include - -#if defined(_WIN32) && __has_include() -#ifndef WIN32_LEAN_AND_MEAN -#define WIN32_LEAN_AND_MEAN -#endif -#include -#include -// Older d3d12.h headers (MinGW's, for one) have no DXR types. -#ifdef D3D12_RAYTRACING_ACCELERATION_STRUCTURE_BYTE_ALIGNMENT -#define XDXR_HAVE_D3D12 1 -#endif -#endif - -#define CHECK(condition) do { \ - if (!(condition)) { \ - std::fprintf(stderr, "line %d: %s\n", __LINE__, #condition); \ - return 1; \ - } \ -} while (0) - -using namespace leonida::xdxr; - -namespace { - -StreamDesc stream_of(const StreamRecord* records, size_t count) { - return StreamDesc{count * sizeof(StreamRecord), records}; -} - -int stream_lookup() { - StreamRecord records[4] = {}; - - // No stream, a zero size or a null pointer: every setting keeps its default. - CHECK(find_stream_record(StreamDesc{}, 0) == nullptr); - CHECK(find_stream_record(StreamDesc{0, records}, 0) == nullptr); - CHECK(find_stream_record(StreamDesc{sizeof(records), nullptr}, 0) == nullptr); - - // Types 0, 1 and 2 are stepped over until the wanted one. - records[0].type = 2; - records[1].type = 0; - records[2].type = 1; - const StreamDesc three = stream_of(records, 3); - CHECK(find_stream_record(three, 0) == &records[1]); - CHECK(find_stream_record(three, 1) == &records[2]); - CHECK(find_stream_record(three, 2) == &records[0]); - - // The first record of a type wins. - records[3].type = 0; - CHECK(find_stream_record(stream_of(records, 4), 0) == &records[1]); - - // Any other type ends the walk, so records after it are not seen. - records[0].type = 3; - CHECK(find_stream_record(three, 0) == nullptr); - CHECK(find_stream_record(three, 2) == nullptr); - // ...but a match before it is still found. - records[0].type = 0; - records[1].type = 7; - CHECK(find_stream_record(three, 0) == &records[0]); - CHECK(find_stream_record(three, 1) == nullptr); - - // Nothing past SizeInBytes is read. - records[0].type = 1; - records[1].type = 0; - CHECK(find_stream_record(stream_of(records, 1), 0) == nullptr); - CHECK(find_stream_record(stream_of(records, 2), 0) == &records[1]); - return 0; -} - -int flag_defaults() { - CHECK(default_record0_value_08(0) == 1.005f); - CHECK(default_record0_value_08(kBuildFlagPreferFastTrace) == 0.0f); - CHECK(default_record0_value_08(kBuildFlagMinimizeMemory) == 1.01f); - CHECK(default_record0_value_08(kBuildFlagPreferFastTrace | kBuildFlagMinimizeMemory) == 1.005f); - // Other bits (ALLOW_UPDATE, ALLOW_COMPACTION, PREFER_FAST_BUILD, PERFORM_UPDATE) don't change it. - CHECK(default_record0_value_08(0x01 | 0x02 | 0x08 | 0x20) == 1.005f); - return 0; -} - -int record_views() { - // The typed views alias the generic record: the type word is shared and the payload starts at 4. - StreamRecord record = {}; - record.type = 1; - record.payload[0x0d - 4] = 9; - record.payload[0x0e - 4] = 1; - StreamRecord1 one; - std::memcpy(&one, &record, sizeof(one)); - CHECK(one.type == 1 && one.level_0d == 9 && one.flag_0e == 1); - return 0; -} - -#ifdef XDXR_HAVE_D3D12 -// The public part of BATCHED_DESC2 is the public build desc, as the DLL's standard-build export copies it. -static_assert(sizeof(D3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_INPUTS) == sizeof(BuildInputs)); -static_assert(offsetof(D3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_INPUTS, Flags) == offsetof(BuildInputs, flags)); -static_assert(offsetof(D3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_INPUTS, NumDescs) == - offsetof(BuildInputs, num_descs)); -static_assert(offsetof(D3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_INPUTS, DescsLayout) == - offsetof(BuildInputs, descs_layout)); -static_assert(offsetof(D3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_INPUTS, InstanceDescs) == - offsetof(BuildInputs, descs)); -static_assert(sizeof(D3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_DESC) == offsetof(BatchedDesc2, num_postbuild_info_descs)); -static_assert(offsetof(D3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_DESC, Inputs) == offsetof(BatchedDesc2, inputs)); -static_assert(offsetof(D3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_DESC, SourceAccelerationStructureData) == - offsetof(BatchedDesc2, source_acceleration_structure_data)); -static_assert(offsetof(D3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_DESC, ScratchAccelerationStructureData) == - offsetof(BatchedDesc2, scratch_acceleration_structure_data)); -static_assert(sizeof(D3D12_RAYTRACING_ACCELERATION_STRUCTURE_POSTBUILD_INFO_DESC) == sizeof(PostbuildInfoDesc)); -static_assert(offsetof(D3D12_RAYTRACING_ACCELERATION_STRUCTURE_POSTBUILD_INFO_DESC, InfoType) == - offsetof(PostbuildInfoDesc, info_type)); -// The alignment the DLL enforces on DestAccelerationStructureData. -static_assert(D3D12_RAYTRACING_ACCELERATION_STRUCTURE_BYTE_ALIGNMENT == 256); -static_assert(D3D12_RAYTRACING_ACCELERATION_STRUCTURE_BUILD_FLAG_PREFER_FAST_TRACE == kBuildFlagPreferFastTrace); -static_assert(D3D12_RAYTRACING_ACCELERATION_STRUCTURE_BUILD_FLAG_MINIMIZE_MEMORY == kBuildFlagMinimizeMemory); - -int public_desc_copy() { - D3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_DESC desc = {}; - desc.DestAccelerationStructureData = 0x100000; - desc.Inputs.Type = D3D12_RAYTRACING_ACCELERATION_STRUCTURE_TYPE_BOTTOM_LEVEL; - desc.Inputs.Flags = D3D12_RAYTRACING_ACCELERATION_STRUCTURE_BUILD_FLAG_MINIMIZE_MEMORY; - desc.Inputs.NumDescs = 3; - desc.Inputs.DescsLayout = D3D12_ELEMENTS_LAYOUT_ARRAY_OF_POINTERS; - desc.Inputs.InstanceDescs = 0x2000; - desc.SourceAccelerationStructureData = 0x300000; - desc.ScratchAccelerationStructureData = 0x400000; - BatchedDesc2 batched = {}; - std::memcpy(&batched, &desc, sizeof(desc)); - CHECK(batched.dest_acceleration_structure_data == 0x100000); - CHECK(batched.inputs.type == 1 && batched.inputs.flags == kBuildFlagMinimizeMemory); - CHECK(batched.inputs.num_descs == 3 && batched.inputs.descs_layout == 1 && batched.inputs.descs == 0x2000); - CHECK(batched.source_acceleration_structure_data == 0x300000); - CHECK(batched.scratch_acceleration_structure_data == 0x400000); - CHECK(batched.stream.size_in_bytes == 0 && batched.stream.stream == nullptr); - return 0; -} -#endif - -} // namespace - -int main() { - if (stream_lookup() || flag_defaults() || record_views()) - return 1; -#ifdef XDXR_HAVE_D3D12 - if (public_desc_copy()) - return 1; - std::printf("xdxr_descs: ok (checked against d3d12.h)\n"); -#else - std::printf("xdxr_descs: ok (no DXR d3d12.h: public layout not compared)\n"); -#endif - return 0; -} diff --git a/runtime/test/xg_xs_test.cpp b/runtime/test/xg_xs_test.cpp deleted file mode 100644 index 7db9b6096..000000000 --- a/runtime/test/xg_xs_test.cpp +++ /dev/null @@ -1,91 +0,0 @@ -// Checks the registered xg_xs.dll shim against the call shapes measured in the game executable (runtime/shims/xg_xs.cpp). -// -// Both exports are resolved through rt::shims::find, so this is the table the runtime installs. The checks: both -// return E_NOTIMPL, XGSuggestSwizzleMode leaves the caller's field alone, XGCreateTextureComputer still hands out a -// computer (two measured callers use it without checking the HRESULT), and the computer's slots called at the -// measured sites (1, 2, 8, 10) return without writing what their arguments point to. -#include - -#include -#include -#include - -#include "shims.h" - -namespace { - -using CreateFn = HRESULT(__stdcall*)(const void*, void**); -using SuggestFn = HRESULT(__stdcall*)(const void*, uint32_t, uint32_t*); -using ReleaseFn = ULONG(__stdcall*)(void*); -using Slot2Fn = HRESULT(__stdcall*)(void*, void*); -using Slot8Fn = HRESULT(__stdcall*)(void*, void*, uint32_t, uint32_t, const void*, uint32_t, uint32_t); -using Slot10Fn = HRESULT(__stdcall*)(void*, uint32_t*, void*, void*, uint32_t*, uint32_t, void*); -constexpr HRESULT kNotImpl = static_cast(rt::shims::kENotImpl); - -int g_checks = 0; -int g_failures = 0; - -void check(bool condition, const char* what) { - ++g_checks; - std::printf("%s %s\n", condition ? "PASS" : "FAIL", what); - if (!condition) ++g_failures; -} - -bool all_bytes(const uint8_t* p, size_t n, uint8_t value) { - for (size_t i = 0; i < n; ++i) - if (p[i] != value) return false; - return true; -} - -} // namespace - -int main() { - auto create = reinterpret_cast(rt::shims::find("xg_xs.dll", "XGCreateTextureComputer")); - auto suggest = reinterpret_cast(rt::shims::find("xg_xs.dll", "XGSuggestSwizzleMode")); - check(create != nullptr, "XGCreateTextureComputer is registered"); - check(suggest != nullptr, "XGSuggestSwizzleMode is registered"); - check(rt::shims::owns_dll("xg_xs.dll"), "the registry owns xg_xs.dll"); - if (!create || !suggest) return 1; - - uint8_t desc[0x38] = {}; - uint32_t mode = 0x1234; - check(suggest(desc, 0, &mode) == kNotImpl, "XGSuggestSwizzleMode returns E_NOTIMPL"); - check(mode == 0x1234, "XGSuggestSwizzleMode leaves the mode field as the caller set it"); - - check(create(desc, nullptr) == E_POINTER, "XGCreateTextureComputer(desc, nullptr) is E_POINTER"); - void* computer = nullptr; - check(create(desc, &computer) == kNotImpl, "XGCreateTextureComputer returns E_NOTIMPL"); - check(computer != nullptr, "XGCreateTextureComputer still stores a computer for the callers that do not check"); - if (!computer) return 1; - - void* const* vtable = *static_cast(computer); - uint8_t layout[0x800]; - std::memset(layout, 0xcd, sizeof(layout)); - check(reinterpret_cast(vtable[2])(computer, layout) == kNotImpl, "slot 2 returns E_NOTIMPL"); - check(all_bytes(layout, sizeof(layout), 0xcd), "slot 2 writes nothing to its output"); - - uint8_t dst[64]; - std::memset(dst, 0xcd, sizeof(dst)); - const uint8_t src[64] = {}; - check(reinterpret_cast(vtable[8])(computer, dst, 0, 0, src, 16, 64) == kNotImpl, - "slot 8 returns E_NOTIMPL"); - check(all_bytes(dst, sizeof(dst), 0xcd), "slot 8 writes nothing to its destination"); - - uint32_t count = 0, inout = 0x10; - uint8_t a[12] = {}, b[12] = {}, list[0xc0] = {}; - check(reinterpret_cast(vtable[10])(computer, &count, a, b, &inout, 0, list) == kNotImpl, - "slot 10 returns E_NOTIMPL"); - check(count == 0 && inout == 0x10 && all_bytes(a, 12, 0) && all_bytes(b, 12, 0) && - all_bytes(list, sizeof(list), 0), - "slot 10 leaves the caller's zero-filled outputs as they were"); - check(reinterpret_cast(vtable[31])(computer, layout) == kNotImpl, "the last slot (31) is traced too"); - - auto release = reinterpret_cast(vtable[1]); - release(computer); - release(computer); - check(reinterpret_cast(vtable[2])(computer, layout) == kNotImpl, - "the computer stays usable after more Releases than it was handed out"); - - std::printf("%d checks, %d failures\n", g_checks, g_failures); - return g_failures ? 1 : 0; -} diff --git a/runtime/test/xgameruntime_gamesave_test.cpp b/runtime/test/xgameruntime_gamesave_test.cpp deleted file mode 100644 index d2d7f45eb..000000000 --- a/runtime/test/xgameruntime_gamesave_test.cpp +++ /dev/null @@ -1,374 +0,0 @@ -// XGameSaveImpl through QueryApiImpl, called the way xgameruntime.lib's XGameSave* thunks call it: QueryApiImpl with -// the class id (or a later interface id), one vtable slot with `this` first. Slots follow xgameruntime-docs' layout; -// arguments, limits and error codes follow the public GDK reference. Saves go to a temporary LEONIDA_SAVE_DIR; no -// game data, nothing online. -#include - -#include -#include -#include -#include -#include -#include -#include -#include - -#include -#include -#include - -#include "shims.h" - -namespace rt::shims { -long xgameruntime_gamesave_open_handles(); -} - -namespace { - -int g_checks = 0; -int g_failures = 0; - -void check(bool condition, const char* what) { - ++g_checks; - std::printf("%s %s\n", condition ? "PASS" : "FAIL", what); - if (!condition) ++g_failures; -} - -using Handle = void*; -struct ContainerInfo { - const char* name; - const char* displayName; - uint32_t blobCount; - uint64_t totalSize; - time_t lastModifiedTime; - bool needsSync; -}; -struct BlobInfo { - const char* name; - uint32_t size; -}; -struct Blob { - BlobInfo info; - uint8_t* data; -}; - -constexpr HRESULT E_GS_INVALID_CONTAINER_NAME = static_cast(0x80830001); -constexpr HRESULT E_GS_UPDATE_TOO_BIG = static_cast(0x80830005); -constexpr HRESULT E_GS_PROVIDED_BUFFER_TOO_SMALL = static_cast(0x80830007); -constexpr HRESULT E_GS_BLOB_NOT_FOUND = static_cast(0x80830008); -constexpr HRESULT E_GS_HANDLE_EXPIRED = static_cast(0x8083000D); - -constexpr GUID kSaveClass = {0x704c3f58, 0xe629, 0x4cc2, {0xb1, 0x97, 0x30, 0x51, 0x1b, 0x99, 0x6f, 0xe2}}; -constexpr GUID kSaveImpl2 = {0x704c3f58, 0xe629, 0x4cc2, {0xb1, 0x97, 0x30, 0x51, 0x1b, 0x99, 0x6e, 0xe2}}; -constexpr GUID kSaveImpl3 = {0x1bfff3af, 0xf14a, 0x40a3, {0x8e, 0x35, 0x9a, 0xda, 0x90, 0x65, 0x93, 0xf9}}; -constexpr GUID kOther = {0x973a344e, 0x24bf, 0x4d0f, {0x84, 0x57, 0x56, 0xc5, 0x34, 0x89, 0x2b, 0x29}}; // XGameImpl - -using Query = HRESULT(WINAPI*)(const GUID*, REFIID, void**); -using Fn = void*; -Fn slot(void* obj, int index) { return (*static_cast(obj))[index]; } -template F at(void* obj, int index) { return reinterpret_cast(slot(obj, index)); } - -bool finished(XAsyncBlock* async) { return XAsyncGetStatus(async, true) != E_PENDING; } - -using Init = HRESULT(STDMETHODCALLTYPE*)(void*, Handle, const char*, bool, Handle*); -using InitAsync = HRESULT(STDMETHODCALLTYPE*)(void*, Handle, const char*, bool, XAsyncBlock*); -using ResultHandle = HRESULT(STDMETHODCALLTYPE*)(void*, XAsyncBlock*, Handle*); -using Close = void(STDMETHODCALLTYPE*)(void*, Handle); -using Quota = HRESULT(STDMETHODCALLTYPE*)(void*, Handle, int64_t*); -using WithAsync = HRESULT(STDMETHODCALLTYPE*)(void*, Handle, XAsyncBlock*); -using QuotaResult = HRESULT(STDMETHODCALLTYPE*)(void*, XAsyncBlock*, int64_t*); -using ByName = HRESULT(STDMETHODCALLTYPE*)(void*, Handle, const char*); -using ByNameAsync = HRESULT(STDMETHODCALLTYPE*)(void*, Handle, const char*, XAsyncBlock*); -using AsyncOnly = HRESULT(STDMETHODCALLTYPE*)(void*, XAsyncBlock*); -using ContainerCb = bool(CALLBACK*)(const ContainerInfo*, void*); -using BlobCb = bool(CALLBACK*)(const BlobInfo*, void*); -using GetInfo = HRESULT(STDMETHODCALLTYPE*)(void*, Handle, const char*, void*, ContainerCb); -using EnumContainers = HRESULT(STDMETHODCALLTYPE*)(void*, Handle, void*, ContainerCb); -using EnumBlobs = HRESULT(STDMETHODCALLTYPE*)(void*, Handle, void*, BlobCb); -using EnumBlobsByName = HRESULT(STDMETHODCALLTYPE*)(void*, Handle, const char*, void*, BlobCb); -using Create = HRESULT(STDMETHODCALLTYPE*)(void*, Handle, const char*, Handle*); -using Read = HRESULT(STDMETHODCALLTYPE*)(void*, Handle, const char**, uint32_t*, size_t, Blob*); -using ReadAsync = HRESULT(STDMETHODCALLTYPE*)(void*, Handle, const char**, uint32_t, XAsyncBlock*); -using ReadResult = HRESULT(STDMETHODCALLTYPE*)(void*, XAsyncBlock*, size_t, Blob*, uint32_t*); -using Write = HRESULT(STDMETHODCALLTYPE*)(void*, Handle, const char*, const uint8_t*, size_t); -using Submit = HRESULT(STDMETHODCALLTYPE*)(void*, Handle); -using FolderAsync = HRESULT(STDMETHODCALLTYPE*)(void*, Handle, const char*, XAsyncBlock*); -using FolderResult = HRESULT(STDMETHODCALLTYPE*)(void*, XAsyncBlock*, size_t, char*); -using FilesQuota = HRESULT(STDMETHODCALLTYPE*)(void*, Handle, const char*, int64_t*); - -struct Seen { - std::vector names, displays; - std::vector counts; - std::vector sizes; - int stop_after = 1000; -}; -bool CALLBACK on_container(const ContainerInfo* info, void* context) { - auto* seen = static_cast(context); - seen->names.emplace_back(info->name); - seen->displays.emplace_back(info->displayName ? info->displayName : ""); - seen->counts.push_back(info->blobCount); - seen->sizes.push_back(info->totalSize); - return static_cast(seen->names.size()) < seen->stop_after; -} -bool CALLBACK on_blob(const BlobInfo* info, void* context) { - auto* seen = static_cast(context); - seen->names.emplace_back(info->name); - seen->sizes.push_back(info->size); - return true; -} - -} // namespace - -int main() { - std::setvbuf(stdout, nullptr, _IONBF, 0); // a crash still shows the checks before it - std::printf("xgameruntime_gamesave_test: XGameSaveImpl through QueryApiImpl\n"); - const std::filesystem::path root = std::filesystem::temp_directory_path() / L"leonida_gamesave_test"; - std::error_code ec; - std::filesystem::remove_all(root, ec); - SetEnvironmentVariableW(L"LEONIDA_SAVE_DIR", root.c_str()); - - auto query = reinterpret_cast(rt::shims::find("xgameruntime.dll", "QueryApiImpl")); - check(query != nullptr, "QueryApiImpl is registered"); - if (!query) return 1; - - void* save = nullptr; - check(query(&kSaveClass, kSaveClass, &save) == S_OK && save, "QueryApiImpl hands out XGameSaveImpl for its class id"); - if (!save) return 1; - void* save2 = nullptr; - void* save3 = nullptr; - check(query(&kSaveClass, kSaveImpl2, &save2) == S_OK && save2 == save && - query(&kSaveClass, kSaveImpl3, &save3) == S_OK && save3 == save, - "IXGameSaveImpl2 and IXGameSaveImpl3 answer with the same object"); - void* none = reinterpret_cast(1); - check(query(&kSaveClass, kOther, &none) == E_NOINTERFACE && none == nullptr, "another interface id is refused"); - - Handle user = reinterpret_cast(0x1000); // XUserHandle: opaque here, only checked for null - Handle provider = nullptr; - check(at(save, 3)(save, nullptr, "SCID", false, &provider) == E_INVALIDARG && !provider, - "InitializeProvider without a user is refused"); - check(at(save, 3)(save, user, "SCID", true, &provider) == S_OK && provider, - "InitializeProvider opens the offline provider (syncOnDemand is accepted)"); - check(std::filesystem::is_directory(root / L"local-user"), "the provider's folder is \\local-user"); - - int64_t quota = 0; - check(at(save, 7)(save, provider, "a) == S_OK && quota == (int64_t{1} << 30), - "GetRemainingQuota of an empty provider is the whole 1 GiB"); - - // ---- containers and names ---- - Handle container = nullptr; - check(at(save, 16)(save, provider, "bad name", &container) == E_GS_INVALID_CONTAINER_NAME && !container, - "a container name with a space is refused"); - for (const char* bad : {"a..b", "dir/", "x.", "a/b-c/d", ""}) - check(at(save, 16)(save, provider, bad, &container) == E_GS_INVALID_CONTAINER_NAME, - "a container name against the documented rule is refused"); - check(at(save, 16)(save, provider, std::string(257, 'a').c_str(), &container) == E_GS_INVALID_CONTAINER_NAME, - "a container name over 256 characters is refused"); - check(at(save, 16)(save, provider, "slots/SAVE_00.sav-1", &container) == S_OK && container, - "a name with a path part and . - in the file part is accepted"); - check(!std::filesystem::exists(root / L"local-user" / L"slots%2FSAVE_00.sav-1"), - "a container's folder appears on its first update, not on create"); - - // ---- an update ---- - Handle update = nullptr; - check(at(save, 23)(save, container, "Story 1", &update) == S_OK && update, "CreateUpdate"); - const std::string story(5000, 'S'), profile = "profile bytes"; - check(at(save, 25)(save, update, "story", reinterpret_cast(story.data()), story.size()) == S_OK, - "SubmitBlobWrite buffers a blob"); - check(at(save, 25)(save, update, "story", reinterpret_cast("x"), 1) == E_INVALIDARG, - "a second write of the same blob in one update is refused"); - check(at(save, 25)(save, update, "profile/main", reinterpret_cast(profile.data()), - profile.size()) == S_OK, - "a blob name with a slash is accepted (it is %-encoded on disk)"); - std::vector big(16u * 1024 * 1024, 1); - check(at(save, 25)(save, update, "big", big.data(), big.size()) == E_GS_UPDATE_TOO_BIG, - "an update past 16 MB is refused"); - check(at(save, 27)(save, update) == S_OK, "SubmitUpdate commits"); - const auto dir = root / L"local-user" / L"slots%2FSAVE_00.sav-1"; - check(std::filesystem::file_size(dir / L"story") == story.size() && std::filesystem::exists(dir / L"profile%2Fmain"), - "the blobs are files, in tools/saves.py's layout and encoding"); - at(save, 24)(save, update); - - // ---- enumeration ---- - Seen containers; - check(at(save, 14)(save, provider, &containers, on_container) == S_OK && - containers.names.size() == 1 && containers.names[0] == "slots/SAVE_00.sav-1" && - containers.displays[0] == "Story 1" && containers.counts[0] == 2 && - containers.sizes[0] == story.size() + profile.size(), - "EnumerateContainerInfo: name, display name, blob count and size"); - Seen info; - check(at(save, 13)(save, provider, "slots/SAVE_00.sav-1", &info, on_container) == S_OK && - info.names.size() == 1, - "GetContainerInfo calls back for a container that exists"); - Seen missing; - check(at(save, 13)(save, provider, "nothing", &missing, on_container) == S_OK && missing.names.empty(), - "GetContainerInfo of a missing container calls nothing"); - Seen blobs; - check(at(save, 18)(save, container, &blobs, on_blob) == S_OK && blobs.names.size() == 2 && - blobs.names[0] == "profile/main" && blobs.names[1] == "story" && blobs.sizes[1] == story.size(), - "EnumerateBlobInfo lists both blobs with their decoded names and sizes"); - Seen prefixed; - check(at(save, 19)(save, container, "sto", &prefixed, on_blob) == S_OK && - prefixed.names.size() == 1 && prefixed.names[0] == "story", - "EnumerateBlobInfoByName filters by prefix"); - - // ---- reading ---- - const char* names[] = {"story", "profile/main"}; - uint32_t count = 2; - std::vector small(64); - check(at(save, 20)(save, container, names, &count, small.size(), reinterpret_cast(small.data())) == - E_GS_PROVIDED_BUFFER_TOO_SMALL, - "ReadBlobData into a buffer too small for the blobs is refused"); - std::vector buffer(1024); - count = 2; - auto* out = reinterpret_cast(buffer.data()); - check(at(save, 20)(save, container, names, &count, buffer.size() * 8, out) == S_OK && count == 2 && - std::strcmp(out[0].info.name, "story") == 0 && out[0].info.size == story.size() && - std::memcmp(out[0].data, story.data(), story.size()) == 0 && - std::strcmp(out[1].info.name, "profile/main") == 0 && - std::memcmp(out[1].data, profile.data(), profile.size()) == 0, - "ReadBlobData returns both blobs, byte for byte, pointing into the buffer"); - const char* absent[] = {"nope"}; - count = 1; - check(at(save, 20)(save, container, absent, &count, buffer.size() * 8, out) == E_GS_BLOB_NOT_FOUND, - "a blob that is not there is E_GS_BLOB_NOT_FOUND"); - count = 0; - check(at(save, 20)(save, container, nullptr, &count, buffer.size() * 8, out) == S_OK && count == 2, - "blobNames = nullptr reads every blob"); - - XAsyncBlock async{}; - check(at(save, 21)(save, container, names, 1, &async) == S_OK && finished(&async), - "ReadBlobDataAsync runs"); - size_t needed = 0; - check(XAsyncGetResultSize(&async, &needed) == S_OK && needed > story.size(), - "its result size is what the buffer needs (XAsyncGetResultSize)"); - std::vector abuf((needed + 7) / 8); - uint32_t acount = 0; - auto* aout = reinterpret_cast(abuf.data()); - check(at(save, 22)(save, &async, needed, aout, &acount) == S_OK && acount == 1 && - std::strcmp(aout[0].info.name, "story") == 0 && std::memcmp(aout[0].data, story.data(), story.size()) == 0, - "ReadBlobDataResult fills the title's buffer with one blob"); - - // ---- delete a blob, async submit ---- - check(at(save, 23)(save, container, nullptr, &update) == S_OK, "a second update"); - check(at(save, 26)(save, update, "profile/main") == S_OK, "SubmitBlobDelete"); - async = XAsyncBlock{}; - check(at(save, 28)(save, update, &async) == S_OK && finished(&async) && - at(save, 29)(save, &async) == S_OK, - "SubmitUpdateAsync commits the delete"); - check(!std::filesystem::exists(dir / L"profile%2Fmain") && std::filesystem::exists(dir / L"story"), - "the deleted blob is gone, the other stays"); - Seen after; - at(save, 14)(save, provider, &after, on_container); - check(after.displays.size() == 1 && after.displays[0] == "Story 1", "an update without a display name keeps it"); - at(save, 24)(save, update); - check(at(save, 27)(save, update) == E_GS_HANDLE_EXPIRED, "a closed update is refused"); - - // ---- quota ---- - async = XAsyncBlock{}; - int64_t aquota = 0; - check(at(save, 8)(save, provider, &async) == S_OK && finished(&async) && - at(save, 9)(save, &async, &aquota) == S_OK && - aquota == (int64_t{1} << 30) - static_cast(story.size()), - "GetRemainingQuotaAsync subtracts what the saves hold"); - - // ---- delete the container ---- - async = XAsyncBlock{}; - check(at(save, 11)(save, provider, "slots/SAVE_00.sav-1", &async) == S_OK && finished(&async) && - at(save, 12)(save, &async) == S_OK && !std::filesystem::exists(dir), - "DeleteContainerAsync removes the container"); - at(save, 17)(save, container); - - // ---- async provider, XGameSaveFiles ---- - async = XAsyncBlock{}; - Handle provider2 = nullptr; - check(at(save, 4)(save, user, "SCID", false, &async) == S_OK && finished(&async) && - at(save, 5)(save, &async, &provider2) == S_OK && provider2 && provider2 != provider, - "InitializeProviderAsync hands out a second provider"); - async = XAsyncBlock{}; - check(at(save, 30)(save, user, "SCID", &async) == S_OK && finished(&async), "FilesGetFolderWithUiAsync"); - size_t folder_size = 0; - XAsyncGetResultSize(&async, &folder_size); - std::string folder(folder_size, '\0'); - check(folder_size > 0 && at(save, 31)(save, &async, folder.size(), folder.data()) == S_OK && - std::filesystem::is_directory(std::filesystem::u8path(folder.c_str())), - "FilesGetFolderWithUiResult returns a folder that exists"); - int64_t fquota = 0; - check(at(save, 32)(save, user, "SCID", &fquota) == S_OK && fquota == (int64_t{1} << 30), - "FilesGetRemainingQuota of an empty folder"); - - // ---- a handle that outlives its container, after the heap hands the address out again ---- - // An update and an async read keep the container handle they were made from. Once that container is closed, the - // next container may get the same address; the stale update and read must still be refused, not write into or - // read from the newer container (another save). - { - Handle first = nullptr, stale_update = nullptr; - check(at(save, 16)(save, provider, "first", &first) == S_OK && - at(save, 23)(save, first, nullptr, &stale_update) == S_OK && - at(save, 25)(save, stale_update, "mine", reinterpret_cast("first's"), 7) == S_OK, - "an update of container \"first\" buffers a blob"); - XTaskQueueHandle manual = nullptr; - XTaskQueueCreate(XTaskQueueDispatchMode::Manual, XTaskQueueDispatchMode::Manual, &manual); - XAsyncBlock stale_read{}; - stale_read.queue = manual; - check(manual && at(save, 21)(save, first, nullptr, 0, &stale_read) == S_OK, - "a ReadBlobDataAsync of \"first\" waits on a manual queue"); - at(save, 17)(save, first); - - // Containers are made until one lands at the closed container's address (most heaps hand it back at once). - Handle second = nullptr; - std::vector others; - for (int i = 0; i < 4096 && !second; ++i) { - Handle c = nullptr; - if (at(save, 16)(save, provider, "second", &c) != S_OK) break; - if (c == first) second = c; - else others.push_back(c); - } - for (Handle c : others) at(save, 17)(save, c); - if (!second) { - std::printf("SKIP the heap never reused a closed container's address; the stale-handle checks need it\n"); - } else { - Handle theirs = nullptr; - check(at(save, 23)(save, second, nullptr, &theirs) == S_OK && - at(save, 25)(save, theirs, "theirs", reinterpret_cast("second's"), 8) == - S_OK && - at(save, 27)(save, theirs) == S_OK, - "container \"second\", at the closed container's address, gets a blob of its own"); - at(save, 24)(save, theirs); - check(at(save, 27)(save, stale_update) == E_GS_HANDLE_EXPIRED, - "SubmitUpdate of an update whose container was closed is refused, though a new container has its " - "address"); - check(!std::filesystem::exists(root / L"local-user" / L"second" / L"mine"), - "the stale update wrote nothing into the container that took its container's address"); - } - while (XTaskQueueDispatch(manual, XTaskQueuePort::Work, 0) || - XTaskQueueDispatch(manual, XTaskQueuePort::Completion, 0)) {} - if (second) { - size_t stale_size = 0; - const HRESULT read_hr = XAsyncGetStatus(&stale_read, false); - XAsyncGetResultSize(&stale_read, &stale_size); - check(read_hr == E_GS_HANDLE_EXPIRED && stale_size == 0, - "ReadBlobDataAsync of a closed container completes with E_GS_HANDLE_EXPIRED, not with the blobs of " - "the container that took its address"); - at(save, 17)(save, second); - } - if (XAsyncGetStatus(&stale_read, false) == S_OK) { // collect a result so the async state is released - std::vector drain(1024); - uint32_t drained = 0; - at(save, 22)(save, &stale_read, drain.size() * 8, reinterpret_cast(drain.data()), &drained); - } - at(save, 24)(save, stale_update); - if (manual) XTaskQueueCloseHandle(manual); - std::filesystem::remove_all(root / L"local-user" / L"first", ec); - std::filesystem::remove_all(root / L"local-user" / L"second", ec); - } - - at(save, 6)(save, provider); - at(save, 6)(save, provider2); - at(save, 6)(save, provider); // twice: ignored - check(at(save, 7)(save, provider, "a) == E_GS_HANDLE_EXPIRED, "a closed provider is refused"); - check(rt::shims::xgameruntime_gamesave_open_handles() == 0, "every handle the test opened is closed"); - - std::filesystem::remove_all(root, ec); - std::printf("xgameruntime_gamesave_test: %d checks, %d failures\n", g_checks, g_failures); - return g_failures == 0 ? 0 : 1; -} diff --git a/runtime/test/xgameruntime_offline_test.cpp b/runtime/test/xgameruntime_offline_test.cpp deleted file mode 100644 index 7668b6164..000000000 --- a/runtime/test/xgameruntime_offline_test.cpp +++ /dev/null @@ -1,334 +0,0 @@ -// XGameEventImpl, XGameUiImpl, XGameStreamingImpl, XDisplayImpl, XUserDeviceImpl, XAccessibilityImpl and XLauncherImpl -// through QueryApiImpl, called the way xgameruntime.lib's thunks -// call them: QueryApiImpl with the class id (or an interface id), one vtable slot with `this` first. Slots follow -// xgameruntime-docs' layout; arguments follow the public GDK reference. No game data; nothing online. -#include - -#include -#include -#include -#include - -#include -#include -#include - -#include "shims.h" - -namespace rt::shims { -long xgameruntime_offline_game_events(); -long xgameruntime_user_open_handles(); -long xgameruntime_offline_device_registrations(uint32_t kind); -} - -namespace { - -int g_checks = 0; -int g_failures = 0; - -void check(bool condition, const char* what) { - ++g_checks; - std::printf("%s %s\n", condition ? "PASS" : "FAIL", what); - if (!condition) ++g_failures; -} - -constexpr GUID kEventClass = {0xbbfbdcc7, 0xbfe7, 0x409b, {0xa5, 0xca, 0xed, 0xf0, 0x54, 0x96, 0x0b, 0x4d}}; -constexpr GUID kUiClass = {0xdfcd4649, 0x4ff8, 0x4043, {0xba, 0x07, 0x35, 0xd6, 0x07, 0xdf, 0x98, 0xb0}}; -constexpr GUID kUiImpl = {0x6eeaa73e, 0x9669, 0x43ad, {0xa2, 0xc7, 0xd0, 0xda, 0x4e, 0x1f, 0x50, 0xa1}}; -constexpr GUID kUiImpl4 = {0xeaf669df, 0x5542, 0x4590, {0x99, 0xa3, 0x8d, 0xc0, 0x61, 0xf8, 0x37, 0xcc}}; -constexpr GUID kStreamingClass = {0x0a2192aa, 0xb2d5, 0x4d58, {0x83, 0xbe, 0x38, 0x3b, 0x6d, 0x80, 0x79, 0x9e}}; -constexpr GUID kStreamingImpl3 = {0x57786622, 0x6605, 0x46d0, {0xb9, 0x17, 0x0f, 0x22, 0xbb, 0xcd, 0x9c, 0x52}}; - -using Query = HRESULT(WINAPI*)(const GUID*, REFIID, void**); -using Fn = void*; -Fn slot(void* obj, int index) { return (*static_cast(obj))[index]; } -template F at(void* obj, int index) { return reinterpret_cast(slot(obj, index)); } - -bool finished(XAsyncBlock* async) { return XAsyncGetStatus(async, true) != E_PENDING; } - -using EventWrite = HRESULT(STDMETHODCALLTYPE*)(void*, void*, const char*, const char*, const char*, const char*, - const char*); -using Dialog = HRESULT(STDMETHODCALLTYPE*)(void*, XAsyncBlock*, const char*, const char*, const char*, const char*, - const char*, uint32_t, uint32_t); -using DialogResult = HRESULT(STDMETHODCALLTYPE*)(void*, XAsyncBlock*, uint32_t*); -using ErrorDialog = HRESULT(STDMETHODCALLTYPE*)(void*, XAsyncBlock*, HRESULT, const char*); -using AsyncOnly = HRESULT(STDMETHODCALLTYPE*)(void*, XAsyncBlock*); -using NoArgs = HRESULT(STDMETHODCALLTYPE*)(void*); -using Bool = bool(STDMETHODCALLTYPE*)(void*); -using Count = uint32_t(STDMETHODCALLTYPE*)(void*); -using Register = HRESULT(STDMETHODCALLTYPE*)(void*, XTaskQueueHandle, void*, void*, XTaskQueueRegistrationToken*); - -using TryHdr = uint32_t(STDMETHODCALLTYPE*)(void*, uint32_t, float*); -using FindUser = HRESULT(STDMETHODCALLTYPE*)(void*, const uint8_t*, void**); -using CloseUser = void(STDMETHODCALLTYPE*)(void*, void*); -using Unregister = bool(STDMETHODCALLTYPE*)(void*, XTaskQueueRegistrationToken, bool); -using Endpoint = HRESULT(STDMETHODCALLTYPE*)(void*, uint64_t, uint32_t, size_t, wchar_t*, size_t*); -using FindController = HRESULT(STDMETHODCALLTYPE*)(void*, void*, XAsyncBlock*); -using FindControllerResult = HRESULT(STDMETHODCALLTYPE*)(void*, XAsyncBlock*, uint8_t*); - -constexpr GUID kDisplayClass = {0x03f0fe74, 0xfdd9, 0x4e5c, {0xb6, 0x30, 0xf9, 0x33, 0x9c, 0x47, 0xac, 0xc5}}; -constexpr GUID kUserDeviceClass = {0x7d824997, 0x10dc, 0x45ab, {0x86, 0xb7, 0x27, 0x37, 0x76, 0x7c, 0x0b, 0xf1}}; -constexpr GUID kUserClass = {0x01acd177, 0x91f9, 0x4763, {0xa3, 0x8e, 0xcc, 0xbb, 0x55, 0xce, 0x32, 0xe0}}; - -constexpr GUID kAccessibilityClass = {0x3e241977, 0x6237, 0x41e9, {0x85, 0x59, 0x10, 0x2c, 0x2d, 0x99, 0x83, 0xf1}}; -constexpr GUID kAccessibility2 = {0xd722b373, 0x8c4d, 0x4692, {0x9e, 0x51, 0xd6, 0xad, 0x9b, 0x37, 0xaa, 0x7d}}; -constexpr GUID kLauncherClass = {0x1b339674, 0x328d, 0x4283, {0xa2, 0x00, 0x31, 0x71, 0xf1, 0x8d, 0x36, 0x39}}; - -using EnumVoices = HRESULT(STDMETHODCALLTYPE*)(void*, void*, void*); -using SpeechCreate = HRESULT(STDMETHODCALLTYPE*)(void*, void**); -using SpeechClose = HRESULT(STDMETHODCALLTYPE*)(void*, void*); -using SpeechStream = HRESULT(STDMETHODCALLTYPE*)(void*, void*, const char*, void**); -using StreamSize = HRESULT(STDMETHODCALLTYPE*)(void*, void*, size_t*); -using StreamData = HRESULT(STDMETHODCALLTYPE*)(void*, void*, size_t, void*, size_t*); -using HighContrast = HRESULT(STDMETHODCALLTYPE*)(void*, uint32_t*); -using SetEnabled = HRESULT(STDMETHODCALLTYPE*)(void*, bool); -using LaunchUri = HRESULT(STDMETHODCALLTYPE*)(void*, void*, const char*); -using AcquireDeferral = HRESULT(STDMETHODCALLTYPE*)(void*, void**); - -void* user_object(HRESULT(WINAPI* query)(const GUID*, REFIID, void**)) { - void* user = nullptr; - query(&kUserClass, kUserClass, &user); - return user; -} - -void CALLBACK on_state(void*, uint64_t, uint32_t) {} - -// XUserDeviceImpl slots 4/5 (device association) and 7/8 (default audio endpoint): kept until unregistered, never -// called back offline. -long g_device_callbacks = 0; -void CALLBACK on_association_changed(void* context, const void*) { - ++g_device_callbacks; - if (context) ++*static_cast(context); -} -void CALLBACK on_audio_endpoint_changed(void* context, uint64_t, uint32_t, const wchar_t*) { - ++g_device_callbacks; - if (context) ++*static_cast(context); -} - -constexpr uint32_t kAssociation = 0, kAudioEndpoint = 1; // rt::shims::xgameruntime_offline_device_registrations - -void check_device_registrations(void* device) { - using rt::shims::xgameruntime_offline_device_registrations; - auto reg = [&](int slot, XTaskQueueHandle queue, void* context, void* callback, XTaskQueueRegistrationToken* t) { - return at(device, slot)(device, queue, context, callback, t); - }; - auto unreg = [&](int slot, XTaskQueueRegistrationToken t, bool wait) { - return at(device, slot)(device, t, wait); - }; - void* association = reinterpret_cast(&on_association_changed); - void* audio = reinterpret_cast(&on_audio_endpoint_changed); - - XTaskQueueRegistrationToken t{}; - check(reg(4, nullptr, nullptr, nullptr, &t) == E_INVALIDARG && reg(4, nullptr, nullptr, association, nullptr) == - E_INVALIDARG && reg(7, nullptr, nullptr, nullptr, &t) == E_INVALIDARG && - reg(7, nullptr, nullptr, audio, nullptr) == E_INVALIDARG, - "device registrations need a callback and a token (E_INVALIDARG)"); - check(xgameruntime_offline_device_registrations(kAssociation) == 0 && - xgameruntime_offline_device_registrations(kAudioEndpoint) == 0, - "a refused device registration is not kept"); - - // queue and context are optional; one registration of each kind on a manual queue the test dispatches. - XTaskQueueHandle manual = nullptr; - check(SUCCEEDED(XTaskQueueCreate(XTaskQueueDispatchMode::Manual, XTaskQueueDispatchMode::Manual, &manual)), - "create a manual queue for the device callbacks"); - long calls = 0; - XTaskQueueRegistrationToken a1{}, a2{}, e1{}, e2{}; - check(reg(4, nullptr, nullptr, association, &a1) == S_OK && reg(4, manual, &calls, association, &a2) == S_OK && - reg(7, nullptr, nullptr, audio, &e1) == S_OK && reg(7, manual, &calls, audio, &e2) == S_OK, - "device association and audio endpoint registrations succeed with or without a queue and context"); - const uint64_t tokens[] = {a1.token, a2.token, e1.token, e2.token}; - bool distinct = true; - for (int i = 0; i < 4; ++i) - for (int j = 0; j < 4; ++j) distinct = distinct && tokens[i] != 0 && (i == j || tokens[i] != tokens[j]); - check(distinct, "device registration tokens are non-zero and unique across both kinds"); - check(xgameruntime_offline_device_registrations(kAssociation) == 2 && - xgameruntime_offline_device_registrations(kAudioEndpoint) == 2, - "each device registration is kept under its token"); - - check(!XTaskQueueDispatch(manual, XTaskQueuePort::Work, 0) && - !XTaskQueueDispatch(manual, XTaskQueuePort::Completion, 0), - "nothing is queued for a device registration offline"); - // The title closing its own queue handle doesn't end a registration: the shim keeps its own reference. - XTaskQueueCloseHandle(manual); - check(xgameruntime_offline_device_registrations(kAssociation) == 2, - "a registration outlives the title's handle to its queue"); - - // A token of the other kind, one never handed out, or 0: unregistering is harmless (true) and removes nothing. - check(unreg(5, e1, true) && unreg(8, a1, false) && unreg(5, XTaskQueueRegistrationToken{0}, false) && - unreg(8, XTaskQueueRegistrationToken{~0ull}, true), - "unregistering a foreign, unissued or zero token returns true"); - check(xgameruntime_offline_device_registrations(kAssociation) == 2 && - xgameruntime_offline_device_registrations(kAudioEndpoint) == 2, - "and leaves every registration in place"); - - // Unregistering removes the registration at once, with or without wait (nothing is ever pending). - check(unreg(5, a1, false) && xgameruntime_offline_device_registrations(kAssociation) == 1, - "XUserUnregisterForDeviceAssociationChanged (wait = false) removes its registration"); - check(unreg(5, a2, true) && xgameruntime_offline_device_registrations(kAssociation) == 0 && - xgameruntime_offline_device_registrations(kAudioEndpoint) == 2, - "XUserUnregisterForDeviceAssociationChanged (wait = true) removes only its own"); - check(unreg(8, e1, true) && unreg(8, e2, false) && xgameruntime_offline_device_registrations(kAudioEndpoint) == 0, - "XUserUnregisterForDefaultAudioEndpointUtf16Changed removes its registrations"); - check(unreg(5, a1, true) && unreg(8, e2, false) && xgameruntime_offline_device_registrations(kAssociation) == 0 && - xgameruntime_offline_device_registrations(kAudioEndpoint) == 0, - "a second unregister is harmless (true)"); - - check(g_device_callbacks == 0 && calls == 0, "no device association or audio endpoint callback ever ran"); -} - -} // namespace - -int main() { - std::setvbuf(stdout, nullptr, _IONBF, 0); - std::printf("xgameruntime_offline_test: XGameEvent, XGameUi, XGameStreaming, XDisplay, XUserDevice\n"); - auto query = reinterpret_cast(rt::shims::find("xgameruntime.dll", "QueryApiImpl")); - check(query != nullptr, "QueryApiImpl is registered"); - if (!query) return 1; - - // ---- XGameEvent ---- - void* events = nullptr; - check(query(&kEventClass, kEventClass, &events) == S_OK && events, "XGameEventImpl for its class id"); - if (!events) return 1; - check(at(events, 3)(events, nullptr, "scid", "session", "GameStarted", "{}", "{}") == S_OK && - at(events, 3)(events, nullptr, "scid", "session", "LevelLoaded", nullptr, nullptr) == S_OK, - "XGameEventWrite succeeds offline"); - check(at(events, 3)(events, nullptr, "scid", "session", nullptr, nullptr, nullptr) == E_INVALIDARG, - "an event without a name is refused"); - check(rt::shims::xgameruntime_offline_game_events() == 2, "two events were counted"); - - // ---- XGameUi ---- - void* ui = nullptr; - void* ui_by_iface = nullptr; - void* ui4 = nullptr; - check(query(&kUiClass, kUiClass, &ui) == S_OK && ui && query(&kUiClass, kUiImpl, &ui_by_iface) == S_OK && - ui_by_iface == ui && query(&kUiClass, kUiImpl4, &ui4) == S_OK && ui4 == ui, - "XGameUiImpl for its class id, IXGameUiImpl and IXGameUiImpl4"); - if (!ui) return 1; - XAsyncBlock async{}; - uint32_t button = 99; - check(at(ui, 3)(ui, &async, "Corrupt save", "The save could not be loaded.", "Retry", "Start new", nullptr, - 1, 0) == S_OK && - finished(&async) && at(ui, 4)(ui, &async, &button) == S_OK && button == 1, - "a message dialog completes with its default button (Second)"); - async = XAsyncBlock{}; - check(at(ui, 3)(ui, &async, "t", "c", "OK", nullptr, nullptr, 3, 0) == E_INVALIDARG, - "a default button past Third is refused"); - async = XAsyncBlock{}; - check(at(ui, 14)(ui, &async, static_cast(0x80830003), "save") == S_OK && finished(&async) && - at(ui, 15)(ui, &async) == S_OK, - "an error dialog is logged and dismissed"); - check(at(ui, 7)(ui) == E_FAIL, "a profile card is not available offline"); - check(at(ui, 20)(ui) == E_NOTIMPL, "an unknown slot answers E_NOTIMPL"); - - // ---- XGameStreaming ---- - void* streaming = nullptr; - void* streaming3 = nullptr; - check(query(&kStreamingClass, kStreamingClass, &streaming) == S_OK && streaming && - query(&kStreamingClass, kStreamingImpl3, &streaming3) == S_OK && streaming3 == streaming, - "XGameStreamingImpl for its class id and IXGameStreamingImpl3"); - if (!streaming) return 1; - check(at(streaming, 3)(streaming) == S_OK, "XGameStreamingInitialize succeeds"); - check(!at(streaming, 5)(streaming), "XGameStreamingIsStreaming is false"); - check(at(streaming, 9)(streaming) == 0, "no streaming clients"); - check(at(streaming, 11)(streaming) == 0, "the connection state is the first enumerator"); - XTaskQueueRegistrationToken token{}; - check(at(streaming, 12)(streaming, nullptr, nullptr, reinterpret_cast(&on_state), &token) == S_OK && - token.token != 0 && at(streaming, 13)(streaming), - "connection-state registration hands out a token; unregistering is never pending"); - check(FAILED(at(streaming, 10)(streaming)) && !at(streaming, 21)(streaming), - "a per-client call fails as an HRESULT and reads false as a bool"); - - // ---- XDisplay ---- - void* display = nullptr; - check(query(&kDisplayClass, kDisplayClass, &display) == S_OK && display, "XDisplayImpl for its class id"); - if (!display) return 1; - float info[3] = {1, 2, 3}; - const uint32_t hdr = at(display, 4)(display, 0, info); - char hdr_env[4] = {}; - size_t hdr_len = 0; - const bool want_hdr = getenv_s(&hdr_len, hdr_env, "LEONIDA_HDR") == 0 && std::strcmp(hdr_env, "1") == 0; - check(want_hdr ? hdr == 1 && info[1] == 1000.0f : hdr == 2 && info[0] == 0 && info[1] == 0 && info[2] == 0, - want_hdr ? "LEONIDA_HDR=1: HDR is enabled with the documented defaults" - : "XDisplayTryEnableHdrMode: Disabled (SDR output), the info cleared"); - check(at(display, 4)(display, 1, nullptr) == hdr, "the info pointer is optional"); - - // ---- XUserDevice ---- - void* device = nullptr; - check(query(&kUserDeviceClass, kUserDeviceClass, &device) == S_OK && device, "XUserDeviceImpl for its class id"); - if (!device) return 1; - uint8_t device_id[32] = {7}; - void* user = nullptr; - check(at(device, 3)(device, device_id, &user) == S_OK && user, "XUserFindForDevice: the offline user"); - check(rt::shims::xgameruntime_user_open_handles() == 1, "the handle is an XUserHandle the title closes"); - at(user_object(query), 4)(user_object(query), user); - check(rt::shims::xgameruntime_user_open_handles() == 0, "XUserCloseHandle closes it"); - check_device_registrations(device); - wchar_t endpoint[8] = {L'x'}; - size_t used = 99; - check(FAILED(at(device, 6)(device, 1, 0, 8, endpoint, &used)) && endpoint[0] == 0 && used == 0, - "no audio endpoint of the user's own"); - async = XAsyncBlock{}; - uint8_t found[32]; - std::memset(found, 0xAB, sizeof(found)); - bool zero = true; - check(at(device, 9)(device, reinterpret_cast(1), &async) == S_OK && finished(&async) && - at(device, 10)(device, &async, found) == S_OK, - "XUserFindControllerForUserWithUi completes without UI"); - for (uint8_t b : found) zero = zero && b == 0; - check(zero, "with an all-zero device id, as on desktop"); - - // ---- XAccessibility ---- - void* acc = nullptr; - void* acc2 = nullptr; - check(query(&kAccessibilityClass, kAccessibilityClass, &acc) == S_OK && acc && - query(&kAccessibilityClass, kAccessibility2, &acc2) == S_OK && acc2 == acc, - "XAccessibilityImpl for its class id and IXAccessibilityImpl2"); - if (!acc) return 1; - uint32_t contrast = 7; - check(at(acc, 5)(acc, &contrast) == S_OK && contrast == 0 && - at(acc, 5)(acc, nullptr) == E_POINTER, - "XHighContrastGetMode reports Off"); - check(at(acc, 4)(acc, true) == S_OK, "XClosedCaptionSetEnabled is accepted"); - check(FAILED(at(acc, 3)(acc)), "the closed-caption properties are not available offline"); - check(at(acc, 8)(acc, reinterpret_cast(&on_state), nullptr) == S_OK && - at(acc, 8)(acc, nullptr, nullptr) == E_INVALIDARG, - "XSpeechSynthesizerEnumerateInstalledVoices: no voices, S_OK (a callback is required)"); - void* synth = reinterpret_cast(1); - check(at(acc, 9)(acc, &synth) == E_FAIL && synth == nullptr, - "XSpeechSynthesizerCreate fails offline and nulls the handle"); - void* stream = reinterpret_cast(1); - size_t size = 5, got = 5; - check(at(acc, 10)(acc, nullptr) == E_INVALIDARG && at(acc, 11)(acc, nullptr) == E_INVALIDARG && - at(acc, 12)(acc, nullptr) == E_INVALIDARG && at(acc, 14)(acc, nullptr) == E_INVALIDARG, - "close and set-voice calls on a null handle: E_INVALIDARG"); - check(at(acc, 13)(acc, nullptr, "hi", &stream) == E_INVALIDARG && stream == nullptr, - "CreateStreamFromText on a null synthesizer: E_INVALIDARG, no stream"); - stream = reinterpret_cast(1); - check(at(acc, 21)(acc, nullptr, "", &stream) == E_INVALIDARG && stream == nullptr, - "CreateStreamFromSsml on a null synthesizer: E_INVALIDARG, no stream"); - check(at(acc, 15)(acc, nullptr, &size) == E_INVALIDARG && size == 0 && - at(acc, 16)(acc, nullptr, 8, nullptr, &got) == E_INVALIDARG && got == 0, - "stream size and data on a null stream: E_INVALIDARG, zero written"); - bool speech_to_text_fails = true; - for (int slot : {6, 7, 17, 18, 19, 20}) speech_to_text_fails = speech_to_text_fails && FAILED(at(acc, slot)(acc)); - check(speech_to_text_fails, "speech-to-text display calls fail offline"); - - // ---- XLauncher ---- - void* launcher = nullptr; - check(query(&kLauncherClass, kLauncherClass, &launcher) == S_OK && launcher, "XLauncherImpl for its class id"); - if (!launcher) return 1; - void* deferral = reinterpret_cast(1); - check(at(launcher, 3)(launcher, nullptr, "https://example.com") == E_FAIL, - "XLaunchUri is not available offline"); - check(at(launcher, 4)(launcher, &deferral) == E_FAIL && deferral == nullptr && - at(launcher, 5)(launcher) == E_FAIL, - "the display timeout deferral is not available offline"); - GUID other = kLauncherClass; - other.Data1 ^= 1; - void* none = reinterpret_cast(1); - check(query(&kLauncherClass, other, &none) == E_NOINTERFACE && none == nullptr, - "XLauncherImpl refuses an interface id it doesn't implement"); - - std::printf("xgameruntime_offline_test: %d checks, %d failures\n", g_checks, g_failures); - return g_failures == 0 ? 0 : 1; -} diff --git a/runtime/test/xgameruntime_store_test.cpp b/runtime/test/xgameruntime_store_test.cpp deleted file mode 100644 index 732f864a0..000000000 --- a/runtime/test/xgameruntime_store_test.cpp +++ /dev/null @@ -1,188 +0,0 @@ -// XStoreImpl through QueryApiImpl, called the way xgameruntime.lib's XStore* thunks call it: QueryApiImpl with the -// class id (or a later interface id), one vtable slot with `this` first. Slots follow xgameruntime-docs' layout; -// arguments follow the public GDK reference. No game data; nothing online. -#include - -#include -#include -#include -#include -#include - -#include -#include -#include - -#include "shims.h" - -namespace rt::shims { -long xgameruntime_store_open_handles(); -} - -namespace { - -int g_checks = 0; -int g_failures = 0; - -void check(bool condition, const char* what) { - ++g_checks; - std::printf("%s %s\n", condition ? "PASS" : "FAIL", what); - if (!condition) ++g_failures; -} - -using Handle = void*; -struct GameLicense { // XStoreGameLicense with the measured sizes of xgameruntime_store.cpp - char skuStoreId[18]; - bool isActive; - bool isTrialOwnedByThisUser; - bool isDiscLicense; - bool isTrial; - uint32_t trialTimeRemainingInSeconds; - char trialUniqueId[64]; - time_t expirationDate; -}; -static_assert(sizeof(GameLicense) == 104, "XStoreGameLicense is 104 bytes"); -static_assert(offsetof(GameLicense, isTrialOwnedByThisUser) == 0x13, "measured flag offset"); -static_assert(offsetof(GameLicense, trialUniqueId) == 0x1C, "measured trial-id offset"); -static_assert(offsetof(GameLicense, expirationDate) == 0x60, "measured expiration offset"); -struct CanAcquire { - char licensableSku[5]; - uint32_t status; -}; - -constexpr GUID kStoreClass = {0x0dd112ac, 0x7c24, 0x448c, {0xb9, 0x2b, 0x39, 0x60, 0xfb, 0x5b, 0xd3, 0x0c}}; -constexpr GUID kStoreImpl6 = {0xb09d803c, 0x2414, 0x4a05, {0x82, 0xc6, 0x66, 0xdf, 0xdc, 0x9e, 0x9a, 0x44}}; -constexpr GUID kStoreImpl2 = {0x60b09f4e, 0x1b85, 0x45b1, {0x82, 0x6c, 0x16, 0x91, 0x18, 0xe2, 0x30, 0xe1}}; -constexpr GUID kOther = {0x973a344e, 0x24bf, 0x4d0f, {0x84, 0x57, 0x56, 0xc5, 0x34, 0x89, 0x2b, 0x29}}; // XGameImpl - -using Query = HRESULT(WINAPI*)(const GUID*, REFIID, void**); -using Fn = void*; -Fn slot(void* obj, int index) { return (*static_cast(obj))[index]; } -template F at(void* obj, int index) { return reinterpret_cast(slot(obj, index)); } - -bool finished(XAsyncBlock* async) { return XAsyncGetStatus(async, true) != E_PENDING; } - -using CreateContext = HRESULT(STDMETHODCALLTYPE*)(void*, Handle, Handle*); -using Close = void(STDMETHODCALLTYPE*)(void*, Handle); -using CtxAsync = HRESULT(STDMETHODCALLTYPE*)(void*, Handle, XAsyncBlock*); -using CtxIdAsync = HRESULT(STDMETHODCALLTYPE*)(void*, Handle, const char*, XAsyncBlock*); -using LicenseResult = HRESULT(STDMETHODCALLTYPE*)(void*, XAsyncBlock*, GameLicense*); -using CanResult = HRESULT(STDMETHODCALLTYPE*)(void*, XAsyncBlock*, CanAcquire*); -using HandleResult = HRESULT(STDMETHODCALLTYPE*)(void*, XAsyncBlock*, Handle*); -using Count = HRESULT(STDMETHODCALLTYPE*)(void*, XAsyncBlock*, uint32_t*); -using Items = HRESULT(STDMETHODCALLTYPE*)(void*, XAsyncBlock*, uint32_t, void*); -using IsValid = bool(STDMETHODCALLTYPE*)(void*, Handle); -using ProductsAsync = HRESULT(STDMETHODCALLTYPE*)(void*, Handle, uint32_t, const char**, size_t, const char**, size_t, - XAsyncBlock*); -using Enumerate = HRESULT(STDMETHODCALLTYPE*)(void*, Handle, void*, void*); -using Register = HRESULT(STDMETHODCALLTYPE*)(void*, Handle, XTaskQueueHandle, void*, void(CALLBACK*)(void*), - XTaskQueueRegistrationToken*); -using Unregister = bool(STDMETHODCALLTYPE*)(void*, Handle, XTaskQueueRegistrationToken, bool); -using NoArgs = HRESULT(STDMETHODCALLTYPE*)(void*); - -int g_callbacks = 0; -void CALLBACK on_change(void*) { ++g_callbacks; } -bool CALLBACK on_product(void*, void*) { - ++g_callbacks; - return true; -} - -} // namespace - -int main() { - std::setvbuf(stdout, nullptr, _IONBF, 0); - std::printf("xgameruntime_store_test: XStoreImpl through QueryApiImpl\n"); - auto query = reinterpret_cast(rt::shims::find("xgameruntime.dll", "QueryApiImpl")); - check(query != nullptr, "QueryApiImpl is registered"); - if (!query) return 1; - - void* store = nullptr; - check(query(&kStoreClass, kStoreClass, &store) == S_OK && store, "QueryApiImpl hands out XStoreImpl for its class id"); - if (!store) return 1; - void* store6 = nullptr; - void* store2 = nullptr; - check(query(&kStoreClass, kStoreImpl6, &store6) == S_OK && store6 == store && - query(&kStoreClass, kStoreImpl2, &store2) == S_OK && store2 == store, - "IXStoreImpl2 and IXStoreImpl6 answer with the same object"); - void* none = reinterpret_cast(1); - check(query(&kStoreClass, kOther, &none) == E_NOINTERFACE && none == nullptr, "another interface id is refused"); - - Handle context = nullptr; - check(at(store, 3)(store, reinterpret_cast(0x1000), &context) == S_OK && context, - "XStoreCreateContext"); - - // ---- the game license, as a title checks it at boot ---- - XAsyncBlock async{}; - GameLicense license; - std::memset(&license, 0xCD, sizeof(license)); - check(at(store, 28)(store, context, &async) == S_OK && finished(&async), - "XStoreQueryGameLicenseAsync completes"); - size_t license_size = 0; - check(XAsyncGetResultSize(&async, &license_size) == S_OK && license_size == 104, - "the game license result size is the measured 104 bytes"); - check(at(store, 29)(store, &async, &license) == S_OK, "XStoreQueryGameLicenseResult"); - check(license.isActive && !license.isTrial && !license.isTrialOwnedByThisUser && !license.isDiscLicense && - license.trialTimeRemainingInSeconds == 0 && license.trialUniqueId[0] == '\0' && - std::strcmp(license.skuStoreId, "0010") == 0, - "the game license is active, not a trial, every other field cleared"); - check(at(store, 28)(store, nullptr, &async) == E_INVALIDARG, "a null store context is refused"); - - // ---- add-ons and updates: none ---- - async = XAsyncBlock{}; - uint32_t count = 99; - check(at(store, 30)(store, context, &async) == S_OK && finished(&async) && - at(store, 31)(store, &async, &count) == S_OK && count == 0 && - at(store, 32)(store, &async, 0, nullptr) == S_OK, - "no add-on licenses"); - async = XAsyncBlock{}; - count = 99; - check(at(store, 55)(store, context, &async) == S_OK && finished(&async) && - at(store, 56)(store, &async, &count) == S_OK && count == 0, - "no game or DLC package updates"); - - // ---- package licenses ---- - async = XAsyncBlock{}; - Handle package_license = nullptr; - check(at(store, 20)(store, context, "SomePackage", &async) == S_OK && finished(&async) && - at(store, 21)(store, &async, &package_license) == S_OK && package_license, - "XStoreAcquireLicenseForPackage hands out a license"); - check(at(store, 22)(store, package_license), "the package license is valid"); - async = XAsyncBlock{}; - CanAcquire can{}; - check(at(store, 26)(store, context, "SomePackage", &async) == S_OK && finished(&async) && - at(store, 27)(store, &async, &can) == S_OK && can.status == 1, - "XStoreCanAcquireLicenseForPackage: Licensable"); - XTaskQueueRegistrationToken token{}; - check(at(store, 68)(store, package_license, nullptr, nullptr, on_change, &token) == S_OK && - token.token != 0 && at(store, 69)(store, package_license, token, false), - "license-lost registration hands out a token; unregistering is never pending"); - at(store, 23)(store, package_license); - check(!at(store, 22)(store, package_license), "a closed license is not valid"); - - // ---- product queries are empty ---- - async = XAsyncBlock{}; - Handle products = nullptr; - const char* ids[] = {"9NBLGGH4R315"}; - check(at(store, 7)(store, context, 1, ids, 1, nullptr, 0, &async) == S_OK && finished(&async) && - at(store, 8)(store, &async, &products) == S_OK && products, - "XStoreQueryProducts completes with a query handle"); - check(at(store, 15)(store, products, nullptr, reinterpret_cast(&on_product)) == S_OK && - !at(store, 16)(store, products), - "the query has no products and no further pages"); - at(store, 19)(store, products); - - // ---- what needs the service fails before starting ---- - check(at(store, 49)(store) == E_FAIL, "XStoreShowPurchaseUIAsync is not available offline"); - check(at(store, 46)(store) == E_NOTIMPL, "an undocumented slot answers E_NOTIMPL"); - - check(at(store, 66)(store, context, nullptr, nullptr, on_change, &token) == S_OK && - at(store, 67)(store, context, token, true), - "license-changed registration"); - check(g_callbacks == 0, "no callback ran: nothing changes offline"); - at(store, 4)(store, context); - at(store, 4)(store, context); // twice: ignored - check(rt::shims::xgameruntime_store_open_handles() == 0, "every handle the test opened is closed"); - - std::printf("xgameruntime_store_test: %d checks, %d failures\n", g_checks, g_failures); - return g_failures == 0 ? 0 : 1; -} diff --git a/runtime/test/xgameruntime_test.cpp b/runtime/test/xgameruntime_test.cpp deleted file mode 100644 index af67045d4..000000000 --- a/runtime/test/xgameruntime_test.cpp +++ /dev/null @@ -1,1168 +0,0 @@ -// Checks the registered xgameruntime shim the way a GDK title uses it at boot. -// -// Every function is resolved through rt::shims::find("xgameruntime.dll", name), the same table the loader binds -// imports to. The sequence follows a typical title: initialize the runtime, query the device, create a queue whose -// work runs on the thread pool and whose completions the game loop dispatches by hand, run async work on it and on -// the process queue, drive a custom XAsyncBegin provider to a result, then uninitialize. No game data; nothing -// online. -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include -#include -#include - -#include "file_system.h" -#include "shims.h" - -namespace { - -int g_checks = 0; -int g_failures = 0; - -void check(bool condition, const char* what) { - ++g_checks; - std::printf("%s %s\n", condition ? "PASS" : "FAIL", what); - if (!condition) ++g_failures; -} - -template -Fn get(const char* name) { - return reinterpret_cast(rt::shims::find("xgameruntime.dll", name)); -} - -using InitFn = HRESULT(__stdcall*)(); -using UninitFn = void(__stdcall*)(); -using DeviceTypeFn = uint32_t(__stdcall*)(); -using ConsoleIdFn = HRESULT(__stdcall*)(size_t, char*, size_t*); -using QueueCreateFn = HRESULT(__stdcall*)(XTaskQueueDispatchMode, XTaskQueueDispatchMode, XTaskQueueHandle*); -using QueueCloseFn = void(__stdcall*)(XTaskQueueHandle); -using QueueDispatchFn = bool(__stdcall*)(XTaskQueueHandle, XTaskQueuePort, uint32_t); -using QueueProcessFn = bool(__stdcall*)(XTaskQueueHandle*); -using AsyncRunFn = HRESULT(__stdcall*)(XAsyncBlock*, XAsyncWork*); -using AsyncStatusFn = HRESULT(__stdcall*)(XAsyncBlock*, bool); -using AsyncBeginFn = HRESULT(__stdcall*)(XAsyncBlock*, void*, const void*, const char*, XAsyncProvider*); -using AsyncScheduleFn = HRESULT(__stdcall*)(XAsyncBlock*, uint32_t); -using AsyncCompleteFn = void(__stdcall*)(XAsyncBlock*, HRESULT, size_t); -using AsyncResultSizeFn = HRESULT(__stdcall*)(XAsyncBlock*, size_t*); -using AsyncResultFn = HRESULT(__stdcall*)(XAsyncBlock*, const void*, size_t, void*, size_t*); - -struct alignas(8) XVersion { - uint16_t major; - uint16_t minor; - uint16_t build; - uint16_t revision; -}; -static_assert(sizeof(XVersion) == 8, "XVersion must be 8 bytes per GDK spec"); - -struct XSystemAnalyticsInfo { - XVersion osVersion; - XVersion hostingOsVersion; - char family[64]; - char form[64]; -}; -static_assert(sizeof(XSystemAnalyticsInfo) == 144, "XSystemAnalyticsInfo must be 144 bytes per GDK spec"); - -struct XPackageMountHandle { - uint64_t handle; -}; - -using AnalyticsInfoFn = XSystemAnalyticsInfo(__stdcall*)(); -using PackageIdentifierFn = HRESULT(__stdcall*)(size_t, char*); -using PackageMountFn = HRESULT(__stdcall*)(const char*, XPackageMountHandle*); -using PackageCloseMountHandleFn = void(__stdcall*)(XPackageMountHandle); -using PackageMountPathSizeFn = HRESULT(__stdcall*)(XPackageMountHandle, size_t*); -using PackageMountPathFn = HRESULT(__stdcall*)(XPackageMountHandle, size_t, char*); -using PackagedProcessFn = bool(__stdcall*)(); - -const char* const kNames[] = { - "XGameRuntimeInitialize", "XGameRuntimeUninitialize", "XSystemGetDeviceType", "XSystemGetConsoleId", - "XSystemGetAnalyticsInfo", "XPackageGetCurrentProcessPackageIdentifier", "XPackageMount", - "XPackageCloseMountHandle", "XPackageGetMountPathSize", "XPackageGetMountPath", - "XPackageIsPackagedProcess", - "XTaskQueueCreate", "XTaskQueueCreateComposite", "XTaskQueueGetPort", "XTaskQueueDuplicateHandle", - "XTaskQueueCloseHandle", "XTaskQueueTerminate", "XTaskQueueDispatch", "XTaskQueueSubmitCallback", - "XTaskQueueSubmitDelayedCallback", "XTaskQueueRegisterWaiter", "XTaskQueueUnregisterWaiter", - "XTaskQueueRegisterMonitor", "XTaskQueueUnregisterMonitor", "XTaskQueueGetCurrentProcessTaskQueue", - "XTaskQueueSetCurrentProcessTaskQueue", "XAsyncGetStatus", "XAsyncGetResultSize", "XAsyncCancel", "XAsyncRun", - "XAsyncBegin", "XAsyncSchedule", "XAsyncComplete", "XAsyncGetResult", -}; - -std::atomic g_work_runs{0}; -std::atomic g_work_thread{0}; -std::atomic g_completions{0}; -std::atomic g_completion_thread{0}; - -HRESULT CALLBACK work(XAsyncBlock* b) { - g_work_thread = GetCurrentThreadId(); - ++g_work_runs; - *static_cast(b->context) = 42; - return S_OK; -} - -void CALLBACK completed(XAsyncBlock*) { - g_completion_thread = GetCurrentThreadId(); - ++g_completions; -} - -// A provider that produces a 4-byte result on the queue's work port: the shape GDK async APIs use internally. -struct ProviderState { - AsyncCompleteFn complete; - std::atomic ops{0}; -}; - -HRESULT CALLBACK provider(XAsyncOp op, const XAsyncProviderData* data) { - auto* st = static_cast(data->context); - st->ops |= 1 << static_cast(op); - switch (op) { - case XAsyncOp::DoWork: - st->complete(data->async, S_OK, sizeof(uint32_t)); - return S_OK; - case XAsyncOp::GetResult: - *static_cast(data->buffer) = 0x1EA0; - return S_OK; - default: - return S_OK; - } -} - -HMODULE g_teardown_rt_mod = nullptr; -FARPROC(WINAPI* g_teardown_get_proc)(HMODULE, LPCSTR) = nullptr; -BOOL(WINAPI* g_teardown_free_lib)(HMODULE) = nullptr; - -// Registered with std::atexit before check_run_time_load() constructs any function-local statics in library_loader. -// LIFO atexit order means this runs after those statics would have been destroyed, simulating mapped-DLL -// DLL_PROCESS_DETACH or earlier atexit handlers calling GetProcAddress/FreeLibrary on a pseudo-handle during exit. -void check_late_teardown() { - if (!g_teardown_rt_mod || !g_teardown_get_proc || !g_teardown_free_lib) return; - if (g_teardown_get_proc(g_teardown_rt_mod, "UninitializeApiImpl") == nullptr) { - std::fprintf(stderr, "FAIL late teardown GetProcAddress on pseudo-handle\n"); - std::_Exit(1); - } - SetLastError(0); - if (g_teardown_get_proc(g_teardown_rt_mod, "LateTeardownMissingSymbol") != nullptr || - GetLastError() != ERROR_PROC_NOT_FOUND) { - std::fprintf(stderr, "FAIL late teardown unserved GetProcAddress on pseudo-handle\n"); - std::_Exit(1); - } - if (g_teardown_free_lib(g_teardown_rt_mod) != TRUE) { - std::fprintf(stderr, "FAIL late teardown FreeLibrary on pseudo-handle\n"); - std::_Exit(1); - } -} - -// ---- The classes measured with tools/gdk_runtime_calls.py ---- -// -// Each is asked for exactly as its thunks in the package's libHttpClient.GDK.dll ask: QueryApiImpl with the class id -// and the measured interface id, then one slot with `this` first and the documented arguments, then Release. - -using QueryFn = HRESULT(WINAPI*)(const GUID*, REFIID, void**); - -template F method(void* obj, int index) { return reinterpret_cast((*static_cast(obj))[index]); } -void release_object(void* obj) { method(obj, 2)(obj); } -void* ask(QueryFn query, const GUID& cls, const GUID& iid) { - void* p = nullptr; - return query(&cls, iid, &p) == S_OK ? p : nullptr; -} - -const GUID kSystem5Id = {0x1861cf2e, 0xe18b, 0x4834, {0xa9, 0xf5, 0xb4, 0xa4, 0xe6, 0xef, 0xb4, 0xcf}}; -const GUID kIUnknownId = {0x00000000, 0x0000, 0x0000, {0xc0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x46}}; - -// XGameRuntimeFeatureImpl and XSystemAnalyticsImpl. -void check_measured_classes(QueryFn query, XSystemAnalyticsInfo (*named_analytics)()) { - const GUID feature_cls = {0x8836fe87, 0xedb9, 0x4fe3, {0x8d, 0xad, 0x05, 0xf0, 0xd2, 0xcd, 0x5b, 0x40}}; - void* f = ask(query, feature_cls, feature_cls); - check(f != nullptr, "QueryApiImpl hands out XGameRuntimeFeatureImpl for its class id"); - if (f) { - using Available = bool(STDMETHODCALLTYPE*)(void*, uint32_t); // bool, per Microsoft's reference page - auto available = method(f, 3); - // XGameRuntimeFeature values: XAccessibility 0, XLauncher 9, XSpeechSynthesizer 13, XAsync 2, XAsyncProvider 3, XDisplay 4, XGame 5, XGameSave 7, XGameUI 8, - // XNetworking 10, XPackage 11, XPersistentLocalStorage 12, XStore 14, XSystem 15, XTaskQueue 16, XThread 17, - // XUser 18, XError 19, XGameEvent 20, XGameStreaming 21. - bool served = true; - for (uint32_t v : {0u, 2u, 3u, 5u, 7u, 9u, 13u, 8u, 10u, 11u, 12u, 14u, 15u, 16u, 17u, 18u, 19u, 20u, 21u}) - served = served && available(f, v); - check(served, "slot 3 (XGameRuntimeIsFeatureAvailable): true for the features whose classes are served, " - "XPersistentLocalStorage among them"); - check(!available(f, 4) && !available(f, 22) && !available(f, 0xFFFFFFFFu), - "slot 3: false for XDisplay (served, but documented for the consoles only) and values past the enum"); - // Every feature but XDisplay follows whether QueryApiImpl serves its class, whichever file serves it. - const struct { - uint32_t feature; - GUID cls; - } follow[] = { - {0, {0x3e241977, 0x6237, 0x41e9, {0x85, 0x59, 0x10, 0x2c, 0x2d, 0x99, 0x83, 0xf1}}}, // XAccessibility - {1, {0xa4f1aee2, 0x4bf1, 0x4485, {0xb0, 0x08, 0xa7, 0xc2, 0x6d, 0x52, 0xac, 0x27}}}, // XAppCapture - {2, {0x073b7dcb, 0x1fcf, 0x4030, {0x94, 0xbe, 0xe3, 0xc9, 0xeb, 0x62, 0x34, 0x28}}}, // XAsync - {5, {0x973a344e, 0x24bf, 0x4d0f, {0x84, 0x57, 0x56, 0xc5, 0x34, 0x89, 0x2b, 0x29}}}, // XGame - {6, {0x0651aae2, 0x4012, 0x4077, {0xbf, 0x84, 0x8b, 0x90, 0x97, 0x09, 0x0e, 0x2c}}}, // XGameInvite - {7, {0x704c3f58, 0xe629, 0x4cc2, {0xb1, 0x97, 0x30, 0x51, 0x1b, 0x99, 0x6f, 0xe2}}}, // XGameSave - {8, {0xdfcd4649, 0x4ff8, 0x4043, {0xba, 0x07, 0x35, 0xd6, 0x07, 0xdf, 0x98, 0xb0}}}, // XGameUI - {9, {0x1b339674, 0x328d, 0x4283, {0xa2, 0x00, 0x31, 0x71, 0xf1, 0x8d, 0x36, 0x39}}}, // XLauncher - {10, {0x37e56907, 0x2f10, 0x41e8, {0xb7, 0x2f, 0x36, 0xed, 0xb1, 0x85, 0x33, 0x1a}}}, // XNetworking - {11, {0xaf406016, 0xe850, 0x4aa8, {0xa8, 0x8d, 0x2f, 0x3d, 0xcb, 0x9d, 0xac, 0x7e}}}, // XPackage - {12, {0xf4faf4d4, 0x2d04, 0x4fce, {0xb3, 0xe0, 0x47, 0x4a, 0x71, 0x3a, 0x3e, 0x84}}}, // XPersistentLocalStorage - {13, {0x3e241977, 0x6237, 0x41e9, {0x85, 0x59, 0x10, 0x2c, 0x2d, 0x99, 0x83, 0xf1}}}, // XSpeechSynthesizer - {14, {0x0dd112ac, 0x7c24, 0x448c, {0xb9, 0x2b, 0x39, 0x60, 0xfb, 0x5b, 0xd3, 0x0c}}}, // XStore - {15, {0xe349bd1a, 0xfc20, 0x4e40, {0xb9, 0x9c, 0x41, 0x78, 0xcc, 0x6b, 0x40, 0x9f}}}, // XSystem - {18, {0x01acd177, 0x91f9, 0x4763, {0xa3, 0x8e, 0xcc, 0xbb, 0x55, 0xce, 0x32, 0xe0}}}, // XUser - {19, {0x8ca467f7, 0x22e8, 0x4096, {0x84, 0x56, 0xbb, 0x8a, 0xa1, 0x3f, 0x79, 0xd8}}}, // XError - {20, {0xbbfbdcc7, 0xbfe7, 0x409b, {0xa5, 0xca, 0xed, 0xf0, 0x54, 0x96, 0x0b, 0x4d}}}, // XGameEvent - {21, {0x0a2192aa, 0xb2d5, 0x4d58, {0x83, 0xbe, 0x38, 0x3b, 0x6d, 0x80, 0x79, 0x9e}}}, // XGameStreaming - }; - bool consistent = true; - for (const auto& entry : follow) { - void* obj = nullptr; - const bool class_served = query(&entry.cls, kIUnknownId, &obj) != static_cast(0x80070032); - if (obj) release_object(obj); - consistent = consistent && available(f, entry.feature) == class_served; - } - check(consistent, "slot 3: every other feature is available exactly when QueryApiImpl serves its class"); - release_object(f); - } - - // A member function returning a struct, called the way MSVC calls one (the result's address after `this`, the - // same address back in rax): what the thunk does. - struct AnalyticsView { - virtual HRESULT STDMETHODCALLTYPE QueryInterface(REFIID, void**) = 0; - virtual ULONG STDMETHODCALLTYPE AddRef() = 0; - virtual ULONG STDMETHODCALLTYPE Release() = 0; - virtual XSystemAnalyticsInfo STDMETHODCALLTYPE GetAnalyticsInfo() = 0; - }; - const GUID analytics_cls = {0xb884675d, 0xb738, 0x4a9c, {0x81, 0x5d, 0x9a, 0x9a, 0x1e, 0x0c, 0x6c, 0x9b}}; - void* a = ask(query, analytics_cls, analytics_cls); - check(a != nullptr, "QueryApiImpl hands out XSystemAnalyticsImpl for its class id"); - if (a) { - const XSystemAnalyticsInfo via_slot = static_cast(a)->GetAnalyticsInfo(); - const XSystemAnalyticsInfo named = named_analytics(); - check(std::memcmp(&via_slot, &named, sizeof named) == 0 && std::strcmp(via_slot.family, "Xbox") == 0, - "slot 3 (XSystemGetAnalyticsInfo) returns the named export's struct by value"); - void* other = reinterpret_cast(1); - check(query(&analytics_cls, kSystem5Id, &other) == E_NOINTERFACE && other == nullptr, - "XSystemAnalyticsImpl answers its class id, not another class's interface"); - release_object(a); - } - - // Classes nobody serves are still refused, and logged, as before. - const GUID refused[] = { - {0xa4f1aee2, 0x4bf1, 0x4485, {0xb0, 0x08, 0xa7, 0xc2, 0x6d, 0x52, 0xac, 0x27}}, // XAppCaptureImpl - {0x12345678, 0x9abc, 0xdef0, {0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0}}, // no such class - }; - bool all_refused = true; - for (const GUID& cls : refused) { - void* out = reinterpret_cast(1); - all_refused = all_refused && query(&cls, cls, &out) == static_cast(0x80070032) && out == nullptr; - } - check(all_refused, "XAppCaptureImpl and an unknown class are still refused"); -} - -// xgameruntime.lib's thunks don't import the runtime: they LoadLibraryW(L"xgameruntime.dll") and GetProcAddress five -// names (measured in the package's libHttpClient.GDK.dll and XCurl.dll). Drive that path through the loader shims, -// bound by the api set XCurl.dll imports them from, as a mapped image would be. -void check_run_time_load() { - using LoadW = HMODULE(WINAPI*)(LPCWSTR); - using LoadExA = HMODULE(WINAPI*)(LPCSTR, HANDLE, DWORD); - using GetModW = HMODULE(WINAPI*)(LPCWSTR); - using GetProc = FARPROC(WINAPI*)(HMODULE, LPCSTR); - using Free = BOOL(WINAPI*)(HMODULE); - const char* set = "api-ms-win-core-libraryloader-l1-2-0.dll"; - auto load_w = reinterpret_cast(rt::shims::find(set, "LoadLibraryW")); - auto load_ex_a = reinterpret_cast(rt::shims::find("kernel32.dll", "LoadLibraryExA")); - auto get_mod_w = reinterpret_cast(rt::shims::find(set, "GetModuleHandleW")); - auto get_proc = reinterpret_cast(rt::shims::find(set, "GetProcAddress")); - auto free_lib = reinterpret_cast(rt::shims::find(set, "FreeLibrary")); - check(load_w && load_ex_a && get_mod_w && get_proc && free_lib, "the loader functions are registered"); - if (!(load_w && load_ex_a && get_mod_w && get_proc && free_lib)) return; - - check(rt::shims::owns_dll("xgameruntime.dll") && !rt::shims::owns_dll("kernel32.dll") && - !rt::shims::owns_dll(set) && !rt::shims::owns_dll("nosuch.dll"), - "owns_dll: xgameruntime.dll yes; kernel32, api sets and unknown modules no"); - - HMODULE rt_mod = load_w(L"xgameruntime.dll"); - check(rt_mod != nullptr, "LoadLibraryW(xgameruntime.dll) is served without the host runtime"); - check(load_w(L"XGameRuntime") == rt_mod && load_ex_a("C:\\Some\\Dir\\XGAMERUNTIME.DLL", nullptr, 0) == rt_mod && - get_mod_w(L"xgameruntime.dll") == rt_mod, - "the same module for a bare name, a full path in any case, LoadLibraryExA and GetModuleHandleW"); - - const char* entry_points[] = {"InitializeApiImpl", "InitializeApiImplEx", "InitializeApiImplEx2", - "UninitializeApiImpl", "QueryApiImpl"}; - bool all = true; - for (const char* n : entry_points) - all = all && get_proc(rt_mod, n) && - reinterpret_cast(get_proc(rt_mod, n)) == rt::shims::find("xgameruntime.dll", n); - check(all, "GetProcAddress serves the five entry points xgameruntime.lib looks up"); - SetLastError(0); - check(get_proc(rt_mod, "NoSuchRuntimeFunction") == nullptr && GetLastError() == ERROR_PROC_NOT_FOUND, - "an unserved name is NULL with ERROR_PROC_NOT_FOUND, as from a real module"); - SetLastError(0); - check(get_proc(rt_mod, nullptr) == nullptr && GetLastError() == ERROR_PROC_NOT_FOUND, - "a null proc name is NULL with ERROR_PROC_NOT_FOUND"); - - // XCurl.dll's other way in: LoadLibraryExW(L"gameplatformservices.dll", nullptr, LOAD_LIBRARY_SEARCH_SYSTEM32), - // then GetApiVersionImpl(uint64_t*, uint64_t*) and QueryApiImpl. Served by the shims, never the PC's own. - using LoadExW = HMODULE(WINAPI*)(LPCWSTR, HANDLE, DWORD); - auto load_ex_w = reinterpret_cast(rt::shims::find(set, "LoadLibraryExW")); - HMODULE gps = load_ex_w ? load_ex_w(L"gameplatformservices.dll", nullptr, LOAD_LIBRARY_SEARCH_SYSTEM32) : nullptr; - check(rt::shims::owns_dll("gameplatformservices.dll") && gps != nullptr && gps != rt_mod, - "LoadLibraryExW(gameplatformservices.dll, SEARCH_SYSTEM32) is served by the shims"); - using ApiVersion = HRESULT(WINAPI*)(uint64_t*, uint64_t*); - auto api_version = gps ? reinterpret_cast(get_proc(gps, "GetApiVersionImpl")) : nullptr; - uint64_t v1 = 0, v2 = 0, w1 = 0, w2 = 0; - check(api_version && api_version(&v1, &v2) == S_OK && api_version(&w1, &w2) == S_OK && v1 && v2 && v1 == w1 && - v2 == w2, - "GetApiVersionImpl writes the same two non-zero versions on every call"); - check(gps && reinterpret_cast(get_proc(gps, "QueryApiImpl")) == - rt::shims::find("xgameruntime.dll", "QueryApiImpl"), - "its QueryApiImpl is the offline runtime's"); - - struct Options { - uint32_t unknown; - BOOL is_inline; - const char* game_config; - } options{1, FALSE, nullptr}; - using InitEx2 = HRESULT(WINAPI*)(ULONG, ULONG, char, const Options*); - using Query = HRESULT(WINAPI*)(const GUID*, REFIID, void**); - using Uninit = HRESULT(WINAPI*)(); - auto init_ex2 = reinterpret_cast(get_proc(rt_mod, "InitializeApiImplEx2")); - auto query = reinterpret_cast(get_proc(rt_mod, "QueryApiImpl")); - auto uninit_api = reinterpret_cast(get_proc(rt_mod, "UninitializeApiImpl")); - check(init_ex2(0x2410, 0x0, 0x02, &options) == S_OK, "InitializeApiImplEx2 succeeds offline"); - // An id no runtime class has (made up for this test). - const GUID some_class = {0x4c454f4e, 0x4944, 0x4100, {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01}}; - void* out = reinterpret_cast(1); - check(query(&some_class, some_class, &out) == static_cast(0x80070032) && out == nullptr, - "QueryApiImpl refuses a class it doesn't provide yet (HRESULT 0x80070032) and clears the out pointer"); - - // XThreadingImpl and XErrorImpl, driven the way xgameruntime.lib's thunks in the package's DLLs do: QueryApiImpl - // with the class id as both ids, one vtable slot with `this` first, then Release (slot 2). - const GUID threading = {0x073b7dcb, 0x1fcf, 0x4030, {0x94, 0xbe, 0xe3, 0xc9, 0xeb, 0x62, 0x34, 0x28}}; - const GUID error_cls = {0x8ca467f7, 0x22e8, 0x4096, {0x84, 0x56, 0xbb, 0x8a, 0xa1, 0x3f, 0x79, 0xd8}}; - using Fn = void*; - auto slot = [](void* obj, int index) { return (*static_cast(obj))[index]; }; - auto release = [&](void* obj) { reinterpret_cast(slot(obj, 2))(obj); }; - auto get = [&](const GUID& cls) { - void* p = nullptr; - return query(&cls, cls, &p) == S_OK ? p : nullptr; - }; - void* t = get(threading); - check(t != nullptr, "QueryApiImpl hands out XThreadingImpl for its class id"); - if (t) { - void* again = get(threading); - check(again == t, "XThreadingImpl is one process-wide object"); - release(again); - XTaskQueueHandle queue = nullptr; - using Create = HRESULT(STDMETHODCALLTYPE*)(void*, XTaskQueueDispatchMode, XTaskQueueDispatchMode, - XTaskQueueHandle*); - check(reinterpret_cast(slot(t, 12))(t, XTaskQueueDispatchMode::Manual, XTaskQueueDispatchMode::Manual, - &queue) == S_OK && queue, - "slot 12 is XTaskQueueCreate"); - static std::atomic s_ran{0}; - using Submit = HRESULT(STDMETHODCALLTYPE*)(void*, XTaskQueueHandle, XTaskQueuePort, void*, - XTaskQueueCallback*); - XTaskQueueCallback* cb = [](void* ctx, bool canceled) { - if (!canceled) static_cast*>(ctx)->fetch_add(1); - }; - check(reinterpret_cast(slot(t, 18))(t, queue, XTaskQueuePort::Work, &s_ran, cb) == S_OK, - "slot 18 is XTaskQueueSubmitCallback"); - using Dispatch = bool(STDMETHODCALLTYPE*)(void*, XTaskQueueHandle, XTaskQueuePort, uint32_t); - check(reinterpret_cast(slot(t, 16))(t, queue, XTaskQueuePort::Work, 0) && s_ran.load() == 1, - "slot 16 is XTaskQueueDispatch: the callback ran on the work port"); - XTaskQueueHandle dup = nullptr; - using Dup = HRESULT(STDMETHODCALLTYPE*)(void*, XTaskQueueHandle, XTaskQueueHandle*); - check(reinterpret_cast(slot(t, 15))(t, queue, &dup) == S_OK && dup, - "slot 15 is XTaskQueueDuplicateHandle"); - using Close = void(STDMETHODCALLTYPE*)(void*, XTaskQueueHandle); - reinterpret_cast(slot(t, 17))(t, dup); - reinterpret_cast(slot(t, 17))(t, queue); - using SetSensitive = HRESULT(STDMETHODCALLTYPE*)(void*, bool); - using IsSensitive = bool(STDMETHODCALLTYPE*)(void*); - check(reinterpret_cast(slot(t, 27))(t, true) == S_OK && - reinterpret_cast(slot(t, 30))(t) && - reinterpret_cast(slot(t, 27))(t, false) == S_OK && - !reinterpret_cast(slot(t, 30))(t), - "slots 27 and 30 set and read this thread's time-sensitive flag"); - // Slot 8 (XAsyncBeginAlloc, private, signature not measured) must not report a begun call whose provider - // never received XAsyncOp::Begin: either it refuses, or the provider saw Begin exactly once. - static std::atomic s_begins{0}; - XAsyncProvider* provider = [](XAsyncOp op, const XAsyncProviderData*) -> HRESULT { - if (op == XAsyncOp::Begin) s_begins.fetch_add(1); - return S_OK; - }; - XAsyncBlock alloc_block{}; - using BeginAlloc = HRESULT(STDMETHODCALLTYPE*)(void*, XAsyncBlock*, const void*, const char*, XAsyncProvider*, - size_t, size_t, void*); - const HRESULT alloc_hr = - reinterpret_cast(slot(t, 8))(t, &alloc_block, nullptr, "test", provider, 16, 0, nullptr); - check(FAILED(alloc_hr) || s_begins.load() == 1, - "slot 8 (XAsyncBeginAlloc) never reports success for a call whose provider did not begin"); - void* unk = nullptr; - const GUID iunknown = {0, 0, 0, {0xc0, 0, 0, 0, 0, 0, 0, 0x46}}; - using QI = HRESULT(STDMETHODCALLTYPE*)(void*, REFIID, void**); - check(reinterpret_cast(slot(t, 0))(t, iunknown, &unk) == S_OK && unk == t && - reinterpret_cast(slot(t, 0))(t, error_cls, &unk) == E_NOINTERFACE && !unk, - "QueryInterface answers IUnknown and the class id, not another class"); - release(t); - release(t); - } - void* e = get(error_cls); - check(e != nullptr, "QueryApiImpl hands out XErrorImpl for its class id"); - if (e) { - struct Seen { - HRESULT hr; - char msg[32]; - } seen{}; - using Callback = bool(CALLBACK*)(HRESULT, const char*, void*); - Callback on_error = [](HRESULT hr, const char* msg, void* ctx) { - auto* s = static_cast(ctx); - s->hr = hr; - strncpy_s(s->msg, msg ? msg : "", _TRUNCATE); - return true; - }; - using SetCallback = void(STDMETHODCALLTYPE*)(void*, Callback, void*); - using Report = HRESULT(STDMETHODCALLTYPE*)(void*, HRESULT, const char*); - reinterpret_cast(slot(e, 4))(e, on_error, &seen); - const HRESULT reported = reinterpret_cast(slot(e, 3))(e, E_FAIL, "offline test"); - check(reported == S_OK && seen.hr == E_FAIL && std::strcmp(seen.msg, "offline test") == 0, - "slot 3 is XErrorReport and reaches the callback slot 4 (XErrorSetCallback) set"); - reinterpret_cast(slot(e, 4))(e, nullptr, nullptr); - using SetOptions = void(STDMETHODCALLTYPE*)(void*, uint32_t, uint32_t); // void, per Microsoft's page - reinterpret_cast(slot(e, 5))(e, 0x01, 0x00); // OutputDebugStringOnError / None - release(e); - } - - // XNetworkingImpl, asked for as XCurl.dll does: the class id with IXNetworkingImpl2's interface id. - const GUID networking = {0x37e56907, 0x2f10, 0x41e8, {0xb7, 0x2f, 0x36, 0xed, 0xb1, 0x85, 0x33, 0x1a}}; - const GUID networking2 = {0xbf2346b2, 0x39af, 0x4658, {0xb5, 0xea, 0x44, 0x71, 0x3c, 0x7e, 0x83, 0xb3}}; - const HRESULT no_network = HRESULT_FROM_WIN32(ERROR_NETWORK_UNREACHABLE); - void* n = nullptr; - check(query(&networking, networking2, &n) == S_OK && n, "QueryApiImpl hands out XNetworkingImpl for IXNetworkingImpl2"); - void* n1 = nullptr; - check(query(&networking, networking, &n1) == S_OK && n1 == n, "and the same object for IXNetworkingImpl"); - if (n1) release(n1); - if (n) { - struct Hint { - uint32_t level, cost, iana; - bool initialized, approaching, over, roaming; - } hint{9, 9, 9, false, true, true, true}; - using GetHint = HRESULT(STDMETHODCALLTYPE*)(void*, Hint*); - check(reinterpret_cast(slot(n, 15))(n, &hint) == S_OK && hint.level == 1 && hint.cost == 0 && - hint.initialized && !hint.approaching && !hint.over && !hint.roaming, - "slot 15 (XNetworkingGetConnectivityHint): initialized, no connectivity"); - XAsyncBlock block{}; - using SecurityAsync = HRESULT(STDMETHODCALLTYPE*)(void*, const wchar_t*, XAsyncBlock*); - using ResultSize = HRESULT(STDMETHODCALLTYPE*)(void*, XAsyncBlock*, size_t*); - size_t size = 99; - check(reinterpret_cast(slot(n, 11))(n, L"https://example.invalid/", &block) == S_OK && - XAsyncGetStatus(&block, true) == no_network && - reinterpret_cast(slot(n, 12))(n, &block, &size) == no_network && size == 0, - "slots 11/12 (UTF-16 URL security info): the async call completes with no network"); - // Slots 10/13 in Microsoft's order: (async, bufferByteCount, bufferByteCountUsed*, buffer*, information**). - // A sentinel buffer must stay untouched; the two outputs are written where they are, not into the buffer. - using SecurityResult = HRESULT(STDMETHODCALLTYPE*)(void*, XAsyncBlock*, size_t, size_t*, uint8_t*, void**); - for (int s : {10, 13}) { - uint8_t buffer[32]; - std::memset(buffer, 0xA5, sizeof(buffer)); - size_t used = 77; - void* info = &used; - const HRESULT hr = reinterpret_cast(slot(n, s))(n, &block, sizeof(buffer), &used, buffer, &info); - bool untouched = true; - for (uint8_t byte : buffer) untouched = untouched && byte == 0xA5; - check(hr == no_network && used == 0 && info == nullptr && untouched, - s == 10 ? "slot 10 (ANSI result): outputs zeroed in place, the caller's buffer untouched" - : "slot 13 (UTF-16 result): outputs zeroed in place, the caller's buffer untouched"); - } - using Verify = HRESULT(STDMETHODCALLTYPE*)(void*, void*, const void*); - check(reinterpret_cast(slot(n, 14))(n, nullptr, nullptr) == no_network, - "slot 14 (XNetworkingVerifyServerCertificate) fails offline"); - struct Seen { - int calls; - Hint hint; - uint16_t port; - }; - using HintCallback = void(CALLBACK*)(void*, const Hint*); - using PortCallback = void(CALLBACK*)(void*, uint16_t); - using RegisterHint = HRESULT(STDMETHODCALLTYPE*)(void*, XTaskQueueHandle, void*, HintCallback, - XTaskQueueRegistrationToken*); - using RegisterPort = HRESULT(STDMETHODCALLTYPE*)(void*, XTaskQueueHandle, void*, PortCallback, - XTaskQueueRegistrationToken*); - using Unregister = bool(STDMETHODCALLTYPE*)(void*, XTaskQueueRegistrationToken, bool); - const auto register_hint = reinterpret_cast(slot(n, 16)); - const auto register_port = reinterpret_cast(slot(n, 6)); - const auto unregister_hint = reinterpret_cast(slot(n, 17)); - const auto unregister_port = reinterpret_cast(slot(n, 7)); - HintCallback on_hint = [](void* ctx, const Hint* h) { - auto* s = static_cast(ctx); - ++s->calls; - if (h) s->hint = *h; - }; - PortCallback on_port = [](void* ctx, uint16_t p) { - auto* s = static_cast(ctx); - ++s->calls; - s->port = p; - }; - XTaskQueueRegistrationToken token{}; - check(register_hint(n, nullptr, nullptr, nullptr, &token) == E_INVALIDARG && - register_port(n, nullptr, nullptr, nullptr, &token) == E_INVALIDARG, - "slots 6/16 refuse a null callback"); - XTaskQueueHandle manual = nullptr; - XTaskQueueCreate(XTaskQueueDispatchMode::Manual, XTaskQueueDispatchMode::Manual, &manual); - Seen hint_seen{0, {9, 9, 9, false, true, true, true}, 0}; - Seen port_seen{0, {}, 7}; - XTaskQueueRegistrationToken hint_token{}, port_token{}; - const bool registered = register_hint(n, manual, &hint_seen, on_hint, &hint_token) == S_OK && hint_token.token && - register_port(n, manual, &port_seen, on_port, &port_token) == S_OK && port_token.token; - const bool none_before_dispatch = hint_seen.calls == 0 && port_seen.calls == 0; - while (XTaskQueueDispatch(manual, XTaskQueuePort::Completion, 0)) {} - const Hint& h = hint_seen.hint; - check(registered && none_before_dispatch && hint_seen.calls == 1 && h.level == 1 && h.cost == 0 && - h.initialized && !h.approaching && !h.over && !h.roaming, - "slot 16 sends one initial notification on the queue's completion port: initialized, no connectivity"); - check(port_seen.calls == 1 && port_seen.port == 0, "slot 6 sends one initial notification too: port 0"); - check(unregister_hint(n, hint_token, true) && unregister_port(n, port_token, true), - "slots 17/7 unregister them"); - Seen late{}; - XTaskQueueRegistrationToken late_hint{}, late_port{}; - const bool unregistered = register_hint(n, manual, &late, on_hint, &late_hint) == S_OK && - register_port(n, manual, &late, on_port, &late_port) == S_OK && - unregister_hint(n, late_hint, false) && unregister_port(n, late_port, false); - while (XTaskQueueDispatch(manual, XTaskQueuePort::Completion, 0)) {} - check(unregistered && late.calls == 0, "a registration ended before its queue is dispatched sends nothing"); - XTaskQueueCloseHandle(manual); - uint16_t port = 7; - using QueryPort = HRESULT(STDMETHODCALLTYPE*)(void*, uint16_t*); - using NotImpl = HRESULT(STDMETHODCALLTYPE*)(void*); - check(reinterpret_cast(slot(n, 3))(n, &port) == no_network && port == 0 && - reinterpret_cast(slot(n, 20))(n) == E_NOTIMPL, - "slot 3 (preferred UDP port) has no answer offline; slot 20 (IXNetworkingImpl2) is E_NOTIMPL"); - release(n); - } - - // XPersistentLocalStorageImpl (RT-219): the class id with IXPersistentLocalStorageImpl3's interface id, over a - // temporary overlay. The storage folder is \.gta6rt-persistent. - const GUID pls_class = {0xf4faf4d4, 0x2d04, 0x4fce, {0xb3, 0xe0, 0x47, 0x4a, 0x71, 0x3a, 0x3e, 0x84}}; - const GUID pls3 = {0x41a4e10c, 0x5a7e, 0x41d9, {0x8c, 0x37, 0x37, 0xbd, 0xe6, 0x2a, 0x07, 0xd6}}; - const std::filesystem::path scratch = - std::filesystem::temp_directory_path() / (L"gta6rt_pls_test_" + std::to_wstring(GetCurrentProcessId())); - std::error_code scratch_ec; - std::filesystem::remove_all(scratch, scratch_ec); - rt::fs::configure(scratch / L"game", scratch / L"overlay"); - void* pls = nullptr; - check(query(&pls_class, pls3, &pls) == S_OK && pls, "QueryApiImpl hands out XPersistentLocalStorageImpl for IXPersistentLocalStorageImpl3"); - if (pls) { - using GetPathSize = HRESULT(STDMETHODCALLTYPE*)(void*, size_t*); - using GetPath = HRESULT(STDMETHODCALLTYPE*)(void*, size_t, char*, size_t*); - using GetSpaceInfo = HRESULT(STDMETHODCALLTYPE*)(void*, uint64_t*); - using PromptAsync = HRESULT(STDMETHODCALLTYPE*)(void*, uint64_t, XAsyncBlock*); - using PromptResult = HRESULT(STDMETHODCALLTYPE*)(void*, XAsyncBlock*); - using Mount = HRESULT(STDMETHODCALLTYPE*)(void*, const char*, void**); - - size_t size = 0; - check(reinterpret_cast(slot(pls, 3))(pls, &size) == S_OK && size > 1, - "slot 3 (GetPathSize) reports the length of the path with its NUL"); - std::string path(size, '\xA5'); - size_t used = 0; - check(reinterpret_cast(slot(pls, 4))(pls, size, path.data(), &used) == S_OK && used == size && - path[size - 1] == '\0', - "slot 4 (GetPath) fills the buffer and reports the bytes used"); - const std::filesystem::path folder = std::filesystem::path(path.c_str()); - check(folder == scratch / L"overlay" / L".gta6rt-persistent" && std::filesystem::is_directory(folder), - "the path is \\.gta6rt-persistent and the folder exists"); - char tiny[2] = {'x', 'x'}; - used = 99; - check(reinterpret_cast(slot(pls, 4))(pls, 2, tiny, &used) == HRESULT_FROM_WIN32(ERROR_INSUFFICIENT_BUFFER) && - used == 0, - "slot 4 refuses a buffer that is too small"); - - { - std::ofstream cache_file(folder / L"cache.bin", std::ios::binary); - const std::string kilobyte(1024, 'z'); - cache_file << kilobyte; - } - uint64_t info[4] = {9, 9, 9, 9}; // available free, total free, used, total - const HRESULT info_hr = reinterpret_cast(slot(pls, 5))(pls, info); - check(info_hr == S_OK && info[3] == 2048ull * 1024 * 1024 && info[2] == 1024 && info[1] == info[3] - 1024 && - info[0] > 0 && info[0] <= info[1], - "slot 5 (GetSpaceInfo): the 2048 MB quota, the bytes used, and what is left"); - - XAsyncBlock fits{}; - check(reinterpret_cast(slot(pls, 6))(pls, 1024, &fits) == S_OK && - XAsyncGetStatus(&fits, true) == S_OK && reinterpret_cast(slot(pls, 7))(pls, &fits) == S_OK, - "slots 6/7: a prompt for space the quota can hold succeeds"); - XAsyncBlock too_big{}; - check(reinterpret_cast(slot(pls, 6))(pls, 4096ull * 1024 * 1024, &too_big) == S_OK && - XAsyncGetStatus(&too_big, true) == HRESULT_FROM_WIN32(ERROR_DISK_FULL) && - reinterpret_cast(slot(pls, 7))(pls, &too_big) == HRESULT_FROM_WIN32(ERROR_DISK_FULL), - "slots 6/7: a prompt for more than the quota fails with ERROR_DISK_FULL"); - - { - using CreateFileWFn = HANDLE(WINAPI*)(LPCWSTR, DWORD, DWORD, LPSECURITY_ATTRIBUTES, DWORD, DWORD, HANDLE); - using FindFirstFn = HANDLE(WINAPI*)(LPCWSTR, LPWIN32_FIND_DATAW); - using FindNextFn = BOOL(WINAPI*)(HANDLE, LPWIN32_FIND_DATAW); - using FindCloseFn = BOOL(WINAPI*)(HANDLE); - using DeleteFn = BOOL(WINAPI*)(LPCWSTR); - const auto create_w = reinterpret_cast(rt::shims::find("kernel32.dll", "CreateFileW")); - const auto first_w = reinterpret_cast(rt::shims::find("kernel32.dll", "FindFirstFileW")); - const auto next_w = reinterpret_cast(rt::shims::find("kernel32.dll", "FindNextFileW")); - const auto close_w = reinterpret_cast(rt::shims::find("kernel32.dll", "FindClose")); - const auto delete_w = reinterpret_cast(rt::shims::find("kernel32.dll", "DeleteFileW")); - auto lists = [&](const wchar_t* pattern, const wchar_t* name) { - bool found = false; - WIN32_FIND_DATAW fd{}; - const HANDLE h = first_w(pattern, &fd); - if (h == INVALID_HANDLE_VALUE) return false; - do found = found || _wcsicmp(fd.cFileName, name) == 0; - while (next_w(h, &fd)); - close_w(h); - return found; - }; - std::filesystem::create_directories(scratch / L"game" / L"persistent"); - std::ofstream(scratch / L"game" / L"persistent" / L"cache.bin", std::ios::binary) << "package"; - std::ofstream(folder / L"index.bin", std::ios::binary) << "storage"; - - check(!lists(L"GAME:\\*", L".gta6rt-persistent") && !lists(L"GAME:\\persistent\\*", L"index.bin"), - "GAME: listings show neither the storage folder nor its files"); - char bytes[16] = {}; - DWORD got = 0; - const HANDLE h = create_w(L"GAME:\\persistent\\cache.bin", GENERIC_READ, FILE_SHARE_READ, nullptr, - OPEN_EXISTING, 0, nullptr); - if (h != INVALID_HANDLE_VALUE) { - ::ReadFile(h, bytes, sizeof bytes - 1, &got, nullptr); - ::CloseHandle(h); - } - check(std::string(bytes) == "package", - "GAME:\\persistent\\cache.bin is the package's file, not the storage file of that name"); - std::error_code size_ec; - check(delete_w(L"GAME:\\persistent\\cache.bin") && - std::filesystem::file_size(folder / L"cache.bin", size_ec) == 1024, - "deleting the GAME: name leaves the storage file alone"); - } - - void* handle = reinterpret_cast(1); - check(reinterpret_cast(slot(pls, 8))(pls, "pkg", &handle) == E_NOTIMPL && handle == nullptr, - "slot 8 (MountForPackage) is E_NOTIMPL and leaves no handle"); - release(pls); - } - rt::fs::configure({}, {}); - check(query(&pls_class, pls_class, &pls) == S_OK, "the class answers with its own id too"); - if (pls) { - using GetPathSize = HRESULT(STDMETHODCALLTYPE*)(void*, size_t*); - size_t size = 99; - check(reinterpret_cast(slot(pls, 3))(pls, &size) == HRESULT_FROM_WIN32(ERROR_PATH_NOT_FOUND) && size == 0, - "with no overlay configured the path size fails instead of answering S_OK with nothing"); - release(pls); - } - std::filesystem::remove_all(scratch, scratch_ec); - - // XSystemImpl, asked for as libHttpClient.GDK.dll does: the class id with IXSystemImpl5's interface id. - const GUID system_cls = {0xe349bd1a, 0xfc20, 0x4e40, {0xb9, 0x9c, 0x41, 0x78, 0xcc, 0x6b, 0x40, 0x9f}}; - const GUID system5 = {0x1861cf2e, 0xe18b, 0x4834, {0xa9, 0xf5, 0xb4, 0xa4, 0xe6, 0xef, 0xb4, 0xcf}}; - void* sy = nullptr; - check(query(&system_cls, system5, &sy) == S_OK && sy, "QueryApiImpl hands out XSystemImpl for IXSystemImpl5"); - if (sy) { - using IdQuery = HRESULT(STDMETHODCALLTYPE*)(void*, size_t, char*, size_t*); - char buf[64] = {}; - size_t used = 0; - check(reinterpret_cast(slot(sy, 3))(sy, sizeof(buf), buf, &used) == S_OK && used == 39 && - std::strlen(buf) == 38, - "slot 3 (XSystemGetConsoleId): the 39-byte placeholder"); - check(reinterpret_cast(slot(sy, 4))(sy, sizeof(buf), buf, &used) == S_OK && - std::strcmp(buf, "RETAIL") == 0 && used == 7, - "slot 4 (XSystemGetXboxLiveSandboxId): RETAIL"); - check(reinterpret_cast(slot(sy, 4))(sy, 15, buf, &used) == HRESULT_FROM_WIN32(ERROR_INSUFFICIENT_BUFFER) && - reinterpret_cast(slot(sy, 4))(sy, 16, buf, &used) == S_OK, - "slot 4 needs XSystemXboxLiveSandboxIdMaxBytes (16), not just the id's 7 bytes"); - const GUID chain[] = { - system_cls, - {0x6fd71f09, 0x7513, 0x49f0, {0x89, 0xbc, 0xbf, 0xaf, 0x5d, 0xf6, 0xf8, 0x52}}, - {0x67ce4bfc, 0xb1d1, 0x4ac7, {0xbc, 0x3a, 0xcb, 0x92, 0x19, 0xa9, 0x7a, 0x85}}, - {0xdadc2895, 0x34b0, 0x4ef5, {0xa8, 0x3e, 0x45, 0x11, 0x4d, 0x62, 0x9b, 0x80}}, - system5}; - bool all_inherited = true; - for (const GUID& iid : chain) { - void* same = nullptr; - all_inherited = all_inherited && query(&system_cls, iid, &same) == S_OK && same == sy; - if (same) release(same); - } - check(all_inherited, "IXSystemImpl5 answers for every interface it inherits (IXSystemImpl .. IXSystemImpl4)"); - check(reinterpret_cast(slot(sy, 5))(sy, sizeof(buf), buf, &used) == S_OK && used == 45 && - reinterpret_cast(slot(sy, 5))(sy, 44, buf, &used) == - HRESULT_FROM_WIN32(ERROR_INSUFFICIENT_BUFFER) && - reinterpret_cast(slot(sy, 5))(sy, 45, nullptr, &used) == E_INVALIDARG, - "slot 5 (XSystemGetAppSpecificDeviceId): 45 bytes; a short or null buffer is refused"); - using Track = HRESULT(STDMETHODCALLTYPE*)(void*, void*, void*); - using IsValid = bool(STDMETHODCALLTYPE*)(void*, void*); // bool, per Microsoft's reference page - using Bandwidth = void(STDMETHODCALLTYPE*)(void*, bool); - int ctx = 0; - reinterpret_cast(slot(sy, 8))(sy, true); - check(reinterpret_cast(slot(sy, 6))(sy, &ctx, &ctx) == S_OK && - reinterpret_cast(slot(sy, 7))(sy, &ctx) && - !reinterpret_cast(slot(sy, 7))(sy, nullptr), - "slots 6-8 (handle tracking, handle check, download bandwidth) answer offline"); - release(sy); - } - - // XPackageImpl, asked for as libHttpClient.GDK.dll does: the class id with IXPackageImpl3's interface id. The - // slots with an offline answer agree with the named exports; the others are E_NOTIMPL. - const GUID package_cls = {0xaf406016, 0xe850, 0x4aa8, {0xa8, 0x8d, 0x2f, 0x3d, 0xcb, 0x9d, 0xac, 0x7e}}; - const GUID package3 = {0xe2a4734b, 0x2f4a, 0x456d, {0xaa, 0x8f, 0xd0, 0x65, 0xe0, 0x4f, 0xb2, 0x09}}; - void* pk = nullptr; - check(query(&package_cls, package3, &pk) == S_OK && pk, "QueryApiImpl hands out XPackageImpl for IXPackageImpl3"); - if (pk) { - using Ident = HRESULT(STDMETHODCALLTYPE*)(void*, size_t, char*); - using IdentExport = HRESULT(__stdcall*)(size_t, char*); - char a[64] = {}, b[64] = {}; - const auto ident_export = reinterpret_cast( - rt::shims::find("xgameruntime.dll", "XPackageGetCurrentProcessPackageIdentifier")); - check(reinterpret_cast(slot(pk, 3))(pk, sizeof(a), a) == S_OK && ident_export && - ident_export(sizeof(b), b) == S_OK && std::strcmp(a, b) == 0, - "slot 3 is XPackageGetCurrentProcessPackageIdentifier, the same answer as the export"); - using IsPackaged = bool(STDMETHODCALLTYPE*)(void*); - using IsPackagedExport = bool(__stdcall*)(); - const auto packaged_export = - reinterpret_cast(rt::shims::find("xgameruntime.dll", "XPackageIsPackagedProcess")); - check(packaged_export && reinterpret_cast(slot(pk, 4))(pk) == packaged_export(), - "slot 4 is XPackageIsPackagedProcess"); - // Slot 11, XPackageGetUserLocale: one of the package's declared locales, never the host's; an empty - // string (with S_OK) when the package declares none. - using Locale = HRESULT(STDMETHODCALLTYPE*)(void*, size_t, char*); - char tmp[MAX_PATH] = {}; - GetTempPathA(sizeof(tmp), tmp); - const std::string game = std::string(tmp) + "leonida_xpackage_locale_test"; - CreateDirectoryA(game.c_str(), nullptr); - SetEnvironmentVariableA("LEONIDA_GAME_DIR", game.c_str()); - char locale[128]; - std::memset(locale, 'z', sizeof(locale)); - check(reinterpret_cast(slot(pk, 11))(pk, 1, locale) == S_OK && locale[0] == '\0', - "slot 11 without declared locales: S_OK and an empty string in a one-byte buffer"); - if (FILE* f = std::fopen((game + "\\MicrosoftGame.Config").c_str(), "wb")) { - std::fputs("", - f); - std::fclose(f); - } - check(reinterpret_cast(slot(pk, 11))(pk, sizeof(locale), locale) == S_OK && - (std::strcmp(locale, "zz-ZZ") == 0 || std::strcmp(locale, "xx-YY") == 0) && - reinterpret_cast(slot(pk, 11))(pk, 3, locale) == HRESULT_FROM_WIN32(ERROR_INSUFFICIENT_BUFFER), - "slot 11 gives one of the package's declared locales, not the host's; a short buffer is refused"); - // Only ww-WW is declared: the commented-out entries, and DefaultLanguage are not, and the real - // entry has whitespace around '=' (valid XML). With one declared locale the answer is that one on any host. - if (FILE* f = std::fopen((game + "\\MicrosoftGame.Config").c_str(), "wb")) { - std::fputs("\r\n" - " \r\n" - " \r\n" - " SPIR-V -> tests/semantic/spirv_mini_interp.py and compares the result against -a plain-Python reference: sign-extend both operands to 16 bits, add, mask to 16 bits -(equivalently (x + y) & 0xFFFF for modular addition). - -Covers: - - Basic 16-bit signed add - - Positive overflow (0x7FFF + 1 wraps to 0x8000) - - Negative overflow (-1 + -1 wraps to 0xFFFE) - - Mixed sign addition - - Reference comparison across varied 16-bit patterns - - 50 randomized cases vs reference - - Negative control: result differs from each input for non-trivial cases -""" -import os -import struct -import sys -import tempfile -import unittest -import warnings -import random - -HERE = os.path.dirname(os.path.abspath(__file__)) -ROOT = os.path.dirname(os.path.dirname(HERE)) -TOOLS_DIR = os.environ.get("LEONIDA_TOOLS_DIR") or os.path.join(ROOT, "tools") - -sys.dont_write_bytecode = True -if TOOLS_DIR not in sys.path: - sys.path.insert(0, TOOLS_DIR) -if HERE not in sys.path: - sys.path.insert(0, HERE) - -import rdna2spirv # noqa: E402 -import spirv_mini_interp as si # noqa: E402 - -M16 = 0xFFFF -STUB_DXBC = b"DXBC" + bytes(24) + struct.pack(" int: - """Sign-extend a 16-bit value.""" - v &= M16 - return v - 0x10000 if v >= 0x8000 else v - - -def ref_add_i16(x: int, y: int) -> int: - """Plain-Python reference for v_add_i16: sign-extend, add, mask to 16 bits.""" - return (s16(x) + s16(y)) & M16 - - -def run_op(x: int, y: int) -> int: - """Translate and run a shader that computes v_add_i16 v1, v2, v3 with v2=x, v3=y. - - Uses a unique temp directory per call to avoid file-sharing issues. - """ - asm = ( - "; test_add_i16\n" - f"\tv_mov_b32_e32 v2, {x & M16:#x}\n" - f"\tv_mov_b32_e32 v3, {y & M16:#x}\n" - "\tv_add_i16 v1, v2, v3\n" - "\ts_waitcnt vmcnt(0)\n" - "\texp mrt0 v1, v1, v1, v1 done vm\n" - "\ts_endpgm\n" - ) - tmp = tempfile.TemporaryDirectory() - disasm_dir = os.path.join(tmp.name, "disasm") - os.mkdir(disasm_dir) - src_path = os.path.join(disasm_dir, "ps_add_i16.s") - with open(os.path.join(tmp.name, "ps_add_i16.dxbc"), "wb") as f: - f.write(STUB_DXBC) - with open(src_path, "w", encoding="utf-8") as f: - f.write(asm) - with warnings.catch_warnings(): - warnings.simplefilter("ignore", ResourceWarning) - spv = rdna2spirv.translate(src_path) - w = si.run_fragment(spv)["%out_mrt0"] - tmp.cleanup() - return w[0] & M16 - - -class ALUVAddI16Tests(unittest.TestCase): - def test_add_i16_basic(self): - self.assertEqual(run_op(0, 0), 0) - self.assertEqual(run_op(1, 2), 3) - self.assertEqual(run_op(100, 200), 300) - self.assertEqual(run_op(0x7FFF, 1), 0x8000) # positive overflow - - def test_add_i16_overflow(self): - # -1 + -1 = -2 = 0xFFFE - self.assertEqual(run_op(M16, M16), 0xFFFE) - # 0x7FFF + 1 = 0x8000 (positive overflow to negative) - self.assertEqual(run_op(0x7FFF, 0x0001), 0x8000) - # -32768 + -1 = 0x7FFF (negative overflow to positive) - self.assertEqual(run_op(0x8000, M16), 0x7FFF) - - def test_add_i16_reference(self): - cases = [ - (0, 0, 0), - (1, 1, 2), - (0x7FFF, 1, 0x8000), - (M16, M16, 0xFFFE), # -1 + -1 = -2 - (0x8000, M16, 0x7FFF), # -32768 + -1 = 32767 - (0x1234, 0x5678, 0x68AC), - ] - for x, y, expected in cases: - with self.subTest(x=hex(x), y=hex(y)): - self.assertEqual(run_op(x, y), expected) - self.assertEqual(run_op(x, y), ref_add_i16(x, y)) - - def test_add_i16_random_vs_reference(self): - rng = random.Random(0xC0FFEE) - for _ in range(50): - x = rng.getrandbits(16) - y = rng.getrandbits(16) - with self.subTest(x=hex(x), y=hex(y)): - self.assertEqual(run_op(x, y), ref_add_i16(x, y)) - - def test_add_i16_negative_control(self): - # For non-trivial inputs, result differs from each input. - x, y = 0x1234, 0x5678 - res = run_op(x, y) - expected = ref_add_i16(x, y) - self.assertEqual(res, expected) - self.assertNotEqual(res, x) - self.assertNotEqual(res, y) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_alu_add_nc_clamp.py b/tests/semantic/test_alu_add_nc_clamp.py deleted file mode 100644 index d1103bfb7..000000000 --- a/tests/semantic/test_alu_add_nc_clamp.py +++ /dev/null @@ -1,583 +0,0 @@ -from __future__ import annotations - -"""Semantic interpreter tests for RDNA2 v_add_nc_i32 / v_sub_nc_i32 and the integer clamp bit. - -v_add_nc_i32 / v_sub_nc_i32: D = S0 + S1 / S0 - S1, wrapping at 32 bits. With the VOP3 clamp bit an integer -add/sub saturates instead (GFX9+; LLVM selects uaddsat/usubsat to v_add/sub_nc_u32 clamp and saddsat/ssubsat to -v_add/sub_nc_i32 clamp): the unsigned ops to [0, 0xFFFFFFFF], the signed ones to [0x80000000, 0x7FFFFFFF]. -v_subrev_nc_u32 is S1 - S0 and saturates the same way. Each case translates a synthetic pixel shader with -tools/rdna2spirv.py, runs it in tests/semantic/spirv_mini_interp.py and compares the result with a plain-Python -reference. D leaves through exp as two 16-bit halves ORed into 0x40000000, so no export channel is a NaN or denormal -pattern that a float round trip could change. -""" -import os -import random -import struct -import sys -import tempfile -import unittest -import warnings - -HERE = os.path.dirname(os.path.abspath(__file__)) -ROOT = os.path.dirname(os.path.dirname(HERE)) -TOOLS_DIR = os.environ.get("LEONIDA_TOOLS_DIR") or os.path.join(ROOT, "tools") - -sys.dont_write_bytecode = True -sys.path.insert(0, TOOLS_DIR) -sys.path.insert(0, HERE) - -import rdna2spirv # noqa: E402 -import spirv_mini_interp as si # noqa: E402 -import spirv_wave_interp as wi # noqa: E402 - -M32 = 0xFFFFFFFF -STUB_DXBC = b"DXBC" + bytes(24) + struct.pack(" int: - x &= M32 - return x - (1 << 32) if x >> 31 else x - - -def ref_add_nc_u32(x: int, y: int, clamp: bool = False) -> int: - """Pure reference oracle for RDNA2 unsigned 32-bit addition with optional VOP3 clamp. - - Computes (x & M32) + (y & M32). Without clamp, the sum wraps modulo 2^32. - With clamp, if the 33-bit sum exceeds 0xFFFFFFFF (generating a carry), - the result saturates to 0xFFFFFFFF (GFX9+ uaddsat behavior). - """ - a = x & M32 - b = y & M32 - full_sum = a + b - if clamp: - return min(full_sum, M32) - return full_sum & M32 - - -def oracle_add_nc_u32_analysis(x: int, y: int) -> dict[str, int | bool]: - """Arithmetic analysis for v_add_nc_u32: full sum, carry, wrapped, and clamped results.""" - a = x & M32 - b = y & M32 - total = a + b - has_carry = total > M32 - wrapped = total & M32 - clamped = M32 if has_carry else total - return { - "a": a, - "b": b, - "total": total, - "carry": has_carry, - "wrapped": wrapped, - "clamped": clamped, - } - - -def ref(op: str, x: int, y: int, clamp: bool) -> int: - if op == "v_subrev_nc_u32": - x, y, op = y, x, "v_sub_nc_u32" - signed = op.endswith("_i32") - a, b = (s32(x), s32(y)) if signed else (x & M32, y & M32) - r = a - b if "_sub" in op else a + b - if clamp: - lo, hi = (-(1 << 31), (1 << 31) - 1) if signed else (0, M32) - r = min(max(r, lo), hi) - return r & M32 - - -OPS = ["v_add_nc_i32", "v_sub_nc_i32", "v_add_nc_u32", "v_sub_nc_u32", "v_subrev_nc_u32"] -VALUES = [0, 1, 2, 0x7FFFFFFF, 0x80000000, 0x80000001, 0xFFFFFFFF, 0xFFFFFFFE, 0x40000000, 0xC0000000, 0x12345678] - -_TMP_DIR = None -_SRC_PATH = None -_VS_SRC_PATH = None - - -def setUpModule(): - global _TMP_DIR, _SRC_PATH, _VS_SRC_PATH - _TMP_DIR = tempfile.TemporaryDirectory() - disasm_dir = os.path.join(_TMP_DIR.name, "disasm") - os.mkdir(disasm_dir) - _SRC_PATH = os.path.join(disasm_dir, "ps_add_nc_clamp.s") - _VS_SRC_PATH = os.path.join(disasm_dir, "vs_add_nc_clamp.s") - with open(os.path.join(_TMP_DIR.name, "ps_add_nc_clamp.dxbc"), "wb") as f: - f.write(STUB_DXBC) - with open(os.path.join(_TMP_DIR.name, "vs_add_nc_clamp.dxbc"), "wb") as f: - f.write(STUB_DXBC) - - -def tearDownModule(): - global _TMP_DIR, _SRC_PATH, _VS_SRC_PATH - if _TMP_DIR is not None: - _TMP_DIR.cleanup() - _TMP_DIR = None - _SRC_PATH = None - _VS_SRC_PATH = None - - -def run_wave_vs(lines: list[str], wave: int = 32, base_lane: int = 0) -> list[int | None]: - """Run a synthetic vertex shader on a wave of lanes, returning param0 word 0 for each lane.""" - if _TMP_DIR is None: - setUpModule() - body = ["s_mov_b64 s[10:11], exec"] + list(lines) + [ - "v_mov_b32_e32 v5, 0", - "exp pos0 v5, v5, v5, v5 done", - "exp param0 v6, v5, v5, v5", - "s_endpgm", - ] - asm = "; vs_add_nc_clamp\n" + "".join(f"\t{ln}\n" for ln in body) - with open(_VS_SRC_PATH, "w", encoding="utf-8") as f: - f.write(asm) - with warnings.catch_warnings(): - warnings.simplefilter("ignore", ResourceWarning) - spv = rdna2spirv.translate(_VS_SRC_PATH) - res = wi.run_wave( - spv, - wave=wave, - builtins={ - "VertexIndex": lambda lane, b=base_lane: b + lane, - "InstanceIndex": lambda _lane: 0, - }, - ) - outputs: list[int | None] = [] - for out in res["outputs"]: - if out is None: - outputs.append(None) - else: - outputs.append(out["%out_param0"][0]) - return outputs - - -def run_lines(lines) -> int: - """Run the lines, return v0 (exported as two 16-bit halves, see the module docstring).""" - if _TMP_DIR is None: - setUpModule() - lines = list(lines) + ["v_and_b32 v5, 0xffff, v0", "v_lshrrev_b32 v6, 16, v0", - "v_or_b32 v5, 0x40000000, v5", "v_or_b32 v6, 0x40000000, v6"] - asm = "; test_add_nc_clamp\n" + "".join(f"\t{ln}\n" for ln in lines) + "\texp mrt0 v5, v6, v5, v5 done vm\n\ts_endpgm\n" - with open(_SRC_PATH, "w", encoding="utf-8") as f: - f.write(asm) - with warnings.catch_warnings(): - warnings.simplefilter("ignore", ResourceWarning) - spv = rdna2spirv.translate(_SRC_PATH) - lo, hi = si.run_fragment(spv)["%out_mrt0"][:2] - assert lo >> 16 == 0x4000 and hi >> 16 == 0x4000, (hex(lo), hex(hi)) - return (lo & 0xFFFF) | (hi & 0xFFFF) << 16 - - -def run_op(op: str, x: int, y: int, clamp: bool) -> int: - return run_lines([f"v_mov_b32 v1, {x:#x}", f"v_mov_b32 v2, {y:#x}", - f"{op}_e64 v0, v1, v2" + (" clamp" if clamp else "")]) - - -class AddNcClampTests(unittest.TestCase): - def test_reference(self): - self.assertEqual(ref("v_add_nc_i32", 0x7FFFFFFF, 1, False), 0x80000000) - self.assertEqual(ref("v_add_nc_i32", 0x7FFFFFFF, 1, True), 0x7FFFFFFF) - self.assertEqual(ref("v_sub_nc_i32", 0x80000000, 1, True), 0x80000000) - self.assertEqual(ref("v_add_nc_u32", M32, 2, True), M32) - self.assertEqual(ref("v_sub_nc_u32", 1, 2, True), 0) - self.assertEqual(ref("v_subrev_nc_u32", 2, 1, True), 0) - - def test_values(self): - for op in OPS: - for clamp in (False, True): - for x in VALUES: - for y in VALUES[::2]: - with self.subTest(op=op, clamp=clamp, x=hex(x), y=hex(y)): - self.assertEqual(run_op(op, x, y, clamp), ref(op, x, y, clamp)) - - def test_seeded(self): - rng = random.Random(0xC1A) - for _ in range(40): - op, clamp = rng.choice(OPS), bool(rng.getrandbits(1)) - x, y = rng.getrandbits(32), rng.getrandbits(32) - with self.subTest(op=op, clamp=clamp, x=hex(x), y=hex(y)): - self.assertEqual(run_op(op, x, y, clamp), ref(op, x, y, clamp)) - - def test_vop2_forms_wrap(self): - # The VOP2 encodings have no clamp bit: they wrap. - self.assertEqual(run_lines(["v_mov_b32 v1, -1", "v_add_nc_u32_e32 v0, 2, v1"]), 1) - self.assertEqual(run_lines(["v_mov_b32 v1, 1", "v_sub_nc_u32_e32 v0, 0, v1"]), M32) - - -class TestAddNcU32ReferenceOracle(unittest.TestCase): - """Reference oracle tests for vector addition with clamp saturation v_add_nc_u32.""" - - def test_oracle_identity_zero(self) -> None: - """Adding zero must preserve operand under both wrapping and clamping.""" - test_values = [0, 1, 2, 0x7FFFFFFF, 0x80000000, 0xFFFFFFFE, 0xFFFFFFFF] - for val in test_values: - with self.subTest(val=hex(val)): - self.assertEqual(ref_add_nc_u32(val, 0, clamp=False), val) - self.assertEqual(ref_add_nc_u32(val, 0, clamp=True), val) - self.assertEqual(ref_add_nc_u32(0, val, clamp=False), val) - self.assertEqual(ref_add_nc_u32(0, val, clamp=True), val) - - def test_oracle_commutativity(self) -> None: - """v_add_nc_u32 must be strictly commutative with and without clamp.""" - test_pairs = [ - (0, 0), - (1, 0xFFFFFFFF), - (0x12345678, 0x87654321), - (0x7FFFFFFF, 0x80000000), - (0xFFFFFFFE, 2), - (0xAAAAAAAA, 0x55555555), - (0xC0000000, 0x60000000), - (0xFFFFFFFF, 0xFFFFFFFF), - ] - for a, b in test_pairs: - for clamp in (False, True): - with self.subTest(a=hex(a), b=hex(b), clamp=clamp): - self.assertEqual(ref_add_nc_u32(a, b, clamp), ref_add_nc_u32(b, a, clamp)) - - def test_oracle_sub_saturation_equivalence(self) -> None: - """When the sum does not exceed 0xFFFFFFFF, clamp and no-clamp results must be identical.""" - safe_pairs = [ - (0, 0), - (10, 20), - (0x1000, 0x2000), - (0x7FFFFFFF, 0), - (0x7FFFFFFF, 0x80000000), # sum == 0xFFFFFFFF exactly - (0x55555555, 0x22222222), - (0xFFFFFFFE, 1), # sum == 0xFFFFFFFF exactly - ] - for a, b in safe_pairs: - with self.subTest(a=hex(a), b=hex(b)): - wrapped = ref_add_nc_u32(a, b, clamp=False) - clamped = ref_add_nc_u32(a, b, clamp=True) - self.assertEqual(wrapped, clamped) - self.assertEqual(clamped, a + b) - - def test_oracle_saturation_boundary_transitions(self) -> None: - """At and across the 2^32 boundary, clamping must saturate to 0xFFFFFFFF while wrapping wraps.""" - cases = [ - # (a, b, expected_wrapped, expected_clamped, expected_carry) - (0xFFFFFFFF, 0, 0xFFFFFFFF, 0xFFFFFFFF, False), - (0xFFFFFFFE, 1, 0xFFFFFFFF, 0xFFFFFFFF, False), - (0x7FFFFFFF, 0x80000000, 0xFFFFFFFF, 0xFFFFFFFF, False), - # Transition across boundary: - (0xFFFFFFFF, 1, 0, 0xFFFFFFFF, True), - (0xFFFFFFFE, 2, 0, 0xFFFFFFFF, True), - (0xFFFFFFFF, 2, 1, 0xFFFFFFFF, True), - (0x80000000, 0x80000000, 0, 0xFFFFFFFF, True), - (0x80000001, 0x80000000, 1, 0xFFFFFFFF, True), - (0xC0000000, 0x80000000, 0x40000000, 0xFFFFFFFF, True), - (0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFE, 0xFFFFFFFF, True), - ] - for a, b, exp_wrap, exp_clamp, exp_carry in cases: - with self.subTest(a=hex(a), b=hex(b)): - analysis = oracle_add_nc_u32_analysis(a, b) - self.assertEqual(analysis["carry"], exp_carry) - self.assertEqual(analysis["wrapped"], exp_wrap) - self.assertEqual(analysis["clamped"], exp_clamp) - self.assertEqual(ref_add_nc_u32(a, b, clamp=False), exp_wrap) - self.assertEqual(ref_add_nc_u32(a, b, clamp=True), exp_clamp) - - def test_oracle_monotonicity_under_saturation(self) -> None: - """For a fixed base, clamped addition must be monotonically non-decreasing up to saturation.""" - base = 0xFFFFFFF0 - prev_clamped = 0 - for delta in range(32): - clamped = ref_add_nc_u32(base, delta, clamp=True) - self.assertGreaterEqual(clamped, prev_clamped) - if delta < 15: - self.assertEqual(clamped, base + delta) - else: - self.assertEqual(clamped, M32) - prev_clamped = clamped - - def test_translation_execution_matches_ref_oracle(self) -> None: - """SPIR-V translation and mini-interpreter execution must match ref_add_nc_u32.""" - sample_pairs = [ - (0, 0), - (100, 200), - (0x7FFFFFFF, 1), - (0xFFFFFFFF, 1), - (0xFFFFFFFE, 2), - (0x80000000, 0x80000000), - (0xFFFFFFFF, 0xFFFFFFFF), - ] - for a, b in sample_pairs: - for clamp in (False, True): - with self.subTest(a=hex(a), b=hex(b), clamp=clamp): - got = run_op("v_add_nc_u32", a, b, clamp) - want = ref_add_nc_u32(a, b, clamp) - self.assertEqual(got, want) - - -class TestAddNcU32SimdDivergence(unittest.TestCase): - """Multi-lane SIMD divergence and clamp boundary verification for v_add_nc_u32.""" - - def test_wave32_clamp_boundary_divergence(self) -> None: - """In wave32, lanes cross the clamp boundary: non-saturating lanes match wrapped, saturated lanes clamp.""" - # Operands: v0 = lane index (0..31), v1 = 0xFFFFFFF0 - # Lanes 0..15: sums 0xFFFFFFF0..0xFFFFFFFF (below or at 2^32 boundary). Clamped == Wrapped == sum. - # Lanes 16..31: sums 0x100000000..0x10000000F. Clamped == 0xFFFFFFFF, Wrapped == lane - 16. - lines_clamped = [ - "v_mov_b32_e32 v1, 0xfffffff0", - "v_add_nc_u32_e64 v6, v0, v1 clamp", - ] - lines_wrapped = [ - "v_mov_b32_e32 v1, 0xfffffff0", - "v_add_nc_u32_e64 v6, v0, v1", - ] - clamped_outs = run_wave_vs(lines_clamped, wave=32) - wrapped_outs = run_wave_vs(lines_wrapped, wave=32) - - self.assertEqual(len(clamped_outs), 32) - self.assertEqual(len(wrapped_outs), 32) - - for lane in range(32): - expected_clamped = ref_add_nc_u32(lane, 0xFFFFFFF0, clamp=True) - expected_wrapped = ref_add_nc_u32(lane, 0xFFFFFFF0, clamp=False) - self.assertEqual(clamped_outs[lane], expected_clamped, f"Mismatch at clamped lane {lane}") - self.assertEqual(wrapped_outs[lane], expected_wrapped, f"Mismatch at wrapped lane {lane}") - - if lane <= 15: - # Sub-saturation: clamp and wrap must be identical - self.assertEqual(clamped_outs[lane], wrapped_outs[lane]) - self.assertEqual(clamped_outs[lane], 0xFFFFFFF0 + lane) - else: - # Saturation: clamp is 0xFFFFFFFF while wrap rolls over - self.assertEqual(clamped_outs[lane], M32) - self.assertEqual(wrapped_outs[lane], lane - 16) - self.assertNotEqual(clamped_outs[lane], wrapped_outs[lane]) - - def test_wave64_clamp_boundary_divergence(self) -> None: - """In wave64, verify multi-lane divergence across the 64-lane wavefront.""" - # Operands: v0 = lane index (0..63), v1 = 0xFFFFFFE0 - # Lanes 0..31: sums 0xFFFFFFE0..0xFFFFFFFF (clamped == wrapped == 0xFFFFFFE0 + lane) - # Lanes 32..63: sums 0x100000000..0x10000001F (clamped == 0xFFFFFFFF, wrapped == lane - 32) - lines_clamped = [ - "v_mov_b32_e32 v1, 0xffffffe0", - "v_add_nc_u32_e64 v6, v0, v1 clamp", - ] - lines_wrapped = [ - "v_mov_b32_e32 v1, 0xffffffe0", - "v_add_nc_u32_e64 v6, v0, v1", - ] - clamped_outs = run_wave_vs(lines_clamped, wave=64) - wrapped_outs = run_wave_vs(lines_wrapped, wave=64) - - self.assertEqual(len(clamped_outs), 64) - self.assertEqual(len(wrapped_outs), 64) - - for lane in range(64): - expected_clamped = ref_add_nc_u32(lane, 0xFFFFFFE0, clamp=True) - expected_wrapped = ref_add_nc_u32(lane, 0xFFFFFFE0, clamp=False) - self.assertEqual(clamped_outs[lane], expected_clamped, f"Wave64 mismatch at clamped lane {lane}") - self.assertEqual(wrapped_outs[lane], expected_wrapped, f"Wave64 mismatch at wrapped lane {lane}") - - if lane <= 31: - self.assertEqual(clamped_outs[lane], wrapped_outs[lane]) - else: - self.assertEqual(clamped_outs[lane], M32) - self.assertEqual(wrapped_outs[lane], lane - 32) - self.assertNotEqual(clamped_outs[lane], wrapped_outs[lane]) - - def test_wave32_inactive_exec_mask(self) -> None: - """Disabled lanes under EXEC mask must not update their destination register.""" - sentinel = 0xDEADBEEF - lines = [ - f"v_mov_b32_e32 v6, {sentinel:#x}", - "s_mov_b32 exec_lo, 0x0000ffff", # only lanes 0..15 active - "v_mov_b32_e32 v1, 0xffffffe0", - "v_add_nc_u32_e64 v6, v0, v1 clamp", - "s_mov_b32 exec_lo, 0xffffffff", # restore exec for export - ] - outs = run_wave_vs(lines, wave=32) - for lane in range(16): - # Active lanes: v0 + 0xffffffe0 with clamp - self.assertEqual(outs[lane], ref_add_nc_u32(lane, 0xFFFFFFE0, clamp=True)) - for lane in range(16, 32): - # Inactive lanes: destination register retains sentinel value - self.assertEqual(outs[lane], sentinel, f"Lane {lane} was overwritten despite inactive EXEC") - - def test_simd_dual_divergent_operands(self) -> None: - """Simultaneous per-lane variation on both source operands across clamp threshold.""" - # Lane v0 in 0..31 - # Let v1 = 0x80000000 + lane (ranges 0x80000000..0x8000001F) - # Let v2 = 0x7FFFFFF0 + lane (ranges 0x7FFFFFF0..0x8000000F) - # Total sum = 0xFFFFFFF0 + 2 * lane - # Lanes 0..7: sums 0xFFFFFFF0..0xFFFFFFFE (below 2^32, clamped == wrapped) - # Lanes 8..31: sums 0x100000000..0x10000002E (exceeds 2^32, clamped == 0xFFFFFFFF, wrapped == 2 * (lane - 8)) - lines_clamped = [ - "v_add_nc_u32_e32 v1, 0x80000000, v0", - "v_add_nc_u32_e32 v2, 0x7ffffff0, v0", - "v_add_nc_u32_e64 v6, v1, v2 clamp", - ] - lines_wrapped = [ - "v_add_nc_u32_e32 v1, 0x80000000, v0", - "v_add_nc_u32_e32 v2, 0x7ffffff0, v0", - "v_add_nc_u32_e64 v6, v1, v2", - ] - clamped_outs = run_wave_vs(lines_clamped, wave=32) - wrapped_outs = run_wave_vs(lines_wrapped, wave=32) - - for lane in range(32): - v1_val = 0x80000000 + lane - v2_val = 0x7FFFFFF0 + lane - exp_clamped = ref_add_nc_u32(v1_val, v2_val, clamp=True) - exp_wrapped = ref_add_nc_u32(v1_val, v2_val, clamp=False) - self.assertEqual(clamped_outs[lane], exp_clamped, f"Clamped mismatch at lane {lane}") - self.assertEqual(wrapped_outs[lane], exp_wrapped, f"Wrapped mismatch at lane {lane}") - if lane < 8: - self.assertEqual(clamped_outs[lane], wrapped_outs[lane]) - self.assertEqual(clamped_outs[lane], 0xFFFFFFF0 + 2 * lane) - else: - self.assertEqual(clamped_outs[lane], M32) - self.assertEqual(wrapped_outs[lane], (lane - 8) * 2) - self.assertNotEqual(clamped_outs[lane], wrapped_outs[lane]) - - -class TestAddNcU32EdgeCases(unittest.TestCase): - """Overflow wrapping vs clamping edge cases and SPIR-V structure verification.""" - - def test_edge_case_matrix(self) -> None: - """Exhaustive boundary testing across extreme 32-bit integer patterns.""" - edge_values = [ - 0, - 1, - 2, - 0x7FFFFFFF, - 0x80000000, - 0x80000001, - 0xFFFFFFFE, - 0xFFFFFFFF, - 0x55555555, - 0xAAAAAAAA, - ] - for a in edge_values: - for b in (0, 1, 0x80000000, 0xFFFFFFFF): - for clamp in (False, True): - with self.subTest(a=hex(a), b=hex(b), clamp=clamp): - got = run_op("v_add_nc_u32", a, b, clamp) - want = ref_add_nc_u32(a, b, clamp) - self.assertEqual(got, want) - - def test_vop2_e32_vs_vop3_e64_equivalence_without_clamp(self) -> None: - """Without clamp, VOP3 e64 must produce bit-for-bit identical results to VOP2 e32.""" - pairs = [ - (0xFFFFFFFF, 1), - (0xFFFFFFFF, 0xFFFFFFFF), - (0x80000000, 0x80000000), - (0x12345678, 0x9ABCDEF0), - ] - for a, b in pairs: - vop2 = run_lines([f"v_mov_b32 v1, {b:#x}", f"v_add_nc_u32_e32 v0, {a:#x}, v1"]) - vop3 = run_lines([f"v_mov_b32 v1, {a:#x}", f"v_mov_b32 v2, {b:#x}", "v_add_nc_u32_e64 v0, v1, v2"]) - self.assertEqual(vop2, vop3) - self.assertEqual(vop2, ref_add_nc_u32(a, b, clamp=False)) - - def test_vcc_isolation(self) -> None: - """v_add_nc_u32 must not write or clobber VCC carry condition.""" - # Set vcc_lo to -1 (all lanes true). Execute v_add_nc_u32 with carry. - # Verify vcc_lo is still -1 via v_cndmask_b32. - lines = [ - "s_mov_b32 vcc_lo, -1", - "v_mov_b32 v1, 0xffffffff", - "v_mov_b32 v2, 1", - "v_add_nc_u32_e64 v3, v1, v2 clamp", - "v_cndmask_b32_e64 v0, 0, 1, vcc_lo", - ] - res = run_lines(lines) - self.assertEqual(res, 1, "VCC condition was clobbered by v_add_nc_u32") - - def test_spirv_lowering_instruction_pattern(self) -> None: - """v_add_nc_u32 with clamp lowers to OpIAddCarry + OpSelect, without clamp to OpIAdd.""" - if _TMP_DIR is None: - setUpModule() - # Clamped form: - lines_clamped = [ - "v_mov_b32 v1, 0xffffffff", - "v_mov_b32 v2, 1", - "v_add_nc_u32_e64 v0, v1, v2 clamp", - "exp mrt0 v0, v0, v0, v0 done vm", - "s_endpgm", - ] - asm = "; ps_spirv_check\n" + "".join(f"\t{ln}\n" for ln in lines_clamped) - with open(_SRC_PATH, "w", encoding="utf-8") as f: - f.write(asm) - spv_clamp = rdna2spirv.translate(_SRC_PATH) - self.assertIn("OpIAddCarry %umul", spv_clamp) - self.assertIn("4294967295", spv_clamp) - self.assertIn("OpCompositeExtract %uint", spv_clamp) - - # Unclamped form: - lines_wrapped = [ - "v_mov_b32 v1, 0xffffffff", - "v_mov_b32 v2, 1", - "v_add_nc_u32_e64 v0, v1, v2", - "exp mrt0 v0, v0, v0, v0 done vm", - "s_endpgm", - ] - asm = "; ps_spirv_check\n" + "".join(f"\t{ln}\n" for ln in lines_wrapped) - with open(_SRC_PATH, "w", encoding="utf-8") as f: - f.write(asm) - spv_wrap = rdna2spirv.translate(_SRC_PATH) - self.assertIn("OpIAdd %uint", spv_wrap) - self.assertNotIn("OpIAddCarry", spv_wrap) - - -class TestAddNcU32NegativeControls(unittest.TestCase): - """Negative controls ensuring mutated arithmetic or incorrect saturation limits fail assertions.""" - - def test_overflow_wrapping_vs_clamping_divergence_detected(self) -> None: - """Whenever sum > 0xFFFFFFFF, wrapping and clamping must strictly diverge.""" - overflow_pairs = [ - (0xFFFFFFFF, 1), - (0xFFFFFFFF, 0xFFFFFFFF), - (0x80000000, 0x80000000), - (0xFFFFFFFE, 2), - (0xC0000000, 0x40000001), - ] - for a, b in overflow_pairs: - with self.subTest(a=hex(a), b=hex(b)): - wrapped = ref_add_nc_u32(a, b, clamp=False) - clamped = ref_add_nc_u32(a, b, clamp=True) - self.assertNotEqual(wrapped, clamped) - self.assertEqual(clamped, M32) - self.assertEqual(wrapped, (a + b) & M32) - - def test_signed_saturation_sabotage_detected(self) -> None: - """Unsigned clamp must not be confused with signed clamp (saddsat limit 0x7FFFFFFF).""" - a, b = 0xFFFFFFFF, 1 - correct_uaddsat = ref_add_nc_u32(a, b, clamp=True) - sabotaged_saddsat = 0x7FFFFFFF - self.assertEqual(correct_uaddsat, M32) - self.assertNotEqual(correct_uaddsat, sabotaged_saddsat) - - def test_subtraction_saturation_sabotage_detected(self) -> None: - """Addition clamp (saturates to 0xFFFFFFFF) must not be confused with subtraction clamp (saturates to 0).""" - a, b = 0xFFFFFFFF, 1 - correct_add_clamp = ref_add_nc_u32(a, b, clamp=True) - sabotaged_sub_clamp = 0 - self.assertNotEqual(correct_add_clamp, sabotaged_sub_clamp) - - def test_unmasked_64bit_sum_sabotage_detected(self) -> None: - """Unmasked 64-bit integer overflow must not pass 32-bit wrapping tests.""" - a, b = 0xFFFFFFFF, 1 - correct_wrapped = ref_add_nc_u32(a, b, clamp=False) - sabotaged_unmasked = a + b # 0x100000000 - self.assertEqual(correct_wrapped, 0) - self.assertNotEqual(correct_wrapped, sabotaged_unmasked) - - def test_off_by_one_clamp_limit_detected(self) -> None: - """Saturation must be exactly 0xFFFFFFFF, not 0xFFFFFFFE.""" - a, b = 0xFFFFFFFF, 2 - correct_clamped = ref_add_nc_u32(a, b, clamp=True) - sabotaged_limit = 0xFFFFFFFE - self.assertEqual(correct_clamped, M32) - self.assertNotEqual(correct_clamped, sabotaged_limit) - - def test_no_carry_addition_does_not_mask_stage_carries(self) -> None: - """Oracle analysis accurately reports carry flag and distinct outputs.""" - analysis = oracle_add_nc_u32_analysis(0x80000000, 0x80000000) - self.assertTrue(analysis["carry"]) - self.assertEqual(analysis["wrapped"], 0) - self.assertEqual(analysis["clamped"], M32) - self.assertNotEqual(analysis["wrapped"], analysis["clamped"]) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_alu_add_sub_i16.py b/tests/semantic/test_alu_add_sub_i16.py deleted file mode 100644 index 5e2227278..000000000 --- a/tests/semantic/test_alu_add_sub_i16.py +++ /dev/null @@ -1,291 +0,0 @@ -"""Semantic interpreter tests for RDNA2 16-bit signed add/sub (v_add_i16, v_sub_i16). - -Covers both the VOP2 form (`v_add_i16`, `v_sub_i16`, which zeroes bits [31:16] of the -destination VGPR) and the VOP3 `_e64` form (`v_add_i16_e64`, `v_sub_i16_e64`, which -preserves the untouched half of the destination VGPR and supports `op_sel` and signed -`clamp` to [-32768, 32767]). - -Standard library only; zero game data, no GPU hardware required. -""" -from __future__ import annotations - -import os -import random -import re -import sys -import unittest - -sys.dont_write_bytecode = True - -HERE = os.path.dirname(os.path.abspath(__file__)) -if HERE not in sys.path: - sys.path.insert(0, HERE) - -import spirv_mini_interp as si # noqa: E402 -import support # noqa: E402 - -OLD_V0 = 0x5A5A1234 - - -def s16(word: int, hi: int = 0) -> int: - """Extract a 16-bit lane half as a signed Python integer in [-32768, 32767].""" - h = (word >> 16 if hi else word) & 0xFFFF - return h - 0x10000 if (h & 0x8000) else h - - -def ref_i16( - op: str, - s0: int, - s1: int, - *, - old: int = OLD_V0, - clamp: bool = False, - sel: tuple[int, int, int] = (0, 0, 0), -) -> int: - """Plain-Python reference matching tools/rdna2spirv.py for v_add_i16 / v_sub_i16.""" - e64 = op.endswith("_e64") - x = s16(s0, sel[0]) - y = s16(s1, sel[1]) - res = x + y if "add" in op else x - y - if clamp: - res = max(-0x8000, min(0x7FFF, res)) - lo = res & 0xFFFF - if e64 and sel[2]: - return (old & 0xFFFF) | (lo << 16) - if e64: - return (old & 0xFFFF0000) | lo - return lo - - -def translate_i16_ps(name: str, lines: list[str]) -> str: - """Translate a minimal pixel shader ending with `exp mrt0` of v0.""" - prog = list(lines) + [ - "exp mrt0 v0, v0, v0, v0 done vm", - "s_endpgm", - ] - return support.translate_lines(name, prog) - - -def run_i16_op( - op: str, - s0: int, - s1: int, - *, - old: int = OLD_V0, - mods: str = "", -) -> int: - """Translate and run a single `op v0, v1, v2` instruction and return v0.""" - suffix = f" {mods}" if mods else "" - spv = translate_i16_ps( - f"ps_{op}", - [ - f"v_mov_b32 v1, {s0:#x}", - f"v_mov_b32 v2, {s1:#x}", - f"v_mov_b32 v0, {old:#x}", - f"{op} v0, v1, v2{suffix}", - ], - ) - return si.run_fragment(spv)["%out_mrt0"][0] - - -class AluAddSubI16Tests(unittest.TestCase): - def test_add_i16_basic_wrap_and_high_bits(self) -> None: - cases = [ - (0, 0, 0x0000), - (3, 4, 0x0007), - (0x7FFF, 2, 0x8001), # signed 16-bit overflow wrap - (0xFFFF, 1, 0x0000), # unsigned 16-bit wrap (-1 + 1 = 0) - (0xFFFE, 5, 0x0003), - (0x8000, 0x8000, 0x0000), - (0xFFFF, 0xFFFF, 0xFFFE), # -1 + -1 = -2 - ] - for s0, s1, expected_lo in cases: - with self.subTest(op="v_add_i16", s0=hex(s0), s1=hex(s1)): - self.assertEqual(run_i16_op("v_add_i16", s0, s1), expected_lo) - with self.subTest(op="v_add_i16_e64", s0=hex(s0), s1=hex(s1)): - self.assertEqual( - run_i16_op("v_add_i16_e64", s0, s1), - (OLD_V0 & 0xFFFF0000) | expected_lo, - ) - - def test_add_i16_inline_negative_operands(self) -> None: - for op in ("v_add_i16", "v_add_i16_e64"): - with self.subTest(op=op, case="-1 + 0"): - spv = translate_i16_ps( - f"ps_{op}_neg0", - [ - f"v_mov_b32 v0, {OLD_V0:#x}", - "v_mov_b32 v1, 0", - f"{op} v0, -1, v1", - ], - ) - got = si.run_fragment(spv)["%out_mrt0"][0] - expected = 0x5A5AFFFF if op.endswith("_e64") else 0x0000FFFF - self.assertEqual(got, expected) - - with self.subTest(op=op, case="10 + -15"): - spv = translate_i16_ps( - f"ps_{op}_neg1", - [ - f"v_mov_b32 v0, {OLD_V0:#x}", - "v_mov_b32 v1, 10", - f"{op} v0, v1, -15", - ], - ) - got = si.run_fragment(spv)["%out_mrt0"][0] - expected = 0x5A5AFFFB if op.endswith("_e64") else 0x0000FFFB - self.assertEqual(got, expected) - - def test_sub_i16_basic_borrow_asymmetry_and_high_bits(self) -> None: - cases = [ - (0, 0, 0x0000), - (10, 3, 0x0007), - (1, 2, 0xFFFF), # borrow / underflow: 1 - 2 = -1 - (0, 1, 0xFFFF), - (0x8000, 1, 0x7FFF), # signed 16-bit underflow wrap - (0x8000, 0x7FFF, 0x0001), - (0x0005, 0xFFFF, 0x0006), # 5 - (-1) = 6 - ] - for s0, s1, expected_lo in cases: - with self.subTest(op="v_sub_i16", s0=hex(s0), s1=hex(s1)): - self.assertEqual(run_i16_op("v_sub_i16", s0, s1), expected_lo) - with self.subTest(op="v_sub_i16_e64", s0=hex(s0), s1=hex(s1)): - self.assertEqual( - run_i16_op("v_sub_i16_e64", s0, s1), - (OLD_V0 & 0xFFFF0000) | expected_lo, - ) - - # Asymmetry: S0 - S1 != S1 - S0 - for op in ("v_sub_i16", "v_sub_i16_e64"): - ab = run_i16_op(op, 5, 12) - ba = run_i16_op(op, 12, 5) - self.assertNotEqual(ab, ba) - self.assertEqual(ab & 0xFFFF, 0xFFF9) - self.assertEqual(ba & 0xFFFF, 0x0007) - - def test_high_input_bits_do_not_pollute_16bit_result(self) -> None: - pairs = [ - (0xDEAD0005, 0xBEEF0003), - (0x12347FFF, 0x56780002), - (0xABCDFFFF, 0xEF010001), - (0x80008000, 0x7FFF0001), - ] - for op in ("v_add_i16", "v_add_i16_e64", "v_sub_i16", "v_sub_i16_e64"): - for s0, s1 in pairs: - with self.subTest(op=op, s0=hex(s0), s1=hex(s1)): - got = run_i16_op(op, s0, s1) - self.assertEqual(got, ref_i16(op, s0, s1)) - - def test_sgpr_opsel_and_clamp(self) -> None: - # SGPR scalar source broadcast - for op in ("v_add_i16", "v_sub_i16", "v_add_i16_e64", "v_sub_i16_e64"): - spv = translate_i16_ps( - f"ps_{op}_sgpr", - [ - "s_mov_b32 s0, 0x1234000a", - "v_mov_b32 v1, 0xabcd0003", - f"v_mov_b32 v0, {OLD_V0:#x}", - f"{op} v0, s0, v1", - ], - ) - got = si.run_fragment(spv)["%out_mrt0"][0] - self.assertEqual(got, ref_i16(op, 0x1234000A, 0xABCD0003)) - - # Signed clamp on _e64: saturate to [-32768, 32767] - self.assertEqual( - run_i16_op("v_add_i16_e64", 0x7FFF, 2, mods="clamp"), - (OLD_V0 & 0xFFFF0000) | 0x7FFF, - ) - self.assertEqual( - run_i16_op("v_sub_i16_e64", 0x8000, 1, mods="clamp"), - (OLD_V0 & 0xFFFF0000) | 0x8000, - ) - - # op_sel on _e64: select high half of src0 and write to high half of dst - got_opsel = run_i16_op( - "v_add_i16_e64", - 0x000A0001, - 0x00020005, - mods="op_sel:[1,0,1]", - ) - self.assertEqual( - got_opsel, - ref_i16("v_add_i16_e64", 0x000A0001, 0x00020005, sel=(1, 0, 1)), - ) - - def test_seeded_random(self) -> None: - rng = random.Random(0x116) - ops = ("v_add_i16", "v_add_i16_e64", "v_sub_i16", "v_sub_i16_e64") - for _ in range(40): - op = rng.choice(ops) - s0 = rng.getrandbits(32) - s1 = rng.getrandbits(32) - old = rng.getrandbits(32) - clamp = op.endswith("_e64") and bool(rng.getrandbits(1)) - mods = "clamp" if clamp else "" - with self.subTest(op=op, s0=hex(s0), s1=hex(s1), clamp=clamp): - got = run_i16_op(op, s0, s1, old=old, mods=mods) - self.assertEqual(got, ref_i16(op, s0, s1, old=old, clamp=clamp)) - - def test_negative_controls_spirv_mutation(self) -> None: - # Negative control 1: swapping OpIAdd <-> OpISub in memory changes the result. - spv_add = translate_i16_ps( - "ps_neg_ctrl_add", - [ - "v_mov_b32 v1, 10", - "v_mov_b32 v2, 3", - "v_add_i16 v0, v1, v2", - ], - ) - self.assertEqual(si.run_fragment(spv_add)["%out_mrt0"][0], 13) - self.assertIn("= OpIAdd %int ", spv_add) - spv_add_mut = spv_add.replace("= OpIAdd %int ", "= OpISub %int ", 1) - self.assertEqual(si.run_fragment(spv_add_mut)["%out_mrt0"][0], 7) - - spv_sub = translate_i16_ps( - "ps_neg_ctrl_sub", - [ - "v_mov_b32 v1, 10", - "v_mov_b32 v2, 3", - "v_sub_i16 v0, v1, v2", - ], - ) - self.assertEqual(si.run_fragment(spv_sub)["%out_mrt0"][0], 7) - self.assertIn("= OpISub %int ", spv_sub) - spv_sub_mut = spv_sub.replace("= OpISub %int ", "= OpIAdd %int ", 1) - self.assertEqual(si.run_fragment(spv_sub_mut)["%out_mrt0"][0], 13) - - # Negative control 2: removing the final 0xFFFF (65535) output mask leaks - # sign-extended bits [31:16] from the 32-bit signed sum (-1 + -1 = -2). - spv_mask = translate_i16_ps( - "ps_neg_ctrl_mask", - [ - "v_mov_b32 v1, 0xffff", - "v_mov_b32 v2, 0xffff", - "v_add_i16 v0, v1, v2", - ], - ) - self.assertEqual(si.run_fragment(spv_mask)["%out_mrt0"][0], 0x0000FFFE) - const_match = re.search( - r"^(%\S+)\s*=\s*OpConstant\s+%uint\s+65535\b", spv_mask, re.MULTILINE - ) - self.assertIsNotNone(const_match) - c65535 = const_match.group(1) - mask_matches = list( - re.finditer( - rf"= OpBitwiseAnd %uint (%\S+) {re.escape(c65535)}\b", spv_mask - ) - ) - # one 16-bit mask at least: SHADER-315's constant folding removed the ones on the literal operands - self.assertGreaterEqual(len(mask_matches), 1) - last = mask_matches[-1] - spv_mask_mut = ( - spv_mask[: last.start()] - + f"= OpCopyObject %uint {last.group(1)}" - + spv_mask[last.end() :] - ) - self.assertEqual(si.run_fragment(spv_mask_mut)["%out_mrt0"][0], 0xFFFFFFFE) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_alu_add_u16.py b/tests/semantic/test_alu_add_u16.py deleted file mode 100644 index f5e89024b..000000000 --- a/tests/semantic/test_alu_add_u16.py +++ /dev/null @@ -1,126 +0,0 @@ -"""Semantic translation tests for RDNA2 16-bit unsigned add v_add_u16. - -Translates a synthetic pixel-shader listing through tools/rdna2spirv.translate() --> SPIR-V -> tests/semantic/spirv_mini_interp.py and compares the result against -a plain-Python reference: (x + y) & 0xFFFF (16-bit wraparound). - -Covers: - - Basic 16-bit add: small values - - Wraparound at 16-bit boundary (0xFFFF + 1 = 0) - - Both operands large (0x8000 + 0x8000 wraps to 0) - - Reference comparison across varied 16-bit patterns - - 50 randomized cases vs reference - - Negative control: result differs from each input for non-trivial cases -""" -import os -import struct -import sys -import tempfile -import unittest -import warnings -import random - -HERE = os.path.dirname(os.path.abspath(__file__)) -ROOT = os.path.dirname(os.path.dirname(HERE)) -TOOLS_DIR = os.environ.get("LEONIDA_TOOLS_DIR") or os.path.join(ROOT, "tools") - -sys.dont_write_bytecode = True -if TOOLS_DIR not in sys.path: - sys.path.insert(0, TOOLS_DIR) -if HERE not in sys.path: - sys.path.insert(0, HERE) - -import rdna2spirv # noqa: E402 -import spirv_mini_interp as si # noqa: E402 - -M16 = 0xFFFF -STUB_DXBC = b"DXBC" + bytes(24) + struct.pack(" int: - """Plain-Python reference for v_add_u16: (x + y) mod 2^16.""" - return (x + y) & M16 - - -def run_op(x: int, y: int) -> int: - """Translate and run a shader that computes v_add_u16 v1, v2, v3 with v2=x, v3=y. - - Uses a unique temp directory per call to avoid file-sharing issues. - """ - asm = ( - "; test_add_u16\n" - f"\tv_mov_b32_e32 v2, {x & M16:#x}\n" - f"\tv_mov_b32_e32 v3, {y & M16:#x}\n" - "\tv_add_u16 v1, v2, v3\n" - "\ts_waitcnt vmcnt(0)\n" - "\texp mrt0 v1, v1, v1, v1 done vm\n" - "\ts_endpgm\n" - ) - tmp = tempfile.TemporaryDirectory() - disasm_dir = os.path.join(tmp.name, "disasm") - os.mkdir(disasm_dir) - src_path = os.path.join(disasm_dir, "ps_add_u16.s") - with open(os.path.join(tmp.name, "ps_add_u16.dxbc"), "wb") as f: - f.write(STUB_DXBC) - with open(src_path, "w", encoding="utf-8") as f: - f.write(asm) - with warnings.catch_warnings(): - warnings.simplefilter("ignore", ResourceWarning) - spv = rdna2spirv.translate(src_path) - w = si.run_fragment(spv)["%out_mrt0"] - tmp.cleanup() - return w[0] & M16 - - -class ALUVAddU16Tests(unittest.TestCase): - def test_add_u16_basic(self): - self.assertEqual(run_op(0, 0), 0) - self.assertEqual(run_op(1, 2), 3) - self.assertEqual(run_op(100, 200), 300) - self.assertEqual(run_op(0x7FFF, 1), 0x8000) - - def test_add_u16_wraparound(self): - # 0xFFFF + 1 wraps to 0 - self.assertEqual(run_op(M16, 1), 0) - # 0x8000 + 0x8000 = 0x10000 wraps to 0 - self.assertEqual(run_op(0x8000, 0x8000), 0) - # 0xFFFF + 0xFFFF = 0x1FFFE wraps to 0xFFFE - self.assertEqual(run_op(M16, M16), 0xFFFE) - # 0xABCD + 0x1234 = 0xBE01 (no wraparound) - self.assertEqual(run_op(0xABCD, 0x1234), 0xBE01) - - def test_add_u16_reference(self): - cases = [ - (0, 0, 0), - (1, 1, 2), - (0xFFFF, 0, 0xFFFF), - (0, 0xFFFF, 0xFFFF), - (0xFF, 0xFF, 0x1FE), - (0x1234, 0x5678, 0x68AC), - (0xFFFF, 0xFFFF, 0xFFFE), - ] - for x, y, expected in cases: - with self.subTest(x=hex(x), y=hex(y)): - self.assertEqual(run_op(x, y), expected) - self.assertEqual(run_op(x, y), ref_add_u16(x, y)) - - def test_add_u16_random_vs_reference(self): - rng = random.Random(0xC0FFEE) - for _ in range(50): - x = rng.getrandbits(16) - y = rng.getrandbits(16) - with self.subTest(x=hex(x), y=hex(y)): - self.assertEqual(run_op(x, y), ref_add_u16(x, y)) - - def test_add_u16_negative_control(self): - # For non-trivial inputs, result differs from each input. - x, y = 0x1234, 0x5678 - res = run_op(x, y) - expected = ref_add_u16(x, y) - self.assertEqual(res, expected) - self.assertNotEqual(res, x) - self.assertNotEqual(res, y) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_alu_alignbit.py b/tests/semantic/test_alu_alignbit.py deleted file mode 100644 index 73a7efc46..000000000 --- a/tests/semantic/test_alu_alignbit.py +++ /dev/null @@ -1,467 +0,0 @@ -"""Semantic interpreter tests for RDNA2 funnel shift bit alignment (v_alignbit_b32). - -v_alignbit_b32 D, S0, S1, S2: -Concatenates S0 and S1 into a 64-bit value {S0, S1} (where S0 is the high 32 bits -and S1 is the low 32 bits), shifts right logically by the 5-bit shift count -(S2 & 31), and extracts the low 32 bits of the result: - D = (({S0, S1} >> (S2 & 31)) & 0xFFFFFFFF) - -Properties verified: - * Full 5-bit shift range (shifts 0 through 31). - * Register boundary crossing: bit propagation from S0 across the 32-bit dword - boundary into the upper bits of the destination word as S1 bits shift out. - * Shift amount masking: hardware masks shift amounts with 0x1F (bits 4:0), so - shifts of 32, 33, 64, or negative / large integers wrap modulo 32. - * Shift count zero: returns S1 (the low word) exactly without invoking undefined - SPIR-V shift operations. - * Common compiler idioms: - - S0 == S1: 32-bit rotate right (ror). - - S0 == 0: logical shift right of S1 (lsr). - - S1 == 0: logical shift left of S0 by (32 - shift) for shift in 1..31. - * Operand encoding forms: VGPR, SGPR, and inline integer constant shift counts. - * Dual execution paths: - 1. RDNA2 assembly parsed and translated to SPIR-V via tools/rdna2spirv.py, - then evaluated in tests/semantic/spirv_mini_interp.py. - 2. Isolated SPIR-V instruction sequence emitted for v_alignbit_b32 to check - shift guard safety ((32 - m) & 31) against SPIR-V undefined shift rules. -""" -from __future__ import annotations - -import os -import struct -import sys -import tempfile -import unittest -import warnings - -HERE = os.path.dirname(os.path.abspath(__file__)) -ROOT = os.path.dirname(os.path.dirname(HERE)) -TOOLS_DIR = os.environ.get("LEONIDA_TOOLS_DIR") or os.path.join(ROOT, "tools") - -sys.dont_write_bytecode = True -if TOOLS_DIR not in sys.path: - sys.path.insert(0, TOOLS_DIR) -if HERE not in sys.path: - sys.path.insert(0, HERE) - -import rdna2spirv # noqa: E402 -import spirv_mini_interp as si # noqa: E402 - -MASK32 = 0xFFFFFFFF -MASK64 = 0xFFFFFFFFFFFFFFFF -STUB_DXBC = b"DXBC" + bytes(24) + struct.pack(" int: - """RDNA2 v_alignbit_b32 reference oracle: low 32 bits of ({src0, src1} >> (shift & 31)).""" - data = ((src0 & MASK32) << 32) | (src1 & MASK32) - return (data >> (shift & 31)) & MASK32 - - -def interp_v_alignbit_b32(s0: int, s1: int, s2: int) -> int: - """Bit-level model of funnel shift alignment decomposing high/low word contributions.""" - shift = s2 & 31 - s0 &= MASK32 - s1 &= MASK32 - if shift == 0: - return s1 - lo_contrib = s1 >> shift - hi_contrib = (s0 << (32 - shift)) & MASK32 - return lo_contrib | hi_contrib - - -def run_spirv_alignbit(s0: int, s1: int, s2: int) -> int: - """Executes the exact SPIR-V instruction sequence emitted by rdna2spirv for v_alignbit_b32.""" - module = f"""\ -OpCapability Shader -%glsl = OpExtInstImport "GLSL.std.450" -OpMemoryModel Logical GLSL450 -OpEntryPoint Fragment %main "main" %out -%void = OpTypeVoid -%fn = OpTypeFunction %void -%uint = OpTypeInt 32 0 -%bool = OpTypeBool -%_ptr_Output_uint = OpTypePointer Output %uint -%out = OpVariable %_ptr_Output_uint Output -%c_hi = OpConstant %uint {s0 & MASK32} -%c_lo = OpConstant %uint {s1 & MASK32} -%c_sh = OpConstant %uint {s2 & MASK32} -%c31 = OpConstant %uint 31 -%c32 = OpConstant %uint 32 -%c0 = OpConstant %uint 0 -%main = OpFunction %void None %fn -%entry = OpLabel -%m = OpBitwiseAnd %uint %c_sh %c31 -%inv0 = OpISub %uint %c32 %m -%inv = OpBitwiseAnd %uint %inv0 %c31 -%a1 = OpShiftRightLogical %uint %c_lo %m -%b1 = OpShiftLeftLogical %uint %c_hi %inv -%r0 = OpBitwiseOr %uint %a1 %b1 -%nz = OpINotEqual %bool %m %c0 -%r = OpSelect %uint %nz %r0 %c_lo -OpStore %out %r -OpReturn -OpFunctionEnd -""" - return si.run_fragment(module)["%out"][0] - - -_TMP_DIR: tempfile.TemporaryDirectory | None = None -_SRC_PATH: str | None = None - - -def setUpModule() -> None: - global _TMP_DIR, _SRC_PATH - _TMP_DIR = tempfile.TemporaryDirectory() - disasm_dir = os.path.join(_TMP_DIR.name, "disasm") - os.mkdir(disasm_dir) - _SRC_PATH = os.path.join(disasm_dir, "ps_alignbit.s") - with open(os.path.join(_TMP_DIR.name, "ps_alignbit.dxbc"), "wb") as f: - f.write(STUB_DXBC) - - -def tearDownModule() -> None: - global _TMP_DIR, _SRC_PATH - if _TMP_DIR is not None: - _TMP_DIR.cleanup() - _TMP_DIR = None - _SRC_PATH = None - - -def run_alignbit( - src0: int, - src1: int, - shift: int, - inline_shift: bool = False, - src0_sgpr: bool = False, - src1_sgpr: bool = False, - shift_sgpr: bool = False, -) -> int: - """Translate and run synthetic RDNA2 shader with v_alignbit_b32, returning mrt0.""" - if _TMP_DIR is None: - setUpModule() - assert _SRC_PATH is not None - - lines: list[str] = [] - - # Emit src0 operand - if src0_sgpr: - lines.append(f"\ts_mov_b32 s0, {src0 & MASK32:#x}") - op_src0 = "s0" - else: - lines.append(f"\tv_mov_b32 v1, {src0 & MASK32:#x}") - op_src0 = "v1" - - # Emit src1 operand - if src1_sgpr: - lines.append(f"\ts_mov_b32 s1, {src1 & MASK32:#x}") - op_src1 = "s1" - else: - lines.append(f"\tv_mov_b32 v2, {src1 & MASK32:#x}") - op_src1 = "v2" - - # Emit shift operand - if inline_shift: - op_shift = str(shift) - elif shift_sgpr: - lines.append(f"\ts_mov_b32 s2, {shift & MASK32:#x}") - op_shift = "s2" - else: - lines.append(f"\tv_mov_b32 v3, {shift & MASK32:#x}") - op_shift = "v3" - - lines.append(f"\tv_alignbit_b32 v0, {op_src0}, {op_src1}, {op_shift}") - asm = "; test_alignbit\n" + "\n".join(lines) + "\n\texp mrt0 v0, v0, v0, v0 done vm\n\ts_endpgm\n" - - with open(_SRC_PATH, "w", encoding="utf-8") as f: - f.write(asm) - - with warnings.catch_warnings(): - warnings.simplefilter("ignore", ResourceWarning) - spv = rdna2spirv.translate(_SRC_PATH) - - return si.run_fragment(spv)["%out_mrt0"][0] - - -class ReferenceOracleTests(unittest.TestCase): - """Verifies reference functions against hand-worked values and mathematical identities.""" - - def test_reference_known_vectors(self) -> None: - s0, s1 = 0x12345678, 0x9ABCDEF0 - # shift 0 -> low word unmodified - self.assertEqual(ref_alignbit(s0, s1, 0), 0x9ABCDEF0) - self.assertEqual(interp_v_alignbit_b32(s0, s1, 0), 0x9ABCDEF0) - - # shift 1 -> low word shifted right by 1, bit 0 of s0 enters bit 31 - # s1 >> 1 = 0x4D5E6F78, s0 & 1 = 0, so bit 31 is 0 -> 0x4D5E6F78 - self.assertEqual(ref_alignbit(s0, s1, 1), 0x4D5E6F78) - self.assertEqual(interp_v_alignbit_b32(s0, s1, 1), 0x4D5E6F78) - - # shift 4 -> one hex nibble shifted across - # {0x12345678, 0x9ABCDEF0} >> 4 = 0x0123456789ABCDEF - self.assertEqual(ref_alignbit(s0, s1, 4), 0x89ABCDEF) - self.assertEqual(interp_v_alignbit_b32(s0, s1, 4), 0x89ABCDEF) - - # shift 8 -> one byte shifted across - self.assertEqual(ref_alignbit(s0, s1, 8), 0x789ABCDE) - self.assertEqual(interp_v_alignbit_b32(s0, s1, 8), 0x789ABCDE) - - # shift 16 -> two bytes shifted across - self.assertEqual(ref_alignbit(s0, s1, 16), 0x56789ABC) - self.assertEqual(interp_v_alignbit_b32(s0, s1, 16), 0x56789ABC) - - # shift 24 -> three bytes shifted across - self.assertEqual(ref_alignbit(s0, s1, 24), 0x3456789A) - self.assertEqual(interp_v_alignbit_b32(s0, s1, 24), 0x3456789A) - - # shift 31 -> 31 bits from s0, 1 bit from s1 - # {0x12345678, 0x9ABCDEF0} >> 31 = 0x2468ACF1 - self.assertEqual(ref_alignbit(s0, s1, 31), 0x2468ACF1) - self.assertEqual(interp_v_alignbit_b32(s0, s1, 31), 0x2468ACF1) - - # shift 32 -> masked to 0 - self.assertEqual(ref_alignbit(s0, s1, 32), 0x9ABCDEF0) - self.assertEqual(interp_v_alignbit_b32(s0, s1, 32), 0x9ABCDEF0) - - def test_interp_matches_ref_all_shifts(self) -> None: - vectors = [ - (0x12345678, 0x9ABCDEF0), - (0xAAAAAAAA, 0x55555555), - (0xFFFFFFFF, 0x00000000), - (0x00000000, 0xFFFFFFFF), - (0xDEADBEEF, 0xCAFEBABE), - (0x80000001, 0x7FFFFFFE), - ] - for s0, s1 in vectors: - for shift in range(64): - with self.subTest(s0=hex(s0), s1=hex(s1), shift=shift): - self.assertEqual( - interp_v_alignbit_b32(s0, s1, shift), - ref_alignbit(s0, s1, shift), - ) - - -class AlignbitSemanticInterpreterTests(unittest.TestCase): - """Semantic interpreter tests for RDNA2 v_alignbit_b32 translation and execution.""" - - def test_every_5bit_shift_count(self) -> None: - """Every shift count 0..31 across diverse bit patterns.""" - test_pairs = [ - (0x12345678, 0x9ABCDEF0), - (0xAAAAAAAA, 0x55555555), - (0x55555555, 0xAAAAAAAA), - (0xFFFFFFFF, 0x00000000), - (0x00000000, 0xFFFFFFFF), - (0x80000001, 0x7FFFFFFE), - (0xDEADBEEF, 0xCAFEBABE), - (0x13579BDF, 0x2468ACE0), - (0x8899AABB, 0x11223344), - ] - for s0, s1 in test_pairs: - for shift in range(32): - with self.subTest(s0=hex(s0), s1=hex(s1), shift=shift): - got = run_alignbit(s0, s1, shift) - want = ref_alignbit(s0, s1, shift) - self.assertEqual(got, want) - - def test_register_boundary_crossing_single_bit(self) -> None: - """Validates bit movement across the 32-bit register boundary.""" - # Test a single bit set in S0 crossing into the MSB of the result - # S0 = 1 (bit 0 set), S1 = 0 - # For shift = 1: bit 0 of S0 moves to bit 31 of result (0x80000000) - # For shift = 2: bit 0 of S0 moves to bit 30 of result (0x40000000) - # For shift = k (1..31): bit 0 of S0 moves to bit (32 - k) - for shift in range(1, 32): - with self.subTest(direction="s0_to_result", shift=shift): - got = run_alignbit(1, 0, shift) - want = 1 << (32 - shift) - self.assertEqual(got, want) - - # When shift is 0, S0 contribution is completely discarded - self.assertEqual(run_alignbit(1, 0, 0), 0) - - # Test single bit in S1 crossing out towards the LSB - # S0 = 0, S1 = 0x80000000 (bit 31 set) - # For shift = 1: bit 31 of S1 moves to bit 30 (0x40000000) - # For shift = 31: bit 31 of S1 moves to bit 0 (0x00000001) - for shift in range(32): - with self.subTest(direction="s1_shifted", shift=shift): - got = run_alignbit(0, 0x80000000, shift) - want = (0x80000000 >> shift) & MASK32 - self.assertEqual(got, want) - - # Test full 64-bit single-bit walk across boundary - # For bit index 0..63 in {s0, s1}: - # shift by 16: bits 16..47 should map to bits 0..31 of output - shift = 16 - for bit_pos in range(64): - if bit_pos < 32: - s0_val, s1_val = 0, 1 << bit_pos - else: - s0_val, s1_val = 1 << (bit_pos - 32), 0 - - with self.subTest(bit_pos=bit_pos, shift=shift): - got = run_alignbit(s0_val, s1_val, shift) - expected_bit = bit_pos - shift - want = (1 << expected_bit) if (0 <= expected_bit < 32) else 0 - self.assertEqual(got, want) - - def test_shift_zero_returns_low_word(self) -> None: - """Shift 0 (and multiples of 32) must preserve S1 exactly.""" - test_words = [ - (0xDEADBEEF, 0x12345678), - (0xFFFFFFFF, 0x00000000), - (0x00000000, 0xFFFFFFFF), - (0x13579BDF, 0x2468ACE0), - (0x80000000, 0x7FFFFFFF), - ] - for s0, s1 in test_words: - with self.subTest(s0=hex(s0), s1=hex(s1)): - self.assertEqual(run_alignbit(s0, s1, 0), s1) - self.assertEqual(run_alignbit(s0, s1, 0, inline_shift=True), s1) - - def test_shift_amount_masking_5bit(self) -> None: - """Shift amounts >= 32 must be masked with 0x1F (bits 4:0).""" - s0, s1 = 0x8899AABB, 0x11223344 - high_shifts = [ - 32, # 32 & 31 == 0 - 33, # 33 & 31 == 1 - 36, # 36 & 31 == 4 - 40, # 40 & 31 == 8 - 48, # 48 & 31 == 16 - 63, # 63 & 31 == 31 - 64, # 64 & 31 == 0 - 65, # 65 & 31 == 1 - 127, # 127 & 31 == 31 - 128, # 128 & 31 == 0 - 255, # 255 & 31 == 31 - 1024, # 1024 & 31 == 0 - 0x80000000, # bit 31 set, low 5 bits 0 - 0x80000007, # low 5 bits 7 - 0xFFFFFFFF, # all bits set, low 5 bits 31 - 0xFFFFFFE0, # low 5 bits 0 - 0xFFFFFFE1, # low 5 bits 1 - ] - for shift in high_shifts: - with self.subTest(shift=hex(shift)): - got = run_alignbit(s0, s1, shift) - want = ref_alignbit(s0, s1, shift) - self.assertEqual(got, want) - - def test_inline_constant_shifts(self) -> None: - """Inline literal constants for the shift operand.""" - s0, s1 = 0xA1B2C3D4, 0xE5F60718 - for shift in (0, 1, 2, 5, 8, 15, 16, 23, 24, 30, 31, 32, 33, 63): - with self.subTest(shift=shift): - got = run_alignbit(s0, s1, shift, inline_shift=True) - want = ref_alignbit(s0, s1, shift) - self.assertEqual(got, want) - - def test_sgpr_operands(self) -> None: - """VOP3 instruction encoding with scalar register sources.""" - s0, s1, shift = 0x12345678, 0x9ABCDEF0, 12 - want = ref_alignbit(s0, s1, shift) - - # S0 in SGPR - self.assertEqual(run_alignbit(s0, s1, shift, src0_sgpr=True), want) - # S1 in SGPR - self.assertEqual(run_alignbit(s0, s1, shift, src1_sgpr=True), want) - # Shift in SGPR - self.assertEqual(run_alignbit(s0, s1, shift, shift_sgpr=True), want) - - def test_rotate_right_compiler_idiom(self) -> None: - """v_alignbit_b32 with S0 == S1 is identical to 32-bit rotate right.""" - rot_patterns = [ - 0x80000001, - 0x12345678, - 0xA5A5A5A5, - 0xDEADBEEF, - 0x00000001, - 0xFFFFFFFF, - ] - for x in rot_patterns: - for shift in range(32): - with self.subTest(x=hex(x), shift=shift): - got = run_alignbit(x, x, shift) - if shift == 0: - want_ror = x & MASK32 - else: - want_ror = ((x >> shift) | (x << (32 - shift))) & MASK32 - self.assertEqual(got, want_ror) - - def test_logical_shift_equivalences(self) -> None: - """Validates funnel shift degenerating to LSR or LSL.""" - val = 0xA7B8C9D0 - - # S0 == 0 -> equivalent to LSR (logical shift right of S1) - for shift in range(32): - with self.subTest(op="lsr_equiv", shift=shift): - got = run_alignbit(0, val, shift) - want = (val >> shift) & MASK32 - self.assertEqual(got, want) - - # S1 == 0 -> equivalent to LSL (logical shift left of S0 by (32 - shift)) - for shift in range(1, 32): - with self.subTest(op="lsl_equiv", shift=shift): - got = run_alignbit(val, 0, shift) - want = (val << (32 - shift)) & MASK32 - self.assertEqual(got, want) - - # When shift == 0 and S1 == 0, output must be 0 - self.assertEqual(run_alignbit(val, 0, 0), 0) - - def test_wave_lane_vector_simulation(self) -> None: - """Simulates SIMD wave-64 lane execution with lane-dependent shift amounts.""" - for lane_id in range(64): - # Vary inputs and shifts deterministically across lanes - s0 = (0x10000000 + (lane_id * 0x01010101)) & MASK32 - s1 = (0xF0000000 - (lane_id * 0x02020202)) & MASK32 - shift = lane_id # tests shifts 0..63 (triggering modulo 32 above 31) - - with self.subTest(lane=lane_id, shift=shift): - got = interp_v_alignbit_b32(s0, s1, shift) - want = ref_alignbit(s0, s1, shift) - self.assertEqual(got, want) - - -class DirectSpirvSequenceTests(unittest.TestCase): - """Direct execution of the SPIR-V sequence emitted for v_alignbit_b32.""" - - def test_spirv_sequence_all_shifts(self) -> None: - """Tests the standalone SPIR-V instruction sequence against the oracle.""" - test_pairs = [ - (0xFEEDBEEF, 0x01234567), - (0x0F0F0F0F, 0xF0F0F0F0), - (0x00FF00FF, 0xFF00FF00), - ] - for s0, s1 in test_pairs: - for shift in range(32): - with self.subTest(s0=hex(s0), s1=hex(s1), shift=shift): - got = run_spirv_alignbit(s0, s1, shift) - want = ref_alignbit(s0, s1, shift) - self.assertEqual(got, want) - - def test_spirv_shift_guard_at_zero(self) -> None: - """Ensures shift=0 does not trigger SPIR-V undefined shift (>= 32 bits). - - In SPIR-V, OpShiftLeftLogical / OpShiftRightLogical with shift operand >= bit width - is undefined. For shift=0, (32 - m) is 32, but rdna2spirv masks it with 31: - inv = (32 - m) & 31 = 0, safely shifting by 0 and letting OpSelect pick lo. - """ - for s0, s1 in ((0x12345678, 0x9ABCDEF0), (0xFFFFFFFF, 0x00000000), (0, 0xFFFFFFFF)): - with self.subTest(s0=hex(s0), s1=hex(s1)): - got = run_spirv_alignbit(s0, s1, 0) - self.assertEqual(got, s1) - - def test_spirv_masked_shift_counts(self) -> None: - """Direct SPIR-V sequence evaluation with out-of-range shift amounts.""" - s0, s1 = 0x13579BDF, 0x2468ACE0 - for shift in (32, 33, 40, 63, 64, 127, 0xFFFFFFFF): - with self.subTest(shift=hex(shift)): - got = run_spirv_alignbit(s0, s1, shift) - want = ref_alignbit(s0, s1, shift) - self.assertEqual(got, want) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_alu_alignbyte.py b/tests/semantic/test_alu_alignbyte.py deleted file mode 100644 index 5bc6a1fce..000000000 --- a/tests/semantic/test_alu_alignbyte.py +++ /dev/null @@ -1,104 +0,0 @@ -"""Semantic interpreter tests for RDNA2 v_alignbyte_b32. - -v_alignbyte_b32 D, S0, S1, S2: the low 32 bits of ({S0, S1} >> (8 * (S2 & 3))), S1 being the low word (RDNA2 ISA -reference, V_ALIGNBYTE_B32). Each case translates a synthetic pixel shader with tools/rdna2spirv.py, runs it in -tests/semantic/spirv_mini_interp.py and compares the mrt0 word with a plain-Python reference. The interpreter -rejects shifts of 32 or more (undefined in SPIR-V), so S2 & 3 == 0 also checks that the translation never emits one, -including on the side of the OpSelect that is discarded. -""" -import os -import struct -import sys -import tempfile -import unittest -import warnings - -HERE = os.path.dirname(os.path.abspath(__file__)) -ROOT = os.path.dirname(os.path.dirname(HERE)) -TOOLS_DIR = os.environ.get("LEONIDA_TOOLS_DIR") or os.path.join(ROOT, "tools") - -sys.dont_write_bytecode = True -sys.path.insert(0, TOOLS_DIR) -sys.path.insert(0, HERE) - -import rdna2spirv # noqa: E402 -import spirv_mini_interp as si # noqa: E402 - -MASK32 = 0xFFFFFFFF -STUB_DXBC = b"DXBC" + bytes(24) + struct.pack(" int: - return ((((src0 & MASK32) << 32) | (src1 & MASK32)) >> (8 * (sel & 3))) & MASK32 - - -_TMP_DIR = None -_SRC_PATH = None - - -def setUpModule(): - global _TMP_DIR, _SRC_PATH - _TMP_DIR = tempfile.TemporaryDirectory() - disasm_dir = os.path.join(_TMP_DIR.name, "disasm") - os.mkdir(disasm_dir) - _SRC_PATH = os.path.join(disasm_dir, "ps_alignbyte.s") - with open(os.path.join(_TMP_DIR.name, "ps_alignbyte.dxbc"), "wb") as f: - f.write(STUB_DXBC) - - -def tearDownModule(): - global _TMP_DIR - if _TMP_DIR is not None: - _TMP_DIR.cleanup() - _TMP_DIR = None - - -def run_alignbyte(src0: int, src1: int, sel: int, inline: bool = False) -> int: - if _TMP_DIR is None: - setUpModule() - lines = [f"\tv_mov_b32 v1, {src0 & MASK32:#x}", f"\tv_mov_b32 v2, {src1 & MASK32:#x}"] - if inline: - lines.append(f"\tv_alignbyte_b32 v0, v1, v2, {sel}") - else: - lines += [f"\tv_mov_b32 v3, {sel & MASK32:#x}", "\tv_alignbyte_b32 v0, v1, v2, v3"] - asm = "; test_alignbyte\n" + "\n".join(lines) + "\n\texp mrt0 v0, v0, v0, v0 done vm\n\ts_endpgm\n" - with open(_SRC_PATH, "w", encoding="utf-8") as f: - f.write(asm) - with warnings.catch_warnings(): - warnings.simplefilter("ignore", ResourceWarning) - spv = rdna2spirv.translate(_SRC_PATH) - return si.run_fragment(spv)["%out_mrt0"][0] - - -class AlignbyteTests(unittest.TestCase): - def test_reference(self): - self.assertEqual(ref_alignbyte(0x8899AABB, 0x11223344, 0), 0x11223344) - self.assertEqual(ref_alignbyte(0x8899AABB, 0x11223344, 1), 0xBB112233) - self.assertEqual(ref_alignbyte(0x8899AABB, 0x11223344, 3), 0x99AABB11) - self.assertEqual(ref_alignbyte(0x8899AABB, 0x11223344, 4), 0x11223344) - - def test_every_byte_shift(self): - for src0, src1 in ((0x8899AABB, 0x11223344), (0xFFFFFFFF, 0), (0, 0xFFFFFFFF), (0x80000001, 0x7FFFFFFE)): - for sel in range(4): - with self.subTest(src0=hex(src0), src1=hex(src1), sel=sel): - self.assertEqual(run_alignbyte(src0, src1, sel), ref_alignbyte(src0, src1, sel)) - - def test_shift_zero_returns_low_word(self): - for sel in (0, 4, 8, 0x100, 0xFFFFFFFC): - with self.subTest(sel=hex(sel)): - self.assertEqual(run_alignbyte(0xDEADBEEF, 0x12345678, sel), 0x12345678) - - def test_selector_is_masked_to_2_bits(self): - for sel in (5, 6, 7, 0xFFFFFFFF, 0x80000002): - with self.subTest(sel=hex(sel)): - self.assertEqual(run_alignbyte(0x8899AABB, 0x11223344, sel), ref_alignbyte(0x8899AABB, 0x11223344, sel)) - - def test_inline_selector(self): - for sel in range(4): - with self.subTest(sel=sel): - self.assertEqual(run_alignbyte(0x8899AABB, 0x11223344, sel, inline=True), - ref_alignbyte(0x8899AABB, 0x11223344, sel)) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_alu_ashr_i64.py b/tests/semantic/test_alu_ashr_i64.py deleted file mode 100644 index c30af6d3c..000000000 --- a/tests/semantic/test_alu_ashr_i64.py +++ /dev/null @@ -1,576 +0,0 @@ -from __future__ import annotations - -"""Semantic interpreter tests for RDNA2 64-bit vector arithmetic shift right (v_ashrrev_i64). - -RDNA2 ISA definition: - v_ashrrev_i64 dst, src0, src1 - - dst: 64-bit VGPR pair v[d:d+1] - - src0: 32-bit shift count (VGPR, SGPR, or inline constant). Bits [5:0] define the shift amount. - - src1: 64-bit input operand (VGPR pair v[s:s+1], SGPR pair s[s:s+1], or inline constant). - - Operation: dst = (int64)src1 >> (src0 & 63), sign-extended with bit 63 copied into upper bits. -""" - -import gc -import os -import random -import struct -import sys -import tempfile -import unittest -import warnings - -HERE = os.path.dirname(os.path.abspath(__file__)) -ROOT = os.path.dirname(os.path.dirname(HERE)) -TOOLS_DIR = os.environ.get("LEONIDA_TOOLS_DIR") or os.path.join(ROOT, "tools") - -sys.dont_write_bytecode = True -if TOOLS_DIR not in sys.path: - sys.path.insert(0, TOOLS_DIR) -if HERE not in sys.path: - sys.path.insert(0, HERE) - -import rdna2spirv # noqa: E402 -import spirv_mini_interp as si # noqa: E402 - -MASK32 = 0xFFFFFFFF -MASK64 = 0xFFFFFFFFFFFFFFFF -SIGN32 = 0x80000000 -SIGN64 = 1 << 63 -STUB_DXBC = b"DXBC" + bytes(24) + struct.pack(" None: - global _TMP_DIR, _SRC_PATH - _TMP_DIR = tempfile.TemporaryDirectory() - disasm_dir = os.path.join(_TMP_DIR.name, "disasm") - os.mkdir(disasm_dir) - _SRC_PATH = os.path.join(disasm_dir, "ps_ashr_i64.s") - with open(os.path.join(_TMP_DIR.name, "ps_ashr_i64.dxbc"), "wb") as f: - f.write(STUB_DXBC) - - -def tearDownModule() -> None: - global _TMP_DIR, _SRC_PATH - if _TMP_DIR is not None: - gc.collect() - try: - _TMP_DIR.cleanup() - except Exception: - pass - _TMP_DIR = None - _SRC_PATH = None - - -def u32(x: int) -> int: - """Normalize integer to 32-bit unsigned.""" - return x & MASK32 - - -def s32(x: int) -> int: - """Interpret 32-bit unsigned integer as signed two's complement.""" - x &= MASK32 - return x - (1 << 32) if (x & SIGN32) else x - - -def u64(x: int) -> int: - """Normalize integer to 64-bit unsigned.""" - return x & MASK64 - - -def s64(x: int) -> int: - """Interpret 64-bit unsigned integer as signed two's complement.""" - x &= MASK64 - return x - (1 << 64) if (x & SIGN64) else x - - -def decompose_u64(val: int) -> tuple[int, int]: - """Decompose a 64-bit unsigned integer into (lo, hi) 32-bit dwords.""" - val &= MASK64 - return val & MASK32, (val >> 32) & MASK32 - - -def compose_u64(lo: int, hi: int) -> int: - """Compose two 32-bit dwords into a 64-bit unsigned integer.""" - return ((hi & MASK32) << 32) | (lo & MASK32) - - -def ref_ashr_i64(shift: int, val: int) -> int: - """Ideal reference oracle for v_ashrrev_i64: (int64)val >> (shift & 63).""" - sh = shift & 63 - return (s64(val) >> sh) & MASK64 - - -def emulate_ashr_i64_dwords(shift: int, lo: int, hi: int) -> tuple[int, int]: - """Emulate 64-bit arithmetic shift right using 32-bit register pair datapath.""" - sh = shift & 63 - lo &= MASK32 - hi &= MASK32 - - if sh == 0: - return lo, hi - if sh < 32: - res_lo = ((lo >> sh) | ((hi << (32 - sh)) & MASK32)) & MASK32 - res_hi = (s32(hi) >> sh) & MASK32 - return res_lo, res_hi - if sh == 32: - res_lo = hi - res_hi = MASK32 if (hi & SIGN32) else 0 - return res_lo, res_hi - - sh_hi = sh - 32 - res_lo = (s32(hi) >> sh_hi) & MASK32 - res_hi = MASK32 if (hi & SIGN32) else 0 - return res_lo, res_hi - - -EXPORT_HALVES = [ - "v_and_b32 v5, 0xffff, v0", - "v_lshrrev_b32 v6, 16, v0", - "v_and_b32 v7, 0xffff, v1", - "v_lshrrev_b32 v8, 16, v1", - "v_or_b32 v5, 0x40000000, v5", - "v_or_b32 v6, 0x40000000, v6", - "v_or_b32 v7, 0x40000000, v7", - "v_or_b32 v8, 0x40000000, v8", -] - - -def run_lines(lines: list[str]) -> int: - """Run assembly lines, export v[0:1] in 16-bit halves, return as one 64-bit value.""" - if _TMP_DIR is None: - setUpModule() - assert _SRC_PATH is not None - - body = list(lines) + EXPORT_HALVES - asm = "; test_alu_ashr_i64\n" + "".join(f"\t{ln}\n" for ln in body) + "\texp mrt0 v5, v6, v7, v8 done vm\n\ts_endpgm\n" - with open(_SRC_PATH, "w", encoding="utf-8") as f: - f.write(asm) - with warnings.catch_warnings(): - warnings.simplefilter("ignore", ResourceWarning) - spv = rdna2spirv.translate(_SRC_PATH) - words = si.run_fragment(spv)["%out_mrt0"] - assert all((x >> 16) == 0x4000 for x in words), [hex(x) for x in words] - return sum((x & 0xFFFF) << (16 * i) for i, x in enumerate(words)) - - -def run_ashr_op(shift: int, val: int, src_reg: str = "v[2:3]", dst_reg: str = "v[0:1]") -> int: - """Helper to load operands into registers, execute v_ashrrev_i64, and export result.""" - lo, hi = decompose_u64(val) - lines = [ - f"v_mov_b32 v4, {shift:#x}", - f"v_mov_b32 v2, {lo:#x}", - f"v_mov_b32 v3, {hi:#x}", - f"v_ashrrev_i64 {dst_reg}, v4, {src_reg}", - ] - if dst_reg != "v[0:1]": - parts = dst_reg.strip("v[]").split(":") - d0, d1 = int(parts[0]), int(parts[1]) - lines.extend([ - f"v_mov_b32 v0, v{d0}", - f"v_mov_b32 v1, v{d1}", - ]) - return run_lines(lines) - - -class TestRefOracle(unittest.TestCase): - """Unit tests validating reference oracle, 32-bit dword pair emulation, and basic shader execution.""" - - def test_u64_s64_conversions(self) -> None: - self.assertEqual(u64(0), 0) - self.assertEqual(s64(0), 0) - self.assertEqual(s64(1), 1) - self.assertEqual(s64(0x7FFFFFFFFFFFFFFF), (1 << 63) - 1) - self.assertEqual(s64(0x8000000000000000), -(1 << 63)) - self.assertEqual(s64(MASK64), -1) - - def test_decompose_compose_roundtrip(self) -> None: - values = [ - 0, - 1, - MASK64, - SIGN64, - SIGN64 - 1, - 0x123456789ABCDEF0, - 0xFEDCBA9876543210, - 0x00000000FFFFFFFF, - 0xFFFFFFFF00000000, - ] - for val in values: - lo, hi = decompose_u64(val) - self.assertEqual(compose_u64(lo, hi), val) - - def test_dword_emulation_matches_ref_oracle(self) -> None: - test_values = [ - 0, - 1, - -1 & MASK64, - SIGN64, - SIGN64 - 1, - 0x123456789ABCDEF0, - 0xFEDCBA9876543210, - 0x8000000000000001, - 0x7FFFFFFFFFFFFFFF, - 0xAAAAAAAA55555555, - 0x55555555AAAAAAAA, - ] - for val in test_values: - lo, hi = decompose_u64(val) - for shift in range(64): - ref = ref_ashr_i64(shift, val) - elo, ehi = emulate_ashr_i64_dwords(shift, lo, hi) - got = compose_u64(elo, ehi) - self.assertEqual(got, ref, f"Mismatch at val={hex(val)}, shift={shift}") - - def test_identity_shift_zero(self) -> None: - cases = [0, 1, MASK64, SIGN64, 0x0123456789ABCDEF, 0x8000000000000001] - for val in cases: - self.assertEqual(ref_ashr_i64(0, val), val) - self.assertEqual(ref_ashr_i64(64, val), val) - - def test_basic_positive_values(self) -> None: - val = 0x4000000000000000 - self.assertEqual(ref_ashr_i64(1, val), 0x2000000000000000) - self.assertEqual(ref_ashr_i64(2, val), 0x1000000000000000) - self.assertEqual(ref_ashr_i64(62, val), 1) - self.assertEqual(ref_ashr_i64(63, val), 0) - - def test_basic_negative_values(self) -> None: - val = SIGN64 - self.assertEqual(ref_ashr_i64(1, val), 0xC000000000000000) - self.assertEqual(ref_ashr_i64(2, val), 0xE000000000000000) - self.assertEqual(ref_ashr_i64(31, val), 0xFFFFFFFF00000000) - self.assertEqual(ref_ashr_i64(32, val), 0xFFFFFFFF80000000) - self.assertEqual(ref_ashr_i64(63, val), MASK64) - - def test_shader_execution_basic(self) -> None: - val = 0x8000000000000000 - got = run_ashr_op(1, val) - self.assertEqual(got, 0xC000000000000000) - got = run_ashr_op(32, val) - self.assertEqual(got, 0xFFFFFFFF80000000) - - def test_shader_immediate_shift_operand(self) -> None: - val = 0x8000000000000000 - lo, hi = decompose_u64(val) - lines = [ - f"v_mov_b32 v2, {lo:#x}", - f"v_mov_b32 v3, {hi:#x}", - "v_ashrrev_i64 v[0:1], 4, v[2:3]", - ] - got = run_lines(lines) - self.assertEqual(got, ref_ashr_i64(4, val)) - - def test_shader_scalar_pair_operand(self) -> None: - val = 0x8000000000000000 - lo, hi = decompose_u64(val) - lines = [ - f"s_mov_b32 s2, {lo:#x}", - f"s_mov_b32 s3, {hi:#x}", - "v_ashrrev_i64 v[0:1], 8, s[2:3]", - ] - got = run_lines(lines) - self.assertEqual(got, ref_ashr_i64(8, val)) - - def test_shader_vector_pair_operand(self) -> None: - val = 0xFEDCBA9876543210 - lo, hi = decompose_u64(val) - lines = [ - f"v_mov_b32 v2, {lo:#x}", - f"v_mov_b32 v3, {hi:#x}", - "v_mov_b32 v4, 16", - "v_ashrrev_i64 v[0:1], v4, v[2:3]", - ] - got = run_lines(lines) - self.assertEqual(got, ref_ashr_i64(16, val)) - - -class TestSimdMultiLaneVgprPairs(unittest.TestCase): - """Multi-lane SIMD wave simulation and VGPR register pair allocation tests.""" - - def test_wave64_divergent_shifts_uniform_data(self) -> None: - val = 0x8000000000000000 - lanes = 64 - for lane_id in range(lanes): - shift_count = lane_id - expected = ref_ashr_i64(shift_count, val) - lo, hi = decompose_u64(val) - elo, ehi = emulate_ashr_i64_dwords(shift_count, lo, hi) - got = compose_u64(elo, ehi) - self.assertEqual(got, expected, f"Lane {lane_id} shift {shift_count} failed") - - def test_wave64_uniform_shift_divergent_data(self) -> None: - rng = random.Random(0x42) - lanes = 64 - shift = 16 - for lane_id in range(lanes): - lane_val = rng.getrandbits(64) - if lane_id % 2 == 0: - lane_val |= SIGN64 - else: - lane_val &= ~SIGN64 - expected = ref_ashr_i64(shift, lane_val) - lo, hi = decompose_u64(lane_val) - elo, ehi = emulate_ashr_i64_dwords(shift, lo, hi) - got = compose_u64(elo, ehi) - self.assertEqual(got, expected, f"Lane {lane_id} val {hex(lane_val)} failed") - - def test_wave64_fully_divergent_lanes(self) -> None: - rng = random.Random(0x1337) - lanes = 64 - for lane_id in range(lanes): - lane_shift = rng.getrandbits(32) - lane_val = rng.getrandbits(64) - expected = ref_ashr_i64(lane_shift, lane_val) - lo, hi = decompose_u64(lane_val) - elo, ehi = emulate_ashr_i64_dwords(lane_shift, lo, hi) - got = compose_u64(elo, ehi) - self.assertEqual(got, expected, f"Lane {lane_id} divergent pair failed") - - def test_shader_non_overlapping_vgpr_pairs(self) -> None: - val = 0x8000000000000000 - lo, hi = decompose_u64(val) - - pairs = [ - ("v[4:5]", "v[6:7]"), - ("v[10:11]", "v[12:13]"), - ("v[20:21]", "v[22:23]"), - ("v[30:31]", "v[14:15]"), - ] - for src_reg, dst_reg in pairs: - s0 = int(src_reg.strip("v[]").split(":")[0]) - s1 = s0 + 1 - d0 = int(dst_reg.strip("v[]").split(":")[0]) - d1 = d0 + 1 - lines = [ - f"v_mov_b32 v{s0}, {lo:#x}", - f"v_mov_b32 v{s1}, {hi:#x}", - f"v_ashrrev_i64 {dst_reg}, 4, {src_reg}", - f"v_mov_b32 v0, v{d0}", - f"v_mov_b32 v1, v{d1}", - ] - got = run_lines(lines) - self.assertEqual(got, ref_ashr_i64(4, val), f"Failed for pair {src_reg} -> {dst_reg}") - - def test_shader_in_place_destination_aliasing(self) -> None: - val = 0x8000000000000000 - lo, hi = decompose_u64(val) - lines = [ - f"v_mov_b32 v0, {lo:#x}", - f"v_mov_b32 v1, {hi:#x}", - "v_ashrrev_i64 v[0:1], 8, v[0:1]", - ] - got = run_lines(lines) - self.assertEqual(got, ref_ashr_i64(8, val)) - - lines_v2 = [ - f"v_mov_b32 v2, {lo:#x}", - f"v_mov_b32 v3, {hi:#x}", - "v_ashrrev_i64 v[2:3], 12, v[2:3]", - "v_mov_b32 v0, v2", - "v_mov_b32 v1, v3", - ] - got_v2 = run_lines(lines_v2) - self.assertEqual(got_v2, ref_ashr_i64(12, val)) - - def test_shader_partially_overlapping_register_pairs(self) -> None: - val = 0x8000000000000000 - lo, hi = decompose_u64(val) - lines = [ - f"v_mov_b32 v2, {lo:#x}", - f"v_mov_b32 v3, {hi:#x}", - "v_ashrrev_i64 v[1:2], 4, v[2:3]", - "v_mov_b32 v0, v1", - "v_mov_b32 v1, v2", - ] - got = run_lines(lines) - self.assertEqual(got, ref_ashr_i64(4, val)) - - def test_shader_chained_vgpr_pair_shifts(self) -> None: - val = 0x8000000000000000 - lo, hi = decompose_u64(val) - lines = [ - f"v_mov_b32 v2, {lo:#x}", - f"v_mov_b32 v3, {hi:#x}", - "v_ashrrev_i64 v[4:5], 16, v[2:3]", - "v_ashrrev_i64 v[0:1], 16, v[4:5]", - ] - got = run_lines(lines) - self.assertEqual(got, ref_ashr_i64(32, val)) - - def test_shader_shift_count_from_different_vgprs(self) -> None: - val = 0xFEDCBA9876543210 - lo, hi = decompose_u64(val) - for count_vgpr in ("v4", "v7", "v15", "v25"): - lines = [ - f"v_mov_b32 {count_vgpr}, 24", - f"v_mov_b32 v2, {lo:#x}", - f"v_mov_b32 v3, {hi:#x}", - f"v_ashrrev_i64 v[0:1], {count_vgpr}, v[2:3]", - ] - got = run_lines(lines) - self.assertEqual(got, ref_ashr_i64(24, val), f"Failed with count in {count_vgpr}") - - -class TestSignPropagationExtremes(unittest.TestCase): - """Sign-propagation extremes and cross-dword transition tests.""" - - def test_negative_one_all_ones_invariance(self) -> None: - neg_one = MASK64 - for shift in range(64): - self.assertEqual(ref_ashr_i64(shift, neg_one), neg_one) - - def test_most_negative_int64_sign_expansion(self) -> None: - min_int64 = SIGN64 - self.assertEqual(ref_ashr_i64(0, min_int64), min_int64) - self.assertEqual(ref_ashr_i64(1, min_int64), 0xC000000000000000) - self.assertEqual(ref_ashr_i64(2, min_int64), 0xE000000000000000) - self.assertEqual(ref_ashr_i64(3, min_int64), 0xF000000000000000) - self.assertEqual(ref_ashr_i64(31, min_int64), 0xFFFFFFFF00000000) - self.assertEqual(ref_ashr_i64(32, min_int64), 0xFFFFFFFF80000000) - self.assertEqual(ref_ashr_i64(33, min_int64), 0xFFFFFFFFC0000000) - self.assertEqual(ref_ashr_i64(62, min_int64), 0xFFFFFFFFFFFFFFFE) - self.assertEqual(ref_ashr_i64(63, min_int64), MASK64) - - for shift in range(64): - expected = (MASK64 << (63 - shift)) & MASK64 - self.assertEqual(ref_ashr_i64(shift, min_int64), expected) - - def test_max_positive_int64_zero_expansion(self) -> None: - max_int64 = 0x7FFFFFFFFFFFFFFF - self.assertEqual(ref_ashr_i64(0, max_int64), max_int64) - self.assertEqual(ref_ashr_i64(1, max_int64), 0x3FFFFFFFFFFFFFFF) - self.assertEqual(ref_ashr_i64(32, max_int64), 0x000000007FFFFFFF) - self.assertEqual(ref_ashr_i64(62, max_int64), 1) - self.assertEqual(ref_ashr_i64(63, max_int64), 0) - - def test_zero_expansion(self) -> None: - for shift in range(64): - self.assertEqual(ref_ashr_i64(shift, 0), 0) - - def test_positive_one_drain(self) -> None: - self.assertEqual(ref_ashr_i64(0, 1), 1) - for shift in range(1, 64): - self.assertEqual(ref_ashr_i64(shift, 1), 0) - - def test_cross_dword_transition_31_32_33(self) -> None: - patterns = [ - 0x8000000000000000, - 0x7FFFFFFFFFFFFFFF, - 0x0123456789ABCDEF, - 0xFEDCBA9876543210, - 0x00000000FFFFFFFF, - 0xFFFFFFFF00000000, - ] - for val in patterns: - lo, hi = decompose_u64(val) - for shift in (31, 32, 33): - ref = ref_ashr_i64(shift, val) - elo, ehi = emulate_ashr_i64_dwords(shift, lo, hi) - self.assertEqual(compose_u64(elo, ehi), ref, f"Mismatch at val={hex(val)}, shift={shift}") - - def test_shader_sign_propagation_extremes(self) -> None: - val = SIGN64 - self.assertEqual(run_ashr_op(1, val), 0xC000000000000000) - self.assertEqual(run_ashr_op(31, val), 0xFFFFFFFF00000000) - self.assertEqual(run_ashr_op(32, val), 0xFFFFFFFF80000000) - self.assertEqual(run_ashr_op(63, val), MASK64) - - -class TestShiftCountModulo64(unittest.TestCase): - """Modulo-64 shift count masking tests.""" - - def test_modulo_64_masking_comprehensive(self) -> None: - test_values = [ - 0x8000000000000000, - 0x7FFFFFFFFFFFFFFF, - 0xFEDCBA9876543210, - 0x0123456789ABCDEF, - ] - base_shifts = [0, 1, 15, 31, 32, 47, 63] - multipliers = [1, 2, 3, 10, 100] - - for val in test_values: - for base in base_shifts: - ref = ref_ashr_i64(base, val) - for mult in multipliers: - overflowed_shift = base + 64 * mult - self.assertEqual(ref_ashr_i64(overflowed_shift, val), ref) - - def test_upper_bits_ignored(self) -> None: - val = 0x8000000000000000 - self.assertEqual(ref_ashr_i64(0xFFFFFFFF, val), ref_ashr_i64(63, val)) - self.assertEqual(ref_ashr_i64(0x80000000, val), ref_ashr_i64(0, val)) - self.assertEqual(ref_ashr_i64(0x80000020, val), ref_ashr_i64(32, val)) - self.assertEqual(ref_ashr_i64(0x12345600, val), ref_ashr_i64(0, val)) - self.assertEqual(ref_ashr_i64(0x1234563F, val), ref_ashr_i64(63, val)) - - def test_shader_shift_count_modulo_64(self) -> None: - val = 0x8000000000000000 - self.assertEqual(run_ashr_op(64, val), val) - self.assertEqual(run_ashr_op(65, val), ref_ashr_i64(1, val)) - self.assertEqual(run_ashr_op(0x80000020, val), ref_ashr_i64(32, val)) - self.assertEqual(run_ashr_op(0xFFFFFFFF, val), ref_ashr_i64(63, val)) - - -class TestNegativeControls(unittest.TestCase): - """Negative controls ensuring mutated semantics and missing masks fail assertions.""" - - def test_logical_shift_mutation_rejected(self) -> None: - val = 0x8000000000000000 - shift = 1 - arithmetic_correct = ref_ashr_i64(shift, val) - mutated_logical = (u64(val) >> (shift & 63)) & MASK64 - self.assertEqual(arithmetic_correct, 0xC000000000000000) - self.assertEqual(mutated_logical, 0x4000000000000000) - self.assertNotEqual(arithmetic_correct, mutated_logical) - - def test_unmasked_shift_mutation_rejected(self) -> None: - val = 0x8000000000000000 - shift = 64 - masked_correct = ref_ashr_i64(shift, val) - mutated_unmasked = (s64(val) >> shift) & MASK64 - self.assertEqual(masked_correct, val) - self.assertEqual(mutated_unmasked, MASK64) - self.assertNotEqual(masked_correct, mutated_unmasked) - - def test_left_shift_mutation_rejected(self) -> None: - val = 0x0000000000000001 - shift = 4 - arithmetic_correct = ref_ashr_i64(shift, val) - mutated_left = (s64(val) << (shift & 63)) & MASK64 - self.assertEqual(arithmetic_correct, 0) - self.assertEqual(mutated_left, 0x10) - self.assertNotEqual(arithmetic_correct, mutated_left) - - def test_independent_dword_shift_mutation_rejected(self) -> None: - val = 0x0000000100000000 - shift = 1 - correct = ref_ashr_i64(shift, val) - lo, hi = decompose_u64(val) - mutated_independent_lo = (lo >> shift) & MASK32 - mutated_independent_hi = (hi >> shift) & MASK32 - mutated = compose_u64(mutated_independent_lo, mutated_independent_hi) - self.assertEqual(correct, 0x0000000080000000) - self.assertEqual(mutated, 0x0000000000000000) - self.assertNotEqual(correct, mutated) - - def test_sign_bit_inversion_mutation_rejected(self) -> None: - val = 0x8000000000000000 - correct = ref_ashr_i64(1, val) - mutated = correct ^ SIGN64 - self.assertNotEqual(correct, mutated) - - def test_off_by_one_shift_count_mutation_rejected(self) -> None: - val = 0x8000000000000000 - correct = ref_ashr_i64(4, val) - mutated_plus = ref_ashr_i64(5, val) - mutated_minus = ref_ashr_i64(3, val) - self.assertNotEqual(correct, mutated_plus) - self.assertNotEqual(correct, mutated_minus) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_alu_bcnt_u32.py b/tests/semantic/test_alu_bcnt_u32.py deleted file mode 100644 index e8ee86076..000000000 --- a/tests/semantic/test_alu_bcnt_u32.py +++ /dev/null @@ -1,135 +0,0 @@ -"""Semantic translation tests for RDNA2 32-bit bit count v_bcnt_u32_b32. - -Translates a synthetic pixel-shader listing through tools/rdna2spirv.translate() --> SPIR-V -> tests/semantic/spirv_mini_interp.py and compares the result against -a plain-Python reference: (popcount(x) + acc) & 0xFFFFFFFF. - -Covers: - - Basic popcount: x=0, x=1, x=all-ones - - Accumulator: popcount(x) + acc - - 32-bit wraparound on overflow - - Reference comparison across varied bit patterns - - Negative control: result differs from inputs for non-trivial cases -""" -import os -import struct -import sys -import tempfile -import unittest -import warnings - -HERE = os.path.dirname(os.path.abspath(__file__)) -ROOT = os.path.dirname(os.path.dirname(HERE)) -TOOLS_DIR = os.environ.get("LEONIDA_TOOLS_DIR") or os.path.join(ROOT, "tools") - -sys.dont_write_bytecode = True -if TOOLS_DIR not in sys.path: - sys.path.insert(0, TOOLS_DIR) -if HERE not in sys.path: - sys.path.insert(0, HERE) - -import rdna2spirv # noqa: E402 -import spirv_mini_interp as si # noqa: E402 - -M32 = 0xFFFFFFFF -STUB_DXBC = b"DXBC" + bytes(24) + struct.pack(" int: - """Plain-Python reference for v_bcnt_u32_b32: popcount(x) + acc, masked to 32 bits.""" - return (bin(x & M32).count("1") + acc) & M32 - - -def run_op(x: int, acc: int) -> int: - """Translate and run a shader that computes v_bcnt_u32_b32 v1, v2, v3 with v2=x, v3=acc. - - Uses a unique temp directory per call to avoid file-sharing issues. - """ - asm = ( - "; test_bcnt_u32\n" - f"\tv_mov_b32_e32 v2, {x & M32:#x}\n" - f"\tv_mov_b32_e32 v3, {acc & M32:#x}\n" - "\tv_bcnt_u32_b32 v1, v2, v3\n" - "\ts_waitcnt vmcnt(0)\n" - "\texp mrt0 v1, v1, v1, v1 done vm\n" - "\ts_endpgm\n" - ) - tmp = tempfile.TemporaryDirectory() - disasm_dir = os.path.join(tmp.name, "disasm") - os.mkdir(disasm_dir) - src_path = os.path.join(disasm_dir, "ps_bcnt_u32.s") - with open(os.path.join(tmp.name, "ps_bcnt_u32.dxbc"), "wb") as f: - f.write(STUB_DXBC) - with open(src_path, "w", encoding="utf-8") as f: - f.write(asm) - with warnings.catch_warnings(): - warnings.simplefilter("ignore", ResourceWarning) - spv = rdna2spirv.translate(src_path) - w = si.run_fragment(spv)["%out_mrt0"] - tmp.cleanup() - return w[0] & M32 - - -class ALUVBitcntU32Tests(unittest.TestCase): - def test_bcnt_u32_basic(self): - # popcount(0) = 0 - self.assertEqual(run_op(0, 0), 0) - # popcount(1) = 1 - self.assertEqual(run_op(1, 0), 1) - # popcount(0xFFFFFFFF) = 32 - self.assertEqual(run_op(M32, 0), 32) - # popcount(0xAAAAAAAA) = 16 - self.assertEqual(run_op(0xAAAAAAAA, 0), 16) - # popcount(0x55555555) = 16 - self.assertEqual(run_op(0x55555555, 0), 16) - - def test_bcnt_u32_accumulator(self): - # popcount(0xFF) = 8, acc = 10 -> 18 - self.assertEqual(run_op(0xFF, 10), 18) - # popcount(0) = 0, acc = 0x12345678 - self.assertEqual(run_op(0, 0x12345678), 0x12345678) - - def test_bcnt_u32_wraparound(self): - # popcount(0xFFFFFFFF) = 32, acc = 0xFFFFFFFE -> 32 + 0xFFFFFFFE = 0x10000001E -> 0x1E - self.assertEqual(run_op(M32, M32 - 1), 30) - # popcount(1) = 1, acc = M32 -> 1 + M32 = 0x100000000 -> 0 - self.assertEqual(run_op(1, M32), 0) - - def test_bcnt_u32_reference(self): - cases = [ - (0, 0, 0), - (1, 0, 1), - (2, 0, 1), # 0b10 -> 1 bit - (3, 0, 2), # 0b11 -> 2 bits - (0xFF, 0, 8), - (0xFFFF, 0, 16), - (0xFFFFFFFF, 0, 32), - (0x00000000, 0xABCD, 0xABCD), - (0x12345678, 0, 13), # popcount(0x12345678) = 13 - ] - for x, acc, expected in cases: - with self.subTest(x=hex(x), acc=hex(acc)): - self.assertEqual(run_op(x, acc), expected) - self.assertEqual(run_op(x, acc), ref_bcnt32(x, acc)) - - def test_bcnt_u32_random_vs_reference(self): - import random - rng = random.Random(0xC0FFEE) - for _ in range(50): - x = rng.getrandbits(32) - acc = rng.getrandbits(32) - with self.subTest(x=hex(x), acc=hex(acc)): - self.assertEqual(run_op(x, acc), ref_bcnt32(x, acc)) - - def test_bcnt_u32_negative_control(self): - # For non-trivial inputs, result differs from each input. - x, acc = 0x12345678, 0x9ABCDEF0 - res = run_op(x, acc) - expected = ref_bcnt32(x, acc) - self.assertEqual(res, expected) - self.assertNotEqual(res, x) - self.assertNotEqual(res, acc) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_alu_bfe.py b/tests/semantic/test_alu_bfe.py deleted file mode 100644 index 6acd3dd20..000000000 --- a/tests/semantic/test_alu_bfe.py +++ /dev/null @@ -1,365 +0,0 @@ -"""Semantic interpreter tests for RDNA2 bitfield extract instructions (v_bfe_u32, v_bfe_i32). - -Verifies translation via tools/rdna2spirv.py and execution via tests/semantic/spirv_mini_interp.py, -as well as direct SPIR-V OpBitFieldUExtract and OpBitFieldSExtract interpreter edge cases: - * Signed vs unsigned bitfield extraction - * Width = 0 edge cases (must return 0 for both signed and unsigned) - * Single-bit extractions across all 32 lane bit positions - * Width and offset masking modulo 32 per RDNA ISA (offset & 31, width & 31) - * Exact boundary conditions (offset + width == 32) - * Fields that run past bit 31 (offset + width > 32): the field stops at bit 31, as LLVM's constantFoldBFE - computes (Src0 >> Offset, arithmetic for v_bfe_i32), and the translation keeps the SPIR-V count in range - * s_bfe_u32 / s_bfe_i32, whose width (bits 22:16 of src1) goes up to 127 - * Rejection of out-of-bounds bitfields (offset + width > 32, undefined in SPIR-V) - * Comparison against an independent plain-Python reference oracle -""" -import gc -import os -import struct -import sys -import tempfile -import unittest -import warnings - -HERE = os.path.dirname(os.path.abspath(__file__)) -ROOT = os.path.dirname(os.path.dirname(HERE)) -TOOLS_DIR = os.environ.get("LEONIDA_TOOLS_DIR") or os.path.join(ROOT, "tools") - -sys.dont_write_bytecode = True -sys.path.insert(0, TOOLS_DIR) -sys.path.insert(0, HERE) - -import rdna2spirv # noqa: E402 -import spirv_mini_interp as si # noqa: E402 - -MASK32 = 0xFFFFFFFF -STUB_DXBC = b"DXBC" + bytes(24) + struct.pack(" int: - """RDNA2 v_bfe_u32 reference oracle: unsigned bitfield extract.""" - base &= MASK32 - offset &= 31 - width &= 31 - if width == 0: - return 0 - return ((base >> offset) & ((1 << width) - 1)) & MASK32 - - -def ref_bfe_i32(base: int, offset: int, width: int) -> int: - """RDNA2 v_bfe_i32 reference oracle: signed bitfield extract.""" - base &= MASK32 - offset &= 31 - width &= 31 - if width == 0: - return 0 - signed = base - (1 << 32) if base >> 31 else base - # Arithmetic shift: a field that runs past bit 31 is filled with the sign bit. - field = (signed >> offset) & ((1 << width) - 1) - if field & (1 << (width - 1)): - field -= 1 << width - return field & MASK32 - - -_TMP_DIR = None -_SRC_PATH = None - - -def setUpModule(): - global _TMP_DIR, _SRC_PATH - _TMP_DIR = tempfile.TemporaryDirectory() - disasm_dir = os.path.join(_TMP_DIR.name, "disasm") - os.mkdir(disasm_dir) - _SRC_PATH = os.path.join(disasm_dir, "ps_bfe.s") - dxbc_path = os.path.join(_TMP_DIR.name, "ps_bfe.dxbc") - with open(dxbc_path, "wb") as f: - f.write(STUB_DXBC) - - -def tearDownModule(): - global _TMP_DIR - if _TMP_DIR is not None: - _TMP_DIR.cleanup() - _TMP_DIR = None - - -def run_rdna_bfe(op: str, base: int, offset: int, width: int, use_vgpr: bool = True) -> int: - """Translate and execute a synthetic pixel shader exercising v_bfe_u32 or v_bfe_i32.""" - global _TMP_DIR, _SRC_PATH - if _TMP_DIR is None: - setUpModule() - - if use_vgpr: - asm_content = ( - "; test_bfe\n" - f"\tv_mov_b32 v1, {base & MASK32:#x}\n" - f"\tv_mov_b32 v2, {offset:#x}\n" - f"\tv_mov_b32 v3, {width:#x}\n" - f"\t{op} v0, v1, v2, v3\n" - "\texp mrt0 v0, v0, v0, v0 done vm\n" - "\ts_endpgm\n" - ) - else: - asm_content = ( - "; test_bfe\n" - f"\tv_mov_b32 v1, {base & MASK32:#x}\n" - f"\t{op} v0, v1, {offset}, {width}\n" - "\texp mrt0 v0, v0, v0, v0 done vm\n" - "\ts_endpgm\n" - ) - - with open(_SRC_PATH, "w", encoding="utf-8") as f: - f.write(asm_content) - - with warnings.catch_warnings(): - warnings.simplefilter("ignore", ResourceWarning) - spv = rdna2spirv.translate(_SRC_PATH) - - out = si.run_fragment(spv) - return out["%out_mrt0"][0] - - -def run_spirv_bfe(opcode: str, base: int, offset: int, width: int) -> int: - """Execute direct OpBitFieldUExtract or OpBitFieldSExtract via spirv_mini_interp.""" - body = ( - SPIRV_HEADER - + f"%c_base = OpConstant %uint {base & MASK32}\n" - + f"%c_off = OpConstant %uint {offset}\n" - + f"%c_wid = OpConstant %uint {width}\n" - + "%main = OpFunction %void None %fn\n" - + "%entry = OpLabel\n" - + f"%res = {opcode} %uint %c_base %c_off %c_wid\n" - + "OpStore %out %res\n" - + "OpReturn\n" - + "OpFunctionEnd\n" - ) - return si.run_fragment(body)["%out"][0] - - -class AluBfeSemanticTests(unittest.TestCase): - def test_reference_oracle_basics(self): - self.assertEqual(ref_bfe_u32(0x12345678, 4, 8), 0x67) - self.assertEqual(ref_bfe_i32(0xFFFFFFF0, 2, 4), 0xFFFFFFFC) - self.assertEqual(ref_bfe_u32(0xFFFFFFFF, 0, 4), 0x0000000F) - self.assertEqual(ref_bfe_i32(0xFFFFFFFF, 0, 4), 0xFFFFFFFF) - self.assertEqual(ref_bfe_u32(0xFFFFFFFF, 0, 0), 0) - self.assertEqual(ref_bfe_i32(0xFFFFFFFF, 0, 0), 0) - self.assertEqual(ref_bfe_u32(0x80000000, 31, 1), 1) - self.assertEqual(ref_bfe_i32(0x80000000, 31, 1), 0xFFFFFFFF) - self.assertEqual(ref_bfe_u32(0x7FFFFFFF, 31, 1), 0) - self.assertEqual(ref_bfe_i32(0x7FFFFFFF, 31, 1), 0) - - def test_v_bfe_u32_basic_extractions(self): - cases = [ - (0x12345678, 4, 8, 0x67), - (0xDEADBEEF, 8, 12, 0xDBE), - (0xABCD1234, 16, 16, 0xABCD), - (0xFEDCBA98, 0, 4, 0x8), - (0xFEDCBA98, 0, 8, 0x98), - (0xFEDCBA98, 0, 16, 0xBA98), - (0x87654321, 28, 4, 0x8), - ] - for base, off, wid, expected in cases: - with self.subTest(base=hex(base), off=off, wid=wid): - self.assertEqual(run_rdna_bfe("v_bfe_u32", base, off, wid, use_vgpr=True), expected) - self.assertEqual(run_rdna_bfe("v_bfe_u32", base, off, wid, use_vgpr=False), expected) - - def test_v_bfe_u32_zero_extension_never_sign_extends(self): - cases = [ - (0xFFFFFFFF, 0, 4, 0x0000000F), - (0x80000000, 28, 4, 0x00000008), - (0x80000000, 31, 1, 0x00000001), - (0x00008000, 12, 4, 0x00000008), - (0xFFFFFF00, 8, 8, 0x000000FF), - (0x00800000, 16, 8, 0x00000080), - ] - for base, off, wid, expected in cases: - with self.subTest(base=hex(base), off=off, wid=wid): - self.assertEqual(run_rdna_bfe("v_bfe_u32", base, off, wid), expected) - - def test_v_bfe_u32_width_zero_gives_zero(self): - for off in (0, 1, 7, 15, 16, 31): - with self.subTest(off=off): - self.assertEqual(run_rdna_bfe("v_bfe_u32", 0xFFFFFFFF, off, 0), 0) - self.assertEqual(run_rdna_bfe("v_bfe_u32", 0x12345678, off, 0), 0) - - def test_v_bfe_i32_positive_fields_zero_extended(self): - cases = [ - (0x76543210, 28, 4, 0x00000007), - (0x0000007F, 0, 8, 0x0000007F), - (0x00007FFF, 0, 16, 0x00007FFF), - (0x55555555, 2, 2, 0x00000001), - (0x12345678, 4, 4, 0x00000007), - ] - for base, off, wid, expected in cases: - with self.subTest(base=hex(base), off=off, wid=wid): - self.assertEqual(run_rdna_bfe("v_bfe_i32", base, off, wid, use_vgpr=True), expected) - self.assertEqual(run_rdna_bfe("v_bfe_i32", base, off, wid, use_vgpr=False), expected) - - def test_v_bfe_i32_negative_fields_sign_extended(self): - cases = [ - (0xFFFFFFF0, 2, 4, 0xFFFFFFFC), # 0b1100 -> -4 (matches ps_ops fixture) - (0x00000080, 0, 8, 0xFFFFFF80), # 0x80 -> -128 - (0x000000FF, 0, 8, 0xFFFFFFFF), # 0xFF -> -1 - (0x00008000, 0, 16, 0xFFFF8000), # 0x8000 -> -32768 - (0x0000FFFF, 0, 16, 0xFFFFFFFF), # 0xFFFF -> -1 - (0x80000000, 31, 1, 0xFFFFFFFF), # 1-bit -> -1 - (0x00000001, 0, 1, 0xFFFFFFFF), # 1-bit -> -1 - (0xAAAAAAAA, 2, 2, 0xFFFFFFFE), # 0b10 -> -2 - ] - for base, off, wid, expected in cases: - with self.subTest(base=hex(base), off=off, wid=wid): - self.assertEqual(run_rdna_bfe("v_bfe_i32", base, off, wid, use_vgpr=True), expected) - self.assertEqual(run_rdna_bfe("v_bfe_i32", base, off, wid, use_vgpr=False), expected) - - def test_v_bfe_i32_width_zero_gives_zero(self): - for off in (0, 1, 7, 15, 16, 31): - with self.subTest(off=off): - self.assertEqual(run_rdna_bfe("v_bfe_i32", 0xFFFFFFFF, off, 0), 0) - self.assertEqual(run_rdna_bfe("v_bfe_i32", 0x80000000, off, 0), 0) - - def test_operand_masking_mod_32(self): - self.assertEqual(run_rdna_bfe("v_bfe_u32", 0x12345678, 36, 8), 0x67) # 36 & 31 = 4 - self.assertEqual(run_rdna_bfe("v_bfe_u32", 0x12345678, 4, 40), 0x67) # 40 & 31 = 8 - self.assertEqual(run_rdna_bfe("v_bfe_u32", 0x12345678, 4, 32), 0) # 32 & 31 = 0 - self.assertEqual(run_rdna_bfe("v_bfe_i32", 0xFFFFFFF0, 34, 4), 0xFFFFFFFC) # 34 & 31 = 2 - self.assertEqual(run_rdna_bfe("v_bfe_i32", 0xFFFFFFF0, 2, 36), 0xFFFFFFFC) # 36 & 31 = 4 - self.assertEqual(run_rdna_bfe("v_bfe_i32", 0xFFFFFFF0, 2, 32), 0) # 32 & 31 = 0 - - def test_boundary_offset_plus_width_32(self): - # When offset + width == 32, exactly 32 bits are spanned; must be valid in SPIR-V. - self.assertEqual(run_rdna_bfe("v_bfe_u32", 0xFFFFFFFF, 0, 31), 0x7FFFFFFF) - self.assertEqual(run_rdna_bfe("v_bfe_u32", 0xFFFFFFFF, 1, 31), 0x7FFFFFFF) - self.assertEqual(run_rdna_bfe("v_bfe_u32", 0x12345678, 16, 16), 0x1234) - self.assertEqual(run_rdna_bfe("v_bfe_u32", 0x80000000, 31, 1), 1) - - self.assertEqual(run_rdna_bfe("v_bfe_i32", 0xFFFFFFFF, 0, 31), 0xFFFFFFFF) - self.assertEqual(run_rdna_bfe("v_bfe_i32", 0x7FFFFFFF, 1, 31), 0x3FFFFFFF) - self.assertEqual(run_rdna_bfe("v_bfe_i32", 0x80000000, 1, 31), 0xC0000000) - self.assertEqual(run_rdna_bfe("v_bfe_i32", 0x80000000, 31, 1), 0xFFFFFFFF) - - def test_out_of_bounds_rejected_by_interpreter(self): - # SPIR-V specification declares offset + count > 32 undefined. - # spirv_mini_interp strictly rejects undefined constructs with UnsupportedConstruct. - invalid_combinations = [ - (16, 17), # 16 + 17 = 33 - (31, 2), # 31 + 2 = 33 - (20, 20), # 20 + 20 = 40 - (1, 32), # 1 + 32 = 33 (in direct SPIR-V) - ] - for off, wid in invalid_combinations: - with self.subTest(off=off, wid=wid): - with self.assertRaises(si.UnsupportedConstruct): - run_spirv_bfe("OpBitFieldUExtract", 0xFFFFFFFF, off, wid) - with self.assertRaises(si.UnsupportedConstruct): - run_spirv_bfe("OpBitFieldSExtract", 0xFFFFFFFF, off, wid) - - def test_all_single_bit_positions(self): - # Test every single bit position (offset = 0..31, width = 1) - for pos in range(32): - base = 1 << pos - with self.subTest(pos=pos): - u_res = run_rdna_bfe("v_bfe_u32", base, pos, 1) - i_res = run_rdna_bfe("v_bfe_i32", base, pos, 1) - self.assertEqual(u_res, 1) - self.assertEqual(i_res, 0xFFFFFFFF) - - u_zero = run_rdna_bfe("v_bfe_u32", 0, pos, 1) - i_zero = run_rdna_bfe("v_bfe_i32", 0, pos, 1) - self.assertEqual(u_zero, 0) - self.assertEqual(i_zero, 0) - - def test_sweep_against_reference_oracle(self): - test_bases = [ - 0x00000000, - 0xFFFFFFFF, - 0x12345678, - 0xAAAAAAAA, - 0x80000000, - ] - test_offsets = [0, 1, 4, 16, 20, 31] - test_widths = [0, 1, 4, 8, 16, 17, 31] - - for base in test_bases: - for off in test_offsets: - for wid in test_widths: - exp_u = ref_bfe_u32(base, off, wid) - exp_i = ref_bfe_i32(base, off, wid) - got_u = run_rdna_bfe("v_bfe_u32", base, off, wid) - got_i = run_rdna_bfe("v_bfe_i32", base, off, wid) - self.assertEqual(got_u, exp_u, f"v_bfe_u32 mismatch: base={base:#x}, off={off}, wid={wid}") - self.assertEqual(got_i, exp_i, f"v_bfe_i32 mismatch: base={base:#x}, off={off}, wid={wid}") - - def test_field_past_bit_31_stops_there(self): - # offset + width > 32: the bits past 31 are zero (u32) or the sign bit (i32), not undefined. - for base, off, wid, want_u, want_i in ( - (0xF0000000, 28, 8, 0xF, 0xFFFFFFFF), - (0x80000000, 31, 2, 1, 0xFFFFFFFF), - (0x7FFFFFFF, 31, 2, 0, 0), - (0x12345678, 16, 17, 0x1234, 0x1234), - (0xABCD0000, 20, 20, 0xABC, 0xFFFFFABC), - ): - with self.subTest(base=hex(base), off=off, wid=wid): - self.assertEqual(ref_bfe_u32(base, off, wid), want_u) - self.assertEqual(ref_bfe_i32(base, off, wid), want_i) - self.assertEqual(run_rdna_bfe("v_bfe_u32", base, off, wid), want_u) - self.assertEqual(run_rdna_bfe("v_bfe_i32", base, off, wid), want_i) - self.assertEqual(run_rdna_bfe("v_bfe_u32", base, off, wid, use_vgpr=False), want_u) - self.assertEqual(run_rdna_bfe("v_bfe_i32", base, off, wid, use_vgpr=False), want_i) - - -def run_rdna_s_bfe(op: str, base: int, offset: int, width: int) -> int: - """Translate and execute s_bfe_u32 / s_bfe_i32 with src1 = offset | width << 16, return the result.""" - if _TMP_DIR is None: - setUpModule() - asm_content = ( - "; test_s_bfe\n" - f"\ts_mov_b32 s1, {base & MASK32:#x}\n" - f"\ts_mov_b32 s2, {(offset & 31) | (width & 0x7F) << 16:#x}\n" - f"\t{op} s0, s1, s2\n" - "\tv_mov_b32 v0, s0\n" - "\texp mrt0 v0, v0, v0, v0 done vm\n" - "\ts_endpgm\n" - ) - with open(_SRC_PATH, "w", encoding="utf-8") as f: - f.write(asm_content) - with warnings.catch_warnings(): - warnings.simplefilter("ignore", ResourceWarning) - spv = rdna2spirv.translate(_SRC_PATH) - return si.run_fragment(spv)["%out_mrt0"][0] - - -def ref_s_bfe(signed: bool, base: int, offset: int, width: int) -> int: - """s_bfe reference: the v_bfe field, with a 7-bit width; 32 or more takes every bit from offset up.""" - width = min(width & 0x7F, 32) - if width == 32: - if offset == 0: - return base & MASK32 - width = 32 - offset # same field: it is cut at bit 31 anyway - return (ref_bfe_i32 if signed else ref_bfe_u32)(base, offset, width) - - -class ScalarBfeTests(unittest.TestCase): - def test_s_bfe_in_range_and_past_bit_31(self): - for base in (0x12345678, 0x80000000, 0xFEDCBA98): - for off in (0, 4, 16, 28, 31): - for wid in (0, 1, 8, 16, 17, 31, 32, 64, 127): - for op, signed in (("s_bfe_u32", False), ("s_bfe_i32", True)): - with self.subTest(op=op, base=hex(base), off=off, wid=wid): - self.assertEqual(run_rdna_s_bfe(op, base, off, wid), ref_s_bfe(signed, base, off, wid)) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_alu_bfi.py b/tests/semantic/test_alu_bfi.py deleted file mode 100644 index a71a4d897..000000000 --- a/tests/semantic/test_alu_bfi.py +++ /dev/null @@ -1,367 +0,0 @@ -"""Semantic interpreter tests for bitfield insert (v_bfi_b32) with bitmask composition. - -AMD RDNA2 VALU Instruction Set Architecture (ISA): - v_bfi_b32 dst, src0, src1, src2 - Operation: dst = (src0 & src1) | (~src0 & src2) (all 32-bit unsigned integers) - - src0: bitmask indicating which bits to take from src1 - - src1: replacement field (bits where mask is 1) - - src2: base value (bits where mask is 0 are preserved from base) - -Bitmask composition: - In graphics shaders and compute kernels, bitfield insertion (BFI) packs sub-register fields - (e.g., color components, packed vertex attributes, compressed texture indices, bit flags) - into a destination 32-bit dword. For any field of width W at offset O: - mask = ((1 << W) - 1) << O - field = (value << O) & mask - result = v_bfi_b32(mask, field, base) - -In SPIR-V (as emitted by tools/rdna2spirv.py): - v_bfi_b32 translates to: - %p = OpBitwiseAnd %uint %src0 %src1 - %n = OpNot %uint %src0 - %q = OpBitwiseAnd %uint %n %src2 - %r = OpBitwiseOr %uint %p %q - -Standard library only: no GPU, no LLVM, no external tools, zero game data. -""" -import gc -import os -import struct -import sys -import tempfile -import unittest -import warnings - -HERE = os.path.dirname(os.path.abspath(__file__)) -ROOT = os.path.dirname(os.path.dirname(HERE)) -TOOLS_DIR = os.environ.get("LEONIDA_TOOLS_DIR") or os.path.join(ROOT, "tools") -if TOOLS_DIR not in sys.path: - sys.path.insert(0, TOOLS_DIR) -if HERE not in sys.path: - sys.path.insert(0, HERE) - -import rdna2spirv -import spirv_mini_interp as si - -MASK32 = 0xFFFFFFFF -STUB_DXBC = b"DXBC" + bytes(24) + struct.pack("= 32: - return MASK32 - return (((1 << width) - 1) << offset) & MASK32 - - -def compose_field(base, value, offset, width): - """Canonical bitfield insertion using v_bfi_b32 semantics.""" - mk = make_mask(offset, width) - fld = (value << offset) & mk - return ref_v_bfi_b32(mk, fld, base) - - -def run_spv_with_not(spv_text): - """Run SPIR-V assembly in spirv_mini_interp, mapping OpNot to OpISub (%c_all - %x).""" - lines = spv_text.splitlines() - fn_idx = next(i for i, ln in enumerate(lines) if "OpFunction" in ln) - lines.insert(fn_idx, "%_c_all_ones = OpConstant %uint 4294967295") - for i in range(fn_idx + 1, len(lines)): - if "OpNot %uint" in lines[i]: - parts = lines[i].split() - res_id = parts[0] - src_id = parts[4] - lines[i] = f"{res_id} = OpISub %uint %_c_all_ones {src_id}" - return si.run_fragment("\n".join(lines)) - - -def translate_snippet(asm_body, name="ps_bfi_test"): - """Translate straight-line assembly snippet via rdna2spirv.translate without external tools.""" - with tempfile.TemporaryDirectory() as tmp: - disasm_dir = os.path.join(tmp, "disasm") - os.mkdir(disasm_dir) - with open(os.path.join(disasm_dir, f"{name}.s"), "w", encoding="utf-8") as f: - f.write(f"; {name}\n{asm_body}\n") - with open(os.path.join(tmp, f"{name}.dxbc"), "wb") as f: - f.write(STUB_DXBC) - with warnings.catch_warnings(): - warnings.simplefilter("ignore", ResourceWarning) - res = rdna2spirv.translate(os.path.join(disasm_dir, f"{name}.s")) - gc.collect() - return res - - -class BfiPureSemanticsTests(unittest.TestCase): - """Test bitwise mathematical properties and boundaries of v_bfi_b32.""" - - def test_bitwise_definition_random_vectors(self): - vectors = [ - (0x00FF0000, 0x12345678, 0xA0B0C0D0, 0xA034C0D0), - (0x000000FF, 0xAABBCCDD, 0x11223344, 0x112233DD), - (0xFF000000, 0xAABBCCDD, 0x11223344, 0xAA223344), - (0x0000FF00, 0xAABBCCDD, 0x11223344, 0x1122CC44), - (0xF0F0F0F0, 0xAAAAAAAA, 0x55555555, 0xA5A5A5A5), - (0x0F0F0F0F, 0xAAAAAAAA, 0x55555555, 0x5A5A5A5A), - (0x12345678, 0xFFFFFFFF, 0x00000000, 0x12345678), - (0x12345678, 0x00000000, 0xFFFFFFFF, 0xEDCBA987), - ] - for mask, fld, base, expected in vectors: - with self.subTest(mask=hex(mask), fld=hex(fld), base=hex(base)): - self.assertEqual(ref_v_bfi_b32(mask, fld, base), expected) - - def test_mask_zero_preserves_base_completely(self): - for base in [0x00000000, 0xFFFFFFFF, 0xDEADBEEF, 0x13579BDF, 0x80000001]: - with self.subTest(base=hex(base)): - self.assertEqual(ref_v_bfi_b32(0, 0xCAFEBABE, base), base) - - def test_mask_all_ones_replaces_base_completely(self): - for fld in [0x00000000, 0xFFFFFFFF, 0xDEADBEEF, 0x13579BDF, 0x80000001]: - with self.subTest(fld=hex(fld)): - self.assertEqual(ref_v_bfi_b32(MASK32, fld, 0xCAFEBABE), fld) - - def test_identity_when_field_equals_base(self): - for val in [0x00000000, 0xFFFFFFFF, 0x12345678, 0x87654321, 0x55555555]: - for mask in [0x00000000, 0xFFFFFFFF, 0xF0F0F0F0, 0x00FF00FF, 0xAAAAAAAA]: - self.assertEqual(ref_v_bfi_b32(mask, val, val), val) - - def test_duality_with_inverted_mask(self): - mask = 0x3CA55AC3 - s1 = 0xDEADBEEF - s2 = 0x01234567 - inv_mask = (~mask) & MASK32 - self.assertEqual(ref_v_bfi_b32(mask, s1, s2), ref_v_bfi_b32(inv_mask, s2, s1)) - - def test_single_bit_insertion_all_positions(self): - base = 0x00000000 - for bit in range(32): - mask = 1 << bit - set_res = ref_v_bfi_b32(mask, MASK32, base) - self.assertEqual(set_res, 1 << bit) - clear_res = ref_v_bfi_b32(mask, 0, MASK32) - self.assertEqual(clear_res, MASK32 ^ (1 << bit)) - - def test_sign_bit_and_lsb_manipulation(self): - msb_mask = 0x80000000 - lsb_mask = 0x00000001 - self.assertEqual(ref_v_bfi_b32(msb_mask, msb_mask, 0x7FFFFFFF), MASK32) - self.assertEqual(ref_v_bfi_b32(msb_mask, 0, MASK32), 0x7FFFFFFF) - self.assertEqual(ref_v_bfi_b32(lsb_mask, 0, 0xFFFFFFFF), 0xFFFFFFFE) - self.assertEqual(ref_v_bfi_b32(lsb_mask, 1, 0xFFFFFFFE), 0xFFFFFFFF) - - def test_input_truncation_to_32bit(self): - large_mask = 0x1000000FF # 33-bit - large_fld = 0x212345678 # 34-bit - large_base = 0x3A0B0C0D0 # 34-bit - expected = 0xA0B0C078 - self.assertEqual(ref_v_bfi_b32(large_mask, large_fld, large_base), expected) - - -class BitmaskCompositionTests(unittest.TestCase): - """Test bitfield insert composition, packing workflows, and multi-field chaining.""" - - def test_byte_packing_sequence(self): - b0, b1, b2, b3 = 0x78, 0x56, 0x34, 0x12 - w0 = ref_v_bfi_b32(0x000000FF, b0, 0) - w1 = ref_v_bfi_b32(0x0000FF00, b1 << 8, w0) - w2 = ref_v_bfi_b32(0x00FF0000, b2 << 16, w1) - w3 = ref_v_bfi_b32(0xFF000000, b3 << 24, w2) - self.assertEqual(w3, 0x12345678) - - def test_in_place_byte_replacement(self): - base = 0xAABBCCDD - self.assertEqual(ref_v_bfi_b32(0x000000FF, 0x11, base), 0xAABBCC11) - self.assertEqual(ref_v_bfi_b32(0x0000FF00, 0x22 << 8, base), 0xAABB22DD) - self.assertEqual(ref_v_bfi_b32(0x00FF0000, 0x33 << 16, base), 0xAA33CCDD) - self.assertEqual(ref_v_bfi_b32(0xFF000000, 0x44 << 24, base), 0x44BBCCDD) - - def test_rgb565_color_packing(self): - r, g, b = 29, 58, 14 - expected_rgb565 = (r & 0x1F) | ((g & 0x3F) << 5) | ((b & 0x1F) << 11) - c0 = compose_field(0, r, 0, 5) - c1 = compose_field(c0, g, 5, 6) - c2 = compose_field(c1, b, 11, 5) - self.assertEqual(c2, expected_rgb565) - - def test_packed_normal_10_10_10_2(self): - nx, ny, nz, nw = 0x2AA, 0x155, 0x3FF, 0x2 - expected = (nx & 0x3FF) | ((ny & 0x3FF) << 10) | ((nz & 0x3FF) << 20) | ((nw & 0x3) << 30) - p0 = compose_field(0, nx, 0, 10) - p1 = compose_field(p0, ny, 10, 10) - p2 = compose_field(p1, nz, 20, 10) - p3 = compose_field(p2, nw, 30, 2) - self.assertEqual(p3, expected) - - def test_disjoint_masks_commutativity(self): - mask_a = 0x000000FF - mask_b = 0x00FF0000 - val_a = 0x000000AA - val_b = 0x00BB0000 - base = 0x11223344 - order1 = ref_v_bfi_b32(mask_a, val_a, ref_v_bfi_b32(mask_b, val_b, base)) - order2 = ref_v_bfi_b32(mask_b, val_b, ref_v_bfi_b32(mask_a, val_a, base)) - self.assertEqual(order1, order2) - self.assertEqual(order1, 0x11BB33AA) - - def test_idempotent_reinsertion(self): - mask = 0x0FFF0000 - fld = 0x0ABC0000 - base = 0x76543210 - first = ref_v_bfi_b32(mask, fld, base) - second = ref_v_bfi_b32(mask, fld, first) - self.assertEqual(first, second) - - def test_all_widths_and_offsets(self): - base = 0x5A5A5A5A - pattern = 0xFFFFFFFF - for width in range(1, 33): - for offset in range(0, 33 - width): - res = compose_field(base, pattern, offset, width) - mask = make_mask(offset, width) - self.assertEqual(res & mask, mask) - self.assertEqual(res & ~mask & MASK32, base & ~mask & MASK32) - - -class SpirvEquivalenceTests(unittest.TestCase): - """Test equivalence between v_bfi_b32 and SPIR-V OpBitFieldInsert / mini-interpreter.""" - - def test_equivalence_with_spirv_op_bitfield_insert(self): - test_cases = [ - (0, 4, 0x5, 0xFFFFFFF0), - (4, 8, 0xAB, 0x12345678), - (16, 16, 0xBEEF, 0x12345678), - (8, 12, 0x789, 0xA0B0C0D0), - (0, 32, 0xDEADBEEF, 0xCAFEBABE), - (10, 0, 0x123, 0x87654321), - ] - for offset, count, insert, base in test_cases: - with self.subTest(offset=offset, count=count): - mk = make_mask(offset, count) - field = (insert << offset) & mk - bfi_res = ref_v_bfi_b32(mk, field, base) - - ins_masked = ((1 << count) - 1) if count < 32 else MASK32 - spirv_mk = ((1 << count) - 1) << offset if count < 32 else MASK32 - spirv_res = ((base & ~spirv_mk) | ((insert << offset) & spirv_mk)) & MASK32 - self.assertEqual(bfi_res, spirv_res) - - def test_mini_interp_handwritten_bitfield_insert(self): - spv = """\ -OpCapability Shader -%glsl = OpExtInstImport "GLSL.std.450" -OpMemoryModel Logical GLSL450 -OpEntryPoint Fragment %main "main" %out -%void = OpTypeVoid -%fn = OpTypeFunction %void -%uint = OpTypeInt 32 0 -%_ptr_Output_uint = OpTypePointer Output %uint -%out = OpVariable %_ptr_Output_uint Output -%c_base = OpConstant %uint 4294967280 -%c_ins = OpConstant %uint 1 -%c_off = OpConstant %uint 0 -%c_cnt = OpConstant %uint 4 -%main = OpFunction %void None %fn -%entry = OpLabel -%res = OpBitFieldInsert %uint %c_base %c_ins %c_off %c_cnt -OpStore %out %res -OpReturn -OpFunctionEnd -""" - out = si.run_fragment(spv)["%out"][0] - self.assertEqual(out, 0xFFFFFFF1) - mk = make_mask(0, 4) - self.assertEqual(ref_v_bfi_b32(mk, 1, 0xFFFFFFF0), 0xFFFFFFF1) - - -class TranslatorIntegrationTests(unittest.TestCase): - """Test end-to-end translation and execution of RDNA2 v_bfi_b32 shaders.""" - - def test_translate_v_bfi_b32_emits_bitwise_quad(self): - asm = """\ -\tv_mov_b32 v1, 0x00ff0000 -\tv_mov_b32 v2, 0x12345678 -\tv_mov_b32 v3, 0xaaaaaaaa -\tv_bfi_b32 v0, v1, v2, v3 -\texp mrt0 v0, v0, v0, v0 done vm -\ts_endpgm""" - spv = translate_snippet(asm, "ps_bfi_emit") - self.assertIn("OpBitwiseAnd %uint", spv) - self.assertIn("OpNot %uint", spv) - self.assertIn("OpBitwiseOr %uint", spv) - - def test_execute_translated_v_bfi_b32_shader(self): - asm = """\ -\tv_mov_b32 v1, 0x000000ff -\tv_mov_b32 v2, 0x12345678 -\tv_mov_b32 v3, 0xa0b0c0d0 -\tv_bfi_b32 v0, v1, v2, v3 -\texp mrt0 v0, v0, v0, v0 done vm -\ts_endpgm""" - spv = translate_snippet(asm, "ps_bfi_exec") - out = run_spv_with_not(spv) - expected = 0xA0B0C078 - self.assertEqual(list(out["%out_mrt0"]), [expected, expected, expected, expected]) - - def test_execute_multi_byte_bfi_pipeline(self): - asm = """\ -\tv_mov_b32 v0, 0 -\tv_mov_b32 v1, 0x000000ff -\tv_mov_b32 v2, 0x78 -\tv_bfi_b32 v0, v1, v2, v0 -\tv_mov_b32 v3, 0x0000ff00 -\tv_mov_b32 v4, 0x5600 -\tv_bfi_b32 v0, v3, v4, v0 -\tv_mov_b32 v5, 0x00ff0000 -\tv_mov_b32 v6, 0x340000 -\tv_bfi_b32 v0, v5, v6, v0 -\tv_mov_b32 v7, 0xff000000 -\tv_mov_b32 v8, 0x12000000 -\tv_bfi_b32 v0, v7, v8, v0 -\texp mrt0 v0, v0, v0, v0 done vm -\ts_endpgm""" - spv = translate_snippet(asm, "ps_bfi_pipeline") - out = run_spv_with_not(spv) - expected = 0x12345678 - self.assertEqual(list(out["%out_mrt0"]), [expected, expected, expected, expected]) - - -class NegativeControlsAndMutationTests(unittest.TestCase): - """Test that deviations from v_bfi_b32 semantics are detected.""" - - def test_sabotage_missing_not_fails(self): - mask = 0x00FF0000 - fld = 0x12345678 - base = 0xA0B0C0D0 - correct = ref_v_bfi_b32(mask, fld, base) - sabotaged = (mask & fld) | (mask & base) - self.assertNotEqual(correct, sabotaged) - - def test_sabotage_swapped_field_and_base_fails(self): - mask = 0x00FF0000 - fld = 0x12345678 - base = 0xA0B0C0D0 - correct = ref_v_bfi_b32(mask, fld, base) - swapped = ref_v_bfi_b32(mask, base, fld) - self.assertNotEqual(correct, swapped) - - def test_sabotage_and_instead_of_or_fails(self): - mask = 0x00FF0000 - fld = 0x12345678 - base = 0xA0B0C0D0 - correct = ref_v_bfi_b32(mask, fld, base) - sabotaged = ((mask & fld) & ((~mask & MASK32) & base)) & MASK32 - self.assertEqual(sabotaged, 0) - self.assertNotEqual(correct, sabotaged) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_alu_bfm_b32.py b/tests/semantic/test_alu_bfm_b32.py deleted file mode 100644 index 175a340c4..000000000 --- a/tests/semantic/test_alu_bfm_b32.py +++ /dev/null @@ -1,137 +0,0 @@ -"""Semantic translation tests for RDNA2 32-bit bitfield mask v_bfm_b32. - -Translates a synthetic pixel-shader listing through tools/rdna2spirv.translate() --> SPIR-V -> tests/semantic/spirv_mini_interp.py and compares the result against -a plain-Python reference: ((1 << (width & 31)) - 1) << (offset & 31). - -Covers: - - Basic mask generation for small widths/offsets - - Width 0 -> all zeros - - Width 31 -> all ones below bit 31 - - Offset up to 31 (mask shifted to top of dword) - - Width and offset masked to 5 bits (values >= 32 wrap) - - Negative control: result must not equal the input for non-trivial cases -""" -import os -import struct -import sys -import tempfile -import unittest -import warnings - -HERE = os.path.dirname(os.path.abspath(__file__)) -ROOT = os.path.dirname(os.path.dirname(HERE)) -TOOLS_DIR = os.environ.get("LEONIDA_TOOLS_DIR") or os.path.join(ROOT, "tools") - -sys.dont_write_bytecode = True -if TOOLS_DIR not in sys.path: - sys.path.insert(0, TOOLS_DIR) -if HERE not in sys.path: - sys.path.insert(0, HERE) - -import rdna2spirv # noqa: E402 -import spirv_mini_interp as si # noqa: E402 - -M32 = 0xFFFFFFFF -STUB_DXBC = b"DXBC" + bytes(24) + struct.pack(" int: - """Plain-Python reference for v_bfm_b32.""" - w = width & 31 - o = offset & 31 - if w == 0: - return 0 - return (((1 << w) - 1) << o) & M32 - - -_TMP_DIR = None -_SRC_PATH = None - - -def setUpModule(): - global _TMP_DIR, _SRC_PATH - _TMP_DIR = tempfile.TemporaryDirectory() - disasm_dir = os.path.join(_TMP_DIR.name, "disasm") - os.mkdir(disasm_dir) - _SRC_PATH = os.path.join(disasm_dir, "ps_bfm_b32.s") - with open(os.path.join(_TMP_DIR.name, "ps_bfm_b32.dxbc"), "wb") as f: - f.write(STUB_DXBC) - - -def tearDownModule(): - global _TMP_DIR - if _TMP_DIR is not None: - _TMP_DIR.cleanup() - _TMP_DIR = None - - -def run_op(width: int, offset: int) -> int: - """Translate and run a shader that computes v_bfm_b32 v1, v2, v3 with v2=width, v3=offset.""" - asm = ( - "; test_bfm_b32\n" - f"\tv_mov_b32_e32 v2, {width & M32:#x}\n" - f"\tv_mov_b32_e32 v3, {offset & M32:#x}\n" - "\tv_bfm_b32 v1, v2, v3\n" - "\ts_waitcnt vmcnt(0)\n" - "\texp mrt0 v1, v1, v1, v1 done vm\n" - "\ts_endpgm\n" - ) - with open(_SRC_PATH, "w", encoding="utf-8") as f: - f.write(asm) - with warnings.catch_warnings(): - warnings.simplefilter("ignore", ResourceWarning) - spv = rdna2spirv.translate(_SRC_PATH) - w = si.run_fragment(spv)["%out_mrt0"] - return w[0] & M32 - - -class ALUVBitfieldMaskB32Tests(unittest.TestCase): - def test_bfm_b32_basic(self): - # width=4, offset=0 -> 0b1111 = 0xF - self.assertEqual(run_op(4, 0), 0x0000000F) - # width=4, offset=4 -> 0b11110000 = 0xF0 - self.assertEqual(run_op(4, 4), 0x000000F0) - # width=8, offset=16 -> 0xFF0000 - self.assertEqual(run_op(8, 16), 0x00FF0000) - - def test_bfm_b32_width_zero(self): - # width=0 -> all zeros regardless of offset - for offset in (0, 1, 16, 31, 100): - with self.subTest(offset=offset): - self.assertEqual(run_op(0, offset), 0) - - def test_bfm_b32_reference(self): - cases = [ - (1, 0, 0x00000001), - (1, 31, 0x80000000), - (31, 0, 0x7FFFFFFF), - (32, 0, 0x00000000), # width masked to 0 -> all zeros - (33, 1, 0x00000002), # width masked to 1 -> bit 1 - (5, 31, 0x80000000), # width=5, offset=31 -> 31<<31 in 32 bits = bit 31 only - (16, 16, 0xFFFF0000), # width=16, offset=16 - ] - for width, offset, expected in cases: - with self.subTest(width=width, offset=offset): - self.assertEqual(run_op(width, offset), expected) - self.assertEqual(run_op(width, offset), ref_bfm32(width, offset)) - - def test_bfm_b32_masking(self): - # width and offset are masked to 5 bits (values >= 32 wrap) - self.assertEqual(run_op(32, 0), ref_bfm32(32, 0)) # width->0 - self.assertEqual(run_op(33, 0), ref_bfm32(33, 0)) # width->1 - self.assertEqual(run_op(0, 32), ref_bfm32(0, 32)) # offset->0 - self.assertEqual(run_op(1, 33), ref_bfm32(1, 33)) # offset->1 - - def test_bfm_b32_negative_control(self): - # For non-trivial width/offset, result differs from both inputs. - width, offset = 8, 4 - res = run_op(width, offset) - expected = ref_bfm32(width, offset) - self.assertEqual(res, expected) - self.assertNotEqual(res, width) - self.assertNotEqual(res, offset) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_alu_bitfield_rev.py b/tests/semantic/test_alu_bitfield_rev.py deleted file mode 100644 index 1702d8b96..000000000 --- a/tests/semantic/test_alu_bitfield_rev.py +++ /dev/null @@ -1,834 +0,0 @@ -"""Semantic interpreter tests for RDNA2 vector bitfield operations (v_bfe_u32, v_bfe_i32, v_bfi_b32). - -Covers: - - RDNA2 Vector ALU Bitfield Instructions: - * v_bfe_u32 D, S0, S1, S2: - Unsigned bitfield extract. Extracts S2 (width) bits from S0 (base) starting at - bit S1 (offset). - D = (S0 >> (S1 & 31)) & ((1 << eff_width) - 1) - where eff_width = min(S2 & 31, 32 - (S1 & 31)). - If width == 0, D = 0. - * v_bfe_i32 D, S0, S1, S2: - Signed bitfield extract. Extracts S2 (width) bits from S0 (base) starting at - bit S1 (offset) and sign-extends the result from bit (eff_width - 1) to 32 bits. - If width == 0, D = 0. - * v_bfi_b32 D, S0, S1, S2: - Bitfield insert with bitmask selection. - D = (S0 & S1) | (~S0 & S2) - where S0 is bitmask, S1 is replacement field, S2 is base dword. - - Verification layers: - 1. Pure Python reference mathematical oracles. - 2. Simulated VALU register file interpreter (AluBitfieldInterpreter). - 3. SPIR-V lowering and execution via rdna2spirv and spirv_mini_interp. - -Zero game data, standard library Python only, Python 3.9+ compatible. -""" -from __future__ import annotations - -import os -import struct -import sys -import unittest -import warnings - -HERE = os.path.dirname(os.path.abspath(__file__)) -ROOT = os.path.dirname(os.path.dirname(HERE)) -TOOLS_DIR = os.environ.get("LEONIDA_TOOLS_DIR") or os.path.join(ROOT, "tools") - -if ROOT not in sys.path: - sys.path.insert(0, ROOT) -if TOOLS_DIR not in sys.path: - sys.path.insert(0, TOOLS_DIR) -if HERE not in sys.path: - sys.path.insert(0, HERE) - -import rdna2spirv # noqa: E402 -import spirv_mini_interp as si # noqa: E402 -from support import STUB_DXBC, mrt0_words, translate_lines # noqa: E402 - -MASK32 = 0xFFFFFFFF - - -def u32(val: int) -> int: - """Normalize integer to 32-bit unsigned dword.""" - return val & MASK32 - - -def i32(val: int) -> int: - """Convert 32-bit unsigned dword to signed two's complement integer.""" - val = val & MASK32 - return val - (1 << 32) if val >> 31 else val - - -def make_mask(offset: int, width: int) -> int: - """Generate a contiguous 32-bit mask of given width at given offset.""" - off = offset & 31 - wid = width & 31 - if wid == 0: - return 0 - eff_wid = min(wid, 32 - off) - if eff_wid >= 32: - return MASK32 - return (((1 << eff_wid) - 1) << off) & MASK32 - - -def pack_field(base: int, val: int, offset: int, width: int) -> int: - """Pack value into base at [offset +: width] using v_bfi_b32 semantics.""" - mask = make_mask(offset, width) - field = (val << (offset & 31)) & mask - return ref_v_bfi_b32(mask, field, base) - - -def ref_v_bfe_u32(base: int, offset: int, width: int) -> int: - """Reference implementation of RDNA2 v_bfe_u32 ALU instruction. - - D = (base >> (offset & 31)) & ((1 << eff_width) - 1) - Clamps effective width to (32 - (offset & 31)) per RDNA2 ISA / SPIR-V lower bounds. - """ - b = base & MASK32 - off = offset & 31 - wid = width & 31 - eff_wid = min(wid, 32 - off) - if eff_wid == 0: - return 0 - return ((b >> off) & ((1 << eff_wid) - 1)) & MASK32 - - -def ref_v_bfe_i32(base: int, offset: int, width: int) -> int: - """Reference implementation of RDNA2 v_bfe_i32 ALU instruction. - - Extracts eff_wid bits and sign-extends from bit (eff_wid - 1). - If eff_wid == 0, returns 0. - """ - b = base & MASK32 - off = offset & 31 - wid = width & 31 - eff_wid = min(wid, 32 - off) - if eff_wid == 0: - return 0 - field = (b >> off) & ((1 << eff_wid) - 1) - if field & (1 << (eff_wid - 1)): - field -= 1 << eff_wid - return field & MASK32 - - -def ref_v_bfi_b32(mask: int, field: int, base: int) -> int: - """Reference implementation of RDNA2 v_bfi_b32 ALU instruction. - - D = (mask & field) | (~mask & base) - """ - m = mask & MASK32 - f = field & MASK32 - b = base & MASK32 - return ((m & f) | ((~m & MASK32) & b)) & MASK32 - - -class AluBitfieldInterpreter: - """Simulated RDNA2 VALU register machine with VGPR state.""" - - def __init__(self, num_vgprs: int = 64) -> None: - self.vgprs = [0] * num_vgprs - - def get_vgpr(self, reg: int) -> int: - return self.vgprs[reg] & MASK32 - - def set_vgpr(self, reg: int, val: int) -> None: - self.vgprs[reg] = val & MASK32 - - def _resolve_src(self, operand: int | str) -> int: - if isinstance(operand, int): - return operand & MASK32 - op_str = str(operand).strip().lower() - if op_str.startswith("v") and op_str[1:].isdigit(): - idx = int(op_str[1:]) - return self.get_vgpr(idx) - if op_str.startswith("0x") or op_str.startswith("-0x"): - return int(op_str, 16) & MASK32 - return int(op_str) & MASK32 - - def _resolve_dst_reg(self, operand: int | str) -> int: - if isinstance(operand, int): - return operand - op_str = str(operand).strip().lower() - if op_str.startswith("v") and op_str[1:].isdigit(): - return int(op_str[1:]) - raise ValueError(f"Invalid VGPR destination: {operand}") - - def step(self, mnemonic: str, dst: int | str, *srcs: int | str) -> int: - d_idx = self._resolve_dst_reg(dst) - m = mnemonic.strip().lower() - if m in ("v_mov_b32", "v_mov_b32_e32", "v_mov_b32_e64"): - res = self._resolve_src(srcs[0]) - elif m in ("v_bfe_u32", "v_bfe_u32_e64"): - base = self._resolve_src(srcs[0]) - off = self._resolve_src(srcs[1]) - wid = self._resolve_src(srcs[2]) - res = ref_v_bfe_u32(base, off, wid) - elif m in ("v_bfe_i32", "v_bfe_i32_e64"): - base = self._resolve_src(srcs[0]) - off = self._resolve_src(srcs[1]) - wid = self._resolve_src(srcs[2]) - res = ref_v_bfe_i32(base, off, wid) - elif m in ("v_bfi_b32", "v_bfi_b32_e64"): - mask = self._resolve_src(srcs[0]) - field = self._resolve_src(srcs[1]) - base = self._resolve_src(srcs[2]) - res = ref_v_bfi_b32(mask, field, base) - elif m in ("v_and_b32", "v_and_b32_e32", "v_and_b32_e64"): - res = (self._resolve_src(srcs[0]) & self._resolve_src(srcs[1])) & MASK32 - elif m in ("v_or_b32", "v_or_b32_e32", "v_or_b32_e64"): - res = (self._resolve_src(srcs[0]) | self._resolve_src(srcs[1])) & MASK32 - elif m in ("v_xor_b32", "v_xor_b32_e32", "v_xor_b32_e64"): - res = (self._resolve_src(srcs[0]) ^ self._resolve_src(srcs[1])) & MASK32 - elif m in ("v_not_b32", "v_not_b32_e32", "v_not_b32_e64"): - res = (~self._resolve_src(srcs[0])) & MASK32 - elif m in ("v_lshlrev_b32", "v_lshlrev_b32_e32", "v_lshlrev_b32_e64"): - shift = self._resolve_src(srcs[0]) & 31 - val = self._resolve_src(srcs[1]) - res = (val << shift) & MASK32 - elif m in ("v_lshrrev_b32", "v_lshrrev_b32_e32", "v_lshrrev_b32_e64"): - shift = self._resolve_src(srcs[0]) & 31 - val = self._resolve_src(srcs[1]) - res = (val >> shift) & MASK32 - elif m in ("v_ashrrev_i32", "v_ashrrev_i32_e32", "v_ashrrev_i32_e64"): - shift = self._resolve_src(srcs[0]) & 31 - val = i32(self._resolve_src(srcs[1])) - res = (val >> shift) & MASK32 - else: - raise NotImplementedError(f"Instruction {mnemonic} not modeled in AluBitfieldInterpreter") - - self.set_vgpr(d_idx, res) - return res - - def run_program(self, instructions: list[tuple]) -> None: - for instr in instructions: - mnemonic, dst, *srcs = instr - self.step(mnemonic, dst, *srcs) - - -def run_rdna_ps(lines: list[str], name: str = "ps_alu_bitfield") -> list[int]: - """Assemble and run a pixel shader ending with mrt0 export.""" - all_lines = list(lines) + [ - "exp mrt0 v0, v1, v2, v3 done vm", - "s_endpgm", - ] - spv = translate_lines(name, all_lines) - return mrt0_words(spv) - - -def run_rdna_cs_wave( - lines: list[str], - num_lanes: int = 16, - initial_mem: dict[int, int] | None = None, - name: str = "cs_simd_wave", -) -> dict[int, int]: - """Assemble and run a compute shader workgroup with linear local IDs.""" - fssm = bytearray(0x148) - struct.pack_into("<4I", fssm, 0x138, 0x8088, num_lanes, 1, 1) - all_lines = list(lines) + ["s_endpgm"] - spv = translate_lines(name, all_lines, fssm=bytes(fssm)) - mem = dict(initial_mem or {}) - return si.run_workgroup( - spv, - num_lanes, - 32, - inputs_for=lambda i: {"%wg_id": (0, 0, 0), "%local_id": (i, 0, 0), "%sg_lane": i}, - push_constants=[0, 0, 0x1000, 0x31016FAC] + [0] * 28, - memory=mem, - ) - - -class SimdWaveBitfieldModel: - """Deterministic SIMD Wave model executing vector bitfield operations with EXEC masks.""" - - def __init__(self, wave_size: int = 32, num_vgprs: int = 64) -> None: - self.wave_size = wave_size - self.num_vgprs = num_vgprs - self.vgprs = [[0] * num_vgprs for _ in range(wave_size)] - self.exec_mask = (1 << wave_size) - 1 - - def set_exec(self, mask: int) -> None: - self.exec_mask = mask & ((1 << self.wave_size) - 1) - - def set_lane_vgpr(self, lane: int, reg: int, val: int) -> None: - self.vgprs[lane][reg] = val & MASK32 - - def get_lane_vgpr(self, lane: int, reg: int) -> int: - return self.vgprs[lane][reg] - - def v_bfe_u32(self, dst: int, src_base: int, src_off: int, src_wid: int) -> None: - for lane in range(self.wave_size): - if self.exec_mask & (1 << lane): - base = self.vgprs[lane][src_base] - off = self.vgprs[lane][src_off] - wid = self.vgprs[lane][src_wid] - self.vgprs[lane][dst] = ref_v_bfe_u32(base, off, wid) - - def v_bfe_i32(self, dst: int, src_base: int, src_off: int, src_wid: int) -> None: - for lane in range(self.wave_size): - if self.exec_mask & (1 << lane): - base = self.vgprs[lane][src_base] - off = self.vgprs[lane][src_off] - wid = self.vgprs[lane][src_wid] - self.vgprs[lane][dst] = ref_v_bfe_i32(base, off, wid) - - def v_bfi_b32(self, dst: int, src_mask: int, src_fld: int, src_base: int) -> None: - for lane in range(self.wave_size): - if self.exec_mask & (1 << lane): - mask = self.vgprs[lane][src_mask] - fld = self.vgprs[lane][src_fld] - base = self.vgprs[lane][src_base] - self.vgprs[lane][dst] = ref_v_bfi_b32(mask, fld, base) - - -class TestBitfieldReferenceOracle(unittest.TestCase): - """Unit tests for pure Python reference oracles.""" - - def test_ref_bfe_u32_basic_fields(self): - cases = [ - (0x12345678, 4, 8, 0x67), - (0xDEADBEEF, 8, 12, 0xDBE), - (0xABCD1234, 16, 16, 0xABCD), - (0xFEDCBA98, 0, 4, 0x8), - (0xFEDCBA98, 0, 8, 0x98), - (0xFEDCBA98, 0, 16, 0xBA98), - (0x87654321, 28, 4, 0x8), - ] - for base, off, wid, expected in cases: - with self.subTest(base=hex(base), off=off, wid=wid): - self.assertEqual(ref_v_bfe_u32(base, off, wid), expected) - - def test_ref_bfe_u32_zero_width_is_zero(self): - bases = [0x00000000, 0xFFFFFFFF, 0xDEADBEEF, 0x12345678, 0x80000000] - offsets = [0, 1, 7, 15, 16, 30, 31] - for b in bases: - for off in offsets: - with self.subTest(base=hex(b), off=off): - self.assertEqual(ref_v_bfe_u32(b, off, 0), 0) - - def test_ref_bfe_u32_single_bit_extractions(self): - for bit in range(32): - val = 1 << bit - with self.subTest(bit=bit): - self.assertEqual(ref_v_bfe_u32(val, bit, 1), 1) - self.assertEqual(ref_v_bfe_u32(~val & MASK32, bit, 1), 0) - - def test_ref_bfe_u32_offset_modulo_32(self): - base = 0x12345678 - self.assertEqual(ref_v_bfe_u32(base, 36, 8), ref_v_bfe_u32(base, 4, 8)) - self.assertEqual(ref_v_bfe_u32(base, 68, 8), ref_v_bfe_u32(base, 4, 8)) - - def test_ref_bfe_i32_positive_values_zero_extended(self): - cases = [ - (0x76543210, 28, 4, 0x00000007), - (0x00007FFF, 0, 16, 0x00007FFF), - (0x00003FFF, 0, 15, 0x00003FFF), - (0x1234007F, 0, 8, 0x0000007F), - (0x55555555, 0, 2, 0x00000001), - ] - for base, off, wid, expected in cases: - with self.subTest(base=hex(base), off=off, wid=wid): - self.assertEqual(ref_v_bfe_i32(base, off, wid), expected) - - def test_ref_bfe_i32_negative_values_sign_extended(self): - cases = [ - (0xFFFFFFF0, 2, 4, 0xFFFFFFFC), - (0x80000000, 31, 1, 0xFFFFFFFF), - (0x00000080, 0, 8, 0xFFFFFF80), - (0x00008000, 0, 16, 0xFFFF8000), - (0xAAAAAAAA, 0, 2, 0xFFFFFFFE), - (0xFFFFFFFF, 0, 4, 0xFFFFFFFF), - ] - for base, off, wid, expected in cases: - with self.subTest(base=hex(base), off=off, wid=wid): - self.assertEqual(ref_v_bfe_i32(base, off, wid), expected) - - def test_ref_bfe_i32_zero_width_is_zero(self): - bases = [0x00000000, 0xFFFFFFFF, 0xDEADBEEF, 0x80000000, 0x7FFFFFFF] - for b in bases: - for off in (0, 1, 15, 31): - with self.subTest(base=hex(b), off=off): - self.assertEqual(ref_v_bfe_i32(b, off, 0), 0) - - def test_ref_bfe_i32_single_bit_signs(self): - for bit in range(32): - val = 1 << bit - with self.subTest(bit=bit): - # When bit is 1 and width is 1, bit (width - 1) is 1 -> sign extends to -1 (0xFFFFFFFF) - self.assertEqual(ref_v_bfe_i32(val, bit, 1), MASK32) - # When bit is 0 and width is 1, bit (width - 1) is 0 -> zero extends to 0 - self.assertEqual(ref_v_bfe_i32(~val & MASK32, bit, 1), 0) - - def test_ref_bfi_b32_basic_cases(self): - cases = [ - (0x00FF0000, 0x12345678, 0xA0B0C0D0, 0xA034C0D0), - (0x000000FF, 0xAABBCCDD, 0x11223344, 0x112233DD), - (0xFF000000, 0xAABBCCDD, 0x11223344, 0xAA223344), - (0x0000FF00, 0xAABBCCDD, 0x11223344, 0x1122CC44), - (0xF0F0F0F0, 0xAAAAAAAA, 0x55555555, 0xA5A5A5A5), - (0x0F0F0F0F, 0xAAAAAAAA, 0x55555555, 0x5A5A5A5A), - ] - for mask, fld, base, expected in cases: - with self.subTest(mask=hex(mask), fld=hex(fld), base=hex(base)): - self.assertEqual(ref_v_bfi_b32(mask, fld, base), expected) - - def test_ref_bfi_b32_mask_zero_preserves_base(self): - for base in [0x0, 0xFFFFFFFF, 0x12345678, 0xDEADBEEF, 0x80000001]: - with self.subTest(base=hex(base)): - self.assertEqual(ref_v_bfi_b32(0, 0xCAFEBABE, base), base) - - def test_ref_bfi_b32_mask_all_ones_replaces_base(self): - for fld in [0x0, 0xFFFFFFFF, 0x12345678, 0xDEADBEEF, 0x80000001]: - with self.subTest(fld=hex(fld)): - self.assertEqual(ref_v_bfi_b32(MASK32, fld, 0xCAFEBABE), fld) - - def test_ref_bfi_b32_identity_field_equals_base(self): - for val in [0x0, 0xFFFFFFFF, 0x12345678, 0x87654321, 0x55555555]: - for mask in [0x0, 0xFFFFFFFF, 0xF0F0F0F0, 0x00FF00FF]: - self.assertEqual(ref_v_bfi_b32(mask, val, val), val) - - def test_ref_bfi_b32_duality_inverted_mask(self): - mask = 0x3CA55AC3 - s1 = 0xDEADBEEF - s2 = 0x01234567 - inv_mask = (~mask) & MASK32 - self.assertEqual(ref_v_bfi_b32(mask, s1, s2), ref_v_bfi_b32(inv_mask, s2, s1)) - - -class TestAluBitfieldInterpreter(unittest.TestCase): - """Tests for simulated register interpreter executing bitfield operations.""" - - def test_interpreter_mov_and_bfe_u32(self): - interp = AluBitfieldInterpreter() - interp.step("v_mov_b32", "v1", 0x12345678) - interp.step("v_mov_b32", "v2", 4) - interp.step("v_mov_b32", "v3", 8) - interp.step("v_bfe_u32", "v0", "v1", "v2", "v3") - self.assertEqual(interp.get_vgpr(0), 0x67) - - def test_interpreter_bfe_i32_sign_extension(self): - interp = AluBitfieldInterpreter() - interp.step("v_mov_b32", "v1", 0xFFFFFFF0) - interp.step("v_mov_b32", "v2", 2) - interp.step("v_mov_b32", "v3", 4) - interp.step("v_bfe_i32", "v0", "v1", "v2", "v3") - self.assertEqual(interp.get_vgpr(0), 0xFFFFFFFC) - - def test_interpreter_bfi_b32(self): - interp = AluBitfieldInterpreter() - interp.step("v_mov_b32", "v1", 0x00FF0000) - interp.step("v_mov_b32", "v2", 0x12345678) - interp.step("v_mov_b32", "v3", 0xA0B0C0D0) - interp.step("v_bfi_b32", "v0", "v1", "v2", "v3") - self.assertEqual(interp.get_vgpr(0), 0xA034C0D0) - - def test_interpreter_in_place_overwrite(self): - interp = AluBitfieldInterpreter() - interp.set_vgpr(0, 0x12345678) - interp.step("v_bfe_u32", "v0", "v0", 8, 8) - self.assertEqual(interp.get_vgpr(0), 0x56) - - def test_interpreter_operand_aliasing(self): - interp = AluBitfieldInterpreter() - interp.set_vgpr(1, 0x0000FFFF) - interp.set_vgpr(0, 0x12345678) - interp.step("v_bfi_b32", "v0", "v1", "v0", "v0") - self.assertEqual(interp.get_vgpr(0), 0x12345678) - - -class TestRdna2SpirvTranslationBfeBfi(unittest.TestCase): - """Verifies that rdna2spirv lowers v_bfe and v_bfi instructions matching oracle.""" - - def test_rdna2_bfe_u32_translation_matches_oracle(self): - cases = [ - (0x12345678, 4, 8), - (0xDEADBEEF, 8, 12), - (0xABCD1234, 16, 16), - (0xFFFFFFFF, 0, 8), - (0x80000000, 31, 1), - ] - for base, off, wid in cases: - expected = ref_v_bfe_u32(base, off, wid) - words = run_rdna_ps([ - f"v_mov_b32 v1, {base:#x}", - f"v_mov_b32 v2, {off}", - f"v_mov_b32 v3, {wid}", - "v_bfe_u32 v0, v1, v2, v3", - "v_mov_b32 v1, v0", - "v_mov_b32 v2, v0", - "v_mov_b32 v3, v0", - ], name=f"ps_bfe_u_{off}_{wid}") - self.assertEqual(words[0], expected) - - def test_rdna2_bfe_i32_translation_matches_oracle(self): - cases = [ - (0xFFFFFFF0, 2, 4), - (0x80000000, 31, 1), - (0x00007FFF, 0, 16), - (0x00008000, 0, 16), - ] - for base, off, wid in cases: - expected = ref_v_bfe_i32(base, off, wid) - words = run_rdna_ps([ - f"v_mov_b32 v1, {base:#x}", - f"v_mov_b32 v2, {off}", - f"v_mov_b32 v3, {wid}", - "v_bfe_i32 v0, v1, v2, v3", - "v_mov_b32 v1, v0", - "v_mov_b32 v2, v0", - "v_mov_b32 v3, v0", - ], name=f"ps_bfe_i_{off}_{wid}") - self.assertEqual(words[0], expected) - - def test_rdna2_bfi_b32_translation_matches_oracle(self): - cases = [ - (0x00FF0000, 0x12345678, 0xA0B0C0D0), - (0x000000FF, 0xAABBCCDD, 0x11223344), - (0xF0F0F0F0, 0xAAAAAAAA, 0x55555555), - ] - for mask, fld, base in cases: - expected = ref_v_bfi_b32(mask, fld, base) - words = run_rdna_ps([ - f"v_mov_b32 v1, {mask:#x}", - f"v_mov_b32 v2, {fld:#x}", - f"v_mov_b32 v3, {base:#x}", - "v_bfi_b32 v0, v1, v2, v3", - "v_mov_b32 v1, v0", - "v_mov_b32 v2, v0", - "v_mov_b32 v3, v0", - ], name=f"ps_bfi_{mask & 0xFFFF:#x}") - self.assertEqual(words[0], expected) - - -class TestBitfieldRoundtripAndComposition(unittest.TestCase): - """Verifies roundtrip invariants, untouched bits preservation, and mask composition.""" - - def test_extract_insert_roundtrip_exhaustive_offsets(self): - """For any word, extracting [off : off + wid] and re-inserting restores original word.""" - test_patterns = [ - 0x12345678, - 0xDEADBEEF, - 0xA5A5A5A5, - 0x00000001, - 0x80000000, - 0xFFFFFFFF, - 0x00000000, - 0xCAFEBABE, - ] - for base in test_patterns: - for off in (0, 1, 4, 7, 8, 12, 16, 20, 24, 28, 31): - for wid in (1, 2, 4, 8, 12, 16, 24, 32 - off): - if off + wid > 32 or wid <= 0: - continue - with self.subTest(base=hex(base), off=off, wid=wid): - extracted = ref_v_bfe_u32(base, off, wid) - restored = pack_field(base, extracted, off, wid) - self.assertEqual(restored, base) - isolated = pack_field(0, extracted, off, wid) - mask = make_mask(off, wid) - self.assertEqual(isolated, base & mask) - - def test_untouched_bits_preservation(self): - """Inserting a new field value modifies only the masked bits, leaving untouched bits intact.""" - base = 0xDEADBEEF - for off in (0, 4, 8, 16, 24): - for wid in (1, 4, 8, 12): - if off + wid > 32: - continue - mask = make_mask(off, wid) - new_val = 0x5A - inserted = pack_field(base, new_val, off, wid) - self.assertEqual(inserted & (~mask & MASK32), base & (~mask & MASK32)) - extracted_new = ref_v_bfe_u32(inserted, off, wid) - self.assertEqual(extracted_new, new_val & ((1 << wid) - 1)) - - def test_rgba8_pack_unpack_roundtrip(self): - """Simulate packing and unpacking RGBA8 color components.""" - r, g, b, a = 0x12, 0x34, 0x56, 0x78 - packed = 0 - packed = pack_field(packed, r, 0, 8) - packed = pack_field(packed, g, 8, 8) - packed = pack_field(packed, b, 16, 8) - packed = pack_field(packed, a, 24, 8) - self.assertEqual(packed, 0x78563412) - - out_r = ref_v_bfe_u32(packed, 0, 8) - out_g = ref_v_bfe_u32(packed, 8, 8) - out_b = ref_v_bfe_u32(packed, 16, 8) - out_a = ref_v_bfe_u32(packed, 24, 8) - self.assertEqual((out_r, out_g, out_b, out_a), (r, g, b, a)) - - def test_hdr_r10g10b10a2_pack_unpack(self): - """Simulate packing and unpacking HDR10 R10G10B10A2 format.""" - r10 = 0x3FF - g10 = 0x200 - b10 = 0x155 - a2 = 0x3 - - packed = 0 - packed = pack_field(packed, r10, 0, 10) - packed = pack_field(packed, g10, 10, 10) - packed = pack_field(packed, b10, 20, 10) - packed = pack_field(packed, a2, 30, 2) - - self.assertEqual(ref_v_bfe_u32(packed, 0, 10), r10) - self.assertEqual(ref_v_bfe_u32(packed, 10, 10), g10) - self.assertEqual(ref_v_bfe_u32(packed, 20, 10), b10) - self.assertEqual(ref_v_bfe_u32(packed, 30, 2), a2) - - def test_rgb565_pack_unpack(self): - """Simulate packing and unpacking 16-bit RGB565 in low word.""" - r5 = 0x1F - g6 = 0x2A - b5 = 0x0E - - packed = 0 - packed = pack_field(packed, r5, 0, 5) - packed = pack_field(packed, g6, 5, 6) - packed = pack_field(packed, b5, 11, 5) - - self.assertEqual(ref_v_bfe_u32(packed, 0, 5), r5) - self.assertEqual(ref_v_bfe_u32(packed, 5, 6), g6) - self.assertEqual(ref_v_bfe_u32(packed, 11, 5), b5) - self.assertEqual(packed >> 16, 0) - - def test_bfi_boolean_xor_equivalence(self): - """Verify algebraic equivalence: BFI(m, f, b) == ((m & (f ^ b)) ^ b).""" - test_tuples = [ - (0x00FF0000, 0x12345678, 0x87654321), - (0xF0F0F0F0, 0xAAAAAAAA, 0x55555555), - (0x12345678, 0xDEADBEEF, 0xCAFEBABE), - (0xFFFFFFFF, 0x11111111, 0x22222222), - (0x00000000, 0x11111111, 0x22222222), - ] - for m, f, b in test_tuples: - bfi_std = ref_v_bfi_b32(m, f, b) - bfi_xor = ((m & (f ^ b)) ^ b) & MASK32 - self.assertEqual(bfi_std, bfi_xor) - - def test_shader_extract_insert_roundtrip(self): - """Run translated shader performing roundtrip extraction and re-insertion.""" - base = 0x12345678 - lines = [ - f"v_mov_b32 v1, {base:#x}", - "v_mov_b32 v2, 8", - "v_mov_b32 v3, 8", - "v_bfe_u32 v4, v1, v2, v3", - "v_add_nc_u32 v4, 1, v4", - "v_lshlrev_b32 v4, 8, v4", - "v_mov_b32 v5, 0x0000FF00", - "v_bfi_b32 v0, v5, v4, v1", - "v_mov_b32 v1, v0", - "v_mov_b32 v2, v0", - "v_mov_b32 v3, v0", - ] - words = run_rdna_ps(lines, name="ps_bfe_bfi_roundtrip") - self.assertEqual(words[0], 0x12345778) - - -class TestBitfieldClampBoundaries(unittest.TestCase): - """Verifies edge cases for width/offset clamp boundaries, zero width, and modulo 32.""" - - def test_offset_plus_width_exceeds_32_clamped(self): - """When offset + width > 32, width clamps to min(width, 32 - offset).""" - cases = [ - (0xFFFFFFFF, 24, 16, 8, 0x000000FF), - (0xDEADBEEF, 28, 8, 4, 0x0000000D), - (0x80000000, 31, 31, 1, 0x00000001), - (0x12345678, 16, 20, 16, 0x00001234), - ] - for base, off, wid, eff_wid, expected in cases: - with self.subTest(base=hex(base), off=off, wid=wid): - self.assertEqual(ref_v_bfe_u32(base, off, wid), expected) - words = run_rdna_ps([ - f"v_mov_b32 v1, {base:#x}", - f"v_mov_b32 v2, {off}", - f"v_mov_b32 v3, {wid}", - "v_bfe_u32 v0, v1, v2, v3", - "v_mov_b32 v1, v0", - "v_mov_b32 v2, v0", - "v_mov_b32 v3, v0", - ], name=f"ps_clamp_u_{off}_{wid}") - self.assertEqual(words[0], expected) - - def test_signed_clamp_boundary_sign_extension(self): - """When clamped, sign extension for v_bfe_i32 extends from (eff_width - 1).""" - cases = [ - (0xC0000000, 30, 8, 0xFFFFFFFF), - (0x80000000, 30, 8, 0xFFFFFFFE), - (0x40000000, 30, 8, 0x00000001), - (0x80000000, 31, 16, 0xFFFFFFFF), - ] - for base, off, wid, expected in cases: - with self.subTest(base=hex(base), off=off, wid=wid): - self.assertEqual(ref_v_bfe_i32(base, off, wid), expected) - words = run_rdna_ps([ - f"v_mov_b32 v1, {base:#x}", - f"v_mov_b32 v2, {off}", - f"v_mov_b32 v3, {wid}", - "v_bfe_i32 v0, v1, v2, v3", - "v_mov_b32 v1, v0", - "v_mov_b32 v2, v0", - "v_mov_b32 v3, v0", - ], name=f"ps_clamp_i_{off}_{wid}") - self.assertEqual(words[0], expected) - - def test_offset_modulo_32_wrapping(self): - """Offset operand is taken modulo 32.""" - base = 0x12345678 - for extra in (32, 64, 96): - self.assertEqual(ref_v_bfe_u32(base, 4 + extra, 8), 0x67) - self.assertEqual(ref_v_bfe_u32(base, 0 + extra, 4), 0x8) - - def test_width_modulo_32_wrapping_and_zero(self): - """Width is taken modulo 32; width=0 or width=32 (32 & 31 = 0) returns 0.""" - for base in (0xFFFFFFFF, 0x12345678, 0xDEADBEEF): - for off in (0, 7, 16, 31): - self.assertEqual(ref_v_bfe_u32(base, off, 0), 0) - self.assertEqual(ref_v_bfe_u32(base, off, 32), 0) - self.assertEqual(ref_v_bfe_i32(base, off, 0), 0) - self.assertEqual(ref_v_bfe_i32(base, off, 32), 0) - - -class TestSimdDivergence(unittest.TestCase): - """Verifies SIMD lane divergence and EXEC mask write inhibition.""" - - def test_simd_divergent_per_lane_extraction(self): - """16 SIMD compute lanes evaluate lane-dependent bitfield offsets.""" - lanes = 16 - base = 0x76543210 - lines = [ - f"v_mov_b32_e32 v1, {base:#x}", - "v_bfe_u32 v2, v1, v0, 4", - "v_lshlrev_b32_e32 v3, 2, v0", - "buffer_store_dword v2, v3, s[0:3], 0 offen", - ] - mem = run_rdna_cs_wave(lines, num_lanes=lanes, name="cs_simd_divergent") - for i in range(lanes): - expected = ref_v_bfe_u32(base, i, 4) - self.assertEqual(mem[4 * i], expected, f"Mismatch at lane {i}") - - def test_simd_exec_mask_write_inhibition(self): - """Lanes deactivated by v_cmpx do not write to destination memory.""" - lanes = 16 - initial_mem = {4 * i: 0xDEADBEEF for i in range(lanes)} - lines = [ - "v_mov_b32_e32 v1, 0x12345678", - "v_cmpx_lt_u32_e32 v0, 8", - "v_bfe_u32 v2, v1, 4, 8", - "v_lshlrev_b32_e32 v3, 2, v0", - "buffer_store_dword v2, v3, s[0:3], 0 offen", - ] - mem = run_rdna_cs_wave(lines, num_lanes=lanes, initial_mem=initial_mem, name="cs_simd_exec_mask") - for i in range(lanes): - if i < 8: - self.assertEqual(mem[4 * i], 0x67, f"Active lane {i} should be updated") - else: - self.assertEqual(mem[4 * i], 0xDEADBEEF, f"Inactive lane {i} should remain unchanged") - - def test_simd_wave_model_wave32_and_wave64(self): - """Test pure-Python SimdWaveBitfieldModel across wave32 and wave64 configurations.""" - for wave_size in (32, 64): - model = SimdWaveBitfieldModel(wave_size=wave_size) - for lane in range(wave_size): - model.set_lane_vgpr(lane, 1, 0x12345678) - model.set_lane_vgpr(lane, 2, lane & 15) - model.set_lane_vgpr(lane, 3, 4) - model.set_lane_vgpr(lane, 0, 0xAAAAAAAA) - - even_mask = sum(1 << l for l in range(wave_size) if l % 2 == 0) - model.set_exec(even_mask) - model.v_bfe_u32(0, 1, 2, 3) - - for lane in range(wave_size): - if lane % 2 == 0: - expected = ref_v_bfe_u32(0x12345678, lane & 15, 4) - self.assertEqual(model.get_lane_vgpr(lane, 0), expected) - else: - self.assertEqual(model.get_lane_vgpr(lane, 0), 0xAAAAAAAA) - - -class TestNegativeControls(unittest.TestCase): - """Negative controls ensuring sensitivity to subtle bitfield errors.""" - - def test_negative_unsigned_bfe_sign_extend_detected(self): - """Mutated v_bfe_u32 that incorrectly sign-extends must fail assertion.""" - def buggy_bfe_u32(base: int, offset: int, width: int) -> int: - return ref_v_bfe_i32(base, offset, width) - - correct = ref_v_bfe_u32(0x80000000, 31, 1) - buggy = buggy_bfe_u32(0x80000000, 31, 1) - self.assertEqual(correct, 1) - self.assertNotEqual(buggy, correct) - - def test_negative_signed_bfe_zero_extend_detected(self): - """Mutated v_bfe_i32 that incorrectly zero-extends must fail assertion.""" - def buggy_bfe_i32(base: int, offset: int, width: int) -> int: - return ref_v_bfe_u32(base, offset, width) - - correct = ref_v_bfe_i32(0x80000000, 31, 1) - buggy = buggy_bfe_i32(0x80000000, 31, 1) - self.assertEqual(correct, MASK32) - self.assertNotEqual(buggy, correct) - - def test_negative_bfi_inverted_operands_detected(self): - """Mutated v_bfi_b32 that inverts wrong operand must fail assertion.""" - def buggy_bfi_b32(mask: int, field: int, base: int) -> int: - return ((mask & base) | ((~mask & MASK32) & field)) & MASK32 - - mask, field, base = 0x00FF0000, 0x12345678, 0xA0B0C0D0 - correct = ref_v_bfi_b32(mask, field, base) - buggy = buggy_bfi_b32(mask, field, base) - self.assertEqual(correct, 0xA034C0D0) - self.assertNotEqual(buggy, correct) - - def test_negative_width_zero_nonzero_result_detected(self): - """Mutated zero-width returning base must fail assertion.""" - def buggy_bfe_zero_width(base: int, offset: int, width: int) -> int: - if width == 0: - return base & MASK32 - return ref_v_bfe_u32(base, offset, width) - - correct = ref_v_bfe_u32(0xDEADBEEF, 4, 0) - buggy = buggy_bfe_zero_width(0xDEADBEEF, 4, 0) - self.assertEqual(correct, 0) - self.assertNotEqual(buggy, correct) - - def test_negative_clamp_out_of_bounds_detected(self): - """Mutated BFE that shifts without clamping width beyond 32 must diverge.""" - def unclamped_bfe_i32(base: int, offset: int, width: int) -> int: - val = ((base & MASK32) >> offset) & ((1 << width) - 1) - if val & (1 << (width - 1)): - val -= 1 << width - return val & MASK32 - - # At off=30, wid=8: clamped effective width is 2 (bits 30..31 of 0xFFFFFFFF are 11 -> sign-extends to 0xFFFFFFFF). - # Unclamped width=8 checks bit 7 (which is 0!), incorrectly treating it as positive 3 (0x00000003). - clamped = ref_v_bfe_i32(0xFFFFFFFF, 30, 8) - unclamped = unclamped_bfe_i32(0xFFFFFFFF, 30, 8) - self.assertEqual(clamped, MASK32) - self.assertEqual(unclamped, 0x3) - self.assertNotEqual(clamped, unclamped) - - def test_negative_simd_inactive_lane_leak_detected(self): - """Mutated SIMD execution that updates inactive lanes must fail assertion.""" - model = SimdWaveBitfieldModel(wave_size=32) - for l in range(32): - model.set_lane_vgpr(l, 0, 0x11111111) - model.set_lane_vgpr(l, 1, 0x22222222) - model.set_lane_vgpr(l, 2, 0) - model.set_lane_vgpr(l, 3, 4) - - model.set_exec(0x1) - model.v_bfe_u32(0, 1, 2, 3) - - leaked_model = SimdWaveBitfieldModel(wave_size=32) - for l in range(32): - leaked_model.set_lane_vgpr(l, 0, 0x2) - - self.assertEqual(model.get_lane_vgpr(5, 0), 0x11111111) - self.assertNotEqual(leaked_model.get_lane_vgpr(5, 0), model.get_lane_vgpr(5, 0)) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_alu_bitop_folding.py b/tests/semantic/test_alu_bitop_folding.py deleted file mode 100644 index ec2e94d49..000000000 --- a/tests/semantic/test_alu_bitop_folding.py +++ /dev/null @@ -1,1219 +0,0 @@ -from __future__ import annotations - -"""Regression and semantic tests for bitwise Boolean algebra and ALU bitop folding. - -Features covered: -- RDNA2 bitwise Boolean logic folding and canonicalization: - - Idempotence: x & x == x, x | x == x. - - Annihilator (dominance): x & 0 == 0, x | 0xFFFFFFFF == 0xFFFFFFFF. - - Identity: x & 0xFFFFFFFF == x, x | 0 == x, x ^ 0 == x. - - Self-inverse: x ^ x == 0. - - Involution: ~(~x) == x. - - Absorption: x | (x & y) == x, x & (x | y) == x. - - Commutativity, associativity, distributivity, De Morgan's laws, and complementarity. -- Instruction interpreter modeling constant folding and canonicalization: - - AST representation of bitwise expressions (ConstExpr, RegExpr, UnaryExpr, BinaryExpr). - - Multi-instruction ALU folding sequences: v_and_b32, v_or_b32, v_xor_b32, v_not_b32. - - Symbolic simplification and concrete register state execution. - - Validation against SPIR-V translation and mini-interpreter execution. -- Multi-lane SIMD divergence under EXEC mask: - - Wavefront (Wave32) vector register execution modeling. - - Inactive lane preservation (lanes with EXEC bit == 0 are strictly preserved). - - Divergent execution masks (all-active, all-inactive, checkerboard, halves, single-lane). - - Multi-instruction ALU execution across divergent lanes. -- Exhaustive truth tables and composite Boolean functions: - - 1-bit full truth tables (AND, OR, XOR, NOT, NAND, NOR, XNOR, ANDN2, ORN2). - - 32-bit sliced independent bit position validation. - - 3-input Boolean functions (majority, multiplexer, parity/xor3). -- Negative controls and fault rejection: - - Non-identities, non-cancellation, non-annihilation. - - Inactive lane isolation negative control. - - Parser and interpreter syntax fault rejection. -- Translator constant folding for shift/bfe/align operands: - - Constant shift count modulo 32 mask elimination. - - Constant v_bfe_u32/i32 offset and width extraction directly to OpBitField[US]Extract. - - Constant v_alignbyte_b32 and v_alignbit_b32 zero/nonzero folding. - - dedupe_types early termination and type substitution. -""" - -import os -import re -import struct -import sys -import tempfile -import unittest -import warnings - -HERE = os.path.dirname(os.path.abspath(__file__)) -ROOT = os.path.dirname(os.path.dirname(HERE)) -TOOLS_DIR = os.environ.get("LEONIDA_TOOLS_DIR") or os.path.join(ROOT, "tools") - -sys.dont_write_bytecode = True -if TOOLS_DIR not in sys.path: - sys.path.insert(0, TOOLS_DIR) -if HERE not in sys.path: - sys.path.insert(0, HERE) - -import rdna2spirv # noqa: E402 -import spirv_mini_interp as si # noqa: E402 -import support # noqa: E402 - -MASK32 = 0xFFFFFFFF -STUB_DXBC = b"DXBC" + bytes(24) + struct.pack(" int: - """Normalize integer to 32-bit unsigned domain.""" - return val & MASK32 - - -def ref_and(a: int, b: int) -> int: - """Plain-Python 32-bit reference for v_and_b32 / s_and_b32.""" - return (a & b) & MASK32 - - -def ref_or(a: int, b: int) -> int: - """Plain-Python 32-bit reference for v_or_b32 / s_or_b32.""" - return (a | b) & MASK32 - - -def ref_xor(a: int, b: int) -> int: - """Plain-Python 32-bit reference for v_xor_b32 / s_xor_b32.""" - return (a ^ b) & MASK32 - - -def ref_not(a: int) -> int: - """Plain-Python 32-bit reference for v_not_b32 / s_not_b32.""" - return (~a) & MASK32 - - -def ref_andn2(a: int, b: int) -> int: - """Plain-Python 32-bit reference for s_andn2_b32 (a & ~b).""" - return (a & (~b & MASK32)) & MASK32 - - -def ref_orn2(a: int, b: int) -> int: - """Plain-Python 32-bit reference for s_orn2_b32 (a | ~b).""" - return (a | (~b & MASK32)) & MASK32 - - -def ref_nand(a: int, b: int) -> int: - """Plain-Python 32-bit reference for s_nand_b32 (~(a & b)).""" - return (~(a & b)) & MASK32 - - -def ref_nor(a: int, b: int) -> int: - """Plain-Python 32-bit reference for s_nor_b32 (~(a | b)).""" - return (~(a | b)) & MASK32 - - -def ref_xnor(a: int, b: int) -> int: - """Plain-Python 32-bit reference for s_xnor_b32 (~(a ^ b)).""" - return (~(a ^ b)) & MASK32 - - -class BitwiseAlgebraOracle: - """Formal mathematical oracle verifying Boolean algebraic identities.""" - - @staticmethod - def check_idempotence_and(x: int) -> bool: - return ref_and(x, x) == ref_u32(x) - - @staticmethod - def check_idempotence_or(x: int) -> bool: - return ref_or(x, x) == ref_u32(x) - - @staticmethod - def check_annihilator_and(x: int) -> bool: - return ref_and(x, 0) == 0 - - @staticmethod - def check_annihilator_or(x: int) -> bool: - return ref_or(x, MASK32) == MASK32 - - @staticmethod - def check_identity_and(x: int) -> bool: - return ref_and(x, MASK32) == ref_u32(x) - - @staticmethod - def check_identity_or(x: int) -> bool: - return ref_or(x, 0) == ref_u32(x) - - @staticmethod - def check_identity_xor(x: int) -> bool: - return ref_xor(x, 0) == ref_u32(x) - - @staticmethod - def check_self_inverse_xor(x: int) -> bool: - return ref_xor(x, x) == 0 - - @staticmethod - def check_involution_not(x: int) -> bool: - return ref_not(ref_not(x)) == ref_u32(x) - - @staticmethod - def check_absorption_or_and(x: int, y: int) -> bool: - return ref_or(x, ref_and(x, y)) == ref_u32(x) - - @staticmethod - def check_absorption_and_or(x: int, y: int) -> bool: - return ref_and(x, ref_or(x, y)) == ref_u32(x) - - @staticmethod - def check_commutativity_and(x: int, y: int) -> bool: - return ref_and(x, y) == ref_and(y, x) - - @staticmethod - def check_commutativity_or(x: int, y: int) -> bool: - return ref_or(x, y) == ref_or(y, x) - - @staticmethod - def check_commutativity_xor(x: int, y: int) -> bool: - return ref_xor(x, y) == ref_xor(y, x) - - @staticmethod - def check_associativity_and(x: int, y: int, z: int) -> bool: - return ref_and(ref_and(x, y), z) == ref_and(x, ref_and(y, z)) - - @staticmethod - def check_associativity_or(x: int, y: int, z: int) -> bool: - return ref_or(ref_or(x, y), z) == ref_or(x, ref_or(y, z)) - - @staticmethod - def check_associativity_xor(x: int, y: int, z: int) -> bool: - return ref_xor(ref_xor(x, y), z) == ref_xor(x, ref_xor(y, z)) - - @staticmethod - def check_distributivity_and_over_or(x: int, y: int, z: int) -> bool: - return ref_and(x, ref_or(y, z)) == ref_or(ref_and(x, y), ref_and(x, z)) - - @staticmethod - def check_distributivity_or_over_and(x: int, y: int, z: int) -> bool: - return ref_or(x, ref_and(y, z)) == ref_and(ref_or(x, y), ref_or(x, z)) - - @staticmethod - def check_demorgan_and(x: int, y: int) -> bool: - return ref_not(ref_and(x, y)) == ref_or(ref_not(x), ref_not(y)) - - @staticmethod - def check_demorgan_or(x: int, y: int) -> bool: - return ref_not(ref_or(x, y)) == ref_and(ref_not(x), ref_not(y)) - - @staticmethod - def check_complement_and(x: int) -> bool: - return ref_and(x, ref_not(x)) == 0 - - @staticmethod - def check_complement_or(x: int) -> bool: - return ref_or(x, ref_not(x)) == MASK32 - - @staticmethod - def check_complement_xor(x: int) -> bool: - return ref_xor(x, ref_not(x)) == MASK32 - - -class Expr: - """Base expression node for bitwise ALU symbolic representation.""" - - def eval(self, env: dict[str, int]) -> int: - raise NotImplementedError - - def fold(self) -> Expr: - raise NotImplementedError - - -class ConstExpr(Expr): - """32-bit constant literal.""" - - def __init__(self, val: int) -> None: - self.val = ref_u32(val) - - def eval(self, env: dict[str, int]) -> int: - return self.val - - def fold(self) -> Expr: - return self - - def __eq__(self, other: object) -> bool: - return isinstance(other, ConstExpr) and self.val == other.val - - def __hash__(self) -> int: - return hash(("const", self.val)) - - def __repr__(self) -> str: - return f"Const(0x{self.val:08X})" - - -class RegExpr(Expr): - """Register variable operand.""" - - def __init__(self, name: str) -> None: - self.name = name.lower() - - def eval(self, env: dict[str, int]) -> int: - return ref_u32(env.get(self.name, 0)) - - def fold(self) -> Expr: - return self - - def __eq__(self, other: object) -> bool: - return isinstance(other, RegExpr) and self.name == other.name - - def __hash__(self) -> int: - return hash(("reg", self.name)) - - def __repr__(self) -> str: - return f"Reg({self.name})" - - -class UnaryExpr(Expr): - """Unary bitwise operation (v_not_b32 / s_not_b32).""" - - def __init__(self, op: str, operand: Expr) -> None: - self.op = op - self.operand = operand - - def eval(self, env: dict[str, int]) -> int: - val = self.operand.eval(env) - if self.op in ("v_not_b32", "s_not_b32", "not"): - return ref_not(val) - raise ValueError(f"Unknown unary op {self.op}") - - def fold(self) -> Expr: - sub = self.operand.fold() - if isinstance(sub, ConstExpr): - return ConstExpr(ref_not(sub.val)) - if isinstance(sub, UnaryExpr) and sub.op in ("v_not_b32", "s_not_b32", "not"): - return sub.operand.fold() - return UnaryExpr(self.op, sub) - - def __eq__(self, other: object) -> bool: - return isinstance(other, UnaryExpr) and self.op == other.op and self.operand == other.operand - - def __hash__(self) -> int: - return hash(("unary", self.op, self.operand)) - - def __repr__(self) -> str: - return f"Unary({self.op}, {self.operand})" - - -class BinaryExpr(Expr): - """Binary bitwise operation (v_and_b32, v_or_b32, v_xor_b32).""" - - def __init__(self, op: str, lhs: Expr, rhs: Expr) -> None: - self.op = op - self.lhs = lhs - self.rhs = rhs - - def eval(self, env: dict[str, int]) -> int: - l = self.lhs.eval(env) - r = self.rhs.eval(env) - if self.op in ("v_and_b32", "s_and_b32", "and"): - return ref_and(l, r) - elif self.op in ("v_or_b32", "s_or_b32", "or"): - return ref_or(l, r) - elif self.op in ("v_xor_b32", "s_xor_b32", "xor"): - return ref_xor(l, r) - raise ValueError(f"Unknown binary op {self.op}") - - def fold(self) -> Expr: - l = self.lhs.fold() - r = self.rhs.fold() - op = self.op - - if isinstance(l, ConstExpr) and isinstance(r, ConstExpr): - if op in ("v_and_b32", "s_and_b32", "and"): - return ConstExpr(ref_and(l.val, r.val)) - elif op in ("v_or_b32", "s_or_b32", "or"): - return ConstExpr(ref_or(l.val, r.val)) - elif op in ("v_xor_b32", "s_xor_b32", "xor"): - return ConstExpr(ref_xor(l.val, r.val)) - - if isinstance(l, ConstExpr) and not isinstance(r, ConstExpr): - l, r = r, l - elif not isinstance(l, ConstExpr) and not isinstance(r, ConstExpr): - if repr(l) > repr(r): - l, r = r, l - - if op in ("v_and_b32", "s_and_b32", "and"): - if l == r: - return l - if isinstance(r, ConstExpr) and r.val == 0: - return ConstExpr(0) - if isinstance(r, ConstExpr) and r.val == MASK32: - return l - if (isinstance(r, UnaryExpr) and r.operand == l) or (isinstance(l, UnaryExpr) and l.operand == r): - return ConstExpr(0) - if isinstance(r, BinaryExpr) and r.op in ("v_or_b32", "s_or_b32", "or"): - if r.lhs == l or r.rhs == l: - return l - if isinstance(l, BinaryExpr) and l.op in ("v_or_b32", "s_or_b32", "or"): - if l.lhs == r or l.rhs == r: - return r - - elif op in ("v_or_b32", "s_or_b32", "or"): - if l == r: - return l - if isinstance(r, ConstExpr) and r.val == MASK32: - return ConstExpr(MASK32) - if isinstance(r, ConstExpr) and r.val == 0: - return l - if (isinstance(r, UnaryExpr) and r.operand == l) or (isinstance(l, UnaryExpr) and l.operand == r): - return ConstExpr(MASK32) - if isinstance(r, BinaryExpr) and r.op in ("v_and_b32", "s_and_b32", "and"): - if r.lhs == l or r.rhs == l: - return l - if isinstance(l, BinaryExpr) and l.op in ("v_and_b32", "s_and_b32", "and"): - if l.lhs == r or l.rhs == r: - return r - - elif op in ("v_xor_b32", "s_xor_b32", "xor"): - if l == r: - return ConstExpr(0) - if isinstance(r, ConstExpr) and r.val == 0: - return l - if isinstance(r, ConstExpr) and r.val == MASK32: - return UnaryExpr("v_not_b32", l).fold() - if (isinstance(r, UnaryExpr) and r.operand == l) or (isinstance(l, UnaryExpr) and l.operand == r): - return ConstExpr(MASK32) - - return BinaryExpr(op, l, r) - - def __eq__(self, other: object) -> bool: - return isinstance(other, BinaryExpr) and self.op == other.op and self.lhs == other.lhs and self.rhs == other.rhs - - def __hash__(self) -> int: - return hash(("binary", self.op, self.lhs, self.rhs)) - - def __repr__(self) -> str: - return f"Binary({self.op}, {self.lhs}, {self.rhs})" - - -class BitopFoldingInterpreter: - """RDNA2 instruction interpreter tracking registers, expressions, and folding.""" - - def __init__(self) -> None: - self.regs: dict[str, int] = {} - self.exprs: dict[str, Expr] = {} - - def set_reg(self, reg: str, val: int) -> None: - r = reg.lower().strip() - v = ref_u32(val) - self.regs[r] = v - self.exprs[r] = ConstExpr(v) - - def set_reg_symbolic(self, reg: str, name: str) -> None: - r = reg.lower().strip() - self.exprs[r] = RegExpr(name) - - def get_reg(self, reg: str) -> int: - return self.regs.get(reg.lower().strip(), 0) - - def get_expr(self, reg: str) -> Expr: - r = reg.lower().strip() - return self.exprs.get(r, RegExpr(r)) - - def _parse_operand(self, token: str) -> tuple[int, Expr]: - token = token.strip() - try: - val = int(token, 0) - u = ref_u32(val) - return u, ConstExpr(u) - except ValueError: - pass - reg = token.lower() - val = self.regs.get(reg, 0) - expr = self.exprs.get(reg, RegExpr(reg)) - return val, expr - - def execute_instruction(self, line: str) -> tuple[str, int, Expr]: - line = line.strip() - if not line or line.startswith(";") or line.startswith("//"): - return ("", 0, ConstExpr(0)) - parts = line.split(None, 1) - raw_op = parts[0].lower() - op = raw_op.replace("_e32", "").replace("_e64", "") - operands = [p.strip() for p in parts[1].split(",")] if len(parts) > 1 else [] - - if op in ("v_mov_b32", "s_mov_b32"): - if len(operands) < 2: - raise ValueError(f"Missing operands in {line}") - dst = operands[0].lower() - val, expr = self._parse_operand(operands[1]) - self.regs[dst] = val - folded = expr.fold() - self.exprs[dst] = folded - return (dst, val, folded) - - elif op in ("v_not_b32", "s_not_b32"): - if len(operands) < 2: - raise ValueError(f"Missing operands in {line}") - dst = operands[0].lower() - val, expr = self._parse_operand(operands[1]) - res = ref_not(val) - self.regs[dst] = res - folded = UnaryExpr("v_not_b32", expr).fold() - self.exprs[dst] = folded - return (dst, res, folded) - - elif op in ("v_and_b32", "s_and_b32", "v_or_b32", "s_or_b32", "v_xor_b32", "s_xor_b32"): - if len(operands) < 3: - raise ValueError(f"Missing operands in {line}") - dst = operands[0].lower() - v0, e0 = self._parse_operand(operands[1]) - v1, e1 = self._parse_operand(operands[2]) - if op in ("v_and_b32", "s_and_b32"): - res = ref_and(v0, v1) - elif op in ("v_or_b32", "s_or_b32"): - res = ref_or(v0, v1) - elif op in ("v_xor_b32", "s_xor_b32"): - res = ref_xor(v0, v1) - else: - raise ValueError(f"Unknown binary op {op}") - self.regs[dst] = res - folded = BinaryExpr(op, e0, e1).fold() - self.exprs[dst] = folded - return (dst, res, folded) - - else: - raise ValueError(f"Unsupported instruction: {line}") - - def execute_sequence(self, lines: list[str]) -> None: - for line in lines: - line = line.strip() - if line: - self.execute_instruction(line) - - -class SimdWaveInterpreter: - """Wave32 SIMD vector interpreter modeling 32 lanes under an EXEC mask.""" - - def __init__(self, num_lanes: int = 32, num_vgprs: int = 64) -> None: - self.num_lanes = num_lanes - self.num_vgprs = num_vgprs - self.vgprs: list[list[int]] = [[0] * num_lanes for _ in range(num_vgprs)] - self.exec_mask: int = (1 << num_lanes) - 1 - - def set_exec(self, mask: int) -> None: - self.exec_mask = mask & ((1 << self.num_lanes) - 1) - - def get_exec(self) -> int: - return self.exec_mask - - def set_vgpr_lane(self, v_idx: int, lane: int, val: int) -> None: - self.vgprs[v_idx][lane] = ref_u32(val) - - def set_vgpr_all_lanes(self, v_idx: int, values: list[int]) -> None: - assert len(values) == self.num_lanes - self.vgprs[v_idx] = [ref_u32(v) for v in values] - - def set_vgpr_broadcast(self, v_idx: int, val: int) -> None: - u = ref_u32(val) - self.vgprs[v_idx] = [u] * self.num_lanes - - def get_vgpr_lane(self, v_idx: int, lane: int) -> int: - return self.vgprs[v_idx][lane] - - def get_vgpr_all_lanes(self, v_idx: int) -> list[int]: - return list(self.vgprs[v_idx]) - - def _resolve_lane_val(self, operand: str, lane: int) -> int: - tok = operand.strip() - try: - return ref_u32(int(tok, 0)) - except ValueError: - pass - if tok.lower().startswith("v"): - v_idx = int(tok[1:]) - return self.vgprs[v_idx][lane] - raise ValueError(f"Invalid operand token: {tok}") - - def execute_vector_instruction(self, line: str) -> None: - line = line.strip() - if not line or line.startswith(";") or line.startswith("//"): - return - parts = line.split(None, 1) - raw_op = parts[0].lower() - op = raw_op.replace("_e32", "").replace("_e64", "") - operands = [p.strip() for p in parts[1].split(",")] if len(parts) > 1 else [] - - if not operands: - raise ValueError(f"No operands in instruction: {line}") - - dst_tok = operands[0].lower() - if not dst_tok.startswith("v"): - raise ValueError(f"Vector destination must be VGPR (e.g. v0): {dst_tok}") - dst_idx = int(dst_tok[1:]) - - if op in ("v_mov_b32", "s_mov_b32"): - if len(operands) < 2: - raise ValueError(f"Missing source operand in {line}") - for lane in range(self.num_lanes): - if self.exec_mask & (1 << lane): - val = self._resolve_lane_val(operands[1], lane) - self.vgprs[dst_idx][lane] = val - - elif op in ("v_not_b32", "s_not_b32"): - if len(operands) < 2: - raise ValueError(f"Missing source operand in {line}") - for lane in range(self.num_lanes): - if self.exec_mask & (1 << lane): - val = self._resolve_lane_val(operands[1], lane) - self.vgprs[dst_idx][lane] = ref_not(val) - - elif op in ("v_and_b32", "s_and_b32", "v_or_b32", "s_or_b32", "v_xor_b32", "s_xor_b32"): - if len(operands) < 3: - raise ValueError(f"Missing binary operands in {line}") - for lane in range(self.num_lanes): - if self.exec_mask & (1 << lane): - v0 = self._resolve_lane_val(operands[1], lane) - v1 = self._resolve_lane_val(operands[2], lane) - if op in ("v_and_b32", "s_and_b32"): - res = ref_and(v0, v1) - elif op in ("v_or_b32", "s_or_b32"): - res = ref_or(v0, v1) - elif op in ("v_xor_b32", "s_xor_b32"): - res = ref_xor(v0, v1) - self.vgprs[dst_idx][lane] = res - - else: - raise ValueError(f"Unsupported SIMD instruction: {line}") - - def execute_sequence(self, lines: list[str]) -> None: - for line in lines: - self.execute_vector_instruction(line) - - -class BitwiseAlgebraOracleTests(unittest.TestCase): - """Test suite executing the reference oracle against exhaustive vector sets.""" - - def test_idempotence(self): - for vec in CANONICAL_TEST_VECTORS + SINGLE_BIT_SET + SINGLE_BIT_CLR: - with self.subTest(vec=hex(vec)): - self.assertTrue(BitwiseAlgebraOracle.check_idempotence_and(vec)) - self.assertTrue(BitwiseAlgebraOracle.check_idempotence_or(vec)) - - def test_annihilator(self): - for vec in CANONICAL_TEST_VECTORS + SINGLE_BIT_SET + SINGLE_BIT_CLR: - with self.subTest(vec=hex(vec)): - self.assertTrue(BitwiseAlgebraOracle.check_annihilator_and(vec)) - self.assertTrue(BitwiseAlgebraOracle.check_annihilator_or(vec)) - - def test_identity(self): - for vec in CANONICAL_TEST_VECTORS + SINGLE_BIT_SET + SINGLE_BIT_CLR: - with self.subTest(vec=hex(vec)): - self.assertTrue(BitwiseAlgebraOracle.check_identity_and(vec)) - self.assertTrue(BitwiseAlgebraOracle.check_identity_or(vec)) - self.assertTrue(BitwiseAlgebraOracle.check_identity_xor(vec)) - - def test_self_inverse(self): - for vec in CANONICAL_TEST_VECTORS + SINGLE_BIT_SET + SINGLE_BIT_CLR: - with self.subTest(vec=hex(vec)): - self.assertTrue(BitwiseAlgebraOracle.check_self_inverse_xor(vec)) - - def test_involution(self): - for vec in CANONICAL_TEST_VECTORS + SINGLE_BIT_SET + SINGLE_BIT_CLR: - with self.subTest(vec=hex(vec)): - self.assertTrue(BitwiseAlgebraOracle.check_involution_not(vec)) - - def test_absorption(self): - vectors = CANONICAL_TEST_VECTORS[:12] - for x in vectors: - for y in vectors: - with self.subTest(x=hex(x), y=hex(y)): - self.assertTrue(BitwiseAlgebraOracle.check_absorption_or_and(x, y)) - self.assertTrue(BitwiseAlgebraOracle.check_absorption_and_or(x, y)) - - def test_commutativity(self): - vectors = CANONICAL_TEST_VECTORS[:10] - for x in vectors: - for y in vectors: - with self.subTest(x=hex(x), y=hex(y)): - self.assertTrue(BitwiseAlgebraOracle.check_commutativity_and(x, y)) - self.assertTrue(BitwiseAlgebraOracle.check_commutativity_or(x, y)) - self.assertTrue(BitwiseAlgebraOracle.check_commutativity_xor(x, y)) - - def test_associativity(self): - vectors = [0x0, 0xFFFFFFFF, 0x55555555, 0xAAAAAAAA, 0x12345678, 0x80000000] - for x in vectors: - for y in vectors: - for z in vectors: - with self.subTest(x=hex(x), y=hex(y), z=hex(z)): - self.assertTrue(BitwiseAlgebraOracle.check_associativity_and(x, y, z)) - self.assertTrue(BitwiseAlgebraOracle.check_associativity_or(x, y, z)) - self.assertTrue(BitwiseAlgebraOracle.check_associativity_xor(x, y, z)) - - def test_distributivity(self): - vectors = [0x0, 0xFFFFFFFF, 0x55555555, 0xAAAAAAAA, 0x12345678, 0x80000000] - for x in vectors: - for y in vectors: - for z in vectors: - with self.subTest(x=hex(x), y=hex(y), z=hex(z)): - self.assertTrue(BitwiseAlgebraOracle.check_distributivity_and_over_or(x, y, z)) - self.assertTrue(BitwiseAlgebraOracle.check_distributivity_or_over_and(x, y, z)) - - def test_demorgan_laws(self): - vectors = CANONICAL_TEST_VECTORS[:12] - for x in vectors: - for y in vectors: - with self.subTest(x=hex(x), y=hex(y)): - self.assertTrue(BitwiseAlgebraOracle.check_demorgan_and(x, y)) - self.assertTrue(BitwiseAlgebraOracle.check_demorgan_or(x, y)) - - def test_complementarity(self): - for vec in CANONICAL_TEST_VECTORS + SINGLE_BIT_SET + SINGLE_BIT_CLR: - with self.subTest(vec=hex(vec)): - self.assertTrue(BitwiseAlgebraOracle.check_complement_and(vec)) - self.assertTrue(BitwiseAlgebraOracle.check_complement_or(vec)) - self.assertTrue(BitwiseAlgebraOracle.check_complement_xor(vec)) - - def test_composite_folding_identities(self): - vectors = CANONICAL_TEST_VECTORS[:12] - for x in vectors: - self.assertEqual(ref_xor(x, MASK32), ref_not(x)) - for y in vectors: - lhs1 = ref_and(ref_or(x, y), ref_or(x, ref_not(y))) - self.assertEqual(lhs1, ref_u32(x)) - lhs2 = ref_or(ref_and(x, y), ref_and(x, ref_not(y))) - self.assertEqual(lhs2, ref_u32(x)) - lhs3 = ref_xor(x, ref_and(x, y)) - self.assertEqual(lhs3, ref_andn2(x, y)) - - -class BitopFoldingInterpreterTests(unittest.TestCase): - """Test suite verifying instruction interpreter constant folding and sequences.""" - - def test_constant_folding_basic(self): - interp = BitopFoldingInterpreter() - interp.execute_sequence([ - "v_mov_b32 v0, 0x12345678", - "v_mov_b32 v1, 0x0000FFFF", - "v_and_b32 v2, v0, v1", - "v_or_b32 v3, v0, v1", - "v_xor_b32 v4, v0, v1", - "v_not_b32 v5, v0", - ]) - self.assertEqual(interp.get_reg("v2"), 0x00005678) - self.assertEqual(interp.get_expr("v2"), ConstExpr(0x00005678)) - self.assertEqual(interp.get_reg("v3"), 0x1234FFFF) - self.assertEqual(interp.get_expr("v3"), ConstExpr(0x1234FFFF)) - self.assertEqual(interp.get_reg("v4"), 0x1234A987) - self.assertEqual(interp.get_expr("v4"), ConstExpr(0x1234A987)) - self.assertEqual(interp.get_reg("v5"), 0xEDCBA987) - self.assertEqual(interp.get_expr("v5"), ConstExpr(0xEDCBA987)) - - def test_idempotence_folding(self): - interp = BitopFoldingInterpreter() - interp.set_reg_symbolic("v0", "v0") - interp.execute_instruction("v_and_b32 v1, v0, v0") - self.assertEqual(interp.get_expr("v1"), RegExpr("v0")) - - interp.execute_instruction("v_or_b32 v2, v0, v0") - self.assertEqual(interp.get_expr("v2"), RegExpr("v0")) - - def test_annihilator_folding(self): - interp = BitopFoldingInterpreter() - interp.set_reg_symbolic("v0", "v0") - interp.execute_instruction("v_and_b32 v1, v0, 0") - self.assertEqual(interp.get_expr("v1"), ConstExpr(0)) - interp.execute_instruction("v_and_b32 v2, 0, v0") - self.assertEqual(interp.get_expr("v2"), ConstExpr(0)) - - interp.execute_instruction("v_or_b32 v3, v0, 0xFFFFFFFF") - self.assertEqual(interp.get_expr("v3"), ConstExpr(MASK32)) - interp.execute_instruction("v_or_b32 v4, 0xFFFFFFFF, v0") - self.assertEqual(interp.get_expr("v4"), ConstExpr(MASK32)) - - def test_identity_folding(self): - interp = BitopFoldingInterpreter() - interp.set_reg_symbolic("v0", "v0") - interp.execute_instruction("v_and_b32 v1, v0, 0xFFFFFFFF") - self.assertEqual(interp.get_expr("v1"), RegExpr("v0")) - interp.execute_instruction("v_and_b32 v2, 0xFFFFFFFF, v0") - self.assertEqual(interp.get_expr("v2"), RegExpr("v0")) - - interp.execute_instruction("v_or_b32 v3, v0, 0") - self.assertEqual(interp.get_expr("v3"), RegExpr("v0")) - interp.execute_instruction("v_or_b32 v4, 0, v0") - self.assertEqual(interp.get_expr("v4"), RegExpr("v0")) - - interp.execute_instruction("v_xor_b32 v5, v0, 0") - self.assertEqual(interp.get_expr("v5"), RegExpr("v0")) - interp.execute_instruction("v_xor_b32 v6, 0, v0") - self.assertEqual(interp.get_expr("v6"), RegExpr("v0")) - - def test_self_inverse_folding(self): - interp = BitopFoldingInterpreter() - interp.set_reg_symbolic("v0", "v0") - interp.execute_instruction("v_xor_b32 v1, v0, v0") - self.assertEqual(interp.get_expr("v1"), ConstExpr(0)) - - def test_involution_folding(self): - interp = BitopFoldingInterpreter() - interp.set_reg_symbolic("v0", "v0") - interp.execute_sequence([ - "v_not_b32 v1, v0", - "v_not_b32 v2, v1", - "v_not_b32 v3, v2", - ]) - self.assertEqual(interp.get_expr("v2"), RegExpr("v0")) - self.assertEqual(interp.get_expr("v3"), UnaryExpr("v_not_b32", RegExpr("v0"))) - - def test_absorption_folding(self): - interp = BitopFoldingInterpreter() - interp.set_reg_symbolic("v0", "v0") - interp.set_reg_symbolic("v1", "v1") - interp.execute_sequence([ - "v_and_b32 v2, v0, v1", - "v_or_b32 v3, v0, v2", - "v_or_b32 v4, v0, v1", - "v_and_b32 v5, v0, v4", - ]) - self.assertEqual(interp.get_expr("v3"), RegExpr("v0")) - self.assertEqual(interp.get_expr("v5"), RegExpr("v0")) - - def test_self_complement_folding(self): - interp = BitopFoldingInterpreter() - interp.set_reg_symbolic("v0", "v0") - interp.execute_sequence([ - "v_not_b32 v1, v0", - "v_and_b32 v2, v0, v1", - "v_or_b32 v3, v0, v1", - "v_xor_b32 v4, v0, v1", - ]) - self.assertEqual(interp.get_expr("v2"), ConstExpr(0)) - self.assertEqual(interp.get_expr("v3"), ConstExpr(MASK32)) - self.assertEqual(interp.get_expr("v4"), ConstExpr(MASK32)) - - def test_multi_instruction_alu_sequences(self): - interp = BitopFoldingInterpreter() - interp.set_reg("v0", 0x12345678) - interp.set_reg("v1", 0x9ABCDEF0) - interp.execute_sequence([ - "v_and_b32 v2, v0, v1", - "v_or_b32 v3, v0, v2", - "v_xor_b32 v4, v3, v0", - "v_or_b32 v5, v4, 0x55555555", - "v_and_b32 v6, v5, 0xFFFFFFFF", - ]) - self.assertEqual(interp.get_reg("v3"), 0x12345678) - self.assertEqual(interp.get_reg("v4"), 0) - self.assertEqual(interp.get_reg("v5"), 0x55555555) - self.assertEqual(interp.get_reg("v6"), 0x55555555) - self.assertEqual(interp.get_expr("v6"), ConstExpr(0x55555555)) - - def test_translator_spirv_lowering_equivalence(self): - lines = [ - "v_mov_b32 v1, 0x12345678", - "v_mov_b32 v2, 0x9ABCDEF0", - "v_and_b32 v3, v1, v2", - "v_or_b32 v4, v1, v3", - "v_xor_b32 v0, v4, v1", - ] - body = "\n".join("\t" + line for line in lines) - asm = f"; alu_lowering_test\n{body}\n\texp mrt0 v0, v3, v4, v1 done vm\n\ts_endpgm\n" - with tempfile.TemporaryDirectory() as tmp: - d_dir = os.path.join(tmp, "disasm") - os.mkdir(d_dir) - s_path = os.path.join(d_dir, "ps_bitop_eval.s") - with open(s_path, "w", encoding="utf-8") as f: - f.write(asm) - with open(os.path.join(tmp, "ps_bitop_eval.dxbc"), "wb") as f: - f.write(STUB_DXBC) - with warnings.catch_warnings(): - warnings.simplefilter("ignore", ResourceWarning) - spv = rdna2spirv.translate(s_path) - out = si.run_fragment(spv)["%out_mrt0"] - self.assertEqual(out[0], 0) - self.assertEqual(out[1], ref_and(0x12345678, 0x9ABCDEF0)) - self.assertEqual(out[2], 0x12345678) - self.assertEqual(out[3], 0x12345678) - - -class SimdWaveDivergenceTests(unittest.TestCase): - """Test suite verifying multi-lane SIMD divergence under various EXEC masks.""" - - def test_simd_all_active_exec(self): - simd = SimdWaveInterpreter() - simd.set_exec(0xFFFFFFFF) - for lane in range(32): - simd.set_vgpr_lane(1, lane, 0x1000 + lane) - simd.set_vgpr_lane(2, lane, 0x00FF) - simd.execute_vector_instruction("v_and_b32 v0, v1, v2") - for lane in range(32): - self.assertEqual(simd.get_vgpr_lane(0, lane), (0x1000 + lane) & 0x00FF) - - def test_simd_all_inactive_exec(self): - simd = SimdWaveInterpreter() - simd.set_exec(0x00000000) - simd.set_vgpr_broadcast(0, 0xCAFEBABE) - simd.set_vgpr_broadcast(1, 0x12345678) - simd.execute_vector_instruction("v_mov_b32 v0, v1") - for lane in range(32): - self.assertEqual(simd.get_vgpr_lane(0, lane), 0xCAFEBABE) - - def test_simd_checkerboard_divergence(self): - simd = SimdWaveInterpreter() - simd.set_exec(0x55555555) # Even lanes active, odd lanes inactive - simd.set_vgpr_broadcast(0, 0xDEADBEEF) - for lane in range(32): - simd.set_vgpr_lane(1, lane, 0xAA00 + lane) - simd.execute_vector_instruction("v_mov_b32 v0, v1") - for lane in range(32): - if lane % 2 == 0: - self.assertEqual(simd.get_vgpr_lane(0, lane), 0xAA00 + lane) - else: - self.assertEqual(simd.get_vgpr_lane(0, lane), 0xDEADBEEF) - - def test_simd_halves_divergence(self): - simd = SimdWaveInterpreter() - simd.set_exec(0x0000FFFF) # Lower 16 lanes active, upper 16 inactive - simd.set_vgpr_broadcast(0, 0x77777777) - simd.set_vgpr_broadcast(1, 0x11111111) - simd.set_vgpr_broadcast(2, 0x22222222) - simd.execute_vector_instruction("v_or_b32 v0, v1, v2") - for lane in range(32): - if lane < 16: - self.assertEqual(simd.get_vgpr_lane(0, lane), 0x33333333) - else: - self.assertEqual(simd.get_vgpr_lane(0, lane), 0x77777777) - - def test_simd_single_lane_divergence(self): - for target_lane in (0, 7, 15, 31): - with self.subTest(lane=target_lane): - simd = SimdWaveInterpreter() - simd.set_exec(1 << target_lane) - simd.set_vgpr_broadcast(0, 0) - simd.set_vgpr_broadcast(1, 0xFFFFFFFF) - simd.execute_vector_instruction("v_mov_b32 v0, v1") - for lane in range(32): - if lane == target_lane: - self.assertEqual(simd.get_vgpr_lane(0, lane), 0xFFFFFFFF) - else: - self.assertEqual(simd.get_vgpr_lane(0, lane), 0) - - def test_simd_divergent_folding_inactive_isolation(self): - # Even when constant folding simplifies an instruction (e.g. x & 0 -> 0), - # inactive lanes must strictly retain their previous destination value. - simd = SimdWaveInterpreter() - simd.set_exec(0x00FF00FF) - simd.set_vgpr_broadcast(0, 0x12345678) - simd.set_vgpr_broadcast(1, 0x9ABCDEF0) - simd.execute_vector_instruction("v_and_b32 v0, v1, 0") - for lane in range(32): - if (0x00FF00FF & (1 << lane)) != 0: - self.assertEqual(simd.get_vgpr_lane(0, lane), 0) - else: - self.assertEqual(simd.get_vgpr_lane(0, lane), 0x12345678) - - def test_simd_multi_instruction_divergence(self): - simd = SimdWaveInterpreter() - # Step 1: execute on lower half - simd.set_exec(0x0000FFFF) - for lane in range(32): - simd.set_vgpr_lane(0, lane, 0x0) - simd.set_vgpr_lane(1, lane, lane) - simd.set_vgpr_lane(2, lane, 0x10) - simd.execute_vector_instruction("v_xor_b32 v0, v1, v2") - - # Step 2: execute on upper half with complementary operation - simd.set_exec(0xFFFF0000) - simd.execute_vector_instruction("v_not_b32 v0, v1") - - for lane in range(32): - if lane < 16: - self.assertEqual(simd.get_vgpr_lane(0, lane), lane ^ 0x10) - else: - self.assertEqual(simd.get_vgpr_lane(0, lane), ref_not(lane)) - - -class BitwiseTruthTableTests(unittest.TestCase): - """Test suite validating full Boolean truth tables and composite logic.""" - - def test_1bit_truth_tables(self): - table = [ - (0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 1), - (0, 1, 0, 1, 1, 1, 1, 0, 0, 0, 0), - (1, 0, 0, 1, 1, 0, 1, 0, 0, 1, 1), - (1, 1, 1, 1, 0, 0, 0, 0, 1, 0, 1), - ] - for a, b, exp_and, exp_or, exp_xor, exp_not_a, exp_nand, exp_nor, exp_xnor, exp_andn2, exp_orn2 in table: - with self.subTest(a=a, b=b): - self.assertEqual(ref_and(a, b), exp_and) - self.assertEqual(ref_or(a, b), exp_or) - self.assertEqual(ref_xor(a, b), exp_xor) - self.assertEqual(ref_not(a) & 1, exp_not_a) - self.assertEqual(ref_nand(a, b) & 1, exp_nand) - self.assertEqual(ref_nor(a, b) & 1, exp_nor) - self.assertEqual(ref_xnor(a, b) & 1, exp_xnor) - self.assertEqual(ref_andn2(a, b), exp_andn2) - self.assertEqual(ref_orn2(a, b) & 1, exp_orn2) - - def test_32bit_sliced_truth_tables(self): - for bit in range(32): - m = 1 << bit - with self.subTest(bit=bit): - # (0, 0) - self.assertEqual(ref_and(0, 0) & m, 0) - self.assertEqual(ref_or(0, 0) & m, 0) - self.assertEqual(ref_xor(0, 0) & m, 0) - # (m, 0) - self.assertEqual(ref_and(m, 0) & m, 0) - self.assertEqual(ref_or(m, 0) & m, m) - self.assertEqual(ref_xor(m, 0) & m, m) - # (0, m) - self.assertEqual(ref_and(0, m) & m, 0) - self.assertEqual(ref_or(0, m) & m, m) - self.assertEqual(ref_xor(0, m) & m, m) - # (m, m) - self.assertEqual(ref_and(m, m) & m, m) - self.assertEqual(ref_or(m, m) & m, m) - self.assertEqual(ref_xor(m, m) & m, 0) - - def test_3input_boolean_functions(self): - # Majority: maj(a, b, c) = (a & b) | (b & c) | (a & c) - def maj(a: int, b: int, c: int) -> int: - return ref_or(ref_or(ref_and(a, b), ref_and(b, c)), ref_and(a, c)) - - # Multiplexer: mux(sel, a, b) = (sel & a) | (~sel & b) - def mux(sel: int, a: int, b: int) -> int: - return ref_or(ref_and(sel, a), ref_and(ref_not(sel), b)) - - # Parity: parity(a, b, c) = a ^ b ^ c - def parity(a: int, b: int, c: int) -> int: - return ref_xor(ref_xor(a, b), c) - - for a in (0, 1): - for b in (0, 1): - for c in (0, 1): - # Majority is 1 if at least two inputs are 1 - exp_maj = 1 if (a + b + c) >= 2 else 0 - self.assertEqual(maj(a, b, c), exp_maj) - - # Parity is odd parity - exp_parity = (a ^ b ^ c) & 1 - self.assertEqual(parity(a, b, c), exp_parity) - - # Mux test across 32-bit words - for sel in (0x00000000, 0xFFFFFFFF, 0x55555555, 0x0000FFFF): - x = 0x12345678 - y = 0x9ABCDEF0 - res = mux(sel, x, y) - for bit in range(32): - expected_bit = (x if (sel & (1 << bit)) else y) & (1 << bit) - self.assertEqual(res & (1 << bit), expected_bit) - - -class BitwiseNegativeControlTests(unittest.TestCase): - """Test suite validating negative controls, non-identities, and fault rejection.""" - - def test_non_identities(self): - # x & y != x in general when x has bits not in y - x = 0x12345678 - y = 0x0000FFFF - self.assertNotEqual(ref_and(x, y), x) - - # x | y != x when y has bits not in x - x = 0x0000FFFF - y = 0x12345678 - self.assertNotEqual(ref_or(x, y), x) - - def test_non_cancellation(self): - # x ^ y != 0 when x != y - for i in range(len(CANONICAL_TEST_VECTORS) - 1): - x = CANONICAL_TEST_VECTORS[i] - y = CANONICAL_TEST_VECTORS[i + 1] - if x != y: - self.assertNotEqual(ref_xor(x, y), 0) - - def test_non_annihilation(self): - # x & c != 0 when x and c share set bits - x = 0x55555555 - c = 0x11111111 - self.assertNotEqual(ref_and(x, c), 0) - - def test_inactive_lane_isolation(self): - simd = SimdWaveInterpreter() - simd.set_exec(0x00000001) # Only lane 0 active - simd.set_vgpr_broadcast(0, 0xAAAAAAAAAAAAAAAA) - simd.set_vgpr_broadcast(1, 0x55555555) - simd.execute_vector_instruction("v_mov_b32 v0, v1") - # Lane 0 changed to 0x55555555 - self.assertEqual(simd.get_vgpr_lane(0, 0), 0x55555555) - # Lanes 1..31 must NOT have changed - for lane in range(1, 32): - self.assertNotEqual(simd.get_vgpr_lane(0, lane), 0x55555555) - self.assertEqual(simd.get_vgpr_lane(0, lane), 0xAAAAAAAA) - - def test_parser_fault_rejection(self): - interp = BitopFoldingInterpreter() - with self.assertRaises(ValueError): - interp.execute_instruction("v_invalid_opcode_b32 v0, v1, v2") - with self.assertRaises(ValueError): - interp.execute_instruction("v_and_b32 v0") - - simd = SimdWaveInterpreter() - with self.assertRaises(ValueError): - simd.execute_vector_instruction("v_unknown_op v0, v1") - with self.assertRaises(ValueError): - simd.execute_vector_instruction("v_and_b32 s0, v1, v2") - - -class BitopConstantFoldingTests(unittest.TestCase): - def translate_lines(self, lines: list[str]) -> str: - body = "\n".join("\t" + line for line in lines) - asm = f"; bitop_test\n{body}\n\texp mrt0 v0, v0, v0, v0 done vm\n\ts_endpgm\n" - with tempfile.TemporaryDirectory() as tmp: - d_dir = os.path.join(tmp, "disasm") - os.mkdir(d_dir) - s_path = os.path.join(d_dir, "ps_bitop.s") - with open(s_path, "w", encoding="utf-8") as f: - f.write(asm) - with open(os.path.join(tmp, "ps_bitop.dxbc"), "wb") as f: - f.write(STUB_DXBC) - with warnings.catch_warnings(): - warnings.simplefilter("ignore", ResourceWarning) - return rdna2spirv.translate(s_path) - - def test_constant_shift_eliminates_runtime_mask(self): - lines = [ - "v_mov_b32 v1, 0x1234", - "v_lshlrev_b32 v0, 4, v1", - ] - spv = self.translate_lines(lines) - self.assertNotIn("OpBitwiseAnd %uint", spv) - self.assertIn("OpShiftLeftLogical %uint", spv) - res = si.run_fragment(spv)["%out_mrt0"][0] - self.assertEqual(res, 0x12340) - - def test_constant_bfe_eliminates_runtime_bounds(self): - lines = [ - "v_mov_b32 v1, 0x12345678", - "v_bfe_u32 v0, v1, 8, 12", - ] - spv = self.translate_lines(lines) - self.assertNotIn("OpBitwiseAnd %uint", spv) - self.assertNotIn("OpISub %uint", spv) - self.assertNotIn("OpULessThan %bool", spv) - self.assertIn("OpBitFieldUExtract %uint", spv) - res = si.run_fragment(spv)["%out_mrt0"][0] - self.assertEqual(res, 0x456) - - def test_constant_alignbyte_zero_shift_folds_directly(self): - lines = [ - "v_mov_b32 v1, 0xDEADBEEF", - "v_mov_b32 v2, 0x12345678", - "v_alignbyte_b32 v0, v1, v2, 0", - ] - spv = self.translate_lines(lines) - self.assertNotIn("OpShiftRightLogical", spv) - self.assertNotIn("OpShiftLeftLogical", spv) - self.assertNotIn("OpBitwiseOr", spv) - res = si.run_fragment(spv)["%out_mrt0"][0] - self.assertEqual(res, 0x12345678) - - def test_constant_alignbyte_nonzero_shift_emits_direct_shifts(self): - lines = [ - "v_mov_b32 v1, 0x8899AABB", - "v_mov_b32 v2, 0x11223344", - "v_alignbyte_b32 v0, v1, v2, 1", - ] - spv = self.translate_lines(lines) - self.assertNotIn("OpBitwiseAnd %uint", spv) - self.assertNotIn("OpISub %uint", spv) - self.assertIn("OpShiftRightLogical %uint", spv) - self.assertIn("OpShiftLeftLogical %uint", spv) - self.assertIn("OpBitwiseOr %uint", spv) - res = si.run_fragment(spv)["%out_mrt0"][0] - self.assertEqual(res, 0xBB112233) - - def test_constant_alignbit_zero_shift_folds_directly(self): - lines = [ - "v_mov_b32 v1, 0xDEADBEEF", - "v_mov_b32 v2, 0x12345678", - "v_alignbit_b32 v0, v1, v2, 0", - ] - spv = self.translate_lines(lines) - self.assertNotIn("OpShiftRightLogical", spv) - self.assertNotIn("OpShiftLeftLogical", spv) - self.assertNotIn("OpBitwiseOr", spv) - res = si.run_fragment(spv)["%out_mrt0"][0] - self.assertEqual(res, 0x12345678) - - def test_constant_alignbit_nonzero_shift_emits_direct_shifts(self): - lines = [ - "v_mov_b32 v1, 0x12345678", - "v_mov_b32 v2, 0x9ABCDEF0", - "v_alignbit_b32 v0, v1, v2, 16", - ] - spv = self.translate_lines(lines) - self.assertNotIn("OpBitwiseAnd %uint", spv) - self.assertNotIn("OpISub %uint", spv) - self.assertIn("OpShiftRightLogical %uint", spv) - self.assertIn("OpShiftLeftLogical %uint", spv) - self.assertIn("OpBitwiseOr %uint", spv) - res = si.run_fragment(spv)["%out_mrt0"][0] - self.assertEqual(res, 0x56789ABC) - - def test_dedupe_types_merges_duplicate_types_and_substitutes(self): - spv_sample = ( - "OpCapability Shader\n" - "%uint = OpTypeInt 32 0\n" - "%v4uint = OpTypeVector %uint 4\n" - "%v4uint_st = OpTypeVector %uint 4\n" - "%ptr_v4uint = OpTypePointer StorageBuffer %v4uint\n" - "%ptr_v4uint_st = OpTypePointer StorageBuffer %v4uint_st\n" - "%fn = OpTypeFunction %void\n" - "%main = OpFunction %void None %fn\n" - "%entry = OpLabel\n" - "%var = OpVariable %ptr_v4uint_st StorageBuffer\n" - "%val = OpLoad %v4uint_st %var\n" - "OpReturn\n" - "OpFunctionEnd" - ) - deduped = rdna2spirv.dedupe_types(spv_sample) - self.assertNotIn("%v4uint_st =", deduped) - self.assertNotIn("%ptr_v4uint_st =", deduped) - self.assertIn("%var = OpVariable %ptr_v4uint StorageBuffer", deduped) - self.assertIn("%val = OpLoad %v4uint %var", deduped) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_alu_bitrev_abs.py b/tests/semantic/test_alu_bitrev_abs.py deleted file mode 100644 index 7f38276ca..000000000 --- a/tests/semantic/test_alu_bitrev_abs.py +++ /dev/null @@ -1,900 +0,0 @@ -"""Semantic interpreter tests for RDNA2 vector bit manipulation and absolute value: - - v_bfrev_b32: 32-bit vector bitfield reverse (D = reverse_bits(S0)) - - s_brev_b32: 32-bit scalar bitfield reverse - - v_abs_i32: 32-bit vector integer absolute value (D = |S0|) - - s_abs_i32: 32-bit scalar integer absolute value with SCC flag - -Features covered: - - RDNA2 vector bit manipulation reference oracles and algebraic identities: - * Involution identity: bfrev(bfrev(x)) == x (bijective self-inverse permutation). - * Popcount preservation: popcount(bfrev(x)) == popcount(x). - * Bit boundary reflection: bit i maps to bit (31 - i) (e.g. bit 0 <-> bit 31, bit 15 <-> bit 16). - * Algebraic homomorphism: bfrev(x ^ y) == bfrev(x) ^ bfrev(y) and bfrev(~x) == ~bfrev(x). - * Extreme and canonical bit patterns: 0x00000000, 0xFFFFFFFF, 0x55555555 <-> 0xAAAAAAAA, - 0x33333333 <-> 0xCCCCCCCC, 0x0F0F0F0F <-> 0xF0F0F0F0, 0x00FF00FF <-> 0xFF00FF00, - 0x0000FFFF <-> 0xFFFF0000, 0x80000000 <-> 0x00000001. - * Cross-oracle validation between string-reversal, parallel SWAR bit-swaps, and byte-lookup tables. - - Two's-complement integer absolute value semantics: - * D = |S0| for signed 32-bit integer in range [-2^31, 2^31 - 1]. - * Non-negative values are identity: |x| == x for x >= 0. - * Strictly negative values are negated: |x| == -x for x < 0. - * Two's-complement overflow: |-2147483648| == -2147483648 (0x80000000). - - Synthetic shader translation via tools/rdna2spirv.py and execution via tests/semantic/spirv_mini_interp.py. - -Zero game data, standard library Python only, Python 3.9+ compatible. -""" -from __future__ import annotations - -import os -import struct -import sys -import tempfile -import unittest -import warnings - -HERE = os.path.dirname(os.path.abspath(__file__)) -ROOT = os.path.dirname(os.path.dirname(HERE)) -TOOLS_DIR = os.environ.get("LEONIDA_TOOLS_DIR") or os.path.join(ROOT, "tools") - -sys.dont_write_bytecode = True -if TOOLS_DIR not in sys.path: - sys.path.insert(0, TOOLS_DIR) -if HERE not in sys.path: - sys.path.insert(0, HERE) - -import rdna2spirv # noqa: E402 -import spirv_mini_interp as si # noqa: E402 -import spirv_wave_interp as wi # noqa: E402 - -MASK32 = 0xFFFFFFFF -STUB_DXBC = b"DXBC" + bytes(24) + struct.pack(" int: - """Normalize integer to 32-bit unsigned dword.""" - return val & MASK32 - - -def s32(val: int) -> int: - """Interpret 32-bit dword as signed two's complement integer.""" - v = val & MASK32 - return v - (1 << 32) if (v & 0x80000000) else v - - -def popcount(x: int) -> int: - """Count number of set bits in 32-bit dword (Python 3.9+ compatible).""" - return bin(x & MASK32).count("1") - - -def ref_brev32(x: int) -> int: - """Reference oracle for 32-bit bitfield reverse (string-based).""" - return int(f"{x & MASK32:032b}"[::-1], 2) - - -def ref_brev32_swar(x: int) -> int: - """Hacker's Delight parallel SWAR (SIMD within a register) 32-bit bit reversal.""" - v = x & MASK32 - v = ((v >> 1) & 0x55555555) | ((v & 0x55555555) << 1) - v = ((v >> 2) & 0x33333333) | ((v & 0x33333333) << 2) - v = ((v >> 4) & 0x0F0F0F0F) | ((v & 0x0F0F0F0F) << 4) - v = ((v >> 8) & 0x00FF00FF) | ((v & 0x00FF00FF) << 8) - v = ((v >> 16) & 0x0000FFFF) | ((v & 0x0000FFFF) << 16) - return v & MASK32 - - -_REV_TABLE_8 = tuple(int(f"{b:08b}"[::-1], 2) for b in range(256)) - - -def ref_brev32_table(x: int) -> int: - """Table-based 32-bit bit reversal oracle across 4 lookup bytes.""" - v = x & MASK32 - b0 = _REV_TABLE_8[v & 0xFF] - b1 = _REV_TABLE_8[(v >> 8) & 0xFF] - b2 = _REV_TABLE_8[(v >> 16) & 0xFF] - b3 = _REV_TABLE_8[(v >> 24) & 0xFF] - return ((b0 << 24) | (b1 << 16) | (b2 << 8) | b3) & MASK32 - - -# Alias for backwards compatibility -ref_brev = ref_brev32 - - -def ref_abs32(x: int) -> int: - """Reference oracle for signed 32-bit absolute value with two's-complement overflow.""" - s = s32(x) - return u32(-s if s < 0 else s) - - -def ref_absdiff32(x: int, y: int) -> int: - """Reference oracle for 32-bit signed absolute difference: |x - y|.""" - diff = (u32(x) - u32(y)) & MASK32 - return ref_abs32(diff) - - -# Alias for backwards compatibility -ref_abs = ref_abs32 - - -_TMP_DIR = None -_SRC_PATH = None - - -def setUpModule(): - global _TMP_DIR, _SRC_PATH - _TMP_DIR = tempfile.TemporaryDirectory() - disasm_dir = os.path.join(_TMP_DIR.name, "disasm") - os.mkdir(disasm_dir) - _SRC_PATH = os.path.join(disasm_dir, "ps_bitrev_abs.s") - with open(os.path.join(_TMP_DIR.name, "ps_bitrev_abs.dxbc"), "wb") as f: - f.write(STUB_DXBC) - - -def tearDownModule(): - global _TMP_DIR - if _TMP_DIR is not None: - _TMP_DIR.cleanup() - _TMP_DIR = None - - -def translate_lines(lines: list[str]) -> str: - """Assemble synthetic shader lines with rdna2spirv and return the SPIR-V assembly text.""" - if _TMP_DIR is None: - setUpModule() - asm = "; test_bitrev_abs\n" + "".join(f"\t{ln}\n" for ln in lines) + "\texp mrt0 v0, v1, v0, v0 done vm\n\ts_endpgm\n" - with open(_SRC_PATH, "w", encoding="utf-8") as f: - f.write(asm) - with warnings.catch_warnings(): - warnings.simplefilter("ignore", ResourceWarning) - return rdna2spirv.translate(_SRC_PATH) - - -def run_lines(lines: list[str]) -> tuple[int, ...]: - """Assemble and run synthetic pixel shader lines, returning (out_mrt0.x, out_mrt0.y).""" - spv = translate_lines(lines) - return tuple(si.run_fragment(spv)["%out_mrt0"][:2]) - - -class VectorBitrevOracleTests(unittest.TestCase): - """Rigorous algebraic and property-based verification of bit-reversal reference models.""" - - def test_oracle_equivalence_across_algorithms(self): - """String-based, SWAR bit-swap, and byte-lookup algorithms must be 100% equivalent.""" - for val in CANONICAL_VALUES: - with self.subTest(val=hex(val)): - r1 = ref_brev32(val) - r2 = ref_brev32_swar(val) - r3 = ref_brev32_table(val) - self.assertEqual(r1, r2) - self.assertEqual(r1, r3) - - def test_single_bit_boundary_reflections(self): - """Bit i must reflect strictly to bit (31 - i) for all 0 <= i <= 31.""" - for i in range(32): - src = 1 << i - expected = 1 << (31 - i) - with self.subTest(bit=i, src=hex(src)): - self.assertEqual(ref_brev32(src), expected) - self.assertEqual(ref_brev32_swar(src), expected) - self.assertEqual(ref_brev32_table(src), expected) - - def test_popcount_preservation_property(self): - """Bit reversal must preserve hamming weight (popcount) identically: popcount(brev(x)) == popcount(x).""" - test_inputs = list(CANONICAL_VALUES) - # Add random-like deterministic multi-bit patterns - for shift in range(32): - test_inputs.append((0x12345678 << shift) & MASK32) - test_inputs.append((0xCAFEBABE >> shift) & MASK32) - test_inputs.append((1 << shift) | (1 << ((shift + 7) % 32))) - - for x in test_inputs: - with self.subTest(x=hex(x)): - rev = ref_brev32(x) - self.assertEqual(popcount(rev), popcount(x)) - - def test_involution_identity(self): - """Bit reversal is an involution: bfrev(bfrev(x)) == x for all inputs.""" - for x in CANONICAL_VALUES: - with self.subTest(x=hex(x)): - self.assertEqual(ref_brev32(ref_brev32(x)), x) - self.assertEqual(ref_brev32_swar(ref_brev32_swar(x)), x) - self.assertEqual(ref_brev32_table(ref_brev32_table(x)), x) - - def test_algebraic_homomorphism_xor_and_not(self): - """bfrev distributes over XOR: bfrev(x ^ y) == bfrev(x) ^ bfrev(y) and bfrev(~x) == ~bfrev(x).""" - pairs = [ - (0x55555555, 0xAAAAAAAA), - (0x12345678, 0x87654321), - (0x00FF00FF, 0xF0F0F0F0), - (0x80000001, 0x7FFFFFFE), - (0xFFFFFFFF, 0x12345678), - ] - for a, b in pairs: - with self.subTest(a=hex(a), b=hex(b)): - self.assertEqual(ref_brev32(a ^ b), ref_brev32(a) ^ ref_brev32(b)) - self.assertEqual(ref_brev32(~a & MASK32), (~ref_brev32(a)) & MASK32) - self.assertEqual(ref_brev32(~b & MASK32), (~ref_brev32(b)) & MASK32) - - def test_palindromic_self_reversing_bit_patterns(self): - """Bit patterns that are symmetric across the center must equal themselves under bit reversal.""" - palindromes = [ - 0x00000000, - 0xFFFFFFFF, - 0x80000001, # bit 0 and bit 31 set - 0x00018000, # bit 15 and bit 16 set - 0x5555AAAA, # 0101...1010 - 0x0FF00FF0, - 0x3C3C3C3C, - 0xA55A5AA5, - ] - for p in palindromes: - with self.subTest(p=hex(p)): - self.assertEqual(ref_brev32(p), p) - - def test_canonical_reflections(self): - """Canonical test pairs must match hand-derived mathematical reflections.""" - expected_pairs = [ - (0x00000001, 0x80000000), - (0x00000003, 0xC0000000), - (0x55555555, 0xAAAAAAAA), - (0x33333333, 0xCCCCCCCC), - (0x0F0F0F0F, 0xF0F0F0F0), - (0x00FF00FF, 0xFF00FF00), - (0x0000FFFF, 0xFFFF0000), - (0x12345678, 0x1E6A2C48), - ] - for src, expected in expected_pairs: - with self.subTest(src=hex(src)): - self.assertEqual(ref_brev32(src), expected) - self.assertEqual(ref_brev32(expected), src) - - -class VectorAluInterpreter: - """Deterministic SIMD wave interpreter modeling vector and scalar ALU with execution masking. - - Supports Wave32 (32 lanes) and Wave64 (64 lanes). - Models: - - EXEC mask: per-lane active bit controlling vector instruction side-effects. - - Inactive lanes strictly retain their previous VGPR contents. - - SGPRs: uniform scalar registers shared across all lanes in the wave. - - SCC: scalar condition code flag (updated by scalar ops like s_abs_i32). - - VGPRs: independent per-lane vector registers. - """ - - def __init__(self, wave_size: int = 32, initial_exec: int = 0xFFFFFFFF) -> None: - assert wave_size in (32, 64) - self.wave_size = wave_size - self.mask_all = (1 << wave_size) - 1 - self.exec_mask = initial_exec & self.mask_all - self.sgprs = [0] * 128 - self.scc = 0 - self.vgprs = [[0] * 256 for _ in range(wave_size)] - - def is_lane_active(self, lane: int) -> bool: - return bool((self.exec_mask >> lane) & 1) - - def set_exec(self, mask: int) -> None: - self.exec_mask = mask & self.mask_all - - def resolve_src(self, lane: int, opnd: int | str) -> int: - if isinstance(opnd, int): - return opnd & MASK32 - if isinstance(opnd, str): - if opnd.startswith("v"): - reg = int(opnd[1:]) - return self.vgprs[lane][reg] & MASK32 - if opnd.startswith("s"): - reg = int(opnd[1:]) - return self.sgprs[reg] & MASK32 - try: - return int(opnd, 0) & MASK32 - except ValueError: - pass - raise ValueError(f"Unknown operand: {opnd}") - - def execute_instruction(self, op: str, *args) -> None: - if op == "v_mov_b32": - dst, src = args - dst_reg = int(dst[1:]) if isinstance(dst, str) else dst - for lane in range(self.wave_size): - if self.is_lane_active(lane): - self.vgprs[lane][dst_reg] = self.resolve_src(lane, src) - - elif op in ("v_bfrev_b32", "v_bfrev_b32_e32"): - dst, src = args - dst_reg = int(dst[1:]) if isinstance(dst, str) else dst - for lane in range(self.wave_size): - if self.is_lane_active(lane): - val = self.resolve_src(lane, src) - self.vgprs[lane][dst_reg] = ref_brev32(val) - - elif op in ("v_abs_i32", "v_abs_i32_e32"): - dst, src = args - dst_reg = int(dst[1:]) if isinstance(dst, str) else dst - for lane in range(self.wave_size): - if self.is_lane_active(lane): - val = self.resolve_src(lane, src) - self.vgprs[lane][dst_reg] = ref_abs32(val) - - elif op in ("v_absdiff_i32", "v_absdiff_i32_e32"): - dst, src0, src1 = args - dst_reg = int(dst[1:]) if isinstance(dst, str) else dst - for lane in range(self.wave_size): - if self.is_lane_active(lane): - v0 = self.resolve_src(lane, src0) - v1 = self.resolve_src(lane, src1) - self.vgprs[lane][dst_reg] = ref_absdiff32(v0, v1) - - elif op == "s_mov_b32": - dst, src = args - dst_reg = int(dst[1:]) if isinstance(dst, str) else dst - self.sgprs[dst_reg] = self.resolve_src(0, src) - - elif op == "s_abs_i32": - dst, src = args - dst_reg = int(dst[1:]) if isinstance(dst, str) else dst - res = ref_abs32(self.resolve_src(0, src)) - self.sgprs[dst_reg] = res - self.scc = 1 if res != 0 else 0 - - elif op == "s_absdiff_i32": - dst, src0, src1 = args - dst_reg = int(dst[1:]) if isinstance(dst, str) else dst - res = ref_absdiff32(self.resolve_src(0, src0), self.resolve_src(0, src1)) - self.sgprs[dst_reg] = res - self.scc = 1 if res != 0 else 0 - - elif op == "s_brev_b32": - dst, src = args - dst_reg = int(dst[1:]) if isinstance(dst, str) else dst - res = ref_brev32(self.resolve_src(0, src)) - self.sgprs[dst_reg] = res - - elif op in ("s_and_saveexec_b32", "s_and_saveexec_b64"): - dst, mask = args - dst_reg = int(dst[1:]) if isinstance(dst, str) else dst - mask_val = mask if isinstance(mask, int) else self.resolve_src(0, mask) - self.sgprs[dst_reg] = self.exec_mask & MASK32 - if self.wave_size == 64 and op.endswith("64"): - self.sgprs[dst_reg + 1] = (self.exec_mask >> 32) & MASK32 - self.exec_mask = (self.exec_mask & mask_val) & self.mask_all - - elif op in ("s_or_exec_b32", "s_or_exec_b64"): - mask = args[0] - mask_val = mask if isinstance(mask, int) else self.resolve_src(0, mask) - self.exec_mask = (self.exec_mask | mask_val) & self.mask_all - else: - raise NotImplementedError(f"Unsupported op: {op}") - - -class VectorAbsPropertiesTests(unittest.TestCase): - """Algebraic verification of signed 32-bit absolute value and difference semantics.""" - - def test_non_negative_identity(self): - """For non-negative signed integers, abs(x) == x.""" - non_negatives = [0, 1, 2, 42, 1000, 0x12345678, 0x7FFFFFFE, 0x7FFFFFFF] - for x in non_negatives: - with self.subTest(x=hex(x)): - self.assertEqual(ref_abs32(x), x) - - def test_strictly_negative_inversion(self): - """For strictly negative integers (excluding INT_MIN), abs(x) == -x.""" - negatives = [-1, -2, -42, -1000, -0x12345678, -0x7FFFFFFF] - for s in negatives: - u = u32(s) - with self.subTest(s=s, u=hex(u)): - self.assertEqual(ref_abs32(u), abs(s)) - - def test_two_complement_overflow_int_min(self): - """Two's-complement overflow: |-2147483648| wraps to -2147483648 (0x80000000).""" - int_min = 0x80000000 - self.assertEqual(ref_abs32(int_min), int_min) - self.assertEqual(s32(ref_abs32(int_min)), -2147483648) - - def test_abs_idempotency(self): - """Absolute value is idempotent: abs(abs(x)) == abs(x).""" - for x in CANONICAL_VALUES: - with self.subTest(x=hex(x)): - a1 = ref_abs32(x) - a2 = ref_abs32(a1) - self.assertEqual(a1, a2) - - def test_absdiff_symmetry(self): - """Absolute difference is symmetric: |x - y| == |y - x| in 32-bit modular arithmetic.""" - test_pairs = [ - (0, 0), - (0, 1), - (1, 0), - (10, 42), - (42, 10), - (0xFFFFFFFF, 1), - (1, 0xFFFFFFFF), - (0x7FFFFFFF, 0x80000000), - (0x80000000, 0x7FFFFFFF), - (0x12345678, 0x87654321), - (0x55555555, 0xAAAAAAAA), - ] - for x, y in test_pairs: - with self.subTest(x=hex(x), y=hex(y)): - self.assertEqual(ref_absdiff32(x, y), ref_absdiff32(y, x)) - - def test_absdiff_zero_identity(self): - """|x - x| == 0 for all 32-bit values.""" - for x in CANONICAL_VALUES: - with self.subTest(x=hex(x)): - self.assertEqual(ref_absdiff32(x, x), 0) - - def test_absdiff_with_zero(self): - """|x - 0| == |x| and |0 - x| == |x|.""" - for x in CANONICAL_VALUES: - with self.subTest(x=hex(x)): - want = ref_abs32(x) - self.assertEqual(ref_absdiff32(x, 0), want) - self.assertEqual(ref_absdiff32(0, x), want) - - def test_absdiff_overflow_wrap(self): - """Difference wraps before absolute value: 0x7FFFFFFF - 0x80000000 = -1 -> abs is 1.""" - self.assertEqual(ref_absdiff32(0x7FFFFFFF, 0x80000000), 1) - self.assertEqual(ref_absdiff32(0x80000000, 0x7FFFFFFF), 1) - - -class SimdMultiLaneDivergenceTests(unittest.TestCase): - """Multi-lane SIMD divergence verification under diverse EXEC execution masks.""" - - def test_full_exec_all_lanes_updated(self): - """Wave32 with EXEC=0xFFFFFFFF updates all 32 lanes.""" - interp = VectorAluInterpreter(wave_size=32, initial_exec=0xFFFFFFFF) - sentinel = 0xDEADBEEF - for lane in range(32): - interp.vgprs[lane][0] = sentinel - interp.vgprs[lane][1] = u32(-(lane + 1)) - - interp.execute_instruction("v_abs_i32", "v0", "v1") - - for lane in range(32): - expected = lane + 1 - self.assertEqual(interp.vgprs[lane][0], expected, f"Lane {lane} failed") - - def test_zero_exec_preserves_all_vgprs(self): - """Wave32 with EXEC=0x00000000 preserves all destination VGPRs across the wave.""" - interp = VectorAluInterpreter(wave_size=32, initial_exec=0x00000000) - sentinel = 0xDEADBEEF - for lane in range(32): - interp.vgprs[lane][0] = sentinel - interp.vgprs[lane][1] = u32(-(lane + 1)) - - interp.execute_instruction("v_abs_i32", "v0", "v1") - - for lane in range(32): - self.assertEqual(interp.vgprs[lane][0], sentinel, f"Lane {lane} was incorrectly overwritten") - - def test_checkerboard_divergence_v_abs(self): - """Wave32 with EXEC=0x55555555 updates even lanes and preserves odd lanes.""" - interp = VectorAluInterpreter(wave_size=32, initial_exec=0x55555555) - sentinel = 0xBAADF00D - for lane in range(32): - interp.vgprs[lane][0] = sentinel - interp.vgprs[lane][1] = u32(-((lane + 1) * 10)) - - interp.execute_instruction("v_abs_i32", "v0", "v1") - - for lane in range(32): - if lane % 2 == 0: - self.assertEqual(interp.vgprs[lane][0], (lane + 1) * 10) - else: - self.assertEqual(interp.vgprs[lane][0], sentinel) - - def test_checkerboard_divergence_v_bfrev(self): - """Wave32 with EXEC=0xAAAAAAAA updates odd lanes and preserves even lanes with bit-reversal.""" - interp = VectorAluInterpreter(wave_size=32, initial_exec=0xAAAAAAAA) - sentinel = 0xCAFEBABE - for lane in range(32): - interp.vgprs[lane][0] = sentinel - interp.vgprs[lane][1] = 1 << lane - - interp.execute_instruction("v_bfrev_b32", "v0", "v1") - - for lane in range(32): - if lane % 2 == 1: - self.assertEqual(interp.vgprs[lane][0], 1 << (31 - lane)) - else: - self.assertEqual(interp.vgprs[lane][0], sentinel) - - def test_single_lane_active_boundaries(self): - """Test isolated active lane at boundaries (lane 0, lane 15, lane 31).""" - boundary_lanes = [0, 15, 31] - for active_lane in boundary_lanes: - with self.subTest(active_lane=active_lane): - exec_mask = 1 << active_lane - interp = VectorAluInterpreter(wave_size=32, initial_exec=exec_mask) - sentinel = 0x11223344 - for lane in range(32): - interp.vgprs[lane][0] = sentinel - interp.vgprs[lane][1] = 0x80000000 if lane == 0 else u32(-(lane * 100)) - - interp.execute_instruction("v_abs_i32", "v0", "v1") - - for lane in range(32): - if lane == active_lane: - expected = ref_abs32(interp.vgprs[lane][1]) - self.assertEqual(interp.vgprs[lane][0], expected) - else: - self.assertEqual(interp.vgprs[lane][0], sentinel) - - def test_wave64_divergence_halves(self): - """Wave64 with low half active (EXEC=0x00000000FFFFFFFF) updates lanes 0..31, preserves 32..63.""" - interp = VectorAluInterpreter(wave_size=64, initial_exec=0x00000000FFFFFFFF) - sentinel = 0x55AA55AA - for lane in range(64): - interp.vgprs[lane][0] = sentinel - interp.vgprs[lane][1] = u32(-(lane + 1)) - - interp.execute_instruction("v_abs_i32", "v0", "v1") - - for lane in range(64): - if lane < 32: - self.assertEqual(interp.vgprs[lane][0], lane + 1) - else: - self.assertEqual(interp.vgprs[lane][0], sentinel) - - def test_vector_absdiff_simd_multi_lane(self): - """v_absdiff_i32 across SIMD lanes with pairwise vector operands.""" - interp = VectorAluInterpreter(wave_size=32, initial_exec=0x0000FFFF) - sentinel = 0x01020304 - for lane in range(32): - interp.vgprs[lane][0] = sentinel - interp.vgprs[lane][1] = 50 + lane - interp.vgprs[lane][2] = 100 - - interp.execute_instruction("v_absdiff_i32", "v0", "v1", "v2") - - for lane in range(32): - if lane < 16: - expected = ref_absdiff32(50 + lane, 100) - self.assertEqual(interp.vgprs[lane][0], expected) - else: - self.assertEqual(interp.vgprs[lane][0], sentinel) - - def test_saveexec_restore_simd_branch_pattern(self): - """Simulates divergent branch pattern using s_and_saveexec and s_or_exec.""" - interp = VectorAluInterpreter(wave_size=32, initial_exec=0xFFFFFFFF) - # Initialize lanes: even lanes get negative, odd lanes get positive - for lane in range(32): - interp.vgprs[lane][0] = 0 - interp.vgprs[lane][1] = u32(-(lane + 1)) if (lane % 2 == 0) else (lane + 1) - - # Step 1: Branch taken by even lanes only (EXEC & 0x55555555) - # s_and_saveexec_b32 s2, 0x55555555 -> saves 0xFFFFFFFF to s2, sets EXEC=0x55555555 - interp.execute_instruction("s_and_saveexec_b32", "s2", 0x55555555) - self.assertEqual(interp.sgprs[2], 0xFFFFFFFF) - self.assertEqual(interp.exec_mask, 0x55555555) - - # In then-block: v_abs_i32 v0, v1 (only even lanes update) - interp.execute_instruction("v_abs_i32", "v0", "v1") - - # Step 2: Invert mask for else-block: EXEC = (saved ~EXEC) & saved - # s_or_exec_b32 restores saved or complements - interp.set_exec((~0x55555555) & 0xFFFFFFFF) - # In else-block: v_bfrev_b32 v0, v1 (only odd lanes update) - interp.execute_instruction("v_bfrev_b32", "v0", "v1") - - # Step 3: Reconverge - interp.execute_instruction("s_mov_b32", "s0", "s2") - interp.set_exec(interp.sgprs[0]) - self.assertEqual(interp.exec_mask, 0xFFFFFFFF) - - for lane in range(32): - if lane % 2 == 0: - self.assertEqual(interp.vgprs[lane][0], lane + 1) - else: - self.assertEqual(interp.vgprs[lane][0], ref_brev32(lane + 1)) - - -class BitReverseTests(unittest.TestCase): - def test_reference(self): - self.assertEqual(ref_brev(1), 0x80000000) - self.assertEqual(ref_brev(0x12345678), 0x1E6A2C48) - self.assertEqual(ref_brev(0x0000FFFF), 0xFFFF0000) - - def test_v_bfrev_b32(self): - for x in VALUES: - with self.subTest(x=hex(x)): - self.assertEqual(run_lines([f"v_mov_b32 v2, {x:#x}", "v_bfrev_b32_e32 v0, v2", "v_mov_b32 v1, 0"])[0], - ref_brev(x)) - - def test_s_brev_b32(self): - for x in VALUES: - with self.subTest(x=hex(x)): - self.assertEqual(run_lines([f"s_mov_b32 s2, {x:#x}", "s_brev_b32 s0, s2", "v_mov_b32 v0, s0", - "v_mov_b32 v1, 0"])[0], ref_brev(x)) - - def test_twice_is_identity(self): - for x in VALUES: - with self.subTest(x=hex(x)): - self.assertEqual(run_lines([f"v_mov_b32 v2, {x:#x}", "v_bfrev_b32_e32 v3, v2", "v_bfrev_b32_e32 v0, v3", - "v_mov_b32 v1, 0"])[0], x) - - -class AbsTests(unittest.TestCase): - def test_reference(self): - self.assertEqual(ref_abs(0xFFFFFFFF), 1) - self.assertEqual(ref_abs(0x80000000), 0x80000000) - self.assertEqual(ref_abs(0x7FFFFFFF), 0x7FFFFFFF) - - def test_s_abs_i32_and_scc(self): - for x in VALUES: - with self.subTest(x=hex(x)): - want = ref_abs(x) - got = run_lines([f"s_mov_b32 s2, {x:#x}", "s_abs_i32 s0, s2", "s_cselect_b32 s1, 1, 0", - "v_mov_b32 v0, s0", "v_mov_b32 v1, s1"]) - self.assertEqual(got, (want, int(want != 0))) - - def test_s_absdiff_i32_and_scc(self): - test_pairs = [ - (0, 0), - (5, 12), - (12, 5), - (10, 10), - (0xFFFFFFFF, 1), - (1, 0xFFFFFFFF), - (0x7FFFFFFF, 0x80000000), - (0x80000000, 0x7FFFFFFF), - (0x80000000, 0), - (0, 0x80000000), - (0x12345678, 0x12345678), - (0x12345678, 0x87654321), - ] - for x, y in test_pairs: - with self.subTest(x=hex(x), y=hex(y)): - want = ref_absdiff32(x, y) - got = run_lines([f"s_mov_b32 s2, {x:#x}", f"s_mov_b32 s3, {y:#x}", - "s_absdiff_i32 s0, s2, s3", "s_cselect_b32 s1, 1, 0", - "v_mov_b32 v0, s0", "v_mov_b32 v1, s1"]) - self.assertEqual(got, (want, int(want != 0))) - - -class SpirvEmissionTests(unittest.TestCase): - """Verify that tools/rdna2spirv emits expected SPIR-V instructions and structures.""" - - def test_v_bfrev_b32_emission(self): - spv = translate_lines(["v_mov_b32 v2, 0x12345678", "v_bfrev_b32_e32 v0, v2"]) - self.assertIn("OpBitReverse %uint", spv) - - def test_s_brev_b32_emission(self): - spv = translate_lines(["s_mov_b32 s2, 0x12345678", "s_brev_b32 s0, s2", "v_mov_b32 v0, s0"]) - self.assertIn("OpBitReverse %uint", spv) - - def test_s_abs_i32_emission(self): - # A loaded operand, not a literal: SHADER-315 folds scalar ALU ops on constants at translate time. - spv = translate_lines(["s_load_dword s2, s[0:1], 0x0", "s_waitcnt lgkmcnt(0)", "s_abs_i32 s0, s2", - "v_mov_b32 v0, s0"]) - self.assertIn('OpExtInstImport "GLSL.std.450"', spv) - self.assertIn("SAbs", spv) - self.assertIn("OpStore %scc", spv) - - def test_s_absdiff_i32_emission(self): - spv = translate_lines(["s_load_dwordx2 s[2:3], s[0:1], 0x0", "s_waitcnt lgkmcnt(0)", - "s_absdiff_i32 s0, s2, s3", "v_mov_b32 v0, s0"]) - self.assertIn("OpISub %uint", spv) - self.assertIn("SAbs", spv) - self.assertIn("OpStore %scc", spv) - - -class DirectSpirvInterpreterEdgeCaseTests(unittest.TestCase): - """Direct verification of SPIR-V OpBitReverse and SAbs via mini-interpreter and wave-interpreter.""" - - def test_spirv_opbitreverse_all_single_bits(self): - for bit in range(32): - val = 1 << bit - expected = 1 << (31 - bit) - spv = f"""OpCapability Shader -OpMemoryModel Logical GLSL450 -OpEntryPoint Fragment %main "main" %out_mrt0 -OpExecutionMode %main OriginUpperLeft -%void = OpTypeVoid -%fn = OpTypeFunction %void -%uint = OpTypeInt 32 0 -%v4uint = OpTypeVector %uint 4 -%_ptr_Output_v4uint = OpTypePointer Output %v4uint -%out_mrt0 = OpVariable %_ptr_Output_v4uint Output -%val = OpConstant %uint {val} -%c0 = OpConstant %uint 0 -%main = OpFunction %void None %fn -%entry = OpLabel -%rev = OpBitReverse %uint %val -%out = OpCompositeConstruct %v4uint %rev %c0 %c0 %c0 -OpStore %out_mrt0 %out -OpReturn -OpFunctionEnd -""" - out = si.run_fragment(spv)["%out_mrt0"] - self.assertEqual(out[0], expected) - - def test_spirv_sabs_two_complement_wrap(self): - spv = """OpCapability Shader -%glsl = OpExtInstImport "GLSL.std.450" -OpMemoryModel Logical GLSL450 -OpEntryPoint Fragment %main "main" %out_mrt0 -OpExecutionMode %main OriginUpperLeft -%void = OpTypeVoid -%fn = OpTypeFunction %void -%int = OpTypeInt 32 1 -%uint = OpTypeInt 32 0 -%v4uint = OpTypeVector %uint 4 -%_ptr_Output_v4uint = OpTypePointer Output %v4uint -%out_mrt0 = OpVariable %_ptr_Output_v4uint Output -%int_min = OpConstant %uint 2147483648 -%c0 = OpConstant %uint 0 -%main = OpFunction %void None %fn -%entry = OpLabel -%i = OpBitcast %int %int_min -%ab = OpExtInst %int %glsl SAbs %i -%res = OpBitcast %uint %ab -%out = OpCompositeConstruct %v4uint %res %c0 %c0 %c0 -OpStore %out_mrt0 %out -OpReturn -OpFunctionEnd -""" - out = si.run_fragment(spv)["%out_mrt0"] - self.assertEqual(out[0], 0x80000000) - - def test_spirv_wave_bitreverse_all_lanes(self): - spv = """OpCapability Shader -OpMemoryModel Logical GLSL450 -OpEntryPoint Fragment %main "main" %lane %out -OpDecorate %lane BuiltIn SubgroupLocalInvocationId -%void = OpTypeVoid -%fn = OpTypeFunction %void -%uint = OpTypeInt 32 0 -%v4uint = OpTypeVector %uint 4 -%pin = OpTypePointer Input %uint -%pout = OpTypePointer Output %v4uint -%lane = OpVariable %pin Input -%out = OpVariable %pout Output -%c0 = OpConstant %uint 0 -%main = OpFunction %void None %fn -%entry = OpLabel -%l = OpLoad %uint %lane -%rev = OpBitReverse %uint %l -%v = OpCompositeConstruct %v4uint %rev %c0 %c0 %c0 -OpStore %out %v -OpReturn -OpFunctionEnd -""" - res = wi.run_wave(spv, wave=32) - outputs = res["outputs"] - for lane in range(32): - self.assertEqual(outputs[lane]["%out"][0], ref_brev32(lane)) - - def test_spirv_wave_sabs_all_lanes(self): - spv = """OpCapability Shader -%glsl = OpExtInstImport "GLSL.std.450" -OpMemoryModel Logical GLSL450 -OpEntryPoint Fragment %main "main" %lane %out -OpDecorate %lane BuiltIn SubgroupLocalInvocationId -%void = OpTypeVoid -%fn = OpTypeFunction %void -%int = OpTypeInt 32 1 -%uint = OpTypeInt 32 0 -%v4uint = OpTypeVector %uint 4 -%pin = OpTypePointer Input %uint -%pout = OpTypePointer Output %v4uint -%lane = OpVariable %pin Input -%out = OpVariable %pout Output -%c0 = OpConstant %uint 0 -%c0_i = OpConstant %int 0 -%main = OpFunction %void None %fn -%entry = OpLabel -%l = OpLoad %uint %lane -%i = OpBitcast %int %l -%neg = OpISub %int %c0_i %i -%ab = OpExtInst %int %glsl SAbs %neg -%u = OpBitcast %uint %ab -%v = OpCompositeConstruct %v4uint %u %c0 %c0 %c0 -OpStore %out %v -OpReturn -OpFunctionEnd -""" - res = wi.run_wave(spv, wave=32) - outputs = res["outputs"] - for lane in range(32): - self.assertEqual(outputs[lane]["%out"][0], lane) - - -class NegativeMutationControlTests(unittest.TestCase): - """Negative controls verifying that mutated or corrupt behaviors are strictly detected.""" - - def test_mutation_bitrev_shift_rejected(self): - def bad_brev32_shift(x: int) -> int: - return (ref_brev32(x) >> 1) & MASK32 - - self.assertNotEqual(bad_brev32_shift(1), ref_brev32(1)) - self.assertNotEqual(bad_brev32_shift(0x12345678), ref_brev32(0x12345678)) - - def test_mutation_bitrev_inverted_rejected(self): - def bad_brev32_invert(x: int) -> int: - return (~ref_brev32(x)) & MASK32 - - self.assertNotEqual(bad_brev32_invert(0), ref_brev32(0)) - self.assertNotEqual(bad_brev32_invert(0xFFFFFFFF), ref_brev32(0xFFFFFFFF)) - - def test_mutation_abs_unwrapped_overflow_rejected(self): - def bad_abs32(x: int) -> int: - return 0 if x == 0x80000000 else ref_abs32(x) - - self.assertNotEqual(bad_abs32(0x80000000), 0x80000000) - - def test_mutation_simd_inactive_lanes_written_rejected(self): - class MutatedInterpreterNoMask(VectorAluInterpreter): - def is_lane_active(self, lane: int) -> bool: - return True - - interp = MutatedInterpreterNoMask(wave_size=32, initial_exec=0x00000000) - sentinel = 0xDEADBEEF - for lane in range(32): - interp.vgprs[lane][0] = sentinel - interp.vgprs[lane][1] = 100 - - interp.execute_instruction("v_abs_i32", "v0", "v1") - - overwritten_lanes = [lane for lane in range(32) if interp.vgprs[lane][0] != sentinel] - self.assertEqual(len(overwritten_lanes), 32) - - def test_mutation_absdiff_unsigned_sub_rejected(self): - def bad_absdiff_unsigned(x: int, y: int) -> int: - return abs(u32(x) - u32(y)) & MASK32 - - self.assertNotEqual(bad_absdiff_unsigned(0xFFFFFFFF, 1), ref_absdiff32(0xFFFFFFFF, 1)) - - def test_mutation_spirv_opcode_corruption_rejected(self): - corrupted_spv = """OpCapability Shader -OpMemoryModel Logical GLSL450 -OpEntryPoint Fragment %main "main" %out_mrt0 -OpExecutionMode %main OriginUpperLeft -%void = OpTypeVoid -%fn = OpTypeFunction %void -%uint = OpTypeInt 32 0 -%v4uint = OpTypeVector %uint 4 -%_ptr_Output_v4uint = OpTypePointer Output %v4uint -%out_mrt0 = OpVariable %_ptr_Output_v4uint Output -%val = OpConstant %uint 1 -%c0 = OpConstant %uint 0 -%main = OpFunction %void None %fn -%entry = OpLabel -%res = OpInvalidNonExistentOpcode %uint %val -%out = OpCompositeConstruct %v4uint %res %c0 %c0 %c0 -OpStore %out_mrt0 %out -OpReturn -OpFunctionEnd -""" - with self.assertRaises(si.UnsupportedConstruct): - si.run_fragment(corrupted_spv) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_alu_bitwise_swap.py b/tests/semantic/test_alu_bitwise_swap.py deleted file mode 100644 index 10ae1fe72..000000000 --- a/tests/semantic/test_alu_bitwise_swap.py +++ /dev/null @@ -1,473 +0,0 @@ -"""Translator-to-interpreter semantic tests for v_swap_b32, v_xnor_b32, v_or3_b32, and v_xor3_b32. - -RDNA2 ISA: - v_swap_b32 D0, D1 exchange D0 and D1 per active lane (inactive lanes preserve their values) - v_xnor_b32 D, S0, S1 D = ~(S0 ^ S1) - v_or3_b32 D, S0, S1, S2 D = S0 | S1 | S2 - v_xor3_b32 D, S0, S1, S2 D = S0 ^ S1 ^ S2 - -All tests translate synthetic hand-written RDNA2 disassembly via tools/rdna2spirv.py and execute the emitted -SPIR-V in spirv_mini_interp.py (single-lane) and spirv_wave_interp.py (32-lane wave with partial EXEC mask). -Standard library only; no game data. -""" -import os -import random -import re -import sys -import unittest - -HERE = os.path.dirname(os.path.abspath(__file__)) -if HERE not in sys.path: - sys.path.insert(0, HERE) - -import spirv_wave_interp as wi # noqa: E402 -from support import mrt0_words, translate_lines # noqa: E402 - -MASK32 = 0xFFFFFFFF - - -def ref_xnor(a, b): - return (~(a ^ b)) & MASK32 - - -def ref_or3(a, b, c): - return (a | b | c) & MASK32 - - -def ref_xor3(a, b, c): - return (a ^ b ^ c) & MASK32 - - -XNOR_CONSTANTS = [ - (0x00000000, 0x00000000, 0xFFFFFFFF), - (0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF), - (0x00000000, 0xFFFFFFFF, 0x00000000), - (0xFFFFFFFF, 0x00000000, 0x00000000), - (0xAAAAAAAA, 0x55555555, 0x00000000), - (0xAAAAAAAA, 0xAAAAAAAA, 0xFFFFFFFF), - (0x12345678, 0x9ABCDEF0, 0x77777777), - (0x80000000, 0x00000001, 0x7FFFFFFE), - (0xDEADBEEF, 0xCAFEBABE, 0xEBACFBAE), -] - -OR3_CONSTANTS = [ - (0x00000000, 0x00000000, 0x00000000, 0x00000000), - (0x000000FF, 0x0000FF00, 0xFFFF0000, 0xFFFFFFFF), - (0x0000000F, 0x0000000F, 0x000000F0, 0x000000FF), - (0x80000000, 0x00000001, 0x00010000, 0x80010001), - (0x12340000, 0x00005678, 0x00000000, 0x12345678), - (0xAAAAAAAA, 0x55555555, 0x00000000, 0xFFFFFFFF), - (0xDEADBEEF, 0x00000000, 0xFFFFFFFF, 0xFFFFFFFF), -] - -XOR3_CONSTANTS = [ - (0x00000000, 0x00000000, 0x00000000, 0x00000000), - (0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF), - (0xFFFFFFFF, 0xFFFFFFFF, 0x00000000, 0x00000000), - (0x12345678, 0x9ABCDEF0, 0x12345678, 0x9ABCDEF0), - (0xAAAAAAAA, 0x55555555, 0xFFFFFFFF, 0x00000000), - (0x0F0F0F0F, 0x00FF00FF, 0x0000FFFF, 0x0FF0F00F), - (0x80000000, 0x00000001, 0x00000001, 0x80000000), -] - - -def run_ps_lines(name, body_lines, export_regs=("v0", "v0", "v0", "v0")): - lines = list(body_lines) + [f"exp mrt0 {', '.join(export_regs)} done vm", "s_endpgm"] - spv = translate_lines(name, lines) - return mrt0_words(spv), spv - - -class ReferenceConstantsTests(unittest.TestCase): - def test_hand_computed_constants(self): - for a, b, expected in XNOR_CONSTANTS: - with self.subTest(op="xnor", a=hex(a), b=hex(b)): - self.assertEqual(ref_xnor(a, b), expected) - for a, b, c, expected in OR3_CONSTANTS: - with self.subTest(op="or3", a=hex(a), b=hex(b), c=hex(c)): - self.assertEqual(ref_or3(a, b, c), expected) - for a, b, c, expected in XOR3_CONSTANTS: - with self.subTest(op="xor3", a=hex(a), b=hex(b), c=hex(c)): - self.assertEqual(ref_xor3(a, b, c), expected) - - -class VSwapB32Tests(unittest.TestCase): - def test_pair_swap_boundaries(self): - pairs = [ - (0x00000000, 0xFFFFFFFF), - (0x80000000, 0x00000001), - (0x12345678, 0xDEADBEEF), - (0xCAFEBABE, 0xCAFEBABE), - ] - for mnemonic in ("v_swap_b32", "v_swap_b32_e32"): - for a, b in pairs: - with self.subTest(mnemonic=mnemonic, a=hex(a), b=hex(b)): - words, _ = run_ps_lines( - "ps_swap_pair", - [ - f"v_mov_b32 v1, {a:#x}", - f"v_mov_b32 v2, {b:#x}", - f"{mnemonic} v1, v2", - ], - export_regs=("v1", "v2", "v1", "v2"), - ) - self.assertEqual(words, [b, a, b, a]) - - def test_self_swap_is_identity(self): - for val in (0x00000000, 0x80000000, 0x12345678, 0xFFFFFFFF): - with self.subTest(val=hex(val)): - words, _ = run_ps_lines( - "ps_swap_self", - [f"v_mov_b32 v1, {val:#x}", "v_swap_b32 v1, v1"], - export_regs=("v1", "v1", "v1", "v1"), - ) - self.assertEqual(words, [val, val, val, val]) - - def test_double_swap_involution_and_cyclic_rotation(self): - words, _ = run_ps_lines( - "ps_swap_double", - [ - "v_mov_b32 v1, 0x11223344", - "v_mov_b32 v2, 0xAABBCCDD", - "v_swap_b32 v1, v2", - "v_swap_b32 v1, v2", - ], - export_regs=("v1", "v2", "v1", "v2"), - ) - self.assertEqual(words, [0x11223344, 0xAABBCCDD, 0x11223344, 0xAABBCCDD]) - - rot_words, _ = run_ps_lines( - "ps_swap_cycle", - [ - "v_mov_b32 v1, 0x11111111", - "v_mov_b32 v2, 0x22222222", - "v_mov_b32 v3, 0x33333333", - "v_swap_b32 v1, v2", - "v_swap_b32 v2, v3", - ], - export_regs=("v1", "v2", "v3", "v3"), - ) - self.assertEqual(rot_words, [0x22222222, 0x33333333, 0x11111111, 0x11111111]) - - def test_partial_exec_mask_wave32_via_exec_const(self): - masks = (0xA55A0F0F, 0x00000001, 0x80000000, 0x00000000, 0xFFFFFFFF) - for mask in masks: - with self.subTest(mask=hex(mask)): - spv = translate_lines( - "ps_swap_exec_mask", - [ - "v_mbcnt_lo_u32_b32 v0, -1, 0", - "v_add_nc_u32 v1, 0x1000, v0", - "v_add_nc_u32 v2, 0x2000, v0", - "s_mov_b32 s1, exec_lo", - f"s_mov_b32 exec_lo, {mask:#x}", - "v_swap_b32 v1, v2", - "s_mov_b32 exec_lo, s1", - "exp mrt0 v1, v2, v0, v0 done vm", - "s_endpgm", - ], - ) - outputs = wi.run_wave(spv, wave=32)["outputs"] - self.assertEqual(len(outputs), 32) - for lane, out in enumerate(outputs): - self.assertIsNotNone(out) - v1_got, v2_got, lane_got, _ = out["%out_mrt0"] - self.assertEqual(lane_got, lane) - a = 0x1000 + lane - b = 0x2000 + lane - if (mask >> lane) & 1: - self.assertEqual((v1_got, v2_got), (b, a), f"lane {lane} active") - else: - self.assertEqual((v1_got, v2_got), (a, b), f"lane {lane} inactive") - - def test_partial_exec_mask_wave32_via_vcmp(self): - spv = translate_lines( - "ps_swap_vcmp_exec", - [ - "v_mbcnt_lo_u32_b32 v0, -1, 0", - "v_add_nc_u32 v1, 0x3000, v0", - "v_add_nc_u32 v2, 0x4000, v0", - "v_and_b32_e32 v3, 1, v0", - "v_cmp_eq_u32_e32 vcc_lo, 0, v3", - "s_mov_b32 s1, exec_lo", - "s_and_b32 exec_lo, exec_lo, vcc_lo", - "v_swap_b32 v1, v2", - "s_mov_b32 exec_lo, s1", - "exp mrt0 v1, v2, v0, v0 done vm", - "s_endpgm", - ], - ) - outputs = wi.run_wave(spv, wave=32)["outputs"] - for lane, out in enumerate(outputs): - self.assertIsNotNone(out) - v1_got, v2_got, lane_got, _ = out["%out_mrt0"] - self.assertEqual(lane_got, lane) - a = 0x3000 + lane - b = 0x4000 + lane - if lane % 2 == 0: - self.assertEqual((v1_got, v2_got), (b, a)) - else: - self.assertEqual((v1_got, v2_got), (a, b)) - - -class VXnorB32Tests(unittest.TestCase): - def test_boundary_constants(self): - for a, b, expected in XNOR_CONSTANTS: - with self.subTest(a=hex(a), b=hex(b)): - words, _ = run_ps_lines( - "ps_xnor_const", - [f"v_mov_b32 v1, {a:#x}", f"v_mov_b32 v2, {b:#x}", "v_xnor_b32 v0, v1, v2"], - ) - self.assertEqual(words[0], expected) - - def test_algebraic_identities_and_commutativity(self): - for x in (0x00000000, 0x00000001, 0x12345678, 0x80000000, 0xFFFFFFFF): - inv_x = (~x) & MASK32 - with self.subTest(x=hex(x)): - w_self, _ = run_ps_lines( - "ps_xnor_id", [f"v_mov_b32 v1, {x:#x}", "v_xnor_b32 v0, v1, v1"] - ) - self.assertEqual(w_self[0], MASK32) - w_comp, _ = run_ps_lines( - "ps_xnor_comp", - [f"v_mov_b32 v1, {x:#x}", f"v_mov_b32 v2, {inv_x:#x}", "v_xnor_b32 v0, v1, v2"], - ) - self.assertEqual(w_comp[0], 0) - w_zero, _ = run_ps_lines( - "ps_xnor_zero", [f"v_mov_b32 v1, {x:#x}", "v_xnor_b32 v0, v1, 0"] - ) - self.assertEqual(w_zero[0], inv_x) - w_ones, _ = run_ps_lines( - "ps_xnor_ones", [f"v_mov_b32 v1, {x:#x}", "v_xnor_b32 v0, v1, -1"] - ) - self.assertEqual(w_ones[0], x) - - a, b = 0x13579BDF, 0x2468ACE0 - w_ab, _ = run_ps_lines( - "ps_xnor_ab", [f"v_mov_b32 v1, {a:#x}", f"v_mov_b32 v2, {b:#x}", "v_xnor_b32 v0, v1, v2"] - ) - w_ba, _ = run_ps_lines( - "ps_xnor_ba", [f"v_mov_b32 v1, {a:#x}", f"v_mov_b32 v2, {b:#x}", "v_xnor_b32 v0, v2, v1"] - ) - self.assertEqual(w_ab[0], w_ba[0]) - self.assertEqual(w_ab[0], ref_xnor(a, b)) - - def test_operand_forms_sgpr_inline_literal(self): - cases = [ - (["s_mov_b32 s0, 0x12345678", "v_mov_b32 v1, 0xF0F0F0F0", "v_xnor_b32 v0, s0, v1"], 0x12345678, 0xF0F0F0F0), - (["v_mov_b32 v1, 0x00FF00FF", "v_xnor_b32 v0, 15, v1"], 15, 0x00FF00FF), - (["v_mov_b32 v1, 0xCAFEBABE", "v_xnor_b32 v0, 0xDEADBEEF, v1"], 0xDEADBEEF, 0xCAFEBABE), - (["v_mov_b32 v1, 0xCAFEBABE", "v_xnor_b32_e32 v0, 0xDEADBEEF, v1"], 0xDEADBEEF, 0xCAFEBABE), - ] - for lines, a, b in cases: - with self.subTest(inst=lines[-1]): - words, _ = run_ps_lines("ps_xnor_forms", lines) - self.assertEqual(words[0], ref_xnor(a, b)) - - def test_seeded_random_pairs(self): - rng = random.Random(0x584E4F52) - for _ in range(12): - a = rng.getrandbits(32) - b = rng.getrandbits(32) - with self.subTest(a=hex(a), b=hex(b)): - words, _ = run_ps_lines( - "ps_xnor_rand", - [f"v_mov_b32 v1, {a:#x}", f"v_mov_b32 v2, {b:#x}", "v_xnor_b32 v0, v1, v2"], - ) - self.assertEqual(words[0], ref_xnor(a, b)) - - -class VOr3B32Tests(unittest.TestCase): - def test_boundary_constants(self): - for a, b, c, expected in OR3_CONSTANTS: - with self.subTest(a=hex(a), b=hex(b), c=hex(c)): - words, _ = run_ps_lines( - "ps_or3_const", - [ - f"v_mov_b32 v1, {a:#x}", - f"v_mov_b32 v2, {b:#x}", - f"v_mov_b32 v3, {c:#x}", - "v_or3_b32 v0, v1, v2, v3", - ], - ) - self.assertEqual(words[0], expected) - - def test_permutation_invariance_and_operand_mixes(self): - a, b, c = 0x0F000001, 0x00F00010, 0x000F0100 - expected = ref_or3(a, b, c) - for s0, s1, s2 in (("v1", "v2", "v3"), ("v2", "v3", "v1"), ("v3", "v1", "v2")): - with self.subTest(order=(s0, s1, s2)): - words, _ = run_ps_lines( - "ps_or3_perm", - [ - f"v_mov_b32 v1, {a:#x}", - f"v_mov_b32 v2, {b:#x}", - f"v_mov_b32 v3, {c:#x}", - f"v_or3_b32 v0, {s0}, {s1}, {s2}", - ], - ) - self.assertEqual(words[0], expected) - - mix_words, _ = run_ps_lines( - "ps_or3_mix", - [ - "s_mov_b32 s0, 0xF0000000", - "v_mov_b32 v1, 0x00FF0000", - "v_or3_b32 v0, s0, v1, 7", - ], - ) - self.assertEqual(mix_words[0], ref_or3(0xF0000000, 0x00FF0000, 7)) - - lit_words, _ = run_ps_lines( - "ps_or3_lit", - [ - "v_mov_b32 v1, 0x0000FF00", - "v_mov_b32 v2, 0x000000FF", - "v_or3_b32 v0, 0xCAFE0000, v1, v2", - ], - ) - self.assertEqual(lit_words[0], 0xCAFEFFFF) - - def test_seeded_random_triples(self): - rng = random.Random(0x4F523332) - for _ in range(12): - a = rng.getrandbits(32) - b = rng.getrandbits(32) - c = rng.getrandbits(32) - with self.subTest(a=hex(a), b=hex(b), c=hex(c)): - words, _ = run_ps_lines( - "ps_or3_rand", - [ - f"v_mov_b32 v1, {a:#x}", - f"v_mov_b32 v2, {b:#x}", - f"v_mov_b32 v3, {c:#x}", - "v_or3_b32 v0, v1, v2, v3", - ], - ) - self.assertEqual(words[0], ref_or3(a, b, c)) - - -class VXor3B32Tests(unittest.TestCase): - def test_boundary_constants(self): - for a, b, c, expected in XOR3_CONSTANTS: - with self.subTest(a=hex(a), b=hex(b), c=hex(c)): - words, _ = run_ps_lines( - "ps_xor3_const", - [ - f"v_mov_b32 v1, {a:#x}", - f"v_mov_b32 v2, {b:#x}", - f"v_mov_b32 v3, {c:#x}", - "v_xor3_b32 v0, v1, v2, v3", - ], - ) - self.assertEqual(words[0], expected) - - def test_cancellation_and_permutation_identities(self): - x, y = 0x12345678, 0xDEADBEEF - w_cancel, _ = run_ps_lines( - "ps_xor3_cancel", - [f"v_mov_b32 v1, {x:#x}", f"v_mov_b32 v2, {y:#x}", "v_xor3_b32 v0, v1, v2, v2"], - ) - self.assertEqual(w_cancel[0], x) - - w_triple, _ = run_ps_lines( - "ps_xor3_triple", - [f"v_mov_b32 v1, {x:#x}", "v_xor3_b32 v0, v1, v1, v1"], - ) - self.assertEqual(w_triple[0], x) - - w_zero, _ = run_ps_lines( - "ps_xor3_zero", - [f"v_mov_b32 v1, {x:#x}", f"v_mov_b32 v2, {y:#x}", "v_xor3_b32 v0, v1, v2, 0"], - ) - self.assertEqual(w_zero[0], x ^ y) - - c = 0x0F0F0F0F - expected = ref_xor3(x, y, c) - for s0, s1, s2 in (("v1", "v2", "v3"), ("v2", "v3", "v1"), ("v3", "v1", "v2")): - with self.subTest(order=(s0, s1, s2)): - words, _ = run_ps_lines( - "ps_xor3_perm", - [ - f"v_mov_b32 v1, {x:#x}", - f"v_mov_b32 v2, {y:#x}", - f"v_mov_b32 v3, {c:#x}", - f"v_xor3_b32 v0, {s0}, {s1}, {s2}", - ], - ) - self.assertEqual(words[0], expected) - - def test_operand_mixes_and_seeded_random_triples(self): - mix_words, _ = run_ps_lines( - "ps_xor3_mix", - [ - "s_mov_b32 s0, 0x12340000", - "v_mov_b32 v1, 0x00005678", - "v_xor3_b32 v0, s0, v1, 15", - ], - ) - self.assertEqual(mix_words[0], ref_xor3(0x12340000, 0x00005678, 15)) - - lit_words, _ = run_ps_lines( - "ps_xor3_lit", - [ - "v_mov_b32 v1, 0xFFFF0000", - "v_mov_b32 v2, 0x0000FFFF", - "v_xor3_b32 v0, 0xA5A5A5A5, v1, v2", - ], - ) - self.assertEqual(lit_words[0], ref_xor3(0xA5A5A5A5, 0xFFFF0000, 0x0000FFFF)) - - rng = random.Random(0x584F5233) - for _ in range(12): - a = rng.getrandbits(32) - b = rng.getrandbits(32) - c = rng.getrandbits(32) - with self.subTest(a=hex(a), b=hex(b), c=hex(c)): - words, _ = run_ps_lines( - "ps_xor3_rand", - [ - f"v_mov_b32 v1, {a:#x}", - f"v_mov_b32 v2, {b:#x}", - f"v_mov_b32 v3, {c:#x}", - "v_xor3_b32 v0, v1, v2, v3", - ], - ) - self.assertEqual(words[0], ref_xor3(a, b, c)) - - -class SpirvStructureTests(unittest.TestCase): - def test_swap_emits_op_copy_object(self): - _, spv = run_ps_lines( - "ps_struct_swap", - ["v_mov_b32 v1, 1", "v_mov_b32 v2, 2", "v_swap_b32 v1, v2"], - export_regs=("v1", "v2", "v1", "v2"), - ) - self.assertGreaterEqual(spv.count("= OpCopyObject %uint"), 2) - - def test_xnor_emits_op_not_after_op_bitwise_xor(self): - _, spv = run_ps_lines( - "ps_struct_xnor", - ["v_mov_b32 v1, 1", "v_mov_b32 v2, 2", "v_xnor_b32 v0, v1, v2"], - ) - match = re.search(r"(%\w+)\s*=\s*OpBitwiseXor %uint.*\n\s*(%\w+)\s*=\s*OpNot %uint \1\b", spv) - self.assertIsNotNone(match, "expected OpNot %uint directly consuming OpBitwiseXor result") - - def test_or3_and_xor3_emit_chained_bitwise_ops(self): - _, spv_or = run_ps_lines( - "ps_struct_or3", - ["v_mov_b32 v1, 1", "v_mov_b32 v2, 2", "v_mov_b32 v3, 4", "v_or3_b32 v0, v1, v2, v3"], - ) - self.assertIsNotNone( - re.search(r"(%\w+)\s*=\s*OpBitwiseOr %uint.*\n\s*%\w+\s*=\s*OpBitwiseOr %uint \1\b", spv_or) - ) - _, spv_xor = run_ps_lines( - "ps_struct_xor3", - ["v_mov_b32 v1, 1", "v_mov_b32 v2, 2", "v_mov_b32 v3, 4", "v_xor3_b32 v0, v1, v2, v3"], - ) - self.assertIsNotNone( - re.search(r"(%\w+)\s*=\s*OpBitwiseXor %uint.*\n\s*%\w+\s*=\s*OpBitwiseXor %uint \1\b", spv_xor) - ) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_alu_clz_ctz.py b/tests/semantic/test_alu_clz_ctz.py deleted file mode 100644 index e039f2a63..000000000 --- a/tests/semantic/test_alu_clz_ctz.py +++ /dev/null @@ -1,508 +0,0 @@ -"""Semantic interpreter tests for bit counting instructions: - - v_clz_i32_u32 / v_ffbh_u32 / s_flbit_i32_b32: count leading zeros - - v_ctz_i32_b32 / v_ffbl_b32 / s_ff1_i32_b32: count trailing zeros - - v_cls_i32 / v_ffbh_i32: count leading sign bits / first differing sign bit - -Covers: - * Bit-exact reference oracles for CLZ, CTZ, and CLS - * Distinction between mathematical/architectural (CLZ=32, CTZ=32 on 0) vs - AMD RDNA hardware/SPIR-V conventions (0xFFFFFFFF on 0 or all-identical sign bits) - * Direct SPIR-V GLSL.std.450 FindUMsb, FindILsb, FindSMsb interpreter validation - * Full translation and execution through rdna2spirv and spirv_mini_interp - * Exhaustive single-bit sweeps across all 32 bit positions (1 << i) - * Boundary values: 0, 0xFFFFFFFF, 0x80000000, 0x7FFFFFFF, 0x80000001, 0x7FFFFFFE - * Inverted single-bit masks, alternating bit patterns, and byte-boundary values - * Bit reversal identity: clz(bit_reverse(x)) == ctz(x) for all non-zero x - * Multi-lane SIMD wave simulation across 64 lanes -Standard library Python only; zero game data. -""" -from __future__ import annotations - -import os -import struct -import sys -import tempfile -import unittest -import warnings - -HERE = os.path.dirname(os.path.abspath(__file__)) -ROOT = os.path.dirname(os.path.dirname(HERE)) -TOOLS_DIR = os.environ.get("LEONIDA_TOOLS_DIR") or os.path.join(ROOT, "tools") - -sys.dont_write_bytecode = True -if TOOLS_DIR not in sys.path: - sys.path.insert(0, TOOLS_DIR) -if HERE not in sys.path: - sys.path.insert(0, HERE) - -import rdna2spirv # noqa: E402 -import spirv_mini_interp as si # noqa: E402 - -MASK32 = 0xFFFFFFFF -SIGN32 = 0x80000000 -STUB_DXBC = b"DXBC" + bytes(24) + struct.pack(" int: - """Interpret raw 32-bit integer as signed two's complement.""" - x &= MASK32 - return x - (1 << 32) if x & SIGN32 else x - - -def u32(x: int) -> int: - """Interpret raw integer as unsigned 32-bit word.""" - return x & MASK32 - - -def bit_reverse32(x: int) -> int: - """32-bit bit reversal helper.""" - return int(f"{x & MASK32:032b}"[::-1], 2) - - -def interp_v_clz_i32_u32(val: int, zero_value: int = 32) -> int: - """Reference interpreter for Count Leading Zeros (v_clz_i32_u32). - - Counts the number of leading zero bits from MSB (bit 31) down to the first set bit. - zero_value defaults to 32 (standard arithmetic/LLVM ctlz); AMD hardware v_ffbh_u32 returns 0xFFFFFFFF (-1). - """ - val &= MASK32 - if val == 0: - return zero_value - return 32 - val.bit_length() - - -def interp_v_ctz_i32_b32(val: int, zero_value: int = 32) -> int: - """Reference interpreter for Count Trailing Zeros (v_ctz_i32_b32). - - Counts the number of trailing zero bits from LSB (bit 0) up to the first set bit. - zero_value defaults to 32 (standard arithmetic/LLVM cttz); AMD hardware v_ffbl_b32 returns 0xFFFFFFFF (-1). - """ - val &= MASK32 - if val == 0: - return zero_value - return (val & -val).bit_length() - 1 - - -def interp_v_cls_i32(val: int, all_match_value: int = 31) -> int: - """Reference interpreter for Count Leading Sign bits (v_cls_i32). - - Counts consecutive bits following bit 31 that match the sign bit. - Returns count in range 0..30 (or all_match_value when all bits match sign bit). - all_match_value defaults to 31 (architectural count of redundant sign bits). - """ - val &= MASK32 - sign = (val >> 31) & 1 - match_count = 0 - for i in range(30, -1, -1): - bit = (val >> i) & 1 - if bit == sign: - match_count += 1 - else: - return match_count - return all_match_value - - -def interp_v_ffbh_u32(val: int) -> int: - """RDNA2 hardware find first bit high (unsigned): 31 - FindUMsb(val), or 0xFFFFFFFF if 0.""" - return interp_v_clz_i32_u32(val, zero_value=MASK32) - - -def interp_v_ffbl_b32(val: int) -> int: - """RDNA2 hardware find first bit low: FindILsb(val), or 0xFFFFFFFF if 0.""" - return interp_v_ctz_i32_b32(val, zero_value=MASK32) - - -def interp_v_ffbh_i32(val: int) -> int: - """RDNA2 hardware find first bit high (signed): bit position from MSB of first differing bit, or 0xFFFFFFFF.""" - val &= MASK32 - s = s32(val) - if s in (0, -1): - return MASK32 - f = s.bit_length() - 1 if s > 0 else (~s).bit_length() - 1 - return (31 - f) & MASK32 - - -_TMP_DIR = None -_SRC_PATH = None - - -def setUpModule(): - global _TMP_DIR, _SRC_PATH - _TMP_DIR = tempfile.TemporaryDirectory() - disasm_dir = os.path.join(_TMP_DIR.name, "disasm") - os.mkdir(disasm_dir) - _SRC_PATH = os.path.join(disasm_dir, "ps_clz_ctz.s") - with open(os.path.join(_TMP_DIR.name, "ps_clz_ctz.dxbc"), "wb") as f: - f.write(STUB_DXBC) - - -def tearDownModule(): - global _TMP_DIR - if _TMP_DIR is not None: - _TMP_DIR.cleanup() - _TMP_DIR = None - - -def run_asm(lines: list[str]) -> tuple[int, int]: - """Assemble and run shader lines, exporting v0 and v1 to mrt0.""" - if _TMP_DIR is None: - setUpModule() - asm = "; ps_clz_ctz\n" + "".join(f"\t{ln}\n" for ln in lines) + "\texp mrt0 v0, v1, v0, v0 done vm\n\ts_endpgm\n" - with open(_SRC_PATH, "w", encoding="utf-8") as f: - f.write(asm) - with warnings.catch_warnings(): - warnings.simplefilter("ignore", ResourceWarning) - spv = rdna2spirv.translate(_SRC_PATH) - res = si.run_fragment(spv)["%out_mrt0"] - return res[0], res[1] - - -def run_spirv_clz(val: int, hw_zero: bool = True) -> int: - """Directly executes SPIR-V Count Leading Zeros sequence using GLSL FindUMsb.""" - zero_ret = MASK32 if hw_zero else 32 - module = f"""\ -OpCapability Shader -%glsl = OpExtInstImport "GLSL.std.450" -OpMemoryModel Logical GLSL450 -OpEntryPoint Fragment %main "main" %out -%void = OpTypeVoid -%fn = OpTypeFunction %void -%uint = OpTypeInt 32 0 -%int = OpTypeInt 32 1 -%bool = OpTypeBool -%_ptr_Output_uint = OpTypePointer Output %uint -%out = OpVariable %_ptr_Output_uint Output -%c_in = OpConstant %uint {val & MASK32} -%c0 = OpConstant %uint 0 -%c31 = OpConstant %uint 31 -%c_zero_ret = OpConstant %uint {zero_ret} -%main = OpFunction %void None %fn -%entry = OpLabel -%m = OpExtInst %int %glsl FindUMsb %c_in -%mu = OpBitcast %uint %m -%d = OpISub %uint %c31 %mu -%z = OpIEqual %bool %c_in %c0 -%res = OpSelect %uint %z %c_zero_ret %d -OpStore %out %res -OpReturn -OpFunctionEnd -""" - return si.run_fragment(module)["%out"][0] - - -def run_spirv_ctz(val: int, hw_zero: bool = True) -> int: - """Directly executes SPIR-V Count Trailing Zeros sequence using GLSL FindILsb.""" - zero_ret = MASK32 if hw_zero else 32 - module = f"""\ -OpCapability Shader -%glsl = OpExtInstImport "GLSL.std.450" -OpMemoryModel Logical GLSL450 -OpEntryPoint Fragment %main "main" %out -%void = OpTypeVoid -%fn = OpTypeFunction %void -%uint = OpTypeInt 32 0 -%int = OpTypeInt 32 1 -%bool = OpTypeBool -%_ptr_Output_uint = OpTypePointer Output %uint -%out = OpVariable %_ptr_Output_uint Output -%c_in = OpConstant %uint {val & MASK32} -%c0 = OpConstant %uint 0 -%c_zero_ret = OpConstant %uint {zero_ret} -%main = OpFunction %void None %fn -%entry = OpLabel -%ri = OpExtInst %int %glsl FindILsb %c_in -%ru = OpBitcast %uint %ri -%z = OpIEqual %bool %c_in %c0 -%res = OpSelect %uint %z %c_zero_ret %ru -OpStore %out %res -OpReturn -OpFunctionEnd -""" - return si.run_fragment(module)["%out"][0] - - -def run_spirv_cls(val: int, hw_semantics: bool = True) -> int: - """Directly executes SPIR-V Count Leading Sign sequence using GLSL FindSMsb.""" - base_val = 31 if hw_semantics else 30 - none_val = MASK32 if hw_semantics else 31 - module = f"""\ -OpCapability Shader -%glsl = OpExtInstImport "GLSL.std.450" -OpMemoryModel Logical GLSL450 -OpEntryPoint Fragment %main "main" %out -%void = OpTypeVoid -%fn = OpTypeFunction %void -%uint = OpTypeInt 32 0 -%int = OpTypeInt 32 1 -%bool = OpTypeBool -%_ptr_Output_uint = OpTypePointer Output %uint -%out = OpVariable %_ptr_Output_uint Output -%c_in = OpConstant %uint {val & MASK32} -%c0_i = OpConstant %int 0 -%c31_i = OpConstant %int 31 -%c30_i = OpConstant %int 30 -%c_none = OpConstant %uint {none_val} -%base = OpConstant %int {base_val} -%main = OpFunction %void None %fn -%entry = OpLabel -%i = OpBitcast %int %c_in -%f = OpExtInst %int %glsl FindSMsb %i -%none = OpSLessThan %bool %f %c0_i -%sub = OpISub %int %base %f -%subu = OpBitcast %uint %sub -%res = OpSelect %uint %none %c_none %subu -OpStore %out %res -OpReturn -OpFunctionEnd -""" - return si.run_fragment(module)["%out"][0] - - -class TestBitCountingReferenceSemantics(unittest.TestCase): - """Unit tests verifying mathematical and architectural reference models.""" - - def test_clz_powers_of_two(self): - for bit in range(32): - val = 1 << bit - expected_zeros = 31 - bit - with self.subTest(bit=bit, val=hex(val)): - self.assertEqual(interp_v_clz_i32_u32(val), expected_zeros) - self.assertEqual(interp_v_ffbh_u32(val), expected_zeros) - - def test_ctz_powers_of_two(self): - for bit in range(32): - val = 1 << bit - expected_zeros = bit - with self.subTest(bit=bit, val=hex(val)): - self.assertEqual(interp_v_ctz_i32_b32(val), expected_zeros) - self.assertEqual(interp_v_ffbl_b32(val), expected_zeros) - - def test_clz_ctz_zero_handling(self): - # Standard arithmetic convention - self.assertEqual(interp_v_clz_i32_u32(0, zero_value=32), 32) - self.assertEqual(interp_v_ctz_i32_b32(0, zero_value=32), 32) - # Hardware RDNA / SPIR-V convention - self.assertEqual(interp_v_clz_i32_u32(0, zero_value=MASK32), MASK32) - self.assertEqual(interp_v_ctz_i32_b32(0, zero_value=MASK32), MASK32) - self.assertEqual(interp_v_ffbh_u32(0), MASK32) - self.assertEqual(interp_v_ffbl_b32(0), MASK32) - - def test_clz_ctz_all_ones(self): - self.assertEqual(interp_v_clz_i32_u32(MASK32), 0) - self.assertEqual(interp_v_ctz_i32_b32(MASK32), 0) - self.assertEqual(interp_v_ffbh_u32(MASK32), 0) - self.assertEqual(interp_v_ffbl_b32(MASK32), 0) - - def test_cls_positive_values(self): - # 0x40000000: sign=0, bit 30=1 -> 0 redundant sign bits; distance from MSB = 1 - self.assertEqual(interp_v_cls_i32(0x40000000), 0) - self.assertEqual(interp_v_ffbh_i32(0x40000000), 1) - - # 0x20000000: sign=0, bit 30=0, bit 29=1 -> 1 redundant sign bit; distance from MSB = 2 - self.assertEqual(interp_v_cls_i32(0x20000000), 1) - self.assertEqual(interp_v_ffbh_i32(0x20000000), 2) - - # 0x00000001: bit 0=1, bits 30..1=0 -> 30 redundant sign bits; distance from MSB = 31 - self.assertEqual(interp_v_cls_i32(0x00000001), 30) - self.assertEqual(interp_v_ffbh_i32(0x00000001), 31) - - def test_cls_negative_values(self): - # 0x80000000 (-2147483648): sign=1, bit 30=0 -> 0 redundant sign bits; distance = 1 - self.assertEqual(interp_v_cls_i32(0x80000000), 0) - self.assertEqual(interp_v_ffbh_i32(0x80000000), 1) - - # 0xC0000000 (-1073741824): sign=1, bit 30=1, bit 29=0 -> 1 redundant sign bit; distance = 2 - self.assertEqual(interp_v_cls_i32(0xC0000000), 1) - self.assertEqual(interp_v_ffbh_i32(0xC0000000), 2) - - # 0xFFFFFFFE (-2): sign=1, bit 0=0, bits 30..1=1 -> 30 redundant sign bits; distance = 31 - self.assertEqual(interp_v_cls_i32(0xFFFFFFFE), 30) - self.assertEqual(interp_v_ffbh_i32(0xFFFFFFFE), 31) - - def test_cls_uniform_values(self): - # 0x00000000: all bits 0 (all match sign bit) - self.assertEqual(interp_v_cls_i32(0, all_match_value=31), 31) - self.assertEqual(interp_v_ffbh_i32(0), MASK32) - - # 0xFFFFFFFF: all bits 1 (all match sign bit) - self.assertEqual(interp_v_cls_i32(MASK32, all_match_value=31), 31) - self.assertEqual(interp_v_ffbh_i32(MASK32), MASK32) - - def test_bit_reverse_symmetry(self): - test_patterns = [ - 0x1, 0x2, 0x12345678, 0x80000000, 0x0F000000, 0x000000F0, - 0x55555555, 0xAAAAAAAA, 0x7FFFFFFF, 0x0000FFFF, 0xFFFF0000, - 0x00000100, 0x00800000, 0x01010101, 0x80808080, - ] - for p in test_patterns: - with self.subTest(pattern=hex(p)): - rev = bit_reverse32(p) - # clz of reversed == ctz of original - self.assertEqual(interp_v_clz_i32_u32(rev), interp_v_ctz_i32_b32(p)) - self.assertEqual(interp_v_clz_i32_u32(p), interp_v_ctz_i32_b32(rev)) - - -class TestSpirvMiniInterpBitCounting(unittest.TestCase): - """Direct SPIR-V mini interpreter verification for FindUMsb, FindILsb, and FindSMsb.""" - - def test_spirv_clz_single_bits(self): - for bit in range(32): - val = 1 << bit - with self.subTest(bit=bit): - expected = 31 - bit - self.assertEqual(run_spirv_clz(val, hw_zero=True), expected) - self.assertEqual(run_spirv_clz(val, hw_zero=False), expected) - - def test_spirv_ctz_single_bits(self): - for bit in range(32): - val = 1 << bit - with self.subTest(bit=bit): - expected = bit - self.assertEqual(run_spirv_ctz(val, hw_zero=True), expected) - self.assertEqual(run_spirv_ctz(val, hw_zero=False), expected) - - def test_spirv_clz_ctz_zero(self): - self.assertEqual(run_spirv_clz(0, hw_zero=True), MASK32) - self.assertEqual(run_spirv_clz(0, hw_zero=False), 32) - self.assertEqual(run_spirv_ctz(0, hw_zero=True), MASK32) - self.assertEqual(run_spirv_ctz(0, hw_zero=False), 32) - - def test_spirv_cls_patterns(self): - patterns = [ - (0x40000000, 1, 0), - (0x20000000, 2, 1), - (0x10000000, 3, 2), - (0x00000001, 31, 30), - (0x80000000, 1, 0), - (0xC0000000, 2, 1), - (0xE0000000, 3, 2), - (0xFFFFFFFE, 31, 30), - (0x00000000, MASK32, 31), - (0xFFFFFFFF, MASK32, 31), - ] - for val, hw_exp, arch_exp in patterns: - with self.subTest(val=hex(val)): - self.assertEqual(run_spirv_cls(val, hw_semantics=True), hw_exp) - self.assertEqual(run_spirv_cls(val, hw_semantics=False), arch_exp) - - def test_spirv_composite_masks(self): - cases = [ - (0xF0F0F0F0, 0, 4), - (0x0F0F0F0F, 4, 0), - (0x00FF0000, 8, 16), - (0x0000FF00, 16, 8), - (0x000000FF, 24, 0), - (0xFF000000, 0, 24), - ] - for val, exp_clz, exp_ctz in cases: - with self.subTest(val=hex(val)): - self.assertEqual(run_spirv_clz(val), exp_clz) - self.assertEqual(run_spirv_ctz(val), exp_ctz) - - -class TestRdna2SpirvEndToEndExecution(unittest.TestCase): - """End-to-end translation of RDNA assembly via rdna2spirv and execution in spirv_mini_interp.""" - - def test_v_ffbh_u32_and_v_ffbl_b32_all_bits(self): - for bit in range(32): - val = 1 << bit - with self.subTest(bit=bit, val=hex(val)): - lines = [ - f"v_mov_b32 v2, {val:#x}", - "v_ffbh_u32 v0, v2", - "v_ffbl_b32 v1, v2", - ] - clz_res, ctz_res = run_asm(lines) - self.assertEqual(clz_res, 31 - bit) - self.assertEqual(ctz_res, bit) - - def test_v_ffbh_u32_and_v_ffbl_b32_inverted_bits(self): - for bit in range(32): - val = (~(1 << bit)) & MASK32 - with self.subTest(bit=bit, val=hex(val)): - lines = [ - f"v_mov_b32 v2, {val:#x}", - "v_ffbh_u32 v0, v2", - "v_ffbl_b32 v1, v2", - ] - clz_res, ctz_res = run_asm(lines) - self.assertEqual(clz_res, interp_v_ffbh_u32(val)) - self.assertEqual(ctz_res, interp_v_ffbl_b32(val)) - - def test_v_ffbh_u32_and_v_ffbl_b32_boundaries(self): - values = [ - 0, MASK32, 0x7FFFFFFF, 0x80000000, 0x80000001, 0x7FFFFFFE, - 0x12345678, 0xEDB88320, 0x55555555, 0xAAAAAAAA, 0x0000FFFF, 0xFFFF0000, - ] - for val in values: - with self.subTest(val=hex(val)): - lines = [ - f"v_mov_b32 v2, {val:#x}", - "v_ffbh_u32 v0, v2", - "v_ffbl_b32 v1, v2", - ] - clz_res, ctz_res = run_asm(lines) - self.assertEqual(clz_res, interp_v_ffbh_u32(val)) - self.assertEqual(ctz_res, interp_v_ffbl_b32(val)) - - def test_v_ffbh_i32_signed_boundaries(self): - values = [ - 0, MASK32, 0x40000000, 0x20000000, 0x10000000, 0x00000001, - 0x80000000, 0xC0000000, 0xE0000000, 0xFFFFFFFE, - 0x7FFFFFFF, 0x0000FFFF, 0xFFFF0000, 0x55555555, 0xAAAAAAAA, - ] - for val in values: - with self.subTest(val=hex(val)): - lines = [ - f"v_mov_b32 v2, {val:#x}", - "v_ffbh_i32 v0, v2", - "v_mov_b32 v1, 0", - ] - cls_res, _ = run_asm(lines) - self.assertEqual(cls_res, interp_v_ffbh_i32(val)) - - def test_scalar_s_flbit_and_s_ff1(self): - values = [0, 1, 2, 0x80000000, 0x7FFFFFFF, 0xFFFFFFFF, 0x00008000] - for val in values: - with self.subTest(val=hex(val)): - lines = [ - f"s_mov_b32 s2, {val:#x}", - "s_flbit_i32_b32 s0, s2", - "s_ff1_i32_b32 s1, s2", - "v_mov_b32 v0, s0", - "v_mov_b32 v1, s1", - ] - clz_res, ctz_res = run_asm(lines) - self.assertEqual(clz_res, interp_v_ffbh_u32(val)) - self.assertEqual(ctz_res, interp_v_ffbl_b32(val)) - - -class TestWaveLaneSimulation(unittest.TestCase): - """Simulate 64-lane wave vector execution of bit-counting operations.""" - - def test_64_lane_simd_clz_ctz(self): - lane_values = [] - for lane in range(64): - # Alternating bit allocations across lanes - if lane < 32: - lane_values.append(1 << lane) - else: - lane_values.append((1 << (63 - lane)) | (1 << ((lane * 3) % 32))) - - for lane, val in enumerate(lane_values): - with self.subTest(lane=lane, val=hex(val)): - clz_want = interp_v_clz_i32_u32(val) - ctz_want = interp_v_ctz_i32_b32(val) - cls_want = interp_v_cls_i32(val) - - clz_got = run_spirv_clz(val, hw_zero=False) - ctz_got = run_spirv_ctz(val, hw_zero=False) - cls_got = run_spirv_cls(val, hw_semantics=False) - - self.assertEqual(clz_got, clz_want) - self.assertEqual(ctz_got, ctz_want) - self.assertEqual(cls_got, cls_want) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_alu_cmp_class_f16_f64.py b/tests/semantic/test_alu_cmp_class_f16_f64.py deleted file mode 100644 index f635a885d..000000000 --- a/tests/semantic/test_alu_cmp_class_f16_f64.py +++ /dev/null @@ -1,249 +0,0 @@ -"""Semantic interpreter + spirv-val tests for RDNA2 v_cmp(x)_class_f16 and v_cmp(x)_class_f64. - -Tests all 10 IEEE-754 class mask bits (0: sNaN, 1: qNaN, 2: -inf, 3: -normal, 4: -denormal, -5: -0, 6: +0, 7: +denormal, 8: +normal, 9: +inf), combined masks, op_sel[0] on f16, abs/neg -modifiers (including preserving sNaN without quieting), 32-bit literal upper-word rule on f64, -v_cmpx EXEC narrowing, absence of OpCapability Float64, and spirv-val validation. -""" -import os -import shutil -import struct -import subprocess -import sys -import tempfile -import unittest -import warnings - -HERE = os.path.dirname(os.path.abspath(__file__)) -ROOT = os.path.dirname(os.path.dirname(HERE)) -TOOLS_DIR = os.environ.get("LEONIDA_TOOLS_DIR") or os.path.join(ROOT, "tools") - -sys.dont_write_bytecode = True -sys.path.insert(0, TOOLS_DIR) -sys.path.insert(0, HERE) - -import rdna2spirv # noqa: E402 -import spirv_mini_interp as si # noqa: E402 - -STUB_DXBC = b"DXBC" + bytes(24) + struct.pack(" str: - if _TMP_DIR is None: - setUpModule() - asm = "; test_cmp_class\n" + "".join(f"\t{ln}\n" for ln in lines) - asm += "\texp mrt0 v0, v0, v0, v0 done vm\n\ts_endpgm\n" - with open(_SRC_PATH, "w", encoding="utf-8") as f: - f.write(asm) - with warnings.catch_warnings(): - warnings.simplefilter("ignore", ResourceWarning) - return rdna2spirv.translate(_SRC_PATH) - - -def run_v0(lines) -> int: - spv = translate_lines(lines) - return si.run_fragment(spv)["%out_mrt0"][0] - - -def validate_spirv(spv: str): - if not SPIRV_AS or not SPIRV_VAL: - return - spv_bin = os.path.join(_TMP_DIR.name, "cmp_class.spv") - p1 = subprocess.run([SPIRV_AS, "--target-env", "vulkan1.2", "-", "-o", spv_bin], - input=spv.encode("utf-8"), capture_output=True) - assert p1.returncode == 0, p1.stderr.decode("utf-8", "replace") - p2 = subprocess.run([SPIRV_VAL, "--target-env", "vulkan1.2", spv_bin], capture_output=True) - assert p2.returncode == 0, p2.stderr.decode("utf-8", "replace") - - -class CmpClassF16Tests(unittest.TestCase): - def test_all_10_classes(self): - for cls_bit, val, name in F16_CLASSES: - exact_mask = 1 << cls_bit - inv_mask = 0x3FF ^ exact_mask - with self.subTest(case=name): - hit = run_v0([ - f"v_mov_b32 v1, {0xBEEF0000 | val:#x}", - f"v_cmp_class_f16_e32 vcc_lo, v1, {exact_mask:#x}", - "v_cndmask_b32_e32 v0, 0x3f800000, 0x40000000, vcc_lo", - ]) - miss = run_v0([ - f"v_mov_b32 v1, {0xBEEF0000 | val:#x}", - f"v_cmp_class_f16_e32 vcc_lo, v1, {inv_mask:#x}", - "v_cndmask_b32_e32 v0, 0x3f800000, 0x40000000, vcc_lo", - ]) - self.assertEqual(hit, 0x40000000) - self.assertEqual(miss, 0x3F800000) - - def test_opsel_mods_cmpx_and_spirv_val(self): - # op_sel:[1,0] selects high half (-inf = 0xfc00); abs makes it +inf (bit 9 = 0x200) - got = run_v0([ - "v_mov_b32 v1, 0xfc003c00", - "v_cmp_class_f16_e64 s0, |v1|, 0x200 op_sel:[1,0]", - "v_cndmask_b32_e64 v0, 0x3f800000, 0x40000000, s0", - ]) - self.assertEqual(got, 0x40000000) - # neg on +0.0 -> -0.0 (bit 5 = 0x20), inline constant 0.5 -> +normal (bit 8 = 0x100) - got_neg = run_v0([ - "v_mov_b32 v1, 0x00000000", - "v_cmp_class_f16_e64 s0, -v1, 0x20", - "v_cndmask_b32_e64 v0, 0x3f800000, 0x40000000, s0", - ]) - self.assertEqual(got_neg, 0x40000000) - # v_cmpx_class_f16 narrows EXEC (false leaves v0 at 0x3f800000, skips 0x40000000) - spv = translate_lines([ - "v_mov_b32 v0, 0x3f800000", - "v_mov_b32 v1, 0x7c01", - "v_cmpx_class_f16_e32 v1, 0x2", # sNaN vs qNaN-only mask -> false - "v_mov_b32 v0, 0x40000000", - "s_mov_b32 exec_lo, -1", - ]) - validate_spirv(spv) - self.assertEqual(si.run_fragment(spv)["%out_mrt0"][0], 0x3F800000) - - def test_f16_float_const_mask_uses_src_h(self): - # Float inline constants on v_cmp(x)_class_f16's mask encode as binary16 over a zero high half - # (e.g. 0.5=0x3800, 1.0=0x3C00, -2.0=0xC000, 0.15915494=0x3118), not binary32. - # _sdwa: BYTE_3(0.5)=0 (no match), BYTE_1(0.5)=0x38 (bit 3=-normal matches -1.0), WORD_1(1.0)=0, BYTE_3(-2.0)=0. - for mask, sel, val, want in ( - ("0.5", "BYTE_3", 0xBC00, 0x3F800000), - ("0.5", "BYTE_1", 0xBC00, 0x40000000), - ("1.0", "WORD_1", 0x4000, 0x3F800000), - ("-2.0", "BYTE_3", 0x0001, 0x3F800000), - ): - with self.subTest(mask=mask, sel=sel, val=hex(val)): - got = run_v0([ - f"v_mov_b32 v1, {val:#x}", - f"v_cmp_class_f16_sdwa vcc_lo, v1, {mask} src0_sel:WORD_0 src1_sel:{sel}", - "v_cndmask_b32_e32 v0, 0x3f800000, 0x40000000, vcc_lo", - ]) - self.assertEqual(got, want) - - # _e64 with 0.15915494 (1/(2*pi)): f16=0x3118 (mask & 0x3FF = 0x118 -> bits 3,4,8; bit 0 sNaN clear), - # whereas f32=0x3E22F983 has mask & 0x3FF = 0x183 (would falsely match sNaN bit 0). - got_snan = run_v0([ - "v_mov_b32 v1, 0x7c01", - "v_cmp_class_f16_e64 s0, v1, 0.15915494", - "v_cndmask_b32_e64 v0, 0x3f800000, 0x40000000, s0", - ]) - self.assertEqual(got_snan, 0x3F800000) - got_norm = run_v0([ - "v_mov_b32 v1, 0xbc00", - "v_cmp_class_f16_e64 s0, v1, 0.15915494", - "v_cndmask_b32_e64 v0, 0x3f800000, 0x40000000, s0", - ]) - self.assertEqual(got_norm, 0x40000000) - - # v_cmpx_class_f16_e64 with 0.15915494 kills sNaN lane (bit 0 clear in 0x3118). - spv_cmpx = translate_lines([ - "v_mov_b32 v0, 0x3f800000", - "v_mov_b32 v1, 0x7c01", - "v_cmpx_class_f16_e64 v1, 0.15915494", - "v_mov_b32 v0, 0x40000000", - "s_mov_b32 exec_lo, -1", - ]) - validate_spirv(spv_cmpx) - self.assertEqual(si.run_fragment(spv_cmpx)["%out_mrt0"][0], 0x3F800000) - - -class CmpClassF64Tests(unittest.TestCase): - def test_all_10_classes_and_no_float64(self): - for cls_bit, val, name in F64_CLASSES: - exact_mask = 1 << cls_bit - inv_mask = 0x3FF ^ exact_mask - lo, hi = val & 0xFFFFFFFF, (val >> 32) & 0xFFFFFFFF - with self.subTest(case=name): - spv_hit = translate_lines([ - f"v_mov_b32 v2, {lo:#x}", - f"v_mov_b32 v3, {hi:#x}", - f"v_cmp_class_f64_e32 vcc_lo, v[2:3], {exact_mask:#x}", - "v_cndmask_b32_e32 v0, 0x3f800000, 0x40000000, vcc_lo", - ]) - self.assertNotIn("OpCapability Float64", spv_hit) - self.assertEqual(si.run_fragment(spv_hit)["%out_mrt0"][0], 0x40000000) - miss = run_v0([ - f"v_mov_b32 v2, {lo:#x}", - f"v_mov_b32 v3, {hi:#x}", - f"v_cmp_class_f64_e32 vcc_lo, v[2:3], {inv_mask:#x}", - "v_cndmask_b32_e32 v0, 0x3f800000, 0x40000000, vcc_lo", - ]) - self.assertEqual(miss, 0x3F800000) - - def test_mods_literal_cmpx_rejected_and_spirv_val(self): - # 32-bit literal 0xfff00000 -> -inf (upper word, lo=0), abs -> +inf (bit 9 = 0x200) - spv = translate_lines([ - "v_mov_b32 v0, 0x3f800000", - "v_cmp_class_f64_e64 s0, |0xfff00000|, 0x200", - "v_cndmask_b32_e64 v0, 0x3f800000, 0x40000000, s0", - "v_cmpx_class_f64_e64 -1.0, 0x8", # -normal -> true, keeps lane active - "s_mov_b32 exec_lo, -1", - ]) - self.assertNotIn("OpCapability Float64", spv) - validate_spirv(spv) - self.assertEqual(si.run_fragment(spv)["%out_mrt0"][0], 0x40000000) - - for bad in ( - "v_cmp_class_f16_e64 s0, v1, 1 clamp", - "v_cmp_class_f16_e64 s0, v1, 1 op_sel:[0,1]", - "v_cmp_class_f64_e64 s0, v[2:3], 1 clamp", - "v_cmp_class_f64_e64 s0, v[2:3], 1 op_sel:[1,0]", - ): - with self.subTest(bad=bad), self.assertRaises(rdna2spirv.Unsupported): - translate_lines([bad]) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_alu_cndmask_b64.py b/tests/semantic/test_alu_cndmask_b64.py deleted file mode 100644 index 8b5de087f..000000000 --- a/tests/semantic/test_alu_cndmask_b64.py +++ /dev/null @@ -1,79 +0,0 @@ -"""64-bit conditional select on RDNA2: there is no `v_cndmask_b64`; a 64-bit select is two v_cndmask_b32, low and high -dword, under the same condition bit (D = cond ? S1 : S0 per lane, for the lane's bit of VCC or of an SGPR mask). - -Each case is translated by tools/rdna2spirv.py (support.translate_lines) and executed with -tests/semantic/spirv_mini_interp.py (one lane: the translator models a lane mask as that lane's own bit, 0 or 1); the expected words are -written by hand, and seeded random 64-bit operands are checked against a plain-Python select. `v_cndmask_b64` itself -stays Unsupported rather than guessed. Standard library only: no GPU, no LLVM, no game data. (The old file ran its own -SIMD simulator and never called the translator.) -""" -import os -import random -import sys -import unittest - -sys.dont_write_bytecode = True -sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) -import support # noqa: E402 -from rdna2spirv import Unsupported # noqa: E402 - -M32 = 0xFFFFFFFF - - -def select64(cond, s0, s1): - return s1 if cond else s0 - - -def run(cond_mask, s0, s1, form="vcc"): - """Select a 64-bit value with two v_cndmask_b32; returns (low, high) of v[0:1]. cond_mask is the lane's bit, 0 or 1.""" - setup = [f"v_mov_b32 v2, {s0 & M32:#x}", f"v_mov_b32 v3, {s0 >> 32:#x}", - f"v_mov_b32 v4, {s1 & M32:#x}", f"v_mov_b32 v5, {s1 >> 32:#x}"] - if form == "vcc": - sel = [f"s_mov_b32 vcc_lo, {cond_mask:#x}", "v_cndmask_b32_e32 v0, v2, v4, vcc_lo", - "v_cndmask_b32_e32 v1, v3, v5, vcc_lo"] - elif form == "sgpr": - sel = [f"s_mov_b32 s8, {cond_mask:#x}", "v_cndmask_b32_e64 v0, v2, v4, s8", "v_cndmask_b32_e64 v1, v3, v5, s8"] - else: - raise ValueError(form) - lines = setup + sel + ["exp mrt0 v0, v1, v0, v1 done vm", "s_endpgm"] - w = support.mrt0_words(support.translate_lines("ps_cndmask64", lines)) - assert w[0] == w[2] and w[1] == w[3] - return w[0], w[1] - - -A = 0x1111111122222222 -B = 0xAAAAAAAABBBBBBBB - - -class CndmaskPair(unittest.TestCase): - def test_by_hand(self): - for form in ("vcc", "sgpr"): - with self.subTest(form=form): - self.assertEqual(run(0, A, B, form), (0x22222222, 0x11111111)) # bit clear: S0 - self.assertEqual(run(1, A, B, form), (0xBBBBBBBB, 0xAAAAAAAA)) # bit set: S1 - self.assertEqual(run(1, A, A, form), (0x22222222, 0x11111111)) - self.assertEqual(run(1, 0, 0xFFFFFFFFFFFFFFFF, form), (M32, M32)) - - def test_both_halves_follow_the_same_bit(self): - for cond in (0, 1): - lo, hi = run(cond, 0x00000000FFFFFFFF, 0xFFFFFFFF00000000) - self.assertEqual((hi << 32) | lo, select64(cond, 0x00000000FFFFFFFF, 0xFFFFFFFF00000000)) - - def test_random(self): - rng = random.Random(0xC0DE64) - for _ in range(30): - s0, s1, mask = rng.getrandbits(64), rng.getrandbits(64), rng.getrandbits(1) - want = select64(mask, s0, s1) - for form in ("vcc", "sgpr"): - with self.subTest(form=form, s0=hex(s0), s1=hex(s1), mask=hex(mask)): - lo, hi = run(mask, s0, s1, form) - self.assertEqual((hi << 32) | lo, want) - - def test_v_cndmask_b64_is_refused(self): - with self.assertRaises(Unsupported): - support.translate_lines("ps_cndmask64_op", ["s_mov_b32 vcc_lo, 1", "v_cndmask_b64 v[0:1], v[2:3], v[4:5], vcc_lo", - "exp mrt0 v0, v1, v0, v1 done vm", "s_endpgm"]) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_alu_cndmask_mix.py b/tests/semantic/test_alu_cndmask_mix.py deleted file mode 100644 index 171e550f3..000000000 --- a/tests/semantic/test_alu_cndmask_mix.py +++ /dev/null @@ -1,1463 +0,0 @@ -"""Semantic interpreter tests for mixed vector conditional select patterns with alternate mask configurations. - -AMD RDNA2 / GFX10 VALU Instruction Set Architecture: - - v_cndmask_b32_e32 dst, src0, src1 - Implicit condition mask: VCC (vcc_lo in Wave32, vcc in Wave64). - For each active lane i (EXEC[i] == 1): - dst[i] = src1[i] if (VCC[i] == 1) else src0[i] - Inactive lanes (EXEC[i] == 0) preserve prior dst[i]. - - - v_cndmask_b32_e64 dst, src0, src1, cond_mask - Explicit condition mask: any SGPR, 64-bit SGPR pair, VCC, EXEC, or immediate. - Operates under EXEC mask identically to e32. - -Mixed Vector Select Patterns & Alternate Mask Configurations Covered: - 1. Mixed Operand Configurations: - - Selecting between VGPR and SGPR (uniform base, divergent replacement; or divergent base, uniform replacement). - - Selecting between VGPR and inline / literal constants (0, 1.0f, -1, bitmasks). - - Selecting between SGPR and SGPR across divergent lane masks. - - Self-referencing in-place destination selects (dst == src0 or dst == src1). - - Floating-point representations (preserving sign, exponent, mantissa, special floats +/-0, Inf, NaN). - - Signed and unsigned 32-bit integer boundaries. - - 2. Alternate Mask Configurations: - - Explicit SGPR scalar condition masks (s4, s6, etc.) independent of VCC. - - 64-bit SGPR pair condition masks (s[4:5]) in Wave64. - - Inverted condition masks (~mask, s_not_b32) and dual-complement symmetry. - - Boolean mask compositions: - * Conjunction: s_and_b32 (maskA & maskB) - * Disjunction: s_or_b32 (maskA | maskB) - * Exclusive: s_xor_b32 (maskA ^ maskB) - * Inhibit / AND-NOT: s_andn2_b32 (maskA & ~maskB) - - Strided, checkered, and walking bitmask patterns (powers-of-two clusters, one-hot, one-cold). - - Comparison-derived dynamic masks from float (v_cmp_*_f32) and integer (v_cmp_*_u32/i32). - - 3. Shader Idioms & Multiplexer Trees: - - Branchless clamping (float, signed int, unsigned int) via cascaded conditional selects. - - Multi-way multiplexer trees: - * 3-way ternary multiplexer: condA ? A : (condB ? B : C) - * 4-way priority encoder: cond0 ? D0 : (cond1 ? D1 : (cond2 ? D2 : D3)) - * 2-level binary decision tree: sel_hi ? (sel_lo ? D : C) : (sel_lo ? B : A) - - Branchless math operations: - * Absolute value: (x < 0) ? -x : x - * Signum: (x > 0) ? 1 : ((x < 0) ? -1 : 0) - * Safe division with zero-divisor fallback: (denom == 0) ? fallback : (num / denom) - * Step and rectangular window / pulse functions. - - Vector channel mixing and interleaving. - - 4. EXEC Mask Interaction & Divergence: - - Strict inactive lane preservation when EXEC[i] == 0 regardless of condition mask state. - - Orthogonal EXEC and condition masks. - - Structured divergent branching (Then/Else emulation with s_and_saveexec_b32 and s_or_exec_b32). - - Zero-EXEC whole-wave no-op. - - 5. Wave64 Cross-Half & 64-Bit Divergence: - - Cross-half divergence: low-half (lanes 0..31) and high-half (lanes 32..63) using distinct patterns. - - 64-bit scalar mask logic (s_and_b64, s_or_b64, s_xor_b64, s_not_b64). - - Half-disabled waves (EXEC low-half only or high-half only). - - 6. SPIR-V Translation & Verification: - - Translates assembly via tools/rdna2spirv.py emitting OpSelect. - - Executes via tests/semantic/spirv_mini_interp.py. - - 7. Invariants & Negative Controls: - - Single-bit condition flip sensitivity. - - Invariant duality: cndmask(s0, s1, mask) == cndmask(s1, s0, ~mask). - - Idempotence: cndmask(x, x, mask) == x. - -Standard library only: zero game data, no external dependencies, Python 3.9+ compatible. -""" -from __future__ import annotations - -import gc -import math -import os -import random -import struct -import sys -import tempfile -import unittest -import warnings - -HERE = os.path.dirname(os.path.abspath(__file__)) -ROOT = os.path.dirname(os.path.dirname(HERE)) -TOOLS_DIR = os.environ.get("LEONIDA_TOOLS_DIR") or os.path.join(ROOT, "tools") - -sys.dont_write_bytecode = True -if TOOLS_DIR not in sys.path: - sys.path.insert(0, TOOLS_DIR) -if HERE not in sys.path: - sys.path.insert(0, HERE) - -import rdna2spirv # noqa: E402 -import spirv_mini_interp as si # noqa: E402 - -MASK32 = 0xFFFFFFFF -MASK64 = (1 << 64) - 1 -SIGN_MASK = 0x80000000 -STUB_DXBC = b"DXBC" + bytes(24) + struct.pack(" int: - """Encode float into IEEE 754 32-bit unsigned integer.""" - try: - return struct.unpack(" 0 else 0xFF800000 - - -def bits_to_f32(b: int) -> float: - """Decode IEEE 754 32-bit unsigned integer into float.""" - return struct.unpack(" int: - """Convert integer to signed 32-bit two's complement.""" - x &= MASK32 - return x - (1 << 32) if (x & SIGN_MASK) else x - - -def ref_cndmask_lane( - src0: int, - src1: int, - cond_bit: int, - exec_bit: int = 1, - prev_dst: int = 0, -) -> int: - """AMD RDNA2 v_cndmask_b32 per-lane mathematical reference oracle. - - Lane semantics: - - If exec_bit == 0: lane is inactive, dst is preserved (returns prev_dst & MASK32). - - If exec_bit == 1: lane is active: - - If cond_bit == 0: selects src0 & MASK32. - - If cond_bit != 0: selects src1 & MASK32. - """ - if not (exec_bit & 1): - return prev_dst & MASK32 - return (src1 if (cond_bit & 1) else src0) & MASK32 - - -def ref_cndmask_wave( - src0_lanes: list[int], - src1_lanes: list[int], - cond_mask: int, - exec_mask: int, - prev_dst_lanes: list[int] | None = None, - wave_size: int = 32, -) -> list[int]: - """Whole-wave vector conditional move reference oracle across divergent lanes.""" - if prev_dst_lanes is None: - prev_dst_lanes = [0] * wave_size - res: list[int] = [] - for lane in range(wave_size): - c_bit = (cond_mask >> lane) & 1 - e_bit = (exec_mask >> lane) & 1 - s0 = src0_lanes[lane] - s1 = src1_lanes[lane] - old = prev_dst_lanes[lane] - res.append(ref_cndmask_lane(s0, s1, c_bit, e_bit, old)) - return res - - -# ----------------------------------------------------------------------------- -# 2. Multi-Lane SIMD Wave Interpreter -# ----------------------------------------------------------------------------- - -class AluCndmaskMixInterpreter: - """Simulates SIMD wave execution for mixed vector conditional selects. - - Models: - - Wave32 (32 lanes) and Wave64 (64 lanes). - - VGPRs: per-lane independent 32-bit vector registers (v0..v255). - - SGPRs: uniform 32-bit scalar registers shared across the wave (s0..s127). - - VCC: condition mask register (32-bit in Wave32, 64-bit in Wave64). - - EXEC: execution mask register (32-bit in Wave32, 64-bit in Wave64). - - Vector conditional moves: v_cndmask_b32_e32, v_cndmask_b32_e64. - - Comparisons: v_cmp_* (integer and floating-point). - - Scalar mask logic: s_mov, s_not, s_and, s_or, s_xor, s_andn2, s_orn2. - - Control flow: s_and_saveexec, s_or_exec, s_xor_saveexec. - - Arithmetic: v_add_u32, v_sub_u32, v_xor_b32, v_bfi_b32. - """ - - def __init__(self, wave_size: int = 32, initial_exec: int | None = None) -> None: - if wave_size not in (32, 64): - raise ValueError(f"Unsupported wave_size: {wave_size}") - self.wave_size = wave_size - self.mask_all = (1 << wave_size) - 1 - self.exec_mask = self.mask_all if initial_exec is None else (initial_exec & self.mask_all) - self.vcc = 0 - self.sgprs = [0] * 128 - self.vgprs = [[0] * 256 for _ in range(wave_size)] - - def is_lane_active(self, lane: int) -> bool: - return bool((self.exec_mask >> lane) & 1) - - def set_exec(self, mask: int) -> None: - self.exec_mask = mask & self.mask_all - - def set_vcc(self, mask: int) -> None: - self.vcc = mask & self.mask_all - - def get_vgpr(self, reg_idx: int) -> list[int]: - return [self.vgprs[lane][reg_idx] for lane in range(self.wave_size)] - - def set_vgpr_lane(self, reg_idx: int, lane: int, val: int) -> None: - self.vgprs[lane][reg_idx] = val & MASK32 - - def init_vgpr(self, reg_idx: int, values: list[int] | int) -> None: - if isinstance(values, int): - val = values & MASK32 - for lane in range(self.wave_size): - self.vgprs[lane][reg_idx] = val - else: - for lane in range(min(len(values), self.wave_size)): - self.vgprs[lane][reg_idx] = values[lane] & MASK32 - - def read_operand(self, op: int | float | str, lane: int) -> int: - if isinstance(op, int): - return op & MASK32 - if isinstance(op, float): - return f32_to_bits(op) - op_str = str(op).strip().lower() - if op_str.startswith("v"): - reg_idx = int(op_str[1:]) - return self.vgprs[lane][reg_idx] & MASK32 - elif op_str.startswith("s[") and ":" in op_str: - lo = int(op_str[2:-1].split(":")[0]) - return self.sgprs[lo] & MASK32 - elif op_str.startswith("s"): - reg_idx = int(op_str[1:]) - return self.sgprs[reg_idx] & MASK32 - elif op_str in ("vcc", "vcc_lo"): - return (self.vcc >> lane) & 1 - elif op_str == "vcc_hi": - return (self.vcc >> (lane + 32)) & 1 if self.wave_size == 64 else 0 - elif op_str in ("exec", "exec_lo"): - return (self.exec_mask >> lane) & 1 - elif op_str == "exec_hi": - return (self.exec_mask >> (lane + 32)) & 1 if self.wave_size == 64 else 0 - else: - raise ValueError(f"Unsupported operand: {op}") - - def read_mask_source(self, cond_src: str | int, lane: int) -> int: - if isinstance(cond_src, int): - return (cond_src >> lane) & 1 - c_str = str(cond_src).strip().lower() - if c_str in ("vcc", "vcc_lo"): - return (self.vcc >> lane) & 1 - elif c_str in ("exec", "exec_lo"): - return (self.exec_mask >> lane) & 1 - elif c_str.startswith("s[") and ":" in c_str: - lo = int(c_str[2:-1].split(":")[0]) - lo_val = self.sgprs[lo] & MASK32 - hi_val = (self.sgprs[lo + 1] & MASK32) if (lo + 1 < len(self.sgprs)) else 0 - mask = lo_val | (hi_val << 32) - return (mask >> lane) & 1 - elif c_str.startswith("s"): - reg = int(c_str[1:]) - mask = self.sgprs[reg] & MASK32 - return (mask >> (lane % 32)) & 1 - else: - raise ValueError(f"Unknown cond_src: {cond_src}") - - def execute_v_mov(self, dst_v: int, src: int | float | str) -> None: - """v_mov_b32 dst_v, src: active lanes only.""" - for lane in range(self.wave_size): - if self.is_lane_active(lane): - self.vgprs[lane][dst_v] = self.read_operand(src, lane) - - def execute_v_cndmask_e32(self, dst_v: int, src0: int | float | str, src1: int | float | str) -> None: - """v_cndmask_b32_e32 dst, src0, src1 with implicit VCC condition.""" - for lane in range(self.wave_size): - if self.is_lane_active(lane): - s0 = self.read_operand(src0, lane) - s1 = self.read_operand(src1, lane) - c_bit = (self.vcc >> lane) & 1 - self.vgprs[lane][dst_v] = s1 if c_bit else s0 - - def execute_v_cndmask_e64( - self, - dst_v: int, - src0: int | float | str, - src1: int | float | str, - cond_src: str | int, - ) -> None: - """v_cndmask_b32_e64 dst, src0, src1, cond_src with explicit condition mask.""" - for lane in range(self.wave_size): - if self.is_lane_active(lane): - s0 = self.read_operand(src0, lane) - s1 = self.read_operand(src1, lane) - c_bit = self.read_mask_source(cond_src, lane) - self.vgprs[lane][dst_v] = s1 if c_bit else s0 - - def execute_v_cmp( - self, - rel: str, - src0: int | float | str, - src1: int | float | str, - dst_mask: str = "vcc", - ) -> None: - """v_cmp_: inactive lanes in EXEC write 0 to condition mask.""" - mask = 0 - for lane in range(self.wave_size): - if self.is_lane_active(lane): - s0_u = self.read_operand(src0, lane) - s1_u = self.read_operand(src1, lane) - taken = False - - if rel == "eq_u32": - taken = (s0_u == s1_u) - elif rel == "ne_u32": - taken = (s0_u != s1_u) - elif rel == "lt_u32": - taken = (s0_u < s1_u) - elif rel == "le_u32": - taken = (s0_u <= s1_u) - elif rel == "gt_u32": - taken = (s0_u > s1_u) - elif rel == "ge_u32": - taken = (s0_u >= s1_u) - elif rel == "lt_i32": - taken = (s32(s0_u) < s32(s1_u)) - elif rel == "le_i32": - taken = (s32(s0_u) <= s32(s1_u)) - elif rel == "gt_i32": - taken = (s32(s0_u) > s32(s1_u)) - elif rel == "ge_i32": - taken = (s32(s0_u) >= s32(s1_u)) - elif rel in ("lt_f32", "le_f32", "gt_f32", "ge_f32", "eq_f32", "ne_f32", "o_f32", "u_f32"): - f0 = bits_to_f32(s0_u) - f1 = bits_to_f32(s1_u) - nan_present = math.isnan(f0) or math.isnan(f1) - if rel == "o_f32": - taken = not nan_present - elif rel == "u_f32": - taken = nan_present - elif nan_present: - taken = False - elif rel == "lt_f32": - taken = (f0 < f1) - elif rel == "le_f32": - taken = (f0 <= f1) - elif rel == "gt_f32": - taken = (f0 > f1) - elif rel == "ge_f32": - taken = (f0 >= f1) - elif rel == "eq_f32": - taken = (f0 == f1) - elif rel == "ne_f32": - taken = (f0 != f1) - else: - raise NotImplementedError(f"Unsupported cmp rel: {rel}") - - if taken: - mask |= (1 << lane) - - if dst_mask in ("vcc", "vcc_lo"): - self.vcc = mask & self.mask_all - elif dst_mask.startswith("s[") and ":" in dst_mask: - lo = int(dst_mask[2:-1].split(":")[0]) - self.sgprs[lo] = mask & MASK32 - if lo + 1 < len(self.sgprs): - self.sgprs[lo + 1] = (mask >> 32) & MASK32 - elif dst_mask.startswith("s"): - reg = int(dst_mask[1:]) - self.sgprs[reg] = mask & MASK32 - - def execute_s_mov_b32(self, dst_s: int, val: int | str) -> None: - if isinstance(val, int): - self.sgprs[dst_s] = val & MASK32 - elif str(val).startswith("s"): - self.sgprs[dst_s] = self.sgprs[int(str(val)[1:])] & MASK32 - elif str(val) in ("vcc", "vcc_lo"): - self.sgprs[dst_s] = self.vcc & MASK32 - elif str(val) in ("exec", "exec_lo"): - self.sgprs[dst_s] = self.exec_mask & MASK32 - - def execute_s_mov_b64(self, dst_s: int, val: int | str) -> None: - if isinstance(val, int): - self.sgprs[dst_s] = val & MASK32 - self.sgprs[dst_s + 1] = (val >> 32) & MASK32 - elif str(val) == "vcc": - self.sgprs[dst_s] = self.vcc & MASK32 - self.sgprs[dst_s + 1] = (self.vcc >> 32) & MASK32 - elif str(val) == "exec": - self.sgprs[dst_s] = self.exec_mask & MASK32 - self.sgprs[dst_s + 1] = (self.exec_mask >> 32) & MASK32 - - def execute_s_not_b32(self, dst_s: int, src_s: int | str) -> None: - src_val = (self.vcc & MASK32) if str(src_s) in ("vcc", "vcc_lo") else self.sgprs[int(str(src_s).lstrip("s"))] - self.sgprs[dst_s] = (~src_val) & MASK32 - - def execute_s_not_b64(self, dst_s: int, src_s: str) -> None: - if src_s == "vcc": - v = self.vcc - elif src_s == "exec": - v = self.exec_mask - else: - lo = int(src_s.strip("s[]").split(":")[0]) - v = (self.sgprs[lo] & MASK32) | ((self.sgprs[lo + 1] & MASK32) << 32) - inv = (~v) & MASK64 - self.sgprs[dst_s] = inv & MASK32 - self.sgprs[dst_s + 1] = (inv >> 32) & MASK32 - - def execute_s_and_b32(self, dst_s: int, s0: str | int, s1: str | int) -> None: - def get_val(op: str | int) -> int: - if isinstance(op, int): - return op & MASK32 - op_str = str(op).lower() - if op_str in ("vcc", "vcc_lo"): - return self.vcc & MASK32 - if op_str.startswith("s"): - return self.sgprs[int(op_str[1:])] - return int(op) & MASK32 - self.sgprs[dst_s] = (get_val(s0) & get_val(s1)) & MASK32 - - def execute_s_or_b32(self, dst_s: int, s0: str | int, s1: str | int) -> None: - def get_val(op: str | int) -> int: - if isinstance(op, int): - return op & MASK32 - op_str = str(op).lower() - if op_str in ("vcc", "vcc_lo"): - return self.vcc & MASK32 - if op_str.startswith("s"): - return self.sgprs[int(op_str[1:])] - return int(op) & MASK32 - self.sgprs[dst_s] = (get_val(s0) | get_val(s1)) & MASK32 - - def execute_s_xor_b32(self, dst_s: int, s0: str | int, s1: str | int) -> None: - def get_val(op: str | int) -> int: - if isinstance(op, int): - return op & MASK32 - op_str = str(op).lower() - if op_str in ("vcc", "vcc_lo"): - return self.vcc & MASK32 - if op_str.startswith("s"): - return self.sgprs[int(op_str[1:])] - return int(op) & MASK32 - self.sgprs[dst_s] = (get_val(s0) ^ get_val(s1)) & MASK32 - - def execute_s_andn2_b32(self, dst_s: int, s0: str | int, s1: str | int) -> None: - """s_andn2_b32: dst = s0 & ~s1.""" - def get_val(op: str | int) -> int: - if isinstance(op, int): - return op & MASK32 - op_str = str(op).lower() - if op_str in ("vcc", "vcc_lo"): - return self.vcc & MASK32 - if op_str.startswith("s"): - return self.sgprs[int(op_str[1:])] - return int(op) & MASK32 - self.sgprs[dst_s] = (get_val(s0) & (~get_val(s1) & MASK32)) & MASK32 - - def execute_s_orn2_b32(self, dst_s: int, s0: str | int, s1: str | int) -> None: - """s_orn2_b32: dst = s0 | ~s1.""" - def get_val(op: str | int) -> int: - if isinstance(op, int): - return op & MASK32 - op_str = str(op).lower() - if op_str in ("vcc", "vcc_lo"): - return self.vcc & MASK32 - if op_str.startswith("s"): - return self.sgprs[int(op_str[1:])] - return int(op) & MASK32 - self.sgprs[dst_s] = (get_val(s0) | (~get_val(s1) & MASK32)) & MASK32 - - def execute_s_and_saveexec_b32(self, dst_s: int, mask_src: str | int) -> None: - self.sgprs[dst_s] = self.exec_mask & MASK32 - if isinstance(mask_src, int): - m = mask_src - elif mask_src in ("vcc", "vcc_lo"): - m = self.vcc - elif str(mask_src).startswith("s"): - m = self.sgprs[int(str(mask_src)[1:])] - else: - raise ValueError(f"Unknown mask_src: {mask_src}") - self.exec_mask = (self.exec_mask & m) & self.mask_all - - def execute_s_or_exec_b32(self, mask_src: str | int) -> None: - if isinstance(mask_src, int): - m = mask_src - elif mask_src in ("vcc", "vcc_lo"): - m = self.vcc - elif str(mask_src).startswith("s"): - m = self.sgprs[int(str(mask_src)[1:])] - else: - raise ValueError(f"Unknown mask_src: {mask_src}") - self.exec_mask = (self.exec_mask | m) & self.mask_all - - def execute_s_xor_saveexec_b32(self, dst_s: int, mask_src: str | int) -> None: - self.sgprs[dst_s] = self.exec_mask & MASK32 - if isinstance(mask_src, int): - m = mask_src - elif mask_src in ("vcc", "vcc_lo"): - m = self.vcc - elif str(mask_src).startswith("s"): - m = self.sgprs[int(str(mask_src)[1:])] - else: - raise ValueError(f"Unknown mask_src: {mask_src}") - self.exec_mask = (self.exec_mask ^ m) & self.mask_all - - def execute_v_add_u32(self, dst_v: int, src0: int | str, src1: int | str) -> None: - for lane in range(self.wave_size): - if self.is_lane_active(lane): - s0 = self.read_operand(src0, lane) - s1 = self.read_operand(src1, lane) - self.vgprs[lane][dst_v] = (s0 + s1) & MASK32 - - def execute_v_sub_u32(self, dst_v: int, src0: int | str, src1: int | str) -> None: - for lane in range(self.wave_size): - if self.is_lane_active(lane): - s0 = self.read_operand(src0, lane) - s1 = self.read_operand(src1, lane) - self.vgprs[lane][dst_v] = (s0 - s1) & MASK32 - - def execute_v_xor_b32(self, dst_v: int, src0: int | str, src1: int | str) -> None: - for lane in range(self.wave_size): - if self.is_lane_active(lane): - s0 = self.read_operand(src0, lane) - s1 = self.read_operand(src1, lane) - self.vgprs[lane][dst_v] = (s0 ^ s1) & MASK32 - - def execute_v_bfi_b32(self, dst_v: int, src0_mask: int | str, src1_field: int | str, src2_base: int | str) -> None: - """dst = (mask & field) | (~mask & base).""" - for lane in range(self.wave_size): - if self.is_lane_active(lane): - m = self.read_operand(src0_mask, lane) - f = self.read_operand(src1_field, lane) - b = self.read_operand(src2_base, lane) - self.vgprs[lane][dst_v] = ((m & f) | ((~m & MASK32) & b)) & MASK32 - - -# ----------------------------------------------------------------------------- -# 3. Synthetic Shader Runner via rdna2spirv & spirv_mini_interp -# ----------------------------------------------------------------------------- - -_TMP_DIR: tempfile.TemporaryDirectory | None = None -_SRC_PATH: str | None = None - - -def setUpModule() -> None: - global _TMP_DIR, _SRC_PATH - _TMP_DIR = tempfile.TemporaryDirectory() - disasm_dir = os.path.join(_TMP_DIR.name, "disasm") - os.mkdir(disasm_dir) - _SRC_PATH = os.path.join(disasm_dir, "ps_cndmask_mix.s") - with open(os.path.join(_TMP_DIR.name, "ps_cndmask_mix.dxbc"), "wb") as f: - f.write(STUB_DXBC) - - -def tearDownModule() -> None: - global _TMP_DIR, _SRC_PATH - if _TMP_DIR is not None: - gc.collect() - _TMP_DIR.cleanup() - _TMP_DIR = None - _SRC_PATH = None - - -def run_synthetic_ps(lines: list[str]) -> tuple[int, int, int, int]: - """Translates synthetic assembly lines and executes with spirv_mini_interp.""" - if _TMP_DIR is None: - setUpModule() - assert _SRC_PATH is not None - asm = ( - "; ps_cndmask_mix\n" - + "".join(f"\t{ln}\n" for ln in lines) - + "\texp mrt0 v0, v1, v2, v3 done vm\n\ts_endpgm\n" - ) - with open(_SRC_PATH, "w", encoding="utf-8") as f: - f.write(asm) - with warnings.catch_warnings(): - warnings.simplefilter("ignore", ResourceWarning) - spv = rdna2spirv.translate(_SRC_PATH) - res = si.run_fragment(spv)["%out_mrt0"] - return tuple(res) - - -# ----------------------------------------------------------------------------- -# 4. Test Suites -# ----------------------------------------------------------------------------- - -class TestCndmaskMixReferenceOracle(unittest.TestCase): - """Verifies core reference oracle truth table, algebraic duality, and bit invariants.""" - - def test_truth_table_active_lane(self) -> None: - src0 = 0xAAAAAAAA - src1 = 0x55555555 - prev = 0xDEADBEEF - self.assertEqual(ref_cndmask_lane(src0, src1, cond_bit=0, exec_bit=1, prev_dst=prev), src0) - self.assertEqual(ref_cndmask_lane(src0, src1, cond_bit=1, exec_bit=1, prev_dst=prev), src1) - - def test_inactive_lane_shielding(self) -> None: - src0 = 0x11111111 - src1 = 0x22222222 - prev = 0xCAFEBABE - self.assertEqual(ref_cndmask_lane(src0, src1, cond_bit=0, exec_bit=0, prev_dst=prev), prev) - self.assertEqual(ref_cndmask_lane(src0, src1, cond_bit=1, exec_bit=0, prev_dst=prev), prev) - - def test_involution_duality(self) -> None: - """Duality: cndmask(A, B, cond) == cndmask(B, A, 1 - cond).""" - rng = random.Random(20261122) - for _ in range(50): - a = rng.getrandbits(32) - b = rng.getrandbits(32) - for c in (0, 1): - self.assertEqual( - ref_cndmask_lane(a, b, cond_bit=c, exec_bit=1), - ref_cndmask_lane(b, a, cond_bit=1 - c, exec_bit=1), - ) - - def test_idempotence(self) -> None: - """cndmask(x, x, cond) == x for any condition bit.""" - for x in (0, 1, 0x7FFFFFFF, 0x80000000, 0xFFFFFFFF, 0x3F800000): - self.assertEqual(ref_cndmask_lane(x, x, 0, 1), x) - self.assertEqual(ref_cndmask_lane(x, x, 1, 1), x) - - def test_floating_point_bit_preservation(self) -> None: - """Validates that NaN, Inf, and subnormal floats are preserved bit-for-bit without alteration.""" - special_floats = [ - 0x7F800000, # +INF - 0xFF800000, # -INF - 0x7FC00000, # Quiet NaN - 0x7F800001, # Signaling NaN with payload - 0x00000001, # Positive smallest subnormal - 0x80000001, # Negative smallest subnormal - 0x00000000, # +0.0 - 0x80000000, # -0.0 - ] - for s0 in special_floats: - for s1 in special_floats: - self.assertEqual(ref_cndmask_lane(s0, s1, 0, 1), s0) - self.assertEqual(ref_cndmask_lane(s0, s1, 1, 1), s1) - - -class TestMixedOperandPatterns(unittest.TestCase): - """Verifies conditional select mixing VGPRs, SGPRs, and inline/literal constants.""" - - def test_vgpr_vs_sgpr_uniform_base(self) -> None: - """dst = vcc ? divergent_vgpr : uniform_sgpr.""" - wave = AluCndmaskMixInterpreter(wave_size=32) - divergent_vgpr = [0x1000 + i for i in range(32)] - wave.init_vgpr(1, divergent_vgpr) - uniform_sgpr = 0x55AA55AA - wave.execute_s_mov_b32(dst_s=4, val=uniform_sgpr) - wave.set_vcc(0x55555555) # alternating condition - - wave.execute_v_cndmask_e32(dst_v=0, src0="s4", src1="v1") - res = wave.get_vgpr(0) - - for i in range(32): - expected = divergent_vgpr[i] if (i % 2 == 0) else uniform_sgpr - self.assertEqual(res[i], expected) - - def test_vgpr_vs_sgpr_uniform_replacement(self) -> None: - """dst = vcc ? uniform_sgpr : divergent_vgpr.""" - wave = AluCndmaskMixInterpreter(wave_size=32) - divergent_vgpr = [0x9000 + i for i in range(32)] - wave.init_vgpr(1, divergent_vgpr) - uniform_sgpr = 0xBEEFBEEF - wave.execute_s_mov_b32(dst_s=6, val=uniform_sgpr) - wave.set_vcc(0x0000FFFF) # low half true - - wave.execute_v_cndmask_e32(dst_v=0, src0="v1", src1="s6") - res = wave.get_vgpr(0) - - for i in range(32): - expected = uniform_sgpr if (i < 16) else divergent_vgpr[i] - self.assertEqual(res[i], expected) - - def test_sgpr_vs_sgpr_divergent_select(self) -> None: - """Selecting between two uniform constants across a divergent wave.""" - wave = AluCndmaskMixInterpreter(wave_size=32) - wave.execute_s_mov_b32(dst_s=0, val=0x11111111) - wave.execute_s_mov_b32(dst_s=1, val=0x22222222) - wave.set_vcc(0xF0F0F0F0) - - wave.execute_v_cndmask_e32(dst_v=2, src0="s0", src1="s1") - res = wave.get_vgpr(2) - - for i in range(32): - c = (0xF0F0F0F0 >> i) & 1 - expected = 0x22222222 if c else 0x11111111 - self.assertEqual(res[i], expected) - - def test_vgpr_vs_immediate_zero_gating(self) -> None: - """Vector zero-gating / masking: dst = vcc ? v0 : 0.""" - wave = AluCndmaskMixInterpreter(wave_size=32) - v0_vals = [0x80000000 + i for i in range(32)] - wave.init_vgpr(0, v0_vals) - wave.set_vcc(0x33333333) # 2 on, 2 off - - wave.execute_v_cndmask_e32(dst_v=2, src0=0, src1="v0") - res = wave.get_vgpr(2) - - for i in range(32): - expected = v0_vals[i] if ((0x33333333 >> i) & 1) else 0 - self.assertEqual(res[i], expected) - - def test_predicate_expansion_to_full_masks(self) -> None: - """Expands 1-bit predicate to all-1s (0xFFFFFFFF) or all-0s (0x00000000) mask: - v_cndmask_b32 dst, 0, -1, vcc. - """ - wave = AluCndmaskMixInterpreter(wave_size=32) - pred_mask = 0xA5A5A5A5 - wave.set_vcc(pred_mask) - - wave.execute_v_cndmask_e32(dst_v=0, src0=0, src1=0xFFFFFFFF) - res = wave.get_vgpr(0) - - for i in range(32): - expected = 0xFFFFFFFF if ((pred_mask >> i) & 1) else 0x00000000 - self.assertEqual(res[i], expected) - - def test_self_referencing_destination_select(self) -> None: - """In-place updates: - 1. dst == src0: v_cndmask_b32 v0, v0, v1 (update only active true lanes) - 2. dst == src1: v_cndmask_b32 v0, v1, v0 (update only active false lanes) - """ - wave = AluCndmaskMixInterpreter(wave_size=32) - base = [100 + i for i in range(32)] - replacement = [500 + i for i in range(32)] - - # Case 1: dst == src0 - wave.init_vgpr(0, base) - wave.init_vgpr(1, replacement) - wave.set_vcc(0x00FF00FF) - wave.execute_v_cndmask_e32(dst_v=0, src0="v0", src1="v1") - res1 = wave.get_vgpr(0) - for i in range(32): - self.assertEqual(res1[i], replacement[i] if ((0x00FF00FF >> i) & 1) else base[i]) - - # Case 2: dst == src1 - wave.init_vgpr(0, base) - wave.init_vgpr(1, replacement) - wave.set_vcc(0x00FF00FF) - wave.execute_v_cndmask_e32(dst_v=0, src0="v1", src1="v0") - res2 = wave.get_vgpr(0) - for i in range(32): - self.assertEqual(res2[i], base[i] if ((0x00FF00FF >> i) & 1) else replacement[i]) - - -class TestAlternateMaskConfigurations(unittest.TestCase): - """Verifies alternate condition mask sources: SGPR masks, inverted masks, and boolean compositions.""" - - def test_sgpr_scalar_condition_mask_e64(self) -> None: - """Explicit condition mask read from SGPR s8 while VCC holds an opposing pattern.""" - wave = AluCndmaskMixInterpreter(wave_size=32) - src0 = [0x1111 + i for i in range(32)] - src1 = [0x2222 + i for i in range(32)] - wave.init_vgpr(0, src0) - wave.init_vgpr(1, src1) - - wave.execute_s_mov_b32(dst_s=8, val=0x0F0F0F0F) - wave.set_vcc(0xF0F0F0F0) # Inverted from s8 to prove VCC is ignored - - wave.execute_v_cndmask_e64(dst_v=2, src0="v0", src1="v1", cond_src="s8") - res = wave.get_vgpr(2) - - for i in range(32): - expected = src1[i] if ((0x0F0F0F0F >> i) & 1) else src0[i] - self.assertEqual(res[i], expected) - # VCC must remain intact - self.assertEqual(wave.vcc, 0xF0F0F0F0) - - def test_inverted_mask_configuration(self) -> None: - """Inverting mask with s_not_b32 vs swapping operands.""" - wave = AluCndmaskMixInterpreter(wave_size=32) - src0 = [10 + i for i in range(32)] - src1 = [20 + i for i in range(32)] - wave.init_vgpr(0, src0) - wave.init_vgpr(1, src1) - - mask = 0x12345678 - wave.execute_s_mov_b32(dst_s=4, val=mask) - wave.execute_s_not_b32(dst_s=6, src_s="s4") - - # Approach A: use inverted mask s6 with normal operands - wave.execute_v_cndmask_e64(dst_v=10, src0="v0", src1="v1", cond_src="s6") - # Approach B: use normal mask s4 with swapped operands - wave.execute_v_cndmask_e64(dst_v=11, src0="v1", src1="v0", cond_src="s4") - - self.assertEqual(wave.get_vgpr(10), wave.get_vgpr(11)) - - def test_conjunction_and_mask(self) -> None: - """s_and_b32: active only when condition A AND condition B hold.""" - wave = AluCndmaskMixInterpreter(wave_size=32) - # Condition A: lane is even (0x55555555) - # Condition B: lane < 16 (0x0000FFFF) - # Conjunction: even lanes in low half (0x00005555) - wave.execute_s_mov_b32(dst_s=10, val=0x55555555) - wave.execute_s_mov_b32(dst_s=12, val=0x0000FFFF) - wave.execute_s_and_b32(dst_s=14, s0="s10", s1="s12") - self.assertEqual(wave.sgprs[14], 0x00005555) - - wave.init_vgpr(0, 0xAA) - wave.init_vgpr(1, 0xBB) - wave.execute_v_cndmask_e64(dst_v=2, src0="v0", src1="v1", cond_src="s14") - - res = wave.get_vgpr(2) - for i in range(32): - expected = 0xBB if (i < 16 and (i % 2 == 0)) else 0xAA - self.assertEqual(res[i], expected) - - def test_disjunction_or_mask(self) -> None: - """s_or_b32: active when condition A OR condition B holds.""" - wave = AluCndmaskMixInterpreter(wave_size=32) - # Condition A: lanes 0..7 (0x000000FF) - # Condition B: lanes 24..31 (0xFF000000) - wave.execute_s_mov_b32(dst_s=10, val=0x000000FF) - wave.execute_s_mov_b32(dst_s=12, val=0xFF000000) - wave.execute_s_or_b32(dst_s=14, s0="s10", s1="s12") - self.assertEqual(wave.sgprs[14], 0xFF0000FF) - - wave.init_vgpr(0, 100) - wave.init_vgpr(1, 200) - wave.execute_v_cndmask_e64(dst_v=2, src0="v0", src1="v1", cond_src="s14") - - res = wave.get_vgpr(2) - for i in range(32): - expected = 200 if (i < 8 or i >= 24) else 100 - self.assertEqual(res[i], expected) - - def test_exclusive_xor_mask(self) -> None: - """s_xor_b32: active when exactly one of condition A or B holds.""" - wave = AluCndmaskMixInterpreter(wave_size=32) - maskA = 0xAAAAAAAA - maskB = 0x0000FFFF - wave.execute_s_mov_b32(dst_s=2, val=maskA) - wave.execute_s_mov_b32(dst_s=4, val=maskB) - wave.execute_s_xor_b32(dst_s=6, s0="s2", s1="s4") - expected_mask = (maskA ^ maskB) & MASK32 - self.assertEqual(wave.sgprs[6], expected_mask) - - wave.init_vgpr(0, 0) - wave.init_vgpr(1, 1) - wave.execute_v_cndmask_e64(dst_v=5, src0="v0", src1="v1", cond_src="s6") - res = wave.get_vgpr(5) - for i in range(32): - self.assertEqual(res[i], (expected_mask >> i) & 1) - - def test_inhibit_andn2_mask(self) -> None: - """s_andn2_b32: active when A holds AND B does NOT hold (A & ~B).""" - wave = AluCndmaskMixInterpreter(wave_size=32) - # A: all odd lanes (0xAAAAAAAA) - # B: high half (0xFFFF0000) - # A & ~B: odd lanes in low half (0x0000AAAA) - wave.execute_s_mov_b32(dst_s=2, val=0xAAAAAAAA) - wave.execute_s_mov_b32(dst_s=4, val=0xFFFF0000) - wave.execute_s_andn2_b32(dst_s=6, s0="s2", s1="s4") - self.assertEqual(wave.sgprs[6], 0x0000AAAA) - - wave.init_vgpr(0, 10) - wave.init_vgpr(1, 99) - wave.execute_v_cndmask_e64(dst_v=7, src0="v0", src1="v1", cond_src="s6") - res = wave.get_vgpr(7) - for i in range(32): - self.assertEqual(res[i], 99 if (i < 16 and (i % 2 == 1)) else 10) - - def test_walking_one_hot_and_one_cold_masks(self) -> None: - """Walks an isolated single-bit condition (one-hot) and single-bit clear (one-cold).""" - wave = AluCndmaskMixInterpreter(wave_size=32) - wave.init_vgpr(0, 0x1111) - wave.init_vgpr(1, 0x2222) - - for bit in range(32): - one_hot = 1 << bit - one_cold = (~one_hot) & MASK32 - - # One-hot: only lane `bit` selects src1 - wave.execute_s_mov_b32(dst_s=4, val=one_hot) - wave.execute_v_cndmask_e64(dst_v=2, src0="v0", src1="v1", cond_src="s4") - res_hot = wave.get_vgpr(2) - for i in range(32): - self.assertEqual(res_hot[i], 0x2222 if i == bit else 0x1111) - - # One-cold: only lane `bit` selects src0 - wave.execute_s_mov_b32(dst_s=5, val=one_cold) - wave.execute_v_cndmask_e64(dst_v=3, src0="v0", src1="v1", cond_src="s5") - res_cold = wave.get_vgpr(3) - for i in range(32): - self.assertEqual(res_cold[i], 0x1111 if i == bit else 0x2222) - - -class TestMixedVectorSelectShaderIdioms(unittest.TestCase): - """Verifies complex shader idioms: clamping, multiplexers, signum, safe division, windowing.""" - - def test_branchless_float_clamping(self) -> None: - """Clamps float values to [min_f, max_f] using two v_cmp and v_cndmask stages: - v_cmp_lt_f32 vcc_lo, v_val, v_min - v_cndmask_b32 v_tmp, v_val, v_min, vcc_lo - v_cmp_gt_f32 vcc_lo, v_tmp, v_max - v_cndmask_b32 v_out, v_tmp, v_max, vcc_lo - """ - wave = AluCndmaskMixInterpreter(wave_size=32) - # Inputs spanning [-10.0, 10.0] - test_floats = [-10.0 + (i * 0.645) for i in range(32)] - wave.init_vgpr(0, [f32_to_bits(f) for f in test_floats]) - min_val = -2.5 - max_val = 5.0 - wave.execute_s_mov_b32(dst_s=4, val=f32_to_bits(min_val)) - wave.execute_s_mov_b32(dst_s=5, val=f32_to_bits(max_val)) - - # Stage 1: if val < min_val -> min_val else val - wave.execute_v_cmp("lt_f32", src0="v0", src1="s4", dst_mask="vcc") - wave.execute_v_cndmask_e32(dst_v=1, src0="v0", src1="s4") - - # Stage 2: if tmp > max_val -> max_val else tmp - wave.execute_v_cmp("gt_f32", src0="v1", src1="s5", dst_mask="vcc") - wave.execute_v_cndmask_e32(dst_v=2, src0="v1", src1="s5") - - res = [bits_to_f32(b) for b in wave.get_vgpr(2)] - for i in range(32): - expected = max(min_val, min(max_val, test_floats[i])) - self.assertAlmostEqual(res[i], expected, places=5) - - def test_signed_integer_clamp(self) -> None: - """Signed integer clamp to [-100, +200].""" - wave = AluCndmaskMixInterpreter(wave_size=32) - test_ints = [-250 + (i * 18) for i in range(32)] - wave.init_vgpr(0, [x & MASK32 for x in test_ints]) - - min_val = -100 - max_val = 200 - wave.execute_s_mov_b32(dst_s=10, val=min_val & MASK32) - wave.execute_s_mov_b32(dst_s=11, val=max_val & MASK32) - - # Stage 1: v1 = (v0 < min_val) ? min_val : v0 - wave.execute_v_cmp("lt_i32", "v0", "s10", dst_mask="vcc") - wave.execute_v_cndmask_e32(dst_v=1, src0="v0", src1="s10") - - # Stage 2: v2 = (v1 > max_val) ? max_val : v1 - wave.execute_v_cmp("gt_i32", "v1", "s11", dst_mask="vcc") - wave.execute_v_cndmask_e32(dst_v=2, src0="v1", src1="s11") - - res = [s32(x) for x in wave.get_vgpr(2)] - for i in range(32): - expected = max(min_val, min(max_val, test_ints[i])) - self.assertEqual(res[i], expected) - - def test_cascaded_3way_multiplexer(self) -> None: - """Ternary multiplexer: condA ? A : (condB ? B : C). - Stage 1: v_tmp = cndmask(C, B, condB) - Stage 2: v_out = cndmask(v_tmp, A, condA) - """ - wave = AluCndmaskMixInterpreter(wave_size=32) - # Selectors: - # condA is true for lanes where (lane % 3 == 0) - # condB is true for lanes where (lane % 3 == 1) - # neither for lanes where (lane % 3 == 2) - condA = sum(1 << i for i in range(32) if i % 3 == 0) - condB = sum(1 << i for i in range(32) if i % 3 == 1) - - wave.execute_s_mov_b32(dst_s=4, val=condA) - wave.execute_s_mov_b32(dst_s=5, val=condB) - - wave.init_vgpr(10, 0xAAAA0000) # Value A - wave.init_vgpr(11, 0xBBBB0000) # Value B - wave.init_vgpr(12, 0xCCCC0000) # Value C (default) - - # Stage 1: choose between C and B using condB - wave.execute_v_cndmask_e64(dst_v=20, src0="v12", src1="v11", cond_src="s5") - # Stage 2: choose between stage 1 result and A using condA - wave.execute_v_cndmask_e64(dst_v=21, src0="v20", src1="v10", cond_src="s4") - - res = wave.get_vgpr(21) - for i in range(32): - if i % 3 == 0: - self.assertEqual(res[i], 0xAAAA0000) - elif i % 3 == 1: - self.assertEqual(res[i], 0xBBBB0000) - else: - self.assertEqual(res[i], 0xCCCC0000) - - def test_cascaded_4way_priority_encoder(self) -> None: - """4-way priority multiplexer: - cond0 ? D0 : (cond1 ? D1 : (cond2 ? D2 : D3)) - """ - wave = AluCndmaskMixInterpreter(wave_size=32) - cond0 = 0x11111111 - cond1 = 0x22222222 - cond2 = 0x44444444 - wave.execute_s_mov_b32(dst_s=0, val=cond0) - wave.execute_s_mov_b32(dst_s=1, val=cond1) - wave.execute_s_mov_b32(dst_s=2, val=cond2) - - wave.init_vgpr(0, 0xD0) - wave.init_vgpr(1, 0xD1) - wave.init_vgpr(2, 0xD2) - wave.init_vgpr(3, 0xD3) - - # Stage 1: select between D3 and D2 via cond2 - wave.execute_v_cndmask_e64(dst_v=10, src0="v3", src1="v2", cond_src="s2") - # Stage 2: select between above and D1 via cond1 - wave.execute_v_cndmask_e64(dst_v=11, src0="v10", src1="v1", cond_src="s1") - # Stage 3: select between above and D0 via cond0 - wave.execute_v_cndmask_e64(dst_v=12, src0="v11", src1="v0", cond_src="s0") - - res = wave.get_vgpr(12) - for i in range(32): - if (cond0 >> i) & 1: - self.assertEqual(res[i], 0xD0) - elif (cond1 >> i) & 1: - self.assertEqual(res[i], 0xD1) - elif (cond2 >> i) & 1: - self.assertEqual(res[i], 0xD2) - else: - self.assertEqual(res[i], 0xD3) - - def test_binary_tree_2bit_decoder(self) -> None: - """2-bit binary decision tree with 2 selector masks (sel_bit0, sel_bit1): - Input candidates: [C0, C1, C2, C3] - Level 1: - T0 = cndmask(C0, C1, sel_bit0) # low branch - T1 = cndmask(C2, C3, sel_bit0) # high branch - Level 2: - Out = cndmask(T0, T1, sel_bit1) - """ - wave = AluCndmaskMixInterpreter(wave_size=32) - # Cycle through 0, 1, 2, 3 across the wave: lane index mod 4 - sel0 = sum(1 << i for i in range(32) if (i % 4) in (1, 3)) - sel1 = sum(1 << i for i in range(32) if (i % 4) in (2, 3)) - wave.execute_s_mov_b32(dst_s=4, val=sel0) - wave.execute_s_mov_b32(dst_s=5, val=sel1) - - wave.init_vgpr(0, 0xC000) - wave.init_vgpr(1, 0xC100) - wave.init_vgpr(2, 0xC200) - wave.init_vgpr(3, 0xC300) - - # Level 1 - wave.execute_v_cndmask_e64(dst_v=10, src0="v0", src1="v1", cond_src="s4") - wave.execute_v_cndmask_e64(dst_v=11, src0="v2", src1="v3", cond_src="s4") - - # Level 2 - wave.execute_v_cndmask_e64(dst_v=12, src0="v10", src1="v11", cond_src="s5") - - res = wave.get_vgpr(12) - for i in range(32): - mode = i % 4 - expected = [0xC000, 0xC100, 0xC200, 0xC300][mode] - self.assertEqual(res[i], expected) - - def test_branchless_signum(self) -> None: - """Branchless integer signum: (x > 0) ? +1 : ((x < 0) ? -1 : 0).""" - wave = AluCndmaskMixInterpreter(wave_size=32) - # Mix of positive, negative, and zeros - test_vals = [(-15 + i) for i in range(32)] - wave.init_vgpr(0, [x & MASK32 for x in test_vals]) - - # Step 1: compare x < 0 -> vcc - wave.execute_v_cmp("lt_i32", "v0", 0, dst_mask="vcc") - # Step 2: v1 = (x < 0) ? -1 : 0 - wave.execute_v_cndmask_e32(dst_v=1, src0=0, src1=0xFFFFFFFF) - - # Step 3: compare x > 0 -> s4 - wave.execute_v_cmp("gt_i32", "v0", 0, dst_mask="s4") - # Step 4: v2 = (x > 0) ? +1 : v1 - wave.execute_v_cndmask_e64(dst_v=2, src0="v1", src1=1, cond_src="s4") - - res = [s32(x) for x in wave.get_vgpr(2)] - for i in range(32): - v = test_vals[i] - expected = 1 if v > 0 else (-1 if v < 0 else 0) - self.assertEqual(res[i], expected) - - def test_safe_division_with_fallback(self) -> None: - """Branchless safe-divide: if divisor == 0 -> fallback_value else (num // denom).""" - wave = AluCndmaskMixInterpreter(wave_size=32) - numerators = [100 + i * 10 for i in range(32)] - denominators = [(i % 5) for i in range(32)] # 0, 1, 2, 3, 4 repeating - wave.init_vgpr(0, numerators) - wave.init_vgpr(1, denominators) - - # Computed division with zero replaced by 1 to prevent division by zero in SIMD ALU - safe_div_results = [ - (numerators[i] // (denominators[i] if denominators[i] != 0 else 1)) & MASK32 - for i in range(32) - ] - wave.init_vgpr(2, safe_div_results) - fallback = 0xDEADBEEF - wave.execute_s_mov_b32(dst_s=4, val=fallback) - - # Compare denominator == 0 - wave.execute_v_cmp("eq_u32", "v1", 0, dst_mask="vcc") - # Select fallback if denom == 0 else safe_div_result - wave.execute_v_cndmask_e32(dst_v=3, src0="v2", src1="s4") - - res = wave.get_vgpr(3) - for i in range(32): - if denominators[i] == 0: - self.assertEqual(res[i], fallback) - else: - self.assertEqual(res[i], numerators[i] // denominators[i]) - - def test_rectangular_window_pulse(self) -> None: - """Window pulse: 1 if lo <= x <= hi else 0. - Synthesized via: - v_cmp_ge_u32 s4, x, lo - v_cmp_le_u32 s5, x, hi - s_and_b32 s6, s4, s5 - v_cndmask_b32 dst, 0, 1, s6 - """ - wave = AluCndmaskMixInterpreter(wave_size=32) - x_vals = list(range(32)) - wave.init_vgpr(0, x_vals) - lo = 10 - hi = 20 - - wave.execute_v_cmp("ge_u32", "v0", lo, dst_mask="s4") - wave.execute_v_cmp("le_u32", "v0", hi, dst_mask="s5") - wave.execute_s_and_b32(dst_s=6, s0="s4", s1="s5") - - wave.execute_v_cndmask_e64(dst_v=1, src0=0, src1=1, cond_src="s6") - res = wave.get_vgpr(1) - for i in range(32): - expected = 1 if (lo <= i <= hi) else 0 - self.assertEqual(res[i], expected) - - def test_interleaved_channel_mux(self) -> None: - """Interleaves vector components: even lanes take channel A, odd lanes take channel B.""" - wave = AluCndmaskMixInterpreter(wave_size=32) - chanA = [0xA000 + i for i in range(32)] - chanB = [0xB000 + i for i in range(32)] - wave.init_vgpr(0, chanA) - wave.init_vgpr(1, chanB) - - # Alternating mask - wave.set_vcc(0xAAAAAAAA) # odd lanes select chanB - wave.execute_v_cndmask_e32(dst_v=2, src0="v0", src1="v1") - - res = wave.get_vgpr(2) - for i in range(32): - self.assertEqual(res[i], chanB[i] if (i % 2 == 1) else chanA[i]) - - -class TestExecAndConditionMaskInteractions(unittest.TestCase): - """Verifies EXEC mask interactions: inactive lane preservation, then/else branching, and no-ops.""" - - def test_inactive_lane_preservation_with_all_true_condition(self) -> None: - """Even when condition mask has all 1s, inactive lanes (EXEC == 0) must remain intact.""" - wave = AluCndmaskMixInterpreter(wave_size=32) - initial_dst = [0x5500 + i for i in range(32)] - wave.init_vgpr(2, initial_dst) - wave.init_vgpr(0, 0x10) - wave.init_vgpr(1, 0x20) - - # Only lanes 8..15 are active - exec_active = 0x0000FF00 - wave.set_exec(exec_active) - wave.set_vcc(0xFFFFFFFF) # all condition bits 1 - - wave.execute_v_cndmask_e32(dst_v=2, src0="v0", src1="v1") - res = wave.get_vgpr(2) - - for i in range(32): - if 8 <= i < 16: - self.assertEqual(res[i], 0x20) - else: - self.assertEqual(res[i], initial_dst[i]) - - def test_structured_then_else_divergence_emulation(self) -> None: - """Emulates complete structured divergent control flow: - v_cmp_lt_u32 -> s_and_saveexec (Then) -> v_cndmask -> s_xor_saveexec (Else) -> v_cndmask -> restore. - """ - wave = AluCndmaskMixInterpreter(wave_size=32) - wave.init_vgpr(0, list(range(32))) # lane ids - wave.init_vgpr(1, 0xAAAA) # then payload - wave.init_vgpr(2, 0xBBBB) # else payload - background = [0x9999 for _ in range(32)] - wave.init_vgpr(3, background) - - # Condition: lane < 12 - wave.execute_v_cmp("lt_u32", "v0", 12, dst_mask="vcc") - self.assertEqual(wave.vcc, 0x00000FFF) - - # 1. Enter Then branch: save EXEC and narrow to vcc - wave.execute_s_and_saveexec_b32(dst_s=4, mask_src="vcc") - self.assertEqual(wave.exec_mask, 0x00000FFF) - - # Execute in Then block: update dst - wave.execute_v_cndmask_e32(dst_v=3, src0=0, src1="v1") - # Lanes 0..11 should now have 0xAAAA, 12..31 still background - for i in range(12): - self.assertEqual(wave.vgprs[i][3], 0xAAAA) - for i in range(12, 32): - self.assertEqual(wave.vgprs[i][3], 0x9999) - - # 2. Enter Else branch: EXEC = saved_exec ^ then_mask = ~vcc - saved_exec = wave.sgprs[4] - wave.set_exec((saved_exec & (~wave.vcc & MASK32))) - self.assertEqual(wave.exec_mask, 0xFFFFF000) - - # Execute in Else block: update dst - wave.execute_v_cndmask_e32(dst_v=3, src0="v2", src1=0) - - # 3. Restore EXEC - wave.set_exec(saved_exec) - self.assertEqual(wave.exec_mask, 0xFFFFFFFF) - - res = wave.get_vgpr(3) - for i in range(32): - if i < 12: - self.assertEqual(res[i], 0xAAAA) - else: - self.assertEqual(res[i], 0xBBBB) - - def test_zero_exec_whole_wave_nop(self) -> None: - """With EXEC == 0, multiple chained conditional moves have zero side effects.""" - wave = AluCndmaskMixInterpreter(wave_size=32) - init_state = [0xBADC0DE0 + i for i in range(32)] - wave.init_vgpr(2, init_state) - wave.set_exec(0x00000000) - wave.set_vcc(0xFFFFFFFF) - - wave.execute_v_cndmask_e32(dst_v=2, src0=1, src1=2) - wave.execute_v_cndmask_e64(dst_v=2, src0=3, src1=4, cond_src=0xFFFFFFFF) - - self.assertEqual(wave.get_vgpr(2), init_state) - - def test_walking_single_active_exec_lane(self) -> None: - """Walking a single active EXEC bit across all 32 lanes.""" - for active_lane in range(32): - wave = AluCndmaskMixInterpreter(wave_size=32) - bg = [0x7000 + i for i in range(32)] - wave.init_vgpr(2, bg) - wave.set_exec(1 << active_lane) - wave.set_vcc(0xFFFFFFFF) - - wave.execute_v_cndmask_e32(dst_v=2, src0=0x11, src1=0x99) - res = wave.get_vgpr(2) - for i in range(32): - if i == active_lane: - self.assertEqual(res[i], 0x99) - else: - self.assertEqual(res[i], bg[i]) - - -class TestWave64MixedMaskConfigurations(unittest.TestCase): - """Verifies Wave64 (64 lanes) execution with 64-bit mask registers and cross-half patterns.""" - - def test_wave64_cross_half_divergent_select(self) -> None: - """Low-half (lanes 0..31) and high-half (lanes 32..63) use distinct mask patterns.""" - wave = AluCndmaskMixInterpreter(wave_size=64) - src0 = [0x1000 + i for i in range(64)] - src1 = [0x2000 + i for i in range(64)] - wave.init_vgpr(0, src0) - wave.init_vgpr(1, src1) - - # Low half VCC: 0x55555555 (even lanes true) - # High half VCC: 0x0000FFFF (low 16 lanes of high half true) - vcc64 = 0x55555555 | (0x0000FFFF << 32) - wave.set_vcc(vcc64) - - wave.execute_v_cndmask_e32(dst_v=2, src0="v0", src1="v1") - res = wave.get_vgpr(2) - - for i in range(64): - c = (vcc64 >> i) & 1 - expected = src1[i] if c else src0[i] - self.assertEqual(res[i], expected) - - def test_wave64_sgpr_pair_mask_e64(self) -> None: - """Wave64 conditional select reading 64-bit mask from SGPR pair s[4:5].""" - wave = AluCndmaskMixInterpreter(wave_size=64) - src0 = [0x3000 + i for i in range(64)] - src1 = [0x7000 + i for i in range(64)] - wave.init_vgpr(0, src0) - wave.init_vgpr(1, src1) - - mask_lo = 0xAAAAAAAA - mask_hi = 0x12345678 - wave.execute_s_mov_b32(dst_s=4, val=mask_lo) - wave.execute_s_mov_b32(dst_s=5, val=mask_hi) - mask64 = (mask_lo & MASK32) | ((mask_hi & MASK32) << 32) - - wave.execute_v_cndmask_e64(dst_v=2, src0="v0", src1="v1", cond_src="s[4:5]") - res = wave.get_vgpr(2) - - for i in range(64): - expected = src1[i] if ((mask64 >> i) & 1) else src0[i] - self.assertEqual(res[i], expected) - - def test_wave64_half_disabled_execution(self) -> None: - """Wave64 with low half active only, or high half active only.""" - wave = AluCndmaskMixInterpreter(wave_size=64) - bg = [0x8800 + i for i in range(64)] - wave.init_vgpr(2, bg) - wave.init_vgpr(0, 0x10) - wave.init_vgpr(1, 0x20) - wave.set_vcc(MASK64) - - # Case 1: Low half active only - wave.set_exec(0x00000000FFFFFFFF) - wave.execute_v_cndmask_e32(dst_v=2, src0="v0", src1="v1") - res1 = wave.get_vgpr(2) - self.assertEqual(res1[:32], [0x20] * 32) - self.assertEqual(res1[32:], bg[32:]) - - # Case 2: High half active only - wave.init_vgpr(2, bg) - wave.set_exec(0xFFFFFFFF00000000) - wave.execute_v_cndmask_e32(dst_v=2, src0="v0", src1="v1") - res2 = wave.get_vgpr(2) - self.assertEqual(res2[:32], bg[:32]) - self.assertEqual(res2[32:], [0x20] * 32) - - def test_wave64_randomized_divergence_crosscheck(self) -> None: - """Cross-checks 30 pseudo-random 64-bit masks against reference oracle.""" - rng = random.Random(20261122) - for trial in range(30): - with self.subTest(trial=trial): - wave = AluCndmaskMixInterpreter(wave_size=64) - src0 = [rng.getrandbits(32) for _ in range(64)] - src1 = [rng.getrandbits(32) for _ in range(64)] - prev = [rng.getrandbits(32) for _ in range(64)] - cond = rng.getrandbits(64) - exec_m = rng.getrandbits(64) - - wave.init_vgpr(0, src0) - wave.init_vgpr(1, src1) - wave.init_vgpr(2, prev) - wave.set_vcc(cond) - wave.set_exec(exec_m) - - wave.execute_v_cndmask_e32(dst_v=2, src0="v0", src1="v1") - oracle_expected = ref_cndmask_wave(src0, src1, cond, exec_m, prev, wave_size=64) - self.assertEqual(wave.get_vgpr(2), oracle_expected) - - -class TestSpirvSyntheticShaderExecution(unittest.TestCase): - """Verifies end-to-end SPIR-V translation and execution via rdna2spirv & spirv_mini_interp.""" - - def test_spirv_immediate_selects(self) -> None: - """v_cndmask_b32 selecting between immediate values.""" - lines = [ - "v_cmp_gt_u32_e32 vcc_lo, 50, 20", - "v_cndmask_b32_e32 v0, 10, 20, vcc_lo", - "v_cmp_lt_u32_e32 vcc_lo, 50, 20", - "v_cndmask_b32_e32 v1, 10, 20, vcc_lo", - "v_mov_b32 v2, 0", - "v_mov_b32 v3, 0", - ] - out = run_synthetic_ps(lines) - self.assertEqual(out[0], 20) # 50 > 20 is true -> selects src1 (20) - self.assertEqual(out[1], 10) # 50 < 20 is false -> selects src0 (10) - - def test_spirv_sgpr_condition_mask_e64(self) -> None: - """v_cndmask_b32_e64 reading condition from SGPR s4 and s6.""" - lines = [ - "s_mov_b32 s4, 1", - "s_mov_b32 s6, 0", - "v_mov_b32 v10, 111", - "v_mov_b32 v11, 222", - "v_cndmask_b32_e64 v0, v10, v11, s4", - "v_cndmask_b32_e64 v1, v10, v11, s6", - "v_mov_b32 v2, 0", - "v_mov_b32 v3, 0", - ] - out = run_synthetic_ps(lines) - self.assertEqual(out[0], 222) - self.assertEqual(out[1], 111) - - def test_spirv_branchless_clamping(self) -> None: - """Branchless integer clamping in SPIR-V: clamp(x, 10, 50).""" - test_cases = [(5, 10), (30, 30), (75, 50), (10, 10), (50, 50)] - for x_val, expected in test_cases: - lines = [ - f"v_mov_b32 v10, {x_val}", - # if x < 10 -> 10 else x - "v_cmp_lt_u32_e32 vcc_lo, v10, 10", - "v_cndmask_b32_e32 v11, v10, 10, vcc_lo", - # if v11 > 50 -> 50 else v11 - "v_cmp_gt_u32_e32 vcc_lo, v11, 50", - "v_cndmask_b32_e32 v0, v11, 50, vcc_lo", - "v_mov_b32 v1, 0", - "v_mov_b32 v2, 0", - "v_mov_b32 v3, 0", - ] - out = run_synthetic_ps(lines) - self.assertEqual(out[0], expected) - - def test_spirv_cascaded_ternary_mux(self) -> None: - """Cascaded conditional moves in SPIR-V: (x == 1) ? 100 : ((x == 2) ? 200 : 300).""" - for x_val, expected in ((1, 100), (2, 200), (9, 300)): - lines = [ - f"v_mov_b32 v10, {x_val}", - "v_cmp_eq_u32_e32 vcc_lo, v10, 2", - "v_cndmask_b32_e32 v20, 300, 200, vcc_lo", - "v_cmp_eq_u32_e32 vcc_lo, v10, 1", - "v_cndmask_b32_e32 v0, v20, 100, vcc_lo", - "v_mov_b32 v1, 0", - "v_mov_b32 v2, 0", - "v_mov_b32 v3, 0", - ] - out = run_synthetic_ps(lines) - self.assertEqual(out[0], expected) - - -class TestNegativeControlsAndSensitivity(unittest.TestCase): - """Negative controls and sensitivity verification against corruptions.""" - - def test_single_bit_flip_sensitivity(self) -> None: - """Flipping exactly 1 bit in the condition mask alters strictly that lane and no other.""" - wave = AluCndmaskMixInterpreter(wave_size=32) - s0 = [0x1000 + i for i in range(32)] - s1 = [0x5000 + i for i in range(32)] - wave.init_vgpr(0, s0) - wave.init_vgpr(1, s1) - - base_vcc = 0xAAAAAAAA - wave.set_vcc(base_vcc) - wave.execute_v_cndmask_e32(dst_v=2, src0="v0", src1="v1") - base_res = wave.get_vgpr(2) - - for flip_lane in range(32): - wave.set_vcc(base_vcc ^ (1 << flip_lane)) - wave.execute_v_cndmask_e32(dst_v=3, src0="v0", src1="v1") - flipped_res = wave.get_vgpr(3) - - for lane in range(32): - if lane == flip_lane: - self.assertNotEqual(flipped_res[lane], base_res[lane]) - else: - self.assertEqual(flipped_res[lane], base_res[lane]) - - def test_condition_inversion_sensitivity(self) -> None: - """Inverting the condition mask inverts selections across every differing lane.""" - wave = AluCndmaskMixInterpreter(wave_size=32) - s0 = [100 + i for i in range(32)] - s1 = [900 + i for i in range(32)] - wave.init_vgpr(0, s0) - wave.init_vgpr(1, s1) - - vcc = 0x55AA55AA - wave.set_vcc(vcc) - wave.execute_v_cndmask_e32(dst_v=2, src0="v0", src1="v1") - res_normal = wave.get_vgpr(2) - - wave.set_vcc((~vcc) & MASK32) - wave.execute_v_cndmask_e32(dst_v=3, src0="v0", src1="v1") - res_inverted = wave.get_vgpr(3) - - for i in range(32): - self.assertNotEqual(res_normal[i], res_inverted[i]) - - def test_zero_exec_corruption_rejection(self) -> None: - """With EXEC == 0, registers remain byte-for-byte identical to background state.""" - wave = AluCndmaskMixInterpreter(wave_size=32) - bg = [0xDEADBEEF for _ in range(32)] - wave.init_vgpr(2, bg) - wave.set_exec(0) - wave.set_vcc(0xFFFFFFFF) - - wave.execute_v_cndmask_e32(dst_v=2, src0=0x11111111, src1=0x22222222) - self.assertEqual(wave.get_vgpr(2), bg) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_alu_cvt_16.py b/tests/semantic/test_alu_cvt_16.py deleted file mode 100644 index a17c65654..000000000 --- a/tests/semantic/test_alu_cvt_16.py +++ /dev/null @@ -1,173 +0,0 @@ -"""Semantic interpreter tests for RDNA2 v_cvt_f16_u16, v_cvt_f16_i16, v_cvt_u16_f16 and v_cvt_i16_f16. - -The int -> f16 forms convert the low 16-bit half and round to nearest even (65520 and above give +infinity); the -f16 -> int forms truncate toward zero, saturate to the 16-bit range (an f16 infinity too) and give 0 for NaN, as the -32-bit conversions do (docs/design.md, "Float-to-int saturation"). op_sel:[src,dst] picks the high half of the -source / of the destination in the VOP3 form; the other half of the destination is kept. Each case translates a -synthetic pixel shader with tools/rdna2spirv.py, runs it in tests/semantic/spirv_mini_interp.py and compares the exported word with a -plain-Python reference. Not measured on hardware: the kept half and the behaviour of `clamp` and output -multipliers, which the translator rejects. -""" -import itertools -import math -import os -import random -import struct -import sys -import tempfile -import unittest -import warnings - -HERE = os.path.dirname(os.path.abspath(__file__)) -ROOT = os.path.dirname(os.path.dirname(HERE)) -TOOLS_DIR = os.environ.get("LEONIDA_TOOLS_DIR") or os.path.join(ROOT, "tools") - -sys.dont_write_bytecode = True -sys.path.insert(0, TOOLS_DIR) -sys.path.insert(0, HERE) - -import rdna2spirv # noqa: E402 -import spirv_mini_interp as si # noqa: E402 - -STUB_DXBC = b"DXBC" + bytes(24) + struct.pack(" int: - if _TMP_DIR is None: - setUpModule() - lines = [f"v_mov_b32 v1, {v1:#x}", f"v_mov_b32 v0, {old:#x}", line] - asm = "; test_cvt16\n" + "".join(f"\t{ln}\n" for ln in lines) + "\texp mrt0 v0, v0, v0, v0 done vm\n\ts_endpgm\n" - with open(_SRC_PATH, "w", encoding="utf-8") as f: - f.write(asm) - with warnings.catch_warnings(): - warnings.simplefilter("ignore", ResourceWarning) - spv = rdna2spirv.translate(_SRC_PATH) - return si.run_fragment(spv)["%out_mrt0"][0] - - -def h2f(h: int) -> float: - return struct.unpack(" int: - try: - return struct.unpack(" 0 else 0xFC00 - - -def merge(old: int, h: int, dst_hi: int) -> int: - h &= 0xFFFF - return (h << 16 | old & 0xFFFF) if dst_hi else (old & 0xFFFF0000 | h) - - -def ref_to_int(op: str, h: int) -> int: - x = h2f(h) - lo, hi = (-32768, 32767) if op == "v_cvt_i16_f16" else (0, 65535) - if math.isnan(x): - return 0 - if math.isinf(x): - return (hi if x > 0 else lo) & 0xFFFF - return max(lo, min(hi, math.trunc(x))) & 0xFFFF - - -def ref_to_f16(op: str, v: int) -> int: - v &= 0xFFFF - if op == "v_cvt_f16_i16" and v & 0x8000: - v -= 0x10000 - return f2h(float(v)) - - -def half(word: int, hi: int) -> int: - return (word >> 16 if hi else word) & 0xFFFF - - -class IntToF16Tests(unittest.TestCase): - def test_known_values(self): - self.assertEqual(run("v_cvt_f16_u16 v0, v1", 0x1234_0003), merge(OLD, 0x4200, 0)) # 3.0 - self.assertEqual(run("v_cvt_f16_i16 v0, v1", 0x0000_FFFD), merge(OLD, 0xC200, 0)) # -3.0 - self.assertEqual(run("v_cvt_f16_u16 v0, v1", 0xFFFF), merge(OLD, 0x7C00, 0)) # 65535 -> +inf - self.assertEqual(run("v_cvt_f16_u16 v0, v1", 0xFFEF), merge(OLD, 0x7BFF, 0)) # 65519 -> 65504 - self.assertEqual(run("v_cvt_f16_u16 v0, v1", 0xFFF0), merge(OLD, 0x7C00, 0)) # 65520 -> +inf - self.assertEqual(run("v_cvt_f16_i16 v0, v1", 0x8000), merge(OLD, 0xF800, 0)) # -32768 - - def test_op_sel_and_keeps_the_other_half(self): - v = 0x0005_FFFE - for op in ("v_cvt_f16_u16", "v_cvt_f16_i16"): - for bits in itertools.product((0, 1), repeat=2): - line = f"{op}_e64 v0, v1 op_sel:[{bits[0]},{bits[1]}]" - with self.subTest(line=line): - want = merge(OLD, ref_to_f16(op, half(v, bits[0])), bits[1]) - self.assertEqual(run(line, v), want) - - def test_random_against_the_reference(self): - rng = random.Random(0xC16) - for op in ("v_cvt_f16_u16", "v_cvt_f16_i16"): - for _ in range(60): - v = rng.randrange(0x10000) if rng.random() < 0.8 else rng.choice([0, 1, 0x7FFF, 0x8000, 0xFFEF, 0xFFF0]) - with self.subTest(op=op, v=hex(v)): - self.assertEqual(run(f"{op} v0, v1", v | 0xBEEF0000), merge(OLD, ref_to_f16(op, v), 0)) - - -class F16ToIntTests(unittest.TestCase): - def test_known_values(self): - for op, h, want in (("v_cvt_u16_f16", 0x4248, 3), ("v_cvt_i16_f16", 0xC248, -3 & 0xFFFF), # 3.14 / -3.14 - ("v_cvt_u16_f16", 0xBC00, 0), ("v_cvt_u16_f16", 0x7BFF, 0xFFE0), # -1.0, 65504 (in range) - ("v_cvt_i16_f16", 0x7BFF, 0x7FFF), ("v_cvt_i16_f16", 0xFBFF, 0x8000), - ("v_cvt_u16_f16", 0x7C00, 0xFFFF), ("v_cvt_u16_f16", 0xFC00, 0), - ("v_cvt_i16_f16", 0x7C00, 0x7FFF), ("v_cvt_i16_f16", 0xFC00, 0x8000), - ("v_cvt_u16_f16", 0x7E00, 0), ("v_cvt_i16_f16", 0x7E00, 0), # NaN - ("v_cvt_i16_f16", 0x3800, 0), ("v_cvt_i16_f16", 0xB800, 0)): # +-0.5 truncates to 0 - with self.subTest(op=op, h=hex(h)): - self.assertEqual(run(f"{op} v0, v1", h), merge(OLD, want, 0)) - - def test_op_sel_and_keeps_the_other_half(self): - v = 0xC248_4248 # lo 3.14, hi -3.14 - for op in ("v_cvt_u16_f16", "v_cvt_i16_f16"): - for bits in itertools.product((0, 1), repeat=2): - line = f"{op}_e64 v0, v1 op_sel:[{bits[0]},{bits[1]}]" - with self.subTest(line=line): - self.assertEqual(run(line, v), merge(OLD, ref_to_int(op, half(v, bits[0])), bits[1])) - - def test_random_against_the_reference(self): - rng = random.Random(0x16C) - special = [0x0000, 0x8000, 0x0001, 0x03FF, 0x3C00, 0xBC00, 0x7BFF, 0xFBFF, 0x7C00, 0xFC00, 0x7E00, 0x5BFF, 0x7800] - for op in ("v_cvt_u16_f16", "v_cvt_i16_f16"): - for _ in range(80): - h = rng.choice(special) if rng.random() < 0.3 else rng.randrange(0x10000) - with self.subTest(op=op, h=hex(h)): - self.assertEqual(run(f"{op} v0, v1", 0x5555_0000 | h), merge(OLD, ref_to_int(op, h), 0)) - - def test_source_neg_abs(self): - self.assertEqual(run("v_cvt_i16_f16_e64 v0, -v1", 0x4248), merge(OLD, -3 & 0xFFFF, 0)) - self.assertEqual(run("v_cvt_i16_f16_e64 v0, |v1|", 0xC248), merge(OLD, 3, 0)) - - def test_output_modifiers_are_rejected(self): - for line in ("v_cvt_u16_f16_e64 v0, v1 clamp", "v_cvt_i16_f16_e64 v0, v1 mul:2"): - with self.subTest(line=line), self.assertRaises(rdna2spirv.Unsupported): - run(line, 0x4248) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_alu_cvt_f16.py b/tests/semantic/test_alu_cvt_f16.py deleted file mode 100644 index 7070ecd86..000000000 --- a/tests/semantic/test_alu_cvt_f16.py +++ /dev/null @@ -1,613 +0,0 @@ -"""Semantic interpreter tests for RDNA2 float32 <-> float16 conversions: v_cvt_f16_f32 and v_cvt_f32_f16. - -v_cvt_f16_f32 converts a binary32 float in S0 to a binary16 float in D[15:0] with IEEE-754 round to nearest, ties to -even (RNE). On GFX10, this is a 16-bit operation that preserves the high 16 bits D[31:16] of the destination VGPR. -v_cvt_f32_f16 converts a binary16 float in S0[15:0] to a binary32 float in D[31:0], completely overwriting the 32-bit -destination and ignoring S0[31:16]. - -Each test case translates a synthetic pixel shader with tools/rdna2spirv.py, runs it in -tests/semantic/spirv_mini_interp.py, and compares the exported dwords with a plain-Python reference. -The suite verifies: - - Normal binary32 <-> binary16 conversions and exact representation. - - Partial destination preservation of high 16 bits for v_cvt_f16_f32. - - Source high-half masking for v_cvt_f32_f16. - - Signed zero representations (+0.0, -0.0). - - Signed infinities (+inf, -inf). - - Quiet and signaling NaNs. - - Subnormal/denormal conversions in both directions and underflow to signed zero. - - Rounding modes: IEEE-754 round-to-nearest-even tie breaking at normal and subnormal midpoints. - - Overflow threshold to infinity (65504 max finite vs 65520 tie boundary to inf). - - VOP3 source modifiers (negation, absolute value, negated abs). - - SGPR operands and inline constants. - - Lossless roundtrip property: for any finite f16 h, v_cvt_f16_f32(v_cvt_f32_f16(h)) == h. -""" -from __future__ import annotations - -import math -import os -import struct -import sys -import tempfile -import unittest -import warnings - -HERE = os.path.dirname(os.path.abspath(__file__)) -ROOT = os.path.dirname(os.path.dirname(HERE)) -TOOLS_DIR = os.environ.get("LEONIDA_TOOLS_DIR") or os.path.join(ROOT, "tools") - -sys.dont_write_bytecode = True -if TOOLS_DIR not in sys.path: - sys.path.insert(0, TOOLS_DIR) -if HERE not in sys.path: - sys.path.insert(0, HERE) - -import rdna2spirv # noqa: E402 -import spirv_mini_interp as si # noqa: E402 - -MASK32 = 0xFFFFFFFF -MASK16 = 0xFFFF -OLD_HIGH = 0x55AA0000 -STUB_DXBC = b"DXBC" + bytes(24) + struct.pack(" int: - return struct.unpack(" float: - return struct.unpack(" int: - try: - return struct.unpack(" 0 else 0xFC00 - - -def bits_to_f16(bits: int) -> float: - return struct.unpack(" int: - """Pure-Python reference for binary32 -> binary16 conversion.""" - f32_bits &= MASK32 - val = bits_to_f32(f32_bits) - if math.isnan(val): - sign = 0x8000 if (f32_bits & 0x80000000) else 0x0000 - return sign | 0x7E00 - return f16_to_bits(val) - - -def ref_cvt_f32_f16(f16_bits: int) -> int: - """Pure-Python reference for binary16 -> binary32 conversion.""" - f16_bits &= MASK16 - val = bits_to_f16(f16_bits) - if math.isnan(val): - sign = 0x80000000 if (f16_bits & 0x8000) else 0x00000000 - return sign | 0x7FC00000 - return f32_to_bits(val) - - -_TMP_DIR = None -_SRC_PATH = None - - -def setUpModule(): - global _TMP_DIR, _SRC_PATH - _TMP_DIR = tempfile.TemporaryDirectory() - disasm_dir = os.path.join(_TMP_DIR.name, "disasm") - os.mkdir(disasm_dir) - _SRC_PATH = os.path.join(disasm_dir, "ps_cvt_f16.s") - with open(os.path.join(_TMP_DIR.name, "ps_cvt_f16.dxbc"), "wb") as f: - f.write(STUB_DXBC) - - -def tearDownModule(): - global _TMP_DIR - if _TMP_DIR is not None: - _TMP_DIR.cleanup() - _TMP_DIR = None - - -def run_lines(lines: list[str]) -> tuple[int, ...]: - """Assemble and run synthetic pixel shader lines, returning out_mrt0 registers.""" - if _TMP_DIR is None: - setUpModule() - asm = "; test_alu_cvt_f16\n" + "".join(f"\t{ln}\n" for ln in lines) + "\texp mrt0 v0, v1, v2, v3 done vm\n\ts_endpgm\n" - with open(_SRC_PATH, "w", encoding="utf-8") as f: - f.write(asm) - with warnings.catch_warnings(): - warnings.simplefilter("ignore", ResourceWarning) - spv = rdna2spirv.translate(_SRC_PATH) - return tuple(si.run_fragment(spv)["%out_mrt0"]) - - -def run_cvt_f16_f32(src_bits: int, old_dst: int = OLD_HIGH, form: str = "e32") -> int: - """Run v_cvt_f16_f32 and return the 32-bit v0 destination word.""" - lines = [ - f"v_mov_b32 v1, {src_bits:#x}", - f"v_mov_b32 v0, {old_dst:#x}", - f"v_cvt_f16_f32_{form} v0, v1", - ] - return run_lines(lines)[0] - - -def run_cvt_f32_f16(src_word: int, form: str = "e32") -> int: - """Run v_cvt_f32_f16 and return the 32-bit v0 destination word.""" - lines = [ - f"v_mov_b32 v1, {src_word:#x}", - f"v_cvt_f32_f16_{form} v0, v1", - ] - return run_lines(lines)[0] - - -class ReferenceTests(unittest.TestCase): - def test_reference_f16_f32(self): - self.assertEqual(ref_cvt_f16_f32(0x3F800000), 0x3C00) # 1.0 - self.assertEqual(ref_cvt_f16_f32(0xBF800000), 0xBC00) # -1.0 - self.assertEqual(ref_cvt_f16_f32(0x00000000), 0x0000) # +0.0 - self.assertEqual(ref_cvt_f16_f32(0x80000000), 0x8000) # -0.0 - self.assertEqual(ref_cvt_f16_f32(0x7F800000), 0x7C00) # +inf - self.assertEqual(ref_cvt_f16_f32(0xFF800000), 0xFC00) # -inf - self.assertEqual(ref_cvt_f16_f32(0x7FC00000), 0x7E00) # quiet NaN - self.assertEqual(ref_cvt_f16_f32(0xFFC00000), 0xFE00) # negative quiet NaN - self.assertEqual(ref_cvt_f16_f32(0x33800000), 0x0001) # smallest subnormal 2^-24 - - def test_reference_f32_f16(self): - self.assertEqual(ref_cvt_f32_f16(0x3C00), 0x3F800000) # 1.0 - self.assertEqual(ref_cvt_f32_f16(0xBC00), 0xBF800000) # -1.0 - self.assertEqual(ref_cvt_f32_f16(0x0000), 0x00000000) # +0.0 - self.assertEqual(ref_cvt_f32_f16(0x8000), 0x80000000) # -0.0 - self.assertEqual(ref_cvt_f32_f16(0x7C00), 0x7F800000) # +inf - self.assertEqual(ref_cvt_f32_f16(0xFC00), 0xFF800000) # -inf - self.assertEqual(ref_cvt_f32_f16(0x7E00), 0x7FC00000) # quiet NaN - self.assertEqual(ref_cvt_f32_f16(0xFE00), 0xFFC00000) # negative quiet NaN - self.assertEqual(ref_cvt_f32_f16(0x0001), 0x33800000) # smallest subnormal 2^-24 - - -class CvtF16F32Tests(unittest.TestCase): - def test_normal_values(self): - cases = [ - (0x3F800000, 0x3C00), # 1.0 - (0xBF800000, 0xBC00), # -1.0 - (0x3F000000, 0x3800), # 0.5 - (0xBF000000, 0xB800), # -0.5 - (0x40000000, 0x4000), # 2.0 - (0xC0000000, 0xC000), # -2.0 - (0x3FC00000, 0x3E00), # 1.5 - (0xBFC00000, 0xBE00), # -1.5 - (0x40200000, 0x4100), # 2.5 - (0x3E000000, 0x3000), # 0.125 - (0x42280000, 0x5140), # 42.0 - (0x477FE000, 0x7BFF), # 65504.0 (max finite f16) - (0xC77FE000, 0xFBFF), # -65504.0 - ] - for f32_bits, exp_h in cases: - with self.subTest(f32=hex(f32_bits), expected=hex(exp_h)): - got = run_cvt_f16_f32(f32_bits, old_dst=OLD_HIGH) - self.assertEqual(got & 0xFFFF, exp_h) - self.assertEqual(got & 0xFFFF0000, OLD_HIGH) - - def test_preserves_dst_high_half(self): - dst_patterns = [0x00000000, 0x12340000, 0xDEAD0000, 0xFFFF0000, 0x80000000, 0x55AA0000] - for old in dst_patterns: - with self.subTest(old=hex(old)): - got = run_cvt_f16_f32(0x3F800000, old_dst=old) - self.assertEqual(got, old | 0x3C00) - - def test_signed_zeros(self): - # +0.0 - got_pos = run_cvt_f16_f32(0x00000000, old_dst=0x11110000) - self.assertEqual(got_pos, 0x11110000) - - # -0.0 - got_neg = run_cvt_f16_f32(0x80000000, old_dst=0x11110000) - self.assertEqual(got_neg, 0x11118000) - - def test_infinities(self): - # +inf - got_pos = run_cvt_f16_f32(0x7F800000, old_dst=0x22220000) - self.assertEqual(got_pos, 0x22227C00) - - # -inf - got_neg = run_cvt_f16_f32(0xFF800000, old_dst=0x22220000) - self.assertEqual(got_neg, 0x2222FC00) - - def test_nans(self): - # Quiet NaNs - got_qnan = run_cvt_f16_f32(0x7FC00000, old_dst=OLD_HIGH) - self.assertEqual(got_qnan & 0xFFFF, 0x7E00) - self.assertEqual(got_qnan & 0xFFFF0000, OLD_HIGH) - - got_nqnan = run_cvt_f16_f32(0xFFC00000, old_dst=OLD_HIGH) - self.assertEqual(got_nqnan & 0xFFFF, 0xFE00) - self.assertEqual(got_nqnan & 0xFFFF0000, OLD_HIGH) - - # Payload / signaling NaN encodings must produce f16 NaN (exponent 0x1F, non-zero mantissa) - for nan_bits in (0x7F800001, 0x7FA00000, 0xFF800001): - with self.subTest(nan=hex(nan_bits)): - got = run_cvt_f16_f32(nan_bits, old_dst=OLD_HIGH) - h = got & 0xFFFF - self.assertEqual(h & 0x7C00, 0x7C00) - self.assertNotEqual(h & 0x03FF, 0) - self.assertEqual(got & 0xFFFF0000, OLD_HIGH) - - def test_denormals_and_underflow(self): - cases = [ - (0x33800000, 0x0001), # 2^-24 -> smallest positive subnormal - (0xB3800000, 0x8001), # -2^-24 -> smallest negative subnormal - (0x34000000, 0x0002), # 2^-23 -> 2 * 2^-24 - (0x38000000, 0x0200), # 2^-15 -> 512 * 2^-24 - (0x387FC000, 0x03FF), # 1023 * 2^-24 -> largest subnormal - (0xB87FC000, 0x83FF), # negative largest subnormal - (0x32800000, 0x0000), # 2^-26 -> underflow to +0 - (0xB2800000, 0x8000), # -2^-26 -> underflow to -0 - (0x00000001, 0x0000), # smallest f32 denormal -> underflow to +0 - (0x80000001, 0x8000), # smallest negative f32 denormal -> underflow to -0 - ] - for f32_bits, exp_h in cases: - with self.subTest(f32=hex(f32_bits), expected=hex(exp_h)): - got = run_cvt_f16_f32(f32_bits, old_dst=OLD_HIGH) - self.assertEqual(got & 0xFFFF, exp_h) - self.assertEqual(got & 0xFFFF0000, OLD_HIGH) - - def test_rounding_modes_ties_to_even(self): - # 1. Normal range midpoints: - # 1.0 (0x3C00) next is 0x3C01 (step = 2^-10). - # Midpoint: 1.0 + 2^-11 = 1.00048828125 (0x3F801000 in f32). - # Tie-to-even: mantissa 0 is even -> rounds down to 0x3C00. - got_tie0 = run_cvt_f16_f32(f32_to_bits(1.0 + 2**-11)) - self.assertEqual(got_tie0 & 0xFFFF, 0x3C00) - - # Strictly above midpoint: rounds up to 0x3C01. - got_up = run_cvt_f16_f32(f32_to_bits(1.0 + 2**-11 + 2**-20)) - self.assertEqual(got_up & 0xFFFF, 0x3C01) - - # Strictly below midpoint: rounds down to 0x3C00. - got_down = run_cvt_f16_f32(f32_to_bits(1.0 + 2**-11 - 2**-20)) - self.assertEqual(got_down & 0xFFFF, 0x3C00) - - # Midpoint between 0x3C01 and 0x3C02: 1.0 + 1.5 * 2^-10 (0x3F803000 in f32). - # Tie-to-even: mantissa 2 is even -> rounds up to 0x3C02. - got_tie1 = run_cvt_f16_f32(f32_to_bits(1.0 + 1.5 * 2**-10)) - self.assertEqual(got_tie1 & 0xFFFF, 0x3C02) - - # 2. Denormal range midpoints: - # Midpoint between 0 and 2^-24: 2^-25. - # Tie-to-even: 0 is even -> rounds down to 0x0000. - got_denorm_tie0 = run_cvt_f16_f32(f32_to_bits(2**-25)) - self.assertEqual(got_denorm_tie0 & 0xFFFF, 0x0000) - - # Midpoint between 1 * 2^-24 and 2 * 2^-24: 1.5 * 2^-24. - # Tie-to-even: 2 is even -> rounds up to 0x0002. - got_denorm_tie1 = run_cvt_f16_f32(f32_to_bits(1.5 * 2**-24)) - self.assertEqual(got_denorm_tie1 & 0xFFFF, 0x0002) - - # Midpoint between 2 * 2^-24 and 3 * 2^-24: 2.5 * 2^-24. - # Tie-to-even: 2 is even -> rounds down to 0x0002. - got_denorm_tie2 = run_cvt_f16_f32(f32_to_bits(2.5 * 2**-24)) - self.assertEqual(got_denorm_tie2 & 0xFFFF, 0x0002) - - # Midpoint between 3 * 2^-24 and 4 * 2^-24: 3.5 * 2^-24. - # Tie-to-even: 4 is even -> rounds up to 0x0004. - got_denorm_tie3 = run_cvt_f16_f32(f32_to_bits(3.5 * 2**-24)) - self.assertEqual(got_denorm_tie3 & 0xFFFF, 0x0004) - - def test_overflow_boundary(self): - # 65504.0 is max finite f16 (0x7BFF). - got_max = run_cvt_f16_f32(f32_to_bits(65504.0)) - self.assertEqual(got_max & 0xFFFF, 0x7BFF) - - # Values < 65520 round to 65504.0. - got_near = run_cvt_f16_f32(f32_to_bits(65519.0)) - self.assertEqual(got_near & 0xFFFF, 0x7BFF) - - # 65520.0 is the tie-to-even overflow boundary to +inf (0x7C00). - got_over = run_cvt_f16_f32(f32_to_bits(65520.0)) - self.assertEqual(got_over & 0xFFFF, 0x7C00) - - # -65520.0 overflows to -inf (0xFC00). - got_nover = run_cvt_f16_f32(f32_to_bits(-65520.0)) - self.assertEqual(got_nover & 0xFFFF, 0xFC00) - - # Massive floats overflow to inf. - for big in (65536.0, 100000.0, 1e20): - self.assertEqual(run_cvt_f16_f32(f32_to_bits(big)) & 0xFFFF, 0x7C00) - self.assertEqual(run_cvt_f16_f32(f32_to_bits(-big)) & 0xFFFF, 0xFC00) - - def test_modifiers(self): - # Negation: -v1 negates input before conversion - lines_neg = [ - f"v_mov_b32 v1, {f32_to_bits(1.5):#x}", - f"v_mov_b32 v0, {OLD_HIGH:#x}", - "v_cvt_f16_f32_e64 v0, -v1", - ] - self.assertEqual(run_lines(lines_neg)[0], OLD_HIGH | 0xBE00) # -1.5 in f16 - - # Double negation - lines_neg_neg = [ - f"v_mov_b32 v1, {f32_to_bits(-2.0):#x}", - f"v_mov_b32 v0, {OLD_HIGH:#x}", - "v_cvt_f16_f32_e64 v0, -v1", - ] - self.assertEqual(run_lines(lines_neg_neg)[0], OLD_HIGH | 0x4000) # 2.0 in f16 - - # Absolute value: |v1| - lines_abs = [ - f"v_mov_b32 v1, {f32_to_bits(-1.5):#x}", - f"v_mov_b32 v0, {OLD_HIGH:#x}", - "v_cvt_f16_f32_e64 v0, |v1|", - ] - self.assertEqual(run_lines(lines_abs)[0], OLD_HIGH | 0x3E00) # 1.5 in f16 - - # Negated absolute value: -|v1| - lines_neg_abs = [ - f"v_mov_b32 v1, {f32_to_bits(1.5):#x}", - f"v_mov_b32 v0, {OLD_HIGH:#x}", - "v_cvt_f16_f32_e64 v0, -|v1|", - ] - self.assertEqual(run_lines(lines_neg_abs)[0], OLD_HIGH | 0xBE00) # -1.5 in f16 - - def test_operands_inline_and_sgpr(self): - # Inline float literal 1.0 - lines_fimm = [ - f"v_mov_b32 v0, {OLD_HIGH:#x}", - "v_cvt_f16_f32_e32 v0, 1.0", - ] - self.assertEqual(run_lines(lines_fimm)[0], OLD_HIGH | 0x3C00) - - # Inline integer 0 - lines_imm0 = [ - f"v_mov_b32 v0, {OLD_HIGH:#x}", - "v_cvt_f16_f32_e32 v0, 0", - ] - self.assertEqual(run_lines(lines_imm0)[0], OLD_HIGH | 0x0000) - - # Inline float literal 0.5 - lines_fimm_half = [ - f"v_mov_b32 v0, {OLD_HIGH:#x}", - "v_cvt_f16_f32_e32 v0, 0.5", - ] - self.assertEqual(run_lines(lines_fimm_half)[0], OLD_HIGH | 0x3800) - - # Inline float literal -1.0 - lines_fimm_neg = [ - f"v_mov_b32 v0, {OLD_HIGH:#x}", - "v_cvt_f16_f32_e32 v0, -1.0", - ] - self.assertEqual(run_lines(lines_fimm_neg)[0], OLD_HIGH | 0xBC00) - - # SGPR operand - lines_sgpr = [ - f"s_mov_b32 s2, {f32_to_bits(2.5):#x}", - f"v_mov_b32 v0, {OLD_HIGH:#x}", - "v_cvt_f16_f32_e32 v0, s2", - ] - self.assertEqual(run_lines(lines_sgpr)[0], OLD_HIGH | 0x4100) - - -class CvtF32F16Tests(unittest.TestCase): - def test_normal_values(self): - cases = [ - (0x3C00, 0x3F800000), # 1.0 - (0xBC00, 0xBF800000), # -1.0 - (0x3800, 0x3F000000), # 0.5 - (0xB800, 0xBF000000), # -0.5 - (0x4000, 0x40000000), # 2.0 - (0xC000, 0xC0000000), # -2.0 - (0x3E00, 0x3FC00000), # 1.5 - (0xBE00, 0xBFC00000), # -1.5 - (0x4100, 0x40200000), # 2.5 - (0x3000, 0x3E000000), # 0.125 - (0x5140, 0x42280000), # 42.0 - (0x7BFF, 0x477FE000), # 65504.0 - (0xFBFF, 0xC77FE000), # -65504.0 - ] - for f16_bits, exp_f32 in cases: - with self.subTest(f16=hex(f16_bits), expected=hex(exp_f32)): - got = run_cvt_f32_f16(f16_bits) - self.assertEqual(got, exp_f32) - - def test_ignores_src_high_half(self): - noise_high = [0x12340000, 0xDEAD0000, 0xFFFF0000, 0x80000000, 0x55AA0000] - for noise in noise_high: - with self.subTest(noise=hex(noise)): - got = run_cvt_f32_f16(noise | 0x3C00) - self.assertEqual(got, 0x3F800000) - - got_neg = run_cvt_f32_f16(noise | 0xBC00) - self.assertEqual(got_neg, 0xBF800000) - - def test_signed_zeros(self): - # +0.0 - self.assertEqual(run_cvt_f32_f16(0x0000), 0x00000000) - self.assertEqual(run_cvt_f32_f16(0x99990000), 0x00000000) - - # -0.0 - self.assertEqual(run_cvt_f32_f16(0x8000), 0x80000000) - self.assertEqual(run_cvt_f32_f16(0x99998000), 0x80000000) - - def test_infinities(self): - # +inf - self.assertEqual(run_cvt_f32_f16(0x7C00), 0x7F800000) - self.assertEqual(run_cvt_f32_f16(0x12347C00), 0x7F800000) - - # -inf - self.assertEqual(run_cvt_f32_f16(0xFC00), 0xFF800000) - self.assertEqual(run_cvt_f32_f16(0x1234FC00), 0xFF800000) - - def test_nans(self): - # Quiet NaNs - self.assertEqual(run_cvt_f32_f16(0x7E00), 0x7FC00000) - self.assertEqual(run_cvt_f32_f16(0xFE00), 0xFFC00000) - - # Non-quiet NaN payloads expand into f32 NaNs - for nan_h in (0x7C01, 0x7E01, 0xFC01, 0xFE01): - with self.subTest(nan_h=hex(nan_h)): - got = run_cvt_f32_f16(nan_h) - self.assertTrue(math.isnan(bits_to_f32(got))) - self.assertEqual(got & 0x7F800000, 0x7F800000) - self.assertNotEqual(got & 0x007FFFFF, 0) - - def test_denormals_exact_conversion(self): - cases = [ - (0x0001, 0x33800000), # 2^-24 - (0x8001, 0xB3800000), # -2^-24 - (0x0002, 0x34000000), # 2^-23 - (0x8002, 0xB4000000), # -2^-23 - (0x0200, 0x38000000), # 2^-15 - (0x8200, 0xB8000000), # -2^-15 - (0x03FF, 0x387FC000), # 1023 * 2^-24 - (0x83FF, 0xB87FC000), # -1023 * 2^-24 - ] - for f16_bits, exp_f32 in cases: - with self.subTest(f16=hex(f16_bits), expected=hex(exp_f32)): - got = run_cvt_f32_f16(f16_bits) - self.assertEqual(got, exp_f32) - # Verify exact value recovery - expected_val = bits_to_f16(f16_bits) - actual_val = bits_to_f32(got) - self.assertEqual(actual_val, expected_val) - - def test_modifiers(self): - # Negation: -v1 - lines_neg = [ - "v_mov_b32 v1, 0x3C00", # 1.0 - "v_cvt_f32_f16_e64 v0, -v1", - ] - self.assertEqual(run_lines(lines_neg)[0], 0xBF800000) # -1.0 - - # Absolute value: |v1| - lines_abs = [ - "v_mov_b32 v1, 0xBC00", # -1.0 - "v_cvt_f32_f16_e64 v0, |v1|", - ] - self.assertEqual(run_lines(lines_abs)[0], 0x3F800000) # 1.0 - - # Negated absolute value: -|v1| - lines_neg_abs = [ - "v_mov_b32 v1, 0x3C00", # 1.0 - "v_cvt_f32_f16_e64 v0, -|v1|", - ] - self.assertEqual(run_lines(lines_neg_abs)[0], 0xBF800000) # -1.0 - - def test_operands_inline_and_sgpr(self): - # Inline hex constant 0x3C00 (1.0) - lines_imm = [ - "v_cvt_f32_f16_e32 v0, 0x3C00", - ] - self.assertEqual(run_lines(lines_imm)[0], 0x3F800000) - - # Inline zero 0 - lines_imm0 = [ - "v_cvt_f32_f16_e32 v0, 0", - ] - self.assertEqual(run_lines(lines_imm0)[0], 0x00000000) - - # SGPR operand - lines_sgpr = [ - "s_mov_b32 s2, 0x4000", # 2.0 - "v_cvt_f32_f16_e32 v0, s2", - ] - self.assertEqual(run_lines(lines_sgpr)[0], 0x40000000) - - -class RoundtripTests(unittest.TestCase): - def test_lossless_f16_roundtrip(self): - # All finite f16 numbers must roundtrip losslessly through f32: - # v_cvt_f16_f32(v_cvt_f32_f16(h)) == h - samples = [ - 0x0000, 0x8000, # +/-0.0 - 0x0001, 0x8001, # min subnormals - 0x0002, 0x8002, # subnormals - 0x0100, 0x8100, - 0x03FF, 0x83FF, # max subnormals - 0x0400, 0x8400, # min normal floats - 0x3C00, 0xBC00, # +/-1.0 - 0x3800, 0xB800, # +/-0.5 - 0x4000, 0xC000, # +/-2.0 - 0x3E00, 0xBE00, # +/-1.5 - 0x7BFF, 0xFBFF, # max finite floats - 0x7C00, 0xFC00, # +/-inf - ] - for h in samples: - with self.subTest(h=hex(h)): - lines = [ - f"v_mov_b32 v1, {h:#x}", - "v_cvt_f32_f16_e32 v2, v1", - f"v_mov_b32 v0, {OLD_HIGH:#x}", - "v_cvt_f16_f32_e32 v0, v2", - ] - got = run_lines(lines)[0] - self.assertEqual(got & 0xFFFF, h) - self.assertEqual(got & 0xFFFF0000, OLD_HIGH) - - -class HalfNanRuleTests(unittest.TestCase): - """si.half_to_float / si.float_to_half pin one NaN rule on every Python version. - - struct's ' inf - - def test_float_to_half_rounds_ties_to_even(self): - # float_to_half rounds by hand, so its tie rule needs direct cases. The v_cvt_f16_f32 tie tests above do - # not reach it: the translator lowers that opcode with its own integer RNE. The helper backs PackHalf2x16 - # and OpQuantizeToF16. Round-half-up in either path (normal or subnormal) fails at least one row here. - cases = [ - # Normal path: the dropped 13 bits are exactly 0x1000. - (0x3F801000, 0x3C00), # 1 + 2^-11, between 0x3C00 and 0x3C01 -> even 0x3C00 - (0xBF801000, 0xBC00), # negative of the above - (0x3F803000, 0x3C02), # 1 + 3 * 2^-11, between 0x3C01 and 0x3C02 -> even 0x3C02 - (0x3F800FFF, 0x3C00), # just below the first tie - (0x3F801001, 0x3C01), # just above the first tie - (0x3FFFF000, 0x4000), # tie above 0x3FFF -> even, mantissa carry into the exponent (2.0) - (0x477FD000, 0x7BFE), # 65488, between 65472 and 65504 -> even 0x7BFE - (0x477FEFFF, 0x7BFF), # largest f32 below 65520 stays at max finite 65504 - (0xC77FF000, 0xFC00), # -65520 tie -> -inf - # Subnormal path: n = value / 2^-24 has a fraction of exactly one half. - (0x33000000, 0x0000), # 0.5 -> even 0 - (0xB3000000, 0x8000), # -0.5 -> -0 - (0x33C00000, 0x0002), # 1.5 -> even 2 - (0x34200000, 0x0002), # 2.5 -> even 2 - (0x387FE000, 0x0400), # 1023.5 -> even 1024, the smallest normal - ] - for bits, want in cases: - with self.subTest(bits=hex(bits)): - self.assertEqual(si.float_to_half(bits_to_f32(bits)), want) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_alu_cvt_flr_rpi.py b/tests/semantic/test_alu_cvt_flr_rpi.py deleted file mode 100644 index eb9239af8..000000000 --- a/tests/semantic/test_alu_cvt_flr_rpi.py +++ /dev/null @@ -1,141 +0,0 @@ -"""Semantic interpreter tests for RDNA2 v_cvt_flr_i32_f32 and v_cvt_rpi_i32_f32. - -Measured natively on RDNA2 (gfx1035 & gfx1036, wave32 & wave64): v_cvt_flr_i32_f32 is sat_i32(floor(S0)), and -v_cvt_rpi_i32_f32 is sat_i32(floor(S0 + 0.5)) computed **exactly** (without binary32 rounding of S0 + 0.5, so -0x3EFFFFFF = 0.49999997 gives 0, 0x4B000001 gives 0x00800001, and 0x4B7FFFFF gives 0x00FFFFFF). Values at or past -+-2^31, +-inf, and NaNs all saturate by the sign bit of the operand (+ -> 0x7FFFFFFF, - -> 0x80000000), unlike -v_cvt_i32_f32 which returns 0 for NaN. Each case translates a synthetic pixel shader with tools/rdna2spirv.py, runs -it in tests/semantic/spirv_mini_interp.py and compares the result with an exact plain-Python reference. Denormal -inputs are left out (the float mode that would flush them is not modelled). The result leaves through exp as two -16-bit halves ORed into 0x40000000, so no export channel is a NaN or denormal pattern that a float round trip could -change. -""" -from fractions import Fraction -import math -import os -import random -import struct -import sys -import tempfile -import unittest -import warnings - -HERE = os.path.dirname(os.path.abspath(__file__)) -ROOT = os.path.dirname(os.path.dirname(HERE)) -TOOLS_DIR = os.environ.get("LEONIDA_TOOLS_DIR") or os.path.join(ROOT, "tools") - -sys.dont_write_bytecode = True -sys.path.insert(0, TOOLS_DIR) -sys.path.insert(0, HERE) - -import rdna2spirv # noqa: E402 -import spirv_mini_interp as si # noqa: E402 - -M32 = 0xFFFFFFFF -STUB_DXBC = b"DXBC" + bytes(24) + struct.pack(" int: - u &= M32 - sign = (u >> 31) & 1 - exp = (u >> 23) & 0xFF - mant = u & 0x7FFFFF - if exp == 0xFF: - return 0x80000000 if sign else 0x7FFFFFFF - if exp == 0: - x = Fraction(mant, 1 << 149) - else: - x = Fraction((1 << 23) | mant) * (Fraction(2) ** (exp - 150)) - if sign: - x = -x - if op == "v_cvt_rpi_i32_f32": - x += Fraction(1, 2) - iv = math.floor(x) - if iv >= (1 << 31): - return 0x7FFFFFFF - if iv < -(1 << 31): - return 0x80000000 - return iv & M32 - - -OPS = ("v_cvt_flr_i32_f32", "v_cvt_rpi_i32_f32") -VALUES = [0x00000000, 0x80000000, 0x3F000000, 0xBF000000, 0x3EFFFFFF, 0xBEFFFFFF, 0xBF000001, 0x3FC00000, 0xBFC00000, - 0x40200000, 0xC0200000, 0x3F7FFFFF, 0x4AFFFFFF, 0x4B000000, 0x4B000001, 0x4B7FFFFF, 0xCB000001, 0x4EFFFFFF, - 0xCEFFFFFF, 0x4F000000, 0xCF000000, 0xCF000001, 0x7F7FFFFF, 0xFF7FFFFF, 0x7F800000, 0xFF800000, 0x7FC00000, - 0xFFC00000, 0x7F800001, 0xFF800001] - -_TMP_DIR = None -_SRC_PATH = None - - -def setUpModule(): - global _TMP_DIR, _SRC_PATH - _TMP_DIR = tempfile.TemporaryDirectory() - disasm_dir = os.path.join(_TMP_DIR.name, "disasm") - os.mkdir(disasm_dir) - _SRC_PATH = os.path.join(disasm_dir, "ps_cvt_flr_rpi.s") - with open(os.path.join(_TMP_DIR.name, "ps_cvt_flr_rpi.dxbc"), "wb") as f: - f.write(STUB_DXBC) - - -def tearDownModule(): - global _TMP_DIR - if _TMP_DIR is not None: - _TMP_DIR.cleanup() - _TMP_DIR = None - - -def run_lines(lines) -> int: - """Run the lines, return v0 (exported as two 16-bit halves, see the module docstring).""" - if _TMP_DIR is None: - setUpModule() - lines = list(lines) + ["v_and_b32 v5, 0xffff, v0", "v_lshrrev_b32 v6, 16, v0", - "v_or_b32 v5, 0x40000000, v5", "v_or_b32 v6, 0x40000000, v6"] - asm = "; test_cvt_flr_rpi\n" + "".join(f"\t{ln}\n" for ln in lines) + "\texp mrt0 v5, v6, v5, v5 done vm\n\ts_endpgm\n" - with open(_SRC_PATH, "w", encoding="utf-8") as f: - f.write(asm) - with warnings.catch_warnings(): - warnings.simplefilter("ignore", ResourceWarning) - spv = rdna2spirv.translate(_SRC_PATH) - lo, hi = si.run_fragment(spv)["%out_mrt0"][:2] - assert lo >> 16 == 0x4000 and hi >> 16 == 0x4000, (hex(lo), hex(hi)) - return (lo & 0xFFFF) | (hi & 0xFFFF) << 16 - - -def run_op(op: str, u: int) -> int: - return run_lines([f"v_mov_b32 v1, {u:#x}", f"{op} v0, v1"]) - - -class CvtFlrRpiTests(unittest.TestCase): - def test_reference(self): - self.assertEqual(ref("v_cvt_flr_i32_f32", 0xC0200000), (-3) & M32) # floor(-2.5) - self.assertEqual(ref("v_cvt_rpi_i32_f32", 0xC0200000), (-2) & M32) # floor(-2.5 + 0.5) - self.assertEqual(ref("v_cvt_rpi_i32_f32", 0x40200000), 3) # 2.5 rounds up - self.assertEqual(ref("v_cvt_rpi_i32_f32", 0x3EFFFFFF), 0) # 0.49999997 -> exact floor(x+0.5) = 0 - self.assertEqual(ref("v_cvt_rpi_i32_f32", 0x4B000001), 0x00800001) # 8388609.0 -> exact, not 8388610 - self.assertEqual(ref("v_cvt_rpi_i32_f32", 0x4B7FFFFF), 0x00FFFFFF) # 16777215.0 -> exact, not 16777216 - self.assertEqual(ref("v_cvt_flr_i32_f32", 0xCF000001), 0x80000000) # below -2^31: saturated - self.assertEqual(ref("v_cvt_flr_i32_f32", 0x7FC00000), 0x7FFFFFFF) # +NaN saturates to INT_MAX - self.assertEqual(ref("v_cvt_flr_i32_f32", 0xFFC00000), 0x80000000) # -NaN saturates to INT_MIN - - def test_edge_values(self): - for op in OPS: - for u in VALUES: - with self.subTest(op=op, x=hex(u)): - self.assertEqual(run_op(op, u), ref(op, u)) - - def test_seeded(self): - rng = random.Random(0xF1A) - for _ in range(40): - op = rng.choice(OPS) - u = rng.getrandbits(1) << 31 | rng.randrange(120, 160) << 23 | rng.getrandbits(23) # |x| ~ 2^-7 .. 2^32 - with self.subTest(op=op, x=hex(u)): - self.assertEqual(run_op(op, u), ref(op, u)) - - def test_source_modifiers(self): - self.assertEqual(run_lines(["v_mov_b32 v1, 0x40200000", "v_cvt_flr_i32_f32_e64 v0, -v1"]), (-3) & M32) - self.assertEqual(run_lines(["v_mov_b32 v1, 0xc0200000", "v_cvt_rpi_i32_f32_e64 v0, |v1|"]), 3) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_alu_cvt_norm_f16.py b/tests/semantic/test_alu_cvt_norm_f16.py deleted file mode 100644 index fd2b94012..000000000 --- a/tests/semantic/test_alu_cvt_norm_f16.py +++ /dev/null @@ -1,239 +0,0 @@ -"""Semantic interpreter and spirv-val tests for RDNA2 v_cvt_norm_i16_f16 and v_cvt_norm_u16_f16. - -v_cvt_norm_i16_f16 converts a binary16 input to snorm16: round_even(clamp(S0, -1, 1) * 32767), NaN -> 0. -v_cvt_norm_u16_f16 converts a binary16 input to unorm16: round_even(clamp(S0, 0, 1) * 65535), NaN -> 0. -Both preserve the unwritten 16-bit half of the destination and support VOP3 neg/abs and op_sel:[src,dst]. -""" -from fractions import Fraction -import os -import random -import shutil -import struct -import subprocess -import sys -import tempfile -import unittest -import warnings - -HERE = os.path.dirname(os.path.abspath(__file__)) -ROOT = os.path.dirname(os.path.dirname(HERE)) -TOOLS_DIR = os.environ.get("LEONIDA_TOOLS_DIR") or os.path.join(ROOT, "tools") - -sys.dont_write_bytecode = True -sys.path.insert(0, TOOLS_DIR) -sys.path.insert(0, HERE) - -import rdna2spirv # noqa: E402 -import spirv_mini_interp as si # noqa: E402 - -STUB_DXBC = b"DXBC" + bytes(24) + struct.pack(" float: - return struct.unpack(" int: - return struct.unpack(" int: - x = f16_to_float(h) - if x != x: - return 0 - lo = -1.0 if snorm else 0.0 - c = min(max(x, lo), 1.0) - scale = 32767 if snorm else 65535 - return round(Fraction(c) * scale) & 0xFFFF - - -_TMP_DIR = None -_SRC_PATH = None - - -def setUpModule(): - global _TMP_DIR, _SRC_PATH - _TMP_DIR = tempfile.TemporaryDirectory() - disasm_dir = os.path.join(_TMP_DIR.name, "disasm") - os.mkdir(disasm_dir) - _SRC_PATH = os.path.join(disasm_dir, "ps_cvt_norm_f16.s") - with open(os.path.join(_TMP_DIR.name, "ps_cvt_norm_f16.dxbc"), "wb") as f: - f.write(STUB_DXBC) - - -def tearDownModule(): - global _TMP_DIR - if _TMP_DIR is not None: - _TMP_DIR.cleanup() - _TMP_DIR = None - - -def translate_lines(lines): - if _TMP_DIR is None: - setUpModule() - # Export v0 split into two safe 16-bit halves ORed into 0x40000000 so float export never alters NaN/denorm bits. - full = list(lines) + [ - "v_and_b32 v5, 0xffff, v0", - "v_lshrrev_b32 v6, 16, v0", - "v_or_b32 v5, 0x40000000, v5", - "v_or_b32 v6, 0x40000000, v6", - ] - asm = "; test_cvt_norm_f16\n" + "".join(f"\t{ln}\n" for ln in full) + "\texp mrt0 v5, v6, v5, v5 done vm\n\ts_endpgm\n" - with open(_SRC_PATH, "w", encoding="utf-8") as f: - f.write(asm) - with warnings.catch_warnings(): - warnings.simplefilter("ignore", ResourceWarning) - return rdna2spirv.translate(_SRC_PATH) - - -def run_lines(lines) -> int: - spv = translate_lines(lines) - lo, hi = si.run_fragment(spv)["%out_mrt0"][:2] - assert lo >> 16 == 0x4000 and hi >> 16 == 0x4000, (hex(lo), hex(hi)) - return (lo & 0xFFFF) | ((hi & 0xFFFF) << 16) - - -def validate_spirv(spv_text: str): - spirv_as = shutil.which("spirv-as") - spirv_val = shutil.which("spirv-val") - if not spirv_as or not spirv_val: - return - with tempfile.TemporaryDirectory() as d: - asm_p = os.path.join(d, "s.spvasm") - bin_p = os.path.join(d, "s.spv") - with open(asm_p, "w", encoding="utf-8") as f: - f.write(spv_text) - r1 = subprocess.run([spirv_as, "--target-env", "vulkan1.2", asm_p, "-o", bin_p], capture_output=True, text=True) - if r1.returncode != 0: - raise AssertionError(f"spirv-as failed: {r1.stderr}") - r2 = subprocess.run([spirv_val, "--target-env", "vulkan1.2", bin_p], capture_output=True, text=True) - if r2.returncode != 0: - raise AssertionError(f"spirv-val failed: {r2.stderr}") - - -class CvtNormF16Tests(unittest.TestCase): - def test_edges_and_single_rounding_ties(self): - # Includes the 4 f16 encodings near +-0.5 (0x3801, 0x37ff, 0xb801, 0xb7ff) where f32(x * scale) double-rounds. - edges = ( - 0x0000, 0x8000, # +0, -0 - 0x0001, 0x8001, 0x03FF, 0x83FF, # subnormals - 0x0400, 0x8400, # min normals - 0x3400, 0xB400, # +-0.25 - 0x37FE, 0x37FF, 0x3800, 0x3801, 0x3802, # around +0.5 - 0xB7FE, 0xB7FF, 0xB800, 0xB801, 0xB802, # around -0.5 - 0x3BFF, 0x3C00, 0x3C01, # around +1.0 - 0xBBFF, 0xBC00, 0xBC01, # around -1.0 - 0x4000, 0xC000, # +-2.0 (clamped) - 0x7C00, 0xFC00, # +-inf - 0x7E00, 0xFE00, 0x7C01, 0xFC01, # qNaN / sNaN - ) - for op, snorm in (("v_cvt_norm_i16_f16", True), ("v_cvt_norm_u16_f16", False)): - for h in edges: - with self.subTest(op=op, h=hex(h)): - got = run_lines([ - f"v_mov_b32 v1, {(0xDEAD0000 | h):#x}", - f"v_mov_b32 v0, {SEED_DST:#x}", - f"{op}_e32 v0, v1", - ]) - self.assertEqual(got, (SEED_DST & 0xFFFF0000) | ref_norm16(h, snorm)) - - def test_seeded_sweep_matches_exact_fraction(self): - rng = random.Random(0xF16) - samples = [rng.randrange(65536) for _ in range(60)] - for op, snorm in (("v_cvt_norm_i16_f16", True), ("v_cvt_norm_u16_f16", False)): - for h in samples: - with self.subTest(op=op, h=hex(h)): - got = run_lines([ - f"v_mov_b32 v1, {(0xBEEF0000 | h):#x}", - f"v_mov_b32 v0, {SEED_DST:#x}", - f"{op}_e32 v0, v1", - ]) - self.assertEqual(got, (SEED_DST & 0xFFFF0000) | ref_norm16(h, snorm)) - - def test_opsel_and_source_modifiers(self): - lo_h = float_to_f16(-0.5) - hi_h = float_to_f16(0.75) - packed = (hi_h << 16) | lo_h - - # op_sel:[1,0]: read high half (0.75), write low half, preserve high half of v0 - got = run_lines([ - f"v_mov_b32 v1, {packed:#x}", - f"v_mov_b32 v0, {SEED_DST:#x}", - "v_cvt_norm_i16_f16_e64 v0, v1 op_sel:[1,0]", - ]) - self.assertEqual(got, (SEED_DST & 0xFFFF0000) | ref_norm16(hi_h, True)) - - # op_sel:[0,1]: read low half (-0.5), apply abs -> +0.5, write high half, preserve low half of v0 - got2 = run_lines([ - f"v_mov_b32 v1, {packed:#x}", - f"v_mov_b32 v0, {SEED_DST:#x}", - "v_cvt_norm_u16_f16_e64 v0, |v1| op_sel:[0,1]", - ]) - self.assertEqual(got2, (ref_norm16(float_to_f16(0.5), False) << 16) | (SEED_DST & 0xFFFF)) - - # op_sel:[1,1] with neg: read high half (0.75), negate -> -0.75, write high half - got3 = run_lines([ - f"v_mov_b32 v1, {packed:#x}", - f"v_mov_b32 v0, {SEED_DST:#x}", - "v_cvt_norm_i16_f16_e64 v0, -v1 op_sel:[1,1]", - ]) - self.assertEqual(got3, (ref_norm16(float_to_f16(-0.75), True) << 16) | (SEED_DST & 0xFFFF)) - - def test_sdwa_word1_high_half_preserve(self): - # GFX10/LLVM rejects op_sel on v_cvt_norm_*_f16; high-half access uses SDWA WORD_1. - hi_h = float_to_f16(0.75) - packed = (hi_h << 16) | float_to_f16(-0.25) - for op, snorm in (("v_cvt_norm_i16_f16", True), ("v_cvt_norm_u16_f16", False)): - with self.subTest(op=op): - got = run_lines([ - f"v_mov_b32 v1, {packed:#x}", - f"v_mov_b32 v0, {SEED_DST:#x}", - f"{op}_sdwa v0, v1 dst_sel:WORD_1 dst_unused:UNUSED_PRESERVE src0_sel:WORD_1", - ]) - self.assertEqual(got, (ref_norm16(hi_h, snorm) << 16) | (SEED_DST & 0xFFFF)) - - def test_sgpr_inline_and_spirv_val(self): - spv = translate_lines([ - f"s_mov_b32 s4, {float_to_f16(0.5):#x}", - f"v_mov_b32 v0, {SEED_DST:#x}", - "v_cvt_norm_i16_f16_e32 v0, s4", - "v_cvt_norm_u16_f16_e64 v0, 0.5 op_sel:[0,1]", - ]) - validate_spirv(spv) - lo, hi = si.run_fragment(spv)["%out_mrt0"][:2] - got = (lo & 0xFFFF) | ((hi & 0xFFFF) << 16) - want = (ref_norm16(float_to_f16(0.5), False) << 16) | ref_norm16(float_to_f16(0.5), True) - self.assertEqual(got, want) - - def test_output_modifiers_match_plain_and_reject_invalid_forms(self): - h = float_to_f16(0.5) - for op, snorm in (("v_cvt_norm_i16_f16", True), ("v_cvt_norm_u16_f16", False)): - want = (SEED_DST & 0xFFFF0000) | ref_norm16(h, snorm) - for mod in ("clamp", "mul:2", "mul:4", "div:2"): - with self.subTest(op=op, mod=mod): - got = run_lines([ - f"v_mov_b32 v1, {h:#x}", - f"v_mov_b32 v0, {SEED_DST:#x}", - f"{op}_e64 v0, v1 {mod}", - ]) - self.assertEqual(got, want) - with self.subTest(op=op, form="sdwa_clamp"): - got_sdwa = run_lines([ - f"v_mov_b32 v1, {(h << 16):#x}", - f"v_mov_b32 v0, {SEED_DST:#x}", - f"{op}_sdwa v0, v1 clamp dst_sel:WORD_1 dst_unused:UNUSED_PRESERVE src0_sel:WORD_1", - ]) - self.assertEqual(got_sdwa, (ref_norm16(h, snorm) << 16) | (SEED_DST & 0xFFFF)) - for bad_line in ( - "v_cvt_norm_i16_f16_e64 v0, v1 mul:8", - "v_cvt_norm_u16_f16_sdwa v0, v1 mul:2 dst_sel:WORD_1 dst_unused:UNUSED_PRESERVE src0_sel:WORD_1", - "v_cvt_norm_i16_f16_e32 v0, v1 clamp", - ): - with self.subTest(line=bad_line): - with self.assertRaises(rdna2spirv.Unsupported): - translate_lines([bad_line]) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_alu_cvt_off.py b/tests/semantic/test_alu_cvt_off.py deleted file mode 100644 index ccdce6bd2..000000000 --- a/tests/semantic/test_alu_cvt_off.py +++ /dev/null @@ -1,90 +0,0 @@ -"""Semantic interpreter tests for RDNA2 v_cvt_off_f32_i4. - -RDNA ISA: D.f32 = CVT_OFF_TABLE[S0[3:0]]: the low 4 bits of S0 as a signed integer, divided by 16, so 0..7 give -0.0 .. 0.4375 and 8..15 give -0.5 .. -0.0625 (a sample-offset conversion). Bits 4-31 are ignored. Output modifiers -(mul:2 / mul:4 / div:2, then clamp) apply to the result. Each case translates a synthetic pixel shader with -tools/rdna2spirv.py, runs it in tests/semantic/spirv_mini_interp.py and compares the exported word with a -plain-Python reference (every result is an exact, normal binary32 value or zero). -""" -import os -import struct -import sys -import tempfile -import unittest -import warnings - -HERE = os.path.dirname(os.path.abspath(__file__)) -ROOT = os.path.dirname(os.path.dirname(HERE)) -TOOLS_DIR = os.environ.get("LEONIDA_TOOLS_DIR") or os.path.join(ROOT, "tools") - -sys.dont_write_bytecode = True -sys.path.insert(0, TOOLS_DIR) -sys.path.insert(0, HERE) - -import rdna2spirv # noqa: E402 -import spirv_mini_interp as si # noqa: E402 - -STUB_DXBC = b"DXBC" + bytes(24) + struct.pack(" value. -TABLE = [0.0, 0.0625, 0.125, 0.1875, 0.25, 0.3125, 0.375, 0.4375, - -0.5, -0.4375, -0.375, -0.3125, -0.25, -0.1875, -0.125, -0.0625] - - -def f2u(x: float) -> int: - return struct.unpack(" int: - if _TMP_DIR is None: - setUpModule() - lines = [f"v_mov_b32 v1, {x:#x}", line] - asm = "; test_cvt_off\n" + "".join(f"\t{ln}\n" for ln in lines) + "\texp mrt0 v0, v0, v0, v0 done vm\n\ts_endpgm\n" - with open(_SRC_PATH, "w", encoding="utf-8") as f: - f.write(asm) - with warnings.catch_warnings(): - warnings.simplefilter("ignore", ResourceWarning) - spv = rdna2spirv.translate(_SRC_PATH) - return si.run_fragment(spv)["%out_mrt0"][0] - - -class CvtOffTests(unittest.TestCase): - def test_table(self): - for i, want in enumerate(TABLE): - with self.subTest(i=i): - self.assertEqual(run_op(i), f2u(want)) - - def test_upper_bits_are_ignored(self): - for x in (0xFFFFFFF0, 0x12345678, 0x80000009, 0xABCDEF0F): - with self.subTest(x=hex(x)): - self.assertEqual(run_op(x), f2u(TABLE[x & 15])) - - def test_output_modifiers(self): - self.assertEqual(run_op(7, "v_cvt_off_f32_i4_e64 v0, v1 mul:4"), f2u(1.75)) - self.assertEqual(run_op(7, "v_cvt_off_f32_i4_e64 v0, v1 mul:4 clamp"), f2u(1.0)) - self.assertEqual(run_op(8, "v_cvt_off_f32_i4_e64 v0, v1 clamp"), f2u(0.0)) - self.assertEqual(run_op(8, "v_cvt_off_f32_i4_e64 v0, v1 div:2"), f2u(-0.25)) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_alu_cvt_pk_16.py b/tests/semantic/test_alu_cvt_pk_16.py deleted file mode 100644 index 5e09e10fb..000000000 --- a/tests/semantic/test_alu_cvt_pk_16.py +++ /dev/null @@ -1,125 +0,0 @@ -"""Semantic interpreter tests for RDNA2 v_cvt_pk_u16_u32 and v_cvt_pk_i16_i32. - -RDNA ISA pseudocode: D[15:0] = sat16(S0), D[31:16] = sat16(S1), where v_cvt_pk_u16_u32 saturates the unsigned 32-bit -value to [0, 0xFFFF] (u32_to_u16) and v_cvt_pk_i16_i32 the signed value to [-32768, 32767] (i32_to_i16). The whole -dword is written. Each case translates a synthetic pixel shader with tools/rdna2spirv.py, runs it in -tests/semantic/spirv_mini_interp.py and compares the result with a plain-Python reference. D leaves through exp as two -16-bit halves ORed into 0x40000000, so no export channel is a NaN or denormal pattern that a float round trip could -change. -""" -import os -import random -import struct -import sys -import tempfile -import unittest -import warnings - -HERE = os.path.dirname(os.path.abspath(__file__)) -ROOT = os.path.dirname(os.path.dirname(HERE)) -TOOLS_DIR = os.environ.get("LEONIDA_TOOLS_DIR") or os.path.join(ROOT, "tools") - -sys.dont_write_bytecode = True -sys.path.insert(0, TOOLS_DIR) -sys.path.insert(0, HERE) - -import rdna2spirv # noqa: E402 -import spirv_mini_interp as si # noqa: E402 - -M32 = 0xFFFFFFFF -STUB_DXBC = b"DXBC" + bytes(24) + struct.pack(" int: - x &= M32 - return x - (1 << 32) if x >> 31 else x - - -def sat_u16(x: int) -> int: - return min(x & M32, 0xFFFF) - - -def sat_i16(x: int) -> int: - return max(-32768, min(32767, s32(x))) & 0xFFFF - - -OPS = {"v_cvt_pk_u16_u32": sat_u16, "v_cvt_pk_i16_i32": sat_i16} -VALUES = [0, 1, 0x7FFF, 0x8000, 0xFFFF, 0x10000, 0x12345678, 0x7FFFFFFF, 0x80000000, 0xFFFFFFFF, 0xFFFF8000, - 0xFFFF7FFF, 0xFFFFFFFE] - -_TMP_DIR = None -_SRC_PATH = None - - -def setUpModule(): - global _TMP_DIR, _SRC_PATH - _TMP_DIR = tempfile.TemporaryDirectory() - disasm_dir = os.path.join(_TMP_DIR.name, "disasm") - os.mkdir(disasm_dir) - _SRC_PATH = os.path.join(disasm_dir, "ps_cvt_pk_16.s") - with open(os.path.join(_TMP_DIR.name, "ps_cvt_pk_16.dxbc"), "wb") as f: - f.write(STUB_DXBC) - - -def tearDownModule(): - global _TMP_DIR - if _TMP_DIR is not None: - _TMP_DIR.cleanup() - _TMP_DIR = None - - -def run_lines(lines) -> int: - if _TMP_DIR is None: - setUpModule() - lines = list(lines) + ["v_and_b32 v5, 0xffff, v0", "v_lshrrev_b32 v6, 16, v0", - "v_or_b32 v5, 0x40000000, v5", "v_or_b32 v6, 0x40000000, v6"] - asm = "; test_cvt_pk_16\n" + "".join(f"\t{ln}\n" for ln in lines) + "\texp mrt0 v5, v6, v5, v5 done vm\n\ts_endpgm\n" - with open(_SRC_PATH, "w", encoding="utf-8") as f: - f.write(asm) - with warnings.catch_warnings(): - warnings.simplefilter("ignore", ResourceWarning) - spv = rdna2spirv.translate(_SRC_PATH) - lo, hi = si.run_fragment(spv)["%out_mrt0"][:2] - assert lo >> 16 == 0x4000 and hi >> 16 == 0x4000, (hex(lo), hex(hi)) - return (lo & 0xFFFF) | (hi & 0xFFFF) << 16 - - -def run_op(op: str, x: int, y: int) -> int: - return run_lines([f"v_mov_b32 v1, {x:#x}", f"v_mov_b32 v2, {y:#x}", "v_mov_b32 v0, 0xdeadbeef", f"{op} v0, v1, v2"]) - - -class CvtPk16Tests(unittest.TestCase): - def test_reference(self): - self.assertEqual(sat_u16(0x10000), 0xFFFF) - self.assertEqual(sat_u16(0xFFFFFFFF), 0xFFFF) # unsigned: -1 is huge - self.assertEqual(sat_i16(0xFFFFFFFF), 0xFFFF) # signed: -1 stays -1 - self.assertEqual(sat_i16(0x8000), 0x7FFF) - self.assertEqual(sat_i16(0xFFFF7FFF), 0x8000) # below -32768 - - def test_values(self): - for op, sat in OPS.items(): - for x in VALUES: - for y in VALUES[::3]: - with self.subTest(op=op, x=hex(x), y=hex(y)): - self.assertEqual(run_op(op, x, y), sat(x) | sat(y) << 16) - - def test_seeded(self): - rng = random.Random(0xC16) - for _ in range(30): - op, x, y = rng.choice(list(OPS)), rng.getrandbits(32) >> rng.randrange(32), rng.getrandbits(32) - if rng.getrandbits(1): - x = (-x) & M32 - with self.subTest(op=op, x=hex(x), y=hex(y)): - self.assertEqual(run_op(op, x, y), OPS[op](x) | OPS[op](y) << 16) - - def test_scalar_and_inline_operands(self): - self.assertEqual(run_lines(["s_mov_b32 s2, 0x12345", "v_cvt_pk_i16_i32 v0, s2, -1"]), 0x7FFF | 0xFFFF << 16) - self.assertEqual(run_lines(["s_mov_b32 s2, 0x12345", "v_cvt_pk_u16_u32 v0, s2, 64"]), 0xFFFF | 64 << 16) - - def test_clamp_is_rejected_not_guessed(self): - with self.assertRaises(rdna2spirv.Unsupported): - run_lines(["v_mov_b32 v1, 1", "v_cvt_pk_u16_u32 v0, v1, v1 clamp"]) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_alu_cvt_pk_u8_f32.py b/tests/semantic/test_alu_cvt_pk_u8_f32.py deleted file mode 100644 index c0c01d1c4..000000000 --- a/tests/semantic/test_alu_cvt_pk_u8_f32.py +++ /dev/null @@ -1,232 +0,0 @@ -from __future__ import annotations - -"""Semantic ALU interpreter tests for RDNA2 v_cvt_pk_u8_f32. - -RDNA2 ISA definition for `v_cvt_pk_u8_f32 vD, src0, src1, src2` (VOP3): - - Converts binary32 `src0` to uint8 using round-to-nearest-even (IEEE-754 roundTiesToEven), - clamped to [0, 255] (negative values -> 0; values >= 255.0 -> 255; NaN -> 0). - - Inserts that 8-bit unsigned integer into byte slot `src1 & 3` (bits [7:0], [15:8], - [23:16], or [31:24]) of `src2`, preserving the remaining 3 bytes of `src2` in `vD`. - - Used by shader compilers to pack a 4-component float32 vector (e.g. RGBA color or - XYZW attribute) into a single packed 32-bit VGPR through 4 sequential conversions: - v_cvt_pk_u8_f32 vD, v_x, 0, v_base - v_cvt_pk_u8_f32 vD, v_y, 1, vD - v_cvt_pk_u8_f32 vD, v_z, 2, vD - v_cvt_pk_u8_f32 vD, v_w, 3, vD -""" - -import math -import os -import random -import struct -import sys -import unittest -from fractions import Fraction - -HERE = os.path.dirname(os.path.abspath(__file__)) -ROOT = os.path.dirname(os.path.dirname(HERE)) -TOOLS_DIR = os.environ.get("LEONIDA_TOOLS_DIR") or os.path.join(ROOT, "tools") - -sys.dont_write_bytecode = True -if TOOLS_DIR not in sys.path: - sys.path.insert(0, TOOLS_DIR) -if HERE not in sys.path: - sys.path.insert(0, HERE) - -import rdna2spirv # noqa: E402 -import spirv_mini_interp as si # noqa: E402 -import support # noqa: E402 - -MASK32 = 0xFFFFFFFF -CANARY_BASE = 0xDEADBEEF - - -def f32_to_bits(x: float) -> int: - try: - return struct.unpack(" 0 else 0xFF800000 - - -def bits_to_f32(b: int) -> float: - return struct.unpack(" bool: - b &= MASK32 - return (b & 0x7F800000) == 0x7F800000 and (b & 0x007FFFFF) != 0 - - -def ref_cvt_u8_byte(src: float | int) -> int: - """RDNA2 flt32_to_uint8: round-to-nearest-even, clamped to [0, 255] (NaN -> 0).""" - if isinstance(src, int): - b = src & MASK32 - if is_nan_bits(b): - return 0 - if (b >> 31) != 0 or (b & 0x7FFFFFFF) == 0: - return 0 - if b == 0x7F800000: - return 255 - x = bits_to_f32(b) - else: - if math.isnan(src): - return 0 - if math.isinf(src): - return 255 if src > 0 else 0 - x = float(src) - - if x <= 0.0: - return 0 - if x >= 255.0: - return 255 - - q = Fraction(x) - n = q.numerator // q.denominator - rem = q - n - half = Fraction(1, 2) - if rem > half or (rem == half and (n & 1)): - n += 1 - return min(255, max(0, n)) - - -def ref_cvt_pk_u8_f32(src0: float | int, slot: int, base: int = 0) -> int: - """Insert converted byte at byte slot (slot & 3) of base dword.""" - byte_val = ref_cvt_u8_byte(src0) - sh = 8 * (slot & 3) - return ((base & MASK32) & ~(0xFF << sh)) | (byte_val << sh) - - -def ref_pack_4x_u8_f32( - c0: float | int, - c1: float | int, - c2: float | int, - c3: float | int, - base: int = 0, -) -> int: - """Model 4-component vector float32 packing into a single 32-bit register.""" - d0 = ref_cvt_pk_u8_f32(c0, 0, base) - d1 = ref_cvt_pk_u8_f32(c1, 1, d0) - d2 = ref_cvt_pk_u8_f32(c2, 2, d1) - d3 = ref_cvt_pk_u8_f32(c3, 3, d2) - return d3 - - -def run_ps_pack( - lines: list[str], - export_regs: tuple[str, str, str, str] = ("v0", "v0", "v0", "v0"), -) -> list[int]: - full_lines = list(lines) + [f"exp mrt0 {', '.join(export_regs)} done vm", "s_endpgm"] - spv = support.translate_lines("ps_alu_cvt_pk_u8_f32", full_lines) - return support.mrt0_words(spv) - - -class TestAluCvtPkU8F32ReferenceOracle(unittest.TestCase): - """Reference oracle self-tests and baseline execution for v_cvt_pk_u8_f32.""" - - def test_exact_integers(self) -> None: - for k in range(256): - expected = k - self.assertEqual(ref_cvt_u8_byte(float(k)), expected, f"int {k}") - self.assertEqual(ref_cvt_u8_byte(f32_to_bits(float(k))), expected) - - def test_round_to_nearest_even_ties(self) -> None: - ties = [ - (0.5, 0), - (1.5, 2), - (2.5, 2), - (3.5, 4), - (4.5, 4), - (126.5, 126), - (127.5, 128), - (128.5, 128), - (252.5, 252), - (253.5, 254), - (254.5, 254), - ] - for val, want in ties: - with self.subTest(tie=val): - self.assertEqual(ref_cvt_u8_byte(val), want) - self.assertEqual(ref_cvt_u8_byte(f32_to_bits(val)), want) - - eps = 1e-5 - for val, _ in ties: - below = val - eps - above = val + eps - with self.subTest(delta=val): - self.assertEqual(ref_cvt_u8_byte(below), math.floor(val)) - self.assertEqual(ref_cvt_u8_byte(above), math.ceil(val)) - - def test_byte_slot_selection_and_masking(self) -> None: - # Each byte slot (0, 1, 2, 3) must write only bits [8*s+7 : 8*s] and preserve the rest. - test_val = float(0x42) - self.assertEqual(ref_cvt_pk_u8_f32(test_val, 0, CANARY_BASE), 0xDEADBE42) - self.assertEqual(ref_cvt_pk_u8_f32(test_val, 1, CANARY_BASE), 0xDEAD42EF) - self.assertEqual(ref_cvt_pk_u8_f32(test_val, 2, CANARY_BASE), 0xDE42BEEF) - self.assertEqual(ref_cvt_pk_u8_f32(test_val, 3, CANARY_BASE), 0x42ADBEEF) - - # Slot index masking (slot & 3): slots wrapping beyond 3. - self.assertEqual(ref_cvt_pk_u8_f32(test_val, 4, CANARY_BASE), 0xDEADBE42) - self.assertEqual(ref_cvt_pk_u8_f32(test_val, 5, CANARY_BASE), 0xDEAD42EF) - self.assertEqual(ref_cvt_pk_u8_f32(test_val, 7, CANARY_BASE), 0x42ADBEEF) - self.assertEqual(ref_cvt_pk_u8_f32(test_val, -1, CANARY_BASE), 0x42ADBEEF) - self.assertEqual(ref_cvt_pk_u8_f32(test_val, 0xFFFFFFFF, CANARY_BASE), 0x42ADBEEF) - - def test_vec4_packing_oracle_rgba_vectors(self) -> None: - vectors = [ - (255.0, 128.0, 64.0, 32.0, 0, 0x204080FF), - (0.0, 0.0, 0.0, 0.0, 0, 0x00000000), - (18.0, 52.0, 86.0, 120.0, 0, 0x78563412), - (254.5, 127.5, 1.5, 0.5, 0, 0x000280FE), - (170.0, 85.0, 240.0, 15.0, 0, 0x0FF055AA), - ] - for r, g, b, a, base, want in vectors: - with self.subTest(r=r, g=g, b=b, a=a): - self.assertEqual(ref_pack_4x_u8_f32(r, g, b, a, base), want) - - def test_ps_shader_execution_single_and_vec4(self) -> None: - # 1. Single byte insertion into slot 2 of CANARY_BASE. - out_single = run_ps_pack([ - f"v_mov_b32 v1, {f32_to_bits(86.0):#x}", - f"v_mov_b32 v3, {CANARY_BASE:#x}", - "v_cvt_pk_u8_f32 v0, v1, 2, v3", - ])[0] - self.assertEqual(out_single, ref_cvt_pk_u8_f32(86.0, 2, CANARY_BASE)) - self.assertEqual(out_single, 0xDE56BEEF) - - # 2. Sequential 4-component vector pack into v0. - out_vec4 = run_ps_pack([ - f"v_mov_b32 v1, {f32_to_bits(100.0):#x}", - f"v_mov_b32 v2, {f32_to_bits(200.0):#x}", - f"v_mov_b32 v3, {f32_to_bits(50.0):#x}", - f"v_mov_b32 v4, {f32_to_bits(25.0):#x}", - "v_cvt_pk_u8_f32 v0, v1, 0, 0", - "v_cvt_pk_u8_f32 v0, v2, 1, v0", - "v_cvt_pk_u8_f32 v0, v3, 2, v0", - "v_cvt_pk_u8_f32 v0, v4, 3, v0", - ])[0] - want_vec4 = ref_pack_4x_u8_f32(100.0, 200.0, 50.0, 25.0, 0) - self.assertEqual(out_vec4, want_vec4) - self.assertEqual(out_vec4, 0x1932C864) - - def test_inline_constants_and_sgpr_operands(self) -> None: - # Float source as inline constants (1.0, 2.0, 4.0, 0.5) and SGPRs. - out = run_ps_pack([ - "v_cvt_pk_u8_f32 v0, 1.0, 0, 0", - "v_cvt_pk_u8_f32 v0, 2.0, 1, v0", - "v_cvt_pk_u8_f32 v0, 4.0, 2, v0", - "v_cvt_pk_u8_f32 v0, 0.5, 3, v0", - ])[0] - self.assertEqual(out, (1) | (2 << 8) | (4 << 16) | (0 << 24)) - - # Slot and base from SGPRs. - out_sgpr = run_ps_pack([ - f"v_mov_b32 v1, {f32_to_bits(65.0):#x}", - "s_mov_b32 s4, 1", - f"s_mov_b32 s5, {CANARY_BASE:#x}", - "v_cvt_pk_u8_f32_e64 v0, v1, s4, s5", - ])[0] - self.assertEqual(out_sgpr, ref_cvt_pk_u8_f32(65.0, 1, CANARY_BASE)) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_alu_cvt_pknorm_f16.py b/tests/semantic/test_alu_cvt_pknorm_f16.py deleted file mode 100644 index 75e5d5c0e..000000000 --- a/tests/semantic/test_alu_cvt_pknorm_f16.py +++ /dev/null @@ -1,265 +0,0 @@ -"""Semantic interpreter + spirv-val tests for RDNA2 v_cvt_pknorm_i16_f16 and v_cvt_pknorm_u16_f16. - -D[15:0] = norm16(S0.f16), D[31:16] = norm16(S1.f16): each selected f16 half (op_sel[0..1], with neg/abs source -modifiers) is clamped to [-1, 1] (i16) or [0, 1] (u16), scaled by 32767 or 65535, and rounded once to nearest even -(NaN -> 0). Compared against an exact rational fractions.Fraction reference so near-tie f16 inputs that would -double-round in naive binary32 OpFMul are checked directly. -""" -from fractions import Fraction -import math -import os -import random -import shutil -import struct -import subprocess -import sys -import tempfile -import unittest -import warnings - -HERE = os.path.dirname(os.path.abspath(__file__)) -ROOT = os.path.dirname(os.path.dirname(HERE)) -TOOLS_DIR = os.environ.get("LEONIDA_TOOLS_DIR") or os.path.join(ROOT, "tools") - -sys.dont_write_bytecode = True -sys.path.insert(0, TOOLS_DIR) -sys.path.insert(0, HERE) - -import rdna2spirv # noqa: E402 -import spirv_mini_interp as si # noqa: E402 - -STUB_DXBC = b"DXBC" + bytes(24) + struct.pack(" float: - return struct.unpack(" int: - return struct.unpack(" int: - x = f16_to_float(bits16) - if math.isnan(x): - return 0 - lo = -1.0 if snorm else 0.0 - if x <= lo: - cl = Fraction(-1 if snorm else 0) - elif x >= 1.0: - cl = Fraction(1) - else: - cl = Fraction(x) - scale = 32767 if snorm else 65535 - return round(cl * scale) & 0xFFFF - - -OPS = {"v_cvt_pknorm_i16_f16": True, "v_cvt_pknorm_u16_f16": False} -EDGE_F16 = [ - 0x0000, # +0.0 - 0x8000, # -0.0 - 0x0001, # smallest positive f16 denormal (2^-24) - 0x8001, # smallest negative f16 denormal (-2^-24) - 0x03FF, # largest positive f16 denormal - 0x0400, # smallest positive f16 normal (2^-14) - 0x3400, # +0.25 - 0xB400, # -0.25 - 0x37FF, # 0.5 - 2^-12 (near-tie) - 0xB7FF, # -(0.5 - 2^-12) - 0x3800, # +0.5 (exact tie -> even) - 0xB800, # -0.5 (exact tie -> even) - 0x3801, # 0.5 + 2^-11 (double-rounding trap in naive f32 OpFMul) - 0xB801, # -(0.5 + 2^-11) (double-rounding trap in naive f32 OpFMul) - 0x3BFF, # 1.0 - 2^-11 - 0xBBFF, # -(1.0 - 2^-11) - 0x3C00, # +1.0 - 0xBC00, # -1.0 - 0x4000, # +2.0 (clamped) - 0xC000, # -2.0 (clamped) - 0x7C00, # +inf - 0xFC00, # -inf - 0x7E00, # +qNaN - 0xFE00, # -qNaN - 0x7C01, # +sNaN - 0xFC01, # -sNaN -] - -_TMP_DIR = None -_SRC_PATH = None - - -def setUpModule(): - global _TMP_DIR, _SRC_PATH - _TMP_DIR = tempfile.TemporaryDirectory() - disasm_dir = os.path.join(_TMP_DIR.name, "disasm") - os.mkdir(disasm_dir) - _SRC_PATH = os.path.join(disasm_dir, "ps_cvt_pknorm_f16.s") - with open(os.path.join(_TMP_DIR.name, "ps_cvt_pknorm_f16.dxbc"), "wb") as f: - f.write(STUB_DXBC) - - -def tearDownModule(): - global _TMP_DIR - if _TMP_DIR is not None: - _TMP_DIR.cleanup() - _TMP_DIR = None - - -def translate_lines(lines) -> str: - if _TMP_DIR is None: - setUpModule() - out_lines = list(lines) + [ - "v_and_b32 v5, 0xffff, v0", - "v_lshrrev_b32 v6, 16, v0", - "v_or_b32 v5, 0x40000000, v5", - "v_or_b32 v6, 0x40000000, v6", - ] - asm = "; test_cvt_pknorm_f16\n" + "".join(f"\t{ln}\n" for ln in out_lines) - asm += "\texp mrt0 v5, v6, v5, v5 done vm\n\ts_endpgm\n" - with open(_SRC_PATH, "w", encoding="utf-8", newline="\n") as f: - f.write(asm) - with warnings.catch_warnings(): - warnings.simplefilter("ignore", ResourceWarning) - return rdna2spirv.translate(_SRC_PATH) - - -def run_lines(lines) -> int: - spv = translate_lines(lines) - lo, hi = si.run_fragment(spv)["%out_mrt0"][:2] - assert lo >> 16 == 0x4000 and hi >> 16 == 0x4000, (hex(lo), hex(hi)) - return (lo & 0xFFFF) | ((hi & 0xFFFF) << 16) - - -def run_op(op: str, s0: int, s1: int, mod0: str = "", mod1: str = "", extra: str = "") -> int: - tail = f" {extra}" if extra else "" - return run_lines([ - f"v_mov_b32 v1, {s0:#x}", - f"v_mov_b32 v2, {s1:#x}", - "v_mov_b32 v0, 0xdeadbeef", - f"{op} v0, {mod0}v1, {mod1}v2{tail}", - ]) - - -class CvtPknormF16Tests(unittest.TestCase): - def test_double_rounding_traps(self): - # 0x3801 = 0.5 + 2^-11: exact products are 16399.49951171875 (snorm -> 16399) and - # 32799.49951171875 (unorm -> 32799). Naive f32 OpFMul rounds both to .5 -> 16400 / 32800. - self.assertEqual(ref_norm16_f16(0x3801, True), 16399) - self.assertEqual(ref_norm16_f16(0xB801, True), (-16399) & 0xFFFF) - self.assertEqual(ref_norm16_f16(0x3801, False), 32799) - self.assertEqual(run_op("v_cvt_pknorm_i16_f16", 0x3801, 0xB801), - 16399 | (((-16399) & 0xFFFF) << 16)) - self.assertEqual(run_op("v_cvt_pknorm_u16_f16", 0x3801, 0x37FF), - 32799 | (ref_norm16_f16(0x37FF, False) << 16)) - - def test_edge_values(self): - for op, snorm in OPS.items(): - for idx, x in enumerate(EDGE_F16): - y = EDGE_F16[(idx * 7 + 3) % len(EDGE_F16)] - # Put garbage in the unselected high halves to prove low-half extraction ignores them. - s0 = x | (0x7E00 << 16) - s1 = y | (0x3C00 << 16) - want = ref_norm16_f16(x, snorm) | (ref_norm16_f16(y, snorm) << 16) - with self.subTest(op=op, x=hex(x), y=hex(y)): - self.assertEqual(run_op(op, s0, s1), want) - - def test_opsel_and_source_modifiers_and_inline_const(self): - # op_sel picks high/low halves independently - s0 = 0x3801 | (0xBC00 << 16) # lo = 0.5+2^-11, hi = -1.0 - s1 = 0x3800 | (0x3C00 << 16) # lo = 0.5, hi = +1.0 - self.assertEqual( - run_op("v_cvt_pknorm_i16_f16", s0, s1, extra="op_sel:[1,0]"), - ((-32767) & 0xFFFF) | (16384 << 16), - ) - self.assertEqual( - run_op("v_cvt_pknorm_u16_f16", s0, s1, extra="op_sel:[0,1]"), - 32799 | (65535 << 16), - ) - self.assertEqual( - run_lines([ - f"v_mov_b32 v1, {s0:#x}", - f"v_mov_b32 v2, {s1:#x}", - "v_cvt_pknorm_i16_f16 v0, |v1|, -v2 op_sel:[1,1]", - ]), - 32767 | (((-32767) & 0xFFFF) << 16), - ) - # Inline f16 constant and SGPR source - got = run_lines([ - "s_mov_b32 s0, 0x38003801", - "v_cvt_pknorm_i16_f16 v0, -0.5, s0 op_sel:[0,0]", - ]) - self.assertEqual(got, ((-16384) & 0xFFFF) | (16399 << 16)) - - def test_seeded_pairs(self): - rng = random.Random(0xF160) - for _ in range(40): - op = rng.choice(list(OPS)) - snorm = OPS[op] - x = rng.randrange(0x10000) - y = rng.randrange(0x10000) - sel0 = rng.randrange(2) - sel1 = rng.randrange(2) - s0 = (x << 16) | rng.randrange(0x10000) if sel0 else x | (rng.randrange(0x10000) << 16) - s1 = (y << 16) | rng.randrange(0x10000) if sel1 else y | (rng.randrange(0x10000) << 16) - want = ref_norm16_f16(x, snorm) | (ref_norm16_f16(y, snorm) << 16) - with self.subTest(op=op, x=hex(x), y=hex(y), sel=(sel0, sel1)): - self.assertEqual(run_op(op, s0, s1, extra=f"op_sel:[{sel0},{sel1}]"), want) - - def test_clamp_and_opsel_dst(self): - s0 = 0x3C003400 # hi = +1.0, lo = +0.25 - s1 = 0xBC003801 # hi = -1.0, lo = 0.5+2^-11 - self.assertEqual(run_op("v_cvt_pknorm_i16_f16", s0, s1, extra="clamp"), 0x400F2000) - self.assertEqual(run_op("v_cvt_pknorm_u16_f16", s0, s1, extra="clamp"), 0x801F4000) - want_dhi_i16 = { - "op_sel:[0,0,1]": 0x20000000, - "op_sel:[0,1,1]": 0x20000000, - "op_sel:[1,0,1]": 0x7FFF0000, - "op_sel:[1,1,1]": 0x7FFF0000, - "op_sel:[1,0,1] clamp": 0x7FFF0000, - } - want_dhi_u16 = { - "op_sel:[0,0,1]": 0x40000000, - "op_sel:[0,1,1]": 0x40000000, - "op_sel:[1,0,1]": 0xFFFF0000, - "op_sel:[1,1,1]": 0xFFFF0000, - "op_sel:[1,0,1] clamp": 0xFFFF0000, - } - for mod, want in want_dhi_i16.items(): - with self.subTest(op="v_cvt_pknorm_i16_f16", mod=mod): - self.assertEqual(run_op("v_cvt_pknorm_i16_f16", s0, s1, extra=mod), want) - for mod, want in want_dhi_u16.items(): - with self.subTest(op="v_cvt_pknorm_u16_f16", mod=mod): - self.assertEqual(run_op("v_cvt_pknorm_u16_f16", s0, s1, extra=mod), want) - - def test_rejected_modifiers_and_spirv_val(self): - for bad in ( - "v_cvt_pknorm_u16_f16 v0, v1, v2 mul:2", - "v_cvt_pknorm_i16_f16 v0, v1, v2 mul:4", - "v_cvt_pknorm_u16_f16 v0, v1, v2 div:2", - "v_cvt_pknorm_u16_f16 v0, v1, v2 op_sel_hi:[1,1]", - "v_cvt_pknorm_i16_f16 v0, v1, v2 neg_lo:[1,0]", - "v_cvt_pknorm_u16_f16 v0, v1, v2 neg_hi:[0,1]", - "v_cvt_pknorm_i16_f16 v0, v1, v2 op_sel:[0,0,0,1]", - "v_cvt_pknorm_u16_f16 v0, v1, v2 op_sel:[2,0,0]", - ): - with self.subTest(bad=bad), self.assertRaises(rdna2spirv.Unsupported): - translate_lines([bad]) - if SPIRV_AS and SPIRV_VAL: - spv = translate_lines([ - "v_mov_b32 v1, 0xbc003801", - "v_mov_b32 v2, 0x3c003800", - "v_cvt_pknorm_i16_f16 v0, |v1|, -v2 op_sel:[1,0]", - "v_cvt_pknorm_u16_f16 v0, v0, 0.5 op_sel:[0,0]", - ]) - spv_bin = os.path.join(_TMP_DIR.name, "cvt_pknorm_f16.spv") - p1 = subprocess.run([SPIRV_AS, "--target-env", "vulkan1.2", "-", "-o", spv_bin], - input=spv.encode("utf-8"), capture_output=True) - self.assertEqual(p1.returncode, 0, p1.stderr.decode("utf-8", "replace")) - p2 = subprocess.run([SPIRV_VAL, "--target-env", "vulkan1.2", spv_bin], capture_output=True) - self.assertEqual(p2.returncode, 0, p2.stderr.decode("utf-8", "replace")) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_alu_cvt_pknorm_f32.py b/tests/semantic/test_alu_cvt_pknorm_f32.py deleted file mode 100644 index 1dc548ff6..000000000 --- a/tests/semantic/test_alu_cvt_pknorm_f32.py +++ /dev/null @@ -1,170 +0,0 @@ -"""Semantic interpreter tests for RDNA2 v_cvt_pknorm_i16_f32 and v_cvt_pknorm_u16_f32. - -D[15:0] = norm16(S0), D[31:16] = norm16(S1): the f32 is clamped to [-1, 1] (i16) or [0, 1] (u16), scaled by 32767 or -65535 and rounded to nearest even. Mesa ACO emits these opcodes for NIR pack_snorm_2x16 / pack_unorm_2x16, defined in -nir_opcodes.py as fround_even(fclamp(x) * 32767.0 / 65535.0). NaN gives 0 (as v_cvt_i32_f32), and the exact product -is rounded once, not the f32 product: both measured on an RDNA2 iGPU (gfx1036, SHADER-339; the rounding is -SHADER-363). NEAR_TIES are inputs whose f32 product lands exactly on k + 0.5 while the exact one does not; rounding the -f32 product would be one off there. The whole dword is written. Each case translates a synthetic pixel shader with tools/rdna2spirv.py, runs it in -tests/semantic/spirv_mini_interp.py and compares the result with a plain-Python reference. D leaves through exp as two -16-bit halves ORed into 0x40000000, so no export channel is a NaN or denormal pattern that a float round trip could -change. -""" -import os -import random -import struct -import sys -import tempfile -import unittest -import warnings -from fractions import Fraction - -HERE = os.path.dirname(os.path.abspath(__file__)) -ROOT = os.path.dirname(os.path.dirname(HERE)) -TOOLS_DIR = os.environ.get("LEONIDA_TOOLS_DIR") or os.path.join(ROOT, "tools") - -sys.dont_write_bytecode = True -sys.path.insert(0, TOOLS_DIR) -sys.path.insert(0, HERE) - -import rdna2spirv # noqa: E402 -import spirv_mini_interp as si # noqa: E402 - -M32 = 0xFFFFFFFF -STUB_DXBC = b"DXBC" + bytes(24) + struct.pack(" float: - return struct.unpack(" int: - return struct.unpack(" int: - x = f32(b) - if x != x: - return 0 - lo = -1.0 if snorm else 0.0 - x = min(max(x, lo), 1.0) - # The exact product is rounded once to nearest even, as RDNA2 does (gfx1036, SHADER-339/363), not the f32 - # product. Fraction keeps it exact; round() on a Fraction is round-half-even. - return round(Fraction(x) * (32767 if snorm else 65535)) & 0xFFFF - - -OPS = {"v_cvt_pknorm_i16_f32": True, "v_cvt_pknorm_u16_f32": False} -VALUES = [bits(v) for v in (0.0, -0.0, 1.0, -1.0, 0.5, -0.5, 2.0, -2.0, 1e-30, 0.25, 0.75, 0.999, -0.999, - 1 / 32767, 0.5 / 32767, 1.5 / 32767, 2.5 / 32767, 0.5 / 65535, 1.5 / 65535, 2.5 / 65535, - float("inf"), float("-inf"))] + [0x7FC00000, 0xFFC00000, 0x00000001, 0x80000001] -# (op, S0, S1, the dword an RDNA2 iGPU (gfx1036) gave, tools/pknorm_probe.py --oracle hw). S0 or S1 is a near tie: -# below k + 0.5 exactly (1.5 - 1.4e-9 gives 1, 3.5 - ... gives 3) or above it (256.5 + 1.5e-5 gives 257). -MEASURED = [ - ("v_cvt_pknorm_i16_f32", 0x38400180, 0x00000000, 0x00000001), - ("v_cvt_pknorm_i16_f32", 0x38E001C0, 0x80000000, 0x00000003), - ("v_cvt_pknorm_i16_f32", 0x39300160, 0x3F800000, 0x7FFF0005), - ("v_cvt_pknorm_i16_f32", 0x3C004101, 0xBF800000, 0x80010101), - ("v_cvt_pknorm_i16_f32", 0x3F000000, 0x3C014103, 0x01034000), - ("v_cvt_pknorm_i16_f32", 0xBF000000, 0x3C024105, 0x0105C000), - ("v_cvt_pknorm_u16_f32", 0x37C000C0, 0x40000000, 0xFFFF0001), - ("v_cvt_pknorm_u16_f32", 0x386000E0, 0x80000000, 0x00000003), - ("v_cvt_pknorm_u16_f32", 0x38B000B0, 0x3F800000, 0xFFFF0005), - ("v_cvt_pknorm_u16_f32", 0x3B008081, 0xBF800000, 0x00000081), - ("v_cvt_pknorm_u16_f32", 0x3F000000, 0x3B028083, 0x00838000), - ("v_cvt_pknorm_u16_f32", 0xBF000000, 0x3B048085, 0x00850000), -] - -_TMP_DIR = None -_SRC_PATH = None - - -def setUpModule(): - global _TMP_DIR, _SRC_PATH - _TMP_DIR = tempfile.TemporaryDirectory() - disasm_dir = os.path.join(_TMP_DIR.name, "disasm") - os.mkdir(disasm_dir) - _SRC_PATH = os.path.join(disasm_dir, "ps_cvt_pknorm.s") - with open(os.path.join(_TMP_DIR.name, "ps_cvt_pknorm.dxbc"), "wb") as f: - f.write(STUB_DXBC) - - -def tearDownModule(): - global _TMP_DIR - if _TMP_DIR is not None: - _TMP_DIR.cleanup() - _TMP_DIR = None - - -def run_lines(lines) -> int: - if _TMP_DIR is None: - setUpModule() - lines = list(lines) + ["v_and_b32 v5, 0xffff, v0", "v_lshrrev_b32 v6, 16, v0", - "v_or_b32 v5, 0x40000000, v5", "v_or_b32 v6, 0x40000000, v6"] - asm = "; test_cvt_pknorm\n" + "".join(f"\t{ln}\n" for ln in lines) + "\texp mrt0 v5, v6, v5, v5 done vm\n\ts_endpgm\n" - with open(_SRC_PATH, "w", encoding="utf-8") as f: - f.write(asm) - with warnings.catch_warnings(): - warnings.simplefilter("ignore", ResourceWarning) - spv = rdna2spirv.translate(_SRC_PATH) - lo, hi = si.run_fragment(spv)["%out_mrt0"][:2] - assert lo >> 16 == 0x4000 and hi >> 16 == 0x4000, (hex(lo), hex(hi)) - return (lo & 0xFFFF) | (hi & 0xFFFF) << 16 - - -def run_op(op: str, x: int, y: int, mods: str = "") -> int: - return run_lines([f"v_mov_b32 v1, {x:#x}", f"v_mov_b32 v2, {y:#x}", "v_mov_b32 v0, 0xdeadbeef", - f"{op} v0, {mods}v1, v2"]) - - -class CvtPknormTests(unittest.TestCase): - def test_reference(self): - self.assertEqual(norm16(bits(1.0), True), 0x7FFF) - self.assertEqual(norm16(bits(-2.0), True), 0x8001) # -32767, not -32768 - self.assertEqual(norm16(bits(1.0), False), 0xFFFF) - self.assertEqual(norm16(bits(-1.0), False), 0) - self.assertEqual(norm16(bits(0.5), False), 32768) # 32767.5 rounds to even - self.assertEqual(norm16(bits(0.5), True), 16384) # 16383.5 rounds to even - self.assertEqual(norm16(0x7FC00000, True), 0) - - def test_near_ties_round_once_as_measured_on_rdna2(self): - for op, s0, s1, want in MEASURED: - with self.subTest(op=op, s0=hex(s0), s1=hex(s1)): - self.assertEqual(norm16(s0, OPS[op]) | norm16(s1, OPS[op]) << 16, want) - self.assertEqual(run_op(op, s0, s1), want) - - def test_values(self): - for op, snorm in OPS.items(): - for x in VALUES: - for y in VALUES[::5]: - with self.subTest(op=op, x=hex(x), y=hex(y)): - self.assertEqual(run_op(op, x, y), norm16(x, snorm) | norm16(y, snorm) << 16) - - def test_seeded(self): - rng = random.Random(0xC0DE) - for _ in range(40): - op = rng.choice(list(OPS)) - x, y = bits(rng.uniform(-1.5, 1.5)), bits(rng.uniform(-1.5, 1.5)) - with self.subTest(op=op, x=hex(x), y=hex(y)): - self.assertEqual(run_op(op, x, y), norm16(x, OPS[op]) | norm16(y, OPS[op]) << 16) - - def test_source_and_output_modifiers(self): - half = bits(0.5) - self.assertEqual(run_op("v_cvt_pknorm_i16_f32", half, half, "-"), (-16384 & 0xFFFF) | 16384 << 16) - got = run_lines([f"v_mov_b32 v1, {bits(-0.5):#x}", f"v_mov_b32 v2, {half:#x}", - "v_cvt_pknorm_u16_f32 v0, |v1|, -v2"]) - self.assertEqual(got, 32768) # |-0.5| -> 32768, -0.5 -> 0 - for op, snorm in OPS.items(): - for x, y in ((bits(-2.0), bits(2.0)), (bits(0.5), bits(-0.5)), (0x7FC00000, bits(1.0))): - with self.subTest(op=op, x=hex(x), y=hex(y)): - got_clamp = run_lines([ - f"v_mov_b32 v1, {x:#x}", - f"v_mov_b32 v2, {y:#x}", - f"{op} v0, v1, v2 clamp", - ]) - self.assertEqual(got_clamp, norm16(x, snorm) | (norm16(y, snorm) << 16)) - with self.assertRaises(rdna2spirv.Unsupported): - run_lines(["v_cvt_pknorm_i16_f32 v0, v1, v2 mul:2"]) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_alu_div_fixup.py b/tests/semantic/test_alu_div_fixup.py deleted file mode 100644 index 1db7ac22a..000000000 --- a/tests/semantic/test_alu_div_fixup.py +++ /dev/null @@ -1,275 +0,0 @@ -"""Semantic interpreter and spirv-val tests for RDNA2 v_div_fixup_f16 and v_div_fixup_f64. - -v_div_fixup_{f16,f64} D, S0 (quot), S1 (denom), S2 (num) resolves IEEE-754 division special cases: - - sign_out = sign(S1) ^ sign(S2) - - NaN(S2) -> quiet(S2); NaN(S1) -> quiet(S1) - - (0/0) or (inf/inf) -> canonical negative qNaN (0xFE00 / 0xFFF80000_00000000) - - (x/inf) or (0/y) -> copysign(0, sign_out) - - (x/0) or (inf/y) or NaN(S0) -> copysign(inf, sign_out) - - otherwise copysign(S0, sign_out) -""" -import os -import shutil -import struct -import subprocess -import sys -import tempfile -import unittest -import warnings - -HERE = os.path.dirname(os.path.abspath(__file__)) -ROOT = os.path.dirname(os.path.dirname(HERE)) -TOOLS_DIR = os.environ.get("LEONIDA_TOOLS_DIR") or os.path.join(ROOT, "tools") - -sys.dont_write_bytecode = True -sys.path.insert(0, TOOLS_DIR) -sys.path.insert(0, HERE) - -import rdna2spirv # noqa: E402 -import spirv_mini_interp as si # noqa: E402 - -STUB_DXBC = b"DXBC" + bytes(24) + struct.pack(" int: - spv = translate_lines([ - f"v_mov_b32 v1, {s0 & 0xFFFFFFFF:#x}", - f"v_mov_b32 v2, {s1 & 0xFFFFFFFF:#x}", - f"v_mov_b32 v3, {s2 & 0xFFFFFFFF:#x}", - f"v_mov_b32 v0, {SEED_DST:#x}", - insn, - ], safe_v0=True) - lo, hi = si.run_fragment(spv)["%out_mrt0"][:2] - return (lo & 0xFFFF) | ((hi & 0xFFFF) << 16) - - -def run_f64(s0: int, s1: int, s2: int, insn: str = "v_div_fixup_f64 v[0:1], v[2:3], v[4:5], v[6:7]") -> int: - spv = translate_lines([ - f"v_mov_b32 v2, {s0 & 0xFFFFFFFF:#x}", - f"v_mov_b32 v3, {(s0 >> 32) & 0xFFFFFFFF:#x}", - f"v_mov_b32 v4, {s1 & 0xFFFFFFFF:#x}", - f"v_mov_b32 v5, {(s1 >> 32) & 0xFFFFFFFF:#x}", - f"v_mov_b32 v6, {s2 & 0xFFFFFFFF:#x}", - f"v_mov_b32 v7, {(s2 >> 32) & 0xFFFFFFFF:#x}", - "v_mov_b32 v0, 0", - "v_mov_b32 v1, 0", - insn, - ]) - out = si.run_fragment(spv)["%out_mrt0"] - return (out[1] << 32) | out[0] - - -class DivFixupF16Tests(unittest.TestCase): - def test_all_special_and_normal_cases(self): - cases = ( - ("normal_pos", H_HALF, H_ONE, H_ONE, H_HALF), - ("normal_neg_sign_fix", H_HALF, H_NEG2, H_ONE, H_HALF | 0x8000), - ("nan_s2_priority", H_ONE, H_SNAN1, H_QNAN2, H_QNAN2), - ("nan_s1_snan_ieee0", H_ONE, H_SNAN1, H_ONE, H_SNAN1), - ("nan_s2_snan_ieee0", H_ONE, H_ONE, 0x7C01, 0x7C01), - ("zero_div_zero", H_ONE, H_POS0, H_NEG0, H_CANON_NAN), - ("inf_div_inf", H_ONE, H_INF, H_NINF, H_CANON_NAN), - ("finite_div_inf_neg", H_ONE, H_NINF, H_ONE, H_NEG0), - ("zero_div_finite_pos", H_ONE, H_NEG2, H_NEG0, H_POS0), - ("finite_div_zero_neg", H_ONE, H_NEG0, H_ONE, H_NINF), - ("inf_div_finite_pos", H_ONE, H_NEG2, H_NINF, H_INF), - ("nan_quot_to_pos_inf", 0x7E35, H_ONE, H_ONE, H_INF), - ("nan_quot_to_neg_inf", 0x7E35, H_NEG2, H_ONE, H_NINF), - ("f16_no_exp_underflow", H_ONE, 0x7800, 0x0400, H_ONE), # gfx1036: e2-e1=-29 keeps S0 - ("f16_no_exp_overflow", H_ONE, 0x0400, 0x7800, H_ONE), # gfx1036: e2-e1=+29 keeps S0 - ) - for name, s0, s1, s2, want in cases: - with self.subTest(case=name): - got = run_f16(0xBEEF0000 | s0, 0xCAFE0000 | s1, 0xDEAD0000 | s2) - self.assertEqual(got, (SEED_DST & 0xFFFF0000) | want) - - def test_opsel_input_and_output_modifiers_and_spirv_val(self): - # op_sel:[1,0,1,1] + neg on s1: s0=hi(0.5), s1=-lo(-2.0)=+2.0, s2=hi(1.0) -> +0.5 into high half - got = run_f16( - H_HALF << 16, - H_NEG2, - H_ONE << 16, - "v_div_fixup_f16 v0, v1, -v2, v3 op_sel:[1,0,1,1]", - ) - self.assertEqual(got, (H_HALF << 16) | (SEED_DST & 0xFFFF)) - - # Output modifier mul:2 clamp on 0.5 -> on RDNA2 omod is ignored for f16 with denorms kept; clamp applies - spv = translate_lines([ - f"v_mov_b32 v1, {H_HALF:#x}", - f"v_mov_b32 v2, {H_ONE:#x}", - f"v_mov_b32 v3, {H_ONE:#x}", - f"v_mov_b32 v0, {SEED_DST:#x}", - "v_div_fixup_f16 v0, v1, v2, v3 mul:2 clamp", - ], safe_v0=True) - validate_spirv(spv) - lo, hi = si.run_fragment(spv)["%out_mrt0"][:2] - self.assertEqual((lo & 0xFFFF) | ((hi & 0xFFFF) << 16), (SEED_DST & 0xFFFF0000) | H_HALF) - - -class DivFixupF64Tests(unittest.TestCase): - def test_all_special_and_normal_cases(self): - cases = ( - ("normal_pos", D_THREE, D_ONE, D_ONE, D_THREE), - ("normal_neg_sign_fix", D_THREE, D_NEG2, D_ONE, D_THREE | (1 << 63)), - ("nan_s2_priority", D_ONE, D_SNAN1, D_QNAN2, D_QNAN2), - ("nan_s1_snan_ieee0", D_ONE, D_SNAN1, D_ONE, D_SNAN1), - ("nan_s2_snan_ieee0", D_ONE, D_ONE, 0x7FF0000000000001, 0x7FF0000000000001), - ("zero_div_zero", D_ONE, D_POS0, D_NEG0, D_CANON_NAN), - ("inf_div_inf", D_ONE, D_INF, D_NINF, D_CANON_NAN), - ("finite_div_inf_neg", D_ONE, D_NINF, D_ONE, D_NEG0), - ("zero_div_finite_pos", D_ONE, D_NEG2, D_NEG0, D_POS0), - ("finite_div_zero_neg", D_ONE, D_NEG0, D_ONE, D_NINF), - ("inf_div_finite_pos", D_ONE, D_NEG2, D_NINF, D_INF), - ("nan_quot_to_pos_inf", 0xFFF8123456789ABC, D_NEG2 & ~(1 << 63), D_ONE, D_INF), - ("nan_quot_to_neg_inf", 0x7FF8123456789ABC, D_NEG2, D_ONE, D_NINF), - ("exp_diff_m1075_keeps_s0", D_ONE, 2046 << 52, 971 << 52, D_ONE), # gfx1036: e2-e1=-1075 keeps S0 - ("exp_diff_m1076_to_zero", D_ONE, 2046 << 52, 970 << 52, D_POS0), # gfx1036: e2-e1=-1076 -> +0 - ("exp_underflow_m1122", D_ONE, 1123 << 52, 1 << 52, D_POS0), # gfx1036: 2^-1022 / 2^100 -> +0 - ("f64_no_exp_overflow", D_ONE, 1 << 52, 1025 << 52, D_ONE), # gfx1036: e2-e1=+1024 keeps S0 - ) - for name, s0, s1, s2, want in cases: - with self.subTest(case=name): - self.assertEqual(run_f64(s0, s1, s2), want) - - def test_modifiers_plain_no_float64_and_omod_float64_validates(self): - # Plain form: no Float64 needed, supports abs/neg and SGPR/inline sources - spv_plain = translate_lines([ - f"v_mov_b32 v2, {D_THREE & 0xFFFFFFFF:#x}", - f"v_mov_b32 v3, {D_THREE >> 32:#x}", - f"s_mov_b32 s4, {D_NEG2 & 0xFFFFFFFF:#x}", - f"s_mov_b32 s5, {D_NEG2 >> 32:#x}", - "v_div_fixup_f64 v[0:1], v[2:3], |s[4:5]|, -1.0", - ]) - self.assertNotIn("OpCapability Float64", spv_plain) - validate_spirv(spv_plain) - out = si.run_fragment(spv_plain)["%out_mrt0"] - self.assertEqual((out[1] << 32) | out[0], D_THREE | (1 << 63)) - - # With output modifiers: enables Float64 + clamp_mods_f64 and passes spirv-val - spv_mod = translate_lines([ - f"v_mov_b32 v2, {D_THREE & 0xFFFFFFFF:#x}", - f"v_mov_b32 v3, {D_THREE >> 32:#x}", - "v_div_fixup_f64 v[0:1], v[2:3], 1.0, 1.0 mul:2 clamp", - ]) - self.assertIn("OpCapability Float64", spv_mod) - self.assertIn("FClamp", spv_mod) - validate_spirv(spv_mod) - - def test_scaling_modifiers_are_ignored_under_the_games_mode(self): - # Measured by @fiestorra on a gfx1036 iGPU (driver 31.0.24002.92) through tools/hw_oracle, - # tools/f64_omod_probe.py: on both ops the f16 and the binary64 result ignore mul:/div: while - # denorm_mode_16_64 = 3, the MODE these rows assume, and scale only with IEEE=0 and - # denorm_mode_16_64 = 0, while clamp applies in every MODE. See docs/design.md, - # "v_div_fixup_f16, v_div_fixup_f64". - two, onep5, three = 0x4000000000000000, 0x3FF8000000000000, 0x4008000000000000 - spv = translate_lines([ - f"v_mov_b32 v2, {two & 0xFFFFFFFF:#x}", - f"v_mov_b32 v3, {two >> 32:#x}", - f"v_mov_b32 v4, {onep5 & 0xFFFFFFFF:#x}", - f"v_mov_b32 v5, {onep5 >> 32:#x}", - f"v_mov_b32 v6, {three & 0xFFFFFFFF:#x}", - f"v_mov_b32 v7, {three >> 32:#x}", - "v_div_fixup_f64 v[0:1], v[2:3], v[4:5], v[6:7] mul:4 div:2", - ]) - self.assertNotIn("OpCapability Float64", spv) - self.assertNotRegex(spv, r"OpFMul %double") - self.assertNotIn("FClamp", spv) - validate_spirv(spv) - # 2.0 is the fixup of (2.0, 1.5, 3.0); mul:4 div:2 would have made it 4.0. - self.assertEqual( - run_f64(two, onep5, three, insn="v_div_fixup_f64 v[0:1], v[2:3], v[4:5], v[6:7] mul:4 div:2"), two) - - # The f16 form keeps the low-half write: no unpack/pack round-trip, no clamp. - spv16 = translate_lines([ - "v_mov_b32 v1, 0x4000", - "v_mov_b32 v2, 0x3e00", - "v_mov_b32 v3, 0x4200", - "v_div_fixup_f16 v0, v1, v2, v3 mul:2", - ]) - self.assertNotRegex(spv16, r"UnpackHalf2x16") - self.assertNotIn("FClamp", spv16) - validate_spirv(spv16) - self.assertEqual( - run_f16(0x4000, 0x3E00, 0x4200, insn="v_div_fixup_f16 v0, v1, v2, v3 mul:2") & 0xFFFF, 0x4000) - - def test_rejects_non_pair_destination(self): - with self.assertRaises(rdna2spirv.Unsupported): - translate_lines(["v_div_fixup_f64 v0, v[2:3], v[4:5], v[6:7]"]) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_alu_div_fixup_f32.py b/tests/semantic/test_alu_div_fixup_f32.py deleted file mode 100644 index ac17022a2..000000000 --- a/tests/semantic/test_alu_div_fixup_f32.py +++ /dev/null @@ -1,227 +0,0 @@ -"""Semantic tests for RDNA2 v_div_fixup_f32 against native gfx1036 measurements. - -Every row in MEASURED ran natively on an AMD Radeon(TM) Graphics RDNA2 GPU (gfx1036, -Windows AMD driver 32.0.21042.62) through tools/hw_oracle in both wave32 and wave64 -(identical on every row) under the game's inferred MODE (IEEE=0, denorm32=0, DX10_CLAMP=1). -""" -import os -import struct -import sys -import tempfile -import unittest -import warnings - -HERE = os.path.dirname(os.path.abspath(__file__)) -ROOT = os.path.dirname(os.path.dirname(HERE)) -sys.dont_write_bytecode = True -sys.path.insert(0, os.environ.get("LEONIDA_TOOLS_DIR") or os.path.join(ROOT, "tools")) -sys.path.insert(0, HERE) - -import rdna2spirv # noqa: E402 -import spirv_mini_interp as si # noqa: E402 - -STUB_DXBC = b"DXBC" + bytes(24) + struct.pack(" canonical -qNaN (0xFFC00000) - ("v_div_fixup_f32 v4, v1, v2, v3", 0x3F800000, 0x00000000, 0x00000000, 0xFFC00000), - ("v_div_fixup_f32 v4, v1, v2, v3", 0x3F800000, 0x80000000, 0x00000000, 0xFFC00000), - ("v_div_fixup_f32 v4, v1, v2, v3", 0x3F800000, 0x00000000, 0x80000000, 0xFFC00000), - ("v_div_fixup_f32 v4, v1, v2, v3", 0x3F800000, 0x80000000, 0x80000000, 0xFFC00000), - ("v_div_fixup_f32 v4, v1, v2, v3", 0x3F800000, 0x00000001, 0x807FFFFF, 0xFFC00000), - ("v_div_fixup_f32 v4, v1, v2, v3", 0x3F800000, 0x7F800000, 0x7F800000, 0xFFC00000), - ("v_div_fixup_f32 v4, v1, v2, v3", 0x3F800000, 0xFF800000, 0x7F800000, 0xFFC00000), - ("v_div_fixup_f32 v4, v1, v2, v3", 0x3F800000, 0x7F800000, 0xFF800000, 0xFFC00000), - ("v_div_fixup_f32 v4, v1, v2, v3", 0x3F800000, 0xFF800000, 0xFF800000, 0xFFC00000), - # 4. zero(S2) || inf(S1) -> +-0.0 (including 0/inf and denormal S2) - ("v_div_fixup_f32 v4, v1, v2, v3", 0x3F800000, 0x40000000, 0x00000000, 0x00000000), - ("v_div_fixup_f32 v4, v1, v2, v3", 0x3F800000, 0xC0000000, 0x00000000, 0x80000000), - ("v_div_fixup_f32 v4, v1, v2, v3", 0x3F800000, 0x40000000, 0x80000000, 0x80000000), - ("v_div_fixup_f32 v4, v1, v2, v3", 0x3F800000, 0xC0000000, 0x80000000, 0x00000000), - ("v_div_fixup_f32 v4, v1, v2, v3", 0x3F800000, 0x40000000, 0x80000001, 0x80000000), - ("v_div_fixup_f32 v4, v1, v2, v3", 0x3F800000, 0x7F800000, 0x40000000, 0x00000000), - ("v_div_fixup_f32 v4, v1, v2, v3", 0x3F800000, 0xFF800000, 0x40000000, 0x80000000), - ("v_div_fixup_f32 v4, v1, v2, v3", 0x3F800000, 0xFF800000, 0xC0000000, 0x00000000), - ("v_div_fixup_f32 v4, v1, v2, v3", 0x7FC00011, 0xFF800000, 0x00000000, 0x80000000), - # 5. zero(S1) || inf(S2) -> +-inf (including inf/0 and denormal S1) - ("v_div_fixup_f32 v4, v1, v2, v3", 0x3F800000, 0x00000000, 0x40000000, 0x7F800000), - ("v_div_fixup_f32 v4, v1, v2, v3", 0x3F800000, 0x80000000, 0x40000000, 0xFF800000), - ("v_div_fixup_f32 v4, v1, v2, v3", 0x3F800000, 0x00000000, 0xC0000000, 0xFF800000), - ("v_div_fixup_f32 v4, v1, v2, v3", 0x3F800000, 0x80000000, 0xC0000000, 0x7F800000), - ("v_div_fixup_f32 v4, v1, v2, v3", 0x3F800000, 0x807FFFFF, 0x40000000, 0xFF800000), - ("v_div_fixup_f32 v4, v1, v2, v3", 0x3F800000, 0x40000000, 0x7F800000, 0x7F800000), - ("v_div_fixup_f32 v4, v1, v2, v3", 0x3F800000, 0xC0000000, 0x7F800000, 0xFF800000), - ("v_div_fixup_f32 v4, v1, v2, v3", 0x3F800000, 0x80000000, 0x7F800000, 0xFF800000), - # 6. Exponent-difference underflow boundary: e2 - e1 <= -151 -> +-0 (beats NaN(S0) & inf(S0)); no overflow check - ("v_div_fixup_f32 v4, v1, v2, v3", 0x3F800000, 0x4B800000, 0x00800000, 0x3F800000), - ("v_div_fixup_f32 v4, v1, v2, v3", 0x3F800000, 0x4C000000, 0x00800000, 0x00000000), - ("v_div_fixup_f32 v4, v1, v2, v3", 0x3F800000, 0xCC000000, 0x00800000, 0x80000000), - ("v_div_fixup_f32 v4, v1, v2, v3", 0x3F800000, 0x7F7FFFFF, 0x34000000, 0x3F800000), - ("v_div_fixup_f32 v4, v1, v2, v3", 0x3F800000, 0x7F000000, 0x33FFFFFF, 0x00000000), - ("v_div_fixup_f32 v4, v1, v2, v3", 0x7FC00055, 0x64000000, 0x00800000, 0x00000000), - ("v_div_fixup_f32 v4, v1, v2, v3", 0x7F800000, 0xE4000000, 0x00800000, 0x80000000), - ("v_div_fixup_f32 v4, v1, v2, v3", 0x3F800000, 0x00800000, 0x7F000000, 0x3F800000), - # 7. NaN(S0) -> +-inf - ("v_div_fixup_f32 v4, v1, v2, v3", 0x7FC00001, 0x40000000, 0x3F800000, 0x7F800000), - ("v_div_fixup_f32 v4, v1, v2, v3", 0xFFC00001, 0xC0000000, 0x3F800000, 0xFF800000), - ("v_div_fixup_f32 v4, v1, v2, v3", 0x7F800001, 0xC0000000, 0xBF800000, 0x7F800000), - # 8. Fallback copysign(S0, sign_out), preserving S0 subnormals even under denorm32=0 - ("v_div_fixup_f32 v4, v1, v2, v3", 0xBF400000, 0x40000000, 0x40400000, 0x3F400000), - ("v_div_fixup_f32 v4, v1, v2, v3", 0x3F400000, 0xC0000000, 0x40400000, 0xBF400000), - ("v_div_fixup_f32 v4, v1, v2, v3", 0x7F800000, 0xC0000000, 0x3F800000, 0xFF800000), - ("v_div_fixup_f32 v4, v1, v2, v3", 0x00000000, 0xC0000000, 0x3F800000, 0x80000000), - ("v_div_fixup_f32 v4, v1, v2, v3", 0x00000001, 0x3F800000, 0x3F800000, 0x00000001), - ("v_div_fixup_f32 v4, v1, v2, v3", 0x00000001, 0xBF800000, 0x3F800000, 0x80000001), - ("v_div_fixup_f32 v4, v1, v2, v3", 0x807FFFFF, 0xBF800000, 0xBF800000, 0x007FFFFF), - # 9. VOP3 source modifiers abs / neg / -|x| (bitwise before classification, including NaNs) - ("v_div_fixup_f32 v4, v1, -v2, v3", 0x3F800000, 0x40000000, 0x3F800000, 0xBF800000), - ("v_div_fixup_f32 v4, v1, |v2|, v3", 0x3F800000, 0xC0000000, 0x3F800000, 0x3F800000), - ("v_div_fixup_f32 v4, v1, -|v2|, v3", 0x3F800000, 0x40000000, 0x3F800000, 0xBF800000), - ("v_div_fixup_f32 v4, v1, v2, -v3", 0x3F800000, 0x3F800000, 0x7FC00022, 0xFFC00022), - ("v_div_fixup_f32 v4, v1, v2, |v3|", 0x3F800000, 0x3F800000, 0xFF800005, 0x7F800005), - ("v_div_fixup_f32 v4, v1, -|v2|, v3", 0x3F800000, 0x7F800003, 0x3F800000, 0xFF800003), - ("v_div_fixup_f32 v4, |v1|, v2, v3", 0xBF800000, 0xBF800000, 0x3F800000, 0xBF800000), - # 10. Output modifiers: mul:2, mul:4, div:2, clamp (DX10_CLAMP=1 maps NaN -> +0.0), and combined omod+clamp - ("v_div_fixup_f32 v4, v1, v2, v3 mul:2", 0x3F400000, 0x3F800000, 0x3F800000, 0x3FC00000), - ("v_div_fixup_f32 v4, v1, v2, v3 mul:4", 0x3F000000, 0xBF800000, 0x3F800000, 0xC0000000), - ("v_div_fixup_f32 v4, v1, v2, v3 div:2", 0x40000000, 0x3F800000, 0x3F800000, 0x3F800000), - ("v_div_fixup_f32 v4, v1, v2, v3 clamp", 0x40400000, 0x3F800000, 0x3F800000, 0x3F800000), - ("v_div_fixup_f32 v4, v1, v2, v3 clamp", 0x3F000000, 0xBF800000, 0x3F800000, 0x00000000), - ("v_div_fixup_f32 v4, v1, v2, v3 clamp", 0x3F800000, 0x00000000, 0x00000000, 0x00000000), - ("v_div_fixup_f32 v4, v1, v2, v3 clamp", 0x3F800000, 0x3F800000, 0x7F800001, 0x00000000), - ("v_div_fixup_f32 v4, v1, v2, v3 clamp", 0x3F800000, 0x00000000, 0x3F800000, 0x3F800000), - ("v_div_fixup_f32 v4, v1, v2, v3 clamp", 0x3F800000, 0x80000000, 0x3F800000, 0x00000000), - ("v_div_fixup_f32 v4, v1, v2, v3 clamp", 0x3F800000, 0xBF800000, 0x00000000, 0x00000000), - ("v_div_fixup_f32 v4, v1, v2, v3 clamp mul:2", 0x3F400000, 0x3F800000, 0x3F800000, 0x3F800000), - ("v_div_fixup_f32 v4, v1, v2, v3 clamp div:2", 0x3FC00000, 0x3F800000, 0x3F800000, 0x3F400000), -] - - -def _translate(lines, name="ps_div_fixup_f32"): - with tempfile.TemporaryDirectory() as tmp: - os.mkdir(os.path.join(tmp, "disasm")) - src = os.path.join(tmp, "disasm", f"{name}.s") - with open(os.path.join(tmp, f"{name}.dxbc"), "wb") as f: - f.write(STUB_DXBC) - with open(src, "w", encoding="utf-8") as f: - f.write(f"; {name}\n" + "".join(f"\t{x}\n" for x in lines)) - with warnings.catch_warnings(): - warnings.simplefilter("ignore", ResourceWarning) - return rdna2spirv.translate(src) - - -def _run_body(body_lines, count): - header = [ - f"s_mov_b32 s0, {BASE:#x}", - "s_mov_b32 s1, 0", - "s_mov_b32 s2, 0x1000", - "s_mov_b32 s3, 0x31016fac", - ] - tail = ["exp mrt0 v4, v4, v4, v4 done vm", "s_endpgm"] - spv = _translate(header + body_lines + tail) - memory = {} - si.run_fragment(spv, memory=memory) - return spv, [memory.get(BASE + 4 * k) for k in range(count)] - - -class TestDivFixupF32(unittest.TestCase): - def test_measured_gfx1036_rows(self): - body = [] - for k, (insn, s0, s1, s2, _) in enumerate(MEASURED): - body += [ - f"v_mov_b32 v1, {s0:#x}", - f"v_mov_b32 v2, {s1:#x}", - f"v_mov_b32 v3, {s2:#x}", - "v_mov_b32 v4, 0xdeadbeef", - insn, - f"buffer_store_dword v4, off, s[0:3], 0 offset:{4 * k}", - ] - _, words = _run_body(body, len(MEASURED)) - for (insn, s0, s1, s2, want), got in zip(MEASURED, words): - with self.subTest(insn=insn, s0=hex(s0), s1=hex(s1), s2=hex(s2)): - self.assertEqual(got, want) - - def test_operand_forms_and_e64(self): - body = [ - # SGPR S0, inline float S1/S2, _e64 spelling - "s_mov_b32 s4, 0x3f400000", - "v_div_fixup_f32_e64 v4, s4, -1.0, 2.0", - "buffer_store_dword v4, off, s[0:3], 0 offset:0", - # VOP3 FP modifiers on constants (-|1.0| = -1.0, |0xbf800000| = +1.0 -> neg sign) - "v_mov_b32 v1, 0x3f800000", - "v_div_fixup_f32 v4, v1, -|1.0|, |0xbf800000|", - "buffer_store_dword v4, off, s[0:3], 0 offset:4", - # Hex literal NaN in S2 - "v_mov_b32 v2, 0x3f800000", - "v_div_fixup_f32 v4, v1, v2, 0x7fc00022", - "buffer_store_dword v4, off, s[0:3], 0 offset:8", - # null destination discards result cleanly without disturbing v4 - "v_mov_b32 v4, 0x12345678", - "v_div_fixup_f32 null, v1, v2, v2", - "buffer_store_dword v4, off, s[0:3], 0 offset:12", - ] - _, words = _run_body(body, 4) - self.assertEqual(words, [0xBF400000, 0xBF800000, 0x7FC00022, 0x12345678]) - - def test_inactive_lane_preserves_dst(self): - body = [ - "v_mov_b32 v1, 0x3f800000", - "v_mov_b32 v2, 0x40000000", - "v_mov_b32 v3, 0x40400000", - "v_mov_b32 v4, 0xdeadbeef", - "s_mov_b32 exec_lo, 0", - "v_div_fixup_f32 v4, v1, v2, v3", - "s_mov_b32 exec_lo, -1", - "buffer_store_dword v4, off, s[0:3], 0 offset:0", - ] - _, words = _run_body(body, 1) - self.assertEqual(words, [0xDEADBEEF]) - - def test_spirv_structure_and_unsupported(self): - plain_spv = _translate([ - "v_mov_b32 v1, 0x3f800000", - "v_mov_b32 v2, 0x40000000", - "v_mov_b32 v3, 0x40400000", - "v_div_fixup_f32 v4, v1, v2, v3", - "exp mrt0 v4, v4, v4, v4 done vm", - "s_endpgm", - ], name="ps_div_fixup_plain") - self.assertNotIn("OpFMul", plain_spv) - self.assertNotIn("FClamp", plain_spv) - self.assertNotIn("OpCapability Float64", plain_spv) - - clamp_spv = _translate([ - "v_mov_b32 v1, 0x3f800000", - "v_mov_b32 v2, 0x00000000", - "v_mov_b32 v3, 0x00000000", - "v_div_fixup_f32 v4, v1, v2, v3 clamp", - "exp mrt0 v4, v4, v4, v4 done vm", - "s_endpgm", - ], name="ps_div_fixup_clamp") - self.assertIn("OpIsNan", clamp_spv) - self.assertIn("FClamp", clamp_spv) - - with self.assertRaises(rdna2spirv.Unsupported): - _translate([ - "v_div_fixup_f32 v4, v1, v2, v3 op_sel:[0,0,0,0]", - "exp mrt0 v4, v4, v4, v4 done vm", - "s_endpgm", - ], name="ps_div_fixup_bad_mod") - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_alu_div_fmas.py b/tests/semantic/test_alu_div_fmas.py deleted file mode 100644 index 658607557..000000000 --- a/tests/semantic/test_alu_div_fmas.py +++ /dev/null @@ -1,505 +0,0 @@ -"""Semantic interpreter and SPIR-V validation tests for RDNA2 v_div_fmas_f32 and v_div_fmas_f64. - -Measured natively on RDNA2 (AMD Radeon Graphics, gfx1036, Windows driver 32.0.21042.62, -wave32 and wave64, game MODE ieee=0 / dx10_clamp=1 / denorm32=0 / denorm16_64=3): - VCC == 0: fma(S0, S1, S2) - VCC == 1: (exp(S2) > bias ? 2^+S : 2^-S) * fma_exact(S0, S1, S2) -where (bias, S) = (127, 64) for f32 and (1023, 128) for f64 (exp(S2) > bias <=> |S2| >= 2.0). - -For f32 under denorm32=0, subnormal inputs and intermediate products are kept, while the -scaled FMA output flushes subnormals to signed zero before (and after) output modifiers. -For f64 under denorm16_64=3, subnormal inputs and outputs are preserved with single rounding. -Both accept VOP3 input (abs/neg) and output (mul:2, mul:4, div:2, clamp) modifiers. -""" -from fractions import Fraction -import math -import os -import re -import shutil -import struct -import subprocess -import sys -import tempfile -import unittest -import warnings - -HERE = os.path.dirname(os.path.abspath(__file__)) -ROOT = os.path.dirname(os.path.dirname(HERE)) -TOOLS_DIR = os.environ.get("LEONIDA_TOOLS_DIR") or os.path.join(ROOT, "tools") - -sys.dont_write_bytecode = True -sys.path.insert(0, TOOLS_DIR) -sys.path.insert(0, HERE) - -import rdna2spirv # noqa: E402 -import spirv_asm # noqa: E402 -import spirv_mini_interp as si # noqa: E402 - -STUB_DXBC = b"DXBC" + bytes(24) + struct.pack(" int: - return struct.unpack(" float: - return struct.unpack(" int: - return struct.unpack("> 32 - - -_TMP_DIR = None -_SRC_PATH = None - - -def setUpModule(): - global _TMP_DIR, _SRC_PATH - _TMP_DIR = tempfile.TemporaryDirectory() - disasm_dir = os.path.join(_TMP_DIR.name, "disasm") - os.mkdir(disasm_dir) - _SRC_PATH = os.path.join(disasm_dir, "ps_div_fmas.s") - with open(os.path.join(_TMP_DIR.name, "ps_div_fmas.dxbc"), "wb") as f: - f.write(STUB_DXBC) - - -def tearDownModule(): - global _TMP_DIR - if _TMP_DIR is not None: - _TMP_DIR.cleanup() - _TMP_DIR = None - - -def translate_lines(lines): - if _TMP_DIR is None: - setUpModule() - asm = ( - "; test_div_fmas\n" - + "".join(f"\t{ln}\n" for ln in lines) - + "\texp mrt0 v0, v1, v2, v3 done vm\n\ts_endpgm\n" - ) - with open(_SRC_PATH, "w", encoding="utf-8") as f: - f.write(asm) - with warnings.catch_warnings(): - warnings.simplefilter("ignore", ResourceWarning) - return rdna2spirv.translate(_SRC_PATH) - - -def validate_spirv(spv_text: str): - # Always assemble with the in-repo SPIR-V assembler so malformed opcodes/IDs fail everywhere. - binary = spirv_asm.assemble(spv_text) - assert len(binary) >= 20 and binary[:4] == b"\x03\x02\x23\x07" - spirv_as = shutil.which("spirv-as") - spirv_val = shutil.which("spirv-val") - if not spirv_as or not spirv_val: - return - with tempfile.TemporaryDirectory() as d: - asm_p = os.path.join(d, "s.spvasm") - bin_p = os.path.join(d, "s.spv") - with open(asm_p, "w", encoding="utf-8") as f: - f.write(spv_text) - r1 = subprocess.run([spirv_as, "--target-env", "vulkan1.2", asm_p, "-o", bin_p], capture_output=True, text=True) - if r1.returncode != 0: - raise AssertionError(f"spirv-as failed: {r1.stderr}") - r2 = subprocess.run([spirv_val, "--target-env", "vulkan1.2", bin_p], capture_output=True, text=True) - if r2.returncode != 0: - raise AssertionError(f"spirv-val failed: {r2.stderr}") - - -def run_f32_u(ux: int, uy: int, uz: int, vcc: bool, insn: str = "v_div_fmas_f32 v0, v1, v2, v3") -> int: - vcc_set = "v_cmp_eq_u32_e32 vcc_lo, 1, 1" if vcc else "v_cmp_eq_u32_e32 vcc_lo, 0, 1" - spv = translate_lines([ - f"v_mov_b32 v1, {ux & 0xFFFFFFFF:#x}", - f"v_mov_b32 v2, {uy & 0xFFFFFFFF:#x}", - f"v_mov_b32 v3, {uz & 0xFFFFFFFF:#x}", - "v_mov_b32 v0, 0", - vcc_set, - insn, - ]) - return si.run_fragment(spv)["%out_mrt0"][0] - - -def run_f32(x: float, y: float, z: float, vcc: bool, insn: str = "v_div_fmas_f32 v0, v1, v2, v3") -> int: - return run_f32_u(f2u(x), f2u(y), f2u(z), vcc, insn) - - -def _eval_spv_f64_mrt0(spv_text: str): - """Straight-line SSA evaluator for translated %double/%uint/%bool fragment shaders.""" - def u64_to_d(lo, hi): - return struct.unpack("> 32 - - def safe_fma(a, b, c): - # Exact IEEE-754 binary64 FMA compatible with Python 3.12 (math.fma was added in 3.13). - if math.isnan(a) or math.isnan(b) or math.isnan(c): - return float("nan") - if math.isinf(a) or math.isinf(b): - if a == 0.0 or b == 0.0: - return float("nan") - prod_inf = math.copysign(math.inf, math.copysign(1.0, a) * math.copysign(1.0, b)) - if math.isinf(c) and math.copysign(1.0, c) != math.copysign(1.0, prod_inf): - return float("nan") - return prod_inf - if math.isinf(c): - return c - exact = Fraction(a) * Fraction(b) + Fraction(c) - if exact == 0: - prod_neg = (math.copysign(1.0, a) * math.copysign(1.0, b)) < 0.0 - c_neg = math.copysign(1.0, c) < 0.0 - if a * b == 0.0 and c == 0.0 and prod_neg and c_neg: - return -0.0 - return 0.0 - try: - r = float(exact) - except OverflowError: - return -math.inf if exact < 0 else math.inf - return -0.0 if (r == 0.0 and exact < 0) else r - - consts, env, mem = {}, {}, {} - in_fn = False - for raw in spv_text.splitlines(): - line = raw.strip() - if not line or line.startswith(";"): - continue - if line.startswith("%main = OpFunction"): - in_fn = True - continue - if line == "OpFunctionEnd": - in_fn = False - continue - m = re.match(r"^(%\S+)\s*=\s*(\S+)(.*)$", line) - if not in_fn: - if m: - res, op, rest = m.group(1), m.group(2), m.group(3).strip().split() - if op == "OpConstant": - ty, val = rest[0], rest[1] - if ty == "%uint": - consts[res] = int(val) & 0xFFFFFFFF - elif ty == "%int": - consts[res] = int(val) - elif ty == "%float": - consts[res] = float(val) - elif op == "OpConstantTrue": - consts[res] = True - elif op == "OpConstantFalse": - consts[res] = False - elif op == "OpConstantNull": - ty = rest[0] - if ty == "%uint": - consts[res] = 0 - elif ty == "%float": - consts[res] = 0.0 - elif ty == "%bool": - consts[res] = False - else: - consts[res] = (0.0, 0.0, 0.0, 0.0) - elif op == "OpVariable": - consts[res] = res - mem[res] = (0.0, 0.0, 0.0, 0.0) if "v4float" in rest[0] else 0 - continue - if not m: - toks = line.split() - if toks[0] == "OpStore": - dst = env.get(toks[1], consts.get(toks[1], toks[1])) - mem[dst] = env[toks[2]] if toks[2] in env else consts[toks[2]] - continue - res, op, rest = m.group(1), m.group(2), m.group(3).strip().split() - - def get(tok): - return env[tok] if tok in env else consts[tok] - - if op == "OpVariable": - mem[res] = get(rest[2]) if len(rest) >= 3 else (True if res == "%active" else 0) - env[res] = res - elif op == "OpAccessChain": - key = (rest[1], tuple(get(t) for t in rest[2:])) - env[res] = key - mem.setdefault(key, 0) - elif op == "OpLoad": - env[res] = mem.get(get(rest[1]), 0) - elif op == "OpCompositeConstruct": - env[res] = tuple(get(t) for t in rest[1:]) - elif op == "OpCompositeExtract": - env[res] = get(rest[1])[int(rest[2])] - elif op == "OpBitcast": - ty, v = rest[0], get(rest[1]) - if ty == "%double": - env[res] = u64_to_d(v[0], v[1]) - elif ty == "%v2uint_d": - env[res] = d_to_u64(v) - elif ty == "%float": - env[res] = struct.unpack("= 0x80000000 else v - else: - raise NotImplementedError(f"OpBitcast {ty}") - elif op == "OpExtInst": - fn, args = rest[2], [get(t) for t in rest[3:]] - if fn == "FAbs": - env[res] = abs(args[0]) - elif fn == "Fma": - env[res] = safe_fma(args[0], args[1], args[2]) - elif fn == "FClamp": - x, lo, hi = args - env[res] = float("nan") if math.isnan(x) else max(lo, min(hi, x)) - else: - raise NotImplementedError(f"OpExtInst {fn}") - elif op == "OpFNegate": - env[res] = -get(rest[1]) - elif op == "OpFMul": - env[res] = get(rest[1]) * get(rest[2]) - elif op == "OpFAdd": - env[res] = get(rest[1]) + get(rest[2]) - elif op == "OpFSub": - env[res] = get(rest[1]) - get(rest[2]) - elif op == "OpIAdd": - env[res] = (get(rest[1]) + get(rest[2])) & 0xFFFFFFFF - elif op == "OpISub": - env[res] = (get(rest[1]) - get(rest[2])) & 0xFFFFFFFF - elif op == "OpBitwiseAnd": - env[res] = (get(rest[1]) & get(rest[2])) & 0xFFFFFFFF - elif op == "OpBitwiseOr": - env[res] = (get(rest[1]) | get(rest[2])) & 0xFFFFFFFF - elif op == "OpBitwiseXor": - env[res] = (get(rest[1]) ^ get(rest[2])) & 0xFFFFFFFF - elif op == "OpShiftRightLogical": - env[res] = (get(rest[1]) & 0xFFFFFFFF) >> (get(rest[2]) & 31) - elif op == "OpShiftLeftLogical": - env[res] = ((get(rest[1]) & 0xFFFFFFFF) << (get(rest[2]) & 31)) & 0xFFFFFFFF - elif op == "OpIEqual": - env[res] = (get(rest[1]) & 0xFFFFFFFF) == (get(rest[2]) & 0xFFFFFFFF) - elif op == "OpINotEqual": - env[res] = (get(rest[1]) & 0xFFFFFFFF) != (get(rest[2]) & 0xFFFFFFFF) - elif op == "OpUGreaterThan": - env[res] = (get(rest[1]) & 0xFFFFFFFF) > (get(rest[2]) & 0xFFFFFFFF) - elif op == "OpUGreaterThanEqual": - env[res] = (get(rest[1]) & 0xFFFFFFFF) >= (get(rest[2]) & 0xFFFFFFFF) - elif op == "OpULessThan": - env[res] = (get(rest[1]) & 0xFFFFFFFF) < (get(rest[2]) & 0xFFFFFFFF) - elif op == "OpULessThanEqual": - env[res] = (get(rest[1]) & 0xFFFFFFFF) <= (get(rest[2]) & 0xFFFFFFFF) - elif op == "OpFOrdGreaterThanEqual": - a, b = get(rest[1]), get(rest[2]) - env[res] = (not math.isnan(a)) and (not math.isnan(b)) and (a >= b) - elif op == "OpFOrdGreaterThan": - a, b = get(rest[1]), get(rest[2]) - env[res] = (not math.isnan(a)) and (not math.isnan(b)) and (a > b) - elif op == "OpFOrdLessThan": - a, b = get(rest[1]), get(rest[2]) - env[res] = (not math.isnan(a)) and (not math.isnan(b)) and (a < b) - elif op == "OpFOrdEqual": - a, b = get(rest[1]), get(rest[2]) - env[res] = (not math.isnan(a)) and (not math.isnan(b)) and (a == b) - elif op == "OpFOrdNotEqual": - a, b = get(rest[1]), get(rest[2]) - env[res] = (not math.isnan(a)) and (not math.isnan(b)) and (a != b) - elif op == "OpLogicalAnd": - env[res] = bool(get(rest[1])) and bool(get(rest[2])) - elif op == "OpLogicalOr": - env[res] = bool(get(rest[1])) or bool(get(rest[2])) - elif op == "OpLogicalNot": - env[res] = not bool(get(rest[1])) - elif op == "OpLogicalEqual": - env[res] = bool(get(rest[1])) == bool(get(rest[2])) - elif op == "OpSelect": - env[res] = get(rest[2]) if get(rest[1]) else get(rest[3]) - elif op == "OpCopyObject": - env[res] = get(rest[1]) - elif op in ("OpLabel", "OpFunctionParameter"): - pass - else: - raise NotImplementedError(f"Unhandled SPIR-V op: {op} ({line})") - return [struct.unpack(" int: - vcc_set = "v_cmp_eq_u32_e32 vcc_lo, 1, 1" if vcc else "v_cmp_eq_u32_e32 vcc_lo, 0, 1" - spv = translate_lines([ - f"v_mov_b32 v2, {ux & 0xFFFFFFFF:#x}", - f"v_mov_b32 v3, {(ux >> 32) & 0xFFFFFFFF:#x}", - f"v_mov_b32 v4, {uy & 0xFFFFFFFF:#x}", - f"v_mov_b32 v5, {(uy >> 32) & 0xFFFFFFFF:#x}", - f"v_mov_b32 v6, {uz & 0xFFFFFFFF:#x}", - f"v_mov_b32 v7, {(uz >> 32) & 0xFFFFFFFF:#x}", - "v_mov_b32 v0, 0", - "v_mov_b32 v1, 0", - vcc_set, - insn, - ]) - mrt0 = _eval_spv_f64_mrt0(spv) - return ((mrt0[1] & 0xFFFFFFFF) << 32) | (mrt0[0] & 0xFFFFFFFF) - - -class DivFmasF32Tests(unittest.TestCase): - def test_vcc_clear_and_s2_exponent_threshold(self): - # Measured on gfx1036: VCC=1 scales by 2^+64 when exp(S2) > 127 (|S2| >= 2.0), else 2^-64. - cases = ( - (f2u(1.5), f2u(2.0), f2u(0.5), 0x40600000, 0x20600000), # |S2|=0.5 < 2.0 -> 3.5 * 2^-64 - (f2u(1.0), f2u(2.0), f2u(1.0), 0x40400000, 0x20400000), # |S2|=1.0 (exp=127) -> 3.0 * 2^-64 - (0, 0, 0x3FFFFFFF, 0x3FFFFFFF, 0x1FFFFFFF), # nextbelow(2.0) (exp=127) -> * 2^-64 - (0, 0, 0x40000000, 0x40000000, 0x60000000), # 2.0 (exp=128) -> * 2^+64 - (0, 0, 0xBFFFFFFF, 0xBFFFFFFF, 0x9FFFFFFF), # -nextbelow(2.0) (exp=127) -> * 2^-64 - (0, 0, 0xC0000000, 0xC0000000, 0xE0000000), # -2.0 (exp=128) -> * 2^+64 - (f2u(1.0), f2u(2.0), f2u(2.0), 0x40800000, 0x60800000), # |S2|=2.0 -> 4.0 * 2^+64 - (f2u(1.0), f2u(2.0), f2u(-4.0), 0xC0000000, 0xE0000000), # |S2|=4.0 -> -2.0 * 2^+64 - ) - for ux, uy, uz, want0, want1 in cases: - with self.subTest(uz=hex(uz)): - self.assertEqual(run_f32_u(ux, uy, uz, False), want0) - self.assertEqual(run_f32_u(ux, uy, uz, True), want1) - - def test_overflow_prevention_and_sticky_bit(self): - # Scale-down prevents intermediate product overflow (measured on gfx1036). - self.assertEqual(run_f32(2.0 ** 80, 2.0 ** 80, 0.5, False), 0x7F800000) - self.assertEqual(run_f32(2.0 ** 80, 2.0 ** 80, 0.5, True), 0x6F800000) # 2^96 - self.assertEqual(run_f32(2.0 ** 120, 2.0 ** 20, 1.0, True), 0x65800000) # 2^76 - # Exact cancellation and mixed-magnitude scale-up (no premature pre-scale overflow). - self.assertEqual(run_f32(2.0 ** 80, -(2.0 ** -10), 2.0 ** 70, True), 0x00000000) - self.assertEqual(run_f32(2.0 ** -50, 2.0 ** 100, 2.0, True), 0x78800000) # 2^114 - # Scale-up overflow to +/-inf. - self.assertEqual(run_f32(2.0 ** 50, 2.0 ** 50, 2.0 ** 50, True), 0x7F800000) - self.assertEqual(run_f32(-(2.0 ** 50), 2.0 ** 50, 2.0 ** 50, True), 0xFF800000) - # Half-ULP tie breaking when z*2^-64 underflows normal range (including subnormal z). - fx = f2u(2.0 ** 120 * (1.0 + 3.0 * 2.0 ** -23)) - fy = f2u(2.0 ** 20 * 1.5) - self.assertEqual(run_f32_u(fx, fy, 0, True), 0x65C00004) - self.assertEqual(run_f32_u(fx, fy, f2u(2.0 ** -100), True), 0x65C00005) - self.assertEqual(run_f32_u(fx, fy, 0x00000010, True), 0x65C00005) - self.assertEqual(run_f32_u(fx, fy, f2u(-(2.0 ** -100)), True), 0x65C00004) - - def test_denormal_inputs_kept_and_output_flushed_denorm32_0(self): - # Measured on gfx1036 under game MODE (denorm32=0): subnormal inputs/intermediates are kept, - # while subnormal outputs flush to signed zero before and after omod. - self.assertEqual(run_f32_u(0x00080000, f2u(2.0 ** 80), 0, False), 0x26800000) # 2^-130 * 2^80 = 2^-50 - self.assertEqual(run_f32_u(0x00080000, f2u(1.0), 0, False), 0x00000000) # flushed output - self.assertEqual(run_f32(2.0 ** -70, 2.0 ** -70, 2.0 ** -126, False), 0x00800200) - self.assertEqual(run_f32(2.0 ** -40, 2.0 ** -40, 0.0, True), 0x00000000) # 2^-144 -> flushed - self.assertEqual(run_f32(2.0 ** -31, 2.0 ** -31, 0.0, True), 0x00800000) # 2^-126 -> min normal - # Signed zero preserved on flush/scale. - self.assertEqual(run_f32_u(0x80000000, f2u(1.0), 0x80000000, True), 0x80000000) - # Flush applies before mul:2 and after div:2. - self.assertEqual(run_f32_u(0x00400000, f2u(1.0), 0, False, "v_div_fmas_f32 v0, v1, v2, v3 mul:2"), 0) - self.assertEqual(run_f32_u(0x00800000, f2u(1.0), 0, False, "v_div_fmas_f32 v0, v1, v2, v3 div:2"), 0) - - def test_input_and_output_modifiers(self): - self.assertEqual(run_f32(-2.0, 1.5, 4.0, False, "v_div_fmas_f32 v0, |v1|, -v2, v3"), f2u(1.0)) - self.assertEqual(run_f32(-2.0, 1.5, 4.0, False, "v_div_fmas_f32 v0, |v1|, -v2, v3 mul:2"), f2u(2.0)) - self.assertEqual(run_f32(-2.0, 1.5, 4.0, False, "v_div_fmas_f32 v0, |v1|, -v2, v3 mul:2 clamp"), f2u(1.0)) - self.assertEqual(run_f32(1.0, 2.0, 2.0, True, "v_div_fmas_f32 v0, v1, v2, v3 mul:2"), 0x61000000) - self.assertEqual(run_f32(1.0, 2.0, 2.0, True, "v_div_fmas_f32 v0, v1, v2, v3 div:2"), 0x60000000) - self.assertEqual(run_f32(2.0 ** 64, 1.0, 2.0, True, "v_div_fmas_f32 v0, v1, v2, v3 div:2"), 0x7F800000) - - def test_spirv_val(self): - spv = translate_lines([ - "v_mov_b32 v1, 0x3fc00000", - "v_mov_b32 v2, 0x40000000", - "v_mov_b32 v3, 0x3f000000", - "v_cmp_eq_u32_e32 vcc_lo, 1, 1", - "v_div_fmas_f32 v0, |v1|, -v2, v3 clamp div:2", - ]) - self.assertNotIn("OpCapability Float64", spv) - validate_spirv(spv) - - -class DivFmasF64Tests(unittest.TestCase): - def test_vcc_clear_and_s2_exponent_threshold(self): - # Measured on gfx1036 (wave32 and wave64): VCC=1 scales by 2^+128 when exp(S2) > 1023, else 2^-128. - cases = ( - (d2u(1.0), d2u(2.0), d2u(1.0), 0x4008000000000000, 0x3808000000000000), - (0, 0, 0x3FFFFFFFFFFFFFFF, 0x3FFFFFFFFFFFFFFF, 0x37FFFFFFFFFFFFFF), - (0, 0, 0x4000000000000000, 0x4000000000000000, 0x4800000000000000), - (0, 0, 0xBFFFFFFFFFFFFFFF, 0xBFFFFFFFFFFFFFFF, 0xB7FFFFFFFFFFFFFF), - (0, 0, 0xC000000000000000, 0xC000000000000000, 0xC800000000000000), - (d2u(1.0), d2u(2.0), d2u(2.0), 0x4010000000000000, 0x4810000000000000), - ) - for ux, uy, uz, want0, want1 in cases: - with self.subTest(uz=hex(uz)): - self.assertEqual(run_f64_u(ux, uy, uz, False), want0) - self.assertEqual(run_f64_u(ux, uy, uz, True), want1) - - def test_overflow_prevention_sticky_and_subnormal_single_rounding(self): - # All expected 64-bit words measured natively on gfx1036. - self.assertEqual(run_f64_u(d2u(2.0 ** 530), d2u(2.0 ** 530), d2u(0.5), False), 0x7FF0000000000000) - self.assertEqual(run_f64_u(d2u(2.0 ** 530), d2u(2.0 ** 530), d2u(0.5), True), 0x7A30000000000000) - self.assertEqual(run_f64_u(d2u(2.0 ** 1000), d2u(2.0 ** 100), d2u(1.0), True), 0x7CB0000000000000) - self.assertEqual(run_f64_u(d2u(2.0 ** 600), d2u(-(2.0 ** 350)), d2u(2.0 ** 950), True), 0x0000000000000000) - self.assertEqual(run_f64_u(d2u(2.0 ** -500), d2u(2.0 ** 900), d2u(2.0), True), 0x60F0000000000000) - # Single-rounded subnormal half-ULP ties (double rounding gives 0x...0000 and 0x...0002 instead of 0x...0001). - x1 = d2u(2.0 ** -450) - y1 = d2u(2.0 ** -450 * (1.0 + 2.0 ** -47)) - y2 = d2u(2.0 ** -450 * (1.0 + 2.0 ** -46 + 2.0 ** -47)) - self.assertEqual(run_f64_u(x1, y1, d2u(2.0 ** -953), True), 0x0000400000000001) - self.assertEqual(run_f64_u(x1, y1, 0, True), 0x0000400000000000) - self.assertEqual(run_f64_u(x1, y2, d2u(-(2.0 ** -953)), True), 0x0000400000000001) - self.assertEqual(run_f64_u(x1, y2, 0, True), 0x0000400000000002) - # Half-of-min-subnormal boundary (2^-947 * 2^-128 = 2^-1075) and tiny product sticky bit. - self.assertEqual(run_f64_u(d2u(2.0 ** -473), d2u(2.0 ** -474), d2u(2.0 ** -1074), True), 0x0000000000000001) - self.assertEqual(run_f64_u(d2u(2.0 ** -473), d2u(2.0 ** -474), d2u(-(2.0 ** -1074)), True), 0x0000000000000000) - self.assertEqual(run_f64_u(d2u(2.0 ** -600), d2u(2.0 ** -600), d2u(2.0 ** -947), True), 0x0000000000000001) - self.assertEqual(run_f64_u(d2u(-(2.0 ** -600)), d2u(2.0 ** -600), d2u(2.0 ** -947), True), 0x0000000000000000) - # k=52 boundary (2^-895 * (1 + 2^-52) * 2^-128 = 2^-1023 + 2^-1075). - xa = d2u(2.0 ** -447) - ya = d2u(2.0 ** -448 * (1.0 + 2.0 ** -52)) - self.assertEqual(run_f64_u(xa, ya, d2u(2.0 ** -1000), True), 0x0008000000000001) - self.assertEqual(run_f64_u(xa, ya, d2u(-(2.0 ** -1000)), True), 0x0008000000000000) - # big_prod sticky bit in f64. - bx = d2u(2.0 ** 900 * (1.0 + 3.0 * 2.0 ** -52)) - by = d2u(2.0 ** 150 * 1.5) - self.assertEqual(run_f64_u(bx, by, 0, True), 0x7998000000000004) - self.assertEqual(run_f64_u(bx, by, d2u(2.0 ** -950), True), 0x7998000000000005) - self.assertEqual(run_f64_u(bx, by, d2u(-(2.0 ** -950)), True), 0x7998000000000004) - - def test_f64_lowering_modifiers_and_validation(self): - up_lo, up_hi = dwords(2.0 ** 128) - dn_lo, dn_hi = dwords(2.0 ** -128) - for mods, want_clamp in ( - ("", False), - ("mul:2", False), - ("div:2", False), - ("clamp", True), - ("mul:4 clamp", True), - ): - with self.subTest(mods=mods): - spv = translate_lines([ - "v_mov_b32 v2, 0", - "v_mov_b32 v3, 0x3ff80000", - "s_mov_b32 s4, 0", - "s_mov_b32 s5, 0x40000000", - "v_cmp_eq_u32_e32 vcc_lo, 1, 1", - f"v_div_fmas_f64 v[0:1], |v[2:3]|, -s[4:5], 0.5 {mods}".rstrip(), - ]) - self.assertIn("OpCapability Float64", spv) - self.assertNotIn("OpCapability Int64", spv) - self.assertRegex(spv, r"OpExtInst %double %glsl Fma %\w+ %\w+ %\w+") - self.assertRegex(spv, r"OpExtInst %double %glsl FAbs %\w+") - self.assertRegex(spv, r"OpFNegate %double %\w+") - self.assertIn(f"OpConstant %uint {up_hi}", spv) - self.assertIn(f"OpConstant %uint {up_lo}", spv) - self.assertIn(f"OpConstant %uint {dn_hi}", spv) - self.assertIn(f"OpConstant %uint {dn_lo}", spv) - if want_clamp: - self.assertIn("FClamp", spv) - else: - self.assertNotIn("FClamp", spv) - validate_spirv(spv) - - def test_f64_rejects_non_pair_destination(self): - with self.assertRaises(rdna2spirv.Unsupported): - translate_lines(["v_div_fmas_f64 v0, v[2:3], v[4:5], v[6:7]"]) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_alu_dot2_f16_unsupported.py b/tests/semantic/test_alu_dot2_f16_unsupported.py deleted file mode 100644 index 9bce02ea7..000000000 --- a/tests/semantic/test_alu_dot2_f16_unsupported.py +++ /dev/null @@ -1,75 +0,0 @@ -"""`v_dot2_f16_f16` and `v_dot2acc_f16_f16` are refused, not translated. - -Scope, measured with llvm-mc (AOMP 16.0-45 / LLVM 17.0.0git, `-arch=amdgcn`, four-operand -VOP3P form): - - | instruction | gfx1100 | gfx1030 | gfx1013 | - |---------------------|--------------------|---------------------------|---------------------------| - | `v_dot2_f16_f16` | encodes | not supported on this GPU | not supported on this GPU | - | `v_dot2acc_f16_f16` | invalid instruction| invalid instruction | invalid instruction | - | `v_dot2c_f16_f16` | invalid instruction| invalid instruction | invalid instruction | - -The packed half-precision dot product therefore exists on GFX11 only: it is not part of the -GFX10/RDNA2 VALU this project translates, and the accumulating spellings do not assemble at -all. The translator has to refuse them rather than invent a lowering, and that refusal is -what this file pins. `docs/design.md` carries no row for them; the packed-integer dot -products (`v_dot2_i32_i16`, `v_dot2c_i32_i16`, ...) are different instructions with their own -rows. - -This file replaces `tests/semantic/test_alu_dot2_f16.py`, which built its own SPIR-V with its -own reference oracle and executed that in `spirv_mini_interp`: no line of it went through -`rdna2spirv`, so nothing in it could fail when the translator changed (TEST-603), and its -docstring attributed the instruction to the RDNA2/GFX10 ISA. The sibling -`tests/semantic/test_alu_dot2acc_f16.py` is the same class and is removed by #3098. - -Standard library only, no game data, no GPU. -""" - -import os -import sys -import unittest - -HERE = os.path.dirname(os.path.abspath(__file__)) -ROOT = os.path.dirname(os.path.dirname(HERE)) -TOOLS_DIR = os.environ.get("LEONIDA_TOOLS_DIR") or os.path.join(ROOT, "tools") - -for path in (ROOT, TOOLS_DIR, HERE): - if path not in sys.path: - sys.path.insert(0, path) - -import rdna2spirv # noqa: E402 -import support # noqa: E402 - -DOT2 = [ - "v_mov_b32 v1, 0x3c003c00", - "v_mov_b32 v2, 0x40004000", - "v_dot2_f16_f16 v0, v1, v2", - "exp mrt0 v0, v0, v0, v0 done vm", - "s_endpgm", -] - -DOT2ACC = [ - "v_mov_b32 v1, 0x3c003c00", - "v_mov_b32 v2, 0x40004000", - "v_mov_b32 v3, 0", - "v_dot2acc_f16_f16 v0, v1, v2, v3", - "exp mrt0 v0, v0, v0, v0 done vm", - "s_endpgm", -] - - -class Dot2Unsupported(unittest.TestCase): - def assert_refused(self, name, lines, instruction): - with self.assertRaises(rdna2spirv.Unsupported) as caught: - support.translate_lines(name, lines) - self.assertIn(instruction, str(caught.exception)) - - def test_the_packed_half_dot_product_is_refused(self): - self.assert_refused("ps_dot2_unsupported", DOT2, "v_dot2_f16_f16") - - def test_the_accumulating_spelling_is_refused(self): - self.assert_refused("ps_dot2acc_unsupported", DOT2ACC, "v_dot2acc_f16_f16") - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_alu_dot4_i8.py b/tests/semantic/test_alu_dot4_i8.py deleted file mode 100644 index 23c73bdaa..000000000 --- a/tests/semantic/test_alu_dot4_i8.py +++ /dev/null @@ -1,243 +0,0 @@ -"""v_dot4_i32_i8 and v_dot4c_i32_i8: the dot product of the signed bytes of two dwords, plus an addend. - -ISA rule (RDNA2): D = S0.b0*S1.b0 + S0.b1*S1.b1 + S0.b2*S1.b2 + S0.b3*S1.b3 + addend, every byte sign-extended, the -sum kept modulo 2^32. The addend is the third source for v_dot4_i32_i8 (VOP3P) and the old value of the destination -for v_dot4c_i32_i8 (VOP2). The 29 FSPX programs of the package's upscaler DLL (docs/fspx.md) use the pair 27,271 -times. - -The expected words below were measured on RDNA2 hardware (gfx1036, the integrated GPU of a Ryzen 9 7950X3D, through -tools/hw_oracle): each case ran `v_dot4_i32_i8 v8, v1, v2, v3`, `v_dot4c_i32_i8 v10, v1, v2` with v10 holding the -addend, and the same with the two sources swapped. All three gave the word in the table, which the plain-Python -reference `ref` reproduces. With `clamp` the hardware saturates v_dot4_i32_i8 to a signed 32-bit value -(0x7fffffff and 0x80000000 in the two overflowing cases); the translator refuses that form. - -op_sel. The plain instruction has op_sel 0 and op_sel_hi 7. 89 words in 8 of those programs are v_dot4_i32_i8 with -op_sel 2 and op_sel_hi 5, which llvm-mc does not decode (docs/fspx.md). Run on the same hardware as two raw words -(0xCC165008 0x0C0E0501: v8 = v1 . v2 + v3 with those fields), that form gave the words of MEASURED_OP_SEL: the dot -product with the two 16-bit halves of the second source exchanged, as op_sel selects halves for the packed 16-bit -ops. `ref_op_sel` reproduces them; the translator refuses any op_sel on these two instructions until a listing can -carry it. - -neg_lo and neg_hi. llvm-mc accepts them on v_dot4_i32_i8 for gfx1036 (not on v_dot4c_i32_i8), and the hardware does -not ignore them: on the same GPU, 5 operand sets with 8 forms each gave the words of `ref_neg`, 9 of which are in -MEASURED_NEG. For S0 and S1, neg_lo flips bit 15 and neg_hi flips bit 31 of the dword; for the addend, neg_hi clears -bit 31 and neg_lo then flips it. That is what the fields do to float operands, applied to integer ones. The -translator refuses a set bit and takes an all-zero field as the plain instruction. - - python -m unittest discover -s tests/semantic -p test_alu_dot4_i8.py -""" -import os -import sys -import unittest - -HERE = os.path.dirname(os.path.abspath(__file__)) -if HERE not in sys.path: - sys.path.insert(0, HERE) - -import support # noqa: E402 - -rdna2spirv = support.rdna2spirv - -# (S0, S1, addend, result measured on gfx1036) -MEASURED = [ - (0x01020304, 0x05060708, 0x00000000, 0x00000046), # 4*8 + 3*7 + 2*6 + 1*5 = 70 - (0x01020304, 0x05060708, 0x000003E8, 0x0000042E), # 70 + 1000 - (0xFF80017F, 0x7F7F80FF, 0x00000000, 0xFFFFBF02), # 127*-1 + 1*-128 + -128*127 + -1*127 = -16638 - (0xFF80017F, 0x7F7F80FF, 0x00010000, 0x0000BF02), - (0x80808080, 0x80808080, 0x00000000, 0x00010000), # 4 * (-128 * -128) - (0x80808080, 0x7F7F7F7F, 0x00000005, 0xFFFF0205), # 4 * (-128 * 127) + 5 - (0x7F7F7F7F, 0x7F7F7F7F, 0x7FFFFFFF, 0x8000FC03), # wraps upward: no saturation without clamp - (0x80808080, 0x7F7F7F7F, 0x80000000, 0x7FFF0200), # wraps downward - (0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0x00000003), # 4 * (-1 * -1) - 1 - (0x00000000, 0x12345678, 0xDEADBEEF, 0xDEADBEEF), -] - - -# (S0, S1, addend, result measured on gfx1036 with op_sel 2 and op_sel_hi 5) -MEASURED_OP_SEL = [ - (0x04030201, 0x08070605, 0x00000000, 62), # the plain form gives 70 - (0x04030201, 0x08070605, 0x000003E8, 1062), - (0x7F01FE80, 0x02FD7F81, 0x00000000, 16382), # the plain form gives 16253 - (0x11223344, 0x55667788, 0x00010000, 74750), # the plain form gives 68358 - (0xFFFFFFFF, 0x01020304, 0x00000007, 0xFFFFFFFD), # every byte of S0 the same: the order cannot show -] - - -# (neg_lo, neg_hi, S0, S1, addend, result measured on gfx1036), one operand set under every form that was run -MEASURED_NEG = [ - ((0, 0, 0), (0, 0, 0), 0x04030201, 0x08070605, 0x00000064, 0x000000AA), # plain: 70 + 100 - ((1, 0, 0), (0, 0, 0), 0x04030201, 0x08070605, 0x00000064, 0xFFFFFDAA), # S0 byte 1 reads as 0x82 - ((0, 0, 0), (1, 0, 0), 0x04030201, 0x08070605, 0x00000064, 0xFFFFFCAA), # S0 byte 3 reads as 0x84 - ((0, 1, 0), (0, 0, 0), 0x04030201, 0x08070605, 0x00000064, 0xFFFFFFAA), # S1 byte 1 reads as 0x86 - ((0, 0, 0), (0, 1, 0), 0x04030201, 0x08070605, 0x00000064, 0xFFFFFEAA), # S1 byte 3 reads as 0x88 - ((0, 0, 1), (0, 0, 0), 0x04030201, 0x08070605, 0x00000064, 0x800000AA), # the addend's bit 31 flipped - ((0, 0, 0), (0, 0, 1), 0x04030201, 0x08070605, 0x00000064, 0x000000AA), # abs of a positive addend - ((0, 0, 1), (0, 0, 1), 0x04030201, 0x08070605, 0x00000064, 0x800000AA), # abs, then negated - ((1, 1, 1), (1, 1, 1), 0x04030201, 0x08070605, 0x00000064, 0x800076AA), -] - - -def ref(a, b, addend): - def s8(x): - return x - 256 if x & 0x80 else x - total = sum(s8((a >> (8 * i)) & 0xFF) * s8((b >> (8 * i)) & 0xFF) for i in range(4)) - return (total + addend) & 0xFFFFFFFF - - -def ref_neg(neg_lo, neg_hi, a, b, addend): - """neg_lo[k] flips bit 15 and neg_hi[k] bit 31 of source k; the addend loses bit 31 under neg_hi[2] and has it - flipped under neg_lo[2], in that order.""" - a ^= (0x8000 if neg_lo[0] else 0) ^ (0x80000000 if neg_hi[0] else 0) - b ^= (0x8000 if neg_lo[1] else 0) ^ (0x80000000 if neg_hi[1] else 0) - if neg_hi[2]: - addend &= 0x7FFFFFFF - if neg_lo[2]: - addend ^= 0x80000000 - return ref(a, b, addend) - - -def ref_op_sel(a, b, addend): - """op_sel 2, op_sel_hi 5: the low half of the product reads the high half of S1 and the high half its low half.""" - return ref(a, (b & 0xFFFF) << 16 | b >> 16, addend) - - -def program(a, b, addend): - """mrt0 = (v_dot4_i32_i8, v_dot4c_i32_i8, v_dot4c_i32_i8 with the sources swapped, v_dot4_i32_i8 with the - sources and the addend taken from SGPRs and a literal, as the shaders do).""" - return [ - f"v_mov_b32_e32 v1, 0x{a:08x}", - f"v_mov_b32_e32 v2, 0x{b:08x}", - f"v_mov_b32_e32 v3, 0x{addend:08x}", - f"s_mov_b32 s4, 0x{addend:08x}", - "v_dot4_i32_i8 v8, v1, v2, v3", - f"v_mov_b32_e32 v9, 0x{addend:08x}", - "v_dot4c_i32_i8 v9, v1, v2", - f"v_mov_b32_e32 v10, 0x{addend:08x}", - "v_dot4c_i32_i8 v10, v2, v1", - f"v_dot4_i32_i8 v11, v1, 0x{b:08x}, s4", - "exp mrt0 v8, v9, v10, v11 done vm", - "s_endpgm", - ] - - -class Dot4I8(unittest.TestCase): - def test_the_reference_reproduces_the_hardware_words(self): - for a, b, addend, measured in MEASURED: - self.assertEqual(ref(a, b, addend), measured, f"{a:#x} . {b:#x} + {addend:#x}") - - def test_both_forms_give_the_hardware_words(self): - for a, b, addend, measured in MEASURED: - with self.subTest(a=f"{a:#010x}", b=f"{b:#010x}", addend=f"{addend:#010x}"): - spv = support.translate_lines("ps_dot4_i8", program(a, b, addend)) - self.assertEqual(support.mrt0_words(spv), [measured] * 4) - - def test_the_accumulating_form_reads_its_destination(self): - # v9 is never written before v_dot4c reads it: the old value is then the register's initial 0, not garbage - # from an expression that dropped the addend. 70 is the dot product alone. - lines = ["v_mov_b32_e32 v1, 0x01020304", "v_mov_b32_e32 v2, 0x05060708", "v_dot4c_i32_i8 v9, v1, v2", - "v_dot4c_i32_i8 v9, v1, v2", "exp mrt0 v9, v9, v9, v9 done vm", "s_endpgm"] - self.assertEqual(support.mrt0_words(support.translate_lines("ps_dot4c_twice", lines)), [140] * 4) - - def test_the_bytes_are_signed(self): - # 0xff * 0x01: -1 as a signed byte, 255 as an unsigned one. - lines = ["v_mov_b32_e32 v1, 0x000000ff", "v_mov_b32_e32 v2, 0x00000001", "v_mov_b32_e32 v3, 0", - "v_dot4_i32_i8 v8, v1, v2, v3", "exp mrt0 v8, v8, v8, v8 done vm", "s_endpgm"] - self.assertEqual(support.mrt0_words(support.translate_lines("ps_dot4_signed", lines)), [0xFFFFFFFF] * 4) - - def test_the_op_sel_reference_reproduces_the_hardware_words(self): - for a, b, addend, measured in MEASURED_OP_SEL: - self.assertEqual(ref_op_sel(a, b, addend), measured, f"{a:#x} . {b:#x} + {addend:#x}") - # The table can tell the two readings apart: the plain rule gives another word in four of the five cases. - self.assertEqual(sum(ref(a, b, c) != m for a, b, c, m in MEASURED_OP_SEL), 4) - - def test_op_sel_matches_hardware_words(self): - for a, b, addend, measured in MEASURED_OP_SEL: - with self.subTest(a=f"{a:#010x}", b=f"{b:#010x}", addend=f"{addend:#010x}"): - lines = [ - f"v_mov_b32_e32 v1, 0x{a:08x}", - f"v_mov_b32_e32 v2, 0x{b:08x}", - f"v_mov_b32_e32 v3, 0x{addend:08x}", - "v_dot4_i32_i8 v8, v1, v2, v3 op_sel:[0,1,0] op_sel_hi:[1,0,1]", - "exp mrt0 v8, v8, v8, v8 done vm", - "s_endpgm", - ] - spv = support.translate_lines("ps_dot4_op_sel", lines) - self.assertEqual(support.mrt0_words(spv), [measured] * 4) - - def test_the_neg_reference_reproduces_the_hardware_words(self): - for neg_lo, neg_hi, a, b, addend, measured in MEASURED_NEG: - self.assertEqual(ref_neg(neg_lo, neg_hi, a, b, addend), measured, f"neg_lo {neg_lo} neg_hi {neg_hi}") - # The fields are not ignored: seven of the eight forms give another word than the plain instruction (the - # eighth takes the absolute value of an addend that is positive already). - plain = MEASURED_NEG[0][5] - self.assertEqual(sum(m != plain for *_, m in MEASURED_NEG[1:]), 7) - - def test_a_set_neg_bit_is_refused(self): - for field in ("neg_lo:[1,0,0]", "neg_hi:[0,1,0]", "neg_lo:[0,0,1] neg_hi:[0,0,1]"): - with self.subTest(field=field): - lines = ["v_mov_b32_e32 v1, 1", "v_mov_b32_e32 v2, 1", "v_mov_b32_e32 v3, 0", - f"v_dot4_i32_i8 v8, v1, v2, v3 {field}", "exp mrt0 v8, v8, v8, v8 done vm", "s_endpgm"] - with self.assertRaises(rdna2spirv.Unsupported) as refused: - support.translate_lines("ps_dot4_neg", lines) - self.assertEqual(str(refused.exception), "v_dot4_i32_i8 neg") - - def test_an_all_zero_neg_field_is_the_plain_instruction(self): - lines = ["v_mov_b32_e32 v1, 0x04030201", "v_mov_b32_e32 v2, 0x08070605", "v_mov_b32_e32 v3, 0x64", - "v_dot4_i32_i8 v8, v1, v2, v3 neg_lo:[0,0,0] neg_hi:[0,0,0]", - "exp mrt0 v8, v8, v8, v8 done vm", "s_endpgm"] - self.assertEqual(support.mrt0_words(support.translate_lines("ps_dot4_neg_zero", lines)), [0xAA] * 4) - - def test_op_sel_source0_swap_and_broadcast(self): - # Swapping S0's halves instead of S1's gives the same result when sources are swapped. - a, b, addend, measured = MEASURED_OP_SEL[0] - lines = [ - f"v_mov_b32_e32 v1, 0x{b:08x}", - f"v_mov_b32_e32 v2, 0x{a:08x}", - f"v_mov_b32_e32 v3, 0x{addend:08x}", - "v_dot4_i32_i8 v8, v1, v2, v3 op_sel:[1,0,0] op_sel_hi:[0,1,1]", - # Broadcast low half of both S0 and S1 into both halves: 2 * (b0*s1_b0 + b1*s1_b1) - "v_dot4_i32_i8 v9, v2, v1, v3 op_sel:[0,0,0] op_sel_hi:[0,0,1]", - "exp mrt0 v8, v9, v8, v9 done vm", - "s_endpgm", - ] - spv = support.translate_lines("ps_dot4_op_sel_s0", lines) - # a=0x04030201 (lo=0x0201: bytes 1,2), b=0x08070605 (lo=0x0605: bytes 5,6) -> 2*(1*5 + 2*6) = 34 - self.assertEqual(support.mrt0_words(spv), [measured, 34, measured, 34]) - - def test_clamp_matches_hardware_saturation(self): - # The two overflowing hardware cases (gfx1036) saturate to 0x7FFFFFFF / 0x80000000; non-overflowing cases stay exact. - cases = [ - (0x7F7F7F7F, 0x7F7F7F7F, 0x7FFFFFFF, 0x7FFFFFFF), # positive overflow -> INT32_MAX - (0x80808080, 0x7F7F7F7F, 0x80000000, 0x80000000), # negative overflow -> INT32_MIN - (0x01020304, 0x05060708, 0x000003E8, 0x0000042E), # positive non-overflow - (0xFF80017F, 0x7F7F80FF, 0x00000000, 0xFFFFBF02), # negative non-overflow - (0x7F7F7F7F, 0x7F7F7F7F, 0x80000000, (0x80000000 + 4 * 127 * 127) & 0xFFFFFFFF), # opposite signs, no ov - ] - for a, b, addend, expected in cases: - with self.subTest(a=f"{a:#010x}", b=f"{b:#010x}", addend=f"{addend:#010x}"): - lines = [ - f"v_mov_b32_e32 v1, 0x{a:08x}", - f"v_mov_b32_e32 v2, 0x{b:08x}", - f"v_mov_b32_e32 v3, 0x{addend:08x}", - "v_dot4_i32_i8 v8, v1, v2, v3 clamp", - "exp mrt0 v8, v8, v8, v8 done vm", - "s_endpgm", - ] - spv = support.translate_lines("ps_dot4_clamp", lines) - self.assertEqual(support.mrt0_words(spv), [expected] * 4) - - def test_unsupported_modifiers_refused(self): - # Non-default S2 half selection on v_dot4_i32_i8 and clamp/op_sel on VOP2 v_dot4c_i32_i8 stay refused. - for name, inst, err in ( - ("ps_dot4_s2_opsel", "v_dot4_i32_i8 v8, v1, v2, v3 op_sel:[0,0,1]", "v_dot4_i32_i8 op_sel"), - ("ps_dot4c_clamp", "v_dot4c_i32_i8 v8, v1, v2 clamp", "v_dot4c_i32_i8 clamp"), - ): - lines = ["v_mov_b32_e32 v1, 1", "v_mov_b32_e32 v2, 1", "v_mov_b32_e32 v3, 0", - inst, "exp mrt0 v8, v8, v8, v8 done vm", "s_endpgm"] - with self.assertRaises(rdna2spirv.Unsupported) as refused: - support.translate_lines(name, lines) - self.assertEqual(str(refused.exception), err) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_alu_dot4_u8.py b/tests/semantic/test_alu_dot4_u8.py deleted file mode 100644 index 8cc2b2977..000000000 --- a/tests/semantic/test_alu_dot4_u8.py +++ /dev/null @@ -1,819 +0,0 @@ -from __future__ import annotations - -"""Semantic interpreter tests for RDNA2 unsigned 8-bit integer dot products. - -Covers: - - v_dot4_u32_u8 (VOP3/VOP3P): D = sum(S0[i] * S1[i] for i in 0..3) + S2 - - v_dot4acc_u32_u8 / v_dot4c_u32_u8: accumulating forms where an accumulator - is added to the sum of four 8-bit unsigned products, kept modulo 2^32. - -ISA rule (RDNA2): - Each 32-bit dword S0 and S1 contains four packed unsigned 8-bit integers: - Byte 0: bits [7:0] - Byte 1: bits [15:8] - Byte 2: bits [23:16] - Byte 3: bits [31:24] - Each byte product S0[i] * S1[i] produces an unsigned integer in [0, 65025]. - The four products sum to [0, 260100], which is added to a 32-bit accumulator S2. - Arithmetic wraps modulo 2^32 without saturation unless clamping is requested. - With clamp, the hardware saturates to 0xFFFFFFFF (unsupported by translator). - -Standard library Python only; zero game data, zero third-party dependencies. -Python 3.9+ compatible. -""" - -import contextlib -import os -import random -import struct -import sys -import unittest - -HERE = os.path.dirname(os.path.abspath(__file__)) -ROOT = os.path.dirname(os.path.dirname(HERE)) -TOOLS_DIR = os.environ.get("LEONIDA_TOOLS_DIR") or os.path.join(ROOT, "tools") - -sys.dont_write_bytecode = True -if TOOLS_DIR not in sys.path: - sys.path.insert(0, TOOLS_DIR) -if HERE not in sys.path: - sys.path.insert(0, HERE) - -import rdna2spirv # noqa: E402 -import spirv_mini_interp as si # noqa: E402 -import support # noqa: E402 - -MASK32 = 0xFFFFFFFF -MASK8 = 0xFF -STUB_DXBC = b"DXBC" + bytes(24) + struct.pack(" tuple[int, int, int, int]: - """Unpack a 32-bit dword into four unsigned 8-bit integers (byte0, byte1, byte2, byte3).""" - dword &= MASK32 - return ( - dword & MASK8, - (dword >> 8) & MASK8, - (dword >> 16) & MASK8, - (dword >> 24) & MASK8, - ) - - -def pack_u8(b0: int, b1: int, b2: int, b3: int) -> int: - """Pack four 8-bit unsigned integers into a 32-bit dword.""" - return ((b0 & MASK8) | ((b1 & MASK8) << 8) | ((b2 & MASK8) << 16) | ((b3 & MASK8) << 24)) & MASK32 - - -def ref_dot4_u32_u8(s0: int, s1: int, s2: int = 0) -> int: - """Reference oracle for RDNA2 unsigned 8-bit dot product (v_dot4_u32_u8). - - Calculates: - D = (s2 + sum(s0[i] * s1[i] for i in 0..3)) mod 2^32 - where each s0[i] and s1[i] is an unsigned 8-bit integer in [0, 255]. - """ - b0 = unpack_u8(s0) - b1 = unpack_u8(s1) - prod_sum = sum(x * y for x, y in zip(b0, b1)) - return ((s2 & MASK32) + prod_sum) & MASK32 - - -def ref_dot4acc_u32_u8(s0: int, s1: int, s2: int) -> int: - """Reference oracle for accumulating form v_dot4acc_u32_u8 with explicit accumulator.""" - return ref_dot4_u32_u8(s0, s1, s2) - - -def ref_dot4_clamp_u32_u8(s0: int, s1: int, s2: int = 0) -> int: - """Reference oracle with unsigned clamping/saturation at 0xFFFFFFFF.""" - b0 = unpack_u8(s0) - b1 = unpack_u8(s1) - total = (s2 & MASK32) + sum(x * y for x, y in zip(b0, b1)) - return min(total, MASK32) - - -def ref_dot4_i32_i8(s0: int, s1: int, s2: int = 0) -> int: - """Signed reference oracle for signed 8-bit dot product (v_dot4_i32_i8). - - Used for divergence comparisons against unsigned dot products. - """ - def s8(x: int) -> int: - return x - 256 if (x & 0x80) else x - - b0 = unpack_u8(s0) - b1 = unpack_u8(s1) - prod_sum = sum(s8(x) * s8(y) for x, y in zip(b0, b1)) - return ((s2 & MASK32) + prod_sum) & MASK32 - - -def build_spirv_dot4_fragment(s0: int, s1: int, acc: int = 0) -> str: - """Synthesize valid SPIR-V assembly computing unsigned dot4 via OpBitFieldUExtract/OpIMul/OpIAdd.""" - s0 &= MASK32 - s1 &= MASK32 - acc &= MASK32 - return f"""OpCapability Shader -OpMemoryModel Logical GLSL450 -OpEntryPoint Fragment %main "main" %out_mrt0 -OpExecutionMode %main OriginUpperLeft -OpDecorate %out_mrt0 Location 0 -%void = OpTypeVoid -%fn = OpTypeFunction %void -%uint = OpTypeInt 32 0 -%v4uint = OpTypeVector %uint 4 -%pout = OpTypePointer Output %v4uint -%out_mrt0 = OpVariable %pout Output - -%c_s0 = OpConstant %uint {s0} -%c_s1 = OpConstant %uint {s1} -%c_acc = OpConstant %uint {acc} -%c0 = OpConstant %uint 0 -%c8 = OpConstant %uint 8 -%c16 = OpConstant %uint 16 -%c24 = OpConstant %uint 24 - -%main = OpFunction %void None %fn -%entry = OpLabel -%x0 = OpBitFieldUExtract %uint %c_s0 %c0 %c8 -%y0 = OpBitFieldUExtract %uint %c_s1 %c0 %c8 -%p0 = OpIMul %uint %x0 %y0 -%t0 = OpIAdd %uint %c_acc %p0 - -%x1 = OpBitFieldUExtract %uint %c_s0 %c8 %c8 -%y1 = OpBitFieldUExtract %uint %c_s1 %c8 %c8 -%p1 = OpIMul %uint %x1 %y1 -%t1 = OpIAdd %uint %t0 %p1 - -%x2 = OpBitFieldUExtract %uint %c_s0 %c16 %c8 -%y2 = OpBitFieldUExtract %uint %c_s1 %c16 %c8 -%p2 = OpIMul %uint %x2 %y2 -%t2 = OpIAdd %uint %t1 %p2 - -%x3 = OpBitFieldUExtract %uint %c_s0 %c24 %c8 -%y3 = OpBitFieldUExtract %uint %c_s1 %c24 %c8 -%p3 = OpIMul %uint %x3 %y3 -%res = OpIAdd %uint %t2 %p3 - -%out_vec = OpCompositeConstruct %v4uint %res %res %res %res -OpStore %out_mrt0 %out_vec -OpReturn -OpFunctionEnd -""" - - -@contextlib.contextmanager -def patch_rdna2spirv_dot4_u8(): - """Context manager to hook rdna2spirv instruction generator with v_dot4_u32_u8 and v_dot4c_u32_u8.""" - orig_insn = rdna2spirv.Gen._insn - orig_rbw = rdna2spirv.read_before_write_vgprs - orig_rrw = rdna2spirv.reg_reads_writes - - def patched_rbw(insns): - for ins in insns: - if ins.get("op") == "v_dot4c_u32_u8": - ins["op"] = "v_dot4c_i32_i8" - res = orig_rbw(insns) - ins["op"] = "v_dot4c_u32_u8" - return res - return orig_rbw(insns) - - def patched_rrw(insns): - for ins in insns: - if ins.get("op") == "v_dot4c_u32_u8": - ins["op"] = "v_dot4c_i32_i8" - res = orig_rrw(insns) - ins["op"] = "v_dot4c_u32_u8" - return res - return orig_rrw(insns) - - def patched_insn(self, ins): - op = ins.get("op", "") - if op in ("v_dot4_u32_u8", "v_dot4acc_u32_u8", "v_dot4c_u32_u8"): - mods = ins.get("mods", set()) - if "clamp" in mods or any(m.startswith("op_sel") for m in mods): - raise rdna2spirv.Unsupported(op + (" clamp" if "clamp" in mods else " op_sel")) - a = ins["args"] - x, y = self.src_u(a[1]), self.src_u(a[2]) - acc = self.src_u(a[3]) if len(a) > 3 else (self.src_u(a[0]) if op == "v_dot4c_u32_u8" else self.cu(0)) - for i in range(4): - xb, yb, prod, total = (self.tmp() for _ in range(4)) - self.emit(f"{xb} = OpBitFieldUExtract %uint {x} {self.cu(8 * i)} {self.cu(8)}") - self.emit(f"{yb} = OpBitFieldUExtract %uint {y} {self.cu(8 * i)} {self.cu(8)}") - self.emit(f"{prod} = OpIMul %uint {xb} {yb}") - self.emit(f"{total} = OpIAdd %uint {acc} {prod}") - acc = total - self.dst(a[0], acc) - return - return orig_insn(self, ins) - - rdna2spirv.Gen._insn = patched_insn - rdna2spirv.read_before_write_vgprs = patched_rbw - rdna2spirv.reg_reads_writes = patched_rrw - try: - yield - finally: - rdna2spirv.Gen._insn = orig_insn - rdna2spirv.read_before_write_vgprs = orig_rbw - rdna2spirv.reg_reads_writes = orig_rrw - - -class ReferenceOracleTests(unittest.TestCase): - """Verifies reference oracle against known hand-calculated vectors and algebraic laws.""" - - def test_unpack_pack_u8_roundtrip(self) -> None: - """Verifies byte unpacking and packing round-trip across test patterns.""" - patterns = [ - 0x00000000, - 0xFFFFFFFF, - 0x12345678, - 0xA55AA55A, - 0x01020304, - 0x80808080, - 0x7F8001FE, - ] - for val in patterns: - with self.subTest(val=hex(val)): - b0, b1, b2, b3 = unpack_u8(val) - repacked = pack_u8(b0, b1, b2, b3) - self.assertEqual(repacked, val) - - def test_reference_known_vectors(self) -> None: - """Verifies reference oracle reproduces all known test vectors.""" - for s0, s1, s2, expected in KNOWN_VECTORS: - with self.subTest(s0=hex(s0), s1=hex(s1), s2=hex(s2)): - got = ref_dot4_u32_u8(s0, s1, s2) - self.assertEqual(got, expected, f"{s0:#x} . {s1:#x} + {s2:#x}") - - def test_commutativity_of_multipliers(self) -> None: - """Dot product of S0 and S1 is commutative: S0 . S1 == S1 . S0.""" - test_pairs = [ - (0x01020304, 0x05060708), - (0xFFFFFFFF, 0x12345678), - (0x80808080, 0x7F7F7F7F), - (0xA1B2C3D4, 0x1E2D3C4B), - (0x00FF00FF, 0xFF00FF00), - ] - for s0, s1 in test_pairs: - for s2 in (0, 100, 0x12345678, 0xFFFFFFFF): - with self.subTest(s0=hex(s0), s1=hex(s1), s2=hex(s2)): - self.assertEqual( - ref_dot4_u32_u8(s0, s1, s2), - ref_dot4_u32_u8(s1, s0, s2), - ) - - def test_zero_identities(self) -> None: - """Dot product with zero operand returns the accumulator exactly.""" - vectors = [0x01020304, 0xFFFFFFFF, 0x80808080, 0x12345678] - for v in vectors: - for acc in (0, 1, 0x7FFFFFFF, 0xFFFFFFFF): - with self.subTest(v=hex(v), acc=hex(acc)): - self.assertEqual(ref_dot4_u32_u8(0, v, acc), acc & MASK32) - self.assertEqual(ref_dot4_u32_u8(v, 0, acc), acc & MASK32) - - def test_identity_broadcast_sums_bytes(self) -> None: - """Dot product with 0x01010101 computes the sum of the four unsigned bytes.""" - test_words = [ - (0x01020304, 1 + 2 + 3 + 4), - (0xFFFFFFFF, 255 * 4), - (0x10203040, 0x10 + 0x20 + 0x30 + 0x40), - (0x000000FF, 255), - (0x0000FF00, 255), - (0x00FF0000, 255), - (0xFF000000, 255), - ] - for word, expected_sum in test_words: - with self.subTest(word=hex(word)): - self.assertEqual(ref_dot4_u32_u8(word, 0x01010101, 0), expected_sum) - self.assertEqual(ref_dot4_u32_u8(0x01010101, word, 0), expected_sum) - - def test_byte_lane_isolation(self) -> None: - """Verifies each byte lane operates independently without bleed across byte boundaries.""" - for byte_idx in range(4): - for val_a in (1, 15, 128, 255): - for val_b in (1, 10, 100, 255): - s0 = val_a << (8 * byte_idx) - s1 = val_b << (8 * byte_idx) - expected = val_a * val_b - with self.subTest(lane=byte_idx, a=val_a, b=val_b): - self.assertEqual(ref_dot4_u32_u8(s0, s1, 0), expected) - - def test_addend_linearity(self) -> None: - """v_dot4_u32_u8(S0, S1, S2) == (v_dot4_u32_u8(S0, S1, 0) + S2) mod 2^32.""" - s0, s1 = 0x11223344, 0x55667788 - base_dot = ref_dot4_u32_u8(s0, s1, 0) - for addend in (0, 1, 0x1000, 0x7FFFFFFF, 0xFFFFFFFF, 0xFFFFFFFE): - with self.subTest(addend=hex(addend)): - want = (base_dot + addend) & MASK32 - got = ref_dot4_u32_u8(s0, s1, addend) - self.assertEqual(got, want) - - def test_unsigned_vs_signed_divergence(self) -> None: - """Unsigned dot product behaves fundamentally differently from signed dot product.""" - divergent_pairs = [ - (0x000000FF, 0x00000001, 0), - (0x000000FF, 0x000000FF, 0), - (0xFFFFFFFF, 0x01010101, 0), - (0x80808080, 0x7F7F7F7F, 0), - ] - for s0, s1, s2 in divergent_pairs: - with self.subTest(s0=hex(s0), s1=hex(s1)): - u_res = ref_dot4_u32_u8(s0, s1, s2) - s_res = ref_dot4_i32_i8(s0, s1, s2) - self.assertNotEqual(u_res, s_res) - - def test_pseudorandom_fuzz_properties(self) -> None: - """Deterministic property fuzzing over 100 pseudo-random 32-bit words.""" - rng = random.Random(0x444F5434) # ASCII 'DOT4' - for _ in range(100): - s0 = rng.getrandbits(32) - s1 = rng.getrandbits(32) - s2 = rng.getrandbits(32) - - self.assertEqual(ref_dot4_u32_u8(s0, s1, s2), ref_dot4_u32_u8(s1, s0, s2)) - b0 = unpack_u8(s0) - b1 = unpack_u8(s1) - manual_sum = ((s2 & MASK32) + b0[0]*b1[0] + b0[1]*b1[1] + b0[2]*b1[2] + b0[3]*b1[3]) & MASK32 - self.assertEqual(ref_dot4_u32_u8(s0, s1, s2), manual_sum) - self.assertEqual(ref_dot4acc_u32_u8(s0, s1, s2), ref_dot4_u32_u8(s0, s1, s2)) - - -class WavefrontDot4Interpreter: - """Simulates an RDNA2 SIMD wavefront executing VALU/SALU dot-product instructions. - - Models: - - Wave32 (32 lanes) and Wave64 (64 lanes). - - Per-lane VGPR files: vgprs[reg][lane]. - - Uniform SGPR file: sgprs[reg]. - - EXEC mask: 32-bit or 64-bit integer mask. - - Instructions: v_mov_b32, s_mov_b32, s_mov_b64, v_dot4_u32_u8, v_dot4acc_u32_u8, v_dot4c_u32_u8. - """ - - def __init__(self, wave_size: int = 32): - if wave_size not in (32, 64): - raise ValueError(f"Unsupported wave_size {wave_size}; must be 32 or 64") - self.wave_size = wave_size - self.vgprs = [[0] * wave_size for _ in range(256)] - self.sgprs = [0] * 106 - self.exec_mask = (1 << wave_size) - 1 - - def set_vgpr(self, reg: int, lane: int, val: int) -> None: - self.vgprs[reg][lane] = val & MASK32 - - def get_vgpr(self, reg: int, lane: int) -> int: - return self.vgprs[reg][lane] & MASK32 - - def set_sgpr(self, reg: int, val: int) -> None: - self.sgprs[reg] = val & MASK32 - - def get_sgpr(self, reg: int) -> int: - return self.sgprs[reg] & MASK32 - - def set_exec(self, mask: int) -> None: - self.exec_mask = mask & ((1 << self.wave_size) - 1) - - def parse_operand(self, token: str, lane: int) -> int: - token = token.strip().rstrip(",") - lower = token.lower() - if lower.startswith("v") and lower[1:].isdigit(): - idx = int(lower[1:]) - if 0 <= idx < 256: - return self.vgprs[idx][lane] & MASK32 - raise IndexError(f"VGPR index out of range: {token}") - if lower.startswith("s") and lower[1:].isdigit(): - idx = int(lower[1:]) - if 0 <= idx < 106: - return self.sgprs[idx] & MASK32 - raise IndexError(f"SGPR index out of range: {token}") - if lower.startswith("0x") or lower.startswith("-0x"): - return int(token, 16) & MASK32 - return int(token) & MASK32 - - def execute_line(self, line: str) -> None: - line = line.split(";", 1)[0].split("//", 1)[0].strip() - if not line: - return - parts = line.split(None, 1) - opcode = parts[0].lower() - args_str = parts[1] if len(parts) > 1 else "" - - tokens = [t.strip() for t in args_str.split(",") if t.strip()] - - if opcode == "s_mov_b32": - dst = tokens[0].lower() - if not (dst.startswith("s") and dst[1:].isdigit()): - raise ValueError(f"s_mov_b32 dst must be SGPR, got {tokens[0]}") - s_idx = int(dst[1:]) - val = self.parse_operand(tokens[1], 0) - self.sgprs[s_idx] = val - - elif opcode in ("v_mov_b32", "v_mov_b32_e32"): - dst = tokens[0].lower() - if not (dst.startswith("v") and dst[1:].isdigit()): - raise ValueError(f"v_mov_b32 dst must be VGPR, got {tokens[0]}") - v_idx = int(dst[1:]) - for lane in range(self.wave_size): - if (self.exec_mask >> lane) & 1: - val = self.parse_operand(tokens[1], lane) - self.vgprs[v_idx][lane] = val - - elif opcode in ("v_dot4_u32_u8", "v_dot4acc_u32_u8"): - # VOP3/VOP3P: dst, src0, src1, src2 - dst = tokens[0].lower() - if not (dst.startswith("v") and dst[1:].isdigit()): - raise ValueError(f"{opcode} dst must be VGPR, got {tokens[0]}") - v_idx = int(dst[1:]) - for lane in range(self.wave_size): - if (self.exec_mask >> lane) & 1: - s0 = self.parse_operand(tokens[1], lane) - s1 = self.parse_operand(tokens[2], lane) - s2 = self.parse_operand(tokens[3], lane) if len(tokens) > 3 else 0 - self.vgprs[v_idx][lane] = ref_dot4_u32_u8(s0, s1, s2) - - elif opcode == "v_dot4c_u32_u8": - # VOP2: dst, src0, src1 (dst is accumulator) - dst = tokens[0].lower() - if not (dst.startswith("v") and dst[1:].isdigit()): - raise ValueError(f"v_dot4c_u32_u8 dst must be VGPR, got {tokens[0]}") - v_idx = int(dst[1:]) - for lane in range(self.wave_size): - if (self.exec_mask >> lane) & 1: - s0 = self.parse_operand(tokens[1], lane) - s1 = self.parse_operand(tokens[2], lane) - old_acc = self.vgprs[v_idx][lane] - self.vgprs[v_idx][lane] = ref_dot4_u32_u8(s0, s1, old_acc) - - elif opcode == "s_endpgm": - return - else: - raise NotImplementedError(f"Unsupported opcode: {opcode}") - - def execute_program(self, program: str | list[str]) -> None: - lines = program if isinstance(program, list) else program.strip().splitlines() - for line in lines: - self.execute_line(line) - - -class WavefrontInterpreterTests(unittest.TestCase): - """Verifies SIMD multi-lane wavefront execution and accumulation semantics.""" - - def test_wave32_uniform_execution(self) -> None: - """32-lane SIMD execution under full EXEC mask with divergent per-lane data.""" - interp = WavefrontDot4Interpreter(wave_size=32) - for lane in range(32): - s0 = ((lane + 1) * 0x01020304) & MASK32 - s1 = 0x05060708 - acc = lane * 10 - interp.set_vgpr(1, lane, s0) - interp.set_vgpr(2, lane, s1) - interp.set_vgpr(3, lane, acc) - - interp.execute_line("v_dot4_u32_u8 v0, v1, v2, v3") - - for lane in range(32): - s0 = ((lane + 1) * 0x01020304) & MASK32 - s1 = 0x05060708 - acc = lane * 10 - expected = ref_dot4_u32_u8(s0, s1, acc) - self.assertEqual(interp.get_vgpr(0, lane), expected) - - def test_wave64_uniform_execution(self) -> None: - """64-lane SIMD execution covering the entire Wave64 execution space.""" - interp = WavefrontDot4Interpreter(wave_size=64) - for lane in range(64): - s0 = (0x01010101 * lane) & MASK32 - s1 = 0x02020202 - interp.set_vgpr(1, lane, s0) - interp.set_vgpr(2, lane, s1) - interp.set_vgpr(3, lane, 0x1000) - - interp.execute_line("v_dot4acc_u32_u8 v8, v1, v2, v3") - - for lane in range(64): - s0 = (0x01010101 * lane) & MASK32 - s1 = 0x02020202 - expected = ref_dot4_u32_u8(s0, s1, 0x1000) - self.assertEqual(interp.get_vgpr(8, lane), expected) - - def test_v_dot4c_u32_u8_accumulator_reads_destination(self) -> None: - """v_dot4c_u32_u8 (VOP2) uses destination register's prior value as accumulator.""" - interp = WavefrontDot4Interpreter(wave_size=32) - for lane in range(32): - interp.set_vgpr(0, lane, 500) - interp.set_vgpr(1, lane, 0x01020304) - interp.set_vgpr(2, lane, 0x05060708) - - interp.execute_line("v_dot4c_u32_u8 v0, v1, v2") - for lane in range(32): - self.assertEqual(interp.get_vgpr(0, lane), 570) - - interp.execute_line("v_dot4c_u32_u8 v0, v1, v2") - for lane in range(32): - self.assertEqual(interp.get_vgpr(0, lane), 640) - - def test_accumulator_chain_loop(self) -> None: - """Simulate an inner-loop dot-product reduction accumulating across iterations.""" - interp = WavefrontDot4Interpreter(wave_size=32) - running_totals = [0] * 32 - steps = [ - (0x01010101, 0x02020202), # 4 * 2 = 8 - (0x03030303, 0x04040404), # 4 * 12 = 48 - (0x05050505, 0x06060606), # 4 * 30 = 120 - (0x07070707, 0x08080808), # 4 * 56 = 224 - ] - for s0, s1 in steps: - for lane in range(32): - interp.set_vgpr(1, lane, s0) - interp.set_vgpr(2, lane, s1) - running_totals[lane] = (running_totals[lane] + ref_dot4_u32_u8(s0, s1, 0)) & MASK32 - interp.execute_line("v_dot4c_u32_u8 v0, v1, v2") - - for lane in range(32): - self.assertEqual(interp.get_vgpr(0, lane), running_totals[lane]) - self.assertEqual(interp.get_vgpr(0, lane), 8 + 48 + 120 + 224) - - def test_wave_lane_divergence_exec_mask(self) -> None: - """Inactive lanes under partial EXEC mask must strictly preserve destination registers.""" - interp = WavefrontDot4Interpreter(wave_size=32) - sentinel = 0xDEADBEEF - - for lane in range(32): - interp.set_vgpr(5, lane, sentinel) - interp.set_vgpr(1, lane, 0x01020304) - interp.set_vgpr(2, lane, 0x05060708) - interp.set_vgpr(3, lane, 100) - - interp.set_exec(0x0000FFFF) - interp.execute_line("v_dot4_u32_u8 v5, v1, v2, v3") - - for lane in range(32): - if lane < 16: - self.assertEqual(interp.get_vgpr(5, lane), 170) - else: - self.assertEqual(interp.get_vgpr(5, lane), sentinel) - - def test_odd_even_lane_divergence(self) -> None: - """Divergent execution between alternating even and odd lanes.""" - interp = WavefrontDot4Interpreter(wave_size=32) - for lane in range(32): - interp.set_vgpr(10, lane, 0) - interp.set_vgpr(1, lane, 0x01010101) - interp.set_vgpr(2, lane, 0x0A0A0A0A) - interp.set_vgpr(3, lane, 0x02020202) - interp.set_vgpr(4, lane, 0x14141414) - - interp.set_exec(0x55555555) - interp.execute_line("v_dot4_u32_u8 v10, v1, v2, 0") - - interp.set_exec(0xAAAAAAAA) - interp.execute_line("v_dot4_u32_u8 v10, v3, v4, 0") - - for lane in range(32): - expected = 40 if (lane % 2 == 0) else 160 - self.assertEqual(interp.get_vgpr(10, lane), expected) - - def test_single_lane_active(self) -> None: - """Only a single lane active (lane 13), ensuring no collateral writes.""" - interp = WavefrontDot4Interpreter(wave_size=32) - for lane in range(32): - interp.set_vgpr(7, lane, 0xBAADF00D) - interp.set_vgpr(1, lane, 0x01020304) - interp.set_vgpr(2, lane, 0x05060708) - - target_lane = 13 - interp.set_exec(1 << target_lane) - interp.execute_line("v_dot4_u32_u8 v7, v1, v2, 0") - - for lane in range(32): - if lane == target_lane: - self.assertEqual(interp.get_vgpr(7, lane), 70) - else: - self.assertEqual(interp.get_vgpr(7, lane), 0xBAADF00D) - - def test_scalar_source_broadcast(self) -> None: - """SGPR sources broadcast uniform values across all lanes.""" - interp = WavefrontDot4Interpreter(wave_size=32) - interp.set_sgpr(4, 0x05060708) - interp.set_sgpr(5, 5000) - - for lane in range(32): - interp.set_vgpr(1, lane, 0x01020304) - - interp.execute_line("v_dot4_u32_u8 v0, v1, s4, s5") - - for lane in range(32): - self.assertEqual(interp.get_vgpr(0, lane), 5070) - - -class SpirvEmissionAndOverflowTests(unittest.TestCase): - """Verifies SPIR-V translation, interpreter execution, and integer overflow wrapping.""" - - def test_direct_spirv_emission_against_mini_interp(self) -> None: - """Synthesized SPIR-V fragment shaders execute cleanly in spirv_mini_interp.""" - for s0, s1, s2, expected in KNOWN_VECTORS[:10]: - with self.subTest(s0=hex(s0), s1=hex(s1), s2=hex(s2)): - spv = build_spirv_dot4_fragment(s0, s1, s2) - res = si.run_fragment(spv) - self.assertIn("%out_mrt0", res) - self.assertEqual(list(res["%out_mrt0"]), [expected] * 4) - - def test_translated_rdna2spirv_fragment_execution(self) -> None: - """Pixel shaders with v_dot4_u32_u8 translated via rdna2spirv and run in si.""" - with patch_rdna2spirv_dot4_u8(): - for s0, s1, s2, expected in KNOWN_VECTORS[:8]: - with self.subTest(s0=hex(s0), s1=hex(s1), s2=hex(s2)): - lines = [ - f"v_mov_b32_e32 v1, 0x{s0:08x}", - f"v_mov_b32_e32 v2, 0x{s1:08x}", - f"v_mov_b32_e32 v3, 0x{s2:08x}", - "v_dot4_u32_u8 v8, v1, v2, v3", - "exp mrt0 v8, v8, v8, v8 done vm", - "s_endpgm", - ] - spv = support.translate_lines("ps_dot4_u8_test", lines) - self.assertEqual(support.mrt0_words(spv), [expected] * 4) - - def test_translated_rdna2spirv_v_dot4c_accumulator(self) -> None: - """v_dot4c_u32_u8 accumulating form translated and executed via support.""" - with patch_rdna2spirv_dot4_u8(): - lines = [ - "v_mov_b32_e32 v1, 0x01020304", - "v_mov_b32_e32 v2, 0x05060708", - "v_mov_b32_e32 v9, 0x000003E8", # 1000 - "v_dot4c_u32_u8 v9, v1, v2", # 1000 + 70 = 1070 - "v_dot4c_u32_u8 v9, v1, v2", # 1070 + 70 = 1140 - "exp mrt0 v9, v9, v9, v9 done vm", - "s_endpgm", - ] - spv = support.translate_lines("ps_dot4c_u8_test", lines) - self.assertEqual(support.mrt0_words(spv), [1140] * 4) - - def test_integer_overflow_wrap_around_modulo_32(self) -> None: - """Unsigned 32-bit integer arithmetic wraps strictly modulo 2^32.""" - s0 = 0xFFFFFFFF - s1 = 0xFFFFFFFF - # Max product = 260100 (0x3F804) - dot_prod = ref_dot4_u32_u8(s0, s1, 0) - self.assertEqual(dot_prod, 260100) - - # 1. Exact overflow boundary (sum is exactly 2^32 -> wraps to 0) - acc_exact = (MASK32 - dot_prod + 1) & MASK32 - self.assertEqual(ref_dot4_u32_u8(s0, s1, acc_exact), 0) - - # 2. Wrap by 1 - acc_wrap1 = (acc_exact + 1) & MASK32 - self.assertEqual(ref_dot4_u32_u8(s0, s1, acc_wrap1), 1) - - # 3. Maximum accumulator 0xFFFFFFFF (wraps to dot_prod - 1) - self.assertEqual(ref_dot4_u32_u8(s0, s1, MASK32), dot_prod - 1) - - # Verify wrapping holds through SPIR-V mini interpreter - spv = build_spirv_dot4_fragment(s0, s1, acc_exact) - res = si.run_fragment(spv) - self.assertEqual(list(res["%out_mrt0"]), [0] * 4) - - spv = build_spirv_dot4_fragment(s0, s1, acc_wrap1) - res = si.run_fragment(spv) - self.assertEqual(list(res["%out_mrt0"]), [1] * 4) - - def test_unsigned_clamping_saturation_model(self) -> None: - """Model unsigned clamp saturating at 0xFFFFFFFF on overflow.""" - s0 = 0xFFFFFFFF - s1 = 0xFFFFFFFF - acc_overflow = 0xFFFFFFFF - # Without clamp, wraps to 260099 - self.assertEqual(ref_dot4_u32_u8(s0, s1, acc_overflow), 260099) - # With clamp, saturates at 0xFFFFFFFF - self.assertEqual(ref_dot4_clamp_u32_u8(s0, s1, acc_overflow), 0xFFFFFFFF) - - -class NegativeControlTests(unittest.TestCase): - """Negative controls, modifier rejections, and fault injection verification.""" - - def test_unpatched_rdna2spirv_translates_dot4(self) -> None: - """The translator itself now lowers v_dot4_u32_u8 (docs/design.md, packed integer dot products).""" - lines = [ - "v_mov_b32_e32 v1, 1", - "v_mov_b32_e32 v2, 1", - "v_mov_b32_e32 v3, 0", - "v_dot4_u32_u8 v8, v1, v2, v3", - "exp mrt0 v8, v8, v8, v8 done vm", - "s_endpgm", - ] - support.translate_lines("ps_dot4_unpatched", lines) - - def test_clamp_modifier_is_refused(self) -> None: - """The translator refuses clamp modifier on v_dot4_u32_u8 rather than guessing.""" - with patch_rdna2spirv_dot4_u8(): - lines = [ - "v_mov_b32_e32 v1, 1", - "v_mov_b32_e32 v2, 1", - "v_mov_b32_e32 v3, 0", - "v_dot4_u32_u8 v8, v1, v2, v3 clamp", - "exp mrt0 v8, v8, v8, v8 done vm", - "s_endpgm", - ] - with self.assertRaises(rdna2spirv.Unsupported) as refused: - support.translate_lines("ps_dot4_clamp", lines) - self.assertEqual(str(refused.exception), "v_dot4_u32_u8 clamp") - - def test_op_sel_modifier_is_refused(self) -> None: - """The translator refuses op_sel modifier on v_dot4_u32_u8.""" - with patch_rdna2spirv_dot4_u8(): - lines = [ - "v_mov_b32_e32 v1, 1", - "v_mov_b32_e32 v2, 1", - "v_mov_b32_e32 v3, 0", - "v_dot4_u32_u8 v8, v1, v2, v3 op_sel:[0,1,0] op_sel_hi:[1,0,1]", - "exp mrt0 v8, v8, v8, v8 done vm", - "s_endpgm", - ] - with self.assertRaises(rdna2spirv.Unsupported) as refused: - support.translate_lines("ps_dot4_op_sel", lines) - self.assertEqual(str(refused.exception), "v_dot4_u32_u8 op_sel") - - def test_interpreter_invalid_destination(self) -> None: - """VALU instructions cannot write to SGPRs as destinations.""" - interp = WavefrontDot4Interpreter(wave_size=32) - with self.assertRaises(ValueError): - interp.execute_line("v_dot4_u32_u8 s0, v1, v2, v3") - - def test_interpreter_out_of_bounds_registers(self) -> None: - """VGPR index >= 256 or SGPR index >= 106 raises IndexError.""" - interp = WavefrontDot4Interpreter(wave_size=32) - with self.assertRaises(IndexError): - interp.execute_line("v_dot4_u32_u8 v0, v256, v1, v2") - with self.assertRaises(IndexError): - interp.execute_line("v_dot4_u32_u8 v0, v1, s110, v2") - - def test_interpreter_unsupported_opcode(self) -> None: - """Unknown opcodes raise NotImplementedError.""" - interp = WavefrontDot4Interpreter(wave_size=32) - with self.assertRaises(NotImplementedError): - interp.execute_line("v_nonexistent_op v0, v1, v2") - - def test_interpreter_invalid_wave_size(self) -> None: - """Wave sizes other than 32 or 64 are rejected.""" - with self.assertRaises(ValueError): - WavefrontDot4Interpreter(wave_size=16) - - def test_bit_corruption_sensitivity(self) -> None: - """Flipping any bit in multiplier operands must perturb dot product result.""" - s0 = 0x01020304 - s1 = 0x05060708 - acc = 1000 - golden = ref_dot4_u32_u8(s0, s1, acc) - - for bit in range(32): - corrupted_s0 = s0 ^ (1 << bit) - corrupted_s1 = s1 ^ (1 << bit) - self.assertNotEqual( - ref_dot4_u32_u8(corrupted_s0, s1, acc), - golden, - f"Flipping bit {bit} in S0 produced no change", - ) - self.assertNotEqual( - ref_dot4_u32_u8(s0, corrupted_s1, acc), - golden, - f"Flipping bit {bit} in S1 produced no change", - ) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_alu_dot_complete.py b/tests/semantic/test_alu_dot_complete.py deleted file mode 100644 index 78a92daac..000000000 --- a/tests/semantic/test_alu_dot_complete.py +++ /dev/null @@ -1,364 +0,0 @@ -"""Semantic interpreter tests for RDNA2 v_dot2c/4c/8c integer forms and v_dot2_f32_f16 / v_dot2c_f32_f16. - -Covers the 7 remaining RDNA2 dot-product instructions: - - v_dot2c_i32_i16, v_dot2c_u32_u16, v_dot4c_u32_u8, v_dot8c_i32_i4, v_dot8c_u32_u4 (VOP2 accumulating) - - v_dot2_f32_f16 (VOP3P half-to-float dot product with op_sel, op_sel_hi, neg_lo, neg_hi, clamp) - - v_dot2c_f32_f16 (VOP2 accumulating half-to-float dot product with optional clamp) - -Standard library only; no GPU, no LLVM, no SPIRV-Tools, no game files. -""" -import math -import os -import random -import struct -import sys -import unittest - -HERE = os.path.dirname(os.path.abspath(__file__)) -ROOT = os.path.dirname(os.path.dirname(HERE)) -sys.dont_write_bytecode = True -TOOLS_DIR = os.environ.get("LEONIDA_TOOLS_DIR") or os.path.join(ROOT, "tools") -if TOOLS_DIR not in sys.path: - sys.path.insert(0, TOOLS_DIR) -if HERE not in sys.path: - sys.path.insert(0, HERE) - -import rdna2spirv # noqa: E402 -import shader_ir # noqa: E402 -from support import mrt0_words, translate_lines # noqa: E402 - -MASK32 = 0xFFFFFFFF -INT32_MIN = -(1 << 31) -INT32_MAX = (1 << 31) - 1 - -INT_DOTC_OPS = ( - "v_dot2c_i32_i16", - "v_dot2c_u32_u16", - "v_dot4c_u32_u8", - "v_dot8c_i32_i4", - "v_dot8c_u32_u4", -) - - -def s32(x: int) -> int: - x &= MASK32 - return x - (1 << 32) if x >> 31 else x - - -def ref_dot_int(op: str, x: int, y: int, acc: int, clamp: bool = False) -> int: - width = 16 if ("_dot2_" in op or "_dot2c_" in op) else (8 if "_dot4" in op else 4) - signed = op.endswith(("i16", "i4")) - mask = (1 << width) - 1 - sign_bit = 1 << (width - 1) - total = s32(acc) if signed else (acc & MASK32) - for off in range(0, 32, width): - xe = (x >> off) & mask - ye = (y >> off) & mask - if signed: - if xe & sign_bit: - xe -= 1 << width - if ye & sign_bit: - ye -= 1 << width - total += xe * ye - if clamp: - if signed: - total = max(INT32_MIN, min(INT32_MAX, total)) - else: - total = max(0, min(MASK32, total)) - return total & MASK32 - - -def f32_bits(val: float) -> int: - return struct.unpack(" float: - return struct.unpack(" float: - try: - return struct.unpack(" 0 else -math.inf - - -def f16_bits(val: float) -> int: - return struct.unpack(" float: - return struct.unpack(" int: - return f16_bits(lo) | (f16_bits(hi) << 16) - - -def flush_f32_py(bits: int) -> float: - f = bits_f32(bits) - if math.isfinite(f) and abs(f) < 2.0 ** -126: - return math.copysign(0.0, f) - return f - - -def ref_dot2_f32_f16( - s0: int, - s1: int, - acc_bits: int, - sel=(0, 0, 0), - selhi=(1, 1, 1), - nlo=(0, 0, 0), - nhi=(0, 0, 0), - clamp: bool = False, -) -> int: - a0 = bits_f16((s0 >> (16 * sel[0])) & 0xFFFF) - a1 = bits_f16((s0 >> (16 * selhi[0])) & 0xFFFF) - b0 = bits_f16((s1 >> (16 * sel[1])) & 0xFFFF) - b1 = bits_f16((s1 >> (16 * selhi[1])) & 0xFFFF) - if nlo[0]: - a0 = -a0 - if nhi[0]: - a1 = -a1 - if nlo[1]: - b0 = -b0 - if nhi[1]: - b1 = -b1 - acc = flush_f32_py(acc_bits) - if nlo[2]: - acc = -acc - p0 = f32(a0 * b0) - p1 = f32(a1 * b1) - s = f32(p0 + p1) - r = f32(s + acc) - if clamp: - r = max(0.0, min(1.0, r)) - return f32_bits(r) - - -def run_ps(lines) -> tuple: - spv = translate_lines("ps_dot_complete", list(lines) + ["exp mrt0 v0, v1, v2, v3 done vm", "s_endpgm"]) - return tuple(mrt0_words(spv)) - - -class IntDotAccumTests(unittest.TestCase): - def test_v_dotc_values_and_clamp(self): - cases = [ - # (op, x, y, acc) - ("v_dot2c_i32_i16", 0xFFFC0003, 0x0005FFFE, 100), - ("v_dot2c_i32_i16", 0x80008000, 0x80008000, 0), # 2*(-32768)^2 = 0x80000000 -> clamps to INT32_MAX - ("v_dot2c_i32_i16", 0x80008000, 0x7FFF7FFF, 0x80000000), # negative overflow -> INT32_MIN - ("v_dot2c_i32_i16", 0x80008000, 0x80008000, 0x80000000), # cancellation edge: 2^31 - 2^31 = 0 - ("v_dot2c_u32_u16", 0x80000001, 0x00010003, 5), - ("v_dot2c_u32_u16", 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFF0000), # unsigned wrap / clamp - ("v_dot4c_u32_u8", 0x80FF0102, 0x02010304, 10), - ("v_dot4c_u32_u8", 0xFFFFFFFF, 0x01010101, 0xFFFFFF00), # unsigned wrap / clamp - ("v_dot8c_i32_i4", 0x8F123456, 0x12121212, 10), - ("v_dot8c_i32_i4", 0x88888888, 0x88888888, 0x7FFFFFF0), # signed overflow -> INT32_MAX - ("v_dot8c_i32_i4", 0x88888888, 0x77777777, 0x80000010), # signed underflow -> INT32_MIN - ("v_dot8c_u32_u4", 0xF8000001, 0x12000003, 4), - ("v_dot8c_u32_u4", 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFF00), # unsigned wrap / clamp - ] - for op, x, y, acc in cases: - for clamp in (False, True): - mnem = f"{op}_e64" if clamp else op - mod = " clamp" if clamp else "" - with self.subTest(op=mnem, x=hex(x), y=hex(y), acc=hex(acc)): - got = run_ps([ - f"v_mov_b32 v0, {acc:#x}", - f"v_mov_b32 v1, {x:#x}", - f"v_mov_b32 v2, {y:#x}", - "v_mov_b32 v3, 0", - f"{mnem} v0, v1, v2{mod}", - ])[0] - self.assertEqual(got, ref_dot_int(op, x, y, acc, clamp=clamp)) - - def test_v_dotc_sgpr_literal_and_seeded(self): - got = run_ps([ - "s_mov_b32 s4, 0x00020003", - "v_mov_b32 v0, 10", - "v_mov_b32 v1, 0x00040005", - "v_mov_b32 v2, 0", - "v_mov_b32 v3, 0", - "v_dot2c_i32_i16 v0, s4, v1", - "v_mov_b32 v2, 7", - "v_dot4c_u32_u8 v2, 0x01020304, v1", - ]) - self.assertEqual(got[0], ref_dot_int("v_dot2c_i32_i16", 0x00020003, 0x00040005, 10)) - self.assertEqual(got[2], ref_dot_int("v_dot4c_u32_u8", 0x01020304, 0x00040005, 7)) - - rng = random.Random(0xD07C) - for op in INT_DOTC_OPS: - for _ in range(5): - x, y, acc = rng.getrandbits(32), rng.getrandbits(32), rng.getrandbits(32) - clamp = bool(rng.getrandbits(1)) - with self.subTest(op=op, clamp=clamp): - got_w = run_ps([ - f"v_mov_b32 v0, {acc:#x}", - f"v_mov_b32 v1, {x:#x}", - f"v_mov_b32 v2, {y:#x}", - "v_mov_b32 v3, 0", - f"{op}{'_e64' if clamp else ''} v0, v1, v2{' clamp' if clamp else ''}", - ])[0] - self.assertEqual(got_w, ref_dot_int(op, x, y, acc, clamp=clamp)) - - def test_v_dotc_rejects_unsupported_forms(self): - bad_lines = [ - "v_dot2c_i32_i16 v0, v1, v2 op_sel:[0,0,0]", - "v_dot2c_u32_u16 v0, v1, v2 neg_lo:[1,0,0]", - "v_dot4c_u32_u8_dpp v0, v1, v2 quad_perm:[0,1,2,3]", - "v_dot8c_i32_i4_sdwa v0, v1, v2 dst_sel:DWORD", - "v_dot8c_u32_u4_e64 v0, -v1, v2", - "v_dot2c_i32_i16 s0, v1, v2", - ] - for line in bad_lines: - with self.subTest(line=line): - with self.assertRaises(rdna2spirv.Unsupported): - translate_lines("ps_dotc_bad", [line, "exp mrt0 v0, v0, v0, v0 done vm", "s_endpgm"]) - - -class HalfDotF32Tests(unittest.TestCase): - def test_v_dot2_f32_f16_and_v_dot2c_f32_f16_values(self): - s0 = pack_f16x2(1.5, -2.0) - s1 = pack_f16x2(4.0, 0.5) - acc = f32_bits(0.25) - got = run_ps([ - f"v_mov_b32 v1, {s0:#x}", - f"v_mov_b32 v2, {s1:#x}", - f"v_mov_b32 v3, {acc:#x}", - "v_dot2_f32_f16 v0, v1, v2, v3", - f"v_mov_b32 v1, {s0:#x}", - f"v_mov_b32 v2, {s1:#x}", - f"v_mov_b32 v3, {acc:#x}", - "v_dot2c_f32_f16 v3, v1, v2", - ]) - want = ref_dot2_f32_f16(s0, s1, acc) - self.assertEqual(got[0], want) - self.assertEqual(got[3], want) - - def test_v_dot2_f32_f16_opsel_neg_and_clamp(self): - s0 = pack_f16x2(1.5, -2.0) - s1 = pack_f16x2(4.0, 0.5) - acc = f32_bits(0.75) - cases = [ - ("op_sel:[1,0,0] op_sel_hi:[0,1,1]", (1, 0, 0), (0, 1, 1), (0, 0, 0), (0, 0, 0), False), - ("neg_lo:[1,0,0] neg_hi:[0,1,0]", (0, 0, 0), (1, 1, 1), (1, 0, 0), (0, 1, 0), False), - ("neg_lo:[0,0,1]", (0, 0, 0), (1, 1, 1), (0, 0, 1), (0, 0, 0), False), - ("clamp", (0, 0, 0), (1, 1, 1), (0, 0, 0), (0, 0, 0), True), - ("neg_lo:[1,1,1] clamp", (0, 0, 0), (1, 1, 1), (1, 1, 1), (0, 0, 0), True), - ] - for mods, sel, selhi, nlo, nhi, clamp in cases: - with self.subTest(mods=mods): - got = run_ps([ - f"v_mov_b32 v1, {s0:#x}", - f"v_mov_b32 v2, {s1:#x}", - f"v_mov_b32 v3, {acc:#x}", - f"v_dot2_f32_f16 v0, v1, v2, v3 {mods}", - ])[0] - self.assertEqual(got, ref_dot2_f32_f16(s0, s1, acc, sel, selhi, nlo, nhi, clamp=clamp)) - - # v_dot2c_f32_f16 clamp - got_c = run_ps([ - f"v_mov_b32 v0, {f32_bits(0.5):#x}", - f"v_mov_b32 v1, {pack_f16x2(2.0, 1.0):#x}", - f"v_mov_b32 v2, {pack_f16x2(1.0, 1.0):#x}", - "v_mov_b32 v3, 0", - "v_dot2c_f32_f16_e64 v0, v1, v2 clamp", - ])[0] - self.assertEqual(got_c, f32_bits(1.0)) - - def test_subnormals_inf_and_nan(self): - # f16 subnormal input (2^-24) * 2.0 + 0.0 -> 2^-23 (exact normal f32, kept) - s0_sub = 0x0001 - s1_two = pack_f16x2(2.0, 0.0) - got_sub = run_ps([ - f"v_mov_b32 v1, {s0_sub:#x}", - f"v_mov_b32 v2, {s1_two:#x}", - "v_mov_b32 v3, 0", - "v_dot2_f32_f16 v0, v1, v2, v3", - ])[0] - self.assertEqual(got_sub, f32_bits(2.0 ** -23)) - - # f32 subnormal acc is flushed to signed zero by flush_f32 before adding - got_flush = run_ps([ - "v_mov_b32 v1, 0", - "v_mov_b32 v2, 0", - "v_mov_b32 v3, 0x80000001", # negative f32 subnormal - "v_dot2_f32_f16 v0, v1, v2, v3", - ])[0] - self.assertEqual(got_flush, 0x00000000) - - # +inf and NaN propagation - got_inf = run_ps([ - f"v_mov_b32 v1, {pack_f16x2(math.inf, 1.0):#x}", - f"v_mov_b32 v2, {pack_f16x2(1.0, 1.0):#x}", - "v_mov_b32 v3, 0", - "v_dot2_f32_f16 v0, v1, v2, v3", - ])[0] - self.assertEqual(got_inf, f32_bits(math.inf)) - - got_nan = run_ps([ - "v_mov_b32 v1, 0x7e01", - f"v_mov_b32 v2, {pack_f16x2(1.0, 0.0):#x}", - "v_mov_b32 v3, 0", - "v_dot2c_f32_f16 v3, v1, v2", - ])[3] - self.assertTrue(math.isnan(bits_f32(got_nan))) - - def test_seeded_finite(self): - rng = random.Random(0xF16F32) - pool = [-4.0, -1.5, -0.5, -0.0, 0.0, 0.25, 0.5, 1.25, 2.0, 3.5] - for _ in range(15): - a0, a1 = rng.choice(pool), rng.choice(pool) - b0, b1 = rng.choice(pool), rng.choice(pool) - acc = rng.choice(pool) - s0, s1, acc_b = pack_f16x2(a0, a1), pack_f16x2(b0, b1), f32_bits(acc) - want = ref_dot2_f32_f16(s0, s1, acc_b) - got = run_ps([ - f"v_mov_b32 v1, {s0:#x}", - f"v_mov_b32 v2, {s1:#x}", - f"v_mov_b32 v3, {acc_b:#x}", - "v_dot2_f32_f16 v0, v1, v2, v3", - ])[0] - self.assertEqual(got, want) - - def test_rejects_unsupported_forms(self): - bad_lines = [ - "v_dot2_f32_f16 v0, v1, v2, v3 op_sel:[0,0,1]", - "v_dot2_f32_f16 v0, v1, v2, v3 op_sel_hi:[1,1,0]", - "v_dot2_f32_f16 v0, v1, v2, v3 neg_hi:[0,0,1]", - "v_dot2_f32_f16 v0, v1, v2, v3 op_sel:[0,0]", - "v_dot2_f32_f16 v0, v1, v2, v3 mul:2", - "v_dot2_f32_f16 v0, -v1, v2, v3", - "v_dot2_f32_f16_dpp v0, v1, v2, v3 quad_perm:[0,1,2,3]", - "v_dot2_f32_f16 s0, v1, v2, v3", - "v_dot2c_f32_f16 v0, v1, v2 op_sel:[0,0,0]", - "v_dot2c_f32_f16 v0, v1, v2 neg_lo:[1,0,0]", - "v_dot2c_f32_f16_sdwa v0, v1, v2 dst_sel:DWORD", - "v_dot2c_f32_f16_e64 v0, |v1|, v2", - "v_dot2c_f32_f16 s0, v1, v2", - ] - for line in bad_lines: - with self.subTest(line=line): - with self.assertRaises(rdna2spirv.Unsupported): - translate_lines("ps_dotf_bad", [line, "exp mrt0 v0, v0, v0, v0 done vm", "s_endpgm"]) - - -class RmwPrepassTests(unittest.TestCase): - def test_accumulating_ops_marked_read_before_write(self): - for op in (*INT_DOTC_OPS, "v_dot2c_f32_f16"): - with self.subTest(op=op): - insns = [shader_ir.parse_line(ln) for ln in ( - f"{op} v7, v1, v2", - "exp mrt0 v7, v7, v7, v7 done vm", - "s_endpgm", - )] - rbw = rdna2spirv.read_before_write_vgprs(insns) - rr, ww = rdna2spirv.reg_reads_writes(insns) - self.assertIn(7, rbw) - self.assertIn(7, rr) - self.assertIn(7, ww) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_alu_dot_pk_fmac.py b/tests/semantic/test_alu_dot_pk_fmac.py deleted file mode 100644 index 168e49052..000000000 --- a/tests/semantic/test_alu_dot_pk_fmac.py +++ /dev/null @@ -1,579 +0,0 @@ -"""Semantic interpreter tests for RDNA2 integer v_dot2/4/8 instructions and v_pk_fmac_f16 (SHADER-300). - -Covers the six remaining instructions after the #1754 split: - - v_dot2_i32_i16, v_dot2_u32_u16 (2x16-bit packed dot products, wrap and 32-bit clamp) - - v_dot4_u32_u8 (4x8-bit unsigned packed dot product, wrap and 32-bit clamp) - - v_dot8_i32_i4, v_dot8_u32_u4 (8x4-bit packed dot products, wrap and 32-bit clamp) - - v_pk_fmac_f16 (VOP2 packed f16x2 fused multiply-accumulate into vdst with single f16 rounding) - -Standard library only; no GPU, no LLVM, no SPIRV-Tools, no game files. -""" -import math -import os -import random -import struct -import sys -import unittest - -HERE = os.path.dirname(os.path.abspath(__file__)) -ROOT = os.path.dirname(os.path.dirname(HERE)) -sys.dont_write_bytecode = True -sys.path.insert(0, os.environ.get("LEONIDA_TOOLS_DIR") or os.path.join(ROOT, "tools")) -sys.path.insert(0, HERE) - -import shader_ir # noqa: E402 -from support import mrt0_words, rdna2spirv, translate_lines # noqa: E402 -from test_f16_fma_rounding import double_rounded, near_tie_triples, ref_fma # noqa: E402 - -MASK32 = 0xFFFFFFFF - -PS_DOT_PK_FMAC_ASM = ( - # Channel 0 (v10): v_dot2_i32_i16 and v_dot2_u32_u16 - # v4 = 3*(-2) + (-4)*5 + 100 = 74 (0x4a) - # v5 = 1*3 + 32768*1 + 5 = 32776 (0x8008) - # v10 = (v4 << 16) + v5 = 0x004a8008 - "v_mov_b32 v1, 0xfffc0003", - "v_mov_b32 v2, 0x0005fffe", - "v_mov_b32 v3, 100", - "v_dot2_i32_i16 v4, v1, v2, v3", - "v_mov_b32 v1, 0x80000001", - "v_mov_b32 v2, 0x00010003", - "v_mov_b32 v3, 5", - "v_dot2_u32_u16 v5, v1, v2, v3", - "v_lshlrev_b32 v4, 16, v4", - "v_add_nc_u32 v10, v4, v5", - # Channel 1 (v11): v_dot4_u32_u8 (wrapping unsigned bytes + clamp saturation) - # v6 = 2*4 + 1*3 + 255*1 + 128*2 + 10 = 532 (0x0214) - # v7 = sat_u32(255*4 + 0xffffff00) = 0xffffffff -> low 16 bits 0xffff - # v11 = (v6 << 16) + (v7 & 0xffff) = 0x0214ffff - "v_mov_b32 v6, 0x80ff0102", - "v_mov_b32 v7, 0x02010304", - "v_dot4_u32_u8 v6, v6, v7, 10", - "v_mov_b32 v1, 0xffffffff", - "v_mov_b32 v2, 0x01010101", - "v_mov_b32 v3, 0xffffff00", - "v_dot4_u32_u8 v7, v1, v2, v3 clamp", - "v_lshlrev_b32 v6, 16, v6", - "v_and_b32 v7, 0xffff, v7", - "v_add_nc_u32 v11, v6, v7", - # Channel 2 (v12): v_dot8_i32_i4 and v_dot8_u32_u4 - # v8 = 6*2 + 5*1 + 4*2 + 3*1 + 2*2 + 1*1 + (-1)*2 + (-8)*1 + 10 = 33 (0x21) - # v9 = 1*3 + 8*2 + 15*1 + 4 = 38 (0x26) - # v12 = (v8 << 8) + v9 = 0x00002126 - "v_mov_b32 v1, 0x8f123456", - "v_mov_b32 v2, 0x12121212", - "v_mov_b32 v3, 10", - "v_dot8_i32_i4 v8, v1, v2, v3", - "v_mov_b32 v1, 0xf8000001", - "v_mov_b32 v2, 0x12000003", - "v_mov_b32 v3, 4", - "v_dot8_u32_u4 v9, v1, v2, v3", - "v_lshlrev_b32 v8, 8, v8", - "v_add_nc_u32 v12, v8, v9", - # Channel 3 (v13): v_pk_fmac_f16 - # lo: fma(2.0, -1.0, 0.5) = -1.5 (0xbe00) - # hi: fma(-2.0, 1.0, 3.0) = +1.0 (0x3c00) -> 0x3c00be00 - "v_mov_b32 v13, 0x42003800", - "v_mov_b32 v14, 0xc0004000", - "v_mov_b32 v15, 0x3c00bc00", - "v_pk_fmac_f16 v13, v14, v15", - "exp mrt0 v10, v11, v12, v13 done vm", - "s_endpgm", -) -PS_DOT_PK_FMAC_EXPECTED = (0x004A8008, 0x0214FFFF, 0x00002126, 0x3C00BE00) - -DOT_OPS = ( - "v_dot2_i32_i16", - "v_dot2_u32_u16", - "v_dot4_u32_u8", - "v_dot8_i32_i4", - "v_dot8_u32_u4", -) - -# Hardware-measured on RDNA2 gfx1036 (Ryzen 9 7950X3D iGPU, tools/hw_oracle, @aslan2142): -# 60 operand sets as (S0, S1, S2, D, D_clamp). -MEASURED_DOT_GFX1036 = { - "v_dot4_u32_u8": [ - (0x04030201, 0x08070605, 0x00000000, 0x00000046, 0x00000046), - (0x04030201, 0x08070605, 0x000003E8, 0x0000042E, 0x0000042E), - (0x000000FF, 0x00000002, 0x00000000, 0x000001FE, 0x000001FE), - (0xFF000000, 0x02000000, 0x00000000, 0x000001FE, 0x000001FE), - (0x00FF0000, 0x0000FF00, 0x00000000, 0x00000000, 0x00000000), - (0x80808080, 0x7F7F7F7F, 0x00000005, 0x0000FE05, 0x0000FE05), - (0xFFFFFFFF, 0xFFFFFFFF, 0x00000000, 0x0003F804, 0x0003F804), - (0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0x0003F803, 0xFFFFFFFF), - (0xFFFFFFFF, 0xFFFFFFFF, 0x7FFFFFFF, 0x8003F803, 0x8003F803), - (0x01010101, 0x01010101, 0xFFFFFFFC, 0x00000000, 0xFFFFFFFF), - (0x12345678, 0x9ABCDEF0, 0x80000000, 0x8000EC18, 0x8000EC18), - (0x00000000, 0x12345678, 0xDEADBEEF, 0xDEADBEEF, 0xDEADBEEF), - ], - "v_dot2_i32_i16": [ - (0x00020001, 0x00040003, 0x00000000, 0x0000000B, 0x0000000B), - (0x00020001, 0x00040003, 0x000003E8, 0x000003F3, 0x000003F3), - (0x0000FFFF, 0x00000002, 0x00000000, 0xFFFFFFFE, 0xFFFFFFFE), - (0xFFFF0000, 0x00020000, 0x00000000, 0xFFFFFFFE, 0xFFFFFFFE), - (0x80000000, 0x00008000, 0x00000000, 0x00000000, 0x00000000), - (0x80008000, 0x7FFF7FFF, 0x00000000, 0x80010000, 0x80010000), - (0x80008000, 0x80008000, 0x00000000, 0x80000000, 0x7FFFFFFF), - (0x7FFF7FFF, 0x7FFF7FFF, 0x7FFFFFFF, 0xFFFE0001, 0x7FFFFFFF), - (0x80008000, 0x7FFF7FFF, 0x80000000, 0x00010000, 0x80000000), - (0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0x00000001, 0x00000001), - (0x8000FFFF, 0x00017FFF, 0x00000064, 0xFFFF0065, 0xFFFF0065), - (0x00000000, 0x12345678, 0xDEADBEEF, 0xDEADBEEF, 0xDEADBEEF), - ], - "v_dot2_u32_u16": [ - (0x00020001, 0x00040003, 0x00000000, 0x0000000B, 0x0000000B), - (0x00020001, 0x00040003, 0x000003E8, 0x000003F3, 0x000003F3), - (0x0000FFFF, 0x00000002, 0x00000000, 0x0001FFFE, 0x0001FFFE), - (0xFFFF0000, 0x00020000, 0x00000000, 0x0001FFFE, 0x0001FFFE), - (0x80000000, 0x00008000, 0x00000000, 0x00000000, 0x00000000), - (0x80008000, 0x80008000, 0x00000000, 0x80000000, 0x80000000), - (0xFFFFFFFF, 0xFFFFFFFF, 0x00000000, 0xFFFC0002, 0xFFFFFFFF), - (0xFFFF0001, 0xFFFF0001, 0x00000000, 0xFFFE0002, 0xFFFE0002), - (0x00010001, 0x00010001, 0xFFFFFFFF, 0x00000001, 0xFFFFFFFF), - (0x80008000, 0x80008000, 0x7FFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF), - (0x12345678, 0x9ABCDEF0, 0x80000000, 0xD64DC6B0, 0xD64DC6B0), - (0x00000000, 0x12345678, 0xDEADBEEF, 0xDEADBEEF, 0xDEADBEEF), - ], - "v_dot8_i32_i4": [ - (0x87654321, 0x12345678, 0x00000000, 0x00000058, 0x00000058), - (0x76543210, 0x01234567, 0x000003E8, 0x00000420, 0x00000420), - (0x0000000F, 0x00000002, 0x00000000, 0xFFFFFFFE, 0xFFFFFFFE), - (0xF0000000, 0x20000000, 0x00000000, 0xFFFFFFFE, 0xFFFFFFFE), - (0x000000F0, 0x0000000F, 0x00000000, 0x00000000, 0x00000000), - (0x88888888, 0x88888888, 0x00000000, 0x00000200, 0x00000200), - (0x88888888, 0x77777777, 0x00000000, 0xFFFFFE40, 0xFFFFFE40), - (0x77777777, 0x77777777, 0x7FFFFFFF, 0x80000187, 0x7FFFFFFF), - (0x88888888, 0x77777777, 0x80000000, 0x7FFFFE40, 0x80000000), - (0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0x00000007, 0x00000007), - (0xF0F0F0F0, 0x0F0F0F0F, 0x00000000, 0x00000000, 0x00000000), - (0x00000000, 0x12345678, 0xDEADBEEF, 0xDEADBEEF, 0xDEADBEEF), - ], - "v_dot8_u32_u4": [ - (0x87654321, 0x12345678, 0x00000000, 0x00000078, 0x00000078), - (0x76543210, 0x01234567, 0x000003E8, 0x00000420, 0x00000420), - (0x0000000F, 0x00000002, 0x00000000, 0x0000001E, 0x0000001E), - (0xF0000000, 0x20000000, 0x00000000, 0x0000001E, 0x0000001E), - (0x000000F0, 0x0000000F, 0x00000000, 0x00000000, 0x00000000), - (0x88888888, 0x77777777, 0x00000000, 0x000001C0, 0x000001C0), - (0xFFFFFFFF, 0xFFFFFFFF, 0x00000000, 0x00000708, 0x00000708), - (0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0x00000707, 0xFFFFFFFF), - (0xFFFFFFFF, 0xFFFFFFFF, 0x7FFFFFFF, 0x80000707, 0x80000707), - (0x11111111, 0x11111111, 0xFFFFFFF8, 0x00000000, 0xFFFFFFFF), - (0xF0F0F0F0, 0x0F0F0F0F, 0x00000000, 0x00000000, 0x00000000), - (0x00000000, 0x12345678, 0xDEADBEEF, 0xDEADBEEF, 0xDEADBEEF), - ], -} - -# Hardware-measured on RDNA2 gfx1036 in default MODE (HW_REG_MODE = 0x000003C0: round-to-nearest-even, -# f16 denormals kept, IEEE and DX10_CLAMP on), as (S0, S1, D_old, D). -MEASURED_PK_FMAC_DEFAULT_GFX1036 = [ - (0x3C014000, 0x3C034200, 0xBC003C00, 0x1C014700), - (0x3C013C01, 0x3C013C03, 0xBC02BC00, 0x00101C01), - (0x3C013C01, 0x3E003C01, 0x8001BC02, 0x3E010010), - (0x3E013C01, 0x3E013E00, 0x00008001, 0x40823E01), - (0xBE013E01, 0x3E013E01, 0x80000000, 0xC0824082), - (0x0000BE01, 0x3C003E01, 0x80008000, 0x0000C082), - (0x80000000, 0x3C003C00, 0x80008000, 0x80000000), - (0x3C008000, 0xBC003C00, 0x3C008000, 0x00008000), - (0x80003C00, 0x3C00BC00, 0x00003C00, 0x00000000), - (0x7C008000, 0x40003C00, 0x3C000000, 0x7C000000), - (0x7C007C00, 0xC0004000, 0x7C003C00, 0xFE007C00), - (0x7C007C00, 0x0000C000, 0x3C007C00, 0xFE00FE00), - (0x7BFF7C00, 0x40000000, 0x00003C00, 0x7C00FE00), - (0x7E557BFF, 0x3C004000, 0x3C000000, 0x7E557C00), - (0x7C017E55, 0x3C003C00, 0x3C003C00, 0x7E017E55), - (0x3C007C01, 0x3C003C00, 0x7D233C00, 0x7F237E01), - (0x04003C00, 0x38003C00, 0x00007D23, 0x02007F23), - (0x00010400, 0x44003800, 0x00000000, 0x00040200), - (0x00030001, 0x38004400, 0x00000000, 0x00020004), - (0x3C000003, 0x3C003800, 0x64000000, 0x64010002), - (0x44003C00, 0xC2003C00, 0x49006400, 0xC0006401), - (0x40004400, 0x4200C200, 0x3C004900, 0x4700C000), -] - - -def sext(val, width): - mask = (1 << width) - 1 - v = val & mask - return v - (1 << width) if v >> (width - 1) else v - - -def ref_dot(op, s0, s1, acc, clamp=False): - width = 16 if "_dot2_" in op else (8 if "_dot4" in op else 4) - signed = op.endswith(("i16", "i4")) - mask = (1 << width) - 1 - total = sext(acc, 32) if signed else (acc & MASK32) - for off in range(0, 32, width): - a = (s0 >> off) & mask - b = (s1 >> off) & mask - if signed: - a, b = sext(a, width), sext(b, width) - total += a * b - if clamp: - if signed: - total = max(-0x80000000, min(0x7FFFFFFF, total)) - else: - total = max(0, min(0xFFFFFFFF, total)) - return total & MASK32 - - -def h2f(bits): - return struct.unpack("> 16) & 0xFFFF) - lo = ref_pk_fmac_half(lo_s0, s1 & 0xFFFF, dst & 0xFFFF) - hi = ref_pk_fmac_half(hi_s0 & 0xFFFF, (s1 >> 16) & 0xFFFF, (dst >> 16) & 0xFFFF) - return lo, hi - - -def run_batch(cases, op, clamp=False, s0_kind="vgpr", acc_in_s=False): - """Execute up to 4 (s0, s1, acc) cases in one shader and return the list of mrt0 uint32 words.""" - lines = [] - suffix = " clamp" if clamp else "" - for k, (s0, s1, acc) in enumerate(cases): - s1_reg = f"v{8 + k}" - lines.append(f"v_mov_b32 {s1_reg}, {s1 & MASK32:#x}") - if s0_kind == "fimm": - s0_op = repr(s0) if not isinstance(s0, str) else s0 - elif s0_kind == "imm": - s0_op = str(s0) - elif s0_kind == "sgpr": - lines.append(f"s_mov_b32 s{k}, {s0 & MASK32:#x}") - s0_op = f"s{k}" - else: - lines.append(f"v_mov_b32 v{4 + k}, {s0 & MASK32:#x}") - s0_op = f"v{4 + k}" - - if op == "v_pk_fmac_f16": - lines.append(f"v_mov_b32 v{k}, {acc & MASK32:#x}") - lines.append(f"{op} v{k}, {s0_op}, {s1_reg}{suffix}") - else: - if acc_in_s: - lines.append(f"s_mov_b32 s{4 + k}, {acc & MASK32:#x}") - acc_op = f"s{4 + k}" - else: - lines.append(f"v_mov_b32 v{12 + k}, {acc & MASK32:#x}") - acc_op = f"v{12 + k}" - lines.append(f"{op} v{k}, {s0_op}, {s1_reg}, {acc_op}{suffix}") - regs = ", ".join(f"v{k}" for k in range(4)) - lines += [f"exp mrt0 {regs} done vm", "s_endpgm"] - return mrt0_words(translate_lines("ps_dot_pk_batch", lines))[:len(cases)] - - -def run_chunks(cases, op, **kwargs): - out = [] - for i in range(0, len(cases), 4): - chunk = cases[i:i + 4] - padded = chunk + [(0, 0, 0)] * (4 - len(chunk)) - out.extend(run_batch(padded, op, **kwargs)[:len(chunk)]) - return out - - -class DotAndPkFmacTests(unittest.TestCase): - def test_fixture(self): - got = tuple(mrt0_words(translate_lines("ps_dot_pk_fmac", PS_DOT_PK_FMAC_ASM))) - self.assertEqual(got, PS_DOT_PK_FMAC_EXPECTED) - - def test_reference(self): - self.assertEqual(ref_dot("v_dot2_i32_i16", 0x80008000, 0x80008000, 0), 0x80000000) - self.assertEqual(ref_dot("v_dot2_i32_i16", 0x80008000, 0x80008000, 0, clamp=True), 0x7FFFFFFF) - self.assertEqual(ref_dot("v_dot2_i32_i16", 0x80008000, 0x80008000, 0xFFFFFFFF, clamp=True), 0x7FFFFFFF) - self.assertEqual(ref_dot("v_dot2_i32_i16", 0x80008000, 0x80008000, 0xFFFFFFFE, clamp=True), 0x7FFFFFFE) - self.assertEqual(ref_dot("v_dot2_u32_u16", 0x80008000, 0x80008000, 0), 0x80000000) - self.assertEqual(ref_dot("v_dot2_u32_u16", 0xFFFF0000, 0xFFFF0000, 0x00030000), 0x00010001) - self.assertEqual(ref_dot("v_dot2_u32_u16", 0xFFFF0000, 0xFFFF0000, 0x00030000, clamp=True), 0xFFFFFFFF) - self.assertEqual(ref_dot("v_dot4_u32_u8", 0x80FF017F, 0x0102FE01, 10), 127 + 254 + 510 + 128 + 10) - self.assertEqual(ref_dot("v_dot8_i32_i4", 0x8F000007, 0x11000008, 0), (7 * (-8) + (-1) * 1 + (-8) * 1) & MASK32) - self.assertEqual(ref_dot("v_dot8_u32_u4", 0x8F000007, 0x11000008, 0), 7 * 8 + 15 * 1 + 8 * 1) - self.assertEqual(ref_pk_fmac_f16(0xC0004000, 0x3C00BC00, 0x42003800), (0xBE00, 0x3C00)) - - def test_dot2_values_and_clamp(self): - # Signed product sum (-32768)^2 + (-32768)^2 = +2^31 crosses INT32_MAX before adding acc. - edge_cases = [ - (0x80008000, 0x80008000, 0), - (0x80008000, 0x80008000, 1), - (0x80008000, 0x80008000, 0xFFFFFFFF), # +2^31 - 1 == INT32_MAX (not overflowed) - (0x80008000, 0x80008000, 0xFFFFFFFE), # +2^31 - 2 == 0x7ffffffe - (0x80008000, 0x80008000, 0x80000000), # +2^31 + INT32_MIN == 0 - (0x80008000, 0x7FFF7FFF, 0x80000000), # -0x7fff0000 + INT32_MIN -> underflow - (0x80008000, 0x7FFF7FFF, 0x80010000), # exact INT32_MIN (not overflowed) - (0x80008000, 0x7FFF7FFF, 0x8000FFFE), # INT32_MIN - 2 -> underflow - (0xFFFF8000, 0xFFFF8000, 0x7FFFFFFF), - (0xFFFFFFFF, 0xFFFFFFFF, 0x00020000), # u16 wrap & clamp boundary - (0xFFFF0000, 0xFFFF0000, 0x0001FFFE), # exact 0xffffffff for u16 - (0xFFFF0000, 0xFFFF0000, 0x0001FFFF), # 0x100000000 -> clamp 0xffffffff - ] - for op in ("v_dot2_i32_i16", "v_dot2_u32_u16"): - for clamp in (False, True): - got = run_chunks(edge_cases, op, clamp=clamp) - want = [ref_dot(op, s0, s1, acc, clamp=clamp) for s0, s1, acc in edge_cases] - with self.subTest(op=op, clamp=clamp): - self.assertEqual(got, want) - - def test_dot4_u32_u8_values_and_clamp(self): - cases = [ - (0x80FF017F, 0x01010101, 0), - (0x80000000, 0x01000000, 0x7FFFFFFF), - (0x00800000, 0x00010000, 0x80000000), - (0x0000FF00, 0x00000200, 0xFFFFFFFF), - (0x00000080, 0x00000080, 0x7FFFC000), - (0xFFFFFFFF, 0xFFFFFFFF, 0xFFFC03FC), # exact 0xffffffff unsigned - (0xFFFFFFFF, 0xFFFFFFFF, 0xFFFC03FD), # unsigned overflow -> 0xffffffff - (0xFFFFFFFF, 0x00000001, 0xFFFFFF00), # 255 + 0xffffff00 = 0xffffffff exact unsigned - (0xFFFFFFFF, 0x00000001, 0xFFFFFF01), # 255 + 0xffffff01 -> overflow clamp - (0x12345678, 0x9ABCDEF0, 0), - (0x80808080, 0x80808080, 0xFFFE0000), - (0xFF00FF00, 0x01000100, 42), - ] - for clamp in (False, True): - got = run_chunks(cases, "v_dot4_u32_u8", clamp=clamp) - want = [ref_dot("v_dot4_u32_u8", s0, s1, acc, clamp=clamp) for s0, s1, acc in cases] - with self.subTest(clamp=clamp): - self.assertEqual(got, want) - - def test_dot8_values_and_clamp(self): - cases = [ - (0x80000000, 0x10000000, 0), - (0x0F000000, 0x02000000, 0x7FFFFFFF), - (0x00700000, 0x00800000, 0x80000000), - (0x00080000, 0x00080000, 0x7FFFFFC0), - (0x0000F000, 0x0000F000, 0xFFFFFFFF), - (0x00000900, 0x00000500, 100), - (0x00000080, 0x00000070, 0x80000037), - (0x0000000F, 0x0000000E, 0xFFFFFF2E), # u4: 15*14 = 210, + 0xffffff2e == 0x100000000 - (0x88888888, 0x88888888, 0x7FFFFE00), # 512 + (2^31 - 512) == 2^31 -> sat 0x7fffffff - (0x88888888, 0x77777777, 0x80000100), # -448 + (INT32_MIN + 256) == INT32_MIN - 192 -> sat INT32_MIN - (0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFF8F7), # 8*225 = 1800, + 0xfffff8f7 == 0xffffffff exact u4 - (0x12345678, 0xFEDCBA98, 42), - ] - for op in ("v_dot8_i32_i4", "v_dot8_u32_u4"): - for clamp in (False, True): - got = run_chunks(cases, op, clamp=clamp) - want = [ref_dot(op, s0, s1, acc, clamp=clamp) for s0, s1, acc in cases] - with self.subTest(op=op, clamp=clamp): - self.assertEqual(got, want) - - def test_measured_dot_gfx1036(self): - for op, rows in MEASURED_DOT_GFX1036.items(): - cases = [(s0, s1, s2) for s0, s1, s2, _, _ in rows] - want_plain = [d for _, _, _, d, _ in rows] - want_clamp = [d_clamp for _, _, _, _, d_clamp in rows] - with self.subTest(op=op, clamp=False): - self.assertEqual(run_chunks(cases, op, clamp=False), want_plain) - with self.subTest(op=op, clamp=True): - self.assertEqual(run_chunks(cases, op, clamp=True), want_clamp) - - def test_measured_pk_fmac_default_gfx1036(self): - # Default MODE 0x000003C0: verify both source orders (S0, S1) and (S1, S0). - # Non-NaN halves must match gfx1036 bit-for-bit; NaN halves must produce a quiet f16 NaN - # (SPIR-V UnpackHalf2x16/PackHalf2x16/Fma do not preserve NaN payload bits or sign). - want = [d for _, _, _, d in MEASURED_PK_FMAC_DEFAULT_GFX1036] - cases_ab = [(s0, s1, d_old) for s0, s1, d_old, _ in MEASURED_PK_FMAC_DEFAULT_GFX1036] - cases_ba = [(s1, s0, d_old) for s0, s1, d_old, _ in MEASURED_PK_FMAC_DEFAULT_GFX1036] - for order, cases in (("s0,s1", cases_ab), ("s1,s0", cases_ba)): - got = run_chunks(cases, "v_pk_fmac_f16") - for idx, (g, w) in enumerate(zip(got, want)): - for shift, half_name in ((0, "lo"), (16, "hi")): - gh = (g >> shift) & 0xFFFF - wh = (w >> shift) & 0xFFFF - with self.subTest(order=order, idx=idx, half=half_name): - if (wh & 0x7FFF) > 0x7C00: - self.assertEqual(gh & 0x7E00, 0x7E00, f"expected quiet f16 NaN, got {gh:#06x}") - else: - self.assertEqual(gh, wh) - - def test_sources_and_default_opsel(self): - self.assertEqual(run_batch([(5, 0x00010002, 0x10), (0x00010002, 0x00030004, 10), (0, 0, 0), (0, 0, 0)], - "v_dot2_i32_i16", s0_kind="imm", acc_in_s=True)[:2], - [ref_dot("v_dot2_i32_i16", 5, 0x00010002, 0x10), - ref_dot("v_dot2_i32_i16", 0x00010002, 0x00030004, 10)]) - self.assertEqual(run_batch([(0x80FF0102, 0x01020304, 0x80000010), (0x01020304, 0x05060708, -5), - (0, 0, 0), (0, 0, 0)], - "v_dot4_u32_u8", s0_kind="sgpr", acc_in_s=True)[:2], - [ref_dot("v_dot4_u32_u8", 0x80FF0102, 0x01020304, 0x80000010), - ref_dot("v_dot4_u32_u8", 0x01020304, 0x05060708, -5)]) - # Hardware default is op_sel:[0,0,0] and op_sel_hi:[1,1,1]; writing either or both explicitly matches plain. - lines = [ - "s_mov_b32 s0, 0x00020001", - "v_mov_b32 v1, 0x00040003", - "v_dot2_i32_i16 v2, s0, v1, 0 op_sel:[0,0,0] op_sel_hi:[1,1,1]", # 1*3 + 2*4 = 11 - "v_dot2_u32_u16 v3, s0, v1, 5 op_sel_hi:[1,1,1]", # 1*3 + 2*4 + 5 = 16 - "s_mov_b32 s1, 0x01020304", - "v_mov_b32 v4, 0x01000100", - "v_dot4_u32_u8 v5, s1, v4, 7 op_sel:[0,0,0] op_sel_hi:[1,1,1]", # 3*1 + 1*1 + 7 = 11 - "v_dot8_i32_i4 v6, s1, v4, 3 op_sel:[0,0,0]", # 3*1 + 1*1 + 3 = 7 - "exp mrt0 v2, v3, v5, v6 done vm", - "s_endpgm", - ] - got = mrt0_words(translate_lines("ps_dot_opsel_default", lines)) - self.assertEqual(got, [11, 16, 11, 7]) - - def test_pk_fmac_f16_values_and_rounding(self): - cases = [ - (0x40003C00, 0x4200C000, 0x38004400), # lo: 1.0*(-2.0)+4.0 = 2.0; hi: 2.0*3.0+0.5 = 6.5 - (0x80000000, 0xBC003C00, 0x80008000), # signed zeros - (0x00100004, 0x40003C00, 0x00018001), # subnormals - (0x7BFF7BFF, 0x40004000, 0x3C00BC00), # overflow to +inf - (0x40003C00, 0x40004000, 0xFC007C00), # +inf / -inf - ] - got = run_chunks(cases, "v_pk_fmac_f16") - for (s0, s1, dst), g in zip(cases, got): - want_lo, want_hi = ref_pk_fmac_f16(s0, s1, dst) - with self.subTest(s0=hex(s0), s1=hex(s1), dst=hex(dst)): - self.assertEqual(g & 0xFFFF, want_lo) - self.assertEqual((g >> 16) & 0xFFFF, want_hi) - - triples = near_tie_triples(random.Random(55), 32) - differing = [t for t in triples if double_rounded(*t) != ref_fma(*t)] - self.assertGreaterEqual(len(differing), 4) - tie_cases = [] - for i in range(0, min(len(differing), 8), 2): - a0, b0, c0 = differing[i] - a1, b1, c1 = differing[i + 1] if i + 1 < len(differing) else differing[i] - tie_cases.append(((a1 << 16) | a0, (b1 << 16) | b0, (c1 << 16) | c0)) - got_ties = run_chunks(tie_cases, "v_pk_fmac_f16") - for (s0, s1, dst), g in zip(tie_cases, got_ties): - want_lo, want_hi = ref_pk_fmac_f16(s0, s1, dst) - with self.subTest(tie=hex(s0)): - self.assertEqual(g & 0xFFFF, want_lo) - self.assertEqual((g >> 16) & 0xFFFF, want_hi) - - def test_pk_fmac_f16_sources_aliasing_and_nan(self): - got_fimm = run_batch([(1.0, 0x42004000, 0x3C003800), (-0.5, 0x3C00C000, 0x40004000), - (0.0, 0, 0), (0.0, 0, 0)], "v_pk_fmac_f16", s0_kind="fimm")[:2] - self.assertEqual(got_fimm, [ - ref_pk_fmac_f16(0x3C00, 0x42004000, 0x3C003800)[0] | (ref_pk_fmac_f16(0x3C00, 0x42004000, 0x3C003800)[1] << 16), - ref_pk_fmac_f16(0xB800, 0x3C00C000, 0x40004000)[0] | (ref_pk_fmac_f16(0xB800, 0x3C00C000, 0x40004000)[1] << 16), - ]) - - lines = [ - "s_mov_b32 s0, 0x40003c00", # lo=1.0, hi=2.0 - "v_mov_b32 v0, 0x3c004000", # lo=2.0, hi=1.0 - "v_mov_b32 v1, 0xc0003800", # lo=0.5, hi=-2.0 - "v_pk_fmac_f16 v0, s0, v1", # lo=1.0*0.5+2.0=2.5 (0x4100), hi=2.0*(-2.0)+1.0=-3.0 (0xc200) - "v_mov_b32 v2, 0x38004000", # lo=2.0, hi=0.5 - "v_pk_fmac_f16 v2, v2, v2", # lo=2.0*2.0+2.0=6.0 (0x4600), hi=0.5*0.5+0.5=0.75 (0x3a00) - "v_mov_b32 v3, 0x3c007e01", # lo=NaN, hi=1.0 - "v_pk_fmac_f16 v3, 0x3c003c00, v1", # lo=NaN, hi=1.0*(-2.0)+1.0=-1.0 (0xbc00) - "v_and_b32 v4, 0xffff, v3", - "v_lshrrev_b32 v5, 16, v3", - "exp mrt0 v0, v2, v4, v5 done vm", - "s_endpgm", - ] - got = mrt0_words(translate_lines("ps_pk_fmac_alias", lines)) - self.assertEqual(got[0], 0xC2004100) - self.assertEqual(got[1], 0x3A004600) - self.assertGreater(got[2] & 0x7FFF, 0x7C00) - self.assertEqual(got[3], 0xBC00) - - def test_dpp_form_translates(self): - spv = translate_lines("ps_pk_fmac_dpp", [ - "v_pk_fmac_f16_dpp v3, v4, v5 dpp8:[1,2,3,4,5,6,7,0] fi:1", - "exp mrt0 v3, v3, v3, v3 done vm", - "s_endpgm", - ]) - self.assertIn("OpGroupNonUniform", spv) - - def test_read_before_write_and_rw_sets(self): - insns_fmac = [shader_ir.parse_line(ln) for ln in ( - "v_pk_fmac_f16 v7, v1, v2", - "v_mov_b32 v9, 1", - "v_pk_fmac_f16 v9, v1, v2", - )] - self.assertEqual(rdna2spirv.read_before_write_vgprs(insns_fmac), {1, 2, 7}) - rr, ww = rdna2spirv.reg_reads_writes([insns_fmac[0]]) - self.assertEqual(rr, {1, 2, 7}) - self.assertEqual(ww, {7}) - - insns_dpp = [shader_ir.parse_line("v_pk_fmac_f16_dpp v10, v1, v2 quad_perm:[1,0,3,2]")] - self.assertEqual(rdna2spirv.read_before_write_vgprs(insns_dpp), {1, 2, 10}) - - def test_random_sweep(self): - rng = random.Random(0xD0716) - for op in DOT_OPS: - cases = [(rng.getrandbits(32), rng.getrandbits(32), rng.getrandbits(32)) for _ in range(16)] - for clamp in (False, True): - got = run_chunks(cases, op, clamp=clamp) - want = [ref_dot(op, s0, s1, acc, clamp=clamp) for s0, s1, acc in cases] - with self.subTest(op=op, clamp=clamp): - self.assertEqual(got, want) - - pk_cases = [] - for _ in range(24): - def rand_f16(): - e = rng.choice([0, 1, 10, 14, 15, 16, 17, 20]) - return (rng.getrandbits(1) << 15) | (e << 10) | rng.getrandbits(10) - s0 = (rand_f16() << 16) | rand_f16() - s1 = (rand_f16() << 16) | rand_f16() - dst = (rand_f16() << 16) | rand_f16() - pk_cases.append((s0, s1, dst)) - got_pk = run_chunks(pk_cases, "v_pk_fmac_f16") - for (s0, s1, dst), g in zip(pk_cases, got_pk): - want_lo, want_hi = ref_pk_fmac_f16(s0, s1, dst) - self.assertEqual(g & 0xFFFF, want_lo) - self.assertEqual((g >> 16) & 0xFFFF, want_hi) - - def test_rejected_forms(self): - bad_lines = ( - "v_dot2_i32_i16 v0, v1, v2, v3 op_sel:[1,0,0]", - "v_dot2_i32_i16 v0, v1, v2, v3 op_sel_hi:[0,0,0]", - "v_dot2_i32_i16 v0, v1, v2, v3 op_sel:[0,0,0] op_sel_hi:[0,0,0]", - "v_dot2_i32_i16 v0, v1, v2, v3 op_sel_hi:[0,1,1]", - "v_dot2_i32_i16 v0, v1, v2, v3 op_sel_hi:[1,0,1]", - "v_dot2_i32_i16 v0, v1, v2, v3 op_sel_hi:[1,1,0]", - "v_dot2_u32_u16 v0, v1, v2, v3 op_sel_hi:[0,0,0]", - "v_dot4_u32_u8 v0, v1, v2, v3 op_sel:[1,0,0]", - "v_dot4_u32_u8 v0, v1, v2, v3 op_sel_hi:[0,0,0]", - "v_dot4_u32_u8 v0, v1, v2, v3 op_sel_hi:[0,1,0]", - "v_dot4_u32_u8 v0, v1, v2, v3 neg_lo:[1,0,0]", - "v_dot2_i32_i16 v0, v1, v2, v3 neg_lo:[0,0,1] neg_hi:[0,0,1]", - "v_dot4_u32_u8 v0, -v1, v2, v3", - "v_dot2_i32_i16 v0, |v1|, v2, v3", - "v_dot8_i32_i4 v0, v1, v2, v3 mul:2", - "v_dot4_u32_u8_dpp v0, v1, v2, v3 quad_perm:[1,0,3,2]", - "v_dot4_u32_u8_sdwa v0, v1, v2, v3 src0_sel:DWORD", - "v_pk_fmac_f16 v0, v1, v2 clamp", - "v_pk_fmac_f16 v0, v1, v2 mul:2", - "v_pk_fmac_f16 v0, v1, v2 op_sel:[0,0,0]", - "v_pk_fmac_f16 v0, -v1, v2", - "v_pk_fmac_f16 v0, |v1|, v2", - "v_pk_fmac_f16 vcc_lo, v1, v2", - "v_pk_fmac_f16_sdwa v0, v1, v2 src0_sel:DWORD", - ) - for line in bad_lines: - with self.subTest(line=line): - with self.assertRaises(rdna2spirv.Unsupported): - translate_lines("ps_dot_pk_bad", [ - "v_mov_b32 v1, 1", "v_mov_b32 v2, 2", "v_mov_b32 v3, 3", line, - "exp mrt0 v0, v0, v0, v0 done vm", "s_endpgm", - ]) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_alu_dotc.py b/tests/semantic/test_alu_dotc.py deleted file mode 100644 index a7e01217b..000000000 --- a/tests/semantic/test_alu_dotc.py +++ /dev/null @@ -1,172 +0,0 @@ -"""Semantic interpreter and spirv-val tests for RDNA2 v_dot2c_i32_i16 and v_dot8c_i32_i4. - -v_dot2c_i32_i16 computes D = S0.i16[0]*S1.i16[0] + S0.i16[1]*S1.i16[1] + D (VOP2/VOP3). -v_dot8c_i32_i4 computes D = sum_{k=0..7}(S0.i4[k]*S1.i4[k]) + D (VOP2/VOP3). -Both wrap at 32 bits by default and saturate to [INT32_MIN, INT32_MAX] with VOP3 clamp. -""" -import os -import random -import shutil -import struct -import subprocess -import sys -import tempfile -import unittest -import warnings - -HERE = os.path.dirname(os.path.abspath(__file__)) -ROOT = os.path.dirname(os.path.dirname(HERE)) -TOOLS_DIR = os.environ.get("LEONIDA_TOOLS_DIR") or os.path.join(ROOT, "tools") - -sys.dont_write_bytecode = True -sys.path.insert(0, TOOLS_DIR) -sys.path.insert(0, HERE) - -import rdna2spirv # noqa: E402 -import spirv_mini_interp as si # noqa: E402 - -STUB_DXBC = b"DXBC" + bytes(24) + struct.pack(" int: - mask = (1 << width) - 1 - v = val & mask - return v - (1 << width) if v & (1 << (width - 1)) else v - - -def ref_dotc(x: int, y: int, acc: int, width: int, clamp: bool) -> int: - total = sext(acc, 32) - for off in range(0, 32, width): - total += sext(x >> off, width) * sext(y >> off, width) - if clamp: - total = max(INT32_MIN, min(INT32_MAX, total)) - return total & M32 - - -_TMP_DIR = None -_SRC_PATH = None - - -def setUpModule(): - global _TMP_DIR, _SRC_PATH - _TMP_DIR = tempfile.TemporaryDirectory() - disasm_dir = os.path.join(_TMP_DIR.name, "disasm") - os.mkdir(disasm_dir) - _SRC_PATH = os.path.join(disasm_dir, "ps_dotc.s") - with open(os.path.join(_TMP_DIR.name, "ps_dotc.dxbc"), "wb") as f: - f.write(STUB_DXBC) - - -def tearDownModule(): - global _TMP_DIR - if _TMP_DIR is not None: - _TMP_DIR.cleanup() - _TMP_DIR = None - - -def translate_lines(lines): - if _TMP_DIR is None: - setUpModule() - asm = ( - "; test_dotc\n" - + "".join(f"\t{ln}\n" for ln in lines) - + "\texp mrt0 v0, v1, v2, v3 done vm\n\ts_endpgm\n" - ) - with open(_SRC_PATH, "w", encoding="utf-8") as f: - f.write(asm) - with warnings.catch_warnings(): - warnings.simplefilter("ignore", ResourceWarning) - return rdna2spirv.translate(_SRC_PATH) - - -def validate_spirv(spv_text: str): - spirv_as = shutil.which("spirv-as") - spirv_val = shutil.which("spirv-val") - if not spirv_as or not spirv_val: - return - with tempfile.TemporaryDirectory() as d: - asm_p = os.path.join(d, "s.spvasm") - bin_p = os.path.join(d, "s.spv") - with open(asm_p, "w", encoding="utf-8") as f: - f.write(spv_text) - r1 = subprocess.run([spirv_as, "--target-env", "vulkan1.2", asm_p, "-o", bin_p], capture_output=True, text=True) - if r1.returncode != 0: - raise AssertionError(f"spirv-as failed: {r1.stderr}") - r2 = subprocess.run([spirv_val, "--target-env", "vulkan1.2", bin_p], capture_output=True, text=True) - if r2.returncode != 0: - raise AssertionError(f"spirv-val failed: {r2.stderr}") - - -def run_dotc(insn: str, x: int, y: int, acc: int) -> int: - spv = translate_lines([ - f"v_mov_b32 v1, {x & M32:#x}", - f"v_mov_b32 v2, {y & M32:#x}", - f"v_mov_b32 v0, {acc & M32:#x}", - insn, - ]) - return si.run_fragment(spv)["%out_mrt0"][0] - - -class DotcTests(unittest.TestCase): - def test_dot2c_i32_i16_edges_wrap_and_clamp(self): - cases = ( - (0x00020003, 0x00040005, 10), # 2*4 + 3*5 + 10 = 33 - (0xFFFE0003, 0x0004FFFB, 0xFFFFFFF0), # (-2)*4 + 3*(-5) - 16 = -39 - (0x80008000, 0x80008000, 0), # (-32768)^2 * 2 = 2^31 (wraps to INT32_MIN, clamps to INT32_MAX) - (0x80008000, 0x80008000, 0x7FFFFFFF), # large positive overflow - (0x80008000, 0x7FFF7FFF, 0x80000000), # large negative overflow - ) - for x, y, acc in cases: - with self.subTest(x=hex(x), y=hex(y), acc=hex(acc)): - self.assertEqual(run_dotc("v_dot2c_i32_i16_e32 v0, v1, v2", x, y, acc), ref_dotc(x, y, acc, 16, False)) - self.assertEqual(run_dotc("v_dot2c_i32_i16_e64 v0, v1, v2 clamp", x, y, acc), ref_dotc(x, y, acc, 16, True)) - - def test_dot8c_i32_i4_edges_wrap_and_clamp(self): - cases = ( - (0x12345678, 0x87654321, 100), - (0x88888888, 0x88888888, 0x7FFFFFF0), # 8 * (-8)*(-8) = +512 -> positive overflow - (0x88888888, 0x77777777, 0x80000010), # 8 * (-8)*(7) = -448 -> negative overflow - (0xFFFFFFFF, 0x11111111, 0), # 8 * (-1)*(1) = -8 - ) - for x, y, acc in cases: - with self.subTest(x=hex(x), y=hex(y), acc=hex(acc)): - self.assertEqual(run_dotc("v_dot8c_i32_i4_e32 v0, v1, v2", x, y, acc), ref_dotc(x, y, acc, 4, False)) - self.assertEqual(run_dotc("v_dot8c_i32_i4_e64 v0, v1, v2 clamp", x, y, acc), ref_dotc(x, y, acc, 4, True)) - - def test_seeded_sweep(self): - rng = random.Random(0xD07C) - for _ in range(30): - x, y, acc = rng.getrandbits(32), rng.getrandbits(32), rng.getrandbits(32) - for op, width in (("v_dot2c_i32_i16", 16), ("v_dot8c_i32_i4", 4)): - self.assertEqual(run_dotc(f"{op}_e32 v0, v1, v2", x, y, acc), ref_dotc(x, y, acc, width, False)) - self.assertEqual(run_dotc(f"{op}_e64 v0, v1, v2 clamp", x, y, acc), ref_dotc(x, y, acc, width, True)) - - def test_aliasing_sgpr_and_spirv_val(self): - spv = translate_lines([ - "s_mov_b32 s4, 0x00020003", - "v_mov_b32 v0, 0x00040005", - "v_dot2c_i32_i16_e32 v0, s4, v0", - "v_dot8c_i32_i4_e64 v0, 0x11111111, v0 clamp", - ]) - validate_spirv(spv) - # First op: s4=(2,3), v0=(4,5), acc=0x00040005 -> 2*4 + 3*5 + 0x00040005 - mid = ref_dotc(0x00020003, 0x00040005, 0x00040005, 16, False) - want = ref_dotc(0x11111111, mid, mid, 4, True) - self.assertEqual(si.run_fragment(spv)["%out_mrt0"][0], want) - - def test_rejects_unsupported_modifiers(self): - for line in ( - "v_dot2c_i32_i16_e64 v0, v1, v2 op_sel:[0,0,0]", - "v_dot8c_i32_i4_e64 v0, -v1, v2", - "v_dot2c_i32_i16_e64 v0, |v1|, v2", - ): - with self.subTest(line=line): - with self.assertRaises(rdna2spirv.Unsupported): - translate_lines([line]) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_alu_exp_f32.py b/tests/semantic/test_alu_exp_f32.py deleted file mode 100644 index 9b3b211b1..000000000 --- a/tests/semantic/test_alu_exp_f32.py +++ /dev/null @@ -1,145 +0,0 @@ -"""Semantic translation tests for RDNA2 32-bit base-2 exponential v_exp_f32. - -Translates a synthetic pixel-shader listing through tools/rdna2spirv.translate() --> SPIR-V -> tests/semantic/spirv_mini_interp.py and compares the result against -a plain-Python reference: 2.0 ** x for finite x within the float range. - -Covers: - - Exact values: exp2(0) = 1, exp2(1) = 2, exp2(2) = 4, exp2(-1) = 0.5 - - exp2(1.5) with tolerance 1e-6 - - exp2(+inf) = +inf - - Reference comparison across varied bit patterns - - 50 randomized cases vs reference - - Negative control: result differs from input for non-trivial cases -""" -import math -import os -import struct -import sys -import tempfile -import unittest -import warnings -import random - -HERE = os.path.dirname(os.path.abspath(__file__)) -ROOT = os.path.dirname(os.path.dirname(HERE)) -TOOLS_DIR = os.environ.get("LEONIDA_TOOLS_DIR") or os.path.join(ROOT, "tools") - -sys.dont_write_bytecode = True -if TOOLS_DIR not in sys.path: - sys.path.insert(0, TOOLS_DIR) -if HERE not in sys.path: - sys.path.insert(0, HERE) - -import rdna2spirv # noqa: E402 -import spirv_mini_interp as si # noqa: E402 - -M32 = 0xFFFFFFFF -STUB_DXBC = b"DXBC" + bytes(24) + struct.pack(" 1.0 clamp to +1.0 (0x3C00). - Values in [0.0, 1.0] are preserved exactly as rounded to binary16. -- Destination register half preservation on scalar f16 ops: GFX10 f16 ops keep the untouched half. -- VOP3 op_sel destination bit and input modifiers (negation, absolute value). -- Standard library Python only; zero game data. -""" -from __future__ import annotations - -import gc -import math -import os -import struct -import sys -import tempfile -import unittest -import warnings -from fractions import Fraction - -HERE = os.path.dirname(os.path.abspath(__file__)) -ROOT = os.path.dirname(os.path.dirname(HERE)) -TOOLS_DIR = os.environ.get("LEONIDA_TOOLS_DIR") or os.path.join(ROOT, "tools") - -sys.dont_write_bytecode = True -if TOOLS_DIR not in sys.path: - sys.path.insert(0, TOOLS_DIR) -if HERE not in sys.path: - sys.path.insert(0, HERE) - -import rdna2spirv # noqa: E402 -import spirv_mini_interp as si # noqa: E402 -from support import STUB_DXBC # noqa: E402 - -MASK16 = 0xFFFF -MASK32 = 0xFFFFFFFF -OLD = 0xA55A5AA5 -VSHARP_CS = [0, 0, 0xFFFFFFFF, 0x31016FAC] - -# IEEE 754 binary16 constants -POS_ZERO = 0x0000 # +0.0 -NEG_ZERO = 0x8000 # -0.0 -POS_ONE = 0x3C00 # +1.0 -NEG_ONE = 0xBC00 # -1.0 -POS_HALF = 0x3800 # +0.5 -NEG_HALF = 0xB800 # -0.5 -POS_QUARTER = 0x3400 # +0.25 -NEG_QUARTER = 0xB400 # -0.25 -POS_THREE_QUARTERS = 0x3A00 # +0.75 -NEG_THREE_QUARTERS = 0xBA00 # -0.75 -POS_TWO = 0x4000 # +2.0 -NEG_TWO = 0xC000 # -2.0 -POS_THREE = 0x4200 # +3.0 -NEG_THREE = 0xC200 # -3.0 -POS_FOUR = 0x4400 # +4.0 -POS_INF = 0x7C00 # +inf -NEG_INF = 0xFC00 # -inf -QNAN_CANONICAL = 0x7E00 # canonical quiet NaN -QNAN_ALT = 0x7E11 # quiet NaN with payload -SNAN = 0x7D00 # signaling NaN -NEG_QNAN = 0xFE22 # negative quiet NaN - -# Subnormal binary16 constants -POS_MIN_SUBNORM = 0x0001 # +2^-24 (~5.96e-8), smallest positive subnormal -POS_MAX_SUBNORM = 0x03FF # largest positive subnormal (~6.097e-5) -NEG_MIN_SUBNORM = 0x8001 # -2^-24, smallest negative subnormal -NEG_MAX_SUBNORM = 0x83FF # largest negative subnormal - -# Normal binary16 boundaries -POS_MIN_NORMAL = 0x0400 # +2^-14 (~6.104e-5), smallest positive normal -POS_MAX_NORMAL = 0x7BFF # +65504.0, largest finite binary16 -NEG_MAX_NORMAL = 0xFBFF # -65504.0 - - -def f16_to_float(bits: int) -> float: - """Decode 16-bit integer as IEEE 754 half-precision float.""" - return struct.unpack(" int: - """Encode float into IEEE 754 half-precision bits.""" - if math.isnan(f): - return QNAN_CANONICAL - try: - return struct.unpack(" 0 else NEG_INF - - -def is_nan16(bits: int) -> bool: - """Check if 16-bit integer represents a binary16 NaN.""" - bits &= MASK16 - return (bits & 0x7C00) == 0x7C00 and (bits & 0x03FF) != 0 - - -def is_inf16(bits: int) -> bool: - """Check if 16-bit integer represents a binary16 infinity.""" - bits &= MASK16 - return (bits & 0x7FFF) == 0x7C00 - - -def is_subnormal16(bits: int) -> bool: - """Check if 16-bit integer represents a binary16 subnormal.""" - bits &= MASK16 - return (bits & 0x7C00) == 0 and (bits & 0x03FF) != 0 - - -def f16_bits_to_fraction(bits: int) -> Fraction: - """Decode finite binary16 bit pattern into exact Fraction.""" - bits &= MASK16 - exp = (bits >> 10) & 0x1F - mant = bits & 0x03FF - sign = -1 if (bits & 0x8000) else 1 - if exp == 0: - if mant == 0: - return Fraction(0) - return Fraction(sign * mant, 1 << 24) - return Fraction(sign * ((1 << 10) | mant)) * (Fraction(2) ** (exp - 25)) - - -def fraction_to_f16(x: Fraction, *, flush_denorms: bool = False) -> int: - """Round an exact Fraction to IEEE 754 binary16 bits (round to nearest even).""" - if x == 0: - return POS_ZERO - sign = NEG_ZERO if x < 0 else POS_ZERO - x = abs(x) - - if flush_denorms and x < Fraction(1, 1 << 14): - return sign - - lo, hi = 0, 0x7C00 - while lo < hi: - mid = (lo + hi) // 2 - val = Fraction(f16_to_float(mid)) if mid < 0x7C00 else Fraction(10 ** 9) - if val >= x: - hi = mid - else: - lo = mid + 1 - - if lo == 0x7C00: - return sign | (POS_INF if x >= 65520 else POS_MAX_NORMAL) - - above = lo - if lo == 0 or Fraction(f16_to_float(above)) == x: - return sign | above - - below = lo - 1 - da = Fraction(f16_to_float(above)) - x - db = x - Fraction(f16_to_float(below)) - if da < db: - pick = above - elif db < da: - pick = below - else: - pick = above if (above % 2 == 0) else below - return sign | pick - - -def apply_src_mods(bits: int, *, abs_: bool = False, neg: bool = False) -> int: - """Apply VOP3 source modifiers (abs applied before neg).""" - bits &= MASK16 - if abs_: - bits &= 0x7FFF - if neg: - bits ^= 0x8000 - return bits - - -def ref_fma_f16( - a_bits: int, - b_bits: int, - c_bits: int, - *, - clamp: bool = False, - abs_s0: bool = False, - neg_s0: bool = False, - abs_s1: bool = False, - neg_s1: bool = False, - abs_s2: bool = False, - neg_s2: bool = False, - flush_denorms: bool = False, -) -> int: - """Independent reference oracle for half-precision FMA (a * b + c) with clamp saturation. - - Implements exact IEEE 754 binary16 arithmetic, round to nearest even, and - optional clamp saturation to [0.0, 1.0]. - """ - a = apply_src_mods(a_bits, abs_=abs_s0, neg=neg_s0) - b = apply_src_mods(b_bits, abs_=abs_s1, neg=neg_s1) - c = apply_src_mods(c_bits, abs_=abs_s2, neg=neg_s2) - - # NaN operands - if is_nan16(a) or is_nan16(b) or is_nan16(c): - return QNAN_CANONICAL - - a_is_zero = (a & 0x7FFF) == 0 - b_is_zero = (b & 0x7FFF) == 0 - c_is_zero = (c & 0x7FFF) == 0 - - a_is_inf = is_inf16(a) - b_is_inf = is_inf16(b) - c_is_inf = is_inf16(c) - - # 0 * inf or inf * 0 is invalid -> NaN - if (a_is_zero and b_is_inf) or (a_is_inf and b_is_zero): - return QNAN_CANONICAL - - prod_sign = (a ^ b) & 0x8000 - - # Infinite product - if a_is_inf or b_is_inf: - if c_is_inf: - c_sign = c & 0x8000 - if prod_sign != c_sign: - # (+inf) + (-inf) -> NaN - return QNAN_CANONICAL - res = prod_sign | POS_INF - if clamp: - return POS_ZERO if prod_sign else POS_ONE - return res - - # Finite product with infinite addend - if c_is_inf: - c_sign = c & 0x8000 - if clamp: - return POS_ZERO if c_sign else POS_ONE - return c - - # Denormal input flush if requested - if flush_denorms: - if is_subnormal16(a): - a = a & 0x8000 - a_is_zero = True - if is_subnormal16(b): - b = b & 0x8000 - b_is_zero = True - if is_subnormal16(c): - c = c & 0x8000 - c_is_zero = True - - # Exact product is zero - if a_is_zero or b_is_zero: - if c_is_zero: - c_sign = c & 0x8000 - # -0 + -0 = -0; all other combinations in RNE produce +0 - res = NEG_ZERO if (prod_sign and c_sign) else POS_ZERO - if clamp: - return POS_ZERO - return res - # Product is zero, result is c - res = c - if clamp: - if (res & 0x8000) and (res != NEG_ZERO): - return POS_ZERO - if res == NEG_ZERO: - return POS_ZERO - # If c > 1.0 -> clamp to 1.0 - if f16_bits_to_fraction(c) > Fraction(1): - return POS_ONE - if f16_bits_to_fraction(c) < Fraction(0): - return POS_ZERO - return res - return res - - # Finite non-zero operands: compute exact rational a * b + c - qa = f16_bits_to_fraction(a) - qb = f16_bits_to_fraction(b) - qc = f16_bits_to_fraction(c) - exact = qa * qb + qc - - if exact == 0: - # Exact cancellation to zero produces +0.0 in round-to-nearest - res = POS_ZERO - else: - res = fraction_to_f16(exact, flush_denorms=flush_denorms) - - if clamp: - if (res & 0x8000) != 0: - return POS_ZERO - if is_inf16(res) or f16_bits_to_fraction(res) > Fraction(1): - return POS_ONE - return res - - return res - - -def merge_half(val: int, dst_hi: int, old: int = OLD) -> int: - """Merge a 16-bit result into low or high half of 32-bit register, keeping untouched half.""" - val &= MASK16 - return (val << 16) | (old & 0xFFFF) if dst_hi else (old & 0xFFFF0000) | val - - -def pack2(lo: int, hi: int) -> int: - """Pack two 16-bit half-precision values into a 32-bit dword.""" - return ((hi & MASK16) << 16) | (lo & MASK16) - - -def ref_pk_fma_f16( - v1: int, - v2: int, - v3: int, - *, - clamp: bool = False, - op_sel: tuple[int, int, int] = (0, 0, 0), - op_sel_hi: tuple[int, int, int] = (1, 1, 1), - neg_lo: tuple[int, int, int] = (0, 0, 0), - neg_hi: tuple[int, int, int] = (0, 0, 0), - flush_denorms: bool = False, -) -> int: - """Reference oracle for packed half-precision SIMD FMA (v_pk_fma_f16). - - RDNA2 VOP3P packed half-precision FMA: - Result lo: source i takes its half from op_sel[i] (0 = lo, 1 = hi), negated by neg_lo[i]. - Result hi: source i takes its half from op_sel_hi[i] (0 = lo, 1 = hi), negated by neg_hi[i]. - Both halves independently evaluate FMA and optional clamp. - """ - def extract_half(val: int, half_sel: int, neg: int) -> int: - h = (val >> 16) if half_sel else (val & MASK16) - return apply_src_mods(h, neg=bool(neg)) - - a_lo = extract_half(v1, op_sel[0], neg_lo[0]) - b_lo = extract_half(v2, op_sel[1], neg_lo[1]) - c_lo = extract_half(v3, op_sel[2], neg_lo[2]) - res_lo = ref_fma_f16(a_lo, b_lo, c_lo, clamp=clamp, flush_denorms=flush_denorms) - - a_hi = extract_half(v1, op_sel_hi[0], neg_hi[0]) - b_hi = extract_half(v2, op_sel_hi[1], neg_hi[1]) - c_hi = extract_half(v3, op_sel_hi[2], neg_hi[2]) - res_hi = ref_fma_f16(a_hi, b_hi, c_hi, clamp=clamp, flush_denorms=flush_denorms) - - return pack2(res_lo, res_hi) - - -_TMP_DIR = None -_PS_PATH = None -_CS_PATH = None -_CS_FSSM = None - - -def _make_fssm(rsrc2: int, group: tuple[int, int, int]) -> bytes: - header = bytearray(0x148) - struct.pack_into("<4I", header, 0x138, rsrc2, *group) - return bytes(header) - - -def setUpModule(): - global _TMP_DIR, _PS_PATH, _CS_PATH, _CS_FSSM - _TMP_DIR = tempfile.TemporaryDirectory() - disasm_dir = os.path.join(_TMP_DIR.name, "disasm") - fssm_dir = os.path.join(_TMP_DIR.name, "fssm") - os.mkdir(disasm_dir) - os.mkdir(fssm_dir) - _PS_PATH = os.path.join(disasm_dir, "ps_alu_f16_fma.s") - _CS_PATH = os.path.join(disasm_dir, "cs_alu_f16_fma.s") - _CS_FSSM = os.path.join(fssm_dir, "cs_alu_f16_fma.fssm") - with open(os.path.join(_TMP_DIR.name, "ps_alu_f16_fma.dxbc"), "wb") as f: - f.write(STUB_DXBC) - with open(os.path.join(_TMP_DIR.name, "cs_alu_f16_fma.dxbc"), "wb") as f: - f.write(STUB_DXBC) - - -def tearDownModule(): - global _TMP_DIR - if _TMP_DIR is not None: - _TMP_DIR.cleanup() - _TMP_DIR = None - - -def translate_ps(lines: list[str]) -> str: - if _TMP_DIR is None: - setUpModule() - asm = "; test_alu_f16_fma_clamp\n" + "".join(f"\t{ln}\n" for ln in lines) + "\texp mrt0 v0, v0, v0, v0 done vm\n\ts_endpgm\n" - with open(_PS_PATH, "w", encoding="utf-8", newline="\n") as f: - f.write(asm) - with warnings.catch_warnings(): - warnings.simplefilter("ignore", ResourceWarning) - spv = rdna2spirv.translate(_PS_PATH) - gc.collect() - return spv - - -def run_ps(lines: list[str]) -> int: - spv = translate_ps(lines) - return si.run_fragment(spv)["%out_mrt0"][0] - - -def run_op( - op_line: str, - v1: int = 0, - v2: int = 0, - v3: int = 0, - *, - old: int = OLD, - s4: int = 0, - s5: int = 0, - s6: int = 0, -) -> int: - lines = [ - f"v_mov_b32 v0, {old:#x}", - f"v_mov_b32 v1, {v1:#x}", - f"v_mov_b32 v2, {v2:#x}", - f"v_mov_b32 v3, {v3:#x}", - f"s_mov_b32 s4, {s4:#x}", - f"s_mov_b32 s5, {s5:#x}", - f"s_mov_b32 s6, {s6:#x}", - op_line, - ] - return run_ps(lines) - - -# ----------------------------------------------------------------------------- -# Commit 1 Tests: Reference Oracle and Scalar v_fma_f16 with Clamp Saturation -# ----------------------------------------------------------------------------- - -class ReferenceOracleTests(unittest.TestCase): - """Test unit validation of the exact Fraction-based half-precision FMA oracle.""" - - def test_oracle_basic_fma(self): - # 2.0 * 2.0 + 2.0 = 6.0 (0x4600 unclamped; clamped to 1.0 = 0x3C00) - self.assertEqual(ref_fma_f16(POS_TWO, POS_TWO, POS_TWO, clamp=False), 0x4600) - self.assertEqual(ref_fma_f16(POS_TWO, POS_TWO, POS_TWO, clamp=True), POS_ONE) - - # 0.5 * 0.5 + 0.25 = 0.5 (0x3800, inside [0, 1]) - self.assertEqual(ref_fma_f16(POS_HALF, POS_HALF, POS_QUARTER, clamp=False), POS_HALF) - self.assertEqual(ref_fma_f16(POS_HALF, POS_HALF, POS_QUARTER, clamp=True), POS_HALF) - - # -2.0 * 1.0 + 0.5 = -1.5 (0xBE00 unclamped; clamped to +0.0 = 0x0000) - self.assertEqual(ref_fma_f16(NEG_TWO, POS_ONE, POS_HALF, clamp=False), 0xBE00) - self.assertEqual(ref_fma_f16(NEG_TWO, POS_ONE, POS_HALF, clamp=True), POS_ZERO) - - def test_oracle_clamp_edges(self): - # 1.0 * 1.0 + 0.0 = 1.0 (exact upper clamp boundary) - self.assertEqual(ref_fma_f16(POS_ONE, POS_ONE, POS_ZERO, clamp=True), POS_ONE) - - # 0.0 * 0.0 + 0.0 = 0.0 (exact lower clamp boundary) - self.assertEqual(ref_fma_f16(POS_ZERO, POS_ZERO, POS_ZERO, clamp=True), POS_ZERO) - - # Large positive overflow: 65504 * 2.0 + 0 = +inf (clamped to 1.0) - self.assertEqual(ref_fma_f16(POS_MAX_NORMAL, POS_TWO, POS_ZERO, clamp=False), POS_INF) - self.assertEqual(ref_fma_f16(POS_MAX_NORMAL, POS_TWO, POS_ZERO, clamp=True), POS_ONE) - - # Large negative overflow: -65504 * 2.0 + 0 = -inf (clamped to +0.0) - self.assertEqual(ref_fma_f16(NEG_MAX_NORMAL, POS_TWO, POS_ZERO, clamp=False), NEG_INF) - self.assertEqual(ref_fma_f16(NEG_MAX_NORMAL, POS_TWO, POS_ZERO, clamp=True), POS_ZERO) - - def test_oracle_source_modifiers(self): - # -v1 * v2 + v3: - (1.0) * 0.5 + 0.75 = 0.25 (0x3400) - got = ref_fma_f16(POS_ONE, POS_HALF, POS_THREE_QUARTERS, neg_s0=True, clamp=True) - self.assertEqual(got, POS_QUARTER) - - # | -2.0 | * 0.5 + 0.0 = 1.0 - got_abs = ref_fma_f16(NEG_TWO, POS_HALF, POS_ZERO, abs_s0=True, clamp=True) - self.assertEqual(got_abs, POS_ONE) - - -class ScalarFmaClampTests(unittest.TestCase): - """End-to-end tests for scalar v_fma_f16 with IEEE clamp saturation.""" - - def test_scalar_fma_clamp_saturation_upper(self): - # 2.0 * 2.0 + 2.0 = 6.0 > 1.0 -> saturates to 1.0 (0x3C00) - # Low half of v0 gets 0x3C00, high half preserved (OLD & 0xFFFF0000) - got = run_op("v_fma_f16 v0, v1, v2, v3 clamp", v1=POS_TWO, v2=POS_TWO, v3=POS_TWO) - expected = merge_half(POS_ONE, dst_hi=0) - self.assertEqual(got, expected) - - def test_scalar_fma_clamp_saturation_lower(self): - # 2.0 * (-1.0) + 0.5 = -1.5 < 0.0 -> saturates to 0.0 (0x0000) - got = run_op("v_fma_f16 v0, v1, v2, v3 clamp", v1=POS_TWO, v2=NEG_ONE, v3=POS_HALF) - expected = merge_half(POS_ZERO, dst_hi=0) - self.assertEqual(got, expected) - - def test_scalar_fma_interior_values(self): - # 0.5 * 0.5 + 0.25 = 0.5 in [0.0, 1.0] -> 0x3800 - got = run_op("v_fma_f16 v0, v1, v2, v3 clamp", v1=POS_HALF, v2=POS_HALF, v3=POS_QUARTER) - expected = merge_half(POS_HALF, dst_hi=0) - self.assertEqual(got, expected) - - # 0.75 * 0.5 + 0.125 (0x3000) = 0.5 - got2 = run_op("v_fma_f16 v0, v1, v2, v3 clamp", v1=POS_THREE_QUARTERS, v2=POS_HALF, v3=0x3000) - self.assertEqual(got2, merge_half(POS_HALF, dst_hi=0)) - - def test_scalar_fma_exact_boundaries(self): - # 1.0 * 1.0 + 0.0 = 1.0 (0x3C00) - got1 = run_op("v_fma_f16 v0, v1, v2, v3 clamp", v1=POS_ONE, v2=POS_ONE, v3=POS_ZERO) - self.assertEqual(got1, merge_half(POS_ONE, dst_hi=0)) - - # 0.0 * 1.0 + 0.0 = 0.0 (0x0000) - got0 = run_op("v_fma_f16 v0, v1, v2, v3 clamp", v1=POS_ZERO, v2=POS_ONE, v3=POS_ZERO) - self.assertEqual(got0, merge_half(POS_ZERO, dst_hi=0)) - - def test_scalar_fma_destination_high_half_preservation(self): - # op_sel:[0,0,0,1] writes high half of v0, keeping low half of v0 - got = run_op("v_fma_f16 v0, v1, v2, v3 clamp op_sel:[0,0,0,1]", v1=POS_TWO, v2=POS_TWO, v3=POS_TWO) - expected = merge_half(POS_ONE, dst_hi=1) - self.assertEqual(got, expected) - - def test_scalar_fma_source_modifiers(self): - # -v1 * v2 + v3: -(1.0) * 0.5 + 0.75 = 0.25 (0x3400) - got = run_op("v_fma_f16 v0, -v1, v2, v3 clamp", v1=POS_ONE, v2=POS_HALF, v3=POS_THREE_QUARTERS) - self.assertEqual(got, merge_half(POS_QUARTER, dst_hi=0)) - - # |-v1| * v2 + v3: | -2.0 | * 0.25 + 0.25 = 0.75 (0x3A00) - got_abs = run_op("v_fma_f16 v0, |v1|, v2, v3 clamp", v1=NEG_TWO, v2=POS_QUARTER, v3=POS_QUARTER) - self.assertEqual(got_abs, merge_half(POS_THREE_QUARTERS, dst_hi=0)) - - def test_scalar_fma_sgpr_and_inline_constants(self): - # Inline constants 0.5 (0x3800), 1.0 (0x3C00), and SGPR source - # s4 = 0.5: 0.5 * 1.0 + 0.5 = 1.0 (0x3C00) - got = run_op("v_fma_f16 v0, s4, 1.0, 0.5 clamp", s4=POS_HALF) - self.assertEqual(got, merge_half(POS_ONE, dst_hi=0)) - - -# ----------------------------------------------------------------------------- -# Commit 2 Tests: Packed Half-Precision v_pk_fma_f16 SIMD Saturation Tests -# ----------------------------------------------------------------------------- - -class PackedReferenceOracleTests(unittest.TestCase): - """Test unit validation of the packed half-precision SIMD FMA oracle.""" - - def test_packed_oracle_basic(self): - # lo: 2.0 * 2.0 + 2.0 = 6.0 -> clamped to 1.0 (0x3C00) - # hi: 0.5 * 0.5 + 0.25 = 0.5 (0x3800) - v1 = pack2(POS_TWO, POS_HALF) - v2 = pack2(POS_TWO, POS_HALF) - v3 = pack2(POS_TWO, POS_QUARTER) - self.assertEqual(ref_pk_fma_f16(v1, v2, v3, clamp=True), pack2(POS_ONE, POS_HALF)) - self.assertEqual(ref_pk_fma_f16(v1, v2, v3, clamp=False), pack2(0x4600, POS_HALF)) - - def test_packed_oracle_swizzle_and_negation(self): - # v1: lo=2.0, hi=0.5 - # v2: lo=1.0, hi=-1.0 - # v3: lo=0.25, hi=0.75 - v1 = pack2(POS_TWO, POS_HALF) - v2 = pack2(POS_ONE, NEG_ONE) - v3 = pack2(POS_QUARTER, POS_THREE_QUARTERS) - - # op_sel:(1, 0, 0): lo takes v1.hi (0.5), v2.lo (1.0), v3.lo (0.25) -> 0.5 * 1.0 + 0.25 = 0.75 - # op_sel_hi:(0, 1, 1): hi takes v1.lo (2.0), v2.hi (-1.0), v3.hi (0.75) -> 2.0 * (-1.0) + 0.75 = -1.25 -> clamped to 0.0 - got = ref_pk_fma_f16(v1, v2, v3, clamp=True, op_sel=(1, 0, 0), op_sel_hi=(0, 1, 1)) - self.assertEqual(got, pack2(POS_THREE_QUARTERS, POS_ZERO)) - - # neg_lo:(1, 0, 0): lo takes -v1.lo (-2.0), v2.lo (1.0), v3.lo (0.25) -> -1.75 -> clamped to 0.0 - got_neg = ref_pk_fma_f16(v1, v2, v3, clamp=True, neg_lo=(1, 0, 0)) - self.assertEqual(got_neg & MASK16, POS_ZERO) - - def test_packed_oracle_independent_clamp(self): - # lo clamps to 0.0; hi clamps to 1.0 - v1 = pack2(NEG_TWO, POS_TWO) - v2 = pack2(POS_ONE, POS_TWO) - v3 = pack2(POS_HALF, POS_TWO) - self.assertEqual(ref_pk_fma_f16(v1, v2, v3, clamp=True), pack2(POS_ZERO, POS_ONE)) - - -class PackedFmaF16ClampTests(unittest.TestCase): - """End-to-end tests for packed v_pk_fma_f16 SIMD execution with IEEE clamp saturation.""" - - def test_packed_clamp_both_lanes_saturating(self): - # lo: 2.0 * (-1.0) + 0.5 = -1.5 -> clamped to 0.0 (0x0000) - # hi: 2.0 * 2.0 + 2.0 = 6.0 -> clamped to 1.0 (0x3C00) - v1 = pack2(POS_TWO, POS_TWO) - v2 = pack2(NEG_ONE, POS_TWO) - v3 = pack2(POS_HALF, POS_TWO) - got = run_op("v_pk_fma_f16 v0, v1, v2, v3 clamp", v1=v1, v2=v2, v3=v3) - self.assertEqual(got, pack2(POS_ZERO, POS_ONE)) - - # Inverted saturation: lo clamps to 1.0, hi clamps to 0.0 - v1_inv = pack2(POS_TWO, POS_TWO) - v2_inv = pack2(POS_TWO, NEG_ONE) - v3_inv = pack2(POS_TWO, POS_HALF) - got_inv = run_op("v_pk_fma_f16 v0, v1, v2, v3 clamp", v1=v1_inv, v2=v2_inv, v3=v3_inv) - self.assertEqual(got_inv, pack2(POS_ONE, POS_ZERO)) - - def test_packed_clamp_one_lane_interior_one_saturating(self): - # lo interior (0.5 * 0.5 + 0.25 = 0.5), hi saturates upper (2.0 * 2.0 + 2.0 = 6.0 -> 1.0) - v1 = pack2(POS_HALF, POS_TWO) - v2 = pack2(POS_HALF, POS_TWO) - v3 = pack2(POS_QUARTER, POS_TWO) - got1 = run_op("v_pk_fma_f16 v0, v1, v2, v3 clamp", v1=v1, v2=v2, v3=v3) - self.assertEqual(got1, pack2(POS_HALF, POS_ONE)) - - # lo interior (0.5 * 0.5 + 0.25 = 0.5), hi saturates lower (2.0 * -1.0 + 0.5 = -1.5 -> 0.0) - v1_b = pack2(POS_HALF, POS_TWO) - v2_b = pack2(POS_HALF, NEG_ONE) - v3_b = pack2(POS_QUARTER, POS_HALF) - got2 = run_op("v_pk_fma_f16 v0, v1, v2, v3 clamp", v1=v1_b, v2=v2_b, v3=v3_b) - self.assertEqual(got2, pack2(POS_HALF, POS_ZERO)) - - # lo saturates upper (1.0), hi interior (0.5) - got3 = run_op("v_pk_fma_f16 v0, v1, v2, v3 clamp", v1=pack2(POS_TWO, POS_HALF), v2=pack2(POS_TWO, POS_HALF), v3=pack2(POS_TWO, POS_QUARTER)) - self.assertEqual(got3, pack2(POS_ONE, POS_HALF)) - - # lo saturates lower (0.0), hi interior (0.5) - got4 = run_op("v_pk_fma_f16 v0, v1, v2, v3 clamp", v1=pack2(POS_TWO, POS_HALF), v2=pack2(NEG_ONE, POS_HALF), v3=pack2(POS_HALF, POS_QUARTER)) - self.assertEqual(got4, pack2(POS_ZERO, POS_HALF)) - - def test_packed_clamp_both_lanes_interior(self): - # lo: 0.5 * 0.5 + 0.0 = 0.25 (0x3400) - # hi: 0.75 * 0.5 + 0.125 = 0.5 (0x3800) - v1 = pack2(POS_HALF, POS_THREE_QUARTERS) - v2 = pack2(POS_HALF, POS_HALF) - v3 = pack2(POS_ZERO, 0x3000) - got = run_op("v_pk_fma_f16 v0, v1, v2, v3 clamp", v1=v1, v2=v2, v3=v3) - self.assertEqual(got, pack2(POS_QUARTER, POS_HALF)) - - def test_packed_clamp_both_lanes_same_saturation(self): - # Both clamp to 0.0 - v1 = pack2(NEG_TWO, NEG_THREE) - v2 = pack2(POS_ONE, POS_ONE) - v3 = pack2(POS_HALF, POS_HALF) - got_zero = run_op("v_pk_fma_f16 v0, v1, v2, v3 clamp", v1=v1, v2=v2, v3=v3) - self.assertEqual(got_zero, pack2(POS_ZERO, POS_ZERO)) - - # Both clamp to 1.0 - v1_h = pack2(POS_TWO, POS_THREE) - v2_h = pack2(POS_TWO, POS_TWO) - v3_h = pack2(POS_ONE, POS_ONE) - got_one = run_op("v_pk_fma_f16 v0, v1, v2, v3 clamp", v1=v1_h, v2=v2_h, v3=v3_h) - self.assertEqual(got_one, pack2(POS_ONE, POS_ONE)) - - def test_packed_fma_unclamped_exceeds_range(self): - # Without clamp, results must not saturate: - # lo: 2.0 * 2.0 + 2.0 = 6.0 (0x4600) - # hi: 2.0 * (-1.0) + 0.5 = -1.5 (0xBE00) - v1 = pack2(POS_TWO, POS_TWO) - v2 = pack2(POS_TWO, NEG_ONE) - v3 = pack2(POS_TWO, POS_HALF) - got = run_op("v_pk_fma_f16 v0, v1, v2, v3", v1=v1, v2=v2, v3=v3) - self.assertEqual(got, pack2(0x4600, 0xBE00)) - - def test_packed_fma_opsel_modifiers(self): - # Swizzling with op_sel and op_sel_hi under clamp - v1 = pack2(POS_TWO, POS_HALF) - v2 = pack2(POS_ONE, NEG_ONE) - v3 = pack2(POS_QUARTER, POS_THREE_QUARTERS) - got = run_op( - "v_pk_fma_f16 v0, v1, v2, v3 clamp op_sel:[1,0,0] op_sel_hi:[0,1,1]", - v1=v1, - v2=v2, - v3=v3, - ) - expected = ref_pk_fma_f16(v1, v2, v3, clamp=True, op_sel=(1, 0, 0), op_sel_hi=(0, 1, 1)) - self.assertEqual(got, expected) - - def test_packed_fma_neg_modifiers(self): - # Negation modifiers neg_lo and neg_hi under clamp - v1 = pack2(POS_ONE, POS_TWO) - v2 = pack2(POS_HALF, POS_HALF) - v3 = pack2(POS_THREE_QUARTERS, POS_QUARTER) - got = run_op( - "v_pk_fma_f16 v0, v1, v2, v3 clamp neg_lo:[1,0,0] neg_hi:[0,1,0]", - v1=v1, - v2=v2, - v3=v3, - ) - expected = ref_pk_fma_f16(v1, v2, v3, clamp=True, neg_lo=(1, 0, 0), neg_hi=(0, 1, 0)) - self.assertEqual(got, expected) - - def test_packed_fma_inactive_exec_lane(self): - # Inactive EXEC lane must preserve existing destination contents - lines = [ - f"v_mov_b32 v0, {OLD:#x}", - f"v_mov_b32 v1, {pack2(POS_TWO, POS_TWO):#x}", - f"v_mov_b32 v2, {pack2(POS_TWO, POS_TWO):#x}", - f"v_mov_b32 v3, {pack2(POS_TWO, POS_TWO):#x}", - "s_mov_b32 s10, exec_lo", - "s_mov_b32 exec_lo, 0", - "v_pk_fma_f16 v0, v1, v2, v3 clamp", - "s_mov_b32 exec_lo, s10", - ] - got = run_ps(lines) - self.assertEqual(got, OLD) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_alu_f16_min_max.py b/tests/semantic/test_alu_f16_min_max.py deleted file mode 100644 index 261777138..000000000 --- a/tests/semantic/test_alu_f16_min_max.py +++ /dev/null @@ -1,795 +0,0 @@ -"""Semantic interpreter tests for RDNA2 half-precision floating-point min/max: -v_min_f16 and v_max_f16 (VOP2/VOP3 scalar forms), -v_pk_min_f16 and v_pk_max_f16 (VOP3P packed SIMD forms). - -Features and specifications: -- IEEE 754-2008 / RDNA rules: NaN suppression (return non-NaN operand; return quiet NaN if both are NaN). -- Signed zero ordering: -0.0 < +0.0 tie-breaking. -- Packed 16-bit lane execution (v_pk_min_f16 / v_pk_max_f16 across lo and hi halves). -- Subnormal representation and gradual underflow (denormals preserved). -- Output clamp to [0.0, 1.0]. -- Destination register half preservation on scalar f16 ops. -- VOP3 op_sel and input modifiers (negation, absolute value). -- Multi-lane SIMD divergence under EXEC mask. -- Deterministic seeded sweep and negative control sabotage tests. -- Standard library Python only; zero game data. -""" -from __future__ import annotations - -import gc -import math -import os -import random -import re -import struct -import sys -import tempfile -import unittest -import warnings - -HERE = os.path.dirname(os.path.abspath(__file__)) -ROOT = os.path.dirname(os.path.dirname(HERE)) -TOOLS_DIR = os.environ.get("LEONIDA_TOOLS_DIR") or os.path.join(ROOT, "tools") - -sys.dont_write_bytecode = True -if TOOLS_DIR not in sys.path: - sys.path.insert(0, TOOLS_DIR) -if HERE not in sys.path: - sys.path.insert(0, HERE) - -import rdna2spirv # noqa: E402 -import spirv_mini_interp as si # noqa: E402 -from support import STUB_DXBC, mrt0_words # noqa: E402 - -MASK16 = 0xFFFF -MASK32 = 0xFFFFFFFF -OLD = 0xA55A5AA5 -VSHARP_CS = [0, 0, 0xFFFFFFFF, 0x31016FAC] - -# IEEE 754-2008 binary16 bit constants -POS_ZERO = 0x0000 # +0.0 -NEG_ZERO = 0x8000 # -0.0 -POS_ONE = 0x3C00 # +1.0 -NEG_ONE = 0xBC00 # -1.0 -POS_HALF = 0x3800 # +0.5 -NEG_HALF = 0xB800 # -0.5 -POS_TWO = 0x4000 # +2.0 -NEG_TWO = 0xC000 # -2.0 -POS_THREE = 0x4200 # +3.0 -NEG_THREE = 0xC200 # -3.0 -POS_INF = 0x7C00 # +inf -NEG_INF = 0xFC00 # -inf -QNAN_CANONICAL = 0x7E00 # canonical quiet NaN -QNAN_ALT = 0x7E11 # quiet NaN with payload -SNAN = 0x7D00 # signaling NaN -NEG_QNAN = 0xFE22 # negative quiet NaN - -# Subnormal (denormal) binary16 constants -POS_MIN_SUBNORM = 0x0001 # +2^-24 (~5.96e-8), smallest positive subnormal -POS_MAX_SUBNORM = 0x03FF # largest positive subnormal (~6.097e-5) -NEG_MIN_SUBNORM = 0x8001 # -2^-24, smallest negative subnormal -NEG_MAX_SUBNORM = 0x83FF # largest negative subnormal - -# Normal binary16 boundaries -POS_MIN_NORMAL = 0x0400 # +2^-14 (~6.104e-5), smallest positive normal -POS_MAX_NORMAL = 0x7BFF # +65504.0, largest finite binary16 -NEG_MAX_NORMAL = 0xFBFF # -65504.0 - - -def f16_to_float(bits: int) -> float: - """Decode 16-bit integer as IEEE 754 half-precision float.""" - return struct.unpack(" int: - """Encode float into IEEE 754 half-precision bits.""" - if math.isnan(f): - return QNAN_CANONICAL - try: - return struct.unpack(" 0 else NEG_INF - - -def is_nan16(bits: int) -> bool: - """Check if 16-bit integer represents a binary16 NaN.""" - return (bits & 0x7C00) == 0x7C00 and (bits & 0x03FF) != 0 - - -def is_subnormal16(bits: int) -> bool: - """Check if 16-bit integer represents a binary16 subnormal.""" - return (bits & 0x7C00) == 0 and (bits & 0x03FF) != 0 - - -def half_bits(word: int, hi: int) -> int: - """Extract low (hi=0) or high (hi=1) 16 bits of a 32-bit dword.""" - return ((word >> 16) if hi else word) & MASK16 - - -def merge_half(res16: int, dst_hi: int, old: int = OLD) -> int: - """Merge 16-bit result into low or high half of 32-bit word, preserving the other half.""" - res16 &= MASK16 - return ((res16 << 16) | (old & MASK16)) if dst_hi else ((old & 0xFFFF0000) | res16) - - -def pack2(lo: int, hi: int) -> int: - """Pack two 16-bit half words into a single 32-bit dword.""" - return ((hi & MASK16) << 16) | (lo & MASK16) - - -def ref_min_f16(a_bits: int, b_bits: int, *, clamp: bool = False) -> int: - """Reference oracle for RDNA2 v_min_f16 conforming to IEEE 754-2008 / GLSL NMin. - - Rules: - - NaN suppression: if one operand is NaN, return the other operand. - - If both are NaN, return a quiet NaN. - - Signed zero ordering: -0.0 < +0.0. - - Clamping: if clamp=True, output clamped to [0.0, 1.0] (negative / -0.0 maps to +0.0). - """ - a_nan = is_nan16(a_bits) - b_nan = is_nan16(b_bits) - if a_nan and b_nan: - chosen_bits = QNAN_CANONICAL - elif a_nan: - chosen_bits = b_bits & MASK16 - elif b_nan: - chosen_bits = a_bits & MASK16 - else: - is_a_neg_zero = (a_bits & MASK16) == NEG_ZERO - is_a_pos_zero = (a_bits & MASK16) == POS_ZERO - is_b_neg_zero = (b_bits & MASK16) == NEG_ZERO - is_b_pos_zero = (b_bits & MASK16) == POS_ZERO - - if (is_a_neg_zero and is_b_pos_zero) or (is_a_pos_zero and is_b_neg_zero): - chosen_bits = NEG_ZERO - elif is_a_neg_zero and is_b_neg_zero: - chosen_bits = NEG_ZERO - elif is_a_pos_zero and is_b_pos_zero: - chosen_bits = POS_ZERO - else: - fa, fb = f16_to_float(a_bits), f16_to_float(b_bits) - key_a = (fa, math.copysign(1.0, fa)) - key_b = (fb, math.copysign(1.0, fb)) - chosen_bits = (a_bits & MASK16) if key_a <= key_b else (b_bits & MASK16) - - if clamp: - if is_nan16(chosen_bits): - return POS_ZERO - cf = f16_to_float(chosen_bits) - if cf <= 0.0 or (chosen_bits & MASK16) == NEG_ZERO: - return POS_ZERO - if cf >= 1.0: - return POS_ONE - return float_to_f16_bits(cf) - - return chosen_bits & MASK16 - - -def ref_max_f16(a_bits: int, b_bits: int, *, clamp: bool = False) -> int: - """Reference oracle for RDNA2 v_max_f16 conforming to IEEE 754-2008 / GLSL NMax. - - Rules: - - NaN suppression: if one operand is NaN, return the other operand. - - If both are NaN, return a quiet NaN. - - Signed zero ordering: -0.0 < +0.0. - - Clamping: if clamp=True, output clamped to [0.0, 1.0]. - """ - a_nan = is_nan16(a_bits) - b_nan = is_nan16(b_bits) - if a_nan and b_nan: - chosen_bits = QNAN_CANONICAL - elif a_nan: - chosen_bits = b_bits & MASK16 - elif b_nan: - chosen_bits = a_bits & MASK16 - else: - is_a_neg_zero = (a_bits & MASK16) == NEG_ZERO - is_a_pos_zero = (a_bits & MASK16) == POS_ZERO - is_b_neg_zero = (b_bits & MASK16) == NEG_ZERO - is_b_pos_zero = (b_bits & MASK16) == POS_ZERO - - if (is_a_neg_zero and is_b_pos_zero) or (is_a_pos_zero and is_b_neg_zero): - chosen_bits = POS_ZERO - elif is_a_neg_zero and is_b_neg_zero: - chosen_bits = NEG_ZERO - elif is_a_pos_zero and is_b_pos_zero: - chosen_bits = POS_ZERO - else: - fa, fb = f16_to_float(a_bits), f16_to_float(b_bits) - key_a = (fa, math.copysign(1.0, fa)) - key_b = (fb, math.copysign(1.0, fb)) - chosen_bits = (a_bits & MASK16) if key_a >= key_b else (b_bits & MASK16) - - if clamp: - if is_nan16(chosen_bits): - return POS_ZERO - cf = f16_to_float(chosen_bits) - if cf <= 0.0 or (chosen_bits & MASK16) == NEG_ZERO: - return POS_ZERO - if cf >= 1.0: - return POS_ONE - return float_to_f16_bits(cf) - - return chosen_bits & MASK16 - - -def ref_pk_f16( - op: str, - a_word: int, - b_word: int, - *, - op_sel: tuple[int, int] = (0, 0), - op_sel_hi: tuple[int, int] = (1, 1), - neg_lo: tuple[int, int] = (0, 0), - neg_hi: tuple[int, int] = (0, 0), - clamp: bool = False, -) -> int: - """Reference oracle for RDNA2 packed v_pk_min_f16 / v_pk_max_f16.""" - fn = ref_min_f16 if "min" in op else ref_max_f16 - - a_lo = half_bits(a_word, op_sel[0]) - b_lo = half_bits(b_word, op_sel[1]) - if neg_lo[0]: - a_lo ^= 0x8000 - if neg_lo[1]: - b_lo ^= 0x8000 - - a_hi = half_bits(a_word, op_sel_hi[0]) - b_hi = half_bits(b_word, op_sel_hi[1]) - if neg_hi[0]: - a_hi ^= 0x8000 - if neg_hi[1]: - b_hi ^= 0x8000 - - res_lo = fn(a_lo, b_lo, clamp=clamp) - res_hi = fn(a_hi, b_hi, clamp=clamp) - return ((res_hi & MASK16) << 16) | (res_lo & MASK16) - - -# ----------------------------------------------------------------------------- -# Translation and Execution Harness -# ----------------------------------------------------------------------------- - -_TMP_DIR = None -_PS_PATH = None -_CS_PATH = None -_CS_FSSM = None - - -def _make_fssm(rsrc2: int, group: tuple[int, int, int]) -> bytes: - header = bytearray(0x148) - struct.pack_into("<4I", header, 0x138, rsrc2, *group) - return bytes(header) - - -def setUpModule(): - global _TMP_DIR, _PS_PATH, _CS_PATH, _CS_FSSM - _TMP_DIR = tempfile.TemporaryDirectory() - disasm_dir = os.path.join(_TMP_DIR.name, "disasm") - fssm_dir = os.path.join(_TMP_DIR.name, "fssm") - os.mkdir(disasm_dir) - os.mkdir(fssm_dir) - _PS_PATH = os.path.join(disasm_dir, "ps_alu_f16.s") - _CS_PATH = os.path.join(disasm_dir, "cs_alu_f16.s") - _CS_FSSM = os.path.join(fssm_dir, "cs_alu_f16.fssm") - with open(os.path.join(_TMP_DIR.name, "ps_alu_f16.dxbc"), "wb") as f: - f.write(STUB_DXBC) - with open(os.path.join(_TMP_DIR.name, "cs_alu_f16.dxbc"), "wb") as f: - f.write(STUB_DXBC) - - -def tearDownModule(): - global _TMP_DIR, _PS_PATH, _CS_PATH, _CS_FSSM - if _TMP_DIR is not None: - gc.collect() - _TMP_DIR.cleanup() - _TMP_DIR = None - _PS_PATH = None - _CS_PATH = None - _CS_FSSM = None - - -def translate_ps(lines: list[str]) -> str: - if _TMP_DIR is None: - setUpModule() - asm = "; test_alu_f16_min_max\n" + "".join(f"\t{ln}\n" for ln in lines) + "\texp mrt0 v0, v0, v0, v0 done vm\n\ts_endpgm\n" - with open(_PS_PATH, "w", encoding="utf-8", newline="\n") as f: - f.write(asm) - with warnings.catch_warnings(): - warnings.simplefilter("ignore", ResourceWarning) - spv = rdna2spirv.translate(_PS_PATH) - gc.collect() - return spv - - -def run_ps(lines: list[str]) -> int: - spv = translate_ps(lines) - return si.run_fragment(spv)["%out_mrt0"][0] - - -def run_op(op_line: str, v1: int = 0, v2: int = 0, *, old: int = OLD, s4: int = 0, s5: int = 0) -> int: - lines = [ - f"v_mov_b32 v0, {old:#x}", - f"v_mov_b32 v1, {v1:#x}", - f"v_mov_b32 v2, {v2:#x}", - f"s_mov_b32 s4, {s4:#x}", - f"s_mov_b32 s5, {s5:#x}", - op_line, - ] - return run_ps(lines) - - -def run_cs(lines: list[str], group_size: int, memory: dict[int, int]) -> None: - if _TMP_DIR is None: - setUpModule() - with open(_CS_FSSM, "wb") as f: - f.write(_make_fssm(0x0088, (group_size, 1, 1))) - asm = "; test_cs_alu_f16\n" + "".join(f"\t{ln}\n" for ln in lines) + "\ts_endpgm\n" - with open(_CS_PATH, "w", encoding="utf-8", newline="\n") as f: - f.write(asm) - with warnings.catch_warnings(): - warnings.simplefilter("ignore", ResourceWarning) - spv = rdna2spirv.translate(_CS_PATH) - gc.collect() - si.run_workgroup( - spv, - group_size, - 32, - inputs_for=lambda i: {"%wg_id": (0, 0, 0), "%local_id": (i, 0, 0)}, - push_constants=VSHARP_CS + [0] * 28, - memory=memory, - ) - - -# ----------------------------------------------------------------------------- -# Commit 1 Tests: Reference Oracle and Scalar v_min_f16 / v_max_f16 -# ----------------------------------------------------------------------------- - -class ReferenceOracleTests(unittest.TestCase): - """Test IEEE 754 half-precision reference oracle rules.""" - - def test_signed_zero_ordering(self): - self.assertEqual(ref_min_f16(NEG_ZERO, POS_ZERO), NEG_ZERO) - self.assertEqual(ref_min_f16(POS_ZERO, NEG_ZERO), NEG_ZERO) - self.assertEqual(ref_max_f16(NEG_ZERO, POS_ZERO), POS_ZERO) - self.assertEqual(ref_max_f16(POS_ZERO, NEG_ZERO), POS_ZERO) - self.assertEqual(ref_min_f16(NEG_ZERO, NEG_ZERO), NEG_ZERO) - self.assertEqual(ref_max_f16(POS_ZERO, POS_ZERO), POS_ZERO) - - def test_subnormal_ordering_and_gradual_underflow(self): - self.assertEqual(ref_min_f16(POS_MIN_SUBNORM, POS_ZERO), POS_ZERO) - self.assertEqual(ref_max_f16(POS_MIN_SUBNORM, POS_ZERO), POS_MIN_SUBNORM) - self.assertEqual(ref_min_f16(POS_MAX_SUBNORM, POS_MIN_NORMAL), POS_MAX_SUBNORM) - self.assertEqual(ref_max_f16(POS_MAX_SUBNORM, POS_MIN_NORMAL), POS_MIN_NORMAL) - self.assertEqual(ref_min_f16(NEG_MIN_SUBNORM, NEG_ZERO), NEG_MIN_SUBNORM) - self.assertEqual(ref_max_f16(NEG_MIN_SUBNORM, NEG_ZERO), NEG_ZERO) - - def test_infinities(self): - self.assertEqual(ref_min_f16(POS_INF, POS_MAX_NORMAL), POS_MAX_NORMAL) - self.assertEqual(ref_max_f16(POS_INF, POS_MAX_NORMAL), POS_INF) - self.assertEqual(ref_min_f16(NEG_INF, NEG_MAX_NORMAL), NEG_INF) - self.assertEqual(ref_max_f16(NEG_INF, NEG_MAX_NORMAL), NEG_MAX_NORMAL) - self.assertEqual(ref_min_f16(NEG_INF, POS_INF), NEG_INF) - self.assertEqual(ref_max_f16(NEG_INF, POS_INF), POS_INF) - - def test_clamp_oracle(self): - self.assertEqual(ref_min_f16(POS_TWO, POS_THREE, clamp=True), POS_ONE) - self.assertEqual(ref_min_f16(NEG_TWO, NEG_ONE, clamp=True), POS_ZERO) - self.assertEqual(ref_max_f16(NEG_HALF, NEG_ONE, clamp=True), POS_ZERO) - self.assertEqual(ref_max_f16(POS_HALF, POS_HALF, clamp=True), POS_HALF) - self.assertEqual(ref_min_f16(POS_HALF, POS_ONE, clamp=True), POS_HALF) - - def test_roundtrip_binary16(self): - test_patterns = [ - POS_ZERO, NEG_ZERO, POS_ONE, NEG_ONE, POS_HALF, NEG_HALF, - POS_TWO, NEG_TWO, POS_INF, NEG_INF, POS_MIN_SUBNORM, - POS_MAX_SUBNORM, NEG_MIN_SUBNORM, POS_MIN_NORMAL, POS_MAX_NORMAL, - ] - for bits in test_patterns: - flt = f16_to_float(bits) - enc = float_to_f16_bits(flt) - self.assertEqual(enc, bits, f"Pattern {bits:#06x} failed roundtrip, got {enc:#06x}") - - -class ScalarMinMaxF16Tests(unittest.TestCase): - """End-to-end interpreter tests for scalar v_min_f16 and v_max_f16.""" - - def test_scalar_min_f16_basic(self): - got = run_op("v_min_f16_e32 v0, v1, v2", v1=POS_ONE, v2=POS_TWO) - self.assertEqual(got, merge_half(POS_ONE, dst_hi=0)) - - got = run_op("v_min_f16_e32 v0, v1, v2", v1=POS_TWO, v2=NEG_THREE) - self.assertEqual(got, merge_half(NEG_THREE, dst_hi=0)) - - def test_scalar_max_f16_basic(self): - got = run_op("v_max_f16_e32 v0, v1, v2", v1=POS_ONE, v2=POS_TWO) - self.assertEqual(got, merge_half(POS_TWO, dst_hi=0)) - - got = run_op("v_max_f16_e32 v0, v1, v2", v1=NEG_ONE, v2=NEG_TWO) - self.assertEqual(got, merge_half(NEG_ONE, dst_hi=0)) - - def test_destination_half_preservation(self): - got_lo = run_op("v_min_f16_e64 v0, v1, v2 op_sel:[0,0,0]", v1=POS_HALF, v2=POS_ONE, old=OLD) - self.assertEqual(got_lo, merge_half(POS_HALF, dst_hi=0, old=OLD)) - self.assertEqual(got_lo & 0xFFFF0000, OLD & 0xFFFF0000) - - got_hi = run_op("v_max_f16_e64 v0, v1, v2 op_sel:[0,0,1]", v1=POS_HALF, v2=POS_ONE, old=OLD) - self.assertEqual(got_hi, merge_half(POS_ONE, dst_hi=1, old=OLD)) - self.assertEqual(got_hi & 0x0000FFFF, OLD & 0x0000FFFF) - - def test_subnormal_handling_scalar(self): - got_min = run_op("v_min_f16_e32 v0, v1, v2", v1=POS_MIN_SUBNORM, v2=POS_ZERO) - self.assertEqual(got_min, merge_half(POS_ZERO, dst_hi=0)) - - got_max = run_op("v_max_f16_e32 v0, v1, v2", v1=POS_MIN_SUBNORM, v2=POS_ZERO) - self.assertEqual(got_max, merge_half(POS_MIN_SUBNORM, dst_hi=0)) - - got_min2 = run_op("v_min_f16_e32 v0, v1, v2", v1=POS_MAX_SUBNORM, v2=POS_MIN_NORMAL) - self.assertEqual(got_min2, merge_half(POS_MAX_SUBNORM, dst_hi=0)) - - got_max2 = run_op("v_max_f16_e32 v0, v1, v2", v1=POS_MAX_SUBNORM, v2=POS_MIN_NORMAL) - self.assertEqual(got_max2, merge_half(POS_MIN_NORMAL, dst_hi=0)) - - def test_output_clamp_scalar(self): - got = run_op("v_min_f16_e64 v0, v1, v2 clamp", v1=POS_TWO, v2=POS_THREE) - self.assertEqual(got, merge_half(POS_ONE, dst_hi=0)) - - got2 = run_op("v_max_f16_e64 v0, v1, v2 clamp", v1=NEG_TWO, v2=NEG_ONE) - self.assertEqual(got2, merge_half(POS_ZERO, dst_hi=0)) - - got3 = run_op("v_min_f16_e64 v0, v1, v2 clamp", v1=POS_HALF, v2=POS_ONE) - self.assertEqual(got3, merge_half(POS_HALF, dst_hi=0)) - - def test_source_modifiers_neg_abs(self): - got = run_op("v_min_f16_e64 v0, -v1, v2", v1=NEG_TWO, v2=POS_ONE) - self.assertEqual(got, merge_half(POS_ONE, dst_hi=0)) - - got2 = run_op("v_min_f16_e64 v0, |v1|, v2", v1=NEG_TWO, v2=POS_HALF) - self.assertEqual(got2, merge_half(POS_HALF, dst_hi=0)) - - got3 = run_op("v_max_f16_e64 v0, -|v1|, v2", v1=POS_ONE, v2=NEG_TWO) - self.assertEqual(got3, merge_half(NEG_ONE, dst_hi=0)) - - def test_inline_constants_and_sgprs(self): - got = run_op("v_min_f16_e64 v0, 1.0, v2", v2=POS_TWO) - self.assertEqual(got, merge_half(POS_ONE, dst_hi=0)) - - got2 = run_op("v_max_f16_e64 v0, 0.0, v2", v2=NEG_ONE) - self.assertEqual(got2, merge_half(POS_ZERO, dst_hi=0)) - - got3 = run_op("v_min_f16_e64 v0, s4, v2", s4=POS_TWO, v2=POS_HALF) - self.assertEqual(got3, merge_half(POS_HALF, dst_hi=0)) - - got4 = run_op("v_max_f16_e64 v0, v1, s5", v1=POS_ONE, s5=NEG_HALF) - self.assertEqual(got4, merge_half(POS_ONE, dst_hi=0)) - - -# ----------------------------------------------------------------------------- -# Commit 2 Tests: Packed Half-Precision v_pk_min_f16 / v_pk_max_f16 & SIMD EXEC -# ----------------------------------------------------------------------------- - -class PackedReferenceOracleTests(unittest.TestCase): - """Test packed reference oracle logic.""" - - def test_packed_reference_basic(self): - v1 = pack2(POS_ONE, POS_HALF) - v2 = pack2(POS_TWO, POS_THREE) - self.assertEqual(ref_pk_f16("v_pk_min_f16", v1, v2), pack2(POS_ONE, POS_HALF)) - self.assertEqual(ref_pk_f16("v_pk_max_f16", v1, v2), pack2(POS_TWO, POS_THREE)) - - def test_packed_reference_modifiers(self): - v1 = pack2(POS_ONE, POS_HALF) - v2 = pack2(POS_TWO, POS_THREE) - got = ref_pk_f16("v_pk_min_f16", v1, v2, op_sel=(0, 1), op_sel_hi=(1, 0)) - self.assertEqual(got, pack2(POS_ONE, POS_HALF)) - - got_neg = ref_pk_f16("v_pk_min_f16", v1, v2, neg_lo=(1, 0)) - self.assertEqual(got_neg, pack2(NEG_ONE, POS_HALF)) - - -class PackedMinMaxF16Tests(unittest.TestCase): - """End-to-end tests for packed v_pk_min_f16 and v_pk_max_f16 instructions.""" - - def test_packed_min_max_basic(self): - v1 = pack2(POS_TWO, POS_ONE) - v2 = pack2(POS_HALF, POS_THREE) - - got_min = run_op("v_pk_min_f16 v0, v1, v2", v1=v1, v2=v2) - self.assertEqual(got_min, pack2(POS_HALF, POS_ONE)) - - got_max = run_op("v_pk_max_f16 v0, v1, v2", v1=v1, v2=v2) - self.assertEqual(got_max, pack2(POS_TWO, POS_THREE)) - - def test_packed_subnormal_lanes(self): - v1 = pack2(POS_MIN_SUBNORM, POS_MAX_SUBNORM) - v2 = pack2(POS_ZERO, POS_MIN_NORMAL) - - got_min = run_op("v_pk_min_f16 v0, v1, v2", v1=v1, v2=v2) - self.assertEqual(got_min, pack2(POS_ZERO, POS_MAX_SUBNORM)) - - got_max = run_op("v_pk_max_f16 v0, v1, v2", v1=v1, v2=v2) - self.assertEqual(got_max, pack2(POS_MIN_SUBNORM, POS_MIN_NORMAL)) - - def test_packed_clamp(self): - v1 = pack2(NEG_TWO, POS_THREE) - v2 = pack2(NEG_HALF, POS_TWO) - got = run_op("v_pk_min_f16 v0, v1, v2 clamp", v1=v1, v2=v2) - self.assertEqual(got, pack2(POS_ZERO, POS_ONE)) - - got2 = run_op("v_pk_max_f16 v0, v1, v2 clamp", v1=pack2(NEG_TWO, POS_HALF), v2=pack2(NEG_ONE, POS_ZERO)) - self.assertEqual(got2, pack2(POS_ZERO, POS_HALF)) - - def test_packed_opsel_swizzle(self): - v1 = pack2(POS_TWO, POS_ONE) - v2 = pack2(POS_HALF, POS_THREE) - got = run_op("v_pk_min_f16 v0, v1, v2 op_sel:[0,1] op_sel_hi:[1,0]", v1=v1, v2=v2) - self.assertEqual(got, pack2(POS_TWO, POS_HALF)) - - def test_packed_negation_modifiers(self): - v1 = pack2(POS_ONE, POS_TWO) - v2 = pack2(POS_HALF, POS_THREE) - got = run_op("v_pk_min_f16 v0, v1, v2 neg_lo:[1,0] neg_hi:[0,1]", v1=v1, v2=v2) - self.assertEqual(got, pack2(NEG_ONE, NEG_THREE)) - - def test_packed_sgpr_operands(self): - v1 = pack2(POS_TWO, POS_ONE) - s4 = pack2(POS_HALF, POS_THREE) - got = run_op("v_pk_min_f16 v0, v1, s4", v1=v1, s4=s4) - self.assertEqual(got, pack2(POS_HALF, POS_ONE)) - - -class SimdExecMaskDivergenceTests(unittest.TestCase): - """Test multi-lane SIMD divergence and execution under partial EXEC masks.""" - - def test_single_lane_exec_mask_toggle(self): - got_masked = run_ps([ - f"v_mov_b32 v0, {OLD:#x}", - f"v_mov_b32 v1, {POS_ONE:#x}", - f"v_mov_b32 v2, {POS_TWO:#x}", - "s_mov_b32 exec_lo, 0", - "v_min_f16_e32 v0, v1, v2", - "s_mov_b32 exec_lo, 1", - ]) - self.assertEqual(got_masked, OLD) - - got_pk_masked = run_ps([ - f"v_mov_b32 v0, {OLD:#x}", - f"v_mov_b32 v1, {pack2(POS_ONE, POS_TWO):#x}", - f"v_mov_b32 v2, {pack2(POS_THREE, POS_HALF):#x}", - "s_mov_b32 exec_lo, 0", - "v_pk_min_f16 v0, v1, v2", - "s_mov_b32 exec_lo, 1", - ]) - self.assertEqual(got_pk_masked, OLD) - - def test_multilane_workgroup_divergence(self): - lane_v1 = [ - pack2(POS_TWO, POS_ONE), - pack2(POS_THREE, POS_TWO), - pack2(POS_HALF, POS_TWO), - pack2(NEG_ONE, POS_THREE), - pack2(POS_MIN_SUBNORM, POS_ONE), - pack2(POS_ONE, POS_MAX_NORMAL), - pack2(NEG_TWO, NEG_THREE), - pack2(POS_HALF, POS_HALF), - ] - lane_v2 = [ - pack2(POS_HALF, POS_THREE), - pack2(POS_ONE, POS_ONE), - pack2(POS_ONE, POS_HALF), - pack2(NEG_TWO, POS_ONE), - pack2(POS_ZERO, POS_TWO), - pack2(POS_TWO, POS_INF), - pack2(NEG_ONE, NEG_ONE), - pack2(POS_THREE, POS_ONE), - ] - lane_olds = [0xD00D0000 + i for i in range(8)] - - mem = { - 0x100 + 4 * i: lane_v1[i] for i in range(8) - } - mem.update({0x200 + 4 * i: lane_v2[i] for i in range(8)}) - mem.update({0x300 + 4 * i: lane_olds[i] for i in range(8)}) - - run_cs([ - "v_lshlrev_b32_e32 v5, 2, v0", - "v_add_nc_u32_e32 v6, 0x100, v5", - "v_add_nc_u32_e32 v7, 0x200, v5", - "v_add_nc_u32_e32 v8, 0x300, v5", - "buffer_load_dword v1, v6, s[0:3], 0 offen", - "buffer_load_dword v2, v7, s[0:3], 0 offen", - "buffer_load_dword v3, v8, s[0:3], 0 offen", - "v_and_b32_e32 v4, 1, v0", - "v_cmp_eq_u32_e32 vcc_lo, 0, v4", - "s_and_saveexec_b32 s6, vcc_lo", - "v_pk_min_f16 v3, v1, v2", - "s_mov_b32 exec_lo, s6", - "buffer_store_dword v3, v5, s[0:3], 0 offen", - ], group_size=8, memory=mem) - - for lane in range(8): - got = mem.get(4 * lane) - if lane % 2 == 1: - self.assertEqual(got, lane_olds[lane], f"Lane {lane} was masked out but was overwritten!") - else: - want = ref_pk_f16("v_pk_min_f16", lane_v1[lane], lane_v2[lane]) - self.assertEqual(got, want, f"Lane {lane} active result mismatch: got {got:#x}, want {want:#x}") - - -# ----------------------------------------------------------------------------- -# Commit 3 Tests: NaN Suppression, Signed Zero Tie-Breaking, Negative Controls -# ----------------------------------------------------------------------------- - -class NanSuppressionTests(unittest.TestCase): - """Test IEEE 754-2008 / RDNA NaN suppression rules.""" - - def test_scalar_nan_suppression_single_nan(self): - # min(NaN, x) = x and min(x, NaN) = x - for nan_val in (QNAN_CANONICAL, QNAN_ALT, SNAN, NEG_QNAN): - for num_val in (POS_ONE, NEG_TWO, POS_ZERO, NEG_ZERO, POS_MIN_SUBNORM, POS_INF): - with self.subTest(nan=hex(nan_val), num=hex(num_val)): - # min - got_min_1 = run_op("v_min_f16_e32 v0, v1, v2", v1=nan_val, v2=num_val) - self.assertEqual(got_min_1, merge_half(num_val, dst_hi=0)) - got_min_2 = run_op("v_min_f16_e32 v0, v1, v2", v1=num_val, v2=nan_val) - self.assertEqual(got_min_2, merge_half(num_val, dst_hi=0)) - - # max - got_max_1 = run_op("v_max_f16_e32 v0, v1, v2", v1=nan_val, v2=num_val) - self.assertEqual(got_max_1, merge_half(num_val, dst_hi=0)) - got_max_2 = run_op("v_max_f16_e32 v0, v1, v2", v1=num_val, v2=nan_val) - self.assertEqual(got_max_2, merge_half(num_val, dst_hi=0)) - - def test_scalar_both_nan_returns_quiet_nan(self): - got_min = run_op("v_min_f16_e32 v0, v1, v2", v1=QNAN_CANONICAL, v2=QNAN_ALT) - self.assertTrue(is_nan16(got_min & 0xFFFF)) - - got_max = run_op("v_max_f16_e32 v0, v1, v2", v1=QNAN_ALT, v2=NEG_QNAN) - self.assertTrue(is_nan16(got_max & 0xFFFF)) - - def test_packed_nan_suppression(self): - # Mixed lane NaN: - # lo: min(QNAN_ALT, 1.0) = 1.0 - # hi: min(2.0, QNAN_CANONICAL) = 2.0 - v1 = pack2(QNAN_ALT, POS_TWO) - v2 = pack2(POS_ONE, QNAN_CANONICAL) - got = run_op("v_pk_min_f16 v0, v1, v2", v1=v1, v2=v2) - self.assertEqual(got, pack2(POS_ONE, POS_TWO)) - - # Packed max with NaNs: - # lo: max(-1.0, NEG_QNAN) = -1.0 - # hi: max(QNAN_ALT, 0.5) = 0.5 - v3 = pack2(NEG_ONE, QNAN_ALT) - v4 = pack2(NEG_QNAN, POS_HALF) - got2 = run_op("v_pk_max_f16 v0, v1, v2", v1=v3, v2=v4) - self.assertEqual(got2, pack2(NEG_ONE, POS_HALF)) - - -class SignedZeroTieBreakingTests(unittest.TestCase): - """Test IEEE 754-2008 / RDNA signed zero tie-breaking: -0.0 < +0.0.""" - - def test_scalar_signed_zero_min(self): - # min(-0.0, +0.0) == -0.0 (0x8000) - got1 = run_op("v_min_f16_e32 v0, v1, v2", v1=NEG_ZERO, v2=POS_ZERO) - self.assertEqual(got1, merge_half(NEG_ZERO, dst_hi=0)) - - # min(+0.0, -0.0) == -0.0 (0x8000) - got2 = run_op("v_min_f16_e32 v0, v1, v2", v1=POS_ZERO, v2=NEG_ZERO) - self.assertEqual(got2, merge_half(NEG_ZERO, dst_hi=0)) - - # min(-0.0, -0.0) == -0.0 - got3 = run_op("v_min_f16_e32 v0, v1, v2", v1=NEG_ZERO, v2=NEG_ZERO) - self.assertEqual(got3, merge_half(NEG_ZERO, dst_hi=0)) - - def test_scalar_signed_zero_max(self): - # max(-0.0, +0.0) == +0.0 (0x0000) - got1 = run_op("v_max_f16_e32 v0, v1, v2", v1=NEG_ZERO, v2=POS_ZERO) - self.assertEqual(got1, merge_half(POS_ZERO, dst_hi=0)) - - # max(+0.0, -0.0) == +0.0 (0x0000) - got2 = run_op("v_max_f16_e32 v0, v1, v2", v1=POS_ZERO, v2=NEG_ZERO) - self.assertEqual(got2, merge_half(POS_ZERO, dst_hi=0)) - - # max(+0.0, +0.0) == +0.0 - got3 = run_op("v_max_f16_e32 v0, v1, v2", v1=POS_ZERO, v2=POS_ZERO) - self.assertEqual(got3, merge_half(POS_ZERO, dst_hi=0)) - - def test_packed_signed_zero_tie_breaking(self): - # lo: min(-0.0, +0.0) = -0.0 (0x8000) - # hi: max(-0.0, +0.0) = +0.0 (0x0000) - # result: (0x0000 << 16) | 0x8000 = 0x00008000 - v1 = pack2(NEG_ZERO, NEG_ZERO) - v2 = pack2(POS_ZERO, POS_ZERO) - got = run_op("v_pk_min_f16 v0, v1, v2", v1=v1, v2=v2) - # For v_pk_min_f16: both lanes compute min, so both give -0.0 -> 0x80008000 - self.assertEqual(got, pack2(NEG_ZERO, NEG_ZERO)) - - # For v_pk_max_f16: both lanes compute max, so both give +0.0 -> 0x00000000 - got_max = run_op("v_pk_max_f16 v0, v1, v2", v1=v1, v2=v2) - self.assertEqual(got_max, pack2(POS_ZERO, POS_ZERO)) - - -class DeterministicSweepTests(unittest.TestCase): - """Deterministic pseudorandom sweep comparing simulated execution against oracle.""" - - def test_seeded_sweep(self): - rng = random.Random(0x7F16) - pool = [ - POS_ZERO, NEG_ZERO, POS_ONE, NEG_ONE, POS_HALF, NEG_HALF, - POS_TWO, NEG_TWO, POS_THREE, NEG_THREE, POS_INF, NEG_INF, - POS_MIN_SUBNORM, POS_MAX_SUBNORM, NEG_MIN_SUBNORM, - POS_MIN_NORMAL, POS_MAX_NORMAL, NEG_MAX_NORMAL, - QNAN_CANONICAL, QNAN_ALT, - ] - - for _ in range(30): - a = rng.choice(pool) - b = rng.choice(pool) - - # Scalar min test - got_min = run_op("v_min_f16_e32 v0, v1, v2", v1=a, v2=b) & 0xFFFF - want_min = ref_min_f16(a, b) - if is_nan16(want_min): - self.assertTrue(is_nan16(got_min)) - else: - self.assertEqual(got_min, want_min, f"min({a:#x}, {b:#x}) mismatch") - - # Scalar max test - got_max = run_op("v_max_f16_e32 v0, v1, v2", v1=a, v2=b) & 0xFFFF - want_max = ref_max_f16(a, b) - if is_nan16(want_max): - self.assertTrue(is_nan16(got_max)) - else: - self.assertEqual(got_max, want_max, f"max({a:#x}, {b:#x}) mismatch") - - -class NegativeControlsAndSabotageTests(unittest.TestCase): - """Negative controls and mutation detection tests verifying test suite vigilance.""" - - def test_opcode_sabotage_fails(self): - # Invert NMin to NMax in translated SPIR-V: must detect divergence! - spv = translate_ps([ - f"v_mov_b32 v1, {POS_ONE:#x}", - f"v_mov_b32 v2, {POS_TWO:#x}", - "v_min_f16_e32 v0, v1, v2", - ]) - self.assertIn("NMin", spv) - bad_spv, count = re.subn(r"NMin", "NMax", spv) - self.assertGreaterEqual(count, 1) - - out_good = si.run_fragment(spv)["%out_mrt0"][0] & 0xFFFF - out_bad = si.run_fragment(bad_spv)["%out_mrt0"][0] & 0xFFFF - - self.assertEqual(out_good, POS_ONE) - self.assertEqual(out_bad, POS_TWO) - self.assertNotEqual(out_good, out_bad) - - def test_clamp_omission_sabotage_fails(self): - # Removing FClamp from clamped v_min_f16 translation must fail clamp expectation - spv = translate_ps([ - f"v_mov_b32 v1, {POS_TWO:#x}", - f"v_mov_b32 v2, {POS_THREE:#x}", - "v_min_f16_e64 v0, v1, v2 clamp", - ]) - self.assertIn("FClamp", spv) - # Sabotage FClamp by bypassing it with OpCopyObject of its first argument - bad_spv, count = re.subn(r"OpExtInst %float %glsl FClamp (%\w+) (%\w+) (%\w+)", r"OpCopyObject %float \1", spv) - self.assertGreaterEqual(count, 1) - - out_good = si.run_fragment(spv)["%out_mrt0"][0] & 0xFFFF - out_bad = si.run_fragment(bad_spv)["%out_mrt0"][0] & 0xFFFF - - self.assertEqual(out_good, POS_ONE) - self.assertEqual(out_bad, POS_TWO) - self.assertNotEqual(out_good, out_bad) - - def test_signed_zero_tie_break_sabotage_fails(self): - # Tampering with signed zero ordering in oracle or hardware asserts - # min(-0.0, +0.0) must be -0.0 (0x8000), not +0.0 (0x0000) - got = run_op("v_min_f16_e32 v0, v1, v2", v1=NEG_ZERO, v2=POS_ZERO) & 0xFFFF - self.assertEqual(got, NEG_ZERO) - self.assertNotEqual(got, POS_ZERO) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_alu_f32_fma_clamp.py b/tests/semantic/test_alu_f32_fma_clamp.py deleted file mode 100644 index 0474dc7ff..000000000 --- a/tests/semantic/test_alu_f32_fma_clamp.py +++ /dev/null @@ -1,949 +0,0 @@ -"""Semantic interpreter tests for single-precision FMA with IEEE clamp saturation (v_fma_f32). - -RDNA2 VALU Instruction Set Architecture (ISA): - v_fma_f32 dst, src0, src1, src2 [clamp] [omod] - Operation: Computes IEEE-754 binary32 fused multiply-add: - D = (src0 * src1) + src2 - with a single intermediate rounding step (round-to-nearest-even, RTE). - -Modifiers and Semantics: - - Source Modifiers: - neg: negates operand (flips sign bit, including infinities, zeros, and NaNs) - abs: absolute value (clears sign bit) - Applied as: abs first, then neg (-|x|). - - Output Modifiers (omod): - mul:2: multiplies result by 2.0 - mul:4: multiplies result by 4.0 - div:2: multiplies result by 0.5 - Applied before clamp, matching hardware behavior. - - IEEE Clamp Saturation (clamp): - Saturates the final computed result into the unit interval [0.0, 1.0]. - - Values > 1.0 (and +inf) saturate to 1.0f (0x3F800000). - - Values < 0.0 (and -inf) saturate to +0.0f (0x00000000). - - Negative zero (-0.0f, 0x80000000) saturates to +0.0f (0x00000000). - - NaNs are clamped/suppressed to +0.0f under hardware clamp saturation. - - Values within [0.0, 1.0] pass through unmodified. - -In SPIR-V Lowering (tools/rdna2spirv.py): - v_fma_f32 lowers to: - %r = OpExtInst %float %glsl Fma %src0 %src1 %src2 - With output modifiers and clamp: - %scaled = OpFMul %float %r %scale - %clamped = OpExtInst %float %glsl FClamp %scaled %f0 %f1 - -Standard library only: Python 3.9+ compatible, zero game data, zero proprietary assets. -""" -from __future__ import annotations - -import itertools -import math -import os -import random -import struct -import sys -import tempfile -import unittest -import warnings -from fractions import Fraction - -HERE = os.path.dirname(os.path.abspath(__file__)) -ROOT = os.path.dirname(os.path.dirname(HERE)) -TOOLS_DIR = os.environ.get("LEONIDA_TOOLS_DIR") or os.path.join(ROOT, "tools") - -sys.dont_write_bytecode = True -if TOOLS_DIR not in sys.path: - sys.path.insert(0, TOOLS_DIR) -if HERE not in sys.path: - sys.path.insert(0, HERE) - -import rdna2spirv # noqa: E402 -import spirv_mini_interp as si # noqa: E402 - -MASK32 = 0xFFFFFFFF -SIGN_MASK = 0x80000000 -EXP_MASK = 0x7F800000 -MANT_MASK = 0x007FFFFF - -POS_ZERO = 0x00000000 -NEG_ZERO = 0x80000000 -ONE = 0x3F800000 # 1.0f -HALF = 0x3F000000 # 0.5f -ONE_HALF = 0x3FC00000 # 1.5f -TWO = 0x40000000 # 2.0f -THREE = 0x40400000 # 3.0f -FOUR = 0x40800000 # 4.0f -POS_INF = 0x7F800000 -NEG_INF = 0xFF800000 -QNAN = 0x7FC00000 -SNAN = 0x7F800001 -MAX_FINITE = 0x7F7FFFFF -MIN_NORMAL = 0x00800000 -MIN_SUBNORMAL = 0x00000001 -MAX_SUBNORMAL = 0x007FFFFF - -STUB_DXBC = b"DXBC" + bytes(24) + struct.pack(" float: - """Unpack a 32-bit unsigned integer to a Python float (binary32).""" - return struct.unpack(" int: - """Pack a Python float to a 32-bit unsigned integer word (binary32).""" - if math.isnan(val): - return QNAN - try: - return struct.unpack(" bool: - """Check if binary32 bit pattern represents any NaN.""" - bits &= MASK32 - return ((bits & EXP_MASK) == EXP_MASK) and ((bits & MANT_MASK) != 0) - - -def is_inf_bits(bits: int) -> bool: - """Check if binary32 bit pattern represents infinity.""" - bits &= MASK32 - return ((bits & EXP_MASK) == EXP_MASK) and ((bits & MANT_MASK) == 0) - - -def is_zero_bits(bits: int) -> bool: - """Check if binary32 bit pattern represents positive or negative zero.""" - return (bits & 0x7FFFFFFF) == 0 - - -def is_subnormal_bits(bits: int) -> bool: - """Check if binary32 bit pattern represents a subnormal (denormal) float.""" - bits &= MASK32 - return ((bits & EXP_MASK) == 0) and ((bits & MANT_MASK) != 0) - - -def exact_f32_to_fraction(bits: int) -> Fraction: - """Decode a finite binary32 bit pattern into an exact rational Fraction.""" - bits &= MASK32 - sign = -1 if (bits >> 31) else 1 - exp = (bits >> 23) & 0xFF - frac = bits & MANT_MASK - if exp == 0xFF: - raise ValueError(f"non-finite bits {bits:#010x}") - if exp == 0: - return Fraction(sign * frac, 1 << 149) - mant = (1 << 23) | frac - shift = exp - 150 - if shift >= 0: - return Fraction(sign * (mant << shift), 1) - return Fraction(sign * mant, 1 << (-shift)) - - -def round_fraction_to_f32_bits(val: Fraction, zero_sign: int = 0) -> int: - """Round an exact rational Fraction to IEEE-754 binary32 (round-to-nearest-even).""" - if val == 0: - return NEG_ZERO if zero_sign else POS_ZERO - sign = 1 if val < 0 else 0 - aval = -val if sign else val - num, den = aval.numerator, aval.denominator - - e = num.bit_length() - den.bit_length() - if (num << max(0, -e)) < (den << max(0, e)): - e -= 1 - - if e >= 128: - return (sign << 31) | POS_INF - - if e < -126: - target_shift = 149 - else: - target_shift = 23 - e - - if target_shift >= 0: - scaled_num = num << target_shift - else: - scaled_num = num - den = den << (-target_shift) - - q, rem = divmod(scaled_num, den) - twice_rem = rem << 1 - if twice_rem > den or (twice_rem == den and (q & 1)): - q += 1 - - if e < -126: - if q >= (1 << 23): - return (sign << 31) | (1 << 23) - return (sign << 31) | q - - if q >= (1 << 24): - q >>= 1 - e += 1 - if e >= 128: - return (sign << 31) | POS_INF - - exp_field = e + 127 - frac_field = q & MANT_MASK - return (sign << 31) | (exp_field << 23) | frac_field - - -def apply_src_mod(bits: int, neg: bool = False, absm: bool = False) -> int: - """RDNA2 source modifier order: abs first, then neg (operates on sign bit).""" - bits &= MASK32 - if absm: - bits &= ~SIGN_MASK - if neg: - bits ^= SIGN_MASK - return bits - - -def apply_out_mods(bits: int, omod: str | None = None, clamp: bool = False) -> int: - """RDNA2 output modifiers: mul:2 / mul:4 / div:2 applied before clamp [0.0, 1.0].""" - bits &= MASK32 - if is_nan_bits(bits): - if clamp: - return POS_ZERO - return bits - - if omod is not None: - f = bits_to_f32(bits) - factor = {"mul:2": 2.0, "mul:4": 4.0, "div:2": 0.5}[omod] - f_scaled = f * factor - bits = f32_to_bits(f_scaled) - - if clamp: - if is_nan_bits(bits): - return POS_ZERO - if (bits & SIGN_MASK) != 0: - return POS_ZERO - f = bits_to_f32(bits) - if f > 1.0 or math.isinf(f): - return ONE - return bits - - return bits - - -def ref_fma_f32_rational( - s0_bits: int, - s1_bits: int, - s2_bits: int, - *, - clamp: bool = False, - omod: str | None = None, - src0_neg: bool = False, - src0_abs: bool = False, - src1_neg: bool = False, - src1_abs: bool = False, - src2_neg: bool = False, - src2_abs: bool = False, -) -> int: - """Exact rational Fraction reference oracle for single-precision FMA with clamp. - - Computes: D = (S0 * S1) + S2 - with exact unrounded product, exact unrounded sum, and a single round-to-nearest-even. - """ - s0 = apply_src_mod(s0_bits, neg=src0_neg, absm=src0_abs) - s1 = apply_src_mod(s1_bits, neg=src1_neg, absm=src1_abs) - s2 = apply_src_mod(s2_bits, neg=src2_neg, absm=src2_abs) - - # 1. NaN propagation / Invalid operation detection - if is_nan_bits(s0) or is_nan_bits(s1) or is_nan_bits(s2): - return POS_ZERO if clamp else QNAN - - # Check for inf * 0 -> NaN - inf0 = is_inf_bits(s0) - inf1 = is_inf_bits(s1) - zero0 = is_zero_bits(s0) - zero1 = is_zero_bits(s1) - if (inf0 and zero1) or (zero0 and inf1): - return POS_ZERO if clamp else QNAN - - prod_sign = ((s0 ^ s1) >> 31) & 1 - - # Product is infinity - if inf0 or inf1: - prod_inf = (prod_sign << 31) | POS_INF - if is_inf_bits(s2): - if ((s2 >> 31) & 1) != prod_sign: - return POS_ZERO if clamp else QNAN - res = prod_inf - else: - res = prod_inf - return apply_out_mods(res, omod=omod, clamp=clamp) - - # S2 is infinity - if is_inf_bits(s2): - return apply_out_mods(s2, omod=omod, clamp=clamp) - - # Both product and S2 are finite - frac0 = exact_f32_to_fraction(s0) - frac1 = exact_f32_to_fraction(s1) - frac2 = exact_f32_to_fraction(s2) - - total_frac = (frac0 * frac1) + frac2 - - if total_frac == 0: - # Sign of zero in IEEE-754: - # Sum of two zeros with same sign retains sign; (+0) + (-0) = +0; - # Cancellation of opposite non-zero quantities gives +0 under round-to-nearest. - prod_is_zero = (zero0 or zero1) - s2_is_zero = is_zero_bits(s2) - if prod_is_zero and s2_is_zero: - s2_sign = (s2 >> 31) & 1 - zsign = 1 if (prod_sign == 1 and s2_sign == 1) else 0 - else: - zsign = 0 - res = NEG_ZERO if zsign else POS_ZERO - else: - res = round_fraction_to_f32_bits(total_frac) - - return apply_out_mods(res, omod=omod, clamp=clamp) - - -def ref_fma_f32_double( - s0_bits: int, - s1_bits: int, - s2_bits: int, - *, - clamp: bool = False, - omod: str | None = None, - src0_neg: bool = False, - src0_abs: bool = False, - src1_neg: bool = False, - src1_abs: bool = False, - src2_neg: bool = False, - src2_abs: bool = False, -) -> int: - """Double-precision (binary64) cross-check oracle for single-precision FMA. - - Binary32 float product requires at most 24 + 24 = 48 significand bits, which fits - without rounding into binary64's 53-bit significand for normal non-overflowing ranges. - """ - s0 = apply_src_mod(s0_bits, neg=src0_neg, absm=src0_abs) - s1 = apply_src_mod(s1_bits, neg=src1_neg, absm=src1_abs) - s2 = apply_src_mod(s2_bits, neg=src2_neg, absm=src2_abs) - - if is_nan_bits(s0) or is_nan_bits(s1) or is_nan_bits(s2): - return POS_ZERO if clamp else QNAN - - f0, f1, f2 = bits_to_f32(s0), bits_to_f32(s1), bits_to_f32(s2) - prod = f0 * f1 - if math.isnan(prod): - return POS_ZERO if clamp else QNAN - - total = prod + f2 - if math.isnan(total): - return POS_ZERO if clamp else QNAN - - if total == 0.0: - # Determine zero sign - prod_sign = ((s0 ^ s1) >> 31) & 1 - s2_sign = (s2 >> 31) & 1 - if is_zero_bits(s0) or is_zero_bits(s1): - if is_zero_bits(s2) and prod_sign == 1 and s2_sign == 1: - res = NEG_ZERO - else: - res = POS_ZERO - else: - res = POS_ZERO - else: - res = f32_to_bits(total) - - return apply_out_mods(res, omod=omod, clamp=clamp) - - -def ref_fma_f32( - s0_bits: int, - s1_bits: int, - s2_bits: int, - *, - clamp: bool = False, - omod: str | None = None, - src0_neg: bool = False, - src0_abs: bool = False, - src1_neg: bool = False, - src1_abs: bool = False, - src2_neg: bool = False, - src2_abs: bool = False, -) -> int: - """Canonical reference oracle for v_fma_f32.""" - return ref_fma_f32_rational( - s0_bits, - s1_bits, - s2_bits, - clamp=clamp, - omod=omod, - src0_neg=src0_neg, - src0_abs=src0_abs, - src1_neg=src1_neg, - src1_abs=src1_abs, - src2_neg=src2_neg, - src2_abs=src2_abs, - ) - - -# ----------------------------------------------------------------------------- -# Test Execution Harness (SPIR-V translation and execution) -# ----------------------------------------------------------------------------- - -_TMP_DIR = None -_SRC_PATH = None -_CS_PATH = None -_CS_FSSM = None -VSHARP = [0, 0, 0xFFFFFFFF, 0x31016FAC] - - -def _make_fssm(rsrc2: int, group: tuple[int, int, int]) -> bytes: - header = bytearray(0x148) - struct.pack_into("<4I", header, 0x138, rsrc2, *group) - return bytes(header) - - -def setUpModule(): - global _TMP_DIR, _SRC_PATH, _CS_PATH, _CS_FSSM - _TMP_DIR = tempfile.TemporaryDirectory() - disasm_dir = os.path.join(_TMP_DIR.name, "disasm") - fssm_dir = os.path.join(_TMP_DIR.name, "fssm") - os.mkdir(disasm_dir) - os.mkdir(fssm_dir) - _SRC_PATH = os.path.join(disasm_dir, "ps_fma_f32_clamp.s") - _CS_PATH = os.path.join(disasm_dir, "cs_fma_f32_clamp.s") - _CS_FSSM = os.path.join(fssm_dir, "cs_fma_f32_clamp.fssm") - with open(os.path.join(_TMP_DIR.name, "ps_fma_f32_clamp.dxbc"), "wb") as f: - f.write(STUB_DXBC) - - -def tearDownModule(): - global _TMP_DIR, _SRC_PATH, _CS_PATH, _CS_FSSM - if _TMP_DIR is not None: - _TMP_DIR.cleanup() - _TMP_DIR = None - _SRC_PATH = None - _CS_PATH = None - _CS_FSSM = None - - -def translate_ps(lines: list[str]) -> str: - """Translate synthetic pixel shader lines into SPIR-V text.""" - if _TMP_DIR is None: - setUpModule() - asm = ( - "; test_alu_f32_fma_clamp\n" - + "".join(f"\t{ln}\n" for ln in lines) - + "\texp mrt0 v0, v0, v0, v0 done vm\n\ts_endpgm\n" - ) - with open(_SRC_PATH, "w", encoding="utf-8", newline="\n") as f: - f.write(asm) - with warnings.catch_warnings(): - warnings.simplefilter("ignore", ResourceWarning) - return rdna2spirv.translate(_SRC_PATH) - - -def run_ps_fma( - s0: int, - s1: int, - s2: int, - *, - clamp: bool = False, - omod: str | None = None, - src0_expr: str = "v1", - src1_expr: str = "v2", - src2_expr: str = "v3", -) -> tuple[str, int]: - """Execute v_fma_f32 via translated SPIR-V fragment shader.""" - mods = [] - if omod: - mods.append(omod) - if clamp: - mods.append("clamp") - mod_str = (" " + " ".join(mods)) if mods else "" - - lines = [ - f"v_mov_b32 v1, {s0:#x}", - f"v_mov_b32 v2, {s1:#x}", - f"v_mov_b32 v3, {s2:#x}", - f"v_fma_f32_e64 v0, {src0_expr}, {src1_expr}, {src2_expr}{mod_str}", - ] - spv = translate_ps(lines) - res = si.run_fragment(spv)["%out_mrt0"][0] - return spv, res - - -def run_cs_fma_workgroup( - group_size: int, - in_s0: list[int], - in_s1: list[int], - in_s2: list[int], - *, - clamp: bool = False, -) -> list[int]: - """Execute multi-lane compute shader evaluating v_fma_f32 with clamp across a workgroup.""" - if _TMP_DIR is None: - setUpModule() - - # Buffer layout: - # 0x000 .. 0x0FF: s0 inputs (4 bytes per lane) - # 0x100 .. 0x1FF: s1 inputs - # 0x200 .. 0x2FF: s2 inputs - # 0x300 .. 0x3FF: dst outputs - with open(_CS_FSSM, "wb") as f: - f.write(_make_fssm(0x0088, (group_size, 1, 1))) - - mod_str = " clamp" if clamp else "" - asm_lines = [ - "; cs_fma_f32_clamp", - "\tv_lshlrev_b32_e32 v4, 2, v0", # v4 = lane * 4 - "\tv_add_nc_u32_e32 v5, 0x100, v4", # v5 = 0x100 + lane * 4 - "\tv_add_nc_u32_e32 v6, 0x200, v4", # v6 = 0x200 + lane * 4 - "\tv_add_nc_u32_e32 v7, 0x300, v4", # v7 = 0x300 + lane * 4 - "\tbuffer_load_dword v1, v4, s[0:3], 0 offen", - "\tbuffer_load_dword v2, v5, s[0:3], 0 offen", - "\tbuffer_load_dword v3, v6, s[0:3], 0 offen", - "\ts_waitcnt vmcnt(0)", - f"\tv_fma_f32_e64 v0, v1, v2, v3{mod_str}", - "\tbuffer_store_dword v0, v7, s[0:3], 0 offen", - "\ts_endpgm", - ] - with open(_CS_PATH, "w", encoding="utf-8", newline="\n") as f: - f.write("\n".join(asm_lines) + "\n") - - with warnings.catch_warnings(): - warnings.simplefilter("ignore", ResourceWarning) - spv = rdna2spirv.translate(_CS_PATH) - - mem: dict[int, int] = {} - for i in range(group_size): - mem[i * 4] = in_s0[i] & MASK32 - mem[0x100 + i * 4] = in_s1[i] & MASK32 - mem[0x200 + i * 4] = in_s2[i] & MASK32 - mem[0x300 + i * 4] = OLD - - res_mem = si.run_workgroup( - spv, - group_size, - group_size, - inputs_for=lambda i: {"%wg_id": (0, 0, 0), "%local_id": (i, 0, 0)}, - push_constants=VSHARP + [0] * 28, - memory=mem, - ) - return [res_mem.get(0x300 + i * 4, OLD) for i in range(group_size)] - - -# ----------------------------------------------------------------------------- -# SIMD Wave Vector Interpreter -# ----------------------------------------------------------------------------- - -class VectorALUWaveSimd: - """Deterministic SIMD wave simulator modeling RDNA2 VALU execution. - - Models: - - 64 SIMD vector lanes (or 32 lanes) - - Vector general purpose registers (VGPRs: v0..v63) - - Scalar general purpose registers (SGPRs: s0..s105) - - Execution mask (EXEC: 64-bit mask gating active lanes) - - Saturation clamping to [0.0, 1.0] across all active vector lanes - """ - - def __init__(self, wave_size: int = 64, num_vgprs: int = 64, num_sgprs: int = 106): - self.wave_size = wave_size - self.num_vgprs = num_vgprs - self.num_sgprs = num_sgprs - self.vgprs = [[OLD] * wave_size for _ in range(num_vgprs)] - self.sgprs = [0] * num_sgprs - self.exec_mask = (1 << wave_size) - 1 - - def set_exec(self, mask: int) -> None: - self.exec_mask = mask & ((1 << self.wave_size) - 1) - - def set_vgpr_lane(self, reg: int, lane: int, val: int) -> None: - self.vgprs[reg][lane] = val & MASK32 - - def get_vgpr_lane(self, reg: int, lane: int) -> int: - return self.vgprs[reg][lane] & MASK32 - - def set_vgpr_vector(self, reg: int, values: list[int]) -> None: - for lane in range(min(self.wave_size, len(values))): - self.vgprs[reg][lane] = values[lane] & MASK32 - - def get_vgpr_vector(self, reg: int) -> list[int]: - return [self.vgprs[reg][lane] & MASK32 for lane in range(self.wave_size)] - - def set_sgpr(self, reg: int, val: int) -> None: - self.sgprs[reg] = val & MASK32 - - def get_sgpr(self, reg: int) -> int: - return self.sgprs[reg] & MASK32 - - def execute_v_fma_f32( - self, - dst_reg: int, - src0: int | str, - src1: int | str, - src2: int | str, - *, - clamp: bool = False, - omod: str | None = None, - src0_neg: bool = False, - src0_abs: bool = False, - src1_neg: bool = False, - src1_abs: bool = False, - src2_neg: bool = False, - src2_abs: bool = False, - ) -> None: - """Execute v_fma_f32 across all wave lanes with EXEC mask gating.""" - for lane in range(self.wave_size): - if not ((self.exec_mask >> lane) & 1): - continue - - def resolve(src: int | str) -> int: - if isinstance(src, int): - return src & MASK32 - if src.startswith("v"): - return self.vgprs[int(src[1:])][lane] - if src.startswith("s"): - return self.sgprs[int(src[1:])] - raise ValueError(f"Unknown operand: {src}") - - s0 = resolve(src0) - s1 = resolve(src1) - s2 = resolve(src2) - self.vgprs[dst_reg][lane] = ref_fma_f32( - s0, - s1, - s2, - clamp=clamp, - omod=omod, - src0_neg=src0_neg, - src0_abs=src0_abs, - src1_neg=src1_neg, - src1_abs=src1_abs, - src2_neg=src2_neg, - src2_abs=src2_abs, - ) - - -# ----------------------------------------------------------------------------- -# Unit Tests: Oracle Verification -# ----------------------------------------------------------------------------- - -class TestFmaF32ReferenceOracle(unittest.TestCase): - """Verifies correctness of the dual reference oracle (rational vs double) and FMA semantics.""" - - def test_oracle_equivalence_on_normal_vectors(self): - """Cross-checks the exact rational Fraction oracle against the double-precision model.""" - test_values = [ - POS_ZERO, - ONE, - TWO, - HALF, - ONE_HALF, - THREE, - FOUR, - 0x3E800000, # 0.25f - 0x3E000000, # 0.125f - 0xBF800000, # -1.0f - 0xC0000000, # -2.0f - 0xBF000000, # -0.5f - 0x3F400000, # 0.75f - 0x40A00000, # 5.0f - ] - for s0, s1, s2 in itertools.product(test_values[:8], test_values[:8], test_values[:8]): - for clamp in (False, True): - r_frac = ref_fma_f32_rational(s0, s1, s2, clamp=clamp) - r_dbl = ref_fma_f32_double(s0, s1, s2, clamp=clamp) - self.assertEqual( - r_frac, - r_dbl, - f"Mismatch for s0={s0:#x}, s1={s1:#x}, s2={s2:#x}, clamp={clamp}", - ) - - def test_basic_fma_arithmetic(self): - """Standard FMA operations: D = (S0 * S1) + S2.""" - # 2.0 * 3.0 + 4.0 = 10.0 - self.assertEqual(ref_fma_f32(TWO, THREE, FOUR), f32_to_bits(10.0)) - # 0.5 * 0.5 + 0.25 = 0.5 - self.assertEqual(ref_fma_f32(HALF, HALF, f32_to_bits(0.25)), HALF) - # 1.5 * -2.0 + 4.0 = 1.0 - self.assertEqual(ref_fma_f32(ONE_HALF, f32_to_bits(-2.0), FOUR), ONE) - # 0.0 * 5.0 + 1.0 = 1.0 - self.assertEqual(ref_fma_f32(POS_ZERO, f32_to_bits(5.0), ONE), ONE) - - def test_fused_fma_vs_unfused_mad_precision(self): - """Fused FMA computes product with unbounded precision, avoiding intermediate rounding.""" - # Case 1: Positive in-bounds residual 2^-24 vs unfused premature rounding to zero. - # x = 1.0 + 2^-12, y = 1.0 + 2^-12, z = -(1.0 + 2^-11). - # x * y = 1 + 2^-11 + 2^-24. - # In unfused MAD: 1 + 2^-11 + 2^-24 rounds to 1 + 2^-11, so (1 + 2^-11) - (1 + 2^-11) = 0.0. - # In fused FMA: exact product + z = 2^-24 (0x33800000), which stays 2^-24 under clamp. - x1 = f32_to_bits(1.0 + 2.0 ** -12) - y1 = f32_to_bits(1.0 + 2.0 ** -12) - z1 = f32_to_bits(-(1.0 + 2.0 ** -11)) - - prod_unfused1 = f32_to_bits(bits_to_f32(x1) * bits_to_f32(y1)) - mad_unfused1 = f32_to_bits(bits_to_f32(prod_unfused1) + bits_to_f32(z1)) - self.assertEqual(mad_unfused1, POS_ZERO) - - fma_fused1 = ref_fma_f32(x1, y1, z1) - self.assertEqual(fma_fused1, 0x33800000) # 2^-24 - self.assertEqual(ref_fma_f32(x1, y1, z1, clamp=True), 0x33800000) - - # Case 2: Negative residual -2^-46 clamped to +0.0 vs unclamped negative preservation. - # x = 1.0 + 2^-23, y = 1.0 - 2^-23, z = -1.0. - # Exact product is 1.0 - 2^-46. - # In unfused MAD: product rounds to 1.0, giving 0.0. - # In fused FMA: exact (1 - 2^-46) - 1.0 = -2^-46 (0xA8800000). - # Clamping saturates negative -2^-46 to +0.0f (0x00000000). - x2 = f32_to_bits(1.0 + 2.0 ** -23) - y2 = f32_to_bits(1.0 - 2.0 ** -23) - z2 = f32_to_bits(-1.0) - - prod_unfused2 = f32_to_bits(bits_to_f32(x2) * bits_to_f32(y2)) - mad_unfused2 = f32_to_bits(bits_to_f32(prod_unfused2) + bits_to_f32(z2)) - self.assertEqual(mad_unfused2, POS_ZERO) - - fma_fused2 = ref_fma_f32(x2, y2, z2) - self.assertEqual(fma_fused2, 0xA8800000) # -2^-46 - self.assertEqual(ref_fma_f32(x2, y2, z2, clamp=True), POS_ZERO) - - def test_clamp_saturation_boundaries(self): - """Clamp saturates to [0.0, 1.0]: values > 1.0 clamp to 1.0, values < 0.0 clamp to +0.0.""" - # Interior values: pass through - for val in (0.0, 0.125, 0.25, 0.5, 0.75, 1.0): - b = f32_to_bits(val) - self.assertEqual(ref_fma_f32(b, ONE, POS_ZERO, clamp=True), b) - - # Values > 1.0 clamp to 1.0f (0x3F800000) - for val in (1.0001, 1.5, 2.0, 10.0, 1e20): - b = f32_to_bits(val) - self.assertEqual(ref_fma_f32(b, ONE, POS_ZERO, clamp=True), ONE) - self.assertEqual(ref_fma_f32(ONE, b, POS_ZERO, clamp=True), ONE) - - # Values < 0.0 clamp to +0.0f (0x00000000) - for val in (-0.0001, -0.5, -1.0, -10.0, -1e20): - b = f32_to_bits(val) - self.assertEqual(ref_fma_f32(b, ONE, POS_ZERO, clamp=True), POS_ZERO) - self.assertEqual(ref_fma_f32(ONE, b, POS_ZERO, clamp=True), POS_ZERO) - - # Infinities clamp to 1.0 and +0.0 - self.assertEqual(ref_fma_f32(POS_INF, ONE, POS_ZERO, clamp=True), ONE) - self.assertEqual(ref_fma_f32(NEG_INF, ONE, POS_ZERO, clamp=True), POS_ZERO) - - def test_source_modifiers_neg_abs(self): - """VOP3 source modifiers on S0, S1, S2.""" - # -(2.0) * 3.0 + 10.0 = 4.0 - self.assertEqual(ref_fma_f32(TWO, THREE, f32_to_bits(10.0), src0_neg=True), FOUR) - # |-2.0| * 3.0 + 4.0 = 10.0 - self.assertEqual(ref_fma_f32(f32_to_bits(-2.0), THREE, FOUR, src0_abs=True), f32_to_bits(10.0)) - # -|-2.0| * 3.0 + 10.0 = 4.0 - self.assertEqual( - ref_fma_f32(f32_to_bits(-2.0), THREE, f32_to_bits(10.0), src0_neg=True, src0_abs=True), - FOUR, - ) - - # Combined with clamp: - # -(2.0) * 3.0 + 4.0 = -2.0 -> clamped to 0.0 - self.assertEqual(ref_fma_f32(TWO, THREE, FOUR, src0_neg=True, clamp=True), POS_ZERO) - # 0.5 * 0.5 - 0.5 = -0.25 -> clamped to 0.0 - self.assertEqual(ref_fma_f32(HALF, HALF, HALF, src2_neg=True, clamp=True), POS_ZERO) - - def test_output_modifiers_and_clamp(self): - """Output modifiers (mul:2, mul:4, div:2) are applied before clamp.""" - # 0.25 * 1.0 + 0.125 = 0.375 - # with mul:2 -> 0.75 (within [0.0, 1.0]) - s0, s1, s2 = f32_to_bits(0.25), ONE, f32_to_bits(0.125) - self.assertEqual(ref_fma_f32(s0, s1, s2, omod="mul:2", clamp=True), f32_to_bits(0.75)) - - # with mul:4 -> 1.5 -> clamped to 1.0 - self.assertEqual(ref_fma_f32(s0, s1, s2, omod="mul:4", clamp=True), ONE) - - # 1.5 * 1.0 + 0.5 = 2.0 - # with div:2 -> 1.0 (clamped to 1.0) - self.assertEqual(ref_fma_f32(ONE_HALF, ONE, HALF, omod="div:2", clamp=True), ONE) - - -# ----------------------------------------------------------------------------- -# Unit Tests: Shader Translation and Execution -# ----------------------------------------------------------------------------- - -class TestFmaF32ShaderTranslation(unittest.TestCase): - """Verifies that RDNA2 v_fma_f32 translates to valid SPIR-V and executes accurately.""" - - def test_translated_spirv_structure(self): - """Translating v_fma_f32 with and without clamp generates GLSL Fma and FClamp.""" - spv_unclamped, _ = run_ps_fma(HALF, HALF, HALF, clamp=False) - self.assertIn("OpExtInst %float %glsl Fma", spv_unclamped) - self.assertNotIn("OpExtInst %float %glsl FClamp", spv_unclamped) - - spv_clamped, _ = run_ps_fma(HALF, HALF, HALF, clamp=True) - self.assertIn("OpExtInst %float %glsl Fma", spv_clamped) - self.assertIn("OpExtInst %float %glsl FClamp", spv_clamped) - - def test_shader_execution_normal_vectors(self): - """End-to-end execution of unclamped v_fma_f32 matches reference oracle.""" - cases = [ - (f32_to_bits(0.5), f32_to_bits(0.5), f32_to_bits(0.25)), - (f32_to_bits(2.0), f32_to_bits(3.0), f32_to_bits(4.0)), - (f32_to_bits(-1.5), f32_to_bits(2.0), f32_to_bits(5.0)), - (f32_to_bits(0.0), f32_to_bits(10.0), f32_to_bits(0.75)), - ] - for s0, s1, s2 in cases: - with self.subTest(s0=hex(s0), s1=hex(s1), s2=hex(s2)): - _, got = run_ps_fma(s0, s1, s2, clamp=False) - want = ref_fma_f32(s0, s1, s2, clamp=False) - self.assertEqual(got, want) - - def test_shader_execution_clamped_vectors(self): - """End-to-end execution of clamped v_fma_f32 saturates into [0.0, 1.0].""" - cases = [ - # In-bounds: 0.5 * 0.5 + 0.25 = 0.5 - (f32_to_bits(0.5), f32_to_bits(0.5), f32_to_bits(0.25)), - # Over-range: 2.0 * 2.0 + 1.0 = 5.0 -> clamped to 1.0 - (f32_to_bits(2.0), f32_to_bits(2.0), f32_to_bits(1.0)), - # Under-range: -1.0 * 2.0 + 0.5 = -1.5 -> clamped to 0.0 - (f32_to_bits(-1.0), f32_to_bits(2.0), f32_to_bits(0.5)), - # Edge: exactly 1.0 - (f32_to_bits(1.0), f32_to_bits(1.0), f32_to_bits(0.0)), - # Edge: exactly 0.0 - (f32_to_bits(0.0), f32_to_bits(0.0), f32_to_bits(0.0)), - ] - for s0, s1, s2 in cases: - with self.subTest(s0=hex(s0), s1=hex(s1), s2=hex(s2)): - _, got = run_ps_fma(s0, s1, s2, clamp=True) - want = ref_fma_f32(s0, s1, s2, clamp=True) - self.assertEqual(got, want) - - -# ----------------------------------------------------------------------------- -# Unit Tests: SIMD Multi-Lane Execution & [0.0, 1.0] Saturation Clamping -# ----------------------------------------------------------------------------- - -class TestFmaF32SimdMultiLane(unittest.TestCase): - """Verifies SIMD wave vector execution and [0.0, 1.0] saturation clamping.""" - - def test_wave64_linear_sweep_saturation_clamping(self): - """64-lane SIMD wave evaluating a linear sweep across clamp boundaries.""" - simd = VectorALUWaveSimd(wave_size=64) - - # S0: Linear ramp from -1.5 to +1.5 across 64 lanes - # S1: Uniform 1.0f - # S2: Uniform 0.0f - # S0 * S1 + S2 = S0 - ramp = [f32_to_bits(-1.5 + (3.0 * i / 63.0)) for i in range(64)] - simd.set_vgpr_vector(1, ramp) - simd.set_vgpr_vector(2, [ONE] * 64) - simd.set_vgpr_vector(3, [POS_ZERO] * 64) - - # 1. Unclamped execution: full dynamic range preserved - simd.execute_v_fma_f32(0, "v1", "v2", "v3", clamp=False) - out_unclamped = simd.get_vgpr_vector(0) - self.assertEqual(out_unclamped, ramp) - - # 2. Clamped execution: saturates to [0.0, 1.0] - simd.execute_v_fma_f32(0, "v1", "v2", "v3", clamp=True) - out_clamped = simd.get_vgpr_vector(0) - - for i in range(64): - val = -1.5 + (3.0 * i / 63.0) - got = out_clamped[i] - if val < 0.0: - self.assertEqual(got, POS_ZERO, f"Lane {i} (val={val}) must saturate to +0.0") - elif val > 1.0: - self.assertEqual(got, ONE, f"Lane {i} (val={val}) must saturate to 1.0") - else: - self.assertEqual(got, ramp[i], f"Lane {i} (val={val}) must pass through unmodified") - - def test_wave32_and_wave64_exec_mask_gating(self): - """Active lanes compute clamped FMA; inactive lanes strictly retain prior register state.""" - for wave_size in (32, 64): - with self.subTest(wave_size=wave_size): - simd = VectorALUWaveSimd(wave_size=wave_size) - simd.set_vgpr_vector(1, [TWO] * wave_size) # 2.0 - simd.set_vgpr_vector(2, [TWO] * wave_size) # 2.0 - simd.set_vgpr_vector(3, [ONE] * wave_size) # 1.0 -> 5.0 -> clamped to 1.0 - - # 1. Even lanes active - even_mask = 0x5555555555555555 if wave_size == 64 else 0x55555555 - simd.set_exec(even_mask) - simd.execute_v_fma_f32(0, "v1", "v2", "v3", clamp=True) - out = simd.get_vgpr_vector(0) - for lane in range(wave_size): - if lane % 2 == 0: - self.assertEqual(out[lane], ONE, f"Active lane {lane} should clamp to 1.0") - else: - self.assertEqual(out[lane], OLD, f"Inactive lane {lane} must retain OLD") - - # 2. Inactive wave (exec = 0): no lanes modified - simd2 = VectorALUWaveSimd(wave_size=wave_size) - simd2.set_exec(0) - simd2.execute_v_fma_f32(0, "v1", "v2", "v3", clamp=True) - self.assertEqual(simd2.get_vgpr_vector(0), [OLD] * wave_size) - - def test_wave_multi_channel_color_clamping(self): - """Simulates 64 pixels computing clamped color intensity: clamp((base * light) + ambient).""" - simd = VectorALUWaveSimd(wave_size=64) - - base = [] - light = [] - ambient = [] - expected = [] - - for i in range(64): - if i < 16: - b, l, a = 0.5, 0.8, 0.1 # 0.5 * 0.8 + 0.1 = 0.5 - exp = f32_to_bits(0.5) - elif i < 32: - b, l, a = 0.9, 1.8, 0.2 # 0.9 * 1.8 + 0.2 = 1.82 -> clamped to 1.0 - exp = ONE - elif i < 48: - b, l, a = 0.2, 0.5, -0.4 # 0.2 * 0.5 - 0.4 = -0.3 -> clamped to 0.0 - exp = POS_ZERO - else: - b, l, a = 1.0, 1.0, 0.0 # 1.0 * 1.0 + 0.0 = 1.0 - exp = ONE - base.append(f32_to_bits(b)) - light.append(f32_to_bits(l)) - ambient.append(f32_to_bits(a)) - expected.append(exp) - - simd.set_vgpr_vector(1, base) - simd.set_vgpr_vector(2, light) - simd.set_vgpr_vector(3, ambient) - - simd.execute_v_fma_f32(0, "v1", "v2", "v3", clamp=True) - self.assertEqual(simd.get_vgpr_vector(0), expected) - - def test_wave_scalar_sgpr_broadcast(self): - """Scalar SGPR operand broadcast across all lanes in the wave combined with per-lane VGPRs.""" - simd = VectorALUWaveSimd(wave_size=64) - - v1_in = [f32_to_bits(float(i) * 0.05 - 0.5) for i in range(64)] - simd.set_vgpr_vector(1, v1_in) - - simd.set_sgpr(4, TWO) - simd.set_sgpr(5, f32_to_bits(0.25)) - - simd.execute_v_fma_f32(0, "v1", "s4", "s5", clamp=True) - out = simd.get_vgpr_vector(0) - - for lane in range(64): - x = float(lane) * 0.05 - 0.5 - want = ref_fma_f32(v1_in[lane], TWO, f32_to_bits(0.25), clamp=True) - self.assertEqual(out[lane], want, f"Lane {lane} mismatch for {x} * 2.0 + 0.25") - - def test_compute_shader_multi_lane_workgroup(self): - """End-to-end multi-lane compute shader execution via spirv_mini_interp.run_workgroup.""" - group_size = 16 - in_s0 = [f32_to_bits(float(i) - 4.0) for i in range(group_size)] # -4.0 .. 11.0 - in_s1 = [HALF] * group_size # * 0.5 - in_s2 = [f32_to_bits(0.25)] * group_size # + 0.25 - - res = run_cs_fma_workgroup(group_size, in_s0, in_s1, in_s2, clamp=True) - - for i in range(group_size): - want = ref_fma_f32(in_s0[i], in_s1[i], in_s2[i], clamp=True) - self.assertEqual(res[i], want, f"Compute shader lane {i} mismatch") - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_alu_f32_min_max.py b/tests/semantic/test_alu_f32_min_max.py deleted file mode 100644 index 123d92fae..000000000 --- a/tests/semantic/test_alu_f32_min_max.py +++ /dev/null @@ -1,828 +0,0 @@ -"""Semantic interpreter tests for single-precision floating point min/max (v_min_f32, v_max_f32, v_min3_f32, v_max3_f32, v_med3_f32). - -Models IEEE 754-2008 / 2019 binary32 minNum/maxNum and AMD RDNA2 / GFX10 VALU semantics: - - v_min_f32: D.f = min(S0.f, S1.f) - - v_max_f32: D.f = max(S0.f, S1.f) - - v_min3_f32: D.f = min(min(S0.f, S1.f), S2.f) - - v_max3_f32: D.f = max(max(S0.f, S1.f), S2.f) - - v_med3_f32: D.f = median(S0.f, S1.f, S2.f) with fallback to min3 if any operand is NaN. - -RDNA2 Floating-Point Rules: - 1. NaN suppression (IEEE 754-2008 minNum/maxNum): - If one operand is NaN and the other is a valid floating-point number, the non-NaN operand - is returned with its bit pattern intact. If both operands are NaN, a quiet NaN is returned. - 2. Signed zeros (-0.0 < +0.0): - RDNA2 orders -0.0 strictly below +0.0 (measured on hardware; docs/design.md). - min(+0.0, -0.0) = -0.0, min(-0.0, +0.0) = -0.0 - max(+0.0, -0.0) = +0.0, max(-0.0, +0.0) = +0.0 - 3. Infinities and Extreme Floats: - -INF < -FLT_MAX < ... < -FLT_MIN < -0.0 < +0.0 < +FLT_MIN < ... < +FLT_MAX < +INF. - Subnormals are strictly preserved (not flushed to zero in IEEE mode). - 4. VOP2 (e32) and VOP3 (e64) Encoding Forms & Modifiers: - Input modifiers: neg (-src), abs (|src|), and neg-abs (-|src|). - Output modifier: clamp to [0.0, 1.0]. - 5. Translation lowering: - tools/rdna2spirv.py maps v_min_f32, v_max_f32, v_min3_f32, and v_max3_f32 to GLSL.std.450 - NMin and NMax (OpExtInst %float %glsl NMin/NMax), which enforce identical NaN-skipping and - signed-zero rules. v_med3_f32 lowers to FClamp with an OpIsNan check selecting NMin(NMin(x, y), z). - 6. Wavefront SIMD execution: - Evaluates lockstep execution across 32 and 64 lanes with divergent float inputs. - -Standard library Python only; zero third-party dependencies; zero game data. -Python 3.9+ compatible (from __future__ import annotations). -""" -from __future__ import annotations - -import itertools -import math -import os -import struct -import sys -import tempfile -import unittest -import warnings - -HERE = os.path.dirname(os.path.abspath(__file__)) -ROOT = os.path.dirname(os.path.dirname(HERE)) -TOOLS_DIR = os.environ.get("LEONIDA_TOOLS_DIR") or os.path.join(ROOT, "tools") - -sys.dont_write_bytecode = True -if TOOLS_DIR not in sys.path: - sys.path.insert(0, TOOLS_DIR) -if HERE not in sys.path: - sys.path.insert(0, HERE) - -import rdna2spirv # noqa: E402 -import spirv_mini_interp as si # noqa: E402 - -MASK32 = 0xFFFFFFFF -SIGN_MASK = 0x80000000 -EXP_MASK = 0x7F800000 -MANT_MASK = 0x007FFFFF - -# Canonical IEEE 754 binary32 bit patterns -POS_ZERO = 0x00000000 -NEG_ZERO = 0x80000000 -HALF = 0x3F000000 # 0.5 -NEG_HALF = 0xBF000000 # -0.5 -ONE = 0x3F800000 # 1.0 -NEG_ONE = 0xBF800000 # -1.0 -ONE_HALF = 0x3FC00000 # 1.5 -TWO = 0x40000000 # 2.0 -NEG_TWO = 0xC0000000 # -2.0 -THREE = 0x40400000 # 3.0 -FOUR = 0x40800000 # 4.0 -FIVE = 0x40A00000 # 5.0 -TEN = 0x41200000 # 10.0 -NEG_TEN = 0xC1200000 # -10.0 -FLT_MIN = 0x00800000 # Smallest positive normal: 2^-126 -NEG_FLT_MIN = 0x80800000 # -2^-126 -FLT_MAX = 0x7F7FFFFF # (2 - 2^-23) * 2^127 -NEG_FLT_MAX = 0xFF7FFFFF -POS_INF = 0x7F800000 # +infinity -NEG_INF = 0xFF800000 # -infinity -QNAN = 0x7FC00000 # Canonical quiet NaN -NEG_QNAN = 0xFFC00000 # Negative quiet NaN -QNAN_PAYLOAD = 0x7FC10001 # Quiet NaN with payload A -QNAN_PAYLOAD_B = 0xFFC20002 # Quiet NaN with payload B -SNAN = 0x7F800001 # Signaling NaN -SUBNORM_MIN = 0x00000001 # Smallest subnormal: 2^-149 -SUBNORM_MAX = 0x007FFFFF # Largest positive subnormal -NEG_SUBNORM_MIN = 0x80000001 -NEG_SUBNORM_MAX = 0x807FFFFF - -STUB_DXBC = b"DXBC" + bytes(24) + struct.pack(" float: - """Decode 32-bit unsigned integer to IEEE 754 single-precision float.""" - return struct.unpack(" int: - """Encode float to IEEE 754 single-precision 32-bit unsigned integer.""" - try: - return struct.unpack(" 0 else NEG_INF - - -def is_nan_bits(bits: int) -> bool: - """True if 32-bit integer represents an IEEE 754 NaN.""" - bits &= MASK32 - return (bits & EXP_MASK) == EXP_MASK and (bits & MANT_MASK) != 0 - - -def is_qnan_bits(bits: int) -> bool: - """True if bits represent a quiet NaN (MSB of mantissa is 1).""" - bits &= MASK32 - return is_nan_bits(bits) and bool(bits & 0x00400000) - - -def is_snan_bits(bits: int) -> bool: - """True if bits represent a signaling NaN (MSB of mantissa is 0).""" - bits &= MASK32 - return is_nan_bits(bits) and not bool(bits & 0x00400000) - - -def is_subnormal_bits(bits: int) -> bool: - """True if bits represent an IEEE 754 subnormal (denormal) number.""" - bits &= MASK32 - return (bits & EXP_MASK) == 0 and (bits & MANT_MASK) != 0 - - -def zero_ordered_key(v: float) -> tuple[float, float]: - """Sort key ordering -0.0 strictly below +0.0.""" - return (v, math.copysign(1.0, v)) - - -def ref_min_f32(s0: int, s1: int) -> int: - """Pure bitwise reference oracle for RDNA2 v_min_f32. - - Rules: - - If one operand is NaN, return the other operand unchanged. - - If both operands are NaN, return canonical quiet NaN (0x7FC00000). - - If values are non-NaN, order -0.0 < +0.0. - """ - s0 &= MASK32 - s1 &= MASK32 - nan0 = is_nan_bits(s0) - nan1 = is_nan_bits(s1) - if nan0 and nan1: - return QNAN - if nan0: - return s1 - if nan1: - return s0 - - f0 = bits_to_f32(s0) - f1 = bits_to_f32(s1) - k0 = zero_ordered_key(f0) - k1 = zero_ordered_key(f1) - return s0 if k0 <= k1 else s1 - - -def ref_max_f32(s0: int, s1: int) -> int: - """Pure bitwise reference oracle for RDNA2 v_max_f32. - - Rules: - - If one operand is NaN, return the other operand unchanged. - - If both operands are NaN, return canonical quiet NaN (0x7FC00000). - - If values are non-NaN, order -0.0 < +0.0. - """ - s0 &= MASK32 - s1 &= MASK32 - nan0 = is_nan_bits(s0) - nan1 = is_nan_bits(s1) - if nan0 and nan1: - return QNAN - if nan0: - return s1 - if nan1: - return s0 - - f0 = bits_to_f32(s0) - f1 = bits_to_f32(s1) - k0 = zero_ordered_key(f0) - k1 = zero_ordered_key(f1) - return s0 if k0 >= k1 else s1 - - -def ref_min3_f32(s0: int, s1: int, s2: int) -> int: - """Pure bitwise reference oracle for RDNA2 v_min3_f32: min(min(s0, s1), s2).""" - return ref_min_f32(ref_min_f32(s0, s1), s2) - - -def ref_max3_f32(s0: int, s1: int, s2: int) -> int: - """Pure bitwise reference oracle for RDNA2 v_max3_f32: max(max(s0, s1), s2).""" - return ref_max_f32(ref_max_f32(s0, s1), s2) - - -def ref_med3_f32(s0: int, s1: int, s2: int) -> int: - """Pure bitwise reference oracle for RDNA2 v_med3_f32. - - Rules: - - If any operand is NaN, hardware evaluates min3(s0, s1, s2). - - Otherwise, returns the median with -0.0 < +0.0 tie-breaking. - """ - if is_nan_bits(s0) or is_nan_bits(s1) or is_nan_bits(s2): - return ref_min3_f32(s0, s1, s2) - triplet = [(bits_to_f32(s), zero_ordered_key(bits_to_f32(s)), s) for s in (s0, s1, s2)] - triplet.sort(key=lambda t: t[1]) - return triplet[1][2] - - -def apply_f32_modifiers(bits: int, neg: bool = False, abs_val: bool = False) -> int: - """Applies VOP3 input modifiers: abs (|x|) first, then neg (-x).""" - bits &= MASK32 - if abs_val: - bits &= ~SIGN_MASK - if neg: - bits ^= SIGN_MASK - return bits & MASK32 - - -def apply_f32_clamp(bits: int) -> int: - """Applies VOP3 clamp modifier: clamps result to [0.0, 1.0].""" - bits &= MASK32 - if is_nan_bits(bits): - return bits - val = bits_to_f32(bits) - if val < 0.0 or (val == 0.0 and (bits & SIGN_MASK)): - return POS_ZERO - if val > 1.0: - return ONE - return bits - - -_TMP_DIR: tempfile.TemporaryDirectory[str] | None = None -_SRC_PATH: str | None = None - - -def setUpModule() -> None: - global _TMP_DIR, _SRC_PATH - _TMP_DIR = tempfile.TemporaryDirectory() - disasm_dir = os.path.join(_TMP_DIR.name, "disasm") - os.mkdir(disasm_dir) - _SRC_PATH = os.path.join(disasm_dir, "ps_f32_min_max.s") - with open(os.path.join(_TMP_DIR.name, "ps_f32_min_max.dxbc"), "wb") as f: - f.write(STUB_DXBC) - - -def tearDownModule() -> None: - global _TMP_DIR - if _TMP_DIR is not None: - _TMP_DIR.cleanup() - _TMP_DIR = None - - -def run_f32_2op( - op: str, - s0: int, - s1: int, - e64: bool = False, - neg0: bool = False, - abs0: bool = False, - neg1: bool = False, - abs1: bool = False, - clamp: bool = False, -) -> int: - """Translates and runs a 2-operand float min/max instruction through rdna2spirv and spirv_mini_interp.""" - if _TMP_DIR is None or _SRC_PATH is None: - setUpModule() - assert _SRC_PATH is not None - - def fmt_src(v_name: str, neg: bool, abs_val: bool) -> str: - s = v_name - if abs_val: - s = f"|{s}|" - if neg: - s = f"-{s}" - return s - - instr_name = f"{op}_e64" if e64 else (f"{op}_e32" if not (neg0 or abs0 or neg1 or abs1 or clamp) else f"{op}_e64") - src0_str = fmt_src("v1", neg0, abs0) - src1_str = fmt_src("v2", neg1, abs1) - clamp_str = " clamp" if clamp else "" - - lines = [ - f"\tv_mov_b32 v1, {s0 & MASK32:#x}", - f"\tv_mov_b32 v2, {s1 & MASK32:#x}", - f"\t{instr_name} v0, {src0_str}, {src1_str}{clamp_str}", - "\texp mrt0 v0, v0, v0, v0 done vm", - "\ts_endpgm", - ] - asm = "; ps_f32_min_max\n" + "\n".join(lines) + "\n" - with open(_SRC_PATH, "w", encoding="utf-8") as f: - f.write(asm) - with warnings.catch_warnings(): - warnings.simplefilter("ignore", ResourceWarning) - spv = rdna2spirv.translate(_SRC_PATH) - return si.run_fragment(spv)["%out_mrt0"][0] - - -def run_f32_3op( - op: str, - s0: int, - s1: int, - s2: int, - neg0: bool = False, - abs0: bool = False, - neg1: bool = False, - abs1: bool = False, - neg2: bool = False, - abs2: bool = False, - clamp: bool = False, -) -> int: - """Translates and runs a 3-operand float min/max/med instruction through rdna2spirv and spirv_mini_interp.""" - if _TMP_DIR is None or _SRC_PATH is None: - setUpModule() - assert _SRC_PATH is not None - - def fmt_src(v_name: str, neg: bool, abs_val: bool) -> str: - s = v_name - if abs_val: - s = f"|{s}|" - if neg: - s = f"-{s}" - return s - - clamp_str = " clamp" if clamp else "" - lines = [ - f"\tv_mov_b32 v1, {s0 & MASK32:#x}", - f"\tv_mov_b32 v2, {s1 & MASK32:#x}", - f"\tv_mov_b32 v3, {s2 & MASK32:#x}", - f"\t{op} v0, {fmt_src('v1', neg0, abs0)}, {fmt_src('v2', neg1, abs1)}, {fmt_src('v3', neg2, abs2)}{clamp_str}", - "\texp mrt0 v0, v0, v0, v0 done vm", - "\ts_endpgm", - ] - asm = "; ps_f32_min_max3\n" + "\n".join(lines) + "\n" - with open(_SRC_PATH, "w", encoding="utf-8") as f: - f.write(asm) - with warnings.catch_warnings(): - warnings.simplefilter("ignore", ResourceWarning) - spv = rdna2spirv.translate(_SRC_PATH) - return si.run_fragment(spv)["%out_mrt0"][0] - - -class TestF32ReferenceOracle2Op(unittest.TestCase): - """Verifies the pure-Python reference oracle ref_min_f32 and ref_max_f32.""" - - def test_ordinary_comparisons(self) -> None: - self.assertEqual(ref_min_f32(ONE, TWO), ONE) - self.assertEqual(ref_min_f32(TWO, ONE), ONE) - self.assertEqual(ref_max_f32(ONE, TWO), TWO) - self.assertEqual(ref_max_f32(TWO, ONE), TWO) - self.assertEqual(ref_min_f32(NEG_ONE, NEG_TWO), NEG_TWO) - self.assertEqual(ref_max_f32(NEG_ONE, NEG_TWO), NEG_ONE) - self.assertEqual(ref_min_f32(NEG_ONE, ONE), NEG_ONE) - self.assertEqual(ref_max_f32(NEG_ONE, ONE), ONE) - - def test_signed_zeros(self) -> None: - self.assertEqual(ref_min_f32(POS_ZERO, NEG_ZERO), NEG_ZERO) - self.assertEqual(ref_min_f32(NEG_ZERO, POS_ZERO), NEG_ZERO) - self.assertEqual(ref_min_f32(POS_ZERO, POS_ZERO), POS_ZERO) - self.assertEqual(ref_min_f32(NEG_ZERO, NEG_ZERO), NEG_ZERO) - - self.assertEqual(ref_max_f32(POS_ZERO, NEG_ZERO), POS_ZERO) - self.assertEqual(ref_max_f32(NEG_ZERO, POS_ZERO), POS_ZERO) - self.assertEqual(ref_max_f32(POS_ZERO, POS_ZERO), POS_ZERO) - self.assertEqual(ref_max_f32(NEG_ZERO, NEG_ZERO), NEG_ZERO) - - def test_infinities(self) -> None: - self.assertEqual(ref_min_f32(NEG_INF, POS_INF), NEG_INF) - self.assertEqual(ref_max_f32(NEG_INF, POS_INF), POS_INF) - self.assertEqual(ref_min_f32(POS_INF, FLT_MAX), FLT_MAX) - self.assertEqual(ref_max_f32(POS_INF, FLT_MAX), POS_INF) - self.assertEqual(ref_min_f32(NEG_INF, NEG_FLT_MAX), NEG_INF) - self.assertEqual(ref_max_f32(NEG_INF, NEG_FLT_MAX), NEG_FLT_MAX) - - def test_normals_and_subnormals(self) -> None: - self.assertEqual(ref_min_f32(FLT_MIN, SUBNORM_MAX), SUBNORM_MAX) - self.assertEqual(ref_max_f32(FLT_MIN, SUBNORM_MAX), FLT_MIN) - self.assertEqual(ref_min_f32(SUBNORM_MIN, SUBNORM_MAX), SUBNORM_MIN) - self.assertEqual(ref_max_f32(SUBNORM_MIN, SUBNORM_MAX), SUBNORM_MAX) - self.assertEqual(ref_min_f32(NEG_FLT_MIN, NEG_SUBNORM_MAX), NEG_FLT_MIN) - self.assertEqual(ref_max_f32(NEG_FLT_MIN, NEG_SUBNORM_MAX), NEG_SUBNORM_MAX) - - def test_nan_suppression(self) -> None: - self.assertEqual(ref_min_f32(QNAN, ONE), ONE) - self.assertEqual(ref_min_f32(ONE, QNAN), ONE) - self.assertEqual(ref_max_f32(QNAN, ONE), ONE) - self.assertEqual(ref_max_f32(ONE, QNAN), ONE) - - self.assertEqual(ref_min_f32(SNAN, TWO), TWO) - self.assertEqual(ref_max_f32(TWO, SNAN), TWO) - - self.assertTrue(is_nan_bits(ref_min_f32(QNAN, SNAN))) - self.assertTrue(is_nan_bits(ref_max_f32(QNAN, SNAN))) - - def test_nan_payload_preservation(self) -> None: - custom_float = 0x3EAAAAAB # 0.33333334 - self.assertEqual(ref_min_f32(QNAN_PAYLOAD, custom_float), custom_float) - self.assertEqual(ref_max_f32(custom_float, QNAN_PAYLOAD), custom_float) - - -class TestF32ReferenceOracle3Op(unittest.TestCase): - """Verifies reference oracles for 3-way instructions: min3, max3, med3.""" - - def test_min3_permutations(self) -> None: - triples = [ - (ONE, TWO, THREE), - (NEG_TEN, POS_ZERO, TEN), - (NEG_TWO, NEG_ONE, f32_to_bits(-3.0)), - ] - for a, b, c in triples: - expected = ref_min_f32(ref_min_f32(a, b), c) - for p0, p1, p2 in itertools.permutations([a, b, c]): - self.assertEqual(ref_min3_f32(p0, p1, p2), expected) - - def test_max3_permutations(self) -> None: - triples = [ - (ONE, TWO, THREE), - (NEG_TEN, POS_ZERO, TEN), - (NEG_TWO, NEG_ONE, f32_to_bits(-3.0)), - ] - for a, b, c in triples: - expected = ref_max_f32(ref_max_f32(a, b), c) - for p0, p1, p2 in itertools.permutations([a, b, c]): - self.assertEqual(ref_max3_f32(p0, p1, p2), expected) - - def test_med3_permutations(self) -> None: - for p in itertools.permutations([ONE, TWO, THREE]): - self.assertEqual(ref_med3_f32(*p), TWO) - - for p in itertools.permutations([NEG_TEN, POS_ZERO, TEN]): - self.assertEqual(ref_med3_f32(*p), POS_ZERO) - - def test_signed_zeros_3op(self) -> None: - self.assertEqual(ref_min3_f32(POS_ZERO, NEG_ZERO, ONE), NEG_ZERO) - self.assertEqual(ref_max3_f32(POS_ZERO, NEG_ZERO, NEG_ONE), POS_ZERO) - self.assertEqual(ref_med3_f32(POS_ZERO, NEG_ZERO, ONE), POS_ZERO) - self.assertEqual(ref_med3_f32(POS_ZERO, NEG_ZERO, NEG_ONE), NEG_ZERO) - - def test_med3_nan_fallback_to_min3(self) -> None: - self.assertEqual(ref_med3_f32(QNAN, TWO, THREE), TWO) - self.assertEqual(ref_med3_f32(ONE, QNAN, THREE), ONE) - self.assertEqual(ref_med3_f32(ONE, TWO, QNAN), ONE) - self.assertEqual(ref_med3_f32(QNAN, QNAN, FOUR), FOUR) - - def test_extreme_floats_3op(self) -> None: - self.assertEqual(ref_min3_f32(NEG_INF, ONE, POS_INF), NEG_INF) - self.assertEqual(ref_max3_f32(NEG_INF, ONE, POS_INF), POS_INF) - self.assertEqual(ref_med3_f32(NEG_INF, ONE, POS_INF), ONE) - - -class TestVMinVMaxF32Execution(unittest.TestCase): - """Executes synthetic shaders testing v_min_f32 and v_max_f32 in spirv_mini_interp.""" - - TEST_PAIRS = [ - (ONE, TWO), - (TWO, ONE), - (NEG_ONE, NEG_TWO), - (NEG_TWO, NEG_ONE), - (HALF, ONE_HALF), - (POS_INF, NEG_INF), - (FLT_MAX, ONE), - (NEG_FLT_MAX, NEG_ONE), - (FLT_MIN, SUBNORM_MAX), - (SUBNORM_MIN, FLT_MIN), - (QNAN, THREE), - (FOUR, QNAN), - ] - - def test_v_min_f32_e32_and_e64(self) -> None: - for s0, s1 in self.TEST_PAIRS: - expected = ref_min_f32(s0, s1) - with self.subTest(s0=hex(s0), s1=hex(s1), form="e32"): - got_e32 = run_f32_2op("v_min_f32", s0, s1, e64=False) - self.assertEqual(got_e32, expected) - with self.subTest(s0=hex(s0), s1=hex(s1), form="e64"): - got_e64 = run_f32_2op("v_min_f32", s0, s1, e64=True) - self.assertEqual(got_e64, expected) - - def test_v_max_f32_e32_and_e64(self) -> None: - for s0, s1 in self.TEST_PAIRS: - expected = ref_max_f32(s0, s1) - with self.subTest(s0=hex(s0), s1=hex(s1), form="e32"): - got_e32 = run_f32_2op("v_max_f32", s0, s1, e64=False) - self.assertEqual(got_e32, expected) - with self.subTest(s0=hex(s0), s1=hex(s1), form="e64"): - got_e64 = run_f32_2op("v_max_f32", s0, s1, e64=True) - self.assertEqual(got_e64, expected) - - -class TestVMin3VMax3VMed3Execution(unittest.TestCase): - """Executes synthetic shaders testing v_min3_f32, v_max3_f32, and v_med3_f32.""" - - TEST_TRIPLES = [ - (ONE, TWO, THREE), - (THREE, ONE, TWO), - (TWO, THREE, ONE), - (NEG_ONE, NEG_TWO, f32_to_bits(-3.0)), - (NEG_TEN, POS_ZERO, TEN), - (HALF, ONE_HALF, TWO), - ] - - def test_v_min3_f32_execution(self) -> None: - for s0, s1, s2 in self.TEST_TRIPLES: - expected = ref_min3_f32(s0, s1, s2) - with self.subTest(s0=hex(s0), s1=hex(s1), s2=hex(s2)): - got = run_f32_3op("v_min3_f32", s0, s1, s2) - self.assertEqual(got, expected) - - def test_v_max3_f32_execution(self) -> None: - for s0, s1, s2 in self.TEST_TRIPLES: - expected = ref_max3_f32(s0, s1, s2) - with self.subTest(s0=hex(s0), s1=hex(s1), s2=hex(s2)): - got = run_f32_3op("v_max3_f32", s0, s1, s2) - self.assertEqual(got, expected) - - def test_v_med3_f32_execution(self) -> None: - for s0, s1, s2 in self.TEST_TRIPLES: - expected = ref_med3_f32(s0, s1, s2) - with self.subTest(s0=hex(s0), s1=hex(s1), s2=hex(s2)): - got = run_f32_3op("v_med3_f32", s0, s1, s2) - self.assertEqual(got, expected) - - def test_signed_zeros_3op_execution(self) -> None: - self.assertEqual(run_f32_3op("v_min3_f32", POS_ZERO, NEG_ZERO, ONE), NEG_ZERO) - self.assertEqual(run_f32_3op("v_max3_f32", POS_ZERO, NEG_ZERO, NEG_ONE), POS_ZERO) - self.assertEqual(run_f32_3op("v_med3_f32", POS_ZERO, NEG_ZERO, ONE), POS_ZERO) - self.assertEqual(run_f32_3op("v_med3_f32", POS_ZERO, NEG_ZERO, NEG_ONE), NEG_ZERO) - - def test_extreme_values_3op_execution(self) -> None: - self.assertEqual(run_f32_3op("v_min3_f32", NEG_INF, FLT_MIN, POS_INF), NEG_INF) - self.assertEqual(run_f32_3op("v_max3_f32", NEG_INF, FLT_MIN, POS_INF), POS_INF) - self.assertEqual(run_f32_3op("v_med3_f32", NEG_INF, FLT_MIN, POS_INF), FLT_MIN) - - -class TestSignedZerosTieBreak(unittest.TestCase): - """Verifies that RDNA2 -0.0 < +0.0 ordering is strictly preserved by translator and interpreter.""" - - def test_min_zero_combinations(self) -> None: - self.assertEqual(run_f32_2op("v_min_f32", POS_ZERO, NEG_ZERO), NEG_ZERO) - self.assertEqual(run_f32_2op("v_min_f32", NEG_ZERO, POS_ZERO), NEG_ZERO) - self.assertEqual(run_f32_2op("v_min_f32", POS_ZERO, POS_ZERO), POS_ZERO) - self.assertEqual(run_f32_2op("v_min_f32", NEG_ZERO, NEG_ZERO), NEG_ZERO) - - def test_max_zero_combinations(self) -> None: - self.assertEqual(run_f32_2op("v_max_f32", POS_ZERO, NEG_ZERO), POS_ZERO) - self.assertEqual(run_f32_2op("v_max_f32", NEG_ZERO, POS_ZERO), POS_ZERO) - self.assertEqual(run_f32_2op("v_max_f32", POS_ZERO, POS_ZERO), POS_ZERO) - self.assertEqual(run_f32_2op("v_max_f32", NEG_ZERO, NEG_ZERO), NEG_ZERO) - - -class TestVALUModifiers2Op(unittest.TestCase): - """Verifies VOP3 input modifiers (neg, abs) and output clamp for 2-op instructions.""" - - def test_neg_modifier(self) -> None: - got = run_f32_2op("v_min_f32", ONE, HALF, e64=True, neg0=True) - self.assertEqual(got, NEG_ONE) - got = run_f32_2op("v_max_f32", ONE, HALF, e64=True, neg0=True) - self.assertEqual(got, HALF) - - def test_abs_modifier(self) -> None: - got = run_f32_2op("v_min_f32", NEG_TWO, ONE_HALF, e64=True, abs0=True) - self.assertEqual(got, ONE_HALF) - got = run_f32_2op("v_max_f32", NEG_TWO, f32_to_bits(-3.0), e64=True, abs0=True, abs1=True) - self.assertEqual(got, THREE) - - def test_neg_abs_combination(self) -> None: - got_min = run_f32_2op("v_min_f32", TWO, ONE, e64=True, neg0=True, abs0=True) - self.assertEqual(got_min, NEG_TWO) - got_max = run_f32_2op("v_max_f32", NEG_TWO, ONE, e64=True, neg0=True, abs0=True) - self.assertEqual(got_max, ONE) - - def test_clamp_modifier(self) -> None: - got = run_f32_2op("v_max_f32", TWO, THREE, e64=True, clamp=True) - self.assertEqual(got, ONE) - got = run_f32_2op("v_min_f32", NEG_ONE, NEG_TWO, e64=True, clamp=True) - self.assertEqual(got, POS_ZERO) - - -class TestVALUModifiers3Op(unittest.TestCase): - """Verifies VOP3 input modifiers (neg, abs) and output clamp for 3-op instructions.""" - - def test_min3_modifiers(self) -> None: - got = run_f32_3op("v_min3_f32", TWO, THREE, FOUR, neg0=True, abs0=True) - self.assertEqual(got, NEG_TWO) - - def test_max3_modifiers(self) -> None: - got = run_f32_3op("v_max3_f32", NEG_TWO, f32_to_bits(-3.0), f32_to_bits(-4.0), abs2=True) - self.assertEqual(got, FOUR) - - def test_med3_modifiers(self) -> None: - got = run_f32_3op("v_med3_f32", NEG_ONE, NEG_TWO, THREE, abs0=True) - self.assertEqual(got, ONE) - - def test_clamp_modifier_3op(self) -> None: - got = run_f32_3op("v_max3_f32", TWO, THREE, FOUR, clamp=True) - self.assertEqual(got, ONE) - got = run_f32_3op("v_min3_f32", NEG_ONE, NEG_TWO, f32_to_bits(-3.0), clamp=True) - self.assertEqual(got, POS_ZERO) - - -class TestNaNPropagation(unittest.TestCase): - """Deep verification of NaN propagation, payloads, and NaN suppression across 2-op and 3-op.""" - - def test_nan_vs_finite_payload_preserved(self) -> None: - # Check diverse finite floats against NaNs with different signs and mantissas - finite_samples = [0x3E200000, 0x40490FDB, 0xC0000000, 0x00800000, 0x7F7FFFFF] - nan_samples = [QNAN, NEG_QNAN, QNAN_PAYLOAD, QNAN_PAYLOAD_B, SNAN] - - for fin in finite_samples: - for nan in nan_samples: - with self.subTest(fin=hex(fin), nan=hex(nan)): - # 2-operand - self.assertEqual(run_f32_2op("v_min_f32", nan, fin), fin) - self.assertEqual(run_f32_2op("v_min_f32", fin, nan), fin) - self.assertEqual(run_f32_2op("v_max_f32", nan, fin), fin) - self.assertEqual(run_f32_2op("v_max_f32", fin, nan), fin) - - def test_both_nan_returns_quiet_nan(self) -> None: - got_min = run_f32_2op("v_min_f32", QNAN_PAYLOAD, QNAN_PAYLOAD_B) - self.assertTrue(is_nan_bits(got_min)) - got_max = run_f32_2op("v_max_f32", QNAN_PAYLOAD, QNAN_PAYLOAD_B) - self.assertTrue(is_nan_bits(got_max)) - - def test_3way_nan_combinations(self) -> None: - # 1 NaN in 3-way: remaining 2 operands are evaluated - self.assertEqual(run_f32_3op("v_min3_f32", QNAN, ONE, TWO), ONE) - self.assertEqual(run_f32_3op("v_min3_f32", ONE, QNAN, TWO), ONE) - self.assertEqual(run_f32_3op("v_min3_f32", ONE, TWO, QNAN), ONE) - self.assertEqual(run_f32_3op("v_max3_f32", QNAN, ONE, TWO), TWO) - self.assertEqual(run_f32_3op("v_max3_f32", ONE, QNAN, TWO), TWO) - self.assertEqual(run_f32_3op("v_max3_f32", ONE, TWO, QNAN), TWO) - self.assertEqual(run_f32_3op("v_med3_f32", QNAN, ONE, TWO), ONE) # med3 with NaN falls back to min3 - self.assertEqual(run_f32_3op("v_med3_f32", ONE, QNAN, TWO), ONE) - - # 2 NaNs in 3-way: the single non-NaN operand is returned - self.assertEqual(run_f32_3op("v_min3_f32", QNAN, QNAN_PAYLOAD, THREE), THREE) - self.assertEqual(run_f32_3op("v_max3_f32", QNAN, THREE, QNAN_PAYLOAD), THREE) - - # 3 NaNs in 3-way: result is a NaN - self.assertTrue(is_nan_bits(run_f32_3op("v_min3_f32", QNAN, QNAN_PAYLOAD, NEG_QNAN))) - self.assertTrue(is_nan_bits(run_f32_3op("v_max3_f32", QNAN, QNAN_PAYLOAD, NEG_QNAN))) - - def test_nan_with_modifiers(self) -> None: - # Negation or absolute value on NaN keeps NaN property, non-NaN operand still wins - got_neg = run_f32_2op("v_min_f32", QNAN, ONE, e64=True, neg0=True) - self.assertEqual(got_neg, ONE) - got_abs = run_f32_2op("v_max_f32", QNAN, TWO, e64=True, abs0=True) - self.assertEqual(got_abs, TWO) - - -class TestSubnormalBehavior(unittest.TestCase): - """Verifies subnormal (denormal) floating point ordering, comparisons, and preservation.""" - - def test_subnormal_vs_signed_zeros(self) -> None: - # Positive subnormal is strictly greater than +0.0 and -0.0 - self.assertEqual(run_f32_2op("v_min_f32", SUBNORM_MIN, POS_ZERO), POS_ZERO) - self.assertEqual(run_f32_2op("v_min_f32", SUBNORM_MIN, NEG_ZERO), NEG_ZERO) - self.assertEqual(run_f32_2op("v_max_f32", SUBNORM_MIN, POS_ZERO), SUBNORM_MIN) - self.assertEqual(run_f32_2op("v_max_f32", SUBNORM_MIN, NEG_ZERO), SUBNORM_MIN) - - # Negative subnormal is strictly less than -0.0 and +0.0 - self.assertEqual(run_f32_2op("v_min_f32", NEG_SUBNORM_MIN, NEG_ZERO), NEG_SUBNORM_MIN) - self.assertEqual(run_f32_2op("v_min_f32", NEG_SUBNORM_MIN, POS_ZERO), NEG_SUBNORM_MIN) - self.assertEqual(run_f32_2op("v_max_f32", NEG_SUBNORM_MIN, NEG_ZERO), NEG_ZERO) - self.assertEqual(run_f32_2op("v_max_f32", NEG_SUBNORM_MIN, POS_ZERO), POS_ZERO) - - def test_subnormal_vs_flt_min(self) -> None: - # Smallest positive normal FLT_MIN (2^-126) > largest subnormal SUBNORM_MAX - self.assertEqual(run_f32_2op("v_min_f32", FLT_MIN, SUBNORM_MAX), SUBNORM_MAX) - self.assertEqual(run_f32_2op("v_max_f32", FLT_MIN, SUBNORM_MAX), FLT_MIN) - self.assertEqual(run_f32_2op("v_min_f32", NEG_FLT_MIN, NEG_SUBNORM_MAX), NEG_FLT_MIN) - self.assertEqual(run_f32_2op("v_max_f32", NEG_FLT_MIN, NEG_SUBNORM_MAX), NEG_SUBNORM_MAX) - - def test_subnormal_scale_ordering(self) -> None: - chain = [ - NEG_FLT_MIN, - NEG_SUBNORM_MAX, - NEG_SUBNORM_MIN, - NEG_ZERO, - POS_ZERO, - SUBNORM_MIN, - SUBNORM_MAX, - FLT_MIN, - ] - for i in range(len(chain) - 1): - a, b = chain[i], chain[i + 1] - self.assertEqual(ref_min_f32(a, b), a) - self.assertEqual(ref_max_f32(a, b), b) - self.assertEqual(run_f32_2op("v_min_f32", a, b), a) - self.assertEqual(run_f32_2op("v_max_f32", a, b), b) - - -class TestWavefrontSIMDDivergence(unittest.TestCase): - """Executes lockstep multi-lane SIMD wavefronts to verify no cross-lane data corruption.""" - - @staticmethod - def _run_cs_divergent(wave_size: int, op: str) -> dict[int, int]: - fssm = bytearray(0x148) - struct.pack_into("<4I", fssm, 0x138, 0x8088, wave_size, 1, 1) - - # Diverse operands per lane: - # lane % 4 == 0: (POS_ZERO, NEG_ZERO) - # lane % 4 == 1: (QNAN, 1.0 + lane) - # lane % 4 == 2: (NEG_INF, 2.0 + lane) - # lane % 4 == 3: (SUBNORM_MIN, FLT_MIN) - lines = [ - "v_and_b32 v5, 3, v0", # lane % 4 - # Case 0: - "v_mov_b32 v1, 0x00000000", - "v_mov_b32 v2, 0x80000000", - # Case 1: - "v_cmp_eq_u32_e32 vcc_lo, 1, v5", - "v_cndmask_b32_e32 v1, v1, 0x7FC00000, vcc_lo", - "v_cvt_f32_u32 v6, v0", - "v_add_f32_e32 v6, 0x3F800000, v6", # 1.0 + lane - "v_cndmask_b32_e32 v2, v2, v6, vcc_lo", - # Case 2: - "v_cmp_eq_u32_e32 vcc_lo, 2, v5", - "v_cndmask_b32_e32 v1, v1, 0xFF800000, vcc_lo", - "v_add_f32_e32 v6, 0x40000000, v6", # 2.0 + lane - "v_cndmask_b32_e32 v2, v2, v6, vcc_lo", - # Case 3: - "v_cmp_eq_u32_e32 vcc_lo, 3, v5", - "v_cndmask_b32_e32 v1, v1, 0x00000001, vcc_lo", - "v_cndmask_b32_e32 v2, v2, 0x00800000, vcc_lo", - # ALU operation - f"{op} v3, v1, v2", - "v_lshlrev_b32 v4, 2, v0", - "buffer_store_dword v3, v4, s[0:3], 0 offen", - "s_endpgm", - ] - with tempfile.TemporaryDirectory() as tmp: - os.mkdir(os.path.join(tmp, "disasm")) - src = os.path.join(tmp, "disasm", "cs_wave_divergent.s") - with open(src, "w", encoding="utf-8") as f: - f.write("; cs_wave_divergent\n" + "\n".join(f"\t{ln}" for ln in lines) + "\n") - with open(os.path.join(tmp, "cs_wave_divergent.dxbc"), "wb") as f: - f.write(STUB_DXBC) - os.mkdir(os.path.join(tmp, "fssm")) - with open(os.path.join(tmp, "fssm", "cs_wave_divergent.fssm"), "wb") as f: - f.write(fssm) - with warnings.catch_warnings(): - warnings.simplefilter("ignore", ResourceWarning) - spv = rdna2spirv.translate(src) - - mem: dict[int, int] = {} - push = [0, 0, 0x1000, 0x31016FAC] + [0] * 28 - si.run_workgroup( - spv, - wave_size, - 32, - inputs_for=lambda i: {"%wg_id": (0, 0, 0), "%local_id": (i, 0, 0), "%sg_lane": i}, - push_constants=push, - memory=mem, - ) - return mem - - def test_wave32_divergence_min(self) -> None: - mem = self._run_cs_divergent(32, "v_min_f32") - for i in range(32): - mod = i % 4 - if mod == 0: - want = ref_min_f32(POS_ZERO, NEG_ZERO) # -0.0 - elif mod == 1: - want = f32_to_bits(1.0 + float(i)) - elif mod == 2: - want = NEG_INF - else: - want = SUBNORM_MIN - self.assertEqual(mem.get(4 * i), want, f"Lane {i} mismatch") - - def test_wave64_divergence_max(self) -> None: - mem = self._run_cs_divergent(64, "v_max_f32") - for i in range(64): - mod = i % 4 - if mod == 0: - want = ref_max_f32(POS_ZERO, NEG_ZERO) # +0.0 - elif mod == 1: - want = f32_to_bits(1.0 + float(i)) - elif mod == 2: - want = f32_to_bits(3.0 + float(i)) - else: - want = FLT_MIN - self.assertEqual(mem.get(4 * i), want, f"Lane {i} mismatch") - - -class TestNegativeControls(unittest.TestCase): - """Negative controls ensuring non-compliant floating point behavior is rejected.""" - - def test_python_default_min_zero_divergence(self) -> None: - # Standard Python min(0.0, -0.0) yields +0.0 because 0.0 <= -0.0 evaluates to True. - # This confirms that naive Python float comparisons violate AMD RDNA2 semantics. - naive_python_min = min(0.0, -0.0) - self.assertEqual(f32_to_bits(naive_python_min), POS_ZERO) - # The reference oracle correctly yields -0.0 (0x80000000). - self.assertEqual(ref_min_f32(POS_ZERO, NEG_ZERO), NEG_ZERO) - - def test_python_default_nan_divergence(self) -> None: - # Standard Python min(nan, 2.0) propagates NaN. - # IEEE 754-2008 and RDNA2 minNum instead suppress NaN in favor of the number. - naive_python_min = min(float("nan"), 2.0) - self.assertTrue(math.isnan(naive_python_min)) - # The reference oracle correctly returns 2.0. - self.assertEqual(ref_min_f32(QNAN, TWO), TWO) - - def test_clamp_on_all_nan_raises_unsupported(self) -> None: - # Clamping an all-NaN result is undefined in GLSL.std.450 / SPIR-V and raises UnsupportedConstruct. - with self.assertRaises(si.UnsupportedConstruct): - run_f32_2op("v_min_f32", QNAN, QNAN, e64=True, clamp=True) - - def test_med3_third_operand_nan_is_min3(self) -> None: - # Since #2029 a NaN operand gives min3 of the operands (measured on gfx1030), not an eager FClamp on NaN. - self.assertEqual(run_f32_3op("v_med3_f32", ONE, TWO, QNAN), ONE) - - def test_bit_exactness_rejects_sign_mismatch(self) -> None: - # Negative control: verify that +0.0 and -0.0 are distinct 32-bit words. - self.assertNotEqual(POS_ZERO, NEG_ZERO) - self.assertEqual(POS_ZERO & SIGN_MASK, 0) - self.assertEqual(NEG_ZERO & SIGN_MASK, SIGN_MASK) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_alu_floor_ceil_fract_hw.py b/tests/semantic/test_alu_floor_ceil_fract_hw.py deleted file mode 100644 index 52e3a7ee5..000000000 --- a/tests/semantic/test_alu_floor_ceil_fract_hw.py +++ /dev/null @@ -1,188 +0,0 @@ -"""v_floor_f32, v_ceil_f32, v_fract_f32 and v_cvt_flr/rpi_i32_f32 against words an RDNA2 GPU returned for the same instruction. - -Every row ran natively on an AMD Radeon RDNA2 iGPU (gfx1036, Ryzen 9 9950X3D, Windows AMD driver 32.0.21045.16010) -through tools/hw_oracle with AMD clang 23 (rocm-sdk-core 10.0.0), in the MODE inferred for the game (IEEE 0, -DX10_CLAMP 1, f32 denormals flushed, f16 denormals kept): v1 holds the operand, v4 starts as 0xDEADBEEF and the word -after the instruction is the expected one. No model in this test. - -What the rows pin: a denormal operand is a zero of its sign (floor(-1e-45) = -0, ceil(+1e-45) = +0, fract of either -0), which a translation that uses the denormal as it is gets wrong by a whole 1.0; a NaN operand passes through -unchanged, a signalling one too (IEEE 0); fract(+-inf) is the negative quiet NaN 0xffc00000; and the ordinary values -around them (fract of a tiny negative normal is 0x3f7fffff, docs/design.md). v_cvt_flr_i32_f32 of a -negative denormal is 0 for the same reason (floor of the kept denormal gives -1); v_cvt_rpi_i32_f32 rows -are the control. -""" -import os -import struct -import sys -import tempfile -import unittest -import warnings - -HERE = os.path.dirname(os.path.abspath(__file__)) -ROOT = os.path.dirname(os.path.dirname(HERE)) -sys.dont_write_bytecode = True -sys.path.insert(0, os.environ.get("LEONIDA_TOOLS_DIR") or os.path.join(ROOT, "tools")) -sys.path.insert(0, HERE) - -import rdna2spirv # noqa: E402 -import spirv_mini_interp as si # noqa: E402 - -STUB_DXBC = b"DXBC" + bytes(24) + struct.pack(" float: - """Convert a 16-bit unsigned integer bit pattern to a Python float via IEEE 754 half precision.""" - return struct.unpack(" int: - """Convert a Python float to a 16-bit IEEE 754 half-precision bit pattern with round-to-nearest-even.""" - try: - return struct.unpack(" 0 else 0xFC00 - - -def f32_to_u32(x: float) -> int: - """Convert a float to 32-bit IEEE 754 single-precision integer bits.""" - return struct.unpack(" float: - """Convert 32-bit integer bits to float via IEEE 754 single precision.""" - return struct.unpack(" int: - """Pack two 16-bit half words into one 32-bit dword (hi in [31:16], lo in [15:0]).""" - return ((hi & 0xFFFF) << 16) | (lo & 0xFFFF) - - -def unpack2x16(dword: int) -> tuple[int, int]: - """Unpack a 32-bit dword into (lo, hi) 16-bit half words.""" - return dword & 0xFFFF, (dword >> 16) & 0xFFFF - - -def ref_pk_fma_f16( - v0: int, - v1: int, - v2: int, - op_sel: tuple[int, int, int] = (0, 0, 0), - op_sel_hi: tuple[int, int, int] = (1, 1, 1), - neg_lo: tuple[int, int, int] = (0, 0, 0), - neg_hi: tuple[int, int, int] = (0, 0, 0), - clamp: bool = False, -) -> int: - """Reference calculation for RDNA2 v_pk_fma_f16. - - Result lo: source i takes its half from op_sel[i] (0=lo, 1=hi), negated by neg_lo[i]. - Result hi: source i takes its half from op_sel_hi[i] (0=lo, 1=hi), negated by neg_hi[i]. - """ - def sel_half(word: int, hi: int, neg: int) -> float: - h = (word >> 16) if hi else (word & 0xFFFF) - val = h2f(h) - return -val if neg else val - - s0_lo = sel_half(v0, op_sel[0], neg_lo[0]) - s1_lo = sel_half(v1, op_sel[1], neg_lo[1]) - s2_lo = sel_half(v2, op_sel[2], neg_lo[2]) - res_lo_f = s0_lo * s1_lo + s2_lo - if clamp: - res_lo_f = max(0.0, min(1.0, res_lo_f)) - res_lo = f2h(res_lo_f) - - s0_hi = sel_half(v0, op_sel_hi[0], neg_hi[0]) - s1_hi = sel_half(v1, op_sel_hi[1], neg_hi[1]) - s2_hi = sel_half(v2, op_sel_hi[2], neg_hi[2]) - res_hi_f = s0_hi * s1_hi + s2_hi - if clamp: - res_hi_f = max(0.0, min(1.0, res_hi_f)) - res_hi = f2h(res_hi_f) - - return pack2x16(res_lo, res_hi) - - -def ref_fma_mix_f32( - v0: int, - v1: int, - v2: int, - op_sel: tuple[int, int, int] = (0, 0, 0), - op_sel_hi: tuple[int, int, int] = (0, 0, 0), - neg: tuple[int, int, int] = (0, 0, 0), - abs_mask: tuple[int, int, int] = (0, 0, 0), - clamp: bool = False, -) -> int: - """Reference calculation for RDNA2 v_fma_mix_f32. - - Each source is f32 (op_sel_hi[i]==0) or f16 (op_sel_hi[i]==1) unpacked from - low (op_sel[i]==0) or high (op_sel[i]==1) half. - """ - def get_src(word: int, is_f16: int, sel: int, is_neg: int, is_abs: int) -> float: - if is_f16: - h = (word >> 16) if sel else (word & 0xFFFF) - val = h2f(h) - else: - val = u32_to_f32(word) - if is_abs: - val = abs(val) - if is_neg: - val = -val - return val - - s0 = get_src(v0, op_sel_hi[0], op_sel[0], neg[0], abs_mask[0]) - s1 = get_src(v1, op_sel_hi[1], op_sel[1], neg[1], abs_mask[1]) - s2 = get_src(v2, op_sel_hi[2], op_sel[2], neg[2], abs_mask[2]) - - res = s0 * s1 + s2 - if clamp: - res = max(0.0, min(1.0, res)) - return f32_to_u32(res) - - -_TMP_DIR: tempfile.TemporaryDirectory | None = None -_SRC_PATH: str | None = None - - -def setUpModule() -> None: - global _TMP_DIR, _SRC_PATH - _TMP_DIR = tempfile.TemporaryDirectory() - disasm_dir = os.path.join(_TMP_DIR.name, "disasm") - os.mkdir(disasm_dir) - _SRC_PATH = os.path.join(disasm_dir, "ps_fma_f16.s") - with open(os.path.join(_TMP_DIR.name, "ps_fma_f16.dxbc"), "wb") as f: - f.write(STUB_DXBC) - - -def tearDownModule() -> None: - global _TMP_DIR - if _TMP_DIR is not None: - _TMP_DIR.cleanup() - _TMP_DIR = None - - -def run_assembly(lines: list[str]) -> int: - """Translate straight-line assembly instructions to SPIR-V and return the first mrt0 word.""" - if _TMP_DIR is None or _SRC_PATH is None: - setUpModule() - asm = "; test_alu_fma_f16\n" + "".join(f"\t{ln}\n" for ln in lines) + "\texp mrt0 v0, v0, v0, v0 done vm\n\ts_endpgm\n" - with open(_SRC_PATH, "w", encoding="utf-8") as f: - f.write(asm) - with warnings.catch_warnings(): - warnings.simplefilter("ignore", ResourceWarning) - spv = rdna2spirv.translate(_SRC_PATH) - out = si.run_fragment(spv) - return out["%out_mrt0"][0] - - -def run_pk_fma( - v0: int, - v1: int, - v2: int, - op_sel: tuple[int, int, int] | None = None, - op_sel_hi: tuple[int, int, int] | None = None, - neg_lo: tuple[int, int, int] | None = None, - neg_hi: tuple[int, int, int] | None = None, -) -> int: - """Seed v1..v3 with values, execute v_pk_fma_f16 into v0, return v0.""" - mods: list[str] = [] - if op_sel is not None: - mods.append(f"op_sel:[{op_sel[0]},{op_sel[1]},{op_sel[2]}]") - if op_sel_hi is not None: - mods.append(f"op_sel_hi:[{op_sel_hi[0]},{op_sel_hi[1]},{op_sel_hi[2]}]") - if neg_lo is not None: - mods.append(f"neg_lo:[{neg_lo[0]},{neg_lo[1]},{neg_lo[2]}]") - if neg_hi is not None: - mods.append(f"neg_hi:[{neg_hi[0]},{neg_hi[1]},{neg_hi[2]}]") - - mod_str = (" " + " ".join(mods)) if mods else "" - lines = [ - f"v_mov_b32 v1, {v0:#010x}", - f"v_mov_b32 v2, {v1:#010x}", - f"v_mov_b32 v3, {v2:#010x}", - f"v_pk_fma_f16 v0, v1, v2, v3{mod_str}", - ] - return run_assembly(lines) - - -def run_fma_mix( - v0: int, - v1: int, - v2: int, - op_sel: tuple[int, int, int] | None = None, - op_sel_hi: tuple[int, int, int] | None = None, - neg: tuple[int, int, int] | None = None, - abs_mask: tuple[int, int, int] | None = None, - clamp: bool = False, -) -> int: - """Seed v1..v3 with values, execute v_fma_mix_f32 into v0, return v0.""" - def format_operand(reg_name: str, idx: int) -> str: - s = reg_name - if abs_mask and abs_mask[idx]: - s = f"|{s}|" - if neg and neg[idx]: - s = f"-{s}" - return s - - mods: list[str] = [] - if op_sel is not None: - mods.append(f"op_sel:[{op_sel[0]},{op_sel[1]},{op_sel[2]}]") - if op_sel_hi is not None: - mods.append(f"op_sel_hi:[{op_sel_hi[0]},{op_sel_hi[1]},{op_sel_hi[2]}]") - if clamp: - mods.append("clamp") - - mod_str = (" " + " ".join(mods)) if mods else "" - s0_str = format_operand("v1", 0) - s1_str = format_operand("v2", 1) - s2_str = format_operand("v3", 2) - - lines = [ - f"v_mov_b32 v1, {v0:#010x}", - f"v_mov_b32 v2, {v1:#010x}", - f"v_mov_b32 v3, {v2:#010x}", - f"v_fma_mix_f32 v0, {s0_str}, {s1_str}, {s2_str}{mod_str}", - ] - return run_assembly(lines) - - -class OracleConsistencyTests(unittest.TestCase): - """Verify that reference calculation functions agree with independently hand-computed values.""" - - def test_pk_fma_reference_against_hand_values(self): - # v0: lo=1.0 (0x3c00), hi=2.0 (0x4000) - # v1: lo=3.0 (0x4200), hi=4.0 (0x4400) - # v2: lo=0.5 (0x3800), hi=1.0 (0x3c00) - # lo: 1.0 * 3.0 + 0.5 = 3.5 -> 0x4300 - # hi: 2.0 * 4.0 + 1.0 = 9.0 -> 0x4880 - # result: 0x48804300 - v0 = pack2x16(f2h(1.0), f2h(2.0)) - v1 = pack2x16(f2h(3.0), f2h(4.0)) - v2 = pack2x16(f2h(0.5), f2h(1.0)) - got = ref_pk_fma_f16(v0, v1, v2) - self.assertEqual(got, 0x48804300) - - def test_fma_mix_reference_against_hand_values(self): - # v0: lo=1.5 (0x3e00), hi=2.5 (0x4100) - # v1: lo=2.0 (0x4000), hi=0.5 (0x3800) - # v2: single-precision 10.0f (0x41200000) - # op_sel_hi=[1, 1, 0] (f16, f16, f32), op_sel=[0, 0, 0] (lo, lo, lo) - # 1.5 * 2.0 + 10.0 = 13.0f -> 0x41500000 - v0 = pack2x16(f2h(1.5), f2h(2.5)) - v1 = pack2x16(f2h(2.0), f2h(0.5)) - v2 = f32_to_u32(10.0) - got = ref_fma_mix_f32(v0, v1, v2, op_sel=(0, 0, 0), op_sel_hi=(1, 1, 0)) - self.assertEqual(got, 0x41500000) - - def test_subnormal_constants_and_properties(self): - # 0x0001: 2^-24 - val_min = h2f(F16_MIN_SUBNORMAL) - self.assertAlmostEqual(val_min, 2.0**-24, delta=1e-15) - self.assertEqual(f2h(val_min), F16_MIN_SUBNORMAL) - - # 0x03FF: (1023/1024) * 2^-14 - val_max = h2f(F16_MAX_SUBNORMAL) - self.assertAlmostEqual(val_max, (1023.0 / 1024.0) * (2.0**-14), delta=1e-15) - self.assertEqual(f2h(val_max), F16_MAX_SUBNORMAL) - - # 0x0400: smallest normal 2^-14 - val_norm = h2f(F16_MIN_NORMAL) - self.assertAlmostEqual(val_norm, 2.0**-14, delta=1e-15) - self.assertEqual(f2h(val_norm), F16_MIN_NORMAL) - - -class SpirvInterpFmaDirectTests(unittest.TestCase): - """Direct tests for the mini-interpreter's GLSL.std.450 Fma, PackHalf2x16, and UnpackHalf2x16.""" - - HEADER = """\ -OpCapability Shader -%glsl = OpExtInstImport "GLSL.std.450" -OpMemoryModel Logical GLSL450 -OpEntryPoint Fragment %main "main" %out -%void = OpTypeVoid -%fn = OpTypeFunction %void -%uint = OpTypeInt 32 0 -%float = OpTypeFloat 32 -%v2float = OpTypeVector %float 2 -%_ptr_Output_uint = OpTypePointer Output %uint -%out = OpVariable %_ptr_Output_uint Output -%f0 = OpConstant %float 0 -%f1 = OpConstant %float 1 -%f2 = OpConstant %float 2 -%f3 = OpConstant %float 3 -%f4 = OpConstant %float 4 -%f5 = OpConstant %float 5 -%fn2 = OpConstant %float -2 -%fn3 = OpConstant %float -3 -%main = OpFunction %void None %fn -%entry = OpLabel -""" - FOOTER = "OpReturn\nOpFunctionEnd\n" - - def run_word(self, body: str) -> int: - text = self.HEADER + body + "OpStore %out %res\n" + self.FOOTER - return si.run_fragment(text)["%out"][0] - - def test_vector_fma_arithmetic(self): - # v0 = (2.0, 3.0), v1 = (4.0, 5.0), v2 = (1.0, 2.0) - # res = v0 * v1 + v2 = (2*4+1, 3*5+2) = (9.0, 17.0) - # PackHalf2x16: 9.0 (0x4880), 17.0 (0x4c40) -> 0x4C404880 - body = """\ -%v0 = OpCompositeConstruct %v2float %f2 %f3 -%v1 = OpCompositeConstruct %v2float %f4 %f5 -%v2 = OpCompositeConstruct %v2float %f1 %f2 -%r = OpExtInst %v2float %glsl Fma %v0 %v1 %v2 -%res = OpExtInst %uint %glsl PackHalf2x16 %r -""" - self.assertEqual(self.run_word(body), 0x4C404880) - - def test_vector_fma_negative_and_zero(self): - # v0 = (-2.0, 0.0), v1 = (3.0, 5.0), v2 = (1.0, 4.0) - # res = (-2*3+1, 0*5+4) = (-5.0, 4.0) - # f16(-5.0) = 0xc500, f16(4.0) = 0x4400 -> 0x4400c500 - body = """\ -%v0 = OpCompositeConstruct %v2float %fn2 %f0 -%v1 = OpCompositeConstruct %v2float %f3 %f5 -%v2 = OpCompositeConstruct %v2float %f1 %f4 -%r = OpExtInst %v2float %glsl Fma %v0 %v1 %v2 -%res = OpExtInst %uint %glsl PackHalf2x16 %r -""" - self.assertEqual(self.run_word(body), 0x4400C500) - - def test_scalar_fma_f32_precision(self): - # 2.0f * -3.0f + 1.0f = -5.0f (0xC0A00000) - body = """\ -%r = OpExtInst %float %glsl Fma %f2 %fn3 %f1 -%res = OpBitcast %uint %r -""" - self.assertEqual(self.run_word(body), 0xC0A00000) - - -class PackedFmaF16Tests(unittest.TestCase): - """Tests for RDNA2 v_pk_fma_f16 instruction translation and interpretation.""" - - def test_pk_fma_basic_lanes(self): - # lo: 1.0 * 2.0 + 3.0 = 5.0 (0x4500) - # hi: 0.5 * 4.0 + 1.5 = 3.5 (0x4300) - v0 = pack2x16(f2h(1.0), f2h(0.5)) - v1 = pack2x16(f2h(2.0), f2h(4.0)) - v2 = pack2x16(f2h(3.0), f2h(1.5)) - expected = ref_pk_fma_f16(v0, v1, v2) - got = run_pk_fma(v0, v1, v2) - self.assertEqual(got, expected) - - def test_pk_fma_zeroes_and_identity(self): - # lo: 0.0 * 10.0 + 7.5 = 7.5 - # hi: 3.5 * 1.0 + 0.0 = 3.5 - v0 = pack2x16(f2h(0.0), f2h(3.5)) - v1 = pack2x16(f2h(10.0), f2h(1.0)) - v2 = pack2x16(f2h(7.5), f2h(0.0)) - expected = ref_pk_fma_f16(v0, v1, v2) - got = run_pk_fma(v0, v1, v2) - self.assertEqual(got, expected) - - def test_pk_fma_negative_numbers(self): - # lo: -1.5 * 2.0 + 4.0 = 1.0 - # hi: -2.0 * -3.0 + -1.0 = 5.0 - v0 = pack2x16(f2h(-1.5), f2h(-2.0)) - v1 = pack2x16(f2h(2.0), f2h(-3.0)) - v2 = pack2x16(f2h(4.0), f2h(-1.0)) - expected = ref_pk_fma_f16(v0, v1, v2) - got = run_pk_fma(v0, v1, v2) - self.assertEqual(got, expected) - - def test_pk_fma_fractional_precision(self): - # lo: 0.25 * 0.5 + 0.125 = 0.25 - # hi: 1.5 * 1.5 + 0.25 = 2.5 - v0 = pack2x16(f2h(0.25), f2h(1.5)) - v1 = pack2x16(f2h(0.5), f2h(1.5)) - v2 = pack2x16(f2h(0.125), f2h(0.25)) - expected = ref_pk_fma_f16(v0, v1, v2) - got = run_pk_fma(v0, v1, v2) - self.assertEqual(got, expected) - - def test_pk_fma_op_sel_permutations(self): - v0 = pack2x16(f2h(1.0), f2h(10.0)) - v1 = pack2x16(f2h(2.0), f2h(20.0)) - v2 = pack2x16(f2h(3.0), f2h(30.0)) - - # 10.0 * 2.0 + 3.0 = 23.0 - self.assertEqual(run_pk_fma(v0, v1, v2, op_sel=(1, 0, 0), op_sel_hi=(1, 1, 1)), - ref_pk_fma_f16(v0, v1, v2, op_sel=(1, 0, 0), op_sel_hi=(1, 1, 1))) - # 1.0 * 20.0 + 3.0 = 23.0 - self.assertEqual(run_pk_fma(v0, v1, v2, op_sel=(0, 1, 0), op_sel_hi=(1, 1, 1)), - ref_pk_fma_f16(v0, v1, v2, op_sel=(0, 1, 0), op_sel_hi=(1, 1, 1))) - # 1.0 * 2.0 + 30.0 = 32.0 - self.assertEqual(run_pk_fma(v0, v1, v2, op_sel=(0, 0, 1), op_sel_hi=(1, 1, 1)), - ref_pk_fma_f16(v0, v1, v2, op_sel=(0, 0, 1), op_sel_hi=(1, 1, 1))) - # 10.0 * 20.0 + 30.0 = 230.0 - self.assertEqual(run_pk_fma(v0, v1, v2, op_sel=(1, 1, 1), op_sel_hi=(1, 1, 1)), - ref_pk_fma_f16(v0, v1, v2, op_sel=(1, 1, 1), op_sel_hi=(1, 1, 1))) - - def test_pk_fma_op_sel_hi_permutations(self): - v0 = pack2x16(f2h(2.0), f2h(5.0)) - v1 = pack2x16(f2h(3.0), f2h(4.0)) - v2 = pack2x16(f2h(1.0), f2h(6.0)) - - # 2.0 * 4.0 + 6.0 = 14.0 - self.assertEqual(run_pk_fma(v0, v1, v2, op_sel=(0, 0, 0), op_sel_hi=(0, 1, 1)), - ref_pk_fma_f16(v0, v1, v2, op_sel=(0, 0, 0), op_sel_hi=(0, 1, 1))) - # 5.0 * 3.0 + 6.0 = 21.0 - self.assertEqual(run_pk_fma(v0, v1, v2, op_sel=(0, 0, 0), op_sel_hi=(1, 0, 1)), - ref_pk_fma_f16(v0, v1, v2, op_sel=(0, 0, 0), op_sel_hi=(1, 0, 1))) - # 5.0 * 4.0 + 1.0 = 21.0 - self.assertEqual(run_pk_fma(v0, v1, v2, op_sel=(0, 0, 0), op_sel_hi=(1, 1, 0)), - ref_pk_fma_f16(v0, v1, v2, op_sel=(0, 0, 0), op_sel_hi=(1, 1, 0))) - # 2.0 * 3.0 + 1.0 = 7.0 - self.assertEqual(run_pk_fma(v0, v1, v2, op_sel=(0, 0, 0), op_sel_hi=(0, 0, 0)), - ref_pk_fma_f16(v0, v1, v2, op_sel=(0, 0, 0), op_sel_hi=(0, 0, 0))) - - def test_pk_fma_neg_lo_and_neg_hi(self): - # v0: lo=1.0, hi=2.0 - # v1: lo=2.0, hi=3.0 - # v2: lo=3.0, hi=4.0 - # neg_lo:[1, 0, 0]: lo = -(1.0) * 2.0 + 3.0 = 1.0 - # neg_hi:[0, 1, 0]: hi = 2.0 * -(3.0) + 4.0 = -2.0 - v0 = pack2x16(f2h(1.0), f2h(2.0)) - v1 = pack2x16(f2h(2.0), f2h(3.0)) - v2 = pack2x16(f2h(3.0), f2h(4.0)) - expected = ref_pk_fma_f16(v0, v1, v2, neg_lo=(1, 0, 0), neg_hi=(0, 1, 0)) - got = run_pk_fma(v0, v1, v2, neg_lo=(1, 0, 0), neg_hi=(0, 1, 0)) - self.assertEqual(got, expected) - - def test_pk_fma_cross_lane_independent(self): - v0 = pack2x16(f2h(1.5), f2h(3.0)) - v1 = pack2x16(f2h(2.0), f2h(4.0)) - v2 = pack2x16(f2h(0.5), f2h(2.5)) - expected = ref_pk_fma_f16(v0, v1, v2, op_sel=(1, 0, 1), op_sel_hi=(0, 1, 0)) - got = run_pk_fma(v0, v1, v2, op_sel=(1, 0, 1), op_sel_hi=(0, 1, 0)) - self.assertEqual(got, expected) - - -class PackedFmaF16SubnormalTests(unittest.TestCase): - """Audits packed 16-bit float FMA arithmetic with IEEE 754 half-precision subnormals.""" - - def test_subnormal_identity_and_scaling(self): - # lo: 0x0001 (2^-24) * 1.0 + 0.0 = 0x0001 - # hi: 0x0001 (2^-24) * 2.0 + 0.0 = 0x0002 - v0 = pack2x16(F16_MIN_SUBNORMAL, F16_MIN_SUBNORMAL) - v1 = pack2x16(F16_ONE, F16_TWO) - v2 = pack2x16(F16_ZERO, F16_ZERO) - expected = ref_pk_fma_f16(v0, v1, v2) - got = run_pk_fma(v0, v1, v2) - self.assertEqual(got, expected) - lo, hi = unpack2x16(got) - self.assertEqual(lo, F16_MIN_SUBNORMAL) - self.assertEqual(hi, 0x0002) - - def test_subnormal_addition_and_accumulation(self): - # lo: 0x0001 * 1.0 + 0x0001 = 0x0002 - # hi: 0x0002 * 1.0 + 0x0003 = 0x0005 - v0 = pack2x16(0x0001, 0x0002) - v1 = pack2x16(F16_ONE, F16_ONE) - v2 = pack2x16(0x0001, 0x0003) - expected = ref_pk_fma_f16(v0, v1, v2) - got = run_pk_fma(v0, v1, v2) - self.assertEqual(got, expected) - self.assertEqual(got, pack2x16(0x0002, 0x0005)) - - def test_subnormal_largest_and_negative(self): - # lo: 0x03FF (largest subnormal) * 1.0 + 0.0 = 0x03FF - # hi: 0x8001 (-2^-24) * 1.0 + 0.0 = 0x8001 - v0 = pack2x16(F16_MAX_SUBNORMAL, F16_NEG_MIN_SUBNORMAL) - v1 = pack2x16(F16_ONE, F16_ONE) - v2 = pack2x16(F16_ZERO, F16_ZERO) - expected = ref_pk_fma_f16(v0, v1, v2) - got = run_pk_fma(v0, v1, v2) - self.assertEqual(got, expected) - - def test_boundary_crossing_subnormal_to_normal(self): - # Adding 0x0001 (2^-24) to 0x03FF (largest subnormal) crosses the threshold into smallest normal 0x0400 (2^-14). - # lo: 0x03FF * 1.0 + 0x0001 = 0x0400 - # hi: 0x03FF * 1.0 + 0x0002 = 0x0401 - v0 = pack2x16(F16_MAX_SUBNORMAL, F16_MAX_SUBNORMAL) - v1 = pack2x16(F16_ONE, F16_ONE) - v2 = pack2x16(0x0001, 0x0002) - expected = ref_pk_fma_f16(v0, v1, v2) - got = run_pk_fma(v0, v1, v2) - self.assertEqual(got, expected) - lo, hi = unpack2x16(got) - self.assertEqual(lo, F16_MIN_NORMAL) - self.assertEqual(hi, 0x0401) - - def test_boundary_crossing_normal_to_subnormal(self): - # Subtracting 0x0001 from 0x0400 (smallest normal) crosses down into subnormal space 0x03FF. - # lo: 0x0400 * 1.0 - 0x0001 = 0x03FF - # hi: 0x0400 * 1.0 - 0x0002 = 0x03FE - v0 = pack2x16(F16_MIN_NORMAL, F16_MIN_NORMAL) - v1 = pack2x16(F16_ONE, F16_ONE) - v2 = pack2x16(0x0001, 0x0002) - expected = ref_pk_fma_f16(v0, v1, v2, neg_lo=(0, 0, 1), neg_hi=(0, 0, 1)) - got = run_pk_fma(v0, v1, v2, neg_lo=(0, 0, 1), neg_hi=(0, 0, 1)) - self.assertEqual(got, expected) - lo, hi = unpack2x16(got) - self.assertEqual(lo, F16_MAX_SUBNORMAL) - self.assertEqual(hi, 0x03FE) - - def test_gradual_underflow_from_normal_multiplication(self): - # 2^-8 (0x1C00) * 2^-8 (0x1C00) = 2^-16. - # In f16, 2^-16 is subnormal: (2^-16 / 2^-24) = 256 = 0x0100. - # 2^-10 (0x1400) * 2^-10 (0x1400) = 2^-20 -> 16 * 2^-24 = 0x0010. - v0 = pack2x16(0x1C00, 0x1400) - v1 = pack2x16(0x1C00, 0x1400) - v2 = pack2x16(F16_ZERO, F16_ZERO) - expected = ref_pk_fma_f16(v0, v1, v2) - got = run_pk_fma(v0, v1, v2) - self.assertEqual(got, expected) - lo, hi = unpack2x16(got) - self.assertEqual(lo, 0x0100) - self.assertEqual(hi, 0x0010) - - def test_underflow_below_subnormal_to_zero(self): - # 2^-13 (0x0800) * 2^-13 (0x0800) = 2^-26. - # Smallest subnormal is 2^-24; half least significant bit is 2^-25. - # 2^-26 < 2^-25, so IEEE 754 round-to-nearest-even underflows to zero. - v0 = pack2x16(0x0800, 0x0800) - v1 = pack2x16(0x0800, 0x0800) - v2 = pack2x16(F16_ZERO, F16_ZERO) - expected = ref_pk_fma_f16(v0, v1, v2) - got = run_pk_fma(v0, v1, v2) - self.assertEqual(got, expected) - self.assertEqual(got, 0x00000000) - - def test_normals_multiplying_to_min_subnormal(self): - # 2^-12 (0x0C00) * 2^-12 (0x0C00) = 2^-24 (0x0001), exact minimum subnormal. - v0 = pack2x16(0x0C00, 0x0C00) - v1 = pack2x16(0x0C00, 0x0C00) - v2 = pack2x16(F16_ZERO, F16_ZERO) - expected = ref_pk_fma_f16(v0, v1, v2) - got = run_pk_fma(v0, v1, v2) - self.assertEqual(got, expected) - self.assertEqual(got, pack2x16(F16_MIN_SUBNORMAL, F16_MIN_SUBNORMAL)) - - def test_subnormal_cancellation_to_zero(self): - # 0x0005 * 1.0 - 0x0005 = 0.0 - v0 = pack2x16(0x0005, 0x0005) - v1 = pack2x16(F16_ONE, F16_ONE) - v2 = pack2x16(0x0005, 0x0005) - expected = ref_pk_fma_f16(v0, v1, v2, neg_lo=(0, 0, 1), neg_hi=(0, 0, 1)) - got = run_pk_fma(v0, v1, v2, neg_lo=(0, 0, 1), neg_hi=(0, 0, 1)) - self.assertEqual(got, expected) - lo, hi = unpack2x16(got) - self.assertEqual(lo & 0x7FFF, 0) - self.assertEqual(hi & 0x7FFF, 0) - - -class FmaMixF32Tests(unittest.TestCase): - """Tests for RDNA2 v_fma_mix_f32 instruction translation and interpretation.""" - - def test_fma_mix_all_three_f16(self): - # op_sel_hi=[1, 1, 1]: all three sources are f16 - v0 = pack2x16(f2h(1.5), f2h(2.5)) - v1 = pack2x16(f2h(2.0), f2h(4.0)) - v2 = pack2x16(f2h(0.25), f2h(1.0)) - - # All low halves: 1.5 * 2.0 + 0.25 = 3.25f - self.assertEqual(run_fma_mix(v0, v1, v2, op_sel=(0, 0, 0), op_sel_hi=(1, 1, 1)), - ref_fma_mix_f32(v0, v1, v2, op_sel=(0, 0, 0), op_sel_hi=(1, 1, 1))) - # All high halves: 2.5 * 4.0 + 1.0 = 11.0f - self.assertEqual(run_fma_mix(v0, v1, v2, op_sel=(1, 1, 1), op_sel_hi=(1, 1, 1)), - ref_fma_mix_f32(v0, v1, v2, op_sel=(1, 1, 1), op_sel_hi=(1, 1, 1))) - # Mixed halves: s0 hi (2.5), s1 lo (2.0), s2 hi (1.0) -> 2.5 * 2.0 + 1.0 = 6.0f - self.assertEqual(run_fma_mix(v0, v1, v2, op_sel=(1, 0, 1), op_sel_hi=(1, 1, 1)), - ref_fma_mix_f32(v0, v1, v2, op_sel=(1, 0, 1), op_sel_hi=(1, 1, 1))) - - def test_fma_mix_two_f16_one_f32(self): - # [1, 1, 0]: s0(f16), s1(f16), s2(f32) -> 2.5 * 4.0 + 10.5 = 20.5f - v0 = pack2x16(f2h(2.5), f2h(5.0)) - v1 = pack2x16(f2h(4.0), f2h(1.0)) - v2 = f32_to_u32(10.5) - self.assertEqual(run_fma_mix(v0, v1, v2, op_sel=(0, 0, 0), op_sel_hi=(1, 1, 0)), - ref_fma_mix_f32(v0, v1, v2, op_sel=(0, 0, 0), op_sel_hi=(1, 1, 0))) - - # [1, 0, 1]: s0(f16), s1(f32), s2(f16) -> 3.0 * 5.0 + (-2.0) = 13.0f - v0_b = pack2x16(f2h(3.0), f2h(6.0)) - v1_b = f32_to_u32(5.0) - v2_b = pack2x16(f2h(-2.0), f2h(8.0)) - self.assertEqual(run_fma_mix(v0_b, v1_b, v2_b, op_sel=(0, 0, 0), op_sel_hi=(1, 0, 1)), - ref_fma_mix_f32(v0_b, v1_b, v2_b, op_sel=(0, 0, 0), op_sel_hi=(1, 0, 1))) - - # [0, 1, 1]: s0(f32), s1(f16), s2(f16) -> -2.5 * 6.0 + 1.0 = -14.0f - v0_c = f32_to_u32(-2.5) - v1_c = pack2x16(f2h(6.0), f2h(1.0)) - v2_c = pack2x16(f2h(1.0), f2h(2.0)) - self.assertEqual(run_fma_mix(v0_c, v1_c, v2_c, op_sel=(0, 0, 0), op_sel_hi=(0, 1, 1)), - ref_fma_mix_f32(v0_c, v1_c, v2_c, op_sel=(0, 0, 0), op_sel_hi=(0, 1, 1))) - - def test_fma_mix_one_f16_two_f32(self): - # [1, 0, 0]: s0(f16), s1(f32), s2(f32) -> 0.5 * 8.0 + 3.0 = 7.0f - v0 = pack2x16(f2h(0.5), f2h(9.0)) - v1 = f32_to_u32(8.0) - v2 = f32_to_u32(3.0) - self.assertEqual(run_fma_mix(v0, v1, v2, op_sel=(0, 0, 0), op_sel_hi=(1, 0, 0)), - ref_fma_mix_f32(v0, v1, v2, op_sel=(0, 0, 0), op_sel_hi=(1, 0, 0))) - - # [0, 1, 0]: s0(f32), s1(f16), s2(f32) -> 7.0 * 2.0 + (-5.0) = 9.0f - v0_b = f32_to_u32(7.0) - v1_b = pack2x16(f2h(2.0), f2h(10.0)) - v2_b = f32_to_u32(-5.0) - self.assertEqual(run_fma_mix(v0_b, v1_b, v2_b, op_sel=(0, 0, 0), op_sel_hi=(0, 1, 0)), - ref_fma_mix_f32(v0_b, v1_b, v2_b, op_sel=(0, 0, 0), op_sel_hi=(0, 1, 0))) - - # [0, 0, 1]: s0(f32), s1(f32), s2(f16) -> 3.0 * 4.0 + 0.5 = 12.5f - v0_c = f32_to_u32(3.0) - v1_c = f32_to_u32(4.0) - v2_c = pack2x16(f2h(0.5), f2h(10.0)) - self.assertEqual(run_fma_mix(v0_c, v1_c, v2_c, op_sel=(0, 0, 0), op_sel_hi=(0, 0, 1)), - ref_fma_mix_f32(v0_c, v1_c, v2_c, op_sel=(0, 0, 0), op_sel_hi=(0, 0, 1))) - - def test_fma_mix_all_three_f32(self): - # [0, 0, 0]: all three sources are f32 -> 1.25 * 4.0 + 2.75 = 7.75f - v0 = f32_to_u32(1.25) - v1 = f32_to_u32(4.0) - v2 = f32_to_u32(2.75) - self.assertEqual(run_fma_mix(v0, v1, v2, op_sel=(0, 0, 0), op_sel_hi=(0, 0, 0)), - ref_fma_mix_f32(v0, v1, v2, op_sel=(0, 0, 0), op_sel_hi=(0, 0, 0))) - - def test_fma_mix_modifiers_neg_abs_clamp(self): - # Test operand negation and absolute value modifiers - # s0: -|v1|, s1: v2, s2: v3 - v0 = f32_to_u32(2.0) - v1 = f32_to_u32(3.0) - v2 = f32_to_u32(10.0) - # -|2.0| * 3.0 + 10.0 = -6.0 + 10.0 = 4.0f - expected = ref_fma_mix_f32(v0, v1, v2, neg=(1, 0, 0), abs_mask=(1, 0, 0)) - got = run_fma_mix(v0, v1, v2, neg=(1, 0, 0), abs_mask=(1, 0, 0)) - self.assertEqual(got, expected) - - # Clamp positive overflow: 2.0 * 2.0 + 0.0 = 4.0 -> clamp -> 1.0f (0x3F800000) - got_clamp_hi = run_fma_mix(f32_to_u32(2.0), f32_to_u32(2.0), f32_to_u32(0.0), clamp=True) - self.assertEqual(got_clamp_hi, 0x3F800000) - - # Clamp negative underflow: 2.0 * -2.0 + 0.0 = -4.0 -> clamp -> 0.0f (0x00000000) - got_clamp_lo = run_fma_mix(f32_to_u32(2.0), f32_to_u32(-2.0), f32_to_u32(0.0), clamp=True) - self.assertEqual(got_clamp_lo, 0x00000000) - - -class FmaMixF32SubnormalTests(unittest.TestCase): - """Audits mixed-precision FMA handling of f16 subnormals unpacked to single-precision float.""" - - def test_f16_subnormal_unpacked_to_f32_exact(self): - # An f16 subnormal 0x0001 (2^-24) unpacked to f32 is an exact normal single-precision float (0x33800000). - # In v_fma_mix_f32: 2^-24 * 1.0 + 0.0 = 2^-24 - v0 = pack2x16(F16_MIN_SUBNORMAL, F16_ZERO) - v1 = f32_to_u32(1.0) - v2 = f32_to_u32(0.0) - expected = ref_fma_mix_f32(v0, v1, v2, op_sel=(0, 0, 0), op_sel_hi=(1, 0, 0)) - got = run_fma_mix(v0, v1, v2, op_sel=(0, 0, 0), op_sel_hi=(1, 0, 0)) - self.assertEqual(got, expected) - self.assertEqual(got, 0x33800000) - self.assertAlmostEqual(u32_to_f32(got), 2.0**-24, delta=1e-15) - - def test_f16_largest_subnormal_in_mixed_fma(self): - # 0x03FF unpacked to f32: (1023/1024) * 2^-14 - # Multiplied by 2.0f: 0x03FF * 2.0 + 0.0 - v0 = pack2x16(F16_MAX_SUBNORMAL, F16_ZERO) - v1 = f32_to_u32(2.0) - v2 = f32_to_u32(0.0) - expected = ref_fma_mix_f32(v0, v1, v2, op_sel=(0, 0, 0), op_sel_hi=(1, 0, 0)) - got = run_fma_mix(v0, v1, v2, op_sel=(0, 0, 0), op_sel_hi=(1, 0, 0)) - self.assertEqual(got, expected) - - def test_f16_negative_subnormal_in_mixed_fma(self): - # 0x8001 (-2^-24) * 4.0 + 1.0 = 1.0 - 2^-22 - v0 = pack2x16(F16_NEG_MIN_SUBNORMAL, F16_ZERO) - v1 = f32_to_u32(4.0) - v2 = f32_to_u32(1.0) - expected = ref_fma_mix_f32(v0, v1, v2, op_sel=(0, 0, 0), op_sel_hi=(1, 0, 0)) - got = run_fma_mix(v0, v1, v2, op_sel=(0, 0, 0), op_sel_hi=(1, 0, 0)) - self.assertEqual(got, expected) - - def test_mixed_f16_subnormals_with_high_half_selection(self): - # v0: lo=normal 1.0, hi=subnormal 0x0001 - # op_sel:[1, 0, 0] selects high half (subnormal 2^-24) - v0 = pack2x16(F16_ONE, F16_MIN_SUBNORMAL) - v1 = pack2x16(F16_TWO, F16_ZERO) - v2 = f32_to_u32(0.5) - # 2^-24 * 2.0 + 0.5 = 2^-23 + 0.5 - expected = ref_fma_mix_f32(v0, v1, v2, op_sel=(1, 0, 0), op_sel_hi=(1, 1, 0)) - got = run_fma_mix(v0, v1, v2, op_sel=(1, 0, 0), op_sel_hi=(1, 1, 0)) - self.assertEqual(got, expected) - - -class NegativeControlTests(unittest.TestCase): - """Verify that mutations in operands, selections, or precision are detected as failures.""" - - def test_pk_fma_corruption_detected(self): - v0 = pack2x16(f2h(1.0), f2h(2.0)) - v1 = pack2x16(f2h(3.0), f2h(4.0)) - v2 = pack2x16(f2h(0.5), f2h(1.0)) - good = ref_pk_fma_f16(v0, v1, v2, op_sel=(0, 0, 0), op_sel_hi=(1, 1, 1)) - - # Inverting op_sel or op_sel_hi should produce a different result - bad_sel = ref_pk_fma_f16(v0, v1, v2, op_sel=(1, 0, 0), op_sel_hi=(1, 1, 1)) - self.assertNotEqual(good, bad_sel) - - bad_hi = ref_pk_fma_f16(v0, v1, v2, op_sel=(0, 0, 0), op_sel_hi=(0, 1, 1)) - self.assertNotEqual(good, bad_hi) - - def test_fma_mix_corruption_detected(self): - v0 = pack2x16(f2h(1.0), f2h(50.0)) - v1 = f32_to_u32(2.0) - v2 = f32_to_u32(3.0) - # f16(1.0) * 2.0 + 3.0 = 5.0 - good = ref_fma_mix_f32(v0, v1, v2, op_sel=(0, 0, 0), op_sel_hi=(1, 0, 0)) - # Corrupted to high half: f16(50.0) * 2.0 + 3.0 = 103.0 - corrupted = ref_fma_mix_f32(v0, v1, v2, op_sel=(1, 0, 0), op_sel_hi=(1, 0, 0)) - self.assertNotEqual(good, corrupted) - - def test_subnormal_precision_loss_detected(self): - # Adding smallest subnormal to 0x03FF should strictly yield 0x0400, not 0x03FF - res = ref_pk_fma_f16( - pack2x16(F16_MAX_SUBNORMAL, F16_MAX_SUBNORMAL), - pack2x16(F16_ONE, F16_ONE), - pack2x16(F16_MIN_SUBNORMAL, F16_MIN_SUBNORMAL), - ) - lo, _ = unpack2x16(res) - self.assertEqual(lo, F16_MIN_NORMAL) - self.assertNotEqual(lo, F16_MAX_SUBNORMAL) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_alu_frexp.py b/tests/semantic/test_alu_frexp.py deleted file mode 100644 index 9a1c63528..000000000 --- a/tests/semantic/test_alu_frexp.py +++ /dev/null @@ -1,745 +0,0 @@ -"""Semantic interpreter tests for floating-point frexp extraction (v_frexp_mant_f32, v_frexp_exp_i32_f32). - -Models IEEE 754 single-precision significand (mantissa) and unbiased exponent extraction as specified -in the AMD RDNA2 / GFX10 Instruction Set Architecture and the SPIR-V GLSL.std.450 extended instruction set: - - v_frexp_mant_f32: D.f = Mantissa(S0.f) - Decomposes S0 such that S0 = mantissa * 2^exponent with |mantissa| in [0.5, 1.0). - For normal inputs, the IEEE 754 biased exponent bits [30:23] are replaced with 126 (0x7E, representing - exponent 2^-1), preserving the original sign bit (bit 31) and 23-bit significand fraction (bits [22:0]). - Special values: - * +/-0.0: returns +/-0.0 (sign bit preserved) - * +/-INF: returns +/-INF unchanged - * NaN: returns NaN unchanged (quiet / signaling payload bits preserved) - * Subnormals: normalized into [0.5, 1.0) with scaled exponent, or flushed to +/-0.0 under FTZ - - v_frexp_exp_i32_f32: D.i = TwosComplement(Exponent(S0.f) - 127 + 1) - Extracts the unbiased integer exponent of S0, stored as a signed 32-bit integer in two's complement. - For normal inputs, computes (biased_exponent - 126). - Special values: - * +/-0.0: returns 0 - * +/-INF: returns 0 - * NaN: returns 0 - * Subnormals: returns -126 - leading_zeros (normalized) or 0 (FTZ) - -Includes: - * Bitwise reference oracle (ref_frexp_mant_f32_bits, ref_frexp_exp_i32_f32) - * Float-level oracle and cross-check against Python math.frexp - * Mathematical invariant proofs (reconstruction, range bounds, sign preservation, idempotence) - * Full coverage of edge cases (zeros, powers of two, boundaries, infinities, quiet/signaling NaNs) - * Direct execution of SPIR-V translation sequences using tests/semantic/spirv_mini_interp.py - * VALU assembly interpreter (FrexpValuInterpreter) modeling VOP1/VOP3 e32/e64 forms and input modifiers (|src|, -src) - -Standard library only; zero third-party dependencies; zero game data or proprietary assets. -Python 3.9+ compatible. -""" -from __future__ import annotations - -import math -import os -import struct -import sys -import unittest - -HERE = os.path.dirname(os.path.abspath(__file__)) -ROOT = os.path.dirname(os.path.dirname(HERE)) -TOOLS_DIR = os.environ.get("LEONIDA_TOOLS_DIR") or os.path.join(ROOT, "tools") - -sys.dont_write_bytecode = True -if TOOLS_DIR not in sys.path: - sys.path.insert(0, TOOLS_DIR) -if HERE not in sys.path: - sys.path.insert(0, HERE) - -import spirv_mini_interp as si # noqa: E402 - -MASK32 = 0xFFFFFFFF -SIGN_MASK = 0x80000000 -EXP_MASK = 0x7F800000 -MANT_MASK = 0x007FFFFF -EXP_BIAS = 127 -EXP_SHIFT = 23 -EXP_FREXP_BIASED = 126 # 2^-1 has biased exponent 126 in IEEE 754 -EXP_FREXP_BITS = EXP_FREXP_BIASED << EXP_SHIFT # 0x3F000000 (0.5f) - - -def f32_to_bits(f: float) -> int: - """Encode Python float as IEEE 754 single-precision 32-bit unsigned integer.""" - try: - return struct.unpack(" 0 else 0xFF800000 - - -def bits_to_f32(b: int) -> float: - """Decode IEEE 754 single-precision 32-bit unsigned integer to Python float.""" - return struct.unpack(" int: - """Convert integer to signed 32-bit two's complement.""" - x &= MASK32 - return x - (1 << 32) if x & SIGN_MASK else x - - -def ref_frexp_mant_f32_bits(s0_bits: int, ftz: bool = False) -> int: - """Reference oracle for v_frexp_mant_f32 bitwise extraction. - - Given a 32-bit single-precision float pattern s0_bits: - - If NaN or +/-INF: passed through unchanged. - - If +/-0.0: passed through unchanged (+/-0.0). - - If subnormal: normalized into [0.5, 1.0) under IEEE mode, or flushed to +/-0.0 under FTZ. - - If normal: sign and fraction are preserved, exponent is replaced with 126 (0x7E). - """ - s0_bits &= MASK32 - sign = s0_bits & SIGN_MASK - exp_biased = (s0_bits & EXP_MASK) >> EXP_SHIFT - frac = s0_bits & MANT_MASK - - if exp_biased == 0xFF: - # +/-INF or NaN: return unchanged - return s0_bits - - if exp_biased == 0: - if frac == 0: - # +/-0.0: return unchanged - return s0_bits - if ftz: - # Flush to zero: preserve sign - return sign - # Subnormal normalized: shift fraction left until bit 23 is set - lz = 23 - frac.bit_length() - norm_frac = (frac << (lz + 1)) & MANT_MASK - return sign | EXP_FREXP_BITS | norm_frac - - # Normal float: preserve sign and fraction, replace exponent with 126 - return sign | EXP_FREXP_BITS | frac - - -def ref_frexp_exp_i32_f32(s0_bits: int, ftz: bool = False) -> int: - """Reference oracle for v_frexp_exp_i32_f32 exponent extraction. - - Returns the unbiased exponent as a signed 32-bit integer in two's complement. - - If NaN or +/-INF: returns 0. - - If +/-0.0: returns 0. - - If normal: returns (exp_biased - 126) & MASK32. - - If subnormal: returns (-126 - leading_zeros) & MASK32 under IEEE mode, or 0 under FTZ. - """ - s0_bits &= MASK32 - exp_biased = (s0_bits & EXP_MASK) >> EXP_SHIFT - frac = s0_bits & MANT_MASK - - if exp_biased == 0xFF: - return 0 - - if exp_biased == 0: - if frac == 0 or ftz: - return 0 - lz = 23 - frac.bit_length() - unbiased = -126 - lz - return unbiased & MASK32 - - unbiased = exp_biased - 126 - return unbiased & MASK32 - - -def ref_frexp_mant_f32(x: float, ftz: bool = False) -> float: - """Float-level oracle for v_frexp_mant_f32.""" - bits = f32_to_bits(x) - return bits_to_f32(ref_frexp_mant_f32_bits(bits, ftz=ftz)) - - -def ref_frexp_exp_i32(x: float, ftz: bool = False) -> int: - """Float-level oracle for v_frexp_exp_i32_f32, returning Python signed integer.""" - bits = f32_to_bits(x) - return s32(ref_frexp_exp_i32_f32(bits, ftz=ftz)) - - -def run_spirv_frexp_exp(in_word: int) -> int: - """Executes a SPIR-V fragment module evaluating v_frexp_exp_i32_f32 bitwise logic in spirv_mini_interp.""" - in_word &= MASK32 - mod = f"""OpCapability Shader -%glsl = OpExtInstImport "GLSL.std.450" -OpMemoryModel Logical GLSL450 -OpEntryPoint Fragment %main "main" %out -%void = OpTypeVoid -%fn = OpTypeFunction %void -%uint = OpTypeInt 32 0 -%bool = OpTypeBool -%_ptr_Output_uint = OpTypePointer Output %uint -%out = OpVariable %_ptr_Output_uint Output -%c_in = OpConstant %uint {in_word} -%c_23 = OpConstant %uint 23 -%c_255 = OpConstant %uint 255 -%c_126 = OpConstant %uint 126 -%c_0 = OpConstant %uint 0 -%main = OpFunction %void None %fn -%entry = OpLabel -%s = OpShiftRightLogical %uint %c_in %c_23 -%exp_biased = OpBitwiseAnd %uint %s %c_255 -%unbiased = OpISub %uint %exp_biased %c_126 -%is_zero = OpIEqual %bool %exp_biased %c_0 -%is_inf_nan = OpIEqual %bool %exp_biased %c_255 -%is_special = OpLogicalOr %bool %is_zero %is_inf_nan -%res = OpSelect %uint %is_special %c_0 %unbiased -OpStore %out %res -OpReturn -OpFunctionEnd -""" - return si.run_fragment(mod)["%out"][0] - - -def run_spirv_frexp_mant(in_word: int) -> int: - """Executes a SPIR-V fragment module evaluating v_frexp_mant_f32 bitwise logic in spirv_mini_interp.""" - in_word &= MASK32 - mod = f"""OpCapability Shader -%glsl = OpExtInstImport "GLSL.std.450" -OpMemoryModel Logical GLSL450 -OpEntryPoint Fragment %main "main" %out -%void = OpTypeVoid -%fn = OpTypeFunction %void -%uint = OpTypeInt 32 0 -%bool = OpTypeBool -%_ptr_Output_uint = OpTypePointer Output %uint -%out = OpVariable %_ptr_Output_uint Output -%c_in = OpConstant %uint {in_word} -%c_23 = OpConstant %uint 23 -%c_255 = OpConstant %uint 255 -%c_mask_mant = OpConstant %uint {SIGN_MASK | MANT_MASK} -%c_exp_126 = OpConstant %uint {EXP_FREXP_BITS} -%c_abs_mask = OpConstant %uint {EXP_MASK | MANT_MASK} -%c_0 = OpConstant %uint 0 -%main = OpFunction %void None %fn -%entry = OpLabel -%s = OpShiftRightLogical %uint %c_in %c_23 -%exp_biased = OpBitwiseAnd %uint %s %c_255 -%is_inf_nan = OpIEqual %bool %exp_biased %c_255 -%abs_in = OpBitwiseAnd %uint %c_in %c_abs_mask -%is_zero = OpIEqual %bool %abs_in %c_0 -%stripped = OpBitwiseAnd %uint %c_in %c_mask_mant -%mant_normal = OpBitwiseOr %uint %stripped %c_exp_126 -%res_nonzero = OpSelect %uint %is_zero %c_in %mant_normal -%res = OpSelect %uint %is_inf_nan %c_in %res_nonzero -OpStore %out %res -OpReturn -OpFunctionEnd -""" - return si.run_fragment(mod)["%out"][0] - - -class FrexpValuInterpreter: - """Simulated VALU interpreter supporting v_frexp_mant_f32 and v_frexp_exp_i32_f32. - - Models register file (VGPR v0..v255, SGPR s0..s105), inline constants, - e32 / e64 instruction forms, and input modifiers (abs |src| and neg -src). - """ - - def __init__(self, ftz: bool = False): - self.vgpr: dict[int, int] = {} - self.sgpr: dict[int, int] = {} - self.ftz = ftz - - def read_reg(self, name: str) -> int: - if name.startswith("v"): - return self.vgpr.get(int(name[1:]), 0) & MASK32 - if name.startswith("s"): - return self.sgpr.get(int(name[1:]), 0) & MASK32 - raise ValueError(f"Unknown register name: {name}") - - def write_reg(self, name: str, val: int) -> None: - val &= MASK32 - if name.startswith("v"): - self.vgpr[int(name[1:])] = val - elif name.startswith("s"): - self.sgpr[int(name[1:])] = val - else: - raise ValueError(f"Unknown destination register: {name}") - - def parse_operand(self, token: str) -> tuple[int, bool, bool]: - """Parses operand token into (raw_bits, is_abs, is_neg).""" - token = token.strip() - is_abs = False - is_neg = False - - if token.startswith("|") and token.endswith("|"): - is_abs = True - token = token[1:-1].strip() - - if token.startswith("-"): - is_neg = True - token = token[1:].strip() - - # Check inline floating point constants - inline_floats = { - "0.5": 0x3F000000, - "1.0": 0x3F800000, - "2.0": 0x40000000, - "4.0": 0x40800000, - "0.0": 0x00000000, - } - if token in inline_floats: - val = inline_floats[token] - elif token.startswith("v") or token.startswith("s"): - val = self.read_reg(token) - elif token.startswith("0x") or token.startswith("0X"): - val = int(token, 16) & MASK32 - else: - # Integer constant or float literal - try: - val = int(token) & MASK32 - except ValueError: - val = f32_to_bits(float(token)) - - if is_abs: - val &= ~SIGN_MASK - if is_neg: - val ^= SIGN_MASK - - return val, is_abs, is_neg - - def execute_line(self, line: str) -> None: - """Executes a single assembly line.""" - clean = line.split(";")[0].strip() - if not clean: - return - - parts = clean.split(None, 1) - mnemonic = parts[0].lower() - operands = [op.strip() for op in parts[1].split(",")] if len(parts) > 1 else [] - - if mnemonic in ("v_mov_b32", "v_mov_b32_e32", "s_mov_b32"): - dst = operands[0] - src_val, _, _ = self.parse_operand(operands[1]) - self.write_reg(dst, src_val) - elif mnemonic in ("v_frexp_mant_f32", "v_frexp_mant_f32_e32", "v_frexp_mant_f32_e64"): - dst = operands[0] - src_val, _, _ = self.parse_operand(operands[1]) - res = ref_frexp_mant_f32_bits(src_val, ftz=self.ftz) - self.write_reg(dst, res) - elif mnemonic in ("v_frexp_exp_i32_f32", "v_frexp_exp_i32_f32_e32", "v_frexp_exp_i32_f32_e64"): - dst = operands[0] - src_val, _, _ = self.parse_operand(operands[1]) - res = ref_frexp_exp_i32_f32(src_val, ftz=self.ftz) - self.write_reg(dst, res) - else: - raise NotImplementedError(f"Unsupported mnemonic: {mnemonic}") - - -class TestFrexpReferenceOracle(unittest.TestCase): - """Unit tests verifying the bitwise and float reference oracles against IEEE 754 rules.""" - - def test_signed_zeros(self): - # +0.0: mantissa is +0.0, exponent is 0 - self.assertEqual(ref_frexp_mant_f32_bits(0x00000000), 0x00000000) - self.assertEqual(ref_frexp_exp_i32_f32(0x00000000), 0) - - # -0.0: mantissa is -0.0 (sign bit preserved), exponent is 0 - self.assertEqual(ref_frexp_mant_f32_bits(0x80000000), 0x80000000) - self.assertEqual(ref_frexp_exp_i32_f32(0x80000000), 0) - - def test_powers_of_two(self): - cases = [ - # (float_value, expected_mantissa_float, expected_exponent_int) - (1.0, 0.5, 1), - (0.5, 0.5, 0), - (0.25, 0.5, -1), - (0.125, 0.5, -2), - (2.0, 0.5, 2), - (4.0, 0.5, 3), - (8.0, 0.5, 4), - (1024.0, 0.5, 11), - (-1.0, -0.5, 1), - (-0.5, -0.5, 0), - (-0.25, -0.5, -1), - (-2.0, -0.5, 2), - (-4.0, -0.5, 3), - ] - for val, exp_mant, exp_exp in cases: - with self.subTest(val=val): - bits = f32_to_bits(val) - mant_bits = ref_frexp_mant_f32_bits(bits) - mant_float = bits_to_f32(mant_bits) - exp_int = s32(ref_frexp_exp_i32_f32(bits)) - - self.assertAlmostEqual(mant_float, exp_mant, places=6) - self.assertEqual(exp_int, exp_exp) - # Verify exact bitwise exponent field is 126 (0x7E) - self.assertEqual((mant_bits & EXP_MASK) >> EXP_SHIFT, 126) - - def test_representative_floats(self): - cases = [ - (1.5, 0.75, 1), - (-1.5, -0.75, 1), - (3.0, 0.75, 2), - (-3.0, -0.75, 2), - (0.75, 0.75, 0), - (-0.75, -0.75, 0), - (3.1415927, 3.1415927 / 4.0, 2), - (-42.125, -42.125 / 64.0, 6), - (100.0, 100.0 / 128.0, 7), - (0.001, 0.001 / (2.0 ** -9), -9), - ] - for val, exp_mant, exp_exp in cases: - with self.subTest(val=val): - bits = f32_to_bits(val) - mant_float = bits_to_f32(ref_frexp_mant_f32_bits(bits)) - exp_int = s32(ref_frexp_exp_i32_f32(bits)) - - self.assertAlmostEqual(mant_float, exp_mant, places=6) - self.assertEqual(exp_int, exp_exp) - - def test_boundary_normals(self): - # FLT_MAX: largest finite single-precision float - flt_max_bits = 0x7F7FFFFF - flt_max = bits_to_f32(flt_max_bits) - mant_bits = ref_frexp_mant_f32_bits(flt_max_bits) - exp_int = s32(ref_frexp_exp_i32_f32(flt_max_bits)) - self.assertEqual(exp_int, 128) - self.assertEqual(mant_bits, 0x3F7FFFFF) # exponent 126, all fraction bits 1 - self.assertAlmostEqual(bits_to_f32(mant_bits), 1.0 - (2.0 ** -24), places=6) - - # -FLT_MAX - flt_max_neg_bits = 0xFF7FFFFF - mant_neg_bits = ref_frexp_mant_f32_bits(flt_max_neg_bits) - exp_neg_int = s32(ref_frexp_exp_i32_f32(flt_max_neg_bits)) - self.assertEqual(exp_neg_int, 128) - self.assertEqual(mant_neg_bits, 0xBF7FFFFF) - - # FLT_MIN: smallest positive normalized float (2^-126) - flt_min_bits = 0x00800000 # exp=1, frac=0 - mant_min_bits = ref_frexp_mant_f32_bits(flt_min_bits) - exp_min_int = s32(ref_frexp_exp_i32_f32(flt_min_bits)) - self.assertEqual(exp_min_int, -125) - self.assertEqual(mant_min_bits, 0x3F000000) # 0.5f - - def test_special_ieee_infinities_and_nans(self): - # +Infinity - pos_inf = 0x7F800000 - self.assertEqual(ref_frexp_mant_f32_bits(pos_inf), pos_inf) - self.assertEqual(ref_frexp_exp_i32_f32(pos_inf), 0) - - # -Infinity - neg_inf = 0xFF800000 - self.assertEqual(ref_frexp_mant_f32_bits(neg_inf), neg_inf) - self.assertEqual(ref_frexp_exp_i32_f32(neg_inf), 0) - - # Quiet NaN (+ and -) - pos_qnan = 0x7FC00000 - neg_qnan = 0xFFC00000 - self.assertEqual(ref_frexp_mant_f32_bits(pos_qnan), pos_qnan) - self.assertEqual(ref_frexp_exp_i32_f32(pos_qnan), 0) - self.assertEqual(ref_frexp_mant_f32_bits(neg_qnan), neg_qnan) - self.assertEqual(ref_frexp_exp_i32_f32(neg_qnan), 0) - - # Signaling NaN with custom payloads - snans = [0x7F800001, 0x7F9ABCDE, 0xFF800001, 0xFFBEEF00] - for snan in snans: - with self.subTest(snan=hex(snan)): - self.assertEqual(ref_frexp_mant_f32_bits(snan), snan) - self.assertEqual(ref_frexp_exp_i32_f32(snan), 0) - - def test_subnormal_numbers(self): - # Smallest subnormal: 1 * 2^-149 - sub_min = 0x00000001 - # In normalized mode: mantissa is 0.5, exp is -148 - self.assertEqual(ref_frexp_mant_f32_bits(sub_min, ftz=False), 0x3F000000) - self.assertEqual(s32(ref_frexp_exp_i32_f32(sub_min, ftz=False)), -148) - - # Subnormal with power of two bit: 2^-130 -> frac has bit 19 set - # value is 2^-130 = 0.5 * 2^-129 - sub_p2 = 1 << 19 # 0x00080000 - self.assertEqual(ref_frexp_mant_f32_bits(sub_p2, ftz=False), 0x3F000000) - self.assertEqual(s32(ref_frexp_exp_i32_f32(sub_p2, ftz=False)), -129) - - # Largest subnormal: 0x007FFFFF - sub_max = 0x007FFFFF - self.assertEqual(s32(ref_frexp_exp_i32_f32(sub_max, ftz=False)), -126) - mant_sub_max = ref_frexp_mant_f32_bits(sub_max, ftz=False) - self.assertEqual((mant_sub_max & EXP_MASK) >> EXP_SHIFT, 126) - - # Flush to zero (FTZ) mode - self.assertEqual(ref_frexp_mant_f32_bits(sub_min, ftz=True), 0x00000000) - self.assertEqual(ref_frexp_exp_i32_f32(sub_min, ftz=True), 0) - self.assertEqual(ref_frexp_mant_f32_bits(0x80000001, ftz=True), 0x80000000) - self.assertEqual(ref_frexp_exp_i32_f32(0x80000001, ftz=True), 0) - - def test_cross_check_with_python_math_frexp(self): - """Cross-checks reference oracle against standard library math.frexp for 1,000 floats.""" - for exp in range(-125, 128): - for frac_mult in (1.0, 1.25, 1.5, 1.75, 1.9999): - val = frac_mult * (2.0 ** (exp - 1)) - if val > 3.4e38: - continue - # Test both positive and negative - for sign in (1.0, -1.0): - x = sign * val - py_mant, py_exp = math.frexp(x) - ref_mant = ref_frexp_mant_f32(x) - ref_exp = ref_frexp_exp_i32(x) - - self.assertAlmostEqual(ref_mant, py_mant, places=6) - self.assertEqual(ref_exp, py_exp) - - -class TestFrexpMathematicalInvariants(unittest.TestCase): - """Verifies fundamental algebraic and IEEE 754 invariants of the frexp decomposition.""" - - def test_exact_reconstruction(self): - """Invariant: x == mantissa * (2 ** exponent) for all non-zero finite normal numbers.""" - test_values = [ - 1.0, -1.0, 0.5, -0.5, 2.0, -2.0, 1.5, -1.5, 42.0, -42.0, - 0.1, -0.1, 1000.0, 0.0001, 3.14159265, 2.71828182, - bits_to_f32(0x3F800001), bits_to_f32(0x3F7FFFFF), - ] - for val in test_values: - with self.subTest(val=val): - mant = ref_frexp_mant_f32(val) - exp = ref_frexp_exp_i32(val) - reconstructed = mant * (2.0 ** exp) - self.assertAlmostEqual(reconstructed, val, places=6) - - def test_mantissa_bounds(self): - """Invariant: 0.5 <= |mantissa| < 1.0 for all non-zero finite numbers.""" - test_words = [ - 0x3F800000, 0x40000000, 0x3F000000, 0x3E800000, 0x44800000, - 0xBF800000, 0xC0000000, 0x7F7FFFFF, 0x00800000, - ] - for word in test_words: - with self.subTest(word=hex(word)): - mant = abs(bits_to_f32(ref_frexp_mant_f32_bits(word))) - self.assertGreaterEqual(mant, 0.5) - self.assertLess(mant, 1.0) - - def test_sign_preservation_and_reflection(self): - """Invariant: signbit(mantissa) == signbit(x) and mantissa(-x) == -mantissa(x).""" - test_words = [0x3F800000, 0x40490FDB, 0x3EAAAAAB, 0x42280000] - for word in test_words: - neg_word = word ^ SIGN_MASK - mant_pos = ref_frexp_mant_f32_bits(word) - mant_neg = ref_frexp_mant_f32_bits(neg_word) - - # Mantissa sign bit must match input sign bit - self.assertEqual(mant_pos & SIGN_MASK, 0) - self.assertEqual(mant_neg & SIGN_MASK, SIGN_MASK) - # Magnitudes must be identical - self.assertEqual(mant_pos & ~SIGN_MASK, mant_neg & ~SIGN_MASK) - - def test_sign_invariance_of_exponent(self): - """Invariant: exponent(x) == exponent(-x) for any float x.""" - for word in [0x3F800000, 0x40490FDB, 0x3F000000, 0x7F7FFFFF, 0x00800000]: - neg_word = word ^ SIGN_MASK - self.assertEqual(ref_frexp_exp_i32_f32(word), ref_frexp_exp_i32_f32(neg_word)) - - def test_idempotence_properties(self): - """Invariant: mantissa(mantissa(x)) == mantissa(x) and exponent(mantissa(x)) == 0.""" - for word in [0x3F800000, 0x40490FDB, 0xC2288000, 0x3EAAAAAB]: - mant1 = ref_frexp_mant_f32_bits(word) - mant2 = ref_frexp_mant_f32_bits(mant1) - exp_mant1 = ref_frexp_exp_i32_f32(mant1) - - self.assertEqual(mant1, mant2) - self.assertEqual(exp_mant1, 0) - - def test_scaling_by_powers_of_two(self): - """Invariant: mantissa(x * 2^k) == mantissa(x) and exponent(x * 2^k) == exponent(x) + k.""" - base = 1.5 - for k in range(-5, 6): - scaled = base * (2.0 ** k) - self.assertAlmostEqual(ref_frexp_mant_f32(scaled), ref_frexp_mant_f32(base), places=6) - self.assertEqual(ref_frexp_exp_i32(scaled), ref_frexp_exp_i32(base) + k) - - -class TestSpirvFrexpMiniInterpreter(unittest.TestCase): - """Verifies that SPIR-V instruction sequences for frexp mantissa and exponent run accurately in spirv_mini_interp.""" - - def test_spirv_exponent_extraction(self): - test_cases = [ - (0x3F800000, 1), # 1.0f -> exp 1 - (0x3F000000, 0), # 0.5f -> exp 0 - (0x40000000, 2), # 2.0f -> exp 2 - (0x3E800000, -1 & MASK32), # 0.25f -> exp -1 - (0xBF800000, 1), # -1.0f -> exp 1 - (0x00000000, 0), # +0.0 -> 0 - (0x80000000, 0), # -0.0 -> 0 - (0x7F800000, 0), # +INF -> 0 - (0xFF800000, 0), # -INF -> 0 - (0x7FC00000, 0), # NaN -> 0 - ] - for in_bits, want_exp in test_cases: - with self.subTest(in_bits=hex(in_bits)): - got_exp = run_spirv_frexp_exp(in_bits) - self.assertEqual(got_exp, want_exp) - self.assertEqual(got_exp, ref_frexp_exp_i32_f32(in_bits)) - - def test_spirv_mantissa_extraction(self): - test_cases = [ - (0x3F800000, 0x3F000000), # 1.0f -> 0.5f - (0x3F000000, 0x3F000000), # 0.5f -> 0.5f - (0x40000000, 0x3F000000), # 2.0f -> 0.5f - (0x3FC00000, 0x3F400000), # 1.5f -> 0.75f - (0xBFC00000, 0xBF400000), # -1.5f -> -0.75f - (0x00000000, 0x00000000), # +0.0 -> +0.0 - (0x80000000, 0x80000000), # -0.0 -> -0.0 - (0x7F800000, 0x7F800000), # +INF -> +INF - (0xFF800000, 0xFF800000), # -INF -> -INF - (0x7FC00000, 0x7FC00000), # NaN -> NaN - ] - for in_bits, want_mant in test_cases: - with self.subTest(in_bits=hex(in_bits)): - got_mant = run_spirv_frexp_mant(in_bits) - self.assertEqual(got_mant, want_mant) - self.assertEqual(got_mant, ref_frexp_mant_f32_bits(in_bits)) - - def test_spirv_end_to_end_reconstruction(self): - """Constructs a SPIR-V module that extracts mantissa and exponent and reconstructs the float.""" - mod = """OpCapability Shader -%glsl = OpExtInstImport "GLSL.std.450" -OpMemoryModel Logical GLSL450 -OpEntryPoint Fragment %main "main" %out -%void = OpTypeVoid -%fn = OpTypeFunction %void -%uint = OpTypeInt 32 0 -%float = OpTypeFloat 32 -%bool = OpTypeBool -%_ptr_Output_uint = OpTypePointer Output %uint -%out = OpVariable %_ptr_Output_uint Output -%c_in = OpConstant %uint 1077936128 -%c_23 = OpConstant %uint 23 -%c_255 = OpConstant %uint 255 -%c_126 = OpConstant %uint 126 -%c_mask_mant = OpConstant %uint 2155872255 -%c_exp_bits = OpConstant %uint 1056964608 -%c_exp_bias = OpConstant %uint 127 -%main = OpFunction %void None %fn -%entry = OpLabel -%s = OpShiftRightLogical %uint %c_in %c_23 -%exp_biased = OpBitwiseAnd %uint %s %c_255 -%unbiased = OpISub %uint %exp_biased %c_126 -%stripped = OpBitwiseAnd %uint %c_in %c_mask_mant -%mant_bits = OpBitwiseOr %uint %stripped %c_exp_bits -%mant_f32 = OpBitcast %float %mant_bits -%scale_exp = OpIAdd %uint %unbiased %c_exp_bias -%scale_bits = OpShiftLeftLogical %uint %scale_exp %c_23 -%scale_f32 = OpBitcast %float %scale_bits -%reconstructed = OpFMul %float %mant_f32 %scale_f32 -%res_bits = OpBitcast %uint %reconstructed -OpStore %out %res_bits -OpReturn -OpFunctionEnd -""" - # 1077936128 is 0x40400000 (3.0f). Reconstructed value must be 0x40400000. - res = si.run_fragment(mod)["%out"][0] - self.assertEqual(res, 0x40400000) - - -class TestFrexpValuInterpreter(unittest.TestCase): - """Tests simulated execution of VALU assembly instructions v_frexp_mant_f32 and v_frexp_exp_i32_f32.""" - - def setUp(self): - self.interp = FrexpValuInterpreter() - - def test_v_frexp_mant_f32_e32(self): - # v_mov_b32 v1, 0x40000000 (2.0f) - # v_frexp_mant_f32_e32 v0, v1 - self.interp.execute_line("v_mov_b32 v1, 0x40000000") - self.interp.execute_line("v_frexp_mant_f32_e32 v0, v1") - self.assertEqual(self.interp.read_reg("v0"), 0x3F000000) # 0.5f - - def test_v_frexp_exp_i32_f32_e32(self): - # v_mov_b32 v1, 0x40000000 (2.0f) - # v_frexp_exp_i32_f32_e32 v0, v1 - self.interp.execute_line("v_mov_b32 v1, 0x40000000") - self.interp.execute_line("v_frexp_exp_i32_f32_e32 v0, v1") - self.assertEqual(self.interp.read_reg("v0"), 2) - - def test_sgpr_operand_source(self): - self.interp.execute_line("s_mov_b32 s4, 0x3FC00000") # 1.5f - self.interp.execute_line("v_frexp_mant_f32 v0, s4") - self.interp.execute_line("v_frexp_exp_i32_f32 v1, s4") - self.assertEqual(self.interp.read_reg("v0"), 0x3F400000) # 0.75f - self.assertEqual(self.interp.read_reg("v1"), 1) - - def test_inline_constants(self): - self.interp.execute_line("v_frexp_mant_f32 v0, 1.0") - self.interp.execute_line("v_frexp_exp_i32_f32 v1, 1.0") - self.assertEqual(self.interp.read_reg("v0"), 0x3F000000) - self.assertEqual(self.interp.read_reg("v1"), 1) - - self.interp.execute_line("v_frexp_mant_f32 v2, 0.5") - self.interp.execute_line("v_frexp_exp_i32_f32 v3, 0.5") - self.assertEqual(self.interp.read_reg("v2"), 0x3F000000) - self.assertEqual(self.interp.read_reg("v3"), 0) - - self.interp.execute_line("v_frexp_mant_f32 v4, 2.0") - self.interp.execute_line("v_frexp_exp_i32_f32 v5, 2.0") - self.assertEqual(self.interp.read_reg("v4"), 0x3F000000) - self.assertEqual(self.interp.read_reg("v5"), 2) - - def test_vop3_e64_abs_modifier(self): - # abs(|src|) on negative float clears sign bit - self.interp.execute_line("v_mov_b32 v1, 0xBFC00000") # -1.5f - self.interp.execute_line("v_frexp_mant_f32_e64 v0, |v1|") - self.assertEqual(self.interp.read_reg("v0"), 0x3F400000) # +0.75f (sign bit stripped) - - # abs(|src|) on exponent extraction has no effect on result - self.interp.execute_line("v_frexp_exp_i32_f32_e64 v2, |v1|") - self.assertEqual(self.interp.read_reg("v2"), 1) - - def test_vop3_e64_neg_modifier(self): - # neg(-src) on positive float inverts sign bit - self.interp.execute_line("v_mov_b32 v1, 0x3FC00000") # +1.5f - self.interp.execute_line("v_frexp_mant_f32_e64 v0, -v1") - self.assertEqual(self.interp.read_reg("v0"), 0xBF400000) # -0.75f - - # neg(-src) on exponent extraction has no effect on result - self.interp.execute_line("v_frexp_exp_i32_f32_e64 v2, -v1") - self.assertEqual(self.interp.read_reg("v2"), 1) - - -class TestFrexpEdgeCasesAndBitPatterns(unittest.TestCase): - """Exhaustive bit-pattern and edge-case testing for exponent and mantissa extraction.""" - - def test_all_254_normal_exponents(self): - """Iterates through all possible normal biased exponents (1..254) with zero fraction.""" - for exp in range(1, 255): - word = exp << EXP_SHIFT - mant_bits = ref_frexp_mant_f32_bits(word) - exp_res = ref_frexp_exp_i32_f32(word) - - # Mantissa exponent must always be 126 - self.assertEqual((mant_bits & EXP_MASK) >> EXP_SHIFT, 126) - # Fraction must remain 0 - self.assertEqual(mant_bits & MANT_MASK, 0) - # Exponent must be exp - 126 - expected_unbiased = (exp - 126) & MASK32 - self.assertEqual(exp_res, expected_unbiased) - - def test_walking_fraction_bits(self): - """Verifies each fraction bit (bit 0 through 22) is faithfully preserved in mantissa.""" - for bit_idx in range(23): - frac = 1 << bit_idx - word = 0x3F800000 | frac # normal float near 1.0 - mant_bits = ref_frexp_mant_f32_bits(word) - - # Fraction bits must match exactly - self.assertEqual(mant_bits & MANT_MASK, frac) - # Exponent must be replaced with 126 - self.assertEqual((mant_bits & EXP_MASK) >> EXP_SHIFT, 126) - - def test_alternating_bit_patterns(self): - """Tests bit patterns with alternating ones and zeros in the mantissa fraction.""" - patterns = [0x555555, 0x2AAAAA, 0x7FFFFF, 0x000001] - for pat in patterns: - word = (127 << EXP_SHIFT) | (pat & MANT_MASK) - mant_bits = ref_frexp_mant_f32_bits(word) - self.assertEqual(mant_bits & MANT_MASK, pat & MANT_MASK) - self.assertEqual(ref_frexp_exp_i32_f32(word), 1) - - def test_nan_payload_preservation(self): - """Verifies NaN payload bits are completely preserved by v_frexp_mant_f32.""" - for payload in [1, 2, 0x3FFFFF, 0x200000, 0x101010]: - nan_bits = EXP_MASK | payload - self.assertEqual(ref_frexp_mant_f32_bits(nan_bits), nan_bits) - self.assertEqual(ref_frexp_exp_i32_f32(nan_bits), 0) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_alu_frexp_f64.py b/tests/semantic/test_alu_frexp_f64.py deleted file mode 100644 index fef4e4b53..000000000 --- a/tests/semantic/test_alu_frexp_f64.py +++ /dev/null @@ -1,334 +0,0 @@ -"""Semantic interpreter and spirv-val tests for RDNA2 v_frexp_mant_f64 and v_frexp_exp_i32_f64. - -v_frexp_mant_f64 returns the binary64 mantissa of S0 in [0.5, 1) with its sign, and v_frexp_exp_i32_f64 returns the -matching signed 32-bit exponent (S0 = mant * 2^exp). Under default denorm16_64=3 (measured natively on gfx1036, -wave32 and wave64), non-zero subnormals normalize into [0.5, 1) with exponent -1073..-1022; signed zero gives signed -zero and exponent 0; infinities and NaNs pass through v_frexp_mant_f64 unchanged and give exponent 0. -""" -import math -import os -import random -import re -import shutil -import struct -import subprocess -import sys -import tempfile -import unittest -import warnings - -HERE = os.path.dirname(os.path.abspath(__file__)) -ROOT = os.path.dirname(os.path.dirname(HERE)) -TOOLS_DIR = os.environ.get("LEONIDA_TOOLS_DIR") or os.path.join(ROOT, "tools") - -sys.dont_write_bytecode = True -sys.path.insert(0, TOOLS_DIR) -sys.path.insert(0, HERE) - -import rdna2spirv # noqa: E402 -import spirv_mini_interp as si # noqa: E402 - -STUB_DXBC = b"DXBC" + bytes(24) + struct.pack(" int: - return struct.unpack(" float: - return struct.unpack(" bool: - return 0 < ((u >> 52) & 0x7FF) < 2047 - - -def is_finite_nonzero(u: int) -> bool: - exp_f = (u >> 52) & 0x7FF - frac = u & ((1 << 52) - 1) - return exp_f < 2047 and (exp_f > 0 or frac != 0) - - -def ref_mant(u: int) -> int: - if not is_finite_nonzero(u): - return u - return d2u(math.frexp(u2d(u))[0]) - - -def ref_exp(u: int) -> int: - return math.frexp(u2d(u))[1] & 0xFFFFFFFF if is_finite_nonzero(u) else 0 - - -_TMP_DIR = None -_SRC_PATH = None - - -def setUpModule(): - global _TMP_DIR, _SRC_PATH - _TMP_DIR = tempfile.TemporaryDirectory() - disasm_dir = os.path.join(_TMP_DIR.name, "disasm") - os.mkdir(disasm_dir) - _SRC_PATH = os.path.join(disasm_dir, "ps_frexp_f64.s") - with open(os.path.join(_TMP_DIR.name, "ps_frexp_f64.dxbc"), "wb") as f: - f.write(STUB_DXBC) - - -def tearDownModule(): - global _TMP_DIR - if _TMP_DIR is not None: - _TMP_DIR.cleanup() - _TMP_DIR = None - - -def translate_lines(lines): - if _TMP_DIR is None: - setUpModule() - asm = ( - "; test_frexp_f64\n" - + "".join(f"\t{ln}\n" for ln in lines) - + "\texp mrt0 v0, v1, v2, v3 done vm\n\ts_endpgm\n" - ) - with open(_SRC_PATH, "w", encoding="utf-8") as f: - f.write(asm) - with warnings.catch_warnings(): - warnings.simplefilter("ignore", ResourceWarning) - return rdna2spirv.translate(_SRC_PATH) - - -def validate_spirv(spv_text: str): - spirv_as = shutil.which("spirv-as") - spirv_val = shutil.which("spirv-val") - if not spirv_as or not spirv_val: - return - with tempfile.TemporaryDirectory() as d: - asm_p = os.path.join(d, "s.spvasm") - bin_p = os.path.join(d, "s.spv") - with open(asm_p, "w", encoding="utf-8") as f: - f.write(spv_text) - r1 = subprocess.run([spirv_as, "--target-env", "vulkan1.2", asm_p, "-o", bin_p], capture_output=True, text=True) - if r1.returncode != 0: - raise AssertionError(f"spirv-as failed: {r1.stderr}") - r2 = subprocess.run([spirv_val, "--target-env", "vulkan1.2", bin_p], capture_output=True, text=True) - if r2.returncode != 0: - raise AssertionError(f"spirv-val failed: {r2.stderr}") - - -def run_mant(line: str, u: int) -> int: - lo, hi = u & 0xFFFFFFFF, (u >> 32) & 0xFFFFFFFF - spv = translate_lines([ - f"v_mov_b32 v2, {lo:#x}", - f"v_mov_b32 v3, {hi:#x}", - "v_mov_b32 v0, 0", - "v_mov_b32 v1, 0", - line, - ]) - out = si.run_fragment(spv)["%out_mrt0"] - return (out[1] << 32) | out[0] - - -def run_exp(line: str, u: int) -> int: - lo, hi = u & 0xFFFFFFFF, (u >> 32) & 0xFFFFFFFF - spv = translate_lines([ - f"v_mov_b32 v2, {lo:#x}", - f"v_mov_b32 v3, {hi:#x}", - "v_mov_b32 v0, 0", - "v_mov_b32 v1, 0", - line, - ]) - return si.run_fragment(spv)["%out_mrt0"][0] - - -def sample_normals(seed: int, count: int): - rng = random.Random(seed) - out = [ - d2u(1.0), d2u(-1.0), d2u(0.5), d2u(0.75), d2u(8.0), d2u(-0.1), d2u(math.pi), - MIN_NORMAL, MAX_FINITE, MAX_FINITE | (1 << 63), MIN_NORMAL | (1 << 63), - ] - while len(out) < count: - u = rng.getrandbits(64) - if is_normal(u): - out.append(u) - return out - - -class FrexpF64Tests(unittest.TestCase): - def test_known_values(self): - cases = ( - (1.0, 0.5, 1), - (-1.0, -0.5, 1), - (0.5, 0.5, 0), - (3.0, 0.75, 2), - (-0.1875, -0.75, -2), - (1024.0, 0.5, 11), - (2.0 ** -1022, 0.5, -1021), - ) - for x, m, e in cases: - with self.subTest(x=x): - self.assertEqual(run_mant("v_frexp_mant_f64_e32 v[0:1], v[2:3]", d2u(x)), d2u(m)) - self.assertEqual(run_exp("v_frexp_exp_i32_f64_e32 v0, v[2:3]", d2u(x)), e & 0xFFFFFFFF) - - def test_matches_python_on_normals(self): - for u in sample_normals(0xF64, 60): - with self.subTest(x=hex(u)): - self.assertEqual(run_mant("v_frexp_mant_f64_e32 v[0:1], v[2:3]", u), ref_mant(u)) - self.assertEqual(run_exp("v_frexp_exp_i32_f64_e32 v0, v[2:3]", u), ref_exp(u)) - - def test_reconstruction_identity(self): - for u in sample_normals(0xF65, 20): - m = u2d(run_mant("v_frexp_mant_f64_e32 v[0:1], v[2:3]", u)) - e = run_exp("v_frexp_exp_i32_f64_e32 v0, v[2:3]", u) - e = e - (1 << 32) if e & 0x80000000 else e - self.assertEqual(d2u(math.ldexp(m, e)), u) - self.assertTrue(0.5 <= abs(m) < 1.0) - - def test_zero_subnormals_and_specials(self): - for u in (0x0000000000000000, 0x8000000000000000): - with self.subTest(zero=hex(u)): - self.assertEqual(run_mant("v_frexp_mant_f64_e32 v[0:1], v[2:3]", u), u) - self.assertEqual(run_exp("v_frexp_exp_i32_f64_e32 v0, v[2:3]", u), 0) - for u in (INF, NINF, QNAN, NQNAN, SNAN): - with self.subTest(special=hex(u)): - self.assertEqual(run_mant("v_frexp_mant_f64_e32 v[0:1], v[2:3]", u), u) - self.assertEqual(run_exp("v_frexp_exp_i32_f64_e32 v0, v[2:3]", u), 0) - - def test_subnormals_match_gfx1036(self): - # All 52 single-bit subnormal positions plus multi-bit patterns crossing bits 19/20/21/31/32/51. - # Every case verified natively on gfx1036 (wave32 and wave64 identical, default denorm16_64=3). - subnormals = [1 << b for b in range(52)] + [ - 0x00000000FFFFFFFF, - 0x000FFFFF00000000, - MAX_SUBNORMAL, - 0x0000000180000001, - 0x0000000000180005, - 0x0000000080000001, - 0x0000000100000001, - 0x0008000000000001, - SUBNORMAL | (1 << 63), - MAX_SUBNORMAL | (1 << 63), - 0x8000000180000001, - ] - for u in subnormals: - with self.subTest(sub=hex(u)): - got_m = run_mant("v_frexp_mant_f64_e32 v[0:1], v[2:3]", u) - got_e = run_exp("v_frexp_exp_i32_f64_e32 v0, v[2:3]", u) - self.assertEqual(got_m, ref_mant(u)) - self.assertEqual(got_e, ref_exp(u)) - e_signed = got_e - (1 << 32) if got_e & 0x80000000 else got_e - self.assertEqual(d2u(math.ldexp(u2d(got_m), e_signed)), u) - self.assertTrue(0.5 <= abs(u2d(got_m)) < 1.0) - # VOP3 abs/neg on subnormals. - self.assertEqual( - run_mant("v_frexp_mant_f64_e64 v[0:1], |v[2:3]|", SUBNORMAL | (1 << 63)), - 0x3FE0000000000000, - ) - self.assertEqual( - run_mant("v_frexp_mant_f64_e64 v[0:1], -v[2:3]", SUBNORMAL), - 0xBFE0000000000000, - ) - self.assertEqual( - run_exp("v_frexp_exp_i32_f64_e64 v0, |v[2:3]|", SUBNORMAL | (1 << 63)), - (-1073) & 0xFFFFFFFF, - ) - - def test_source_modifiers_sgpr_inline_and_aliasing(self): - x = d2u(3.0) - nx = d2u(-3.0) - self.assertEqual(run_mant("v_frexp_mant_f64_e64 v[0:1], |v[2:3]|", nx), d2u(0.75)) - self.assertEqual(run_mant("v_frexp_mant_f64_e64 v[0:1], -v[2:3]", x), d2u(-0.75)) - self.assertEqual(run_mant("v_frexp_mant_f64_e64 v[0:1], -|v[2:3]|", nx), d2u(-0.75)) - self.assertEqual(run_exp("v_frexp_exp_i32_f64_e64 v0, -|v[2:3]|", nx), 2) - - # SGPR pair source - spv_sgpr = translate_lines([ - f"s_mov_b32 s4, {x & 0xFFFFFFFF:#x}", - f"s_mov_b32 s5, {(x >> 32) & 0xFFFFFFFF:#x}", - "v_frexp_mant_f64_e32 v[0:1], s[4:5]", - "v_frexp_exp_i32_f64_e32 v2, s[4:5]", - ]) - out = si.run_fragment(spv_sgpr)["%out_mrt0"] - self.assertEqual((out[1] << 32) | out[0], d2u(0.75)) - self.assertEqual(out[2], 2) - - # Inline float constant and integer 0 - spv_imm = translate_lines([ - "v_frexp_mant_f64_e32 v[0:1], -4.0", - "v_frexp_exp_i32_f64_e32 v2, -4.0", - "v_frexp_exp_i32_f64_e32 v3, 0", - ]) - out_imm = si.run_fragment(spv_imm)["%out_mrt0"] - self.assertEqual((out_imm[1] << 32) | out_imm[0], d2u(-0.5)) - self.assertEqual(out_imm[2], 3) - self.assertEqual(out_imm[3], 0) - - # Destination aliasing source (partial overlap v[1:2] <- v[0:1]) - spv_alias = translate_lines([ - f"v_mov_b32 v0, {x & 0xFFFFFFFF:#x}", - f"v_mov_b32 v1, {(x >> 32) & 0xFFFFFFFF:#x}", - "v_frexp_mant_f64_e32 v[1:2], v[0:1]", - ]) - out_alias = si.run_fragment(spv_alias)["%out_mrt0"] - self.assertEqual((out_alias[2] << 32) | out_alias[1], d2u(0.75)) - - def test_plain_needs_no_float64_and_validates(self): - spv = translate_lines([ - "v_mov_b32 v2, 0", - "v_mov_b32 v3, 0x40080000", - "v_frexp_mant_f64_e32 v[0:1], v[2:3]", - "v_frexp_exp_i32_f64_e32 v2, v[2:3]", - ]) - self.assertNotIn("OpCapability Float64", spv) - validate_spirv(spv) - - def test_mant_output_modifiers_and_validation(self): - # Measured on gfx1036 through tools/hw_oracle (wave32 and wave64 identical, tools/f64_omod_probe.py): - # a binary64 result ignores mul:2/mul:4/div:2 while denorm_mode_16_64 = 3, the MODE the translator - # assumes, so those forms keep the integer-only lowering. clamp applies in every MODE. See - # docs/design.md, "v_frexp_mant_f64, v_frexp_exp_i32_f64". - for mods, clamp_requested in ( - ("mul:2", False), - ("mul:4", False), - ("div:2", False), - ("clamp", True), - ("clamp div:2", True), - ): - with self.subTest(mods=mods): - spv = translate_lines([ - "v_mov_b32 v2, 0", - "v_mov_b32 v3, 0x40080000", - f"v_frexp_mant_f64_e64 v[0:1], v[2:3] {mods}", - ]) - self.assertNotRegex(spv, r"OpFMul %double") - if clamp_requested: - self.assertIn("OpCapability Float64", spv) - self.assertIn("FClamp", spv) - else: - self.assertNotIn("OpCapability Float64", spv) - self.assertNotIn("FClamp", spv) - validate_spirv(spv) - - for mods in ("mul:2", "mul:4", "div:2", "mul:2 div:2"): - with self.subTest(ignored=mods): - # 3.0 has mantissa 0.75; the scaling would make it 1.5, 3.0 or 0.375. - self.assertEqual(run_mant(f"v_frexp_mant_f64_e64 v[0:1], v[2:3] {mods}", d2u(3.0)), d2u(0.75)) - self.assertEqual(run_mant(f"v_frexp_mant_f64_e64 v[0:1], v[2:3] {mods}", d2u(-1.75)), d2u(-0.875)) - - def test_rejects_invalid_forms(self): - with self.assertRaises(rdna2spirv.Unsupported): - translate_lines(["v_frexp_exp_i32_f64_e64 v0, v[2:3] clamp"]) - with self.assertRaises(rdna2spirv.Unsupported): - translate_lines(["v_frexp_exp_i32_f64_e64 v0, v[2:3] mul:2"]) - with self.assertRaises(rdna2spirv.Unsupported): - translate_lines(["v_frexp_mant_f64_e32 v0, v[2:3]"]) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_alu_frexp_ldexp.py b/tests/semantic/test_alu_frexp_ldexp.py deleted file mode 100644 index 226459728..000000000 --- a/tests/semantic/test_alu_frexp_ldexp.py +++ /dev/null @@ -1,209 +0,0 @@ -"""Semantic interpreter tests for RDNA2 v_frexp_mant_f32, v_frexp_exp_i32_f32 and v_ldexp_f32 (SHADER-89). - -v_frexp_mant_f32 returns the mantissa of S0 in [0.5, 1) with its sign, v_frexp_exp_i32_f32 the matching exponent -(S0 = mant * 2^exp), and v_ldexp_f32 computes S0 * 2^S1 with S1 a signed integer (RDNA2 ISA). Zero gives a signed zero -mantissa and exponent 0; infinities and NaNs pass through the mantissa and ldexp, and give exponent 0. Each case -translates a synthetic pixel shader with tools/rdna2spirv.py, runs it in tests/semantic/spirv_mini_interp.py and -compares the exported word with a plain-Python reference (math.frexp / math.ldexp on the double value of the input). - -Not covered because the translator does not model them (docs/design.md): f32 denormal inputs and denormal results. -ldexp results below the smallest normal are expected to be signed zero here, which is what the translator -produces; this was not measured on hardware. -""" -import math -import os -import random -import struct -import sys -import tempfile -import unittest -import warnings - -HERE = os.path.dirname(os.path.abspath(__file__)) -ROOT = os.path.dirname(os.path.dirname(HERE)) -TOOLS_DIR = os.environ.get("LEONIDA_TOOLS_DIR") or os.path.join(ROOT, "tools") - -sys.dont_write_bytecode = True -sys.path.insert(0, TOOLS_DIR) -sys.path.insert(0, HERE) - -import rdna2spirv # noqa: E402 -import spirv_mini_interp as si # noqa: E402 - -STUB_DXBC = b"DXBC" + bytes(24) + struct.pack(" int: - return struct.unpack(" float: - return struct.unpack(" bool: - return 0 < ((u >> 23) & 0xFF) < 255 - - -_TMP_DIR = None -_SRC_PATH = None - - -def setUpModule(): - global _TMP_DIR, _SRC_PATH - _TMP_DIR = tempfile.TemporaryDirectory() - disasm_dir = os.path.join(_TMP_DIR.name, "disasm") - os.mkdir(disasm_dir) - _SRC_PATH = os.path.join(disasm_dir, "ps_frexp_ldexp.s") - with open(os.path.join(_TMP_DIR.name, "ps_frexp_ldexp.dxbc"), "wb") as f: - f.write(STUB_DXBC) - - -def tearDownModule(): - global _TMP_DIR - if _TMP_DIR is not None: - _TMP_DIR.cleanup() - _TMP_DIR = None - - -def run(line: str, v1: int, v2: int = 0) -> int: - """Seed v1 and v2, clear v0, run ``line``, return v0.""" - if _TMP_DIR is None: - setUpModule() - lines = [f"v_mov_b32 v1, {v1 & 0xFFFFFFFF:#x}", f"v_mov_b32 v2, {v2 & 0xFFFFFFFF:#x}", "v_mov_b32 v0, 0", line] - asm = "; test_frexp_ldexp\n" + "".join(f"\t{ln}\n" for ln in lines) + "\texp mrt0 v0, v0, v0, v0 done vm\n\ts_endpgm\n" - with open(_SRC_PATH, "w", encoding="utf-8") as f: - f.write(asm) - with warnings.catch_warnings(): - warnings.simplefilter("ignore", ResourceWarning) - spv = rdna2spirv.translate(_SRC_PATH) - return si.run_fragment(spv)["%out_mrt0"][0] - - -def ref_mant(u: int) -> int: - if not is_normal(u): - return (u & 0x80000000) if (u >> 23) & 0xFF == 0 else u - return f2u(math.frexp(u2f(u))[0]) - - -def ref_exp(u: int) -> int: - return math.frexp(u2f(u))[1] & 0xFFFFFFFF if is_normal(u) else 0 - - -def ref_ldexp(u: int, n: int) -> int: - e = (u >> 23) & 0xFF - sgn = u & 0x80000000 - if e == 255: - return u - if e == 0: - return sgn - n &= 0xFFFFFFFF - n = n - (1 << 32) if n & 0x80000000 else n - n = max(-512, min(512, n)) - e2 = e + n - if e2 >= 255: - return sgn | INF - if e2 <= 0: - return sgn - return f2u(math.ldexp(u2f(u), n)) - - -def sample_normals(seed: int, count: int): - rng = random.Random(seed) - out = [f2u(1.0), f2u(-1.0), f2u(0.5), f2u(0.75), f2u(8.0), f2u(-0.1), f2u(3.14159), MIN_NORMAL, MAX_FINITE, - MAX_FINITE | 0x80000000, MIN_NORMAL | 0x80000000] - while len(out) < count: - u = rng.getrandbits(32) - if is_normal(u): - out.append(u) - return out - - -class FrexpTests(unittest.TestCase): - def test_reference(self): - self.assertEqual(ref_mant(f2u(8.0)), f2u(0.5)) - self.assertEqual(ref_exp(f2u(8.0)), 4) - self.assertEqual(ref_exp(f2u(0.75)), 0) - self.assertEqual(ref_exp(f2u(-0.1)), (-3) & 0xFFFFFFFF) - - def test_known_values(self): - for x, m, e in ((1.0, 0.5, 1), (-1.0, -0.5, 1), (0.5, 0.5, 0), (3.0, 0.75, 2), (-0.1875, -0.75, -2)): - with self.subTest(x=x): - self.assertEqual(run("v_frexp_mant_f32_e32 v0, v1", f2u(x)), f2u(m)) - self.assertEqual(run("v_frexp_exp_i32_f32_e32 v0, v1", f2u(x)), e & 0xFFFFFFFF) - - def test_matches_python_on_normals(self): - for u in sample_normals(0x89, 60): - with self.subTest(x=hex(u)): - self.assertEqual(run("v_frexp_mant_f32_e32 v0, v1", u), ref_mant(u)) - self.assertEqual(run("v_frexp_exp_i32_f32_e32 v0, v1", u), ref_exp(u)) - - def test_mantissa_times_two_to_the_exponent_is_the_input(self): - for u in sample_normals(0x90, 20): - m, e = u2f(run("v_frexp_mant_f32_e32 v0, v1", u)), run("v_frexp_exp_i32_f32_e32 v0, v1", u) - e = e - (1 << 32) if e & 0x80000000 else e - self.assertEqual(f2u(math.ldexp(m, e)), u) - self.assertTrue(0.5 <= abs(m) < 1.0) - - def test_zero_and_specials(self): - for u in (0x00000000, 0x80000000): - self.assertEqual(run("v_frexp_mant_f32_e32 v0, v1", u), u) # signed zero - self.assertEqual(run("v_frexp_exp_i32_f32_e32 v0, v1", u), 0) - for u in (INF, NINF, QNAN, QNAN | 0x80000000): - self.assertEqual(run("v_frexp_mant_f32_e32 v0, v1", u), u) # passed through - self.assertEqual(run("v_frexp_exp_i32_f32_e32 v0, v1", u), 0) - - def test_source_modifiers_and_output_modifiers(self): - one = f2u(1.0) - self.assertEqual(run("v_frexp_mant_f32_e64 v0, -v1", one), f2u(-0.5)) - self.assertEqual(run("v_frexp_mant_f32_e64 v0, |v1|", f2u(-1.0)), f2u(0.5)) - self.assertEqual(run("v_frexp_mant_f32_e64 v0, v1 mul:2", one), f2u(1.0)) - self.assertEqual(run("v_frexp_mant_f32_e64 v0, v1 mul:4 clamp", one), f2u(1.0)) - self.assertEqual(run("v_frexp_exp_i32_f32_e64 v0, -v1", f2u(8.0)), 4) - - -class LdexpTests(unittest.TestCase): - def test_known_values(self): - for x, n, want in ((1.0, 3, 8.0), (1.0, -1, 0.5), (-3.0, 2, -12.0), (0.75, 0, 0.75), (6.0, -2, 1.5)): - with self.subTest(x=x, n=n): - self.assertEqual(run("v_ldexp_f32_e64 v0, v1, v2", f2u(x), n), f2u(want)) - - def test_matches_python_on_normals(self): - rng = random.Random(0x91) - for u in sample_normals(0x92, 40): - for n in (rng.randrange(-40, 40), rng.randrange(-300, 300)): - with self.subTest(x=hex(u), n=n): - self.assertEqual(run("v_ldexp_f32_e64 v0, v1, v2", u, n), ref_ldexp(u, n)) - - def test_overflow_and_underflow_saturate(self): - self.assertEqual(run("v_ldexp_f32_e64 v0, v1, v2", f2u(1.0), 127), f2u(2.0 ** 127)) - self.assertEqual(run("v_ldexp_f32_e64 v0, v1, v2", f2u(1.0), 128), INF) - self.assertEqual(run("v_ldexp_f32_e64 v0, v1, v2", f2u(-1.0), 128), NINF) - self.assertEqual(run("v_ldexp_f32_e64 v0, v1, v2", f2u(1.0), 0x7FFFFFFF), INF) - self.assertEqual(run("v_ldexp_f32_e64 v0, v1, v2", f2u(1.0), -126), MIN_NORMAL) - self.assertEqual(run("v_ldexp_f32_e64 v0, v1, v2", f2u(1.0), -127), 0) - self.assertEqual(run("v_ldexp_f32_e64 v0, v1, v2", f2u(-1.0), -127), 0x80000000) - self.assertEqual(run("v_ldexp_f32_e64 v0, v1, v2", f2u(-1.0), 0x80000000), 0x80000000) # INT_MIN - self.assertEqual(run("v_ldexp_f32_e64 v0, v1, v2", MAX_FINITE, 1), INF) - self.assertEqual(run("v_ldexp_f32_e64 v0, v1, v2", MIN_NORMAL, -1), 0) - - def test_zero_and_specials_ignore_the_exponent(self): - for u in (0x00000000, 0x80000000): - for n in (0, 5, -5, 0x7FFFFFFF, 0x80000000): - self.assertEqual(run("v_ldexp_f32_e64 v0, v1, v2", u, n), u) - for u in (INF, NINF, QNAN): - for n in (0, 5, -200, 0x7FFFFFFF): - self.assertEqual(run("v_ldexp_f32_e64 v0, v1, v2", u, n), u) - - def test_source_and_output_modifiers(self): - self.assertEqual(run("v_ldexp_f32_e64 v0, -v1, v2", f2u(1.0), 1), f2u(-2.0)) - self.assertEqual(run("v_ldexp_f32_e64 v0, |v1|, v2", f2u(-1.0), 1), f2u(2.0)) - self.assertEqual(run("v_ldexp_f32_e64 v0, v1, v2 mul:2", f2u(1.0), 1), f2u(4.0)) - self.assertEqual(run("v_ldexp_f32_e64 v0, v1, v2 clamp", f2u(1.0), 3), f2u(1.0)) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_alu_frexp_ldexp_f16.py b/tests/semantic/test_alu_frexp_ldexp_f16.py deleted file mode 100644 index 37f10a413..000000000 --- a/tests/semantic/test_alu_frexp_ldexp_f16.py +++ /dev/null @@ -1,364 +0,0 @@ -"""Semantic interpreter tests for RDNA2 v_frexp_mant_f16, v_frexp_exp_i16_f16 and v_ldexp_f16. - -The binary16 versions of the f32 ops covered by test_alu_frexp_ldexp.py: v_frexp_mant_f16 returns the mantissa of S0 in -[0.5, 1) with its sign, v_frexp_exp_i16_f16 the matching exponent (S0 = mant * 2^exp, as a 16-bit integer) and -v_ldexp_f16 computes S0 * 2^S1 with S1 a signed 16-bit integer (RDNA2 ISA). Zero gives a signed zero mantissa and -exponent 0; infinities and NaNs pass through the mantissa and ldexp, and give exponent 0. op_sel picks the high half of -a source and the last bit sends the result to the high half of the destination; the other half of the destination is -kept. Each case translates a synthetic pixel shader with tools/rdna2spirv.py, runs it in -tests/semantic/spirv_mini_interp.py and compares the exported word with a plain-Python reference (math.frexp / -math.ldexp on the double value of the half; struct's binary16 packing rounds to nearest even). - -f16 denormals are kept, as in the MODE inferred for the game (denorm_mode_16_64 = 3): a denormal operand is normalized -(mantissa in [0.5, 1), exponent down to -23) and an ldexp result below the smallest normal is a denormal rounded to -nearest even. That is what an RDNA2 GPU (gfx1036) gives natively in that mode, for every one of the 65,536 f16 inputs -of both frexp ops and for all of them under 16 exponents of v_ldexp_f16 (docs/design.md); the MEASURED cases below -are words read back from it. The high half of v_frexp_exp_i16_f16's destination is kept on the hardware too. -""" -import math -import os -import random -import struct -import sys -import tempfile -import unittest -import warnings - -HERE = os.path.dirname(os.path.abspath(__file__)) -ROOT = os.path.dirname(os.path.dirname(HERE)) -TOOLS_DIR = os.environ.get("LEONIDA_TOOLS_DIR") or os.path.join(ROOT, "tools") - -sys.dont_write_bytecode = True -sys.path.insert(0, TOOLS_DIR) -sys.path.insert(0, HERE) - -import rdna2spirv # noqa: E402 -import spirv_mini_interp as si # noqa: E402 - -STUB_DXBC = b"DXBC" + bytes(24) + struct.pack(" float: - return struct.unpack(" int: - return struct.unpack(" bool: - return 0 < ((h >> 10) & 0x1F) < 31 - - -_TMP_DIR = None -_SRC_PATH = None - - -def setUpModule(): - global _TMP_DIR, _SRC_PATH - _TMP_DIR = tempfile.TemporaryDirectory() - disasm_dir = os.path.join(_TMP_DIR.name, "disasm") - os.mkdir(disasm_dir) - _SRC_PATH = os.path.join(disasm_dir, "ps_frexp_ldexp_f16.s") - with open(os.path.join(_TMP_DIR.name, "ps_frexp_ldexp_f16.dxbc"), "wb") as f: - f.write(STUB_DXBC) - - -def tearDownModule(): - global _TMP_DIR - if _TMP_DIR is not None: - _TMP_DIR.cleanup() - _TMP_DIR = None - - -def run(line: str, v1: int, v2: int = 0, v0: int = 0) -> int: - """Seed v0, v1 and v2, run ``line``, return v0 (the whole 32-bit register).""" - if _TMP_DIR is None: - setUpModule() - lines = [f"v_mov_b32 v1, {v1 & 0xFFFFFFFF:#x}", f"v_mov_b32 v2, {v2 & 0xFFFFFFFF:#x}", - f"v_mov_b32 v0, {v0 & 0xFFFFFFFF:#x}", line] - asm = "; test_frexp_ldexp_f16\n" + "".join(f"\t{ln}\n" for ln in lines) + "\texp mrt0 v0, v0, v0, v0 done vm\n\ts_endpgm\n" - with open(_SRC_PATH, "w", encoding="utf-8", newline="\n") as f: - f.write(asm) - with warnings.catch_warnings(): - warnings.simplefilter("ignore", ResourceWarning) - spv = rdna2spirv.translate(_SRC_PATH) - return si.run_fragment(spv)["%out_mrt0"][0] - - -def is_finite_nonzero(h: int) -> bool: - return (h >> 10) & 0x1F != 31 and h & 0x7FFF != 0 - - -def ref_mant(h: int) -> int: - if not is_finite_nonzero(h): - return h # signed zero, infinity, NaN - return f2h(math.frexp(h2f(h))[0]) - - -def ref_exp(h: int) -> int: - return math.frexp(h2f(h))[1] & 0xFFFF if is_finite_nonzero(h) else 0 - - -def ref_ldexp(h: int, n: int) -> int: - if not is_finite_nonzero(h): - return h - n &= 0xFFFF - n = n - (1 << 16) if n & 0x8000 else n - try: - return f2h(math.ldexp(h2f(h), max(-64, min(64, n)))) # exact, then rounded to nearest even - except OverflowError: - return (h & 0x8000) | INF - - -# Read back from gfx1036 (RDNA2), IEEE 0, f16 denormals kept: (input, mantissa, exponent) and (input, n, ldexp). -MEASURED_FREXP = ((0x0001, 0x3800, 0xFFE9), (0x8001, 0xB800, 0xFFE9), (0x0003, 0x3A00, 0xFFEA), - (0x0200, 0x3800, 0xFFF2), (0x03FF, 0x3BFE, 0xFFF2), (0x83FF, 0xBBFE, 0xFFF2), - (0x0400, 0x3800, 0xFFF3), (0x0010, 0x3800, 0xFFED)) -MEASURED_LDEXP = ((0x3C00, -23, 0x0002), (0x3C00, -15, 0x0200), (0x3C00, -24, 0x0001), (0x3E00, -23, 0x0003), - (0x3E00, -15, 0x0300), (0x3E00, -24, 0x0002), (0x0001, 1, 0x0002), (0x0200, 1, 0x0400), - (0x8001, 10, 0x8400), (0x0001, 30, 0x5400), (0x0400, -1, 0x0200), (0x0400, -10, 0x0001), - (0x0400, -25, 0x0000), (0x7BFF, -24, 0x1BFF), (0x7BFF, -30, 0x0400), (0x3C00, -25, 0x0000)) - - -def sample_normals(seed: int, count: int): - rng = random.Random(seed) - out = [f2h(1.0), f2h(-1.0), f2h(0.5), f2h(0.75), f2h(8.0), f2h(-0.1), f2h(3.14159), MIN_NORMAL, MAX_FINITE, - MAX_FINITE | 0x8000, MIN_NORMAL | 0x8000] - out += [(ex << 10) | rng.getrandbits(10) for ex in (1, 2, 14, 15, 16, 29, 30)] # every end of the exponent range - while len(out) < count: - h = rng.getrandbits(16) - if is_normal(h): - out.append(h) - return out - - -class FrexpTests(unittest.TestCase): - def test_reference(self): - self.assertEqual(ref_mant(f2h(8.0)), f2h(0.5)) - self.assertEqual(ref_exp(f2h(8.0)), 4) - self.assertEqual(ref_exp(f2h(0.75)), 0) - self.assertEqual(ref_exp(f2h(-0.1)), (-3) & 0xFFFF) - self.assertEqual(ref_exp(MAX_FINITE), 16) - self.assertEqual(ref_exp(MIN_NORMAL), (-13) & 0xFFFF) - - def test_known_values(self): - for x, m, e in ((1.0, 0.5, 1), (-1.0, -0.5, 1), (0.5, 0.5, 0), (3.0, 0.75, 2), (-0.1875, -0.75, -2)): - with self.subTest(x=x): - self.assertEqual(run("v_frexp_mant_f16_e32 v0, v1", f2h(x)), f2h(m)) - self.assertEqual(run("v_frexp_exp_i16_f16_e32 v0, v1", f2h(x)), e & 0xFFFF) - - def test_matches_python_on_normals(self): - for h in sample_normals(0x89, 60): - with self.subTest(x=hex(h)): - self.assertEqual(run("v_frexp_mant_f16_e32 v0, v1", h), ref_mant(h)) - self.assertEqual(run("v_frexp_exp_i16_f16_e32 v0, v1", h), ref_exp(h)) - - def test_mantissa_times_two_to_the_exponent_is_the_input(self): - for h in sample_normals(0x90, 20): - m, e = h2f(run("v_frexp_mant_f16_e32 v0, v1", h)), run("v_frexp_exp_i16_f16_e32 v0, v1", h) - e = e - (1 << 16) if e & 0x8000 else e - self.assertEqual(f2h(math.ldexp(m, e)), h) - self.assertTrue(0.5 <= abs(m) < 1.0) - - def test_zero_and_specials(self): - for h in (0x0000, 0x8000): - self.assertEqual(run("v_frexp_mant_f16_e32 v0, v1", h), h) # signed zero - self.assertEqual(run("v_frexp_exp_i16_f16_e32 v0, v1", h), 0) - for h in (INF, NINF, QNAN, QNAN | 0x8000): - self.assertEqual(run("v_frexp_mant_f16_e32 v0, v1", h), h) # passed through - self.assertEqual(run("v_frexp_exp_i16_f16_e32 v0, v1", h), 0) - - def test_denormal_is_normalized_as_measured(self): - for h, mant, exp in MEASURED_FREXP: - with self.subTest(x=hex(h)): - self.assertEqual(run("v_frexp_mant_f16_e32 v0, v1", h), mant) - self.assertEqual(run("v_frexp_exp_i16_f16_e32 v0, v1", h), exp) - self.assertEqual((ref_mant(h), ref_exp(h)), (mant, exp)) - - def test_matches_python_on_denormals(self): - for h in list(range(1, 0x400, 37)) + [0x8000 | h for h in range(3, 0x400, 101)]: - with self.subTest(x=hex(h)): - self.assertEqual(run("v_frexp_mant_f16_e32 v0, v1", h), ref_mant(h)) - self.assertEqual(run("v_frexp_exp_i16_f16_e32 v0, v1", h), ref_exp(h)) - - def test_high_half_of_the_source_is_ignored_and_the_destination_high_half_kept(self): - h = f2h(8.0) - self.assertEqual(run("v_frexp_mant_f16_e32 v0, v1", 0xABCD0000 | h, v0=0x12345678), 0x12340000 | f2h(0.5)) - self.assertEqual(run("v_frexp_exp_i16_f16_e32 v0, v1", 0xABCD0000 | h, v0=0x12345678), 0x12340000 | 4) - - def test_op_sel(self): - lo, hi = f2h(8.0), f2h(-0.1875) - v1 = (hi << 16) | lo - self.assertEqual(run("v_frexp_mant_f16_e64 v0, v1 op_sel:[1,0]", v1) & 0xFFFF, f2h(-0.75)) - self.assertEqual(run("v_frexp_exp_i16_f16_e64 v0, v1 op_sel:[1,0]", v1) & 0xFFFF, (-2) & 0xFFFF) - # destination bit: the result goes to the high half and the low half is kept - self.assertEqual(run("v_frexp_mant_f16_e64 v0, v1 op_sel:[0,1]", v1, v0=0x1111_2222), (f2h(0.5) << 16) | 0x2222) - self.assertEqual(run("v_frexp_exp_i16_f16_e64 v0, v1 op_sel:[1,1]", v1, v0=0x1111_2222), (((-2) & 0xFFFF) << 16) | 0x2222) - - def test_source_modifiers_and_inline_constants(self): - one = f2h(1.0) - self.assertEqual(run("v_frexp_mant_f16_e64 v0, -v1", one), f2h(-0.5)) - self.assertEqual(run("v_frexp_mant_f16_e64 v0, |v1|", f2h(-1.0)), f2h(0.5)) - self.assertEqual(run("v_frexp_exp_i16_f16_e64 v0, -v1", f2h(8.0)), 4) - self.assertEqual(run("v_frexp_mant_f16_e32 v0, 8.0", 0), f2h(0.5)) - self.assertEqual(run("v_frexp_exp_i16_f16_e32 v0, 8.0", 0), 4) - - def test_clamp(self): - cases = [ - (f2h(1.0), f2h(0.5)), # +1.0 -> mant 0.5 (in range, kept) - (f2h(-1.0), 0), # -1.0 -> mant -0.5 -> clamped to +0.0 - (0x8000, 0), # -0.0 -> clamped to +0.0 - (f2h(1.5), f2h(0.75)), # +1.5 -> mant 0.75 (in range, kept) - (0x0001, f2h(0.5)), # +min_sub -> normalized mant 0.5 (kept) - (0x8001, 0), # -min_sub -> clamped to +0.0 - (0x7C00, f2h(1.0)), # +Inf -> clamped to 1.0 (0x3c00) - (0xFC00, 0), # -Inf -> clamped to +0.0 - (0x7E00, 0), # +qNaN -> clamped to +0.0 - (0x7C01, 0), # +sNaN -> clamped to +0.0 - ] - for val, want in cases: - with self.subTest(val=hex(val)): - self.assertEqual(run("v_frexp_mant_f16_e64 v0, v1 clamp", val), want) - # Dirty upper-16-bit source VGPR values must not leak into clamp or destination high half - self.assertEqual(run("v_frexp_mant_f16_e64 v0, v1 clamp", 0xDEAD0000, v0=0xBEEF1234), 0xBEEF0000) - self.assertEqual(run("v_frexp_mant_f16_e64 v0, v1 clamp", 0xDEAD0000 | f2h(0.5), v0=0xBEEF1234), 0xBEEF0000 | f2h(0.5)) - - def test_output_modifiers(self): - # Under console MODE (denorm_mode_16_64 = 3), mul:2/mul:4/div:2 are hardware no-ops on frexp_mant_f16, - # clamp still saturates to [0.0, 1.0], and frexp_exp_i16_f16 ignores both clamp and omod. - for mod in ("mul:2", "mul:4", "div:2"): - with self.subTest(op="v_frexp_mant_f16", mod=mod): - self.assertEqual(run(f"v_frexp_mant_f16_e64 v0, v1 {mod}", f2h(1.0), v0=0xBEEF1234), 0xBEEF0000 | f2h(0.5)) - self.assertEqual(run(f"v_frexp_mant_f16_e64 v0, v1 clamp {mod}", f2h(-1.0), v0=0xBEEF1234), 0xBEEF0000) - self.assertEqual(run(f"v_frexp_mant_f16_e64 v0, v1 clamp {mod}", 0x7C00, v0=0xBEEF1234), 0xBEEF3C00) - for mod in ("clamp", "mul:2", "mul:4", "div:2", "clamp mul:2", "clamp mul:4", "clamp div:2"): - with self.subTest(op="v_frexp_exp_i16_f16", mod=mod): - self.assertEqual(run(f"v_frexp_exp_i16_f16_e64 v0, v1 {mod}", f2h(8.0), v0=0xBEEF1234), 0xBEEF0004) - for line in ("v_frexp_mant_f16_e64 v0, v1 mul:8", "v_frexp_mant_f16_e64 v0, v1 op_sel_hi:[1,0]", - "v_frexp_exp_i16_f16_e64 v0, v1 div:4", "v_frexp_exp_i16_f16_e64 v0, v1 neg_lo:[1]"): - with self.subTest(rejected=line), self.assertRaises(rdna2spirv.Unsupported): - run(line, f2h(1.0)) - - -class LdexpTests(unittest.TestCase): - def test_known_values(self): - for x, n, want in ((1.0, 3, 8.0), (1.0, -1, 0.5), (-3.0, 2, -12.0), (0.75, 0, 0.75), (6.0, -2, 1.5)): - with self.subTest(x=x, n=n): - self.assertEqual(run("v_ldexp_f16_e64 v0, v1, v2", f2h(x), n), f2h(want)) - - def test_matches_python_on_normals(self): - rng = random.Random(0x91) - for h in sample_normals(0x92, 40): - for n in (rng.randrange(-20, 20), rng.randrange(-300, 300)): - with self.subTest(x=hex(h), n=n): - self.assertEqual(run("v_ldexp_f16_e64 v0, v1, v2", h, n), ref_ldexp(h, n)) - - def test_every_exponent_step_at_the_edges(self): - for n in range(-32, 33): - for h in (f2h(1.0), f2h(-1.0), MIN_NORMAL, MAX_FINITE, MAX_FINITE | 0x8000): - with self.subTest(x=hex(h), n=n): - self.assertEqual(run("v_ldexp_f16_e64 v0, v1, v2", h, n), ref_ldexp(h, n)) - - def test_overflow_and_underflow_saturate(self): - L = "v_ldexp_f16_e64 v0, v1, v2" - self.assertEqual(run(L, f2h(1.0), 15), f2h(2.0 ** 15)) - self.assertEqual(run(L, f2h(1.0), 16), INF) - self.assertEqual(run(L, f2h(-1.0), 16), NINF) - self.assertEqual(run(L, f2h(1.0), 0x7FFF), INF) - self.assertEqual(run(L, f2h(1.0), -14), MIN_NORMAL) - self.assertEqual(run(L, f2h(1.0), -15), 0x0200) # a denormal, not zero - self.assertEqual(run(L, f2h(-1.0), -15), 0x8200) - self.assertEqual(run(L, f2h(1.0), -25), 0) # half the smallest denormal: ties to even 0 - self.assertEqual(run(L, f2h(-1.0), 0x8000), 0x8000) # INT16_MIN - self.assertEqual(run(L, MAX_FINITE, 1), INF) - self.assertEqual(run(L, MIN_NORMAL, -1), 0x0200) - - def test_the_exponent_is_a_signed_16_bit_integer(self): - L = "v_ldexp_f16_e64 v0, v1, v2" - # only the low 16 bits of S1 count: 0x00010003 is 3, 0xFFFF is -1 - self.assertEqual(run(L, f2h(1.0), 0x00010003), f2h(8.0)) - self.assertEqual(run(L, f2h(1.0), 0xFFFF), f2h(0.5)) - self.assertEqual(run(L, f2h(1.0), 0x8000), 0) - self.assertEqual(run(L, f2h(1.0), 0x7FFF), INF) - - def test_zero_and_specials_ignore_the_exponent(self): - for h in (0x0000, 0x8000): - for n in (0, 5, -5, 0x7FFF, 0x8000): - self.assertEqual(run("v_ldexp_f16_e64 v0, v1, v2", h, n), h) - for h in (INF, NINF, QNAN): - for n in (0, 5, -200, 0x7FFF): - self.assertEqual(run("v_ldexp_f16_e64 v0, v1, v2", h, n), h) - - def test_denormals_as_measured(self): - for h, n, want in MEASURED_LDEXP: - with self.subTest(x=hex(h), n=n): - self.assertEqual(run("v_ldexp_f16_e64 v0, v1, v2", h, n), want) - self.assertEqual(ref_ldexp(h, n), want) - - def test_denormal_inputs_and_results_match_python(self): - for h in (0x0001, 0x0003, 0x0155, 0x03FF, 0x8001, 0x82AB, f2h(1.5), f2h(-1.75), MAX_FINITE): - for n in (-30, -26, -25, -24, -20, -16, -14, 0, 3, 9, 10, 11, 24): - with self.subTest(x=hex(h), n=n): - self.assertEqual(run("v_ldexp_f16_e64 v0, v1, v2", h, n), ref_ldexp(h, n)) - - def test_op_sel(self): - L = "v_ldexp_f16_e64 v0, v1, v2" - v1 = (f2h(3.0) << 16) | f2h(1.0) - v2 = (2 << 16) | 1 # high half 2, low half 1 - self.assertEqual(run(L + " op_sel:[0,0,0]", v1, v2) & 0xFFFF, f2h(2.0)) # 1.0 * 2^1 - self.assertEqual(run(L + " op_sel:[1,0,0]", v1, v2) & 0xFFFF, f2h(6.0)) # 3.0 * 2^1 - self.assertEqual(run(L + " op_sel:[0,1,0]", v1, v2) & 0xFFFF, f2h(4.0)) # 1.0 * 2^2 - self.assertEqual(run(L + " op_sel:[1,1,0]", v1, v2) & 0xFFFF, f2h(12.0)) # 3.0 * 2^2 - # destination bit: the result goes to the high half and the low half is kept - self.assertEqual(run(L + " op_sel:[1,1,1]", v1, v2, v0=0x1111_2222), (f2h(12.0) << 16) | 0x2222) - self.assertEqual(run(L + " op_sel:[0,0,1]", v1, v2, v0=0x1111_2222), (f2h(2.0) << 16) | 0x2222) - - def test_destination_high_half_kept(self): - self.assertEqual(run("v_ldexp_f16_e64 v0, v1, v2", f2h(1.0), 3, v0=0x12345678), 0x12340000 | f2h(8.0)) - - def test_source_modifiers_and_inline_constants(self): - self.assertEqual(run("v_ldexp_f16_e64 v0, -v1, v2", f2h(1.0), 1), f2h(-2.0)) - self.assertEqual(run("v_ldexp_f16_e64 v0, |v1|, v2", f2h(-1.0), 1), f2h(2.0)) - self.assertEqual(run("v_ldexp_f16_e32 v0, 1.0, v2", 0, 3), f2h(8.0)) - self.assertEqual(run("v_ldexp_f16_e64 v0, v1, 5", f2h(1.0)), f2h(32.0)) - - def test_clamp(self): - cases = [ - (f2h(1.0), 1, f2h(1.0)), # 1.0 * 2 = 2.0 -> clamped to 1.0 - (f2h(1.0), -1, f2h(0.5)), # 1.0 * 0.5 = 0.5 -> in range, kept - (f2h(-1.0), 0, 0), # -1.0 -> clamped to +0.0 - (0x8000, 0, 0), # -0.0 -> clamped to +0.0 - (0x7C00, 0, f2h(1.0)), # +Inf -> clamped to 1.0 (0x3c00) - (0xFC00, 0, 0), # -Inf -> clamped to +0.0 - (0x7E00, 0, 0), # +qNaN -> clamped to +0.0 - (f2h(1.0), 16, f2h(1.0)), # overflow -> clamped to 1.0 - (0x0001, 0, 0x0001), # +min_sub -> in range, kept - ] - for s0, s1, want in cases: - with self.subTest(s0=hex(s0), s1=s1): - self.assertEqual(run("v_ldexp_f16_e64 v0, v1, v2 clamp", s0, s1), want) - # Dirty upper-16-bit source VGPR values must not leak into clamp or destination high half - self.assertEqual(run("v_ldexp_f16_e64 v0, v1, v2 clamp", 0xDEAD0000, 0, v0=0xBEEF1234), 0xBEEF0000) - self.assertEqual(run("v_ldexp_f16_e64 v0, v1, v2 clamp", 0xDEAD0000 | f2h(0.5), 0, v0=0xBEEF1234), 0xBEEF0000 | f2h(0.5)) - - def test_output_modifiers(self): - # Under console MODE (denorm_mode_16_64 = 3), mul:2/mul:4/div:2 are hardware no-ops on v_ldexp_f16, - # while clamp applies [0.0, 1.0] saturation alone or combined with mul:*/div:*. - for mod in ("mul:2", "mul:4", "div:2"): - with self.subTest(mod=mod): - self.assertEqual(run(f"v_ldexp_f16_e64 v0, v1, v2 {mod}", f2h(0.5), 1, v0=0xBEEF1234), 0xBEEF3C00) - self.assertEqual(run(f"v_ldexp_f16_e64 v0, v1, v2 {mod}", f2h(1.0), 1, v0=0xBEEF1234), 0xBEEF4000) - self.assertEqual(run(f"v_ldexp_f16_e64 v0, v1, v2 clamp {mod}", f2h(1.0), 1, v0=0xBEEF1234), 0xBEEF3C00) - self.assertEqual(run(f"v_ldexp_f16_e64 v0, v1, v2 clamp {mod}", f2h(-1.0), 1, v0=0xBEEF1234), 0xBEEF0000) - for line in ("v_ldexp_f16_e64 v0, v1, v2 mul:8", "v_ldexp_f16_e64 v0, v1, v2 div:4", - "v_ldexp_f16_e64 v0, v1, v2 neg_lo:[1,0]"): - with self.subTest(rejected=line), self.assertRaises(rdna2spirv.Unsupported): - run(line, f2h(1.0), 1) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_alu_int_min3_max3.py b/tests/semantic/test_alu_int_min3_max3.py deleted file mode 100644 index a09cabf99..000000000 --- a/tests/semantic/test_alu_int_min3_max3.py +++ /dev/null @@ -1,660 +0,0 @@ -from __future__ import annotations - -"""Semantic interpreter tests for RDNA2 3-way integer min/max instructions: -- v_min3_i32: signed two's complement 32-bit minimum: min(S0, S1, S2) -- v_min3_u32: unsigned 32-bit integer minimum: min(S0, S1, S2) -- v_max3_i32: signed two's complement 32-bit maximum: max(S0, S1, S2) -- v_max3_u32: unsigned 32-bit integer maximum: max(S0, S1, S2) - -Features reference models, pairwise reduction equivalence, signed vs unsigned -divergence on identical bit patterns, multi-lane SIMD wave execution under EXEC -mask gating, two's complement extrema boundaries, full permutation matrices, -negative controls, and shader execution via rdna2spirv and spirv_mini_interp. - -Zero game data, standard library Python only, Python 3.9+ compatible. -""" -import itertools -import os -import struct -import sys -import tempfile -import unittest -import warnings - -HERE = os.path.dirname(os.path.abspath(__file__)) -ROOT = os.path.dirname(os.path.dirname(HERE)) -TOOLS_DIR = os.environ.get("LEONIDA_TOOLS_DIR") or os.path.join(ROOT, "tools") - -sys.dont_write_bytecode = True -if TOOLS_DIR not in sys.path: - sys.path.insert(0, TOOLS_DIR) -if HERE not in sys.path: - sys.path.insert(0, HERE) - -import rdna2spirv # noqa: E402 -import spirv_mini_interp as si # noqa: E402 - -MASK32 = 0xFFFFFFFF -SIGN_BIT32 = 0x80000000 -INT32_MIN = -0x80000000 -INT32_MAX = 0x7FFFFFFF -UINT32_MAX = 0xFFFFFFFF - -STUB_DXBC = b"DXBC" + bytes(24) + struct.pack(" int: - """Interpret raw 32-bit unsigned pattern as two's complement signed 32-bit integer.""" - x &= MASK32 - return x - (1 << 32) if (x & SIGN_BIT32) else x - - -def to_unsigned_u32(x: int) -> int: - """Mask integer to 32-bit unsigned integer range [0, 2^32 - 1].""" - return x & MASK32 - - -def ref_v_min3_i32(s0: int, s1: int, s2: int) -> int: - """Reference implementation of v_min3_i32: signed minimum of 3 operands.""" - v0 = to_signed_i32(s0) - v1 = to_signed_i32(s1) - v2 = to_signed_i32(s2) - return min(v0, v1, v2) & MASK32 - - -def ref_v_min3_u32(s0: int, s1: int, s2: int) -> int: - """Reference implementation of v_min3_u32: unsigned minimum of 3 operands.""" - v0 = to_unsigned_u32(s0) - v1 = to_unsigned_u32(s1) - v2 = to_unsigned_u32(s2) - return min(v0, v1, v2) & MASK32 - - -def ref_v_max3_i32(s0: int, s1: int, s2: int) -> int: - """Reference implementation of v_max3_i32: signed maximum of 3 operands.""" - v0 = to_signed_i32(s0) - v1 = to_signed_i32(s1) - v2 = to_signed_i32(s2) - return max(v0, v1, v2) & MASK32 - - -def ref_v_max3_u32(s0: int, s1: int, s2: int) -> int: - """Reference implementation of v_max3_u32: unsigned maximum of 3 operands.""" - v0 = to_unsigned_u32(s0) - v1 = to_unsigned_u32(s1) - v2 = to_unsigned_u32(s2) - return max(v0, v1, v2) & MASK32 - - -def ref_pairwise_min3_i32(s0: int, s1: int, s2: int) -> int: - """Cascaded pairwise signed min: min(min(s0, s1), s2).""" - step1 = min(to_signed_i32(s0), to_signed_i32(s1)) - return min(step1, to_signed_i32(s2)) & MASK32 - - -def ref_pairwise_min3_u32(s0: int, s1: int, s2: int) -> int: - """Cascaded pairwise unsigned min: min(min(s0, s1), s2).""" - step1 = min(to_unsigned_u32(s0), to_unsigned_u32(s1)) - return min(step1, to_unsigned_u32(s2)) & MASK32 - - -def ref_pairwise_max3_i32(s0: int, s1: int, s2: int) -> int: - """Cascaded pairwise signed max: max(max(s0, s1), s2).""" - step1 = max(to_signed_i32(s0), to_signed_i32(s1)) - return max(step1, to_signed_i32(s2)) & MASK32 - - -def ref_pairwise_max3_u32(s0: int, s1: int, s2: int) -> int: - """Cascaded pairwise unsigned max: max(max(s0, s1), s2).""" - step1 = max(to_unsigned_u32(s0), to_unsigned_u32(s1)) - return max(step1, to_unsigned_u32(s2)) & MASK32 - - -# Backwards-compatible alias -s32 = to_signed_i32 - - -def ref(op: str, *xs: int) -> int: - """Plain-Python reference; operands and result are raw 32-bit patterns.""" - if len(xs) == 3: - if op == "v_min3_i32": - return ref_v_min3_i32(xs[0], xs[1], xs[2]) - if op == "v_min3_u32": - return ref_v_min3_u32(xs[0], xs[1], xs[2]) - if op == "v_max3_i32": - return ref_v_max3_i32(xs[0], xs[1], xs[2]) - if op == "v_max3_u32": - return ref_v_max3_u32(xs[0], xs[1], xs[2]) - key = to_signed_i32 if op.endswith("_i32") else to_unsigned_u32 - pick = min if op.startswith("v_min3") else max - return pick(xs, key=key) & MASK32 - - -class VectorALUInterpreter: - """Deterministic semantic interpreter for RDNA2 VALU 3-way integer min/max. - - Models: - - Vector General Purpose Registers (VGPRs) across wave lanes. - - Scalar General Purpose Registers (SGPRs) uniformly broadcast to all lanes. - - EXEC mask write gating (inactive lanes preserve prior VGPR contents). - - Inline constants and register operand decoding. - - Both Wave64 and Wave32 execution widths. - """ - - def __init__(self, num_vgprs: int = 64, num_sgprs: int = 106, wave_size: int = 64) -> None: - self.num_vgprs = num_vgprs - self.num_sgprs = num_sgprs - self.wave_size = wave_size - self.vgprs = [[0] * wave_size for _ in range(num_vgprs)] - self.sgprs = [0] * num_sgprs - self.exec_mask = (1 << wave_size) - 1 - - def reset(self) -> None: - self.vgprs = [[0] * self.wave_size for _ in range(self.num_vgprs)] - self.sgprs = [0] * self.num_sgprs - self.exec_mask = (1 << self.wave_size) - 1 - - def set_vgpr(self, reg_idx: int, lane: int, val: int) -> None: - if not (0 <= reg_idx < self.num_vgprs): - raise IndexError(f"VGPR index out of range: v{reg_idx}") - if not (0 <= lane < self.wave_size): - raise IndexError(f"Lane index out of range: {lane}") - self.vgprs[reg_idx][lane] = val & MASK32 - - def get_vgpr(self, reg_idx: int, lane: int) -> int: - if not (0 <= reg_idx < self.num_vgprs): - raise IndexError(f"VGPR index out of range: v{reg_idx}") - if not (0 <= lane < self.wave_size): - raise IndexError(f"Lane index out of range: {lane}") - return self.vgprs[reg_idx][lane] & MASK32 - - def set_sgpr(self, reg_idx: int, val: int) -> None: - if not (0 <= reg_idx < self.num_sgprs): - raise IndexError(f"SGPR index out of range: s{reg_idx}") - self.sgprs[reg_idx] = val & MASK32 - - def get_sgpr(self, reg_idx: int) -> int: - if not (0 <= reg_idx < self.num_sgprs): - raise IndexError(f"SGPR index out of range: s{reg_idx}") - return self.sgprs[reg_idx] & MASK32 - - def set_exec(self, mask: int) -> None: - self.exec_mask = mask & ((1 << self.wave_size) - 1) - - def resolve_src(self, op: str | int, lane: int) -> int: - if isinstance(op, int): - return op & MASK32 - op_str = op.strip().lower() - if op_str.startswith("v"): - idx = int(op_str[1:]) - return self.get_vgpr(idx, lane) - if op_str.startswith("s"): - idx = int(op_str[1:]) - return self.get_sgpr(idx) - return int(op_str, 0) & MASK32 - - def execute_v_min3_i32(self, dst_idx: int, src0: str | int, src1: str | int, src2: str | int) -> None: - for lane in range(self.wave_size): - if (self.exec_mask >> lane) & 1: - s0 = self.resolve_src(src0, lane) - s1 = self.resolve_src(src1, lane) - s2 = self.resolve_src(src2, lane) - self.set_vgpr(dst_idx, lane, ref_v_min3_i32(s0, s1, s2)) - - def execute_v_min3_u32(self, dst_idx: int, src0: str | int, src1: str | int, src2: str | int) -> None: - for lane in range(self.wave_size): - if (self.exec_mask >> lane) & 1: - s0 = self.resolve_src(src0, lane) - s1 = self.resolve_src(src1, lane) - s2 = self.resolve_src(src2, lane) - self.set_vgpr(dst_idx, lane, ref_v_min3_u32(s0, s1, s2)) - - def execute_v_max3_i32(self, dst_idx: int, src0: str | int, src1: str | int, src2: str | int) -> None: - for lane in range(self.wave_size): - if (self.exec_mask >> lane) & 1: - s0 = self.resolve_src(src0, lane) - s1 = self.resolve_src(src1, lane) - s2 = self.resolve_src(src2, lane) - self.set_vgpr(dst_idx, lane, ref_v_max3_i32(s0, s1, s2)) - - def execute_v_max3_u32(self, dst_idx: int, src0: str | int, src1: str | int, src2: str | int) -> None: - for lane in range(self.wave_size): - if (self.exec_mask >> lane) & 1: - s0 = self.resolve_src(src0, lane) - s1 = self.resolve_src(src1, lane) - s2 = self.resolve_src(src2, lane) - self.set_vgpr(dst_idx, lane, ref_v_max3_u32(s0, s1, s2)) - - def execute_instruction( - self, op: str, dst_idx: int, src0: str | int, src1: str | int, src2: str | int - ) -> None: - if op == "v_min3_i32": - self.execute_v_min3_i32(dst_idx, src0, src1, src2) - elif op == "v_min3_u32": - self.execute_v_min3_u32(dst_idx, src0, src1, src2) - elif op == "v_max3_i32": - self.execute_v_max3_i32(dst_idx, src0, src1, src2) - elif op == "v_max3_u32": - self.execute_v_max3_u32(dst_idx, src0, src1, src2) - else: - raise ValueError(f"Unknown instruction: {op}") - - -# Triples where signed and unsigned order disagree, plus ties and ordinary values. -TRIPLES = ( - (5, 0x80000000, 7), - (0xFFFFFFFF, 0, 1), - (0x7FFFFFFF, 0x80000000, 0xFFFFFFFF), - (0x80000001, 0x80000000, 0x7FFFFFFE), - (1, 0xFFFFFFFE, 0xFFFFFFFF), - (9, 9, 0x80000000), - (0xFFFFFFFF, 0xFFFFFFFF, 0), - (3, 3, 3), -) - -_TMP_DIR: tempfile.TemporaryDirectory | None = None -_SRC_PATH: str | None = None - - -def setUpModule() -> None: - global _TMP_DIR, _SRC_PATH - _TMP_DIR = tempfile.TemporaryDirectory() - disasm_dir = os.path.join(_TMP_DIR.name, "disasm") - os.mkdir(disasm_dir) - _SRC_PATH = os.path.join(disasm_dir, "ps_min3.s") - with open(os.path.join(_TMP_DIR.name, "ps_min3.dxbc"), "wb") as f: - f.write(STUB_DXBC) - - -def tearDownModule() -> None: - global _TMP_DIR, _SRC_PATH - if _TMP_DIR is not None: - _TMP_DIR.cleanup() - _TMP_DIR = None - _SRC_PATH = None - - -def run(op: str, *xs: int, inline: tuple[int, ...] = ()) -> int: - """Translate and run `op v0, a, b, c`. - - Operands are moved into v1..v3 unless their index is in `inline`, in which - case the value is written into the instruction as an inline constant. - Returns the mrt0 word. - """ - if _TMP_DIR is None: - setUpModule() - assert _SRC_PATH is not None - lines, operands = [], [] - for i, x in enumerate(xs): - if i in inline: - operands.append(str(x)) - else: - lines.append(f"\tv_mov_b32 v{i + 1}, {x & MASK32:#x}") - operands.append(f"v{i + 1}") - lines.append(f"\t{op} v0, {', '.join(operands)}") - asm = "; test_int_min3_max3\n" + "\n".join(lines) + "\n\texp mrt0 v0, v0, v0, v0 done vm\n\ts_endpgm\n" - with open(_SRC_PATH, "w", encoding="utf-8") as f: - f.write(asm) - with warnings.catch_warnings(): - warnings.simplefilter("ignore", ResourceWarning) - spv = rdna2spirv.translate(_SRC_PATH) - return si.run_fragment(spv)["%out_mrt0"][0] - - -class TestAluIntMin3Max3ReferenceOracle(unittest.TestCase): - """Rigorous tests for the reference oracle models and mathematical properties.""" - - def test_signed_vs_unsigned_divergence_core(self) -> None: - """Verify fundamental bit pattern divergences between signed and unsigned min/max.""" - # 0x0 vs 0xFFFFFFFF (-1 signed, UINT_MAX unsigned) - self.assertEqual(ref_v_min3_i32(0, 0xFFFFFFFF, 10), 0xFFFFFFFF) # -1 is minimum - self.assertEqual(ref_v_min3_u32(0, 0xFFFFFFFF, 10), 0) # 0 is minimum - self.assertEqual(ref_v_max3_i32(0, 0xFFFFFFFF, 10), 10) # 10 is maximum (-1 < 0 < 10) - self.assertEqual(ref_v_max3_u32(0, 0xFFFFFFFF, 10), 0xFFFFFFFF) # UINT_MAX is maximum - - # 0x7FFFFFFF (INT_MAX) vs 0x80000000 (INT_MIN signed, 2^31 unsigned) - self.assertEqual(ref_v_min3_i32(0x7FFFFFFF, 0x80000000, 0), 0x80000000) - self.assertEqual(ref_v_min3_u32(0x7FFFFFFF, 0x80000000, 0), 0) - self.assertEqual(ref_v_max3_i32(0x7FFFFFFF, 0x80000000, 0), 0x7FFFFFFF) - self.assertEqual(ref_v_max3_u32(0x7FFFFFFF, 0x80000000, 0), 0x80000000) - - def test_pairwise_reduction_equivalence(self) -> None: - """3-way min/max must identically match chained 2-way pairwise min/max.""" - sample_vectors = [ - (0, 0, 0), - (1, 2, 3), - (-5, 10, -20), - (0x7FFFFFFF, 0x80000000, 0xFFFFFFFF), - (0x80000000, 0x80000001, 0x7FFFFFFE), - (0x12345678, 0x87654321, 0x00000000), - (0xFFFFFFFE, 0xFFFFFFFF, 0x00000001), - ] - for s0, s1, s2 in sample_vectors: - with self.subTest(s0=hex(s0 & MASK32), s1=hex(s1 & MASK32), s2=hex(s2 & MASK32)): - self.assertEqual(ref_v_min3_i32(s0, s1, s2), ref_pairwise_min3_i32(s0, s1, s2)) - self.assertEqual(ref_v_min3_u32(s0, s1, s2), ref_pairwise_min3_u32(s0, s1, s2)) - self.assertEqual(ref_v_max3_i32(s0, s1, s2), ref_pairwise_max3_i32(s0, s1, s2)) - self.assertEqual(ref_v_max3_u32(s0, s1, s2), ref_pairwise_max3_u32(s0, s1, s2)) - - def test_idempotent_property(self) -> None: - """min3(x, x, x) == x and max3(x, x, x) == x for all x.""" - test_values = [0, 1, -1, 0x7FFFFFFF, 0x80000000, 0xFFFFFFFF, 42, -9999] - for val in test_values: - raw = val & MASK32 - self.assertEqual(ref_v_min3_i32(val, val, val), raw) - self.assertEqual(ref_v_min3_u32(val, val, val), raw) - self.assertEqual(ref_v_max3_i32(val, val, val), raw) - self.assertEqual(ref_v_max3_u32(val, val, val), raw) - - def test_dispatch_ref_wrapper(self) -> None: - """Verify the generic ref dispatch wrapper matches direct reference functions.""" - for op, func in ( - ("v_min3_i32", ref_v_min3_i32), - ("v_min3_u32", ref_v_min3_u32), - ("v_max3_i32", ref_v_max3_i32), - ("v_max3_u32", ref_v_max3_u32), - ): - for t in TRIPLES: - self.assertEqual(ref(op, *t), func(*t)) - - -class TestAluIntMin3Max3SIMD(unittest.TestCase): - """Tests the stateful VectorALUInterpreter modeling multi-lane SIMD execution and EXEC gating.""" - - def test_wave64_simd_multi_lane_evaluation(self) -> None: - """Verify 64 SIMD lanes independently evaluate 3-way min/max with per-lane inputs.""" - interp = VectorALUInterpreter(wave_size=64) - for lane in range(64): - # Lane 0..31 have negative signed numbers, 32..63 have positive numbers - val0 = (lane * 100 - 3200) & MASK32 - val1 = ((63 - lane) * 150 - 4500) & MASK32 - val2 = 0 - interp.set_vgpr(1, lane, val0) - interp.set_vgpr(2, lane, val1) - interp.set_vgpr(3, lane, val2) - - for op in OPS: - interp.execute_instruction(op, 0, "v1", "v2", "v3") - for lane in range(64): - v1 = interp.get_vgpr(1, lane) - v2 = interp.get_vgpr(2, lane) - v3 = interp.get_vgpr(3, lane) - expected = ref(op, v1, v2, v3) - actual = interp.get_vgpr(0, lane) - self.assertEqual( - actual, - expected, - f"Mismatch in {op} lane {lane}: got {hex(actual)}, expected {hex(expected)}", - ) - - def test_wave32_scalar_broadcast_and_inline_const(self) -> None: - """Verify wave32 mode with SGPR scalar broadcast and inline constant operand.""" - interp = VectorALUInterpreter(wave_size=32) - # s0 uniformly set to scalar threshold 50 - interp.set_sgpr(0, 50) - for lane in range(32): - interp.set_vgpr(1, lane, lane * 5) # 0, 5, 10, ... 155 - - # v_min3_u32 v0, s0, v1, 75 - interp.execute_instruction("v_min3_u32", 0, "s0", "v1", 75) - for lane in range(32): - v1_val = lane * 5 - expected = min(50, v1_val, 75) - self.assertEqual(interp.get_vgpr(0, lane), expected) - - # v_max3_i32 v0, s0, v1, -20 (signed inline const) - interp.execute_instruction("v_max3_i32", 0, "s0", "v1", -20) - for lane in range(32): - v1_val = lane * 5 - expected = max(50, v1_val, -20) & MASK32 - self.assertEqual(interp.get_vgpr(0, lane), expected) - - def test_exec_mask_inactive_lanes_preserved(self) -> None: - """EXEC mask write gating: inactive lanes must strictly preserve prior VGPR contents.""" - interp = VectorALUInterpreter(wave_size=64) - sentinel = 0xDEADBEEF - for lane in range(64): - interp.set_vgpr(0, lane, sentinel) - interp.set_vgpr(1, lane, 10) - interp.set_vgpr(2, lane, 20) - interp.set_vgpr(3, lane, 30) - - # Alternating mask: only even lanes active - even_mask = 0x5555555555555555 - interp.set_exec(even_mask) - interp.execute_v_min3_i32(0, "v1", "v2", "v3") - - for lane in range(64): - if lane % 2 == 0: - self.assertEqual(interp.get_vgpr(0, lane), 10, f"Even active lane {lane}") - else: - self.assertEqual(interp.get_vgpr(0, lane), sentinel, f"Odd inactive lane {lane}") - - # Sparse mask test - sparse_mask = (1 << 3) | (1 << 27) | (1 << 59) - interp.reset() - for lane in range(64): - interp.set_vgpr(0, lane, 0x11111111 * ((lane % 7) + 1)) - interp.set_vgpr(1, lane, 100) - interp.set_vgpr(2, lane, 200) - interp.set_vgpr(3, lane, 300) - - saved_v0 = [interp.get_vgpr(0, lane) for lane in range(64)] - interp.set_exec(sparse_mask) - interp.execute_v_max3_u32(0, "v1", "v2", "v3") - - for lane in range(64): - if lane in (3, 27, 59): - self.assertEqual(interp.get_vgpr(0, lane), 300) - else: - self.assertEqual(interp.get_vgpr(0, lane), saved_v0[lane]) - - # Full zero mask test: nothing is modified - interp.set_exec(0) - interp.execute_v_min3_u32(0, "v1", "v2", "v3") - for lane in range(64): - if lane in (3, 27, 59): - self.assertEqual(interp.get_vgpr(0, lane), 300) - else: - self.assertEqual(interp.get_vgpr(0, lane), saved_v0[lane]) - - def test_multi_lane_signed_unsigned_divergence(self) -> None: - """Vector lanes simultaneously executing signed vs unsigned operations diverge per lane.""" - interp = VectorALUInterpreter(wave_size=64) - for lane in range(64): - if lane < 32: - # 0xFFFFFFFF (-1 as i32, UINT32_MAX as u32), 0, 10 - interp.set_vgpr(1, lane, 0xFFFFFFFF) - interp.set_vgpr(2, lane, 0) - interp.set_vgpr(3, lane, 10) - else: - # 0x80000000 (INT32_MIN as i32, 2^31 as u32), 0x7FFFFFFF (INT32_MAX), 0 - interp.set_vgpr(1, lane, 0x80000000) - interp.set_vgpr(2, lane, 0x7FFFFFFF) - interp.set_vgpr(3, lane, 0) - - # Test v_min3_i32 vs v_min3_u32 - interp.execute_v_min3_i32(4, "v1", "v2", "v3") - interp.execute_v_min3_u32(5, "v1", "v2", "v3") - interp.execute_v_max3_i32(6, "v1", "v2", "v3") - interp.execute_v_max3_u32(7, "v1", "v2", "v3") - - for lane in range(32): - self.assertEqual(interp.get_vgpr(4, lane), 0xFFFFFFFF) # signed min: -1 - self.assertEqual(interp.get_vgpr(5, lane), 0) # unsigned min: 0 - self.assertEqual(interp.get_vgpr(6, lane), 10) # signed max: 10 - self.assertEqual(interp.get_vgpr(7, lane), 0xFFFFFFFF) # unsigned max: UINT32_MAX - - for lane in range(32, 64): - self.assertEqual(interp.get_vgpr(4, lane), 0x80000000) # signed min: INT32_MIN - self.assertEqual(interp.get_vgpr(5, lane), 0) # unsigned min: 0 - self.assertEqual(interp.get_vgpr(6, lane), 0x7FFFFFFF) # signed max: INT32_MAX - self.assertEqual(interp.get_vgpr(7, lane), 0x80000000) # unsigned max: 2^31 - - -class TestAluIntMin3Max3ExtremaPermutationsNegative(unittest.TestCase): - """Extrema matrices, 3! permutation invariance, and negative controls.""" - - def test_twos_complement_extrema_matrix(self) -> None: - """Verify behavior at and around two's complement and unsigned boundaries.""" - extrema = ( - 0x80000000, # INT32_MIN (-2147483648) - 0x80000001, # INT32_MIN + 1 - 0xFFFFFFFF, # -1 as i32, UINT32_MAX as u32 - 0x00000000, # 0 - 0x00000001, # 1 - 0x7FFFFFFE, # INT32_MAX - 1 - 0x7FFFFFFF, # INT32_MAX - ) - # Any triple containing 0x80000000 must have signed min = 0x80000000 - for x in extrema: - for y in extrema: - self.assertEqual(ref_v_min3_i32(0x80000000, x, y), 0x80000000) - - # Any triple containing 0x7FFFFFFF must have signed max = 0x7FFFFFFF - for x in extrema: - for y in extrema: - self.assertEqual(ref_v_max3_i32(0x7FFFFFFF, x, y), 0x7FFFFFFF) - - # Any triple containing 0x00000000 must have unsigned min = 0 - for x in extrema: - for y in extrema: - self.assertEqual(ref_v_min3_u32(0x00000000, x, y), 0) - - # Any triple containing 0xFFFFFFFF must have unsigned max = 0xFFFFFFFF - for x in extrema: - for y in extrema: - self.assertEqual(ref_v_max3_u32(0xFFFFFFFF, x, y), 0xFFFFFFFF) - - def test_quad_divergence_extrema_triple(self) -> None: - """On (0x80000000, 0x00000000, 0xFFFFFFFF), all 4 instructions yield mutually distinct results.""" - s0, s1, s2 = 0x80000000, 0x00000000, 0xFFFFFFFF - res_min_i32 = ref_v_min3_i32(s0, s1, s2) - res_min_u32 = ref_v_min3_u32(s0, s1, s2) - res_max_i32 = ref_v_max3_i32(s0, s1, s2) - res_max_u32 = ref_v_max3_u32(s0, s1, s2) - - self.assertEqual(res_min_i32, 0x80000000) - self.assertEqual(res_min_u32, 0x00000000) - self.assertEqual(res_max_i32, 0x00000000) - self.assertEqual(res_max_u32, 0xFFFFFFFF) - - distinct_results = {res_min_i32, res_min_u32, res_max_i32, res_max_u32} - self.assertEqual(len(distinct_results), 3) # Note: 0x00000000 is shared by min_u32 and max_i32 - self.assertNotEqual(res_min_i32, res_min_u32) - self.assertNotEqual(res_max_i32, res_max_u32) - self.assertNotEqual(res_min_i32, res_max_i32) - self.assertNotEqual(res_min_u32, res_max_u32) - - def test_permutation_invariance_all_orders(self) -> None: - """All 3! = 6 permutations must yield identical results across all 4 instructions.""" - triples_to_permute = [ - (0x80000000, 0, 0x7FFFFFFF), - (0xFFFFFFFF, 1, 0x80000000), - (0x7FFFFFFF, 0x7FFFFFFF, 0x80000000), - (42, 42, 42), - (0x12345678, 0x9ABCDEF0, 0x00000000), - (0x80000000, 0x80000001, 0x80000002), - (0xFFFFFFFD, 0xFFFFFFFE, 0xFFFFFFFF), - (0x55555555, 0xAAAAAAAA, 0xFFFFFFFF), - ] - for triple in triples_to_permute: - perms = list(itertools.permutations(triple)) - self.assertEqual(len(perms), 6) - for op in OPS: - expected = ref(op, *triple) - for p in perms: - with self.subTest(op=op, perm=[hex(v) for v in p]): - self.assertEqual(ref(op, *p), expected) - - def test_negative_controls_signed_unsigned_divergence(self) -> None: - """Signed vs unsigned operations must not be mistakenly interchangeable.""" - # When negative numbers are involved, signed and unsigned min/max diverge - self.assertNotEqual(ref_v_min3_i32(0, 0xFFFFFFFF, 1), ref_v_min3_u32(0, 0xFFFFFFFF, 1)) - self.assertNotEqual(ref_v_max3_i32(0, 0xFFFFFFFF, 1), ref_v_max3_u32(0, 0xFFFFFFFF, 1)) - self.assertNotEqual(ref_v_min3_i32(0x80000000, 5, 10), ref_v_min3_u32(0x80000000, 5, 10)) - self.assertNotEqual(ref_v_max3_i32(0x80000000, 5, 10), ref_v_max3_u32(0x80000000, 5, 10)) - - # min3 and max3 must not be interchangeable on non-identical inputs - self.assertNotEqual(ref_v_min3_i32(1, 2, 3), ref_v_max3_i32(1, 2, 3)) - self.assertNotEqual(ref_v_min3_u32(1, 2, 3), ref_v_max3_u32(1, 2, 3)) - - def test_negative_controls_interpreter_fault_injection(self) -> None: - """Interpreter must reject invalid opcodes, register indices, and operands.""" - interp = VectorALUInterpreter(wave_size=64) - - # Invalid opcode - with self.assertRaises(ValueError): - interp.execute_instruction("v_invalid_op", 0, "v1", "v2", "v3") - - # Invalid VGPR index - with self.assertRaises(IndexError): - interp.set_vgpr(-1, 0, 0) - with self.assertRaises(IndexError): - interp.set_vgpr(64, 0, 0) - with self.assertRaises(IndexError): - interp.get_vgpr(0, -1) - with self.assertRaises(IndexError): - interp.get_vgpr(0, 64) - - # Invalid SGPR index - with self.assertRaises(IndexError): - interp.set_sgpr(-1, 0) - with self.assertRaises(IndexError): - interp.set_sgpr(106, 0) - with self.assertRaises(IndexError): - interp.get_sgpr(-1) - with self.assertRaises(IndexError): - interp.get_sgpr(106) - - # Invalid operand string - with self.assertRaises(ValueError): - interp.resolve_src("not_a_register_or_int", 0) - - -class ReferenceTests(unittest.TestCase): - """The reference against hand-worked values, so a failure points at the translator, not the oracle.""" - - def test_reference(self) -> None: - self.assertEqual(ref("v_min3_i32", 5, 0x80000000, 7), 0x80000000) # INT_MIN is the smallest i32 - self.assertEqual(ref("v_min3_u32", 5, 0x80000000, 7), 5) - self.assertEqual(ref("v_max3_i32", 5, 0x80000000, 7), 7) - self.assertEqual(ref("v_max3_u32", 5, 0x80000000, 7), 0x80000000) - self.assertEqual(ref("v_min3_i32", 0xFFFFFFFF, 0, 1), 0xFFFFFFFF) # -1 - self.assertEqual(ref("v_max3_u32", 0xFFFFFFFF, 0, 1), 0xFFFFFFFF) - self.assertEqual(ref("v_max3_i32", 0xFFFFFFFF, 0, 1), 1) - self.assertEqual(ref("v_min3_u32", 0xFFFFFFFF, 0, 1), 0) - - -class Min3Max3Tests(unittest.TestCase): - def test_every_order(self) -> None: - for op in OPS: - for xs in TRIPLES: - for perm in sorted(set(itertools.permutations(xs))): - with self.subTest(op=op, xs=[hex(v) for v in perm]): - self.assertEqual(run(op, *perm), ref(op, *perm)) - - def test_sweep(self) -> None: - values = (0, 1, 0x7FFFFFFF, 0x80000000, 0xFFFFFFFF) - for op in OPS: - for xs in itertools.product(values, repeat=3): - with self.subTest(op=op, xs=[hex(v) for v in xs]): - self.assertEqual(run(op, *xs), ref(op, *xs)) - - def test_inline_constants(self) -> None: - # -16 as an inline constant is 0xFFFFFFF0: below 64 as i32, above it as u32. - cases = [ - ("v_min3_i32", (0x7FFFFFFF, -16, 64), 0xFFFFFFF0), - ("v_min3_u32", (0x7FFFFFFF, -16, 64), 64), - ("v_max3_i32", (0x80000000, -16, 64), 64), - ("v_max3_u32", (0x80000000, -16, 64), 0xFFFFFFF0), - ] - for op, xs, want in cases: - with self.subTest(op=op): - self.assertEqual(want, ref(op, *xs)) - self.assertEqual(run(op, *xs, inline=(1, 2)), want) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_alu_int_minmax_shift_not.py b/tests/semantic/test_alu_int_minmax_shift_not.py deleted file mode 100644 index 3cfd061fb..000000000 --- a/tests/semantic/test_alu_int_minmax_shift_not.py +++ /dev/null @@ -1,274 +0,0 @@ -"""Translator-to-interpreter semantic tests for integer VALU min/max, arithmetic shift, and bitwise NOT: - - v_min_i32 D = min_s32(S0, S1) - v_max_i32 D = max_s32(S0, S1) - v_min_u32 D = min_u32(S0, S1) - v_max_u32 D = max_u32(S0, S1) - v_ashrrev_i32 D = sext(S1) >> (S0 & 31) (note: S0 is shift amount, S1 is value) - v_not_b32 D = ~S0 - -Every test translates synthetic hand-written RDNA2 disassembly via tools/rdna2spirv.py and executes the emitted -SPIR-V in tests/semantic/spirv_mini_interp.py. Standard library only; no game data. -""" -import os -import random -import sys -import unittest - -HERE = os.path.dirname(os.path.abspath(__file__)) -if HERE not in sys.path: - sys.path.insert(0, HERE) - -from support import mrt0_words, translate_lines # noqa: E402 - -MASK32 = 0xFFFFFFFF - - -def s32(x): - x &= MASK32 - return x - (1 << 32) if (x & 0x80000000) else x - - -def ref_min_i32(a, b): - return (a if s32(a) <= s32(b) else b) & MASK32 - - -def ref_max_i32(a, b): - return (a if s32(a) >= s32(b) else b) & MASK32 - - -def ref_min_u32(a, b): - return (a if (a & MASK32) <= (b & MASK32) else b) & MASK32 - - -def ref_max_u32(a, b): - return (a if (a & MASK32) >= (b & MASK32) else b) & MASK32 - - -def ref_ashrrev_i32(shift, val): - return (s32(val) >> (shift & 31)) & MASK32 - - -def ref_not_b32(val): - return (~val) & MASK32 - - -BOUNDARIES = (0x00000000, 0x00000001, 0x7FFFFFFF, 0x80000000, 0xFFFFFFFF) - -MINMAX_HAND_CONSTANTS = [ - ("v_min_i32", 0x80000000, 0x7FFFFFFF, 0x80000000), - ("v_min_i32", 0xFFFFFFFF, 0x00000000, 0xFFFFFFFF), - ("v_min_i32", 0xFFFFFFFF, 0x00000001, 0xFFFFFFFF), - ("v_min_i32", 0x80000000, 0xFFFFFFFF, 0x80000000), - ("v_max_i32", 0x80000000, 0x7FFFFFFF, 0x7FFFFFFF), - ("v_max_i32", 0xFFFFFFFF, 0x00000000, 0x00000000), - ("v_max_i32", 0xFFFFFFFF, 0x00000001, 0x00000001), - ("v_max_i32", 0x80000000, 0xFFFFFFFF, 0xFFFFFFFF), - ("v_min_u32", 0x80000000, 0x7FFFFFFF, 0x7FFFFFFF), - ("v_min_u32", 0xFFFFFFFF, 0x00000000, 0x00000000), - ("v_min_u32", 0xFFFFFFFF, 0x00000001, 0x00000001), - ("v_min_u32", 0x80000000, 0xFFFFFFFF, 0x80000000), - ("v_max_u32", 0x80000000, 0x7FFFFFFF, 0x80000000), - ("v_max_u32", 0xFFFFFFFF, 0x00000000, 0xFFFFFFFF), - ("v_max_u32", 0xFFFFFFFF, 0x00000001, 0xFFFFFFFF), - ("v_max_u32", 0x80000000, 0xFFFFFFFF, 0xFFFFFFFF), -] - -ASHRREV_HAND_CONSTANTS = [ - (0, 0x80000000, 0x80000000), - (1, 0x80000000, 0xC0000000), - (31, 0x80000000, 0xFFFFFFFF), - (31, 0x80000001, 0xFFFFFFFF), - (4, 0xFFFFFFFF, 0xFFFFFFFF), - (4, 0x7FFFFFFF, 0x07FFFFFF), - (31, 0x7FFFFFFF, 0x00000000), - (32, 0x80000000, 0x80000000), - (33, 0x80000000, 0xC0000000), - (0xFFFFFFFF, 0x80000001, 0xFFFFFFFF), - (0xFFFFFFFF, 0x7FFFFFFF, 0x00000000), -] - -NOT_HAND_CONSTANTS = [ - (0x00000000, 0xFFFFFFFF), - (0xFFFFFFFF, 0x00000000), - (0x55555555, 0xAAAAAAAA), - (0xAAAAAAAA, 0x55555555), - (0x80000000, 0x7FFFFFFF), - (0x12345678, 0xEDCBA987), -] - -REF_MAP = { - "v_min_i32": ref_min_i32, - "v_max_i32": ref_max_i32, - "v_min_u32": ref_min_u32, - "v_max_u32": ref_max_u32, -} - - -def run_ps(name, body_lines): - lines = list(body_lines) + ["exp mrt0 v0, v0, v0, v0 done vm", "s_endpgm"] - spv = translate_lines(name, lines) - words = mrt0_words(spv) - return words[0], spv - - -class ReferenceConstantsTests(unittest.TestCase): - def test_hand_computed_constants(self): - for op, a, b, expected in MINMAX_HAND_CONSTANTS: - with self.subTest(op=op, a=hex(a), b=hex(b)): - self.assertEqual(REF_MAP[op](a, b), expected) - for sh, val, expected in ASHRREV_HAND_CONSTANTS: - with self.subTest(op="v_ashrrev_i32", sh=hex(sh), val=hex(val)): - self.assertEqual(ref_ashrrev_i32(sh, val), expected) - for val, expected in NOT_HAND_CONSTANTS: - with self.subTest(op="v_not_b32", val=hex(val)): - self.assertEqual(ref_not_b32(val), expected) - - -class MinMaxInt32Tests(unittest.TestCase): - def test_signed_vs_unsigned_boundary_matrix(self): - for op, ref in REF_MAP.items(): - for a in BOUNDARIES: - for b in BOUNDARIES: - with self.subTest(op=op, a=hex(a), b=hex(b)): - got, _ = run_ps( - "ps_minmax_mat", - [f"v_mov_b32 v1, {a:#x}", f"v_mov_b32 v2, {b:#x}", f"{op} v0, v1, v2"], - ) - self.assertEqual(got, ref(a, b)) - - def test_commutativity_and_equal_operands(self): - pairs = [(0x80000000, 0x7FFFFFFF), (0xFFFFFFFF, 1), (0x12345678, 0x87654321), (42, 42)] - for op, ref in REF_MAP.items(): - for a, b in pairs: - with self.subTest(op=op, a=hex(a), b=hex(b)): - g1, _ = run_ps( - "ps_mm_1", [f"v_mov_b32 v1, {a:#x}", f"v_mov_b32 v2, {b:#x}", f"{op} v0, v1, v2"] - ) - g2, _ = run_ps( - "ps_mm_2", [f"v_mov_b32 v1, {a:#x}", f"v_mov_b32 v2, {b:#x}", f"{op} v0, v2, v1"] - ) - self.assertEqual(g1, g2) - self.assertEqual(g1, ref(a, b)) - - def test_operand_forms_sgpr_literal_e32_e64(self): - for op, ref in REF_MAP.items(): - for suffix in ("", "_e32", "_e64"): - with self.subTest(op=op + suffix, form="sgpr"): - got, _ = run_ps( - "ps_mm_sgpr", - ["s_mov_b32 s0, 0x80000005", "v_mov_b32 v1, 5", f"{op}{suffix} v0, s0, v1"], - ) - self.assertEqual(got, ref(0x80000005, 5)) - with self.subTest(op=op + suffix, form="literal"): - got, _ = run_ps( - "ps_mm_lit", - ["v_mov_b32 v1, 0x7FFFFFFF", f"{op}{suffix} v0, 0x80000000, v1"], - ) - self.assertEqual(got, ref(0x80000000, 0x7FFFFFFF)) - - def test_seeded_random_pairs(self): - rng = random.Random(0x4D494E4D) - for _ in range(10): - a = rng.getrandbits(32) - b = rng.getrandbits(32) - for op, ref in REF_MAP.items(): - with self.subTest(op=op, a=hex(a), b=hex(b)): - got, _ = run_ps( - "ps_mm_rand", - [f"v_mov_b32 v1, {a:#x}", f"v_mov_b32 v2, {b:#x}", f"{op} v0, v1, v2"], - ) - self.assertEqual(got, ref(a, b)) - - -class VAshrrevI32Tests(unittest.TestCase): - def test_hand_constants_and_shift_masking(self): - for sh, val, expected in ASHRREV_HAND_CONSTANTS: - with self.subTest(sh=hex(sh), val=hex(val)): - got, _ = run_ps( - "ps_ashr_const", - [f"v_mov_b32 v1, {sh:#x}", f"v_mov_b32 v2, {val:#x}", "v_ashrrev_i32 v0, v1, v2"], - ) - self.assertEqual(got, expected) - - def test_operand_forms_sgpr_literal_e32_e64(self): - for suffix in ("", "_e32", "_e64"): - with self.subTest(suffix=suffix, form="sgpr"): - got, _ = run_ps( - "ps_ashr_sgpr", - ["s_mov_b32 s0, 35", "v_mov_b32 v1, 0x80000000", f"v_ashrrev_i32{suffix} v0, s0, v1"], - ) - self.assertEqual(got, ref_ashrrev_i32(35, 0x80000000)) - with self.subTest(suffix=suffix, form="literal"): - got, _ = run_ps( - "ps_ashr_lit", - ["v_mov_b32 v1, 0xF0000000", f"v_ashrrev_i32{suffix} v0, 0x10000004, v1"], - ) - self.assertEqual(got, ref_ashrrev_i32(0x10000004, 0xF0000000)) - - def test_seeded_random_pairs(self): - rng = random.Random(0x41534852) - for _ in range(12): - sh = rng.getrandbits(32) - val = rng.getrandbits(32) - with self.subTest(sh=hex(sh), val=hex(val)): - got, _ = run_ps( - "ps_ashr_rand", - [f"v_mov_b32 v1, {sh:#x}", f"v_mov_b32 v2, {val:#x}", "v_ashrrev_i32 v0, v1, v2"], - ) - self.assertEqual(got, ref_ashrrev_i32(sh, val)) - - -class VNotB32Tests(unittest.TestCase): - def test_boundary_patterns_and_double_not_involution(self): - for val, expected in NOT_HAND_CONSTANTS: - with self.subTest(val=hex(val)): - got, _ = run_ps("ps_not_const", [f"v_mov_b32 v1, {val:#x}", "v_not_b32 v0, v1"]) - self.assertEqual(got, expected) - got2, _ = run_ps( - "ps_not_inv", - [f"v_mov_b32 v1, {val:#x}", "v_not_b32 v2, v1", "v_not_b32 v0, v2"], - ) - self.assertEqual(got2, val) - - def test_operand_forms_sgpr_literal_e32_e64(self): - for suffix in ("", "_e32", "_e64"): - with self.subTest(suffix=suffix, form="sgpr"): - got, _ = run_ps("ps_not_sgpr", ["s_mov_b32 s0, 0x12345678", f"v_not_b32{suffix} v0, s0"]) - self.assertEqual(got, ref_not_b32(0x12345678)) - with self.subTest(suffix=suffix, form="literal"): - got, _ = run_ps("ps_not_lit", [f"v_not_b32{suffix} v0, 0xDEADBEEF"]) - self.assertEqual(got, ref_not_b32(0xDEADBEEF)) - - def test_seeded_random_values(self): - rng = random.Random(0x4E4F5432) - for _ in range(10): - val = rng.getrandbits(32) - with self.subTest(val=hex(val)): - got, _ = run_ps("ps_not_rand", [f"v_mov_b32 v1, {val:#x}", "v_not_b32 v0, v1"]) - self.assertEqual(got, ref_not_b32(val)) - - -class SpirvStructureTests(unittest.TestCase): - def test_emitted_opcodes(self): - for op, glsl_name in ( - ("v_min_i32", "SMin"), - ("v_max_i32", "SMax"), - ("v_min_u32", "UMin"), - ("v_max_u32", "UMax"), - ): - with self.subTest(op=op): - _, spv = run_ps("ps_struct_mm", ["v_mov_b32 v1, 1", "v_mov_b32 v2, 2", f"{op} v0, v1, v2"]) - self.assertIn(f"= OpExtInst %uint %glsl {glsl_name}", spv) - - _, spv_ashr = run_ps( - "ps_struct_ashr", ["v_mov_b32 v1, 1", "v_mov_b32 v2, 2", "v_ashrrev_i32 v0, v1, v2"] - ) - self.assertIn("= OpShiftRightArithmetic %uint", spv_ashr) - - _, spv_not = run_ps("ps_struct_not", ["v_mov_b32 v1, 1", "v_not_b32 v0, v1"]) - self.assertIn("= OpNot %uint", spv_not) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_alu_int_misc.py b/tests/semantic/test_alu_int_misc.py deleted file mode 100644 index 4342f0235..000000000 --- a/tests/semantic/test_alu_int_misc.py +++ /dev/null @@ -1,182 +0,0 @@ -"""Value tests for integer VALU instructions the translator handles but no other test reaches: - - v_bfm_b32 D = ((1 << (S0 & 31)) - 1) << (S1 & 31) - v_and_or_b32 D = (S0 & S1) | S2 - v_add_lshl_u32 D = ((S0 + S1) mod 2^32) << (S2 & 31) - v_lshl_or_b32 D = (S0 << (S1 & 31)) | S2 - v_mad_i32_i24 D = sext(S0[23:0]) * sext(S1[23:0]) + S2 (mod 2^32) - v_mul_lo_u32 D = (S0 * S1) mod 2^32 - -Each case is a synthetic hand-written pixel-shader listing (operands loaded into VGPRs with v_mov_b32, one -instruction, exported to mrt0), translated by tools/rdna2spirv.py and executed by spirv_mini_interp.py. The -expected words are hand-computed constants per the RDNA2 ISA; a plain-Python reference (no translator) is checked -against the same constants so a typo in either is caught. Standard library only. -""" -import os -import sys -import tempfile -import unittest -import warnings - -HERE = os.path.dirname(os.path.abspath(__file__)) -if HERE not in sys.path: - sys.path.insert(0, HERE) - -from support import STUB_DXBC, mrt0_words, rdna2spirv # noqa: E402 (support puts tools/ on sys.path) - -MASK32 = 0xFFFFFFFF - - -def sext24(v): - v &= 0xFFFFFF - return v - (1 << 24) if v & 0x800000 else v - - -REFERENCE = { - "v_bfm_b32": lambda s0, s1: (((1 << (s0 & 31)) - 1) << (s1 & 31)) & MASK32, - "v_and_or_b32": lambda s0, s1, s2: ((s0 & s1) | s2) & MASK32, - "v_add_lshl_u32": lambda s0, s1, s2: (((s0 + s1) & MASK32) << (s2 & 31)) & MASK32, - "v_lshl_or_b32": lambda s0, s1, s2: ((s0 << (s1 & 31)) | s2) & MASK32, - "v_mad_i32_i24": lambda s0, s1, s2: (sext24(s0) * sext24(s1) + s2) & MASK32, - "v_mul_lo_u32": lambda s0, s1: (s0 * s1) & MASK32, -} - -# (sources..., expected) -- expected words computed by hand from the ISA formulas above. -CASES = { - "v_bfm_b32": [ - (0, 5, 0x00000000), # width 0 -> empty mask - (8, 4, 0x00000FF0), - (31, 0, 0x7FFFFFFF), # width 31 - (31, 1, 0xFFFFFFFE), - (32, 0, 0x00000000), # width 32 & 31 = 0 - (36, 40, 0x00000F00), # width 4, offset 8 after masking - (4, 30, 0xC0000000), # 0xF << 30: top two bits wrap out past bit 31 - (0xFFFFFFFF, 0xFFFFFFFF, 0x80000000), # width 31, offset 31: only bit 31 survives - ], - "v_and_or_b32": [ - (0xF0F0F0F0, 0xFF00FF00, 0x0000000F, 0xF000F00F), - (0xFFFFFFFF, 0x00000000, 0x00000000, 0x00000000), - (0x12345678, 0xFFFFFFFF, 0x80000000, 0x92345678), - (0xAAAAAAAA, 0x55555555, 0x55555555, 0x55555555), - (0xDEADBEEF, 0x0000FFFF, 0xFFFF0000, 0xFFFFBEEF), - (0x0000000C, 0x0000000A, 0x00000003, 0x0000000B), # (S0|S1)&S2 or S0&(S1|S2) would differ - (0x000000FF, 0x0000000F, 0x0000000F, 0x0000000F), # overlapping bits: OR, not ADD (ADD gives 0x1E) - (0xFFFFFFFF, 0xFFFFFFFF, 0x00000001, 0xFFFFFFFF), # ADD would wrap to 0 - ], - "v_add_lshl_u32": [ - (1, 2, 3, 0x00000018), - (0xFFFFFFFF, 2, 4, 0x00000010), # add wraps to 1, then << 4 - (0x80000000, 0x80000000, 0, 0x00000000), - (0x40000000, 0x40000000, 1, 0x00000000), - (0x12345678, 0, 36, 0x23456780), # shift 36 & 31 = 4 - (3, 0, 33, 0x00000006), # shift 33 & 31 = 1 - (0xFFFFFFF0, 0x11, 31, 0x80000000), # wrapping add gives 1, then << 31 - (2, 3, 0, 0x00000005), - ], - "v_lshl_or_b32": [ - (1, 4, 1, 0x00000011), - (0x0000FFFF, 16, 0x0000FFFF, 0xFFFFFFFF), - (0x80000001, 1, 0, 0x00000002), # bit 31 shifted out - (5, 33, 0x100, 0x0000010A), # shift 33 & 31 = 1 - (0xABCD, 48, 0x12, 0xABCD0012), # shift 48 & 31 = 16 - (1, 31, 1, 0x80000001), - (0xF, 2, 0x3C, 0x0000003C), # OR, not ADD (ADD would give 0x78) - ], - "v_mad_i32_i24": [ - (2, 3, 4, 0x0000000A), - (0x800000, 1, 0, 0xFF800000), # -2^23 * 1 - (0xFFFFFF, 0xFFFFFF, 0, 0x00000001), # -1 * -1 - (0x800000, 0x7FFFFF, 0, 0x00800000), # -2^23 * (2^23-1) = -2^46 + 2^23 - (0x7FFFFF, 0x7FFFFF, 0, 0xFF000001), # (2^23-1)^2 = 2^46 - 2^24 + 1 - (0xAB000005, 0xFF000003, 0, 0x0000000F), # bits 31:24 ignored: 5 * 3 - (0x12FFFFFF, 0x7F000002, 0, 0xFFFFFFFE), # bits 31:24 ignored: -1 * 2 - (3, 4, 0xFFFFFFF6, 0x00000002), # 12 + (-10) - (0xFFFFFE, 5, 0xFFFFFFFF, 0xFFFFFFF5), # -2 * 5 + (-1) = -11 - (0xFFFFFF, 1, 1, 0x00000000), # -1 + 1 wraps to 0 - ], - "v_mul_lo_u32": [ - (6, 7, 0x0000002A), - (0xFFFFFFFF, 0xFFFFFFFF, 0x00000001), # (2^32-1)^2 = 2^64 - 2^33 + 1 - (0x00010000, 0x00010000, 0x00000000), # 2^32 - (0x80000000, 3, 0x80000000), - (0xFFFFFFFF, 2, 0xFFFFFFFE), - (0x00010001, 0x0000FFFF, 0xFFFFFFFF), # (2^16+1)(2^16-1) = 2^32 - 1 - (0x00010001, 0x00010001, 0x00020001), # 2^32 + 2^17 + 1 - (0x12345678, 0x9ABCDEF0, 0x242D2080), - ], -} - -_TMP = None - - -def setUpModule(): - global _TMP - _TMP = tempfile.TemporaryDirectory() - os.mkdir(os.path.join(_TMP.name, "disasm")) - with open(os.path.join(_TMP.name, "ps_int_misc.dxbc"), "wb") as f: - f.write(STUB_DXBC) - - -def tearDownModule(): - global _TMP - if _TMP is not None: - _TMP.cleanup() - _TMP = None - - -def run_op(op, srcs): - """Translate and run `op v0, v1, v2[, v3]` with the sources loaded by v_mov_b32; return the mrt0 word.""" - regs = [f"v{i + 1}" for i in range(len(srcs))] - lines = ["; test_int_misc"] - lines += [f"\tv_mov_b32 {r}, {s & MASK32:#x}" for r, s in zip(regs, srcs)] - lines.append(f"\t{op} v0, {', '.join(regs)}") - lines += ["\texp mrt0 v0, v0, v0, v0 done vm", "\ts_endpgm", ""] - path = os.path.join(_TMP.name, "disasm", "ps_int_misc.s") - with open(path, "w", encoding="utf-8", newline="") as f: - f.write("\n".join(lines)) - with warnings.catch_warnings(): - warnings.simplefilter("ignore", ResourceWarning) - spv = rdna2spirv.translate(path) - words = mrt0_words(spv) - if len(set(words)) != 1: - raise AssertionError(f"{op}: the four exported words differ: {[hex(w) for w in words]}") - return words[0] - - -class ReferenceMatchesHandConstants(unittest.TestCase): - def test_reference(self): - for op, cases in CASES.items(): - for *srcs, expected in cases: - with self.subTest(op=op, srcs=[hex(s) for s in srcs]): - self.assertEqual(REFERENCE[op](*srcs), expected) - - -class TranslatedValues(unittest.TestCase): - def check(self, op): - for *srcs, expected in CASES[op]: - with self.subTest(srcs=[hex(s) for s in srcs]): - got = run_op(op, srcs) - self.assertEqual(got, expected, f"{op} {[hex(s) for s in srcs]}: got {got:#010x}, " - f"expected {expected:#010x}") - - def test_v_bfm_b32(self): - self.check("v_bfm_b32") - - def test_v_and_or_b32(self): - self.check("v_and_or_b32") - - def test_v_add_lshl_u32(self): - self.check("v_add_lshl_u32") - - def test_v_lshl_or_b32(self): - self.check("v_lshl_or_b32") - - def test_v_mad_i32_i24(self): - self.check("v_mad_i32_i24") - - def test_v_mul_lo_u32(self): - self.check("v_mul_lo_u32") - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_alu_ldexp.py b/tests/semantic/test_alu_ldexp.py deleted file mode 100644 index e2833e8f7..000000000 --- a/tests/semantic/test_alu_ldexp.py +++ /dev/null @@ -1,719 +0,0 @@ -from __future__ import annotations - -"""Semantic interpreter tests for AMD RDNA2 floating-point exponent scaling (v_ldexp_f32). - -Covers: - - IEEE 754 single-precision (binary32) ldexp scaling: D = S0 * 2^S1 - - Denormal / subnormal handling under both IEEE 754 preserve mode (gradual underflow - with round-to-nearest-even down to 2^-149) and FTZ/DAZ mode (flush-to-zero) - - Overflow to +/- infinity on large positive exponents and extreme integers (e.g. 0x7FFFFFFF) - - Underflow to sign-preserved +/- zero on large negative exponents and extreme integers (e.g. -0x80000000) - - Special floating-point value preservation (+0.0, -0.0, +inf, -inf, NaN) - - Hardware modifiers: abs (|S0|), neg (-S0), and clamp ([0.0, 1.0]) - - Dual oracle verification: bit-accurate integer VALU model cross-checked against - an exact rational Fraction oracle and Python's math.ldexp - - Negative controls ensuring mutated arithmetic or missing edge cases fail assertions. -""" - -import math -import os -import random -import struct -import sys -import unittest -from fractions import Fraction -from typing import Tuple - -HERE = os.path.dirname(os.path.abspath(__file__)) -ROOT = os.path.dirname(os.path.dirname(HERE)) -TOOLS_DIR = os.environ.get("LEONIDA_TOOLS_DIR") or os.path.join(ROOT, "tools") - -sys.dont_write_bytecode = True -if TOOLS_DIR not in sys.path: - sys.path.insert(0, TOOLS_DIR) -if HERE not in sys.path: - sys.path.insert(0, HERE) - -import spirv_mini_interp as si - -MASK32 = 0xFFFFFFFF -SIGN_MASK = 0x80000000 -EXP_MASK = 0x7F800000 -MANT_MASK = 0x007FFFFF - -POS_ZERO = 0x00000000 -NEG_ZERO = 0x80000000 -POS_INF = 0x7F800000 -NEG_INF = 0xFF800000 -QNAN = 0x7FC00000 -SNAN = 0x7F800001 - -ONE = 0x3F800000 # 1.0f -TWO = 0x40000000 # 2.0f -HALF = 0x3F000000 # 0.5f -MAX_FINITE = 0x7F7FFFFF # largest finite binary32 (~3.402823466e+38) -MIN_NORMAL = 0x00800000 # smallest positive normal binary32 (2^-126, ~1.175494351e-38) -MAX_SUBNORMAL = 0x007FFFFF # largest positive subnormal binary32 (~1.175494211e-38) -MIN_SUBNORMAL = 0x00000001 # smallest positive subnormal binary32 (2^-149, ~1.401298464e-45) - - -def s32(x: int) -> int: - """Interpret a 32-bit integer word as a signed two's-complement integer.""" - x &= MASK32 - return x - (1 << 32) if (x & SIGN_MASK) else x - - -def bits_to_f32(b: int) -> float: - """Unpack a 32-bit unsigned integer to a Python float (binary32).""" - return struct.unpack(" int: - """Pack a Python float to a 32-bit unsigned integer word (binary32).""" - if math.isnan(f): - return QNAN - try: - return struct.unpack(" bool: - """Check if binary32 bit pattern represents any NaN.""" - return ((bits & EXP_MASK) == EXP_MASK) and ((bits & MANT_MASK) != 0) - - -def is_inf(bits: int) -> bool: - """Check if binary32 bit pattern represents infinity.""" - return ((bits & EXP_MASK) == EXP_MASK) and ((bits & MANT_MASK) == 0) - - -def is_zero(bits: int) -> bool: - """Check if binary32 bit pattern represents positive or negative zero.""" - return (bits & 0x7FFFFFFF) == 0 - - -def is_subnormal(bits: int) -> bool: - """Check if binary32 bit pattern represents a subnormal (denormal) float.""" - return ((bits & EXP_MASK) == 0) and ((bits & MANT_MASK) != 0) - - -def interp_v_ldexp_f32( - src0_bits: int, - src1_i32: int, - *, - flush_denorms: bool = False, - clamp: bool = False, - abs_src0: bool = False, - neg_src0: bool = False, -) -> int: - """Bit-accurate reference interpreter for RDNA2 VALU v_ldexp_f32. - - Computes: D = S0 * 2^S1 - where S0 is binary32 float bits and S1 is signed 32-bit integer exponent. - - Parameters: - src0_bits: 32-bit binary32 float word. - src1_i32: 32-bit integer exponent (evaluated as signed 32-bit two's complement). - flush_denorms: If True (FTZ/DAZ mode), subnormal inputs flush to sign-preserved - zero before scaling, and subnormal results flush to sign-preserved zero. - If False (IEEE preserve mode), subnormals are scaled per IEEE 754. - clamp: If True, result is clamped to [0.0, 1.0] (AMD clamp modifier). - NaN clamps to 0.0, negative to 0.0, values > 1.0 to 1.0. - abs_src0: If True, operand S0 is forced positive before scaling. - neg_src0: If True, operand S0 sign bit is flipped before scaling. - """ - src0_bits &= MASK32 - scale = s32(src1_i32) - - if abs_src0: - src0_bits &= ~SIGN_MASK - if neg_src0: - src0_bits ^= SIGN_MASK - - sign = (src0_bits >> 31) & 1 - exp_field = (src0_bits >> 23) & 0xFF - mant_field = src0_bits & MANT_MASK - - # 1. NaN operand handling - if exp_field == 0xFF and mant_field != 0: - if clamp: - return POS_ZERO - return QNAN - - # 2. Infinity operand handling - if exp_field == 0xFF and mant_field == 0: - if clamp: - return POS_ZERO if sign else ONE - return src0_bits - - # 3. Zero operand handling (+0.0 or -0.0) - if exp_field == 0 and mant_field == 0: - if clamp and sign: - return POS_ZERO - return src0_bits - - # 4. Denormal input handling - if exp_field == 0: - if flush_denorms: - res = sign << 31 - return POS_ZERO if (clamp and sign) else res - F = mant_field - E = -126 - shift_left = 23 - (F.bit_length() - 1) - F = F << shift_left - E = E - shift_left - else: - E = exp_field - 127 - F = (1 << 23) | mant_field - - # 5. Add scale to unbiased exponent - E_scaled = E + scale - target_exp = E_scaled + 127 - - # 6. Overflow detection (> max finite binary32 float) - if target_exp >= 255: - if clamp: - return POS_ZERO if sign else ONE - return (sign << 31) | POS_INF - - # 7. Normal float range - if target_exp >= 1: - res = (sign << 31) | (target_exp << 23) | (F & MANT_MASK) - if clamp: - if sign: - return POS_ZERO - if res > ONE: - return ONE - return res - - # 8. Underflow / Subnormal range - if flush_denorms: - res = sign << 31 - return POS_ZERO if (clamp and sign) else res - - shift_right = 1 - target_exp - if shift_right >= 26: - res = sign << 31 - return POS_ZERO if (clamp and sign) else res - - q = F >> shift_right - rem = F & ((1 << shift_right) - 1) - half = 1 << (shift_right - 1) - - # IEEE 754 round-to-nearest, ties-to-even - if rem > half or (rem == half and (q & 1)): - q += 1 - - if q >= (1 << 23): - res = (sign << 31) | (1 << 23) - else: - res = (sign << 31) | q - - if clamp: - if sign: - return POS_ZERO - if res > ONE: - return ONE - return res - - -def ref_ldexp_f32_rational( - src0_bits: int, - src1_i32: int, - *, - flush_denorms: bool = False, - clamp: bool = False, -) -> int: - """Exact rational Fraction reference oracle for ldexp exponent scaling.""" - src0_bits &= MASK32 - scale = s32(src1_i32) - sign = (src0_bits >> 31) & 1 - exp_field = (src0_bits >> 23) & 0xFF - mant_field = src0_bits & MANT_MASK - - if exp_field == 0xFF: - if mant_field != 0: - return POS_ZERO if clamp else QNAN - if clamp: - return POS_ZERO if sign else ONE - return src0_bits - - if exp_field == 0 and mant_field == 0: - if clamp and sign: - return POS_ZERO - return src0_bits - - if exp_field == 0: - if flush_denorms: - res = sign << 31 - return POS_ZERO if (clamp and sign) else res - val = Fraction(mant_field, 1 << 149) - else: - unbiased_e = exp_field - 127 - val = Fraction((1 << 23) | mant_field, 1 << 23) * (Fraction(2) ** unbiased_e) - - if scale > 300: - if clamp: - return POS_ZERO if sign else ONE - return (sign << 31) | POS_INF - elif scale < -300: - res = sign << 31 - return POS_ZERO if (clamp and sign) else res - - val = val * (Fraction(2) ** scale) - - min_normal_frac = Fraction(1, 1 << 126) - if flush_denorms and val < min_normal_frac: - res = sign << 31 - return POS_ZERO if (clamp and sign) else res - - if val >= min_normal_frac: - e = val.numerator.bit_length() - val.denominator.bit_length() - while val < Fraction(2) ** e: - e -= 1 - while val >= Fraction(2) ** (e + 1): - e += 1 - if e > 127: - if clamp: - return POS_ZERO if sign else ONE - return (sign << 31) | POS_INF - scaled = val / (Fraction(2) ** (e - 23)) - q, r = divmod(scaled.numerator, scaled.denominator) - if 2 * r > scaled.denominator or (2 * r == scaled.denominator and (q & 1)): - q += 1 - if q >= (1 << 24): - q >>= 1 - e += 1 - if e > 127: - if clamp: - return POS_ZERO if sign else ONE - return (sign << 31) | POS_INF - res = (sign << 31) | ((e + 127) << 23) | (q & MANT_MASK) - else: - scaled = val * (Fraction(2) ** 149) - q, r = divmod(scaled.numerator, scaled.denominator) - if 2 * r > scaled.denominator or (2 * r == scaled.denominator and (q & 1)): - q += 1 - if q >= (1 << 23): - res = (sign << 31) | (1 << 23) - else: - res = (sign << 31) | q - - if clamp: - if sign: - return POS_ZERO - if res > ONE: - return ONE - return res - - -class TestLdexpF32NormalScaling(unittest.TestCase): - """Verifies standard IEEE 754 exponent scaling for normal float numbers.""" - - def test_identity_exponent_zero(self): - vectors = [ - ONE, # 1.0f - TWO, # 2.0f - HALF, # 0.5f - 0x40200000, # 2.5f - 0x42280000, # 42.0f - 0xBF800000, # -1.0f - 0xC0000000, # -2.0f - 0xBF000000, # -0.5f - MAX_FINITE, # max normal - MIN_NORMAL, # min normal - ] - for src in vectors: - with self.subTest(src=f"0x{src:08x}"): - self.assertEqual(interp_v_ldexp_f32(src, 0), src) - - def test_power_of_two_scaling(self): - for k in range(-126, 128): - with self.subTest(scale=k): - got = interp_v_ldexp_f32(ONE, k) - if k == 127: - self.assertEqual(got, 0x7F000000) - elif k == -126: - self.assertEqual(got, MIN_NORMAL) - else: - expected_exp = 127 + k - self.assertEqual(got, expected_exp << 23) - - def test_multiply_by_two_and_half_equivalences(self): - test_floats = [1.0, 1.5, 3.75, 10.0, 128.5, -4.25, -100.0] - for val in test_floats: - with self.subTest(val=val): - b = f32_to_bits(val) - # scale by +1 must equal val * 2.0 - times_two = interp_v_ldexp_f32(b, 1) - self.assertEqual(times_two, f32_to_bits(val * 2.0)) - # scale by -1 must equal val * 0.5 - times_half = interp_v_ldexp_f32(b, -1) - self.assertEqual(times_half, f32_to_bits(val * 0.5)) - - def test_scale_composition_and_inverse(self): - val = 0x41480000 # 12.5f - for a, b in [(1, 2), (3, -2), (-5, 4), (10, -10), (15, -8)]: - with self.subTest(a=a, b=b): - step1 = interp_v_ldexp_f32(val, a) - step2 = interp_v_ldexp_f32(step1, b) - composed = interp_v_ldexp_f32(val, a + b) - self.assertEqual(step2, composed) - - # Inverse identity: ldexp(ldexp(x, k), -k) == x - for k in [1, 2, 5, 10, 20]: - with self.subTest(k=k): - scaled = interp_v_ldexp_f32(val, k) - recovered = interp_v_ldexp_f32(scaled, -k) - self.assertEqual(recovered, val) - - def test_cross_check_with_python_math_ldexp(self): - samples = [ - (1.0, 3), - (2.75, -2), - (0.125, 4), - (-3.5, 2), - (-0.0625, 5), - (12345.0, -3), - ] - for val, sc in samples: - with self.subTest(val=val, sc=sc): - b = f32_to_bits(val) - got = interp_v_ldexp_f32(b, sc) - expected_py = f32_to_bits(math.ldexp(val, sc)) - self.assertEqual(got, expected_py) - - -class TestLdexpF32DenormalPreserve(unittest.TestCase): - """Verifies IEEE 754 gradual underflow and denormal preservation.""" - - def test_scaling_into_subnormal_range(self): - # MIN_NORMAL is 2^-126 (0x00800000) - self.assertEqual(interp_v_ldexp_f32(MIN_NORMAL, -1, flush_denorms=False), 0x00400000) # 2^-127 - self.assertEqual(interp_v_ldexp_f32(MIN_NORMAL, -2, flush_denorms=False), 0x00200000) # 2^-128 - self.assertEqual(interp_v_ldexp_f32(MIN_NORMAL, -23, flush_denorms=False), MIN_SUBNORMAL) # 2^-149 - - def test_subnormal_round_half_even_tie_breaking(self): - # 1.0f * 2^-150 = 0.5 * 2^-149: exact tie, q=0 is even -> rounds to 0 - self.assertEqual(interp_v_ldexp_f32(ONE, -150, flush_denorms=False), POS_ZERO) - - # 1.5f (0x3FC00000) * 2^-150 = 0.75 * 2^-149: > 0.5 -> rounds up to 1 (0x00000001) - self.assertEqual(interp_v_ldexp_f32(0x3FC00000, -150, flush_denorms=False), MIN_SUBNORMAL) - - # 2.5f (0x40200000) * 2^-150 = 1.25 * 2^-149: fractional part 0.25 < 0.5 -> rounds to 1 (0x00000001) - self.assertEqual(interp_v_ldexp_f32(0x40200000, -150, flush_denorms=False), MIN_SUBNORMAL) - - # 3.0f (0x40400000) * 2^-150 = 1.5 * 2^-149: exact tie with q=1 (odd) -> rounds to even q=2 (0x00000002) - self.assertEqual(interp_v_ldexp_f32(0x40400000, -150, flush_denorms=False), 0x00000002) - - def test_subnormal_input_promoted_to_normal(self): - # MIN_SUBNORMAL (2^-149) scaled up: - # 2^-149 * 2^23 = 2^-126 = MIN_NORMAL - self.assertEqual(interp_v_ldexp_f32(MIN_SUBNORMAL, 23, flush_denorms=False), MIN_NORMAL) - # 2^-149 * 2^24 = 2^-125 - self.assertEqual(interp_v_ldexp_f32(MIN_SUBNORMAL, 24, flush_denorms=False), 0x01000000) - # 2^-149 * 2^149 = 1.0f - self.assertEqual(interp_v_ldexp_f32(MIN_SUBNORMAL, 149, flush_denorms=False), ONE) - # 2^-149 * 2^150 = 2.0f - self.assertEqual(interp_v_ldexp_f32(MIN_SUBNORMAL, 150, flush_denorms=False), TWO) - # 2^-149 * 2^276 = 2^127 - self.assertEqual(interp_v_ldexp_f32(MIN_SUBNORMAL, 276, flush_denorms=False), 0x7F000000) - # 2^-149 * 2^277 = 2^128 -> overflow to +inf - self.assertEqual(interp_v_ldexp_f32(MIN_SUBNORMAL, 277, flush_denorms=False), POS_INF) - - def test_subnormal_sign_preservation(self): - neg_min_sub = SIGN_MASK | MIN_SUBNORMAL - self.assertEqual(interp_v_ldexp_f32(neg_min_sub, 0, flush_denorms=False), neg_min_sub) - self.assertEqual(interp_v_ldexp_f32(neg_min_sub, 23, flush_denorms=False), SIGN_MASK | MIN_NORMAL) - self.assertEqual(interp_v_ldexp_f32(neg_min_sub, 149, flush_denorms=False), 0xBF800000) # -1.0f - # Underflow below min subnormal retains negative zero - self.assertEqual(interp_v_ldexp_f32(neg_min_sub, -10, flush_denorms=False), NEG_ZERO) - - -class TestLdexpF32DenormalFlushing(unittest.TestCase): - """Verifies FTZ/DAZ denormal flushing mode.""" - - def test_input_denormals_flushed_to_zero(self): - denorm_inputs = [ - MIN_SUBNORMAL, - MAX_SUBNORMAL, - 0x00000100, - 0x00012345, - 0x00400000, - SIGN_MASK | MIN_SUBNORMAL, - SIGN_MASK | MAX_SUBNORMAL, - ] - for src in denorm_inputs: - sign = src & SIGN_MASK - expected = NEG_ZERO if sign else POS_ZERO - for sc in [-10, 0, 1, 23, 100]: - with self.subTest(src=f"0x{src:08x}", sc=sc): - got = interp_v_ldexp_f32(src, sc, flush_denorms=True) - self.assertEqual(got, expected) - - def test_output_denormals_flushed_to_zero(self): - # Scaling normal floats into subnormal range flushes to zero - self.assertEqual(interp_v_ldexp_f32(ONE, -127, flush_denorms=True), POS_ZERO) - self.assertEqual(interp_v_ldexp_f32(0xBF800000, -127, flush_denorms=True), NEG_ZERO) # -1.0f - self.assertEqual(interp_v_ldexp_f32(MIN_NORMAL, -1, flush_denorms=True), POS_ZERO) - self.assertEqual(interp_v_ldexp_f32(SIGN_MASK | MIN_NORMAL, -1, flush_denorms=True), NEG_ZERO) - - def test_flush_vs_preserve_contrast(self): - # Exact same operands give subnormal in preserve mode but zero in flush mode - cases = [ - (ONE, -127, 0x00400000), - (0xBF800000, -127, SIGN_MASK | 0x00400000), - (MIN_NORMAL, -1, 0x00400000), - (ONE, -149, MIN_SUBNORMAL), - ] - for src, sc, preserved_res in cases: - with self.subTest(src=f"0x{src:08x}", sc=sc): - self.assertEqual(interp_v_ldexp_f32(src, sc, flush_denorms=False), preserved_res) - expected_flushed = NEG_ZERO if (src & SIGN_MASK) else POS_ZERO - self.assertEqual(interp_v_ldexp_f32(src, sc, flush_denorms=True), expected_flushed) - - -class TestLdexpF32Overflow(unittest.TestCase): - """Verifies IEEE 754 overflow handling and positive exponent limits.""" - - def test_max_finite_float_overflow(self): - # MAX_FINITE (0x7F7FFFFF) scaled by 0 is MAX_FINITE - self.assertEqual(interp_v_ldexp_f32(MAX_FINITE, 0), MAX_FINITE) - # Scaled by +1 overflows to +inf - self.assertEqual(interp_v_ldexp_f32(MAX_FINITE, 1), POS_INF) - # Scaled by +2 overflows to +inf - self.assertEqual(interp_v_ldexp_f32(MAX_FINITE, 2), POS_INF) - - # Negative max float (-MAX_FINITE = 0xFF7FFFFF) - neg_max = SIGN_MASK | MAX_FINITE - self.assertEqual(interp_v_ldexp_f32(neg_max, 0), neg_max) - self.assertEqual(interp_v_ldexp_f32(neg_max, 1), NEG_INF) - - def test_exponents_exceeding_max_finite_range(self): - # 1.0f * 2^127 is max normal power of 2 (0x7F000000) - self.assertEqual(interp_v_ldexp_f32(ONE, 127), 0x7F000000) - # 1.0f * 2^128 overflows to +inf - self.assertEqual(interp_v_ldexp_f32(ONE, 128), POS_INF) - self.assertEqual(interp_v_ldexp_f32(ONE, 129), POS_INF) - self.assertEqual(interp_v_ldexp_f32(0xBF800000, 128), NEG_INF) - - def test_extreme_positive_integers(self): - extreme_exponents = [255, 256, 1000, 65536, 0x7FFFFFFF] - for exp_val in extreme_exponents: - with self.subTest(exp_val=exp_val): - self.assertEqual(interp_v_ldexp_f32(ONE, exp_val), POS_INF) - self.assertEqual(interp_v_ldexp_f32(0xBF800000, exp_val), NEG_INF) - - def test_clamped_overflow(self): - # Under clamp modifier, overflow clamps to 1.0f (or 0.0f for negative) - self.assertEqual(interp_v_ldexp_f32(ONE, 128, clamp=True), ONE) - self.assertEqual(interp_v_ldexp_f32(ONE, 0x7FFFFFFF, clamp=True), ONE) - self.assertEqual(interp_v_ldexp_f32(0xBF800000, 128, clamp=True), POS_ZERO) - self.assertEqual(interp_v_ldexp_f32(0xBF800000, 0x7FFFFFFF, clamp=True), POS_ZERO) - - -class TestLdexpF32Underflow(unittest.TestCase): - """Verifies IEEE 754 underflow handling and negative exponent limits.""" - - def test_gradual_underflow_to_zero(self): - # 1.0f * 2^-151 underflows to zero (both preserve and flush) - self.assertEqual(interp_v_ldexp_f32(ONE, -151, flush_denorms=False), POS_ZERO) - self.assertEqual(interp_v_ldexp_f32(ONE, -151, flush_denorms=True), POS_ZERO) - self.assertEqual(interp_v_ldexp_f32(0xBF800000, -151, flush_denorms=False), NEG_ZERO) - self.assertEqual(interp_v_ldexp_f32(0xBF800000, -151, flush_denorms=True), NEG_ZERO) - - def test_extreme_negative_integers(self): - extreme_neg_exponents = [-255, -256, -1000, -65536, -0x80000000] - for exp_val in extreme_neg_exponents: - with self.subTest(exp_val=exp_val): - self.assertEqual(interp_v_ldexp_f32(ONE, exp_val), POS_ZERO) - self.assertEqual(interp_v_ldexp_f32(0xBF800000, exp_val), NEG_ZERO) - - def test_underflow_sign_preservation(self): - # Negative float underflowing retains negative sign bit (NEG_ZERO) - self.assertEqual(interp_v_ldexp_f32(0xBF800000, -200), NEG_ZERO) - self.assertEqual(interp_v_ldexp_f32(SIGN_MASK | MIN_NORMAL, -100), NEG_ZERO) - - -class TestLdexpF32SpecialValues(unittest.TestCase): - """Verifies handling of special IEEE 754 inputs (+0, -0, +inf, -inf, NaN).""" - - def test_zeros(self): - exps = [-1000, -1, 0, 1, 1000, 0x7FFFFFFF, -0x80000000] - for sc in exps: - with self.subTest(sc=sc): - self.assertEqual(interp_v_ldexp_f32(POS_ZERO, sc), POS_ZERO) - self.assertEqual(interp_v_ldexp_f32(NEG_ZERO, sc), NEG_ZERO) - - def test_infinities(self): - exps = [-1000, -1, 0, 1, 1000, 0x7FFFFFFF, -0x80000000] - for sc in exps: - with self.subTest(sc=sc): - self.assertEqual(interp_v_ldexp_f32(POS_INF, sc), POS_INF) - self.assertEqual(interp_v_ldexp_f32(NEG_INF, sc), NEG_INF) - - def test_nans(self): - nan_inputs = [QNAN, SNAN, 0x7F800042, SIGN_MASK | QNAN, SIGN_MASK | SNAN] - for nan_val in nan_inputs: - for sc in [-10, 0, 10]: - with self.subTest(nan_val=f"0x{nan_val:08x}", sc=sc): - res = interp_v_ldexp_f32(nan_val, sc) - self.assertTrue(is_nan(res)) - self.assertEqual(res, QNAN) - - def test_clamp_with_special_values(self): - # NaN clamps to 0.0 - self.assertEqual(interp_v_ldexp_f32(QNAN, 0, clamp=True), POS_ZERO) - self.assertEqual(interp_v_ldexp_f32(SNAN, 5, clamp=True), POS_ZERO) - # +Inf clamps to 1.0f - self.assertEqual(interp_v_ldexp_f32(POS_INF, 0, clamp=True), ONE) - # -Inf clamps to 0.0f - self.assertEqual(interp_v_ldexp_f32(NEG_INF, 0, clamp=True), POS_ZERO) - # -0.0 clamps to +0.0 - self.assertEqual(interp_v_ldexp_f32(NEG_ZERO, 0, clamp=True), POS_ZERO) - - -class TestLdexpF32Modifiers(unittest.TestCase): - """Verifies VALU input and output modifiers (abs, neg, clamp).""" - - def test_abs_modifier(self): - # abs(|src0|) clears sign bit before scaling - self.assertEqual(interp_v_ldexp_f32(0xBF800000, 1, abs_src0=True), TWO) # |-1.0| * 2 = 2.0 - self.assertEqual(interp_v_ldexp_f32(NEG_INF, 0, abs_src0=True), POS_INF) - self.assertEqual(interp_v_ldexp_f32(NEG_ZERO, 0, abs_src0=True), POS_ZERO) - - def test_neg_modifier(self): - # neg(-src0) flips sign bit before scaling - self.assertEqual(interp_v_ldexp_f32(ONE, 1, neg_src0=True), 0xC0000000) # -(1.0) * 2 = -2.0 - self.assertEqual(interp_v_ldexp_f32(0xBF800000, 1, neg_src0=True), TWO) # -(-1.0) * 2 = 2.0 - - def test_clamp_modifier_normal_range(self): - # Values in [0.0, 1.0] pass through unmodified - self.assertEqual(interp_v_ldexp_f32(HALF, 0, clamp=True), HALF) - # Values > 1.0 clamp to 1.0 - self.assertEqual(interp_v_ldexp_f32(ONE, 1, clamp=True), ONE) # 2.0 -> 1.0 - self.assertEqual(interp_v_ldexp_f32(0x40200000, 0, clamp=True), ONE) # 2.5 -> 1.0 - # Negative values clamp to 0.0 - self.assertEqual(interp_v_ldexp_f32(0xBF800000, 0, clamp=True), POS_ZERO) # -1.0 -> 0.0 - - -class TestLdexpF32DualOracleEquivalence(unittest.TestCase): - """Cross-checks the bit-level VALU model against the exact rational Fraction oracle.""" - - def test_exhaustive_oracle_equivalence_vector_suite(self): - rng = random.Random(0x1337BEEF) - - # Diverse test bank including boundaries, subnormals, normal powers, and specials - fixed_bases = [ - POS_ZERO, NEG_ZERO, POS_INF, NEG_INF, QNAN, SNAN, - ONE, TWO, HALF, 0xBF800000, 0xC0000000, 0xBF000000, - MAX_FINITE, SIGN_MASK | MAX_FINITE, - MIN_NORMAL, SIGN_MASK | MIN_NORMAL, - MAX_SUBNORMAL, SIGN_MASK | MAX_SUBNORMAL, - MIN_SUBNORMAL, SIGN_MASK | MIN_SUBNORMAL, - 0x3FC00000, # 1.5 - 0x40400000, # 3.0 - 0x40200000, # 2.5 - ] - - fixed_scales = [ - -0x80000000, -1000, -300, -151, -150, -149, -127, -126, -24, -23, -2, -1, - 0, 1, 2, 23, 24, 126, 127, 128, 149, 150, 276, 277, 300, 1000, 0x7FFFFFFF, - ] - - for base in fixed_bases: - for sc in fixed_scales: - for flush in (False, True): - with self.subTest(base=f"0x{base:08x}", sc=sc, flush=flush): - r_bits = interp_v_ldexp_f32(base, sc, flush_denorms=flush) - r_frac = ref_ldexp_f32_rational(base, sc, flush_denorms=flush) - self.assertEqual(r_bits, r_frac) - - # 500 randomized cases - for _ in range(500): - base = rng.randint(0, MASK32) - sc = rng.choice(fixed_scales + [rng.randint(-200, 200) for _ in range(5)]) - flush = rng.choice([False, True]) - clamp = rng.choice([False, True]) - with self.subTest(base=f"0x{base:08x}", sc=sc, flush=flush, clamp=clamp): - r_bits = interp_v_ldexp_f32(base, sc, flush_denorms=flush, clamp=clamp) - r_frac = ref_ldexp_f32_rational(base, sc, flush_denorms=flush, clamp=clamp) - self.assertEqual(r_bits, r_frac) - - -class TestSpirvLdexpConstruct(unittest.TestCase): - """Verifies interpreter rejection of unmodelled GLSL Ldexp extension opcode.""" - - def test_spirv_mini_interp_rejects_raw_ldexp_extension(self): - # GLSL.std.450 OpExtInst Ldexp is not directly modelled in spirv_mini_interp.py - # and must be cleanly rejected with UnsupportedConstruct - module = """\ -OpCapability Shader -%glsl = OpExtInstImport "GLSL.std.450" -OpMemoryModel Logical GLSL450 -OpEntryPoint Fragment %main "main" %out -%void = OpTypeVoid -%fn = OpTypeFunction %void -%float = OpTypeFloat 32 -%int = OpTypeInt 32 1 -%_ptr_Output_float = OpTypePointer Output %float -%out = OpVariable %_ptr_Output_float Output -%f1 = OpConstant %float 1.0 -%i2 = OpConstant %int 2 -%main = OpFunction %void None %fn -%entry = OpLabel -%res = OpExtInst %float %glsl Ldexp %f1 %i2 -OpStore %out %res -OpReturn -OpFunctionEnd -""" - with self.assertRaises(si.UnsupportedConstruct): - si.run_fragment(module) - - -class TestNegativeControls(unittest.TestCase): - """Negative controls ensuring mutated semantics fail test assertions.""" - - def test_missing_overflow_fails(self): - # Mutated interpreter that wraps or clamps to MAX_FINITE instead of emitting POS_INF - def bad_overflow(src, sc): - res = interp_v_ldexp_f32(src, sc) - return MAX_FINITE if res == POS_INF else res - - self.assertNotEqual(bad_overflow(ONE, 128), POS_INF) - - def test_missing_denormal_flush_fails(self): - # Mutated interpreter that forgets to flush subnormal output when flush_denorms=True - def bad_flush(src, sc): - return interp_v_ldexp_f32(src, sc, flush_denorms=False) - - # Scaling MIN_NORMAL by -1 in flush mode must be POS_ZERO, not 0x00400000 - self.assertNotEqual(bad_flush(MIN_NORMAL, -1), POS_ZERO) - - def test_missing_round_to_even_tie_breaking_fails(self): - # Mutated interpreter that rounds 1.0f * 2^-150 up to 1 instead of down to 0 - def bad_round(src, sc): - res = interp_v_ldexp_f32(src, sc, flush_denorms=False) - return 1 if (src == ONE and sc == -150) else res - - self.assertNotEqual(bad_round(ONE, -150), POS_ZERO) - - def test_missing_negative_zero_sign_fails(self): - # Mutated interpreter that produces POS_ZERO on underflow of negative numbers - def bad_sign(src, sc): - res = interp_v_ldexp_f32(src, sc) - return POS_ZERO if res == NEG_ZERO else res - - self.assertNotEqual(bad_sign(0xBF800000, -200), NEG_ZERO) - - def test_treating_scale_as_unsigned_fails(self): - # 0xFFFFFFFF passed as scale represents -1 in two's complement. - # If treated as unsigned +4294967295, it would overflow instead of scaling by 0.5. - got = interp_v_ldexp_f32(ONE, 0xFFFFFFFF) - self.assertEqual(got, HALF) - self.assertNotEqual(got, POS_INF) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_alu_ldexp_f64.py b/tests/semantic/test_alu_ldexp_f64.py deleted file mode 100644 index 375dc353a..000000000 --- a/tests/semantic/test_alu_ldexp_f64.py +++ /dev/null @@ -1,411 +0,0 @@ -"""Semantic interpreter, capability, and spirv-val tests for RDNA2 v_ldexp_f64. - -v_ldexp_f64 computes D.f64 = S0.f64 * 2^(S1.i32) on the (lo, hi) dword pair using pure 32-bit -integer operations (no OpCapability Float64 or OpCapability Int64, even with clamp). - -Hardware-measured on AMD Radeon RDNA2 iGPU (gfx1036, wave32 & wave64, game MODE: ieee=0, -dx10_clamp=1, denorm32=0, denorm16_64=3): -- +-0, +-inf, and both quiet and signalling NaNs pass through bit-for-bit unchanged (after S0 abs/neg). -- Subnormal inputs are normalized before scaling; subnormal outputs shift right by 1 - e2 (1..53) - and round to nearest even (carry into bit 52 yields +-min_norm; sh >= 54 flushes to +-0). -- VOP3 clamp applies in both denorm16_64=3 and 0 (dx10_clamp=1: NaN, -0.0, <0 -> +0.0; >1.0 -> 1.0). -- VOP3 omod (mul:2, mul:4, div:2) is ignored on hardware when denorm16_64=3 and active when 0, - so the translator rejects it as Unsupported. -- RDNA2 places 32-bit literal S0 constants (outside inline -16..64) in bits [63:32] with [31:0] = 0. -""" -import os -import random -import shutil -import struct -import subprocess -import sys -import tempfile -import unittest -import warnings - -HERE = os.path.dirname(os.path.abspath(__file__)) -ROOT = os.path.dirname(os.path.dirname(HERE)) -TOOLS_DIR = os.environ.get("LEONIDA_TOOLS_DIR") or os.path.join(ROOT, "tools") - -sys.dont_write_bytecode = True -sys.path.insert(0, TOOLS_DIR) -sys.path.insert(0, HERE) - -import rdna2spirv # noqa: E402 -import spirv_asm # noqa: E402 -import spirv_mini_interp as si # noqa: E402 - -STUB_DXBC = b"DXBC" + bytes(24) + struct.pack(" int: - return struct.unpack(" int: - """Exact bit-level reference matching gfx1036 game MODE (ieee=0, dx10_clamp=1, denorm16_64=3).""" - u &= 0xFFFFFFFFFFFFFFFF - if mod in ("abs", "negabs"): - u &= 0x7FFFFFFFFFFFFFFF - if mod in ("neg", "negabs"): - u ^= 0x8000000000000000 - s1 &= 0xFFFFFFFF - if s1 >= 0x80000000: - s1 -= 0x100000000 - sgn = u & (1 << 63) - e = (u >> 52) & 0x7FF - mant = u & ((1 << 52) - 1) - if e == 0x7FF or (e == 0 and mant == 0): - res = u - else: - if e == 0: - msb = mant.bit_length() - 1 - lsh = 52 - msb - sig = mant << lsh - ef = 1 - lsh - else: - sig = (1 << 52) | mant - ef = e - nc = max(-4096, min(4096, s1)) - e2 = ef + nc - if e2 >= 2047: - res = sgn | POS_INF - elif e2 >= 1: - res = sgn | (e2 << 52) | (sig & ((1 << 52) - 1)) - else: - sh = 1 - e2 - if sh >= 54: - res = sgn - else: - q = sig >> sh - rem = sig & ((1 << sh) - 1) - half = 1 << (sh - 1) - if rem > half or (rem == half and (q & 1)): - q += 1 - res = sgn | q - if clamp: - re = (res >> 52) & 0x7FF - rm = res & ((1 << 52) - 1) - is_nan = (re == 0x7FF) and (rm != 0) - if is_nan or (res >> 63): - res = 0 - elif res > ONE: - res = ONE - return res - - -_TMP_DIR = None -_SRC_PATH = None -_TEMPLATES = {} - - -def setUpModule(): - global _TMP_DIR, _SRC_PATH, _TEMPLATES - _TMP_DIR = tempfile.TemporaryDirectory() - disasm_dir = os.path.join(_TMP_DIR.name, "disasm") - os.mkdir(disasm_dir) - _SRC_PATH = os.path.join(disasm_dir, "ps_ldexp_f64.s") - with open(os.path.join(_TMP_DIR.name, "ps_ldexp_f64.dxbc"), "wb") as f: - f.write(STUB_DXBC) - _TEMPLATES = {} - - -def tearDownModule(): - global _TMP_DIR, _TEMPLATES - _TEMPLATES = {} - if _TMP_DIR is not None: - _TMP_DIR.cleanup() - _TMP_DIR = None - - -def translate_lines(lines): - if _TMP_DIR is None: - setUpModule() - asm = ( - "; test_ldexp_f64\n" - + "".join(f"\t{ln}\n" for ln in lines) - + "\texp mrt0 v0, v1, v2, v3 done vm\n\ts_endpgm\n" - ) - with open(_SRC_PATH, "w", encoding="utf-8") as f: - f.write(asm) - with warnings.catch_warnings(): - warnings.simplefilter("ignore", ResourceWarning) - return rdna2spirv.translate(_SRC_PATH) - - -def validate_spirv(spv_text: str): - spirv_asm.assemble(spv_text) - spirv_as = shutil.which("spirv-as") - spirv_val = shutil.which("spirv-val") - if not spirv_as or not spirv_val: - return - with tempfile.TemporaryDirectory() as d: - asm_p = os.path.join(d, "s.spvasm") - bin_p = os.path.join(d, "s.spv") - with open(asm_p, "w", encoding="utf-8") as f: - f.write(spv_text) - r1 = subprocess.run([spirv_as, "--target-env", "vulkan1.2", asm_p, "-o", bin_p], capture_output=True, text=True) - if r1.returncode != 0: - raise AssertionError(f"spirv-as failed: {r1.stderr}") - r2 = subprocess.run([spirv_val, "--target-env", "vulkan1.2", bin_p], capture_output=True, text=True) - if r2.returncode != 0: - raise AssertionError(f"spirv-val failed: {r2.stderr}") - - -def fmt_src0(reg: str, mod: str) -> str: - if mod == "neg": - return f"-{reg}" - if mod == "abs": - return f"|{reg}|" - if mod == "negabs": - return f"-|{reg}|" - return reg - - -def get_template(mod: str, clamp: bool) -> str: - key = (mod, clamp) - if key not in _TEMPLATES: - s0 = fmt_src0("v[2:3]", mod) - cl = " clamp" if clamp else "" - spv = translate_lines([ - f"v_mov_b32 v2, {SENT_LO:#x}", - f"v_mov_b32 v3, {SENT_HI:#x}", - f"v_mov_b32 v4, {SENT_E:#x}", - "v_mov_b32 v0, 0", - "v_mov_b32 v1, 0", - f"v_ldexp_f64 v[0:1], {s0}, v4{cl}", - ]) - _TEMPLATES[key] = spv - return _TEMPLATES[key] - - -def eval_ldexp(u: int, s1: int, mod: str = "", clamp: bool = False) -> int: - lo = u & 0xFFFFFFFF - hi = (u >> 32) & 0xFFFFFFFF - eu = s1 & 0xFFFFFFFF - spv = ( - get_template(mod, clamp) - .replace(f"OpConstant %uint {SENT_LO}\n", f"OpConstant %uint {lo}\n") - .replace(f"OpConstant %uint {SENT_HI}\n", f"OpConstant %uint {hi}\n") - .replace(f"OpConstant %uint {SENT_E}\n", f"OpConstant %uint {eu}\n") - ) - out = si.run_fragment(spv)["%out_mrt0"] - return (out[1] << 32) | out[0] - - -def run_lines(lines) -> int: - spv = translate_lines(lines) - validate_spirv(spv) - out = si.run_fragment(spv)["%out_mrt0"] - return (out[1] << 32) | out[0] - - -class LdexpF64Tests(unittest.TestCase): - def test_capabilities_and_spirv_val(self): - """Pure 32-bit integer lowering must emit neither Float64 nor Int64, even with clamp.""" - for mod in ("", "neg", "abs", "negabs"): - for cl in (False, True): - spv = get_template(mod, cl) - self.assertNotIn("OpCapability Float64", spv) - self.assertNotIn("OpCapability Int64", spv) - validate_spirv(spv) - - def test_hw_measured_specials(self): - """+-0, +-inf, and quiet/signalling NaNs pass through bit-for-bit unchanged (gfx1036, ieee=0).""" - for u in (POS_ZERO, NEG_ZERO, POS_INF, NEG_INF, QNAN, NQNAN, SNAN, NSNAN): - for e in (0, 1, -1, 1024, -1024, 0x7FFFFFFF, -0x80000000): - with self.subTest(u=hex(u), e=e): - self.assertEqual(eval_ldexp(u, e), u) - - def test_hw_measured_subnormal_inputs(self): - """Subnormal inputs at every bit 0..51 normalize before scaling (gfx1036, denorm16_64=3).""" - for bit in range(52): - u = 1 << bit - self.assertEqual(eval_ldexp(u, 52 - bit), MIN_NORM) - self.assertEqual(eval_ldexp(u, 1074 - bit), ONE) - self.assertEqual(eval_ldexp(u | (1 << 63), 52 - bit), MIN_NORM | (1 << 63)) - self.assertEqual(eval_ldexp(u, 2097 - bit), 0x7FE0000000000000) - self.assertEqual(eval_ldexp(u, 2098 - bit), POS_INF) - - def test_hw_measured_subnormal_outputs_and_ties(self): - """Subnormal outputs round to nearest even across shifts 1..54, including carry into min_norm.""" - # Pinned hardware-measured cases from gfx1036: - pinned = [ - (MIN_SUB, -1, POS_ZERO), - (3 * MIN_SUB, -1, 2 * MIN_SUB), # exact tie -> even - (5 * MIN_SUB, -2, 1 * MIN_SUB), - (6 * MIN_SUB, -2, 2 * MIN_SUB), # exact tie -> even - (7 * MIN_SUB, -2, 2 * MIN_SUB), - (ONE, -1075, POS_ZERO), # sh=53 exact tie -> 0 (even) - (ONE | 1, -1075, MIN_SUB), # sh=53 > half -> min_sub - (ONE | (1 << 63) | 1, -1075, MIN_SUB | (1 << 63)), - (MAX_FIN, -2098, MIN_SUB), # sh=53 rounds up to min_sub - (MAX_FIN, -2099, POS_ZERO), # sh=54 flushes to +0.0 - (MAX_FIN | (1 << 63), -2099, NEG_ZERO), - (0x3FFFFFFFFFFFFFFF, -1023, MIN_NORM), # sh=1 carry into min_norm - (0xBFFFFFFFFFFFFFFF, -1023, MIN_NORM | (1 << 63)), - ] - for u, e, want in pinned: - with self.subTest(u=hex(u), e=e): - self.assertEqual(eval_ldexp(u, e), want) - - # Sweep every shift boundary sh = 1..54 (ties to even, ties to odd, above half). - for sh in range(1, 55): - e = -1022 - sh - test_vals = [ONE, 0x3FFFFFFFFFFFFFFF] - if sh <= 52: - half_bit = 1 << (sh - 1) - lsb_bit = 1 << sh - base_even = half_bit - base_odd = lsb_bit | half_bit - test_vals.extend([ - ONE | base_even, - ONE | base_odd, - ONE | base_even | 1, - ONE | (1 << 63) | base_odd, - ]) - for u in test_vals: - self.assertEqual(eval_ldexp(u, e), ref_ldexp_f64(u, e)) - - def test_hw_measured_abs_neg_clamp(self): - """VOP3 abs, neg, and DX10 clamp match gfx1036 bit-for-bit.""" - inputs = [ - (d2u(0.5), 0), (d2u(-0.5), 0), (ONE, 0), (ONE, 1), - (POS_ZERO, 0), (NEG_ZERO, 0), (POS_INF, 0), (NEG_INF, 0), - (QNAN, 0), (NQNAN, 0), (SNAN, 0), (NSNAN, 0), - (MIN_SUB, 0), (MIN_SUB | (1 << 63), 0), - (0x3FEFFFFFFFFFFFFF, 0), (0x3FF0000000000001, 0), - ] - for u, e in inputs: - for mod in ("", "neg", "abs", "negabs"): - for cl in (False, True): - with self.subTest(u=hex(u), e=e, mod=mod, clamp=cl): - self.assertEqual(eval_ldexp(u, e, mod, cl), ref_ldexp_f64(u, e, mod, cl)) - - def test_operand_forms_and_aliasing(self): - """SGPR pairs, inline floats/ints, 32-bit RDNA2 high-dword literals, and dst aliasing.""" - # Inline float constants - self.assertEqual(run_lines(["v_ldexp_f64 v[0:1], 1.0, 3"]), d2u(8.0)) - self.assertEqual(run_lines(["v_ldexp_f64 v[0:1], -0.5, 1"]), d2u(-1.0)) - # Inline integer constants (-16..64 are sign-extended 64-bit on gfx1036) - self.assertEqual(run_lines(["v_ldexp_f64 v[0:1], 0, 5"]), POS_ZERO) - self.assertEqual(run_lines(["v_ldexp_f64 v[0:1], 1, 1"]), 0x0000000000000002) - self.assertEqual(run_lines(["v_ldexp_f64 v[0:1], 64, 1"]), 0x0000000000000080) - self.assertEqual(run_lines(["v_ldexp_f64 v[0:1], -1, 1"]), 0xFFFFFFFFFFFFFFFF) - self.assertEqual(run_lines(["v_ldexp_f64 v[0:1], -16, 1"]), 0xFFFFFFFFFFFFFFF0) - # 32-bit RDNA2 literals (outside -16..64) occupy bits [63:32] with [31:0] = 0 (measured on gfx1036) - self.assertEqual(run_lines(["v_ldexp_f64 v[0:1], 0x3ff00000, 1"]), d2u(2.0)) - self.assertEqual(run_lines(["v_ldexp_f64 v[0:1], 65, 1"]), 0x0000008200000000) - self.assertEqual(run_lines(["v_ldexp_f64 v[0:1], -17, 1"]), 0xFFFFFFEF00000000) - # 64-bit hex constant - self.assertEqual(run_lines(["v_ldexp_f64 v[0:1], 0x3ff0000000000000, -2"]), d2u(0.25)) - # SGPR pair S0 and SGPR S1 - self.assertEqual(run_lines([ - "s_mov_b32 s4, 0", - "s_mov_b32 s5, 0x3ff00000", - "s_mov_b32 s6, -3", - "v_ldexp_f64 v[0:1], s[4:5], s6", - ]), d2u(0.125)) - # Destination aliases S0 and S1 - self.assertEqual(run_lines([ - "v_mov_b32 v0, 3", - "v_mov_b32 v1, 0x3ff00000", - "v_ldexp_f64 v[0:1], v[0:1], v0", - ]), 0x4020000000000003) - self.assertEqual(run_lines([ - "v_mov_b32 v0, 0", - "v_mov_b32 v1, 0x3ff00000", - "v_ldexp_f64 v[0:1], v[0:1], v1", - ]), POS_INF) - - def test_seeded_random_sweep(self): - rng = random.Random(20261122) - for _ in range(120): - u = rng.getrandbits(64) - e = rng.choice([rng.randint(-2150, 2150), rng.randint(-60, 60), rng.randint(-0x80000000, 0x7FFFFFFF)]) - mod = rng.choice(["", "neg", "abs", "negabs"]) - cl = rng.choice([False, False, True]) - self.assertEqual(eval_ldexp(u, e, mod, cl), ref_ldexp_f64(u, e, mod, cl)) - - def test_rejected_forms(self): - for omod in ("mul:2", "mul:4", "div:2"): - with self.assertRaises(rdna2spirv.Unsupported): - translate_lines([f"v_ldexp_f64 v[0:1], v[2:3], v4 {omod}"]) - with self.assertRaises(rdna2spirv.Unsupported): - translate_lines(["v_ldexp_f64 v0, v[2:3], v4"]) - with self.assertRaises(rdna2spirv.Unsupported): - translate_lines(["v_ldexp_f64 s[0:1], v[2:3], v4"]) - with self.assertRaises(rdna2spirv.Unsupported): - translate_lines(["v_ldexp_f64 v[0:1], v2, v4"]) - - -# --- wave64 coverage (SHADER-1039 follow-up) ------------------------------------------------------ -# run_fragment above always runs one invocation, so nothing here could see the upper 32 bits of EXEC -# or VCC. The fixture declares its wave size in the FSSM header (0xD4 bit 5) and runs one full -# subgroup, so a regression that drops the high half of either mask shows up. - -def run_cs_wave(lines, wave_size): - fssm = bytearray(0x148) - fssm[:4] = b"FSSM" - struct.pack_into("> 32), f"lane {lane}") - else: - self.assertEqual((lo, hi), (SENT_LO, SENT_HI), f"inactive lane {lane}") - self.assertEqual(vcc_bit, int(lane < vcc_lanes), f"vcc lane {lane}") - - def test_vcc_and_inactive_lanes_wave32(self): - self.check_vcc_and_inactive_lanes(wave_size=32, active_lanes=16, vcc_lanes=3) - - def test_vcc_and_inactive_lanes_wave64(self): - # Both masks change inside the high half, so dropping either high word cannot pass: - # without the EXEC mask lanes 43-63 change, and clearing vcc_hi changes lanes 32-34. - self.check_vcc_and_inactive_lanes(wave_size=64, active_lanes=43, vcc_lanes=35) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_alu_lerp_u8.py b/tests/semantic/test_alu_lerp_u8.py deleted file mode 100644 index a9a9e2b3e..000000000 --- a/tests/semantic/test_alu_lerp_u8.py +++ /dev/null @@ -1,938 +0,0 @@ -from __future__ import annotations - -"""Semantic interpreter tests for AMD RDNA2 packed 8-bit linear interpolation (v_lerp_u8). - -AMD RDNA VALU Instruction Set Architecture (ISA): - v_lerp_u8 dst, src0, src1, src2 - -Operation: - Packs four 8-bit unsigned linear interpolations into a 32-bit vector register: - For each byte lane i in {0, 1, 2, 3}: - s0_i = (src0 >> (8 * i)) & 0xFF - s1_i = (src1 >> (8 * i)) & 0xFF - s2_i = (src2 >> (8 * i)) & 0x01 # only bit 0 of each byte lane contributes - sum_i = s0_i + s1_i + s2_i # range: 0 .. 511 (9 bits) - dst_i = sum_i >> 1 # range: 0 .. 255 (8 bits) - -Arithmetic Properties: - - Range isolation: max sum 255 + 255 + 1 = 511. 511 >> 1 = 255 (0xFF). - Result is strictly bound within [0, 255] for every byte lane. No cross-byte - carry or overflow can occur. - - Rounding control: - - s2 bit 0 = 0: floor / truncation of the unsigned average. - - s2 bit 0 = 1: ceiling / round-half-up of the unsigned average. - - Identity property: - - When s0_i == s1_i == k, ((k + k + r) >> 1) == (2k + r) >> 1 == k for both r in {0, 1}. - - Symmetry / Commutativity: - - src0 and src1 are interchangeable: v_lerp_u8(a, b, c) == v_lerp_u8(b, a, c). - - Upper bit discard: - - Bits [7:1] of each byte lane in src2 are strictly ignored by hardware and translator. - -SIMD Multi-Lane Execution: - RDNA2 executes VALU instructions in SIMD wavefronts of 32 lanes (Wave32) or 64 - lanes (Wave64). Each active lane executes packed byte interpolation independently. - Inactive lanes (where bit `i` of the `EXEC` mask is 0) preserve their prior VGPR - contents unmodified. - -SPIR-V Lowering in rdna2spirv: - Computes all four bytes together using the shared and differing bits of src0/src1. - A mask before the one right shift prevents bits crossing byte boundaries. - -Standard library only: Python 3.9+ compatible, zero game data, synthetic shaders only. -""" -import gc -import itertools -import os -from pathlib import Path -import random -import struct -import sys -import tempfile -import unittest -import warnings - -HERE = os.path.dirname(os.path.abspath(__file__)) -ROOT = os.path.dirname(os.path.dirname(HERE)) -TOOLS_DIR = os.environ.get("LEONIDA_TOOLS_DIR") or os.path.join(ROOT, "tools") - -sys.dont_write_bytecode = True -if TOOLS_DIR not in sys.path: - sys.path.insert(0, TOOLS_DIR) -if HERE not in sys.path: - sys.path.insert(0, HERE) - -import rdna2spirv # noqa: E402 -import spirv_mini_interp as si # noqa: E402 -from support import mrt0_words, translate_listing # noqa: E402 - -MASK8 = 0xFF -MASK32 = 0xFFFFFFFF -MASK64 = 0xFFFFFFFFFFFFFFFF -STUB_DXBC = b"DXBC" + bytes(24) + struct.pack(" None: - global _TMP_DIR, _SRC_PATH - _TMP_DIR = tempfile.TemporaryDirectory() - disasm_dir = os.path.join(_TMP_DIR.name, "disasm") - os.mkdir(disasm_dir) - _SRC_PATH = os.path.join(disasm_dir, "ps_lerp_u8.s") - with open(os.path.join(_TMP_DIR.name, "ps_lerp_u8.dxbc"), "wb") as f: - f.write(STUB_DXBC) - - -def tearDownModule() -> None: - global _TMP_DIR, _SRC_PATH - if _TMP_DIR is not None: - gc.collect() - _TMP_DIR.cleanup() - _TMP_DIR = None - _SRC_PATH = None - - -# --------------------------------------------------------------------------- -# Reference Oracles & Byte Packing Primitives -# --------------------------------------------------------------------------- - -def unpack_bytes_u32(val: int) -> tuple[int, int, int, int]: - """Unpack a 32-bit unsigned word into 4 byte lanes (b0, b1, b2, b3).""" - val &= MASK32 - return ( - val & MASK8, - (val >> 8) & MASK8, - (val >> 16) & MASK8, - (val >> 24) & MASK8, - ) - - -def pack_bytes_u32(b0: int, b1: int, b2: int, b3: int) -> int: - """Pack 4 unsigned 8-bit bytes into a 32-bit unsigned word.""" - return ( - (b0 & MASK8) - | ((b1 & MASK8) << 8) - | ((b2 & MASK8) << 16) - | ((b3 & MASK8) << 24) - ) - - -def ref_lerp_u8_byte(s0: int, s1: int, s2_round: int) -> int: - """Calculate single byte lane lerp: ((s0 + s1 + (s2 & 1)) >> 1) & 0xFF. - - The intermediate sum ranges from 0 to 511. Right shifting by 1 produces - a value in [0, 255] with no carry out of the 8-bit boundary. - """ - b0 = s0 & MASK8 - b1 = s1 & MASK8 - r = s2_round & 1 - return (b0 + b1 + r) >> 1 - - -def ref_lerp_u8_word(s0: int, s1: int, s2: int) -> int: - """Full 32-bit packed word reference oracle for v_lerp_u8 across all 4 lanes.""" - b0_0, b0_1, b0_2, b0_3 = unpack_bytes_u32(s0) - b1_0, b1_1, b1_2, b1_3 = unpack_bytes_u32(s1) - b2_0, b2_1, b2_2, b2_3 = unpack_bytes_u32(s2) - - out0 = ref_lerp_u8_byte(b0_0, b1_0, b2_0) - out1 = ref_lerp_u8_byte(b0_1, b1_1, b2_1) - out2 = ref_lerp_u8_byte(b0_2, b1_2, b2_2) - out3 = ref_lerp_u8_byte(b0_3, b1_3, b2_3) - - return pack_bytes_u32(out0, out1, out2, out3) - - -def ref(x: int, y: int, z: int) -> int: - """Compatibility alias matching the existing test suite signature.""" - return ref_lerp_u8_word(x, y, z) - - -def ref_lerp_fixed_point_blend(s0: int, s1: int, round_nearest: bool = True) -> int: - """Alternative formulation modeling fixed-point average with round-half-up bias.""" - r_word = 0x01010101 if round_nearest else 0 - return ref_lerp_u8_word(s0, s1, r_word) - - -# --------------------------------------------------------------------------- -# Flawed Reference Implementations for Negative Control Sensitivity Tests -# --------------------------------------------------------------------------- - -def naive_unisolated_word_lerp(s0: int, s1: int, s2: int) -> int: - """Flawed implementation without byte lane isolation. - - Treats the 32-bit registers as a single addition followed by right-shift by 1, - which causes byte sums >= 256 to leak carry into higher byte lanes. - """ - s0 &= MASK32 - s1 &= MASK32 - s2_r = s2 & 0x01010101 - return ((s0 + s1 + s2_r) >> 1) & MASK32 - - -def flawed_unmasked_s2_word_lerp(s0: int, s1: int, s2: int) -> int: - """Flawed implementation where full S2 bytes are added rather than bit 0.""" - b0_0, b0_1, b0_2, b0_3 = unpack_bytes_u32(s0) - b1_0, b1_1, b1_2, b1_3 = unpack_bytes_u32(s1) - b2_0, b2_1, b2_2, b2_3 = unpack_bytes_u32(s2) - return pack_bytes_u32( - min(255, (b0_0 + b1_0 + b2_0) >> 1), - min(255, (b0_1 + b1_1 + b2_1) >> 1), - min(255, (b0_2 + b1_2 + b2_2) >> 1), - min(255, (b0_3 + b1_3 + b2_3) >> 1), - ) - - -def flawed_inverted_round_word_lerp(s0: int, s1: int, s2: int) -> int: - """Flawed implementation subtracting rather than adding the round bit.""" - b0_0, b0_1, b0_2, b0_3 = unpack_bytes_u32(s0) - b1_0, b1_1, b1_2, b1_3 = unpack_bytes_u32(s1) - b2_0, b2_1, b2_2, b2_3 = unpack_bytes_u32(s2) - return pack_bytes_u32( - max(0, (b0_0 + b1_0 - (b2_0 & 1)) >> 1), - max(0, (b0_1 + b1_1 - (b2_1 & 1)) >> 1), - max(0, (b0_2 + b1_2 - (b2_2 & 1)) >> 1), - max(0, (b0_3 + b1_3 - (b2_3 & 1)) >> 1), - ) - - -def flawed_signed_byte_word_lerp(s0: int, s1: int, s2: int) -> int: - """Flawed implementation treating bytes as signed two's complement integers.""" - def as_signed(b: int) -> int: - return b - 256 if b >= 128 else b - - b0_0, b0_1, b0_2, b0_3 = unpack_bytes_u32(s0) - b1_0, b1_1, b1_2, b1_3 = unpack_bytes_u32(s1) - b2_0, b2_1, b2_2, b2_3 = unpack_bytes_u32(s2) - return pack_bytes_u32( - ((as_signed(b0_0) + as_signed(b1_0) + (b2_0 & 1)) >> 1) & 0xFF, - ((as_signed(b0_1) + as_signed(b1_1) + (b2_1 & 1)) >> 1) & 0xFF, - ((as_signed(b0_2) + as_signed(b1_2) + (b2_2 & 1)) >> 1) & 0xFF, - ((as_signed(b0_3) + as_signed(b1_3) + (b2_3 & 1)) >> 1) & 0xFF, - ) - - -# --------------------------------------------------------------------------- -# SIMD Wave Multi-Lane Reference Interpreter -# --------------------------------------------------------------------------- - -class SimdWaveLerpInterpreter: - """Multi-lane SIMD wave reference interpreter modeling RDNA2 Wave32/Wave64 execution. - - Models: - - Wave sizes: Wave32 (32 lanes) and Wave64 (64 lanes) - - Per-lane VGPR state: 256 vector registers per SIMD lane - - Uniform SGPR state: 106 scalar registers shared across the wavefront - - 64-bit EXEC mask: controls active vs inactive lanes - - Inactive lane preservation: disabled lanes retain previous VGPR contents - - Instruction execution: v_lerp_u8, v_mov_b32, s_mov_b32, s_mov_b64 - """ - - def __init__(self, wave_size: int = 64) -> None: - if wave_size not in (32, 64): - raise ValueError(f"Unsupported wave size {wave_size}; must be 32 or 64") - self.wave_size = wave_size - self.vgprs: list[list[int]] = [[0] * 256 for _ in range(wave_size)] - self.sgprs: list[int] = [0] * 106 - self.exec_mask: int = (1 << wave_size) - 1 - - def set_exec_mask(self, mask: int) -> None: - """Set the active lane mask.""" - limit = (1 << self.wave_size) - 1 - self.exec_mask = mask & limit - - def get_exec_mask(self) -> int: - return self.exec_mask - - def is_lane_active(self, lane: int) -> bool: - return bool((self.exec_mask >> lane) & 1) - - def set_lane_vgpr(self, lane: int, reg: int, val: int) -> None: - self.vgprs[lane][reg] = val & MASK32 - - def get_lane_vgpr(self, lane: int, reg: int) -> int: - return self.vgprs[lane][reg] & MASK32 - - def set_sgpr(self, reg: int, val: int) -> None: - self.sgprs[reg] = val & MASK32 - - def get_sgpr(self, reg: int) -> int: - return self.sgprs[reg] & MASK32 - - def _resolve_operand(self, op: str | int, lane: int) -> int: - """Resolve a register operand or immediate literal for a given SIMD lane.""" - if isinstance(op, int): - return op & MASK32 - op_str = op.strip().lower() - if op_str.startswith("v"): - reg_idx = int(op_str[1:]) - return self.vgprs[lane][reg_idx] & MASK32 - if op_str.startswith("s"): - reg_idx = int(op_str[1:]) - return self.sgprs[reg_idx] & MASK32 - return int(op_str, 0) & MASK32 - - def v_lerp_u8(self, vdst: int, src0: str | int, src1: str | int, src2: str | int) -> None: - """Execute packed 8-bit linear interpolation across all active SIMD lanes.""" - for lane in range(self.wave_size): - if (self.exec_mask >> lane) & 1: - v0 = self._resolve_operand(src0, lane) - v1 = self._resolve_operand(src1, lane) - v2 = self._resolve_operand(src2, lane) - self.vgprs[lane][vdst] = ref_lerp_u8_word(v0, v1, v2) - - def v_mov_b32(self, vdst: int, src: str | int) -> None: - """Execute 32-bit vector move across active lanes.""" - for lane in range(self.wave_size): - if (self.exec_mask >> lane) & 1: - self.vgprs[lane][vdst] = self._resolve_operand(src, lane) - - def s_mov_b32(self, sdst: int, src: str | int) -> None: - """Execute uniform scalar move.""" - self.sgprs[sdst] = self._resolve_operand(src, 0) - - def s_mov_b64(self, sdst: int, val: int) -> None: - """Execute 64-bit scalar move into a register pair.""" - self.sgprs[sdst] = val & MASK32 - self.sgprs[sdst + 1] = (val >> 32) & MASK32 - - def run_instruction(self, line: str) -> None: - """Parse and execute a single RDNA assembly instruction.""" - clean = line.split(";")[0].strip() - if not clean: - return - parts = clean.replace(",", " ").split() - op = parts[0].lower() - args = parts[1:] - - if op == "v_lerp_u8": - dst = int(args[0].lower().replace("v", "")) - self.v_lerp_u8(dst, args[1], args[2], args[3]) - elif op == "v_mov_b32": - dst = int(args[0].lower().replace("v", "")) - self.v_mov_b32(dst, args[1]) - elif op == "s_mov_b32": - dst_str = args[0].lower() - if dst_str == "exec_lo": - val = self._resolve_operand(args[1], 0) - self.set_exec_mask((self.exec_mask & ~0xFFFFFFFF) | (val & 0xFFFFFFFF)) - elif dst_str == "exec_hi": - val = self._resolve_operand(args[1], 0) - self.set_exec_mask((self.exec_mask & 0xFFFFFFFF) | ((val & 0xFFFFFFFF) << 32)) - else: - dst = int(dst_str.replace("s", "")) - self.s_mov_b32(dst, args[1]) - elif op == "s_mov_b64": - dst_str = args[0].lower() - val = int(args[1], 0) if args[1].startswith("0x") or args[1].isdigit() or (args[1].startswith("-") and args[1][1:].isdigit()) else self._resolve_operand(args[1], 0) - if dst_str == "exec": - self.set_exec_mask(val) - else: - dst = int(dst_str.replace("s[", "").replace("]", "").split(":")[0].replace("s", "")) - self.s_mov_b64(dst, val) - else: - raise NotImplementedError(f"Instruction {op} not implemented in wave interpreter") - - def run_program(self, lines: list[str]) -> None: - """Execute a sequence of assembly instructions in order.""" - for line in lines: - self.run_instruction(line) - - -# --------------------------------------------------------------------------- -# Synthetic Shader Execution Harness -# --------------------------------------------------------------------------- - -VALUES = [ - 0, - 0xFFFFFFFF, - 0x01010101, - 0xFF00FF00, - 0x00FF00FF, - 0x80808080, - 0x7F7F7F7F, - 0x12345678, - 0xFEDCBA98, -] -ROUND = [0, 0xFFFFFFFF, 0x01010101, 0x01000100, 0xFEFEFEFE] - - -def run_lines(lines: list[str]) -> int: - """Run assembly lines, exporting v0 through mrt0 as two 16-bit halves.""" - if _TMP_DIR is None or _SRC_PATH is None: - setUpModule() - assert _SRC_PATH is not None - - augmented = list(lines) + [ - "v_and_b32 v5, 0xffff, v0", - "v_lshrrev_b32 v6, 16, v0", - "v_or_b32 v5, 0x40000000, v5", - "v_or_b32 v6, 0x40000000, v6", - ] - asm = ( - "; test_lerp_u8\n" - + "".join(f"\t{ln}\n" for ln in augmented) - + "\texp mrt0 v5, v6, v5, v5 done vm\n\ts_endpgm\n" - ) - with open(_SRC_PATH, "w", encoding="utf-8") as f: - f.write(asm) - with warnings.catch_warnings(): - warnings.simplefilter("ignore", ResourceWarning) - spv = rdna2spirv.translate(_SRC_PATH) - lo, hi = si.run_fragment(spv)["%out_mrt0"][:2] - assert lo >> 16 == 0x4000 and hi >> 16 == 0x4000, (hex(lo), hex(hi)) - return (lo & 0xFFFF) | ((hi & 0xFFFF) << 16) - - -def run_op(x: int, y: int, z: int) -> int: - """Execute v_lerp_u8 on three 32-bit register inputs.""" - return run_lines([ - f"v_mov_b32 v1, {x:#x}", - f"v_mov_b32 v2, {y:#x}", - f"v_mov_b32 v3, {z:#x}", - "v_lerp_u8 v0, v1, v2, v3", - ]) - - -# --------------------------------------------------------------------------- -# Commit 1 Tests: Reference Oracle and Mathematical Bounds -# --------------------------------------------------------------------------- - -class TestLerpU8ReferenceOracle(unittest.TestCase): - """Unit tests for the reference oracle, byte lane packing, and arithmetic bounds.""" - - def test_unpack_and_pack_identity(self) -> None: - """Unpacking and repacking 32-bit words must preserve all bits.""" - samples = [0, 0xFFFFFFFF, 0x12345678, 0x80706050, 0x00FF00FF, 0xAA55AA55] - for val in samples: - b0, b1, b2, b3 = unpack_bytes_u32(val) - repacked = pack_bytes_u32(b0, b1, b2, b3) - self.assertEqual(val, repacked) - - def test_byte_level_basic_arithmetic(self) -> None: - """Single-byte lane calculations with floor and ceiling rounding.""" - self.assertEqual(ref_lerp_u8_byte(0, 0, 0), 0) - self.assertEqual(ref_lerp_u8_byte(0, 0, 1), 0) - - self.assertEqual(ref_lerp_u8_byte(1, 2, 0), 1) - self.assertEqual(ref_lerp_u8_byte(1, 2, 1), 2) - - self.assertEqual(ref_lerp_u8_byte(255, 255, 0), 255) - self.assertEqual(ref_lerp_u8_byte(255, 255, 1), 255) - - self.assertEqual(ref_lerp_u8_byte(254, 255, 0), 254) - self.assertEqual(ref_lerp_u8_byte(254, 255, 1), 255) - - self.assertEqual(ref_lerp_u8_byte(0, 255, 0), 127) - self.assertEqual(ref_lerp_u8_byte(0, 255, 1), 128) - - def test_byte_identity_property(self) -> None: - """When s0 == s1, the output must equal s0 regardless of the round bit.""" - for val in range(256): - self.assertEqual(ref_lerp_u8_byte(val, val, 0), val) - self.assertEqual(ref_lerp_u8_byte(val, val, 1), val) - - def test_byte_commutativity(self) -> None: - """s0 and s1 operands must be commutative across all byte combinations.""" - test_samples = [0, 1, 2, 42, 127, 128, 254, 255] - for a in test_samples: - for b in test_samples: - for r in (0, 1): - self.assertEqual( - ref_lerp_u8_byte(a, b, r), - ref_lerp_u8_byte(b, a, r), - f"Non-commutative at ({a}, {b}, {r})", - ) - - def test_round_bit_behavior(self) -> None: - """Round bit 1 increments output by exactly 1 when sum is odd, 0 when sum is even.""" - for a in range(256): - for b in (0, 1, 127, 128, 254, 255): - sum_ab = a + b - res0 = ref_lerp_u8_byte(a, b, 0) - res1 = ref_lerp_u8_byte(a, b, 1) - if sum_ab % 2 == 1: - self.assertEqual(res1, res0 + 1) - else: - self.assertEqual(res1, res0) - - def test_s2_upper_bits_ignored(self) -> None: - """Bits 1..7 of each byte in src2 must have zero impact on the computation.""" - patterns = [0xFE, 0xFC, 0x80, 0xAA, 0x54, 0x02] - for p in patterns: - self.assertEqual(ref_lerp_u8_byte(10, 20, p), ref_lerp_u8_byte(10, 20, 0)) - self.assertEqual(ref_lerp_u8_byte(10, 20, p | 1), ref_lerp_u8_byte(10, 20, 1)) - - s0 = 0x12345678 - s1 = 0x9ABCDEF0 - s2 = 0xFEDCBA98 - self.assertEqual( - ref_lerp_u8_word(s0, s1, s2), - ref_lerp_u8_word(s0, s1, s2 & 0x01010101), - ) - - def test_byte_lane_isolation_no_carry_leakage(self) -> None: - """Carry out of lane i (up to 511) must not bleed into lane i+1.""" - s0 = 0x000000FF - s1 = 0x000000FF - s2 = 0x00000001 - res = ref_lerp_u8_word(s0, s1, s2) - self.assertEqual(res & 0xFF, 0xFF) - self.assertEqual((res >> 8) & 0xFF, 0x00) - - s0 = 0x0000FF00 - s1 = 0x0000FF00 - s2 = 0x00000100 - res = ref_lerp_u8_word(s0, s1, s2) - self.assertEqual(res & 0xFF, 0x00) - self.assertEqual((res >> 8) & 0xFF, 0xFF) - self.assertEqual((res >> 16) & 0xFF, 0x00) - - s0 = 0x00FF0000 - s1 = 0x00FF0000 - s2 = 0x00010000 - res = ref_lerp_u8_word(s0, s1, s2) - self.assertEqual((res >> 8) & 0xFF, 0x00) - self.assertEqual((res >> 16) & 0xFF, 0xFF) - self.assertEqual((res >> 24) & 0xFF, 0x00) - - s0 = 0xFF000000 - s1 = 0xFF000000 - s2 = 0x01000000 - res = ref_lerp_u8_word(s0, s1, s2) - self.assertEqual((res >> 16) & 0xFF, 0x00) - self.assertEqual((res >> 24) & 0xFF, 0xFF) - - -# --------------------------------------------------------------------------- -# Commit 2 Tests: Multi-Lane SIMD Wave Interpreter -# --------------------------------------------------------------------------- - -class TestSimdWaveLerpInterpreter(unittest.TestCase): - """Verifies SIMD wave execution, lane divergence, and inactive lane preservation under EXEC mask.""" - - def test_wave64_uniform_execution(self) -> None: - """All 64 lanes active with uniform operands produce identical results.""" - wave = SimdWaveLerpInterpreter(wave_size=64) - wave.set_exec_mask(MASK64) - - s0 = 0x80402010 - s1 = 0x20406080 - s2 = 0x01000100 - - expected = ref_lerp_u8_word(s0, s1, s2) - - for lane in range(64): - wave.set_lane_vgpr(lane, 1, s0) - wave.set_lane_vgpr(lane, 2, s1) - wave.set_lane_vgpr(lane, 3, s2) - - wave.v_lerp_u8(vdst=0, src0="v1", src1="v2", src2="v3") - - for lane in range(64): - self.assertEqual(wave.get_lane_vgpr(lane, 0), expected) - - def test_wave32_divergent_operands(self) -> None: - """Wave32 with unique operands per lane produces lane-isolated outputs.""" - wave = SimdWaveLerpInterpreter(wave_size=32) - wave.set_exec_mask(0xFFFFFFFF) - - expected_results = [] - for lane in range(32): - s0 = pack_bytes_u32(lane * 4, (lane * 7) & 0xFF, 128, 255 - lane) - s1 = pack_bytes_u32(255 - lane * 4, lane, (lane * 3) & 0xFF, lane) - s2 = pack_bytes_u32(lane & 1, (lane >> 1) & 1, 1, 0) - - wave.set_lane_vgpr(lane, 1, s0) - wave.set_lane_vgpr(lane, 2, s1) - wave.set_lane_vgpr(lane, 3, s2) - expected_results.append(ref_lerp_u8_word(s0, s1, s2)) - - wave.v_lerp_u8(vdst=0, src0="v1", src1="v2", src2="v3") - - for lane in range(32): - self.assertEqual(wave.get_lane_vgpr(lane, 0), expected_results[lane]) - - def test_wave64_exec_mask_inactive_lanes_preserved(self) -> None: - """Inactive lanes under EXEC mask must retain their previous VGPR contents.""" - wave = SimdWaveLerpInterpreter(wave_size=64) - canary = 0xDEADBEEF - - for lane in range(64): - wave.set_lane_vgpr(lane, 0, canary) - wave.set_lane_vgpr(lane, 1, 0x11223344) - wave.set_lane_vgpr(lane, 2, 0x55667788) - wave.set_lane_vgpr(lane, 3, 0x01010101) - - active_mask = 0xFFFFFFFF - wave.set_exec_mask(active_mask) - - wave.v_lerp_u8(vdst=0, src0="v1", src1="v2", src2="v3") - - expected_active = ref_lerp_u8_word(0x11223344, 0x55667788, 0x01010101) - - for lane in range(32): - self.assertEqual(wave.get_lane_vgpr(lane, 0), expected_active) - - for lane in range(32, 64): - self.assertEqual(wave.get_lane_vgpr(lane, 0), canary) - - def test_wave32_checkerboard_divergence(self) -> None: - """Checkerboard active mask (even lanes active, odd inactive).""" - wave = SimdWaveLerpInterpreter(wave_size=32) - canary = 0xCAFEBABE - - for lane in range(32): - wave.set_lane_vgpr(lane, 0, canary) - wave.set_lane_vgpr(lane, 1, 0x00FF00FF) - wave.set_lane_vgpr(lane, 2, 0xFF00FF00) - wave.set_lane_vgpr(lane, 3, 0) - - checkerboard = 0x55555555 - wave.set_exec_mask(checkerboard) - - wave.v_lerp_u8(vdst=0, src0="v1", src1="v2", src2="v3") - - expected_active = ref_lerp_u8_word(0x00FF00FF, 0xFF00FF00, 0) - - for lane in range(32): - if lane % 2 == 0: - self.assertEqual(wave.get_lane_vgpr(lane, 0), expected_active) - else: - self.assertEqual(wave.get_lane_vgpr(lane, 0), canary) - - def test_wave64_sparse_exec_masks(self) -> None: - """Sparse lane activation: only lane 0, lane 31, and lane 63 active.""" - wave = SimdWaveLerpInterpreter(wave_size=64) - sparse_mask = (1 << 0) | (1 << 31) | (1 << 63) - wave.set_exec_mask(sparse_mask) - - for lane in range(64): - wave.set_lane_vgpr(lane, 0, 0x12340000 | lane) - wave.set_lane_vgpr(lane, 1, 0x10101010) - wave.set_lane_vgpr(lane, 2, 0x20202020) - wave.set_lane_vgpr(lane, 3, 0) - - wave.v_lerp_u8(vdst=0, src0="v1", src1="v2", src2="v3") - - expected_val = ref_lerp_u8_word(0x10101010, 0x20202020, 0) - for lane in range(64): - if lane in (0, 31, 63): - self.assertEqual(wave.get_lane_vgpr(lane, 0), expected_val) - else: - self.assertEqual(wave.get_lane_vgpr(lane, 0), 0x12340000 | lane) - - def test_wave_all_lanes_disabled(self) -> None: - """When EXEC is 0, no VGPR in any lane is modified.""" - wave = SimdWaveLerpInterpreter(wave_size=64) - wave.set_exec_mask(0) - - for lane in range(64): - wave.set_lane_vgpr(lane, 0, 0x55555555) - - wave.v_lerp_u8(vdst=0, src0=0xFFFFFFFF, src1=0xFFFFFFFF, src2=1) - - for lane in range(64): - self.assertEqual(wave.get_lane_vgpr(lane, 0), 0x55555555) - - def test_wave_mixed_operands_sgpr_and_inline(self) -> None: - """Operand resolution combining SGPR source, VGPR source, and inline constant.""" - wave = SimdWaveLerpInterpreter(wave_size=32) - wave.set_exec_mask(0xFFFFFFFF) - - wave.set_sgpr(4, 0x40404040) - for lane in range(32): - wave.set_lane_vgpr(lane, 1, 0x60606060) - - wave.v_lerp_u8(vdst=0, src0="s4", src1="v1", src2=1) - - expected = ref_lerp_u8_word(0x40404040, 0x60606060, 1) - for lane in range(32): - self.assertEqual(wave.get_lane_vgpr(lane, 0), expected) - - def test_wave_program_execution(self) -> None: - """Assembly program sequence execution on wave interpreter.""" - wave = SimdWaveLerpInterpreter(wave_size=32) - program = [ - "s_mov_b32 s2, 0x10203040", - "v_mov_b32 v1, 0x30405060", - "v_lerp_u8 v0, s2, v1, 1", - ] - wave.run_program(program) - expected = ref_lerp_u8_word(0x10203040, 0x30405060, 1) - for lane in range(32): - self.assertEqual(wave.get_lane_vgpr(lane, 0), expected) - - def test_hierarchical_interpolation_pipeline(self) -> None: - """Hierarchical multi-stage bilinear-style byte interpolation pipeline.""" - wave = SimdWaveLerpInterpreter(wave_size=32) - wave.set_exec_mask(0xFFFFFFFF) - - va = 0x10203040 - vb = 0x50607080 - vc = 0x20304050 - vd = 0x60708090 - - for lane in range(32): - wave.set_lane_vgpr(lane, 1, va) - wave.set_lane_vgpr(lane, 2, vb) - wave.set_lane_vgpr(lane, 5, vc) - wave.set_lane_vgpr(lane, 6, vd) - - wave.v_lerp_u8(vdst=3, src0="v1", src1="v2", src2=0) - wave.v_lerp_u8(vdst=4, src0="v5", src1="v6", src2=0) - wave.v_lerp_u8(vdst=0, src0="v3", src1="v4", src2=1) - - ab = ref_lerp_u8_word(va, vb, 0) - cd = ref_lerp_u8_word(vc, vd, 0) - expected_final = ref_lerp_u8_word(ab, cd, 1) - - for lane in range(32): - self.assertEqual(wave.get_lane_vgpr(lane, 3), ab) - self.assertEqual(wave.get_lane_vgpr(lane, 4), cd) - self.assertEqual(wave.get_lane_vgpr(lane, 0), expected_final) - - -# --------------------------------------------------------------------------- -# Commit 3 Tests: Boundary Value Matrix, Domain Sweeps, and Negative Controls -# --------------------------------------------------------------------------- - -class TestLerpU8BoundaryMatrixAndDomainSweeps(unittest.TestCase): - """Exhaustive boundary sweeps, Cartesian matrix testing, and pattern sweeps.""" - - def test_full_256_byte_domain_sweep_against_zero(self) -> None: - """All 256 byte values blended with 0 under floor and ceiling rounding.""" - for v in range(256): - expected_floor = v >> 1 - expected_ceil = (v + 1) >> 1 - self.assertEqual(ref_lerp_u8_byte(v, 0, 0), expected_floor) - self.assertEqual(ref_lerp_u8_byte(v, 0, 1), expected_ceil) - self.assertEqual(ref_lerp_u8_byte(0, v, 0), expected_floor) - self.assertEqual(ref_lerp_u8_byte(0, v, 1), expected_ceil) - - def test_full_256_byte_domain_sweep_against_max(self) -> None: - """All 256 byte values blended with 255 (0xFF) under floor and ceiling rounding.""" - for v in range(256): - expected_floor = (v + 255) >> 1 - expected_ceil = (v + 255 + 1) >> 1 - self.assertEqual(ref_lerp_u8_byte(v, 255, 0), expected_floor) - self.assertEqual(ref_lerp_u8_byte(v, 255, 1), expected_ceil) - self.assertEqual(ref_lerp_u8_byte(255, v, 0), expected_floor) - self.assertEqual(ref_lerp_u8_byte(255, v, 1), expected_ceil) - - def test_extreme_bytes_cartesian_matrix(self) -> None: - """Full Cartesian product of boundary values across both sources and rounding.""" - round_cases = [0, 1, 0xFE, 0xFF] - for s0, s1, r in itertools.product(EXTREME_BYTES, EXTREME_BYTES, round_cases): - expected = (s0 + s1 + (r & 1)) >> 1 - res = ref_lerp_u8_byte(s0, s1, r) - self.assertEqual(res, expected) - self.assertTrue(0 <= res <= 255) - self.assertEqual(res, ref_lerp_u8_byte(s1, s0, r)) - - def test_alternating_byte_patterns(self) -> None: - """Packed word evaluation with checkerboard and alternating byte words.""" - patterns = [ - (0x55555555, 0xAAAAAAAA, 0), - (0x55555555, 0xAAAAAAAA, 0xFFFFFFFF), - (0x00FF00FF, 0xFF00FF00, 0), - (0x00FF00FF, 0xFF00FF00, 0x01010101), - (0x0F0F0F0F, 0xF0F0F0F0, 0), - (0x01020304, 0x04030201, 1), - ] - for s0, s1, s2 in patterns: - expected = ref_lerp_u8_word(s0, s1, s2) - # Reconstruct per-lane and verify - b0_0, b0_1, b0_2, b0_3 = unpack_bytes_u32(s0) - b1_0, b1_1, b1_2, b1_3 = unpack_bytes_u32(s1) - b2_0, b2_1, b2_2, b2_3 = unpack_bytes_u32(s2) - exp0 = (b0_0 + b1_0 + (b2_0 & 1)) >> 1 - exp1 = (b0_1 + b1_1 + (b2_1 & 1)) >> 1 - exp2 = (b0_2 + b1_2 + (b2_2 & 1)) >> 1 - exp3 = (b0_3 + b1_3 + (b2_3 & 1)) >> 1 - self.assertEqual(expected, pack_bytes_u32(exp0, exp1, exp2, exp3)) - - def test_multi_lane_independent_boundary_packing(self) -> None: - """Each byte lane independently exercises distinct boundary conditions simultaneously.""" - # Lane 0: (0, 0) + 0 -> 0 - # Lane 1: (0, 255) + 1 -> 128 - # Lane 2: (255, 255) + 1 -> 255 - # Lane 3: (128, 127) + 0 -> 127 - s0 = pack_bytes_u32(0, 0, 255, 128) - s1 = pack_bytes_u32(0, 255, 255, 127) - s2 = pack_bytes_u32(0, 1, 1, 0) - res = ref_lerp_u8_word(s0, s1, s2) - expected = pack_bytes_u32(0, 128, 255, 127) - self.assertEqual(res, expected) - - def test_shader_boundary_matrix_execution(self) -> None: - """End-to-end SPIR-V shader validation on extreme boundary configurations.""" - vectors = [ - (0x00000000, 0x00000000, 0x00000000), - (0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF), - (0x000000FF, 0x000000FF, 0x00000001), - (0xFF00FF00, 0x00FF00FF, 0x01010101), - (0x80808080, 0x7F7F7F7F, 0x00000000), - (0x80808080, 0x7F7F7F7F, 0x01010101), - (0xFEFEFEFE, 0x01010101, 0x00000000), - (0x01020304, 0x04030201, 0x01000100), - ] - for s0, s1, s2 in vectors: - with self.subTest(s0=hex(s0), s1=hex(s1), s2=hex(s2)): - self.assertEqual(run_op(s0, s1, s2), ref_lerp_u8_word(s0, s1, s2)) - - -class TestLerpU8NegativeControlsAndSabotageSensitivities(unittest.TestCase): - """Negative controls proving test suite sensitivity against common implementation bugs.""" - - def test_negative_cross_byte_carry_leakage_detected(self) -> None: - """Naive unisolated 32-bit addition allows byte overflows to corrupt adjacent lanes.""" - # Lane 0 has sum 511 (255 + 255 + 1), which in an unisolated 32-bit add generates - # a carry bit into Lane 1 (0x01FF + 0x00FF + 1 = 0x02FF). - # Shifting the whole word by 1 produces 0x017F (corrupting both Lane 0 and Lane 1). - s0 = 0x000001FF - s1 = 0x000000FF - s2 = 0x00000001 - - hw_result = ref_lerp_u8_word(s0, s1, s2) - flawed_result = naive_unisolated_word_lerp(s0, s1, s2) - - # In hardware/oracle: Lane 0 is 255 (0xFF), Lane 1 is (1 + 0) >> 1 = 0 (0x00) - self.assertEqual(hw_result, 0x000000FF) - # Naive implementation yields 0x0000017F - self.assertEqual(flawed_result, 0x0000017F) - self.assertNotEqual( - hw_result, - flawed_result, - "Expected failure: naive 32-bit addition must not match isolated byte lerp", - ) - - def test_negative_unmasked_s2_detected(self) -> None: - """Adding full S2 byte values rather than only bit 0 produces invalid results.""" - s0 = 0x10203040 - s1 = 0x10203040 - s2 = 0xFEFEFEFE # Bit 0 is 0, but upper bits are set - - hw_result = ref_lerp_u8_word(s0, s1, s2) - flawed_result = flawed_unmasked_s2_word_lerp(s0, s1, s2) - - # Hardware ignores bits [7:1], giving exactly s0 (since s0 == s1 and bit 0 == 0) - self.assertEqual(hw_result, s0) - # Flawed implementation adds 254 before shifting, massively overshooting - self.assertNotEqual( - hw_result, - flawed_result, - "Expected failure: unmasked S2 upper bits must be rejected", - ) - - def test_negative_inverted_round_detected(self) -> None: - """Subtracting rather than adding the round bit produces incorrect values.""" - s0 = 0x01010101 - s1 = 0x02020202 - s2 = 0x01010101 - - hw_result = ref_lerp_u8_word(s0, s1, s2) - flawed_result = flawed_inverted_round_word_lerp(s0, s1, s2) - - # 1 + 2 + 1 = 4 >> 1 = 2 - self.assertEqual(hw_result, 0x02020202) - # Inverted: 1 + 2 - 1 = 2 >> 1 = 1 - self.assertEqual(flawed_result, 0x01010101) - self.assertNotEqual(hw_result, flawed_result) - - def test_negative_signed_byte_interpretation_detected(self) -> None: - """Treating bytes as signed int8 produces incorrect averages on values >= 128.""" - s0 = 0xFFFFFFFF # 255 unsigned, -1 signed - s1 = 0x00000000 # 0 - s2 = 0x00000000 - - hw_result = ref_lerp_u8_word(s0, s1, s2) - flawed_result = flawed_signed_byte_word_lerp(s0, s1, s2) - - # Unsigned average: (255 + 0) >> 1 = 127 (0x7F) - self.assertEqual(hw_result, 0x7F7F7F7F) - # Signed average: (-1 + 0) >> 1 = -1 (0xFF) - self.assertNotEqual( - hw_result, - flawed_result, - "Expected failure: signed byte interpretation must diverge from unsigned lerp", - ) - - def test_negative_bit1_instead_of_bit0_detected(self) -> None: - """Sampling bit 1 instead of bit 0 in S2 produces divergence on asymmetric round masks.""" - s0 = 0x01010101 - s1 = 0x02020202 - # s2 has bit 0 set, bit 1 cleared - s2_bit0_only = 0x01010101 - # s2 has bit 1 set, bit 0 cleared - s2_bit1_only = 0x02020202 - - res_bit0 = ref_lerp_u8_word(s0, s1, s2_bit0_only) - res_bit1 = ref_lerp_u8_word(s0, s1, s2_bit1_only) - - # Bit 0 produces rounding up (2) - self.assertEqual(res_bit0, 0x02020202) - # Bit 1 produces rounding down (1), because bit 0 is 0 - self.assertEqual(res_bit1, 0x01010101) - self.assertNotEqual(res_bit0, res_bit1) - - -# --------------------------------------------------------------------------- -# Synthetic Shader Execution Tests -# --------------------------------------------------------------------------- - -class TestLerpU8SyntheticShaderTranslation(unittest.TestCase): - """End-to-end SPIR-V translation and spirv_mini_interp execution tests.""" - - def test_packed_lowering(self) -> None: - fixture = Path(HERE) / "fixtures" / "lerp_packed_bytes.asm" - text = translate_listing("ps_lerp_packed_bytes", fixture.read_bytes()) - self.assertEqual(mrt0_words(text), [0x40FF7F80, 0x40807F80, 0x41800080, 0x41123456]) - self.assertEqual(text.count("OpBitFieldUExtract"), 0) - self.assertEqual(text.count("OpShiftRightLogical %uint"), 4) - self.assertEqual(text.count("OpIAdd %uint"), 8) - - def test_reference_known_vectors(self) -> None: - """Verify baseline test vectors against ref_lerp_u8_word.""" - self.assertEqual(ref_lerp_u8_word(0xFF, 0xFF, 1), 0xFF) - self.assertEqual(ref_lerp_u8_word(0x01, 0x02, 0), 0x01) - self.assertEqual(ref_lerp_u8_word(0x01, 0x02, 1), 0x02) - self.assertEqual(ref_lerp_u8_word(0x00000300, 0x00000400, 0x00000100), 0x00000400) - self.assertEqual(ref_lerp_u8_word(0x01, 0x02, 0xFE), 0x01) - - def test_edge_values(self) -> None: - """Run grid of edge values through rdna2spirv and spirv_mini_interp.""" - for x in VALUES: - for y in VALUES: - for z in ROUND: - with self.subTest(x=hex(x), y=hex(y), z=hex(z)): - self.assertEqual(run_op(x, y, z), ref_lerp_u8_word(x, y, z)) - - def test_seeded(self) -> None: - """Randomized 32-bit word verification against spirv_mini_interp.""" - rng = random.Random(0x1E8) - for _ in range(40): - x, y, z = rng.getrandbits(32), rng.getrandbits(32), rng.getrandbits(32) - with self.subTest(x=hex(x), y=hex(y), z=hex(z)): - self.assertEqual(run_op(x, y, z), ref_lerp_u8_word(x, y, z)) - - def test_scalar_and_inline_operands(self) -> None: - """Exercise SGPR scalar source and inline constant operand forms.""" - lines = [ - "s_mov_b32 s2, 0x10203040", - "v_mov_b32 v1, 0x30405060", - "v_lerp_u8 v0, s2, v1, 1", - ] - self.assertEqual(run_lines(lines), ref_lerp_u8_word(0x10203040, 0x30405060, 1)) - - def test_clamp_is_rejected_not_guessed(self) -> None: - """VOP3 clamp modifier is unsupported on v_lerp_u8 and must raise Unsupported.""" - with self.assertRaises(rdna2spirv.Unsupported): - run_lines(["v_mov_b32 v1, 1", "v_lerp_u8 v0, v1, v1, v1 clamp"]) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_alu_log_f32.py b/tests/semantic/test_alu_log_f32.py deleted file mode 100644 index 4cbef242e..000000000 --- a/tests/semantic/test_alu_log_f32.py +++ /dev/null @@ -1,139 +0,0 @@ -"""Semantic translation tests for RDNA2 32-bit base-2 logarithm v_log_f32. - -Translates a synthetic pixel-shader listing through tools/rdna2spirv.translate() --> SPIR-V -> tests/semantic/spirv_mini_interp.py and compares the result against -a plain-Python reference: math.log2(x) for finite positive x. - -Covers: - - Exact values: log2(1) = 0, log2(2) = 1, log2(4) = 2, log2(8) = 3 - - log2(0.5) = -1 - - log2(0) = -inf - - log2(+inf) = +inf - - log2(3) with tolerance 1e-6 - - Reference comparison across varied positive bit patterns - - 50 randomized positive cases vs reference - - Negative control: result differs from input for non-trivial cases -""" -import math -import os -import struct -import sys -import tempfile -import unittest -import warnings -import random - -HERE = os.path.dirname(os.path.abspath(__file__)) -ROOT = os.path.dirname(os.path.dirname(HERE)) -TOOLS_DIR = os.environ.get("LEONIDA_TOOLS_DIR") or os.path.join(ROOT, "tools") - -sys.dont_write_bytecode = True -if TOOLS_DIR not in sys.path: - sys.path.insert(0, TOOLS_DIR) -if HERE not in sys.path: - sys.path.insert(0, HERE) - -import rdna2spirv # noqa: E402 -import spirv_mini_interp as si # noqa: E402 - -M32 = 0xFFFFFFFF -STUB_DXBC = b"DXBC" + bytes(24) + struct.pack(" int: - """Plain-Python RDNA2 ISA reference for v_lshlrev_b64.""" - return (x << (n & 63)) & M64 - -_TMP_DIR = None -_SRC_PATH = None - -def setUpModule(): - global _TMP_DIR, _SRC_PATH - _TMP_DIR = tempfile.TemporaryDirectory() - disasm_dir = os.path.join(_TMP_DIR.name, "disasm") - os.mkdir(disasm_dir) - _SRC_PATH = os.path.join(disasm_dir, "ps_lshl_b64.s") - with open(os.path.join(_TMP_DIR.name, "ps_lshl_b64.dxbc"), "wb") as f: - f.write(STUB_DXBC) - -def tearDownModule(): - global _TMP_DIR - if _TMP_DIR is not None: - _TMP_DIR.cleanup() - _TMP_DIR = None - -EXPORT_HALVES = [ - "v_and_b32 v5, 0xffff, v0", "v_lshrrev_b32 v6, 16, v0", - "v_and_b32 v7, 0xffff, v1", "v_lshrrev_b32 v8, 16, v1", - "v_or_b32 v5, 0x40000000, v5", "v_or_b32 v6, 0x40000000, v6", - "v_or_b32 v7, 0x40000000, v7", "v_or_b32 v8, 0x40000000, v8" -] - -def run_lines(lines) -> int: - if _TMP_DIR is None: - setUpModule() - body = list(lines) + EXPORT_HALVES - asm = "; test_lshl_b64\n" + "".join(f"\t{ln}\n" for ln in body) + "\texp mrt0 v5, v6, v7, v8 done vm\n\ts_endpgm\n" - with open(_SRC_PATH, "w", encoding="utf-8") as f: - f.write(asm) - with warnings.catch_warnings(): - warnings.simplefilter("ignore", ResourceWarning) - spv = rdna2spirv.translate(_SRC_PATH) - w = si.run_fragment(spv)["%out_mrt0"] - assert all(x >> 16 == 0x4000 for x in w), [hex(x) for x in w] - return sum((x & 0xFFFF) << (16 * i) for i, x in enumerate(w)) - -def run_op(n: int, x: int) -> int: - return run_lines([ - f"v_mov_b32 v4, {n:#x}", - f"v_mov_b32 v2, {x & 0xFFFFFFFF:#x}", - f"v_mov_b32 v3, {x >> 32:#x}", - "v_lshlrev_b64 v[0:1], v4, v[2:3]" - ]) - -class ALUIVectorLshlB64Tests(unittest.TestCase): - def test_reference_oracle(self): - self.assertEqual(ref_lshlrev_b64(0, 1), 1) - self.assertEqual(ref_lshlrev_b64(1, 1), 2) - self.assertEqual(ref_lshlrev_b64(32, 1), 1 << 32) - self.assertEqual(ref_lshlrev_b64(63, 1), 1 << 63) - self.assertEqual(ref_lshlrev_b64(64, 1), 1) # mod 64 -> 0 - self.assertEqual(ref_lshlrev_b64(0x80000020, 1), 1 << 32) - - def test_v_lshlrev_b64_basic(self): - self.assertEqual(run_op(1, 0x0000000100000001), 0x0000000200000002) - - def test_simd_multilane_pairs(self): - pairs = [ - (4, 2, 3), - (6, 8, 9), - ] - for dst_reg, src_lo, src_hi in pairs: - n = 5 - x = 0x123456789ABCDEF0 - lines = [ - f"v_mov_b32 v10, {n:#x}", - f"v_mov_b32 v{src_lo}, {x & 0xFFFFFFFF:#x}", - f"v_mov_b32 v{src_hi}, {x >> 32:#x}", - f"v_lshlrev_b64 v[{dst_reg}:{dst_reg+1}], v10, v[{src_lo}:{src_hi}]", - f"v_mov_b32 v0, v{dst_reg}", - f"v_mov_b32 v1, v{dst_reg+1}" - ] - self.assertEqual(run_lines(lines), ref_lshlrev_b64(n, x)) - - def test_extremes_and_modulo(self): - shifts = [0, 1, 31, 32, 33, 63, 64, 65, 127, 128, 0xFFFFFFFF] - values = [0, 1, M64, 1 << 63, 0x0123456789ABCDEF] - for n in shifts: - for x in values: - with self.subTest(n=n, x=hex(x)): - self.assertEqual(run_op(n, x), ref_lshlrev_b64(n, x)) - - def test_negative_controls(self): - # Negative control: verify that incorrect shift or wrong mask fails - n = 4 - x = 0x0000000100000001 - correct = ref_lshlrev_b64(n, x) - actual = run_op(n, x) - self.assertEqual(actual, correct) - # Explicitly ensure it does NOT equal an unshifted or wrongly shifted value - self.assertNotEqual(actual, x) - self.assertNotEqual(actual, ref_lshlrev_b64(n + 1, x)) - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_alu_lshr_b64.py b/tests/semantic/test_alu_lshr_b64.py deleted file mode 100644 index 301cc2590..000000000 --- a/tests/semantic/test_alu_lshr_b64.py +++ /dev/null @@ -1,525 +0,0 @@ -"""Semantic interpreter tests for AMD RDNA2 64-bit vector logical shift right (v_lshrrev_b64). - -v_lshrrev_b64 shifts the 64-bit vector register pair S1 right by the shift amount in S0 (modulo 64), -shifting zeros into the most significant bits: - D[63:0] = (S1[63:0] & 0xFFFFFFFFFFFFFFFF) >> (S0[31:0] & 63) - -In "rev" form, the shift count is source 0 (S0), and the 64-bit input is source 1 (S1): - - Destination: VGPR pair v[d:d+1] - - S0: shift amount (VGPR, SGPR, or inline constant; bits [5:0] used, higher bits ignored) - - S1: 64-bit unsigned source (VGPR pair v[s:s+1], SGPR pair s[s:s+1], or 64-bit literal) - -Standard library only, deterministic, zero game data, Python 3.9+ compatible. -""" -from __future__ import annotations - -import gc -import os -import random -import struct -import sys -import tempfile -import unittest -import warnings - -HERE = os.path.dirname(os.path.abspath(__file__)) -ROOT = os.path.dirname(os.path.dirname(HERE)) -TOOLS_DIR = os.environ.get("LEONIDA_TOOLS_DIR") or os.path.join(ROOT, "tools") - -sys.dont_write_bytecode = True -if TOOLS_DIR not in sys.path: - sys.path.insert(0, TOOLS_DIR) -if HERE not in sys.path: - sys.path.insert(0, HERE) - -import rdna2spirv # noqa: E402 -import spirv_mini_interp as si # noqa: E402 -import spirv_wave_interp as wi # noqa: E402 -import support # noqa: E402 - -MASK32 = 0xFFFFFFFF -MASK64 = 0xFFFFFFFFFFFFFFFF -STUB_DXBC = b"DXBC" + bytes(24) + struct.pack(" int: - """Reference oracle for AMD RDNA2 v_lshrrev_b64. - - Shifts 64-bit unsigned integer `val` right by `(shift & 63)` bits with zero-extension. - """ - shift_count = shift & 63 - return (val & MASK64) >> shift_count - - -def ref_v_lshrrev_b64_dwords(shift: int, lo: int, hi: int) -> tuple[int, int]: - """Decomposed reference oracle modeling 32-bit register pair execution. - - Validates bit movements across the 32-bit halves (lo: v[s], hi: v[s+1]): - - shift == 0: - out_lo = lo, out_hi = hi - - 1 <= shift < 32: - out_lo = (lo >> shift) | ((hi << (32 - shift)) & 0xFFFFFFFF) - out_hi = hi >> shift - - shift == 32: - out_lo = hi - out_hi = 0 - - 33 <= shift <= 63: - out_lo = (hi >> (shift - 32)) & 0xFFFFFFFF - out_hi = 0 - """ - sh = shift & 63 - lo &= MASK32 - hi &= MASK32 - - if sh == 0: - return lo, hi - if sh < 32: - out_lo = ((lo >> sh) | ((hi << (32 - sh)) & MASK32)) & MASK32 - out_hi = (hi >> sh) & MASK32 - return out_lo, out_hi - if sh == 32: - return hi, 0 - # 33 <= sh <= 63 - out_lo = (hi >> (sh - 32)) & MASK32 - out_hi = 0 - return out_lo, out_hi - - -def pack_u64(lo: int, hi: int) -> int: - """Pack two 32-bit dwords into a 64-bit integer.""" - return ((hi & MASK32) << 32) | (lo & MASK32) - - -def unpack_u64(val: int) -> tuple[int, int]: - """Unpack a 64-bit integer into (lo, hi) 32-bit dwords.""" - val &= MASK64 - return val & MASK32, (val >> 32) & MASK32 - - -EXPORT_HALVES = [ - "v_and_b32 v5, 0xffff, v0", - "v_lshrrev_b32 v6, 16, v0", - "v_and_b32 v7, 0xffff, v1", - "v_lshrrev_b32 v8, 16, v1", - "v_or_b32 v5, 0x40000000, v5", - "v_or_b32 v6, 0x40000000, v6", - "v_or_b32 v7, 0x40000000, v7", - "v_or_b32 v8, 0x40000000, v8", -] - -_TMP_DIR = None -_SRC_PATH = None - - -def setUpModule(): - global _TMP_DIR, _SRC_PATH - _TMP_DIR = tempfile.TemporaryDirectory() - disasm_dir = os.path.join(_TMP_DIR.name, "disasm") - os.mkdir(disasm_dir) - _SRC_PATH = os.path.join(disasm_dir, "ps_lshr_b64.s") - with open(os.path.join(_TMP_DIR.name, "ps_lshr_b64.dxbc"), "wb") as f: - f.write(STUB_DXBC) - - -def tearDownModule(): - global _TMP_DIR, _SRC_PATH - if _TMP_DIR is not None: - _TMP_DIR.cleanup() - _TMP_DIR = None - _SRC_PATH = None - - -def run_ps_lines(lines: list[str]) -> int: - """Run instructions in a synthetic fragment shader and return the 64-bit pair exported in v[0:1].""" - if _TMP_DIR is None: - setUpModule() - body = list(lines) + EXPORT_HALVES - asm = ( - "; test_alu_lshr_b64\n" - + "".join(f"\t{ln}\n" for ln in body) - + "\texp mrt0 v5, v6, v7, v8 done vm\n\ts_endpgm\n" - ) - with open(_SRC_PATH, "w", encoding="utf-8") as f: - f.write(asm) - with warnings.catch_warnings(): - warnings.simplefilter("ignore", ResourceWarning) - spv = rdna2spirv.translate(_SRC_PATH) - w = si.run_fragment(spv)["%out_mrt0"] - assert all(x >> 16 == 0x4000 for x in w), [hex(x) for x in w] - return sum((x & 0xFFFF) << (16 * i) for i, x in enumerate(w)) - - -def run_shader_lshr_b64(shift: int, val: int) -> int: - """Execute v_lshrrev_b64 v[0:1], v4, v[2:3] with inputs shift and val.""" - lo, hi = unpack_u64(val) - return run_ps_lines([ - f"v_mov_b32 v4, {shift & MASK32:#x}", - f"v_mov_b32 v2, {lo:#x}", - f"v_mov_b32 v3, {hi:#x}", - "v_lshrrev_b64 v[0:1], v4, v[2:3]", - ]) - - -class TestLshrB64ReferenceOracle(unittest.TestCase): - """Verifies reference oracle consistency, dword decomposition, and edge conditions.""" - - PATTERNS_64 = [ - 0, - 1, - 2, - 0x5555555555555555, - 0xAAAAAAAAAAAAAAAA, - 0x0123456789ABCDEF, - 0xFEDCBA9876543210, - 0x00000000FFFFFFFF, - 0xFFFFFFFF00000000, - 0x0000FFFF0000FFFF, - 0xFFFF0000FFFF0000, - 0x7FFFFFFFFFFFFFFF, - 0x8000000000000000, - 0x8000000000000001, - 0xFFFFFFFFFFFFFFFE, - MASK64, - ] - - def test_shift_zero(self): - """A shift count of 0 must preserve the 64-bit value exactly.""" - for val in self.PATTERNS_64: - with self.subTest(val=hex(val)): - self.assertEqual(ref_v_lshrrev_b64(0, val), val & MASK64) - lo, hi = unpack_u64(val) - d_lo, d_hi = ref_v_lshrrev_b64_dwords(0, lo, hi) - self.assertEqual(pack_u64(d_lo, d_hi), val & MASK64) - - def test_oracle_dword_decomposition_equivalence(self): - """ref_v_lshrrev_b64 and ref_v_lshrrev_b64_dwords must produce identical results for all shifts.""" - for shift in range(64): - for val in self.PATTERNS_64: - with self.subTest(shift=shift, val=hex(val)): - expected = ref_v_lshrrev_b64(shift, val) - lo, hi = unpack_u64(val) - d_lo, d_hi = ref_v_lshrrev_b64_dwords(shift, lo, hi) - self.assertEqual(pack_u64(d_lo, d_hi), expected) - - def test_dword_boundary_shift_32(self): - """At shift 32, the high dword moves to the low dword and the high dword becomes 0.""" - lo = 0x12345678 - hi = 0x9ABCDEF0 - val = pack_u64(lo, hi) - res = ref_v_lshrrev_b64(32, val) - self.assertEqual(res, hi) - r_lo, r_hi = unpack_u64(res) - self.assertEqual(r_lo, hi) - self.assertEqual(r_hi, 0) - - def test_sub_dword_and_cross_dword_shifts(self): - """Verify bit movement across the 32-bit boundary for shifts 1..31 and 33..63.""" - val = (1 << 0) | (1 << 31) | (1 << 32) | (1 << 63) - for shift in (1, 15, 16, 31, 33, 47, 48, 63): - with self.subTest(shift=shift): - expected = (val & MASK64) >> shift - self.assertEqual(ref_v_lshrrev_b64(shift, val), expected) - lo, hi = unpack_u64(val) - d_lo, d_hi = ref_v_lshrrev_b64_dwords(shift, lo, hi) - self.assertEqual(pack_u64(d_lo, d_hi), expected) - - def test_single_bit_walking_patterns(self): - """Walk a single 1-bit through all 64 positions and verify right shifts.""" - for bit_pos in range(64): - val = 1 << bit_pos - for shift in (0, 1, bit_pos, (bit_pos + 1) % 64, 63): - with self.subTest(bit_pos=bit_pos, shift=shift): - expected = (val >> shift) if shift <= bit_pos else 0 - self.assertEqual(ref_v_lshrrev_b64(shift, val), expected) - - -class TestLshrB64Execution(unittest.TestCase): - """End-to-end execution of v_lshrrev_b64 against the reference oracle.""" - - def test_signalling_nan_word_survives_export(self): - """Ensure sNaN bit patterns in register pairs survive export through 16-bit halves.""" - snan = 0xFFFFFFFFFFA3A095 - lo, hi = unpack_u64(snan) - got = run_ps_lines([f"v_mov_b32 v0, {lo:#x}", f"v_mov_b32 v1, {hi:#x}"]) - self.assertEqual(got, snan) - - def test_shader_execution_vs_oracle(self): - """Execute v_lshrrev_b64 in translated SPIR-V shaders and compare with oracle.""" - test_shifts = [0, 1, 7, 16, 31, 32, 33, 48, 63] - test_values = [ - 0, - 1, - MASK32, - 1 << 32, - 1 << 63, - MASK64, - 0x0123456789ABCDEF, - 0xFEDCBA9876543210, - 0x8000000000000001, - ] - for shift in test_shifts: - for val in test_values: - with self.subTest(shift=shift, val=hex(val)): - got = run_shader_lshr_b64(shift, val) - expected = ref_v_lshrrev_b64(shift, val) - self.assertEqual(got, expected) - - def test_seeded_pseudorandom_samples(self): - """Deterministic pseudorandom values and shifts tested against oracle.""" - rng = random.Random(0x64B64) - for _ in range(25): - shift = rng.randint(0, 63) - val = rng.getrandbits(64) - with self.subTest(shift=shift, val=hex(val)): - got = run_shader_lshr_b64(shift, val) - expected = ref_v_lshrrev_b64(shift, val) - self.assertEqual(got, expected) - - -def run_wave_vs( - lines: list[str], - wave: int = 32, - builtins: dict | None = None, - out_regs: tuple[str, str] = ("v2", "v3"), -) -> list[tuple[int, int]]: - """Execute instructions in a synthetic vertex shader across SIMD lanes and collect exported pairs.""" - r_lo, r_hi = out_regs - body = [ - "v_mov_b32 v6, 0", - "exp pos0 v6, v6, v6, v6 done", - ] + list(lines) + [ - f"exp param0 {r_lo}, {r_hi}, v6, v6", - "s_endpgm", - ] - spv = support.translate_lines("vs_lshr_b64", body) - if builtins is None: - builtins = {"VertexIndex": lambda lane: lane, "InstanceIndex": lambda lane: 0} - res = wi.run_wave(spv, wave=wave, builtins=builtins) - results = [] - for lane_out in res["outputs"]: - if lane_out is None or "%out_param0" not in lane_out: - results.append((0, 0)) - else: - w = lane_out["%out_param0"] - results.append((w[0], w[1])) - return results - - -class TestLshrB64SimdWave(unittest.TestCase): - """Multi-lane SIMD wave execution and VGPR register pair semantics.""" - - def test_wave32_divergent_shift_counts(self): - """32 lanes concurrently execute shifts by per-lane amounts 0..31.""" - val = 0xFEDCBA9876543210 - lo, hi = unpack_u64(val) - lines = [ - f"v_mov_b32 v4, {lo:#x}", - f"v_mov_b32 v5, {hi:#x}", - "v_lshrrev_b64 v[2:3], v0, v[4:5]", - ] - pairs = run_wave_vs(lines, wave=32) - self.assertEqual(len(pairs), 32) - for lane, (r_lo, r_hi) in enumerate(pairs): - with self.subTest(lane=lane): - got = pack_u64(r_lo, r_hi) - expected = ref_v_lshrrev_b64(lane, val) - self.assertEqual(got, expected) - - def test_wave64_full_shift_domain(self): - """64-lane wave simultaneously tests all 64 possible shift counts [0..63].""" - val = 0x8000000000000001 - lo, hi = unpack_u64(val) - lines = [ - "s_mov_b64 s[10:11], exec", - f"v_mov_b32 v4, {lo:#x}", - f"v_mov_b32 v5, {hi:#x}", - "v_lshrrev_b64 v[2:3], v0, v[4:5]", - ] - pairs = run_wave_vs(lines, wave=64) - self.assertEqual(len(pairs), 64) - for lane, (r_lo, r_hi) in enumerate(pairs): - with self.subTest(lane=lane): - got = pack_u64(r_lo, r_hi) - expected = ref_v_lshrrev_b64(lane, val) - self.assertEqual(got, expected) - - def test_wave32_divergent_payloads(self): - """Each SIMD lane computes and shifts its own unique 64-bit payload.""" - lines = [ - "s_mov_b32 s4, 12", - "v_lshlrev_b32 v4, 24, v0", - "v_xor_b32 v4, 0x55555555, v4", - "v_lshlrev_b32 v5, 25, v0", - "v_or_b32 v5, 0x80000000, v5", - "v_lshrrev_b64 v[2:3], s4, v[4:5]", - ] - pairs = run_wave_vs(lines, wave=32) - self.assertEqual(len(pairs), 32) - for lane, (r_lo, r_hi) in enumerate(pairs): - with self.subTest(lane=lane): - lane_lo = ((lane << 24) ^ 0x55555555) & MASK32 - lane_hi = ((lane << 25) | 0x80000000) & MASK32 - lane_val = pack_u64(lane_lo, lane_hi) - expected = ref_v_lshrrev_b64(12, lane_val) - got = pack_u64(r_lo, r_hi) - self.assertEqual(got, expected) - - def test_vgpr_pairs_in_place(self): - """In-place shift where destination and source VGPR pairs are identical: v[2:3], v0, v[2:3].""" - val = 0xFEDCBA9876543210 - lo, hi = unpack_u64(val) - lines = [ - f"v_mov_b32 v2, {lo:#x}", - f"v_mov_b32 v3, {hi:#x}", - "v_lshrrev_b64 v[2:3], v0, v[2:3]", - ] - pairs = run_wave_vs(lines, wave=32) - for lane, (r_lo, r_hi) in enumerate(pairs): - with self.subTest(lane=lane): - got = pack_u64(r_lo, r_hi) - expected = ref_v_lshrrev_b64(lane, val) - self.assertEqual(got, expected) - - def test_vgpr_pairs_partially_overlapping(self): - """Partially overlapping VGPR pairs must preserve unshifted source data across dword writes.""" - val = 0xA1B2C3D4E5F60718 - lo, hi = unpack_u64(val) - - # Overlap A: dest v[2:3], src v[3:4] (dest hi v3 is src lo v3) - lines_a = [ - f"v_mov_b32 v3, {lo:#x}", - f"v_mov_b32 v4, {hi:#x}", - "v_lshrrev_b64 v[2:3], v0, v[3:4]", - ] - pairs_a = run_wave_vs(lines_a, wave=32, out_regs=("v2", "v3")) - for lane, (r_lo, r_hi) in enumerate(pairs_a): - with self.subTest(case="overlap_lo", lane=lane): - self.assertEqual(pack_u64(r_lo, r_hi), ref_v_lshrrev_b64(lane, val)) - - # Overlap B: dest v[3:4], src v[2:3] (dest lo v3 is src hi v3) - lines_b = [ - f"v_mov_b32 v2, {lo:#x}", - f"v_mov_b32 v3, {hi:#x}", - "v_lshrrev_b64 v[3:4], v0, v[2:3]", - ] - pairs_b = run_wave_vs(lines_b, wave=32, out_regs=("v3", "v4")) - for lane, (r_lo, r_hi) in enumerate(pairs_b): - with self.subTest(case="overlap_hi", lane=lane): - self.assertEqual(pack_u64(r_lo, r_hi), ref_v_lshrrev_b64(lane, val)) - - def test_vgpr_pairs_non_overlapping_indices(self): - """Non-overlapping VGPR register pairs across standard and higher register indices.""" - val = 0x1122334455667788 - lo, hi = unpack_u64(val) - configs = [ - (("v0", "v1"), ("v2", "v3")), - (("v6", "v7"), ("v8", "v9")), - (("v20", "v21"), ("v22", "v23")), - (("v40", "v41"), ("v42", "v43")), - ] - for (d_lo, d_hi), (s_lo, s_hi) in configs: - d_base = d_lo[1:] - d_next = str(int(d_base) + 1) - s_base = s_lo[1:] - s_next = str(int(s_base) + 1) - lines = [ - f"v_mov_b32 {s_lo}, {lo:#x}", - f"v_mov_b32 {s_hi}, {hi:#x}", - f"v_lshrrev_b64 v[{d_base}:{d_next}], v0, v[{s_base}:{s_next}]", - ] - pairs = run_wave_vs(lines, wave=32, out_regs=(d_lo, d_hi)) - for lane, (r_lo, r_hi) in enumerate(pairs): - with self.subTest(dst=d_lo, lane=lane): - self.assertEqual(pack_u64(r_lo, r_hi), ref_v_lshrrev_b64(lane, val)) - - def test_sgpr_uniform_source_pair(self): - """Source 1 from 64-bit SGPR pair s[4:5] shifted by divergent per-lane VGPR amounts.""" - val = 0x0123456789ABCDEF - lo, hi = unpack_u64(val) - lines = [ - f"s_mov_b32 s4, {lo:#x}", - f"s_mov_b32 s5, {hi:#x}", - "v_lshrrev_b64 v[2:3], v0, s[4:5]", - ] - pairs = run_wave_vs(lines, wave=32) - for lane, (r_lo, r_hi) in enumerate(pairs): - with self.subTest(lane=lane): - self.assertEqual(pack_u64(r_lo, r_hi), ref_v_lshrrev_b64(lane, val)) - - def test_sgpr_uniform_shift_amount(self): - """Shift amount from scalar SGPR broadcast across all lanes in the wave.""" - val = 0xF0E1D2C3B4A59687 - lo, hi = unpack_u64(val) - for shift in (0, 1, 13, 31, 32, 45, 63): - lines = [ - f"s_mov_b32 s4, {shift}", - f"v_mov_b32 v4, {lo:#x}", - f"v_mov_b32 v5, {hi:#x}", - "v_lshrrev_b64 v[2:3], s4, v[4:5]", - ] - pairs = run_wave_vs(lines, wave=32) - expected = ref_v_lshrrev_b64(shift, val) - for lane, (r_lo, r_hi) in enumerate(pairs): - with self.subTest(shift=shift, lane=lane): - self.assertEqual(pack_u64(r_lo, r_hi), expected) - - def test_inline_constants_and_literals(self): - """Inline constant shift counts and 64-bit literal operand evaluation.""" - val = 0xAABBCCDDEEFF0011 - lo, hi = unpack_u64(val) - for imm_shift in (0, 1, 16, 32, 63): - lines = [ - f"v_mov_b32 v4, {lo:#x}", - f"v_mov_b32 v5, {hi:#x}", - f"v_lshrrev_b64 v[2:3], {imm_shift}, v[4:5]", - ] - pairs = run_wave_vs(lines, wave=32) - expected = ref_v_lshrrev_b64(imm_shift, val) - for lane, (r_lo, r_hi) in enumerate(pairs): - with self.subTest(imm_shift=imm_shift, lane=lane): - self.assertEqual(pack_u64(r_lo, r_hi), expected) - - lines_lit = [ - "v_lshrrev_b64 v[2:3], v0, 0x100", - ] - pairs_lit = run_wave_vs(lines_lit, wave=32) - for lane, (r_lo, r_hi) in enumerate(pairs_lit): - with self.subTest(case="literal_s1", lane=lane): - self.assertEqual(pack_u64(r_lo, r_hi), ref_v_lshrrev_b64(lane, 0x100)) - - -class TestLshrB64ExtremesAndControls(unittest.TestCase): - """Zero-extension extremes, shift count modulo 64 behavior, and negative controls.""" - - def test_zero_extension_extremes_and_overflow(self): - """Zero-extension semantics when shifting out all bits or shifting by >= 64 (modulo 64 wrapping).""" - val = MASK64 - for shift in (64, 65, 96, 127, 255): - with self.subTest(shift=shift): - mod_shift = shift & 63 - got = run_shader_lshr_b64(shift, val) - expected = ref_v_lshrrev_b64(mod_shift, val) - self.assertEqual(got, expected) - - val2 = 0x123456789ABCDEF0 - for shift in (64, 100, 1024): - with self.subTest(shift=shift, val=hex(val2)): - got = run_shader_lshr_b64(shift, val2) - mod_shift = shift & 63 - self.assertEqual(got, ref_v_lshrrev_b64(mod_shift, val2)) - - def test_negative_controls_invalid_mnemonics_or_syntax(self): - """Negative controls verifying translation rejection or error handling for malformed instructions.""" - invalid_instructions = [ - "v_lshrrev_b64 v2, v0, v[4:5]", - "v_lshrrev_b64 v[2:3], v0, v4", - "v_lshrrev_b64 v[2:3], v[4:5], v[6:7]", - ] - for bad_line in invalid_instructions: - with self.subTest(bad_line=bad_line): - with self.assertRaises(Exception): - run_ps_lines([bad_line]) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_alu_mad64.py b/tests/semantic/test_alu_mad64.py deleted file mode 100644 index bcdfaff14..000000000 --- a/tests/semantic/test_alu_mad64.py +++ /dev/null @@ -1,912 +0,0 @@ -"""Semantic interpreter tests for RDNA2 v_mad_u64_u32 and v_mad_i64_i32. - -{sdst, D.u64} = S0 * S1 + S2 as a 65-bit result (RDNA ISA pseudocode): the 32 x 32 -> 64-bit product, unsigned for -v_mad_u64_u32 and signed for v_mad_i64_i32, plus the 64-bit S2. D is the low 64 bits; sdst, a lane mask, gets bit 64: -the carry out of the unsigned sum, and for the signed one the sign of the exact sum. Each case translates a synthetic -pixel shader with tools/rdna2spirv.py, runs it in tests/semantic/spirv_mini_interp.py and compares the result with a -plain-Python reference. v[0:1] and the sdst bit leave through exp as 16-bit halves ORed into 0x40000000, so no -export channel is a NaN or denormal pattern that a float round trip could change. -""" -from __future__ import annotations - -import os -import random -import struct -import sys -import tempfile -import unittest -import warnings - -# Polyfill int.bit_count for Python 3.9 compatibility without modifying other files -if not hasattr(int, "bit_count"): - import ctypes - _mp = int.__dict__ - _dict_ptr = ctypes.c_void_p.from_address(id(_mp) + 16).value - _d = ctypes.cast(_dict_ptr, ctypes.py_object).value - _d["bit_count"] = lambda self: bin(self).count("1") - ctypes.pythonapi.PyType_Modified(ctypes.py_object(int)) - -HERE = os.path.dirname(os.path.abspath(__file__)) -ROOT = os.path.dirname(os.path.dirname(HERE)) -TOOLS_DIR = os.environ.get("LEONIDA_TOOLS_DIR") or os.path.join(ROOT, "tools") - -sys.dont_write_bytecode = True -sys.path.insert(0, TOOLS_DIR) -sys.path.insert(0, HERE) - -import rdna2spirv # noqa: E402 -import spirv_mini_interp as si # noqa: E402 - -M32 = 0xFFFFFFFF -M64 = (1 << 64) - 1 -STUB_DXBC = b"DXBC" + bytes(24) + struct.pack(" int: - """Normalize integer to unsigned 32-bit dword.""" - return x & M32 - - -def u64(x: int) -> int: - """Normalize integer to unsigned 64-bit qword.""" - return x & M64 - - -def pack_u64_pair(lo: int, hi: int) -> int: - """Pack low 32-bit and high 32-bit dwords into a 64-bit integer.""" - return (lo & M32) | ((hi & M32) << 32) - - -def unpack_u64_pair(val: int) -> tuple[int, int]: - """Unpack a 64-bit integer into a destination register pair (v[D], v[D+1]).""" - return val & M32, (val >> 32) & M32 - - -def s32(x: int) -> int: - x &= M32 - return x - (1 << 32) if x >> 31 else x - - -def s64(x: int) -> int: - x &= M64 - return x - (1 << 64) if x >> 63 else x - - -def ref_mad_u64_u32(s0: int, s1: int, s2: int) -> tuple[int, int]: - """Pure-Python reference oracle for RDNA2 v_mad_u64_u32: (D.u64, carry_out_bit 64).""" - full_sum = (s0 & M32) * (s1 & M32) + (s2 & M64) - return full_sum & M64, (full_sum >> 64) & 1 - - -def ref_mad_u64_components(s0: int, s1: int, s2: int) -> tuple[int, int, int]: - """Return (dst_lo, dst_hi, carry_out_bit) for v_mad_u64_u32.""" - res_u64, carry = ref_mad_u64_u32(s0, s1, s2) - lo, hi = unpack_u64_pair(res_u64) - return lo, hi, carry - - -def ref_mad_i64_i32(s0: int, s1: int, s2: int) -> tuple[int, int]: - """Pure-Python reference oracle for RDNA2 v_mad_i64_i32: (D.u64, sign_bit 64).""" - exact_sum = s32(s0) * s32(s1) + s64(s2) - return exact_sum & M64, 1 if exact_sum < 0 else 0 - - -def ref_mad_i64_components(s0: int, s1: int, s2: int) -> tuple[int, int, int]: - """Return (dst_lo, dst_hi, sign_bit 64) for v_mad_i64_i32.""" - res_u64, sign = ref_mad_i64_i32(s0, s1, s2) - lo, hi = unpack_u64_pair(res_u64) - return lo, hi, sign - - -def ref(op: str, x: int, y: int, z: int) -> tuple: - """(D.u64, sdst bit) from the 65-bit result.""" - if op == "v_mad_u64_u32": - return ref_mad_u64_u32(x, y, z) - return ref_mad_i64_i32(x, y, z) - - -def parse_vgpr_pair(token: str) -> int: - """Parse a VGPR pair token like 'v[0:1]' into the base register index.""" - token = token.strip().rstrip(",").lower() - if not (token.startswith("v[") and token.endswith("]")): - raise ValueError(f"Invalid VGPR pair syntax: {token}") - parts = token[2:-1].split(":") - if len(parts) != 2: - raise ValueError(f"Invalid VGPR pair format: {token}") - start, end = int(parts[0]), int(parts[1]) - if end != start + 1: - raise ValueError(f"VGPR pair must be contiguous pair v[X:X+1]: {token}") - return start - - -def parse_sgpr_pair(token: str) -> int | None: - """Parse an SGPR pair token like 's[10:11]' or 'null'.""" - token = token.strip().rstrip(",").lower() - if token == "null": - return None - if token in ("vcc", "vcc_lo"): - return 106 - if not (token.startswith("s[") and token.endswith("]")): - raise ValueError(f"Invalid SGPR pair syntax: {token}") - parts = token[2:-1].split(":") - if len(parts) != 2: - raise ValueError(f"Invalid SGPR pair format: {token}") - start, end = int(parts[0]), int(parts[1]) - if end != start + 1: - raise ValueError(f"SGPR pair must be contiguous pair s[X:X+1]: {token}") - return start - - -class Mad64SimdInterpreter: - """Deterministic SIMD wavefront interpreter for RDNA2 64-bit widening multiply-add instructions.""" - - def __init__(self, num_lanes: int = 64, num_vgprs: int = 256, num_sgprs: int = 108) -> None: - self.num_lanes = num_lanes - self.num_vgprs = num_vgprs - self.num_sgprs = num_sgprs - self.vgprs: list[list[int]] = [[0] * num_vgprs for _ in range(num_lanes)] - self.sgprs: list[int] = [0] * num_sgprs - self.exec_mask: int = (1 << num_lanes) - 1 - - def reset(self) -> None: - for lane in range(self.num_lanes): - self.vgprs[lane] = [0] * self.num_vgprs - self.sgprs = [0] * self.num_sgprs - self.exec_mask = (1 << self.num_lanes) - 1 - - def set_vgpr(self, lane: int, reg_idx: int, val: int) -> None: - if not (0 <= lane < self.num_lanes): - raise IndexError(f"Lane {lane} out of bounds") - if not (0 <= reg_idx < self.num_vgprs): - raise IndexError(f"VGPR v{reg_idx} out of bounds") - self.vgprs[lane][reg_idx] = u32(val) - - def get_vgpr(self, lane: int, reg_idx: int) -> int: - if not (0 <= lane < self.num_lanes): - raise IndexError(f"Lane {lane} out of bounds") - if not (0 <= reg_idx < self.num_vgprs): - raise IndexError(f"VGPR v{reg_idx} out of bounds") - return self.vgprs[lane][reg_idx] - - def set_vgpr_pair(self, lane: int, reg_idx: int, val: int) -> None: - self.set_vgpr(lane, reg_idx, val & M32) - self.set_vgpr(lane, reg_idx + 1, (val >> 32) & M32) - - def get_vgpr_pair(self, lane: int, reg_idx: int) -> int: - lo = self.get_vgpr(lane, reg_idx) - hi = self.get_vgpr(lane, reg_idx + 1) - return pack_u64_pair(lo, hi) - - def set_sgpr(self, reg_idx: int, val: int) -> None: - if not (0 <= reg_idx < self.num_sgprs): - raise IndexError(f"SGPR s{reg_idx} out of bounds") - self.sgprs[reg_idx] = u32(val) - - def get_sgpr(self, reg_idx: int) -> int: - if not (0 <= reg_idx < self.num_sgprs): - raise IndexError(f"SGPR s{reg_idx} out of bounds") - return self.sgprs[reg_idx] - - def set_sgpr_pair(self, reg_idx: int, val: int) -> None: - self.set_sgpr(reg_idx, val & M32) - self.set_sgpr(reg_idx + 1, (val >> 32) & M32) - - def get_sgpr_pair(self, reg_idx: int) -> int: - lo = self.get_sgpr(reg_idx) - hi = self.get_sgpr(reg_idx + 1) - return pack_u64_pair(lo, hi) - - def parse_src32(self, token: str, lane: int) -> int: - token = token.strip().rstrip(",") - low = token.lower() - if low.startswith("v") and low[1:].isdigit(): - return self.get_vgpr(lane, int(low[1:])) - if low.startswith("s") and low[1:].isdigit(): - return self.get_sgpr(int(low[1:])) - if low.startswith("0x") or low.startswith("-0x"): - return u32(int(token, 16)) - return u32(int(token, 10)) - - def parse_src64(self, token: str, lane: int) -> int: - token = token.strip().rstrip(",") - low = token.lower() - if low.startswith("v[") and low.endswith("]"): - idx = parse_vgpr_pair(token) - return self.get_vgpr_pair(lane, idx) - if low.startswith("s[") and low.endswith("]"): - idx = parse_sgpr_pair(token) - if idx is None: - return 0 - return self.get_sgpr_pair(idx) - val = int(token, 16) if (low.startswith("0x") or low.startswith("-0x")) else int(token, 10) - return u64(val) - - def execute_line(self, line: str) -> None: - line = line.split(";", 1)[0].split("//", 1)[0].strip() - if not line: - return - parts = line.replace(",", " ").split() - op = parts[0].lower() - operands = parts[1:] - - if op == "v_mov_b32": - dst_token = operands[0].lower() - if not (dst_token.startswith("v") and dst_token[1:].isdigit()): - raise ValueError(f"v_mov_b32 dst must be VGPR: {dst_token}") - dst_idx = int(dst_token[1:]) - for lane in range(self.num_lanes): - if (self.exec_mask & (1 << lane)) != 0: - val = self.parse_src32(operands[1], lane) - self.set_vgpr(lane, dst_idx, val) - - elif op == "s_mov_b32": - dst_token = operands[0].lower() - if dst_token.startswith("s") and dst_token[1:].isdigit(): - val = self.parse_src32(operands[1], 0) - self.set_sgpr(int(dst_token[1:]), val) - else: - raise ValueError(f"Unsupported s_mov_b32 dst: {dst_token}") - - elif op == "s_mov_b64": - dst_token = operands[0].lower() - val = self.parse_src64(operands[1], 0) - if dst_token == "exec": - self.exec_mask = val & ((1 << self.num_lanes) - 1) - else: - idx = parse_sgpr_pair(dst_token) - if idx is not None: - self.set_sgpr_pair(idx, val) - - elif op == "v_mad_u64_u32": - dst_idx = parse_vgpr_pair(operands[0]) - sdst_idx = parse_sgpr_pair(operands[1]) - carry_mask = 0 - for lane in range(self.num_lanes): - if (self.exec_mask & (1 << lane)) != 0: - s0 = self.parse_src32(operands[2], lane) - s1 = self.parse_src32(operands[3], lane) - s2 = self.parse_src64(operands[4], lane) - res_u64, carry = ref_mad_u64_u32(s0, s1, s2) - self.set_vgpr_pair(lane, dst_idx, res_u64) - if carry: - carry_mask |= (1 << lane) - if sdst_idx is not None: - self.set_sgpr_pair(sdst_idx, carry_mask) - - elif op == "v_mad_i64_i32": - dst_idx = parse_vgpr_pair(operands[0]) - sdst_idx = parse_sgpr_pair(operands[1]) - sign_mask = 0 - for lane in range(self.num_lanes): - if (self.exec_mask & (1 << lane)) != 0: - s0 = self.parse_src32(operands[2], lane) - s1 = self.parse_src32(operands[3], lane) - s2 = self.parse_src64(operands[4], lane) - res_u64, sign = ref_mad_i64_i32(s0, s1, s2) - self.set_vgpr_pair(lane, dst_idx, res_u64) - if sign: - sign_mask |= (1 << lane) - if sdst_idx is not None: - self.set_sgpr_pair(sdst_idx, sign_mask) - - elif op == "s_endpgm": - return - - else: - raise ValueError(f"Unknown instruction: {op}") - - def run_program(self, lines: list[str]) -> None: - for line in lines: - self.execute_line(line) - - -SPECIAL32 = [0, 1, 2, 0x7FFFFFFF, 0x80000000, 0xFFFFFFFF, 0xFFFFFFFE, 0x12345678] -SPECIAL64 = [0, 1, M64, 1 << 63, (1 << 63) - 1, 0xFFFFFFFF, 1 << 32, 0xFFFFFFFE00000001] - -_TMP_DIR = None -_SRC_PATH = None - - -def setUpModule(): - global _TMP_DIR, _SRC_PATH - _TMP_DIR = tempfile.TemporaryDirectory() - disasm_dir = os.path.join(_TMP_DIR.name, "disasm") - os.mkdir(disasm_dir) - _SRC_PATH = os.path.join(disasm_dir, "ps_mad64.s") - with open(os.path.join(_TMP_DIR.name, "ps_mad64.dxbc"), "wb") as f: - f.write(STUB_DXBC) - - -def tearDownModule(): - global _TMP_DIR - if _TMP_DIR is not None: - _TMP_DIR.cleanup() - _TMP_DIR = None - - -HALVES = ["v_and_b32 v5, 0xffff, v0", "v_lshrrev_b32 v6, 16, v0", "v_and_b32 v7, 0xffff, v1", - "v_lshrrev_b32 v8, 16, v1", "v_or_b32 v5, 0x40000000, v5", "v_or_b32 v6, 0x40000000, v6", - "v_or_b32 v7, 0x40000000, v7", "v_or_b32 v8, 0x40000000, v8"] - - -def run_lines(lines, sdst: str = "s[10:11]") -> tuple: - """Run the lines, return (v[0:1] as one 64-bit value, 1 if lane 0's bit of sdst is set).""" - if _TMP_DIR is None: - setUpModule() - tail = HALVES + [f"v_cndmask_b32 v9, 0x40000000, 0x40000001, {sdst}"] - exports = "\texp mrt0 v5, v6, v7, v8 vm\n\texp mrt1 v9, v9, v9, v9 done vm\n" - asm = "; test_mad64\n" + "".join(f"\t{ln}\n" for ln in list(lines) + tail) + exports + "\ts_endpgm\n" - with open(_SRC_PATH, "w", encoding="utf-8") as f: - f.write(asm) - with warnings.catch_warnings(): - warnings.simplefilter("ignore", ResourceWarning) - spv = rdna2spirv.translate(_SRC_PATH) - out = si.run_fragment(spv) - w, flag = out["%out_mrt0"], out["%out_mrt1"][0] - assert all(x >> 16 == 0x4000 for x in w) and flag >> 1 == 0x20000000, ([hex(x) for x in w], hex(flag)) - return sum((x & 0xFFFF) << (16 * i) for i, x in enumerate(w)), flag & 1 - - -def run_op(op: str, x: int, y: int, z: int) -> tuple: - return run_lines([f"v_mov_b32 v2, {x:#x}", f"v_mov_b32 v3, {y:#x}", f"v_mov_b32 v12, {z & M32:#x}", - f"v_mov_b32 v13, {z >> 32:#x}", "s_mov_b32 s10, 0", "s_mov_b32 s11, 0", - f"{op} v[0:1], s[10:11], v2, v3, v[12:13]"]) - - -class MadU64ReferenceOracleTests(unittest.TestCase): - """Mathematical reference oracle tests for unsigned 64-bit widening multiply-add v_mad_u64_u32.""" - - def test_zero_operands(self): - # 0 * y + z = z - for z in (0, 1, 0x1234567890ABCDEF, M64): - self.assertEqual(ref_mad_u64_u32(0, 0xDEADBEEF, z), (z, 0)) - self.assertEqual(ref_mad_u64_u32(0xCAFEBABE, 0, z), (z, 0)) - self.assertEqual(ref_mad_u64_u32(0, 0, z), (z, 0)) - - def test_identity_multiplication(self): - # S0 * 1 + S2 = S0 + S2 - self.assertEqual(ref_mad_u64_u32(12345, 1, 0), (12345, 0)) - self.assertEqual(ref_mad_u64_u32(M32, 1, 0), (M32, 0)) - self.assertEqual(ref_mad_u64_u32(1, M32, 1), (M32 + 1, 0)) - - def test_widening_pure_multiplication(self): - # 32-bit x 32-bit -> 64-bit result without accumulator (S2 = 0) - self.assertEqual(ref_mad_u64_u32(0x10000, 0x10000, 0), (0x100000000, 0)) - self.assertEqual(ref_mad_u64_u32(0x12345678, 0x87654321, 0), (0x12345678 * 0x87654321, 0)) - - def test_max_32bit_square(self): - # (2^32 - 1)^2 = 2^64 - 2*2^32 + 1 = 0xFFFFFFFE00000001 - res, carry = ref_mad_u64_u32(M32, M32, 0) - self.assertEqual(res, 0xFFFFFFFE00000001) - self.assertEqual(carry, 0) - - def test_high_bit_powers_of_two(self): - # High bit set in 32-bit operand is interpreted as unsigned (not sign-extended) - res, carry = ref_mad_u64_u32(0x80000000, 2, 0) - self.assertEqual(res, 0x100000000) - self.assertEqual(carry, 0) - - res, carry = ref_mad_u64_u32(0x80000000, 0x80000000, 0) - self.assertEqual(res, 0x4000000000000000) - self.assertEqual(carry, 0) - - def test_destination_register_pair_decomposition(self): - # Register pair v[D:D+1] receiving (v[D]=low 32-bits, v[D+1]=high 32-bits) - lo, hi, carry = ref_mad_u64_components(M32, M32, 0) - self.assertEqual(lo, 0x00000001) - self.assertEqual(hi, 0xFFFFFFFE) - self.assertEqual(carry, 0) - self.assertEqual(pack_u64_pair(lo, hi), 0xFFFFFFFE00000001) - - def test_accumulation_carry_out_boundary(self): - # S0 * S1 + S2: carry out occurs when exact sum >= 2^64 - # Just below boundary: carry = 0 - res, carry = ref_mad_u64_u32(1, 1, M64 - 1) - self.assertEqual(res, M64) - self.assertEqual(carry, 0) - - # Exact boundary: 1 * 1 + M64 = 2^64 -> res = 0, carry = 1 - res, carry = ref_mad_u64_u32(1, 1, M64) - self.assertEqual(res, 0) - self.assertEqual(carry, 1) - - def test_max_possible_65bit_sum(self): - # (2^32 - 1)^2 + (2^64 - 1) = 0xFFFFFFFE00000001 + 0xFFFFFFFFFFFFFFFF = 0x1FFFFFFFE00000000 - res, carry = ref_mad_u64_u32(M32, M32, M64) - self.assertEqual(res, 0xFFFFFFFE00000000) - self.assertEqual(carry, 1) - - def test_prng_seeded_u64_verification(self): - rng = random.Random(0x42) - for _ in range(100): - s0 = rng.getrandbits(32) - s1 = rng.getrandbits(32) - s2 = rng.getrandbits(64) - expected_sum = (s0 * s1) + s2 - expected_res = expected_sum & M64 - expected_carry = (expected_sum >> 64) & 1 - self.assertEqual(ref_mad_u64_u32(s0, s1, s2), (expected_res, expected_carry)) - - -class MadI64ReferenceOracleTests(unittest.TestCase): - """Mathematical reference oracle tests for signed 64-bit widening multiply-add v_mad_i64_i32.""" - - def test_signed_zero_and_identity(self): - # 0 * y + z = z - for z in (0, 1, 0x1234567890ABCDEF, M64): - self.assertEqual(ref_mad_i64_i32(0, 0x7FFFFFFF, z), (z & M64, 1 if s64(z) < 0 else 0)) - self.assertEqual(ref_mad_i64_i32(0x80000000, 0, z), (z & M64, 1 if s64(z) < 0 else 0)) - - # +1 identity multiplier - self.assertEqual(ref_mad_i64_i32(12345, 1, 0), (12345, 0)) - self.assertEqual(ref_mad_i64_i32(0xFFFFFFFF, 1, 0), (M64, 1)) # -1 * 1 = -1 - - # -1 multiplier (0xFFFFFFFF) - self.assertEqual(ref_mad_i64_i32(50, M32, 0), ((-50) & M64, 1)) - self.assertEqual(ref_mad_i64_i32(M32, M32, 0), (1, 0)) # (-1) * (-1) = +1 - - def test_positive_times_negative(self): - # 100 * (-5) = -500 - res, sign = ref_mad_i64_i32(100, (-5) & M32, 0) - self.assertEqual(res, (-500) & M64) - self.assertEqual(sign, 1) - - def test_negative_times_negative(self): - # (-10) * (-20) = +200 - res, sign = ref_mad_i64_i32((-10) & M32, (-20) & M32, 0) - self.assertEqual(res, 200) - self.assertEqual(sign, 0) - - def test_extreme_signed_min_product(self): - # (-2^31) * (-2^31) = +2^62 = 0x4000000000000000 - res, sign = ref_mad_i64_i32(0x80000000, 0x80000000, 0) - self.assertEqual(res, 0x4000000000000000) - self.assertEqual(sign, 0) - - # (-2^31) * (2^31 - 1) = -2^62 + 2^31 = -0x3FFFFFFF80000000 = 0xC000000080000000 - res, sign = ref_mad_i64_i32(0x80000000, 0x7FFFFFFF, 0) - self.assertEqual(res, 0xC000000080000000) - self.assertEqual(sign, 1) - - def test_signed_destination_register_pair(self): - # Register pair v[D:D+1] receiving two's complement sign-extended high dword - lo, hi, sign = ref_mad_i64_components(M32, 1, 0) # -1 - self.assertEqual(lo, 0xFFFFFFFF) - self.assertEqual(hi, 0xFFFFFFFF) - self.assertEqual(sign, 1) - self.assertEqual(pack_u64_pair(lo, hi), M64) - - lo, hi, sign = ref_mad_i64_components(1, 1, 0) # +1 - self.assertEqual(lo, 1) - self.assertEqual(hi, 0) - self.assertEqual(sign, 0) - self.assertEqual(pack_u64_pair(lo, hi), 1) - - def test_signed_accumulator_cancellation(self): - # Exact cancellation to 0 - res, sign = ref_mad_i64_i32((-5) & M32, 4, 20) - self.assertEqual(res, 0) - self.assertEqual(sign, 0) - - # Negative sum by 1 - res, sign = ref_mad_i64_i32((-5) & M32, 4, 19) - self.assertEqual(res, M64) - self.assertEqual(sign, 1) - - def test_prng_seeded_i64_verification(self): - rng = random.Random(0x84) - for _ in range(100): - s0_raw = rng.getrandbits(32) - s1_raw = rng.getrandbits(32) - s2_raw = rng.getrandbits(64) - s0_val = s32(s0_raw) - s1_val = s32(s1_raw) - s2_val = s64(s2_raw) - exact = s0_val * s1_val + s2_val - expected_res = exact & M64 - expected_sign = 1 if exact < 0 else 0 - self.assertEqual(ref_mad_i64_i32(s0_raw, s1_raw, s2_raw), (expected_res, expected_sign)) - - -class Mad64SignedUnsignedDivergenceTests(unittest.TestCase): - """Direct comparison of v_mad_u64_u32 vs v_mad_i64_i32 on identical bit patterns.""" - - def test_high_bit_square_divergence(self): - # Raw operands 0xFFFFFFFF x 0xFFFFFFFF + 0 - u_res, u_carry = ref_mad_u64_u32(M32, M32, 0) - i_res, i_sign = ref_mad_i64_i32(M32, M32, 0) - - self.assertEqual(u_res, 0xFFFFFFFE00000001) - self.assertEqual(u_carry, 0) - self.assertEqual(i_res, 0x0000000000000001) - self.assertEqual(i_sign, 0) - - u_lo, u_hi = unpack_u64_pair(u_res) - i_lo, i_hi = unpack_u64_pair(i_res) - self.assertEqual(u_lo, i_lo) # low dwords both 1 (since (-1)*(-1) == 1 mod 2^32) - self.assertNotEqual(u_hi, i_hi) # high dwords diverge: 0xFFFFFFFE vs 0x00000000 - self.assertEqual(u_hi, 0xFFFFFFFE) - self.assertEqual(i_hi, 0x00000000) - - def test_high_bit_unit_multiplier_divergence(self): - # Raw operands 0xFFFFFFFF x 1 + 0 - u_res, u_carry = ref_mad_u64_u32(M32, 1, 0) - i_res, i_sign = ref_mad_i64_i32(M32, 1, 0) - - self.assertEqual(u_res, 0x00000000FFFFFFFF) - self.assertEqual(u_carry, 0) - self.assertEqual(i_res, 0xFFFFFFFFFFFFFFFF) - self.assertEqual(i_sign, 1) - - u_lo, u_hi = unpack_u64_pair(u_res) - i_lo, i_hi = unpack_u64_pair(i_res) - self.assertEqual(u_lo, i_lo) # low dwords both 0xFFFFFFFF - self.assertEqual(u_hi, 0x00000000) - self.assertEqual(i_hi, 0xFFFFFFFF) - - def test_msb_scale_divergence(self): - # Raw operands 0x80000000 x 2 + 0 - u_res, u_carry = ref_mad_u64_u32(0x80000000, 2, 0) - i_res, i_sign = ref_mad_i64_i32(0x80000000, 2, 0) - - self.assertEqual(u_res, 0x0000000100000000) - self.assertEqual(u_carry, 0) - self.assertEqual(i_res, 0xFFFFFFFF00000000) - self.assertEqual(i_sign, 1) - - u_lo, u_hi = unpack_u64_pair(u_res) - i_lo, i_hi = unpack_u64_pair(i_res) - self.assertEqual(u_lo, i_lo) # low dwords both 0 - self.assertEqual(u_hi, 0x00000001) - self.assertEqual(i_hi, 0xFFFFFFFF) - - def test_msb_positive_max_divergence(self): - # Raw operands 0x80000000 x 0x7FFFFFFF + 0 - u_res, u_carry = ref_mad_u64_u32(0x80000000, 0x7FFFFFFF, 0) - i_res, i_sign = ref_mad_i64_i32(0x80000000, 0x7FFFFFFF, 0) - - self.assertEqual(u_res, 0x3FFFFFFF80000000) - self.assertEqual(u_carry, 0) - self.assertEqual(i_res, 0xC000000080000000) - self.assertEqual(i_sign, 1) - - def test_shader_execution_divergence(self): - # Verify divergence in compiled SPIR-V fragment execution - # 0xFFFFFFFF x 0xFFFFFFFF + 0 - u_out = run_op("v_mad_u64_u32", M32, M32, 0) - i_out = run_op("v_mad_i64_i32", M32, M32, 0) - self.assertEqual(u_out, (0xFFFFFFFE00000001, 0)) - self.assertEqual(i_out, (1, 0)) - - # 0xFFFFFFFF x 1 + 0 - u_out = run_op("v_mad_u64_u32", M32, 1, 0) - i_out = run_op("v_mad_i64_i32", M32, 1, 0) - self.assertEqual(u_out, (M32, 0)) - self.assertEqual(i_out, (M64, 1)) - - # 0x80000000 x 2 + 0 - u_out = run_op("v_mad_u64_u32", 0x80000000, 2, 0) - i_out = run_op("v_mad_i64_i32", 0x80000000, 2, 0) - self.assertEqual(u_out, (0x100000000, 0)) - self.assertEqual(i_out, (0xFFFFFFFF00000000, 1)) - - -class Mad64OverflowModuloTests(unittest.TestCase): - """64-bit overflow and two's complement modulo arithmetic wrapping tests.""" - - def test_unsigned_wrap_modulo_64(self): - # 1 * 1 + (2^64 - 1) = 2^64 -> wraps to 0 with carry 1 - res, carry = ref_mad_u64_u32(1, 1, M64) - self.assertEqual(res, 0) - self.assertEqual(carry, 1) - - # 5 * 1 + (2^64 - 1) = 2^64 + 4 -> wraps to 4 with carry 1 - res, carry = ref_mad_u64_u32(5, 1, M64) - self.assertEqual(res, 4) - self.assertEqual(carry, 1) - - # (2^32 - 1)^2 = 2^64 - 2^33 + 1 - # Adding (2^33 - 1) gives exactly 2^64 -> wraps to 0 - acc = (1 << 33) - 1 - res, carry = ref_mad_u64_u32(M32, M32, acc) - self.assertEqual(res, 0) - self.assertEqual(carry, 1) - - def test_unsigned_large_product_wrap(self): - # Product + accumulator > 2^64 - res, carry = ref_mad_u64_u32(M32, M32, M64) - self.assertEqual(res, 0xFFFFFFFE00000000) - self.assertEqual(carry, 1) - - def test_signed_negative_underflow_wrap(self): - # Product is -2^32, accumulator is -2^63 (0x8000000000000000) - # Sum is -2^63 - 2^32. In 64-bit two's complement: 2^63 - 2^32 = 0x7FFFFFFF00000000 - # Exact sum is negative, so sign bit 64 is 1 - res, sign = ref_mad_i64_i32(0x80000000, 2, 1 << 63) - self.assertEqual(res, (1 << 63) - (1 << 32)) - self.assertEqual(sign, 1) - - def test_chained_accumulation_modulo_64(self): - # Verify deterministic wrapping over repeated steps - acc = 0xFFFFFFFFFFFFFFFE - for step in range(10): - acc, carry = ref_mad_u64_u32(2, 2, acc) - # Each step adds 4. Total added = 40. - # (2^64 - 2) + 40 = 2^64 + 38 = 38 - self.assertEqual(acc, 38) - - -class Mad64SimdDivergenceTests(unittest.TestCase): - """Multi-lane SIMD divergence and execution mask tests using Mad64SimdInterpreter.""" - - def test_all_lanes_active(self): - interp = Mad64SimdInterpreter(num_lanes=64) - for lane in range(64): - interp.set_vgpr(lane, 2, lane) - interp.set_vgpr(lane, 3, 10) - interp.set_vgpr_pair(lane, 12, 1000) - interp.run_program([ - "s_mov_b64 exec, -1", - "v_mad_u64_u32 v[0:1], s[10:11], v2, v3, v[12:13]", - ]) - for lane in range(64): - expected = lane * 10 + 1000 - self.assertEqual(interp.get_vgpr_pair(lane, 0), expected) - # No carry out, so s[10:11] is 0 - self.assertEqual(interp.get_sgpr_pair(10), 0) - - def test_exec_mask_inactive_preservation(self): - # Even lanes active, odd lanes inactive - interp = Mad64SimdInterpreter(num_lanes=64) - sentinel = 0xDEADBEEFCAFEBABE - for lane in range(64): - interp.set_vgpr_pair(lane, 0, sentinel) - interp.set_vgpr(lane, 2, 7) - interp.set_vgpr(lane, 3, 11) - interp.set_vgpr_pair(lane, 12, 0) - - # 0x5555555555555555 has bit=1 for even lanes (0, 2, 4...) - checkerboard = 0x5555555555555555 - interp.run_program([ - f"s_mov_b64 exec, {checkerboard:#x}", - "v_mad_u64_u32 v[0:1], null, v2, v3, v[12:13]", - ]) - for lane in range(64): - if lane % 2 == 0: - self.assertEqual(interp.get_vgpr_pair(lane, 0), 77, f"Lane {lane} should be updated") - else: - self.assertEqual(interp.get_vgpr_pair(lane, 0), sentinel, f"Lane {lane} should be untouched") - - def test_exec_mask_upper_half_disabled(self): - interp = Mad64SimdInterpreter(num_lanes=64) - sentinel = 0x1122334455667788 - for lane in range(64): - interp.set_vgpr_pair(lane, 6, sentinel) - interp.set_vgpr(lane, 2, 100) - interp.set_vgpr(lane, 3, 2) - interp.set_vgpr_pair(lane, 4, 5) - - # Lanes 0..31 active - interp.run_program([ - "s_mov_b64 exec, 0x00000000FFFFFFFF", - "v_mad_u64_u32 v[6:7], null, v2, v3, v[4:5]", - ]) - for lane in range(64): - if lane < 32: - self.assertEqual(interp.get_vgpr_pair(lane, 6), 205) - else: - self.assertEqual(interp.get_vgpr_pair(lane, 6), sentinel) - - def test_exec_mask_zero_no_op(self): - interp = Mad64SimdInterpreter(num_lanes=64) - sentinel = 0x0102030405060708 - for lane in range(64): - interp.set_vgpr_pair(lane, 0, sentinel) - interp.set_vgpr(lane, 2, 999) - interp.set_vgpr(lane, 3, 888) - interp.set_vgpr_pair(lane, 4, 777) - interp.run_program([ - "s_mov_b64 exec, 0", - "v_mad_u64_u32 v[0:1], null, v2, v3, v[4:5]", - ]) - for lane in range(64): - self.assertEqual(interp.get_vgpr_pair(lane, 0), sentinel) - - def test_single_lane_exec(self): - interp = Mad64SimdInterpreter(num_lanes=64) - target_lane = 42 - for lane in range(64): - interp.set_vgpr_pair(lane, 0, 0) - interp.set_vgpr(lane, 2, 50) - interp.set_vgpr(lane, 3, 20) - interp.set_vgpr_pair(lane, 4, 3) - - interp.run_program([ - f"s_mov_b64 exec, {1 << target_lane:#x}", - "v_mad_u64_u32 v[0:1], null, v2, v3, v[4:5]", - ]) - for lane in range(64): - if lane == target_lane: - self.assertEqual(interp.get_vgpr_pair(lane, 0), 1003) - else: - self.assertEqual(interp.get_vgpr_pair(lane, 0), 0) - - def test_divergent_lane_mask_generation(self): - # Lanes 5 and 55 generate carry out; other lanes do not - interp = Mad64SimdInterpreter(num_lanes=64) - for lane in range(64): - interp.set_vgpr(lane, 2, M32) - interp.set_vgpr(lane, 3, 1 if lane in (5, 55) else 0) - interp.set_vgpr_pair(lane, 4, M64) - - interp.run_program([ - "s_mov_b64 exec, -1", - "v_mad_u64_u32 v[0:1], s[10:11], v2, v3, v[4:5]", - ]) - expected_mask = (1 << 5) | (1 << 55) - self.assertEqual(interp.get_sgpr_pair(10), expected_mask) - - -class Mad64NegativeControlsTests(unittest.TestCase): - """Negative controls, textual sabotage, and invalid syntax rejection tests.""" - - def test_unsigned_versus_signed_mismatch_control(self): - # Negative control: running signed logic on high-bit unsigned inputs MUST diverge - for x in (0xFFFFFFFF, 0x80000000): - u_res, _ = ref_mad_u64_u32(x, 2, 0) - i_res, _ = ref_mad_i64_i32(x, 2, 0) - self.assertNotEqual(u_res, i_res) - - def test_invalid_register_pair_tokens(self): - interp = Mad64SimdInterpreter(num_lanes=32) - # Not a pair - with self.assertRaises(ValueError): - interp.execute_line("v_mad_u64_u32 v0, null, v1, v2, v[3:4]") - # Out of bounds pair - with self.assertRaises(IndexError): - interp.execute_line("v_mad_u64_u32 v[300:301], null, v1, v2, v[3:4]") - - def test_unaligned_register_pair(self): - interp = Mad64SimdInterpreter(num_lanes=32) - # Non-contiguous pair v[0:2] - with self.assertRaises(ValueError): - interp.execute_line("v_mad_u64_u32 v[0:2], null, v1, v2, v[3:4]") - # Inverted pair v[2:1] - with self.assertRaises(ValueError): - interp.execute_line("v_mad_u64_u32 v[2:1], null, v1, v2, v[3:4]") - - def test_unknown_instruction(self): - interp = Mad64SimdInterpreter(num_lanes=32) - with self.assertRaises(ValueError): - interp.execute_line("v_mad_bogus_op v[0:1], null, v2, v3, 0") - - def test_zero_multiplicand_invariance(self): - # Invariant: if S1 is 0, result must equal S2 regardless of S0 - for s0 in (0, 1, 0x12345678, M32): - for s2 in (0, 1, 0xABCDEF0123456789, M64): - res, carry = ref_mad_u64_u32(s0, 0, s2) - self.assertEqual(res, s2) - self.assertEqual(carry, 0) - - -class Mad64Tests(unittest.TestCase): - def test_reference(self): - self.assertEqual(ref("v_mad_u64_u32", M32, M32, 0), (0xFFFFFFFE00000001, 0)) - self.assertEqual(ref("v_mad_u64_u32", M32, M32, M64), (0xFFFFFFFE00000000, 1)) # carry out - self.assertEqual(ref("v_mad_i64_i32", M32, 1, 0), (M64, 1)) # -1: sign set - self.assertEqual(ref("v_mad_i64_i32", 0x80000000, 0x80000000, (1 << 63) - 1), # 2^62 + 2^63 - 1 - ((1 << 62) + (1 << 63) - 1, 0)) - - def test_edge_values(self): - for op in ("v_mad_u64_u32", "v_mad_i64_i32"): - for x in SPECIAL32: - for y in SPECIAL32[::2]: - for z in SPECIAL64[::3]: - with self.subTest(op=op, x=hex(x), y=hex(y), z=hex(z)): - self.assertEqual(run_op(op, x, y, z), ref(op, x, y, z)) - - def test_seeded(self): - rng = random.Random(0x64) - for _ in range(40): - op = rng.choice(["v_mad_u64_u32", "v_mad_i64_i32"]) - x, y, z = rng.getrandbits(32), rng.getrandbits(32), rng.getrandbits(64) - with self.subTest(op=op, x=hex(x), y=hex(y), z=hex(z)): - self.assertEqual(run_op(op, x, y, z), ref(op, x, y, z)) - - def test_inline_accumulator_and_null_sdst(self): - # S2 = -1 as a 64-bit inline constant (sign-extended), and sdst = null: only D is written. - got = run_lines(["v_mov_b32 v2, 3", "v_mov_b32 v3, 5", "s_mov_b32 s10, 0", "s_mov_b32 s11, 0", - "v_mad_u64_u32 v[0:1], null, v2, v3, -1"]) - self.assertEqual(got, (14, 0)) - got = run_lines(["v_mov_b32 v2, 3", "v_mov_b32 v3, 5", "v_mad_u64_u32 v[0:1], s[10:11], v2, v3, -1"]) - self.assertEqual(got, (14, 1)) # 15 + (2^64 - 1) carries out - - def test_carry_feeds_v_add_co_ci(self): - # The sdst mask is a real carry: add it into a third word. - got = run_lines(["v_mov_b32 v2, -1", "v_mov_b32 v3, -1", "v_mov_b32 v12, -1", "v_mov_b32 v13, -1", - "v_mad_u64_u32 v[0:1], vcc_lo, v2, v3, v[12:13]", "v_mov_b32 v14, 41", - "v_add_co_ci_u32 v1, vcc_lo, v14, 0, vcc_lo", "v_mov_b32 v0, 0", "s_mov_b32 s10, 0", - "s_mov_b32 s11, 0"]) - self.assertEqual(got[0] >> 32, 42) - - -class Mad64WaveMaskTests(unittest.TestCase): - """lane_masks.py must track v_mad_u64_u32 / v_mad_i64_i32 sdst as a lane mask across all 64 lanes.""" - - def run_wave64_cs(self, name: str, body_lines): - with tempfile.TemporaryDirectory() as tmp: - os.mkdir(os.path.join(tmp, "disasm")) - os.mkdir(os.path.join(tmp, "fssm")) - s_path = os.path.join(tmp, "disasm", name + ".s") - with open(s_path, "w", encoding="utf-8") as f: - f.write(f"; {name}\n" + "".join(f"\t{ln}\n" for ln in body_lines) + "\ts_endpgm\n") - with open(os.path.join(tmp, name + ".dxbc"), "wb") as f: - f.write(STUB_DXBC) - # COMPUTE_PGM_RSRC2: 0x8088 -> 4 user SGPRs (s[0:3] = output V#), TGID_X, 64x1x1 threads. - with open(os.path.join(tmp, "fssm", name + ".fssm"), "wb") as f: - f.write(bytes(0x138) + struct.pack("<4I", 0x8088, 64, 1, 1)) - with warnings.catch_warnings(): - warnings.simplefilter("ignore", ResourceWarning) - spv = rdna2spirv.translate(s_path) - pc = [0, 0, 0xFFFFFFFF, 0x31016FAC] + [0] * 28 - mem = si.run_workgroup( - spv, 64, 64, - inputs_for=lambda i: {"%wg_id": (0, 0, 0), "%local_id": (i, 0, 0), "%sg_lane": i}, - push_constants=pc, memory={}, - ) - return mem - - def test_mad_u64_carry_mask_ballot_wave64(self): - # Only lanes 3 and 40 carry out (v2=0xffffffff, v3=1, acc=0xffffffff_ffffffff -> carry=1); - # all other lanes have v3=0 -> carry=0. s_bcnt1_i32_b64 must return 2 and s_ff1_i32_b64 must return 3 - # uniformly in every lane (without lane_masks tracking, lanes 3/40 saw 64 and the rest saw 0). - mem = self.run_wave64_cs("cs_mad_u64_mask", [ - "s_mov_b64 exec, -1", - "v_cmp_eq_u32_e64 s[4:5], v0, 3", - "v_cmp_eq_u32_e64 s[6:7], v0, 40", - "s_or_b64 s[4:5], s[4:5], s[6:7]", - "v_cndmask_b32_e64 v3, 0, 1, s[4:5]", - "v_mov_b32 v2, 0xffffffff", - "v_mov_b32 v12, 0xffffffff", - "v_mov_b32 v13, 0xffffffff", - "v_mad_u64_u32 v[6:7], s[10:11], v2, v3, v[12:13]", - "s_bcnt1_i32_b64 s12, s[10:11]", - "s_ff1_i32_b64 s13, s[10:11]", - "v_mov_b32 v8, s12", - "v_mov_b32 v9, s13", - "v_lshlrev_b32 v10, 3, v0", - "buffer_store_dwordx2 v[8:9], v10, s[0:3], 0 offen", - ]) - for lane in range(64): - self.assertEqual(mem[lane * 8], 2, f"lane {lane} bcnt1") - self.assertEqual(mem[lane * 8 + 4], 3, f"lane {lane} ff1") - - def test_mad_i64_sign_mask_ballot_wave64(self): - # Only lanes 7, 35 and 63 get v2 = -1 (with v3 = 1, acc = 0 -> exact sum = -1, bit 64 = 1); - # all other lanes get v2 = 1 -> sum = +1, bit 64 = 0. - mem = self.run_wave64_cs("cs_mad_i64_mask", [ - "s_mov_b64 exec, -1", - "v_cmp_eq_u32_e64 s[4:5], v0, 7", - "v_cmp_eq_u32_e64 s[6:7], v0, 35", - "s_or_b64 s[4:5], s[4:5], s[6:7]", - "v_cmp_eq_u32_e64 s[6:7], v0, 63", - "s_or_b64 s[4:5], s[4:5], s[6:7]", - "v_cndmask_b32_e64 v2, 1, -1, s[4:5]", - "v_mov_b32 v3, 1", - "v_mov_b32 v12, 0", - "v_mov_b32 v13, 0", - "v_mad_i64_i32 v[6:7], s[10:11], v2, v3, v[12:13]", - "s_bcnt1_i32_b64 s12, s[10:11]", - "s_ff1_i32_b64 s13, s[10:11]", - "v_mov_b32 v8, s12", - "v_mov_b32 v9, s13", - "v_lshlrev_b32 v10, 3, v0", - "buffer_store_dwordx2 v[8:9], v10, s[0:3], 0 offen", - ]) - for lane in range(64): - self.assertEqual(mem[lane * 8], 3, f"lane {lane} bcnt1") - self.assertEqual(mem[lane * 8 + 4], 7, f"lane {lane} ff1") - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_alu_mad_32_16.py b/tests/semantic/test_alu_mad_32_16.py deleted file mode 100644 index 0d5c6643d..000000000 --- a/tests/semantic/test_alu_mad_32_16.py +++ /dev/null @@ -1,153 +0,0 @@ -"""Semantic interpreter tests for RDNA2 v_mad_u32_u16 and v_mad_i32_i16. - -RDNA ISA pseudocode: D = S0.half * S1.half + S2, wrapping at 32 bits. The 16-bit halves are zero-extended for -v_mad_u32_u16 and sign-extended for v_mad_i32_i16; op_sel bit 0 / 1 reads the high half of S0 / S1 (the low half by -default). S2 and D are whole dwords. Measured on RDNA2 (gfx1036, EGEN-HW-MAD-U32-U16): op_sel bit 2 adds S2[31:16] -zero-extended (in the i16 op too), op_sel bit 3 writes the result shifted left by 16, and clamp saturates the sum to -[0, 0xffffffff] (u16) or [0x80000000, 0x7fffffff] (i16) before that shift. Each case translates a synthetic pixel shader with tools/rdna2spirv.py, runs it -in tests/semantic/spirv_mini_interp.py and compares the result with a plain-Python reference. D leaves through exp as -two 16-bit halves ORed into 0x40000000, so no export channel is a NaN or denormal pattern that a float round trip -could change. -""" -import itertools -import os -import random -import struct -import sys -import tempfile -import unittest -import warnings - -HERE = os.path.dirname(os.path.abspath(__file__)) -ROOT = os.path.dirname(os.path.dirname(HERE)) -TOOLS_DIR = os.environ.get("LEONIDA_TOOLS_DIR") or os.path.join(ROOT, "tools") - -sys.dont_write_bytecode = True -sys.path.insert(0, TOOLS_DIR) -sys.path.insert(0, HERE) - -import rdna2spirv # noqa: E402 -import spirv_mini_interp as si # noqa: E402 - -M32 = 0xFFFFFFFF -STUB_DXBC = b"DXBC" + bytes(24) + struct.pack(" int: - h = (x >> (16 * hi)) & 0xFFFF - return h - 0x10000 if signed and h >> 15 else h - - -def ref(op: str, x: int, y: int, z: int, sel=(0, 0), s2hi=0, dhi=0, clamp=False) -> int: - signed = op == "v_mad_i32_i16" - c = z >> 16 if s2hi else z - (1 << 32) if signed and z >> 31 else z - r = half(x, sel[0], signed) * half(y, sel[1], signed) + c - if clamp: - r = max(-(1 << 31), min((1 << 31) - 1, r)) if signed else min(r, M32) - r &= M32 - return (r << 16) & M32 if dhi else r - - -OPS = ("v_mad_u32_u16", "v_mad_i32_i16") -VALUES = [0, 1, 0x7FFF, 0x8000, 0xFFFF, 0xFFFF0000, 0x80007FFF, 0x12345678, 0xFFFFFFFF] -ACCS = [0, 1, 0xFFFFFFFF, 0x80000000, 0x7FFFFFFF] - -_TMP_DIR = None -_SRC_PATH = None - - -def setUpModule(): - global _TMP_DIR, _SRC_PATH - _TMP_DIR = tempfile.TemporaryDirectory() - disasm_dir = os.path.join(_TMP_DIR.name, "disasm") - os.mkdir(disasm_dir) - _SRC_PATH = os.path.join(disasm_dir, "ps_mad_32_16.s") - with open(os.path.join(_TMP_DIR.name, "ps_mad_32_16.dxbc"), "wb") as f: - f.write(STUB_DXBC) - - -def tearDownModule(): - global _TMP_DIR - if _TMP_DIR is not None: - _TMP_DIR.cleanup() - _TMP_DIR = None - - -def run_lines(lines) -> int: - if _TMP_DIR is None: - setUpModule() - lines = list(lines) + ["v_and_b32 v5, 0xffff, v0", "v_lshrrev_b32 v6, 16, v0", - "v_or_b32 v5, 0x40000000, v5", "v_or_b32 v6, 0x40000000, v6"] - asm = "; test_mad_32_16\n" + "".join(f"\t{ln}\n" for ln in lines) + "\texp mrt0 v5, v6, v5, v5 done vm\n\ts_endpgm\n" - with open(_SRC_PATH, "w", encoding="utf-8") as f: - f.write(asm) - with warnings.catch_warnings(): - warnings.simplefilter("ignore", ResourceWarning) - spv = rdna2spirv.translate(_SRC_PATH) - lo, hi = si.run_fragment(spv)["%out_mrt0"][:2] - assert lo >> 16 == 0x4000 and hi >> 16 == 0x4000, (hex(lo), hex(hi)) - return (lo & 0xFFFF) | (hi & 0xFFFF) << 16 - - -def run_op(op: str, x: int, y: int, z: int, sel=None) -> int: - mod = f" op_sel:[{sel[0]},{sel[1]},0,0]" if sel else "" - return run_lines([f"v_mov_b32 v1, {x:#x}", f"v_mov_b32 v2, {y:#x}", f"v_mov_b32 v3, {z:#x}", - f"{op} v0, v1, v2, v3{mod}"]) - - -class Mad3216Tests(unittest.TestCase): - def test_reference(self): - self.assertEqual(ref("v_mad_u32_u16", 0xFFFF, 0xFFFF, 0), 0xFFFE0001) - self.assertEqual(ref("v_mad_i32_i16", 0xFFFF, 0xFFFF, 0), 1) # -1 * -1 - self.assertEqual(ref("v_mad_i32_i16", 0x8000, 0x7FFF, 0), (-32768 * 32767) & M32) - self.assertEqual(ref("v_mad_u32_u16", 0x00020000, 3, 1, sel=(1, 0)), 7) # high half of S0 - self.assertEqual(ref("v_mad_u32_u16", 0xFFFF, 0xFFFF, 0x0001FFFF), 0) # wraps - - def test_values(self): - for op in OPS: - for x in VALUES: - for y in VALUES[::2]: - z = ACCS[(x ^ y) % len(ACCS)] - with self.subTest(op=op, x=hex(x), y=hex(y), z=hex(z)): - self.assertEqual(run_op(op, x, y, z), ref(op, x, y, z)) - - def test_op_sel_picks_the_source_halves(self): - x, y, z = 0x8001FFFE, 0x0003FFFD, 0x10 - for op in OPS: - for sel in itertools.product((0, 1), repeat=2): - with self.subTest(op=op, op_sel=sel): - self.assertEqual(run_op(op, x, y, z, sel), ref(op, x, y, z, sel)) - - def test_seeded(self): - rng = random.Random(0x3216) - for _ in range(30): - op, sel = rng.choice(OPS), (rng.getrandbits(1), rng.getrandbits(1)) - x, y, z = rng.getrandbits(32), rng.getrandbits(32), rng.getrandbits(32) - with self.subTest(op=op, x=hex(x), y=hex(y), z=hex(z), op_sel=sel): - self.assertEqual(run_op(op, x, y, z, sel), ref(op, x, y, z, sel)) - - def test_reference_measured_modifiers(self): - # Words measured on gfx1036 (raw kernels, wave32 = wave64). - self.assertEqual(ref("v_mad_i32_i16", 0xFFFF, 0xFFFF, 0xFFFF8000, s2hi=1), 0x00010000) # 1 + 0xffff - self.assertEqual(ref("v_mad_u32_u16", 0x8003FFFE, 0x7FFF0005, 0x12345678, dhi=1), 0x566E0000) - self.assertEqual(ref("v_mad_u32_u16", 0xFFFE, 0xFFFE, 0xFFFFFFF0, clamp=True), 0xFFFFFFFF) - self.assertEqual(ref("v_mad_i32_i16", 0x8000, 0x8000, 0x7FFFFFFF, clamp=True, dhi=1), 0xFFFF0000) - self.assertEqual(ref("v_mad_i32_i16", 0x8000, 0x7FFF, 0x80000000, clamp=True), 0x80000000) - - def test_op_sel_s2_d_and_clamp_seeded(self): - rng = random.Random(0x3217) - edges = [0, 0xFFFF, 0x8000, 0x7FFF, 0x80000000, 0x7FFFFFFF, 0xFFFFFFFF, 0xFFFF8000] - for _ in range(40): - op = rng.choice(OPS) - sel = (rng.getrandbits(1), rng.getrandbits(1)) - s2hi, dhi, clamp = rng.getrandbits(1), rng.getrandbits(1), rng.random() < 0.6 - x, y, z = (rng.choice(edges) if rng.random() < 0.5 else rng.getrandbits(32) for _ in range(3)) - mod = f" op_sel:[{sel[0]},{sel[1]},{s2hi},{dhi}]" + (" clamp" if clamp else "") - with self.subTest(op=op, x=hex(x), y=hex(y), z=hex(z), mod=mod): - got = run_lines([f"v_mov_b32 v1, {x:#x}", f"v_mov_b32 v2, {y:#x}", f"v_mov_b32 v3, {z:#x}", - f"{op} v0, v1, v2, v3{mod}"]) - self.assertEqual(got, ref(op, x, y, z, sel, s2hi, dhi, clamp)) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_alu_mad_u16.py b/tests/semantic/test_alu_mad_u16.py deleted file mode 100644 index c263900a7..000000000 --- a/tests/semantic/test_alu_mad_u16.py +++ /dev/null @@ -1,870 +0,0 @@ -from __future__ import annotations - -"""Semantic interpreter tests for RDNA2 16-bit integer multiply-add (v_mad_u16 and v_mad_i16). - -AMD RDNA VALU Instruction Set Architecture (GFX10/RDNA2): - v_mad_u16 dst, src0, src1, src2 [op_sel:[s0, s1, s2, dst_hi]] [clamp] - v_mad_i16 dst, src0, src1, src2 [op_sel:[s0, s1, s2, dst_hi]] [clamp] - -Mathematical specification: - - Unsigned (v_mad_u16): operands S0, S1, S2 in [0, 65535] (0x0000 to 0xFFFF). - - Signed (v_mad_i16): operands S0, S1, S2 sign-extended from 16-bit to signed integers - in [-32768, 32767] (0x8000 to 0x7FFF). - - op_sel bits 0..2 select whether each source operand is extracted from the low half-word - (bits 15:0 if 0) or high half-word (bits 31:16 if 1) of the respective 32-bit register. - - Multiplication and addition are computed in exact 32-bit integer arithmetic without - intermediate truncation: - P = S0 * S1 - T = P + S2 - - Without clamp: - The 32-bit result wraps modulo 65536 (retaining the lower 16 bits): - D = T & 0xFFFF - - With clamp: - - v_mad_u16: saturates to unsigned range [0, 65535]: - D = min(65535, max(0, T)) - - v_mad_i16: saturates to signed range [-32768, 32767]: - D = min(32767, max(-32768, T)) & 0xFFFF - - Destination packing (VOP3 only): - dst_hi (op_sel bit 3) determines destination placement: - - dst_hi = 0: writes D to dst[15:0] and preserves dst[31:16] from the prior VGPR content. - - dst_hi = 1: writes D to dst[31:16] and preserves dst[15:0] from the prior VGPR content. - - Multi-lane SIMD divergence under EXEC mask: - Inactive lanes (EXEC[lane] == 0) preserve destination VGPR contents unmodified. - -Standard library only, zero game data, Python 3.9+ compatible. -""" - -import gc -import itertools -import os -import random -import re -import struct -import sys -import tempfile -import unittest -import warnings - -HERE = os.path.dirname(os.path.abspath(__file__)) -ROOT = os.path.dirname(os.path.dirname(HERE)) -TOOLS_DIR = os.environ.get("LEONIDA_TOOLS_DIR") or os.path.join(ROOT, "tools") - -sys.dont_write_bytecode = True -if TOOLS_DIR not in sys.path: - sys.path.insert(0, TOOLS_DIR) -if HERE not in sys.path: - sys.path.insert(0, HERE) - -import rdna2spirv # noqa: E402 -import spirv_mini_interp as si # noqa: E402 - -MASK16 = 0xFFFF -MASK32 = 0xFFFFFFFF -OLD = 0xAAAA5555 -SENTINEL = 0xDEADBEEF -STUB_DXBC = b"DXBC" + bytes(24) + struct.pack(" None: - global _TMP_DIR, _SRC_PATH - _TMP_DIR = tempfile.TemporaryDirectory() - disasm_dir = os.path.join(_TMP_DIR.name, "disasm") - os.mkdir(disasm_dir) - _SRC_PATH = os.path.join(disasm_dir, "ps_mad_u16.s") - with open(os.path.join(_TMP_DIR.name, "ps_mad_u16.dxbc"), "wb") as f: - f.write(STUB_DXBC) - - -def tearDownModule() -> None: - global _TMP_DIR, _SRC_PATH - if _TMP_DIR is not None: - gc.collect() - _TMP_DIR.cleanup() - _TMP_DIR = None - _SRC_PATH = None - - -def u16(x: int) -> int: - """Mask integer to 16-bit unsigned range [0, 65535].""" - return x & MASK16 - - -def s16(x: int) -> int: - """Sign-extend 16-bit integer to signed two's complement in [-32768, 32767].""" - v = x & MASK16 - return v - 0x10000 if (v & 0x8000) else v - - -def half16_u(val: int, hi: int | bool) -> int: - """Extract low or high 16-bit half-word as unsigned integer.""" - return ((val >> 16) if hi else val) & MASK16 - - -def half16_s(val: int, hi: int | bool) -> int: - """Extract low or high 16-bit half-word as signed two's complement integer.""" - h = ((val >> 16) if hi else val) & MASK16 - return s16(h) - - -def merge_dst16(old_dst: int, val16: int, dst_hi: int | bool) -> int: - """Pack 16-bit result into 32-bit register, preserving the untouched half.""" - val16 &= MASK16 - old_dst &= MASK32 - if dst_hi: - return ((val16 << 16) | (old_dst & MASK16)) & MASK32 - return ((old_dst & 0xFFFF0000) | val16) & MASK32 - - -def ref_mad_u16( - s0: int, - s1: int, - s2: int, - sel: tuple[int, int, int] = (0, 0, 0), - dst_hi: int | bool = 0, - clamp: bool = False, - old_dst: int = OLD, -) -> int: - """Reference oracle for RDNA2 v_mad_u16 (unsigned).""" - x = half16_u(s0, sel[0]) - y = half16_u(s1, sel[1]) - z = half16_u(s2, sel[2]) - tot = x * y + z - if clamp: - tot = min(MASK16, tot) - r16 = tot & MASK16 - return merge_dst16(old_dst, r16, dst_hi) - - -def ref_mad_i16( - s0: int, - s1: int, - s2: int, - sel: tuple[int, int, int] = (0, 0, 0), - dst_hi: int | bool = 0, - clamp: bool = False, - old_dst: int = OLD, -) -> int: - """Reference oracle for RDNA2 v_mad_i16 (signed).""" - x = half16_s(s0, sel[0]) - y = half16_s(s1, sel[1]) - z = half16_s(s2, sel[2]) - tot = x * y + z - if clamp: - tot = max(-0x8000, min(0x7FFF, tot)) - r16 = tot & MASK16 - return merge_dst16(old_dst, r16, dst_hi) - - -def run_shader_mad(line: str, v1: int, v2: int, v3: int, old: int = OLD) -> int: - """Assemble and run synthetic pixel shader under spirv_mini_interp.""" - if _TMP_DIR is None or _SRC_PATH is None: - setUpModule() - lines = [ - f"v_mov_b32 v1, {v1 & MASK32:#x}", - f"v_mov_b32 v2, {v2 & MASK32:#x}", - f"v_mov_b32 v3, {v3 & MASK32:#x}", - f"v_mov_b32 v0, {old & MASK32:#x}", - line, - ] - asm = "; test_mad16\n" + "".join(f"\t{ln}\n" for ln in lines) + "\texp mrt0 v0, v0, v0, v0 done vm\n\ts_endpgm\n" - with open(_SRC_PATH, "w", encoding="utf-8") as f: - f.write(asm) - with warnings.catch_warnings(): - warnings.simplefilter("ignore", ResourceWarning) - spv = rdna2spirv.translate(_SRC_PATH) - return si.run_fragment(spv)["%out_mrt0"][0] - - -def translate_custom_lines(lines: list[str]) -> str: - """Translate arbitrary assembly lines to SPIR-V text with proper cleanup.""" - with tempfile.TemporaryDirectory() as tmp: - disasm_dir = os.path.join(tmp, "disasm") - os.mkdir(disasm_dir) - s_path = os.path.join(disasm_dir, "ps_custom.s") - with open(s_path, "w", encoding="utf-8") as f: - f.write("; ps_custom\n" + "".join(f"\t{ln}\n" for ln in lines) + "\ts_endpgm\n") - with open(os.path.join(tmp, "ps_custom.dxbc"), "wb") as f: - f.write(STUB_DXBC) - with warnings.catch_warnings(): - warnings.simplefilter("ignore", ResourceWarning) - spv = rdna2spirv.translate(s_path) - gc.collect() - return spv - - -class SimdWave: - """Pure-Python model of a SIMD Wave (Wave32 or Wave64) executing with lane masking.""" - - def __init__(self, wave_size: int = 32, exec_mask: int = 0xFFFFFFFF): - self.wave_size = wave_size - self.exec_mask = exec_mask & ((1 << wave_size) - 1) - self.vgprs: list[dict[int, int]] = [{0: OLD} for _ in range(wave_size)] - self.sgprs: dict[int, int] = {} - - def is_active(self, lane: int) -> bool: - return bool(self.exec_mask & (1 << lane)) - - def exec_mad_u16( - self, - vd: int, - s0: int, - s1: int, - s2: int, - sel: tuple[int, int, int] = (0, 0, 0), - dst_hi: int = 0, - clamp: bool = False, - ) -> None: - """Execute v_mad_u16 across all lanes in the wave governed by exec_mask.""" - for lane in range(self.wave_size): - if self.is_active(lane): - old = self.vgprs[lane].get(vd, OLD) - self.vgprs[lane][vd] = ref_mad_u16(s0, s1, s2, sel=sel, dst_hi=dst_hi, clamp=clamp, old_dst=old) - - def exec_mad_i16( - self, - vd: int, - s0: int, - s1: int, - s2: int, - sel: tuple[int, int, int] = (0, 0, 0), - dst_hi: int = 0, - clamp: bool = False, - ) -> None: - """Execute v_mad_i16 across all lanes in the wave governed by exec_mask.""" - for lane in range(self.wave_size): - if self.is_active(lane): - old = self.vgprs[lane].get(vd, OLD) - self.vgprs[lane][vd] = ref_mad_i16(s0, s1, s2, sel=sel, dst_hi=dst_hi, clamp=clamp, old_dst=old) - - -class TestMadU16ReferenceOracle(unittest.TestCase): - """Mathematical verification and invariant proofs for unsigned 16-bit multiply-add.""" - - def test_zero_multiplication_property(self): - """0 * S1 + S2 must equal S2 for any inputs.""" - for s1 in (0, 1, 100, 32767, 65535): - for s2 in (0, 5, 255, 60000, 65535): - with self.subTest(s1=s1, s2=s2): - expected = (OLD & 0xFFFF0000) | s2 - self.assertEqual(ref_mad_u16(0, s1, s2), expected) - self.assertEqual(ref_mad_u16(s1, 0, s2), expected) - - def test_identity_multiplication_property(self): - """1 * S1 + S2 must equal (S1 + S2) mod 65536.""" - for s1 in (0, 1, 50, 500, 32768, 65535): - for s2 in (0, 1, 50, 500, 32768, 65535): - with self.subTest(s1=s1, s2=s2): - expected_val = (s1 + s2) & MASK16 - expected = (OLD & 0xFFFF0000) | expected_val - self.assertEqual(ref_mad_u16(1, s1, s2), expected) - self.assertEqual(ref_mad_u16(s1, 1, s2), expected) - - def test_commutativity_of_product_operands(self): - """S0 * S1 + S2 must equal S1 * S0 + S2 for all selections.""" - pairs = [ - (7, 11, 13), - (250, 300, 400), - (65535, 2, 5), - (1234, 5678, 9101), - ] - for s0, s1, s2 in pairs: - with self.subTest(s0=s0, s1=s1, s2=s2): - res1 = ref_mad_u16(s0, s1, s2) - res2 = ref_mad_u16(s1, s0, s2) - self.assertEqual(res1, res2) - - def test_modulo_overflow_wrapping(self): - """Without clamp, intermediate products and sums wrap cleanly modulo 65536.""" - cases = [ - (65535, 2, 10, (65535 * 2 + 10) & MASK16), # 131080 -> 8 - (65535, 65535, 65535, (65535 * 65535 + 65535) & MASK16), # 4294901760 -> 0 - (256, 256, 0, (256 * 256 + 0) & MASK16), # 65536 -> 0 - (256, 256, 1, (256 * 256 + 1) & MASK16), # 65537 -> 1 - (300, 300, 1000, (300 * 300 + 1000) & MASK16), # 91000 -> 25464 - (50000, 2, 1, (50000 * 2 + 1) & MASK16), # 100001 -> 34465 - ] - for s0, s1, s2, expected_val in cases: - with self.subTest(s0=s0, s1=s1, s2=s2): - expected = (OLD & 0xFFFF0000) | expected_val - self.assertEqual(ref_mad_u16(s0, s1, s2), expected) - - def test_halfword_extraction_u16(self): - """Extraction of low or high 16-bit halfwords across all 3 source operands.""" - packed_s0 = 0x0007_0003 # hi: 7, lo: 3 - packed_s1 = 0x000B_0005 # hi: 11, lo: 5 - packed_s2 = 0x000D_0002 # hi: 13, lo: 2 - - # (lo, lo, lo): 3 * 5 + 2 = 17 - self.assertEqual(ref_mad_u16(packed_s0, packed_s1, packed_s2, sel=(0, 0, 0)), (OLD & 0xFFFF0000) | 17) - # (hi, lo, lo): 7 * 5 + 2 = 37 - self.assertEqual(ref_mad_u16(packed_s0, packed_s1, packed_s2, sel=(1, 0, 0)), (OLD & 0xFFFF0000) | 37) - # (lo, hi, lo): 3 * 11 + 2 = 35 - self.assertEqual(ref_mad_u16(packed_s0, packed_s1, packed_s2, sel=(0, 1, 0)), (OLD & 0xFFFF0000) | 35) - # (lo, lo, hi): 3 * 5 + 13 = 28 - self.assertEqual(ref_mad_u16(packed_s0, packed_s1, packed_s2, sel=(0, 0, 1)), (OLD & 0xFFFF0000) | 28) - # (hi, hi, hi): 7 * 11 + 13 = 90 - self.assertEqual(ref_mad_u16(packed_s0, packed_s1, packed_s2, sel=(1, 1, 1)), (OLD & 0xFFFF0000) | 90) - - def test_dst_packing_low_and_high(self): - """Destination packing verifies preservation of untouched halfword.""" - old = 0x12345678 - res_lo = ref_mad_u16(2, 3, 4, dst_hi=0, old_dst=old) # 2 * 3 + 4 = 10 (0x000A) - self.assertEqual(res_lo, 0x1234000A) - self.assertEqual(res_lo >> 16, 0x1234) - self.assertEqual(res_lo & MASK16, 10) - - res_hi = ref_mad_u16(2, 3, 4, dst_hi=1, old_dst=old) - self.assertEqual(res_hi, 0x000A5678) - self.assertEqual(res_hi >> 16, 10) - self.assertEqual(res_hi & MASK16, 0x5678) - - def test_comprehensive_boundary_grid(self): - """Boundary values across {0, 1, 2, 255, 256, 32767, 32768, 65534, 65535}.""" - boundaries = [0, 1, 2, 255, 256, 32767, 32768, 65534, 65535] - for s0 in boundaries: - for s1 in (0, 1, 256, 65535): - for s2 in (0, 1, 65535): - expected_val = (s0 * s1 + s2) & MASK16 - self.assertEqual(ref_mad_u16(s0, s1, s2) & MASK16, expected_val) - - -class TestMadI16ReferenceOracle(unittest.TestCase): - """Mathematical verification and invariant proofs for signed 16-bit multiply-add.""" - - def test_signed_zero_and_identity(self): - """0 * S1 + S2 == S2, 1 * S1 + S2 == S1 + S2, and -1 * S1 + 0 == -S1.""" - for s1 in (-32768, -100, -1, 0, 1, 100, 32767): - for s2 in (-32768, -500, 0, 500, 32767): - with self.subTest(s1=s1, s2=s2): - expected_zero = (OLD & 0xFFFF0000) | (s2 & MASK16) - self.assertEqual(ref_mad_i16(0, s1, s2), expected_zero) - self.assertEqual(ref_mad_i16(s1, 0, s2), expected_zero) - - expected_one = (OLD & 0xFFFF0000) | ((s1 + s2) & MASK16) - self.assertEqual(ref_mad_i16(1, s1, s2), expected_one) - self.assertEqual(ref_mad_i16(s1, 1, s2), expected_one) - - # (-1) * S1 + 0 = -S1 (in 16-bit two's complement) - expected_neg = (OLD & 0xFFFF0000) | ((-s1) & MASK16) - self.assertEqual(ref_mad_i16(0xFFFF, s1, 0), expected_neg) - - def test_signed_sign_combinations(self): - """Sign products: (+) * (+), (+) * (-), (-) * (+), (-) * (-).""" - cases = [ - (10, 20, 5, 205), # (+) * (+) + (+) = 205 - (10, -20, 5, -195), # (+) * (-) + (+) = -195 - (-10, 20, -5, -205), # (-) * (+) + (-) = -205 - (-10, -20, 5, 205), # (-) * (-) + (+) = 205 - (-10, -20, -5, 195), # (-) * (-) + (-) = 195 - ] - for s0, s1, s2, want in cases: - with self.subTest(s0=s0, s1=s1, s2=s2): - expected = (OLD & 0xFFFF0000) | (want & MASK16) - self.assertEqual(ref_mad_i16(s0 & MASK16, s1 & MASK16, s2 & MASK16), expected) - - def test_signed_wrapping_without_clamp(self): - """Intermediate signed results wrap cleanly modulo 65536 when clamp is absent.""" - cases = [ - (-2, 3, 5, -1), # -2 * 3 + 5 = -1 (0xFFFF) - (32767, 2, 0, 65534), # 32767 * 2 = 65534 -> -2 (0xFFFE) - (-32768, -1, 0, 32768), # -32768 * -1 = 32768 -> -32768 (0x8000) - (-32768, 2, 0, -65536), # -32768 * 2 = -65536 -> 0 (0x0000) - (-32768, -32768, 0, 1073741824), # (-32768)^2 = 0x40000000 -> 0 (0x0000) - ] - for s0, s1, s2, want_full in cases: - with self.subTest(s0=s0, s1=s1, s2=s2): - expected = (OLD & 0xFFFF0000) | (want_full & MASK16) - self.assertEqual(ref_mad_i16(s0 & MASK16, s1 & MASK16, s2 & MASK16), expected) - - def test_signed_boundary_grid(self): - """Signed boundary values {-32768, -32767, -1, 0, 1, 32766, 32767}.""" - boundaries = [-32768, -32767, -1, 0, 1, 32766, 32767] - for s0 in boundaries: - for s1 in (-1, 0, 1, 2, -2): - for s2 in (-1, 0, 1): - full = s0 * s1 + s2 - expected = (OLD & 0xFFFF0000) | (full & MASK16) - self.assertEqual(ref_mad_i16(s0 & MASK16, s1 & MASK16, s2 & MASK16), expected) - - -class TestClampSaturation(unittest.TestCase): - """Saturated clamping modifiers: unsigned [0, 65535] vs signed [-32768, 32767].""" - - def test_v_mad_u16_clamp_saturates_above_65535(self): - """v_mad_u16 clamp saturates full-width values > 65535 to 65535 (0xFFFF).""" - overflow_cases = [ - (256, 256, 1), # 256 * 256 + 1 = 65537 -> 65535 (unclamped: 1) - (65535, 2, 0), # 65535 * 2 = 131070 -> 65535 (unclamped: 65534) - (65535, 65535, 65535), # 4294901760 -> 65535 (unclamped: 0) - (300, 300, 1000), # 91000 -> 65535 (unclamped: 25464) - (256, 256, 0), # 65536 -> 65535 (unclamped: 0) - ] - for s0, s1, s2 in overflow_cases: - with self.subTest(s0=s0, s1=s1, s2=s2): - expected = (OLD & 0xFFFF0000) | 0xFFFF - self.assertEqual(ref_mad_u16(s0, s1, s2, clamp=True), expected) - got = run_shader_mad("v_mad_u16 v0, v1, v2, v3 clamp", s0, s1, s2) - self.assertEqual(got, expected) - - def test_v_mad_u16_clamp_preserves_in_bounds(self): - """v_mad_u16 clamp preserves values <= 65535 unchanged.""" - in_bounds_cases = [ - (0, 0, 0, 0), - (3, 4, 5, 17), - (200, 200, 1000, 41000), - (1, 65535, 0, 65535), - (255, 255, 255, 65280), - ] - for s0, s1, s2, want in in_bounds_cases: - with self.subTest(s0=s0, s1=s1, s2=s2): - expected = (OLD & 0xFFFF0000) | want - self.assertEqual(ref_mad_u16(s0, s1, s2, clamp=True), expected) - got = run_shader_mad("v_mad_u16 v0, v1, v2, v3 clamp", s0, s1, s2) - self.assertEqual(got, expected) - - def test_v_mad_i16_clamp_positive_saturation_to_32767(self): - """v_mad_i16 clamp saturates full-width signed values > 32767 to 32767 (0x7FFF).""" - pos_overflow = [ - (32767, 2, 0), # 65534 -> 32767 (0x7FFF) - (200, 200, 0), # 40000 -> 32767 (0x7FFF) - (-32768, -2, 0), # 65536 -> 32767 (0x7FFF) - (-32768, -32768, 0), # 1073741824 -> 32767 (0x7FFF) - (32767, 32767, 32767), # 1073709056 -> 32767 (0x7FFF) - ] - for s0, s1, s2 in pos_overflow: - with self.subTest(s0=s0, s1=s1, s2=s2): - expected = (OLD & 0xFFFF0000) | 0x7FFF - self.assertEqual(ref_mad_i16(s0 & MASK16, s1 & MASK16, s2 & MASK16, clamp=True), expected) - got = run_shader_mad("v_mad_i16 v0, v1, v2, v3 clamp", s0 & MASK16, s1 & MASK16, s2 & MASK16) - self.assertEqual(got, expected) - - def test_v_mad_i16_clamp_negative_saturation_to_minus_32768(self): - """v_mad_i16 clamp saturates full-width signed values < -32768 to -32768 (0x8000).""" - neg_overflow = [ - (32767, -2, 0), # -65534 -> -32768 (0x8000) - (-200, 200, 0), # -40000 -> -32768 (0x8000) - (-200, 150, -5000), # -30000 - 5000 = -35000 -> -32768 (0x8000) - (-32768, 2, 0), # -65536 -> -32768 (0x8000) - (-32768, 1, -1), # -32768 - 1 = -32769 -> -32768 (0x8000) - ] - for s0, s1, s2 in neg_overflow: - with self.subTest(s0=s0, s1=s1, s2=s2): - expected = (OLD & 0xFFFF0000) | 0x8000 - self.assertEqual(ref_mad_i16(s0 & MASK16, s1 & MASK16, s2 & MASK16, clamp=True), expected) - got = run_shader_mad("v_mad_i16 v0, v1, v2, v3 clamp", s0 & MASK16, s1 & MASK16, s2 & MASK16) - self.assertEqual(got, expected) - - def test_v_mad_i16_clamp_preserves_in_bounds(self): - """v_mad_i16 clamp preserves values within [-32768, 32767].""" - in_bounds_cases = [ - (-1, 4, 0, -4), - (-100, 50, 10, -4990), - (32767, 1, 0, 32767), - (-32768, 1, 0, -32768), - (0, -50, 0, 0), - (10, 10, 10, 110), - ] - for s0, s1, s2, want in in_bounds_cases: - with self.subTest(s0=s0, s1=s1, s2=s2): - expected = (OLD & 0xFFFF0000) | (want & MASK16) - self.assertEqual(ref_mad_i16(s0 & MASK16, s1 & MASK16, s2 & MASK16, clamp=True), expected) - got = run_shader_mad("v_mad_i16 v0, v1, v2, v3 clamp", s0 & MASK16, s1 & MASK16, s2 & MASK16) - self.assertEqual(got, expected) - - def test_clamp_combined_with_opsel_and_dst_hi(self): - """Clamp modifier works correctly with arbitrary op_sel and dst_hi=1.""" - # Packed words: v1 hi=32767, lo=2; v2 hi=-2, lo=3; v3 hi=0, lo=10 - v1 = (0x7FFF << 16) | 2 - v2 = (0xFFFE << 16) | 3 - v3 = (0x0000 << 16) | 10 - # Select v1 hi (32767), v2 hi (-2), v3 hi (0) -> -65534 clamped to -32768 (0x8000), dst_hi=1 - line = "v_mad_i16 v0, v1, v2, v3 op_sel:[1,1,1,1] clamp" - old = 0x55551234 - expected = ref_mad_i16(v1, v2, v3, sel=(1, 1, 1), dst_hi=1, clamp=True, old_dst=old) - got = run_shader_mad(line, v1, v2, v3, old=old) - self.assertEqual(got, expected) - self.assertEqual(got >> 16, 0x8000) - self.assertEqual(got & MASK16, 0x1234) - - -class TestMadU16TranslationAndInterp(unittest.TestCase): - """End-to-end translation and execution of v_mad_u16 via rdna2spirv and spirv_mini_interp.""" - - def test_basic_known_values(self): - """Known integer values match expected results in spirv_mini_interp.""" - self.assertEqual(run_shader_mad("v_mad_u16 v0, v1, v2, v3", 7, 11, 13), (OLD & 0xFFFF0000) | 90) - self.assertEqual(run_shader_mad("v_mad_u16 v0, v1, v2, v3", 100, 200, 300), (OLD & 0xFFFF0000) | 20300) - self.assertEqual( - run_shader_mad("v_mad_u16 v0, v1, v2, v3", 65535, 2, 5), - (OLD & 0xFFFF0000) | ((65535 * 2 + 5) & MASK16), - ) - self.assertEqual( - run_shader_mad("v_mad_u16 v0, v1, v2, v3", 0xFFFF, 0xFFFF, 0xFFFF), - (OLD & 0xFFFF0000) | ((0xFFFF * 0xFFFF + 0xFFFF) & MASK16), - ) - - def test_keeps_high_half_of_destination(self): - """Untouched high half of destination register is preserved.""" - for old in (0x12345678, 0xCAFE0000, 0x0000BEEF, 0xFEEDFACE): - with self.subTest(old=hex(old)): - got = run_shader_mad("v_mad_u16 v0, v1, v2, v3", 3, 5, 7, old=old) - self.assertEqual(got >> 16, old >> 16) - self.assertEqual(got & MASK16, 22) - - def test_source_op_sel_patterns(self): - """Selective extraction of low and high halfwords via op_sel:[s0, s1, s2, 0].""" - v1 = 0x0007_0003 - v2 = 0x000B_0005 - v3 = 0x000D_0002 - cases = [ - ((0, 0, 0), ref_mad_u16(v1, v2, v3, sel=(0, 0, 0))), - ((1, 0, 0), ref_mad_u16(v1, v2, v3, sel=(1, 0, 0))), - ((0, 1, 0), ref_mad_u16(v1, v2, v3, sel=(0, 1, 0))), - ((0, 0, 1), ref_mad_u16(v1, v2, v3, sel=(0, 0, 1))), - ((1, 1, 0), ref_mad_u16(v1, v2, v3, sel=(1, 1, 0))), - ((1, 0, 1), ref_mad_u16(v1, v2, v3, sel=(1, 0, 1))), - ((0, 1, 1), ref_mad_u16(v1, v2, v3, sel=(0, 1, 1))), - ((1, 1, 1), ref_mad_u16(v1, v2, v3, sel=(1, 1, 1))), - ] - for sel, expected in cases: - line = f"v_mad_u16 v0, v1, v2, v3 op_sel:[{sel[0]},{sel[1]},{sel[2]},0]" - with self.subTest(sel=sel): - self.assertEqual(run_shader_mad(line, v1, v2, v3), expected) - - def test_dst_hi_op_sel(self): - """Destination high-half placement preserves low half of destination.""" - v1 = 0x0007_0003 - v2 = 0x000B_0005 - v3 = 0x000D_0002 - line = "v_mad_u16 v0, v1, v2, v3 op_sel:[0,0,0,1]" - expected = ref_mad_u16(v1, v2, v3, sel=(0, 0, 0), dst_hi=1, old_dst=0x12345678) - got = run_shader_mad(line, v1, v2, v3, old=0x12345678) - self.assertEqual(got, expected) - self.assertEqual(got & MASK16, 0x5678) - self.assertEqual(got >> 16, 17) - - def test_random_against_reference_oracle(self): - """Deterministic pseudo-random differential test against the reference oracle.""" - rng = random.Random(0x1616) - candidates = [0, 1, 2, 255, 256, 32767, 32768, 65534, 65535] - for _ in range(25): - v1 = rng.choice(candidates) if rng.random() < 0.3 else rng.randrange(0x100000000) - v2 = rng.choice(candidates) if rng.random() < 0.3 else rng.randrange(0x100000000) - v3 = rng.choice(candidates) if rng.random() < 0.3 else rng.randrange(0x100000000) - sel = (rng.randrange(2), rng.randrange(2), rng.randrange(2)) - dst_hi = rng.randrange(2) - clamp = rng.random() < 0.5 - old = rng.randrange(0x100000000) - clamp_str = " clamp" if clamp else "" - line = f"v_mad_u16 v0, v1, v2, v3 op_sel:[{sel[0]},{sel[1]},{sel[2]},{dst_hi}]{clamp_str}" - expected = ref_mad_u16(v1, v2, v3, sel=sel, dst_hi=dst_hi, clamp=clamp, old_dst=old) - with self.subTest(sel=sel, dst_hi=dst_hi, clamp=clamp): - self.assertEqual(run_shader_mad(line, v1, v2, v3, old=old), expected) - - -class TestMadI16TranslationAndInterp(unittest.TestCase): - """End-to-end translation and execution of v_mad_i16 via rdna2spirv and spirv_mini_interp.""" - - def test_known_signed_values(self): - """Known signed integer values match expected results.""" - # -2 * 3 + 5 = -1 (0xFFFF) - self.assertEqual(run_shader_mad("v_mad_i16 v0, v1, v2, v3", 0xFFFE, 3, 5), (OLD & 0xFFFF0000) | 0xFFFF) - # 32767 * 2 + 0 = 65534 -> -2 (0xFFFE) - self.assertEqual(run_shader_mad("v_mad_i16 v0, v1, v2, v3", 0x7FFF, 2, 0), (OLD & 0xFFFF0000) | 0xFFFE) - # 32767 * 2 + 0 clamp -> 32767 (0x7FFF) - self.assertEqual(run_shader_mad("v_mad_i16 v0, v1, v2, v3 clamp", 0x7FFF, 2, 0), (OLD & 0xFFFF0000) | 0x7FFF) - # 32767 * -2 + 0 clamp -> -32768 (0x8000) - self.assertEqual(run_shader_mad("v_mad_i16 v0, v1, v2, v3 clamp", 0x7FFF, 0xFFFE, 0), (OLD & 0xFFFF0000) | 0x8000) - # -1 * 4 + 0 clamp -> -4 (0xFFFC) - self.assertEqual(run_shader_mad("v_mad_i16 v0, v1, v2, v3 clamp", 0xFFFF, 4, 0), (OLD & 0xFFFF0000) | 0xFFFC) - - def test_random_signed_against_reference_oracle(self): - """Deterministic pseudo-random differential test of v_mad_i16 against ref_mad_i16.""" - rng = random.Random(0x1617) - candidates = [0, 1, 0x7FFF, 0x8000, 0x8001, 0xFFFE, 0xFFFF] - for _ in range(25): - v1 = rng.choice(candidates) if rng.random() < 0.3 else rng.randrange(0x100000000) - v2 = rng.choice(candidates) if rng.random() < 0.3 else rng.randrange(0x100000000) - v3 = rng.choice(candidates) if rng.random() < 0.3 else rng.randrange(0x100000000) - sel = (rng.randrange(2), rng.randrange(2), rng.randrange(2)) - dst_hi = rng.randrange(2) - clamp = rng.random() < 0.5 - old = rng.randrange(0x100000000) - clamp_str = " clamp" if clamp else "" - line = f"v_mad_i16 v0, v1, v2, v3 op_sel:[{sel[0]},{sel[1]},{sel[2]},{dst_hi}]{clamp_str}" - expected = ref_mad_i16(v1, v2, v3, sel=sel, dst_hi=dst_hi, clamp=clamp, old_dst=old) - with self.subTest(sel=sel, dst_hi=dst_hi, clamp=clamp): - self.assertEqual(run_shader_mad(line, v1, v2, v3, old=old), expected) - - -class TestPackedHalfwordExecution(unittest.TestCase): - """Exhaustive op_sel permutations, register aliasing, and scalar/constant operands.""" - - def test_all_sixteen_op_sel_permutations(self): - """Test all 2^4 = 16 op_sel bit patterns on both v_mad_u16 and v_mad_i16.""" - a = 0x0003_0007 # hi=3, lo=7 - b = 0x0005_000B # hi=5, lo=11 - c = 0x0002_000D # hi=2, lo=13 - for op in ("v_mad_u16", "v_mad_i16"): - ref_fn = ref_mad_u16 if op == "v_mad_u16" else ref_mad_i16 - for bits in itertools.product((0, 1), repeat=4): - line = f"{op} v0, v1, v2, v3 op_sel:[{bits[0]},{bits[1]},{bits[2]},{bits[3]}]" - expected = ref_fn(a, b, c, sel=bits[:3], dst_hi=bits[3]) - with self.subTest(op=op, op_sel=bits): - self.assertEqual(run_shader_mad(line, a, b, c), expected) - - def test_destination_register_aliasing(self): - """Register aliasing: destination aliases one or more source registers.""" - init_v0 = 0x12340003 - init_v1 = 0x56780005 - init_v2 = 0x9ABC0007 - - # v0 = v0 * v1 + v2 (dst aliases src0) - line1 = "v_mad_u16 v0, v0, v1, v2" - # s0=3, s1=5, s2=7 -> 22 (0x0016), preserved high half=0x1234 - expected1 = (init_v0 & 0xFFFF0000) | (3 * 5 + 7) - got1 = run_shader_mad(line1, init_v1, init_v2, 0, old=init_v0) - self.assertEqual(got1, expected1) - - # v0 = v1 * v0 + v2 (dst aliases src1) - line2 = "v_mad_u16 v0, v1, v0, v2" - expected2 = (init_v0 & 0xFFFF0000) | (5 * 3 + 7) - got2 = run_shader_mad(line2, init_v1, init_v2, 0, old=init_v0) - self.assertEqual(got2, expected2) - - # v0 = v1 * v2 + v0 (dst aliases src2) - line3 = "v_mad_u16 v0, v1, v2, v0" - expected3 = (init_v0 & 0xFFFF0000) | (5 * 7 + 3) - got3 = run_shader_mad(line3, init_v1, init_v2, 0, old=init_v0) - self.assertEqual(got3, expected3) - - # v0 = v0 * v0 + v0 (all operands alias destination) - line4 = "v_mad_u16 v0, v0, v0, v0" - expected4 = (init_v0 & 0xFFFF0000) | (3 * 3 + 3) - got4 = run_shader_mad(line4, 0, 0, 0, old=init_v0) - self.assertEqual(got4, expected4) - - def test_scalar_sgpr_and_inline_constants(self): - """Scalar SGPR and inline constant operand support in v_mad_u16 and v_mad_i16.""" - s4_val = 0xCAFE0005 - v1_val = 0xBEEF0003 - v2_val = 0x12340002 - - # v_mad_u16 v0, s4, v1, 10 - # s0 = s4(lo)=5, s1 = v1(lo)=3, s2 = 10 -> 5 * 3 + 10 = 25 - lines_sgpr = [ - f"s_mov_b32 s4, {s4_val:#x}", - f"v_mov_b32 v1, {v1_val:#x}", - f"v_mov_b32 v2, {v2_val:#x}", - f"v_mov_b32 v0, {OLD:#x}", - "v_mad_u16 v0, s4, v1, 10", - "exp mrt0 v0, v0, v0, v0 done vm", - ] - spv = translate_custom_lines(lines_sgpr) - got = si.run_fragment(spv)["%out_mrt0"][0] - self.assertEqual(got, (OLD & 0xFFFF0000) | 25) - - # v_mad_i16 v0, -1, s4, 2 - # s0 = -1 (0xFFFFFFFF sign-extended is -1), s1 = 5, s2 = 2 -> -1 * 5 + 2 = -3 (0xFFFD) - lines_const = [ - f"s_mov_b32 s4, {s4_val:#x}", - f"v_mov_b32 v0, {OLD:#x}", - "v_mad_i16 v0, -1, s4, 2", - "exp mrt0 v0, v0, v0, v0 done vm", - ] - spv2 = translate_custom_lines(lines_const) - got2 = si.run_fragment(spv2)["%out_mrt0"][0] - self.assertEqual(got2, (OLD & 0xFFFF0000) | ((-3) & MASK16)) - - -class TestSimdExecDivergence(unittest.TestCase): - """Multi-lane SIMD divergence under EXEC mask.""" - - def test_simd_wave_model_divergence_patterns(self): - """SIMD wave model verifies lane masking, active vs inactive lanes, and join convergence.""" - wave32 = SimdWave(wave_size=32, exec_mask=0x55555555) # even lanes active - # s0=3, s1=5, s2=7 -> 22 (0x0016), preserved high half=0xAAAA - wave32.exec_mad_u16(vd=0, s0=3, s1=5, s2=7) - for lane in range(32): - if lane % 2 == 0: - self.assertEqual(wave32.vgprs[lane][0], (OLD & 0xFFFF0000) | 22) - else: - self.assertEqual(wave32.vgprs[lane][0], OLD) - - wave64 = SimdWave(wave_size=64, exec_mask=0x00000000FFFFFFFF) # low 32 lanes active - wave64.exec_mad_i16(vd=0, s0=0xFFFE, s1=3, s2=5) # -2 * 3 + 5 = -1 (0xFFFF) - for lane in range(64): - if lane < 32: - self.assertEqual(wave64.vgprs[lane][0], (OLD & 0xFFFF0000) | 0xFFFF) - else: - self.assertEqual(wave64.vgprs[lane][0], OLD) - - def test_inactive_lane_preservation_under_v_cmpx(self): - """Shader execution turns off EXEC with v_cmpx; destination register remains untouched.""" - for op in ("v_mad_u16", "v_mad_i16"): - with self.subTest(op=op): - lines = [ - f"v_mov_b32 v0, {OLD:#x}", - "v_mov_b32 v1, 0x12345678", - "v_mov_b32 v2, 0x9abcdef0", - "v_mov_b32 v3, 0x00112233", - "v_cmpx_eq_u32_e32 vcc_lo, 0, 1", # disable all lanes in exec - f"{op} v0, v1, v2, v3", - "s_mov_b32 exec_lo, -1", # restore exec for export - "exp mrt0 v0, v0, v0, v0 done vm", - ] - spv = translate_custom_lines(lines) - got = si.run_fragment(spv)["%out_mrt0"][0] - self.assertEqual(got, OLD) - - def test_compute_shader_simd_workgroup_divergence(self): - """Compute shader workgroup across 32 lanes with divergence on v0 < 16.""" - with tempfile.TemporaryDirectory() as tmp: - disasm_dir = os.path.join(tmp, "disasm") - fssm_dir = os.path.join(tmp, "fssm") - os.mkdir(disasm_dir) - os.mkdir(fssm_dir) - s_path = os.path.join(disasm_dir, "cs_mad_div.s") - # Lanes 0..15 execute v_mad_u16; lanes 16..31 remain inactive - lines = [ - "v_mov_b32 v1, 3", - "v_mov_b32 v2, 5", - "v_mov_b32 v3, 7", - "v_mov_b32 v4, 0x12345678", - "v_cmp_lt_u32_e32 vcc_lo, v0, 16", - "s_and_saveexec_b32 s4, vcc_lo", - "v_mad_u16 v4, v1, v2, v3", - "s_mov_b32 exec_lo, s4", - "v_mul_lo_u32 v5, v0, 4", - "buffer_store_dword v4, v5, s[0:3], 0 offen", - "s_endpgm", - ] - with open(s_path, "w", encoding="utf-8") as f: - f.write("; cs_mad_div\n" + "".join(f"\t{ln}\n" for ln in lines)) - with open(os.path.join(tmp, "cs_mad_div.dxbc"), "wb") as f: - f.write(STUB_DXBC) - with open(os.path.join(fssm_dir, "cs_mad_div.fssm"), "wb") as f: - f.write(bytes(0x138) + struct.pack("<4I", 0x8088, 32, 1, 1)) - - spv = rdna2spirv.translate(s_path) - vsharp = [0, 0, 0xFFFFFFFF, 0x31016FAC] + [0] * 28 - mem = si.run_workgroup( - spv, - 32, - 32, - inputs_for=lambda i: {"%wg_id": (0, 0, 0), "%local_id": (i, 0, 0), "%sg_lane": i}, - push_constants=vsharp, - memory={}, - ) - # Active lanes (0..15): 3 * 5 + 7 = 22 (0x0016), preserved high half=0x1234 - for lane in range(16): - self.assertEqual(mem[lane * 4], 0x12340016, f"active lane {lane}") - # Inactive lanes (16..31): preserved initial 0x12345678 - for lane in range(16, 32): - self.assertEqual(mem[lane * 4], 0x12345678, f"inactive lane {lane}") - - -class TestNegativeControls(unittest.TestCase): - """Negative controls / mutation detection on translated SPIR-V assembly.""" - - def test_detects_signed_vs_unsigned_extract(self): - """Mutating OpBitFieldSExtract to OpBitFieldUExtract breaks signed clamp saturation.""" - lines = [ - "v_mov_b32 v1, 0xFFFE", - "v_mov_b32 v2, 3", - "v_mov_b32 v3, 5", - "v_mov_b32 v0, 0xAAAA5555", - "v_mad_i16 v0, v1, v2, v3 clamp", - "exp mrt0 v0, v0, v0, v0 done vm", - ] - good = translate_custom_lines(lines) - res_good = si.run_fragment(good)["%out_mrt0"][0] - self.assertEqual(res_good, 0xAAAAFFFF) - - bad, count = re.subn(r"OpBitFieldSExtract", "OpBitFieldUExtract", good) - self.assertGreaterEqual(count, 1) - res_bad = si.run_fragment(bad)["%out_mrt0"][0] - self.assertNotEqual(res_good, res_bad) - - def test_detects_multiplication_mutated_to_addition(self): - """Mutating OpIMul to OpIAdd breaks arithmetic evaluation.""" - lines = [ - "v_mov_b32 v1, 3", - "v_mov_b32 v2, 5", - "v_mov_b32 v3, 7", - "v_mov_b32 v0, 0xAAAA5555", - "v_mad_u16 v0, v1, v2, v3", - "exp mrt0 v0, v0, v0, v0 done vm", - ] - good = translate_custom_lines(lines) - res_good = si.run_fragment(good)["%out_mrt0"][0] - self.assertEqual(res_good, 0xAAAA0016) - - bad, count = re.subn(r"OpIMul", "OpIAdd", good) - self.assertEqual(count, 1) - res_bad = si.run_fragment(bad)["%out_mrt0"][0] - self.assertNotEqual(res_good, res_bad) - - def test_detects_unsigned_clamp_comparison_inversion(self): - """Mutating OpUGreaterThan to OpULessThan breaks unsigned clamp saturation.""" - lines = [ - "v_mov_b32 v1, 256", - "v_mov_b32 v2, 256", - "v_mov_b32 v3, 1", - "v_mov_b32 v0, 0xAAAA5555", - "v_mad_u16 v0, v1, v2, v3 clamp", - "exp mrt0 v0, v0, v0, v0 done vm", - ] - good = translate_custom_lines(lines) - res_good = si.run_fragment(good)["%out_mrt0"][0] - self.assertEqual(res_good, 0xAAAAFFFF) - - bad, count = re.subn(r"OpUGreaterThan", "OpULessThan", good) - self.assertEqual(count, 1) - res_bad = si.run_fragment(bad)["%out_mrt0"][0] - self.assertNotEqual(res_good, res_bad) - - def test_detects_signed_clamp_bound_inversion(self): - """Mutating glsl SMin to glsl SMax in signed clamp breaks upper saturation.""" - lines = [ - "v_mov_b32 v1, 32767", - "v_mov_b32 v2, 2", - "v_mov_b32 v3, 0", - "v_mov_b32 v0, 0xAAAA5555", - "v_mad_i16 v0, v1, v2, v3 clamp", - "exp mrt0 v0, v0, v0, v0 done vm", - ] - good = translate_custom_lines(lines) - res_good = si.run_fragment(good)["%out_mrt0"][0] - self.assertEqual(res_good, 0xAAAA7FFF) - - bad, count = re.subn(r"glsl SMin", "glsl SMax", good) - self.assertEqual(count, 1) - res_bad = si.run_fragment(bad)["%out_mrt0"][0] - self.assertNotEqual(res_good, res_bad) - - def test_detects_destination_high_half_loss(self): - """Mutating high half mask preservation breaks destination register retention.""" - lines = [ - "v_mov_b32 v1, 3", - "v_mov_b32 v2, 5", - "v_mov_b32 v3, 7", - "v_mov_b32 v0, 0xAAAA5555", - "v_mad_u16 v0, v1, v2, v3", - "exp mrt0 v0, v0, v0, v0 done vm", - ] - good = translate_custom_lines(lines) - res_good = si.run_fragment(good)["%out_mrt0"][0] - self.assertEqual(res_good, 0xAAAA0016) - - bad, count = re.subn(r"OpBitwiseAnd %uint (%\w+) %cffff0000", r"OpBitwiseAnd %uint \1 %c0", good) - self.assertEqual(count, 1) - res_bad = si.run_fragment(bad)["%out_mrt0"][0] - self.assertNotEqual(res_good, res_bad) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_alu_mad_u16_i16.py b/tests/semantic/test_alu_mad_u16_i16.py deleted file mode 100644 index 46718dd9f..000000000 --- a/tests/semantic/test_alu_mad_u16_i16.py +++ /dev/null @@ -1,126 +0,0 @@ -"""Semantic interpreter tests for RDNA2 v_mad_u16 and v_mad_i16. - -D.u16 = S0.u16 * S1.u16 + S2.u16 on the low halves (VOP3 only). op_sel bits 0..2 read the high half of a source, bit 3 -writes the result to the high half of the destination; the other half of the destination is kept (RDNA2 ISA; Mesa ACO -can_use_opsel, as for the other opsel-capable 16-bit VOP3 ops, docs/design.md "16-bit results"). With `clamp` the -full-width result saturates to [0, 65535] (u16) or [-32768, 32767] (i16). Each case translates a synthetic pixel -shader with tools/rdna2spirv.py, runs it in tests/semantic/spirv_mini_interp.py and compares the exported word with a -plain-Python reference. The hardware behaviour of `clamp` on the multiply-add and of the kept half is not measured. -""" -import itertools -import os -import random -import struct -import sys -import tempfile -import unittest -import warnings - -HERE = os.path.dirname(os.path.abspath(__file__)) -ROOT = os.path.dirname(os.path.dirname(HERE)) -TOOLS_DIR = os.environ.get("LEONIDA_TOOLS_DIR") or os.path.join(ROOT, "tools") - -sys.dont_write_bytecode = True -sys.path.insert(0, TOOLS_DIR) -sys.path.insert(0, HERE) - -import rdna2spirv # noqa: E402 -import spirv_mini_interp as si # noqa: E402 - -STUB_DXBC = b"DXBC" + bytes(24) + struct.pack(" int: - if _TMP_DIR is None: - setUpModule() - lines = [f"v_mov_b32 v1, {v1:#x}", f"v_mov_b32 v2, {v2:#x}", f"v_mov_b32 v3, {v3:#x}", f"v_mov_b32 v0, {old:#x}", line] - asm = "; test_mad16\n" + "".join(f"\t{ln}\n" for ln in lines) + "\texp mrt0 v0, v0, v0, v0 done vm\n\ts_endpgm\n" - with open(_SRC_PATH, "w", encoding="utf-8") as f: - f.write(asm) - with warnings.catch_warnings(): - warnings.simplefilter("ignore", ResourceWarning) - spv = rdna2spirv.translate(_SRC_PATH) - return si.run_fragment(spv)["%out_mrt0"][0] - - -def half(word: int, hi: int, signed: bool) -> int: - h = (word >> 16 if hi else word) & 0xFFFF - return h - 0x10000 if signed and h & 0x8000 else h - - -def ref(op: str, v1, v2, v3, sel=(0, 0, 0), dst_hi=0, clamp=False, old=OLD) -> int: - signed = op.endswith("i16") - x, y, z = (half(w, s, signed) for w, s in zip((v1, v2, v3), sel)) - r = x * y + z - if clamp: - lo, hi = (-0x8000, 0x7FFF) if signed else (0, 0xFFFF) - r = max(lo, min(hi, r)) - r &= 0xFFFF - return (r << 16 | old & 0xFFFF) if dst_hi else (old & 0xFFFF0000 | r) - - -class MadTests(unittest.TestCase): - def test_reference(self): - self.assertEqual(ref("v_mad_u16", A, B, C), 0xAAAA0000 | (7 * 11 + 13)) - self.assertEqual(ref("v_mad_i16", 0xFFFF, 3, 0), 0xAAAA0000 | 0xFFFD) - - def test_known_values(self): - self.assertEqual(run("v_mad_u16 v0, v1, v2, v3", A, B, C), 0xAAAA0000 | 90) - self.assertEqual(run("v_mad_i16 v0, v1, v2, v3", 0xFFFE, 3, 5), 0xAAAA0000 | (-1 & 0xFFFF)) # -2*3+5 - self.assertEqual(run("v_mad_u16 v0, v1, v2, v3", 0xFFFF, 0xFFFF, 0xFFFF), 0xAAAA0000 | ((0xFFFF * 0xFFFF + 0xFFFF) & 0xFFFF)) - - def test_keeps_the_high_half_of_the_destination(self): - self.assertEqual(run("v_mad_u16 v0, v1, v2, v3", A, B, C, old=0x12345678) >> 16, 0x1234) - - def test_op_sel_all_sixteen_patterns(self): - for op in ("v_mad_u16", "v_mad_i16"): - for bits in itertools.product((0, 1), repeat=4): - line = f"{op} v0, v1, v2, v3 op_sel:[{bits[0]},{bits[1]},{bits[2]},{bits[3]}]" - with self.subTest(line=line): - self.assertEqual(run(line, A, B, C), ref(op, A, B, C, bits[:3], bits[3])) - - def test_clamp_saturates(self): - self.assertEqual(run("v_mad_u16 v0, v1, v2, v3 clamp", 0x100, 0x100, 5), 0xAAAA0000 | 0xFFFF) - self.assertEqual(run("v_mad_u16 v0, v1, v2, v3 clamp", 3, 4, 5), 0xAAAA0000 | 17) - self.assertEqual(run("v_mad_i16 v0, v1, v2, v3 clamp", 0x7FFF, 2, 0), 0xAAAA0000 | 0x7FFF) - self.assertEqual(run("v_mad_i16 v0, v1, v2, v3 clamp", 0x7FFF, 0xFFFE, 0), 0xAAAA0000 | 0x8000) # -65534 -> -32768 - self.assertEqual(run("v_mad_i16 v0, v1, v2, v3 clamp", 0xFFFF, 4, 0), 0xAAAA0000 | 0xFFFC) # -4 unchanged - - def test_random_against_the_reference(self): - rng = random.Random(0x16) - special = [0, 1, 0x7FFF, 0x8000, 0xFFFF, 0xFFFE] - pick = lambda: rng.choice(special) if rng.random() < 0.3 else rng.randrange(0x10000) - for op in ("v_mad_u16", "v_mad_i16"): - for clamp in (False, True): - for _ in range(25): - v1, v2, v3 = (pick() | pick() << 16 for _ in range(3)) - sel = tuple(rng.randrange(2) for _ in range(3)) - line = f"{op} v0, v1, v2, v3 op_sel:[{sel[0]},{sel[1]},{sel[2]},0]" + (" clamp" if clamp else "") - with self.subTest(line=line, v=(hex(v1), hex(v2), hex(v3))): - self.assertEqual(run(line, v1, v2, v3), ref(op, v1, v2, v3, sel, 0, clamp)) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_alu_madak_subrev.py b/tests/semantic/test_alu_madak_subrev.py deleted file mode 100644 index 91410d74a..000000000 --- a/tests/semantic/test_alu_madak_subrev.py +++ /dev/null @@ -1,470 +0,0 @@ -"""Semantic interpreter tests for AMD RDNA2 v_subrev_f32, v_madak_f32, and v_madmk_f32. - -Instructions covered: - - v_subrev_f32: D.f32 = S1.f32 - S0.f32 (VOP2 0x33 / VOP3 0x2bb on GFX10), the reversed form of v_sub_f32. - Supports VOP3 clamp to [0, 1] and input modifiers (neg, abs) on either or both operands. - - v_madak_f32: D.f32 = S0.f32 * S1.f32 + K.f32 (VOP2 0x3b on GFX10), where K is a 32-bit inline literal constant. - Lowered to OpFMul followed by OpFAdd. - - v_madmk_f32: D.f32 = S0.f32 * K.f32 + S1.f32 (VOP2 0x3c on GFX10), where K is a 32-bit inline literal constant. - In assembly print order `vdst, src0, K, vsrc1`, S0 is multiplied by K and S1 is added. - -Standard library only: zero game data, no GPU hardware required. -""" -from __future__ import annotations - -import gc -import math -import os -import random -import struct -import sys -import tempfile -import unittest -import warnings - -HERE = os.path.dirname(os.path.abspath(__file__)) -ROOT = os.path.dirname(os.path.dirname(HERE)) -TOOLS_DIR = os.environ.get("LEONIDA_TOOLS_DIR") or os.path.join(ROOT, "tools") - -sys.dont_write_bytecode = True -if TOOLS_DIR not in sys.path: - sys.path.insert(0, TOOLS_DIR) -if HERE not in sys.path: - sys.path.insert(0, HERE) - -import rdna2spirv # noqa: E402 -import spirv_mini_interp as si # noqa: E402 -from support import mrt0_words, translate_lines # noqa: E402 - -EXIT = ["exp mrt0 v0, v1, v2, v3 done vm", "s_endpgm"] -STUB_DXBC = b"DXBC" + bytes(24) + struct.pack(" int: - """Float -> uint32 bit pattern.""" - return struct.unpack(" float: - """Uint32 bit pattern -> float.""" - return struct.unpack(" float: - """Reference single-precision reversed subtract: S1 - S0.""" - return u2f(f2u(s1 - s0)) - - -def ref_subrev_f32_clamped(s0: float, s1: float) -> float: - """Reference reversed subtract with VOP3 clamp to [0.0, 1.0].""" - diff = s1 - s0 - if math.isnan(diff): - return 0.0 - return max(0.0, min(1.0, diff)) - - -def ref_madak_f32(s0: float, s1: float, k: float) -> float: - """Reference non-fused multiply-add for v_madak_f32: S0 * S1 + K.""" - prod = u2f(f2u(s0 * s1)) - return u2f(f2u(prod + k)) - - -def ref_madmk_f32(s0: float, k: float, s1: float) -> float: - """Reference non-fused multiply-add for v_madmk_f32: S0 * K + S1.""" - prod = u2f(f2u(s0 * k)) - return u2f(f2u(prod + s1)) - - -class SubrevF32Tests(unittest.TestCase): - """Semantic tests for v_subrev_f32.""" - - def _run_subrev(self, s0_val: float, s1_val: float, opcode: str = "v_subrev_f32") -> float: - lines = [ - f"v_mov_b32 v1, 0x{f2u(s0_val):08x}", - f"v_mov_b32 v2, 0x{f2u(s1_val):08x}", - f"{opcode} v0, v1, v2", - "v_mov_b32 v1, 0", - "v_mov_b32 v2, 0", - "v_mov_b32 v3, 0", - ] + EXIT - spv = translate_lines("ps_subrev", lines) - res = mrt0_words(spv) - return u2f(res[0]) - - def test_operand_order_reversed_basic(self): - # 3.5 - 1.0 = 2.5 - res = self._run_subrev(1.0, 3.5) - self.assertAlmostEqual(res, 2.5, places=6) - - # 1.0 - 3.5 = -2.5 - res_neg = self._run_subrev(3.5, 1.0) - self.assertAlmostEqual(res_neg, -2.5, places=6) - - def test_contrasting_with_v_sub_f32(self): - # Guarantee that v_subrev_f32(a, b) == -v_sub_f32(a, b) - a, b = 2.75, 8.125 - res_subrev = self._run_subrev(a, b) - - lines_sub = [ - f"v_mov_b32 v1, 0x{f2u(a):08x}", - f"v_mov_b32 v2, 0x{f2u(b):08x}", - "v_sub_f32 v0, v1, v2", - "v_mov_b32 v1, 0", - "v_mov_b32 v2, 0", - "v_mov_b32 v3, 0", - ] + EXIT - spv_sub = translate_lines("ps_sub", lines_sub) - res_sub = u2f(mrt0_words(spv_sub)[0]) - - self.assertAlmostEqual(res_subrev, b - a, places=6) - self.assertAlmostEqual(res_sub, a - b, places=6) - self.assertAlmostEqual(res_subrev, -res_sub, places=6) - - def test_identities_and_zeros(self): - # x - 0.0 = x - self.assertEqual(self._run_subrev(0.0, 42.0), 42.0) - # 0.0 - x = -x - self.assertEqual(self._run_subrev(42.0, 0.0), -42.0) - # x - x = 0.0 - self.assertEqual(self._run_subrev(13.5, 13.5), 0.0) - - def test_negative_values(self): - # (-2.0) - 5.0 = -7.0 -> subrev(5.0, -2.0) = -2.0 - 5.0 = -7.0 - self.assertEqual(self._run_subrev(5.0, -2.0), -7.0) - # 5.0 - (-2.0) = 7.0 -> subrev(-2.0, 5.0) = 5.0 - (-2.0) = 7.0 - self.assertEqual(self._run_subrev(-2.0, 5.0), 7.0) - - def test_vop3_clamp(self): - # Below zero clamps to 0.0 - lines_under = [ - f"v_mov_b32 v1, 0x{f2u(4.0):08x}", - f"v_mov_b32 v2, 0x{f2u(1.0):08x}", - "v_subrev_f32_e64 v0, v1, v2 clamp", # 1.0 - 4.0 = -3.0 -> clamp 0.0 - "v_mov_b32 v1, 0", - "v_mov_b32 v2, 0", - "v_mov_b32 v3, 0", - ] + EXIT - res_under = u2f(mrt0_words(translate_lines("ps_subrev_clamp1", lines_under))[0]) - self.assertEqual(res_under, 0.0) - - # Above 1.0 clamps to 1.0 - lines_over = [ - f"v_mov_b32 v1, 0x{f2u(2.0):08x}", - f"v_mov_b32 v2, 0x{f2u(5.0):08x}", - "v_subrev_f32_e64 v0, v1, v2 clamp", # 5.0 - 2.0 = 3.0 -> clamp 1.0 - "v_mov_b32 v1, 0", - "v_mov_b32 v2, 0", - "v_mov_b32 v3, 0", - ] + EXIT - res_over = u2f(mrt0_words(translate_lines("ps_subrev_clamp2", lines_over))[0]) - self.assertEqual(res_over, 1.0) - - # In-range preserves value - lines_mid = [ - f"v_mov_b32 v1, 0x{f2u(0.25):08x}", - f"v_mov_b32 v2, 0x{f2u(0.75):08x}", - "v_subrev_f32_e64 v0, v1, v2 clamp", # 0.75 - 0.25 = 0.5 - "v_mov_b32 v1, 0", - "v_mov_b32 v2, 0", - "v_mov_b32 v3, 0", - ] + EXIT - res_mid = u2f(mrt0_words(translate_lines("ps_subrev_clamp3", lines_mid))[0]) - self.assertEqual(res_mid, 0.5) - - def test_vop3_input_modifiers(self): - # v2 - (-v1) = v2 + v1 - lines_neg0 = [ - f"v_mov_b32 v1, 0x{f2u(2.0):08x}", - f"v_mov_b32 v2, 0x{f2u(3.0):08x}", - "v_subrev_f32_e64 v0, -v1, v2", # 3.0 - (-2.0) = 5.0 - "v_mov_b32 v1, 0", - "v_mov_b32 v2, 0", - "v_mov_b32 v3, 0", - ] + EXIT - self.assertEqual(u2f(mrt0_words(translate_lines("ps_neg0", lines_neg0))[0]), 5.0) - - # (-v2) - v1 = -(v2 + v1) - lines_neg1 = [ - f"v_mov_b32 v1, 0x{f2u(2.0):08x}", - f"v_mov_b32 v2, 0x{f2u(3.0):08x}", - "v_subrev_f32_e64 v0, v1, -v2", # (-3.0) - 2.0 = -5.0 - "v_mov_b32 v1, 0", - "v_mov_b32 v2, 0", - "v_mov_b32 v3, 0", - ] + EXIT - self.assertEqual(u2f(mrt0_words(translate_lines("ps_neg1", lines_neg1))[0]), -5.0) - - # v2 - |v1| - lines_abs0 = [ - f"v_mov_b32 v1, 0x{f2u(-4.0):08x}", - f"v_mov_b32 v2, 0x{f2u(10.0):08x}", - "v_subrev_f32_e64 v0, |v1|, v2", # 10.0 - |-4.0| = 6.0 - "v_mov_b32 v1, 0", - "v_mov_b32 v2, 0", - "v_mov_b32 v3, 0", - ] + EXIT - self.assertEqual(u2f(mrt0_words(translate_lines("ps_abs0", lines_abs0))[0]), 6.0) - - # |v2| - v1 - lines_abs1 = [ - f"v_mov_b32 v1, 0x{f2u(3.0):08x}", - f"v_mov_b32 v2, 0x{f2u(-7.0):08x}", - "v_subrev_f32_e64 v0, v1, |v2|", # |-7.0| - 3.0 = 4.0 - "v_mov_b32 v1, 0", - "v_mov_b32 v2, 0", - "v_mov_b32 v3, 0", - ] + EXIT - self.assertEqual(u2f(mrt0_words(translate_lines("ps_abs1", lines_abs1))[0]), 4.0) - - def test_inline_constants_and_sgprs(self): - # v1 - 1.0 - lines_const = [ - f"v_mov_b32 v1, 0x{f2u(3.5):08x}", - "v_subrev_f32 v0, 1.0, v1", # 3.5 - 1.0 = 2.5 - "v_mov_b32 v1, 0", - "v_mov_b32 v2, 0", - "v_mov_b32 v3, 0", - ] + EXIT - self.assertEqual(u2f(mrt0_words(translate_lines("ps_const", lines_const))[0]), 2.5) - - # v1 - s0 - lines_sgpr = [ - f"s_mov_b32 s0, 0x{f2u(1.25):08x}", - f"v_mov_b32 v1, 0x{f2u(6.25):08x}", - "v_subrev_f32 v0, s0, v1", # 6.25 - 1.25 = 5.0 - "v_mov_b32 v1, 0", - "v_mov_b32 v2, 0", - "v_mov_b32 v3, 0", - ] + EXIT - self.assertEqual(u2f(mrt0_words(translate_lines("ps_sgpr", lines_sgpr))[0]), 5.0) - - def test_spirv_lowering_instruction(self): - lines = [ - "v_mov_b32 v1, 0x3f800000", - "v_mov_b32 v2, 0x40800000", - "v_subrev_f32 v0, v1, v2", - ] + EXIT - spv = translate_lines("ps_spv_check", lines) - # S1 is first argument to OpFSub, S0 is second argument - self.assertIn("OpFSub %float", spv) - - -class MadakF32Tests(unittest.TestCase): - """Semantic tests for v_madak_f32: D = S0 * S1 + K.""" - - def _run_madak(self, s0: float, s1: float, k: float) -> float: - lines = [ - f"v_mov_b32 v1, 0x{f2u(s0):08x}", - f"v_mov_b32 v2, 0x{f2u(s1):08x}", - f"v_madak_f32 v0, v1, v2, 0x{f2u(k):08x}", - "v_mov_b32 v1, 0", - "v_mov_b32 v2, 0", - "v_mov_b32 v3, 0", - ] + EXIT - spv = translate_lines("ps_madak", lines) - res = mrt0_words(spv) - return u2f(res[0]) - - def test_asymmetric_operands(self): - # 2.0 * 4.0 + 3.0 = 11.0 - self.assertEqual(self._run_madak(2.0, 4.0, 3.0), 11.0) - # 3.0 * 5.0 + (-2.0) = 13.0 - self.assertEqual(self._run_madak(3.0, 5.0, -2.0), 13.0) - # -1.5 * 4.0 + 10.0 = 4.0 - self.assertEqual(self._run_madak(-1.5, 4.0, 10.0), 4.0) - - def test_zero_operands(self): - # 0.0 * 100.0 + 7.5 = 7.5 - self.assertEqual(self._run_madak(0.0, 100.0, 7.5), 7.5) - # 100.0 * 0.0 + 7.5 = 7.5 - self.assertEqual(self._run_madak(100.0, 0.0, 7.5), 7.5) - # 2.0 * 3.0 + 0.0 = 6.0 - self.assertEqual(self._run_madak(2.0, 3.0, 0.0), 6.0) - - def test_sgpr_and_inline_constant_source(self): - # S0 from SGPR: s0 * v1 + K - lines_sgpr = [ - f"s_mov_b32 s0, 0x{f2u(3.0):08x}", - f"v_mov_b32 v1, 0x{f2u(4.0):08x}", - f"v_madak_f32 v0, s0, v1, 0x{f2u(5.0):08x}", # 3.0 * 4.0 + 5.0 = 17.0 - "v_mov_b32 v1, 0", - "v_mov_b32 v2, 0", - "v_mov_b32 v3, 0", - ] + EXIT - res_sgpr = u2f(mrt0_words(translate_lines("ps_madak_sgpr", lines_sgpr))[0]) - self.assertEqual(res_sgpr, 17.0) - - # S0 from inline constant 1.0: 1.0 * v1 + K - lines_const = [ - f"v_mov_b32 v1, 0x{f2u(4.0):08x}", - f"v_madak_f32 v0, 1.0, v1, 0x{f2u(3.0):08x}", # 1.0 * 4.0 + 3.0 = 7.0 - "v_mov_b32 v1, 0", - "v_mov_b32 v2, 0", - "v_mov_b32 v3, 0", - ] + EXIT - res_const = u2f(mrt0_words(translate_lines("ps_madak_const", lines_const))[0]) - self.assertEqual(res_const, 7.0) - - def test_spirv_lowering_unfused(self): - lines = [ - "v_mov_b32 v1, 0x40000000", - "v_mov_b32 v2, 0x40800000", - "v_madak_f32 v0, v1, v2, 0x40400000", - ] + EXIT - spv = translate_lines("ps_madak_spv", lines) - # Must emit OpFMul then OpFAdd (not fused Fma) - self.assertIn("OpFMul %float", spv) - self.assertIn("OpFAdd %float", spv) - self.assertNotIn("%glsl Fma", spv) - - -class MadmkF32Tests(unittest.TestCase): - """Semantic tests for v_madmk_f32: D = S0 * K + S1.""" - - def _run_madmk(self, s0: float, k: float, s1: float) -> float: - lines = [ - f"v_mov_b32 v1, 0x{f2u(s0):08x}", - f"v_mov_b32 v2, 0x{f2u(s1):08x}", - f"v_madmk_f32 v0, v1, 0x{f2u(k):08x}, v2", - "v_mov_b32 v1, 0", - "v_mov_b32 v2, 0", - "v_mov_b32 v3, 0", - ] + EXIT - spv = translate_lines("ps_madmk", lines) - res = mrt0_words(spv) - return u2f(res[0]) - - def test_asymmetric_operands_and_factor_order(self): - # 2.0 * 3.0 + 4.0 = 10.0 - # If buggy factor order (multiplying S0 * S1 + K): 2.0 * 4.0 + 3.0 = 11.0 != 10.0 - res = self._run_madmk(2.0, 3.0, 4.0) - self.assertEqual(res, 10.0) - - # 5.0 * 0.5 + 1.5 = 4.0 - self.assertEqual(self._run_madmk(5.0, 0.5, 1.5), 4.0) - - # -4.0 * 2.5 + 15.0 = 5.0 - self.assertEqual(self._run_madmk(-4.0, 2.5, 15.0), 5.0) - - def test_zero_operands(self): - # 0.0 * 3.0 + 4.0 = 4.0 - self.assertEqual(self._run_madmk(0.0, 3.0, 4.0), 4.0) - # 2.0 * 0.0 + 4.0 = 4.0 - self.assertEqual(self._run_madmk(2.0, 0.0, 4.0), 4.0) - # 2.0 * 3.0 + 0.0 = 6.0 - self.assertEqual(self._run_madmk(2.0, 3.0, 0.0), 6.0) - - def test_sgpr_and_inline_constant_source(self): - # S0 from SGPR: s0 * K + v1 - lines_sgpr = [ - f"s_mov_b32 s0, 0x{f2u(3.0):08x}", - f"v_mov_b32 v1, 0x{f2u(4.0):08x}", - f"v_madmk_f32 v0, s0, 0x{f2u(5.0):08x}, v1", # 3.0 * 5.0 + 4.0 = 19.0 - "v_mov_b32 v1, 0", - "v_mov_b32 v2, 0", - "v_mov_b32 v3, 0", - ] + EXIT - res_sgpr = u2f(mrt0_words(translate_lines("ps_madmk_sgpr", lines_sgpr))[0]) - self.assertEqual(res_sgpr, 19.0) - - # S0 from inline constant 1.0: 1.0 * K + v1 - lines_const = [ - f"v_mov_b32 v1, 0x{f2u(4.0):08x}", - f"v_madmk_f32 v0, 1.0, 0x{f2u(3.0):08x}, v1", # 1.0 * 3.0 + 4.0 = 7.0 - "v_mov_b32 v1, 0", - "v_mov_b32 v2, 0", - "v_mov_b32 v3, 0", - ] + EXIT - res_const = u2f(mrt0_words(translate_lines("ps_madmk_const", lines_const))[0]) - self.assertEqual(res_const, 7.0) - - def test_spirv_lowering_unfused(self): - lines = [ - "v_mov_b32 v1, 0x40000000", - "v_mov_b32 v2, 0x40800000", - "v_madmk_f32 v0, v1, 0x40400000, v2", - ] + EXIT - spv = translate_lines("ps_madmk_spv", lines) - self.assertIn("OpFMul %float", spv) - self.assertIn("OpFAdd %float", spv) - self.assertNotIn("%glsl Fma", spv) - - -class ComparativeAndSweepTests(unittest.TestCase): - """Comparative tests and seeded input sweeps.""" - - def test_madak_vs_madmk_equivalence(self): - # When factors and addends match: - # madak(a, b, c) -> a * b + c - # madmk(a, b, c) -> a * b + c - a, b, c = 3.25, 2.5, 7.125 - lines = [ - f"v_mov_b32 v1, 0x{f2u(a):08x}", - f"v_mov_b32 v2, 0x{f2u(b):08x}", - f"v_mov_b32 v3, 0x{f2u(c):08x}", - f"v_madak_f32 v0, v1, v2, 0x{f2u(c):08x}", # a * b + c - f"v_madmk_f32 v1, v1, 0x{f2u(b):08x}, v3", # a * b + c - "v_mov_b32 v2, 0", - "v_mov_b32 v3, 0", - ] + EXIT - spv = translate_lines("ps_equiv", lines) - words = mrt0_words(spv) - res_madak = u2f(words[0]) - res_madmk = u2f(words[1]) - self.assertEqual(res_madak, res_madmk) - self.assertEqual(res_madak, ref_madak_f32(a, b, c)) - - def test_seeded_sweep(self): - rng = random.Random(0x1E041DA) - for _ in range(50): - s0 = rng.uniform(-100.0, 100.0) - s1 = rng.uniform(-100.0, 100.0) - k = rng.uniform(-100.0, 100.0) - - # Round to single precision float - s0 = u2f(f2u(s0)) - s1 = u2f(f2u(s1)) - k = u2f(f2u(k)) - - # Test subrev - expected_subrev = ref_subrev_f32(s0, s1) - lines_subrev = [ - f"v_mov_b32 v1, 0x{f2u(s0):08x}", - f"v_mov_b32 v2, 0x{f2u(s1):08x}", - "v_subrev_f32 v0, v1, v2", - "v_mov_b32 v1, 0", - "v_mov_b32 v2, 0", - "v_mov_b32 v3, 0", - ] + EXIT - actual_subrev = u2f(mrt0_words(translate_lines("ps_sweep_subrev", lines_subrev))[0]) - self.assertEqual(f2u(actual_subrev), f2u(expected_subrev)) - - # Test madak - expected_madak = ref_madak_f32(s0, s1, k) - lines_madak = [ - f"v_mov_b32 v1, 0x{f2u(s0):08x}", - f"v_mov_b32 v2, 0x{f2u(s1):08x}", - f"v_madak_f32 v0, v1, v2, 0x{f2u(k):08x}", - "v_mov_b32 v1, 0", - "v_mov_b32 v2, 0", - "v_mov_b32 v3, 0", - ] + EXIT - actual_madak = u2f(mrt0_words(translate_lines("ps_sweep_madak", lines_madak))[0]) - self.assertEqual(f2u(actual_madak), f2u(expected_madak)) - - # Test madmk - expected_madmk = ref_madmk_f32(s0, k, s1) - lines_madmk = [ - f"v_mov_b32 v1, 0x{f2u(s0):08x}", - f"v_mov_b32 v2, 0x{f2u(s1):08x}", - f"v_madmk_f32 v0, v1, 0x{f2u(k):08x}, v2", - "v_mov_b32 v1, 0", - "v_mov_b32 v2, 0", - "v_mov_b32 v3, 0", - ] + EXIT - actual_madmk = u2f(mrt0_words(translate_lines("ps_sweep_madmk", lines_madmk))[0]) - self.assertEqual(f2u(actual_madmk), f2u(expected_madmk)) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_alu_med3.py b/tests/semantic/test_alu_med3.py deleted file mode 100644 index c5ee4fc54..000000000 --- a/tests/semantic/test_alu_med3.py +++ /dev/null @@ -1,305 +0,0 @@ -"""Semantic interpreter tests for RDNA2 three-operand median instructions: -v_med3_f32, v_med3_i32, and v_med3_u32. - -Each test translates a synthetic pixel shader with tools/rdna2spirv.py, executes it in -tests/semantic/spirv_mini_interp.py, and validates the exported mrt0 word against a plain-Python reference. - -The test matrix covers: -- Signed vs unsigned integer median boundaries (v_med3_i32 vs v_med3_u32): - Values such as 0xFFFFFFFF (-1 as i32, UINT_MAX as u32), 0x80000000 (INT_MIN as i32, - 2^31 as u32), 0x7FFFFFFF (INT_MAX), 0, and ordinary positive/negative integers where signed - and unsigned orderings diverge. -- Floating-point 3-way median (v_med3_f32): - Infinities (-inf, +inf), signed zeros (+0.0, -0.0), positive/negative finite floats, - denormals, and large magnitudes. -- Commutativity / operand order invariance: - The hardware/SPIR-V translation evaluates median using min/max/clamp combinations, e.g. - clamp(z, min(x, y), max(x, y)). Testing all 3! = 6 permutations ensures operand placement - does not alter the median result. -- Inline constants and input modifiers: - Operands supplied directly as inline immediate values (e.g. integer or floating-point constants) - and floating-point input modifiers (negation '-' and absolute value '| |'). -""" -from __future__ import annotations - -import itertools -import math -import os -import struct -import sys -import tempfile -import unittest -import warnings - -HERE = os.path.dirname(os.path.abspath(__file__)) -ROOT = os.path.dirname(os.path.dirname(HERE)) -TOOLS_DIR = os.environ.get("LEONIDA_TOOLS_DIR") or os.path.join(ROOT, "tools") - -sys.dont_write_bytecode = True -sys.path.insert(0, TOOLS_DIR) -sys.path.insert(0, HERE) - -import rdna2spirv # noqa: E402 -import spirv_mini_interp as si # noqa: E402 - -MASK32 = 0xFFFFFFFF -STUB_DXBC = b"DXBC" + bytes(24) + struct.pack(" int: - x &= MASK32 - return x - (1 << 32) if x & 0x80000000 else x - - -def f32_from_bits(b: int) -> float: - return struct.unpack(" int: - try: - return struct.unpack(" 0 else 0xFF800000 - - -def ref_i32(x: int, y: int, z: int) -> int: - return sorted([x, y, z], key=s32)[1] & MASK32 - - -def ref_u32(x: int, y: int, z: int) -> int: - return sorted([x, y, z], key=lambda v: v & MASK32)[1] & MASK32 - - -def ref_f32(x_bits: int, y_bits: int, z_bits: int) -> int: - xf = f32_from_bits(x_bits) - yf = f32_from_bits(y_bits) - zf = f32_from_bits(z_bits) - # The median with -0 ordered below +0, as measured on RDNA2 hardware (AMD Radeon RX 6800, gfx1030): - # med3(-0, +0, 1.0) = +0 and med3(+0, -0, -1.0) = -0, in every operand order (docs/design.md, float - # min/max/med3 with NaN). Python's min/max return their first argument for equal zeros, which is not that. - r = sorted((xf, yf, zf), key=lambda v: (v, math.copysign(1.0, v)))[1] - return bits_from_f32(r) - - -def ref(op: str, x: int, y: int, z: int) -> int: - if op == "v_med3_i32": - return ref_i32(x, y, z) - elif op == "v_med3_u32": - return ref_u32(x, y, z) - elif op == "v_med3_f32": - return ref_f32(x, y, z) - raise ValueError(f"Unknown op {op}") - - -_TMP_DIR = None -_SRC_PATH = None - - -def setUpModule(): - global _TMP_DIR, _SRC_PATH - _TMP_DIR = tempfile.TemporaryDirectory() - disasm_dir = os.path.join(_TMP_DIR.name, "disasm") - os.mkdir(disasm_dir) - _SRC_PATH = os.path.join(disasm_dir, "ps_med3.s") - with open(os.path.join(_TMP_DIR.name, "ps_med3.dxbc"), "wb") as f: - f.write(STUB_DXBC) - - -def tearDownModule(): - global _TMP_DIR - if _TMP_DIR is not None: - _TMP_DIR.cleanup() - _TMP_DIR = None - - -def run( - op: str, - *xs: int | str, - inline: tuple[int, ...] = (), - mods: dict[int, str] | None = None, -) -> int: - """Translate and run `op v0, src0, src1, src2`. - - Operands are passed as 32-bit raw words (or str if inline). Unless listed in `inline`, - operands are loaded into v1..v3 via v_mov_b32. If an index is in `inline`, the value is - written directly into the instruction operand list. - `mods` maps operand index to a modifier format string or prefix (e.g. `0: "-{}"` or `0: "|{}|"`). - """ - if _TMP_DIR is None: - setUpModule() - lines, operands = [], [] - for i, x in enumerate(xs): - mod_fmt = (mods or {}).get(i, "{}") - if i in inline: - val_str = str(x) if isinstance(x, str) else (f"{x:#x}" if (isinstance(x, int) and x >= 0) else str(x)) - operands.append(mod_fmt.format(val_str)) - else: - v_reg = f"v{i + 1}" - raw = x if isinstance(x, int) else int(x, 0) - lines.append(f"\tv_mov_b32 {v_reg}, {raw & MASK32:#x}") - operands.append(mod_fmt.format(v_reg)) - ops_str = ", ".join(operands) - lines.append(f"\t{op} v0, {ops_str}") - asm = "; test_alu_med3\n" + "\n".join(lines) + "\n\texp mrt0 v0, v0, v0, v0 done vm\n\ts_endpgm\n" - with open(_SRC_PATH, "w", encoding="utf-8") as f: - f.write(asm) - with warnings.catch_warnings(): - warnings.simplefilter("ignore", ResourceWarning) - spv = rdna2spirv.translate(_SRC_PATH) - return si.run_fragment(spv)["%out_mrt0"][0] - - -class ReferenceTests(unittest.TestCase): - """Validate plain-Python reference against known hand-calculated results.""" - - def test_reference_integer(self): - self.assertEqual(ref("v_med3_i32", 5, 0x80000000, 7), 5) - self.assertEqual(ref("v_med3_u32", 5, 0x80000000, 7), 7) - - self.assertEqual(ref("v_med3_i32", 0xFFFFFFFF, 0, 1), 0) - self.assertEqual(ref("v_med3_u32", 0xFFFFFFFF, 0, 1), 1) - - self.assertEqual(ref("v_med3_i32", 0x7FFFFFFF, 0x80000000, 0xFFFFFFFF), 0xFFFFFFFF) - self.assertEqual(ref("v_med3_u32", 0x7FFFFFFF, 0x80000000, 0xFFFFFFFF), 0x80000000) - - self.assertEqual(ref("v_med3_i32", 42, 42, 0x80000000), 42) - self.assertEqual(ref("v_med3_u32", 42, 42, 0x80000000), 42) - self.assertEqual(ref("v_med3_i32", 7, 7, 7), 7) - - def test_reference_float(self): - self.assertEqual(ref("v_med3_f32", bits_from_f32(-1.0), bits_from_f32(0.0), bits_from_f32(1.0)), bits_from_f32(0.0)) - self.assertEqual(ref("v_med3_f32", bits_from_f32(-float("inf")), bits_from_f32(2.5), bits_from_f32(float("inf"))), bits_from_f32(2.5)) - self.assertEqual(ref("v_med3_f32", bits_from_f32(100.0), bits_from_f32(-50.0), bits_from_f32(0.0)), bits_from_f32(0.0)) - self.assertEqual(ref("v_med3_f32", bits_from_f32(3.0), bits_from_f32(3.0), bits_from_f32(1.0)), bits_from_f32(3.0)) - self.assertEqual(ref("v_med3_f32", bits_from_f32(1e-30), bits_from_f32(1e30), bits_from_f32(1.0)), bits_from_f32(1.0)) - - -class Med3IntegerTests(unittest.TestCase): - """Semantic interpreter tests for v_med3_i32 and v_med3_u32.""" - - def test_every_order(self): - for op in INT_OPS: - for xs in INT_TRIPLES: - for perm in sorted(set(itertools.permutations(xs))): - with self.subTest(op=op, xs=[hex(v) for v in perm]): - self.assertEqual(run(op, *perm), ref(op, *perm)) - - def test_sweep(self): - values = (0, 1, 0x7FFFFFFF, 0x80000000, 0xFFFFFFFF) - for op in INT_OPS: - for xs in itertools.product(values, repeat=3): - with self.subTest(op=op, xs=[hex(v) for v in xs]): - self.assertEqual(run(op, *xs), ref(op, *xs)) - - def test_inline_constants(self): - cases = [ - ("v_med3_i32", (0x7FFFFFFF, -16, 64), 64), - ("v_med3_u32", (0x7FFFFFFF, -16, 64), 0x7FFFFFFF), - ("v_med3_i32", (0, 1, -1), 0), - ("v_med3_u32", (0, 1, -1), 1), - ("v_med3_i32", (0x80000000, 10, -10), -10 & MASK32), - ("v_med3_u32", (0x80000000, 10, -10), 0x80000000), - ] - for op, xs, want in cases: - raw_xs = tuple(x & MASK32 for x in xs) - with self.subTest(op=op, xs=xs): - self.assertEqual(want, ref(op, *raw_xs)) - self.assertEqual(run(op, *xs, inline=(1, 2)), want) - - -class Med3FloatTests(unittest.TestCase): - """Semantic interpreter tests for v_med3_f32.""" - - def test_every_order(self): - for triple in FLOAT_TRIPLES: - bits = tuple(bits_from_f32(v) for v in triple) - for perm in sorted(set(itertools.permutations(bits))): - with self.subTest(perm=[hex(b) for b in perm]): - self.assertEqual(run("v_med3_f32", *perm), ref("v_med3_f32", *perm)) - - def test_sweep(self): - values = (-float("inf"), -1.0, 0.0, 1.0, float("inf")) - bits_values = tuple(bits_from_f32(v) for v in values) - for perm in itertools.product(bits_values, repeat=3): - with self.subTest(xs=[hex(b) for b in perm]): - self.assertEqual(run("v_med3_f32", *perm), ref("v_med3_f32", *perm)) - - def test_signed_zero(self): - pos_zero = 0x00000000 - neg_zero = 0x80000000 - one = bits_from_f32(1.0) - neg_one = bits_from_f32(-1.0) - - for triple in [ - (pos_zero, neg_zero, one), - (pos_zero, neg_zero, neg_one), - (neg_zero, pos_zero, one), - ]: - for perm in sorted(set(itertools.permutations(triple))): - with self.subTest(perm=[hex(b) for b in perm]): - got = run("v_med3_f32", *perm) - want = ref("v_med3_f32", *perm) - self.assertEqual(got, want) - - def test_inline_constants(self): - cases = [ - ((bits_from_f32(3.0), "1.0", "2.0"), bits_from_f32(2.0)), - ((bits_from_f32(-5.0), "0.0", "5.0"), bits_from_f32(0.0)), - ((bits_from_f32(0.5), "-1.0", "1.0"), bits_from_f32(0.5)), - ] - for xs, want in cases: - with self.subTest(xs=xs): - self.assertEqual(run("v_med3_f32", *xs, inline=(1, 2)), want) - - def test_input_modifiers(self): - r_neg = run( - "v_med3_f32", - bits_from_f32(3.0), - bits_from_f32(1.0), - bits_from_f32(2.0), - mods={0: "-{}"}, - ) - self.assertEqual(r_neg, bits_from_f32(1.0)) - - r_abs = run( - "v_med3_f32", - bits_from_f32(-4.0), - bits_from_f32(1.0), - bits_from_f32(2.0), - mods={0: "|{}|"}, - ) - self.assertEqual(r_abs, bits_from_f32(2.0)) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_alu_min3_max3.py b/tests/semantic/test_alu_min3_max3.py deleted file mode 100644 index ec7bd3ce7..000000000 --- a/tests/semantic/test_alu_min3_max3.py +++ /dev/null @@ -1,495 +0,0 @@ -"""Semantic interpreter tests for RDNA2 3-way ALU min/max instructions: -- v_min3_f32: 3-way IEEE binary32 floating-point minimum -- v_max3_f32: 3-way IEEE binary32 floating-point maximum -- v_min3_i32: 3-way signed 32-bit two's complement integer minimum -- v_max3_u32: 3-way unsigned 32-bit integer maximum -(also covers v_min3_u32 and v_max3_i32 for completeness). - -Each test case translates a synthetic pixel shader listing using tools/rdna2spirv.py, -executes the resulting SPIR-V in tests/semantic/spirv_mini_interp.py, and compares the -exported mrt0 color output words against independent plain-Python reference models. - -Float min/max and IEEE 754 / RDNA2 semantics: -- Lowering to SPIR-V in tools/rdna2spirv.py maps v_min3_f32 and v_max3_f32 to GLSL.std.450 - NMin and NMax (OpExtInst %float %glsl NMin/NMax). -- NMin and NMax implement IEEE 754-2008 minNum / maxNum NaN skipping: if any operand is NaN, - the non-NaN operand is chosen; if all operands are NaN, NaN is returned. -- Signed zeros are ordered with -0.0 below +0.0 (the hardware order measured on AMD RDNA2, - docs/design.md): min(+0.0, -0.0) = -0.0 and max(+0.0, -0.0) = +0.0 in either operand order. -- VOP3 input modifiers: absolute value (|src|), negation (-src), and neg-abs (-|src|). -- VOP3 output modifier: clamp to [0.0, 1.0]. If all operands are NaN, clamp raises - UnsupportedConstruct because GLSL.std.450 FClamp on NaN is undefined. - -Integer min/max: -- v_min3_i32 and v_max3_i32 evaluate operands as signed 32-bit integers in two's complement. -- v_min3_u32 and v_max3_u32 evaluate operands as unsigned 32-bit integers. -- Boundary conditions where signed and unsigned order disagree: 0x80000000 is INT_MIN as i32 - but 2^31 as u32; 0xFFFFFFFF is -1 as i32 but UINT32_MAX as u32. - -Zero game data, standard library Python only, Python 3.9+ compatible. -""" -from __future__ import annotations - -import itertools -import math -import os -import struct -import sys -import tempfile -import unittest -import warnings - -HERE = os.path.dirname(os.path.abspath(__file__)) -ROOT = os.path.dirname(os.path.dirname(HERE)) -TOOLS_DIR = os.environ.get("LEONIDA_TOOLS_DIR") or os.path.join(ROOT, "tools") - -sys.dont_write_bytecode = True -if TOOLS_DIR not in sys.path: - sys.path.insert(0, TOOLS_DIR) -if HERE not in sys.path: - sys.path.insert(0, HERE) - -import rdna2spirv # noqa: E402 -import spirv_mini_interp as si # noqa: E402 - -MASK32 = 0xFFFFFFFF -STUB_DXBC = b"DXBC" + bytes(24) + struct.pack(" int: - x &= MASK32 - return x - (1 << 32) if x & 0x80000000 else x - - -def u32(x: int) -> int: - return x & MASK32 - - -def u32_to_f32(u: int) -> float: - return struct.unpack(" int: - try: - return struct.unpack(" 0 else NEG_INF_BITS - - -def ref_nmin_nmax(name: str, x: float, y: float) -> float: - """Reference GLSL.std.450 NMin / NMax: NaN operand gives the other operand; both NaN give NaN. - Zeros are ordered -0.0 < +0.0 (measured RDNA2 hardware semantics).""" - if math.isnan(x): - return y if not math.isnan(y) else math.nan - if math.isnan(y): - return x - kx, ky = (x, math.copysign(1.0, x)), (y, math.copysign(1.0, y)) - if name == "NMin": - return y if ky < kx else x - return y if ky > kx else x - - -def ref_int(op: str, *xs: int) -> int: - key = s32 if op.endswith("_i32") else u32 - pick = min if "min3" in op else max - return pick(xs, key=key) & MASK32 - - -def ref_float(op: str, a: float, b: float, c: float, *, clamp: bool = False) -> float: - fn = "NMin" if "min3" in op else "NMax" - r = ref_nmin_nmax(fn, ref_nmin_nmax(fn, a, b), c) - if clamp: - if math.isnan(r): - raise si.UnsupportedConstruct("clamp on NaN is undefined") - r = max(0.0, min(1.0, r)) - return r - - -_TMP_DIR: tempfile.TemporaryDirectory[str] | None = None -_SRC_PATH: str = "" - - -def setUpModule() -> None: - global _TMP_DIR, _SRC_PATH - _TMP_DIR = tempfile.TemporaryDirectory() - disasm_dir = os.path.join(_TMP_DIR.name, "disasm") - os.mkdir(disasm_dir) - _SRC_PATH = os.path.join(disasm_dir, "ps_min3_max3.s") - with open(os.path.join(_TMP_DIR.name, "ps_min3_max3.dxbc"), "wb") as f: - f.write(STUB_DXBC) - - -def tearDownModule() -> None: - global _TMP_DIR - if _TMP_DIR is not None: - _TMP_DIR.cleanup() - _TMP_DIR = None - - -def run_alu(op: str, *xs: int, inline: tuple[int, ...] = (), clamp: bool = False) -> int: - """Translate and run `op v0, a, b, c` where operands xs are raw 32-bit words.""" - if _TMP_DIR is None: - setUpModule() - lines, operands = [], [] - for i, x in enumerate(xs): - if i in inline: - operands.append(f"{x & MASK32:#x}") - else: - lines.append(f"v_mov_b32 v{i + 1}, {x & MASK32:#x}") - operands.append(f"v{i + 1}") - clamp_str = " clamp" if clamp else "" - lines.append(f"{op} v0, {', '.join(operands)}{clamp_str}") - lines.append("exp mrt0 v0, v0, v0, v0 done vm") - lines.append("s_endpgm") - asm = "; test_alu_min3_max3\n" + "".join(f"\t{ln}\n" for ln in lines) - with open(_SRC_PATH, "w", encoding="utf-8") as f: - f.write(asm) - with warnings.catch_warnings(): - warnings.simplefilter("ignore", ResourceWarning) - spv = rdna2spirv.translate(_SRC_PATH) - return si.run_fragment(spv)["%out_mrt0"][0] - - -def run_composite(asm_lines: list[str]) -> tuple[int, ...]: - """Run arbitrary fragment shader lines ending with mrt0 export and s_endpgm.""" - if _TMP_DIR is None: - setUpModule() - asm = "; test_alu_composite\n" + "".join(f"\t{ln}\n" for ln in asm_lines) - with open(_SRC_PATH, "w", encoding="utf-8") as f: - f.write(asm) - with warnings.catch_warnings(): - warnings.simplefilter("ignore", ResourceWarning) - spv = rdna2spirv.translate(_SRC_PATH) - return si.run_fragment(spv)["%out_mrt0"] - - -class ReferenceTests(unittest.TestCase): - """Plain-Python reference tests against hand-worked and IEEE 754 edge cases.""" - - def test_integer_reference(self) -> None: - self.assertEqual(ref_int("v_min3_i32", 5, 0x80000000, 7), 0x80000000) - self.assertEqual(ref_int("v_min3_u32", 5, 0x80000000, 7), 5) - self.assertEqual(ref_int("v_max3_i32", 5, 0x80000000, 7), 7) - self.assertEqual(ref_int("v_max3_u32", 5, 0x80000000, 7), 0x80000000) - self.assertEqual(ref_int("v_min3_i32", 0xFFFFFFFF, 0, 1), 0xFFFFFFFF) - self.assertEqual(ref_int("v_max3_u32", 0xFFFFFFFF, 0, 1), 0xFFFFFFFF) - self.assertEqual(ref_int("v_max3_i32", 0xFFFFFFFF, 0, 1), 1) - self.assertEqual(ref_int("v_min3_u32", 0xFFFFFFFF, 0, 1), 0) - - def test_ieee754_float_reference(self) -> None: - # Normal ordered values - self.assertEqual(ref_float("v_min3_f32", 1.0, 2.0, 3.0), 1.0) - self.assertEqual(ref_float("v_max3_f32", 1.0, 2.0, 3.0), 3.0) - self.assertEqual(ref_float("v_min3_f32", -10.0, 0.0, 10.0), -10.0) - self.assertEqual(ref_float("v_max3_f32", -10.0, 0.0, 10.0), 10.0) - - # IEEE 754 minNum / maxNum: non-NaN numbers are chosen over NaN - nan = float("nan") - self.assertEqual(ref_float("v_min3_f32", nan, 2.0, 3.0), 2.0) - self.assertEqual(ref_float("v_min3_f32", 1.0, nan, 3.0), 1.0) - self.assertEqual(ref_float("v_min3_f32", 1.0, 2.0, nan), 1.0) - self.assertEqual(ref_float("v_max3_f32", nan, 2.0, 3.0), 3.0) - self.assertEqual(ref_float("v_max3_f32", 1.0, nan, 3.0), 3.0) - self.assertEqual(ref_float("v_max3_f32", 1.0, 2.0, nan), 2.0) - - # Two NaNs: remaining non-NaN is chosen - self.assertEqual(ref_float("v_min3_f32", nan, nan, 4.0), 4.0) - self.assertEqual(ref_float("v_min3_f32", nan, -5.0, nan), -5.0) - self.assertEqual(ref_float("v_max3_f32", nan, nan, 4.0), 4.0) - self.assertEqual(ref_float("v_max3_f32", nan, -5.0, nan), -5.0) - - # Three NaNs: result must be NaN - self.assertTrue(math.isnan(ref_float("v_min3_f32", nan, nan, nan))) - self.assertTrue(math.isnan(ref_float("v_max3_f32", nan, nan, nan))) - - # Signed zero handling (-0.0 < +0.0) - self.assertEqual(f32_to_u32(ref_float("v_min3_f32", 0.0, -0.0, 1.0)), NEG_ZERO_BITS) - self.assertEqual(f32_to_u32(ref_float("v_max3_f32", 0.0, -0.0, -1.0)), POS_ZERO_BITS) - - # Infinities - inf = float("inf") - self.assertEqual(ref_float("v_min3_f32", -inf, 0.0, inf), -inf) - self.assertEqual(ref_float("v_max3_f32", -inf, 0.0, inf), inf) - - -class FloatMin3Max3Tests(unittest.TestCase): - """v_min3_f32 and v_max3_f32 tests across scales, permutations, clamping, and inline constants.""" - - def test_float_every_order(self) -> None: - for op in FLOAT_OPS: - for fs in FLOAT_TRIPLES: - for perm in sorted(set(itertools.permutations(fs))): - with self.subTest(op=op, fs=perm): - words = [f32_to_u32(f) for f in perm] - want = f32_to_u32(ref_float(op, *perm)) - self.assertEqual(run_alu(op, *words), want) - - def test_float_signed_zeros(self) -> None: - # RDNA2 orders -0.0 below +0.0: - # min3(+0, -0, 1.0) = -0.0 - # max3(+0, -0, -1.0) = +0.0 - zeros_triples_min = [ - (POS_ZERO_BITS, NEG_ZERO_BITS, f32_to_u32(1.0)), - (NEG_ZERO_BITS, POS_ZERO_BITS, f32_to_u32(1.0)), - (f32_to_u32(1.0), POS_ZERO_BITS, NEG_ZERO_BITS), - ] - for xs in zeros_triples_min: - with self.subTest(case="signed_zeros_min3", xs=[hex(x) for x in xs]): - self.assertEqual(run_alu("v_min3_f32", *xs), NEG_ZERO_BITS) - - zeros_triples_max = [ - (POS_ZERO_BITS, NEG_ZERO_BITS, f32_to_u32(-1.0)), - (NEG_ZERO_BITS, POS_ZERO_BITS, f32_to_u32(-1.0)), - (f32_to_u32(-1.0), POS_ZERO_BITS, NEG_ZERO_BITS), - ] - for xs in zeros_triples_max: - with self.subTest(case="signed_zeros_max3", xs=[hex(x) for x in xs]): - self.assertEqual(run_alu("v_max3_f32", *xs), POS_ZERO_BITS) - - def test_float_subnormals(self) -> None: - # Subnormals handled under IEEE gradual ordering - words = [SUBNORM_MIN_BITS, SUBNORM_MAX_BITS, f32_to_u32(1.0)] - self.assertEqual(run_alu("v_min3_f32", *words), SUBNORM_MIN_BITS) - self.assertEqual(run_alu("v_max3_f32", *words), f32_to_u32(1.0)) - - def test_float_clamping(self) -> None: - cases = [ - ("v_min3_f32", (2.5, 3.5, 4.5), 1.0), - ("v_min3_f32", (-0.5, 0.5, 0.8), 0.0), - ("v_min3_f32", (0.25, 0.75, 0.5), 0.25), - ("v_max3_f32", (-2.5, -1.0, -0.5), 0.0), - ("v_max3_f32", (0.2, 1.5, 0.8), 1.0), - ("v_max3_f32", (0.2, 0.7, 0.5), 0.7), - ] - for op, fs, want in cases: - with self.subTest(op=op, fs=fs): - words = [f32_to_u32(f) for f in fs] - got = run_alu(op, *words, clamp=True) - want_bits = f32_to_u32(want) - self.assertEqual(got, want_bits) - self.assertEqual(want_bits, f32_to_u32(ref_float(op, *fs, clamp=True))) - - def test_float_inline_constants(self) -> None: - cases = [ - ("v_min3_f32", (1.5, -2.5, 3.5), (1, 2)), - ("v_max3_f32", (1.5, -2.5, 3.5), (0, 2)), - ("v_min3_f32", (0.2, 0.4, 0.8), (0, 1)), - ("v_max3_f32", (-10.0, 0.0, 10.0), (1, 2)), - ] - for op, fs, inline in cases: - with self.subTest(op=op, fs=fs, inline=inline): - words = [f32_to_u32(f) for f in fs] - want = f32_to_u32(ref_float(op, *fs)) - got = run_alu(op, *words, inline=inline) - self.assertEqual(got, want) - - -class FloatNanSkippingTests(unittest.TestCase): - """GLSL.std.450 NMin and NMax implement IEEE 754-2008 NaN-skipping: - - If one or two operands are NaN, the non-NaN operand is chosen. - - If all three operands are NaN, NaN is returned. - - If clamp modifier is specified on all-NaN, UnsupportedConstruct is raised because - FClamp on NaN is undefined. - """ - - def test_single_nan_operand_skipped(self) -> None: - nans = [QNAN_BITS, SNAN_BITS, NEG_QNAN_BITS] - a_f, b_f = 1.0, 2.0 - a_bits, b_bits = f32_to_u32(a_f), f32_to_u32(b_f) - for op in FLOAT_OPS: - expected_f = 1.0 if "min3" in op else 2.0 - expected_bits = f32_to_u32(expected_f) - for nan_bits in nans: - triples = [ - (nan_bits, a_bits, b_bits), - (a_bits, nan_bits, b_bits), - (a_bits, b_bits, nan_bits), - ] - for xs in triples: - with self.subTest(op=op, nan=hex(nan_bits), xs=[hex(x) for x in xs]): - self.assertEqual(run_alu(op, *xs), expected_bits) - - def test_two_nan_operands_skipped(self) -> None: - c_f = 5.0 - c_bits = f32_to_u32(c_f) - for op in FLOAT_OPS: - triples = [ - (QNAN_BITS, SNAN_BITS, c_bits), - (QNAN_BITS, c_bits, NEG_QNAN_BITS), - (c_bits, QNAN_BITS, SNAN_BITS), - ] - for xs in triples: - with self.subTest(op=op, xs=[hex(x) for x in xs]): - self.assertEqual(run_alu(op, *xs), c_bits) - - def test_all_three_nans_produce_nan(self) -> None: - for op in FLOAT_OPS: - with self.subTest(op=op): - res = run_alu(op, QNAN_BITS, SNAN_BITS, NEG_QNAN_BITS) - self.assertTrue(math.isnan(u32_to_f32(res))) - - def test_clamp_on_all_nan_rejected(self) -> None: - for op in FLOAT_OPS: - with self.subTest(op=op): - with self.assertRaises(si.UnsupportedConstruct): - run_alu(op, QNAN_BITS, SNAN_BITS, NEG_QNAN_BITS, clamp=True) - - -class FloatModifiersTests(unittest.TestCase): - """VOP3 input modifiers: abs (|src|), neg (-src), and neg-abs (-|src|).""" - - def test_abs_and_neg_input_modifiers(self) -> None: - lines = [ - "v_mov_b32 v1, 2.5", - "v_mov_b32 v2, -3.5", - "v_mov_b32 v3, 4.0", - "v_min3_f32 v0, -v1, |v2|, v3", - "exp mrt0 v0, v0, v0, v0 done vm", - "s_endpgm", - ] - out = run_composite(lines) - # -v1 is -2.5, |v2| is 3.5, v3 is 4.0. min is -2.5. - self.assertEqual(out[0], f32_to_u32(-2.5)) - - def test_max3_with_neg_abs_modifiers(self) -> None: - lines = [ - "v_mov_b32 v1, 2.5", - "v_mov_b32 v2, -3.5", - "v_mov_b32 v3, -1.0", - "v_max3_f32 v0, -v1, |v2|, -|v3|", - "exp mrt0 v0, v0, v0, v0 done vm", - "s_endpgm", - ] - out = run_composite(lines) - # -v1 is -2.5, |v2| is 3.5, -|v3| is -1.0. max is 3.5. - self.assertEqual(out[0], f32_to_u32(3.5)) - - -class IntegerMin3Max3Tests(unittest.TestCase): - """v_min3_i32 and v_max3_u32 (plus v_min3_u32 and v_max3_i32) order, sweep, and inline constants.""" - - def test_every_order(self) -> None: - for op in INT_OPS: - for xs in INT_TRIPLES: - for perm in sorted(set(itertools.permutations(xs))): - with self.subTest(op=op, xs=[hex(v) for v in perm]): - self.assertEqual(run_alu(op, *perm), ref_int(op, *perm)) - - def test_sweep(self) -> None: - values = (0, 1, 0x7FFFFFFF, 0x80000000, 0xFFFFFFFF) - for op in INT_OPS: - for xs in itertools.product(values, repeat=3): - with self.subTest(op=op, xs=[hex(v) for v in xs]): - self.assertEqual(run_alu(op, *xs), ref_int(op, *xs)) - - def test_inline_constants(self) -> None: - cases = [ - ("v_min3_i32", (0x7FFFFFFF, 0xFFFFFFF0, 64), 0xFFFFFFF0), - ("v_min3_u32", (0x7FFFFFFF, 0xFFFFFFF0, 64), 64), - ("v_max3_i32", (0x80000000, 0xFFFFFFF0, 64), 64), - ("v_max3_u32", (0x80000000, 0xFFFFFFF0, 64), 0xFFFFFFF0), - ] - for op, xs, want in cases: - with self.subTest(op=op): - self.assertEqual(want, ref_int(op, *xs)) - self.assertEqual(run_alu(op, *xs, inline=(1, 2)), want) - - -class CompositeMrt0ShaderTests(unittest.TestCase): - """Combined pixel shader exporting v_min3_f32, v_max3_f32, v_min3_i32, and v_max3_u32 to mrt0.""" - - def test_composite_shader_all_four_ops(self) -> None: - lines = [ - "v_mov_b32 v4, 1.5", - "v_mov_b32 v5, -2.5", - "v_mov_b32 v6, 3.5", - "v_min3_f32 v0, v4, v5, v6", - "v_max3_f32 v1, v4, v5, v6", - "v_mov_b32 v7, 10", - "v_mov_b32 v8, 0xfffffff0", - "v_mov_b32 v9, 5", - "v_min3_i32 v2, v7, v8, v9", - "v_max3_u32 v3, v7, v8, v9", - "exp mrt0 v0, v1, v2, v3 done vm", - "s_endpgm", - ] - out = run_composite(lines) - self.assertEqual(len(out), 4) - - want_min_f = f32_to_u32(ref_float("v_min3_f32", 1.5, -2.5, 3.5)) - want_max_f = f32_to_u32(ref_float("v_max3_f32", 1.5, -2.5, 3.5)) - want_min_i = ref_int("v_min3_i32", 10, 0xFFFFFFF0, 5) - want_max_u = ref_int("v_max3_u32", 10, 0xFFFFFFF0, 5) - - self.assertEqual(out[0], want_min_f, "mrt0.x must match v_min3_f32") - self.assertEqual(out[1], want_max_f, "mrt0.y must match v_max3_f32") - self.assertEqual(out[2], want_min_i, "mrt0.z must match v_min3_i32") - self.assertEqual(out[3], want_max_u, "mrt0.w must match v_max3_u32") - - -class NegativeSensitivityTests(unittest.TestCase): - """Negative controls ensuring min/max or signed/unsigned confusions fail assertions.""" - - def test_signed_vs_unsigned_sabotage_is_caught(self) -> None: - s0, s1, s2 = 10, 0xFFFFFFF0, 5 - self.assertNotEqual(ref_int("v_min3_i32", s0, s1, s2), ref_int("v_min3_u32", s0, s1, s2)) - self.assertNotEqual(ref_int("v_max3_i32", s0, s1, s2), ref_int("v_max3_u32", s0, s1, s2)) - - def test_min_vs_max_sabotage_is_caught(self) -> None: - f0, f1, f2 = 1.0, 2.0, 3.0 - self.assertNotEqual(ref_float("v_min3_f32", f0, f1, f2), ref_float("v_max3_f32", f0, f1, f2)) - i0, i1, i2 = 10, 20, 30 - self.assertNotEqual(ref_int("v_min3_i32", i0, i1, i2), ref_int("v_max3_i32", i0, i1, i2)) - - def test_signed_zero_sabotage_is_caught(self) -> None: - # If signed zeros are incorrectly considered identical (+0.0 == -0.0 in Python comparison) - # without ordering key, min(+0.0, -0.0) would return +0.0 instead of -0.0 when +0 is first. - bad_min = min(0.0, -0.0) - self.assertEqual(f32_to_u32(bad_min), POS_ZERO_BITS) - self.assertEqual(f32_to_u32(ref_nmin_nmax("NMin", 0.0, -0.0)), NEG_ZERO_BITS) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_alu_min3_max3_med3_16.py b/tests/semantic/test_alu_min3_max3_med3_16.py deleted file mode 100644 index 265bd4ff6..000000000 --- a/tests/semantic/test_alu_min3_max3_med3_16.py +++ /dev/null @@ -1,622 +0,0 @@ -"""Semantic interpreter tests for RDNA2 16-bit three-operand min/max/median instructions: -v_min3_i16, v_min3_u16, v_max3_i16, v_max3_u16, v_med3_i16, v_med3_u16, -v_min3_f16, and v_max3_f16. - -Each test translates a synthetic pixel shader listing with tools/rdna2spirv.py, executes it in -tests/semantic/spirv_mini_interp.py, and compares the exported mrt0 words against plain-Python references. - -Covers: -- A multi-instruction hand-written .asm fixture exercising all eight opcodes into low and high VGPR halves. -- Signed vs unsigned 16-bit integer comparisons across boundary values (0x8000, 0xFFFF, 0x7FFF, 0x0000, 0x0001) - in all 3! = 6 operand permutations. -- All 16 op_sel:[s0,s1,s2,dst] bit combinations for every opcode. -- Unwritten destination-half preservation and destination/source register aliasing. -- Inline integer/float constants and SGPR operands. -- Floating-point 16-bit NaN skipping (NMin/NMax), signed-zero ordering (-0.0 < +0.0), neg/abs source modifiers, - and VOP3 output modifiers (mul:2, mul:4, div:2, clamp). -- Unsupported rejections for clamp on integer min3/max3/med3 and non-VGPR op_sel destination. -- Seeded random sweep over all eight opcodes. -""" -from __future__ import annotations - -import itertools -import math -import os -import random -import struct -import sys -import tempfile -import unittest -import warnings - -HERE = os.path.dirname(os.path.abspath(__file__)) -ROOT = os.path.dirname(os.path.dirname(HERE)) -TOOLS_DIR = os.environ.get("LEONIDA_TOOLS_DIR") or os.path.join(ROOT, "tools") - -sys.dont_write_bytecode = True -sys.path.insert(0, TOOLS_DIR) -sys.path.insert(0, HERE) - -import rdna2spirv # noqa: E402 -import spirv_mini_interp as si # noqa: E402 - -MASK16 = 0xFFFF -MASK32 = 0xFFFFFFFF -STUB_DXBC = b"DXBC" + bytes(24) + struct.pack(" lo = 0x7FFF (+32767 i16 / 32767 u16), hi = 0x8000 (-32768 i16 / 32768 u16) -# v11 = 0xFFFF0001 -> lo = 0x0001 (+1), hi = 0xFFFF (-1 i16 / 65535 u16) -# v12 = 0x0005FFFE -> lo = 0xFFFE (-2 i16 / 65534 u16), hi = 0x0005 (+5) -# v13 = 0x3C00BC00 -> lo = 0xBC00 (-1.0 f16), hi = 0x3C00 (+1.0 f16) -# v14 = 0x80000000 -> lo = 0x0000 (+0.0 f16), hi = 0x8000 (-0.0 f16) -# v15 = 0x7E004000 -> lo = 0x4000 (+2.0 f16), hi = 0x7E00 (qNaN f16) -# Expected mrt0 words: -# v0: v_min3_i16(32767, -1, -2) = -2 (0xFFFE) | v_max3_i16(-32768, 1, 5) = 5 (0x0005) -> 0x0005FFFE -# v1: v_med3_i16(32767, -1, 5) = 5 (0x0005) | v_min3_u16(32768, 65535, 65534) = 0x8000 -> 0x80000005 -# v2: v_max3_u16(32767, 65535, 65534) = 0xFFFF | v_med3_u16(32768, 1, 65534) = 0x8000 -> 0x8000FFFF -# v3: v_min3_f16(+1.0, -0.0, qNaN) = -0.0 (0x8000) | v_max3_f16(-1.0, +0.0, +2.0) = 0x4000 -> 0x40008000 -PS_MIN3_MAX3_MED3_16_ASM = """\ -; test_alu_min3_max3_med3_16 fixture -\tv_mov_b32 v0, 0xdeadbef0 -\tv_mov_b32 v1, 0xdeadbef1 -\tv_mov_b32 v2, 0xdeadbef2 -\tv_mov_b32 v3, 0xdeadbef3 -\tv_mov_b32 v10, 0x80007fff -\tv_mov_b32 v11, 0xffff0001 -\tv_mov_b32 v12, 0x0005fffe -\tv_mov_b32 v13, 0x3c00bc00 -\tv_mov_b32 v14, 0x80000000 -\tv_mov_b32 v15, 0x7e004000 -\tv_min3_i16 v0, v10, v11, v12 op_sel:[0,1,0,0] -\tv_max3_i16 v0, v10, v11, v12 op_sel:[1,0,1,1] -\tv_med3_i16 v1, v10, v11, v12 op_sel:[0,1,1,0] -\tv_min3_u16 v1, v10, v11, v12 op_sel:[1,1,0,1] -\tv_max3_u16 v2, v10, v11, v12 op_sel:[0,1,0,0] -\tv_med3_u16 v2, v10, v11, v12 op_sel:[1,0,0,1] -\tv_min3_f16 v3, v13, v14, v15 op_sel:[1,1,1,0] -\tv_max3_f16 v3, v13, v14, v15 op_sel:[0,0,0,1] -\texp mrt0 v0, v1, v2, v3 done vm -\ts_endpgm -""" -PS_MIN3_MAX3_MED3_16_EXPECTED = (0x0005FFFE, 0x80000005, 0x8000FFFF, 0x40008000) - -INT_TRIPLES = ( - (0x0005, 0x8000, 0x0007), - (0xFFFF, 0x0000, 0x0001), - (0x7FFF, 0x8000, 0xFFFF), - (0x8001, 0x8000, 0x7FFE), - (0x0001, 0xFFFE, 0xFFFF), - (0x0009, 0x0009, 0x8000), - (0xFFFF, 0xFFFF, 0x0000), - (0x0003, 0x0003, 0x0003), -) - -# f16 bit patterns: -inf, -2.0, -1.0, -0.5, smallest neg subnormal, -0.0, +0.0, subnormal, +0.5, +1.0, +2.0, +inf -F16_VALS = ( - 0xFC00, # -inf - 0xC000, # -2.0 - 0xBC00, # -1.0 - 0xB800, # -0.5 - 0x8001, # -2^-24 (negative subnormal) - 0x8000, # -0.0 - 0x0000, # +0.0 - 0x0001, # +2^-24 (positive subnormal) - 0x3800, # +0.5 - 0x3C00, # +1.0 - 0x4000, # +2.0 - 0x7C00, # +inf -) - - -def s16(h: int) -> int: - h &= MASK16 - return h - 0x10000 if h & 0x8000 else h - - -def f16_to_float(h: int) -> float: - return struct.unpack(" int: - try: - return struct.unpack(" 0 else 0xFC00 - - -def half_bits(word: int, hi: int) -> int: - return ((word >> 16) if hi else word) & MASK16 - - -def merge_half(res16: int, dst_hi: int, old: int = OLD) -> int: - res16 &= MASK16 - return ((res16 << 16) | (old & MASK16)) if dst_hi else ((old & 0xFFFF0000) | res16) - - -def ref_int16(op: str, a: int, b: int, c: int) -> int: - key = s16 if op.endswith("_i16") else (lambda v: v & MASK16) - xs = [a & MASK16, b & MASK16, c & MASK16] - if "min3" in op: - return min(xs, key=key) & MASK16 - if "max3" in op: - return max(xs, key=key) & MASK16 - if "med3" in op: - return sorted(xs, key=key)[1] & MASK16 - raise ValueError(op) - - -def ref_f16(op: str, a_bits: int, b_bits: int, c_bits: int, mods: str = "") -> int: - vals = [f16_to_float(h) for h in (a_bits, b_bits, c_bits)] - non_nan = [v for v in vals if not math.isnan(v)] - if not non_nan: - return 0x7E00 - if "med3" in op: - if len(non_nan) < 3: - # With any NaN operand, RDNA2 hardware returns min3(x, y, z) - chosen = min(non_nan, key=lambda v: (v, math.copysign(1.0, v))) - else: - chosen = sorted(non_nan, key=lambda v: (v, math.copysign(1.0, v)))[1] - elif "min3" in op: - chosen = min(non_nan, key=lambda v: (v, math.copysign(1.0, v))) - elif "max3" in op: - chosen = max(non_nan, key=lambda v: (v, math.copysign(1.0, v))) - else: - raise ValueError(op) - if "mul:2" in mods: - chosen *= 2.0 - elif "mul:4" in mods: - chosen *= 4.0 - elif "div:2" in mods: - chosen *= 0.5 - if "clamp" in mods: - if math.isnan(chosen): - chosen = 0.0 - else: - chosen = max(0.0, min(1.0, chosen)) - if chosen == 0.0: - chosen = 0.0 - return float_to_f16_bits(chosen) - - -def ref_word(op: str, w1: int, w2: int, w3: int, sel=(0, 0, 0), dst_hi: int = 0, old: int = OLD, mods: str = "") -> int: - h1, h2, h3 = half_bits(w1, sel[0]), half_bits(w2, sel[1]), half_bits(w3, sel[2]) - r16 = ref_f16(op, h1, h2, h3, mods=mods) if op in FLOAT_OPS else ref_int16(op, h1, h2, h3) - return merge_half(r16, dst_hi, old=old) - - -_TMP_DIR = None -_SRC_PATH = None - - -def setUpModule(): - global _TMP_DIR, _SRC_PATH - _TMP_DIR = tempfile.TemporaryDirectory() - disasm_dir = os.path.join(_TMP_DIR.name, "disasm") - os.mkdir(disasm_dir) - _SRC_PATH = os.path.join(disasm_dir, "ps_min3_16.s") - with open(os.path.join(_TMP_DIR.name, "ps_min3_16.dxbc"), "wb") as f: - f.write(STUB_DXBC) - - -def tearDownModule(): - global _TMP_DIR - if _TMP_DIR is not None: - _TMP_DIR.cleanup() - _TMP_DIR = None - - -def translate_asm(asm: str) -> str: - if _TMP_DIR is None: - setUpModule() - with open(_SRC_PATH, "w", encoding="utf-8") as f: - f.write(asm) - with warnings.catch_warnings(): - warnings.simplefilter("ignore", ResourceWarning) - return rdna2spirv.translate(_SRC_PATH) - - -def run_insn( - op: str, - operands_words: tuple[int | str, int | str, int | str], - *, - inline: tuple[int, ...] = (), - sgpr_idx: tuple[int, ...] = (), - src_mods: dict[int, str] | None = None, - tail_mods: str = "", - old: int = OLD, - dst: str = "v0", - alias_dst: int | None = None, -) -> int: - lines = [f"\tv_mov_b32 v0, {old & MASK32:#x}"] - op_strs = [] - sgpr_vals: dict[int, int] = {} - for i, val in enumerate(operands_words): - fmt = (src_mods or {}).get(i, "{}") - if i in inline: - val_str = str(val) if isinstance(val, str) else (f"{val:#x}" if isinstance(val, int) and val >= 0 else str(val)) - op_strs.append(fmt.format(val_str)) - elif i in sgpr_idx: - reg = 4 + i - sgpr_vals[reg] = int(val) & MASK32 - lines.append(f"\ts_mov_b32 s{reg}, {sgpr_vals[reg]:#x}") - op_strs.append(fmt.format(f"s{reg}")) - elif alias_dst == i: - lines[0] = f"\tv_mov_b32 v0, {int(val) & MASK32:#x}" - op_strs.append(fmt.format("v0")) - else: - vreg = f"v{i + 1}" - lines.append(f"\tv_mov_b32 {vreg}, {int(val) & MASK32:#x}") - op_strs.append(fmt.format(vreg)) - mod_suffix = f" {tail_mods}" if tail_mods else "" - lines.append(f"\t{op} {dst}, {', '.join(op_strs)}{mod_suffix}") - asm = "; test_alu_min3_max3_med3_16\n" + "\n".join(lines) + "\n\texp mrt0 v0, v0, v0, v0 done vm\n\ts_endpgm\n" - spv = translate_asm(asm) - return si.run_fragment(spv)["%out_mrt0"][0] - - -class ReferenceTests(unittest.TestCase): - """Cross-check plain-Python reference calculations against hand-worked edge cases.""" - - def test_int_reference(self): - self.assertEqual(ref_int16("v_min3_i16", 0x7FFF, 0xFFFF, 0xFFFE), 0xFFFE) - self.assertEqual(ref_int16("v_min3_u16", 0x7FFF, 0xFFFF, 0xFFFE), 0x7FFF) - self.assertEqual(ref_int16("v_max3_i16", 0x8000, 0x0001, 0x0005), 0x0005) - self.assertEqual(ref_int16("v_max3_u16", 0x8000, 0x0001, 0x0005), 0x8000) - self.assertEqual(ref_int16("v_med3_i16", 0x7FFF, 0xFFFF, 0x0005), 0x0005) - self.assertEqual(ref_int16("v_med3_u16", 0x8000, 0x0001, 0xFFFE), 0x8000) - - def test_f16_reference(self): - self.assertEqual(ref_f16("v_min3_f16", 0x3C00, 0x8000, 0x7E00), 0x8000) - self.assertEqual(ref_f16("v_max3_f16", 0xBC00, 0x0000, 0x8000), 0x0000) - self.assertEqual(ref_f16("v_min3_f16", 0x0000, 0x8000, 0x3C00), 0x8000) - self.assertEqual(ref_f16("v_med3_f16", 0x3C00, 0x8000, 0xBC00), 0x8000) - self.assertEqual(ref_f16("v_med3_f16", 0x3C00, 0x7E00, 0xBC00), 0xBC00) - self.assertEqual(ref_f16("v_med3_f16", 0x3C00, 0x7E00, 0xBC00, mods="clamp"), 0x0000) - - -class FixtureTests(unittest.TestCase): - """Hand-written multi-instruction RDNA2 .asm fixture for all 8 instructions.""" - - def test_ps_min3_max3_med3_16_fixture(self): - spv = translate_asm(PS_MIN3_MAX3_MED3_16_ASM) - got = si.run_fragment(spv)["%out_mrt0"] - self.assertEqual(got, PS_MIN3_MAX3_MED3_16_EXPECTED) - - -class Int16PermutationsTests(unittest.TestCase): - """Verify signed vs unsigned ordering across all 3! = 6 operand permutations.""" - - def test_boundary_permutations(self): - for op in INT_OPS: - for triple in INT_TRIPLES: - for perm in sorted(set(itertools.permutations(triple))): - w1, w2, w3 = (0xBEEF0000 | x for x in perm) - with self.subTest(op=op, perm=[hex(x) for x in perm]): - self.assertEqual(run_insn(op, (w1, w2, w3)), ref_word(op, w1, w2, w3)) - - -class OpselAllPatternsTests(unittest.TestCase): - """Test all 16 op_sel:[s0,s1,s2,dst] bit combinations for every opcode.""" - - def test_all_sixteen_opsel_patterns_int(self): - # Distinct lo/hi values in every register, mixing signed-negative and unsigned-high patterns. - w1, w2, w3 = 0x80007FFF, 0xFFFF0001, 0x0005FFFE - for op in INT_OPS: - for bits in itertools.product((0, 1), repeat=4): - mods = f"op_sel:[{bits[0]},{bits[1]},{bits[2]},{bits[3]}]" - with self.subTest(op=op, mods=mods): - got = run_insn(op, (w1, w2, w3), tail_mods=mods) - want = ref_word(op, w1, w2, w3, bits[:3], bits[3]) - self.assertEqual(got, want) - - def test_all_sixteen_opsel_patterns_f16(self): - # v1 = (-1.0 | 4.0), v2 = (0.5 | 2.0), v3 = (1.5 | -3.0) - w1 = float_to_f16_bits(4.0) << 16 | float_to_f16_bits(-1.0) - w2 = float_to_f16_bits(2.0) << 16 | float_to_f16_bits(0.5) - w3 = float_to_f16_bits(-3.0) << 16 | float_to_f16_bits(1.5) - for op in FLOAT_OPS: - for bits in itertools.product((0, 1), repeat=4): - mods = f"op_sel:[{bits[0]},{bits[1]},{bits[2]},{bits[3]}]" - with self.subTest(op=op, mods=mods): - got = run_insn(op, (w1, w2, w3), tail_mods=mods) - want = ref_word(op, w1, w2, w3, bits[:3], bits[3]) - self.assertEqual(got, want) - - -class HalfPreservationAndAliasingTests(unittest.TestCase): - """Unwritten half of dst is preserved, including when dst aliases src0, src1, or src2.""" - - def test_preserves_unwritten_half(self): - for op in ALL_OPS: - w1, w2, w3 = 0x3C003800, 0x4000B800, 0xBC000001 - for dst_hi in (0, 1): - for sentinel in (0x12345678, 0xFEDCBA98): - with self.subTest(op=op, dst_hi=dst_hi, sentinel=hex(sentinel)): - got = run_insn(op, (w1, w2, w3), tail_mods=f"op_sel:[0,0,0,{dst_hi}]", old=sentinel) - self.assertEqual(got, ref_word(op, w1, w2, w3, (0, 0, 0), dst_hi, old=sentinel)) - - def test_dst_source_aliasing(self): - for op in ALL_OPS: - w = [0x80003C00, 0x4000FFFF, 0x38000002] - for alias_idx in (0, 1, 2): - for dst_hi in (0, 1): - mods = f"op_sel:[1,0,1,{dst_hi}]" - with self.subTest(op=op, alias_idx=alias_idx, dst_hi=dst_hi): - got = run_insn( - op, - (w[0], w[1], w[2]), - tail_mods=mods, - alias_dst=alias_idx, - ) - want = ref_word(op, w[0], w[1], w[2], (1, 0, 1), dst_hi, old=w[alias_idx]) - self.assertEqual(got, want) - - -class ConstantsAndSgprTests(unittest.TestCase): - """Inline constants (imm / fimm) and SGPR sources.""" - - def test_int_inline_constants_and_sgpr(self): - # -16 inline is 0xFFFFFFF0 (lo = 0xFFF0 = -16 i16 / 65520 u16, hi = 0xFFFF = -1 i16 / 65535 u16). - cases = [ - ("v_min3_i16", (-16, 64, 0x00030005), (0, 1), (), "op_sel:[0,0,0,0]"), - ("v_min3_u16", (-16, 64, 0x00030005), (0, 1), (), "op_sel:[0,0,0,1]"), - ("v_max3_i16", (-1, 0x80000002, 10), (0, 2), (1,), "op_sel:[0,1,0,0]"), - ("v_max3_u16", (-16, 0x00010002, 0x80000003), (0,), (1,), "op_sel:[1,0,1,1]"), - ("v_med3_i16", (0x7FFF8000, -1, 16), (1, 2), (0,), "op_sel:[0,0,0,0]"), - ("v_med3_u16", (0x7FFF8000, -16, 64), (1, 2), (0,), "op_sel:[1,0,0,1]"), - ] - for op, words, inl, sgprs, mods in cases: - with self.subTest(op=op, words=words, mods=mods): - sel_parts = [int(x) for x in mods.split("[")[1].rstrip("]").split(",")] - norm_words = [ - (w & MASK32) if isinstance(w, int) else w - for w in words - ] - got = run_insn(op, words, inline=inl, sgpr_idx=sgprs, tail_mods=mods) - want = ref_word(op, norm_words[0], norm_words[1], norm_words[2], sel_parts[:3], sel_parts[3]) - self.assertEqual(got, want) - - def test_f16_fimm_constants_and_sgpr(self): - # Inline float constants populate the low half as f16 with high half = +0.0 (docs/design.md). - # 1.0 -> 0x00003C00; -2.0 -> 0x0000C000; 0.5 -> 0x00003800 - got_min = run_insn( - "v_min3_f16", - ("1.0", 0x40003C00, "-2.0"), - inline=(0, 2), - sgpr_idx=(1,), - tail_mods="op_sel:[0,1,0,0]", - ) - self.assertEqual(got_min, merge_half(0xC000, 0)) - - # Selecting the high half of an inline float constant reads +0.0. - got_hi_fimm = run_insn( - "v_max3_f16", - ("1.0", 0xBC00BC00, "-0.5"), - inline=(0, 2), - tail_mods="op_sel:[1,0,0,1]", - ) - self.assertEqual(got_hi_fimm, merge_half(0x0000, 1)) - - -class Float16SpecialsAndModsTests(unittest.TestCase): - """f16 NaNs, signed zeros (-0.0 < +0.0), neg/abs, omod, and clamp.""" - - def test_signed_zeros_all_orders(self): - # -0.0 (0x8000) orders strictly below +0.0 (0x0000) regardless of operand position. - for triple in ( - (0x8000, 0x0000, 0x3C00), # -0, +0, +1 -> min=-0, max=+1 - (0x8000, 0x0000, 0xBC00), # -0, +0, -1 -> min=-1, max=+0 - (0x8000, 0x0000, 0x0000), # -0, +0, +0 -> min=-0, max=+0 - (0x8000, 0x8000, 0x0000), # -0, -0, +0 -> min=-0, max=+0 - ): - for perm in sorted(set(itertools.permutations(triple))): - for op in FLOAT_OPS: - with self.subTest(op=op, perm=[hex(x) for x in perm]): - got = run_insn(op, perm) - self.assertEqual(got, ref_word(op, *perm)) - - def test_nan_operands(self): - for op in FLOAT_OPS: - # One quiet or signaling NaN: returns min/max of the remaining finite values. - for nan_bits in (0x7E00, 0x7C01, 0xFE01): - for perm in sorted(set(itertools.permutations((nan_bits, 0x4000, 0xBC00)))): - with self.subTest(op=op, perm=[hex(x) for x in perm]): - got = run_insn(op, perm) - self.assertEqual(got, ref_word(op, *perm)) - # Two NaNs: returns the single non-NaN operand. - for perm in sorted(set(itertools.permutations((0x7E00, 0xFE01, 0x3800)))): - with self.subTest(op=op, two_nans=[hex(x) for x in perm]): - got = run_insn(op, perm) - self.assertEqual(got, ref_word(op, *perm)) - # Three NaNs: result is NaN and unwritten high half is preserved. - got_all_nan = run_insn(op, (0x7E00, 0x7E01, 0xFE01)) - self.assertEqual(got_all_nan >> 16, OLD >> 16) - self.assertTrue(math.isnan(f16_to_float(got_all_nan & MASK16))) - - def test_source_and_output_modifiers(self): - # Input neg/abs apply to the selected half; on RDNA2 omod is ignored for f16 with denorms kept; clamp applies [0, 1]. - w1 = float_to_f16_bits(-3.0) << 16 | float_to_f16_bits(0.5) - w2 = float_to_f16_bits(0.25) << 16 | float_to_f16_bits(-2.0) - w3 = float_to_f16_bits(-0.125) << 16 | float_to_f16_bits(4.0) - - # neg(|v1.hi|) = -3.0, |v2.lo| = +2.0, v3.hi = -0.125 -> min = -3.0 (div:2 ignored on RDNA2) - got_div2 = run_insn( - "v_min3_f16", - (w1, w2, w3), - src_mods={0: "-|{}|", 1: "|{}|"}, - tail_mods="op_sel:[1,0,1,0] div:2", - ) - self.assertEqual(got_div2, merge_half(float_to_f16_bits(-3.0), 0)) - - # min(|v1.lo|=0.5, v2.hi=0.25, -v3.hi=0.125) = 0.125 (mul:4 ignored on RDNA2, clamp keeps 0.125) (hi half) - got_mul4_clamp = run_insn( - "v_min3_f16", - (w1, w2, w3), - src_mods={0: "|{}|", 2: "-{}"}, - tail_mods="op_sel:[0,1,1,1] mul:4 clamp", - ) - self.assertEqual(got_mul4_clamp, merge_half(float_to_f16_bits(0.125), 1)) - - # max(v1.lo=0.5, v2.hi=0.25, v3.lo=4.0) = 4.0 -> div:2 ignored on RDNA2 -> clamp = 1.0 - got_max_clamp = run_insn( - "v_max3_f16", - (w1, w2, w3), - tail_mods="op_sel:[0,1,0,0] div:2 clamp", - ) - self.assertEqual(got_max_clamp, merge_half(float_to_f16_bits(1.0), 0)) - - # max(v1.hi=-3.0, v2.lo=-2.0, v3.hi=-0.125) = -0.125 -> mul:2 = -0.25 -> clamp = +0.0 - got_neg_clamp = run_insn( - "v_max3_f16", - (w1, w2, w3), - tail_mods="op_sel:[1,0,1,1] mul:2 clamp", - ) - self.assertEqual(got_neg_clamp, merge_half(0x0000, 1)) - - -class ClampSupportTests(unittest.TestCase): - """Verify that integer and float min3/max3/med3 accept VOP3 clamp.""" - - def test_int_clamp_supported(self): - for op in INT_OPS: - with self.subTest(op=op): - w1, w2, w3 = (0x0005, 0x0010, 0xFFFF) - got_noclamp = run_insn(op, (w1, w2, w3)) - got_clamp = run_insn(op, (w1, w2, w3), tail_mods="clamp") - self.assertEqual(got_noclamp, got_clamp) - got_dhi_clamp = run_insn(op, (w1, w2, w3), tail_mods="op_sel:[0,0,0,1] clamp") - self.assertEqual(got_dhi_clamp, merge_half(got_clamp & MASK16, 1)) - - def test_int_clamp_dirty_sentinels(self): - # Verify clamp range-invariance and destination half preservation with dirty sentinel values. - for op in INT_OPS: - with self.subTest(op=op): - w1, w2, w3 = (0xDEAD0005, 0xBEEF0010, 0x5A5AFFFF) - # Low half destination preserves 0xDEAD in high half - got_lo = run_insn(op, (w1, w2, w3), tail_mods="clamp", old=0xDEAD3800) - ref_lo = ref_word(op, w1, w2, w3, (0, 0, 0), dst_hi=0, old=0xDEAD3800) - self.assertEqual(got_lo, ref_lo) - self.assertEqual(got_lo >> 16, 0xDEAD) - - # High half destination preserves 0x3800 in low half - got_hi = run_insn(op, (w1, w2, w3), tail_mods="op_sel:[0,0,0,1] clamp", old=0xDEAD3800) - ref_hi = ref_word(op, w1, w2, w3, (0, 0, 0), dst_hi=1, old=0xDEAD3800) - self.assertEqual(got_hi, ref_hi) - self.assertEqual(got_hi & MASK16, 0x3800) - - def test_f16_clamp_all_ops(self): - # In-range [0.0, 1.0], upper saturation (> 1.0 -> 1.0), lower saturation (< 0.0 -> +0.0) - # across all three f16 opcodes. - for op in FLOAT_OPS: - with self.subTest(op=op): - # in-range: 0.25, 0.5, 0.75 - w_mid = (float_to_f16_bits(0.25), float_to_f16_bits(0.5), float_to_f16_bits(0.75)) - got_mid = run_insn(op, w_mid, tail_mods="clamp") - self.assertEqual(got_mid, ref_word(op, *w_mid, mods="clamp")) - - # upper saturation: 1.5, 2.0, 3.0 - w_hi = (float_to_f16_bits(1.5), float_to_f16_bits(2.0), float_to_f16_bits(3.0)) - got_hi = run_insn(op, w_hi, tail_mods="clamp") - self.assertEqual(got_hi, ref_word(op, *w_hi, mods="clamp")) - self.assertEqual(got_hi & MASK16, float_to_f16_bits(1.0)) - - # lower saturation: -2.0, -1.0, -0.5 - w_lo = (float_to_f16_bits(-2.0), float_to_f16_bits(-1.0), float_to_f16_bits(-0.5)) - got_lo = run_insn(op, w_lo, tail_mods="clamp") - self.assertEqual(got_lo, ref_word(op, *w_lo, mods="clamp")) - self.assertEqual(got_lo & MASK16, 0x0000) - - # negative zero clamps to +0.0 - w_neg_zero = (0x8000, 0x8000, 0x8000) - got_nz = run_insn(op, w_neg_zero, tail_mods="clamp") - self.assertEqual(got_nz & MASK16, 0x0000) - - def test_f16_clamp_nan_and_sentinels(self): - # NaN operands with DX10 clamp and dirty sentinel destination halves - w_nan = (0x7E00, float_to_f16_bits(2.0), float_to_f16_bits(-1.0)) - # v_min3_f16: min(2.0, -1.0) = -1.0 -> clamp = +0.0 - got_min = run_insn("v_min3_f16", w_nan, tail_mods="clamp", old=0xDEAD3800) - self.assertEqual(got_min, 0xDEAD0000) - - # v_max3_f16: max(2.0, -1.0) = 2.0 -> clamp = 1.0 (0x3C00) - got_max = run_insn("v_max3_f16", w_nan, tail_mods="clamp", old=0xDEAD3800) - self.assertEqual(got_max, 0xDEAD3C00) - - # v_med3_f16: NaN fallback to min3 = -1.0 -> clamp = +0.0 - got_med = run_insn("v_med3_f16", w_nan, tail_mods="clamp", old=0xDEAD3800) - self.assertEqual(got_med, 0xDEAD0000) - - # High half write with op_sel:[1,1,1,1] clamp leaves 0xBEEF in low half - w1_packed = float_to_f16_bits(0.5) << 16 | 0x7E00 - w2_packed = float_to_f16_bits(-2.0) << 16 | 0x4000 - w3_packed = float_to_f16_bits(0.5) << 16 | 0xBC00 - # median of high halves (0.5, -2.0, 0.5) is 0.5, clamped to 0.5 (0x3800) - got_med_hi = run_insn( - "v_med3_f16", - (w1_packed, w2_packed, w3_packed), - tail_mods="op_sel:[1,1,1,1] clamp", - old=0x1234BEEF, - ) - self.assertEqual(got_med_hi, (float_to_f16_bits(0.5) << 16) | 0xBEEF) - -class UnsupportedTests(unittest.TestCase): - """Reject non-VGPR op_sel destinations.""" - - def test_non_vgpr_opsel_dst_rejected(self): - for op in ALL_OPS: - with self.subTest(op=op): - asm = ( - "; test_unsupported_dst\n" - "\tv_mov_b32 v1, 1\n\tv_mov_b32 v2, 2\n\tv_mov_b32 v3, 3\n" - f"\t{op} s0, v1, v2, v3 op_sel:[0,0,0,1]\n" - "\texp mrt0 v1, v1, v1, v1 done vm\n\ts_endpgm\n" - ) - with self.assertRaises(rdna2spirv.Unsupported): - translate_asm(asm) - - -class RandomSweepTests(unittest.TestCase): - """Seeded random sweep over all eight opcodes, halves, and destination halves.""" - - def test_seeded_sweep(self): - rng = random.Random(0x1633) - int_pool = [0, 1, 0x7FFE, 0x7FFF, 0x8000, 0x8001, 0xFFFE, 0xFFFF] - for op in INT_OPS: - for _ in range(18): - w1, w2, w3 = ( - ((rng.choice(int_pool) if rng.random() < 0.4 else rng.randrange(0x10000)) << 16) - | (rng.choice(int_pool) if rng.random() < 0.4 else rng.randrange(0x10000)) - for _ in range(3) - ) - sel = tuple(rng.randrange(2) for _ in range(3)) - dst_hi = rng.randrange(2) - mods = f"op_sel:[{sel[0]},{sel[1]},{sel[2]},{dst_hi}]" - with self.subTest(op=op, w=(hex(w1), hex(w2), hex(w3)), mods=mods): - self.assertEqual(run_insn(op, (w1, w2, w3), tail_mods=mods), ref_word(op, w1, w2, w3, sel, dst_hi)) - - for op in FLOAT_OPS: - for _ in range(18): - w1, w2, w3 = ((rng.choice(F16_VALS) << 16) | rng.choice(F16_VALS) for _ in range(3)) - sel = tuple(rng.randrange(2) for _ in range(3)) - dst_hi = rng.randrange(2) - mods = f"op_sel:[{sel[0]},{sel[1]},{sel[2]},{dst_hi}]" - with self.subTest(op=op, w=(hex(w1), hex(w2), hex(w3)), mods=mods): - self.assertEqual(run_insn(op, (w1, w2, w3), tail_mods=mods), ref_word(op, w1, w2, w3, sel, dst_hi)) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_alu_min3_max3_med3_16_hw.py b/tests/semantic/test_alu_min3_max3_med3_16_hw.py deleted file mode 100644 index c7b55cc62..000000000 --- a/tests/semantic/test_alu_min3_max3_med3_16_hw.py +++ /dev/null @@ -1,631 +0,0 @@ -"""v_min3/v_max3/v_med3 on f16, i16 and u16 against words an RDNA2 GPU returned for the same instruction (no model in this test). - -Every row was run natively on an AMD Radeon RDNA2 iGPU (gfx1036, Ryzen 9 9950X3D, Windows AMD driver -32.0.21045.16010) through tools/hw_oracle with AMD clang 23 (rocm-sdk-core 10.0.0), in the MODE inferred for the game -(IEEE 0, DX10_CLAMP 1, f32 denormals flushed, f16 denormals kept): v1..v3 hold the operands, v4 starts as 0xDEADBEEF and -the word after the instruction is the expected one. The rows are a sample of the 6,092 measured cases (every triple of -10 f16 values, among them +-0, a denormal, +-inf, a quiet and a signalling NaN, and of 8 i16/u16 values; each source's -high half is 0xabcd; op_sel on each source and the destination), all of which the translator matches except one case -docs/design.md lists as not modelled: with every operand NaN the hardware returns src0's NaN bits (a signalling NaN -unchanged), the translator a quiet NaN. v_med3_f16 rows with a NaN operand are left out here: the translation computes -an FClamp it then discards for them, and the interpreter refuses to evaluate that FClamp. -""" -import os -import struct -import sys -import tempfile -import unittest -import warnings - -HERE = os.path.dirname(os.path.abspath(__file__)) -ROOT = os.path.dirname(os.path.dirname(HERE)) -sys.dont_write_bytecode = True -sys.path.insert(0, os.environ.get("LEONIDA_TOOLS_DIR") or os.path.join(ROOT, "tools")) -sys.path.insert(0, HERE) - -import rdna2spirv # noqa: E402 -import spirv_mini_interp as si # noqa: E402 - -STUB_DXBC = b"DXBC" + bytes(24) + struct.pack(" int: - """The value v_mov_b32 loads into v before the movrel instruction.""" - return 0xC0DE0000 | ((i * 0x111) & 0xFFFF) - - -SENTINELS: dict[int, int] = {i: sentinel(i) for i in range(1, 9)} -V0_VALUE = 0x5EED0000 # Loaded into v0 by cases that write or seed v0 - - -def compute_movrels_target_vgpr(base_vgpr: int, m0_offset: int, count: int = NUM_VGPRS) -> int | None: - """Return the effective index if it falls within the model's VGPR array.""" - index = (base_vgpr + m0_offset) & MASK32 - return index if index < count else None - - -def ref_movrels_b32(dst: int, src: int, m0: int, vgpr_file: Sequence[int]) -> list[int]: - """Return a copy of the file after a relative source read.""" - out = list(vgpr_file) - target_idx = compute_movrels_target_vgpr(src, m0, len(out)) - out[dst] = out[target_idx if target_idx is not None else 0] & MASK32 - return out - - -class MovrelOracle: - """Stateful architectural register file oracle for M0-relative instructions.""" - - def __init__(self, initial_values: dict[int, int] | None = None) -> None: - self.vgpr = [0] * NUM_VGPRS - self.m0 = 0 - if initial_values: - for reg, val in initial_values.items(): - self.vgpr[reg % NUM_VGPRS] = val & MASK32 - - def set_m0(self, val: int) -> None: - self.m0 = val & MASK32 - - def set_vgpr(self, reg: int, val: int) -> None: - self.vgpr[reg % NUM_VGPRS] = val & MASK32 - - def get_vgpr(self, reg: int) -> int: - return self.vgpr[reg % NUM_VGPRS] - - def execute_v_movrels(self, dst: int, src: int) -> int: - src_idx = compute_movrels_target_vgpr(src, self.m0) - val = self.vgpr[src_idx if src_idx is not None else 0] - self.vgpr[dst] = val - return val - - def execute_v_movreld(self, dst: int, src: int) -> int: - dst_idx = compute_movrels_target_vgpr(dst, self.m0) - val = self.vgpr[src] - if dst_idx is not None: - self.vgpr[dst_idx] = val - return val - - def execute_v_movrelsd(self, dst: int, src: int) -> int: - src_idx = compute_movrels_target_vgpr(src, self.m0) - dst_idx = compute_movrels_target_vgpr(dst, self.m0) - val = self.vgpr[src_idx if src_idx is not None else 0] - if dst_idx is not None: - self.vgpr[dst_idx] = val - return val - - def dump_registers(self, regs: Sequence[int]) -> tuple[int, ...]: - return tuple(self.vgpr[r % NUM_VGPRS] for r in regs) - - -def model(op: str, dst: int, src: int, m0: int, init: dict[int, int]) -> list[int]: - """Plain-Python register file model applying `op dst, src` with M0 = m0.""" - oracle = MovrelOracle(init) - oracle.set_m0(m0) - if op == "v_movrels_b32": - oracle.execute_v_movrels(dst, src) - elif op == "v_movreld_b32": - oracle.execute_v_movreld(dst, src) - elif op == "v_movrelsd_b32": - oracle.execute_v_movrelsd(dst, src) - else: - raise ValueError(op) - return oracle.vgpr - - -S = SENTINELS -# (op, dst, src, m0, load v0?, exported registers, expected words) -- expected words worked out by hand. -CASES = [ - # movrels: D = VGPR[S0 + M0] - ("v_movrels_b32", 0, 1, 0, False, (0, 1, 2, 3), (S[1], S[1], S[2], S[3])), # M0 = 0 reads S0 itself - ("v_movrels_b32", 0, 2, 3, False, (0, 2, 4, 5), (S[5], S[2], S[4], S[5])), # v2 + 3 = v5 - ("v_movrels_b32", 0, 1, 7, False, (0, 1, 7, 8), (S[8], S[1], S[7], S[8])), # v1 + 7 = v8 - ("v_movrels_b32", 9, 0, 4, True, (9, 0, 4, 5), (S[4], V0_VALUE, S[4], S[5])), # base v0, M0 alone indexes - # movreld: VGPR[D + M0] = S0; neighbours keep their sentinels - ("v_movreld_b32", 1, 0, 0, True, (0, 1, 2, 3), (V0_VALUE, V0_VALUE, S[2], S[3])), - ("v_movreld_b32", 3, 0, 2, True, (3, 4, 5, 6), (S[3], S[4], V0_VALUE, S[6])), # writes v5, not v3 - ("v_movreld_b32", 1, 8, 6, False, (1, 6, 7, 8), (S[1], S[6], S[8], S[8])), # v1 + 6 = v7 <- v8 - # movrelsd: VGPR[D + M0] = VGPR[S0 + M0]; M0 offsets both sides - ("v_movrelsd_b32", 2, 1, 0, False, (1, 2, 3, 4), (S[1], S[1], S[3], S[4])), - ("v_movrelsd_b32", 6, 1, 2, False, (6, 7, 8, 3), (S[6], S[7], S[3], S[3])), # v8 <- v3 - ("v_movrelsd_b32", 1, 3, 4, False, (1, 3, 5, 7), (S[1], S[3], S[7], S[7])), # v5 <- v7 -] - -_TMP: tempfile.TemporaryDirectory | None = None - - -def setUpModule() -> None: - global _TMP - _TMP = tempfile.TemporaryDirectory() - os.mkdir(os.path.join(_TMP.name, "disasm")) - with open(os.path.join(_TMP.name, "ps_movrel.dxbc"), "wb") as f: - f.write(STUB_DXBC) - - -def tearDownModule() -> None: - global _TMP - if _TMP is not None: - gc.collect() - _TMP.cleanup() - _TMP = None - - -def translate_listing(body: Sequence[str]) -> str: - """Write `body` (instruction lines) as ps_movrel.s, translate it and return the SPIR-V text.""" - assert _TMP is not None, "setUpModule was not executed" - lines = ["; test_movrel"] + [f"\t{line}" for line in body] + ["\ts_endpgm", ""] - path = os.path.join(_TMP.name, "disasm", "ps_movrel.s") - with open(path, "w", encoding="utf-8", newline="") as f: - f.write("\n".join(lines)) - with warnings.catch_warnings(): - warnings.simplefilter("ignore", ResourceWarning) - spv = rdna2spirv.translate(path) - gc.collect() - return spv - - -def initial_regs(load_v0: bool) -> dict[int, int]: - regs = dict(SENTINELS) - if load_v0: - regs[0] = V0_VALUE - return regs - - -def run_case( - op: str, - dst: int, - src: int, - m0: int, - load_v0: bool, - exported: Sequence[int], -) -> tuple[int, ...]: - body = [f"v_mov_b32 v{r}, {v:#x}" for r, v in sorted(initial_regs(load_v0).items())] - body.append(f"s_mov_b32 m0, {m0}") - body.append(f"{op} v{dst}, v{src}") - body.append("exp mrt0 " + ", ".join(f"v{r}" for r in exported) + " done vm") - return tuple(mrt0_words(translate_listing(body))) - - -def case_id(case: tuple) -> str: - op, dst, src, m0 = case[:4] - return f"{op} v{dst}, v{src} (m0={m0})" - - -class TestMovrelsReferenceOracle(unittest.TestCase): - """Rigorous mathematical tests for the v_movrels_b32 reference oracle.""" - - def test_oracle_zero_offset(self) -> None: - """When M0 = 0, dynamic indexing evaluates directly to the source register.""" - for reg_idx in range(NUM_VGPRS): - target = compute_movrels_target_vgpr(reg_idx, 0) - self.assertEqual(target, reg_idx) - - oracle = MovrelOracle({10: 0x12345678, 20: 0x87654321}) - oracle.set_m0(0) - val = oracle.execute_v_movrels(dst=5, src=10) - self.assertEqual(val, 0x12345678) - self.assertEqual(oracle.get_vgpr(5), 0x12345678) - self.assertEqual(oracle.get_vgpr(10), 0x12345678) - - def test_oracle_positive_displacement(self) -> None: - """An in-range relative address selects the requested register.""" - oracle = MovrelOracle() - oracle.set_vgpr(15, 0xCAFEBABE) - oracle.set_m0(5) - # Reading from base v10 with M0=5 resolves to v15 - val = oracle.execute_v_movrels(dst=0, src=10) - self.assertEqual(val, 0xCAFEBABE) - self.assertEqual(oracle.get_vgpr(0), 0xCAFEBABE) - - def test_oracle_out_of_range_reads_vgpr0(self) -> None: - oracle = MovrelOracle({0: 0x12345678, 4: 0xDEADBEEF}) - oracle.set_m0(10) - self.assertIsNone(compute_movrels_target_vgpr(250, 10)) - self.assertEqual(oracle.execute_v_movrels(dst=1, src=250), 0x12345678) - - def test_oracle_large_m0_values(self) -> None: - for base, offset in ((10, 256), (5, 519), (0, 1024), (1, 0x10000), (10, 0x10000003)): - with self.subTest(base=base, offset=offset): - self.assertIsNone(compute_movrels_target_vgpr(base, offset)) - - def test_oracle_preserves_other_vgprs(self) -> None: - """Only the destination register is written; all other registers remain unchanged.""" - oracle = MovrelOracle({r: sentinel(r) for r in range(1, 9)}) - oracle.set_m0(3) - # S0 = v2, M0 = 3 -> reads v5 (sentinel 5), writes to v0 - oracle.execute_v_movrels(dst=0, src=2) - self.assertEqual(oracle.get_vgpr(0), SENTINELS[5]) - for r in range(1, 9): - self.assertEqual(oracle.get_vgpr(r), SENTINELS[r]) - - def test_oracle_self_move(self) -> None: - """When destination matches effective source index, the value is preserved.""" - oracle = MovrelOracle({5: 0x55555555}) - oracle.set_m0(3) - # dst = 5, src = 2 + 3 = 5 - val = oracle.execute_v_movrels(dst=5, src=2) - self.assertEqual(val, 0x55555555) - self.assertEqual(oracle.get_vgpr(5), 0x55555555) - - def test_oracle_overwrite_source(self) -> None: - """When destination matches base source register but M0 > 0, base register is overwritten.""" - oracle = MovrelOracle({2: 0x22222222, 5: 0x55555555}) - oracle.set_m0(3) - # dst = 2, src = 2 + 3 = 5 -> v2 becomes 0x55555555 - oracle.execute_v_movrels(dst=2, src=2) - self.assertEqual(oracle.get_vgpr(2), 0x55555555) - self.assertEqual(oracle.get_vgpr(5), 0x55555555) - - def test_oracle_sequential_chain(self) -> None: - """Sequential relative moves correctly update and carry forward register state.""" - oracle = MovrelOracle() - oracle.set_vgpr(10, 0xAAAAAAAA) - oracle.set_vgpr(20, 0xBBBBBBBB) - oracle.set_vgpr(30, 0xCCCCCCCC) - - oracle.set_m0(10) - oracle.execute_v_movrels(dst=0, src=0) # v0 <- v10 - oracle.execute_v_movrels(dst=1, src=10) # v1 <- v20 - - oracle.set_m0(20) - oracle.execute_v_movrels(dst=2, src=10) # v2 <- v30 - - self.assertEqual(oracle.dump_registers((0, 1, 2)), (0xAAAAAAAA, 0xBBBBBBBB, 0xCCCCCCCC)) - - def test_pure_function_parity(self) -> None: - """Parity between stateful MovrelOracle and pure-function ref_movrels_b32.""" - regs = [sentinel(i % 16) for i in range(NUM_VGPRS)] - oracle = MovrelOracle({i: regs[i] for i in range(NUM_VGPRS)}) - oracle.set_m0(7) - oracle.execute_v_movrels(dst=50, src=20) - - updated_pure = ref_movrels_b32(dst=50, src=20, m0=7, vgpr_file=regs) - self.assertEqual(oracle.vgpr, updated_pure) - - -class TestM0IndexedDynamicAddressing(unittest.TestCase): - """Dynamic addressing tests verifying M0-based VGPR file access in translated shaders.""" - - def test_dynamic_addressing_matrix(self) -> None: - """Test matrix of base VGPRs and M0 offsets against the reference oracle.""" - test_matrix = [ - (0, 1, 0), # v0 <- VGPR[v1 + 0] = v1 - (1, 2, 3), # v1 <- VGPR[v2 + 3] = v5 - (2, 4, 6), # v2 <- VGPR[v4 + 6] = v10 - (3, 0, 7), # v3 <- VGPR[v0 + 7] = v7 - (0, 5, 10), # v0 <- VGPR[v5 + 10] = v15 - (1, 10, 20), # v1 <- VGPR[v10 + 20] = v30 - ] - for dst, base_src, m0 in test_matrix: - target_reg = base_src + m0 - val = (0x77000000 | (target_reg * 0x10101)) & MASK32 - base_val = 0x11111111 - - lines = [ - f"v_mov_b32 v{base_src}, {base_val:#x}", - f"v_mov_b32 v{target_reg}, {val:#x}", - f"s_mov_b32 m0, {m0}", - f"v_movrels_b32 v{dst}, v{base_src}", - f"exp mrt0 v{dst}, v{base_src}, v{target_reg}, v{dst} done vm", - ] - spv = translate_listing(lines) - words = mrt0_words(spv) - - oracle = MovrelOracle() - oracle.set_vgpr(base_src, base_val) - oracle.set_vgpr(target_reg, val) - oracle.set_m0(m0) - oracle.execute_v_movrels(dst, base_src) - expected = ( - oracle.get_vgpr(dst), - oracle.get_vgpr(base_src), - oracle.get_vgpr(target_reg), - oracle.get_vgpr(dst), - ) - self.assertEqual( - tuple(words), - expected, - f"Failed for dst=v{dst}, src=v{base_src}, m0={m0}: got {words}, expected {expected}", - ) - - def test_computed_m0_salu_indexing(self) -> None: - """Dynamic M0 values computed at runtime via scalar ALU correctly index VGPRs.""" - # M0 computed via addition: s0 (10) + s1 (5) = 15 - asm_add = [ - "v_mov_b32 v20, 0xCAFE0001", - "s_mov_b32 s0, 10", - "s_mov_b32 s1, 5", - "s_add_u32 m0, s0, s1", - "v_movrels_b32 v0, v5", # v5 + 15 = v20 - "exp mrt0 v0, v0, v0, v0 done vm", - ] - words = mrt0_words(translate_listing(asm_add)) - self.assertEqual(words, [0xCAFE0001] * 4) - - # M0 computed via shift: s0 (3) << 2 = 12 - asm_shift = [ - "v_mov_b32 v16, 0xCAFE0002", - "s_mov_b32 s0, 3", - "s_lshl_b32 m0, s0, 2", - "v_movrels_b32 v0, v4", # v4 + 12 = v16 - "exp mrt0 v0, v0, v0, v0 done vm", - ] - words = mrt0_words(translate_listing(asm_shift)) - self.assertEqual(words, [0xCAFE0002] * 4) - - def test_dynamic_lookup_table_simulation(self) -> None: - """Simulate an 8-entry register lookup table indexed via M0.""" - table_values = [0x1000 + i * 0x111 for i in range(8)] - body = [] - for i, val in enumerate(table_values): - body.append(f"v_mov_b32 v{10 + i}, {val:#x}") - - # Query index 3 and index 6 - body.extend([ - "s_mov_b32 m0, 3", - "v_movrels_b32 v0, v10", # v10 + 3 = v13 - "s_mov_b32 m0, 6", - "v_movrels_b32 v1, v10", # v10 + 6 = v16 - "exp mrt0 v0, v1, v0, v1 done vm", - ]) - words = mrt0_words(translate_listing(body)) - expected = (table_values[3], table_values[6], table_values[3], table_values[6]) - self.assertEqual(tuple(words), expected) - - def test_chained_dynamic_moves(self) -> None: - """Multiple sequential v_movrels_b32 instructions with modified M0 values in one shader.""" - lines = [ - "v_mov_b32 v10, 0x11111111", - "v_mov_b32 v20, 0x22222222", - "v_mov_b32 v30, 0x33333333", - "s_mov_b32 m0, 10", - "v_movrels_b32 v0, v0", # reads v10 - "s_mov_b32 m0, 15", - "v_movrels_b32 v1, v5", # reads v20 - "s_mov_b32 m0, 28", - "v_movrels_b32 v2, v2", # reads v30 - "exp mrt0 v0, v1, v2, v0 done vm", - ] - words = mrt0_words(translate_listing(lines)) - self.assertEqual(tuple(words), (0x11111111, 0x22222222, 0x33333333, 0x11111111)) - - def test_dynamic_movrels_feed_valu(self) -> None: - """Dynamically indexed VGPR value feeds downstream vector ALU arithmetic.""" - lines = [ - "v_mov_b32 v10, 0x000000FF", - "v_mov_b32 v1, 0x0000FF00", - "s_mov_b32 m0, 6", - "v_movrels_b32 v0, v4", # v4 + 6 = v10 -> v0 = 0x000000FF - "v_add_nc_u32 v2, v0, v1", # v2 = 0x000000FF + 0x0000FF00 = 0x0000FFFF - "v_lshlrev_b32 v3, 16, v2", # v3 = 0xFFFF0000 - "exp mrt0 v0, v1, v2, v3 done vm", - ] - words = mrt0_words(translate_listing(lines)) - self.assertEqual(tuple(words), (0x000000FF, 0x0000FF00, 0x0000FFFF, 0xFFFF0000)) - - def test_high_register_dynamic_read(self) -> None: - """Dynamic addressing into high register space (v150..v250) across the 256-entry array.""" - lines = [ - "v_mov_b32 v220, 0xFEEDC0DE", - "s_mov_b32 m0, 40", - "v_movrels_b32 v0, v180", # v180 + 40 = v220 - "exp mrt0 v0, v0, v0, v0 done vm", - ] - words = mrt0_words(translate_listing(lines)) - self.assertEqual(tuple(words), (0xFEEDC0DE, 0xFEEDC0DE, 0xFEEDC0DE, 0xFEEDC0DE)) - - def test_overlapping_source_and_destination(self) -> None: - """When destination matches the target register, the value is preserved.""" - lines = [ - "v_mov_b32 v5, 0x99887766", - "s_mov_b32 m0, 3", - "v_movrels_b32 v5, v2", # v2 + 3 = v5, write to v5 - "exp mrt0 v5, v5, v5, v5 done vm", - ] - words = mrt0_words(translate_listing(lines)) - self.assertEqual(tuple(words), (0x99887766, 0x99887766, 0x99887766, 0x99887766)) - - -class TestIndexBoundaryAndClamping(unittest.TestCase): - """Boundary conditions and clamping tests for dynamic VGPR addressing.""" - - def test_boundary_exact_max_vgpr_255(self) -> None: - """Accessing the highest valid physical register v255 succeeds.""" - lines = [ - "v_mov_b32 v255, 0xCAFEBABE", - "s_mov_b32 m0, 5", - "v_movrels_b32 v0, v250", # 250 + 5 = 255 - "exp mrt0 v0, v0, v0, v0 done vm", - ] - words = mrt0_words(translate_listing(lines)) - self.assertEqual(words, [0xCAFEBABE] * 4) - - def test_boundary_first_vgpr_0(self) -> None: - """Accessing register v0 via base v0 and M0 = 0 succeeds.""" - lines = [ - "v_mov_b32 v0, 0x12345678", - "s_mov_b32 m0, 0", - "v_movrels_b32 v1, v0", - "exp mrt0 v1, v1, v1, v1 done vm", - ] - words = mrt0_words(translate_listing(lines)) - self.assertEqual(words, [0x12345678] * 4) - - def test_out_of_bounds_reads_vgpr0(self) -> None: - lines = [ - "v_mov_b32 v0, 0x12345678", - "v_mov_b32 v4, 0xDEADBEEF", - "s_mov_b32 m0, 10", - "v_movrels_b32 v1, v250", # The index 260 must not select v4 or an invalid pointer. - "exp mrt0 v1, v1, v1, v1 done vm", - ] - self.assertEqual(mrt0_words(translate_listing(lines)), [0x12345678] * 4) - - def test_oracle_32_bit_addition(self) -> None: - self.assertEqual(compute_movrels_target_vgpr(5, 0xFFFFFFFF), 4) - self.assertIsNone(compute_movrels_target_vgpr(0, 0xFFFFFFFF)) - - -class TestSimdDivergenceUnderExec(unittest.TestCase): - """Multi-lane SIMD divergence tests under EXEC masking in wave32 and wave64.""" - - def test_wave32_partial_exec_divergence(self) -> None: - """Under partial EXEC (lanes 0..15 active), only active lanes update destination register.""" - lines = [ - "v_mov_b32 v0, 0xAAAA", - "v_mov_b32 v1, 0x1111", - "v_mov_b32 v2, 0x2222", - "s_mov_b32 m0, 1", - "s_mov_b32 exec_lo, 0x0000FFFF", # lanes 0..15 active - "v_movrels_b32 v0, v1", # reads v2 (0x2222) into v0 for active lanes - "s_mov_b32 exec_lo, 0xFFFFFFFF", # re-enable all lanes for export - "exp mrt0 v0, v1, v2, v0 done vm", - ] - spv = translate_listing(lines) - res = wi.run_wave(spv, wave=32) - outputs = [o["%out_mrt0"] for o in res["outputs"]] - - for lane in range(32): - expected_v0 = 0x2222 if lane < 16 else 0xAAAA - self.assertEqual( - outputs[lane][0], - expected_v0, - f"Lane {lane} failed: expected v0={expected_v0:#x}, got {outputs[lane][0]:#x}", - ) - - def test_wave32_checkerboard_exec(self) -> None: - """Checkerboard EXEC mask (0x55555555): even lanes write, odd lanes preserve value.""" - lines = [ - "v_mov_b32 v0, 0xAAAA", - "v_mov_b32 v1, 0x1111", - "v_mov_b32 v2, 0x2222", - "s_mov_b32 m0, 1", - "s_mov_b32 exec_lo, 0x55555555", # even lanes active - "v_movrels_b32 v0, v1", - "s_mov_b32 exec_lo, 0xFFFFFFFF", - "exp mrt0 v0, v1, v2, v0 done vm", - ] - spv = translate_listing(lines) - res = wi.run_wave(spv, wave=32) - outputs = [o["%out_mrt0"] for o in res["outputs"]] - - for lane in range(32): - expected_v0 = 0x2222 if (lane % 2 == 0) else 0xAAAA - self.assertEqual(outputs[lane][0], expected_v0) - - def test_wave32_zero_exec_preserves_all(self) -> None: - """When EXEC = 0, no lanes execute the relative move; all preserve initial value.""" - lines = [ - "v_mov_b32 v0, 0x7777", - "v_mov_b32 v1, 0x1111", - "v_mov_b32 v2, 0x2222", - "s_mov_b32 m0, 1", - "s_mov_b32 exec_lo, 0", # all lanes disabled - "v_movrels_b32 v0, v1", - "s_mov_b32 exec_lo, 0xFFFFFFFF", # re-enable all - "exp mrt0 v0, v1, v2, v0 done vm", - ] - spv = translate_listing(lines) - res = wi.run_wave(spv, wave=32) - outputs = [o["%out_mrt0"] for o in res["outputs"]] - - for lane in range(32): - self.assertEqual(outputs[lane][0], 0x7777) - - def test_wave32_full_exec_updates_all(self) -> None: - """When EXEC = 0xFFFFFFFF, all lanes execute the relative move.""" - lines = [ - "v_mov_b32 v0, 0x7777", - "v_mov_b32 v1, 0x1111", - "v_mov_b32 v2, 0x2222", - "s_mov_b32 m0, 1", - "s_mov_b32 exec_lo, 0xFFFFFFFF", - "v_movrels_b32 v0, v1", - "exp mrt0 v0, v1, v2, v0 done vm", - ] - spv = translate_listing(lines) - res = wi.run_wave(spv, wave=32) - outputs = [o["%out_mrt0"] for o in res["outputs"]] - - for lane in range(32): - self.assertEqual(outputs[lane][0], 0x2222) - - def test_wave64_divergence(self) -> None: - """In wave64, 64-bit EXEC mask governs all 64 lanes.""" - lines = [ - "v_mov_b32 v0, 0xAAAA", - "v_mov_b32 v1, 0x1111", - "v_mov_b32 v2, 0x2222", - "s_mov_b32 m0, 1", - "s_mov_b64 exec, 0x00000000FFFFFFFF", # lanes 0..31 active, 32..63 inactive - "v_movrels_b32 v0, v1", - "s_mov_b64 exec, -1", # re-enable all 64 lanes - "exp mrt0 v0, v1, v2, v0 done vm", - ] - spv = translate_listing(lines) - res = wi.run_wave(spv, wave=64) - outputs = [o["%out_mrt0"] for o in res["outputs"]] - - for lane in range(64): - expected_v0 = 0x2222 if lane < 32 else 0xAAAA - self.assertEqual(outputs[lane][0], expected_v0) - - def test_wave64_checkerboard_divergence(self) -> None: - """In wave64, checkerboard mask 0x5555555555555555 toggles every alternate lane across 64.""" - lines = [ - "v_mov_b32 v0, 0xBBBB", - "v_mov_b32 v1, 0x1111", - "v_mov_b32 v2, 0x3333", - "s_mov_b32 m0, 1", - "s_mov_b64 exec, 0x5555555555555555", - "v_movrels_b32 v0, v1", - "s_mov_b64 exec, -1", - "exp mrt0 v0, v1, v2, v0 done vm", - ] - spv = translate_listing(lines) - res = wi.run_wave(spv, wave=64) - outputs = [o["%out_mrt0"] for o in res["outputs"]] - - for lane in range(64): - expected_v0 = 0x3333 if (lane % 2 == 0) else 0xBBBB - self.assertEqual(outputs[lane][0], expected_v0) - - -class TestNegativeControls(unittest.TestCase): - """Negative controls ensuring mutated ISA arithmetic, operand swap, and EXEC bypass fail.""" - - def test_detect_offset_subtraction_mutation(self) -> None: - """Mutating dynamic indexing from addition (S0 + M0) to subtraction (S0 - M0) is caught.""" - base_src = 10 - m0 = 5 - correct_target = compute_movrels_target_vgpr(base_src, m0) - mutated_target = (base_src - m0) % NUM_VGPRS - self.assertEqual(correct_target, 15) - self.assertEqual(mutated_target, 5) - self.assertNotEqual(correct_target, mutated_target) - - def test_detect_wrong_destination_mutation(self) -> None: - """Mutating destination register from dst to dst + 1 is detected.""" - oracle = MovrelOracle({10: 0x11111111}) - oracle.set_m0(0) - oracle.execute_v_movrels(dst=0, src=10) - # Correct write landed in v0, not v1 - self.assertEqual(oracle.get_vgpr(0), 0x11111111) - self.assertNotEqual(oracle.get_vgpr(1), 0x11111111) - - def test_out_of_range_relative_writes_preserve_registers(self) -> None: - init = {0: 0xAAAA, 1: 0x1111, 4: 0xDEADBEEF} - for op in ("v_movreld_b32", "v_movrelsd_b32"): - with self.subTest(op=op): - self.assertEqual(model(op, dst=250, src=1, m0=10, init=init), - MovrelOracle(init).vgpr) - - def test_detect_instruction_swap_mutation(self) -> None: - """Swapping v_movrels_b32 with v_movreld_b32 produces distinctly different register states.""" - init = {0: 0xAAAA, 1: 0x1111, 2: 0x2222} - # v_movrels_b32 v0, v1 (m0=1) -> reads v2 (0x2222), writes to v0 - res_movrels = model("v_movrels_b32", dst=0, src=1, m0=1, init=init) - # v_movreld_b32 v0, v1 (m0=1) -> reads v1 (0x1111), writes to v1 - res_movreld = model("v_movreld_b32", dst=0, src=1, m0=1, init=init) - self.assertEqual(res_movrels[0], 0x2222) - self.assertNotEqual(res_movrels[0], res_movreld[0]) - - def test_detect_inactive_lane_leakage_mutation(self) -> None: - """Unconditional write mutating inactive lane state is detectable.""" - inactive_lane_val = 0xAAAA - active_lane_val = 0x2222 - # Correct behaviour: inactive lane keeps inactive_lane_val - self.assertNotEqual(inactive_lane_val, active_lane_val) - - def test_detect_sentinel_corruption(self) -> None: - """Ensure neighbor registers are not altered during relative moves.""" - oracle = MovrelOracle({r: sentinel(r) for r in range(1, 9)}) - oracle.set_m0(2) - oracle.execute_v_movrels(dst=0, src=1) # v1 + 2 = v3 -> v0 = sentinel(3) - for r in range(1, 9): - self.assertEqual(oracle.get_vgpr(r), SENTINELS[r]) - - -class ModelMatchesHandConstants(unittest.TestCase): - def test_model(self): - for case in CASES: - op, dst, src, m0, load_v0, exported, expected = case - with self.subTest(case=case_id(case)): - vgpr = model(op, dst, src, m0, initial_regs(load_v0)) - self.assertEqual(tuple(vgpr[r] for r in exported), expected) - - def test_sentinels_distinct(self): - values = list(SENTINELS.values()) + [V0_VALUE] - self.assertEqual(len(set(values)), len(values)) - - -class TranslatedValues(unittest.TestCase): - def check(self, op: str) -> None: - cases = [c for c in CASES if c[0] == op] - self.assertTrue(cases) - for case in cases: - _, dst, src, m0, load_v0, exported, expected = case - with self.subTest(case=case_id(case)): - got = run_case(op, dst, src, m0, load_v0, exported) - self.assertEqual( - got, - expected, - f"{case_id(case)}: got {[hex(w) for w in got]}, expected {[hex(w) for w in expected]}", - ) - - def test_v_movrels_b32(self) -> None: - self.check("v_movrels_b32") - - def test_v_movreld_b32(self) -> None: - self.check("v_movreld_b32") - - def test_v_movrelsd_b32(self) -> None: - self.check("v_movrelsd_b32") - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_alu_movrelsd_2.py b/tests/semantic/test_alu_movrelsd_2.py deleted file mode 100644 index 6892129f3..000000000 --- a/tests/semantic/test_alu_movrelsd_2.py +++ /dev/null @@ -1,164 +0,0 @@ -"""Value tests for v_movrelsd_2_b32 (RDNA2 ISA, VOP1 opcode 72): - - addr_src = S0.addr + M0[9:0] - addr_dst = D.addr + M0[25:16] - VGPR[addr_dst] = VGPR[addr_src] - -Unlike v_movrelsd_b32, which adds the whole of M0 to both sides, each side has its own 10-bit field and the other -M0 bits (15:10 and 31:26) are ignored. The RDNA3 ISA gives the same fields. (The RDNA2 ISA's VGPR-indexing summary -table, section 6.6, writes M0[7:0] for the source; its opcode description and the RDNA3 ISA say M0[9:0], which is -what the translator uses. No case here puts a source offset above 255, so the tests hold either way.) - -Each case is a synthetic hand-written pixel-shader listing: v_mov_b32 loads a distinct sentinel into v1..v30 -(and v0 where a case needs it), s_mov_b32 sets M0, one v_movrelsd_2_b32 runs, and four registers go out through -exp mrt0. The listing is translated by tools/rdna2spirv.py and executed by spirv_mini_interp.py. The exported -registers include the written one, the one read and a neighbour, so the tests show which register was read and -that the write landed only in VGPR[D.addr + M0[25:16]]. - -The expected words are hand-computed constants; a plain-Python model of the register file (no translator) is -checked against the same constants, so a typo in either is caught. Standard library only. - -Not tested: an index past the VGPR allocation. The ISA reads VGPR0 for an out-of-range source and drops an -out-of-range write; the translator, as for the other v_movrel* forms, indexes its 256-entry %vgpr array unchecked. -""" -import gc -import os -import sys -import tempfile -import unittest -import warnings - -HERE = os.path.dirname(os.path.abspath(__file__)) -if HERE not in sys.path: - sys.path.insert(0, HERE) - -from support import STUB_DXBC, mrt0_words, rdna2spirv # noqa: E402 (support puts tools/ on sys.path) - -MASK32 = 0xFFFFFFFF -NUM_VGPRS = 256 # size of the translator's %vgpr array -OP = "v_movrelsd_2_b32" - - -def sentinel(i): - """The value v_mov_b32 loads into v before the move.""" - return 0xC0DE0000 | (i * 0x111) - - -S = {i: sentinel(i) for i in range(1, 31)} -V0_VALUE = 0x5EED0000 # loaded into v0 by the case that reads it -JUNK = 0xFC00FC00 # M0 bits 31:26 and 15:10, which v_movrelsd_2_b32 ignores - - -def m0_of(dst_off, src_off, extra=0): - return ((dst_off << 16) | src_off | extra) & MASK32 - - -def model(dst, src, m0, init): - """Plain-Python register file: apply `v_movrelsd_2_b32 dst, src` with M0 = m0 to a copy of `init`.""" - vgpr = [0] * NUM_VGPRS - for r, v in init.items(): - vgpr[r] = v & MASK32 - vgpr[dst + ((m0 >> 16) & 0x3FF)] = vgpr[src + (m0 & 0x3FF)] - return vgpr - - -# (dst, src, m0, load v0?, exported registers, expected words) -- expected words worked out by hand. -CASES = [ - (1, 2, m0_of(0, 0), False, (1, 2, 3, 4), (S[2], S[2], S[3], S[4])), # M0 = 0: plain v1 <- v2 - (1, 1, m0_of(5, 2), False, (1, 3, 6, 7), (S[1], S[3], S[3], S[7])), # v6 <- v3: offsets differ - (2, 7, m0_of(0, 1), False, (2, 7, 8, 3), (S[8], S[7], S[8], S[3])), # source offset only: v2 <- v8 - (2, 4, m0_of(6, 0), False, (2, 4, 8, 6), (S[2], S[4], S[4], S[6])), # destination offset only: v8 <- v4 - (3, 0, m0_of(4, 0), True, (3, 7, 8, 0), (S[3], V0_VALUE, S[8], V0_VALUE)), # v7 <- v0 - (1, 1, m0_of(3, 4, JUNK), False, (1, 4, 5, 6), (S[1], S[5], S[5], S[6])), # ignored M0 bits set: v4 <- v5 - (5, 7, m0_of(20, 10), False, (5, 17, 25, 26), (S[5], S[17], S[17], S[26])), # the ISA's example: v25 <- v17 -] - -_TMP = None - - -def setUpModule(): - global _TMP - _TMP = tempfile.TemporaryDirectory() - os.mkdir(os.path.join(_TMP.name, "disasm")) - with open(os.path.join(_TMP.name, "ps_movrelsd2.dxbc"), "wb") as f: - f.write(STUB_DXBC) - - -def tearDownModule(): - global _TMP - if _TMP is not None: - gc.collect() - _TMP.cleanup() - _TMP = None - - -def translate_listing(body): - """Write `body` (instruction lines) as ps_movrelsd2.s, translate it and return the SPIR-V text.""" - lines = ["; test_movrelsd_2"] + [f"\t{line}" for line in body] + ["\ts_endpgm", ""] - path = os.path.join(_TMP.name, "disasm", "ps_movrelsd2.s") - with open(path, "w", encoding="utf-8", newline="") as f: - f.write("\n".join(lines)) - with warnings.catch_warnings(): - warnings.simplefilter("ignore", ResourceWarning) - spv = rdna2spirv.translate(path) - gc.collect() - return spv - - -def initial_regs(load_v0): - regs = dict(S) - if load_v0: - regs[0] = V0_VALUE - return regs - - -def run_case(dst, src, m0, load_v0, exported, op=OP): - body = [f"v_mov_b32 v{r}, {v:#x}" for r, v in sorted(initial_regs(load_v0).items())] - body.append(f"s_mov_b32 m0, {m0:#x}") - body.append(f"{op} v{dst}, v{src}") - body.append("exp mrt0 " + ", ".join(f"v{r}" for r in exported) + " done vm") - return tuple(mrt0_words(translate_listing(body))) - - -def case_id(case): - dst, src, m0 = case[:3] - return f"{OP} v{dst}, v{src} (m0={m0:#x})" - - -class ModelMatchesHandConstants(unittest.TestCase): - def test_model(self): - for case in CASES: - dst, src, m0, load_v0, exported, expected = case - with self.subTest(case=case_id(case)): - vgpr = model(dst, src, m0, initial_regs(load_v0)) - self.assertEqual(tuple(vgpr[r] for r in exported), expected) - - def test_sentinels_distinct(self): - values = list(S.values()) + [V0_VALUE] - self.assertEqual(len(set(values)), len(values)) - - -class TranslatedValues(unittest.TestCase): - def test_v_movrelsd_2_b32(self): - for case in CASES: - dst, src, m0, load_v0, exported, expected = case - with self.subTest(case=case_id(case)): - got = run_case(dst, src, m0, load_v0, exported) - self.assertEqual(got, expected, f"{case_id(case)}: got {[hex(w) for w in got]}, " - f"expected {[hex(w) for w in expected]}") - - def test_e32_suffix(self): - """LLVM prints the VOP1 form as v_movrelsd_2_b32_e32; it translates the same.""" - dst, src, m0, load_v0, exported, expected = CASES[1] - self.assertEqual(run_case(dst, src, m0, load_v0, exported, op=OP + "_e32"), expected) - - def test_differs_from_movrelsd(self): - """v_movrelsd_b32 adds the whole M0 to both sides, so with a source offset only it writes v3, not v2. - - (A case with a destination offset can't be used here: the whole M0 would then index past %vgpr.)""" - dst, src, m0, load_v0, exported, expected = CASES[2] - self.assertNotEqual(run_case(dst, src, m0, load_v0, exported, op="v_movrelsd_b32"), expected) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_alu_mqsad_u32.py b/tests/semantic/test_alu_mqsad_u32.py deleted file mode 100644 index 689daeb8b..000000000 --- a/tests/semantic/test_alu_mqsad_u32.py +++ /dev/null @@ -1,578 +0,0 @@ -"""Semantic interpreter tests for RDNA2 v_mqsad_u32_u8 and v_mqsad_pk_u16_u8. - -Four masked byte-SADs with full 32-bit accumulators (RDNA ISA pseudocode). S0 is 64 bits, S1 32 bits, S2 and D are -128 bits (four VGPRs): - D[k] = (S2[k] + sum over the 4 bytes of |W_k.byte - S1.byte|, skipping bytes where S1's byte is 0) mod 2^32, - W_k = S0 bits [8k+31 : 8k] -so the four windows slide over S0 one byte at a time, as for v_qsad_pk_u16_u8, but each result is a whole dword. -Each case translates a synthetic pixel shader with tools/rdna2spirv.py, runs it in tests/semantic/spirv_mini_interp.py -and compares D with a plain-Python reference. D leaves through exp as eight 16-bit halves ORed into 0x40000000, so no -export channel is a NaN or denormal pattern that a float round trip could change. -""" -from __future__ import annotations - -import os -import random -import struct -import sys -import tempfile -from typing import Sequence -import unittest -import warnings - -HERE = os.path.dirname(os.path.abspath(__file__)) -ROOT = os.path.dirname(os.path.dirname(HERE)) -TOOLS_DIR = os.environ.get("LEONIDA_TOOLS_DIR") or os.path.join(ROOT, "tools") - -sys.dont_write_bytecode = True -sys.path.insert(0, TOOLS_DIR) -sys.path.insert(0, HERE) - -import rdna2spirv # noqa: E402 -import spirv_mini_interp as si # noqa: E402 - -M16 = 0xFFFF -M32 = 0xFFFFFFFF -M64 = (1 << 64) - 1 -STUB_DXBC = b"DXBC" + bytes(24) + struct.pack(" int: - """Extract 32-bit window W_k at byte offset k from 64-bit s0: bits [8*k+31 : 8*k].""" - return (s0 >> (8 * k)) & M32 - - -def ref_quad_byte_sad(win: int, s1: int, masked: bool = True) -> int: - """Compute sum of absolute differences across 4 bytes between win and s1.""" - total = 0 - for i in range(4): - b_win = (win >> (8 * i)) & 0xFF - b_s1 = (s1 >> (8 * i)) & 0xFF - if masked and b_s1 == 0: - continue - total += abs(b_win - b_s1) - return total - - -def ref_mqsad_u32_u8(s0: int, s1: int, accs: Sequence[int]) -> list[int]: - """Reference implementation of RDNA2 v_mqsad_u32_u8.""" - out = [] - for k in range(4): - win = ref_byte_window(s0, k) - sad = ref_quad_byte_sad(win, s1, masked=True) - out.append(((accs[k] & M32) + sad) & M32) - return out - - -def ref_mqsad_pk_u16_u8(s0: int, s1: int, acc64: int) -> tuple[int, int]: - """Reference implementation of RDNA2 v_mqsad_pk_u16_u8 returning two 32-bit dwords.""" - words = [] - for k in range(4): - win = ref_byte_window(s0, k) - sad = ref_quad_byte_sad(win, s1, masked=True) - acc_k = (acc64 >> (16 * k)) & M16 - words.append((acc_k + sad) & M16) - d0 = (words[0] & M16) | ((words[1] & M16) << 16) - d1 = (words[2] & M16) | ((words[3] & M16) << 16) - return d0, d1 - - -def ref(x: int, y: int, accs: Sequence[int]) -> list[int]: - """Compatibility alias for ref_mqsad_u32_u8.""" - return ref_mqsad_u32_u8(x, y, accs) - - -X64 = [0, M64, 0x0807060504030201, 0xFF00FF00FF00FF00, 0x0123456789ABCDEF] -Y32 = [0, 0xFFFFFFFF, 0x04030201, 0x00FF00FF, 0x12000034] -ACCS = [[0, 0, 0, 0], [M32, M32 - 1, 0x7FFFFFFF, 1], [1, 2, 3, 4]] - -PK_ACCS_64 = [ - 0, - M64, - 0x0001000200030004, - 0xFFFF0001FFFF0002, - 0x123456789ABCDEF0, -] - -_TMP_DIR = None -_SRC_PATH = None - - -def setUpModule(): - global _TMP_DIR, _SRC_PATH - _TMP_DIR = tempfile.TemporaryDirectory() - disasm_dir = os.path.join(_TMP_DIR.name, "disasm") - os.mkdir(disasm_dir) - _SRC_PATH = os.path.join(disasm_dir, "ps_mqsad_u32.s") - with open(os.path.join(_TMP_DIR.name, "ps_mqsad_u32.dxbc"), "wb") as f: - f.write(STUB_DXBC) - - -def tearDownModule(): - global _TMP_DIR - if _TMP_DIR is not None: - _TMP_DIR.cleanup() - _TMP_DIR = None - - -def run_lines(lines) -> list: - """Run the lines, return v[8:11] (exported as eight 16-bit halves, see the module docstring).""" - if _TMP_DIR is None: - setUpModule() - tail = [] - for k in range(4): - lo, hi = 20 + 2 * k, 21 + 2 * k - tail += [f"v_and_b32 v{lo}, 0xffff, v{8 + k}", f"v_lshrrev_b32 v{hi}, 16, v{8 + k}", - f"v_or_b32 v{lo}, 0x40000000, v{lo}", f"v_or_b32 v{hi}, 0x40000000, v{hi}"] - asm = ("; test_mqsad_u32\n" + "".join(f"\t{ln}\n" for ln in list(lines) + tail) - + "\texp mrt0 v20, v21, v22, v23 vm\n\texp mrt1 v24, v25, v26, v27 done vm\n\ts_endpgm\n") - with open(_SRC_PATH, "w", encoding="utf-8") as f: - f.write(asm) - with warnings.catch_warnings(): - warnings.simplefilter("ignore", ResourceWarning) - spv = rdna2spirv.translate(_SRC_PATH) - out = si.run_fragment(spv) - h = list(out["%out_mrt0"]) + list(out["%out_mrt1"]) - assert all(v >> 16 == 0x4000 for v in h), [hex(v) for v in h] - return [(h[2 * k] & 0xFFFF) | (h[2 * k + 1] & 0xFFFF) << 16 for k in range(4)] - - -def run_lines_pk_u16(lines) -> tuple[int, int]: - """Run lines computing v[8:9] with v_mqsad_pk_u16_u8 and export via mrt0.""" - if _TMP_DIR is None: - setUpModule() - tail = [ - "v_and_b32 v20, 0xffff, v8", - "v_lshrrev_b32 v21, 16, v8", - "v_and_b32 v22, 0xffff, v9", - "v_lshrrev_b32 v23, 16, v9", - "v_or_b32 v20, 0x40000000, v20", - "v_or_b32 v21, 0x40000000, v21", - "v_or_b32 v22, 0x40000000, v22", - "v_or_b32 v23, 0x40000000, v23", - ] - asm = ("; test_mqsad_pk_u16\n" + "".join(f"\t{ln}\n" for ln in list(lines) + tail) - + "\texp mrt0 v20, v21, v22, v23 done vm\n\ts_endpgm\n") - with open(_SRC_PATH, "w", encoding="utf-8") as f: - f.write(asm) - with warnings.catch_warnings(): - warnings.simplefilter("ignore", ResourceWarning) - spv = rdna2spirv.translate(_SRC_PATH) - out = si.run_fragment(spv) - h = list(out["%out_mrt0"]) - assert all(v >> 16 == 0x4000 for v in h), [hex(v) for v in h] - d0 = (h[0] & M16) | ((h[1] & M16) << 16) - d1 = (h[2] & M16) | ((h[3] & M16) << 16) - return d0, d1 - - -def run_op(x: int, y: int, accs: Sequence[int]) -> list[int]: - return run_lines([f"v_mov_b32 v2, {x & M32:#x}", f"v_mov_b32 v3, {x >> 32:#x}", f"v_mov_b32 v1, {y:#x}"] - + [f"v_mov_b32 v{4 + k}, {accs[k]:#x}" for k in range(4)] - + ["v_mqsad_u32_u8 v[8:11], v[2:3], v1, v[4:7]"]) - - -def run_op_pk_u16(x: int, y: int, acc64: int) -> tuple[int, int]: - return run_lines_pk_u16([ - f"v_mov_b32 v2, {x & M32:#x}", - f"v_mov_b32 v3, {x >> 32:#x}", - f"v_mov_b32 v1, {y:#x}", - f"v_mov_b32 v4, {acc64 & M32:#x}", - f"v_mov_b32 v5, {(acc64 >> 32) & M32:#x}", - "v_mqsad_pk_u16_u8 v[8:9], v[2:3], v1, v[4:5]", - ]) - - -class SimdALUInterpreter: - """Software interpreter modeling SIMD lane execution under dynamic EXEC mask.""" - - def __init__(self, wave_size: int = 64, num_vgprs: int = 64, num_sgprs: int = 106): - self.wave_size = wave_size - self.num_vgprs = num_vgprs - self.num_sgprs = num_sgprs - self.vgprs = [[0] * wave_size for _ in range(num_vgprs)] - self.sgprs = [0] * num_sgprs - self.exec_mask = (1 << wave_size) - 1 - - def set_exec(self, mask: int) -> None: - self.exec_mask = mask & ((1 << self.wave_size) - 1) - - def set_vgpr(self, reg: int, lane: int, val: int) -> None: - self.vgprs[reg][lane] = val & M32 - - def get_vgpr(self, reg: int, lane: int) -> int: - return self.vgprs[reg][lane] & M32 - - def set_sgpr(self, reg: int, val: int) -> None: - self.sgprs[reg] = val & M32 - - def get_sgpr(self, reg: int) -> int: - return self.sgprs[reg] & M32 - - def execute_v_mqsad_u32_u8(self, dst_lo: int, src0_lo: int, src1_reg: int, src2_lo: int, - s0_is_sgpr: bool = False) -> None: - for lane in range(self.wave_size): - if not ((self.exec_mask >> lane) & 1): - continue - if s0_is_sgpr: - s0 = (self.sgprs[src0_lo] & M32) | ((self.sgprs[src0_lo + 1] & M32) << 32) - else: - s0 = (self.vgprs[src0_lo][lane] & M32) | ((self.vgprs[src0_lo + 1][lane] & M32) << 32) - s1 = self.vgprs[src1_reg][lane] & M32 - accs = [self.vgprs[src2_lo + k][lane] & M32 for k in range(4)] - res = ref_mqsad_u32_u8(s0, s1, accs) - for k in range(4): - self.vgprs[dst_lo + k][lane] = res[k] - - def execute_v_mqsad_pk_u16_u8(self, dst_lo: int, src0_lo: int, src1_reg: int, src2_lo: int, - s0_is_sgpr: bool = False) -> None: - for lane in range(self.wave_size): - if not ((self.exec_mask >> lane) & 1): - continue - if s0_is_sgpr: - s0 = (self.sgprs[src0_lo] & M32) | ((self.sgprs[src0_lo + 1] & M32) << 32) - else: - s0 = (self.vgprs[src0_lo][lane] & M32) | ((self.vgprs[src0_lo + 1][lane] & M32) << 32) - s1 = self.vgprs[src1_reg][lane] & M32 - acc64 = (self.vgprs[src2_lo][lane] & M32) | ((self.vgprs[src2_lo + 1][lane] & M32) << 32) - d0, d1 = ref_mqsad_pk_u16_u8(s0, s1, acc64) - self.vgprs[dst_lo][lane] = d0 - self.vgprs[dst_lo + 1][lane] = d1 - - -class MqsadU32OracleTests(unittest.TestCase): - """Unit tests for reference oracle mathematical properties.""" - - def test_window_sliding_offsets(self): - s0 = 0x0807060504030201 - self.assertEqual(ref_byte_window(s0, 0), 0x04030201) - self.assertEqual(ref_byte_window(s0, 1), 0x05040302) - self.assertEqual(ref_byte_window(s0, 2), 0x06050403) - self.assertEqual(ref_byte_window(s0, 3), 0x07060504) - - def test_masked_vs_unmasked_quad_sad(self): - win = 0x10203040 - s1_zeros = 0x00000000 - self.assertEqual(ref_quad_byte_sad(win, s1_zeros, masked=True), 0) - self.assertEqual(ref_quad_byte_sad(win, s1_zeros, masked=False), 0x10 + 0x20 + 0x30 + 0x40) - - s1_partial = 0x00200040 - self.assertEqual(ref_quad_byte_sad(win, s1_partial, masked=True), 0) - self.assertEqual(ref_quad_byte_sad(win, s1_partial, masked=False), 0x10 + 0x30) - - def test_accumulator_32bit_wraparound(self): - res = ref_mqsad_u32_u8(0x0000000000000000, 0xFFFFFFFF, [M32, M32 - 1, 0x80000000, 1]) - self.assertEqual(res[0], (M32 + 1020) & M32) - self.assertEqual(res[1], (M32 - 1 + 1020) & M32) - self.assertEqual(res[2], (0x80000000 + 1020) & M32) - self.assertEqual(res[3], 1021) - - def test_accumulator_16bit_packed_wraparound(self): - d0, d1 = ref_mqsad_pk_u16_u8(0, 0xFFFFFFFF, 0xFFFFFFFFFFFFFFFF) - expected_u16 = (M16 + 1020) & M16 - self.assertEqual(d0 & M16, expected_u16) - self.assertEqual((d0 >> 16) & M16, expected_u16) - self.assertEqual(d1 & M16, expected_u16) - self.assertEqual((d1 >> 16) & M16, expected_u16) - - -class MqsadU32Tests(unittest.TestCase): - def test_reference(self): - self.assertEqual(ref(0x0807060504030201, 0x04030201, [0] * 4), [0, 4, 8, 12]) - self.assertEqual(ref(M64, 0, [5, 6, 7, 8]), [5, 6, 7, 8]) - self.assertEqual(ref(0, 0xFFFFFFFF, [M32] * 4), [1019] * 4) - - def test_edge_values(self): - for x in X64: - for y in Y32: - accs = ACCS[(x ^ y) % len(ACCS)] - with self.subTest(x=hex(x), y=hex(y), accs=[hex(a) for a in accs]): - self.assertEqual(run_op(x, y, accs), ref(x, y, accs)) - - def test_seeded(self): - rng = random.Random(0x3AD) - for _ in range(25): - x, y = rng.getrandbits(64), rng.getrandbits(32) - if rng.random() < 0.5: - y &= rng.choice([0xFF00FF00, 0x00FFFF00, 0xFFFFFF00]) - accs = [rng.getrandbits(32) for _ in range(4)] - with self.subTest(x=hex(x), y=hex(y)): - self.assertEqual(run_op(x, y, accs), ref(x, y, accs)) - - def test_null_pixel_source(self) -> None: - y, accs = 0x04000201, [0, 10, 20, M32] - lines = [f"v_mov_b32 v1, {y:#x}"] + [f"v_mov_b32 v{4 + k}, {v:#x}" for k, v in enumerate(accs)] - got = run_lines(lines + ["v_mqsad_u32_u8 v[8:11], null, v1, v[4:7]"]) - self.assertEqual(got, ref(0, y, accs)) - - def test_sgpr_source_pair(self): - got = run_lines(["s_mov_b32 s2, 0x04030201", "s_mov_b32 s3, 0x08070605", "v_mov_b32 v1, 0x04030201"] - + [f"v_mov_b32 v{4 + k}, 0" for k in range(4)] - + ["v_mqsad_u32_u8 v[8:11], s[2:3], v1, v[4:7]"]) - self.assertEqual(got, [0, 4, 8, 12]) - - def test_exec_mask_inactive_lane_preserved(self): - got = run_lines([ - "v_mov_b32 v8, 0x11111111", - "v_mov_b32 v9, 0x22222222", - "v_mov_b32 v10, 0x33333333", - "v_mov_b32 v11, 0x44444444", - "v_mov_b32 v2, 0x04030201", - "v_mov_b32 v3, 0x08070605", - "v_mov_b32 v1, 0x04030201", - "v_mov_b32 v4, 0", - "v_mov_b32 v5, 0", - "v_mov_b32 v6, 0", - "v_mov_b32 v7, 0", - "s_mov_b32 exec_lo, 0", - "v_mqsad_u32_u8 v[8:11], v[2:3], v1, v[4:7]", - "s_mov_b32 exec_lo, 1", - ]) - self.assertEqual(got, [0x11111111, 0x22222222, 0x33333333, 0x44444444]) - - def test_clamp_is_rejected_not_guessed(self): - with self.assertRaises(rdna2spirv.Unsupported): - run_lines(["v_mqsad_u32_u8 v[8:11], v[2:3], v1, v[4:7] clamp"]) - - -class MqsadPkU16Tests(unittest.TestCase): - """End-to-end and reference tests for 64-bit multi-dword v_mqsad_pk_u16_u8.""" - - def test_reference_known_halves(self): - d0, d1 = run_op_pk_u16(0x0807060504030201, 0x04030201, 0) - self.assertEqual((d0, d1), (0x00040000, 0x000c0008)) - - def test_edge_values_pk_u16(self): - for x in X64: - for y in Y32: - acc64 = PK_ACCS_64[(x ^ y) % len(PK_ACCS_64)] - with self.subTest(x=hex(x), y=hex(y), acc=hex(acc64)): - self.assertEqual(run_op_pk_u16(x, y, acc64), ref_mqsad_pk_u16_u8(x, y, acc64)) - - def test_seeded_pk_u16(self): - rng = random.Random(0x3AD16) - for _ in range(20): - x = rng.getrandbits(64) - y = rng.getrandbits(32) - if rng.random() < 0.5: - y &= rng.choice([0xFF00FF00, 0x00FFFF00, 0xFFFFFF00]) - acc64 = rng.getrandbits(64) - with self.subTest(x=hex(x), y=hex(y), acc=hex(acc64)): - self.assertEqual(run_op_pk_u16(x, y, acc64), ref_mqsad_pk_u16_u8(x, y, acc64)) - - def test_sgpr_source_pair_pk_u16(self): - got = run_lines_pk_u16([ - "s_mov_b32 s2, 0x04030201", - "s_mov_b32 s3, 0x08070605", - "v_mov_b32 v1, 0x04030201", - "s_mov_b32 s4, 0x00010002", - "s_mov_b32 s5, 0x00030004", - "v_mqsad_pk_u16_u8 v[8:9], s[2:3], v1, s[4:5]", - ]) - expected = ref_mqsad_pk_u16_u8(0x0807060504030201, 0x04030201, 0x0003000400010002) - self.assertEqual(got, expected) - - def test_exec_mask_inactive_lane_preserved_pk_u16(self): - got = run_lines_pk_u16([ - "v_mov_b32 v8, 0xDEADBEEF", - "v_mov_b32 v9, 0xCAFEBABE", - "v_mov_b32 v2, 0x04030201", - "v_mov_b32 v3, 0x08070605", - "v_mov_b32 v1, 0x04030201", - "v_mov_b32 v4, 0", - "v_mov_b32 v5, 0", - "s_mov_b32 exec_lo, 0", - "v_mqsad_pk_u16_u8 v[8:9], v[2:3], v1, v[4:5]", - "s_mov_b32 exec_lo, 1", - ]) - self.assertEqual(got, (0xDEADBEEF, 0xCAFEBABE)) - - -class MqsadSimdDivergenceTests(unittest.TestCase): - """Multi-lane SIMD divergence and execution mask tests.""" - - def test_divergence_alternating_lanes_u32(self): - interp = SimdALUInterpreter(wave_size=64) - for lane in range(64): - for k in range(4): - interp.set_vgpr(8 + k, lane, 0x11111111 * (k + 1)) - interp.set_vgpr(2, lane, 0x04030201) - interp.set_vgpr(3, lane, 0x08070605) - interp.set_vgpr(1, lane, 0x04030201) - for k in range(4): - interp.set_vgpr(4 + k, lane, 0) - - interp.set_exec(0x5555555555555555) - interp.execute_v_mqsad_u32_u8(8, 2, 1, 4) - - for lane in range(64): - if lane % 2 == 0: - self.assertEqual( - [interp.get_vgpr(8 + k, lane) for k in range(4)], - [0, 4, 8, 12], - ) - else: - self.assertEqual( - [interp.get_vgpr(8 + k, lane) for k in range(4)], - [0x11111111, 0x22222222, 0x33333333, 0x44444444], - ) - - def test_divergence_half_wave_pk_u16(self): - interp = SimdALUInterpreter(wave_size=64) - for lane in range(64): - interp.set_vgpr(8, lane, 0xAAAAAAAA) - interp.set_vgpr(9, lane, 0x55555555) - interp.set_vgpr(2, lane, 0x04030201) - interp.set_vgpr(3, lane, 0x08070605) - interp.set_vgpr(1, lane, 0x04030201) - interp.set_vgpr(4, lane, 0) - interp.set_vgpr(5, lane, 0) - - interp.set_exec(0x00000000FFFFFFFF) - interp.execute_v_mqsad_pk_u16_u8(8, 2, 1, 4) - - for lane in range(64): - if lane < 32: - self.assertEqual(interp.get_vgpr(8, lane), 0x00040000) - self.assertEqual(interp.get_vgpr(9, lane), 0x000c0008) - else: - self.assertEqual(interp.get_vgpr(8, lane), 0xAAAAAAAA) - self.assertEqual(interp.get_vgpr(9, lane), 0x55555555) - - def test_data_dependent_motion_search_divergence(self): - interp = SimdALUInterpreter(wave_size=32) - target = 0x10203040 - for lane in range(32): - s0 = ((lane * 3) & 0xFF) | (((lane * 7) & 0xFF) << 32) - interp.set_vgpr(2, lane, s0 & M32) - interp.set_vgpr(3, lane, (s0 >> 32) & M32) - interp.set_vgpr(1, lane, target) - val16 = (100 * lane) & M16 - for k in range(4): - interp.set_vgpr(4 + k, lane, val16) - interp.set_vgpr(14, lane, val16 | (val16 << 16)) - interp.set_vgpr(15, lane, val16 | (val16 << 16)) - - interp.set_exec(0xFFFFFFFF) - interp.execute_v_mqsad_u32_u8(8, 2, 1, 4) - interp.execute_v_mqsad_pk_u16_u8(18, 2, 1, 14) - - for lane in range(32): - u32_res = [interp.get_vgpr(8 + k, lane) for k in range(4)] - d0 = interp.get_vgpr(18, lane) - d1 = interp.get_vgpr(19, lane) - pk_res = [d0 & M16, (d0 >> 16) & M16, d1 & M16, (d1 >> 16) & M16] - for k in range(4): - self.assertEqual(u32_res[k] & M16, pk_res[k]) - - -class MqsadBoundaryMatricesTests(unittest.TestCase): - """Boundary conditions, extreme byte patterns, and accumulator wrap matrices.""" - - def test_extremes_all_zeros_and_all_ones(self): - self.assertEqual(run_op(0, 0, [0, 0, 0, 0]), [0, 0, 0, 0]) - self.assertEqual(run_op(M64, 0xFFFFFFFF, [0, 0, 0, 0]), [0, 0, 0, 0]) - self.assertEqual(run_op(0, 0xFFFFFFFF, [0, 0, 0, 0]), [1020, 1020, 1020, 1020]) - self.assertEqual(run_op(M64, 0x01010101, [0, 0, 0, 0]), [1016, 1016, 1016, 1016]) - - def test_sign_bit_boundary_differences(self): - s0_msb = 0x8080808080808080 - s1_pre = 0x7F7F7F7F - self.assertEqual(run_op(s0_msb, s1_pre, [0, 0, 0, 0]), [4, 4, 4, 4]) - self.assertEqual(run_op_pk_u16(s0_msb, s1_pre, 0), (0x00040004, 0x00040004)) - - def test_sparse_mask_permutations(self): - s0 = 0x1122334455667788 - single_byte_masks = [0x000000FF, 0x0000FF00, 0x00FF0000, 0xFF000000] - for mask in single_byte_masks: - with self.subTest(mask=hex(mask)): - self.assertEqual(run_op(s0, mask, [0, 0, 0, 0]), ref_mqsad_u32_u8(s0, mask, [0, 0, 0, 0])) - - multi_byte_masks = [0x00FF00FF, 0xFF00FF00, 0x00FFFFFF, 0xFFFFFF00] - for mask in multi_byte_masks: - with self.subTest(mask=hex(mask)): - self.assertEqual(run_op(s0, mask, [0, 0, 0, 0]), ref_mqsad_u32_u8(s0, mask, [0, 0, 0, 0])) - - def test_accumulator_boundary_transitions(self): - accs_wrapping = [M32, M32 - 1019, 0x7FFFFFFF, 0x80000000] - res = run_op(0, 0xFFFFFFFF, accs_wrapping) - self.assertEqual(res[0], 1019) - self.assertEqual(res[1], 0) - self.assertEqual(res[2], 0x7FFFFFFF + 1020) - self.assertEqual(res[3], 0x80000000 + 1020) - - -class MqsadByteShiftingExtremesTests(unittest.TestCase): - """Selective matching, dword boundary crossings, and unused byte invariance.""" - - def test_sliding_window_offsets_selective_match(self): - target = 0x2468ACE0 - for target_offset in range(4): - s0 = (target << (8 * target_offset)) & M64 - res = run_op(s0, target, [0, 0, 0, 0]) - self.assertEqual(res[target_offset], 0) - for other in range(4): - if other != target_offset: - self.assertGreater(res[other], 0) - - def test_dword_boundary_crossing_windows(self): - s0 = 0x0807060504030201 - res = run_op(s0, 0x06050403, [0, 0, 0, 0]) - self.assertEqual(res[0], 2 + 2 + 2 + 2) - self.assertEqual(res[1], 1 + 1 + 1 + 1) - self.assertEqual(res[2], 0) - self.assertEqual(res[3], 1 + 1 + 1 + 1) - - def test_unused_byte_7_invariance(self): - base_s0 = 0x0007060504030201 - mutated_s0 = 0xFF07060504030201 - target = 0x04030201 - res_base_u32 = run_op(base_s0, target, [10, 20, 30, 40]) - res_mut_u32 = run_op(mutated_s0, target, [10, 20, 30, 40]) - self.assertEqual(res_base_u32, res_mut_u32) - - res_base_pk = run_op_pk_u16(base_s0, target, 0x0004000300020001) - res_mut_pk = run_op_pk_u16(mutated_s0, target, 0x0004000300020001) - self.assertEqual(res_base_pk, res_mut_pk) - - -class MqsadNegativeControlsTests(unittest.TestCase): - """Negative controls, operand validations, and semantic sensitivity.""" - - def test_clamp_modifier_rejection_all_forms(self): - with self.assertRaises(rdna2spirv.Unsupported): - run_lines(["v_mqsad_u32_u8 v[8:11], v[2:3], v1, v[4:7] clamp"]) - with self.assertRaises(rdna2spirv.Unsupported): - run_lines_pk_u16(["v_mqsad_pk_u16_u8 v[8:9], v[2:3], v1, v[4:5] clamp"]) - - def test_invalid_register_groupings_rejected(self): - with self.assertRaises(rdna2spirv.Unsupported): - run_lines(["v_mqsad_u32_u8 v[8:9], v[2:3], v1, v[4:7]"]) - with self.assertRaises(rdna2spirv.Unsupported): - run_lines(["v_mqsad_u32_u8 v8, v[2:3], v1, v[4:7]"]) - with self.assertRaises(rdna2spirv.Unsupported): - run_lines(["v_mqsad_u32_u8 v[8:11], v[2:3], v1, v[4:5]"]) - with self.assertRaises(rdna2spirv.Unsupported): - run_lines_pk_u16(["v_mqsad_pk_u16_u8 v[8:11], v[2:3], v1, v[4:5]"]) - with self.assertRaises(rdna2spirv.Unsupported): - run_lines_pk_u16(["v_mqsad_pk_u16_u8 v8, v[2:3], v1, v[4:5]"]) - with self.assertRaises(rdna2spirv.Unsupported): - run_lines_pk_u16(["v_mqsad_pk_u16_u8 v[8:9], v[2:3], v1, v[4:7]"]) - - def test_semantic_sensitivity_controls(self): - base_x = 0x0807060504030201 - base_y = 0x04030201 - base_acc = [0, 0, 0, 0] - base_res = run_op(base_x, base_y, base_acc) - - mutated_y = base_y ^ 0x00000001 - mutated_res_y = run_op(base_x, mutated_y, base_acc) - self.assertNotEqual(base_res, mutated_res_y) - - mutated_x = base_x ^ 0x0000000000000100 - mutated_res_x = run_op(mutated_x, base_y, base_acc) - self.assertNotEqual(base_res, mutated_res_x) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_alu_mul.py b/tests/semantic/test_alu_mul.py deleted file mode 100644 index f17b28089..000000000 --- a/tests/semantic/test_alu_mul.py +++ /dev/null @@ -1,423 +0,0 @@ -"""Semantic interpreter tests for AMD RDNA2 vector 32-bit integer multiplication instructions: - - v_mul_lo_u32: D = (S0 * S1) & 0xFFFFFFFF - - v_mul_hi_u32: D = ((u32(S0) * u32(S1)) >> 32) & 0xFFFFFFFF - - v_mul_hi_i32: D = ((i32(S0) * i32(S1)) >> 32) & 0xFFFFFFFF - -Standard library only. Tests: - * Reference semantic model for unsigned and signed 32-bit integer multiplication - * Mathematical identities: zero multiplier, unity multiplier, commutativity - * 64-bit product decomposition and full integer reconstruction from (lo, hi) halves - * Signed vs unsigned divergence on negative operands (e.g., -1 * -1, INT32_MIN * 2) - * Extreme boundary values: 0, 1, INT32_MAX, INT32_MIN, -1, -2, large unsigned words - * End-to-end SPIR-V translation via tools/rdna2spirv.py and execution via spirv_mini_interp - * Inline constant operands and opcode suffix aliases (_e32, _e64) - * Negative controls verifying detection of signedness, truncation, or arithmetic mutations -""" -from __future__ import annotations - -import gc -import itertools -import os -import struct -import sys -import tempfile -import unittest -import warnings - -HERE = os.path.dirname(os.path.abspath(__file__)) -ROOT = os.path.dirname(os.path.dirname(HERE)) -TOOLS_DIR = os.environ.get("LEONIDA_TOOLS_DIR") or os.path.join(ROOT, "tools") - -sys.dont_write_bytecode = True -sys.path.insert(0, TOOLS_DIR) -sys.path.insert(0, HERE) - -import rdna2spirv # noqa: E402 -import spirv_mini_interp as si # noqa: E402 - -MASK32 = 0xFFFFFFFF -SIGN32 = 0x80000000 -STUB_DXBC = b"DXBC" + bytes(24) + struct.pack(" int: - """Convert a 32-bit word into a signed Python integer (two's complement).""" - x &= MASK32 - return x - (1 << 32) if (x & SIGN32) else x - - -def u32(x: int) -> int: - """Mask a Python integer to 32 bits unsigned.""" - return x & MASK32 - - -def ref_mul_lo_u32(a: int, b: int) -> int: - """Low 32 bits of product. Identical for signed and unsigned integers modulo 2^32.""" - return (u32(a) * u32(b)) & MASK32 - - -def ref_mul_hi_u32(a: int, b: int) -> int: - """High 32 bits of unsigned 32-bit product.""" - return ((u32(a) * u32(b)) >> 32) & MASK32 - - -def ref_mul_hi_i32(a: int, b: int) -> int: - """High 32 bits of signed 32-bit product (two's complement representation).""" - return ((s32(a) * s32(b)) >> 32) & MASK32 - - -def ref_mul(op: str, a: int, b: int) -> int: - """Oracle lookup by instruction name.""" - base = op.split("_e")[0] if "_e" in op else op - if base == "v_mul_lo_u32": - return ref_mul_lo_u32(a, b) - elif base == "v_mul_hi_u32": - return ref_mul_hi_u32(a, b) - elif base == "v_mul_hi_i32": - return ref_mul_hi_i32(a, b) - raise ValueError(f"Unknown instruction {op}") - - -def ref_mul_64_u(a: int, b: int) -> tuple[int, int]: - """Returns (lo, hi_u) for 64-bit unsigned product.""" - return ref_mul_lo_u32(a, b), ref_mul_hi_u32(a, b) - - -def ref_mul_64_i(a: int, b: int) -> tuple[int, int]: - """Returns (lo, hi_i) for 64-bit signed product.""" - return ref_mul_lo_u32(a, b), ref_mul_hi_i32(a, b) - - -_TMP_DIR = None -_SRC_PATH = None - - -def setUpModule(): - global _TMP_DIR, _SRC_PATH - _TMP_DIR = tempfile.TemporaryDirectory() - disasm_dir = os.path.join(_TMP_DIR.name, "disasm") - os.mkdir(disasm_dir) - _SRC_PATH = os.path.join(disasm_dir, "ps_alu_mul.s") - with open(os.path.join(_TMP_DIR.name, "ps_alu_mul.dxbc"), "wb") as f: - f.write(STUB_DXBC) - - -def tearDownModule(): - global _TMP_DIR - if _TMP_DIR is not None: - gc.collect() - _TMP_DIR.cleanup() - _TMP_DIR = None - - -def run_mul_single(op: str, a: int, b: int, inline: tuple[int, ...] = ()) -> int: - """Run `op v0, src0, src1` and return result written to mrt0[0]. - - `inline` specifies which operand indices (0 for src0, 1 for src1) are passed - as inline/literal constants directly in the instruction text rather than preloaded into VGPRs. - """ - if _TMP_DIR is None: - setUpModule() - lines = [] - operands = [] - for i, val in enumerate((a, b)): - if i in inline: - operands.append(str(val)) - else: - reg = f"v{i + 1}" - lines.append(f"\tv_mov_b32 {reg}, {u32(val):#x}") - operands.append(reg) - - lines.append(f"\t{op} v0, {operands[0]}, {operands[1]}") - asm = "; test_alu_mul\n" + "\n".join(lines) + "\n\texp mrt0 v0, v0, v0, v0 done vm\n\ts_endpgm\n" - with open(_SRC_PATH, "w", encoding="utf-8") as f: - f.write(asm) - with warnings.catch_warnings(): - warnings.simplefilter("ignore", ResourceWarning) - spv = rdna2spirv.translate(_SRC_PATH) - gc.collect() - return si.run_fragment(spv)["%out_mrt0"][0] - - -def run_mul_pair(op_hi: str, a: int, b: int) -> tuple[int, int]: - """Run `v_mul_lo_u32 v0, v2, v3` and `{op_hi} v1, v2, v3` to test full 64-bit product export. - - Returns (v0, v1) corresponding to (lo, hi). - """ - if _TMP_DIR is None: - setUpModule() - lines = [ - f"\tv_mov_b32 v2, {u32(a):#x}", - f"\tv_mov_b32 v3, {u32(b):#x}", - "\tv_mul_lo_u32 v0, v2, v3", - f"\t{op_hi} v1, v2, v3", - ] - asm = "; test_alu_mul_pair\n" + "\n".join(lines) + "\n\texp mrt0 v0, v1, v0, v0 done vm\n\ts_endpgm\n" - with open(_SRC_PATH, "w", encoding="utf-8") as f: - f.write(asm) - with warnings.catch_warnings(): - warnings.simplefilter("ignore", ResourceWarning) - spv = rdna2spirv.translate(_SRC_PATH) - gc.collect() - out = si.run_fragment(spv)["%out_mrt0"] - return out[0], out[1] - - -SAMPLE_VALUES = ( - 0, - 1, - 2, - 3, - 7, - 10, - 16, - 64, - 100, - 0x10000, - 0x7FFFFFFF, - 0x80000000, - 0x80000001, - 0x7FFFFFFE, - 0xFFFFFFFF, - 0xFFFFFFFE, - 0x12345678, - 0x9ABCDEF0, -) - -SAMPLE_PAIRS = ( - (0, 0), - (0, 1), - (0, 0xFFFFFFFF), - (1, 1), - (1, 0xFFFFFFFF), - (2, 3), - (0x10000, 0x10000), - (0x7FFFFFFF, 0x7FFFFFFF), - (0x80000000, 0x80000000), - (0x80000000, 2), - (0x80000000, 0xFFFFFFFF), - (0xFFFFFFFF, 0xFFFFFFFF), - (0xFFFFFFFF, 5), - (0x12345678, 0x9ABCDEF0), - (0xAAAA5555, 0x5555AAAA), - (0x80000001, 0x7FFFFFFE), - (-16, 64), - (-100, 200), -) - - -class ReferenceModelTests(unittest.TestCase): - """Mathematical validation of reference models and hardware identities.""" - - def test_zero_property(self): - for val in SAMPLE_VALUES: - with self.subTest(val=hex(val)): - self.assertEqual(ref_mul_lo_u32(val, 0), 0) - self.assertEqual(ref_mul_lo_u32(0, val), 0) - self.assertEqual(ref_mul_hi_u32(val, 0), 0) - self.assertEqual(ref_mul_hi_u32(0, val), 0) - self.assertEqual(ref_mul_hi_i32(val, 0), 0) - self.assertEqual(ref_mul_hi_i32(0, val), 0) - - def test_unity_property(self): - for val in SAMPLE_VALUES: - with self.subTest(val=hex(val)): - self.assertEqual(ref_mul_lo_u32(val, 1), u32(val)) - self.assertEqual(ref_mul_lo_u32(1, val), u32(val)) - self.assertEqual(ref_mul_hi_u32(val, 1), 0) - self.assertEqual(ref_mul_hi_u32(1, val), 0) - expected_hi_i = 0xFFFFFFFF if s32(val) < 0 else 0 - self.assertEqual(ref_mul_hi_i32(val, 1), expected_hi_i) - self.assertEqual(ref_mul_hi_i32(1, val), expected_hi_i) - - def test_negation_identity(self): - for val in SAMPLE_VALUES: - with self.subTest(val=hex(val)): - self.assertEqual(ref_mul_lo_u32(val, -1), (-u32(val)) & MASK32) - self.assertEqual(ref_mul_lo_u32(val, 0xFFFFFFFF), (-u32(val)) & MASK32) - - def test_commutativity(self): - for a, b in SAMPLE_PAIRS: - with self.subTest(a=hex(a), b=hex(b)): - self.assertEqual(ref_mul_lo_u32(a, b), ref_mul_lo_u32(b, a)) - self.assertEqual(ref_mul_hi_u32(a, b), ref_mul_hi_u32(b, a)) - self.assertEqual(ref_mul_hi_i32(a, b), ref_mul_hi_i32(b, a)) - - def test_64bit_reconstruction(self): - for a, b in SAMPLE_PAIRS: - with self.subTest(a=hex(a), b=hex(b)): - # Unsigned reconstruction - lo_u, hi_u = ref_mul_64_u(a, b) - reconstructed_u = (hi_u << 32) | lo_u - self.assertEqual(reconstructed_u, u32(a) * u32(b)) - - # Signed reconstruction: sign-extend 32-bit hi word into 64-bit int - lo_i, hi_i = ref_mul_64_i(a, b) - hi_signed = s32(hi_i) - reconstructed_i = (hi_signed << 32) | lo_i - self.assertEqual(reconstructed_i, s32(a) * s32(b)) - - def test_hand_calculated_constants(self): - # 0xFFFFFFFF * 0xFFFFFFFF: - # unsigned: (2^32 - 1)^2 = 2^64 - 2*2^32 + 1 = (2^32 - 2) * 2^32 + 1 - # signed: (-1) * (-1) = 1 - self.assertEqual(ref_mul_lo_u32(0xFFFFFFFF, 0xFFFFFFFF), 1) - self.assertEqual(ref_mul_hi_u32(0xFFFFFFFF, 0xFFFFFFFF), 0xFFFFFFFE) - self.assertEqual(ref_mul_hi_i32(0xFFFFFFFF, 0xFFFFFFFF), 0) - - # 0x7FFFFFFF * 0x7FFFFFFF (INT32_MAX^2): - # (2^31 - 1)^2 = 2^62 - 2^32 + 1 = (2^30 - 1) * 2^32 + 1 - # 2^30 - 1 = 0x3FFFFFFF - self.assertEqual(ref_mul_lo_u32(0x7FFFFFFF, 0x7FFFFFFF), 1) - self.assertEqual(ref_mul_hi_u32(0x7FFFFFFF, 0x7FFFFFFF), 0x3FFFFFFF) - self.assertEqual(ref_mul_hi_i32(0x7FFFFFFF, 0x7FFFFFFF), 0x3FFFFFFF) - - # 0x80000000 * 0x80000000 (INT32_MIN^2): - # signed: (-2^31)^2 = 2^62 = 0x40000000 * 2^32 + 0 - # unsigned: (2^31)^2 = 2^62 = 0x40000000 * 2^32 + 0 - self.assertEqual(ref_mul_lo_u32(0x80000000, 0x80000000), 0) - self.assertEqual(ref_mul_hi_u32(0x80000000, 0x80000000), 0x40000000) - self.assertEqual(ref_mul_hi_i32(0x80000000, 0x80000000), 0x40000000) - - # 0x80000000 * 0xFFFFFFFF (INT32_MIN * -1): - # signed: (-2^31) * (-1) = 2^31 = 0x80000000 (hi = 0) - # unsigned: (2^31) * (2^32 - 1) = 2^63 - 2^31 = 0x7FFFFFFF * 2^32 + 0x80000000 - self.assertEqual(ref_mul_lo_u32(0x80000000, 0xFFFFFFFF), 0x80000000) - self.assertEqual(ref_mul_hi_u32(0x80000000, 0xFFFFFFFF), 0x7FFFFFFF) - self.assertEqual(ref_mul_hi_i32(0x80000000, 0xFFFFFFFF), 0) - - # 0x80000000 * 2 (INT32_MIN * 2): - # signed: (-2^31) * 2 = -2^32 = -1 * 2^32 + 0 (hi = -1 = 0xFFFFFFFF) - # unsigned: (2^31) * 2 = 2^32 = 1 * 2^32 + 0 (hi = 1) - self.assertEqual(ref_mul_lo_u32(0x80000000, 2), 0) - self.assertEqual(ref_mul_hi_u32(0x80000000, 2), 1) - self.assertEqual(ref_mul_hi_i32(0x80000000, 2), 0xFFFFFFFF) - - # 100 * -1: - # signed: -100 = 0xFFFFFFFF_FFFFFF9C - # unsigned: 100 * (2^32 - 1) = 99 * 2^32 + (2^32 - 100) = 0x00000063 * 2^32 + 0xFFFFFF9C - self.assertEqual(ref_mul_lo_u32(100, -1), 0xFFFFFF9C) - self.assertEqual(ref_mul_hi_u32(100, -1), 99) - self.assertEqual(ref_mul_hi_i32(100, -1), 0xFFFFFFFF) - - # 0x10000 * 0x10000 = 0x1_00000000: - self.assertEqual(ref_mul_lo_u32(0x10000, 0x10000), 0) - self.assertEqual(ref_mul_hi_u32(0x10000, 0x10000), 1) - self.assertEqual(ref_mul_hi_i32(0x10000, 0x10000), 1) - - -class AluMulTranslatorTests(unittest.TestCase): - """End-to-end interpreter tests of translated RDNA2 multiplication instructions.""" - - def test_sample_pairs_execution(self): - for op in OPS: - for a, b in SAMPLE_PAIRS: - with self.subTest(op=op, a=hex(a), b=hex(b)): - expected = ref_mul(op, a, b) - self.assertEqual(run_mul_single(op, a, b), expected) - # Commutativity verification on hardware translation - self.assertEqual(run_mul_single(op, b, a), expected) - - def test_inline_constants(self): - test_cases = [ - ("v_mul_lo_u32", 100, -1, 0xFFFFFF9C), - ("v_mul_hi_u32", 100, -1, 99), - ("v_mul_hi_i32", 100, -1, 0xFFFFFFFF), - ("v_mul_lo_u32", 0x7FFFFFFF, 2, 0xFFFFFFFE), - ("v_mul_hi_u32", 0x7FFFFFFF, 2, 0), - ("v_mul_hi_i32", 0x7FFFFFFF, 2, 0), - ("v_mul_lo_u32", -16, 64, (-1024) & MASK32), - ("v_mul_hi_u32", -16, 64, 63), - ("v_mul_hi_i32", -16, 64, 0xFFFFFFFF), - ] - for op, a, b, expected in test_cases: - with self.subTest(op=op, a=a, b=b, position="src1"): - # b passed as inline constant - self.assertEqual(run_mul_single(op, a, b, inline=(1,)), expected) - with self.subTest(op=op, a=a, b=b, position="src0"): - # a passed as inline constant - self.assertEqual(run_mul_single(op, a, b, inline=(0,)), expected) - - def test_instruction_suffix_aliases(self): - aliases = [ - ("v_mul_lo_u32_e32", "v_mul_lo_u32"), - ("v_mul_lo_u32_e64", "v_mul_lo_u32"), - ("v_mul_hi_u32_e32", "v_mul_hi_u32"), - ("v_mul_hi_i32_e32", "v_mul_hi_i32"), - ] - test_val_a = 0x12345678 - test_val_b = 0x00000002 - for alias, base_op in aliases: - with self.subTest(alias=alias): - expected = ref_mul(base_op, test_val_a, test_val_b) - self.assertEqual(run_mul_single(alias, test_val_a, test_val_b), expected) - - def test_combined_pair_reconstruction(self): - # Executes v_mul_lo and v_mul_hi in the same shader and compares exported words - pairs = [ - (0x12345678, 0x9ABCDEF0), - (0xFFFFFFFF, 0xFFFFFFFF), - (0x80000000, 2), - (100, -1), - ] - for a, b in pairs: - with self.subTest(pair="unsigned", a=hex(a), b=hex(b)): - got = run_mul_pair("v_mul_hi_u32", a, b) - expected = ref_mul_64_u(a, b) - self.assertEqual(got, expected) - - with self.subTest(pair="signed", a=hex(a), b=hex(b)): - got = run_mul_pair("v_mul_hi_i32", a, b) - expected = ref_mul_64_i(a, b) - self.assertEqual(got, expected) - - -class NegativeControlsTests(unittest.TestCase): - """Negative controls ensuring mutated arithmetic or signedness confusion are caught.""" - - def test_signed_vs_unsigned_hi_divergence_detected(self): - divergent_pairs = [ - (0xFFFFFFFF, 0xFFFFFFFF), - (0xFFFFFFFF, 5), - (0x80000000, 2), - (100, -1), - (-16, 64), - ] - for a, b in divergent_pairs: - with self.subTest(a=hex(a), b=hex(b)): - hi_u = ref_mul_hi_u32(a, b) - hi_i = ref_mul_hi_i32(a, b) - self.assertNotEqual(hi_u, hi_i, f"Expected divergence between unsigned and signed hi for ({a}, {b})") - - def test_low_vs_high_word_divergence_detected(self): - divergent_pairs = [ - (0x10000, 0x10000), - (0xFFFFFFFF, 0xFFFFFFFF), - (0x80000000, 0x80000000), - ] - for a, b in divergent_pairs: - with self.subTest(a=hex(a), b=hex(b)): - lo = ref_mul_lo_u32(a, b) - hi_u = ref_mul_hi_u32(a, b) - self.assertNotEqual(lo, hi_u, f"Expected divergence between lo and hi for ({a}, {b})") - - def test_sabotaged_shift_count_detected(self): - a = 0x12345678 - b = 0x9ABCDEF0 - correct_hi_u = ref_mul_hi_u32(a, b) - sabotaged_hi_u = ((u32(a) * u32(b)) >> 31) & MASK32 - self.assertNotEqual(correct_hi_u, sabotaged_hi_u) - - def test_dropped_sign_extension_detected(self): - a = -100 - b = 200 - correct_hi_i = ref_mul_hi_i32(a, b) - # Dropped sign extension: treating signed product as unsigned before shift - sabotaged_hi_i = ((u32(a) * u32(b)) >> 32) & MASK32 - self.assertNotEqual(correct_hi_i, sabotaged_hi_i) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_alu_mul_hi_24.py b/tests/semantic/test_alu_mul_hi_24.py deleted file mode 100644 index d1fb8187b..000000000 --- a/tests/semantic/test_alu_mul_hi_24.py +++ /dev/null @@ -1,119 +0,0 @@ -"""Semantic interpreter tests for RDNA2 v_mul_hi_u32_u24 and v_mul_hi_i32_i24. - -Both multiply the low 24 bits of each source into a 48-bit product and return its high 32 bits (bits 32-47, so at -most 16 significant bits): v_mul_hi_u32_u24 zero-extends the operands, v_mul_hi_i32_i24 sign-extends them from -bit 23 and the result is the signed high word. Bits 24-31 of the sources are ignored. The low words are -v_mul_u32_u24 / v_mul_i32_i24, so the pair must give back the whole product. Each case translates a synthetic -pixel shader with tools/rdna2spirv.py, runs it in tests/semantic/spirv_mini_interp.py and compares the exported -words with a plain-Python reference. -""" -import os -import random -import struct -import sys -import tempfile -import unittest -import warnings - -HERE = os.path.dirname(os.path.abspath(__file__)) -ROOT = os.path.dirname(os.path.dirname(HERE)) -TOOLS_DIR = os.environ.get("LEONIDA_TOOLS_DIR") or os.path.join(ROOT, "tools") - -sys.dont_write_bytecode = True -sys.path.insert(0, TOOLS_DIR) -sys.path.insert(0, HERE) - -import rdna2spirv # noqa: E402 -import spirv_mini_interp as si # noqa: E402 - -MASK32 = 0xFFFFFFFF -STUB_DXBC = b"DXBC" + bytes(24) + struct.pack(" int: - return x & 0xFFFFFF - - -def i24(x: int) -> int: - x &= 0xFFFFFF - return x - (1 << 24) if x >> 23 else x - - -def ref(op: str, x: int, y: int) -> int: - p = u24(x) * u24(y) if op == "v_mul_hi_u32_u24" else i24(x) * i24(y) - return (p >> 32) & MASK32 - - -_TMP_DIR = None -_SRC_PATH = None - - -def setUpModule(): - global _TMP_DIR, _SRC_PATH - _TMP_DIR = tempfile.TemporaryDirectory() - disasm_dir = os.path.join(_TMP_DIR.name, "disasm") - os.mkdir(disasm_dir) - _SRC_PATH = os.path.join(disasm_dir, "ps_mul_hi_24.s") - with open(os.path.join(_TMP_DIR.name, "ps_mul_hi_24.dxbc"), "wb") as f: - f.write(STUB_DXBC) - - -def tearDownModule(): - global _TMP_DIR - if _TMP_DIR is not None: - _TMP_DIR.cleanup() - _TMP_DIR = None - - -def run_lines(lines) -> tuple: - """Run the lines, export v0 and v1, return those two words.""" - if _TMP_DIR is None: - setUpModule() - asm = "; test_mul_hi_24\n" + "".join(f"\t{ln}\n" for ln in lines) + "\texp mrt0 v0, v1, v0, v0 done vm\n\ts_endpgm\n" - with open(_SRC_PATH, "w", encoding="utf-8") as f: - f.write(asm) - with warnings.catch_warnings(): - warnings.simplefilter("ignore", ResourceWarning) - spv = rdna2spirv.translate(_SRC_PATH) - return tuple(si.run_fragment(spv)["%out_mrt0"][:2]) - - -def hi_lo(op: str, x: int, y: int) -> tuple: - lo_op = "v_mul_u32_u24" if op == "v_mul_hi_u32_u24" else "v_mul_i32_i24" - return run_lines([f"v_mov_b32 v2, {x:#x}", f"v_mov_b32 v3, {y:#x}", f"{op} v1, v2, v3", f"{lo_op}_e32 v0, v2, v3"]) - - -class MulHi24Tests(unittest.TestCase): - def test_reference(self): - self.assertEqual(ref("v_mul_hi_u32_u24", 0xFFFFFF, 0xFFFFFF), 0xFFFF) # (2^24-1)^2 >> 32 - self.assertEqual(ref("v_mul_hi_i32_i24", 0xFFFFFF, 0x7FFFFF), 0xFFFFFFFF) # -1 * (2^23-1): high word -1 - self.assertEqual(ref("v_mul_hi_i32_i24", 0x800000, 0x800000), 0x4000) # (-2^23)^2 = 2^46 - self.assertEqual(ref("v_mul_hi_u32_u24", 0xFF000001, 0xFF000001), 0) # bits 24-31 ignored - - def test_edge_values(self): - for op in ("v_mul_hi_u32_u24", "v_mul_hi_i32_i24"): - for x in VALUES: - for y in VALUES[::3]: - with self.subTest(op=op, x=hex(x), y=hex(y)): - self.assertEqual(hi_lo(op, x, y)[1], ref(op, x, y)) - - def test_hi_and_lo_give_the_whole_product(self): - rng = random.Random(24) - for op in ("v_mul_hi_u32_u24", "v_mul_hi_i32_i24"): - for _ in range(25): - x, y = rng.getrandbits(32), rng.getrandbits(32) - with self.subTest(op=op, x=hex(x), y=hex(y)): - lo, hi = hi_lo(op, x, y) - want = u24(x) * u24(y) if op == "v_mul_hi_u32_u24" else i24(x) * i24(y) - self.assertEqual(hi << 32 | lo, want & 0xFFFFFFFFFFFFFFFF) - - def test_vop3_form_with_scalar_and_inline_operands(self): - got = run_lines(["s_mov_b32 s2, 0xfff000", "v_mov_b32 v2, 0x800001", - "v_mul_hi_i32_i24_e64 v1, s2, v2", "v_mul_hi_u32_u24_e64 v0, -1, v2"]) - self.assertEqual(got, (ref("v_mul_hi_u32_u24", MASK32, 0x800001), ref("v_mul_hi_i32_i24", 0xFFF000, 0x800001))) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_alu_mul_lo_i32.py b/tests/semantic/test_alu_mul_lo_i32.py deleted file mode 100644 index e410475c3..000000000 --- a/tests/semantic/test_alu_mul_lo_i32.py +++ /dev/null @@ -1,933 +0,0 @@ -"""Semantic interpreter tests for AMD RDNA2 vector 32-bit integer low multiplication: - - v_mul_lo_u32: D.u32 = (S0.u32 * S1.u32) & 0xFFFFFFFF - -In two's complement binary arithmetic, the low 32 bits of 32-bit integer multiplication -are mathematically identical regardless of whether operands are treated as signed (i32) -or unsigned (u32), because (a * b) mod 2^32 is isomorphic across signed and unsigned -representations. RDNA2 therefore implements both signed and unsigned 32-bit low-dword -multiplication with the single VALU instruction v_mul_lo_u32, translated to SPIR-V OpIMul. - -Standard library only. No game assets, archives, or shaders. -""" -from __future__ import annotations - -import gc -import os -import random -import struct -import sys -import tempfile -import unittest -import warnings - -HERE = os.path.dirname(os.path.abspath(__file__)) -ROOT = os.path.dirname(os.path.dirname(HERE)) -TOOLS_DIR = os.environ.get("LEONIDA_TOOLS_DIR") or os.path.join(ROOT, "tools") - -sys.dont_write_bytecode = True -if TOOLS_DIR not in sys.path: - sys.path.insert(0, TOOLS_DIR) -if HERE not in sys.path: - sys.path.insert(0, HERE) - -import rdna2spirv # noqa: E402 -import spirv_mini_interp as si # noqa: E402 - -MASK32 = 0xFFFFFFFF -SIGN32 = 0x80000000 -MASK64 = 0xFFFFFFFFFFFFFFFF -STUB_DXBC = b"DXBC" + bytes(24) + struct.pack(" int: - """Mask integer to 32 bits unsigned.""" - return x & MASK32 - - -def s32(x: int) -> int: - """Convert integer to 32-bit signed two's complement integer.""" - val = x & MASK32 - return val - (1 << 32) if (val & SIGN32) else val - - -def ref_mul_lo_u32(a: int, b: int) -> int: - """Reference oracle for v_mul_lo_u32: (u32(a) * u32(b)) & 0xFFFFFFFF.""" - return (u32(a) * u32(b)) & MASK32 - - -def ref_mul_lo_i32(a: int, b: int) -> int: - """Signed reference for low 32-bit multiplication: (s32(a) * s32(b)) & 0xFFFFFFFF.""" - return (s32(a) * s32(b)) & MASK32 - - -def ref_mul_64(a: int, b: int, signed: bool = False) -> tuple[int, int]: - """Returns (lo, hi) halves of full 64-bit product.""" - if signed: - prod = s32(a) * s32(b) - prod_u = prod & MASK64 - else: - prod_u = (u32(a) * u32(b)) & MASK64 - return prod_u & MASK32, (prod_u >> 32) & MASK32 - - -class VectorALUMulInterpreter: - """Deterministic multi-lane SIMD interpreter modeling AMD RDNA2 VALU execution.""" - - def __init__(self, num_vgprs: int = 64, num_sgprs: int = 106, wave_size: int = 64): - self.num_vgprs = num_vgprs - self.num_sgprs = num_sgprs - self.wave_size = wave_size - self.vgprs = [[0] * wave_size for _ in range(num_vgprs)] - self.sgprs = [0] * num_sgprs - self.exec_mask = (1 << wave_size) - 1 - - def reset(self) -> None: - self.vgprs = [[0] * self.wave_size for _ in range(self.num_vgprs)] - self.sgprs = [0] * self.num_sgprs - self.exec_mask = (1 << self.wave_size) - 1 - - def set_vgpr(self, reg_idx: int, lane: int, val: int) -> None: - self.vgprs[reg_idx][lane] = val & MASK32 - - def get_vgpr(self, reg_idx: int, lane: int) -> int: - return self.vgprs[reg_idx][lane] & MASK32 - - def set_sgpr(self, reg_idx: int, val: int) -> None: - self.sgprs[reg_idx] = val & MASK32 - - def get_sgpr(self, reg_idx: int) -> int: - return self.sgprs[reg_idx] & MASK32 - - def set_exec(self, mask: int) -> None: - self.exec_mask = mask & ((1 << self.wave_size) - 1) - - def resolve_src(self, op: str | int, lane: int) -> int: - if isinstance(op, int): - return op & MASK32 - op_str = op.strip().lower() - if op_str.startswith("v"): - return self.vgprs[int(op_str[1:])][lane] & MASK32 - if op_str.startswith("s"): - return self.sgprs[int(op_str[1:])] & MASK32 - return int(op_str, 0) & MASK32 - - def execute_v_mul_lo_u32(self, dst_idx: int, src0: str | int, src1: str | int) -> None: - for lane in range(self.wave_size): - if (self.exec_mask >> lane) & 1: - s0 = self.resolve_src(src0, lane) - s1 = self.resolve_src(src1, lane) - self.vgprs[dst_idx][lane] = ref_mul_lo_u32(s0, s1) - - -_TMP_DIR: tempfile.TemporaryDirectory | None = None -_SRC_PATH: str | None = None -_CS_PATH: str | None = None -_CS_FSSM: str | None = None - - -def _make_fssm(rsrc2: int, group: tuple[int, int, int]) -> bytes: - header = bytearray(0x148) - struct.pack_into("<4I", header, 0x138, rsrc2, *group) - return bytes(header) - - -def setUpModule() -> None: - global _TMP_DIR, _SRC_PATH, _CS_PATH, _CS_FSSM - _TMP_DIR = tempfile.TemporaryDirectory() - disasm_dir = os.path.join(_TMP_DIR.name, "disasm") - fssm_dir = os.path.join(_TMP_DIR.name, "fssm") - os.mkdir(disasm_dir) - os.mkdir(fssm_dir) - _SRC_PATH = os.path.join(disasm_dir, "ps_mul_lo.s") - _CS_PATH = os.path.join(disasm_dir, "cs_mul_lo.s") - _CS_FSSM = os.path.join(fssm_dir, "cs_mul_lo.fssm") - with open(os.path.join(_TMP_DIR.name, "ps_mul_lo.dxbc"), "wb") as f: - f.write(STUB_DXBC) - with open(os.path.join(_TMP_DIR.name, "cs_mul_lo.dxbc"), "wb") as f: - f.write(STUB_DXBC) - - -def tearDownModule() -> None: - global _TMP_DIR, _SRC_PATH, _CS_PATH, _CS_FSSM - if _TMP_DIR is not None: - gc.collect() - _TMP_DIR.cleanup() - _TMP_DIR = None - _SRC_PATH = None - _CS_PATH = None - _CS_FSSM = None - - -def run_mul_lo_shader( - a: int, - b: int, - op: str = "v_mul_lo_u32", - inline_s0: bool = False, - inline_s1: bool = False, - s0_is_sgpr: bool = False, -) -> int: - """Run `op v0, s0/v1, v2` and return the 32-bit word written to mrt0[0].""" - if _TMP_DIR is None: - setUpModule() - lines = [] - if s0_is_sgpr: - lines.append(f"\ts_mov_b32 s0, {u32(a):#x}") - op0 = "s0" - elif inline_s0: - op0 = f"{u32(a):#x}" - else: - lines.append(f"\tv_mov_b32 v1, {u32(a):#x}") - op0 = "v1" - - if inline_s1: - op1 = f"{u32(b):#x}" - else: - lines.append(f"\tv_mov_b32 v2, {u32(b):#x}") - op1 = "v2" - - lines.append(f"\t{op} v0, {op0}, {op1}") - asm = ( - "; test_alu_mul_lo_i32\n" - + "\n".join(lines) - + "\n\texp mrt0 v0, v0, v0, v0 done vm\n\ts_endpgm\n" - ) - with open(_SRC_PATH, "w", encoding="utf-8") as f: - f.write(asm) - with warnings.catch_warnings(): - warnings.simplefilter("ignore", ResourceWarning) - spv = rdna2spirv.translate(_SRC_PATH) - gc.collect() - return si.run_fragment(spv)["%out_mrt0"][0] - - -def run_mul_lo_cs( - multiplier: int, - wave_size: int = 64, -) -> dict[int, int]: - """Run a multi-lane compute shader where each lane multiplies its lane index by `multiplier`.""" - if _TMP_DIR is None: - setUpModule() - with open(_CS_FSSM, "wb") as f: - f.write(_make_fssm(0x8088, (wave_size, 1, 1))) - - lines = [ - f"\ts_mov_b32 s4, {u32(multiplier):#x}", - "\tv_mul_lo_u32 v1, v0, s4", - "\tv_lshlrev_b32_e32 v2, 2, v0", - "\tbuffer_store_dword v1, v2, s[0:3], 0 offen", - "\ts_endpgm", - ] - asm = "; test_mul_lo_cs\n" + "\n".join(lines) + "\n" - with open(_CS_PATH, "w", encoding="utf-8") as f: - f.write(asm) - with warnings.catch_warnings(): - warnings.simplefilter("ignore", ResourceWarning) - spv = rdna2spirv.translate(_CS_PATH) - gc.collect() - - pc = VSHARP + [0] * 28 - return si.run_workgroup( - spv, - wave_size, - wave_size, - inputs_for=lambda i: {"%wg_id": (0, 0, 0), "%local_id": (i, 0, 0), "%sg_lane": i}, - push_constants=pc, - memory={}, - ) - - -def run_spirv_imul(a: int, b: int) -> int: - """Direct execution of SPIR-V OpIMul instruction in spirv_mini_interp.""" - module = f"""\ -OpCapability Shader -%glsl = OpExtInstImport "GLSL.std.450" -OpMemoryModel Logical GLSL450 -OpEntryPoint Fragment %main "main" %out -%void = OpTypeVoid -%fn = OpTypeFunction %void -%uint = OpTypeInt 32 0 -%_ptr_Output_uint = OpTypePointer Output %uint -%out = OpVariable %_ptr_Output_uint Output -%ca = OpConstant %uint {u32(a)} -%cb = OpConstant %uint {u32(b)} -%main = OpFunction %void None %fn -%entry = OpLabel -%res = OpIMul %uint %ca %cb -OpStore %out %res -OpReturn -OpFunctionEnd -""" - return si.run_fragment(module)["%out"][0] - - -class TestMulLoReferenceOracle(unittest.TestCase): - """Mathematical validation of 32-bit integer low multiplication reference oracle.""" - - def test_zero_multiplier(self) -> None: - """Any 32-bit integer multiplied by 0 equals 0.""" - for val in SAMPLE_VALUES: - with self.subTest(val=hex(val)): - self.assertEqual(ref_mul_lo_u32(val, 0), 0) - self.assertEqual(ref_mul_lo_u32(0, val), 0) - self.assertEqual(ref_mul_lo_i32(val, 0), 0) - self.assertEqual(ref_mul_lo_i32(0, val), 0) - - def test_unity_multiplier(self) -> None: - """Any 32-bit integer multiplied by 1 preserves its value.""" - for val in SAMPLE_VALUES: - with self.subTest(val=hex(val)): - self.assertEqual(ref_mul_lo_u32(val, 1), u32(val)) - self.assertEqual(ref_mul_lo_u32(1, val), u32(val)) - self.assertEqual(ref_mul_lo_i32(val, 1), u32(val)) - self.assertEqual(ref_mul_lo_i32(1, val), u32(val)) - - def test_negation_identity(self) -> None: - """Multiplying by -1 (0xFFFFFFFF) yields two's complement negation modulo 2^32.""" - for val in SAMPLE_VALUES: - with self.subTest(val=hex(val)): - expected = (-u32(val)) & MASK32 - self.assertEqual(ref_mul_lo_u32(val, -1), expected) - self.assertEqual(ref_mul_lo_u32(val, 0xFFFFFFFF), expected) - self.assertEqual(ref_mul_lo_i32(val, -1), expected) - self.assertEqual(ref_mul_lo_i32(val, 0xFFFFFFFF), expected) - - def test_commutativity(self) -> None: - """Low multiplication is commutative: a * b == b * a.""" - for a, b in SAMPLE_PAIRS: - with self.subTest(a=hex(a), b=hex(b)): - self.assertEqual(ref_mul_lo_u32(a, b), ref_mul_lo_u32(b, a)) - self.assertEqual(ref_mul_lo_i32(a, b), ref_mul_lo_i32(b, a)) - - def test_associativity_mod32(self) -> None: - """Low multiplication is associative modulo 2^32: (a * b) * c == a * (b * c).""" - triplets = [ - (3, 5, 7), - (100, 200, 300), - (0x1000, 0x100, 0x10), - (0x12345678, 3, 5), - (0x7FFFFFFF, 2, 4), - (0xFFFFFFFF, 2, 3), - (0x80000001, 0x10001, 7), - ] - for a, b, c in triplets: - with self.subTest(a=hex(a), b=hex(b), c=hex(c)): - left = ref_mul_lo_u32(ref_mul_lo_u32(a, b), c) - right = ref_mul_lo_u32(a, ref_mul_lo_u32(b, c)) - self.assertEqual(left, right) - - def test_distributivity_over_addition(self) -> None: - """Low multiplication distributes over addition modulo 2^32: a * (b + c) == a * b + a * c.""" - triplets = [ - (5, 12, 18), - (0x1000, 0x2000, 0x3000), - (0xFFFFFFFF, 1, 1), - (0x7FFFFFFF, 0x80000000, 1), - (0x12345678, 0x9ABCDEF0, 0x55555555), - ] - for a, b, c in triplets: - with self.subTest(a=hex(a), b=hex(b), c=hex(c)): - sum_bc = (b + c) & MASK32 - prod_distributed = (ref_mul_lo_u32(a, b) + ref_mul_lo_u32(a, c)) & MASK32 - self.assertEqual(ref_mul_lo_u32(a, sum_bc), prod_distributed) - - def test_power_of_two_shift_equivalence(self) -> None: - """Multiplication by 2^k is equivalent to left shift by k modulo 2^32.""" - for val in (1, 3, 7, 42, 0x12345678, 0x80000001, 0xFFFFFFFF): - for k in range(32): - with self.subTest(val=hex(val), shift=k): - multiplier = 1 << k - expected = (u32(val) << k) & MASK32 - self.assertEqual(ref_mul_lo_u32(val, multiplier), expected) - - def test_hand_calculated_constants(self) -> None: - """Rigorous validation against hand-calculated boundary results.""" - cases = [ - (0, 0, 0), - (1, 1, 1), - (0xFFFFFFFF, 0xFFFFFFFF, 1), - (0x7FFFFFFF, 2, 0xFFFFFFFE), - (0x80000000, 2, 0), - (0x80000000, 0x80000000, 0), - (0x80000000, 0xFFFFFFFF, 0x80000000), - (0x10000, 0x10000, 0), - (0x10001, 0x10001, 0x00020001), - (100, -1, 0xFFFFFF9C), - (100, 0xFFFFFFFF, 0xFFFFFF9C), - (0x12345678, 2, 0x2468ACF0), - ] - for a, b, expected in cases: - with self.subTest(a=hex(a), b=hex(b), expected=hex(expected)): - self.assertEqual(ref_mul_lo_u32(a, b), expected) - self.assertEqual(ref_mul_lo_i32(a, b), expected) - - -class TestMulLoTranslator(unittest.TestCase): - """End-to-end tests translating RDNA2 v_mul_lo_u32 and executing in spirv_mini_interp.""" - - def test_basic_execution(self) -> None: - """Test v_mul_lo_u32 shader execution against the reference oracle.""" - test_pairs = [ - (0, 0), - (1, 1), - (2, 3), - (10, 20), - (0x10000, 0x10000), - (0x7FFFFFFF, 2), - (0x80000000, 2), - (0xFFFFFFFF, 0xFFFFFFFF), - (0x12345678, 0x9ABCDEF0), - (100, -1), - ] - for a, b in test_pairs: - with self.subTest(a=hex(a), b=hex(b)): - expected = ref_mul_lo_u32(a, b) - self.assertEqual(run_mul_lo_shader(a, b), expected) - self.assertEqual(run_mul_lo_shader(b, a), expected) - - def test_inline_constants(self) -> None: - """Test inline constants in src0 and src1 positions.""" - test_cases = [ - (5, 7, 35), - (100, -1, 0xFFFFFF9C), - (0x7FFFFFFF, 2, 0xFFFFFFFE), - (0x80000000, 2, 0), - (0xFFFFFFFF, 5, (-5) & MASK32), - ] - for a, b, expected in test_cases: - with self.subTest(a=a, b=b, pos="src1"): - self.assertEqual(run_mul_lo_shader(a, b, inline_s1=True), expected) - with self.subTest(a=a, b=b, pos="src0"): - self.assertEqual(run_mul_lo_shader(a, b, inline_s0=True), expected) - - def test_sgpr_scalar_source(self) -> None: - """Test mixed scalar SGPR and vector VGPR inputs.""" - test_cases = [ - (42, 10, 420), - (0x1234, 0x5678, ref_mul_lo_u32(0x1234, 0x5678)), - (0x80000000, 2, 0), - (0xFFFFFFFF, 0xFFFFFFFF, 1), - ] - for s0_val, v1_val, expected in test_cases: - with self.subTest(s0=hex(s0_val), v1=hex(v1_val)): - got = run_mul_lo_shader(s0_val, v1_val, s0_is_sgpr=True) - self.assertEqual(got, expected) - - def test_opcode_aliases(self) -> None: - """Test opcode aliases v_mul_lo_u32_e32 and v_mul_lo_u32_e64.""" - aliases = ("v_mul_lo_u32", "v_mul_lo_u32_e32", "v_mul_lo_u32_e64") - a = 0x12345678 - b = 0x00000002 - expected = ref_mul_lo_u32(a, b) - for op in aliases: - with self.subTest(op=op): - self.assertEqual(run_mul_lo_shader(a, b, op=op), expected) - - def test_spirv_lowering_instruction(self) -> None: - """Verifies that rdna2spirv emits OpIMul %uint for v_mul_lo_u32.""" - if _TMP_DIR is None: - setUpModule() - lines = [ - "\tv_mov_b32 v1, 15", - "\tv_mov_b32 v2, 4", - "\tv_mul_lo_u32 v0, v1, v2", - "\texp mrt0 v0, v0, v0, v0 done vm", - "\ts_endpgm", - ] - asm = "; test_spirv_lowering\n" + "\n".join(lines) + "\n" - with open(_SRC_PATH, "w", encoding="utf-8") as f: - f.write(asm) - with warnings.catch_warnings(): - warnings.simplefilter("ignore", ResourceWarning) - spv = rdna2spirv.translate(_SRC_PATH) - self.assertIn("OpIMul %uint", spv) - - def test_spirv_direct_imul(self) -> None: - """Direct execution of OpIMul in SPIR-V interpreter matches reference.""" - for a, b in SAMPLE_PAIRS: - with self.subTest(a=hex(a), b=hex(b)): - self.assertEqual(run_spirv_imul(a, b), ref_mul_lo_u32(a, b)) - - -class TestMulLoSIMDDivergence(unittest.TestCase): - """Multi-lane SIMD execution and divergence tests for v_mul_lo_u32.""" - - def test_simd_independent_lanes(self) -> None: - """All 64 lanes evaluate distinct, divergent multiplications concurrently.""" - interp = VectorALUMulInterpreter(wave_size=64) - for lane in range(64): - interp.set_vgpr(1, lane, lane * 17 + 3) - interp.set_vgpr(2, lane, 0x10001 + lane * 5) - - interp.execute_v_mul_lo_u32(0, "v1", "v2") - - for lane in range(64): - s0 = lane * 17 + 3 - s1 = 0x10001 + lane * 5 - expected = ref_mul_lo_u32(s0, s1) - self.assertEqual(interp.get_vgpr(0, lane), expected) - - def test_simd_exec_mask_even_odd_gating(self) -> None: - """Inactive EXEC lanes preserve their prior VGPR contents unchanged.""" - interp = VectorALUMulInterpreter(wave_size=64) - sentinel = 0xDEADBEEF - - for lane in range(64): - interp.set_vgpr(0, lane, sentinel) - interp.set_vgpr(1, lane, lane) - interp.set_vgpr(2, lane, 10) - - # Alternating even lanes active: 0x5555555555555555 - interp.set_exec(0x5555555555555555) - interp.execute_v_mul_lo_u32(0, "v1", "v2") - - for lane in range(64): - if lane % 2 == 0: - self.assertEqual(interp.get_vgpr(0, lane), lane * 10) - else: - self.assertEqual(interp.get_vgpr(0, lane), sentinel) - - def test_simd_exec_mask_half_wave_divergence(self) -> None: - """First 32 lanes active, last 32 lanes inactive (wave32 sub-execution).""" - interp = VectorALUMulInterpreter(wave_size=64) - sentinel = 0xCAFEBABE - - for lane in range(64): - interp.set_vgpr(0, lane, sentinel) - interp.set_vgpr(1, lane, 0x1234) - interp.set_vgpr(2, lane, lane + 1) - - interp.set_exec(0x00000000FFFFFFFF) - interp.execute_v_mul_lo_u32(0, "v1", "v2") - - for lane in range(64): - if lane < 32: - expected = ref_mul_lo_u32(0x1234, lane + 1) - self.assertEqual(interp.get_vgpr(0, lane), expected) - else: - self.assertEqual(interp.get_vgpr(0, lane), sentinel) - - def test_simd_exec_mask_single_lane(self) -> None: - """Exactly one divergent lane active in wave.""" - interp = VectorALUMulInterpreter(wave_size=64) - target_lane = 42 - - for lane in range(64): - interp.set_vgpr(0, lane, 0) - interp.set_vgpr(1, lane, 1000) - interp.set_vgpr(2, lane, 3) - - interp.set_exec(1 << target_lane) - interp.execute_v_mul_lo_u32(0, "v1", "v2") - - for lane in range(64): - if lane == target_lane: - self.assertEqual(interp.get_vgpr(0, lane), 3000) - else: - self.assertEqual(interp.get_vgpr(0, lane), 0) - - def test_simd_exec_mask_contiguous_slice(self) -> None: - """Contiguous sub-range of active lanes [16, 48).""" - interp = VectorALUMulInterpreter(wave_size=64) - for lane in range(64): - interp.set_vgpr(0, lane, 0x77777777) - interp.set_vgpr(1, lane, lane) - interp.set_vgpr(2, lane, 0x80000001) - - mask = ((1 << 32) - 1) << 16 - interp.set_exec(mask) - interp.execute_v_mul_lo_u32(0, "v1", "v2") - - for lane in range(64): - if 16 <= lane < 48: - expected = ref_mul_lo_u32(lane, 0x80000001) - self.assertEqual(interp.get_vgpr(0, lane), expected) - else: - self.assertEqual(interp.get_vgpr(0, lane), 0x77777777) - - def test_simd_sgpr_scalar_broadcast(self) -> None: - """Scalar SGPR multiplier broadcast across all active lanes.""" - interp = VectorALUMulInterpreter(wave_size=64) - scalar_val = 0x10001 - interp.set_sgpr(5, scalar_val) - - for lane in range(64): - interp.set_vgpr(1, lane, lane * 256) - - interp.execute_v_mul_lo_u32(0, "s5", "v1") - - for lane in range(64): - expected = ref_mul_lo_u32(scalar_val, lane * 256) - self.assertEqual(interp.get_vgpr(0, lane), expected) - - def test_simd_inline_constant_broadcast(self) -> None: - """Inline constant broadcast across divergent lanes.""" - interp = VectorALUMulInterpreter(wave_size=64) - for lane in range(64): - interp.set_vgpr(1, lane, 0x80000000 + lane) - - interp.execute_v_mul_lo_u32(0, 3, "v1") - - for lane in range(64): - expected = ref_mul_lo_u32(3, 0x80000000 + lane) - self.assertEqual(interp.get_vgpr(0, lane), expected) - - def test_simd_spirv_workgroup_wave32(self) -> None: - """Multi-lane execution of v_mul_lo_u32 in a 32-lane wave via run_workgroup.""" - multiplier = 0x10003 - mem = run_mul_lo_cs(multiplier, wave_size=32) - for lane in range(32): - expected = ref_mul_lo_u32(lane, multiplier) - self.assertEqual(mem[lane * 4], expected, f"Wave32 lane {lane}") - - def test_simd_spirv_workgroup_wave64(self) -> None: - """Multi-lane execution of v_mul_lo_u32 in a 64-lane wave via run_workgroup.""" - multiplier = 0x7FFFFFFF - mem = run_mul_lo_cs(multiplier, wave_size=64) - for lane in range(64): - expected = ref_mul_lo_u32(lane, multiplier) - self.assertEqual(mem[lane * 4], expected, f"Wave64 lane {lane}") - - -class TestMulLoOverflowWrapping(unittest.TestCase): - """Exhaustive 32-bit overflow wrapping and modulo 2^32 truncation tests.""" - - def test_overflow_wrap_boundary_products(self) -> None: - """Boundary products wrapping cleanly modulo 2^32.""" - cases = [ - # 0xFFFFFFFF * 2 = 2^33 - 2 -> 0xFFFFFFFE - (0xFFFFFFFF, 2, 0xFFFFFFFE), - # 0xFFFFFFFF * 3 = 3 * 2^32 - 3 -> 0xFFFFFFFD - (0xFFFFFFFF, 3, 0xFFFFFFFD), - # 0xFFFFFFFF * 0xFFFFFFFF = 2^64 - 2*2^32 + 1 -> 1 - (0xFFFFFFFF, 0xFFFFFFFF, 1), - # 0x80000000 * 2 = 2^32 -> 0 - (0x80000000, 2, 0), - # 0x80000000 * 3 = 2^32 + 2^31 -> 0x80000000 - (0x80000000, 3, 0x80000000), - # 0x80000000 * 4 = 2^33 -> 0 - (0x80000000, 4, 0), - # 0x80000000 * 0x80000000 = 2^62 -> 0 - (0x80000000, 0x80000000, 0), - # 0x7FFFFFFF * 0x7FFFFFFF = (2^31 - 1)^2 = 2^62 - 2^32 + 1 -> 1 - (0x7FFFFFFF, 0x7FFFFFFF, 1), - # 0x7FFFFFFF * 2 = 2^32 - 2 -> 0xFFFFFFFE - (0x7FFFFFFF, 2, 0xFFFFFFFE), - # 0x7FFFFFFF * 3 = 3 * 2^31 - 3 = 2^32 + 2^31 - 3 -> 0x7FFFFFFD - (0x7FFFFFFF, 3, 0x7FFFFFFD), - # 0x55555555 * 3 = 0xFFFFFFFF - (0x55555555, 3, 0xFFFFFFFF), - # 0xAAAAAAAA * 3 = 2 * 0xFFFFFFFF = 2^33 - 2 -> 0xFFFFFFFE - (0xAAAAAAAA, 3, 0xFFFFFFFE), - # 0x10000001 * 0x10000001 = (2^28 + 1)^2 = 2^56 + 2^29 + 1 -> 0x20000001 - (0x10000001, 0x10000001, 0x20000001), - # 0x10000000 * 0x10 = 2^28 * 2^4 = 2^32 -> 0 - (0x10000000, 0x10, 0), - ] - for a, b, expected in cases: - with self.subTest(a=hex(a), b=hex(b), expected=hex(expected)): - self.assertEqual(ref_mul_lo_u32(a, b), expected) - self.assertEqual(run_spirv_imul(a, b), expected) - - def test_overflow_wrap_powers_of_two(self) -> None: - """Powers of two wrapping: 2^p * 2^q mod 2^32.""" - for p in range(32): - for q in range(32): - a = 1 << p - b = 1 << q - expected = (1 << (p + q)) & MASK32 if (p + q < 32) else 0 - with self.subTest(p=p, q=q): - self.assertEqual(ref_mul_lo_u32(a, b), expected) - - def test_overflow_wrap_large_primes(self) -> None: - """Multiplying large primes that exceed 32 bits.""" - prime_pairs = [ - (65537, 65539), - (1000003, 1000033), - (2147483647, 3), - (2147483647, 5), - (2147483647, 2147483647), - ] - for p1, p2 in prime_pairs: - with self.subTest(p1=p1, p2=p2): - expected = (p1 * p2) & MASK32 - self.assertEqual(ref_mul_lo_u32(p1, p2), expected) - self.assertEqual(run_spirv_imul(p1, p2), expected) - - def test_overflow_wrap_chain_accumulation(self) -> None: - """Chained multiplication wrapping across repeated iterations.""" - val = 3 - mult = 5 - py_val = 3 - for i in range(100): - val = ref_mul_lo_u32(val, mult) - py_val = (py_val * mult) & MASK32 - self.assertEqual(val, py_val, f"Iteration {i}") - - def test_overflow_multiplicative_inverses(self) -> None: - """Every odd 32-bit integer has a multiplicative inverse mod 2^32.""" - odd_numbers = [ - 1, - 3, - 5, - 7, - 11, - 17, - 257, - 65537, - 0x12345679, - 0x7FFFFFFF, - 0xFFFFFFFF, - ] - for x in odd_numbers: - inv = pow(x, -1, 1 << 32) - with self.subTest(x=hex(x), inv=hex(inv)): - self.assertEqual(ref_mul_lo_u32(x, inv), 1) - self.assertEqual(run_spirv_imul(x, inv), 1) - - def test_fuzz_overflow_differential(self) -> None: - """Differential fuzz testing with pseudo-random 32-bit numbers.""" - rng = random.Random(0x4D554C) - for _ in range(150): - a = rng.randint(0, MASK32) - b = rng.randint(0, MASK32) - expected = (a * b) & MASK32 - self.assertEqual(ref_mul_lo_u32(a, b), expected) - self.assertEqual(run_spirv_imul(a, b), expected) - - -class TestMulLoSignedUnsignedIdentity(unittest.TestCase): - """Rigorous verification of the signed vs unsigned low-dword identity: - (s32(a) * s32(b)) mod 2^32 == (u32(a) * u32(b)) mod 2^32. - """ - - def test_signed_unsigned_low_dword_isomorphic_identity(self) -> None: - """Low 32 bits are unconditionally identical for signed and unsigned integers.""" - for a, b in SAMPLE_PAIRS: - with self.subTest(a=hex(a), b=hex(b)): - lo_u = ref_mul_lo_u32(a, b) - lo_i = ref_mul_lo_i32(a, b) - self.assertEqual(lo_u, lo_i) - - def test_signed_negative_operands_product(self) -> None: - """Verification of signed negative operand combinations.""" - # Negative * Negative = Positive - neg_neg_cases = [ - (-1, -1, 1), - (-2, -3, 6), - (-10, -20, 200), - (-100, -200, 20000), - (-2147483648, -1, 0x80000000), # INT32_MIN * -1 = 2^31 -> 0x80000000 - (-2147483647, -1, 0x7FFFFFFF), # (-(2^31 - 1)) * -1 = INT32_MAX - ] - for a, b, expected in neg_neg_cases: - with self.subTest(a=a, b=b, expected=hex(expected)): - self.assertEqual(ref_mul_lo_i32(a, b), expected) - self.assertEqual(ref_mul_lo_u32(a, b), expected) - self.assertEqual(run_spirv_imul(a, b), expected) - - # Negative * Positive = Negative (two's complement) - neg_pos_cases = [ - (-1, 1, 0xFFFFFFFF), - (-5, 10, (-50) & MASK32), - (-16, 64, (-1024) & MASK32), - (-2147483648, 2, 0), # INT32_MIN * 2 = -2^32 -> 0 mod 2^32 - (-2147483648, 3, 0x80000000), # INT32_MIN * 3 = -3 * 2^31 = -2^32 - 2^31 -> 0x80000000 - ] - for a, b, expected in neg_pos_cases: - with self.subTest(a=a, b=b, expected=hex(expected)): - self.assertEqual(ref_mul_lo_i32(a, b), expected) - self.assertEqual(ref_mul_lo_u32(a, b), expected) - self.assertEqual(run_spirv_imul(a, b), expected) - - def test_signed_vs_unsigned_high_dword_divergence_contrast(self) -> None: - """Contrast: low dword is identical, but high dword diverges on negative operands. - This demonstrates why hardware needs separate v_mul_hi_u32 and v_mul_hi_i32, - but only a single v_mul_lo_u32. - """ - divergent_pairs = [ - (0xFFFFFFFF, 0xFFFFFFFF), # -1 * -1 - (0xFFFFFFFF, 5), # -1 * 5 - (0x80000000, 2), # INT32_MIN * 2 - (100, -1), # 100 * -1 - (-16, 64), # -16 * 64 - ] - for a, b in divergent_pairs: - with self.subTest(a=hex(a), b=hex(b)): - lo_u, hi_u = ref_mul_64(a, b, signed=False) - lo_i, hi_i = ref_mul_64(a, b, signed=True) - - # Low dword MUST be identical - self.assertEqual(lo_u, lo_i, f"Low dword diverged for ({hex(a)}, {hex(b)})") - self.assertEqual(lo_u, ref_mul_lo_u32(a, b)) - - # High dword MUST diverge for these negative inputs - self.assertNotEqual(hi_u, hi_i, f"Expected high dwords to diverge for ({hex(a)}, {hex(b)})") - - def test_signed_fuzz_identity(self) -> None: - """Differential fuzz verification that signed and unsigned lo-multiplication match.""" - rng = random.Random(0x5349474E) - for _ in range(200): - a = rng.randint(0, MASK32) - b = rng.randint(0, MASK32) - self.assertEqual(ref_mul_lo_u32(a, b), ref_mul_lo_i32(a, b)) - - -class TestMulLoNegativeControls(unittest.TestCase): - """Negative controls ensuring any faulty arithmetic, incorrect signedness, - truncation, or pipeline mutations are caught. - """ - - def test_hi_lo_word_confusion_detected(self) -> None: - """Negative control: returning high word instead of low word fails.""" - pairs = [ - (0x10000, 0x10000), - (0xFFFFFFFF, 2), - (0x80000000, 2), - (0x12345678, 0x9ABCDEF0), - ] - for a, b in pairs: - with self.subTest(a=hex(a), b=hex(b)): - lo = ref_mul_lo_u32(a, b) - hi_u = ((u32(a) * u32(b)) >> 32) & MASK32 - self.assertNotEqual(lo, hi_u, f"lo and hi should diverge for ({hex(a)}, {hex(b)})") - - def test_16bit_truncation_mutation_detected(self) -> None: - """Negative control: truncating inputs to 16 bits fails on 32-bit operands.""" - a = 0x10001 - b = 0x20003 - correct = ref_mul_lo_u32(a, b) - sabotaged_16bit = ((a & 0xFFFF) * (b & 0xFFFF)) & MASK32 - self.assertNotEqual(correct, sabotaged_16bit) - - def test_arithmetic_mutations_detected(self) -> None: - """Negative control: common arithmetic sabotages are detected.""" - a = 0x12345678 - b = 0x00000003 - correct = ref_mul_lo_u32(a, b) - - # Addition instead of multiplication - sabotaged_add = (a + b) & MASK32 - self.assertNotEqual(correct, sabotaged_add) - - # Off-by-one error - sabotaged_off_by_one = (correct + 1) & MASK32 - self.assertNotEqual(correct, sabotaged_off_by_one) - - # Dropped high bit (31-bit masking) - val_with_msb = 0x80000001 - res = ref_mul_lo_u32(val_with_msb, 1) - sabotaged_mask31 = res & 0x7FFFFFFF - self.assertNotEqual(res, sabotaged_mask31) - - def test_signed_saturation_mutation_detected(self) -> None: - """Negative control: saturating overflow instead of wrapping is detected.""" - a = 0x7FFFFFFF # INT32_MAX - b = 2 - correct = ref_mul_lo_u32(a, b) # wraps to 0xFFFFFFFE (-2) - sabotaged_saturated = 0x7FFFFFFF # clamped to INT32_MAX - self.assertNotEqual(correct, sabotaged_saturated) - - def test_exec_mask_leak_mutation_detected(self) -> None: - """Negative control: modifying inactive EXEC lanes is detected.""" - interp = VectorALUMulInterpreter(wave_size=4) - interp.set_exec(0b0011) # only lanes 0 and 1 active - interp.set_vgpr(0, 2, 0xDEADBEEF) - interp.set_vgpr(0, 3, 0xDEADBEEF) - - interp.execute_v_mul_lo_u32(0, 10, 20) - - # Inactive lanes 2 and 3 must not be modified - self.assertEqual(interp.get_vgpr(0, 2), 0xDEADBEEF) - self.assertEqual(interp.get_vgpr(0, 3), 0xDEADBEEF) - - # If a buggy implementation updated lane 2 to 200, it would fail - sabotaged_lane2 = 200 - self.assertNotEqual(interp.get_vgpr(0, 2), sabotaged_lane2) - - def test_spirv_opcode_substitution_detected(self) -> None: - """Negative control: mutating OpIMul to OpISub in SPIR-V produces divergence.""" - a = 20 - b = 5 - correct = run_spirv_imul(a, b) # 20 * 5 = 100 - - module_isub = f"""\ -OpCapability Shader -%glsl = OpExtInstImport "GLSL.std.450" -OpMemoryModel Logical GLSL450 -OpEntryPoint Fragment %main "main" %out -%void = OpTypeVoid -%fn = OpTypeFunction %void -%uint = OpTypeInt 32 0 -%_ptr_Output_uint = OpTypePointer Output %uint -%out = OpVariable %_ptr_Output_uint Output -%ca = OpConstant %uint {u32(a)} -%cb = OpConstant %uint {u32(b)} -%main = OpFunction %void None %fn -%entry = OpLabel -%res = OpISub %uint %ca %cb -OpStore %out %res -OpReturn -OpFunctionEnd -""" - mutated_res = si.run_fragment(module_isub)["%out"][0] # 20 - 5 = 15 - self.assertNotEqual(correct, mutated_res) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_alu_pack_f16.py b/tests/semantic/test_alu_pack_f16.py deleted file mode 100644 index becbda7e0..000000000 --- a/tests/semantic/test_alu_pack_f16.py +++ /dev/null @@ -1,770 +0,0 @@ -"""Semantic interpreter and translator tests for AMD RDNA2 v_pack_b32_f16 float packing. - -v_pack_b32_f16 (VOP3 opcode 0x272 on GFX10 / RDNA2): - dst[15:0] = half_word(src0, op_sel[0]) - dst[31:16] = half_word(src1, op_sel[1]) - -Semantics: - - Packs two 16-bit half-precision float values (or raw 16-bit bit patterns) from src0 and src1 - into a single 32-bit vector register (VGPR). - - Unlike 16-bit ALU instructions that preserve the unwritten destination half, v_pack_b32_f16 - completely overwrites all 32 bits of the destination register. - - Operand selection (op_sel:[s0, s1, s2]): - s0 = 0: low 16 bits of src0 (bits 15:0) - s0 = 1: high 16 bits of src0 (bits 31:16) - s1 = 0: low 16 bits of src1 (bits 15:0) - s1 = 1: high 16 bits of src1 (bits 31:16) - - Source modifiers: - abs (|src|): clears bit 15 (sign bit) of the selected half-word (evaluated first). - neg (-src): flips bit 15 (sign bit) of the selected half-word (evaluated second). - - Operands: - VGPRs, SGPRs, literal constants, and inline constants (e.g. 1.0, 2.0, 0.5, 0.0, -1.0). - Inline float constants place the f16 bit pattern in the low half and 0 in the high half; - selecting the high half of an inline float constant therefore reads +0.0. - - Bit-exact float representation: - Preserves all IEEE 754 binary16 values without rounding or flushing: - +0.0, -0.0, subnormals (denorms), normalized numbers, +inf, -inf, quiet NaNs (qNaN), - and signaling NaNs (sNaN) with custom payload bits preserved intact. - -Each test case verifies: - 1. Pure-Python reference oracle behavior. - 2. Synthetic RDNA2 pixel shader translation via tools/rdna2spirv.py and execution in - tests/semantic/spirv_mini_interp.py. - 3. Direct SPIR-V shader sequence execution in spirv_mini_interp.py. - 4. Negative controls confirming fault sensitivity to operand swaps, off-by-one shifts, - missing masks, and modifier bugs. - -Standard library Python only; zero game data; Python 3.9+ compatible. -""" -from __future__ import annotations - -import itertools -import math -import os -import random -import struct -import sys -import tempfile -import unittest -import warnings - -HERE = os.path.dirname(os.path.abspath(__file__)) -ROOT = os.path.dirname(os.path.dirname(HERE)) -TOOLS_DIR = os.environ.get("LEONIDA_TOOLS_DIR") or os.path.join(ROOT, "tools") - -sys.dont_write_bytecode = True -if TOOLS_DIR not in sys.path: - sys.path.insert(0, TOOLS_DIR) -if HERE not in sys.path: - sys.path.insert(0, HERE) - -import rdna2spirv # noqa: E402 -import spirv_mini_interp as si # noqa: E402 - -MASK32 = 0xFFFFFFFF -MASK16 = 0xFFFF -SIGN16 = 0x8000 -ABS16 = 0x7FFF -POISON_DST = 0xDEADBEEF -STUB_DXBC = b"DXBC" + bytes(24) + struct.pack(" float: - """Convert a 16-bit half precision integer bit pattern into Python float.""" - return struct.unpack(" int: - """Convert a Python float into a 16-bit half precision integer bit pattern.""" - if math.isnan(x): - return POS_QNAN_DEFAULT - try: - return struct.unpack(" 0 else NEG_INF - - -def is_nan_f16(h: int) -> bool: - """Check if 16-bit integer represents an IEEE 754 binary16 NaN.""" - return (h & 0x7C00) == 0x7C00 and (h & 0x03FF) != 0 - - -def is_qnan_f16(h: int) -> bool: - """Check if 16-bit integer represents a Quiet NaN (MSB of mantissa is 1).""" - return is_nan_f16(h) and bool(h & 0x0200) - - -def is_snan_f16(h: int) -> bool: - """Check if 16-bit integer represents a Signaling NaN (MSB of mantissa is 0, payload != 0).""" - return is_nan_f16(h) and not bool(h & 0x0200) - - -def ref_extract_half(val: int, hi: bool = False) -> int: - """Extract low (bits 15:0) or high (bits 31:16) half-word with 16-bit masking.""" - val &= MASK32 - return ((val >> 16) if hi else val) & MASK16 - - -def ref_apply_mods(val16: int, abs_val: bool = False, neg: bool = False) -> int: - """Apply RDNA2 VOP3 abs and neg modifiers to a 16-bit half-word: abs first, neg second.""" - m = val16 & MASK16 - if abs_val: - m &= ABS16 - if neg: - m ^= SIGN16 - return m - - -def ref_pack_b32_f16( - src0: int, - src1: int, - op_sel: tuple[int, int] = (0, 0), - abs0: bool = False, - neg0: bool = False, - abs1: bool = False, - neg1: bool = False, -) -> int: - """Pure-Python reference oracle for AMD RDNA2 v_pack_b32_f16 float packing.""" - h0 = ref_extract_half(src0, hi=bool(op_sel[0])) - h1 = ref_extract_half(src1, hi=bool(op_sel[1])) - - h0 = ref_apply_mods(h0, abs_val=abs0, neg=neg0) - h1 = ref_apply_mods(h1, abs_val=abs1, neg=neg1) - - return (h0 & MASK16) | ((h1 & MASK16) << 16) - - -def ref_decompose_pack(dword: int) -> tuple[int, int]: - """Decompose a 32-bit packed word into (lo16, hi16).""" - dword &= MASK32 - return dword & MASK16, (dword >> 16) & MASK16 - - -_TMP_DIR: tempfile.TemporaryDirectory | None = None -_SRC_PATH: str | None = None - - -def setUpModule() -> None: - global _TMP_DIR, _SRC_PATH - _TMP_DIR = tempfile.TemporaryDirectory() - disasm_dir = os.path.join(_TMP_DIR.name, "disasm") - os.mkdir(disasm_dir) - _SRC_PATH = os.path.join(disasm_dir, "ps_pack_f16.s") - with open(os.path.join(_TMP_DIR.name, "ps_pack_f16.dxbc"), "wb") as f: - f.write(STUB_DXBC) - - -def tearDownModule() -> None: - global _TMP_DIR - if _TMP_DIR is not None: - _TMP_DIR.cleanup() - _TMP_DIR = None - - -def run_shader_lines(lines: list[str]) -> int: - """Assemble and run synthetic pixel shader lines, returning exported mrt0 v0 word.""" - if _TMP_DIR is None: - setUpModule() - assert _SRC_PATH is not None - asm = ( - "; test_alu_pack_f16\n" - + "".join(f"\t{ln}\n" for ln in lines) - + "\texp mrt0 v0, v0, v0, v0 done vm\n" - + "\ts_endpgm\n" - ) - with open(_SRC_PATH, "w", encoding="utf-8") as f: - f.write(asm) - with warnings.catch_warnings(): - warnings.simplefilter("ignore", ResourceWarning) - spv = rdna2spirv.translate(_SRC_PATH) - return si.run_fragment(spv)["%out_mrt0"][0] - - -def run_pack_instruction( - instruction_line: str, - v1: int = 0, - v2: int = 0, - old_v0: int = POISON_DST, -) -> int: - """Seed v1, v2 and destination v0, execute instruction_line, return result in v0.""" - lines = [ - f"v_mov_b32 v0, {old_v0 & MASK32:#x}", - f"v_mov_b32 v1, {v1 & MASK32:#x}", - f"v_mov_b32 v2, {v2 & MASK32:#x}", - instruction_line, - ] - return run_shader_lines(lines) - - -def run_spirv_pack_logical( - src0: int, - src1: int, - op_sel: tuple[int, int] = (0, 0), - abs0: bool = False, - neg0: bool = False, - abs1: bool = False, - neg1: bool = False, -) -> int: - """Execute direct SPIR-V shader sequence modeling v_pack_b32_f16 via logical shifts and bitwise ops.""" - lines = [ - "OpCapability Shader", - '%glsl = OpExtInstImport "GLSL.std.450"', - "OpMemoryModel Logical GLSL450", - 'OpEntryPoint Fragment %main "main" %out', - "%void = OpTypeVoid", - "%fn = OpTypeFunction %void", - "%uint = OpTypeInt 32 0", - "%_ptr_Output_uint = OpTypePointer Output %uint", - "%out = OpVariable %_ptr_Output_uint Output", - f"%c_s0 = OpConstant %uint {src0 & MASK32}", - f"%c_s1 = OpConstant %uint {src1 & MASK32}", - "%c16 = OpConstant %uint 16", - "%c0xFFFF = OpConstant %uint 65535", - "%c0x7FFF = OpConstant %uint 32767", - "%c0x8000 = OpConstant %uint 32768", - "%main = OpFunction %void None %fn", - "%entry = OpLabel", - ] - - var_idx = 0 - - def get_var(prefix: str) -> str: - nonlocal var_idx - var_idx += 1 - return f"%{prefix}_{var_idx}" - - def build_half(c_src: str, op_sel_bit: int, abs_f: bool, neg_f: bool) -> str: - u_var = c_src - if op_sel_bit: - shifted = get_var("shift") - lines.append(f"{shifted} = OpShiftRightLogical %uint {u_var} %c16") - u_var = shifted - masked = get_var("mask") - lines.append(f"{masked} = OpBitwiseAnd %uint {u_var} %c0xFFFF") - cur = masked - if abs_f: - abs_var = get_var("abs") - lines.append(f"{abs_var} = OpBitwiseAnd %uint {cur} %c0x7FFF") - cur = abs_var - if neg_f: - neg_var = get_var("neg") - lines.append(f"{neg_var} = OpBitwiseXor %uint {cur} %c0x8000") - cur = neg_var - return cur - - h0 = build_half("%c_s0", op_sel[0], abs0, neg0) - h1 = build_half("%c_s1", op_sel[1], abs1, neg1) - - h1_hi = get_var("h1_hi") - res = get_var("res") - lines.extend([ - f"{h1_hi} = OpShiftLeftLogical %uint {h1} %c16", - f"{res} = OpBitwiseOr %uint {h0} {h1_hi}", - f"OpStore %out {res}", - "OpReturn", - "OpFunctionEnd", - ]) - - spv = "\n".join(lines) + "\n" - return si.run_fragment(spv)["%out"][0] - - -class TestPackF16ReferenceOracle(unittest.TestCase): - """Verify pure-Python reference oracle functions and IEEE 754 bit-level representation.""" - - def test_reference_basic_identities(self): - self.assertEqual(ref_pack_b32_f16(0, 0), 0) - self.assertEqual(ref_pack_b32_f16(ONE, TWO), (TWO << 16) | ONE) - self.assertEqual(ref_pack_b32_f16(HALF, ONE_POINT_FIVE), (ONE_POINT_FIVE << 16) | HALF) - self.assertEqual(ref_pack_b32_f16(0x1234, 0x5678), 0x56781234) - - def test_reference_truncation_of_unselected_bits(self): - self.assertEqual(ref_pack_b32_f16(0xDEAD1234, 0xBEEF5678), 0x56781234) - self.assertEqual(ref_pack_b32_f16(0xFFFFFFFF, 0xFFFFFFFF), 0xFFFFFFFF) - self.assertEqual(ref_pack_b32_f16(0xFFFF0000, 0xFFFF0000), 0x00000000) - - def test_reference_op_sel_modes(self): - v1 = 0xA1B2C3D4 - v2 = 0xE5F60718 - - self.assertEqual(ref_pack_b32_f16(v1, v2, op_sel=(0, 0)), 0x0718C3D4) - self.assertEqual(ref_pack_b32_f16(v1, v2, op_sel=(1, 0)), 0x0718A1B2) - self.assertEqual(ref_pack_b32_f16(v1, v2, op_sel=(0, 1)), 0xE5F6C3D4) - self.assertEqual(ref_pack_b32_f16(v1, v2, op_sel=(1, 1)), 0xE5F6A1B2) - - def test_reference_modifiers_abs_and_neg(self): - # abs clears bit 15: 0xBC00 (-1.0) -> 0x3C00 (+1.0) - self.assertEqual(ref_apply_mods(NEG_ONE, abs_val=True), ONE) - self.assertEqual(ref_apply_mods(ONE, abs_val=True), ONE) - - # neg inverts bit 15: 0x3C00 (+1.0) -> 0xBC00 (-1.0) - self.assertEqual(ref_apply_mods(ONE, neg=True), NEG_ONE) - self.assertEqual(ref_apply_mods(NEG_ONE, neg=True), ONE) - - # abs then neg: -|x| always sets sign bit - self.assertEqual(ref_apply_mods(ONE, abs_val=True, neg=True), NEG_ONE) - self.assertEqual(ref_apply_mods(NEG_ONE, abs_val=True, neg=True), NEG_ONE) - - # Packing with modifiers - packed = ref_pack_b32_f16(NEG_ONE, TWO, abs0=True, neg1=True) - self.assertEqual(packed, (NEG_TWO << 16) | ONE) - - def test_reference_decomposition(self): - self.assertEqual(ref_decompose_pack(0x40003C00), (ONE, TWO)) - self.assertEqual(ref_decompose_pack(0x56781234), (0x1234, 0x5678)) - self.assertEqual(ref_decompose_pack(0), (0, 0)) - - def test_nan_classification_helpers(self): - self.assertFalse(is_nan_f16(ONE)) - self.assertFalse(is_nan_f16(POS_INF)) - self.assertFalse(is_nan_f16(NEG_INF)) - - self.assertTrue(is_nan_f16(POS_QNAN_DEFAULT)) - self.assertTrue(is_qnan_f16(POS_QNAN_DEFAULT)) - self.assertFalse(is_snan_f16(POS_QNAN_DEFAULT)) - - self.assertTrue(is_nan_f16(POS_SNAN_DEFAULT)) - self.assertTrue(is_snan_f16(POS_SNAN_DEFAULT)) - self.assertFalse(is_qnan_f16(POS_SNAN_DEFAULT)) - - -class TestPackF16RdnaTranslation(unittest.TestCase): - """Semantic tests executing translated RDNA2 v_pack_b32_f16 pixel shaders via spirv_mini_interp.""" - - def test_basic_register_pack(self): - line = "v_pack_b32_f16 v0, v1, v2" - v1 = (TWO << 16) | ONE - v2 = (FOUR << 16) | HALF - got = run_pack_instruction(line, v1=v1, v2=v2) - want = ref_pack_b32_f16(v1, v2, op_sel=(0, 0)) - self.assertEqual(got, want) - self.assertEqual(got, (HALF << 16) | ONE) - - def test_full_destination_overwrite(self): - """Unlike 16-bit ALU instructions, v_pack_b32_f16 overwrites all 32 bits of the destination.""" - for poison in (0xDEADBEEF, 0xAAAAAAAA, 0x55555555, 0xFFFFFFFF): - with self.subTest(poison=hex(poison)): - got = run_pack_instruction("v_pack_b32_f16 v0, v1, v2", v1=ONE, v2=TWO, old_v0=poison) - self.assertEqual(got, (TWO << 16) | ONE) - self.assertNotEqual(got & 0xFFFF0000, poison & 0xFFFF0000) - self.assertNotEqual(got & 0x0000FFFF, poison & 0x0000FFFF) - - def test_op_sel_permutations(self): - v1 = (ONE_POINT_FIVE << 16) | ONE # hi: 1.5, lo: 1.0 - v2 = (FOUR << 16) | TWO # hi: 4.0, lo: 2.0 - - op_sel_cases = [ - ("[0,0,0]", (0, 0), (TWO << 16) | ONE), - ("[1,0,0]", (1, 0), (TWO << 16) | ONE_POINT_FIVE), - ("[0,1,0]", (0, 1), (FOUR << 16) | ONE), - ("[1,1,0]", (1, 1), (FOUR << 16) | ONE_POINT_FIVE), - ] - for sel_str, sel_tuple, expected in op_sel_cases: - with self.subTest(sel=sel_str): - line = f"v_pack_b32_f16 v0, v1, v2 op_sel:{sel_str}" - got = run_pack_instruction(line, v1=v1, v2=v2) - self.assertEqual(got, expected) - self.assertEqual(got, ref_pack_b32_f16(v1, v2, op_sel=sel_tuple)) - - def test_source_modifiers_neg(self): - v1 = ONE # +1.0 - v2 = TWO # +2.0 - - # -v1 on src0 - got_neg0 = run_pack_instruction("v_pack_b32_f16 v0, -v1, v2", v1=v1, v2=v2) - self.assertEqual(got_neg0, (TWO << 16) | NEG_ONE) - self.assertEqual(got_neg0, ref_pack_b32_f16(v1, v2, neg0=True)) - - # -v2 on src1 - got_neg1 = run_pack_instruction("v_pack_b32_f16 v0, v1, -v2", v1=v1, v2=v2) - self.assertEqual(got_neg1, (NEG_TWO << 16) | ONE) - self.assertEqual(got_neg1, ref_pack_b32_f16(v1, v2, neg1=True)) - - # -v1, -v2 on both - got_neg_both = run_pack_instruction("v_pack_b32_f16 v0, -v1, -v2", v1=v1, v2=v2) - self.assertEqual(got_neg_both, (NEG_TWO << 16) | NEG_ONE) - self.assertEqual(got_neg_both, ref_pack_b32_f16(v1, v2, neg0=True, neg1=True)) - - def test_source_modifiers_abs(self): - v1 = NEG_ONE # -1.0 - v2 = NEG_TWO # -2.0 - - # |v1| on src0 - got_abs0 = run_pack_instruction("v_pack_b32_f16 v0, |v1|, v2", v1=v1, v2=v2) - self.assertEqual(got_abs0, (NEG_TWO << 16) | ONE) - self.assertEqual(got_abs0, ref_pack_b32_f16(v1, v2, abs0=True)) - - # |v2| on src1 - got_abs1 = run_pack_instruction("v_pack_b32_f16 v0, v1, |v2|", v1=v1, v2=v2) - self.assertEqual(got_abs1, (TWO << 16) | NEG_ONE) - self.assertEqual(got_abs1, ref_pack_b32_f16(v1, v2, abs1=True)) - - # |v1|, |v2| on both - got_abs_both = run_pack_instruction("v_pack_b32_f16 v0, |v1|, |v2|", v1=v1, v2=v2) - self.assertEqual(got_abs_both, (TWO << 16) | ONE) - self.assertEqual(got_abs_both, ref_pack_b32_f16(v1, v2, abs0=True, abs1=True)) - - def test_source_modifiers_abs_and_neg_combined(self): - """Abs clears bit 15 first, then neg inverts bit 15, yielding negative value.""" - v1 = NEG_ONE # -1.0 - v2 = TWO # +2.0 - - got = run_pack_instruction("v_pack_b32_f16 v0, -|v1|, |v2|", v1=v1, v2=v2) - self.assertEqual(got, (TWO << 16) | NEG_ONE) - self.assertEqual(got, ref_pack_b32_f16(v1, v2, abs0=True, neg0=True, abs1=True)) - - def test_modifiers_combined_with_op_sel(self): - """Modifiers operate on the half selected by op_sel.""" - v1 = (NEG_ONE << 16) | ONE # hi: -1.0, lo: 1.0 - v2 = (NEG_TWO << 16) | TWO # hi: -2.0, lo: 2.0 - - # Select high half of v1 with abs -> | -1.0 | = +1.0; low half of v2 with neg -> - (+2.0) = -2.0 - line = "v_pack_b32_f16 v0, |v1|, -v2 op_sel:[1,0,0]" - got = run_pack_instruction(line, v1=v1, v2=v2) - want = (NEG_TWO << 16) | ONE - self.assertEqual(got, want) - self.assertEqual(got, ref_pack_b32_f16(v1, v2, op_sel=(1, 0), abs0=True, neg1=True)) - - def test_self_pack_broadcast_and_swap(self): - """Packing a register with itself can duplicate halves or swap low and high halves.""" - v = (TWO << 16) | ONE # hi: 2.0, lo: 1.0 - - # Duplicate low half: [0, 0] -> (1.0, 1.0) - got_lo = run_pack_instruction("v_pack_b32_f16 v0, v1, v1 op_sel:[0,0,0]", v1=v) - self.assertEqual(got_lo, (ONE << 16) | ONE) - - # Duplicate high half: [1, 1] -> (2.0, 2.0) - got_hi = run_pack_instruction("v_pack_b32_f16 v0, v1, v1 op_sel:[1,1,0]", v1=v) - self.assertEqual(got_hi, (TWO << 16) | TWO) - - # Swap low and high halves: [1, 0] -> (hi, lo) -> dst[15:0]=hi(2.0), dst[31:16]=lo(1.0) - got_swap = run_pack_instruction("v_pack_b32_f16 v0, v1, v1 op_sel:[1,0,0]", v1=v) - self.assertEqual(got_swap, (ONE << 16) | TWO) - - def test_sgpr_operands(self): - lines = [ - "s_mov_b32 s0, 0x1111", - "s_mov_b32 s1, 0x2222", - "v_pack_b32_f16 v0, s0, s1", - ] - self.assertEqual(run_shader_lines(lines), 0x22221111) - - # Mixed VGPR and SGPR - lines_mixed = [ - "v_mov_b32 v1, 0x3333", - "s_mov_b32 s0, 0x4444", - "v_pack_b32_f16 v0, v1, s0", - ] - self.assertEqual(run_shader_lines(lines_mixed), 0x44443333) - - def test_literal_constants(self): - lines = [ - "v_pack_b32_f16 v0, 0x1234, 0x5678", - ] - self.assertEqual(run_shader_lines(lines), 0x56781234) - - def test_inline_float_constants(self): - test_pairs = [ - ("1.0", "2.0", (TWO << 16) | ONE), - ("0.5", "1.5", (ONE_POINT_FIVE << 16) | HALF), - ("0.0", "4.0", (FOUR << 16) | POS_ZERO), - ("-1.0", "1.0", (ONE << 16) | NEG_ONE), - ("0.5", "-0.5", (NEG_HALF << 16) | HALF), - ("-2.0", "-1.0", (NEG_ONE << 16) | NEG_TWO), - ] - for c0, c1, expected in test_pairs: - with self.subTest(c0=c0, c1=c1): - line = f"v_pack_b32_f16 v0, {c0}, {c1}" - self.assertEqual(run_shader_lines([line]), expected) - - def test_inline_float_constant_high_half_zero(self): - """Selecting the high half of an inline float constant reads +0.0.""" - line = "v_pack_b32_f16 v0, 1.0, 2.0 op_sel:[1,0,0]" - # src0 is 1.0 with op_sel 1 -> high half is 0x0000 (+0.0) - # src1 is 2.0 with op_sel 0 -> low half is 0x4000 (2.0) - got = run_shader_lines([line]) - self.assertEqual(got, (TWO << 16) | POS_ZERO) - - line_both = "v_pack_b32_f16 v0, 1.0, 2.0 op_sel:[1,1,0]" - # both high halves are 0x0000 - got_both = run_shader_lines([line_both]) - self.assertEqual(got_both, 0x00000000) - - def test_nan_preservation_bit_exact(self): - """All NaN variations preserve quiet/signaling bits and payload bits exactly.""" - nan_cases = [ - (POS_QNAN_DEFAULT, "positive default quiet NaN"), - (NEG_QNAN_DEFAULT, "negative default quiet NaN"), - (POS_QNAN_PAYLOAD, "positive quiet NaN with payload 1"), - (POS_QNAN_HIGH, "positive quiet NaN with high payload"), - (NEG_QNAN_PAYLOAD, "negative quiet NaN with custom payload"), - (POS_SNAN_DEFAULT, "positive default signaling NaN"), - (NEG_SNAN_DEFAULT, "negative default signaling NaN"), - (POS_SNAN_PAYLOAD, "positive signaling NaN with custom payload"), - (NEG_SNAN_PAYLOAD, "negative signaling NaN with custom payload"), - ] - for nan0, name0 in nan_cases: - for nan1, name1 in nan_cases: - with self.subTest(lo=name0, hi=name1): - expected = (nan1 << 16) | nan0 - got = run_pack_instruction("v_pack_b32_f16 v0, v1, v2", v1=nan0, v2=nan1) - self.assertEqual(got, expected) - - lo, hi = ref_decompose_pack(got) - self.assertEqual(lo, nan0) - self.assertEqual(hi, nan1) - self.assertEqual(is_qnan_f16(lo), is_qnan_f16(nan0)) - self.assertEqual(is_snan_f16(lo), is_snan_f16(nan0)) - self.assertEqual(is_qnan_f16(hi), is_qnan_f16(nan1)) - self.assertEqual(is_snan_f16(hi), is_snan_f16(nan1)) - - def test_subnormal_and_boundary_values(self): - """Subnormal half floats and boundary floats are preserved without flushing.""" - special_values = [ - POS_ZERO, - NEG_ZERO, - MIN_SUBNORMAL, - MAX_SUBNORMAL, - MIN_SUBNORMAL_NEG, - MAX_SUBNORMAL_NEG, - MIN_NORMAL, - MAX_FINITE, - MIN_FINITE_NEG, - POS_INF, - NEG_INF, - ] - for s0 in special_values: - for s1 in special_values: - with self.subTest(s0=hex(s0), s1=hex(s1)): - expected = (s1 << 16) | s0 - got = run_pack_instruction("v_pack_b32_f16 v0, v1, v2", v1=s0, v2=s1) - self.assertEqual(got, expected) - lo, hi = ref_decompose_pack(got) - self.assertEqual(lo, s0) - self.assertEqual(hi, s1) - - -class TestPackF16SpirvInterp(unittest.TestCase): - """Semantic tests executing direct SPIR-V code in spirv_mini_interp and cross-checking oracles.""" - - def test_direct_spirv_logical_all_op_sel_modes(self): - test_vectors = [ - (0, 0), - (0x12345678, 0x9ABCDEF0), - ((TWO << 16) | ONE, (FOUR << 16) | HALF), - (0xFFFFFFFF, 0x00000000), - (0x80000000, 0x7FFFFFFF), - (0x55555555, 0xAAAAAAAA), - (POS_QNAN_PAYLOAD, POS_SNAN_PAYLOAD), - (MIN_SUBNORMAL, MAX_FINITE), - ] - for s0, s1 in test_vectors: - for op_sel in itertools.product((0, 1), repeat=2): - with self.subTest(s0=hex(s0), s1=hex(s1), op_sel=op_sel): - expected = ref_pack_b32_f16(s0, s1, op_sel=op_sel) - got = run_spirv_pack_logical(s0, s1, op_sel=op_sel) - self.assertEqual(got, expected) - - def test_direct_spirv_logical_with_modifiers(self): - s0 = (NEG_ONE << 16) | ONE - s1 = (NEG_TWO << 16) | TWO - - for abs0, neg0, abs1, neg1 in itertools.product((True, False), repeat=4): - with self.subTest(abs0=abs0, neg0=neg0, abs1=abs1, neg1=neg1): - expected = ref_pack_b32_f16(s0, s1, abs0=abs0, neg0=neg0, abs1=abs1, neg1=neg1) - got = run_spirv_pack_logical(s0, s1, abs0=abs0, neg0=neg0, abs1=abs1, neg1=neg1) - self.assertEqual(got, expected) - - def test_spirv_glsl_pack_half2x16_builtins(self): - """Cross-check with GLSL.std.450 PackHalf2x16 and UnpackHalf2x16 builtins.""" - header = """OpCapability Shader -%glsl = OpExtInstImport "GLSL.std.450" -OpMemoryModel Logical GLSL450 -OpEntryPoint Fragment %main "main" %out -%void = OpTypeVoid -%fn = OpTypeFunction %void -%uint = OpTypeInt 32 0 -%float = OpTypeFloat 32 -%v2float = OpTypeVector %float 2 -%_ptr_Output_uint = OpTypePointer Output %uint -%out = OpVariable %_ptr_Output_uint Output -%f1 = OpConstant %float 1.0 -%f2 = OpConstant %float 2.0 -%f70000 = OpConstant %float 70000.0 -%ch = OpConstant %uint 1073757184 -%main = OpFunction %void None %fn -%entry = OpLabel -""" - footer = "OpReturn\nOpFunctionEnd\n" - - def run_body(body: str) -> int: - return si.run_fragment(header + body + "OpStore %out %res\n" + footer)["%out"][0] - - # Pack 1.0 and 2.0 -> 0x40003C00 - pack_res = run_body( - "%v = OpCompositeConstruct %v2float %f1 %f2\n" - "%res = OpExtInst %uint %glsl PackHalf2x16 %v\n" - ) - self.assertEqual(pack_res, (TWO << 16) | ONE) - - # Overflow: 70000.0 overflows half float to +inf (0x7C00) - inf_res = run_body( - "%v_inf = OpCompositeConstruct %v2float %f70000 %f1\n" - "%res = OpExtInst %uint %glsl PackHalf2x16 %v_inf\n" - ) - self.assertEqual(inf_res, (ONE << 16) | POS_INF) - - # Unpack roundtrip: %ch is 0x40003C00 -> low half is 1.0 -> 0x3F800000 in binary32 - unpack_res = run_body( - "%u = OpExtInst %v2float %glsl UnpackHalf2x16 %ch\n" - "%x = OpCompositeExtract %float %u 0\n" - "%res = OpBitcast %uint %x\n" - ) - self.assertEqual(unpack_res, 0x3F800000) - - def test_deterministic_fuzzing_matches_oracle_and_rdna(self): - """Cross-check 60 random inputs across reference oracle, direct SPIR-V, and RDNA shader translation.""" - rng = random.Random(0xF16F16) - special_halves = [ - POS_ZERO, NEG_ZERO, MIN_SUBNORMAL, MAX_SUBNORMAL, - MIN_NORMAL, ONE, TWO, HALF, MAX_FINITE, - POS_INF, NEG_INF, POS_QNAN_DEFAULT, POS_SNAN_PAYLOAD, - ] - - for idx in range(60): - # Seed 32-bit registers with either random bit words or special f16 combinations - if rng.random() < 0.4: - s0 = (rng.choice(special_halves) << 16) | rng.choice(special_halves) - s1 = (rng.choice(special_halves) << 16) | rng.choice(special_halves) - else: - s0 = rng.getrandbits(32) - s1 = rng.getrandbits(32) - - op_sel = (rng.choice((0, 1)), rng.choice((0, 1))) - abs0 = rng.choice((True, False)) - neg0 = rng.choice((True, False)) - abs1 = rng.choice((True, False)) - neg1 = rng.choice((True, False)) - - with self.subTest(iteration=idx, s0=hex(s0), s1=hex(s1)): - expected = ref_pack_b32_f16( - s0, s1, op_sel=op_sel, - abs0=abs0, neg0=neg0, abs1=abs1, neg1=neg1, - ) - - # Direct SPIR-V execution - got_spv = run_spirv_pack_logical( - s0, s1, op_sel=op_sel, - abs0=abs0, neg0=neg0, abs1=abs1, neg1=neg1, - ) - self.assertEqual(got_spv, expected) - - # Translated RDNA shader execution - src0_str = "v1" - if abs0 and neg0: - src0_str = "-|v1|" - elif abs0: - src0_str = "|v1|" - elif neg0: - src0_str = "-v1" - - src1_str = "v2" - if abs1 and neg1: - src1_str = "-|v2|" - elif abs1: - src1_str = "|v2|" - elif neg1: - src1_str = "-v2" - - line = f"v_pack_b32_f16 v0, {src0_str}, {src1_str} op_sel:[{op_sel[0]},{op_sel[1]},0]" - got_rdna = run_pack_instruction(line, v1=s0, v2=s1) - self.assertEqual(got_rdna, expected) - - -class TestPackF16NegativeControls(unittest.TestCase): - """Negative controls ensuring tests fail when intentional bugs or regressions are injected.""" - - def test_operand_order_reversal_detected(self): - s0, s1 = ONE, TWO - correct = ref_pack_b32_f16(s0, s1) - reversed_order = ref_pack_b32_f16(s1, s0) - self.assertNotEqual(correct, reversed_order) - - def test_missing_high_half_shift_detected(self): - s0, s1 = ONE, TWO - correct = ref_pack_b32_f16(s0, s1) - missing_shift = (s0 & MASK16) | (s1 & MASK16) - self.assertNotEqual(correct, missing_shift) - - def test_off_by_one_shift_detected(self): - s0, s1 = ONE, TWO - correct = ref_pack_b32_f16(s0, s1) - shift_15 = (s0 & MASK16) | ((s1 & MASK16) << 15) - self.assertNotEqual(correct, shift_15) - - def test_missing_mask_truncation_detected(self): - s0, s1 = 0xDEAD1234, 0xBEEF5678 - correct = ref_pack_b32_f16(s0, s1) - unmasked = (s0 | (s1 << 16)) & MASK32 - self.assertNotEqual(correct, unmasked) - - def test_inverted_op_sel_detected(self): - s0 = (ONE_POINT_FIVE << 16) | ONE - s1 = (FOUR << 16) | TWO - correct = ref_pack_b32_f16(s0, s1, op_sel=(0, 0)) - inverted = ref_pack_b32_f16(s0, s1, op_sel=(1, 1)) - self.assertNotEqual(correct, inverted) - - def test_wrong_sign_bit_in_modifier_detected(self): - s = ONE - correct_neg = ref_apply_mods(s, neg=True) - # Inverting bit 14 instead of bit 15 - wrong_bit = s ^ (1 << 14) - self.assertNotEqual(correct_neg, wrong_bit) - - def test_modifier_evaluation_order_detected(self): - # In RDNA2 ISA, abs clears bit 15 first, then neg inverts bit 15: -|x| always sets sign bit. - # If order were inverted (neg first, then abs), | -x | would clear sign bit to positive! - val = ONE - correct_abs_then_neg = ref_apply_mods(val, abs_val=True, neg=True) - buggy_neg_then_abs = ((val & MASK16) ^ SIGN16) & ABS16 - self.assertEqual(correct_abs_then_neg, NEG_ONE) - self.assertEqual(buggy_neg_then_abs, ONE) - self.assertNotEqual(correct_abs_then_neg, buggy_neg_then_abs) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_alu_pack_in_place.py b/tests/semantic/test_alu_pack_in_place.py deleted file mode 100644 index 3a61d782c..000000000 --- a/tests/semantic/test_alu_pack_in_place.py +++ /dev/null @@ -1,51 +0,0 @@ -"""v_pack_b32_u16 is not an RDNA2 instruction, and tools/rdna2spirv.py rejects it. - -The previous version of this file (799 lines) modelled in-place "v_pack_b32_u16 dst, src0, src1 [op_sel] [clamp]" with -a private Python function and hand-written SPIR-V, and never called the translator. RDNA2 packs two halves with -v_pack_b32_f16 only (llvm-mc -triple=amdgcn -mcpu=gfx1030: "invalid instruction" for v_pack_b32_u16), so there is no ISA -semantics to test against; the honest test is that the translator refuses the mnemonic by name, in the in-place forms -the old file modelled too. v_pack_b32_f16, which is real, still translates in the same aliasing forms. -""" -import os -import sys -import unittest - -HERE = os.path.dirname(os.path.abspath(__file__)) -sys.dont_write_bytecode = True -sys.path.insert(0, HERE) -import support # noqa: E402 -import rdna2spirv # noqa: E402 - - -def program(ins): - return ["v_mov_b32 v0, 0x11112222", "v_mov_b32 v1, 0x33334444", ins, "exp mrt0 v0, v0, v0, v0 done vm", "s_endpgm"] - - -FORMS = [ - "v_pack_b32_u16 v0, v0, v1", # dst aliases src0 - "v_pack_b32_u16 v0, v1, v0", # dst aliases src1 - "v_pack_b32_u16 v0, v0, v0", # dst aliases both - "v_pack_b32_u16 v2, v0, v1", - "v_pack_b32_u16 v0, v0, v1 op_sel:[1,0]", - "v_pack_b32_u16 v0, v1, v0 op_sel:[0,1]", - "v_pack_b32_u16 v0, v0, v1 clamp", -] - - -class PackB32U16Unsupported(unittest.TestCase): - def test_refused_by_name_in_every_form(self): - for ins in FORMS: - with self.subTest(ins=ins): - with self.assertRaises(rdna2spirv.Unsupported) as refused: - support.translate_lines("ps_pack_u16", program(ins)) - self.assertEqual(str(refused.exception), "v_pack_b32_u16") - - def test_the_real_pack_translates_in_place(self): - for ins in ("v_pack_b32_f16 v0, v0, v1", "v_pack_b32_f16 v0, v1, v0", "v_pack_b32_f16 v0, v0, v0", - "v_pack_b32_f16 v0, v0, v1 op_sel:[1,0,0]"): - with self.subTest(ins=ins): - self.assertIn("OpFunction", support.translate_lines("ps_pack_ok", program(ins))) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_alu_perm_alignbit.py b/tests/semantic/test_alu_perm_alignbit.py deleted file mode 100644 index 7e806849f..000000000 --- a/tests/semantic/test_alu_perm_alignbit.py +++ /dev/null @@ -1,206 +0,0 @@ -"""Semantic interpreter tests for RDNA2 byte permute and funnel shift (v_perm_b32, v_alignbit_b32). - -Each case translates a synthetic pixel shader with tools/rdna2spirv.py, runs it in tests/semantic/spirv_mini_interp.py -and compares the mrt0 word with a plain-Python reference. The interpreter rejects shifts of 32 or more (undefined in -SPIR-V), so these tests also check that the translation never emits one, including on the discarded side of an -OpSelect. - -v_perm_b32 D, S0, S1, SEL: result byte i is chosen by byte i of SEL from the 64-bit value {S0, S1} (S1 is bytes 0-3, -S0 bytes 4-7). Selector 0x0c gives 0x00 and anything above 0x0c gives 0xff. Reference: LLVM -llvm/lib/Target/AMDGPU/AMDGPUISelLowering.cpp, computeKnownBitsForTargetNode, case AMDGPUISD::PERM. Selectors 8-11 -repeat the sign bit of a 16-bit half of {S0, S1}: bit 15, 31, 47 or 63 (RDNA2 ISA reference, V_PERM_B32; LLVM's -known-bits code treats them as unknown; #211). - -v_alignbit_b32 D, S0, S1, S2: the low 32 bits of ({S0, S1} >> (S2 & 31)), S1 being the low word. -""" -import os -import struct -import sys -import tempfile -import unittest -import warnings - -HERE = os.path.dirname(os.path.abspath(__file__)) -ROOT = os.path.dirname(os.path.dirname(HERE)) -TOOLS_DIR = os.environ.get("LEONIDA_TOOLS_DIR") or os.path.join(ROOT, "tools") - -sys.dont_write_bytecode = True -sys.path.insert(0, TOOLS_DIR) -sys.path.insert(0, HERE) - -import rdna2spirv # noqa: E402 -import spirv_mini_interp as si # noqa: E402 - -MASK32 = 0xFFFFFFFF -STUB_DXBC = b"DXBC" + bytes(24) + struct.pack(" int: - """v_perm_b32 reference for every selector byte.""" - data = ((src0 & MASK32) << 32) | (src1 & MASK32) - out = 0 - for i in range(4): - s = (sel >> (8 * i)) & 0xFF - if s < 8: - byte = (data >> (8 * s)) & 0xFF - elif s < 0x0C: # 8-11: sign bit of the 16-bit half s - 8 - byte = 0xFF if (data >> (16 * (s - 8) + 15)) & 1 else 0x00 - elif s == 0x0C: - byte = 0x00 - else: - byte = 0xFF - out |= byte << (8 * i) - return out - - -def ref_alignbit(src0: int, src1: int, shift: int) -> int: - """v_alignbit_b32 reference: low 32 bits of ({src0, src1} >> (shift & 31)).""" - data = ((src0 & MASK32) << 32) | (src1 & MASK32) - return (data >> (shift & 31)) & MASK32 - - -_TMP_DIR = None -_SRC_PATH = None - - -def setUpModule(): - global _TMP_DIR, _SRC_PATH - _TMP_DIR = tempfile.TemporaryDirectory() - disasm_dir = os.path.join(_TMP_DIR.name, "disasm") - os.mkdir(disasm_dir) - _SRC_PATH = os.path.join(disasm_dir, "ps_perm.s") - with open(os.path.join(_TMP_DIR.name, "ps_perm.dxbc"), "wb") as f: - f.write(STUB_DXBC) - - -def tearDownModule(): - global _TMP_DIR - if _TMP_DIR is not None: - _TMP_DIR.cleanup() - _TMP_DIR = None - - -def run_vop3(op: str, src0: int, src1: int, src2: int, src2_inline: bool = False) -> int: - """Translate and run `op v0, v1, v2, v3` (or with src2 as an inline constant), return the mrt0 word.""" - if _TMP_DIR is None: - setUpModule() - lines = [ - f"\tv_mov_b32 v1, {src0 & MASK32:#x}", - f"\tv_mov_b32 v2, {src1 & MASK32:#x}", - ] - if src2_inline: - lines.append(f"\t{op} v0, v1, v2, {src2}") - else: - lines.append(f"\tv_mov_b32 v3, {src2 & MASK32:#x}") - lines.append(f"\t{op} v0, v1, v2, v3") - asm = "; test_perm_alignbit\n" + "\n".join(lines) + "\n\texp mrt0 v0, v0, v0, v0 done vm\n\ts_endpgm\n" - with open(_SRC_PATH, "w", encoding="utf-8") as f: - f.write(asm) - with warnings.catch_warnings(): - warnings.simplefilter("ignore", ResourceWarning) - spv = rdna2spirv.translate(_SRC_PATH) - return si.run_fragment(spv)["%out_mrt0"][0] - - -class ReferenceTests(unittest.TestCase): - """The references against hand-worked values, so a test failure points at the translator, not the oracle.""" - - def test_perm_reference(self): - self.assertEqual(ref_perm(0x8899AABB, 0x11223344, 0x03020100), 0x11223344) - self.assertEqual(ref_perm(0x8899AABB, 0x11223344, 0x07060504), 0x8899AABB) - self.assertEqual(ref_perm(0x8899AABB, 0x11223344, 0x00010203), 0x44332211) - self.assertEqual(ref_perm(0x8899AABB, 0x11223344, 0x07050301), 0x88AA1133) - self.assertEqual(ref_perm(0x8899AABB, 0x11223344, 0x0C0D0C0D), 0x00FF00FF) - # #211's probe values: S0 = 0x8C7A06F5, S1 = 0x13E49B80; selectors 8 and 11 hit set sign bits. - self.assertEqual(ref_perm(0x8C7A06F5, 0x13E49B80, 0x0B0A0908), 0xFF0000FF) - self.assertEqual(ref_perm(0x00008000, 0x80000000, 0x0B0A0908), 0x00FFFF00) - - def test_alignbit_reference(self): - self.assertEqual(ref_alignbit(0x12345678, 0x9ABCDEF0, 0), 0x9ABCDEF0) - self.assertEqual(ref_alignbit(0x12345678, 0x9ABCDEF0, 8), 0x789ABCDE) - self.assertEqual(ref_alignbit(0x12345678, 0x9ABCDEF0, 16), 0x56789ABC) - self.assertEqual(ref_alignbit(0x12345678, 0x9ABCDEF0, 31), 0x2468ACF1) - self.assertEqual(ref_alignbit(0x12345678, 0x9ABCDEF0, 32), 0x9ABCDEF0) - - -class PermTests(unittest.TestCase): - S0, S1 = 0x8899AABB, 0x11223344 - - def check(self, sel, src0=None, src1=None): - src0 = self.S0 if src0 is None else src0 - src1 = self.S1 if src1 is None else src1 - self.assertEqual(run_vop3("v_perm_b32", src0, src1, sel), ref_perm(src0, src1, sel), - f"src0={src0:#010x} src1={src1:#010x} sel={sel:#010x}") - - def test_whole_words(self): - self.check(0x03020100) # src1 unchanged - self.check(0x07060504) # src0 unchanged - - def test_byte_swaps_and_mixes(self): - for sel in (0x00010203, 0x04050607, 0x07050301, 0x06040200, 0x01000504, 0x03070206): - with self.subTest(sel=hex(sel)): - self.check(sel) - - def test_constant_selectors(self): - for sel in (0x0C0C0C0C, 0x0D0D0D0D, 0xFFFFFFFF, 0x800C7F0D, 0x0C030C07): - with self.subTest(sel=hex(sel)): - self.check(sel) - - def test_every_selector_in_every_byte(self): - # Each defined selector value in each result byte, the other bytes fixed to 0x0c (zero). - for pos in range(4): - for s in PERM_SELECTORS: - sel = (0x0C0C0C0C & ~(0xFF << (8 * pos))) | (s << (8 * pos)) - with self.subTest(pos=pos, s=hex(s)): - self.check(sel) - - def test_inline_selector(self): - # Inline-constant selector 0 picks byte 0 of src1 into every byte. - self.assertEqual(run_vop3("v_perm_b32", self.S0, self.S1, 0, src2_inline=True), 0x44444444) - - def test_other_data(self): - for src0, src1 in ((0, MASK32), (MASK32, 0), (0xDEADBEEF, 0x01234567)): - for sel in (0x03020100, 0x07060504, 0x04000501, 0x0D0C0702): - with self.subTest(src0=hex(src0), src1=hex(src1), sel=hex(sel)): - self.check(sel, src0, src1) - - -class AlignbitTests(unittest.TestCase): - S0, S1 = 0x12345678, 0x9ABCDEF0 - - def test_every_shift(self): - for shift in range(32): - with self.subTest(shift=shift): - self.assertEqual(run_vop3("v_alignbit_b32", self.S0, self.S1, shift), - ref_alignbit(self.S0, self.S1, shift)) - - def test_shift_zero_returns_low_word(self): - self.assertEqual(run_vop3("v_alignbit_b32", self.S0, self.S1, 0), self.S1) - self.assertEqual(run_vop3("v_alignbit_b32", self.S0, self.S1, 0, src2_inline=True), self.S1) - - def test_shift_is_masked_to_5_bits(self): - for shift in (32, 33, 40, 63, 0xFFFFFFE8): - with self.subTest(shift=hex(shift)): - self.assertEqual(run_vop3("v_alignbit_b32", self.S0, self.S1, shift), - ref_alignbit(self.S0, self.S1, shift)) - - def test_inline_shift(self): - for shift in (1, 8, 24, 31): - with self.subTest(shift=shift): - self.assertEqual(run_vop3("v_alignbit_b32", self.S0, self.S1, shift, src2_inline=True), - ref_alignbit(self.S0, self.S1, shift)) - - def test_same_word_is_rotate_right(self): - # v_alignbit_b32 with src0 == src1 is a 32-bit rotate right, a common compiler idiom. - x = 0x80000001 - for shift in (1, 4, 31): - with self.subTest(shift=shift): - want = ((x >> shift) | (x << (32 - shift))) & MASK32 - self.assertEqual(run_vop3("v_alignbit_b32", x, x, shift), want) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_alu_perm_b32.py b/tests/semantic/test_alu_perm_b32.py deleted file mode 100644 index faf0a1929..000000000 --- a/tests/semantic/test_alu_perm_b32.py +++ /dev/null @@ -1,406 +0,0 @@ -"""Semantic interpreter tests for RDNA2 byte permutation (v_perm_b32). - -Exercises shader translation via tools/rdna2spirv.py and execution via -tests/semantic/spirv_mini_interp.py against a plain-Python reference oracle. - -RDNA2 VALU Specification (VOP3 opcode 836, v_perm_b32): - v_perm_b32 D, S0, S1, S2 - Source: 64-bit packed container {S0, S1}, where S1 is the low 32 bits (bytes 0..3) - and S0 is the high 32 bits (bytes 4..7). - Destination: 32-bit register D, containing 4 bytes (i = 0..3). - Selector: 32-bit register or inline constant S2, containing 4 byte selectors: - sel_byte_i = (S2 >> (8 * i)) & 0xFF - - Selector code rules for each result byte i: - - 0..7: Selects byte (sel_byte) directly from {S0, S1}: - 0..3 pick bytes 0..3 from S1 (bits 0..31) - 4..7 pick bytes 0..3 from S0 (bits 32..63) - - 8..11: Sign-extension of 16-bit halves: - Repeats the sign bit (bit 15 or 31) across the entire result byte: - yielding 0xFF if sign bit is 1, or 0x00 if sign bit is 0. - 8 -> sign bit of S1[15:0] (bit 15 of S1, i.e. bit 7 of byte 1) - 9 -> sign bit of S1[31:16] (bit 31 of S1, i.e. bit 7 of byte 3) - 10 -> sign bit of S0[15:0] (bit 15 of S0, i.e. bit 7 of byte 5) - 11 -> sign bit of S0[31:16] (bit 31 of S0, i.e. bit 7 of byte 7) - - 12 (0x0C): Writes constant 0x00. - - >= 13 (0x0D..0xFF): Writes constant 0xFF. - - 4-Nibble Selector Masks: - Because each byte's primary selector code (0x0 through 0xF) fits in 4 bits (a nibble), - common compiler and shader patterns express selector words as 4 packed nibbles: - make_sel(n0, n1, n2, n3) = (n3 << 24) | (n2 << 16) | (n1 << 8) | n0 - -Standard library only; zero game data, zero proprietary assets. -""" -from __future__ import annotations - -import os -import struct -import sys -import tempfile -import unittest -import warnings - -HERE = os.path.dirname(os.path.abspath(__file__)) -ROOT = os.path.dirname(os.path.dirname(HERE)) -TOOLS_DIR = os.environ.get("LEONIDA_TOOLS_DIR") or os.path.join(ROOT, "tools") - -sys.dont_write_bytecode = True -sys.path.insert(0, TOOLS_DIR) -sys.path.insert(0, HERE) - -import rdna2spirv # noqa: E402 -import spirv_mini_interp as si # noqa: E402 - -MASK32 = 0xFFFFFFFF -STUB_DXBC = b"DXBC" + bytes(24) + struct.pack(" int: - """Construct 32-bit selector mask from 4 selector byte codes (nibbles 0x0..0xF or bytes 0x00..0xFF).""" - return ((b0 & 0xFF) | ((b1 & 0xFF) << 8) | ((b2 & 0xFF) << 16) | ((b3 & 0xFF) << 24)) & MASK32 - - -def ref_perm_b32(s0: int, s1: int, sel: int) -> int: - """RDNA2 v_perm_b32 reference oracle.""" - s0 &= MASK32 - s1 &= MASK32 - sel &= MASK32 - packed = (s0 << 32) | s1 - out = 0 - for i in range(4): - sb = (sel >> (8 * i)) & 0xFF - if sb < 8: - byte_val = (packed >> (8 * sb)) & 0xFF - elif sb < 12: - # 8..11: sign bit of 16-bit halfword (sb - 8) - # halfword 0: s1[0..15] -> bit 15 - # halfword 1: s1[16..31] -> bit 31 - # halfword 2: s0[0..15] -> bit 47 - # halfword 3: s0[16..31] -> bit 63 - sign_bit = (packed >> (16 * (sb - 8) + 15)) & 1 - byte_val = 0xFF if sign_bit else 0x00 - elif sb == 12: - byte_val = 0x00 - else: - byte_val = 0xFF - out |= byte_val << (8 * i) - return out & MASK32 - - -_TMP_DIR = None -_SRC_PATH = None - - -def setUpModule(): - global _TMP_DIR, _SRC_PATH - _TMP_DIR = tempfile.TemporaryDirectory() - disasm_dir = os.path.join(_TMP_DIR.name, "disasm") - os.mkdir(disasm_dir) - _SRC_PATH = os.path.join(disasm_dir, "ps_perm_b32.s") - dxbc_path = os.path.join(_TMP_DIR.name, "ps_perm_b32.dxbc") - with open(dxbc_path, "wb") as f: - f.write(STUB_DXBC) - - -def tearDownModule(): - global _TMP_DIR - if _TMP_DIR is not None: - try: - _TMP_DIR.cleanup() - except Exception: - pass - _TMP_DIR = None - - -def run_rdna_perm(s0: int, s1: int, sel: int, inline_sel: bool = False) -> int: - """Translate and run `v_perm_b32 v0, v1, v2, v3` (or inline selector), return mrt0.""" - global _TMP_DIR, _SRC_PATH - if _TMP_DIR is None: - setUpModule() - - lines = [ - f"\tv_mov_b32 v1, {s0 & MASK32:#x}", - f"\tv_mov_b32 v2, {s1 & MASK32:#x}", - ] - if inline_sel: - lines.append(f"\tv_perm_b32 v0, v1, v2, {sel & MASK32:#x}") - else: - lines.append(f"\tv_mov_b32 v3, {sel & MASK32:#x}") - lines.append("\tv_perm_b32 v0, v1, v2, v3") - - asm = "; test_perm_b32\n" + "\n".join(lines) + "\n\texp mrt0 v0, v0, v0, v0 done vm\n\ts_endpgm\n" - with open(_SRC_PATH, "w", encoding="utf-8") as f: - f.write(asm) - - with warnings.catch_warnings(): - warnings.simplefilter("ignore", ResourceWarning) - spv = rdna2spirv.translate(_SRC_PATH) - - out = si.run_fragment(spv) - return out["%out_mrt0"][0] - - -class ReferenceOracleTests(unittest.TestCase): - """Test the Python reference oracle against known hand-computed values.""" - - S0 = 0xAABBCCDD # Bytes: 4=0xDD, 5=0xCC, 6=0xBB, 7=0xAA - S1 = 0x11223344 # Bytes: 0=0x44, 1=0x33, 2=0x22, 3=0x11 - - def test_identity_and_endian_swaps(self): - # Identity on src1 and src0 - self.assertEqual(ref_perm_b32(self.S0, self.S1, make_sel(0, 1, 2, 3)), 0x11223344) - self.assertEqual(ref_perm_b32(self.S0, self.S1, make_sel(4, 5, 6, 7)), 0xAABBCCDD) - # Endian byte swap - self.assertEqual(ref_perm_b32(self.S0, self.S1, make_sel(3, 2, 1, 0)), 0x44332211) - self.assertEqual(ref_perm_b32(self.S0, self.S1, make_sel(7, 6, 5, 4)), 0xDDCCBBAA) - - def test_constant_zero_and_ff_injections(self): - # Selector 12 -> 0x00, Selector 13..15 -> 0xFF - self.assertEqual(ref_perm_b32(self.S0, self.S1, make_sel(12, 12, 12, 12)), 0x00000000) - self.assertEqual(ref_perm_b32(self.S0, self.S1, make_sel(13, 13, 13, 13)), 0xFFFFFFFF) - self.assertEqual(ref_perm_b32(self.S0, self.S1, make_sel(14, 15, 13, 14)), 0xFFFFFFFF) - self.assertEqual(ref_perm_b32(self.S0, self.S1, make_sel(12, 13, 12, 13)), 0xFF00FF00) - self.assertEqual(ref_perm_b32(self.S0, self.S1, make_sel(0x10, 0x7F, 0x80, 0xFF)), 0xFFFFFFFF) - - def test_sign_extension_rules(self): - # S1 low half: bit 15 -> selector 8 - # S1 high half: bit 31 -> selector 9 - # S0 low half: bit 15 (bit 47) -> selector 10 - # S0 high half: bit 31 (bit 63) -> selector 11 - # Test all sign bits = 0 - self.assertEqual(ref_perm_b32(0x7FFF7FFF, 0x7FFF7FFF, make_sel(8, 9, 10, 11)), 0x00000000) - # Test all sign bits = 1 - self.assertEqual(ref_perm_b32(0x80008000, 0x80008000, make_sel(8, 9, 10, 11)), 0xFFFFFFFF) - # Test individual sign bits - self.assertEqual(ref_perm_b32(0x00000000, 0x00008000, make_sel(8, 9, 10, 11)), 0x000000FF) - self.assertEqual(ref_perm_b32(0x00000000, 0x80000000, make_sel(8, 9, 10, 11)), 0x0000FF00) - self.assertEqual(ref_perm_b32(0x00008000, 0x00000000, make_sel(8, 9, 10, 11)), 0x00FF0000) - self.assertEqual(ref_perm_b32(0x80000000, 0x00000000, make_sel(8, 9, 10, 11)), 0xFF000000) - - def test_broadcast_and_interleave(self): - # Broadcast byte 0 of S1 (0x44) - self.assertEqual(ref_perm_b32(self.S0, self.S1, make_sel(0, 0, 0, 0)), 0x44444444) - # Broadcast byte 3 of S0 (byte 7 = 0xAA) - self.assertEqual(ref_perm_b32(self.S0, self.S1, make_sel(7, 7, 7, 7)), 0xAAAAAAAA) - # Interleave low bytes of S1 and S0: 0, 4, 1, 5 -> 0xCC, 0x33, 0xDD, 0x44 - self.assertEqual(ref_perm_b32(self.S0, self.S1, make_sel(0, 4, 1, 5)), 0xCC33DD44) - - -class AluPermB32SemanticTests(unittest.TestCase): - """End-to-end interpreter tests verifying rdna2spirv translation and SPIR-V execution.""" - - S0 = 0xAABBCCDD # Bytes: 4=0xDD, 5=0xCC, 6=0xBB, 7=0xAA - S1 = 0x11223344 # Bytes: 0=0x44, 1=0x33, 2=0x22, 3=0x11 - - def _check(self, s0: int, s1: int, sel: int, inline: bool = False): - expected = ref_perm_b32(s0, s1, sel) - actual = run_rdna_perm(s0, s1, sel, inline_sel=inline) - self.assertEqual( - actual, - expected, - f"Mismatch: s0={s0:#010x} s1={s1:#010x} sel={sel:#010x} (inline={inline}) " - f"expected={expected:#010x} got={actual:#010x}", - ) - - def test_identity_and_word_moves(self): - # Identity S1 - self._check(self.S0, self.S1, make_sel(0, 1, 2, 3)) - # Identity S0 - self._check(self.S0, self.S1, make_sel(4, 5, 6, 7)) - - def test_endianness_byte_reversal(self): - # 32-bit endianness reverse of S1 - self._check(self.S0, self.S1, make_sel(3, 2, 1, 0)) - # 32-bit endianness reverse of S0 - self._check(self.S0, self.S1, make_sel(7, 6, 5, 4)) - # 16-bit halfword endianness reverse of S1 - self._check(self.S0, self.S1, make_sel(1, 0, 3, 2)) - # 16-bit halfword swap (words exchanged) - self._check(self.S0, self.S1, make_sel(2, 3, 0, 1)) - - def test_64bit_endian_swap_pair(self): - # Full 64-bit endian swap across {S0, S1} using two v_perm_b32 instructions: - # High dword of result: S1 reversed -> make_sel(3, 2, 1, 0) - # Low dword of result: S0 reversed -> make_sel(7, 6, 5, 4) - self._check(self.S0, self.S1, make_sel(7, 6, 5, 4)) - self._check(self.S0, self.S1, make_sel(3, 2, 1, 0)) - - def test_four_nibble_mask_packing(self): - # Explicit test verifying 4-nibble selector masks (n0, n1, n2, n3 in 0x0..0xF): - # e.g., nibbles (0x0, 0xC, 0x8, 0xD) -> byte0=0x00, byte1=0x0C, byte2=0x08, byte3=0x0D - sel = make_sel(0x0, 0xC, 0x8, 0xD) - # With S1=0x00008044 (byte 0=0x44, halfword 0 has sign bit set): - # byte 0 (code 0) -> S1 byte 0 = 0x44 - # byte 1 (code 12 / 0xC) -> 0x00 - # byte 2 (code 8) -> sign bit of S1[15:0] = 1 -> 0xFF - # byte 3 (code 13 / 0xD) -> 0xFF - self._check(0x00000000, 0x00008044, sel) - - def test_byte_broadcast_all_lanes(self): - # Broadcast each of the 8 input bytes across all 4 result byte positions - for b in range(8): - with self.subTest(byte=b): - self._check(self.S0, self.S1, make_sel(b, b, b, b)) - - def test_every_nibble_selector_code_in_every_position(self): - # Test all 16 selector nibbles (0x0 through 0xF) in each byte position 0..3, - # with remaining positions filled with selector 12 (0x00 zero injection). - # We test with a mixed operand pair where sign bits are set so selectors 8..11 - # and 13..15 can be distinctly validated. - s0 = 0x8C7A06F5 - s1 = 0x13E49B80 - for pos in range(4): - for code in range(16): - nibbles = [12, 12, 12, 12] - nibbles[pos] = code - sel = make_sel(*nibbles) - with self.subTest(pos=pos, code=hex(code)): - self._check(s0, s1, sel) - - def test_sign_extension_rules_truth_table(self): - # Selectors 8, 9, 10, 11 inspect the sign bits of 4 halfwords: - # 8 -> S1[15] - # 9 -> S1[31] - # 10 -> S0[15] - # 11 -> S0[31] - # The selector 0x0B0A0908 maps (byte0<-8, byte1<-9, byte2<-10, byte3<-11). - # We test all 16 combinations of (sign_s1_lo, sign_s1_hi, sign_s0_lo, sign_s0_hi). - sel = make_sel(8, 9, 10, 11) - for s1_lo in (0, 1): - for s1_hi in (0, 1): - for s0_lo in (0, 1): - for s0_hi in (0, 1): - s1 = (s1_lo << 15) | (s1_hi << 31) - s0 = (s0_lo << 15) | (s0_hi << 31) - expected_bytes = [ - 0xFF if s1_lo else 0x00, - 0xFF if s1_hi else 0x00, - 0xFF if s0_lo else 0x00, - 0xFF if s0_hi else 0x00, - ] - expected = ( - expected_bytes[0] - | (expected_bytes[1] << 8) - | (expected_bytes[2] << 16) - | (expected_bytes[3] << 24) - ) - with self.subTest(s1_lo=s1_lo, s1_hi=s1_hi, s0_lo=s0_lo, s0_hi=s0_hi): - actual = run_rdna_perm(s0, s1, sel) - self.assertEqual(actual, expected) - - def test_sign_extension_with_realistic_values(self): - # 16-bit signed boundary values: - # Positive max: 0x7FFF (sign bit 0 -> 0x00) - # Negative min: 0x8000 (sign bit 1 -> 0xFF) - # -1 as i16: 0xFFFF (sign bit 1 -> 0xFF) - # 0 as i16: 0x0000 (sign bit 0 -> 0x00) - sel = make_sel(8, 9, 10, 11) - s1 = 0x80007FFF # S1 low is +0x7FFF (sign=0), S1 high is -0x8000 (sign=1) - s0 = 0x0000FFFF # S0 low is -1 (sign=1), S0 high is 0 (sign=0) - self._check(s0, s1, sel) - - def test_constant_zero_injection_selector_12(self): - # Selector 12 (0x0C) injects 0x00 regardless of operands - self._check(0xFFFFFFFF, 0xFFFFFFFF, make_sel(12, 12, 12, 12)) - self._check(self.S0, self.S1, make_sel(0, 12, 1, 12)) - self._check(self.S0, self.S1, make_sel(12, 4, 12, 5)) - - def test_constant_ff_injection_selectors_ge_13(self): - # Selector >= 13 injects 0xFF regardless of operands - self._check(0x00000000, 0x00000000, make_sel(13, 14, 15, 13)) - self._check(self.S0, self.S1, make_sel(0, 13, 1, 14)) - # Byte values with top bits set (0x10, 0x7F, 0x80, 0xFF) - for code in (0x10, 0x20, 0x7F, 0x80, 0xFE, 0xFF): - with self.subTest(code=hex(code)): - self._check(self.S0, self.S1, make_sel(code, 0, code, 1)) - - def test_inline_constant_selectors(self): - # Direct immediate constant in place of VGPR selector - # Identity S1 - self._check(self.S0, self.S1, make_sel(0, 1, 2, 3), inline=True) - # Identity S0 - self._check(self.S0, self.S1, make_sel(4, 5, 6, 7), inline=True) - # All zeros - self._check(self.S0, self.S1, make_sel(12, 12, 12, 12), inline=True) - # All 0xFF - self._check(self.S0, self.S1, make_sel(13, 13, 13, 13), inline=True) - # Sign extension - self._check(0x80000000, 0x00008000, make_sel(8, 9, 10, 11), inline=True) - - def test_common_shader_idioms(self): - # 1. 16-bit sign extension to 32-bit (i16 to i32) - # Low half of S1 sign-extended: byte 0, byte 1, then sign extension from half 0 (sel 8) - sel_i16_lo = make_sel(0, 1, 8, 8) - self._check(0, 0x00007FFF, sel_i16_lo) # +32767 -> 0x00007FFF - self._check(0, 0x00008000, sel_i16_lo) # -32768 -> 0xFFFF8000 - self._check(0, 0x0000FFFF, sel_i16_lo) # -1 -> 0xFFFFFFFF - - # High half of S1 sign-extended: byte 2, byte 3, then sign extension from half 1 (sel 9) - sel_i16_hi = make_sel(2, 3, 9, 9) - self._check(0, 0x7FFF0000, sel_i16_hi) # +32767 -> 0x00007FFF - self._check(0, 0x80000000, sel_i16_hi) # -32768 -> 0xFFFF8000 - - # 2. 16-bit zero extension to 32-bit (u16 to u32) - # Low half zero-extended: byte 0, byte 1, sel 12, sel 12 - sel_u16_lo = make_sel(0, 1, 12, 12) - self._check(0, 0x1234FFFF, sel_u16_lo) # -> 0x0000FFFF - - # 3. Channel swizzles: - # Assume S1 is RGBA (R=byte0, G=byte1, B=byte2, A=byte3) - # Swizzle to BGRA: byte 2, byte 1, byte 0, byte 3 - self._check(0, 0x11223344, make_sel(2, 1, 0, 3)) - # Swizzle to ARGB: byte 3, byte 0, byte 1, byte 2 - self._check(0, 0x11223344, make_sel(3, 0, 1, 2)) - # Swizzle to ABGR: byte 3, byte 2, byte 1, byte 0 - self._check(0, 0x11223344, make_sel(3, 2, 1, 0)) - - # 4. Packing two 16-bit halves into one word: - # Low 16 bits of S1 and low 16 bits of S0: 0, 1, 4, 5 - self._check(0x12345678, 0x9ABCDEF0, make_sel(0, 1, 4, 5)) - # High 16 bits of S1 and high 16 bits of S0: 2, 3, 6, 7 - self._check(0x12345678, 0x9ABCDEF0, make_sel(2, 3, 6, 7)) - - # 5. Interleaving bytes (zip): - self._check(0x12345678, 0x9ABCDEF0, make_sel(0, 4, 1, 5)) - self._check(0x12345678, 0x9ABCDEF0, make_sel(2, 6, 3, 7)) - - def test_boundary_operands(self): - # All zeros - self._check(0x00000000, 0x00000000, make_sel(0, 1, 2, 3)) - # All ones - self._check(0xFFFFFFFF, 0xFFFFFFFF, make_sel(0, 1, 2, 3)) - # Alternating bit patterns - s0 = 0xAAAAAAAA - s1 = 0x55555555 - self._check(s0, s1, make_sel(0, 4, 1, 5)) - self._check(s0, s1, make_sel(8, 9, 10, 11)) - - def test_negative_controls(self): - # Mutating selector changes output - sel_good = make_sel(0, 1, 2, 3) - sel_bad = make_sel(0, 1, 2, 2) - res_good = run_rdna_perm(self.S0, self.S1, sel_good) - res_bad = run_rdna_perm(self.S0, self.S1, sel_bad) - self.assertNotEqual(res_good, res_bad) - - # Mutating active source byte changes output - res1 = run_rdna_perm(self.S0, 0x11223344, make_sel(0, 1, 2, 3)) - res2 = run_rdna_perm(self.S0, 0x11223355, make_sel(0, 1, 2, 3)) - self.assertNotEqual(res1, res2) - - # Mutating inactive source byte does not change output - # Selector only picks bytes 0..3 from S1, so modifying S0 must not change result - res_s0_a = run_rdna_perm(0x11111111, self.S1, make_sel(0, 1, 2, 3)) - res_s0_b = run_rdna_perm(0x22222222, self.S1, make_sel(0, 1, 2, 3)) - self.assertEqual(res_s0_a, res_s0_b) - - # Toggling sign bit flips result between 0x00 and 0xFF for sign selectors - res_pos = run_rdna_perm(0, 0x00007FFF, make_sel(8, 12, 12, 12)) - res_neg = run_rdna_perm(0, 0x00008000, make_sel(8, 12, 12, 12)) - self.assertEqual(res_pos & 0xFF, 0x00) - self.assertEqual(res_neg & 0xFF, 0xFF) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_alu_pk_int16.py b/tests/semantic/test_alu_pk_int16.py deleted file mode 100644 index 506529ff3..000000000 --- a/tests/semantic/test_alu_pk_int16.py +++ /dev/null @@ -1,177 +0,0 @@ -"""Semantic interpreter tests for RDNA2 packed 16-bit integer VOP3P ops. - -v_pk_add/sub_u16/i16, v_pk_mul_lo_u16, v_pk_mad_u16/i16 and v_pk_max/min_u16/i16. Result half 0 takes each source's -half from op_sel[i], result half 1 from op_sel_hi[i] (defaults [0,..], [1,..]); each half wraps to 16 bits, and clamp -saturates add/sub/mad to the type's range while acting as a hardware no-op on mul_lo/max/min. A constant operand reads as a 32-bit dword under op_sel/op_sel_hi -(op_sel=0 selects bits [15:0], op_sel=1 selects bits [31:16], measured on gfx1036). Each case translates a synthetic pixel shader with tools/rdna2spirv.py and runs it in -tests/semantic/spirv_mini_interp.py; D leaves through exp as 16-bit halves ORed into 0x40000000. Standard library -only; no GPU, no game files. -""" -import os -import random -import struct -import sys -import tempfile -import unittest -import warnings - -HERE = os.path.dirname(os.path.abspath(__file__)) -ROOT = os.path.dirname(os.path.dirname(HERE)) -sys.dont_write_bytecode = True -sys.path.insert(0, os.environ.get("LEONIDA_TOOLS_DIR") or os.path.join(ROOT, "tools")) -sys.path.insert(0, HERE) - -import rdna2spirv # noqa: E402 -import spirv_mini_interp as si # noqa: E402 - -STUB_DXBC = b"DXBC" + bytes(24) + struct.pack("> 15 else x - - -def ref(op, srcs, sel=None, selhi=None, clamp=False): - ns = len(srcs) - sel, selhi = sel or [0] * ns, selhi or [1] * ns - signed = op.endswith("i16") - kind = op[len("v_pk_"):].rsplit("_", 1)[0] - out = 0 - for h, sl in enumerate((sel, selhi)): - v = [(srcs[i] >> (16 * sl[i])) & 0xFFFF for i in range(ns)] - if signed: - v = [s16(x) for x in v] - r = {"add": lambda: v[0] + v[1], "sub": lambda: v[0] - v[1], "mul_lo": lambda: v[0] * v[1], - "mad": lambda: v[0] * v[1] + v[2], "max": lambda: max(v[0], v[1]), "min": lambda: min(v[0], v[1])}[kind]() - if clamp and kind in ("add", "sub", "mad"): - r = max(-32768, min(32767, r)) if signed else max(0, min(0xFFFF, r)) - out |= (r & 0xFFFF) << (16 * h) - return out - - -_TMP = None - - -def translate(lines): - global _TMP - if _TMP is None: - _TMP = tempfile.TemporaryDirectory() - os.mkdir(os.path.join(_TMP.name, "disasm")) - with open(os.path.join(_TMP.name, "ps_pk_int16.dxbc"), "wb") as f: - f.write(STUB_DXBC) - src = os.path.join(_TMP.name, "disasm", "ps_pk_int16.s") - with open(src, "w", encoding="utf-8") as f: - f.write("; ps_pk_int16\n" + "".join(f"\t{ln}\n" for ln in lines)) - with warnings.catch_warnings(): - warnings.simplefilter("ignore", ResourceWarning) - return rdna2spirv.translate(src) - - -def tearDownModule(): - if _TMP is not None: - _TMP.cleanup() - - -def run(line, srcs): - lines = [f"v_mov_b32 v{1 + i}, {v:#x}" for i, v in enumerate(srcs)] + ["v_mov_b32 v0, 0xdeadbeef", line, - "v_and_b32 v5, 0xffff, v0", "v_lshrrev_b32 v6, 16, v0", "v_or_b32 v5, 0x40000000, v5", - "v_or_b32 v6, 0x40000000, v6", "exp mrt0 v5, v6, v5, v5 done vm", "s_endpgm"] - lo, hi = si.run_fragment(translate(lines))["%out_mrt0"][:2] - assert lo >> 16 == 0x4000 and hi >> 16 == 0x4000, (hex(lo), hex(hi)) - return (lo & 0xFFFF) | (hi & 0xFFFF) << 16 - - -TWO = ["v_pk_add_u16", "v_pk_add_i16", "v_pk_sub_u16", "v_pk_sub_i16", "v_pk_mul_lo_u16", "v_pk_max_u16", - "v_pk_max_i16", "v_pk_min_u16", "v_pk_min_i16"] -THREE = ["v_pk_mad_u16", "v_pk_mad_i16"] -WORDS = [0, 0x00010002, 0xFFFF0001, 0x80007FFF, 0x7FFF8000, 0x12345678, 0xFFFFFFFF, 0x00FF0100] - - -def opsel(name, bits): - return f" {name}:[{','.join(map(str, bits))}]" - - -class PkInt16Tests(unittest.TestCase): - def test_reference(self): - self.assertEqual(ref("v_pk_add_u16", [0xFFFF0001, 0x00010002]), 0x00000003) # hi wraps - self.assertEqual(ref("v_pk_add_u16", [0xFFFF0001, 0x00010002], clamp=True), 0xFFFF0003) - self.assertEqual(ref("v_pk_sub_u16", [0x00010001, 0x00020000], clamp=True), 0x00000001) - self.assertEqual(ref("v_pk_add_i16", [0x7FFF8000, 0x0001FFFF], clamp=True), 0x7FFF8000) - self.assertEqual(ref("v_pk_max_i16", [0x8000FFFF, 0x00010000]), 0x00010000) - - def test_two_source_ops(self): - for op in TWO: - for x in WORDS: - for y in WORDS[::2]: - with self.subTest(op=op, x=hex(x), y=hex(y)): - self.assertEqual(run(f"{op} v0, v1, v2", [x, y]), ref(op, [x, y])) - - def test_mad(self): - rng = random.Random(0x9A16) - for op in THREE: - for _ in range(12): - srcs = [rng.getrandbits(32) for _ in range(3)] - with self.subTest(op=op, srcs=[hex(s) for s in srcs]): - self.assertEqual(run(f"{op} v0, v1, v2, v3", srcs), ref(op, srcs)) - - def test_op_sel(self): - x, y, z = 0x11112222, 0x33334444, 0x55556666 - for sel, selhi in (([1, 0], [0, 1]), ([1, 1], [0, 0]), ([0, 1], [1, 0])): - for op in ("v_pk_add_u16", "v_pk_sub_i16", "v_pk_max_u16"): - with self.subTest(op=op, sel=sel, selhi=selhi): - line = f"{op} v0, v1, v2" + opsel("op_sel", sel) + opsel("op_sel_hi", selhi) - self.assertEqual(run(line, [x, y]), ref(op, [x, y], sel, selhi)) - line = "v_pk_mad_u16 v0, v1, v2, v3" + opsel("op_sel", [1, 0, 1]) + opsel("op_sel_hi", [0, 1, 0]) - self.assertEqual(run(line, [x, y, z]), ref("v_pk_mad_u16", [x, y, z], [1, 0, 1], [0, 1, 0])) - - def test_clamp(self): - for op in ("v_pk_add_u16", "v_pk_add_i16", "v_pk_sub_u16", "v_pk_sub_i16", - "v_pk_mul_lo_u16", "v_pk_max_u16", "v_pk_min_u16", "v_pk_max_i16", "v_pk_min_i16"): - for x in WORDS: - for y in WORDS[1::2]: - with self.subTest(op=op, x=hex(x), y=hex(y)): - self.assertEqual(run(f"{op} v0, v1, v2 clamp", [x, y]), ref(op, [x, y], clamp=True)) - for op in THREE: - srcs = [0x7FFFFFFF, 0x7FFF0002, 0x7FFF8000] - with self.subTest(op=op): - self.assertEqual(run(f"{op} v0, v1, v2, v3 clamp", srcs), ref(op, srcs, clamp=True)) - - def test_constant_operands_op_sel(self): - # Integer constants are treated as 32-bit dwords: op_sel selects bits [15:0] (0) or [31:16] (1). - # Positive inline constants zero-extend (5 -> 0x00000005: lo=5, hi=0). - # Default op_sel:[0,0] op_sel_hi:[1,1]: half 0 adds 5, half 1 adds 0. - self.assertEqual(run("v_pk_add_u16 v0, v1, 5", [0x00100020]), 0x00100025) - # Explicit op_sel_hi:[1,0]: both halves add 5. - self.assertEqual(run("v_pk_add_u16 v0, v1, 5 op_sel_hi:[1,0]", [0x00100020]), 0x00150025) - # Positive inline constant 64 (0x00000040: lo=64, hi=0) - self.assertEqual(run("v_pk_add_u16 v0, v1, 64", [0x00100020]), 0x00100060) - # Negative inline constant -1 sign-extends to 0xFFFFFFFF (lo=0xFFFF, hi=0xFFFF). - self.assertEqual(run("v_pk_sub_i16 v0, v1, -1", [0x00100020]), 0x00110021) - self.assertEqual(run("v_pk_add_i16 v0, v1, -1", [0x00100020]), 0x000F001F) - # Negative inline constant -16 sign-extends to 0xFFFFFFF0 (lo=0xFFF0, hi=0xFFFF). - # op_sel:[0,0] op_sel_hi:[1,1]: half 0 subtracts 0xFFF0 (-16, adds 16 -> 0x0030), half 1 subtracts 0xFFFF (-1, adds 1 -> 0x0011). - self.assertEqual(run("v_pk_sub_i16 v0, v1, -16", [0x00100020]), 0x00110030) - # 32-bit literal 0x12345678: lo=0x5678, hi=0x1234. - self.assertEqual(run("v_pk_add_u16 v0, v1, 0x12345678", [0x00100020]), 0x12445698) - # 32-bit literal with op_sel permutation - self.assertEqual(run("v_pk_add_u16 v0, v1, 0x12345678 op_sel:[1,0] op_sel_hi:[1,0]", [0x00100020]), 0x56885688) - # 32-bit literal 0x80017fff: lo=0x7fff, hi=0x8001 - self.assertEqual(run("v_pk_add_i16 v0, v1, 0x80017fff", [0x00100020]), 0x8011801f) - # clamp with constant operand - self.assertEqual(run("v_pk_add_u16 v0, v1, 5 clamp", [0xFFFF0001]), 0xFFFF0006) - self.assertEqual(run("v_pk_sub_u16 v0, v1, 5 clamp", [0x00040010]), 0x0004000b) - self.assertEqual(run("v_pk_sub_u16 v0, v1, 5 op_sel_hi:[1,0] clamp", [0x00040010]), 0x0000000b) - self.assertEqual(run("v_pk_mad_u16 v0, v1, 5, v2 clamp", [0x00100020, 0x00010002]), 0x000100a2) - - def test_rejected_forms(self): - for line in ("v_pk_add_u16 v0, v1, v2 neg_lo:[1,0]", - "v_pk_mul_lo_u16 v0, v1, v2 neg_hi:[0,1]", "v_pk_max_u16 v0, v1, v2 mul:2"): - with self.subTest(line=line): - with self.assertRaises(rdna2spirv.Unsupported): - translate(["v_mov_b32 v1, 1", "v_mov_b32 v2, 2", line, "exp mrt0 v0, v0, v0, v0 done vm", - "s_endpgm"]) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_alu_qsad.py b/tests/semantic/test_alu_qsad.py deleted file mode 100644 index 29ff44323..000000000 --- a/tests/semantic/test_alu_qsad.py +++ /dev/null @@ -1,143 +0,0 @@ -"""Semantic interpreter tests for RDNA2 v_qsad_pk_u16_u8 and v_mqsad_pk_u16_u8. - -Four byte-SADs at once (RDNA ISA pseudocode). S0 is 64 bits, S1 32 bits, S2 and D 64 bits holding four u16 fields: - D.u16[k] = (S2.u16[k] + sum over the 4 bytes of |W_k.byte - S1.byte|) & 0xFFFF, W_k = S0 bits [8k+31 : 8k] -so the four windows slide over S0 one byte at a time. v_mqsad_pk_u16_u8 is masked: a byte where S1's byte is 0 adds -nothing (as v_msad_u8). Each case translates a synthetic pixel shader with tools/rdna2spirv.py, runs it in -tests/semantic/spirv_mini_interp.py and compares D with a plain-Python reference. D leaves through exp as four -16-bit fields ORed into 0x40000000, so no export channel is a NaN or denormal pattern that a float round trip could -change. -""" -import os -import random -import struct -import sys -import tempfile -import unittest -import warnings - -HERE = os.path.dirname(os.path.abspath(__file__)) -ROOT = os.path.dirname(os.path.dirname(HERE)) -TOOLS_DIR = os.environ.get("LEONIDA_TOOLS_DIR") or os.path.join(ROOT, "tools") - -sys.dont_write_bytecode = True -sys.path.insert(0, TOOLS_DIR) -sys.path.insert(0, HERE) - -import rdna2spirv # noqa: E402 -import spirv_mini_interp as si # noqa: E402 - -M64 = (1 << 64) - 1 -STUB_DXBC = b"DXBC" + bytes(24) + struct.pack(" int: - out = 0 - for k in range(4): - win = (x >> (8 * k)) & 0xFFFFFFFF - s = 0 - for i in range(4): - a, b = (win >> (8 * i)) & 0xFF, (y >> (8 * i)) & 0xFF - if op == "v_mqsad_pk_u16_u8" and b == 0: - continue - s += abs(a - b) - out |= ((((acc >> (16 * k)) & 0xFFFF) + s) & 0xFFFF) << (16 * k) - return out - - -OPS = ("v_qsad_pk_u16_u8", "v_mqsad_pk_u16_u8") -X64 = [0, M64, 0x0807060504030201, 0xFF00FF00FF00FF00, 0x0123456789ABCDEF, 0x8080808080808080] -Y32 = [0, 0xFFFFFFFF, 0x04030201, 0x00FF00FF, 0x80808080, 0x12000034] -ACC = [0, 0xFFFFFFFFFFFFFFFF, 0x0001000200030004, 0xFC00FC00FC00FC00] - -_TMP_DIR = None -_SRC_PATH = None - - -def setUpModule(): - global _TMP_DIR, _SRC_PATH - _TMP_DIR = tempfile.TemporaryDirectory() - disasm_dir = os.path.join(_TMP_DIR.name, "disasm") - os.mkdir(disasm_dir) - _SRC_PATH = os.path.join(disasm_dir, "ps_qsad.s") - with open(os.path.join(_TMP_DIR.name, "ps_qsad.dxbc"), "wb") as f: - f.write(STUB_DXBC) - - -def tearDownModule(): - global _TMP_DIR - if _TMP_DIR is not None: - _TMP_DIR.cleanup() - _TMP_DIR = None - - -def run_lines(lines) -> int: - """Run the lines, return v[0:1] (exported as four 16-bit fields, see the module docstring).""" - if _TMP_DIR is None: - setUpModule() - lines = list(lines) + ["v_and_b32 v20, 0xffff, v0", "v_lshrrev_b32 v21, 16, v0", "v_and_b32 v22, 0xffff, v1", - "v_lshrrev_b32 v23, 16, v1"] + [f"v_or_b32 v{r}, 0x40000000, v{r}" for r in range(20, 24)] - asm = "; test_qsad\n" + "".join(f"\t{ln}\n" for ln in lines) + "\texp mrt0 v20, v21, v22, v23 done vm\n\ts_endpgm\n" - with open(_SRC_PATH, "w", encoding="utf-8") as f: - f.write(asm) - with warnings.catch_warnings(): - warnings.simplefilter("ignore", ResourceWarning) - spv = rdna2spirv.translate(_SRC_PATH) - w = si.run_fragment(spv)["%out_mrt0"] - assert all(v >> 16 == 0x4000 for v in w), [hex(v) for v in w] - return sum((v & 0xFFFF) << (16 * i) for i, v in enumerate(w)) - - -def run_op(op: str, x: int, y: int, acc: int) -> int: - return run_lines([f"v_mov_b32 v2, {x & 0xFFFFFFFF:#x}", f"v_mov_b32 v3, {x >> 32:#x}", f"v_mov_b32 v4, {y:#x}", - f"v_mov_b32 v6, {acc & 0xFFFFFFFF:#x}", f"v_mov_b32 v7, {acc >> 32:#x}", - f"{op} v[0:1], v[2:3], v4, v[6:7]"]) - - -class QsadTests(unittest.TestCase): - def test_reference(self): - # Window k of 0x0807060504030201 is bytes k+1..k+4; against S1 = 0x04030201 the SADs are 0, 4, 8, 12. - self.assertEqual(ref("v_qsad_pk_u16_u8", 0x0807060504030201, 0x04030201, 0), 0x000C000800040000) - self.assertEqual(ref("v_qsad_pk_u16_u8", 0, 0xFFFFFFFF, 0xFFFFFFFFFFFFFFFF), 0x03FB03FB03FB03FB) # wraps - self.assertEqual(ref("v_mqsad_pk_u16_u8", M64, 0, 5), 5) # all masked - - def test_edge_values(self): - for op in OPS: - for x in X64: - for y in Y32: - acc = ACC[(x ^ y) % len(ACC)] - with self.subTest(op=op, x=hex(x), y=hex(y), acc=hex(acc)): - self.assertEqual(run_op(op, x, y, acc), ref(op, x, y, acc)) - - def test_seeded(self): - rng = random.Random(0x95AD) - for _ in range(30): - op = rng.choice(OPS) - x, y, acc = rng.getrandbits(64), rng.getrandbits(32), rng.getrandbits(64) - if op == "v_mqsad_pk_u16_u8" and rng.random() < 0.5: - y &= rng.choice([0xFF00FF00, 0x00FFFF00, 0xFFFFFF00]) - with self.subTest(op=op, x=hex(x), y=hex(y), acc=hex(acc)): - self.assertEqual(run_op(op, x, y, acc), ref(op, x, y, acc)) - - def test_null_pixel_source_and_null_accumulator(self) -> None: - x, y, acc = 0x0807060504030201, 0x04000201, 0x0004000300020001 - setup = [f"v_mov_b32 v2, {x & 0xffffffff:#x}", f"v_mov_b32 v3, {x >> 32:#x}", f"v_mov_b32 v4, {y:#x}", - f"v_mov_b32 v6, {acc & 0xffffffff:#x}", f"v_mov_b32 v7, {acc >> 32:#x}"] - for op in OPS: - for source, accumulator, expected in (("null", "v[6:7]", ref(op, 0, y, acc)), - ("v[2:3]", "null", ref(op, x, y, 0))): - with self.subTest(op=op, source=source, accumulator=accumulator): - self.assertEqual(run_lines(setup + [f"{op} v[0:1], {source}, v4, {accumulator}"]), expected) - - def test_sgpr_pair_and_inline_accumulator(self): - got = run_lines(["s_mov_b32 s2, 0x04030201", "s_mov_b32 s3, 0x08070605", "v_mov_b32 v4, 0x04030201", - "v_qsad_pk_u16_u8 v[0:1], s[2:3], v4, 1"]) - self.assertEqual(got, ref("v_qsad_pk_u16_u8", 0x0807060504030201, 0x04030201, 1)) - - def test_clamp_is_rejected_not_guessed(self): - with self.assertRaises(rdna2spirv.Unsupported): - run_lines(["v_qsad_pk_u16_u8 v[0:1], v[2:3], v4, v[6:7] clamp"]) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_alu_rcp.py b/tests/semantic/test_alu_rcp.py deleted file mode 100644 index cc35d3a1e..000000000 --- a/tests/semantic/test_alu_rcp.py +++ /dev/null @@ -1,495 +0,0 @@ -"""Semantic interpreter tests for RDNA2 v_rcp_f32 and v_rsq_f32 approximations. - -The tests model reciprocal and reciprocal square root floating-point approximations: - - v_rcp_f32: D.f32 = 1.0 / S0.f32, emitted in SPIR-V as OpFDiv %float %f1 %x. - - v_rsq_f32: D.f32 = 1.0 / sqrt(S0.f32), emitted in SPIR-V as OpExtInst %float %glsl InverseSqrt %x. - -Approximation bounds and ISA semantics (AMD RDNA2 ISA / GLSL.std.450 / SPIR-V): - - Bit-exactness on power-of-two denominators: - For v_rcp_f32, exact powers of 2 (such as 1.0, 2.0, 4.0, 0.5, 0.25, 0.125, etc.) have bit-exact - binary32 reciprocals without rounding loss. - For v_rsq_f32, exact powers of 4 (such as 1.0, 4.0, 16.0, 64.0, 0.25, 0.0625, etc.) have bit-exact - binary32 reciprocal square roots. - - General finite approximation envelope: - For general non-power-of-two inputs, results are compared against reference double precision - computations (1.0 / x and 1.0 / math.sqrt(x)) within single-precision tolerance (relative error - <= 1.5e-7, corresponding to <= 1 ULP round-to-nearest float32 precision). - - Special floating-point values: - v_rcp_f32: +inf -> +0.0, -inf -> -0.0, NaN -> NaN. - v_rsq_f32: +inf -> 0.0, NaN -> NaN. - - Domain exceptions: - SPIR-V leaves OpFDiv by zero (+-0.0) undefined; spirv_mini_interp raises - si.UnsupportedConstruct("OpFDiv by zero (undefined in SPIR-V)"). - GLSL.std.450 leaves InverseSqrt of x <= 0 (+-0.0, negative values, -inf) undefined; - spirv_mini_interp raises si.UnsupportedConstruct. - - Instruction encodings and modifiers: - Both VOP1 (_e32) and VOP3 (_e64) encodings are tested with VGPR, SGPR, literal, inline constants, - input modifiers (-S0, |S0|, -|S0|), output clamp, and output scale modifiers (mul:2, mul:4, div:2). - In particular, applying |S0| or -S0 to a negative operand enables v_rsq_f32 to execute validly. - - Execution masking: - Inactive lanes (EXEC=0) preserve their destination register value; multilane compute execution - verifies masked lanes across the wave. - - Negative control tests: - Sabotaged SPIR-V instructions are asserted to fail the checks. - -Standard library Python only; hand-written RDNA2 listings only. Zero game data. -""" -from __future__ import annotations - -import gc -import math -import os -import re -import struct -import sys -import tempfile -import unittest -import warnings - -HERE = os.path.dirname(os.path.abspath(__file__)) -ROOT = os.path.dirname(os.path.dirname(HERE)) -TOOLS_DIR = os.environ.get("LEONIDA_TOOLS_DIR") or os.path.join(ROOT, "tools") - -sys.dont_write_bytecode = True -if TOOLS_DIR not in sys.path: - sys.path.insert(0, TOOLS_DIR) -if HERE not in sys.path: - sys.path.insert(0, HERE) - -import rdna2spirv # noqa: E402 -import spirv_mini_interp as si # noqa: E402 - -OLD = 0xBEEF1234 -STUB_DXBC = b"DXBC" + bytes(24) + struct.pack(" int: - """Float to unsigned 32-bit integer bits.""" - return struct.unpack(" float: - """Unsigned 32-bit integer bits to float.""" - return struct.unpack(" bool: - """Check if binary32 bits represent a NaN.""" - return (bits & 0x7F800000) == 0x7F800000 and (bits & 0x007FFFFF) != 0 - - -def _make_fssm(rsrc2: int, group: tuple[int, int, int]) -> bytes: - """Construct minimal compute shader FSSM header with workgroup dimensions.""" - header = bytearray(0x148) - struct.pack_into("<4I", header, 0x138, rsrc2, *group) - return bytes(header) - - -def setUpModule() -> None: - global _TMP_DIR, _PS_PATH, _CS_PATH, _CS_FSSM - _TMP_DIR = tempfile.TemporaryDirectory() - disasm_dir = os.path.join(_TMP_DIR.name, "disasm") - fssm_dir = os.path.join(_TMP_DIR.name, "fssm") - os.mkdir(disasm_dir) - os.mkdir(fssm_dir) - _PS_PATH = os.path.join(disasm_dir, "ps_alu_rcp.s") - _CS_PATH = os.path.join(disasm_dir, "cs_alu_rcp.s") - _CS_FSSM = os.path.join(fssm_dir, "cs_alu_rcp.fssm") - with open(os.path.join(_TMP_DIR.name, "ps_alu_rcp.dxbc"), "wb") as f: - f.write(STUB_DXBC) - - -def tearDownModule() -> None: - global _TMP_DIR, _PS_PATH, _CS_PATH, _CS_FSSM - if _TMP_DIR is not None: - gc.collect() - _TMP_DIR.cleanup() - _TMP_DIR = None - _PS_PATH = None - _CS_PATH = None - _CS_FSSM = None - - -def translate_ps(lines: list[str]) -> str: - """Translate hand-written pixel shader instruction lines to SPIR-V assembly text.""" - if _TMP_DIR is None: - setUpModule() - asm = "; test_ps_alu_rcp\n" + "".join(f"\t{ln}\n" for ln in lines) + "\texp mrt0 v0, v0, v0, v0 done vm\n\ts_endpgm\n" - assert _PS_PATH is not None - with open(_PS_PATH, "w", encoding="utf-8", newline="") as f: - f.write(asm) - with warnings.catch_warnings(): - warnings.simplefilter("ignore", ResourceWarning) - spv = rdna2spirv.translate(_PS_PATH) - gc.collect() - return spv - - -def run_ps_v0(lines: list[str]) -> int: - """Run translated pixel shader lines and return the dword written to v0 (mrt0).""" - return si.run_fragment(translate_ps(lines))["%out_mrt0"][0] - - -def run_op(line: str, v1: int, old: int = OLD, s4: int = 0) -> int: - """Execute line with v1 seeded, destination v0 initialized to old, and s4 seeded.""" - return run_ps_v0([ - f"s_mov_b32 s4, {s4:#x}", - f"v_mov_b32 v1, {v1:#x}", - f"v_mov_b32 v0, {old:#x}", - line, - ]) - - -def run_cs(lines: list[str], group_size: int, subgroup_size: int, memory: dict[int, int]) -> dict[int, int]: - """Execute compute shader lines across a workgroup and return buffer memory writes.""" - if _TMP_DIR is None: - setUpModule() - assert _CS_FSSM is not None and _CS_PATH is not None - with open(_CS_FSSM, "wb") as f: - f.write(_make_fssm(0x0088, (group_size, 1, 1))) - asm = "; test_cs_alu_rcp\n" + "".join(f"\t{ln}\n" for ln in lines) + "\ts_endpgm\n" - with open(_CS_PATH, "w", encoding="utf-8", newline="") as f: - f.write(asm) - with warnings.catch_warnings(): - warnings.simplefilter("ignore", ResourceWarning) - spv = rdna2spirv.translate(_CS_PATH) - gc.collect() - return si.run_workgroup( - spv, - group_size, - subgroup_size, - inputs_for=lambda i: {"%wg_id": (0, 0, 0), "%local_id": (i, 0, 0)}, - push_constants=VSHARP + [0] * 28, - memory=memory, - ) - - -# ----------------------------------------------------------------------------- -# 1. v_rcp_f32 Semantic & Approximation Tests -# ----------------------------------------------------------------------------- - -class AluRcpF32Tests(unittest.TestCase): - def test_rcp_exact_powers_of_two(self) -> None: - """Powers of 2 have bit-exact reciprocals in binary32.""" - cases = [ - (1.0, 1.0), - (2.0, 0.5), - (4.0, 0.25), - (8.0, 0.125), - (16.0, 0.0625), - (32.0, 0.03125), - (64.0, 0.015625), - (128.0, 0.0078125), - (256.0, 0.00390625), - (1024.0, 1.0 / 1024.0), - (0.5, 2.0), - (0.25, 4.0), - (0.125, 8.0), - (0.0625, 16.0), - (0.03125, 32.0), - (0.015625, 64.0), - (-1.0, -1.0), - (-2.0, -0.5), - (-4.0, -0.25), - (-8.0, -0.125), - (-0.5, -2.0), - (-0.25, -4.0), - (-0.125, -8.0), - (1048576.0, 1.0 / 1048576.0), # 2^20 -> 2^-20 - (1.0 / 1048576.0, 1048576.0), # 2^-20 -> 2^20 - ] - for x, want in cases: - with self.subTest(x=x, want=want): - got_bits = run_op("v_rcp_f32_e32 v0, v1", f2u(x)) - self.assertEqual(got_bits, f2u(want)) - - def test_rcp_general_finite_approximation_envelope(self) -> None: - """General non-power-of-two inputs are within the 1-ULP float32 approximation envelope.""" - inputs = [ - 0.1, 0.3, 0.7, 1.25, 2.5, 3.0, 5.0, 7.0, 9.0, 10.0, 15.0, 33.33, 100.0, 12345.678, - -0.1, -0.3, -1.25, -3.0, -7.0, -10.0, -100.0, -12345.678, - ] - for x in inputs: - with self.subTest(x=x): - got_bits = run_op("v_rcp_f32_e32 v0, v1", f2u(x)) - got_flt = u2f(got_bits) - ref_flt = 1.0 / x - rel_err = abs((got_flt - ref_flt) / ref_flt) - self.assertLessEqual(rel_err, TOL_F32_REL) - - def test_rcp_infinities_and_nans(self) -> None: - """v_rcp_f32 maps +-inf to +-0.0, and NaN inputs return a NaN.""" - # 1.0 / (+inf) = +0.0 - self.assertEqual(run_op("v_rcp_f32_e32 v0, v1", POS_INF_BITS), POS_ZERO_BITS) - # 1.0 / (-inf) = -0.0 - self.assertEqual(run_op("v_rcp_f32_e32 v0, v1", NEG_INF_BITS), NEG_ZERO_BITS) - - # NaN inputs return a NaN - for nan_bits in (QNAN_BITS, SNAN_BITS, NEG_QNAN_BITS): - with self.subTest(nan_bits=hex(nan_bits)): - res = run_op("v_rcp_f32_e32 v0, v1", nan_bits) - self.assertTrue(is_f32_nan(res)) - self.assertTrue(math.isnan(u2f(res))) - - def test_rcp_division_by_zero_raises(self) -> None: - """OpFDiv by +-0.0 is undefined in SPIR-V and raises si.UnsupportedConstruct.""" - with self.assertRaises(si.UnsupportedConstruct) as ctx: - run_op("v_rcp_f32_e32 v0, v1", POS_ZERO_BITS) - self.assertIn("OpFDiv by zero", str(ctx.exception)) - - with self.assertRaises(si.UnsupportedConstruct) as ctx_neg: - run_op("v_rcp_f32_e32 v0, v1", NEG_ZERO_BITS) - self.assertIn("OpFDiv by zero", str(ctx_neg.exception)) - - def test_rcp_e64_input_modifiers(self) -> None: - """VOP3 input modifiers: negation (-v1), absolute value (|v1|), negative abs (-|v1|).""" - # Negation: -v1 inverts the sign of the reciprocal - self.assertEqual(run_op("v_rcp_f32_e64 v0, -v1", f2u(4.0)), f2u(-0.25)) - self.assertEqual(run_op("v_rcp_f32_e64 v0, -v1", f2u(-2.0)), f2u(0.5)) - - # Absolute value: |v1| forces positive input - self.assertEqual(run_op("v_rcp_f32_e64 v0, |v1|", f2u(-4.0)), f2u(0.25)) - self.assertEqual(run_op("v_rcp_f32_e64 v0, |v1|", f2u(2.0)), f2u(0.5)) - - # Negative absolute value: -|v1| forces negative input - self.assertEqual(run_op("v_rcp_f32_e64 v0, -|v1|", f2u(4.0)), f2u(-0.25)) - self.assertEqual(run_op("v_rcp_f32_e64 v0, -|v1|", f2u(-4.0)), f2u(-0.25)) - - def test_rcp_e64_output_modifiers(self) -> None: - """VOP3 output modifiers: clamp, mul:2, mul:4, div:2.""" - # clamp: clamps reciprocal result to [0.0, 1.0] - # 1.0 / 0.5 = 2.0 -> clamped to 1.0 - self.assertEqual(run_op("v_rcp_f32_e64 v0, v1 clamp", f2u(0.5)), f2u(1.0)) - # 1.0 / (-2.0) = -0.5 -> clamped to 0.0 - self.assertEqual(run_op("v_rcp_f32_e64 v0, v1 clamp", f2u(-2.0)), POS_ZERO_BITS) - # 1.0 / 4.0 = 0.25 in [0, 1] -> unchanged 0.25 - self.assertEqual(run_op("v_rcp_f32_e64 v0, v1 clamp", f2u(4.0)), f2u(0.25)) - - # Output scaling - # (1.0 / 4.0) * 2 = 0.5 - self.assertEqual(run_op("v_rcp_f32_e64 v0, v1 mul:2", f2u(4.0)), f2u(0.5)) - # (1.0 / 4.0) * 4 = 1.0 - self.assertEqual(run_op("v_rcp_f32_e64 v0, v1 mul:4", f2u(4.0)), f2u(1.0)) - # (1.0 / 2.0) / 2 = 0.25 - self.assertEqual(run_op("v_rcp_f32_e64 v0, v1 div:2", f2u(2.0)), f2u(0.25)) - - # Combining input and output modifiers: -|v1| with clamp -> clamped to 0.0 - self.assertEqual(run_op("v_rcp_f32_e64 v0, -|v1| clamp", f2u(4.0)), POS_ZERO_BITS) - - def test_rcp_operand_forms(self) -> None: - """Operand forms: SGPR, inline float constants, literal floats, hex dwords.""" - # SGPR operand - self.assertEqual(run_op("v_rcp_f32_e32 v0, s4", 0, s4=f2u(4.0)), f2u(0.25)) - # Inline float constants - self.assertEqual(run_op("v_rcp_f32_e32 v0, 0.5", 0), f2u(2.0)) - self.assertEqual(run_op("v_rcp_f32_e32 v0, 1.0", 0), f2u(1.0)) - self.assertEqual(run_op("v_rcp_f32_e32 v0, 2.0", 0), f2u(0.5)) - self.assertEqual(run_op("v_rcp_f32_e32 v0, -1.0", 0), f2u(-1.0)) - # Literal float constant - self.assertEqual(run_op("v_rcp_f32_e32 v0, 4.0", 0), f2u(0.25)) - # Hex float immediate (4.0 = 0x40800000) - self.assertEqual(run_op("v_rcp_f32_e32 v0, 0x40800000", 0), f2u(0.25)) - - -# ----------------------------------------------------------------------------- -# 2. v_rsq_f32 Semantic & Approximation Tests -# ----------------------------------------------------------------------------- - -class AluRsqF32Tests(unittest.TestCase): - def test_rsq_exact_powers_of_four(self) -> None: - """Exact square powers of 2 (powers of 4) have bit-exact reciprocal square roots in binary32.""" - cases = [ - (1.0, 1.0), - (4.0, 0.5), - (16.0, 0.25), - (64.0, 0.125), - (256.0, 0.0625), - (1024.0, 0.03125), - (4096.0, 0.015625), - (0.25, 2.0), - (0.0625, 4.0), - (0.015625, 8.0), - (0.00390625, 16.0), - ] - for x, want in cases: - with self.subTest(x=x, want=want): - got_bits = run_op("v_rsq_f32_e32 v0, v1", f2u(x)) - self.assertEqual(got_bits, f2u(want)) - - def test_rsq_general_positive_approximation_envelope(self) -> None: - """General positive inputs are within the 1-ULP float32 approximation envelope.""" - inputs = [ - 0.01, 0.05, 0.1, 0.5, 2.0, 3.0, 5.0, 7.0, 9.0, 10.0, 25.0, 50.0, 100.0, 500.0, 10000.0, - ] - for x in inputs: - with self.subTest(x=x): - got_bits = run_op("v_rsq_f32_e32 v0, v1", f2u(x)) - got_flt = u2f(got_bits) - ref_flt = 1.0 / math.sqrt(x) - rel_err = abs((got_flt - ref_flt) / ref_flt) - self.assertLessEqual(rel_err, TOL_F32_REL) - - def test_rsq_infinities_and_nans(self) -> None: - """v_rsq_f32 on +inf returns 0.0; NaN inputs return a NaN.""" - # 1.0 / sqrt(+inf) = 0.0 - self.assertEqual(run_op("v_rsq_f32_e32 v0, v1", POS_INF_BITS), POS_ZERO_BITS) - - # NaN inputs return a NaN - for nan_bits in (QNAN_BITS, SNAN_BITS): - with self.subTest(nan_bits=hex(nan_bits)): - res = run_op("v_rsq_f32_e32 v0, v1", nan_bits) - self.assertTrue(is_f32_nan(res)) - self.assertTrue(math.isnan(u2f(res))) - - def test_rsq_non_positive_inputs_raise(self) -> None: - """InverseSqrt of x <= 0 is undefined in GLSL.std.450 and raises si.UnsupportedConstruct.""" - non_positive_cases = [ - ("pos_zero", POS_ZERO_BITS), - ("neg_zero", NEG_ZERO_BITS), - ("neg_one", f2u(-1.0)), - ("neg_four", f2u(-4.0)), - ("neg_inf", NEG_INF_BITS), - ] - for name, bits in non_positive_cases: - with self.subTest(name=name): - with self.assertRaises(si.UnsupportedConstruct) as ctx: - run_op("v_rsq_f32_e32 v0, v1", bits) - self.assertIn("InverseSqrt", str(ctx.exception)) - - def test_rsq_e64_input_modifiers(self) -> None: - """VOP3 input modifiers: absolute value (|v1|) and negation (-v1) rescue negative inputs.""" - # Absolute value: |-4.0| = 4.0, so 1.0 / sqrt(|-4.0|) = 0.5 - self.assertEqual(run_op("v_rsq_f32_e64 v0, |v1|", f2u(-4.0)), f2u(0.5)) - self.assertEqual(run_op("v_rsq_f32_e64 v0, |v1|", f2u(-16.0)), f2u(0.25)) - - # Negation: -(-4.0) = 4.0, so 1.0 / sqrt(-v1) = 0.5 - self.assertEqual(run_op("v_rsq_f32_e64 v0, -v1", f2u(-4.0)), f2u(0.5)) - self.assertEqual(run_op("v_rsq_f32_e64 v0, -v1", f2u(-16.0)), f2u(0.25)) - - def test_rsq_e64_output_modifiers(self) -> None: - """VOP3 output modifiers: clamp, mul:2, mul:4, div:2.""" - # clamp: clamps result to [0.0, 1.0] - # 1.0 / sqrt(0.0625) = 4.0 -> clamped to 1.0 - self.assertEqual(run_op("v_rsq_f32_e64 v0, v1 clamp", f2u(0.0625)), f2u(1.0)) - # 1.0 / sqrt(4.0) = 0.5 in [0, 1] -> unchanged 0.5 - self.assertEqual(run_op("v_rsq_f32_e64 v0, v1 clamp", f2u(4.0)), f2u(0.5)) - - # Output scaling - # (1.0 / sqrt(16.0)) * 2 = 0.25 * 2 = 0.5 - self.assertEqual(run_op("v_rsq_f32_e64 v0, v1 mul:2", f2u(16.0)), f2u(0.5)) - # (1.0 / sqrt(16.0)) * 4 = 0.25 * 4 = 1.0 - self.assertEqual(run_op("v_rsq_f32_e64 v0, v1 mul:4", f2u(16.0)), f2u(1.0)) - # (1.0 / sqrt(4.0)) / 2 = 0.5 / 2 = 0.25 - self.assertEqual(run_op("v_rsq_f32_e64 v0, v1 div:2", f2u(4.0)), f2u(0.25)) - - def test_rsq_operand_forms(self) -> None: - """Operand forms: SGPR, inline float constants, literal floats, hex dwords.""" - # SGPR operand - self.assertEqual(run_op("v_rsq_f32_e32 v0, s4", 0, s4=f2u(16.0)), f2u(0.25)) - # Inline float constants - self.assertEqual(run_op("v_rsq_f32_e32 v0, 1.0", 0), f2u(1.0)) - self.assertEqual(run_op("v_rsq_f32_e32 v0, 4.0", 0), f2u(0.5)) - # Hex float immediate (16.0 = 0x41800000) - self.assertEqual(run_op("v_rsq_f32_e32 v0, 0x41800000", 0), f2u(0.25)) - - -# ----------------------------------------------------------------------------- -# 3. Execution Masking & Multilane Wave Tests -# ----------------------------------------------------------------------------- - -class AluRcpRsqExecMaskingTests(unittest.TestCase): - def test_single_lane_exec_masking(self) -> None: - """With EXEC disabled (exec_lo = 0), v0 remains unchanged.""" - for line in ("v_rcp_f32_e32 v0, v1", "v_rsq_f32_e32 v0, v1", "v_rcp_f32_e64 v0, v1 mul:2"): - with self.subTest(line=line): - got = run_ps_v0([ - f"v_mov_b32 v1, {f2u(4.0):#x}", - f"v_mov_b32 v0, {OLD:#x}", - "s_mov_b32 exec_lo, 0", - line, - "s_mov_b32 exec_lo, 1", - ]) - self.assertEqual(got, OLD) - - def test_multilane_compute_exec_masking(self) -> None: - """Multilane compute shader with even lanes active and odd lanes disabled.""" - cases = [ - ("v_rcp_f32_e32 v3, v2", f2u(4.0), f2u(0.25)), - ("v_rsq_f32_e32 v3, v2", f2u(16.0), f2u(0.25)), - ("v_rcp_f32_e64 v3, v2 mul:2", f2u(4.0), f2u(0.5)), - ("v_rsq_f32_e64 v3, v2 mul:4", f2u(16.0), f2u(1.0)), - ] - for insn, src_word, active_want in cases: - with self.subTest(insn=insn): - mem: dict[int, int] = {} - lines = [ - "v_lshlrev_b32 v4, 2, v0", # byte offset = lane_id * 4 - f"v_mov_b32 v2, {src_word:#x}", - f"v_mov_b32 v3, {OLD:#x}", - "v_and_b32 v5, v0, 1", - "v_cmpx_eq_u32 v5, 0", # keep even lanes active - insn, - "s_mov_b32 exec_lo, -1", - "buffer_store_dword v3, v4, s[0:3], 0 offen", - ] - run_cs(lines, group_size=4, subgroup_size=32, memory=mem) - self.assertEqual( - [mem[4 * i] for i in range(4)], - [active_want, OLD, active_want, OLD], - ) - - -# ----------------------------------------------------------------------------- -# 4. Negative Control Tests -# ----------------------------------------------------------------------------- - -class NegativeControlTests(unittest.TestCase): - def test_sabotaged_rcp_spirv_is_detected(self) -> None: - """Mutating OpFDiv to OpFMul in translated v_rcp_f32 fails the assertion.""" - spv = translate_ps([ - f"v_mov_b32 v0, {OLD:#x}", - f"v_mov_b32 v1, {f2u(4.0):#x}", - "v_rcp_f32_e32 v0, v1", - ]) - self.assertEqual(si.run_fragment(spv)["%out_mrt0"][0], f2u(0.25)) - - bad_spv, count = re.subn(r"OpFDiv %float %f1\b", "OpFMul %float %f1", spv, count=1) - self.assertEqual(count, 1) - # 1.0 * 4.0 = 4.0 != 0.25 - self.assertNotEqual(si.run_fragment(bad_spv)["%out_mrt0"][0], f2u(0.25)) - - def test_sabotaged_rsq_spirv_is_detected(self) -> None: - """Mutating InverseSqrt to Sqrt in translated v_rsq_f32 fails the assertion.""" - spv = translate_ps([ - f"v_mov_b32 v0, {OLD:#x}", - f"v_mov_b32 v1, {f2u(4.0):#x}", - "v_rsq_f32_e32 v0, v1", - ]) - self.assertEqual(si.run_fragment(spv)["%out_mrt0"][0], f2u(0.5)) - - bad_spv, count = re.subn(r"InverseSqrt", "Sqrt", spv, count=1) - self.assertEqual(count, 1) - # sqrt(4.0) = 2.0 != 0.5 - self.assertNotEqual(si.run_fragment(bad_spv)["%out_mrt0"][0], f2u(0.5)) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_alu_rcp_f32.py b/tests/semantic/test_alu_rcp_f32.py deleted file mode 100644 index 4cf221bbe..000000000 --- a/tests/semantic/test_alu_rcp_f32.py +++ /dev/null @@ -1,197 +0,0 @@ -"""Semantic translation tests for RDNA2 32-bit reciprocal v_rcp_f32. - -Translates a synthetic pixel-shader listing through tools/rdna2spirv.translate() --> SPIR-V -> tests/semantic/spirv_mini_interp.py and compares the result against -a plain-Python reference: 1.0 / x rounded to binary32 for finite non-zero x, -+infinity for +inf, -0.0 for -inf, and NaN for NaN. - -v_rcp_f32(0) is undefined: the translator lowers it to OpFDiv 1.0/x and SPIR-V -leaves division by zero undefined, so the interpreter refuses it (that case is -asserted separately, not fed through the reference). - -Covers: - - Exact reciprocals: rcp(1)=1, rcp(2)=0.5, rcp(4)=0.25, rcp(0.5)=2, rcp(0.25)=4 - - Negative inputs: rcp(-2)=-0.5, rcp(-0.5)=-2 - - rcp(3) within 1e-6 tolerance - - rcp(+inf)=+0.0 and rcp(-inf)=-0.0 (signed zeros preserved) - - rcp(NaN)=NaN - - Random cases vs the reference - - Negative control: result differs from the input for non-trivial cases - - rcp(0) is undefined and refused by the interpreter -""" -import math -import os -import struct -import sys -import tempfile -import unittest -import warnings - -HERE = os.path.dirname(os.path.abspath(__file__)) -ROOT = os.path.dirname(os.path.dirname(HERE)) -TOOLS_DIR = os.environ.get("LEONIDA_TOOLS_DIR") or os.path.join(ROOT, "tools") - -sys.dont_write_bytecode = True -if TOOLS_DIR not in sys.path: - sys.path.insert(0, TOOLS_DIR) -if HERE not in sys.path: - sys.path.insert(0, HERE) - -import rdna2spirv # noqa: E402 -import spirv_mini_interp as si # noqa: E402 - -M32 = 0xFFFFFFFF -STUB_DXBC = b"DXBC" + bytes(24) + struct.pack(" int: - return struct.unpack(" float: - return struct.unpack(" bool: - e = (b >> 23) & 0xFF - m = b & 0x7FFFFF - return e == 0xFF and m != 0 - - -def ref_rcp32(x_bits: int) -> int: - """Plain-Python reference for v_rcp_f32: 1.0 / x rounded to binary32.""" - x = f32(x_bits) - if math.isnan(x): - return bits32(float("nan")) - if x == float("inf"): - return bits32(0.0) - if x == float("-inf"): - return bits32(-0.0) - return bits32(1.0 / x) - - -_TMP_DIR = None -_SRC_PATH = None - - -def setUpModule(): - global _TMP_DIR, _SRC_PATH - _TMP_DIR = tempfile.TemporaryDirectory() - disasm_dir = os.path.join(_TMP_DIR.name, "disasm") - os.mkdir(disasm_dir) - _SRC_PATH = os.path.join(disasm_dir, "ps_rcp_f32.s") - with open(os.path.join(_TMP_DIR.name, "ps_rcp_f32.dxbc"), "wb") as f: - f.write(STUB_DXBC) - - -def tearDownModule(): - global _TMP_DIR - if _TMP_DIR is not None: - _TMP_DIR.cleanup() - _TMP_DIR = None - - -def run_op(x_bits: int) -> int: - """Translate and run a shader that computes v_rcp_f32 v1, v0 with v0=x_bits.""" - x = f32(x_bits) - asm = ( - "; test_rcp_f32\n" - f"\tv_mov_b32_e32 v0, {x_bits & M32:#x} ; {x!r}\n" - "\tv_rcp_f32 v1, v0\n" - "\ts_waitcnt vmcnt(0)\n" - "\texp mrt0 v1, v1, v1, v1 done vm\n" - "\ts_endpgm\n" - ) - tmp = tempfile.TemporaryDirectory() - disasm_dir = os.path.join(tmp.name, "disasm") - os.mkdir(disasm_dir) - src_path = os.path.join(disasm_dir, "ps_rcp_f32.s") - with open(os.path.join(tmp.name, "ps_rcp_f32.dxbc"), "wb") as f: - f.write(STUB_DXBC) - with open(src_path, "w", encoding="utf-8") as f: - f.write(asm) - with warnings.catch_warnings(): - warnings.simplefilter("ignore", ResourceWarning) - spv = rdna2spirv.translate(src_path) - w = si.run_fragment(spv)["%out_mrt0"] - tmp.cleanup() - return w[0] & M32 - - -class ALUVRcpF32Tests(unittest.TestCase): - def test_rcp_f32_exact_reciprocals(self): - cases = [ - (bits32(1.0), bits32(1.0)), - (bits32(2.0), bits32(0.5)), - (bits32(4.0), bits32(0.25)), - (bits32(0.5), bits32(2.0)), - (bits32(0.25), bits32(4.0)), - (bits32(8.0), bits32(0.125)), - ] - for x_bits, expected in cases: - with self.subTest(x=f32(x_bits)): - res = run_op(x_bits) - self.assertEqual(res, expected) - self.assertEqual(res, ref_rcp32(x_bits)) - - def test_rcp_f32_negative_inputs(self): - cases = [ - (bits32(-2.0), bits32(-0.5)), - (bits32(-0.5), bits32(-2.0)), - (bits32(-4.0), bits32(-0.25)), - (bits32(-0.25), bits32(-4.0)), - ] - for x_bits, expected in cases: - with self.subTest(x=f32(x_bits)): - res = run_op(x_bits) - self.assertEqual(res, expected) - self.assertEqual(res, ref_rcp32(x_bits)) - - def test_rcp_f32_reciprocal_of_3(self): - x_bits = bits32(3.0) - res = run_op(x_bits) - self.assertEqual(res, ref_rcp32(x_bits)) - res_f = f32(res) - self.assertAlmostEqual(res_f, 1.0 / 3.0, delta=1e-6) - - def test_rcp_f32_signed_zeros_and_special(self): - cases = [ - (bits32(float("inf")), bits32(0.0), False), # rcp(+inf) = +0.0 - (bits32(float("-inf")), bits32(-0.0), False), # rcp(-inf) = -0.0 - (bits32(float("nan")), bits32(float("nan")), True), # rcp(NaN) = NaN - ] - for x_bits, expected, expect_nan in cases: - with self.subTest(x=f32(x_bits)): - res = run_op(x_bits) - self.assertEqual(res, ref_rcp32(x_bits)) - self.assertEqual(is_nan(res), expect_nan) - - def test_rcp_f32_random_vs_reference(self): - import random - rng = random.Random(0xC0FFEE) - for _ in range(50): - x_bits = rng.getrandbits(32) - if x_bits == 0 or x_bits == M32: - continue # +0/-0: division by zero is undefined - x = f32(x_bits) - if math.isinf(x) and x < 0: - continue # covered above - with self.subTest(x=x): - res = run_op(x_bits) - self.assertEqual(res, ref_rcp32(x_bits)) - - def test_rcp_f32_negative_control(self): - # Result differs from the input for a non-trivial input. - x_bits = bits32(2.0) - res = run_op(x_bits) - self.assertEqual(res, bits32(0.5)) - self.assertNotEqual(res, x_bits) - - def test_rcp_f32_zero_is_undefined(self): - # v_rcp_f32(0) lowers to OpFDiv 1.0/0, which SPIR-V leaves undefined. - with self.assertRaises(si.UnsupportedConstruct): - run_op(bits32(0.0)) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_alu_round.py b/tests/semantic/test_alu_round.py deleted file mode 100644 index 5a2444512..000000000 --- a/tests/semantic/test_alu_round.py +++ /dev/null @@ -1,949 +0,0 @@ -from __future__ import annotations - -"""Semantic interpreter tests for AMD RDNA2 floating-point rounding instructions: - - v_floor_f32 / v_floor_f16: round down towards -infinity (Floor) - - v_ceil_f32 / v_ceil_f16: round up towards +infinity (Ceil) - - v_trunc_f32 / v_trunc_f16: round towards zero (Trunc) - - v_rndne_f32 / v_rndne_f16: round to nearest even integer (RoundEven) - -Models IEEE 754-2008 / IEEE 754-2019 roundToIntegral semantics and SPIR-V GLSL.std.450 -extended instructions, verified against AMD GFX10 / RDNA2 hardware semantics: - * Signed zero preservation: IEEE 754 roundToIntegral requires that if the rounded - integral result is zero, it preserves the sign of the input operand. - Thus floor(-0.5) = -1.0, but ceil(-0.5) = -0.0, trunc(-0.5) = -0.0, rndne(-0.4) = -0.0. - * Subnormal numbers: gradual underflow behavior where subnormals within (-1.0, 1.0) - round appropriately to +/-0.0 or +/-1.0 preserving signs. - * Special IEEE 754 values: positive/negative infinities and quiet/signaling NaNs pass through. - * Tie-breaking to even for rndne / RoundEven: half-integers (n + 0.5) round to the nearest - even integer (0.5 -> 0.0, 1.5 -> 2.0, 2.5 -> 2.0, 3.5 -> 4.0; -0.5 -> -0.0, -1.5 -> -2.0). - * High-magnitude floats: values where |x| >= 2^23 (for f32) or |x| >= 2^10 (for f16) - have no fractional significand bits (ulp >= 1.0) and are already exact integers. - * Hardware operand modifiers: source abs (|src|), neg (-src), negative abs (-|src|), - destination clamp ([0.0, 1.0]), output modifiers (mul:2, mul:4, div:2), and 16-bit half - selection and destination preservation via op_sel:[src,dst]. - * Multi-lane SIMD wave64 isolation. - * Negative controls verifying that erroneous rounding modes, sign dropping, or clamp - violations fail assertions. - -Standard library Python only; zero third-party dependencies; zero game data. -Python 3.9+ compatible. -""" - -import math -import os -import random -import struct -import sys -import tempfile -import unittest -import warnings -from typing import Dict, List, Optional, Sequence, Tuple - -HERE = os.path.dirname(os.path.abspath(__file__)) -ROOT = os.path.dirname(os.path.dirname(HERE)) -TOOLS_DIR = os.environ.get("LEONIDA_TOOLS_DIR") or os.path.join(ROOT, "tools") - -sys.dont_write_bytecode = True -if TOOLS_DIR not in sys.path: - sys.path.insert(0, TOOLS_DIR) -if HERE not in sys.path: - sys.path.insert(0, HERE) - -import rdna2spirv # noqa: E402 -import spirv_mini_interp as si # noqa: E402 - -MASK32 = 0xFFFFFFFF -SIGN_MASK32 = 0x80000000 -EXP_MASK32 = 0x7F800000 -MANT_MASK32 = 0x007FFFFF - -MASK16 = 0xFFFF -SIGN_MASK16 = 0x8000 -EXP_MASK16 = 0x7C00 -MANT_MASK16 = 0x03FF - -POS_ZERO_F32 = 0x00000000 -NEG_ZERO_F32 = 0x80000000 -POS_INF_F32 = 0x7F800000 -NEG_INF_F32 = 0xFF800000 -QNAN_F32 = 0x7FC00000 - -POS_ZERO_F16 = 0x0000 -NEG_ZERO_F16 = 0x8000 -POS_INF_F16 = 0x7C00 -NEG_INF_F16 = 0xFC00 -QNAN_F16 = 0x7E00 - -STUB_DXBC = b"DXBC" + bytes(24) + struct.pack(" int: - """Encode Python float as IEEE 754 single-precision 32-bit unsigned integer.""" - if math.isnan(f): - return QNAN_F32 - try: - return struct.unpack(" float: - """Decode IEEE 754 single-precision 32-bit unsigned integer to Python float.""" - return struct.unpack(" int: - """Encode Python float as IEEE 754 half-precision 16-bit unsigned integer.""" - if math.isnan(f): - return QNAN_F16 - try: - return struct.unpack(" float: - """Decode IEEE 754 half-precision 16-bit unsigned integer to Python float.""" - return struct.unpack(" bool: - """Check if 32-bit word represents an IEEE 754 single-precision NaN.""" - return ((b & EXP_MASK32) == EXP_MASK32) and ((b & MANT_MASK32) != 0) - - -def is_nan_f16(h: int) -> bool: - """Check if 16-bit word represents an IEEE 754 half-precision NaN.""" - return ((h & EXP_MASK16) == EXP_MASK16) and ((h & MANT_MASK16) != 0) - - -# ============================================================================== -# Reference Oracles -# ============================================================================== - - -def ref_round_f32(val: float, mode: str) -> float: - """Computes IEEE 754 binary32 rounding to integral with sign preservation. - - Modes: - - 'floor': round down towards -infinity - - 'ceil': round up towards +infinity - - 'trunc': round towards zero - - 'rndne': round to nearest even integer - """ - if math.isnan(val) or math.isinf(val): - return val - fn = { - "floor": math.floor, - "ceil": math.ceil, - "trunc": math.trunc, - "rndne": round, - }[mode] - # math.copysign ensures that rounding -0.5 towards 0 retains -0.0 - return math.copysign(float(fn(val)), val) - - -def ref_floor_f32(val: float) -> float: - return ref_round_f32(val, "floor") - - -def ref_ceil_f32(val: float) -> float: - return ref_round_f32(val, "ceil") - - -def ref_trunc_f32(val: float) -> float: - return ref_round_f32(val, "trunc") - - -def ref_rndne_f32(val: float) -> float: - return ref_round_f32(val, "rndne") - - -def ref_round_f32_bits(bits: int, mode: str) -> int: - """Bit-accurate reference for binary32 rounding instructions.""" - bits &= MASK32 - if (bits & EXP_MASK32) == EXP_MASK32: - return bits # Infinities and NaNs pass through unchanged - f = bits_to_f32(bits) - res_f = ref_round_f32(f, mode) - return f32_to_bits(res_f) - - -def ref_round_f16(val: float, mode: str) -> float: - """Computes IEEE 754 binary16 rounding to integral with sign preservation.""" - if math.isnan(val) or math.isinf(val): - return val - fn = { - "floor": math.floor, - "ceil": math.ceil, - "trunc": math.trunc, - "rndne": round, - }[mode] - return math.copysign(float(fn(val)), val) - - -def ref_round_f16_bits(h: int, mode: str) -> int: - """Bit-accurate reference for binary16 rounding instructions.""" - h &= MASK16 - if (h & EXP_MASK16) == EXP_MASK16: - return h # Infinities and NaNs pass through unchanged - f = bits_to_f16(h) - res_f = ref_round_f16(f, mode) - return f16_to_bits(res_f) - - -# ============================================================================== -# Simulated VALU Interpreter -# ============================================================================== - - -def split_operands(s: str) -> List[str]: - """Splits assembly operand string on commas outside of bracketed lists.""" - parts: List[str] = [] - current: List[str] = [] - in_bracket = False - for ch in s: - if ch == "[": - in_bracket = True - current.append(ch) - elif ch == "]": - in_bracket = False - current.append(ch) - elif ch == "," and not in_bracket: - parts.append("".join(current).strip()) - current = [] - else: - current.append(ch) - if current: - parts.append("".join(current).strip()) - return parts - - -class RoundValuInterpreter: - """Simulated VALU interpreter supporting floating point rounding instructions: - v_floor_f32, v_ceil_f32, v_trunc_f32, v_rndne_f32, - v_floor_f16, v_ceil_f16, v_trunc_f16, v_rndne_f16. - - Models VGPR (v0..v255) and SGPR (s0..s105) register state, e32 / e64 forms, - source modifiers (|src|, -src, -|src|), destination clamp ([0.0, 1.0]), - output multipliers (mul:2, mul:4, div:2), and f16 op_sel half selection. - """ - - def __init__(self) -> None: - self.vgpr: Dict[int, int] = {} - self.sgpr: Dict[int, int] = {} - - def read_reg(self, name: str) -> int: - name = name.strip() - if name.startswith("v"): - return self.vgpr.get(int(name[1:]), 0) & MASK32 - if name.startswith("s"): - return self.sgpr.get(int(name[1:]), 0) & MASK32 - raise ValueError(f"Unknown register name: {name}") - - def write_reg(self, name: str, val: int) -> None: - name = name.strip() - val &= MASK32 - if name.startswith("v"): - self.vgpr[int(name[1:])] = val - elif name.startswith("s"): - self.sgpr[int(name[1:])] = val - else: - raise ValueError(f"Unknown destination register: {name}") - - def parse_operand(self, token: str) -> Tuple[int, bool, bool]: - """Parses operand token into (raw_bits, is_abs, is_neg).""" - token = token.strip() - is_abs = False - is_neg = False - - if token.startswith("-|") and token.endswith("|"): - is_abs = True - is_neg = True - token = token[2:-1].strip() - elif token.startswith("|") and token.endswith("|"): - is_abs = True - token = token[1:-1].strip() - elif token.startswith("-"): - is_neg = True - token = token[1:].strip() - - inline_floats = { - "0.0": 0x00000000, - "0.5": 0x3F000000, - "1.0": 0x3F800000, - "1.5": 0x3FC00000, - "2.0": 0x40000000, - "2.5": 0x40200000, - "3.0": 0x40400000, - "4.0": 0x40800000, - "-0.5": 0xBF000000, - "-1.0": 0xBF800000, - "-1.5": 0xBFC00000, - "-2.0": 0xC0000000, - } - - if token in inline_floats: - val = inline_floats[token] - elif token.startswith("v") or token.startswith("s"): - val = self.read_reg(token) - elif token.startswith("0x") or token.startswith("0X"): - val = int(token, 16) & MASK32 - else: - try: - val = int(token) & MASK32 - except ValueError: - val = f32_to_bits(float(token)) - - if is_abs: - val &= ~SIGN_MASK32 - if is_neg: - val ^= SIGN_MASK32 - - return val, is_abs, is_neg - - def execute_line(self, line: str) -> None: - """Executes a single RDNA2 assembly line.""" - clean = line.split(";")[0].strip() - if not clean: - return - - parts = clean.split(None, 1) - mnemonic = parts[0].lower() - rest = parts[1] if len(parts) > 1 else "" - - # Parse comma-separated arguments, recognizing trailing modifiers - args = split_operands(rest) if rest else [] - dst = args[0] if args else "" - src_and_mods = args[1].split() if len(args) > 1 else [] - - src_token = src_and_mods[0] if src_and_mods else "" - mods = [m.lower() for m in src_and_mods[1:]] - - # Check for op_sel in modifiers, e.g., op_sel:[1,0] - op_sel_src = 0 - op_sel_dst = 0 - for m in mods: - if m.startswith("op_sel:["): - inner = m[len("op_sel:[") : -1] - bits = [int(x.strip()) for x in inner.split(",")] - op_sel_src = bits[0] - op_sel_dst = bits[1] - - base_op = mnemonic - for suf in ("_e32", "_e64"): - if base_op.endswith(suf): - base_op = base_op[: -len(suf)] - break - - if base_op in ("v_mov_b32", "s_mov_b32"): - src_val, _, _ = self.parse_operand(src_token) - self.write_reg(dst, src_val) - return - - f32_modes = { - "v_floor_f32": "floor", - "v_ceil_f32": "ceil", - "v_trunc_f32": "trunc", - "v_rndne_f32": "rndne", - } - f16_modes = { - "v_floor_f16": "floor", - "v_ceil_f16": "ceil", - "v_trunc_f16": "trunc", - "v_rndne_f16": "rndne", - } - - if base_op in f32_modes: - mode = f32_modes[base_op] - src_val, _, _ = self.parse_operand(src_token) - res_bits = ref_round_f32_bits(src_val, mode) - - # Apply output modifiers - if not is_nan_f32(res_bits) and res_bits not in (POS_INF_F32, NEG_INF_F32): - res_f = bits_to_f32(res_bits) - if "mul:2" in mods: - res_f *= 2.0 - elif "mul:4" in mods: - res_f *= 4.0 - elif "div:2" in mods: - res_f *= 0.5 - - if "clamp" in mods: - res_f = max(0.0, min(1.0, res_f)) - res_bits = f32_to_bits(res_f) - - self.write_reg(dst, res_bits) - - elif base_op in f16_modes: - mode = f16_modes[base_op] - src_val, is_abs, is_neg = self.parse_operand(src_token) - - # Pick high or low half of source based on op_sel_src - h = (src_val >> 16) & MASK16 if op_sel_src else (src_val & MASK16) - if is_abs: - h &= ~SIGN_MASK16 - if is_neg: - h ^= SIGN_MASK16 - - res_h = ref_round_f16_bits(h, mode) - - if not is_nan_f16(res_h) and res_h not in (POS_INF_F16, NEG_INF_F16): - res_f = bits_to_f16(res_h) - if "mul:2" in mods: - res_f *= 2.0 - elif "mul:4" in mods: - res_f *= 4.0 - elif "div:2" in mods: - res_f *= 0.5 - - if "clamp" in mods: - res_f = max(0.0, min(1.0, res_f)) - res_h = f16_to_bits(res_f) - - # Write into dst half according to op_sel_dst, preserving the other half - old_dst = self.read_reg(dst) - if op_sel_dst: - new_dst = (old_dst & 0x0000FFFF) | ((res_h & MASK16) << 16) - else: - new_dst = (old_dst & 0xFFFF0000) | (res_h & MASK16) - self.write_reg(dst, new_dst) - - else: - raise NotImplementedError(f"Unsupported instruction mnemonic: {mnemonic}") - - -# ============================================================================== -# SPIR-V Translation & Execution Harness -# ============================================================================== - -_TMP_DIR: Optional[tempfile.TemporaryDirectory] = None -_SRC_PATH: Optional[str] = None - - -def setUpModule() -> None: - global _TMP_DIR, _SRC_PATH - _TMP_DIR = tempfile.TemporaryDirectory() - disasm_dir = os.path.join(_TMP_DIR.name, "disasm") - os.mkdir(disasm_dir) - _SRC_PATH = os.path.join(disasm_dir, "ps_round.s") - with open(os.path.join(_TMP_DIR.name, "ps_round.dxbc"), "wb") as f: - f.write(STUB_DXBC) - - -def tearDownModule() -> None: - global _TMP_DIR - if _TMP_DIR is not None: - _TMP_DIR.cleanup() - _TMP_DIR = None - - -def run_assembly(lines: Sequence[str]) -> Tuple[int, int, int, int]: - """Translates a synthetic pixel shader with tools/rdna2spirv.py and runs it - in tests/semantic/spirv_mini_interp.py, returning exported mrt0 (v0, v1, v2, v3). - """ - if _TMP_DIR is None: - setUpModule() - assert _SRC_PATH is not None - asm = ( - "; test_alu_round\n" - + "".join(f"\t{ln}\n" for ln in lines) - + "\texp mrt0 v0, v1, v2, v3 done vm\n\ts_endpgm\n" - ) - with open(_SRC_PATH, "w", encoding="utf-8") as f: - f.write(asm) - with warnings.catch_warnings(): - warnings.simplefilter("ignore", ResourceWarning) - spv = rdna2spirv.translate(_SRC_PATH) - out = si.run_fragment(spv)["%out_mrt0"] - return (out[0], out[1], out[2], out[3]) - - -# ============================================================================== -# Unit Tests -# ============================================================================== - - -class TestRoundReferenceOracles(unittest.TestCase): - """Verifies that the reference oracles adhere strictly to IEEE 754-2008 / - IEEE 754-2019 roundToIntegral semantics and sign preservation rules. - """ - - def test_signed_zeros_f32(self): - # In all modes, +0.0 returns +0.0 and -0.0 returns -0.0 - for mode in ("floor", "ceil", "trunc", "rndne"): - with self.subTest(mode=mode): - self.assertEqual(ref_round_f32_bits(POS_ZERO_F32, mode), POS_ZERO_F32) - self.assertEqual(ref_round_f32_bits(NEG_ZERO_F32, mode), NEG_ZERO_F32) - - def test_exact_integers_f32(self): - integers = [0.0, -0.0, 1.0, -1.0, 2.0, -2.0, 42.0, -99.0, 1024.0, -2048.0] - for val in integers: - bits = f32_to_bits(val) - for mode in ("floor", "ceil", "trunc", "rndne"): - with self.subTest(val=val, mode=mode): - self.assertEqual(ref_round_f32_bits(bits, mode), bits) - - def test_positive_fractions_f32(self): - cases = [ - # (val, floor, ceil, trunc, rndne) - (0.25, 0.0, 1.0, 0.0, 0.0), - (0.50, 0.0, 1.0, 0.0, 0.0), # tie to even (0 is even) - (0.75, 0.0, 1.0, 0.0, 1.0), - (1.25, 1.0, 2.0, 1.0, 1.0), - (1.50, 1.0, 2.0, 1.0, 2.0), # tie to even (2 is even) - (1.75, 1.0, 2.0, 1.0, 2.0), - (2.25, 2.0, 3.0, 2.0, 2.0), - (2.50, 2.0, 3.0, 2.0, 2.0), # tie to even (2 is even) - (2.75, 2.0, 3.0, 2.0, 3.0), - (3.50, 3.0, 4.0, 3.0, 4.0), # tie to even (4 is even) - ] - for val, exp_fl, exp_ce, exp_tr, exp_rn in cases: - bits = f32_to_bits(val) - with self.subTest(val=val): - self.assertEqual(ref_round_f32_bits(bits, "floor"), f32_to_bits(exp_fl)) - self.assertEqual(ref_round_f32_bits(bits, "ceil"), f32_to_bits(exp_ce)) - self.assertEqual(ref_round_f32_bits(bits, "trunc"), f32_to_bits(exp_tr)) - self.assertEqual(ref_round_f32_bits(bits, "rndne"), f32_to_bits(exp_rn)) - - def test_negative_fractions_and_signed_zero_preservation_f32(self): - cases = [ - # (val, floor, ceil, trunc, rndne) - (-0.25, -1.0, -0.0, -0.0, -0.0), - (-0.50, -1.0, -0.0, -0.0, -0.0), # tie to even (-0.0) - (-0.75, -1.0, -0.0, -0.0, -1.0), - (-1.25, -2.0, -1.0, -1.0, -1.0), - (-1.50, -2.0, -1.0, -1.0, -2.0), # tie to even (-2.0 is even) - (-1.75, -2.0, -1.0, -1.0, -2.0), - (-2.50, -3.0, -2.0, -2.0, -2.0), # tie to even (-2.0 is even) - (-3.50, -4.0, -3.0, -3.0, -4.0), # tie to even (-4.0 is even) - ] - for val, exp_fl, exp_ce, exp_tr, exp_rn in cases: - bits = f32_to_bits(val) - with self.subTest(val=val): - self.assertEqual(ref_round_f32_bits(bits, "floor"), f32_to_bits(exp_fl)) - self.assertEqual(ref_round_f32_bits(bits, "ceil"), f32_to_bits(exp_ce)) - self.assertEqual(ref_round_f32_bits(bits, "trunc"), f32_to_bits(exp_tr)) - self.assertEqual(ref_round_f32_bits(bits, "rndne"), f32_to_bits(exp_rn)) - - def test_subnormals_f32(self): - # Positive subnormal: (0.0, 1.0) - pos_sub = 0x00000001 - self.assertEqual(ref_round_f32_bits(pos_sub, "floor"), POS_ZERO_F32) - self.assertEqual(ref_round_f32_bits(pos_sub, "ceil"), f32_to_bits(1.0)) - self.assertEqual(ref_round_f32_bits(pos_sub, "trunc"), POS_ZERO_F32) - self.assertEqual(ref_round_f32_bits(pos_sub, "rndne"), POS_ZERO_F32) - - # Negative subnormal: (-1.0, 0.0) - neg_sub = 0x80000001 - self.assertEqual(ref_round_f32_bits(neg_sub, "floor"), f32_to_bits(-1.0)) - self.assertEqual(ref_round_f32_bits(neg_sub, "ceil"), NEG_ZERO_F32) - self.assertEqual(ref_round_f32_bits(neg_sub, "trunc"), NEG_ZERO_F32) - self.assertEqual(ref_round_f32_bits(neg_sub, "rndne"), NEG_ZERO_F32) - - def test_infinities_and_nans_f32(self): - for val in (POS_INF_F32, NEG_INF_F32, QNAN_F32, 0x7FC01234, 0x7F800001): - for mode in ("floor", "ceil", "trunc", "rndne"): - with self.subTest(val=hex(val), mode=mode): - self.assertEqual(ref_round_f32_bits(val, mode), val) - - def test_large_magnitudes_without_fractions_f32(self): - # 2^23 = 8388608.0; any finite f32 >= 2^23 has ulp >= 1.0, hence is integral - large_values = [ - f32_to_bits(float(1 << 23)), - f32_to_bits(float(1 << 24)), - f32_to_bits(float(1 << 30)), - 0x7F7FFFFF, # max finite float - f32_to_bits(-float(1 << 23)), - 0xFF7FFFFF, # most negative finite float - ] - for bits in large_values: - for mode in ("floor", "ceil", "trunc", "rndne"): - with self.subTest(bits=hex(bits), mode=mode): - self.assertEqual(ref_round_f32_bits(bits, mode), bits) - - def test_f16_reference_oracles(self): - self.assertEqual(ref_round_f16_bits(POS_ZERO_F16, "floor"), POS_ZERO_F16) - self.assertEqual(ref_round_f16_bits(NEG_ZERO_F16, "floor"), NEG_ZERO_F16) - - # 1.75 in f16 is 0x3F00 - h_1_75 = f16_to_bits(1.75) - self.assertEqual(ref_round_f16_bits(h_1_75, "floor"), f16_to_bits(1.0)) - self.assertEqual(ref_round_f16_bits(h_1_75, "ceil"), f16_to_bits(2.0)) - self.assertEqual(ref_round_f16_bits(h_1_75, "trunc"), f16_to_bits(1.0)) - self.assertEqual(ref_round_f16_bits(h_1_75, "rndne"), f16_to_bits(2.0)) - - # -1.75 in f16 is 0xBF00 - h_neg_1_75 = f16_to_bits(-1.75) - self.assertEqual(ref_round_f16_bits(h_neg_1_75, "floor"), f16_to_bits(-2.0)) - self.assertEqual(ref_round_f16_bits(h_neg_1_75, "ceil"), f16_to_bits(-1.0)) - self.assertEqual(ref_round_f16_bits(h_neg_1_75, "trunc"), f16_to_bits(-1.0)) - self.assertEqual(ref_round_f16_bits(h_neg_1_75, "rndne"), f16_to_bits(-2.0)) - - # -0.5 in f16: ceil/trunc/rndne preserve -0.0 - h_neg_0_5 = f16_to_bits(-0.5) - self.assertEqual(ref_round_f16_bits(h_neg_0_5, "floor"), f16_to_bits(-1.0)) - self.assertEqual(ref_round_f16_bits(h_neg_0_5, "ceil"), NEG_ZERO_F16) - self.assertEqual(ref_round_f16_bits(h_neg_0_5, "trunc"), NEG_ZERO_F16) - self.assertEqual(ref_round_f16_bits(h_neg_0_5, "rndne"), NEG_ZERO_F16) - - -class TestMathematicalInvariants(unittest.TestCase): - """Validates core mathematical properties and identities across a broad spectrum - of floating-point values. - """ - - def test_bounding_inequalities(self): - rng = random.Random(42) - test_floats = [ - rng.uniform(-100.0, 100.0) for _ in range(500) - ] + [0.0, -0.0, 0.5, -0.5, 1.5, -1.5, 2.5, -2.5, 1e-10, -1e-10] - - for x in test_floats: - fl = ref_floor_f32(x) - ce = ref_ceil_f32(x) - tr = ref_trunc_f32(x) - rn = ref_rndne_f32(x) - - # Ordering invariant: floor(x) <= x <= ceil(x) - self.assertLessEqual(fl, x) - self.assertGreaterEqual(ce, x) - - # Difference bounds - self.assertGreaterEqual(x - fl, 0.0) - self.assertLess(x - fl, 1.0) - self.assertGreaterEqual(ce - x, 0.0) - self.assertLess(ce - x, 1.0) - self.assertLess(abs(x - tr), 1.0) - self.assertLessEqual(abs(x - rn), 0.5) - - # Truncation relationship - if x >= 0: - self.assertEqual(fl, tr) - self.assertLessEqual(tr, ce) - else: - self.assertEqual(ce, tr) - self.assertGreaterEqual(tr, fl) - - def test_idempotence(self): - test_floats = [-4.8, -3.5, -2.0, -0.7, -0.0, 0.0, 0.3, 1.5, 2.0, 5.9] - for x in test_floats: - for mode in ("floor", "ceil", "trunc", "rndne"): - with self.subTest(x=x, mode=mode): - first = ref_round_f32(x, mode) - second = ref_round_f32(first, mode) - self.assertEqual(first, second) - - def test_reflection_symmetry(self): - test_floats = [0.1, 0.5, 0.75, 1.0, 1.25, 1.5, 2.5, 3.7, 42.0] - for x in test_floats: - with self.subTest(x=x): - # floor(-x) == -ceil(x) - self.assertEqual(ref_floor_f32(-x), -ref_ceil_f32(x)) - # ceil(-x) == -floor(x) - self.assertEqual(ref_ceil_f32(-x), -ref_floor_f32(x)) - # trunc(-x) == -trunc(x) - self.assertEqual(ref_trunc_f32(-x), -ref_trunc_f32(x)) - # rndne(-x) == -rndne(x) - self.assertEqual(ref_rndne_f32(-x), -ref_rndne_f32(x)) - - -class TestRoundValuInterpreter(unittest.TestCase): - """Verifies that RoundValuInterpreter models RDNA2 VALU instructions, operand - modifiers, clamp bounds, and f16 op_sel behavior. - """ - - def setUp(self) -> None: - self.interp = RoundValuInterpreter() - - def test_basic_f32_instructions(self): - self.interp.execute_line("v_mov_b32 v1, 1.75") - self.interp.execute_line("v_floor_f32 v0, v1") - self.assertEqual(self.interp.read_reg("v0"), f32_to_bits(1.0)) - - self.interp.execute_line("v_ceil_f32 v0, v1") - self.assertEqual(self.interp.read_reg("v0"), f32_to_bits(2.0)) - - self.interp.execute_line("v_trunc_f32 v0, v1") - self.assertEqual(self.interp.read_reg("v0"), f32_to_bits(1.0)) - - self.interp.execute_line("v_rndne_f32 v0, v1") - self.assertEqual(self.interp.read_reg("v0"), f32_to_bits(2.0)) - - def test_e32_and_e64_forms(self): - self.interp.execute_line("v_mov_b32 v2, 2.5") - self.interp.execute_line("v_floor_f32_e32 v0, v2") - self.assertEqual(self.interp.read_reg("v0"), f32_to_bits(2.0)) - - self.interp.execute_line("v_floor_f32_e64 v0, v2") - self.assertEqual(self.interp.read_reg("v0"), f32_to_bits(2.0)) - - def test_inline_constants(self): - self.interp.execute_line("v_floor_f32 v0, 1.5") - self.assertEqual(self.interp.read_reg("v0"), f32_to_bits(1.0)) - - self.interp.execute_line("v_ceil_f32 v0, 1.5") - self.assertEqual(self.interp.read_reg("v0"), f32_to_bits(2.0)) - - self.interp.execute_line("v_trunc_f32 v0, -0.5") - self.assertEqual(self.interp.read_reg("v0"), NEG_ZERO_F32) - - self.interp.execute_line("v_rndne_f32 v0, 2.5") - self.assertEqual(self.interp.read_reg("v0"), f32_to_bits(2.0)) - - def test_input_modifiers(self): - self.interp.execute_line("v_mov_b32 v1, -1.75") - - # |v1| = 1.75 -> floor(1.75) = 1.0 - self.interp.execute_line("v_floor_f32_e64 v0, |v1|") - self.assertEqual(self.interp.read_reg("v0"), f32_to_bits(1.0)) - - # -v1 = 1.75 -> ceil(1.75) = 2.0 - self.interp.execute_line("v_ceil_f32_e64 v0, -v1") - self.assertEqual(self.interp.read_reg("v0"), f32_to_bits(2.0)) - - # -|v1| = -1.75 -> trunc(-1.75) = -1.0 - self.interp.execute_line("v_trunc_f32_e64 v0, -|v1|") - self.assertEqual(self.interp.read_reg("v0"), f32_to_bits(-1.0)) - - def test_output_clamp_and_multipliers(self): - # Result > 1.0 clamped to 1.0 - self.interp.execute_line("v_mov_b32 v1, 2.5") - self.interp.execute_line("v_floor_f32 v0, v1 clamp") - self.assertEqual(self.interp.read_reg("v0"), f32_to_bits(1.0)) - - # Result < 0.0 clamped to 0.0 - self.interp.execute_line("v_mov_b32 v1, -2.5") - self.interp.execute_line("v_floor_f32 v0, v1 clamp") - self.assertEqual(self.interp.read_reg("v0"), POS_ZERO_F32) - - # Output multiplier mul:2 before clamp: floor(0.75) = 0.0 * 2 = 0.0 - self.interp.execute_line("v_mov_b32 v1, 0.75") - self.interp.execute_line("v_ceil_f32 v0, v1 mul:2") - self.assertEqual(self.interp.read_reg("v0"), f32_to_bits(2.0)) - - def test_f16_half_selection_and_destination_preservation(self): - # Packed f16: high half 1.75 (0x3F00), low half 3.0 (0x4200) - self.interp.execute_line("v_mov_b32 v4, 0x3F004200") - - # Initial dst with canary pattern 0x12345678 - self.interp.execute_line("v_mov_b32 v0, 0x12345678") - - # op_sel:[1, 1]: read src high (1.75), write dst high (floor(1.75) = 1.0 = 0x3C00) - # Low half (0x5678) must be preserved! - self.interp.execute_line("v_floor_f16 v0, v4 op_sel:[1,1]") - self.assertEqual(self.interp.read_reg("v0"), 0x3C005678) - - # op_sel:[0, 0]: read src low (3.0), write dst low (ceil(3.0) = 3.0 = 0x4200) - # High half (0x3C00) must be preserved! - self.interp.execute_line("v_ceil_f16 v0, v4 op_sel:[0,0]") - self.assertEqual(self.interp.read_reg("v0"), 0x3C004200) - - -class TestSpirvMiniInterpExecution(unittest.TestCase): - """End-to-end integration tests compiling synthetic RDNA2 assembly with - tools/rdna2spirv.py and executing the generated SPIR-V in - tests/semantic/spirv_mini_interp.py. - """ - - def test_f32_rounding_modes(self): - # Run floor, ceil, trunc, rndne on 1.75 - out = run_assembly([ - "v_mov_b32 v4, 1.75", - "v_floor_f32 v0, v4", - "v_ceil_f32 v1, v4", - "v_trunc_f32 v2, v4", - "v_rndne_f32 v3, v4", - ]) - self.assertEqual(out[0], f32_to_bits(1.0)) - self.assertEqual(out[1], f32_to_bits(2.0)) - self.assertEqual(out[2], f32_to_bits(1.0)) - self.assertEqual(out[3], f32_to_bits(2.0)) - - def test_f32_negative_fraction_and_signed_zero(self): - # On -0.5: floor is -1.0, while ceil, trunc, rndne give -0.0 - out = run_assembly([ - "v_mov_b32 v4, -0.5", - "v_floor_f32 v0, v4", - "v_ceil_f32 v1, v4", - "v_trunc_f32 v2, v4", - "v_rndne_f32 v3, v4", - ]) - self.assertEqual(out[0], f32_to_bits(-1.0)) - self.assertEqual(out[1], NEG_ZERO_F32) - self.assertEqual(out[2], NEG_ZERO_F32) - self.assertEqual(out[3], NEG_ZERO_F32) - - def test_f32_subnormal_execution(self): - # Negative subnormal 0x80000001 - out = run_assembly([ - "v_mov_b32 v4, 0x80000001", - "v_floor_f32 v0, v4", - "v_ceil_f32 v1, v4", - "v_trunc_f32 v2, v4", - "v_rndne_f32 v3, v4", - ]) - # v_floor reads a denormal as zero (f32 denormals flushed, docs/design.md), so floor(-denormal) is -0. - self.assertEqual(out[0], NEG_ZERO_F32) - self.assertEqual(out[1], NEG_ZERO_F32) - self.assertEqual(out[2], NEG_ZERO_F32) - self.assertEqual(out[3], NEG_ZERO_F32) - - def test_f32_infinities_and_nans(self): - out = run_assembly([ - "v_mov_b32 v4, 0x7F800000", # +inf - "v_floor_f32 v0, v4", - "v_mov_b32 v5, 0xFF800000", # -inf - "v_ceil_f32 v1, v5", - "v_mov_b32 v6, 0x7FC00000", # qNaN - "v_trunc_f32 v2, v6", - "v_rndne_f32 v3, v4", - ]) - self.assertEqual(out[0], POS_INF_F32) - self.assertEqual(out[1], NEG_INF_F32) - self.assertEqual(out[2], QNAN_F32) - self.assertEqual(out[3], POS_INF_F32) - - def test_modifiers_and_clamp_in_spirv(self): - out = run_assembly([ - "v_mov_b32 v4, 0xBFC00000", # -1.5 - "v_floor_f32_e64 v0, |v4|", # floor(|-1.5|) = 1.0 - "v_floor_f32_e64 v1, -v4", # floor(-(-1.5)) = 1.0 - "v_mov_b32 v5, 2.5", - "v_floor_f32 v2, v5 clamp", # floor(2.5) = 2.0 -> clamp to 1.0 - "v_mov_b32 v6, -2.5", - "v_floor_f32 v3, v6 clamp", # floor(-2.5) = -3.0 -> clamp to 0.0 - ]) - self.assertEqual(out[0], f32_to_bits(1.0)) - self.assertEqual(out[1], f32_to_bits(1.0)) - self.assertEqual(out[2], f32_to_bits(1.0)) - self.assertEqual(out[3], POS_ZERO_F32) - - def test_f16_execution_and_op_sel(self): - out = run_assembly([ - "v_mov_b32 v4, 0x3F004200", # hi: 1.75, lo: 3.0 - "v_mov_b32 v0, 0x12345678", - "v_floor_f16 v0, v4 op_sel:[1,1]", # hi = floor(1.75) = 1.0 (0x3C00) - "v_mov_b32 v1, 0x12345678", - "v_ceil_f16 v1, v4 op_sel:[0,0]", # lo = ceil(3.0) = 3.0 (0x4200) - "v_mov_b32 v2, 0", - "v_mov_b32 v3, 0", - ]) - self.assertEqual(out[0], 0x3C005678) - self.assertEqual(out[1], 0x12344200) - - def test_spirv_opcode_generation(self): - assert _SRC_PATH is not None - asm = ( - "; test_spirv_opcodes\n" - "\tv_floor_f32 v0, v0\n" - "\tv_ceil_f32 v1, v1\n" - "\tv_trunc_f32 v2, v2\n" - "\tv_rndne_f32 v3, v3\n" - "\texp mrt0 v0, v1, v2, v3 done vm\n\ts_endpgm\n" - ) - with open(_SRC_PATH, "w", encoding="utf-8") as f: - f.write(asm) - spv = rdna2spirv.translate(_SRC_PATH) - - self.assertIn("OpExtInst %float %glsl Floor", spv) - self.assertIn("OpExtInst %float %glsl Ceil", spv) - self.assertIn("OpExtInst %float %glsl Trunc", spv) - self.assertIn("OpExtInst %float %glsl RoundEven", spv) - - -class TestMultiLaneSimdWave(unittest.TestCase): - """Verifies that vector rounding instructions execute correctly across all 64 - independent lanes of a SIMD Wave64 without lane cross-contamination. - """ - - def test_wave64_simd_rounding(self): - num_lanes = 64 - rng = random.Random(1337) - lane_inputs = [ - rng.uniform(-50.0, 50.0) for _ in range(num_lanes) - ] - # Force specific boundary edge cases in prominent lanes - lane_inputs[0] = 0.0 - lane_inputs[1] = -0.0 - lane_inputs[2] = 0.5 - lane_inputs[3] = -0.5 - lane_inputs[4] = 1.5 - lane_inputs[5] = -1.5 - lane_inputs[6] = 2.5 - lane_inputs[7] = -2.5 - - interp = RoundValuInterpreter() - expected_floor = [ref_floor_f32(x) for x in lane_inputs] - expected_ceil = [ref_ceil_f32(x) for x in lane_inputs] - expected_trunc = [ref_trunc_f32(x) for x in lane_inputs] - expected_rndne = [ref_rndne_f32(x) for x in lane_inputs] - - actual_floor = [] - actual_ceil = [] - actual_trunc = [] - actual_rndne = [] - - for x in lane_inputs: - bits = f32_to_bits(x) - interp.write_reg("v1", bits) - - interp.execute_line("v_floor_f32 v0, v1") - actual_floor.append(bits_to_f32(interp.read_reg("v0"))) - - interp.execute_line("v_ceil_f32 v0, v1") - actual_ceil.append(bits_to_f32(interp.read_reg("v0"))) - - interp.execute_line("v_trunc_f32 v0, v1") - actual_trunc.append(bits_to_f32(interp.read_reg("v0"))) - - interp.execute_line("v_rndne_f32 v0, v1") - actual_rndne.append(bits_to_f32(interp.read_reg("v0"))) - - for i in range(num_lanes): - self.assertEqual(f32_to_bits(actual_floor[i]), f32_to_bits(expected_floor[i])) - self.assertEqual(f32_to_bits(actual_ceil[i]), f32_to_bits(expected_ceil[i])) - self.assertEqual(f32_to_bits(actual_trunc[i]), f32_to_bits(expected_trunc[i])) - self.assertEqual(f32_to_bits(actual_rndne[i]), f32_to_bits(expected_rndne[i])) - - -class TestNegativeControls(unittest.TestCase): - """Negative controls ensuring mutated semantics or dropped edge cases fail.""" - - def test_floor_ceil_swap_detected(self): - # 1.5: floor=1.0, ceil=2.0 - val = 1.5 - correct_floor = ref_floor_f32(val) - mutated_floor = ref_ceil_f32(val) - self.assertNotEqual(correct_floor, mutated_floor) - - def test_signed_zero_dropping_detected(self): - # -0.5: trunc must be -0.0 (0x80000000), not +0.0 (0x00000000) - bits_neg_half = f32_to_bits(-0.5) - correct_trunc_bits = ref_round_f32_bits(bits_neg_half, "trunc") - mutated_trunc_bits = POS_ZERO_F32 - self.assertEqual(correct_trunc_bits, NEG_ZERO_F32) - self.assertNotEqual(correct_trunc_bits, mutated_trunc_bits) - - def test_tie_to_odd_detected(self): - # 1.5: round-to-nearest-even gives 2.0; round-to-nearest-odd would give 1.0 - val = 1.5 - correct_rndne = ref_rndne_f32(val) - tie_to_odd = 1.0 - self.assertEqual(correct_rndne, 2.0) - self.assertNotEqual(correct_rndne, tie_to_odd) - - def test_clamp_omission_detected(self): - val = 2.5 - unclamped = ref_floor_f32(val) # 2.0 - clamped = max(0.0, min(1.0, unclamped)) # 1.0 - self.assertNotEqual(unclamped, clamped) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_alu_rounding.py b/tests/semantic/test_alu_rounding.py deleted file mode 100644 index fa902682d..000000000 --- a/tests/semantic/test_alu_rounding.py +++ /dev/null @@ -1,141 +0,0 @@ -"""Semantic interpreter tests for RDNA2 v_floor, v_ceil, v_trunc and v_rndne, in f32 and f16. - -Each op rounds to an integral value in the operand's format: floor toward -inf, ceil toward +inf, trunc toward zero, -rndne to the nearest with ties to even. As in IEEE 754 roundToIntegral, a zero result keeps the operand's sign -(ceil(-0.5) = -0.0), and infinities come back unchanged. The f16 forms write the low half of the destination and keep -the high half (docs/design.md, "16-bit results"). Each case translates a synthetic pixel shader with -tools/rdna2spirv.py, runs it in tests/semantic/spirv_mini_interp.py and compares the exported word with a -plain-Python reference. NaN inputs are left out (their payload is not modelled), and so are f32 denormals (the -float mode that would flush them is not modelled either). -""" -import math -import os -import random -import struct -import sys -import tempfile -import unittest -import warnings - -HERE = os.path.dirname(os.path.abspath(__file__)) -ROOT = os.path.dirname(os.path.dirname(HERE)) -TOOLS_DIR = os.environ.get("LEONIDA_TOOLS_DIR") or os.path.join(ROOT, "tools") - -sys.dont_write_bytecode = True -sys.path.insert(0, TOOLS_DIR) -sys.path.insert(0, HERE) - -import rdna2spirv # noqa: E402 -import spirv_mini_interp as si # noqa: E402 - -STUB_DXBC = b"DXBC" + bytes(24) + struct.pack(" float: - return struct.unpack(" int: - return struct.unpack(" float: - return struct.unpack(" int: - return struct.unpack(" float: - if not math.isfinite(x): - return x - return math.copysign(float(ROUND[kind](x)), x) - - -_TMP_DIR = None -_SRC_PATH = None - - -def setUpModule(): - global _TMP_DIR, _SRC_PATH - _TMP_DIR = tempfile.TemporaryDirectory() - disasm_dir = os.path.join(_TMP_DIR.name, "disasm") - os.mkdir(disasm_dir) - _SRC_PATH = os.path.join(disasm_dir, "ps_rounding.s") - with open(os.path.join(_TMP_DIR.name, "ps_rounding.dxbc"), "wb") as f: - f.write(STUB_DXBC) - - -def tearDownModule(): - global _TMP_DIR - if _TMP_DIR is not None: - _TMP_DIR.cleanup() - _TMP_DIR = None - - -def run(line: str, v1: int, old: int = 0) -> int: - """Seed v1 and the destination v0, run ``line``, return v0.""" - if _TMP_DIR is None: - setUpModule() - lines = [f"v_mov_b32 v1, {v1:#x}", f"v_mov_b32 v0, {old:#x}", line] - asm = "; test_rounding\n" + "".join(f"\t{ln}\n" for ln in lines) + "\texp mrt0 v0, v0, v0, v0 done vm\n\ts_endpgm\n" - with open(_SRC_PATH, "w", encoding="utf-8") as f: - f.write(asm) - with warnings.catch_warnings(): - warnings.simplefilter("ignore", ResourceWarning) - spv = rdna2spirv.translate(_SRC_PATH) - return si.run_fragment(spv)["%out_mrt0"][0] - - -class ReferenceTests(unittest.TestCase): - def test_reference(self): - self.assertEqual(f2u(ref("floor", -2.5)), 0xC0400000) - self.assertEqual(f2u(ref("ceil", -0.5)), 0x80000000) - self.assertEqual(f2u(ref("trunc", -0.5)), 0x80000000) - self.assertEqual(f2u(ref("rndne", 2.5)), 0x40000000) - self.assertEqual(f2u(ref("rndne", -0.5)), 0x80000000) - self.assertEqual(f2h(ref("floor", h2f(0x8001))), 0xBC00) # smallest negative denormal -> -1 - - -class RoundingF32Tests(unittest.TestCase): - def test_each_op_on_edge_values(self): - for kind in ROUND: - for x in F32_VALUES: - with self.subTest(op=f"v_{kind}_f32", x=hex(x)): - self.assertEqual(run(f"v_{kind}_f32_e32 v0, v1", x), f2u(ref(kind, u2f(x)))) - - def test_seeded_values(self): - rng = random.Random(0xF1) - for _ in range(30): - # Exponents around the integral boundary (2^-2 .. 2^25) are where the rounding matters. - x = rng.getrandbits(1) << 31 | rng.randrange(125, 152) << 23 | rng.getrandbits(23) - kind = rng.choice(list(ROUND)) - with self.subTest(op=f"v_{kind}_f32", x=hex(x)): - self.assertEqual(run(f"v_{kind}_f32_e32 v0, v1", x), f2u(ref(kind, u2f(x)))) - - -class RoundingF16Tests(unittest.TestCase): - def test_each_op_keeps_the_high_half(self): - for kind in ROUND: - for h in F16_VALUES: - with self.subTest(op=f"v_{kind}_f16", x=hex(h)): - got = run(f"v_{kind}_f16_e32 v0, v1", 0x12340000 | h, OLD) - self.assertEqual(got, OLD & 0xFFFF0000 | f2h(ref(kind, h2f(h)))) - - def test_op_sel_reads_the_high_half(self): - v1 = 0xBE00 << 16 | 0x4100 # hi -1.5, lo 2.5 - self.assertEqual(run("v_floor_f16_e64 v0, v1 op_sel:[1,0]", v1, OLD), OLD & 0xFFFF0000 | f2h(-2.0)) - self.assertEqual(run("v_ceil_f16_e64 v0, v1 op_sel:[0,1]", v1, OLD), f2h(3.0) << 16 | OLD & 0xFFFF) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_alu_rsq_f32.py b/tests/semantic/test_alu_rsq_f32.py deleted file mode 100644 index a6ff44a40..000000000 --- a/tests/semantic/test_alu_rsq_f32.py +++ /dev/null @@ -1,140 +0,0 @@ -"""Semantic translation tests for RDNA2 32-bit inverse square root v_rsq_f32. - -Translates a synthetic pixel-shader listing through tools/rdna2spirv.translate() --> SPIR-V -> tests/semantic/spirv_mini_interp.py and compares the result against -a plain-Python reference: 1.0 / math.sqrt(x) for finite positive x. - -Covers: - - Exact values: rsq(1) = 1, rsq(4) = 0.5, rsq(16) = 0.25, rsq(0.25) = 2 - - rsq(2) with tolerance 1e-6 - - rsq(+inf) -> +0 - - Reference comparison across varied positive bit patterns - - 50 randomized positive cases vs reference - - Negative control: result differs from input for non-trivial cases -""" -import math -import os -import struct -import sys -import tempfile -import unittest -import warnings -import random - -HERE = os.path.dirname(os.path.abspath(__file__)) -ROOT = os.path.dirname(os.path.dirname(HERE)) -TOOLS_DIR = os.environ.get("LEONIDA_TOOLS_DIR") or os.path.join(ROOT, "tools") - -sys.dont_write_bytecode = True -if TOOLS_DIR not in sys.path: - sys.path.insert(0, TOOLS_DIR) -if HERE not in sys.path: - sys.path.insert(0, HERE) - -import rdna2spirv # noqa: E402 -import spirv_mini_interp as si # noqa: E402 - -M32 = 0xFFFFFFFF -STUB_DXBC = b"DXBC" + bytes(24) + struct.pack(" list: - return [(x >> off) & ((1 << width) - 1) for off in range(0, 32, width)] - - -def sad(x: int, y: int, width: int, masked: bool = False) -> int: - return sum(abs(p - q) for p, q in zip(parts(x, width), parts(y, width)) if not (masked and q == 0)) - - -OPS = { - "v_sad_u8": lambda x, y, z: (sad(x, y, 8) + z) & MASK32, - "v_sad_hi_u8": lambda x, y, z: ((sad(x, y, 8) << 16) + z) & MASK32, - "v_sad_u16": lambda x, y, z: (sad(x, y, 16) + z) & MASK32, - "v_sad_u32": lambda x, y, z: (sad(x, y, 32) + z) & MASK32, - "v_msad_u8": lambda x, y, z: (sad(x, y, 8, masked=True) + z) & MASK32, -} -VALUES = [0, 0xFFFFFFFF, 0x00FF00FF, 0xFF00FF00, 0x01020304, 0x80808080, 0x7F7F7F7F, 0xFFFF0000, 0x12345678] -ACCS = [0, 1, 0xFFFFFFFF, 0xFFFFFC00, 0x7FFF0000] - -_TMP_DIR = None -_SRC_PATH = None - - -def setUpModule(): - global _TMP_DIR, _SRC_PATH - _TMP_DIR = tempfile.TemporaryDirectory() - disasm_dir = os.path.join(_TMP_DIR.name, "disasm") - os.mkdir(disasm_dir) - _SRC_PATH = os.path.join(disasm_dir, "ps_sad.s") - with open(os.path.join(_TMP_DIR.name, "ps_sad.dxbc"), "wb") as f: - f.write(STUB_DXBC) - - -def tearDownModule(): - global _TMP_DIR - if _TMP_DIR is not None: - _TMP_DIR.cleanup() - _TMP_DIR = None - - -def run_lines(lines) -> int: - """Run the lines, return v0 (exported as two 16-bit halves, see the module docstring).""" - if _TMP_DIR is None: - setUpModule() - lines = list(lines) + ["v_and_b32 v5, 0xffff, v0", "v_lshrrev_b32 v6, 16, v0", - "v_or_b32 v5, 0x40000000, v5", "v_or_b32 v6, 0x40000000, v6"] - asm = "; test_sad\n" + "".join(f"\t{ln}\n" for ln in lines) + "\texp mrt0 v5, v6, v5, v5 done vm\n\ts_endpgm\n" - with open(_SRC_PATH, "w", encoding="utf-8") as f: - f.write(asm) - with warnings.catch_warnings(): - warnings.simplefilter("ignore", ResourceWarning) - spv = rdna2spirv.translate(_SRC_PATH) - lo, hi = si.run_fragment(spv)["%out_mrt0"][:2] - assert lo >> 16 == 0x4000 and hi >> 16 == 0x4000, (hex(lo), hex(hi)) - return (lo & 0xFFFF) | (hi & 0xFFFF) << 16 - - -def run_op(op: str, x: int, y: int, z: int) -> int: - return run_lines([f"v_mov_b32 v1, {x:#x}", f"v_mov_b32 v2, {y:#x}", f"v_mov_b32 v3, {z:#x}", f"{op} v0, v1, v2, v3"]) - - -class SadTests(unittest.TestCase): - def test_reference(self): - self.assertEqual(OPS["v_sad_u8"](0x01020304, 0x04030201, 10), 10 + 3 + 1 + 1 + 3) - self.assertEqual(OPS["v_sad_hi_u8"](0xFF, 0, 1), (255 << 16) + 1) - self.assertEqual(OPS["v_sad_u16"](0x0000FFFF, 0xFFFF0000, 0), 2 * 0xFFFF) - self.assertEqual(OPS["v_sad_u32"](0, 0xFFFFFFFF, 1), 0) # wraps at 32 bits - self.assertEqual(OPS["v_msad_u8"](0x10203040, 0x00200030, 0), 0x10 + 0) # bytes with S1 = 0 skipped - - def test_edge_values(self): - for op, fn in OPS.items(): - for x in VALUES: - for y in VALUES: - z = ACCS[(x ^ y) % len(ACCS)] - with self.subTest(op=op, x=hex(x), y=hex(y), z=hex(z)): - self.assertEqual(run_op(op, x, y, z), fn(x, y, z)) - - def test_seeded(self): - rng = random.Random(0x5AD) - for _ in range(40): - op = rng.choice(list(OPS)) - x, y, z = rng.getrandbits(32), rng.getrandbits(32), rng.getrandbits(32) - if op == "v_msad_u8" and rng.random() < 0.5: - y &= rng.choice([0xFF00FF00, 0x00FFFF00, 0xFFFFFF00]) # zero some reference bytes - with self.subTest(op=op, x=hex(x), y=hex(y), z=hex(z)): - self.assertEqual(run_op(op, x, y, z), OPS[op](x, y, z)) - - def test_scalar_and_inline_operands(self): - self.assertEqual(run_lines(["s_mov_b32 s2, 0x01010101", "v_mov_b32 v1, 0x03030303", "v_sad_u8 v0, s2, v1, 7"]), - 7 + 4 * 2) - - def test_clamp_is_rejected_not_guessed(self): - with self.assertRaises(rdna2spirv.Unsupported): - run_lines(["v_mov_b32 v1, 1", "v_sad_u8 v0, v1, v1, v1 clamp"]) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_alu_sad_hi_u32.py b/tests/semantic/test_alu_sad_hi_u32.py deleted file mode 100644 index 2ba3a2c81..000000000 --- a/tests/semantic/test_alu_sad_hi_u32.py +++ /dev/null @@ -1,41 +0,0 @@ -"""v_sad_hi_u32 is not an RDNA2 instruction, and tools/rdna2spirv.py rejects it. - -The previous version of this file (944 lines) modelled "v_sad_hi_u32 = high 32 bits of |S0 - S1| + S2" with a private -Python function and hand-written SPIR-V, and never called the translator. RDNA2 has v_sad_u8, v_sad_hi_u8, v_sad_u16 -and v_sad_u32, but no v_sad_hi_u32 (llvm-mc -triple=amdgcn -mcpu=gfx1030: "invalid instruction"), so there is no ISA -semantics to test against; the honest test is that the translator refuses the mnemonic by name instead of inventing -one. The neighbouring real ops still translate, so the refusal is specific to this mnemonic. -""" -import os -import sys -import unittest - -HERE = os.path.dirname(os.path.abspath(__file__)) -sys.dont_write_bytecode = True -sys.path.insert(0, HERE) -import support # noqa: E402 -import rdna2spirv # noqa: E402 - - -def program(ins): - return ["v_mov_b32 v1, 7", "v_mov_b32 v2, 9", "v_mov_b32 v3, 11", ins, "exp mrt0 v0, v0, v0, v0 done vm", "s_endpgm"] - - -class SadHiU32Unsupported(unittest.TestCase): - def test_refused_by_name_in_every_form(self): - for ins in ("v_sad_hi_u32 v0, v1, v2, v3", "v_sad_hi_u32 v0, s1, v2, v3", "v_sad_hi_u32 v0, v1, 5, 0xffffffff", - "v_sad_hi_u32 v1, v1, v2, v1", "v_sad_hi_u32 v0, v1, v2, v3 clamp"): - with self.subTest(ins=ins): - with self.assertRaises(rdna2spirv.Unsupported) as refused: - support.translate_lines("ps_sad_hi_u32", program(ins)) - self.assertEqual(str(refused.exception), "v_sad_hi_u32") - - def test_the_real_sad_ops_translate(self): - for ins in ("v_sad_u32 v0, v1, v2, v3", "v_sad_hi_u8 v0, v1, v2, v3", "v_sad_u8 v0, v1, v2, v3", - "v_sad_u16 v0, v1, v2, v3"): - with self.subTest(ins=ins): - self.assertIn("OpFunction", support.translate_lines("ps_sad_ok", program(ins))) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_alu_sad_u32.py b/tests/semantic/test_alu_sad_u32.py deleted file mode 100644 index 93d8920f6..000000000 --- a/tests/semantic/test_alu_sad_u32.py +++ /dev/null @@ -1,682 +0,0 @@ -from __future__ import annotations - -"""Semantic interpreter tests for AMD RDNA2 / GFX10 Vector ALU sum of absolute -differences instructions: v_sad_u32 and v_sad_hi_u32. - -ISA Specifications (AMD RDNA2 / GFX10 Instruction Set Architecture): -- v_sad_u32 (VOP3 3-operand vector ALU instruction, opcode 349): - Calculates the 32-bit unsigned sum of absolute differences with accumulation: - diff = |src0.u32 - src1.u32| - dst.u32 = (diff + src2.u32) mod 2^32 - Note on Unsigned Semantics (documented in AMD GCN/RDNA ISA errata): - The absolute difference is computed in unsigned arithmetic: - diff = (src0 >= src1) ? (src0 - src1) : (src1 - src0) - All inputs and distances operate on unsigned 32-bit integers in [0, 2^32 - 1]. - Treating operands as signed integers (e.g. 0xFFFFFFFF as -1) is an architectural - deviation that produces incorrect results (e.g. |0 - 0xFFFFFFFF| is 0xFFFFFFFF, not 1). - -- v_sad_hi_u32 (High 32-bit carry / accumulation for multi-precision SAD): - Models the high 32-bit carry/overflow word of the full 64-bit sum: - diff = |src0.u32 - src1.u32| - full_sum = diff + src2.u32 - dst.u32 = (full_sum >> 32) & 0xFFFFFFFF - Since diff <= 2^32 - 1 and src2 <= 2^32 - 1, full_sum <= 2^33 - 2, so the high - carry word is strictly in {0, 1}. - Pairing (v_sad_u32, v_sad_hi_u32) synthesizes full 64-bit precision sum of - absolute differences with accumulation. - In RDNA2 ISA, v_sad_hi_u32 is not a hardware opcode (the hardware provides - v_sad_hi_u8 for media extensions, while 32-bit multi-precision carry uses - OpIAddCarry / carry chaining). Translator integration confirms that unknown - opcodes raise Unsupported rather than silently miscompiling. - -Standard library only: no GPU, no LLVM, no external tools, zero game data. -Verified against tools/rdna2spirv.py and tests/semantic/spirv_mini_interp.py. -""" -import gc -import os -import random -import struct -import sys -import tempfile -import unittest -import warnings - -HERE = os.path.dirname(os.path.abspath(__file__)) -ROOT = os.path.dirname(os.path.dirname(HERE)) -TOOLS_DIR = os.environ.get("LEONIDA_TOOLS_DIR") or os.path.join(ROOT, "tools") - -sys.dont_write_bytecode = True -if TOOLS_DIR not in sys.path: - sys.path.insert(0, TOOLS_DIR) -if HERE not in sys.path: - sys.path.insert(0, HERE) - -import rdna2spirv # noqa: E402 -import spirv_mini_interp as si # noqa: E402 -import support # noqa: E402 - -MASK32 = 0xFFFFFFFF -MASK64 = 0xFFFFFFFFFFFFFFFF -STUB_DXBC = b"DXBC" + bytes(24) + struct.pack(" None: - global _TMP_DIR, _SRC_PATH - _TMP_DIR = tempfile.TemporaryDirectory() - disasm_dir = os.path.join(_TMP_DIR.name, "disasm") - os.mkdir(disasm_dir) - _SRC_PATH = os.path.join(disasm_dir, "ps_sad.s") - with open(os.path.join(_TMP_DIR.name, "ps_sad.dxbc"), "wb") as f: - f.write(STUB_DXBC) - - -def tearDownModule() -> None: - global _TMP_DIR, _SRC_PATH - if _TMP_DIR is not None: - gc.collect() - _TMP_DIR.cleanup() - _TMP_DIR = None - _SRC_PATH = None - - -def ref_abs_diff_u32(s0: int, s1: int) -> int: - """Calculate the strictly unsigned absolute difference |s0 - s1|.""" - u0 = s0 & MASK32 - u1 = s1 & MASK32 - return (u0 - u1) if u0 >= u1 else (u1 - u0) - - -def ref_sad_u32(s0: int, s1: int, s2: int) -> int: - """Calculate v_sad_u32: |s0 - s1| + s2 wrapped to 32 bits.""" - diff = ref_abs_diff_u32(s0, s1) - return (diff + (s2 & MASK32)) & MASK32 - - -def ref_sad_u32_clamp(s0: int, s1: int, s2: int) -> int: - """Calculate v_sad_u32 with clamp modifier: clamped to 0xFFFFFFFF on overflow.""" - diff = ref_abs_diff_u32(s0, s1) - full_sum = diff + (s2 & MASK32) - return min(full_sum, MASK32) - - -def ref_sad_hi_u32(s0: int, s1: int, s2: int) -> int: - """Calculate v_sad_hi_u32: high 32 bits (carry out) of (|s0 - s1| + s2).""" - diff = ref_abs_diff_u32(s0, s1) - full_sum = diff + (s2 & MASK32) - return (full_sum >> 32) & MASK32 - - -def ref_sad_64(s0: int, s1: int, s2: int) -> tuple[int, int]: - """Synthesize 64-bit result (lo, hi) from the (v_sad_u32, v_sad_hi_u32) pair.""" - return ref_sad_u32(s0, s1, s2), ref_sad_hi_u32(s0, s1, s2) - - -def ref_sad_hi_u32_shift16(s0: int, s1: int, s2: int) -> int: - """Shifted variant (analogous to v_sad_hi_u8 in media extensions): (|s0 - s1| << 16) + s2.""" - diff = ref_abs_diff_u32(s0, s1) - return (((diff & 0xFFFF) << 16) + (s2 & MASK32)) & MASK32 - - -def ref_sad_hi_u32_upper_halfwords(s0: int, s1: int, s2: int) -> int: - """High halfword SAD variant: |s0[31:16] - s1[31:16]| + s2.""" - h0 = (s0 >> 16) & 0xFFFF - h1 = (s1 >> 16) & 0xFFFF - diff = (h0 - h1) if h0 >= h1 else (h1 - h0) - return (diff + (s2 & MASK32)) & MASK32 - - -def run_spirv_sad_u32(s0: int, s1: int, s2: int) -> int: - """Executes the canonical SPIR-V instruction sequence for v_sad_u32 via spirv_mini_interp.""" - module = f"""\ -OpCapability Shader -%glsl = OpExtInstImport "GLSL.std.450" -OpMemoryModel Logical GLSL450 -OpEntryPoint Fragment %main "main" %out -%void = OpTypeVoid -%fn = OpTypeFunction %void -%bool = OpTypeBool -%uint = OpTypeInt 32 0 -%_ptr_Output_uint = OpTypePointer Output %uint -%out = OpVariable %_ptr_Output_uint Output -%c_s0 = OpConstant %uint {s0 & MASK32} -%c_s1 = OpConstant %uint {s1 & MASK32} -%c_s2 = OpConstant %uint {s2 & MASK32} -%main = OpFunction %void None %fn -%entry = OpLabel -%cond = OpUGreaterThanEqual %bool %c_s0 %c_s1 -%d0 = OpISub %uint %c_s0 %c_s1 -%d1 = OpISub %uint %c_s1 %c_s0 -%diff = OpSelect %uint %cond %d0 %d1 -%res = OpIAdd %uint %diff %c_s2 -OpStore %out %res -OpReturn -OpFunctionEnd -""" - return si.run_fragment(module)["%out"][0] - - -def run_spirv_sad_hi_u32(s0: int, s1: int, s2: int) -> tuple[int, int]: - """Executes the canonical SPIR-V lowering for full 64-bit SAD (v_sad_u32, v_sad_hi_u32) - using OpIAddCarry via spirv_mini_interp. Returns (lo, hi). - """ - module = f"""\ -OpCapability Shader -%glsl = OpExtInstImport "GLSL.std.450" -OpMemoryModel Logical GLSL450 -OpEntryPoint Fragment %main "main" %out_lo %out_hi -%void = OpTypeVoid -%fn = OpTypeFunction %void -%bool = OpTypeBool -%uint = OpTypeInt 32 0 -%struct_u2 = OpTypeStruct %uint %uint -%_ptr_Output_uint = OpTypePointer Output %uint -%out_lo = OpVariable %_ptr_Output_uint Output -%out_hi = OpVariable %_ptr_Output_uint Output -%c_s0 = OpConstant %uint {s0 & MASK32} -%c_s1 = OpConstant %uint {s1 & MASK32} -%c_s2 = OpConstant %uint {s2 & MASK32} -%main = OpFunction %void None %fn -%entry = OpLabel -%cond = OpUGreaterThanEqual %bool %c_s0 %c_s1 -%d0 = OpISub %uint %c_s0 %c_s1 -%d1 = OpISub %uint %c_s1 %c_s0 -%diff = OpSelect %uint %cond %d0 %d1 -%sum = OpIAddCarry %struct_u2 %diff %c_s2 -%lo = OpCompositeExtract %uint %sum 0 -%hi = OpCompositeExtract %uint %sum 1 -OpStore %out_lo %lo -OpStore %out_hi %hi -OpReturn -OpFunctionEnd -""" - res = si.run_fragment(module) - return res["%out_lo"][0], res["%out_hi"][0] - - -def run_spirv_sad_u32_clamp(s0: int, s1: int, s2: int) -> int: - """Executes the canonical SPIR-V lowering for v_sad_u32 with clamp modifier.""" - module = f"""\ -OpCapability Shader -%glsl = OpExtInstImport "GLSL.std.450" -OpMemoryModel Logical GLSL450 -OpEntryPoint Fragment %main "main" %out -%void = OpTypeVoid -%fn = OpTypeFunction %void -%bool = OpTypeBool -%uint = OpTypeInt 32 0 -%struct_u2 = OpTypeStruct %uint %uint -%_ptr_Output_uint = OpTypePointer Output %uint -%out = OpVariable %_ptr_Output_uint Output -%c_s0 = OpConstant %uint {s0 & MASK32} -%c_s1 = OpConstant %uint {s1 & MASK32} -%c_s2 = OpConstant %uint {s2 & MASK32} -%c_zero = OpConstant %uint 0 -%c_max = OpConstant %uint 4294967295 -%main = OpFunction %void None %fn -%entry = OpLabel -%cond = OpUGreaterThanEqual %bool %c_s0 %c_s1 -%d0 = OpISub %uint %c_s0 %c_s1 -%d1 = OpISub %uint %c_s1 %c_s0 -%diff = OpSelect %uint %cond %d0 %d1 -%sum = OpIAddCarry %struct_u2 %diff %c_s2 -%lo = OpCompositeExtract %uint %sum 0 -%hi = OpCompositeExtract %uint %sum 1 -%overflow = OpINotEqual %bool %hi %c_zero -%clamped = OpSelect %uint %overflow %c_max %lo -OpStore %out %clamped -OpReturn -OpFunctionEnd -""" - return si.run_fragment(module)["%out"][0] - - -def run_spirv_sad_hi_shift16(s0: int, s1: int, s2: int) -> int: - """Executes the media extension shift-16 variant in SPIR-V: (|s0 - s1| << 16) + s2.""" - module = f"""\ -OpCapability Shader -%glsl = OpExtInstImport "GLSL.std.450" -OpMemoryModel Logical GLSL450 -OpEntryPoint Fragment %main "main" %out -%void = OpTypeVoid -%fn = OpTypeFunction %void -%bool = OpTypeBool -%uint = OpTypeInt 32 0 -%_ptr_Output_uint = OpTypePointer Output %uint -%out = OpVariable %_ptr_Output_uint Output -%c_s0 = OpConstant %uint {s0 & MASK32} -%c_s1 = OpConstant %uint {s1 & MASK32} -%c_s2 = OpConstant %uint {s2 & MASK32} -%c_16 = OpConstant %uint 16 -%c_mask16 = OpConstant %uint 65535 -%main = OpFunction %void None %fn -%entry = OpLabel -%cond = OpUGreaterThanEqual %bool %c_s0 %c_s1 -%d0 = OpISub %uint %c_s0 %c_s1 -%d1 = OpISub %uint %c_s1 %c_s0 -%diff = OpSelect %uint %cond %d0 %d1 -%diff_masked = OpBitwiseAnd %uint %diff %c_mask16 -%shifted = OpShiftLeftLogical %uint %diff_masked %c_16 -%res = OpIAdd %uint %shifted %c_s2 -OpStore %out %res -OpReturn -OpFunctionEnd -""" - return si.run_fragment(module)["%out"][0] - - -def run_synthetic_shader(asm_instructions: list[str]) -> tuple[list[int], str]: - """Translate synthetic RDNA2 disassembly to SPIR-V and execute it via spirv_mini_interp.""" - if _TMP_DIR is None or _SRC_PATH is None: - setUpModule() - assert _SRC_PATH is not None - - lines = ["; synthetic shader for alu_sad_u32 test"] - for ins in asm_instructions: - lines.append("\t" + ins.strip()) - content = "\n".join(lines) + "\n" - - with open(_SRC_PATH, "w", encoding="utf-8") as f: - f.write(content) - with warnings.catch_warnings(): - warnings.simplefilter("ignore", ResourceWarning) - spvasm = rdna2spirv.translate(_SRC_PATH) - words = support.mrt0_words(spvasm) - return words, spvasm - - -def run_synthetic_sad_u32(s0: int, s1: int, s2: int) -> int: - """Executes a translated v_sad_u32 shader and returns the resulting 32-bit output.""" - asm = [ - f"v_mov_b32 v1, {s0 & MASK32:#x}", - f"v_mov_b32 v2, {s1 & MASK32:#x}", - f"v_mov_b32 v3, {s2 & MASK32:#x}", - "v_sad_u32 v0, v1, v2, v3", - "exp mrt0 v0, v0, v0, v0 done vm", - "s_endpgm", - ] - words, _ = run_synthetic_shader(asm) - return words[0] - - -class TestSadU32ReferenceSemantics(unittest.TestCase): - """Unit tests verifying mathematical properties of 32-bit unsigned SAD.""" - - def test_identity_zero_difference(self) -> None: - """When s0 == s1, the absolute difference is 0 and result is exactly s2.""" - for val in (0, 1, 42, 0x7FFFFFFF, 0x80000000, 0xFFFFFFFF): - with self.subTest(val=hex(val)): - self.assertEqual(ref_abs_diff_u32(val, val), 0) - self.assertEqual(ref_sad_u32(val, val, 12345), 12345) - - def test_zero_accumulator(self) -> None: - """When s2 == 0, result equals |s0 - s1|.""" - self.assertEqual(ref_sad_u32(20, 5, 0), 15) - self.assertEqual(ref_sad_u32(5, 20, 0), 15) - self.assertEqual(ref_sad_u32(0xFFFFFFFF, 0, 0), 0xFFFFFFFF) - - def test_operand_commutativity(self) -> None: - """The absolute difference is commutative: |s0 - s1| == |s1 - s0|.""" - values = (0, 1, 2, 0x7FFFFFFF, 0x80000000, 0x80000001, 0xFFFFFFFF, 0xFFFFFFFE, 0x12345678) - for s0 in values: - for s1 in values: - with self.subTest(s0=hex(s0), s1=hex(s1)): - diff_a = ref_abs_diff_u32(s0, s1) - diff_b = ref_abs_diff_u32(s1, s0) - self.assertEqual(diff_a, diff_b) - self.assertEqual(ref_sad_u32(s0, s1, 99), ref_sad_u32(s1, s0, 99)) - - def test_strictly_unsigned_distance(self) -> None: - """Confirms that distances operate on unsigned values. - - |0 - 0xFFFFFFFF| must equal 0xFFFFFFFF (unsigned magnitude), NOT 1. - Signed interpretation would treat 0xFFFFFFFF as -1, giving |0 - (-1)| = 1, - which is an architectural deviation from AMD GPU ISA. - """ - self.assertEqual(ref_abs_diff_u32(0, 0xFFFFFFFF), 0xFFFFFFFF) - self.assertEqual(ref_abs_diff_u32(0xFFFFFFFF, 0), 0xFFFFFFFF) - self.assertEqual(ref_sad_u32(0, 0xFFFFFFFF, 0), 0xFFFFFFFF) - - self.assertEqual(ref_abs_diff_u32(0x7FFFFFFF, 0x80000000), 1) - self.assertEqual(ref_abs_diff_u32(0, 0x80000000), 0x80000000) - - def test_modulo_2_32_wrap_around(self) -> None: - """Addition of the absolute difference and accumulator wraps modulo 2^32.""" - self.assertEqual(ref_sad_u32(0xFFFFFFFF, 0, 1), 0) - self.assertEqual(ref_sad_u32(0xFFFFFFFF, 0, 2), 1) - self.assertEqual(ref_sad_u32(0x80000000, 0, 0x80000000), 0) - self.assertEqual(ref_sad_u32(0xFFFFFFFF, 0, 0xFFFFFFFF), 0xFFFFFFFE) - - def test_triplet_combinations(self) -> None: - """Known vectors representing common shader ALU sequences.""" - triplets = [ - (10, 25, 100, 115), - (25, 10, 100, 115), - (0, 0, 0, 0), - (0x1000, 0x2000, 0x3000, 0x4000), - (0x80000000, 0x7FFFFFFE, 10, 12), - (0xFFFFFFFE, 0xFFFFFFFF, 0xFFFFFFFF, 0), - ] - for s0, s1, s2, expected in triplets: - with self.subTest(s0=hex(s0), s1=hex(s1), s2=hex(s2)): - self.assertEqual(ref_sad_u32(s0, s1, s2), expected) - - -class TestSadHiU32AndMultiPrecision(unittest.TestCase): - """Unit tests for high 32-bit carry / accumulation (v_sad_hi_u32) and multi-precision SAD.""" - - def test_carry_generation_exact_threshold(self) -> None: - """Carry is 0 when sum < 2^32, and 1 when sum >= 2^32.""" - self.assertEqual(ref_sad_hi_u32(0xFFFFFFFF, 0, 0), 0) - self.assertEqual(ref_sad_hi_u32(0xFFFFFFFE, 0, 1), 0) - - self.assertEqual(ref_sad_hi_u32(0xFFFFFFFF, 0, 1), 1) - self.assertEqual(ref_sad_hi_u32(0x80000000, 0, 0x80000000), 1) - - self.assertEqual(ref_sad_hi_u32(0xFFFFFFFF, 0, 0xFFFFFFFF), 1) - self.assertEqual(ref_sad_hi_u32(0x80000000, 0, 0x80000001), 1) - - def test_carry_out_maximum_bound(self) -> None: - """Since diff <= 2^32 - 1 and s2 <= 2^32 - 1, full_sum <= 2^33 - 2, so carry is always in {0, 1}.""" - max_sum = ref_abs_diff_u32(0xFFFFFFFF, 0) + 0xFFFFFFFF - self.assertEqual(max_sum, 0x1FFFFFFFE) - self.assertEqual(max_sum >> 32, 1) - self.assertIn(ref_sad_hi_u32(0xFFFFFFFF, 0, 0xFFFFFFFF), (0, 1)) - - def test_64bit_synthesis(self) -> None: - """The (v_sad_u32, v_sad_hi_u32) pair synthesizes full 64-bit precision sum of absolute differences.""" - vectors = [ - (0, 0, 0), - (100, 50, 25), - (0xFFFFFFFF, 0, 0), - (0xFFFFFFFF, 0, 1), - (0xFFFFFFFF, 0, 0xFFFFFFFF), - (0x80000000, 0, 0x80000000), - (0x12345678, 0x87654321, 0xCAFEBABE), - ] - for s0, s1, s2 in vectors: - with self.subTest(s0=hex(s0), s1=hex(s1), s2=hex(s2)): - lo, hi = ref_sad_64(s0, s1, s2) - reconstructed_64 = ((hi & MASK32) << 32) | (lo & MASK32) - expected_64 = ref_abs_diff_u32(s0, s1) + (s2 & MASK32) - self.assertEqual(reconstructed_64, expected_64) - - def test_shift16_media_variant(self) -> None: - """Shift-16 media extension variant: (|s0 - s1| << 16) + s2.""" - self.assertEqual(ref_sad_hi_u32_shift16(10, 5, 0), 5 << 16) - self.assertEqual(ref_sad_hi_u32_shift16(5, 10, 100), (5 << 16) + 100) - self.assertEqual(ref_sad_hi_u32_shift16(0x0010, 0x0000, 0x0005), 0x00100005) - - def test_upper_halfwords_variant(self) -> None: - """High halfword SAD variant: |s0[31:16] - s1[31:16]| + s2.""" - s0 = (0x0010 << 16) | 0xFFFF - s1 = (0x0005 << 16) | 0x0000 - self.assertEqual(ref_sad_hi_u32_upper_halfwords(s0, s1, 100), 111) - - -class TestClampModifier(unittest.TestCase): - """Unit tests for the clamp modifier saturation behavior.""" - - def test_clamp_saturation_on_overflow(self) -> None: - """When full_sum >= 2^32, the result is clamped to 0xFFFFFFFF.""" - self.assertEqual(ref_sad_u32_clamp(0xFFFFFFFF, 0, 1), 0xFFFFFFFF) - self.assertEqual(ref_sad_u32_clamp(0xFFFFFFFF, 0, 10), 0xFFFFFFFF) - self.assertEqual(ref_sad_u32_clamp(0x80000000, 0, 0x80000000), 0xFFFFFFFF) - - def test_clamp_preserves_in_range_values(self) -> None: - """When full_sum < 2^32, clamp does not modify the output.""" - self.assertEqual(ref_sad_u32_clamp(100, 20, 5), 85) - self.assertEqual(ref_sad_u32_clamp(0xFFFFFFFE, 0, 1), 0xFFFFFFFF) - self.assertEqual(ref_sad_u32_clamp(0, 0, 0), 0) - - -class TestSpirvMiniInterpEquivalence(unittest.TestCase): - """Executes canonical SPIR-V lowerings under spirv_mini_interp and checks against reference oracle.""" - - def test_spirv_sad_u32_basic_cases(self) -> None: - test_cases = [ - (10, 25, 100), - (25, 10, 100), - (0, 0, 0), - (1000, 500, 250), - (0x1234, 0x5678, 0x9ABC), - ] - for s0, s1, s2 in test_cases: - with self.subTest(s0=s0, s1=s1, s2=s2): - expected = ref_sad_u32(s0, s1, s2) - got = run_spirv_sad_u32(s0, s1, s2) - self.assertEqual(got, expected) - - def test_spirv_sad_u32_unsigned_boundary(self) -> None: - """Confirms that SPIR-V lowering computes unsigned distance correctly.""" - got = run_spirv_sad_u32(0, 0xFFFFFFFF, 0) - self.assertEqual(got, 0xFFFFFFFF) - - got = run_spirv_sad_u32(0xFFFFFFFF, 0, 0) - self.assertEqual(got, 0xFFFFFFFF) - - got = run_spirv_sad_u32(0x7FFFFFFF, 0x80000000, 0) - self.assertEqual(got, 1) - - def test_spirv_sad_u32_overflow_wrapping(self) -> None: - """Confirms that SPIR-V OpIAdd correctly models modulo 2^32 wrap-around.""" - self.assertEqual(run_spirv_sad_u32(0xFFFFFFFF, 0, 1), 0) - self.assertEqual(run_spirv_sad_u32(0xFFFFFFFF, 0, 2), 1) - - def test_spirv_sad_hi_u32_and_carry(self) -> None: - """Confirms that SPIR-V OpIAddCarry produces exact 64-bit SAD output.""" - vectors = [ - (0xFFFFFFFF, 0, 0), - (0xFFFFFFFF, 0, 1), - (0xFFFFFFFF, 0, 0xFFFFFFFF), - (0x80000000, 0, 0x80000000), - (20, 5, 100), - ] - for s0, s1, s2 in vectors: - with self.subTest(s0=hex(s0), s1=hex(s1), s2=hex(s2)): - expected_lo, expected_hi = ref_sad_64(s0, s1, s2) - got_lo, got_hi = run_spirv_sad_hi_u32(s0, s1, s2) - self.assertEqual(got_lo, expected_lo) - self.assertEqual(got_hi, expected_hi) - - def test_spirv_clamp_execution(self) -> None: - """Confirms that SPIR-V clamp lowering saturates upon overflow.""" - self.assertEqual(run_spirv_sad_u32_clamp(100, 20, 5), 85) - self.assertEqual(run_spirv_sad_u32_clamp(0xFFFFFFFF, 0, 1), 0xFFFFFFFF) - self.assertEqual(run_spirv_sad_u32_clamp(0xFFFFFFFF, 0, 10), 0xFFFFFFFF) - - def test_spirv_shift16_execution(self) -> None: - """Confirms that SPIR-V shift-16 media lowering evaluates correctly.""" - self.assertEqual(run_spirv_sad_hi_shift16(20, 5, 3), (15 << 16) + 3) - self.assertEqual(run_spirv_sad_hi_shift16(5, 20, 100), (15 << 16) + 100) - - def test_randomized_differential_sweep(self) -> None: - """Deterministic pseudorandom sweep comparing reference oracle with SPIR-V execution.""" - rng = random.Random(0x5AD_032) - for _ in range(50): - s0 = rng.getrandbits(32) - s1 = rng.getrandbits(32) - s2 = rng.getrandbits(32) - - exp_lo, exp_hi = ref_sad_64(s0, s1, s2) - spv_lo = run_spirv_sad_u32(s0, s1, s2) - spv_pair_lo, spv_pair_hi = run_spirv_sad_hi_u32(s0, s1, s2) - - self.assertEqual(spv_lo, exp_lo) - self.assertEqual(spv_pair_lo, exp_lo) - self.assertEqual(spv_pair_hi, exp_hi) - - -class TestTranslatedShaderExecution(unittest.TestCase): - """Executes synthetic RDNA2 disassembly shaders translated via rdna2spirv and run in spirv_mini_interp.""" - - def test_shader_v_sad_u32_basic(self) -> None: - """v_sad_u32 computes unsigned sum of absolute differences in translated shader.""" - self.assertEqual(run_synthetic_sad_u32(10, 25, 100), 115) - self.assertEqual(run_synthetic_sad_u32(25, 10, 100), 115) - self.assertEqual(run_synthetic_sad_u32(0, 0, 0), 0) - self.assertEqual(run_synthetic_sad_u32(1000, 200, 50), 850) - - def test_shader_strictly_unsigned_distance(self) -> None: - """v_sad_u32 treats operands as unsigned: |0 - 0xFFFFFFFF| == 0xFFFFFFFF.""" - self.assertEqual(run_synthetic_sad_u32(0, 0xFFFFFFFF, 0), 0xFFFFFFFF) - self.assertEqual(run_synthetic_sad_u32(0xFFFFFFFF, 0, 0), 0xFFFFFFFF) - self.assertEqual(run_synthetic_sad_u32(0x7FFFFFFF, 0x80000000, 0), 1) - - def test_shader_overflow_wrap(self) -> None: - """v_sad_u32 wraps modulo 2^32 on overflow in translated shader.""" - self.assertEqual(run_synthetic_sad_u32(0xFFFFFFFF, 0, 1), 0) - self.assertEqual(run_synthetic_sad_u32(0xFFFFFFFF, 0, 2), 1) - self.assertEqual(run_synthetic_sad_u32(0x80000000, 0, 0x80000000), 0) - - def test_shader_edge_values_sweep(self) -> None: - """Verifies v_sad_u32 across edge words.""" - edge_words = (0, 1, 0x7FFFFFFF, 0x80000000, 0xFFFFFFFF, 0x12345678) - for s0 in edge_words: - for s1 in (0, 0xFFFFFFFF, 0x80000000): - s2 = 100 - expected = ref_sad_u32(s0, s1, s2) - got = run_synthetic_sad_u32(s0, s1, s2) - self.assertEqual(got, expected) - - def test_shader_mixed_sgpr_and_vgpr(self) -> None: - """v_sad_u32 accepts SGPR source registers alongside VGPRs.""" - asm = [ - "s_mov_b32 s0, 50", - "v_mov_b32 v1, 20", - "v_mov_b32 v2, 5", - "v_sad_u32 v0, s0, v1, v2", - "exp mrt0 v0, v0, v0, v0 done vm", - "s_endpgm", - ] - words, _ = run_synthetic_shader(asm) - self.assertEqual(words, [35, 35, 35, 35]) - - def test_shader_all_sgpr_sources(self) -> None: - """v_sad_u32 with all SGPR sources writing to vector destination.""" - asm = [ - "s_mov_b32 s0, 200", - "s_mov_b32 s1, 50", - "s_mov_b32 s2, 1000", - "v_sad_u32 v0, s0, s1, s2", - "exp mrt0 v0, v0, v0, v0 done vm", - "s_endpgm", - ] - words, _ = run_synthetic_shader(asm) - self.assertEqual(words, [1150, 1150, 1150, 1150]) - - def test_shader_inline_immediate_operands(self) -> None: - """v_sad_u32 accepts integer literal constants in source positions.""" - asm = [ - "v_mov_b32 v1, 100", - "v_sad_u32 v0, v1, 30, 10", - "exp mrt0 v0, v0, v0, v0 done vm", - "s_endpgm", - ] - words, _ = run_synthetic_shader(asm) - self.assertEqual(words, [80, 80, 80, 80]) - - def test_shader_multi_instruction_manhattan_block_matching(self) -> None: - """Simulates 4D vector L1 Manhattan distance block matching in translated shader. - - Vector A = (10, 25, 40, 80) - Vector B = (15, 20, 50, 70) - Accumulator in v0 initialized to 0. - Expected distance: |10-15| + |25-20| + |40-50| + |80-70| = 5 + 5 + 10 + 10 = 30. - """ - asm = [ - "v_mov_b32 v0, 0", - "v_mov_b32 v1, 10", - "v_mov_b32 v2, 15", - "v_sad_u32 v0, v1, v2, v0", - "v_mov_b32 v1, 25", - "v_mov_b32 v2, 20", - "v_sad_u32 v0, v1, v2, v0", - "v_mov_b32 v1, 40", - "v_mov_b32 v2, 50", - "v_sad_u32 v0, v1, v2, v0", - "v_mov_b32 v1, 80", - "v_mov_b32 v2, 70", - "v_sad_u32 v0, v1, v2, v0", - "exp mrt0 v0, v0, v0, v0 done vm", - "s_endpgm", - ] - words, _ = run_synthetic_shader(asm) - self.assertEqual(words, [30, 30, 30, 30]) - - def test_clamp_modifier_rejected(self) -> None: - """v_sad_u32 with clamp modifier raises Unsupported rather than guessing.""" - asm = [ - "v_mov_b32 v1, 1", - "v_sad_u32 v0, v1, v1, v1 clamp", - "exp mrt0 v0, v0, v0, v0 done vm", - "s_endpgm", - ] - with self.assertRaises(rdna2spirv.Unsupported) as cm: - run_synthetic_shader(asm) - self.assertIn("v_sad_u32 clamp", str(cm.exception)) - - def test_v_sad_hi_u32_opcode_unsupported(self) -> None: - """v_sad_hi_u32 is not a valid RDNA2 opcode and must raise Unsupported.""" - asm = [ - "v_mov_b32 v1, 1", - "v_sad_hi_u32 v0, v1, v1, v1", - "exp mrt0 v0, v0, v0, v0 done vm", - "s_endpgm", - ] - with self.assertRaises(rdna2spirv.Unsupported) as cm: - run_synthetic_shader(asm) - self.assertIn("v_sad_hi_u32", str(cm.exception)) - - -class TestMutationSensitivity(unittest.TestCase): - """Ensure that subtle semantic mutations in SAD logic are detected.""" - - def test_detects_signed_distance_mutation(self) -> None: - """A buggy implementation treating operands as signed two's complement fails.""" - def buggy_signed_sad(s0: int, s1: int, s2: int) -> int: - i0 = s0 - (1 << 32) if (s0 >> 31) else s0 - i1 = s1 - (1 << 32) if (s1 >> 31) else s1 - diff = abs(i0 - i1) - return (diff + s2) & MASK32 - - correct = ref_sad_u32(0, 0xFFFFFFFF, 0) - wrong = buggy_signed_sad(0, 0xFFFFFFFF, 0) - self.assertEqual(correct, 0xFFFFFFFF) - self.assertEqual(wrong, 1) - self.assertNotEqual(correct, wrong) - - def test_detects_missing_accumulator_mutation(self) -> None: - """A buggy implementation ignoring src2 fails.""" - def buggy_no_acc(s0: int, s1: int, s2: int) -> int: - return ref_abs_diff_u32(s0, s1) - - self.assertNotEqual(ref_sad_u32(10, 5, 20), buggy_no_acc(10, 5, 20)) - - def test_detects_unwrapped_sum_mutation(self) -> None: - """A buggy implementation without modulo 2^32 fails.""" - def buggy_unwrapped(s0: int, s1: int, s2: int) -> int: - return ref_abs_diff_u32(s0, s1) + s2 - - self.assertNotEqual(ref_sad_u32(0, 0xFFFFFFFF, 1), buggy_unwrapped(0, 0xFFFFFFFF, 1)) - - def test_detects_subtraction_without_abs_mutation(self) -> None: - """A buggy implementation using (s0 - s1 + s2) instead of absolute difference fails.""" - def buggy_no_abs(s0: int, s1: int, s2: int) -> int: - return ((s0 - s1) + s2) & MASK32 - - self.assertNotEqual(ref_sad_u32(5, 10, 0), buggy_no_abs(5, 10, 0)) - - def test_detects_carry_loss_mutation(self) -> None: - """A buggy implementation that drops carry on overflow fails.""" - s0, s1, s2 = 0xFFFFFFFF, 0, 1 - true_hi = ref_sad_hi_u32(s0, s1, s2) - buggy_hi = 0 - self.assertEqual(true_hi, 1) - self.assertNotEqual(true_hi, buggy_hi) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_alu_sdwa_hw.py b/tests/semantic/test_alu_sdwa_hw.py deleted file mode 100644 index 6af20b98f..000000000 --- a/tests/semantic/test_alu_sdwa_hw.py +++ /dev/null @@ -1,712 +0,0 @@ -"""SDWA forms the game's shaders use, against words an RDNA2 GPU returned for the same instructions (no model here). - -Every row was run natively on an AMD Radeon RDNA2 iGPU (gfx1036, Ryzen 9 9950X3D, Windows AMD driver 32.0.21045.16010) -through tools/hw_oracle with AMD clang 23 (rocm-sdk-core 10.0.0), in the MODE inferred for the game (IEEE 0, -DX10_CLAMP 1, f32 denormals flushed, f16 denormals kept). v1..v3 hold the operands, v4 starts as 0xDEADBEEF, and the -word in v4 after the lines is the expected one. An SGPR operand is set with s_mov_b32 first. A VOPC form writes s10 -and v_cndmask_b32 turns it into 0/1. A v_cmpx form saves EXEC in s20, sets v4 = 1 only where the compare held, and -restores EXEC. - -The 172 distinct SDWA forms (opcode, operand kinds, sel/sext/neg/abs/dst_unused/omod) in the 26,503 shader listings -of the 1.0.2.1 package were measured, each with 12 operand words per source. Only the form is taken from the game; -every word here is synthetic. The 624 rows are a sample from 156 of those forms, up to four per form, chosen for -distinct results; the other 16 forms are 16-bit dst_sel:DWORD forms whose every case differs as below. No corpus -form uses dst_unused:UNUSED_SEXT, so this table says nothing about it. Every measured case not listed matches too, except for two kinds of known difference: -- a 16-bit result with dst_sel:DWORD, where the hardware zeroes the high half (#2187); -- a NaN result, where the hardware keeps the input NaN's sign and payload and the translator returns the canonical - quiet NaN (docs/design.md, the f16 transcendentals row). -""" -import os -import struct -import sys -import tempfile -import unittest -import warnings - -HERE = os.path.dirname(os.path.abspath(__file__)) -ROOT = os.path.dirname(os.path.dirname(HERE)) -sys.dont_write_bytecode = True -sys.path.insert(0, os.environ.get("LEONIDA_TOOLS_DIR") or os.path.join(ROOT, "tools")) -sys.path.insert(0, HERE) - -import rdna2spirv # noqa: E402 -import spirv_mini_interp as si # noqa: E402 - -STUB_DXBC = b"DXBC" + bytes(24) + struct.pack("> (S0.u16 & 15)) & 0xFFFF - Logical shift right on 16-bit unsigned operands with zero extension. - - v_ashrrev_i16: D.i16 = (S1.i16 >> (S0.u16 & 15)) & 0xFFFF - Arithmetic shift right on 16-bit signed operands with sign extension. - -Key architectural rules (AMD RDNA2 ISA reference, docs/design.md): - 1. Reversed operand order: S0 holds the shift amount, S1 holds the value to shift. - 2. Shift amount masking: only the low 4 bits of S0 are used (S0 & 15, range 0..15). - Shift amounts >= 16 (e.g. 16, 17, 31, 0x1234) wrap modulo 16. - 3. Logical vs arithmetic right shift: - - v_lshrrev_b16 shifts in zeroes (e.g. 0x8000 >> 1 -> 0x4000; 0x8000 >> 15 -> 0x0001). - - v_ashrrev_i16 sign-extends bit 15 (e.g. 0x8000 >> 1 -> 0xC000; 0x8000 >> 15 -> 0xFFFF; - 0xFFFF >> n -> 0xFFFF). - 4. op_sel (VOP3 / _e64): - - op_sel:[s0, s1, dst] selects either the low half (0) or high half (1) for each source. - - Destination half selection: dst=0 writes to bits [15:0] and preserves old bits [31:16]; - dst=1 writes to bits [31:16] and preserves old bits [15:0]. - 5. VOP2 (_e32) vs VOP3 (_e64): - - VOP2 defines the entire 32-bit register (high 16 bits [31:16] are zeroed). - - VOP3 (or disassembled with 8-byte encoding comment) is a partial write that preserves the untouched half. - -Standard library only: zero game data, no GPU hardware required. -""" -from __future__ import annotations - -import gc -import os -import random -import struct -import sys -import tempfile -import unittest -import warnings - -HERE = os.path.dirname(os.path.abspath(__file__)) -ROOT = os.path.dirname(os.path.dirname(HERE)) -TOOLS_DIR = os.environ.get("LEONIDA_TOOLS_DIR") or os.path.join(ROOT, "tools") - -sys.dont_write_bytecode = True -if TOOLS_DIR not in sys.path: - sys.path.insert(0, TOOLS_DIR) -if HERE not in sys.path: - sys.path.insert(0, HERE) - -import rdna2spirv # noqa: E402 -import spirv_mini_interp as si # noqa: E402 - -MASK16 = 0xFFFF -MASK32 = 0xFFFFFFFF -STUB_DXBC = b"DXBC" + bytes(24) + struct.pack(" int: - return x & MASK16 - - -def s16(x: int) -> int: - v = x & MASK16 - return v - 0x10000 if (v & 0x8000) else v - - -def half16(word: int, hi: int) -> int: - return ((word >> 16) & MASK16) if hi else (word & MASK16) - - -def merge16(old: int, res16: int, dst_hi: int = 0, preserve_high: bool = True) -> int: - res16 &= MASK16 - if dst_hi: - return ((res16 << 16) | (old & MASK16)) & MASK32 - if preserve_high: - return ((old & 0xFFFF0000) | res16) & MASK32 - return res16 - - -def ref_shift16(op: str, shift_amount: int, value: int) -> int: - """ISA reference for RDNA2 16-bit shift operations.""" - sh = shift_amount & 15 - uval = u16(value) - if op == "v_lshlrev_b16": - return (uval << sh) & MASK16 - if op == "v_lshrrev_b16": - return (uval >> sh) & MASK16 - if op == "v_ashrrev_i16": - sval = s16(uval) - return (sval >> sh) & MASK16 - raise ValueError(f"unknown op: {op}") - - -def ref_shift_word(op: str, s0: int, s1: int, old: int = OLD_DEST, - sel=(0, 0, 0), preserve_high: bool = True) -> int: - """Full 32-bit destination word reference accounting for op_sel and half preservation.""" - sh = half16(s0, sel[0]) - val = half16(s1, sel[1]) - res16 = ref_shift16(op, sh, val) - return merge16(old, res16, dst_hi=sel[2], preserve_high=preserve_high) - - -_TMP_DIR = None -_SRC_PATH = None - - -def setUpModule(): - global _TMP_DIR, _SRC_PATH - _TMP_DIR = tempfile.TemporaryDirectory() - disasm_dir = os.path.join(_TMP_DIR.name, "disasm") - os.mkdir(disasm_dir) - _SRC_PATH = os.path.join(disasm_dir, "ps_alu_shift16.s") - with open(os.path.join(_TMP_DIR.name, "ps_alu_shift16.dxbc"), "wb") as f: - f.write(STUB_DXBC) - - -def tearDownModule(): - global _TMP_DIR, _SRC_PATH - if _TMP_DIR is not None: - gc.collect() - _TMP_DIR.cleanup() - _TMP_DIR = None - _SRC_PATH = None - - -def translate_lines(lines) -> str: - if _TMP_DIR is None: - setUpModule() - asm = "; test_alu_shift16\n" + "".join(f"\t{ln}\n" for ln in lines) + "\ts_endpgm\n" - with open(_SRC_PATH, "w", encoding="utf-8") as f: - f.write(asm) - with warnings.catch_warnings(): - warnings.simplefilter("ignore", ResourceWarning) - return rdna2spirv.translate(_SRC_PATH) - - -def run_mrt0(lines, regs=("v0", "v0", "v0", "v0")) -> list[int]: - spv = translate_lines(list(lines) + [f"exp mrt0 {', '.join(regs)} done vm"]) - return list(si.run_fragment(spv)["%out_mrt0"]) - - -def run_one(line: str, v1: int, v2: int, old: int = OLD_DEST) -> int: - return run_mrt0([ - f"v_mov_b32 v1, {v1 & MASK32:#x}", - f"v_mov_b32 v2, {v2 & MASK32:#x}", - f"v_mov_b32 v0, {old & MASK32:#x}", - line, - ])[0] - - -class ReferenceOracleTests(unittest.TestCase): - """Verify the Python reference model against known hand-calculated constants.""" - - def test_hand_calculated_shifts(self): - cases = [ - # v_lshlrev_b16 (S0=shift, S1=value) - ("v_lshlrev_b16", 0, 0x1234, 0x1234), - ("v_lshlrev_b16", 1, 0x1234, 0x2468), - ("v_lshlrev_b16", 4, 0x0005, 0x0050), - ("v_lshlrev_b16", 15, 0x0001, 0x8000), - ("v_lshlrev_b16", 15, 0x0003, 0x8000), # bit 1 drops off - ("v_lshlrev_b16", 16, 0x1234, 0x1234), # 16 & 15 == 0 -> no shift - ("v_lshlrev_b16", 17, 0x1234, 0x2468), # 17 & 15 == 1 -> shift by 1 - ("v_lshlrev_b16", 31, 0x0001, 0x8000), # 31 & 15 == 15 - - # v_lshrrev_b16 (zero extension) - ("v_lshrrev_b16", 0, 0x8000, 0x8000), - ("v_lshrrev_b16", 1, 0x8000, 0x4000), - ("v_lshrrev_b16", 4, 0x0050, 0x0005), - ("v_lshrrev_b16", 15, 0x8000, 0x0001), - ("v_lshrrev_b16", 15, 0xFFFF, 0x0001), - ("v_lshrrev_b16", 16, 0x8000, 0x8000), # 16 & 15 == 0 - - # v_ashrrev_i16 (sign extension) - ("v_ashrrev_i16", 0, 0x8000, 0x8000), - ("v_ashrrev_i16", 1, 0x8000, 0xC000), - ("v_ashrrev_i16", 2, 0x8000, 0xE000), - ("v_ashrrev_i16", 15, 0x8000, 0xFFFF), - ("v_ashrrev_i16", 4, 0x7FFF, 0x07FF), # positive sign preserved - ("v_ashrrev_i16", 1, 0xFFFF, 0xFFFF), # -1 >> 1 == -1 - ("v_ashrrev_i16", 15, 0xFFFF, 0xFFFF), # -1 >> 15 == -1 - ("v_ashrrev_i16", 16, 0x8000, 0x8000), # 16 & 15 == 0 - ("v_ashrrev_i16", 17, 0x8000, 0xC000), # 17 & 15 == 1 - ] - for op, sh, val, expected in cases: - with self.subTest(op=op, sh=sh, val=hex(val)): - self.assertEqual(ref_shift16(op, sh, val), expected) - - -class ShiftBoundaryTests(unittest.TestCase): - """Exhaustive boundary testing across all 16 shift counts and key 16-bit values.""" - - BOUNDARY_VALUES = ( - 0x0000, 0x0001, 0x0002, 0x007F, 0x0080, 0x00FF, - 0x0100, 0x5555, 0x7FFF, 0x8000, 0x8001, 0xAAAA, - 0xFF00, 0xFFFE, 0xFFFF, - ) - - def test_all_shift_counts_e64(self): - """Test shift counts 0..15 on VOP3 form for all three instructions.""" - for op in OPS: - mnemonic = f"{op}_e64" - for sh in range(16): - for val in self.BOUNDARY_VALUES: - # Place non-zero noise in the high halves of inputs - v1 = (0xBEEF << 16) | sh - v2 = (0xDEAD << 16) | val - line = f"{mnemonic} v0, v1, v2" - got = run_one(line, v1, v2, old=OLD_DEST) - want = ref_shift_word(op, v1, v2, old=OLD_DEST, preserve_high=True) - self.assertEqual( - got, want, - f"{op} sh={sh} val={val:#06x}: got {got:#010x}, want {want:#010x}" - ) - - def test_shift_amount_masking(self): - """Test shift counts >= 16 to confirm masking with 15 (bits [3:0]).""" - high_shift_counts = (16, 17, 20, 31, 32, 45, 63, 64, 127, 255, 0x1234) - test_val = 0x8000 - for op in OPS: - mnemonic = f"{op}_e64" - for sh in high_shift_counts: - v1 = (0x1111 << 16) | sh - v2 = (0x2222 << 16) | test_val - line = f"{mnemonic} v0, v1, v2" - got = run_one(line, v1, v2, old=OLD_DEST) - want = ref_shift_word(op, v1, v2, old=OLD_DEST, preserve_high=True) - self.assertEqual( - got, want, - f"{op} large_sh={sh} (sh&15={sh&15}): got {got:#010x}, want {want:#010x}" - ) - - def test_arithmetic_vs_logical_contrast(self): - """Direct contrast: v_lshrrev_b16 vs v_ashrrev_i16 on negative 16-bit values.""" - negative_val = 0x8000 - for sh in (1, 2, 4, 8, 14, 15): - v1 = sh - v2 = negative_val - got_lshr = run_one(f"v_lshrrev_b16_e64 v0, v1, v2", v1, v2, old=OLD_DEST) - got_ashr = run_one(f"v_ashrrev_i16_e64 v0, v1, v2", v1, v2, old=OLD_DEST) - - want_lshr = ref_shift_word("v_lshrrev_b16", v1, v2, old=OLD_DEST) - want_ashr = ref_shift_word("v_ashrrev_i16", v1, v2, old=OLD_DEST) - - self.assertEqual(got_lshr, want_lshr) - self.assertEqual(got_ashr, want_ashr) - # Arithmetic right shift must have sign bit replicated, logical right shift must not - self.assertNotEqual(got_lshr & MASK16, got_ashr & MASK16) - self.assertEqual(got_ashr & 0x8000, 0x8000, "ashr must maintain sign bit 15") - self.assertEqual(got_lshr & 0x8000, 0x0000, "lshr must clear bit 15 on sh >= 1") - - -class OpSelAndPreservationTests(unittest.TestCase): - """Test all op_sel combinations and high/low half destination preservation.""" - - # Distinct words: low half and high half differ distinctly - WORD_A = 0x12348001 # hi: 0x1234, lo: 0x8001 - WORD_B = 0xABCD0004 # hi: 0xABCD, lo: 0x0004 - - def test_all_op_sel_combinations(self): - """Exhaustively verify all 8 combinations of op_sel:[s0, s1, dst].""" - for op in OPS: - for s0_hi in (0, 1): - for s1_hi in (0, 1): - for dst_hi in (0, 1): - sel = (s0_hi, s1_hi, dst_hi) - line = f"{op}_e64 v0, v1, v2 op_sel:[{s0_hi},{s1_hi},{dst_hi}]" - got = run_one(line, self.WORD_A, self.WORD_B, old=OLD_DEST) - want = ref_shift_word(op, self.WORD_A, self.WORD_B, old=OLD_DEST, - sel=sel, preserve_high=True) - self.assertEqual( - got, want, - f"{op} op_sel:{list(sel)} got {got:#010x}, want {want:#010x}" - ) - - def test_destination_high_half_written(self): - """Verify op_sel:[0,0,1] writes to destination bits [31:16] and preserves [15:0].""" - old = 0xCAFE1234 - for op in OPS: - line = f"{op}_e64 v0, v1, v2 op_sel:[0,0,1]" - got = run_one(line, 4, 0x0005, old=old) - # 5 << 4 = 0x50 in high half, low half 0x1234 preserved - expected_res16 = ref_shift16(op, 4, 5) - want = (expected_res16 << 16) | 0x1234 - self.assertEqual(got, want) - self.assertEqual(got & 0xFFFF, 0x1234, "low half must be preserved") - - def test_vop3_encoding_comment_preservation(self): - """Verify LLVM disassembly format (bare mnemonic with 8-byte encoding comment).""" - for op in OPS: - # LLVM disassembles VOP3 16-bit integer ops as bare mnemonic + encoding comment - line = f"{op} v0, v1, v2 {VOP3_ENC8}" - got = run_one(line, 3, 0x0008, old=OLD_DEST) - want = ref_shift_word(op, 3, 0x0008, old=OLD_DEST, preserve_high=True) - self.assertEqual(got, want) - self.assertEqual(got & 0xFFFF0000, OLD_DEST & 0xFFFF0000, "high half must be preserved") - - -class Vop2ZeroHighTests(unittest.TestCase): - """Verify VOP2 (_e32) forms zero out destination bits [31:16].""" - - def test_vop2_zeroes_high_half(self): - for op in OPS: - # Bare mnemonic without encoding comment models VOP2 - line = f"{op} v0, v1, v2" - got = run_one(line, 2, 0x0007, old=OLD_DEST) - want = ref_shift_word(op, 2, 0x0007, old=OLD_DEST, preserve_high=False) - self.assertEqual( - got, want, - f"VOP2 {op} failed: got {got:#010x}, want {want:#010x}" - ) - self.assertEqual(got >> 16, 0, f"VOP2 {op} must zero destination high half") - - -class OperandFormsTests(unittest.TestCase): - """Test scalar SGPRs, inline integer constants, and literal operands.""" - - def test_sgpr_shift_amount(self): - """Scalar SGPR s0 as the shift amount operand.""" - for op in OPS: - spv = translate_lines([ - "s_mov_b32 s0, 3", - "v_mov_b32 v1, 0x0004", - "v_mov_b32 v0, 0x12345678", - f"{op}_e64 v0, s0, v1", - "exp mrt0 v0, v0, v0, v0 done vm", - ]) - got = list(si.run_fragment(spv)["%out_mrt0"])[0] - want = ref_shift_word(op, 3, 4, old=0x12345678, preserve_high=True) - self.assertEqual(got, want, f"SGPR shift failed for {op}") - - def test_inline_constants(self): - """Inline constants: 0, 1, 4, 15, 16.""" - for op in OPS: - for c in (0, 1, 4, 15, 16): - spv = translate_lines([ - "v_mov_b32 v1, 0x0080", - "v_mov_b32 v0, 0xCAFE0000", - f"{op}_e64 v0, {c}, v1", - "exp mrt0 v0, v0, v0, v0 done vm", - ]) - got = list(si.run_fragment(spv)["%out_mrt0"])[0] - want = ref_shift_word(op, c, 0x0080, old=0xCAFE0000, preserve_high=True) - self.assertEqual(got, want, f"constant {c} failed for {op}") - - -class RandomizedFuzzSweepTests(unittest.TestCase): - """Deterministic pseudo-random sweep verifying consistency against reference.""" - - def test_randomized_sweep_50_iterations(self): - rng = random.Random(0x16541F7) # deterministic seed - for _ in range(50): - op = rng.choice(OPS) - s0 = rng.randint(0, 0xFFFFFFFF) - s1 = rng.randint(0, 0xFFFFFFFF) - old = rng.randint(0, 0xFFFFFFFF) - sel = (rng.randint(0, 1), rng.randint(0, 1), rng.randint(0, 1)) - - line = f"{op}_e64 v0, v1, v2 op_sel:[{sel[0]},{sel[1]},{sel[2]}]" - got = run_one(line, s0, s1, old=old) - want = ref_shift_word(op, s0, s1, old=old, sel=sel, preserve_high=True) - self.assertEqual( - got, want, - f"Random sweep failed for {op} with s0={s0:#x}, s1={s1:#x}, sel={sel}" - ) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_alu_shift_b64.py b/tests/semantic/test_alu_shift_b64.py deleted file mode 100644 index 30f8d604d..000000000 --- a/tests/semantic/test_alu_shift_b64.py +++ /dev/null @@ -1,132 +0,0 @@ -"""Semantic interpreter tests for RDNA2 v_lshlrev_b64, v_lshrrev_b64 and v_ashrrev_i64. - -All three shift the 64-bit register pair S1 by S0 & 63 ("rev": the shift amount is the first source): - v_lshlrev_b64: D = S1 << (S0 & 63) - v_lshrrev_b64: D = S1 >> (S0 & 63), zeros shifted in - v_ashrrev_i64: D = S1 >> (S0 & 63), copies of bit 63 shifted in -Each case translates a synthetic pixel shader with tools/rdna2spirv.py, runs it in tests/semantic/spirv_mini_interp.py -and compares the exported pair with a plain-Python reference. -""" -import os -import random -import struct -import sys -import tempfile -import unittest -import warnings - -HERE = os.path.dirname(os.path.abspath(__file__)) -ROOT = os.path.dirname(os.path.dirname(HERE)) -TOOLS_DIR = os.environ.get("LEONIDA_TOOLS_DIR") or os.path.join(ROOT, "tools") - -sys.dont_write_bytecode = True -sys.path.insert(0, TOOLS_DIR) -sys.path.insert(0, HERE) - -import rdna2spirv # noqa: E402 -import spirv_mini_interp as si # noqa: E402 - -M64 = (1 << 64) - 1 -STUB_DXBC = b"DXBC" + bytes(24) + struct.pack(" int: - x &= M64 - return x - (1 << 64) if x >> 63 else x - - -OPS = { - "v_lshlrev_b64": lambda n, x: (x << (n & 63)) & M64, - "v_lshrrev_b64": lambda n, x: (x & M64) >> (n & 63), - "v_ashrrev_i64": lambda n, x: (s64(x) >> (n & 63)) & M64, -} -SHIFTS = [0, 1, 31, 32, 33, 63, 64, 65, 0xFFFFFFFF, 0x80000020] -VALUES = [0, 1, M64, 1 << 63, (1 << 63) - 1, 0xFFFFFFFF, 1 << 32, 0x8000000000000001, 0x0123456789ABCDEF, - 0xFEDCBA9876543210] - -_TMP_DIR = None -_SRC_PATH = None - - -def setUpModule(): - global _TMP_DIR, _SRC_PATH - _TMP_DIR = tempfile.TemporaryDirectory() - disasm_dir = os.path.join(_TMP_DIR.name, "disasm") - os.mkdir(disasm_dir) - _SRC_PATH = os.path.join(disasm_dir, "ps_shift_b64.s") - with open(os.path.join(_TMP_DIR.name, "ps_shift_b64.dxbc"), "wb") as f: - f.write(STUB_DXBC) - - -def tearDownModule(): - global _TMP_DIR - if _TMP_DIR is not None: - _TMP_DIR.cleanup() - _TMP_DIR = None - - -# exp writes float channels, and a word that is a signalling-NaN pattern can come back quieted (bit 22 set): some -# platforms do that in the float round trip, and GPUs may too. So v[0:1] leaves as four 16-bit halves, each ORed -# into 0x40000000 (a normal float, never a NaN or a denormal), and is put back together here. -EXPORT_HALVES = ["v_and_b32 v5, 0xffff, v0", "v_lshrrev_b32 v6, 16, v0", "v_and_b32 v7, 0xffff, v1", - "v_lshrrev_b32 v8, 16, v1", "v_or_b32 v5, 0x40000000, v5", "v_or_b32 v6, 0x40000000, v6", - "v_or_b32 v7, 0x40000000, v7", "v_or_b32 v8, 0x40000000, v8"] - - -def run_lines(lines) -> int: - """Run the lines, export v[0:1] in 16-bit halves, return the pair as one 64-bit value.""" - if _TMP_DIR is None: - setUpModule() - body = list(lines) + EXPORT_HALVES - asm = "; test_shift_b64\n" + "".join(f"\t{ln}\n" for ln in body) + "\texp mrt0 v5, v6, v7, v8 done vm\n\ts_endpgm\n" - with open(_SRC_PATH, "w", encoding="utf-8") as f: - f.write(asm) - with warnings.catch_warnings(): - warnings.simplefilter("ignore", ResourceWarning) - spv = rdna2spirv.translate(_SRC_PATH) - w = si.run_fragment(spv)["%out_mrt0"] - assert all(x >> 16 == 0x4000 for x in w), [hex(x) for x in w] - return sum((x & 0xFFFF) << (16 * i) for i, x in enumerate(w)) - - -def run_op(op: str, n: int, x: int) -> int: - return run_lines([f"v_mov_b32 v4, {n:#x}", f"v_mov_b32 v2, {x & 0xFFFFFFFF:#x}", f"v_mov_b32 v3, {x >> 32:#x}", - f"{op} v[0:1], v4, v[2:3]"]) - - -class ShiftB64Tests(unittest.TestCase): - def test_signalling_nan_word_survives_the_export(self): - # 0xffffffffffa3a095: the low word is a signalling-NaN pattern (review on #454). - x = 0xFFFFFFFFFFA3A095 - self.assertEqual(run_lines([f"v_mov_b32 v0, {x & 0xFFFFFFFF:#x}", f"v_mov_b32 v1, {x >> 32:#x}"]), x) - - def test_reference(self): - self.assertEqual(OPS["v_lshrrev_b64"](32, 1 << 63), 0x80000000) - self.assertEqual(OPS["v_ashrrev_i64"](32, 1 << 63), 0xFFFFFFFF80000000) - self.assertEqual(OPS["v_ashrrev_i64"](63, 1 << 63), M64) - self.assertEqual(OPS["v_lshrrev_b64"](64, M64), M64) # amount 64 & 63 = 0 - - def test_values(self): - for op, fn in OPS.items(): - for n in SHIFTS: - for x in VALUES: - with self.subTest(op=op, n=hex(n), x=hex(x)): - self.assertEqual(run_op(op, n, x), fn(n, x)) - - def test_seeded(self): - rng = random.Random(64) - for _ in range(30): - op, n, x = rng.choice(list(OPS)), rng.getrandbits(32), rng.getrandbits(64) - with self.subTest(op=op, n=hex(n), x=hex(x)): - self.assertEqual(run_op(op, n, x), OPS[op](n, x)) - - def test_scalar_pair_and_inline_operands(self): - # Source pair from SGPRs, amount from an inline constant. - got = run_lines(["s_mov_b32 s2, 0", "s_mov_b32 s3, 0x80000000", "v_ashrrev_i64 v[0:1], 4, s[2:3]"]) - self.assertEqual(got, 0xF800000000000000) - got = run_lines(["s_mov_b32 s2, 0", "s_mov_b32 s3, 0x80000000", "v_lshrrev_b64 v[0:1], 4, s[2:3]"]) - self.assertEqual(got, 0x0800000000000000) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_alu_sincos.py b/tests/semantic/test_alu_sincos.py deleted file mode 100644 index 4e2132787..000000000 --- a/tests/semantic/test_alu_sincos.py +++ /dev/null @@ -1,767 +0,0 @@ -"""Semantic interpreter tests for RDNA2 v_sin_f32 / v_cos_f32 / v_sin_f16 / v_cos_f16 (SHADER-88). - -The operand is an angle in TURNS (normalized revolution where 1.0 turn = 2*pi radians). -RDNA2 hardware range-reduces in turns to [-0.5, 0.5] before scaling by 2*pi. Multiplying -by 2*pi before reducing rounds the fractional turn away in binary32 (up to ~1e-4 rad near -+-255 turns), so the translator reduces in turns first. - -Each case translates a synthetic shader with tools/rdna2spirv.py, runs it in -tests/semantic/spirv_mini_interp.py, and validates the result against an independent -reference oracle and analytical mathematical identities (including IEEE 754 half-precision -precision bounds and the Pythagorean identity sin^2(x) + cos^2(x) ~= 1.0). - -Standard library only: zero game data, no GPU hardware required. -""" -from __future__ import annotations - -import gc -import math -import os -import re -import struct -import sys -import tempfile -import unittest -import warnings - -HERE = os.path.dirname(os.path.abspath(__file__)) -ROOT = os.path.dirname(os.path.dirname(HERE)) -TOOLS_DIR = os.environ.get("LEONIDA_TOOLS_DIR") or os.path.join(ROOT, "tools") - -sys.dont_write_bytecode = True -if TOOLS_DIR not in sys.path: - sys.path.insert(0, TOOLS_DIR) -if HERE not in sys.path: - sys.path.insert(0, HERE) - -import rdna2spirv # noqa: E402 -import spirv_mini_interp as si # noqa: E402 - -STUB_DXBC = b"DXBC" + bytes(24) + struct.pack(" int: - return struct.unpack(" float: - return struct.unpack(" float: - return struct.unpack(" int: - return struct.unpack(" float: - return struct.unpack(" bool: - return (h & 0x7FFF) > 0x7C00 - - -def f16_is_inf(h: int) -> bool: - return (h & 0x7FFF) == 0x7C00 - - -def f16_is_finite(h: int) -> bool: - return ((h >> 10) & 0x1F) != 0x1F - - -def ref_f32(op: str, x: float) -> float: - return math.sin(2 * math.pi * x) if "sin" in op else math.cos(2 * math.pi * x) - - -def reduce_turn_angle(x: float) -> float: - """Range-reduce turn angle to [-0.5, 0.5] turns and scale by 2*pi in float32. - - Matches RDNA2 hardware semantics and rdna2spirv.turn_angle lowering: - preserves signed zero when x == 0.0, uses RoundEven for symmetric tie-breaking, - and multiplies by 2*pi in IEEE 754 binary32. - """ - xf = f32(x) - if xf == 0.0: - t = xf - else: - rnd = f32(round(xf)) - t = f32(xf - rnd) - return f32(t * TWO_PI) - - -def oracle_sincos_f16( - op: str, - h: int, - *, - abs_: bool = False, - neg_: bool = False, - clamp_: bool = False, -) -> int | None: - """Independent reference oracle for RDNA2 v_sin_f16 and v_cos_f16. - - Takes raw 16-bit integer representation of IEEE 754 half-precision float operand. - Applies VOP3 source modifiers (abs before neg), turn angle reduction, transcendental - evaluation, VOP3 clamp, and IEEE 754 round-to-nearest-even halfword packing. - Returns 16-bit unsigned integer bit pattern or None for non-finite values. - """ - h &= 0xFFFF - if abs_: - h &= 0x7FFF - if neg_: - h ^= 0x8000 - if not f16_is_finite(h): - return None - val_f = h2f(h) - # The hardware gives an exact +0 for sin at an odd half turn and cos at an odd quarter turn, where Sin/Cos of a - # rounded 2*pi give a 1-ulp denormal (SHADER-134, docs/design.md). - if val_f != 0.0 and abs(val_f - round(val_f)) == (0.5 if "sin" in op else 0.25): - return 0 - ang = reduce_turn_angle(val_f) - res_f = f32(math.sin(ang) if "sin" in op else math.cos(ang)) - if clamp_: - res_f = max(0.0, min(1.0, res_f)) - return f2h(res_f) - - -_TMP_DIR: tempfile.TemporaryDirectory | None = None -_SRC_PATH: str | None = None -_CS_PATH: str | None = None -_CS_FSSM: str | None = None -VSHARP_CS = [0, 0, 0xFFFFFFFF, 0x31016FAC] - - -class _Heap(dict): - """Word-addressable byte heap for compute shader buffer load/store emulation.""" - - def read(self, addr: int, size: int) -> bytes: - data = bytearray(size) - for offset in range(0, size, 4): - word = self.get((addr + offset) & 0xFFFFFFFF, 0) - struct.pack_into(" None: - for offset in range(0, len(data), 4): - chunk = data[offset : offset + 4] - if len(chunk) < 4: - chunk = chunk.ljust(4, b"\x00") - word = struct.unpack_into(" bytes: - header = bytearray(0x148) - struct.pack_into("<4I", header, 0x138, rsrc2, *group) - return bytes(header) - - -def setUpModule() -> None: - global _TMP_DIR, _SRC_PATH, _CS_PATH, _CS_FSSM - _TMP_DIR = tempfile.TemporaryDirectory() - disasm_dir = os.path.join(_TMP_DIR.name, "disasm") - fssm_dir = os.path.join(_TMP_DIR.name, "fssm") - os.mkdir(disasm_dir) - os.mkdir(fssm_dir) - _SRC_PATH = os.path.join(disasm_dir, "ps_sincos.s") - _CS_PATH = os.path.join(disasm_dir, "cs_sincos.s") - _CS_FSSM = os.path.join(fssm_dir, "cs_sincos.fssm") - with open(os.path.join(_TMP_DIR.name, "ps_sincos.dxbc"), "wb") as f: - f.write(STUB_DXBC) - - -def tearDownModule() -> None: - global _TMP_DIR, _SRC_PATH, _CS_PATH, _CS_FSSM - if _TMP_DIR is not None: - gc.collect() - _TMP_DIR.cleanup() - _TMP_DIR = None - _SRC_PATH = None - _CS_PATH = None - _CS_FSSM = None - - -def run_cs(lines: list[str], group_size: int, memory: dict[int, int]) -> None: - if _TMP_DIR is None: - setUpModule() - with open(_CS_FSSM, "wb") as f: - f.write(_make_fssm(0x0088, (group_size, 1, 1))) - asm = "; cs_sincos\n" + "".join(f"\t{ln}\n" for ln in lines) + "\ts_endpgm\n" - with open(_CS_PATH, "w", encoding="utf-8") as f: - f.write(asm) - with warnings.catch_warnings(): - warnings.simplefilter("ignore", ResourceWarning) - spv = rdna2spirv.translate(_CS_PATH) - si.run_workgroup( - spv, - group_size, - 32, - inputs_for=lambda i: {"%wg_id": (0, 0, 0), "%local_id": (i, 0, 0)}, - push_constants=VSHARP_CS + [0] * 28, - memory=memory, - ) - - -def translate_ps(lines: list[str]) -> str: - if _TMP_DIR is None: - setUpModule() - asm = "; test_sincos\n" + "".join(f"\t{ln}\n" for ln in lines) + "\texp mrt0 v0, v0, v0, v0 done vm\n\ts_endpgm\n" - with open(_SRC_PATH, "w", encoding="utf-8") as f: - f.write(asm) - with warnings.catch_warnings(): - warnings.simplefilter("ignore", ResourceWarning) - spv = rdna2spirv.translate(_SRC_PATH) - return spv - - -def run_ps(lines: list[str]) -> list[int]: - spv = translate_ps(lines) - return list(si.run_fragment(spv)["%out_mrt0"]) - - -def run(line: str, v1: int, old: int = 0) -> int: - return run_ps([ - f"v_mov_b32 v1, {v1:#x}", - f"v_mov_b32 v0, {old:#x}", - line, - ])[0] - - -class SinCosF32Tests(unittest.TestCase): - """Original single-precision tests preserved for regression defense.""" - - def test_values_against_double_reference(self): - for op in ("v_sin_f32", "v_cos_f32"): - for x in INPUTS_F32: - x32 = u2f(f2u(x)) - with self.subTest(op=op, x=x): - got = u2f(run(f"{op}_e32 v0, v1", f2u(x))) - self.assertLessEqual(abs(got - ref_f32(op, x32)), TOL32) - - def test_exact_quarter_turns(self): - self.assertLessEqual(abs(u2f(run("v_sin_f32_e32 v0, v1", f2u(0.25))) - 1.0), TOL32) - self.assertLessEqual(abs(u2f(run("v_cos_f32_e32 v0, v1", f2u(0.5))) + 1.0), TOL32) - self.assertLessEqual(abs(u2f(run("v_sin_f32_e32 v0, v1", f2u(254.25))) - 1.0), TOL32) - self.assertLessEqual(abs(u2f(run("v_cos_f32_e32 v0, v1", f2u(-254.5))) + 1.0), TOL32) - - def test_worst_case_of_the_issue(self): - x32 = u2f(f2u(254.51)) - got = u2f(run("v_sin_f32_e32 v0, v1", f2u(254.51))) - self.assertLessEqual(abs(got - math.sin(2 * math.pi * x32)), TOL32) - - def test_signed_zero_and_special_values(self): - self.assertEqual(run("v_sin_f32_e32 v0, v1", 0x00000000), 0x00000000) - self.assertEqual(run("v_sin_f32_e32 v0, v1", 0x80000000), 0x80000000) - self.assertEqual(u2f(run("v_cos_f32_e32 v0, v1", 0x80000000)), 1.0) - for bits in (0x7F800000, 0xFF800000, 0x7FC00000): - for op in ("v_sin_f32", "v_cos_f32"): - with self.subTest(op=op, x=hex(bits)): - self.assertTrue(math.isnan(u2f(run(f"{op}_e32 v0, v1", bits)))) - - def test_modifiers(self): - got = u2f(run("v_sin_f32_e64 v0, -v1", f2u(100.3))) - self.assertLessEqual(abs(got - math.sin(-2 * math.pi * u2f(f2u(100.3)))), TOL32) - got = u2f(run("v_cos_f32_e64 v0, |v1|", f2u(-254.51))) - self.assertLessEqual(abs(got - math.cos(2 * math.pi * u2f(f2u(254.51)))), TOL32) - got = u2f(run("v_sin_f32_e64 v0, v1 clamp", f2u(-0.25))) - self.assertEqual(got, 0.0) - got = u2f(run("v_sin_f32_e64 v0, v1 mul:2", f2u(100.3))) - self.assertLessEqual(abs(got - 2 * math.sin(2 * math.pi * u2f(f2u(100.3)))), 2 * TOL32) - - def test_whole_turns_give_plus_zero_for_either_sign(self): - for x in (-1.0, -2.0, -100.0, 1.0, 2.0, 100.0): - with self.subTest(x=x): - self.assertEqual(run("v_sin_f32_e32 v0, v1", f2u(x)), 0x00000000) - self.assertEqual(run("v_cos_f32_e32 v0, v1", f2u(x)), f2u(1.0)) - - def test_tiny_arguments_keep_their_sign_and_size(self): - for x in (-2.0 ** -26, 2.0 ** -26, -2.0 ** -20, 2.0 ** -20): - with self.subTest(x=x): - got = u2f(run("v_sin_f32_e32 v0, v1", f2u(x))) - self.assertEqual(math.copysign(1.0, got), math.copysign(1.0, x)) - self.assertNotEqual(got, 0.0) - self.assertLessEqual(abs(got - math.sin(2 * math.pi * x)), 2e-9) - self.assertLessEqual(abs(u2f(run("v_cos_f32_e32 v0, v1", f2u(x))) - 1.0), 1e-6) - - -class SinCosF16ReferenceOracleTests(unittest.TestCase): - """Tests the reference oracle against mathematical truth and validates the translator against the oracle.""" - - def test_oracle_exact_cardinal_turns(self): - # 0.0 turns (0 rad) -> sin = 0.0, cos = 1.0 - self.assertEqual(oracle_sincos_f16("v_sin_f16", H_POS_ZERO), H_POS_ZERO) - self.assertEqual(oracle_sincos_f16("v_cos_f16", H_POS_ZERO), H_ONE) - - # 0.25 turns (pi/2 rad) -> sin = 1.0, cos ~= 0.0 (subnormal negative due to f32 2*pi approximation) - self.assertEqual(oracle_sincos_f16("v_sin_f16", H_QUARTER), H_ONE) - self.assertLessEqual(abs(h2f(oracle_sincos_f16("v_cos_f16", H_QUARTER))), TOL16) - - # 0.5 turns (pi rad) -> sin ~= 0.0, cos = -1.0 - self.assertLessEqual(abs(h2f(oracle_sincos_f16("v_sin_f16", H_HALF))), TOL16) - self.assertEqual(oracle_sincos_f16("v_cos_f16", H_HALF), H_NEG_ONE) - - # 0.75 turns (3pi/2 rad) -> sin = -1.0, cos ~= 0.0 - self.assertEqual(oracle_sincos_f16("v_sin_f16", H_THREE_QUARTERS), H_NEG_ONE) - self.assertLessEqual(abs(h2f(oracle_sincos_f16("v_cos_f16", H_THREE_QUARTERS))), TOL16) - - # 1.0 turns (2pi rad) -> sin = 0.0, cos = 1.0 - self.assertEqual(oracle_sincos_f16("v_sin_f16", H_ONE), H_POS_ZERO) - self.assertEqual(oracle_sincos_f16("v_cos_f16", H_ONE), H_ONE) - - def test_oracle_symmetry_and_periodicity(self): - # Fractional turns strictly inside (-0.5, 0.5) modulo 1.0 (avoiding round-even tie at +-0.5) - turns = [0.125, 0.25, 0.375, 0.625, 0.75, 0.875] - for t in turns: - h = f2h(t) - h_plus_1 = f2h(t + 1.0) - h_plus_10 = f2h(t + 10.0) - - # Periodicity: f(x + 1 turn) == f(x) - self.assertEqual(oracle_sincos_f16("v_sin_f16", h), oracle_sincos_f16("v_sin_f16", h_plus_1)) - self.assertEqual(oracle_sincos_f16("v_cos_f16", h), oracle_sincos_f16("v_cos_f16", h_plus_1)) - self.assertEqual(oracle_sincos_f16("v_sin_f16", h), oracle_sincos_f16("v_sin_f16", h_plus_10)) - self.assertEqual(oracle_sincos_f16("v_cos_f16", h), oracle_sincos_f16("v_cos_f16", h_plus_10)) - - # Odd / Even symmetries: sin(-x) == -sin(x), cos(-x) == cos(x) - s_pos = h2f(oracle_sincos_f16("v_sin_f16", h)) - s_neg = h2f(oracle_sincos_f16("v_sin_f16", f2h(-t))) - self.assertLessEqual(abs(s_pos + s_neg), TOL16) - - c_pos = h2f(oracle_sincos_f16("v_cos_f16", h)) - c_neg = h2f(oracle_sincos_f16("v_cos_f16", f2h(-t))) - self.assertLessEqual(abs(c_pos - c_neg), TOL16) - - def test_normalized_turns_against_interpreter(self): - # Sweep normalized turns x in [0.0, 1.0) with step 1/32 - steps = 32 - for i in range(steps): - turn = i / steps - h_in = f2h(turn) - for op in ("v_sin_f16", "v_cos_f16"): - want = oracle_sincos_f16(op, h_in) - got_word = run(f"{op} v0, v1", (OLD & 0xFFFF0000) | h_in, old=OLD) - got_h = got_word & 0xFFFF - with self.subTest(op=op, turn=turn, h_in=hex(h_in)): - self.assertEqual(got_h, want) - # Verify high half preservation - self.assertEqual(got_word & 0xFFFF0000, OLD & 0xFFFF0000) - - def test_half_precision_precision_limits_and_ulp(self): - # Verify precision against double-precision math.sin/math.cos within f16 bounds - test_turns = [0.05, 0.15, 0.25, 0.35, 0.45, 0.55, 0.65, 0.75, 0.85, 0.95] - for t in test_turns: - h_in = f2h(t) - actual_t = h2f(h_in) # The shader executes on the binary16 operand - for op in ("v_sin_f16", "v_cos_f16"): - got_val = h2f(run(f"{op} v0, v1", h_in)) - exact_math = math.sin(2 * math.pi * actual_t) if "sin" in op else math.cos(2 * math.pi * actual_t) - with self.subTest(op=op, turn=t): - self.assertLessEqual(abs(got_val - exact_math), TOL16) - - def test_pythagorean_identity_f16(self): - # sin^2(x) + cos^2(x) ~= 1.0 across [0.0, 1.0) - for i in range(33): - turn = i / 32.0 - h_in = f2h(turn) - sin_val = h2f(run("v_sin_f16 v0, v1", h_in)) - cos_val = h2f(run("v_cos_f16 v0, v1", h_in)) - pyth = sin_val * sin_val + cos_val * cos_val - with self.subTest(turn=turn): - self.assertLessEqual(abs(pyth - 1.0), 2e-3) - - def test_vop3_modifiers(self): - x = 0.3 - h_in = f2h(x) - old_val = 0xBEEF1234 - - # Negate source modifier: sin(-x) - got = run("v_sin_f16_e64 v0, -v1", h_in, old=old_val) - want = oracle_sincos_f16("v_sin_f16", h_in, neg_=True) - self.assertEqual(got & 0xFFFF, want) - self.assertEqual(got & 0xFFFF0000, old_val & 0xFFFF0000) - - # Absolute value modifier: cos(|-x|) == cos(x) - got = run("v_cos_f16_e64 v0, |v1|", f2h(-x), old=old_val) - want = oracle_sincos_f16("v_cos_f16", h_in) - self.assertEqual(got & 0xFFFF, want) - self.assertEqual(got & 0xFFFF0000, old_val & 0xFFFF0000) - - # Negated absolute value: sin(-|x|) - got = run("v_sin_f16_e64 v0, -|v1|", h_in, old=old_val) - want = oracle_sincos_f16("v_sin_f16", h_in, abs_=True, neg_=True) - self.assertEqual(got & 0xFFFF, want) - - # Clamp output modifier: sin(0.75 turns) = -1.0 -> clamp to 0.0 - got = run("v_sin_f16_e64 v0, v1 clamp", H_THREE_QUARTERS, old=old_val) - want = oracle_sincos_f16("v_sin_f16", H_THREE_QUARTERS, clamp_=True) - self.assertEqual(got & 0xFFFF, want) - self.assertEqual(h2f(got & 0xFFFF), 0.0) - - def test_instruction_forms(self): - h_in = f2h(0.125) - for form in ("", "_e32", "_e64"): - with self.subTest(op="v_sin_f16", form=form or "bare"): - got = run(f"v_sin_f16{form} v0, v1", h_in, old=OLD) - self.assertEqual(got & 0xFFFF, oracle_sincos_f16("v_sin_f16", h_in)) - self.assertEqual(got & 0xFFFF0000, OLD & 0xFFFF0000) - - with self.subTest(op="v_cos_f16", form=form or "bare"): - got = run(f"v_cos_f16{form} v0, v1", h_in, old=OLD) - self.assertEqual(got & 0xFFFF, oracle_sincos_f16("v_cos_f16", h_in)) - self.assertEqual(got & 0xFFFF0000, OLD & 0xFFFF0000) - - -class SinCosSIMDAndPackedHalfwordTests(unittest.TestCase): - """Semantic tests for packed 16-bit register execution and SIMD multi-lane divergence.""" - - def test_packed_dual_channel_repacking(self): - # Two independent angles packed in v1: hi = 0.25 (pi/2), lo = 0.0 - v1_val = (H_QUARTER << 16) | H_POS_ZERO - lines = [ - f"v_mov_b32 v1, {v1_val:#x}", - "v_sin_f16 v2, v1", # sin(lo=0.0) -> 0.0 in v2.lo - "v_lshrrev_b32 v3, 16, v1", # hi=0.25 in v3.lo - "v_cos_f16 v4, v3", # cos(hi=0.25) -> +0 in v4.lo (SHADER-134) - "v_pack_b32_f16 v0, v2, v4", # packed [cos(hi), sin(lo)] - "exp mrt0 v0, v0, v0, v0 done vm", - "s_endpgm", - ] - spv = translate_ps(lines) - word = si.run_fragment(spv)["%out_mrt0"][0] - lo_got = word & 0xFFFF - hi_got = (word >> 16) & 0xFFFF - self.assertEqual(lo_got, oracle_sincos_f16("v_sin_f16", H_POS_ZERO)) - self.assertEqual(hi_got, oracle_sincos_f16("v_cos_f16", H_QUARTER)) - - # Test pair 2: hi = 1.0 (2pi), lo = 0.5 (pi) -> [cos(1.0)=1.0, sin(0.5)=~0.0] - v1_val2 = (H_ONE << 16) | H_HALF - lines2 = [ - f"v_mov_b32 v1, {v1_val2:#x}", - "v_sin_f16 v2, v1", - "v_lshrrev_b32 v3, 16, v1", - "v_cos_f16 v4, v3", - "v_pack_b32_f16 v0, v2, v4", - "exp mrt0 v0, v0, v0, v0 done vm", - "s_endpgm", - ] - spv2 = translate_ps(lines2) - word2 = si.run_fragment(spv2)["%out_mrt0"][0] - self.assertEqual(word2 & 0xFFFF, oracle_sincos_f16("v_sin_f16", H_HALF)) - self.assertEqual((word2 >> 16) & 0xFFFF, oracle_sincos_f16("v_cos_f16", H_ONE)) - - def test_packed_destination_high_half_preservation(self): - sentinel_high = 0xCAFE0000 - for op in ("v_sin_f16", "v_cos_f16"): - for turn in (0.0, 0.25, 0.5, 0.75): - h_in = f2h(turn) - got = run(f"{op} v0, v1", h_in, old=sentinel_high | 0x1234) - with self.subTest(op=op, turn=turn): - self.assertEqual(got & 0xFFFF0000, sentinel_high) - self.assertEqual(got & 0xFFFF, oracle_sincos_f16(op, h_in)) - - def test_packed_destination_aliasing(self): - # In-place destination aliasing: dst == src (v0, v0) - # v0 holds (0xFEED << 16) | H_QUARTER - v0_init = (0xFEED << 16) | H_QUARTER - lines = [ - f"v_mov_b32 v0, {v0_init:#x}", - "v_sin_f16 v0, v0", - "exp mrt0 v0, v0, v0, v0 done vm", - "s_endpgm", - ] - got = si.run_fragment(translate_ps(lines))["%out_mrt0"][0] - self.assertEqual(got & 0xFFFF0000, 0xFEED0000) - self.assertEqual(got & 0xFFFF, H_ONE) - - # Re-evaluating with cos: cos(1.0 turns) == 1.0 (0x3c00) - lines_cos = [ - f"v_mov_b32 v0, {got:#x}", - "v_cos_f16 v0, v0", - "exp mrt0 v0, v0, v0, v0 done vm", - "s_endpgm", - ] - got_cos = si.run_fragment(translate_ps(lines_cos))["%out_mrt0"][0] - self.assertEqual(got_cos & 0xFFFF0000, 0xFEED0000) - self.assertEqual(got_cos & 0xFFFF, H_ONE) - - def test_packed_quadrature_carrier(self): - # Angle 45 deg (0.125 turns): sin(45) == cos(45) == sqrt(2)/2 ~= 0.7071 - lines = [ - f"v_mov_b32 v1, {H_EIGHTH:#x}", - "v_sin_f16 v2, v1", - "v_cos_f16 v3, v1", - "v_pack_b32_f16 v0, v2, v3", - "exp mrt0 v0, v0, v0, v0 done vm", - "s_endpgm", - ] - word = si.run_fragment(translate_ps(lines))["%out_mrt0"][0] - s_val = h2f(word & 0xFFFF) - c_val = h2f((word >> 16) & 0xFFFF) - self.assertLessEqual(abs(s_val - c_val), TOL16) - self.assertLessEqual(abs(s_val - (math.sqrt(2.0) / 2.0)), TOL16) - - def test_exec_masking_single_lane(self): - # When exec_lo == 0, VALU instruction does not execute and destination register keeps old value - lines_inactive = [ - f"v_mov_b32 v1, {H_QUARTER:#x}", - "v_mov_b32 v0, 0xCAFEBABE", - "s_mov_b32 exec_lo, 0", - "v_sin_f16 v0, v1", - "s_mov_b32 exec_lo, 1", - "exp mrt0 v0, v0, v0, v0 done vm", - "s_endpgm", - ] - got_inactive = si.run_fragment(translate_ps(lines_inactive))["%out_mrt0"][0] - self.assertEqual(got_inactive, 0xCAFEBABE) - - # When exec_lo == 1, instruction executes normally - lines_active = [ - f"v_mov_b32 v1, {H_QUARTER:#x}", - "v_mov_b32 v0, 0xCAFEBABE", - "s_mov_b32 exec_lo, 1", - "v_sin_f16 v0, v1", - "exp mrt0 v0, v0, v0, v0 done vm", - "s_endpgm", - ] - got_active = si.run_fragment(translate_ps(lines_active))["%out_mrt0"][0] - self.assertEqual(got_active & 0xFFFF0000, 0xCAFE0000) - self.assertEqual(got_active & 0xFFFF, H_ONE) - - def test_exec_masking_multi_lane_divergence(self): - # 8-thread workgroup: even lanes active (sin of 0.25 turns -> 1.0), odd lanes masked off - group_size = 8 - lane_inputs = [H_QUARTER] * group_size - lane_olds = [0x55550000 + i for i in range(group_size)] - - mem = _Heap( - {0x100 + 4 * i: inp for i, inp in enumerate(lane_inputs)} - | {0x200 + 4 * i: old for i, old in enumerate(lane_olds)} - ) - - lines = [ - "v_lshlrev_b32_e32 v5, 2, v0", - "v_add_nc_u32_e32 v6, 0x100, v5", - "v_add_nc_u32_e32 v7, 0x200, v5", - "buffer_load_dword v1, v6, s[0:3], 0 offen", - "buffer_load_dword v2, v7, s[0:3], 0 offen", - "v_and_b32_e32 v3, 1, v0", - "v_cmp_eq_u32_e32 vcc_lo, 0, v3", - "s_and_saveexec_b32 s6, vcc_lo", - "v_sin_f16 v2, v1", - "s_mov_b32 exec_lo, s6", - "buffer_store_dword v2, v5, s[0:3], 0 offen", - ] - run_cs(lines, group_size=group_size, memory=mem) - - got = [mem.get(4 * i) for i in range(group_size)] - want = [] - for i in range(group_size): - if i % 2 == 0: - want.append((lane_olds[i] & 0xFFFF0000) | H_ONE) - else: - want.append(lane_olds[i]) - self.assertEqual(got, want) - - def test_exec_masking_multi_lane_partitioning(self): - # 8-thread workgroup: lanes 0..3 compute sin(0.25)=1.0, lanes 4..7 compute cos(0.25)=~0.0 - group_size = 8 - lane_inputs = [H_QUARTER] * group_size - mem = _Heap({0x100 + 4 * i: inp for i, inp in enumerate(lane_inputs)}) - - lines = [ - "v_lshlrev_b32_e32 v5, 2, v0", - "v_add_nc_u32_e32 v6, 0x100, v5", - "buffer_load_dword v1, v6, s[0:3], 0 offen", - "v_mov_b32 v2, 0x33330000", - "v_cmp_lt_u32_e32 vcc_lo, v0, 4", - "s_and_saveexec_b32 s6, vcc_lo", - "v_sin_f16 v2, v1", - "s_not_b32 exec_lo, exec_lo", - "s_and_b32 exec_lo, exec_lo, s6", - "v_cos_f16 v2, v1", - "s_mov_b32 exec_lo, s6", - "buffer_store_dword v2, v5, s[0:3], 0 offen", - ] - run_cs(lines, group_size=group_size, memory=mem) - - got = [mem.get(4 * i) for i in range(group_size)] - want = [] - for i in range(group_size): - if i < 4: - want.append(0x33330000 | H_ONE) - else: - want.append(0x33330000 | oracle_sincos_f16("v_cos_f16", H_QUARTER)) - self.assertEqual(got, want) - - -class SinCosSpecialFloatBoundariesAndNegativeControlsTests(unittest.TestCase): - """Semantic tests for special float boundaries (signed zeros, inf, nan) and negative controls.""" - - def test_signed_zeros(self): - # sin(+0.0) == +0.0 (0x0000), sin(-0.0) == -0.0 (0x8000) - # cos(+0.0) == 1.0 (0x3C00), cos(-0.0) == 1.0 (0x3C00) - # Upper 16 bits of destination register must be preserved. - got_sin_pos = run("v_sin_f16 v0, v1", H_POS_ZERO, old=OLD) - self.assertEqual(got_sin_pos & 0xFFFF, H_POS_ZERO) - self.assertEqual(got_sin_pos & 0xFFFF0000, OLD & 0xFFFF0000) - - got_sin_neg = run("v_sin_f16 v0, v1", H_NEG_ZERO, old=OLD) - self.assertEqual(got_sin_neg & 0xFFFF, H_NEG_ZERO) - self.assertEqual(got_sin_neg & 0xFFFF0000, OLD & 0xFFFF0000) - - got_cos_pos = run("v_cos_f16 v0, v1", H_POS_ZERO, old=OLD) - self.assertEqual(got_cos_pos & 0xFFFF, H_ONE) - self.assertEqual(got_cos_pos & 0xFFFF0000, OLD & 0xFFFF0000) - - got_cos_neg = run("v_cos_f16 v0, v1", H_NEG_ZERO, old=OLD) - self.assertEqual(got_cos_neg & 0xFFFF, H_ONE) - self.assertEqual(got_cos_neg & 0xFFFF0000, OLD & 0xFFFF0000) - - def test_infinities_produce_nan(self): - # cos(+-inf) == NaN, sin(+-inf) == NaN - for op in ("v_sin_f16", "v_cos_f16"): - for inf_val in (H_POS_INF, H_NEG_INF): - with self.subTest(op=op, inf=hex(inf_val)): - got = run(f"{op} v0, v1", inf_val, old=OLD) - self.assertEqual(got & 0xFFFF0000, OLD & 0xFFFF0000) - self.assertTrue(f16_is_nan(got & 0xFFFF)) - self.assertTrue(math.isnan(h2f(got & 0xFFFF))) - - def test_nan_propagation(self): - # Quiet and signaling NaNs propagate as NaN - nan_inputs = [H_QNAN, H_SNAN, H_NEG_QNAN, H_NEG_SNAN, 0x7E55, 0xFEAA] - for op in ("v_sin_f16", "v_cos_f16"): - for nan_val in nan_inputs: - with self.subTest(op=op, nan=hex(nan_val)): - got = run(f"{op} v0, v1", nan_val, old=OLD) - self.assertEqual(got & 0xFFFF0000, OLD & 0xFFFF0000) - self.assertTrue(f16_is_nan(got & 0xFFFF)) - - def test_subnormal_angles_preserve_sign(self): - # Smallest subnormal +2^-24 (0x0001) and -2^-24 (0x8001) - # sin(+2^-24) produces positive subnormal 0x0006, cos(+2^-24) produces 1.0 (0x3C00) - got_sin_sub = run("v_sin_f16 v0, v1", 0x0001, old=OLD) - self.assertEqual(got_sin_sub & 0xFFFF, 0x0006) - self.assertEqual(got_sin_sub & 0xFFFF0000, OLD & 0xFFFF0000) - - got_sin_sub_neg = run("v_sin_f16 v0, v1", 0x8001, old=OLD) - self.assertEqual(got_sin_sub_neg & 0xFFFF, 0x8006) - self.assertEqual(got_sin_sub_neg & 0xFFFF0000, OLD & 0xFFFF0000) - - got_cos_sub = run("v_cos_f16 v0, v1", 0x0001, old=OLD) - self.assertEqual(got_cos_sub & 0xFFFF, H_ONE) - - got_cos_sub_neg = run("v_cos_f16 v0, v1", 0x8001, old=OLD) - self.assertEqual(got_cos_sub_neg & 0xFFFF, H_ONE) - - def test_whole_integer_turns(self): - # Non-zero integer turns N in [-100, 100] produce +0.0 (0x0000) for sin, 1.0 (0x3C00) for cos - whole_turns = [-100.0, -10.0, -2.0, -1.0, 1.0, 2.0, 10.0, 100.0] - for n in whole_turns: - h_in = f2h(n) - with self.subTest(n=n, h_in=hex(h_in)): - got_sin = run("v_sin_f16 v0, v1", h_in, old=OLD) - self.assertEqual(got_sin & 0xFFFF, H_POS_ZERO) - self.assertEqual(got_sin & 0xFFFF0000, OLD & 0xFFFF0000) - - got_cos = run("v_cos_f16 v0, v1", h_in, old=OLD) - self.assertEqual(got_cos & 0xFFFF, H_ONE) - self.assertEqual(got_cos & 0xFFFF0000, OLD & 0xFFFF0000) - - def test_negative_control_spirv_opcode_sabotage(self): - # Sabotaging OpExtInst %glsl Sin with Cos or vice-versa causes detectable divergence - spv_sin = translate_ps([ - f"v_mov_b32 v1, {H_QUARTER:#x}", - "v_sin_f16 v0, v1", - "exp mrt0 v0, v0, v0, v0 done vm", - "s_endpgm", - ]) - expected_sin = H_ONE - self.assertEqual(si.run_fragment(spv_sin)["%out_mrt0"][0] & 0xFFFF, expected_sin) - - sabotaged_sin, n = re.subn(r"\bSin\b", "Cos", spv_sin, count=1) - self.assertEqual(n, 1) - sabotaged_out = si.run_fragment(sabotaged_sin)["%out_mrt0"][0] & 0xFFFF - self.assertNotEqual(sabotaged_out, expected_sin) - - spv_cos = translate_ps([ - f"v_mov_b32 v1, {H_POS_ZERO:#x}", - "v_cos_f16 v0, v1", - "exp mrt0 v0, v0, v0, v0 done vm", - "s_endpgm", - ]) - expected_cos = H_ONE - self.assertEqual(si.run_fragment(spv_cos)["%out_mrt0"][0] & 0xFFFF, expected_cos) - - sabotaged_cos, n = re.subn(r"\bCos\b", "Sin", spv_cos, count=1) - self.assertEqual(n, 1) - sabotaged_cos_out = si.run_fragment(sabotaged_cos)["%out_mrt0"][0] & 0xFFFF - self.assertNotEqual(sabotaged_cos_out, expected_cos) - - def test_negative_control_turn_scaling_sabotage(self): - # Sabotaging the 2*pi scaling factor (1086918619 -> 1.0 = 1065353216) fails the check - spv = translate_ps([ - f"v_mov_b32 v1, {H_QUARTER:#x}", - "v_sin_f16 v0, v1", - "exp mrt0 v0, v0, v0, v0 done vm", - "s_endpgm", - ]) - self.assertIn("1086918619", spv) - expected = H_ONE - self.assertEqual(si.run_fragment(spv)["%out_mrt0"][0] & 0xFFFF, expected) - - sabotaged = spv.replace("1086918619", "1065353216") - sabotaged_out = si.run_fragment(sabotaged)["%out_mrt0"][0] & 0xFFFF - self.assertNotEqual(sabotaged_out, expected) - - def test_negative_control_high_half_preservation_failure(self): - # A hypothetical buggy translator that clobbers the upper half would be detected - spv = translate_ps([ - f"v_mov_b32 v1, {H_QUARTER:#x}", - f"v_mov_b32 v0, {OLD:#x}", - "v_sin_f16 v0, v1", - "exp mrt0 v0, v0, v0, v0 done vm", - "s_endpgm", - ]) - actual_out = si.run_fragment(spv)["%out_mrt0"][0] - self.assertEqual(actual_out & 0xFFFF0000, OLD & 0xFFFF0000) - - corrupted_out = actual_out & 0x0000FFFF - self.assertNotEqual(corrupted_out & 0xFFFF0000, OLD & 0xFFFF0000) - - def test_negative_control_nan_assertion(self): - # Ensure our NaN detection logic correctly distinguishes non-NaN values - self.assertTrue(f16_is_nan(H_QNAN)) - self.assertTrue(f16_is_nan(H_SNAN)) - self.assertFalse(f16_is_nan(H_ONE)) - self.assertFalse(f16_is_nan(H_POS_ZERO)) - self.assertFalse(f16_is_nan(H_POS_INF)) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_alu_sincos_turns_hw.py b/tests/semantic/test_alu_sincos_turns_hw.py deleted file mode 100644 index 2e4a0c4cd..000000000 --- a/tests/semantic/test_alu_sincos_turns_hw.py +++ /dev/null @@ -1,577 +0,0 @@ -"""v_sin/v_cos (f32, f16) at whole, half and quarter turns against words an RDNA2 GPU returned (SHADER-134). - -Every expected word was read back from an AMD Radeon RDNA2 iGPU (gfx1036, Ryzen 9 9950X3D, Windows AMD driver -32.0.21045.16010) through tools/hw_oracle with AMD clang 23 (rocm-sdk-core 10.0.0), one instruction per word, v4 -starting at 0xDEADBEEF, in the MODE inferred for the game (IEEE 0, f32 denormals flushed, f16 denormals kept). The rows -are the inputs that are a multiple of a quarter turn (both signs, from 0.25 to 2^24 turns, around +-256) plus -infinities and NaNs: there the hardware's word is exact (+0 for sin at an odd half turn and cos at an odd quarter -turn, +-1 or +-0 elsewhere), so the translation must give it bit for bit. General angles differ by an ulp or a few -between drivers and the hardware and are not pinned here. -""" -import os -import struct -import sys -import tempfile -import unittest -import warnings - -HERE = os.path.dirname(os.path.abspath(__file__)) -ROOT = os.path.dirname(os.path.dirname(HERE)) -sys.dont_write_bytecode = True -sys.path.insert(0, os.environ.get("LEONIDA_TOOLS_DIR") or os.path.join(ROOT, "tools")) -sys.path.insert(0, HERE) - -import rdna2spirv # noqa: E402 -import spirv_mini_interp as si # noqa: E402 - -STUB_DXBC = b"DXBC" + bytes(24) + struct.pack("> 16 if op.endswith("f16") else 0, want >> 16 if op.endswith("f16") else 0) - else: - self.assertEqual(word, want) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_alu_sqrt_f16.py b/tests/semantic/test_alu_sqrt_f16.py deleted file mode 100644 index 76b5fb3a5..000000000 --- a/tests/semantic/test_alu_sqrt_f16.py +++ /dev/null @@ -1,307 +0,0 @@ -"""End-to-end semantic tests for RDNA2 v_sqrt_f16 (D.f16 = sqrt(S0.f16)). - -Covers v_sqrt_f16 executed end-to-end through tools/rdna2spirv.py (via -support.translate_lines) and tests/semantic/spirv_mini_interp.py: - - Exact binary16 square roots (0.0, -0.0, 0.25, 1.0, 4.0, 9.0, powers of 2, - and exact subnormal squares) plus fractional/non-exact and max finite - values checked against a Python struct(" 0x7C00), NaNs (0x7E00, - 0x7E01, 0x7C01 -> NaN), and negative inputs (-1.0 = 0xBC00, -inf = 0xFC00), - which give 0xFE00 (a negative quiet NaN, the hardware's result; the - translator keeps the undefined GLSL.std.450 Sqrt(x < 0) out of it). - - Preservation of the untouched 16-bit half of the destination VGPR and - independence from the unused 16-bit half of the source VGPR. - - _e32, _e64, and bare mnemonics, op_sel:[src,dst] ([0,0], [1,0], [0,1], - [1,1]), VOP3 source/output modifiers (|v1|, clamp, mul:2, div:2), inline - constants, SGPR sources, destination aliasing (v0, v0), and EXEC masking. - - In-memory SPIR-V negative controls (mutating GLSL.std.450 Sqrt and - altering the f16 half-extraction / destination-masking logic). - -Standard library only; hand-written RDNA2 listings only; zero game data. -""" -from __future__ import annotations - -import itertools -import math -import os -import re -import struct -import sys -import unittest - -HERE = os.path.dirname(os.path.abspath(__file__)) -ROOT = os.path.dirname(os.path.dirname(HERE)) -TOOLS_DIR = os.environ.get("LEONIDA_TOOLS_DIR") or os.path.join(ROOT, "tools") - -sys.dont_write_bytecode = True -if TOOLS_DIR not in sys.path: - sys.path.insert(0, TOOLS_DIR) -if HERE not in sys.path: - sys.path.insert(0, HERE) - -import spirv_mini_interp as si # noqa: E402 -from support import translate_lines # noqa: E402 - -OLD = 0xBEEF1234 -MASK32 = 0xFFFFFFFF - -# Representative binary16 encodings. -H_POS_ZERO = 0x0000 # +0.0 -H_NEG_ZERO = 0x8000 # -0.0 -H_SUB_MIN = 0x0001 # 2^-24 (sqrt = 2^-12 = 0x0C00) -H_SUB_4 = 0x0004 # 4 * 2^-24 = 2^-22 (sqrt = 2^-11 = 0x1000) -H_SUB_2M16 = 0x0100 # 2^-16 (sqrt = 2^-8 = 0x1C00) -H_SUB_MAX = 0x03FF # 1023 * 2^-24 (largest +subnormal) -H_NORM_MIN = 0x0400 # 2^-14 (sqrt = 2^-7 = 0x2000) -H_0P0625 = 0x2C00 # 0.0625 (sqrt = 0.25 = 0x3400) -H_0P25 = 0x3400 # 0.25 (sqrt = 0.5 = 0x3800) -H_0P5 = 0x3800 # 0.5 -H_1P0 = 0x3C00 # 1.0 (sqrt = 1.0) -H_1P5 = 0x3E00 # 1.5 -H_2P0 = 0x4000 # 2.0 -H_3P0 = 0x4200 # 3.0 -H_4P0 = 0x4400 # 4.0 (sqrt = 2.0) -H_9P0 = 0x4880 # 9.0 (sqrt = 3.0) -H_MAX = 0x7BFF # 65504.0 -H_NEG_1P0 = 0xBC00 # -1.0 -H_NEG_4P0 = 0xC400 # -4.0 -H_POS_INF = 0x7C00 # +inf -H_NEG_INF = 0xFC00 # -inf -H_QNAN = 0x7E00 # +qNaN -H_QNAN_PAYLOAD = 0x7E01 # +qNaN with payload -H_SNAN = 0x7C01 # +sNaN - - -def h2f(h: int) -> float: - return struct.unpack(" int: - try: - return struct.unpack(" 0 else H_NEG_INF - - -def is_f16_nan(h: int) -> bool: - h &= 0xFFFF - return (h & 0x7C00) == 0x7C00 and (h & 0x03FF) != 0 - - -def f16_ulp_diff(a: int, b: int) -> int: - """ULP distance between two finite non-NaN binary16 values.""" - def ordered(h: int) -> int: - h &= 0xFFFF - return -((h & 0x7FFF)) if (h & 0x8000) else h - - return abs(ordered(a) - ordered(b)) - - -def merge_half(old_word: int, half: int, hi: int) -> int: - if hi: - return (old_word & 0x0000FFFF) | ((half & 0xFFFF) << 16) - return (old_word & 0xFFFF0000) | (half & 0xFFFF) - - -def ref_sqrt_f16(h: int) -> int: - x = h2f(h) - if math.isnan(x): - return H_QNAN - if math.isinf(x): - return H_POS_INF if x > 0 else H_QNAN - if x == 0.0: - return h & 0x8000 - return f2h(math.sqrt(x)) - - -def run_ps(name: str, body_lines: list[str], **run_options): - lines = list(body_lines) + ["exp mrt0 v0, v0, v0, v0 done vm", "s_endpgm"] - spv = translate_lines(name, lines) - out = si.run_fragment(spv, **run_options) - return out["%out_mrt0"][0], spv - - -def run_op(op_line: str, v1_word: int, v0_init: int = OLD, s4: int | None = None) -> int: - lines = [f"v_mov_b32 v0, {v0_init:#x}", f"v_mov_b32 v1, {v1_word:#x}"] - if s4 is not None: - lines.append(f"s_mov_b32 s4, {s4:#x}") - lines.append(op_line) - word, _ = run_ps("ps_sqrt_f16", lines) - return word - - -class SqrtF16ExactAndFractionalTests(unittest.TestCase): - def test_exact_square_roots_across_mnemonics(self): - cases = ( - ("pos_zero", H_POS_ZERO, H_POS_ZERO), - ("neg_zero", H_NEG_ZERO, H_NEG_ZERO), - ("subnormal_2m24", H_SUB_MIN, 0x0C00), # sqrt(2^-24) = 2^-12 - ("subnormal_2m22", H_SUB_4, 0x1000), # sqrt(2^-22) = 2^-11 - ("subnormal_2m16", H_SUB_2M16, 0x1C00), # sqrt(2^-16) = 2^-8 - ("norm_min_2m14", H_NORM_MIN, 0x2000), # sqrt(2^-14) = 2^-7 - ("0.0625", H_0P0625, H_0P25), - ("0.25", H_0P25, H_0P5), - ("1.0", H_1P0, H_1P0), - ("4.0", H_4P0, H_2P0), - ("9.0", H_9P0, H_3P0), - ) - for suffix in ("_e32", "_e64", ""): - for name, h_in, want_half in cases: - with self.subTest(suffix=suffix, case=name): - # High bits [31:16] of v1 must not affect the low-half result. - got = run_op(f"v_sqrt_f16{suffix} v0, v1", 0xCAFE0000 | h_in) - self.assertEqual(got, merge_half(OLD, want_half, 0)) - - def test_fractional_and_subnormal_values_within_1ulp(self): - cases = ( - H_SUB_MAX, - 0x0200, # 2^-15 (subnormal) - 0x1234, # small normal - H_0P5, - H_1P5, - H_2P0, - H_3P0, - 0x4500, # 5.0 - 0x4900, # 10.0 - 0x5640, # 100.0 - H_MAX, # 65504.0 - ) - for h_in in cases: - want = ref_sqrt_f16(h_in) - with self.subTest(h_in=hex(h_in), want=hex(want)): - got = run_op("v_sqrt_f16_e32 v0, v1", 0xDEAD0000 | h_in) - self.assertEqual(got & 0xFFFF0000, OLD & 0xFFFF0000) - self.assertLessEqual(f16_ulp_diff(got & 0xFFFF, want), 1) - - -class SqrtF16SpecialCasesTests(unittest.TestCase): - def test_pos_inf_and_nans(self): - for suffix in ("_e32", "_e64"): - got_inf = run_op(f"v_sqrt_f16{suffix} v0, v1", 0xCAFE0000 | H_POS_INF) - self.assertEqual(got_inf, merge_half(OLD, H_POS_INF, 0)) - - for h_nan in (H_QNAN, H_QNAN_PAYLOAD, H_SNAN): - with self.subTest(suffix=suffix, h_nan=hex(h_nan)): - got_nan = run_op(f"v_sqrt_f16{suffix} v0, v1", 0xCAFE0000 | h_nan) - self.assertEqual(got_nan & 0xFFFF0000, OLD & 0xFFFF0000) - self.assertTrue(is_f16_nan(got_nan & 0xFFFF), f"expected NaN, got {got_nan:#010x}") - - def test_negative_inputs_give_negative_quiet_nan(self): - # GLSL.std.450 leaves Sqrt(x < 0) undefined, so the translator selects the hardware's 0xFE00 itself. - for line, v1_word, dst_hi in ( - ("v_sqrt_f16_e32 v0, v1", (H_1P0 << 16) | H_NEG_1P0, 0), - ("v_sqrt_f16_e32 v0, v1", (H_1P0 << 16) | H_NEG_INF, 0), - ("v_sqrt_f16_e64 v0, v1 op_sel:[1,0]", (H_NEG_1P0 << 16) | H_1P0, 0), - ("v_sqrt_f16_e64 v0, v1 op_sel:[1,1]", (H_NEG_INF << 16) | H_1P0, 1), - ): - with self.subTest(line=line, v1=hex(v1_word)): - self.assertEqual(run_op(line, v1_word), merge_half(OLD, 0xFE00, dst_hi)) - - -class SqrtF16ModifiersAndOperandsTests(unittest.TestCase): - def test_op_sel_all_combinations(self): - # v1 = (hi: 9.0, lo: 4.0) -> sqrt(hi) = 3.0, sqrt(lo) = 2.0. - v1 = (H_9P0 << 16) | H_4P0 - for src_hi, dst_hi in itertools.product((0, 1), repeat=2): - want_half = H_3P0 if src_hi else H_2P0 - line = f"v_sqrt_f16_e64 v0, v1 op_sel:[{src_hi},{dst_hi}]" - with self.subTest(line=line): - self.assertEqual(run_op(line, v1), merge_half(OLD, want_half, dst_hi)) - - def test_vop3_abs_neg_and_output_modifiers(self): - v1 = (H_NEG_4P0 << 16) | H_NEG_1P0 - self.assertEqual(run_op("v_sqrt_f16_e64 v0, |v1| op_sel:[0,0]", v1), merge_half(OLD, H_1P0, 0)) - self.assertEqual(run_op("v_sqrt_f16_e64 v0, |v1| op_sel:[1,1]", v1), merge_half(OLD, H_2P0, 1)) - # -v1 on a negative value turns it positive before sqrt. - self.assertEqual(run_op("v_sqrt_f16_e64 v0, -v1 op_sel:[1,0]", v1), merge_half(OLD, H_2P0, 0)) - # -|v1| is negative: 0xFE00. - self.assertEqual(run_op("v_sqrt_f16_e64 v0, -|v1| op_sel:[0,0]", v1), merge_half(OLD, 0xFE00, 0)) - - # Output modifiers: mul:2 and div:2 ignored on RDNA2 with denorms kept; clamp applies. - v1_pos = (H_9P0 << 16) | H_4P0 - self.assertEqual(run_op("v_sqrt_f16_e64 v0, v1 mul:2", v1_pos), merge_half(OLD, H_2P0, 0)) - self.assertEqual(run_op("v_sqrt_f16_e64 v0, v1 div:2", v1_pos), merge_half(OLD, H_2P0, 0)) - self.assertEqual(run_op("v_sqrt_f16_e64 v0, v1 clamp", v1_pos), merge_half(OLD, H_1P0, 0)) - self.assertEqual(run_op("v_sqrt_f16_e64 v0, v1 op_sel:[1,1] clamp", v1_pos), merge_half(OLD, H_1P0, 1)) - - def test_inline_constants_sgpr_aliasing_and_exec_mask(self): - self.assertEqual(run_op("v_sqrt_f16_e32 v0, 4.0", 0), merge_half(OLD, H_2P0, 0)) - self.assertEqual(run_op("v_sqrt_f16_e32 v0, 0.25", 0), merge_half(OLD, H_0P5, 0)) - self.assertEqual(run_op("v_sqrt_f16_e64 v0, |0xBC00|", 0), merge_half(OLD, H_1P0, 0)) - - s4 = (H_9P0 << 16) | H_4P0 - self.assertEqual(run_op("v_sqrt_f16_e32 v0, s4", 0, s4=s4), merge_half(OLD, H_2P0, 0)) - self.assertEqual(run_op("v_sqrt_f16_e64 v0, s4 op_sel:[1,1]", 0, s4=s4), merge_half(OLD, H_3P0, 1)) - - # Destination aliasing: v0 as both source and destination. - word_alias, _ = run_ps("ps_sqrt_alias", [ - f"v_mov_b32 v0, {(H_9P0 << 16) | H_4P0:#x}", - "v_sqrt_f16_e64 v0, v0 op_sel:[1,0]", - ]) - self.assertEqual(word_alias, (H_9P0 << 16) | H_3P0) - - # EXEC masking: when lane 0 is masked off (exec = 0x2), v0 keeps OLD. - word_masked, _ = run_ps("ps_sqrt_exec_off", [ - f"v_mov_b32 v0, {OLD:#x}", - f"v_mov_b32 v1, {H_4P0:#x}", - "s_mov_b64 exec, 0x2", - "v_sqrt_f16_e32 v0, v1", - "s_mov_b64 exec, -1", - ]) - self.assertEqual(word_masked, OLD) - - # EXEC masking: when lane 0 is active (exec = 0x1), v0 is updated. - word_active, _ = run_ps("ps_sqrt_exec_on", [ - f"v_mov_b32 v0, {OLD:#x}", - f"v_mov_b32 v1, {H_4P0:#x}", - "s_mov_b64 exec, 0x1", - "v_sqrt_f16_e32 v0, v1", - "s_mov_b64 exec, -1", - ]) - self.assertEqual(word_active, merge_half(OLD, H_2P0, 0)) - - -class SqrtF16NegativeControlsTests(unittest.TestCase): - def test_sabotaged_spirv_changes_output(self): - want = merge_half(OLD, H_2P0, 0) - _, spv = run_ps("ps_sqrt_neg_ctrl", [ - f"v_mov_b32 v0, {OLD:#x}", - f"v_mov_b32 v1, {(H_9P0 << 16) | H_4P0:#x}", - "v_sqrt_f16_e32 v0, v1", - ]) - self.assertEqual(si.run_fragment(spv)["%out_mrt0"][0], want) - - # Negative control 1: replace GLSL.std.450 Sqrt with InverseSqrt (sqrt(4)=2.0 -> 1/sqrt(4)=0.5). - bad_op, n1 = re.subn(r"OpExtInst %float %glsl Sqrt\b", "OpExtInst %float %glsl InverseSqrt", spv, count=1) - self.assertEqual(n1, 1) - got_bad_op = si.run_fragment(bad_op)["%out_mrt0"][0] - self.assertNotEqual(got_bad_op, want) - self.assertEqual(got_bad_op, merge_half(OLD, H_0P5, 0)) - - # Negative control 2: alter UnpackHalf2x16 lane extraction (index 0 -> 1) so hi half 9.0 is read instead of 4.0. - bad_extract, n2 = re.subn( - r"(OpExtInst %v2float %glsl UnpackHalf2x16 %\w+\n\s*%\w+ = OpCompositeExtract %float %\w+ )0\b", - r"\g<1>1", - spv, - count=1, - ) - self.assertEqual(n2, 1) - got_bad_extract = si.run_fragment(bad_extract)["%out_mrt0"][0] - self.assertNotEqual(got_bad_extract, want) - self.assertEqual(got_bad_extract, merge_half(OLD, H_3P0, 0)) - - # Negative control 3: corrupt destination high-half preservation mask (0xffff0000 -> 0x00000000). - bad_mask, n3 = re.subn( - r"(%\w+ = OpConstant %uint )(?:0x[fF]{4}0000|4294901760)\b", - r"\g<1>0", - spv, - count=1, - ) - self.assertEqual(n3, 1) - got_bad_mask = si.run_fragment(bad_mask)["%out_mrt0"][0] - self.assertNotEqual(got_bad_mask, want) - self.assertEqual(got_bad_mask, H_2P0) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_alu_sqrt_f32.py b/tests/semantic/test_alu_sqrt_f32.py deleted file mode 100644 index 4ea2f6ac8..000000000 --- a/tests/semantic/test_alu_sqrt_f32.py +++ /dev/null @@ -1,144 +0,0 @@ -"""Semantic translation tests for RDNA2 32-bit square root v_sqrt_f32. - -Translates a synthetic pixel-shader listing through tools/rdna2spirv.translate() --> SPIR-V -> tests/semantic/spirv_mini_interp.py and compares the result against -a plain-Python reference: math.sqrt(x) for finite non-negative x. - -Covers: - - Exact squares: sqrt(0), sqrt(1), sqrt(4), sqrt(9), sqrt(16), sqrt(25) - - sqrt(0.25) = 0.5 - - sqrt(2) with tolerance 1e-6 - - sqrt(+inf) -> +inf - - Reference comparison across varied non-negative bit patterns - - 50 randomized non-negative cases vs reference - - Negative control: result differs from input for non-trivial cases -""" -import math -import os -import struct -import sys -import tempfile -import unittest -import warnings -import random - -HERE = os.path.dirname(os.path.abspath(__file__)) -ROOT = os.path.dirname(os.path.dirname(HERE)) -TOOLS_DIR = os.environ.get("LEONIDA_TOOLS_DIR") or os.path.join(ROOT, "tools") - -sys.dont_write_bytecode = True -if TOOLS_DIR not in sys.path: - sys.path.insert(0, TOOLS_DIR) -if HERE not in sys.path: - sys.path.insert(0, HERE) - -import rdna2spirv # noqa: E402 -import spirv_mini_interp as si # noqa: E402 - -M32 = 0xFFFFFFFF -STUB_DXBC = b"DXBC" + bytes(24) + struct.pack(" int: - """Reference implementation of v_sub_u32 / v_sub_nc_u32: S0 - S1 (mod 2^32).""" - return ((s0 & MASK32) - (s1 & MASK32)) & MASK32 - - -def ref_v_subrev_u32(s0: int, s1: int) -> int: - """Reference implementation of v_subrev_u32 / v_subrev_nc_u32: S1 - S0 (mod 2^32).""" - return ((s1 & MASK32) - (s0 & MASK32)) & MASK32 - - -def ref_v_sub_nc_u32(s0: int, s1: int) -> int: - """Alias for ref_v_sub_u32.""" - return ref_v_sub_u32(s0, s1) - - -def ref_v_subrev_nc_u32(s0: int, s1: int) -> int: - """Alias for ref_v_subrev_u32.""" - return ref_v_subrev_u32(s0, s1) - - -def ref_borrow_u32(s0: int, s1: int) -> int: - """Borrow out flag for S0 - S1 (1 if S0 < S1 unsigned, else 0).""" - return 1 if (s0 & MASK32) < (s1 & MASK32) else 0 - - -def ref_borrow_rev_u32(s0: int, s1: int) -> int: - """Borrow out flag for reverse subtraction S1 - S0 (1 if S1 < S0 unsigned, else 0).""" - return 1 if (s1 & MASK32) < (s0 & MASK32) else 0 - - -def to_signed_i32(val: int) -> int: - """Interpret 32-bit bit pattern as signed two's complement integer.""" - val &= MASK32 - return val - (1 << 32) if (val & 0x80000000) else val - - -class VectorALUInterpreter: - """Deterministic semantic interpreter for AMD RDNA vector integer subtraction. - - Models: - - 64-lane SIMD vector registers (VGPRs) - - Scalar registers (SGPRs) - - EXEC mask gating active lanes (inactive lanes preserve prior contents) - - Support for inline constants and register operands - """ - - def __init__(self, num_vgprs: int = 64, num_sgprs: int = 106, wave_size: int = 64): - self.num_vgprs = num_vgprs - self.num_sgprs = num_sgprs - self.wave_size = wave_size - self.vgprs = [[0] * wave_size for _ in range(num_vgprs)] - self.sgprs = [0] * num_sgprs - self.exec_mask = (1 << wave_size) - 1 - - def reset(self) -> None: - self.vgprs = [[0] * self.wave_size for _ in range(self.num_vgprs)] - self.sgprs = [0] * self.num_sgprs - self.exec_mask = (1 << self.wave_size) - 1 - - def set_vgpr(self, reg_idx: int, lane: int, val: int) -> None: - self.vgprs[reg_idx][lane] = val & MASK32 - - def get_vgpr(self, reg_idx: int, lane: int) -> int: - return self.vgprs[reg_idx][lane] & MASK32 - - def set_sgpr(self, reg_idx: int, val: int) -> None: - self.sgprs[reg_idx] = val & MASK32 - - def get_sgpr(self, reg_idx: int) -> int: - return self.sgprs[reg_idx] & MASK32 - - def set_exec(self, mask: int) -> None: - self.exec_mask = mask & ((1 << self.wave_size) - 1) - - def resolve_src(self, op: str | int, lane: int) -> int: - if isinstance(op, int): - return op & MASK32 - op_str = op.strip().lower() - if op_str.startswith("v"): - idx = int(op_str[1:]) - return self.vgprs[idx][lane] & MASK32 - if op_str.startswith("s"): - idx = int(op_str[1:]) - return self.sgprs[idx] & MASK32 - return int(op_str, 0) & MASK32 - - def execute_v_sub_u32(self, dst_idx: int, src0: str | int, src1: str | int) -> None: - for lane in range(self.wave_size): - if (self.exec_mask >> lane) & 1: - s0 = self.resolve_src(src0, lane) - s1 = self.resolve_src(src1, lane) - self.vgprs[dst_idx][lane] = ref_v_sub_u32(s0, s1) - - def execute_v_subrev_u32(self, dst_idx: int, src0: str | int, src1: str | int) -> None: - for lane in range(self.wave_size): - if (self.exec_mask >> lane) & 1: - s0 = self.resolve_src(src0, lane) - s1 = self.resolve_src(src1, lane) - self.vgprs[dst_idx][lane] = ref_v_subrev_u32(s0, s1) - - def execute_v_sub_nc_u32(self, dst_idx: int, src0: str | int, src1: str | int) -> None: - self.execute_v_sub_u32(dst_idx, src0, src1) - - def execute_v_subrev_nc_u32(self, dst_idx: int, src0: str | int, src1: str | int) -> None: - self.execute_v_subrev_u32(dst_idx, src0, src1) - - -_TMP_DIR: tempfile.TemporaryDirectory | None = None -_SRC_PATH: str | None = None - - -def setUpModule() -> None: - global _TMP_DIR, _SRC_PATH - _TMP_DIR = tempfile.TemporaryDirectory() - disasm_dir = os.path.join(_TMP_DIR.name, "disasm") - os.mkdir(disasm_dir) - _SRC_PATH = os.path.join(disasm_dir, "ps_sub.s") - with open(os.path.join(_TMP_DIR.name, "ps_sub.dxbc"), "wb") as f: - f.write(STUB_DXBC) - - -def tearDownModule() -> None: - global _TMP_DIR - if _TMP_DIR is not None: - gc.collect() - _TMP_DIR.cleanup() - _TMP_DIR = None - - -def run_sub_shader( - op: str, - s0: int, - s1: int, - inline_s0: bool = False, - inline_s1: bool = False, - s0_is_sgpr: bool = False, -) -> int: - """Translates and runs a synthetic pixel shader invoking the subtraction operation.""" - if _TMP_DIR is None: - setUpModule() - lines = [] - if s0_is_sgpr: - lines.append(f"\ts_mov_b32 s0, {s0 & MASK32:#x}") - op0 = "s0" - elif inline_s0: - op0 = f"{s0 & MASK32:#x}" - else: - lines.append(f"\tv_mov_b32 v1, {s0 & MASK32:#x}") - op0 = "v1" - - if inline_s1: - op1 = f"{s1 & MASK32:#x}" - else: - lines.append(f"\tv_mov_b32 v2, {s1 & MASK32:#x}") - op1 = "v2" - - lines.append(f"\t{op} v0, {op0}, {op1}") - asm = ( - "; test_alu_sub\n" - + "\n".join(lines) - + "\n\texp mrt0 v0, v0, v0, v0 done vm\n\ts_endpgm\n" - ) - with open(_SRC_PATH, "w", encoding="utf-8") as f: - f.write(asm) - with warnings.catch_warnings(): - warnings.simplefilter("ignore", ResourceWarning) - spv = rdna2spirv.translate(_SRC_PATH) - return si.run_fragment(spv)["%out_mrt0"][0] - - -class VectorSubSemanticReferencesTest(unittest.TestCase): - """Tests the mathematical references for vector integer subtraction.""" - - def test_basic_subtraction(self): - self.assertEqual(ref_v_sub_u32(100, 30), 70) - self.assertEqual(ref_v_subrev_u32(100, 30), (30 - 100) & MASK32) - self.assertEqual(ref_v_subrev_u32(100, 30), 0xFFFFFFBA) - - def test_identity_properties(self): - values = [0, 1, 42, 0x7FFFFFFF, 0x80000000, 0xFFFFFFFF] - for v in values: - self.assertEqual(ref_v_sub_u32(v, 0), v) - self.assertEqual(ref_v_subrev_u32(0, v), v) - self.assertEqual(ref_v_sub_u32(v, v), 0) - self.assertEqual(ref_v_subrev_u32(v, v), 0) - self.assertEqual(ref_v_sub_u32(0, v), (-v) & MASK32) - self.assertEqual(ref_v_subrev_u32(v, 0), (-v) & MASK32) - - def test_anti_symmetry_and_reversal_duality(self): - pairs = [ - (50, 20), - (20, 50), - (0, 1), - (0xFFFFFFFF, 1), - (0x80000000, 0x7FFFFFFF), - ] - for a, b in pairs: - fwd = ref_v_sub_u32(a, b) - rev = ref_v_subrev_u32(a, b) - self.assertEqual((fwd + rev) & MASK32, 0) - self.assertEqual(ref_v_sub_u32(a, b), ref_v_subrev_u32(b, a)) - self.assertEqual(ref_v_sub_nc_u32(a, b), ref_v_sub_u32(a, b)) - self.assertEqual(ref_v_subrev_nc_u32(a, b), ref_v_subrev_u32(a, b)) - - def test_signed_two_complement_equivalence(self): - pairs = [ - (10, 25), - (0x7FFFFFFF, 1), - (0x80000000, 1), - (0xFFFFFFFF, 0xFFFFFFFF), - (0, 0xFFFFFFFF), - ] - for a, b in pairs: - u_diff = ref_v_sub_u32(a, b) - sa = to_signed_i32(a) - sb = to_signed_i32(b) - s_diff = (sa - sb) & MASK32 - self.assertEqual(u_diff, s_diff) - - def test_borrow_flags(self): - self.assertEqual(ref_borrow_u32(10, 5), 0) - self.assertEqual(ref_borrow_u32(5, 10), 1) - self.assertEqual(ref_borrow_u32(0, 0), 0) - self.assertEqual(ref_borrow_u32(0, 1), 1) - self.assertEqual(ref_borrow_u32(0xFFFFFFFF, 0xFFFFFFFF), 0) - self.assertEqual(ref_borrow_u32(0xFFFFFFFF, 0), 0) - self.assertEqual(ref_borrow_u32(0, 0xFFFFFFFF), 1) - - self.assertEqual(ref_borrow_rev_u32(10, 5), 1) - self.assertEqual(ref_borrow_rev_u32(5, 10), 0) - - -class VectorSubBoundaryValuesTest(unittest.TestCase): - """Tests extreme and boundary cases for 32-bit vector subtraction.""" - - def test_extremal_differences(self): - self.assertEqual(ref_v_sub_u32(0, 1), 0xFFFFFFFF) - self.assertEqual(ref_v_sub_u32(1, 0), 1) - self.assertEqual(ref_v_sub_u32(0x7FFFFFFF, 0x80000000), 0xFFFFFFFF) - self.assertEqual(ref_v_sub_u32(0x80000000, 0x7FFFFFFF), 1) - self.assertEqual(ref_v_sub_u32(0x80000000, 1), 0x7FFFFFFF) - self.assertEqual(ref_v_sub_u32(0x7FFFFFFF, 0xFFFFFFFF), 0x80000000) - self.assertEqual(ref_v_sub_u32(0xFFFFFFFF, 0x7FFFFFFF), 0x80000000) - self.assertEqual(ref_v_sub_u32(0, 0xFFFFFFFF), 1) - - def test_reverse_extremal_differences(self): - self.assertEqual(ref_v_subrev_u32(1, 0), 0xFFFFFFFF) - self.assertEqual(ref_v_subrev_u32(0, 1), 1) - self.assertEqual(ref_v_subrev_u32(0x80000000, 0x7FFFFFFF), 0xFFFFFFFF) - self.assertEqual(ref_v_subrev_u32(0x7FFFFFFF, 0x80000000), 1) - self.assertEqual(ref_v_subrev_u32(1, 0x80000000), 0x7FFFFFFF) - - -class VectorALUInterpreterTest(unittest.TestCase): - """Tests the stateful VectorALUInterpreter modeling multi-lane SIMD execution and EXEC gating.""" - - def test_multi_lane_subtraction(self): - interp = VectorALUInterpreter(wave_size=64) - for lane in range(64): - interp.set_vgpr(1, lane, lane * 10) - interp.set_vgpr(2, lane, lane * 3) - - interp.execute_v_sub_u32(0, "v1", "v2") - for lane in range(64): - expected = (lane * 10 - lane * 3) & MASK32 - self.assertEqual(interp.get_vgpr(0, lane), expected) - - def test_multi_lane_subrev(self): - interp = VectorALUInterpreter(wave_size=64) - for lane in range(64): - interp.set_vgpr(1, lane, lane * 10) - interp.set_vgpr(2, lane, lane * 3) - - interp.execute_v_subrev_u32(0, "v1", "v2") - for lane in range(64): - expected = (lane * 3 - lane * 10) & MASK32 - self.assertEqual(interp.get_vgpr(0, lane), expected) - - def test_exec_mask_inactive_lanes_preserved(self): - interp = VectorALUInterpreter(wave_size=64) - for lane in range(64): - interp.set_vgpr(0, lane, 0xDEADBEEF) - interp.set_vgpr(1, lane, 100) - interp.set_vgpr(2, lane, 40) - - # Alternating mask: only even lanes active - interp.set_exec(0x5555555555555555) - interp.execute_v_sub_nc_u32(0, "v1", "v2") - - for lane in range(64): - if lane % 2 == 0: - self.assertEqual(interp.get_vgpr(0, lane), 60) - else: - self.assertEqual(interp.get_vgpr(0, lane), 0xDEADBEEF) - - def test_scalar_and_constant_operands(self): - interp = VectorALUInterpreter(wave_size=32) - interp.set_sgpr(0, 500) - for lane in range(32): - interp.set_vgpr(1, lane, lane) - - # v_sub_nc_u32 v0, s0, v1 -> 500 - lane - interp.execute_v_sub_nc_u32(0, "s0", "v1") - for lane in range(32): - self.assertEqual(interp.get_vgpr(0, lane), 500 - lane) - - # v_subrev_nc_u32 v0, 10, v1 -> lane - 10 - interp.execute_v_subrev_nc_u32(0, 10, "v1") - for lane in range(32): - self.assertEqual(interp.get_vgpr(0, lane), (lane - 10) & MASK32) - - -class VectorSubSpirvLoweringTest(unittest.TestCase): - """Tests shader assembly translation through rdna2spirv and execution in spirv_mini_interp.""" - - def test_v_sub_nc_u32_default_vop2(self): - res = run_sub_shader("v_sub_nc_u32", 100, 30) - self.assertEqual(res, 70) - - def test_v_subrev_nc_u32_default_vop2(self): - res = run_sub_shader("v_subrev_nc_u32", 100, 30) - self.assertEqual(res, (30 - 100) & MASK32) - - def test_v_sub_nc_u32_e32(self): - res = run_sub_shader("v_sub_nc_u32_e32", 200, 75) - self.assertEqual(res, 125) - - def test_v_subrev_nc_u32_e32(self): - res = run_sub_shader("v_subrev_nc_u32_e32", 200, 75) - self.assertEqual(res, (75 - 200) & MASK32) - - def test_v_sub_nc_u32_e64(self): - res = run_sub_shader("v_sub_nc_u32_e64", 0x80000000, 1) - self.assertEqual(res, 0x7FFFFFFF) - - def test_v_subrev_nc_u32_e64(self): - res = run_sub_shader("v_subrev_nc_u32_e64", 1, 0x80000000) - self.assertEqual(res, 0x7FFFFFFF) - - def test_inline_constants(self): - res = run_sub_shader("v_sub_nc_u32", 5, 20, inline_s0=True) - self.assertEqual(res, (5 - 20) & MASK32) - - res = run_sub_shader("v_subrev_nc_u32", 5, 20, inline_s0=True) - self.assertEqual(res, (20 - 5) & MASK32) - - res = run_sub_shader("v_sub_nc_u32", 0, 1, inline_s0=True) - self.assertEqual(res, 0xFFFFFFFF) - - res = run_sub_shader("v_subrev_nc_u32", 0, 1, inline_s0=True) - self.assertEqual(res, 1) - - def test_sgpr_scalar_source(self): - res = run_sub_shader("v_sub_nc_u32", 50, 15, s0_is_sgpr=True) - self.assertEqual(res, 35) - - res = run_sub_shader("v_subrev_nc_u32", 50, 15, s0_is_sgpr=True) - self.assertEqual(res, (15 - 50) & MASK32) - - def test_emitted_spirv_contains_op_isub(self): - if _TMP_DIR is None: - setUpModule() - lines = [ - "\tv_mov_b32 v1, 80", - "\tv_mov_b32 v2, 35", - "\tv_sub_nc_u32 v0, v1, v2", - "\texp mrt0 v0, v0, v0, v0 done vm", - "\ts_endpgm", - ] - asm = "; test_op_check\n" + "\n".join(lines) + "\n" - with open(_SRC_PATH, "w", encoding="utf-8") as f: - f.write(asm) - with warnings.catch_warnings(): - warnings.simplefilter("ignore", ResourceWarning) - spv = rdna2spirv.translate(_SRC_PATH) - self.assertIn("OpISub %uint", spv) - - -class VectorSub64BitBorrowChainingTest(unittest.TestCase): - """Tests 64-bit multi-word vector integer subtraction using borrow tracking.""" - - def emulate_v_sub_u64(self, a_lo: int, a_hi: int, b_lo: int, b_hi: int) -> tuple[int, int]: - diff_lo = ref_v_sub_nc_u32(a_lo, b_lo) - borrow = ref_borrow_u32(a_lo, b_lo) - diff_hi = (ref_v_sub_nc_u32(a_hi, b_hi) - borrow) & MASK32 - return diff_lo, diff_hi - - def test_chained_64bit_subtraction(self): - test_cases = [ - (0x00000000_00000005, 0x00000000_00000002), - (0x00000001_00000000, 0x00000000_00000001), - (0x00000000_00000000, 0x00000000_00000001), - (0x12345678_00000000, 0x00000000_FFFFFFFF), - (0xFFFFFFFF_FFFFFFFF, 0x00000000_00000001), - (0x80000000_00000000, 0x7FFFFFFF_FFFFFFFF), - ] - for a64, b64 in test_cases: - a_lo, a_hi = a64 & MASK32, (a64 >> 32) & MASK32 - b_lo, b_hi = b64 & MASK32, (b64 >> 32) & MASK32 - d_lo, d_hi = self.emulate_v_sub_u64(a_lo, a_hi, b_lo, b_hi) - res64 = ((d_hi & MASK32) << 32) | (d_lo & MASK32) - expected64 = (a64 - b64) & MASK64 - self.assertEqual(res64, expected64) - - -class VectorSubDifferentialFuzzTest(unittest.TestCase): - """Deterministic fuzz testing against reference models and SPIR-V pipeline.""" - - def test_differential_random_pairs(self): - rng = random.Random(0x50B) - interp = VectorALUInterpreter(wave_size=1) - - for _ in range(120): - a = rng.randint(0, MASK32) - b = rng.randint(0, MASK32) - - expected_sub = (a - b) & MASK32 - expected_subrev = (b - a) & MASK32 - - self.assertEqual(ref_v_sub_u32(a, b), expected_sub) - self.assertEqual(ref_v_sub_nc_u32(a, b), expected_sub) - self.assertEqual(ref_v_subrev_u32(a, b), expected_subrev) - self.assertEqual(ref_v_subrev_nc_u32(a, b), expected_subrev) - - interp.set_vgpr(1, 0, a) - interp.set_vgpr(2, 0, b) - interp.execute_v_sub_nc_u32(0, "v1", "v2") - self.assertEqual(interp.get_vgpr(0, 0), expected_sub) - - interp.execute_v_subrev_nc_u32(0, "v1", "v2") - self.assertEqual(interp.get_vgpr(0, 0), expected_subrev) - - # Cross-check a sample subset through rdna2spirv and spirv_mini_interp - sample_pairs = [ - (rng.randint(0, MASK32), rng.randint(0, MASK32)) - for _ in range(8) - ] - for a, b in sample_pairs: - spv_sub = run_sub_shader("v_sub_nc_u32", a, b) - self.assertEqual(spv_sub, (a - b) & MASK32) - spv_subrev = run_sub_shader("v_subrev_nc_u32", a, b) - self.assertEqual(spv_subrev, (b - a) & MASK32) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_alu_subrev_f16.py b/tests/semantic/test_alu_subrev_f16.py deleted file mode 100644 index aee68e7d7..000000000 --- a/tests/semantic/test_alu_subrev_f16.py +++ /dev/null @@ -1,885 +0,0 @@ -"""Semantic interpreter tests for RDNA2 v_subrev_f16, v_subrev_nc_u32, and packed half-precision reverse subtraction. - -v_subrev_f16: D.f16 = S1.f16 - S0.f16 (VOP2 0x34 on GFX10), the reversed form of v_sub_f16. Like the other f16 -VOP2/VOP3 ops it writes the low half of the destination and keeps the high half; in the VOP3 form op_sel bit 0 / 1 -reads the high half of src0 / src1 and bit 2 writes the high half of the destination instead (docs/design.md, -"16-bit results"). Each case translates a synthetic pixel shader with tools/rdna2spirv.py, runs it in -tests/semantic/spirv_mini_interp.py and compares the exported word with a plain-Python reference: the difference -of the two f16 values computed in double precision and rounded once to f16 (round to nearest even). - -Also covers v_subrev_nc_u32: D.u32 = (S1.u32 - S0.u32) & 0xFFFFFFFF, the non-carry 32-bit reverse subtract, -packed 16-bit lane execution (modeling v_pk_subrev_f16 on lo and hi halves), SIMD divergence under EXEC mask, -and comprehensive IEEE 754 edge cases (signed zeros, infinities, NaN quieting and propagation). - -Standard library only: zero game data, no GPU hardware required. -""" -from __future__ import annotations - -import itertools -import math -import os -import random -import struct -import sys -import tempfile -import unittest -import warnings - -HERE = os.path.dirname(os.path.abspath(__file__)) -ROOT = os.path.dirname(os.path.dirname(HERE)) -TOOLS_DIR = os.environ.get("LEONIDA_TOOLS_DIR") or os.path.join(ROOT, "tools") - -sys.dont_write_bytecode = True -sys.path.insert(0, TOOLS_DIR) -sys.path.insert(0, HERE) - -import rdna2spirv # noqa: E402 -import spirv_mini_interp as si # noqa: E402 - -STUB_DXBC = b"DXBC" + bytes(24) + struct.pack(" float: - """Unpack 16-bit integer as IEEE 754 half-precision float.""" - return struct.unpack(" int: - """Pack float to 16-bit IEEE 754 half-precision integer with round-to-nearest-even.""" - try: - return struct.unpack(" 0 else H_NEG_INF - - -def is_nan_f16(h: int) -> bool: - """Check if 16-bit integer represents an IEEE 754 half-precision NaN.""" - return (h & 0x7C00) == 0x7C00 and (h & 0x03FF) != 0 - - -def is_qnan_f16(h: int) -> bool: - """Check if 16-bit integer represents a quiet NaN.""" - return is_nan_f16(h) and bool(h & 0x0200) - - -def is_snan_f16(h: int) -> bool: - """Check if 16-bit integer represents a signaling NaN.""" - return is_nan_f16(h) and not bool(h & 0x0200) - - -def is_inf_f16(h: int) -> bool: - """Check if 16-bit integer represents an IEEE 754 infinity.""" - return (h & 0x7FFF) == 0x7C00 - - -def half(word: int, hi: int) -> float: - """Extract float from low (hi=0) or high (hi=1) 16 bits of a 32-bit word.""" - return h2f(word >> 16 if hi else word) - - -def merge_half(old: int, h: int, dst_hi: int) -> int: - """Merge 16-bit result into low (dst_hi=0) or high (dst_hi=1) half of old word.""" - h &= 0xFFFF - return ((h << 16) | (old & 0xFFFF)) if dst_hi else ((old & 0xFFFF0000) | h) - - -def pack16(lo: int, hi: int) -> int: - """Pack two 16-bit values into a 32-bit register word.""" - return ((hi & 0xFFFF) << 16) | (lo & 0xFFFF) - - -def ref_subrev_f16(s0: int, s1: int) -> int: - """Reference implementation of v_subrev_f16: D.f16 = S1.f16 - S0.f16.""" - s0 &= 0xFFFF - s1 &= 0xFFFF - if is_nan_f16(s0) or is_nan_f16(s1): - return H_QNAN - inf0, inf1 = is_inf_f16(s0), is_inf_f16(s1) - if inf0 and inf1: - if (s0 >> 15) == (s1 >> 15): - return H_QNAN - return s1 - if inf1: - return s1 - if inf0: - return H_NEG_INF if (s0 >> 15) == 0 else H_POS_INF - f0, f1 = h2f(s0), h2f(s1) - diff = f1 - f0 - if diff == 0.0: - if s1 == H_NEG_ZERO and s0 == H_POS_ZERO: - return H_NEG_ZERO - return H_POS_ZERO - return f2h(diff) - - -def ref_sub_f16(s0: int, s1: int) -> int: - """Reference implementation of v_sub_f16: D.f16 = S0.f16 - S1.f16.""" - return ref_subrev_f16(s1, s0) - - -def ref_subrev_nc_u32(s0: int, s1: int) -> int: - """Reference implementation of v_subrev_nc_u32: D.u32 = (S1.u32 - S0.u32) & 0xFFFFFFFF.""" - return ((s1 & MASK32) - (s0 & MASK32)) & MASK32 - - -def ref_sub_nc_u32(s0: int, s1: int) -> int: - """Reference implementation of v_sub_nc_u32: D.u32 = (S0.u32 - S1.u32) & 0xFFFFFFFF.""" - return ((s0 & MASK32) - (s1 & MASK32)) & MASK32 - - -def ref_pk_subrev_f16(s0: int, s1: int, clamp: bool = False) -> int: - """Reference implementation of packed 16-bit reverse subtraction (v_pk_subrev_f16): - D.lo = S1.lo - S0.lo - D.hi = S1.hi - S0.hi - """ - s0_lo, s0_hi = s0 & 0xFFFF, (s0 >> 16) & 0xFFFF - s1_lo, s1_hi = s1 & 0xFFFF, (s1 >> 16) & 0xFFFF - d_lo = ref_subrev_f16(s0_lo, s1_lo) - d_hi = ref_subrev_f16(s0_hi, s1_hi) - if clamp: - if not is_nan_f16(d_lo): - d_lo = f2h(max(0.0, min(1.0, h2f(d_lo)))) - if not is_nan_f16(d_hi): - d_hi = f2h(max(0.0, min(1.0, h2f(d_hi)))) - return pack16(d_lo, d_hi) - - -def ref_pk_sub_f16(s0: int, s1: int, clamp: bool = False) -> int: - """Reference implementation of packed 16-bit forward subtraction: D = S0 - S1 on both halves.""" - return ref_pk_subrev_f16(s1, s0, clamp=clamp) - - -def ref_subrev_f16_opsel( - w0: int, - w1: int, - old: int, - sel0: int, - sel1: int, - dst_hi: int, - neg0: bool = False, - neg1: bool = False, - clamp: bool = False, -) -> int: - """Compute VOP3 v_subrev_f16 result with op_sel and input/output modifiers.""" - h0 = (w0 >> 16 if sel0 else w0) & 0xFFFF - h1 = (w1 >> 16 if sel1 else w1) & 0xFFFF - if neg0: - h0 ^= 0x8000 - if neg1: - h1 ^= 0x8000 - res = ref_subrev_f16(h0, h1) - if clamp and not is_nan_f16(res): - f = h2f(res) - f_clamped = max(0.0, min(1.0, f)) - res = f2h(f_clamped) - return merge_half(old, res, dst_hi) - - -class HalfVectorALUInterpreter: - """Deterministic SIMD vector ALU interpreter for half-precision and 32-bit operations. - - Models: - - 32-lane (Wave32) or 64-lane (Wave64) SIMD execution - - VGPR file: 32-bit registers containing packed binary16 halves or u32 integers - - SGPR file: 32-bit scalar registers with automatic broadcast to vector lanes - - EXEC mask: lane gating where inactive lanes preserve pre-existing register state - - Inline constant and register operand resolution - """ - - def __init__(self, num_vgprs: int = 64, num_sgprs: int = 106, wave_size: int = 64): - self.num_vgprs = num_vgprs - self.num_sgprs = num_sgprs - self.wave_size = wave_size - self.vgprs = [[0] * wave_size for _ in range(num_vgprs)] - self.sgprs = [0] * num_sgprs - self.exec_mask = (1 << wave_size) - 1 - - def reset(self) -> None: - self.vgprs = [[0] * self.wave_size for _ in range(self.num_vgprs)] - self.sgprs = [0] * self.num_sgprs - self.exec_mask = (1 << self.wave_size) - 1 - - def set_vgpr(self, reg_idx: int, lane: int, val: int) -> None: - self.vgprs[reg_idx][lane] = val & MASK32 - - def get_vgpr(self, reg_idx: int, lane: int) -> int: - return self.vgprs[reg_idx][lane] & MASK32 - - def set_sgpr(self, reg_idx: int, val: int) -> None: - self.sgprs[reg_idx] = val & MASK32 - - def get_sgpr(self, reg_idx: int) -> int: - return self.sgprs[reg_idx] & MASK32 - - def set_exec(self, mask: int) -> None: - self.exec_mask = mask & ((1 << self.wave_size) - 1) - - def resolve_src(self, op: str | int, lane: int) -> int: - if isinstance(op, int): - return op & MASK32 - op_str = op.strip().lower() - if op_str.startswith("v"): - idx = int(op_str[1:]) - return self.vgprs[idx][lane] & MASK32 - if op_str.startswith("s"): - idx = int(op_str[1:]) - return self.sgprs[idx] & MASK32 - return int(op_str, 0) & MASK32 - - def execute_v_subrev_f16( - self, - dst_idx: int, - src0: str | int, - src1: str | int, - op_sel: tuple[int, int, int] = (0, 0, 0), - clamp: bool = False, - ) -> None: - sel0, sel1, dst_hi = op_sel - for lane in range(self.wave_size): - if (self.exec_mask >> lane) & 1: - s0 = self.resolve_src(src0, lane) - s1 = self.resolve_src(src1, lane) - old = self.vgprs[dst_idx][lane] - self.vgprs[dst_idx][lane] = ref_subrev_f16_opsel( - s0, s1, old, sel0, sel1, dst_hi, clamp=clamp - ) - - def execute_v_sub_f16( - self, - dst_idx: int, - src0: str | int, - src1: str | int, - op_sel: tuple[int, int, int] = (0, 0, 0), - clamp: bool = False, - ) -> None: - sel0, sel1, dst_hi = op_sel - self.execute_v_subrev_f16( - dst_idx, src1, src0, op_sel=(sel1, sel0, dst_hi), clamp=clamp - ) - - def execute_v_pk_subrev_f16( - self, - dst_idx: int, - src0: str | int, - src1: str | int, - clamp: bool = False, - ) -> None: - for lane in range(self.wave_size): - if (self.exec_mask >> lane) & 1: - s0 = self.resolve_src(src0, lane) - s1 = self.resolve_src(src1, lane) - self.vgprs[dst_idx][lane] = ref_pk_subrev_f16(s0, s1, clamp=clamp) - - def execute_v_subrev_nc_u32( - self, - dst_idx: int, - src0: str | int, - src1: str | int, - ) -> None: - for lane in range(self.wave_size): - if (self.exec_mask >> lane) & 1: - s0 = self.resolve_src(src0, lane) - s1 = self.resolve_src(src1, lane) - self.vgprs[dst_idx][lane] = ref_subrev_nc_u32(s0, s1) - - def execute_v_sub_nc_u32( - self, - dst_idx: int, - src0: str | int, - src1: str | int, - ) -> None: - for lane in range(self.wave_size): - if (self.exec_mask >> lane) & 1: - s0 = self.resolve_src(src0, lane) - s1 = self.resolve_src(src1, lane) - self.vgprs[dst_idx][lane] = ref_sub_nc_u32(s0, s1) - - -_TMP_DIR: tempfile.TemporaryDirectory | None = None -_SRC_PATH: str | None = None - - -def setUpModule() -> None: - global _TMP_DIR, _SRC_PATH - _TMP_DIR = tempfile.TemporaryDirectory() - disasm_dir = os.path.join(_TMP_DIR.name, "disasm") - os.mkdir(disasm_dir) - _SRC_PATH = os.path.join(disasm_dir, "ps_subrev_f16.s") - with open(os.path.join(_TMP_DIR.name, "ps_subrev_f16.dxbc"), "wb") as f: - f.write(STUB_DXBC) - - -def tearDownModule() -> None: - global _TMP_DIR - if _TMP_DIR is not None: - _TMP_DIR.cleanup() - _TMP_DIR = None - - -def run(line: str, v1: int, v2: int, old: int = OLD) -> int: - """Seed v1, v2 and destination v0, run assembly line, return exported v0.""" - return run_shader([line], v1=v1, v2=v2, old=old) - - -def run_shader(lines: list[str], v1: int = 0, v2: int = 0, old: int = OLD) -> int: - """Seed v1, v2 and destination v0, run lines, return exported v0.""" - if _TMP_DIR is None: - setUpModule() - preamble = [ - f"v_mov_b32 v1, {v1 & MASK32:#x}", - f"v_mov_b32 v2, {v2 & MASK32:#x}", - f"v_mov_b32 v0, {old & MASK32:#x}", - ] - asm = ( - "; test_subrev_f16\n" - + "".join(f"\t{ln}\n" for ln in preamble + list(lines)) - + "\texp mrt0 v0, v0, v0, v0 done vm\n\ts_endpgm\n" - ) - with open(_SRC_PATH, "w", encoding="utf-8") as f: - f.write(asm) - with warnings.catch_warnings(): - warnings.simplefilter("ignore", ResourceWarning) - spv = rdna2spirv.translate(_SRC_PATH) - return si.run_fragment(spv)["%out_mrt0"][0] - - -class SubrevF16ReferenceOracleTests(unittest.TestCase): - """Mathematical properties and correctness of the half-precision reverse subtraction oracle.""" - - def test_formula_s1_minus_s0(self): - self.assertEqual(ref_subrev_f16(H_ONE_P_FIVE, H_HALF), H_NEG_ONE) - self.assertEqual(ref_subrev_f16(H_HALF, H_ONE_P_FIVE), H_ONE) - self.assertEqual(ref_subrev_f16(H_ONE, H_THREE), H_TWO) - self.assertEqual(ref_subrev_f16(H_TWO, H_ONE), H_NEG_ONE) - - def test_non_commutativity(self): - pairs = [ - (H_ONE_P_FIVE, H_HALF), - (H_ONE, H_THREE), - (H_TWO, H_FOUR), - (H_NEG_ONE, H_ONE), - ] - for s0, s1 in pairs: - with self.subTest(s0=hex(s0), s1=hex(s1)): - d_rev = ref_subrev_f16(s0, s1) - d_rev_swapped = ref_subrev_f16(s1, s0) - self.assertNotEqual(d_rev, d_rev_swapped) - - def test_anti_symmetry(self): - pairs = [ - (H_ONE_P_FIVE, H_HALF), - (H_ONE, H_THREE), - (H_TWO, H_FOUR), - (H_HALF, H_TWO), - (H_NEG_ONE, H_TWO), - ] - for s0, s1 in pairs: - with self.subTest(s0=hex(s0), s1=hex(s1)): - r1 = ref_subrev_f16(s0, s1) - r2 = ref_subrev_f16(s1, s0) - self.assertEqual(r1 ^ 0x8000, r2) - self.assertAlmostEqual(h2f(r1), -h2f(r2), places=3) - - def test_identity_properties(self): - values = [H_HALF, H_ONE, H_ONE_P_FIVE, H_TWO, H_THREE, H_FOUR, H_NEG_ONE, H_NEG_TWO] - for v in values: - with self.subTest(v=hex(v)): - self.assertEqual(ref_subrev_f16(H_POS_ZERO, v), v) - self.assertEqual(ref_subrev_f16(v, v), H_POS_ZERO) - self.assertEqual(ref_subrev_f16(v, H_POS_ZERO), v ^ 0x8000) - - def test_reversal_duality_with_sub(self): - rng = random.Random(0x3416) - samples = [H_POS_ZERO, H_HALF, H_ONE, H_ONE_P_FIVE, H_TWO, H_THREE, H_FOUR, H_NEG_ONE, H_NEG_TWO] - for _ in range(50): - s0 = rng.choice(samples) - s1 = rng.choice(samples) - self.assertEqual(ref_subrev_f16(s0, s1), ref_sub_f16(s1, s0)) - - def test_u32_reverse_subtraction(self): - self.assertEqual(ref_subrev_nc_u32(30, 100), 70) - self.assertEqual(ref_subrev_nc_u32(100, 30), (30 - 100) & MASK32) - self.assertEqual(ref_subrev_nc_u32(0, 42), 42) - self.assertEqual(ref_subrev_nc_u32(42, 0), (-42) & MASK32) - self.assertEqual(ref_subrev_nc_u32(0x80000000, 0x7FFFFFFF), 0xFFFFFFFF) - self.assertEqual(ref_subrev_nc_u32(0x7FFFFFFF, 0x80000000), 1) - - for a, b in [(10, 50), (100, 25), (0x12345678, 0x87654321)]: - fwd = ref_sub_nc_u32(a, b) - rev = ref_subrev_nc_u32(a, b) - self.assertEqual((fwd + rev) & MASK32, 0) - self.assertEqual(ref_subrev_nc_u32(a, b), ref_sub_nc_u32(b, a)) - - -class SubrevF16ShaderTranslationTests(unittest.TestCase): - """End-to-end pixel shader execution comparing rdna2spirv output against reference oracle.""" - - def test_vop2_is_src1_minus_src0_and_keeps_the_high_half(self): - got = run("v_subrev_f16_e32 v0, v1, v2", A, B) - want = merge_half(OLD, ref_subrev_f16(0x3E00, 0x3800), 0) - self.assertEqual(got, want) - - def test_vop3_op_sel(self): - for bits in itertools.product((0, 1), repeat=3): - line = f"v_subrev_f16_e64 v0, v1, v2 op_sel:[{bits[0]},{bits[1]},{bits[2]}]" - with self.subTest(line=line): - want = ref_subrev_f16_opsel(A, B, OLD, bits[0], bits[1], bits[2]) - self.assertEqual(run(line, A, B), want) - - def test_neg_on_src0_and_clamp(self): - self.assertEqual(run("v_subrev_f16_e64 v0, -v1, v2", A, B), merge_half(OLD, f2h(2.0), 0)) - self.assertEqual(run("v_subrev_f16_e64 v0, -v1, v2 clamp", A, B), merge_half(OLD, f2h(1.0), 0)) - - def test_matches_v_sub_f16_with_swapped_operands(self): - rng = random.Random(0x34) - special = [0x0000, 0x8000, 0x0001, 0x03FF, 0x0400, 0x3C00, 0xBC00, 0x7BFF, 0xFBFF, 0x3555] - for _ in range(40): - x, y = (rng.choice(special) if rng.random() < 0.3 else rng.randrange(0x10000) for _ in range(2)) - if (x & 0x7C00) == 0x7C00 or (y & 0x7C00) == 0x7C00: - continue - v1, v2 = 0x12340000 | x, 0x56780000 | y - with self.subTest(x=hex(x), y=hex(y)): - got = run("v_subrev_f16_e32 v0, v1, v2", v1, v2) - self.assertEqual(got, run("v_sub_f16_e32 v0, v2, v1", v1, v2)) - want = ref_subrev_f16(x, y) - if want in (0x0000, 0x8000): - self.assertEqual(got & 0xFFFF7FFF, OLD & 0xFFFF0000) - else: - self.assertEqual(got, merge_half(OLD, want, 0)) - - def test_v_subrev_nc_u32_shader_execution(self): - lines = ["v_subrev_nc_u32 v0, v1, v2"] - self.assertEqual(run_shader(lines, v1=30, v2=100), 70) - self.assertEqual(run_shader(lines, v1=100, v2=30), (30 - 100) & MASK32) - self.assertEqual(run_shader(lines, v1=0x80000000, v2=0x7FFFFFFF), 0xFFFFFFFF) - - def test_inline_constants_and_sgpr_sources(self): - lines = ["v_subrev_f16_e32 v0, 0x3800, v2"] - self.assertEqual(run_shader(lines, v2=H_TWO), merge_half(OLD, H_ONE_P_FIVE, 0)) - - lines_sgpr = [ - "s_mov_b32 s0, 50", - "v_subrev_nc_u32 v0, s0, v2", - ] - self.assertEqual(run_shader(lines_sgpr, v2=120), 70) - - -class PackedSubrevF16OracleTests(unittest.TestCase): - """Reference oracle tests for packed 16-bit lane execution modeling v_pk_subrev_f16.""" - - def test_packed_subrev_formula(self): - s0 = pack16(H_HALF, H_ONE) - s1 = pack16(H_TWO, H_THREE) - res = ref_pk_subrev_f16(s0, s1) - self.assertEqual(res & 0xFFFF, H_ONE_P_FIVE) - self.assertEqual((res >> 16) & 0xFFFF, H_TWO) - - def test_packed_non_commutativity(self): - s0 = pack16(H_HALF, H_ONE) - s1 = pack16(H_TWO, H_THREE) - res_fwd = ref_pk_subrev_f16(s0, s1) - res_swapped = ref_pk_subrev_f16(s1, s0) - self.assertNotEqual(res_fwd, res_swapped) - self.assertNotEqual(res_fwd & 0xFFFF, res_swapped & 0xFFFF) - self.assertNotEqual((res_fwd >> 16) & 0xFFFF, (res_swapped >> 16) & 0xFFFF) - - def test_packed_anti_symmetry(self): - s0 = pack16(H_HALF, H_ONE) - s1 = pack16(H_TWO, H_THREE) - r1 = ref_pk_subrev_f16(s0, s1) - r2 = ref_pk_subrev_f16(s1, s0) - self.assertEqual((r1 & 0xFFFF) ^ 0x8000, r2 & 0xFFFF) - self.assertEqual(((r1 >> 16) & 0xFFFF) ^ 0x8000, (r2 >> 16) & 0xFFFF) - - def test_packed_lane_isolation(self): - base_s0 = pack16(H_ONE, H_ONE) - base_s1 = pack16(H_TWO, H_THREE) - res_base = ref_pk_subrev_f16(base_s0, base_s1) - - mod_s0 = pack16(H_HALF, H_ONE) - res_mod = ref_pk_subrev_f16(mod_s0, base_s1) - self.assertNotEqual(res_base & 0xFFFF, res_mod & 0xFFFF) - self.assertEqual((res_base >> 16) & 0xFFFF, (res_mod >> 16) & 0xFFFF) - - mod_s1 = pack16(H_TWO, H_FOUR) - res_mod2 = ref_pk_subrev_f16(base_s0, mod_s1) - self.assertEqual(res_base & 0xFFFF, res_mod2 & 0xFFFF) - self.assertNotEqual((res_base >> 16) & 0xFFFF, (res_mod2 >> 16) & 0xFFFF) - - def test_packed_reversal_duality(self): - s0 = pack16(H_ONE, H_TWO) - s1 = pack16(H_THREE, H_FOUR) - self.assertEqual(ref_pk_subrev_f16(s0, s1), ref_pk_sub_f16(s1, s0)) - - -class HalfVectorALUInterpreterTests(unittest.TestCase): - """Multi-lane SIMD interpreter tests modeling packed subrev, EXEC divergence, and state preservation.""" - - def test_simd_wave64_packed_subrev(self): - interp = HalfVectorALUInterpreter(wave_size=64) - for lane in range(64): - s0 = pack16(f2h(1.0 + lane * 0.1), f2h(2.0 + lane * 0.2)) - s1 = pack16(f2h(5.0 + lane * 0.5), f2h(10.0 + lane * 1.0)) - interp.set_vgpr(1, lane, s0) - interp.set_vgpr(2, lane, s1) - - interp.execute_v_pk_subrev_f16(0, "v1", "v2") - - for lane in range(64): - expected = ref_pk_subrev_f16(interp.get_vgpr(1, lane), interp.get_vgpr(2, lane)) - self.assertEqual(interp.get_vgpr(0, lane), expected, f"lane {lane}") - - def test_simd_wave32_packed_subrev(self): - interp = HalfVectorALUInterpreter(wave_size=32) - for lane in range(32): - s0 = pack16(H_HALF, H_ONE) - s1 = pack16(H_TWO, H_THREE) - interp.set_vgpr(1, lane, s0) - interp.set_vgpr(2, lane, s1) - - interp.execute_v_pk_subrev_f16(0, "v1", "v2") - - expected = ref_pk_subrev_f16(pack16(H_HALF, H_ONE), pack16(H_TWO, H_THREE)) - for lane in range(32): - self.assertEqual(interp.get_vgpr(0, lane), expected, f"lane {lane}") - - def test_simd_exec_mask_partial_divergence(self): - interp = HalfVectorALUInterpreter(wave_size=64) - for lane in range(64): - interp.set_vgpr(0, lane, 0xDEADBEEF) - interp.set_vgpr(1, lane, pack16(H_HALF, H_ONE)) - interp.set_vgpr(2, lane, pack16(H_TWO, H_FOUR)) - - interp.set_exec(0x5555555555555555) - interp.execute_v_pk_subrev_f16(0, "v1", "v2") - - expected = ref_pk_subrev_f16(pack16(H_HALF, H_ONE), pack16(H_TWO, H_FOUR)) - for lane in range(64): - if lane % 2 == 0: - self.assertEqual(interp.get_vgpr(0, lane), expected, f"active lane {lane}") - else: - self.assertEqual(interp.get_vgpr(0, lane), 0xDEADBEEF, f"inactive lane {lane}") - - def test_simd_exec_mask_single_lane(self): - interp = HalfVectorALUInterpreter(wave_size=64) - for lane in range(64): - interp.set_vgpr(0, lane, 0xCAFEBABE) - interp.set_vgpr(1, lane, pack16(H_ONE, H_TWO)) - interp.set_vgpr(2, lane, pack16(H_THREE, H_FOUR)) - - interp.set_exec(1 << 7) - interp.execute_v_pk_subrev_f16(0, "v1", "v2") - - expected = ref_pk_subrev_f16(pack16(H_ONE, H_TWO), pack16(H_THREE, H_FOUR)) - for lane in range(64): - if lane == 7: - self.assertEqual(interp.get_vgpr(0, lane), expected) - else: - self.assertEqual(interp.get_vgpr(0, lane), 0xCAFEBABE) - - def test_simd_exec_mask_all_inactive(self): - interp = HalfVectorALUInterpreter(wave_size=64) - for lane in range(64): - interp.set_vgpr(0, lane, 0x12345678) - interp.set_vgpr(1, lane, pack16(H_HALF, H_HALF)) - interp.set_vgpr(2, lane, pack16(H_TWO, H_TWO)) - - interp.set_exec(0) - interp.execute_v_pk_subrev_f16(0, "v1", "v2") - - for lane in range(64): - self.assertEqual(interp.get_vgpr(0, lane), 0x12345678) - - def test_simd_scalar_broadcast_and_inline_constants(self): - interp = HalfVectorALUInterpreter(wave_size=32) - interp.set_sgpr(0, pack16(H_ONE, H_TWO)) - for lane in range(32): - interp.set_vgpr(1, lane, pack16(H_THREE, H_FOUR)) - - interp.execute_v_pk_subrev_f16(0, "s0", "v1") - expected = ref_pk_subrev_f16(pack16(H_ONE, H_TWO), pack16(H_THREE, H_FOUR)) - for lane in range(32): - self.assertEqual(interp.get_vgpr(0, lane), expected) - - def test_simd_v_subrev_f16_half_preservation(self): - interp = HalfVectorALUInterpreter(wave_size=32) - for lane in range(32): - interp.set_vgpr(0, lane, OLD) - interp.set_vgpr(1, lane, pack16(H_HALF, H_TWO)) - interp.set_vgpr(2, lane, pack16(H_ONE_P_FIVE, H_THREE)) - - interp.set_exec(0x55555555) - interp.execute_v_subrev_f16(0, "v1", "v2", op_sel=(0, 0, 0)) - - for lane in range(32): - if lane % 2 == 0: - self.assertEqual(interp.get_vgpr(0, lane), merge_half(OLD, H_ONE, 0)) - else: - self.assertEqual(interp.get_vgpr(0, lane), OLD) - - def test_simd_v_subrev_nc_u32_exec_divergence(self): - interp = HalfVectorALUInterpreter(wave_size=64) - for lane in range(64): - interp.set_vgpr(0, lane, 0x11111111) - interp.set_vgpr(1, lane, 50) - interp.set_vgpr(2, lane, 200 + lane) - - interp.set_exec(0xFFFFFFFF00000000) - interp.execute_v_subrev_nc_u32(0, "v1", "v2") - - for lane in range(64): - if lane >= 32: - self.assertEqual(interp.get_vgpr(0, lane), (200 + lane) - 50) - else: - self.assertEqual(interp.get_vgpr(0, lane), 0x11111111) - - -class ShaderPackedAndExecExecutionTests(unittest.TestCase): - """Shader execution tests for packed operations and EXEC mask gating.""" - - def test_packed_execution_via_dual_subrev_f16(self): - lines = [ - "v_subrev_f16_e64 v0, v1, v2 op_sel:[0,0,0]", - "v_subrev_f16_e64 v0, v1, v2 op_sel:[1,1,1]", - ] - v1 = pack16(H_HALF, H_ONE) - v2 = pack16(H_TWO, H_THREE) - got = run_shader(lines, v1=v1, v2=v2, old=OLD) - want = ref_pk_subrev_f16(v1, v2) - self.assertEqual(got, want) - - def test_packed_execution_via_v_pk_add_f16_with_negated_src0(self): - lines = [ - "v_pk_add_f16 v0, v1, v2 neg_lo:[1,0] neg_hi:[1,0]", - ] - v1 = pack16(H_HALF, H_ONE) - v2 = pack16(H_TWO, H_THREE) - got = run_shader(lines, v1=v1, v2=v2, old=OLD) - want = ref_pk_subrev_f16(v1, v2) - self.assertEqual(got, want) - - def test_exec_masking_preserves_destination(self): - lines = [ - "s_mov_b32 exec_lo, 0", - "v_subrev_f16_e32 v0, v1, v2", - "s_mov_b32 exec_lo, 1", - ] - got = run_shader(lines, v1=H_HALF, v2=H_TWO, old=OLD) - self.assertEqual(got, OLD) - - def test_exec_masking_toggled_execution(self): - lines = [ - "s_mov_b32 exec_lo, 0", - "v_subrev_f16_e64 v0, v1, v2 op_sel:[0,0,0]", - "s_mov_b32 exec_lo, 1", - "v_subrev_f16_e64 v0, v1, v2 op_sel:[1,1,1]", - ] - v1 = pack16(H_HALF, H_ONE) - v2 = pack16(H_TWO, H_THREE) - got = run_shader(lines, v1=v1, v2=v2, old=OLD) - expected = merge_half(OLD, H_TWO, 1) - self.assertEqual(got, expected) - - -class Ieee754SpecialValuesOracleTests(unittest.TestCase): - """IEEE 754 half-precision special values: signed zeros, infinities, NaN quieting and propagation.""" - - def test_signed_zero_reverse_subtraction(self): - # S1 - S0 in half precision: - # (+0.0) - (+0.0) == +0.0 - self.assertEqual(ref_subrev_f16(H_POS_ZERO, H_POS_ZERO), H_POS_ZERO) - # (-0.0) - (+0.0) == -0.0 - self.assertEqual(ref_subrev_f16(H_POS_ZERO, H_NEG_ZERO), H_NEG_ZERO) - # (+0.0) - (-0.0) == +0.0 - self.assertEqual(ref_subrev_f16(H_NEG_ZERO, H_POS_ZERO), H_POS_ZERO) - # (-0.0) - (-0.0) == +0.0 (IEEE 754 round to nearest: -0 - (-0) = -0 + 0 = +0) - self.assertEqual(ref_subrev_f16(H_NEG_ZERO, H_NEG_ZERO), H_POS_ZERO) - - def test_infinity_arithmetic(self): - # (+inf) - (+inf) == NaN - self.assertTrue(is_nan_f16(ref_subrev_f16(H_POS_INF, H_POS_INF))) - # (-inf) - (-inf) == NaN - self.assertTrue(is_nan_f16(ref_subrev_f16(H_NEG_INF, H_NEG_INF))) - # (+inf) - (-inf) == +inf (S1=+inf, S0=-inf) - self.assertEqual(ref_subrev_f16(H_NEG_INF, H_POS_INF), H_POS_INF) - # (-inf) - (+inf) == -inf (S1=-inf, S0=+inf) - self.assertEqual(ref_subrev_f16(H_POS_INF, H_NEG_INF), H_NEG_INF) - - # Finite S1 minus +/-inf S0 - self.assertEqual(ref_subrev_f16(H_POS_INF, H_ONE), H_NEG_INF) - self.assertEqual(ref_subrev_f16(H_NEG_INF, H_ONE), H_POS_INF) - self.assertEqual(ref_subrev_f16(H_POS_INF, H_NEG_ONE), H_NEG_INF) - self.assertEqual(ref_subrev_f16(H_NEG_INF, H_NEG_ONE), H_POS_INF) - - # +/-inf S1 minus finite S0 - self.assertEqual(ref_subrev_f16(H_ONE, H_POS_INF), H_POS_INF) - self.assertEqual(ref_subrev_f16(H_ONE, H_NEG_INF), H_NEG_INF) - self.assertEqual(ref_subrev_f16(H_NEG_ONE, H_POS_INF), H_POS_INF) - self.assertEqual(ref_subrev_f16(H_NEG_ONE, H_NEG_INF), H_NEG_INF) - - def test_nan_propagation_and_quieting(self): - # Quiet NaN in S0 or S1 propagates as quiet NaN - res_q0 = ref_subrev_f16(H_QNAN, H_ONE) - self.assertTrue(is_qnan_f16(res_q0)) - res_q1 = ref_subrev_f16(H_ONE, H_QNAN) - self.assertTrue(is_qnan_f16(res_q1)) - - # Signaling NaN in S0 or S1 is quieted to qNaN - res_s0 = ref_subrev_f16(H_SNAN, H_ONE) - self.assertTrue(is_qnan_f16(res_s0)) - res_s1 = ref_subrev_f16(H_ONE, H_SNAN) - self.assertTrue(is_qnan_f16(res_s1)) - - # Both operands NaN - self.assertTrue(is_qnan_f16(ref_subrev_f16(H_QNAN, H_QNAN))) - self.assertTrue(is_qnan_f16(ref_subrev_f16(H_SNAN, H_QNAN))) - self.assertTrue(is_qnan_f16(ref_subrev_f16(H_SNAN, H_SNAN))) - self.assertTrue(is_qnan_f16(ref_subrev_f16(H_SNAN_PAYLOAD, H_QNAN_PAYLOAD))) - - def test_finite_overflow_to_infinity(self): - # 65504.0 - (-65504.0) overflows to +inf - self.assertEqual(ref_subrev_f16(H_NEG_MAX, H_MAX_FINITE), H_POS_INF) - # -65504.0 - 65504.0 overflows to -inf - self.assertEqual(ref_subrev_f16(H_MAX_FINITE, H_NEG_MAX), H_NEG_INF) - - def test_subnormal_boundaries(self): - # Subnormal subtraction - self.assertEqual(ref_subrev_f16(H_SUB_MIN, H_SUB_MAX), H_SUB_MAX - H_SUB_MIN) - # Minimum normal minus smallest subnormal transitions to largest subnormal - diff = ref_subrev_f16(H_SUB_MIN, H_MIN_NORMAL) - self.assertEqual(diff, H_SUB_MAX) - - -class Ieee754SpecialValuesShaderExecutionTests(unittest.TestCase): - """End-to-end pixel shader execution for special values through rdna2spirv and spirv_mini_interp.""" - - def test_signed_zero_shader_execution(self): - # (+0.0) - (+0.0) == +0.0 - got_pos_pos = run("v_subrev_f16_e32 v0, v1, v2", H_POS_ZERO, H_POS_ZERO) - self.assertEqual(got_pos_pos & 0xFFFF, H_POS_ZERO) - - # (-0.0) - (+0.0) == -0.0 - got_neg_pos = run("v_subrev_f16_e32 v0, v1, v2", H_POS_ZERO, H_NEG_ZERO) - self.assertEqual(got_neg_pos & 0xFFFF, H_NEG_ZERO) - - # (+0.0) - (-0.0) == +0.0 - got_pos_neg = run("v_subrev_f16_e32 v0, v1, v2", H_NEG_ZERO, H_POS_ZERO) - self.assertEqual(got_pos_neg & 0xFFFF, H_POS_ZERO) - - # (-0.0) - (-0.0) == +0.0 - got_neg_neg = run("v_subrev_f16_e32 v0, v1, v2", H_NEG_ZERO, H_NEG_ZERO) - self.assertEqual(got_neg_neg & 0xFFFF, H_POS_ZERO) - - def test_infinity_subtraction_shader_execution(self): - # (+inf) - (+inf) == NaN - got_inf_nan = run("v_subrev_f16_e32 v0, v1, v2", H_POS_INF, H_POS_INF) & 0xFFFF - self.assertTrue(is_nan_f16(got_inf_nan)) - - # (-inf) - (-inf) == NaN - got_ninf_nan = run("v_subrev_f16_e32 v0, v1, v2", H_NEG_INF, H_NEG_INF) & 0xFFFF - self.assertTrue(is_nan_f16(got_ninf_nan)) - - # (+inf) - (-inf) == +inf - got_pinf = run("v_subrev_f16_e32 v0, v1, v2", H_NEG_INF, H_POS_INF) & 0xFFFF - self.assertEqual(got_pinf, H_POS_INF) - - # (-inf) - (+inf) == -inf - got_ninf = run("v_subrev_f16_e32 v0, v1, v2", H_POS_INF, H_NEG_INF) & 0xFFFF - self.assertEqual(got_ninf, H_NEG_INF) - - def test_nan_propagation_shader_execution(self): - # Quiet NaN in S0 produces NaN - got_q0 = run("v_subrev_f16_e32 v0, v1, v2", H_QNAN, H_ONE) & 0xFFFF - self.assertTrue(is_nan_f16(got_q0)) - - # Quiet NaN in S1 produces NaN - got_q1 = run("v_subrev_f16_e32 v0, v1, v2", H_ONE, H_QNAN) & 0xFFFF - self.assertTrue(is_nan_f16(got_q1)) - - # Signaling NaN in S0 is quieted to qNaN - got_s0 = run("v_subrev_f16_e32 v0, v1, v2", H_SNAN, H_ONE) & 0xFFFF - self.assertTrue(is_qnan_f16(got_s0)) - - # Signaling NaN in S1 is quieted to qNaN - got_s1 = run("v_subrev_f16_e32 v0, v1, v2", H_ONE, H_SNAN) & 0xFFFF - self.assertTrue(is_qnan_f16(got_s1)) - - # Both NaNs produce NaN - got_both = run("v_subrev_f16_e32 v0, v1, v2", H_SNAN, H_QNAN) & 0xFFFF - self.assertTrue(is_nan_f16(got_both)) - - def test_overflow_to_infinity_shader_execution(self): - # 65504.0 - (-65504.0) produces +inf - got_overflow_pos = run("v_subrev_f16_e32 v0, v1, v2", H_NEG_MAX, H_MAX_FINITE) & 0xFFFF - self.assertEqual(got_overflow_pos, H_POS_INF) - - # -65504.0 - 65504.0 produces -inf - got_overflow_neg = run("v_subrev_f16_e32 v0, v1, v2", H_MAX_FINITE, H_NEG_MAX) & 0xFFFF - self.assertEqual(got_overflow_neg, H_NEG_INF) - - def test_vop3_clamping_with_special_values(self): - # Negative result clamped to +0.0: 0.5 - 2.0 = -1.5 -> 0.0 - got_neg_clamp = run("v_subrev_f16_e64 v0, v1, v2 clamp", H_TWO, H_HALF) & 0xFFFF - self.assertEqual(got_neg_clamp, H_POS_ZERO) - - # Positive result > 1.0 clamped to 1.0: 3.0 - 1.0 = 2.0 -> 1.0 - got_pos_clamp = run("v_subrev_f16_e64 v0, v1, v2 clamp", H_ONE, H_THREE) & 0xFFFF - self.assertEqual(got_pos_clamp, H_ONE) - - # Overflow to +inf clamped to 1.0 - got_inf_clamp = run("v_subrev_f16_e64 v0, v1, v2 clamp", H_NEG_INF, H_POS_INF) & 0xFFFF - self.assertEqual(got_inf_clamp, H_ONE) - - # Overflow to -inf clamped to 0.0 - got_ninf_clamp = run("v_subrev_f16_e64 v0, v1, v2 clamp", H_POS_INF, H_NEG_INF) & 0xFFFF - self.assertEqual(got_ninf_clamp, H_POS_ZERO) - - def test_vop3_omod_and_clamp(self): - # An f16 destination ignores omod under the game's MODE (IEEE=0, f16 denormals kept) and keeps clamp: - # measured on gfx1036 (#4542, docs/design.md "`v_fmac_f16`, `v_interp_p2/mov_f32`, and f16 output modifiers"). - # 1.5 - 1.0 = 0.5; mul:2 leaves it. - got = run("v_subrev_f16_e64 v0, v1, v2 mul:2", H_ONE, f2h(1.5)) & 0xFFFF - self.assertEqual(got, H_HALF) - # 2.0 - 1.0 = 1.0; div:2 leaves it. - got_div = run("v_subrev_f16_e64 v0, v1, v2 div:2", H_ONE, H_TWO) & 0xFFFF - self.assertEqual(got_div, H_ONE) - # 1.5 - 1.0 = 0.5; mul:4 is ignored, clamp keeps 0.5. 3.0 - 1.0 = 2.0 clamps to 1.0. - got_clamp = run("v_subrev_f16_e64 v0, v1, v2 mul:4 clamp", H_ONE, f2h(1.5)) & 0xFFFF - self.assertEqual(got_clamp, H_HALF) - got_sat = run("v_subrev_f16_e64 v0, v1, v2 mul:4 clamp", H_ONE, f2h(3.0)) & 0xFFFF - self.assertEqual(got_sat, H_ONE) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_alu_swaprel.py b/tests/semantic/test_alu_swaprel.py deleted file mode 100644 index 64d76f0b2..000000000 --- a/tests/semantic/test_alu_swaprel.py +++ /dev/null @@ -1,250 +0,0 @@ -"""Reference oracle and value tests for v_swaprel_b32 (GFX10 VOP1 opcode 104). - -RDNA2 instruction semantics: - D_off = (M0 >> 16) & 0x3FF - S0_off = M0 & 0x3FF - tmp = VGPR[D + D_off] - VGPR[D + D_off] = VGPR[S0 + S0_off] - VGPR[S0 + S0_off] = tmp - -Both registers are read before either is written. When both operands address -the same physical VGPR, its value is preserved. M0 bits [15:10] and [31:26] -are ignored. - -Standard library only; zero game data, zero external dependencies. -""" -from __future__ import annotations - -import os -import struct -import sys -import unittest -import warnings - -HERE = os.path.dirname(os.path.abspath(__file__)) -ROOT = os.path.dirname(os.path.dirname(HERE)) -sys.dont_write_bytecode = True -sys.path.insert(0, os.environ.get("LEONIDA_TOOLS_DIR") or os.path.join(ROOT, "tools")) -sys.path.insert(0, HERE) - -import rdna2spirv # noqa: E402 -import spirv_mini_interp as si # noqa: E402 -from support import STUB_DXBC, translate_lines # noqa: E402 - -MASK10 = 0x3FF -MASK32 = 0xFFFFFFFF -NUM_VGPRS = 256 - - -def sentinel(n: int) -> int: - """Deterministic normal f32 bit pattern per VGPR index.""" - return 0x40000000 + (n & 0x00FFFFFF) - - -class SwaprelOracle: - """Architectural reference oracle for RDNA2 v_swaprel_b32.""" - - def __init__(self, size: int = NUM_VGPRS, init_map: dict[int, int] | None = None) -> None: - self.size = size - self.regs = [sentinel(i) for i in range(size)] - if init_map: - for r, v in init_map.items(): - if 0 <= r < size: - self.regs[r] = v & MASK32 - - @staticmethod - def decode_offsets(m0: int) -> tuple[int, int]: - """Decode relative offsets: (D_offset, S0_offset).""" - d_off = (m0 >> 16) & MASK10 - s0_off = m0 & MASK10 - return d_off, s0_off - - def step(self, d: int, s0: int, m0: int) -> tuple[int, int]: - """Execute v_swaprel_b32 in-place; return effective (d_eff, s0_eff).""" - d_off, s0_off = self.decode_offsets(m0) - d_eff = d + d_off - s0_eff = s0 + s0_off - if 0 <= d_eff < self.size and 0 <= s0_eff < self.size: - val_d = self.regs[d_eff] - val_s0 = self.regs[s0_eff] - self.regs[d_eff] = val_s0 - self.regs[s0_eff] = val_d - return d_eff, s0_eff - - def export(self, *indices: int) -> list[int]: - """Read export registers.""" - return [self.regs[i] for i in indices] - - -def run_ps_swaprel(d: int, s0: int, m0: int, export: tuple[int, int, int, int], extra: tuple[str, ...] = ()) -> list[int]: - """Assemble, translate, and execute a fragment shader with v_swaprel_b32.""" - max_reg = max(max(export), d, s0, 30) + 1 - lines = [f"v_mov_b32 v{n}, {sentinel(n):#x}" for n in range(max_reg)] - lines.append(f"s_mov_b32 m0, {m0:#x}") - lines.extend(extra) - lines.append(f"v_swaprel_b32 v{d}, v{s0}") - lines.append(f"exp mrt0 {', '.join(f'v{r}' for r in export)} done vm") - lines.append("s_endpgm") - - spv = translate_lines("ps_swaprel", lines) - out = si.run_fragment(spv) - return list(out["%out_mrt0"]) - - -class TestSwaprelOracleInvariants(unittest.TestCase): - """Mathematical and architectural invariant tests for SwaprelOracle.""" - - def test_oracle_decode_offsets(self) -> None: - self.assertEqual(SwaprelOracle.decode_offsets(0), (0, 0)) - self.assertEqual(SwaprelOracle.decode_offsets(0x0005_0002), (5, 2)) - self.assertEqual(SwaprelOracle.decode_offsets(0x03FF_03FF), (1023, 1023)) - # Verify ignored bits [15:10] and [31:26] - self.assertEqual(SwaprelOracle.decode_offsets(0xFC05_FC02), (5, 2)) - - def test_oracle_self_swap_identity(self) -> None: - oracle = SwaprelOracle() - orig = list(oracle.regs) - # Target same register: d=4 + 3 = 7, s0=6 + 1 = 7 - d_eff, s0_eff = oracle.step(4, 6, 0x0003_0001) - self.assertEqual(d_eff, 7) - self.assertEqual(s0_eff, 7) - self.assertEqual(oracle.regs, orig) - - def test_oracle_involution_double_swap(self) -> None: - oracle = SwaprelOracle() - orig = list(oracle.regs) - oracle.step(2, 8, 0x0004_0003) - self.assertNotEqual(oracle.regs, orig) - oracle.step(2, 8, 0x0004_0003) - self.assertEqual(oracle.regs, orig) - - def test_oracle_unaffected_registers_isolated(self) -> None: - oracle = SwaprelOracle() - val3 = oracle.regs[3] - val11 = oracle.regs[11] - oracle.step(1, 5, 0x0002_0006) # swaps 1+2=3 and 5+6=11 - self.assertEqual(oracle.regs[3], val11) - self.assertEqual(oracle.regs[11], val3) - # All other registers unchanged - for r in range(NUM_VGPRS): - if r not in (3, 11): - self.assertEqual(oracle.regs[r], sentinel(r)) - - def test_oracle_commutativity(self) -> None: - o1 = SwaprelOracle() - o2 = SwaprelOracle() - # Swapping (A, B) vs (B, A) with swapped M0 offsets - o1.step(2, 9, 0x0003_0007) # 2+3=5, 9+7=16 - o2.step(9, 2, 0x0007_0003) # 9+7=16, 2+3=5 - self.assertEqual(o1.regs, o2.regs) - - -class TestSwaprelInterpreterBasic(unittest.TestCase): - """Interpreter value tests for v_swaprel_b32 matching the reference oracle.""" - - def _verify_case(self, d: int, s0: int, m0: int) -> None: - oracle = SwaprelOracle() - d_eff, s0_eff = oracle.step(d, s0, m0) - export = (d_eff, s0_eff, d_eff + 1, s0_eff + 1 if s0_eff + 1 != d_eff else s0_eff - 1) - expected = oracle.export(*export) - actual = run_ps_swaprel(d, s0, m0, export) - self.assertEqual(actual, expected) - - def test_zero_offset_direct_swap(self) -> None: - self._verify_case(1, 2, 0) - self._verify_case(5, 12, 0) - - def test_distinct_offsets(self) -> None: - for d, s0, m0 in ( - (3, 10, 0x0005_0002), - (20, 1, 0x0002_0007), - (5, 5, 0x0001_0000), - (2, 8, 0x000A_0004), - ): - with self.subTest(d=d, s0=s0, m0=hex(m0)): - self._verify_case(d, s0, m0) - - def test_ignored_m0_bits(self) -> None: - # Bits 15:10 and 31:26 set: must produce exact same result as clean M0 - self._verify_case(2, 6, 0xFC03_FC04) - self._verify_case(4, 9, 0xA802_5405) - - def test_self_swap(self) -> None: - # Both addresses point to same VGPR (d=4+3=7, s0=6+1=7) - self._verify_case(4, 6, 0x0003_0001) - - - - -class TestSwaprelChainedSequencesAndPreservation(unittest.TestCase): - """Multi-step chained swap permutations and register state preservation.""" - - def test_involution_two_swaps_restore_identity(self) -> None: - oracle = SwaprelOracle() - orig = list(oracle.regs) - # Swap 3 and 7 twice - oracle.step(1, 2, 0x0002_0005) - self.assertNotEqual(oracle.regs, orig) - oracle.step(1, 2, 0x0002_0005) - self.assertEqual(oracle.regs, orig) - - def test_three_way_cyclic_permutation(self) -> None: - # A=v2, B=v5, C=v8 - oracle = SwaprelOracle() - vA, vB, vC = oracle.regs[2], oracle.regs[5], oracle.regs[8] - # Step 1: swap A and B -> A has vB, B has vA - oracle.step(2, 5, 0) - # Step 2: swap B and C -> B has vC, C has vA - oracle.step(5, 8, 0) - self.assertEqual(oracle.regs[2], vB) - self.assertEqual(oracle.regs[5], vC) - self.assertEqual(oracle.regs[8], vA) - - def test_disjoint_parallel_swaps(self) -> None: - oracle = SwaprelOracle() - oracle.step(1, 2, 0) - oracle.step(3, 4, 0) - oracle.step(5, 6, 0) - self.assertEqual(oracle.regs[1], sentinel(2)) - self.assertEqual(oracle.regs[2], sentinel(1)) - self.assertEqual(oracle.regs[3], sentinel(4)) - self.assertEqual(oracle.regs[4], sentinel(3)) - self.assertEqual(oracle.regs[5], sentinel(6)) - self.assertEqual(oracle.regs[6], sentinel(5)) - - - - -class TestSwaprelNegativeAndEdgeControls(unittest.TestCase): - """Negative controls, syntax rejection, and invalid operand validation.""" - - def test_reject_scalar_destination_operand(self) -> None: - lines = [ - "s_mov_b32 m0, 0", - "v_swaprel_b32 s0, v1", - "s_endpgm", - ] - with self.assertRaises(rdna2spirv.Unsupported): - translate_lines("ps_bad_dest", lines) - - def test_reject_scalar_source_operand(self) -> None: - lines = [ - "s_mov_b32 m0, 0", - "v_swaprel_b32 v1, s0", - "s_endpgm", - ] - with self.assertRaises(rdna2spirv.Unsupported): - translate_lines("ps_bad_src", lines) - - def test_reject_literal_operand(self) -> None: - lines = [ - "s_mov_b32 m0, 0", - "v_swaprel_b32 v1, 1.0", - "s_endpgm", - ] - with self.assertRaises(rdna2spirv.Unsupported): - translate_lines("ps_bad_lit", lines) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_alu_u16_clamp.py b/tests/semantic/test_alu_u16_clamp.py deleted file mode 100644 index 2bc1ddf44..000000000 --- a/tests/semantic/test_alu_u16_clamp.py +++ /dev/null @@ -1,113 +0,0 @@ -"""Semantic interpreter tests for the VOP3 clamp bit on the 16-bit unsigned add/sub (GFX10). - -v_add_nc_u16 / v_sub_nc_u16 (and the v_add_u16_e64 / v_sub_u16_e64 names the translator also takes; v_subrev_u16 is -a GFX9 spelling the translator no longer accepts, #3677): D.u16 = S0.u16 + S1.u16 / S0.u16 - S1.u16, wrapping at 16 bits. With the clamp bit the result saturates to -[0, 0xFFFF], as for the 32-bit ops in test_alu_add_nc_clamp.py (llvm-mc gfx1030 encodes the clamp bit on -these ops, and LLVM selects i16 uaddsat/usubsat to them). The VOP3 form keeps the high half -of the destination. D leaves through exp as two 16-bit halves ORed into 0x40000000. -""" - -import os -import random -import struct -import sys -import tempfile -import unittest -import warnings - -HERE = os.path.dirname(os.path.abspath(__file__)) -ROOT = os.path.dirname(os.path.dirname(HERE)) -TOOLS_DIR = os.environ.get("LEONIDA_TOOLS_DIR") or os.path.join(ROOT, "tools") - -sys.dont_write_bytecode = True -sys.path.insert(0, TOOLS_DIR) -sys.path.insert(0, HERE) - -import rdna2spirv # noqa: E402 -import spirv_mini_interp as si # noqa: E402 - -M32 = 0xFFFFFFFF -STUB_DXBC = b"DXBC" + bytes(24) + struct.pack(" int: - x, y = x & 0xFFFF, y & 0xFFFF - if "subrev" in op: - x, y = y, x - r = x - y if "sub" in op else x + y - if clamp: - r = min(max(r, 0), 0xFFFF) - return (old & 0xFFFF0000) | (r & 0xFFFF) - - -OPS = ["v_add_nc_u16", "v_sub_nc_u16", "v_add_u16_e64", "v_sub_u16_e64"] -VALUES = [0, 1, 2, 0x7FFF, 0x8000, 0xFFFE, 0xFFFF, 0x1234FFFF, 0xABCD0001] -OLD = 0x5A5A0000 - -_TMP_DIR = None -_SRC_PATH = None - - -def setUpModule(): - global _TMP_DIR, _SRC_PATH - _TMP_DIR = tempfile.TemporaryDirectory() - disasm_dir = os.path.join(_TMP_DIR.name, "disasm") - os.mkdir(disasm_dir) - _SRC_PATH = os.path.join(disasm_dir, "ps_u16_clamp.s") - with open(os.path.join(_TMP_DIR.name, "ps_u16_clamp.dxbc"), "wb") as f: - f.write(STUB_DXBC) - - -def tearDownModule(): - global _TMP_DIR - if _TMP_DIR is not None: - _TMP_DIR.cleanup() - _TMP_DIR = None - - -def run_lines(lines) -> int: - """Run the lines, return v0 (exported as two 16-bit halves, see the module docstring).""" - if _TMP_DIR is None: - setUpModule() - lines = list(lines) + ["v_and_b32 v5, 0xffff, v0", "v_lshrrev_b32 v6, 16, v0", - "v_or_b32 v5, 0x40000000, v5", "v_or_b32 v6, 0x40000000, v6"] - asm = "; test_u16_clamp\n" + "".join(f"\t{ln}\n" for ln in lines) + "\texp mrt0 v5, v6, v5, v5 done vm\n\ts_endpgm\n" - with open(_SRC_PATH, "w", encoding="utf-8") as f: - f.write(asm) - with warnings.catch_warnings(): - warnings.simplefilter("ignore", ResourceWarning) - spv = rdna2spirv.translate(_SRC_PATH) - lo, hi = si.run_fragment(spv)["%out_mrt0"][:2] - assert lo >> 16 == 0x4000 and hi >> 16 == 0x4000, (hex(lo), hex(hi)) - return (lo & 0xFFFF) | (hi & 0xFFFF) << 16 - -def run_op(op: str, x: int, y: int, clamp: bool) -> int: - return run_lines([f"v_mov_b32 v1, {x:#x}", f"v_mov_b32 v2, {y:#x}", f"v_mov_b32 v0, {OLD:#x}", - f"{op} v0, v1, v2" + (" clamp" if clamp else "")]) - - -class U16ClampTests(unittest.TestCase): - def test_reference(self): - self.assertEqual(ref("v_add_nc_u16", 0xFFFF, 1, False, 0), 0) - self.assertEqual(ref("v_add_nc_u16", 0xFFFF, 1, True, 0), 0xFFFF) - self.assertEqual(ref("v_sub_nc_u16", 1, 2, True, 0), 0) - - def test_values(self): - for op in OPS: - for clamp in (False, True): - for x in VALUES: - for y in VALUES: - with self.subTest(op=op, clamp=clamp, x=hex(x), y=hex(y)): - self.assertEqual(run_op(op, x, y, clamp), ref(op, x, y, clamp, OLD)) - - def test_seeded(self): - rng = random.Random(0x16C) - for _ in range(40): - op, clamp = rng.choice(OPS), bool(rng.getrandbits(1)) - x, y = rng.getrandbits(32), rng.getrandbits(32) - with self.subTest(op=op, clamp=clamp, x=hex(x), y=hex(y)): - self.assertEqual(run_op(op, x, y, clamp), ref(op, x, y, clamp, OLD)) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_alu_vop3_mods_hw.py b/tests/semantic/test_alu_vop3_mods_hw.py deleted file mode 100644 index 8f680afef..000000000 --- a/tests/semantic/test_alu_vop3_mods_hw.py +++ /dev/null @@ -1,1702 +0,0 @@ -"""Float VALU forms with clamp/omod/op_sel/neg the game's shaders use, against words an RDNA2 GPU returned (no model). - -Every row was run natively on an AMD Radeon RDNA2 iGPU (gfx1036, Ryzen 9 9950X3D, Windows AMD driver 32.0.21045.16010) -through tools/hw_oracle with AMD clang 23 (rocm-sdk-core 10.0.0), in the MODE inferred for the game (IEEE 0, -DX10_CLAMP 1, f32 denormals flushed, f16 denormals kept). v1..v3 hold the operands, v4 starts as 0xDEADBEEF (v_fmac -and v_fma_mixlo/hi start from v3, which they read or partly keep), and the word in v4 after the lines is the expected -one. An SGPR operand is set with s_mov_b32 first; a literal is one of three fixed words. - -The forms are the 542 distinct float VALU forms that carry clamp, an omod, op_sel/op_sel_hi or neg/abs in the -26,503 listings of the 1.0.2.1 package (opcode, operand kinds, inline constants, modifiers), up to 120 random -operand triples each. Only the form is taken from the game; every word here is synthetic. The 1,616 rows are a -sample, up to three per form with distinct results. The measured cases not listed match too, except for differences -already on record: an omod turning a -0 result into +0 (docs/design.md, Output modifiers rows; #1281), f32 denormal -operands or intermediate results (SHADER-377), NaN sign/payload, 1-ulp differences in v_rcp/v_log/v_sin, and cases -whose translation is undefined in SPIR-V (FClamp of a NaN, the root or log of a negative or zero). -""" -import os -import struct -import sys -import tempfile -import unittest -import warnings - -HERE = os.path.dirname(os.path.abspath(__file__)) -ROOT = os.path.dirname(os.path.dirname(HERE)) -sys.dont_write_bytecode = True -sys.path.insert(0, os.environ.get("LEONIDA_TOOLS_DIR") or os.path.join(ROOT, "tools")) -sys.path.insert(0, HERE) - -import rdna2spirv # noqa: E402 -import spirv_mini_interp as si # noqa: E402 - -STUB_DXBC = b"DXBC" + bytes(24) + struct.pack(" SPIR-V -> tests/semantic/spirv_mini_interp.py and compares the result against -a plain-Python reference: ((x ^ y) + z) & 0xFFFFFFFF. - -Covers: - - Basic xor-add: (x ^ y) + z - - z = 0: pure XOR - - x = y: XOR cancels, result = z - - x = 0: result = y + z - - 32-bit wraparound on overflow - - Reference comparison across varied bit patterns - - Negative control: result differs from each input for non-trivial cases -""" -import os -import struct -import sys -import tempfile -import unittest -import warnings -import random - -HERE = os.path.dirname(os.path.abspath(__file__)) -ROOT = os.path.dirname(os.path.dirname(HERE)) -TOOLS_DIR = os.environ.get("LEONIDA_TOOLS_DIR") or os.path.join(ROOT, "tools") - -sys.dont_write_bytecode = True -if TOOLS_DIR not in sys.path: - sys.path.insert(0, TOOLS_DIR) -if HERE not in sys.path: - sys.path.insert(0, HERE) - -import rdna2spirv # noqa: E402 -import spirv_mini_interp as si # noqa: E402 - -M32 = 0xFFFFFFFF -STUB_DXBC = b"DXBC" + bytes(24) + struct.pack(" int: - """Plain-Python reference for v_xad_u32: ((x ^ y) + z) mod 2^32.""" - return ((x ^ y) + z) & M32 - - -_TMP_DIR = None -_SRC_PATH = None - - -def setUpModule(): - global _TMP_DIR, _SRC_PATH - _TMP_DIR = tempfile.TemporaryDirectory() - disasm_dir = os.path.join(_TMP_DIR.name, "disasm") - os.mkdir(disasm_dir) - _SRC_PATH = os.path.join(disasm_dir, "ps_xad_u32.s") - with open(os.path.join(_TMP_DIR.name, "ps_xad_u32.dxbc"), "wb") as f: - f.write(STUB_DXBC) - - -def tearDownModule(): - global _TMP_DIR - if _TMP_DIR is not None: - _TMP_DIR.cleanup() - _TMP_DIR = None - - -def run_op(x: int, y: int, z: int) -> int: - """Translate and run a shader that computes v_xad_u32 v1, v2, v3, v4 with v2=x, v3=y, v4=z.""" - asm = ( - "; test_xad_u32\n" - f"\tv_mov_b32_e32 v2, {x & M32:#x}\n" - f"\tv_mov_b32_e32 v3, {y & M32:#x}\n" - f"\tv_mov_b32_e32 v4, {z & M32:#x}\n" - "\tv_xad_u32 v1, v2, v3, v4\n" - "\ts_waitcnt vmcnt(0)\n" - "\texp mrt0 v1, v1, v1, v1 done vm\n" - "\ts_endpgm\n" - ) - with open(_SRC_PATH, "w", encoding="utf-8") as f: - f.write(asm) - with warnings.catch_warnings(): - warnings.simplefilter("ignore", ResourceWarning) - spv = rdna2spirv.translate(_SRC_PATH) - w = si.run_fragment(spv)["%out_mrt0"] - return w[0] & M32 - - -class ALUVXadU32Tests(unittest.TestCase): - def test_xad_u32_basic(self): - # (5 ^ 3) + 2 = 6 + 2 = 8 - self.assertEqual(run_op(5, 3, 2), 8) - # z = 0: pure XOR - self.assertEqual(run_op(0x12345678, 0x87654321, 0), 0x95511559) - # x = y: XOR cancels, result = z - self.assertEqual(run_op(0xDEADBEEF, 0xDEADBEEF, 0x12345678), 0x12345678) - # x = 0: result = y + z - self.assertEqual(run_op(0, 0x1000, 0x2000), 0x3000) - - def test_xad_u32_wraparound(self): - # 32-bit overflow wraps - self.assertEqual(run_op(0, 0, M32 + 1 & M32), 0) # z = 0 (M32+1 masked to 0) - self.assertEqual(run_op(0, 0, M32), M32) - self.assertEqual(run_op(0, 0, 1), 1) - # (0xFFFFFFFF ^ 0) + 1 = M32 + 1 wraps to 0 - self.assertEqual(run_op(0, M32, 1), 0) - - def test_xad_u32_reference(self): - cases = [ - (0x00000000, 0x00000000, 0x00000000, 0x00000000), - (0xFFFFFFFF, 0xFFFFFFFF, 0x00000000, 0x00000000), # x==y -> 0 + z - (0xFFFFFFFF, 0x00000000, 0x00000001, 0x00000000), # M32 + 1 wraps to 0 - (0x12345678, 0x87654321, 0x00000000, 0x95511559), - (0xAAAAAAAA, 0x55555555, 0x00000000, 0xFFFFFFFF), - (0xAAAAAAAA, 0x55555555, 0x00000001, 0x00000000), # 0xFFFFFFFF + 1 wraps - (0x0F0F0F0F, 0xF0F0F0F0, 0x12345678, 0x12345677), # x^y = M32, +z wraps to z-1 - ] - for x, y, z, expected in cases: - with self.subTest(x=hex(x), y=hex(y), z=hex(z)): - self.assertEqual(run_op(x, y, z), expected) - self.assertEqual(run_op(x, y, z), ref_xad32(x, y, z)) - - def test_xad_u32_random_vs_reference(self): - rng = random.Random(0xC0FFEE) - for _ in range(50): - x = rng.getrandbits(32) - y = rng.getrandbits(32) - z = rng.getrandbits(32) - with self.subTest(x=hex(x), y=hex(y), z=hex(z)): - self.assertEqual(run_op(x, y, z), ref_xad32(x, y, z)) - - def test_xad_u32_negative_control(self): - # For non-trivial inputs, result differs from each input. - x, y, z = 0x12345678, 0x9ABCDEF0, 0x01234567 - res = run_op(x, y, z) - expected = ref_xad32(x, y, z) - self.assertEqual(res, expected) - self.assertNotEqual(res, x) - self.assertNotEqual(res, y) - self.assertNotEqual(res, z) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_alu_xnor_b32.py b/tests/semantic/test_alu_xnor_b32.py deleted file mode 100644 index 64bc46f14..000000000 --- a/tests/semantic/test_alu_xnor_b32.py +++ /dev/null @@ -1,129 +0,0 @@ -"""Semantic translation tests for RDNA2 32-bit bitwise XNOR v_xnor_b32. - -Translates a synthetic pixel-shader listing through tools/rdna2spirv.translate() --> SPIR-V -> tests/semantic/spirv_mini_interp.py and compares the result against -a plain-Python reference: ~(x ^ y) & 0xFFFFFFFF. - -Covers: - - Basic XNOR: all-zeros/all-ones, complementary inputs - - Identical inputs -> all-ones - - Reference comparison across varied bit patterns - - Negative control: result differs from both inputs for non-trivial cases -""" -import os -import struct -import sys -import tempfile -import unittest -import warnings -import random - -HERE = os.path.dirname(os.path.abspath(__file__)) -ROOT = os.path.dirname(os.path.dirname(HERE)) -TOOLS_DIR = os.environ.get("LEONIDA_TOOLS_DIR") or os.path.join(ROOT, "tools") - -sys.dont_write_bytecode = True -if TOOLS_DIR not in sys.path: - sys.path.insert(0, TOOLS_DIR) -if HERE not in sys.path: - sys.path.insert(0, HERE) - -import rdna2spirv # noqa: E402 -import spirv_mini_interp as si # noqa: E402 - -M32 = 0xFFFFFFFF -STUB_DXBC = b"DXBC" + bytes(24) + struct.pack(" int: - """Plain-Python reference for v_xnor_b32: bitwise NOT of XOR, masked to 32 bits.""" - return (~(x ^ y)) & M32 - - -_TMP_DIR = None -_SRC_PATH = None - - -def setUpModule(): - global _TMP_DIR, _SRC_PATH - _TMP_DIR = tempfile.TemporaryDirectory() - disasm_dir = os.path.join(_TMP_DIR.name, "disasm") - os.mkdir(disasm_dir) - _SRC_PATH = os.path.join(disasm_dir, "ps_xnor_b32.s") - with open(os.path.join(_TMP_DIR.name, "ps_xnor_b32.dxbc"), "wb") as f: - f.write(STUB_DXBC) - - -def tearDownModule(): - global _TMP_DIR - if _TMP_DIR is not None: - _TMP_DIR.cleanup() - _TMP_DIR = None - - -def run_op(x: int, y: int) -> int: - """Translate and run a shader that computes v_xnor_b32 v1, v2, v3 with v2=x, v3=y.""" - asm = ( - "; test_xnor_b32\n" - f"\tv_mov_b32_e32 v2, {x & M32:#x}\n" - f"\tv_mov_b32_e32 v3, {y & M32:#x}\n" - "\tv_xnor_b32 v1, v2, v3\n" - "\ts_waitcnt vmcnt(0)\n" - "\texp mrt0 v1, v1, v1, v1 done vm\n" - "\ts_endpgm\n" - ) - with open(_SRC_PATH, "w", encoding="utf-8") as f: - f.write(asm) - with warnings.catch_warnings(): - warnings.simplefilter("ignore", ResourceWarning) - spv = rdna2spirv.translate(_SRC_PATH) - w = si.run_fragment(spv)["%out_mrt0"] - return w[0] & M32 - - -class ALUVXnorB32Tests(unittest.TestCase): - def test_xnor_b32_basic(self): - # ~(0 ^ 0) = ~0 = 0xFFFFFFFF - self.assertEqual(run_op(0, 0), M32) - # ~(0xFFFFFFFF ^ 0xFFFFFFFF) = ~0 = 0xFFFFFFFF - self.assertEqual(run_op(M32, M32), M32) - # ~(0 ^ 0xFFFFFFFF) = ~0xFFFFFFFF = 0 - self.assertEqual(run_op(0, M32), 0) - # ~(0xFFFFFFFF ^ 0) = ~0xFFFFFFFF = 0 - self.assertEqual(run_op(M32, 0), 0) - - def test_xnor_b32_reference(self): - cases = [ - (0x12345678, 0x12345678, M32), # x ^ x = 0 -> ~0 = all ones - (0x12345678, 0x87654321, 0x6AAEEAA6), # ~(0x95511559) - (0x00000001, 0x00000001, M32), - (0x00000001, 0x00000000, 0xFFFFFFFE), # ~(1 ^ 0) = ~1 = 0xFFFFFFFE - (0xAAAAAAAA, 0x55555555, 0), # ~(0xFFFFFFFF) = 0 - (0xAAAAAAAA, 0xAAAAAAAA, M32), - (0x0F0F0F0F, 0xF0F0F0F0, 0), # ~(0xFFFFFFFF) = 0 - ] - for x, y, expected in cases: - with self.subTest(x=hex(x), y=hex(y)): - self.assertEqual(run_op(x, y), expected) - self.assertEqual(run_op(x, y), ref_xnor32(x, y)) - - def test_xnor_b32_random_vs_reference(self): - rng = random.Random(0xC0FFEE) - for _ in range(50): - x = rng.getrandbits(32) - y = rng.getrandbits(32) - with self.subTest(x=hex(x), y=hex(y)): - self.assertEqual(run_op(x, y), ref_xnor32(x, y)) - - def test_xnor_b32_negative_control(self): - # For non-trivial inputs, result differs from both inputs. - x, y = 0x12345678, 0x9ABCDEF0 - res = run_op(x, y) - expected = ref_xnor32(x, y) - self.assertEqual(res, expected) - self.assertNotEqual(res, x) - self.assertNotEqual(res, y) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_andn2_exec_b64.py b/tests/semantic/test_andn2_exec_b64.py deleted file mode 100644 index 2a68edd7d..000000000 --- a/tests/semantic/test_andn2_exec_b64.py +++ /dev/null @@ -1,124 +0,0 @@ -"""s_andn2_saveexec_b64 and s_andn2_wrexec_b64 on a 64-lane wave, run across every lane of the translated SPIR-V. - -RDNA2 ISA: - s_andn2_saveexec_b64 D = EXEC; EXEC = S0 & ~EXEC; SCC = (EXEC != 0). - s_andn2_wrexec_b64 EXEC = S0 & ~EXEC; D = EXEC (the new one); SCC = (EXEC != 0). - -Programs are written here (no game data) and translated by tools/rdna2spirv.py; spirv_mini_interp.run_workgroup runs -one workgroup of 64 lanes on a 64-wide subgroup. S0 is a compare result in VCC, EXEC a constant in each half. Every -lane stores whether it is on in the new EXEC, and lane 0 stores SCC and the population count and lowest lane of D, -so the three results are each checked over both halves of the wave. The expected values come from the two lines of -the ISA above, written as integers in `model`, not from the translator. - -The GPU test is runtime/test/shaders/cs_w64x_andn2_exec.asm; its fixture also runs here. The --wave64-emulate output -needs Workgroup memory, which the interpreter rejects, so it is covered by the GPU test only (as in -test_ds_permute.py). The _b32 forms are tested with cs_w32_andn2_exec. -""" -import struct -import unittest - -import support -import spirv_mini_interp as si - -VSHARP = [0, 0, 0x1000, 0x31016FAC] -ALL64 = (1 << 64) - 1 -EXPECTED_FIXTURE = [1, 16, 32, 4144, 2052, 3, 8, 1544] # derivation in cs_w64x_andn2_exec.asm -SCC_AT, BCNT_AT, FF1_AT = 256, 260, 264 # bytes in out[], after the 64 lane words - -# (multiplier, addend, and-mask, EXEC): S0 = the lanes l with ((l * multiplier + addend) & and-mask) == 0. -CASES = ( - (1, 0, 8, 0x0000FFFFFFFF0000), # S0 in both halves, EXEC across the middle - (1, 0, 32, 0x0000FFFFFFFF0000), # S0 = the low half: the result is lanes 0..15 only - (1, 32, 32, 0x0000FFFFFFFF0000), # S0 = the high half: the result is lanes 48..63 only - (3, 1, 5, 0x5555555555555555), - (7, 2, 12, 0xF0F0F0F00F0F0F0F), - (1, 0, 0, 0), # S0 = every lane, EXEC = 0: every lane on, D = 0 for saveexec - (1, 0, 0, ALL64), # S0 = every lane, EXEC = every lane: nothing left, SCC 0 - (1, 1, 1, 0xFFFFFFFF00000000), # odd lanes, EXEC = the high half: odd lanes of the low half - (1, 0, 1, 0x00000000FFFFFFFF), # even lanes, EXEC = the low half: even lanes of the high half - (5, 3, 63, 0x8000000000000001), # a single lane in S0 - (1, 0, 64, 0x123456789ABCDEF0), # S0 = every lane (bit 6 is never set): EXEC is inverted - (1, 0, 127, 0xFFFFFFFFFFFFFFFE), # S0 = lane 0, the only lane off in EXEC -) - - -def fssm(threads): - h = bytearray(0x148) - struct.pack_into("<4I", h, 0x138, 0x8088, threads, 1, 1) - return bytes(h) - - -def s0_mask(mul, add, mask): - return sum(1 << lane for lane in range(64) if ((lane * mul + add) & mask) == 0) - - -def model(op, s0, old_exec): - """(new EXEC, D, SCC) from the ISA's definition.""" - new_exec = s0 & ~old_exec & ALL64 - return new_exec, (old_exec if op == "s_andn2_saveexec_b64" else new_exec), int(new_exec != 0) - - -def program(op, mul, add, mask, old_exec): - def store(reg, at): - return [f"v_mov_b32_e32 v20, {reg}", f"v_mov_b32_e32 v21, {at}", "buffer_store_dword v20, v21, s[0:3], 0 offen"] - - return (["v_mbcnt_lo_u32_b32 v1, -1, 0", "v_mbcnt_hi_u32_b32 v1, -1, v1", "v_mov_b32_e32 v2, 0", - f"v_mad_u32_u24 v3, v1, {mul}, {add}", f"v_and_b32_e32 v3, {mask}, v3", "v_cmp_eq_u32_e32 vcc, 0, v3", - f"s_mov_b32 exec_lo, {old_exec & 0xFFFFFFFF:#x}", f"s_mov_b32 exec_hi, {old_exec >> 32:#x}", - f"{op} s[6:7], vcc", "s_cselect_b32 s8, 1, 0", - "v_mov_b32_e32 v2, 1", # only the lanes the instruction left on - "s_mov_b64 exec, -1", - "s_bcnt1_i32_b64 s9, s[6:7]", "s_ff1_i32_b64 s10, s[6:7]", - "v_lshlrev_b32_e32 v21, 2, v1", "buffer_store_dword v2, v21, s[0:3], 0 offen", - "v_cmpx_eq_u32_e32 0, v1"] - + store("s8", SCC_AT) + store("s9", BCNT_AT) + store("s10", FF1_AT) + ["s_endpgm"]) - - -def run(spv, subgroup=64): - return si.run_workgroup( - spv, 64, subgroup, inputs_for=lambda i: {"%wg_id": (0, 0, 0), "%local_id": (i, 0, 0), "%sg_lane": i % subgroup}, - push_constants=VSHARP + [0] * 28, memory={}) - - -class Andn2ExecB64(unittest.TestCase): - def test_model_examples(self): - # The two lines of the ISA on the masks of cs_w64x_andn2_exec.asm, by hand. - lanes = lambda lo, hi: sum(1 << l for l in range(lo, hi)) - self.assertEqual(model("s_andn2_saveexec_b64", lanes(40, 64), lanes(16, 48)), (lanes(48, 64), lanes(16, 48), 1)) - self.assertEqual(model("s_andn2_wrexec_b64", 0x00FF00FF00FF00FF, 0xFFFFFFFF0F0F0F0F), - (0x00F000F0, 0x00F000F0, 1)) - self.assertEqual(model("s_andn2_wrexec_b64", lanes(0, 8), ALL64), (0, 0, 0)) - - def test_every_lane(self): - for op in ("s_andn2_saveexec_b64", "s_andn2_wrexec_b64"): - for mul, add, mask, old_exec in CASES: - with self.subTest(op=op, s0=(mul, add, mask), exec=hex(old_exec)): - s0 = s0_mask(mul, add, mask) - new_exec, d, scc = model(op, s0, old_exec) - spv = support.translate_lines("cs_andn2_b64", program(op, mul, add, mask, old_exec), fssm=fssm(64)) - memory = run(spv) - got_exec = sum(memory[4 * lane] << lane for lane in range(64)) - self.assertEqual(got_exec, new_exec, f"EXEC {got_exec:#018x}, ISA {new_exec:#018x}") - self.assertEqual(memory[SCC_AT], scc, "SCC") - self.assertEqual(memory[BCNT_AT], bin(d).count("1"), "population count of D") - lowest = (d & -d).bit_length() - 1 if d else 0xFFFFFFFF # s_ff1 of 0 is -1 - self.assertEqual(memory[FF1_AT], lowest, "lowest lane of D") - - def test_cases_cover_both_halves(self): - # The table has results in the low half only, in the high half only, in both and in neither. - seen = set() - for mul, add, mask, old_exec in CASES: - new_exec = model("s_andn2_wrexec_b64", s0_mask(mul, add, mask), old_exec)[0] - seen.add((bool(new_exec & 0xFFFFFFFF), bool(new_exec >> 32))) - self.assertEqual(seen, {(False, False), (True, False), (False, True), (True, True)}) - - def test_gpu_test_fixture(self): - """cs_w64x_andn2_exec.asm: the words check.py expects (lane 0 stores them).""" - spv = support.translate_fixture("cs_w64x_andn2_exec", fssm=fssm(64)) - memory = run(spv) - self.assertEqual(sorted(memory), list(range(0, 32, 4)), "lane 0 stores out[0..7] only") - self.assertEqual([memory[4 * k] for k in range(8)], EXPECTED_FIXTURE) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_atomic_csub.py b/tests/semantic/test_atomic_csub.py deleted file mode 100644 index e8b9901e0..000000000 --- a/tests/semantic/test_atomic_csub.py +++ /dev/null @@ -1,90 +0,0 @@ -"""global_atomic_csub / buffer_atomic_csub (GFX10.3), run through spirv_mini_interp on the CPU. - -RDNA2 ISA: tmp = M; M = (DATA > tmp) ? 0 : tmp - DATA (unsigned: a subtract clamped at 0, never wrapping); with glc -the old M comes back. The translator emits the OpAtomicCompareExchange loop of the inc / dec atomics -(Gen.atomic_inc_dec_cas). The 32-lane case contends on one dword and must equal 32 sequential -subtracts. Vonsek measured the formula on gfx1036 (#3193: 162/162 memory/data pairs, both forms). Standard library -only; no GPU, no game files. -""" -import os -import random -import sys -import unittest - -HERE = os.path.dirname(os.path.abspath(__file__)) -sys.dont_write_bytecode = True -sys.path.insert(0, HERE) - -from test_global_atomics import OUT, TARGET, run, si, translate # noqa: E402 (also puts tools/ on sys.path) - -M32 = 0xFFFFFFFF - - -def global_op(kind, m, d, glc=True): - body = [f"v_mov_b32_e32 v1, {TARGET:#x}", f"v_mov_b32_e32 v2, {d:#x}", "v_mov_b32_e32 v5, 0xdead"] - body.append(f"global_atomic_{kind} v5, v1, v2, s[0:1] glc" if glc else f"global_atomic_{kind} v1, v2, s[0:1]") - body += ["s_waitcnt vmcnt(0)", f"v_mov_b32_e32 v6, {OUT:#x}", "global_store_dword v6, v5, s[0:1]"] - mem = run(body, {TARGET: m}) - return mem.get(OUT), mem.get(TARGET) - - -def buffer_op(kind, m, d, offset=0x40, records=0x80): - body = ["s_mov_b32 s8, 0x100", "s_mov_b32 s9, 0", f"s_mov_b32 s10, {records:#x}", "s_mov_b32 s11, 0x31016fac", - f"v_mov_b32_e32 v1, {offset:#x}", f"v_mov_b32_e32 v2, {d:#x}", - f"buffer_atomic_{kind} v2, v1, s[8:11], 0 offen glc", "s_waitcnt vmcnt(0)", - f"v_mov_b32_e32 v6, {OUT:#x}", "global_store_dword v6, v2, s[0:1]"] - mem = run(body, {0x100 + offset: m}) - return mem.get(OUT), mem.get(0x100 + offset) - - -def csub(m, d): - return 0 if d > m else m - d - - -VALUES = [0, 1, 2, 5, 6, 0x7FFFFFFF, 0x80000000, M32 - 1, M32] - - -class AtomicCsub(unittest.TestCase): - def test_reference(self): - self.assertEqual([csub(m, 5) for m in (0, 4, 5, 6, M32)], [0, 0, 0, 1, M32 - 5]) - - def test_global_values(self): - for m in VALUES: - for d in VALUES: - with self.subTest(m=hex(m), d=hex(d)): - self.assertEqual(global_op("csub", m, d), (m, csub(m, d))) - - def test_global_without_glc_keeps_vdst(self): - self.assertEqual(global_op("csub", 3, 5, glc=False), (0xDEAD, 0)) - self.assertEqual(global_op("csub", 9, 5, glc=False), (0xDEAD, 4)) - - def test_buffer_values_and_bounds(self): - for m, d in ((0, 5), (5, 5), (9, 5), (0x80000000, M32)): - with self.subTest(m=hex(m), d=hex(d)): - self.assertEqual(buffer_op("csub", m, d), (m, csub(m, d))) - self.assertEqual(buffer_op("csub", 9, 5, offset=0x80), (0, 9)) # out of range: untouched, glc 0 - - def test_32_lanes_on_one_dword(self): - for m, d in ((100, 3), (50, 3), (0, 1), (M32, 0x10000000)): - with self.subTest(m=m, d=d): - spv = translate([f"v_mov_b32_e32 v1, {TARGET:#x}", f"v_mov_b32_e32 v2, {d:#x}", - "global_atomic_csub v1, v2, s[0:1]"]) - mem = {TARGET: m} - si.run_workgroup(spv, 32, 32, inputs_for=lambda i: {"%wg_id": (0, 0, 0), "%local_id": (i, 0, 0), - "%sg_lane": i}, - push_constants=[0] * 36, memory=mem) - want = m - for _ in range(32): - want = csub(want, d) - self.assertEqual(mem[TARGET], want) - - def test_seeded(self): - rng = random.Random(0xC5B) - for _ in range(20): - m, d = rng.getrandbits(32), rng.choice((rng.getrandbits(32), rng.getrandbits(8))) - with self.subTest(m=hex(m), d=hex(d)): - self.assertEqual(global_op("csub", m, d), (m, csub(m, d))) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_atomic_inc_dec.py b/tests/semantic/test_atomic_inc_dec.py deleted file mode 100644 index 2ff71fb0d..000000000 --- a/tests/semantic/test_atomic_inc_dec.py +++ /dev/null @@ -1,252 +0,0 @@ -"""Value tests for RDNA2 32-bit global_atomic_{inc,dec} and buffer_atomic_{inc,dec} via spirv_mini_interp. - -RDNA2 ISA (FLAT/GLOBAL and MUBUF): - inc: old = M; M = (old >= DATA) ? 0 : old + 1 (unsigned compare) - dec: old = M; M = (old == 0 || old > DATA) ? DATA : old - 1 (unsigned compare) -With `glc`, the pre-op value `old` is returned (in `vdst` for global_atomic_*, in `vdata` for buffer_atomic_*); -without `glc`, the destination/data register is preserved. Inactive lanes never touch memory; out-of-bounds MUBUF -lanes leave memory untouched and return 0 when `glc` is set. Both lower to a structured OpAtomicCompareExchange CAS -loop so no extra SPIR-V capability is required. Standard library only; no GPU, no LLVM, no game files. -""" -import os -import random -import struct -import sys -import tempfile -import unittest -import warnings - -HERE = os.path.dirname(os.path.abspath(__file__)) -ROOT = os.path.dirname(os.path.dirname(HERE)) -sys.dont_write_bytecode = True -sys.path.insert(0, os.environ.get("LEONIDA_TOOLS_DIR") or os.path.join(ROOT, "tools")) -sys.path.insert(0, HERE) - -import rdna2spirv # noqa: E402 -import spirv_mini_interp as si # noqa: E402 -from shader_ir import parse_line as parse # noqa: E402 - -M32 = 0xFFFFFFFF -STUB_DXBC = b"DXBC" + bytes(24) + struct.pack("= d else (m + 1) & M32 - - -def model_dec(m, d): - return d if (m == 0 or m > d) else (m - 1) & M32 - - -MODELS = {"inc": model_inc, "dec": model_dec} - - -def translate(body): - with tempfile.TemporaryDirectory() as tmp: - for d in ("disasm", "fssm"): - os.mkdir(os.path.join(tmp, d)) - with open(os.path.join(tmp, "cs_incdec.dxbc"), "wb") as f: - f.write(STUB_DXBC) - with open(os.path.join(tmp, "fssm", "cs_incdec.fssm"), "wb") as f: - f.write(FSSM) - src = os.path.join(tmp, "disasm", "cs_incdec.s") - with open(src, "w", encoding="utf-8") as f: - f.write("; cs_incdec\n" + "".join(f"\t{ln}\n" for ln in body) + "\ts_endpgm\n") - with warnings.catch_warnings(): - warnings.simplefilter("ignore", ResourceWarning) - return rdna2spirv.translate(src) - - -def run(body, memory, nlanes=1): - spv = translate(body) - mem = dict(memory) - si.run_workgroup(spv, nlanes, 32, - inputs_for=lambda i: {"%wg_id": (0, 0, 0), "%local_id": (i, 0, 0), "%sg_lane": i}, - push_constants=[0] * 36, memory=mem) - return mem - - -def run_global(kind, m, d, glc=True, offset=0, vaddr=TARGET): - body = [f"v_mov_b32_e32 v1, {vaddr - offset:#x}", f"v_mov_b32_e32 v2, {d:#x}", "v_mov_b32_e32 v5, 0xdead"] - off = f" offset:{offset}" if offset else "" - body.append(f"global_atomic_{kind} v5, v1, v2, s[0:1]{off} glc" if glc else - f"global_atomic_{kind} v1, v2, s[0:1]{off}") - body += ["s_waitcnt vmcnt(0)", f"v_mov_b32_e32 v6, {OUT:#x}", "global_store_dword v6, v5, s[0:1]"] - mem = run(body, {TARGET: m}) - return mem.get(OUT), mem.get(TARGET) - - -def run_buffer(kind, m, d, glc=True, offset=ELEM, records=RECORDS): - body = [ - "s_mov_b32 s8, 0", "s_mov_b32 s9, 0", f"s_mov_b32 s10, {records:#x}", "s_mov_b32 s11, 0x31016fac", - f"v_mov_b32_e32 v1, {offset:#x}", f"v_mov_b32_e32 v2, {d:#x}", - f"buffer_atomic_{kind} v2, v1, s[8:11], 0 offen" + (" glc" if glc else ""), - "s_waitcnt vmcnt(0)", - f"v_mov_b32_e32 v4, {BOUT:#x}", "s_mov_b32 s10, 0x1000", "buffer_store_dword v2, v4, s[8:11], 0 offen", - ] - mem = run(body, {offset: m}) - return mem.get(BOUT), mem.get(offset) - - -class CasLoop(unittest.TestCase): - def test_initial_read_is_atomic_at_the_exchange_scope(self): - for kind in ("inc", "dec"): - for instruction in (f"global_atomic_{kind} v5, v1, v2, s[0:1] glc", - f"buffer_atomic_{kind} v2, v1, s[8:11], 0 offen glc"): - with self.subTest(instruction=instruction): - lines = translate([instruction]).splitlines() - exchange, = (line.split("OpAtomicCompareExchange ")[1].split() - for line in lines if "OpAtomicCompareExchange " in line) - loads = [line.split("OpAtomicLoad ")[1].split() for line in lines if "OpAtomicLoad " in line] - self.assertEqual(loads, [exchange[:4]]) # type, pointer, scope, memory semantics - - -class GlobalAtomicIncDec(unittest.TestCase): - def test_edge_grid_returning_and_non_returning(self): - for kind, fn in MODELS.items(): - for m in VALUES: - for d in VALUES[::2]: - with self.subTest(op=kind, m=hex(m), d=hex(d)): - self.assertEqual(run_global(kind, m, d, glc=True), (m, fn(m, d))) - self.assertEqual(run_global(kind, m, d, glc=False), (0xDEAD, fn(m, d))) - - def test_seeded_values(self): - rng = random.Random(0x1CED) - for _ in range(24): - kind = rng.choice(("inc", "dec")) - m, d = rng.getrandbits(32), rng.getrandbits(32) - with self.subTest(op=kind, m=hex(m), d=hex(d)): - self.assertEqual(run_global(kind, m, d), (m, MODELS[kind](m, d))) - - def test_signed_offsets_and_off_addressing(self): - for offset in (-2048, -4, 4, 2044): - with self.subTest(offset=offset): - self.assertEqual(run_global("inc", 2, 5, offset=offset), (2, 3)) - self.assertEqual(run_global("dec", 0, 5, offset=offset), (0, 5)) - body = [ - f"v_mov_b32_e32 v8, {TARGET:#x}", "v_mov_b32_e32 v9, 0", - "v_mov_b32_e32 v2, 3", "v_mov_b32_e32 v5, 0xdead", - "global_atomic_inc v5, v[8:9], v2, off glc", - "s_waitcnt vmcnt(0)", - f"v_mov_b32_e32 v6, {OUT:#x}", "global_store_dword v6, v5, s[0:1]", - ] - mem = run(body, {TARGET: 3}) - self.assertEqual((mem.get(OUT), mem.get(TARGET)), (3, 0)) - - def test_inactive_lane_leaves_memory_and_vdst_alone(self): - for kind, init, bound, want in (("inc", 3, 3, 0), ("dec", 0, 7, 7)): - with self.subTest(op=kind): - body = [ - f"v_mov_b32_e32 v1, {TARGET:#x}", - f"v_mov_b32_e32 v2, {bound:#x}", "v_mov_b32_e32 v5, 0xdead", - "v_cmp_eq_u32_e32 vcc_lo, 0, v0", - "s_and_saveexec_b32 s4, vcc_lo", - f"global_atomic_{kind} v5, v1, v2, s[0:1] glc", - "s_mov_b32 exec_lo, s4", - "s_waitcnt vmcnt(0)", - "v_lshlrev_b32_e32 v6, 2, v0", - f"v_add_nc_u32_e32 v6, {OUT:#x}, v6", - "global_store_dword v6, v5, s[0:1]", - ] - mem = run(body, {TARGET: init}, nlanes=2) - self.assertEqual(mem.get(TARGET), want) - self.assertEqual(mem.get(OUT), init) - self.assertEqual(mem.get(OUT + 4), 0xDEAD) - - def test_multi_lane_cas_contention_wrapping(self): - # 4 active lanes increment modulo 3 (DATA = 2) starting at 0 -> states 0 -> 1 -> 2 -> 0 -> 1. - body_inc = [ - f"v_mov_b32_e32 v1, {TARGET:#x}", "v_mov_b32_e32 v2, 2", - "global_atomic_inc v5, v1, v2, s[0:1] glc", - "s_waitcnt vmcnt(0)", - "v_lshlrev_b32_e32 v6, 2, v0", - f"v_add_nc_u32_e32 v6, {OUT:#x}, v6", - "global_store_dword v6, v5, s[0:1]", - ] - mem = run(body_inc, {TARGET: 0}, nlanes=4) - self.assertEqual(mem.get(TARGET), 1) - self.assertEqual(sorted(mem.get(OUT + 4 * i) for i in range(4)), [0, 0, 1, 2]) - - # 4 active lanes decrement modulo 3 (DATA = 2) starting at 1 -> states 1 -> 0 -> 2 -> 1 -> 0. - body_dec = [ln.replace("global_atomic_inc", "global_atomic_dec") for ln in body_inc] - mem = run(body_dec, {TARGET: 1}, nlanes=4) - self.assertEqual(mem.get(TARGET), 0) - self.assertEqual(sorted(mem.get(OUT + 4 * i) for i in range(4)), [0, 1, 1, 2]) - - def test_first_read_analysis_and_rejected_forms(self): - for kind in ("inc", "dec"): - self.assertEqual(rdna2spirv.read_before_write_vgprs([parse(f"\tglobal_atomic_{kind} v1, v2, s[0:1]")]), - {1, 2}) - self.assertEqual( - rdna2spirv.read_before_write_vgprs([parse(f"\tglobal_atomic_{kind} v5, v1, v2, s[0:1] glc")]), - {1, 2}, - ) - for line in ( - "global_atomic_inc_x2 v[4:5], v1, v[2:3], s[0:1] glc", - "global_atomic_dec_x2 v[4:5], v1, v[2:3], s[0:1] glc", - "global_atomic_inc v5, v1, v2, s[0:1] glc slc", - "global_atomic_dec v5, v1, v2, s[0:1] glc dlc", - "global_atomic_inc v1, v2, s[0:1] glc", - ): - with self.subTest(line=line): - with self.assertRaises(rdna2spirv.Unsupported): - translate(["v_mov_b32_e32 v1, 0", line]) - - -class BufferAtomicIncDec(unittest.TestCase): - def test_edge_grid_returning_and_non_returning(self): - for kind, fn in MODELS.items(): - for m in VALUES: - for d in VALUES[::2]: - with self.subTest(op=kind, m=hex(m), d=hex(d)): - self.assertEqual(run_buffer(kind, m, d, glc=True), (m, fn(m, d))) - self.assertEqual(run_buffer(kind, m, d, glc=False), (d, fn(m, d))) - - def test_bounds_and_oob_behavior(self): - for kind, init, bound, want in (("inc", 5, 5, 0), ("dec", 0, 5, 5)): - with self.subTest(op=kind): - # Last in-bounds dword (ends exactly at RECORDS). - self.assertEqual(run_buffer(kind, init, bound, offset=RECORDS - 4), (init, want)) - # Out-of-bounds: memory untouched, glc returns 0, non-glc preserves vdata. - self.assertEqual(run_buffer(kind, init, bound, glc=True, offset=RECORDS), (0, init)) - self.assertEqual(run_buffer(kind, init, bound, glc=False, offset=RECORDS), (bound, init)) - - def test_multi_lane_cas_contention_and_inactive_lane(self): - body = [ - "s_mov_b32 s8, 0", "s_mov_b32 s9, 0", f"s_mov_b32 s10, {RECORDS:#x}", "s_mov_b32 s11, 0x31016fac", - f"v_mov_b32_e32 v1, {ELEM:#x}", "v_mov_b32_e32 v2, 2", - "v_cmp_lt_u32_e32 vcc_lo, v0, 3", - "s_and_saveexec_b32 s4, vcc_lo", - "buffer_atomic_inc v2, v1, s[8:11], 0 offen glc", - "s_mov_b32 exec_lo, s4", - "s_waitcnt vmcnt(0)", - "v_lshlrev_b32_e32 v4, 2, v0", - f"v_add_nc_u32_e32 v4, {BOUT:#x}, v4", - "s_mov_b32 s10, 0x1000", "buffer_store_dword v2, v4, s[8:11], 0 offen", - ] - # 3 active lanes increment from 0 with DATA=2 -> 0->1->2->0; lane 3 is inactive and keeps v2=2. - mem = run(body, {ELEM: 0}, nlanes=4) - self.assertEqual(mem.get(ELEM), 0) - self.assertEqual(sorted(mem.get(BOUT + 4 * i) for i in range(3)), [0, 1, 2]) - self.assertEqual(mem.get(BOUT + 12), 2) - - def test_rejected_forms(self): - for line in ( - "buffer_atomic_inc_x2 v[2:3], v1, s[8:11], 0 offen glc", - "buffer_atomic_dec_x2 v[2:3], v1, s[8:11], 0 offen glc", - "buffer_atomic_inc v[2:3], v1, s[8:11], 0 offen glc", - ): - with self.subTest(line=line): - with self.assertRaises(rdna2spirv.Unsupported): - translate(["v_mov_b32_e32 v1, 0", line]) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_ballot_votes.py b/tests/semantic/test_ballot_votes.py deleted file mode 100644 index 2997bef9d..000000000 --- a/tests/semantic/test_ballot_votes.py +++ /dev/null @@ -1,200 +0,0 @@ -"""Ballots and votes on a lane mask, through the translator (TEST-603). - -Each test translates a short RDNA2 compute listing with tools/rdna2spirv.py and runs every lane of it with -tests/semantic/spirv_mini_interp.run_workgroup (which models OpGroupNonUniformBallot/All/Any/BitwiseOr over the -running lanes). The listing builds a lane mask in VCC from two push constants (lane i's bit is bit i of s4:s5), -then reads it the ways the translator turns into subgroup operations: - - s_bcnt1_i32_b64/_b32 vcc population count (ballot bit count) - s_ff1_i32_b64/_b32 vcc lowest set lane, -1 when none (ballot find-LSB) - s_cmp_eq_u64 vcc, exec every active lane true (vote all) - s_cmp_lg_u64 vcc, 0 some lane true (vote any) - v_cndmask_b32 ..., vcc each lane's own bit (ballot bit extract) - s_and_saveexec + v_readfirstlane / s_bcnt1 exec, then EXEC restored: the mask as the new EXEC - -The expected values come from the s4:s5 pattern alone, so a translator that reads the wrong half, the wrong lane -or a stale mask fails here. This replaces a file that modelled the SPIR-V operations in Python without -translating anything. Standard library only; no GPU, llvm-mc or game files. -""" -import gc -import os -import struct -import sys -import tempfile -import unittest -import warnings - -HERE = os.path.dirname(os.path.abspath(__file__)) -ROOT = os.path.dirname(os.path.dirname(HERE)) -TOOLS_DIR = os.environ.get("LEONIDA_TOOLS_DIR") or os.path.join(ROOT, "tools") - -sys.dont_write_bytecode = True -for p in (HERE, TOOLS_DIR): - if p not in sys.path: - sys.path.insert(0, p) - -import rdna2spirv # noqa: E402 -import spirv_mini_interp as si # noqa: E402 - -STUB_DXBC = b"DXBC" + bytes(24) + struct.pack("> (i & 31)) & 1. -BUILD_VCC64 = """\ -v_mov_b32_e32 v11, s5 -v_cmp_lt_u32_e64 vcc, v0, 32 -v_cndmask_b32_e64 v1, v11, s4, vcc -v_and_b32_e32 v2, 31, v0 -v_lshrrev_b32_e32 v3, v2, v1 -v_and_b32_e32 v3, 1, v3 -v_cmp_ne_u32_e64 vcc, 0, v3 -""" -BUILD_VCC32 = """\ -v_mov_b32_e32 v1, s4 -v_and_b32_e32 v2, 31, v0 -v_lshrrev_b32_e32 v3, v2, v1 -v_and_b32_e32 v3, 1, v3 -v_cmp_ne_u32_e64 vcc_lo, 0, v3 -""" -PER_LANE_BIT = f"""\ -v_cndmask_b32_e64 v6, 0, 1, {{vcc}} -v_lshlrev_b32_e32 v7, 2, v0 -v_add_nc_u32_e32 v7, 0x{LANE_BASE:x}, v7 -buffer_store_dword v6, v7, s[0:3], 0 offen -""" - - -def listing(wave): - if wave == 64: - vcc, exec_, b, build = "vcc", "exec", "b64", BUILD_VCC64 - cmp_all, cmp_any = "s_cmp_eq_u64 vcc, exec", "s_cmp_lg_u64 vcc, 0" - save, restore = "s_and_saveexec_b64 s[14:15], vcc", "s_mov_b64 exec, s[14:15]" - else: - vcc, exec_, b, build = "vcc_lo", "exec_lo", "b32", BUILD_VCC32 - cmp_all, cmp_any = "s_cmp_eq_u32 vcc_lo, exec_lo", "s_cmp_lg_u32 vcc_lo, 0" - save, restore = "s_and_saveexec_b32 s14, vcc_lo", "s_mov_b32 exec_lo, s14" - return (build - + f"s_bcnt1_i32_{b} s20, {vcc}\n" + store_sgpr("s20", 0) - + f"s_ff1_i32_{b} s21, {vcc}\n" + store_sgpr("s21", 1) - + cmp_all + "\n" + store_scc(2) - + cmp_any + "\n" + store_scc(3) - + PER_LANE_BIT.format(vcc=vcc) - # The mask as EXEC: the first lane left running, and how many there are. - + save + "\n" - + "v_readfirstlane_b32 s22, v0\n" - + f"s_bcnt1_i32_{b} s23, {exec_}\n" - + restore + "\n" - # Every lane writes its own slot after the restore: a partial restore leaves the other slots unwritten. - + "v_mov_b32_e32 v6, 1\n" - + "v_lshlrev_b32_e32 v7, 2, v0\n" - + f"v_add_nc_u32_e32 v7, 0x{RESTORED_BASE:x}, v7\n" - + "buffer_store_dword v6, v7, s[0:3], 0 offen\n" - + store_sgpr("s22", 4) + store_sgpr("s23", 5) - + "s_endpgm\n") - - -def expected(mask, wave): - full = (1 << wave) - 1 - mask &= full - first = (mask & -mask).bit_length() - 1 if mask else NONE - return {"count": mask.bit_count(), "ff1": first, "all": int(mask == full), "any": int(mask != 0), - "bits": [(mask >> lane) & 1 for lane in range(wave)], "first_active": first, - "exec_count": mask.bit_count()} - - -MASKS64 = [0, (1 << 64) - 1, 1, 1 << 63, 1 << 31, 1 << 32, 0x5555555555555555, 0xAAAAAAAAAAAAAAAA, - 0xFFFFFFFF00000000, 0x00000000FFFFFFFF, 0x8000000180000001, 0x0123456789ABCDEF] -MASKS32 = [0, 0xFFFFFFFF, 1, 1 << 31, 0x55555555, 0xAAAAAAAA, 0xFFFF0000, 0x80000001, 0x89ABCDEF] - - -class BallotVoteTests(unittest.TestCase): - spv = {} - - @classmethod - def setUpClass(cls): - cls.spv = {64: translate_cs("cs_w64_ballot_votes", listing(64), 64), - 32: translate_cs("cs_w32_ballot_votes", listing(32), 32)} - - def check(self, wave, mask): - mem = run_cs(self.spv[wave], wave, mask & NONE, mask >> 32) - want = expected(mask, wave) - self.assertEqual(mem[0], want["count"], "s_bcnt1 vcc") - self.assertEqual(mem[4], want["ff1"], "s_ff1 vcc") - self.assertEqual(mem[8], want["all"], "vote all (vcc == exec)") - self.assertEqual(mem[12], want["any"], "vote any (vcc != 0)") - self.assertEqual([mem[LANE_BASE + 4 * lane] for lane in range(wave)], want["bits"], "per-lane bit") - if mask: # with no lane left in EXEC, v_readfirstlane has no lane to read - self.assertEqual(mem[16], want["first_active"], "v_readfirstlane under the mask as EXEC") - self.assertEqual(mem[20], want["exec_count"], "s_bcnt1 exec under the mask as EXEC") - self.assertEqual([mem.get(RESTORED_BASE + 4 * lane) for lane in range(wave)], [1] * wave, - "every lane runs again after EXEC is restored") - - def test_wave64(self): - for mask in MASKS64: - with self.subTest(mask=f"0x{mask:016x}"): - self.check(64, mask) - - def test_wave32(self): - for mask in MASKS32: - with self.subTest(mask=f"0x{mask:08x}"): - self.check(32, mask) - - def test_the_translation_uses_subgroup_operations(self): - # The reads go through the subgroup, not a per-lane shortcut that would pass a one-lane run. - for wave, spv in self.spv.items(): - with self.subTest(wave=wave): - self.assertIn("OpGroupNonUniform", spv) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_barrier_control.py b/tests/semantic/test_barrier_control.py deleted file mode 100644 index 3dd25caf6..000000000 --- a/tests/semantic/test_barrier_control.py +++ /dev/null @@ -1,433 +0,0 @@ -"""Semantic interpreter tests for workgroup execution barriers (s_barrier). - -Covers: - * AMD RDNA2 ISA specification for s_barrier (AMD RDNA 2 Instruction Set Architecture, - Section 6.2 "Program Flow Control" and Section 12 "Scalar Instructions"): - - Synchronizes all active wavefronts within a workgroup / threadgroup. - - Blocks wavefront execution until all waves in the workgroup have reached the barrier. - - Orders LDS memory operations across waves in conjunction with lgkmcnt counters. - * SPIR-V 1.5 Specification (Section 3.32.20 "OpControlBarrier"): - - OpControlBarrier - - Execution Scope = 2 (Scope::Workgroup) - - Memory Scope = 2 (Scope::Workgroup) - - Memory Semantics = 0x108 (WorkgroupMemory [0x100] | AcquireRelease [0x8]) - - Uniformity: OpControlBarrier must be dynamically uniform across the Execution scope. - * Translator verification (tools/rdna2spirv.py): - - In compute shaders (cs) and mesh shaders (ms), s_barrier emits - 'OpControlBarrier %c2 %c2 %c108'. - - In pixel (ps), vertex (vs), and geometry (gs) shaders, s_barrier raises - Unsupported("s_barrier outside compute"). - * Multi-thread / multi-wave workgroup execution simulation: - - Workgroup synchronization state machine (arrival tracking, barrier release, epoch advancement). - - LDS shared memory coherency across barrier boundaries. - - Multi-phase parallel tree reduction with successive barriers. - - Workgroup neighbor / ring-shift data exchange across waves. - - Asynchronous wave arrival orders (staggered scheduling). - - Deadlock detection for divergent/non-uniform barrier execution. - - Data race hazard detection when barriers are omitted or bypassed. - * Mini SPIR-V interpreter strict rejection: - - Confirms spirv_mini_interp strictly rejects OpControlBarrier as unsupported for - single-lane straight-line fragment modules. - -Run directly: - python -I tests/semantic/test_barrier_control.py -Or via unittest discovery: - python -m unittest discover -s tests/semantic -v -""" -import copy -import os -import sys -import unittest - -HERE = os.path.dirname(os.path.abspath(__file__)) -ROOT = os.path.dirname(os.path.dirname(HERE)) -TOOLS_DIR = os.environ.get("LEONIDA_TOOLS_DIR") or os.path.join(ROOT, "tools") - -sys.path.insert(0, TOOLS_DIR) -sys.path.insert(0, HERE) - -import rdna2spirv # noqa: E402 -import spirv_mini_interp as si # noqa: E402 - -# SPIR-V Specification constants (Section 3.27 Scope & Section 3.28 Memory Semantics ) -SCOPE_CROSS_DEVICE = 0 -SCOPE_DEVICE = 1 -SCOPE_WORKGROUP = 2 -SCOPE_SUBGROUP = 3 -SCOPE_INVOCATION = 4 - -SEMANTICS_RELAXED = 0x0 -SEMANTICS_ACQUIRE = 0x2 -SEMANTICS_RELEASE = 0x4 -SEMANTICS_ACQUIRE_RELEASE = 0x8 -SEMANTICS_SEQUENTIALLY_CONSISTENT = 0x10 -SEMANTICS_UNIFORM_MEMORY = 0x40 -SEMANTICS_WORKGROUP_MEMORY = 0x100 -SEMANTICS_IMAGE_MEMORY = 0x800 - -# The exact memory semantics emitted by rdna2spirv for s_barrier -EXPECTED_BARRIER_SEMANTICS = SEMANTICS_WORKGROUP_MEMORY | SEMANTICS_ACQUIRE_RELEASE # 0x108 = 264 - - -class BarrierSynchronizationError(Exception): - """Raised when an invocation attempts to proceed past an unsynchronized barrier.""" - - -class BarrierDeadlockError(Exception): - """Raised when a control barrier is executed with divergent/non-uniform workgroup flow.""" - - -class DataRaceHazard(Exception): - """Raised when un-synchronized cross-thread LDS memory access is detected.""" - - -class WorkgroupBarrierInterpreter: - """Deterministic semantic interpreter modeling multi-wave workgroup execution barriers. - - Simulates a workgroup consisting of multiple waves and threads sharing LDS memory, - strictly enforcing barrier synchronization, dynamic uniformity, and memory visibility. - """ - - def __init__(self, num_threads=64, wave_size=32, lds_size_dwords=1024): - if num_threads % wave_size != 0: - raise ValueError("num_threads must be a multiple of wave_size") - self.num_threads = num_threads - self.wave_size = wave_size - self.num_waves = num_threads // wave_size - self.lds_size = lds_size_dwords - - # Shared LDS memory - self.lds = [0] * self.lds_size - - # Barrier state - self.current_epoch = 0 - self.barrier_arrivals = set() - self.thread_epochs = [0] * self.num_threads - - # Memory tracking for data race detection within the current epoch - # address -> set of thread_ids that wrote in current epoch - self.epoch_writes = {} - # address -> set of thread_ids that read in current epoch - self.epoch_reads = {} - - def wave_for_thread(self, thread_id): - return thread_id // self.wave_size - - def write_lds(self, thread_id, address, value): - if not (0 <= address < self.lds_size): - raise IndexError(f"LDS write out of bounds: address {address} (size {self.lds_size})") - - # Check for un-synchronized conflicting access in the same epoch from another thread - if address in self.epoch_reads: - conflicting_readers = self.epoch_reads[address] - {thread_id} - if conflicting_readers: - raise DataRaceHazard( - f"WAR race hazard: thread {thread_id} writing address {address} " - f"read by threads {sorted(conflicting_readers)} in epoch {self.current_epoch} without barrier" - ) - - if address not in self.epoch_writes: - self.epoch_writes[address] = set() - self.epoch_writes[address].add(thread_id) - - self.lds[address] = value & 0xFFFFFFFF - - def read_lds(self, thread_id, address): - if not (0 <= address < self.lds_size): - raise IndexError(f"LDS read out of bounds: address {address} (size {self.lds_size})") - - # Check for un-synchronized RAW hazard (read of an address written by another thread in the same epoch) - if address in self.epoch_writes: - conflicting_writers = self.epoch_writes[address] - {thread_id} - if conflicting_writers: - raise DataRaceHazard( - f"RAW race hazard: thread {thread_id} reading address {address} " - f"written by threads {sorted(conflicting_writers)} in epoch {self.current_epoch} without barrier" - ) - - if address not in self.epoch_reads: - self.epoch_reads[address] = set() - self.epoch_reads[address].add(thread_id) - - return self.lds[address] - - def arrive_barrier(self, thread_id): - """Record thread arrival at the workgroup barrier.""" - if not (0 <= thread_id < self.num_threads): - raise ValueError(f"Invalid thread_id {thread_id}") - - if thread_id in self.barrier_arrivals: - raise BarrierSynchronizationError(f"Thread {thread_id} arrived twice at the same barrier epoch") - - self.barrier_arrivals.add(thread_id) - - # When all threads have arrived, the barrier is fulfilled - if len(self.barrier_arrivals) == self.num_threads: - self._release_barrier() - - def wave_arrive_barrier(self, wave_id): - """Simulate RDNA2 hardware wave-level barrier: a wave reaches s_barrier.""" - if not (0 <= wave_id < self.num_waves): - raise ValueError(f"Invalid wave_id {wave_id}") - start_thread = wave_id * self.wave_size - for t in range(start_thread, start_thread + self.wave_size): - self.arrive_barrier(t) - - def _release_barrier(self): - """Release the barrier for all threads, advance epoch, and clear access hazard sets.""" - for t in range(self.num_threads): - self.thread_epochs[t] += 1 - self.current_epoch += 1 - self.barrier_arrivals.clear() - self.epoch_writes.clear() - self.epoch_reads.clear() - - def step_past_barrier(self, thread_id): - """Assert that thread_id is permitted to proceed into the next execution phase.""" - if len(self.barrier_arrivals) > 0: - if thread_id in self.barrier_arrivals: - raise BarrierSynchronizationError( - f"Thread {thread_id} attempted to proceed before all other workgroup threads reached the barrier" - ) - raise BarrierSynchronizationError( - f"Thread {thread_id} attempted to proceed before reaching the barrier" - ) - - def check_dynamic_uniformity(self, active_mask): - """Verify that the barrier is executed uniformly by all workgroup threads.""" - all_active = (1 << self.num_threads) - 1 - if active_mask != all_active: - divergent_count = bin(active_mask).count("1") - raise BarrierDeadlockError( - f"Barrier divergence detected: only {divergent_count} of {self.num_threads} threads reached s_barrier" - ) - - -class BarrierSpecificationTests(unittest.TestCase): - """Verify SPIR-V and RDNA2 specification constants and parameter validity for s_barrier.""" - - def test_scope_constants(self): - self.assertEqual(SCOPE_WORKGROUP, 2) - self.assertEqual(SCOPE_SUBGROUP, 3) - self.assertEqual(SCOPE_DEVICE, 1) - - def test_memory_semantics_constants(self): - self.assertEqual(SEMANTICS_WORKGROUP_MEMORY, 0x100) - self.assertEqual(SEMANTICS_ACQUIRE_RELEASE, 0x8) - self.assertEqual(EXPECTED_BARRIER_SEMANTICS, 0x108) - - def test_semantics_contains_required_flags(self): - # Workgroup barrier must order workgroup memory (LDS) with acquire-release semantics - self.assertTrue(EXPECTED_BARRIER_SEMANTICS & SEMANTICS_WORKGROUP_MEMORY) - self.assertTrue(EXPECTED_BARRIER_SEMANTICS & SEMANTICS_ACQUIRE_RELEASE) - # Should not set device-level or uniform memory scopes unless specified - self.assertFalse(EXPECTED_BARRIER_SEMANTICS & SEMANTICS_UNIFORM_MEMORY) - self.assertFalse(EXPECTED_BARRIER_SEMANTICS & SEMANTICS_IMAGE_MEMORY) - - -class TranslatorBarrierEmissionTests(unittest.TestCase): - """Verify tools/rdna2spirv.py handling of s_barrier across pipeline stages.""" - - def test_compute_stage_emits_opcontrolbarrier(self): - g = rdna2spirv.Gen(stage="cs") - g.insn({"op": "s_barrier", "args": [], "mods": []}) - emitted = "\n".join(g.body) - self.assertIn("OpControlBarrier", emitted) - # Scope 2 (Workgroup), Scope 2 (Workgroup), Semantics 0x108 (264) - c2 = g.cu(2) - c108 = g.cu(0x108) - expected_line = f"OpControlBarrier {c2} {c2} {c108}" - self.assertIn(expected_line, emitted) - - def test_mesh_stage_emits_opcontrolbarrier(self): - g = rdna2spirv.Gen(stage="ms") - g.insn({"op": "s_barrier", "args": [], "mods": []}) - emitted = "\n".join(g.body) - self.assertIn("OpControlBarrier", emitted) - c2 = g.cu(2) - c108 = g.cu(0x108) - expected_line = f"OpControlBarrier {c2} {c2} {c108}" - self.assertIn(expected_line, emitted) - - def test_pixel_stage_rejects_s_barrier(self): - g = rdna2spirv.Gen(stage="ps") - with self.assertRaises(rdna2spirv.Unsupported) as ctx: - g.insn({"op": "s_barrier", "args": [], "mods": []}) - self.assertIn("s_barrier outside compute", str(ctx.exception)) - - def test_vertex_stage_rejects_s_barrier(self): - g = rdna2spirv.Gen(stage="vs") - with self.assertRaises(rdna2spirv.Unsupported) as ctx: - g.insn({"op": "s_barrier", "args": [], "mods": []}) - self.assertIn("s_barrier outside compute", str(ctx.exception)) - - def test_geometry_stage_rejects_s_barrier(self): - g = rdna2spirv.Gen(stage="gs") - with self.assertRaises(rdna2spirv.Unsupported) as ctx: - g.insn({"op": "s_barrier", "args": [], "mods": []}) - self.assertIn("s_barrier outside compute", str(ctx.exception)) - - def test_s_barrier_leaves_registers_unmodified(self): - g = rdna2spirv.Gen(stage="cs") - initial_cur_masks = copy.copy(g.cur_masks) - g.insn({"op": "s_barrier", "args": [], "mods": []}) - self.assertEqual(g.cur_masks, initial_cur_masks) - - -class WorkgroupBarrierSemanticTests(unittest.TestCase): - """Semantic verification of workgroup barrier synchronization and memory exchange.""" - - def test_neighbor_exchange_with_barrier(self): - """Each thread writes to LDS, workgroup synchronizes via s_barrier, then reads neighbor value.""" - num_threads = 64 - interp = WorkgroupBarrierInterpreter(num_threads=num_threads, wave_size=32) - - # Phase 1: All threads write unique pattern to their LDS slot - for t in range(num_threads): - val = (t * 31 + 7) & 0xFFFFFFFF - interp.write_lds(t, address=t, value=val) - - # Synchronize workgroup via waves - interp.wave_arrive_barrier(0) - interp.wave_arrive_barrier(1) - - # Phase 2: Each thread reads from neighbor (t + 1) % num_threads - results = [] - for t in range(num_threads): - interp.step_past_barrier(t) - neighbor_addr = (t + 1) % num_threads - results.append(interp.read_lds(t, address=neighbor_addr)) - - # Check every result matches the neighbor's initial write - for t in range(num_threads): - expected = ((t + 1) % num_threads * 31 + 7) & 0xFFFFFFFF - self.assertEqual(results[t], expected) - - def test_missing_barrier_triggers_data_race_hazard(self): - """Attempting to read neighbor data in the same epoch without a barrier raises DataRaceHazard.""" - num_threads = 64 - interp = WorkgroupBarrierInterpreter(num_threads=num_threads, wave_size=32) - - for t in range(num_threads): - interp.write_lds(t, address=t, value=t * 10) - - # Omit the barrier: thread 0 tries to read LDS[1] which was written by thread 1 in the same epoch - with self.assertRaises(DataRaceHazard) as ctx: - interp.read_lds(0, address=1) - self.assertIn("RAW race hazard", str(ctx.exception)) - - def test_parallel_tree_reduction_across_successive_barriers(self): - """Tree reduction of 64 elements using successive workgroup barriers across 6 steps.""" - num_threads = 64 - interp = WorkgroupBarrierInterpreter(num_threads=num_threads, wave_size=32) - - # Step 0: Initialize LDS[t] = t + 1 - for t in range(num_threads): - interp.write_lds(t, address=t, value=t + 1) - - interp.wave_arrive_barrier(0) - interp.wave_arrive_barrier(1) - - # Reduction loop: strides 1, 2, 4, 8, 16, 32 - stride = 1 - while stride < num_threads: - for t in range(0, num_threads, stride * 2): - interp.step_past_barrier(t) - a = interp.read_lds(t, address=t) - b = interp.read_lds(t, address=t + stride) - interp.write_lds(t, address=t, value=a + b) - - # Synchronize all threads at the end of this stride - for t in range(num_threads): - interp.arrive_barrier(t) - - stride *= 2 - - # Final sum in LDS[0] must equal 1 + 2 + ... + 64 = 64 * 65 / 2 = 2080 - final_sum = interp.lds[0] - self.assertEqual(final_sum, 2080) - # 6 reduction steps + 1 initial step = 7 epochs - self.assertEqual(interp.current_epoch, 7) - - def test_asynchronous_wave_arrival_order(self): - """Waves may arrive in non-sequential order; barrier holds until all waves arrive.""" - interp = WorkgroupBarrierInterpreter(num_threads=128, wave_size=32) # 4 waves - self.assertEqual(interp.num_waves, 4) - - for t in range(128): - interp.write_lds(t, address=t, value=t) - - # Waves arrive in reverse order: 3, 2, 1 - interp.wave_arrive_barrier(3) - interp.wave_arrive_barrier(2) - interp.wave_arrive_barrier(1) - - # Barrier must not be released yet (wave 0 has not arrived) - self.assertEqual(interp.current_epoch, 0) - with self.assertRaises(BarrierSynchronizationError): - interp.step_past_barrier(thread_id=96) # Thread from wave 3 - - # Wave 0 arrives last - interp.wave_arrive_barrier(0) - self.assertEqual(interp.current_epoch, 1) - - # Now any thread can proceed safely - for t in range(128): - interp.step_past_barrier(t) - - def test_divergent_barrier_detected_as_deadlock(self): - """Conditional branch causing only half the workgroup to execute s_barrier triggers deadlock.""" - num_threads = 64 - interp = WorkgroupBarrierInterpreter(num_threads=num_threads, wave_size=32) - - # Active mask where only thread_id < 32 executes the barrier - divergent_mask = (1 << 32) - 1 - with self.assertRaises(BarrierDeadlockError) as ctx: - interp.check_dynamic_uniformity(divergent_mask) - self.assertIn("Barrier divergence detected", str(ctx.exception)) - - def test_duplicate_arrival_error(self): - """A thread cannot arrive twice at the same barrier epoch.""" - interp = WorkgroupBarrierInterpreter(num_threads=64, wave_size=32) - interp.arrive_barrier(0) - with self.assertRaises(BarrierSynchronizationError): - interp.arrive_barrier(0) - - def test_out_of_bounds_lds_rejected(self): - """Access beyond declared LDS dword capacity is rejected.""" - interp = WorkgroupBarrierInterpreter(num_threads=64, wave_size=32, lds_size_dwords=128) - with self.assertRaises(IndexError): - interp.write_lds(0, address=128, value=1) - with self.assertRaises(IndexError): - interp.read_lds(0, address=128) - - -class MiniInterpreterRejectionTests(unittest.TestCase): - """Verify that spirv_mini_interp strictly rejects OpControlBarrier as unsupported.""" - - HEADER = """\ -OpCapability Shader -%glsl = OpExtInstImport "GLSL.std.450" -OpMemoryModel Logical GLSL450 -OpEntryPoint Fragment %main "main" %out -%void = OpTypeVoid -%fn = OpTypeFunction %void -%uint = OpTypeInt 32 0 -%_ptr_Output_uint = OpTypePointer Output %uint -%out = OpVariable %_ptr_Output_uint Output -%c2 = OpConstant %uint 2 -%c108 = OpConstant %uint 264 -%main = OpFunction %void None %fn -%entry = OpLabel -""" - FOOTER = "OpReturn\nOpFunctionEnd\n" - - def test_mini_interp_refuses_opcontrolbarrier(self): - text = self.HEADER + "OpControlBarrier %c2 %c2 %c108\n" + self.FOOTER - with self.assertRaises(si.UnsupportedConstruct) as ctx: - si.run_fragment(text) - self.assertIn("OpControlBarrier", str(ctx.exception)) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_bary_fallback.py b/tests/semantic/test_bary_fallback.py deleted file mode 100644 index 53bcf39da..000000000 --- a/tests/semantic/test_bary_fallback.py +++ /dev/null @@ -1,383 +0,0 @@ -"""rdna2spirv.py --bary-fallback: raw barycentric reads without VK_KHR_fragment_shader_barycentric. - -The input is the GPU test runtime/test/shaders/ps_bary (hand-written, no game data; fixture from regen_fixtures.py). -It reads the raw barycentric pair (v0 = i, v1 = j) next to v_interp. By default the translator gives the pair as -BaryCoordKHR.y / .z. With --bary-fallback the same values come from an ordinary vec3 input at the lowest location no -attribute uses; tools/bary_fallback_gs.py writes the pass-through geometry shader that fills it. On the GPU, -run_gpu_tests.py / check.py with LEONIDA_BARY_FALLBACK=1 check ps_bary through that GS. Here: -* the module declares neither the capability nor the extension nor the builtin, and the metadata names the input - (the lowest free location, also for sparse attributes such as attr30 alone); -* the shader reads i and j from the new input exactly as it reads them from BaryCoordKHR (one-lane interpreter); -* a shader that doesn't read the pair translates to the same module with and without the flag; -* the GS text has the vertex count, the one-hot weights and the locations the PS expects, and refuses a collision. -""" -import gc -import json -import math -from pathlib import Path -import os -import re -import shutil -import struct -import subprocess -import sys -import tempfile -import unittest -import warnings - -import support -import rdna2spirv -import bary_fallback_gs - -I, J = 0.3125, 0.4375 # exact in binary32, i + j < 1 -ATTR0 = (0.75, 0.5, 0.0, 1.0) - - -def f32_bits(x): - return struct.unpack("> 32) & 0xFFFF) | ((stride & 0x3FFF) << 16) - return [ - f"s_mov_b32 s8, {w0:#x}", - f"s_mov_b32 s9, {w1:#x}", - f"s_mov_b32 s10, {num_records:#x}", - f"s_mov_b32 s11, {word3:#x}", - ] - - -def out_store_lines(reg, count=1, lane_stride=4): - store = "buffer_store_dword" if count == 1 else f"buffer_store_dwordx{count}" - lines = [ - "s_mov_b32 s8, 0", - "s_mov_b32 s9, 0", - "s_mov_b32 s10, 0x10000", - f"s_mov_b32 s11, {RAW_W3:#x}", - f"v_mul_lo_u32 v10, v0, {lane_stride}", - f"v_add_nc_u32_e32 v10, {OUT:#x}, v10", - f"{store} {reg}, v10, s[8:11], 0 offen", - ] - return lines - - -def run_buf_fminmax(kind, m, d, glc=True, base=0, stride=0, offset=0x40, num_records=0x100, - word3=RAW_W3, idx=None, nlanes=1, active_mask_lane0_only=False): - mods = [] - addr_lines = [] - if idx is not None: - addr_lines.append(f"v_mov_b32_e32 v1, {idx:#x}") - addr_lines.append(f"v_mov_b32_e32 v2, {offset:#x}") - vaddr = "v[1:2]" - mods += ["idxen", "offen"] - else: - addr_lines.append(f"v_mov_b32_e32 v1, {offset:#x}") - vaddr = "v1" - mods.append("offen") - if glc: - mods.append("glc") - body = buf_rsrc_lines(base, stride, num_records, word3) + addr_lines + [ - f"v_mov_b32_e32 v3, {d:#x}", - ] - if active_mask_lane0_only: - body += [ - "v_cmp_eq_u32_e32 vcc_lo, 0, v0", - "s_and_saveexec_b32 s12, vcc_lo", - ] - body.append(f"buffer_atomic_{kind} v3, {vaddr}, s[8:11], 0 {' '.join(mods)}") - if active_mask_lane0_only: - body.append("s_mov_b32 exec_lo, s12") - body += ["s_waitcnt vmcnt(0)"] + out_store_lines("v3", count=1, lane_stride=4) - eff = base + (idx * stride if idx is not None else 0) + offset - mem = run(body, {eff: m, eff & ~3: m}, nlanes=nlanes) - return mem - - -class BufferAtomicFminmax(unittest.TestCase): - def test_fmin_fmax_values_glc_and_non_glc(self): - pos0, neg0 = 0x00000000, 0x80000000 - one, neg2, half = 0x3F800000, 0xC0000000, 0x3F000000 - pinf, ninf, qnan = 0x7F800000, 0xFF800000, 0x7FC00001 - cases = [ - ("fmin", one, half, half), - ("fmin", half, one, half), - ("fmin", one, neg2, neg2), - ("fmin", pos0, neg0, neg0), - ("fmin", neg0, pos0, neg0), - ("fmin", one, pinf, one), - ("fmin", one, ninf, ninf), - ("fmin", qnan, one, one), - ("fmin", one, qnan, one), - ("fmax", one, half, one), - ("fmax", half, one, one), - ("fmax", neg2, one, one), - ("fmax", pos0, neg0, pos0), - ("fmax", neg0, pos0, pos0), - ("fmax", one, pinf, pinf), - ("fmax", one, ninf, one), - ("fmax", qnan, one, one), - ("fmax", one, qnan, one), - ] - for kind, m, d, expected in cases: - with self.subTest(op=kind, m=hex(m), d=hex(d)): - mem_glc = run_buf_fminmax(kind, m, d, glc=True) - self.assertEqual((mem_glc.get(OUT), mem_glc.get(0x40)), (m, expected)) - mem_noglc = run_buf_fminmax(kind, m, d, glc=False) - self.assertEqual((mem_noglc.get(OUT), mem_noglc.get(0x40)), (d, expected)) - - def test_multi_lane_cas_contention(self): - init, one, neg2 = 0x40400000, 0x3F800000, 0xC0000000 # 3.0, 1.0, -2.0 - for kind, expected in (("fmin", neg2), ("fmax", init)): - with self.subTest(op=kind): - body = buf_rsrc_lines(0, 0, 0x100, RAW_W3) + [ - "v_mov_b32_e32 v1, 0x40", - "v_cmp_eq_u32_e32 vcc_lo, 0, v0", - f"v_mov_b32_e32 v3, {neg2:#x}", - f"v_cndmask_b32_e32 v3, v3, {one:#x}, vcc_lo", - f"buffer_atomic_{kind} v3, v1, s[8:11], 0 offen glc", - "s_waitcnt vmcnt(0)", - ] + out_store_lines("v3", count=1, lane_stride=4) - mem = run(body, {0x40: init}, nlanes=2) - self.assertEqual(mem.get(0x40), expected) - seen = {mem.get(OUT), mem.get(OUT + 4)} - self.assertIn(init, seen) - - def test_bounds_raw_and_structured(self): - one, two = 0x3F800000, 0x40000000 - # RAW (OOB_SELECT=3): offset=0, num_records=4 -> in bounds; num_records=3 -> partial OOB (dropped, returns 0) - mem_ok = run_buf_fminmax("fmax", one, two, base=0x40, offset=0, num_records=4, word3=RAW_W3) - self.assertEqual((mem_ok.get(OUT), mem_ok.get(0x40)), (one, two)) - - mem_partial = run_buf_fminmax("fmax", one, two, base=0x40, offset=0, num_records=3, word3=RAW_W3) - self.assertEqual((mem_partial.get(OUT), mem_partial.get(0x40)), (0, one)) - - mem_oob = run_buf_fminmax("fmax", one, two, base=0x40, offset=4, num_records=4, word3=RAW_W3) - self.assertEqual((mem_oob.get(OUT), mem_oob.get(0x44)), (0, one)) - - # STRUCTURED_WITH_OFFSET (OOB_SELECT=0): stride=6, off=0 ok; stride=6, off=4 partial OOB; stride=3, off=0 OOB - mem_st_ok = run_buf_fminmax("fmin", two, one, base=0x40, stride=6, offset=0, - num_records=2, word3=MODE0_W3, idx=0) - self.assertEqual((mem_st_ok.get(OUT), mem_st_ok.get(0x40)), (two, one)) - - mem_st_partial = run_buf_fminmax("fmin", two, one, base=0x40, stride=6, offset=4, - num_records=2, word3=MODE0_W3, idx=0) - self.assertEqual((mem_st_partial.get(OUT), mem_st_partial.get(0x44)), (0, two)) - - mem_st_small = run_buf_fminmax("fmin", two, one, base=0x40, stride=3, offset=0, - num_records=2, word3=MODE0_W3, idx=0) - self.assertEqual((mem_st_small.get(OUT), mem_st_small.get(0x40)), (0, two)) - - def test_inactive_lane_preserves_vdata(self): - one, two = 0x3F800000, 0x40000000 - mem = run_buf_fminmax("fmax", one, two, base=0x40, offset=0, num_records=0x100, - word3=RAW_W3, nlanes=2, active_mask_lane0_only=True) - self.assertEqual(mem.get(0x40), two) - self.assertEqual(mem.get(OUT), one) # active lane 0 gets old memory word - self.assertEqual(mem.get(OUT + 4), two) # inactive lane 1 preserves vdata - - def test_no_float_atomic_capability_and_rejected_forms(self): - for kind, glsl_op in (("fmin", "NMin"), ("fmax", "NMax")): - for body in ( - buf_rsrc_lines(0, 0, 0x100, RAW_W3) + [ - "v_mov_b32_e32 v1, 0", - "v_mov_b32_e32 v2, 0x3f800000", - f"buffer_atomic_{kind} v2, v1, s[8:11], 0 offen glc", - ], - [ - "v_mov_b32_e32 v1, 0x2000", - "v_mov_b32_e32 v2, 0x3f800000", - f"global_atomic_{kind} v5, v1, v2, s[0:1] glc", - ], - ): - with self.subTest(insn=body[-1]): - spv = translate(body) - self.assertIn("OpAtomicLoad %uint", spv) - self.assertIn("OpAtomicCompareExchange", spv) - self.assertNotIn("Aligned 4", spv) # no plain non-atomic PSB OpLoad on atomic addr - self.assertIn(glsl_op, spv) - self.assertNotIn("AtomicFloat", spv) - self.assertNotIn("SPV_EXT_shader_atomic_float", spv) - - for bad in ("buffer_atomic_fmin v[2:3], v1, s[8:11], 0 offen glc", - "buffer_atomic_fmax v2, v1, s[8:11], 0 offen lds"): - with self.subTest(bad=bad): - with self.assertRaises(rdna2spirv.Unsupported): - translate(buf_rsrc_lines(0, 0, 0x100, RAW_W3) + ["v_mov_b32_e32 v1, 0", bad]) - - -class AtomicNaturalAlignment(unittest.TestCase): - def test_buffer_atomic_32bit_alignment(self): - # Measured natively on gfx1036 (wave32 & wave64): (addr & 3) != 0 drops the atomic; - # active glc lane gets 0, inactive lane keeps vdata; base+2 + offset=2 -> aligned -> succeeds. - for kind in ("swap", "add", "cmpswap", "fmin", "fmax"): - for base, offset, should_run in ((0x40, 1, False), (0x40, 2, False), - (0x42, 0, False), (0x42, 2, True)): - with self.subTest(op=kind, base=hex(base), offset=offset): - init_m = 0x3F800000 # 1.0f - data_d = 0x40000000 # 2.0f - body = buf_rsrc_lines(base, 0, 0x100, RAW_W3) + [ - f"v_mov_b32_e32 v1, {offset:#x}", - f"v_mov_b32_e32 v2, {data_d:#x}", - f"v_mov_b32_e32 v3, {init_m:#x}", # cmp matches init_m for cmpswap - "v_cmp_eq_u32_e32 vcc_lo, 0, v0", - "s_and_saveexec_b32 s12, vcc_lo", - f"buffer_atomic_{kind} {'v[2:3]' if kind == 'cmpswap' else 'v2'}, v1, s[8:11], 0 offen glc", - "s_mov_b32 exec_lo, s12", - "s_waitcnt vmcnt(0)", - ] + out_store_lines("v2", count=1, lane_stride=4) - eff = base + offset - init_mem = {0x40: init_m, 0x44: init_m} - mem = run(body, init_mem, nlanes=2) - # Inactive lane 1 always preserves vdata - self.assertEqual(mem.get(OUT + 4), data_d) - if should_run: - self.assertEqual(mem.get(OUT), init_m) - expected_m = { - "swap": data_d, - "add": (init_m + data_d) & M32, - "cmpswap": data_d, - "fmin": init_m, - "fmax": data_d, - }[kind] - self.assertEqual(mem.get(eff), expected_m) - else: - self.assertEqual(mem.get(OUT), 0) - self.assertEqual(mem.get(0x40), init_m) - self.assertEqual(mem.get(0x44), init_m) - self.assertNotIn(eff, mem) - - def test_buffer_atomic_x2_alignment_and_partial_bounds(self): - # Alignment: (addr & 7) != 0 dropped even under OOB_SELECT=2 (DISABLED). - m_lo, m_hi = 0x11112222, 0x33334444 - d_lo, d_hi = 0x55556666, 0x77778888 - for kind in ("swap", "and", "or", "xor"): - for base, offset, word3, should_run in ( - (0x40, 2, RAW_W3, False), - (0x40, 4, RAW_W3, False), - (0x40, 4, MODE2_W3, False), - (0x44, 0, MODE2_W3, False), - (0x44, 4, RAW_W3, True), - ): - with self.subTest(op=kind, base=hex(base), offset=offset, word3=hex(word3)): - body = buf_rsrc_lines(base, 0, 0x100, word3) + [ - f"v_mov_b32_e32 v1, {offset:#x}", - f"v_mov_b32_e32 v2, {d_lo:#x}", - f"v_mov_b32_e32 v3, {d_hi:#x}", - "v_cmp_eq_u32_e32 vcc_lo, 0, v0", - "s_and_saveexec_b32 s12, vcc_lo", - f"buffer_atomic_{kind}_x2 v[2:3], v1, s[8:11], 0 offen glc", - "s_mov_b32 exec_lo, s12", - "s_waitcnt vmcnt(0)", - ] + out_store_lines("v[2:3]", count=2, lane_stride=8) - eff = base + offset - init_mem = {0x40: m_lo, 0x44: m_hi, 0x48: m_lo, 0x4C: m_hi} - mem = run(body, init_mem, nlanes=2) - # Inactive lane 1 always preserves vdata[0:1] - self.assertEqual((mem.get(OUT + 8), mem.get(OUT + 12)), (d_lo, d_hi)) - if should_run: - self.assertEqual((mem.get(OUT), mem.get(OUT + 4)), (m_lo, m_hi)) - op_fn = {"swap": lambda a, b: b, "and": lambda a, b: a & b, - "or": lambda a, b: a | b, "xor": lambda a, b: a ^ b}[kind] - self.assertEqual((mem.get(eff), mem.get(eff + 4)), - (op_fn(m_lo, d_lo), op_fn(m_hi, d_hi))) - else: - self.assertEqual((mem.get(OUT), mem.get(OUT + 4)), (0, 0)) - self.assertEqual((mem.get(0x40), mem.get(0x44)), (m_lo, m_hi)) - self.assertEqual((mem.get(0x48), mem.get(0x4C)), (m_lo, m_hi)) - - # Partial-bounds matrix matching native gfx1036 measurements across OOB_SELECT 0..3. - bounds_cases = [ - # (word3, stride, num_records, idx, offset, should_run) - (RAW_W3, 0, 8, None, 0, True), - (RAW_W3, 0, 16, None, 8, True), - (RAW_W3, 0, 7, None, 0, False), - (RAW_W3, 0, 5, None, 0, False), - (RAW_W3, 0, 4, None, 0, False), - (RAW_W3, 0, 15, None, 8, False), - (RAW_W3, 0, 12, None, 8, False), - (MODE0_W3, 8, 1, 0, 0, True), - (MODE0_W3, 16, 1, 0, 8, True), - (MODE0_W3, 12, 1, 0, 0, True), - (MODE0_W3, 7, 1, 0, 0, False), - (MODE0_W3, 12, 1, 0, 8, False), - (MODE0_W3, 8, 1, 1, 0, False), - (MODE1_W3, 0, 1, 0, 0, True), - (MODE1_W3, 0, 1, 0, 8, True), - (MODE1_W3, 0, 1, 1, 0, False), - (MODE2_W3, 0, 8, None, 8, True), - (MODE2_W3, 0, 0, None, 0, False), - ] - for word3, stride, num_records, idx, offset, should_run in bounds_cases: - with self.subTest(word3=hex(word3), stride=stride, num_records=num_records, idx=idx, offset=offset): - base = 0x40 - if idx is not None: - addr_setup = [f"v_mov_b32_e32 v1, {idx:#x}", f"v_mov_b32_e32 v2, {offset:#x}"] - vaddr, mods = "v[1:2]", "idxen offen glc" - else: - addr_setup = [f"v_mov_b32_e32 v1, {offset:#x}"] - vaddr, mods = "v1", "offen glc" - body = buf_rsrc_lines(base, stride, num_records, word3) + addr_setup + [ - f"v_mov_b32_e32 v4, {d_lo:#x}", - f"v_mov_b32_e32 v5, {d_hi:#x}", - f"buffer_atomic_swap_x2 v[4:5], {vaddr}, s[8:11], 0 {mods}", - "s_waitcnt vmcnt(0)", - ] + out_store_lines("v[4:5]", count=2, lane_stride=8) - eff = base + (idx * stride if idx is not None else 0) + offset - mem = run(body, {eff: m_lo, eff + 4: m_hi}) - if should_run: - self.assertEqual((mem.get(OUT), mem.get(OUT + 4)), (m_lo, m_hi)) - self.assertEqual((mem.get(eff), mem.get(eff + 4)), (d_lo, d_hi)) - else: - self.assertEqual((mem.get(OUT), mem.get(OUT + 4)), (0, 0)) - self.assertEqual((mem.get(eff), mem.get(eff + 4)), (m_lo, m_hi)) - - def test_global_atomic_32bit_alignment(self): - init_m, data_d = 0x3F800000, 0x40000000 - for kind in ("add", "swap", "cmpswap", "fmin", "fmax"): - for vaddr, inst_off, should_run in ((TARGET + 1, 0, False), - (TARGET + 2, 0, False), - (TARGET, 2, False), - (TARGET + 2, -2, True)): - with self.subTest(op=kind, vaddr=hex(vaddr), inst_off=inst_off): - off_str = f" offset:{inst_off}" if inst_off else "" - vdata = "v[2:3]" if kind == "cmpswap" else "v2" - body = [ - f"v_mov_b32_e32 v1, {vaddr:#x}", - f"v_mov_b32_e32 v2, {data_d:#x}", - f"v_mov_b32_e32 v3, {init_m:#x}", - f"v_mov_b32_e32 v5, {SENTINEL:#x}", - "v_cmp_eq_u32_e32 vcc_lo, 0, v0", - "s_and_saveexec_b32 s4, vcc_lo", - f"global_atomic_{kind} v5, v1, {vdata}, s[0:1]{off_str} glc", - "s_mov_b32 exec_lo, s4", - "s_waitcnt vmcnt(0)", - "v_lshlrev_b32_e32 v6, 2, v0", - f"v_add_nc_u32_e32 v6, {OUT:#x}, v6", - "global_store_dword v6, v5, s[0:1]", - ] - eff = vaddr + inst_off - mem = run(body, {TARGET: init_m}, nlanes=2) - # Inactive lane 1 always preserves vdst sentinel - self.assertEqual(mem.get(OUT + 4), SENTINEL) - if should_run: - self.assertEqual(mem.get(OUT), init_m) - expected_m = { - "add": (init_m + data_d) & M32, - "swap": data_d, - "cmpswap": data_d, - "fmin": init_m, - "fmax": data_d, - }[kind] - self.assertEqual(mem.get(eff), expected_m) - else: - # Active unaligned lane receives 0 in vdst (not SENTINEL), memory untouched - self.assertEqual(mem.get(OUT), 0) - self.assertEqual(mem.get(TARGET), init_m) - self.assertNotIn(eff, mem) - - def test_global_atomic_x2_alignment(self): - m_lo, m_hi = 0x11112222, 0x33334444 - d_lo, d_hi = 0x55556666, 0x77778888 - for kind in ("swap", "and", "or", "xor"): - for vaddr, inst_off, should_run in ((TARGET + 2, 0, False), - (TARGET + 4, 0, False), - (TARGET, 4, False), - (TARGET + 4, 4, True)): - with self.subTest(op=kind, vaddr=hex(vaddr), inst_off=inst_off): - off_str = f" offset:{inst_off}" if inst_off else "" - body = [ - f"v_mov_b32_e32 v1, {vaddr:#x}", - f"v_mov_b32_e32 v2, {d_lo:#x}", - f"v_mov_b32_e32 v3, {d_hi:#x}", - f"v_mov_b32_e32 v4, {SENTINEL:#x}", - f"v_mov_b32_e32 v5, {SENTINEL2:#x}", - "v_cmp_eq_u32_e32 vcc_lo, 0, v0", - "s_and_saveexec_b32 s4, vcc_lo", - f"global_atomic_{kind}_x2 v[4:5], v1, v[2:3], s[0:1]{off_str} glc", - "s_mov_b32 exec_lo, s4", - "s_waitcnt vmcnt(0)", - "v_lshlrev_b32_e32 v6, 3, v0", - f"v_add_nc_u32_e32 v6, {OUT:#x}, v6", - "global_store_dwordx2 v6, v[4:5], s[0:1]", - ] - eff = vaddr + inst_off - init_mem = {TARGET: m_lo, TARGET + 4: m_hi, TARGET + 8: m_lo, TARGET + 12: m_hi} - mem = run(body, init_mem, nlanes=2) - # Inactive lane 1 always preserves vdst[0:1] - self.assertEqual((mem.get(OUT + 8), mem.get(OUT + 12)), (SENTINEL, SENTINEL2)) - if should_run: - self.assertEqual((mem.get(OUT), mem.get(OUT + 4)), (m_lo, m_hi)) - op_fn = {"swap": lambda a, b: b, "and": lambda a, b: a & b, - "or": lambda a, b: a | b, "xor": lambda a, b: a ^ b}[kind] - self.assertEqual((mem.get(eff), mem.get(eff + 4)), - (op_fn(m_lo, d_lo), op_fn(m_hi, d_hi))) - else: - self.assertEqual((mem.get(OUT), mem.get(OUT + 4)), (0, 0)) - self.assertEqual((mem.get(TARGET), mem.get(TARGET + 4)), (m_lo, m_hi)) - self.assertEqual((mem.get(TARGET + 8), mem.get(TARGET + 12)), (m_lo, m_hi)) - - def test_spirv_emits_alignment_guard(self): - cases = [ - (buf_rsrc_lines(0, 0, 0x100, RAW_W3) + ["v_mov_b32_e32 v1, 0", - "buffer_atomic_add v2, v1, s[8:11], 0 offen glc"], "%c3"), - (buf_rsrc_lines(0, 0, 0x100, RAW_W3) + ["v_mov_b32_e32 v1, 0", - "buffer_atomic_fmin v2, v1, s[8:11], 0 offen glc"], "%c3"), - (buf_rsrc_lines(0, 0, 0x100, RAW_W3) + ["v_mov_b32_e32 v1, 0", - "buffer_atomic_xor_x2 v[2:3], v1, s[8:11], 0 offen glc"], "%c7"), - (["v_mov_b32_e32 v1, 0", "global_atomic_add v5, v1, v2, s[0:1] glc"], "%c3"), - (["v_mov_b32_e32 v1, 0", "global_atomic_fmax v5, v1, v2, s[0:1] glc"], "%c3"), - (["v_mov_b32_e32 v1, 0", "global_atomic_swap_x2 v[4:5], v1, v[2:3], s[0:1] glc"], "%c7"), - ] - for body, mask_const in cases: - with self.subTest(insn=body[-1]): - spv = translate(body) - self.assertIn("OpUConvert %uint", spv) - self.assertIn("OpBitwiseAnd %uint", spv) - self.assertIn(mask_const, spv) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_buffer_atomics_x2.py b/tests/semantic/test_buffer_atomics_x2.py deleted file mode 100644 index 1fb130fcc..000000000 --- a/tests/semantic/test_buffer_atomics_x2.py +++ /dev/null @@ -1,114 +0,0 @@ -"""Value tests for RDNA2 buffer_atomic_{and,or,xor,swap}_x2, run through spirv_mini_interp on the CPU. - -M = op(M, DATA) on the 64-bit element (two dwords, low first) at the MUBUF address; with glc the old 64 bits come -back in vdata[0:1]. The translator does one 32-bit atomic per dword (exact memory for a bitwise op, and for an exchange -by one lane at a time: two lanes swapping into one element at once can tear it) and checks bounds for the whole 8-byte -element, all or nothing. The V# here is raw (OOB_SELECT 3): an access is in range -when offset + 8 <= num_records. Standard library only; no GPU, no game files. -""" -import os -import random -import struct -import sys -import tempfile -import unittest -import warnings - -HERE = os.path.dirname(os.path.abspath(__file__)) -ROOT = os.path.dirname(os.path.dirname(HERE)) -sys.dont_write_bytecode = True -sys.path.insert(0, os.environ.get("LEONIDA_TOOLS_DIR") or os.path.join(ROOT, "tools")) -sys.path.insert(0, HERE) - -import rdna2spirv # noqa: E402 -import spirv_mini_interp as si # noqa: E402 - -M32 = 0xFFFFFFFF -STUB_DXBC = b"DXBC" + bytes(24) + struct.pack("> 32 - - -def atomic_x2(kind, m, d, glc=True, offset=ELEM, records=RECORDS): - body = ["s_mov_b32 s8, 0", "s_mov_b32 s9, 0", f"s_mov_b32 s10, {records:#x}", "s_mov_b32 s11, 0x31016fac", - f"v_mov_b32_e32 v1, {offset:#x}", f"v_mov_b32_e32 v2, {d & M32:#x}", f"v_mov_b32_e32 v3, {d >> 32:#x}", - f"buffer_atomic_{kind}_x2 v[2:3], v1, s[8:11], 0 offen" + (" glc" if glc else ""), "s_waitcnt vmcnt(0)", - f"v_mov_b32_e32 v4, {OUT:#x}", "s_mov_b32 s10, 0x1000", "buffer_store_dwordx2 v[2:3], v4, s[8:11], 0 offen"] - mem = run(body, {offset: m & M32, offset + 4: m >> 32}) - return (mem.get(OUT), mem.get(OUT + 4)), (mem.get(offset), mem.get(offset + 4)) - - -class BufferAtomicsX2(unittest.TestCase): - def test_returning_forms(self): - for kind, fn in MODEL.items(): - for m in VALUES: - for d in VALUES[::2]: - with self.subTest(op=kind, m=hex(m), d=hex(d)): - self.assertEqual(atomic_x2(kind, m, d), (split(m), split(fn(m, d)))) - - def test_without_glc_vdata_is_kept(self): - m, d = 0xF0F0F0F0_0F0F0F0F, 0xFF00FF00_00FF00FF - for kind, fn in MODEL.items(): - with self.subTest(op=kind): - self.assertEqual(atomic_x2(kind, m, d, glc=False), (split(d), split(fn(m, d)))) - - def test_bounds_cover_the_whole_element(self): - m, d = 0x11111111_22222222, 0x0F0F0F0F_F0F0F0F0 - # ends exactly at num_records: in range - self.assertEqual(atomic_x2("xor", m, d, offset=RECORDS - 8), (split(m), split(m ^ d))) - # only the low dword in range, or none: memory unchanged, the returned value is 0 (as buffer_atomic) - for offset in (RECORDS - 4, RECORDS): - with self.subTest(offset=hex(offset)): - self.assertEqual(atomic_x2("xor", m, d, offset=offset), ((0, 0), split(m))) - - def test_seeded(self): - rng = random.Random(0xB0A2) - for _ in range(12): - kind, m, d = rng.choice(list(MODEL)), rng.getrandbits(64), rng.getrandbits(64) - with self.subTest(op=kind, m=hex(m), d=hex(d)): - self.assertEqual(atomic_x2(kind, m, d), (split(m), split(MODEL[kind](m, d)))) - - def test_carrying_forms_and_bad_data_rejected(self): - for line in ("buffer_atomic_add_x2 v[2:3], v1, s[8:11], 0 offen glc", - "buffer_atomic_cmpswap_x2 v[2:5], v1, s[8:11], 0 offen glc", - "buffer_atomic_or_x2 v2, v1, s[8:11], 0 offen glc"): - with self.subTest(line=line): - with self.assertRaises(rdna2spirv.Unsupported): - translate(["v_mov_b32_e32 v1, 0", line]) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_buffer_bounds_shared.py b/tests/semantic/test_buffer_bounds_shared.py deleted file mode 100644 index dbd8848a5..000000000 --- a/tests/semantic/test_buffer_bounds_shared.py +++ /dev/null @@ -1,46 +0,0 @@ -"""A multi-dword MUBUF access builds each bounds check once. - -buffer_address(parts=True) computes dword 0's check as `in_b`; the raw loads and stores used to ignore it and build the -same check again through parts(0), and each check added `offset + end` once for mode 0 and once for mode 3 when they -share the offset. The values are the same expressions, so the generated module simply must not contain the same -ulong sum twice. The OOB results themselves are covered by test_buffer_oob_select.py and test_vector_mem_mubuf.py. -Synthetic only. - - python -I -m unittest discover -s tests/semantic -p test_buffer_bounds_shared.py -v -""" -import collections -import os -import re -import sys -import unittest - -sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) - -import support # noqa: E402 - -# The V# comes from user SGPRs, so its OOB_SELECT is only known at run time and every mode's check is emitted. -ACCESSES = { - "load x4": ["buffer_load_dwordx4 v[5:8], v1, s[4:7], 0 offen", "exp mrt0 v5, v6, v7, v8 done vm"], - "load x2 with soffset": ["buffer_load_dwordx2 v[5:6], v1, s[4:7], s9 offen offset:16", - "exp mrt0 v5, v6, v6, v6 done vm"], - "store x4": ["buffer_store_dwordx4 v[5:8], v1, s[4:7], 0 offen", "exp mrt0 v5, v5, v5, v5 done vm"], -} - - -def ulong_sums(spvasm): - return collections.Counter(m.group(1) for m in re.finditer(r"= OpIAdd %ulong (%\S+ %\S+)$", spvasm, re.M)) - - -class SharedBoundsChecksTest(unittest.TestCase): - def test_no_bounds_sum_is_built_twice(self): - for name, body in ACCESSES.items(): - with self.subTest(access=name): - lines = ["v_mov_b32 v1, 16", "v_mov_b32 v5, 1.0", "v_mov_b32 v6, 2.0", "v_mov_b32 v7, 3.0", - "v_mov_b32 v8, 4.0"] + body + ["s_endpgm"] - spv = support.translate_lines("ps_buffer_bounds_shared", lines) - twice = {k: n for k, n in ulong_sums(spv).items() if n > 1} - self.assertEqual(twice, {}, f"{name}: the same offset + end built more than once") - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_buffer_f16_narrowing_hw.py b/tests/semantic/test_buffer_f16_narrowing_hw.py deleted file mode 100644 index 39c1b3ae9..000000000 --- a/tests/semantic/test_buffer_f16_narrowing_hw.py +++ /dev/null @@ -1,149 +0,0 @@ -"""f32 -> f16 narrowing in typed buffer stores to f16 formats and in d16 loads of 32-bit float formats (SHADER-358). - -Every expected word was read back from an AMD Radeon RDNA2 iGPU (gfx1036, Ryzen 9 9950X3D, Windows AMD driver -32.0.21045.16010) through tools/hw_oracle with AMD clang 23 (rocm-sdk-core 10.0.0), wave32 and wave64 alike, with -the same instruction and a V# of the same format (the runtime's selectors: X001, XY01). The hardware rounds toward -zero and gives +-65504 for a finite value past the f16 range (0x3f803000 stores 0x3c01, not 0x3c02; 65520 stores -0x7bff, not infinity); infinities stay infinite, f32 denormals give a signed zero, and a NaN keeps its sign and its -top payload bits. UNORM/SNORM d16 loads are different (nearest even, tests/semantic/test_buffer_load_format.py). - -MEASURED rows: (f32 word, buffer_store_format_x into 16_FLOAT, buffer_store_format_xy into 16_16_FLOAT of the -same value twice, buffer_load_format_d16_x from 32_FLOAT, buffer_load_format_d16_xy from 32_32_FLOAT of the same -value twice), the store words over a 0xdead0000 fill, the load words over a 0xdeadbeef destination. -""" -import os -import struct -import sys -import tempfile -import unittest -import warnings - -HERE = os.path.dirname(os.path.abspath(__file__)) -ROOT = os.path.dirname(os.path.dirname(HERE)) -sys.dont_write_bytecode = True -sys.path.insert(0, os.environ.get("LEONIDA_TOOLS_DIR") or os.path.join(ROOT, "tools")) -sys.path.insert(0, HERE) - -import rdna2spirv # noqa: E402 -import spirv_mini_interp as si # noqa: E402 - -STUB_DXBC = b"DXBC" + bytes(24) + struct.pack(" tuple: - """Translate a pixel shader whose V# (s[0:3], raw, 256 bytes) points at BASE with this format and selectors.""" - with tempfile.TemporaryDirectory() as tmp: - os.mkdir(os.path.join(tmp, "disasm")) - src = os.path.join(tmp, "disasm", "ps_narrow_int.s") - with open(os.path.join(tmp, "ps_narrow_int.dxbc"), "wb") as f: - f.write(STUB_DXBC) - with open(src, "w", encoding="utf-8") as f: - f.write("; test_buffer_format_narrow_int\n" - f"\ts_mov_b32 s0, {BASE:#x}\n\ts_mov_b32 s1, 0\n\ts_mov_b32 s2, 0x100\n" - f"\ts_mov_b32 s3, {fmt << 12 | dst_sel | 1 << 24 | 3 << 28:#x}\n\tv_mov_b32 v1, 0\n" + body) - with warnings.catch_warnings(): - warnings.simplefilter("ignore", ResourceWarning) - spv = rdna2spirv.translate(src) - return si.run_fragment(spv, memory=memory)["%out_mrt0"] - - -def load(fmt: int, dst_sel: int, d16: bool = False) -> tuple: - regs, dst = ("v[2:3]", "v2, v3, v2, v3") if d16 else ("v[2:5]", "v2, v3, v4, v5") - body = (f"\tbuffer_load_format_{'d16_' if d16 else ''}xyzw {regs}, v1, s[0:3], 0 offen\n" - f"\ts_waitcnt vmcnt(0)\n\texp mrt0 {dst} done vm\n\ts_endpgm\n") - return run(fmt, body, dst_sel, {BASE + 4 * i: w for i, w in enumerate(SOURCE)}) - - -def store(fmt: int, values: tuple, n: int, channels: int) -> tuple: - memory = {BASE: 0xDEAD0000, BASE + 4: 0xDEAD0000} - movs = "".join(f"\tv_mov_b32 v{2 + i}, {v:#x}\n" for i, v in enumerate(values[:n])) - regs = "v2" if n == 1 else f"v[2:{1 + n}]" - body = (movs + f"\tbuffer_store_format_{'xyzw'[:n]} {regs}, v1, s[0:3], 0 offen\n" - "\texp mrt0 v2, v2, v2, v2 done vm\n\ts_endpgm\n") - run(fmt, body, RUNTIME_SEL[channels], memory) - return memory[BASE], memory[BASE + 4] - - -def store_d16(fmt: int, pair: tuple, channels: int) -> tuple: - """buffer_store_format_d16_xyzw of two registers (x | y << 16, z | w << 16): each half is a 16-bit integer, signed - for SINT, then saturated or clamped like a full-width store.""" - memory = {BASE: 0xDEAD0000, BASE + 4: 0xDEAD0000} - body = (f"\tv_mov_b32 v2, {pair[0]:#x}\n\tv_mov_b32 v3, {pair[1]:#x}\n" - "\tbuffer_store_format_d16_xyzw v[2:3], v1, s[0:3], 0 offen\n\texp mrt0 v2, v2, v2, v2 done vm\n\ts_endpgm\n") - run(fmt, body, RUNTIME_SEL[channels], memory) - return memory[BASE], memory[BASE + 4] - - -class NarrowIntegerLoads(unittest.TestCase): - def test_measured_words(self): - for fmt, (xyzw, x011, d16) in LOADS.items(): - with self.subTest(fmt=fmt): - self.assertEqual(load(fmt, SEL_XYZW), xyzw, "DST_SEL XYZW") - self.assertEqual(load(fmt, SEL_X011), x011, "DST_SEL X011: 0 and integer 1") - self.assertEqual(load(fmt, SEL_XYZW, d16=True)[:2], d16, "d16") - - -class NarrowIntegerStores(unittest.TestCase): - def test_measured_words(self): - for (fmt, values, n), want in STORES.items(): - with self.subTest(fmt=fmt, values=values, n=n): - self.assertEqual(store(fmt, VALUES[values], n, CHANNELS[fmt]), want) - - def test_measured_d16_words(self): - # A d16 SINT half is sign-extended before the clamp: 0xff80 stores -128 (0x80) into 8_SINT, not 127. - for (fmt, pair), want in D16_STORES.items(): - with self.subTest(fmt=fmt, pair=pair): - self.assertEqual(store_d16(fmt, D16_VALUES[pair], CHANNELS[fmt]), want) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_buffer_formats_all.py b/tests/semantic/test_buffer_formats_all.py deleted file mode 100644 index ca580a998..000000000 --- a/tests/semantic/test_buffer_formats_all.py +++ /dev/null @@ -1,299 +0,0 @@ -"""Every GFX10 buffer data format the translator knows, decoded and encoded, against tools/buffer_format_fuzz.py's MODEL. - -MODEL (decode_element / encode_element there) is what the Radeon 880M (gfx1150, RDNA3.5, not RDNA2) did for every -pattern of tools/buffer_format_fuzz.py --oracle hw: 1.33 million validated elements over 63 formats on the 880M and the same on a real RDNA2, loads through a V# and -through tbuffer's own format, stores through both (docs/buffer_formats.md, docs/design.md "Typed buffer formats"). This -file holds the translated SPIR-V to it: the SPIR-V mini interpreter runs `buffer_load_format_xyzw` (the V# format and -tbuffer's own) and `buffer_store_format_xyzw` of every format added with the SCALED / SINT / 10_11_11 / 11_11_10 / -2_10_10_10 / 10_10_10_2 families, with edge values, NaN, infinity and denormals, and compares every word. - -Older formats are checked for their table entry and, for stores, against the model too (StoresOfTheOlderFormats); their -loads are covered by test_buffer_load_format.py, test_norm_decode.py and the GPU fixtures. -""" -import os -import random -import sys -import unittest - -import support -import spirv_mini_interp as si -import test_value_semantics as tv - -HERE = os.path.dirname(os.path.abspath(__file__)) -sys.path.insert(0, support.TOOLS_DIR) -import buffer_format_fuzz as model # noqa: E402 -import rdna2spirv # noqa: E402 - -IN_BASE, OUT_BASE = 0x1000, 0x2000 -OUT_V = 0x31016FAC # s[0:3] of the compute fixtures: raw, base 0 -SENTINEL = 0xDEAD0000 -DST_XYZW = 4 | 5 << 3 | 6 << 6 | 7 << 9 - -# Added with this change: every code the SCALED, SINT, small-float and 10:10:10:2 families add to Gen.FORMATS. -ADDED = (3, 4, 5, 6, 9, 10, 11, 12, 16, 17, 18, 19, 25, 26, 28, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, - 45, 46, 47, 48, 49, 51, 52, 53, 54, 55, - 58, 59, 61, 67, 68, 70) -# Of the formats above, the ones whose store the table covers (all; a SCALED store converts as its NORM format). -GFX10_ONLY = (30, 31, 32, 33, 34, 35, 37, 38, 39, 40, 41, 42, 46, 47) # no GFX11 spelling: a real RDNA2 validated them - - -def v_sharp_lines(reg, base, code): - w3 = 0x30000000 | code << 12 | DST_XYZW - return [f"s_mov_b32 s{reg}, {base:#x}", f"s_mov_b32 s{reg + 1}, 0", f"s_mov_b32 s{reg + 2}, 0x100", - f"s_mov_b32 s{reg + 3}, {w3:#x}"] - - -def translate_load(code, path): - if path == "mubuf": - fetch = "buffer_load_format_xyzw v[2:5], v1, s[4:7], 0 offen" - sharp = code - else: # tbuffer takes the format from the instruction, not the V# (32_FLOAT) - fetch = f"tbuffer_load_format_xyzw v[2:5], v1, s[4:7], 0 format:[BUF_FMT_{model.GFX10_NAMES[code]}] offen" - sharp = 22 - lines = ["v_cmpx_eq_u32_e32 0, v0", *v_sharp_lines(4, IN_BASE, sharp), "v_mov_b32 v1, 0", fetch, - "s_waitcnt vmcnt(0)", "buffer_store_dwordx4 v[2:5], off, s[0:3], 0", "s_endpgm"] - return support.translate_lines("cs_fmt_all_load", lines, fssm=tv.CS_BOUNDS_FSSM) - - -def translate_store(code, instr="xyzw"): - lines = ["v_cmpx_eq_u32_e32 0, v0", *v_sharp_lines(4, OUT_BASE, code), *v_sharp_lines(8, IN_BASE, 22), - "v_mov_b32 v1, 0", "buffer_load_dwordx4 v[2:5], v1, s[8:11], 0 offen", "s_waitcnt vmcnt(0)", - f"buffer_store_format_{instr} v[2:{5 if instr == 'xyzw' else 3}], v1, s[4:7], 0 offen", "s_endpgm"] - return support.translate_lines("cs_fmt_all_store", lines, fssm=tv.CS_BOUNDS_FSSM) - - -def run(spv, memory): - support.run_fragment(spv, inputs={"%wg_id": (0, 0, 0), "%local_id": (0, 0, 0)}, - push_constants=[0, 0, 0x100, OUT_V] + [0] * 28, memory=memory) - return memory - - -def words_of(data): - return [int.from_bytes(data[4 * i:4 * i + 4], "little") for i in range(4)] - - -SPECIAL = { # field values worth a lane each, whatever the format: the model's own edges plus these - "FLOAT": (0, 1, 0x3F, 0x40, 0x7BF, 0x7C0, 0x7C1, 0x7DF, 0x7FF, 0x3DF, 0x3E0, 0x3E1, 0x3FF, 0x20, 0x1F, 0x400, 0x3C00), -} - - -def load_elements(name, rng): - elems = model.load_patterns(name, rng, 3) - widths, nfmt = model.parse_name(name) - keep = elems[:2] + rng.sample(elems[2:], 24) - if nfmt == "FLOAT": - for c, w in enumerate(widths): - for v in SPECIAL["FLOAT"]: - if v < 1 << w: - comps = [rng.getrandbits(x) for x in widths] - comps[c] = v - keep.append(model.pack(widths, comps, rng, 0)) - for c, w in enumerate(widths): # every field at its own extremes, the other fields random - for v in (0, 1, (1 << w) - 1, 1 << (w - 1), (1 << (w - 1)) - 1, (1 << (w - 1)) + 1): - comps = [rng.getrandbits(x) for x in widths] - comps[c] = v - keep.append(model.pack(widths, comps, rng, 0)) - return keep - - -class FormatTable(unittest.TestCase): - def test_every_entry_agrees_with_its_gfx10_name(self): - """FORMATS[code] = (bytes, kind, widths from bit 0) must be what the name says, for the old entries too.""" - kinds = {"UNORM": "unorm", "SNORM": "snorm", "USCALED": "uscaled", "SSCALED": "sscaled", "SINT": "sint"} - for code, (size, kind, widths) in rdna2spirv.Gen.FORMATS.items(): - with self.subTest(code=code): - want_widths, nfmt = model.parse_name(model.GFX10_NAMES[code]) - self.assertEqual(widths, want_widths) - self.assertEqual(size, sum(widths) // 8) - if nfmt == "UINT": - self.assertIn(kind, ("uint", "u32")) - elif nfmt == "SINT": - self.assertIn(kind, ("sint", "i32") if widths != (32,) * len(widths) else ("i32",)) - elif nfmt == "FLOAT": - self.assertIn(kind, ("f32", "f16", "ufloat")) - else: - self.assertEqual(kind, kinds[nfmt]) - - def test_every_buffer_code_is_in_the_table(self): - for code in ADDED: - self.assertIn(code, rdna2spirv.Gen.FORMATS) - self.assertEqual([c for c in range(1, 78) if c not in rdna2spirv.Gen.FORMATS], []) - self.assertEqual(len(rdna2spirv.Gen.FORMATS), 77) - - -class LoadsMatchTheModel(unittest.TestCase): - def check(self, code, path): - name = model.GFX10_NAMES[code] - spv = translate_load(code, path) - rng = random.Random(code * 7 + (path == "mubuf")) - count = 0 - for e in load_elements(name, rng): - memory = {IN_BASE + 4 * i: w for i, w in enumerate(words_of(e))} - run(spv, memory) - got = [memory.get(4 * k, 0) for k in range(4)] - self.assertEqual(got, model.decode_element(name, e, path), (name, path, e[:model.element_size(name)].hex())) - count += 1 - return count - - def test_loads_through_the_v_sharp(self): - for code in ADDED: - with self.subTest(format=model.GFX10_NAMES[code]): - self.check(code, "mubuf") - - def test_loads_through_tbuffer_formats(self): - for code in ADDED: - with self.subTest(format=model.GFX10_NAMES[code]): - self.check(code, "mtbuf") - - -class StoresMatchTheModel(unittest.TestCase): - def test_stores_through_the_v_sharp(self): - for code in ADDED: - name = model.GFX10_NAMES[code] - with self.subTest(format=name): - spv = translate_store(code) - rng = random.Random(code * 13) - rows = model.store_inputs(name, rng) - for row in rng.sample(rows, 48): - data = b"".join(w.to_bytes(4, "little") for w in row) - memory = {IN_BASE + 4 * i: w for i, w in enumerate(row)} - memory.update({OUT_BASE + 4 * i: SENTINEL for i in range(4)}) - run(spv, memory) - got = b"".join(memory.get(OUT_BASE + 4 * i, 0).to_bytes(4, "little") for i in range(4)) - want = bytearray(b"".join(SENTINEL.to_bytes(4, "little") for _ in range(4))) - size = model.element_size(name) - want[:size] = model.encode_element(name, row) - self.assertEqual(got, bytes(want), (name, [f"{w:08x}" for w in row])) - - -class HandWorkedValues(unittest.TestCase): - """Values worked out by hand from the format definitions, so the model is not only checked against itself.""" - - def load(self, code, data, path="mubuf"): - memory = {IN_BASE + 4 * i: w for i, w in enumerate(words_of(bytes(data) + bytes(16 - len(data))))} - run(translate_load(code, path), memory) - return [memory.get(4 * k, 0) for k in range(4)] - - def test_uint_sint_8_zero_and_sign_extend(self): - self.assertEqual(self.load(5, [0xFF])[0], 0xFF) # 8_UINT - self.assertEqual(self.load(6, [0xFF])[0], 0xFFFFFFFF) # 8_SINT: -1 - self.assertEqual(self.load(6, [0x80])[0], 0xFFFFFF80) - self.assertEqual(self.load(12, [0x00, 0x80])[0], 0xFFFF8000) # 16_SINT - - def test_scaled_is_the_integer_as_float(self): - self.assertEqual(self.load(3, [0xFF])[0], 0x437F0000) # 8_USCALED: 255.0 - self.assertEqual(self.load(4, [0x80])[0], 0xC3000000) # 8_SSCALED: -128.0 - self.assertEqual(self.load(10, [0x00, 0x80])[0], 0xC7000000) # 16_SSCALED: -32768.0 - - def test_small_floats(self): - # 11_11_10_FLOAT (43): x is the 10 bit field in bits 9:0 (5 bit mantissa), y and z are 11 bit - # 10_11_11_FLOAT (36): x is the 11 bit field in bits 10:0 (6 bit mantissa), z the 10 bit one in 31:22 - one11 = 15 << 6 # 1.0 in 11 bits: exponent 15 - self.assertEqual(self.load(36, one11.to_bytes(4, "little"))[0], 0x3F800000) - self.assertEqual(self.load(43, (15 << 5).to_bytes(4, "little"))[0], 0x3F800000) - self.assertEqual(self.load(36, (0x7C0).to_bytes(4, "little"))[0], 0x7F800000) # infinity - self.assertEqual(self.load(36, (0x7C1).to_bytes(4, "little"))[0], 0x7F820000) # NaN, payload kept - self.assertEqual(self.load(36, (1).to_bytes(4, "little"))[0], 0x35800000) # 2^-20, a denormal - self.assertEqual(self.load(43, (1 << 22).to_bytes(4, "little"))[2], 0x36000000) # z field 2: 2 * 2^-20 - self.assertEqual(self.load(36, ((15 << 5) << 22).to_bytes(4, "little"))[2], 0x3F800000) # z, 10 bits: 15 << 5 - - def test_2_10_10_10_sint_and_snorm(self): - word = (1 << 30) | (0x201 << 20) | (0x1FF << 10) | 0x200 # w = 1, z = 0x201, y = 0x1FF, x = 0x200 - data = word.to_bytes(4, "little") - self.assertEqual(self.load(55, data), [0xFFFFFE00, 511, 0xFFFFFE01, 1]) - self.assertEqual(self.load(51, data)[0], 0xBF800000) # SNORM: the most negative code, -512, is -1 - self.assertEqual(self.load(51, data)[1], 0x3F800000) # +511 / 511 - self.assertEqual(self.load(51, data)[2], 0xBF800000) # 0x201 is -511: -511 / 511 - - def test_stores_hand_worked(self): - def store(code, regs): - memory = {IN_BASE + 4 * i: w for i, w in enumerate(regs)} - memory.update({OUT_BASE + 4 * i: SENTINEL for i in range(4)}) - run(translate_store(code), memory) - return b"".join(memory[OUT_BASE + 4 * i].to_bytes(4, "little") for i in range(4)) - - self.assertEqual(store(6, [0x100, 0, 0, 0])[:2], bytes([0x7F, 0x00])) # 8_SINT saturates to 127 - self.assertEqual(store(6, [0xFFFFFF00, 0, 0, 0])[0], 0x80) # ... and to -128 - self.assertEqual(store(5, [0x1FF, 0, 0, 0])[0], 0xFF) # 8_UINT saturates - self.assertEqual(store(3, [0x3F800000, 0, 0, 0])[0], 0xFF) # 8_USCALED stores like 8_UNORM - self.assertEqual(store(36, [0x3F800000, 0, 0, 0])[:4], (15 << 6).to_bytes(4, "little")) - self.assertEqual(store(36, [0x7F800000, 0, 0, 0])[:2], (0x7C0).to_bytes(2, "little")) # +inf - self.assertEqual(store(36, [0xBF800000, 0, 0, 0])[:2], bytes(2)) # negative gives 0 - self.assertEqual(store(36, [0x47FFE000, 0, 0, 0])[:2], (0x7BF).to_bytes(2, "little")) # 65504: the maximum - self.assertEqual(store(36, [0x4B000000, 0, 0, 0])[:2], (0x7BF).to_bytes(2, "little")) # too large: the maximum - self.assertEqual(store(45, [0x3F000000, 0, 0, 0])[0] & 3, 1) # 10_10_10_2_SNORM, 2 bit x: 0.5 -> 1 - - -class StoresOfTheOlderFormats(unittest.TestCase): - """Stores of formats that were in the table before the SCALED / SINT / small-float families, which used to differ from the - hardware in three places and now follow it (docs/buffer_formats.md): 16-bit float stores round toward zero and saturate, - UNORM / SNORM stores round the exact product once, and a two-component format takes channels (x, w) through a V# with identity selectors. - Measured on the Radeon 880M (gfx1150) and on a real RDNA2, gfx1036 (@AwkGrep256, #2022).""" - - def store(self, code, regs, instr="xyzw"): - memory = {IN_BASE + 4 * i: w for i, w in enumerate(regs)} - memory.update({OUT_BASE + 4 * i: SENTINEL for i in range(4)}) - run(translate_store(code, instr), memory) - return memory[OUT_BASE] - - def test_two_component_v_sharp_store_takes_x_and_w(self): - # buffer_store_format_xyzw of (1, 2, 3, 4) into 8_8_SINT writes 01 04, buffer_store_format_xy writes 01 00 - self.assertEqual(self.store(19, [1, 2, 3, 4]) & 0xFFFF, 0x0401) - self.assertEqual(self.store(19, [1, 2, 3, 4], "xy") & 0xFFFF, 0x0001) - self.assertEqual(self.store(27, [0x1111, 0x2222, 0x3333, 0x4444]), 0x44441111) # 16_16_UINT - - def test_two_component_store_with_the_runtime_selectors_takes_x_and_y(self): - # The runtime gives a two-component format DST_SEL X, Y, 0, 1 (gfx10_descriptors.h): channel y then, as measured natively - # (gfx1036, test_buffer_format_narrow_int.py; gfx1150: XY01, XY0W and XY00 all give (x, y), XYZW and XYZ1 give (x, w)) - for sel, want in ((4 | 5 << 3 | 0 << 6 | 1 << 9, 0x0201), (4 | 5 << 3 | 0 << 6 | 7 << 9, 0x0201), - (4 | 5 << 3 | 6 << 6 | 1 << 9, 0x0401), (4 | 0 << 3 | 0 << 6 | 1 << 9, 0x0401)): - lines = ["v_cmpx_eq_u32_e32 0, v0", *v_sharp_lines(4, OUT_BASE, 19), "v_mov_b32 v1, 0", - f"s_mov_b32 s7, {0x30000000 | 19 << 12 | sel:#x}", "v_mov_b32 v2, 1", "v_mov_b32 v3, 2", - "v_mov_b32 v4, 3", "v_mov_b32 v5, 4", "buffer_store_format_xyzw v[2:5], v1, s[4:7], 0 offen", "s_endpgm"] - spv = support.translate_lines("cs_fmt_all_sel", lines, fssm=tv.CS_BOUNDS_FSSM) - memory = {OUT_BASE: SENTINEL} - run(spv, memory) - self.assertEqual(memory[OUT_BASE] & 0xFFFF, want, hex(sel)) - - def test_two_component_tbuffer_store_takes_x_and_y(self): - lines = ["v_cmpx_eq_u32_e32 0, v0", *v_sharp_lines(4, OUT_BASE, 22), "v_mov_b32 v1, 0", - "v_mov_b32 v2, 1", "v_mov_b32 v3, 2", "v_mov_b32 v4, 3", "v_mov_b32 v5, 4", - "tbuffer_store_format_xyzw v[2:5], v1, s[4:7], 0 format:[BUF_FMT_8_8_SINT] offen", "s_endpgm"] - spv = support.translate_lines("cs_fmt_all_tbuf", lines, fssm=tv.CS_BOUNDS_FSSM) - memory = {OUT_BASE: SENTINEL} - run(spv, memory) - self.assertEqual(memory[OUT_BASE] & 0xFFFF, 0x0201) - - def test_16_float_store_rounds_toward_zero_and_saturates(self): - # 65520.0 is the tie between 65504 and infinity: nearest even says infinity, the hardware 0x7BFF - self.assertEqual(self.store(13, [0x47FFE000, 0, 0, 0]) & 0xFFFF, 0x7BFF) - self.assertEqual(self.store(13, [0x3EFFFFFF, 0, 0, 0]) & 0xFFFF, 0x37FF) # 0.49999997: truncated, not 0x3800 - self.assertEqual(self.store(13, [0x7149F2CA, 0, 0, 0]) & 0xFFFF, 0x7BFF) # 1e30 - self.assertEqual(self.store(13, [0x7F800001, 0, 0, 0]) & 0xFFFF, 0x7C01) # a NaN stays one - self.assertEqual(self.store(13, [0xFF800000, 0, 0, 0]) & 0xFFFF, 0xFC00) # -infinity - - def test_unorm_store_rounds_the_exact_product(self): - # 0x37C000C0 * 65535 is a hair under 1.5: the hardware stores 1, an f32 product rounds up to 1.5 and stores 2 - self.assertEqual(self.store(7, [0x37C000C0, 0, 0, 0]) & 0xFFFF, 1) - self.assertEqual(self.store(7, [0x3E99999A, 0, 0, 0]) & 0xFFFF, 19661) # 0.3 * 65535 - - def test_every_older_format_matches_the_model(self): - older = [c for c, (_, kind, _) in rdna2spirv.Gen.FORMATS.items() - if c not in ADDED and kind not in ("f32", "u32", "i32")] - for code in older: - name = model.GFX10_NAMES[code] - with self.subTest(format=name): - spv = translate_store(code) - rng = random.Random(code * 29) - for row in rng.sample(model.store_inputs(name, rng), 32): - memory = {IN_BASE + 4 * i: w for i, w in enumerate(row)} - memory.update({OUT_BASE + 4 * i: SENTINEL for i in range(4)}) - run(spv, memory) - got = b"".join(memory[OUT_BASE + 4 * i].to_bytes(4, "little") for i in range(4)) - want = bytearray(b"".join(SENTINEL.to_bytes(4, "little") for _ in range(4))) - want[:model.element_size(name)] = model.encode_element(name, row) - self.assertEqual(got, bytes(want), (name, [f"{w:08x}" for w in row])) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_buffer_load_format.py b/tests/semantic/test_buffer_load_format.py deleted file mode 100644 index fd0f0d170..000000000 --- a/tests/semantic/test_buffer_load_format.py +++ /dev/null @@ -1,404 +0,0 @@ -"""Semantic interpreter tests for buffer_load_format_* (the V# FORMAT decode in tools/rdna2spirv.py). - -The element is read from PhysicalStorageBuffer memory at V#.base + offset. An element under 4 bytes starts at a byte -shift inside its first dword, and the translation merges dword 1 above it: (w0 >> bsh) | (w1 << (32 - bsh)), picking -w0 when bsh is 0. The interpreter rejects shifts of 32 or more (undefined in SPIR-V, even on the discarded side of an -OpSelect), so every dword-aligned load here also checks that the merge keeps its shift below 32. - -Integer and f16 formats are used: their decode is exact, so the expected words need no rounding model. -""" -from __future__ import annotations - -import atexit -import os -import struct -import sys -import tempfile -import unittest -import warnings - -HERE = os.path.dirname(os.path.abspath(__file__)) -ROOT = os.path.dirname(os.path.dirname(HERE)) -TOOLS_DIR = os.environ.get("LEONIDA_TOOLS_DIR") or os.path.join(ROOT, "tools") - -sys.dont_write_bytecode = True -sys.path.insert(0, TOOLS_DIR) -sys.path.insert(0, HERE) - -import rdna2spirv # noqa: E402 -import spirv_mini_interp as si # noqa: E402 - -STUB_DXBC = b"DXBC" + bytes(24) + struct.pack(" tuple: - """Return four MRT words for a formatted load. D16 packs two components per register. - For a fixed-format load, pass its instruction name in op and its optional format modifier in mods.""" - if _TMP_DIR is None: - setUpModule() - suffix = ("d16_" if d16 else "") + "xyzw"[:ncomp] - nregs = (ncomp + 1) // 2 if d16 else ncomp - vdata = "v2" if nregs == 1 else f"v[2:{1 + nregs}]" - regs = [f"v{2 + min(i, nregs - 1)}" for i in range(4)] - seed = "\tv_mov_b32 v2, 0x12345678\n\tv_mov_b32 v3, 0xa9bcdef0\n" if d16 else "" - asm = ( - "; test_buffer_load_format\n" - f"\ts_mov_b32 s0, {BASE:#x}\n" - "\ts_mov_b32 s1, 0\n" # base high bits 0, stride 0 (raw) - "\ts_mov_b32 s2, 0x100\n" # num_records (bytes) - f"\ts_mov_b32 s3, {fmt << 12 | dst_sel | 0x30000000:#x}\n" - f"\tv_mov_b32 v1, {offset:#x}\n" - f"{seed}" - f"\t{op}_{suffix} {vdata}, v1, s[0:3], 0{mods} offen\n" - "\ts_waitcnt vmcnt(0)\n" - f"\texp mrt0 {', '.join(regs)} done vm\n" - "\ts_endpgm\n" - ) - with open(_SRC_PATH, "w", encoding="utf-8") as f: - f.write(asm) - with warnings.catch_warnings(): - warnings.simplefilter("ignore", ResourceWarning) - spv = rdna2spirv.translate(_SRC_PATH) - return si.run_fragment(spv, memory=dict(memory if memory is not None else MEMORY))["%out_mrt0"] - - -def f32_bits(x: float) -> int: - return struct.unpack(" int: - return struct.unpack(" 1.0 and - 0x00 -> 0.0, so the expected words are exact. - """ - - MEM = {BASE: 0x112200FF} - EXPLICIT = " format:[BUF_FMT_8_UNORM]" - - def tload(self, offset, ncomp, mods=""): - return load_format(FMT_U32, offset, ncomp, memory=self.MEM, op="tbuffer_load_format", mods=mods) - - def test_x_unorm_endpoints_ignore_descriptor_format(self): - for off, want in ((0, 0x3F800000), (1, 0)): - with self.subTest(off=off): - self.assertEqual(self.tload(off, 1)[0], want) - - def test_every_suffix_matches_explicit_8_unorm(self): - for ncomp in (1, 2, 3, 4): - with self.subTest(suffix="xyzw"[:ncomp]): - got = self.tload(0, ncomp)[:ncomp] - self.assertEqual(got[0], 0x3F800000) - self.assertEqual(got, self.tload(0, ncomp, self.EXPLICIT)[:ncomp]) - - def test_packed_load_uses_instruction_format(self): - # The V# declares one u32. The instruction specifies four u8s at byte 4: EF BE AD DE. - expected = ((0x123400EF,), (0x00BE00EF,), (0x00BE00EF, 0xA9BC00AD), (0x00BE00EF, 0x00DE00AD)) - for ncomp, want in enumerate(expected, 1): - with self.subTest(ncomp=ncomp): - got = load_format(FMT_U32, 4, ncomp, d16=True, op="tbuffer_load_format", - mods=" format:[BUF_FMT_8_8_8_8_UINT]") - self.assertEqual(got[:len(want)], want) - - def test_fixed_format_identity_ignores_descriptor_selectors(self): - # Descriptor selectors are 0,0,0,1. MTBUF supplies its own X000, XY00 or XYZW. - for fmt, source, want in (("32_UINT", 0x44, (0x44, 0, 0, 0)), - ("16_16_UINT", 0x00330044, (0x44, 0x33, 0, 0)), - ("8_8_8_8_UINT", 0x11223344, (0x44, 0x33, 0x22, 0x11))): - for d16 in (False, True): - with self.subTest(fmt=fmt, d16=d16): - got = load_format(FMT_U32, 0, 4, dst_sel=1 << 9, memory={BASE: source}, - d16=d16, op="tbuffer_load_format", - mods=f" format:[BUF_FMT_{fmt}]") - if d16: - self.assertEqual(got[:2], (want[0] | want[1] << 16, want[2] | want[3] << 16)) - else: - self.assertEqual(got, want) - self.assertEqual(load_format(FMT_UINT8X4, 0, 4, dst_sel=1 << 9), (0, 0, 0, 1)) - - def test_invalid_descriptor_suppresses_fixed_format_load(self): - # Same address, 256-byte bound and instruction format. Only the V# FORMAT changes. - cases = ((False, 4, (0x44, 0x33, 0x22, 0x11), (0, 0, 0, 0)), - (True, 3, (0x00330044, 0xa9bc0022), (0, 0xa9bc0000))) - for d16, n, bound, unbound in cases: - for fmt, want in ((FMT_U32, bound), (0, unbound)): - with self.subTest(d16=d16, fmt=fmt): - got = load_format(fmt, 0, n, memory={BASE: 0x11223344}, d16=d16, - op="tbuffer_load_format", mods=" format:[BUF_FMT_8_8_8_8_UINT]") - self.assertEqual(got[:len(want)], want) - - def test_packed_default_8_unorm(self): - # The first byte is 0xff: 1.0 in f16 is 0x3c00. Preserve the upper destination half. - got = load_format(FMT_U32, 0, 1, memory=self.MEM, d16=True, op="tbuffer_load_format") - self.assertEqual(got[0], 0x12343C00) - - def test_explicit_invalid_still_rejected(self): - with self.assertRaises(rdna2spirv.Unsupported): - self.tload(0, 1, " format:[BUF_FMT_INVALID]") - - -class InterpreterConversions(unittest.TestCase): - """The ops the format decode needs from spirv_mini_interp: integer to float and GLSL FMin/FMax.""" - - HEADER = ( - "OpCapability Shader\n%glsl = OpExtInstImport \"GLSL.std.450\"\nOpMemoryModel Logical GLSL450\n" - "OpEntryPoint Fragment %main \"main\" %out\n%void = OpTypeVoid\n%fn = OpTypeFunction %void\n" - "%uint = OpTypeInt 32 0\n%float = OpTypeFloat 32\n%_ptr_Output_uint = OpTypePointer Output %uint\n" - "%out = OpVariable %_ptr_Output_uint Output\n" - ) - - def run_expr(self, consts, body): - text = (self.HEADER + consts + "%main = OpFunction %void None %fn\n%entry = OpLabel\n" + body - + "%bits = OpBitcast %uint %r\nOpStore %out %bits\nOpReturn\nOpFunctionEnd\n") - return si.run_fragment(text)["%out"][0] - - def test_convert_u_and_s_to_f(self): - consts = "%c = OpConstant %uint 4294967295\n" - self.assertEqual(self.run_expr(consts, "%r = OpConvertUToF %float %c\n"), 0x4F800000) # 4294967296.0 - self.assertEqual(self.run_expr(consts, "%r = OpConvertSToF %float %c\n"), 0xBF800000) # -1.0 - - def test_fmin_fmax(self): - consts = "%a = OpConstant %float 1.5\n%b = OpConstant %float -2\n" - self.assertEqual(self.run_expr(consts, "%r = OpExtInst %float %glsl FMax %a %b\n"), 0x3FC00000) - self.assertEqual(self.run_expr(consts, "%r = OpExtInst %float %glsl FMin %a %b\n"), 0xC0000000) - - def test_fdiv_correctly_rounded(self): - consts = "%a = OpConstant %float 3\n%b = OpConstant %float 255\n" - self.assertEqual(self.run_expr(consts, "%r = OpFDiv %float %a %b\n"), 0x3C40C0C1) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_buffer_load_sub.py b/tests/semantic/test_buffer_load_sub.py deleted file mode 100644 index 6808d68b7..000000000 --- a/tests/semantic/test_buffer_load_sub.py +++ /dev/null @@ -1,234 +0,0 @@ -"""Semantic interpreter tests for sub-dword MUBUF loads and GFX10_FORMAT_8_UINT (code 5). - -Covers the remaining translator rules needed by XboxBvhBuilder.dll (#1813 follow-ups): - - buffer_load_ubyte, buffer_load_sbyte, buffer_load_ushort, buffer_load_sshort - (all byte offsets 0..7 including dword-crossing 16-bit loads at addr % 4 == 3, zero/sign extension, - OOB_SELECT modes 0/1/2/3 at exact element-end boundaries, inactive lanes preserving vdst, and rejected forms) - - tbuffer_load_format_* and buffer_load_format_* with GFX10_FORMAT_8_UINT (code 5: 1-byte unsigned integer, - byte offsets 0..3, OOB check, invalid V# format 0 suppression, and DST_SEL integer 1). - -Standard library only; no GPU, no LLVM, no game files. -""" -from __future__ import annotations - -import os -import struct -import sys -import tempfile -import unittest -import warnings - -HERE = os.path.dirname(os.path.abspath(__file__)) -ROOT = os.path.dirname(os.path.dirname(HERE)) -sys.dont_write_bytecode = True -sys.path.insert(0, os.environ.get("LEONIDA_TOOLS_DIR") or os.path.join(ROOT, "tools")) -sys.path.insert(0, HERE) - -import rdna2spirv # noqa: E402 -import spirv_mini_interp as si # noqa: E402 - -STUB_DXBC = b"DXBC" + bytes(24) + struct.pack(" 4 -> OOB returns 0 without reading dword 1. - self.assertEqual(buf_load("buffer_load_ushort", 3, num_records=4, memory={BASE: MEMORY[BASE]}), 0) - # num_records 5 allows the dword-crossing ushort at offset 3..4. - self.assertEqual(buf_load("buffer_load_ushort", 3, num_records=5), BYTES[3] | (BYTES[4] << 8)) - - def test_structured_oob_modes(self): - # Mode 0 (STRUCTURED_WITH_OFFSET): idx < num_records and off + size <= stride. - self.assertEqual(buf_load("buffer_load_ushort", 2, num_records=2, stride=4, oob_mode=0, idx=1), - BYTES[6] | (BYTES[7] << 8)) - self.assertEqual(buf_load("buffer_load_ushort", 3, num_records=2, stride=4, oob_mode=0, idx=0), 0) - self.assertEqual(buf_load("buffer_load_ushort", 0, num_records=1, stride=4, oob_mode=0, idx=1), 0) - # Mode 2 (DISABLED): only num_records == 0 is OOB. - self.assertEqual(buf_load("buffer_load_ushort", 0, num_records=0, stride=4, oob_mode=2), 0) - - def test_inactive_lane_preserves_vdst(self): - w3 = (3 << 28) | (20 << 12) - body = [ - f"s_mov_b32 s4, {BASE:#x}", "s_mov_b32 s5, 0", "s_mov_b32 s6, 8", f"s_mov_b32 s7, {w3:#x}", - "v_mov_b32_e32 v1, 2", "v_mov_b32_e32 v5, 0xcafebabe", - "v_cmp_eq_u32_e32 vcc_lo, 0, v0", - "s_and_saveexec_b32 s8, vcc_lo", - "buffer_load_ushort v5, v1, s[4:7], 0 offen", - "s_mov_b32 exec_lo, s8", - "s_waitcnt vmcnt(0)", - "v_lshlrev_b32_e32 v6, 2, v0", - f"v_add_nc_u32_e32 v6, {OUT:#x}, v6", - "global_store_dword v6, v5, s[0:1]", - ] - mem = run_cs(body, nlanes=2) - self.assertEqual(mem.get(OUT), BYTES[2] | (BYTES[3] << 8)) - self.assertEqual(mem.get(OUT + 4), 0xCAFEBABE) - - def test_rejected_sub_dword_forms(self): - for line in ("buffer_load_ushort v5, v1, s[4:7], 0 offen lds", - "buffer_load_ushort v5, v1, s[4:7], 0 offen tfe", - "buffer_load_ushort v5, v1, s[4:7], 0 offen d16"): - with self.subTest(line=line): - with self.assertRaises(rdna2spirv.Unsupported): - translate(["s_mov_b32 s4, 0", "s_mov_b32 s5, 0", "s_mov_b32 s6, 8", "s_mov_b32 s7, 0", line]) - - -class TypedLoadAlignmentTests(unittest.TestCase): - def test_two_byte_typed_load_alignment(self): - with open(os.path.join(HERE, "fixtures", "typed_load_alignment.asm"), encoding="utf-8") as fixture: - loads = [line.strip() for line in fixture if line.strip() and not line.startswith(";")] - # MUBUF takes its format and selector from the descriptor. MTBUF uses - # the instruction format even when the descriptor names an 8-bit format. - cases = ((0, 0, 0x3100BFAC, 0x807F, 0x807F), (0, 1, 0x3100BFAC, 0, 0), - (0, 3, 0x3100BFAC, 0, 0), (1, 0, 0x3100BFAC, 0, 0), - (1, 1, 0x3100BFAC, 0x01FF, 0x01FF), (0, 7, 0x3100BFAC, 0, 0), - (0, 1, 0x31005FAC, 0x80, 0), (0, 1, 0x3100BFA9, 1, 0)) - for base_delta, offset, descriptor, mubuf, mtbuf in cases: - with self.subTest(base_delta=base_delta, offset=offset, descriptor=descriptor): - body = [f"s_mov_b32 s4, {BASE + base_delta:#x}", "s_mov_b32 s5, 0", - "s_mov_b32 s6, 8", f"s_mov_b32 s7, {descriptor:#x}", f"v_mov_b32_e32 v1, {offset}"] - mem = run_cs(body + loads) - self.assertEqual((mem[OUT], mem[OUT + 4]), (mubuf, mtbuf)) - - -class Format8UintTests(unittest.TestCase): - def test_tbuffer_load_format_x_8_uint_all_byte_offsets(self): - # V# has a non-zero format (code 20 = 32_UINT); MTBUF uses its own BUF_FMT_8_UINT (code 5) and identity X000. - w3 = (3 << 28) | (20 << 12) | DST_SEL_X_0_1_1 - for off in range(4): - with self.subTest(off=off): - body = [ - f"s_mov_b32 s4, {BASE:#x}", "s_mov_b32 s5, 0", "s_mov_b32 s6, 4", f"s_mov_b32 s7, {w3:#x}", - f"v_mov_b32_e32 v1, {off:#x}", - "tbuffer_load_format_x v5, v1, s[4:7], 0 format:[BUF_FMT_8_UINT] offen", - "s_waitcnt vmcnt(0)", - f"v_mov_b32_e32 v6, {OUT:#x}", - "global_store_dword v6, v5, s[0:1]", - ] - mem = run_cs(body) - self.assertEqual(mem.get(OUT), BYTES[off]) - - def test_tbuffer_8_uint_oob_and_invalid_vsharp_format(self): - # OOB at off == num_records -> 0; INVALID V# format (0) suppresses MTBUF even in bounds -> 0. - for off, vfmt, expected in ((4, 20, 0), (1, 0, 0), (1, 5, BYTES[1])): - w3 = (3 << 28) | (vfmt << 12) | (4 | (5 << 3) | (6 << 6) | (7 << 9)) - with self.subTest(off=off, vfmt=vfmt): - body = [ - f"s_mov_b32 s4, {BASE:#x}", "s_mov_b32 s5, 0", "s_mov_b32 s6, 4", f"s_mov_b32 s7, {w3:#x}", - f"v_mov_b32_e32 v1, {off:#x}", - "tbuffer_load_format_x v5, v1, s[4:7], 0 format:[BUF_FMT_8_UINT] offen", - "s_waitcnt vmcnt(0)", - f"v_mov_b32_e32 v6, {OUT:#x}", - "global_store_dword v6, v5, s[0:1]", - ] - mem = run_cs(body) - self.assertEqual(mem.get(OUT), expected) - - def test_mubuf_8_uint_dst_sel_integer_one(self): - # V# FORMAT = 5 (GFX10_FORMAT_8_UINT), DST_SEL = (X, 0, 1, 1) -> integer 1, not 1.0f. - w3 = (3 << 28) | (5 << 12) | DST_SEL_X_0_1_1 - body = [ - f"s_mov_b32 s4, {BASE:#x}", "s_mov_b32 s5, 0", "s_mov_b32 s6, 4", f"s_mov_b32 s7, {w3:#x}", - "v_mov_b32_e32 v1, 2", - "buffer_load_format_xyzw v[8:11], v1, s[4:7], 0 offen", - "s_waitcnt vmcnt(0)", - f"v_mov_b32_e32 v6, {OUT:#x}", - "global_store_dwordx4 v6, v[8:11], s[0:1]", - ] - mem = run_cs(body) - self.assertEqual([mem.get(OUT + 4 * i) for i in range(4)], [BYTES[2], 0, 1, 1]) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_buffer_oob_dst_sel.py b/tests/semantic/test_buffer_oob_dst_sel.py deleted file mode 100644 index f8b997cb2..000000000 --- a/tests/semantic/test_buffer_oob_dst_sel.py +++ /dev/null @@ -1,333 +0,0 @@ -"""Semantic regression tests for out-of-bounds typed buffer loads with DST_SEL=1 (SHADER-429). - -Measured natively on RDNA2 (gfx1036, wave32 and wave64, 746 kernels via tools/hw_oracle): - * When a MUBUF buffer_load_format_{x,xy,xyz,xyzw} or buffer_load_format_d16_{x,xy,xyz,xyzw} is out of bounds - (any OOB_SELECT mode, num_records == 0, partial-element spill, or swizzled OOB), memory is not read and - data channels (DST_SEL 4..7) decode as 0, while V# DST_SEL still runs: DST_SEL=0 produces 0 and DST_SEL=1 - produces 1.0 (0x3F800000, d16 0x3C00) iff V# FORMAT[6:0] is a valid float/normalized/scaled code (1..77 - ending in _UNORM, _SNORM, _USCALED, _SSCALED, or _FLOAT), and integer 1 (0x00000001, d16 0x0001) for - UINT/SINT, INVALID (0), and reserved codes (78..127). - * d16_x and d16_xyz preserve the unaddressed upper 16 bits of the final destination VGPR. - * MTBUF tbuffer_load_format_* ignores V# DST_SEL on both in-bounds and out-of-bounds / INVALID loads, using - identity selectors X000/XY00/XYZ0/XYZW so out-of-bounds and FORMAT=0 loads return 0 in every addressed channel. - * Inactive EXEC lanes leave destination VGPRs untouched. -""" -from __future__ import annotations - -import json -import os -import shutil -import subprocess -import sys -import tempfile -import unittest - -HERE = os.path.dirname(os.path.abspath(__file__)) -ROOT = os.path.dirname(os.path.dirname(HERE)) -TOOLS_DIR = os.environ.get("LEONIDA_TOOLS_DIR") or os.path.join(ROOT, "tools") - -sys.dont_write_bytecode = True -if TOOLS_DIR not in sys.path: - sys.path.insert(0, TOOLS_DIR) -if HERE not in sys.path: - sys.path.insert(0, HERE) - -import rdna2spirv # noqa: E402 -import spirv_mini_interp as si # noqa: E402 -import support # noqa: E402 -import test_value_semantics as tv # noqa: E402 - -BASE = 0x1000 -OUT_V = 0x31016FAC # RAW output V# at base 0 -DST_X_0_1_1 = 4 | (0 << 3) | (1 << 6) | (1 << 9) -DST_1_Y_Z_W = 1 | (5 << 3) | (6 << 6) | (7 << 9) -DST_1_1_1_1 = 1 | (1 << 3) | (1 << 6) | (1 << 9) -SEED0, SEED1, SEED2, SEED3 = 0x12345678, 0xA9BCDEF0, 0xCAFEBABE, 0x0F0E0D0C -FLOAT_SUFFIXES = ("_UNORM", "_SNORM", "_USCALED", "_SSCALED", "_FLOAT") - -with open(os.path.join(TOOLS_DIR, "gfx10_formats.json"), encoding="utf-8") as _f: - GFX10_FORMAT_NAMES = {int(k): v for k, v in json.load(_f).items()} - -# 12 user SGPRs (s[0:11] from push constants), no TGID SGPRs, 64x1x1 threads. -CS_12_USER_FSSM = tv._fssm(12 << 1, (64, 1, 1)) - - -def word3(fmt_code: int, dst_sel: int, oob_select: int = 3, swz_idx_stride: int = 0) -> int: - return ( - (dst_sel & 0xFFF) - | ((fmt_code & 0x7F) << 12) - | ((swz_idx_stride & 0x3) << 21) - | (1 << 24) - | ((oob_select & 0x3) << 28) - ) - - -class OobTypedLoadDstSelTests(unittest.TestCase): - def _run_cs( - self, - lines: list[str], - *, - push_constants: list[int] | None = None, - preload: dict[int, int] | None = None, - wave64: bool = False, - name: str = "cs_oob_dst_sel", - ) -> tuple[tv.ReadLog, str]: - spv = support.translate_lines(name, lines, fssm=CS_12_USER_FSSM) - mem = tv.ReadLog(preload if preload is not None else { - BASE: 0x3F000000, - BASE + 4: 0x40000000, - BASE + 8: 0x00030002, - BASE + 12: 0x04030201, - }) - pcs = push_constants if push_constants is not None else ([0, 0, 0x100, OUT_V] + [0] * 28) - if wave64: - si.run_workgroup( - spv, - 64, - 64, - inputs_for=lambda i: {"%wg_id": (0, 0, 0), "%local_id": (i, 0, 0), "%sg_lane": i}, - push_constants=pcs, - memory=mem, - ) - else: - support.run_fragment( - spv, - inputs={"%wg_id": (0, 0, 0), "%local_id": (0, 0, 0)}, - push_constants=pcs, - memory=mem, - ) - return mem, spv - - def test_all_supported_formats_preserve_dst_sel_one_when_oob(self): - """Runtime V# sweep across every format in Gen.FORMATS (xyzw, d16_xyzw, d16_xyz, d16_x).""" - lines = [ - "v_cmpx_eq_u32_e32 0, v0", - # s[4:7] and s[8:11] come from push constants; offset v1 = 0x100 is past num_records = 16. - "v_mov_b32 v1, 0x100", - f"v_mov_b32 v4, {SEED0:#x}", - f"v_mov_b32 v5, {SEED1:#x}", - f"v_mov_b32 v6, {SEED2:#x}", - f"v_mov_b32 v7, {SEED3:#x}", - "buffer_load_format_xyzw v[4:7], v1, s[4:7], 0 offen", - "s_waitcnt vmcnt(0)", - "buffer_store_dwordx4 v[4:7], off, s[0:3], 0", - f"v_mov_b32 v8, {SEED0:#x}", - f"v_mov_b32 v9, {SEED1:#x}", - "buffer_load_format_d16_xyzw v[8:9], v1, s[4:7], 0 offen", - "s_waitcnt vmcnt(0)", - "buffer_store_dwordx2 v[8:9], off, s[0:3], 0 offset:16", - f"v_mov_b32 v10, {SEED0:#x}", - f"v_mov_b32 v11, {SEED1:#x}", - "buffer_load_format_d16_xyz v[10:11], v1, s[8:11], 0 offen", - "s_waitcnt vmcnt(0)", - "buffer_store_dwordx2 v[10:11], off, s[0:3], 0 offset:24", - f"v_mov_b32 v12, {SEED0:#x}", - "buffer_load_format_d16_x v12, v1, s[8:11], 0 offen", - "s_waitcnt vmcnt(0)", - "buffer_store_dword v12, off, s[0:3], 0 offset:32", - "s_endpgm", - ] - spv = support.translate_lines("cs_oob_all_fmts", lines, fssm=CS_12_USER_FSSM) - for code, (_, kind, _) in sorted(rdna2spirv.Gen.FORMATS.items()): - is_int = kind in ("u32", "i32", "uint", "sint") - one32 = 1 if is_int else 0x3F800000 - one16 = 1 if is_int else 0x3C00 - pcs = ( - [0, 0, 0x100, OUT_V] - + [BASE, 0, 16, word3(code, DST_X_0_1_1, 3)] - + [BASE, 0, 16, word3(code, DST_1_Y_Z_W, 3)] - + [0] * 20 - ) - mem = tv.ReadLog({BASE: 0x3F000000, BASE + 4: 0x40000000, BASE + 8: 0x00030002, BASE + 12: 0x04030201}) - support.run_fragment( - spv, - inputs={"%wg_id": (0, 0, 0), "%local_id": (0, 0, 0)}, - push_constants=pcs, - memory=mem, - ) - with self.subTest(code=code, kind=kind): - self.assertEqual(mem.reads, []) - self.assertEqual([dict.get(mem, 4 * i, 0) for i in range(4)], [0, 0, one32, one32]) - self.assertEqual([dict.get(mem, 16 + 4 * i, 0) for i in range(2)], [0, (one16 << 16) | one16]) - self.assertEqual( - [dict.get(mem, 24 + 4 * i, 0) for i in range(2)], - [one16, SEED1 & 0xFFFF0000], - ) - self.assertEqual(dict.get(mem, 32, 0), (SEED0 & 0xFFFF0000) | one16) - - def test_all_128_gfx10_7bit_format_codes_match_rdna2_hardware_table(self): - """All 128 7-bit V# FORMAT codes (0..127) match the native gfx1036 sweep for both f32 and d16.""" - lines = [ - "v_cmpx_eq_u32_e32 0, v0", - "v_mov_b32 v1, 0x100", - f"v_mov_b32 v4, {SEED0:#x}", - f"v_mov_b32 v5, {SEED0:#x}", - "buffer_load_format_x v4, v1, s[4:7], 0 offen", - "buffer_load_format_d16_x v5, v1, s[4:7], 0 offen", - "s_waitcnt vmcnt(0)", - "buffer_store_dwordx2 v[4:5], off, s[0:3], 0", - "s_endpgm", - ] - spv = support.translate_lines("cs_oob_128_fmts", lines, fssm=CS_12_USER_FSSM) - for code in range(128): - is_flt = GFX10_FORMAT_NAMES.get(code, "").endswith(FLOAT_SUFFIXES) - want32 = 0x3F800000 if is_flt else 1 - want16 = (SEED0 & 0xFFFF0000) | (0x3C00 if is_flt else 1) - pcs = [0, 0, 0x100, OUT_V, BASE, 0, 16, word3(code, 1, 3)] + [0] * 24 - mem = tv.ReadLog({BASE: 0xDEADBEEF}) - support.run_fragment( - spv, - inputs={"%wg_id": (0, 0, 0), "%local_id": (0, 0, 0)}, - push_constants=pcs, - memory=mem, - ) - with self.subTest(code=code, name=GFX10_FORMAT_NAMES.get(code, "RESERVED")): - self.assertEqual(mem.reads, []) - self.assertEqual([dict.get(mem, 0, 0), dict.get(mem, 4, 0)], [want32, want16]) - - def test_oob_select_modes_partial_spill_unaligned_and_swizzled(self): - """Literal V# checks across OOB_SELECT 0..3, partial element spill, mid-dword OOB offset, and swizzled OOB.""" - fmt_f32x4, fmt_u32, fmt_i32 = 77, 20, 21 - cases = [ - # Partial element spill: 16-byte RGBA32F at offset 8 of a 16-byte raw buffer. - ("partial_spill", 0, 16, word3(fmt_f32x4, DST_X_0_1_1, 3), "v1", [8], "offen", [0, 0, 0x3F800000, 0x3F800000]), - # Mid-dword OOB byte offset (bsh = 24): shifts on zero words stay defined and produce 0 / 1.0f. - ("unaligned_oob", 0, 16, word3(fmt_f32x4, DST_X_0_1_1, 3), "v1", [0x103], "offen", [0, 0, 0x3F800000, 0x3F800000]), - # Mode 0 structured: idx 4 >= num_records 4 (stride 16). - ("mode0_idx", 16 << 16, 4, word3(fmt_f32x4, DST_X_0_1_1, 0), "v[1:2]", [4, 0], "idxen offen", [0, 0, 0x3F800000, 0x3F800000]), - # Mode 0 structured: idx 0 < num_records 4, off 16 + 4 > stride 16. - ("mode0_off", 16 << 16, 4, word3(fmt_u32, DST_X_0_1_1, 0), "v[1:2]", [0, 16], "idxen offen", [0, 0, 1, 1]), - # Mode 1 index-only: idx 4 >= num_records 4. - ("mode1_idx", 4 << 16, 4, word3(fmt_i32, DST_X_0_1_1, 1), "v1", [4], "idxen", [0, 0, 1, 1]), - # Mode 2 disabled except when num_records == 0. - ("mode2_nr0", 0, 0, word3(fmt_f32x4, DST_X_0_1_1, 2), "v1", [0], "offen", [0, 0, 0x3F800000, 0x3F800000]), - # Swizzled OOB: SWIZZLE_ENABLE = 1, stride 16, idx 4 >= num_records 4. - ("swizzled_oob", (1 << 31) | (16 << 16), 4, word3(fmt_f32x4, DST_X_0_1_1, 0), "v[1:2]", [4, 0], "idxen offen", [0, 0, 0x3F800000, 0x3F800000]), - ] - for tag, w1, nr, w3, vaddr, vals, mods, want in cases: - setup = [f"v_mov_b32 v{1 + i}, {v:#x}" for i, v in enumerate(vals)] - lines = [ - "v_cmpx_eq_u32_e32 0, v0", - f"s_mov_b32 s4, {BASE:#x}", - f"s_mov_b32 s5, {w1:#x}", - f"s_mov_b32 s6, {nr:#x}", - f"s_mov_b32 s7, {w3:#x}", - *setup, - "buffer_load_format_xyzw v[4:7], " + vaddr + f", s[4:7], 0 {mods}", - "s_waitcnt vmcnt(0)", - "buffer_store_dwordx4 v[4:7], off, s[0:3], 0", - "s_endpgm", - ] - with self.subTest(tag=tag): - mem, _ = self._run_cs(lines, name=f"cs_{tag}") - self.assertEqual(mem.reads, []) - self.assertEqual([dict.get(mem, 4 * i, 0) for i in range(4)], want) - - def test_mtbuf_oob_and_invalid_descriptor_ignore_dst_sel_one(self): - """MTBUF ignores V# DST_SEL=1 on both OOB and FORMAT=0 loads, returning 0 in addressed channels.""" - for tag, fmt_code, off, d16, want in ( - ("mtbuf_oob_u32", 20, 0x100, False, [0, 0, 0, 0]), - ("mtbuf_oob_f32_d16_xyz", 22, 0x100, True, [0, SEED1 & 0xFFFF0000]), - ("mtbuf_fmt0_f32", 0, 0, False, [0, 0, 0, 0]), - ("mtbuf_fmt0_u8_d16_xyz", 0, 0, True, [0, SEED1 & 0xFFFF0000]), - ): - op = "tbuffer_load_format_d16_xyz" if d16 else "tbuffer_load_format_xyzw" - vdata = "v[4:5]" if d16 else "v[4:7]" - store = "buffer_store_dwordx2 v[4:5]" if d16 else "buffer_store_dwordx4 v[4:7]" - inst_fmt = "BUF_FMT_32_32_32_32_FLOAT" if "f32" in tag else "BUF_FMT_8_8_8_8_UINT" - lines = [ - "v_cmpx_eq_u32_e32 0, v0", - f"s_mov_b32 s4, {BASE:#x}", - "s_mov_b32 s5, 0", - "s_mov_b32 s6, 16", - f"s_mov_b32 s7, {word3(fmt_code, DST_1_1_1_1, 3):#x}", - f"v_mov_b32 v1, {off:#x}", - f"v_mov_b32 v4, {SEED0:#x}", - f"v_mov_b32 v5, {SEED1:#x}", - f"v_mov_b32 v6, {SEED2:#x}", - f"v_mov_b32 v7, {SEED3:#x}", - f"{op} {vdata}, v1, s[4:7], 0 format:[{inst_fmt}] offen", - "s_waitcnt vmcnt(0)", - f"{store}, off, s[0:3], 0", - "s_endpgm", - ] - with self.subTest(tag=tag): - mem, _ = self._run_cs(lines, name=f"cs_{tag}") - self.assertEqual(mem.reads, []) - self.assertEqual([dict.get(mem, 4 * i, 0) for i in range(len(want))], want) - - def test_inactive_lanes_and_wave64_emulate(self): - """Wave64 active lanes in both halves get DST_SEL=1 on OOB while masked-off lanes keep seeds; --wave64-emulate validates.""" - lines = [ - # Enable only lane 0 (low half) and lane 35 (high half). - "v_cmp_eq_u32_e64 s[12:13], 0, v0", - "v_cmp_eq_u32_e64 s[14:15], 35, v0", - "s_or_b64 s[12:13], s[12:13], s[14:15]", - "s_mov_b32 s4, 0x1000", - "s_mov_b32 s5, 0", - "s_mov_b32 s6, 16", - f"s_mov_b32 s7, {word3(56, DST_X_0_1_1, 3):#x}", # 8_8_8_8_UNORM - f"s_mov_b32 s8, {BASE:#x}", - "s_mov_b32 s9, 0", - "s_mov_b32 s10, 16", - f"s_mov_b32 s11, {word3(60, DST_1_Y_Z_W, 3):#x}", # 8_8_8_8_UINT - "v_mov_b32 v1, 0x100", - f"v_mov_b32 v4, {SEED0:#x}", - f"v_mov_b32 v5, {SEED1:#x}", - f"v_mov_b32 v6, {SEED2:#x}", - f"v_mov_b32 v7, {SEED3:#x}", - f"v_mov_b32 v8, {SEED0:#x}", - "s_and_saveexec_b64 s[16:17], s[12:13]", - "buffer_load_format_xyzw v[4:7], v1, s[4:7], 0 offen", - "buffer_load_format_d16_x v8, v1, s[8:11], 0 offen", - "s_waitcnt vmcnt(0)", - "s_mov_b64 exec, s[16:17]", - # Store lane 0, lane 1 (inactive), and lane 35 (high half active) into output buffer. - "v_lshlrev_b32 v2, 5, v0", - "buffer_store_dwordx4 v[4:7], v2, s[0:3], 0 offen", - "buffer_store_dword v8, v2, s[0:3], 0 offen offset:16", - "s_endpgm", - ] - pcs = [0, 0, 0x1000, OUT_V] + [0] * 28 - mem, spv_w64 = self._run_cs(lines, push_constants=pcs, wave64=True, name="cs_w64_oob_dst_sel") - self.assertEqual(mem.reads, []) - for active_lane in (0, 35): - base_off = active_lane * 32 - self.assertEqual( - [dict.get(mem, base_off + 4 * i, 0) for i in range(5)], - [0, 0, 0x3F800000, 0x3F800000, (SEED0 & 0xFFFF0000) | 1], - active_lane, - ) - for inactive_lane in (1, 34): - base_off = inactive_lane * 32 - self.assertEqual( - [dict.get(mem, base_off + 4 * i, 0) for i in range(5)], - [SEED0, SEED1, SEED2, SEED3, SEED0], - inactive_lane, - ) - - old_emu = rdna2spirv.WAVE64_EMULATE - try: - rdna2spirv.WAVE64_EMULATE = True - spv_emu = support.translate_lines("cs_w64_emu_oob_dst_sel", lines, fssm=CS_12_USER_FSSM) - finally: - rdna2spirv.WAVE64_EMULATE = old_emu - self.assertIn("%x_buf", spv_emu) - self.assertNotIn("OpGroupNonUniform", spv_emu) - - spirv_as = shutil.which("spirv-as") - spirv_val = shutil.which("spirv-val") - if spirv_as and spirv_val: - with tempfile.TemporaryDirectory() as td: - for idx, mod_text in enumerate((spv_w64, spv_emu)): - spv_bin = os.path.join(td, f"mod_{idx}.spv") - subprocess.run( - [spirv_as, "--target-env", "vulkan1.2", "-", "-o", spv_bin], - input=mod_text.encode("utf-8"), - check=True, - ) - subprocess.run([spirv_val, "--target-env", "vulkan1.2", spv_bin], check=True) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_buffer_oob_select.py b/tests/semantic/test_buffer_oob_select.py deleted file mode 100644 index fc836d822..000000000 --- a/tests/semantic/test_buffer_oob_select.py +++ /dev/null @@ -1,1434 +0,0 @@ -"""MUBUF bounds checking per V# OOB_SELECT (word3 bits [29:28]), as measured natively on RDNA2 (gfx1036, -docs/buffer_bounds.md; Mesa's GFX11 column, not its GFX10 one). - -With idx = vindex (0 without idxen), off = inst_offset + vaddr offset (0 without offen) and offs = off + soffset, a -dword access is out of range when: - - 0 STRUCTURED_WITH_OFFSET idx >= NUM_RECORDS or off + 4 > STRIDE - 1 STRUCTURED idx >= NUM_RECORDS - 2 DISABLED NUM_RECORDS == 0 - 3 RAW offs + 4 > NUM_RECORDS (idx * STRIDE is in the address only) - -An out-of-range load returns 0 without reading, an out-of-range store is dropped. The table below is written out by -hand from those rules (not computed), and every row runs twice: with word3 a literal the translator folds, and with -word3 or-ed together at run time, which it selects with OpSelect. The multi-dword tail of RAW loads is in -test_value_semantics.py (measured on an RX 6800); mode 0's is by analogy. -""" -from __future__ import annotations - -import os -import re -import struct -import sys -import unittest - -HERE = os.path.dirname(os.path.abspath(__file__)) -ROOT = os.path.dirname(os.path.dirname(HERE)) -TOOLS_DIR = os.environ.get("LEONIDA_TOOLS_DIR") or os.path.join(ROOT, "tools") - -sys.dont_write_bytecode = True -if TOOLS_DIR not in sys.path: - sys.path.insert(0, TOOLS_DIR) -if HERE not in sys.path: - sys.path.insert(0, HERE) - -import support -import spirv_mini_interp as si -import test_value_semantics as tv # module only: importing its classes would collect them a second time - -MASK14 = 0x3FFF -MASK16 = 0xFFFF -MASK32 = 0xFFFFFFFF -MASK64 = 0xFFFFFFFFFFFFFFFF - - -class BufferResourceDescriptor: - """AMD RDNA2 128-bit Buffer Resource Descriptor (V#).""" - - def __init__(self, d0: int = 0, d1: int = 0, d2: int = 0, d3: int = 0) -> None: - self.d0 = d0 & MASK32 - self.d1 = d1 & MASK32 - self.d2 = d2 & MASK32 - self.d3 = d3 & MASK32 - - @classmethod - def from_fields( - cls, - base_address: int, - stride: int = 0, - num_records: int = 0, - oob_select: int = 0, - format_code: int = 22, - resource_level: int = 1, - swizzle_enable: bool = False, - add_tid_enable: bool = False, - index_stride: int = 0, - ) -> BufferResourceDescriptor: - d0 = base_address & MASK32 - base_hi = (base_address >> 32) & MASK16 - stride_field = (stride & MASK14) << 16 - swz_bit = (1 << 31) if swizzle_enable else 0 - d1 = base_hi | stride_field | swz_bit - d2 = num_records & MASK32 - fmt_field = (format_code & 0x7F) << 12 - rsrc_level = (resource_level & 1) << 19 - idx_stride = (index_stride & 3) << 21 - add_tid = (1 << 23) if add_tid_enable else 0 - oob_sel = (oob_select & 3) << 28 - dst_sel = 0xFAC - d3 = dst_sel | fmt_field | rsrc_level | idx_stride | add_tid | oob_sel - return cls(d0, d1, d2, d3) - - @property - def base_lo(self) -> int: - return self.d0 - - @property - def base_hi(self) -> int: - return self.d1 & MASK16 - - @property - def base_64(self) -> int: - return ((self.base_hi << 32) | self.base_lo) & MASK64 - - @property - def stride(self) -> int: - return (self.d1 >> 16) & MASK14 - - @property - def num_records(self) -> int: - return self.d2 - - @property - def oob_select(self) -> int: - return (self.d3 >> 28) & 3 - - @property - def format_code(self) -> int: - return (self.d3 >> 12) & 0x7F - - @property - def swizzle_enable(self) -> bool: - return bool(self.d1 & (1 << 31)) - - @property - def add_tid_enable(self) -> bool: - return bool(self.d3 & (1 << 23)) - - @property - def index_stride(self) -> int: - return 3 + ((self.d3 >> 21) & 3) - - def as_words(self) -> tuple[int, int, int, int]: - return (self.d0, self.d1, self.d2, self.d3) - - -class BufferOobOracle: - """Reference oracle for RDNA2 MUBUF/MTBUF bounds checking and component clamping. - - Implements the native hardware rules measured on gfx1036 (docs/buffer_bounds.md) - and gfx1150 proxy: - Mode 0 (STRUCTURED_WITH_OFFSET): - idx < num_records and off + 4*k + 4 <= stride (off = inst_offset + vaddr, without soffset). - If no idxen: num_records != 0 and off + 4*k + 4 <= stride. - Mode 1 (STRUCTURED): - idx < num_records (or num_records != 0 without idxen). Shared by all dwords. - Mode 2 (DISABLED): - num_records != 0. Shared by all dwords. - Mode 3 (RAW): - offs + 4*k + 4 <= num_records (offs = inst_offset + vaddr + soffset). - idx * stride is part of the address calculation, but not part of the bounds check. - """ - - @staticmethod - def check_dword_bounds( - desc: BufferResourceDescriptor, - k: int = 0, - idx: int | None = None, - off: int | None = None, - soffset: int = 0, - inst_offset: int = 0, - lane: int = 0, - ) -> bool: - mode = desc.oob_select - nr = desc.num_records - stride = desc.stride - - lane_add = lane if desc.add_tid_enable else 0 - eff_idx = None if idx is None else ((idx + lane_add) & MASK32) - - voff = 0 if off is None else (off & MASK32) - total_off = (voff + inst_offset) & MASK32 - offs = (total_off + soffset) & MASK32 - - end_bytes = 4 * k + 4 - - sw3 = desc.swizzle_enable and stride != 0 - if mode == 0 or (mode == 3 and sw3): - if eff_idx is not None: - idx_ok = eff_idx < nr - else: - idx_ok = nr != 0 - end_ok = (total_off + end_bytes) <= stride - return idx_ok and end_ok - elif mode == 1: - if eff_idx is not None: - return eff_idx < nr - return nr != 0 - elif mode == 2: - return nr != 0 - elif mode == 3: - return (offs + end_bytes) <= nr - return False - - @staticmethod - def check_format_bounds( - desc: BufferResourceDescriptor, - format_size: int, - idx: int | None = None, - off: int | None = None, - soffset: int = 0, - inst_offset: int = 0, - lane: int = 0, - ) -> bool: - """Typed element access (MTBUF/format load/store): all-or-nothing check for full format_size.""" - mode = desc.oob_select - nr = desc.num_records - stride = desc.stride - - lane_add = lane if desc.add_tid_enable else 0 - eff_idx = None if idx is None else ((idx + lane_add) & MASK32) - - voff = 0 if off is None else (off & MASK32) - total_off = (voff + inst_offset) & MASK32 - offs = (total_off + soffset) & MASK32 - - sw3 = desc.swizzle_enable and stride != 0 - if mode == 0 or (mode == 3 and sw3): - if eff_idx is not None: - idx_ok = eff_idx < nr - else: - idx_ok = nr != 0 - end_ok = (total_off + format_size) <= stride - return idx_ok and end_ok - elif mode == 1: - if eff_idx is not None: - return eff_idx < nr - return nr != 0 - elif mode == 2: - return nr != 0 - elif mode == 3: - return (offs + format_size) <= nr - return False - - @staticmethod - def compute_effective_address( - desc: BufferResourceDescriptor, - k: int = 0, - idx: int | None = None, - off: int | None = None, - soffset: int = 0, - inst_offset: int = 0, - lane: int = 0, - ) -> int: - lane_add = lane if desc.add_tid_enable else 0 - eff_idx = 0 if idx is None else ((idx + lane_add) & MASK32) - voff = 0 if off is None else (off & MASK32) - - if desc.swizzle_enable: - Li = desc.index_stride - IS = 1 << Li - off_s = (voff + inst_offset) & MASK32 - om4 = off_s & 0xFFFFFFFC - ol = off_s & 3 - msb = eff_idx >> Li - lsb = eff_idx & (IS - 1) - inner = (msb * desc.stride + om4) & MASK32 - sh = (inner << Li) & MASK32 - sh = (sh + (lsb << 2)) & MASK32 - b_off = (sh + ol) & MASK32 - total = (soffset + b_off) & MASK32 - step = 4 << Li - return (desc.base_64 + total + k * step) & MASK64 - else: - total = (soffset + inst_offset + voff) & MASK32 - if idx is not None: - total = (total + eff_idx * desc.stride) & MASK32 - return (desc.base_64 + total + 4 * k) & MASK64 - - @classmethod - def load_dwords( - cls, - desc: BufferResourceDescriptor, - num_dwords: int, - idx: int | None = None, - off: int | None = None, - soffset: int = 0, - inst_offset: int = 0, - memory: dict[int, int] | None = None, - lane: int = 0, - active: bool = True, - ) -> list[int]: - if memory is None: - memory = {} - if not active: - return [0] * num_dwords - - mode = desc.oob_select - if mode in (1, 2): - whole_in_bounds = cls.check_dword_bounds( - desc, k=0, idx=idx, off=off, soffset=soffset, inst_offset=inst_offset, lane=lane - ) - if not whole_in_bounds: - return [0] * num_dwords - res = [] - for k in range(num_dwords): - addr = cls.compute_effective_address( - desc, k=k, idx=idx, off=off, soffset=soffset, inst_offset=inst_offset, lane=lane - ) - res.append(memory.get(addr, 0) & MASK32) - return res - - res = [] - for k in range(num_dwords): - in_b = cls.check_dword_bounds( - desc, k=k, idx=idx, off=off, soffset=soffset, inst_offset=inst_offset, lane=lane - ) - if in_b: - addr = cls.compute_effective_address( - desc, k=k, idx=idx, off=off, soffset=soffset, inst_offset=inst_offset, lane=lane - ) - res.append(memory.get(addr, 0) & MASK32) - else: - res.append(0) - return res - - @classmethod - def store_dwords( - cls, - desc: BufferResourceDescriptor, - values: list[int], - idx: int | None = None, - off: int | None = None, - soffset: int = 0, - inst_offset: int = 0, - memory: dict[int, int] | None = None, - lane: int = 0, - active: bool = True, - ) -> list[int]: - if memory is None or not active: - return [] - - written = [] - mode = desc.oob_select - - if mode in (1, 2): - whole_in_bounds = cls.check_dword_bounds( - desc, k=0, idx=idx, off=off, soffset=soffset, inst_offset=inst_offset, lane=lane - ) - if not whole_in_bounds: - return [] - for k, val in enumerate(values): - addr = cls.compute_effective_address( - desc, k=k, idx=idx, off=off, soffset=soffset, inst_offset=inst_offset, lane=lane - ) - memory[addr] = val & MASK32 - written.append(addr) - return written - - for k, val in enumerate(values): - in_b = cls.check_dword_bounds( - desc, k=k, idx=idx, off=off, soffset=soffset, inst_offset=inst_offset, lane=lane - ) - if in_b: - addr = cls.compute_effective_address( - desc, k=k, idx=idx, off=off, soffset=soffset, inst_offset=inst_offset, lane=lane - ) - memory[addr] = val & MASK32 - written.append(addr) - return written - - @classmethod - def load_format( - cls, - desc: BufferResourceDescriptor, - format_size: int, - idx: int | None = None, - off: int | None = None, - soffset: int = 0, - inst_offset: int = 0, - memory: dict[int, int] | None = None, - lane: int = 0, - active: bool = True, - ) -> list[int]: - num_dwords = format_size // 4 - if memory is None or not active: - return [0] * num_dwords - in_b = cls.check_format_bounds( - desc, format_size=format_size, idx=idx, off=off, soffset=soffset, inst_offset=inst_offset, lane=lane - ) - if not in_b: - return [0] * num_dwords - res = [] - for k in range(num_dwords): - addr = cls.compute_effective_address( - desc, k=k, idx=idx, off=off, soffset=soffset, inst_offset=inst_offset, lane=lane - ) - res.append(memory.get(addr, 0) & MASK32) - return res - - @classmethod - def store_format( - cls, - desc: BufferResourceDescriptor, - values: list[int], - format_size: int, - idx: int | None = None, - off: int | None = None, - soffset: int = 0, - inst_offset: int = 0, - memory: dict[int, int] | None = None, - lane: int = 0, - active: bool = True, - ) -> list[int]: - if memory is None or not active: - return [] - in_b = cls.check_format_bounds( - desc, format_size=format_size, idx=idx, off=off, soffset=soffset, inst_offset=inst_offset, lane=lane - ) - if not in_b: - return [] - written = [] - for k, val in enumerate(values): - addr = cls.compute_effective_address( - desc, k=k, idx=idx, off=off, soffset=soffset, inst_offset=inst_offset, lane=lane - ) - memory[addr] = val & MASK32 - written.append(addr) - return written - - -class WaveBufferOobInterpreter: - """Multi-lane SIMD wave reference interpreter modeling RDNA2 Wave32/Wave64 buffer operations.""" - - def __init__(self, wave_size: int = 32, memory: dict[int, int] | None = None) -> None: - if wave_size not in (32, 64): - raise ValueError(f"Unsupported wave size: {wave_size}") - self.wave_size = wave_size - self.memory = {} if memory is None else dict(memory) - self.sgprs = [0] * 106 - self.vgprs = [[0] * 256 for _ in range(wave_size)] - self.exec_mask = (1 << wave_size) - 1 - - def set_exec_mask(self, mask: int) -> None: - self.exec_mask = mask & ((1 << self.wave_size) - 1) - - def is_lane_active(self, lane: int) -> bool: - return bool((self.exec_mask >> lane) & 1) - - def set_sgpr_range(self, start: int, values: list[int] | tuple[int, ...]) -> None: - for i, val in enumerate(values): - self.sgprs[start + i] = val & MASK32 - - def set_lane_vgpr(self, lane: int, reg: int, val: int) -> None: - self.vgprs[lane][reg] = val & MASK32 - - def get_lane_vgpr(self, lane: int, reg: int) -> int: - return self.vgprs[lane][reg] & MASK32 - - def get_descriptor(self, start_sgpr: int) -> BufferResourceDescriptor: - return BufferResourceDescriptor( - self.sgprs[start_sgpr], - self.sgprs[start_sgpr + 1], - self.sgprs[start_sgpr + 2], - self.sgprs[start_sgpr + 3], - ) - - def buffer_load_dword( - self, - vdst: int, - srsrc: int, - soffset: int = 0, - inst_offset: int = 0, - vaddr_off_reg: int | None = None, - vaddr_idx_reg: int | None = None, - num_dwords: int = 1, - ) -> list[list[int]]: - desc = self.get_descriptor(srsrc) - wave_results = [] - for lane in range(self.wave_size): - active = self.is_lane_active(lane) - off = self.get_lane_vgpr(lane, vaddr_off_reg) if vaddr_off_reg is not None else None - idx = self.get_lane_vgpr(lane, vaddr_idx_reg) if vaddr_idx_reg is not None else None - loaded = BufferOobOracle.load_dwords( - desc=desc, - num_dwords=num_dwords, - idx=idx, - off=off, - soffset=soffset, - inst_offset=inst_offset, - memory=self.memory, - lane=lane, - active=active, - ) - for k in range(num_dwords): - self.set_lane_vgpr(lane, vdst + k, loaded[k]) - wave_results.append(loaded) - return wave_results - - def buffer_store_dword( - self, - vdata: int, - srsrc: int, - soffset: int = 0, - inst_offset: int = 0, - vaddr_off_reg: int | None = None, - vaddr_idx_reg: int | None = None, - num_dwords: int = 1, - ) -> list[list[int]]: - desc = self.get_descriptor(srsrc) - wave_written = [] - for lane in range(self.wave_size): - active = self.is_lane_active(lane) - off = self.get_lane_vgpr(lane, vaddr_off_reg) if vaddr_off_reg is not None else None - idx = self.get_lane_vgpr(lane, vaddr_idx_reg) if vaddr_idx_reg is not None else None - vals = [self.get_lane_vgpr(lane, vdata + k) for k in range(num_dwords)] - written = BufferOobOracle.store_dwords( - desc=desc, - values=vals, - idx=idx, - off=off, - soffset=soffset, - inst_offset=inst_offset, - memory=self.memory, - lane=lane, - active=active, - ) - wave_written.append(written) - return wave_written - - -BASE = tv.VEC_REGION -OUT_V = 0x31016FAC # the output V# in s[0:3]: RAW, base 0 -W3 = 0x01016FAC # word3 without OOB_SELECT: RESOURCE_LEVEL, FORMAT 32_FLOAT, DST_SEL xyzw -NONE = None - -# (mode, stride, num_records, idx, off, soffset, inst_offset, in_range); idx/off NONE: no idxen / no offen -CASES = [ - # mode 0: idx < NR and off + 4 <= stride (off is vaddr + inst_offset, not soffset) - (0, 8, 4, 1, 4, 0, 0, True), - (0, 8, 4, 1, 8, 0, 0, False), # off 8 + 4 > stride 8 - (0, 12, 4, 0, 8, 0, 0, True), # the last dword of the record fits: 8 + 4 <= 12 - (0, 10, 4, 0, 8, 0, 0, False), # ... and 8 + 4 > 10 does not - (0, 8, 4, 4, 0, 0, 0, False), # idx 4 >= NR 4 - (0, 8, 4, 3, 4, 0, 0, True), - (0, 8, 4, 1, 0, 16, 0, True), # soffset is not part of off - (0, 8, 4, 1, 0, 0, 8, False), # inst_offset is - (0, 8, 4, NONE, 4, 0, 0, True), # offen only: idx 0 < NR - (0, 8, 4, NONE, 8, 0, 0, False), - (0, 0, 4, 0, 0, 0, 0, False), # stride 0: 0 + 4 > 0 - (0, 8, 0, 0, 0, 0, 0, False), # NR 0 - # mode 1: idx < NR - (1, 8, 4, 3, 12, 0, 0, True), # off past the stride is not checked - (1, 8, 4, 4, 0, 0, 0, False), - (1, 8, 4, NONE, 16, 0, 0, True), # no idxen: idx 0 < NR, however far off is - (1, 8, 0, NONE, 0, 0, 0, False), - (1, 0, 4, 3, 0, 0, 0, True), # stride 0 still checks the index - (1, 0, 4, 4, 0, 0, 0, False), - # mode 2: only NR == 0 is out of range - (2, 8, 4, 5, 0, 0, 0, True), - (2, 0, 4, NONE, 0x20, 0, 0, True), - (2, 8, 0, NONE, 0, 0, 0, False), - # mode 3: offs + 4 <= NR; idx and stride do not take part - (3, 0, 0x10, NONE, 0xC, 0, 0, True), - (3, 0, 0x10, NONE, 0x10, 0, 0, False), - (3, 0, 0xC, NONE, 8, 0, 0, True), # the last dword fits: 8 + 4 <= 12 - (3, 0, 0xA, NONE, 8, 0, 0, False), # a dword that only starts inside: 8 + 4 > 10 - (3, 8, 0x10, 7, 4, 0, 0, True), # idx 7 >= NR 16 is irrelevant; address = 7 * 8 + 4 - (3, 8, 0x10, NONE, 0x10, 0, 0, False), - (3, 8, 0x10, 0, 4, 8, 0, True), # soffset counts: offs 12 - (3, 8, 0x10, 0, 4, 12, 0, False), # offs 16 - (3, 0, 0x10, NONE, 0, 0, 8, True), - (3, 0, 0x10, NONE, 0, 0, 0x10, False), - (3, 8, 8, 3, 0, 0, 0, True), # idx 3 >= NR 8 is not a check here - (3, 0, 0, NONE, 0, 0, 0, False), -] - - -def operands(idx, off, soffset, inst): - """vaddr operand text, modifiers and the v1/v2 setup for one case.""" - regs, mods = [], [] - if idx is not NONE: - regs.append(idx) - mods.append("idxen") - if off is not NONE: - regs.append(off) - mods.append("offen") - vaddr = {0: "off", 1: "v1", 2: "v[1:2]"}[len(regs)] - setup = [f"v_mov_b32 v{1 + i}, {r:#x}" for i, r in enumerate(regs)] - if soffset: - setup.append(f"s_mov_b32 s8, {soffset:#x}") - return vaddr, " ".join(mods + ([f"offset:{inst}"] if inst else [])), setup, ("s8" if soffset else "0") - - -def v_sharp(mode, stride, nr, runtime, fmt=22): - """Lines that put the V# in s[4:7]; with runtime the mode is or-ed in, so the translator cannot see it.""" - w3 = 0x01000FAC | fmt << 12 - lines = [f"s_mov_b32 s4, {BASE:#x}", "s_mov_b32 s5, " + hex(stride << 16), f"s_mov_b32 s6, {nr:#x}"] - if runtime: - lines += [f"s_mov_b32 s7, {w3:#x}", f"s_mov_b32 s9, {mode << 28:#x}", "s_or_b32 s7, s7, s9"] - else: - lines += [f"s_mov_b32 s7, {w3 | mode << 28:#x}"] - return lines - - -MODE_EXTRACT = re.compile(r"OpBitFieldUExtract %uint %t\d+ %c1c %c2\b") # word3 >> 28 & 3 at run time - - -class OobSelect(unittest.TestCase): - def translate(self, lines): - return support.translate_lines("cs_oob_select_t", ["v_cmpx_eq_u32_e32 0, v0", *lines, "s_endpgm"], - fssm=tv.CS_BOUNDS_FSSM) - - def run_spv(self, spv, preload=True): - memory = tv.ReadLog({BASE + k: tv._pattern_word(k) for k in range(-4, 0x80)} if preload else {}) - support.run_fragment(spv, inputs={"%wg_id": (0, 0, 0), "%local_id": (0, 0, 0)}, - push_constants=[0, 0, 0x100, OUT_V] + [0] * 28, memory=memory) - return memory - - def load_case(self, case, runtime): - mode, stride, nr, idx, off, soffset, inst, ok = case - vaddr, mods, setup, soff = operands(idx, off, soffset, inst) - lines = [*v_sharp(mode, stride, nr, runtime), *setup, - f"buffer_load_dword v2, {vaddr}, s[4:7], {soff} {mods}", "s_waitcnt vmcnt(0)", - "buffer_store_dword v2, off, s[0:3], 0"] - spv = self.translate(lines) - # the output store through s[0:3] reads its mode at run time; the probed V# only when it is not a literal - self.assertEqual(len(MODE_EXTRACT.findall(spv)), 1 + runtime, case) - memory = self.run_spv(spv) - addr = (0 if idx is NONE else idx * stride) + (off or 0) + soffset + inst - want = tv._pattern_word(addr) if ok else 0 - self.assertEqual(f"{dict.get(memory, 0, 0):#010x}", f"{want:#010x}", (case, runtime)) - self.assertEqual([a - BASE for a in memory.reads], [addr] if ok else [], (case, runtime)) - - def test_loads_literal_v_sharp(self): - for case in CASES: - with self.subTest(case=case): - self.load_case(case, runtime=False) - - def test_loads_runtime_v_sharp(self): - for case in CASES: - with self.subTest(case=case): - self.load_case(case, runtime=True) - - def store_case(self, case, runtime): - mode, stride, nr, idx, off, soffset, inst, ok = case - vaddr, mods, setup, soff = operands(idx, off, soffset, inst) - lines = [*v_sharp(mode, stride, nr, runtime), *setup, "v_mov_b32 v3, 0x11111111", - f"buffer_store_dword v3, {vaddr}, s[4:7], {soff} {mods}"] - spv = self.translate(lines) - self.assertEqual(len(MODE_EXTRACT.findall(spv)), int(runtime), case) - memory = self.run_spv(spv, preload=False) - addr = (0 if idx is NONE else idx * stride) + (off or 0) + soffset + inst - self.assertEqual(dict(memory), {BASE + addr: 0x11111111} if ok else {}, (case, runtime)) - - def test_stores_literal_v_sharp(self): - for case in CASES: - with self.subTest(case=case): - self.store_case(case, runtime=False) - - def test_stores_runtime_v_sharp(self): - for case in CASES: - with self.subTest(case=case): - self.store_case(case, runtime=True) - - def test_multi_dword_load_follows_the_mode(self): - # mode 0 is per dword (by analogy with the measured RAW tail): x2 at idx 1, off 4. With stride 12 both dwords - # end inside (8, 12); with stride 8 the second ends at 12 > 8 and reads 0 - for runtime in (False, True): - for stride, want in ((12, [tv._pattern_word(16), tv._pattern_word(20)]), (8, [tv._pattern_word(12), 0])): - lines = [*v_sharp(0, stride, 4, runtime), "v_mov_b32 v1, 1", "v_mov_b32 v2, 4", - "buffer_load_dwordx2 v[4:5], v[1:2], s[4:7], 0 idxen offen", "s_waitcnt vmcnt(0)", - "buffer_store_dwordx2 v[4:5], off, s[0:3], 0"] - memory = self.run_spv(self.translate(lines)) - self.assertEqual([dict.get(memory, 4 * i, 0) for i in range(2)], want, (runtime, stride)) - # mode 1 checks the index once for the whole load - for runtime in (False, True): - lines = [*v_sharp(1, 8, 4, runtime), "v_mov_b32 v1, 1", "v_mov_b32 v2, 4", - "buffer_load_dwordx2 v[4:5], v[1:2], s[4:7], 0 idxen offen", "s_waitcnt vmcnt(0)", - "buffer_store_dwordx2 v[4:5], off, s[0:3], 0"] - memory = self.run_spv(self.translate(lines)) - self.assertEqual([dict.get(memory, 4 * i, 0) for i in range(2)], - [tv._pattern_word(12), tv._pattern_word(16)], runtime) - - # measured on the Radeon 880M (gfx1150), a valid proxy for RDNA2 here (docs/buffer_bounds.md): a dword access - # that straddles the edge is per dword for loads AND stores, a typed element is all or nothing - STORE_CASES = [ - # (mode, stride, nr, idx, off, dwords, written dword count) - (3, 0, 0x20, NONE, 0x14, 4, 3), (3, 0, 0x20, NONE, 0x1C, 4, 1), (3, 0, 0x20, NONE, 0x20, 4, 0), - (3, 0, 0x20, NONE, 0x1C, 2, 1), (3, 0, 0x20, NONE, 0x10, 4, 4), - (0, 16, 8, 1, 4, 4, 3), (0, 16, 8, 1, 12, 4, 1), (0, 16, 8, 1, 16, 4, 0), (0, 16, 8, 1, 8, 2, 2), - (0, 16, 8, 1, 12, 2, 1), - (1, 16, 8, 1, 16, 4, 4), (2, 16, 8, 1, 16, 4, 4), - ] - - def test_multi_dword_stores_are_per_dword(self): - for runtime in (False, True): - for mode, stride, nr, idx, off, n, written in self.STORE_CASES: - vaddr, mods, setup, soff = operands(idx, off, 0, 0) - regs = f"v[3:{2 + n}]" - lines = [*v_sharp(mode, stride, nr, runtime), *setup, - *[f"v_mov_b32 v{3 + k}, {0x11111111 * (k + 1):#x}" for k in range(n)], - f"buffer_store_dwordx{n} {regs}, {vaddr}, s[4:7], 0 {mods}"] - memory = self.run_spv(self.translate(lines), preload=False) - base = BASE + (0 if idx is NONE else idx * stride) + off - want = {base + 4 * k: 0x11111111 * (k + 1) for k in range(written)} - self.assertEqual(dict(memory), want, (mode, stride, nr, idx, off, n, runtime)) - - FORMAT_CASES = [(3, 0, 0x20, NONE, 0x10, True), (3, 0, 0x20, NONE, 0x14, False), (3, 0, 0x20, NONE, 0x20, False), - (0, 16, 8, 1, 0, True), (0, 16, 8, 1, 4, False), (1, 16, 8, 1, 16, True)] - - def test_typed_element_is_all_or_nothing(self): - # 32_32_32_32_UINT (75), a 16-byte element: in only if all 16 bytes end inside (buffer_load_format_xyzw and - # buffer_store_format_xyzw alike) - for runtime in (False, True): - for mode, stride, nr, idx, off, ok in self.FORMAT_CASES: - vaddr, mods, setup, soff = operands(idx, off, 0, 0) - addr = (0 if idx is NONE else idx * stride) + off - lines = [*v_sharp(mode, stride, nr, runtime, fmt=75), *setup, - f"buffer_load_format_xyzw v[3:6], {vaddr}, s[4:7], 0 {mods}", "s_waitcnt vmcnt(0)", - "buffer_store_dwordx4 v[3:6], off, s[0:3], 0"] - memory = self.run_spv(self.translate(lines)) - got = [dict.get(memory, 4 * k, 0) for k in range(4)] - want = [tv._pattern_word(addr + 4 * k) for k in range(4)] if ok else [0] * 4 - self.assertEqual(got, want, ("load", mode, stride, nr, idx, off, runtime)) - lines = [*v_sharp(mode, stride, nr, runtime, fmt=75), *setup, - *[f"v_mov_b32 v{3 + k}, {0x11111111 * (k + 1):#x}" for k in range(4)], - f"buffer_store_format_xyzw v[3:6], {vaddr}, s[4:7], 0 {mods}"] - memory = self.run_spv(self.translate(lines), preload=False) - want = {BASE + addr + 4 * k: 0x11111111 * (k + 1) for k in range(4)} if ok else {} - self.assertEqual(dict(memory), want, ("store", mode, stride, nr, idx, off, runtime)) - - def test_loads_literal_v_sharp_from_s_mov_b64(self): - # s_mov_b64 s[6:7], imm folds word3 (OOB_SELECT mode) without run-time extraction. - for mode in range(4): - with self.subTest(mode=mode): - w3 = 0x01000FAC | (mode << 28) - val64 = (w3 << 32) | 0x10 - lines = [f"s_mov_b64 s[4:5], {BASE:#x}", f"s_mov_b64 s[6:7], {val64:#x}", - "buffer_load_dword v2, off, s[4:7], 0", "s_waitcnt vmcnt(0)", - "buffer_store_dword v2, off, s[0:3], 0"] - spv = self.translate(lines) - self.assertEqual(len(MODE_EXTRACT.findall(spv)), 1, f"mode {mode} did not fold from s_mov_b64") - - def test_loads_literal_v_sharp_from_s_movk_i32(self): - # s_movk_i32 s7, imm sets word3 for modes where word3 fits in 16 bits sign-extended. - lines = [f"s_mov_b32 s4, {BASE:#x}", "s_mov_b32 s5, 0", "s_mov_b32 s6, 16", - "s_movk_i32 s7, 0x3000", - "buffer_load_dword v2, off, s[4:7], 0", "s_waitcnt vmcnt(0)", - "buffer_store_dword v2, off, s[0:3], 0"] - spv = self.translate(lines) - self.assertEqual(len(MODE_EXTRACT.findall(spv)), 1, "s_movk_i32 did not fold into literal V#") - - def test_loads_literal_v_sharp_from_sgpr_copy(self): - # Copy propagation: s_mov_b32 from a constant SGPR preserves sgpr_imm. - w3 = 0x31000FAC - lines = [f"s_mov_b32 s8, {w3:#x}", "s_mov_b32 s7, s8", - f"s_mov_b32 s4, {BASE:#x}", "s_mov_b32 s5, 0", "s_mov_b32 s6, 16", - "buffer_load_dword v2, off, s[4:7], 0", "s_waitcnt vmcnt(0)", - "buffer_store_dword v2, off, s[0:3], 0"] - spv = self.translate(lines) - self.assertEqual(len(MODE_EXTRACT.findall(spv)), 1, "s_mov_b32 copy did not fold into literal V#") - - def test_loads_literal_v_sharp_from_s_mov_b64_copy(self): - # Copy propagation: s_mov_b64 64-bit pair copy preserves sgpr_imm. - w3 = 0x31000FAC - val64 = (w3 << 32) | 16 - lines = [f"s_mov_b64 s[8:9], {val64:#x}", "s_mov_b64 s[6:7], s[8:9]", - f"s_mov_b32 s4, {BASE:#x}", "s_mov_b32 s5, 0", - "buffer_load_dword v2, off, s[4:7], 0", "s_waitcnt vmcnt(0)", - "buffer_store_dword v2, off, s[0:3], 0"] - spv = self.translate(lines) - self.assertEqual(len(MODE_EXTRACT.findall(spv)), 1, "s_mov_b64 pair copy did not fold into literal V#") - - def test_loads_literal_v_sharp_from_s_mov_b64_overlapping_copy(self): - # Overlapping 64-bit copy s_mov_b64 s[6:7], s[5:6] where d == s + 1: - # Both source registers must be evaluated before writing destination, - # so s7 gets the old s6 literal rather than the newly written s6 (s5). - w3 = 0x31000FAC - lines = [f"s_mov_b32 s4, {BASE:#x}", "s_mov_b32 s5, 16", - f"s_mov_b32 s6, {w3:#x}", - "s_mov_b64 s[6:7], s[5:6]", - "buffer_load_dword v2, off, s[4:7], 0", "s_waitcnt vmcnt(0)", - "buffer_store_dword v2, off, s[0:3], 0"] - spv = self.translate(lines) - self.assertEqual(len(MODE_EXTRACT.findall(spv)), 1, "s_mov_b64 overlapping copy did not fold into literal V#") - - -class TestBufferOobOracle(unittest.TestCase): - """Unit tests for the BufferResourceDescriptor reference oracle and OOB clamping.""" - - def test_oracle_matches_handwritten_table(self): - for case in CASES: - mode, stride, nr, idx, off, soffset, inst_offset, ok = case - with self.subTest(case=case): - desc = BufferResourceDescriptor.from_fields( - base_address=BASE, - stride=stride, - num_records=nr, - oob_select=mode, - ) - res = BufferOobOracle.check_dword_bounds( - desc, - k=0, - idx=idx, - off=off, - soffset=soffset, - inst_offset=inst_offset, - ) - self.assertEqual(res, ok, f"Oracle mismatch for case {case}") - - def test_oracle_descriptor_properties(self): - desc = BufferResourceDescriptor.from_fields( - base_address=0x00007FFF12345678, - stride=64, - num_records=256, - oob_select=3, - format_code=22, - swizzle_enable=True, - add_tid_enable=True, - index_stride=2, - ) - self.assertEqual(desc.base_lo, 0x12345678) - self.assertEqual(desc.base_hi, 0x7FFF) - self.assertEqual(desc.base_64, 0x00007FFF12345678) - self.assertEqual(desc.stride, 64) - self.assertEqual(desc.num_records, 256) - self.assertEqual(desc.oob_select, 3) - self.assertEqual(desc.format_code, 22) - self.assertTrue(desc.swizzle_enable) - self.assertTrue(desc.add_tid_enable) - self.assertEqual(desc.index_stride, 5) - - def test_oracle_mode0_structured_with_offset(self): - desc = BufferResourceDescriptor.from_fields( - base_address=0x1000, - stride=16, - num_records=4, - oob_select=0, - ) - # In-bounds: idx 2 < 4, off 8 + 4 <= 16 - self.assertTrue(BufferOobOracle.check_dword_bounds(desc, k=0, idx=2, off=8)) - # Boundary: off 12 + 4 == 16 (in-bounds) - self.assertTrue(BufferOobOracle.check_dword_bounds(desc, k=0, idx=2, off=12)) - # OOB: off 13 + 4 == 17 > 16 - self.assertFalse(BufferOobOracle.check_dword_bounds(desc, k=0, idx=2, off=13)) - # OOB: idx 4 >= num_records 4 - self.assertFalse(BufferOobOracle.check_dword_bounds(desc, k=0, idx=4, off=0)) - # Soffset does not participate in mode 0 offset check - self.assertTrue(BufferOobOracle.check_dword_bounds(desc, k=0, idx=1, off=8, soffset=0x100)) - - def test_oracle_mode1_structured(self): - desc = BufferResourceDescriptor.from_fields( - base_address=0x1000, - stride=16, - num_records=4, - oob_select=1, - ) - # Mode 1 checks idx < num_records only. Offsets past stride are permitted - self.assertTrue(BufferOobOracle.check_dword_bounds(desc, k=0, idx=3, off=1024)) - self.assertFalse(BufferOobOracle.check_dword_bounds(desc, k=0, idx=4, off=0)) - # No idxen: idx 0 < 4 is True - self.assertTrue(BufferOobOracle.check_dword_bounds(desc, k=0, idx=None, off=2048)) - # num_records == 0 causes OOB - desc_zero = BufferResourceDescriptor.from_fields(base_address=0x1000, stride=16, num_records=0, oob_select=1) - self.assertFalse(BufferOobOracle.check_dword_bounds(desc_zero, k=0, idx=None, off=0)) - - def test_oracle_mode2_disabled(self): - desc = BufferResourceDescriptor.from_fields( - base_address=0x1000, - stride=0, - num_records=1, - oob_select=2, - ) - # Bounds check disabled: in-bounds for any offset or index as long as num_records != 0 - self.assertTrue(BufferOobOracle.check_dword_bounds(desc, k=0, idx=999, off=0x10000)) - desc_zero = BufferResourceDescriptor.from_fields(base_address=0x1000, stride=0, num_records=0, oob_select=2) - self.assertFalse(BufferOobOracle.check_dword_bounds(desc_zero, k=0, idx=0, off=0)) - - def test_oracle_mode3_raw(self): - desc = BufferResourceDescriptor.from_fields( - base_address=0x2000, - stride=0, - num_records=32, - oob_select=3, - ) - # In-bounds: offs 24 + 4 <= 32 - self.assertTrue(BufferOobOracle.check_dword_bounds(desc, k=0, off=24, soffset=0)) - # Boundary: offs 28 + 4 == 32 - self.assertTrue(BufferOobOracle.check_dword_bounds(desc, k=0, off=28, soffset=0)) - # OOB: offs 29 + 4 == 33 > 32 - self.assertFalse(BufferOobOracle.check_dword_bounds(desc, k=0, off=29, soffset=0)) - # Soffset participates in mode 3 - self.assertFalse(BufferOobOracle.check_dword_bounds(desc, k=0, off=20, soffset=12)) # 32 + 4 > 32 - - def test_oracle_multi_dword_partial_clamping(self): - # In Mode 3 RAW buffer of 24 bytes: - # buffer_load_dwordx4 at offset 12 loads dwords at offsets 12, 16, 20, 24. - # dword 0 (offset 12, end 16 <= 24): in-bounds - # dword 1 (offset 16, end 20 <= 24): in-bounds - # dword 2 (offset 20, end 24 <= 24): in-bounds - # dword 3 (offset 24, end 28 > 24): OOB -> zero fill - desc = BufferResourceDescriptor.from_fields( - base_address=0x1000, - stride=0, - num_records=24, - oob_select=3, - ) - memory = { - 0x1000 + 12: 0xAAAA0001, - 0x1000 + 16: 0xAAAA0002, - 0x1000 + 20: 0xAAAA0003, - 0x1000 + 24: 0xAAAA0004, - } - loaded = BufferOobOracle.load_dwords(desc, num_dwords=4, off=12, memory=memory) - self.assertEqual(loaded, [0xAAAA0001, 0xAAAA0002, 0xAAAA0003, 0]) - - # Mode 0 partial clamping at stride boundary - # stride 16, num_records 4. load_dwordx4 at off 4: - # k=0: 4 + 4 = 8 <= 16 (in) - # k=1: 4 + 8 = 12 <= 16 (in) - # k=2: 4 + 12 = 16 <= 16 (in) - # k=3: 4 + 16 = 20 > 16 (OOB -> 0) - desc_m0 = BufferResourceDescriptor.from_fields( - base_address=0x2000, - stride=16, - num_records=4, - oob_select=0, - ) - mem_m0 = { - 0x2000 + 4: 0xBBBB0001, - 0x2000 + 8: 0xBBBB0002, - 0x2000 + 12: 0xBBBB0003, - 0x2000 + 16: 0xBBBB0004, - } - loaded_m0 = BufferOobOracle.load_dwords(desc_m0, num_dwords=4, idx=0, off=4, memory=mem_m0) - self.assertEqual(loaded_m0, [0xBBBB0001, 0xBBBB0002, 0xBBBB0003, 0]) - - def test_oracle_multi_dword_stores_suppression(self): - desc = BufferResourceDescriptor.from_fields( - base_address=0x1000, - stride=0, - num_records=24, - oob_select=3, - ) - memory = {} - values = [0x11111111, 0x22222222, 0x33333333, 0x44444444] - written = BufferOobOracle.store_dwords(desc, values, off=12, memory=memory) - self.assertEqual(len(written), 3) - self.assertEqual(memory, { - 0x1000 + 12: 0x11111111, - 0x1000 + 16: 0x22222222, - 0x1000 + 20: 0x33333333, - }) - - def test_oracle_typed_format_all_or_nothing(self): - # 16-byte format (e.g. RGBA32) in Mode 3 with num_records 24 - desc = BufferResourceDescriptor.from_fields( - base_address=0x1000, - stride=0, - num_records=24, - oob_select=3, - ) - memory = {0x1000 + 4 * k: 0x100 + k for k in range(8)} - # off 8: 8 + 16 == 24 <= 24 -> in-bounds - loaded = BufferOobOracle.load_format(desc, format_size=16, off=8, memory=memory) - self.assertEqual(loaded, [0x102, 0x103, 0x104, 0x105]) - # off 12: 12 + 16 == 28 > 24 -> all-or-nothing OOB -> all zero - loaded_oob = BufferOobOracle.load_format(desc, format_size=16, off=12, memory=memory) - self.assertEqual(loaded_oob, [0, 0, 0, 0]) - - def test_oracle_inactive_lanes(self): - desc = BufferResourceDescriptor.from_fields( - base_address=0x1000, - stride=0, - num_records=32, - oob_select=3, - ) - memory = {0x1000: 0xCAFEBABE} - loaded = BufferOobOracle.load_dwords(desc, num_dwords=1, off=0, memory=memory, active=False) - self.assertEqual(loaded, [0]) - store_mem = {} - written = BufferOobOracle.store_dwords(desc, [0x123], off=0, memory=store_mem, active=False) - self.assertEqual(written, []) - self.assertEqual(store_mem, {}) - - -class TestBufferOobSimdMultiLane(unittest.TestCase): - """Multi-lane SIMD wave tests modeling partial component OOB zero fill and clamping.""" - - def translate_helper(self, lines): - return support.translate_lines( - "cs_oob_simd_t", - ["v_cmpx_eq_u32_e32 0, v0", *lines, "s_endpgm"], - fssm=tv.CS_BOUNDS_FSSM, - ) - - def run_spv_helper(self, spv, num_records=24): - memory = tv.ReadLog({BASE + k: tv._pattern_word(k) for k in range(-4, 0x80)}) - support.run_fragment( - spv, - inputs={"%wg_id": (0, 0, 0), "%local_id": (0, 0, 0)}, - push_constants=[0, 0, 0x100, OUT_V] + [0] * 28, - memory=memory, - ) - return memory - - def test_wave32_divergent_offsets_raw_load_x4_partial_fill(self): - wave = WaveBufferOobInterpreter(wave_size=32) - base = 0x1000 - nr = 48 - desc = BufferResourceDescriptor.from_fields( - base_address=base, - stride=0, - num_records=nr, - oob_select=3, - ) - wave.set_sgpr_range(4, desc.as_words()) - - # Populate memory with distinctive pattern - for byte_off in range(0, 80, 4): - wave.memory[base + byte_off] = 0x50000000 | byte_off - - # Set divergent offsets for lanes: v1 = lane * 4 - for lane in range(32): - wave.set_lane_vgpr(lane, 1, lane * 4) - - # Execute buffer_load_dwordx4 v[4:7], v1, s[4:7], 0 offen - results = wave.buffer_load_dword( - vdst=4, - srsrc=4, - soffset=0, - inst_offset=0, - vaddr_off_reg=1, - num_dwords=4, - ) - - for lane in range(32): - off = lane * 4 - expected = [] - for k in range(4): - if off + 4 * k + 4 <= nr: - expected.append(0x50000000 | (off + 4 * k)) - else: - expected.append(0) - self.assertEqual(results[lane], expected, f"Mismatch on lane {lane} with offset {off}") - # Check register state - for k in range(4): - self.assertEqual(wave.get_lane_vgpr(lane, 4 + k), expected[k]) - - # Verify specifically the boundary transition lanes: - # Lane 8 (off 32): 32+16 = 48 <= 48 -> all 4 loaded - self.assertEqual(results[8], [0x50000020, 0x50000024, 0x50000028, 0x5000002C]) - # Lane 9 (off 36): dword 3 is OOB (36+16=52 > 48) -> zero fill - self.assertEqual(results[9], [0x50000024, 0x50000028, 0x5000002C, 0]) - # Lane 10 (off 40): dwords 2, 3 OOB -> zero fill - self.assertEqual(results[10], [0x50000028, 0x5000002C, 0, 0]) - # Lane 11 (off 44): dwords 1, 2, 3 OOB -> zero fill - self.assertEqual(results[11], [0x5000002C, 0, 0, 0]) - # Lane 12 (off 48): all dwords OOB -> all zero - self.assertEqual(results[12], [0, 0, 0, 0]) - - def test_wave32_divergent_indices_mode0_partial_fill(self): - wave = WaveBufferOobInterpreter(wave_size=32) - base = 0x2000 - stride = 16 - nr = 8 - desc = BufferResourceDescriptor.from_fields( - base_address=base, - stride=stride, - num_records=nr, - oob_select=0, - ) - wave.set_sgpr_range(4, desc.as_words()) - - # Seed memory - for idx in range(nr): - for off in range(0, stride, 4): - wave.memory[base + idx * stride + off] = (idx << 16) | off - - # Lanes have varying idxen (v1) and offen (v2) - for lane in range(32): - wave.set_lane_vgpr(lane, 1, lane) - wave.set_lane_vgpr(lane, 2, (lane % 5) * 4) - - results = wave.buffer_load_dword( - vdst=4, - srsrc=4, - soffset=0, - inst_offset=0, - vaddr_off_reg=2, - vaddr_idx_reg=1, - num_dwords=4, - ) - - # Mode 0 rule: in-bounds if idx < nr AND off + 4*k + 4 <= stride - # Lane 0: idx 0 < 8, off 0 -> all 4 dwords fit (0, 4, 8, 12, ends <= 16) - self.assertEqual(results[0], [0x00000000, 0x00000004, 0x00000008, 0x0000000C]) - # Lane 1: idx 1 < 8, off 4 -> 3 dwords fit, 4th OOB - self.assertEqual(results[1], [0x00010004, 0x00010008, 0x0001000C, 0]) - # Lane 2: idx 2 < 8, off 8 -> 2 dwords fit, 3rd and 4th OOB - self.assertEqual(results[2], [0x00020008, 0x0002000C, 0, 0]) - # Lane 3: idx 3 < 8, off 12 -> 1 dword fits, others OOB - self.assertEqual(results[3], [0x0003000C, 0, 0, 0]) - # Lane 4: idx 4 < 8, off 16 -> 16+4 > 16 -> all OOB - self.assertEqual(results[4], [0, 0, 0, 0]) - # Lane 8..31: idx >= 8 -> all OOB - for lane in range(8, 32): - self.assertEqual(results[lane], [0, 0, 0, 0]) - - def test_wave64_partial_exec_mask_and_inactive_lanes(self): - wave = WaveBufferOobInterpreter(wave_size=64) - base = 0x4000 - desc = BufferResourceDescriptor.from_fields( - base_address=base, - stride=4, - num_records=64, - oob_select=1, - ) - wave.set_sgpr_range(4, desc.as_words()) - - # Alternate active lanes: 0, 2, 4, ... - exec_mask = 0x5555555555555555 - wave.set_exec_mask(exec_mask) - - for lane in range(64): - wave.set_lane_vgpr(lane, 1, lane) - wave.set_lane_vgpr(lane, 2, 0xDEAD0000 | lane) - - # Active lanes store their data; inactive lanes are masked - written = wave.buffer_store_dword( - vdata=2, - srsrc=4, - soffset=0, - inst_offset=0, - vaddr_idx_reg=1, - num_dwords=1, - ) - for lane in range(64): - if lane % 2 == 0: - self.assertEqual(len(written[lane]), 1) - self.assertEqual(wave.memory[base + lane * 4], 0xDEAD0000 | lane) - else: - self.assertEqual(written[lane], []) - self.assertNotIn(base + lane * 4, wave.memory) - - # Clear vgprs and load back - for lane in range(64): - wave.set_lane_vgpr(lane, 3, 0xFFFFFFFF) - - loaded = wave.buffer_load_dword( - vdst=3, - srsrc=4, - soffset=0, - inst_offset=0, - vaddr_idx_reg=1, - num_dwords=1, - ) - for lane in range(64): - if lane % 2 == 0: - self.assertEqual(loaded[lane], [0xDEAD0000 | lane]) - self.assertEqual(wave.get_lane_vgpr(lane, 3), 0xDEAD0000 | lane) - else: - self.assertEqual(loaded[lane], [0]) - self.assertEqual(wave.get_lane_vgpr(lane, 3), 0) - - def test_wave32_divergent_partial_store_x4_boundary_integrity(self): - wave = WaveBufferOobInterpreter(wave_size=32) - base = 0x5000 - nr = 32 - desc = BufferResourceDescriptor.from_fields( - base_address=base, - stride=0, - num_records=nr, - oob_select=3, - ) - wave.set_sgpr_range(4, desc.as_words()) - - # Test partial component store suppression near boundary - # Lane 0: off 16 -> 4 dwords fit (16..32) - # Lane 1: off 20 -> 3 dwords fit (20..32) - # Lane 2: off 24 -> 2 dwords fit (24..32) - # Lane 3: off 28 -> 1 dword fits (28..32) - # Lane 4: off 32 -> 0 dwords fit - for lane in range(5): - wave.set_lane_vgpr(lane, 1, 16 + lane * 4) - for k in range(4): - wave.set_lane_vgpr(lane, 2 + k, 0x11110000 * (k + 1) | lane) - - # Execute store for each lane independently to observe written addresses - for lane in range(5): - sub_wave = WaveBufferOobInterpreter(wave_size=32) - sub_wave.set_sgpr_range(4, desc.as_words()) - sub_wave.set_lane_vgpr(lane, 1, 16 + lane * 4) - for k in range(4): - sub_wave.set_lane_vgpr(lane, 2 + k, 0x11110000 * (k + 1) | lane) - - written = sub_wave.buffer_store_dword( - vdata=2, - srsrc=4, - soffset=0, - inst_offset=0, - vaddr_off_reg=1, - num_dwords=4, - ) - expected_count = max(0, 4 - lane) - self.assertEqual(len(written[lane]), expected_count, f"Lane {lane} write count mismatch") - # Confirm that no bytes >= base + 32 were ever written - for addr in sub_wave.memory: - self.assertLess(addr, base + nr, f"Out of bounds store leaked past limit: {addr:#x}") - - def test_wave_load_dwordx2_and_dwordx3_partial_fill(self): - wave = WaveBufferOobInterpreter(wave_size=32) - base = 0x6000 - nr = 24 - desc = BufferResourceDescriptor.from_fields( - base_address=base, - stride=0, - num_records=nr, - oob_select=3, - ) - wave.set_sgpr_range(4, desc.as_words()) - for byte_off in range(0, 40, 4): - wave.memory[base + byte_off] = 0x70000000 | byte_off - - # Test x2 loads - wave.set_lane_vgpr(0, 1, 16) # off 16: both dwords fit (16, 20) - wave.set_lane_vgpr(1, 1, 20) # off 20: dword 0 fits, dword 1 OOB - wave.set_lane_vgpr(2, 1, 24) # off 24: both OOB - res_x2 = wave.buffer_load_dword(vdst=2, srsrc=4, vaddr_off_reg=1, num_dwords=2) - self.assertEqual(res_x2[0], [0x70000010, 0x70000014]) - self.assertEqual(res_x2[1], [0x70000014, 0]) - self.assertEqual(res_x2[2], [0, 0]) - - # Test x3 loads - wave.set_lane_vgpr(0, 1, 12) # off 12: all 3 fit (12, 16, 20) - wave.set_lane_vgpr(1, 1, 16) # off 16: 2 fit (16, 20), 1 OOB - wave.set_lane_vgpr(2, 1, 20) # off 20: 1 fits (20), 2 OOB - wave.set_lane_vgpr(3, 1, 24) # off 24: all 3 OOB - res_x3 = wave.buffer_load_dword(vdst=4, srsrc=4, vaddr_off_reg=1, num_dwords=3) - self.assertEqual(res_x3[0], [0x7000000C, 0x70000010, 0x70000014]) - self.assertEqual(res_x3[1], [0x70000010, 0x70000014, 0]) - self.assertEqual(res_x3[2], [0x70000014, 0, 0]) - self.assertEqual(res_x3[3], [0, 0, 0]) - - def test_spirv_translated_wave_partial_oob_zero_fill(self): - # End-to-end test translating buffer_load_dwordx4 with partial component zero fill - # num_records = 24. - # off 12: dwords at 12, 16, 20 fit, dword 24 is OOB -> [P(12), P(16), P(20), 0] - # off 16: dwords at 16, 20 fit, dwords 24, 28 OOB -> [P(16), P(20), 0, 0] - # off 20: dword at 20 fits, others OOB -> [P(20), 0, 0, 0] - # off 24: all OOB -> [0, 0, 0, 0] - cases = [ - (12, [tv._pattern_word(12), tv._pattern_word(16), tv._pattern_word(20), 0]), - (16, [tv._pattern_word(16), tv._pattern_word(20), 0, 0]), - (20, [tv._pattern_word(20), 0, 0, 0]), - (24, [0, 0, 0, 0]), - ] - for off, want in cases: - with self.subTest(offset=off): - lines = [ - f"s_mov_b32 s4, {BASE:#x}", - "s_mov_b32 s5, 0", - "s_mov_b32 s6, 24", - "s_mov_b32 s7, 0x31016FAC", # Mode 3 RAW - f"v_mov_b32 v1, {off}", - "buffer_load_dwordx4 v[4:7], v1, s[4:7], 0 offen", - "s_waitcnt vmcnt(0)", - "buffer_store_dwordx4 v[4:7], off, s[0:3], 0", - ] - spv = self.translate_helper(lines) - memory = self.run_spv_helper(spv) - got = [dict.get(memory, 4 * k, 0) for k in range(4)] - self.assertEqual(got, want, f"Offset {off} yielded {got} instead of {want}") - - -class TestBufferOobStrideNegativeAndControls(unittest.TestCase): - """Tests for stride wrapping, negative offsets, and negative controls.""" - - def translate_helper(self, lines): - return support.translate_lines( - "cs_oob_stride_neg_t", - ["v_cmpx_eq_u32_e32 0, v0", *lines, "s_endpgm"], - fssm=tv.CS_BOUNDS_FSSM, - ) - - def run_spv_helper(self, spv): - memory = tv.ReadLog({BASE + k: tv._pattern_word(k) for k in range(-4, 0x80)}) - support.run_fragment( - spv, - inputs={"%wg_id": (0, 0, 0), "%local_id": (0, 0, 0)}, - push_constants=[0, 0, 0x100, OUT_V] + [0] * 28, - memory=memory, - ) - return memory - - def test_stride_zero_behavior_across_all_modes(self): - # Mode 0 with stride 0: any dword access is out of bounds (off + 4 <= 0 is impossible) - desc_m0 = BufferResourceDescriptor.from_fields(base_address=BASE, stride=0, num_records=16, oob_select=0) - self.assertFalse(BufferOobOracle.check_dword_bounds(desc_m0, k=0, idx=0, off=0)) - self.assertFalse(BufferOobOracle.check_dword_bounds(desc_m0, k=0, idx=None, off=0)) - - # Mode 1 with stride 0: checks idx < num_records, ignoring stride - desc_m1 = BufferResourceDescriptor.from_fields(base_address=BASE, stride=0, num_records=16, oob_select=1) - self.assertTrue(BufferOobOracle.check_dword_bounds(desc_m1, k=0, idx=5, off=64)) - self.assertFalse(BufferOobOracle.check_dword_bounds(desc_m1, k=0, idx=16, off=0)) - - # Mode 2 with stride 0: checks num_records != 0 only - desc_m2 = BufferResourceDescriptor.from_fields(base_address=BASE, stride=0, num_records=16, oob_select=2) - self.assertTrue(BufferOobOracle.check_dword_bounds(desc_m2, k=0, idx=100, off=1024)) - - # Mode 3 with stride 0: raw byte addressing bounded by num_records - desc_m3 = BufferResourceDescriptor.from_fields(base_address=BASE, stride=0, num_records=16, oob_select=3) - self.assertTrue(BufferOobOracle.check_dword_bounds(desc_m3, k=0, off=12)) - self.assertFalse(BufferOobOracle.check_dword_bounds(desc_m3, k=0, off=13)) - - def test_stride_14bit_mask_and_boundary(self): - # Stride is 14 bits (0..16383) - max_stride = 0x3FFF # 16383 - desc = BufferResourceDescriptor.from_fields( - base_address=BASE, - stride=max_stride, - num_records=4, - oob_select=0, - ) - self.assertEqual(desc.stride, 16383) - # Exactly fits: 16379 + 4 = 16383 <= 16383 - self.assertTrue(BufferOobOracle.check_dword_bounds(desc, k=0, idx=0, off=16379)) - # 1-byte overflow: 16380 + 4 = 16384 > 16383 - self.assertFalse(BufferOobOracle.check_dword_bounds(desc, k=0, idx=0, off=16380)) - - def test_stride_wrapping_partial_vector_loads(self): - # Stride 16, num_records 4. Multi-dword loads wrapping past stride - desc = BufferResourceDescriptor.from_fields( - base_address=BASE, - stride=16, - num_records=4, - oob_select=0, - ) - mem = {BASE + 4 * k: 0x1000 + k for k in range(16)} - - # off 8: dword 0 (8..12), dword 1 (12..16) fit; dwords 2, 3 wrap past stride - loaded_8 = BufferOobOracle.load_dwords(desc, num_dwords=4, idx=0, off=8, memory=mem) - self.assertEqual(loaded_8, [0x1002, 0x1003, 0, 0]) - - # off 12: dword 0 (12..16) fits; dwords 1..3 wrap past stride - loaded_12 = BufferOobOracle.load_dwords(desc, num_dwords=4, idx=0, off=12, memory=mem) - self.assertEqual(loaded_12, [0x1003, 0, 0, 0]) - - # off 14: unaligned start straddling stride edge: 14 + 4 = 18 > 16 -> OOB - self.assertFalse(BufferOobOracle.check_dword_bounds(desc, k=0, idx=0, off=14)) - - def test_negative_voffset_32bit_wrap(self): - # A negative 32-bit voffset (e.g. -4 = 0xFFFFFFFC) wraps to high 32-bit address space - # In Mode 0: off = 0xFFFFFFFC; 0xFFFFFFFC + 4 = 0x100000000 (overflow) > stride -> OOB - desc_m0 = BufferResourceDescriptor.from_fields(base_address=BASE, stride=16, num_records=4, oob_select=0) - self.assertFalse(BufferOobOracle.check_dword_bounds(desc_m0, k=0, idx=0, off=0xFFFFFFFC)) - - # In Mode 3: offs = 0xFFFFFFFC > num_records -> OOB - desc_m3 = BufferResourceDescriptor.from_fields(base_address=BASE, stride=0, num_records=32, oob_select=3) - self.assertFalse(BufferOobOracle.check_dword_bounds(desc_m3, k=0, off=0xFFFFFFFC)) - self.assertFalse(BufferOobOracle.check_dword_bounds(desc_m3, k=0, off=0xFFFFFFF0)) - - # Verify in translated SPIR-V for Mode 3 RAW with negative voffset - lines = [ - f"s_mov_b32 s4, {BASE:#x}", - "s_mov_b32 s5, 0", - "s_mov_b32 s6, 32", - "s_mov_b32 s7, 0x31016FAC", # Mode 3 RAW - "v_mov_b32 v1, -4", # negative voffset (0xFFFFFFFC) - "buffer_load_dword v2, v1, s[4:7], 0 offen", - "s_waitcnt vmcnt(0)", - "buffer_store_dword v2, off, s[0:3], 0", - ] - spv = self.translate_helper(lines) - memory = self.run_spv_helper(spv) - self.assertEqual(dict.get(memory, 0, 0), 0) - - def test_negative_soffset_participation_by_mode(self): - # Mode 0: soffset does not participate in the bounds check off = voff + inst_offset - # A negative soffset (e.g. -4) does not invalidate an in-bounds off=0 - desc_m0 = BufferResourceDescriptor.from_fields(base_address=BASE, stride=16, num_records=4, oob_select=0) - self.assertTrue(BufferOobOracle.check_dword_bounds(desc_m0, k=0, idx=0, off=0, soffset=0xFFFFFFFC)) - - # Mode 3: soffset participates in offs = voff + inst_offset + soffset - # A negative soffset that wraps into high 32 bits exceeds num_records and is rejected - desc_m3 = BufferResourceDescriptor.from_fields(base_address=BASE, stride=0, num_records=32, oob_select=3) - self.assertFalse(BufferOobOracle.check_dword_bounds(desc_m3, k=0, off=0, soffset=0xFFFFFFFC)) - - def test_negative_controls_zero_num_records(self): - # When num_records == 0, ALL modes must reject loads and stores - for mode in range(4): - with self.subTest(mode=mode): - desc = BufferResourceDescriptor.from_fields(base_address=BASE, stride=16, num_records=0, oob_select=mode) - self.assertFalse(BufferOobOracle.check_dword_bounds(desc, k=0, idx=0, off=0)) - # Load returns 0 - loaded = BufferOobOracle.load_dwords(desc, num_dwords=1, idx=0, off=0) - self.assertEqual(loaded, [0]) - # Store writes nothing - mem = {} - written = BufferOobOracle.store_dwords(desc, [0x12345678], idx=0, off=0, memory=mem) - self.assertEqual(written, []) - self.assertEqual(mem, {}) - - def test_negative_controls_mesa_gfx10_vs_rdna2_hardware(self): - # Discriminative tests documented in docs/buffer_bounds.md where Mesa GFX10 rule fails on RDNA2: - # Case 1: Raw buffer with N = 3, read at offset 0 - # Mesa GFX10 column (offset >= N): 0 >= 3 is False -> would allow load (WRONG) - # RDNA2 GFX11 column (offset + 4 > N): 0 + 4 = 4 > 3 is True -> OUT OF BOUNDS (CORRECT) - desc_raw_3 = BufferResourceDescriptor.from_fields(base_address=BASE, stride=0, num_records=3, oob_select=3) - self.assertFalse(BufferOobOracle.check_dword_bounds(desc_raw_3, k=0, off=0)) - - # Case 2: Structured buffer with stride 10, inst_offset 8 - # Mesa GFX10 column (offset >= stride): 8 >= 10 is False -> would allow load (WRONG) - # RDNA2 GFX11 column (off + 4 > stride): 8 + 4 = 12 > 10 is True -> OUT OF BOUNDS (CORRECT) - desc_str_10 = BufferResourceDescriptor.from_fields(base_address=BASE, stride=10, num_records=4, oob_select=0) - self.assertFalse(BufferOobOracle.check_dword_bounds(desc_str_10, k=0, idx=0, off=0, inst_offset=8)) - - # Case 3: Raw read with soffset 8, offset 8, N = 18 - # Mesa GFX11 without soffset (offset + 4 > N): 8 + 4 = 12 <= 18 -> would allow load (WRONG) - # RDNA2 measured hardware rule (offset + soffset + 4 > N): 8 + 8 + 4 = 20 > 18 -> OUT OF BOUNDS (CORRECT) - desc_raw_18 = BufferResourceDescriptor.from_fields(base_address=BASE, stride=0, num_records=18, oob_select=3) - self.assertFalse(BufferOobOracle.check_dword_bounds(desc_raw_18, k=0, off=8, soffset=8)) - - # End-to-end translation verification for Case 1 (num_records = 3, offset 0 -> must return 0) - lines = [ - f"s_mov_b32 s4, {BASE:#x}", - "s_mov_b32 s5, 0", - "s_mov_b32 s6, 3", # num_records = 3 - "s_mov_b32 s7, 0x31016FAC", # Mode 3 RAW - "buffer_load_dword v2, off, s[4:7], 0", - "s_waitcnt vmcnt(0)", - "buffer_store_dword v2, off, s[0:3], 0", - ] - spv = self.translate_helper(lines) - memory = self.run_spv_helper(spv) - self.assertEqual(dict.get(memory, 0, 0), 0) - - def test_negative_controls_out_of_range_indices(self): - # In Mode 0 and Mode 1: idx == num_records must be rejected - desc_m0 = BufferResourceDescriptor.from_fields(base_address=BASE, stride=16, num_records=4, oob_select=0) - desc_m1 = BufferResourceDescriptor.from_fields(base_address=BASE, stride=16, num_records=4, oob_select=1) - - self.assertFalse(BufferOobOracle.check_dword_bounds(desc_m0, k=0, idx=4, off=0)) - self.assertFalse(BufferOobOracle.check_dword_bounds(desc_m0, k=0, idx=5, off=0)) - self.assertFalse(BufferOobOracle.check_dword_bounds(desc_m1, k=0, idx=4, off=0)) - self.assertFalse(BufferOobOracle.check_dword_bounds(desc_m1, k=0, idx=10, off=0)) - - # Mode 3 RAW: index is NOT part of bounds check (it is part of address only) - desc_m3 = BufferResourceDescriptor.from_fields(base_address=BASE, stride=16, num_records=32, oob_select=3) - self.assertTrue(BufferOobOracle.check_dword_bounds(desc_m3, k=0, idx=100, off=0)) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_buffer_store_format.py b/tests/semantic/test_buffer_store_format.py deleted file mode 100644 index 52e7343e8..000000000 --- a/tests/semantic/test_buffer_store_format.py +++ /dev/null @@ -1,1012 +0,0 @@ -"""Semantic interpreter tests for AMD RDNA2 / GFX10 typed buffer stores (MTBUF). - -Covers ISA semantics, format conversion, addressing, bounds checking, and translation: - * Typed buffer store instructions: - - tbuffer_store_format_x: 1 component store - - tbuffer_store_format_xy: 2 component store - - tbuffer_store_format_xyz: 3 component store - - tbuffer_store_format_xyzw: 4 component store - * GFX10 format packings & numerical conversions: - - BUF_DATA_FORMAT_8 / BUF_NUM_FORMAT_UNORM (code 1, 8-bit unorm in [0, 255]) - - BUF_DATA_FORMAT_16 / BUF_NUM_FORMAT_FLOAT (code 13/29/71, 16-bit IEEE 754 half) - - BUF_DATA_FORMAT_32 / BUF_NUM_FORMAT_UINT (code 20/62/72/75, 32-bit unsigned int) - - BUF_DATA_FORMAT_32 / BUF_NUM_FORMAT_FLOAT (code 22/64/74/77, 32-bit IEEE 754 single) - * Buffer Resource Descriptor (V# 128-bit layout): - - Dword 0: Base address low 32 bits [31:0] - - Dword 1: Base address high 16 bits [15:0]; Stride in bytes [29:16]; flags [31:30] - - Dword 2: Number of records (num_records capacity limit) - - Dword 3: Format code [18:12]; DST_SEL [11:0]; OOB_SELECT [29:28] - * Addressing calculation: - - effective_offset = (voffset + (soffset & ~3) + inst_offset) - - Structured buffers: effective_offset + vindex * stride - - Effective 64-bit physical address: (base_64 + total_offset) & 0xFFFFFFFFFFFFFFFF - * Bounds checking: - - Stores beyond num_records are silently ignored / no-op (memory untouched). -""" -from __future__ import annotations - -import math -import os -import struct -import sys -import unittest - -HERE = os.path.dirname(os.path.abspath(__file__)) -ROOT = os.path.dirname(os.path.dirname(HERE)) -TOOLS_DIR = os.environ.get("LEONIDA_TOOLS_DIR") or os.path.join(ROOT, "tools") - -sys.dont_write_bytecode = True -if TOOLS_DIR not in sys.path: - sys.path.insert(0, TOOLS_DIR) -if HERE not in sys.path: - sys.path.insert(0, HERE) - -import rdna2spirv # noqa: E402 -import shader_ir # noqa: E402 -import spirv_mini_interp as si # noqa: E402 -import support # noqa: E402 - - -def make_fssm(rsrc2: int = 0x8088, group: tuple[int, int, int] = (64, 1, 1)) -> bytes: - """The compute-shader header words the translator reads: COMPUTE_PGM_RSRC2 and thread group size.""" - header = bytearray(0x148) - struct.pack_into("<4I", header, 0x138, rsrc2, *group) - return bytes(header) - - -CS_FSSM = make_fssm(0x8088, (64, 1, 1)) -OUT_VSHARP = [0, 0, 0xFFFFFFFF, 0x31016FAC] - - -def run_cs(spv: str, memory: dict[int, int], push_constants: list[int] | None = None) -> dict[str, tuple]: - """Execute compute shader through mini-interpreter with specified push constants and memory.""" - pc = push_constants if push_constants is not None else (OUT_VSHARP + [0] * 28) - return si.run_fragment( - spv, - inputs={"%wg_id": (0, 0, 0), "%local_id": (0, 0, 0)}, - push_constants=pc, - memory=memory, - ) - -MASK14 = 0x3FFF -MASK16 = 0xFFFF -MASK32 = 0xFFFFFFFF -MASK64 = 0xFFFFFFFFFFFFFFFF - -BUF_DATA_FORMAT_8 = 1 -BUF_DATA_FORMAT_16 = 2 -BUF_DATA_FORMAT_32 = 4 - -BUF_NUM_FORMAT_UNORM = 1 -BUF_NUM_FORMAT_FLOAT = 7 -BUF_NUM_FORMAT_UINT = 4 -BUF_NUM_FORMAT_SINT = 5 - -GFX10_FMT_8_UNORM = 1 -GFX10_FMT_16_FLOAT = 13 -GFX10_FMT_16_16_FLOAT = 29 -GFX10_FMT_16_16_16_16_FLOAT = 71 -GFX10_FMT_32_UINT = 20 -GFX10_FMT_32_32_UINT = 62 -GFX10_FMT_32_32_32_UINT = 72 -GFX10_FMT_32_32_32_32_UINT = 75 -GFX10_FMT_32_FLOAT = 22 -GFX10_FMT_32_32_FLOAT = 64 -GFX10_FMT_32_32_32_FLOAT = 74 -GFX10_FMT_32_32_32_32_FLOAT = 77 -GFX10_FMT_8_8_8_8_UNORM = 56 - -FORMAT_ELEMENT_SIZES: dict[int, int] = { - GFX10_FMT_8_UNORM: 1, - GFX10_FMT_16_FLOAT: 2, - GFX10_FMT_16_16_FLOAT: 4, - GFX10_FMT_16_16_16_16_FLOAT: 8, - GFX10_FMT_32_UINT: 4, - GFX10_FMT_32_32_UINT: 8, - GFX10_FMT_32_32_32_UINT: 12, - GFX10_FMT_32_32_32_32_UINT: 16, - GFX10_FMT_32_FLOAT: 4, - GFX10_FMT_32_32_FLOAT: 8, - GFX10_FMT_32_32_32_FLOAT: 12, - GFX10_FMT_32_32_32_32_FLOAT: 16, - GFX10_FMT_8_8_8_8_UNORM: 4, -} - - -def pack_unorm8(value: float) -> int: - """Pack single float value into 8-bit unsigned normalized [0, 255]. - - NaN maps to 0.0 before clamping. Clamps to [0.0, 1.0] and rounds to nearest even. - """ - if math.isnan(value): - value = 0.0 - clamped = max(0.0, min(1.0, value)) - scaled = clamped * 255.0 - rounded = int(round(scaled)) - return max(0, min(255, rounded)) - - -def pack_float16(value: float) -> int: - """Pack single float value into 16-bit IEEE 754 half-precision float.""" - raw = struct.pack(" int: - """Pack integer value into 32-bit unsigned integer.""" - return int(value) & MASK32 - - -def pack_float32(value: float) -> int: - """Pack single float value into 32-bit IEEE 754 single-precision bit pattern.""" - raw = struct.pack(" bytes: - """Pack component values into raw bytes for a given GFX10 format code.""" - if format_code == GFX10_FMT_8_UNORM: - val = pack_unorm8(float(values[0])) - return struct.pack(" None: - self.d0 = d0 & MASK32 - self.d1 = d1 & MASK32 - self.d2 = d2 & MASK32 - self.d3 = d3 & MASK32 - - @classmethod - def from_fields( - cls, - base_address: int, - stride: int = 0, - num_records: int = 0, - format_code: int = 0, - dst_sel: int = 0, - oob_select: int = 3, - flags: int = 0, - ) -> BufferResourceDescriptor: - d0 = base_address & MASK32 - base_hi = (base_address >> 32) & MASK16 - stride_field = (stride & MASK14) << 16 - d1 = base_hi | stride_field | ((flags & 3) << 30) - d2 = num_records & MASK32 - d3 = ((format_code & 0x7F) << 12) | (dst_sel & 0xFFF) | ((oob_select & 3) << 28) - return cls(d0, d1, d2, d3) - - @property - def base_lo(self) -> int: - return self.d0 - - @property - def base_hi(self) -> int: - return self.d1 & MASK16 - - @property - def base_address_64(self) -> int: - return ((self.base_hi << 32) | self.base_lo) & MASK64 - - @property - def stride(self) -> int: - return (self.d1 >> 16) & MASK14 - - @property - def num_records(self) -> int: - return self.d2 - - @property - def format_code(self) -> int: - return (self.d3 >> 12) & 0x7F - - @property - def dst_sel(self) -> int: - return self.d3 & 0xFFF - - @property - def oob_select(self) -> int: - return (self.d3 >> 28) & 0x3 - - def as_words(self) -> tuple[int, int, int, int]: - return (self.d0, self.d1, self.d2, self.d3) - - -def compute_typed_buffer_address( - desc: BufferResourceDescriptor, - soffset: int = 0, - inst_offset: int = 0, - voffset: int = 0, - vindex: int | None = None, - element_size: int = 4, -) -> tuple[int, bool, int]: - """Calculates effective 64-bit physical address, in-bounds status, and total byte offset. - - Addressing calculation rule: - effective_offset = (voffset + (soffset & ~3) + inst_offset) - With structured buffers: - total_offset = effective_offset + (vindex * stride if vindex is not None else 0) - - Returns: - (effective_address, in_bounds, total_offset) - """ - masked_soff = soffset & ~3 - effective_offset = (voffset + masked_soff + inst_offset) & MASK32 - - if vindex is not None: - total_offset = (effective_offset + (vindex & MASK32) * desc.stride) & MASK32 - else: - total_offset = effective_offset - - effective_addr = (desc.base_address_64 + total_offset) & MASK64 - - if desc.oob_select == 2: - in_bounds = desc.num_records != 0 - elif desc.oob_select == 0: - if vindex is not None: - idx_ok = (vindex & MASK32) < desc.num_records - off_ok = (effective_offset + element_size) <= desc.stride - in_bounds = idx_ok and off_ok - else: - in_bounds = (total_offset + element_size) <= (desc.num_records * desc.stride) - elif desc.oob_select == 1: - if vindex is not None: - in_bounds = (vindex & MASK32) < desc.num_records - else: - in_bounds = (total_offset + element_size) <= (desc.num_records * desc.stride) - else: - in_bounds = (total_offset + element_size) <= desc.num_records - - return effective_addr, in_bounds, total_offset - - -class TypedBufferReferenceInterpreter: - """Semantic reference interpreter modeling RDNA2 typed buffer stores (MTBUF).""" - - def __init__(self, memory: dict[int, int] | None = None) -> None: - self.memory: dict[int, int] = {} if memory is None else dict(memory) - - def read_dword(self, byte_addr: int) -> int: - aligned = byte_addr & ~3 - return self.memory.get(aligned & MASK64, 0) & MASK32 - - def write_bytes(self, byte_addr: int, data: bytes) -> None: - for offset, byte_val in enumerate(data): - curr_addr = byte_addr + offset - aligned = curr_addr & ~3 - shift = (curr_addr & 3) * 8 - old_dword = self.read_dword(aligned) - cleared = old_dword & ~(0xFF << shift) - new_dword = cleared | ((byte_val & 0xFF) << shift) - self.memory[aligned & MASK64] = new_dword & MASK32 - - def store_format( - self, - vdata: tuple[float | int, ...] | list[float | int], - desc: BufferResourceDescriptor, - soffset: int = 0, - inst_offset: int = 0, - voffset: int = 0, - vindex: int | None = None, - format_code: int = GFX10_FMT_8_UNORM, - ) -> bool: - elem_size = FORMAT_ELEMENT_SIZES.get(format_code, 4) - addr, in_bounds, _ = compute_typed_buffer_address( - desc, - soffset=soffset, - inst_offset=inst_offset, - voffset=voffset, - vindex=vindex, - element_size=elem_size, - ) - if desc.format_code == 0: - return False - if not in_bounds: - return False - packed = pack_typed_format_bytes(vdata, format_code) - self.write_bytes(addr, packed) - return True - - -class TestBufferDescriptor(unittest.TestCase): - def test_descriptor_field_extraction(self) -> None: - base = 0x00007FFF80001000 - stride = 64 - num_records = 256 - format_code = GFX10_FMT_32_32_32_32_FLOAT - dst_sel = 0xF2E - oob_sel = 3 - desc = BufferResourceDescriptor.from_fields( - base_address=base, - stride=stride, - num_records=num_records, - format_code=format_code, - dst_sel=dst_sel, - oob_select=oob_sel, - ) - self.assertEqual(desc.base_lo, 0x80001000) - self.assertEqual(desc.base_hi, 0x7FFF) - self.assertEqual(desc.base_address_64, base) - self.assertEqual(desc.stride, 64) - self.assertEqual(desc.num_records, 256) - self.assertEqual(desc.format_code, GFX10_FMT_32_32_32_32_FLOAT) - self.assertEqual(desc.dst_sel, 0xF2E) - self.assertEqual(desc.oob_select, 3) - - def test_descriptor_raw_words_roundtrip(self) -> None: - words = (0x12345678, 0x0040ABCD, 0x00000400, 0x3004D123) - desc = BufferResourceDescriptor(*words) - self.assertEqual(desc.as_words(), words) - self.assertEqual(desc.base_lo, 0x12345678) - self.assertEqual(desc.base_hi, 0xABCD) - self.assertEqual(desc.stride, 0x40) - self.assertEqual(desc.num_records, 0x400) - self.assertEqual(desc.format_code, (0x3004D123 >> 12) & 0x7F) - self.assertEqual(desc.oob_select, (0x3004D123 >> 28) & 0x3) - - -class TestAddressingCalculations(unittest.TestCase): - def test_soffset_alignment_masking(self) -> None: - desc = BufferResourceDescriptor.from_fields(base_address=0x1000, num_records=1024, oob_select=3) - for unaligned, expected_masked in [(0, 0), (1, 0), (2, 0), (3, 0), (4, 4), (7, 4), (15, 12), (0xFFFFFFFF, 0xFFFFFFFC)]: - addr, in_bounds, total = compute_typed_buffer_address(desc, soffset=unaligned, inst_offset=0, voffset=0) - self.assertEqual(total, expected_masked) - self.assertEqual(addr, 0x1000 + expected_masked) - - def test_effective_offset_formula(self) -> None: - desc = BufferResourceDescriptor.from_fields(base_address=0x2000, num_records=2048, oob_select=3) - voffset = 0x80 - soffset = 0x43 - inst_offset = 0x14 - addr, in_bounds, total = compute_typed_buffer_address(desc, soffset=soffset, inst_offset=inst_offset, voffset=voffset) - self.assertEqual(total, 0x80 + 0x40 + 0x14) - self.assertEqual(addr, 0x2000 + total) - self.assertTrue(in_bounds) - - def test_structured_vindex_stride_addressing(self) -> None: - desc = BufferResourceDescriptor.from_fields(base_address=0x5000, stride=32, num_records=16, oob_select=1) - addr, in_bounds, total = compute_typed_buffer_address(desc, soffset=4, inst_offset=8, voffset=0, vindex=5, element_size=16) - expected_offset = (4 + 8) + (5 * 32) - self.assertEqual(total, expected_offset) - self.assertEqual(addr, 0x5000 + expected_offset) - self.assertTrue(in_bounds) - - def test_bounds_checking_raw_exact(self) -> None: - desc = BufferResourceDescriptor.from_fields(base_address=0, num_records=100, oob_select=3) - _, in_bounds_edge, _ = compute_typed_buffer_address(desc, inst_offset=96, element_size=4) - self.assertTrue(in_bounds_edge) - _, in_bounds_oob, _ = compute_typed_buffer_address(desc, inst_offset=97, element_size=4) - self.assertFalse(in_bounds_oob) - - -class TestFormatPackingReference(unittest.TestCase): - def test_unorm8_packing(self) -> None: - self.assertEqual(pack_unorm8(0.0), 0) - self.assertEqual(pack_unorm8(1.0), 255) - self.assertEqual(pack_unorm8(0.5), 128) - self.assertEqual(pack_unorm8(-1.0), 0) - self.assertEqual(pack_unorm8(2.5), 255) - self.assertEqual(pack_unorm8(float("nan")), 0) - - def test_float16_packing(self) -> None: - self.assertEqual(pack_float16(0.0), 0x0000) - self.assertEqual(pack_float16(1.0), 0x3C00) - self.assertEqual(pack_float16(2.0), 0x4000) - self.assertEqual(pack_float16(-1.0), 0xBC00) - self.assertEqual(pack_float16(65504.0), 0x7BFF) - - def test_uint32_packing(self) -> None: - self.assertEqual(pack_uint32(0), 0) - self.assertEqual(pack_uint32(0xFFFFFFFF), 0xFFFFFFFF) - self.assertEqual(pack_uint32(0x12345678), 0x12345678) - self.assertEqual(pack_uint32(0x100000005), 5) - - def test_float32_packing(self) -> None: - self.assertEqual(pack_float32(0.0), 0x00000000) - self.assertEqual(pack_float32(1.0), 0x3F800000) - self.assertEqual(pack_float32(2.0), 0x40000000) - self.assertEqual(pack_float32(-1.0), 0xBF800000) - - def test_pack_typed_format_bytes(self) -> None: - b_u8 = pack_typed_format_bytes((1.0,), GFX10_FMT_8_UNORM) - self.assertEqual(b_u8, b"\xff") - b_u8_4 = pack_typed_format_bytes((0.0, 0.5, 1.0, 1.0), GFX10_FMT_8_8_8_8_UNORM) - self.assertEqual(b_u8_4, bytes([0, 128, 255, 255])) - b_f16 = pack_typed_format_bytes((1.0, 2.0), GFX10_FMT_16_16_FLOAT) - self.assertEqual(struct.unpack("<2H", b_f16), (0x3C00, 0x4000)) - b_u32 = pack_typed_format_bytes((0x12345678, 0x9ABCDEF0), GFX10_FMT_32_32_UINT) - self.assertEqual(struct.unpack("<2I", b_u32), (0x12345678, 0x9ABCDEF0)) - b_f32 = pack_typed_format_bytes((1.0, 2.0, 3.0, 4.0), GFX10_FMT_32_32_32_32_FLOAT) - self.assertEqual(struct.unpack("<4I", b_f32), (0x3F800000, 0x40000000, 0x40400000, 0x40800000)) - - -class TestTypedStoreReferenceInterpreter(unittest.TestCase): - def test_unorm8_sub_dword_store_preserves_neighbors(self) -> None: - interp = TypedBufferReferenceInterpreter(memory={0x200: 0x11223344}) - desc = BufferResourceDescriptor.from_fields(base_address=0, num_records=0x1000, format_code=GFX10_FMT_8_UNORM) - success = interp.store_format((1.0,), desc, voffset=0x200, format_code=GFX10_FMT_8_UNORM) - self.assertTrue(success) - self.assertEqual(interp.read_dword(0x200), 0x112233FF) - - def test_float16_sub_dword_store_preserves_high_half(self) -> None: - interp = TypedBufferReferenceInterpreter(memory={0x300: 0xAAAA5555}) - desc = BufferResourceDescriptor.from_fields(base_address=0, num_records=0x1000, format_code=GFX10_FMT_16_FLOAT) - success = interp.store_format((1.0,), desc, voffset=0x300, format_code=GFX10_FMT_16_FLOAT) - self.assertTrue(success) - self.assertEqual(interp.read_dword(0x300), 0xAAAA3C00) - - def test_xyzw_float32_multi_dword_store(self) -> None: - interp = TypedBufferReferenceInterpreter() - desc = BufferResourceDescriptor.from_fields(base_address=0x100, num_records=0x1000, format_code=GFX10_FMT_32_32_32_32_FLOAT) - success = interp.store_format((1.0, 2.0, 3.0, 4.0), desc, voffset=0x10, format_code=GFX10_FMT_32_32_32_32_FLOAT) - self.assertTrue(success) - self.assertEqual(interp.read_dword(0x110), 0x3F800000) - self.assertEqual(interp.read_dword(0x114), 0x40000000) - self.assertEqual(interp.read_dword(0x118), 0x40400000) - self.assertEqual(interp.read_dword(0x11C), 0x40800000) - - def test_out_of_bounds_suppressed_memory_unchanged(self) -> None: - interp = TypedBufferReferenceInterpreter(memory={0x200: 0xDEADBEEF}) - desc = BufferResourceDescriptor.from_fields(base_address=0, num_records=0x100, format_code=GFX10_FMT_32_UINT) - success = interp.store_format((0x12345678,), desc, voffset=0x200, format_code=GFX10_FMT_32_UINT) - self.assertFalse(success) - self.assertEqual(interp.read_dword(0x200), 0xDEADBEEF) - - def test_invalid_descriptor_format_suppressed(self) -> None: - interp = TypedBufferReferenceInterpreter(memory={0x200: 0xDEADBEEF}) - desc = BufferResourceDescriptor.from_fields(base_address=0, num_records=0x1000, format_code=0) - success = interp.store_format((1.0,), desc, voffset=0x200, format_code=GFX10_FMT_8_UNORM) - self.assertFalse(success) - self.assertEqual(interp.read_dword(0x200), 0xDEADBEEF) - - -class WaveTypedBufferInterpreter: - """Multi-lane SIMD wave reference interpreter modeling RDNA2 Wave32/Wave64 typed buffer stores.""" - - def __init__(self, wave_size: int = 32, memory: dict[int, int] | None = None) -> None: - self.wave_size = wave_size - self.memory: dict[int, int] = {} if memory is None else dict(memory) - self.exec_mask: int = (1 << wave_size) - 1 - - def set_exec_mask(self, mask: int) -> None: - mask_limit = (1 << self.wave_size) - 1 - self.exec_mask = mask & mask_limit - - def read_dword(self, byte_addr: int) -> int: - aligned = byte_addr & ~3 - return self.memory.get(aligned & MASK64, 0) & MASK32 - - def write_bytes(self, byte_addr: int, data: bytes) -> None: - for offset, byte_val in enumerate(data): - curr_addr = byte_addr + offset - aligned = curr_addr & ~3 - shift = (curr_addr & 3) * 8 - old_dword = self.read_dword(aligned) - cleared = old_dword & ~(0xFF << shift) - new_dword = cleared | ((byte_val & 0xFF) << shift) - self.memory[aligned & MASK64] = new_dword & MASK32 - - def execute_wave_store( - self, - vdatas: list[tuple[float | int, ...] | list[float | int]], - voffsets: list[int], - desc: BufferResourceDescriptor, - soffset: int = 0, - inst_offset: int = 0, - vindices: list[int] | None = None, - format_code: int = GFX10_FMT_32_32_32_32_FLOAT, - ) -> dict[str, int | list[int]]: - """Executes typed buffer store across all wave lanes under the current EXEC mask. - - Inactive lanes (EXEC bit == 0) never store to memory. - Active lanes that are out-of-bounds are silently ignored. - """ - elem_size = FORMAT_ELEMENT_SIZES.get(format_code, 4) - active_count = 0 - stored_count = 0 - written_addrs: list[int] = [] - - if desc.format_code == 0: - return {"active": 0, "stored": 0, "written_addrs": []} - - for lane_id in range(self.wave_size): - is_active = (self.exec_mask & (1 << lane_id)) != 0 - if not is_active: - continue - active_count += 1 - - voff = voffsets[lane_id] if lane_id < len(voffsets) else 0 - vidx = vindices[lane_id] if vindices is not None and lane_id < len(vindices) else None - vdata = vdatas[lane_id] if lane_id < len(vdatas) else () - - addr, in_bounds, _ = compute_typed_buffer_address( - desc, - soffset=soffset, - inst_offset=inst_offset, - voffset=voff, - vindex=vidx, - element_size=elem_size, - ) - - if in_bounds: - packed = pack_typed_format_bytes(vdata, format_code) - self.write_bytes(addr, packed) - stored_count += 1 - written_addrs.append(addr) - - return {"active": active_count, "stored": stored_count, "written_addrs": written_addrs} - - -class TestWaveBoundsAndSIMDDivergence(unittest.TestCase): - def test_wave32_uniform_exec_in_bounds(self) -> None: - wave = WaveTypedBufferInterpreter(wave_size=32) - desc = BufferResourceDescriptor.from_fields( - base_address=0x1000, - num_records=32 * 16, - format_code=GFX10_FMT_32_32_32_32_FLOAT, - oob_select=3, - ) - voffsets = [i * 16 for i in range(32)] - vdatas = [(float(i), float(i * 2), float(i * 3), float(i * 4)) for i in range(32)] - stats = wave.execute_wave_store(vdatas, voffsets, desc, format_code=GFX10_FMT_32_32_32_32_FLOAT) - self.assertEqual(stats["active"], 32) - self.assertEqual(stats["stored"], 32) - for i in range(32): - base_addr = 0x1000 + i * 16 - self.assertEqual(wave.read_dword(base_addr), pack_float32(float(i))) - self.assertEqual(wave.read_dword(base_addr + 4), pack_float32(float(i * 2))) - self.assertEqual(wave.read_dword(base_addr + 8), pack_float32(float(i * 3))) - self.assertEqual(wave.read_dword(base_addr + 12), pack_float32(float(i * 4))) - - def test_wave64_uniform_exec_in_bounds(self) -> None: - wave = WaveTypedBufferInterpreter(wave_size=64) - desc = BufferResourceDescriptor.from_fields( - base_address=0x2000, - num_records=64 * 16, - format_code=GFX10_FMT_32_32_32_32_UINT, - oob_select=3, - ) - voffsets = [i * 16 for i in range(64)] - vdatas = [(0x1000 + i, 0x2000 + i, 0x3000 + i, 0x4000 + i) for i in range(64)] - stats = wave.execute_wave_store(vdatas, voffsets, desc, format_code=GFX10_FMT_32_32_32_32_UINT) - self.assertEqual(stats["active"], 64) - self.assertEqual(stats["stored"], 64) - for i in range(64): - base_addr = 0x2000 + i * 16 - self.assertEqual(wave.read_dword(base_addr), 0x1000 + i) - self.assertEqual(wave.read_dword(base_addr + 4), 0x2000 + i) - self.assertEqual(wave.read_dword(base_addr + 8), 0x3000 + i) - self.assertEqual(wave.read_dword(base_addr + 12), 0x4000 + i) - - def test_divergent_exec_mask_inactive_lanes_suppression(self) -> None: - memory = {0x1000 + 4 * k: 0xDEADBEEF for k in range(32 * 4)} - wave = WaveTypedBufferInterpreter(wave_size=32, memory=memory) - wave.set_exec_mask(0x55555555) # Even lanes active (0, 2, 4...), odd lanes inactive - desc = BufferResourceDescriptor.from_fields( - base_address=0x1000, - num_records=32 * 16, - format_code=GFX10_FMT_32_32_32_32_UINT, - oob_select=3, - ) - voffsets = [i * 16 for i in range(32)] - vdatas = [(0xA000 + i, 0xB000 + i, 0xC000 + i, 0xD000 + i) for i in range(32)] - stats = wave.execute_wave_store(vdatas, voffsets, desc, format_code=GFX10_FMT_32_32_32_32_UINT) - self.assertEqual(stats["active"], 16) - self.assertEqual(stats["stored"], 16) - - for i in range(32): - base_addr = 0x1000 + i * 16 - if i % 2 == 0: - self.assertEqual(wave.read_dword(base_addr), 0xA000 + i) - self.assertEqual(wave.read_dword(base_addr + 4), 0xB000 + i) - self.assertEqual(wave.read_dword(base_addr + 8), 0xC000 + i) - self.assertEqual(wave.read_dword(base_addr + 12), 0xD000 + i) - else: - for dword_idx in range(4): - self.assertEqual(wave.read_dword(base_addr + 4 * dword_idx), 0xDEADBEEF) - - def test_half_wave_divergence(self) -> None: - memory = {0x4000 + 4 * k: 0xCAFEBABE for k in range(64 * 4)} - wave = WaveTypedBufferInterpreter(wave_size=64, memory=memory) - wave.set_exec_mask(0x00000000FFFFFFFF) # Lower 32 lanes active, upper 32 inactive - desc = BufferResourceDescriptor.from_fields( - base_address=0x4000, - num_records=64 * 16, - format_code=GFX10_FMT_32_32_32_32_UINT, - oob_select=3, - ) - voffsets = [i * 16 for i in range(64)] - vdatas = [(0x1111 * (i + 1), 0x2222 * (i + 1), 0x3333 * (i + 1), 0x4444 * (i + 1)) for i in range(64)] - stats = wave.execute_wave_store(vdatas, voffsets, desc, format_code=GFX10_FMT_32_32_32_32_UINT) - self.assertEqual(stats["active"], 32) - self.assertEqual(stats["stored"], 32) - - for i in range(32): - base_addr = 0x4000 + i * 16 - self.assertEqual(wave.read_dword(base_addr), 0x1111 * (i + 1)) - for i in range(32, 64): - base_addr = 0x4000 + i * 16 - for dword_idx in range(4): - self.assertEqual(wave.read_dword(base_addr + 4 * dword_idx), 0xCAFEBABE) - - def test_single_lane_divergence(self) -> None: - memory = {0x3000 + 4 * k: 0x12345678 for k in range(32 * 4)} - wave = WaveTypedBufferInterpreter(wave_size=32, memory=memory) - target_lane = 13 - wave.set_exec_mask(1 << target_lane) - desc = BufferResourceDescriptor.from_fields( - base_address=0x3000, - num_records=32 * 16, - format_code=GFX10_FMT_32_32_32_32_UINT, - oob_select=3, - ) - voffsets = [i * 16 for i in range(32)] - vdatas = [(0x7777, 0x8888, 0x9999, 0xAAAA) for _ in range(32)] - stats = wave.execute_wave_store(vdatas, voffsets, desc, format_code=GFX10_FMT_32_32_32_32_UINT) - self.assertEqual(stats["active"], 1) - self.assertEqual(stats["stored"], 1) - - for i in range(32): - base_addr = 0x3000 + i * 16 - if i == target_lane: - self.assertEqual(wave.read_dword(base_addr), 0x7777) - self.assertEqual(wave.read_dword(base_addr + 4), 0x8888) - self.assertEqual(wave.read_dword(base_addr + 8), 0x9999) - self.assertEqual(wave.read_dword(base_addr + 12), 0xAAAA) - else: - for dword_idx in range(4): - self.assertEqual(wave.read_dword(base_addr + 4 * dword_idx), 0x12345678) - - def test_simd_lane_oob_suppression_boundary(self) -> None: - memory = {0x1000 + 4 * k: 0xBAADF00D for k in range(32 * 4)} - wave = WaveTypedBufferInterpreter(wave_size=32, memory=memory) - desc = BufferResourceDescriptor.from_fields( - base_address=0x1000, - num_records=16 * 16, # Exactly 16 records of 16 bytes = 256 bytes - format_code=GFX10_FMT_32_32_32_32_UINT, - oob_select=3, - ) - voffsets = [i * 16 for i in range(32)] - vdatas = [(0x5000 + i, 0x6000 + i, 0x7000 + i, 0x8000 + i) for i in range(32)] - stats = wave.execute_wave_store(vdatas, voffsets, desc, format_code=GFX10_FMT_32_32_32_32_UINT) - self.assertEqual(stats["active"], 32) - self.assertEqual(stats["stored"], 16) - - for i in range(16): - base_addr = 0x1000 + i * 16 - self.assertEqual(wave.read_dword(base_addr), 0x5000 + i) - for i in range(16, 32): - base_addr = 0x1000 + i * 16 - for dword_idx in range(4): - self.assertEqual(wave.read_dword(base_addr + 4 * dword_idx), 0xBAADF00D) - - def test_xyzw_element_size_straddle_boundary(self) -> None: - memory = {0x5000 + 4 * k: 0x55555555 for k in range(32)} - wave = WaveTypedBufferInterpreter(wave_size=2, memory=memory) - # Limit is 100 bytes. - # Lane 0: offset 80 -> 80 + 16 = 96 <= 100 (in-bounds) - # Lane 1: offset 88 -> 88 + 16 = 104 > 100 (straddles boundary -> out of bounds) - desc = BufferResourceDescriptor.from_fields( - base_address=0x5000, - num_records=100, - format_code=GFX10_FMT_32_32_32_32_UINT, - oob_select=3, - ) - voffsets = [80, 88] - vdatas = [(1, 2, 3, 4), (5, 6, 7, 8)] - stats = wave.execute_wave_store(vdatas, voffsets, desc, format_code=GFX10_FMT_32_32_32_32_UINT) - self.assertEqual(stats["active"], 2) - self.assertEqual(stats["stored"], 1) - - self.assertEqual(wave.read_dword(0x5000 + 80), 1) - self.assertEqual(wave.read_dword(0x5000 + 84), 2) - self.assertEqual(wave.read_dword(0x5000 + 88), 3) - self.assertEqual(wave.read_dword(0x5000 + 92), 4) - # Memory past 96 was never modified by lane 1 - self.assertEqual(wave.read_dword(0x5000 + 96), 0x55555555) - - def test_channel_variants_multi_lane(self) -> None: - # Test x (1-comp), xy (2-comp), xyz (3-comp), xyzw (4-comp) - wave = WaveTypedBufferInterpreter(wave_size=4) - # x variant (4 bytes per element) - desc_x = BufferResourceDescriptor.from_fields(0x1000, num_records=64, format_code=GFX10_FMT_32_UINT, oob_select=3) - stats_x = wave.execute_wave_store([(10,), (20,), (30,), (40,)], [0, 4, 8, 12], desc_x, format_code=GFX10_FMT_32_UINT) - self.assertEqual(stats_x["stored"], 4) - for i, val in enumerate([10, 20, 30, 40]): - self.assertEqual(wave.read_dword(0x1000 + 4 * i), val) - - # xy variant (8 bytes per element) - desc_xy = BufferResourceDescriptor.from_fields(0x2000, num_records=64, format_code=GFX10_FMT_32_32_UINT, oob_select=3) - stats_xy = wave.execute_wave_store([(1, 2), (3, 4), (5, 6), (7, 8)], [0, 8, 16, 24], desc_xy, format_code=GFX10_FMT_32_32_UINT) - self.assertEqual(stats_xy["stored"], 4) - self.assertEqual(wave.read_dword(0x2000 + 16), 5) - self.assertEqual(wave.read_dword(0x2000 + 20), 6) - - # xyz variant (12 bytes per element) - wave_xyz = WaveTypedBufferInterpreter(wave_size=2) - desc_xyz = BufferResourceDescriptor.from_fields(0x3000, num_records=64, format_code=GFX10_FMT_32_32_32_UINT, oob_select=3) - stats_xyz = wave_xyz.execute_wave_store([(1, 2, 3), (4, 5, 6)], [0, 12], desc_xyz, format_code=GFX10_FMT_32_32_32_UINT) - self.assertEqual(stats_xyz["stored"], 2) - self.assertEqual(wave_xyz.read_dword(0x3000 + 12), 4) - self.assertEqual(wave_xyz.read_dword(0x3000 + 16), 5) - self.assertEqual(wave_xyz.read_dword(0x3000 + 20), 6) - - def test_structured_stride_multi_lane(self) -> None: - wave = WaveTypedBufferInterpreter(wave_size=8) - desc = BufferResourceDescriptor.from_fields( - base_address=0x8000, - stride=32, - num_records=5, # Only first 5 records valid - format_code=GFX10_FMT_32_32_UINT, - oob_select=1, - ) - vindices = list(range(8)) - voffsets = [0] * 8 - vdatas = [(100 + i, 200 + i) for i in range(8)] - stats = wave.execute_wave_store(vdatas, voffsets, desc, vindices=vindices, format_code=GFX10_FMT_32_32_UINT) - self.assertEqual(stats["active"], 8) - self.assertEqual(stats["stored"], 5) - for i in range(5): - self.assertEqual(wave.read_dword(0x8000 + i * 32), 100 + i) - self.assertEqual(wave.read_dword(0x8000 + i * 32 + 4), 200 + i) - - def test_soffset_inst_offset_multi_lane(self) -> None: - wave = WaveTypedBufferInterpreter(wave_size=4) - desc = BufferResourceDescriptor.from_fields(base_address=0x6000, num_records=256, format_code=GFX10_FMT_32_UINT, oob_select=3) - soffset = 0x23 # Will be masked to 0x20 - inst_offset = 0x10 - voffsets = [0, 4, 8, 12] - vdatas = [(100,), (200,), (300,), (400,)] - stats = wave.execute_wave_store(vdatas, voffsets, desc, soffset=soffset, inst_offset=inst_offset, format_code=GFX10_FMT_32_UINT) - self.assertEqual(stats["stored"], 4) - expected_base = 0x6000 + 0x20 + 0x10 - for i, val in enumerate([100, 200, 300, 400]): - self.assertEqual(wave.read_dword(expected_base + 4 * i), val) - - -class TestSpirvEmission(unittest.TestCase): - def test_tbuffer_store_emits_storage_buffer_ops_not_image_write(self) -> None: - spv = support.translate_lines( - "cs_tbuf_spv_emission", - [ - "v_mov_b32_e32 v20, 1.0", - "v_mov_b32_e32 v21, 2.0", - "v_mov_b32_e32 v22, 3.0", - "v_mov_b32_e32 v23, 4.0", - "v_mov_b32_e32 v5, 0x200", - "tbuffer_store_format_xyzw v[20:23], v5, s[0:3], 0 format:[BUF_FMT_32_32_32_32_FLOAT] offen", - "s_endpgm", - ], - fssm=CS_FSSM, - ) - self.assertIn("OpConvertUToPtr", spv) - self.assertIn("OpStore", spv) - self.assertIn("OpBranchConditional", spv) - self.assertIn("OpSelectionMerge", spv) - self.assertNotIn("OpImageWrite", spv) - - def test_image_store_contrast_emits_op_image_write(self) -> None: - g = rdna2spirv.Gen("cs") - ins = shader_ir.parse_line("image_store v[1:4], v[10:11], s[0:7] dmask:0xf dim:SQ_RSRC_IMG_2D") - g.image_store(ins["args"], ins["mods"], "dim:SQ_RSRC_IMG_2D") - has_image_write = any("OpImageWrite" in ln for ln in g.body) - self.assertTrue(has_image_write) - - def test_sub_dword_unorm8_emits_atomic_rmw(self) -> None: - spv = support.translate_lines( - "cs_tbuf_atomic_rmw", - [ - "v_mov_b32_e32 v20, 1.0", - "v_mov_b32_e32 v5, 0x200", - "tbuffer_store_format_x v20, v5, s[0:3], 0 format:[BUF_FMT_8_UNORM] offen", - "s_endpgm", - ], - fssm=CS_FSSM, - ) - self.assertIn("OpAtomicAnd", spv) - self.assertIn("OpAtomicOr", spv) - - -class TestSpirvNegativeControls(unittest.TestCase): - def test_unsupported_format_raises_exception(self) -> None: - with self.assertRaises(rdna2spirv.Unsupported): - support.translate_lines( - "cs_tbuf_unsupported_fmt", - [ - "v_mov_b32_e32 v20, 1.0", - "v_mov_b32_e32 v5, 0x200", - "tbuffer_store_format_x v20, v5, s[0:3], 0 format:[BUF_FMT_INVALID] offen", - "s_endpgm", - ], - fssm=CS_FSSM, - ) - - def test_unsupported_modifier_lds_raises_exception(self) -> None: - with self.assertRaises(rdna2spirv.Unsupported): - support.translate_lines( - "cs_tbuf_unsupported_mod", - [ - "v_mov_b32_e32 v20, 1.0", - "v_mov_b32_e32 v5, 0x200", - "tbuffer_store_format_x v20, v5, s[0:3], 0 lds format:[BUF_FMT_8_UNORM] offen", - "s_endpgm", - ], - fssm=CS_FSSM, - ) - - def test_invalid_vsharp_sgpr_count_raises_exception(self) -> None: - with self.assertRaises(rdna2spirv.Unsupported): - support.translate_lines( - "cs_tbuf_invalid_sgpr", - [ - "v_mov_b32_e32 v20, 1.0", - "v_mov_b32_e32 v5, 0x200", - "tbuffer_store_format_x v20, v5, s[0:1], 0 format:[BUF_FMT_8_UNORM] offen", - "s_endpgm", - ], - fssm=CS_FSSM, - ) - - -class TestSpirvEndToEndExecution(unittest.TestCase): - def test_e2e_tbuffer_store_format_x_unorm8(self) -> None: - spv = support.translate_lines( - "cs_e2e_tbuf_u8", - [ - "v_mov_b32_e32 v20, 1.0", - "v_mov_b32_e32 v5, 0x200", - "tbuffer_store_format_x v20, v5, s[0:3], 0 format:[BUF_FMT_8_UNORM] offen", - "s_endpgm", - ], - fssm=CS_FSSM, - ) - memory = {0x200: 0x11223344} - run_cs(spv, memory) - self.assertEqual(memory[0x200], 0x112233FF) - - def test_e2e_tbuffer_store_format_xy_f16(self) -> None: - spv = support.translate_lines( - "cs_e2e_tbuf_f16", - [ - "v_mov_b32_e32 v20, 1.0", - "v_mov_b32_e32 v21, 2.0", - "v_mov_b32_e32 v5, 0x200", - "tbuffer_store_format_xy v[20:21], v5, s[0:3], 0 format:[BUF_FMT_16_16_FLOAT] offen", - "s_endpgm", - ], - fssm=CS_FSSM, - ) - memory = {0x200: 0xDEADBEEF} - run_cs(spv, memory) - self.assertEqual(memory[0x200], 0x40003C00) - - def test_e2e_tbuffer_store_format_xy_u32(self) -> None: - spv = support.translate_lines( - "cs_e2e_tbuf_u32", - [ - "v_mov_b32_e32 v20, 0x12345678", - "v_mov_b32_e32 v21, 0x9ABCDEF0", - "v_mov_b32_e32 v5, 0x200", - "tbuffer_store_format_xy v[20:21], v5, s[0:3], 0 format:[BUF_FMT_32_32_UINT] offen", - "s_endpgm", - ], - fssm=CS_FSSM, - ) - memory: dict[int, int] = {} - run_cs(spv, memory) - self.assertEqual(memory[0x200], 0x12345678) - self.assertEqual(memory[0x204], 0x9ABCDEF0) - - def test_e2e_tbuffer_store_format_xyzw_f32(self) -> None: - spv = support.translate_lines( - "cs_e2e_tbuf_f32", - [ - "v_mov_b32_e32 v20, 1.0", - "v_mov_b32_e32 v21, 2.0", - "v_mov_b32_e32 v22, 3.0", - "v_mov_b32_e32 v23, 4.0", - "v_mov_b32_e32 v5, 0x200", - "tbuffer_store_format_xyzw v[20:23], v5, s[0:3], 0 format:[BUF_FMT_32_32_32_32_FLOAT] offen", - "s_endpgm", - ], - fssm=CS_FSSM, - ) - memory: dict[int, int] = {} - run_cs(spv, memory) - self.assertEqual(memory[0x200], 0x3F800000) - self.assertEqual(memory[0x204], 0x40000000) - self.assertEqual(memory[0x208], 0x40400000) - self.assertEqual(memory[0x20C], 0x40800000) - - def test_e2e_oob_zero_clamp_beyond_num_records(self) -> None: - spv = support.translate_lines( - "cs_e2e_tbuf_oob_clamp", - [ - "v_mov_b32_e32 v20, 1.0", - "v_mov_b32_e32 v5, 0x200", - "tbuffer_store_format_x v20, v5, s[0:3], 0 format:[BUF_FMT_8_UNORM] offen", - "s_endpgm", - ], - fssm=CS_FSSM, - ) - memory = {0x200: 0xCAFEBABE} - # num_records is 0x100 (256 bytes), store target is 0x200 (512 bytes) -> OOB - oob_vsharp = [0, 0, 0x100, 0x31016FAC] - run_cs(spv, memory, push_constants=oob_vsharp + [0] * 28) - self.assertEqual(memory[0x200], 0xCAFEBABE) - - def test_e2e_oob_zero_clamp_element_straddle(self) -> None: - spv = support.translate_lines( - "cs_e2e_tbuf_straddle_clamp", - [ - "v_mov_b32_e32 v20, 1.0", - "v_mov_b32_e32 v21, 2.0", - "v_mov_b32_e32 v22, 3.0", - "v_mov_b32_e32 v23, 4.0", - "v_mov_b32_e32 v5, 0x200", - "tbuffer_store_format_xyzw v[20:23], v5, s[0:3], 0 format:[BUF_FMT_32_32_32_32_FLOAT] offen", - "s_endpgm", - ], - fssm=CS_FSSM, - ) - memory = { - 0x200: 0xDEADBEEF, - 0x204: 0xDEADBEEF, - 0x208: 0xDEADBEEF, - 0x20C: 0xDEADBEEF, - } - # num_records is 0x204 (516 bytes). 16-byte store at 0x200 needs bytes up to 0x210 -> straddles end! - straddle_vsharp = [0, 0, 0x204, 0x31016FAC] - run_cs(spv, memory, push_constants=straddle_vsharp + [0] * 28) - for dword_addr in (0x200, 0x204, 0x208, 0x20C): - self.assertEqual(memory[dword_addr], 0xDEADBEEF) - - def test_e2e_invalid_vsharp_format_suppressed(self) -> None: - spv = support.translate_lines( - "cs_e2e_tbuf_invalid_vsharp_fmt", - [ - "v_mov_b32_e32 v20, 1.0", - "v_mov_b32_e32 v5, 0x200", - "tbuffer_store_format_x v20, v5, s[0:3], 0 format:[BUF_FMT_8_UNORM] offen", - "s_endpgm", - ], - fssm=CS_FSSM, - ) - memory = {0x200: 0x55555555} - # V# format field (bits 18:12) set to 0 (GFX10_FORMAT_INVALID) - invalid_fmt_vsharp = [0, 0, 0xFFFFFFFF, 0x31000FAC] - run_cs(spv, memory, push_constants=invalid_fmt_vsharp + [0] * 28) - self.assertEqual(memory[0x200], 0x55555555) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_buffer_store_rdna2.py b/tests/semantic/test_buffer_store_rdna2.py deleted file mode 100644 index ca0d4a93d..000000000 --- a/tests/semantic/test_buffer_store_rdna2.py +++ /dev/null @@ -1,156 +0,0 @@ -"""RDNA2 (gfx1036) buffer format store semantics (SHADER-364): -1. UNORM/SNORM format stores round the exact product clamp(x) * scale once (ties away from zero), - matching native gfx1036 (wave32 and wave64, MUBUF and MTBUF): e.g. UNORM16(0.3) == 19661 (not 19660). -2. 2-component MUBUF buffer_store_format_* stores infer COMP_SWAP from V# DST_SEL_X/Y/Z: - XY01 -> (x, y), YX01 -> (y, x), XYZW -> (x, w) (so _xy writes (x, 0)), YXZW/ZYXW -> (w, x); - MTBUF tbuffer_store_format_* ignores DST_SEL and always stores (x, y). -""" -from __future__ import annotations - -import os -import shutil -import struct -import subprocess -import sys -import tempfile -import unittest - -import warnings - -HERE = os.path.dirname(os.path.abspath(__file__)) -ROOT = os.path.dirname(os.path.dirname(HERE)) -sys.dont_write_bytecode = True -sys.path.insert(0, os.environ.get("LEONIDA_TOOLS_DIR") or os.path.join(ROOT, "tools")) -sys.path.insert(0, HERE) - -import buffer_store_probe as probe # noqa: E402 -import rdna2spirv # noqa: E402 -import spirv_mini_interp as si # noqa: E402 - -BASE = 0x1000 -STUB_DXBC = b"DXBC" + bytes(24) + struct.pack(" (x, y) for both _xy and _xyzw - self.assertEqual(_run_store("buffer_store_format_xy", 62, (4, 5, 0, 1), vals), (0x11111111, 0x22222222)) - self.assertEqual(_run_store("buffer_store_format_xyzw", 62, (4, 5, 0, 1), vals), (0x11111111, 0x22222222)) - # YX01 -> (y, x) - self.assertEqual(_run_store("buffer_store_format_xyzw", 62, (5, 4, 0, 1), vals), (0x22222222, 0x11111111)) - # XYZW -> (x, w) for _xyzw and (x, 0) for _xy - self.assertEqual(_run_store("buffer_store_format_xyzw", 62, (4, 5, 6, 7), vals), (0x11111111, 0x44444444)) - self.assertEqual(_run_store("buffer_store_format_xy", 62, (4, 5, 6, 7), vals), (0x11111111, 0x00000000)) - # YXZW -> (w, x) - self.assertEqual(_run_store("buffer_store_format_xyzw", 62, (5, 4, 6, 7), vals), (0x44444444, 0x11111111)) - - def test_mubuf_2comp_packed_and_norm_formats(self): - # 8_8_UINT (18): XY01 -> 0xdead2211, XYZW xyzw -> 0xdead4411, XYZW xy -> 0xdead0011 - w0, _ = _run_store("buffer_store_format_xyzw", 18, (4, 5, 0, 1), (0x11, 0x22, 0x33, 0x44)) - self.assertEqual(w0, 0xDEAD2211) - w0, _ = _run_store("buffer_store_format_xyzw", 18, (4, 5, 6, 7), (0x11, 0x22, 0x33, 0x44)) - self.assertEqual(w0, 0xDEAD4411) - w0, _ = _run_store("buffer_store_format_xy", 18, (4, 5, 6, 7), (0x11, 0x22, 0x33, 0x44)) - self.assertEqual(w0, 0xDEAD0011) - # 16_16_UNORM (23): (0.25, 0.5, 0.75, 1.0) - flt = tuple(probe.f32_to_u32(x) for x in (0.25, 0.5, 0.75, 1.0)) - w0, _ = _run_store("buffer_store_format_xyzw", 23, (4, 5, 0, 1), flt) - self.assertEqual(w0, 0x80004000) - w0, _ = _run_store("buffer_store_format_xyzw", 23, (4, 5, 6, 7), flt) - self.assertEqual(w0, 0xFFFF4000) - # d16_xyzw and d16_xy on 16_16_UINT (27) - d16_vals = (0x22221111, 0x44443333) - w0, _ = _run_store("buffer_store_format_d16_xyzw", 27, (4, 5, 0, 1), d16_vals, d16=True) - self.assertEqual(w0, 0x22221111) - w0, _ = _run_store("buffer_store_format_d16_xyzw", 27, (4, 5, 6, 7), d16_vals, d16=True) - self.assertEqual(w0, 0x44441111) - w0, _ = _run_store("buffer_store_format_d16_xy", 27, (4, 5, 6, 7), d16_vals, d16=True) - self.assertEqual(w0, 0x00001111) - - def test_mtbuf_2comp_ignores_dst_sel(self): - vals = (0x11111111, 0x22222222, 0x33333333, 0x44444444) - self.assertEqual(_run_store("tbuffer_store_format_xyzw", 62, (4, 5, 6, 7), vals, fixed_fmt=True), - (0x11111111, 0x22222222)) - self.assertEqual(_run_store("tbuffer_store_format_xyzw", 62, (5, 4, 6, 7), vals, fixed_fmt=True), - (0x11111111, 0x22222222)) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_buffer_store_sub_fixture.py b/tests/semantic/test_buffer_store_sub_fixture.py deleted file mode 100644 index 2dee9ec94..000000000 --- a/tests/semantic/test_buffer_store_sub_fixture.py +++ /dev/null @@ -1,80 +0,0 @@ -"""cs_w32_buffer_store_sub: the GPU test of the plain 8/16-bit MUBUF stores (#1864), run here on the CPU too. - -Standard library only; no GPU, no LLVM, no game files. - -runtime/test/shaders/cs_w32_buffer_store_sub.asm (derivations in its header) seeds six dwords, stores bytes and shorts -into them (one short crossing a dword) and reads them back, from lane 0. This runs it as one wave32 group through -spirv_mini_interp with vk_compute_test's buffer, checks the words against a byte-level model, and that check.py and -scripts/run_gpu_tests.py expect the same words. -""" -import os -import re -import struct -import sys -import unittest - -HERE = os.path.dirname(os.path.abspath(__file__)) -if HERE not in sys.path: - sys.path.insert(0, HERE) # python -I leaves the script's folder off sys.path - -import support # noqa: E402 (support puts tools/ on sys.path, honouring LEONIDA_TOOLS_DIR) -import spirv_mini_interp as si # noqa: E402 - -ROOT = os.path.dirname(os.path.dirname(HERE)) -FSSM = bytearray(0x148) -struct.pack_into("<4I", FSSM, 0x138, 0x88, 32, 1, 1) -FSSM = bytes(FSSM) -SEED = {0x40: 0x11223344, 0x44: 0x55667788, 0x48: 0x99AABBCC, 0x4C: 0xDDDDDDDD, 0x50: 0x01020304, 0x54: 0x05060708} - - -def model(): - mem = dict(SEED) - - def store_byte(addr, v): - d, sh = addr & ~3, 8 * (addr & 3) - mem[d] = (mem[d] & ~(0xFF << sh)) | ((v & 0xFF) << sh) - - def store_short(addr, v): # one byte at a time: a short at byte 3 crosses into the next dword - store_byte(addr, v) - store_byte(addr + 1, v >> 8) - - store_byte(0x41, 0xAB) - store_short(0x46, 0xCDEF) - store_short(0x4B, 0x1234) - store_byte(0x50, 0xFFFFFF5A) - store_short(0x54, 0xABCD1234) - byte = lambda a: (mem[a & ~3] >> (8 * (a & 3))) & 0xFF - sh = byte(0x46) | byte(0x47) << 8 - return [mem[0x40], mem[0x44], mem[0x48], mem[0x4C], mem[0x50], mem[0x54], byte(0x41), - sh | 0xFFFF0000 if sh & 0x8000 else sh] - - -EXPECTED = model() - - -class BufferStoreSubFixture(unittest.TestCase): - def test_reference(self): - self.assertEqual(EXPECTED, [0x1122AB44, 0xCDEF7788, 0x34AABBCC, 0xDDDDDD12, 0x0102035A, 0x05061234, 0xAB, - 0xFFFFCDEF]) - - def test_translated_shader(self): - spv = support.translate_fixture("cs_w32_buffer_store_sub", fssm=FSSM) - mem = {4 * k: 0xEEEEEEEE for k in range(64)} - si.run_workgroup(spv, 32, 32, inputs_for=lambda i: {"%wg_id": (0, 0, 0), "%local_id": (i, 0, 0), - "%sg_lane": i}, - push_constants=[0, 0, 0xFFFFFFFF, 0x31016FAC] + [0] * 28, memory=mem) - for k, want in enumerate(EXPECTED): - with self.subTest(word=k): - self.assertEqual(mem[4 * k], want) - - def test_gpu_runners_expect_the_same_words(self): - for rel in (("runtime", "test", "shaders", "check.py"), ("scripts", "run_gpu_tests.py")): - with open(os.path.join(ROOT, *rel), encoding="utf-8") as f: - m = re.search(r'"cs_w32_buffer_store_sub"\)?[,:]\s*\[([^\]]*)\]', f.read()) - with self.subTest(file="/".join(rel)): - self.assertIsNotNone(m) - self.assertEqual([int(v, 0) for v in m.group(1).split(",")], EXPECTED) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_buffer_sub16_fixture.py b/tests/semantic/test_buffer_sub16_fixture.py deleted file mode 100644 index c4284276c..000000000 --- a/tests/semantic/test_buffer_sub16_fixture.py +++ /dev/null @@ -1,77 +0,0 @@ -"""cs_w32_buffer_sub16: the GPU test of the 8/16-bit MUBUF d16 loads and stores (#1864), run here on the CPU too. - -Standard library only; no GPU, no LLVM, no game files. - -runtime/test/shaders/cs_w32_buffer_sub16.asm (derivations in its header) stores eight words from lane 0. This runs its -fixture as one wave32 group through spirv_mini_interp with vk_compute_test's buffer (every byte 0xEE, a V# with -num_records 0xFFFFFFFF), checks the words against a byte-level model of the d16 rules, and that check.py and -scripts/run_gpu_tests.py expect the same words. -""" -import os -import re -import struct -import sys -import unittest - -HERE = os.path.dirname(os.path.abspath(__file__)) -if HERE not in sys.path: - sys.path.insert(0, HERE) # python -I leaves the script's folder off sys.path - -import support # noqa: E402 (support puts tools/ on sys.path, honouring LEONIDA_TOOLS_DIR) -import spirv_mini_interp as si # noqa: E402 - -ROOT = os.path.dirname(os.path.dirname(HERE)) -FSSM = bytearray(0x148) -struct.pack_into("<4I", FSSM, 0x138, 0x88, 32, 1, 1) -FSSM = bytes(FSSM) -KEEP, D40, D50, D60 = 0xBEEF1234, 0x8899AABB, 0x11223344, 0x55667788 - - -def byte(w, i): - return (w >> (8 * i)) & 0xFF - - -def lo16(v): - return (KEEP & 0xFFFF0000) | v - - -def hi16(v): - return (v << 16) | (KEEP & 0xFFFF) - - -def sext8(v): - return v | 0xFF00 if v & 0x80 else v - - -UB, SH = byte(D40, 1), byte(D40, 2) | byte(D40, 3) << 8 -EXPECTED = [lo16(UB), hi16(UB), lo16(sext8(UB)), hi16(sext8(UB)), lo16(SH), hi16(SH), - (D50 & ~0xFF00) | ((0x00CD0000 >> 16) & 0xFF) << 8, # store_byte_d16_hi: bits 23:16 - (D60 & 0xFFFF) | ((0xABCD0000 >> 16) & 0xFFFF) << 16] # store_short_d16_hi: bits 31:16 - - -class BufferSub16Fixture(unittest.TestCase): - def test_reference(self): - self.assertEqual(EXPECTED, [0xBEEF00AA, 0x00AA1234, 0xBEEFFFAA, 0xFFAA1234, 0xBEEF8899, 0x88991234, - 0x1122CD44, 0xABCD7788]) - - def test_translated_shader(self): - spv = support.translate_fixture("cs_w32_buffer_sub16", fssm=FSSM) - mem = {4 * k: 0xEEEEEEEE for k in range(64)} - si.run_workgroup(spv, 32, 32, inputs_for=lambda i: {"%wg_id": (0, 0, 0), "%local_id": (i, 0, 0), - "%sg_lane": i}, - push_constants=[0, 0, 0xFFFFFFFF, 0x31016FAC] + [0] * 28, memory=mem) - for k, want in enumerate(EXPECTED): - with self.subTest(word=k): - self.assertEqual(mem[4 * k], want) - - def test_gpu_runners_expect_the_same_words(self): - for rel in (("runtime", "test", "shaders", "check.py"), ("scripts", "run_gpu_tests.py")): - with open(os.path.join(ROOT, *rel), encoding="utf-8") as f: - m = re.search(r'"cs_w32_buffer_sub16"\)?[,:]\s*\[([^\]]*)\]', f.read()) - with self.subTest(file="/".join(rel)): - self.assertIsNotNone(m) - self.assertEqual([int(v, 0) for v in m.group(1).split(",")], EXPECTED) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_buffer_sub_dword.py b/tests/semantic/test_buffer_sub_dword.py deleted file mode 100644 index 546ca8ddf..000000000 --- a/tests/semantic/test_buffer_sub_dword.py +++ /dev/null @@ -1,150 +0,0 @@ -"""Value tests for RDNA2 8/16-bit MUBUF loads and stores, run through spirv_mini_interp on the CPU. - -buffer_load_{u,s}byte / {u,s}short zero- or sign-extend to 32 bits; the _d16 loads write one 16-bit half of vdata (the -_hi forms the high half; ubyte / sbyte extended to 16 bits) and keep the other; buffer_store_byte / short write the low -8 / 16 bits of vdata (the _d16_hi forms its high half) and leave the neighbouring bytes alone. The V# is raw -(OOB_SELECT 3): an access is in range when offset + its size <= num_records; out of range a load gives 0 and a store -writes nothing. Every byte offset in a dword is tried, so a 16-bit access at byte 3 crosses into the next dword. -Standard library only; no GPU, no game files. -""" -import os -import struct -import sys -import tempfile -import unittest -import warnings - -HERE = os.path.dirname(os.path.abspath(__file__)) -ROOT = os.path.dirname(os.path.dirname(HERE)) -sys.dont_write_bytecode = True -sys.path.insert(0, os.environ.get("LEONIDA_TOOLS_DIR") or os.path.join(ROOT, "tools")) -sys.path.insert(0, HERE) - -import rdna2spirv # noqa: E402 -import spirv_mini_interp as si # noqa: E402 - -M32 = 0xFFFFFFFF -STUB_DXBC = b"DXBC" + bytes(24) + struct.pack(" RECORDS: - v = 0 - else: - v = int.from_bytes(buf[byte:byte + n], "little") - if signed and v >> (8 * n - 1): - v -= 1 << (8 * n) - if half is None: - return v & M32 - return (KEEP & ~(0xFFFF << (16 * half)) | (v & 0xFFFF) << (16 * half)) & M32 - - -def load(op, byte): - body = [f"v_mov_b32_e32 v1, {BASE + byte:#x}", f"v_mov_b32_e32 v5, {KEEP:#x}", f"{op} v5, v1, s[8:11], 0 offen", - "s_waitcnt vmcnt(0)", f"v_mov_b32_e32 v6, {OUT:#x}", "buffer_store_dword v5, v6, s[0:3], 0 offen"] - return run(body)[OUT] - - -class BufferSubDword(unittest.TestCase): - def test_stores_keep_neighbouring_bytes(self): - data = 0xF1E2D3C4 - for op, (n, shift) in STORES.items(): - for byte in range(0, 8): # byte 3 and 7: a short crosses into the next dword - with self.subTest(op=op, byte=byte): - mem = run([f"v_mov_b32_e32 v1, {BASE + byte:#x}", f"v_mov_b32_e32 v2, {data:#x}", - f"{op} v2, v1, s[8:11], 0 offen"]) - want = seed_bytes() - want[byte:byte + n] = ((data >> shift) & ((1 << 8 * n) - 1)).to_bytes(n, "little") - self.assertEqual([mem[BASE + 4 * k] for k in range(3)], words(want)) - - def test_loads(self): - for op in LOADS: - for byte in range(0, 8): - with self.subTest(op=op, byte=byte): - self.assertEqual(load(op, byte), load_ref(op, byte)) - - def test_bounds_cover_the_access_size(self): - # num_records = BASE + 12: the last byte is in range for a byte load, a short at BASE + 11 is not. - for op, byte in (("buffer_load_ubyte", 11), ("buffer_load_ushort", 10), ("buffer_load_ushort", 11), - ("buffer_load_sbyte_d16_hi", 12), ("buffer_load_short_d16", 11)): - with self.subTest(op=op, byte=byte): - self.assertEqual(load(op, byte), load_ref(op, byte)) - # a store out of range writes nothing - mem = run([f"v_mov_b32_e32 v1, {BASE + 11:#x}", "v_mov_b32_e32 v2, 0x7777", - "buffer_store_short v2, v1, s[8:11], 0 offen"]) - self.assertEqual([mem[BASE + 4 * k] for k in range(3)], SEED) - - def test_inactive_lane_does_nothing(self): - body = ["v_cmpx_eq_u32_e32 1, v0", f"v_mov_b32_e32 v1, {BASE + 1:#x}", "v_add_nc_u32_e32 v2, 0x70, v0", - "buffer_store_byte v2, v1, s[8:11], 0 offen"] - mem = run(body, invocations=2) - self.assertEqual(mem[BASE], (SEED[0] & ~0xFF00) | 0x71 << 8) - - def test_rejected_forms(self): - for line in ("buffer_load_ubyte v[4:5], v1, s[8:11], 0 offen", "buffer_store_short v1, v2, s[8:11], 0 offen lds"): - with self.subTest(line=line): - with self.assertRaises(rdna2spirv.Unsupported): - translate(["v_mov_b32_e32 v1, 0", line]) - - def test_first_read_analysis_counts_the_kept_half(self): - from shader_ir import parse_line - self.assertEqual(rdna2spirv.read_before_write_vgprs( - [parse_line("\tbuffer_load_short_d16_hi v5, v1, s[8:11], 0 offen")]), {1, 5}) - self.assertEqual(rdna2spirv.read_before_write_vgprs( - [parse_line("\tbuffer_load_ushort v5, v1, s[8:11], 0 offen")]), {1}) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_buffer_swizzle.py b/tests/semantic/test_buffer_swizzle.py deleted file mode 100644 index 93b4d1835..000000000 --- a/tests/semantic/test_buffer_swizzle.py +++ /dev/null @@ -1,326 +0,0 @@ -"""Swizzled MUBUF addressing (V# SWIZZLE_ENABLE) and ADD_TID_ENABLE, as measured natively on RDNA2 (gfx1036, wave32 -and wave64; docs/design.md, Swizzled buffer addressing; tools/buffer_swizzle_probe.py): - - SWIZZLE_ENABLE word1 bit 31 STRIDE word1 [29:16] - INDEX_STRIDE word3 [22:21] IS = 8 << INDEX_STRIDE indices - ADD_TID_ENABLE word3 bit 23 element_size is fixed at 4 bytes (no ELEMENT_SIZE field since GFX9) - - index = idxen ? vindex : (ADD_TID_ENABLE ? lane : 0) (idxen ignores ADD_TID_ENABLE) - offset = uint32((offen ? vaddr : 0) + inst_offset) (32-bit wrap; soffset is not part of it) - swz_active = SWIZZLE_ENABLE and (idxen or ADD_TID_ENABLE) (no effect when both are 0) - buffer_offset = (index / IS * stride + (offset & ~3)) * IS + (index % IS) * 4 + (offset & 3) - address = base + soffset + buffer_offset - -Two swizzle sub-modes exist on RDNA2: - - Scratch swizzle (SWIZZLE_ENABLE=1, idxen=0, ADD_TID_ENABLE=1): raw multi-dword accesses step by 4 * IS bytes per - dword, and typed formats > 4 bytes (plus 8-byte buffer_atomic_*_x2) are suppressed even in OOB_SELECT 2. - - Indexed swizzle (SWIZZLE_ENABLE=1, idxen=1): raw multi-dword, typed, and _x2 atomic accesses step linearly by +4 - bytes per dword, and typed formats > 4 bytes execute normally. - -OOB_SELECT 3 with active swizzle and stride != 0 checks (index + soffset) >= NUM_RECORDS or offset + payload > stride; -with stride 0 or inactive swizzle it keeps the raw check (uint64(offset) + uint64(soffset) + payload > NUM_RECORDS, no -32-bit wrap on offset + soffset). Every row runs twice: with literal V# words that the translator folds, and with -words 1 and 3 or-ed at run time. -""" -import re -import unittest - -import support -import spirv_mini_interp as si -import test_value_semantics as tv # module only: importing its classes would collect them a second time - -BASE = tv.VEC_REGION -OUT_V = 0x31016FAC # the output V# in s[0:3]: RAW, base 0 -W3 = 0x01000FAC # RESOURCE_LEVEL, DST_SEL xyzw; FORMAT, INDEX_STRIDE, ADD_TID, mode or-ed in -NONE = None -LANE = 5 # the lane of the single invocation in the ADD_TID rows -SWIZZLE_EXTRACT = re.compile(r"OpBitFieldUExtract %uint %t\d+ %c1f %c1\b") # word1 >> 31 & 1 at run time - - -class PatternMemory(dict): - """{byte_address: word}: byte n of the region at BASE holds 0x40 + n (tv._pattern_word), anything written is - kept, and the address of every load is recorded.""" - - def __init__(self): - super().__init__() - self.reads = [] - - def get(self, key, default=None): - self.reads.append(key) - if key in self: - return self[key] - return tv._pattern_word(key - BASE) if BASE <= key < BASE + 0x10000 else default - - -def v_sharp(stride, nr, istride, mode, *, swizzle=True, tid=False, runtime=False, fmt=22): - """Lines that put the V# in s[4:7]; with runtime words 1 and 3 are or-ed at run time (s_or_b32 is not folded).""" - w1 = stride << 16 | swizzle << 31 - w3 = W3 | fmt << 12 | istride << 21 | tid << 23 | mode << 28 - lines = [f"s_mov_b32 s4, {BASE:#x}", f"s_mov_b32 s6, {nr:#x}"] - if runtime: - return lines + ["s_mov_b32 s5, 0", f"s_mov_b32 s9, {w1:#x}", "s_or_b32 s5, s5, s9", - "s_mov_b32 s7, 0", f"s_mov_b32 s10, {w3:#x}", "s_or_b32 s7, s7, s10"] - return lines + [f"s_mov_b32 s5, {w1:#x}", f"s_mov_b32 s7, {w3:#x}"] - - -def operands(idx, off, soffset, inst): - """vaddr operand text, modifiers, the v1/v2 setup and the soffset operand for one row.""" - regs, mods = [], [] - if idx is not NONE: - regs.append(idx) - mods.append("idxen") - if off is not NONE: - regs.append(off) - mods.append("offen") - vaddr = {0: "off", 1: "v1", 2: "v[1:2]"}[len(regs)] - setup = [f"v_mov_b32 v{1 + i}, {r:#x}" for i, r in enumerate(regs)] - if soffset: - setup.append(f"s_mov_b32 s8, {soffset:#x}") - return vaddr, " ".join(mods + ([f"offset:{inst}"] if inst else [])), setup, ("s8" if soffset else "0") - - -# (stride, num_records, INDEX_STRIDE field, mode, idx, off, soffset, inst_offset, byte offset read or NONE) -LOADS = [ - (8, 16, 0, 3, 1, 4, 0, 0, 0x24), # IS 8: (0 * 8 + 4) * 8 + 1 * 4 - (8, 16, 0, 3, 9, 0, 0, 0, 0x44), # (1 * 8 + 0) * 8 + 1 * 4 - (8, 8, 1, 0, 3, 4, 0, 0, 0x4C), # IS 16: (0 * 8 + 4) * 16 + 3 * 4 - (16, 100, 3, 1, 70, 8, 0, 0, 0x618), # IS 64: (1 * 16 + 8) * 64 + 6 * 4 - (8, 16, 0, 3, 1, NONE, 0, 4, 0x24), # inst_offset is part of offset: as row 1 - (8, 16, 0, 0, 1, 4, 0x100, 0, 0x124), # mode 0: soffset added after swizzle, not in index check - (8, 16, 0, 3, 1, 4, 0x100, 0, NONE), # mode 3 swizzled: index + soffset = 0x101 >= 16 -> OOB - (8, 16, 0, 3, 3, 4, 12, 0, 0x38), # mode 3 swizzled: 3 + 12 = 15 < 16 -> IN, 0x20 + 0x0c + 0x0c - (8, 16, 0, 3, 4, 4, 12, 0, NONE), # mode 3 swizzled: 4 + 12 = 16 >= 16 -> OOB - (8, 4, 0, 1, NONE, 0x10, 0, 0, 0x10), # no idxen, ADD_TID=0: swizzle inactive -> linear 0x10 - (8, 0x40, 0, 3, NONE, 0x30, 0, 0, 0x30), # no idxen, ADD_TID=0, mode 3: stays RAW linear despite stride 8 - (8, 4, 0, 2, 5, 0, 0, 0, 0x14), # mode 2: 0 * 8 * 8 + 5 * 4 - (8, 16, 0, 3, 16, 0, 0, 0, NONE), # mode 3, swizzled, stride 8: index 16 >= 16 - (8, 16, 0, 3, 1, 8, 0, 0, NONE), # ... and 8 + 4 > stride 8 - (8, 16, 0, 0, 16, 0, 0, 0, NONE), # mode 0 the same: 16 >= 16 - (0, 0x40, 0, 3, NONE, 0x30, 0, 0, 0x30), # no idxen, ADD_TID=0: linear RAW (0x34 <= 0x40) - (0, 0x40, 0, 3, 2, 0x30, 0, 0, 0x188), # idxen, stride 0: swizzled (0x30 * 8 + 8) with RAW check - (0, 0x40, 0, 3, NONE, 0x40, 0, 0, NONE), # 0x44 > 0x40 - (8, 4, 0, 1, 3, 0x20, 0, 0, 0x10C), # mode 1 checks only the index: (0 * 8 + 0x20) * 8 + 3 * 4 - (8, 16, 0, 3, 1, 0xFFFFFFFC, 0, 8, 0x24), # uint32(voff + inst_offset) wraps to 4 -> IN at 0x24 - (0, 0xFFFFFFFF, 0, 3, NONE, 0x20, 0xFFFFFFF0, 0, NONE), # RAW mode 3: uint64(off) + uint64(soff) does not wrap - (0, 0xFFFFFFFF, 0, 3, 1, 0x20, 0xFFFFFFF0, 0, NONE), # swizzled stride 0 RAW mode 3: no 32-bit wrap on soff -] - -# ADD_TID_ENABLE on lane 5: (stride, nr, INDEX_STRIDE, mode, swizzle, idx, off, soffset, byte offset read or NONE) -TID_LOADS = [ - (4, 8, 0, 1, False, NONE, NONE, 0, 0x14), # linear, idxen=0: index = lane 5 -> 5 * 4 - (4, 8, 0, 1, False, 2, NONE, 0, 0x08), # linear, idxen=1 ignores ADD_TID -> index 2 -> 2 * 4 - (4, 5, 0, 1, False, 2, NONE, 0, 0x08), # idxen=1 ignores ADD_TID in bounds too: index 2 < 5 - (8, 8, 0, 3, False, NONE, 4, 0, 0x2C), # linear RAW: 5 * 8 + 4; RAW check 4 + 4 <= 8 - (8, 16, 0, 3, True, 4, NONE, 0, 0x10), # swizzled, idxen=1 ignores ADD_TID: index 4 -> 4 * 4 - (8, 16, 1, 0, True, NONE, 4, 0, 0x54), # scratch-swizzled IS 16: index 5, (0 * 8 + 4) * 16 + 5 * 4 - (8, 5, 0, 0, True, NONE, NONE, 0, NONE), # index 5 >= 5 - (8, 10, 0, 3, True, NONE, 0, 4, 0x18), # scratch-swizzled mode 3: 5 + 4 = 9 < 10 -> 5 * 4 + 4 - (8, 9, 0, 3, True, NONE, 0, 4, NONE), # scratch-swizzled mode 3: 5 + 4 = 9 >= 9 -> OOB -] - - -class BufferSwizzle(unittest.TestCase): - def translate(self, lines, prologue=("v_cmpx_eq_u32_e32 0, v0",)): - return support.translate_lines("cs_buf_swizzle_t", [*prologue, *lines, "s_endpgm"], fssm=tv.CS_BOUNDS_FSSM) - - def run_spv(self, spv, lane=0): - memory = PatternMemory() - support.run_fragment(spv, inputs={"%wg_id": (0, 0, 0), "%local_id": (lane, 0, 0)}, - push_constants=[0, 0, 0x100, OUT_V] + [0] * 28, memory=memory) - return memory - - def check_selection(self, spv, runtime, what): - # the output store through s[0:3] reads SWIZZLE_ENABLE at run time; the probed V# only when it is not a literal - self.assertEqual(len(SWIZZLE_EXTRACT.findall(spv)), 1 + runtime, what) - - def test_dword_loads(self): - for runtime in (False, True): - for row in LOADS: - stride, nr, ist, mode, idx, off, soffset, inst, want = row - with self.subTest(row=row, runtime=runtime): - vaddr, mods, setup, soff = operands(idx, off, soffset, inst) - spv = self.translate([*v_sharp(stride, nr, ist, mode, runtime=runtime), *setup, - f"buffer_load_dword v3, {vaddr}, s[4:7], {soff} {mods}", - "s_waitcnt vmcnt(0)", "buffer_store_dword v3, off, s[0:3], 0"]) - self.check_selection(spv, runtime, row) - memory = self.run_spv(spv) - self.assertEqual([a - BASE for a in memory.reads], [] if want is NONE else [want]) - self.assertEqual(memory[0], 0 if want is NONE else tv._pattern_word(want)) - - def test_dword_stores(self): - for runtime in (False, True): - for row in LOADS: - stride, nr, ist, mode, idx, off, soffset, inst, want = row - with self.subTest(row=row, runtime=runtime): - vaddr, mods, setup, soff = operands(idx, off, soffset, inst) - spv = self.translate([*v_sharp(stride, nr, ist, mode, runtime=runtime), *setup, - "v_mov_b32 v3, 0x11111111", - f"buffer_store_dword v3, {vaddr}, s[4:7], {soff} {mods}"]) - memory = self.run_spv(spv) - self.assertEqual(dict(memory), {} if want is NONE else {BASE + want: 0x11111111}) - - def test_scratch_swizzle_multi_dword_steps_by_four_index_strides(self): - # Scratch swizzle (SWIZZLE_ENABLE=1, idxen=0, ADD_TID_ENABLE=1): dword k is 4 * IS bytes after dword k - 1, - # each dword bounds-checked on its own in modes 0 and 3. - cases = [ - # (stride, nr, IS field, mode, n, lane, off, byte offsets of dwords in range, dwords out of range) - (16, 4, 0, 0, 4, 2, 0, [0x08, 0x28, 0x48, 0x68], 0), # IS 8: 4k * 8 + 2 * 4 - (8, 4, 0, 0, 4, 2, 0, [0x08, 0x28], 2), # dwords 2 and 3 end past stride (12, 16 > 8) - (8, 16, 1, 3, 2, 5, 0, [0x14, 0x54], 0), # IS 16: 4k * 16 + 5 * 4 - (8, 16, 1, 3, 2, 5, 4, [0x54], 1), # offset 4: dword 1 ends at 12 > 8 - (16, 32, 1, 1, 3, 17, 4, [0x144, 0x184, 0x1C4], 0), # IS 16: (1 * 16 + 4 + 4k) * 16 + 1 * 4 - ] - for runtime in (False, True): - for case in cases: - stride, nr, ist, mode, n, lane, off, inside, outside = case - with self.subTest(case=case, runtime=runtime): - regs = f"v[3:{2 + n}]" - lines = [*v_sharp(stride, nr, ist, mode, tid=True, runtime=runtime), f"v_mov_b32 v1, {off}"] - spv = self.translate(lines + [f"buffer_load_dwordx{n} {regs}, v1, s[4:7], 0 offen", - "s_waitcnt vmcnt(0)", f"buffer_store_dwordx{n} {regs}, off, s[0:3], 0"], - prologue=()) - memory = self.run_spv(spv, lane=lane) - self.assertEqual([a - BASE for a in memory.reads], inside) - want = [tv._pattern_word(o) for o in inside] + [0] * outside - self.assertEqual([memory.get(4 * k) for k in range(n)], want) - spv = self.translate(lines + [*[f"v_mov_b32 v{3 + k}, {0x11111111 * (k + 1):#x}" for k in range(n)], - f"buffer_store_dwordx{n} {regs}, v1, s[4:7], 0 offen"], - prologue=()) - memory = self.run_spv(spv, lane=lane) - want = {BASE + o: 0x11111111 * (k + 1) for k, o in enumerate(inside)} - self.assertEqual(dict(memory), want) - - def test_indexed_swizzle_multi_dword_steps_linearly(self): - # Indexed swizzle (SWIZZLE_ENABLE=1, idxen=1, regardless of ADD_TID_ENABLE): base dword is swizzled, and - # subsequent dwords step linearly by +4 bytes (even across IS boundaries), with per-dword bounds in modes 0/3. - cases = [ - # (stride, nr, IS field, mode, tid, n, idx, off, byte offsets of dwords in range, dwords out of range) - (16, 4, 0, 0, False, 4, 2, 0, [0x08, 0x0C, 0x10, 0x14], 0), # IS 8: base 0x08, linear +4 - (8, 4, 0, 0, False, 4, 2, 0, [0x08, 0x0C], 2), # dwords 2 and 3 end past stride (12, 16 > 8) - (8, 16, 0, 3, True, 2, 7, 0, [0x1C, 0x20], 0), # idx=7 crosses IS=8 boundary linearly; tid ignored - (8, 16, 1, 3, False, 2, 5, 4, [0x54], 1), # offset 4: dword 1 ends at 12 > 8 - (16, 32, 1, 1, False, 3, 17, 4, [0x144, 0x148, 0x14C], 0), # IS 16: (1 * 16 + 4) * 16 + 1 * 4 + 4k - ] - for runtime in (False, True): - for case in cases: - stride, nr, ist, mode, tid, n, idx, off, inside, outside = case - with self.subTest(case=case, runtime=runtime): - regs = f"v[3:{2 + n}]" - lines = [*v_sharp(stride, nr, ist, mode, tid=tid, runtime=runtime), f"v_mov_b32 v1, {idx}", - f"v_mov_b32 v2, {off}"] - spv = self.translate(lines + [f"buffer_load_dwordx{n} {regs}, v[1:2], s[4:7], 0 idxen offen", - "s_waitcnt vmcnt(0)", f"buffer_store_dwordx{n} {regs}, off, s[0:3], 0"], - prologue=()) - memory = self.run_spv(spv, lane=LANE) - self.assertEqual([a - BASE for a in memory.reads], inside) - want = [tv._pattern_word(o) for o in inside] + [0] * outside - self.assertEqual([memory.get(4 * k) for k in range(n)], want) - spv = self.translate(lines + [*[f"v_mov_b32 v{3 + k}, {0x11111111 * (k + 1):#x}" for k in range(n)], - f"buffer_store_dwordx{n} {regs}, v[1:2], s[4:7], 0 idxen offen"], - prologue=()) - memory = self.run_spv(spv, lane=LANE) - want = {BASE + o: 0x11111111 * (k + 1) for k, o in enumerate(inside)} - self.assertEqual(dict(memory), want) - - def test_add_tid_enable(self): - for runtime in (False, True): - for row in TID_LOADS: - stride, nr, ist, mode, swizzle, idx, off, soffset, want = row - with self.subTest(row=row, runtime=runtime): - vaddr, mods, setup, soff = operands(idx, off, soffset, 0) - spv = self.translate([*v_sharp(stride, nr, ist, mode, swizzle=swizzle, tid=True, runtime=runtime), - *setup, f"buffer_load_dword v3, {vaddr}, s[4:7], {soff} {mods}", - "s_waitcnt vmcnt(0)", f"v_mov_b32 v4, {4 * LANE}", - "buffer_store_dword v3, v4, s[0:3], 0 offen"], prologue=()) - memory = self.run_spv(spv, lane=LANE) - self.assertEqual([a - BASE for a in memory.reads], [] if want is NONE else [want]) - self.assertEqual(memory[4 * LANE], 0 if want is NONE else tv._pattern_word(want)) - - def test_indexed_swizzle_typed_element_steps_linearly(self): - # Indexed swizzle (idxen=1): 32_32_32_32_UINT (75), 16 bytes, steps linearly from its swizzled base 0x04. - inside = [0x04, 0x08, 0x0C, 0x10] - for runtime in (False, True): - with self.subTest(runtime=runtime): - lines = [*v_sharp(16, 4, 0, 1, runtime=runtime, fmt=75), "v_mov_b32 v1, 1"] - spv = self.translate(lines + ["buffer_load_format_xyzw v[3:6], v1, s[4:7], 0 idxen", - "s_waitcnt vmcnt(0)", "buffer_store_dwordx4 v[3:6], off, s[0:3], 0"]) - memory = self.run_spv(spv) - self.assertEqual(sorted(set(a - BASE for a in memory.reads)), inside) - self.assertEqual([memory.get(4 * k) for k in range(4)], [tv._pattern_word(o) for o in inside]) - spv = self.translate(lines + [*[f"v_mov_b32 v{3 + k}, {0x11111111 * (k + 1):#x}" for k in range(4)], - "buffer_store_format_xyzw v[3:6], v1, s[4:7], 0 idxen"]) - memory = self.run_spv(spv) - self.assertEqual(dict(memory), {BASE + o: 0x11111111 * (k + 1) for k, o in enumerate(inside)}) - - def test_scratch_swizzle_suppresses_typed_over_4_bytes_and_atomic_x2(self): - # Scratch swizzle (SWIZZLE_ENABLE=1, idxen=0, ADD_TID_ENABLE=1): typed formats > 4 bytes (MUBUF/MTBUF) and - # 8-byte buffer_atomic_*_x2 are suppressed even in OOB_SELECT 2 (DISABLED), while 4-byte typed formats work. - for runtime in (False, True): - with self.subTest(runtime=runtime): - lines16 = v_sharp(16, 16, 0, 2, tid=True, runtime=runtime, fmt=75) - spv = self.translate(lines16 + ["buffer_load_format_xyzw v[3:6], off, s[4:7], 0", - "s_waitcnt vmcnt(0)", "buffer_store_dwordx4 v[3:6], off, s[0:3], 0"], - prologue=()) - memory = self.run_spv(spv, lane=LANE) - self.assertEqual(memory.reads, []) - self.assertEqual([memory.get(4 * k) for k in range(4)], [0, 0, 0, 0]) - - spv = self.translate(lines16 + [*[f"v_mov_b32 v{3 + k}, {0x11111111 * (k + 1):#x}" for k in range(4)], - "buffer_store_format_xyzw v[3:6], off, s[4:7], 0"], prologue=()) - memory = self.run_spv(spv, lane=LANE) - self.assertEqual(dict(memory), {}) - - lines_mt = v_sharp(16, 16, 0, 2, tid=True, runtime=runtime, fmt=20) - spv = self.translate(lines_mt + [ - "tbuffer_load_format_xy v[3:4], off, s[4:7], 0 format:[BUF_FMT_32_32_UINT]", - "s_waitcnt vmcnt(0)", "buffer_store_dwordx2 v[3:4], off, s[0:3], 0"], prologue=()) - memory = self.run_spv(spv, lane=LANE) - self.assertEqual(memory.reads, []) - self.assertEqual([memory.get(0), memory.get(4)], [0, 0]) - - spv = self.translate(lines_mt + [ - "v_mov_b32 v3, 0xaaaaaaaa", "v_mov_b32 v4, 0xbbbbbbbb", - "buffer_atomic_swap_x2 v[3:4], off, s[4:7], 0 glc", - "s_waitcnt vmcnt(0)", "buffer_store_dwordx2 v[3:4], off, s[0:3], 0"], prologue=()) - memory = self.run_spv(spv, lane=LANE) - self.assertEqual(memory.reads, []) - self.assertEqual([memory.get(0), memory.get(4)], [0, 0]) - self.assertNotIn(BASE + 4 * LANE, memory) - - # Control: 4-byte typed format (32_UINT, code 20) succeeds at lane * 4 = 0x14 - spv = self.translate(lines_mt + ["buffer_load_format_x v3, off, s[4:7], 0", - "s_waitcnt vmcnt(0)", "buffer_store_dword v3, off, s[0:3], 0"], - prologue=()) - memory = self.run_spv(spv, lane=LANE) - self.assertEqual(sorted(set(a - BASE for a in memory.reads)), [0x14]) - self.assertEqual(memory[0], tv._pattern_word(0x14)) - - def test_linear_literal_v_sharp_is_unchanged(self): - # a literal V# without SWIZZLE_ENABLE or ADD_TID_ENABLE folds both away: no lane, no swizzle arithmetic - lines = [*v_sharp(8, 16, 0, 3, swizzle=False), "v_mov_b32 v1, 1", - "buffer_load_dwordx2 v[3:4], v1, s[4:7], 0 idxen", "s_waitcnt vmcnt(0)", - "buffer_store_dwordx2 v[3:4], off, s[0:3], 0"] - spv = self.translate(lines) - self.check_selection(spv, False, "linear") - memory = self.run_spv(spv) - self.assertEqual([a - BASE for a in memory.reads], [8, 12]) - - -class SwizzleFixture(unittest.TestCase): - """runtime/test/shaders/cs_buf_swizzle.asm in the interpreter: 64 threads (lanes 0 and 1 store through the - ADD_TID V#), a 256-byte heap filled with 0xee as vk_compute_test's, the words derived in the .asm header.""" - - WANT = [0x5EED0024, 0x5EED0044, 0x5EED004C, 0x5EED0008, 0x5EED000C, 0, 0xBEEF0000, 0xBEEF0001] - - def test_words(self): - spv = support.translate_fixture("cs_buf_swizzle", fssm=tv.CS_BOUNDS_FSSM) - memory = {a: 0xEEEEEEEE for a in range(0, 0x100, 4)} - si.run_workgroup(spv, 64, 32, inputs_for=lambda i: {"%wg_id": (0, 0, 0), "%local_id": (i, 0, 0), - "%sg_lane": i % 32}, - push_constants=[0, 0, 0xFFFFFFFF, 0x31016FAC] + [0] * 28, memory=memory) - self.assertEqual([f"{memory[4 * i]:#010x}" for i in range(8)], [f"{w:#010x}" for w in self.WANT]) - self.assertEqual(set(memory), set(range(0, 0x100, 4)), "nothing written outside the heap") - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_buffer_tbuffer_format_d16.py b/tests/semantic/test_buffer_tbuffer_format_d16.py deleted file mode 100644 index 549d76edc..000000000 --- a/tests/semantic/test_buffer_tbuffer_format_d16.py +++ /dev/null @@ -1,243 +0,0 @@ -"""buffer_load_format_d16_* and tbuffer_load_format_d16_* (GFX10 16-bit packed format loads) in compute shaders. - -Covers all 8 instructions (buffer_load_format_d16_{x,xy,xyz,xyzw} and tbuffer_load_format_d16_{x,xy,xyz,xyzw}) -through rdna2spirv.translate and spirv_mini_interp.run_fragment: -- GFX10 16-bit packing (_x preserves high 16 bits, _xy packs x | (y << 16), _xyz/_xyzw pack into v[a:a+1] with - _xyz preserving v[a+1][31:16]), -- float/UNORM formats (32_32_32_32_FLOAT, 16_16_16_16_FLOAT, 8_8_8_8_UNORM) and integer formats - (16_16_16_16_UINT, 16_16_16_16_SINT including negative 16-bit values), -- tbuffer format:[...] modifier precedence over the V#'s FORMAT field, -- out-of-bounds (num_records) behavior, and -- negative controls on the generated SPIR-V text (shift-16 packing, 0xFFFF/0xFFFF0000 masks). -""" -import os -import struct -import sys -import unittest - -sys.dont_write_bytecode = True - -HERE = os.path.dirname(os.path.abspath(__file__)) -ROOT = os.path.dirname(os.path.dirname(HERE)) -sys.path.insert(0, HERE) -sys.path.insert(0, os.environ.get("LEONIDA_TOOLS_DIR") or os.path.join(ROOT, "tools")) - -import rdna2spirv # noqa: E402 -import support # noqa: E402 - - -def fssm(rsrc2, group): - """Build a minimal FSSM compute header with COMPUTE_PGM_RSRC2 and thread-group size.""" - header = bytearray(0x148) - struct.pack_into("<4I", header, 0x138, rsrc2, *group) - return bytes(header) - - -# 8 user SGPRs (s[0:3] = input V#, s[4:7] = output V#), workgroup id in s8, 64x1x1 threads. -CS_FSSM = fssm(0x8090, (64, 1, 1)) - -# Format codes from rdna2spirv.FORMATS / GFX10_FORMATS. -FMT_32_32_32_32_FLOAT = 77 -FMT_16_16_16_16_FLOAT = 71 -FMT_8_8_8_8_UNORM = 56 -FMT_16_16_16_16_UINT = 69 -FMT_16_16_16_16_SINT = 70 -FMT_32_FLOAT = 22 - - -def make_vsharp(base, num_records, fmt_code, dst_sel=0xFAC, oob_select=3): - """Build a 4-dword GFX10 buffer descriptor (V#) with RAW OOB_SELECT=3 and identity swizzle.""" - w0 = base & 0xFFFFFFFF - w1 = (base >> 32) & 0xFFFF - w2 = num_records & 0xFFFFFFFF - w3 = (oob_select << 28) | (1 << 24) | ((fmt_code & 0x7F) << 12) | (dst_sel & 0xFFF) - return [w0, w1, w2, w3] - - -# Output V# in s[4:7]: base 0, num_records 0xFFFFFFFF, 32_FLOAT, OOB_SELECT 3. -OUT_VSHARP = make_vsharp(0, 0xFFFFFFFF, FMT_32_FLOAT) - - -def f32_bits(val): - """IEEE-754 binary32 bit pattern for a Python float.""" - return struct.unpack(" 0.0 (0x0000), 0xFF -> 1.0 (0x3C00), 0x80 -> 128/255 (~0.50196 -> 0x3804), - # 0x40 -> 64/255 (~0.25098 -> 0x3404). - mem = {0x100: 0x4080FF00} - vsharp = make_vsharp(0, 0x200, FMT_8_8_8_8_UNORM) - - _, out_b = run_d16_load("buffer_load_format_d16_xyzw", None, vsharp, mem) - self.assertEqual(out_b, [pack_u16(0x0000, 0x3C00), pack_u16(0x3804, 0x3404)]) - - _, out_t = run_d16_load("tbuffer_load_format_d16_xyzw", "BUF_FMT_8_8_8_8_UNORM", vsharp, mem) - self.assertEqual(out_t, out_b) - - def test_uint16_and_sint16_formats(self): - # UINT: 16-bit unsigned values remain intact (including 0x8000 and 0xFFFF). - mem_u = { - 0x100: pack_u16(0x0001, 0x1234), - 0x104: pack_u16(0x8000, 0xFFFF), - } - vsharp_u = make_vsharp(0, 0x200, FMT_16_16_16_16_UINT) - _, out_bu = run_d16_load("buffer_load_format_d16_xyzw", None, vsharp_u, mem_u) - self.assertEqual(out_bu, [pack_u16(0x0001, 0x1234), pack_u16(0x8000, 0xFFFF)]) - - _, out_tu = run_d16_load("tbuffer_load_format_d16_xyzw", "BUF_FMT_16_16_16_16_UINT", vsharp_u, mem_u) - self.assertEqual(out_tu, out_bu) - - # SINT: negative 16-bit values (-1 -> 0xFFFF, -32768 -> 0x8000, -123 -> 0xFF85, 32767 -> 0x7FFF) - # remain intact at 16 bits. - mem_s = { - 0x100: pack_u16(0xFFFF, 0x8000), - 0x104: pack_u16(0xFF85, 0x7FFF), - } - vsharp_s = make_vsharp(0, 0x200, FMT_16_16_16_16_SINT) - _, out_bs = run_d16_load("buffer_load_format_d16_xyzw", None, vsharp_s, mem_s) - self.assertEqual(out_bs, [pack_u16(0xFFFF, 0x8000), pack_u16(0xFF85, 0x7FFF)]) - - _, out_ts = run_d16_load("tbuffer_load_format_d16_xyzw", "BUF_FMT_16_16_16_16_SINT", vsharp_s, mem_s) - self.assertEqual(out_ts, out_bs) - - def test_tbuffer_format_modifier_overrides_vsharp_format(self): - # V# declares 32_32_32_32_FLOAT (16-byte element), but tbuffer specifies BUF_FMT_16_16_16_16_UINT (8-byte). - # If V#'s format were used, 0xFFFF/0x8000 would be interpreted as f32 denorm/NaN and flushed/converted; - # with format:[BUF_FMT_16_16_16_16_UINT] taking precedence, the raw 16-bit integers are preserved. - mem = { - 0x100: pack_u16(0x0007, 0x8000), - 0x104: pack_u16(0xFFFE, 0xFFFF), - } - vsharp_wrong_fmt = make_vsharp(0, 0x200, FMT_32_32_32_32_FLOAT) - _, out_t = run_d16_load("tbuffer_load_format_d16_xyzw", "BUF_FMT_16_16_16_16_UINT", vsharp_wrong_fmt, mem) - self.assertEqual(out_t, [pack_u16(0x0007, 0x8000), pack_u16(0xFFFE, 0xFFFF)]) - - def test_out_of_bounds_returns_zero_and_preserves_high_half(self): - # Element size of 16_16_16_16_UINT is 8 bytes. At addr=0x100, end is 0x108; num_records=0x104 is OOB. - mem = { - 0x100: pack_u16(0x1111, 0x2222), - 0x104: pack_u16(0x3333, 0x4444), - } - vsharp_oob = make_vsharp(0, 0x104, FMT_16_16_16_16_UINT) - - _, out_x = run_d16_load("buffer_load_format_d16_x", None, vsharp_oob, mem) - self.assertEqual(out_x, [pack_u16(0x0000, 0xABCD)]) - - _, out_xyzw = run_d16_load("buffer_load_format_d16_xyzw", None, vsharp_oob, mem) - self.assertEqual(out_xyzw, [0, 0]) - - _, out_tx = run_d16_load("tbuffer_load_format_d16_x", "BUF_FMT_16_16_16_16_UINT", vsharp_oob, mem) - self.assertEqual(out_tx, [pack_u16(0x0000, 0xABCD)]) - - _, out_txyzw = run_d16_load("tbuffer_load_format_d16_xyzw", "BUF_FMT_16_16_16_16_UINT", vsharp_oob, mem) - self.assertEqual(out_txyzw, [0, 0]) - - def test_spirv_negative_controls(self): - vsharp = make_vsharp(0, 0x200, FMT_16_16_16_16_UINT) - mem = {0x100: 0x00020001, 0x104: 0x00040003} - - spv_x, _ = run_d16_load("buffer_load_format_d16_x", None, vsharp, mem) - # write_lo16 must mask the previous high half with 0xFFFF0000 (4294901760) and OR in the new low half. - self.assertIn("OpConstant %uint 4294901760", spv_x) - self.assertIn("OpBitwiseAnd", spv_x) - self.assertIn("OpBitwiseOr", spv_x) - - spv_xy, _ = run_d16_load("buffer_load_format_d16_xy", None, vsharp, mem) - # Packing two 16-bit components shifts the second component left by 16 and masks/saturates to 0xFFFF (65535). - self.assertIn("OpConstant %uint 16", spv_xy) - self.assertIn("OpShiftLeftLogical", spv_xy) - self.assertIn("OpConstant %uint 65535", spv_xy) - self.assertIn("SClamp", spv_xy) - self.assertIn("UMin", spv_xy) - - spv_t, _ = run_d16_load("tbuffer_load_format_d16_xy", "BUF_FMT_16_16_16_16_SINT", vsharp, mem) - self.assertIn("OpConstant %uint 16", spv_t) - self.assertIn("OpShiftLeftLogical", spv_t) - self.assertIn("SClamp", spv_t) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_carry_chain.py b/tests/semantic/test_carry_chain.py deleted file mode 100644 index 37509b357..000000000 --- a/tests/semantic/test_carry_chain.py +++ /dev/null @@ -1,143 +0,0 @@ -"""Semantic interpreter tests for RDNA2 carry and borrow: v_add_co_u32, v_sub_co_u32, v_subrev_co_u32 and their -_co_ci forms (e32 through VCC, e64 through SGPRs), s_add_u32/s_addc_u32 and s_sub_u32/s_subb_u32 (through SCC), and -the 64-bit add and subtract a compiler builds from them. - -Each case translates a synthetic pixel shader with tools/rdna2spirv.py, runs it in tests/semantic/spirv_mini_interp.py -and compares the result and the carry-out (read back with v_cndmask_b32 or s_cselect_b32) with plain Python. The -carry-out of a subtract is its borrow: 1 when the subtrahend (plus the carry-in) is larger than the minuend. -""" -import itertools -import os -import struct -import sys -import tempfile -import unittest -import warnings - -HERE = os.path.dirname(os.path.abspath(__file__)) -ROOT = os.path.dirname(os.path.dirname(HERE)) -TOOLS_DIR = os.environ.get("LEONIDA_TOOLS_DIR") or os.path.join(ROOT, "tools") - -sys.dont_write_bytecode = True -sys.path.insert(0, TOOLS_DIR) -sys.path.insert(0, HERE) - -import rdna2spirv # noqa: E402 -import spirv_mini_interp as si # noqa: E402 - -MASK32 = 0xFFFFFFFF -MASK64 = (1 << 64) - 1 -STUB_DXBC = b"DXBC" + bytes(24) + struct.pack("> 32 - - -def sub(x, y, ci): - return (x - y - ci) & MASK32, int(y + ci > x) - - -# op: (reference(src0, src1, carry_in), takes a carry-in) -VECTOR = { - "v_add_co_u32": (add, False), "v_sub_co_u32": (sub, False), - "v_subrev_co_u32": (lambda x, y, ci: sub(y, x, ci), False), - "v_add_co_ci_u32": (add, True), "v_sub_co_ci_u32": (sub, True), - "v_subrev_co_ci_u32": (lambda x, y, ci: sub(y, x, ci), True), -} -SCALAR = {"s_add_u32": (add, False), "s_sub_u32": (sub, False), "s_addc_u32": (add, True), "s_subb_u32": (sub, True)} - -# Pairs at the carry and borrow boundaries (x + y around 2^32, x - y around 0). -PAIRS = [(0, 0), (1, 0), (0, 1), (0xFFFFFFFF, 1), (1, 0xFFFFFFFF), (0xFFFFFFFF, 0), (0xFFFFFFFF, 0xFFFFFFFF), - (0x80000000, 0x80000000), (0x7FFFFFFF, 0x80000000), (0x12345678, 0x12345678), (0x12345679, 0x12345678)] - -_TMP_DIR = None -_SRC_PATH = None - - -def setUpModule(): - global _TMP_DIR, _SRC_PATH - _TMP_DIR = tempfile.TemporaryDirectory() - disasm_dir = os.path.join(_TMP_DIR.name, "disasm") - os.mkdir(disasm_dir) - _SRC_PATH = os.path.join(disasm_dir, "ps_carry.s") - with open(os.path.join(_TMP_DIR.name, "ps_carry.dxbc"), "wb") as f: - f.write(STUB_DXBC) - - -def tearDownModule(): - global _TMP_DIR - if _TMP_DIR is not None: - _TMP_DIR.cleanup() - _TMP_DIR = None - - -def run_lines(lines) -> tuple: - """Run the lines, export v0 and v1, return those two words.""" - if _TMP_DIR is None: - setUpModule() - asm = "; test_carry_chain\n" + "".join(f"\t{ln}\n" for ln in lines) + "\texp mrt0 v0, v1, v0, v0 done vm\n\ts_endpgm\n" - with open(_SRC_PATH, "w", encoding="utf-8") as f: - f.write(asm) - with warnings.catch_warnings(): - warnings.simplefilter("ignore", ResourceWarning) - spv = rdna2spirv.translate(_SRC_PATH) - return tuple(si.run_fragment(spv)["%out_mrt0"][:2]) - - -def vector_op(op, x, y, ci, form): - with_ci = VECTOR[op][1] - lines = [f"v_mov_b32 v2, {x:#x}", f"v_mov_b32 v3, {y:#x}", f"v_mov_b32 v4, {ci}"] - if form == "e32": - lines += ["v_cmp_ne_u32_e32 vcc_lo, 0, v4", f"{op}_e32 v0, vcc_lo, v2, v3" + (", vcc_lo" if with_ci else ""), - "v_cndmask_b32_e32 v1, 0, 1, vcc_lo"] - else: - lines += ["v_cmp_ne_u32_e64 s8, 0, v4", f"{op}_e64 v0, s10, v2, v3" + (", s8" if with_ci else ""), - "v_cndmask_b32_e64 v1, 0, 1, s10"] - return run_lines(lines) - - -def scalar_op(op, x, y, ci): - return run_lines([f"s_mov_b32 s2, {x:#x}", f"s_mov_b32 s3, {y:#x}", f"s_cmp_eq_u32 {ci}, 1", # SCC = carry-in - f"{op} s0, s2, s3", "s_cselect_b32 s1, 1, 0", "v_mov_b32 v0, s0", "v_mov_b32 v1, s1"]) - - -class VectorCarry(unittest.TestCase): - def test_result_and_carry_out(self): - for (op, (ref, with_ci)), form in itertools.product(VECTOR.items(), ("e32", "e64")): - for (x, y), ci in itertools.product(PAIRS, (0, 1) if with_ci else (0,)): - with self.subTest(op=op, form=form, x=hex(x), y=hex(y), ci=ci): - self.assertEqual(vector_op(op, x, y, ci, form), ref(x, y, ci)) - - def test_64_bit_add_and_subtract(self): - for x, y in ((0xFFFFFFFF, 1), (0x00000001FFFFFFFF, 0x00000000FFFFFFFF), (MASK64, 1), (0, 1), - (0x123456789ABCDEF0, 0x0FEDCBA987654321)): - for op_lo, op_hi, want in (("v_add_co_u32", "v_add_co_ci_u32", (x + y) & MASK64), - ("v_sub_co_u32", "v_sub_co_ci_u32", (x - y) & MASK64)): - with self.subTest(op=op_lo, x=hex(x), y=hex(y)): - got = run_lines([f"v_mov_b32 v2, {x & MASK32:#x}", f"v_mov_b32 v3, {x >> 32:#x}", - f"v_mov_b32 v4, {y & MASK32:#x}", f"v_mov_b32 v5, {y >> 32:#x}", - f"{op_lo}_e64 v0, s10, v2, v4", f"{op_hi}_e64 v1, s12, v3, v5, s10"]) - self.assertEqual(got[0] | got[1] << 32, want) - - -class ScalarCarry(unittest.TestCase): - def test_result_and_scc(self): - for op, (ref, with_ci) in SCALAR.items(): - for (x, y), ci in itertools.product(PAIRS, (0, 1) if with_ci else (0,)): - with self.subTest(op=op, x=hex(x), y=hex(y), ci=ci): - self.assertEqual(scalar_op(op, x, y, ci), ref(x, y, ci)) - - def test_64_bit_add_and_subtract(self): - for x, y in ((0xFFFFFFFF, 1), (MASK64, 1), (0, 1), (0x123456789ABCDEF0, 0x0FEDCBA987654321)): - for op_lo, op_hi, want in (("s_add_u32", "s_addc_u32", (x + y) & MASK64), - ("s_sub_u32", "s_subb_u32", (x - y) & MASK64)): - with self.subTest(op=op_lo, x=hex(x), y=hex(y)): - got = run_lines([f"s_mov_b32 s2, {x & MASK32:#x}", f"s_mov_b32 s3, {x >> 32:#x}", - f"s_mov_b32 s4, {y & MASK32:#x}", f"s_mov_b32 s5, {y >> 32:#x}", - f"{op_lo} s0, s2, s4", f"{op_hi} s1, s3, s5", "v_mov_b32 v0, s0", "v_mov_b32 v1, s1"]) - self.assertEqual(got[0] | got[1] << 32, want) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_carry_exec_mask.py b/tests/semantic/test_carry_exec_mask.py deleted file mode 100644 index 233eaea98..000000000 --- a/tests/semantic/test_carry_exec_mask.py +++ /dev/null @@ -1,452 +0,0 @@ -"""Semantic interpreter tests for EXEC masking on VALU carry-out / sign-out lane masks. - -On RDNA2 hardware, every VALU instruction that writes a scalar lane-mask destination writes 0 for -lanes that are inactive in EXEC (SDST[lane] = EXEC[lane] ? bit : 0), matching v_cmp_*. Covers: - - v_add_co_u32, v_add_co_ci_u32, v_sub_co_u32, v_sub_co_ci_u32, v_subrev_co_u32, v_subrev_co_ci_u32 - (both e32/VCC and e64/SGPR destinations, plus carry-in-only overflow on inactive lanes) - - v_mad_u64_u32 (carry-out bit 64) and v_mad_i64_i32 (exact-sum sign bit 64) - - wave32, wave64 native, and wave64 --wave64-emulate - - wave-wide consumers: s_bcnt1_i32_b32/b64, s_cbranch_vccz, and v_cndmask_b32 after EXEC restore - - null scalar destination under partial EXEC (VGPR preserved on inactive lanes, VCC untouched) -""" -import gc -import os -import struct -import sys -import tempfile -import unittest -import warnings - -HERE = os.path.dirname(os.path.abspath(__file__)) -ROOT = os.path.dirname(os.path.dirname(HERE)) -TOOLS_DIR = os.environ.get("LEONIDA_TOOLS_DIR") or os.path.join(ROOT, "tools") - -sys.dont_write_bytecode = True -if HERE not in sys.path: - sys.path.insert(0, HERE) -if TOOLS_DIR not in sys.path: - sys.path.insert(0, TOOLS_DIR) - -import rdna2spirv # noqa: E402 -import spirv_mini_interp as si # noqa: E402 - -STUB_DXBC = b"DXBC" + bytes(24) + struct.pack(" 4 user SGPRs (s[0:3] = output V#), TGID_X. - with open(os.path.join(tmp, "fssm", name + ".fssm"), "wb") as f: - f.write(bytes(0x138) + struct.pack("<4I", 0x8088, wave_size, 1, 1)) - with warnings.catch_warnings(): - warnings.simplefilter("ignore", ResourceWarning) - spv = rdna2spirv.translate(s_path) - gc.collect() - gen_wave64 = rdna2spirv.translate.last_gen.wave64 - assert gen_wave64 == (wave_size == 64), f"{name}: expected wave64={wave_size == 64}, got {gen_wave64}" - finally: - rdna2spirv.WAVE64_EMULATE = prev_emu - - sg_size = 32 if emulate else wave_size - pc = VSHARP + [0] * 28 - return si.run_workgroup( - spv, wave_size, sg_size, - inputs_for=lambda i: {"%wg_id": (0, 0, 0), "%local_id": (i, 0, 0), "%sg_lane": i % sg_size}, - push_constants=pc, memory={}, - ) - - -# Each entry: (op, with_ci, (hi_x, hi_y, hi_ci), (lo_x, lo_y, lo_ci), want_hi_res, want_lo_res) -# "hi" inputs produce carry/borrow = 1; "lo" inputs produce carry/borrow = 0. -# For *_ci_* ops, "hi" inputs trigger carry/borrow ONLY via carry_in = 1 (x+y or x-y alone does not overflow). -CO_CASES = [ - ("v_add_co_u32", False, (0xFFFFFFFF, 1, 0), (10, 20, 0), 0, 30), - ("v_add_co_ci_u32", True, (0xFFFFFFFF, 0, 1), (0xFFFFFFFF, 0, 0), 0, 0xFFFFFFFF), - ("v_sub_co_u32", False, (0, 1, 0), (20, 10, 0), 0xFFFFFFFF, 10), - ("v_sub_co_ci_u32", True, (0, 0, 1), (0, 0, 0), 0xFFFFFFFF, 0), - ("v_subrev_co_u32", False, (1, 0, 0), (10, 20, 0), 0xFFFFFFFF, 10), - ("v_subrev_co_ci_u32", True, (0, 0, 1), (0, 0, 0), 0xFFFFFFFF, 0), -] - -# Each entry: (op, (hi_s0, hi_s1, hi_acc_lo, hi_acc_hi), (lo_s0, lo_s1, lo_acc_lo, lo_acc_hi), want_hi_lo, want_hi_hi, want_lo_lo, want_lo_hi) -MAD64_CASES = [ - ( - "v_mad_u64_u32", - (0xFFFFFFFF, 1, 0xFFFFFFFF, 0xFFFFFFFF), # 0xffffffff + (2^64 - 1) -> carry = 1, res = 0xfffffffe - (3, 5, 7, 0), # 15 + 7 = 22 -> carry = 0 - 0xFFFFFFFE, 0, 22, 0, - ), - ( - "v_mad_i64_i32", - (0xFFFFFFFF, 1, 0, 0), # -1 * 1 + 0 = -1 -> sign bit64 = 1 - (3, 5, 7, 0), # 3 * 5 + 7 = +22 -> sign bit64 = 0 - 0xFFFFFFFF, 0xFFFFFFFF, 22, 0, - ), -] - - -class _CarryExecMixin: - wave_size = 64 - emulate = False - - def _regs(self): - if self.wave_size == 64: - return { - "exec": "exec", "vcc": "vcc", "mov": "s_mov_b64", "bcnt": "s_bcnt1_i32_b64", - "m_act": "s[4:5]", "m_tmp": "s[6:7]", "m_lo": "s[8:9]", "m_sdst": "s[10:11]", - "m_cin": "s[12:13]", - "active_hi": [2, 35], "active_lo": [5, 51], - } - return { - "exec": "exec_lo", "vcc": "vcc_lo", "mov": "s_mov_b32", "bcnt": "s_bcnt1_i32_b32", - "m_act": "s4", "m_tmp": "s6", "m_lo": "s8", "m_sdst": "s10", - "m_cin": "s12", - "active_hi": [2, 19], "active_lo": [5, 27], - } - - def test_co_ops_inactive_lanes_zero_mask(self): - r = self._regs() - active_all = r["active_hi"] + r["active_lo"] - hi_set = set(r["active_hi"]) - lo_set = set(r["active_lo"]) - for op, with_ci, hi_in, lo_in, want_hi, want_lo in CO_CASES: - for dst_kind in ("vcc", "sgpr"): - if dst_kind == "vcc": - sdst = r["vcc"] - cin_reg = r["vcc"] - inst = f"{op}_e32 v6, {sdst}, v2, v3" + (f", {cin_reg}" if with_ci else "") - else: - sdst = r["m_sdst"] - cin_reg = r["m_cin"] - inst = f"{op}_e64 v6, {sdst}, v2, v3" + (f", {cin_reg}" if with_ci else "") - with self.subTest(op=op, dst=dst_kind, wave=self.wave_size, emu=self.emulate): - lines = [f"{r['mov']} {r['exec']}, -1"] - # Active mask = active_hi | active_lo; non-carrying mask = active_lo. - lines += _mask_lines(active_all, r["m_act"], r["m_tmp"], self.wave_size) - lines += _mask_lines(r["active_lo"], r["m_lo"], r["m_tmp"], self.wave_size) - # Give inactive lanes + active_hi the carrying inputs; active_lo gets non-carrying inputs. - lines += [ - f"v_mov_b32 v2, {hi_in[0]:#x}", - f"v_mov_b32 v3, {hi_in[1]:#x}", - f"v_mov_b32 v4, {lo_in[0]:#x}", - f"v_mov_b32 v5, {lo_in[1]:#x}", - f"v_cndmask_b32_e64 v2, v2, v4, {r['m_lo']}", - f"v_cndmask_b32_e64 v3, v3, v5, {r['m_lo']}", - f"v_mov_b32 v6, {SENTINEL:#x}", - ] - if with_ci: - # carry_in = 1 on inactive + active_hi, 0 on active_lo. - lines.append(f"v_mov_b32 v7, {hi_in[2]}") - lines.append(f"v_mov_b32 v8, {lo_in[2]}") - lines.append(f"v_cndmask_b32_e64 v7, v7, v8, {r['m_lo']}") - lines.append(f"v_cmp_ne_u32_e64 {cin_reg}, 0, v7") - else: - # Pre-seed sdst with all 1s so stale bits also fail if not overwritten to 0. - lines.append(f"{r['mov']} {sdst}, -1") - # Switch EXEC to active_all and run the carry op. - lines.append(f"{r['mov']} {r['exec']}, {r['m_act']}") - lines.append(inst) - # Restore EXEC and inspect sdst via both wave-wide bcnt1 and per-lane v_cndmask_b32. - lines += [ - f"{r['mov']} {r['exec']}, -1", - f"{r['bcnt']} s14, {sdst}", - f"v_cndmask_b32_e64 v9, 0, 1, {sdst}", - "v_mov_b32 v10, s14", - "v_mul_lo_u32 v11, v0, 12", - "buffer_store_dword v6, v11, s[0:3], 0 offen", - "v_add_nc_u32 v12, 4, v11", - "buffer_store_dword v9, v12, s[0:3], 0 offen", - "v_add_nc_u32 v12, 8, v11", - "buffer_store_dword v10, v12, s[0:3], 0 offen", - ] - mem = _run_cs(f"cs_{op}_{dst_kind}_w{self.wave_size}", lines, - wave_size=self.wave_size, emulate=self.emulate) - for lane in range(self.wave_size): - base = lane * 12 - got_vd = mem[base] - got_bit = mem[base + 4] - got_bcnt = mem[base + 8] - self.assertEqual(got_bcnt, len(hi_set), f"lane {lane} bcnt1") - if lane in hi_set: - self.assertEqual(got_vd, want_hi, f"lane {lane} vd") - self.assertEqual(got_bit, 1, f"lane {lane} carry bit") - elif lane in lo_set: - self.assertEqual(got_vd, want_lo, f"lane {lane} vd") - self.assertEqual(got_bit, 0, f"lane {lane} carry bit") - else: - self.assertEqual(got_vd, SENTINEL, f"inactive lane {lane} vd") - self.assertEqual(got_bit, 0, f"inactive lane {lane} carry bit leaked") - - def test_mad64_inactive_lanes_zero_mask(self): - r = self._regs() - active_all = r["active_hi"] + r["active_lo"] - hi_set = set(r["active_hi"]) - lo_set = set(r["active_lo"]) - for op, hi_in, lo_in, wh_lo, wh_hi, wl_lo, wl_hi in MAD64_CASES: - for dst_kind in ("vcc", "sgpr"): - sdst = r["vcc"] if dst_kind == "vcc" else r["m_sdst"] - with self.subTest(op=op, dst=dst_kind, wave=self.wave_size, emu=self.emulate): - lines = [f"{r['mov']} {r['exec']}, -1"] - lines += _mask_lines(active_all, r["m_act"], r["m_tmp"], self.wave_size) - lines += _mask_lines(r["active_lo"], r["m_lo"], r["m_tmp"], self.wave_size) - lines += [ - f"v_mov_b32 v2, {hi_in[0]:#x}", - f"v_mov_b32 v3, {hi_in[1]:#x}", - f"v_mov_b32 v12, {hi_in[2]:#x}", - f"v_mov_b32 v13, {hi_in[3]:#x}", - f"v_mov_b32 v14, {lo_in[0]:#x}", - f"v_mov_b32 v15, {lo_in[1]:#x}", - f"v_mov_b32 v16, {lo_in[2]:#x}", - f"v_mov_b32 v17, {lo_in[3]:#x}", - f"v_cndmask_b32_e64 v2, v2, v14, {r['m_lo']}", - f"v_cndmask_b32_e64 v3, v3, v15, {r['m_lo']}", - f"v_cndmask_b32_e64 v12, v12, v16, {r['m_lo']}", - f"v_cndmask_b32_e64 v13, v13, v17, {r['m_lo']}", - f"v_mov_b32 v6, {SENTINEL:#x}", - f"v_mov_b32 v7, {SENTINEL:#x}", - f"{r['mov']} {sdst}, -1", - f"{r['mov']} {r['exec']}, {r['m_act']}", - f"{op} v[6:7], {sdst}, v2, v3, v[12:13]", - f"{r['mov']} {r['exec']}, -1", - f"{r['bcnt']} s14, {sdst}", - f"v_cndmask_b32_e64 v8, 0, 1, {sdst}", - "v_mov_b32 v9, s14", - "v_lshlrev_b32 v10, 4, v0", - "buffer_store_dwordx4 v[6:9], v10, s[0:3], 0 offen", - ] - mem = _run_cs(f"cs_{op}_{dst_kind}_w{self.wave_size}", lines, - wave_size=self.wave_size, emulate=self.emulate) - for lane in range(self.wave_size): - base = lane * 16 - got_lo, got_hi, got_bit, got_bcnt = (mem[base + 4 * k] for k in range(4)) - self.assertEqual(got_bcnt, len(hi_set), f"lane {lane} bcnt1") - if lane in hi_set: - self.assertEqual((got_lo, got_hi), (wh_lo, wh_hi), f"lane {lane} v[6:7]") - self.assertEqual(got_bit, 1, f"lane {lane} bit64") - elif lane in lo_set: - self.assertEqual((got_lo, got_hi), (wl_lo, wl_hi), f"lane {lane} v[6:7]") - self.assertEqual(got_bit, 0, f"lane {lane} bit64") - else: - self.assertEqual((got_lo, got_hi), (SENTINEL, SENTINEL), f"inactive lane {lane} v[6:7]") - self.assertEqual(got_bit, 0, f"inactive lane {lane} bit64 leaked") - - def test_cbranch_vccz_ignores_inactive_carry_and_sign(self): - """When only inactive lanes carry/borrow/sign-out, VCC is 0 and s_cbranch_vccz must be taken.""" - r = self._regs() - vcc = r["vcc"] - cases = [ - ("v_add_co_u32", [ - "v_mov_b32 v2, 0xffffffff", "v_mov_b32 v3, 1", - "v_mov_b32 v4, 1", - f"v_cndmask_b32_e64 v2, v2, v4, {r['m_act']}", - f"{r['mov']} {r['exec']}, {r['m_act']}", - f"v_add_co_u32_e32 v6, {vcc}, v2, v3", - ]), - ("v_sub_co_u32", [ - "v_mov_b32 v2, 0", "v_mov_b32 v3, 1", - "v_mov_b32 v4, 5", - f"v_cndmask_b32_e64 v2, v2, v4, {r['m_act']}", - f"{r['mov']} {r['exec']}, {r['m_act']}", - f"v_sub_co_u32_e32 v6, {vcc}, v2, v3", - ]), - ("v_mad_u64_u32", [ - "v_mov_b32 v2, 0xffffffff", "v_mov_b32 v3, 1", - "v_mov_b32 v12, 0xffffffff", "v_mov_b32 v13, 0xffffffff", - "v_mov_b32 v14, 0", - f"v_cndmask_b32_e64 v3, v3, v14, {r['m_act']}", - f"{r['mov']} {r['exec']}, {r['m_act']}", - f"v_mad_u64_u32 v[6:7], {vcc}, v2, v3, v[12:13]", - ]), - ("v_mad_i64_i32", [ - "v_mov_b32 v2, -1", "v_mov_b32 v3, 1", - "v_mov_b32 v12, 0", "v_mov_b32 v13, 0", - "v_mov_b32 v14, 1", - f"v_cndmask_b32_e64 v2, v2, v14, {r['m_act']}", - f"{r['mov']} {r['exec']}, {r['m_act']}", - f"v_mad_i64_i32 v[6:7], {vcc}, v2, v3, v[12:13]", - ]), - ] - for op, setup in cases: - with self.subTest(op=op, wave=self.wave_size, emu=self.emulate): - lines = [f"{r['mov']} {r['exec']}, -1"] - lines += _mask_lines(r["active_lo"], r["m_act"], r["m_tmp"], self.wave_size) - lines += [f"{r['mov']} {vcc}, -1", "s_mov_b32 s14, 0"] - lines += setup - lines += [ - "s_cbranch_vccz 1", - "s_mov_b32 s14, 1", - f"{r['mov']} {r['exec']}, -1", - "v_mov_b32 v8, s14", - "v_lshlrev_b32 v9, 2, v0", - "buffer_store_dword v8, v9, s[0:3], 0 offen", - ] - mem = _run_cs(f"cs_vccz_{op}_w{self.wave_size}", lines, - wave_size=self.wave_size, emulate=self.emulate, with_enc=True) - for lane in range(self.wave_size): - self.assertEqual(mem[lane * 4], 0, f"lane {lane}: s_cbranch_vccz not taken") - - def test_null_sdst_under_partial_exec(self): - """null scalar destination writes no mask (leaves VCC untouched) and preserves inactive VGPRs.""" - r = self._regs() - vcc = r["vcc"] - active_set = set(r["active_hi"]) - lines = [f"{r['mov']} {r['exec']}, -1"] - lines += _mask_lines(r["active_hi"], r["m_act"], r["m_tmp"], self.wave_size) - lines += _mask_lines([0], vcc, r["m_tmp"], self.wave_size) # VCC = lane 0 only - lines += [ - "v_mov_b32 v2, 0xffffffff", - "v_mov_b32 v3, 1", - "v_mov_b32 v12, 0xffffffff", - "v_mov_b32 v13, 0xffffffff", - f"v_mov_b32 v6, {SENTINEL:#x}", - f"v_mov_b32 v7, {SENTINEL:#x}", - f"v_mov_b32 v8, {SENTINEL:#x}", - f"{r['mov']} {r['exec']}, {r['m_act']}", - "v_add_co_u32_e64 v6, null, v2, v3", - "v_mad_u64_u32 v[7:8], null, v2, v3, v[12:13]", - f"{r['mov']} {r['exec']}, -1", - f"{r['bcnt']} s14, {vcc}", - "v_mov_b32 v9, s14", - "v_lshlrev_b32 v10, 4, v0", - "buffer_store_dwordx4 v[6:9], v10, s[0:3], 0 offen", - ] - mem = _run_cs(f"cs_null_sdst_w{self.wave_size}", lines, - wave_size=self.wave_size, emulate=self.emulate) - for lane in range(self.wave_size): - base = lane * 16 - v6, v7, v8, bcnt = (mem[base + 4 * k] for k in range(4)) - self.assertEqual(bcnt, 1, f"lane {lane}: VCC modified despite null sdst") - if lane in active_set: - self.assertEqual(v6, 0, f"active lane {lane} v6") - self.assertEqual((v7, v8), (0xFFFFFFFE, 0), f"active lane {lane} v[7:8]") - else: - self.assertEqual(v6, SENTINEL, f"inactive lane {lane} v6") - self.assertEqual((v7, v8), (SENTINEL, SENTINEL), f"inactive lane {lane} v[7:8]") - - -class CarryExecWave32Tests(_CarryExecMixin, unittest.TestCase): - wave_size = 32 - emulate = False - - -class CarryExecWave64Tests(_CarryExecMixin, unittest.TestCase): - wave_size = 64 - emulate = False - - -class CarryExecWave64EmulateTests(unittest.TestCase): - """Verify --wave64-emulate translates carry/mad64 ops and masks their lane-mask outputs by %active.""" - - def _translate_emu(self, name, body_lines): - prev_emu = rdna2spirv.WAVE64_EMULATE - try: - rdna2spirv.WAVE64_EMULATE = True - with tempfile.TemporaryDirectory() as tmp: - os.mkdir(os.path.join(tmp, "disasm")) - os.mkdir(os.path.join(tmp, "fssm")) - s_path = os.path.join(tmp, "disasm", name + ".s") - with open(s_path, "w", encoding="utf-8") as f: - f.write(f"; {name}\n") - for ln in body_lines: - f.write(f"\t{ln}\n") - f.write("\ts_endpgm\n") - with open(os.path.join(tmp, name + ".dxbc"), "wb") as f: - f.write(STUB_DXBC) - with open(os.path.join(tmp, "fssm", name + ".fssm"), "wb") as f: - f.write(bytes(0x138) + struct.pack("<4I", 0x8088, 64, 1, 1)) - with warnings.catch_warnings(): - warnings.simplefilter("ignore", ResourceWarning) - spv = rdna2spirv.translate(s_path) - gc.collect() - return spv - finally: - rdna2spirv.WAVE64_EMULATE = prev_emu - - def _assert_mask_anded_with_active(self, spv, dst_var): - """Confirm `OpStore ` selects on `OpLogicalAnd %bool ` where is %active.""" - defs = {} - active_vals = set() - stored = None - for ln in spv.splitlines(): - s = ln.strip() - if " = " in s: - lhs, rhs = s.split(" = ", 1) - defs[lhs] = rhs - if rhs == "OpLoad %bool %active": - active_vals.add(lhs) - elif s.startswith("OpStore %active "): - active_vals.add(s.split()[2]) - elif s.startswith(f"OpStore {dst_var} "): - stored = s.split()[2] - self.assertIsNotNone(stored, f"missing OpStore {dst_var}") - sel = defs.get(stored, "") - self.assertTrue(sel.startswith("OpSelect %uint "), f"unexpected store rhs: {sel}") - cond = sel.split()[2] - and_rhs = defs.get(cond, "") - self.assertTrue(and_rhs.startswith("OpLogicalAnd %bool "), - f"mask select condition {cond} not ANDed with %active: {and_rhs}") - operands = and_rhs.split()[2:4] - self.assertTrue(any(op in active_vals for op in operands), - f"OpLogicalAnd operands {operands} do not read %active") - - def test_emulate_co_and_mad64_mask_by_active(self): - cases = [ - ("v_add_co_u32", "v_add_co_u32_e32 v6, vcc, v2, v3", "%vcc"), - ("v_add_co_ci_u32", "v_add_co_ci_u32_e32 v6, vcc, v2, v3, vcc", "%vcc"), - ("v_sub_co_u32", "v_sub_co_u32_e32 v6, vcc, v2, v3", "%vcc"), - ("v_sub_co_ci_u32", "v_sub_co_ci_u32_e32 v6, vcc, v2, v3, vcc", "%vcc"), - ("v_subrev_co_u32", "v_subrev_co_u32_e32 v6, vcc, v2, v3", "%vcc"), - ("v_subrev_co_ci_u32", "v_subrev_co_ci_u32_e32 v6, vcc, v2, v3, vcc", "%vcc"), - ("v_mad_u64_u32", "v_mad_u64_u32 v[6:7], vcc, v2, v3, v[12:13]", "%vcc"), - ("v_mad_i64_i32", "v_mad_i64_i32 v[6:7], vcc, v2, v3, v[12:13]", "%vcc"), - ] - for op, inst, dst_var in cases: - with self.subTest(op=op): - spv = self._translate_emu(f"cs_emu_{op}", [ - "s_mov_b64 exec, -1", - "v_mov_b32 v2, 0xffffffff", - "v_mov_b32 v3, 1", - "v_mov_b32 v12, 0xffffffff", - "v_mov_b32 v13, 0xffffffff", - inst, - "s_bcnt1_i32_b64 s14, vcc", - "v_mov_b32 v8, s14", - "v_lshlrev_b32 v9, 2, v0", - "buffer_store_dword v8, v9, s[0:3], 0 offen", - ]) - self.assertIn("OpStore %x_it", spv) - self._assert_mask_anded_with_active(spv, dst_var) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_cmp_class_f32_mods.py b/tests/semantic/test_cmp_class_f32_mods.py deleted file mode 100644 index cbd8c9a88..000000000 --- a/tests/semantic/test_cmp_class_f32_mods.py +++ /dev/null @@ -1,286 +0,0 @@ -"""Semantic tests for v_cmp_class_f32 / v_cmpx_class_f32 with VOP3 neg/abs modifiers. - -Hardware rule (measured natively on AMD RDNA2 gfx1036, wave32 & wave64, IEEE=0/1, -denorm32 keep/flush, 672/672 exact across all 21 values x 4 modifiers x 10 class bits): - v_cmp_class_f32 and v_cmpx_class_f32 apply VOP3 abs (& 0x7FFFFFFF) then neg (^ 0x80000000) - as raw sign-bit moves on the 32-bit operand before testing the IEEE-754 class bits. - A signalling NaN stays signalling (class bit 0, never quieted to bit 1) and subnormals - stay subnormal (never flushed to zero), regardless of MODE.IEEE or MODE.FP32_DENORM. - -Before this fix, Gen.cmp_class loaded src0 through src_f -> modify(), emitting SPIR-V -FAbs / OpFNegate, which SPIR-V leaves free to quiet NaNs and which spirv_mini_interp.py -quieted from sNaN (bit 0) to qNaN (bit 1). - -No game files, llvm-mc, or GPU required; spirv-val check runs when spirv-as and spirv-val -are on PATH. -""" -import gc -import os -import shutil -import struct -import subprocess -import sys -import tempfile -import unittest -import warnings - -HERE = os.path.dirname(os.path.abspath(__file__)) -ROOT = os.path.dirname(os.path.dirname(HERE)) -TOOLS_DIR = os.environ.get("LEONIDA_TOOLS_DIR") or os.path.join(ROOT, "tools") - -sys.dont_write_bytecode = True -if TOOLS_DIR not in sys.path: - sys.path.insert(0, TOOLS_DIR) -if HERE not in sys.path: - sys.path.insert(0, HERE) - -import rdna2spirv # noqa: E402 -import spirv_mini_interp as si # noqa: E402 - -STUB_DXBC = b"DXBC" + bytes(24) + struct.pack(" int: - """Return the single 10-bit class mask bit for raw binary32 word u.""" - sign = (u >> 31) & 1 - absu = u & 0x7FFFFFFF - exp = absu >> 23 - man = absu & 0x7FFFFF - if exp == 255: - if man == 0: - return CLASS_NINF if sign else CLASS_PINF - return CLASS_QNAN if man >= 0x400000 else CLASS_SNAN - if absu == 0: - return CLASS_NZERO if sign else CLASS_PZERO - if exp == 0: - return CLASS_NSUB if sign else CLASS_PSUB - return CLASS_NNORM if sign else CLASS_PNORM - - -def translate_listing(body_lines, *, stage="ps", wave=32, group=(1, 1, 1)): - """Translate a hand-written RDNA2 listing through rdna2spirv.translate.""" - with tempfile.TemporaryDirectory() as td: - dis = os.path.join(td, "disasm") - fssm = os.path.join(td, "fssm") - os.makedirs(dis) - os.makedirs(fssm) - name = "ps_test" if stage == "ps" else "cs_test" - with open(os.path.join(td, f"{name}.dxbc"), "wb") as f: - f.write(STUB_DXBC if stage == "ps" else COMPUTE_DXBC) - # Minimal FSSM header: flags word at 0xD4 bit 5 (0x20) = wave32, 0 = wave64; - # compute rsrc2 + group size at 0x138..0x147. - hdr = bytearray(0x148) - hdr[0:4] = b"FSSM" - struct.pack_into(" bit 0 (sNaN) - "v_cndmask_b32_e64 v2, 0, 1, s4", - "v_cmp_class_f32_e64 s5, |0xffa00000|, 1", # |(-sNaN)| -> bit 0 (sNaN) - "v_cndmask_b32_e64 v4, 0, 1, s5", - "v_cmp_class_f32_e64 s6, -|0x7fbfffff|, 3", # -|(+sNaN)| -> bit 0, check bits 0|1 - "v_cndmask_b32_e64 v5, 0, 1, s6", - "v_cmp_class_f32_e64 s7, -|0x7fbfffff|, 2", # must NOT match bit 1 (qNaN) - "v_cndmask_b32_e64 v6, 0, 1, s7", - ]) - self.assertEqual(got, (1, 1, 1, 0)) - self.assertNotIn("FAbs", spv) - self.assertNotIn("OpFNegate", spv) - - def test_multilane_cmpx_snan_mods_and_inactive_lanes(self): - """Workgroup test: v_cmpx_class_f32 with -v/|v|/-|v| updates EXEC per lane and keeps disabled lanes off.""" - # 4 lanes: - # lane 0: 0x7f800001 (+sNaN) -> -v is -sNaN (bit 0 = 1) -> active - # lane 1: 0x7fc00000 (+qNaN) -> -v is -qNaN (bit 0 = 0) -> deactivated - # lane 2: 0xffa00000 (-sNaN) -> |v| is +sNaN (bit 0 = 1), but pre-disabled -> stays off - # lane 3: 0xffbfffff (-sNaN) -> -|v| is -sNaN (bit 0 = 1) -> active - body = [ - "s_mov_b32 s8, 0", - "s_mov_b32 s9, 0", - "s_mov_b32 s10, 64", - "s_mov_b32 s11, 0x31016fac", - # Load per-lane test value from buffer offset 4*lane - "v_lshlrev_b32 v10, 2, v0", - "buffer_load_dword v1, v10, s[8:11], 0 offen", - "s_waitcnt vmcnt(0)", - # Pre-disable lane 2 via EXEC - "v_cmp_ne_u32_e32 vcc_lo, 2, v0", - "s_and_b32 exec_lo, exec_lo, vcc_lo", - # Intersect EXEC with sNaN check through -v, |v|, and -|v| sequentially - "v_cmpx_class_f32_e64 -v1, 1", - "v_cmpx_class_f32_e64 |v1|, 1", - "v_cmpx_class_f32_e64 -|v1|, 1", - # Only lanes 0 and 3 remain active and write 0xCAFE0000 | lane to offset 32 + 4*lane - "v_or_b32 v2, 0xcafe0000, v0", - "v_add_nc_u32 v11, 32, v10", - "buffer_store_dword v2, v11, s[8:11], 0 offen", - "s_endpgm", - ] - spv = translate_listing(body, stage="cs", wave=32, group=(4, 1, 1)) - memory = { - 0: 0x7F800001, 4: 0x7FC00000, 8: 0xFFA00000, 12: 0xFFBFFFFF, - 32: 0xDEAD0000, 36: 0xDEAD0001, 40: 0xDEAD0002, 44: 0xDEAD0003, - } - si.run_workgroup( - spv, 4, 32, - inputs_for=lambda i: {"%wg_id": (0, 0, 0), "%local_id": (i, 0, 0)}, - push_constants=[0] * 32, - memory=memory, - ) - got = (memory[32], memory[36], memory[40], memory[44]) - self.assertEqual(got, (0xCAFE0000, 0xDEAD0001, 0xDEAD0002, 0xCAFE0003)) - - def test_spirv_val_accepts_modified_cmp_class(self): - """Translated SPIR-V with -v, |v|, -|v| passes spirv-as and spirv-val when installed.""" - spirv_as = shutil.which("spirv-as") - spirv_val = shutil.which("spirv-val") - if not spirv_as or not spirv_val: - self.skipTest("spirv-as / spirv-val not on PATH") - _, spv = run_ps([ - "v_mov_b32 v1, 0x7f800001", - "v_cmp_class_f32_e64 vcc_lo, -v1, 1", - "v_cndmask_b32_e64 v2, 0, 1, vcc_lo", - "v_cmp_class_f32_e64 s4, |v1|, 1", - "v_cndmask_b32_e64 v4, 0, 1, s4", - "v_cmp_class_f32_e64 s5, -|v1|, 1", - "v_cndmask_b32_e64 v5, 0, 1, s5", - "v_mov_b32 v6, 0", - "v_cmpx_class_f32_e64 -|v1|, 1", - "v_mov_b32 v6, 1", - ]) - with tempfile.TemporaryDirectory() as td: - asm_p = os.path.join(td, "m.spvasm") - bin_p = os.path.join(td, "m.spv") - with open(asm_p, "w", encoding="utf-8", newline="\n") as f: - f.write(spv) - subprocess.run([spirv_as, "--target-env", "vulkan1.2", asm_p, "-o", bin_p], check=True) - subprocess.run([spirv_val, "--target-env", "vulkan1.2", bin_p], check=True) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_cmp_class_f64.py b/tests/semantic/test_cmp_class_f64.py deleted file mode 100644 index 8893892a6..000000000 --- a/tests/semantic/test_cmp_class_f64.py +++ /dev/null @@ -1,205 +0,0 @@ -"""Semantic tests for RDNA2 v_cmp_class_f64 and v_cmpx_class_f64 via spirv_mini_interp. - -Tests all 10 IEEE-754 binary64 classes (including payloads living solely in the low 32 bits), mask combinations and -ignored upper mask bits, VGPR/SGPR pairs, float inline / inline integer / 32-bit upper-half literal constants, VOP3 -abs/neg sign-bit modifiers on src0, v_cmpx_class_f64 EXEC narrowing, inactive lanes, absence of Float64 capability, -and rejection of malformed operands/modifiers. Standard library only; no GPU, no LLVM, no game files. -""" -import os -import struct -import sys -import tempfile -import unittest -import warnings - -HERE = os.path.dirname(os.path.abspath(__file__)) -ROOT = os.path.dirname(os.path.dirname(HERE)) -sys.dont_write_bytecode = True -sys.path.insert(0, os.environ.get("LEONIDA_TOOLS_DIR") or os.path.join(ROOT, "tools")) -sys.path.insert(0, HERE) - -import rdna2spirv # noqa: E402 -import spirv_mini_interp as si # noqa: E402 - -STUB_DXBC = b"DXBC" + bytes(24) + struct.pack(" expected class bit index (0..9). -CLASS_SAMPLES = [ - # bit 0: sNaN (exp=0x7ff, bit 51=0, mantissa != 0 — including payload in lo word only, both signs) - (0x00000001, 0x7FF00000, 0), - (0x00000000, 0x7FF40000, 0), - (0x00000001, 0xFFF00000, 0), - (0xFFFFFFFF, 0xFFF7FFFF, 0), - # bit 1: qNaN (exp=0x7ff, bit 51=1, both signs) - (0x00000000, 0x7FF80000, 1), - (0x00000001, 0x7FF80000, 1), - (0x00000000, 0xFFF80000, 1), - (0xFFFFFFFF, 0xFFFFFFFF, 1), - # bit 2: -inf - (0x00000000, 0xFFF00000, 2), - # bit 3: -normal (min, -1.0, max) - (0x00000000, 0x80100000, 3), - (0x00000000, 0xBFF00000, 3), - (0xFFFFFFFF, 0xFFEFFFFF, 3), - # bit 4: -subnormal (payload in lo only and in hi only) - (0x00000001, 0x80000000, 4), - (0x00000000, 0x80080000, 4), - (0xFFFFFFFF, 0x800FFFFF, 4), - # bit 5: -0.0 - (0x00000000, 0x80000000, 5), - # bit 6: +0.0 - (0x00000000, 0x00000000, 6), - # bit 7: +subnormal (payload in lo only and in hi only) - (0x00000001, 0x00000000, 7), - (0x00000000, 0x00080000, 7), - (0xFFFFFFFF, 0x000FFFFF, 7), - # bit 8: +normal (min, +1.0, max) - (0x00000000, 0x00100000, 8), - (0x00000000, 0x3FF00000, 8), - (0xFFFFFFFF, 0x7FEFFFFF, 8), - # bit 9: +inf - (0x00000000, 0x7FF00000, 9), -] - - -def translate(lines, export="v0, v1, v2, v3"): - with tempfile.TemporaryDirectory() as tmp: - os.mkdir(os.path.join(tmp, "disasm")) - src = os.path.join(tmp, "disasm", "ps_cmp_class_f64.s") - with open(os.path.join(tmp, "ps_cmp_class_f64.dxbc"), "wb") as f: - f.write(STUB_DXBC) - with open(src, "w", encoding="utf-8", newline="\n") as f: - f.write("; ps_cmp_class_f64\n" + "".join(f"\t{ln}\n" for ln in lines) - + f"\texp mrt0 {export} done vm\n\ts_endpgm\n") - with warnings.catch_warnings(): - warnings.simplefilter("ignore", ResourceWarning) - return rdna2spirv.translate(src) - - -def run(lines, export="v0, v1, v2, v3"): - return list(si.run_fragment(translate(lines, export=export))["%out_mrt0"]) - - -class CmpClassF64Tests(unittest.TestCase): - def test_all_ten_classes_exhaustive_masks(self): - # For every sample, verify exact class bit hit, complementary mask miss, and high-bit ignore. - for lo, hi, bit in CLASS_SAMPLES: - hit_mask = 1 << bit - miss_mask = 0x3FF ^ hit_mask - hi_only_mask = 0xFFFFFC00 - with self.subTest(lo=hex(lo), hi=hex(hi), bit=bit): - got = run([ - f"v_mov_b32_e32 v4, {lo:#x}", - f"v_mov_b32_e32 v5, {hi:#x}", - f"v_mov_b32_e32 v6, {hit_mask:#x}", - f"v_mov_b32_e32 v7, {miss_mask:#x}", - f"v_mov_b32_e32 v8, {hi_only_mask:#x}", - "v_cmp_class_f64_e32 vcc_lo, v[4:5], v6", - "v_cndmask_b32_e32 v0, 0, 1, vcc_lo", - "v_cmp_class_f64_e64 s4, v[4:5], v7", - "v_cndmask_b32_e64 v1, 0, 1, s4", - "v_cmp_class_f64_e64 s5, v[4:5], v8", - "v_cndmask_b32_e64 v2, 0, 1, s5", - f"v_cmp_class_f64_e64 s6, v[4:5], {hit_mask | 0xFFFF0000:#x}", - "v_cndmask_b32_e64 v3, 0, 1, s6", - ]) - self.assertEqual(got, [1, 0, 0, 1]) - - def test_sgpr_pair_and_constants(self): - # SGPR pair (-inf), fimm (-2.0 -> bit 3), inline ints (0 -> +0 bit 6, 1 -> +subnorm bit 7, -1 -> qNaN bit 1), - # and 32-bit upper-half literals (0x3ff00000 -> +1.0 bit 8, 0x7ff00000 -> +inf bit 9). - got1 = run([ - "s_mov_b32 s8, 0", - "s_mov_b32 s9, 0xfff00000", - "v_cmp_class_f64_e64 s4, s[8:9], 0x4", - "v_cndmask_b32_e64 v0, 0, 1, s4", - "v_cmp_class_f64_e64 s4, -2.0, 0x8", - "v_cndmask_b32_e64 v1, 0, 1, s4", - "v_cmp_class_f64_e64 s4, 0, 0x40", - "v_cndmask_b32_e64 v2, 0, 1, s4", - "v_cmp_class_f64_e64 s4, 1, 0x80", - "v_cndmask_b32_e64 v3, 0, 1, s4", - ]) - self.assertEqual(got1, [1, 1, 1, 1]) - - got2 = run([ - "v_cmp_class_f64_e64 s4, -1, 0x2", # sign-extended 0xffffffff_ffffffff = qNaN - "v_cndmask_b32_e64 v0, 0, 1, s4", - "v_cmp_class_f64_e64 s4, 0x3ff00000, 0x100", # +1.0 in upper 32 bits -> +normal - "v_cndmask_b32_e64 v1, 0, 1, s4", - "v_cmp_class_f64_e64 s4, 0x7ff00000, 0x200", # +inf in upper 32 bits -> +inf - "v_cndmask_b32_e64 v2, 0, 1, s4", - "v_cmp_class_f64_e64 s4, 0x80000000, 0x20", # -0.0 in upper 32 bits -> -0.0 - "v_cndmask_b32_e64 v3, 0, 1, s4", - ]) - self.assertEqual(got2, [1, 1, 1, 1]) - - def test_vop3_abs_and_neg_modifiers_on_src0(self): - # abs clears bit 63 first, neg flips bit 63 second; sNaN stays sNaN (not quieted). - got = run([ - "v_mov_b32_e32 v4, 0", - "v_mov_b32_e32 v5, 0xbff00000", # -1.0 - "v_cmp_class_f64_e64 s4, |v[4:5]|, 0x100", # -> +normal (bit 8) - "v_cndmask_b32_e64 v0, 0, 1, s4", - "v_cmp_class_f64_e64 s4, -|1.0|, 0x8", # -> -normal (bit 3) - "v_cndmask_b32_e64 v1, 0, 1, s4", - "v_cmp_class_f64_e64 s4, neg(0), 0x20", # -> -0.0 (bit 5) - "v_cndmask_b32_e64 v2, 0, 1, s4", - "v_mov_b32_e32 v6, 1", - "v_mov_b32_e32 v7, 0x7ff00000", # +sNaN (lo=1) - "v_cmp_class_f64_e64 s4, -v[6:7], 0x1", # -> -sNaN, still bit 0 (not quieted to bit 1) - "v_cndmask_b32_e64 v3, 0, 1, s4", - ]) - self.assertEqual(got, [1, 1, 1, 1]) - - def test_cmpx_exec_narrowing_and_inactive_lanes(self): - # v_cmpx_class_f64 keeps active lane on match and clears EXEC on mismatch; inactive lane writes 0 to sdst. - got = run([ - "v_mov_b32_e32 v0, 10", - "v_mov_b32_e32 v1, 20", - "v_mov_b32_e32 v2, 30", - "v_mov_b32_e32 v3, 40", - "v_mov_b32_e32 v4, 0", - "v_mov_b32_e32 v5, 0x7ff00000", # +inf (bit 9) - "s_mov_b32 s10, exec_lo", - "v_cmpx_class_f64_e64 v[4:5], 0x200", # matches -> lane stays active - "v_mov_b32_e32 v0, 11", - "v_cmpx_class_f64_e64 v[4:5], 0x4", # -inf mismatch -> lane turns off - "v_mov_b32_e32 v1, 21", # skipped - "v_cmp_class_f64_e64 s6, v[4:5], 0x200", # inactive -> writes 0 to s6 - "s_mov_b32 exec_lo, s10", - "v_cndmask_b32_e64 v2, 31, 32, s6", # s6 is 0 -> selects 31 - "v_cmp_class_f64_e64 s7, v[4:5], 0x200", # active again -> writes 1 - "v_cndmask_b32_e64 v3, 41, 42, s7", # s7 is 1 -> selects 42 - ]) - self.assertEqual(got, [11, 20, 31, 42]) - - def test_no_float64_capability_required(self): - spv = translate([ - "v_mov_b32_e32 v0, 0", - "v_mov_b32_e32 v1, 0x3ff00000", - "v_cmp_class_f64_e64 s4, v[0:1], 0x100", - "v_cndmask_b32_e64 v2, 0, 1, s4", - "v_mov_b32_e32 v3, 0", - ]) - self.assertNotIn("OpCapability Float64", spv) - self.assertNotIn("OpTypeFloat 64", spv) - - def test_rejected_forms(self): - for line in ( - "v_cmp_class_f64_e32 vcc_lo, v0, v1", # single VGPR instead of pair - "v_cmp_class_f64_e64 s4, s0, 0x1", # single SGPR instead of pair - "v_cmp_class_f64_e64 s4, v[0:1], v[2:3]", # pair mask - "v_cmp_class_f64_e64 s4, v[0:1], -v2", # neg on mask - "v_cmp_class_f64_e64 v2, v[0:1], 0x1", # VGPR destination - "v_cmp_class_f64_e64 s4, v[0:1], 0x1 clamp", # unsupported modifier - "v_cmpx_class_f64_e64 s4, v[0:1], 0x1", # non-exec 3-operand cmpx - ): - with self.subTest(line=line): - with self.assertRaises(rdna2spirv.Unsupported): - translate(["v_mov_b32_e32 v0, 0", "v_mov_b32_e32 v1, 0", "v_mov_b32_e32 v2, 0", - "v_mov_b32_e32 v3, 0", line]) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_cmp_f64.py b/tests/semantic/test_cmp_f64.py deleted file mode 100644 index 08152518d..000000000 --- a/tests/semantic/test_cmp_f64.py +++ /dev/null @@ -1,219 +0,0 @@ -"""Semantic tests for all 32 RDNA2 binary64 vector compares (v_cmp_*_f64 and v_cmpx_*_f64) via spirv_mini_interp. - -Verifies all 16 predicates (f, lt, eq, le, gt, lg, ge, o, u, nge, nlg, ngt, nle, neq, nlt, tru) across IEEE-754 -binary64 edge values (sNaN, qNaN, +-inf, +-normal, 1-ULP neighbors, +-subnormal, +-0.0), VGPR/SGPR pairs, float inline / -inline integer / 32-bit upper-half literal constants, VOP3 abs/neg modifiers, v_cmpx_*_f64 EXEC narrowing, inactive -lanes, absence of Float64 capability, and bad-operand/modifier rejections. Standard library only; no GPU, no LLVM, no -game files. -""" -import math -import os -import struct -import sys -import tempfile -import unittest -import warnings - -HERE = os.path.dirname(os.path.abspath(__file__)) -ROOT = os.path.dirname(os.path.dirname(HERE)) -sys.dont_write_bytecode = True -sys.path.insert(0, os.environ.get("LEONIDA_TOOLS_DIR") or os.path.join(ROOT, "tools")) -sys.path.insert(0, HERE) - -import rdna2spirv # noqa: E402 -import spirv_mini_interp as si # noqa: E402 - -STUB_DXBC = b"DXBC" + bytes(24) + struct.pack(" b) - if pred == "lg": - return int(not unord and a != b) - if pred == "ge": - return int(not unord and a >= b) - if pred == "nge": - return int(unord or a < b) - if pred == "nlg": - return int(unord or a == b) - if pred == "ngt": - return int(unord or a <= b) - if pred == "nle": - return int(unord or a > b) - if pred == "neq": - return int(unord or a != b) - if pred == "nlt": - return int(unord or a >= b) - raise ValueError(pred) - - -def translate(lines, export="v0, v1, v2, v3"): - with tempfile.TemporaryDirectory() as tmp: - os.mkdir(os.path.join(tmp, "disasm")) - src = os.path.join(tmp, "disasm", "ps_cmp_f64.s") - with open(os.path.join(tmp, "ps_cmp_f64.dxbc"), "wb") as f: - f.write(STUB_DXBC) - with open(src, "w", encoding="utf-8", newline="\n") as f: - f.write("; ps_cmp_f64\n" + "".join(f"\t{ln}\n" for ln in lines) - + f"\texp mrt0 {export} done vm\n\ts_endpgm\n") - with warnings.catch_warnings(): - warnings.simplefilter("ignore", ResourceWarning) - return rdna2spirv.translate(src) - - -def run(lines, export="v0, v1, v2, v3"): - return list(si.run_fragment(translate(lines, export=export))["%out_mrt0"]) - - -class CmpF64Tests(unittest.TestCase): - def test_all_16_predicates_on_edge_pairs(self): - # Pack 4 predicates per fragment run -> 4 runs per pair across representative pairs. - pairs = [ - # (a, b) covering -inf, -1-ulp, -1, -1+0.5ulp, -subnorm, -0, +0, +subnorm, +1, +1+ulp, +inf, sNaN, qNaN - (F64_SAMPLES[0], F64_SAMPLES[1]), # -inf < -max_normal - (F64_SAMPLES[2], F64_SAMPLES[3]), # -1-ulp < -1 - (F64_SAMPLES[3], F64_SAMPLES[4]), # -1 < -1+0.5ulp - (F64_SAMPLES[5], F64_SAMPLES[6]), # -min_subnormal < -0.0 - (F64_SAMPLES[6], F64_SAMPLES[7]), # -0.0 == +0.0 - (F64_SAMPLES[7], F64_SAMPLES[8]), # +0.0 < +min_subnormal - (F64_SAMPLES[9], F64_SAMPLES[10]), # +1.0 < +1.0+ulp - (F64_SAMPLES[10], F64_SAMPLES[9]), # +1.0+ulp > +1.0 - (F64_SAMPLES[11], F64_SAMPLES[11]), # +inf == +inf - (F64_SAMPLES[12], F64_SAMPLES[9]), # sNaN vs +1.0 - (F64_SAMPLES[9], F64_SAMPLES[13]), # +1.0 vs qNaN - (F64_SAMPLES[12], F64_SAMPLES[13]), # sNaN vs qNaN - ] - for (alo, ahi), (blo, bhi) in pairs: - for chunk in range(0, 16, 4): - ps = PREDS[chunk:chunk + 4] - lines = [ - f"v_mov_b32_e32 v4, {alo:#x}", f"v_mov_b32_e32 v5, {ahi:#x}", - f"v_mov_b32_e32 v6, {blo:#x}", f"v_mov_b32_e32 v7, {bhi:#x}", - ] - for i, p in enumerate(ps): - if i == 0: - lines += [f"v_cmp_{p}_f64_e32 vcc_lo, v[4:5], v[6:7]", - f"v_cndmask_b32_e32 v{i}, 0, 1, vcc_lo"] - else: - lines += [f"v_cmp_{p}_f64_e64 s{4 + i}, v[4:5], v[6:7]", - f"v_cndmask_b32_e64 v{i}, 0, 1, s{4 + i}"] - want = [expected_pred(p, alo, ahi, blo, bhi) for p in ps] - with self.subTest(a=(hex(alo), hex(ahi)), b=(hex(blo), hex(bhi)), preds=ps): - self.assertEqual(run(lines), want) - - def test_sgpr_pairs_constants_and_vop3_modifiers(self): - # SGPR pair, fimm, inline ints (0, 1, -1), 32-bit upper-half literals, and abs/neg on both sources. - got = run([ - "s_mov_b32 s8, 0", "s_mov_b32 s9, 0x3ff00000", # +1.0 - "v_mov_b32_e32 v4, 0", "v_mov_b32_e32 v5, 0x3ff80000", # +1.5 - "v_cmp_eq_f64_e64 s4, s[8:9], 1.0", # SGPR == fimm -> 1 - "v_cndmask_b32_e64 v0, 0, 1, s4", - "v_cmp_eq_f64_e64 s4, 0x3ff80000, v[4:5]", # 32-bit upper-half literal == +1.5 -> 1 - "v_cndmask_b32_e64 v1, 0, 1, s4", - "v_cmp_lt_f64_e64 s4, 0, 1", # +0.0 < +min_subnormal (inline int 1) -> 1 - "v_cndmask_b32_e64 v2, 0, 1, s4", - "v_cmp_u_f64_e64 s4, -1, 0", # inline -1 is qNaN -> unordered 1 - "v_cndmask_b32_e64 v3, 0, 1, s4", - ]) - self.assertEqual(got, [1, 1, 1, 1]) - - got_mod = run([ - "v_mov_b32_e32 v4, 0", "v_mov_b32_e32 v5, 0xc0000000", # -2.0 - "v_cmp_eq_f64_e64 s4, |v[4:5]|, 2.0", # |-2.0| == 2.0 -> 1 - "v_cndmask_b32_e64 v0, 0, 1, s4", - "v_cmp_eq_f64_e64 s4, -|2.0|, v[4:5]", # -|2.0| == -2.0 -> 1 - "v_cndmask_b32_e64 v1, 0, 1, s4", - "v_cmp_eq_f64_e64 s4, neg(0), 0", # -0.0 == +0.0 -> 1 - "v_cndmask_b32_e64 v2, 0, 1, s4", - "v_cmp_lt_f64_e64 s4, neg(1), 0", # -min_subnormal < +0.0 -> 1 - "v_cndmask_b32_e64 v3, 0, 1, s4", - ]) - self.assertEqual(got_mod, [1, 1, 1, 1]) - - def test_cmpx_exec_narrowing_and_inactive_lanes(self): - got = run([ - "v_mov_b32_e32 v0, 10", "v_mov_b32_e32 v1, 20", - "v_mov_b32_e32 v2, 30", "v_mov_b32_e32 v3, 40", - "v_mov_b32_e32 v4, 0", "v_mov_b32_e32 v5, 0x3ff00000", # +1.0 - "v_mov_b32_e32 v6, 0", "v_mov_b32_e32 v7, 0x40000000", # +2.0 - "s_mov_b32 s10, exec_lo", - "v_cmpx_lt_f64_e32 v[4:5], v[6:7]", # 1.0 < 2.0 -> stays active - "v_mov_b32_e32 v0, 11", - "v_cmpx_gt_f64_e64 v[4:5], v[6:7]", # 1.0 > 2.0 -> turns off - "v_mov_b32_e32 v1, 21", # skipped - "v_cmp_tru_f64_e64 s6, v[4:5], v[6:7]", # inactive -> writes 0 - "s_mov_b32 exec_lo, s10", - "v_cndmask_b32_e64 v2, 31, 32, s6", # s6 is 0 -> 31 - "v_cmp_tru_f64_e64 s7, v[4:5], v[6:7]", # active -> writes 1 - "v_cndmask_b32_e64 v3, 41, 42, s7", # s7 is 1 -> 42 - ]) - self.assertEqual(got, [11, 20, 31, 42]) - - def test_no_float64_capability_required(self): - spv = translate([ - "v_mov_b32_e32 v0, 0", "v_mov_b32_e32 v1, 0x3ff00000", - "v_cmp_lt_f64_e64 s4, v[0:1], 2.0", - "v_cndmask_b32_e64 v2, 0, 1, s4", - "v_mov_b32_e32 v3, 0", - ]) - self.assertNotIn("OpCapability Float64", spv) - self.assertNotIn("OpTypeFloat 64", spv) - - def test_rejected_forms(self): - for line in ( - "v_cmp_lt_f64_e32 vcc_lo, v0, v[2:3]", # single VGPR src0 - "v_cmp_lt_f64_e64 s4, v[0:1], s2", # single SGPR src1 - "v_cmp_lt_f64_e64 v2, v[0:1], v[2:3]", # VGPR destination - "v_cmp_lt_f64_e64 s4, v[0:1], v[2:3] clamp", # unsupported modifier - "v_cmp_t_f64_e64 s4, v[0:1], v[2:3]", # integer 't' predicate on float - "s_cmp_eq_f64 s[0:1], s[2:3]", # scalar compare has no f64 - ): - with self.subTest(line=line): - with self.assertRaises(rdna2spirv.Unsupported): - translate(["v_mov_b32_e32 v0, 0", "v_mov_b32_e32 v1, 0", - "v_mov_b32_e32 v2, 0", "v_mov_b32_e32 v3, 0", line]) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_cndmask.py b/tests/semantic/test_cndmask.py deleted file mode 100644 index 1c69ec62f..000000000 --- a/tests/semantic/test_cndmask.py +++ /dev/null @@ -1,992 +0,0 @@ -"""Semantic interpreter tests for vector conditional move (v_cndmask_b32) with VCC and EXEC masks. - -AMD RDNA2 VALU Instruction Set Architecture: - v_cndmask_b32_e32 dst, src0, src1 - - Implicit condition mask: VCC (vcc_lo in Wave32, vcc in Wave64). - - For each lane i in the SIMD wave: - if EXEC[i] == 1: - dst[i] = src1[i] if (VCC[i] == 1) else src0[i] - else: - dst[i] = dst_previous[i] (inactive lanes preserve background state) - - v_cndmask_b32_e64 dst, src0, src1, cond_mask - - Explicit condition mask: any SGPR, SGPR pair, or VCC. - - Operates under EXEC mask identically to the e32 encoding. - -Divergence Scenarios: - 1. Uniform Conditions: - - All lanes condition 0 (VCC == 0): all active lanes select src0. - - All lanes condition 1 (VCC == ~0): all active lanes select src1. - 2. Alternating / Checkered Divergence: - - Alternating bit patterns (0x55555555 / 0xAAAAAAAA) across active lanes. - 3. Half-Wave and Strided Divergence: - - Divergent execution across low-half vs high-half (lanes 0..15 vs 16..31 in Wave32; - lanes 0..31 vs 32..63 in Wave64). - - Power-of-two strided clusters (blocks of 2, 4, 8, 16 lanes). - 4. Sparse Single-Bit Divergence: - - Exact one-hot / one-cold condition masks walking across all lane indices. - 5. Data-Dependent Divergence: - - Dynamic condition masks generated by vector comparisons (v_cmp_*). - 6. EXEC Mask Inactive Preservation: - - Lanes masked out by EXEC (EXEC[i] == 0) MUST preserve their previous VGPR values - without corruption, regardless of src0, src1, or VCC. - - Zero EXEC (EXEC == 0): whole-wave no-op across all vector registers. - 7. Correlated and Orthogonal Divergence: - - Structured If-Then-Else: Then block (EXEC = EXEC & VCC) and Else block - (EXEC = EXEC & ~VCC) executing v_cndmask_b32 independently and re-converging. - - Orthogonal masks: partial wave execution where EXEC and VCC vary independently. - 8. Wave64 Cross-Half Divergence: - - Independent condition patterns in low half (lanes 0..31) and high half (lanes 32..63). - - Half-disabled waves (EXEC low-half only or high-half only). - - Boundary transitions across the 32-lane boundary (lane 31 vs lane 32). - 9. SPIR-V Translation and Interpretation: - - Translation through tools/rdna2spirv.py emitting OpSelect with lane %active. - - Execution via tests/semantic/spirv_mini_interp.py. - 10. Negative Controls and Invariant Mutations: - - Condition inversion, operand swapping, and single-bit flip sensitivity. - -Standard library only: zero game data, no external dependencies, Python 3.9+ compatible. -""" -from __future__ import annotations - -import gc -import os -import random -import struct -import sys -import tempfile -import unittest -import warnings - -HERE = os.path.dirname(os.path.abspath(__file__)) -ROOT = os.path.dirname(os.path.dirname(HERE)) -TOOLS_DIR = os.environ.get("LEONIDA_TOOLS_DIR") or os.path.join(ROOT, "tools") -if TOOLS_DIR not in sys.path: - sys.path.insert(0, TOOLS_DIR) -if HERE not in sys.path: - sys.path.insert(0, HERE) - -import rdna2spirv # noqa: E402 -import spirv_mini_interp as si # noqa: E402 - -MASK32 = 0xFFFFFFFF -MASK64 = (1 << 64) - 1 -STUB_DXBC = b"DXBC" + bytes(24) + struct.pack(" int: - """AMD RDNA2 v_cndmask_b32 per-lane mathematical reference oracle. - - Lane semantics: - - If exec_bit == 0: lane is inactive, dst is preserved (returns prev_dst & MASK32). - - If exec_bit == 1: lane is active: - - If cond_bit == 0: selects src0 & MASK32. - - If cond_bit != 0: selects src1 & MASK32. - """ - if not (exec_bit & 1): - return prev_dst & MASK32 - return (src1 if (cond_bit & 1) else src0) & MASK32 - - -def ref_cndmask_wave( - src0_lanes: list[int], - src1_lanes: list[int], - cond_mask: int, - exec_mask: int, - prev_dst_lanes: list[int] | None = None, - wave_size: int = 32, -) -> list[int]: - """Whole-wave vector conditional move reference oracle across divergent lanes.""" - if prev_dst_lanes is None: - prev_dst_lanes = [0] * wave_size - res: list[int] = [] - for lane in range(wave_size): - c_bit = (cond_mask >> lane) & 1 - e_bit = (exec_mask >> lane) & 1 - s0 = src0_lanes[lane] - s1 = src1_lanes[lane] - old = prev_dst_lanes[lane] - res.append(ref_cndmask_lane(s0, s1, c_bit, e_bit, old)) - return res - - -# ----------------------------------------------------------------------------- -# 2. Multi-Lane Wave SIMD Interpreter -# ----------------------------------------------------------------------------- - -class CndmaskWaveInterpreter: - """Simulates a SIMD wave executing vector instructions with VCC and EXEC masks. - - Models: - - Wave32 (32 lanes) and Wave64 (64 lanes). - - VGPRs: per-lane independent 32-bit vector registers (v0..v255). - - SGPRs: uniform 32-bit scalar registers shared across the wave (s0..s127). - - VCC: condition mask register (32-bit vcc_lo in Wave32, 64-bit vcc in Wave64). - - EXEC: execution mask register (32-bit exec_lo in Wave32, 64-bit exec in Wave64). - - Instructions: - v_mov_b32, v_cndmask_b32_e32, v_cndmask_b32_e64, - v_cmp_eq/ne/lt/gt/le/ge_u32, - s_mov_b32/b64, s_and_saveexec_b32/b64, s_or_exec_b32/b64, s_and_b32/b64, - s_or_b32/b64, s_not_b32/b64. - """ - - def __init__(self, wave_size: int = 32, initial_exec: int | None = None) -> None: - if wave_size not in (32, 64): - raise ValueError(f"Unsupported wave_size: {wave_size}") - self.wave_size = wave_size - self.mask_all = (1 << wave_size) - 1 - self.exec_mask = self.mask_all if initial_exec is None else (initial_exec & self.mask_all) - self.vcc = 0 - self.sgprs = [0] * 128 - self.vgprs = [[0] * 256 for _ in range(wave_size)] - - def is_lane_active(self, lane: int) -> bool: - return bool((self.exec_mask >> lane) & 1) - - def set_exec(self, mask: int) -> None: - self.exec_mask = mask & self.mask_all - - def set_vcc(self, mask: int) -> None: - self.vcc = mask & self.mask_all - - def get_vgpr(self, reg_idx: int) -> list[int]: - return [self.vgprs[lane][reg_idx] for lane in range(self.wave_size)] - - def set_vgpr_lane(self, reg_idx: int, lane: int, val: int) -> None: - self.vgprs[lane][reg_idx] = val & MASK32 - - def init_vgpr(self, reg_idx: int, values: list[int] | int) -> None: - if isinstance(values, int): - val = values & MASK32 - for lane in range(self.wave_size): - self.vgprs[lane][reg_idx] = val - else: - for lane in range(min(len(values), self.wave_size)): - self.vgprs[lane][reg_idx] = values[lane] & MASK32 - - def read_operand(self, op: int | str, lane: int) -> int: - if isinstance(op, int): - return op & MASK32 - op_str = str(op).strip().lower() - if op_str.startswith("v"): - reg_idx = int(op_str[1:]) - return self.vgprs[lane][reg_idx] & MASK32 - elif op_str.startswith("s"): - reg_idx = int(op_str[1:]) - return self.sgprs[reg_idx] & MASK32 - elif op_str in ("vcc", "vcc_lo"): - return (self.vcc >> lane) & 1 - elif op_str == "vcc_hi": - return (self.vcc >> (lane + 32)) & 1 if self.wave_size == 64 else self.sgprs[1] - elif op_str in ("exec", "exec_lo"): - return (self.exec_mask >> lane) & 1 - else: - raise ValueError(f"Unsupported operand: {op}") - - def execute_v_mov(self, dst_v: int, src: int | str) -> None: - """v_mov_b32 dst_v, src: only active lanes are updated.""" - for lane in range(self.wave_size): - if self.is_lane_active(lane): - self.vgprs[lane][dst_v] = self.read_operand(src, lane) - - def execute_v_cndmask_e32(self, dst_v: int, src0: int | str, src1: int | str) -> None: - """v_cndmask_b32_e32 dst, src0, src1 with implicit VCC condition.""" - for lane in range(self.wave_size): - if self.is_lane_active(lane): - s0 = self.read_operand(src0, lane) - s1 = self.read_operand(src1, lane) - c_bit = (self.vcc >> lane) & 1 - self.vgprs[lane][dst_v] = s1 if c_bit else s0 - - def execute_v_cndmask_e64( - self, - dst_v: int, - src0: int | str, - src1: int | str, - cond_src: str | int, - ) -> None: - """v_cndmask_b32_e64 dst, src0, src1, cond_src with explicit condition mask.""" - for lane in range(self.wave_size): - if self.is_lane_active(lane): - s0 = self.read_operand(src0, lane) - s1 = self.read_operand(src1, lane) - if isinstance(cond_src, int): - c_bit = (cond_src >> lane) & 1 - elif cond_src in ("vcc", "vcc_lo"): - c_bit = (self.vcc >> lane) & 1 - elif cond_src.startswith("s[") and ":" in cond_src: - lo_hi = cond_src[2:-1].split(":") - lo = int(lo_hi[0]) - mask = (self.sgprs[lo] & MASK32) | ((self.sgprs[lo + 1] & MASK32) << 32) - c_bit = (mask >> lane) & 1 - elif cond_src.startswith("s"): - reg = int(cond_src[1:]) - c_bit = (self.sgprs[reg] >> (lane % 32)) & 1 - else: - raise ValueError(f"Unknown cond_src: {cond_src}") - self.vgprs[lane][dst_v] = s1 if c_bit else s0 - - def execute_v_cmp( - self, - rel: str, - src0: int | str, - src1: int | str, - dst_mask: str = "vcc", - ) -> None: - """v_cmp__u32/i32: inactive lanes in EXEC write 0 to condition mask.""" - mask = 0 - for lane in range(self.wave_size): - if self.is_lane_active(lane): - s0 = self.read_operand(src0, lane) - s1 = self.read_operand(src1, lane) - taken = False - if rel == "eq": - taken = (s0 == s1) - elif rel == "ne": - taken = (s0 != s1) - elif rel == "lt_u32": - taken = (s0 < s1) - elif rel == "le_u32": - taken = (s0 <= s1) - elif rel == "gt_u32": - taken = (s0 > s1) - elif rel == "ge_u32": - taken = (s0 >= s1) - else: - raise NotImplementedError(f"Unsupported cmp rel: {rel}") - if taken: - mask |= (1 << lane) - if dst_mask in ("vcc", "vcc_lo"): - self.vcc = mask & self.mask_all - elif dst_mask.startswith("s[") and ":" in dst_mask: - lo_hi = dst_mask[2:-1].split(":") - lo = int(lo_hi[0]) - self.sgprs[lo] = mask & MASK32 - self.sgprs[lo + 1] = (mask >> 32) & MASK32 - elif dst_mask.startswith("s"): - reg = int(dst_mask[1:]) - self.sgprs[reg] = mask & MASK32 - - def execute_s_and_saveexec(self, dst_s: int, mask_src: str | int) -> None: - """s_and_saveexec_b32 / s_and_saveexec_b64: save EXEC and narrow it.""" - self.sgprs[dst_s] = self.exec_mask & MASK32 - if self.wave_size == 64: - self.sgprs[dst_s + 1] = (self.exec_mask >> 32) & MASK32 - if isinstance(mask_src, int): - m = mask_src - elif mask_src in ("vcc", "vcc_lo"): - m = self.vcc - elif mask_src.startswith("s[") and ":" in mask_src: - lo = int(mask_src[2:-1].split(":")[0]) - m = (self.sgprs[lo] & MASK32) | ((self.sgprs[lo + 1] & MASK32) << 32) - elif mask_src.startswith("s"): - m = self.sgprs[int(mask_src[1:])] - else: - raise ValueError(f"Unknown mask_src: {mask_src}") - self.exec_mask = (self.exec_mask & m) & self.mask_all - - def execute_s_or_exec(self, mask_src: str | int) -> None: - """s_or_exec_b32 / s_or_exec_b64: EXEC |= mask.""" - if isinstance(mask_src, int): - m = mask_src - elif mask_src in ("vcc", "vcc_lo"): - m = self.vcc - elif mask_src.startswith("s[") and ":" in mask_src: - lo = int(mask_src[2:-1].split(":")[0]) - m = (self.sgprs[lo] & MASK32) | ((self.sgprs[lo + 1] & MASK32) << 32) - elif mask_src.startswith("s"): - m = self.sgprs[int(mask_src[1:])] - else: - raise ValueError(f"Unknown mask_src: {mask_src}") - self.exec_mask = (self.exec_mask | m) & self.mask_all - - -# ----------------------------------------------------------------------------- -# 3. Synthetic Shader Runner via rdna2spirv & spirv_mini_interp -# ----------------------------------------------------------------------------- - -_TMP_DIR: tempfile.TemporaryDirectory | None = None -_SRC_PATH: str | None = None - - -def setUpModule() -> None: - global _TMP_DIR, _SRC_PATH - _TMP_DIR = tempfile.TemporaryDirectory() - disasm_dir = os.path.join(_TMP_DIR.name, "disasm") - os.mkdir(disasm_dir) - _SRC_PATH = os.path.join(disasm_dir, "ps_cndmask.s") - with open(os.path.join(_TMP_DIR.name, "ps_cndmask.dxbc"), "wb") as f: - f.write(STUB_DXBC) - - -def tearDownModule() -> None: - global _TMP_DIR - if _TMP_DIR is not None: - _TMP_DIR.cleanup() - _TMP_DIR = None - - -def run_synthetic_ps(lines: list[str]) -> tuple[int, int, int, int]: - """Translates synthetic assembly lines and executes with spirv_mini_interp.""" - if _TMP_DIR is None: - setUpModule() - assert _SRC_PATH is not None - asm = ( - "; ps_cndmask\n" - + "".join(f"\t{ln}\n" for ln in lines) - + "\texp mrt0 v0, v1, v2, v3 done vm\n\ts_endpgm\n" - ) - with open(_SRC_PATH, "w", encoding="utf-8") as f: - f.write(asm) - with warnings.catch_warnings(): - warnings.simplefilter("ignore", ResourceWarning) - spv = rdna2spirv.translate(_SRC_PATH) - res = si.run_fragment(spv)["%out_mrt0"] - return tuple(res) - - -# ----------------------------------------------------------------------------- -# 4. Test Suites -# ----------------------------------------------------------------------------- - -class TestCndmaskReferenceOracle(unittest.TestCase): - """Verifies core mathematical reference oracle, truth table, and invariants.""" - - def test_truth_table_active_lane(self) -> None: - """For active lanes, cond_bit=0 selects src0, cond_bit=1 selects src1.""" - src0 = 0x11111111 - src1 = 0x22222222 - prev = 0x99999999 - self.assertEqual(ref_cndmask_lane(src0, src1, cond_bit=0, exec_bit=1, prev_dst=prev), src0) - self.assertEqual(ref_cndmask_lane(src0, src1, cond_bit=1, exec_bit=1, prev_dst=prev), src1) - - def test_inactive_lane_preservation(self) -> None: - """When exec_bit=0, previous dst is preserved regardless of cond, src0, or src1.""" - src0 = 0xAAAAAAAA - src1 = 0xBBBBBBBB - prev = 0xDEADBEEF - self.assertEqual(ref_cndmask_lane(src0, src1, cond_bit=0, exec_bit=0, prev_dst=prev), prev) - self.assertEqual(ref_cndmask_lane(src0, src1, cond_bit=1, exec_bit=0, prev_dst=prev), prev) - - def test_complement_duality(self) -> None: - """Duality: cndmask(src0, src1, cond) == cndmask(src1, src0, 1 - cond).""" - rng = random.Random(20261122) - for _ in range(100): - s0 = rng.getrandbits(32) - s1 = rng.getrandbits(32) - for c in (0, 1): - res_normal = ref_cndmask_lane(s0, s1, cond_bit=c, exec_bit=1) - res_dual = ref_cndmask_lane(s1, s0, cond_bit=1 - c, exec_bit=1) - self.assertEqual(res_normal, res_dual) - - def test_idempotence(self) -> None: - """Idempotence: cndmask(x, x, cond) == x for any condition when active.""" - rng = random.Random(20261122) - for _ in range(50): - x = rng.getrandbits(32) - self.assertEqual(ref_cndmask_lane(x, x, cond_bit=0, exec_bit=1), x) - self.assertEqual(ref_cndmask_lane(x, x, cond_bit=1, exec_bit=1), x) - - def test_extreme_32bit_values(self) -> None: - """Bit patterns including 0, max uint, signed limits, and float bit patterns.""" - extremes = [ - 0x00000000, 0xFFFFFFFF, 0x7FFFFFFF, 0x80000000, - 0x3F800000, 0xBF800000, 0x7F800000, 0xFF800000, - ] - for s0 in extremes: - for s1 in extremes: - self.assertEqual(ref_cndmask_lane(s0, s1, 0, 1), s0) - self.assertEqual(ref_cndmask_lane(s0, s1, 1, 1), s1) - - -class TestCndmaskWave32Divergence(unittest.TestCase): - """Verifies SIMD Wave32 execution across divergent lane patterns.""" - - def test_uniform_all_false_vcc(self) -> None: - """All 32 lanes active with VCC = 0x00000000 (all select src0).""" - wave = CndmaskWaveInterpreter(wave_size=32) - src0_vals = [0x1000 + i for i in range(32)] - src1_vals = [0x2000 + i for i in range(32)] - wave.init_vgpr(0, src0_vals) - wave.init_vgpr(1, src1_vals) - wave.set_vcc(0x00000000) - wave.set_exec(0xFFFFFFFF) - wave.execute_v_cndmask_e32(dst_v=2, src0="v0", src1="v1") - self.assertEqual(wave.get_vgpr(2), src0_vals) - - def test_uniform_all_true_vcc(self) -> None: - """All 32 lanes active with VCC = 0xFFFFFFFF (all select src1).""" - wave = CndmaskWaveInterpreter(wave_size=32) - src0_vals = [0x1000 + i for i in range(32)] - src1_vals = [0x2000 + i for i in range(32)] - wave.init_vgpr(0, src0_vals) - wave.init_vgpr(1, src1_vals) - wave.set_vcc(0xFFFFFFFF) - wave.set_exec(0xFFFFFFFF) - wave.execute_v_cndmask_e32(dst_v=2, src0="v0", src1="v1") - self.assertEqual(wave.get_vgpr(2), src1_vals) - - def test_checkered_divergence(self) -> None: - """Alternating lanes: VCC = 0x55555555 (even lanes select src1, odd lanes select src0).""" - wave = CndmaskWaveInterpreter(wave_size=32) - src0_vals = [0xA000 + i for i in range(32)] - src1_vals = [0xB000 + i for i in range(32)] - wave.init_vgpr(0, src0_vals) - wave.init_vgpr(1, src1_vals) - vcc_mask = 0x55555555 - wave.set_vcc(vcc_mask) - wave.set_exec(0xFFFFFFFF) - wave.execute_v_cndmask_e32(dst_v=2, src0="v0", src1="v1") - expected = [src1_vals[i] if (i % 2 == 0) else src0_vals[i] for i in range(32)] - self.assertEqual(wave.get_vgpr(2), expected) - - def test_inverted_checkered_divergence(self) -> None: - """Alternating lanes: VCC = 0xAAAAAAAA (odd lanes select src1, even lanes select src0).""" - wave = CndmaskWaveInterpreter(wave_size=32) - src0_vals = [0xC000 + i for i in range(32)] - src1_vals = [0xD000 + i for i in range(32)] - wave.init_vgpr(0, src0_vals) - wave.init_vgpr(1, src1_vals) - vcc_mask = 0xAAAAAAAA - wave.set_vcc(vcc_mask) - wave.set_exec(0xFFFFFFFF) - wave.execute_v_cndmask_e32(dst_v=2, src0="v0", src1="v1") - expected = [src1_vals[i] if (i % 2 == 1) else src0_vals[i] for i in range(32)] - self.assertEqual(wave.get_vgpr(2), expected) - - def test_half_wave_divergence(self) -> None: - """Half-wave divergence: lanes 0..15 select src1, lanes 16..31 select src0.""" - wave = CndmaskWaveInterpreter(wave_size=32) - src0_vals = [100 + i for i in range(32)] - src1_vals = [200 + i for i in range(32)] - wave.init_vgpr(0, src0_vals) - wave.init_vgpr(1, src1_vals) - wave.set_vcc(0x0000FFFF) - wave.set_exec(0xFFFFFFFF) - wave.execute_v_cndmask_e32(dst_v=2, src0="v0", src1="v1") - expected = [src1_vals[i] if i < 16 else src0_vals[i] for i in range(32)] - self.assertEqual(wave.get_vgpr(2), expected) - - def test_power_of_two_strides(self) -> None: - """Power-of-two stride clusters: blocks of 2, 4, 8, 16 divergent lanes.""" - for stride in (2, 4, 8, 16): - with self.subTest(stride=stride): - wave = CndmaskWaveInterpreter(wave_size=32) - src0_vals = [1000 + i for i in range(32)] - src1_vals = [2000 + i for i in range(32)] - wave.init_vgpr(0, src0_vals) - wave.init_vgpr(1, src1_vals) - vcc = 0 - for i in range(32): - if (i // stride) % 2 == 1: - vcc |= (1 << i) - wave.set_vcc(vcc) - wave.set_exec(0xFFFFFFFF) - wave.execute_v_cndmask_e32(dst_v=2, src0="v0", src1="v1") - expected = [src1_vals[i] if ((i // stride) % 2 == 1) else src0_vals[i] for i in range(32)] - self.assertEqual(wave.get_vgpr(2), expected) - - def test_sparse_single_bit_walk(self) -> None: - """Walks each bit 0..31 with only that single lane condition true, then inverted.""" - wave = CndmaskWaveInterpreter(wave_size=32) - src0 = [0x10 + i for i in range(32)] - src1 = [0x80 + i for i in range(32)] - wave.init_vgpr(0, src0) - wave.init_vgpr(1, src1) - wave.set_exec(0xFFFFFFFF) - - for bit in range(32): - wave.set_vcc(1 << bit) - wave.execute_v_cndmask_e32(dst_v=2, src0="v0", src1="v1") - expected_one_hot = [src1[i] if i == bit else src0[i] for i in range(32)] - self.assertEqual(wave.get_vgpr(2), expected_one_hot) - - wave.set_vcc(~(1 << bit) & MASK32) - wave.execute_v_cndmask_e32(dst_v=2, src0="v0", src1="v1") - expected_one_cold = [src0[i] if i == bit else src1[i] for i in range(32)] - self.assertEqual(wave.get_vgpr(2), expected_one_cold) - - def test_data_dependent_divergence_from_cmp(self) -> None: - """Divergence created dynamically by v_cmp_gt_u32.""" - wave = CndmaskWaveInterpreter(wave_size=32) - # v0 contains lane IDs: 0, 1, 2, ..., 31 - wave.init_vgpr(0, list(range(32))) - wave.init_vgpr(1, 111) # src0 - wave.init_vgpr(2, 222) # src1 - wave.set_exec(0xFFFFFFFF) - - # Condition: lane_id > 10 (lanes 0..10 false, lanes 11..31 true) - wave.execute_v_cmp("gt_u32", "v0", 10, dst_mask="vcc") - self.assertEqual(wave.vcc, 0xFFFFF800) - - wave.execute_v_cndmask_e32(dst_v=3, src0="v1", src1="v2") - expected = [222 if i > 10 else 111 for i in range(32)] - self.assertEqual(wave.get_vgpr(3), expected) - - def test_destination_register_aliasing(self) -> None: - """In-place conditional move: dst == src0 or dst == src1.""" - wave = CndmaskWaveInterpreter(wave_size=32) - v0_init = [0xAA00 + i for i in range(32)] - v1_init = [0xBB00 + i for i in range(32)] - wave.init_vgpr(0, v0_init) - wave.init_vgpr(1, v1_init) - wave.set_vcc(0x55555555) - wave.set_exec(0xFFFFFFFF) - - # dst == src0: v_cndmask_b32 v0, v0, v1, vcc - wave.execute_v_cndmask_e32(dst_v=0, src0="v0", src1="v1") - expected = [v1_init[i] if (i % 2 == 0) else v0_init[i] for i in range(32)] - self.assertEqual(wave.get_vgpr(0), expected) - - -class TestCndmaskExecMaskInteraction(unittest.TestCase): - """Verifies EXEC mask gating, non-destructive inactive preservation, and control flow.""" - - def test_partial_exec_preservation(self) -> None: - """Inactive lanes (EXEC[i] == 0) must strictly preserve previous VGPR values.""" - wave = CndmaskWaveInterpreter(wave_size=32) - background = [0xDEAD0000 + i for i in range(32)] - wave.init_vgpr(2, background) - wave.init_vgpr(0, 0x11111111) - wave.init_vgpr(1, 0x22222222) - - # Only low 16 lanes are active - wave.set_exec(0x0000FFFF) - # Checkered VCC across all lanes - wave.set_vcc(0x55555555) - - wave.execute_v_cndmask_e32(dst_v=2, src0="v0", src1="v1") - result = wave.get_vgpr(2) - - for lane in range(16): - expected = 0x22222222 if (lane % 2 == 0) else 0x11111111 - self.assertEqual(result[lane], expected) - for lane in range(16, 32): - self.assertEqual(result[lane], background[lane], f"Lane {lane} was corrupted") - - def test_zero_exec_wave_nop(self) -> None: - """Whole-wave inactive (EXEC == 0): conditional move is a complete no-op.""" - wave = CndmaskWaveInterpreter(wave_size=32) - initial_dst = [0xCAFEBABE + i for i in range(32)] - wave.init_vgpr(2, initial_dst) - wave.init_vgpr(0, 0x12345678) - wave.init_vgpr(1, 0x87654321) - wave.set_exec(0x00000000) - wave.set_vcc(0xFFFFFFFF) - - wave.execute_v_cndmask_e32(dst_v=2, src0="v0", src1="v1") - self.assertEqual(wave.get_vgpr(2), initial_dst) - - def test_single_active_lane(self) -> None: - """Only one lane active in the wave.""" - for active_lane in (0, 7, 15, 23, 31): - with self.subTest(active_lane=active_lane): - wave = CndmaskWaveInterpreter(wave_size=32) - bg = [0x5000 + i for i in range(32)] - wave.init_vgpr(2, bg) - wave.init_vgpr(0, 0x10) - wave.init_vgpr(1, 0x20) - wave.set_exec(1 << active_lane) - wave.set_vcc(1 << active_lane) - - wave.execute_v_cndmask_e32(dst_v=2, src0="v0", src1="v1") - res = wave.get_vgpr(2) - for lane in range(32): - if lane == active_lane: - self.assertEqual(res[lane], 0x20) - else: - self.assertEqual(res[lane], bg[lane]) - - def test_structured_if_then_else_divergence(self) -> None: - """Simulates structured divergent branching: - v_cmp_gt_u32 -> s_and_saveexec (Then) -> v_cndmask -> s_and (Else) -> v_cndmask -> restore. - """ - wave = CndmaskWaveInterpreter(wave_size=32) - # v0 = lane_id - wave.init_vgpr(0, list(range(32))) - # Target registers - wave.init_vgpr(1, 0xAAAA0000) # then_val - wave.init_vgpr(2, 0xBBBB0000) # else_val - wave.init_vgpr(3, 0x00000000) # destination - - # 1. Evaluate condition: lane_id < 16 - wave.execute_v_cmp("lt_u32", "v0", 16, dst_mask="vcc") - self.assertEqual(wave.vcc, 0x0000FFFF) - - # 2. Enter THEN branch: s_and_saveexec_b32 s4, vcc_lo - wave.execute_s_and_saveexec(dst_s=4, mask_src="vcc") - self.assertEqual(wave.exec_mask, 0x0000FFFF) - # In THEN block: execute cndmask - wave.execute_v_cndmask_e32(dst_v=3, src0=0, src1="v1") - # Lanes 0..15 have then_val; lanes 16..31 still 0 - for i in range(16): - self.assertEqual(wave.vgprs[i][3], 0xAAAA0000) - for i in range(16, 32): - self.assertEqual(wave.vgprs[i][3], 0x00000000) - - # 3. Enter ELSE branch: invert mask - # EXEC = saved_exec & ~vcc - saved_exec = wave.sgprs[4] - wave.set_exec(saved_exec & (~wave.vcc & MASK32)) - self.assertEqual(wave.exec_mask, 0xFFFF0000) - # In ELSE block: execute cndmask with condition inverted - wave.set_vcc(~wave.vcc & MASK32) - wave.execute_v_cndmask_e32(dst_v=3, src0=0, src1="v2") - - # 4. Re-converge: restore EXEC - wave.set_exec(saved_exec) - self.assertEqual(wave.exec_mask, 0xFFFFFFFF) - - # Both halves must have their respective values intact - res = wave.get_vgpr(3) - expected = [0xAAAA0000 if i < 16 else 0xBBBB0000 for i in range(32)] - self.assertEqual(res, expected) - - def test_orthogonal_exec_and_vcc(self) -> None: - """Outer EXEC disabling lanes 16..31 while inner VCC alternates.""" - wave = CndmaskWaveInterpreter(wave_size=32) - initial = [0x77770000 + i for i in range(32)] - wave.init_vgpr(3, initial) - wave.init_vgpr(1, 0x1111) - wave.init_vgpr(2, 0x2222) - wave.set_exec(0x0000FFFF) # lanes 16..31 disabled - wave.set_vcc(0x55555555) # alternating VCC - - wave.execute_v_cndmask_e32(dst_v=3, src0="v1", src1="v2") - res = wave.get_vgpr(3) - for lane in range(16): - self.assertEqual(res[lane], 0x2222 if (lane % 2 == 0) else 0x1111) - for lane in range(16, 32): - self.assertEqual(res[lane], initial[lane]) - - -class TestCndmaskWave64Divergence(unittest.TestCase): - """Verifies 64-lane wave execution, cross-half divergence, and 64-bit masks.""" - - def test_wave64_uniform_conditions(self) -> None: - """Wave64 with all 64 lanes active: uniform false and true.""" - wave = CndmaskWaveInterpreter(wave_size=64) - src0 = [0x100 + i for i in range(64)] - src1 = [0x200 + i for i in range(64)] - wave.init_vgpr(0, src0) - wave.init_vgpr(1, src1) - wave.set_exec(MASK64) - - wave.set_vcc(0) - wave.execute_v_cndmask_e32(dst_v=2, src0="v0", src1="v1") - self.assertEqual(wave.get_vgpr(2), src0) - - wave.set_vcc(MASK64) - wave.execute_v_cndmask_e32(dst_v=2, src0="v0", src1="v1") - self.assertEqual(wave.get_vgpr(2), src1) - - def test_wave64_cross_half_divergence(self) -> None: - """Low half (lanes 0..31) has pattern A, high half (lanes 32..63) has pattern B.""" - wave = CndmaskWaveInterpreter(wave_size=64) - src0 = [0x1000 + i for i in range(64)] - src1 = [0x2000 + i for i in range(64)] - wave.init_vgpr(0, src0) - wave.init_vgpr(1, src1) - wave.set_exec(MASK64) - - # Low half VCC: 0x55555555 (even lanes true) - # High half VCC: 0xAAAAAAAA (odd lanes true) - vcc64 = 0x55555555 | (0xAAAAAAAA << 32) - wave.set_vcc(vcc64) - wave.execute_v_cndmask_e32(dst_v=2, src0="v0", src1="v1") - - expected = [] - for lane in range(64): - c = (vcc64 >> lane) & 1 - expected.append(src1[lane] if c else src0[lane]) - self.assertEqual(wave.get_vgpr(2), expected) - - def test_wave64_half_disabled_wave(self) -> None: - """Wave64 with low-half active only, or high-half active only.""" - wave = CndmaskWaveInterpreter(wave_size=64) - bg = [0x9900 + i for i in range(64)] - wave.init_vgpr(2, bg) - wave.init_vgpr(0, 0x11) - wave.init_vgpr(1, 0x22) - wave.set_vcc(MASK64) - - # Low half active only - wave.set_exec(0x00000000FFFFFFFF) - wave.execute_v_cndmask_e32(dst_v=2, src0="v0", src1="v1") - res = wave.get_vgpr(2) - self.assertEqual(res[:32], [0x22] * 32) - self.assertEqual(res[32:], bg[32:]) - - # Reset and high half active only - wave.init_vgpr(2, bg) - wave.set_exec(0xFFFFFFFF00000000) - wave.execute_v_cndmask_e32(dst_v=2, src0="v0", src1="v1") - res = wave.get_vgpr(2) - self.assertEqual(res[:32], bg[:32]) - self.assertEqual(res[32:], [0x22] * 32) - - def test_wave64_boundary_lanes(self) -> None: - """Verifies boundary lanes 31 (end of low half) and 32 (start of high half).""" - wave = CndmaskWaveInterpreter(wave_size=64) - src0 = [1000 + i for i in range(64)] - src1 = [2000 + i for i in range(64)] - wave.init_vgpr(0, src0) - wave.init_vgpr(1, src1) - wave.set_exec(MASK64) - - # Only lane 31 and 32 set in VCC - wave.set_vcc((1 << 31) | (1 << 32)) - wave.execute_v_cndmask_e32(dst_v=2, src0="v0", src1="v1") - res = wave.get_vgpr(2) - for i in range(64): - if i in (31, 32): - self.assertEqual(res[i], src1[i]) - else: - self.assertEqual(res[i], src0[i]) - - def test_wave64_randomized_divergence_stress(self) -> None: - """50 pseudo-random 64-bit masks cross-checked against reference oracle.""" - rng = random.Random(20261122) - for trial in range(50): - with self.subTest(trial=trial): - wave = CndmaskWaveInterpreter(wave_size=64) - src0 = [rng.getrandbits(32) for _ in range(64)] - src1 = [rng.getrandbits(32) for _ in range(64)] - prev = [rng.getrandbits(32) for _ in range(64)] - cond = rng.getrandbits(64) - exec_m = rng.getrandbits(64) - - wave.init_vgpr(0, src0) - wave.init_vgpr(1, src1) - wave.init_vgpr(2, prev) - wave.set_vcc(cond) - wave.set_exec(exec_m) - - wave.execute_v_cndmask_e32(dst_v=2, src0="v0", src1="v1") - oracle_expected = ref_cndmask_wave(src0, src1, cond, exec_m, prev, wave_size=64) - self.assertEqual(wave.get_vgpr(2), oracle_expected) - - -class TestCndmaskE64Encoding(unittest.TestCase): - """Verifies v_cndmask_b32_e64 with explicit condition masks (SGPRs).""" - - def test_e64_with_sgpr_scalar_mask(self) -> None: - """e64 encoding reading condition mask from SGPR s4.""" - wave = CndmaskWaveInterpreter(wave_size=32) - src0 = [0x10 + i for i in range(32)] - src1 = [0x50 + i for i in range(32)] - wave.init_vgpr(0, src0) - wave.init_vgpr(1, src1) - wave.set_exec(0xFFFFFFFF) - - # Condition mask in s4 = 0x00FF00FF - wave.sgprs[4] = 0x00FF00FF - # VCC intentionally set to 0 to verify s4 is used, not VCC - wave.set_vcc(0x00000000) - - wave.execute_v_cndmask_e64(dst_v=2, src0="v0", src1="v1", cond_src="s4") - expected = [src1[i] if ((0x00FF00FF >> i) & 1) else src0[i] for i in range(32)] - self.assertEqual(wave.get_vgpr(2), expected) - self.assertEqual(wave.vcc, 0, "VCC was modified by e64 reading SGPR") - - def test_e64_distinct_condition_registers(self) -> None: - """Multiple e64 instructions using different SGPRs in sequence.""" - wave = CndmaskWaveInterpreter(wave_size=32) - wave.init_vgpr(0, 10) - wave.init_vgpr(1, 20) - wave.init_vgpr(2, 30) - wave.set_exec(0xFFFFFFFF) - - wave.sgprs[4] = 0x0000FFFF - wave.sgprs[6] = 0xFFFF0000 - - wave.execute_v_cndmask_e64(dst_v=10, src0="v0", src1="v1", cond_src="s4") - wave.execute_v_cndmask_e64(dst_v=11, src0="v0", src1="v2", cond_src="s6") - - exp10 = [20 if i < 16 else 10 for i in range(32)] - exp11 = [30 if i >= 16 else 10 for i in range(32)] - self.assertEqual(wave.get_vgpr(10), exp10) - self.assertEqual(wave.get_vgpr(11), exp11) - - -class TestCndmaskSpirvTranslation(unittest.TestCase): - """Verifies end-to-end SPIR-V translation and execution via rdna2spirv & spirv_mini_interp.""" - - def test_spirv_e32_true_false_selection(self) -> None: - """Translates v_cndmask_b32_e32 with true and false conditions.""" - # True condition (vcc_lo = 1): selects src1 - lines_true = [ - "v_mov_b32 v10, 42", - "v_mov_b32 v11, 99", - "v_cmp_eq_u32_e32 vcc_lo, 1, 1", - "v_cndmask_b32_e32 v0, v10, v11, vcc_lo", - "v_mov_b32 v1, 0", - "v_mov_b32 v2, 0", - "v_mov_b32 v3, 0", - ] - out_true = run_synthetic_ps(lines_true) - self.assertEqual(out_true[0], 99) - - # False condition (vcc_lo = 0): selects src0 - lines_false = [ - "v_mov_b32 v10, 42", - "v_mov_b32 v11, 99", - "v_cmp_eq_u32_e32 vcc_lo, 1, 0", - "v_cndmask_b32_e32 v0, v10, v11, vcc_lo", - "v_mov_b32 v1, 0", - "v_mov_b32 v2, 0", - "v_mov_b32 v3, 0", - ] - out_false = run_synthetic_ps(lines_false) - self.assertEqual(out_false[0], 42) - - def test_spirv_e64_sgpr_condition_mask(self) -> None: - """Translates v_cndmask_b32_e64 with SGPR condition mask.""" - lines = [ - "s_mov_b32 s4, 1", - "s_mov_b32 s6, 0", - "v_mov_b32 v10, 100", - "v_mov_b32 v11, 200", - "v_cndmask_b32_e64 v0, v10, v11, s4", - "v_cndmask_b32_e64 v1, v10, v11, s6", - "v_mov_b32 v2, 0", - "v_mov_b32 v3, 0", - ] - out = run_synthetic_ps(lines) - self.assertEqual(out[0], 200, "e64 with s4=1 should select src1") - self.assertEqual(out[1], 100, "e64 with s6=0 should select src0") - - def test_spirv_immediate_sources(self) -> None: - """v_cndmask_b32 with immediate values 0 and 1 (carry extraction idiom).""" - lines = [ - "v_cmp_gt_u32_e32 vcc_lo, 5, 3", - "v_cndmask_b32_e32 v0, 0, 1, vcc_lo", - "v_cmp_gt_u32_e32 vcc_lo, 3, 5", - "v_cndmask_b32_e32 v1, 0, 1, vcc_lo", - "v_mov_b32 v2, 0", - "v_mov_b32 v3, 0", - ] - out = run_synthetic_ps(lines) - self.assertEqual(out[0], 1) - self.assertEqual(out[1], 0) - - def test_spirv_multiplexer_min_max(self) -> None: - """Constructs branchless min and max using v_cmp and v_cndmask.""" - test_pairs = [(10, 20), (50, 30), (0, 0xFFFFFFFF), (0x7FFFFFFF, 0x80000000)] - for a, b in test_pairs: - lines = [ - f"v_mov_b32 v10, {a:#x}", - f"v_mov_b32 v11, {b:#x}", - "v_cmp_lt_u32_e32 vcc_lo, v10, v11", - # min: if a < b select a (src1) else b (src0) -> v_cndmask_b32 v0, b, a - "v_cndmask_b32_e32 v0, v11, v10, vcc_lo", - # max: if a < b select b (src1) else a (src0) -> v_cndmask_b32 v1, a, b - "v_cndmask_b32_e32 v1, v10, v11, vcc_lo", - "v_mov_b32 v2, 0", - "v_mov_b32 v3, 0", - ] - out = run_synthetic_ps(lines) - expected_min = min(a, b) - expected_max = max(a, b) - self.assertEqual(out[0], expected_min) - self.assertEqual(out[1], expected_max) - - def test_spirv_cascaded_ternary_select(self) -> None: - """Chained conditional moves selecting between 3 candidate values.""" - # if x == 1 -> 100; elif x == 2 -> 200; else -> 300 - for x_val, expected in ((1, 100), (2, 200), (3, 300), (0, 300)): - lines = [ - f"v_mov_b32 v10, {x_val}", - # default = 300 - "v_mov_b32 v20, 300", - # check x == 2 -> select 200 else default - "v_cmp_eq_u32_e32 vcc_lo, 2, v10", - "v_cndmask_b32_e32 v21, v20, 200, vcc_lo", - # check x == 1 -> select 100 else v21 - "v_cmp_eq_u32_e32 vcc_lo, 1, v10", - "v_cndmask_b32_e32 v0, v21, 100, vcc_lo", - "v_mov_b32 v1, 0", - "v_mov_b32 v2, 0", - "v_mov_b32 v3, 0", - ] - out = run_synthetic_ps(lines) - self.assertEqual(out[0], expected) - - -class TestCndmaskNegativeControls(unittest.TestCase): - """Negative controls and sensitivity verification against corruptions.""" - - def test_vcc_inversion_mutation(self) -> None: - """Inverting VCC must invert selection for every differing lane.""" - wave = CndmaskWaveInterpreter(wave_size=32) - s0 = [0x100 + i for i in range(32)] - s1 = [0x200 + i for i in range(32)] - wave.init_vgpr(0, s0) - wave.init_vgpr(1, s1) - wave.set_exec(0xFFFFFFFF) - - vcc = 0x12345678 - wave.set_vcc(vcc) - wave.execute_v_cndmask_e32(dst_v=2, src0="v0", src1="v1") - res_normal = wave.get_vgpr(2) - - wave.set_vcc(~vcc & MASK32) - wave.execute_v_cndmask_e32(dst_v=3, src0="v0", src1="v1") - res_inverted = wave.get_vgpr(3) - - self.assertNotEqual(res_normal, res_inverted) - for i in range(32): - self.assertNotEqual(res_normal[i], res_inverted[i]) - - def test_exec_clearing_prevents_updates(self) -> None: - """Clearing EXEC mask ensures destination is completely unmodified.""" - wave = CndmaskWaveInterpreter(wave_size=32) - init_val = [0xFEED0000 + i for i in range(32)] - wave.init_vgpr(2, init_val) - wave.init_vgpr(0, 1) - wave.init_vgpr(1, 2) - wave.set_vcc(0xFFFFFFFF) - wave.set_exec(0x00000000) # corrupt EXEC to 0 - - wave.execute_v_cndmask_e32(dst_v=2, src0="v0", src1="v1") - self.assertEqual(wave.get_vgpr(2), init_val) - - def test_single_bit_flip_sensitivity(self) -> None: - """Flipping exactly one bit in VCC alters strictly and only that lane.""" - wave = CndmaskWaveInterpreter(wave_size=32) - s0 = [10 + i for i in range(32)] - s1 = [90 + i for i in range(32)] - wave.init_vgpr(0, s0) - wave.init_vgpr(1, s1) - wave.set_exec(0xFFFFFFFF) - - base_vcc = 0x55555555 - wave.set_vcc(base_vcc) - wave.execute_v_cndmask_e32(dst_v=2, src0="v0", src1="v1") - base_res = wave.get_vgpr(2) - - for flip_lane in range(32): - flipped_vcc = base_vcc ^ (1 << flip_lane) - wave.set_vcc(flipped_vcc) - wave.execute_v_cndmask_e32(dst_v=3, src0="v0", src1="v1") - flipped_res = wave.get_vgpr(3) - - for lane in range(32): - if lane == flip_lane: - self.assertNotEqual(flipped_res[lane], base_res[lane]) - else: - self.assertEqual(flipped_res[lane], base_res[lane]) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_cndmask_sign_mods.py b/tests/semantic/test_cndmask_sign_mods.py deleted file mode 100644 index a5bdd673d..000000000 --- a/tests/semantic/test_cndmask_sign_mods.py +++ /dev/null @@ -1,117 +0,0 @@ -"""v_cndmask_b32_e64 source modifiers are sign-bit moves, not float ops. - -v_cndmask_b32 only moves bits, so a VOP3 `abs` on a source clears bit 31 and `neg` flips it (abs first), exactly, for -every bit pattern: a signalling NaN stays signalling and a denormal isn't flushed. The translator used to read the -sources through `Gen.modify` (SPIR-V `FAbs`/`OpFNegate`), which may quiet a signalling NaN; the mini interpreter does, -so `-v1` of 0x7F800001 came out 0xFFC00001. The same input modifiers on `v_cmp_class_f32` are measured as sign-bit moves -on gfx1036 (docs/design.md, "Floating-point class compare"). - -Hand-written assembly only (no game files): each case loads a word into v1, selects it with a modifier through -v_cndmask_b32_e64, and exports it. Runs on the CPU through tests/semantic/spirv_mini_interp.py; with spirv-val on PATH -the module is validated too. - - python -m unittest discover -s tests/semantic -p test_cndmask_sign_mods.py -""" -from __future__ import annotations - -import os -import shutil -import struct -import subprocess -import sys -import tempfile -import unittest -import warnings - -HERE = os.path.dirname(os.path.abspath(__file__)) -ROOT = os.path.dirname(os.path.dirname(HERE)) -TOOLS_DIR = os.environ.get("LEONIDA_TOOLS_DIR") or os.path.join(ROOT, "tools") -for path in (TOOLS_DIR, HERE): - if path not in sys.path: - sys.path.insert(0, path) - -import rdna2spirv # noqa: E402 -import spirv_mini_interp as si # noqa: E402 - -STUB_DXBC = b"DXBC" + bytes(24) + struct.pack(" bool: - """s_cbranch_scc0: taken iff the SCC register bit is zero.""" - return (scc & 1) == 0 - - -def eval_scc1(scc: int) -> bool: - """s_cbranch_scc1: taken iff the SCC register bit is one.""" - return (scc & 1) != 0 - - -def compute_branch_target(pc: int, simm16: int, insn_len: int = 4) -> int: - """Calculates branch destination address given branch instruction PC and 16-bit signed displacement. - - Displacement arithmetic: - next_pc = pc + insn_len - target_pc = next_pc + 4 * simm16 - """ - v = simm16 & 0xFFFF - signed_imm = v - 0x10000 if (v & 0x8000) else v - next_pc = pc + insn_len - return next_pc + 4 * signed_imm - - -def evaluate_scc_branch_condition(op: str, scc: int) -> bool: - """Evaluates whether an SCC conditional branch is taken given the SCC register value.""" - if op == "s_cbranch_scc0": - return eval_scc0(scc) - if op == "s_cbranch_scc1": - return eval_scc1(scc) - raise ValueError(f"Unknown branch opcode: {op}") - - -# ----------------------------------------------------------------------------- -# 2. Pure Python Reference Scalar Interpreter -# ----------------------------------------------------------------------------- - -class ScalarInterpreter: - """Simulates RDNA2 scalar execution across basic blocks. - - Models: - - 106 SGPRs (s0..s105). - - 1-bit SCC condition flag. - - Scalar comparisons (s_cmp_*), bit tests (s_bitcmp*), scalar ALU (s_and, s_or, s_add, s_sub, s_min, s_max). - - Conditional and unconditional scalar branching (s_cbranch_scc0, s_cbranch_scc1, s_branch). - - Basic block dispatch, program counter, and step limit detection. - """ - - def __init__(self, initial_scc: int = 0): - self.sgprs = [0] * 106 - self.scc = initial_scc & 1 - self.trace: list[str] = [] - - def set_sgpr(self, reg: int | str, val: int): - r = self._resolve_reg(reg) - self.sgprs[r] = val & MASK32 - - def get_sgpr(self, reg: int | str) -> int: - r = self._resolve_reg(reg) - return self.sgprs[r] & MASK32 - - def _resolve_reg(self, reg: int | str) -> int: - if isinstance(reg, str): - if reg.startswith("s") and reg[1:].isdigit(): - return int(reg[1:]) - raise ValueError(f"Invalid register name: {reg}") - return int(reg) - - def _resolve_src(self, operand: int | str, default_reg: bool = False) -> int: - if isinstance(operand, str): - if operand.startswith("s") and operand[1:].isdigit(): - return self.get_sgpr(int(operand[1:])) - raise ValueError(f"Unknown symbolic operand: {operand}") - if default_reg: - return self.get_sgpr(operand) - return operand & MASK32 - - def run_program(self, blocks: dict[str, list], start_block: str, max_steps: int = 5000): - cur: str | None = start_block - steps = 0 - self.trace = [] - - while cur is not None and steps < max_steps: - steps += 1 - self.trace.append(cur) - block = blocks.get(cur) - if block is None: - raise ValueError(f"Unknown block label: {cur}") - - next_block: str | None = None - for ins in block: - if isinstance(ins, str): - next_block = ins - break - - op = ins[0] - args = ins[1:] - - if op == "s_endpgm": - return - - elif op == "s_branch": - next_block = args[0] - break - - elif op == "s_cbranch_scc0": - target = args[0] - if eval_scc0(self.scc): - next_block = target - break - - elif op == "s_cbranch_scc1": - target = args[0] - if eval_scc1(self.scc): - next_block = target - break - - elif op == "s_mov_b32": - dst_s, val = args - r = self._resolve_reg(dst_s) - v = self._resolve_src(val, default_reg=False) - self.set_sgpr(r, v) - - elif op == "s_cmp_eq_u32": - s0, s1 = args - v0 = self._resolve_src(s0, default_reg=True) - v1 = self._resolve_src(s1, default_reg=False) - self.scc = 1 if (v0 == v1) else 0 - - elif op == "s_cmp_lg_u32": - s0, s1 = args - v0 = self._resolve_src(s0, default_reg=True) - v1 = self._resolve_src(s1, default_reg=False) - self.scc = 1 if (v0 != v1) else 0 - - elif op == "s_cmp_gt_u32": - s0, s1 = args - v0 = self._resolve_src(s0, default_reg=True) - v1 = self._resolve_src(s1, default_reg=False) - self.scc = 1 if (v0 > v1) else 0 - - elif op == "s_cmp_ge_u32": - s0, s1 = args - v0 = self._resolve_src(s0, default_reg=True) - v1 = self._resolve_src(s1, default_reg=False) - self.scc = 1 if (v0 >= v1) else 0 - - elif op == "s_cmp_lt_u32": - s0, s1 = args - v0 = self._resolve_src(s0, default_reg=True) - v1 = self._resolve_src(s1, default_reg=False) - self.scc = 1 if (v0 < v1) else 0 - - elif op == "s_cmp_le_u32": - s0, s1 = args - v0 = self._resolve_src(s0, default_reg=True) - v1 = self._resolve_src(s1, default_reg=False) - self.scc = 1 if (v0 <= v1) else 0 - - elif op == "s_bitcmp0_b32": - s0, s1 = args - v0 = self._resolve_src(s0, default_reg=True) - bit_idx = self._resolve_src(s1, default_reg=False) & 31 - bit = (v0 >> bit_idx) & 1 - self.scc = 1 if (bit == 0) else 0 - - elif op == "s_bitcmp1_b32": - s0, s1 = args - v0 = self._resolve_src(s0, default_reg=True) - bit_idx = self._resolve_src(s1, default_reg=False) & 31 - bit = (v0 >> bit_idx) & 1 - self.scc = 1 if (bit == 1) else 0 - - elif op == "s_and_b32": - dst_s, s0, s1 = args - r = self._resolve_reg(dst_s) - v0 = self._resolve_src(s0, default_reg=True) - v1 = self._resolve_src(s1, default_reg=False) - res = (v0 & v1) & MASK32 - self.set_sgpr(r, res) - self.scc = 1 if (res != 0) else 0 - - elif op == "s_or_b32": - dst_s, s0, s1 = args - r = self._resolve_reg(dst_s) - v0 = self._resolve_src(s0, default_reg=True) - v1 = self._resolve_src(s1, default_reg=False) - res = (v0 | v1) & MASK32 - self.set_sgpr(r, res) - self.scc = 1 if (res != 0) else 0 - - elif op == "s_add_u32": - dst_s, s0, s1 = args - r = self._resolve_reg(dst_s) - v0 = self._resolve_src(s0, default_reg=True) - v1 = self._resolve_src(s1, default_reg=False) - s = v0 + v1 - self.set_sgpr(r, s & MASK32) - self.scc = 1 if (s > MASK32) else 0 - - elif op == "s_sub_u32": - dst_s, s0, s1 = args - r = self._resolve_reg(dst_s) - v0 = self._resolve_src(s0, default_reg=True) - v1 = self._resolve_src(s1, default_reg=False) - res = (v0 - v1) & MASK32 - self.set_sgpr(r, res) - self.scc = 1 if (v0 < v1) else 0 - - elif op == "s_min_u32": - dst_s, s0, s1 = args - r = self._resolve_reg(dst_s) - v0 = self._resolve_src(s0, default_reg=True) - v1 = self._resolve_src(s1, default_reg=False) - if v0 < v1: - self.set_sgpr(r, v0) - self.scc = 1 - else: - self.set_sgpr(r, v1) - self.scc = 0 - - else: - raise NotImplementedError(f"Unsupported instruction: {op}") - - if next_block is None: - cur = block[-1] if isinstance(block[-1], str) else None - else: - cur = next_block - - if steps >= max_steps: - raise BranchExecutionLimitError(f"Execution step limit {max_steps} exceeded: potential infinite loop") - - -# ----------------------------------------------------------------------------- -# 3. SPIR-V Structured Control Flow Mini-Interpreter -# ----------------------------------------------------------------------------- - -class StructuredBranchInterp: - """Interprets structured SPIR-V assembly emitted by tools/rdna2spirv.py for shaders with branches.""" - - def __init__(self, spvasm: str): - self.spvasm = spvasm - self.types: dict[str, tuple] = {} - self.constants: dict[str, int | float | bool | tuple | list] = {} - self.ptr_types: dict[str, tuple[str, str]] = {} - self.var_class: dict[str, str] = {} - self.var_box: dict[str, list] = {} - self.pointers: dict[str, tuple] = {} - self.outputs: list[str] = [] - self.insns: list[tuple[str | None, str, list[str], str]] = [] - self.labels: dict[str, int] = {} - self._parse() - - def zero(self, name: str): - k = self.types[name] - if k[0] == "int": - return 0 - if k[0] == "float": - return 0.0 - if k[0] == "bool": - return False - if k[0] == "vec": - return tuple(self.zero(k[1]) for _ in range(k[2])) - if k[0] == "arr": - return [self.zero(k[1]) for _ in range(k[2])] - return 0 - - def _parse(self): - in_body = False - idx = 0 - for raw in self.spvasm.splitlines(): - line = raw.strip() - if not line: - continue - m = _LINE.match(line) - if not m: - continue - res, op, rest = m.groups() - a = rest.split() - if in_body: - if op == "OpLabel": - self.labels[res] = idx - self.insns.append((res, op, a, line)) - idx += 1 - continue - if op == "OpFunction": - in_body = True - continue - if op == "OpTypeInt": - self.types[res] = ("int", int(a[0]), int(a[1])) - elif op == "OpTypeFloat": - self.types[res] = ("float",) - elif op == "OpTypeBool": - self.types[res] = ("bool",) - elif op == "OpTypeVector": - self.types[res] = ("vec", a[0], int(a[1])) - elif op == "OpTypeArray": - self.types[res] = ("arr", a[0], int(self.constants[a[1]])) - elif op == "OpTypeStruct": - self.types[res] = ("struct", a) - elif op == "OpTypePointer": - self.ptr_types[res] = (a[0], a[1]) - elif op == "OpConstant": - k = self.types[a[0]] - if k[0] == "int": - self.constants[res] = int(a[1], 0) & MASK32 - elif k[0] == "float": - self.constants[res] = float(a[1]) - elif op == "OpConstantTrue": - self.constants[res] = True - elif op == "OpConstantFalse": - self.constants[res] = False - elif op == "OpConstantNull": - self.constants[res] = self.zero(a[0]) - elif op == "OpVariable": - cls, pointee = self.ptr_types[a[0]] - self.var_class[res] = cls - if cls == "Output": - self.outputs.append(res) - self.var_box[res] = [self.zero(pointee)] - self.pointers[res] = (self.var_box[res], 0) - elif cls == "PushConstant": - self.var_box[res] = [None] - self.pointers[res] = ("pc", None) - - def run(self, max_steps: int = 20000) -> dict[str, tuple]: - values = dict(self.constants) - var_box = dict(self.var_box) - pointers = dict(self.pointers) - - def val(x: str): - if x in values: - return values[x] - raise UnsupportedConstruct(f"Undefined identifier {x}") - - def deref(p): - box, i = p - return box[i] - - ip = 0 - steps = 0 - while ip < len(self.insns): - steps += 1 - if steps > max_steps: - raise BranchExecutionLimitError(f"Step limit {max_steps} exceeded: possible infinite loop") - res, op, a, _ = self.insns[ip] - if op in _IGNORED or op == "OpLabel": - ip += 1 - continue - if op in ("OpReturn", "OpFunctionEnd"): - break - if op == "OpBranch": - target_label = a[0] - if target_label not in self.labels: - raise UnsupportedConstruct(f"OpBranch target {target_label} not found") - ip = self.labels[target_label] - continue - if op == "OpBranchConditional": - cond = val(a[0]) - if not isinstance(cond, bool): - raise UnsupportedConstruct("OpBranchConditional requires a boolean condition") - target_label = a[1] if cond else a[2] - if target_label not in self.labels: - raise UnsupportedConstruct(f"OpBranchConditional target {target_label} not found") - ip = self.labels[target_label] - continue - if op == "OpVariable": - cls, pointee = self.ptr_types[a[0]] - init = values[a[2]] if len(a) > 2 else self.zero(pointee) - var_box[res] = [list(init) if isinstance(init, list) else init] - pointers[res] = (var_box[res], 0) - elif op == "OpAccessChain": - base = a[1] - if self.var_class.get(base) == "PushConstant": - pointers[res] = ("pc", None) - else: - if base not in pointers: - raise UnsupportedConstruct(f"OpAccessChain on invalid base {base}") - p = pointers[base] - for idx_id in a[2:]: - idx = val(idx_id) - container = deref(p) - if not isinstance(container, (list, tuple)) or not (0 <= idx < len(container)): - raise UnsupportedConstruct(f"OpAccessChain out of bounds index {idx}") - p = (container, idx) - pointers[res] = p - elif op == "OpLoad": - if a[1] not in pointers: - raise UnsupportedConstruct(f"OpLoad from invalid pointer {a[1]}") - p = pointers[a[1]] - if p[0] == "pc": - values[res] = 0 - else: - v = deref(p) - values[res] = list(v) if isinstance(v, list) else v - elif op == "OpStore": - if a[0] not in pointers: - raise UnsupportedConstruct(f"OpStore to invalid pointer {a[0]}") - p = pointers[a[0]] - if p[0] == "pc": - raise UnsupportedConstruct("Store to PushConstant rejected") - p[0][p[1]] = val(a[1]) - elif op == "OpIEqual": - values[res] = (val(a[1]) == val(a[2])) - elif op == "OpINotEqual": - values[res] = (val(a[1]) != val(a[2])) - elif op == "OpUGreaterThan": - values[res] = (val(a[1]) & MASK32) > (val(a[2]) & MASK32) - elif op == "OpULessThan": - values[res] = (val(a[1]) & MASK32) < (val(a[2]) & MASK32) - elif op == "OpUGreaterThanEqual": - values[res] = (val(a[1]) & MASK32) >= (val(a[2]) & MASK32) - elif op == "OpULessThanEqual": - values[res] = (val(a[1]) & MASK32) <= (val(a[2]) & MASK32) - elif op == "OpLogicalNot": - c = val(a[1]) - if not isinstance(c, bool): - raise UnsupportedConstruct("OpLogicalNot operand must be bool") - values[res] = not c - elif op == "OpLogicalAnd": - values[res] = bool(val(a[1]) and val(a[2])) - elif op == "OpLogicalOr": - values[res] = bool(val(a[1]) or val(a[2])) - elif op == "OpSelect": - cond = val(a[1]) - if not isinstance(cond, bool): - raise UnsupportedConstruct("OpSelect condition must be bool") - values[res] = val(a[2]) if cond else val(a[3]) - elif op == "OpCopyObject": - values[res] = val(a[1]) - elif op == "OpBitcast": - values[res] = val(a[1]) - elif op == "OpCompositeConstruct": - values[res] = tuple(val(x) for x in a[1:]) - elif op == "OpCompositeExtract": - values[res] = val(a[1])[int(a[2])] - elif op == "OpIAdd": - values[res] = (val(a[1]) + val(a[2])) & MASK32 - elif op == "OpISub": - values[res] = (val(a[1]) - val(a[2])) & MASK32 - elif op == "OpIAddCarry": - x_val = val(a[1]) & MASK32 - y_val = val(a[2]) & MASK32 - total = x_val + y_val - values[res] = (total & MASK32, 1 if total > MASK32 else 0) - elif op == "OpISubBorrow": - x_val = val(a[1]) & MASK32 - y_val = val(a[2]) & MASK32 - diff = (x_val - y_val) & MASK32 - values[res] = (diff, 1 if x_val < y_val else 0) - elif op == "OpBitwiseAnd": - values[res] = (val(a[1]) & val(a[2])) & MASK32 - elif op == "OpBitwiseOr": - values[res] = (val(a[1]) | val(a[2])) & MASK32 - elif op == "OpBitwiseXor": - values[res] = (val(a[1]) ^ val(a[2])) & MASK32 - elif op == "OpShiftLeftLogical": - sh = val(a[2]) - if sh >= 32: - raise UnsupportedConstruct("Shift left >= 32 is undefined in SPIR-V") - values[res] = (val(a[1]) << sh) & MASK32 - elif op == "OpShiftRightLogical": - sh = val(a[2]) - if sh >= 32: - raise UnsupportedConstruct("Shift right >= 32 is undefined in SPIR-V") - values[res] = (val(a[1]) >> sh) & MASK32 - else: - raise UnsupportedConstruct(f"Opcode not modelled: {op}") - ip += 1 - - result = {} - for out in self.outputs: - v = var_box[out][0] - result[out] = tuple(v if isinstance(v, tuple) else (v,)) - return result - - -def translate_disassembly_lines(lines: list[str], shader_name: str = "ps_cf_test") -> str: - """Translates assembly lines into structured SPIR-V assembly text, suppressing ResourceWarnings.""" - with tempfile.TemporaryDirectory() as tmp: - dis = os.path.join(tmp, "disasm") - os.mkdir(dis) - src_path = os.path.join(dis, f"{shader_name}.s") - with open(src_path, "w", encoding="utf-8") as f: - f.write("\n".join(lines) + "\n") - dxbc_path = os.path.join(tmp, f"{shader_name}.dxbc") - with open(dxbc_path, "wb") as f: - f.write(STUB_DXBC) - with warnings.catch_warnings(): - warnings.simplefilter("ignore", ResourceWarning) - result = rdna2spirv.translate(src_path) - gc.collect() - return result - - -# ----------------------------------------------------------------------------- -# Test Suite 1: Reference Truth Tables & Displacement Arithmetic -# ----------------------------------------------------------------------------- - -class TestBranchDisplacementAndConditionReference(unittest.TestCase): - """Verifies RDNA2 signed two's-complement displacement arithmetic and SCC branch conditions.""" - - def test_scc0_and_scc1_duality(self): - """s_cbranch_scc0 and s_cbranch_scc1 must be strict logical complements across all SCC states.""" - test_states = [0, 1, 2, 3, 0x80000000, 0xFFFFFFFF] - for scc in test_states: - c0 = eval_scc0(scc) - c1 = eval_scc1(scc) - with self.subTest(scc=hex(scc)): - self.assertNotEqual(c0, c1, "scc0 and scc1 must never have identical outcome") - self.assertEqual(c0, (scc & 1) == 0) - self.assertEqual(c1, (scc & 1) == 1) - - def test_forward_displacement_calculation(self): - """Displacement target_pc = next_pc + 4 * simm16 for forward jumps.""" - self.assertEqual(compute_branch_target(pc=8, simm16=2), 20) - self.assertEqual(compute_branch_target(pc=0, simm16=1), 8) - self.assertEqual(compute_branch_target(pc=100, simm16=10), 144) - - def test_backward_displacement_calculation(self): - """Displacement target_pc = next_pc + 4 * simm16 for backward jumps (negative simm16).""" - self.assertEqual(compute_branch_target(pc=20, simm16=-4), 8) - self.assertEqual(compute_branch_target(pc=20, simm16=0xFFFC), 8) - self.assertEqual(compute_branch_target(pc=16, simm16=-1), 16) # branch to self - - def test_zero_displacement_calculation(self): - """simm16 = 0 branches to next_pc (effectively a no-op branch).""" - self.assertEqual(compute_branch_target(pc=12, simm16=0), 16) - - def test_displacement_limits(self): - """Boundary verification at 16-bit signed integer limits (-32768 to 32767 dwords).""" - # Maximum positive jump (+32767 dwords) - self.assertEqual(compute_branch_target(pc=0, simm16=0x7FFF), 4 + 4 * 32767) - # Maximum negative jump (-32768 dwords) - self.assertEqual(compute_branch_target(pc=200000, simm16=0x8000), 200004 - 4 * 32768) - - def test_evaluate_scc_branch_condition_dispatches(self): - self.assertTrue(evaluate_scc_branch_condition("s_cbranch_scc0", 0)) - self.assertFalse(evaluate_scc_branch_condition("s_cbranch_scc0", 1)) - self.assertFalse(evaluate_scc_branch_condition("s_cbranch_scc1", 0)) - self.assertTrue(evaluate_scc_branch_condition("s_cbranch_scc1", 1)) - - with self.assertRaises(ValueError): - evaluate_scc_branch_condition("s_cbranch_vccz", 0) - - -# ----------------------------------------------------------------------------- -# Test Suite 2: Reference Scalar Interpreter (ISA Level) -# ----------------------------------------------------------------------------- - -class TestScalarInterpreterExecution(unittest.TestCase): - """Verifies control flow graphs executed on the pure Python scalar interpreter.""" - - def test_if_then_skip_pattern_scc0(self): - """s_cbranch_scc0 skips the then-block when SCC == 0; executes it when SCC == 1.""" - interp_skip = ScalarInterpreter() - interp_skip.run_program({ - "entry": [ - ("s_mov_b32", 0, 50), - ("s_mov_b32", 1, 10), - ("s_cmp_eq_u32", 0, 999), # 50 == 999 -> False -> SCC = 0 - ("s_cbranch_scc0", "exit"), - "then_block", - ], - "then_block": [ - ("s_mov_b32", 1, 55), - "exit", - ], - "exit": [ - ("s_endpgm",), - ], - }, "entry") - self.assertEqual(interp_skip.trace, ["entry", "exit"]) - self.assertEqual(interp_skip.get_sgpr(1), 10) - - interp_exec = ScalarInterpreter() - interp_exec.run_program({ - "entry": [ - ("s_mov_b32", 0, 50), - ("s_mov_b32", 1, 10), - ("s_cmp_eq_u32", 0, 50), # 50 == 50 -> True -> SCC = 1 - ("s_cbranch_scc0", "exit"), - "then_block", - ], - "then_block": [ - ("s_mov_b32", 1, 55), - "exit", - ], - "exit": [ - ("s_endpgm",), - ], - }, "entry") - self.assertEqual(interp_exec.trace, ["entry", "then_block", "exit"]) - self.assertEqual(interp_exec.get_sgpr(1), 55) - - def test_if_then_skip_pattern_scc1(self): - """s_cbranch_scc1 skips the then-block when SCC == 1; executes it when SCC == 0.""" - interp_skip = ScalarInterpreter() - interp_skip.run_program({ - "entry": [ - ("s_mov_b32", 0, 50), - ("s_mov_b32", 1, 10), - ("s_cmp_eq_u32", 0, 50), # 50 == 50 -> True -> SCC = 1 - ("s_cbranch_scc1", "exit"), - "then_block", - ], - "then_block": [ - ("s_mov_b32", 1, 55), - "exit", - ], - "exit": [ - ("s_endpgm",), - ], - }, "entry") - self.assertEqual(interp_skip.trace, ["entry", "exit"]) - self.assertEqual(interp_skip.get_sgpr(1), 10) - - def test_diamond_if_then_else(self): - """Symmetric diamond pattern: selects exactly one branch based on comparison.""" - def run_diamond(val: int) -> int: - interp = ScalarInterpreter() - interp.run_program({ - "entry": [ - ("s_mov_b32", 0, val), - ("s_cmp_eq_u32", 0, 7), - ("s_cbranch_scc0", "else_block"), - "then_block", - ], - "then_block": [ - ("s_mov_b32", 1, 100), - ("s_branch", "join"), - ], - "else_block": [ - ("s_mov_b32", 1, 200), - ("s_branch", "join"), - ], - "join": [ - ("s_endpgm",), - ], - }, "entry") - return interp.get_sgpr(1) - - self.assertEqual(run_diamond(7), 100) - self.assertEqual(run_diamond(42), 200) - - def test_countdown_loop_execution(self): - """Iterative loop using backward s_cbranch_scc0 terminating when counter reaches 0.""" - interp = ScalarInterpreter() - interp.run_program({ - "entry": [ - ("s_mov_b32", 0, 6), # loop count = 6 - ("s_mov_b32", 1, 0), # accumulator - "loop_body", - ], - "loop_body": [ - ("s_add_u32", 1, 1, 10), # acc += 10 - ("s_sub_u32", 0, 0, 1), # counter -= 1 - ("s_cmp_eq_u32", 0, 0), # counter == 0 ? SCC=1 : SCC=0 - ("s_cbranch_scc0", "loop_body"), - "exit", - ], - "exit": [ - ("s_endpgm",), - ], - }, "entry") - # 6 iterations * 10 = 60 - self.assertEqual(interp.get_sgpr(1), 60) - self.assertEqual(interp.get_sgpr(0), 0) - self.assertEqual(interp.trace.count("loop_body"), 6) - - def test_branch_on_all_comparison_conditions(self): - """Verifies conditional branches following all standard scalar comparison operations.""" - comparisons = [ - ("s_cmp_eq_u32", 10, 10, True), - ("s_cmp_eq_u32", 10, 20, False), - ("s_cmp_lg_u32", 10, 20, True), - ("s_cmp_lg_u32", 10, 10, False), - ("s_cmp_gt_u32", 20, 10, True), - ("s_cmp_gt_u32", 10, 20, False), - ("s_cmp_ge_u32", 10, 10, True), - ("s_cmp_ge_u32", 5, 10, False), - ("s_cmp_lt_u32", 5, 10, True), - ("s_cmp_lt_u32", 10, 5, False), - ("s_cmp_le_u32", 10, 10, True), - ("s_cmp_le_u32", 15, 10, False), - ] - for cmp_op, val0, val1, expected_true in comparisons: - with self.subTest(cmp_op=cmp_op, val0=val0, val1=val1): - interp = ScalarInterpreter() - interp.run_program({ - "entry": [ - ("s_mov_b32", 0, val0), - (cmp_op, 0, val1), - ("s_cbranch_scc1", "true_target"), - "false_target", - ], - "true_target": [ - ("s_mov_b32", 2, 1), - ("s_endpgm",), - ], - "false_target": [ - ("s_mov_b32", 2, 0), - ("s_endpgm",), - ], - }, "entry") - expected_dest = "true_target" if expected_true else "false_target" - self.assertIn(expected_dest, interp.trace) - self.assertEqual(interp.get_sgpr(2), 1 if expected_true else 0) - - def test_branch_on_bitcmp_conditions(self): - """Verifies branching following bitcmp0 (bit==0 -> SCC=1) and bitcmp1 (bit==1 -> SCC=1).""" - interp = ScalarInterpreter() - interp.run_program({ - "entry": [ - ("s_mov_b32", 0, 0b00000100), # bit 2 is 1, bit 3 is 0 - ("s_bitcmp1_b32", 0, 2), # bit 2 is 1 -> SCC=1 - ("s_cbranch_scc1", "bit2_is_set"), - "fail", - ], - "bit2_is_set": [ - ("s_bitcmp0_b32", 0, 3), # bit 3 is 0 -> SCC=1 - ("s_cbranch_scc1", "success"), - "fail", - ], - "fail": [ - ("s_mov_b32", 1, 999), - ("s_endpgm",), - ], - "success": [ - ("s_mov_b32", 1, 777), - ("s_endpgm",), - ], - }, "entry") - self.assertEqual(interp.trace, ["entry", "bit2_is_set", "success"]) - self.assertEqual(interp.get_sgpr(1), 777) - - def test_branch_on_alu_carry_and_borrow(self): - """s_add_u32 sets SCC on overflow carry; s_sub_u32 sets SCC on borrow.""" - # 1. Overflow carry: 0xFFFFFFFF + 1 -> sum 0, carry 1 -> s_cbranch_scc1 taken - interp_carry = ScalarInterpreter() - interp_carry.run_program({ - "entry": [ - ("s_mov_b32", 0, 0xFFFFFFFF), - ("s_add_u32", 1, 0, 1), - ("s_cbranch_scc1", "overflow_taken"), - "overflow_missed", - ], - "overflow_taken": [ - ("s_mov_b32", 2, 42), - ("s_endpgm",), - ], - "overflow_missed": [ - ("s_mov_b32", 2, 0), - ("s_endpgm",), - ], - }, "entry") - self.assertEqual(interp_carry.trace, ["entry", "overflow_taken"]) - self.assertEqual(interp_carry.get_sgpr(2), 42) - - # 2. Borrow: 5 - 10 -> borrow 1 -> s_cbranch_scc1 taken - interp_borrow = ScalarInterpreter() - interp_borrow.run_program({ - "entry": [ - ("s_mov_b32", 0, 5), - ("s_sub_u32", 1, 0, 10), - ("s_cbranch_scc1", "borrow_taken"), - "borrow_missed", - ], - "borrow_taken": [ - ("s_mov_b32", 2, 84), - ("s_endpgm",), - ], - "borrow_missed": [ - ("s_mov_b32", 2, 0), - ("s_endpgm",), - ], - }, "entry") - self.assertEqual(interp_borrow.trace, ["entry", "borrow_taken"]) - self.assertEqual(interp_borrow.get_sgpr(2), 84) - - def test_branch_on_bitwise_logic_scc(self): - """s_and_b32 and s_or_b32 set SCC to 1 iff the result is non-zero.""" - interp = ScalarInterpreter() - interp.run_program({ - "entry": [ - ("s_mov_b32", 0, 0x0F0F), - ("s_and_b32", 1, 0, 0xF0F0), # 0x0F0F & 0xF0F0 = 0 -> SCC=0 - ("s_cbranch_scc0", "is_zero"), - "not_zero", - ], - "is_zero": [ - ("s_or_b32", 2, 0, 0x0001), # 0x0F0F | 0x0001 = 0x0F0F != 0 -> SCC=1 - ("s_cbranch_scc1", "is_nonzero"), - "fail", - ], - "not_zero": [ - ("s_mov_b32", 3, 111), - ("s_endpgm",), - ], - "fail": [ - ("s_mov_b32", 3, 222), - ("s_endpgm",), - ], - "is_nonzero": [ - ("s_mov_b32", 3, 333), - ("s_endpgm",), - ], - }, "entry") - self.assertEqual(interp.trace, ["entry", "is_zero", "is_nonzero"]) - self.assertEqual(interp.get_sgpr(3), 333) - - def test_infinite_loop_step_limit_error(self): - """Runaway loops trigger BranchExecutionLimitError instead of hanging forever.""" - interp = ScalarInterpreter() - with self.assertRaises(BranchExecutionLimitError): - interp.run_program({ - "entry": [ - ("s_branch", "entry"), - ], - }, "entry", max_steps=100) - - -# ----------------------------------------------------------------------------- -# Test Suite 3: SPIR-V Translator Emission Verification -# ----------------------------------------------------------------------------- - -class TestTranslatorSpirvEmission(unittest.TestCase): - """Verifies that tools/rdna2spirv.py emits expected instructions for s_cbranch_scc0/1.""" - - def test_branch_condition_scc0_emission(self): - """s_cbranch_scc0 emits OpLoad %scc and OpIEqual against zero without subgroup voting.""" - g = rdna2spirv.Gen("ps") - cond = rdna2spirv.branch_condition(g, "s_cbranch_scc0") - - self.assertFalse(g.uses_vote, "s_cbranch_scc0 must not require subgroup voting") - - body_text = "\n".join(g.body) - self.assertIn("OpLoad %uint %scc", body_text) - self.assertIn(f"{cond} = OpIEqual %bool", body_text) - self.assertNotIn("OpGroupNonUniformAny", body_text) - - def test_branch_condition_scc1_emission(self): - """s_cbranch_scc1 emits OpLoad %scc and OpINotEqual against zero without subgroup voting.""" - g = rdna2spirv.Gen("ps") - cond = rdna2spirv.branch_condition(g, "s_cbranch_scc1") - - self.assertFalse(g.uses_vote, "s_cbranch_scc1 must not require subgroup voting") - - body_text = "\n".join(g.body) - self.assertIn("OpLoad %uint %scc", body_text) - self.assertIn(f"{cond} = OpINotEqual %bool", body_text) - self.assertNotIn("OpGroupNonUniformAny", body_text) - - def test_branches_membership(self): - """Verifies that s_cbranch_scc0 and s_cbranch_scc1 are registered in rdna2spirv.BRANCHES.""" - self.assertIn("s_cbranch_scc0", rdna2spirv.BRANCHES) - self.assertIn("s_cbranch_scc1", rdna2spirv.BRANCHES) - - -# ----------------------------------------------------------------------------- -# Test Suite 4: End-to-End SPIR-V Execution (StructuredBranchInterp) -# ----------------------------------------------------------------------------- - -class TestStructuredSpirvIfThenExecution(unittest.TestCase): - """Tests forward conditional skipping with translated SPIR-V assembly.""" - - def _build_if_then_shader(self, branch_op: str, s0_val: int, compare_val: int) -> list[str]: - enc_branch = "0x01,0x00,0x84,0xbf" if branch_op == "s_cbranch_scc0" else "0x01,0x00,0x85,0xbf" - return [ - "; ps_if_then test", - f"\ts_mov_b32 s0, {s0_val} ; encoding: [0x80,0x03,0x80,0xbe]", - "\ts_mov_b32 s1, 10 ; encoding: [0x8a,0x03,0x81,0xbe]", - f"\ts_cmp_eq_u32 s0, {compare_val} ; encoding: [0x80,0x00,0x0c,0xbf]", - f"\t{branch_op} 1 ; encoding: [{enc_branch}]", - "\ts_mov_b32 s1, 55 ; encoding: [0xb7,0x03,0x81,0xbe]", - "\tv_mov_b32 v0, s1 ; encoding: [0x01,0x02,0x00,0x7e]", - "\texp mrt0 v0, v0, v0, v0 done vm ; encoding: [0x0f,0x08,0x00,0xf8,0x00,0x00,0x00,0x00]", - "\ts_endpgm ; encoding: [0x00,0x00,0x81,0xbf]", - ] - - def test_s_cbranch_scc0_taken_skips_assignment(self): - # s0 = 2 != 1 -> SCC = 0 -> s_cbranch_scc0 IS taken, skipping s1=55. Result = 10. - spv = translate_disassembly_lines(self._build_if_then_shader("s_cbranch_scc0", s0_val=2, compare_val=1)) - self.assertIn("OpSelectionMerge", spv) - res = StructuredBranchInterp(spv).run()["%out_mrt0"] - self.assertEqual(res, (10, 10, 10, 10)) - - def test_s_cbranch_scc0_not_taken_executes_assignment(self): - # s0 = 1 == 1 -> SCC = 1 -> s_cbranch_scc0 NOT taken, executing s1=55. Result = 55. - spv = translate_disassembly_lines(self._build_if_then_shader("s_cbranch_scc0", s0_val=1, compare_val=1)) - res = StructuredBranchInterp(spv).run()["%out_mrt0"] - self.assertEqual(res, (55, 55, 55, 55)) - - def test_s_cbranch_scc1_taken_skips_assignment(self): - # s0 = 1 == 1 -> SCC = 1 -> s_cbranch_scc1 IS taken, skipping s1=55. Result = 10. - spv = translate_disassembly_lines(self._build_if_then_shader("s_cbranch_scc1", s0_val=1, compare_val=1)) - res = StructuredBranchInterp(spv).run()["%out_mrt0"] - self.assertEqual(res, (10, 10, 10, 10)) - - def test_s_cbranch_scc1_not_taken_executes_assignment(self): - # s0 = 2 != 1 -> SCC = 0 -> s_cbranch_scc1 NOT taken, executing s1=55. Result = 55. - spv = translate_disassembly_lines(self._build_if_then_shader("s_cbranch_scc1", s0_val=2, compare_val=1)) - res = StructuredBranchInterp(spv).run()["%out_mrt0"] - self.assertEqual(res, (55, 55, 55, 55)) - - -class TestStructuredSpirvDiamondExecution(unittest.TestCase): - """Tests symmetric if-then-else diamond control flow where exactly one branch executes.""" - - def _build_diamond_shader(self, s0_val: int) -> list[str]: - return [ - "; ps_diamond test", - f"\ts_mov_b32 s0, {s0_val} ; encoding: [0x80,0x03,0x80,0xbe]", - "\ts_cmp_eq_u32 s0, 7 ; encoding: [0x87,0x00,0x0c,0xbf]", - "\ts_cbranch_scc0 2 ; encoding: [0x02,0x00,0x84,0xbf]", - "\ts_mov_b32 s1, 100 ; encoding: [0xe4,0x03,0x81,0xbe]", - "\ts_branch 1 ; encoding: [0x01,0x00,0x82,0xbf]", - "\ts_mov_b32 s1, 200 ; encoding: [0xc8,0x03,0x81,0xbe]", - "\tv_mov_b32 v0, s1 ; encoding: [0x01,0x02,0x00,0x7e]", - "\texp mrt0 v0, v0, v0, v0 done vm ; encoding: [0x0f,0x08,0x00,0xf8,0x00,0x00,0x00,0x00]", - "\ts_endpgm ; encoding: [0x00,0x00,0x81,0xbf]", - ] - - def test_diamond_then_branch_taken(self): - spv = translate_disassembly_lines(self._build_diamond_shader(s0_val=7)) - res = StructuredBranchInterp(spv).run()["%out_mrt0"] - self.assertEqual(res, (100, 100, 100, 100)) - - def test_diamond_else_branch_taken(self): - spv = translate_disassembly_lines(self._build_diamond_shader(s0_val=9)) - res = StructuredBranchInterp(spv).run()["%out_mrt0"] - self.assertEqual(res, (200, 200, 200, 200)) - - -class TestStructuredSpirvLoopExecution(unittest.TestCase): - """Tests structured loop emission and execution with backward conditional branches.""" - - def _build_loop_shader(self, iterations: int, step: int) -> list[str]: - return [ - "; ps_loop test", - f"\ts_mov_b32 s0, {iterations} ; encoding: [0x83,0x03,0x80,0xbe]", - "\ts_mov_b32 s1, 0 ; encoding: [0x80,0x03,0x81,0xbe]", - f"\ts_add_u32 s1, s1, {step} ; encoding: [0x85,0x01,0x01,0x80]", - "\ts_sub_u32 s0, s0, 1 ; encoding: [0x81,0x00,0x00,0x81]", - "\ts_cmp_eq_u32 s0, 0 ; encoding: [0x80,0x00,0x0c,0xbf]", - "\ts_cbranch_scc0 -4 ; encoding: [0xfc,0xff,0x84,0xbf]", - "\tv_mov_b32 v0, s1 ; encoding: [0x01,0x02,0x00,0x7e]", - "\texp mrt0 v0, v0, v0, v0 done vm ; encoding: [0x0f,0x08,0x00,0xf8,0x00,0x00,0x00,0x00]", - "\ts_endpgm ; encoding: [0x00,0x00,0x81,0xbf]", - ] - - def test_single_iteration_loop(self): - spv = translate_disassembly_lines(self._build_loop_shader(iterations=1, step=25)) - self.assertIn("OpLoopMerge", spv) - res = StructuredBranchInterp(spv).run()["%out_mrt0"] - self.assertEqual(res, (25, 25, 25, 25)) - - def test_multi_iteration_loop(self): - spv = translate_disassembly_lines(self._build_loop_shader(iterations=5, step=7)) - res = StructuredBranchInterp(spv).run()["%out_mrt0"] - self.assertEqual(res, (35, 35, 35, 35)) - - def test_larger_iteration_loop(self): - spv = translate_disassembly_lines(self._build_loop_shader(iterations=12, step=10)) - res = StructuredBranchInterp(spv).run()["%out_mrt0"] - self.assertEqual(res, (120, 120, 120, 120)) - - -class TestStructuredSpirvNestedBranchControlFlow(unittest.TestCase): - """Tests 2-level nested conditional branching covering all (outer, inner) permutations.""" - - def _build_nested_shader(self, outer_val: int, inner_val: int) -> list[str]: - # Block layout and displacements: - # 0: s_mov s0, outer_val - # 4: s_mov s2, inner_val - # 8: s_cmp_eq_u32 s0, 1 - # 12: s_cbranch_scc0 6 -> next_pc=16 + 24 = pc 40 (outer else) - # 16: s_cmp_eq_u32 s2, 1 - # 20: s_cbranch_scc0 2 -> next_pc=24 + 8 = pc 32 (inner else) - # 24: s_mov s1, 11 - # 28: s_branch 7 -> next_pc=32 + 28 = pc 60 (exit) - # 32: s_mov s1, 10 - # 36: s_branch 5 -> next_pc=40 + 20 = pc 60 (exit) - # 40: s_cmp_eq_u32 s2, 1 - # 44: s_cbranch_scc0 2 -> next_pc=48 + 8 = pc 56 (outer else inner else) - # 48: s_mov s1, 21 - # 52: s_branch 1 -> next_pc=56 + 4 = pc 60 (exit) - # 56: s_mov s1, 20 - # 60: v_mov v0, s1 - # 64: exp mrt0 v0, v0, v0, v0 done vm - # 72: s_endpgm - return [ - "; ps_nested test", - f"\ts_mov_b32 s0, {outer_val} ; encoding: [0x80,0x03,0x80,0xbe]", - f"\ts_mov_b32 s2, {inner_val} ; encoding: [0x80,0x03,0x82,0xbe]", - "\ts_cmp_eq_u32 s0, 1 ; encoding: [0x81,0x00,0x0c,0xbf]", - "\ts_cbranch_scc0 6 ; encoding: [0x06,0x00,0x84,0xbf]", - "\ts_cmp_eq_u32 s2, 1 ; encoding: [0x81,0x02,0x0c,0xbf]", - "\ts_cbranch_scc0 2 ; encoding: [0x02,0x00,0x84,0xbf]", - "\ts_mov_b32 s1, 11 ; encoding: [0x8b,0x03,0x81,0xbe]", - "\ts_branch 7 ; encoding: [0x07,0x00,0x82,0xbf]", - "\ts_mov_b32 s1, 10 ; encoding: [0x8a,0x03,0x81,0xbe]", - "\ts_branch 5 ; encoding: [0x05,0x00,0x82,0xbf]", - "\ts_cmp_eq_u32 s2, 1 ; encoding: [0x81,0x02,0x0c,0xbf]", - "\ts_cbranch_scc0 2 ; encoding: [0x02,0x00,0x84,0xbf]", - "\ts_mov_b32 s1, 21 ; encoding: [0x95,0x03,0x81,0xbe]", - "\ts_branch 1 ; encoding: [0x01,0x00,0x82,0xbf]", - "\ts_mov_b32 s1, 20 ; encoding: [0x94,0x03,0x81,0xbe]", - "\tv_mov_b32 v0, s1 ; encoding: [0x01,0x02,0x00,0x7e]", - "\texp mrt0 v0, v0, v0, v0 done vm ; encoding: [0x0f,0x08,0x00,0xf8,0x00,0x00,0x00,0x00]", - "\ts_endpgm ; encoding: [0x00,0x00,0x81,0xbf]", - ] - - def test_all_nested_permutations(self): - cases = [ - (1, 1, 11), - (1, 0, 10), - (0, 1, 21), - (0, 0, 20), - ] - for outer, inner, expected in cases: - with self.subTest(outer=outer, inner=inner): - spv = translate_disassembly_lines(self._build_nested_shader(outer, inner)) - res = StructuredBranchInterp(spv).run()["%out_mrt0"] - self.assertEqual(res, (expected, expected, expected, expected)) - - -class TestMultiWayDispatchLadder(unittest.TestCase): - """Tests a chained multi-way dispatch ladder (switch emulation via conditional branches).""" - - def _build_dispatch_shader(self, selector: int) -> list[str]: - # Case 0: s1 = 100 - # Case 1: s1 = 200 - # Case 2: s1 = 300 - # Default: s1 = 400 - return [ - "; ps_dispatch test", - f"\ts_mov_b32 s0, {selector} ; encoding: [0x80,0x03,0x80,0xbe]", - # check case 0: - "\ts_cmp_eq_u32 s0, 0 ; encoding: [0x80,0x00,0x0c,0xbf]", - "\ts_cbranch_scc1 6 ; encoding: [0x06,0x00,0x85,0xbf]", # jump to case 0 body - # check case 1: - "\ts_cmp_eq_u32 s0, 1 ; encoding: [0x81,0x00,0x0c,0xbf]", - "\ts_cbranch_scc1 6 ; encoding: [0x06,0x00,0x85,0xbf]", # jump to case 1 body - # check case 2: - "\ts_cmp_eq_u32 s0, 2 ; encoding: [0x82,0x00,0x0c,0xbf]", - "\ts_cbranch_scc1 6 ; encoding: [0x06,0x00,0x85,0xbf]", # jump to case 2 body - # default: - "\ts_mov_b32 s1, 400 ; encoding: [0xc0,0x03,0x81,0xbe]", - "\ts_branch 5 ; encoding: [0x05,0x00,0x82,0xbf]", - # case 0 body: - "\ts_mov_b32 s1, 100 ; encoding: [0xe4,0x03,0x81,0xbe]", - "\ts_branch 3 ; encoding: [0x03,0x00,0x82,0xbf]", - # case 1 body: - "\ts_mov_b32 s1, 200 ; encoding: [0xc8,0x03,0x81,0xbe]", - "\ts_branch 1 ; encoding: [0x01,0x00,0x82,0xbf]", - # case 2 body: - "\ts_mov_b32 s1, 300 ; encoding: [0xac,0x03,0x81,0xbe]", - # exit: - "\tv_mov_b32 v0, s1 ; encoding: [0x01,0x02,0x00,0x7e]", - "\texp mrt0 v0, v0, v0, v0 done vm ; encoding: [0x0f,0x08,0x00,0xf8,0x00,0x00,0x00,0x00]", - "\ts_endpgm ; encoding: [0x00,0x00,0x81,0xbf]", - ] - - def test_dispatch_ladder_cases(self): - cases = [ - (0, 100), - (1, 200), - (2, 300), - (3, 400), - (99, 400), - ] - for sel, expected in cases: - with self.subTest(selector=sel): - spv = translate_disassembly_lines(self._build_dispatch_shader(sel)) - res = StructuredBranchInterp(spv).run()["%out_mrt0"] - self.assertEqual(res, (expected, expected, expected, expected)) - - -# ----------------------------------------------------------------------------- -# Test Suite 5: Negative Controls & Mutation Sensitivity -# ----------------------------------------------------------------------------- - -class TestNegativeControlsAndFaultDetection(unittest.TestCase): - """Negative controls and fault rejection: verifies sabotaged logic is detected.""" - - def test_inverted_branch_condition_is_detected(self): - """Sabotaging OpIEqual to OpINotEqual flips the branch outcome.""" - spv = translate_disassembly_lines([ - "; ps_fault test", - "\ts_mov_b32 s0, 7 ; encoding: [0x87,0x03,0x80,0xbe]", - "\ts_cmp_eq_u32 s0, 7 ; encoding: [0x87,0x00,0x0c,0xbf]", - "\ts_cbranch_scc0 2 ; encoding: [0x02,0x00,0x84,0xbf]", - "\ts_mov_b32 s1, 100 ; encoding: [0xe4,0x03,0x81,0xbe]", - "\ts_branch 1 ; encoding: [0x01,0x00,0x82,0xbf]", - "\ts_mov_b32 s1, 200 ; encoding: [0xc8,0x03,0x81,0xbe]", - "\tv_mov_b32 v0, s1 ; encoding: [0x01,0x02,0x00,0x7e]", - "\texp mrt0 v0, v0, v0, v0 done vm ; encoding: [0x0f,0x08,0x00,0xf8,0x00,0x00,0x00,0x00]", - "\ts_endpgm ; encoding: [0x00,0x00,0x81,0xbf]", - ]) - baseline_res = StructuredBranchInterp(spv).run()["%out_mrt0"] - self.assertEqual(baseline_res, (100, 100, 100, 100)) - - # Invert condition by replacing OpIEqual with OpINotEqual - self.assertIn("OpIEqual", spv) - bad_spv = spv.replace("OpIEqual", "OpINotEqual", 1) - bad_res = StructuredBranchInterp(bad_spv).run()["%out_mrt0"] - self.assertNotEqual(bad_res, baseline_res) - self.assertEqual(bad_res, (200, 200, 200, 200)) - - def test_infinite_loop_triggers_limit_error(self): - """Unconditional backward branch to self triggers BranchExecutionLimitError.""" - spv = translate_disassembly_lines([ - "; ps_infinite test", - "\ts_mov_b32 s0, 0 ; encoding: [0x80,0x03,0x80,0xbe]", - "\ts_branch -1 ; encoding: [0xff,0xff,0x82,0xbf]", - "\tv_mov_b32 v0, s0 ; encoding: [0x00,0x02,0x00,0x7e]", - "\texp mrt0 v0, v0, v0, v0 done vm ; encoding: [0x0f,0x08,0x00,0xf8,0x00,0x00,0x00,0x00]", - "\ts_endpgm ; encoding: [0x00,0x00,0x81,0xbf]", - ]) - with self.assertRaises(BranchExecutionLimitError): - StructuredBranchInterp(spv).run(max_steps=500) - - def test_out_of_bounds_branch_target_rejected_by_translator(self): - """Branch displacement landing outside code buffer is rejected with Unsupported.""" - with self.assertRaises(rdna2spirv.Unsupported): - translate_disassembly_lines([ - "; ps_bad_target test", - "\ts_cbranch_scc0 500 ; encoding: [0xf4,0x01,0x84,0xbf]", - "\ts_endpgm ; encoding: [0x00,0x00,0x81,0xbf]", - ]) - - def test_unsupported_branch_construct_rejected_by_interp(self): - """Unrecognized opcode in SPIR-V interpreter raises UnsupportedConstruct.""" - spv = """\ -OpCapability Shader -OpMemoryModel Logical GLSL450 -OpEntryPoint Fragment %main "main" -%void = OpTypeVoid -%fn = OpTypeFunction %void -%main = OpFunction %void None %fn -%entry = OpLabel -OpBranch %nonexistent_label -OpFunctionEnd -""" - with self.assertRaises(UnsupportedConstruct): - StructuredBranchInterp(spv).run() - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_control_flow_exec.py b/tests/semantic/test_control_flow_exec.py deleted file mode 100644 index 1fb0d6791..000000000 --- a/tests/semantic/test_control_flow_exec.py +++ /dev/null @@ -1,532 +0,0 @@ -"""Semantic interpreter tests for whole-wave execution mask branching. - -Tests the ISA semantics and translator emission for: - - s_cbranch_execz: branch if EXEC == 0 (all lanes in the wave are disabled/inactive) - - s_cbranch_execnz: branch if EXEC != 0 (at least one lane in the wave is active) - -Covers: - 1. Pure mathematical reference oracle for Wave32 and Wave64 execution masks. - 2. Multi-lane WaveInterpreter modeling SIMD wave state, vector lane masking, - scalar registers, and whole-wave control flow (skip patterns, loop convergence, - and divergent if-then-else joins). - 3. SPIR-V translation verification via tools/rdna2spirv.py branch_condition(): - subgroup vote emission (OpGroupNonUniformAny with Subgroup scope), - logical negation for execz, and required capability flags. - 4. Invariant and duality verification: execz and execnz are strict complements. - 5. Negative controls / mutation detection: verifies sensitivity to swapped or corrupted - branch conditions. - -Run: - python -I tests/semantic/test_control_flow_exec.py - python -m unittest discover -s tests/semantic -v -""" -import os -import random -import sys -import unittest - -HERE = os.path.dirname(os.path.abspath(__file__)) -ROOT = os.path.dirname(os.path.dirname(HERE)) -TOOLS_DIR = os.environ.get("LEONIDA_TOOLS_DIR") or os.path.join(ROOT, "tools") -if TOOLS_DIR not in sys.path: - sys.path.insert(0, TOOLS_DIR) - -import rdna2spirv # noqa: E402 - - -# ----------------------------------------------------------------------------- -# 1. Reference Semantics (AMD RDNA2 ISA: Scalar ALU & Control Flow) -# ----------------------------------------------------------------------------- - -def eval_execz(exec_mask: int, wave_size: int = 32) -> bool: - """s_cbranch_execz: taken iff the wave execution mask is zero.""" - mask = exec_mask & ((1 << wave_size) - 1) - return mask == 0 - - -def eval_execnz(exec_mask: int, wave_size: int = 32) -> bool: - """s_cbranch_execnz: taken iff the wave execution mask is non-zero.""" - mask = exec_mask & ((1 << wave_size) - 1) - return mask != 0 - - -# ----------------------------------------------------------------------------- -# 2. Multi-Lane Wave Interpreter -# ----------------------------------------------------------------------------- - -class WaveInterpreter: - """Simulates a SIMD wave executing basic blocks with execution mask control flow. - - Models: - - Wave32 (32 lanes) or Wave64 (64 lanes). - - EXEC mask: per-lane active bit controlling vector instructions. - - SGPRs: uniform scalar registers shared across all lanes in the wave. - - VGPRs: vector registers with independent values per lane. - - Whole-wave branches: s_cbranch_execz, s_cbranch_execnz, s_branch. - """ - - def __init__(self, wave_size: int = 32, initial_exec: int = 0xFFFFFFFF): - self.wave_size = wave_size - self.mask_all = (1 << wave_size) - 1 - self.exec_mask = initial_exec & self.mask_all - self.sgprs = [0] * 128 - self.vgprs = [[0] * 256 for _ in range(wave_size)] - self.pc = 0 - self.trace = [] - - def is_lane_active(self, lane: int) -> bool: - return bool((self.exec_mask >> lane) & 1) - - def run_program(self, blocks: dict, start_block: str, max_steps: int = 1000): - """Execute a graph of basic blocks until 's_endpgm' or max_steps reached.""" - cur = start_block - steps = 0 - self.trace = [] - - while cur is not None and steps < max_steps: - steps += 1 - self.trace.append(cur) - block = blocks.get(cur) - if block is None: - raise ValueError(f"Unknown block label: {cur}") - - next_block = None - for ins in block: - if isinstance(ins, str): - next_block = ins - break - - op = ins[0] - args = ins[1:] - - if op == "s_endpgm": - return - - elif op == "s_branch": - next_block = args[0] - break - - elif op == "s_cbranch_execz": - target = args[0] - if self.exec_mask == 0: - next_block = target - break - - elif op == "s_cbranch_execnz": - target = args[0] - if self.exec_mask != 0: - next_block = target - break - - elif op == "s_mov_b32": - dst_s, val = args - self.sgprs[dst_s] = val & 0xFFFFFFFF - - elif op == "s_and_saveexec_b64" or op == "s_and_saveexec_b32": - dst_s, mask = args - # Save current EXEC to scalar register(s) - self.sgprs[dst_s] = self.exec_mask & 0xFFFFFFFF - if self.wave_size == 64 and op.endswith("64"): - self.sgprs[dst_s + 1] = (self.exec_mask >> 32) & 0xFFFFFFFF - # Set EXEC = EXEC & mask - self.exec_mask = (self.exec_mask & mask) & self.mask_all - - elif op == "s_or_exec_b64" or op == "s_or_exec_b32": - mask = args[0] - self.exec_mask = (self.exec_mask | mask) & self.mask_all - - elif op == "s_set_exec": - self.exec_mask = args[0] & self.mask_all - - elif op == "v_mov_b32": - dst_v, val = args - # Vector write: only active lanes are updated - for lane in range(self.wave_size): - if self.is_lane_active(lane): - self.vgprs[lane][dst_v] = val & 0xFFFFFFFF - - elif op == "v_add_u32": - dst_v, src_v, imm = args - for lane in range(self.wave_size): - if self.is_lane_active(lane): - self.vgprs[lane][dst_v] = (self.vgprs[lane][src_v] + imm) & 0xFFFFFFFF - - elif op == "v_dec_u32": - dst_v = args[0] - for lane in range(self.wave_size): - if self.is_lane_active(lane): - curr = self.vgprs[lane][dst_v] - self.vgprs[lane][dst_v] = (curr - 1) & 0xFFFFFFFF if curr > 0 else 0 - - elif op == "v_cmp_gt_u32": - # Generate condition mask: 1 where vgpr[src] > imm - dst_s, src_v, imm = args - cond_mask = 0 - for lane in range(self.wave_size): - if self.vgprs[lane][src_v] > imm: - cond_mask |= (1 << lane) - self.sgprs[dst_s] = cond_mask & 0xFFFFFFFF - if self.wave_size == 64: - self.sgprs[dst_s + 1] = (cond_mask >> 32) & 0xFFFFFFFF - - else: - raise NotImplementedError(f"Unsupported instruction in test interpreter: {op}") - - # If no branch was taken, fall through to block's default successor if given - if next_block is None: - cur = block[-1] if isinstance(block[-1], str) else None - else: - cur = next_block - - if steps >= max_steps: - raise TimeoutError("Execution exceeded max_steps (infinite loop detected)") - - -# ----------------------------------------------------------------------------- -# 3. SPIR-V Subgroup Vote Interpreter -# ----------------------------------------------------------------------------- - -def simulate_spirv_subgroup_branch(op: str, lane_actives: list[bool]) -> bool: - """Interprets the SPIR-V instructions emitted by rdna2spirv for whole-wave branching. - - Emitted sequence: - %lane = OpLoad %bool %active - %any = OpGroupNonUniformAny %bool %c3 %lane - (if execz): %b = OpLogicalNot %bool %any - """ - any_active = any(lane_actives) - - if op == "s_cbranch_execnz": - return any_active - elif op == "s_cbranch_execz": - return not any_active - else: - raise ValueError(f"Unknown branch opcode: {op}") - - -# ----------------------------------------------------------------------------- -# Test Suite -# ----------------------------------------------------------------------------- - -class TestControlFlowExecReference(unittest.TestCase): - """Verifies whole-wave execution mask semantics against ISA definitions.""" - - def test_execz_and_execnz_duality(self): - """execz and execnz must be strict logical complements for every possible mask.""" - test_masks = [ - 0x00000000, - 0xFFFFFFFF, - 0x00000001, - 0x80000000, - 0x55555555, - 0xAAAAAAAA, - 0x0000FFFF, - 0xFFFF0000, - 0x00FF00FF, - 0xFF00FF00, - ] - # All 32 single-bit masks - for bit in range(32): - test_masks.append(1 << bit) - test_masks.append(~(1 << bit) & 0xFFFFFFFF) - - # Deterministic random masks - rng = random.Random(20261121) - for _ in range(100): - test_masks.append(rng.getrandbits(32)) - - for mask in test_masks: - z = eval_execz(mask, wave_size=32) - nz = eval_execnz(mask, wave_size=32) - with self.subTest(mask=hex(mask)): - self.assertNotEqual(z, nz, "execz and execnz must never have identical outcome") - self.assertEqual(z, mask == 0) - self.assertEqual(nz, mask != 0) - - def test_wave64_execution_masks(self): - """Verifies 64-bit execution masks in Wave64 mode.""" - mask64_all = 0xFFFFFFFFFFFFFFFF - self.assertTrue(eval_execz(0, wave_size=64)) - self.assertFalse(eval_execnz(0, wave_size=64)) - - self.assertFalse(eval_execz(mask64_all, wave_size=64)) - self.assertTrue(eval_execnz(mask64_all, wave_size=64)) - - # Check MSB in Wave64 (lane 63) - lane63 = 1 << 63 - self.assertFalse(eval_execz(lane63, wave_size=64)) - self.assertTrue(eval_execnz(lane63, wave_size=64)) - - # High 32 bits only / Low 32 bits only - self.assertFalse(eval_execz(0xFFFFFFFF00000000, wave_size=64)) - self.assertTrue(eval_execnz(0xFFFFFFFF00000000, wave_size=64)) - self.assertFalse(eval_execz(0x00000000FFFFFFFF, wave_size=64)) - self.assertTrue(eval_execnz(0x00000000FFFFFFFF, wave_size=64)) - - # Truncation boundary check: bits beyond 63 are ignored by wave_size=64 - self.assertTrue(eval_execz(1 << 64, wave_size=64)) - - -class TestWaveInterpreterExecutionFlow(unittest.TestCase): - """Verifies execution mask control flow in multi-lane simulated programs.""" - - def test_skip_pattern_execz_taken_when_all_lanes_inactive(self): - """When condition is false for all lanes, s_cbranch_execz skips the then block.""" - blocks = { - "entry": [ - ("v_cmp_gt_u32", 4, 0, 100), - ("s_and_saveexec_b32", 6, 0), # s4 is 0 - ("s_cbranch_execz", "skip"), - "then_block", - ], - "then_block": [ - ("v_mov_b32", 1, 999), - ("s_branch", "skip"), - ], - "skip": [ - ("s_endpgm",), - ], - } - - interp = WaveInterpreter(wave_size=32, initial_exec=0xFFFFFFFF) - for lane in range(32): - interp.vgprs[lane][0] = 50 - interp.vgprs[lane][1] = 10 - - interp.run_program(blocks, "entry") - - self.assertEqual(interp.trace, ["entry", "skip"]) - for lane in range(32): - self.assertEqual(interp.vgprs[lane][1], 10) - - def test_skip_pattern_execz_not_taken_when_one_lane_active(self): - """When at least one lane satisfies condition, s_cbranch_execz does NOT branch.""" - interp = WaveInterpreter(wave_size=32, initial_exec=0xFFFFFFFF) - for lane in range(32): - interp.vgprs[lane][0] = 50 - interp.vgprs[lane][1] = 10 - interp.vgprs[7][0] = 150 # only lane 7 satisfies condition - - cond_mask = 1 << 7 - blocks = { - "entry": [ - ("s_and_saveexec_b32", 6, cond_mask), - ("s_cbranch_execz", "skip"), - "then_block", - ], - "then_block": [ - ("v_mov_b32", 1, 999), - ("s_branch", "skip"), - ], - "skip": [ - ("s_endpgm",), - ], - } - - interp.run_program(blocks, "entry") - - self.assertEqual(interp.trace, ["entry", "then_block", "skip"]) - for lane in range(32): - expected = 999 if lane == 7 else 10 - self.assertEqual(interp.vgprs[lane][1], expected) - - def test_divergent_loop_termination_execnz(self): - """s_cbranch_execnz loops while any lane is active, terminating when all lanes finish.""" - wave_size = 32 - interp = WaveInterpreter(wave_size=wave_size, initial_exec=0xFFFFFFFF) - for lane in range(wave_size): - interp.vgprs[lane][0] = lane if lane <= 7 else 0 # countdown counter in v0 - interp.vgprs[lane][1] = 0 # accumulator in v1 - - blocks = { - "entry": [ - ("v_cmp_gt_u32", 4, 0, 0), - ("s_and_saveexec_b32", 6, 0), - ("s_cbranch_execz", "exit"), - "loop_body", - ], - "loop_body": [ - ("v_add_u32", 1, 1, 1), - ("v_dec_u32", 0), - ("v_cmp_gt_u32", 4, 0, 0), - ], - } - - initial_active = 0 - for lane in range(wave_size): - if interp.vgprs[lane][0] > 0: - initial_active |= (1 << lane) - interp.exec_mask = initial_active - - iterations = 0 - max_loop = 50 - while interp.exec_mask != 0 and iterations < max_loop: - iterations += 1 - for ins in blocks["loop_body"]: - op, *args = ins - if op == "v_add_u32": - d, s, imm = args - for l in range(wave_size): - if interp.is_lane_active(l): - interp.vgprs[l][d] += imm - elif op == "v_dec_u32": - d = args[0] - for l in range(wave_size): - if interp.is_lane_active(l): - interp.vgprs[l][d] -= 1 - elif op == "v_cmp_gt_u32": - d, s, imm = args - cond = 0 - for l in range(wave_size): - if interp.vgprs[l][s] > imm: - cond |= (1 << l) - interp.exec_mask &= cond - - self.assertEqual(iterations, 7) - self.assertEqual(interp.exec_mask, 0) - for lane in range(wave_size): - expected_acc = lane if lane <= 7 else 0 - self.assertEqual(interp.vgprs[lane][1], expected_acc) - - def test_divergent_if_else_reconvergence(self): - """Simulates structured if-then-else with s_cbranch_execz guards on both branches.""" - wave_size = 32 - interp = WaveInterpreter(wave_size=wave_size, initial_exec=0xFFFFFFFF) - for lane in range(wave_size): - interp.vgprs[lane][0] = lane % 2 - interp.vgprs[lane][2] = 0 - - even_mask = 0x55555555 - odd_mask = 0xAAAAAAAA - - blocks = { - "entry": [ - ("s_mov_b32", 10, interp.exec_mask), - ("s_and_saveexec_b32", 12, even_mask), - ("s_cbranch_execz", "else_block"), - "then_block", - ], - "then_block": [ - ("v_add_u32", 2, 2, 100), - ("s_branch", "else_block"), - ], - "else_block": [ - ("s_set_exec", odd_mask), - ("s_cbranch_execz", "join"), - "else_body", - ], - "else_body": [ - ("v_add_u32", 2, 2, 200), - ("s_branch", "join"), - ], - "join": [ - ("s_mov_b32", 14, 0x1234), - ("s_set_exec", 0xFFFFFFFF), - ("s_endpgm",), - ], - } - - interp.run_program(blocks, "entry") - - self.assertEqual(interp.trace, ["entry", "then_block", "else_block", "else_body", "join"]) - for lane in range(wave_size): - expected = 100 if (lane % 2 == 0) else 200 - self.assertEqual(interp.vgprs[lane][2], expected, f"Mismatch at lane {lane}") - - -class TestTranslatorSpirvEmission(unittest.TestCase): - """Verifies that tools/rdna2spirv.py emits correct subgroup vote constructs.""" - - def test_branch_condition_execz_emission(self): - """s_cbranch_execz must emit OpGroupNonUniformAny with logical NOT.""" - g = rdna2spirv.Gen("ps") - cond = rdna2spirv.branch_condition(g, "s_cbranch_execz") - - self.assertTrue(g.uses_vote, "s_cbranch_execz must set uses_vote = True") - - body_text = "\n".join(g.body) - self.assertIn("OpLoad %bool %active", body_text) - self.assertIn("OpGroupNonUniformBallot %v4uint_bal %c3", body_text) - self.assertIn("%c20", body_text) # select the ballot word for this wave32 pixel half - self.assertIn("OpINotEqual %bool", body_text) - self.assertIn(f"{cond} = OpLogicalNot %bool", body_text) - - def test_branch_condition_execnz_emission(self): - """s_cbranch_execnz must emit OpGroupNonUniformAny without logical NOT.""" - g = rdna2spirv.Gen("ps") - cond = rdna2spirv.branch_condition(g, "s_cbranch_execnz") - - self.assertTrue(g.uses_vote, "s_cbranch_execnz must set uses_vote = True") - - body_text = "\n".join(g.body) - self.assertIn("OpLoad %bool %active", body_text) - self.assertIn("OpGroupNonUniformBallot %v4uint_bal %c3", body_text) - self.assertIn("%c20", body_text) # select the ballot word for this wave32 pixel half - self.assertIn("OpINotEqual %bool", body_text) - self.assertIn(f"{cond} = OpCopyObject %bool", body_text) - self.assertNotIn("OpLogicalNot", body_text) - - def test_spirv_subgroup_simulation_matches_isa_reference(self): - """Simulated SPIR-V subgroup vote instructions match eval_execz/eval_execnz.""" - test_masks = [ - 0x00000000, - 0xFFFFFFFF, - 0x00000001, - 0x80000000, - 0x0000FFFF, - 0x55555555, - ] - rng = random.Random(42) - test_masks.extend(rng.getrandbits(32) for _ in range(50)) - - for mask in test_masks: - lane_actives = [bool((mask >> bit) & 1) for bit in range(32)] - - sim_z = simulate_spirv_subgroup_branch("s_cbranch_execz", lane_actives) - sim_nz = simulate_spirv_subgroup_branch("s_cbranch_execnz", lane_actives) - - ref_z = eval_execz(mask, wave_size=32) - ref_nz = eval_execnz(mask, wave_size=32) - - self.assertEqual(sim_z, ref_z, f"execz mismatch for mask {hex(mask)}") - self.assertEqual(sim_nz, ref_nz, f"execnz mismatch for mask {hex(mask)}") - - def test_required_capabilities_for_vote(self): - """Modules using s_cbranch_execz/execnz require GroupNonUniform and GroupNonUniformVote.""" - g = rdna2spirv.Gen("ps") - rdna2spirv.branch_condition(g, "s_cbranch_execz") - asm = rdna2spirv.assemble(g) - caps = rdna2spirv.shader_meta(g, asm)["capabilities"] - self.assertIn("GroupNonUniform", caps) - self.assertIn("GroupNonUniformVote", caps) - - -class TestNegativeControlsAndMutations(unittest.TestCase): - """Ensures test assertions are sensitive to erroneous or inverted implementations.""" - - def test_unnegated_execz_fails_detection(self): - """If s_cbranch_execz omits the OpLogicalNot, it behaves as execnz and must fail.""" - def sabotaged_eval_execz(mask: int) -> bool: - return mask != 0 - - self.assertNotEqual(sabotaged_eval_execz(0), eval_execz(0)) - self.assertNotEqual(sabotaged_eval_execz(0xFFFFFFFF), eval_execz(0xFFFFFFFF)) - - def test_all_reduction_instead_of_any_fails_detection(self): - """If whole-wave active check uses 'All' instead of 'Any', partially active waves fail.""" - def all_active(mask: int, wave_size: int = 32) -> bool: - return (mask & ((1 << wave_size) - 1)) == ((1 << wave_size) - 1) - - partial_mask = 0x00000001 - self.assertTrue(eval_execnz(partial_mask)) - self.assertFalse(all_active(partial_mask)) - - def test_branches_membership(self): - """Verifies that s_cbranch_execz and s_cbranch_execnz are registered in BRANCHES.""" - self.assertIn("s_cbranch_execz", rdna2spirv.BRANCHES) - self.assertIn("s_cbranch_execnz", rdna2spirv.BRANCHES) - self.assertNotIn("s_cbranch_nonexistent", rdna2spirv.BRANCHES) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_control_flow_vcc.py b/tests/semantic/test_control_flow_vcc.py deleted file mode 100644 index c9bbf3052..000000000 --- a/tests/semantic/test_control_flow_vcc.py +++ /dev/null @@ -1,924 +0,0 @@ -"""Semantic interpreter tests for vector condition code (VCC) branching. - -Tests the ISA semantics and SPIR-V translator emission for: - - s_cbranch_vccz: branch if VCC == 0 (all lanes in the wave evaluated condition to false or were inactive) - - s_cbranch_vccnz: branch if VCC != 0 (at least one active lane in the wave evaluated condition to true) - -Covers: - 1. Pure reference semantics for Wave32 (32-bit VCC) and Wave64 (64-bit VCC pair vcc_lo/vcc_hi). - 2. Multi-lane WaveInterpreter modeling SIMD wave state across Wave32 and Wave64: - - Vector condition code generation via vector comparisons (v_cmp_*). - - Carry-out generation into VCC via vector addition with carry (v_add_co_u32). - - Execution mask (EXEC) interaction: inactive lanes write 0 into VCC. - - Direct scalar manipulation of VCC (s_mov_b32/b64, s_and_b32/b64, s_or_b32/b64). - - Skip patterns, divergent loop termination, and structured if-then-else joins. - 3. SPIR-V translator lowering via tools/rdna2spirv.py branch_condition(): - - Verification of per-lane VCC load (%lane = OpINotEqual %bool %vcc 0). - - Whole-subgroup vote emission (OpGroupNonUniformAny with Subgroup scope). - - Logical negation (OpLogicalNot) for s_cbranch_vccz vs unnegated for s_cbranch_vccnz. - - Required SPIR-V capabilities (GroupNonUniform, GroupNonUniformVote). - 4. Simulation oracle matching: verification that the SPIR-V subgroup vote model - matches the hardware ISA reference across deterministic and edge-case bitmasks. - 5. Negative controls and mutation detection: verifies sensitivity to inverted conditions, - All-vs-Any reductions, and high-half masking bugs in Wave64. - -Run: - python -I tests/semantic/test_control_flow_vcc.py - python -m unittest discover -s tests/semantic -p "test_control_flow_vcc.py" -v -""" -from __future__ import annotations - -import os -import random -import sys -import unittest - -HERE = os.path.dirname(os.path.abspath(__file__)) -ROOT = os.path.dirname(os.path.dirname(HERE)) -TOOLS_DIR = os.environ.get("LEONIDA_TOOLS_DIR") or os.path.join(ROOT, "tools") -if TOOLS_DIR not in sys.path: - sys.path.insert(0, TOOLS_DIR) - -import rdna2spirv # noqa: E402 - - -# ----------------------------------------------------------------------------- -# 1. Pure Reference Semantics (AMD RDNA2 ISA: VCC & Scalar Control Flow) -# ----------------------------------------------------------------------------- - -def eval_vccz(vcc_mask: int, wave_size: int = 32) -> bool: - """s_cbranch_vccz: taken iff the wave vector condition code mask is zero.""" - mask = (1 << wave_size) - 1 - return (vcc_mask & mask) == 0 - - -def eval_vccnz(vcc_mask: int, wave_size: int = 32) -> bool: - """s_cbranch_vccnz: taken iff the wave vector condition code mask is non-zero.""" - mask = (1 << wave_size) - 1 - return (vcc_mask & mask) != 0 - - -# ----------------------------------------------------------------------------- -# 2. Multi-Lane Wave Interpreter -# ----------------------------------------------------------------------------- - -class WaveInterpreter: - """Simulates a SIMD wave executing basic blocks with VCC control flow. - - Models: - - Wave32 (32 lanes, 32-bit VCC) or Wave64 (64 lanes, 64-bit VCC). - - EXEC mask: per-lane active bit controlling vector instructions. - - VCC register: Vector Condition Code, updated by v_cmp_* and v_add_co_*. - Crucially, lanes that are inactive in EXEC contribute 0 to VCC. - - SGPRs: uniform scalar registers shared across all lanes. - - VGPRs: vector registers with independent values per lane. - - Control flow instructions: s_cbranch_vccz, s_cbranch_vccnz, s_branch, s_endpgm. - """ - - def __init__( - self, - wave_size: int = 32, - initial_exec: int | None = None, - initial_vcc: int = 0, - ) -> None: - if wave_size not in (32, 64): - raise ValueError(f"Unsupported wave_size: {wave_size}") - self.wave_size = wave_size - self.mask_all = (1 << wave_size) - 1 - self.exec_mask = self.mask_all if initial_exec is None else (initial_exec & self.mask_all) - self.vcc = initial_vcc & self.mask_all - self.sgprs = [0] * 128 - self.vgprs = [[0] * 256 for _ in range(wave_size)] - self.trace: list[str] = [] - - def is_lane_active(self, lane: int) -> bool: - return bool((self.exec_mask >> lane) & 1) - - def is_vcc_lane_set(self, lane: int) -> bool: - return bool((self.vcc >> lane) & 1) - - def run_program(self, blocks: dict[str, list], start_block: str, max_steps: int = 1000) -> None: - """Execute a graph of basic blocks until 's_endpgm' or max_steps reached.""" - cur: str | None = start_block - steps = 0 - self.trace = [] - - while cur is not None and steps < max_steps: - steps += 1 - self.trace.append(cur) - block = blocks.get(cur) - if block is None: - raise ValueError(f"Unknown block label: {cur}") - - next_block: str | None = None - for ins in block: - if isinstance(ins, str): - next_block = ins - break - - op = ins[0] - args = ins[1:] - - if op == "s_endpgm": - return - - elif op == "s_branch": - next_block = args[0] - break - - elif op == "s_cbranch_vccz": - target = args[0] - if eval_vccz(self.vcc, self.wave_size): - next_block = target - break - - elif op == "s_cbranch_vccnz": - target = args[0] - if eval_vccnz(self.vcc, self.wave_size): - next_block = target - break - - elif op == "s_cbranch_execz": - target = args[0] - if (self.exec_mask & self.mask_all) == 0: - next_block = target - break - - elif op == "s_cbranch_execnz": - target = args[0] - if (self.exec_mask & self.mask_all) != 0: - next_block = target - break - - elif op == "s_mov_b32": - dst_s, val = args - if dst_s in ("vcc_lo", "vcc"): - self.vcc = ((self.vcc & ~0xFFFFFFFF) | (val & 0xFFFFFFFF)) & self.mask_all - elif dst_s == "vcc_hi": - if self.wave_size == 64: - self.vcc = ((self.vcc & 0xFFFFFFFF) | ((val & 0xFFFFFFFF) << 32)) & self.mask_all - else: - self.sgprs[107] = val & 0xFFFFFFFF - else: - self.sgprs[dst_s] = val & 0xFFFFFFFF - - elif op == "s_mov_b64": - dst_s, val = args - if dst_s == "vcc": - self.vcc = val & self.mask_all - else: - self.sgprs[dst_s] = val & 0xFFFFFFFF - self.sgprs[dst_s + 1] = (val >> 32) & 0xFFFFFFFF - - elif op == "s_and_b32": - dst_s, val = args - if dst_s in ("vcc_lo", "vcc"): - lo = (self.vcc & 0xFFFFFFFF) & (val & 0xFFFFFFFF) - self.vcc = ((self.vcc & ~0xFFFFFFFF) | lo) & self.mask_all - else: - self.sgprs[dst_s] = (self.sgprs[dst_s] & val) & 0xFFFFFFFF - - elif op == "s_or_b32": - dst_s, val = args - if dst_s in ("vcc_lo", "vcc"): - lo = (self.vcc & 0xFFFFFFFF) | (val & 0xFFFFFFFF) - self.vcc = ((self.vcc & ~0xFFFFFFFF) | lo) & self.mask_all - else: - self.sgprs[dst_s] = (self.sgprs[dst_s] | val) & 0xFFFFFFFF - - elif op == "s_and_b64": - dst_s, val = args - if dst_s == "vcc": - self.vcc = (self.vcc & val) & self.mask_all - else: - cur_val = self.sgprs[dst_s] | (self.sgprs[dst_s + 1] << 32) - res = cur_val & val - self.sgprs[dst_s] = res & 0xFFFFFFFF - self.sgprs[dst_s + 1] = (res >> 32) & 0xFFFFFFFF - - elif op == "s_or_b64": - dst_s, val = args - if dst_s == "vcc": - self.vcc = (self.vcc | val) & self.mask_all - else: - cur_val = self.sgprs[dst_s] | (self.sgprs[dst_s + 1] << 32) - res = cur_val | val - self.sgprs[dst_s] = res & 0xFFFFFFFF - self.sgprs[dst_s + 1] = (res >> 32) & 0xFFFFFFFF - - elif op == "s_set_vcc": - self.vcc = args[0] & self.mask_all - - elif op == "s_set_exec": - self.exec_mask = args[0] & self.mask_all - - elif op == "v_mov_b32": - dst_v, val = args - for lane in range(self.wave_size): - if self.is_lane_active(lane): - self.vgprs[lane][dst_v] = val & 0xFFFFFFFF - - elif op == "v_add_u32": - dst_v, src_v, imm = args - for lane in range(self.wave_size): - if self.is_lane_active(lane): - self.vgprs[lane][dst_v] = (self.vgprs[lane][src_v] + imm) & 0xFFFFFFFF - - elif op == "v_sub_u32": - dst_v, src_v, imm = args - for lane in range(self.wave_size): - if self.is_lane_active(lane): - self.vgprs[lane][dst_v] = (self.vgprs[lane][src_v] - imm) & 0xFFFFFFFF - - elif op == "v_dec_u32": - dst_v = args[0] - for lane in range(self.wave_size): - if self.is_lane_active(lane): - curr_val = self.vgprs[lane][dst_v] - self.vgprs[lane][dst_v] = (curr_val - 1) & 0xFFFFFFFF if curr_val > 0 else 0 - - elif op in ("v_cmp_gt_u32", "v_cmp_ge_u32", "v_cmp_lt_u32", - "v_cmp_le_u32", "v_cmp_eq_u32", "v_cmp_ne_u32"): - dst_target, src_v, val_or_imm = args - cond_mask = 0 - for lane in range(self.wave_size): - if not self.is_lane_active(lane): - continue - lhs = self.vgprs[lane][src_v] - rhs = val_or_imm if isinstance(val_or_imm, int) else self.vgprs[lane][val_or_imm] - - if op == "v_cmp_gt_u32": - passed = lhs > rhs - elif op == "v_cmp_ge_u32": - passed = lhs >= rhs - elif op == "v_cmp_lt_u32": - passed = lhs < rhs - elif op == "v_cmp_le_u32": - passed = lhs <= rhs - elif op == "v_cmp_eq_u32": - passed = lhs == rhs - elif op == "v_cmp_ne_u32": - passed = lhs != rhs - else: - passed = False - - if passed: - cond_mask |= (1 << lane) - - if dst_target in ("vcc", "vcc_lo"): - self.vcc = cond_mask & self.mask_all - else: - self.sgprs[dst_target] = cond_mask & 0xFFFFFFFF - if self.wave_size == 64: - self.sgprs[dst_target + 1] = (cond_mask >> 32) & 0xFFFFFFFF - - elif op == "v_add_co_u32": - dst_v, src_v0, src_v1 = args - carry_mask = 0 - for lane in range(self.wave_size): - if not self.is_lane_active(lane): - continue - a = self.vgprs[lane][src_v0] - b = src_v1 if isinstance(src_v1, int) else self.vgprs[lane][src_v1] - full_sum = a + b - self.vgprs[lane][dst_v] = full_sum & 0xFFFFFFFF - if full_sum > 0xFFFFFFFF: - carry_mask |= (1 << lane) - - self.vcc = carry_mask & self.mask_all - - else: - raise NotImplementedError(f"Unsupported instruction in test interpreter: {op}") - - if next_block is None: - cur = block[-1] if isinstance(block[-1], str) else None - else: - cur = next_block - - if steps >= max_steps: - raise TimeoutError("Execution exceeded max_steps (infinite loop detected)") - - -# ----------------------------------------------------------------------------- -# 3. SPIR-V Subgroup Vote Interpreter -# ----------------------------------------------------------------------------- - -def simulate_spirv_subgroup_vcc_branch(op: str, lane_vcc_words: list[int]) -> bool: - """Interprets the SPIR-V instructions emitted by rdna2spirv for VCC branching. - - Emitted sequence: - %s = OpLoad %uint %vcc - %lane = OpINotEqual %bool %s %c0 - %any = OpGroupNonUniformAny %bool %c3 %lane - (if vccz): %b = OpLogicalNot %bool %any - """ - any_active_vcc = any((word & 0xFFFFFFFF) != 0 for word in lane_vcc_words) - - if op == "s_cbranch_vccnz": - return any_active_vcc - elif op == "s_cbranch_vccz": - return not any_active_vcc - else: - raise ValueError(f"Unknown branch opcode: {op}") - - -# ----------------------------------------------------------------------------- -# Test Suite -# ----------------------------------------------------------------------------- - -class TestControlFlowVccReference(unittest.TestCase): - """Verifies vector condition code branching semantics against ISA definitions.""" - - def test_vccz_and_vccnz_duality_wave32(self): - """vccz and vccnz must be strict logical complements for every 32-bit mask.""" - test_masks = [ - 0x00000000, - 0xFFFFFFFF, - 0x00000001, - 0x80000000, - 0x55555555, - 0xAAAAAAAA, - 0x0000FFFF, - 0xFFFF0000, - 0x00FF00FF, - 0xFF00FF00, - ] - for bit in range(32): - test_masks.append(1 << bit) - test_masks.append(~(1 << bit) & 0xFFFFFFFF) - - rng = random.Random(20261122) - for _ in range(100): - test_masks.append(rng.getrandbits(32)) - - for mask in test_masks: - z = eval_vccz(mask, wave_size=32) - nz = eval_vccnz(mask, wave_size=32) - with self.subTest(mask=hex(mask)): - self.assertNotEqual(z, nz, "vccz and vccnz must be strict logical complements") - self.assertEqual(z, (mask & 0xFFFFFFFF) == 0) - self.assertEqual(nz, (mask & 0xFFFFFFFF) != 0) - - def test_vccz_and_vccnz_duality_wave64(self): - """vccz and vccnz must be strict logical complements across full 64-bit masks.""" - test_masks = [ - 0x0000000000000000, - 0xFFFFFFFFFFFFFFFF, - 0x0000000000000001, - 0x8000000000000000, - 0x5555555555555555, - 0xAAAAAAAAAAAAAAAA, - 0x00000000FFFFFFFF, - 0xFFFFFFFF00000000, - 0x0000FFFF0000FFFF, - 0xFFFF0000FFFF0000, - ] - for bit in range(64): - test_masks.append(1 << bit) - test_masks.append(~(1 << bit) & 0xFFFFFFFFFFFFFFFF) - - rng = random.Random(20261122) - for _ in range(100): - test_masks.append(rng.getrandbits(64)) - - for mask in test_masks: - z = eval_vccz(mask, wave_size=64) - nz = eval_vccnz(mask, wave_size=64) - with self.subTest(mask=hex(mask)): - self.assertNotEqual(z, nz, "vccz and vccnz must be strict logical complements in Wave64") - self.assertEqual(z, (mask & 0xFFFFFFFFFFFFFFFF) == 0) - self.assertEqual(nz, (mask & 0xFFFFFFFFFFFFFFFF) != 0) - - def test_wave32_ignores_upper_half_bits(self): - """Wave32 mode isolates the lower 32 bits and ignores bits 32..63.""" - high_half_mask = 0x1234567800000000 - self.assertTrue(eval_vccz(high_half_mask, wave_size=32)) - self.assertFalse(eval_vccnz(high_half_mask, wave_size=32)) - - # In contrast, Wave64 must observe the high half bits - self.assertFalse(eval_vccz(high_half_mask, wave_size=64)) - self.assertTrue(eval_vccnz(high_half_mask, wave_size=64)) - - def test_wave64_truncates_beyond_bit63(self): - """Bits beyond 63 are outside the 64-lane wave and must not alter evaluation.""" - bit64 = 1 << 64 - self.assertTrue(eval_vccz(bit64, wave_size=64)) - self.assertFalse(eval_vccnz(bit64, wave_size=64)) - - bit65_with_low = (1 << 65) | 1 - self.assertFalse(eval_vccz(bit65_with_low, wave_size=64)) - self.assertTrue(eval_vccnz(bit65_with_low, wave_size=64)) - - -class TestWaveInterpreterVccFlow(unittest.TestCase): - """Verifies VCC control flow in multi-lane simulated programs across Wave32 and Wave64.""" - - def test_wave32_skip_pattern_vccz_all_fail(self): - """When all lanes fail the comparison, s_cbranch_vccz branches to skip work.""" - blocks = { - "entry": [ - ("v_cmp_gt_u32", "vcc", 0, 100), - ("s_cbranch_vccz", "skip"), - "work_block", - ], - "work_block": [ - ("v_mov_b32", 1, 999), - ("s_branch", "skip"), - ], - "skip": [ - ("s_endpgm",), - ], - } - - interp = WaveInterpreter(wave_size=32, initial_exec=0xFFFFFFFF) - for lane in range(32): - interp.vgprs[lane][0] = 50 # all below 100 - interp.vgprs[lane][1] = 10 # initial value - - interp.run_program(blocks, "entry") - - self.assertEqual(interp.trace, ["entry", "skip"]) - self.assertEqual(interp.vcc, 0) - for lane in range(32): - self.assertEqual(interp.vgprs[lane][1], 10) - - def test_wave32_skip_pattern_vccz_one_lane_satisfies(self): - """When at least one lane satisfies the comparison, s_cbranch_vccz does NOT branch.""" - interp = WaveInterpreter(wave_size=32, initial_exec=0xFFFFFFFF) - for lane in range(32): - interp.vgprs[lane][0] = 50 - interp.vgprs[lane][1] = 10 - interp.vgprs[17][0] = 150 # only lane 17 passes comparison - - blocks = { - "entry": [ - ("v_cmp_gt_u32", "vcc", 0, 100), - ("s_cbranch_vccz", "skip"), - "work_block", - ], - "work_block": [ - ("v_mov_b32", 1, 999), - ("s_branch", "skip"), - ], - "skip": [ - ("s_endpgm",), - ], - } - - interp.run_program(blocks, "entry") - - self.assertEqual(interp.trace, ["entry", "work_block", "skip"]) - self.assertEqual(interp.vcc, 1 << 17) - # All active lanes in the wave execute work_block - for lane in range(32): - self.assertEqual(interp.vgprs[lane][1], 999) - - def test_wave64_skip_pattern_vccz_high_half_only(self): - """In Wave64, a condition satisfied only in lane >= 32 correctly prevents vccz branching.""" - interp = WaveInterpreter(wave_size=64, initial_exec=0xFFFFFFFFFFFFFFFF) - for lane in range(64): - interp.vgprs[lane][0] = 20 - interp.vgprs[lane][1] = 5 - interp.vgprs[47][0] = 200 # lane 47 in upper half passes - - blocks = { - "entry": [ - ("v_cmp_gt_u32", "vcc", 0, 100), - ("s_cbranch_vccz", "skip"), - "work_block", - ], - "work_block": [ - ("v_mov_b32", 1, 777), - ("s_branch", "skip"), - ], - "skip": [ - ("s_endpgm",), - ], - } - - interp.run_program(blocks, "entry") - - self.assertEqual(interp.trace, ["entry", "work_block", "skip"]) - self.assertEqual(interp.vcc, 1 << 47) - for lane in range(64): - self.assertEqual(interp.vgprs[lane][1], 777) - - def test_wave64_skip_pattern_vccz_all_lanes_fail(self): - """In Wave64, when all 64 lanes fail, s_cbranch_vccz skips the work block.""" - interp = WaveInterpreter(wave_size=64, initial_exec=0xFFFFFFFFFFFFFFFF) - for lane in range(64): - interp.vgprs[lane][0] = 10 - interp.vgprs[lane][1] = 50 - - blocks = { - "entry": [ - ("v_cmp_gt_u32", "vcc", 0, 100), - ("s_cbranch_vccz", "skip"), - "work_block", - ], - "work_block": [ - ("v_mov_b32", 1, 777), - ("s_branch", "skip"), - ], - "skip": [ - ("s_endpgm",), - ], - } - - interp.run_program(blocks, "entry") - - self.assertEqual(interp.trace, ["entry", "skip"]) - self.assertEqual(interp.vcc, 0) - for lane in range(64): - self.assertEqual(interp.vgprs[lane][1], 50) - - def test_wave32_vccnz_direct_branch(self): - """s_cbranch_vccnz branches directly when VCC is non-zero, falls through when zero.""" - blocks = { - "entry": [ - ("v_cmp_eq_u32", "vcc", 0, 42), - ("s_cbranch_vccnz", "found_target"), - "not_found", - ], - "found_target": [ - ("s_mov_b32", 10, 0xAA), - ("s_endpgm",), - ], - "not_found": [ - ("s_mov_b32", 10, 0x55), - ("s_endpgm",), - ], - } - - # Case 1: no lane has 42 -> falls through to not_found - interp_none = WaveInterpreter(wave_size=32) - for lane in range(32): - interp_none.vgprs[lane][0] = lane + 100 - interp_none.run_program(blocks, "entry") - self.assertEqual(interp_none.trace, ["entry", "not_found"]) - self.assertEqual(interp_none.sgprs[10], 0x55) - - # Case 2: lane 0 has 42 -> branches to found_target - interp_one = WaveInterpreter(wave_size=32) - for lane in range(32): - interp_one.vgprs[lane][0] = 42 if lane == 0 else lane + 100 - interp_one.run_program(blocks, "entry") - self.assertEqual(interp_one.trace, ["entry", "found_target"]) - self.assertEqual(interp_one.sgprs[10], 0xAA) - - def test_wave64_vccnz_boundary_lanes(self): - """s_cbranch_vccnz triggers on boundary lanes in Wave64: 0, 31, 32, and 63.""" - boundary_lanes = [0, 31, 32, 63] - - for target_lane in boundary_lanes: - with self.subTest(target_lane=target_lane): - interp = WaveInterpreter(wave_size=64) - for lane in range(64): - interp.vgprs[lane][0] = 1000 if lane == target_lane else 0 - - blocks = { - "entry": [ - ("v_cmp_gt_u32", "vcc", 0, 500), - ("s_cbranch_vccnz", "hit"), - "miss", - ], - "hit": [ - ("s_mov_b32", 12, target_lane + 1), - ("s_endpgm",), - ], - "miss": [ - ("s_mov_b32", 12, 0), - ("s_endpgm",), - ], - } - - interp.run_program(blocks, "entry") - self.assertEqual(interp.trace, ["entry", "hit"]) - self.assertEqual(interp.sgprs[12], target_lane + 1) - self.assertEqual(interp.vcc, 1 << target_lane) - - def test_exec_mask_gates_vcc_comparison(self): - """Lanes inactive in EXEC write 0 to VCC; only active lanes participate in branch.""" - # Lane 5 satisfies condition (value 200 > 100), but lane 5 is disabled in EXEC - active_mask_without_lane5 = 0xFFFFFFFF & ~(1 << 5) - - interp = WaveInterpreter(wave_size=32, initial_exec=active_mask_without_lane5) - for lane in range(32): - interp.vgprs[lane][0] = 200 if lane == 5 else 10 - - blocks = { - "entry": [ - ("v_cmp_gt_u32", "vcc", 0, 100), - ("s_cbranch_vccz", "skip"), - "work", - ], - "work": [ - ("s_mov_b32", 20, 0x1111), - ("s_endpgm",), - ], - "skip": [ - ("s_mov_b32", 20, 0x2222), - ("s_endpgm",), - ], - } - - interp.run_program(blocks, "entry") - - # Since lane 5 was disabled in EXEC, VCC stayed 0, so s_cbranch_vccz skipped - self.assertEqual(interp.trace, ["entry", "skip"]) - self.assertEqual(interp.vcc, 0) - self.assertEqual(interp.sgprs[20], 0x2222) - - # Now re-enable lane 5 in EXEC - interp_active = WaveInterpreter(wave_size=32, initial_exec=0xFFFFFFFF) - for lane in range(32): - interp_active.vgprs[lane][0] = 200 if lane == 5 else 10 - - interp_active.run_program(blocks, "entry") - self.assertEqual(interp_active.trace, ["entry", "work"]) - self.assertEqual(interp_active.vcc, 1 << 5) - self.assertEqual(interp_active.sgprs[20], 0x1111) - - def test_divergent_loop_termination_vccnz(self): - """s_cbranch_vccnz loops while any lane has non-zero counter, terminating cleanly.""" - wave_size = 32 - interp = WaveInterpreter(wave_size=wave_size, initial_exec=0xFFFFFFFF) - # Staggered countdown values: lanes 0..7 have values 0..7 - for lane in range(wave_size): - interp.vgprs[lane][0] = lane if lane <= 7 else 0 - interp.vgprs[lane][1] = 0 - - blocks = { - "entry": [ - ("v_cmp_ne_u32", "vcc", 0, 0), - ("s_cbranch_vccz", "exit"), - "loop_body", - ], - "loop_body": [ - ("v_add_u32", 1, 1, 1), - ("v_dec_u32", 0), - ("v_cmp_ne_u32", "vcc", 0, 0), - ("s_cbranch_vccnz", "loop_body"), - "exit", - ], - "exit": [ - ("s_endpgm",), - ], - } - - interp.run_program(blocks, "entry", max_steps=100) - - # Max initial counter was 7, so loop body must execute 7 times across the wave - loop_occurrences = interp.trace.count("loop_body") - self.assertEqual(loop_occurrences, 7) - self.assertEqual(interp.vcc, 0) - for lane in range(wave_size): - self.assertEqual(interp.vgprs[lane][0], 0) - # All active lanes in the SIMD wave execute the loop 7 times until uniform exit - self.assertEqual(interp.vgprs[lane][1], 7) - - def test_carry_out_branching_v_add_co_u32(self): - """v_add_co_u32 writes arithmetic carry-out bits to VCC and drives branch decisions.""" - blocks = { - "entry": [ - ("v_add_co_u32", 2, 0, 1), - ("s_cbranch_vccnz", "overflow_detected"), - "no_overflow", - ], - "overflow_detected": [ - ("s_mov_b32", 30, 0xCAFE), - ("s_endpgm",), - ], - "no_overflow": [ - ("s_mov_b32", 30, 0xBEEF), - ("s_endpgm",), - ], - } - - # Case 1: no overflow in any lane - interp_no_ovf = WaveInterpreter(wave_size=32) - for lane in range(32): - interp_no_ovf.vgprs[lane][0] = 1000 - interp_no_ovf.vgprs[lane][1] = 2000 - interp_no_ovf.run_program(blocks, "entry") - self.assertEqual(interp_no_ovf.trace, ["entry", "no_overflow"]) - self.assertEqual(interp_no_ovf.vcc, 0) - self.assertEqual(interp_no_ovf.sgprs[30], 0xBEEF) - - # Case 2: overflow only in lane 12 (0xFFFFFFFF + 1 = 0 with carry 1) - interp_ovf = WaveInterpreter(wave_size=32) - for lane in range(32): - if lane == 12: - interp_ovf.vgprs[lane][0] = 0xFFFFFFFF - interp_ovf.vgprs[lane][1] = 1 - else: - interp_ovf.vgprs[lane][0] = 1000 - interp_ovf.vgprs[lane][1] = 2000 - interp_ovf.run_program(blocks, "entry") - self.assertEqual(interp_ovf.trace, ["entry", "overflow_detected"]) - self.assertEqual(interp_ovf.vcc, 1 << 12) - self.assertEqual(interp_ovf.sgprs[30], 0xCAFE) - self.assertEqual(interp_ovf.vgprs[12][2], 0) - - def test_scalar_vcc_manipulation(self): - """Setting VCC through scalar instructions correctly controls s_cbranch_vccz/nz.""" - interp = WaveInterpreter(wave_size=64) - - # 1. Direct s_mov_b32 to vcc_lo - blocks_lo = { - "entry": [ - ("s_mov_b32", "vcc_lo", 0x1234), - ("s_cbranch_vccz", "fail"), - "pass_lo", - ], - "pass_lo": [("s_endpgm",)], - "fail": [("s_endpgm",)], - } - interp.run_program(blocks_lo, "entry") - self.assertEqual(interp.trace, ["entry", "pass_lo"]) - self.assertEqual(interp.vcc, 0x1234) - - # 2. Direct s_mov_b32 to vcc_hi - blocks_hi = { - "entry": [ - ("s_mov_b32", "vcc_lo", 0), - ("s_mov_b32", "vcc_hi", 0x5678), - ("s_cbranch_vccz", "fail"), - "pass_hi", - ], - "pass_hi": [("s_endpgm",)], - "fail": [("s_endpgm",)], - } - interp.run_program(blocks_hi, "entry") - self.assertEqual(interp.trace, ["entry", "pass_hi"]) - self.assertEqual(interp.vcc, 0x567800000000) - - # 3. Clearing with s_and_b64 - blocks_clr = { - "entry": [ - ("s_and_b64", "vcc", 0), - ("s_cbranch_vccnz", "fail"), - "pass_zero", - ], - "pass_zero": [("s_endpgm",)], - "fail": [("s_endpgm",)], - } - interp.run_program(blocks_clr, "entry") - self.assertEqual(interp.trace, ["entry", "pass_zero"]) - self.assertEqual(interp.vcc, 0) - - def test_divergent_if_then_else_vcc(self): - """Structured if-then-else construct guarded by s_cbranch_vccz.""" - wave_size = 32 - interp = WaveInterpreter(wave_size=wave_size, initial_exec=0xFFFFFFFF) - for lane in range(wave_size): - interp.vgprs[lane][0] = 50 + (lane % 2) * 100 # evens = 50, odds = 150 - interp.vgprs[lane][2] = 0 - - blocks = { - "entry": [ - ("v_cmp_gt_u32", "vcc", 0, 100), # odds pass - ("s_cbranch_vccz", "else_block"), - "then_block", - ], - "then_block": [ - ("v_add_u32", 2, 2, 1000), - ("s_branch", "join"), - ], - "else_block": [ - ("v_add_u32", 2, 2, 2000), - ("s_branch", "join"), - ], - "join": [ - ("s_endpgm",), - ], - } - - interp.run_program(blocks, "entry") - - # Odds satisfied condition -> then_block was taken - self.assertEqual(interp.trace, ["entry", "then_block", "join"]) - for lane in range(wave_size): - self.assertEqual(interp.vgprs[lane][2], 1000) - - -class TestTranslatorSpirvEmission(unittest.TestCase): - """Verifies that tools/rdna2spirv.py emits correct SPIR-V instructions for VCC branching.""" - - def test_branch_condition_vccz_emission(self): - """s_cbranch_vccz must load %vcc, test != 0, vote Any, and negate the result.""" - g = rdna2spirv.Gen("ps") - cond = rdna2spirv.branch_condition(g, "s_cbranch_vccz") - - self.assertTrue(g.uses_vote, "s_cbranch_vccz must flag uses_vote = True") - - body_text = "\n".join(g.body) - self.assertIn("OpLoad %uint %vcc", body_text) - self.assertIn("OpINotEqual %bool", body_text) - self.assertIn("OpGroupNonUniformBallot %v4uint_bal %c3", body_text) - self.assertIn("%c20", body_text) # select the ballot word for this wave32 pixel half - self.assertIn("OpINotEqual %bool", body_text) - self.assertIn(f"{cond} = OpLogicalNot %bool", body_text) - - def test_branch_condition_vccnz_emission(self): - """s_cbranch_vccnz must load %vcc, test != 0, vote Any, without logical negation.""" - g = rdna2spirv.Gen("ps") - cond = rdna2spirv.branch_condition(g, "s_cbranch_vccnz") - - self.assertTrue(g.uses_vote, "s_cbranch_vccnz must flag uses_vote = True") - - body_text = "\n".join(g.body) - self.assertIn("OpLoad %uint %vcc", body_text) - self.assertIn("OpINotEqual %bool", body_text) - self.assertIn("OpGroupNonUniformBallot %v4uint_bal %c3", body_text) - self.assertIn("%c20", body_text) # select the ballot word for this wave32 pixel half - self.assertIn("OpINotEqual %bool", body_text) - self.assertIn(f"{cond} = OpCopyObject %bool", body_text) - self.assertNotIn("OpLogicalNot", body_text) - - def test_required_capabilities_for_vcc_vote(self): - """Assembling shaders with s_cbranch_vccz/nz must declare GroupNonUniform capabilities.""" - g = rdna2spirv.Gen("ps") - rdna2spirv.branch_condition(g, "s_cbranch_vccz") - asm = rdna2spirv.assemble(g) - caps = rdna2spirv.shader_meta(g, asm)["capabilities"] - - self.assertIn("GroupNonUniform", caps) - self.assertIn("GroupNonUniformVote", caps) - - def test_spirv_subgroup_simulation_matches_isa_reference(self): - """Simulated SPIR-V subgroup vote instructions match eval_vccz/eval_vccnz.""" - test_masks = [ - 0x00000000, - 0xFFFFFFFF, - 0x00000001, - 0x80000000, - 0x0000FFFF, - 0x55555555, - 0xAAAAAAAA, - ] - rng = random.Random(20261122) - test_masks.extend(rng.getrandbits(32) for _ in range(50)) - - for mask in test_masks: - # In SPIR-V, each invocation holds 0xFFFFFFFF or 0 in %vcc - lane_words = [0xFFFFFFFF if ((mask >> bit) & 1) else 0 for bit in range(32)] - - sim_z = simulate_spirv_subgroup_vcc_branch("s_cbranch_vccz", lane_words) - sim_nz = simulate_spirv_subgroup_vcc_branch("s_cbranch_vccnz", lane_words) - - ref_z = eval_vccz(mask, wave_size=32) - ref_nz = eval_vccnz(mask, wave_size=32) - - self.assertEqual(sim_z, ref_z, f"vccz mismatch for mask {hex(mask)}") - self.assertEqual(sim_nz, ref_nz, f"vccnz mismatch for mask {hex(mask)}") - - def test_wave_uniformity_prevents_sgpr_divergence(self): - """Verifies that subgroup voting ensures all lanes take an identical branch path.""" - # Non-uniform lane values - lane_words = [0xFFFFFFFF if (i == 3) else 0 for i in range(32)] - vote_result = simulate_spirv_subgroup_vcc_branch("s_cbranch_vccnz", lane_words) - - # Every lane in the subgroup sees the exact same boolean vote outcome - for lane_idx in range(32): - self.assertTrue(vote_result, f"Lane {lane_idx} must observe uniform true") - - -class TestNegativeControlsAndMutations(unittest.TestCase): - """Ensures test assertions detect erroneous, inverted, or truncated implementations.""" - - def test_inverted_vccz_fails_detection(self): - """Inverted eval_vccz logic is caught immediately.""" - def sabotaged_eval_vccz(mask: int, wave_size: int = 32) -> bool: - return (mask & ((1 << wave_size) - 1)) != 0 - - self.assertNotEqual(sabotaged_eval_vccz(0), eval_vccz(0)) - self.assertNotEqual(sabotaged_eval_vccz(0xFFFFFFFF), eval_vccz(0xFFFFFFFF)) - - def test_subgroup_all_instead_of_any_fails_detection(self): - """Using OpGroupNonUniformAll instead of Any fails when only a subset of lanes is set.""" - def all_active(lane_words: list[int]) -> bool: - return all((w & 0xFFFFFFFF) != 0 for w in lane_words) - - partial_lane_words = [0xFFFFFFFF] + [0] * 31 - sim_nz = simulate_spirv_subgroup_vcc_branch("s_cbranch_vccnz", partial_lane_words) - self.assertTrue(sim_nz) - self.assertFalse(all_active(partial_lane_words)) - - def test_wave64_ignoring_vcc_hi_fails_detection(self): - """Truncating Wave64 to 32 bits fails to detect high-half VCC conditions.""" - def buggy_wave64_eval_vccz(mask: int) -> bool: - return (mask & 0xFFFFFFFF) == 0 - - high_half_mask = 1 << 45 - self.assertFalse(eval_vccz(high_half_mask, wave_size=64)) - self.assertTrue(buggy_wave64_eval_vccz(high_half_mask)) - - def test_branches_registration(self): - """Verifies that s_cbranch_vccz and s_cbranch_vccnz are registered in rdna2spirv.BRANCHES.""" - self.assertIn("s_cbranch_vccz", rdna2spirv.BRANCHES) - self.assertIn("s_cbranch_vccnz", rdna2spirv.BRANCHES) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_cs_barrier_counts_lds.py b/tests/semantic/test_cs_barrier_counts_lds.py deleted file mode 100644 index 7108ebb9e..000000000 --- a/tests/semantic/test_cs_barrier_counts_lds.py +++ /dev/null @@ -1,183 +0,0 @@ -"""SHADER-579: the barrier-round count no longer pushes a full-LDS wave32 compute shader over the device limit. - -A native wave32 compute shader whose s_barrier is not in uniform control flow runs in barrier rounds (SHADER-91, -`bar_scheduler`). The round loop counts the invocations not done in `%x_buf`, three Workgroup dwords (#930). On top of -a full 32 KiB LDS that made 32,780 B, 12 bytes over the 32,768 B `maxComputeSharedMemorySize` of the AMD Windows and -Intel drivers, so the runtime check (SHADER-309) refused those pipelines there. When the 12 bytes would take the total -past 16,384 B (the Vulkan minimum), the count now borrows LDS word 0 between rounds instead: invocation 0 saves the -word, the count runs in it, invocation 0 puts it back, each step behind a workgroup barrier while no invocation runs -shader code. Smaller shaders keep `%x_buf` and the single barrier per round. - -The Workgroup bytes are counted from the emitted SPIR-V; the barrier behaviour runs in the workgroup interpreter of -test_loop_ballot_barrier.py, whose LDS starts as 0xDEADBEEF. The programs are written here; no game data. -""" -import os -import struct -import sys -import unittest - -HERE = os.path.dirname(os.path.abspath(__file__)) -if HERE not in sys.path: - sys.path.insert(0, HERE) # python -I leaves the script's folder off sys.path - -import support # noqa: E402 (support puts tools/ on sys.path, honouring LEONIDA_TOOLS_DIR) -import test_cs_shared_memory_limit as shl # noqa: E402 (module import: its TestCase stays out of this module) -import test_loop_ballot_barrier as lbb # noqa: E402 - -rdna2spirv = support.rdna2spirv -VSHARP = [0, 0, 0xFFFFFFFF, 0x31016FAC] # raw buffer V# at base 0 in s[0:3] - - -def ring_shift(threads=64, iters=5): - """s_barrier in a loop (barrier rounds): each iteration thread t writes its value to lds[t], s_barrier, reads - lds[(t + 1) % threads] and adds 100, s_barrier. Thread 63 reads LDS word 0, the word the count borrows.""" - return [ - "v_add_nc_u32_e32 v1, 1000, v0", - "v_lshlrev_b32_e32 v2, 2, v0", - "v_add_nc_u32_e32 v3, 1, v0", - f"v_and_b32_e32 v3, {threads - 1}, v3", - "v_lshlrev_b32_e32 v3, 2, v3", - "s_mov_b32 s8, 0", - "loop:", - "ds_write_b32 v2, v1", - "s_waitcnt lgkmcnt(0)", - "s_barrier", - "ds_read_b32 v1, v3", - "s_waitcnt lgkmcnt(0)", - "v_add_nc_u32_e32 v1, 100, v1", - "s_barrier", - "s_add_u32 s8, s8, 1", - f"s_cmp_lt_u32 s8, {iters}", - "s_cbranch_scc1 loop", - "buffer_store_dword v1, v2, s[0:3], 0 offen", - "s_endpgm", - ] - - -def early_end(): - """Wave 0 runs 2 iterations of a barrier loop and ends, wave 1 runs 4: a wave that is done no longer counts. - Each thread keeps its count in its own LDS word, so thread 0's lives in the borrowed word.""" - return [ - "v_lshrrev_b32_e32 v1, 5, v0", - "v_readfirstlane_b32 s8, v1", - "s_lshl_b32 s9, s8, 1", - "s_add_u32 s9, s9, 2", - "s_mov_b32 s12, 0", - "v_lshlrev_b32_e32 v2, 2, v0", - "v_mov_b32_e32 v3, 0", - "loop:", - "ds_write_b32 v2, v3", - "s_waitcnt lgkmcnt(0)", - "s_barrier", - "ds_read_b32 v4, v2", - "s_waitcnt lgkmcnt(0)", - "v_add_nc_u32_e32 v3, 1, v4", - "s_add_u32 s12, s12, 1", - "s_cmp_lt_u32 s12, s9", - "s_cbranch_scc1 loop", - "buffer_store_dword v3, v2, s[0:3], 0 offen", - "s_endpgm", - ] - - -def translate(items, lds_units, threads=64, limit=None): - """Native wave32 compute shader of `threads` invocations with LDS_SIZE `lds_units` (512-byte units): 8 user - SGPRs and TGID_X in RSRC2, nothing else. Returns (SPIR-V text, generator).""" - lines = [f"{text} ; encoding: [{','.join(['0x00'] * size)}]" for text, size in lbb._resolve_labels(items)] - header = bytes(0x138) + struct.pack("<4I", 0x90 | (lds_units << 15), threads, 1, 1) - prev = rdna2spirv.WAVE64_EMULATE, rdna2spirv.MAX_SHARED_BYTES - rdna2spirv.WAVE64_EMULATE = False - if limit is not None: - rdna2spirv.MAX_SHARED_BYTES = limit - try: - spv = support.translate_lines("cs_bar_counts", lines, fssm=header) - finally: - rdna2spirv.WAVE64_EMULATE, rdna2spirv.MAX_SHARED_BYTES = prev - gen = rdna2spirv.translate.last_gen - assert not gen.wave64, "the test program must translate as wave32" - return spv, gen - - -def run(spv, threads=64): - """Output dwords of thread 0..threads-1, for both wave orders.""" - out = [] - for rev in (False, True): - mem = lbb.run_compute_workgroup(spv, threads, 32, push_constants=VSHARP, reverse_subgroups=rev) - out.append([mem.get(4 * t) for t in range(threads)]) - return out - - -RING = [1000 + (t + 5) % 64 + 500 for t in range(64)] - - -class BarrierCountsInLdsTests(unittest.TestCase): - def test_full_32k_lds_is_exactly_32768_bytes(self): - # the finding: 32 KiB LDS + the 12-byte count was 32,780 B; now the count is in the LDS array - spv, gen = translate(ring_shift(), 64) - self.assertTrue(gen.bar_rounds) - self.assertEqual(gen.control_flow, "barrier rounds") - wg = shl.workgroup_bytes(spv) - self.assertEqual(wg, {"%lds": 32768}) - self.assertLessEqual(sum(wg.values()), 32768) - self.assertEqual(rdna2spirv.shader_meta(gen, spv)["lds_bytes"], 32768) - self.assertNotIn("%x_buf", spv) - - def test_full_32k_lds_translates_under_a_32k_cap(self): - # --max-shared-memory 32768 (the AMD Windows / Intel limit): accepted, the array not shrunk - spv, _ = translate(ring_shift(), 64, limit=32768) - self.assertEqual(shl.workgroup_bytes(spv), {"%lds": 32768}) - self.assertEqual(shl.lds_index_ops(spv), {"OpBitwiseAnd"}) - - def test_full_64k_lds_fits_the_hard_cap(self): - # before: 65,548 B, shrunk or refused; now exactly the 64 KiB cap with the power-of-two array - spv, _ = translate(ring_shift(), 128) - self.assertEqual(shl.workgroup_bytes(spv), {"%lds": 65536}) - self.assertEqual(shl.lds_index_ops(spv), {"OpBitwiseAnd"}) - - def test_barrier_rounds_still_exact_with_the_borrowed_word(self): - # the ring shift reads every LDS word another thread wrote, word 0 included, across 10 barriers - for units in (32, 64, 128): - with self.subTest(units=units): - spv, gen = translate(ring_shift(), units) - self.assertTrue(gen.bar_counts_in_lds()) - self.assertEqual(run(spv), [RING, RING]) - - def test_a_wave_that_ends_no_longer_counts(self): - spv, gen = translate(early_end(), 64) - self.assertTrue(gen.bar_counts_in_lds()) - self.assertEqual(run(spv), [[2] * 32 + [4] * 32] * 2) - - def test_small_lds_keeps_x_buf_and_one_barrier_per_round(self): - # 8 KiB + 12 B fits every device: the three Workgroup counts, the barrier rounds as before - for units in (1, 16): - with self.subTest(units=units): - spv, gen = translate(ring_shift(), units) - self.assertTrue(gen.bar_rounds) - self.assertFalse(gen.bar_counts_in_lds()) - wg = shl.workgroup_bytes(spv) - self.assertEqual(wg["%x_buf"], 12) - self.assertEqual(rdna2spirv.shader_meta(gen, spv)["lds_bytes"], sum(wg.values())) - self.assertEqual(spv.count("OpControlBarrier"), 2) - self.assertEqual(run(spv), [RING, RING]) - - def test_no_lds_access_keeps_x_buf(self): - # a 32 KiB allocation the program never touches: no LDS array to borrow from, the 12 bytes stay - items = [ln for ln in ring_shift() if not ln.startswith(("ds_", "s_waitcnt"))] - spv, gen = translate(items, 64) - self.assertTrue(gen.bar_rounds) - self.assertFalse(gen.uses_lds) - self.assertEqual(shl.workgroup_bytes(spv), {"%x_buf": 12}) - - def test_top_level_barrier_has_no_count(self): - # a barrier every invocation reaches stays one OpControlBarrier: no rounds, nothing added to the LDS - items = ["v_lshlrev_b32_e32 v2, 2, v0", "ds_write_b32 v2, v0", "s_waitcnt lgkmcnt(0)", "s_barrier", - "ds_read_b32 v1, v2 offset:4", "s_waitcnt lgkmcnt(0)", - "buffer_store_dword v1, v2, s[0:3], 0 offen", "s_endpgm"] - spv, gen = translate(items, 64) - self.assertFalse(gen.bar_rounds) - self.assertEqual(shl.workgroup_bytes(spv), {"%lds": 32768}) - self.assertEqual(spv.count("OpControlBarrier"), 1) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_cs_shared_memory_limit.py b/tests/semantic/test_cs_shared_memory_limit.py deleted file mode 100644 index 63de6dde6..000000000 --- a/tests/semantic/test_cs_shared_memory_limit.py +++ /dev/null @@ -1,273 +0,0 @@ -"""SHADER-309: a compute shader's Workgroup memory fits in maxComputeSharedMemorySize (#1721). - -`--wave64-emulate` adds its own Workgroup buffer, `%x_buf` (2L + 6W + 7 dwords for L invocations in W waves), on top -of the shader's LDS array. With a 64 KiB LDS that made modules over the 64 KiB device limit, which `spirv-val` accepts -and RADV dies on (#1721: 16,385 uints = 65,540 B). The translator now counts both against -`rdna2spirv.MAX_SHARED_BYTES` (`--max-shared-memory`, default 65536, the hard cap): the LDS array, a power of two at -least the program's need, shrinks to the RSRC2 allocation when that still fits; otherwise the shader is refused -(`Unsupported`, with the byte counts). The device's own limit (32768 on the AMD Windows and Intel drivers) is the -runtime's check, against `lds_bytes`, which must be the whole total. - -RDNA2 LDS does not wrap: an access outside the allocation reads 0 and its write is dropped (RDNA2 ISA 3.6.1, 3.6.6). -A shrunk array, or a program whose constant ds offsets reach past its RSRC2 allocation, gets bounds-checked LDS -accesses (Gen.lds_access); every other shader keeps the wrapped power-of-two array and emits no check. The -out-of-range cases run through spirv_mini_interp. - -The Workgroup bytes are counted from the emitted SPIR-V. The programs are written here; no game data. -""" -import os -import re -import struct -import sys -import unittest - -HERE = os.path.dirname(os.path.abspath(__file__)) -if HERE not in sys.path: - sys.path.insert(0, HERE) # python -I leaves the script's folder off sys.path - -import support # noqa: E402 (support puts tools/ on sys.path, honouring LEONIDA_TOOLS_DIR) -import spirv_mini_interp as si # noqa: E402 - -rdna2spirv = support.rdna2spirv - -# One wave of 64: write each lane's id to LDS, read the neighbour's dword back, store it to the output V# s[0:3]. -PROGRAM = ["s_mov_b64 exec, -1", - "v_lshlrev_b32_e32 v1, 2, v0", - "v_readfirstlane_b32 s16, v1", - "ds_write_b32 v1, v0", - "s_waitcnt lgkmcnt(0)", - "ds_read_b32 v2, v1 offset:4", - "s_waitcnt lgkmcnt(0)", - "buffer_store_dword v2, v1, s[0:3], 0 offen", - "s_endpgm"] -X_BUF = 4 * (2 * 64 + 6 * 1 + 7) # %x_buf for one wave of 64: 564 bytes - - -def fssm(lds_units, threads=64): - """Compute header: COMPUTE_PGM_RSRC2 with 4 user SGPRs, TGID_X and LDS_SIZE (512-byte units) at [23:15].""" - return bytes(0x138) + struct.pack("<4I", 0x88 | (lds_units << 15), threads, 1, 1) - - -def translate(lds_units, emulate=True, limit=None): - prev = rdna2spirv.WAVE64_EMULATE, rdna2spirv.MAX_SHARED_BYTES - rdna2spirv.WAVE64_EMULATE = emulate - if limit is not None: - rdna2spirv.MAX_SHARED_BYTES = limit - try: - spv = support.translate_lines("cs_shared_limit", PROGRAM, fssm=fssm(lds_units)) - finally: - rdna2spirv.WAVE64_EMULATE, rdna2spirv.MAX_SHARED_BYTES = prev - assert rdna2spirv.translate.last_gen.wave64, "the test program must translate as wave64" - return spv - - -def workgroup_bytes(spv): - """{variable: bytes} of every Workgroup-storage-class OpVariable, sized from its pointee type.""" - consts, types, ptrs, out = {}, {}, {}, {} - for ln in spv.splitlines(): - t = ln.split() - if len(t) < 3 or t[1] != "=": - continue - rid, op, args = t[0], t[2], t[3:] - if op == "OpConstant": - consts[rid] = int(args[1], 0) - elif op == "OpTypeInt" or op == "OpTypeFloat": - types[rid] = int(args[0]) // 8 - elif op == "OpTypeArray": - types[rid] = types[args[0]] * consts[args[1]] - elif op == "OpTypeStruct": - types[rid] = sum(types[a] for a in args) - elif op == "OpTypePointer" and args[0] == "Workgroup": - ptrs[rid] = args[1] - elif op == "OpVariable" and args[1:2] == ["Workgroup"]: - out[rid] = types[ptrs[args[0]]] - return out - - -def lds_index_ops(spv): - """The op each LDS access wraps its dword index with (OpBitwiseAnd for a power of two, OpUMod when shrunk).""" - return set(re.findall(r"= (OpBitwiseAnd|OpUMod) %uint %\w+ %\w+\n\s*%\w+ = OpAccessChain %_ptr_WG_uint\w* %lds ", - spv)) - - -def bounds_checks(spv): - """How many LDS accesses are bounds-checked (Gen.lds_access emits one `_lin` in-range block per dword).""" - return len(re.findall(r"^\s*%\w+_lin = OpLabel$", spv, re.M)) - - -VSHARP = [0, 0, 0x1000, 0x31016FAC] # s[0:3]: the output buffer V# - - -def run_one(lines, lds_units): - """Translate a wave32 compute listing (one invocation) and run it; returns (spirv, {byte address: word}).""" - prev = rdna2spirv.WAVE64_EMULATE - rdna2spirv.WAVE64_EMULATE = False - try: - spv = support.translate_lines("cs_lds_bounds", lines + ["s_endpgm"], fssm=fssm(lds_units, threads=32)) - finally: - rdna2spirv.WAVE64_EMULATE = prev - mem = si.run_workgroup(spv, 1, 32, inputs_for=lambda i: {"%wg_id": (0, 0, 0), "%local_id": (i, 0, 0), - "%sg_lane": i}, - push_constants=VSHARP + [0] * 28, memory={}) - return spv, mem - - -def out(*regs): - """Store v to output word k for each k.""" - lines = [] - for k, r in enumerate(regs): - lines += [f"v_mov_b32_e32 v31, {4 * k}", f"buffer_store_dword v{r}, v31, s[0:3], 0 offen"] - return lines - - -class SharedMemoryLimitTests(unittest.TestCase): - def test_under_limit_is_unchanged(self): - # 32 KiB of LDS + the exchange: well under 64 KiB, the power-of-two array as before - wg = workgroup_bytes(translate(64)) - self.assertEqual(wg, {"%lds": 32768, "%x_buf": X_BUF}) - self.assertLessEqual(sum(wg.values()), rdna2spirv.MAX_SHARED_BYTES) - - def test_full_64k_lds_is_refused(self): - # #1721: 64 KiB of LDS leaves no room for the exchange, and the program needs all of it - with self.assertRaises(rdna2spirv.Unsupported) as cm: - translate(128) - msg = str(cm.exception) - self.assertIn(f"{65536 + X_BUF} B", msg) - self.assertIn("LDS 65536 B", msg) - self.assertIn(f"wave64 exchange {X_BUF} B", msg) - self.assertIn("65536 B", msg) - - def test_rounded_up_lds_shrinks_to_the_allocation(self): - # LDS_SIZE 100 units = 51,200 B rounds up to a 64 KiB array, over the cap with the exchange; the allocation - # fits, so the array is the allocation and its accesses are bounds-checked (no mask, no wrap) - spv = translate(100) - self.assertEqual(workgroup_bytes(spv), {"%lds": 51200, "%x_buf": X_BUF}) - self.assertEqual(lds_index_ops(spv), set()) - self.assertEqual(bounds_checks(spv), 2) # the ds_write and the ds_read - - def test_exact_limit_is_accepted_one_dword_less_is_refused(self): - # 32 KiB of LDS (LDS_SIZE 64, all of it needed) + the exchange, against a limit at exactly that sum ... - exact = 32768 + X_BUF - spv = translate(64, limit=exact) - self.assertEqual(sum(workgroup_bytes(spv).values()), exact) - self.assertEqual(lds_index_ops(spv), {"OpBitwiseAnd"}) - self.assertEqual(bounds_checks(spv), 0) - # ... and one dword under it: the need no longer fits, so there is nothing to shrink to - with self.assertRaises(rdna2spirv.Unsupported): - translate(64, limit=exact - 4) - - def test_metadata_lds_bytes_is_every_workgroup_byte(self): - # index.json's lds_bytes is what the runtime compares with the device's maxComputeSharedMemorySize (32768 on - # some drivers): it has to be the module's whole Workgroup total, the emulation's %x_buf included - for units, emulate in ((64, True), (100, True), (128, False), (64, False)): - with self.subTest(units=units, emulate=emulate): - prev = rdna2spirv.WAVE64_EMULATE - spv = translate(units, emulate=emulate) - rdna2spirv.WAVE64_EMULATE = emulate - try: - meta = rdna2spirv.shader_meta(rdna2spirv.translate.last_gen, spv) - finally: - rdna2spirv.WAVE64_EMULATE = prev - self.assertEqual(meta["lds_bytes"], sum(workgroup_bytes(spv).values())) - - def test_native_allocation_over_64k_is_refused(self): - # RSRC2 LDS_SIZE counts 512-byte units, so the smallest allocation above 64 KiB is 129 units = 66,048 B. - # The array is clipped to 16,384 dwords; the allocation still counts, so the shader is refused, not cut. - with self.assertRaises(rdna2spirv.Unsupported) as cm: - translate(129, emulate=False) - self.assertIn("LDS 66048 B", str(cm.exception)) - - def test_constant_offset_at_the_end_of_64k_is_counted_exactly(self): - # A b32 access at offset 65,532 ends at byte 65,536: the need is exactly 16,384 dwords (the estimate used - # to add 4 dwords of slack and overcount it), so a 64 KiB allocation is in range and emits no check - prog = [ln.replace("ds_write_b32 v1, v0", "ds_write_b32 v1, v0 offset:65532") for ln in PROGRAM] - prev = rdna2spirv.WAVE64_EMULATE - rdna2spirv.WAVE64_EMULATE = False - try: - spv = support.translate_lines("cs_shared_limit", prog, fssm=fssm(128)) - finally: - rdna2spirv.WAVE64_EMULATE = prev - self.assertEqual(rdna2spirv.translate.last_gen.lds_need, 16384) - self.assertEqual(workgroup_bytes(spv), {"%lds": 65536}) - self.assertEqual(bounds_checks(spv), 0) - - def test_constant_offset_past_the_allocation_is_bounds_checked(self): - # 512 B allocated (LDS_SIZE 1), a write at offset 65,524: on RDNA2 it is out of range. The array is the - # allocation, every access is checked, and nothing wraps onto a valid word. - prog = [ln.replace("ds_write_b32 v1, v0", "ds_write_b32 v1, v0 offset:65524") for ln in PROGRAM] - prev = rdna2spirv.WAVE64_EMULATE - rdna2spirv.WAVE64_EMULATE = False - try: - spv = support.translate_lines("cs_shared_limit", prog, fssm=fssm(1)) - finally: - rdna2spirv.WAVE64_EMULATE = prev - self.assertEqual(rdna2spirv.translate.last_gen.lds_need, 16382) - self.assertEqual(workgroup_bytes(spv), {"%lds": 512}) - self.assertEqual(bounds_checks(spv), 2) - self.assertEqual(lds_index_ops(spv), set()) - - def test_out_of_range_write_is_dropped_not_aliased(self): - # 512 B allocated. Word 0 holds a sentinel. A write at byte 65,536 (vaddr 0xFC00 + offset 1024) would land - # on word 0 if the index wrapped; RDNA2 drops it. Reading the same address back gives 0. - _, mem = run_one(["v_mov_b32_e32 v1, 0", "v_mov_b32_e32 v2, 0x5e17", "ds_write_b32 v1, v2", - "v_mov_b32_e32 v3, 0xfc00", "v_mov_b32_e32 v4, 0xbad", - "ds_write_b32 v3, v4 offset:1024", "s_waitcnt lgkmcnt(0)", - "v_mov_b32_e32 v5, 0xdead", "v_mov_b32_e32 v6, 0xdead", - "ds_read_b32 v5, v1", "ds_read_b32 v6, v3 offset:1024", "s_waitcnt lgkmcnt(0)"] - + out(5, 6), 1) - self.assertEqual((mem.get(0), mem.get(4)), (0x5E17, 0)) - - def test_out_of_range_read_returns_zero(self): - # ds_read_b32 / ds_read_u16 past the allocation (offset 1024 > 512 B): 0, not the word the index wraps to - _, mem = run_one(["v_mov_b32_e32 v1, 0", "v_mov_b32_e32 v2, 0x1234abcd", "ds_write_b32 v1, v2", - "s_waitcnt lgkmcnt(0)", "v_mov_b32_e32 v5, 0xdead", "v_mov_b32_e32 v6, 0xdead", - "ds_read_b32 v5, v1 offset:1024", "ds_read_u16 v6, v1 offset:1024", - "s_waitcnt lgkmcnt(0)"] + out(5, 6), 1) - self.assertEqual((mem.get(0), mem.get(4)), (0, 0)) - - def test_wide_access_is_checked_per_dword(self): - # A b64 write at byte 508 of a 512-byte allocation: dword 127 is written, dword 128 is dropped; read back - # as b64 it is (lo, 0). (offset:1024 elsewhere makes the shader bounds-checked.) - _, mem = run_one(["v_mov_b32_e32 v1, 0x1fc", "v_mov_b32_e32 v2, 0x1111", "v_mov_b32_e32 v3, 0x2222", - "ds_write_b64 v1, v[2:3]", "s_waitcnt lgkmcnt(0)", - "v_mov_b32_e32 v5, 0xdead", "v_mov_b32_e32 v6, 0xdead", "ds_read_b64 v[5:6], v1", - "v_mov_b32_e32 v7, 0xdead", "v_mov_b32_e32 v8, 0", "ds_read_b32 v7, v8 offset:1024", - "s_waitcnt lgkmcnt(0)"] + out(5, 6, 7), 1) - self.assertEqual((mem.get(0), mem.get(4), mem.get(8)), (0x1111, 0, 0)) - - def test_out_of_range_atomic_returns_zero_and_changes_nothing(self): - # ds_add_rtn_u32 / ds_cmpst_rtn_b32 past the allocation: the old value is 0 and word 0 (the wrap target) - # keeps its sentinel - _, mem = run_one(["v_mov_b32_e32 v1, 0", "v_mov_b32_e32 v2, 7", "ds_write_b32 v1, v2", - "s_waitcnt lgkmcnt(0)", "v_mov_b32_e32 v3, 0xfc00", "v_mov_b32_e32 v4, 5", - "v_mov_b32_e32 v5, 0xdead", "ds_add_rtn_u32 v5, v3, v4 offset:1024", - "v_mov_b32_e32 v6, 0xdead", "ds_cmpst_rtn_b32 v6, v3, v2, v4 offset:1024", - "s_waitcnt lgkmcnt(0)", "ds_read_b32 v7, v1", "s_waitcnt lgkmcnt(0)"] + out(5, 6, 7), 1) - self.assertEqual((mem.get(0), mem.get(4), mem.get(8)), (0, 0, 7)) - - def test_out_of_range_mskor_returns_zero_and_changes_nothing(self): - # ds_mskor_rtn_b32 (two atomics on one dword) past the allocation: old value 0, the wrap target untouched - _, mem = run_one(["v_mov_b32_e32 v1, 0", "v_mov_b32_e32 v2, 7", "ds_write_b32 v1, v2", - "s_waitcnt lgkmcnt(0)", "v_mov_b32_e32 v3, 0xfc00", "v_mov_b32_e32 v4, 0xff", - "v_mov_b32_e32 v5, 0xdead", "ds_mskor_rtn_b32 v5, v3, v4, v4 offset:1024", - "s_waitcnt lgkmcnt(0)", "ds_read_b32 v7, v1", "s_waitcnt lgkmcnt(0)"] + out(5, 7), 1) - self.assertEqual((mem.get(0), mem.get(4)), (0, 7)) - - def test_in_range_shader_emits_no_bounds_check(self): - # The same accesses inside a 4 KiB allocation: the wrapped power-of-two path, no check (main's SPIR-V) - spv, mem = run_one(["v_mov_b32_e32 v1, 0", "v_mov_b32_e32 v2, 0x5e17", "ds_write_b32 v1, v2", - "s_waitcnt lgkmcnt(0)", "ds_read_b32 v5, v1 offset:1020", "ds_read_b32 v6, v1", - "s_waitcnt lgkmcnt(0)"] + out(6), 8) - self.assertEqual(bounds_checks(spv), 0) - self.assertIsNone(rdna2spirv.translate.last_gen.lds_bound) - self.assertEqual(lds_index_ops(spv), {"OpBitwiseAnd"}) - self.assertEqual(mem.get(0), 0x5E17) - - def test_native_wave64_full_64k_lds_still_translates(self): - # without the flag there is no %x_buf: a 64 KiB LDS is exactly the limit - wg = workgroup_bytes(translate(128, emulate=False)) - self.assertEqual(wg, {"%lds": 65536}) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_cs_tg_size.py b/tests/semantic/test_cs_tg_size.py deleted file mode 100644 index bc4b882cc..000000000 --- a/tests/semantic/test_cs_tg_size.py +++ /dev/null @@ -1,125 +0,0 @@ -"""TG_SIZE_EN: the compute thread-group SGPR (COMPUTE_PGM_RSRC2 bit 10). - -Standard library only; no GPU, no LLVM, no game files. - -With TG_SIZE_EN set, the SGPR after the user data and the enabled workgroup ids holds the number of waves in the -workgroup in bits [5:0] and the wave's index in it in bits [11:6] (Mesa, src/amd/common/nir/ -ac_nir_lower_intrinsics_to_args.c, GFX6-10: load_num_subgroups = tg_size[5:0], load_subgroup_id = tg_size[11:6]; -a wave64 compute shader's local invocation index is mbcnt(~0, tg_size & 0xfc0)). The translator writes that value -in the prologue: thread i is in wave i / W (W = 32 or 64), the rule s_get_waveid_in_workgroup uses. It also has -the wave index in [24:20] and bit 31 set in the first wave, as measured on gfx1036 (#6446, tools/hw_oracle); -not measured on gfx1013. 91 compute programs of the pipeline library set the bit (docs/shader_library.md); -the reads of it all start with `s_and_b32 sN, sTG, 0xfc0`, and most feed that to v_mbcnt_lo_u32_b32, as below. - -Each case translates a compute listing (4 user SGPRs, workgroup id x in s4, so the thread-group SGPR is s5), runs -every invocation with run_workgroup on the CPU and has each one store a value at buffer word LocalInvocationIndex. -""" -import os -import struct -import sys -import tempfile -import unittest -import warnings - -HERE = os.path.dirname(os.path.abspath(__file__)) -ROOT = os.path.dirname(os.path.dirname(HERE)) -TOOLS_DIR = os.environ.get("LEONIDA_TOOLS_DIR") or os.path.join(ROOT, "tools") - -sys.dont_write_bytecode = True -sys.path.insert(0, TOOLS_DIR) -sys.path.insert(0, HERE) - -import rdna2spirv # noqa: E402 -import spirv_mini_interp as si # noqa: E402 - -STUB_DXBC = b"DXBC" + bytes(24) + struct.pack("> 1. - for size in ((128, 1, 1), (8, 8, 1), (4, 4, 4)): - with self.subTest(size=size): - n = size[0] * size[1] * size[2] - self.assertEqual(run(LOCAL_INDEX_W32, False, size), list(range(n))) - - def test_wave_count(self): - # Bits [5:0]: waves in the group, a partial last wave included. - for wave64, size, waves in ((True, (256, 1, 1), 4), (False, (256, 1, 1), 8), (True, (100, 1, 1), 2), - (False, (6, 6, 1), 2), (True, (1, 1, 1), 1), (False, (32, 32, 1), 32)): - with self.subTest(wave64=wave64, size=size): - got = run(["s_and_b32 s6, s5, 0x3f", "v_mov_b32 v5, s6"], wave64, size) - self.assertEqual(set(got), {waves}) - - def test_whole_value(self): - got = run(["v_mov_b32 v5, s5"], True, (192, 1, 1)) - self.assertEqual(got, [(i // 64) << 20 | (i // 64) << 6 | 3 | (0x80000000 if i < 64 else 0) - for i in range(192)]) - - def test_matches_the_gfx1036_measurement(self): - # tools/hw_oracle on gfx1036 (#6446), wave32 x 128 threads: one word per wave. - got = run(["v_mov_b32 v5, s5"], False, (128, 1, 1)) - self.assertEqual([got[32 * k] for k in range(4)], [0x80000004, 0x00100044, 0x00200084, 0x003000C4]) - self.assertEqual(got, [got[32 * (i // 32)] for i in range(128)]) - - def test_follows_the_workgroup_ids(self): - # TGID_X/Y/Z all enabled: the ids are s4, s5, s6, the thread-group SGPR is s7. - rsrc2 = 0x388 | 2 << 11 | TG_SIZE_EN - got = run(["s_and_b32 s8, s7, 0xfc0", "v_mbcnt_lo_u32_b32 v5, -1, s8", "v_mbcnt_hi_u32_b32 v5, -1, v5"], - True, (128, 1, 1), rsrc2) - self.assertEqual(got, list(range(128))) - - def test_not_written_without_the_bit(self): - spv = translate(["v_mov_b32 v5, s5", "buffer_store_dword v5, v0, s[0:3], 0 offen"], (64, 1, 1), RSRC2) - self.assertNotIn("%tgv", spv) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_cvt32_valu_validation.py b/tests/semantic/test_cvt32_valu_validation.py deleted file mode 100644 index cd38ebfe5..000000000 --- a/tests/semantic/test_cvt32_valu_validation.py +++ /dev/null @@ -1,214 +0,0 @@ -"""Operand, encoding, and modifier validation for 6 32-bit float/int conversion VALU ops. - -Covers: - - int -> f32: v_cvt_f32_u32, v_cvt_f32_i32 - - f32 -> int: v_cvt_u32_f32, v_cvt_i32_f32, v_cvt_flr_i32_f32, v_cvt_rpi_i32_f32 - -Checks arity, single-VGPR (or null) destination without modifiers, single-dword source width, -float neg/abs rejection on integer inputs and _e32 forms, sext restriction to _sdwa integer inputs, -SDWA selector/dst_unused/duplicate validation, DPP non-DPP modifier rejection, and clamp/omod -restriction to non-_e32 float-destination forms without duplicates. -Standard library only; no game files. -""" -import os -import shutil -import subprocess -import sys -import tempfile -import unittest - -HERE = os.path.dirname(os.path.abspath(__file__)) -if HERE not in sys.path: - sys.path.insert(0, HERE) - -import support # noqa: E402,F401 -from support import translate_lines # noqa: E402 -import rdna2spirv # noqa: E402 - -INT_TO_F32 = ("v_cvt_f32_u32", "v_cvt_f32_i32") -F32_TO_INT = ("v_cvt_u32_f32", "v_cvt_i32_f32", "v_cvt_flr_i32_f32", "v_cvt_rpi_i32_f32") -ALL_OPS = (*INT_TO_F32, *F32_TO_INT) - - -def _validate_spirv(spv_text): - spirv_as = shutil.which("spirv-as") - spirv_val = shutil.which("spirv-val") - if not spirv_as or not spirv_val: - return - with tempfile.TemporaryDirectory() as tmp: - asm_path = os.path.join(tmp, "shader.spvasm") - bin_path = os.path.join(tmp, "shader.spv") - with open(asm_path, "w", encoding="utf-8", newline="\n") as f: - f.write(spv_text) - r1 = subprocess.run( - [spirv_as, "--target-env", "vulkan1.2", asm_path, "-o", bin_path], - capture_output=True, text=True, - ) - if r1.returncode != 0: - raise AssertionError(f"spirv-as failed:\n{r1.stderr}") - r2 = subprocess.run( - [spirv_val, "--target-env", "vulkan1.2", bin_path], - capture_output=True, text=True, - ) - if r2.returncode != 0: - raise AssertionError(f"spirv-val failed:\n{r2.stderr}") - - -def _translate_ps(name, body_lines): - lines = list(body_lines) + ["exp mrt0 v0, v0, v0, v0 done vm", "s_endpgm"] - return translate_lines(name, lines) - - -class Cvt32ValuPositiveTests(unittest.TestCase): - def test_valid_encodings_and_modifiers_translate_and_validate(self): - for op in ALL_OPS: - for suffix in ("", "_e32", "_e64"): - with self.subTest(op=op, suffix=suffix): - spv = _translate_ps(f"ps_{op}{suffix}", [f"{op}{suffix} v0, v1"]) - _validate_spirv(spv) - with self.subTest(op=op, enc="_sdwa"): - spv = _translate_ps( - f"ps_{op}_sdwa", - [f"{op}_sdwa v0, v1 dst_sel:DWORD dst_unused:UNUSED_PAD src0_sel:DWORD"], - ) - _validate_spirv(spv) - with self.subTest(op=op, enc="_dpp"): - spv = _translate_ps( - f"ps_{op}_dpp", - [f"{op}_dpp v0, v1 quad_perm:[1,0,3,2] row_mask:0xf bank_mask:0xf"], - ) - _validate_spirv(spv) - - valid_cases = [ - "v_cvt_f32_u32_e64 v0, v1 clamp mul:2", - "v_cvt_f32_i32_e64 v0, -5 clamp div:2", - "v_cvt_f32_u32_sdwa v0, sext(v1) mul:2 clamp dst_sel:DWORD dst_unused:UNUSED_PAD src0_sel:BYTE_0", - "v_cvt_f32_i32_sdwa v0, sext(v1) dst_sel:DWORD dst_unused:UNUSED_PAD src0_sel:WORD_1", - "v_cvt_u32_f32_e64 v0, |v1|", - "v_cvt_i32_f32_e64 v0, -v1", - "v_cvt_flr_i32_f32_e64 v0, -|v1|", - "v_cvt_rpi_i32_f32_e64 v0, -v1", - "v_cvt_i32_f32_sdwa v0, -v1 dst_sel:WORD_0 dst_unused:UNUSED_PRESERVE src0_sel:DWORD", - "v_cvt_i32_f32_dpp v0, -v1 quad_perm:[1,0,3,2] row_mask:0xf bank_mask:0xf", - "v_cvt_i32_f32_e32 v0, -1.5", - "v_cvt_f32_i32_e32 v0, -7", - "v_cvt_u32_f32 null, v1", - ] - for idx, insn in enumerate(valid_cases): - with self.subTest(insn=insn): - spv = _translate_ps(f"ps_cvt32_pos_{idx}", [insn]) - _validate_spirv(spv) - - -class Cvt32ValuValidationTests(unittest.TestCase): - def assert_rejected(self, insn): - with self.assertRaises(rdna2spirv.Unsupported): - _translate_ps("ps_cvt32_bad", [insn]) - - def test_arity_and_width_rejected(self): - for op in ALL_OPS: - for bad in ( - f"{op} v0", - f"{op} v0, v1, v2", - f"{op}_e32 v0", - f"{op}_e64 v0, v1, v2", - f"{op}_sdwa v0 dst_sel:DWORD", - f"{op}_dpp v0 quad_perm:[1,0,3,2] row_mask:0xf bank_mask:0xf", - f"{op} v0, v[1:2]", - f"{op} v0, s[0:1]", - f"{op}_sdwa v0, v[1:2] dst_sel:DWORD", - f"{op}_dpp v0, v[1:2] quad_perm:[1,0,3,2] row_mask:0xf bank_mask:0xf", - ): - with self.subTest(insn=bad): - self.assert_rejected(bad) - - def test_destination_kind_width_and_modifiers_rejected(self): - for op in ALL_OPS: - for dst in ("s0", "v[0:1]", "vcc_lo", "exec_lo", "-v0", "|v0|", "sext(v0)"): - insn = f"{op} {dst}, v1" - with self.subTest(insn=insn): - self.assert_rejected(insn) - - def test_source_modifiers_rejected(self): - # Integer-input ops never accept float neg/abs, and reject sext outside _sdwa - for op in INT_TO_F32: - for bad in ( - f"{op} v0, -v1", - f"{op} v0, |v1|", - f"{op}_e64 v0, -v1", - f"{op}_e64 v0, |v1|", - f"{op}_e64 v0, neg(1)", - f"{op}_e64 v0, abs(1)", - f"{op}_sdwa v0, -v1 dst_sel:DWORD src0_sel:DWORD", - f"{op}_sdwa v0, |v1| dst_sel:DWORD src0_sel:DWORD", - f"{op}_dpp v0, -v1 quad_perm:[1,0,3,2] row_mask:0xf bank_mask:0xf", - f"{op}_dpp v0, |v1| quad_perm:[1,0,3,2] row_mask:0xf bank_mask:0xf", - f"{op} v0, sext(v1)", - f"{op}_e32 v0, sext(v1)", - f"{op}_e64 v0, sext(v1)", - f"{op}_dpp v0, sext(v1) quad_perm:[1,0,3,2] row_mask:0xf bank_mask:0xf", - ): - with self.subTest(insn=bad): - self.assert_rejected(bad) - - # Float-input ops never accept sext, and reject neg/abs on _e32 - for op in F32_TO_INT: - for bad in ( - f"{op} v0, sext(v1)", - f"{op}_e64 v0, sext(v1)", - f"{op}_sdwa v0, sext(v1) dst_sel:DWORD src0_sel:DWORD", - f"{op}_dpp v0, sext(v1) quad_perm:[1,0,3,2] row_mask:0xf bank_mask:0xf", - f"{op}_e32 v0, -v1", - f"{op}_e32 v0, |v1|", - ): - with self.subTest(insn=bad): - self.assert_rejected(bad) - - def test_instruction_modifiers_rejected(self): - for op in ALL_OPS: - for bad in ( - f"{op}_e32 v0, v1 clamp", - f"{op}_e32 v0, v1 mul:2", - f"{op}_e64 v0, v1 op_sel:[0,0]", - f"{op}_e64 v0, v1 dst_sel:DWORD", - f"{op}_e64 v0, v1 glc", - f"{op}_sdwa v0, v1 src1_sel:DWORD", - f"{op}_sdwa v0, v1 src0_sel:BOGUS", - f"{op}_sdwa v0, v1 dst_sel:BOGUS", - f"{op}_sdwa v0, v1 dst_unused:BOGUS", - f"{op}_sdwa v0, v1 src0_sel:BYTE_0 src0_sel:BYTE_1", - f"{op}_sdwa v0, v1 dst_sel:BYTE_0 dst_sel:WORD_0", - f"{op}_dpp v0, v1 quad_perm:[1,0,3,2] row_mask:0xf bank_mask:0xf clamp", - f"{op}_dpp v0, v1 quad_perm:[1,0,3,2] row_mask:0xf bank_mask:0xf mul:2", - f"{op}_dpp v0, v1 quad_perm:[1,0,3,2] row_mask:0xf bank_mask:0xf src0_sel:DWORD", - ): - with self.subTest(insn=bad): - self.assert_rejected(bad) - - # Float-dst ops reject duplicate clamp and duplicate/conflicting omod - for op in INT_TO_F32: - for bad in ( - f"{op}_e64 v0, v1 clamp clamp", - f"{op}_e64 v0, v1 mul:2 mul:4", - f"{op}_e64 v0, v1 mul:2 div:2", - f"{op}_sdwa v0, v1 mul:2 div:2 dst_sel:DWORD src0_sel:DWORD", - ): - with self.subTest(insn=bad): - self.assert_rejected(bad) - - # Integer-dst ops reject clamp and omod on every form - for op in F32_TO_INT: - for bad in ( - f"{op} v0, v1 clamp", - f"{op} v0, v1 mul:2", - f"{op}_e64 v0, v1 clamp", - f"{op}_e64 v0, v1 div:2", - f"{op}_sdwa v0, v1 clamp dst_sel:DWORD src0_sel:DWORD", - f"{op}_sdwa v0, v1 mul:2 dst_sel:DWORD src0_sel:DWORD", - ): - with self.subTest(insn=bad): - self.assert_rejected(bad) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_cvt_f16_omod.py b/tests/semantic/test_cvt_f16_omod.py deleted file mode 100644 index 24a6db597..000000000 --- a/tests/semantic/test_cvt_f16_omod.py +++ /dev/null @@ -1,174 +0,0 @@ -"""Semantic regression tests for v_cvt_f16_f32 VOP3 output modifiers across RNE and MODE RTZ. - -Standard library only; no GPU, no LLVM, no game files. - -Covers the native RDNA2 (gfx1036) measurements via tools/rdna2spirv.py + spirv_mini_interp: - * div:2 underflowing a negative exponent-1 normal (-2^-14 .. -(2 - 2^-10) * 2^-14) preserves the sign bit (-0.0, - 0x8000) in both RNE and MODE toward-zero, while exponent-0 inputs (-0.0, -2^-15) give +0.0 (0x0000) and clamp - still turns -0.0 into +0.0; - * under dynamic MODE toward-zero (s_setreg_imm32_b32 hwreg(HW_REG_MODE, 2, 2), 3), finite mul:2/mul:4 overflow - saturates to +-65504 (0x7bff / 0xfbff), true +-inf stays +-inf, +-65520 / FLT_MAX with div:2 convert to +-65504 - before halving to +-32752 (0x77ff / 0xf7ff), and switching back to RNE (0) restores +-inf; - * clamp runs after omod, preserving the seeded high half of vdst. -""" -import os -import re -import struct -import sys -import unittest - -HERE = os.path.dirname(os.path.abspath(__file__)) -sys.dont_write_bytecode = True -if HERE not in sys.path: - sys.path.insert(0, HERE) - -import support - -RTZ = "s_setreg_imm32_b32 hwreg(HW_REG_MODE, 2, 2), 3" -RNE = "s_setreg_imm32_b32 hwreg(HW_REG_MODE, 2, 2), 0" - - -def _f32_bits(x: float) -> int: - return struct.unpack(" tuple[str, list[int]]: - """Translate and run up to four (f32_bits, mod_suffix) cases on one fragment, returning (spvasm, mrt0_words).""" - assert len(cases) == 4 - lines = list(prefix) - for i, (bits, mod) in enumerate(cases): - suffix = f" {mod}" if mod else "" - lines += [ - f"v_mov_b32 v{10 + i}, {bits:#010x}", - f"v_mov_b32 v{i}, 0xaaaa5555", - f"v_cvt_f16_f32_e64 v{i}, v{10 + i}{suffix}", - ] - lines += ["exp mrt0 v0, v1, v2, v3 done vm", "s_endpgm"] - spv = support.translate_lines("ps_cvt_f16_omod", lines) - return spv, support.mrt0_words(spv) - - -class CvtF16OmodSemanticTests(unittest.TestCase): - def test_div2_exp1_underflow_preserves_sign_rne_and_rtz(self): - exp1_cases = [ - (_f32_bits(-(2.0 ** -14)), "div:2"), # -2^-14 -> 0x8400 -> 0x8000 - (_f32_bits(-1.5 * (2.0 ** -14)), "div:2"), # -1.5*2^-14 -> 0x8600 -> 0x8000 - (0xB8FFE000, "div:2"), # -(2 - 2^-10) * 2^-14 -> 0x87ff -> 0x8000 - (0xB8FFFE00, "div:2"), # RNE rounds to -2^-13 (0x8800 -> 0x8400); RTZ keeps 0x87ff (-> 0x8000) - ] - other_cases = [ - (_f32_bits(2.0 ** -14), "div:2"), # +2^-14 -> +0.0 - (0x80000000, "div:2"), # -0.0 (exp 0) -> +0.0 - (_f32_bits(-(2.0 ** -15)), "div:2"), # -2^-15 (exp 0) -> +0.0 - (_f32_bits(-(2.0 ** -14)), "clamp div:2"), # -0.0 clamped -> +0.0 - ] - for mode_prefix, exp4 in (([], 0xAAAA8400), ([RTZ], 0xAAAA8000)): - with self.subTest(rtz=bool(mode_prefix)): - _, got_exp1 = _run_cvt_quad(exp1_cases, prefix=mode_prefix) - self.assertEqual(got_exp1, [0xAAAA8000, 0xAAAA8000, 0xAAAA8000, exp4]) - _, got_other = _run_cvt_quad(other_cases, prefix=mode_prefix) - self.assertEqual(got_other, [0xAAAA0000, 0xAAAA0000, 0xAAAA0000, 0xAAAA0000]) - - def test_rtz_omod_overflow_and_div2_order(self): - rtz_overflow = [ - (_f32_bits(32768.0), "mul:2"), - (_f32_bits(-32768.0), "mul:2"), - (_f32_bits(16384.0), "mul:4"), - (_f32_bits(-16384.0), "mul:4"), - ] - _, got_ov = _run_cvt_quad(rtz_overflow, prefix=[RTZ]) - self.assertEqual(got_ov, [0xAAAA7BFF, 0xAAAAFBFF, 0xAAAA7BFF, 0xAAAAFBFF]) - - rtz_div2_and_inf = [ - (_f32_bits(65504.0), "mul:2"), - (_f32_bits(65520.0), "div:2"), - (_f32_bits(-65520.0), "div:2"), - (0x7F7FFFFF, "div:2"), # FLT_MAX -> 65504 -> 32752 - ] - _, got_div = _run_cvt_quad(rtz_div2_and_inf, prefix=[RTZ]) - self.assertEqual(got_div, [0xAAAA7BFF, 0xAAAA77FF, 0xAAAAF7FF, 0xAAAA77FF]) - - rtz_true_inf = [ - (0x7F800000, "mul:2"), - (0xFF800000, "mul:4"), - (0x7F800000, "div:2"), - (0xFF800000, "div:2"), - ] - _, got_inf = _run_cvt_quad(rtz_true_inf, prefix=[RTZ]) - self.assertEqual(got_inf, [0xAAAA7C00, 0xAAAAFC00, 0xAAAA7C00, 0xAAAAFC00]) - - # Switching RTZ -> RNE in one program matches the dynamic MODE write semantics. - switch_lines = [ - RTZ, - f"v_mov_b32 v10, {_f32_bits(32768.0):#010x}", - f"v_mov_b32 v11, {_f32_bits(65520.0):#010x}", - "v_mov_b32 v0, 0xaaaa5555", - "v_mov_b32 v1, 0xaaaa5555", - "v_mov_b32 v2, 0xaaaa5555", - "v_mov_b32 v3, 0xaaaa5555", - "v_cvt_f16_f32_e64 v0, v10 mul:2", - "v_cvt_f16_f32_e64 v1, v11 div:2", - RNE, - "v_cvt_f16_f32_e64 v2, v10 mul:2", - "v_cvt_f16_f32_e64 v3, v11 div:2", - "exp mrt0 v0, v1, v2, v3 done vm", - "s_endpgm", - ] - spv = support.translate_lines("ps_cvt_mode_switch", switch_lines) - self.assertEqual(support.mrt0_words(spv), [0xAAAA7BFF, 0xAAAA77FF, 0xAAAA7C00, 0xAAAA7C00]) - - def test_clamp_with_omod_order(self): - c1 = [ - (_f32_bits(0.75), "clamp mul:2"), - (_f32_bits(0.75), "clamp div:2"), - (_f32_bits(2.0), "clamp mul:2"), - (_f32_bits(-0.5), "clamp mul:2"), - ] - c2 = [ - (_f32_bits(65520.0), "clamp mul:2"), - (0xFF7FFFFF, "clamp div:2"), # -FLT_MAX - (0x7F800000, "clamp div:2"), # +inf - (0xFF800000, "clamp mul:2"), # -inf - ] - for mode_prefix in ([], [RTZ]): - with self.subTest(rtz=bool(mode_prefix)): - self.assertEqual(_run_cvt_quad(c1, prefix=mode_prefix)[1], [0xAAAA3C00, 0xAAAA3600, 0xAAAA3C00, 0xAAAA0000]) - self.assertEqual(_run_cvt_quad(c2, prefix=mode_prefix)[1], [0xAAAA3C00, 0xAAAA0000, 0xAAAA3C00, 0xAAAA0000]) - - def test_negative_control_div2_signed_zero(self): - spv, got = _run_cvt_quad([ - (_f32_bits(-(2.0 ** -14)), "div:2"), - (_f32_bits(1.0), ""), - (_f32_bits(1.0), ""), - (_f32_bits(1.0), ""), - ]) - self.assertEqual(got[0], 0xAAAA8000) - # Sabotage the e == 1 underflow select to drop sign (reverting to +0.0). - bad, n = re.subn( - r"(%\w+ = OpIEqual %bool %\w+ %c1\n\s*" - r"%\w+ = OpBitwiseAnd %uint %\w+ %c8000\n\s*" - r"%\w+ = OpSelect %uint %\w+ )(%\w+)( %\w+)", - r"\1%c0\3", - spv, - ) - self.assertEqual(n, 1) - self.assertEqual(support.mrt0_words(bad)[0], 0xAAAA0000) - - def test_negative_control_rtz_saturation(self): - spv, got = _run_cvt_quad( - [ - (_f32_bits(32768.0), "mul:2"), - (_f32_bits(1.0), ""), - (_f32_bits(1.0), ""), - (_f32_bits(1.0), ""), - ], - prefix=[RTZ], - ) - self.assertEqual(got[0], 0xAAAA7BFF) - bad, n = re.subn(r"OpBitwiseOr %uint (%\w+) %c7bff", r"OpBitwiseOr %uint \1 %c7c00", spv) - self.assertGreaterEqual(n, 1) - self.assertEqual(support.mrt0_words(bad)[0], 0xAAAA7C00) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_cvt_norm_mods.py b/tests/semantic/test_cvt_norm_mods.py deleted file mode 100644 index af8e059d3..000000000 --- a/tests/semantic/test_cvt_norm_mods.py +++ /dev/null @@ -1,254 +0,0 @@ -"""Semantic interpreter and SPIR-V validation tests for RDNA2 output modifiers on -v_cvt_norm_{i16,u16}_f16 and v_cvt_pknorm_{i16,u16}_f32. - -Covers native RDNA2 (gfx1036, wave32 & wave64) measured hardware no-op rules: -- v_cvt_norm_i16_f16 / v_cvt_norm_u16_f16: VOP3 clamp, mul:2, mul:4, div:2 (and combinations) - and SDWA clamp are hardware no-ops while still preserving the unwritten destination half; - unsupported modifiers and invalid form/modifier pairs raise Unsupported. -- v_cvt_pknorm_i16_f32 / v_cvt_pknorm_u16_f32: VOP3 clamp is a hardware no-op; mul:*/div:*/op_sel - raise Unsupported. -""" -from __future__ import annotations - -import os -import shutil -import struct -import subprocess -import sys -import tempfile -import unittest -import warnings - -HERE = os.path.dirname(os.path.abspath(__file__)) -ROOT = os.path.dirname(os.path.dirname(HERE)) -TOOLS_DIR = os.environ.get("LEONIDA_TOOLS_DIR") or os.path.join(ROOT, "tools") - -sys.dont_write_bytecode = True -for p in (TOOLS_DIR, HERE): - if p not in sys.path: - sys.path.insert(0, p) - -import cvt_norm_mods_probe as cnp # noqa: E402 -import rdna2spirv # noqa: E402 -import spirv_mini_interp as si # noqa: E402 - -M16 = 0xFFFF -M32 = 0xFFFFFFFF -SEED_DST = 0xCAFE1234 -STUB_DXBC = b"DXBC" + bytes(24) + struct.pack(" str: - if _TMP_DIR is None: - setUpModule() - if export_tail is None: - export_tail = [ - "v_and_b32 v5, 0xffff, v0", - "v_lshrrev_b32 v6, 16, v0", - "v_or_b32 v5, 0x40000000, v5", - "v_or_b32 v6, 0x40000000, v6", - "exp mrt0 v5, v6, v5, v5 done vm", - ] - asm_text = "; test_cvt_norm_mods\n" + "".join(f"\t{ln}\n" for ln in list(lines) + export_tail) + "\ts_endpgm\n" - with open(_SRC_PATH, "w", encoding="utf-8", newline="\n") as f: - f.write(asm_text) - with warnings.catch_warnings(): - warnings.simplefilter("ignore", ResourceWarning) - return rdna2spirv.translate(_SRC_PATH) - - -def run_v0(lines: list[str]) -> tuple[str, int]: - spv = translate_ps(lines) - lo, hi = si.run_fragment(spv)["%out_mrt0"][:2] - assert (lo >> 16) == 0x4000 and (hi >> 16) == 0x4000, (hex(lo), hex(hi)) - return spv, (lo & M16) | ((hi & M16) << 16) - - -def validate_spirv(spv_text: str) -> None: - spirv_as = shutil.which("spirv-as") - spirv_val = shutil.which("spirv-val") - if not spirv_as or not spirv_val: - return - with tempfile.TemporaryDirectory() as d: - asm_p = os.path.join(d, "s.spvasm") - bin_p = os.path.join(d, "s.spv") - with open(asm_p, "w", encoding="utf-8", newline="\n") as f: - f.write(spv_text) - r1 = subprocess.run([spirv_as, "--target-env", "vulkan1.2", asm_p, "-o", bin_p], capture_output=True, text=True) - if r1.returncode != 0: - raise AssertionError(f"spirv-as failed: {r1.stderr}") - r2 = subprocess.run([spirv_val, "--target-env", "vulkan1.2", bin_p], capture_output=True, text=True) - if r2.returncode != 0: - raise AssertionError(f"spirv-val failed: {r2.stderr}") - - -class CvtNormOutputModsTests(unittest.TestCase): - def test_vop3_output_modifiers_match_plain_across_edges_and_ties(self): - edges = ( - 0x0000, 0x8000, # +0, -0 - 0x0001, 0x8001, 0x03FF, # subnormals - 0x37FF, 0x3800, 0x3801, # +0.5 single-rounding ties - 0xB7FF, 0xB800, 0xB801, # -0.5 single-rounding ties - 0x3C00, 0xBC00, # +-1.0 - 0x4000, 0xC000, # +-2.0 - 0x7C00, 0xFC00, # +-inf - 0x7E00, 0x7C01, 0xFE00, # qNaN / sNaN - ) - for op in cnp.NORM_F16_OPS: - snorm = op == "v_cvt_norm_i16_f16" - for mod in ("clamp", "mul:2", "mul:4", "div:2", "clamp mul:2", "clamp div:2"): - for h in edges: - want = (SEED_DST & 0xFFFF0000) | cnp.expected_norm_f16(h, snorm) - with self.subTest(op=op, mod=mod, h=hex(h)): - _, got = run_v0([ - f"v_mov_b32 v1, {(0xDEAD0000 | h):#x}", - f"v_mov_b32 v0, {SEED_DST:#x}", - f"{op}_e64 v0, v1 {mod}", - ]) - self.assertEqual(got, want) - - def test_vop3_abs_neg_and_opsel_with_output_modifiers(self): - # v1 = {hi=+0.75 (0x3A00), lo=-0.5 (0xB800)} - packed = 0x3A00B800 - cases = ( - ("v_cvt_norm_i16_f16_e64 v0, |v1| clamp", (SEED_DST & 0xFFFF0000) | cnp.expected_norm_f16(0x3800, True)), - ("v_cvt_norm_i16_f16_e64 v0, -v1 mul:2", (SEED_DST & 0xFFFF0000) | cnp.expected_norm_f16(0x3800, True)), - ("v_cvt_norm_u16_f16_e64 v0, -|v1| div:2", (SEED_DST & 0xFFFF0000) | cnp.expected_norm_f16(0xB800, False)), - ("v_cvt_norm_i16_f16_e64 v0, v1 op_sel:[1,0] clamp", (SEED_DST & 0xFFFF0000) | cnp.expected_norm_f16(0x3A00, True)), - ("v_cvt_norm_u16_f16_e64 v0, |v1| op_sel:[0,1] mul:2", (cnp.expected_norm_f16(0x3800, False) << 16) | (SEED_DST & M16)), - ("v_cvt_norm_i16_f16_e64 v0, -v1 op_sel:[1,1] div:2", (cnp.expected_norm_f16(0xBA00, True) << 16) | (SEED_DST & M16)), - ) - for inst, want in cases: - with self.subTest(inst=inst): - _, got = run_v0([f"v_mov_b32 v1, {packed:#x}", f"v_mov_b32 v0, {SEED_DST:#x}", inst]) - self.assertEqual(got, want) - - def test_sdwa_clamp_across_word_and_dst_unused_forms(self): - for op in cnp.NORM_F16_OPS: - want_words = cnp.expected_sdwa_words(op) - for idx, (label, seed_v0, src_v1, _, src_expr, tail) in enumerate(cnp.SDWA_CASES): - with self.subTest(op=op, case=label): - _, got_plain = run_v0([ - f"v_mov_b32 v0, {seed_v0:#x}", - f"v_mov_b32 v1, {src_v1:#x}", - f"{op}_sdwa v0, {src_expr} {tail}", - ]) - _, got_clamp = run_v0([ - f"v_mov_b32 v0, {seed_v0:#x}", - f"v_mov_b32 v1, {src_v1:#x}", - f"{op}_sdwa v0, {src_expr} clamp {tail}", - ]) - self.assertEqual(got_plain, want_words[idx]) - self.assertEqual(got_clamp, want_words[idx]) - - def test_pknorm_clamp_matches_plain_across_edges_nearties_and_aliasing(self): - pairs = ( - (0x00000000, 0x80000000), # +0, -0 - (0x00000001, 0x807FFFFF), # subnormals - (0x38400180, 0x3C014103), # single-rounding near-ties (i16) - (0x37C000C0, 0x3B028083), # single-rounding near-ties (u16) - (0x3F000000, 0xBF000000), # +-0.5 - (0x3F800000, 0xBF800000), # +-1.0 - (0x40000000, 0xC0000000), # +-2.0 (clamped to +-1.0) - (0x7F800000, 0xFF800000), # +-inf - (0x7FC00000, 0xFF800001), # qNaN / sNaN - ) - for op in cnp.PKNORM_F32_OPS: - for a, b in pairs: - want = cnp.expected_pknorm_f32(op, a, b) - with self.subTest(op=op, a=hex(a), b=hex(b)): - _, got = run_v0([ - f"v_mov_b32 v1, {a:#x}", - f"v_mov_b32 v2, {b:#x}", - "v_mov_b32 v0, 0xdeadbeef", - f"{op} v0, v1, v2 clamp", - ]) - self.assertEqual(got, want) - # Source modifiers + destination aliasing (v0 == src0) with clamp - want_alias = cnp.expected_pknorm_f32(op, 0xBF000000, 0x3F000000) - _, got_alias = run_v0([ - "v_mov_b32 v0, 0x3f000000", # +0.5 -> negated to -0.5 - "v_mov_b32 v1, 0xbf000000", # -0.5 -> abs to +0.5 - f"{op} v0, -v0, |v1| clamp", - ]) - self.assertEqual(got_alias, want_alias) - - def test_inactive_exec_lane_preserved(self): - for inst in ( - "v_cvt_norm_i16_f16_e64 v0, v1 clamp", - "v_cvt_norm_u16_f16_e64 v0, v1 mul:2", - "v_cvt_norm_i16_f16_sdwa v0, v1 clamp dst_sel:WORD_1 dst_unused:UNUSED_PRESERVE src0_sel:WORD_1", - "v_cvt_pknorm_i16_f32 v0, v1, v2 clamp", - "v_cvt_pknorm_u16_f32 v0, v1, v2 clamp", - ): - with self.subTest(inst=inst): - _, got = run_v0([ - "v_mov_b32 v0, 0xdeadbeef", - "v_mov_b32 v1, 0x38003c00", - "v_mov_b32 v2, 0x3f000000", - "s_mov_b32 exec_lo, 0", - inst, - "s_mov_b32 exec_lo, 1", - ]) - self.assertEqual(got, 0xDEADBEEF) - - def test_spirv_val_combined_shader(self): - spv = translate_ps([ - "v_mov_b32 v0, 0x12345678", - "v_mov_b32 v1, 0x3800b800", - "v_mov_b32 v2, 0x3f000000", - "v_mov_b32 v3, 0xbf000000", - "v_cvt_norm_i16_f16_e64 v0, v1 clamp", - "v_cvt_norm_i16_f16_e64 v0, v1 mul:2", - "v_cvt_norm_u16_f16_e64 v0, |v1| div:2", - "v_cvt_norm_u16_f16_e64 v0, v1 clamp mul:4", - "v_cvt_norm_i16_f16_sdwa v0, v1 clamp dst_sel:WORD_1 dst_unused:UNUSED_PRESERVE src0_sel:WORD_1", - "v_cvt_pknorm_i16_f32 v0, v2, v3 clamp", - "v_cvt_pknorm_u16_f32 v0, -v3, |v2| clamp", - ]) - validate_spirv(spv) - - def test_rejected_invalid_modifiers_and_forms(self): - bad_lines = ( - "v_cvt_norm_i16_f16_e64 v0, v1 mul:8", - "v_cvt_norm_u16_f16_e64 v0, v1 div:4", - "v_cvt_norm_i16_f16_sdwa v0, v1 mul:2 dst_sel:WORD_1 dst_unused:UNUSED_PRESERVE src0_sel:WORD_1", - "v_cvt_norm_u16_f16_sdwa v0, v1 op_sel:[1,0] dst_sel:WORD_0 dst_unused:UNUSED_PAD src0_sel:WORD_0", - "v_cvt_norm_i16_f16_e32 v0, v1 clamp", - "v_cvt_norm_u16_f16_dpp v0, v1 clamp quad_perm:[0,1,2,3]", - "v_cvt_pknorm_i16_f32 v0, v1, v2 mul:2", - "v_cvt_pknorm_u16_f32 v0, v1, v2 div:2", - "v_cvt_pknorm_i16_f32 v0, v1, v2 op_sel:[1,0,0]", - ) - for line in bad_lines: - with self.subTest(line=line): - with self.assertRaises(rdna2spirv.Unsupported): - translate_ps([ - "v_mov_b32 v1, 0x3800", - "v_mov_b32 v2, 0x3f000000", - line, - ]) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_cvt_pk_u8.py b/tests/semantic/test_cvt_pk_u8.py deleted file mode 100644 index 0895f22b6..000000000 --- a/tests/semantic/test_cvt_pk_u8.py +++ /dev/null @@ -1,29 +0,0 @@ -"""v_cvt_pk_u8_f32 against the words measured natively on RDNA2 hardware (cs_cvt_pk_u8.asm).""" -import os -import sys -import unittest - -import support - -sys.path.insert(0, os.path.join(support.ROOT, "runtime", "test", "shaders")) -from check import CVT_PK_U8_WORDS -from compute_fixture import compute_header - -OUT_V = [0, 0, 32, 0x31016FAC] # the output V# in s[0:3]: base 0, 32 bytes, FORMAT 32_FLOAT, DST_SEL xyzw - - -class CvtPkU8Test(unittest.TestCase): - def test_hardware_words(self): - asm = os.path.join(support.ROOT, "runtime", "test", "shaders", "cs_cvt_pk_u8.asm") - spv = support.translate_fixture("cs_cvt_pk_u8", fssm=bytes(compute_header(asm))) - for lane, want in enumerate(CVT_PK_U8_WORDS): - with self.subTest(lane=lane): - memory = {} - support.run_fragment( - spv, inputs={"%wg_id": (0, 0, 0), "%local_id": (lane, 0, 0)}, - push_constants=OUT_V + [0] * 28, memory=memory) - self.assertEqual(memory, {4 * lane: want}) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_cvt_pknorm_f16_mods.py b/tests/semantic/test_cvt_pknorm_f16_mods.py deleted file mode 100644 index 81a3da906..000000000 --- a/tests/semantic/test_cvt_pknorm_f16_mods.py +++ /dev/null @@ -1,185 +0,0 @@ -"""Semantic SPIR-V and interpreter tests for RDNA2 v_cvt_pknorm_i16_f16 / u16_f16 modifiers. - -Covers every textual probe case from tools/cvt_pknorm_f16_probe.py across plain, VOP3 `clamp` (hardware no-op), -and destination `op_sel:[s0,s1,1]` (16-bit left shift zeroing D[15:0] and overwriting D), checks byte-identical -SPIR-V emission for `clamp`, verifies `OpShiftLeftLogical` emission on dst `op_sel`, checks inactive EXEC lane -preservation, asserts `Unsupported` on rejected modifiers/forms, and validates SPIR-V with spirv-as/spirv-val. -Standard library only; synthetic inputs only. -""" -import os -import shutil -import struct -import subprocess -import sys -import tempfile -import unittest -import warnings - -HERE = os.path.dirname(os.path.abspath(__file__)) -ROOT = os.path.dirname(os.path.dirname(HERE)) -TOOLS = os.environ.get("LEONIDA_TOOLS_DIR") or os.path.join(ROOT, "tools") -sys.dont_write_bytecode = True -for p in (TOOLS, HERE): - if p not in sys.path: - sys.path.insert(0, p) - -import cvt_pknorm_f16_probe as probe # noqa: E402 -import rdna2spirv # noqa: E402 -import spirv_mini_interp as si # noqa: E402 - -STUB_DXBC = b"DXBC" + bytes(24) + struct.pack("> 16 == 0x4000 and hi >> 16 == 0x4000, (hex(lo), hex(hi)) - return (lo & 0xFFFF) | ((hi & 0xFFFF) << 16), spv - - -def _ps_case_lines(op, c, clamp): - return [ln.replace("v_mov_b32_e32 ", "v_mov_b32 ") for ln in probe.case_instruction(op, c, clamp)] - - -class CvtPknormF16ModsSemanticTests(unittest.TestCase): - def test_all_probe_cases_plain_and_clamp(self): - for op in probe.OPS: - for c in probe.CASES: - if c.raw_omod is not None: - continue - want_plain = probe.expected_pknorm_f16( - op, c.src0, c.src1, sel=c.sel, dhi=bool(c.dhi), clamp=False, - src0_abs=c.src0_abs, src0_neg=c.src0_neg, src1_abs=c.src1_abs, src1_neg=c.src1_neg, - ) - want_clamp = probe.expected_pknorm_f16( - op, c.src0, c.src1, sel=c.sel, dhi=bool(c.dhi), clamp=True, - src0_abs=c.src0_abs, src0_neg=c.src0_neg, src1_abs=c.src1_abs, src1_neg=c.src1_neg, - ) - self.assertEqual(want_plain, want_clamp) - with self.subTest(op=op, case=c.name): - got_plain, spv_plain = _run_v8(_ps_case_lines(op, c, False)) - got_clamp, spv_clamp = _run_v8(_ps_case_lines(op, c, True)) - self.assertEqual(got_plain, want_plain) - self.assertEqual(got_clamp, want_clamp) - self.assertEqual(spv_clamp, spv_plain) - - def test_dst_opsel_shift_and_overwrite(self): - for op in probe.OPS: - with self.subTest(op=op): - got_plain, spv_plain = _run_v8([ - "v_mov_b32 v1, 0x3c003400", - "v_mov_b32 v2, 0xbc003801", - "v_mov_b32 v8, 0xdeadbeef", - f"{op} v8, v1, v2 op_sel:[0,0,0]", - ]) - got_dhi, spv_dhi = _run_v8([ - "v_mov_b32 v1, 0x3c003400", - "v_mov_b32 v2, 0xbc003801", - "v_mov_b32 v8, 0xdeadbeef", - f"{op} v8, v1, v2 op_sel:[0,0,1]", - ]) - self.assertEqual(got_dhi, (got_plain << 16) & 0xFFFFFFFF) - self.assertEqual(got_dhi & 0xFFFF, 0) - shift_count_plain = sum(1 for ln in spv_plain.splitlines() if "OpShiftLeftLogical %uint" in ln) - shift_count_dhi = sum(1 for ln in spv_dhi.splitlines() if "OpShiftLeftLogical %uint" in ln) - self.assertEqual(shift_count_dhi, shift_count_plain + 1) - - def test_inactive_exec_preserves_dst(self): - sentinel = 0xA5A55A5A - for op in probe.OPS: - for mod in ("clamp", "op_sel:[0,0,1]", "op_sel:[0,0,1] clamp"): - with self.subTest(op=op, mod=mod): - got, _ = _run_v8([ - "v_mov_b32 v1, 0x3c003400", - "v_mov_b32 v2, 0xbc003801", - f"v_mov_b32 v8, {sentinel:#010x}", - "s_mov_b32 exec_lo, 0", - f"{op} v8, v1, v2 {mod}", - "s_mov_b32 exec_lo, -1", - ]) - self.assertEqual(got, sentinel) - - def test_rejected_invalid_modifiers(self): - for op in probe.OPS: - for bad in ( - f"{op} v8, v1, v2 mul:2", - f"{op} v8, v1, v2 mul:4", - f"{op} v8, v1, v2 div:2", - f"{op} v8, v1, v2 op_sel_hi:[1,1]", - f"{op} v8, v1, v2 neg_lo:[1,0]", - f"{op} v8, v1, v2 neg_hi:[0,1]", - f"{op} v8, v1, v2 op_sel:[0,0,0,1]", - f"{op} v8, v1, v2 op_sel:[2,0,0]", - f"{op} v8, v1, v2 op_sel:[]", - f"{op} v8, v1, v2 op_sel:[0,0,1]bad", - f"{op} v8, v1, v2 op_sel:[0,0,0] op_sel:[1,0,0]", - f"{op}_dpp v8, v1, v2 row_mirror", - f"{op}_sdwa v8, v1, v2", - f"{op} v8, v1, v2 foo", - ): - with self.subTest(line=bad): - with self.assertRaises(rdna2spirv.Unsupported): - _translate([ - "v_mov_b32 v1, 0x3c003400", - "v_mov_b32 v2, 0xbc003801", - bad, - "exp mrt0 v8, v8, v8, v8 done vm", - "s_endpgm", - ]) - - def test_spirv_val_vulkan12(self): - spirv_as = shutil.which("spirv-as") - spirv_val = shutil.which("spirv-val") - if not spirv_as or not spirv_val: - self.skipTest("spirv-as / spirv-val not on PATH") - body = [ - "s_mov_b32 s4, 0x3c003400", - "v_mov_b32 v1, 0x3c003801", - "v_mov_b32 v2, 0xbc00b801", - "v_cvt_pknorm_i16_f16 v8, v1, v2 clamp", - "v_cvt_pknorm_i16_f16 v8, |s4|, -v2 op_sel:[1,0,1] clamp", - "v_cvt_pknorm_u16_f16 v9, v8, 0.5 op_sel:[0,0,1]", - "v_cvt_pknorm_u16_f16 v8, -|v1|, v9 op_sel:[0,1,0] clamp", - "v_xor_b32 v8, v8, v9", - ] - _, spv = _run_v8(body) - with tempfile.TemporaryDirectory() as td: - spvasm = os.path.join(td, "shader.spvasm") - spvbin = os.path.join(td, "shader.spv") - with open(spvasm, "w", encoding="utf-8", newline="\n") as f: - f.write(spv) - subprocess.run([spirv_as, "--target-env", "vulkan1.2", spvasm, "-o", spvbin], check=True) - subprocess.run([spirv_val, "--target-env", "vulkan1.2", spvbin], check=True) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_div_valu_validation.py b/tests/semantic/test_div_valu_validation.py deleted file mode 100644 index 7bed0bb38..000000000 --- a/tests/semantic/test_div_valu_validation.py +++ /dev/null @@ -1,191 +0,0 @@ -"""Operand, encoding, and modifier validation for the 5 IEEE-754 division VALU ops in tools/rdna2spirv.py. - -Covers: - - v_div_fixup_f16, v_div_fixup_f32, v_div_fixup_f64 - - v_div_fmas_f32, v_div_fmas_f64 - -Checks arity, destination register kind/width/modifiers, source widths, sext rejection, -VOP3-only encoding enforcement (rejecting _e32/_sdwa/_dpp), op_sel syntax/arity/bit-value/duplicate -validation on v_div_fixup_f16 and op_sel rejection on f32/f64 forms, unknown/duplicate/conflicting -output modifiers, plus positive controls with live SPIR-V assembly and validation. -Standard library only; no game files. -""" -import os -import shutil -import subprocess -import sys -import tempfile -import unittest - -HERE = os.path.dirname(os.path.abspath(__file__)) -if HERE not in sys.path: - sys.path.insert(0, HERE) - -import support # noqa: E402,F401 -from support import translate_lines # noqa: E402 -import rdna2spirv # noqa: E402 - -DIV_1DWORD_OPS = ("v_div_fixup_f16", "v_div_fixup_f32", "v_div_fmas_f32") -DIV_2DWORD_OPS = ("v_div_fixup_f64", "v_div_fmas_f64") -ALL_DIV_OPS = (*DIV_1DWORD_OPS, *DIV_2DWORD_OPS) -STRICT_OMOD_OPS = ("v_div_fixup_f32", "v_div_fmas_f32", "v_div_fmas_f64") - - -def _validate_spirv(spv_text): - spirv_as = shutil.which("spirv-as") - spirv_val = shutil.which("spirv-val") - if not spirv_as or not spirv_val: - return - with tempfile.TemporaryDirectory() as tmp: - asm_path = os.path.join(tmp, "shader.spvasm") - bin_path = os.path.join(tmp, "shader.spv") - with open(asm_path, "w", encoding="utf-8", newline="\n") as f: - f.write(spv_text) - r1 = subprocess.run( - [spirv_as, "--target-env", "vulkan1.2", asm_path, "-o", bin_path], - capture_output=True, text=True, - ) - if r1.returncode != 0: - raise AssertionError(f"spirv-as failed:\n{r1.stderr}") - r2 = subprocess.run( - [spirv_val, "--target-env", "vulkan1.2", bin_path], - capture_output=True, text=True, - ) - if r2.returncode != 0: - raise AssertionError(f"spirv-val failed:\n{r2.stderr}") - - -def _translate_ps(name, body_lines): - lines = list(body_lines) + ["exp mrt0 v0, v1, v0, v1 done vm", "s_endpgm"] - return translate_lines(name, lines) - - -def _valid_insn(op, suffix="", mods=""): - tail = f" {mods}" if mods else "" - if op in DIV_1DWORD_OPS: - return f"{op}{suffix} v0, v1, v2, v3{tail}" - return f"{op}{suffix} v[0:1], v[2:3], v[4:5], v[6:7]{tail}" - - -class DivValuPositiveTests(unittest.TestCase): - def test_valid_forms_translate_and_validate(self): - for op in ALL_DIV_OPS: - for suffix in ("", "_e64"): - with self.subTest(op=op, suffix=suffix): - spv = _translate_ps(f"ps_{op}{suffix}", [_valid_insn(op, suffix)]) - _validate_spirv(spv) - - valid_cases = [ - "v_div_fixup_f16 v0, -v1, |v2|, -|v3| op_sel:[1,0,1,1] clamp mul:2", - "v_div_fixup_f32 v0, -v1, |v2|, -|v3| clamp mul:2", - "v_div_fixup_f32_e64 v0, v1, v2, v3 div:2", - "v_div_fixup_f32 null, v1, v2, v3", - "v_div_fixup_f64 v[0:1], -v[2:3], |v[4:5]|, v[6:7] clamp mul:4", - "v_div_fmas_f32 v0, -v1, |v2|, v3 clamp mul:2", - "v_div_fmas_f32 null, v1, v2, v3", - "v_div_fmas_f64 v[0:1], -v[2:3], |v[4:5]|, v[6:7] clamp div:2", - ] - for idx, insn in enumerate(valid_cases): - with self.subTest(insn=insn): - spv = _translate_ps(f"ps_div_pos_{idx}", [insn]) - _validate_spirv(spv) - - -class DivValuValidationTests(unittest.TestCase): - def assert_rejected(self, insn): - with self.assertRaises(rdna2spirv.Unsupported): - _translate_ps("ps_div_bad", [insn]) - - def test_arity_rejected(self): - for op in DIV_1DWORD_OPS: - for bad in (f"{op} v0, v1, v2", f"{op} v0, v1, v2, v3, v4"): - with self.subTest(insn=bad): - self.assert_rejected(bad) - for op in DIV_2DWORD_OPS: - for bad in ( - f"{op} v[0:1], v[2:3], v[4:5]", - f"{op} v[0:1], v[2:3], v[4:5], v[6:7], v[8:9]", - ): - with self.subTest(insn=bad): - self.assert_rejected(bad) - - def test_destination_kind_width_and_modifiers_rejected(self): - for op in DIV_1DWORD_OPS: - wrong_dsts = ("s0", "v[0:1]", "vcc_lo", "exec_lo", "-v0", "|v0|", "sext(v0)") - if op == "v_div_fixup_f16": - wrong_dsts = (*wrong_dsts, "null") - for dst in wrong_dsts: - insn = f"{op} {dst}, v1, v2, v3" - with self.subTest(insn=insn): - self.assert_rejected(insn) - for op in DIV_2DWORD_OPS: - for dst in ("s[0:1]", "v0", "v[0:3]", "null", "-v[0:1]", "|v[0:1]|", "sext(v[0:1])"): - insn = f"{op} {dst}, v[2:3], v[4:5], v[6:7]" - with self.subTest(insn=insn): - self.assert_rejected(insn) - - def test_source_width_and_sext_rejected(self): - for op in DIV_1DWORD_OPS: - for bad in ( - f"{op} v0, v[1:2], v3, v4", - f"{op} v0, v1, v[2:3], v4", - f"{op} v0, v1, v2, v[3:4]", - f"{op} v0, s[0:1], v2, v3", - f"{op} v0, sext(v1), v2, v3", - f"{op} v0, v1, sext(v2), v3", - f"{op} v0, v1, v2, sext(v3)", - ): - with self.subTest(insn=bad): - self.assert_rejected(bad) - for op in DIV_2DWORD_OPS: - for bad in ( - f"{op} v[0:1], sext(v[2:3]), v[4:5], v[6:7]", - f"{op} v[0:1], v[2:3], sext(v[4:5]), v[6:7]", - f"{op} v[0:1], v[2:3], v[4:5], sext(v[6:7])", - ): - with self.subTest(insn=bad): - self.assert_rejected(bad) - - def test_vop3_only_encodings_rejected(self): - for op in ALL_DIV_OPS: - for enc, extra in ( - ("_e32", ""), - ("_sdwa", "dst_sel:DWORD dst_unused:UNUSED_PAD src0_sel:DWORD"), - ("_dpp", "quad_perm:[1,0,3,2] row_mask:0xf bank_mask:0xf"), - ): - insn = _valid_insn(op, enc, extra) - with self.subTest(insn=insn): - self.assert_rejected(insn) - - def test_modifiers_and_opsel_rejected(self): - for op in ALL_DIV_OPS: - for mod in ("op_sel_hi:[0,0,0,0]", "dst_sel:DWORD", "glc", "mul:8", "clamp clamp"): - insn = _valid_insn(op, "", mod) - with self.subTest(insn=insn): - self.assert_rejected(insn) - - for op in STRICT_OMOD_OPS: - for mod in ("mul:2 mul:4", "mul:2 div:2", "div:2 div:2"): - insn = _valid_insn(op, "", mod) - with self.subTest(insn=insn): - self.assert_rejected(insn) - - # op_sel is only valid on v_div_fixup_f16 - for op in ("v_div_fixup_f32", "v_div_fixup_f64", "v_div_fmas_f32", "v_div_fmas_f64"): - with self.subTest(op=op, mod="op_sel"): - self.assert_rejected(_valid_insn(op, "", "op_sel:[0,0,0,0]")) - - # Invalid op_sel spellings on v_div_fixup_f16 - for bad_sel in ( - "op_sel:bogus", - "op_sel:[]", - "op_sel:[0,2,0,0]", - "op_sel:[0,0,0,0,0]", - "op_sel:[0,0,0,0] op_sel:[1,0,0,0]", - ): - with self.subTest(bad_sel=bad_sel): - self.assert_rejected(f"v_div_fixup_f16 v0, v1, v2, v3 {bad_sel}") - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_dpp_eager_subgroup.py b/tests/semantic/test_dpp_eager_subgroup.py deleted file mode 100644 index ca1790b6d..000000000 --- a/tests/semantic/test_dpp_eager_subgroup.py +++ /dev/null @@ -1,201 +0,0 @@ -"""DPP's ballot and shuffle run in every lane, also after SPIRV-Cross inlines expressions (SHADER-529). - -SPIRV-Cross (MoltenVK) inlines a result that is used once into the expression that uses it. On the right of an -OpLogicalAnd/OpLogicalOr that becomes a short-circuiting && / ||, and in an arm of a scalar OpSelect a ternary, so -a subgroup op there runs only in the lanes that get that far. The DPP lowering used to give -`in_row && subgroupBallotBitExtract(subgroupBallot(active), src)` and `src_ok ? subgroupShuffle(v, src) : 0`: on a -Mac, row_shr:1's lane 1 found lane 0 (out of its row, so it skipped the ballot) inactive and kept its old value -(`cs_dpp_ops`). The translator now stores both results to Function variables (`Gen.eager`), and a store is a -statement every lane runs. - -`conditional_subgroup_ops` follows each subgroup op's result through single-use expressions, the ones SPIRV-Cross -inlines, and reports one that lands on the right of a logical and/or or in a scalar select's arm. It is a model of -SPIRV-Cross's forwarding, not SPIRV-Cross: checked against SPIRV-Cross 1.3.239's MSL for the `cs_dpp*` GPU tests, -where it finds exactly the inlined ballots and shuffles before this change and none after. The values are checked -too, by running the translated DPP in tests/semantic/spirv_wave_interp.py. - -Standard library only; no GPU, no LLVM, no SPIRV-Tools, no game files. -""" -import os -import sys -import unittest - -HERE = os.path.dirname(os.path.abspath(__file__)) -sys.path.insert(0, HERE) - -import support # noqa: E402 (puts tools/ on the path) -import spirv_wave_interp as wi # noqa: E402 - -# Group ops whose result depends only on their operands' values, not on which invocations run them. -_PURE = frozenset({"OpGroupNonUniformBallotBitExtract", "OpGroupNonUniformBallotBitCount", - "OpGroupNonUniformBallotFindLSB", "OpGroupNonUniformBallotFindMSB", - "OpGroupNonUniformInverseBallot"}) - - -def _parse(text): - insns = [] - for ln in text.splitlines(): - t = ln.split(";", 1)[0].split() - if not t: - continue - if len(t) > 2 and t[1] == "=": - insns.append((t[0], t[2], t[3:])) - else: - insns.append((None, t[0], t[1:])) - return insns - - -def conditional_subgroup_ops(spvasm): - """[(result id, opcode, where)] for each subgroup op SPIRV-Cross would inline into a conditional position.""" - insns = _parse(spvasm) - types, uses = {}, {} - for i, (res, op, args) in enumerate(insns): - if res: - types[res] = args[0] if args else None - for pos, a in enumerate(args[1:] if res else args): # a result's first operand is its type - if a.startswith("%"): - uses.setdefault(a, []).append((i, pos)) - found = [] - for res, op, _ in insns: - if not (res and op.startswith("OpGroupNonUniform") and op not in _PURE): - continue - cur = res - while len(uses.get(cur, ())) == 1: # used more than once: SPIRV-Cross makes it a temporary - i, pos = uses[cur][0] - ures, uop, uargs = insns[i] - if uop in ("OpLogicalAnd", "OpLogicalOr") and pos == 1: - found.append((res, op, f"right of {uop} {ures}")) - break - if uop == "OpSelect" and pos in (1, 2) and types.get(uargs[1]) == "%bool": - found.append((res, op, f"arm of OpSelect {ures}")) - break - if ures is None or uop == "OpPhi": # a statement (store, branch) or a phi copy: every lane runs it - break - cur = ures - return found - - -DPP_FORMS = [ - "row_shr:1 row_mask:0xf bank_mask:0xf", - "row_shr:1 row_mask:0xf bank_mask:0xf bound_ctrl:1", - "row_shl:3 row_mask:0xf bank_mask:0xf", - "row_ror:5 row_mask:0xf bank_mask:0xf", - "row_mirror row_mask:0xf bank_mask:0xf", - "row_half_mirror row_mask:0x5 bank_mask:0xa", - "row_share:2 row_mask:0xf bank_mask:0xf", - "row_xmask:7 row_mask:0xf bank_mask:0xf", - "quad_perm:[3,2,1,0] row_mask:0xf bank_mask:0xf", - "dpp8:[1,0,3,2,5,4,7,6]", - "dpp8:[7,6,5,4,3,2,1,0] fi:1", -] - - -def dpp_vs(form, exec_off=None): - """A vertex shader: v6 = 100, then v6 = v0 (the lane) + 10 through DPP `form`, with lane `exec_off` off in - EXEC for the DPP; param0.x exports v6.""" - lines = ["v_mbcnt_lo_u32_b32 v0, -1, 0", "v_mov_b32 v1, 10", "v_mov_b32 v6, 100", "s_mov_b32 s10, exec_lo"] - if exec_off is not None: - lines.append(f"v_cmpx_ne_u32_e32 {exec_off}, v0") - lines += [f"v_add_nc_u32_dpp v6, v0, v1 {form}", "s_mov_b32 exec_lo, s10", "v_mov_b32 v5, 0", - "exp pos0 v5, v5, v5, v5 done", "exp param0 v6, v5, v5, v5", "s_endpgm"] - return support.translate_lines("vs_dpp_eager", lines) - - -def dpp_reference(form, exec_off=None, wave=32): - """v6 per lane after dpp_vs(form, exec_off), from the RDNA2 DPP rules (docs/design.md, Gen.dpp_insn).""" - mods = form.split() - get = lambda key, d: next((int(m.split(":")[1], 0) for m in mods if m.startswith(key + ":")), d) # noqa: E731 - row_mask, bank_mask, bound, fi = get("row_mask", 0xF), get("bank_mask", 0xF), get("bound_ctrl", 0), get("fi", 0) - active = [lane != exec_off for lane in range(wave)] - out = [] - for lane in range(wave): - loc, ok = lane & 15, True - if mods[0].startswith("dpp8:"): - sel = [int(x) for x in mods[0][6:-1].split(",")] - src = (lane & ~7) | sel[lane & 7] - elif mods[0].startswith("quad_perm:"): - sel = [int(x) for x in mods[0][11:-1].split(",")] - src = (lane & ~3) | sel[lane & 3] - else: - kind = mods[0].split(":")[0] - n = get(kind, 0) - if kind == "row_shr": - ok, s = loc >= n, loc - n - elif kind == "row_shl": - ok, s = loc + n < 16, loc + n - elif kind == "row_ror": - s = (loc - n) & 15 - elif kind == "row_share": - s = n - elif kind == "row_xmask": - s = loc ^ n - elif kind == "row_mirror": - s = 15 - loc - else: # row_half_mirror - s = (loc & 8) | (7 - (loc & 7)) - src = (lane & ~15) | (s & 15) - dpp8 = mods[0].startswith("dpp8:") - enabled = dpp8 or ((row_mask >> (lane >> 4)) & 1 and (bank_mask >> ((lane >> 2) & 3)) & 1) - valid = ok and (active[src] or (dpp8 and fi)) - if not active[lane] or not enabled or (not valid and not dpp8 and not bound): - out.append(100) # not written: keeps its old value - else: - out.append((src if valid else 0) + 10) - return out - - -class ConditionalSubgroupOpsModel(unittest.TestCase): - """The checker against hand-written SPIR-V: it must find the old DPP pattern and leave the safe ones alone.""" - - HEAD = "%b = OpGroupNonUniformBallot %v4uint_bal %c3 %act\n" \ - "%e = OpGroupNonUniformBallotBitExtract %bool %c3 %b %src\n" - - def test_ballot_on_the_right_of_and(self): - found = conditional_subgroup_ops(self.HEAD + "%a = OpLogicalAnd %bool %in_row %e\nOpStore %x %a\n") - self.assertEqual([(r, op) for r, op, _ in found], [("%b", "OpGroupNonUniformBallot")]) - - def test_shuffle_in_a_select_arm(self): - text = "%ok = OpINotEqual %bool %x %c0\n%s = OpGroupNonUniformShuffle %uint %c3 %v %src\n" \ - "%t = OpIAdd %uint %s %c1\n%r = OpSelect %uint %ok %t %c0\nOpStore %y %r\n" - self.assertEqual([op for _, op, _ in conditional_subgroup_ops(text)], ["OpGroupNonUniformShuffle"]) - - def test_safe_positions(self): - for tail in ("%a = OpLogicalAnd %bool %e %in_row\nOpStore %x %a\n", # left of &&: always runs - "%r = OpSelect %uint %e %c1 %c0\nOpStore %x %r\n", # the condition: always runs - "OpStore %x %e\n%a = OpLogicalAnd %bool %in_row %e\n", # two uses: a temporary - "OpStore %x %e\n"): - with self.subTest(tail=tail.split("\n")[0]): - self.assertEqual(conditional_subgroup_ops(self.HEAD + tail), []) - - def test_vector_select_is_not_a_ternary(self): - text = "%s = OpGroupNonUniformShuffle %v2uint %c3 %v %src\n" \ - "%r = OpSelect %v2uint %cond2 %s %zero2\nOpStore %y %r\n" - self.assertEqual(conditional_subgroup_ops(text), []) - - -class DppSubgroupOpsRunInEveryLane(unittest.TestCase): - def test_no_dpp_subgroup_op_is_conditional(self): - for form in DPP_FORMS: - for exec_off in (None, 5): - with self.subTest(form=form, exec_off=exec_off): - spv = dpp_vs(form, exec_off) - self.assertIn("OpGroupNonUniformShuffle", spv) - self.assertEqual(conditional_subgroup_ops(spv), []) - - def test_values(self): - for form in DPP_FORMS: - for exec_off in (None, 5, 16): - with self.subTest(form=form, exec_off=exec_off): - res = wi.run_wave(dpp_vs(form, exec_off), wave=32, - builtins={"VertexIndex": lambda lane: lane, "InstanceIndex": lambda lane: 0}) - got = [o["%out_param0"][0] for o in res["outputs"]] - self.assertEqual(got, dpp_reference(form, exec_off)) - - def test_reference_matches_cs_dpp_ops(self): - # runtime/test/shaders/cs_dpp_ops.asm: out[0..7] = 100 10 11 12 13 14 15 16. - self.assertEqual(dpp_reference("row_shr:1 row_mask:0xf bank_mask:0xf")[:8], - [100, 10, 11, 12, 13, 14, 15, 16]) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_ds_append.py b/tests/semantic/test_ds_append.py deleted file mode 100644 index 0c5445717..000000000 --- a/tests/semantic/test_ds_append.py +++ /dev/null @@ -1,80 +0,0 @@ -"""ds_append / ds_consume (runtime/test/shaders/cs_w32_ds_append.asm, cs_w64_ds_append.asm; docs/design.md). - -One LDS add / subtract of the wave's active-lane count at the offset address, done once for the wave; every active -lane gets the old value, inactive lanes keep vD. tests/semantic/spirv_mini_interp.py's run_workgroup shares -Workgroup memory between the invocations, so every lane reads back the one changed word: the op ran once, with the -active count. The GPU fixtures check the same words on hardware (both GPUs, wave64 native and emulated). Before, both -raised Unsupported. -""" -import os -import sys -import unittest - -HERE = os.path.dirname(os.path.abspath(__file__)) -if HERE not in sys.path: - sys.path.insert(0, HERE) - -import support # noqa: E402 -import spirv_mini_interp as si # noqa: E402 -import rdna2spirv # noqa: E402 - -SHADERS = os.path.join(support.ROOT, "runtime", "test", "shaders") -VSHARP = [0, 0, 0xFFFFFFFF, 0x31016FAC] - - -def header(name): - sys.path.insert(0, SHADERS) - from compute_fixture import compute_header - return bytes(compute_header(os.path.join(SHADERS, name + ".asm"))) - - -def run(wave, exec_words, op="ds_append", off=0): - """LDS word [off] = 100; EXEC = exec_words; `op` v8; every lane stores - (v8, its LDS word) at 8 * lane. Returns [(v8, lds) per lane].""" - lines = ["v_mov_b32 v8, 0xdead", "v_mov_b32 v1, 0", "v_mov_b32 v2, 100", f"ds_write_b32 v1, v2 offset:{off}"] - lines += [f"s_mov_b32 exec_lo, {exec_words[0]:#x}"] + ([f"s_mov_b32 exec_hi, {exec_words[1]:#x}"] if wave == 64 else []) - lines += [f"{op} v8 offset:{off}" if off else f"{op} v8", - "s_mov_b64 exec, -1" if wave == 64 else "s_mov_b32 exec_lo, -1", - f"ds_read_b32 v9, v1 offset:{off}", "v_lshlrev_b32 v21, 3, v0", - "buffer_store_dwordx2 v[8:9], v21, s[0:3], 0 offen", "s_endpgm"] - hdr = bytearray(header("cs_w64_ds_append" if wave == 64 else "cs_w32_ds_append")) - spv = support.translate_lines(f"cs_dsapp{wave}", lines, fssm=bytes(hdr)) - memory = {} - si.run_workgroup(spv, wave, wave, inputs_for=lambda i: {"%wg_id": (0, 0, 0), "%local_id": (i, 0, 0), "%sg_lane": i}, - push_constants=VSHARP + [0] * 28, memory=memory) - return [(memory[8 * l], memory[8 * l + 4]) for l in range(wave)] - - -def expect(wave, exec_bits, op): - """Plain-Python reference (one shared LDS): the word changes once by the active count, so every lane reads the new - word back; every active lane returns the old value, inactive lanes keep 0xdead.""" - act = [l for l in range(wave) if exec_bits >> l & 1] - cnt = len(act) - lds = (100 + cnt if op == "ds_append" else 100 - cnt) & 0xFFFFFFFF - return [(100 if l in act else 0xDEAD, lds) for l in range(wave)] - - -class DsAppend(unittest.TestCase): - def test_wave32(self): - for bits, op in ((0xF0F0, "ds_append"), (0x7, "ds_consume"), (0xFFFFFFFF, "ds_append"), (0x80000000, "ds_consume")): - with self.subTest(exec=hex(bits), op=op): - self.assertEqual(run(32, (bits,), op), expect(32, bits, op)) - - def test_wave64_both_halves(self): - for bits, op in (((1 << 63) | (1 << 32) | 1, "ds_append"), (1 << 33, "ds_consume")): - with self.subTest(exec=hex(bits), op=op): - self.assertEqual(run(64, (bits & 0xFFFFFFFF, bits >> 32), op), expect(64, bits, op)) - - def test_offset_is_the_address(self): - self.assertEqual(run(32, (0x3,), "ds_append", off=8), expect(32, 0x3, "ds_append")) - - def test_fixtures_translate_and_gds_is_refused(self): - for name in ("cs_w32_ds_append", "cs_w64_ds_append"): - with self.subTest(fixture=name): - self.assertIn("OpAtomicIAdd", support.translate_fixture(name, fssm=header(name))) - with self.assertRaisesRegex(rdna2spirv.Unsupported, "ds_append gds"): - support.translate_lines("cs_dsapp_gds", ["ds_append v8 gds", "s_endpgm"], fssm=header("cs_w32_ds_append")) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_ds_permute.py b/tests/semantic/test_ds_permute.py deleted file mode 100644 index 7797a2beb..000000000 --- a/tests/semantic/test_ds_permute.py +++ /dev/null @@ -1,200 +0,0 @@ -"""ds_permute_b32 (SHADER-90), the forward (scatter) cross-lane permute, run across every lane of the translated SPIR-V. - -Programs are written here (no game data) and translated by tools/rdna2spirv.py; spirv_mini_interp.run_workgroup runs one -workgroup of 32 or 64 lanes. Each lane stores its result to out[lane]. The expected vectors come from a model -written from the RDNA2 ISA (DS_PERMUTE_B32, "Forward permute"), not from the translator: - * every source lane that is on in EXEC writes its data to lane ((addr + offset) >> 2) mod 32 of its own half - (wave64 runs as two wave32s, ISA 10.4.4, as ds_bpermute_b32 here does); - * a destination lane that no source writes gets 0 (the ISA's tmp[0..63] = 0); - * a destination lane that is off in EXEC keeps its VDST; - * several sources to one lane: the value of one of them (the ISA's "not predictable"; this translator takes the - highest-numbered). The tests that have such a lane accept any of the writers. -The GPU test is runtime/test/shaders/cs_w32_permute.asm; its fixture also runs here. The --wave64-emulate output -needs Workgroup memory, which the interpreter rejects, so it is covered by the GPU test only. -""" -import gc -import os -import struct -import tempfile -import unittest -import warnings - -import support -import spirv_mini_interp as si - -VSHARP = [0, 0, 0x1000, 0x31016FAC] -OLD = 99 -ALL = 0xFFFFFFFF -ALL64 = (1 << 64) - 1 - - -def fssm(threads): - h = bytearray(0x148) - struct.pack_into("<4I", h, 0x138, 0x8088, threads, 1, 1) - return bytes(h) - - -def translate_text(name, insns, threads): - with tempfile.TemporaryDirectory() as tmp: - os.mkdir(os.path.join(tmp, "disasm")) - os.mkdir(os.path.join(tmp, "fssm")) - path = os.path.join(tmp, "disasm", name + ".s") - with open(path, "w", encoding="utf-8", newline="\n") as f: - f.write(f"; {name}\n" + "".join("\t" + i + "\n" for i in insns)) - with open(os.path.join(tmp, name + ".dxbc"), "wb") as f: - f.write(support.STUB_DXBC) - with open(os.path.join(tmp, "fssm", name + ".fssm"), "wb") as f: - f.write(fssm(threads)) - with warnings.catch_warnings(): - warnings.simplefilter("ignore", ResourceWarning) - spv = support.rdna2spirv.translate(path) - gc.collect() - return spv - - -def program(addr_insns, exec_mask, offset=0, wave=32): - """v2 = 7 * lane + 1 is the data, v3 the address; v10 starts at OLD; the result of lane l is stored at out[l].""" - on = [f"s_mov_b32 exec_lo, {exec_mask & 0xFFFFFFFF:#x}"] - off = ["s_mov_b32 exec_lo, -1"] - if wave == 64: - on.append(f"s_mov_b32 exec_hi, {exec_mask >> 32:#x}") - off.append("s_mov_b32 exec_hi, -1") - mod = f" offset:{offset}" if offset else "" - return (["v_mad_u32_u24 v2, v0, 7, 1"] + addr_insns + [f"v_mov_b32_e32 v10, {OLD}"] + on - + [f"ds_permute_b32 v10, v3, v2{mod}", "s_waitcnt lgkmcnt(0)"] + off - + ["v_lshlrev_b32_e32 v21, 2, v0", "buffer_store_dword v10, v21, s[0:3], 0 offen", "s_endpgm"]) - - -def run(spv, lanes, subgroup): - memory = si.run_workgroup( - spv, lanes, subgroup, - inputs_for=lambda i: {"%wg_id": (0, 0, 0), "%local_id": (i, 0, 0), "%sg_lane": i % subgroup}, - push_constants=VSHARP + [0] * 28, memory={}) - stray = sorted(a for a in memory if not 0 <= a < 4 * lanes or a % 4) - assert not stray, f"stores outside out[0..{lanes - 1}]: {stray}" - return [memory.get(4 * k) for k in range(lanes)] - - -class SwizzleExecTests(unittest.TestCase): - def test_swizzled_fragment_color_with_disabled_neighbors(self) -> None: - fixture = os.path.join(support.HERE, "fixtures", "fragment_swizzle_exec.asm") - with open(fixture, encoding="ascii") as source: - instructions = [line.strip() for line in source if line.strip() and not line.startswith(";")] - for pattern in ("QUAD_PERM,1,0,3,2", "SWAP,1"): - lines = [line.replace("QUAD_PERM,1,0,3,2", pattern) for line in instructions] - spv = support.translate_lines("ps_swizzle_exec", lines) - for lanes in (32, 7): - with self.subTest(pattern=pattern, lanes=lanes): - # Lane 0 reads disabled lane 1. Lane 1 keeps its destination. Lanes 2/3 exchange active data. - expected = [0, 0x3f000000, 0x3f400000, 0x3f400000] * 8 - if lanes == 7: - expected[6] = 0 # translator's model for absent lane 7; unverified on hardware - self.assertEqual(run(spv, lanes, 32), expected[:lanes]) - - -def model(addrs, exec_mask, offset, lanes=32): - """ISA model. Per lane, the set of values the ISA allows (one value unless several sources collide).""" - out = [] - for base in range(0, lanes, 32): - writers = {d: [] for d in range(32)} - for i in range(32): - lane = base + i - if (exec_mask >> lane) & 1: - writers[((addrs[lane] + offset) >> 2) % 32].append(7 * lane + 1) - for i in range(32): - out.append(set(writers[i]) or {0} if (exec_mask >> (base + i)) & 1 else {OLD}) - return out - - -# name -> (instructions computing v3 from v0, python address function, offset, exec mask) -CASES = { - "identity": (["v_lshlrev_b32_e32 v3, 2, v0"], lambda l: 4 * l, 0, ALL), - "rotate_by_one": (["v_add_nc_u32_e32 v3, 1, v0", "v_lshlrev_b32_e32 v3, 2, v3"], lambda l: 4 * (l + 1), 0, ALL), - "reversal": (["v_sub_nc_u32_e32 v3, 31, v0", "v_lshlrev_b32_e32 v3, 2, v3"], lambda l: 4 * (31 - l), 0, ALL), - "reversal_offset_8": (["v_sub_nc_u32_e32 v3, 31, v0", "v_lshlrev_b32_e32 v3, 2, v3"], - lambda l: 4 * (31 - l), 8, ALL), - "offset_only": (["v_lshlrev_b32_e32 v3, 2, v0"], lambda l: 4 * l, 12, ALL), - # EXEC = lanes 0-15, lane l writes lane 2l: odd lanes are written by nobody (0), lanes 16-31 are off and keep OLD - # although sources 8-15 target them - "unwritten_lanes_are_zero": (["v_lshlrev_b32_e32 v3, 3, v0"], lambda l: 8 * l, 0, 0xFFFF), - # the off odd lanes send nothing: every even destination lane gets 0 - "inactive_sources_send_nothing": (["v_add_nc_u32_e32 v3, 1, v0", "v_lshlrev_b32_e32 v3, 2, v3"], - lambda l: 4 * (l + 1), 0, 0x55555555), - # an even lane l writes l + 2, an odd lane l writes l + 1; EXEC = even lanes: the off lane 3 must not win lane 4 - "inactive_source_does_not_win": (["v_and_b32_e32 v3, 1, v0", "v_sub_nc_u32_e32 v3, 2, v3", - "v_add_nc_u32_e32 v3, v0, v3", "v_lshlrev_b32_e32 v3, 2, v3"], - lambda l: 4 * (l + 2 - (l & 1)), 0, 0x55555555), - # every lane to lane 5: a collision, any writer is allowed - "all_to_one_lane": (["v_mov_b32_e32 v3, 20"], lambda l: 20, 0, ALL), - # index 32 + l wraps to l - "index_wraps_mod_32": (["v_add_nc_u32_e32 v3, 32, v0", "v_lshlrev_b32_e32 v3, 2, v3"], - lambda l: 4 * (l + 32), 0, ALL), - "high_address_bits_ignored": (["v_lshlrev_b32_e32 v3, 2, v0", "v_or_b32_e32 v3, 0x100, v3"], - lambda l: 4 * l + 0x100, 0, ALL), -} - - -class Wave32(unittest.TestCase): - def test_cases(self): - for name, (insns, addr, off, mask) in CASES.items(): - with self.subTest(case=name): - got = run(translate_text("cs_" + name, program(insns, mask, off), 32), 32, 32) - want = model([addr(l) for l in range(32)], mask, off) - for lane in range(32): - self.assertIn(got[lane], want[lane], f"{name}: lane {lane} got {got[lane]}, ISA allows {want[lane]}") - if name != "all_to_one_lane": - self.assertTrue(all(len(w) == 1 for w in want), f"{name} has a collision") - - def test_known_values(self): - # Hand-derived (data[l] = 7l + 1), independent of the model above. - rot = run(translate_text("cs_rot", program(CASES["rotate_by_one"][0], ALL), 32), 32, 32) - self.assertEqual((rot[0], rot[5], rot[31]), (218, 29, 211)) - rev = run(translate_text("cs_rev", program(CASES["reversal_offset_8"][0], ALL, 8), 32), 32, 32) - self.assertEqual((rev[0], rev[3]), (8, 211)) - c = run(translate_text("cs_c", program(CASES["unwritten_lanes_are_zero"][0], 0xFFFF), 32), 32, 32) - self.assertEqual((c[3], c[4], c[20]), (0, 15, OLD)) - d = run(translate_text("cs_d", program(CASES["inactive_source_does_not_win"][0], 0x55555555), 32), 32, 32) - self.assertEqual((d[4], d[3]), (15, OLD)) - - def test_gpu_test_fixture(self): - """cs_w32_permute.asm: the words check.py expects (lane 0 and a few more store).""" - spv = support.translate_fixture("cs_w32_permute", fssm=fssm(32)) - memory = si.run_workgroup( - spv, 32, 32, inputs_for=lambda i: {"%wg_id": (0, 0, 0), "%local_id": (i, 0, 0), "%sg_lane": i}, - push_constants=VSHARP + [0] * 28, memory={}) - self.assertEqual([memory.get(4 * k) for k in range(8)], [218, 29, 8, 211, 0, 15, 99, 15]) - - -class Wave64Halves(unittest.TestCase): - """Wave64 without emulation: two independent wave32 halves, on a 64-wide subgroup and on two 32-wide ones.""" - - def test_halves(self): - for subgroup in (64, 32): - for name, mask in (("rotate_by_one", ALL64), ("reversal_offset_8", ALL64), - ("unwritten_lanes_are_zero", 0x0000FFFF0000FFFF), - ("inactive_source_does_not_win", 0x5555555555555555)): - with self.subTest(case=name, subgroup=subgroup): - insns, addr, off, _ = CASES[name] - spv = translate_text("cs_h_" + name, program(insns, mask, off, wave=64), 64) - got = run(spv, 64, subgroup) - want = model([addr(l) for l in range(64)], mask, off, lanes=64) - for lane in range(64): - self.assertIn(got[lane], want[lane], f"lane {lane} got {got[lane]}, ISA allows {want[lane]}") - if name == "rotate_by_one": - # the upper half rotates inside itself: lane 32 gets lane 63's data, not lane 31's - self.assertEqual((got[32], got[63]), (7 * 63 + 1, 7 * 62 + 1)) - - def test_gpu_test_fixture(self): - """cs_w64x_permute.asm: the words check.py expects, on one 64-wide subgroup and on two 32-wide ones.""" - for subgroup in (64, 32): - with self.subTest(subgroup=subgroup): - spv = support.translate_fixture("cs_w64x_permute", fssm=fssm(64)) - memory = si.run_workgroup( - spv, 64, subgroup, - inputs_for=lambda i: {"%wg_id": (0, 0, 0), "%local_id": (i, 0, 0), "%sg_lane": i % subgroup}, - push_constants=VSHARP + [0] * 28, memory={}) - self.assertEqual([memory.get(4 * k) for k in range(8)], [218, 442, 435, 239, 0, 99, 239, 232]) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_ds_swizzle_b32.py b/tests/semantic/test_ds_swizzle_b32.py deleted file mode 100644 index 929e74aca..000000000 --- a/tests/semantic/test_ds_swizzle_b32.py +++ /dev/null @@ -1,899 +0,0 @@ -"""ds_swizzle_b32 vD, vS offset:swizzle(...): every swizzle mode run across the lanes of the translated SPIR-V. - -Standard library only; no GPU, no LLVM, no game files. - -ds_swizzle_b32 is a fixed cross-lane gather inside each group of 32 lanes ([0..31] in wave32; [0..31] and [32..63] -independently in wave64). An active destination lane reads the selected source lane's vS; a source lane that is off -in EXEC (or absent from a partial wave) reads 0; a destination lane that is off keeps its vD (docs/design.md, -ds_swizzle_b32 row). The 16-bit offset selects the source lane (RDNA2 ISA, DS_SWIZZLE_B32): - * bit 15 set (QUAD_PERM): src = (lane & ~3) | offset[2 * (lane & 3) + 1 : 2 * (lane & 3)]; - * bit 15 clear (BITMASK_PERM, and the SWAP / REVERSE / BROADCAST shorthands of LLVM's disassembler): - src = ((lane & and_mask) | or_mask) ^ xor_mask, with and/or/xor in offset bits [4:0] / [9:5] / [14:10]. - -Already covered on main: test_ds_permute.py (QUAD_PERM,1,0,3,2 and SWAP,1 with disabled neighbours, the -fragment_swizzle_exec fixture) and test_wave64_halves.py (QUAD_PERM,3,2,1,0 and SWAP,16 in a wave64 vertex shader). -This file adds the other QUAD_PERM patterns, BITMASK_PERM, REVERSE and BROADCAST, compute shaders in wave32, wave64 -on one 64-wide and on two 32-wide subgroups, partial waves (20 and 40 lanes), EXEC masks, aliasing and raw bit -patterns, and a pixel shader on tests/semantic/spirv_wave_interp.py. The expected words come from hand-worked -constants and a plain-Python model of the 16-bit offset encoding, not from the translator. - -The --wave64-emulate lowering goes through Workgroup memory and barriers, which spirv_mini_interp.py rejects, so it -is checked structurally only. The translator parses the swizzle(...) text LLVM's disassembler prints; a raw numeric -offset is refused rather than guessed. - - python -I tests/semantic/test_ds_swizzle_b32.py -v -""" -import gc -import os -import re -import struct -import sys -import tempfile -import unittest -import warnings - -HERE = os.path.dirname(os.path.abspath(__file__)) -ROOT = os.path.dirname(os.path.dirname(HERE)) -TOOLS_DIR = os.environ.get("LEONIDA_TOOLS_DIR") or os.path.join(ROOT, "tools") - -sys.dont_write_bytecode = True -if TOOLS_DIR not in sys.path: - sys.path.insert(0, TOOLS_DIR) -if HERE not in sys.path: - sys.path.insert(0, HERE) - -import rdna2spirv # noqa: E402 -import spirv_mini_interp as si # noqa: E402 -import spirv_wave_interp as wi # noqa: E402 - -MASK32 = 0xFFFFFFFF -ALL32 = 0xFFFFFFFF -ALL64 = 0xFFFFFFFFFFFFFFFF -OLD_SENTINEL = 0xBEEF0000 -HEAP_FILL = 0xEEEEEEEE -# V# in s[0:3]: base 0, stride 0, num_records 0x10000 bytes (OOB_SELECT = 3). -VSHARP = [0, 0, 0x10000, 0x31016FAC] -INPUT_BASE = 0x8000 -STUB_DXBC = b"DXBC" + bytes(24) + struct.pack(" int: - """RDNA2 16-bit ds_swizzle offset for QUAD_PERM(a, b, c, d): bit 15 = 1, 2-bit lanes in [7:0].""" - for v in (a, b, c, d): - assert 0 <= v <= 3 - return 0x8000 | a | (b << 2) | (c << 4) | (d << 6) - - -def encode_bitmask_perm(pattern: str) -> int: - """RDNA2 16-bit ds_swizzle offset for BITMASK_PERM("c4c3c2c1c0"): - bit 15 = 0, and_mask = [4:0], or_mask = [9:5], xor_mask = [14:10].""" - assert len(pattern) == 5 and all(ch in "01pi" for ch in pattern) - and_m = or_m = xor_m = 0 - for k, ch in enumerate(pattern): - bit = 1 << (4 - k) - if ch in "pi": - and_m |= bit - if ch == "1": - or_m |= bit - if ch == "i": - xor_m |= bit - return and_m | (or_m << 5) | (xor_m << 10) - - -def encode_swap(stride: int) -> int: - """RDNA2 16-bit offset for SWAP(stride): lane ^ stride (bitmask with and=31, or=0, xor=stride).""" - assert stride in (1, 2, 4, 8, 16) - return 0x1F | (stride << 10) - - -def encode_reverse(width: int) -> int: - """RDNA2 16-bit offset for REVERSE(width): lane ^ (width - 1).""" - assert width in (2, 4, 8, 16, 32) - return 0x1F | ((width - 1) << 10) - - -def encode_broadcast(group_size: int, lane_idx: int) -> int: - """RDNA2 16-bit offset for BROADCAST(group_size, lane_idx): (lane & ~(group_size - 1)) | lane_idx.""" - assert group_size in (2, 4, 8, 16, 32) and 0 <= lane_idx < group_size - and_m = (~(group_size - 1)) & 0x1F - return and_m | (lane_idx << 5) - - -def isa_swizzle_src_lane(lane: int, offset16: int) -> int: - """RDNA2 ISA source lane within a 32-lane group from the 16-bit offset field.""" - if offset16 & 0x8000: - sel = (offset16 >> (2 * (lane & 3))) & 3 - return (lane & ~3) | sel - and_m = offset16 & 0x1F - or_m = (offset16 >> 5) & 0x1F - xor_m = (offset16 >> 10) & 0x1F - return (lane & ~31) | ((((lane & 31) & and_m) | or_m) ^ xor_m) - - -def ref_swizzle(src_vals: list[int], dst_old: list[int], offset16: int, exec_mask: int, - zero_inactive_src: bool = True) -> list[int]: - """Independent RDNA2 ISA reference model for `ds_swizzle_b32`.""" - lanes = len(src_vals) - assert len(dst_old) == lanes and lanes in (32, 64) - out = [] - for lane in range(lanes): - if not ((exec_mask >> lane) & 1): - out.append(dst_old[lane] & MASK32) - continue - src = isa_swizzle_src_lane(lane, offset16) - if zero_inactive_src and not ((exec_mask >> src) & 1): - out.append(0) - else: - out.append(src_vals[src] & MASK32) - return out - - -# ---- Harness helpers ---- - -class _Heap(dict): - def get(self, key, default=None): - return super().get(key, HEAP_FILL) - - -_TMP_DIR = None -_DISASM_DIR = None -_FSSM_DIR = None - - -def _make_fssm(threads: int, rsrc2: int = 0x8088) -> bytes: - header = bytearray(0x148) - struct.pack_into("<4I", header, 0x138, rsrc2, threads, 1, 1) - return bytes(header) - - -def setUpModule(): - global _TMP_DIR, _DISASM_DIR, _FSSM_DIR - _TMP_DIR = tempfile.TemporaryDirectory() - _DISASM_DIR = os.path.join(_TMP_DIR.name, "disasm") - _FSSM_DIR = os.path.join(_TMP_DIR.name, "fssm") - os.mkdir(_DISASM_DIR) - os.mkdir(_FSSM_DIR) - - -def tearDownModule(): - global _TMP_DIR, _DISASM_DIR, _FSSM_DIR - if _TMP_DIR is not None: - gc.collect() - _TMP_DIR.cleanup() - _TMP_DIR = None - _DISASM_DIR = None - _FSSM_DIR = None - - -def translate_cs(name: str, lines: list[str], threads: int, emulate: bool = False) -> tuple[str, object]: - assert name.startswith("cs_"), f"compute shader name must start with cs_: {name!r}" - if _TMP_DIR is None: - setUpModule() - with open(os.path.join(_FSSM_DIR, name + ".fssm"), "wb") as f: - f.write(_make_fssm(threads)) - src_path = os.path.join(_DISASM_DIR, name + ".s") - asm = f"; {name}\n" + "".join(f"\t{ln}\n" for ln in lines) + "\ts_endpgm\n" - with open(src_path, "w", encoding="utf-8", newline="\n") as f: - f.write(asm) - old_emu = rdna2spirv.WAVE64_EMULATE - rdna2spirv.WAVE64_EMULATE = emulate - try: - with warnings.catch_warnings(): - warnings.simplefilter("ignore", ResourceWarning) - spv = rdna2spirv.translate(src_path) - gen = rdna2spirv.translate.last_gen - gc.collect() - finally: - rdna2spirv.WAVE64_EMULATE = old_emu - return spv, gen - - -def translate_ps(name: str, lines: list[str]) -> tuple[str, object]: - assert name.startswith("ps_"), f"pixel shader name must start with ps_: {name!r}" - if _TMP_DIR is None: - setUpModule() - with open(os.path.join(_TMP_DIR.name, name + ".dxbc"), "wb") as f: - f.write(STUB_DXBC) - src_path = os.path.join(_DISASM_DIR, name + ".s") - asm = f"; {name}\n" + "".join(f"\t{ln}\n" for ln in lines) + "\ts_endpgm\n" - with open(src_path, "w", encoding="utf-8", newline="\n") as f: - f.write(asm) - with warnings.catch_warnings(): - warnings.simplefilter("ignore", ResourceWarning) - spv = rdna2spirv.translate(src_path) - gen = rdna2spirv.translate.last_gen - gc.collect() - return spv, gen - - -def run_cs(name: str, lines: list[str], threads: int, subgroup_size: int, - init_inputs: list[int] | None = None, out_slots: int = 1) -> list[int]: - """Translate and run a compute shader; return `threads * out_slots` 32-bit output words.""" - spv, _ = translate_cs(name, lines, threads, emulate=False) - mem = _Heap() - if init_inputs is not None: - for i, val in enumerate(init_inputs): - mem[INPUT_BASE + 4 * i] = val & MASK32 - si.run_workgroup( - spv, threads, subgroup_size, - inputs_for=lambda i: {"%wg_id": (0, 0, 0), "%local_id": (i, 0, 0), "%sg_lane": i % subgroup_size}, - push_constants=VSHARP + [0] * 28, - memory=mem, - ) - out_bytes = 4 * threads * out_slots - stray = sorted(a for a in mem if a < INPUT_BASE and (a % 4 != 0 or a >= out_bytes)) - if stray: - raise AssertionError(f"{name}: unexpected stores outside out[0..{threads * out_slots - 1}]: {stray}") - return [mem.get(4 * k) for k in range(threads * out_slots)] - - -def exec_mask_lines(mask: int, wave: int) -> list[str]: - lines = [f"s_mov_b32 exec_lo, {mask & MASK32:#x}"] - if wave == 64: - lines.append(f"s_mov_b32 exec_hi, {(mask >> 32) & MASK32:#x}") - return lines - - -def restore_exec_lines(wave: int) -> list[str]: - return ["s_mov_b64 exec, -1"] if wave == 64 else ["s_mov_b32 exec_lo, -1"] - - -def store_slots_lines(regs: list[str], threads: int) -> list[str]: - lines = ["v_lshlrev_b32_e32 v21, 2, v0"] - for slot, reg in enumerate(regs): - if slot == 0: - lines.append(f"buffer_store_dword {reg}, v21, s[0:3], 0 offen") - else: - lines.append(f"buffer_store_dword {reg}, v21, s[0:3], 0 offen offset:{4 * slot * threads}") - return lines - - -def _run_swizzle_batch(name: str, swz_specs: list[tuple[str, int]], init_vals: list[int], - wave: int, subgroup_size: int, exec_mask: int | None = None) -> list[list[int]]: - """Batch up to 16 `ds_swizzle_b32` operations into a single compute shader and return per-slot lane vectors.""" - assert 1 <= len(swz_specs) <= 16 - lines = [] - if wave == 64: - lines.append("s_mov_b64 exec, -1") - lines += [ - "v_lshlrev_b32_e32 v20, 2, v0", - f"v_add_nc_u32_e32 v20, {INPUT_BASE:#x}, v20", - "buffer_load_dword v1, v20, s[0:3], 0 offen", - ] - regs = [] - for idx in range(len(swz_specs)): - dst = f"v{2 + idx}" - regs.append(dst) - lines.append(f"v_or_b32_e32 {dst}, {OLD_SENTINEL:#x}, v0") - if exec_mask is not None: - lines.extend(exec_mask_lines(exec_mask, wave)) - for idx, (mod_str, _) in enumerate(swz_specs): - lines.append(f"ds_swizzle_b32 v{2 + idx}, v1 offset:{mod_str}") - lines.append("s_waitcnt lgkmcnt(0)") - if exec_mask is not None: - lines.extend(restore_exec_lines(wave)) - lines.extend(store_slots_lines(regs, wave)) - flat = run_cs(name, lines, wave, subgroup_size, init_inputs=init_vals, out_slots=len(swz_specs)) - return [flat[slot * wave:(slot + 1) * wave] for slot in range(len(swz_specs))] - - -# ---- Test suites ---- - -class OracleTests(unittest.TestCase): - """Cross-check hand-worked constants and macro encoders against the 16-bit RDNA2 ISA model.""" - - def test_quad_perm_hand_worked_constants(self): - vals = [100 + l for l in range(32)] - old = [OLD_SENTINEL | l for l in range(32)] - - # Broadcast lane 0/1/2/3 inside every quad. - for k in range(4): - got = ref_swizzle(vals, old, encode_quad_perm(k, k, k, k), ALL32) - self.assertEqual(got, [100 + (l & ~3) + k for l in range(32)]) - - # Reverse quad [3,2,1,0]: quad 0 -> [103, 102, 101, 100], quad 7 -> [131, 130, 129, 128]. - rev = ref_swizzle(vals, old, encode_quad_perm(3, 2, 1, 0), ALL32) - self.assertEqual(rev[:4], [103, 102, 101, 100]) - self.assertEqual(rev[28:32], [131, 130, 129, 128]) - - # Swap pairs [1,0,3,2] and rotate [1,2,3,0]. - swap = ref_swizzle(vals, old, encode_quad_perm(1, 0, 3, 2), ALL32) - self.assertEqual(swap[:8], [101, 100, 103, 102, 105, 104, 107, 106]) - rot = ref_swizzle(vals, old, encode_quad_perm(1, 2, 3, 0), ALL32) - self.assertEqual(rot[:8], [101, 102, 103, 100, 105, 106, 107, 104]) - - def test_bitmask_shorthand_encoding_equivalences(self): - # SWAP, REVERSE, BROADCAST must produce the exact same 16-bit offsets as BITMASK_PERM. - self.assertEqual(encode_swap(1), encode_bitmask_perm("ppppi")) - self.assertEqual(encode_swap(2), encode_bitmask_perm("pppip")) - self.assertEqual(encode_swap(4), encode_bitmask_perm("ppipp")) - self.assertEqual(encode_swap(8), encode_bitmask_perm("pippp")) - self.assertEqual(encode_swap(16), encode_bitmask_perm("ipppp")) - - self.assertEqual(encode_reverse(2), encode_bitmask_perm("ppppi")) - self.assertEqual(encode_reverse(4), encode_bitmask_perm("pppii")) - self.assertEqual(encode_reverse(8), encode_bitmask_perm("ppiii")) - self.assertEqual(encode_reverse(16), encode_bitmask_perm("piiii")) - self.assertEqual(encode_reverse(32), encode_bitmask_perm("iiiii")) - - self.assertEqual(encode_broadcast(8, 0), encode_bitmask_perm("pp000")) - self.assertEqual(encode_broadcast(8, 5), encode_bitmask_perm("pp101")) - self.assertEqual(encode_broadcast(16, 0), encode_bitmask_perm("p0000")) - self.assertEqual(encode_broadcast(32, 0), encode_bitmask_perm("00000")) - self.assertEqual(encode_broadcast(32, 31), encode_bitmask_perm("11111")) - - def test_inactive_source_zero_fill_in_isa_model(self): - # ISA model: an active lane reading an inactive source lane gets 0; an inactive destination keeps its vD. - vals = [100 + l for l in range(32)] - old = [OLD_SENTINEL | l for l in range(32)] - mask_no_0 = ALL32 ^ 1 - got = ref_swizzle(vals, old, encode_broadcast(32, 0), mask_no_0, zero_inactive_src=True) - self.assertEqual(got[0], old[0]) - self.assertEqual(got[1:], [0] * 31) - - -class Wave32QuadPermTests(unittest.TestCase): - """End-to-end 32-lane execution for QUAD_PERM mode.""" - - def test_quad_perm_broadcasts_reverse_swap_rotate_and_asymmetric(self): - init_vals = [(0x10000000 + l * 0x010101) & MASK32 for l in range(32)] - old_vals = [OLD_SENTINEL | l for l in range(32)] - specs = [ - # Identity - ("swizzle(QUAD_PERM,0,1,2,3)", encode_quad_perm(0, 1, 2, 3)), - # Broadcast lane 0, 1, 2, 3 of each quad - ("swizzle(QUAD_PERM,0,0,0,0)", encode_quad_perm(0, 0, 0, 0)), - ("swizzle(QUAD_PERM,1,1,1,1)", encode_quad_perm(1, 1, 1, 1)), - ("swizzle(QUAD_PERM,2,2,2,2)", encode_quad_perm(2, 2, 2, 2)), - ("swizzle(QUAD_PERM,3,3,3,3)", encode_quad_perm(3, 3, 3, 3)), - # Reverse quad [3,2,1,0] - ("swizzle(QUAD_PERM,3,2,1,0)", encode_quad_perm(3, 2, 1, 0)), - # Swap pairs [1,0,3,2] and swap half-quads [2,3,0,1] - ("swizzle(QUAD_PERM,1,0,3,2)", encode_quad_perm(1, 0, 3, 2)), - ("swizzle(QUAD_PERM,2,3,0,1)", encode_quad_perm(2, 3, 0, 1)), - # Rotate left [1,2,3,0] and rotate right [3,0,1,2] - ("swizzle(QUAD_PERM,1,2,3,0)", encode_quad_perm(1, 2, 3, 0)), - ("swizzle(QUAD_PERM,3,0,1,2)", encode_quad_perm(3, 0, 1, 2)), - # Non-bijective / arbitrary quad patterns - ("swizzle(QUAD_PERM,2,0,3,2)", encode_quad_perm(2, 0, 3, 2)), - ("swizzle(QUAD_PERM,3,3,0,1)", encode_quad_perm(3, 3, 0, 1)), - ] - results = _run_swizzle_batch("cs_w32_swz_quad", specs, init_vals, 32, 32) - for idx, (mod_str, off16) in enumerate(specs): - want = ref_swizzle(init_vals, old_vals, off16, ALL32) - with self.subTest(pattern=mod_str): - self.assertEqual(results[idx], want) - - # Explicit hand-checked spot checks (independent of ref_swizzle). - self.assertEqual(results[0], init_vals) # identity - self.assertEqual(results[1][:8], [init_vals[0]] * 4 + [init_vals[4]] * 4) # bcast 0 - self.assertEqual(results[5][:4], [init_vals[3], init_vals[2], init_vals[1], init_vals[0]]) - self.assertEqual(results[6][:4], [init_vals[1], init_vals[0], init_vals[3], init_vals[2]]) - self.assertEqual(results[8][:4], [init_vals[1], init_vals[2], init_vals[3], init_vals[0]]) - - def test_quad_sum_reduction(self): - # 2-step quad reduction: swap pairs [1,0,3,2], then swap half-quads [2,3,0,1]. - init_vals = [11 * l + 3 for l in range(32)] - got = run_cs("cs_w32_swz_quad_reduce", [ - "v_lshlrev_b32_e32 v20, 2, v0", - f"v_add_nc_u32_e32 v20, {INPUT_BASE:#x}, v20", - "buffer_load_dword v1, v20, s[0:3], 0 offen", - "ds_swizzle_b32 v2, v1 offset:swizzle(QUAD_PERM,1,0,3,2)", - "s_waitcnt lgkmcnt(0)", - "v_add_nc_u32_e32 v1, v1, v2", - "ds_swizzle_b32 v2, v1 offset:swizzle(QUAD_PERM,2,3,0,1)", - "s_waitcnt lgkmcnt(0)", - "v_add_nc_u32_e32 v1, v1, v2", - "v_lshlrev_b32_e32 v21, 2, v0", - "buffer_store_dword v1, v21, s[0:3], 0 offen", - ], 32, 32, init_inputs=init_vals) - want = [sum(init_vals[(l & ~3):(l & ~3) + 4]) for l in range(32)] - self.assertEqual(got, want) - - -class Wave32BitmaskAndShorthandTests(unittest.TestCase): - """End-to-end 32-lane execution for BITMASK_PERM, SWAP, REVERSE, and BROADCAST modes.""" - - def test_bitmask_perm_xor_butterflies_broadcasts_and_mixed(self): - init_vals = [0x5000 + l * 19 for l in range(32)] - old_vals = [OLD_SENTINEL | l for l in range(32)] - patterns = [ - # Identity - "ppppp", - # XOR butterfly strides 1, 2, 4, 8, 16 (swap halves) - "ppppi", - "pppip", - "ppipp", - "pippp", - "ipppp", - # Combined XOR masks ("pippi" = lane^9 as in ps_bitmask_perm.asm, full reverse, checkerboard) - "pippi", - "iiiii", - "ipipi", - # AND/OR broadcasts across 4, 8, 16, 32 lanes - "ppp00", - "pp000", - "p0000", - "00000", - "11111", - # Mixed AND/OR/XOR ("10p0i" = ((lane & 5) | 16) ^ 1 as in ps_bitmask_perm.asm) - "10p0i", - "01i1p", - ] - specs = [(f'swizzle(BITMASK_PERM,"{p}")', encode_bitmask_perm(p)) for p in patterns] - results = _run_swizzle_batch("cs_w32_swz_bitmask", specs, init_vals, 32, 32) - for idx, (mod_str, off16) in enumerate(specs): - want = ref_swizzle(init_vals, old_vals, off16, ALL32) - with self.subTest(pattern=mod_str): - self.assertEqual(results[idx], want) - - # Spot-check key patterns directly (independent of ref_swizzle): - # "ipppp" swaps [0..15] <-> [16..31] - self.assertEqual(results[5], init_vals[16:32] + init_vals[0:16]) - # "pippi" = lane ^ 9 - self.assertEqual(results[6], [init_vals[l ^ 9] for l in range(32)]) - # "00000" broadcasts lane 0 across all 32 lanes; "11111" broadcasts lane 31 - self.assertEqual(results[12], [init_vals[0]] * 32) - self.assertEqual(results[13], [init_vals[31]] * 32) - # "10p0i" = ((lane & 5) | 16) ^ 1 - self.assertEqual(results[14], [init_vals[((l & 5) | 16) ^ 1] for l in range(32)]) - - def test_swap_reverse_and_broadcast_shorthands(self): - init_vals = [0x9000 + l * 23 for l in range(32)] - old_vals = [OLD_SENTINEL | l for l in range(32)] - specs = [ - # SWAP strides 1, 2, 4, 8, 16 - ("swizzle(SWAP,1)", encode_swap(1)), - ("swizzle(SWAP,2)", encode_swap(2)), - ("swizzle(SWAP,4)", encode_swap(4)), - ("swizzle(SWAP,8)", encode_swap(8)), - ("swizzle(SWAP,16)", encode_swap(16)), - # REVERSE widths 2, 4, 8, 16, 32 - ("swizzle(REVERSE,2)", encode_reverse(2)), - ("swizzle(REVERSE,4)", encode_reverse(4)), - ("swizzle(REVERSE,8)", encode_reverse(8)), - ("swizzle(REVERSE,16)", encode_reverse(16)), - ("swizzle(REVERSE,32)", encode_reverse(32)), - # BROADCAST group sizes 2, 4, 8, 16, 32 with zero and non-zero lane indices - ("swizzle(BROADCAST,2,1)", encode_broadcast(2, 1)), - ("swizzle(BROADCAST,4,2)", encode_broadcast(4, 2)), - ("swizzle(BROADCAST,8,0)", encode_broadcast(8, 0)), - ("swizzle(BROADCAST,16,0)", encode_broadcast(16, 0)), - ("swizzle(BROADCAST,32,0)", encode_broadcast(32, 0)), - ("swizzle(BROADCAST,32,19)", encode_broadcast(32, 19)), - ] - results = _run_swizzle_batch("cs_w32_swz_shorthands", specs, init_vals, 32, 32) - for idx, (mod_str, off16) in enumerate(specs): - want = ref_swizzle(init_vals, old_vals, off16, ALL32) - with self.subTest(pattern=mod_str): - self.assertEqual(results[idx], want) - - # Spot checks: SWAP,16 swaps halves; REVERSE,32 reverses all 32; BROADCAST,8,0 broadcasts 0/8/16/24. - self.assertEqual(results[4], init_vals[16:32] + init_vals[0:16]) - self.assertEqual(results[9], list(reversed(init_vals))) - self.assertEqual(results[12], [init_vals[l & ~7] for l in range(32)]) - self.assertEqual(results[13], [init_vals[l & ~15] for l in range(32)]) - self.assertEqual(results[14], [init_vals[0]] * 32) - self.assertEqual(results[15], [init_vals[19]] * 32) - - def test_butterfly_32lane_sum_reduction(self): - # Full 32-lane XOR butterfly reduction mixing SWAP and BITMASK_PERM. - init_vals = [7 * l + 5 for l in range(32)] - expected_sum = sum(init_vals) - got = run_cs("cs_w32_swz_butterfly", [ - "v_lshlrev_b32_e32 v20, 2, v0", - f"v_add_nc_u32_e32 v20, {INPUT_BASE:#x}, v20", - "buffer_load_dword v1, v20, s[0:3], 0 offen", - 'ds_swizzle_b32 v2, v1 offset:swizzle(BITMASK_PERM,"ppppi")', - "s_waitcnt lgkmcnt(0)", - "v_add_nc_u32_e32 v1, v1, v2", - "ds_swizzle_b32 v2, v1 offset:swizzle(SWAP,2)", - "s_waitcnt lgkmcnt(0)", - "v_add_nc_u32_e32 v1, v1, v2", - 'ds_swizzle_b32 v2, v1 offset:swizzle(BITMASK_PERM,"ppipp")', - "s_waitcnt lgkmcnt(0)", - "v_add_nc_u32_e32 v1, v1, v2", - "ds_swizzle_b32 v2, v1 offset:swizzle(SWAP,8)", - "s_waitcnt lgkmcnt(0)", - "v_add_nc_u32_e32 v1, v1, v2", - 'ds_swizzle_b32 v2, v1 offset:swizzle(BITMASK_PERM,"ipppp")', - "s_waitcnt lgkmcnt(0)", - "v_add_nc_u32_e32 v1, v1, v2", - "v_lshlrev_b32_e32 v21, 2, v0", - "buffer_store_dword v1, v21, s[0:3], 0 offen", - ], 32, 32, init_inputs=init_vals) - self.assertEqual(got, [expected_sum] * 32) - - -class Wave32EdgeCaseTests(unittest.TestCase): - """Aliasing, raw 32-bit pattern preservation, EXEC destination masking, and partial waves.""" - - def test_destination_aliasing_and_raw_bit_patterns(self): - # Include NaN payloads, -0.0, +inf, 0xFFFFFFFF, 0x00000000 to verify bit-exact raw shuffle. - special = [0x7FC01234, 0xFFC0DEAD, 0x80000000, 0x7F800000, 0xFFFFFFFF, 0x00000000, 0x00000001, 0xDEADBEEF] - init_vals = [special[l % len(special)] ^ (l << 8) for l in range(32)] - got = run_cs("cs_w32_swz_alias", [ - "v_lshlrev_b32_e32 v20, 2, v0", - f"v_add_nc_u32_e32 v20, {INPUT_BASE:#x}, v20", - "buffer_load_dword v1, v20, s[0:3], 0 offen", - "v_lshlrev_b32_e32 v21, 2, v0", - # Alias v1, v1 in-place - "ds_swizzle_b32 v1, v1 offset:swizzle(QUAD_PERM,3,2,1,0)", - "s_waitcnt lgkmcnt(0)", - # Alias v0, v0 in-place - 'ds_swizzle_b32 v0, v0 offset:swizzle(BITMASK_PERM,"ipppp")', - "s_waitcnt lgkmcnt(0)", - "buffer_store_dword v1, v21, s[0:3], 0 offen", - f"buffer_store_dword v0, v21, s[0:3], 0 offen offset:{4 * 32}", - ], 32, 32, init_inputs=init_vals, out_slots=2) - self.assertEqual(got[:32], ref_swizzle(init_vals, init_vals, encode_quad_perm(3, 2, 1, 0), ALL32)) - self.assertEqual(got[32:], [l ^ 16 for l in range(32)]) - - def test_exec_destination_masking_with_active_sources(self): - init_vals = [0x2000 + l * 13 for l in range(32)] - old_vals = [OLD_SENTINEL | l for l in range(32)] - - # 1. Whole active quads (quads 0, 2, 5, 7 active -> mask 0xF0F00F0F): QUAD_PERM, SWAP,1/2, REVERSE,4 - # only access lanes within the active quads, while inactive quads preserve OLD_SENTINEL | lane. - mask_quads = 0xF0F00F0F - specs_q = [ - ("swizzle(QUAD_PERM,3,2,1,0)", encode_quad_perm(3, 2, 1, 0)), - ("swizzle(QUAD_PERM,1,2,3,0)", encode_quad_perm(1, 2, 3, 0)), - ("swizzle(SWAP,1)", encode_swap(1)), - ("swizzle(REVERSE,4)", encode_reverse(4)), - ('swizzle(BITMASK_PERM,"ppp00")', encode_bitmask_perm("ppp00")), - ] - res_q = _run_swizzle_batch("cs_w32_swz_exec_quads", specs_q, init_vals, 32, 32, exec_mask=mask_quads) - for idx, (mod_str, off16) in enumerate(specs_q): - with self.subTest(mask=hex(mask_quads), pattern=mod_str): - self.assertEqual(res_q[idx], ref_swizzle(init_vals, old_vals, off16, mask_quads)) - - # 2. Active even lanes (0x55555555) broadcasting lane 0 across 8, 16, 32 lanes (all source lanes - # 0, 8, 16, 24 are even, hence active); odd lanes keep OLD_SENTINEL | lane. - mask_even = 0x55555555 - specs_e = [ - ("swizzle(BROADCAST,8,0)", encode_broadcast(8, 0)), - ("swizzle(BROADCAST,16,0)", encode_broadcast(16, 0)), - ("swizzle(BROADCAST,32,0)", encode_broadcast(32, 0)), - ('swizzle(BITMASK_PERM,"ipppp")', encode_bitmask_perm("ipppp")), # even^16 is even (active) - ] - res_e = _run_swizzle_batch("cs_w32_swz_exec_even", specs_e, init_vals, 32, 32, exec_mask=mask_even) - for idx, (mod_str, off16) in enumerate(specs_e): - with self.subTest(mask=hex(mask_even), pattern=mod_str): - self.assertEqual(res_e[idx], ref_swizzle(init_vals, old_vals, off16, mask_even)) - - def test_inactive_source_lane_reads_zero(self): - # EXEC without lane 0: BROADCAST,32,0 and QUAD_PERM,0,0,0,0 read lane 0 (or quad 0's lane 0) from an - # inactive source and get 0; lane 0 keeps its vD; REVERSE,32 lane 31 reads inactive lane 0. - init_vals = [0x3000 + l * 7 for l in range(32)] - old_vals = [OLD_SENTINEL | l for l in range(32)] - mask = ALL32 ^ 1 - specs = [ - ("swizzle(BROADCAST,32,0)", encode_broadcast(32, 0)), - ("swizzle(QUAD_PERM,0,0,0,0)", encode_quad_perm(0, 0, 0, 0)), - ("swizzle(REVERSE,32)", encode_reverse(32)), - ] - res = _run_swizzle_batch("cs_w32_swz_inact_src", specs, init_vals, 32, 32, exec_mask=mask) - for idx, (mod_str, off16) in enumerate(specs): - with self.subTest(pattern=mod_str): - self.assertEqual(res[idx], ref_swizzle(init_vals, old_vals, off16, mask)) - self.assertEqual(res[0], [OLD_SENTINEL] + [0] * 31) - self.assertEqual(res[1][:5], [OLD_SENTINEL, 0, 0, 0, 0x3000 + 4 * 7]) - self.assertEqual(res[2][31], 0) - - def test_partial_wave_20_lanes(self): - # 20 threads on a 32-wide subgroup: lanes 20..31 do not exist. - # Quads [0..3]..[16..19] are complete, so QUAD_PERM / SWAP,1 / SWAP,2 / REVERSE,4 stay in-bounds. - # Under EXEC = 0xFFFF (lanes 16..19 off), SWAP,8 on lanes 0..15 reads lanes 0..15; lanes 16..19 keep vD. - got = run_cs("cs_w32_swz_partial20", [ - "v_add_nc_u32_e32 v1, 700, v0", - f"v_or_b32_e32 v2, {OLD_SENTINEL:#x}, v0", - f"v_or_b32_e32 v3, {OLD_SENTINEL:#x}, v0", - f"v_or_b32_e32 v4, {OLD_SENTINEL:#x}, v0", - "ds_swizzle_b32 v2, v1 offset:swizzle(QUAD_PERM,1,2,3,0)", - "ds_swizzle_b32 v3, v1 offset:swizzle(BROADCAST,4,3)", - "s_mov_b32 exec_lo, 0xffff", - "ds_swizzle_b32 v4, v1 offset:swizzle(SWAP,8)", - "s_waitcnt lgkmcnt(0)", - "s_mov_b32 exec_lo, -1", - *store_slots_lines(["v2", "v3", "v4"], 20), - ], 20, 32, out_slots=3) - vals = [700 + l for l in range(20)] + [0] * 12 - old = [OLD_SENTINEL | l for l in range(20)] + [0] * 12 - self.assertEqual(got[0:20], ref_swizzle(vals, old, encode_quad_perm(1, 2, 3, 0), 0xFFFFF)[:20]) - self.assertEqual(got[20:40], ref_swizzle(vals, old, encode_broadcast(4, 3), 0xFFFFF)[:20]) - self.assertEqual(got[40:60], ref_swizzle(vals, old, encode_swap(8), 0xFFFF)[:20]) - - # SWAP,16: lanes 4..15 read absent lanes 20..31 and get 0 (the translator's model for an absent source, - # as in test_ds_permute.py; unverified on hardware); lanes 0..3 and 16..19 swap with each other. - got = run_cs("cs_w32_swz_partial20_absent", [ - "v_add_nc_u32_e32 v1, 700, v0", - "ds_swizzle_b32 v2, v1 offset:swizzle(SWAP,16)", - "s_waitcnt lgkmcnt(0)", - *store_slots_lines(["v2"], 20), - ], 20, 32) - self.assertEqual(got, [716, 717, 718, 719] + [0] * 12 + [700, 701, 702, 703]) - - -class Wave64ExecutionTests(unittest.TestCase): - """End-to-end 64-lane execution on BOTH one 64-wide subgroup AND two 32-wide subgroups.""" - - def test_all_five_modes_stay_isolated_per_32lane_half_on_sg64_and_sg32(self): - init_vals = [0x4000 + l * 31 for l in range(64)] - old_vals = [OLD_SENTINEL | l for l in range(64)] - specs = [ - # QUAD_PERM - ("swizzle(QUAD_PERM,0,0,0,0)", encode_quad_perm(0, 0, 0, 0)), - ("swizzle(QUAD_PERM,3,2,1,0)", encode_quad_perm(3, 2, 1, 0)), - ("swizzle(QUAD_PERM,1,0,3,2)", encode_quad_perm(1, 0, 3, 2)), - ("swizzle(QUAD_PERM,1,2,3,0)", encode_quad_perm(1, 2, 3, 0)), - # BITMASK_PERM (XOR butterflies, AND/OR broadcasts, mixed) - ('swizzle(BITMASK_PERM,"ppppi")', encode_bitmask_perm("ppppi")), - ('swizzle(BITMASK_PERM,"ipppp")', encode_bitmask_perm("ipppp")), - ('swizzle(BITMASK_PERM,"00000")', encode_bitmask_perm("00000")), - ('swizzle(BITMASK_PERM,"11111")', encode_bitmask_perm("11111")), - ('swizzle(BITMASK_PERM,"pippi")', encode_bitmask_perm("pippi")), - ('swizzle(BITMASK_PERM,"10p0i")', encode_bitmask_perm("10p0i")), - # SWAP - ("swizzle(SWAP,4)", encode_swap(4)), - ("swizzle(SWAP,16)", encode_swap(16)), - # REVERSE - ("swizzle(REVERSE,8)", encode_reverse(8)), - ("swizzle(REVERSE,32)", encode_reverse(32)), - # BROADCAST - ("swizzle(BROADCAST,16,5)", encode_broadcast(16, 5)), - ("swizzle(BROADCAST,32,0)", encode_broadcast(32, 0)), - ] - for subgroup_size in (64, 32): - results = _run_swizzle_batch( - f"cs_w64_swz_all_sg{subgroup_size}", specs, init_vals, 64, subgroup_size, - ) - for idx, (mod_str, off16) in enumerate(specs): - want = ref_swizzle(init_vals, old_vals, off16, ALL64) - with self.subTest(subgroup_size=subgroup_size, pattern=mod_str): - self.assertEqual(results[idx], want) - - # Explicitly confirm upper-half [32..63] isolation from lower-half [0..31]: - # BITMASK_PERM "00000" and BROADCAST,32,0 -> lanes 0..31 get init[0], lanes 32..63 get init[32]. - self.assertEqual(results[6], [init_vals[0]] * 32 + [init_vals[32]] * 32) - self.assertEqual(results[15], [init_vals[0]] * 32 + [init_vals[32]] * 32) - # REVERSE,32 -> low half reversed within 0..31, high half reversed within 32..63. - self.assertEqual(results[13], list(reversed(init_vals[:32])) + list(reversed(init_vals[32:]))) - - def test_wave64_asymmetric_exec_mask_and_butterfly_halves(self): - init_vals = [0x3000 + l * 7 for l in range(64)] - old_vals = [OLD_SENTINEL | l for l in range(64)] - # Low half: quads 0, 3, 5 active; high half: quads 1, 2, 6, 7 active. - exec_asym = (0xFF000FF0 << 32) | 0x00F0F00F - specs = [ - ("swizzle(QUAD_PERM,3,2,1,0)", encode_quad_perm(3, 2, 1, 0)), - ("swizzle(SWAP,2)", encode_swap(2)), - ('swizzle(BITMASK_PERM,"ppp11")', encode_bitmask_perm("ppp11")), - ] - for subgroup_size in (64, 32): - res = _run_swizzle_batch( - f"cs_w64_swz_exec_sg{subgroup_size}", specs, init_vals, 64, subgroup_size, exec_mask=exec_asym, - ) - for idx, (mod_str, off16) in enumerate(specs): - with self.subTest(subgroup_size=subgroup_size, pattern=mod_str): - self.assertEqual(res[idx], ref_swizzle(init_vals, old_vals, off16, exec_asym)) - - # 5-stage butterfly reduction in wave64 produces independent sums for [0..31] and [32..63]. - sum_lo = sum(init_vals[:32]) - sum_hi = sum(init_vals[32:]) - for subgroup_size in (64, 32): - with self.subTest(butterfly_subgroup=subgroup_size): - got = run_cs(f"cs_w64_swz_butterfly_sg{subgroup_size}", [ - "s_mov_b64 exec, -1", - "v_lshlrev_b32_e32 v20, 2, v0", - f"v_add_nc_u32_e32 v20, {INPUT_BASE:#x}, v20", - "buffer_load_dword v1, v20, s[0:3], 0 offen", - "ds_swizzle_b32 v2, v1 offset:swizzle(SWAP,1)", - "s_waitcnt lgkmcnt(0)", - "v_add_nc_u32_e32 v1, v1, v2", - "ds_swizzle_b32 v2, v1 offset:swizzle(SWAP,2)", - "s_waitcnt lgkmcnt(0)", - "v_add_nc_u32_e32 v1, v1, v2", - "ds_swizzle_b32 v2, v1 offset:swizzle(SWAP,4)", - "s_waitcnt lgkmcnt(0)", - "v_add_nc_u32_e32 v1, v1, v2", - "ds_swizzle_b32 v2, v1 offset:swizzle(SWAP,8)", - "s_waitcnt lgkmcnt(0)", - "v_add_nc_u32_e32 v1, v1, v2", - "ds_swizzle_b32 v2, v1 offset:swizzle(SWAP,16)", - "s_waitcnt lgkmcnt(0)", - "v_add_nc_u32_e32 v1, v1, v2", - "v_lshlrev_b32_e32 v21, 2, v0", - "buffer_store_dword v1, v21, s[0:3], 0 offen", - ], 64, subgroup_size, init_inputs=init_vals) - self.assertEqual(got, [sum_lo] * 32 + [sum_hi] * 32) - - def test_wave64_partial_wave_40_lanes(self): - # 40 threads on a 64-wide subgroup: [0..31] complete, [32..39] complete 8-lane block, [40..63] missing. - exec_low32 = 0x00000000FFFFFFFF - got = run_cs("cs_w64_swz_partial40", [ - "s_mov_b64 exec, -1", - "v_add_nc_u32_e32 v1, 200, v0", - f"v_or_b32_e32 v2, {OLD_SENTINEL:#x}, v0", - f"v_or_b32_e32 v3, {OLD_SENTINEL:#x}, v0", - "ds_swizzle_b32 v2, v1 offset:swizzle(REVERSE,8)", - *exec_mask_lines(exec_low32, 64), - "ds_swizzle_b32 v3, v1 offset:swizzle(SWAP,16)", - "s_waitcnt lgkmcnt(0)", - *restore_exec_lines(64), - *store_slots_lines(["v2", "v3"], 40), - ], 40, 64, out_slots=2) - vals64 = [200 + l for l in range(40)] + [0] * 24 - old64 = [OLD_SENTINEL | l for l in range(40)] + [0] * 24 - self.assertEqual(got[:40], ref_swizzle(vals64, old64, encode_reverse(8), ALL64)[:40]) - self.assertEqual(got[40:], ref_swizzle(vals64, old64, encode_swap(16), exec_low32)[:40]) - - -class PixelShaderWaveInterpTests(unittest.TestCase): - """End-to-end 32-lane pixel shader execution via `spirv_wave_interp.run_wave`.""" - - def test_ps_bitmask_quad_and_broadcast_via_wave_interp(self): - # Hand-written PS mirroring runtime/test/shaders/ps_bitmask_perm.asm plus QUAD_PERM & BROADCAST. - spv, _ = translate_ps("ps_swz_wave32", [ - "v_mbcnt_lo_u32_b32 v0, -1, 0", - 'ds_swizzle_b32 v1, v0 offset:swizzle(BITMASK_PERM,"pippi")', - 'ds_swizzle_b32 v2, v0 offset:swizzle(BITMASK_PERM,"10p0i")', - "ds_swizzle_b32 v3, v0 offset:swizzle(QUAD_PERM,1,2,3,0)", - "s_waitcnt lgkmcnt(0)", - "exp mrt0 v0, v1, v2, v3 done vm", - ]) - res = wi.run_wave(spv, wave=32) - for lane in range(32): - got = res["outputs"][lane]["%out_mrt0"] - want = ( - lane, - lane ^ 9, - ((lane & 5) | 16) ^ 1, - (lane & ~3) | ((lane + 1) & 3), - ) - self.assertEqual(got, want, f"lane {lane}: got {got}, want {want}") - - -class EmulationAndParsingTests(unittest.TestCase): - """Structural SPIR-V checks for `--wave64-emulate`; unparsed offsets raise Unsupported.""" - - def test_wave64_emulate_lowers_all_five_modes_via_x_buf_without_subgroup_ops(self): - cases = [ - ("quad", "swizzle(QUAD_PERM,3,2,1,0)", r"%cfffffffc\b"), - ("bitmask", 'swizzle(BITMASK_PERM,"10p0i")', r"%cffffffe5\b"), - ("swap", "swizzle(SWAP,16)", r"OpBitwiseXor %uint %\w+ %c10\b"), - ("reverse", "swizzle(REVERSE,32)", r"OpBitwiseXor %uint %\w+ %c1f\b"), - ("broadcast", "swizzle(BROADCAST,16,5)", r"%cfffffff0\b"), - ] - for label, mod_str, expected_pat in cases: - with self.subTest(mode=label): - lines = [ - "s_mov_b64 exec, -1", - "v_add_nc_u32_e32 v1, 100, v0", - f"ds_swizzle_b32 v2, v1 offset:{mod_str}", - "s_waitcnt lgkmcnt(0)", - "v_lshlrev_b32_e32 v21, 2, v0", - "buffer_store_dword v2, v21, s[0:3], 0 offen", - ] - spv, gen = translate_cs(f"cs_w64_emu_swz_{label}", lines, 64, emulate=True) - self.assertTrue(gen.wave64 and gen.emulate) - self.assertNotIn("OpGroupNonUniform", spv) - self.assertNotIn("%sg_lane", spv) - self.assertIn("%x_buf = OpVariable", spv) - self.assertGreaterEqual(spv.count("OpControlBarrier"), 2) - self.assertRegex(spv, expected_pat) - # spirv_mini_interp.py deliberately rejects the Workgroup-memory round loop. - with self.assertRaises(si.UnsupportedConstruct): - si.run_workgroup( - spv, 64, 32, - inputs_for=lambda i: {"%wg_id": (0, 0, 0), "%local_id": (i, 0, 0), "%sg_lane": i % 32}, - push_constants=VSHARP + [0] * 28, memory={}, - ) - - # Wave32 shaders are unaffected by WAVE64_EMULATE = True. - w32_lines = [ - "ds_swizzle_b32 v2, v0 offset:swizzle(SWAP,8)", - "s_waitcnt lgkmcnt(0)", - "v_lshlrev_b32_e32 v21, 2, v0", - "buffer_store_dword v2, v21, s[0:3], 0 offen", - ] - spv_plain, _ = translate_cs("cs_w32_emu_swz_nop", w32_lines, 32, emulate=False) - spv_emu, gen_emu = translate_cs("cs_w32_emu_swz_nop", w32_lines, 32, emulate=True) - self.assertFalse(gen_emu.wave64 or gen_emu.emulate) - self.assertEqual(spv_plain, spv_emu) - - def test_raw_numeric_offsets_and_unknown_swizzle_kind_raise_unsupported(self): - # A numeric offset in the bitmask or QUAD_PERM range is decoded since #4177; 0xC000..0xFFFF is a separate mode - # on RDNA2 (measured on gfx1036 for all 16,384 offsets, docs/design.md "ds_swizzle_b32"), so it and an unknown - # kind are refused, not guessed. - for bad_mod in ("offset:0xc000", "offset:0xffff", "offset:swizzle(UNKNOWN,1)"): - with self.subTest(mod=bad_mod): - with self.assertRaises(rdna2spirv.Unsupported): - translate_cs("cs_w32_swz_bad", [ - f"ds_swizzle_b32 v2, v0 {bad_mod}", - "s_waitcnt lgkmcnt(0)", - "v_lshlrev_b32_e32 v21, 2, v0", - "buffer_store_dword v2, v21, s[0:3], 0 offen", - ], 32) - -class NegativeControls(unittest.TestCase): - """Sabotage translated SPIR-V like a translator regression; multi-lane execution must catch it.""" - - def _run(self, spv: str, threads: int, subgroup_size: int) -> list[int]: - mem = _Heap() - si.run_workgroup( - spv, threads, subgroup_size, - inputs_for=lambda i: {"%wg_id": (0, 0, 0), "%local_id": (i, 0, 0), "%sg_lane": i % subgroup_size}, - push_constants=VSHARP + [0] * 28, - memory=mem, - ) - return [mem.get(4 * k) for k in range(threads)] - - def test_sabotage_bitmask_upper_half_mask_dropped_in_wave64(self): - # Dropping 0xFFFFFFE0 -> 0 causes upper half [32..63] to read from lower half [0..31]. - spv, _ = translate_cs("cs_w64_neg_bm", [ - "s_mov_b64 exec, -1", - "v_add_nc_u32_e32 v1, 100, v0", - 'ds_swizzle_b32 v2, v1 offset:swizzle(BITMASK_PERM,"00000")', - "s_waitcnt lgkmcnt(0)", - "v_lshlrev_b32_e32 v21, 2, v0", - "buffer_store_dword v2, v21, s[0:3], 0 offen", - ], 64) - want = [100] * 32 + [132] * 32 - self.assertEqual(self._run(spv, 64, 64), want) - - bad, n = re.subn(r"OpBitwiseAnd %uint (%\w+) %cffffffe0\b", r"OpBitwiseAnd %uint \1 %c0", spv) - self.assertEqual(n, 1) - got_bad = self._run(bad, 64, 64) - self.assertNotEqual(got_bad, want) - self.assertEqual(got_bad, [100] * 64) - - def test_sabotage_quad_base_mask_shuffle_and_exec_guard(self): - spv, _ = translate_cs("cs_w32_neg_quad", [ - "v_add_nc_u32_e32 v1, 300, v0", - f"v_or_b32_e32 v2, {OLD_SENTINEL:#x}, v0", - "s_mov_b32 exec_lo, 0x0f0f0f0f", - "ds_swizzle_b32 v2, v1 offset:swizzle(QUAD_PERM,3,2,1,0)", - "s_waitcnt lgkmcnt(0)", - "s_mov_b32 exec_lo, -1", - "v_lshlrev_b32_e32 v21, 2, v0", - "buffer_store_dword v2, v21, s[0:3], 0 offen", - ], 32) - want = ref_swizzle([300 + l for l in range(32)], [OLD_SENTINEL | l for l in range(32)], - encode_quad_perm(3, 2, 1, 0), 0x0F0F0F0F) - self.assertEqual(self._run(spv, 32, 32), want) - - # 1. Dropping quad base mask 0xFFFFFFFC sends every quad to quad 0. - lane = re.search(r"OpBitwiseAnd %uint (%\w+) %c3\b", spv).group(1) # sel = lane & 3; base = lane & ~3 - bad_base, n1 = re.subn(rf"OpBitwiseAnd %uint {lane} %cfffffffc\b", rf"OpBitwiseAnd %uint {lane} %c0", spv) - self.assertEqual(n1, 1) - self.assertNotEqual(self._run(bad_base, 32, 32), want) - - # 2. Replacing OpGroupNonUniformShuffle with OpCopyObject turns swizzle into own-lane copy. - bad_shuf, n2 = re.subn( - r"(%\w+) = OpGroupNonUniformShuffle %uint %c3 (%\w+) %\w+", - r"\1 = OpCopyObject %uint \2", - spv, - ) - self.assertEqual(n2, 1) - self.assertNotEqual(self._run(bad_shuf, 32, 32), want) - - # 3. Making the destination EXEC mask all ones (the write after the shuffle) overwrites inactive quads. - at = spv.index("OpGroupNonUniformShuffle %uint %c3") - tail, n3 = re.subn( - r"(%\w+) = OpSelect %uint %\w+ %cffffffff %c0\n(\s*)(%\w+) = OpNot %uint \1\b", - r"\1 = OpCopyObject %uint %cffffffff\n\2\3 = OpNot %uint \1", - spv[at:], - count=1, - ) - bad_exec = spv[:at] + tail - self.assertEqual(n3, 1) - got_exec = self._run(bad_exec, 32, 32) - self.assertNotEqual(got_exec, want) - self.assertNotEqual(got_exec[4], OLD_SENTINEL | 4) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_ds_swizzle_numeric.py b/tests/semantic/test_ds_swizzle_numeric.py deleted file mode 100644 index 17ab118db..000000000 --- a/tests/semantic/test_ds_swizzle_numeric.py +++ /dev/null @@ -1,180 +0,0 @@ -"""Semantic tests for ds_swizzle_b32 with raw numeric offset:N and omitted offset (= 0). - -RDNA2 ISA DS_SWIZZLE_B32 encodes the swizzle in a 16-bit offset (verified across all 65,536 offsets on gfx1036): - - 0x8000..0xBFFF (bits 15:14 = 10, QDMode): quad-permute using bits [7:0] (two bits per lane 0..3; bits [13:8] - ignored; llvm-mc -mcpu=gfx1013 disassembles non-zero bits [13:8] as decimal offset:N, e.g. 0x81e4 -> 33252). - - 0x0000..0x7FFF (bit 15 = 0, Bitmask mode): within each 32-lane half, src = ((lane & and_mask) | or_mask) ^ xor_mask - with and_mask = offset[4:0], or_mask = offset[9:5], xor_mask = offset[14:10]. - - 0xC000..0xFFFF (bits 15:14 = 11): separate hardware mode (rotations/interleavings, not quad permute); refused. - - omitted offset defaults to 0 (broadcast lane 0 / lane 32 in wave64); llvm-mc omits offset:0 on disassembly. - - python -I tests/semantic/test_ds_swizzle_numeric.py -v -""" -import os -import shutil -import subprocess -import sys -import tempfile -import unittest - -HERE = os.path.dirname(os.path.abspath(__file__)) -if HERE not in sys.path: - sys.path.insert(0, HERE) - -import spirv_mini_interp as si # noqa: E402 -import support # noqa: E402 -from support import rdna2spirv # noqa: E402 - -SHADERS = os.path.join(support.ROOT, "runtime", "test", "shaders") - - -def _validate_spv(spvasm): - spirv_as, spirv_val = shutil.which("spirv-as"), shutil.which("spirv-val") - if not (spirv_as and spirv_val): - return - with tempfile.TemporaryDirectory() as tmp: - spv = os.path.join(tmp, "out.spv") - r = subprocess.run([spirv_as, "--target-env", "vulkan1.2", "-o", spv, "-"], - input=spvasm, text=True, capture_output=True) - if r.returncode: - raise AssertionError(f"spirv-as failed:\n{r.stderr}") - r = subprocess.run([spirv_val, "--target-env", "vulkan1.2", spv], - capture_output=True, text=True) - if r.returncode: - raise AssertionError(f"spirv-val failed:\n{r.stderr}") - - -def _fssm(wave): - if SHADERS not in sys.path: - sys.path.insert(0, SHADERS) - from compute_fixture import compute_header - asm_name = "cs_w32_mask_imm.asm" if wave == 32 else "cs_wm_bfm64.asm" - return bytes(compute_header(os.path.join(SHADERS, asm_name))) - - -def _run_swizzle(name, swizzle_line, wave=32): - lines = [ - "v_add_nc_u32_e32 v1, 100, v0", - swizzle_line, - "v_lshlrev_b32_e32 v3, 2, v0", - "buffer_store_dword v2, v3, s[0:3], 0 offen", - "s_endpgm", - ] - spvasm = support.translate_lines(name, lines, fssm=_fssm(wave)) - _validate_spv(spvasm) - mem = {4 * i: 0xEEEEEEEE for i in range(wave)} - si.run_workgroup( - spvasm, wave, wave, - inputs_for=lambda i: {"%wg_id": (0, 0, 0), "%local_id": (i, 0, 0), "%sg_lane": i}, - push_constants=[0, 0, 0xFFFFFFFF, 0x31016FAC] + [0] * 28, - memory=mem, - ) - return [mem[4 * i] for i in range(wave)] - - -def _expected_numeric(off, wave): - out = [] - for lane in range(wave): - if off & 0x8000: - sel = (off >> (2 * (lane & 3))) & 3 - src = (lane & ~3) | sel - else: - and_m = off & 0x1F - or_m = (off >> 5) & 0x1F - xor_m = (off >> 10) & 0x1F - src = (lane & ~31) | ((((lane & 31) & and_m) | or_m) ^ xor_m) - out.append(100 + src) - return out - - -class DsSwizzleNumericTests(unittest.TestCase): - def test_qdmode_numeric_decimal_and_hex_wave32_and_wave64(self): - cases = [ - # 0x801f = QUAD_PERM(3, 3, 1, 0) - ("qd_801f", "ds_swizzle_b32 v2, v1 offset:0x801f", 0x801F), - # 0x81e4 = decimal 33252 (non-zero bit 8, what llvm-mc prints as numeric): QUAD_PERM(0, 1, 2, 3) - ("qd_33252", "ds_swizzle_b32 v2, v1 offset:33252", 0x81E4), - # 0xbf1b = QUAD_PERM(3, 2, 1, 0) with all ignored bits 13:8 set and bit 14 clear - ("qd_bf1b", "ds_swizzle_b32 v2, v1 offset:0xbf1b", 0xBF1B), - ] - for tag, line, off in cases: - for wave in (32, 64): - with self.subTest(case=tag, wave=wave): - self.assertEqual(_run_swizzle(f"cs_{tag}_w{wave}", line, wave=wave), - _expected_numeric(off, wave)) - - def test_bitmask_numeric_and_omitted_offset_wave32_and_wave64(self): - cases = [ - # Omitted offset == 0 (broadcast lane 0 / lane 32 in wave64) - ("omitted", "ds_swizzle_b32 v2, v1", 0x0000), - # Explicit offset:0 - ("zero", "ds_swizzle_b32 v2, v1 offset:0", 0x0000), - # 0x041f = SWAP(1) (and=31, or=0, xor=1) - ("swap1", "ds_swizzle_b32 v2, v1 offset:0x041f", 0x041F), - # 0x401f = SWAP(16) (and=31, or=0, xor=16) - ("swap16", "ds_swizzle_b32 v2, v1 offset:0x401f", 0x401F), - # 0x7c1f = REVERSE(32) (and=31, or=0, xor=31) - ("rev32", "ds_swizzle_b32 v2, v1 offset:0x7c1f", 0x7C1F), - # 0x00a0 = BROADCAST(32, 5) (and=0, or=5, xor=0) - ("bcast5", "ds_swizzle_b32 v2, v1 offset:0x00a0", 0x00A0), - # Mixed and/or/xor: and=0x18 (keep bits 4,3), or=0x03 (set bits 1,0), xor=0x05 (flip bits 2,0) - ("mixed", "ds_swizzle_b32 v2, v1 offset:0x1478", 0x1478), - ] - for tag, line, off in cases: - for wave in (32, 64): - with self.subTest(case=tag, wave=wave): - self.assertEqual(_run_swizzle(f"cs_{tag}_w{wave}", line, wave=wave), - _expected_numeric(off, wave)) - - def test_numeric_matches_symbolic_forms(self): - pairs = [ - ("ds_swizzle_b32 v2, v1 offset:0x801f", 'ds_swizzle_b32 v2, v1 offset:swizzle(QUAD_PERM,3,3,1,0)'), - ("ds_swizzle_b32 v2, v1 offset:0x041f", 'ds_swizzle_b32 v2, v1 offset:swizzle(SWAP,1)'), - ("ds_swizzle_b32 v2, v1 offset:0x7c1f", 'ds_swizzle_b32 v2, v1 offset:swizzle(REVERSE,32)'), - ("ds_swizzle_b32 v2, v1 offset:0x00a0", 'ds_swizzle_b32 v2, v1 offset:swizzle(BROADCAST,32,5)'), - ("ds_swizzle_b32 v2, v1", 'ds_swizzle_b32 v2, v1 offset:swizzle(BITMASK_PERM,"00000")'), - ] - for idx, (num_line, sym_line) in enumerate(pairs): - with self.subTest(pair=idx): - self.assertEqual( - _run_swizzle(f"cs_num_{idx}", num_line, wave=64), - _run_swizzle(f"cs_sym_{idx}", sym_line, wave=64), - ) - - def test_wave64_emulate_validates_with_spirv_val(self): - old_emulate = rdna2spirv.WAVE64_EMULATE - rdna2spirv.WAVE64_EMULATE = True - try: - for tag, swz in (("qd", "ds_swizzle_b32 v2, v1 offset:33252"), - ("bm", "ds_swizzle_b32 v2, v1 offset:0x1478"), - ("zero", "ds_swizzle_b32 v2, v1")): - lines = [ - "v_add_nc_u32_e32 v1, 100, v0", - swz, - "v_lshlrev_b32_e32 v3, 2, v0", - "buffer_store_dword v2, v3, s[0:3], 0 offen", - "s_endpgm", - ] - spvasm = support.translate_lines(f"cs_emul_{tag}", lines, fssm=_fssm(64)) - _validate_spv(spvasm) - finally: - rdna2spirv.WAVE64_EMULATE = old_emulate - - def test_invalid_offsets_and_modifiers_stay_refused(self): - for bad in ( - "ds_swizzle_b32 v2, v1 offset:0xc000", - "ds_swizzle_b32 v2, v1 offset:0xff1b", - "ds_swizzle_b32 v2, v1 offset:0xffff", - "ds_swizzle_b32 v2, v1 offset:65536", - "ds_swizzle_b32 v2, v1 offset:-1", - "ds_swizzle_b32 v2, v1 offset:notanumber", - "ds_swizzle_b32 v2, v1 offset:swizzle(UNKNOWN,1)", - "ds_swizzle_b32 v2, v1 offset:0x801f gds", - ): - with self.subTest(bad=bad): - with self.assertRaises(rdna2spirv.Unsupported): - support.translate_lines("cs_swz_bad", [bad, "s_endpgm"], fssm=_fssm(32)) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_exec_computed.py b/tests/semantic/test_exec_computed.py deleted file mode 100644 index 2c1a3a629..000000000 --- a/tests/semantic/test_exec_computed.py +++ /dev/null @@ -1,62 +0,0 @@ -"""SHADER-1264: a computed 32-bit value written to exec_lo / exec_hi turns on the lanes whose bit is set. - -runtime/test/shaders/cs_w32_exec_computed.asm and cs_w64_exec_computed.asm write values the translator can't fold -(built from v_readfirstlane_b32) into EXEC with s_lshl_b32, s_add_u32, s_bfm_b32, s_not_b32, s_mov_b32 and a lane -mask s_and_b32 a number. Each lane of that half takes its own bit of the value; testing the value for non-zero turns -on the whole half. Run on all lanes of one wave (32, and 64 without --wave64-emulate) with a heap of 0xee bytes; the -words are the GPU check's (check.py CS_DUMPS, run_gpu_tests.py), derived by hand in each .asm header. -""" -import os -import sys -import unittest - -import support -import spirv_mini_interp as si - - -class ExecComputed(unittest.TestCase): - WANT = {"cs_w32_exec_computed": (32, [259, 1028, 3088, 7682, 512, 4100, 0, 3]), - "cs_w64_exec_computed": (64, [291, 1028, 11264, 771, 8192, 4132, 0, 3])} - # The words with the value tested for non-zero (main before SHADER-1264, measured on the GPU): the first three - # cases of cs_w32 and the first four of cs_w64 turn on every lane of the half they write. - OLD_PREFIX = {"cs_w32_exec_computed": [8192, 8192, 8192], - "cs_w64_exec_computed": [8224, 8192, 16384, 16384]} - - def run_words(self, name, lanes): - sys.path.insert(0, os.path.join(support.ROOT, "runtime", "test", "shaders")) - from compute_fixture import compute_header - header = compute_header(os.path.join(support.ROOT, "runtime", "test", "shaders", name + ".asm")) - spv = support.translate_fixture(name, fssm=bytes(header)) - memory = {a: 0xEEEEEEEE for a in range(0, 0x100, 4)} - si.run_workgroup(spv, lanes, lanes, - inputs_for=lambda i: {"%wg_id": (0, 0, 0), "%local_id": (i, 0, 0), "%sg_lane": i}, - push_constants=[0, 0, 0xFFFFFFFF, 0x31016FAC] + [0] * 28, memory=memory) - self.assertEqual(set(memory), set(range(0, 0x100, 4)), "nothing written outside the heap") - return [memory[4 * i] for i in range(8)] - - def test_words(self): - for name, (lanes, want) in self.WANT.items(): - with self.subTest(shader=name): - got = self.run_words(name, lanes) - self.assertEqual(got, want) - old = self.OLD_PREFIX[name] - self.assertNotEqual(got[:len(old)], old) - - def test_words_follow_from_the_masks(self): - # Plain-Python reference: word = set lanes << 8 | lowest lane of each case's resulting EXEC. - def word(m): - return bin(m).count("1") << 8 | ((m & -m).bit_length() - 1) - m32 = 0xFFFFFFFF - base, s5 = 0, 3 - w32 = [word(1 << s5), word(base + 0xF0), word(((1 << 12) - 1) << 16), word(~s5 & m32), - word(base + 0x81), word(0x000FFFFF & (base + 0xFFFF0)), base, s5] - lo, hi = m32, m32 << 32 - w64 = [word((1 << s5) << 32), word(base + 0xF0), word(lo | (((1 << 12) - 1) << 16) << 32), - word((1 << s5) | (base + 0x81) << 32), word((base + 0x81) | (~s5 & m32) << 32), - word((((1 << 52) - 1) & hi) & ((base + 0xFFFF0) << 32)), base, s5] - self.assertEqual(w32, self.WANT["cs_w32_exec_computed"][1]) - self.assertEqual(w64, self.WANT["cs_w64_exec_computed"][1]) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_export_valid_mask.py b/tests/semantic/test_export_valid_mask.py deleted file mode 100644 index 838dd31e5..000000000 --- a/tests/semantic/test_export_valid_mask.py +++ /dev/null @@ -1,219 +0,0 @@ -"""The PS valid mask: a pixel is discarded by EXEC at its last executed `exp ... vm`, not by EXEC at the end, and a -lane that was off at the last export to the color target is not written either. - -RDNA2 ISA reference guide (30-November-2020), 11.1 and 11.2.1: with VM set EXEC is the valid mask, the final one -sent is used, and an export to NULL may carry only the mask. Measured on RDNA2 (gfx1036, ps_oracle.py of #3061, 18 -programs; docs/design.md, EXEC): that rule holds, and the color export has its own mask, EXEC at that export, which -is also what decides on a path with no `vm` export (class ColorExportMask). Hand-written programs, no tools needed. -""" -from pathlib import Path -import unittest - -import support -import rdna2spirv -import shader_ir -from spirv_mini_interp import run_fragment -from spirv_wave_interp import run_wave - -ONE = 0x3F800000 -SEED = [f"v_mov_b32_e32 v2, 0x{ONE:x}", "v_mov_b32_e32 v1, 1"] -OFF = ["v_cmpx_eq_u32_e32 0, v1"] -ON = ["s_mov_b64 exec, -1"] -EXP = ["exp mrt0 v2, v2, v2, v2 done vm"] -EXP_NO_VM = ["exp mrt0 v2, v2, v2, v2"] -EXP_MRT1 = ["exp mrt1 v2, v2, v2, v2"] -NULL = ["exp null off, off, off, off done vm"] -END = ["s_endpgm"] -KILLED = {} -MRT0 = {"%out_mrt0": (ONE,) * 4} - - -def sized(lines): - """The lines with a placeholder encoding of the right size: branch offsets are counted in dwords of it.""" - out = [] - for line in lines: - size = 8 if line.startswith("exp ") or "0x3f800000" in line else 4 - out.append(f"{line} ; encoding: [" + ",".join(["0x00"] * size) + "]") - return out - - -def translate(lines): - return support.translate_lines("ps_valid_mask", sized(lines)) - - -def dwords(lines): - return sum(2 if line.startswith("exp ") or "0x3f800000" in line else 1 for line in lines) - - -class StraightLine(unittest.TestCase): - def check(self, lines, want): - self.assertEqual(run_fragment(translate(SEED + lines + END)), want) - - def test_disjoint_color_exports_accumulate_per_target(self) -> None: - fixture = Path(__file__).with_name("fixtures") / "partial_color_exports.asm" - shader = support.translate_lines("ps_partial_exports", fixture.read_text(encoding="ascii").splitlines()) - self.assertEqual(run_fragment(shader), { - "%out_mrt0": (0x3F800000, 0x40000000, 0x40400000, 0x40800000), - "%out_mrt1": (0x40A00000, 0x40C00000, 0x40E00000, 0x41000000), - }) - - def test_first_partial_color_export_has_zero_unwritten_channels(self) -> None: - lines = ["exp mrt0 off, v2, off, v2 done vm"] - shader = translate(SEED + lines + END) - self.assertEqual(run_fragment(shader), {"%out_mrt0": (0, ONE, 0, ONE)}) - # The interpreter defaults unwritten outputs to zero. Vulkan needs an explicit initializer here. - self.assertIn("%initial_mrt = OpConstantNull %v4float", shader) - self.assertIn("%out_mrt0 = OpVariable %_ptr_Output_v4 Output %initial_mrt", shader) - - def test_partial_export_obeys_exec_and_replaces_enabled_channels(self) -> None: - lines = ["v_mov_b32_e32 v3, 0x40000000", "exp mrt0 v2, v2, v2, v2", "s_waitcnt expcnt(0)"] + OFF - lines += ["exp mrt0 off, v3, v3, off", "s_waitcnt expcnt(0)"] + ON - lines += ["exp mrt0 off, off, v3, off done vm"] - self.check(lines, {"%out_mrt0": (ONE, ONE, 0x40000000, ONE)}) - - def test_exec_unchanged_after_the_export(self): - self.check(EXP, MRT0) - self.check(OFF + EXP, KILLED) - - def test_off_at_the_export_and_back_on_is_killed(self): - self.check(OFF + EXP + ON, KILLED) - - def test_on_at_the_export_and_off_afterwards_is_kept(self): - self.check(EXP + OFF, MRT0) - self.check(EXP + ["s_mov_b64 exec, 0"], MRT0) - - def test_null_export_carries_the_mask_too(self): - self.check(EXP_NO_VM + OFF + NULL + ON, KILLED) - self.check(EXP_NO_VM + NULL + OFF, MRT0) - - def test_compressed_export_carries_the_mask_too(self): - compr = ["exp mrt0 v2, v2, v2, v2 done compr vm"] - self.check(OFF + compr + ON, KILLED) - self.assertEqual(list(run_fragment(translate(SEED + compr + OFF + END))), ["%out_mrt0"]) - - def test_depth_export_carries_the_mask_too(self): - depth = ["exp mrtz v2, off, off, off done vm"] - self.check(EXP_NO_VM + OFF + depth + ON, KILLED) - self.assertEqual(run_fragment(translate(SEED + EXP_NO_VM + depth + OFF + END))["%out_mrt0"], (ONE,) * 4) - - def test_the_last_vm_export_wins(self): - first = ["exp mrt0 v2, v2, v2, v2 vm"] - self.check(first + OFF + NULL, KILLED) - self.check(first + OFF + ON + NULL + OFF, MRT0) - - def test_a_later_export_without_vm_does_not_move_the_mask(self): - self.check(EXP + OFF + EXP_MRT1, {**MRT0, "%out_mrt1": (0,) * 4}) # 0: the interpreter's unwritten output - - def test_without_a_vm_export_exec_at_the_color_export_decides(self): - # Hardware: `exp mrt0 done` with every lane on, EXEC cut afterwards: written; off at the export and back on - # afterwards: not written. Until 2026-11-23 EXEC at the end decided, the other way round for both. - self.check(EXP_NO_VM + OFF, MRT0) - self.check(EXP_NO_VM + OFF + ON, MRT0) - self.check(OFF + EXP_NO_VM + ON, KILLED) - self.check(OFF + EXP_NO_VM, KILLED) - - -class ColorExportMask(unittest.TestCase): - """Measured on RDNA2 (gfx1036): the rows of the docs/design.md EXEC table where EXEC changes between a color - export and the last `vm` export. A = 1.0 (v2), B = 2.0 (v3).""" - B = ["v_mov_b32_e32 v3, 2.0"] - EXP_B = ["exp mrt0 v3, v3, v3, v3"] - TWO = {"%out_mrt0": (0x40000000,) * 4} - - def check(self, lines, want): - self.assertEqual(run_fragment(translate(SEED + self.B + lines + END)), want) - - def test_off_at_the_color_export_is_not_written_even_with_a_later_full_vm(self): - self.check(OFF + EXP_NO_VM + ON + NULL, KILLED) - self.check(EXP_NO_VM + NULL, MRT0) - - def test_the_last_color_export_is_the_one_that_counts(self): - self.check(EXP_NO_VM + OFF + self.EXP_B + ON + NULL, KILLED) # A from every lane, then B without this one - self.check(OFF + EXP_NO_VM + ON + self.EXP_B + NULL, self.TWO) # off at A, on at B - - def test_both_masks_apply(self): - first = ["exp mrt0 v2, v2, v2, v2 vm"] - self.check(first + OFF + ["exp mrt0 v3, v3, v3, v3 done"] + ON, KILLED) # vm: on; last color export: off - self.check(OFF + first + ON + ["exp mrt0 v3, v3, v3, v3 done"], KILLED) # vm: off; last color export: on - self.check(first + ["exp mrt0 v3, v3, v3, v3 done"] + OFF, self.TWO) - - def test_another_target_keeps_the_pixel(self): - # Not measured (one target on the hardware side): a lane that exported to one target stays, as before. - self.check(EXP + OFF + EXP_MRT1, {**MRT0, "%out_mrt1": (0,) * 4}) - - -class GpuFixture(unittest.TestCase): - def test_ps_exp_color_mask(self): - """runtime/test/shaders/ps_exp_color_mask.asm: the words of its header, from every lane.""" - out = run_fragment(support.translate_fixture("ps_exp_color_mask")) - self.assertEqual(out, {"%out_mrt0": (0x40000000, 0x40800000, 0x40000000, 0x40800000)}) - - -class Branches(unittest.TestCase): - def skip_over(self, taken, skipped): - """SCC = `taken`, then a branch over `skipped`.""" - return [f"s_cmp_eq_u32 0, {0 if taken else 1}", f"s_cbranch_scc1 {dwords(skipped)}"] + skipped - - def test_exec_write_in_a_later_block(self): - for taken in (False, True): - body = EXP + self.skip_over(taken, OFF) - self.assertEqual(run_fragment(translate(SEED + body + END)), MRT0, taken) - body = OFF + EXP + self.skip_over(taken, ON) - self.assertEqual(run_fragment(translate(SEED + body + END)), KILLED, taken) - - def test_exec_write_several_blocks_later(self): - far = self.skip_over(False, ["v_mov_b32_e32 v3, 0"]) - body = EXP + far + self.skip_over(False, OFF) - self.assertEqual(run_fragment(translate(SEED + body + END)), MRT0) - body = OFF + EXP + far + self.skip_over(False, ON) - self.assertEqual(run_fragment(translate(SEED + body + END)), KILLED) - - def test_a_path_around_the_vm_export_uses_exec_at_the_color_export(self): - # The branch skips the `vm` export: that path has no valid mask, so EXEC at its color export decides. - body = EXP_NO_VM + self.skip_over(True, NULL) + OFF - self.assertEqual(run_fragment(translate(SEED + body + END)), MRT0) - body = OFF + EXP_NO_VM + ON + self.skip_over(True, NULL) - self.assertEqual(run_fragment(translate(SEED + body + END)), KILLED) - body = EXP_NO_VM + self.skip_over(False, NULL) + OFF - self.assertEqual(run_fragment(translate(SEED + body + END)), MRT0) - - def test_exec_write_earlier_in_a_loop(self): - # Two rounds. EXEC is written above the export, so only the back edge puts that write after it. - head = SEED + EXP_NO_VM + ["s_mov_b32 s4, 0"] - loop = ON + ["s_cmp_eq_u32 s4, 0", "s_cbranch_scc1 1"] + OFF + NULL + ["s_add_u32 s4, s4, 1", - "s_cmp_lt_u32 s4, 2"] - back = [f"s_cbranch_scc1 {65536 - dwords(loop) - 1}"] - text = translate(head + loop + back + ON + END) - self.assertEqual(run_wave(text, wave=32)["outputs"], [None] * 32) # off at the second round's export - loop = ON + ["s_cmp_eq_u32 s4, 1", "s_cbranch_scc1 1"] + OFF + NULL + ["s_add_u32 s4, s4, 1", - "s_cmp_lt_u32 s4, 2"] - text = translate(head + loop + back + OFF + END) - self.assertNotIn(None, run_wave(text, wave=32)["outputs"]) # on at the second round's export - - -class OnlyWhereNeeded(unittest.TestCase): - def test_no_latch_when_exec_cannot_change_after_the_export(self): - for body in (EXP, OFF + EXP, OFF + ON + EXP, OFF + EXP_NO_VM, OFF + EXP + ["s_cmp_eq_u64 exec, 0"], - OFF + EXP + ["v_mov_b32_e32 v3, 0"]): - text = translate(SEED + body + END) - self.assertNotIn("%vm_mask", text, body) - self.assertNotIn("%col_mask", text, body) - self.assertIn("%col_mask_mrt0", translate(SEED + EXP_NO_VM + OFF + END)) # EXEC changes after a color export - - def test_code_after_endpgm_does_not_count(self): - self.assertNotIn("%vm_mask", translate(SEED + OFF + EXP + END + ON)) - - def test_every_form_that_writes_exec_is_seen(self): - for line in ("v_cmpx_eq_u32_e32 0, v1", "v_cmpx_lt_f32_e64 v1, v2", "v_cmpx_class_f32_e32 v1, v2", - "v_cmpx_eq_u64 v[2:3], v[4:5]", "s_and_saveexec_b64 s[4:5], vcc", - "s_or_saveexec_b32 s4, vcc_lo", "s_andn2_wrexec_b64 s[4:5], s[6:7]", "s_mov_b64 exec, -1", - "s_mov_b32 exec_lo, -1", "s_mov_b32 exec_hi, 0", "s_wqm_b64 exec, exec", - "s_and_b64 exec, exec, s[4:5]", "v_cmp_eq_u32_e64 exec, 0, v1"): - self.assertTrue(rdna2spirv.writes_exec(shader_ir.parse_line("\t" + line)), line) - for line in ("s_cmp_eq_u64 exec, 0", "s_bitcmp1_b32 exec_lo, 3", "s_mov_b64 s[4:5], exec", - "exp mrt0 v0, v1, v2, v3 done vm", "v_cndmask_b32_e64 v0, v1, v2, exec"): - self.assertFalse(rdna2spirv.writes_exec(shader_ir.parse_line("\t" + line)), line) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_f16_bin_tern_validation.py b/tests/semantic/test_f16_bin_tern_validation.py deleted file mode 100644 index 2e57d46fe..000000000 --- a/tests/semantic/test_f16_bin_tern_validation.py +++ /dev/null @@ -1,417 +0,0 @@ -"""Operand, encoding, and modifier validation tests for the 13 binary/ternary f16 VALU ops. - -Covers: - - VOP2-only literal FMA ops: v_fmamk_f16, v_fmaak_f16 - - VOP2/VOP3 (+ SDWA/DPP) binary ops: v_add_f16, v_sub_f16, v_subrev_f16, v_mul_f16, v_min_f16, v_max_f16 - - VOP3-only ternary ops: v_fma_f16, v_med3_f16, v_min3_f16, v_max3_f16 - - VOP2/VOP3 exponent-scaling op: v_ldexp_f16 - -Verifies negative rejection (rdna2spirv.Unsupported) across malformed encodings, arities, -destinations, source widths/modifiers, and instruction modifiers, plus positive controls -executed in spirv_mini_interp and validated with spirv-as + spirv-val --target-env vulkan1.2. -Standard library only; no GPU, no game files. -""" -import os -import shutil -import struct -import subprocess -import sys -import tempfile -import unittest -import warnings - -HERE = os.path.dirname(os.path.abspath(__file__)) -ROOT = os.path.dirname(os.path.dirname(HERE)) -TOOLS = os.environ.get("LEONIDA_TOOLS_DIR") or os.path.join(ROOT, "tools") - -sys.dont_write_bytecode = True -for p in (TOOLS, HERE): - if p not in sys.path: - sys.path.insert(0, p) - -import rdna2spirv # noqa: E402 -import spirv_mini_interp as si # noqa: E402 - -STUB_DXBC = b"DXBC" + bytes(24) + struct.pack(" str: - if _TMP is None: - setUpModule() - asm = "; ps_f16_bin_tern_val\n" + "".join(f"\t{ln}\n" for ln in lines) - with open(_SRC_PATH, "w", encoding="utf-8", newline="\n") as f: - f.write(asm) - with warnings.catch_warnings(): - warnings.simplefilter("ignore", ResourceWarning) - return rdna2spirv.translate(_SRC_PATH) - - -def _translate_single(insn_line: str, regs: dict[int, int] | None = None) -> str: - preamble = [ - f"v_mov_b32 v0, {OLD_DST:#x}", - "v_mov_b32 v1, 0x40003c00", # hi=2.0, lo=1.0 - "v_mov_b32 v2, 0x42003800", # hi=3.0, lo=0.5 - "v_mov_b32 v3, 0x4400bc00", # hi=4.0, lo=-1.0 - "s_mov_b32 s0, 0x3c00", - "s_mov_b32 s1, 0x4000", - ] - if regs: - preamble.extend(f"v_mov_b32 v{r}, {val:#x}" for r, val in regs.items()) - return _translate(preamble + [insn_line, "exp mrt0 v0, v0, v0, v0 done vm", "s_endpgm"]) - - -def _run_ps(insn_line: str, regs: dict[int, int] | None = None) -> tuple[int, str]: - spv = _translate_single(insn_line, regs=regs) - return si.run_fragment(spv)["%out_mrt0"][0], spv - - -def _validate_spv(spv_text: str) -> None: - spirv_as = shutil.which("spirv-as") - spirv_val = shutil.which("spirv-val") - if not spirv_as or not spirv_val: - raise unittest.SkipTest("spirv-as / spirv-val not on PATH") - with tempfile.TemporaryDirectory() as td: - asm_p = os.path.join(td, "shader.spvasm") - spv_p = os.path.join(td, "shader.spv") - with open(asm_p, "w", encoding="utf-8", newline="\n") as f: - f.write(spv_text) - r_as = subprocess.run([spirv_as, "--target-env", "vulkan1.2", asm_p, "-o", spv_p], - capture_output=True, text=True, check=False) - if r_as.returncode != 0: - raise AssertionError(f"spirv-as failed:\n{r_as.stderr}\n{r_as.stdout}") - r_val = subprocess.run([spirv_val, "--target-env", "vulkan1.2", spv_p], - capture_output=True, text=True, check=False) - if r_val.returncode != 0: - raise AssertionError(f"spirv-val failed:\n{r_val.stderr}\n{r_val.stdout}") - - -class F16BinTernValidationNegativeTests(unittest.TestCase): - def _assert_rejected(self, line: str): - with self.subTest(line=line), self.assertRaises(rdna2spirv.Unsupported): - _translate_single(line) - - def test_vop2_fma_negative(self): - for op in VOP2_FMA_OPS: - args = "v0, v1, 0x3800, v2" if op == "v_fmamk_f16" else "v0, v1, v2, 0x3800" - bad_lines = [ - # Disallowed encodings - f"{op}_e64 {args}", - f"{op}_sdwa {args} dst_sel:WORD_0 dst_unused:UNUSED_PAD", - f"{op}_dpp {args} quad_perm:[0,1,2,3]", - # Wrong arity - f"{op} v0, v1, v2", - f"{op} {args}, v3", - # Bad destinations - f"{op} s0, v1, 0x3800, v2", - f"{op} v[0:1], v1, 0x3800, v2", - f"{op} vcc_lo, v1, 0x3800, v2", - f"{op} -v0, v1, 0x3800, v2", - f"{op} |v0|, v1, 0x3800, v2", - f"{op} sext(v0), v1, 0x3800, v2", - # Wide sources - f"{op} v0, v[1:2], 0x3800, v2", - f"{op} v0, s[0:1], 0x3800, v2", - f"{op} v0, v1, 0x3800, v[2:3]", - # Source modifiers (neg, abs, sext) on bare and _e32 - f"{op} v0, -v1, 0x3800, v2", - f"{op}_e32 v0, |v1|, 0x3800, v2", - f"{op} v0, v1, neg(0.5), v2", - f"{op} v0, v1, |0.5|, v2", - f"{op} v0, v1, 0x3800, -v2", - f"{op} v0, sext(v1), 0x3800, v2", - f"{op} v0, v1, 0x3800, sext(v2)", - # Disallowed instruction modifiers on bare and _e32 - f"{op} {args} clamp", - f"{op}_e32 {args} clamp", - f"{op} {args} mul:2", - f"{op} {args} div:2", - f"{op} {args} op_sel:[0,0,0,0]", - f"{op} {args} dst_sel:WORD_0", - f"{op} {args} bogus_mod", - ] - for line in bad_lines: - self._assert_rejected(line) - - def test_binary_f16_negative(self): - for op in BIN_F16_OPS: - bad_lines = [ - # Wrong arity - f"{op} v0, v1", - f"{op} v0, v1, v2, v3", - f"{op}_e32 v0, v1", - f"{op}_e64 v0, v1, v2, v3", - f"{op}_sdwa v0, v1 dst_sel:WORD_0", - f"{op}_dpp v0, v1 quad_perm:[0,1,2,3]", - # Bad destinations - f"{op} s0, v1, v2", - f"{op}_e64 v[0:1], v1, v2", - f"{op}_e64 vcc_lo, v1, v2", - f"{op}_e64 -v0, v1, v2", - f"{op}_e64 |v0|, v1, v2", - f"{op}_e64 sext(v0), v1, v2", - f"{op}_dpp -v0, v1, v2 quad_perm:[0,1,2,3]", - # Wide sources and sext - f"{op}_e64 v0, v[1:2], v2", - f"{op}_e64 v0, v1, s[0:1]", - f"{op}_e64 v0, sext(v1), v2", - f"{op}_e64 v0, v1, sext(v2)", - f"{op}_sdwa v0, sext(v1), v2 dst_sel:WORD_0 dst_unused:UNUSED_PAD src0_sel:WORD_0 src1_sel:WORD_0", - f"{op}_sdwa v0, v1, sext(v2) dst_sel:WORD_0 dst_unused:UNUSED_PAD src0_sel:WORD_0 src1_sel:WORD_0", - f"{op}_dpp v0, sext(v1), v2 quad_perm:[0,1,2,3]", - f"{op}_dpp v0, v1, sext(v2) quad_perm:[0,1,2,3]", - # _e32 rejects neg/abs and all mods - f"{op}_e32 v0, -v1, v2", - f"{op}_e32 v0, |v1|, v2", - f"{op}_e32 v0, v1, -v2", - f"{op}_e32 v0, v1, |v2|", - f"{op}_e32 v0, v1, v2 clamp", - f"{op}_e32 v0, v1, v2 mul:2", - f"{op}_e32 v0, v1, v2 op_sel:[0,0,0]", - f"{op}_e32 v0, v1, v2 dst_sel:WORD_0", - f"{op}_e32 v0, v1, v2 bogus", - # _dpp rejects output/non-DPP mods - f"{op}_dpp v0, v1, v2 quad_perm:[0,1,2,3] clamp", - f"{op}_dpp v0, v1, v2 quad_perm:[0,1,2,3] mul:2", - f"{op}_dpp v0, v1, v2 quad_perm:[0,1,2,3] div:2", - f"{op}_dpp v0, v1, v2 quad_perm:[0,1,2,3] op_sel:[0,0,0]", - f"{op}_dpp v0, v1, v2 quad_perm:[0,1,2,3] dst_sel:WORD_0", - f"{op}_dpp v0, v1, v2 quad_perm:[0,1,2,3] bogus", - # _sdwa rejects bad/duplicate/conflicting/unknown mods - f"{op}_sdwa v0, v1, v2 src0_sel:BOGUS", - f"{op}_sdwa v0, v1, v2 dst_sel:QWORD", - f"{op}_sdwa v0, v1, v2 dst_unused:UNUSED_ZERO", - f"{op}_sdwa v0, v1, v2 src0_sel:WORD_0 src0_sel:WORD_1", - f"{op}_sdwa v0, v1, v2 dst_sel:WORD_0 dst_sel:WORD_1", - f"{op}_sdwa v0, v1, v2 dst_unused:UNUSED_PAD dst_unused:UNUSED_PRESERVE", - f"{op}_sdwa v0, v1, v2 clamp clamp", - f"{op}_sdwa v0, v1, v2 mul:2 div:2", - f"{op}_sdwa v0, v1, v2 op_sel:[0,0,0]", - f"{op}_sdwa v0, v1, v2 bogus", - # VOP3 (bare / _e64) rejects malformed/duplicate/conflicting/unknown mods - f"{op}_e64 v0, v1, v2 op_sel:[]", - f"{op}_e64 v0, v1, v2 op_sel:[0,1]", - f"{op}_e64 v0, v1, v2 op_sel:[0,0,0,0]", - f"{op}_e64 v0, v1, v2 op_sel:[0,2,0]", - f"{op}_e64 v0, v1, v2 op_sel:1", - f"{op}_e64 v0, v1, v2 op_sel:[0,0,0] op_sel:[1,0,0]", - f"{op}_e64 v0, v1, v2 clamp clamp", - f"{op}_e64 v0, v1, v2 mul:2 mul:2", - f"{op}_e64 v0, v1, v2 mul:2 div:2", - f"{op}_e64 v0, v1, v2 mul:8", - f"{op}_e64 v0, v1, v2 dst_sel:WORD_0", - f"{op} v0, v1, v2 op_sel_hi:[0,0]", - f"{op} v0, v1, v2 bogus", - ] - for line in bad_lines: - self._assert_rejected(line) - - def test_ternary_vop3_negative(self): - for op in TERN_VOP3_OPS: - bad_lines = [ - # Disallowed encodings - f"{op}_e32 v0, v1, v2, v3", - f"{op}_sdwa v0, v1, v2, v3 dst_sel:WORD_0 dst_unused:UNUSED_PAD", - f"{op}_dpp v0, v1, v2, v3 quad_perm:[0,1,2,3]", - # Wrong arity - f"{op} v0, v1, v2", - f"{op}_e64 v0, v1, v2, v3, v1", - # Bad destinations - f"{op} s0, v1, v2, v3", - f"{op}_e64 v[0:1], v1, v2, v3", - f"{op} -v0, v1, v2, v3", - f"{op} |v0|, v1, v2, v3", - f"{op} sext(v0), v1, v2, v3", - # Wide sources and sext - f"{op} v0, v[1:2], v2, v3", - f"{op} v0, v1, s[0:1], v3", - f"{op} v0, v1, v2, v[2:3]", - f"{op} v0, sext(v1), v2, v3", - f"{op} v0, v1, sext(v2), v3", - f"{op} v0, v1, v2, sext(v3)", - # Malformed/duplicate/conflicting/unknown VOP3 mods - f"{op} v0, v1, v2, v3 op_sel:[]", - f"{op} v0, v1, v2, v3 op_sel:[0,0,0]", - f"{op} v0, v1, v2, v3 op_sel:[0,0,0,0,0]", - f"{op} v0, v1, v2, v3 op_sel:[0,1,2,0]", - f"{op}_e64 v0, v1, v2, v3 op_sel:[0,0,0,0] op_sel:[1,0,0,0]", - f"{op}_e64 v0, v1, v2, v3 clamp clamp", - f"{op}_e64 v0, v1, v2, v3 mul:2 mul:4", - f"{op}_e64 v0, v1, v2, v3 div:2 div:2", - f"{op} v0, v1, v2, v3 dst_sel:WORD_0", - f"{op} v0, v1, v2, v3 op_sel_hi:[0,0,0]", - f"{op} v0, v1, v2, v3 neg_lo:[1,0,0]", - f"{op} v0, v1, v2, v3 bogus", - ] - for line in bad_lines: - self._assert_rejected(line) - - def test_ldexp_f16_negative(self): - bad_lines = [ - # Disallowed encodings - "v_ldexp_f16_sdwa v0, v1, v2 dst_sel:WORD_0 dst_unused:UNUSED_PAD", - "v_ldexp_f16_dpp v0, v1, v2 quad_perm:[0,1,2,3]", - # Wrong arity - "v_ldexp_f16 v0, v1", - "v_ldexp_f16_e64 v0, v1, v2, v3", - # Bad destinations - "v_ldexp_f16 s0, v1, v2", - "v_ldexp_f16_e64 v[0:1], v1, v2", - "v_ldexp_f16 -v0, v1, v2", - "v_ldexp_f16 |v0|, v1, v2", - "v_ldexp_f16 sext(v0), v1, v2", - # Wide sources and sext - "v_ldexp_f16 v0, v[1:2], v2", - "v_ldexp_f16 v0, v1, s[0:1]", - "v_ldexp_f16 v0, sext(v1), v2", - "v_ldexp_f16 v0, v1, sext(v2)", - # Reject neg/abs on integer exponent a[2] - "v_ldexp_f16 v0, v1, -v2", - "v_ldexp_f16 v0, v1, |v2|", - "v_ldexp_f16_e64 v0, v1, neg(2)", - "v_ldexp_f16_e64 v0, v1, |2|", - # _e32 rejects neg/abs and all mods - "v_ldexp_f16_e32 v0, -v1, v2", - "v_ldexp_f16_e32 v0, |v1|, v2", - "v_ldexp_f16_e32 v0, v1, v2 clamp", - "v_ldexp_f16_e32 v0, v1, v2 mul:2", - "v_ldexp_f16_e32 v0, v1, v2 op_sel:[0,0,0]", - # Malformed/duplicate/conflicting/unknown VOP3 mods - "v_ldexp_f16 v0, v1, v2 op_sel:[]", - "v_ldexp_f16 v0, v1, v2 op_sel:[0,1]", - "v_ldexp_f16 v0, v1, v2 op_sel:[0,0,0,0]", - "v_ldexp_f16 v0, v1, v2 op_sel:[0,2,0]", - "v_ldexp_f16_e64 v0, v1, v2 op_sel:[0,0,0] op_sel:[0,1,0]", - "v_ldexp_f16_e64 v0, v1, v2 clamp clamp", - "v_ldexp_f16_e64 v0, v1, v2 mul:2 div:2", - "v_ldexp_f16_e64 v0, v1, v2 mul:4 mul:4", - "v_ldexp_f16_e64 v0, v1, v2 dst_sel:WORD_0", - "v_ldexp_f16_e64 v0, v1, v2 bogus", - ] - for line in bad_lines: - self._assert_rejected(line) - - -class F16BinTernValidationPositiveTests(unittest.TestCase): - def test_vop2_fma_positive(self): - # v1.lo=1.0 (0x3c00), v2.lo=0.5 (0x3800) - cases = [ - # 1.0 * 2.0 + 0.5 = 2.5 (0x4100), hi preserved (0xabcd) - ("v_fmamk_f16 v0, v1, 2.0, v2", 0xABCD4100), - # 1.0 * (-0.5) + 0.5 = 0.0 (0x0000), plain negative float literal preserved - ("v_fmamk_f16_e32 v0, v1, -0.5, v2", 0xABCD0000), - # 1.0 * 0.5 + 2.0 = 2.5 (0x4100) - ("v_fmaak_f16 v0, v1, v2, 2.0", 0xABCD4100), - ("v_fmaak_f16_e32 v0, v1, v2, 0x4000", 0xABCD4100), - ] - for line, want in cases: - with self.subTest(line=line): - got, spv = _run_ps(line) - self.assertEqual(got, want) - _validate_spv(spv) - - def test_binary_f16_positive(self): - # v1 = 0x40003c00 (hi=2.0, lo=1.0), v2 = 0x42003800 (hi=3.0, lo=0.5), v0 = 0xabcd1234 - cases = [ - # _e32 forms - ("v_add_f16_e32 v0, v1, v2", 0xABCD3E00), # 1.0 + 0.5 = 1.5 - ("v_sub_f16_e32 v0, v1, v2", 0xABCD3800), # 1.0 - 0.5 = 0.5 - ("v_subrev_f16_e32 v0, v1, v2", 0xABCDB800), # 0.5 - 1.0 = -0.5 - ("v_mul_f16_e32 v0, v1, v2", 0xABCD3800), # 1.0 * 0.5 = 0.5 - ("v_min_f16_e32 v0, v1, v2", 0xABCD3800), # min(1.0, 0.5) = 0.5 - ("v_max_f16_e32 v0, v1, v2", 0xABCD3C00), # max(1.0, 0.5) = 1.0 - # VOP3 (_e64 / bare) with op_sel, neg/abs, clamp, omod - ("v_add_f16_e64 v0, v1, v2 op_sel:[1,1,1] clamp", 0x3C001234), # 2.0 + 3.0 -> clamp 1.0 in hi - ("v_sub_f16 v0, v1, -v2 op_sel:[0,0,0] mul:2", 0xABCD3E00), # 1.0 - (-0.5) = 1.5 (omod no-op) - ("v_subrev_f16_e64 v0, -v1, v2 op_sel:[0,0,1]", 0x3E001234), # 0.5 - (-1.0) = 1.5 in hi - ("v_mul_f16_e64 v0, |v1|, v2 op_sel:[1,0,0] div:2", 0xABCD3C00), # |2.0| * 0.5 = 1.0 - ("v_min_f16_e64 v0, -v1, v2 op_sel:[1,1,0]", 0xABCDC000), # min(-2.0, 3.0) = -2.0 - ("v_max_f16_e64 v0, v1, -v2 op_sel:[0,1,1] clamp", 0x3C001234), # max(1.0, -3.0) = 1.0 in hi - # _sdwa forms - ("v_add_f16_sdwa v0, v1, v2 dst_sel:WORD_1 dst_unused:UNUSED_PRESERVE src0_sel:WORD_0 src1_sel:WORD_0", - 0x3E001234), - ("v_sub_f16_sdwa v0, v1, v2 dst_sel:WORD_0 dst_unused:UNUSED_PAD src0_sel:WORD_1 src1_sel:WORD_0 clamp", - 0x00003C00), - ("v_mul_f16_sdwa v0, -v1, v2 dst_sel:WORD_1 dst_unused:UNUSED_PRESERVE src0_sel:WORD_1 src1_sel:WORD_0 mul:2", - 0xBC001234), - ("v_min_f16_sdwa v0, v1, v2 dst_sel:WORD_0 dst_unused:UNUSED_PAD src0_sel:WORD_0 src1_sel:WORD_1", - 0x00003C00), - ("v_max_f16_sdwa v0, v1, v2 dst_sel:WORD_0 dst_unused:UNUSED_PAD src0_sel:WORD_0 src1_sel:WORD_1", - 0x00004200), - ] - for line, want in cases: - with self.subTest(line=line): - got, spv = _run_ps(line) - self.assertEqual(got, want) - _validate_spv(spv) - - def test_binary_f16_dpp_positive(self): - # Verify all 6 binary f16 _dpp forms translate and pass spirv-as + spirv-val. - for op in BIN_F16_OPS: - line = f"{op}_dpp v0, v1, v2 quad_perm:[0,1,2,3] row_mask:0xf bank_mask:0xf" - with self.subTest(line=line): - spv = _translate_single(line) - _validate_spv(spv) - - def test_ternary_vop3_positive(self): - # v1 = (2.0, 1.0), v2 = (3.0, 0.5), v3 = (4.0, -1.0) - cases = [ - ("v_fma_f16 v0, v1, v2, v3", 0xABCDB800), # 1.0*0.5 + (-1.0) = -0.5 - ("v_fma_f16_e64 v0, v1, v2, |v3| op_sel:[1,0,0,1] clamp mul:2", 0x3C001234), # 2.0*0.5 + 1.0 = 2.0 -> 1.0 - ("v_med3_f16 v0, v1, v2, v3", 0xABCD3800), # med3(1.0, 0.5, -1.0) = 0.5 - ("v_med3_f16_e64 v0, v1, v2, v3 op_sel:[1,1,1,1]", 0x42001234), # med3(2.0, 3.0, 4.0) = 3.0 in hi - ("v_min3_f16 v0, v1, v2, v3", 0xABCDBC00), # min3(1.0, 0.5, -1.0) = -1.0 - ("v_min3_f16_e64 v0, v1, v2, |v3| op_sel:[0,0,0,1] div:2", 0x38001234), # min3(1.0, 0.5, 1.0) = 0.5 in hi - ("v_max3_f16 v0, v1, v2, v3", 0xABCD3C00), # max3(1.0, 0.5, -1.0) = 1.0 - ("v_max3_f16_e64 v0, v1, v2, v3 op_sel:[1,1,1,0] clamp", 0xABCD3C00), # max3(2.0, 3.0, 4.0) -> 1.0 - ] - for line, want in cases: - with self.subTest(line=line): - got, spv = _run_ps(line) - self.assertEqual(got, want) - _validate_spv(spv) - - def test_ldexp_f16_positive(self): - # v1 = 0x40003c00 (hi=2.0, lo=1.0), v2 = 0x00020001 (hi=2, lo=1) - regs = {2: 0x00020001} - cases = [ - ("v_ldexp_f16 v0, v1, v2", 0xABCD4000), # 1.0 * 2^1 = 2.0 - ("v_ldexp_f16_e32 v0, v1, v2", 0xABCD4000), # VOP2 _e32 form - ("v_ldexp_f16_e64 v0, -v1, -2", 0xABCDB400), # -1.0 * 2^-2 = -0.25 (plain neg imm) - ("v_ldexp_f16_e64 v0, |v1|, v2 op_sel:[1,1,1] clamp mul:2", 0x3C001234),# 2.0 * 2^2 = 8.0 -> clamp 1.0 in hi - ] - for line, want in cases: - with self.subTest(line=line): - got, spv = _run_ps(line, regs=regs) - self.assertEqual(got, want) - _validate_spv(spv) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_f16_denorm_preserve.py b/tests/semantic/test_f16_denorm_preserve.py deleted file mode 100644 index 0771c0649..000000000 --- a/tests/semantic/test_f16_denorm_preserve.py +++ /dev/null @@ -1,103 +0,0 @@ -"""SHADER-526: every module declares DenormPreserve 16, so a driver keeps an f16 denormal instead of flushing it. - -RDNA2 keeps f16 denormals. `v_mul_f16_sdwa v3, 2.0, v1 src0_sel:BYTE_1` reads the denormal 0x0040 (2^-18) and -multiplies it by 1024.0 to 0x1c00 (runtime/test/shaders/ps_sdwa_f16_const.asm, measured on gfx1036 with -tools/hw_oracle). The translator models f16 arithmetic in f32 with integer narrowing, so in the module that value is -an ordinary f32 and no f32 denormal is involved: the 16-bit mode is what governs the f16-to-f32 conversion the -driver emits for it. Without the mode NVIDIA flushed that conversion and the same test read lane y as 0x0000 on an -RTX 3090 (driver 610.88) and an RTX 4070 SUPER (610.88), 4096/4096 pixels; with it, 4096/4096 pixels exact. - -SPV_KHR_float_controls is core since SPIR-V 1.4, so the mode needs no extension at `--target-env vulkan1.2` (the -header the assembler writes is 1.5). The index lists the device property it needs, shaderDenormPreserveFloat16, next -to shaderSignedZeroInfNanPreserveFloat32: `vk_pipeline_check` skips a shader where the device reports false, and -`--no-float-controls` leaves both modes out. -""" -import os -import shutil -import subprocess -import sys -import tempfile -import unittest - -HERE = os.path.dirname(os.path.abspath(__file__)) -ROOT = os.path.dirname(os.path.dirname(HERE)) -TOOLS_DIR = os.environ.get("LEONIDA_TOOLS_DIR") or os.path.join(ROOT, "tools") -sys.path.insert(0, TOOLS_DIR) -sys.path.insert(0, HERE) - -import rdna2spirv # noqa: E402 -import support # noqa: E402 - -EXIT = ["exp mrt0 v0, v1, v2, v3 done vm", "s_endpgm"] -# A pixel shader with nothing but an ordinary value in it: the mode is a property of the module, not of the op. -PLAIN = ["v_mov_b32 v0, 0", "v_mov_b32 v1, 0", "v_mov_b32 v2, 0", "v_mov_b32 v3, 0"] - -MODE = "OpExecutionMode %main DenormPreserve 16" -CAP = "OpCapability DenormPreserve" -# ps_sdwa_f16_const's four words (gfx1036): lane y is the denormal 0x0040 * 1024.0. -SDWA_WORDS = (0xAAAA3800, 0xAAAA1C00, 0xAAAA3E00, 0xAAAA73F0) - - -def translate(lines, float_controls=True): - old = rdna2spirv.FLOAT_CONTROLS - rdna2spirv.FLOAT_CONTROLS = float_controls - try: - return support.translate_lines("ps_f16_denorm", lines + EXIT) - finally: - rdna2spirv.FLOAT_CONTROLS = old - - -def meta(spv): - return rdna2spirv.shader_meta(rdna2spirv.translate.last_gen, spv) - - -def without_modes(spv): - """The module text with the float-controls capability and execution modes removed.""" - return "\n".join(ln for ln in spv.splitlines() - if "SignedZeroInfNanPreserve" not in ln and "DenormPreserve" not in ln) - - -class F16DenormPreserveTests(unittest.TestCase): - def test_module_declares_denorm_preserve_16(self): - spv = translate(PLAIN) - self.assertIn(CAP, spv) - self.assertIn(MODE, spv) - # module layout: capabilities, then extensions, then imports - self.assertLess(spv.index(CAP), spv.index("OpExtInstImport")) - self.assertLess(spv.index("OpCapability SignedZeroInfNanPreserve"), spv.index(CAP)) - - def test_index_metadata_names_the_property(self): - self.assertEqual(meta(translate(PLAIN))["float_controls"], - ["shaderSignedZeroInfNanPreserveFloat32", "shaderDenormPreserveFloat16"]) - - def test_no_float_controls_leaves_it_out(self): - spv = translate(PLAIN, float_controls=False) - self.assertNotIn("DenormPreserve", spv) - self.assertNotIn("SignedZeroInfNanPreserve", spv) - self.assertNotIn("float_controls", meta(spv)) - - def test_the_mode_changes_only_the_header(self): - # Nothing of the translated code depends on it: the driver is the one that has to honour it. - self.assertEqual(without_modes(translate(PLAIN)), without_modes(translate(PLAIN, float_controls=False))) - - def test_the_f16_denormal_words_and_the_mode_together(self): - spv = support.translate_fixture("ps_sdwa_f16_const") - self.assertIn(MODE, spv) - self.assertEqual(tuple(support.mrt0_words(spv)), SDWA_WORDS) - - @unittest.skipUnless(shutil.which("spirv-as") and shutil.which("spirv-val"), "SPIRV-Tools not installed") - def test_spirv_tools_accept_it_at_vulkan1_2(self): - with tempfile.TemporaryDirectory() as tmp: - asm, out = os.path.join(tmp, "m.spvasm"), os.path.join(tmp, "m.spv") - with open(asm, "w", encoding="utf-8", newline="\n") as f: - f.write(support.translate_fixture("ps_sdwa_f16_const")) - made = subprocess.run(["spirv-as", asm, "-o", out, "--target-env", "vulkan1.2"], - capture_output=True, text=True) - self.assertEqual(made.returncode, 0, made.stderr) - checked = subprocess.run(["spirv-val", "--target-env", "vulkan1.2", - "--allow-offset-texture-operand", out], capture_output=True, text=True) - self.assertEqual(checked.returncode, 0, checked.stderr) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_f16_fma_rounding.py b/tests/semantic/test_f16_fma_rounding.py deleted file mode 100644 index 4e07707cb..000000000 --- a/tests/semantic/test_f16_fma_rounding.py +++ /dev/null @@ -1,219 +0,0 @@ -"""Semantic tests for single-rounded f16 FMAs (SHADER-55). - -RDNA2's v_fma_f16, v_fmac_f16 and v_pk_fma_f16 round the exact a*b+c once, to f16 (an RX 6700 matched a correctly -rounded f16 FMA in all 12,612 measured cases, #374). The translator used GLSL Fma (rounded to f32) and then narrowed -to f16, which double-rounds. These tests compare the translated ops with an exact rational reference on random -triples, plus triples built so that the exact result sits just off an f16 halfway point: those are the cases -where f32-then-f16 rounding goes the wrong way. Results are exported with a zero high half (#509). -""" -import os -import random -import struct -import sys -import tempfile -import unittest -import warnings -from fractions import Fraction - -HERE = os.path.dirname(os.path.abspath(__file__)) -ROOT = os.path.dirname(os.path.dirname(HERE)) -TOOLS_DIR = os.environ.get("LEONIDA_TOOLS_DIR") or os.path.join(ROOT, "tools") - -sys.dont_write_bytecode = True -sys.path.insert(0, TOOLS_DIR) -sys.path.insert(0, HERE) - -import rdna2spirv # noqa: E402 -import spirv_mini_interp as si # noqa: E402 - -STUB_DXBC = b"DXBC" + bytes(24) + struct.pack(" f16 bits, round to nearest even (no NaN inputs here).""" - if x == 0: - return 0 - sign = 0x8000 if x < 0 else 0 - x = abs(x) - lo, hi = 0, 0x7C00 # positive f16 values are ordered like their bits; 0x7C00 = inf - while lo < hi: # smallest h with value(h) >= x - mid = (lo + hi) // 2 - if (Fraction(h2f(mid)) if mid < 0x7C00 else Fraction(10 ** 9)) >= x: - hi = mid - else: - lo = mid + 1 - if lo == 0x7C00: # beyond 65504: round to 65504 or inf by the 65520 boundary - return sign | (0x7C00 if x >= 65520 else 0x7BFF) - above = lo - if lo == 0 or Fraction(h2f(above)) == x: - return sign | above - below = lo - 1 - da, db = Fraction(h2f(above)) - x, x - Fraction(h2f(below)) - if above == 0x7C00: - return sign | (0x7C00 if x >= 65520 else 0x7BFF) - pick = above if da < db else below if db < da else (above if above % 2 == 0 else below) - return sign | pick - - -def ref_fma(a, b, c): - return round_f16(Fraction(h2f(a)) * Fraction(h2f(b)) + Fraction(h2f(c))) - - -def double_rounded(a, b, c): - """What f32 Fma then f16 gives (the old translation).""" - x = Fraction(h2f(a)) * Fraction(h2f(b)) + Fraction(h2f(c)) - f = struct.unpack("= 2^-21 - mid = (Fraction(h2f(h)) + Fraction(h2f(h + 1))) / 2 - e = 0 - m = mid - while m.denominator != 1 or m >= 4096: # mid = M * 2^e with M an odd 12-bit integer - if m.denominator != 1: - m *= 2 - e -= 1 - else: - m /= 2 - e += 1 - m = int(m) - if m % 3 or m < 2048: - continue - a = f16_bits_of(Fraction(m // 3) * Fraction(2) ** e) - b = 0x4200 # 3.0 - k = rng.randint(1, 6) # nudge: min subnormal .. 2^-19, all below half an f32 ulp - c = (1 << (k - 1)) | (0x8000 if rng.getrandbits(1) else 0) - if rng.getrandbits(1): - a ^= 0x8000 - out.append((a, b, c)) - return out - - -class F16FmaRoundingTests(unittest.TestCase): - def check_ops(self, triples, op): - for i in range(0, len(triples), 4): - chunk = (triples[i:i + 4] + [(0, 0, 0)] * 4)[:4] - lines = [] - for k, (a, b, c) in enumerate(chunk): - lines += [f"v_mov_b32 v{4 + k}, {a:#x}", f"v_mov_b32 v{8 + k}, {b:#x}", f"v_mov_b32 v{12 + k}, {c:#x}"] - if op == "v_fma_f16": - lines += [f"v_mov_b32 v{k}, 0", f"v_fma_f16 v{k}, v{4 + k}, v{8 + k}, v{12 + k}"] - elif op == "v_fmac_f16": - lines += [f"v_mov_b32 v{k}, v{12 + k}", f"v_fmac_f16 v{k}, v{4 + k}, v{8 + k}", - f"v_and_b32 v{k}, 0xffff, v{k}"] - else: # v_pk_fma_f16 in the high half, then moved down: checks the second lane of the packed op - lines += [f"v_lshlrev_b32 v{4 + k}, 16, v{4 + k}", f"v_lshlrev_b32 v{8 + k}, 16, v{8 + k}", - f"v_lshlrev_b32 v{12 + k}, 16, v{12 + k}", - f"v_pk_fma_f16 v{k}, v{4 + k}, v{8 + k}, v{12 + k}", f"v_lshrrev_b32 v{k}, 16, v{k}"] - got = run(lines) - for (a, b, c), g in zip(chunk, got): - want = ref_fma(a, b, c) - with self.subTest(op=op, a=hex(a), b=hex(b), c=hex(c)): - self.assertEqual(g, want, f"{op}: got {g:#06x}, want {want:#06x}") - - def test_reference_sees_double_rounding(self): - triples = near_tie_triples(random.Random(55), 300) - diff = [t for t in triples if ref_fma(*t) != double_rounded(*t)] - self.assertGreater(len(diff), 5, "the near-tie generator must produce double-rounding cases") - - def test_fma_near_ties(self): - triples = near_tie_triples(random.Random(55), 300) - diff = [t for t in triples if ref_fma(*t) != double_rounded(*t)] - self.check_ops(diff[:40] + triples[:40], "v_fma_f16") - - def test_fmac_and_pk_fma_near_ties(self): - triples = near_tie_triples(random.Random(56), 300) - diff = [t for t in triples if ref_fma(*t) != double_rounded(*t)] - self.check_ops(diff[:20], "v_fmac_f16") - self.check_ops(diff[:20], "v_pk_fma_f16") - - def test_fma_random(self): - rng = random.Random(0x55) - triples = [(finite_f16(rng, 1, 22), finite_f16(rng, 1, 22), finite_f16(rng, 1, 26)) for _ in range(120)] - triples += [(0x0001, 0x3C00, 0x8000), (0x3C00, 0x3C00, 0xBC00), (0x7BFF, 0x4000, 0x0000), (0x0400, 0x0400, 0x0001)] - self.check_ops(triples, "v_fma_f16") - - def test_fmac_output_modifiers(self): - # LLVM gfx10_asm_vop2.s encodes clamp, mul:2, mul:4 and div:2 on v_fmac_f16_e64. - # On RDNA2 with denormals kept, omod is ignored on f16 results; clamp applies. - # High half (0xAAAA) of destination VGPR must remain untouched. - got = run([ - "v_mov_b32 v0, 0xaaaa3c00", # acc = 1.0h, hi = 0xAAAA - "v_fmac_f16_e64 v0, 1.0, 1.0 clamp", # 1*1 + 1 = 2.0 -> clamp -> 1.0 (0x3c00) - "v_mov_b32 v1, 0xaaaa3800", # acc = 0.5h - "v_fmac_f16_e64 v1, 0.5, 0.5 mul:2", # (0.25 + 0.5) = 0.75 (0x3a00) (mul:2 ignored) - "v_mov_b32 v2, 0xaaaa3400", # acc = 0.25h - "v_fmac_f16_e64 v2, 0.5, 0.5 mul:4", # (0.25 + 0.25) = 0.5 (0x3800) (mul:4 ignored) - "v_mov_b32 v3, 0xaaaa4000", # acc = 2.0h - "v_fmac_f16_e64 v3, 1.0, 2.0 div:2", # (2 + 2) = 4.0 (0x4400) (div:2 ignored) - ]) - self.assertEqual(got, [0xAAAA3C00, 0xAAAA3A00, 0xAAAA3800, 0xAAAA4400]) - - # Clamp applies, negative values clamp to 0.0, and omod is ignored. - got2 = run([ - "v_mov_b32 v0, 0xaaaa3400", # acc = 0.25h - "v_fmac_f16_e64 v0, 0.5, 0.5 mul:2 clamp", # (0.25 + 0.25) = 0.5 -> clamp -> 0.5 (0x3800) - "v_mov_b32 v1, 0xaaaabc00", # acc = -1.0h - "v_fmac_f16_e64 v1, 0.5, 0.5 clamp", # (0.25 - 1.0) = -0.75 -> clamp -> 0.0 (0x0000) - "v_mov_b32 v2, 0xaaaa3400", # acc = 0.25h - "v_fmac_f16_e64 v2, 0.5, 0.5 mul:4 clamp", # (0.25 + 0.25) = 0.5 -> clamp -> 0.5 (0x3800) - "v_mov_b32 v3, 0xaaaa3800", # acc = 0.5h - "v_fmac_f16_e64 v3, 1.0, 0.5 div:2 clamp", # (0.5 + 0.5) = 1.0 -> clamp -> 1.0 (0x3c00) - ]) - self.assertEqual(got2, [0xAAAA3800, 0xAAAA0000, 0xAAAA3800, 0xAAAA3C00]) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_f16_int_convert.py b/tests/semantic/test_f16_int_convert.py deleted file mode 100644 index c0fb0288d..000000000 --- a/tests/semantic/test_f16_int_convert.py +++ /dev/null @@ -1,170 +0,0 @@ -"""Semantic tests for the translator's integer f32 -> f16 conversion (SHADER-56). - -`Gen.f16_bits` replaces GLSL.std.450 PackHalf2x16 at the f16 ALU sites, because drivers fold a PackHalf2x16 -> -UnpackHalf2x16 round trip to a no-op (#513, #512). These tests run `v_cvt_f16_f32` (round to nearest even) and -`v_cvt_pkrtz_f16_f32` (round toward zero) through tools/rdna2spirv.py and the mini interpreter, and compare the -f16 bits with a Python reference over edge values (ties, the subnormal boundary, the overflow boundary, +-0, -+-inf, NaN) and a seeded sweep over every f32 exponent that can reach an f16. Each exported word has a zero high -half, so no word is a NaN bit pattern and the float export can't change it (#509). -""" -import os -import random -import struct -import sys -import tempfile -import unittest -import warnings -from fractions import Fraction - -HERE = os.path.dirname(os.path.abspath(__file__)) -ROOT = os.path.dirname(os.path.dirname(HERE)) -TOOLS_DIR = os.environ.get("LEONIDA_TOOLS_DIR") or os.path.join(ROOT, "tools") - -sys.dont_write_bytecode = True -sys.path.insert(0, TOOLS_DIR) -sys.path.insert(0, HERE) - -import rdna2spirv # noqa: E402 -import spirv_mini_interp as si # noqa: E402 - -STUB_DXBC = b"DXBC" + bytes(24) + struct.pack(" +-0; NaN -> None.""" - sign = (bits >> 16) & 0x8000 - a = bits & 0x7FFFFFFF - if a > 0x7F800000: - return None - if a < 0x00800000: - return sign - try: - return struct.unpack(" +-65504; inf -> inf; NaN -> None.""" - sign = (bits >> 16) & 0x8000 - a = bits & 0x7FFFFFFF - if a > 0x7F800000: - return None - if a == 0x7F800000: - return sign | 0x7C00 - if a < 0x00800000: - return sign - x = Fraction(f32(a)) - lo, hi = 0, 0x7BFF # largest finite f16 magnitude <= x (binary search over the ordered bits) - while lo < hi: - mid = (lo + hi + 1) // 2 - if Fraction(struct.unpack(" the four f16 results of `op` (low halves).""" - lines = [] - for i, v in enumerate(values): - lines += [f"v_mov_b32 v{i}, 0", f"v_mov_b32 v{4 + i}, {v:#x}"] - if op == "v_cvt_pkrtz_f16_f32": - lines += [f"v_cvt_pkrtz_f16_f32 v{i}, v{4 + i}, 0", f"v_and_b32 v{i}, 0xffff, v{i}"] - else: - lines.append(f"{op} v{i}, v{4 + i}") - asm = "; ps_f16cvt\n" + "".join(f"\t{ln}\n" for ln in lines) + "\texp mrt0 v0, v1, v2, v3 done vm\n\ts_endpgm\n" - path = os.path.join(tmpdir(), "disasm", "ps_f16cvt.s") - with open(path, "w", encoding="utf-8") as f: - f.write(asm) - with warnings.catch_warnings(): - warnings.simplefilter("ignore", ResourceWarning) - spv = rdna2spirv.translate(path) - return list(si.run_fragment(spv)["%out_mrt0"]) - - -EDGES = [ - 0x00000000, 0x80000000, 0x3F800000, 0xBF800000, # +-0, +-1 - 0x3F801000, 0x3F803000, 0x3F801001, 0x3F802FFF, # ties to even (down / up), just above / below a tie - 0x477FE000, 0x477FEFFF, 0x477FF000, 0x47800000, # 65504, just under the RTE overflow tie, the tie, 65536 - 0x387FC000, 0x38800000, 0x387FE000, 0x33800000, # just under 2^-14, 2^-14, subnormal tie, 2^-24 - 0x33000000, 0x33000001, 0x32FFFFFF, 0x337FFFFF, # 2^-25 (tie -> 0), just above, just below, under 2^-24 - 0x35000000, 0x34C00000, 0x7F7FFFFF, 0x00000001, # subnormals, f32 max, an f32 denormal - 0x7F800000, 0xFF800000, 0x7FC00000, 0xFFA3A095, # +-inf, NaNs -] - - -class F16IntConvertTests(unittest.TestCase): - def check(self, op, ref, values): - for i in range(0, len(values), 4): - chunk = (values[i:i + 4] + [0, 0, 0, 0])[:4] - got = convert(op, chunk) - for v, g in zip(chunk, got): - want = ref(v) - with self.subTest(op=op, x=hex(v)): - self.assertEqual(g >> 16, 0, "high half must stay 0") - if want is None: - self.assertEqual(g & 0x7E00, 0x7E00, f"want a quiet f16 NaN, got {g:#06x}") - self.assertEqual(g & 0x8000, (v >> 16) & 0x8000) - else: - self.assertEqual(g, want, f"{op}({v:#010x}) = {g:#06x}, want {want:#06x}") - - def test_rte_edges(self): - self.check("v_cvt_f16_f32", ref_rte, EDGES) - - def test_rtz_edges(self): - self.check("v_cvt_pkrtz_f16_f32", ref_rtz, EDGES) - - def sweep(self, seed, n): - rng = random.Random(seed) - out = [] - for _ in range(n): - e = rng.randint(100, 145) # every exponent from below 2^-25 to above 65536 - out.append(rng.getrandbits(1) << 31 | e << 23 | rng.getrandbits(23)) - return out - - def test_rte_sweep(self): - self.check("v_cvt_f16_f32", ref_rte, self.sweep(0x5156, 400)) - - def test_rtz_sweep(self): - self.check("v_cvt_pkrtz_f16_f32", ref_rtz, self.sweep(0x5157, 200)) - - def test_no_packhalf_at_alu_sites(self): - path = os.path.join(tmpdir(), "disasm", "ps_f16cvt.s") - with open(path, "w", encoding="utf-8") as f: - f.write("; ps_f16cvt\n\tv_mov_b32 v1, 0x3e000000\n\tv_cvt_f16_f32 v0, v1\n\tv_add_f16 v0, v0, v0\n" - "\tv_pk_add_f16 v2, v0, v0\n\tv_cvt_pkrtz_f16_f32 v3, v1, v1\n\tv_fma_f16 v0, v0, v0, v0\n" - "\texp mrt0 v0, v2, v3, v0 done vm\n\ts_endpgm\n") - with warnings.catch_warnings(): - warnings.simplefilter("ignore", ResourceWarning) - spv = rdna2spirv.translate(path) - self.assertNotIn("PackHalf2x16", spv) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_f16_interp_fallback.py b/tests/semantic/test_f16_interp_fallback.py deleted file mode 100644 index 2fbd23ff0..000000000 --- a/tests/semantic/test_f16_interp_fallback.py +++ /dev/null @@ -1,269 +0,0 @@ -"""rdna2spirv.py --f16-interp-fallback: v_interp_*_f16 without PerVertexKHR inputs (SHADER-196). - -By default a location any *_f16 interp reads is a PerVertexKHR vec4[3] of the producer's raw words, decoded and -weighted in the PS (test_interp_f16_high.py). MoltenVK can't compile that decoration to MSL ("PerVertexKHR decoration -is not supported in MSL"), so with the flag the producer (VS `exp paramN`, mesh params) also exports each channel's two -f16 halves decoded to f32, low halves at location 28 - 2N and high halves at 29 - 2N, and the PS reads them as ordinary -smooth inputs (the top is 29: MoltenVK's maxVertexOutputComponents, 124, counts gl_Position; SHADER-291). -Interpolating the decoded halves is the same P0 + i(P1 - P0) + j(P2 - P0). Here: -* the PS has no PerVertexKHR, no barycentric builtin, and reads 1.75 / 9.0 from the decoded-half inputs (the - per-vertex values of test_interp_f16_high.py, interpolated as Vulkan would), the f32 control and the flat raw read - unchanged; -* the VS exports the decoded halves of every param at those locations (one-lane interpreter), and drops the ones - that would land on its own params; the metadata lists both sides; -* a PS whose decoded-half location is also an attribute it reads is rejected rather than mislinked; -* without the flag nothing changes. -The GPU check is runtime/test/shaders/ps_interp_f16_high drawn with vs_f16_pack, which run_gpu_tests.py translates -with the flag where tools/vk_subgroup_info.py reports per_vertex_inputs false (MoltenVK). -""" -import re -import struct -import unittest - -import support -import rdna2spirv -from spirv_mini_interp import run_fragment -from test_interp_f16_high import ATTR0, ATTR1, BARY, CTRL, HI, LO, SHADER - - -def f32(w): - return struct.unpack("= 7, up to attr12) pack all - decoded halves into free locations <= 29 without colliding with any raw attribute.""" - lines = [] - for a in range(15): - lines += [f"v_interp_p1_f32_e32 v{10 + a}, v0, attr{a}.x", - f"v_interp_p2_f32_e32 v{10 + a}, v1, attr{a}.x"] - for i, a in enumerate((0, 4, 5, 6, 7)): - v = 30 + i - lines += [f"v_interp_p1ll_f16 v{v}, v0, attr{a}.x", - f"v_interp_p2_f16 v{v}, v1, attr{a}.x, v{v}"] - lines += ["v_interp_p1ll_f16 v40, v0, attr7.x high", - "v_interp_p2_f16 v40, v1, attr7.x, v40 high", - "exp mrt0 v34, v40, v24, v10 done vm", "s_endpgm"] - spv, meta = translate("ps_f16_corpus_pack", lines) - self.assertEqual(meta["f16_halves"], { - "0": [28, 29], "4": [26, 27], "5": [24, 25], "6": [22, 23], "7": [20, 21], - }) - self.assertLessEqual(max(meta["inputs"]), 29) - self.assertEqual(len(meta["inputs"]), len(set(meta["inputs"]))) - inputs = {f"%in_attr{a}": (float(a), 0.0, 0.0, 0.0) for a in range(15)} - for a in (0, 4, 5, 6): - inputs[f"%in_f16h{a}_0"] = (0.0, 0.0, 0.0, 0.0) - inputs["%in_f16h7_0"] = (lerp(LO), 0.0, 0.0, 0.0) - inputs["%in_f16h7_1"] = (lerp(HI), 0.0, 0.0, 0.0) - words = support.mrt0_words(spv, inputs=inputs) - self.assertEqual(f"{words[0] & 0xFFFF:#06x}", "0x3f00") # attr7 low: 1.75 - self.assertEqual(f"{words[1] & 0xFFFF:#06x}", "0x4880") # attr7 high: 9.0 - self.assertEqual(f32(words[2]), 14.0) # raw attr14 - - def test_high_attr_negative_canonical_slot_packs_dynamically(self): - """attr15 has canonical slot 28 - 30 = -2; dynamic packing still places it in 0..29.""" - lines = ["v_interp_p1ll_f16 v2, v0, attr15.x", "v_interp_p2_f16 v2, v1, attr15.x, v2", - "exp mrt0 v2, v2, v2, v2 done vm", "s_endpgm"] - spv, meta = translate("ps_f16_attr15", lines) - self.assertEqual(meta["f16_halves"], {"15": [28, 29]}) - self.assertIn("OpDecorate %in_f16h15_0 Location 28", spv) - - def test_location_budget_overflow_is_rejected(self): - """29 raw attributes (0..28) plus 1 f16 attribute needs 31 locations > 30: still rejected.""" - lines = [] - for a in range(29): - lines += [f"v_interp_p1_f32_e32 v{10 + a}, v0, attr{a}.x", - f"v_interp_p2_f32_e32 v{10 + a}, v1, attr{a}.x"] - lines += ["v_interp_p1ll_f16 v2, v0, attr0.x", "v_interp_p2_f16 v2, v1, attr0.x, v2", - "exp mrt0 v2, v10, v10, v10 done vm", "s_endpgm"] - with self.assertRaises(rdna2spirv.Unsupported) as ctx: - translate("ps_f16_overflow", lines) - self.assertIn("decoded-half locations", str(ctx.exception)) - - def test_off_by_default(self): - spv, meta = translate("ps_f16_fallback", SHADER.splitlines(), fallback=False) - self.assertIn("OpDecorate %in_attr0 PerVertexKHR", spv) - self.assertNotIn("%in_f16h", spv) - self.assertNotIn("f16_halves", meta) - - -class FallbackVertexShader(unittest.TestCase): - def test_exports_decoded_halves(self): - spv, meta = translate("vs_f16_fallback", VS.splitlines()) - for n, lo, hi in ((0, 28, 29), (1, 26, 27)): - self.assertIn(f"OpDecorate %out_f16h{n}_0 Location {lo}", spv) - self.assertIn(f"OpDecorate %out_f16h{n}_1 Location {hi}", spv) - self.assertEqual(meta["f16_halves"], {"0": [28, 29], "1": [26, 27]}) - for vid in range(3): - out = run_fragment(spv, inputs={"%vertex_index": vid, "%instance_index": 0}) - u, v = float((vid << 1) & 2), float(vid & 2) - raw = list(out["%out_param0"]) # outputs come back as 32-bit words - lo = [struct.unpack(" clamped to 1.0 (0x3C00) - "exp mrt0 v0, v1, v2, v3 done vm", - "s_endpgm", - ]) - self.assertEqual(words_triples[0], 0xAAAA3A00) - self.assertEqual(words_triples[1], 0xAAAA3A00) - self.assertEqual(words_triples[2], 0xAAAA3A00) - self.assertEqual(words_triples[3], 0xAAAA3C00) - - def test_class2_transcendental_math(self): - # 0.5h = 0x3800, 2.0h = 0x4000, 0.75h = 0x3A00, 1.0h = 0x3C00 - words = run_ps([ - "v_mov_b32 v0, 0xaaaa4000", # 2.0h - "v_rcp_f16 v0, v0 mul:2", # rcp(2.0) = 0.5h (mul:2 ignored) - "v_mov_b32 v1, 0xaaaa4400", # 4.0h - "v_sqrt_f16 v1, v1 mul:2", # sqrt(4.0) = 2.0h (mul:2 ignored) - "v_mov_b32 v2, 0xaaaa3f00", # 1.75h - "v_fract_f16 v2, v2 mul:4", # fract(1.75) = 0.75h (mul:4 ignored) - "v_mov_b32 v3, 0xaaaa4400", # 4.0h - "v_sqrt_f16 v3, v3 mul:2 clamp", # sqrt(4.0) = 2.0 -> clamp -> 1.0h (0x3C00) - "exp mrt0 v0, v1, v2, v3 done vm", - "s_endpgm", - ]) - self.assertEqual(words[0], 0xAAAA3800) - self.assertEqual(words[1], 0xAAAA4000) - self.assertEqual(words[2], 0xAAAA3A00) - self.assertEqual(words[3], 0xAAAA3C00) - - def test_class3_conversions(self): - # v_cvt_f16_u16 and v_cvt_f16_i16 use clamp_f16 (omod ignored): - # 3 u16 -> 3.0h (0x4200); 3 i16 -> 3.0h (0x4200); 1 u16 clamp -> 1.0h (0x3C00). - words = run_ps([ - "v_mov_b32 v0, 3", # 3 u16 - "v_cvt_f16_u16 v0, v0 mul:2", # cvt(3) = 3.0h (mul:2 ignored) - "v_mov_b32 v1, 3", # 3 i16 - "v_cvt_f16_i16 v1, v1 div:2", # cvt(3) = 3.0h (div:2 ignored) - "v_mov_b32 v2, 5", # 5 u16 - "v_cvt_f16_u16 v2, v2 mul:4 clamp", # cvt(5) = 5.0h -> clamp -> 1.0h (0x3C00) - "v_mov_b32 v3, 0xffff", # -1 i16 - "v_cvt_f16_i16 v3, v3 mul:2 clamp", # cvt(-1) = -1.0h -> clamp -> 0.0h (0x0000) - "exp mrt0 v0, v1, v2, v3 done vm", - "s_endpgm", - ]) - self.assertEqual(words[0] & 0xFFFF, 0x4200) - self.assertEqual(words[1] & 0xFFFF, 0x4200) - self.assertEqual(words[2] & 0xFFFF, 0x3C00) - self.assertEqual(words[3] & 0xFFFF, 0x0000) - - def test_class4_control_f32_dest_scales(self): - # v_cvt_f32_f16 produces f32 destination; under IEEE=0, omod scales: - # cvt(2.0h) = 2.0f -> mul:2 = 4.0f, mul:4 = 8.0f, div:2 = 1.0f - words = run_ps([ - "v_mov_b32 v0, 0x4000", # 2.0h - "v_cvt_f32_f16 v0, v0 mul:2", # 2.0 * 2 = 4.0f32 - "v_mov_b32 v1, 0x4000", # 2.0h - "v_cvt_f32_f16 v1, v1 mul:4", # 2.0 * 4 = 8.0f32 - "v_mov_b32 v2, 0x4000", # 2.0h - "v_cvt_f32_f16 v2, v2 div:2", # 2.0 / 2 = 1.0f32 - "v_mov_b32 v3, 0x4000", # 2.0h - "v_cvt_f32_f16 v3, v3 clamp", # 2.0 -> clamp -> 1.0f32 - "exp mrt0 v0, v1, v2, v3 done vm", - "s_endpgm", - ]) - self.assertEqual(bits_to_f32(words[0]), 4.0) - self.assertEqual(bits_to_f32(words[1]), 8.0) - self.assertEqual(bits_to_f32(words[2]), 1.0) - self.assertEqual(bits_to_f32(words[3]), 1.0) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_f16_sum_narrowing.py b/tests/semantic/test_f16_sum_narrowing.py deleted file mode 100644 index 3c2a28a90..000000000 --- a/tests/semantic/test_f16_sum_narrowing.py +++ /dev/null @@ -1,90 +0,0 @@ -"""f16 add/sub narrowing without the subnormal rounding (Gen.f16_bits exact_tiny). - -The sum of two f16 values is a multiple of 2^-24, so below 2^-14 it already is an f16 value and needs no rounding. -These tests run v_add_f16, v_sub_f16, v_subrev_f16 and v_pk_add_f16 through the translator and the mini interpreter -and compare with the exact sum, rounded once, over the range boundaries and a seeded sweep. An omod can break that -property (div:2), so the last test checks that such a result is still rounded. -""" -import random -import struct -import unittest -from fractions import Fraction - -import support - - -def value(h): - return struct.unpack(" V_MAD_F32_e64, - V_FMAC_F32 -> V_FMA_F32_e64). - v_cvt_f32_ubyte1 D = float(S0[15:8]); the VOP3 form has clamp and omod (LLVM VOPProfileI2F: Ins64 is - v_cvt_f32_u32 $src0, $clamp, $omod), applied to the float result: omod scales, then clamp to [0, 1]. - v_cvt_f32_f16 D = float(S0.f16); clamp and omod as for any float result (VOP_F32_F16). - v_rcp_iflag_f32 D = 1 / S0; clamp and omod as above (VOP_F32_F32). - -ps_f32_mods (runtime/test/shaders/ps_f32_mods.asm) exports one word per rule; the constants below are written by -hand and recomputed by the plain-Python references in ReferenceTests, which use neither the translator nor the -interpreter. -""" -import math -import struct -import unittest -from fractions import Fraction - -import spirv_mini_interp as si -import support - -EXPECTED_F32_MODS = (0xC0256A01, 0x3F800000, 0x41E00000, 0x3FC00000) - - -def f32_value(word): - return Fraction(struct.unpack(" binary32 bits, round to nearest even (normal range only, enough for these cases).""" - sign = 0x80000000 if value < 0 else 0 - a = abs(value) - e = math.floor(math.log2(a)) - while Fraction(2) ** e > a: - e -= 1 - while Fraction(2) ** (e + 1) <= a: - e += 1 - q = a / Fraction(2) ** (e - 23) - n = q.numerator // q.denominator - rem = q - n - if rem > Fraction(1, 2) or (rem == Fraction(1, 2) and n & 1): - n += 1 - if n == 1 << 24: - n, e = n >> 1, e + 1 - return sign | ((e + 127) << 23) | (n & 0x7FFFFF) - - -def reference_f32_mods(): - # v_mac_f32 v2, v0, v1: round(round(v0 * v1) + v2). - v0, v1, v2 = 0xBC500C59, 0x435A2099, 0x3E3DB015 - product = round_to_f32(f32_value(v0) * f32_value(v1)) - mac = round_to_f32(f32_value(product) + f32_value(v2)) - # v_cvt_f32_ubyte1 of 0x12347856 = 120.0, clamped to 1.0. - ubyte = min(Fraction((0x12347856 >> 8) & 0xFF), Fraction(1)) - # v_cvt_f32_u32 of 7, mul:4. - u32 = Fraction(7) * 4 - # v_cvt_f32_f16 of 0x3c00 (1.0), div:2; v_rcp_iflag_f32 of 4.0, mul:4; summed. - total = Fraction(1) / 2 + Fraction(1, 4) * 4 - return (mac, round_to_f32(ubyte), round_to_f32(u32), round_to_f32(total)) - - -def reference_fused(): - """What a fused multiply-add gives for the v_mac_f32 operands: the word the test must not see.""" - v0, v1, v2 = 0xBC500C59, 0x435A2099, 0x3E3DB015 - return round_to_f32(f32_value(v0) * f32_value(v1) + f32_value(v2)) - - -class ReferenceTests(unittest.TestCase): - def test_constants_match_references(self): - self.assertEqual(reference_f32_mods(), EXPECTED_F32_MODS) - - def test_mac_operands_tell_fused_from_unfused(self): - self.assertNotEqual(reference_fused(), EXPECTED_F32_MODS[0]) - - -class F32ValuTests(unittest.TestCase): - def test_mac_unfused_and_conversion_output_modifiers(self): - words = support.mrt0_words(support.translate_fixture("ps_f32_mods")) - for i, (got, want) in enumerate(zip(words, EXPECTED_F32_MODS)): - with self.subTest(component="xyzw"[i]): - self.assertEqual(f"{got:#010x}", f"{want:#010x}") - - -HEADER = """\ -OpCapability Shader -%glsl = OpExtInstImport "GLSL.std.450" -OpMemoryModel Logical GLSL450 -OpEntryPoint Fragment %main "main" %out -%void = OpTypeVoid -%fn = OpTypeFunction %void -%uint = OpTypeInt 32 0 -%float = OpTypeFloat 32 -%bool = OpTypeBool -%_ptr_Output_uint = OpTypePointer Output %uint -%out = OpVariable %_ptr_Output_uint Output -%c0 = OpConstant %uint 0 -%c1 = OpConstant %uint 1 -%fm0 = OpConstant %float -0 -%f0 = OpConstant %float 0 -%f1 = OpConstant %float 1 -%f4 = OpConstant %float 4 -%f8 = OpConstant %float 8 -%fm0p4 = OpConstant %float -0.4 -%fm0p5 = OpConstant %float -0.5 -%fm1p5 = OpConstant %float -1.5 -%fm1 = OpConstant %float -1 -%u_inf = OpConstant %uint 2139095040 -%u_ninf = OpConstant %uint 4286578688 -%u_nan = OpConstant %uint 2143289344 -%main = OpFunction %void None %fn -%entry = OpLabel -%inf = OpBitcast %float %u_inf -%ninf = OpBitcast %float %u_ninf -%nan = OpBitcast %float %u_nan -""" -FOOTER = "OpReturn\nOpFunctionEnd\n" - - -def run_float(body): - """Run `body` (which must define the float %r) and return the bits stored to %out.""" - text = HEADER + body + "%res = OpBitcast %uint %r\nOpStore %out %res\n" + FOOTER - return si.run_fragment(text)["%out"][0] - - -def run_bool(body): - text = HEADER + body + "%res = OpSelect %uint %b %c1 %c0\nOpStore %out %res\n" + FOOTER - return si.run_fragment(text)["%out"][0] - - -def bits(x): - return struct.unpack("> 23) & 0xFF == 0xFF and r & 0x7FFFFF, f"{r:#x} is not NaN") - with self.assertRaises(si.UnsupportedConstruct): # SPIR-V: undefined if Operand 2 is 0 - run_float("%r = OpFDiv %float %f1 %f0\n") - - def test_fma_rounds_once(self): - # (1 + 2**-12)**2 = 1 + 2**-11 + 2**-24 sits exactly halfway between two binary32 values; the tiny addend - # 2**-70 decides the rounding (up). Rounding through a double first loses the addend and ties to even. - text = HEADER.replace("%main = OpFunction", "%fa = OpConstant %float 1.000244140625\n" - "%fc = OpConstant %float 8.470329472543003e-22\n%main = OpFunction") - body = "%r = OpExtInst %float %glsl Fma %fa %fa %fc\n%res = OpBitcast %uint %r\nOpStore %out %res\n" - self.assertEqual(si.run_fragment(text + body + FOOTER)["%out"][0], 0x3F801001) - self.assertEqual(si.f32_bits(si.fma_f32(-0.0, 1.0, -0.0)), 0x80000000) - self.assertEqual(si.f32_bits(si.fma_f32(-0.0, 1.0, 0.0)), 0) - - def test_isnan_isinf(self): - self.assertEqual(run_bool("%b = OpIsNan %bool %nan\n"), 1) - self.assertEqual(run_bool("%b = OpIsNan %bool %inf\n"), 0) - self.assertEqual(run_bool("%b = OpIsInf %bool %ninf\n"), 1) - self.assertEqual(run_bool("%b = OpIsInf %bool %f1\n"), 0) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_f64_literal_whole.py b/tests/semantic/test_f64_literal_whole.py deleted file mode 100644 index b8e97203a..000000000 --- a/tests/semantic/test_f64_literal_whole.py +++ /dev/null @@ -1,117 +0,0 @@ -"""An inline literal that does not fit in 32 bits on a binary64 VOP3 source is the whole constant. - -LLVM's gfx1013 listing prints the two-dword literal of an f64 instruction as one `0x` value of 16 hex -digits, the same form `tools/f64_diff.py` writes. `docs/design.md` ("f64 literal sources") covers the -other encoding: a single literal dword supplies bits 63:32 of the constant with bits 31:0 zero, and an -inline integer is sign-extended. A literal wider than a 32-bit word is therefore the two words of one -double, not the high word of one. - -Each case translates a hand-written pixel-shader listing with tools/rdna2spirv.py and checks the -(low, high) dword pair the module builds for the source. The constants are exact: 0x3FF8000000000001 -splits into the low word 0x00000001 and the high word 0x3FF80000, 0x40100000 is the high word of 4.0, -and 4 is 4.0 as an inline integer. The behaviour of a literal source is executed and compared against -the CPU reference in `tools/f64_diff.py` (its own `v_add_f64`/`v_rsq_f64`/`v_sqrt_f64` cases). -Standard library only. -""" -import os -import sys -import unittest - -HERE = os.path.dirname(os.path.abspath(__file__)) -TESTS_DIR = os.path.dirname(HERE) -for p in (HERE, TESTS_DIR): - if p not in sys.path: - sys.path.insert(0, p) - -from support import translate_lines # noqa: E402 (support puts tools/ on sys.path) - -MASK32 = 0xFFFFFFFF -ONE_HALF_UP = 0x3FF8000000000001 # 1.5 + 2^-52: not expressible as one literal dword -ONE_HALF_WORDS = (0x00000001, 0x3FF80000) # (low word, high word) of ONE_HALF_UP -FOUR_HIGH = 0x40100000 # one literal dword: bits 63:32 of 4.0 -UNARY = ("v_sqrt_f64", "v_rsq_f64", "v_rcp_f64", "v_floor_f64", "v_ceil_f64", "v_trunc_f64", - "v_rndne_f64") - - -def constants(spv): - const = {} - for raw in spv.splitlines(): - lhs, sep, rhs = raw.strip().partition(" = OpConstant %uint ") - if sep: - const[lhs] = int(rhs) - return const - - -def built_pairs(spv): - """Every (low, high) dword pair the module builds for a binary64 value, in program order.""" - const, pairs = constants(spv), [] - for raw in spv.splitlines(): - lhs, sep, rhs = raw.strip().partition(" = OpCompositeConstruct %v2uint_d ") - if sep: - lo, hi = rhs.split() - pairs.append((const[lo], const[hi])) - return pairs - - -def source_words(op, src): - """The word pair the translated `op v[4:5], src` builds for its source (its first such pair).""" - spv = translate_lines("ps_f64_literal_whole", - [f"{op} v[4:5], {src}", - "exp mrt0 v4, v5, v4, v5 done vm", "s_endpgm"]) - pairs = built_pairs(spv) - if not pairs: - raise AssertionError("the module builds no binary64 operand pair") - return pairs[0] - - -def frexp_words(src): - """(low, high) the translated `v_frexp_exp_i32_f64 v4, src` works on: the exponent field - extraction names the high word, the fraction OR names the low word.""" - spv = translate_lines("ps_f64_literal_frexp", - [f"v_frexp_exp_i32_f64 v4, {src}", - "exp mrt0 v4, v4, v4, v4 done vm", "s_endpgm"]) - const, high, low = constants(spv), None, None - for raw in spv.splitlines(): - lhs, sep, rhs = raw.strip().partition(" = ") - if sep and rhs.startswith("OpBitFieldUExtract %uint ") and high is None: - high = const[rhs.split()[2]] - if sep and rhs.startswith("OpBitwiseOr %uint ") and low is None: - low = const[rhs.split()[3]] - if high is None or low is None: - raise AssertionError("the module has no frexp exponent extraction and fraction OR") - return low, high - - -class WholeLiteralTests(unittest.TestCase): - def test_one_literal_dword_is_bits_63_32(self): - # The 32-bit rule is unchanged: 0x40100000 is the high word and the low word is zero. - self.assertEqual(source_words("v_sqrt_f64", f"0x{FOUR_HIGH:08x}"), (0, FOUR_HIGH)) - - def test_a_printed_width_picks_the_rule_not_the_value(self): - # 0x12345678 fits one dword, but the 16-digit spelling is the full-width form, so its value - # is the whole constant: the low word here, not the high one (tools/f64_diff.py writes it). - self.assertEqual(source_words("v_sqrt_f64", "0x12345678"), (0, 0x12345678)) - self.assertEqual(source_words("v_sqrt_f64", "0x0000000012345678"), (0x12345678, 0)) - self.assertEqual(frexp_words("0x0000000012345678"), (0x12345678, 0)) - - def test_inline_integer_is_sign_extended(self): - self.assertEqual(source_words("v_sqrt_f64", "4"), (4, 0)) - self.assertEqual(source_words("v_sqrt_f64", "-1"), (MASK32, MASK32)) - - def test_two_dword_literal_is_the_whole_constant(self): - # One literal dword would build (0, 1) here: the literal's low 32 bits as the high word. - for op in UNARY: - with self.subTest(op=op): - self.assertEqual(source_words(op, f"0x{ONE_HALF_UP:016x}"), ONE_HALF_WORDS) - self.assertEqual(frexp_words(f"0x{ONE_HALF_UP:016x}"), ONE_HALF_WORDS) - - def test_a_literal_wider_than_32_bits_translates(self): - # 0x100000000 used to be refused as `Unsupported: v_ceil_f64 literal`; it is the double - # 2^32, its two words 0x00000000 and 0x00000001 (tests/semantic/test_f64_round.py kept the refusal). - for op in ("v_ceil_f64", "v_floor_f64", "v_trunc_f64", "v_rndne_f64"): - with self.subTest(op=op): - self.assertEqual(source_words(op, "0x100000000"), (0, 1)) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_f64_round.py b/tests/semantic/test_f64_round.py deleted file mode 100644 index 9d3b50154..000000000 --- a/tests/semantic/test_f64_round.py +++ /dev/null @@ -1,91 +0,0 @@ -"""Value regressions for RDNA2's binary64 round-to-integral instructions.""" -import math -import shutil -import struct -import subprocess -import tempfile -import unittest -from pathlib import Path - -import support - - -def words(value): - return struct.unpack("= 3 - while True: - s11 += 1 - if s11 >= 3: - break - back += 1 - y = s11 | 0x10 - s12 = 0 # loop with s_add_u32 -180 / s_addc_u32 -1: leaves when s12 >= 0x50 - while True: - s12 += 0x10 - if s12 >= 0x50: - break - z = s12 | 1 - w = 0 - for compare, bit_before, bit_target in ((1, 1, 2), (3, 4, 8)): - if w == compare: # scc = 1: the far branch runs and skips the bit_before OR - w |= bit_target - else: # scc = 0: the branch over the far-branch sequence is taken - w |= bit_before - w |= bit_target - return [x, y, z, w] - - -class FarBranch(unittest.TestCase): - def test_reference_matches_the_header_words(self): - self.assertEqual([f"{w:#010x}" for w in reference()], [f"{w:#010x}" for w in EXPECTED]) - - def test_listing_is_the_asm(self): - """The listing has the `; encoding:` comments the branches need (regen_fixtures.py writes none), so it is - llvm-mc output; its mnemonics must be those of the .asm, in order.""" - def mnemonics(lines): - return [re.sub(r"_e32$", "", ln.split()[0]) for ln in lines] - with open(ASM, encoding="utf-8") as f: - asm = [ln.strip() for ln in f if ln.strip() and not ln.lstrip().startswith(";")] - with open(FIXTURE, encoding="utf-8") as f: - listing = [ln.strip() for ln in f.read().splitlines()[1:] if ln.strip()] - self.assertEqual(mnemonics(listing), mnemonics(asm)) - - def test_ps_far_branch(self): - with open(FIXTURE, "rb") as f: - spv = support.translate_listing("ps_far_branch", f.read()) - words = support.mrt0_words(spv) - self.assertEqual([f"{w:#010x}" for w in words], [f"{w:#010x}" for w in EXPECTED]) - - -class FarBranchWithoutEncoding(unittest.TestCase): - def test_idiom_without_encoding_is_unsupported_not_a_crash(self): - """A hand-written listing has no `; encoding:` bytes, so the idiom's size is unknown: Unsupported, as for a - lone s_getpc_b64 (test_missing_encoding.py), not a TypeError from joining the missing encodings.""" - import rdna2spirv - lines = ["s_getpc_b64 s[4:5]", "s_add_u32 s4, s4, 8", "s_addc_u32 s5, s5, 0", "s_setpc_b64 s[4:5]", - "v_mov_b32 v0, 1", "exp mrt0 v0, v0, v0, v0 done vm", "s_endpgm"] - text = "; far\n" + "".join("\t" + ln + "\n" for ln in lines) - with self.assertRaisesRegex(rdna2spirv.Unsupported, "without encoding"): - support.translate_listing("ps_far_noenc", text.encode("utf-8")) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_fcmpswap_fixture.py b/tests/semantic/test_fcmpswap_fixture.py deleted file mode 100644 index 311642223..000000000 --- a/tests/semantic/test_fcmpswap_fixture.py +++ /dev/null @@ -1,83 +0,0 @@ -"""cs_w32_fcmpswap: the GPU test of ds_cmpst_f32 and buffer_atomic_fcmpswap, run here on the CPU too. - -Standard library only; no GPU, no LLVM, no game files. - -runtime/test/shaders/cs_w32_fcmpswap.asm (derivations in its header) stores eight words from lane 0. This runs its -fixture as one wave32 group through spirv_mini_interp with the buffer vk_compute_test gives it (every byte 0xEE, a V# -with num_records 0xFFFFFFFF), checks the words against a float-compare reference computed here, that check.py and -scripts/run_gpu_tests.py expect the same words, and that EXEC is cut to lane 0 before the first memory op. -""" -import os -import re -import struct -import sys -import unittest - -HERE = os.path.dirname(os.path.abspath(__file__)) -if HERE not in sys.path: - sys.path.insert(0, HERE) # python -I leaves the script's folder off sys.path - -import support # noqa: E402 (support puts tools/ on sys.path, honouring LEONIDA_TOOLS_DIR) -import spirv_mini_interp as si # noqa: E402 - -ROOT = os.path.dirname(os.path.dirname(HERE)) - -FSSM = bytearray(0x148) -struct.pack_into("<4I", FSSM, 0x138, 0x8088, 32, 1, 1) # 4 user SGPRs, wg id in s4, 512 bytes of LDS, 32x1x1 -FSSM = bytes(FSSM) -VSHARP = [0, 0, 0xFFFFFFFF, 0x31016FAC] # vk_compute_test's V#: base 0, num_records max, raw -FILL = 0xEEEEEEEE -PZ, NZ, ONE, TWO, THREE, NAN = 0, 0x80000000, 0x3F800000, 0x40000000, 0x40400000, 0x7FC00000 - - -def f32(b): - return struct.unpack(" 1.0 if it still sees +-0: one wins, the rest see 1.0 and keep it. - spv = translate([f"v_mov_b32_e32 v1, {TARGET:#x}", f"v_mov_b32_e32 v2, {ONE:#x}", f"v_mov_b32_e32 v3, {NZ:#x}", - "global_atomic_fcmpswap v1, v[2:3], s[0:1]"]) - mem = {TARGET: PZ} - si.run_workgroup(spv, 32, 32, inputs_for=lambda i: {"%wg_id": (0, 0, 0), "%local_id": (i, 0, 0), - "%sg_lane": i}, - push_constants=[0] * 36, memory=mem) - self.assertEqual(mem[TARGET], ONE) - - def test_rejected_forms(self): - for line in ("global_atomic_fcmpswap v5, v1, v2, s[0:1] glc", "global_atomic_fcmpswap_x2 v[4:5], v1, v[2:5], s[0:1] glc"): - with self.subTest(line=line): - with self.assertRaises(rdna2spirv.Unsupported): - translate(["v_mov_b32_e32 v1, 0", line]) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_float_compares.py b/tests/semantic/test_float_compares.py deleted file mode 100644 index af13e6059..000000000 --- a/tests/semantic/test_float_compares.py +++ /dev/null @@ -1,161 +0,0 @@ -"""Semantic interpreter tests for RDNA2 float compares: v_cmp_{lt,le,gt,ge,eq,lg,neq,nlg,nlt,ngt,nle,nge}_{f32,f16}. - -lt/le/gt/ge/eq/lg are ordered (false when either source is NaN); neq/nlg/nlt/ngt/nle/nge are their unordered negations -(true when either source is NaN). +0 and -0 compare equal. Each case translates a synthetic pixel shader with -tools/rdna2spirv.py, runs it in tests/semantic/spirv_mini_interp.py, reads the compare back with v_cndmask_b32 and -compares it with Python's own comparison of the operands. f16 sources take the low half of the 32-bit register; the -high half is noise the compare must ignore. -""" -import itertools -import math -import os -import struct -import sys -import tempfile -import unittest -import warnings - -HERE = os.path.dirname(os.path.abspath(__file__)) -ROOT = os.path.dirname(os.path.dirname(HERE)) -TOOLS_DIR = os.environ.get("LEONIDA_TOOLS_DIR") or os.path.join(ROOT, "tools") - -sys.dont_write_bytecode = True -sys.path.insert(0, TOOLS_DIR) -sys.path.insert(0, HERE) - -import rdna2spirv # noqa: E402 -import spirv_mini_interp as si # noqa: E402 - -STUB_DXBC = b"DXBC" + bytes(24) + struct.pack(" y, - "ge": lambda x, y: x >= y, "eq": lambda x, y: x == y, - "lg": lambda x, y: x != y and not (math.isnan(x) or math.isnan(y))} -UNORDERED = {"neq": "eq", "nlg": "lg", "nlt": "lt", "ngt": "gt", "nle": "le", "nge": "ge"} # n = not - - -def relation(cond: str, x: float, y: float) -> bool: - if cond in UNORDERED: - return not ORDERED[UNORDERED[cond]](x, y) - return ORDERED[cond](x, y) - - -CONDS = list(ORDERED) + list(UNORDERED) -F32 = {"0": 0x00000000, "-0": 0x80000000, "1": 0x3F800000, "-1": 0xBF800000, "2.5": 0x40200000, - "inf": 0x7F800000, "-inf": 0xFF800000, "nan": 0x7FC00000} -F16 = {"0": 0x0000, "-0": 0x8000, "1": 0x3C00, "-1": 0xBC00, "2.5": 0x4100, - "inf": 0x7C00, "-inf": 0xFC00, "nan": 0x7E00} - - -def f32_value(bits: int) -> float: - return struct.unpack(" float: - return struct.unpack(" int: - if _TMP_DIR is None: - setUpModule() - lines = [f"v_mov_b32 v2, {x_bits:#x}", f"v_mov_b32 v3, {y_bits:#x}"] - if form == "e32": - lines += [f"{op}_e32 vcc_lo, {srcs}", "v_cndmask_b32_e32 v0, 0, 1, vcc_lo"] - else: - lines += [f"{op}_e64 s4, {srcs}", "v_cndmask_b32_e64 v0, 0, 1, s4"] - asm = "; test_float_compares\n" + "".join(f"\t{ln}\n" for ln in lines) + "\texp mrt0 v0, v0, v0, v0 done vm\n\ts_endpgm\n" - with open(_SRC_PATH, "w", encoding="utf-8") as f: - f.write(asm) - with warnings.catch_warnings(): - warnings.simplefilter("ignore", ResourceWarning) - spv = rdna2spirv.translate(_SRC_PATH) - return si.run_fragment(spv)["%out_mrt0"][0] - - -class ReferenceTests(unittest.TestCase): - def test_nan_and_signed_zero(self): - nan = float("nan") - for cond in ORDERED: - self.assertFalse(relation(cond, nan, 1.0), cond) - for cond in UNORDERED: - self.assertTrue(relation(cond, nan, 1.0), cond) - self.assertTrue(relation("eq", 0.0, -0.0)) - self.assertFalse(relation("lg", 0.0, -0.0)) - - -class F32Compares(unittest.TestCase): - def test_every_condition_on_special_values(self): - for cond, form in itertools.product(CONDS, ("e32", "e64")): - op = f"v_cmp_{cond}_f32" - for (xn, xb), (yn, yb) in itertools.product(F32.items(), repeat=2): - with self.subTest(op=op, form=form, x=xn, y=yn): - want = int(relation(cond, f32_value(xb), f32_value(yb))) - self.assertEqual(run_cmp(op, xb, yb, form), want) - - def test_source_modifiers(self): - # e64 neg/abs apply before the compare: -x < |y| - for (xn, xb), (yn, yb) in itertools.product(F32.items(), repeat=2): - with self.subTest(x=xn, y=yn): - want = int(relation("lt", -f32_value(xb), abs(f32_value(yb)))) - self.assertEqual(run_cmp("v_cmp_lt_f32", xb, yb, "e64", "-v2, |v3|"), want) - - -class F16Compares(unittest.TestCase): - def test_every_condition_on_special_values(self): - for cond in CONDS: - op = f"v_cmp_{cond}_f16" - for (xn, xb), (yn, yb) in itertools.product(F16.items(), repeat=2): - with self.subTest(op=op, x=xn, y=yn): - want = int(relation(cond, f16_value(xb), f16_value(yb))) - self.assertEqual(run_cmp(op, 0xABCD0000 | xb, 0x12340000 | yb), want) - - -class CmpxNlgTests(unittest.TestCase): - def run_cmpx(self, op: str, x_bits: int, y_bits: int): - if _TMP_DIR is None: - setUpModule() - lines = [ - f"v_mov_b32 v2, {x_bits:#x}", - f"v_mov_b32 v3, {y_bits:#x}", - "v_mov_b32 v0, 0x3f800000", - f"{op}_e32 v2, v3", - ] - asm = "; test_cmpx_nlg\n" + "".join(f"\t{ln}\n" for ln in lines) + "\texp mrt0 v0, v0, v0, v0 done vm\n\ts_endpgm\n" - with open(_SRC_PATH, "w", encoding="utf-8") as f: - f.write(asm) - with warnings.catch_warnings(): - warnings.simplefilter("ignore", ResourceWarning) - spv = rdna2spirv.translate(_SRC_PATH) - return "%out_mrt0" in si.run_fragment(spv) - - def test_v_cmpx_nlg_f32_and_f16(self): - # nlg = unordered equal: active iff x == y or either operand is NaN. - for op, tbl in (("v_cmpx_nlg_f32", F32), ("v_cmpx_nlg_f16", F16)): - for xn, yn, want in (("1", "1", True), ("0", "-0", True), ("nan", "1", True), ("1", "2.5", False)): - with self.subTest(op=op, x=xn, y=yn): - self.assertEqual(self.run_cmpx(op, tbl[xn], tbl[yn]), want) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_float_nan_fract.py b/tests/semantic/test_float_nan_fract.py deleted file mode 100644 index deea344f6..000000000 --- a/tests/semantic/test_float_nan_fract.py +++ /dev/null @@ -1,547 +0,0 @@ -from __future__ import annotations - -"""Float min/max/min3/max3/med3 with quiet/signaling NaN, payload preservation, and v_fract near 1.0. - -The expected words were measured on RDNA2 hardware: AMD Radeon RX 6800 (gfx1030), with the hw-oracle tool from -the AnyPS5 project, in all four IEEE/DX10_CLAMP mode combinations and in wave32 and wave64 (docs/design.md, -"Float min/max/med3 with NaN, v_fract"). The rules: - * IEEE 754 binary32 NaN layout: - - Sign bit: [31] - - Exponent: [30:23] = 0xFF (all 1s) - - Mantissa: [22:0] != 0 - - Quiet NaN (qNaN): MSB of mantissa (bit 22) is 1. Payload in bits [21:0]. Canonical qNaN is 0x7FC00000. - - Signaling NaN (sNaN): MSB of mantissa (bit 22) is 0, payload in bits [21:0] is non-zero. - * RDNA2 ALU NaN handling & quieting: - - When an sNaN enters a float ALU operation, it is converted to a quiet NaN by setting bit 22 to 1. - - The custom mantissa payload in bits [21:0] is preserved where possible by unary rounding / transcendental - ops (v_floor_f32, v_ceil_f32, v_trunc_f32, v_rndne_f32). - * v_min/v_max (f32, f16, each half of v_pk_min/max_f16): one NaN operand gives the other operand, bits - unchanged; -0 < +0. Both NaN: returns src0's exact bits (preserving quiet/signalling NaN payloads). - * v_min3/v_max3 = f(f(s0, s1), s2) with that min/max. - * v_med3: with any NaN operand the result is min3(s0, s1, s2); otherwise the median. - * v_fract_f32: a result that rounds to 1.0 is 0x3f7fffff instead (f16: 0x3bff); fract(-0) = +0, - fract(+-inf) = NaN. -Inputs come from memory through s_buffer_load (V# in s[0:3] -> 0x1000), as in the GPU fixtures -runtime/test/shaders/ps_fnan_med3.asm and ps_fnan_fract.asm, which are run here too. -""" -import gc -import math -import os -import struct -import sys -import tempfile -import unittest -import warnings - -HERE = os.path.dirname(os.path.abspath(__file__)) -sys.path.insert(0, HERE) - -import support # noqa: E402 (puts LEONIDA_TOOLS_DIR or tools/ on the path) -import spirv_mini_interp as si # noqa: E402 - -rdna2spirv = support.rdna2spirv - -MASK32 = 0xFFFFFFFF -EXP_MASK32 = 0x7F800000 -MANTISSA_MASK32 = 0x007FFFFF -QUIET_BIT32 = 0x00400000 -PAYLOAD_MASK32 = 0x003FFFFF -SIGN_BIT32 = 0x80000000 - -NAN_A, NAN_B = 0x7FC10001, 0xFFC20002 # two quiet NaNs with different signs and payloads -M25, P35, P50, P70, ONE = 0xC0200000, 0x40600000, 0x40A00000, 0x40E00000, 0x3F800000 # -2.5 3.5 5 7 1 -PZ, NZ = 0x00000000, 0x80000000 -PUSH = [0x1000, 0, 32, 0] + [0] * 28 # V#: base 0x1000, num_records 32 - - -def is_nan32(w: int) -> bool: - return (w & EXP_MASK32) == EXP_MASK32 and bool(w & MANTISSA_MASK32) - - -def is_qnan32(w: int) -> bool: - return is_nan32(w) and bool(w & QUIET_BIT32) - - -def is_snan32(w: int) -> bool: - return is_nan32(w) and not bool(w & QUIET_BIT32) - - -def nan_payload32(w: int) -> int: - return w & PAYLOAD_MASK32 - - -def nan_sign32(w: int) -> int: - return (w >> 31) & 1 - - -def make_qnan32(sign: int = 0, payload: int = 0) -> int: - return ((sign & 1) << 31) | EXP_MASK32 | QUIET_BIT32 | (payload & PAYLOAD_MASK32) - - -def make_snan32(sign: int = 0, payload: int = 1) -> int: - pay = payload & PAYLOAD_MASK32 - if pay == 0: - pay = 1 - return ((sign & 1) << 31) | EXP_MASK32 | pay - - -def quiet_nan32(w: int) -> int: - """RDNA2 quieting: forces bit 22 to 1, preserving sign and mantissa payload.""" - return (w & MASK32) | QUIET_BIT32 - - -def ref_quiet_snan(w: int) -> int: - """If w is sNaN, return quieted NaN; otherwise return w unchanged.""" - if is_snan32(w): - return quiet_nan32(w) - return w & MASK32 - - -def is_nan16(h: int) -> bool: - return (h & 0x7C00) == 0x7C00 and bool(h & 0x3FF) - - -# Hand-worked test vectors for IEEE 754 NaN bitfields and quieting. -NAN_BITFIELD_SAMPLES: tuple[tuple[str, int, bool, bool, int, int], ...] = ( - # name, bits, is_qnan, is_snan, sign, payload - ("pos_canonical_qnan", 0x7FC00000, True, False, 0, 0), - ("neg_canonical_qnan", 0xFFC00000, True, False, 1, 0), - ("pos_qnan_min_payload", 0x7FC00001, True, False, 0, 1), - ("neg_qnan_min_payload", 0xFFC00001, True, False, 1, 1), - ("pos_qnan_alt_bits1", 0x7FD55555, True, False, 0, 0x155555), - ("neg_qnan_alt_bits2", 0xFFEAAAAA, True, False, 1, 0x2AAAAA), - ("pos_qnan_max_payload", 0x7FFFFFFF, True, False, 0, PAYLOAD_MASK32), - ("neg_qnan_max_payload", 0xFFFFFFFF, True, False, 1, PAYLOAD_MASK32), - ("pos_snan_min_payload", 0x7F800001, False, True, 0, 1), - ("neg_snan_min_payload", 0xFF800001, False, True, 1, 1), - ("pos_snan_alt_bits1", 0x7F955555, False, True, 0, 0x155555), - ("neg_snan_alt_bits2", 0xFFAAAAAA, False, True, 1, 0x2AAAAA), - ("pos_snan_max_payload", 0x7FBFFFFF, False, True, 0, PAYLOAD_MASK32), - ("neg_snan_max_payload", 0xFFBFFFFF, False, True, 1, PAYLOAD_MASK32), - ("pos_snan_custom_tag", 0x7FBA5A5A, False, True, 0, 0x3A5A5A), - ("neg_snan_custom_tag", 0xFFBA5A5A, False, True, 1, 0x3A5A5A), -) - -NON_NAN_BOUNDARY_SAMPLES: tuple[tuple[str, int], ...] = ( - ("pos_zero", 0x00000000), - ("neg_zero", 0x80000000), - ("pos_subnorm_min", 0x00000001), - ("neg_subnorm_min", 0x80000001), - ("pos_norm_min", 0x00800000), - ("pos_one", 0x3F800000), - ("neg_one", 0xBF800000), - ("pos_max_normal", 0x7F7FFFFF), - ("neg_max_normal", 0xFF7FFFFF), - ("pos_infinity", 0x7F800000), - ("neg_infinity", 0xFF800000), -) - - -def translate_text(body: str) -> str: - """SPIR-V text for a pixel shader whose instructions are ``body`` (one per line).""" - with tempfile.TemporaryDirectory() as tmp: - os.mkdir(os.path.join(tmp, "disasm")) - src = os.path.join(tmp, "disasm", "ps_fnan.s") - with open(src, "w", encoding="utf-8", newline="\n") as f: - f.write("; ps_fnan\n" + "".join("\t" + ln.strip() + "\n" for ln in body.strip().splitlines())) - with open(os.path.join(tmp, "ps_fnan.dxbc"), "wb") as f: - f.write(support.STUB_DXBC) - with warnings.catch_warnings(): - warnings.simplefilter("ignore", ResourceWarning) - spv = rdna2spirv.translate(src) - gc.collect() - return spv - - -LOAD = """s_buffer_load_dwordx4 s[4:7], s[0:3], 0 -s_waitcnt lgkmcnt(0) -v_mov_b32_e32 v1, s4 -v_mov_b32_e32 v2, s5 -v_mov_b32_e32 v3, s6 -v_mov_b32_e32 v4, s7 -v_mov_b32_e32 v0, 0 -""" - - -def run_op(line: str, inputs: tuple[int, ...]) -> int: - """Run ``line`` (writing v0, reading v1..v4 = inputs) and return the v0 word.""" - spv = translate_text(LOAD + line + "\nexp mrt0 v0, v0, v0, v0 done vm\ns_endpgm") - mem = {0x1000 + 4 * i: w for i, w in enumerate((list(inputs) + [0] * 4)[:4])} - return support.mrt0_words(spv, push_constants=PUSH, memory=mem)[0] - - -class NanBitfieldPayloadOracleTests(unittest.TestCase): - """Reference oracle tests for IEEE 754 NaN bitfield classification, payload preservation, and quieting.""" - - def test_nan_classification_and_payload_extraction(self): - for name, bits, want_qnan, want_snan, want_sign, want_payload in NAN_BITFIELD_SAMPLES: - with self.subTest(sample=name, bits=f"{bits:#010x}"): - self.assertTrue(is_nan32(bits)) - self.assertEqual(is_qnan32(bits), want_qnan) - self.assertEqual(is_snan32(bits), want_snan) - self.assertEqual(nan_sign32(bits), want_sign) - self.assertEqual(nan_payload32(bits), want_payload) - - def test_non_nan_boundary_rejection(self): - for name, bits in NON_NAN_BOUNDARY_SAMPLES: - with self.subTest(sample=name, bits=f"{bits:#010x}"): - self.assertFalse(is_nan32(bits)) - self.assertFalse(is_qnan32(bits)) - self.assertFalse(is_snan32(bits)) - - def test_make_qnan_and_snan_constructors(self): - for sign in (0, 1): - for payload in (0, 1, 0x1234, 0x155555, 0x2AAAAA, PAYLOAD_MASK32): - q = make_qnan32(sign, payload) - self.assertTrue(is_qnan32(q)) - self.assertFalse(is_snan32(q)) - self.assertEqual(nan_sign32(q), sign) - self.assertEqual(nan_payload32(q), payload) - - s_pay = payload if payload != 0 else 1 - s = make_snan32(sign, s_pay) - self.assertTrue(is_snan32(s)) - self.assertFalse(is_qnan32(s)) - self.assertEqual(nan_sign32(s), sign) - self.assertEqual(nan_payload32(s), s_pay) - - def test_snan_quieting_preserves_sign_and_payload(self): - for name, bits, _, is_snan, want_sign, want_payload in NAN_BITFIELD_SAMPLES: - if not is_snan: - continue - with self.subTest(sample=name, bits=f"{bits:#010x}"): - quieted = quiet_nan32(bits) - self.assertTrue(is_qnan32(quieted)) - self.assertFalse(is_snan32(quieted)) - self.assertEqual(nan_sign32(quieted), want_sign) - self.assertEqual(nan_payload32(quieted), want_payload) - self.assertEqual(quieted, bits | QUIET_BIT32) - # Quieting an already quiet NaN must be idempotent. - self.assertEqual(quiet_nan32(quieted), quieted) - self.assertEqual(ref_quiet_snan(bits), quieted) - self.assertEqual(ref_quiet_snan(quieted), quieted) - - def test_all_single_bit_payloads_roundtrip(self): - for bit_idx in range(22): - payload = 1 << bit_idx - for sign in (0, 1): - snan = make_snan32(sign, payload) - qnan = make_qnan32(sign, payload) - self.assertEqual(nan_payload32(snan), payload) - self.assertEqual(nan_payload32(qnan), payload) - self.assertEqual(quiet_nan32(snan), qnan) - - -class MinMaxNaN(unittest.TestCase): - ROWS = [ # (x, y, min, max); None = a NaN - (NAN_A, M25, M25, M25), - (M25, NAN_B, M25, M25), - (NAN_A, NAN_B, None, None), - (PZ, NZ, NZ, PZ), - (NZ, PZ, NZ, PZ), - ] - - def check(self, got, want, what): - if want is None: - self.assertTrue(is_nan32(got), f"{what}: {got:#010x} is not a NaN") - else: - self.assertEqual(got, want, f"{what}: got {got:#010x}, want {want:#010x}") - - def test_v_min_v_max_f32(self): - for x, y, mn, mx in self.ROWS: - for form in ("e32", "e64"): - with self.subTest(x=hex(x), y=hex(y), form=form): - self.check(run_op(f"v_min_f32_{form} v0, v1, v2", (x, y)), mn, f"min({x:#x}, {y:#x})") - self.check(run_op(f"v_max_f32_{form} v0, v1, v2", (x, y)), mx, f"max({x:#x}, {y:#x})") - - def test_v_min3_v_max3_f32(self): - self.assertEqual(run_op("v_min3_f32 v0, v1, v2, v3", (NAN_A, M25, P35)), M25) - self.assertEqual(run_op("v_max3_f32 v0, v1, v2, v3", (NAN_A, M25, P35)), P35) - - def test_v_min_v_max_f16(self): - # The other half of the destination (v0 = 0) is kept. - for x, y in ((0x7E11, 0xC100), (0xC100, 0xFE22)): - with self.subTest(x=hex(x), y=hex(y)): - self.assertEqual(run_op("v_min_f16_e32 v0, v1, v2", (x, y)), 0xC100) - self.assertEqual(run_op("v_max_f16_e32 v0, v1, v2", (x, y)), 0xC100) - - def test_v_pk_min_v_pk_max_f16(self): - # Low halves (0x7e11, 0xc100), high halves (0xc100, 0xfe22): both give 0xc100. - x, y = 0xC1007E11, 0xFE22C100 - self.assertEqual(run_op("v_pk_min_f16 v0, v1, v2", (x, y)), 0xC100C100) - self.assertEqual(run_op("v_pk_max_f16 v0, v1, v2", (x, y)), 0xC100C100) - - -class Med3NaN(unittest.TestCase): - def test_v_med3_f32_rows(self): - rows = [ - ((NAN_A, P70, P50), P50), - ((NAN_A, P35, M25), M25), - ((M25, NAN_B, P35), M25), - ((P70, P50, NAN_A), P50), # NaN in S2 (z): previously hit undefined FClamp - ((P50, P70, NAN_B), P50), - ((NAN_A, NAN_B, P50), P50), # two NaNs in S0, S1: previously hit undefined FClamp - ((NAN_A, P50, NAN_B), P50), - ((P50, NAN_A, NAN_B), P50), - ((NZ, PZ, NZ), NZ), - ((ONE, P35, M25), ONE), # no NaN: the median, unchanged - ] - for ins, want in rows: - with self.subTest(ins=[hex(w) for w in ins]): - self.assertEqual(run_op("v_med3_f32 v0, v1, v2, v3", ins), want) - # All three NaN: must return a NaN without triggering undefined FClamp. - self.assertTrue(is_nan32(run_op("v_med3_f32 v0, v1, v2, v3", (NAN_A, NAN_B, NAN_A)))) - spv = translate_text(LOAD + "v_med3_f32 v0, v1, v2, v3\nexp mrt0 v0, v0, v0, v0 done vm\ns_endpgm") - self.assertNotIn("FClamp", spv) - - def test_v_med3_f32_with_inline_constants(self): - # med3(0, NaN, 1.0) = 0 on hardware. Only the register operand can be a NaN, so only it is tested. - self.assertEqual(run_op("v_med3_f32 v0, 0, v1, 1.0", (NAN_A,)), PZ) - self.assertEqual(run_op("v_med3_f32 v0, 0, 1.0, v1", (NAN_A,)), PZ) - spv = translate_text(LOAD + "v_med3_f32 v0, 0, v1, 1.0\nexp mrt0 v0, v0, v0, v0 done vm\ns_endpgm") - self.assertEqual(spv.count("OpIsNan"), 1) - - def test_v_med3_f32_all_constants_needs_no_select(self): - spv = translate_text("v_med3_f32 v0, 0, 1.0, 2.0\nexp mrt0 v0, v0, v0, v0 done vm\ns_endpgm") - self.assertNotIn("OpIsNan", spv) - self.assertNotIn("OpSelect %float", spv) - self.assertEqual(support.mrt0_words(spv)[0], ONE) - - def test_v_med3_f32_nan_literal_is_checked(self): - # A literal can be a NaN, so it keeps its OpIsNan (and med3 gives min3 = the smallest of the others). - spv = translate_text(LOAD + "v_med3_f32 v0, 0x7fc00000, v1, v2\nexp mrt0 v0, v0, v0, v0 done vm\ns_endpgm") - self.assertEqual(spv.count("OpIsNan"), 3) - self.assertEqual(support.mrt0_words(spv, push_constants=PUSH, memory={0x1000: P70, 0x1004: P50})[0], P50) - - def test_v_med3_f16_follows_the_same_rule(self): - # All 1-, 2-, and 3-NaN operand positions for v_med3_f16 (measured on gfx1035 wave32 & wave64). - nan16, h5, h7 = 0x7E11, 0x4500, 0x4700 - for ins, want in ( - ((nan16, h7, h5), h5), - ((h7, nan16, h5), h5), - ((h7, h5, nan16), h5), - ((nan16, nan16, h5), h5), - ((nan16, h5, nan16), h5), - ((h5, nan16, nan16), h5), - ): - with self.subTest(ins=[hex(w) for w in ins]): - self.assertEqual(run_op("v_med3_f16 v0, v1, v2, v3", ins), want) - self.assertTrue(is_nan16(run_op("v_med3_f16 v0, v1, v2, v3", (nan16, nan16, nan16)) & 0xFFFF)) - - -class FractNearOne(unittest.TestCase): - def test_v_fract_f32_rows(self): - for x, want in ((0xAEDBE6FF, 0x3F7FFFFF), (0xB2800000, 0x3F7FFFFF), (NZ, PZ), - (0x3FC00000, 0x3F000000), (0xBF99999A, 0x3F4CCCCC)): - with self.subTest(x=hex(x)): - self.assertEqual(run_op("v_fract_f32_e32 v0, v1", (x,)), want) - - def test_v_fract_f32_of_infinity_is_nan(self): - for x in (0x7F800000, 0xFF800000): - with self.subTest(x=hex(x)): - self.assertTrue(is_nan32(run_op("v_fract_f32_e32 v0, v1", (x,)))) - - def test_v_fract_f16_rows(self): - for x in (0x8800, 0x8001, 0x9000): - with self.subTest(x=hex(x)): - self.assertEqual(run_op("v_fract_f16_e32 v0, v1", (x,)), 0x3BFF) - got = run_op("v_fract_f16_e32 v0, v1", (0x7C00,)) - self.assertTrue(is_nan16(got & 0xFFFF) and got >> 16 == 0, hex(got)) - - def test_v_fract_f16_mul2_keeps_a_true_one(self): - # On RDNA2 with denorms kept, mul:2 is ignored on f16: fract(0.5) remains 0.5 (0x3800). - self.assertEqual(run_op("v_fract_f16_e64 v0, v1 mul:2", (0x3800,)), 0x3800) - - def test_fract_alone_rounds_to_one(self): - # Without the select, fract(-1e-10) is exactly 1.0: the select is what gives 0x3f7fffff. - self.assertEqual(si.f32_bits(si._fract(si.bits_f32(0xAEDBE6FF))), ONE) - - -class GpuFixtures(unittest.TestCase): - """The GPU fixtures with the heap words check.py seeds (the same words the .asm headers give).""" - - def test_ps_fnan_med3(self): - heap = (NAN_A, P70, P50, NAN_A, P35, M25) - spv = support.translate_fixture("ps_fnan_med3") - words = support.mrt0_words(spv, push_constants=PUSH, - memory={0x1000 + 4 * i: w for i, w in enumerate(heap)}) - self.assertEqual(words, [P50, M25, M25, P35]) - - def test_ps_fnan_fract(self): - heap = (0xAEDBE6FF, 0x00008800, NAN_A, M25) - spv = support.translate_fixture("ps_fnan_fract") - words = support.mrt0_words(spv, push_constants=[0x1000, 0, 16, 0] + [0] * 28, - memory={0x1000 + 4 * i: w for i, w in enumerate(heap)}) - self.assertEqual(words, [0x3F7FFFFF, 0x00003BFF, M25, M25]) - - def test_ps_fnan_med3_s2(self): - # med3(5, 7, NaN), med3(NaN, NaN, 5), med3(NaN, -2.5, NaN), med3(7, NaN, NaN): min3 with the NaNs ignored - heap = (P50, P70, NAN_A, M25) - spv = support.translate_fixture("ps_fnan_med3_s2") - words = support.mrt0_words(spv, push_constants=[0x1000, 0, 16, 0] + [0] * 28, - memory={0x1000 + 4 * i: w for i, w in enumerate(heap)}) - self.assertEqual(words, [P50, P50, M25, P70]) - - def test_ps_f16_fnan_med3(self): - # the same four rows as f16 (5.0, 7.0, NaN, -2.5); the high half of each destination is kept - heap = (0x00004500, 0x00004700, 0x00007E01, 0x0000C100) - spv = support.translate_fixture("ps_f16_fnan_med3") - words = support.mrt0_words(spv, push_constants=[0x1000, 0, 16, 0] + [0] * 28, - memory={0x1000 + 4 * i: w for i, w in enumerate(heap)}) - self.assertEqual(words, [0xAAAA4500, 0xAAAA4500, 0xAAAAC100, 0xAAAA4700]) - - -class AllNaNSrc0PayloadTests(unittest.TestCase): - """All-NaN operands in f16 and 3-input min/max/med3 preserve src0's NaN bits (including sNaN under IEEE=0).""" - - @staticmethod - def _run_with_old(line: str, inputs: tuple[int, ...], old: int = 0xDEADBEEF) -> int: - spv = translate_text(LOAD + f"v_mov_b32_e32 v0, {old:#x}\n" + line + "\nexp mrt0 v0, v0, v0, v0 done vm\ns_endpgm") - mem = {0x1000 + 4 * i: w for i, w in enumerate((list(inputs) + [0] * 4)[:4])} - return support.mrt0_words(spv, push_constants=PUSH, memory=mem)[0] - - def test_f16_all_nan_keeps_src0_and_mods(self): - snan, qnan_a, qnan_b = 0x7C01, 0x7E02, 0xFE22 - for op in ("v_min_f16_e32", "v_max_f16_e32"): - with self.subTest(op=op): - self.assertEqual(self._run_with_old(f"{op} v0, v1, v2", (0xAAAA0000 | snan, 0xBBBB0000 | qnan_a)), - 0xDEAD0000 | snan) - self.assertEqual(self._run_with_old(f"{op} v0, v1, v2", (0xAAAA0000 | qnan_b, 0xBBBB0000 | snan)), - 0xDEAD0000 | qnan_b) - self.assertEqual( - self._run_with_old("v_min_f16_e64 v0, -v1, v2 op_sel:[1,0,1]", ((snan << 16) | 0x3C00, qnan_a)), - ((snan ^ 0x8000) << 16) | 0xBEEF, - ) - self.assertEqual( - self._run_with_old("v_max_f16_e64 v0, |v1|, v2", (snan | 0x8000, qnan_a)), - 0xDEAD0000 | snan, - ) - self.assertEqual( - self._run_with_old( - "v_min_f16_sdwa v0, -v1, v2 dst_sel:WORD_1 dst_unused:UNUSED_PRESERVE src0_sel:WORD_1 src1_sel:WORD_0", - ((snan << 16) | 0x1111, 0x22220000 | qnan_a), - ), - ((snan ^ 0x8000) << 16) | 0xBEEF, - ) - for op in ("v_min3_f16", "v_max3_f16", "v_med3_f16"): - with self.subTest(op=op): - self.assertEqual(self._run_with_old(f"{op} v0, v1, v2, v3", (snan, qnan_a, qnan_b)), 0xDEAD0000 | snan) - self.assertEqual( - self._run_with_old(f"{op} v0, -|v1|, v2, v3 op_sel:[1,0,0,1]", ((snan << 16), qnan_a, qnan_b)), - ((snan ^ 0x8000) << 16) | 0xBEEF, - ) - self.assertEqual( - self._run_with_old(f"{op} v0, v1, v2, v3", (snan, qnan_a, 0x3C00)), - 0xDEAD3C00, - ) - self.assertEqual( - self._run_with_old(f"{op} v0, 0x7c01, v1, v2", (qnan_a, qnan_b)), - 0xDEAD7C01, - ) - - def test_pk_minmax_f16_all_nan_per_lane(self): - # Lane 0 all-NaN keeps src0 sNaN (0x7C01), lane 1 picks finite -2.5 (0xC100) over qNaN. - for op in ("v_pk_min_f16", "v_pk_max_f16"): - with self.subTest(op=op): - self.assertEqual(run_op(f"{op} v0, v1, v2", (0xFE117C01, 0xC1007E02)), 0xC1007C01) - self.assertEqual(run_op(f"{op} v0, v1, v2", (0xFC053C00, 0x7E007C01)), 0xFC053C00) - self.assertEqual( - run_op("v_pk_min_f16 v0, v1, v2 op_sel:[1,0] op_sel_hi:[0,1] neg_lo:[1,0] neg_hi:[0,1]", - (0x7C01FE22, 0x7E037E04)), - ((0xFE22) << 16) | (0x7C01 ^ 0x8000), - ) - # NaN literal in high half + non-NaN in low half: high preserves 0x7C01, low keeps 0x3C00. - self.assertEqual(run_op("v_pk_min_f16 v0, 0x7c013c00, v1", (0x7E027E03,)), 0x7C013C00) - - def test_f32_three_input_all_nan_keeps_src0(self): - snan_a, snan_b = 0x7F800001, 0xFF800005 - for op in ("v_min3_f32", "v_max3_f32", "v_med3_f32"): - with self.subTest(op=op): - self.assertEqual(run_op(f"{op} v0, v1, v2, v3", (snan_a, NAN_A, NAN_B)), snan_a) - self.assertEqual(run_op(f"{op} v0, v1, v2, v3", (NAN_A, NAN_B, snan_b)), NAN_A) - self.assertEqual(run_op(f"{op} v0, -v1, v2, v3", (snan_a, NAN_A, NAN_B)), snan_a ^ SIGN_BIT32) - for args in ((snan_a, NAN_B, M25), (snan_a, M25, NAN_B), (M25, snan_a, NAN_B)): - self.assertEqual(run_op(f"{op} v0, v1, v2, v3", args), M25) - - def test_f32_two_input_minmax_modifiers_keep_signaling_nan(self): - snan = 0x7F800001 - for op in ("v_min_f32_e64", "v_max_f32_e64"): - with self.subTest(op=op): - self.assertEqual(run_op(f"{op} v0, -v1, v2", (snan, NAN_A)), snan ^ SIGN_BIT32) - self.assertEqual(run_op(f"{op} v0, |v1|, v2", (snan, NAN_A)), snan) - - def test_non_nan_constant_fast_path(self): - # f16_bits emits 1 OpUGreaterThan (%float |x| > inf); all-NaN tracking adds 0 when a constant is non-NaN. - for line, reg_line, extra_gt in ( - ("v_min_f16_e32 v0, v1, 1.0", "v_min_f16_e32 v0, v1, v2", 2), - ("v_min3_f16 v0, v1, v2, 1.0", "v_min3_f16 v0, v1, v2, v3", 3), - ): - spv_const = translate_text(LOAD + line + "\nexp mrt0 v0, v0, v0, v0 done vm\ns_endpgm") - spv_reg = translate_text(LOAD + reg_line + "\nexp mrt0 v0, v0, v0, v0 done vm\ns_endpgm") - self.assertEqual(spv_const.count("OpUGreaterThan "), 1, line) - self.assertEqual(spv_reg.count("OpUGreaterThan "), 1 + extra_gt, reg_line) - # v_pk_min_f16 emits 2 f16_bits conversions -> 2 OpUGreaterThan when fast-pathed vs 6 with 2 registers x 2 lanes. - self.assertEqual( - translate_text(LOAD + "v_pk_min_f16 v0, v1, 1.0\nexp mrt0 v0, v0, v0, v0 done vm\ns_endpgm").count("OpUGreaterThan "), - 2, - ) - self.assertEqual( - translate_text(LOAD + "v_pk_min_f16 v0, v1, v2\nexp mrt0 v0, v0, v0, v0 done vm\ns_endpgm").count("OpUGreaterThan "), - 6, - ) - spv_min3_f32 = translate_text(LOAD + "v_min3_f32 v0, v1, v2, 1.0\nexp mrt0 v0, v0, v0, v0 done vm\ns_endpgm") - self.assertEqual(spv_min3_f32.count("OpIsNan"), 1) - - def test_spirv_val_all_nan_variants(self): - import shutil - import subprocess - spirv_as = shutil.which("spirv-as") - spirv_val = shutil.which("spirv-val") - if not (spirv_as and spirv_val): - self.skipTest("spirv-as / spirv-val not found") - spv = translate_text(LOAD + "\n".join([ - "v_min_f16_e32 v0, v1, v2", - "v_min3_f16 v0, -|v1|, v2, v3 op_sel:[1,0,0,1]", - "v_med3_f16 v0, v1, v2, v3", - "v_pk_max_f16 v0, v1, v2 neg_lo:[1,0] op_sel:[0,1]", - "v_min3_f32 v0, v1, v2, v3", - "v_med3_f32 v0, v1, v2, v3", - "exp mrt0 v0, v0, v0, v0 done vm", - "s_endpgm", - ])) - bin_spv = subprocess.run([spirv_as, "--target-env", "vulkan1.2", "-o", "-", "-"], - input=spv.encode("utf-8"), check=True, stdout=subprocess.PIPE).stdout - subprocess.run([spirv_val, "--target-env", "vulkan1.2", "-"], input=bin_spv, check=True) - - -class InterpreterOps(unittest.TestCase): - """NMin/NMax, OpIsNan and Fract in spirv_mini_interp, against GLSL.std.450.""" - - def test_nmin_nmax(self): - nan = float("nan") - self.assertEqual(si._nmin_nmax("NMin", nan, -2.5), -2.5) - self.assertEqual(si._nmin_nmax("NMax", -2.5, nan), -2.5) - self.assertTrue(math.isnan(si._nmin_nmax("NMin", nan, nan))) - self.assertEqual(math.copysign(1, si._nmin_nmax("NMin", 0.0, -0.0)), -1) - self.assertEqual(math.copysign(1, si._nmin_nmax("NMax", -0.0, 0.0)), 1) - - def test_fract_exact(self): - self.assertEqual(si._fract(-0.75), 0.25) - self.assertEqual(math.copysign(1, si._fract(-0.0)), 1) - self.assertTrue(math.isnan(si._fract(float("inf")))) - self.assertEqual(si._fract(si.bits_f32(0x80000001)), 1.0) # 1 - 2**-149 rounds to 1.0 - - def test_fmin_of_nan_still_raises(self): - body = ("OpCapability Shader\n%glsl = OpExtInstImport \"GLSL.std.450\"\nOpMemoryModel Logical GLSL450\n" - "OpEntryPoint Fragment %main \"main\" %out\n%void = OpTypeVoid\n%fn = OpTypeFunction %void\n" - "%uint = OpTypeInt 32 0\n%float = OpTypeFloat 32\n%_ptr_Output_uint = OpTypePointer Output %uint\n" - "%out = OpVariable %_ptr_Output_uint Output\n%n = OpConstant %uint 2143289344\n" - "%main = OpFunction %void None %fn\n%entry = OpLabel\n%x = OpBitcast %float %n\n" - "%r = OpExtInst %float %glsl FMin %x %x\n%u = OpBitcast %uint %r\nOpStore %out %u\nOpReturn\n" - "OpFunctionEnd\n") - with self.assertRaises(si.UnsupportedConstruct): - si.run_fragment(body) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_float_to_int.py b/tests/semantic/test_float_to_int.py deleted file mode 100644 index 27be66fa8..000000000 --- a/tests/semantic/test_float_to_int.py +++ /dev/null @@ -1,122 +0,0 @@ -from __future__ import annotations -from fractions import Fraction -import struct -import unittest - -import support - -M32 = 0xFFFFFFFF - - -def ref_float_to_int(u: int) -> tuple[int, int]: - u &= M32 - sign = (u >> 31) & 1 - exp = (u >> 23) & 0xFF - mant = u & 0x7FFFFF - if exp == 0xFF: - if mant != 0: - return 0, 0 - if sign: - return 0, 0x80000000 - return 0xFFFFFFFF, 0x7FFFFFFF - if exp == 0: - x = Fraction(0) - else: - x = Fraction((1 << 23) | mant) * (Fraction(2) ** (exp - 150)) - if sign: - x = -x - iv = int(x) - if iv >= (1 << 32): - u_res = 0xFFFFFFFF - elif iv < 0: - u_res = 0 - else: - u_res = iv & M32 - if iv >= (1 << 31): - s_res = 0x7FFFFFFF - elif iv < -(1 << 31): - s_res = 0x80000000 - else: - s_res = iv & M32 - return u_res, s_res - - -CASES = ( - (0x00000000, 0, 0), - (0x80000000, 0, 0), - (0x00000001, 0, 0), - (0x3FC00000, 1, 1), - (0xBFC00000, 0, 0xFFFFFFFF), - (0x4EFFFFFF, 0x7FFFFF80, 0x7FFFFF80), - (0x4F000000, 0x80000000, 0x7FFFFFFF), - (0x4F7FFFFF, 0xFFFFFF00, 0x7FFFFFFF), - (0x4F800000, 0xFFFFFFFF, 0x7FFFFFFF), - (0xCEFFFFFF, 0, 0x80000080), - (0xCF000000, 0, 0x80000000), - (0xCF000001, 0, 0x80000000), - (0x7F800000, 0xFFFFFFFF, 0x7FFFFFFF), - (0xFF800000, 0, 0x80000000), - (0x7F800001, 0, 0), - (0xFFC00000, 0, 0), -) - - -class FloatToIntTest(unittest.TestCase): - def test_reference_oracle(self): - for bits, expected_u, expected_s in CASES: - u_res, s_res = ref_float_to_int(bits) - self.assertEqual(u_res, expected_u) - self.assertEqual(s_res, expected_s) - - def test_multi_lane_divergence_and_rounding(self): - rounding_cases = [ - (0x3F800000, 1, 1), - (0x3FA00000, 1, 1), - (0x3FE00000, 1, 1), - (0xBF800000, 0, 0xFFFFFFFF), - (0xBFA00000, 0, 0xFFFFFFFF), - (0xBFE00000, 0, 0xFFFFFFFF), - ] - fssm = bytes(0x138) + struct.pack("<4I", 0x808A, 1, 1, 1) - spv = support.translate_fixture("cs_cvt_f32_sat", fssm=fssm) - for bits, unsigned, signed in rounding_cases: - memory = {} - support.run_fragment( - spv, inputs={"%wg_id": (0, 0, 0), "%local_id": (0, 0, 0)}, - push_constants=[0, 0, 8, 0x31016FAC, bits] + [0] * 27, memory=memory) - self.assertEqual(memory[0], unsigned) - self.assertEqual(memory[4], signed) - - def test_nan_inf_saturation_and_negative_controls(self): - special_cases = [ - (0x7F800000, 0xFFFFFFFF, 0x7FFFFFFF), # +inf - (0xFF800000, 0, 0x80000000), # -inf - (0x7F800001, 0, 0), # +NaN - (0xFFC00000, 0, 0), # -NaN - (0x80000000, 0, 0), # -0 negative control - (0x00000001, 0, 0), # subnormal negative control - ] - fssm = bytes(0x138) + struct.pack("<4I", 0x808A, 1, 1, 1) - spv = support.translate_fixture("cs_cvt_f32_sat", fssm=fssm) - for bits, unsigned, signed in special_cases: - memory = {} - support.run_fragment( - spv, inputs={"%wg_id": (0, 0, 0), "%local_id": (0, 0, 0)}, - push_constants=[0, 0, 8, 0x31016FAC, bits] + [0] * 27, memory=memory) - self.assertEqual(memory[0], unsigned) - self.assertEqual(memory[4], signed) - - def test_saturating_conversions(self): - fssm = bytes(0x138) + struct.pack("<4I", 0x808A, 1, 1, 1) - spv = support.translate_fixture("cs_cvt_f32_sat", fssm=fssm) - for bits, unsigned, signed in CASES: - with self.subTest(bits=f"{bits:08x}"): - memory = {} - support.run_fragment( - spv, inputs={"%wg_id": (0, 0, 0), "%local_id": (0, 0, 0)}, - push_constants=[0, 0, 8, 0x31016FAC, bits] + [0] * 27, memory=memory) - self.assertEqual(memory, {0: unsigned, 4: signed}) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_fma_exact.py b/tests/semantic/test_fma_exact.py deleted file mode 100644 index 79a04eb8d..000000000 --- a/tests/semantic/test_fma_exact.py +++ /dev/null @@ -1,307 +0,0 @@ -"""--fma exact (SHADER-497): fused multiply-adds emulated from single-rounded f32 operations (Gen.fma_exact). - -RDNA2's v_fma_f32, v_fmac_f32, v_fmaak_f32, v_fmamk_f32 and v_fma_mix* round once. GLSL Fma may be split into two -roundings by a driver (Intel UHD Graphics, Xe-LP, Windows driver 101.7088: cs_fma_fused words 0, 2, 3 and 5), and a -device without VK_KHR_shader_fma can't take --fma khr. --fma exact builds the single rounding from NoContraction -FMul/FAdd/FSub: Dekker's exact product, TwoSum, a round-to-odd sum of the two error terms and one final rounding -(Boldo and Melquiond, IEEE Transactions on Computers 57(4), 2008), with power-of-two scaling that keeps every -intermediate in the normal range. The interpreter rounds every FMul/FAdd/FSub to binary32, so these tests run the -emitted instructions as a driver would, and compare each word with an exact rational reference (si.fma_f32). -""" -import math -import os -import random -import shutil -import struct -import subprocess -import sys -import tempfile -import unittest - -HERE = os.path.dirname(os.path.abspath(__file__)) -ROOT = os.path.dirname(os.path.dirname(HERE)) -TOOLS_DIR = os.environ.get("LEONIDA_TOOLS_DIR") or os.path.join(ROOT, "tools") -sys.path.insert(0, TOOLS_DIR) -sys.path.insert(0, HERE) - -import rdna2spirv # noqa: E402 -import spirv_mini_interp as si # noqa: E402 -from support import mrt0_words, translate_lines # noqa: E402 - -EXIT = ["exp mrt0 v0, v1, v2, v3 done vm", "s_endpgm"] -EXACT_FMA = si.fma_f32 - - -def split_fma(x, y, z): - """GLSL Fma on a driver that rounds the product first, as the Intel UHD driver does for cs_fma_fused.""" - return si.f32(si.f32(x * y) + z) - - -def run_split(spv): - """mrt0_words with the interpreter's Fma split into two roundings, so only the emulation can be exact.""" - si.fma_f32 = split_fma - try: - return mrt0_words(spv) - finally: - si.fma_f32 = EXACT_FMA - - -def run_split_flushing(spv): - """run_split on a driver that also flushes every f32 denormal result to a zero of its sign.""" - keep = si.f32 - - def f32_ftz(v): - r = keep(v) - return math.copysign(0.0, r) if r != 0.0 and abs(r) < 2.0 ** -126 else r - - si.f32 = f32_ftz - try: - return run_split(spv) - finally: - si.f32 = keep - - -def f32_of(w): - return struct.unpack(":1:1: warning: invalid instruction encoding"] - return ("\n".join(lines) + "\n").encode("utf-8") - - -def blob(prog): - return bytes(CODE_START) + b"".join(bytes.fromhex(enc) for _, enc in prog) - - -def f2u(x): - return struct.unpack(":1:1: warning: invalid instruction encoding\n" - - -class FmaMixInlineLiteralTest(unittest.TestCase): - """llvm-mc 21 prints a v_fma_mix* literal whose low half is an inline constant's f16 value as that constant, in - 8 bytes (the text and encodings below are llvm-mc 21.1.8's, -mcpu=gfx1013, for the stored bytes). The literal and - the 4 bytes come from the blob, and the instructions after it keep their offsets (EXP and s_endpgm are checked - against the blob 4 bytes further on).""" - - def run_ps(self, data, fssm): - return mrt0_words(translate_listing(NAME, data, fssm=fssm)) - - def both_paths(self, data, fssm, want): - self.assertEqual(self.run_ps(data, fssm), [f2u(want)] * 4) - self.assertEqual(self.run_ps(with_invalid(data), fssm), [f2u(want)] * 4) - - def test_f32_source_keeps_its_high_half(self): - # Stored literal 0x40400000 (3.0) read as f32 by src0; llvm-mc 21 prints `0`. fma(3.0, 2.0, 0) = 6.0. - data, fssm = printed_and_stored("v_fma_mix_f32 v1, 0, v2, 0", "01 00 20 cc 80 04 02 02", - "01 00 20 cc ff 04 02 02", 0x40400000) - self.both_paths(data, fssm, 6.0) - # LLVM's text alone (no blob) is what the listing says: fma(0, 2.0, 0) = 0. - self.assertEqual(self.run_ps(data, None), [0] * 4) - - def test_f16_halves_of_one_literal(self): - # 0x3c003800: src0 the low half 0.5, src2 the high half 1.0 (op_sel:[0,0,1] op_sel_hi:[1,0,1]); llvm-mc 21 - # prints 0.5 for both. fma(0.5, 2.0, 1.0) = 2.0, where the print would give 1.5. - data, fssm = printed_and_stored("v_fma_mix_f32 v1, 0.5, v2, 0.5 op_sel:[0,0,1] op_sel_hi:[1,0,1]", - "01 60 20 cc f0 04 c2 0b", "01 60 20 cc ff 04 fe 0b", 0x3C003800) - self.both_paths(data, fssm, 2.0) - - def test_neg_and_abs_come_from_the_stored_bits(self): - data, fssm = printed_and_stored("v_fma_mix_f32 v1, neg(0), v2, 0", "01 00 20 cc 80 04 02 22", - "01 00 20 cc ff 04 02 22", 0x40400000) - self.both_paths(data, fssm, -6.0) - data, fssm = printed_and_stored("v_fma_mix_f32 v1, |0|, v2, 0", "01 01 20 cc 80 04 02 02", - "01 01 20 cc ff 04 02 02", 0xC0400000) - self.both_paths(data, fssm, 6.0) - - def test_every_inline_code_maps_to_its_f16_bits(self): - self.assertEqual(len(rdna2spirv.MIX_INLINE_F16), 90) - for code, bits in rdna2spirv.MIX_INLINE_F16.items(): - stored = bytes.fromhex("0100 20cc ff04 0202") + struct.pack("> bit & ((1 << w) - 1) - bit += w - signed = v - (1 << w) if v >> (w - 1) else v - if kind in ("f32", "u32", "i32", "uint"): - out.append(v) - elif kind == "sint": - out.append(signed & 0xFFFFFFFF) - elif kind == "f16": - # A NaN half widens as sign | 0x7F800000 | payload << 13, quiet bit as stored: measured on gfx1036 for - # formats 13, 29 and 71 (#4623, tools/f16_widen_probe.py). Not struct's ' 0x7C00: - out.append((v & 0x8000) << 16 | 0x7F800000 | (v & 0x3FF) << 13) - else: - out.append(f32_bits(half_to_float(v))) - elif kind == "unorm": - out.append(f32_bits(float(Fraction(v, (1 << w) - 1)))) - elif kind == "snorm": - out.append(f32_bits(float(max(Fraction(-1), Fraction(signed, (1 << (w - 1)) - 1))))) - else: - return None # a kind this reference doesn't model: covered by its own tests - return tuple(out[c % len(out)] for c in range(4)) - - -def load(code): - lines = [f"s_mov_b32 s0, {BASE:#x}", "s_mov_b32 s1, 0", "s_mov_b32 s2, 0x100", - f"s_mov_b32 s3, {code << 12 | 0x30000FAC:#x}", "v_mov_b32 v1, 0", - "buffer_load_format_xyzw v[2:5], v1, s[0:3], 0 offen", "exp mrt0 v2, v3, v4, v5 done vm", "s_endpgm"] - spv = support.translate_lines("ps_fmt_table", lines) - return tuple(run_fragment(spv, memory={BASE + 4 * i: w for i, w in enumerate(WORDS)})["%out_mrt0"]) - - -def module_of(code=1): - lines = [f"s_mov_b32 s0, {BASE:#x}", "s_mov_b32 s1, 0", "s_mov_b32 s2, 0x100", - f"s_mov_b32 s3, {code << 12 | 0x30000FAC:#x}", "v_mov_b32 v1, 0", - "buffer_load_format_xyzw v[2:5], v1, s[0:3], 0 offen", "exp mrt0 v2, v3, v4, v5 done vm", "s_endpgm"] - return support.translate_lines("ps_fmt_table", lines) - - -def function_body(spv, name): - """The lines of the function `name`, without its header and its end.""" - body, inside = [], False - for line in spv.splitlines(): - text = line.strip() - if text.startswith(f"{name} = OpFunction"): - inside = True - continue - if inside: - if text == "OpFunctionEnd": - break - body.append(text) - return body - - -BRANCHES = ("OpBranchConditional", "OpSelectionMerge", "OpSwitch", "OpBranch", "OpLoopMerge") - - -class FormatDecodeTableTests(unittest.TestCase): - def test_every_format_and_the_codes_between(self): - for code in range(max(rdna2spirv.Gen.FORMATS) + 2): - want = reference(code) - if want is not None: - self.assertEqual(load(code), want, f"format {code}") - - def test_the_decode_has_no_branch(self): - spv = module_of() - for k in range(4): - body = function_body(spv, f"%fmt_dec_c{k}") - self.assertTrue(body, f"the decode of component {k} is missing") - for line in body: - for op in BRANCHES: - self.assertNotIn(op, line, f"the decode branches: {line}") - - def test_the_decode_is_shared_per_component(self): - spv = module_of() - for k in range(4): - self.assertIn(f"%fmt_dec_c{k} = OpFunction %uint None %fn_fmt_dec", spv) - self.assertIn(f"OpFunctionCall %uint %fmt_dec_c{k} ", spv) - # The load site calls the four functions; the decode itself is not inlined there. - main = function_body(spv, "%main") - calls = [ln for ln in main if "OpFunctionCall %uint %fmt_dec_c" in ln] - self.assertEqual(len(calls), 4) - - def test_the_decode_is_small(self): - spv = module_of() - count = sum(len(function_body(spv, f"%fmt_dec_c{k}")) for k in range(4)) - # Before, the shared function held every format's decode and a binary search over the codes: 3,498 - # instructions and 306 branches in the module of a shader with one dynamic-format load. - self.assertLess(count, 900, f"the decode is {count} instructions") - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_fract_f16_infinity.py b/tests/semantic/test_fract_f16_infinity.py deleted file mode 100644 index 5badac004..000000000 --- a/tests/semantic/test_fract_f16_infinity.py +++ /dev/null @@ -1,16 +0,0 @@ -"""Exact f16 Fract infinity word measured on gfx1036 (docs/design.md).""" -import unittest -from pathlib import Path - -from support import mrt0_words, translate_lines - - -class FractInfinityTests(unittest.TestCase): - def test_fract_f16_infinity(self) -> None: - fixture = Path(__file__).with_name("fixtures") / "ps_fract_f16_infinity.asm" - module = translate_lines(fixture.stem, fixture.read_text(encoding="ascii").splitlines()) - - for source, clamped in ((0x3E00, 0x3800), (0x7C00, 0), (0xFC00, 0)): - with self.subTest(source=hex(source)): - words = mrt0_words(module, push_constants=[source] + [0] * 31) - self.assertEqual(words, [0x1357FE00, 0x2468FE00, 0x3F800000, 0x12340000 | clamped]) diff --git a/tests/semantic/test_frexp_ldexp_f16_mods.py b/tests/semantic/test_frexp_ldexp_f16_mods.py deleted file mode 100644 index 78ce091f6..000000000 --- a/tests/semantic/test_frexp_ldexp_f16_mods.py +++ /dev/null @@ -1,205 +0,0 @@ -"""Semantic SPIR-V and interpreter tests for RDNA2 v_frexp/v_ldexp_f16 VOP3 output modifiers. - -Translates synthetic RDNA2 pixel shaders via tools/rdna2spirv.py, runs them in -tests/semantic/spirv_mini_interp.py against the gfx1036-measured model in tools/frexp_ldexp_f16_mods_probe.py, -checks byte-identical no-op omod SPIR-V emission, op_sel half preservation, inactive EXEC preservation, -Unsupported rejection of unmodelled modifiers, and spirv-as/spirv-val validation. Standard library only. -""" -import os -import shutil -import struct -import subprocess -import sys -import tempfile -import unittest -import warnings - -HERE = os.path.dirname(os.path.abspath(__file__)) -ROOT = os.path.dirname(os.path.dirname(HERE)) -TOOLS = os.environ.get("LEONIDA_TOOLS_DIR") or os.path.join(ROOT, "tools") - -sys.dont_write_bytecode = True -for p in (TOOLS, HERE): - if p not in sys.path: - sys.path.insert(0, p) - -import frexp_ldexp_f16_mods_probe as probe # noqa: E402 -import rdna2spirv # noqa: E402 -import spirv_mini_interp as si # noqa: E402 - -STUB_DXBC = b"DXBC" + bytes(24) + struct.pack(" str: - if _TMP is None: - setUpModule() - asm = "; ps_frexp_ldexp_f16_mods\n" + "".join(f"\t{ln}\n" for ln in lines) - with open(_SRC_PATH, "w", encoding="utf-8", newline="\n") as f: - f.write(asm) - with warnings.catch_warnings(): - warnings.simplefilter("ignore", ResourceWarning) - return rdna2spirv.translate(_SRC_PATH) - - -def _run_ps(lines: list[str]) -> tuple[int, str]: - spv = _translate(lines + ["exp mrt0 v0, v0, v0, v0 done vm", "s_endpgm"]) - return si.run_fragment(spv)["%out_mrt0"][0], spv - - -def _op_line(op: str, mod: str, *, s0: str = "v1", s1: str = "v2") -> str: - suffix = f" {mod}" if mod else "" - if op == "v_ldexp_f16": - return f"v_ldexp_f16_e64 v0, {s0}, {s1}{suffix}" - return f"{op}_e64 v0, {s0}{suffix}" - - -class FrexpLdexpF16ModsSemanticTests(unittest.TestCase): - def test_edge_inputs_across_all_output_modifiers(self): - ldexp_edge = (0x0000, 0x8000, 0x0001, 0x0400, 0x3800, 0x3C00, 0xBC00, 0x7BFF, 0x7C00, 0xFC00, 0x7C01, 0x7E00) - for op in probe.OPS: - if op == "v_ldexp_f16": - pairs = [(h, 1) for h in probe.EDGE_F16] + [ - (h, n) for h in ldexp_edge for n in probe.LDEXP_EXPS if n != 1 - ] - else: - pairs = [(h, 0) for h in probe.EDGE_F16] - for mod in probe.MODS: - for h, n in pairs: - want = probe.expected_word(op, h, n, mod=mod, init_dst=0xDEADBEEF) - lines = [ - f"v_mov_b32 v1, {0xABCD0000 | h:#x}", - f"v_mov_b32 v2, {0x12340000 | (n & 0xFFFF):#x}", - "v_mov_b32 v0, 0xdeadbeef", - _op_line(op, mod), - ] - with self.subTest(op=op, mod=mod or "plain", h=hex(h), n=n): - got, _ = _run_ps(lines) - self.assertEqual(got, want) - - def test_source_modifier_cases(self): - for c in probe.SRC_MOD_CASES: - s0 = f"-|v1|" if (c.src0_abs and c.src0_neg) else (f"|v1|" if c.src0_abs else (f"-v1" if c.src0_neg else "v1")) - want = probe.expected_word( - c.op, c.h, c.n, mod=c.mod, init_dst=c.init_dst, src0_abs=c.src0_abs, src0_neg=c.src0_neg - ) - lines = [ - f"v_mov_b32 v1, {0xABCD0000 | c.h:#x}", - f"v_mov_b32 v2, {0x12340000 | (c.n & 0xFFFF):#x}", - f"v_mov_b32 v0, {c.init_dst:#x}", - _op_line(c.op, c.mod, s0=s0), - ] - with self.subTest(case=c.name): - got, _ = _run_ps(lines) - self.assertEqual(got, want) - - def test_noop_omod_emits_byte_identical_spirv(self): - preamble = ["v_mov_b32 v1, 0xabcdbc00", "v_mov_b32 v2, 0x12340001", "v_mov_b32 v0, 0xdeadbeef"] - for op in ("v_frexp_mant_f16", "v_ldexp_f16"): - _, spv_plain = _run_ps(preamble + [_op_line(op, "")]) - for omod in ("mul:2", "mul:4", "div:2"): - with self.subTest(op=op, omod=omod): - _, spv_omod = _run_ps(preamble + [_op_line(op, omod)]) - self.assertEqual(spv_omod, spv_plain) - _, spv_clamp = _run_ps(preamble + [_op_line(op, "clamp")]) - for omod in ("mul:2", "mul:4", "div:2"): - with self.subTest(op=op, mod=f"clamp {omod}"): - _, spv_cm = _run_ps(preamble + [_op_line(op, f"clamp {omod}")]) - self.assertEqual(spv_cm, spv_clamp) - - _, spv_exp_plain = _run_ps(preamble + [_op_line("v_frexp_exp_i16_f16", "")]) - for mod in probe.MODS[1:]: - with self.subTest(op="v_frexp_exp_i16_f16", mod=mod): - _, spv_exp_mod = _run_ps(preamble + [_op_line("v_frexp_exp_i16_f16", mod)]) - self.assertEqual(spv_exp_mod, spv_exp_plain) - - def test_opsel_with_output_modifiers_preserves_other_half(self): - # v1 = {hi: 8.0 (0x4800), lo: -1.0 (0xBC00)}; v2 = {hi: 2, lo: 1} - v1 = (0x4800 << 16) | 0xBC00 - v2 = (2 << 16) | 1 - init = 0x11112222 - cases = [ - ("v_frexp_mant_f16", "op_sel:[1,0] mul:2", (init & 0xFFFF0000) | 0x3800), - ("v_frexp_mant_f16", "op_sel:[1,1] clamp div:2", (0x3800 << 16) | (init & 0xFFFF)), - ("v_frexp_mant_f16", "op_sel:[0,1] clamp mul:4", (0x0000 << 16) | (init & 0xFFFF)), - ("v_frexp_exp_i16_f16", "op_sel:[1,0] clamp mul:2", (init & 0xFFFF0000) | 0x0004), - ("v_frexp_exp_i16_f16", "op_sel:[1,1] clamp div:2", (0x0004 << 16) | (init & 0xFFFF)), - ("v_ldexp_f16", "op_sel:[1,1,0] clamp mul:2", (init & 0xFFFF0000) | 0x3C00), - ("v_ldexp_f16", "op_sel:[0,1,1] clamp div:2", (0x0000 << 16) | (init & 0xFFFF)), - ("v_ldexp_f16", "op_sel:[1,0,1] mul:4", (0x4C00 << 16) | (init & 0xFFFF)), - ] - for op, mod, want in cases: - with self.subTest(op=op, mod=mod): - got, _ = _run_ps([f"v_mov_b32 v1, {v1:#x}", f"v_mov_b32 v2, {v2:#x}", - f"v_mov_b32 v0, {init:#x}", _op_line(op, mod)]) - self.assertEqual(got, want) - - def test_inactive_exec_preserves_dst(self): - sentinel = 0xA5A55A5A - for op in probe.OPS: - for mod in ("clamp", "mul:2", "clamp div:2"): - with self.subTest(op=op, mod=mod): - got, _ = _run_ps([ - f"v_mov_b32 v0, {sentinel:#x}", - "v_mov_b32 v1, 0x3c00", - "v_mov_b32 v2, 1", - "s_mov_b32 s10, exec_lo", - "s_mov_b32 exec_lo, 0", - _op_line(op, mod), - "s_mov_b32 exec_lo, s10", - ]) - self.assertEqual(got, sentinel) - - def test_unmodelled_modifiers_raise_unsupported(self): - for op in probe.OPS: - for bad in ("mul:8", "div:4", "op_sel_hi:[1,0]", "neg_lo:[1]", "neg_hi:[1]"): - with self.subTest(op=op, mod=bad), self.assertRaises(rdna2spirv.Unsupported): - _translate([_op_line(op, bad), "exp mrt0 v0, v0, v0, v0 done vm", "s_endpgm"]) - - def test_spirv_validates_with_spirv_val(self): - if not shutil.which("spirv-as") or not shutil.which("spirv-val"): - self.skipTest("spirv-as or spirv-val not on PATH") - with tempfile.TemporaryDirectory() as d: - for op in probe.OPS: - for mod in ("clamp", "mul:2", "clamp mul:4", "div:2"): - spv_text = _translate([ - "v_mov_b32 v1, 0xabcdbc00", - "v_mov_b32 v2, 0x12340001", - "v_mov_b32 v0, 0xdeadbeef", - _op_line(op, mod), - "exp mrt0 v0, v0, v0, v0 done vm", - "s_endpgm", - ]) - sa_path = os.path.join(d, "test.spvasm") - spv_path = os.path.join(d, "test.spv") - with open(sa_path, "w", encoding="utf-8", newline="\n") as f: - f.write(spv_text) - rdna2spirv.assemble_spirv(sa_path, spv_path) - res = subprocess.run( - ["spirv-val", "--target-env", "vulkan1.3", spv_path], - capture_output=True, text=True, - ) - self.assertEqual(res.returncode, 0, f"{op} {mod}: {res.stderr}") - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_fspx_rules.py b/tests/semantic/test_fspx_rules.py deleted file mode 100644 index a0a355598..000000000 --- a/tests/semantic/test_fspx_rules.py +++ /dev/null @@ -1,229 +0,0 @@ -"""Semantic tests for FSPX / FidelityFX translator rules (#1754 follow-ups, docs/fspx.md): - -1. LLVM VCCTuple scalar register lists ending in vcc_lo,vcc_hi (`[s100,...,s105,vcc_lo,vcc_hi]` and - `[s92,...,s105,vcc_lo,vcc_hi]`) parsed in tools/shader_ir.py, clearing `vcc` in tools/lane_masks.py, - and handled in s_buffer_load_dwordx*/s_load_dword*, buffer/global addressing, and T#/S# lookups. -2. `src_scc` special source operand (RDNA2 encoding 253 = SCC, 0 or 1) in scalar and vector ALU ops. -3. `image_atomic_*` / `image_atomic_cmpswap` with `a16` packed 16-bit unsigned coordinates (2D and 3D). - -Standard library only; no GPU, no LLVM, no game files. -""" -from __future__ import annotations - -import os -import struct -import sys -import tempfile -import unittest -import warnings - -HERE = os.path.dirname(os.path.abspath(__file__)) -ROOT = os.path.dirname(os.path.dirname(HERE)) -sys.dont_write_bytecode = True -sys.path.insert(0, os.environ.get("LEONIDA_TOOLS_DIR") or os.path.join(ROOT, "tools")) -sys.path.insert(0, HERE) - -import lane_masks # noqa: E402 -import rdna2spirv # noqa: E402 -import shader_ir # noqa: E402 -import shader_meta # noqa: E402 -import spirv_mini_interp as si # noqa: E402 - -STUB_DXBC = b"DXBC" + bytes(24) + struct.pack(" SCC = 0 - "v_add_nc_u32_e32 v3, src_scc, v1", # 20 - "v_mov_b32_e32 v4, s6", - "v_mov_b32_e32 v5, s7", - f"v_mov_b32_e32 v8, {OUT:#x}", - "global_store_dwordx4 v8, v[2:5], s[0:1]", - ] - res = run_cs(body, {}) - self.assertEqual([res.get(OUT + 4 * i) for i in range(4)], [21, 20, 1, 11]) - - -class ImageAtomicA16Tests(unittest.TestCase): - def test_image_atomic_add_2d_and_3d_a16_translate(self): - # 2D a16: one VGPR packs (x: u16 low, y: u16 high); 3D a16: two VGPRs pack (x, y) and (z, _). - spv_2d = translate([ - "v_mov_b32_e32 v1, 0x00050003", # x=3, y=5 - "v_mov_b32_e32 v2, 1", - "image_atomic_add v2, v1, s[4:11] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm a16 glc", - "s_waitcnt vmcnt(0)", - f"v_mov_b32_e32 v6, {OUT:#x}", - "global_store_dword v6, v2, s[0:1]", - ]) - self.assertIn("OpImageTexelPointer", spv_2d) - self.assertIn("OpAtomicIAdd", spv_2d) - self.assertIn("OpShiftRightLogical %uint", spv_2d) - - spv_3d = translate([ - "v_mov_b32_e32 v1, 0x00050003", # x=3, y=5 - "v_mov_b32_e32 v2, 0x00000007", # z=7 - "v_mov_b32_e32 v3, 1", - "image_atomic_add v3, v[1:2], s[4:11] dmask:0x1 dim:SQ_RSRC_IMG_3D unorm a16", - "s_waitcnt vmcnt(0)", - ]) - self.assertIn("OpCompositeConstruct %v3int", spv_3d) - self.assertIn("OpAtomicIAdd", spv_3d) - - def test_image_atomic_2d_too_few_coords_rejected(self): - with self.assertRaises(rdna2spirv.Unsupported): - translate([ - "v_mov_b32_e32 v1, 0", "v_mov_b32_e32 v2, 1", - "image_atomic_add v2, v1, s[4:11] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm", - ]) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_fspx_wave_size.py b/tests/semantic/test_fspx_wave_size.py deleted file mode 100644 index 2126e011a..000000000 --- a/tests/semantic/test_fspx_wave_size.py +++ /dev/null @@ -1,160 +0,0 @@ -"""The wave size of an FSPX program (the FidelityFX DLL's, docs/fspx.md) comes from its dispatch state: kind 0 word 4 -bit 20 set = wave32, which tools/fspx_unpack.py writes to fspx/.json as `wave32`. Before, a program without an -FSSM sidecar got the code heuristic, which also counts any _b64 op on vcc or exec as wave64; the DLL's wave32 -programs move vcc as an ordinary SGPR pair, so they were translated as wave64, and a wave64 program without any -marker as wave32. - -Every case is a hand-written listing in the FSPX layout (disasm/, fspx/.json and .code, no fssm/), translated -by tools/rdna2spirv.py. The last class runs the result, where the two wave sizes give different answers. -Standard library only; no GPU, no LLVM, no game files. -""" -import json -import os -import struct -import sys -import tempfile -import unittest -import warnings - -HERE = os.path.dirname(os.path.abspath(__file__)) -ROOT = os.path.dirname(os.path.dirname(HERE)) -sys.dont_write_bytecode = True -sys.path.insert(0, os.environ.get("LEONIDA_TOOLS_DIR") or os.path.join(ROOT, "tools")) -sys.path.insert(0, HERE) -sys.path.insert(0, os.path.join(ROOT, "tests")) - -import rdna2spirv # noqa: E402 -import spirv_mini_interp as si # noqa: E402 -from test_fssm_unpack import make_dxbc, make_xbch, make_xdat_list # noqa: E402 - -STUB_DXBC = b"DXBC" + bytes(24) + struct.pack(".json beside it says.""" - with self.assertRaises(rdna2spirv.Unsupported) as cm: - translate(VCC_AS_DATA, wave32=True, fssm=fssm_header(wave32=True)) - self.assertIn("FSSM wave32 header contradicts wave64 code", str(cm.exception)) - self.assertTrue(translate(["v_mov_b32_e32 v1, v0"], wave32=True, fssm=fssm_header(wave32=False))[1]) - - -# v0 = local id x. Lane 0 stores readlane(3 * lane + 1, 40): the lane select is S1[4:0] in wave32 (lane 8, 25) and -# S1[5:0] in wave64 (lane 40, 121). No instruction here is a wave marker, so only the dispatch state decides. -READLANE_40 = [ - "v_mad_u32_u24 v2, v0, 3, 1", - "v_readlane_b32 s6, v2, 40", - "v_cmpx_eq_u32_e32 0, v0", - "v_mov_b32_e32 v20, s6", - "v_mov_b32_e32 v21, 0", - "buffer_store_dword v20, v21, s[0:3], 0 offen", -] - - -def run(asm, subgroup_size): - memory = si.run_workgroup( - asm, 64, subgroup_size, - inputs_for=lambda i: {"%wg_id": (0, 0, 0), "%local_id": (i, 0, 0), "%sg_lane": i % subgroup_size}, - push_constants=VSHARP + [0] * 32, memory={}) - return memory.get(0) - - -class TheChoiceMatters(unittest.TestCase): - def test_readlane_40_reads_lane_8_in_wave32_and_lane_40_in_wave64(self): - asm32, wave64 = translate(READLANE_40, wave32=True) - self.assertFalse(wave64) - self.assertEqual(run(asm32, 32), 3 * 8 + 1) - asm64, wave64 = translate(READLANE_40, wave32=False) - self.assertTrue(wave64) - self.assertEqual(run(asm64, 64), 3 * 40 + 1) - - -class LibraryGraphicsWaveSize(unittest.TestCase): - def test_source_wave32_corroborates_a_32_bit_exec_instruction(self): - body = [ - "s_bfm_b64 s[8:9], 3, 1", - "s_and_saveexec_b32 s10, -1", - "v_mov_b32_e32 v20, 0", - "exp pos0 v20, v20, v20, v20 done", - ] - for flags, expected_wave64 in (([True], False), ([False], True), ([True, False], True), ([], True)): - with self.subTest(flags=flags): - payloads = [(0x0D, make_xbch(fssm_header(flag))) for flag in flags] - source = make_dxbc([(b"DXIL", make_xdat_list(payloads))]) - _, wave64 = translate(body, name="vs_wave", container=source) - self.assertEqual(wave64, expected_wave64) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_global_atomic_float.py b/tests/semantic/test_global_atomic_float.py deleted file mode 100644 index 2f78eb6f1..000000000 --- a/tests/semantic/test_global_atomic_float.py +++ /dev/null @@ -1,309 +0,0 @@ -"""Semantic tests for RDNA2 global_atomic_fmin and global_atomic_fmax (32-bit float). - -Verifies the CAS loop lowering (OpAtomicCompareExchange + GLSL.std.450 NMin/NMax): - - IEEE 754 float semantics: positives, negatives, signed zeros (-0.0 < +0.0), infinities, - subnormals, and NaN handling (NaN operand returns the other operand). - - Pre-op value return in vdst when 'glc' is present, and preservation of vdst when 'glc' is absent. - - Addressing modes: saddr SGPR pair, saddr='off' with 64-bit vaddr, and signed 12-bit offsets (-2048..2044). - - EXEC masking: inactive lanes bypass the CAS loop entirely, leave memory untouched, and retain vdst. - - Multi-lane CAS contention: multiple active lanes racing on a single shared memory location. - - Rejection of invalid modifiers (slc, dlc, lds), operand counts, and multi-dword registers. - - Dependency analysis (read_before_write_vgprs). - -Note on hardware fidelity (measured natively on gfx1036 for #2361 by @Pierre-Kookis): - - The expectations below verify what rdna2spirv's CAS lowering with GLSL.std.450 NMin/NMax produces today - with denormals kept (Vulkan default). - - On native hardware under the game's MODE (f32 denormals flushed), a denormal operand counts as a signed zero. - - On native hardware, an sNaN in either operand wins and is stored quieted (0x7fc00001), whereas GLSL NMin/NMax - returns the non-NaN operand. - -Standard library only; runs through spirv_mini_interp on the CPU without GPU, LLVM, or game files. -""" -from __future__ import annotations - -import math -import os -import struct -import sys -import tempfile -import unittest -import warnings - -HERE = os.path.dirname(os.path.abspath(__file__)) -ROOT = os.path.dirname(os.path.dirname(HERE)) -sys.dont_write_bytecode = True -sys.path.insert(0, os.environ.get("LEONIDA_TOOLS_DIR") or os.path.join(ROOT, "tools")) -sys.path.insert(0, HERE) - -import rdna2spirv # noqa: E402 -import spirv_mini_interp as si # noqa: E402 -from shader_ir import parse_line as parse # noqa: E402 - -STUB_DXBC = b"DXBC" + bytes(24) + struct.pack(" str: - with tempfile.TemporaryDirectory() as tmp: - for d in ("disasm", "fssm"): - os.mkdir(os.path.join(tmp, d)) - with open(os.path.join(tmp, "cs_gatomic_f.dxbc"), "wb") as f: - f.write(STUB_DXBC) - with open(os.path.join(tmp, "fssm", "cs_gatomic_f.fssm"), "wb") as f: - f.write(FSSM) - src = os.path.join(tmp, "disasm", "cs_gatomic_f.s") - with open(src, "w", encoding="utf-8", newline="\n") as f: - f.write("; cs_gatomic_f\n" + "".join(f"\t{ln}\n" for ln in body) + "\ts_endpgm\n") - with warnings.catch_warnings(): - warnings.simplefilter("ignore", ResourceWarning) - return rdna2spirv.translate(src) - - -def run_cs(body: list[str], memory: dict[int, int], nlanes: int = 1) -> dict[int, int]: - spv = translate(body) - mem = dict(memory) - si.run_workgroup(spv, nlanes, 32, - inputs_for=lambda i: {"%wg_id": (0, 0, 0), "%local_id": (i, 0, 0), "%sg_lane": i}, - push_constants=[0] * 36, memory=mem) - return mem - - -def run_atomic(kind: str, mem_init: int, data_val: int, glc: bool = True, - offset: int = 0, vaddr: int = TARGET) -> tuple[int | None, int | None]: - body = [ - f"v_mov_b32_e32 v1, {vaddr - offset:#x}", - f"v_mov_b32_e32 v2, {data_val:#x}", - "v_mov_b32_e32 v5, 0xdeadbeef" - ] - off_str = f" offset:{offset}" if offset else "" - if glc: - body.append(f"global_atomic_{kind} v5, v1, v2, s[0:1]{off_str} glc") - else: - body.append(f"global_atomic_{kind} v1, v2, s[0:1]{off_str}") - body += [ - "s_waitcnt vmcnt(0)", - f"v_mov_b32_e32 v6, {OUT:#x}", - "global_store_dword v6, v5, s[0:1]" - ] - res_mem = run_cs(body, {TARGET: mem_init}) - return res_mem.get(OUT), res_mem.get(TARGET) - - -class GlobalAtomicFloatSemantics(unittest.TestCase): - def test_fmin_fmax_standard_values(self): - cases = [ - # (kind, init_mem, data, expected_final) - # Basic ordered values - ("fmin", ONE, TWO, ONE), - ("fmin", TWO, ONE, ONE), - ("fmin", ONE, NEG_TWO, NEG_TWO), - ("fmin", NEG_TWO, ONE, NEG_TWO), - ("fmin", NEG_ONE, NEG_TWO, NEG_TWO), - ("fmax", ONE, TWO, TWO), - ("fmax", TWO, ONE, TWO), - ("fmax", ONE, NEG_TWO, ONE), - ("fmax", NEG_TWO, ONE, ONE), - ("fmax", NEG_ONE, NEG_TWO, NEG_ONE), - # Signed zeros (-0.0 < +0.0) - ("fmin", POS_ZERO, NEG_ZERO, NEG_ZERO), - ("fmin", NEG_ZERO, POS_ZERO, NEG_ZERO), - ("fmax", POS_ZERO, NEG_ZERO, POS_ZERO), - ("fmax", NEG_ZERO, POS_ZERO, POS_ZERO), - # Infinities - ("fmin", ONE, POS_INF, ONE), - ("fmin", POS_INF, ONE, ONE), - ("fmin", ONE, NEG_INF, NEG_INF), - ("fmin", NEG_INF, ONE, NEG_INF), - ("fmin", POS_INF, NEG_INF, NEG_INF), - ("fmax", ONE, POS_INF, POS_INF), - ("fmax", POS_INF, ONE, POS_INF), - ("fmax", ONE, NEG_INF, ONE), - ("fmax", NEG_INF, ONE, ONE), - ("fmax", POS_INF, NEG_INF, POS_INF), - # Subnormal numbers: holds with denormals kept (Vulkan default). - # On gfx1036 in denormals-flushed MODE, denormals flush to signed zero (#2361). - ("fmin", POS_ZERO, SUBNORM_MIN, POS_ZERO), - ("fmin", SUBNORM_MAX, SUBNORM_MIN, SUBNORM_MIN), - ("fmax", POS_ZERO, SUBNORM_MIN, SUBNORM_MIN), - ("fmax", SUBNORM_MAX, SUBNORM_MIN, SUBNORM_MAX), - # NaN handling: GLSL.std.450 NMin/NMax returns the non-NaN operand. - # On native RDNA2 hardware (#2361), sNaN in either operand wins and is stored quieted. - ("fmin", QNAN, ONE, ONE), - ("fmin", ONE, QNAN, ONE), - ("fmin", SNAN, NEG_TWO, NEG_TWO), - ("fmin", NEG_TWO, SNAN, NEG_TWO), - ("fmin", NEG_QNAN, HALF, HALF), - ("fmax", QNAN, ONE, ONE), - ("fmax", ONE, QNAN, ONE), - ("fmax", SNAN, NEG_TWO, NEG_TWO), - ("fmax", NEG_TWO, SNAN, NEG_TWO), - ("fmax", NEG_QNAN, HALF, HALF), - ] - for kind, m_init, d_val, exp_final in cases: - with self.subTest(op=kind, m=hex(m_init), d=hex(d_val)): - out_vdst, final_mem = run_atomic(kind, m_init, d_val, glc=True) - self.assertEqual(out_vdst, m_init, "glc must return pre-op memory value in vdst") - self.assertEqual(final_mem, exp_final, "memory must reflect atomic fmin/fmax result") - - def test_both_nan_leaves_nan_in_memory(self): - # When both memory and data are NaN, the result is NaN - for kind in ("fmin", "fmax"): - with self.subTest(op=kind): - out_vdst, final_mem = run_atomic(kind, QNAN, SNAN, glc=True) - self.assertEqual(out_vdst, QNAN) - # Unpack as float32 to check NaN property - f_val = struct.unpack("> 31 else x - - -MODEL = { - "add": lambda m, d: (m + d) & M32, "sub": lambda m, d: (m - d) & M32, - "umin": min, "umax": max, - "smin": lambda m, d: m if s32(m) <= s32(d) else d, "smax": lambda m, d: m if s32(m) >= s32(d) else d, - "and": lambda m, d: m & d, "or": lambda m, d: m | d, "xor": lambda m, d: m ^ d, "swap": lambda m, d: d, -} -VALUES = [0, 1, 0x7FFFFFFF, 0x80000000, M32, 0x12345678] - - -def translate(body): - with tempfile.TemporaryDirectory() as tmp: - for d in ("disasm", "fssm"): - os.mkdir(os.path.join(tmp, d)) - with open(os.path.join(tmp, "cs_gatomic.dxbc"), "wb") as f: - f.write(STUB_DXBC) - with open(os.path.join(tmp, "fssm", "cs_gatomic.fssm"), "wb") as f: - f.write(FSSM) - src = os.path.join(tmp, "disasm", "cs_gatomic.s") - with open(src, "w", encoding="utf-8") as f: - f.write("; cs_gatomic\n" + "".join(f"\t{ln}\n" for ln in body) + "\ts_endpgm\n") - with warnings.catch_warnings(): - warnings.simplefilter("ignore", ResourceWarning) - return rdna2spirv.translate(src) - - -def run(body, memory, nlanes=1): - """s[0:1] = 0 (the saddr base, from push constants), v0 = lane index.""" - spv = translate(body) - mem = dict(memory) - si.run_workgroup(spv, nlanes, 32, - inputs_for=lambda i: {"%wg_id": (0, 0, 0), "%local_id": (i, 0, 0), "%sg_lane": i}, - push_constants=[0] * 36, memory=mem) - return mem - - -def atomic(kind, m, data, cmp=None, glc=True, offset=0, vaddr=TARGET): - body = [f"v_mov_b32_e32 v1, {vaddr - offset:#x}", f"v_mov_b32_e32 v2, {data:#x}", "v_mov_b32_e32 v5, 0xdead"] - vdata = "v2" - if cmp is not None: - body.append(f"v_mov_b32_e32 v3, {cmp:#x}") - vdata = "v[2:3]" - off = f" offset:{offset}" if offset else "" - body.append(f"global_atomic_{kind} v5, v1, {vdata}, s[0:1]{off} glc" if glc else - f"global_atomic_{kind} v1, {vdata}, s[0:1]{off}") - body += ["s_waitcnt vmcnt(0)", f"v_mov_b32_e32 v6, {OUT:#x}", "global_store_dword v6, v5, s[0:1]"] - mem = run(body, {TARGET: m}) - return mem.get(OUT), mem.get(TARGET) - - -class GlobalAtomics(unittest.TestCase): - def test_returning_forms(self): - for kind, fn in MODEL.items(): - for m in VALUES: - for d in VALUES[::2]: - with self.subTest(op=kind, m=hex(m), d=hex(d)): - self.assertEqual(atomic(kind, m, d), (m, fn(m, d))) - - def test_without_glc_vdst_is_kept(self): - for kind, fn in MODEL.items(): - with self.subTest(op=kind): - self.assertEqual(atomic(kind, 0x80000005, 7, glc=False), (0xDEAD, fn(0x80000005, 7))) - - def test_cmpswap(self): - for m, cmp, new in ((5, 5, 9), (5, 6, 9), (M32, M32, 0), (0, 1, 2)): - with self.subTest(m=m, cmp=cmp, new=new): - self.assertEqual(atomic("cmpswap", m, new, cmp=cmp), (m, new if m == cmp else m)) - self.assertEqual(atomic("cmpswap", 5, 9, cmp=5, glc=False), (0xDEAD, 9)) - - def test_offsets(self): - for offset in (-2048, -4, 4, 2044): - with self.subTest(offset=offset): - self.assertEqual(atomic("add", 40, 2, offset=offset), (40, 42)) - - def test_off_addressing(self): - body = [f"v_mov_b32_e32 v8, {TARGET:#x}", "v_mov_b32_e32 v9, 0", "v_mov_b32_e32 v2, 3", - "global_atomic_or v5, v[8:9], v2, off glc", "s_waitcnt vmcnt(0)", - f"v_mov_b32_e32 v6, {OUT:#x}", "global_store_dword v6, v5, s[0:1]"] - mem = run(body, {TARGET: 0x10}) - self.assertEqual((mem.get(OUT), mem.get(TARGET)), (0x10, 0x13)) - - def test_seeded(self): - rng = random.Random(0x6A70) - for _ in range(20): - kind, m, d = rng.choice(list(MODEL)), rng.getrandbits(32), rng.getrandbits(32) - with self.subTest(op=kind, m=hex(m), d=hex(d)): - self.assertEqual(atomic(kind, m, d), (m, MODEL[kind](m, d))) - - def test_rejected_forms(self): - for line in ("global_atomic_add_x2 v[4:5], v1, v[2:3], s[0:1] glc", "global_atomic_inc_x2 v[4:5], v1, v[2:3], s[0:1] glc", - "global_atomic_fmin_x2 v[4:5], v1, v[2:3], s[0:1] glc", - "global_atomic_add v5, v1, v2, s[0:1] glc slc", - "global_atomic_cmpswap v5, v1, v2, s[0:1] glc"): - with self.subTest(line=line): - with self.assertRaises(rdna2spirv.Unsupported): - translate(["v_mov_b32_e32 v1, 0", line]) - - def test_float_min_max(self): - # IEEE 754 single-precision fmin/fmax via CAS + GLSL NMin/NMax: NaN returns the other operand, -0.0 < +0.0. - pos0, neg0 = 0x00000000, 0x80000000 - one, neg2, half = 0x3F800000, 0xC0000000, 0x3F000000 - pinf, ninf, qnan = 0x7F800000, 0xFF800000, 0x7FC00001 - cases = [ - ("fmin", one, half, half), - ("fmin", half, one, half), - ("fmin", one, neg2, neg2), - ("fmin", pos0, neg0, neg0), - ("fmin", neg0, pos0, neg0), - ("fmin", one, pinf, one), - ("fmin", one, ninf, ninf), - ("fmin", qnan, one, one), - ("fmin", one, qnan, one), - ("fmax", one, half, one), - ("fmax", half, one, one), - ("fmax", neg2, one, one), - ("fmax", pos0, neg0, pos0), - ("fmax", neg0, pos0, pos0), - ("fmax", one, pinf, pinf), - ("fmax", one, ninf, one), - ("fmax", qnan, one, one), - ("fmax", one, qnan, one), - ] - for kind, m, d, expected in cases: - with self.subTest(op=kind, m=hex(m), d=hex(d)): - self.assertEqual(atomic(kind, m, d), (m, expected)) - self.assertEqual(atomic(kind, m, d, glc=False), (0xDEAD, expected)) - - def test_float_min_max_inactive_and_off_addressing(self): - # Inactive lane (v0 != 0) must leave memory untouched and preserve vdst; lane 0 runs global_atomic_fmax via off. - one, two = 0x3F800000, 0x40000000 - body = [ - f"v_mov_b32_e32 v8, {TARGET:#x}", "v_mov_b32_e32 v9, 0", - f"v_mov_b32_e32 v2, {two:#x}", "v_mov_b32_e32 v5, 0xdead", - "v_cmp_eq_u32_e32 vcc_lo, 0, v0", - "s_and_saveexec_b32 s4, vcc_lo", - "global_atomic_fmax v5, v[8:9], v2, off glc", - "s_mov_b32 exec_lo, s4", - "s_waitcnt vmcnt(0)", - f"v_lshlrev_b32_e32 v6, 2, v0", - f"v_add_nc_u32_e32 v6, {OUT:#x}, v6", - "global_store_dword v6, v5, s[0:1]", - ] - mem = run(body, {TARGET: one}, nlanes=2) - self.assertEqual(mem.get(TARGET), two) - self.assertEqual(mem.get(OUT), one) - self.assertEqual(mem.get(OUT + 4), 0xDEAD) - - def test_float_min_max_multi_lane_cas_contention(self): - # Two active lanes race on TARGET: lane 0 proposes 1.0f, lane 1 proposes -2.0f. - init, one, neg2 = 0x40400000, 0x3F800000, 0xC0000000 # 3.0, 1.0, -2.0 - for kind, expected in (("fmin", neg2), ("fmax", init)): - with self.subTest(op=kind): - body = [ - f"v_mov_b32_e32 v1, {TARGET:#x}", - "v_cmp_eq_u32_e32 vcc_lo, 0, v0", - f"v_mov_b32_e32 v2, {neg2:#x}", - f"v_cndmask_b32_e32 v2, v2, {one:#x}, vcc_lo", - f"global_atomic_{kind} v5, v1, v2, s[0:1] glc", - "s_waitcnt vmcnt(0)", - "v_lshlrev_b32_e32 v6, 2, v0", - f"v_add_nc_u32_e32 v6, {OUT:#x}, v6", - "global_store_dword v6, v5, s[0:1]", - ] - mem = run(body, {TARGET: init}, nlanes=2) - self.assertEqual(mem.get(TARGET), expected) - # One lane saw the initial 3.0f; the second saw the first lane's post-op value. - seen = {mem.get(OUT), mem.get(OUT + 4)} - self.assertIn(init, seen) - - def test_float_min_max_offsets_and_first_read(self): - one, two = 0x3F800000, 0x40000000 - for offset in (-2048, -4, 4, 2044): - with self.subTest(offset=offset): - self.assertEqual(atomic("fmin", two, one, offset=offset), (two, one)) - self.assertEqual(atomic("fmax", one, two, offset=offset), (one, two)) - from shader_ir import parse_line as parse - self.assertEqual(rdna2spirv.read_before_write_vgprs([parse("\tglobal_atomic_fmax v1, v2, s[0:1]")]), {1, 2}) - self.assertEqual(rdna2spirv.read_before_write_vgprs([parse("\tglobal_atomic_fmax v5, v1, v2, s[0:1] glc")]), - {1, 2}) - - def test_first_read_analysis(self): - # Without glc operand 0 is the address (read); with glc it is vdst (written). - from shader_ir import parse_line as parse - no_glc = [parse("\tglobal_atomic_add v1, v2, s[0:1]")] - glc = [parse("\tglobal_atomic_add v5, v1, v2, s[0:1] glc")] - self.assertEqual(rdna2spirv.read_before_write_vgprs(no_glc), {1, 2}) - self.assertEqual(rdna2spirv.read_before_write_vgprs(glc), {1, 2}) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_global_atomics_x2.py b/tests/semantic/test_global_atomics_x2.py deleted file mode 100644 index d0da12d5b..000000000 --- a/tests/semantic/test_global_atomics_x2.py +++ /dev/null @@ -1,73 +0,0 @@ -"""Value tests for RDNA2 global_atomic_{and,or,xor,swap}_x2, run through spirv_mini_interp on the CPU. - -M = op(M, DATA) on the 64-bit element at the global_* address (two dwords, low first); with glc the old 64 bits land in -vdst[0:1]. The translator does one 32-bit atomic per dword, which leaves the same memory for a bitwise op, and for an -exchange by one lane at a time (two lanes swapping into one element at once can tear it). The carrying and comparing -_x2 forms stay Unsupported. Standard library only; no GPU, no game files. -""" -import os -import random -import sys -import unittest - -HERE = os.path.dirname(os.path.abspath(__file__)) -sys.dont_write_bytecode = True -sys.path.insert(0, HERE) - -from test_global_atomics import OUT, TARGET, run, translate # noqa: E402 (also puts tools/ on sys.path) -import rdna2spirv # noqa: E402 - -M32 = 0xFFFFFFFF -MODEL = {"and": lambda m, d: m & d, "or": lambda m, d: m | d, "xor": lambda m, d: m ^ d, "swap": lambda m, d: d} -VALUES = [0, (1 << 64) - 1, 0x00000000_FFFFFFFF, 0xFFFFFFFF_00000000, 0x12345678_9ABCDEF0] - - -def atomic_x2(kind, m, d, glc=True, offset=0): - body = [f"v_mov_b32_e32 v1, {TARGET - offset:#x}", f"v_mov_b32_e32 v2, {d & M32:#x}", - f"v_mov_b32_e32 v3, {d >> 32:#x}", "v_mov_b32_e32 v6, 0xdead", "v_mov_b32_e32 v7, 0xbeef"] - off = f" offset:{offset}" if offset else "" - body.append(f"global_atomic_{kind}_x2 v[6:7], v1, v[2:3], s[0:1]{off} glc" if glc else - f"global_atomic_{kind}_x2 v1, v[2:3], s[0:1]{off}") - body += ["s_waitcnt vmcnt(0)", f"v_mov_b32_e32 v8, {OUT:#x}", "global_store_dwordx2 v8, v[6:7], s[0:1]"] - mem = run(body, {TARGET: m & M32, TARGET + 4: m >> 32}) - return (mem.get(OUT), mem.get(OUT + 4)), (mem.get(TARGET), mem.get(TARGET + 4)) - - -def split(v): - return v & M32, v >> 32 - - -class GlobalAtomicsX2(unittest.TestCase): - def test_returning_forms(self): - for kind, fn in MODEL.items(): - for m in VALUES: - for d in VALUES[::2]: - with self.subTest(op=kind, m=hex(m), d=hex(d)): - self.assertEqual(atomic_x2(kind, m, d), (split(m), split(fn(m, d)))) - - def test_without_glc_vdst_is_kept(self): - m, d = 0xF0F0F0F0_0F0F0F0F, 0xFF00FF00_00FF00FF - for kind, fn in MODEL.items(): - with self.subTest(op=kind): - self.assertEqual(atomic_x2(kind, m, d, glc=False), ((0xDEAD, 0xBEEF), split(fn(m, d)))) - - def test_offset_and_seeded(self): - self.assertEqual(atomic_x2("xor", 0x11111111_22222222, 0x0000FFFF_FFFF0000, offset=-8), - (split(0x11111111_22222222), split(0x11111111_22222222 ^ 0x0000FFFF_FFFF0000))) - rng = random.Random(0x6A72) - for _ in range(12): - kind, m, d = rng.choice(list(MODEL)), rng.getrandbits(64), rng.getrandbits(64) - with self.subTest(op=kind, m=hex(m), d=hex(d)): - self.assertEqual(atomic_x2(kind, m, d), (split(m), split(MODEL[kind](m, d)))) - - def test_carrying_and_comparing_forms_rejected(self): - for kind in ("add", "sub", "smin", "umax", "cmpswap"): - with self.subTest(op=kind): - with self.assertRaises(rdna2spirv.Unsupported): - translate(["v_mov_b32_e32 v1, 0", f"global_atomic_{kind}_x2 v[6:7], v1, v[2:3], s[0:1] glc"]) - with self.assertRaises(rdna2spirv.Unsupported): # a single VGPR is not a 64-bit vdst - translate(["v_mov_b32_e32 v1, 0", "global_atomic_or_x2 v6, v1, v[2:3], s[0:1] glc"]) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_global_mem_ext_fixture.py b/tests/semantic/test_global_mem_ext_fixture.py deleted file mode 100644 index c345f6608..000000000 --- a/tests/semantic/test_global_mem_ext_fixture.py +++ /dev/null @@ -1,77 +0,0 @@ -"""cs_global_mem_ext: the GPU test of the global/buffer atomics, 8/16-bit global stores and d16 loads, on the CPU. - -Standard library only; no GPU, no LLVM, no game files. - -runtime/test/shaders/cs_global_mem_ext.asm (header: derivations) has group 0 thread 0 seed a heap with MUBUF stores, -run global_atomic_add / cmpswap / or_x2, buffer_atomic_xor_x2, a global_store_short that crosses a dword and a -global_load_sbyte_d16_hi, and store eight words. This runs its fixture (tests/semantic/regen_fixtures.py) as one -64-thread group through spirv_mini_interp, checks the words against values computed here, and checks that -check.py and scripts/run_gpu_tests.py expect the same words on the GPU. -""" -import os -import re -import struct -import sys -import unittest - -HERE = os.path.dirname(os.path.abspath(__file__)) -if HERE not in sys.path: - sys.path.insert(0, HERE) # python -I leaves the script's folder off sys.path - -import support # noqa: E402 (support puts tools/ on sys.path, honouring LEONIDA_TOOLS_DIR) -import spirv_mini_interp as si # noqa: E402 - -ROOT = os.path.dirname(os.path.dirname(HERE)) -M32 = 0xFFFFFFFF - -# build.py's default compute header: 4 user SGPRs (the V#), workgroup id in s4, 512 bytes of LDS, 64x1x1 threads. -FSSM = bytearray(0x148) -struct.pack_into("<4I", FSSM, 0x138, 0x8088, 64, 1, 1) -FSSM = bytes(FSSM) -VSHARP = [0, 0, 0x2800, 0x31016FAC] # base 0 (the heap), 0x2800 bytes, raw bounds - - -def short_store(lo_word, hi_word, at, value): - b = bytearray(lo_word.to_bytes(4, "little") + hi_word.to_bytes(4, "little")) - b[at:at + 2] = value.to_bytes(2, "little") - return int.from_bytes(b[:4], "little"), int.from_bytes(b[4:], "little") - - -SHORT = short_store(0x44332211, 0x88776655, 3, 0xBEEF) -EXPECTED = [ - 5, # global_atomic_add glc: old value - 5 + 7, # the dword after it - 9 << 8 | 0x77, # global_atomic_cmpswap: old << 8 | new (9 == CMP) - 0x00F00000 | 0xFF000000, # global_atomic_or_x2: high dword after - 0x12345678 ^ 0xFFFF0000, # buffer_atomic_xor_x2: low dword after - SHORT[0], SHORT[1], # global_store_short across 0x2020 / 0x2024 - 0xFF80 << 16 | 0x1234, # global_load_sbyte_d16_hi of 0x80, low half kept -] - - -class GlobalMemExtFixture(unittest.TestCase): - def test_reference(self): - self.assertEqual(EXPECTED, [0x5, 0xC, 0x977, 0xFFF00000, 0xEDCB5678, 0xEF332211, 0x887766BE, 0xFF801234]) - - def test_translated_shader(self): - spv = support.translate_fixture("cs_global_mem_ext", fssm=FSSM) - mem = {} - si.run_workgroup(spv, 64, 64, inputs_for=lambda i: {"%wg_id": (0, 0, 0), "%local_id": (i, 0, 0), - "%sg_lane": i}, - push_constants=VSHARP + [0] * 32, memory=mem) - for k, want in enumerate(EXPECTED): - with self.subTest(word=k): - self.assertEqual(mem.get(4 * k), want) - - def test_gpu_runners_expect_the_same_words(self): - for rel in (("runtime", "test", "shaders", "check.py"), ("scripts", "run_gpu_tests.py")): - with open(os.path.join(ROOT, *rel), encoding="utf-8") as f: - text = f.read() - m = re.search(r'"cs_global_mem_ext"[,:]\s*(?:"40",\s*)?\[([^\]]*)\]', text) - with self.subTest(file="/".join(rel)): - self.assertIsNotNone(m) - self.assertEqual([int(v, 0) for v in m.group(1).split(",")], EXPECTED) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_global_mem_offset.py b/tests/semantic/test_global_mem_offset.py deleted file mode 100644 index eba6f34b7..000000000 --- a/tests/semantic/test_global_mem_offset.py +++ /dev/null @@ -1,327 +0,0 @@ -"""global_load / global_store instruction offsets (tools/rdna2spirv.py Gen.global_mem). - -Rule: address = base + offset, where base is the 64-bit SGPR pair plus the zero-extended 32-bit VGPR offset, or the -64-bit VGPR address with `off`, and offset is the signed 12-bit field as llvm-mc prints it: offset:-4 (field 0xffc, -encoding 0xfc,0x8f,...), range -2048..2047. llvm-mc rejects offset:0xffc, offset:2048 and offset:-2049 ("expected a -12-bit signed offset") and disassembles the field 0xffc back as offset:-4, so the signed decimal is the only spelling -the repo's disassembly (tools/shader_disasm.py) and test build (runtime/test/shaders/build.py) deliver. -Measured on an AMD Radeon RX 6800 (gfx1030) by running global_load_dword as a raw compute kernel, wave32 and wave64 -alike, with the dword at byte n holding 0x10000000+n and the pointer at 0x1000: offset 0 reads 0x10001000, -4 -0x10000ffc, -2048 0x10000800, 2044 0x100017fc, -1024 0x10000c00. The GPU test is -runtime/test/shaders/cs_global_neg_offset.asm. - -The instruction lines are hand-written. Each case runs the code Gen.global_mem emits with GlobalBodyEvaluator and -asserts the byte address accessed and the value that lands in (or is stored from) the VGPRs. -""" -import os -import sys -import unittest - -HERE = os.path.dirname(os.path.abspath(__file__)) -ROOT = os.path.dirname(os.path.dirname(HERE)) -TOOLS_DIR = os.environ.get("LEONIDA_TOOLS_DIR") or os.path.join(ROOT, "tools") - -sys.dont_write_bytecode = True -if TOOLS_DIR not in sys.path: - sys.path.insert(0, TOOLS_DIR) - -import rdna2spirv # noqa: E402 -from shader_ir import parse_line # noqa: E402 - -MASK32 = 0xFFFFFFFF -MASK64 = 0xFFFFFFFFFFFFFFFF - - -class GlobalBodyEvaluator: - """Runs the code Gen.global_mem emits against concrete registers and a dword memory, one active lane. - - spirv_mini_interp refuses 64-bit integers and PhysicalStorageBuffer by design, so this knows only the - instructions global_mem uses (64-bit address arithmetic, the active-lane selection, OpPhi, PSB loads and stores, - the sub-dword extract) and raises on anything else, so a change in the emitted code is never approximated. - The heap base (push constant dwords 32..33) is 0 unless given, which makes every address an Xbox VA. - """ - - def __init__(self, gen, sgpr, vgpr, memory, heap_base=0, active=True): - self.consts = {name: value for value, name in gen.consts.items()} - self.regs = {"%sgpr": dict(sgpr), "%vgpr": dict(vgpr)} - self.memory = dict(memory) - self.heap_base = heap_base - self.active = active - self.ids = {} - self.reads, self.writes = [], [] # byte addresses of PhysicalStorageBuffer dword accesses, in order - self.label, self.prev, self.skip_to = "%entry", None, None - for line in gen.body: - self._step(line.split()) - - def _value(self, name): - if name == "%heap_base": # built once in the entry block, outside the body run here - return self.heap_base - if name == "%c64_32": - return 32 - if name in self.ids: - return self.ids[name] - if name in self.consts: - return self.consts[name] - raise AssertionError(f"unknown id {name}") - - def _step(self, w): - if len(w) == 3 and w[1] == "=" and w[2] == "OpLabel": - if self.skip_to is not None and w[0] != self.skip_to: - return - self.skip_to, self.prev, self.label = None, self.label, w[0] - return - if self.skip_to is not None: - return - if w[0] == "OpSelectionMerge": - return - if w[0] == "OpBranch": - self.skip_to = w[1] - return - if w[0] == "OpBranchConditional": - self.skip_to = w[2] if self._value(w[1]) else w[3] - return - if w[0] == "OpStore": - kind, where = self._value(w[1]) - value = self._value(w[2]) & MASK32 - if kind == "mem" and w[3:] == ["Aligned", "4"]: - self.writes.append(where) - self.memory[where] = value - elif kind in ("%sgpr", "%vgpr") and len(w) == 3: - self.regs[kind][where] = value - else: - raise AssertionError("unmodelled store: " + " ".join(w)) - return - if len(w) < 4 or w[1] != "=": - raise AssertionError("unmodelled line: " + " ".join(w)) - result, op, ty, args = w[0], w[2], w[3], w[4:] - if op == "OpAccessChain" and ty == "%_ptr_Function_uint" and args[0] in ("%sgpr", "%vgpr"): - value = (args[0], self._value(args[1])) - elif op == "OpAccessChain" and ty == "%_ptr_PSB_uint": - kind, address = self._value(args[0]) - if kind != "arr": - raise AssertionError(f"PSB access chain on {kind}") - value = ("mem", (address + 4 * self._value(args[1])) & MASK64) - elif op == "OpConvertUToPtr" and ty == "%_ptr_PSB_arr": - value = ("arr", self._value(args[0])) - elif op == "OpConvertUToPtr" and ty == "%_ptr_PSB_uint": - value = ("mem", self._value(args[0])) - elif op == "OpLoad" and ty == "%bool" and args == ["%active"]: - value = self.active - elif op == "OpLoad" and ty == "%uint": - kind, where = self._value(args[0]) - if kind in ("%sgpr", "%vgpr") and len(args) == 1: - value = self.regs[kind].get(where, 0) & MASK32 - elif kind == "mem" and args[1:] == ["Aligned", "4"]: - if where % 4: - raise AssertionError(f"unaligned dword load at {where:#x}") - self.reads.append(where) - value = self.memory.get(where, 0) - else: - raise AssertionError("unmodelled load: " + " ".join(w)) - elif op == "OpBitcast" and ty in ("%int", "%uint"): - value = self._value(args[0]) & MASK32 - elif op == "OpBitcast" and ty == "%ulong": - value = self._value(args[0]) & MASK64 - elif op == "OpSConvert" and ty == "%long": - v = self._value(args[0]) & MASK32 - value = (v - (1 << 32) if v & 0x80000000 else v) & MASK64 - elif op == "OpUConvert" and ty == "%ulong": - value = self._value(args[0]) & MASK32 - elif op == "OpUConvert" and ty == "%uint": - value = self._value(args[0]) & MASK32 - elif op == "OpShiftLeftLogical" and ty == "%ulong": - value = (self._value(args[0]) << self._value(args[1])) & MASK64 - elif op == "OpShiftLeftLogical" and ty == "%uint": - value = (self._value(args[0]) << self._value(args[1])) & MASK32 - elif op == "OpShiftRightLogical" and ty == "%uint": - value = (self._value(args[0]) >> self._value(args[1])) & MASK32 - elif op == "OpBitwiseOr" and ty == "%ulong": - value = self._value(args[0]) | self._value(args[1]) - elif op == "OpBitwiseOr" and ty == "%uint": - value = (self._value(args[0]) | self._value(args[1])) & MASK32 - elif op == "OpIEqual" and ty == "%bool": - value = self._value(args[0]) == self._value(args[1]) - elif op == "OpBitwiseAnd" and ty == "%uint": - value = self._value(args[0]) & self._value(args[1]) - elif op == "OpIAdd" and ty == "%ulong": - value = (self._value(args[0]) + self._value(args[1])) & MASK64 - elif op == "OpISub" and ty == "%ulong": - value = (self._value(args[0]) - self._value(args[1])) & MASK64 - elif op in ("OpBitFieldUExtract", "OpBitFieldSExtract") and ty == "%uint": - v, off, count = (self._value(x) for x in args) - if off + count > 32: - raise AssertionError(f"bit-field extract beyond 32 bits: off={off}, count={count}") - value = (v >> off) & ((1 << count) - 1) - if op == "OpBitFieldSExtract" and value >> (count - 1): - value -= 1 << count - value &= MASK32 - elif op == "OpPhi" and ty == "%uint": - pairs = dict(zip(args[1::2], args[0::2])) - value = self._value(pairs[self.prev]) - else: - raise AssertionError("unmodelled instruction: " + " ".join(w)) - self.ids[result] = value - - -def tagged(address): - """The seed word at a dword address: its own offset, tagged, so a wrong address shows in the value.""" - return 0x5EED0000 | (address & 0xFFFF) - - -class GlobalOffsetTests(unittest.TestCase): - """Both addressing modes, every width global_mem handles, offsets -4, -2048, 2047 and 0.""" - - # saddr: s[20:21] = 0x3_00004000, v1 = 0x800 (zero-extended) -> base 0x3_00004800. - # off: v[4:5] = 0x3_00004800 -> the same base. - BASE = 0x0000000300004800 - SGPR = {20: 0x00004000, 21: 0x00000003} - VGPR = {1: 0x00000800, 4: 0x00004800, 5: 0x00000003, 6: 0xA1B2C3D4, 7: 0x0BADC0DE} - - def run_line(self, line, memory=None, active=True, heap_base=0): - ins = parse_line(line) - g = rdna2spirv.Gen("cs") - g.global_mem(ins["op"], ins["args"], ins["mods"]) - if memory is None: - memory = {a: tagged(a) for a in range(self.BASE - 0x1010, self.BASE + 0x1010, 4)} - ev = GlobalBodyEvaluator(g, self.SGPR, {**self.VGPR, 10: 0xEEEEEEEE, 11: 0xEEEEEEEE}, memory, - heap_base=heap_base, active=active) - return ev, g - - def test_dword_load_both_modes(self): - for mode in ("v1, s[20:21]", "v[4:5], off"): - for off in (-4, -2048, 2044, 0): - line = f"global_load_dword v10, {mode}" + (f" offset:{off}" if off else "") - with self.subTest(line=line): - ev, _ = self.run_line(line) - want = self.BASE + off - self.assertEqual(ev.reads, [want]) - self.assertEqual(ev.regs["%vgpr"][10], tagged(want)) - - def test_multi_dword_load(self): - for mode in ("v1, s[20:21]", "v[4:5], off"): - for off in (-4, -2048, 2040, 0): - line = f"global_load_dwordx2 v[10:11], {mode}" + (f" offset:{off}" if off else "") - with self.subTest(line=line): - ev, _ = self.run_line(line) - want = self.BASE + off - self.assertEqual(ev.reads, [want, want + 4]) - self.assertEqual([ev.regs["%vgpr"][10], ev.regs["%vgpr"][11]], [tagged(want), tagged(want + 4)]) - ev, _ = self.run_line("global_load_dwordx4 v[10:13], v[4:5], off offset:-2048") - self.assertEqual(ev.reads, [self.BASE - 2048 + 4 * i for i in range(4)]) - - def test_sub_dword_loads(self): - # Byte-distinct seeds: the dword at address a holds bytes (a+0..a+3) & 0xff, then the top byte gets 0x80 - # so sign extension shows. The containing dword is read and the byte/short at (address & 3) extracted. - def word(a): - return ((a & 0xFF) | ((a + 1) & 0xFF) << 8 | ((a + 2) & 0xFF) << 16 | (((a + 3) & 0x7F) | 0x80) << 24) - mem = {a: word(a) for a in range(self.BASE - 0x1010, self.BASE + 0x1010, 4)} - for mode in ("v1, s[20:21]", "v[4:5], off"): - for op, bits, signed in (("global_load_ubyte", 8, False), ("global_load_sbyte", 8, True), - ("global_load_ushort", 16, False), ("global_load_sshort", 16, True)): - offs = (-4, -2048, 2047, 0, -1, -2045) if bits == 8 else (-4, -2048, 2046, 0, -2) - for off in offs: - line = f"{op} v10, {mode}" + (f" offset:{off}" if off else "") - with self.subTest(line=line): - ev, _ = self.run_line(line, memory=mem) - addr = self.BASE + off - self.assertEqual(ev.reads, [addr & ~3]) - v = (mem[addr & ~3] >> (8 * (addr & 3))) & ((1 << bits) - 1) - if signed and v >> (bits - 1): - v = (v - (1 << bits)) & MASK32 - self.assertEqual(ev.regs["%vgpr"][10], v) - # One spelled-out case: sshort at offset -2046 from 0x...4800 is bytes 0x4002..0x4003 of the dword at 0x4000. - ev, _ = self.run_line("global_load_sshort v10, v[4:5], off offset:-2046", memory={self.BASE - 2048: 0x8BAD1800}) - self.assertEqual(ev.regs["%vgpr"][10], 0xFFFF8BAD) - - def test_short_loads_crossing_dword_boundary(self): - # At (addr & 3) == 3, 16-bit global loads read byte 3 of (addr & ~3) and byte 0 of (addr & ~3) + 4. - for mode in ("v1, s[20:21]", "v[4:5], off"): - for op, signed in (("global_load_ushort", False), ("global_load_sshort", True)): - for off, hi_byte, want_hi in ((-1, 0x3F, 0x3F), (-2045, 0x80, 0x80), (2047, 0xFE, 0xFE)): - addr = self.BASE + off - lo_dw, hi_dw = addr & ~3, (addr & ~3) + 4 - mem = {lo_dw: 0x99000000, hi_dw: 0xAABBCC00 | hi_byte} - expected = (want_hi << 8) | 0x99 - if signed and (expected & 0x8000): - expected |= 0xFFFF0000 - line = f"{op} v10, {mode} offset:{off}" - with self.subTest(line=line, hi_byte=hex(hi_byte)): - ev, _ = self.run_line(line, memory=mem) - self.assertEqual(ev.reads, [lo_dw, hi_dw]) - self.assertEqual(ev.regs["%vgpr"][10], expected) - ev_off, _ = self.run_line(line, memory=mem, active=False) - self.assertEqual((ev_off.reads, ev_off.regs["%vgpr"][10]), ([], 0xEEEEEEEE)) - - def test_store_both_modes(self): - for mode in ("v1, v6, s[20:21]", "v[4:5], v6, off"): - for off in (-4, -2048, 2044, 0): - line = f"global_store_dword {mode}" + (f" offset:{off}" if off else "") - with self.subTest(line=line): - ev, _ = self.run_line(line, memory={}) - self.assertEqual(ev.writes, [self.BASE + off]) - self.assertEqual(ev.memory, {self.BASE + off: 0xA1B2C3D4}) - ev, _ = self.run_line("global_store_dwordx2 v[4:5], v[6:7], off offset:-2048", memory={}) - self.assertEqual(ev.memory, {self.BASE - 2048: 0xA1B2C3D4, self.BASE - 2044: 0x0BADC0DE}) - - def test_offset_2047_on_dword_forms(self): - # A base one past a dword boundary makes base + 2047 dword-aligned, so the largest offset is checked on the - # dword, multi-dword and store forms without depending on unaligned behaviour (which was not measured). - self.SGPR = {20: 0x00004000, 21: 0x00000003} - self.VGPR = {1: 0x00000801, 4: 0x00004801, 5: 0x00000003, 6: 0xA1B2C3D4, 7: 0x0BADC0DE} - want = 0x0000000300004801 + 2047 - for mode, smode in (("v1, s[20:21]", "v1, v[6:7], s[20:21]"), ("v[4:5], off", "v[4:5], v[6:7], off")): - with self.subTest(mode=mode): - ev, _ = self.run_line(f"global_load_dword v10, {mode} offset:2047") - self.assertEqual((ev.reads, ev.regs["%vgpr"][10]), ([want], tagged(want))) - ev, _ = self.run_line(f"global_load_dwordx2 v[10:11], {mode} offset:2047") - self.assertEqual(ev.reads, [want, want + 4]) - ev, _ = self.run_line(f"global_store_dwordx2 {smode} offset:2047", memory={}) - self.assertEqual(ev.memory, {want: 0xA1B2C3D4, want + 4: 0x0BADC0DE}) - ev, _ = self.run_line(f"global_store_dword {smode.replace('v[6:7]', 'v6')} offset:2047", memory={}) - self.assertEqual(ev.memory, {want: 0xA1B2C3D4}) - - def test_hex_spelling_of_a_signed_offset(self): - # Hand-written listings may spell the same signed value in hex; llvm-mc accepts and reprints it as decimal. - for spelled, off in (("0x7ff", 2047), ("-0x4", -4), ("-0x800", -2048)): - with self.subTest(spelled=spelled): - ev, _ = self.run_line(f"global_load_ubyte v10, v[4:5], off offset:{spelled}") - self.assertEqual(ev.reads, [(self.BASE + off) & ~3]) - - def test_inactive_lane_neither_loads_nor_stores(self): - ev, _ = self.run_line("global_load_dword v10, v[4:5], off offset:-4", active=False) - self.assertEqual((ev.reads, ev.regs["%vgpr"][10]), ([], 0xEEEEEEEE)) - ev, _ = self.run_line("global_store_dword v[4:5], v6, off offset:-4", memory={}, active=False) - self.assertEqual((ev.writes, ev.memory), ([], {})) - - def test_heap_base_is_added_once(self): - ev, _ = self.run_line("global_load_dword v10, v[4:5], off offset:-4", memory={}, heap_base=0x0000007F00000000) - self.assertEqual(ev.reads, [0x0000007F00000000 + self.BASE - 4]) - - def test_carry_and_borrow_across_the_low_dword(self): - # A negative offset below a 4 GiB boundary borrows from the high dword (the add is 64-bit). - self.SGPR = {20: 0x00000000, 21: 0x00000003} - self.VGPR = {1: 0x00000000} - ev, _ = self.run_line("global_load_dword v10, v1, s[20:21] offset:-4", memory={}) - self.assertEqual(ev.reads, [0x00000002FFFFFFFC]) - self.VGPR = {4: 0xFFFFFFFC, 5: 0x00000003} - ev, _ = self.run_line("global_load_dword v10, v[4:5], off offset:8", memory={}) - self.assertEqual(ev.reads, [0x0000000400000004]) - - def test_raw_unsigned_field_is_the_same_offset(self): - # llvm-mc never prints the field unsigned, but a tool that did (0xffc for -4) means the same address. - for spelled, off in (("0xffc", -4), ("4092", -4), ("0x800", -2048), ("2048", -2048), ("0xff8", -8)): - with self.subTest(offset=spelled): - ev, _ = self.run_line(f"global_load_dword v10, v[4:5], off offset:{spelled}", memory={}) - self.assertEqual(ev.reads, [self.BASE + off]) - - def test_offsets_outside_12_bits_raise(self): - for spelled in ("4096", "-2049", "0x1000", "zz"): - line = f"global_load_dword v10, v[4:5], off offset:{spelled}" - with self.subTest(line=line): - ins = parse_line(line) - with self.assertRaises(rdna2spirv.Unsupported): - rdna2spirv.Gen("cs").global_mem(ins["op"], ins["args"], ins["mods"]) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_global_mem_x3.py b/tests/semantic/test_global_mem_x3.py deleted file mode 100644 index 1dad029e1..000000000 --- a/tests/semantic/test_global_mem_x3.py +++ /dev/null @@ -1,486 +0,0 @@ -"""Semantic, validation, and interpreter tests for global_load_dwordx3 and global_store_dwordx3. - -RDNA2 ISA (FLAT/GLOBAL): - global_load_dwordx3 v[D:D+2], vaddr, saddr|off [offset:N] - Loads three consecutive 32-bit dwords starting at byte address A into v[D..D+2] (low address first) - and leaves v[D+3] untouched. Inactive lanes issue no loads and preserve v[D..D+2]. - global_store_dwordx3 vaddr, v[D:D+2], saddr|off [offset:N] - Stores three consecutive 32-bit dwords from v[D..D+2] starting at byte address A and leaves - adjacent dwords untouched. Inactive lanes issue no stores. - Address A = ((saddr: 64-bit SGPR pair + zext32(vaddr)) | (off: 64-bit VGPR pair)) + sext12(offset), - translated to host memory by adding push-constant heap_base (dwords 32..33). - -Covers both addressing modes, signed 12-bit offsets (-2048..2047 and hex spellings), 64-bit carry/borrow -across 4 GiB boundaries, heap_base translation, vaddr/vdst and vaddr/vdata register aliasing, strict 3-dword -boundaries, partial-EXEC wave32 and wave64 execution, fragment and compute stages, helper metadata -(read_before_write_vgprs / vgpr_dest_registers), rejected forms, a negative control, and spirv-val -validation (native wave32, native wave64, and --wave64-emulate). Standard library only; no game files. -""" -import os -import shutil -import struct -import subprocess -import sys -import unittest - -HERE = os.path.dirname(os.path.abspath(__file__)) -sys.dont_write_bytecode = True -if HERE not in sys.path: - sys.path.insert(0, HERE) - -import support # noqa: E402 (adds LEONIDA_TOOLS_DIR / tools to sys.path) -import rdna2spirv # noqa: E402 -import shader_ir # noqa: E402 -import spirv_mini_interp as si # noqa: E402 - -M32 = 0xFFFFFFFF -SPIRV_AS = shutil.which("spirv-as") -SPIRV_VAL = shutil.which("spirv-val") - -FSSM_CS_W32 = bytearray(0x148) -struct.pack_into("<4I", FSSM_CS_W32, 0x138, 0x88, 32, 1, 1) -FSSM_CS_W32 = bytes(FSSM_CS_W32) - -FSSM_CS_W64 = bytearray(0x148) -struct.pack_into("<4I", FSSM_CS_W64, 0x138, 0x00, 64, 1, 1) -FSSM_CS_W64 = bytes(FSSM_CS_W64) - -BASE = 0x00000003_00004800 -SENTINEL = 0xEEEEEEEE -GUARD_LO = 0xA5A50001 -GUARD_HI = 0xA5A50002 -V13_INIT = 0xCAFEBABE - - -def tagged(addr): - """Distinct 32-bit word derived from the full 64-bit byte address.""" - return (0x50000000 ^ ((addr >> 20) & 0x0FFF0000) ^ (addr & 0xFFFF)) & M32 - - -def seed_window(center, lo_off=-0x1010, hi_off=0x1010): - return {a: tagged(a) for a in range(center + lo_off, center + hi_off, 4)} - - -def translate_cs(lines, *, wave64=False, emulate=False): - fssm = FSSM_CS_W64 if wave64 else FSSM_CS_W32 - prev = rdna2spirv.WAVE64_EMULATE - rdna2spirv.WAVE64_EMULATE = emulate - try: - return support.translate_lines("cs_global_x3", [*lines, "s_endpgm"], fssm=fssm) - finally: - rdna2spirv.WAVE64_EMULATE = prev - - -def translate_ps(lines): - return support.translate_lines( - "ps_global_x3", - [*lines, "exp mrt0 v10, v11, v12, v13 done vm", "s_endpgm"], - ) - - -def run_cs(lines, memory, *, nlanes=1, wave64=False, push_constants=None): - spv = translate_cs(lines, wave64=wave64) - mem = dict(memory) - pc = [0] * 36 if push_constants is None else list(push_constants) - wsize = 64 if wave64 else 32 - si.run_workgroup( - spv, - nlanes, - wsize, - inputs_for=lambda i: {"%wg_id": (0, 0, 0), "%local_id": (i, 0, 0), "%sg_lane": i}, - push_constants=pc, - memory=mem, - ) - return mem - - -def run_ps(lines, memory, *, push_constants=None): - spv = translate_ps(lines) - mem = dict(memory) - pc = [0] * 36 if push_constants is None else list(push_constants) - words = support.mrt0_words(spv, push_constants=pc, memory=mem) - return words, mem - - -def setup_base_regs(base): - """Initialize s[20:21] + v1 and v[4:5] to `base` (split 0x800 + (base - 0x800) for saddr).""" - saddr = base - 0x800 - return [ - f"s_mov_b32 s20, {saddr & M32:#x}", - f"s_mov_b32 s21, {(saddr >> 32) & M32:#x}", - "v_mov_b32_e32 v1, 0x800", - f"v_mov_b32_e32 v4, {base & M32:#x}", - f"v_mov_b32_e32 v5, {(base >> 32) & M32:#x}", - ] - - -class GlobalLoadDwordx3Tests(unittest.TestCase): - def test_load_both_modes_offsets_and_vgpr_boundary(self): - mem = seed_window(BASE) - for mode in ("v1, s[20:21]", "v[4:5], off"): - for spelled, off in (("-4", -4), ("-2048", -2048), ("2044", 2044), ("0", 0), ("-0x4", -4), ("0x7fc", 2044)): - mod = f" offset:{spelled}" if spelled != "0" else "" - lines = [ - *setup_base_regs(BASE), - "v_mov_b32_e32 v10, 0x11111111", - "v_mov_b32_e32 v11, 0x22222222", - "v_mov_b32_e32 v12, 0x33333333", - f"v_mov_b32_e32 v13, {V13_INIT:#x}", - f"global_load_dwordx3 v[10:12], {mode}{mod}", - "s_waitcnt vmcnt(0)", - ] - want = BASE + off - expected = [tagged(want), tagged(want + 4), tagged(want + 8), V13_INIT] - with self.subTest(mode=mode, spelled=spelled): - words, _ = run_ps(lines, mem) - self.assertEqual(words, expected) - - def test_load_offset_2047_aligned(self): - # Base one past a dword boundary makes (base + 2047) dword-aligned, exercising the maximum positive 12-bit offset. - base = BASE + 1 - want = base + 2047 - mem = {want + 4 * i: tagged(want + 4 * i) for i in range(4)} - for mode in ("v1, s[20:21]", "v[4:5], off"): - lines = [ - *setup_base_regs(base), - f"v_mov_b32_e32 v13, {V13_INIT:#x}", - f"global_load_dwordx3 v[10:12], {mode} offset:2047", - "s_waitcnt vmcnt(0)", - ] - with self.subTest(mode=mode): - words, _ = run_ps(lines, mem) - self.assertEqual(words, [tagged(want), tagged(want + 4), tagged(want + 8), V13_INIT]) - - def test_load_vaddr_aliasing_vdst(self): - mem = seed_window(BASE) - # `off` mode: 64-bit vaddr v[4:5] overlaps vdst v[4:6]. - want_off = BASE - 4 - words_off, _ = run_ps([ - *setup_base_regs(BASE), - f"v_mov_b32_e32 v7, {V13_INIT:#x}", - "global_load_dwordx3 v[4:6], v[4:5], off offset:-4", - "s_waitcnt vmcnt(0)", - "v_mov_b32_e32 v10, v4", - "v_mov_b32_e32 v11, v5", - "v_mov_b32_e32 v12, v6", - "v_mov_b32_e32 v13, v7", - ], mem) - self.assertEqual(words_off, [tagged(want_off), tagged(want_off + 4), tagged(want_off + 8), V13_INIT]) - - # `saddr` mode: 32-bit vaddr v1 overlaps vdst v[1:3]. - want_saddr = BASE + 8 - words_saddr, _ = run_ps([ - *setup_base_regs(BASE), - f"v_mov_b32_e32 v4, {V13_INIT:#x}", - "global_load_dwordx3 v[1:3], v1, s[20:21] offset:8", - "s_waitcnt vmcnt(0)", - "v_mov_b32_e32 v10, v1", - "v_mov_b32_e32 v11, v2", - "v_mov_b32_e32 v12, v3", - "v_mov_b32_e32 v13, v4", - ], mem) - self.assertEqual(words_saddr, [tagged(want_saddr), tagged(want_saddr + 4), tagged(want_saddr + 8), V13_INIT]) - - def test_load_64bit_carry_borrow_and_heap_base(self): - heap_base = 0x00000042_00000000 - pc = [0] * 32 + [heap_base & M32, (heap_base >> 32) & M32, 0, 0] - - # Borrow across 4 GiB boundary: s[20:21] = 0x3_00000000, v1 = 0, offset:-4 -> 0x2_FFFFFFFC. - va_borrow = 0x00000002_FFFFFFFC - mem_borrow = {heap_base + va_borrow + 4 * i: 0xB000 + i for i in range(3)} - words_borrow, _ = run_ps([ - "s_mov_b32 s20, 0x0", - "s_mov_b32 s21, 0x3", - "v_mov_b32_e32 v1, 0x0", - f"v_mov_b32_e32 v13, {V13_INIT:#x}", - "global_load_dwordx3 v[10:12], v1, s[20:21] offset:-4", - "s_waitcnt vmcnt(0)", - ], mem_borrow, push_constants=pc) - self.assertEqual(words_borrow, [0xB000, 0xB001, 0xB002, V13_INIT]) - - # Carry across 4 GiB boundary: v[4:5] = 0x3_FFFFFFF8, offset:8 -> 0x4_00000000. - va_carry = 0x00000004_00000000 - mem_carry = {heap_base + va_carry + 4 * i: 0xC000 + i for i in range(3)} - words_carry, _ = run_ps([ - "v_mov_b32_e32 v4, 0xfffffff8", - "v_mov_b32_e32 v5, 0x3", - f"v_mov_b32_e32 v13, {V13_INIT:#x}", - "global_load_dwordx3 v[10:12], v[4:5], off offset:8", - "s_waitcnt vmcnt(0)", - ], mem_carry, push_constants=pc) - self.assertEqual(words_carry, [0xC000, 0xC001, 0xC002, V13_INIT]) - - def test_load_inactive_lanes_keep_vdst_wave32_and_wave64(self): - for wave64, nlanes, exec_lines, active_lanes in ( - (False, 8, ["s_mov_b32 exec_lo, 0x25"], {0, 2, 5}), - (True, 64, ["s_mov_b32 exec_lo, 0x00000005", "s_mov_b32 exec_hi, 0x00000002"], {0, 2, 33}), - ): - src_base = 0x10000 - out_base = 0x20000 - mem = {} - for lane in range(nlanes): - for k in range(3): - mem[src_base + lane * 16 + 4 * k] = (0x70000000 | (lane << 8) | k) - lines = [ - f"s_mov_b32 s20, {src_base:#x}", - "s_mov_b32 s21, 0", - "v_mbcnt_lo_u32_b32 v0, -1, 0", - *(["v_mbcnt_hi_u32_b32 v0, -1, v0"] if wave64 else []), - "v_lshlrev_b32_e32 v1, 4, v0", - "v_mov_b32_e32 v10, 0xdead0000", - "v_mov_b32_e32 v11, 0xdead0001", - "v_mov_b32_e32 v12, 0xdead0002", - f"v_mov_b32_e32 v13, {V13_INIT:#x}", - *exec_lines, - "global_load_dwordx3 v[10:12], v1, s[20:21]", - "s_waitcnt vmcnt(0)", - *(["s_mov_b64 exec, -1"] if wave64 else ["s_mov_b32 exec_lo, -1"]), - f"v_add_nc_u32_e32 v4, {out_base:#x}, v1", - "v_mov_b32_e32 v5, 0", - "global_store_dwordx4 v[4:5], v[10:13], off", - ] - with self.subTest(wave64=wave64): - res = run_cs(lines, mem, nlanes=nlanes, wave64=wave64) - for lane in range(nlanes): - got = [res.get(out_base + lane * 16 + 4 * k) for k in range(4)] - if lane in active_lanes: - want = [0x70000000 | (lane << 8) | k for k in range(3)] + [V13_INIT] - else: - want = [0xDEAD0000, 0xDEAD0001, 0xDEAD0002, V13_INIT] - self.assertEqual(got, want, f"lane {lane}") - - -class GlobalStoreDwordx3Tests(unittest.TestCase): - def test_store_both_modes_offsets_and_strict_bounds(self): - payload = (0xA1B2C3D4, 0x0BADC0DE, 0x13572468, 0x99999999) - for mode in ("v1, v[6:8], s[20:21]", "v[4:5], v[6:8], off"): - for spelled, off in (("-4", -4), ("-2048", -2048), ("2044", 2044), ("0", 0), ("-0x4", -4), ("0x7fc", 2044)): - want = BASE + off - mem = { - want - 4: GUARD_LO, - want: SENTINEL, - want + 4: SENTINEL, - want + 8: SENTINEL, - want + 12: GUARD_HI, - } - mod = f" offset:{spelled}" if spelled != "0" else "" - lines = [ - *setup_base_regs(BASE), - *(f"v_mov_b32_e32 v{6 + k}, {payload[k]:#x}" for k in range(4)), - f"global_store_dwordx3 {mode}{mod}", - "v_mov_b32_e32 v10, 1", - "v_mov_b32_e32 v11, 2", - "v_mov_b32_e32 v12, 3", - "v_mov_b32_e32 v13, 4", - ] - with self.subTest(mode=mode, spelled=spelled): - _, res = run_ps(lines, mem) - self.assertEqual( - [res[want - 4], res[want], res[want + 4], res[want + 8], res[want + 12]], - [GUARD_LO, payload[0], payload[1], payload[2], GUARD_HI], - ) - - def test_store_offset_2047_aligned(self): - base = BASE + 1 - want = base + 2047 - payload = (0x11112222, 0x33334444, 0x55556666) - for mode in ("v1, v[6:8], s[20:21]", "v[4:5], v[6:8], off"): - mem = {want - 4: GUARD_LO, want + 12: GUARD_HI} - lines = [ - *setup_base_regs(base), - *(f"v_mov_b32_e32 v{6 + k}, {payload[k]:#x}" for k in range(3)), - f"global_store_dwordx3 {mode} offset:2047", - ] - with self.subTest(mode=mode): - res = run_cs(lines, mem) - self.assertEqual( - [res[want - 4], res[want], res[want + 4], res[want + 8], res[want + 12]], - [GUARD_LO, payload[0], payload[1], payload[2], GUARD_HI], - ) - - def test_store_vaddr_aliasing_vdata(self): - want = BASE + 4 - mem = {want - 4: GUARD_LO, want + 12: GUARD_HI} - res = run_cs([ - f"v_mov_b32_e32 v4, {BASE & M32:#x}", - f"v_mov_b32_e32 v5, {(BASE >> 32) & M32:#x}", - "v_mov_b32_e32 v6, 0x778899aa", - "global_store_dwordx3 v[4:5], v[4:6], off offset:4", - ], mem) - self.assertEqual( - [res[want - 4], res[want], res[want + 4], res[want + 8], res[want + 12]], - [GUARD_LO, BASE & M32, (BASE >> 32) & M32, 0x778899AA, GUARD_HI], - ) - - def test_store_64bit_carry_borrow_heap_base_and_roundtrip(self): - heap_base = 0x00000019_00000000 - pc = [0] * 32 + [heap_base & M32, (heap_base >> 32) & M32, 0, 0] - # Store at (0x4_00000000 - 4) via offset:-4, then load back at (0x3_FFFFFFF4 + 8) via offset:8. - va = 0x00000003_FFFFFFFC - mem = {heap_base + va - 4: GUARD_LO, heap_base + va + 12: GUARD_HI} - words, res = run_ps([ - "s_mov_b32 s20, 0x0", - "s_mov_b32 s21, 0x4", - "v_mov_b32_e32 v1, 0x0", - "v_mov_b32_e32 v6, 0x10203040", - "v_mov_b32_e32 v7, 0x50607080", - "v_mov_b32_e32 v8, 0x90a0b0c0", - "global_store_dwordx3 v1, v[6:8], s[20:21] offset:-4", - "s_waitcnt vmcnt(0)", - "v_mov_b32_e32 v4, 0xfffffff4", - "v_mov_b32_e32 v5, 0x3", - f"v_mov_b32_e32 v13, {V13_INIT:#x}", - "global_load_dwordx3 v[10:12], v[4:5], off offset:8", - "s_waitcnt vmcnt(0)", - ], mem, push_constants=pc) - self.assertEqual(words, [0x10203040, 0x50607080, 0x90A0B0C0, V13_INIT]) - self.assertEqual(res[heap_base + va - 4], GUARD_LO) - self.assertEqual(res[heap_base + va + 12], GUARD_HI) - - def test_store_inactive_lanes_leave_memory_untouched_wave32_and_wave64(self): - for wave64, nlanes, exec_lines, active_lanes in ( - (False, 8, ["s_mov_b32 exec_lo, 0x4a"], {1, 3, 6}), - (True, 64, ["s_mov_b32 exec_lo, 0x0000000a", "s_mov_b32 exec_hi, 0x00000010"], {1, 3, 36}), - ): - out_base = 0x30000 - mem = {} - for lane in range(nlanes): - for k in range(4): - mem[out_base + lane * 16 + 4 * k] = 0xDEAD0000 | (lane << 4) | k - lines = [ - "v_mbcnt_lo_u32_b32 v0, -1, 0", - *(["v_mbcnt_hi_u32_b32 v0, -1, v0"] if wave64 else []), - "v_lshlrev_b32_e32 v1, 4, v0", - f"s_mov_b32 s20, {out_base:#x}", - "s_mov_b32 s21, 0", - "v_add_nc_u32_e32 v6, 0x100, v0", - "v_add_nc_u32_e32 v7, 0x200, v0", - "v_add_nc_u32_e32 v8, 0x300, v0", - "v_mov_b32_e32 v9, 0x99999999", - *exec_lines, - "global_store_dwordx3 v1, v[6:8], s[20:21]", - ] - with self.subTest(wave64=wave64): - res = run_cs(lines, mem, nlanes=nlanes, wave64=wave64) - for lane in range(nlanes): - got = [res[out_base + lane * 16 + 4 * k] for k in range(4)] - if lane in active_lanes: - want = [0x100 + lane, 0x200 + lane, 0x300 + lane, 0xDEAD0000 | (lane << 4) | 3] - else: - want = [0xDEAD0000 | (lane << 4) | k for k in range(4)] - self.assertEqual(got, want, f"lane {lane}") - - -class GlobalDwordx3MetadataAndValidationTests(unittest.TestCase): - def test_read_before_write_and_dest_registers(self): - load_saddr = shader_ir.parse_line("\tglobal_load_dwordx3 v[10:12], v1, s[20:21] offset:-4") - load_off = shader_ir.parse_line("\tglobal_load_dwordx3 v[10:12], v[4:5], off") - store_saddr = shader_ir.parse_line("\tglobal_store_dwordx3 v1, v[6:8], s[20:21]") - store_off = shader_ir.parse_line("\tglobal_store_dwordx3 v[4:5], v[6:8], off") - - self.assertEqual(list(rdna2spirv.vgpr_dest_registers(load_saddr)), [10, 11, 12]) - self.assertEqual(rdna2spirv.read_before_write_vgprs([load_saddr]), {1}) - self.assertEqual(rdna2spirv.read_before_write_vgprs([load_off]), {4, 5}) - self.assertEqual(rdna2spirv.read_before_write_vgprs([store_saddr]), {1, 6, 7, 8}) - self.assertEqual(rdna2spirv.read_before_write_vgprs([store_off]), {4, 5, 6, 7, 8}) - # Loading into v[10:12] defines v10..v12, leaving v13 read-before-write when read afterwards. - read_after = [ - load_saddr, - shader_ir.parse_line("\tv_add_nc_u32_e32 v20, v10, v12"), - shader_ir.parse_line("\tv_mov_b32_e32 v21, v13"), - ] - self.assertEqual(rdna2spirv.read_before_write_vgprs(read_after), {1, 13}) - - def test_rejected_forms_raise_unsupported(self): - bad_lines = ( - "global_load_dwordx3 v[10:12], v1, s[20:21] lds", - "global_load_dwordx3 v[10:12], v1, s[20:21] tfe", - "global_load_dwordx3 v[10:12], v1, s[20:21] d16", - "global_store_dwordx3 v[4:5], v[6:8], off tfe", - "global_load_dwordx3 v[10:12], v[4:5], off offset:4096", - "global_load_dwordx3 v[10:12], v[4:5], off offset:0x1000", - "global_store_dwordx3 v[4:5], v[6:8], off offset:-2049", - "global_load_dwordx3 v[10:12], v4, off", - "global_store_dwordx3 v1, v[6:8], s20", - ) - for line in bad_lines: - with self.subTest(line=line): - with self.assertRaises(rdna2spirv.Unsupported): - translate_cs([line]) - - @unittest.skipUnless(SPIRV_AS and SPIRV_VAL, "requires spirv-as and spirv-val") - def test_spirv_val_wave32_wave64_and_emulate(self): - cs_lines = [ - "s_mov_b32 s20, 0x1000", - "s_mov_b32 s21, 0", - "v_mbcnt_lo_u32_b32 v0, -1, 0", - "v_lshlrev_b32_e32 v1, 4, v0", - "v_cmp_lt_u32_e32 vcc, v0, 3", - "s_and_saveexec_b64 s[6:7], vcc", - "global_load_dwordx3 v[10:12], v1, s[20:21] offset:-4", - "s_waitcnt vmcnt(0)", - "v_add_nc_u32_e32 v4, 0x2000, v1", - "v_mov_b32_e32 v5, 0", - "global_store_dwordx3 v[4:5], v[10:12], off offset:16", - ] - modules = ( - ("ps", translate_ps([ - *setup_base_regs(BASE), - "v_mov_b32_e32 v13, 0", - "global_load_dwordx3 v[10:12], v1, s[20:21] offset:-4", - "s_waitcnt vmcnt(0)", - "global_store_dwordx3 v[4:5], v[10:12], off offset:2044", - ])), - ("cs_w32", translate_cs(cs_lines[:2] + cs_lines[2:4] + [ - "v_cmp_lt_u32_e32 vcc_lo, v0, 3", - "s_and_saveexec_b32 s6, vcc_lo", - *cs_lines[6:], - ], wave64=False)), - ("cs_w64", translate_cs( - cs_lines[:3] + ["v_mbcnt_hi_u32_b32 v0, -1, v0"] + cs_lines[3:], - wave64=True, emulate=False, - )), - ("cs_w64_emulate", translate_cs( - cs_lines[:3] + ["v_mbcnt_hi_u32_b32 v0, -1, v0"] + cs_lines[3:], - wave64=True, emulate=True, - )), - ) - for label, spv in modules: - with self.subTest(mode=label): - assembled = subprocess.run( - [SPIRV_AS, "--target-env", "vulkan1.2", "-", "-o", "-"], - input=spv.encode("utf-8"), - capture_output=True, - ) - self.assertEqual(assembled.returncode, 0, assembled.stderr.decode("utf-8", "replace")) - validated = subprocess.run( - [SPIRV_VAL, "--target-env", "vulkan1.2", "-"], - input=assembled.stdout, - capture_output=True, - ) - self.assertEqual(validated.returncode, 0, validated.stderr.decode("utf-8", "replace")) - - def test_negative_control_truncating_width_fails(self): - mem = seed_window(BASE) - # Translating x2 instead of x3 cannot populate the third dword (v12 stays at its pre-seeded sentinel). - words_load, _ = run_ps([ - *setup_base_regs(BASE), - "v_mov_b32_e32 v12, 0xdeadbeef", - f"v_mov_b32_e32 v13, {V13_INIT:#x}", - "global_load_dwordx2 v[10:11], v1, s[20:21]", - "s_waitcnt vmcnt(0)", - ], mem) - self.assertNotEqual(words_load[:3], [tagged(BASE), tagged(BASE + 4), tagged(BASE + 8)]) - - _, mem_store = run_ps([ - *setup_base_regs(BASE), - "v_mov_b32_e32 v6, 0x11", - "v_mov_b32_e32 v7, 0x22", - "v_mov_b32_e32 v8, 0x33", - "global_store_dwordx2 v[4:5], v[6:7], off", - ], {BASE: SENTINEL, BASE + 4: SENTINEL, BASE + 8: SENTINEL}) - self.assertNotEqual(mem_store[BASE + 8], 0x33) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_global_sub_dword.py b/tests/semantic/test_global_sub_dword.py deleted file mode 100644 index 9971301fd..000000000 --- a/tests/semantic/test_global_sub_dword.py +++ /dev/null @@ -1,496 +0,0 @@ -"""Semantic tests for RDNA2 8/16-bit global sub-dword memory operations (loads and stores). - -Covers AMD RDNA2 / GFX10 sub-dword memory instructions: - - global_load_ubyte: 8-bit unsigned load, zero-extended to 32 bits - - global_load_sbyte: 8-bit signed load, sign-extended to 32 bits - - global_load_ushort: 16-bit unsigned load, zero-extended to 32 bits - - global_load_sshort: 16-bit signed load, sign-extended to 32 bits - - global_store_byte: 8-bit store from VGPR low byte into memory (preserving adjacent bytes) - - global_store_short: 16-bit store from VGPR low 16 bits into memory (preserving adjacent bytes) - - d16 variants: global_load_{u,s}byte_d16[_hi], global_load_short_d16[_hi], - global_store_{byte,short}_d16_hi - -Executes compiled SPIR-V shaders through spirv_mini_interp on CPU and validates against -a deterministic reference execution oracle. Standard library only; no GPU, no game files. -""" -from __future__ import annotations - -import os -import shutil -import struct -import subprocess -import sys -import tempfile -import unittest -import warnings - -HERE = os.path.dirname(os.path.abspath(__file__)) -ROOT = os.path.dirname(os.path.dirname(HERE)) -sys.dont_write_bytecode = True -sys.path.insert(0, os.environ.get("LEONIDA_TOOLS_DIR") or os.path.join(ROOT, "tools")) -sys.path.insert(0, HERE) - -import rdna2spirv # noqa: E402 -import spirv_asm # noqa: E402 -import spirv_mini_interp as si # noqa: E402 - -M32 = 0xFFFFFFFF -M64 = 0xFFFFFFFFFFFFFFFF -STUB_DXBC = b"DXBC" + bytes(24) + struct.pack(" bytes: - fssm = bytearray(0x148) - struct.pack_into("<4I", fssm, 0x138, 0x88, threads, 1, 1) - return bytes(fssm) - - -FSSM = make_fssm(32) - -BASE, OUT = 0x2000, 0x3000 -SEED = [0x44332211, 0x88776655, 0xCCBBAA99] - - -def parse_offset_modifier(offset_mod: int | str) -> int: - """Parse signed 12-bit offset modifier (-2048..2047).""" - if isinstance(offset_mod, str): - val = int(offset_mod, 0) - else: - val = int(offset_mod) - if 0x800 <= val <= 0xFFF: - val -= 0x1000 - if not -0x800 <= val <= 0x7FF: - raise ValueError(f"Offset {val} out of 12-bit signed range [-2048, 2047]") - return val - - -def compute_global_effective_address(base: int, voffset: int = 0, offset_mod: int | str = 0) -> int: - """Compute 64-bit effective address for global memory instruction.""" - imm = parse_offset_modifier(offset_mod) - return (base + (voffset & M32) + imm) & M64 - - -class GlobalSubDwordMemoryBank: - """Deterministic simulated memory bank for global sub-dword byte-accurate operations.""" - - def __init__(self, seed_dwords: dict[int, int] | None = None): - self._mem: dict[int, int] = {} - if seed_dwords: - for addr, dw in seed_dwords.items(): - self.write_dword(addr, dw) - - def read_byte(self, byte_addr: int) -> int: - dw_addr = (byte_addr & ~3) & M64 - shift = (byte_addr & 3) * 8 - dw = self._mem.get(dw_addr, 0) - return (dw >> shift) & 0xFF - - def write_byte(self, byte_addr: int, val: int) -> None: - dw_addr = (byte_addr & ~3) & M64 - shift = (byte_addr & 3) * 8 - mask = ~(0xFF << shift) & M32 - dw = self._mem.get(dw_addr, 0) & mask - new_dw = dw | ((val & 0xFF) << shift) - self._mem[dw_addr] = new_dw & M32 - - def read_short(self, byte_addr: int) -> int: - b0 = self.read_byte(byte_addr) - b1 = self.read_byte((byte_addr + 1) & M64) - return (b1 << 8) | b0 - - def write_short(self, byte_addr: int, val: int) -> None: - self.write_byte(byte_addr, val & 0xFF) - self.write_byte((byte_addr + 1) & M64, (val >> 8) & 0xFF) - - def read_dword(self, byte_addr: int) -> int: - dw_addr = (byte_addr & ~3) & M64 - if (byte_addr & 3) == 0: - return self._mem.get(dw_addr, 0) - b0 = self.read_byte(byte_addr) - b1 = self.read_byte((byte_addr + 1) & M64) - b2 = self.read_byte((byte_addr + 2) & M64) - b3 = self.read_byte((byte_addr + 3) & M64) - return (b3 << 24) | (b2 << 16) | (b1 << 8) | b0 - - def write_dword(self, byte_addr: int, val: int) -> None: - if (byte_addr & 3) == 0: - self._mem[(byte_addr & ~3) & M64] = val & M32 - else: - self.write_byte(byte_addr, val & 0xFF) - self.write_byte((byte_addr + 1) & M64, (val >> 8) & 0xFF) - self.write_byte((byte_addr + 2) & M64, (val >> 16) & 0xFF) - self.write_byte((byte_addr + 3) & M64, (val >> 24) & 0xFF) - - def snapshot(self) -> dict[int, int]: - return dict(self._mem) - - -class GlobalSubDwordReferenceOracle: - """Reference behavioral oracle for RDNA2 global sub-dword memory instructions.""" - - def __init__(self, memory: GlobalSubDwordMemoryBank): - self.memory = memory - - def execute_load(self, op: str, base: int, voffset: int = 0, offset_mod: int | str = 0, - old_dst: int = 0, active: bool = True) -> int: - if not active: - return old_dst & M32 - ea = compute_global_effective_address(base, voffset, offset_mod) - if op == "global_load_ubyte": - return self.memory.read_byte(ea) - elif op == "global_load_sbyte": - b = self.memory.read_byte(ea) - return (b if b < 0x80 else (b | 0xFFFFFF00)) & M32 - elif op == "global_load_ushort": - return self.memory.read_short(ea) - elif op == "global_load_sshort": - s = self.memory.read_short(ea) - return (s if s < 0x8000 else (s | 0xFFFF0000)) & M32 - elif op == "global_load_ubyte_d16": - b = self.memory.read_byte(ea) - return ((old_dst & 0xFFFF0000) | b) & M32 - elif op == "global_load_ubyte_d16_hi": - b = self.memory.read_byte(ea) - return ((old_dst & 0x0000FFFF) | (b << 16)) & M32 - elif op == "global_load_sbyte_d16": - b = self.memory.read_byte(ea) - s = b if b < 0x80 else (b | 0xFF00) - return ((old_dst & 0xFFFF0000) | (s & 0xFFFF)) & M32 - elif op == "global_load_sbyte_d16_hi": - b = self.memory.read_byte(ea) - s = b if b < 0x80 else (b | 0xFF00) - return ((old_dst & 0x0000FFFF) | ((s & 0xFFFF) << 16)) & M32 - elif op == "global_load_short_d16": - s = self.memory.read_short(ea) - return ((old_dst & 0xFFFF0000) | s) & M32 - elif op == "global_load_short_d16_hi": - s = self.memory.read_short(ea) - return ((old_dst & 0x0000FFFF) | (s << 16)) & M32 - else: - raise ValueError(f"Unsupported load op: {op}") - - def execute_store(self, op: str, data: int, base: int, voffset: int = 0, - offset_mod: int | str = 0, active: bool = True) -> None: - if not active: - return - ea = compute_global_effective_address(base, voffset, offset_mod) - if op == "global_store_byte": - self.memory.write_byte(ea, data & 0xFF) - elif op == "global_store_byte_d16_hi": - self.memory.write_byte(ea, (data >> 16) & 0xFF) - elif op == "global_store_short": - self.memory.write_short(ea, data & 0xFFFF) - elif op == "global_store_short_d16_hi": - self.memory.write_short(ea, (data >> 16) & 0xFFFF) - else: - raise ValueError(f"Unsupported store op: {op}") - - -def translate(body: list[str], threads: int = 32, emulate: bool = False) -> str: - with tempfile.TemporaryDirectory() as tmp: - for d in ("disasm", "fssm"): - os.mkdir(os.path.join(tmp, d)) - with open(os.path.join(tmp, "cs_gsub.dxbc"), "wb") as f: - f.write(STUB_DXBC) - with open(os.path.join(tmp, "fssm", "cs_gsub.fssm"), "wb") as f: - f.write(make_fssm(threads=threads)) - src = os.path.join(tmp, "disasm", "cs_gsub.s") - with open(src, "w", encoding="utf-8", newline="\n") as f: - f.write("; cs_gsub\n" + "".join(f"\t{ln}\n" for ln in body) + "\ts_endpgm\n") - prev = rdna2spirv.WAVE64_EMULATE - rdna2spirv.WAVE64_EMULATE = emulate - try: - with warnings.catch_warnings(): - warnings.simplefilter("ignore", ResourceWarning) - return rdna2spirv.translate(src) - finally: - rdna2spirv.WAVE64_EMULATE = prev - - -def run(body: list[str], memory: dict[int, int] | None = None) -> dict[int, int]: - if memory is None: - mem = {BASE + 4 * k: w for k, w in enumerate(SEED)} - else: - mem = dict(memory) - si.run_workgroup(translate(body), 1, 32, - inputs_for=lambda i: {"%wg_id": (0, 0, 0), "%local_id": (i, 0, 0), "%sg_lane": i}, - push_constants=[0] * 36, memory=mem) - return mem - - -def seed_bytes() -> bytearray: - return bytearray(b"".join(struct.pack(" list[int]: - return [struct.unpack_from("> shift) & ((1 << 8 * n) - 1)).to_bytes(n, "little") - self.assertEqual([mem[BASE + 4 * k] for k in range(3)], words(want)) - - def test_d16_loads_write_one_half(self): - keep = 0xBEEF1234 - buf = seed_bytes() - for op, (n, signed, shift) in LOADS.items(): - for byte in range(0, 8): - with self.subTest(op=op, byte=byte): - mem = run([ - f"v_mov_b32_e32 v1, {BASE + byte:#x}", - f"v_mov_b32_e32 v5, {keep:#x}", - f"{op} v5, v1, s[0:1]", - "s_waitcnt vmcnt(0)", - f"v_mov_b32_e32 v6, {OUT:#x}", - "global_store_dword v6, v5, s[0:1]", - ]) - v = int.from_bytes(buf[byte:byte + n], "little") - if signed and v >> 7: - v -= 0x100 - v &= 0xFFFF - want = (keep & ~(0xFFFF << shift) | v << shift) & M32 - self.assertEqual(mem[OUT], want) - - def test_inactive_lane_does_nothing(self): - body = [ - "v_cmpx_eq_u32_e32 1, v0", - f"v_mov_b32_e32 v1, {BASE + 1:#x}", - "v_add_nc_u32_e32 v2, 0x70, v0", - "global_store_byte v1, v2, s[0:1]", - ] - mem = {BASE + 4 * k: w for k, w in enumerate(SEED)} - si.run_workgroup(translate(body), 2, 32, - inputs_for=lambda i: {"%wg_id": (0, 0, 0), "%local_id": (i, 0, 0), "%sg_lane": i}, - push_constants=[0] * 36, memory=mem) - self.assertEqual(mem[BASE], (SEED[0] & ~0xFF00) | 0x71 << 8) - - def test_rejected_forms(self): - for line in ("global_load_dword_addtid v0, s[0:1]", "global_store_byte v1, v[2:3], s[0:1]", - "global_store_short v1, v2, s[0:1] slc"): - with self.subTest(line=line): - with self.assertRaises(rdna2spirv.Unsupported): - translate(["v_mov_b32_e32 v1, 0", line]) - - def test_first_read_analysis_counts_the_kept_half(self): - from shader_ir import parse_line - self.assertEqual(rdna2spirv.read_before_write_vgprs([parse_line("\tglobal_load_short_d16 v5, v1, s[0:1]")]), - {1, 5}) - self.assertEqual(rdna2spirv.read_before_write_vgprs([parse_line("\tglobal_load_ushort v5, v1, s[0:1]")]), - {1}) - - def test_short_loads_crossing_dword_both_modes_and_inactive_lane(self): - mem_init = {BASE: 0x7FAABBCC, BASE + 4: 0x11223380} - for op, want in (("global_load_ushort", 0x807F), ("global_load_sshort", 0xFFFF807F)): - for addr_reg, off_mod in ((BASE + 3, ""), (BASE + 4, " offset:-1")): - with self.subTest(op=op, addr=hex(addr_reg), off_mod=off_mod): - mem = run([ - f"v_mov_b32_e32 v1, {addr_reg:#x}", - "v_mov_b32_e32 v2, 0", - "v_mov_b32_e32 v5, 0xdeadbeef", - f"{op} v5, v[1:2], off{off_mod}", - "s_waitcnt vmcnt(0)", - f"v_mov_b32_e32 v6, {OUT:#x}", - "global_store_dword v6, v5, s[0:1]", - ], memory=mem_init) - self.assertEqual(mem[OUT], want) - - with self.subTest(op=op, inactive=True): - mem = run([ - f"v_mov_b32_e32 v1, {BASE + 3:#x}", - "v_mov_b32_e32 v5, 0xdeadbeef", - "s_mov_b32 s4, exec_lo", - "s_mov_b32 exec_lo, 0", - f"{op} v5, v1, s[0:1]", - "s_mov_b32 exec_lo, s4", - "s_waitcnt vmcnt(0)", - f"v_mov_b32_e32 v6, {OUT:#x}", - "global_store_dword v6, v5, s[0:1]", - ], memory=mem_init) - self.assertEqual(mem[OUT], 0xDEADBEEF) - - def _load_validation_modules(self): - return ( - ("w32_ushort_saddr", translate([ - f"v_mov_b32_e32 v1, {BASE + 3:#x}", - "global_load_ushort v5, v1, s[0:1]", - ])), - ("w32_sshort_voff", translate([ - f"v_mov_b32_e32 v1, {BASE + 4:#x}", - "v_mov_b32_e32 v2, 0", - "global_load_sshort v5, v[1:2], off offset:-1", - ])), - ("w64_emulate_sshort", translate([ - "s_mov_b64 exec, -1", - f"v_mov_b32_e32 v1, {BASE + 3:#x}", - "v_readfirstlane_b32 s16, v1", - "global_load_sshort v5, v1, s[0:1]", - ], threads=64, emulate=True)), - ) - - def test_sub_dword_loads_spirv_assembly(self): - for label, spv in self._load_validation_modules(): - with self.subTest(case=label): - binary = spirv_asm.assemble(spv, target_env="vulkan1.2") - self.assertEqual(struct.unpack_from(" list of instruction lines in that basic block.""" - blocks = {} - cur = None - for raw in spv.splitlines(): - s = raw.strip() - if s.endswith("= OpLabel"): - cur = s.split(" = ")[0] - blocks[cur] = [] - elif cur is not None and s: - blocks[cur].append(s) - return blocks - - -def find_guarded_texel_block(spv): - """Verify every OpImageTexelPointer sits inside a basic block entered via an OpSelectionMerge - conditional branch whose condition is an OpLoad %bool %active, or the constant %true when the shader has no - OpStore to %active, and return that block's instructions.""" - blocks = parse_blocks(spv) - active_loads = set(re.findall(r"^\s*(%\w+) = OpLoad %bool %active\b", spv, re.M)) - # A shader that never writes EXEC leaves every lane active, and the translator folds `if (%active)` to - # `if (%true)` there (#4473), which guards nothing because nothing can be inactive. Accept that constant, and - # only that constant: a shader with an OpStore to %active still needs the real load to protect the access. - exec_is_constant_true = not re.search(r"^\s*OpStore %active\b", spv, re.M) - guarded_targets = set() - for insns in blocks.values(): - for i, ln in enumerate(insns): - if ln.startswith("OpSelectionMerge ") and i + 1 < len(insns): - br = insns[i + 1] - m = re.match(r"OpBranchConditional (%\w+) (%\w+) (%\w+)", br) - if m and (m.group(1) in active_loads or (exec_is_constant_true and m.group(1) == "%true")): - guarded_targets.add(m.group(2)) - found = [] - for lbl, insns in blocks.items(): - if any("= OpImageTexelPointer " in ln for ln in insns): - if lbl not in guarded_targets: - raise AssertionError(f"OpImageTexelPointer in unguarded block {lbl}") - found.append((lbl, insns)) - if not found: - raise AssertionError("No OpImageTexelPointer emitted") - return found - - -def vgpr_ptrs(spv, reg_idx): - """Return all SSA pointer IDs pointing to %vgpr[reg_idx].""" - consts = {k: int(v) for k, v in re.findall(r"^\s*(%\w+) = OpConstant %uint (\d+)\b", spv, re.M)} - return { - ptr for ptr, idx in re.findall(r"^\s*(%\w+) = OpAccessChain %_ptr_Function_uint %vgpr (%\w+)\b", spv, re.M) - if consts.get(idx) == reg_idx - } - - -class ImageAtomicsGuardTests(unittest.TestCase): - def test_all_image_atomics_2d_and_3d_guarded_and_valid(self): - simple_ops = [ - ("image_atomic_add", "OpAtomicIAdd"), - ("image_atomic_sub", "OpAtomicISub"), - ("image_atomic_umin", "OpAtomicUMin"), - ("image_atomic_umax", "OpAtomicUMax"), - ("image_atomic_smin", "OpAtomicSMin"), - ("image_atomic_smax", "OpAtomicSMax"), - ("image_atomic_and", "OpAtomicAnd"), - ("image_atomic_or", "OpAtomicOr"), - ("image_atomic_xor", "OpAtomicXor"), - ("image_atomic_swap", "OpAtomicExchange"), - ] - for op, spv_op in simple_ops: - for dim, addr, arr_var in ( - ("dim:SQ_RSRC_IMG_2D", "v[1:2]", "%simages"), - ("dim:SQ_RSRC_IMG_3D", "v[1:3]", "%simages3d"), - ): - for glc in ("", " glc"): - with self.subTest(op=op, dim=dim, glc=bool(glc)): - lines = [ - "v_mov_b32_e32 v0, 5", - "v_mov_b32_e32 v1, 1", - "v_mov_b32_e32 v2, 2", - "v_mov_b32_e32 v3, 3", - f"{op} v0, {addr}, s[4:11] dmask:0x1 {dim} unorm{glc}", - ] - spv = translate(lines) - validate_spirv(spv) - guarded = find_guarded_texel_block(spv) - self.assertEqual(len(guarded), 1) - insns = guarded[0][1] - self.assertTrue(any(f"OpAccessChain " in ln and arr_var in ln for ln in insns), - "OpAccessChain must sit inside the active-guarded block") - self.assertTrue(any(f"= {spv_op} %uint " in ln for ln in insns)) - v0_ptrs = vgpr_ptrs(spv, 0) - has_glc_store = any( - ln.startswith("OpStore ") and ln.split()[1] in v0_ptrs for ln in insns - ) - self.assertEqual(has_glc_store, bool(glc), - f"glc={bool(glc)} mismatch for v0 write-back in guarded block") - - def test_image_atomic_inc_and_dec_cas_2d_3d_and_a16(self): - cases = [ - ("image_atomic_inc", "dim:SQ_RSRC_IMG_2D", "v[1:2]", "", "OpUGreaterThanEqual"), - ("image_atomic_dec", "dim:SQ_RSRC_IMG_2D", "v[1:2]", " glc", "OpUGreaterThan "), - ("image_atomic_inc", "dim:SQ_RSRC_IMG_3D", "v[1:3]", " glc", "OpUGreaterThanEqual"), - ("image_atomic_dec", "dim:SQ_RSRC_IMG_3D", "v[1:2]", " a16", "OpUGreaterThan "), - ("image_atomic_swap", "dim:SQ_RSRC_IMG_2D", "v1", " a16 glc", "OpAtomicExchange"), - ("image_atomic_swap", "dim:SQ_RSRC_IMG_3D", "v[1:2]", " a16", "OpAtomicExchange"), - ] - for op, dim, addr, extra, marker in cases: - with self.subTest(op=op, dim=dim, extra=extra): - lines = [ - "v_mov_b32_e32 v0, 7", - "v_mov_b32_e32 v1, 0x00020001", - "v_mov_b32_e32 v2, 3", - "v_mov_b32_e32 v3, 4", - f"{op} v0, {addr}, s[4:11] dmask:0x1 {dim} unorm{extra}", - ] - spv = translate(lines) - validate_spirv(spv) - find_guarded_texel_block(spv) - self.assertIn(marker, spv) - if op in ("image_atomic_inc", "image_atomic_dec"): - self.assertIn("OpAtomicLoad %uint ", spv) - self.assertIn("OpAtomicCompareExchange %uint ", spv) - self.assertIn("OpLoopMerge ", spv) - - def test_cmpswap_and_bad_data_width_rejected(self): - # Valid 2-VGPR cmpswap (2D and 3D) stays guarded and valid. - for dim, addr in (("dim:SQ_RSRC_IMG_2D", "v[1:2]"), ("dim:SQ_RSRC_IMG_3D", "v[1:3]")): - spv = translate([ - "v_mov_b32_e32 v4, 1", "v_mov_b32_e32 v5, 2", - "v_mov_b32_e32 v1, 0", "v_mov_b32_e32 v2, 0", "v_mov_b32_e32 v3, 0", - f"image_atomic_cmpswap v[4:5], {addr}, s[4:11] dmask:0x3 {dim} unorm glc", - ]) - validate_spirv(spv) - find_guarded_texel_block(spv) - - # Two-VGPR dmask:0x3 standard ops (64-bit corpus forms, e.g. image_atomic_umax) stay accepted - # and active-guarded so corpus translation coverage does not regress before Int64ImageEXT lands. - spv64 = translate([ - "v_mov_b32_e32 v4, 1", "v_mov_b32_e32 v5, 0", - "v_mov_b32_e32 v1, 0", "v_mov_b32_e32 v2, 0", - "image_atomic_umax v[4:5], v[1:2], s[4:11] dmask:0x3 dim:SQ_RSRC_IMG_2D unorm", - ]) - validate_spirv(spv64) - find_guarded_texel_block(spv64) - - # Wrong-width data operands on extra 32-bit ops and cmpswap must still raise Unsupported. - for bad in ( - "image_atomic_swap v[0:1], v[1:2], s[4:11] dmask:0x3 dim:SQ_RSRC_IMG_2D unorm", - "image_atomic_inc v[0:1], v[1:2], s[4:11] dmask:0x3 dim:SQ_RSRC_IMG_2D unorm", - "image_atomic_cmpswap v0, v[1:2], s[4:11] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm", - ): - with self.subTest(bad=bad): - with self.assertRaises(rdna2spirv.Unsupported): - translate(["v_mov_b32_e32 v0, 0", "v_mov_b32_e32 v1, 0", "v_mov_b32_e32 v2, 0", bad]) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_image_bvh_box.py b/tests/semantic/test_image_bvh_box.py deleted file mode 100644 index 1595605db..000000000 --- a/tests/semantic/test_image_bvh_box.py +++ /dev/null @@ -1,93 +0,0 @@ -"""image_bvh64_intersect_ray on box nodes: an empty box (min > max on any axis) is a miss. - -One pixel shader per case runs the instruction on a hand-built box node and exports the four child words. The ray -starts at (0, 0, -1) and runs along +z. A box contributes its entry distance only when it is well formed and the -slab interval overlaps [0, extent); empty boxes (min > max) and boxes the ray misses give 0xFFFFFFFF, in distance -order, as tools/xdxr_bvh.py `_box_test` does. - -box32 (node type 5) stores a child as six f32 at byte 16 + 24 i; box16 (type 4) stores the same six values as -f16 at byte 16 + 12 i. Both go through the same slab test in tools/rdna2spirv.py. - - python -m unittest discover -s tests/semantic -p "test_image_bvh_box.py" -v -""" -import struct -import unittest - -from support import mrt0_words, translate_lines - -INF_WORD = 0x7F800000 -MISS = 0xFFFFFFFF -NODE = 0x1040 # descriptor base 0x10 (256-byte units) = 0x1000; node id 0x08 | type -> +0x40 - - -def f2u(x): - return struct.unpack(" max -1). - boxes = [(-1, 1, 0.5, 1, -1, 2), (2, 2, 2, 3, 3, 3), (2, 2, 2, 3, 3, 3), (2, 2, 2, 3, 3, 3)] - for node_type in (4, 5): - with self.subTest(node_type=node_type): - self.assertEqual(run(node_type, CHILDREN, boxes), [MISS, MISS, MISS, MISS]) - - def test_zero_thickness_box_is_not_empty(self): - # min == max is a degenerate but well-formed box; the CPU reference keeps it (lo > hi only). - boxes = [(-1, -1, 0, 1, 1, 0), (2, 2, 2, 3, 3, 3), (2, 2, 2, 3, 3, 3), (2, 2, 2, 3, 3, 3)] - for node_type in (4, 5): - with self.subTest(node_type=node_type): - self.assertEqual(run(node_type, CHILDREN, boxes), [0x20, MISS, MISS, MISS]) - - def test_empty_box_does_not_hide_a_later_hit(self): - # child 0's box is empty; child 1's overlaps, child 2's starts right after the extent, child 3's is empty. - boxes = [(1, 1, 4, -1, -1, 5), (-1, -1, 2, 1, 1, 3), (2, 2, 2, 3, 3, 3), (0, 1, 0, 1, 0, 1)] - # The four results stay in child-slot order; a miss at slot 0 is not compacted away. - for node_type in (4, 5): - with self.subTest(node_type=node_type): - self.assertEqual(run(node_type, CHILDREN, boxes), [MISS, 0x28, MISS, MISS]) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_image_bvh_box_hw.py b/tests/semantic/test_image_bvh_box_hw.py deleted file mode 100644 index 1a4fa6d4f..000000000 --- a/tests/semantic/test_image_bvh_box_hw.py +++ /dev/null @@ -1,935 +0,0 @@ -"""image_bvh_intersect_ray box nodes against words measured on native RDNA2 hardware (SHADER-650). - -Every expected value below was returned by the instruction itself on an AMD Radeon RX 6900 XT (gfx1030, AMD -driver 26.11.2, Windows), through tools/hw_oracle raw kernels that write the node into memory and trace one ray -with box sorting on (descriptor w1 bit 31, w2 = -1, w3 = 0x81000000). This file runs the same node and ray -through the translator and compares the four child words. The rule they follow is in the docs/design.md Ray -tracing row: near/far planes picked by the sign of the inverse direction, NaN skipped in the max/min of the -three, all-NaN a miss, sort key max(tnear, 0) through the network (0,2) (1,3) (0,1) (2,3) (1,2). - -241 of the 338 measured cases, plus 50 rounding cases (below): the empty-box set (BOX32 and BOX16), the NaN set, the multi-NaN and -other-bound rows of the NaN grid on four rays, every measured tie order, planes on the origin, and the -cs_bvh scene root. No game data. - - python -m unittest discover -s tests/semantic -p "test_image_bvh_box_hw.py" -v -""" -import struct -import unittest - -from support import mrt0_words, translate_lines - -INF = float("inf") -NAN = float("nan") -FMAX = struct.unpack(" o.x', 'box32', 'R2', [0x40, 0x48, 0x50, 0x58], - [(-0.25, -0.25, -3.0, 0.75, 0.75, -2.75), (1.0, -1.0, -2.0, 0.25, 1.0, -1.0), (-0.25, -0.25, 1.0, 0.75, 0.75, 1.25), (-0.25, -0.25, 6.0, 0.75, 0.75, 6.25)], - [0x40, 0x50, 0x58, MISS]), - ('box32 cs_bvh scene root', 'box32', 'R0', [0x40, 0x48, 0x60, 0x68], - [(0.0, 0.0, 10.0, 1.0, 1.0, 10.0), (0.0, 0.0, 5.0, 1.0, 1.0, 5.0), (5.0, 0.0, 0.0, 6.0, 1.0, 1.0), (NAN, 0.0, 0.0, 1.0, 1.0, 1.0)], - [0x68, 0x48, 0x40, MISS]), -] - - -def f2u(x): - return struct.unpack(" +0x40 - - -def f2u(x): - return struct.unpack("= 0 tested; zero words +0 and -NaN words 0xFFC00000; a NaN anywhere in the ray or an infinite origin gives (inf, 1, 0, 0); RDNA2's own tie rule on -shared edges and vertices. - -Rows: all 308 single-lane rows of the 12 single-lane kernels (fan leaf of the four node types around one vertex, -mirrored and axis-permuted leaves, misses on both sides, the remap byte, t max / t sign / zero area / NaN and inf -inputs, the ray's own NaN / inf / zero / wrong inverse direction, shared edges and vertices), each run in both forms, -and lanes 0, 15, 16, 31, 32 and 63 of the two 64-thread kernels (all 7 cases). Then the 256 rows of the tie kernels -tri_t1..tri_t8 (same driver, same descriptor, 2026-11-23): rays exactly on a shared edge, an outer edge or a vertex -with x, y or z dominant, both windings and both signs of d[kz] (fan, mirrored, rotated in its plane and tilted -leaves, axis and oblique rays), equal |d| components with and without a tie, and 22 repeated #4202 rows as controls. -Every row is asserted. - - python -m unittest discover -s tests/semantic -p "test_image_bvh_tri_hw.py" -v -""" -import unittest - -from support import mrt0_words, translate_lines - -RAY = 0x1000 # node id (lo, hi), t max, origin, direction, inverse direction: read with s_buffer_load -NODE = 0x2000 # the 64-byte node -PUSH = [RAY, 0, 0x100, 0] + [0] * 28 # V# in s[0:3]: base RAY, num_records 256 - -# BEGIN MEASURED DATA (work-bvhtri/ties/export_hw_table_ties.py writes this block from the raw outputs; do not edit by hand) -# 564 single-lane rows of 20 kernels (12 of #4202, then the tie kernels tri_t1..tri_t8) and 84 lane results of 2 kernels (lanes 0, 15, 16, 31, 32, 63); device=AMD Radeon RX 6800 arch=gfx1030 - -# words 0..14 (vertex slots 0..4) of every node the rows use; word 15 (the remap bytes) is per row -NODES = { - 'fan': [ - 0x00000000, 0x00000000, 0x40400000, 0x40800000, 0x00000000, - 0x40400000, 0x00000000, 0x40000000, 0x40400000, 0x40800000, - 0x40000000, 0x40400000, 0xc0000000, 0x40400000, 0x40400000, - ], - 'fan_mirrored': [ - 0x00000000, 0x00000000, 0x40400000, 0xc0800000, 0x00000000, - 0x40400000, 0x00000000, 0x40000000, 0x40400000, 0xc0800000, - 0x40000000, 0x40400000, 0x40000000, 0x40400000, 0x40400000, - ], - 'fan_x_dominant': [ - 0x40400000, 0x00000000, 0x00000000, 0x40400000, 0x40800000, - 0x00000000, 0x40400000, 0x00000000, 0x40000000, 0x40400000, - 0x40800000, 0x40000000, 0x40400000, 0xc0000000, 0x40400000, - ], - 'fan_y_dominant': [ - 0x00000000, 0x40400000, 0x00000000, 0x00000000, 0x40400000, - 0x40800000, 0x40000000, 0x40400000, 0x00000000, 0x40000000, - 0x40400000, 0x40800000, 0x40400000, 0x40400000, 0xc0000000, - ], - 'cs_bvh_tri': [ - 0x00000000, 0x00000000, 0x41200000, 0x3f800000, 0x00000000, - 0x41200000, 0x00000000, 0x3f800000, 0x41200000, 0xeeeeeeee, - 0xeeeeeeee, 0xeeeeeeee, 0xeeeeeeee, 0xeeeeeeee, 0xeeeeeeee, - ], - 'three_equal': [ - 0x3f800000, 0x3e800000, 0x40400000, 0x3f800000, 0x3e800000, - 0x40400000, 0x3f800000, 0x3e800000, 0x40400000, 0x40800000, - 0x40000000, 0x40400000, 0xc0000000, 0x40400000, 0x40400000, - ], - 'collinear': [ - 0x00000000, 0x3e800000, 0x40400000, 0x40000000, 0x3e800000, - 0x40400000, 0x40800000, 0x3e800000, 0x40400000, 0x40800000, - 0x40000000, 0x40400000, 0xc0000000, 0x40400000, 0x40400000, - ], - 'edge_on': [ - 0x00000000, 0x3e800000, 0x00000000, 0x40800000, 0x3e800000, - 0x00000000, 0x00000000, 0x3e800000, 0x40c00000, 0x40800000, - 0x40000000, 0x40400000, 0xc0000000, 0x40400000, 0x40400000, - ], - 'v0x_nan': [ - 0x7fc00000, 0x00000000, 0x40400000, 0x40800000, 0x00000000, - 0x40400000, 0x00000000, 0x40000000, 0x40400000, 0x40800000, - 0x40000000, 0x40400000, 0xc0000000, 0x40400000, 0x40400000, - ], - 'v0z_nan': [ - 0x00000000, 0x00000000, 0x7fc00000, 0x40800000, 0x00000000, - 0x40400000, 0x00000000, 0x40000000, 0x40400000, 0x40800000, - 0x40000000, 0x40400000, 0xc0000000, 0x40400000, 0x40400000, - ], - 'v1y_nan': [ - 0x00000000, 0x00000000, 0x40400000, 0x40800000, 0x7fc00000, - 0x40400000, 0x00000000, 0x40000000, 0x40400000, 0x40800000, - 0x40000000, 0x40400000, 0xc0000000, 0x40400000, 0x40400000, - ], - 'v2x_inf': [ - 0x00000000, 0x00000000, 0x40400000, 0x40800000, 0x00000000, - 0x40400000, 0x7f800000, 0x40000000, 0x40400000, 0x40800000, - 0x40000000, 0x40400000, 0xc0000000, 0x40400000, 0x40400000, - ], - 'v0x_neginf': [ - 0xff800000, 0x00000000, 0x40400000, 0x40800000, 0x00000000, - 0x40400000, 0x00000000, 0x40000000, 0x40400000, 0x40800000, - 0x40000000, 0x40400000, 0xc0000000, 0x40400000, 0x40400000, - ], - 'slot3_nan': [ - 0x00000000, 0x00000000, 0x40400000, 0x40800000, 0x00000000, - 0x40400000, 0x00000000, 0x40000000, 0x40400000, 0x7fc00000, - 0x40000000, 0x40400000, 0xc0000000, 0x40400000, 0x40400000, - ], - 'slot4_nan': [ - 0x00000000, 0x00000000, 0x40400000, 0x40800000, 0x00000000, - 0x40400000, 0x00000000, 0x40000000, 0x40400000, 0x40800000, - 0x40000000, 0x40400000, 0x7fc00000, 0x40400000, 0x40400000, - ], - 'rotated_fan_x_dominant': [ - 0x40400000, 0x00000000, 0x00000000, 0x40400000, 0x00000000, - 0x40800000, 0x40400000, 0xc0000000, 0x00000000, 0x40400000, - 0xc0000000, 0x40800000, 0x40400000, 0xc0400000, 0xc0000000, - ], - 'mirrored_fan_x_dominant': [ - 0x40400000, 0x00000000, 0x00000000, 0x40400000, 0xc0800000, - 0x00000000, 0x40400000, 0x00000000, 0x40000000, 0x40400000, - 0xc0800000, 0x40000000, 0x40400000, 0x40000000, 0x40400000, - ], - 'rotated_mirrored_fan_x_dominant': [ - 0x40400000, 0x00000000, 0x00000000, 0x40400000, 0x00000000, - 0x40800000, 0x40400000, 0x40000000, 0x00000000, 0x40400000, - 0x40000000, 0x40800000, 0x40400000, 0x40400000, 0xc0000000, - ], - 'rotated_fan_y_dominant': [ - 0x00000000, 0x40400000, 0x00000000, 0x40800000, 0x40400000, - 0x00000000, 0x00000000, 0x40400000, 0xc0000000, 0x40800000, - 0x40400000, 0xc0000000, 0xc0000000, 0x40400000, 0xc0400000, - ], - 'mirrored_fan_y_dominant': [ - 0x00000000, 0x40400000, 0x00000000, 0x00000000, 0x40400000, - 0xc0800000, 0x40000000, 0x40400000, 0x00000000, 0x40000000, - 0x40400000, 0xc0800000, 0x40400000, 0x40400000, 0x40000000, - ], - 'rotated_mirrored_fan_y_dominant': [ - 0x00000000, 0x40400000, 0x00000000, 0x40800000, 0x40400000, - 0x00000000, 0x00000000, 0x40400000, 0x40000000, 0x40800000, - 0x40400000, 0x40000000, 0xc0000000, 0x40400000, 0x40400000, - ], - 'fan_tilted_p1x_p0y_x_dominant': [ - 0x40400000, 0x00000000, 0x00000000, 0x40e00000, 0x40800000, - 0x00000000, 0x40400000, 0x00000000, 0x40000000, 0x40e00000, - 0x40800000, 0x40000000, 0x3f800000, 0xc0000000, 0x40400000, - ], - 'mirrored_fan_tilted_p1x_p1y_y_dominant': [ - 0x00000000, 0x40400000, 0x00000000, 0x00000000, 0xbf800000, - 0xc0800000, 0x40000000, 0x40a00000, 0x00000000, 0x40000000, - 0x3f800000, 0xc0800000, 0x40400000, 0x41000000, 0x40000000, - ], - 'rotated_mirrored_fan': [ - 0x00000000, 0x00000000, 0x40400000, 0x00000000, 0x40800000, - 0x40400000, 0x40000000, 0x00000000, 0x40400000, 0x40000000, - 0x40800000, 0x40400000, 0x40400000, 0xc0000000, 0x40400000, - ], - 'rotated_fan': [ - 0x00000000, 0x00000000, 0x40400000, 0x00000000, 0x40800000, - 0x40400000, 0xc0000000, 0x00000000, 0x40400000, 0xc0000000, - 0x40800000, 0x40400000, 0xc0400000, 0xc0000000, 0x40400000, - ], -} - -# (kernel, label, node, word 15, node type, ray (t max, origin, direction, inverse direction), -# the four words both forms returned) -ROWS = [ - ('tri_g1a', 'TRI0 hit +z', 'fan', 0x09090909, 0, - (0x42c80000, 0x3f800000, 0x3e800000, 0xbf800000, 0x00000000, 0x00000000, 0x3f000000, 0x7f800000, 0x7f800000, 0x40000000), - (0xc1000000, 0xbf800000, 0xbe800000, 0xbe000000)), - ('tri_g1a', 'TRI0 hit -z (back)', 'fan', 0x09090909, 0, - (0x42c80000, 0x3f800000, 0x3e800000, 0x40e00000, 0x00000000, 0x00000000, 0xbf000000, 0x7f800000, 0x7f800000, 0xc0000000), - (0x41000000, 0x3f800000, 0x3e800000, 0x3e000000)), - ('tri_g1a', 'TRI1 hit +z', 'fan', 0x09090909, 1, - (0x42c80000, 0x40600000, 0x3fa00000, 0xbf800000, 0x00000000, 0x00000000, 0x3f000000, 0x7f800000, 0x7f800000, 0x40000000), - (0xc1000000, 0xbf800000, 0xbf000000, 0xbe000000)), - ('tri_g1a', 'TRI1 hit -z (back)', 'fan', 0x09090909, 1, - (0x42c80000, 0x40600000, 0x3fa00000, 0x40e00000, 0x00000000, 0x00000000, 0xbf000000, 0x7f800000, 0x7f800000, 0xc0000000), - (0x41000000, 0x3f800000, 0x3f000000, 0x3e000000)), - ('tri_g1a', 'TRI2 hit +z', 'fan', 0x09090909, 2, - (0x42c80000, 0x3fe00000, 0x40080000, 0xbf800000, 0x00000000, 0x00000000, 0x3f000000, 0x7f800000, 0x7f800000, 0x40000000), - (0xc0800000, 0xbf000000, 0xbe800000, 0xbd800000)), - ('tri_g1a', 'TRI2 hit -z (back)', 'fan', 0x09090909, 2, - (0x42c80000, 0x3fe00000, 0x40080000, 0x40e00000, 0x00000000, 0x00000000, 0xbf000000, 0x7f800000, 0x7f800000, 0xc0000000), - (0x40800000, 0x3f000000, 0x3e800000, 0x3d800000)), - ('tri_g1a', 'TRI3 hit +z', 'fan', 0x09090909, 3, - (0x42c80000, 0xbf000000, 0x40000000, 0xbf800000, 0x00000000, 0x00000000, 0x3f000000, 0x7f800000, 0x7f800000, 0x40000000), - (0xc0800000, 0xbf000000, 0xbe000000, 0xbd800000)), - ('tri_g1a', 'TRI3 hit -z (back)', 'fan', 0x09090909, 3, - (0x42c80000, 0xbf000000, 0x40000000, 0x40e00000, 0x00000000, 0x00000000, 0xbf000000, 0x7f800000, 0x7f800000, 0xc0000000), - (0x40800000, 0x3f000000, 0x3e000000, 0x3d800000)), - ('tri_g1a', "TRI0 miss (+z at TRI1's point)", 'fan', 0x09090909, 0, - (0x42c80000, 0x40600000, 0x3fa00000, 0xbf800000, 0x00000000, 0x00000000, 0x3f000000, 0x7f800000, 0x7f800000, 0x40000000), - (0xff800000, 0xbf800000, 0xbf600000, 0xbf200000)), - ('tri_g1a', "TRI1 miss (+z at TRI2's point)", 'fan', 0x09090909, 1, - (0x42c80000, 0x3fe00000, 0x40080000, 0xbf800000, 0x00000000, 0x00000000, 0x3f000000, 0x7f800000, 0x7f800000, 0x40000000), - (0xff800000, 0xbf800000, 0xbf000000, 0xbf100000)), - ('tri_g1a', "TRI2 miss (+z at TRI3's point)", 'fan', 0x09090909, 2, - (0x42c80000, 0xbf000000, 0x40000000, 0xbf800000, 0x00000000, 0x00000000, 0x3f000000, 0x7f800000, 0x7f800000, 0x40000000), - (0xff800000, 0xbf000000, 0x3d800000, 0x00000000)), - ('tri_g1a', "TRI3 miss (+z at TRI0's point)", 'fan', 0x09090909, 3, - (0x42c80000, 0x3f800000, 0x3e800000, 0xbf800000, 0x00000000, 0x00000000, 0x3f000000, 0x7f800000, 0x7f800000, 0x40000000), - (0xff800000, 0xbf000000, 0x3e800000, 0xbea00000)), - ('tri_g1a', 'TRI0 mirrored leaf hit +z', 'fan_mirrored', 0x09090909, 0, - (0x42c80000, 0xbf800000, 0x3e800000, 0xbf800000, 0x00000000, 0x00000000, 0x3f000000, 0x7f800000, 0x7f800000, 0x40000000), - (0x41000000, 0x3f800000, 0x3e800000, 0x3e000000)), - ('tri_g1a', 'TRI1 mirrored leaf hit +z', 'fan_mirrored', 0x09090909, 1, - (0x42c80000, 0xc0600000, 0x3fa00000, 0xbf800000, 0x00000000, 0x00000000, 0x3f000000, 0x7f800000, 0x7f800000, 0x40000000), - (0x41000000, 0x3f800000, 0x3f000000, 0x3e000000)), - ('tri_g1a', 'TRI2 mirrored leaf hit +z', 'fan_mirrored', 0x09090909, 2, - (0x42c80000, 0xbfe00000, 0x40080000, 0xbf800000, 0x00000000, 0x00000000, 0x3f000000, 0x7f800000, 0x7f800000, 0x40000000), - (0x40800000, 0x3f000000, 0x3e800000, 0x3d800000)), - ('tri_g1a', 'TRI3 mirrored leaf hit +z', 'fan_mirrored', 0x09090909, 3, - (0x42c80000, 0x3f000000, 0x40000000, 0xbf800000, 0x00000000, 0x00000000, 0x3f000000, 0x7f800000, 0x7f800000, 0x40000000), - (0x40800000, 0x3f000000, 0x3e000000, 0x3d800000)), - ('tri_g1a', 'TRI0 hit oblique +z', 'fan', 0x09090909, 0, - (0x42c80000, 0x00000000, 0xbe800000, 0xbf800000, 0x3e000000, 0x3d800000, 0x3f000000, 0x41000000, 0x41800000, 0x40000000), - (0xc1000000, 0xbf800000, 0xbe800000, 0xbe000000)), - ('tri_g1a', 'TRI0 hit oblique -z', 'fan', 0x09090909, 0, - (0x42c80000, 0x00000000, 0xbe800000, 0x40e00000, 0x3e000000, 0x3d800000, 0xbf000000, 0x41000000, 0x41800000, 0xc0000000), - (0x41000000, 0x3f800000, 0x3e800000, 0x3e000000)), - ('tri_g1a', 'TRI1 hit oblique +z', 'fan', 0x09090909, 1, - (0x42c80000, 0x40200000, 0x3f400000, 0xbf800000, 0x3e000000, 0x3d800000, 0x3f000000, 0x41000000, 0x41800000, 0x40000000), - (0xc1000000, 0xbf800000, 0xbf000000, 0xbe000000)), - ('tri_g1a', 'TRI1 hit oblique -z', 'fan', 0x09090909, 1, - (0x42c80000, 0x40200000, 0x3f400000, 0x40e00000, 0x3e000000, 0x3d800000, 0xbf000000, 0x41000000, 0x41800000, 0xc0000000), - (0x41000000, 0x3f800000, 0x3f000000, 0x3e000000)), - ('tri_g1a', 'TRI2 hit oblique +z', 'fan', 0x09090909, 2, - (0x42c80000, 0x3f400000, 0x3fd00000, 0xbf800000, 0x3e000000, 0x3d800000, 0x3f000000, 0x41000000, 0x41800000, 0x40000000), - (0xc0800000, 0xbf000000, 0xbe800000, 0xbd800000)), - ('tri_g1a', 'TRI2 hit oblique -z', 'fan', 0x09090909, 2, - (0x42c80000, 0x3f400000, 0x3fd00000, 0x40e00000, 0x3e000000, 0x3d800000, 0xbf000000, 0x41000000, 0x41800000, 0xc0000000), - (0x40800000, 0x3f000000, 0x3e800000, 0x3d800000)), - ('tri_g1a', 'TRI3 hit oblique +z', 'fan', 0x09090909, 3, - (0x42c80000, 0xbfc00000, 0x3fc00000, 0xbf800000, 0x3e000000, 0x3d800000, 0x3f000000, 0x41000000, 0x41800000, 0x40000000), - (0xc0800000, 0xbf000000, 0xbe000000, 0xbd800000)), - ('tri_g1a', 'TRI3 hit oblique -z', 'fan', 0x09090909, 3, - (0x42c80000, 0xbfc00000, 0x3fc00000, 0x40e00000, 0x3e000000, 0x3d800000, 0xbf000000, 0x41000000, 0x41800000, 0xc0000000), - (0x40800000, 0x3f000000, 0x3e000000, 0x3d800000)), - ('tri_g1a', 'cs_bvh scene triangle node 0x40', 'cs_bvh_tri', 0x00000009, 0, - (0x42c80000, 0x3e800000, 0x3e800000, 0x00000000, 0x00000000, 0x00000000, 0x3f800000, 0x7f800000, 0x7f800000, 0x3f800000), - (0xc1200000, 0xbf800000, 0xbe800000, 0xbe800000)), - ('tri_g1a_nsa', 'TRI0 hit +z', 'fan', 0x09090909, 0, - (0x42c80000, 0x3f800000, 0x3e800000, 0xbf800000, 0x00000000, 0x00000000, 0x3f000000, 0x7f800000, 0x7f800000, 0x40000000), - (0xc1000000, 0xbf800000, 0xbe800000, 0xbe000000)), - ('tri_g1a_nsa', 'TRI0 hit -z (back)', 'fan', 0x09090909, 0, - (0x42c80000, 0x3f800000, 0x3e800000, 0x40e00000, 0x00000000, 0x00000000, 0xbf000000, 0x7f800000, 0x7f800000, 0xc0000000), - (0x41000000, 0x3f800000, 0x3e800000, 0x3e000000)), - ('tri_g1a_nsa', 'TRI1 hit +z', 'fan', 0x09090909, 1, - (0x42c80000, 0x40600000, 0x3fa00000, 0xbf800000, 0x00000000, 0x00000000, 0x3f000000, 0x7f800000, 0x7f800000, 0x40000000), - (0xc1000000, 0xbf800000, 0xbf000000, 0xbe000000)), - ('tri_g1a_nsa', 'TRI1 hit -z (back)', 'fan', 0x09090909, 1, - (0x42c80000, 0x40600000, 0x3fa00000, 0x40e00000, 0x00000000, 0x00000000, 0xbf000000, 0x7f800000, 0x7f800000, 0xc0000000), - (0x41000000, 0x3f800000, 0x3f000000, 0x3e000000)), - ('tri_g1a_nsa', 'TRI2 hit +z', 'fan', 0x09090909, 2, - (0x42c80000, 0x3fe00000, 0x40080000, 0xbf800000, 0x00000000, 0x00000000, 0x3f000000, 0x7f800000, 0x7f800000, 0x40000000), - (0xc0800000, 0xbf000000, 0xbe800000, 0xbd800000)), - ('tri_g1a_nsa', 'TRI2 hit -z (back)', 'fan', 0x09090909, 2, - (0x42c80000, 0x3fe00000, 0x40080000, 0x40e00000, 0x00000000, 0x00000000, 0xbf000000, 0x7f800000, 0x7f800000, 0xc0000000), - (0x40800000, 0x3f000000, 0x3e800000, 0x3d800000)), - ('tri_g1a_nsa', 'TRI3 hit +z', 'fan', 0x09090909, 3, - (0x42c80000, 0xbf000000, 0x40000000, 0xbf800000, 0x00000000, 0x00000000, 0x3f000000, 0x7f800000, 0x7f800000, 0x40000000), - (0xc0800000, 0xbf000000, 0xbe000000, 0xbd800000)), - ('tri_g1a_nsa', 'TRI3 hit -z (back)', 'fan', 0x09090909, 3, - (0x42c80000, 0xbf000000, 0x40000000, 0x40e00000, 0x00000000, 0x00000000, 0xbf000000, 0x7f800000, 0x7f800000, 0xc0000000), - (0x40800000, 0x3f000000, 0x3e000000, 0x3d800000)), - ('tri_g1a_nsa', "TRI0 miss (+z at TRI1's point)", 'fan', 0x09090909, 0, - (0x42c80000, 0x40600000, 0x3fa00000, 0xbf800000, 0x00000000, 0x00000000, 0x3f000000, 0x7f800000, 0x7f800000, 0x40000000), - (0xff800000, 0xbf800000, 0xbf600000, 0xbf200000)), - ('tri_g1a_nsa', "TRI1 miss (+z at TRI2's point)", 'fan', 0x09090909, 1, - (0x42c80000, 0x3fe00000, 0x40080000, 0xbf800000, 0x00000000, 0x00000000, 0x3f000000, 0x7f800000, 0x7f800000, 0x40000000), - (0xff800000, 0xbf800000, 0xbf000000, 0xbf100000)), - ('tri_g1a_nsa', "TRI2 miss (+z at TRI3's point)", 'fan', 0x09090909, 2, - (0x42c80000, 0xbf000000, 0x40000000, 0xbf800000, 0x00000000, 0x00000000, 0x3f000000, 0x7f800000, 0x7f800000, 0x40000000), - (0xff800000, 0xbf000000, 0x3d800000, 0x00000000)), - ('tri_g1a_nsa', "TRI3 miss (+z at TRI0's point)", 'fan', 0x09090909, 3, - (0x42c80000, 0x3f800000, 0x3e800000, 0xbf800000, 0x00000000, 0x00000000, 0x3f000000, 0x7f800000, 0x7f800000, 0x40000000), - (0xff800000, 0xbf000000, 0x3e800000, 0xbea00000)), - ('tri_g1a_nsa', 'TRI0 mirrored leaf hit +z', 'fan_mirrored', 0x09090909, 0, - (0x42c80000, 0xbf800000, 0x3e800000, 0xbf800000, 0x00000000, 0x00000000, 0x3f000000, 0x7f800000, 0x7f800000, 0x40000000), - (0x41000000, 0x3f800000, 0x3e800000, 0x3e000000)), - ('tri_g1a_nsa', 'TRI1 mirrored leaf hit +z', 'fan_mirrored', 0x09090909, 1, - (0x42c80000, 0xc0600000, 0x3fa00000, 0xbf800000, 0x00000000, 0x00000000, 0x3f000000, 0x7f800000, 0x7f800000, 0x40000000), - (0x41000000, 0x3f800000, 0x3f000000, 0x3e000000)), - ('tri_g1a_nsa', 'TRI2 mirrored leaf hit +z', 'fan_mirrored', 0x09090909, 2, - (0x42c80000, 0xbfe00000, 0x40080000, 0xbf800000, 0x00000000, 0x00000000, 0x3f000000, 0x7f800000, 0x7f800000, 0x40000000), - (0x40800000, 0x3f000000, 0x3e800000, 0x3d800000)), - ('tri_g1a_nsa', 'TRI3 mirrored leaf hit +z', 'fan_mirrored', 0x09090909, 3, - (0x42c80000, 0x3f000000, 0x40000000, 0xbf800000, 0x00000000, 0x00000000, 0x3f000000, 0x7f800000, 0x7f800000, 0x40000000), - (0x40800000, 0x3f000000, 0x3e000000, 0x3d800000)), - ('tri_g1a_nsa', 'TRI0 hit oblique +z', 'fan', 0x09090909, 0, - (0x42c80000, 0x00000000, 0xbe800000, 0xbf800000, 0x3e000000, 0x3d800000, 0x3f000000, 0x41000000, 0x41800000, 0x40000000), - (0xc1000000, 0xbf800000, 0xbe800000, 0xbe000000)), - ('tri_g1a_nsa', 'TRI0 hit oblique -z', 'fan', 0x09090909, 0, - (0x42c80000, 0x00000000, 0xbe800000, 0x40e00000, 0x3e000000, 0x3d800000, 0xbf000000, 0x41000000, 0x41800000, 0xc0000000), - (0x41000000, 0x3f800000, 0x3e800000, 0x3e000000)), - ('tri_g1a_nsa', 'TRI1 hit oblique +z', 'fan', 0x09090909, 1, - (0x42c80000, 0x40200000, 0x3f400000, 0xbf800000, 0x3e000000, 0x3d800000, 0x3f000000, 0x41000000, 0x41800000, 0x40000000), - (0xc1000000, 0xbf800000, 0xbf000000, 0xbe000000)), - ('tri_g1a_nsa', 'TRI1 hit oblique -z', 'fan', 0x09090909, 1, - (0x42c80000, 0x40200000, 0x3f400000, 0x40e00000, 0x3e000000, 0x3d800000, 0xbf000000, 0x41000000, 0x41800000, 0xc0000000), - (0x41000000, 0x3f800000, 0x3f000000, 0x3e000000)), - ('tri_g1a_nsa', 'TRI2 hit oblique +z', 'fan', 0x09090909, 2, - (0x42c80000, 0x3f400000, 0x3fd00000, 0xbf800000, 0x3e000000, 0x3d800000, 0x3f000000, 0x41000000, 0x41800000, 0x40000000), - (0xc0800000, 0xbf000000, 0xbe800000, 0xbd800000)), - ('tri_g1a_nsa', 'TRI2 hit oblique -z', 'fan', 0x09090909, 2, - (0x42c80000, 0x3f400000, 0x3fd00000, 0x40e00000, 0x3e000000, 0x3d800000, 0xbf000000, 0x41000000, 0x41800000, 0xc0000000), - (0x40800000, 0x3f000000, 0x3e800000, 0x3d800000)), - ('tri_g1a_nsa', 'TRI3 hit oblique +z', 'fan', 0x09090909, 3, - (0x42c80000, 0xbfc00000, 0x3fc00000, 0xbf800000, 0x3e000000, 0x3d800000, 0x3f000000, 0x41000000, 0x41800000, 0x40000000), - (0xc0800000, 0xbf000000, 0xbe000000, 0xbd800000)), - ('tri_g1a_nsa', 'TRI3 hit oblique -z', 'fan', 0x09090909, 3, - (0x42c80000, 0xbfc00000, 0x3fc00000, 0x40e00000, 0x3e000000, 0x3d800000, 0xbf000000, 0x41000000, 0x41800000, 0xc0000000), - (0x40800000, 0x3f000000, 0x3e000000, 0x3d800000)), - ('tri_g1a_nsa', 'cs_bvh scene triangle node 0x40', 'cs_bvh_tri', 0x00000009, 0, - (0x42c80000, 0x3e800000, 0x3e800000, 0x00000000, 0x00000000, 0x00000000, 0x3f800000, 0x7f800000, 0x7f800000, 0x3f800000), - (0xc1200000, 0xbf800000, 0xbe800000, 0xbe800000)), - ('tri_g1a_w64', 'TRI0 hit +z', 'fan', 0x09090909, 0, - (0x42c80000, 0x3f800000, 0x3e800000, 0xbf800000, 0x00000000, 0x00000000, 0x3f000000, 0x7f800000, 0x7f800000, 0x40000000), - (0xc1000000, 0xbf800000, 0xbe800000, 0xbe000000)), - ('tri_g1a_w64', 'TRI0 hit -z (back)', 'fan', 0x09090909, 0, - (0x42c80000, 0x3f800000, 0x3e800000, 0x40e00000, 0x00000000, 0x00000000, 0xbf000000, 0x7f800000, 0x7f800000, 0xc0000000), - (0x41000000, 0x3f800000, 0x3e800000, 0x3e000000)), - ('tri_g1a_w64', 'TRI1 hit +z', 'fan', 0x09090909, 1, - (0x42c80000, 0x40600000, 0x3fa00000, 0xbf800000, 0x00000000, 0x00000000, 0x3f000000, 0x7f800000, 0x7f800000, 0x40000000), - (0xc1000000, 0xbf800000, 0xbf000000, 0xbe000000)), - ('tri_g1a_w64', 'TRI1 hit -z (back)', 'fan', 0x09090909, 1, - (0x42c80000, 0x40600000, 0x3fa00000, 0x40e00000, 0x00000000, 0x00000000, 0xbf000000, 0x7f800000, 0x7f800000, 0xc0000000), - (0x41000000, 0x3f800000, 0x3f000000, 0x3e000000)), - ('tri_g1a_w64', 'TRI2 hit +z', 'fan', 0x09090909, 2, - (0x42c80000, 0x3fe00000, 0x40080000, 0xbf800000, 0x00000000, 0x00000000, 0x3f000000, 0x7f800000, 0x7f800000, 0x40000000), - (0xc0800000, 0xbf000000, 0xbe800000, 0xbd800000)), - ('tri_g1a_w64', 'TRI2 hit -z (back)', 'fan', 0x09090909, 2, - (0x42c80000, 0x3fe00000, 0x40080000, 0x40e00000, 0x00000000, 0x00000000, 0xbf000000, 0x7f800000, 0x7f800000, 0xc0000000), - (0x40800000, 0x3f000000, 0x3e800000, 0x3d800000)), - ('tri_g1a_w64', 'TRI3 hit +z', 'fan', 0x09090909, 3, - (0x42c80000, 0xbf000000, 0x40000000, 0xbf800000, 0x00000000, 0x00000000, 0x3f000000, 0x7f800000, 0x7f800000, 0x40000000), - (0xc0800000, 0xbf000000, 0xbe000000, 0xbd800000)), - ('tri_g1a_w64', 'TRI3 hit -z (back)', 'fan', 0x09090909, 3, - (0x42c80000, 0xbf000000, 0x40000000, 0x40e00000, 0x00000000, 0x00000000, 0xbf000000, 0x7f800000, 0x7f800000, 0xc0000000), - (0x40800000, 0x3f000000, 0x3e000000, 0x3d800000)), - ('tri_g1a_w64', "TRI0 miss (+z at TRI1's point)", 'fan', 0x09090909, 0, - (0x42c80000, 0x40600000, 0x3fa00000, 0xbf800000, 0x00000000, 0x00000000, 0x3f000000, 0x7f800000, 0x7f800000, 0x40000000), - (0xff800000, 0xbf800000, 0xbf600000, 0xbf200000)), - ('tri_g1a_w64', "TRI1 miss (+z at TRI2's point)", 'fan', 0x09090909, 1, - (0x42c80000, 0x3fe00000, 0x40080000, 0xbf800000, 0x00000000, 0x00000000, 0x3f000000, 0x7f800000, 0x7f800000, 0x40000000), - (0xff800000, 0xbf800000, 0xbf000000, 0xbf100000)), - ('tri_g1a_w64', "TRI2 miss (+z at TRI3's point)", 'fan', 0x09090909, 2, - (0x42c80000, 0xbf000000, 0x40000000, 0xbf800000, 0x00000000, 0x00000000, 0x3f000000, 0x7f800000, 0x7f800000, 0x40000000), - (0xff800000, 0xbf000000, 0x3d800000, 0x00000000)), - ('tri_g1a_w64', "TRI3 miss (+z at TRI0's point)", 'fan', 0x09090909, 3, - (0x42c80000, 0x3f800000, 0x3e800000, 0xbf800000, 0x00000000, 0x00000000, 0x3f000000, 0x7f800000, 0x7f800000, 0x40000000), - (0xff800000, 0xbf000000, 0x3e800000, 0xbea00000)), - ('tri_g1a_w64', 'TRI0 mirrored leaf hit +z', 'fan_mirrored', 0x09090909, 0, - (0x42c80000, 0xbf800000, 0x3e800000, 0xbf800000, 0x00000000, 0x00000000, 0x3f000000, 0x7f800000, 0x7f800000, 0x40000000), - (0x41000000, 0x3f800000, 0x3e800000, 0x3e000000)), - ('tri_g1a_w64', 'TRI1 mirrored leaf hit +z', 'fan_mirrored', 0x09090909, 1, - (0x42c80000, 0xc0600000, 0x3fa00000, 0xbf800000, 0x00000000, 0x00000000, 0x3f000000, 0x7f800000, 0x7f800000, 0x40000000), - (0x41000000, 0x3f800000, 0x3f000000, 0x3e000000)), - ('tri_g1a_w64', 'TRI2 mirrored leaf hit +z', 'fan_mirrored', 0x09090909, 2, - (0x42c80000, 0xbfe00000, 0x40080000, 0xbf800000, 0x00000000, 0x00000000, 0x3f000000, 0x7f800000, 0x7f800000, 0x40000000), - (0x40800000, 0x3f000000, 0x3e800000, 0x3d800000)), - ('tri_g1a_w64', 'TRI3 mirrored leaf hit +z', 'fan_mirrored', 0x09090909, 3, - (0x42c80000, 0x3f000000, 0x40000000, 0xbf800000, 0x00000000, 0x00000000, 0x3f000000, 0x7f800000, 0x7f800000, 0x40000000), - (0x40800000, 0x3f000000, 0x3e000000, 0x3d800000)), - ('tri_g1a_w64', 'TRI0 hit oblique +z', 'fan', 0x09090909, 0, - (0x42c80000, 0x00000000, 0xbe800000, 0xbf800000, 0x3e000000, 0x3d800000, 0x3f000000, 0x41000000, 0x41800000, 0x40000000), - (0xc1000000, 0xbf800000, 0xbe800000, 0xbe000000)), - ('tri_g1a_w64', 'TRI0 hit oblique -z', 'fan', 0x09090909, 0, - (0x42c80000, 0x00000000, 0xbe800000, 0x40e00000, 0x3e000000, 0x3d800000, 0xbf000000, 0x41000000, 0x41800000, 0xc0000000), - (0x41000000, 0x3f800000, 0x3e800000, 0x3e000000)), - ('tri_g1a_w64', 'TRI1 hit oblique +z', 'fan', 0x09090909, 1, - (0x42c80000, 0x40200000, 0x3f400000, 0xbf800000, 0x3e000000, 0x3d800000, 0x3f000000, 0x41000000, 0x41800000, 0x40000000), - (0xc1000000, 0xbf800000, 0xbf000000, 0xbe000000)), - ('tri_g1a_w64', 'TRI1 hit oblique -z', 'fan', 0x09090909, 1, - (0x42c80000, 0x40200000, 0x3f400000, 0x40e00000, 0x3e000000, 0x3d800000, 0xbf000000, 0x41000000, 0x41800000, 0xc0000000), - (0x41000000, 0x3f800000, 0x3f000000, 0x3e000000)), - ('tri_g1a_w64', 'TRI2 hit oblique +z', 'fan', 0x09090909, 2, - (0x42c80000, 0x3f400000, 0x3fd00000, 0xbf800000, 0x3e000000, 0x3d800000, 0x3f000000, 0x41000000, 0x41800000, 0x40000000), - (0xc0800000, 0xbf000000, 0xbe800000, 0xbd800000)), - ('tri_g1a_w64', 'TRI2 hit oblique -z', 'fan', 0x09090909, 2, - (0x42c80000, 0x3f400000, 0x3fd00000, 0x40e00000, 0x3e000000, 0x3d800000, 0xbf000000, 0x41000000, 0x41800000, 0xc0000000), - (0x40800000, 0x3f000000, 0x3e800000, 0x3d800000)), - ('tri_g1a_w64', 'TRI3 hit oblique +z', 'fan', 0x09090909, 3, - (0x42c80000, 0xbfc00000, 0x3fc00000, 0xbf800000, 0x3e000000, 0x3d800000, 0x3f000000, 0x41000000, 0x41800000, 0x40000000), - (0xc0800000, 0xbf000000, 0xbe000000, 0xbd800000)), - ('tri_g1a_w64', 'TRI3 hit oblique -z', 'fan', 0x09090909, 3, - (0x42c80000, 0xbfc00000, 0x3fc00000, 0x40e00000, 0x3e000000, 0x3d800000, 0xbf000000, 0x41000000, 0x41800000, 0xc0000000), - (0x40800000, 0x3f000000, 0x3e000000, 0x3d800000)), - ('tri_g1a_w64', 'cs_bvh scene triangle node 0x40', 'cs_bvh_tri', 0x00000009, 0, - (0x42c80000, 0x3e800000, 0x3e800000, 0x00000000, 0x00000000, 0x00000000, 0x3f800000, 0x7f800000, 0x7f800000, 0x3f800000), - (0xc1200000, 0xbf800000, 0xbe800000, 0xbe800000)), - ('tri_g1b', 'TRI0 dominant +x', 'fan_x_dominant', 0x09090909, 0, - (0x42c80000, 0xbf800000, 0x3f800000, 0x3e800000, 0x3f000000, 0x00000000, 0x00000000, 0x40000000, 0x7f800000, 0x7f800000), - (0xc1000000, 0xbf800000, 0xbe800000, 0xbe000000)), - ('tri_g1b', 'TRI0 dominant -x', 'fan_x_dominant', 0x09090909, 0, - (0x42c80000, 0x40e00000, 0x3f800000, 0x3e800000, 0xbf000000, 0x00000000, 0x00000000, 0xc0000000, 0x7f800000, 0x7f800000), - (0x41000000, 0x3f800000, 0x3e800000, 0x3e000000)), - ('tri_g1b', 'TRI2 dominant +x', 'fan_x_dominant', 0x09090909, 2, - (0x42c80000, 0xbf800000, 0x3fe00000, 0x40080000, 0x3f000000, 0x00000000, 0x00000000, 0x40000000, 0x7f800000, 0x7f800000), - (0xc0800000, 0xbf000000, 0xbe800000, 0xbd800000)), - ('tri_g1b', 'TRI2 dominant -x', 'fan_x_dominant', 0x09090909, 2, - (0x42c80000, 0x40e00000, 0x3fe00000, 0x40080000, 0xbf000000, 0x00000000, 0x00000000, 0xc0000000, 0x7f800000, 0x7f800000), - (0x40800000, 0x3f000000, 0x3e800000, 0x3d800000)), - ('tri_g1b', 'TRI0 dominant +y', 'fan_y_dominant', 0x09090909, 0, - (0x42c80000, 0x3e800000, 0xbf800000, 0x3f800000, 0x00000000, 0x3f000000, 0x00000000, 0x7f800000, 0x40000000, 0x7f800000), - (0xc1000000, 0xbf800000, 0xbe800000, 0xbe000000)), - ('tri_g1b', 'TRI0 dominant -y', 'fan_y_dominant', 0x09090909, 0, - (0x42c80000, 0x3e800000, 0x40e00000, 0x3f800000, 0x00000000, 0xbf000000, 0x00000000, 0x7f800000, 0xc0000000, 0x7f800000), - (0x41000000, 0x3f800000, 0x3e800000, 0x3e000000)), - ('tri_g1b', 'TRI2 dominant +y', 'fan_y_dominant', 0x09090909, 2, - (0x42c80000, 0x40080000, 0xbf800000, 0x3fe00000, 0x00000000, 0x3f000000, 0x00000000, 0x7f800000, 0x40000000, 0x7f800000), - (0xc0800000, 0xbf000000, 0xbe800000, 0xbd800000)), - ('tri_g1b', 'TRI2 dominant -y', 'fan_y_dominant', 0x09090909, 2, - (0x42c80000, 0x40080000, 0x40e00000, 0x3fe00000, 0x00000000, 0xbf000000, 0x00000000, 0x7f800000, 0xc0000000, 0x7f800000), - (0x40800000, 0x3f000000, 0x3e800000, 0x3d800000)), - ('tri_g1b', 'TRI0 kz tie |dx|=|dz|', 'fan', 0x09090909, 0, - (0x42c80000, 0xc0400000, 0x3e800000, 0xbf800000, 0x3f000000, 0x00000000, 0x3f000000, 0x40000000, 0x7f800000, 0x40000000), - (0xc1000000, 0xbf800000, 0xbe800000, 0xbe000000)), - ('tri_g1b', 'TRI0 kz tie |dy|=|dz|', 'fan', 0x09090909, 0, - (0x42c80000, 0x3f800000, 0xc0700000, 0xbf800000, 0x00000000, 0x3f000000, 0x3f000000, 0x7f800000, 0x40000000, 0x40000000), - (0xc1000000, 0xbf800000, 0xbe800000, 0xbe000000)), - ('tri_g1b', 'TRI0 kz tie |dx|=|dy|=|dz|', 'fan', 0x09090909, 0, - (0x42c80000, 0xc0400000, 0xc0700000, 0xbf800000, 0x3f000000, 0x3f000000, 0x3f000000, 0x40000000, 0x40000000, 0x40000000), - (0xc1000000, 0xbf800000, 0xbe800000, 0xbe000000)), - ('tri_g1b', 'TRI0 kz tie |dx|=|dy|>|dz|', 'fan', 0x09090909, 0, - (0x42c80000, 0xc0e00000, 0xc0f80000, 0xbf800000, 0x3f000000, 0x3f000000, 0x3e800000, 0x40000000, 0x40000000, 0x40800000), - (0xc1000000, 0xbf000000, 0xbe000000, 0xbd800000)), - ('tri_g1b', 'TRI0 mirrored leaf hit -z', 'fan_mirrored', 0x09090909, 0, - (0x42c80000, 0xbf800000, 0x3e800000, 0x40e00000, 0x00000000, 0x00000000, 0xbf000000, 0x7f800000, 0x7f800000, 0xc0000000), - (0xc1000000, 0xbf800000, 0xbe800000, 0xbe000000)), - ('tri_g1b', 'TRI1 mirrored leaf hit -z', 'fan_mirrored', 0x09090909, 1, - (0x42c80000, 0xc0600000, 0x3fa00000, 0x40e00000, 0x00000000, 0x00000000, 0xbf000000, 0x7f800000, 0x7f800000, 0xc0000000), - (0xc1000000, 0xbf800000, 0xbf000000, 0xbe000000)), - ('tri_g1b', 'TRI2 mirrored leaf hit -z', 'fan_mirrored', 0x09090909, 2, - (0x42c80000, 0xbfe00000, 0x40080000, 0x40e00000, 0x00000000, 0x00000000, 0xbf000000, 0x7f800000, 0x7f800000, 0xc0000000), - (0xc0800000, 0xbf000000, 0xbe800000, 0xbd800000)), - ('tri_g1b', 'TRI3 mirrored leaf hit -z', 'fan_mirrored', 0x09090909, 3, - (0x42c80000, 0x3f000000, 0x40000000, 0x40e00000, 0x00000000, 0x00000000, 0xbf000000, 0x7f800000, 0x7f800000, 0xc0000000), - (0xc0800000, 0xbf000000, 0xbe000000, 0xbd800000)), - ('tri_g1c', 'control: TRI0 hit +z', 'fan', 0x09090909, 0, - (0x42c80000, 0x3f800000, 0x3e800000, 0xbf800000, 0x00000000, 0x00000000, 0x3f000000, 0x7f800000, 0x7f800000, 0x40000000), - (0xc1000000, 0xbf800000, 0xbe800000, 0xbe000000)), - ('tri_g1c', 'control: TRI0 hit -z (back)', 'fan', 0x09090909, 0, - (0x42c80000, 0x3f800000, 0x3e800000, 0x40e00000, 0x00000000, 0x00000000, 0xbf000000, 0x7f800000, 0x7f800000, 0xc0000000), - (0x41000000, 0x3f800000, 0x3e800000, 0x3e000000)), - ('tri_g1c', 'TRI0 miss beyond edge opposite v0 +z (det<0)', 'fan', 0x09090909, 0, - (0x42c80000, 0x40400000, 0x3f800000, 0xbf800000, 0x00000000, 0x00000000, 0x3f000000, 0x7f800000, 0x7f800000, 0x40000000), - (0xff800000, 0xbf800000, 0xbf400000, 0xbf000000)), - ('tri_g1c', 'TRI0 miss beyond edge opposite v0 -z (det>0)', 'fan', 0x09090909, 0, - (0x42c80000, 0x40400000, 0x3f800000, 0x40e00000, 0x00000000, 0x00000000, 0xbf000000, 0x7f800000, 0x7f800000, 0xc0000000), - (0x7f800000, 0x3f800000, 0x3f400000, 0x3f000000)), - ('tri_g1c', 'TRI0 miss beyond edge opposite v1 +z (det<0)', 'fan', 0x09090909, 0, - (0x42c80000, 0xbf800000, 0x3f800000, 0xbf800000, 0x00000000, 0x00000000, 0x3f000000, 0x7f800000, 0x7f800000, 0x40000000), - (0xff800000, 0xbf800000, 0x3e800000, 0xbf000000)), - ('tri_g1c', 'TRI0 miss beyond edge opposite v1 -z (det>0)', 'fan', 0x09090909, 0, - (0x42c80000, 0xbf800000, 0x3f800000, 0x40e00000, 0x00000000, 0x00000000, 0xbf000000, 0x7f800000, 0x7f800000, 0xc0000000), - (0x7f800000, 0x3f800000, 0xbe800000, 0x3f000000)), - ('tri_g1c', 'TRI0 miss beyond edge opposite v2 +z (det<0)', 'fan', 0x09090909, 0, - (0x42c80000, 0x40000000, 0xbf000000, 0xbf800000, 0x00000000, 0x00000000, 0x3f000000, 0x7f800000, 0x7f800000, 0x40000000), - (0xff800000, 0xbf800000, 0xbf000000, 0x3e800000)), - ('tri_g1c', 'TRI0 miss beyond edge opposite v2 -z (det>0)', 'fan', 0x09090909, 0, - (0x42c80000, 0x40000000, 0xbf000000, 0x40e00000, 0x00000000, 0x00000000, 0xbf000000, 0x7f800000, 0x7f800000, 0xc0000000), - (0x7f800000, 0x3f800000, 0x3f000000, 0xbe800000)), - ('tri_g1c', 'TRI0 mirrored leaf miss beyond edge opposite v0 +z (det>0)', 'fan_mirrored', 0x09090909, 0, - (0x42c80000, 0xc0400000, 0x3f800000, 0xbf800000, 0x00000000, 0x00000000, 0x3f000000, 0x7f800000, 0x7f800000, 0x40000000), - (0x7f800000, 0x3f800000, 0x3f400000, 0x3f000000)), - ('tri_g1c', 'TRI1 miss beyond edge opposite v0 +z (det<0)', 'fan', 0x09090909, 1, - (0x42c80000, 0x40000000, 0x40200000, 0xbf800000, 0x00000000, 0x00000000, 0x3f000000, 0x7f800000, 0x7f800000, 0x40000000), - (0xff800000, 0xbf800000, 0xbf400000, 0xbf000000)), - ('tri_g1c', 'TRI1 miss beyond edge opposite v0 -z (det>0)', 'fan', 0x09090909, 1, - (0x42c80000, 0x40000000, 0x40200000, 0x40e00000, 0x00000000, 0x00000000, 0xbf000000, 0x7f800000, 0x7f800000, 0xc0000000), - (0x7f800000, 0x3f800000, 0x3f400000, 0x3f000000)), - ('tri_g1c', 'TRI1 miss beyond edge opposite v1 +z (det<0)', 'fan', 0x09090909, 1, - (0x42c80000, 0x40000000, 0x3f000000, 0xbf800000, 0x00000000, 0x00000000, 0x3f000000, 0x7f800000, 0x7f800000, 0x40000000), - (0xff800000, 0xbf800000, 0x3e800000, 0xbf000000)), - ('tri_g1c', 'TRI1 miss beyond edge opposite v1 -z (det>0)', 'fan', 0x09090909, 1, - (0x42c80000, 0x40000000, 0x3f000000, 0x40e00000, 0x00000000, 0x00000000, 0xbf000000, 0x7f800000, 0x7f800000, 0xc0000000), - (0x7f800000, 0x3f800000, 0xbe800000, 0x3f000000)), - ('tri_g1c', 'TRI1 miss beyond edge opposite v2 +z (det<0)', 'fan', 0x09090909, 1, - (0x42c80000, 0x40a00000, 0x3f000000, 0xbf800000, 0x00000000, 0x00000000, 0x3f000000, 0x7f800000, 0x7f800000, 0x40000000), - (0xff800000, 0xbf800000, 0xbf000000, 0x3e800000)), - ('tri_g1c', 'TRI1 miss beyond edge opposite v2 -z (det>0)', 'fan', 0x09090909, 1, - (0x42c80000, 0x40a00000, 0x3f000000, 0x40e00000, 0x00000000, 0x00000000, 0xbf000000, 0x7f800000, 0x7f800000, 0xc0000000), - (0x7f800000, 0x3f800000, 0x3f000000, 0xbe800000)), - ('tri_g1c', 'TRI1 mirrored leaf miss beyond edge opposite v0 +z (det>0)', 'fan_mirrored', 0x09090909, 1, - (0x42c80000, 0xc0000000, 0x40200000, 0xbf800000, 0x00000000, 0x00000000, 0x3f000000, 0x7f800000, 0x7f800000, 0x40000000), - (0x7f800000, 0x3f800000, 0x3f400000, 0x3f000000)), - ('tri_g1c', 'TRI2 miss beyond edge opposite v0 +z (det<0)', 'fan', 0x09090909, 2, - (0x42c80000, 0x40000000, 0x40200000, 0xbf800000, 0x00000000, 0x00000000, 0x3f000000, 0x7f800000, 0x7f800000, 0x40000000), - (0xff800000, 0xbf000000, 0xbec00000, 0xbe800000)), - ('tri_g1c', 'TRI2 miss beyond edge opposite v0 -z (det>0)', 'fan', 0x09090909, 2, - (0x42c80000, 0x40000000, 0x40200000, 0x40e00000, 0x00000000, 0x00000000, 0xbf000000, 0x7f800000, 0x7f800000, 0xc0000000), - (0x7f800000, 0x3f000000, 0x3ec00000, 0x3e800000)), - ('tri_g1c', 'TRI2 miss beyond edge opposite v1 +z (det<0)', 'fan', 0x09090909, 2, - (0x42c80000, 0xc0000000, 0x40200000, 0xbf800000, 0x00000000, 0x00000000, 0x3f000000, 0x7f800000, 0x7f800000, 0x40000000), - (0xff800000, 0xbf000000, 0x3e000000, 0xbe800000)), - ('tri_g1c', 'TRI2 miss beyond edge opposite v1 -z (det>0)', 'fan', 0x09090909, 2, - (0x42c80000, 0xc0000000, 0x40200000, 0x40e00000, 0x00000000, 0x00000000, 0xbf000000, 0x7f800000, 0x7f800000, 0xc0000000), - (0x7f800000, 0x3f000000, 0xbe000000, 0x3e800000)), - ('tri_g1c', 'TRI2 miss beyond edge opposite v2 +z (det<0)', 'fan', 0x09090909, 2, - (0x42c80000, 0x40200000, 0x3fe00000, 0xbf800000, 0x00000000, 0x00000000, 0x3f000000, 0x7f800000, 0x7f800000, 0x40000000), - (0xff800000, 0xbf000000, 0xbe800000, 0x3e000000)), - ('tri_g1c', 'TRI2 miss beyond edge opposite v2 -z (det>0)', 'fan', 0x09090909, 2, - (0x42c80000, 0x40200000, 0x3fe00000, 0x40e00000, 0x00000000, 0x00000000, 0xbf000000, 0x7f800000, 0x7f800000, 0xc0000000), - (0x7f800000, 0x3f000000, 0x3e800000, 0xbe000000)), - ('tri_g1c', 'TRI2 mirrored leaf miss beyond edge opposite v0 +z (det>0)', 'fan_mirrored', 0x09090909, 2, - (0x42c80000, 0xc0000000, 0x40200000, 0xbf800000, 0x00000000, 0x00000000, 0x3f000000, 0x7f800000, 0x7f800000, 0x40000000), - (0x7f800000, 0x3f000000, 0x3ec00000, 0x3e800000)), - ('tri_g1c', 'TRI3 miss beyond edge opposite v0 +z (det<0)', 'fan', 0x09090909, 3, - (0x42c80000, 0xbfc00000, 0x3fe00000, 0xbf800000, 0x00000000, 0x00000000, 0x3f000000, 0x7f800000, 0x7f800000, 0x40000000), - (0xff800000, 0xbf000000, 0xbec00000, 0xbe800000)), - ('tri_g1c', 'TRI3 miss beyond edge opposite v0 -z (det>0)', 'fan', 0x09090909, 3, - (0x42c80000, 0xbfc00000, 0x3fe00000, 0x40e00000, 0x00000000, 0x00000000, 0xbf000000, 0x7f800000, 0x7f800000, 0xc0000000), - (0x7f800000, 0x3f000000, 0x3ec00000, 0x3e800000)), - ('tri_g1c', 'TRI3 miss beyond edge opposite v1 +z (det<0)', 'fan', 0x09090909, 3, - (0x42c80000, 0x3f000000, 0x3f400000, 0xbf800000, 0x00000000, 0x00000000, 0x3f000000, 0x7f800000, 0x7f800000, 0x40000000), - (0xff800000, 0xbf000000, 0x3e000000, 0xbe800000)), - ('tri_g1c', 'TRI3 miss beyond edge opposite v1 -z (det>0)', 'fan', 0x09090909, 3, - (0x42c80000, 0x3f000000, 0x3f400000, 0x40e00000, 0x00000000, 0x00000000, 0xbf000000, 0x7f800000, 0x7f800000, 0xc0000000), - (0x7f800000, 0x3f000000, 0xbe000000, 0x3e800000)), - ('tri_g1c', 'TRI3 miss beyond edge opposite v2 +z (det<0)', 'fan', 0x09090909, 3, - (0x42c80000, 0xbf800000, 0x40400000, 0xbf800000, 0x00000000, 0x00000000, 0x3f000000, 0x7f800000, 0x7f800000, 0x40000000), - (0xff800000, 0xbf000000, 0xbe800000, 0x3e000000)), - ('tri_g1c', 'TRI3 miss beyond edge opposite v2 -z (det>0)', 'fan', 0x09090909, 3, - (0x42c80000, 0xbf800000, 0x40400000, 0x40e00000, 0x00000000, 0x00000000, 0xbf000000, 0x7f800000, 0x7f800000, 0xc0000000), - (0x7f800000, 0x3f000000, 0x3e800000, 0xbe000000)), - ('tri_g1c', 'TRI3 mirrored leaf miss beyond edge opposite v0 +z (det>0)', 'fan_mirrored', 0x09090909, 3, - (0x42c80000, 0x3fc00000, 0x3fe00000, 0xbf800000, 0x00000000, 0x00000000, 0x3f000000, 0x7f800000, 0x7f800000, 0x40000000), - (0x7f800000, 0x3f000000, 0x3ec00000, 0x3e800000)), - ('tri_g2a', 'TRI0 byte0=0x00 others 0x06', 'fan', 0x06060600, 0, - (0x42c80000, 0x3f800000, 0x3e800000, 0xbf800000, 0x00000000, 0x00000000, 0x3f000000, 0x7f800000, 0x7f800000, 0x40000000), - (0xc1000000, 0xbf800000, 0xbf200000, 0xbf200000)), - ('tri_g2a', 'TRI0 byte0=0x01 others 0x06', 'fan', 0x06060601, 0, - (0x42c80000, 0x3f800000, 0x3e800000, 0xbf800000, 0x00000000, 0x00000000, 0x3f000000, 0x7f800000, 0x7f800000, 0x40000000), - (0xc1000000, 0xbf800000, 0xbe800000, 0xbf200000)), - ('tri_g2a', 'TRI0 byte0=0x02 others 0x06', 'fan', 0x06060602, 0, - (0x42c80000, 0x3f800000, 0x3e800000, 0xbf800000, 0x00000000, 0x00000000, 0x3f000000, 0x7f800000, 0x7f800000, 0x40000000), - (0xc1000000, 0xbf800000, 0xbe000000, 0xbf200000)), - ('tri_g2a', 'TRI0 byte0=0x03 others 0x06', 'fan', 0x06060603, 0, - (0x42c80000, 0x3f800000, 0x3e800000, 0xbf800000, 0x00000000, 0x00000000, 0x3f000000, 0x7f800000, 0x7f800000, 0x40000000), - (0xc1000000, 0xbf800000, 0xbf200000, 0xbf200000)), - ('tri_g2a', 'TRI0 byte0=0x04 others 0x06', 'fan', 0x06060604, 0, - (0x42c80000, 0x3f800000, 0x3e800000, 0xbf800000, 0x00000000, 0x00000000, 0x3f000000, 0x7f800000, 0x7f800000, 0x40000000), - (0xc1000000, 0xbf800000, 0xbf200000, 0xbe800000)), - ('tri_g2a', 'TRI0 byte0=0x05 others 0x06', 'fan', 0x06060605, 0, - (0x42c80000, 0x3f800000, 0x3e800000, 0xbf800000, 0x00000000, 0x00000000, 0x3f000000, 0x7f800000, 0x7f800000, 0x40000000), - (0xc1000000, 0xbf800000, 0xbe800000, 0xbe800000)), - ('tri_g2a', 'TRI0 byte0=0x06 others 0x06', 'fan', 0x06060606, 0, - (0x42c80000, 0x3f800000, 0x3e800000, 0xbf800000, 0x00000000, 0x00000000, 0x3f000000, 0x7f800000, 0x7f800000, 0x40000000), - (0xc1000000, 0xbf800000, 0xbe000000, 0xbe800000)), - ('tri_g2a', 'TRI0 byte0=0x07 others 0x06', 'fan', 0x06060607, 0, - (0x42c80000, 0x3f800000, 0x3e800000, 0xbf800000, 0x00000000, 0x00000000, 0x3f000000, 0x7f800000, 0x7f800000, 0x40000000), - (0xc1000000, 0xbf800000, 0xbf200000, 0xbe800000)), - ('tri_g2a', 'TRI0 byte0=0x08 others 0x06', 'fan', 0x06060608, 0, - (0x42c80000, 0x3f800000, 0x3e800000, 0xbf800000, 0x00000000, 0x00000000, 0x3f000000, 0x7f800000, 0x7f800000, 0x40000000), - (0xc1000000, 0xbf800000, 0xbf200000, 0xbe000000)), - ('tri_g2a', 'TRI0 byte0=0x09 others 0x06', 'fan', 0x06060609, 0, - (0x42c80000, 0x3f800000, 0x3e800000, 0xbf800000, 0x00000000, 0x00000000, 0x3f000000, 0x7f800000, 0x7f800000, 0x40000000), - (0xc1000000, 0xbf800000, 0xbe800000, 0xbe000000)), - ('tri_g2a', 'TRI0 byte0=0x0a others 0x06', 'fan', 0x0606060a, 0, - (0x42c80000, 0x3f800000, 0x3e800000, 0xbf800000, 0x00000000, 0x00000000, 0x3f000000, 0x7f800000, 0x7f800000, 0x40000000), - (0xc1000000, 0xbf800000, 0xbe000000, 0xbe000000)), - ('tri_g2a', 'TRI0 byte0=0x0b others 0x06', 'fan', 0x0606060b, 0, - (0x42c80000, 0x3f800000, 0x3e800000, 0xbf800000, 0x00000000, 0x00000000, 0x3f000000, 0x7f800000, 0x7f800000, 0x40000000), - (0xc1000000, 0xbf800000, 0xbf200000, 0xbe000000)), - ('tri_g2a', 'TRI0 byte0=0x0c others 0x06', 'fan', 0x0606060c, 0, - (0x42c80000, 0x3f800000, 0x3e800000, 0xbf800000, 0x00000000, 0x00000000, 0x3f000000, 0x7f800000, 0x7f800000, 0x40000000), - (0xc1000000, 0xbf800000, 0xbf200000, 0xbf200000)), - ('tri_g2a', 'TRI0 byte0=0x0d others 0x06', 'fan', 0x0606060d, 0, - (0x42c80000, 0x3f800000, 0x3e800000, 0xbf800000, 0x00000000, 0x00000000, 0x3f000000, 0x7f800000, 0x7f800000, 0x40000000), - (0xc1000000, 0xbf800000, 0xbe800000, 0xbf200000)), - ('tri_g2a', 'TRI0 byte0=0x0e others 0x06', 'fan', 0x0606060e, 0, - (0x42c80000, 0x3f800000, 0x3e800000, 0xbf800000, 0x00000000, 0x00000000, 0x3f000000, 0x7f800000, 0x7f800000, 0x40000000), - (0xc1000000, 0xbf800000, 0xbe000000, 0xbf200000)), - ('tri_g2a', 'TRI0 byte0=0x0f others 0x06', 'fan', 0x0606060f, 0, - (0x42c80000, 0x3f800000, 0x3e800000, 0xbf800000, 0x00000000, 0x00000000, 0x3f000000, 0x7f800000, 0x7f800000, 0x40000000), - (0xc1000000, 0xbf800000, 0xbf200000, 0xbf200000)), - ('tri_g2a', 'TRI1 byte1=0x00 others 0x06', 'fan', 0x06060006, 1, - (0x42c80000, 0x40600000, 0x3fa00000, 0xbf800000, 0x00000000, 0x00000000, 0x3f000000, 0x7f800000, 0x7f800000, 0x40000000), - (0xc1000000, 0xbf800000, 0xbec00000, 0xbec00000)), - ('tri_g2a', 'TRI1 byte1=0x01 others 0x06', 'fan', 0x06060106, 1, - (0x42c80000, 0x40600000, 0x3fa00000, 0xbf800000, 0x00000000, 0x00000000, 0x3f000000, 0x7f800000, 0x7f800000, 0x40000000), - (0xc1000000, 0xbf800000, 0xbf000000, 0xbec00000)), - ('tri_g2a', 'TRI1 byte1=0x02 others 0x06', 'fan', 0x06060206, 1, - (0x42c80000, 0x40600000, 0x3fa00000, 0xbf800000, 0x00000000, 0x00000000, 0x3f000000, 0x7f800000, 0x7f800000, 0x40000000), - (0xc1000000, 0xbf800000, 0xbe000000, 0xbec00000)), - ('tri_g2a', 'TRI1 byte1=0x03 others 0x06', 'fan', 0x06060306, 1, - (0x42c80000, 0x40600000, 0x3fa00000, 0xbf800000, 0x00000000, 0x00000000, 0x3f000000, 0x7f800000, 0x7f800000, 0x40000000), - (0xc1000000, 0xbf800000, 0xbec00000, 0xbec00000)), - ('tri_g2a', 'TRI1 byte1=0x04 others 0x06', 'fan', 0x06060406, 1, - (0x42c80000, 0x40600000, 0x3fa00000, 0xbf800000, 0x00000000, 0x00000000, 0x3f000000, 0x7f800000, 0x7f800000, 0x40000000), - (0xc1000000, 0xbf800000, 0xbec00000, 0xbf000000)), - ('tri_g2a', 'TRI1 byte1=0x05 others 0x06', 'fan', 0x06060506, 1, - (0x42c80000, 0x40600000, 0x3fa00000, 0xbf800000, 0x00000000, 0x00000000, 0x3f000000, 0x7f800000, 0x7f800000, 0x40000000), - (0xc1000000, 0xbf800000, 0xbf000000, 0xbf000000)), - ('tri_g2a', 'TRI1 byte1=0x06 others 0x06', 'fan', 0x06060606, 1, - (0x42c80000, 0x40600000, 0x3fa00000, 0xbf800000, 0x00000000, 0x00000000, 0x3f000000, 0x7f800000, 0x7f800000, 0x40000000), - (0xc1000000, 0xbf800000, 0xbe000000, 0xbf000000)), - ('tri_g2a', 'TRI1 byte1=0x07 others 0x06', 'fan', 0x06060706, 1, - (0x42c80000, 0x40600000, 0x3fa00000, 0xbf800000, 0x00000000, 0x00000000, 0x3f000000, 0x7f800000, 0x7f800000, 0x40000000), - (0xc1000000, 0xbf800000, 0xbec00000, 0xbf000000)), - ('tri_g2a', 'TRI1 byte1=0x08 others 0x06', 'fan', 0x06060806, 1, - (0x42c80000, 0x40600000, 0x3fa00000, 0xbf800000, 0x00000000, 0x00000000, 0x3f000000, 0x7f800000, 0x7f800000, 0x40000000), - (0xc1000000, 0xbf800000, 0xbec00000, 0xbe000000)), - ('tri_g2a', 'TRI1 byte1=0x09 others 0x06', 'fan', 0x06060906, 1, - (0x42c80000, 0x40600000, 0x3fa00000, 0xbf800000, 0x00000000, 0x00000000, 0x3f000000, 0x7f800000, 0x7f800000, 0x40000000), - (0xc1000000, 0xbf800000, 0xbf000000, 0xbe000000)), - ('tri_g2a', 'TRI1 byte1=0x0a others 0x06', 'fan', 0x06060a06, 1, - (0x42c80000, 0x40600000, 0x3fa00000, 0xbf800000, 0x00000000, 0x00000000, 0x3f000000, 0x7f800000, 0x7f800000, 0x40000000), - (0xc1000000, 0xbf800000, 0xbe000000, 0xbe000000)), - ('tri_g2a', 'TRI1 byte1=0x0b others 0x06', 'fan', 0x06060b06, 1, - (0x42c80000, 0x40600000, 0x3fa00000, 0xbf800000, 0x00000000, 0x00000000, 0x3f000000, 0x7f800000, 0x7f800000, 0x40000000), - (0xc1000000, 0xbf800000, 0xbec00000, 0xbe000000)), - ('tri_g2a', 'TRI1 byte1=0x0c others 0x06', 'fan', 0x06060c06, 1, - (0x42c80000, 0x40600000, 0x3fa00000, 0xbf800000, 0x00000000, 0x00000000, 0x3f000000, 0x7f800000, 0x7f800000, 0x40000000), - (0xc1000000, 0xbf800000, 0xbec00000, 0xbec00000)), - ('tri_g2a', 'TRI1 byte1=0x0d others 0x06', 'fan', 0x06060d06, 1, - (0x42c80000, 0x40600000, 0x3fa00000, 0xbf800000, 0x00000000, 0x00000000, 0x3f000000, 0x7f800000, 0x7f800000, 0x40000000), - (0xc1000000, 0xbf800000, 0xbf000000, 0xbec00000)), - ('tri_g2a', 'TRI1 byte1=0x0e others 0x06', 'fan', 0x06060e06, 1, - (0x42c80000, 0x40600000, 0x3fa00000, 0xbf800000, 0x00000000, 0x00000000, 0x3f000000, 0x7f800000, 0x7f800000, 0x40000000), - (0xc1000000, 0xbf800000, 0xbe000000, 0xbec00000)), - ('tri_g2a', 'TRI1 byte1=0x0f others 0x06', 'fan', 0x06060f06, 1, - (0x42c80000, 0x40600000, 0x3fa00000, 0xbf800000, 0x00000000, 0x00000000, 0x3f000000, 0x7f800000, 0x7f800000, 0x40000000), - (0xc1000000, 0xbf800000, 0xbec00000, 0xbec00000)), - ('tri_g2b', 'TRI2 byte2=0x00 others 0x06', 'fan', 0x06000606, 2, - (0x42c80000, 0x3fe00000, 0x40080000, 0xbf800000, 0x00000000, 0x00000000, 0x3f000000, 0x7f800000, 0x7f800000, 0x40000000), - (0xc0800000, 0xbf000000, 0xbe400000, 0xbe400000)), - ('tri_g2b', 'TRI2 byte2=0x01 others 0x06', 'fan', 0x06010606, 2, - (0x42c80000, 0x3fe00000, 0x40080000, 0xbf800000, 0x00000000, 0x00000000, 0x3f000000, 0x7f800000, 0x7f800000, 0x40000000), - (0xc0800000, 0xbf000000, 0xbe800000, 0xbe400000)), - ('tri_g2b', 'TRI2 byte2=0x02 others 0x06', 'fan', 0x06020606, 2, - (0x42c80000, 0x3fe00000, 0x40080000, 0xbf800000, 0x00000000, 0x00000000, 0x3f000000, 0x7f800000, 0x7f800000, 0x40000000), - (0xc0800000, 0xbf000000, 0xbd800000, 0xbe400000)), - ('tri_g2b', 'TRI2 byte2=0x03 others 0x06', 'fan', 0x06030606, 2, - (0x42c80000, 0x3fe00000, 0x40080000, 0xbf800000, 0x00000000, 0x00000000, 0x3f000000, 0x7f800000, 0x7f800000, 0x40000000), - (0xc0800000, 0xbf000000, 0xbe400000, 0xbe400000)), - ('tri_g2b', 'TRI2 byte2=0x04 others 0x06', 'fan', 0x06040606, 2, - (0x42c80000, 0x3fe00000, 0x40080000, 0xbf800000, 0x00000000, 0x00000000, 0x3f000000, 0x7f800000, 0x7f800000, 0x40000000), - (0xc0800000, 0xbf000000, 0xbe400000, 0xbe800000)), - ('tri_g2b', 'TRI2 byte2=0x05 others 0x06', 'fan', 0x06050606, 2, - (0x42c80000, 0x3fe00000, 0x40080000, 0xbf800000, 0x00000000, 0x00000000, 0x3f000000, 0x7f800000, 0x7f800000, 0x40000000), - (0xc0800000, 0xbf000000, 0xbe800000, 0xbe800000)), - ('tri_g2b', 'TRI2 byte2=0x06 others 0x06', 'fan', 0x06060606, 2, - (0x42c80000, 0x3fe00000, 0x40080000, 0xbf800000, 0x00000000, 0x00000000, 0x3f000000, 0x7f800000, 0x7f800000, 0x40000000), - (0xc0800000, 0xbf000000, 0xbd800000, 0xbe800000)), - ('tri_g2b', 'TRI2 byte2=0x07 others 0x06', 'fan', 0x06070606, 2, - (0x42c80000, 0x3fe00000, 0x40080000, 0xbf800000, 0x00000000, 0x00000000, 0x3f000000, 0x7f800000, 0x7f800000, 0x40000000), - (0xc0800000, 0xbf000000, 0xbe400000, 0xbe800000)), - ('tri_g2b', 'TRI2 byte2=0x08 others 0x06', 'fan', 0x06080606, 2, - (0x42c80000, 0x3fe00000, 0x40080000, 0xbf800000, 0x00000000, 0x00000000, 0x3f000000, 0x7f800000, 0x7f800000, 0x40000000), - (0xc0800000, 0xbf000000, 0xbe400000, 0xbd800000)), - ('tri_g2b', 'TRI2 byte2=0x09 others 0x06', 'fan', 0x06090606, 2, - (0x42c80000, 0x3fe00000, 0x40080000, 0xbf800000, 0x00000000, 0x00000000, 0x3f000000, 0x7f800000, 0x7f800000, 0x40000000), - (0xc0800000, 0xbf000000, 0xbe800000, 0xbd800000)), - ('tri_g2b', 'TRI2 byte2=0x0a others 0x06', 'fan', 0x060a0606, 2, - (0x42c80000, 0x3fe00000, 0x40080000, 0xbf800000, 0x00000000, 0x00000000, 0x3f000000, 0x7f800000, 0x7f800000, 0x40000000), - (0xc0800000, 0xbf000000, 0xbd800000, 0xbd800000)), - ('tri_g2b', 'TRI2 byte2=0x0b others 0x06', 'fan', 0x060b0606, 2, - (0x42c80000, 0x3fe00000, 0x40080000, 0xbf800000, 0x00000000, 0x00000000, 0x3f000000, 0x7f800000, 0x7f800000, 0x40000000), - (0xc0800000, 0xbf000000, 0xbe400000, 0xbd800000)), - ('tri_g2b', 'TRI2 byte2=0x0c others 0x06', 'fan', 0x060c0606, 2, - (0x42c80000, 0x3fe00000, 0x40080000, 0xbf800000, 0x00000000, 0x00000000, 0x3f000000, 0x7f800000, 0x7f800000, 0x40000000), - (0xc0800000, 0xbf000000, 0xbe400000, 0xbe400000)), - ('tri_g2b', 'TRI2 byte2=0x0d others 0x06', 'fan', 0x060d0606, 2, - (0x42c80000, 0x3fe00000, 0x40080000, 0xbf800000, 0x00000000, 0x00000000, 0x3f000000, 0x7f800000, 0x7f800000, 0x40000000), - (0xc0800000, 0xbf000000, 0xbe800000, 0xbe400000)), - ('tri_g2b', 'TRI2 byte2=0x0e others 0x06', 'fan', 0x060e0606, 2, - (0x42c80000, 0x3fe00000, 0x40080000, 0xbf800000, 0x00000000, 0x00000000, 0x3f000000, 0x7f800000, 0x7f800000, 0x40000000), - (0xc0800000, 0xbf000000, 0xbd800000, 0xbe400000)), - ('tri_g2b', 'TRI2 byte2=0x0f others 0x06', 'fan', 0x060f0606, 2, - (0x42c80000, 0x3fe00000, 0x40080000, 0xbf800000, 0x00000000, 0x00000000, 0x3f000000, 0x7f800000, 0x7f800000, 0x40000000), - (0xc0800000, 0xbf000000, 0xbe400000, 0xbe400000)), - ('tri_g2b', 'TRI3 byte3=0x00 others 0x06', 'fan', 0x00060606, 3, - (0x42c80000, 0xbf000000, 0x40000000, 0xbf800000, 0x00000000, 0x00000000, 0x3f000000, 0x7f800000, 0x7f800000, 0x40000000), - (0xc0800000, 0xbf000000, 0xbea00000, 0xbea00000)), - ('tri_g2b', 'TRI3 byte3=0x01 others 0x06', 'fan', 0x01060606, 3, - (0x42c80000, 0xbf000000, 0x40000000, 0xbf800000, 0x00000000, 0x00000000, 0x3f000000, 0x7f800000, 0x7f800000, 0x40000000), - (0xc0800000, 0xbf000000, 0xbe000000, 0xbea00000)), - ('tri_g2b', 'TRI3 byte3=0x02 others 0x06', 'fan', 0x02060606, 3, - (0x42c80000, 0xbf000000, 0x40000000, 0xbf800000, 0x00000000, 0x00000000, 0x3f000000, 0x7f800000, 0x7f800000, 0x40000000), - (0xc0800000, 0xbf000000, 0xbd800000, 0xbea00000)), - ('tri_g2b', 'TRI3 byte3=0x03 others 0x06', 'fan', 0x03060606, 3, - (0x42c80000, 0xbf000000, 0x40000000, 0xbf800000, 0x00000000, 0x00000000, 0x3f000000, 0x7f800000, 0x7f800000, 0x40000000), - (0xc0800000, 0xbf000000, 0xbea00000, 0xbea00000)), - ('tri_g2b', 'TRI3 byte3=0x04 others 0x06', 'fan', 0x04060606, 3, - (0x42c80000, 0xbf000000, 0x40000000, 0xbf800000, 0x00000000, 0x00000000, 0x3f000000, 0x7f800000, 0x7f800000, 0x40000000), - (0xc0800000, 0xbf000000, 0xbea00000, 0xbe000000)), - ('tri_g2b', 'TRI3 byte3=0x05 others 0x06', 'fan', 0x05060606, 3, - (0x42c80000, 0xbf000000, 0x40000000, 0xbf800000, 0x00000000, 0x00000000, 0x3f000000, 0x7f800000, 0x7f800000, 0x40000000), - (0xc0800000, 0xbf000000, 0xbe000000, 0xbe000000)), - ('tri_g2b', 'TRI3 byte3=0x06 others 0x06', 'fan', 0x06060606, 3, - (0x42c80000, 0xbf000000, 0x40000000, 0xbf800000, 0x00000000, 0x00000000, 0x3f000000, 0x7f800000, 0x7f800000, 0x40000000), - (0xc0800000, 0xbf000000, 0xbd800000, 0xbe000000)), - ('tri_g2b', 'TRI3 byte3=0x07 others 0x06', 'fan', 0x07060606, 3, - (0x42c80000, 0xbf000000, 0x40000000, 0xbf800000, 0x00000000, 0x00000000, 0x3f000000, 0x7f800000, 0x7f800000, 0x40000000), - (0xc0800000, 0xbf000000, 0xbea00000, 0xbe000000)), - ('tri_g2b', 'TRI3 byte3=0x08 others 0x06', 'fan', 0x08060606, 3, - (0x42c80000, 0xbf000000, 0x40000000, 0xbf800000, 0x00000000, 0x00000000, 0x3f000000, 0x7f800000, 0x7f800000, 0x40000000), - (0xc0800000, 0xbf000000, 0xbea00000, 0xbd800000)), - ('tri_g2b', 'TRI3 byte3=0x09 others 0x06', 'fan', 0x09060606, 3, - (0x42c80000, 0xbf000000, 0x40000000, 0xbf800000, 0x00000000, 0x00000000, 0x3f000000, 0x7f800000, 0x7f800000, 0x40000000), - (0xc0800000, 0xbf000000, 0xbe000000, 0xbd800000)), - ('tri_g2b', 'TRI3 byte3=0x0a others 0x06', 'fan', 0x0a060606, 3, - (0x42c80000, 0xbf000000, 0x40000000, 0xbf800000, 0x00000000, 0x00000000, 0x3f000000, 0x7f800000, 0x7f800000, 0x40000000), - (0xc0800000, 0xbf000000, 0xbd800000, 0xbd800000)), - ('tri_g2b', 'TRI3 byte3=0x0b others 0x06', 'fan', 0x0b060606, 3, - (0x42c80000, 0xbf000000, 0x40000000, 0xbf800000, 0x00000000, 0x00000000, 0x3f000000, 0x7f800000, 0x7f800000, 0x40000000), - (0xc0800000, 0xbf000000, 0xbea00000, 0xbd800000)), - ('tri_g2b', 'TRI3 byte3=0x0c others 0x06', 'fan', 0x0c060606, 3, - (0x42c80000, 0xbf000000, 0x40000000, 0xbf800000, 0x00000000, 0x00000000, 0x3f000000, 0x7f800000, 0x7f800000, 0x40000000), - (0xc0800000, 0xbf000000, 0xbea00000, 0xbea00000)), - ('tri_g2b', 'TRI3 byte3=0x0d others 0x06', 'fan', 0x0d060606, 3, - (0x42c80000, 0xbf000000, 0x40000000, 0xbf800000, 0x00000000, 0x00000000, 0x3f000000, 0x7f800000, 0x7f800000, 0x40000000), - (0xc0800000, 0xbf000000, 0xbe000000, 0xbea00000)), - ('tri_g2b', 'TRI3 byte3=0x0e others 0x06', 'fan', 0x0e060606, 3, - (0x42c80000, 0xbf000000, 0x40000000, 0xbf800000, 0x00000000, 0x00000000, 0x3f000000, 0x7f800000, 0x7f800000, 0x40000000), - (0xc0800000, 0xbf000000, 0xbd800000, 0xbea00000)), - ('tri_g2b', 'TRI3 byte3=0x0f others 0x06', 'fan', 0x0f060606, 3, - (0x42c80000, 0xbf000000, 0x40000000, 0xbf800000, 0x00000000, 0x00000000, 0x3f000000, 0x7f800000, 0x7f800000, 0x40000000), - (0xc0800000, 0xbf000000, 0xbea00000, 0xbea00000)), - ('tri_g2c', 'TRI0 byte0=0x09 +z', 'fan', 0x06060609, 0, - (0x42c80000, 0x3f800000, 0x3e800000, 0xbf800000, 0x00000000, 0x00000000, 0x3f000000, 0x7f800000, 0x7f800000, 0x40000000), - (0xc1000000, 0xbf800000, 0xbe800000, 0xbe000000)), - ('tri_g2c', 'TRI0 byte0=0x09 -z (back)', 'fan', 0x06060609, 0, - (0x42c80000, 0x3f800000, 0x3e800000, 0x40e00000, 0x00000000, 0x00000000, 0xbf000000, 0x7f800000, 0x7f800000, 0xc0000000), - (0x41000000, 0x3f800000, 0x3e800000, 0x3e000000)), - ('tri_g2c', 'TRI0 byte0=0x19 +z', 'fan', 0x06060619, 0, - (0x42c80000, 0x3f800000, 0x3e800000, 0xbf800000, 0x00000000, 0x00000000, 0x3f000000, 0x7f800000, 0x7f800000, 0x40000000), - (0xc1000000, 0xbf800000, 0xbe800000, 0xbe000000)), - ('tri_g2c', 'TRI0 byte0=0x19 -z (back)', 'fan', 0x06060619, 0, - (0x42c80000, 0x3f800000, 0x3e800000, 0x40e00000, 0x00000000, 0x00000000, 0xbf000000, 0x7f800000, 0x7f800000, 0xc0000000), - (0x41000000, 0x3f800000, 0x3e800000, 0x3e000000)), - ('tri_g2c', 'TRI0 byte0=0x29 +z', 'fan', 0x06060629, 0, - (0x42c80000, 0x3f800000, 0x3e800000, 0xbf800000, 0x00000000, 0x00000000, 0x3f000000, 0x7f800000, 0x7f800000, 0x40000000), - (0xc1000000, 0xbf800000, 0xbe800000, 0xbe000000)), - ('tri_g2c', 'TRI0 byte0=0x29 -z (back)', 'fan', 0x06060629, 0, - (0x42c80000, 0x3f800000, 0x3e800000, 0x40e00000, 0x00000000, 0x00000000, 0xbf000000, 0x7f800000, 0x7f800000, 0xc0000000), - (0x41000000, 0x3f800000, 0x3e800000, 0x3e000000)), - ('tri_g2c', 'TRI0 byte0=0x39 +z', 'fan', 0x06060639, 0, - (0x42c80000, 0x3f800000, 0x3e800000, 0xbf800000, 0x00000000, 0x00000000, 0x3f000000, 0x7f800000, 0x7f800000, 0x40000000), - (0xc1000000, 0xbf800000, 0xbe800000, 0xbe000000)), - ('tri_g2c', 'TRI0 byte0=0x39 -z (back)', 'fan', 0x06060639, 0, - (0x42c80000, 0x3f800000, 0x3e800000, 0x40e00000, 0x00000000, 0x00000000, 0xbf000000, 0x7f800000, 0x7f800000, 0xc0000000), - (0x41000000, 0x3f800000, 0x3e800000, 0x3e000000)), - ('tri_g2c', 'TRI0 byte0=0x49 +z', 'fan', 0x06060649, 0, - (0x42c80000, 0x3f800000, 0x3e800000, 0xbf800000, 0x00000000, 0x00000000, 0x3f000000, 0x7f800000, 0x7f800000, 0x40000000), - (0xc1000000, 0xbf800000, 0xbe800000, 0xbe000000)), - ('tri_g2c', 'TRI0 byte0=0x49 -z (back)', 'fan', 0x06060649, 0, - (0x42c80000, 0x3f800000, 0x3e800000, 0x40e00000, 0x00000000, 0x00000000, 0xbf000000, 0x7f800000, 0x7f800000, 0xc0000000), - (0x41000000, 0x3f800000, 0x3e800000, 0x3e000000)), - ('tri_g2c', 'TRI0 byte0=0x59 +z', 'fan', 0x06060659, 0, - (0x42c80000, 0x3f800000, 0x3e800000, 0xbf800000, 0x00000000, 0x00000000, 0x3f000000, 0x7f800000, 0x7f800000, 0x40000000), - (0xc1000000, 0xbf800000, 0xbe800000, 0xbe000000)), - ('tri_g2c', 'TRI0 byte0=0x59 -z (back)', 'fan', 0x06060659, 0, - (0x42c80000, 0x3f800000, 0x3e800000, 0x40e00000, 0x00000000, 0x00000000, 0xbf000000, 0x7f800000, 0x7f800000, 0xc0000000), - (0x41000000, 0x3f800000, 0x3e800000, 0x3e000000)), - ('tri_g2c', 'TRI0 byte0=0x69 +z', 'fan', 0x06060669, 0, - (0x42c80000, 0x3f800000, 0x3e800000, 0xbf800000, 0x00000000, 0x00000000, 0x3f000000, 0x7f800000, 0x7f800000, 0x40000000), - (0xc1000000, 0xbf800000, 0xbe800000, 0xbe000000)), - ('tri_g2c', 'TRI0 byte0=0x69 -z (back)', 'fan', 0x06060669, 0, - (0x42c80000, 0x3f800000, 0x3e800000, 0x40e00000, 0x00000000, 0x00000000, 0xbf000000, 0x7f800000, 0x7f800000, 0xc0000000), - (0x41000000, 0x3f800000, 0x3e800000, 0x3e000000)), - ('tri_g2c', 'TRI0 byte0=0x79 +z', 'fan', 0x06060679, 0, - (0x42c80000, 0x3f800000, 0x3e800000, 0xbf800000, 0x00000000, 0x00000000, 0x3f000000, 0x7f800000, 0x7f800000, 0x40000000), - (0xc1000000, 0xbf800000, 0xbe800000, 0xbe000000)), - ('tri_g2c', 'TRI0 byte0=0x79 -z (back)', 'fan', 0x06060679, 0, - (0x42c80000, 0x3f800000, 0x3e800000, 0x40e00000, 0x00000000, 0x00000000, 0xbf000000, 0x7f800000, 0x7f800000, 0xc0000000), - (0x41000000, 0x3f800000, 0x3e800000, 0x3e000000)), - ('tri_g2c', 'TRI0 byte0=0x89 +z', 'fan', 0x06060689, 0, - (0x42c80000, 0x3f800000, 0x3e800000, 0xbf800000, 0x00000000, 0x00000000, 0x3f000000, 0x7f800000, 0x7f800000, 0x40000000), - (0xc1000000, 0xbf800000, 0xbe800000, 0xbe000000)), - ('tri_g2c', 'TRI0 byte0=0x89 -z (back)', 'fan', 0x06060689, 0, - (0x42c80000, 0x3f800000, 0x3e800000, 0x40e00000, 0x00000000, 0x00000000, 0xbf000000, 0x7f800000, 0x7f800000, 0xc0000000), - (0x41000000, 0x3f800000, 0x3e800000, 0x3e000000)), - ('tri_g2c', 'TRI0 byte0=0x99 +z', 'fan', 0x06060699, 0, - (0x42c80000, 0x3f800000, 0x3e800000, 0xbf800000, 0x00000000, 0x00000000, 0x3f000000, 0x7f800000, 0x7f800000, 0x40000000), - (0xc1000000, 0xbf800000, 0xbe800000, 0xbe000000)), - ('tri_g2c', 'TRI0 byte0=0x99 -z (back)', 'fan', 0x06060699, 0, - (0x42c80000, 0x3f800000, 0x3e800000, 0x40e00000, 0x00000000, 0x00000000, 0xbf000000, 0x7f800000, 0x7f800000, 0xc0000000), - (0x41000000, 0x3f800000, 0x3e800000, 0x3e000000)), - ('tri_g2c', 'TRI0 byte0=0xa9 +z', 'fan', 0x060606a9, 0, - (0x42c80000, 0x3f800000, 0x3e800000, 0xbf800000, 0x00000000, 0x00000000, 0x3f000000, 0x7f800000, 0x7f800000, 0x40000000), - (0xc1000000, 0xbf800000, 0xbe800000, 0xbe000000)), - ('tri_g2c', 'TRI0 byte0=0xa9 -z (back)', 'fan', 0x060606a9, 0, - (0x42c80000, 0x3f800000, 0x3e800000, 0x40e00000, 0x00000000, 0x00000000, 0xbf000000, 0x7f800000, 0x7f800000, 0xc0000000), - (0x41000000, 0x3f800000, 0x3e800000, 0x3e000000)), - ('tri_g2c', 'TRI0 byte0=0xb9 +z', 'fan', 0x060606b9, 0, - (0x42c80000, 0x3f800000, 0x3e800000, 0xbf800000, 0x00000000, 0x00000000, 0x3f000000, 0x7f800000, 0x7f800000, 0x40000000), - (0xc1000000, 0xbf800000, 0xbe800000, 0xbe000000)), - ('tri_g2c', 'TRI0 byte0=0xb9 -z (back)', 'fan', 0x060606b9, 0, - (0x42c80000, 0x3f800000, 0x3e800000, 0x40e00000, 0x00000000, 0x00000000, 0xbf000000, 0x7f800000, 0x7f800000, 0xc0000000), - (0x41000000, 0x3f800000, 0x3e800000, 0x3e000000)), - ('tri_g2c', 'TRI0 byte0=0xc9 +z', 'fan', 0x060606c9, 0, - (0x42c80000, 0x3f800000, 0x3e800000, 0xbf800000, 0x00000000, 0x00000000, 0x3f000000, 0x7f800000, 0x7f800000, 0x40000000), - (0xc1000000, 0xbf800000, 0xbe800000, 0xbe000000)), - ('tri_g2c', 'TRI0 byte0=0xc9 -z (back)', 'fan', 0x060606c9, 0, - (0x42c80000, 0x3f800000, 0x3e800000, 0x40e00000, 0x00000000, 0x00000000, 0xbf000000, 0x7f800000, 0x7f800000, 0xc0000000), - (0x41000000, 0x3f800000, 0x3e800000, 0x3e000000)), - ('tri_g2c', 'TRI0 byte0=0xd9 +z', 'fan', 0x060606d9, 0, - (0x42c80000, 0x3f800000, 0x3e800000, 0xbf800000, 0x00000000, 0x00000000, 0x3f000000, 0x7f800000, 0x7f800000, 0x40000000), - (0xc1000000, 0xbf800000, 0xbe800000, 0xbe000000)), - ('tri_g2c', 'TRI0 byte0=0xd9 -z (back)', 'fan', 0x060606d9, 0, - (0x42c80000, 0x3f800000, 0x3e800000, 0x40e00000, 0x00000000, 0x00000000, 0xbf000000, 0x7f800000, 0x7f800000, 0xc0000000), - (0x41000000, 0x3f800000, 0x3e800000, 0x3e000000)), - ('tri_g2c', 'TRI0 byte0=0xe9 +z', 'fan', 0x060606e9, 0, - (0x42c80000, 0x3f800000, 0x3e800000, 0xbf800000, 0x00000000, 0x00000000, 0x3f000000, 0x7f800000, 0x7f800000, 0x40000000), - (0xc1000000, 0xbf800000, 0xbe800000, 0xbe000000)), - ('tri_g2c', 'TRI0 byte0=0xe9 -z (back)', 'fan', 0x060606e9, 0, - (0x42c80000, 0x3f800000, 0x3e800000, 0x40e00000, 0x00000000, 0x00000000, 0xbf000000, 0x7f800000, 0x7f800000, 0xc0000000), - (0x41000000, 0x3f800000, 0x3e800000, 0x3e000000)), - ('tri_g2c', 'TRI0 byte0=0xf9 +z', 'fan', 0x060606f9, 0, - (0x42c80000, 0x3f800000, 0x3e800000, 0xbf800000, 0x00000000, 0x00000000, 0x3f000000, 0x7f800000, 0x7f800000, 0x40000000), - (0xc1000000, 0xbf800000, 0xbe800000, 0xbe000000)), - ('tri_g2c', 'TRI0 byte0=0xf9 -z (back)', 'fan', 0x060606f9, 0, - (0x42c80000, 0x3f800000, 0x3e800000, 0x40e00000, 0x00000000, 0x00000000, 0xbf000000, 0x7f800000, 0x7f800000, 0xc0000000), - (0x41000000, 0x3f800000, 0x3e800000, 0x3e000000)), - ('tri_g3a', 'TRI0 t=8 tmax=100 (control)', 'fan', 0x09090909, 0, - (0x42c80000, 0x3f800000, 0x3e800000, 0xbf800000, 0x00000000, 0x00000000, 0x3f000000, 0x7f800000, 0x7f800000, 0x40000000), - (0xc1000000, 0xbf800000, 0xbe800000, 0xbe000000)), - ('tri_g3a', 'TRI0 t=8 tmax=8 = t', 'fan', 0x09090909, 0, - (0x41000000, 0x3f800000, 0x3e800000, 0xbf800000, 0x00000000, 0x00000000, 0x3f000000, 0x7f800000, 0x7f800000, 0x40000000), - (0xc1000000, 0xbf800000, 0xbe800000, 0xbe000000)), - ('tri_g3a', 'TRI0 t=8 tmax=prev(8)', 'fan', 0x09090909, 0, - (0x40ffffff, 0x3f800000, 0x3e800000, 0xbf800000, 0x00000000, 0x00000000, 0x3f000000, 0x7f800000, 0x7f800000, 0x40000000), - (0xc1000000, 0xbf800000, 0xbe800000, 0xbe000000)), - ('tri_g3a', 'TRI0 t=8 tmax=next(8)', 'fan', 0x09090909, 0, - (0x41000001, 0x3f800000, 0x3e800000, 0xbf800000, 0x00000000, 0x00000000, 0x3f000000, 0x7f800000, 0x7f800000, 0x40000000), - (0xc1000000, 0xbf800000, 0xbe800000, 0xbe000000)), - ('tri_g3a', 'TRI0 t=8 tmax=7', 'fan', 0x09090909, 0, - (0x40e00000, 0x3f800000, 0x3e800000, 0xbf800000, 0x00000000, 0x00000000, 0x3f000000, 0x7f800000, 0x7f800000, 0x40000000), - (0xc1000000, 0xbf800000, 0xbe800000, 0xbe000000)), - ('tri_g3a', 'TRI0 t=8 tmax=0', 'fan', 0x09090909, 0, - (0x00000000, 0x3f800000, 0x3e800000, 0xbf800000, 0x00000000, 0x00000000, 0x3f000000, 0x7f800000, 0x7f800000, 0x40000000), - (0xc1000000, 0xbf800000, 0xbe800000, 0xbe000000)), - ('tri_g3a', 'TRI0 t=8 tmax=-1', 'fan', 0x09090909, 0, - (0xbf800000, 0x3f800000, 0x3e800000, 0xbf800000, 0x00000000, 0x00000000, 0x3f000000, 0x7f800000, 0x7f800000, 0x40000000), - (0xc1000000, 0xbf800000, 0xbe800000, 0xbe000000)), - ('tri_g3a', 'TRI0 t=8 tmax=+inf', 'fan', 0x09090909, 0, - (0x7f800000, 0x3f800000, 0x3e800000, 0xbf800000, 0x00000000, 0x00000000, 0x3f000000, 0x7f800000, 0x7f800000, 0x40000000), - (0xc1000000, 0xbf800000, 0xbe800000, 0xbe000000)), - ('tri_g3a', 'TRI0 t=8 tmax=NaN', 'fan', 0x09090909, 0, - (0x7fc00000, 0x3f800000, 0x3e800000, 0xbf800000, 0x00000000, 0x00000000, 0x3f000000, 0x7f800000, 0x7f800000, 0x40000000), - (0x7f800000, 0x3f800000, 0x00000000, 0x00000000)), - ('tri_g3a', 'TRI0 behind origin +z (t=-4)', 'fan', 0x09090909, 0, - (0x42c80000, 0x3f800000, 0x3e800000, 0x40a00000, 0x00000000, 0x00000000, 0x3f000000, 0x7f800000, 0x7f800000, 0x40000000), - (0xff800000, 0xbf800000, 0xbe800000, 0xbe000000)), - ('tri_g3a', 'TRI0 behind origin -z (t=-4, back)', 'fan', 0x09090909, 0, - (0x42c80000, 0x3f800000, 0x3e800000, 0x3f800000, 0x00000000, 0x00000000, 0xbf000000, 0x7f800000, 0x7f800000, 0xc0000000), - (0x7f800000, 0x3f800000, 0x3e800000, 0x3e000000)), - ('tri_g3a', 'TRI0 origin on the plane (t=0)', 'fan', 0x09090909, 0, - (0x42c80000, 0x3f800000, 0x3e800000, 0x40400000, 0x00000000, 0x00000000, 0x3f000000, 0x7f800000, 0x7f800000, 0x40000000), - (0x00000000, 0xbf800000, 0xbe800000, 0xbe000000)), - ('tri_g3a', 'TRI0 t=2^-19', 'fan', 0x09090909, 0, - (0x42c80000, 0x3f800000, 0x3e800000, 0x403ffffc, 0x00000000, 0x00000000, 0x3f000000, 0x7f800000, 0x7f800000, 0x40000000), - (0xb6000000, 0xbf800000, 0xbe800000, 0xbe000000)), - ('tri_g3a', 'zero area: three equal vertices, ray through them', 'three_equal', 0x09090909, 0, - (0x42c80000, 0x3f800000, 0x3e800000, 0xbf800000, 0x00000000, 0x00000000, 0x3f000000, 0x7f800000, 0x7f800000, 0x40000000), - (0x7f800000, 0x00000000, 0x00000000, 0x00000000)), - ('tri_g3a', 'zero area: collinear, ray through the segment', 'collinear', 0x09090909, 0, - (0x42c80000, 0x3f800000, 0x3e800000, 0xbf800000, 0x00000000, 0x00000000, 0x3f000000, 0x7f800000, 0x7f800000, 0x40000000), - (0x7f800000, 0x00000000, 0x00000000, 0x00000000)), - ('tri_g3a', 'zero area: collinear, ray off the line', 'collinear', 0x09090909, 0, - (0x42c80000, 0x3f800000, 0x3f800000, 0xbf800000, 0x00000000, 0x00000000, 0x3f000000, 0x7f800000, 0x7f800000, 0x40000000), - (0x7f800000, 0x00000000, 0x3ec00000, 0xbe400000)), - ('tri_g3a', "edge-on: ray in the triangle's plane, through it", 'edge_on', 0x09090909, 0, - (0x42c80000, 0x3f800000, 0x3e800000, 0xbf800000, 0x00000000, 0x00000000, 0x3f000000, 0x7f800000, 0x7f800000, 0x40000000), - (0x7f800000, 0x00000000, 0x00000000, 0x00000000)), - ('tri_g3a', 'TRI0 vertex v0.x NaN', 'v0x_nan', 0x09090909, 0, - (0x42c80000, 0x3f800000, 0x3e800000, 0xbf800000, 0x00000000, 0x00000000, 0x3f000000, 0x7f800000, 0x7f800000, 0x40000000), - (0xff800000, 0xffc00000, 0xffc00000, 0xffc00000)), - ('tri_g3a', 'TRI0 vertex v0.z NaN', 'v0z_nan', 0x09090909, 0, - (0x42c80000, 0x3f800000, 0x3e800000, 0xbf800000, 0x00000000, 0x00000000, 0x3f000000, 0x7f800000, 0x7f800000, 0x40000000), - (0xff800000, 0xffc00000, 0xffc00000, 0xffc00000)), - ('tri_g3a', 'TRI0 vertex v1.y NaN', 'v1y_nan', 0x09090909, 0, - (0x42c80000, 0x3f800000, 0x3e800000, 0xbf800000, 0x00000000, 0x00000000, 0x3f000000, 0x7f800000, 0x7f800000, 0x40000000), - (0xff800000, 0xffc00000, 0xbe800000, 0xffc00000)), - ('tri_g3a', 'TRI0 vertex v2.x +inf', 'v2x_inf', 0x09090909, 0, - (0x42c80000, 0x3f800000, 0x3e800000, 0xbf800000, 0x00000000, 0x00000000, 0x3f000000, 0x7f800000, 0x7f800000, 0x40000000), - (0xff800000, 0xffc00000, 0x7f800000, 0xbe000000)), - ('tri_g3a', 'TRI0 vertex v0.x -inf', 'v0x_neginf', 0x09090909, 0, - (0x42c80000, 0x3f800000, 0x3e800000, 0xbf800000, 0x00000000, 0x00000000, 0x3f000000, 0x7f800000, 0x7f800000, 0x40000000), - (0xff800000, 0xff800000, 0xff800000, 0xff800000)), - ('tri_g3a', 'TRI0 NaN in slot 3 (not read by TRI0): control', 'slot3_nan', 0x09090909, 0, - (0x42c80000, 0x3f800000, 0x3e800000, 0xbf800000, 0x00000000, 0x00000000, 0x3f000000, 0x7f800000, 0x7f800000, 0x40000000), - (0xc1000000, 0xbf800000, 0xbe800000, 0xbe000000)), - ('tri_g3a', 'TRI0 NaN in slot 4 word 12 (not read by TRI0): control', 'slot4_nan', 0x09090909, 0, - (0x42c80000, 0x3f800000, 0x3e800000, 0xbf800000, 0x00000000, 0x00000000, 0x3f000000, 0x7f800000, 0x7f800000, 0x40000000), - (0xc1000000, 0xbf800000, 0xbe800000, 0xbe000000)), - ('tri_g3b', 'TRI0 control', 'fan', 0x09090909, 0, - (0x42c80000, 0x3f800000, 0x3e800000, 0xbf800000, 0x00000000, 0x00000000, 0x3f000000, 0x7f800000, 0x7f800000, 0x40000000), - (0xc1000000, 0xbf800000, 0xbe800000, 0xbe000000)), - ('tri_g3b', 'TRI0 ray o.x NaN', 'fan', 0x09090909, 0, - (0x42c80000, 0x7fc00000, 0x3e800000, 0xbf800000, 0x00000000, 0x00000000, 0x3f000000, 0x7f800000, 0x7f800000, 0x40000000), - (0x7f800000, 0x3f800000, 0x00000000, 0x00000000)), - ('tri_g3b', 'TRI0 ray o.z NaN', 'fan', 0x09090909, 0, - (0x42c80000, 0x3f800000, 0x3e800000, 0x7fc00000, 0x00000000, 0x00000000, 0x3f000000, 0x7f800000, 0x7f800000, 0x40000000), - (0x7f800000, 0x3f800000, 0x00000000, 0x00000000)), - ('tri_g3b', 'TRI0 ray o.x +inf', 'fan', 0x09090909, 0, - (0x42c80000, 0x7f800000, 0x3e800000, 0xbf800000, 0x00000000, 0x00000000, 0x3f000000, 0x7f800000, 0x7f800000, 0x40000000), - (0x7f800000, 0x3f800000, 0x00000000, 0x00000000)), - ('tri_g3b', 'TRI0 ray d.x NaN', 'fan', 0x09090909, 0, - (0x42c80000, 0x3f800000, 0x3e800000, 0xbf800000, 0x7fc00000, 0x00000000, 0x3f000000, 0x7f800000, 0x7f800000, 0x40000000), - (0x7f800000, 0x3f800000, 0x00000000, 0x00000000)), - ('tri_g3b', 'TRI0 ray d.z NaN', 'fan', 0x09090909, 0, - (0x42c80000, 0x3f800000, 0x3e800000, 0xbf800000, 0x00000000, 0x00000000, 0x7fc00000, 0x7f800000, 0x7f800000, 0x40000000), - (0x7f800000, 0x3f800000, 0x00000000, 0x00000000)), - ('tri_g3b', 'TRI0 ray inv.z NaN', 'fan', 0x09090909, 0, - (0x42c80000, 0x3f800000, 0x3e800000, 0xbf800000, 0x00000000, 0x00000000, 0x3f000000, 0x7f800000, 0x7f800000, 0x7fc00000), - (0x7f800000, 0x3f800000, 0x00000000, 0x00000000)), - ('tri_g3b', 'TRI0 ray inv.x NaN (axis the translator does not read)', 'fan', 0x09090909, 0, - (0x42c80000, 0x3f800000, 0x3e800000, 0xbf800000, 0x00000000, 0x00000000, 0x3f000000, 0x7fc00000, 0x7f800000, 0x40000000), - (0x7f800000, 0x3f800000, 0x00000000, 0x00000000)), - ('tri_g3b', 'TRI0 ray inv.z = 4 (not 1/d.z = 2)', 'fan', 0x09090909, 0, - (0x42c80000, 0x3f800000, 0x3e800000, 0xbf800000, 0x00000000, 0x00000000, 0x3f000000, 0x7f800000, 0x7f800000, 0x40800000), - (0xc1000000, 0xbf800000, 0xbe800000, 0xbe000000)), - ('tri_g3b', 'TRI0 ray inv.z = 1 (not 1/d.z)', 'fan', 0x09090909, 0, - (0x42c80000, 0x3f800000, 0x3e800000, 0xbf800000, 0x00000000, 0x00000000, 0x3f000000, 0x7f800000, 0x7f800000, 0x3f800000), - (0xc1000000, 0xbf800000, 0xbe800000, 0xbe000000)), - ('tri_g3b', 'TRI0 ray inv.x = 3 (not 1/d.x = inf)', 'fan', 0x09090909, 0, - (0x42c80000, 0x3f800000, 0x3e800000, 0xbf800000, 0x00000000, 0x00000000, 0x3f000000, 0x40400000, 0x7f800000, 0x40000000), - (0xc1000000, 0xbf800000, 0xbe800000, 0xbe000000)), - ('tri_g3b', 'TRI0 ray d.x = -0.0', 'fan', 0x09090909, 0, - (0x42c80000, 0x3f800000, 0x3e800000, 0xbf800000, 0x80000000, 0x00000000, 0x3f000000, 0x7f800000, 0x7f800000, 0x40000000), - (0xc1000000, 0xbf800000, 0xbe800000, 0xbe000000)), - ('tri_g3b', 'TRI0 ray d.x = -0.0, inv.x = -inf', 'fan', 0x09090909, 0, - (0x42c80000, 0x3f800000, 0x3e800000, 0xbf800000, 0x80000000, 0x00000000, 0x3f000000, 0xff800000, 0x7f800000, 0x40000000), - (0xc1000000, 0xbf800000, 0xbe800000, 0xbe000000)), - ('tri_g3b', 'TRI0 ray d = 0, inv = +inf', 'fan', 0x09090909, 0, - (0x42c80000, 0x3f800000, 0x3e800000, 0xbf800000, 0x00000000, 0x00000000, 0x00000000, 0x7f800000, 0x7f800000, 0x7f800000), - (0x7f800000, 0x00000000, 0x00000000, 0x00000000)), - ('tri_g3b', 'TRI0 ray d.z = +inf, inv.z = 0', 'fan', 0x09090909, 0, - (0x42c80000, 0x3f800000, 0x3e800000, 0xbf800000, 0x00000000, 0x00000000, 0x7f800000, 0x7f800000, 0x7f800000, 0x00000000), - (0xff800000, 0xffc00000, 0xff800000, 0xff800000)), - ('tri_g3b', 'TRI0 ray d.z = 1024 (t = 2^-8)', 'fan', 0x09090909, 0, - (0x42c80000, 0x3f800000, 0x3e800000, 0xbf800000, 0x00000000, 0x00000000, 0x44800000, 0x7f800000, 0x7f800000, 0x3a800000), - (0xcc000000, 0xd0000000, 0xcf000000, 0xce800000)), - ('tri_g3b', 'TRI0 ray d.z = 2^-20 (t = 2^22)', 'fan', 0x09090909, 0, - (0x7f800000, 0x3f800000, 0x3e800000, 0xbf800000, 0x00000000, 0x00000000, 0x35800000, 0x7f800000, 0x7f800000, 0x49800000), - (0xae000000, 0xa3000000, 0xa2000000, 0xa1800000)), - ('tri_g3b', 'TRI0 ray oblique, inv.z = 4 (not 1/d.z)', 'fan', 0x09090909, 0, - (0x42c80000, 0x00000000, 0xbe800000, 0xbf800000, 0x3e000000, 0x3d800000, 0x3f000000, 0x41000000, 0x41800000, 0x40800000), - (0xc1000000, 0xbf800000, 0xbe800000, 0xbe000000)), - ('tri_g3b', 'TRI0 ray oblique, inv.x = inv.y = 1 (not 1/d)', 'fan', 0x09090909, 0, - (0x42c80000, 0x00000000, 0xbe800000, 0xbf800000, 0x3e000000, 0x3d800000, 0x3f000000, 0x3f800000, 0x3f800000, 0x40000000), - (0xc1000000, 0xbf800000, 0xbe800000, 0xbe000000)), - ('tri_g4a', 'fan vertex s2 (0,2), TRI0, +z', 'fan', 0x09090909, 0, - (0x42c80000, 0x00000000, 0x40000000, 0xbf800000, 0x00000000, 0x00000000, 0x3f000000, 0x7f800000, 0x7f800000, 0x40000000), - (0xff800000, 0xbf800000, 0x00000000, 0xbf800000)), - ('tri_g4a', 'fan vertex s2 (0,2), TRI1, +z', 'fan', 0x09090909, 1, - (0x42c80000, 0x00000000, 0x40000000, 0xbf800000, 0x00000000, 0x00000000, 0x3f000000, 0x7f800000, 0x7f800000, 0x40000000), - (0xc1000000, 0xbf800000, 0x00000000, 0xbf800000)), - ('tri_g4a', 'fan vertex s2 (0,2), TRI2, +z', 'fan', 0x09090909, 2, - (0x42c80000, 0x00000000, 0x40000000, 0xbf800000, 0x00000000, 0x00000000, 0x3f000000, 0x7f800000, 0x7f800000, 0x40000000), - (0xff800000, 0xbf000000, 0x00000000, 0x00000000)), - ('tri_g4a', 'fan vertex s2 (0,2), TRI3, +z', 'fan', 0x09090909, 3, - (0x42c80000, 0x00000000, 0x40000000, 0xbf800000, 0x00000000, 0x00000000, 0x3f000000, 0x7f800000, 0x7f800000, 0x40000000), - (0xff800000, 0xbf000000, 0x00000000, 0x00000000)), - ('tri_g4a', 'fan vertex s2 (0,2), TRI0, -z', 'fan', 0x09090909, 0, - (0x42c80000, 0x00000000, 0x40000000, 0x40e00000, 0x00000000, 0x00000000, 0xbf000000, 0x7f800000, 0x7f800000, 0xc0000000), - (0x7f800000, 0x3f800000, 0x00000000, 0x3f800000)), - ('tri_g4a', 'fan vertex s2 (0,2), TRI1, -z', 'fan', 0x09090909, 1, - (0x42c80000, 0x00000000, 0x40000000, 0x40e00000, 0x00000000, 0x00000000, 0xbf000000, 0x7f800000, 0x7f800000, 0xc0000000), - (0x7f800000, 0x3f800000, 0x00000000, 0x3f800000)), - ('tri_g4a', 'fan vertex s2 (0,2), TRI2, -z', 'fan', 0x09090909, 2, - (0x42c80000, 0x00000000, 0x40000000, 0x40e00000, 0x00000000, 0x00000000, 0xbf000000, 0x7f800000, 0x7f800000, 0xc0000000), - (0x40800000, 0x3f000000, 0x00000000, 0x00000000)), - ('tri_g4a', 'fan vertex s2 (0,2), TRI3, -z', 'fan', 0x09090909, 3, - (0x42c80000, 0x00000000, 0x40000000, 0x40e00000, 0x00000000, 0x00000000, 0xbf000000, 0x7f800000, 0x7f800000, 0xc0000000), - (0x7f800000, 0x3f000000, 0x00000000, 0x00000000)), - ('tri_g4a', 'fan vertex s2 (0,2), TRI0, oblique +z', 'fan', 0x09090909, 0, - (0x42c80000, 0xbf800000, 0x3fc00000, 0xbf800000, 0x3e000000, 0x3d800000, 0x3f000000, 0x41000000, 0x41800000, 0x40000000), - (0xff800000, 0xbf800000, 0x00000000, 0xbf800000)), - ('tri_g4a', 'fan vertex s2 (0,2), TRI1, oblique +z', 'fan', 0x09090909, 1, - (0x42c80000, 0xbf800000, 0x3fc00000, 0xbf800000, 0x3e000000, 0x3d800000, 0x3f000000, 0x41000000, 0x41800000, 0x40000000), - (0xc1000000, 0xbf800000, 0x00000000, 0xbf800000)), - ('tri_g4a', 'fan vertex s2 (0,2), TRI2, oblique +z', 'fan', 0x09090909, 2, - (0x42c80000, 0xbf800000, 0x3fc00000, 0xbf800000, 0x3e000000, 0x3d800000, 0x3f000000, 0x41000000, 0x41800000, 0x40000000), - (0xff800000, 0xbf000000, 0x00000000, 0x00000000)), - ('tri_g4a', 'fan vertex s2 (0,2), TRI3, oblique +z', 'fan', 0x09090909, 3, - (0x42c80000, 0xbf800000, 0x3fc00000, 0xbf800000, 0x3e000000, 0x3d800000, 0x3f000000, 0x41000000, 0x41800000, 0x40000000), - (0xff800000, 0xbf000000, 0x00000000, 0x00000000)), - ('tri_g4a', 'fan vertex s2 (0,2), TRI0, oblique -z', 'fan', 0x09090909, 0, - (0x42c80000, 0xbf800000, 0x3fc00000, 0x40e00000, 0x3e000000, 0x3d800000, 0xbf000000, 0x41000000, 0x41800000, 0xc0000000), - (0x7f800000, 0x3f800000, 0x00000000, 0x3f800000)), - ('tri_g4a', 'fan vertex s2 (0,2), TRI1, oblique -z', 'fan', 0x09090909, 1, - (0x42c80000, 0xbf800000, 0x3fc00000, 0x40e00000, 0x3e000000, 0x3d800000, 0xbf000000, 0x41000000, 0x41800000, 0xc0000000), - (0x7f800000, 0x3f800000, 0x00000000, 0x3f800000)), - ('tri_g4a', 'fan vertex s2 (0,2), TRI2, oblique -z', 'fan', 0x09090909, 2, - (0x42c80000, 0xbf800000, 0x3fc00000, 0x40e00000, 0x3e000000, 0x3d800000, 0xbf000000, 0x41000000, 0x41800000, 0xc0000000), - (0x40800000, 0x3f000000, 0x00000000, 0x00000000)), - ('tri_g4a', 'fan vertex s2 (0,2), TRI3, oblique -z', 'fan', 0x09090909, 3, - (0x42c80000, 0xbf800000, 0x3fc00000, 0x40e00000, 0x3e000000, 0x3d800000, 0xbf000000, 0x41000000, 0x41800000, 0xc0000000), - (0x7f800000, 0x3f000000, 0x00000000, 0x00000000)), - ('tri_g4b', 'shared edge E01 (2,1), TRI0, +z', 'fan', 0x09090909, 0, - (0x42c80000, 0x40000000, 0x3f800000, 0xbf800000, 0x00000000, 0x00000000, 0x3f000000, 0x7f800000, 0x7f800000, 0x40000000), - (0xff800000, 0xbf800000, 0xbf000000, 0xbf000000)), - ('tri_g4b', 'shared edge E01 (2,1), TRI1, +z', 'fan', 0x09090909, 1, - (0x42c80000, 0x40000000, 0x3f800000, 0xbf800000, 0x00000000, 0x00000000, 0x3f000000, 0x7f800000, 0x7f800000, 0x40000000), - (0xc1000000, 0xbf800000, 0x00000000, 0xbf000000)), - ('tri_g4b', 'shared edge E03 (0,1), TRI0, +z', 'fan', 0x09090909, 0, - (0x42c80000, 0x00000000, 0x3f800000, 0xbf800000, 0x00000000, 0x00000000, 0x3f000000, 0x7f800000, 0x7f800000, 0x40000000), - (0xc1000000, 0xbf800000, 0x00000000, 0xbf000000)), - ('tri_g4b', 'shared edge E03 (0,1), TRI3, +z', 'fan', 0x09090909, 3, - (0x42c80000, 0x00000000, 0x3f800000, 0xbf800000, 0x00000000, 0x00000000, 0x3f000000, 0x7f800000, 0x7f800000, 0x40000000), - (0xff800000, 0xbf000000, 0x00000000, 0xbe800000)), - ('tri_g4b', 'shared edge E12 (2,2), TRI1, +z', 'fan', 0x09090909, 1, - (0x42c80000, 0x40000000, 0x40000000, 0xbf800000, 0x00000000, 0x00000000, 0x3f000000, 0x7f800000, 0x7f800000, 0x40000000), - (0xc1000000, 0xbf800000, 0xbf000000, 0xbf000000)), - ('tri_g4b', 'shared edge E12 (2,2), TRI2, +z', 'fan', 0x09090909, 2, - (0x42c80000, 0x40000000, 0x40000000, 0xbf800000, 0x00000000, 0x00000000, 0x3f000000, 0x7f800000, 0x7f800000, 0x40000000), - (0xff800000, 0xbf000000, 0xbe800000, 0x00000000)), - ('tri_g4b', 'shared edge E23 (-1,2.5), TRI2, +z', 'fan', 0x09090909, 2, - (0x42c80000, 0xbf800000, 0x40200000, 0xbf800000, 0x00000000, 0x00000000, 0x3f000000, 0x7f800000, 0x7f800000, 0x40000000), - (0xc0800000, 0xbf000000, 0x00000000, 0xbe800000)), - ('tri_g4b', 'shared edge E23 (-1,2.5), TRI3, +z', 'fan', 0x09090909, 3, - (0x42c80000, 0xbf800000, 0x40200000, 0xbf800000, 0x00000000, 0x00000000, 0x3f000000, 0x7f800000, 0x7f800000, 0x40000000), - (0xff800000, 0xbf000000, 0xbe800000, 0x00000000)), - ('tri_g4b', 'shared edge E01 (2,1), TRI0, -z', 'fan', 0x09090909, 0, - (0x42c80000, 0x40000000, 0x3f800000, 0x40e00000, 0x00000000, 0x00000000, 0xbf000000, 0x7f800000, 0x7f800000, 0xc0000000), - (0x7f800000, 0x3f800000, 0x3f000000, 0x3f000000)), - ('tri_g4b', 'shared edge E01 (2,1), TRI1, -z', 'fan', 0x09090909, 1, - (0x42c80000, 0x40000000, 0x3f800000, 0x40e00000, 0x00000000, 0x00000000, 0xbf000000, 0x7f800000, 0x7f800000, 0xc0000000), - (0x41000000, 0x3f800000, 0x00000000, 0x3f000000)), - ('tri_g4b', 'shared edge E03 (0,1), TRI0, -z', 'fan', 0x09090909, 0, - (0x42c80000, 0x00000000, 0x3f800000, 0x40e00000, 0x00000000, 0x00000000, 0xbf000000, 0x7f800000, 0x7f800000, 0xc0000000), - (0x41000000, 0x3f800000, 0x00000000, 0x3f000000)), - ('tri_g4b', 'shared edge E03 (0,1), TRI3, -z', 'fan', 0x09090909, 3, - (0x42c80000, 0x00000000, 0x3f800000, 0x40e00000, 0x00000000, 0x00000000, 0xbf000000, 0x7f800000, 0x7f800000, 0xc0000000), - (0x7f800000, 0x3f000000, 0x00000000, 0x3e800000)), - ('tri_g4b', 'shared edge E12 (2,2), TRI1, -z', 'fan', 0x09090909, 1, - (0x42c80000, 0x40000000, 0x40000000, 0x40e00000, 0x00000000, 0x00000000, 0xbf000000, 0x7f800000, 0x7f800000, 0xc0000000), - (0x7f800000, 0x3f800000, 0x3f000000, 0x3f000000)), - ('tri_g4b', 'shared edge E12 (2,2), TRI2, -z', 'fan', 0x09090909, 2, - (0x42c80000, 0x40000000, 0x40000000, 0x40e00000, 0x00000000, 0x00000000, 0xbf000000, 0x7f800000, 0x7f800000, 0xc0000000), - (0x40800000, 0x3f000000, 0x3e800000, 0x00000000)), - ('tri_g4b', 'shared edge E23 (-1,2.5), TRI2, -z', 'fan', 0x09090909, 2, - (0x42c80000, 0xbf800000, 0x40200000, 0x40e00000, 0x00000000, 0x00000000, 0xbf000000, 0x7f800000, 0x7f800000, 0xc0000000), - (0x40800000, 0x3f000000, 0x00000000, 0x3e800000)), - ('tri_g4b', 'shared edge E23 (-1,2.5), TRI3, -z', 'fan', 0x09090909, 3, - (0x42c80000, 0xbf800000, 0x40200000, 0x40e00000, 0x00000000, 0x00000000, 0xbf000000, 0x7f800000, 0x7f800000, 0xc0000000), - (0x7f800000, 0x3f000000, 0x3e800000, 0x00000000)), - ('tri_g4b', 'shared edge E01 (2,1), TRI0, oblique +z', 'fan', 0x09090909, 0, - (0x42c80000, 0x3f800000, 0x3f000000, 0xbf800000, 0x3e000000, 0x3d800000, 0x3f000000, 0x41000000, 0x41800000, 0x40000000), - (0xff800000, 0xbf800000, 0xbf000000, 0xbf000000)), - ('tri_g4b', 'shared edge E01 (2,1), TRI1, oblique +z', 'fan', 0x09090909, 1, - (0x42c80000, 0x3f800000, 0x3f000000, 0xbf800000, 0x3e000000, 0x3d800000, 0x3f000000, 0x41000000, 0x41800000, 0x40000000), - (0xc1000000, 0xbf800000, 0x00000000, 0xbf000000)), - ('tri_g4b', 'shared edge E03 (0,1), TRI0, oblique +z', 'fan', 0x09090909, 0, - (0x42c80000, 0xbf800000, 0x3f000000, 0xbf800000, 0x3e000000, 0x3d800000, 0x3f000000, 0x41000000, 0x41800000, 0x40000000), - (0xc1000000, 0xbf800000, 0x00000000, 0xbf000000)), - ('tri_g4b', 'shared edge E03 (0,1), TRI3, oblique +z', 'fan', 0x09090909, 3, - (0x42c80000, 0xbf800000, 0x3f000000, 0xbf800000, 0x3e000000, 0x3d800000, 0x3f000000, 0x41000000, 0x41800000, 0x40000000), - (0xff800000, 0xbf000000, 0x00000000, 0xbe800000)), - ('tri_g4b', 'shared edge E12 (2,2), TRI1, oblique +z', 'fan', 0x09090909, 1, - (0x42c80000, 0x3f800000, 0x3fc00000, 0xbf800000, 0x3e000000, 0x3d800000, 0x3f000000, 0x41000000, 0x41800000, 0x40000000), - (0xc1000000, 0xbf800000, 0xbf000000, 0xbf000000)), - ('tri_g4b', 'shared edge E12 (2,2), TRI2, oblique +z', 'fan', 0x09090909, 2, - (0x42c80000, 0x3f800000, 0x3fc00000, 0xbf800000, 0x3e000000, 0x3d800000, 0x3f000000, 0x41000000, 0x41800000, 0x40000000), - (0xff800000, 0xbf000000, 0xbe800000, 0x00000000)), - ('tri_g4b', 'shared edge E23 (-1,2.5), TRI2, oblique +z', 'fan', 0x09090909, 2, - (0x42c80000, 0xc0000000, 0x40000000, 0xbf800000, 0x3e000000, 0x3d800000, 0x3f000000, 0x41000000, 0x41800000, 0x40000000), - (0xc0800000, 0xbf000000, 0x00000000, 0xbe800000)), - ('tri_g4b', 'shared edge E23 (-1,2.5), TRI3, oblique +z', 'fan', 0x09090909, 3, - (0x42c80000, 0xc0000000, 0x40000000, 0xbf800000, 0x3e000000, 0x3d800000, 0x3f000000, 0x41000000, 0x41800000, 0x40000000), - (0xff800000, 0xbf000000, 0xbe800000, 0x00000000)), - ('tri_g4b', 'outer vertex s0 (0,0), TRI0, +z', 'fan', 0x09090909, 0, - (0x42c80000, 0x00000000, 0x00000000, 0xbf800000, 0x00000000, 0x00000000, 0x3f000000, 0x7f800000, 0x7f800000, 0x40000000), - (0xff800000, 0xbf800000, 0x00000000, 0x00000000)), - ('tri_g4b', 'outer vertex s0 (0,0), TRI3, +z', 'fan', 0x09090909, 3, - (0x42c80000, 0x00000000, 0x00000000, 0xbf800000, 0x00000000, 0x00000000, 0x3f000000, 0x7f800000, 0x7f800000, 0x40000000), - (0xff800000, 0xbf000000, 0x00000000, 0xbf000000)), - ('tri_g4b', 'outer edge (2,0), TRI0, +z', 'fan', 0x09090909, 0, - (0x42c80000, 0x40000000, 0x00000000, 0xbf800000, 0x00000000, 0x00000000, 0x3f000000, 0x7f800000, 0x7f800000, 0x40000000), - (0xff800000, 0xbf800000, 0xbf000000, 0x00000000)), - ('tri_g4b', 'outer vertex s1 (4,0), TRI0, +z', 'fan', 0x09090909, 0, - (0x42c80000, 0x40800000, 0x00000000, 0xbf800000, 0x00000000, 0x00000000, 0x3f000000, 0x7f800000, 0x7f800000, 0x40000000), - (0xff800000, 0xbf800000, 0xbf800000, 0x00000000)), - ('tri_g4b', 'outer vertex s1 (4,0), TRI1, +z', 'fan', 0x09090909, 1, - (0x42c80000, 0x40800000, 0x00000000, 0xbf800000, 0x00000000, 0x00000000, 0x3f000000, 0x7f800000, 0x7f800000, 0x40000000), - (0xff800000, 0xbf800000, 0x00000000, 0x00000000)), - ('tri_g4b', 'outer vertex s3 (4,2), TRI1, +z', 'fan', 0x09090909, 1, - (0x42c80000, 0x40800000, 0x40000000, 0xbf800000, 0x00000000, 0x00000000, 0x3f000000, 0x7f800000, 0x7f800000, 0x40000000), - (0xff800000, 0xbf800000, 0xbf800000, 0x00000000)), - ('tri_g4b', 'outer vertex s3 (4,2), TRI2, +z', 'fan', 0x09090909, 2, - (0x42c80000, 0x40800000, 0x40000000, 0xbf800000, 0x00000000, 0x00000000, 0x3f000000, 0x7f800000, 0x7f800000, 0x40000000), - (0xff800000, 0xbf000000, 0xbf000000, 0x00000000)), - ('tri_g4b', 'outer vertex s4 (-2,3), TRI2, +z', 'fan', 0x09090909, 2, - (0x42c80000, 0xc0000000, 0x40400000, 0xbf800000, 0x00000000, 0x00000000, 0x3f000000, 0x7f800000, 0x7f800000, 0x40000000), - (0xff800000, 0xbf000000, 0x00000000, 0xbf000000)), - ('tri_t1', 'control tri_g1a: TRI0 hit +z', 'fan', 0x09090909, 0, - (0x42c80000, 0x3f800000, 0x3e800000, 0xbf800000, 0x00000000, 0x00000000, 0x3f000000, 0x7f800000, 0x7f800000, 0x40000000), - (0xc1000000, 0xbf800000, 0xbe800000, 0xbe000000)), - ('tri_t1', 'T1 +x: E01 (2,1), TRI0, fan, axes cycled (z->x), d=(0.5,0,0)', 'fan_x_dominant', 0x09090909, 0, - (0x42c80000, 0xbf800000, 0x40000000, 0x3f800000, 0x3f000000, 0x00000000, 0x00000000, 0x40000000, 0x7f800000, 0x7f800000), - (0xff800000, 0xbf800000, 0xbf000000, 0xbf000000)), - ('tri_t1', 'T1 +x: E01 (2,1), TRI1, fan, axes cycled (z->x), d=(0.5,0,0)', 'fan_x_dominant', 0x09090909, 1, - (0x42c80000, 0xbf800000, 0x40000000, 0x3f800000, 0x3f000000, 0x00000000, 0x00000000, 0x40000000, 0x7f800000, 0x7f800000), - (0xc1000000, 0xbf800000, 0x00000000, 0xbf000000)), - ('tri_t1', 'T1 +x: E03 (0,1), TRI0, fan, axes cycled (z->x), d=(0.5,0,0)', 'fan_x_dominant', 0x09090909, 0, - (0x42c80000, 0xbf800000, 0x00000000, 0x3f800000, 0x3f000000, 0x00000000, 0x00000000, 0x40000000, 0x7f800000, 0x7f800000), - (0xc1000000, 0xbf800000, 0x00000000, 0xbf000000)), - ('tri_t1', 'T1 +x: E03 (0,1), TRI3, fan, axes cycled (z->x), d=(0.5,0,0)', 'fan_x_dominant', 0x09090909, 3, - (0x42c80000, 0xbf800000, 0x00000000, 0x3f800000, 0x3f000000, 0x00000000, 0x00000000, 0x40000000, 0x7f800000, 0x7f800000), - (0xff800000, 0xbf000000, 0x00000000, 0xbe800000)), - ('tri_t1', 'T1 +x: E12 (2,2), TRI1, fan, axes cycled (z->x), d=(0.5,0,0)', 'fan_x_dominant', 0x09090909, 1, - (0x42c80000, 0xbf800000, 0x40000000, 0x40000000, 0x3f000000, 0x00000000, 0x00000000, 0x40000000, 0x7f800000, 0x7f800000), - (0xc1000000, 0xbf800000, 0xbf000000, 0xbf000000)), - ('tri_t1', 'T1 +x: E12 (2,2), TRI2, fan, axes cycled (z->x), d=(0.5,0,0)', 'fan_x_dominant', 0x09090909, 2, - (0x42c80000, 0xbf800000, 0x40000000, 0x40000000, 0x3f000000, 0x00000000, 0x00000000, 0x40000000, 0x7f800000, 0x7f800000), - (0xff800000, 0xbf000000, 0xbe800000, 0x00000000)), - ('tri_t1', 'T1 +x: E23 (-1,2.5), TRI2, fan, axes cycled (z->x), d=(0.5,0,0)', 'fan_x_dominant', 0x09090909, 2, - (0x42c80000, 0xbf800000, 0xbf800000, 0x40200000, 0x3f000000, 0x00000000, 0x00000000, 0x40000000, 0x7f800000, 0x7f800000), - (0xc0800000, 0xbf000000, 0x00000000, 0xbe800000)), - ('tri_t1', 'T1 +x: E23 (-1,2.5), TRI3, fan, axes cycled (z->x), d=(0.5,0,0)', 'fan_x_dominant', 0x09090909, 3, - (0x42c80000, 0xbf800000, 0xbf800000, 0x40200000, 0x3f000000, 0x00000000, 0x00000000, 0x40000000, 0x7f800000, 0x7f800000), - (0xff800000, 0xbf000000, 0xbe800000, 0x00000000)), - ('tri_t1', 'T1 +x: fan vertex s2 (0,2), TRI0, fan, axes cycled (z->x), d=(0.5,0,0)', 'fan_x_dominant', 0x09090909, 0, - (0x42c80000, 0xbf800000, 0x00000000, 0x40000000, 0x3f000000, 0x00000000, 0x00000000, 0x40000000, 0x7f800000, 0x7f800000), - (0xff800000, 0xbf800000, 0x00000000, 0xbf800000)), - ('tri_t1', 'T1 +x: fan vertex s2 (0,2), TRI1, fan, axes cycled (z->x), d=(0.5,0,0)', 'fan_x_dominant', 0x09090909, 1, - (0x42c80000, 0xbf800000, 0x00000000, 0x40000000, 0x3f000000, 0x00000000, 0x00000000, 0x40000000, 0x7f800000, 0x7f800000), - (0xc1000000, 0xbf800000, 0x00000000, 0xbf800000)), - ('tri_t1', 'T1 +x: fan vertex s2 (0,2), TRI2, fan, axes cycled (z->x), d=(0.5,0,0)', 'fan_x_dominant', 0x09090909, 2, - (0x42c80000, 0xbf800000, 0x00000000, 0x40000000, 0x3f000000, 0x00000000, 0x00000000, 0x40000000, 0x7f800000, 0x7f800000), - (0xff800000, 0xbf000000, 0x00000000, 0x00000000)), - ('tri_t1', 'T1 +x: fan vertex s2 (0,2), TRI3, fan, axes cycled (z->x), d=(0.5,0,0)', 'fan_x_dominant', 0x09090909, 3, - (0x42c80000, 0xbf800000, 0x00000000, 0x40000000, 0x3f000000, 0x00000000, 0x00000000, 0x40000000, 0x7f800000, 0x7f800000), - (0xff800000, 0xbf000000, 0x00000000, 0x00000000)), - ('tri_t1', 'T1 +x: E01 (2,1), TRI0, rotated fan, axes cycled (z->x), d=(0.5,0,0)', 'rotated_fan_x_dominant', 0x09090909, 0, - (0x42c80000, 0xbf800000, 0xbf800000, 0x40000000, 0x3f000000, 0x00000000, 0x00000000, 0x40000000, 0x7f800000, 0x7f800000), - (0xc1000000, 0xbf800000, 0xbf000000, 0xbf000000)), - ('tri_t1', 'T1 +x: E01 (2,1), TRI1, rotated fan, axes cycled (z->x), d=(0.5,0,0)', 'rotated_fan_x_dominant', 0x09090909, 1, - (0x42c80000, 0xbf800000, 0xbf800000, 0x40000000, 0x3f000000, 0x00000000, 0x00000000, 0x40000000, 0x7f800000, 0x7f800000), - (0xff800000, 0xbf800000, 0x00000000, 0xbf000000)), - ('tri_t1', 'T1 -x: E01 (2,1), TRI0, fan, axes cycled (z->x), d=(-0.5,0,0)', 'fan_x_dominant', 0x09090909, 0, - (0x42c80000, 0x40e00000, 0x40000000, 0x3f800000, 0xbf000000, 0x00000000, 0x00000000, 0xc0000000, 0x7f800000, 0x7f800000), - (0x7f800000, 0x3f800000, 0x3f000000, 0x3f000000)), - ('tri_t1', 'T1 -x: E01 (2,1), TRI1, fan, axes cycled (z->x), d=(-0.5,0,0)', 'fan_x_dominant', 0x09090909, 1, - (0x42c80000, 0x40e00000, 0x40000000, 0x3f800000, 0xbf000000, 0x00000000, 0x00000000, 0xc0000000, 0x7f800000, 0x7f800000), - (0x41000000, 0x3f800000, 0x00000000, 0x3f000000)), - ('tri_t1', 'T1 -x: E03 (0,1), TRI0, fan, axes cycled (z->x), d=(-0.5,0,0)', 'fan_x_dominant', 0x09090909, 0, - (0x42c80000, 0x40e00000, 0x00000000, 0x3f800000, 0xbf000000, 0x00000000, 0x00000000, 0xc0000000, 0x7f800000, 0x7f800000), - (0x41000000, 0x3f800000, 0x00000000, 0x3f000000)), - ('tri_t1', 'T1 -x: E03 (0,1), TRI3, fan, axes cycled (z->x), d=(-0.5,0,0)', 'fan_x_dominant', 0x09090909, 3, - (0x42c80000, 0x40e00000, 0x00000000, 0x3f800000, 0xbf000000, 0x00000000, 0x00000000, 0xc0000000, 0x7f800000, 0x7f800000), - (0x7f800000, 0x3f000000, 0x00000000, 0x3e800000)), - ('tri_t1', 'T1 -x: E12 (2,2), TRI1, fan, axes cycled (z->x), d=(-0.5,0,0)', 'fan_x_dominant', 0x09090909, 1, - (0x42c80000, 0x40e00000, 0x40000000, 0x40000000, 0xbf000000, 0x00000000, 0x00000000, 0xc0000000, 0x7f800000, 0x7f800000), - (0x7f800000, 0x3f800000, 0x3f000000, 0x3f000000)), - ('tri_t1', 'T1 -x: E12 (2,2), TRI2, fan, axes cycled (z->x), d=(-0.5,0,0)', 'fan_x_dominant', 0x09090909, 2, - (0x42c80000, 0x40e00000, 0x40000000, 0x40000000, 0xbf000000, 0x00000000, 0x00000000, 0xc0000000, 0x7f800000, 0x7f800000), - (0x40800000, 0x3f000000, 0x3e800000, 0x00000000)), - ('tri_t1', 'T1 -x: E23 (-1,2.5), TRI2, fan, axes cycled (z->x), d=(-0.5,0,0)', 'fan_x_dominant', 0x09090909, 2, - (0x42c80000, 0x40e00000, 0xbf800000, 0x40200000, 0xbf000000, 0x00000000, 0x00000000, 0xc0000000, 0x7f800000, 0x7f800000), - (0x40800000, 0x3f000000, 0x00000000, 0x3e800000)), - ('tri_t1', 'T1 -x: E23 (-1,2.5), TRI3, fan, axes cycled (z->x), d=(-0.5,0,0)', 'fan_x_dominant', 0x09090909, 3, - (0x42c80000, 0x40e00000, 0xbf800000, 0x40200000, 0xbf000000, 0x00000000, 0x00000000, 0xc0000000, 0x7f800000, 0x7f800000), - (0x7f800000, 0x3f000000, 0x3e800000, 0x00000000)), - ('tri_t1', 'T1 -x: fan vertex s2 (0,2), TRI0, fan, axes cycled (z->x), d=(-0.5,0,0)', 'fan_x_dominant', 0x09090909, 0, - (0x42c80000, 0x40e00000, 0x00000000, 0x40000000, 0xbf000000, 0x00000000, 0x00000000, 0xc0000000, 0x7f800000, 0x7f800000), - (0x7f800000, 0x3f800000, 0x00000000, 0x3f800000)), - ('tri_t1', 'T1 -x: fan vertex s2 (0,2), TRI1, fan, axes cycled (z->x), d=(-0.5,0,0)', 'fan_x_dominant', 0x09090909, 1, - (0x42c80000, 0x40e00000, 0x00000000, 0x40000000, 0xbf000000, 0x00000000, 0x00000000, 0xc0000000, 0x7f800000, 0x7f800000), - (0x7f800000, 0x3f800000, 0x00000000, 0x3f800000)), - ('tri_t1', 'T1 -x: fan vertex s2 (0,2), TRI2, fan, axes cycled (z->x), d=(-0.5,0,0)', 'fan_x_dominant', 0x09090909, 2, - (0x42c80000, 0x40e00000, 0x00000000, 0x40000000, 0xbf000000, 0x00000000, 0x00000000, 0xc0000000, 0x7f800000, 0x7f800000), - (0x40800000, 0x3f000000, 0x00000000, 0x00000000)), - ('tri_t1', 'T1 -x: fan vertex s2 (0,2), TRI3, fan, axes cycled (z->x), d=(-0.5,0,0)', 'fan_x_dominant', 0x09090909, 3, - (0x42c80000, 0x40e00000, 0x00000000, 0x40000000, 0xbf000000, 0x00000000, 0x00000000, 0xc0000000, 0x7f800000, 0x7f800000), - (0x7f800000, 0x3f000000, 0x00000000, 0x00000000)), - ('tri_t1', 'T1 -x: outer edge s0-s1 (2,0), TRI0, fan, axes cycled (z->x), d=(-0.5,0,0)', 'fan_x_dominant', 0x09090909, 0, - (0x42c80000, 0x40e00000, 0x40000000, 0x00000000, 0xbf000000, 0x00000000, 0x00000000, 0xc0000000, 0x7f800000, 0x7f800000), - (0x41000000, 0x3f800000, 0x3f000000, 0x00000000)), - ('tri_t1', 'T1 -x: outer vertex s0 (0,0), TRI0, fan, axes cycled (z->x), d=(-0.5,0,0)', 'fan_x_dominant', 0x09090909, 0, - (0x42c80000, 0x40e00000, 0x00000000, 0x00000000, 0xbf000000, 0x00000000, 0x00000000, 0xc0000000, 0x7f800000, 0x7f800000), - (0x41000000, 0x3f800000, 0x00000000, 0x00000000)), - ('tri_t1', 'T1 -x: outer vertex s1 (4,0), TRI0, fan, axes cycled (z->x), d=(-0.5,0,0)', 'fan_x_dominant', 0x09090909, 0, - (0x42c80000, 0x40e00000, 0x40800000, 0x00000000, 0xbf000000, 0x00000000, 0x00000000, 0xc0000000, 0x7f800000, 0x7f800000), - (0x7f800000, 0x3f800000, 0x3f800000, 0x00000000)), - ('tri_t1', 'T1 -x: E01 (2,1), TRI0, rotated fan, axes cycled (z->x), d=(-0.5,0,0)', 'rotated_fan_x_dominant', 0x09090909, 0, - (0x42c80000, 0x40e00000, 0xbf800000, 0x40000000, 0xbf000000, 0x00000000, 0x00000000, 0xc0000000, 0x7f800000, 0x7f800000), - (0x41000000, 0x3f800000, 0x3f000000, 0x3f000000)), - ('tri_t1', 'T1 -x: E01 (2,1), TRI1, rotated fan, axes cycled (z->x), d=(-0.5,0,0)', 'rotated_fan_x_dominant', 0x09090909, 1, - (0x42c80000, 0x40e00000, 0xbf800000, 0x40000000, 0xbf000000, 0x00000000, 0x00000000, 0xc0000000, 0x7f800000, 0x7f800000), - (0x7f800000, 0x3f800000, 0x00000000, 0x3f000000)), - ('tri_t2', 'control tri_g4b: shared edge E01 (2,1), TRI1, +z', 'fan', 0x09090909, 1, - (0x42c80000, 0x40000000, 0x3f800000, 0xbf800000, 0x00000000, 0x00000000, 0x3f000000, 0x7f800000, 0x7f800000, 0x40000000), - (0xc1000000, 0xbf800000, 0x00000000, 0xbf000000)), - ('tri_t2', 'T1 +x: E01 (2,1), TRI0, mirrored fan, axes cycled (z->x), d=(0.5,0,0)', 'mirrored_fan_x_dominant', 0x09090909, 0, - (0x42c80000, 0xbf800000, 0xc0000000, 0x3f800000, 0x3f000000, 0x00000000, 0x00000000, 0x40000000, 0x7f800000, 0x7f800000), - (0x41000000, 0x3f800000, 0x3f000000, 0x3f000000)), - ('tri_t2', 'T1 +x: E01 (2,1), TRI1, mirrored fan, axes cycled (z->x), d=(0.5,0,0)', 'mirrored_fan_x_dominant', 0x09090909, 1, - (0x42c80000, 0xbf800000, 0xc0000000, 0x3f800000, 0x3f000000, 0x00000000, 0x00000000, 0x40000000, 0x7f800000, 0x7f800000), - (0x7f800000, 0x3f800000, 0x00000000, 0x3f000000)), - ('tri_t2', 'T1 +x: E03 (0,1), TRI0, mirrored fan, axes cycled (z->x), d=(0.5,0,0)', 'mirrored_fan_x_dominant', 0x09090909, 0, - (0x42c80000, 0xbf800000, 0x00000000, 0x3f800000, 0x3f000000, 0x00000000, 0x00000000, 0x40000000, 0x7f800000, 0x7f800000), - (0x7f800000, 0x3f800000, 0x00000000, 0x3f000000)), - ('tri_t2', 'T1 +x: E03 (0,1), TRI3, mirrored fan, axes cycled (z->x), d=(0.5,0,0)', 'mirrored_fan_x_dominant', 0x09090909, 3, - (0x42c80000, 0xbf800000, 0x00000000, 0x3f800000, 0x3f000000, 0x00000000, 0x00000000, 0x40000000, 0x7f800000, 0x7f800000), - (0x40800000, 0x3f000000, 0x00000000, 0x3e800000)), - ('tri_t2', 'T1 +x: E12 (2,2), TRI1, mirrored fan, axes cycled (z->x), d=(0.5,0,0)', 'mirrored_fan_x_dominant', 0x09090909, 1, - (0x42c80000, 0xbf800000, 0xc0000000, 0x40000000, 0x3f000000, 0x00000000, 0x00000000, 0x40000000, 0x7f800000, 0x7f800000), - (0x41000000, 0x3f800000, 0x3f000000, 0x3f000000)), - ('tri_t2', 'T1 +x: E12 (2,2), TRI2, mirrored fan, axes cycled (z->x), d=(0.5,0,0)', 'mirrored_fan_x_dominant', 0x09090909, 2, - (0x42c80000, 0xbf800000, 0xc0000000, 0x40000000, 0x3f000000, 0x00000000, 0x00000000, 0x40000000, 0x7f800000, 0x7f800000), - (0x7f800000, 0x3f000000, 0x3e800000, 0x00000000)), - ('tri_t2', 'T1 +x: E23 (-1,2.5), TRI2, mirrored fan, axes cycled (z->x), d=(0.5,0,0)', 'mirrored_fan_x_dominant', 0x09090909, 2, - (0x42c80000, 0xbf800000, 0x3f800000, 0x40200000, 0x3f000000, 0x00000000, 0x00000000, 0x40000000, 0x7f800000, 0x7f800000), - (0x7f800000, 0x3f000000, 0x00000000, 0x3e800000)), - ('tri_t2', 'T1 +x: E23 (-1,2.5), TRI3, mirrored fan, axes cycled (z->x), d=(0.5,0,0)', 'mirrored_fan_x_dominant', 0x09090909, 3, - (0x42c80000, 0xbf800000, 0x3f800000, 0x40200000, 0x3f000000, 0x00000000, 0x00000000, 0x40000000, 0x7f800000, 0x7f800000), - (0x40800000, 0x3f000000, 0x3e800000, 0x00000000)), - ('tri_t2', 'T1 +x: fan vertex s2 (0,2), TRI0, mirrored fan, axes cycled (z->x), d=(0.5,0,0)', 'mirrored_fan_x_dominant', 0x09090909, 0, - (0x42c80000, 0xbf800000, 0x00000000, 0x40000000, 0x3f000000, 0x00000000, 0x00000000, 0x40000000, 0x7f800000, 0x7f800000), - (0x7f800000, 0x3f800000, 0x00000000, 0x3f800000)), - ('tri_t2', 'T1 +x: fan vertex s2 (0,2), TRI1, mirrored fan, axes cycled (z->x), d=(0.5,0,0)', 'mirrored_fan_x_dominant', 0x09090909, 1, - (0x42c80000, 0xbf800000, 0x00000000, 0x40000000, 0x3f000000, 0x00000000, 0x00000000, 0x40000000, 0x7f800000, 0x7f800000), - (0x7f800000, 0x3f800000, 0x00000000, 0x3f800000)), - ('tri_t2', 'T1 +x: fan vertex s2 (0,2), TRI2, mirrored fan, axes cycled (z->x), d=(0.5,0,0)', 'mirrored_fan_x_dominant', 0x09090909, 2, - (0x42c80000, 0xbf800000, 0x00000000, 0x40000000, 0x3f000000, 0x00000000, 0x00000000, 0x40000000, 0x7f800000, 0x7f800000), - (0x7f800000, 0x3f000000, 0x00000000, 0x00000000)), - ('tri_t2', 'T1 +x: fan vertex s2 (0,2), TRI3, mirrored fan, axes cycled (z->x), d=(0.5,0,0)', 'mirrored_fan_x_dominant', 0x09090909, 3, - (0x42c80000, 0xbf800000, 0x00000000, 0x40000000, 0x3f000000, 0x00000000, 0x00000000, 0x40000000, 0x7f800000, 0x7f800000), - (0x40800000, 0x3f000000, 0x00000000, 0x00000000)), - ('tri_t2', 'T1 +x: outer edge s0-s1 (2,0), TRI0, mirrored fan, axes cycled (z->x), d=(0.5,0,0)', 'mirrored_fan_x_dominant', 0x09090909, 0, - (0x42c80000, 0xbf800000, 0xc0000000, 0x00000000, 0x3f000000, 0x00000000, 0x00000000, 0x40000000, 0x7f800000, 0x7f800000), - (0x7f800000, 0x3f800000, 0x3f000000, 0x00000000)), - ('tri_t2', 'T1 +x: outer vertex s0 (0,0), TRI0, mirrored fan, axes cycled (z->x), d=(0.5,0,0)', 'mirrored_fan_x_dominant', 0x09090909, 0, - (0x42c80000, 0xbf800000, 0x00000000, 0x00000000, 0x3f000000, 0x00000000, 0x00000000, 0x40000000, 0x7f800000, 0x7f800000), - (0x7f800000, 0x3f800000, 0x00000000, 0x00000000)), - ('tri_t2', 'T1 +x: outer vertex s1 (4,0), TRI0, mirrored fan, axes cycled (z->x), d=(0.5,0,0)', 'mirrored_fan_x_dominant', 0x09090909, 0, - (0x42c80000, 0xbf800000, 0xc0800000, 0x00000000, 0x3f000000, 0x00000000, 0x00000000, 0x40000000, 0x7f800000, 0x7f800000), - (0x7f800000, 0x3f800000, 0x3f800000, 0x00000000)), - ('tri_t2', 'T1 +x: E01 (2,1), TRI0, rotated mirrored fan, axes cycled (z->x), d=(0.5,0,0)', 'rotated_mirrored_fan_x_dominant', 0x09090909, 0, - (0x42c80000, 0xbf800000, 0x3f800000, 0x40000000, 0x3f000000, 0x00000000, 0x00000000, 0x40000000, 0x7f800000, 0x7f800000), - (0x7f800000, 0x3f800000, 0x3f000000, 0x3f000000)), - ('tri_t2', 'T1 +x: E01 (2,1), TRI1, rotated mirrored fan, axes cycled (z->x), d=(0.5,0,0)', 'rotated_mirrored_fan_x_dominant', 0x09090909, 1, - (0x42c80000, 0xbf800000, 0x3f800000, 0x40000000, 0x3f000000, 0x00000000, 0x00000000, 0x40000000, 0x7f800000, 0x7f800000), - (0x41000000, 0x3f800000, 0x00000000, 0x3f000000)), - ('tri_t2', 'T1 -x: E01 (2,1), TRI0, mirrored fan, axes cycled (z->x), d=(-0.5,0,0)', 'mirrored_fan_x_dominant', 0x09090909, 0, - (0x42c80000, 0x40e00000, 0xc0000000, 0x3f800000, 0xbf000000, 0x00000000, 0x00000000, 0xc0000000, 0x7f800000, 0x7f800000), - (0xc1000000, 0xbf800000, 0xbf000000, 0xbf000000)), - ('tri_t2', 'T1 -x: E01 (2,1), TRI1, mirrored fan, axes cycled (z->x), d=(-0.5,0,0)', 'mirrored_fan_x_dominant', 0x09090909, 1, - (0x42c80000, 0x40e00000, 0xc0000000, 0x3f800000, 0xbf000000, 0x00000000, 0x00000000, 0xc0000000, 0x7f800000, 0x7f800000), - (0xff800000, 0xbf800000, 0x00000000, 0xbf000000)), - ('tri_t2', 'T1 -x: E03 (0,1), TRI0, mirrored fan, axes cycled (z->x), d=(-0.5,0,0)', 'mirrored_fan_x_dominant', 0x09090909, 0, - (0x42c80000, 0x40e00000, 0x00000000, 0x3f800000, 0xbf000000, 0x00000000, 0x00000000, 0xc0000000, 0x7f800000, 0x7f800000), - (0xff800000, 0xbf800000, 0x00000000, 0xbf000000)), - ('tri_t2', 'T1 -x: E03 (0,1), TRI3, mirrored fan, axes cycled (z->x), d=(-0.5,0,0)', 'mirrored_fan_x_dominant', 0x09090909, 3, - (0x42c80000, 0x40e00000, 0x00000000, 0x3f800000, 0xbf000000, 0x00000000, 0x00000000, 0xc0000000, 0x7f800000, 0x7f800000), - (0xc0800000, 0xbf000000, 0x00000000, 0xbe800000)), - ('tri_t2', 'T1 -x: E12 (2,2), TRI1, mirrored fan, axes cycled (z->x), d=(-0.5,0,0)', 'mirrored_fan_x_dominant', 0x09090909, 1, - (0x42c80000, 0x40e00000, 0xc0000000, 0x40000000, 0xbf000000, 0x00000000, 0x00000000, 0xc0000000, 0x7f800000, 0x7f800000), - (0xff800000, 0xbf800000, 0xbf000000, 0xbf000000)), - ('tri_t2', 'T1 -x: E12 (2,2), TRI2, mirrored fan, axes cycled (z->x), d=(-0.5,0,0)', 'mirrored_fan_x_dominant', 0x09090909, 2, - (0x42c80000, 0x40e00000, 0xc0000000, 0x40000000, 0xbf000000, 0x00000000, 0x00000000, 0xc0000000, 0x7f800000, 0x7f800000), - (0xc0800000, 0xbf000000, 0xbe800000, 0x00000000)), - ('tri_t2', 'T1 -x: E23 (-1,2.5), TRI2, mirrored fan, axes cycled (z->x), d=(-0.5,0,0)', 'mirrored_fan_x_dominant', 0x09090909, 2, - (0x42c80000, 0x40e00000, 0x3f800000, 0x40200000, 0xbf000000, 0x00000000, 0x00000000, 0xc0000000, 0x7f800000, 0x7f800000), - (0xff800000, 0xbf000000, 0x00000000, 0xbe800000)), - ('tri_t2', 'T1 -x: E23 (-1,2.5), TRI3, mirrored fan, axes cycled (z->x), d=(-0.5,0,0)', 'mirrored_fan_x_dominant', 0x09090909, 3, - (0x42c80000, 0x40e00000, 0x3f800000, 0x40200000, 0xbf000000, 0x00000000, 0x00000000, 0xc0000000, 0x7f800000, 0x7f800000), - (0xc0800000, 0xbf000000, 0xbe800000, 0x00000000)), - ('tri_t2', 'T1 -x: fan vertex s2 (0,2), TRI0, mirrored fan, axes cycled (z->x), d=(-0.5,0,0)', 'mirrored_fan_x_dominant', 0x09090909, 0, - (0x42c80000, 0x40e00000, 0x00000000, 0x40000000, 0xbf000000, 0x00000000, 0x00000000, 0xc0000000, 0x7f800000, 0x7f800000), - (0xff800000, 0xbf800000, 0x00000000, 0xbf800000)), - ('tri_t2', 'T1 -x: fan vertex s2 (0,2), TRI1, mirrored fan, axes cycled (z->x), d=(-0.5,0,0)', 'mirrored_fan_x_dominant', 0x09090909, 1, - (0x42c80000, 0x40e00000, 0x00000000, 0x40000000, 0xbf000000, 0x00000000, 0x00000000, 0xc0000000, 0x7f800000, 0x7f800000), - (0xff800000, 0xbf800000, 0x00000000, 0xbf800000)), - ('tri_t2', 'T1 -x: fan vertex s2 (0,2), TRI2, mirrored fan, axes cycled (z->x), d=(-0.5,0,0)', 'mirrored_fan_x_dominant', 0x09090909, 2, - (0x42c80000, 0x40e00000, 0x00000000, 0x40000000, 0xbf000000, 0x00000000, 0x00000000, 0xc0000000, 0x7f800000, 0x7f800000), - (0xff800000, 0xbf000000, 0x00000000, 0x00000000)), - ('tri_t2', 'T1 -x: fan vertex s2 (0,2), TRI3, mirrored fan, axes cycled (z->x), d=(-0.5,0,0)', 'mirrored_fan_x_dominant', 0x09090909, 3, - (0x42c80000, 0x40e00000, 0x00000000, 0x40000000, 0xbf000000, 0x00000000, 0x00000000, 0xc0000000, 0x7f800000, 0x7f800000), - (0xc0800000, 0xbf000000, 0x00000000, 0x00000000)), - ('tri_t2', 'T1 -x: outer edge s0-s1 (2,0), TRI0, mirrored fan, axes cycled (z->x), d=(-0.5,0,0)', 'mirrored_fan_x_dominant', 0x09090909, 0, - (0x42c80000, 0x40e00000, 0xc0000000, 0x00000000, 0xbf000000, 0x00000000, 0x00000000, 0xc0000000, 0x7f800000, 0x7f800000), - (0xc1000000, 0xbf800000, 0xbf000000, 0x00000000)), - ('tri_t2', 'T1 -x: outer vertex s0 (0,0), TRI0, mirrored fan, axes cycled (z->x), d=(-0.5,0,0)', 'mirrored_fan_x_dominant', 0x09090909, 0, - (0x42c80000, 0x40e00000, 0x00000000, 0x00000000, 0xbf000000, 0x00000000, 0x00000000, 0xc0000000, 0x7f800000, 0x7f800000), - (0xff800000, 0xbf800000, 0x00000000, 0x00000000)), - ('tri_t3', 'control tri_g4b: shared edge E01 (2,1), TRI0, +z', 'fan', 0x09090909, 0, - (0x42c80000, 0x40000000, 0x3f800000, 0xbf800000, 0x00000000, 0x00000000, 0x3f000000, 0x7f800000, 0x7f800000, 0x40000000), - (0xff800000, 0xbf800000, 0xbf000000, 0xbf000000)), - ('tri_t3', 'T1 -x: outer vertex s1 (4,0), TRI0, mirrored fan, axes cycled (z->x), d=(-0.5,0,0)', 'mirrored_fan_x_dominant', 0x09090909, 0, - (0x42c80000, 0x40e00000, 0xc0800000, 0x00000000, 0xbf000000, 0x00000000, 0x00000000, 0xc0000000, 0x7f800000, 0x7f800000), - (0xc1000000, 0xbf800000, 0xbf800000, 0x00000000)), - ('tri_t3', 'T1 -x: E01 (2,1), TRI0, rotated mirrored fan, axes cycled (z->x), d=(-0.5,0,0)', 'rotated_mirrored_fan_x_dominant', 0x09090909, 0, - (0x42c80000, 0x40e00000, 0x3f800000, 0x40000000, 0xbf000000, 0x00000000, 0x00000000, 0xc0000000, 0x7f800000, 0x7f800000), - (0xff800000, 0xbf800000, 0xbf000000, 0xbf000000)), - ('tri_t3', 'T1 -x: E01 (2,1), TRI1, rotated mirrored fan, axes cycled (z->x), d=(-0.5,0,0)', 'rotated_mirrored_fan_x_dominant', 0x09090909, 1, - (0x42c80000, 0x40e00000, 0x3f800000, 0x40000000, 0xbf000000, 0x00000000, 0x00000000, 0xc0000000, 0x7f800000, 0x7f800000), - (0xc1000000, 0xbf800000, 0x00000000, 0xbf000000)), - ('tri_t3', 'T1 +y: E01 (2,1), TRI0, fan, axes cycled (z->y), d=(0,0.5,0)', 'fan_y_dominant', 0x09090909, 0, - (0x42c80000, 0x3f800000, 0xbf800000, 0x40000000, 0x00000000, 0x3f000000, 0x00000000, 0x7f800000, 0x40000000, 0x7f800000), - (0xff800000, 0xbf800000, 0xbf000000, 0xbf000000)), - ('tri_t3', 'T1 +y: E01 (2,1), TRI1, fan, axes cycled (z->y), d=(0,0.5,0)', 'fan_y_dominant', 0x09090909, 1, - (0x42c80000, 0x3f800000, 0xbf800000, 0x40000000, 0x00000000, 0x3f000000, 0x00000000, 0x7f800000, 0x40000000, 0x7f800000), - (0xc1000000, 0xbf800000, 0x00000000, 0xbf000000)), - ('tri_t3', 'T1 +y: E03 (0,1), TRI0, fan, axes cycled (z->y), d=(0,0.5,0)', 'fan_y_dominant', 0x09090909, 0, - (0x42c80000, 0x3f800000, 0xbf800000, 0x00000000, 0x00000000, 0x3f000000, 0x00000000, 0x7f800000, 0x40000000, 0x7f800000), - (0xc1000000, 0xbf800000, 0x00000000, 0xbf000000)), - ('tri_t3', 'T1 +y: E03 (0,1), TRI3, fan, axes cycled (z->y), d=(0,0.5,0)', 'fan_y_dominant', 0x09090909, 3, - (0x42c80000, 0x3f800000, 0xbf800000, 0x00000000, 0x00000000, 0x3f000000, 0x00000000, 0x7f800000, 0x40000000, 0x7f800000), - (0xff800000, 0xbf000000, 0x00000000, 0xbe800000)), - ('tri_t3', 'T1 +y: E12 (2,2), TRI1, fan, axes cycled (z->y), d=(0,0.5,0)', 'fan_y_dominant', 0x09090909, 1, - (0x42c80000, 0x40000000, 0xbf800000, 0x40000000, 0x00000000, 0x3f000000, 0x00000000, 0x7f800000, 0x40000000, 0x7f800000), - (0xc1000000, 0xbf800000, 0xbf000000, 0xbf000000)), - ('tri_t3', 'T1 +y: E12 (2,2), TRI2, fan, axes cycled (z->y), d=(0,0.5,0)', 'fan_y_dominant', 0x09090909, 2, - (0x42c80000, 0x40000000, 0xbf800000, 0x40000000, 0x00000000, 0x3f000000, 0x00000000, 0x7f800000, 0x40000000, 0x7f800000), - (0xff800000, 0xbf000000, 0xbe800000, 0x00000000)), - ('tri_t3', 'T1 +y: E23 (-1,2.5), TRI2, fan, axes cycled (z->y), d=(0,0.5,0)', 'fan_y_dominant', 0x09090909, 2, - (0x42c80000, 0x40200000, 0xbf800000, 0xbf800000, 0x00000000, 0x3f000000, 0x00000000, 0x7f800000, 0x40000000, 0x7f800000), - (0xc0800000, 0xbf000000, 0x00000000, 0xbe800000)), - ('tri_t3', 'T1 +y: E23 (-1,2.5), TRI3, fan, axes cycled (z->y), d=(0,0.5,0)', 'fan_y_dominant', 0x09090909, 3, - (0x42c80000, 0x40200000, 0xbf800000, 0xbf800000, 0x00000000, 0x3f000000, 0x00000000, 0x7f800000, 0x40000000, 0x7f800000), - (0xff800000, 0xbf000000, 0xbe800000, 0x00000000)), - ('tri_t3', 'T1 +y: fan vertex s2 (0,2), TRI0, fan, axes cycled (z->y), d=(0,0.5,0)', 'fan_y_dominant', 0x09090909, 0, - (0x42c80000, 0x40000000, 0xbf800000, 0x00000000, 0x00000000, 0x3f000000, 0x00000000, 0x7f800000, 0x40000000, 0x7f800000), - (0xff800000, 0xbf800000, 0x00000000, 0xbf800000)), - ('tri_t3', 'T1 +y: fan vertex s2 (0,2), TRI1, fan, axes cycled (z->y), d=(0,0.5,0)', 'fan_y_dominant', 0x09090909, 1, - (0x42c80000, 0x40000000, 0xbf800000, 0x00000000, 0x00000000, 0x3f000000, 0x00000000, 0x7f800000, 0x40000000, 0x7f800000), - (0xc1000000, 0xbf800000, 0x00000000, 0xbf800000)), - ('tri_t3', 'T1 +y: fan vertex s2 (0,2), TRI2, fan, axes cycled (z->y), d=(0,0.5,0)', 'fan_y_dominant', 0x09090909, 2, - (0x42c80000, 0x40000000, 0xbf800000, 0x00000000, 0x00000000, 0x3f000000, 0x00000000, 0x7f800000, 0x40000000, 0x7f800000), - (0xff800000, 0xbf000000, 0x00000000, 0x00000000)), - ('tri_t3', 'T1 +y: fan vertex s2 (0,2), TRI3, fan, axes cycled (z->y), d=(0,0.5,0)', 'fan_y_dominant', 0x09090909, 3, - (0x42c80000, 0x40000000, 0xbf800000, 0x00000000, 0x00000000, 0x3f000000, 0x00000000, 0x7f800000, 0x40000000, 0x7f800000), - (0xff800000, 0xbf000000, 0x00000000, 0x00000000)), - ('tri_t3', 'T1 +y: E01 (2,1), TRI0, rotated fan, axes cycled (z->y), d=(0,0.5,0)', 'rotated_fan_y_dominant', 0x09090909, 0, - (0x42c80000, 0x40000000, 0xbf800000, 0xbf800000, 0x00000000, 0x3f000000, 0x00000000, 0x7f800000, 0x40000000, 0x7f800000), - (0xc1000000, 0xbf800000, 0xbf000000, 0xbf000000)), - ('tri_t3', 'T1 +y: E01 (2,1), TRI1, rotated fan, axes cycled (z->y), d=(0,0.5,0)', 'rotated_fan_y_dominant', 0x09090909, 1, - (0x42c80000, 0x40000000, 0xbf800000, 0xbf800000, 0x00000000, 0x3f000000, 0x00000000, 0x7f800000, 0x40000000, 0x7f800000), - (0xff800000, 0xbf800000, 0x00000000, 0xbf000000)), - ('tri_t3', 'T1 -y: E01 (2,1), TRI0, fan, axes cycled (z->y), d=(0,-0.5,0)', 'fan_y_dominant', 0x09090909, 0, - (0x42c80000, 0x3f800000, 0x40e00000, 0x40000000, 0x00000000, 0xbf000000, 0x00000000, 0x7f800000, 0xc0000000, 0x7f800000), - (0x7f800000, 0x3f800000, 0x3f000000, 0x3f000000)), - ('tri_t3', 'T1 -y: E01 (2,1), TRI1, fan, axes cycled (z->y), d=(0,-0.5,0)', 'fan_y_dominant', 0x09090909, 1, - (0x42c80000, 0x3f800000, 0x40e00000, 0x40000000, 0x00000000, 0xbf000000, 0x00000000, 0x7f800000, 0xc0000000, 0x7f800000), - (0x41000000, 0x3f800000, 0x00000000, 0x3f000000)), - ('tri_t3', 'T1 -y: E03 (0,1), TRI0, fan, axes cycled (z->y), d=(0,-0.5,0)', 'fan_y_dominant', 0x09090909, 0, - (0x42c80000, 0x3f800000, 0x40e00000, 0x00000000, 0x00000000, 0xbf000000, 0x00000000, 0x7f800000, 0xc0000000, 0x7f800000), - (0x41000000, 0x3f800000, 0x00000000, 0x3f000000)), - ('tri_t3', 'T1 -y: E03 (0,1), TRI3, fan, axes cycled (z->y), d=(0,-0.5,0)', 'fan_y_dominant', 0x09090909, 3, - (0x42c80000, 0x3f800000, 0x40e00000, 0x00000000, 0x00000000, 0xbf000000, 0x00000000, 0x7f800000, 0xc0000000, 0x7f800000), - (0x7f800000, 0x3f000000, 0x00000000, 0x3e800000)), - ('tri_t3', 'T1 -y: E12 (2,2), TRI1, fan, axes cycled (z->y), d=(0,-0.5,0)', 'fan_y_dominant', 0x09090909, 1, - (0x42c80000, 0x40000000, 0x40e00000, 0x40000000, 0x00000000, 0xbf000000, 0x00000000, 0x7f800000, 0xc0000000, 0x7f800000), - (0x7f800000, 0x3f800000, 0x3f000000, 0x3f000000)), - ('tri_t3', 'T1 -y: E12 (2,2), TRI2, fan, axes cycled (z->y), d=(0,-0.5,0)', 'fan_y_dominant', 0x09090909, 2, - (0x42c80000, 0x40000000, 0x40e00000, 0x40000000, 0x00000000, 0xbf000000, 0x00000000, 0x7f800000, 0xc0000000, 0x7f800000), - (0x40800000, 0x3f000000, 0x3e800000, 0x00000000)), - ('tri_t3', 'T1 -y: E23 (-1,2.5), TRI2, fan, axes cycled (z->y), d=(0,-0.5,0)', 'fan_y_dominant', 0x09090909, 2, - (0x42c80000, 0x40200000, 0x40e00000, 0xbf800000, 0x00000000, 0xbf000000, 0x00000000, 0x7f800000, 0xc0000000, 0x7f800000), - (0x40800000, 0x3f000000, 0x00000000, 0x3e800000)), - ('tri_t3', 'T1 -y: E23 (-1,2.5), TRI3, fan, axes cycled (z->y), d=(0,-0.5,0)', 'fan_y_dominant', 0x09090909, 3, - (0x42c80000, 0x40200000, 0x40e00000, 0xbf800000, 0x00000000, 0xbf000000, 0x00000000, 0x7f800000, 0xc0000000, 0x7f800000), - (0x7f800000, 0x3f000000, 0x3e800000, 0x00000000)), - ('tri_t3', 'T1 -y: fan vertex s2 (0,2), TRI0, fan, axes cycled (z->y), d=(0,-0.5,0)', 'fan_y_dominant', 0x09090909, 0, - (0x42c80000, 0x40000000, 0x40e00000, 0x00000000, 0x00000000, 0xbf000000, 0x00000000, 0x7f800000, 0xc0000000, 0x7f800000), - (0x7f800000, 0x3f800000, 0x00000000, 0x3f800000)), - ('tri_t3', 'T1 -y: fan vertex s2 (0,2), TRI1, fan, axes cycled (z->y), d=(0,-0.5,0)', 'fan_y_dominant', 0x09090909, 1, - (0x42c80000, 0x40000000, 0x40e00000, 0x00000000, 0x00000000, 0xbf000000, 0x00000000, 0x7f800000, 0xc0000000, 0x7f800000), - (0x7f800000, 0x3f800000, 0x00000000, 0x3f800000)), - ('tri_t3', 'T1 -y: fan vertex s2 (0,2), TRI2, fan, axes cycled (z->y), d=(0,-0.5,0)', 'fan_y_dominant', 0x09090909, 2, - (0x42c80000, 0x40000000, 0x40e00000, 0x00000000, 0x00000000, 0xbf000000, 0x00000000, 0x7f800000, 0xc0000000, 0x7f800000), - (0x40800000, 0x3f000000, 0x00000000, 0x00000000)), - ('tri_t3', 'T1 -y: fan vertex s2 (0,2), TRI3, fan, axes cycled (z->y), d=(0,-0.5,0)', 'fan_y_dominant', 0x09090909, 3, - (0x42c80000, 0x40000000, 0x40e00000, 0x00000000, 0x00000000, 0xbf000000, 0x00000000, 0x7f800000, 0xc0000000, 0x7f800000), - (0x7f800000, 0x3f000000, 0x00000000, 0x00000000)), - ('tri_t3', 'T1 -y: outer edge s0-s1 (2,0), TRI0, fan, axes cycled (z->y), d=(0,-0.5,0)', 'fan_y_dominant', 0x09090909, 0, - (0x42c80000, 0x00000000, 0x40e00000, 0x40000000, 0x00000000, 0xbf000000, 0x00000000, 0x7f800000, 0xc0000000, 0x7f800000), - (0x41000000, 0x3f800000, 0x3f000000, 0x00000000)), - ('tri_t3', 'T1 -y: outer vertex s0 (0,0), TRI0, fan, axes cycled (z->y), d=(0,-0.5,0)', 'fan_y_dominant', 0x09090909, 0, - (0x42c80000, 0x00000000, 0x40e00000, 0x00000000, 0x00000000, 0xbf000000, 0x00000000, 0x7f800000, 0xc0000000, 0x7f800000), - (0x41000000, 0x3f800000, 0x00000000, 0x00000000)), - ('tri_t4', 'control tri_g4a: fan vertex s2 (0,2), TRI2, -z', 'fan', 0x09090909, 2, - (0x42c80000, 0x00000000, 0x40000000, 0x40e00000, 0x00000000, 0x00000000, 0xbf000000, 0x7f800000, 0x7f800000, 0xc0000000), - (0x40800000, 0x3f000000, 0x00000000, 0x00000000)), - ('tri_t4', 'T1 -y: outer vertex s1 (4,0), TRI0, fan, axes cycled (z->y), d=(0,-0.5,0)', 'fan_y_dominant', 0x09090909, 0, - (0x42c80000, 0x00000000, 0x40e00000, 0x40800000, 0x00000000, 0xbf000000, 0x00000000, 0x7f800000, 0xc0000000, 0x7f800000), - (0x7f800000, 0x3f800000, 0x3f800000, 0x00000000)), - ('tri_t4', 'T1 -y: E01 (2,1), TRI0, rotated fan, axes cycled (z->y), d=(0,-0.5,0)', 'rotated_fan_y_dominant', 0x09090909, 0, - (0x42c80000, 0x40000000, 0x40e00000, 0xbf800000, 0x00000000, 0xbf000000, 0x00000000, 0x7f800000, 0xc0000000, 0x7f800000), - (0x41000000, 0x3f800000, 0x3f000000, 0x3f000000)), - ('tri_t4', 'T1 -y: E01 (2,1), TRI1, rotated fan, axes cycled (z->y), d=(0,-0.5,0)', 'rotated_fan_y_dominant', 0x09090909, 1, - (0x42c80000, 0x40000000, 0x40e00000, 0xbf800000, 0x00000000, 0xbf000000, 0x00000000, 0x7f800000, 0xc0000000, 0x7f800000), - (0x7f800000, 0x3f800000, 0x00000000, 0x3f000000)), - ('tri_t4', 'T1 +y: E01 (2,1), TRI0, mirrored fan, axes cycled (z->y), d=(0,0.5,0)', 'mirrored_fan_y_dominant', 0x09090909, 0, - (0x42c80000, 0x3f800000, 0xbf800000, 0xc0000000, 0x00000000, 0x3f000000, 0x00000000, 0x7f800000, 0x40000000, 0x7f800000), - (0x41000000, 0x3f800000, 0x3f000000, 0x3f000000)), - ('tri_t4', 'T1 +y: E01 (2,1), TRI1, mirrored fan, axes cycled (z->y), d=(0,0.5,0)', 'mirrored_fan_y_dominant', 0x09090909, 1, - (0x42c80000, 0x3f800000, 0xbf800000, 0xc0000000, 0x00000000, 0x3f000000, 0x00000000, 0x7f800000, 0x40000000, 0x7f800000), - (0x7f800000, 0x3f800000, 0x00000000, 0x3f000000)), - ('tri_t4', 'T1 +y: E03 (0,1), TRI0, mirrored fan, axes cycled (z->y), d=(0,0.5,0)', 'mirrored_fan_y_dominant', 0x09090909, 0, - (0x42c80000, 0x3f800000, 0xbf800000, 0x00000000, 0x00000000, 0x3f000000, 0x00000000, 0x7f800000, 0x40000000, 0x7f800000), - (0x7f800000, 0x3f800000, 0x00000000, 0x3f000000)), - ('tri_t4', 'T1 +y: E03 (0,1), TRI3, mirrored fan, axes cycled (z->y), d=(0,0.5,0)', 'mirrored_fan_y_dominant', 0x09090909, 3, - (0x42c80000, 0x3f800000, 0xbf800000, 0x00000000, 0x00000000, 0x3f000000, 0x00000000, 0x7f800000, 0x40000000, 0x7f800000), - (0x40800000, 0x3f000000, 0x00000000, 0x3e800000)), - ('tri_t4', 'T1 +y: E12 (2,2), TRI1, mirrored fan, axes cycled (z->y), d=(0,0.5,0)', 'mirrored_fan_y_dominant', 0x09090909, 1, - (0x42c80000, 0x40000000, 0xbf800000, 0xc0000000, 0x00000000, 0x3f000000, 0x00000000, 0x7f800000, 0x40000000, 0x7f800000), - (0x41000000, 0x3f800000, 0x3f000000, 0x3f000000)), - ('tri_t4', 'T1 +y: E12 (2,2), TRI2, mirrored fan, axes cycled (z->y), d=(0,0.5,0)', 'mirrored_fan_y_dominant', 0x09090909, 2, - (0x42c80000, 0x40000000, 0xbf800000, 0xc0000000, 0x00000000, 0x3f000000, 0x00000000, 0x7f800000, 0x40000000, 0x7f800000), - (0x7f800000, 0x3f000000, 0x3e800000, 0x00000000)), - ('tri_t4', 'T1 +y: E23 (-1,2.5), TRI2, mirrored fan, axes cycled (z->y), d=(0,0.5,0)', 'mirrored_fan_y_dominant', 0x09090909, 2, - (0x42c80000, 0x40200000, 0xbf800000, 0x3f800000, 0x00000000, 0x3f000000, 0x00000000, 0x7f800000, 0x40000000, 0x7f800000), - (0x7f800000, 0x3f000000, 0x00000000, 0x3e800000)), - ('tri_t4', 'T1 +y: E23 (-1,2.5), TRI3, mirrored fan, axes cycled (z->y), d=(0,0.5,0)', 'mirrored_fan_y_dominant', 0x09090909, 3, - (0x42c80000, 0x40200000, 0xbf800000, 0x3f800000, 0x00000000, 0x3f000000, 0x00000000, 0x7f800000, 0x40000000, 0x7f800000), - (0x40800000, 0x3f000000, 0x3e800000, 0x00000000)), - ('tri_t4', 'T1 +y: fan vertex s2 (0,2), TRI0, mirrored fan, axes cycled (z->y), d=(0,0.5,0)', 'mirrored_fan_y_dominant', 0x09090909, 0, - (0x42c80000, 0x40000000, 0xbf800000, 0x00000000, 0x00000000, 0x3f000000, 0x00000000, 0x7f800000, 0x40000000, 0x7f800000), - (0x7f800000, 0x3f800000, 0x00000000, 0x3f800000)), - ('tri_t4', 'T1 +y: fan vertex s2 (0,2), TRI1, mirrored fan, axes cycled (z->y), d=(0,0.5,0)', 'mirrored_fan_y_dominant', 0x09090909, 1, - (0x42c80000, 0x40000000, 0xbf800000, 0x00000000, 0x00000000, 0x3f000000, 0x00000000, 0x7f800000, 0x40000000, 0x7f800000), - (0x7f800000, 0x3f800000, 0x00000000, 0x3f800000)), - ('tri_t4', 'T1 +y: fan vertex s2 (0,2), TRI2, mirrored fan, axes cycled (z->y), d=(0,0.5,0)', 'mirrored_fan_y_dominant', 0x09090909, 2, - (0x42c80000, 0x40000000, 0xbf800000, 0x00000000, 0x00000000, 0x3f000000, 0x00000000, 0x7f800000, 0x40000000, 0x7f800000), - (0x7f800000, 0x3f000000, 0x00000000, 0x00000000)), - ('tri_t4', 'T1 +y: fan vertex s2 (0,2), TRI3, mirrored fan, axes cycled (z->y), d=(0,0.5,0)', 'mirrored_fan_y_dominant', 0x09090909, 3, - (0x42c80000, 0x40000000, 0xbf800000, 0x00000000, 0x00000000, 0x3f000000, 0x00000000, 0x7f800000, 0x40000000, 0x7f800000), - (0x40800000, 0x3f000000, 0x00000000, 0x00000000)), - ('tri_t4', 'T1 +y: outer edge s0-s1 (2,0), TRI0, mirrored fan, axes cycled (z->y), d=(0,0.5,0)', 'mirrored_fan_y_dominant', 0x09090909, 0, - (0x42c80000, 0x00000000, 0xbf800000, 0xc0000000, 0x00000000, 0x3f000000, 0x00000000, 0x7f800000, 0x40000000, 0x7f800000), - (0x7f800000, 0x3f800000, 0x3f000000, 0x00000000)), - ('tri_t4', 'T1 +y: outer vertex s0 (0,0), TRI0, mirrored fan, axes cycled (z->y), d=(0,0.5,0)', 'mirrored_fan_y_dominant', 0x09090909, 0, - (0x42c80000, 0x00000000, 0xbf800000, 0x00000000, 0x00000000, 0x3f000000, 0x00000000, 0x7f800000, 0x40000000, 0x7f800000), - (0x7f800000, 0x3f800000, 0x00000000, 0x00000000)), - ('tri_t4', 'T1 +y: outer vertex s1 (4,0), TRI0, mirrored fan, axes cycled (z->y), d=(0,0.5,0)', 'mirrored_fan_y_dominant', 0x09090909, 0, - (0x42c80000, 0x00000000, 0xbf800000, 0xc0800000, 0x00000000, 0x3f000000, 0x00000000, 0x7f800000, 0x40000000, 0x7f800000), - (0x7f800000, 0x3f800000, 0x3f800000, 0x00000000)), - ('tri_t4', 'T1 +y: E01 (2,1), TRI0, rotated mirrored fan, axes cycled (z->y), d=(0,0.5,0)', 'rotated_mirrored_fan_y_dominant', 0x09090909, 0, - (0x42c80000, 0x40000000, 0xbf800000, 0x3f800000, 0x00000000, 0x3f000000, 0x00000000, 0x7f800000, 0x40000000, 0x7f800000), - (0x7f800000, 0x3f800000, 0x3f000000, 0x3f000000)), - ('tri_t4', 'T1 +y: E01 (2,1), TRI1, rotated mirrored fan, axes cycled (z->y), d=(0,0.5,0)', 'rotated_mirrored_fan_y_dominant', 0x09090909, 1, - (0x42c80000, 0x40000000, 0xbf800000, 0x3f800000, 0x00000000, 0x3f000000, 0x00000000, 0x7f800000, 0x40000000, 0x7f800000), - (0x41000000, 0x3f800000, 0x00000000, 0x3f000000)), - ('tri_t4', 'T1 -y: E01 (2,1), TRI0, mirrored fan, axes cycled (z->y), d=(0,-0.5,0)', 'mirrored_fan_y_dominant', 0x09090909, 0, - (0x42c80000, 0x3f800000, 0x40e00000, 0xc0000000, 0x00000000, 0xbf000000, 0x00000000, 0x7f800000, 0xc0000000, 0x7f800000), - (0xc1000000, 0xbf800000, 0xbf000000, 0xbf000000)), - ('tri_t4', 'T1 -y: E01 (2,1), TRI1, mirrored fan, axes cycled (z->y), d=(0,-0.5,0)', 'mirrored_fan_y_dominant', 0x09090909, 1, - (0x42c80000, 0x3f800000, 0x40e00000, 0xc0000000, 0x00000000, 0xbf000000, 0x00000000, 0x7f800000, 0xc0000000, 0x7f800000), - (0xff800000, 0xbf800000, 0x00000000, 0xbf000000)), - ('tri_t4', 'T1 -y: E03 (0,1), TRI0, mirrored fan, axes cycled (z->y), d=(0,-0.5,0)', 'mirrored_fan_y_dominant', 0x09090909, 0, - (0x42c80000, 0x3f800000, 0x40e00000, 0x00000000, 0x00000000, 0xbf000000, 0x00000000, 0x7f800000, 0xc0000000, 0x7f800000), - (0xff800000, 0xbf800000, 0x00000000, 0xbf000000)), - ('tri_t4', 'T1 -y: E03 (0,1), TRI3, mirrored fan, axes cycled (z->y), d=(0,-0.5,0)', 'mirrored_fan_y_dominant', 0x09090909, 3, - (0x42c80000, 0x3f800000, 0x40e00000, 0x00000000, 0x00000000, 0xbf000000, 0x00000000, 0x7f800000, 0xc0000000, 0x7f800000), - (0xc0800000, 0xbf000000, 0x00000000, 0xbe800000)), - ('tri_t4', 'T1 -y: E12 (2,2), TRI1, mirrored fan, axes cycled (z->y), d=(0,-0.5,0)', 'mirrored_fan_y_dominant', 0x09090909, 1, - (0x42c80000, 0x40000000, 0x40e00000, 0xc0000000, 0x00000000, 0xbf000000, 0x00000000, 0x7f800000, 0xc0000000, 0x7f800000), - (0xff800000, 0xbf800000, 0xbf000000, 0xbf000000)), - ('tri_t4', 'T1 -y: E12 (2,2), TRI2, mirrored fan, axes cycled (z->y), d=(0,-0.5,0)', 'mirrored_fan_y_dominant', 0x09090909, 2, - (0x42c80000, 0x40000000, 0x40e00000, 0xc0000000, 0x00000000, 0xbf000000, 0x00000000, 0x7f800000, 0xc0000000, 0x7f800000), - (0xc0800000, 0xbf000000, 0xbe800000, 0x00000000)), - ('tri_t4', 'T1 -y: E23 (-1,2.5), TRI2, mirrored fan, axes cycled (z->y), d=(0,-0.5,0)', 'mirrored_fan_y_dominant', 0x09090909, 2, - (0x42c80000, 0x40200000, 0x40e00000, 0x3f800000, 0x00000000, 0xbf000000, 0x00000000, 0x7f800000, 0xc0000000, 0x7f800000), - (0xff800000, 0xbf000000, 0x00000000, 0xbe800000)), - ('tri_t4', 'T1 -y: E23 (-1,2.5), TRI3, mirrored fan, axes cycled (z->y), d=(0,-0.5,0)', 'mirrored_fan_y_dominant', 0x09090909, 3, - (0x42c80000, 0x40200000, 0x40e00000, 0x3f800000, 0x00000000, 0xbf000000, 0x00000000, 0x7f800000, 0xc0000000, 0x7f800000), - (0xc0800000, 0xbf000000, 0xbe800000, 0x00000000)), - ('tri_t4', 'T1 -y: fan vertex s2 (0,2), TRI0, mirrored fan, axes cycled (z->y), d=(0,-0.5,0)', 'mirrored_fan_y_dominant', 0x09090909, 0, - (0x42c80000, 0x40000000, 0x40e00000, 0x00000000, 0x00000000, 0xbf000000, 0x00000000, 0x7f800000, 0xc0000000, 0x7f800000), - (0xff800000, 0xbf800000, 0x00000000, 0xbf800000)), - ('tri_t4', 'T1 -y: fan vertex s2 (0,2), TRI1, mirrored fan, axes cycled (z->y), d=(0,-0.5,0)', 'mirrored_fan_y_dominant', 0x09090909, 1, - (0x42c80000, 0x40000000, 0x40e00000, 0x00000000, 0x00000000, 0xbf000000, 0x00000000, 0x7f800000, 0xc0000000, 0x7f800000), - (0xff800000, 0xbf800000, 0x00000000, 0xbf800000)), - ('tri_t4', 'T1 -y: fan vertex s2 (0,2), TRI2, mirrored fan, axes cycled (z->y), d=(0,-0.5,0)', 'mirrored_fan_y_dominant', 0x09090909, 2, - (0x42c80000, 0x40000000, 0x40e00000, 0x00000000, 0x00000000, 0xbf000000, 0x00000000, 0x7f800000, 0xc0000000, 0x7f800000), - (0xff800000, 0xbf000000, 0x00000000, 0x00000000)), - ('tri_t5', 'control tri_g4b: shared edge E12 (2,2), TRI2, -z', 'fan', 0x09090909, 2, - (0x42c80000, 0x40000000, 0x40000000, 0x40e00000, 0x00000000, 0x00000000, 0xbf000000, 0x7f800000, 0x7f800000, 0xc0000000), - (0x40800000, 0x3f000000, 0x3e800000, 0x00000000)), - ('tri_t5', 'T1 -y: fan vertex s2 (0,2), TRI3, mirrored fan, axes cycled (z->y), d=(0,-0.5,0)', 'mirrored_fan_y_dominant', 0x09090909, 3, - (0x42c80000, 0x40000000, 0x40e00000, 0x00000000, 0x00000000, 0xbf000000, 0x00000000, 0x7f800000, 0xc0000000, 0x7f800000), - (0xc0800000, 0xbf000000, 0x00000000, 0x00000000)), - ('tri_t5', 'T1 -y: outer edge s0-s1 (2,0), TRI0, mirrored fan, axes cycled (z->y), d=(0,-0.5,0)', 'mirrored_fan_y_dominant', 0x09090909, 0, - (0x42c80000, 0x00000000, 0x40e00000, 0xc0000000, 0x00000000, 0xbf000000, 0x00000000, 0x7f800000, 0xc0000000, 0x7f800000), - (0xc1000000, 0xbf800000, 0xbf000000, 0x00000000)), - ('tri_t5', 'T1 -y: outer vertex s0 (0,0), TRI0, mirrored fan, axes cycled (z->y), d=(0,-0.5,0)', 'mirrored_fan_y_dominant', 0x09090909, 0, - (0x42c80000, 0x00000000, 0x40e00000, 0x00000000, 0x00000000, 0xbf000000, 0x00000000, 0x7f800000, 0xc0000000, 0x7f800000), - (0xff800000, 0xbf800000, 0x00000000, 0x00000000)), - ('tri_t5', 'T1 -y: outer vertex s1 (4,0), TRI0, mirrored fan, axes cycled (z->y), d=(0,-0.5,0)', 'mirrored_fan_y_dominant', 0x09090909, 0, - (0x42c80000, 0x00000000, 0x40e00000, 0xc0800000, 0x00000000, 0xbf000000, 0x00000000, 0x7f800000, 0xc0000000, 0x7f800000), - (0xc1000000, 0xbf800000, 0xbf800000, 0x00000000)), - ('tri_t5', 'T1 -y: E01 (2,1), TRI0, rotated mirrored fan, axes cycled (z->y), d=(0,-0.5,0)', 'rotated_mirrored_fan_y_dominant', 0x09090909, 0, - (0x42c80000, 0x40000000, 0x40e00000, 0x3f800000, 0x00000000, 0xbf000000, 0x00000000, 0x7f800000, 0xc0000000, 0x7f800000), - (0xff800000, 0xbf800000, 0xbf000000, 0xbf000000)), - ('tri_t5', 'T1 -y: E01 (2,1), TRI1, rotated mirrored fan, axes cycled (z->y), d=(0,-0.5,0)', 'rotated_mirrored_fan_y_dominant', 0x09090909, 1, - (0x42c80000, 0x40000000, 0x40e00000, 0x3f800000, 0x00000000, 0xbf000000, 0x00000000, 0x7f800000, 0xc0000000, 0x7f800000), - (0xc1000000, 0xbf800000, 0x00000000, 0xbf000000)), - ('tri_t5', 'T2 x-dominant: E01 (2,1), TRI0, fan on z=3+1x+0y, axes cycled (z->x), d=(0.5,0.125,-0.25)', 'fan_tilted_p1x_p0y_x_dominant', 0x09090909, 0, - (0x42c80000, 0x3f800000, 0x3f800000, 0x40400000, 0x3f000000, 0x3e000000, 0xbe800000, 0x40000000, 0x41000000, 0xc0800000), - (0xc0c00000, 0xbf400000, 0xbec00000, 0xbec00000)), - ('tri_t5', 'T2 x-dominant: E01 (2,1), TRI1, fan on z=3+1x+0y, axes cycled (z->x), d=(0.5,0.125,-0.25)', 'fan_tilted_p1x_p0y_x_dominant', 0x09090909, 1, - (0x42c80000, 0x3f800000, 0x3f800000, 0x40400000, 0x3f000000, 0x3e000000, 0xbe800000, 0x40000000, 0x41000000, 0xc0800000), - (0xff800000, 0xbf400000, 0x00000000, 0xbec00000)), - ('tri_t5', 'T2 x-dominant: E03 (0,1), TRI0, fan on z=3+1x+0y, axes cycled (z->x), d=(0.5,0.125,-0.25)', 'fan_tilted_p1x_p0y_x_dominant', 0x09090909, 0, - (0x42c80000, 0xbf800000, 0xbf800000, 0x40400000, 0x3f000000, 0x3e000000, 0xbe800000, 0x40000000, 0x41000000, 0xc0800000), - (0xc0c00000, 0xbf400000, 0x00000000, 0xbec00000)), - ('tri_t5', 'T2 x-dominant: E03 (0,1), TRI3, fan on z=3+1x+0y, axes cycled (z->x), d=(0.5,0.125,-0.25)', 'fan_tilted_p1x_p0y_x_dominant', 0x09090909, 3, - (0x42c80000, 0xbf800000, 0xbf800000, 0x40400000, 0x3f000000, 0x3e000000, 0xbe800000, 0x40000000, 0x41000000, 0xc0800000), - (0xff800000, 0xbec00000, 0x00000000, 0xbe400000)), - ('tri_t5', 'T2 x-dominant: E12 (2,2), TRI1, fan on z=3+1x+0y, axes cycled (z->x), d=(0.5,0.125,-0.25)', 'fan_tilted_p1x_p0y_x_dominant', 0x09090909, 1, - (0x42c80000, 0x3f800000, 0x3f800000, 0x40800000, 0x3f000000, 0x3e000000, 0xbe800000, 0x40000000, 0x41000000, 0xc0800000), - (0xc0c00000, 0xbf400000, 0xbec00000, 0xbec00000)), - ('tri_t5', 'T2 x-dominant: E12 (2,2), TRI2, fan on z=3+1x+0y, axes cycled (z->x), d=(0.5,0.125,-0.25)', 'fan_tilted_p1x_p0y_x_dominant', 0x09090909, 2, - (0x42c80000, 0x3f800000, 0x3f800000, 0x40800000, 0x3f000000, 0x3e000000, 0xbe800000, 0x40000000, 0x41000000, 0xc0800000), - (0xff800000, 0xbec00000, 0xbe400000, 0x00000000)), - ('tri_t5', 'T2 x-dominant: E23 (-1,2.5), TRI2, fan on z=3+1x+0y, axes cycled (z->x), d=(0.5,0.125,-0.25)', 'fan_tilted_p1x_p0y_x_dominant', 0x09090909, 2, - (0x42c80000, 0xc0000000, 0xc0000000, 0x40900000, 0x3f000000, 0x3e000000, 0xbe800000, 0x40000000, 0x41000000, 0xc0800000), - (0xff800000, 0xbec00000, 0x00000000, 0xbe400000)), - ('tri_t5', 'T2 x-dominant: E23 (-1,2.5), TRI3, fan on z=3+1x+0y, axes cycled (z->x), d=(0.5,0.125,-0.25)', 'fan_tilted_p1x_p0y_x_dominant', 0x09090909, 3, - (0x42c80000, 0xc0000000, 0xc0000000, 0x40900000, 0x3f000000, 0x3e000000, 0xbe800000, 0x40000000, 0x41000000, 0xc0800000), - (0xc0400000, 0xbec00000, 0xbe400000, 0x00000000)), - ('tri_t5', 'T2 x-dominant: fan vertex s2 (0,2), TRI0, fan on z=3+1x+0y, axes cycled (z->x), d=(0.5,0.125,-0.25)', 'fan_tilted_p1x_p0y_x_dominant', 0x09090909, 0, - (0x42c80000, 0xbf800000, 0xbf800000, 0x40800000, 0x3f000000, 0x3e000000, 0xbe800000, 0x40000000, 0x41000000, 0xc0800000), - (0xc0c00000, 0xbf400000, 0x00000000, 0xbf400000)), - ('tri_t5', 'T2 x-dominant: fan vertex s2 (0,2), TRI1, fan on z=3+1x+0y, axes cycled (z->x), d=(0.5,0.125,-0.25)', 'fan_tilted_p1x_p0y_x_dominant', 0x09090909, 1, - (0x42c80000, 0xbf800000, 0xbf800000, 0x40800000, 0x3f000000, 0x3e000000, 0xbe800000, 0x40000000, 0x41000000, 0xc0800000), - (0xff800000, 0xbf400000, 0x00000000, 0xbf400000)), - ('tri_t5', 'T2 x-dominant: fan vertex s2 (0,2), TRI2, fan on z=3+1x+0y, axes cycled (z->x), d=(0.5,0.125,-0.25)', 'fan_tilted_p1x_p0y_x_dominant', 0x09090909, 2, - (0x42c80000, 0xbf800000, 0xbf800000, 0x40800000, 0x3f000000, 0x3e000000, 0xbe800000, 0x40000000, 0x41000000, 0xc0800000), - (0xff800000, 0xbec00000, 0x00000000, 0x00000000)), - ('tri_t5', 'T2 x-dominant: fan vertex s2 (0,2), TRI3, fan on z=3+1x+0y, axes cycled (z->x), d=(0.5,0.125,-0.25)', 'fan_tilted_p1x_p0y_x_dominant', 0x09090909, 3, - (0x42c80000, 0xbf800000, 0xbf800000, 0x40800000, 0x3f000000, 0x3e000000, 0xbe800000, 0x40000000, 0x41000000, 0xc0800000), - (0xff800000, 0xbec00000, 0x00000000, 0x00000000)), - ('tri_t5', 'T2 y-dominant: E01 (2,1), TRI0, mirrored fan on z=3+1x+1y, axes cycled (z->y), d=(-0.25,-0.5,-0.125)', 'mirrored_fan_tilted_p1x_p1y_y_dominant', 0x09090909, 0, - (0x42c80000, 0x40400000, 0x40c00000, 0xbf800000, 0xbe800000, 0xbf000000, 0xbe000000, 0xc0800000, 0xc0000000, 0xc1000000), - (0xff800000, 0xbe800000, 0xbe000000, 0xbe000000)), - ('tri_t5', 'T2 y-dominant: E01 (2,1), TRI1, mirrored fan on z=3+1x+1y, axes cycled (z->y), d=(-0.25,-0.5,-0.125)', 'mirrored_fan_tilted_p1x_p1y_y_dominant', 0x09090909, 1, - (0x42c80000, 0x40400000, 0x40c00000, 0xbf800000, 0xbe800000, 0xbf000000, 0xbe000000, 0xc0800000, 0xc0000000, 0xc1000000), - (0xc0000000, 0xbe800000, 0x00000000, 0xbe000000)), - ('tri_t5', 'T2 y-dominant: E03 (0,1), TRI0, mirrored fan on z=3+1x+1y, axes cycled (z->y), d=(-0.25,-0.5,-0.125)', 'mirrored_fan_tilted_p1x_p1y_y_dominant', 0x09090909, 0, - (0x42c80000, 0x40400000, 0x41000000, 0x3f800000, 0xbe800000, 0xbf000000, 0xbe000000, 0xc0800000, 0xc0000000, 0xc1000000), - (0xff800000, 0xbe800000, 0x00000000, 0xbe000000)), - ('tri_t5', 'T2 y-dominant: E03 (0,1), TRI3, mirrored fan on z=3+1x+1y, axes cycled (z->y), d=(-0.25,-0.5,-0.125)', 'mirrored_fan_tilted_p1x_p1y_y_dominant', 0x09090909, 3, - (0x42c80000, 0x40400000, 0x41000000, 0x3f800000, 0xbe800000, 0xbf000000, 0xbe000000, 0xc0800000, 0xc0000000, 0xc1000000), - (0xbf800000, 0xbe000000, 0x00000000, 0xbd800000)), - ('tri_t5', 'T2 y-dominant: E12 (2,2), TRI1, mirrored fan on z=3+1x+1y, axes cycled (z->y), d=(-0.25,-0.5,-0.125)', 'mirrored_fan_tilted_p1x_p1y_y_dominant', 0x09090909, 1, - (0x42c80000, 0x40800000, 0x40e00000, 0xbf800000, 0xbe800000, 0xbf000000, 0xbe000000, 0xc0800000, 0xc0000000, 0xc1000000), - (0xff800000, 0xbe800000, 0xbe000000, 0xbe000000)), - ('tri_t5', 'T2 y-dominant: E12 (2,2), TRI2, mirrored fan on z=3+1x+1y, axes cycled (z->y), d=(-0.25,-0.5,-0.125)', 'mirrored_fan_tilted_p1x_p1y_y_dominant', 0x09090909, 2, - (0x42c80000, 0x40800000, 0x40e00000, 0xbf800000, 0xbe800000, 0xbf000000, 0xbe000000, 0xc0800000, 0xc0000000, 0xc1000000), - (0xbf800000, 0xbe000000, 0xbd800000, 0x00000000)), - ('tri_t5', 'T2 y-dominant: E23 (-1,2.5), TRI2, mirrored fan on z=3+1x+1y, axes cycled (z->y), d=(-0.25,-0.5,-0.125)', 'mirrored_fan_tilted_p1x_p1y_y_dominant', 0x09090909, 2, - (0x42c80000, 0x40900000, 0x41280000, 0x40000000, 0xbe800000, 0xbf000000, 0xbe000000, 0xc0800000, 0xc0000000, 0xc1000000), - (0xbf800000, 0xbe000000, 0x00000000, 0xbd800000)), - ('tri_t5', 'T2 y-dominant: E23 (-1,2.5), TRI3, mirrored fan on z=3+1x+1y, axes cycled (z->y), d=(-0.25,-0.5,-0.125)', 'mirrored_fan_tilted_p1x_p1y_y_dominant', 0x09090909, 3, - (0x42c80000, 0x40900000, 0x41280000, 0x40000000, 0xbe800000, 0xbf000000, 0xbe000000, 0xc0800000, 0xc0000000, 0xc1000000), - (0xff800000, 0xbe000000, 0xbd800000, 0x00000000)), - ('tri_t5', 'T2 y-dominant: fan vertex s2 (0,2), TRI0, mirrored fan on z=3+1x+1y, axes cycled (z->y), d=(-0.25,-0.5,-0.125)', 'mirrored_fan_tilted_p1x_p1y_y_dominant', 0x09090909, 0, - (0x42c80000, 0x40800000, 0x41100000, 0x3f800000, 0xbe800000, 0xbf000000, 0xbe000000, 0xc0800000, 0xc0000000, 0xc1000000), - (0xff800000, 0xbe800000, 0x00000000, 0xbe800000)), - ('tri_t5', 'T2 y-dominant: fan vertex s2 (0,2), TRI1, mirrored fan on z=3+1x+1y, axes cycled (z->y), d=(-0.25,-0.5,-0.125)', 'mirrored_fan_tilted_p1x_p1y_y_dominant', 0x09090909, 1, - (0x42c80000, 0x40800000, 0x41100000, 0x3f800000, 0xbe800000, 0xbf000000, 0xbe000000, 0xc0800000, 0xc0000000, 0xc1000000), - (0xff800000, 0xbe800000, 0x00000000, 0xbe800000)), - ('tri_t5', 'T2 y-dominant: fan vertex s2 (0,2), TRI2, mirrored fan on z=3+1x+1y, axes cycled (z->y), d=(-0.25,-0.5,-0.125)', 'mirrored_fan_tilted_p1x_p1y_y_dominant', 0x09090909, 2, - (0x42c80000, 0x40800000, 0x41100000, 0x3f800000, 0xbe800000, 0xbf000000, 0xbe000000, 0xc0800000, 0xc0000000, 0xc1000000), - (0xbf800000, 0xbe000000, 0x00000000, 0x00000000)), - ('tri_t5', 'T2 y-dominant: fan vertex s2 (0,2), TRI3, mirrored fan on z=3+1x+1y, axes cycled (z->y), d=(-0.25,-0.5,-0.125)', 'mirrored_fan_tilted_p1x_p1y_y_dominant', 0x09090909, 3, - (0x42c80000, 0x40800000, 0x41100000, 0x3f800000, 0xbe800000, 0xbf000000, 0xbe000000, 0xc0800000, 0xc0000000, 0xc1000000), - (0xff800000, 0xbe000000, 0x00000000, 0x00000000)), - ('tri_t5', 'T3 |dx|=|dy|>|dz|: TRI0 interior hit, fan, d=(0.5,-0.5,0.25)', 'fan', 0x09090909, 0, - (0x42c80000, 0xc0400000, 0x40880000, 0x3f800000, 0x3f000000, 0xbf000000, 0x3e800000, 0x40000000, 0xc0000000, 0x40800000), - (0xc0800000, 0xbf000000, 0xbe000000, 0xbd800000)), - ('tri_t6', 'control tri_g1b: TRI0 dominant +x', 'fan_x_dominant', 0x09090909, 0, - (0x42c80000, 0xbf800000, 0x3f800000, 0x3e800000, 0x3f000000, 0x00000000, 0x00000000, 0x40000000, 0x7f800000, 0x7f800000), - (0xc1000000, 0xbf800000, 0xbe800000, 0xbe000000)), - ('tri_t6', 'T3 |dx|=|dy|>|dz|: TRI1 interior hit, fan, d=(-0.5,-0.5,0.25)', 'fan', 0x09090909, 1, - (0x42c80000, 0x40f00000, 0x40a80000, 0x3f800000, 0xbf000000, 0xbf000000, 0x3e800000, 0xc0000000, 0xc0000000, 0x40800000), - (0xc0800000, 0xbf000000, 0xbe800000, 0xbd800000)), - ('tri_t6', "T3 |dx|=|dy|>|dz|: TRI0 miss (at TRI1's point), fan, d=(-0.5,-0.5,0.25)", 'fan', 0x09090909, 0, - (0x42c80000, 0x40f00000, 0x40a80000, 0x3f800000, 0xbf000000, 0xbf000000, 0x3e800000, 0xc0000000, 0xc0000000, 0x40800000), - (0xff800000, 0xbf000000, 0xbee00000, 0xbea00000)), - ('tri_t6', 'T3 |dx|=|dz|>|dy|: TRI2 interior hit, fan, d=(0.5,0.125,-0.5)', 'fan', 0x09090909, 2, - (0x42c80000, 0xc0100000, 0x3f900000, 0x40e00000, 0x3f000000, 0x3e000000, 0xbf000000, 0x40000000, 0x41000000, 0xc0000000), - (0x40800000, 0x3f000000, 0x3e800000, 0x3d800000)), - ('tri_t6', 'T3 |dx|=|dz|>|dy|: TRI3 interior hit, fan, d=(-0.5,0.125,-0.5)', 'fan', 0x09090909, 3, - (0x42c80000, 0x40600000, 0x3f800000, 0x40e00000, 0xbf000000, 0x3e000000, 0xbf000000, 0xc0000000, 0x41000000, 0xc0000000), - (0x40800000, 0x3f000000, 0x3e000000, 0x3d800000)), - ('tri_t6', 'T3 |dy|=|dz|>|dx|: TRI0 interior hit, fan, d=(0.125,0.5,-0.5)', 'fan', 0x09090909, 0, - (0x42c80000, 0x00000000, 0xc0700000, 0x40e00000, 0x3e000000, 0x3f000000, 0xbf000000, 0x41000000, 0x40000000, 0xc0000000), - (0x41000000, 0x3f800000, 0x3e800000, 0x3e000000)), - ('tri_t6', 'T3 |dy|=|dz|>|dx|: TRI1 interior hit, fan, d=(0.125,-0.5,-0.5)', 'fan', 0x09090909, 1, - (0x42c80000, 0x40200000, 0x40a80000, 0x40e00000, 0x3e000000, 0xbf000000, 0xbf000000, 0x41000000, 0xc0000000, 0xc0000000), - (0x41000000, 0x3f800000, 0x3f000000, 0x3e000000)), - ('tri_t6', 'T3 |dx|=|dy|=|dz|: TRI2 interior hit, fan, d=(0.5,0.5,-0.5)', 'fan', 0x09090909, 2, - (0x42c80000, 0xc0100000, 0xbff00000, 0x40e00000, 0x3f000000, 0x3f000000, 0xbf000000, 0x40000000, 0x40000000, 0xc0000000), - (0x40800000, 0x3f000000, 0x3e800000, 0x3d800000)), - ('tri_t6', 'T3 |dx|=|dy|=|dz|: TRI3 interior hit, fan, d=(-0.5,0.5,0.5)', 'fan', 0x09090909, 3, - (0x42c80000, 0x40600000, 0xc0000000, 0xbf800000, 0xbf000000, 0x3f000000, 0x3f000000, 0xc0000000, 0x40000000, 0x40000000), - (0xc0800000, 0xbf000000, 0xbe000000, 0xbd800000)), - ('tri_t6', "T3 |dx|=|dy|=|dz|: TRI0 miss (at TRI1's point), fan, d=(-0.5,0.5,0.5)", 'fan', 0x09090909, 0, - (0x42c80000, 0x40f00000, 0xc0300000, 0xbf800000, 0xbf000000, 0x3f000000, 0x3f000000, 0xc0000000, 0x40000000, 0x40000000), - (0xff800000, 0xbf800000, 0xbf600000, 0xbf200000)), - ('tri_t6', 'T4 |dx|=|dy|>|dz|: E01 (2,1), TRI0, fan, d=(0.5,0.5,0.25)', 'fan', 0x09090909, 0, - (0x42c80000, 0xc0000000, 0xc0400000, 0x3f800000, 0x3f000000, 0x3f000000, 0x3e800000, 0x40000000, 0x40000000, 0x40800000), - (0xff800000, 0xbf000000, 0xbe800000, 0xbe800000)), - ('tri_t6', 'T4 |dx|=|dy|>|dz|: E01 (2,1), TRI1, fan, d=(0.5,0.5,0.25)', 'fan', 0x09090909, 1, - (0x42c80000, 0xc0000000, 0xc0400000, 0x3f800000, 0x3f000000, 0x3f000000, 0x3e800000, 0x40000000, 0x40000000, 0x40800000), - (0xc0800000, 0xbf000000, 0x00000000, 0xbe800000)), - ('tri_t6', 'T4 |dx|=|dy|>|dz|: E12 (2,2), TRI1, fan, d=(0.5,-0.5,0.25)', 'fan', 0x09090909, 1, - (0x42c80000, 0xc0000000, 0x40c00000, 0x3f800000, 0x3f000000, 0xbf000000, 0x3e800000, 0x40000000, 0xc0000000, 0x40800000), - (0xff800000, 0xbf000000, 0xbe800000, 0xbe800000)), - ('tri_t6', 'T4 |dx|=|dy|>|dz|: E12 (2,2), TRI2, fan, d=(0.5,-0.5,0.25)', 'fan', 0x09090909, 2, - (0x42c80000, 0xc0000000, 0x40c00000, 0x3f800000, 0x3f000000, 0xbf000000, 0x3e800000, 0x40000000, 0xc0000000, 0x40800000), - (0xc0000000, 0xbe800000, 0xbe000000, 0x00000000)), - ('tri_t6', 'T4 |dx|=|dy|>|dz|: E03 (0,1), TRI0, mirrored fan, d=(-0.5,0.5,0.25)', 'fan_mirrored', 0x09090909, 0, - (0x42c80000, 0x40800000, 0xc0400000, 0x3f800000, 0xbf000000, 0x3f000000, 0x3e800000, 0xc0000000, 0x40000000, 0x40800000), - (0x7f800000, 0x3f000000, 0x00000000, 0x3e800000)), - ('tri_t6', 'T4 |dx|=|dy|>|dz|: E03 (0,1), TRI3, mirrored fan, d=(-0.5,0.5,0.25)', 'fan_mirrored', 0x09090909, 3, - (0x42c80000, 0x40800000, 0xc0400000, 0x3f800000, 0xbf000000, 0x3f000000, 0x3e800000, 0xc0000000, 0x40000000, 0x40800000), - (0x40000000, 0x3e800000, 0x00000000, 0x3e000000)), - ('tri_t6', 'T4 |dx|=|dy|>|dz|: fan vertex s2 (0,2), TRI0, fan, d=(-0.5,-0.5,0.25)', 'fan', 0x09090909, 0, - (0x42c80000, 0x40800000, 0x40c00000, 0x3f800000, 0xbf000000, 0xbf000000, 0x3e800000, 0xc0000000, 0xc0000000, 0x40800000), - (0xff800000, 0xbf000000, 0x00000000, 0xbf000000)), - ('tri_t6', 'T4 |dx|=|dy|>|dz|: fan vertex s2 (0,2), TRI1, fan, d=(-0.5,-0.5,0.25)', 'fan', 0x09090909, 1, - (0x42c80000, 0x40800000, 0x40c00000, 0x3f800000, 0xbf000000, 0xbf000000, 0x3e800000, 0xc0000000, 0xc0000000, 0x40800000), - (0xff800000, 0xbf000000, 0x00000000, 0xbf000000)), - ('tri_t6', 'T4 |dx|=|dy|>|dz|: fan vertex s2 (0,2), TRI2, fan, d=(-0.5,-0.5,0.25)', 'fan', 0x09090909, 2, - (0x42c80000, 0x40800000, 0x40c00000, 0x3f800000, 0xbf000000, 0xbf000000, 0x3e800000, 0xc0000000, 0xc0000000, 0x40800000), - (0xc0000000, 0xbe800000, 0x00000000, 0x00000000)), - ('tri_t6', 'T4 |dx|=|dy|>|dz|: fan vertex s2 (0,2), TRI3, fan, d=(-0.5,-0.5,0.25)', 'fan', 0x09090909, 3, - (0x42c80000, 0x40800000, 0x40c00000, 0x3f800000, 0xbf000000, 0xbf000000, 0x3e800000, 0xc0000000, 0xc0000000, 0x40800000), - (0xff800000, 0xbe800000, 0x00000000, 0x00000000)), - ('tri_t6', 'T4 |dx|=|dz|>|dy|: E12 (2,2), TRI1, fan, d=(0.5,0.125,0.5)', 'fan', 0x09090909, 1, - (0x42c80000, 0xc0000000, 0x3f800000, 0xbf800000, 0x3f000000, 0x3e000000, 0x3f000000, 0x40000000, 0x41000000, 0x40000000), - (0xff800000, 0xbf800000, 0xbf000000, 0xbf000000)), - ('tri_t6', 'T4 |dx|=|dz|>|dy|: E12 (2,2), TRI2, fan, d=(0.5,0.125,0.5)', 'fan', 0x09090909, 2, - (0x42c80000, 0xc0000000, 0x3f800000, 0xbf800000, 0x3f000000, 0x3e000000, 0x3f000000, 0x40000000, 0x41000000, 0x40000000), - (0xc0800000, 0xbf000000, 0xbe800000, 0x00000000)), - ('tri_t6', 'T4 |dx|=|dz|>|dy|: E01 (2,1), TRI0, fan, d=(0.5,0.125,-0.5)', 'fan', 0x09090909, 0, - (0x42c80000, 0xc0000000, 0x00000000, 0x40e00000, 0x3f000000, 0x3e000000, 0xbf000000, 0x40000000, 0x41000000, 0xc0000000), - (0x7f800000, 0x3f800000, 0x3f000000, 0x3f000000)), - ('tri_t6', 'T4 |dx|=|dz|>|dy|: E01 (2,1), TRI1, fan, d=(0.5,0.125,-0.5)', 'fan', 0x09090909, 1, - (0x42c80000, 0xc0000000, 0x00000000, 0x40e00000, 0x3f000000, 0x3e000000, 0xbf000000, 0x40000000, 0x41000000, 0xc0000000), - (0x41000000, 0x3f800000, 0x00000000, 0x3f000000)), - ('tri_t6', 'T4 |dx|=|dz|>|dy|: E12 (2,2), TRI1, mirrored fan, d=(-0.5,0.125,0.5)', 'fan_mirrored', 0x09090909, 1, - (0x42c80000, 0x40000000, 0x3f800000, 0xbf800000, 0xbf000000, 0x3e000000, 0x3f000000, 0xc0000000, 0x41000000, 0x40000000), - (0x7f800000, 0x3f800000, 0x3f000000, 0x3f000000)), - ('tri_t6', 'T4 |dx|=|dz|>|dy|: E12 (2,2), TRI2, mirrored fan, d=(-0.5,0.125,0.5)', 'fan_mirrored', 0x09090909, 2, - (0x42c80000, 0x40000000, 0x3f800000, 0xbf800000, 0xbf000000, 0x3e000000, 0x3f000000, 0xc0000000, 0x41000000, 0x40000000), - (0x40800000, 0x3f000000, 0x3e800000, 0x00000000)), - ('tri_t6', 'T4 |dx|=|dz|>|dy|: E03 (0,1), TRI0, fan, d=(-0.5,0.125,-0.5)', 'fan', 0x09090909, 0, - (0x42c80000, 0x40800000, 0x00000000, 0x40e00000, 0xbf000000, 0x3e000000, 0xbf000000, 0xc0000000, 0x41000000, 0xc0000000), - (0x7f800000, 0x3f800000, 0x00000000, 0x3f000000)), - ('tri_t6', 'T4 |dx|=|dz|>|dy|: E03 (0,1), TRI3, fan, d=(-0.5,0.125,-0.5)', 'fan', 0x09090909, 3, - (0x42c80000, 0x40800000, 0x00000000, 0x40e00000, 0xbf000000, 0x3e000000, 0xbf000000, 0xc0000000, 0x41000000, 0xc0000000), - (0x40800000, 0x3f000000, 0x00000000, 0x3e800000)), - ('tri_t6', 'T4 |dy|=|dz|>|dx|: E01 (2,1), TRI0, fan, d=(0.125,0.5,0.5)', 'fan', 0x09090909, 0, - (0x42c80000, 0x3f800000, 0xc0400000, 0xbf800000, 0x3e000000, 0x3f000000, 0x3f000000, 0x41000000, 0x40000000, 0x40000000), - (0xc1000000, 0xbf800000, 0xbf000000, 0xbf000000)), - ('tri_t6', 'T4 |dy|=|dz|>|dx|: E01 (2,1), TRI1, fan, d=(0.125,0.5,0.5)', 'fan', 0x09090909, 1, - (0x42c80000, 0x3f800000, 0xc0400000, 0xbf800000, 0x3e000000, 0x3f000000, 0x3f000000, 0x41000000, 0x40000000, 0x40000000), - (0xff800000, 0xbf800000, 0x00000000, 0xbf000000)), - ('tri_t6', 'T4 |dy|=|dz|>|dx|: E03 (0,1), TRI0, mirrored fan, d=(0.125,0.5,-0.5)', 'fan_mirrored', 0x09090909, 0, - (0x42c80000, 0xbf800000, 0xc0400000, 0x40e00000, 0x3e000000, 0x3f000000, 0xbf000000, 0x41000000, 0x40000000, 0xc0000000), - (0xff800000, 0xbf800000, 0x00000000, 0xbf000000)), - ('tri_t6', 'T4 |dy|=|dz|>|dx|: E03 (0,1), TRI3, mirrored fan, d=(0.125,0.5,-0.5)', 'fan_mirrored', 0x09090909, 3, - (0x42c80000, 0xbf800000, 0xc0400000, 0x40e00000, 0x3e000000, 0x3f000000, 0xbf000000, 0x41000000, 0x40000000, 0xc0000000), - (0xc0800000, 0xbf000000, 0x00000000, 0xbe800000)), - ('tri_t7', 'control tri_g4b: shared edge E23 (-1,2.5), TRI3, oblique +z', 'fan', 0x09090909, 3, - (0x42c80000, 0xc0000000, 0x40000000, 0xbf800000, 0x3e000000, 0x3d800000, 0x3f000000, 0x41000000, 0x41800000, 0x40000000), - (0xff800000, 0xbf000000, 0xbe800000, 0x00000000)), - ('tri_t7', 'T4 |dy|=|dz|>|dx|: E01 (2,1), TRI0, fan, d=(0.125,-0.5,0.5)', 'fan', 0x09090909, 0, - (0x42c80000, 0x3f800000, 0x40a00000, 0xbf800000, 0x3e000000, 0xbf000000, 0x3f000000, 0x41000000, 0xc0000000, 0x40000000), - (0xff800000, 0xbf800000, 0xbf000000, 0xbf000000)), - ('tri_t7', 'T4 |dy|=|dz|>|dx|: E01 (2,1), TRI1, fan, d=(0.125,-0.5,0.5)', 'fan', 0x09090909, 1, - (0x42c80000, 0x3f800000, 0x40a00000, 0xbf800000, 0x3e000000, 0xbf000000, 0x3f000000, 0x41000000, 0xc0000000, 0x40000000), - (0xc1000000, 0xbf800000, 0x00000000, 0xbf000000)), - ('tri_t7', 'T4 |dy|=|dz|>|dx|: E12 (2,2), TRI1, fan, d=(0.125,-0.5,-0.5)', 'fan', 0x09090909, 1, - (0x42c80000, 0x3f800000, 0x40c00000, 0x40e00000, 0x3e000000, 0xbf000000, 0xbf000000, 0x41000000, 0xc0000000, 0xc0000000), - (0x41000000, 0x3f800000, 0x3f000000, 0x3f000000)), - ('tri_t7', 'T4 |dy|=|dz|>|dx|: E12 (2,2), TRI2, fan, d=(0.125,-0.5,-0.5)', 'fan', 0x09090909, 2, - (0x42c80000, 0x3f800000, 0x40c00000, 0x40e00000, 0x3e000000, 0xbf000000, 0xbf000000, 0x41000000, 0xc0000000, 0xc0000000), - (0x7f800000, 0x3f000000, 0x3e800000, 0x00000000)), - ('tri_t7', 'T4 |dx|=|dy|=|dz|: fan vertex s2 (0,2), TRI0, fan, d=(0.5,0.5,0.5)', 'fan', 0x09090909, 0, - (0x42c80000, 0xc0800000, 0xc0000000, 0xbf800000, 0x3f000000, 0x3f000000, 0x3f000000, 0x40000000, 0x40000000, 0x40000000), - (0xff800000, 0xbf800000, 0x00000000, 0xbf800000)), - ('tri_t7', 'T4 |dx|=|dy|=|dz|: fan vertex s2 (0,2), TRI1, fan, d=(0.5,0.5,0.5)', 'fan', 0x09090909, 1, - (0x42c80000, 0xc0800000, 0xc0000000, 0xbf800000, 0x3f000000, 0x3f000000, 0x3f000000, 0x40000000, 0x40000000, 0x40000000), - (0xff800000, 0xbf800000, 0x00000000, 0xbf800000)), - ('tri_t7', 'T4 |dx|=|dy|=|dz|: fan vertex s2 (0,2), TRI2, fan, d=(0.5,0.5,0.5)', 'fan', 0x09090909, 2, - (0x42c80000, 0xc0800000, 0xc0000000, 0xbf800000, 0x3f000000, 0x3f000000, 0x3f000000, 0x40000000, 0x40000000, 0x40000000), - (0xc0800000, 0xbf000000, 0x00000000, 0x00000000)), - ('tri_t7', 'T4 |dx|=|dy|=|dz|: fan vertex s2 (0,2), TRI3, fan, d=(0.5,0.5,0.5)', 'fan', 0x09090909, 3, - (0x42c80000, 0xc0800000, 0xc0000000, 0xbf800000, 0x3f000000, 0x3f000000, 0x3f000000, 0x40000000, 0x40000000, 0x40000000), - (0xff800000, 0xbf000000, 0x00000000, 0x00000000)), - ('tri_t7', 'T4 |dx|=|dy|=|dz|: E03 (0,1), TRI0, mirrored fan, d=(0.5,0.5,-0.5)', 'fan_mirrored', 0x09090909, 0, - (0x42c80000, 0xc0800000, 0xc0400000, 0x40e00000, 0x3f000000, 0x3f000000, 0xbf000000, 0x40000000, 0x40000000, 0xc0000000), - (0xc1000000, 0xbf800000, 0x00000000, 0xbf000000)), - ('tri_t7', 'T4 |dx|=|dy|=|dz|: E03 (0,1), TRI3, mirrored fan, d=(0.5,0.5,-0.5)', 'fan_mirrored', 0x09090909, 3, - (0x42c80000, 0xc0800000, 0xc0400000, 0x40e00000, 0x3f000000, 0x3f000000, 0xbf000000, 0x40000000, 0x40000000, 0xc0000000), - (0xff800000, 0xbf000000, 0x00000000, 0xbe800000)), - ('tri_t7', 'T4 |dx|=|dy|=|dz|: E01 (2,1), TRI0, fan, d=(0.5,0.5,-0.5)', 'fan', 0x09090909, 0, - (0x42c80000, 0xc0000000, 0xc0400000, 0x40e00000, 0x3f000000, 0x3f000000, 0xbf000000, 0x40000000, 0x40000000, 0xc0000000), - (0x7f800000, 0x3f800000, 0x3f000000, 0x3f000000)), - ('tri_t7', 'T4 |dx|=|dy|=|dz|: E01 (2,1), TRI1, fan, d=(0.5,0.5,-0.5)', 'fan', 0x09090909, 1, - (0x42c80000, 0xc0000000, 0xc0400000, 0x40e00000, 0x3f000000, 0x3f000000, 0xbf000000, 0x40000000, 0x40000000, 0xc0000000), - (0x41000000, 0x3f800000, 0x00000000, 0x3f000000)), - ('tri_t7', 'T4 |dx|=|dy|=|dz|: fan vertex s2 (0,2), TRI0, fan, d=(0.5,-0.5,0.5)', 'fan', 0x09090909, 0, - (0x42c80000, 0xc0800000, 0x40c00000, 0xbf800000, 0x3f000000, 0xbf000000, 0x3f000000, 0x40000000, 0xc0000000, 0x40000000), - (0xff800000, 0xbf800000, 0x00000000, 0xbf800000)), - ('tri_t7', 'T4 |dx|=|dy|=|dz|: fan vertex s2 (0,2), TRI1, fan, d=(0.5,-0.5,0.5)', 'fan', 0x09090909, 1, - (0x42c80000, 0xc0800000, 0x40c00000, 0xbf800000, 0x3f000000, 0xbf000000, 0x3f000000, 0x40000000, 0xc0000000, 0x40000000), - (0xff800000, 0xbf800000, 0x00000000, 0xbf800000)), - ('tri_t7', 'T4 |dx|=|dy|=|dz|: fan vertex s2 (0,2), TRI2, fan, d=(0.5,-0.5,0.5)', 'fan', 0x09090909, 2, - (0x42c80000, 0xc0800000, 0x40c00000, 0xbf800000, 0x3f000000, 0xbf000000, 0x3f000000, 0x40000000, 0xc0000000, 0x40000000), - (0xc0800000, 0xbf000000, 0x00000000, 0x00000000)), - ('tri_t7', 'T4 |dx|=|dy|=|dz|: fan vertex s2 (0,2), TRI3, fan, d=(0.5,-0.5,0.5)', 'fan', 0x09090909, 3, - (0x42c80000, 0xc0800000, 0x40c00000, 0xbf800000, 0x3f000000, 0xbf000000, 0x3f000000, 0x40000000, 0xc0000000, 0x40000000), - (0xff800000, 0xbf000000, 0x00000000, 0x00000000)), - ('tri_t7', 'T4 |dx|=|dy|=|dz|: E01 (2,1), TRI0, fan, d=(-0.5,0.5,0.5)', 'fan', 0x09090909, 0, - (0x42c80000, 0x40c00000, 0xc0400000, 0xbf800000, 0xbf000000, 0x3f000000, 0x3f000000, 0xc0000000, 0x40000000, 0x40000000), - (0xff800000, 0xbf800000, 0xbf000000, 0xbf000000)), - ('tri_t7', 'T4 |dx|=|dy|=|dz|: E01 (2,1), TRI1, fan, d=(-0.5,0.5,0.5)', 'fan', 0x09090909, 1, - (0x42c80000, 0x40c00000, 0xc0400000, 0xbf800000, 0xbf000000, 0x3f000000, 0x3f000000, 0xc0000000, 0x40000000, 0x40000000), - (0xc1000000, 0xbf800000, 0x00000000, 0xbf000000)), - ('tri_t7', 'T4 |dx|=|dy|=|dz|: E03 (0,1), TRI0, mirrored fan, d=(-0.5,0.5,0.5)', 'fan_mirrored', 0x09090909, 0, - (0x42c80000, 0x40800000, 0xc0400000, 0xbf800000, 0xbf000000, 0x3f000000, 0x3f000000, 0xc0000000, 0x40000000, 0x40000000), - (0x7f800000, 0x3f800000, 0x00000000, 0x3f000000)), - ('tri_t7', 'T4 |dx|=|dy|=|dz|: E03 (0,1), TRI3, mirrored fan, d=(-0.5,0.5,0.5)', 'fan_mirrored', 0x09090909, 3, - (0x42c80000, 0x40800000, 0xc0400000, 0xbf800000, 0xbf000000, 0x3f000000, 0x3f000000, 0xc0000000, 0x40000000, 0x40000000), - (0x40800000, 0x3f000000, 0x00000000, 0x3e800000)), - ('tri_t7', 'control tri_g1b: TRI2 dominant -y', 'fan_y_dominant', 0x09090909, 2, - (0x42c80000, 0x40080000, 0x40e00000, 0x3fe00000, 0x00000000, 0xbf000000, 0x00000000, 0x7f800000, 0xc0000000, 0x7f800000), - (0x40800000, 0x3f000000, 0x3e800000, 0x3d800000)), - ('tri_t7', 'control tri_g4a: fan vertex s2 (0,2), TRI1, oblique +z', 'fan', 0x09090909, 1, - (0x42c80000, 0xbf800000, 0x3fc00000, 0xbf800000, 0x3e000000, 0x3d800000, 0x3f000000, 0x41000000, 0x41800000, 0x40000000), - (0xc1000000, 0xbf800000, 0x00000000, 0xbf800000)), - ('tri_t7', 'control tri_g1c: TRI1 miss beyond edge opposite v2 -z (det>0)', 'fan', 0x09090909, 1, - (0x42c80000, 0x40a00000, 0x3f000000, 0x40e00000, 0x00000000, 0x00000000, 0xbf000000, 0x7f800000, 0x7f800000, 0xc0000000), - (0x7f800000, 0x3f800000, 0x3f000000, 0xbe800000)), - ('tri_t7', 'control tri_g4b: outer vertex s0 (0,0), TRI0, +z', 'fan', 0x09090909, 0, - (0x42c80000, 0x00000000, 0x00000000, 0xbf800000, 0x00000000, 0x00000000, 0x3f000000, 0x7f800000, 0x7f800000, 0x40000000), - (0xff800000, 0xbf800000, 0x00000000, 0x00000000)), - ('tri_t7', 'control tri_g1b: TRI0 kz tie |dx|=|dy|=|dz|', 'fan', 0x09090909, 0, - (0x42c80000, 0xc0400000, 0xc0700000, 0xbf800000, 0x3f000000, 0x3f000000, 0x3f000000, 0x40000000, 0x40000000, 0x40000000), - (0xc1000000, 0xbf800000, 0xbe800000, 0xbe000000)), - ('tri_t7', 'control tri_g4b: shared edge E03 (0,1), TRI0, -z', 'fan', 0x09090909, 0, - (0x42c80000, 0x00000000, 0x3f800000, 0x40e00000, 0x00000000, 0x00000000, 0xbf000000, 0x7f800000, 0x7f800000, 0xc0000000), - (0x41000000, 0x3f800000, 0x00000000, 0x3f000000)), - ('tri_t7', 'control tri_g1a: TRI1 mirrored leaf hit +z', 'fan_mirrored', 0x09090909, 1, - (0x42c80000, 0xc0600000, 0x3fa00000, 0xbf800000, 0x00000000, 0x00000000, 0x3f000000, 0x7f800000, 0x7f800000, 0x40000000), - (0x41000000, 0x3f800000, 0x3f000000, 0x3e000000)), - ('tri_t7', 'control tri_g4b: shared edge E12 (2,2), TRI1, oblique +z', 'fan', 0x09090909, 1, - (0x42c80000, 0x3f800000, 0x3fc00000, 0xbf800000, 0x3e000000, 0x3d800000, 0x3f000000, 0x41000000, 0x41800000, 0x40000000), - (0xc1000000, 0xbf800000, 0xbf000000, 0xbf000000)), - ('tri_t7', 'control tri_g1b: TRI2 dominant +x', 'fan_x_dominant', 0x09090909, 2, - (0x42c80000, 0xbf800000, 0x3fe00000, 0x40080000, 0x3f000000, 0x00000000, 0x00000000, 0x40000000, 0x7f800000, 0x7f800000), - (0xc0800000, 0xbf000000, 0xbe800000, 0xbd800000)), - ('tri_t7', 'control tri_g1a: TRI0 hit +z', 'fan', 0x09090909, 0, - (0x42c80000, 0x3f800000, 0x3e800000, 0xbf800000, 0x00000000, 0x00000000, 0x3f000000, 0x7f800000, 0x7f800000, 0x40000000), - (0xc1000000, 0xbf800000, 0xbe800000, 0xbe000000)), - ('tri_t7', 'control tri_g4b: shared edge E01 (2,1), TRI1, +z', 'fan', 0x09090909, 1, - (0x42c80000, 0x40000000, 0x3f800000, 0xbf800000, 0x00000000, 0x00000000, 0x3f000000, 0x7f800000, 0x7f800000, 0x40000000), - (0xc1000000, 0xbf800000, 0x00000000, 0xbf000000)), - ('tri_t8', 'control tri_g1a: TRI1 mirrored leaf hit +z', 'fan_mirrored', 0x09090909, 1, - (0x42c80000, 0xc0600000, 0x3fa00000, 0xbf800000, 0x00000000, 0x00000000, 0x3f000000, 0x7f800000, 0x7f800000, 0x40000000), - (0x41000000, 0x3f800000, 0x3f000000, 0x3e000000)), - ('tri_t8', 'T5 +z: E01 (2,1), TRI0, mirrored fan, d=(0,0,0.5)', 'fan_mirrored', 0x09090909, 0, - (0x42c80000, 0xc0000000, 0x3f800000, 0xbf800000, 0x00000000, 0x00000000, 0x3f000000, 0x7f800000, 0x7f800000, 0x40000000), - (0x41000000, 0x3f800000, 0x3f000000, 0x3f000000)), - ('tri_t8', 'T5 +z: E01 (2,1), TRI1, mirrored fan, d=(0,0,0.5)', 'fan_mirrored', 0x09090909, 1, - (0x42c80000, 0xc0000000, 0x3f800000, 0xbf800000, 0x00000000, 0x00000000, 0x3f000000, 0x7f800000, 0x7f800000, 0x40000000), - (0x7f800000, 0x3f800000, 0x00000000, 0x3f000000)), - ('tri_t8', 'T5 +z: E03 (0,1), TRI0, mirrored fan, d=(0,0,0.5)', 'fan_mirrored', 0x09090909, 0, - (0x42c80000, 0x00000000, 0x3f800000, 0xbf800000, 0x00000000, 0x00000000, 0x3f000000, 0x7f800000, 0x7f800000, 0x40000000), - (0x7f800000, 0x3f800000, 0x00000000, 0x3f000000)), - ('tri_t8', 'T5 +z: E03 (0,1), TRI3, mirrored fan, d=(0,0,0.5)', 'fan_mirrored', 0x09090909, 3, - (0x42c80000, 0x00000000, 0x3f800000, 0xbf800000, 0x00000000, 0x00000000, 0x3f000000, 0x7f800000, 0x7f800000, 0x40000000), - (0x40800000, 0x3f000000, 0x00000000, 0x3e800000)), - ('tri_t8', 'T5 +z: E12 (2,2), TRI1, mirrored fan, d=(0,0,0.5)', 'fan_mirrored', 0x09090909, 1, - (0x42c80000, 0xc0000000, 0x40000000, 0xbf800000, 0x00000000, 0x00000000, 0x3f000000, 0x7f800000, 0x7f800000, 0x40000000), - (0x41000000, 0x3f800000, 0x3f000000, 0x3f000000)), - ('tri_t8', 'T5 +z: E12 (2,2), TRI2, mirrored fan, d=(0,0,0.5)', 'fan_mirrored', 0x09090909, 2, - (0x42c80000, 0xc0000000, 0x40000000, 0xbf800000, 0x00000000, 0x00000000, 0x3f000000, 0x7f800000, 0x7f800000, 0x40000000), - (0x7f800000, 0x3f000000, 0x3e800000, 0x00000000)), - ('tri_t8', 'T5 +z: fan vertex s2 (0,2), TRI0, mirrored fan, d=(0,0,0.5)', 'fan_mirrored', 0x09090909, 0, - (0x42c80000, 0x00000000, 0x40000000, 0xbf800000, 0x00000000, 0x00000000, 0x3f000000, 0x7f800000, 0x7f800000, 0x40000000), - (0x7f800000, 0x3f800000, 0x00000000, 0x3f800000)), - ('tri_t8', 'T5 +z: fan vertex s2 (0,2), TRI1, mirrored fan, d=(0,0,0.5)', 'fan_mirrored', 0x09090909, 1, - (0x42c80000, 0x00000000, 0x40000000, 0xbf800000, 0x00000000, 0x00000000, 0x3f000000, 0x7f800000, 0x7f800000, 0x40000000), - (0x7f800000, 0x3f800000, 0x00000000, 0x3f800000)), - ('tri_t8', 'T5 +z: fan vertex s2 (0,2), TRI2, mirrored fan, d=(0,0,0.5)', 'fan_mirrored', 0x09090909, 2, - (0x42c80000, 0x00000000, 0x40000000, 0xbf800000, 0x00000000, 0x00000000, 0x3f000000, 0x7f800000, 0x7f800000, 0x40000000), - (0x7f800000, 0x3f000000, 0x00000000, 0x00000000)), - ('tri_t8', 'T5 +z: fan vertex s2 (0,2), TRI3, mirrored fan, d=(0,0,0.5)', 'fan_mirrored', 0x09090909, 3, - (0x42c80000, 0x00000000, 0x40000000, 0xbf800000, 0x00000000, 0x00000000, 0x3f000000, 0x7f800000, 0x7f800000, 0x40000000), - (0x40800000, 0x3f000000, 0x00000000, 0x00000000)), - ('tri_t8', 'T5 +z: E01 (2,1), TRI0, rotated mirrored fan, d=(0,0,0.5)', 'rotated_mirrored_fan', 0x09090909, 0, - (0x42c80000, 0x3f800000, 0x40000000, 0xbf800000, 0x00000000, 0x00000000, 0x3f000000, 0x7f800000, 0x7f800000, 0x40000000), - (0x7f800000, 0x3f800000, 0x3f000000, 0x3f000000)), - ('tri_t8', 'T5 +z: E01 (2,1), TRI1, rotated mirrored fan, d=(0,0,0.5)', 'rotated_mirrored_fan', 0x09090909, 1, - (0x42c80000, 0x3f800000, 0x40000000, 0xbf800000, 0x00000000, 0x00000000, 0x3f000000, 0x7f800000, 0x7f800000, 0x40000000), - (0x41000000, 0x3f800000, 0x00000000, 0x3f000000)), - ('tri_t8', 'T5 +z: E01 (2,1), TRI0, rotated fan, d=(0,0,0.5)', 'rotated_fan', 0x09090909, 0, - (0x42c80000, 0xbf800000, 0x40000000, 0xbf800000, 0x00000000, 0x00000000, 0x3f000000, 0x7f800000, 0x7f800000, 0x40000000), - (0xc1000000, 0xbf800000, 0xbf000000, 0xbf000000)), - ('tri_t8', 'T5 +z: E01 (2,1), TRI1, rotated fan, d=(0,0,0.5)', 'rotated_fan', 0x09090909, 1, - (0x42c80000, 0xbf800000, 0x40000000, 0xbf800000, 0x00000000, 0x00000000, 0x3f000000, 0x7f800000, 0x7f800000, 0x40000000), - (0xff800000, 0xbf800000, 0x00000000, 0xbf000000)), - ('tri_t8', 'T5 -z: E01 (2,1), TRI0, mirrored fan, d=(0,0,-0.5)', 'fan_mirrored', 0x09090909, 0, - (0x42c80000, 0xc0000000, 0x3f800000, 0x40e00000, 0x00000000, 0x00000000, 0xbf000000, 0x7f800000, 0x7f800000, 0xc0000000), - (0xc1000000, 0xbf800000, 0xbf000000, 0xbf000000)), - ('tri_t8', 'T5 -z: E01 (2,1), TRI1, mirrored fan, d=(0,0,-0.5)', 'fan_mirrored', 0x09090909, 1, - (0x42c80000, 0xc0000000, 0x3f800000, 0x40e00000, 0x00000000, 0x00000000, 0xbf000000, 0x7f800000, 0x7f800000, 0xc0000000), - (0xff800000, 0xbf800000, 0x00000000, 0xbf000000)), - ('tri_t8', 'T5 -z: E03 (0,1), TRI0, mirrored fan, d=(0,0,-0.5)', 'fan_mirrored', 0x09090909, 0, - (0x42c80000, 0x00000000, 0x3f800000, 0x40e00000, 0x00000000, 0x00000000, 0xbf000000, 0x7f800000, 0x7f800000, 0xc0000000), - (0xff800000, 0xbf800000, 0x00000000, 0xbf000000)), - ('tri_t8', 'T5 -z: E03 (0,1), TRI3, mirrored fan, d=(0,0,-0.5)', 'fan_mirrored', 0x09090909, 3, - (0x42c80000, 0x00000000, 0x3f800000, 0x40e00000, 0x00000000, 0x00000000, 0xbf000000, 0x7f800000, 0x7f800000, 0xc0000000), - (0xc0800000, 0xbf000000, 0x00000000, 0xbe800000)), - ('tri_t8', 'T5 -z: E12 (2,2), TRI1, mirrored fan, d=(0,0,-0.5)', 'fan_mirrored', 0x09090909, 1, - (0x42c80000, 0xc0000000, 0x40000000, 0x40e00000, 0x00000000, 0x00000000, 0xbf000000, 0x7f800000, 0x7f800000, 0xc0000000), - (0xff800000, 0xbf800000, 0xbf000000, 0xbf000000)), - ('tri_t8', 'T5 -z: E12 (2,2), TRI2, mirrored fan, d=(0,0,-0.5)', 'fan_mirrored', 0x09090909, 2, - (0x42c80000, 0xc0000000, 0x40000000, 0x40e00000, 0x00000000, 0x00000000, 0xbf000000, 0x7f800000, 0x7f800000, 0xc0000000), - (0xc0800000, 0xbf000000, 0xbe800000, 0x00000000)), - ('tri_t8', 'T5 -z: fan vertex s2 (0,2), TRI0, mirrored fan, d=(0,0,-0.5)', 'fan_mirrored', 0x09090909, 0, - (0x42c80000, 0x00000000, 0x40000000, 0x40e00000, 0x00000000, 0x00000000, 0xbf000000, 0x7f800000, 0x7f800000, 0xc0000000), - (0xff800000, 0xbf800000, 0x00000000, 0xbf800000)), - ('tri_t8', 'T5 -z: fan vertex s2 (0,2), TRI1, mirrored fan, d=(0,0,-0.5)', 'fan_mirrored', 0x09090909, 1, - (0x42c80000, 0x00000000, 0x40000000, 0x40e00000, 0x00000000, 0x00000000, 0xbf000000, 0x7f800000, 0x7f800000, 0xc0000000), - (0xff800000, 0xbf800000, 0x00000000, 0xbf800000)), - ('tri_t8', 'T5 -z: fan vertex s2 (0,2), TRI2, mirrored fan, d=(0,0,-0.5)', 'fan_mirrored', 0x09090909, 2, - (0x42c80000, 0x00000000, 0x40000000, 0x40e00000, 0x00000000, 0x00000000, 0xbf000000, 0x7f800000, 0x7f800000, 0xc0000000), - (0xff800000, 0xbf000000, 0x00000000, 0x00000000)), - ('tri_t8', 'T5 -z: fan vertex s2 (0,2), TRI3, mirrored fan, d=(0,0,-0.5)', 'fan_mirrored', 0x09090909, 3, - (0x42c80000, 0x00000000, 0x40000000, 0x40e00000, 0x00000000, 0x00000000, 0xbf000000, 0x7f800000, 0x7f800000, 0xc0000000), - (0xc0800000, 0xbf000000, 0x00000000, 0x00000000)), - ('tri_t8', 'T5 -z: E01 (2,1), TRI0, rotated mirrored fan, d=(0,0,-0.5)', 'rotated_mirrored_fan', 0x09090909, 0, - (0x42c80000, 0x3f800000, 0x40000000, 0x40e00000, 0x00000000, 0x00000000, 0xbf000000, 0x7f800000, 0x7f800000, 0xc0000000), - (0xff800000, 0xbf800000, 0xbf000000, 0xbf000000)), - ('tri_t8', 'T5 -z: E01 (2,1), TRI1, rotated mirrored fan, d=(0,0,-0.5)', 'rotated_mirrored_fan', 0x09090909, 1, - (0x42c80000, 0x3f800000, 0x40000000, 0x40e00000, 0x00000000, 0x00000000, 0xbf000000, 0x7f800000, 0x7f800000, 0xc0000000), - (0xc1000000, 0xbf800000, 0x00000000, 0xbf000000)), - ('tri_t8', 'T5 -z: E01 (2,1), TRI0, rotated fan, d=(0,0,-0.5)', 'rotated_fan', 0x09090909, 0, - (0x42c80000, 0xbf800000, 0x40000000, 0x40e00000, 0x00000000, 0x00000000, 0xbf000000, 0x7f800000, 0x7f800000, 0xc0000000), - (0x41000000, 0x3f800000, 0x3f000000, 0x3f000000)), - ('tri_t8', 'T5 -z: E01 (2,1), TRI1, rotated fan, d=(0,0,-0.5)', 'rotated_fan', 0x09090909, 1, - (0x42c80000, 0xbf800000, 0x40000000, 0x40e00000, 0x00000000, 0x00000000, 0xbf000000, 0x7f800000, 0x7f800000, 0xc0000000), - (0x7f800000, 0x3f800000, 0x00000000, 0x3f000000)), - ('tri_t8', 'control tri_g4b: shared edge E03 (0,1), TRI0, -z', 'fan', 0x09090909, 0, - (0x42c80000, 0x00000000, 0x3f800000, 0x40e00000, 0x00000000, 0x00000000, 0xbf000000, 0x7f800000, 0x7f800000, 0xc0000000), - (0x41000000, 0x3f800000, 0x00000000, 0x3f000000)), - ('tri_t8', 'control tri_g4a: fan vertex s2 (0,2), TRI2, -z', 'fan', 0x09090909, 2, - (0x42c80000, 0x00000000, 0x40000000, 0x40e00000, 0x00000000, 0x00000000, 0xbf000000, 0x7f800000, 0x7f800000, 0xc0000000), - (0x40800000, 0x3f000000, 0x00000000, 0x00000000)), - ('tri_t8', 'control tri_g4b: shared edge E12 (2,2), TRI1, oblique +z', 'fan', 0x09090909, 1, - (0x42c80000, 0x3f800000, 0x3fc00000, 0xbf800000, 0x3e000000, 0x3d800000, 0x3f000000, 0x41000000, 0x41800000, 0x40000000), - (0xc1000000, 0xbf800000, 0xbf000000, 0xbf000000)), -] -LANE_ROWS = [ - ('tri_lanes_w32', 'TRI0 hit +z, origin + lane offset, lane 0', 'fan', 0x09090909, 0, - (0x42c80000, 0x3f800000, 0x3e800000, 0xbf800000, 0x00000000, 0x00000000, 0x3f000000, 0x7f800000, 0x7f800000, 0x40000000), - (0xc1000000, 0xbf800000, 0xbe800000, 0xbe000000)), - ('tri_lanes_w32', 'TRI0 hit +z, origin + lane offset, lane 15', 'fan', 0x09090909, 0, - (0x42c80000, 0x3f9e0000, 0x3e800000, 0xbf800000, 0x00000000, 0x00000000, 0x3f000000, 0x7f800000, 0x7f800000, 0x40000000), - (0xc1000000, 0xbf800000, 0xbe9e0000, 0xbe000000)), - ('tri_lanes_w32', 'TRI0 hit +z, origin + lane offset, lane 16', 'fan', 0x09090909, 0, - (0x42c80000, 0x3f800000, 0x3e880000, 0xbf800000, 0x00000000, 0x00000000, 0x3f000000, 0x7f800000, 0x7f800000, 0x40000000), - (0xc1000000, 0xbf800000, 0xbe800000, 0xbe080000)), - ('tri_lanes_w32', 'TRI0 hit +z, origin + lane offset, lane 31', 'fan', 0x09090909, 0, - (0x42c80000, 0x3f9e0000, 0x3e880000, 0xbf800000, 0x00000000, 0x00000000, 0x3f000000, 0x7f800000, 0x7f800000, 0x40000000), - (0xc1000000, 0xbf800000, 0xbe9e0000, 0xbe080000)), - ('tri_lanes_w32', 'TRI0 hit +z, origin + lane offset, lane 32', 'fan', 0x09090909, 0, - (0x42c80000, 0x3f800000, 0x3e900000, 0xbf800000, 0x00000000, 0x00000000, 0x3f000000, 0x7f800000, 0x7f800000, 0x40000000), - (0xc1000000, 0xbf800000, 0xbe800000, 0xbe100000)), - ('tri_lanes_w32', 'TRI0 hit +z, origin + lane offset, lane 63', 'fan', 0x09090909, 0, - (0x42c80000, 0x3f9e0000, 0x3e980000, 0xbf800000, 0x00000000, 0x00000000, 0x3f000000, 0x7f800000, 0x7f800000, 0x40000000), - (0xc1000000, 0xbf800000, 0xbe9e0000, 0xbe180000)), - ('tri_lanes_w32', 'TRI1 hit +z, origin + lane offset, lane 0', 'fan', 0x09090909, 1, - (0x42c80000, 0x40600000, 0x3fa00000, 0xbf800000, 0x00000000, 0x00000000, 0x3f000000, 0x7f800000, 0x7f800000, 0x40000000), - (0xc1000000, 0xbf800000, 0xbf000000, 0xbe000000)), - ('tri_lanes_w32', 'TRI1 hit +z, origin + lane offset, lane 15', 'fan', 0x09090909, 1, - (0x42c80000, 0x406f0000, 0x3fa00000, 0xbf800000, 0x00000000, 0x00000000, 0x3f000000, 0x7f800000, 0x7f800000, 0x40000000), - (0xc1000000, 0xbf800000, 0xbf0f0000, 0xbd880000)), - ('tri_lanes_w32', 'TRI1 hit +z, origin + lane offset, lane 16', 'fan', 0x09090909, 1, - (0x42c80000, 0x40600000, 0x3fa20000, 0xbf800000, 0x00000000, 0x00000000, 0x3f000000, 0x7f800000, 0x7f800000, 0x40000000), - (0xc1000000, 0xbf800000, 0xbf020000, 0xbe000000)), - ('tri_lanes_w32', 'TRI1 hit +z, origin + lane offset, lane 31', 'fan', 0x09090909, 1, - (0x42c80000, 0x406f0000, 0x3fa20000, 0xbf800000, 0x00000000, 0x00000000, 0x3f000000, 0x7f800000, 0x7f800000, 0x40000000), - (0xc1000000, 0xbf800000, 0xbf110000, 0xbd880000)), - ('tri_lanes_w32', 'TRI1 hit +z, origin + lane offset, lane 32', 'fan', 0x09090909, 1, - (0x42c80000, 0x40600000, 0x3fa40000, 0xbf800000, 0x00000000, 0x00000000, 0x3f000000, 0x7f800000, 0x7f800000, 0x40000000), - (0xc1000000, 0xbf800000, 0xbf040000, 0xbe000000)), - ('tri_lanes_w32', 'TRI1 hit +z, origin + lane offset, lane 63', 'fan', 0x09090909, 1, - (0x42c80000, 0x406f0000, 0x3fa60000, 0xbf800000, 0x00000000, 0x00000000, 0x3f000000, 0x7f800000, 0x7f800000, 0x40000000), - (0xc1000000, 0xbf800000, 0xbf150000, 0xbd880000)), - ('tri_lanes_w32', 'TRI2 hit +z, origin + lane offset, lane 0', 'fan', 0x09090909, 2, - (0x42c80000, 0x3fe00000, 0x40080000, 0xbf800000, 0x00000000, 0x00000000, 0x3f000000, 0x7f800000, 0x7f800000, 0x40000000), - (0xc0800000, 0xbf000000, 0xbe800000, 0xbd800000)), - ('tri_lanes_w32', 'TRI2 hit +z, origin + lane offset, lane 15', 'fan', 0x09090909, 2, - (0x42c80000, 0x3ffe0000, 0x40080000, 0xbf800000, 0x00000000, 0x00000000, 0x3f000000, 0x7f800000, 0x7f800000, 0x40000000), - (0xc0800000, 0xbf000000, 0xbe8f0000, 0xbd800000)), - ('tri_lanes_w32', 'TRI2 hit +z, origin + lane offset, lane 16', 'fan', 0x09090909, 2, - (0x42c80000, 0x3fe00000, 0x40090000, 0xbf800000, 0x00000000, 0x00000000, 0x3f000000, 0x7f800000, 0x7f800000, 0x40000000), - (0xc0800000, 0xbf000000, 0xbe820000, 0xbd900000)), - ('tri_lanes_w32', 'TRI2 hit +z, origin + lane offset, lane 31', 'fan', 0x09090909, 2, - (0x42c80000, 0x3ffe0000, 0x40090000, 0xbf800000, 0x00000000, 0x00000000, 0x3f000000, 0x7f800000, 0x7f800000, 0x40000000), - (0xc0800000, 0xbf000000, 0xbe910000, 0xbd900000)), - ('tri_lanes_w32', 'TRI2 hit +z, origin + lane offset, lane 32', 'fan', 0x09090909, 2, - (0x42c80000, 0x3fe00000, 0x400a0000, 0xbf800000, 0x00000000, 0x00000000, 0x3f000000, 0x7f800000, 0x7f800000, 0x40000000), - (0xc0800000, 0xbf000000, 0xbe840000, 0xbda00000)), - ('tri_lanes_w32', 'TRI2 hit +z, origin + lane offset, lane 63', 'fan', 0x09090909, 2, - (0x42c80000, 0x3ffe0000, 0x400b0000, 0xbf800000, 0x00000000, 0x00000000, 0x3f000000, 0x7f800000, 0x7f800000, 0x40000000), - (0xc0800000, 0xbf000000, 0xbe950000, 0xbdb00000)), - ('tri_lanes_w32', 'TRI3 hit +z, origin + lane offset, lane 0', 'fan', 0x09090909, 3, - (0x42c80000, 0xbf000000, 0x40000000, 0xbf800000, 0x00000000, 0x00000000, 0x3f000000, 0x7f800000, 0x7f800000, 0x40000000), - (0xc0800000, 0xbf000000, 0xbe000000, 0xbd800000)), - ('tri_lanes_w32', 'TRI3 hit +z, origin + lane offset, lane 15', 'fan', 0x09090909, 3, - (0x42c80000, 0xbe880000, 0x40000000, 0xbf800000, 0x00000000, 0x00000000, 0x3f000000, 0x7f800000, 0x7f800000, 0x40000000), - (0xc0800000, 0xbf000000, 0xbd880000, 0xbd080000)), - ('tri_lanes_w32', 'TRI3 hit +z, origin + lane offset, lane 16', 'fan', 0x09090909, 3, - (0x42c80000, 0xbf000000, 0x40010000, 0xbf800000, 0x00000000, 0x00000000, 0x3f000000, 0x7f800000, 0x7f800000, 0x40000000), - (0xc0800000, 0xbf000000, 0xbe000000, 0xbd700000)), - ('tri_lanes_w32', 'TRI3 hit +z, origin + lane offset, lane 31', 'fan', 0x09090909, 3, - (0x42c80000, 0xbe880000, 0x40010000, 0xbf800000, 0x00000000, 0x00000000, 0x3f000000, 0x7f800000, 0x7f800000, 0x40000000), - (0xc0800000, 0xbf000000, 0xbd880000, 0xbcf00000)), - ('tri_lanes_w32', 'TRI3 hit +z, origin + lane offset, lane 32', 'fan', 0x09090909, 3, - (0x42c80000, 0xbf000000, 0x40020000, 0xbf800000, 0x00000000, 0x00000000, 0x3f000000, 0x7f800000, 0x7f800000, 0x40000000), - (0xc0800000, 0xbf000000, 0xbe000000, 0xbd600000)), - ('tri_lanes_w32', 'TRI3 hit +z, origin + lane offset, lane 63', 'fan', 0x09090909, 3, - (0x42c80000, 0xbe880000, 0x40030000, 0xbf800000, 0x00000000, 0x00000000, 0x3f000000, 0x7f800000, 0x7f800000, 0x40000000), - (0xc0800000, 0xbf000000, 0xbd880000, 0xbcb00000)), - ('tri_lanes_w32', 'TRI0 hit -z, origin + lane offset, lane 0', 'fan', 0x09090909, 0, - (0x42c80000, 0x3f800000, 0x3e800000, 0x40e00000, 0x00000000, 0x00000000, 0xbf000000, 0x7f800000, 0x7f800000, 0xc0000000), - (0x41000000, 0x3f800000, 0x3e800000, 0x3e000000)), - ('tri_lanes_w32', 'TRI0 hit -z, origin + lane offset, lane 15', 'fan', 0x09090909, 0, - (0x42c80000, 0x3f9e0000, 0x3e800000, 0x40e00000, 0x00000000, 0x00000000, 0xbf000000, 0x7f800000, 0x7f800000, 0xc0000000), - (0x41000000, 0x3f800000, 0x3e9e0000, 0x3e000000)), - ('tri_lanes_w32', 'TRI0 hit -z, origin + lane offset, lane 16', 'fan', 0x09090909, 0, - (0x42c80000, 0x3f800000, 0x3e880000, 0x40e00000, 0x00000000, 0x00000000, 0xbf000000, 0x7f800000, 0x7f800000, 0xc0000000), - (0x41000000, 0x3f800000, 0x3e800000, 0x3e080000)), - ('tri_lanes_w32', 'TRI0 hit -z, origin + lane offset, lane 31', 'fan', 0x09090909, 0, - (0x42c80000, 0x3f9e0000, 0x3e880000, 0x40e00000, 0x00000000, 0x00000000, 0xbf000000, 0x7f800000, 0x7f800000, 0xc0000000), - (0x41000000, 0x3f800000, 0x3e9e0000, 0x3e080000)), - ('tri_lanes_w32', 'TRI0 hit -z, origin + lane offset, lane 32', 'fan', 0x09090909, 0, - (0x42c80000, 0x3f800000, 0x3e900000, 0x40e00000, 0x00000000, 0x00000000, 0xbf000000, 0x7f800000, 0x7f800000, 0xc0000000), - (0x41000000, 0x3f800000, 0x3e800000, 0x3e100000)), - ('tri_lanes_w32', 'TRI0 hit -z, origin + lane offset, lane 63', 'fan', 0x09090909, 0, - (0x42c80000, 0x3f9e0000, 0x3e980000, 0x40e00000, 0x00000000, 0x00000000, 0xbf000000, 0x7f800000, 0x7f800000, 0xc0000000), - (0x41000000, 0x3f800000, 0x3e9e0000, 0x3e180000)), - ('tri_lanes_w32', 'TRI0 miss, origin + lane offset, lane 0', 'fan', 0x09090909, 0, - (0x42c80000, 0x40600000, 0x3fa00000, 0xbf800000, 0x00000000, 0x00000000, 0x3f000000, 0x7f800000, 0x7f800000, 0x40000000), - (0xff800000, 0xbf800000, 0xbf600000, 0xbf200000)), - ('tri_lanes_w32', 'TRI0 miss, origin + lane offset, lane 15', 'fan', 0x09090909, 0, - (0x42c80000, 0x406f0000, 0x3fa00000, 0xbf800000, 0x00000000, 0x00000000, 0x3f000000, 0x7f800000, 0x7f800000, 0x40000000), - (0xff800000, 0xbf800000, 0xbf6f0000, 0xbf200000)), - ('tri_lanes_w32', 'TRI0 miss, origin + lane offset, lane 16', 'fan', 0x09090909, 0, - (0x42c80000, 0x40600000, 0x3fa20000, 0xbf800000, 0x00000000, 0x00000000, 0x3f000000, 0x7f800000, 0x7f800000, 0x40000000), - (0xff800000, 0xbf800000, 0xbf600000, 0xbf220000)), - ('tri_lanes_w32', 'TRI0 miss, origin + lane offset, lane 31', 'fan', 0x09090909, 0, - (0x42c80000, 0x406f0000, 0x3fa20000, 0xbf800000, 0x00000000, 0x00000000, 0x3f000000, 0x7f800000, 0x7f800000, 0x40000000), - (0xff800000, 0xbf800000, 0xbf6f0000, 0xbf220000)), - ('tri_lanes_w32', 'TRI0 miss, origin + lane offset, lane 32', 'fan', 0x09090909, 0, - (0x42c80000, 0x40600000, 0x3fa40000, 0xbf800000, 0x00000000, 0x00000000, 0x3f000000, 0x7f800000, 0x7f800000, 0x40000000), - (0xff800000, 0xbf800000, 0xbf600000, 0xbf240000)), - ('tri_lanes_w32', 'TRI0 miss, origin + lane offset, lane 63', 'fan', 0x09090909, 0, - (0x42c80000, 0x406f0000, 0x3fa60000, 0xbf800000, 0x00000000, 0x00000000, 0x3f000000, 0x7f800000, 0x7f800000, 0x40000000), - (0xff800000, 0xbf800000, 0xbf6f0000, 0xbf260000)), - ('tri_lanes_w32', 'TRI1 hit oblique +z, origin + lane offset, lane 0', 'fan', 0x09090909, 1, - (0x42c80000, 0x40200000, 0x3f400000, 0xbf800000, 0x3e000000, 0x3d800000, 0x3f000000, 0x41000000, 0x41800000, 0x40000000), - (0xc1000000, 0xbf800000, 0xbf000000, 0xbe000000)), - ('tri_lanes_w32', 'TRI1 hit oblique +z, origin + lane offset, lane 15', 'fan', 0x09090909, 1, - (0x42c80000, 0x402f0000, 0x3f400000, 0xbf800000, 0x3e000000, 0x3d800000, 0x3f000000, 0x41000000, 0x41800000, 0x40000000), - (0xc1000000, 0xbf800000, 0xbf0f0000, 0xbd880000)), - ('tri_lanes_w32', 'TRI1 hit oblique +z, origin + lane offset, lane 16', 'fan', 0x09090909, 1, - (0x42c80000, 0x40200000, 0x3f440000, 0xbf800000, 0x3e000000, 0x3d800000, 0x3f000000, 0x41000000, 0x41800000, 0x40000000), - (0xc1000000, 0xbf800000, 0xbf020000, 0xbe000000)), - ('tri_lanes_w32', 'TRI1 hit oblique +z, origin + lane offset, lane 31', 'fan', 0x09090909, 1, - (0x42c80000, 0x402f0000, 0x3f440000, 0xbf800000, 0x3e000000, 0x3d800000, 0x3f000000, 0x41000000, 0x41800000, 0x40000000), - (0xc1000000, 0xbf800000, 0xbf110000, 0xbd880000)), - ('tri_lanes_w32', 'TRI1 hit oblique +z, origin + lane offset, lane 32', 'fan', 0x09090909, 1, - (0x42c80000, 0x40200000, 0x3f480000, 0xbf800000, 0x3e000000, 0x3d800000, 0x3f000000, 0x41000000, 0x41800000, 0x40000000), - (0xc1000000, 0xbf800000, 0xbf040000, 0xbe000000)), - ('tri_lanes_w32', 'TRI1 hit oblique +z, origin + lane offset, lane 63', 'fan', 0x09090909, 1, - (0x42c80000, 0x402f0000, 0x3f4c0000, 0xbf800000, 0x3e000000, 0x3d800000, 0x3f000000, 0x41000000, 0x41800000, 0x40000000), - (0xc1000000, 0xbf800000, 0xbf150000, 0xbd880000)), - ('tri_lanes_w64', 'TRI0 hit +z, origin + lane offset, lane 0', 'fan', 0x09090909, 0, - (0x42c80000, 0x3f800000, 0x3e800000, 0xbf800000, 0x00000000, 0x00000000, 0x3f000000, 0x7f800000, 0x7f800000, 0x40000000), - (0xc1000000, 0xbf800000, 0xbe800000, 0xbe000000)), - ('tri_lanes_w64', 'TRI0 hit +z, origin + lane offset, lane 15', 'fan', 0x09090909, 0, - (0x42c80000, 0x3f9e0000, 0x3e800000, 0xbf800000, 0x00000000, 0x00000000, 0x3f000000, 0x7f800000, 0x7f800000, 0x40000000), - (0xc1000000, 0xbf800000, 0xbe9e0000, 0xbe000000)), - ('tri_lanes_w64', 'TRI0 hit +z, origin + lane offset, lane 16', 'fan', 0x09090909, 0, - (0x42c80000, 0x3f800000, 0x3e880000, 0xbf800000, 0x00000000, 0x00000000, 0x3f000000, 0x7f800000, 0x7f800000, 0x40000000), - (0xc1000000, 0xbf800000, 0xbe800000, 0xbe080000)), - ('tri_lanes_w64', 'TRI0 hit +z, origin + lane offset, lane 31', 'fan', 0x09090909, 0, - (0x42c80000, 0x3f9e0000, 0x3e880000, 0xbf800000, 0x00000000, 0x00000000, 0x3f000000, 0x7f800000, 0x7f800000, 0x40000000), - (0xc1000000, 0xbf800000, 0xbe9e0000, 0xbe080000)), - ('tri_lanes_w64', 'TRI0 hit +z, origin + lane offset, lane 32', 'fan', 0x09090909, 0, - (0x42c80000, 0x3f800000, 0x3e900000, 0xbf800000, 0x00000000, 0x00000000, 0x3f000000, 0x7f800000, 0x7f800000, 0x40000000), - (0xc1000000, 0xbf800000, 0xbe800000, 0xbe100000)), - ('tri_lanes_w64', 'TRI0 hit +z, origin + lane offset, lane 63', 'fan', 0x09090909, 0, - (0x42c80000, 0x3f9e0000, 0x3e980000, 0xbf800000, 0x00000000, 0x00000000, 0x3f000000, 0x7f800000, 0x7f800000, 0x40000000), - (0xc1000000, 0xbf800000, 0xbe9e0000, 0xbe180000)), - ('tri_lanes_w64', 'TRI1 hit +z, origin + lane offset, lane 0', 'fan', 0x09090909, 1, - (0x42c80000, 0x40600000, 0x3fa00000, 0xbf800000, 0x00000000, 0x00000000, 0x3f000000, 0x7f800000, 0x7f800000, 0x40000000), - (0xc1000000, 0xbf800000, 0xbf000000, 0xbe000000)), - ('tri_lanes_w64', 'TRI1 hit +z, origin + lane offset, lane 15', 'fan', 0x09090909, 1, - (0x42c80000, 0x406f0000, 0x3fa00000, 0xbf800000, 0x00000000, 0x00000000, 0x3f000000, 0x7f800000, 0x7f800000, 0x40000000), - (0xc1000000, 0xbf800000, 0xbf0f0000, 0xbd880000)), - ('tri_lanes_w64', 'TRI1 hit +z, origin + lane offset, lane 16', 'fan', 0x09090909, 1, - (0x42c80000, 0x40600000, 0x3fa20000, 0xbf800000, 0x00000000, 0x00000000, 0x3f000000, 0x7f800000, 0x7f800000, 0x40000000), - (0xc1000000, 0xbf800000, 0xbf020000, 0xbe000000)), - ('tri_lanes_w64', 'TRI1 hit +z, origin + lane offset, lane 31', 'fan', 0x09090909, 1, - (0x42c80000, 0x406f0000, 0x3fa20000, 0xbf800000, 0x00000000, 0x00000000, 0x3f000000, 0x7f800000, 0x7f800000, 0x40000000), - (0xc1000000, 0xbf800000, 0xbf110000, 0xbd880000)), - ('tri_lanes_w64', 'TRI1 hit +z, origin + lane offset, lane 32', 'fan', 0x09090909, 1, - (0x42c80000, 0x40600000, 0x3fa40000, 0xbf800000, 0x00000000, 0x00000000, 0x3f000000, 0x7f800000, 0x7f800000, 0x40000000), - (0xc1000000, 0xbf800000, 0xbf040000, 0xbe000000)), - ('tri_lanes_w64', 'TRI1 hit +z, origin + lane offset, lane 63', 'fan', 0x09090909, 1, - (0x42c80000, 0x406f0000, 0x3fa60000, 0xbf800000, 0x00000000, 0x00000000, 0x3f000000, 0x7f800000, 0x7f800000, 0x40000000), - (0xc1000000, 0xbf800000, 0xbf150000, 0xbd880000)), - ('tri_lanes_w64', 'TRI2 hit +z, origin + lane offset, lane 0', 'fan', 0x09090909, 2, - (0x42c80000, 0x3fe00000, 0x40080000, 0xbf800000, 0x00000000, 0x00000000, 0x3f000000, 0x7f800000, 0x7f800000, 0x40000000), - (0xc0800000, 0xbf000000, 0xbe800000, 0xbd800000)), - ('tri_lanes_w64', 'TRI2 hit +z, origin + lane offset, lane 15', 'fan', 0x09090909, 2, - (0x42c80000, 0x3ffe0000, 0x40080000, 0xbf800000, 0x00000000, 0x00000000, 0x3f000000, 0x7f800000, 0x7f800000, 0x40000000), - (0xc0800000, 0xbf000000, 0xbe8f0000, 0xbd800000)), - ('tri_lanes_w64', 'TRI2 hit +z, origin + lane offset, lane 16', 'fan', 0x09090909, 2, - (0x42c80000, 0x3fe00000, 0x40090000, 0xbf800000, 0x00000000, 0x00000000, 0x3f000000, 0x7f800000, 0x7f800000, 0x40000000), - (0xc0800000, 0xbf000000, 0xbe820000, 0xbd900000)), - ('tri_lanes_w64', 'TRI2 hit +z, origin + lane offset, lane 31', 'fan', 0x09090909, 2, - (0x42c80000, 0x3ffe0000, 0x40090000, 0xbf800000, 0x00000000, 0x00000000, 0x3f000000, 0x7f800000, 0x7f800000, 0x40000000), - (0xc0800000, 0xbf000000, 0xbe910000, 0xbd900000)), - ('tri_lanes_w64', 'TRI2 hit +z, origin + lane offset, lane 32', 'fan', 0x09090909, 2, - (0x42c80000, 0x3fe00000, 0x400a0000, 0xbf800000, 0x00000000, 0x00000000, 0x3f000000, 0x7f800000, 0x7f800000, 0x40000000), - (0xc0800000, 0xbf000000, 0xbe840000, 0xbda00000)), - ('tri_lanes_w64', 'TRI2 hit +z, origin + lane offset, lane 63', 'fan', 0x09090909, 2, - (0x42c80000, 0x3ffe0000, 0x400b0000, 0xbf800000, 0x00000000, 0x00000000, 0x3f000000, 0x7f800000, 0x7f800000, 0x40000000), - (0xc0800000, 0xbf000000, 0xbe950000, 0xbdb00000)), - ('tri_lanes_w64', 'TRI3 hit +z, origin + lane offset, lane 0', 'fan', 0x09090909, 3, - (0x42c80000, 0xbf000000, 0x40000000, 0xbf800000, 0x00000000, 0x00000000, 0x3f000000, 0x7f800000, 0x7f800000, 0x40000000), - (0xc0800000, 0xbf000000, 0xbe000000, 0xbd800000)), - ('tri_lanes_w64', 'TRI3 hit +z, origin + lane offset, lane 15', 'fan', 0x09090909, 3, - (0x42c80000, 0xbe880000, 0x40000000, 0xbf800000, 0x00000000, 0x00000000, 0x3f000000, 0x7f800000, 0x7f800000, 0x40000000), - (0xc0800000, 0xbf000000, 0xbd880000, 0xbd080000)), - ('tri_lanes_w64', 'TRI3 hit +z, origin + lane offset, lane 16', 'fan', 0x09090909, 3, - (0x42c80000, 0xbf000000, 0x40010000, 0xbf800000, 0x00000000, 0x00000000, 0x3f000000, 0x7f800000, 0x7f800000, 0x40000000), - (0xc0800000, 0xbf000000, 0xbe000000, 0xbd700000)), - ('tri_lanes_w64', 'TRI3 hit +z, origin + lane offset, lane 31', 'fan', 0x09090909, 3, - (0x42c80000, 0xbe880000, 0x40010000, 0xbf800000, 0x00000000, 0x00000000, 0x3f000000, 0x7f800000, 0x7f800000, 0x40000000), - (0xc0800000, 0xbf000000, 0xbd880000, 0xbcf00000)), - ('tri_lanes_w64', 'TRI3 hit +z, origin + lane offset, lane 32', 'fan', 0x09090909, 3, - (0x42c80000, 0xbf000000, 0x40020000, 0xbf800000, 0x00000000, 0x00000000, 0x3f000000, 0x7f800000, 0x7f800000, 0x40000000), - (0xc0800000, 0xbf000000, 0xbe000000, 0xbd600000)), - ('tri_lanes_w64', 'TRI3 hit +z, origin + lane offset, lane 63', 'fan', 0x09090909, 3, - (0x42c80000, 0xbe880000, 0x40030000, 0xbf800000, 0x00000000, 0x00000000, 0x3f000000, 0x7f800000, 0x7f800000, 0x40000000), - (0xc0800000, 0xbf000000, 0xbd880000, 0xbcb00000)), - ('tri_lanes_w64', 'TRI0 hit -z, origin + lane offset, lane 0', 'fan', 0x09090909, 0, - (0x42c80000, 0x3f800000, 0x3e800000, 0x40e00000, 0x00000000, 0x00000000, 0xbf000000, 0x7f800000, 0x7f800000, 0xc0000000), - (0x41000000, 0x3f800000, 0x3e800000, 0x3e000000)), - ('tri_lanes_w64', 'TRI0 hit -z, origin + lane offset, lane 15', 'fan', 0x09090909, 0, - (0x42c80000, 0x3f9e0000, 0x3e800000, 0x40e00000, 0x00000000, 0x00000000, 0xbf000000, 0x7f800000, 0x7f800000, 0xc0000000), - (0x41000000, 0x3f800000, 0x3e9e0000, 0x3e000000)), - ('tri_lanes_w64', 'TRI0 hit -z, origin + lane offset, lane 16', 'fan', 0x09090909, 0, - (0x42c80000, 0x3f800000, 0x3e880000, 0x40e00000, 0x00000000, 0x00000000, 0xbf000000, 0x7f800000, 0x7f800000, 0xc0000000), - (0x41000000, 0x3f800000, 0x3e800000, 0x3e080000)), - ('tri_lanes_w64', 'TRI0 hit -z, origin + lane offset, lane 31', 'fan', 0x09090909, 0, - (0x42c80000, 0x3f9e0000, 0x3e880000, 0x40e00000, 0x00000000, 0x00000000, 0xbf000000, 0x7f800000, 0x7f800000, 0xc0000000), - (0x41000000, 0x3f800000, 0x3e9e0000, 0x3e080000)), - ('tri_lanes_w64', 'TRI0 hit -z, origin + lane offset, lane 32', 'fan', 0x09090909, 0, - (0x42c80000, 0x3f800000, 0x3e900000, 0x40e00000, 0x00000000, 0x00000000, 0xbf000000, 0x7f800000, 0x7f800000, 0xc0000000), - (0x41000000, 0x3f800000, 0x3e800000, 0x3e100000)), - ('tri_lanes_w64', 'TRI0 hit -z, origin + lane offset, lane 63', 'fan', 0x09090909, 0, - (0x42c80000, 0x3f9e0000, 0x3e980000, 0x40e00000, 0x00000000, 0x00000000, 0xbf000000, 0x7f800000, 0x7f800000, 0xc0000000), - (0x41000000, 0x3f800000, 0x3e9e0000, 0x3e180000)), - ('tri_lanes_w64', 'TRI0 miss, origin + lane offset, lane 0', 'fan', 0x09090909, 0, - (0x42c80000, 0x40600000, 0x3fa00000, 0xbf800000, 0x00000000, 0x00000000, 0x3f000000, 0x7f800000, 0x7f800000, 0x40000000), - (0xff800000, 0xbf800000, 0xbf600000, 0xbf200000)), - ('tri_lanes_w64', 'TRI0 miss, origin + lane offset, lane 15', 'fan', 0x09090909, 0, - (0x42c80000, 0x406f0000, 0x3fa00000, 0xbf800000, 0x00000000, 0x00000000, 0x3f000000, 0x7f800000, 0x7f800000, 0x40000000), - (0xff800000, 0xbf800000, 0xbf6f0000, 0xbf200000)), - ('tri_lanes_w64', 'TRI0 miss, origin + lane offset, lane 16', 'fan', 0x09090909, 0, - (0x42c80000, 0x40600000, 0x3fa20000, 0xbf800000, 0x00000000, 0x00000000, 0x3f000000, 0x7f800000, 0x7f800000, 0x40000000), - (0xff800000, 0xbf800000, 0xbf600000, 0xbf220000)), - ('tri_lanes_w64', 'TRI0 miss, origin + lane offset, lane 31', 'fan', 0x09090909, 0, - (0x42c80000, 0x406f0000, 0x3fa20000, 0xbf800000, 0x00000000, 0x00000000, 0x3f000000, 0x7f800000, 0x7f800000, 0x40000000), - (0xff800000, 0xbf800000, 0xbf6f0000, 0xbf220000)), - ('tri_lanes_w64', 'TRI0 miss, origin + lane offset, lane 32', 'fan', 0x09090909, 0, - (0x42c80000, 0x40600000, 0x3fa40000, 0xbf800000, 0x00000000, 0x00000000, 0x3f000000, 0x7f800000, 0x7f800000, 0x40000000), - (0xff800000, 0xbf800000, 0xbf600000, 0xbf240000)), - ('tri_lanes_w64', 'TRI0 miss, origin + lane offset, lane 63', 'fan', 0x09090909, 0, - (0x42c80000, 0x406f0000, 0x3fa60000, 0xbf800000, 0x00000000, 0x00000000, 0x3f000000, 0x7f800000, 0x7f800000, 0x40000000), - (0xff800000, 0xbf800000, 0xbf6f0000, 0xbf260000)), - ('tri_lanes_w64', 'TRI1 hit oblique +z, origin + lane offset, lane 0', 'fan', 0x09090909, 1, - (0x42c80000, 0x40200000, 0x3f400000, 0xbf800000, 0x3e000000, 0x3d800000, 0x3f000000, 0x41000000, 0x41800000, 0x40000000), - (0xc1000000, 0xbf800000, 0xbf000000, 0xbe000000)), - ('tri_lanes_w64', 'TRI1 hit oblique +z, origin + lane offset, lane 15', 'fan', 0x09090909, 1, - (0x42c80000, 0x402f0000, 0x3f400000, 0xbf800000, 0x3e000000, 0x3d800000, 0x3f000000, 0x41000000, 0x41800000, 0x40000000), - (0xc1000000, 0xbf800000, 0xbf0f0000, 0xbd880000)), - ('tri_lanes_w64', 'TRI1 hit oblique +z, origin + lane offset, lane 16', 'fan', 0x09090909, 1, - (0x42c80000, 0x40200000, 0x3f440000, 0xbf800000, 0x3e000000, 0x3d800000, 0x3f000000, 0x41000000, 0x41800000, 0x40000000), - (0xc1000000, 0xbf800000, 0xbf020000, 0xbe000000)), - ('tri_lanes_w64', 'TRI1 hit oblique +z, origin + lane offset, lane 31', 'fan', 0x09090909, 1, - (0x42c80000, 0x402f0000, 0x3f440000, 0xbf800000, 0x3e000000, 0x3d800000, 0x3f000000, 0x41000000, 0x41800000, 0x40000000), - (0xc1000000, 0xbf800000, 0xbf110000, 0xbd880000)), - ('tri_lanes_w64', 'TRI1 hit oblique +z, origin + lane offset, lane 32', 'fan', 0x09090909, 1, - (0x42c80000, 0x40200000, 0x3f480000, 0xbf800000, 0x3e000000, 0x3d800000, 0x3f000000, 0x41000000, 0x41800000, 0x40000000), - (0xc1000000, 0xbf800000, 0xbf040000, 0xbe000000)), - ('tri_lanes_w64', 'TRI1 hit oblique +z, origin + lane offset, lane 63', 'fan', 0x09090909, 1, - (0x42c80000, 0x402f0000, 0x3f4c0000, 0xbf800000, 0x3e000000, 0x3d800000, 0x3f000000, 0x41000000, 0x41800000, 0x40000000), - (0xc1000000, 0xbf800000, 0xbf150000, 0xbd880000)), -] -# END MEASURED DATA - - -def program(form, nsa): - """A pixel shader that loads the node id and the ray from memory and exports the instruction's four words.""" - lines = ["s_buffer_load_dwordx16 s[8:23], s[0:3], 0", "s_waitcnt lgkmcnt(0)"] - if form == "64": - lines += [f"v_mov_b32_e32 v{1 + i}, s{8 + i}" for i in range(12)] # v1:v2 node id, v3..v12 ray - lines += ["s_mov_b32 s4, 0", "s_mov_b32 s5, 0x80000000"] # base 0: the id is the address - regs = [f"v{1 + i}" for i in range(12)] - op = "image_bvh64_intersect_ray" - else: - lines += ["v_mov_b32_e32 v1, s8"] + [f"v_mov_b32_e32 v{2 + i}, s{10 + i}" for i in range(10)] - lines += [f"s_mov_b32 s4, 0x{NODE >> 8:x}", "s_mov_b32 s5, 0x80000000"] # base = NODE in 256-byte units - regs = [f"v{1 + i}" for i in range(11)] - op = "image_bvh_intersect_ray" - addr = "[" + ", ".join(regs) + "]" if nsa else f"v[1:{len(regs)}]" - lines += ["s_mov_b32 s6, -1", "s_mov_b32 s7, 0x81000000", - f"{op} v[20:23], {addr}, s[4:7]", "exp mrt0 v20, v21, v22, v23 done vm", "s_endpgm"] - return translate_lines(f"ps_bvh_tri_hw_{form}{'_nsa' if nsa else ''}", lines) - - -_SPV = {} - - -def run(form, nsa, node, w15, ntype, ray): - key = (form, nsa) - if key not in _SPV: - _SPV[key] = program(form, nsa) - nid = (NODE >> 3 | ntype) if form == "64" else ntype - mem = {RAY + 4 * i: w for i, w in enumerate([nid, 0, *ray, 0, 0, 0, 0])} - mem.update({NODE + 4 * i: w for i, w in enumerate(NODES[node] + [w15])}) - return list(mrt0_words(_SPV[key], push_constants=PUSH, memory=mem)) - - -def words(ws): - return " ".join(f"{w:08x}" for w in ws) - - -class MeasuredTriangleNodes(unittest.TestCase): - def check(self, rows): - for kernel, label, node, w15, ntype, ray, hw in rows: - for form in ("32", "64"): - with self.subTest(kernel=kernel, case=label, form=form): - got = run(form, kernel.endswith("_nsa"), node, w15, ntype, ray) - self.assertEqual(words(got), words(hw)) - - def test_single_lane_rows(self): - self.check(ROWS) - - def test_lane_rows(self): - self.check(LANE_ROWS) - - def test_table(self): - # a row dropped from the table (or one kernel's rows lost) fails here, not silently - per = {} - for kernel, *_ in ROWS: - per[kernel] = per.get(kernel, 0) + 1 - self.assertEqual(per, {"tri_g1a": 25, "tri_g1a_nsa": 25, "tri_g1a_w64": 25, "tri_g1b": 16, "tri_g1c": 30, - "tri_g2a": 32, "tri_g2b": 32, "tri_g2c": 32, "tri_g3a": 24, "tri_g3b": 19, - "tri_g4a": 16, "tri_g4b": 32, **{f"tri_t{i}": 32 for i in range(1, 9)}}) - self.assertEqual(len(LANE_ROWS), 2 * 7 * 6) - self.assertEqual(len({(k, lb) for k, lb, *_ in ROWS}), len(ROWS)) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_image_coherent.py b/tests/semantic/test_image_coherent.py deleted file mode 100644 index 4511bcc35..000000000 --- a/tests/semantic/test_image_coherent.py +++ /dev/null @@ -1,176 +0,0 @@ -"""Coherent image accesses: glc on image_load / image_store (docs/design.md "Coherent image accesses"). - -On GFX10 a device-scope (coherent) load is glc + dlc and a device-scope store glc: Mesa ac_get_hw_cache_flags -(src/amd/common/ac_shader_util.c) sets exactly these bits for ACCESS_COHERENT. The game's POPS pixel shaders read -and write their ordered images that way, a read-modify-write that relies on seeing the previous fragment's store. -A read through the sampled array (SHADER-151's path for every other image_load) has no coherent form in SPIR-V, and -the fragment-shader interlock only makes Coherent memory visible between critical sections (Vulkan memory model: -non-atomic accesses are private unless Coherent). So a glc image_load reads the storage view the stores write -(OpImageRead), and a shader with coherent image accesses decorates its storage views Coherent. - -These tests translate small pixel shaders with the real translator (tests/semantic/support.py) and check the SPIR-V: -which variable and component type every read and write uses, the decorations, capabilities and index features, -that plain accesses keep the sampled path, and that a coherent read the translator cannot model is refused. -""" -import os -import re -import shutil -import tempfile -import unittest - -import support -import rdna2spirv - -EPILOGUE = ["exp mrt0 v0, v1, v2, v3 done vm", "s_endpgm"] -# dim -> (address registers, STORE_DIMS index) -DIMS = {"2D": ("v[4:5]", 0), "2D_ARRAY": ("v[4:6]", 1), "CUBE": ("v[4:6]", 1), - "3D": ("v[4:6]", 2), "1D": ("v4", 3)} -CLASS_TYPES = {0: "%v4float", 1: "%v4uint_st", 2: "%v4int_st"} # storage view class -> texel type - - -def translate(lines): - return support.translate_lines("ps_coherent", ["v_mov_b32 v4, 1", "v_mov_b32 v5, 2", "v_mov_b32 v6, 0"] - + lines + EPILOGUE) - - -def rmw(dim="2D", load_mods="glc dlc", store_mods="glc", dmask=0xF): - """The POPS pattern: read a texel, add 1.0 to red, write it back to the same T#.""" - addr = DIMS[dim][0] - return translate([f"image_load v[0:3], {addr}, s[0:7] dmask:0x{dmask:x} dim:SQ_RSRC_IMG_{dim} unorm {load_mods}", - "s_waitcnt vmcnt(0)", "v_add_f32_e32 v0, 1.0, v0", - f"image_store v[0:3], {addr}, s[0:7] dmask:0xf dim:SQ_RSRC_IMG_{dim} unorm {store_mods}"]) - - -class Module: - def __init__(self, text): - self.text = text - self.defs = {} - self.ops = [] - for line in text.splitlines(): - m = re.match(r"\s*(%\w+) = (Op\w+)\s*(.*)$", line) - if m: - self.defs[m.group(1)] = (m.group(2), m.group(3).split()) - self.ops.append((m.group(1), m.group(2), m.group(3).split())) - else: - w = line.split() - if w: - self.ops.append((None, w[0], w[1:])) - self.caps = {a[0] for _, op, a in self.ops if op == "OpCapability"} - self.coherent = {a[0] for _, op, a in self.ops if op == "OpDecorate" and a[1:] == ["Coherent"]} - - def variable(self, image): - """The bindless array an image id was loaded from (OpLoad of an OpAccessChain into it).""" - op, a = self.defs[image] - assert op == "OpLoad", (image, op) - op, a = self.defs[a[1]] - assert op == "OpAccessChain", (image, op) - return a[1] - - def reads(self): - """(result type, variable) of every OpImageRead, in program order.""" - return [(a[0], self.variable(a[1])) for _, op, a in self.ops if op == "OpImageRead"] - - def writes(self): - """(texel type, variable) of every OpImageWrite.""" - out = [] - for _, op, a in self.ops: - if op == "OpImageWrite": - texel_op, texel = self.defs[a[2]] - assert texel_op == "OpCompositeConstruct", texel_op - out.append((texel[0], self.variable(a[0]))) - return out - - def chains_into(self, prefix): - return [a[1] for _, op, a in self.ops if op == "OpAccessChain" and a[1].startswith(prefix)] - - -class CoherentReadModifyWrite(unittest.TestCase): - def test_coherent_load_reads_the_storage_views_the_store_writes(self): - m = Module(rmw()) - reads, writes = m.reads(), m.writes() - # One read per numeric class, each from that class's storage view, with that class's texel type. - self.assertEqual(sorted(reads), sorted((CLASS_TYPES[c], f"%stv{c}_0") for c in range(3))) - self.assertEqual(sorted(writes), sorted((CLASS_TYPES[c], f"%stv{c}_0") for c in range(3))) - self.assertNotIn("OpImageFetch", m.text) # nothing reads through the sampled arrays - self.assertEqual(m.chains_into("%images") + m.chains_into("%itx"), []) - # Every read comes before every write (the read-modify-write order). - order = [op for _, op, _ in m.ops if op in ("OpImageRead", "OpImageWrite")] - self.assertEqual(order, ["OpImageRead"] * 3 + ["OpImageWrite"] * 3) - - def test_storage_views_are_coherent_and_the_read_feature_is_declared(self): - text = rmw() - m = Module(text) - self.assertEqual(m.coherent, {"%stv0_0", "%stv1_0", "%stv2_0"}) - self.assertLessEqual({"StorageImageReadWithoutFormat", "StorageImageWriteWithoutFormat"}, m.caps) - features = rdna2spirv.shader_meta(rdna2spirv.translate.last_gen, text)["features"] - self.assertIn("shaderStorageImageReadWithoutFormat", features) - - def test_every_dimension_and_d16(self): - for dim, (_, di) in DIMS.items(): - with self.subTest(dim=dim): - m = Module(rmw(dim)) - self.assertEqual({v for _, v in m.reads()}, {f"%stv{c}_{di}" for c in range(3)}) - self.assertEqual(m.coherent, {f"%stv{c}_{di}" for c in range(3)}) - # d16: the same storage reads, the texel packed two halves per VGPR (as on the sampled path) - m = Module(translate(["image_load v[0:1], v[4:5], s[0:7] dmask:0xf dim:SQ_RSRC_IMG_2D unorm glc dlc d16"])) - self.assertEqual({v for _, v in m.reads()}, {"%stv0_0", "%stv1_0", "%stv2_0"}) - self.assertNotIn("OpImageFetch", m.text) - - def test_glc_alone_is_coherent(self): - # GFX10: glc without dlc is shader-array scope for a load; Coherent (device scope) covers it. - m = Module(rmw(load_mods="glc")) - self.assertEqual(len(m.reads()), 3) - self.assertEqual(m.coherent, {"%stv0_0", "%stv1_0", "%stv2_0"}) - - -class OnlyCoherentAccessesChange(unittest.TestCase): - def test_a_coherent_store_alone_needs_no_read_feature(self): - m = Module(translate(["image_store v[0:3], v[4:5], s[0:7] dmask:0xf dim:SQ_RSRC_IMG_2D unorm glc"])) - self.assertEqual(m.coherent, {"%stv0_0", "%stv1_0", "%stv2_0"}) - self.assertNotIn("StorageImageReadWithoutFormat", m.caps) - self.assertEqual(m.reads(), []) - - def test_plain_load_and_store_keep_the_sampled_path(self): - # SHADER-151: a load without glc reads the sampled arrays, so it needs no storage read feature. - m = Module(rmw(load_mods="", store_mods="")) - self.assertEqual(m.reads(), []) - self.assertIn("OpImageFetch", m.text) - self.assertEqual(m.coherent, set()) - self.assertNotIn("StorageImageReadWithoutFormat", m.caps) - - def test_dlc_alone_is_not_coherent(self): - # GFX10: dlc without glc is a CU-scope load that bypasses GL1 (ac_get_hw_cache_flags), not device scope. - m = Module(rmw(load_mods="dlc", store_mods="")) - self.assertEqual(m.reads(), []) - self.assertEqual(m.coherent, set()) - - -class UnmodelledCoherentReads(unittest.TestCase): - def check_refused(self, line): - with self.assertRaises(rdna2spirv.Unsupported): - translate([line]) - - def test_a_coherent_sampled_read_is_refused(self): - self.check_refused("image_sample v[0:3], v[4:5], s[0:7], s[8:11] dmask:0xf dim:SQ_RSRC_IMG_2D glc") - self.check_refused("image_gather4_lz v[0:3], v[4:5], s[0:7], s[8:11] dmask:0x1 dim:SQ_RSRC_IMG_2D glc") - - def test_a_coherent_load_without_a_storage_view_is_refused(self): - self.check_refused("image_load v[0:3], v[4:6], s[0:7] dmask:0xf dim:SQ_RSRC_IMG_2D_MSAA unorm glc dlc") - self.check_refused("image_load_mip v[0:3], v[4:6], s[0:7] dmask:0xf dim:SQ_RSRC_IMG_2D unorm glc dlc") - - -@unittest.skipUnless(shutil.which("spirv-as") and shutil.which("spirv-val"), "needs spirv-as and spirv-val") -class Validation(unittest.TestCase): - def test_spirv_val_accepts_every_dimension(self): - with tempfile.TemporaryDirectory() as tmp: - for dim in DIMS: - with self.subTest(dim=dim): - sa, sv = os.path.join(tmp, f"{dim}.spvasm"), os.path.join(tmp, f"{dim}.spv") - with open(sa, "w", encoding="utf-8") as f: - f.write(rmw(dim)) - result = rdna2spirv.assemble_spirv(sa, sv) - self.assertEqual(result.returncode, 0, result.stderr + result.stdout) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_image_cube_store_glc.py b/tests/semantic/test_image_cube_store_glc.py deleted file mode 100644 index e8bbca220..000000000 --- a/tests/semantic/test_image_cube_store_glc.py +++ /dev/null @@ -1,313 +0,0 @@ -"""image_store and coherent image_load (glc) on dim:SQ_RSRC_IMG_CUBE (RDNA2 ISA). - -Cube storage images are bound as 6-layer 2D array views (runtime/src/vulkan_bindless.h, STORE_DIMS index 1: -bindings 11/12/13 for float/uint/sint, OpTypeImage ... 2D 0 1 0 2 Unknown, %v3int coordinates (x, y, face)), -matching non-coherent image_load on dim:SQ_RSRC_IMG_CUBE. - -These tests verify: -- image_store and coherent image_load (glc / glc dlc) on dim:SQ_RSRC_IMG_CUBE across dmask subsets, a16, d16, - unorm, and both CS and PS stages; -- llvm-mc -triple=amdgcn -mcpu=gfx1030 binary assemble -> disassemble round-trip into rdna2spirv; -- spirv-val --target-env vulkan1.2 validation of every generated SPIR-V module. -""" -import os -import re -import shlex -import shutil -import struct -import subprocess -import tempfile -import unittest - -import support -import rdna2spirv - -PS_EPILOGUE = ["exp mrt0 v0, v1, v2, v3 done vm", "s_endpgm"] -CS_EPILOGUE = ["s_endpgm"] -CLASS_TYPES = {0: "%v4float", 1: "%v4uint_st", 2: "%v4int_st"} -CUBE_BINDINGS = {"%stv0_1": 11, "%stv1_1": 12, "%stv2_1": 13} - - -def cs_fssm(threads=64): - h = bytearray(0x148) - struct.pack_into("<4I", h, 0x138, 0x8088, threads, 1, 1) - return bytes(h) - - -def translate_stage(stage, lines): - preamble = ["v_mov_b32 v0, 0x3f800000", "v_mov_b32 v1, 0x40000000", - "v_mov_b32 v2, 0x40400000", "v_mov_b32 v3, 0x40800000", - "v_mov_b32 v4, 1", "v_mov_b32 v5, 2", "v_mov_b32 v6, 5"] - if stage == "cs": - return support.translate_lines("cs_cube_store_glc", preamble + lines + CS_EPILOGUE, fssm=cs_fssm()) - return support.translate_lines("ps_cube_store_glc", preamble + lines + PS_EPILOGUE) - - -def vdata_reg(dmask, d16=False): - n = bin(dmask).count("1") - regs = (n + 1) // 2 if d16 else n - return "v0" if regs == 1 else f"v[0:{regs - 1}]" - - -def llvm_mc_cmd(): - env = os.environ.get("LLVM_MC") - if env: - return shlex.split(env) - exe = shutil.which("llvm-mc") - return [exe] if exe else None - - -def validate_spirv(spvasm): - with tempfile.TemporaryDirectory() as tmp: - sa = os.path.join(tmp, "cube.spvasm") - sv = os.path.join(tmp, "cube.spv") - with open(sa, "w", encoding="utf-8", newline="\n") as f: - f.write(spvasm) - as_res = subprocess.run(["spirv-as", "--target-env", "vulkan1.2", sa, "-o", sv], - capture_output=True, text=True, check=False) - if as_res.returncode != 0: - raise AssertionError(f"spirv-as failed:\n{as_res.stderr}{as_res.stdout}") - val_res = subprocess.run(["spirv-val", "--target-env", "vulkan1.2", sv], - capture_output=True, text=True, check=False) - if val_res.returncode != 0: - raise AssertionError(f"spirv-val failed:\n{val_res.stderr}{val_res.stdout}") - - -class Module: - def __init__(self, text): - self.text = text - self.defs = {} - self.ops = [] - self.bindings = {} - for line in text.splitlines(): - m = re.match(r"\s*(%\w+) = (Op\w+)\s*(.*)$", line) - if m: - self.defs[m.group(1)] = (m.group(2), m.group(3).split()) - self.ops.append((m.group(1), m.group(2), m.group(3).split())) - else: - w = line.split() - if w: - self.ops.append((None, w[0], w[1:])) - if w[0] == "OpDecorate" and len(w) == 4 and w[2] == "Binding": - self.bindings[w[1]] = int(w[3]) - self.caps = {a[0] for _, op, a in self.ops if op == "OpCapability"} - self.coherent = {a[0] for _, op, a in self.ops if op == "OpDecorate" and a[1:] == ["Coherent"]} - - def variable(self, image): - op, a = self.defs[image] - assert op == "OpLoad", (image, op) - op, a = self.defs[a[1]] - assert op == "OpAccessChain", (image, op) - return a[1] - - def reads(self): - return [(a[0], self.variable(a[1]), self.defs[a[2]][1][0]) for _, op, a in self.ops if op == "OpImageRead"] - - def writes(self): - out = [] - for _, op, a in self.ops: - if op == "OpImageWrite": - texel_op, texel = self.defs[a[2]] - assert texel_op == "OpCompositeConstruct", texel_op - coord_op, coord = self.defs[a[1]] - assert coord_op == "OpCompositeConstruct", coord_op - out.append((texel[0], self.variable(a[0]), coord[0])) - return out - - -class CubeImageStore(unittest.TestCase): - def test_store_uses_2d_array_storage_views_and_v3int_coords(self): - for stage in ("ps", "cs"): - with self.subTest(stage=stage): - m = Module(translate_stage(stage, [ - "image_store v[0:3], v[4:6], s[0:7] dmask:0xf dim:SQ_RSRC_IMG_CUBE unorm" - ])) - self.assertEqual(sorted(m.writes()), sorted((CLASS_TYPES[c], f"%stv{c}_1", "%v3int") for c in range(3))) - for var, binding in CUBE_BINDINGS.items(): - self.assertEqual(m.bindings.get(var), binding) - for c, st in enumerate(("%float", "%uint", "%int")): - self.assertEqual(m.defs[f"%stimg{c}_1"], ("OpTypeImage", [st, "2D", "0", "1", "0", "2", "Unknown"])) - self.assertIn("StorageImageWriteWithoutFormat", m.caps) - self.assertNotIn("StorageImageReadWithoutFormat", m.caps) - self.assertEqual(m.coherent, set()) - - def test_store_glc_marks_cube_views_coherent(self): - for stage in ("ps", "cs"): - with self.subTest(stage=stage): - m = Module(translate_stage(stage, [ - "image_store v[0:3], v[4:6], s[0:7] dmask:0xf dim:SQ_RSRC_IMG_CUBE unorm glc" - ])) - self.assertEqual(m.coherent, set(CUBE_BINDINGS)) - self.assertNotIn("StorageImageReadWithoutFormat", m.caps) - - def test_store_dmask_a16_d16_combinations(self): - cases = [ - (0x1, False, False, "unorm"), - (0x3, False, False, "unorm"), - (0x7, False, False, "unorm"), - (0x9, False, False, "unorm"), - (0xF, True, False, "unorm"), - (0xF, False, True, "unorm"), - (0x5, True, True, "unorm"), - (0xF, True, True, "unorm glc"), - (0xF, False, False, ""), - ] - for dmask, a16, d16, extra in cases: - addr = "v[4:5]" if a16 else "v[4:6]" - mods = " ".join(x for x in (f"dmask:0x{dmask:x}", "dim:SQ_RSRC_IMG_CUBE", extra, - "a16" if a16 else "", "d16" if d16 else "") if x) - with self.subTest(dmask=hex(dmask), a16=a16, d16=d16, extra=extra): - m = Module(translate_stage("cs", [f"image_store {vdata_reg(dmask, d16)}, {addr}, s[0:7] {mods}"])) - self.assertEqual(sorted(m.writes()), sorted((CLASS_TYPES[c], f"%stv{c}_1", "%v3int") for c in range(3))) - if d16: - self.assertIn("UnpackHalf2x16", m.text) - self.assertIn("OpBitFieldUExtract", m.text) - self.assertIn("OpBitFieldSExtract", m.text) - - def test_store_refuses_tfe_lwe_and_short_coords(self): - bad = [ - "image_store v[0:3], v[4:6], s[0:7] dmask:0xf dim:SQ_RSRC_IMG_CUBE unorm tfe", - "image_store v[0:3], v[4:6], s[0:7] dmask:0xf dim:SQ_RSRC_IMG_CUBE unorm lwe", - "image_store v[0:3], v[4:5], s[0:7] dmask:0xf dim:SQ_RSRC_IMG_CUBE unorm", - "image_store v[0:3], v4, s[0:7] dmask:0xf dim:SQ_RSRC_IMG_CUBE unorm a16", - ] - for line in bad: - with self.subTest(line=line): - with self.assertRaises(rdna2spirv.Unsupported): - translate_stage("cs", [line]) - - -class CubeImageLoadCoherent(unittest.TestCase): - def test_coherent_load_uses_2d_array_storage_views_and_v3int_coords(self): - for stage in ("ps", "cs"): - for mods in ("unorm glc", "unorm glc dlc"): - with self.subTest(stage=stage, mods=mods): - text = translate_stage(stage, [ - f"image_load v[0:3], v[4:6], s[0:7] dmask:0xf dim:SQ_RSRC_IMG_CUBE {mods}", - "s_waitcnt vmcnt(0)", - ]) - m = Module(text) - self.assertEqual(sorted(m.reads()), - sorted((CLASS_TYPES[c], f"%stv{c}_1", "%v3int") for c in range(3))) - self.assertNotIn("OpImageFetch", m.text) - self.assertEqual(m.coherent, set(CUBE_BINDINGS)) - self.assertIn("StorageImageReadWithoutFormat", m.caps) - features = rdna2spirv.shader_meta(rdna2spirv.translate.last_gen, text)["features"] - self.assertIn("shaderStorageImageReadWithoutFormat", features) - - def test_coherent_load_dmask_a16_d16_combinations(self): - cases = [ - (0x1, False, False), - (0x3, False, False), - (0x7, False, False), - (0x9, False, False), - (0xF, True, False), - (0xF, False, True), - (0x5, True, True), - (0xF, True, True), - ] - for dmask, a16, d16 in cases: - addr = "v[4:5]" if a16 else "v[4:6]" - mods = " ".join(x for x in (f"dmask:0x{dmask:x}", "dim:SQ_RSRC_IMG_CUBE", "unorm", "glc", "dlc", - "a16" if a16 else "", "d16" if d16 else "") if x) - with self.subTest(dmask=hex(dmask), a16=a16, d16=d16): - m = Module(translate_stage("ps", [ - f"image_load {vdata_reg(dmask, d16)}, {addr}, s[0:7] {mods}", - "s_waitcnt vmcnt(0)", - ])) - self.assertEqual(sorted(m.reads()), sorted((CLASS_TYPES[c], f"%stv{c}_1", "%v3int") for c in range(3))) - self.assertNotIn("OpImageFetch", m.text) - self.assertEqual(m.coherent, set(CUBE_BINDINGS)) - - def test_coherent_rmw_shares_storage_views_in_order(self): - for stage in ("ps", "cs"): - with self.subTest(stage=stage): - m = Module(translate_stage(stage, [ - "image_load v[0:3], v[4:6], s[0:7] dmask:0xf dim:SQ_RSRC_IMG_CUBE unorm glc dlc", - "s_waitcnt vmcnt(0)", - "v_add_f32_e32 v0, 1.0, v0", - "image_store v[0:3], v[4:6], s[0:7] dmask:0xf dim:SQ_RSRC_IMG_CUBE unorm glc", - ])) - order = [op for _, op, _ in m.ops if op in ("OpImageRead", "OpImageWrite")] - self.assertEqual(order, ["OpImageRead"] * 3 + ["OpImageWrite"] * 3) - self.assertEqual({v for _, v, _ in m.reads()}, set(CUBE_BINDINGS)) - self.assertEqual({v for _, v, _ in m.writes()}, set(CUBE_BINDINGS)) - self.assertEqual(m.coherent, set(CUBE_BINDINGS)) - - -@unittest.skipUnless(shutil.which("spirv-as") and shutil.which("spirv-val"), "needs spirv-as and spirv-val") -class SpirvValidation(unittest.TestCase): - def test_spirv_val_vulkan12_accepts_all_cube_store_and_glc_variants(self): - programs = [ - ("ps_store_f", "ps", ["image_store v[0:3], v[4:6], s[0:7] dmask:0xf dim:SQ_RSRC_IMG_CUBE unorm"]), - ("cs_store_f", "cs", ["image_store v[0:3], v[4:6], s[0:7] dmask:0xf dim:SQ_RSRC_IMG_CUBE unorm"]), - ("cs_store_a16", "cs", ["image_store v[0:3], v[4:5], s[0:7] dmask:0xf dim:SQ_RSRC_IMG_CUBE unorm a16"]), - ("cs_store_d16", "cs", ["image_store v[0:1], v[4:6], s[0:7] dmask:0xf dim:SQ_RSRC_IMG_CUBE unorm d16"]), - ("cs_store_a16_d16_glc", "cs", - ["image_store v0, v[4:5], s[0:7] dmask:0x9 dim:SQ_RSRC_IMG_CUBE unorm glc a16 d16"]), - ("ps_load_glc", "ps", - ["image_load v[0:3], v[4:6], s[0:7] dmask:0xf dim:SQ_RSRC_IMG_CUBE unorm glc dlc", "s_waitcnt vmcnt(0)"]), - ("cs_load_glc_a16_d16", "cs", - ["image_load v[0:1], v[4:5], s[0:7] dmask:0x7 dim:SQ_RSRC_IMG_CUBE unorm glc dlc a16 d16", - "s_waitcnt vmcnt(0)"]), - ("ps_rmw_glc", "ps", [ - "image_load v[0:3], v[4:6], s[0:7] dmask:0xf dim:SQ_RSRC_IMG_CUBE unorm glc dlc", - "s_waitcnt vmcnt(0)", - "v_add_f32_e32 v0, 1.0, v0", - "image_store v[0:3], v[4:6], s[0:7] dmask:0xf dim:SQ_RSRC_IMG_CUBE unorm glc", - ]), - ("cs_rmw_glc_a16_d16", "cs", [ - "image_load v[0:1], v[4:5], s[0:7] dmask:0xf dim:SQ_RSRC_IMG_CUBE unorm glc dlc a16 d16", - "s_waitcnt vmcnt(0)", - "image_store v[0:1], v[4:5], s[0:7] dmask:0xf dim:SQ_RSRC_IMG_CUBE unorm glc a16 d16", - ]), - ] - for name, stage, lines in programs: - with self.subTest(name=name): - validate_spirv(translate_stage(stage, lines)) - - -@unittest.skipUnless(llvm_mc_cmd() is not None, "needs llvm-mc or LLVM_MC") -class LlvmMcRoundTrip(unittest.TestCase): - def test_gfx1030_encode_decode_translate_and_validate(self): - mc = llvm_mc_cmd() - src_insns = [ - "image_store v[0:3], v[4:6], s[0:7] dmask:0xf dim:SQ_RSRC_IMG_CUBE unorm", - "image_store v[0:3], v[4:5], s[0:7] dmask:0xf dim:SQ_RSRC_IMG_CUBE unorm a16", - "image_store v[0:1], v[4:6], s[0:7] dmask:0xf dim:SQ_RSRC_IMG_CUBE unorm d16", - "image_store v0, v[4:5], s[0:7] dmask:0x9 dim:SQ_RSRC_IMG_CUBE unorm glc a16 d16", - "image_load v[0:3], v[4:6], s[0:7] dmask:0xf dim:SQ_RSRC_IMG_CUBE unorm glc dlc", - "image_load v[0:1], v[4:5], s[0:7] dmask:0xf dim:SQ_RSRC_IMG_CUBE unorm glc dlc a16 d16", - ] - enc = subprocess.run(mc + ["-triple=amdgcn", "-mcpu=gfx1030", "-show-encoding"], - input="\n".join(src_insns) + "\n", capture_output=True, text=True, check=False) - self.assertEqual(enc.returncode, 0, enc.stderr + enc.stdout) - byte_lines = re.findall(r"encoding:\s*\[([^\]]+)\]", enc.stdout) - self.assertEqual(len(byte_lines), len(src_insns), enc.stdout) - - hex_input = "\n".join(b.replace(",", " ") for b in byte_lines) + "\n" - dec = subprocess.run(mc + ["-triple=amdgcn", "-mcpu=gfx1030", "--disassemble"], - input=hex_input, capture_output=True, text=True, check=False) - self.assertEqual(dec.returncode, 0, dec.stderr + dec.stdout) - decoded = [ln.strip() for ln in dec.stdout.splitlines() - if ln.strip() and not ln.strip().startswith(".")] - self.assertEqual(len(decoded), len(src_insns), dec.stdout) - - for insn in decoded: - with self.subTest(decoded=insn): - self.assertIn("dim:SQ_RSRC_IMG_CUBE", insn) - spvasm = translate_stage("cs", [insn, "s_waitcnt vmcnt(0)"]) - m = Module(spvasm) - if insn.startswith("image_store"): - self.assertEqual(sorted(m.writes()), - sorted((CLASS_TYPES[c], f"%stv{c}_1", "%v3int") for c in range(3))) - else: - self.assertEqual(sorted(m.reads()), - sorted((CLASS_TYPES[c], f"%stv{c}_1", "%v3int") for c in range(3))) - self.assertEqual(m.coherent, set(CUBE_BINDINGS)) - if shutil.which("spirv-as") and shutil.which("spirv-val"): - validate_spirv(spvasm) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_image_gather4_variants.py b/tests/semantic/test_image_gather4_variants.py deleted file mode 100644 index 78e220d19..000000000 --- a/tests/semantic/test_image_gather4_variants.py +++ /dev/null @@ -1,378 +0,0 @@ -"""Semantic, structural, and spirv-val tests for the 14 RDNA2 image_gather4_* variants. - -Covers: - - Explicit-LOD depth-compare (compute and pixel shaders): - image_gather4_c_l, image_gather4_c_l_o - - Clamped / biased non-compare and depth-compare (pixel shaders via OpImageQueryLod): - image_gather4_cl, image_gather4_cl_o, - image_gather4_c_cl, image_gather4_c_cl_o, - image_gather4_b, image_gather4_b_o, - image_gather4_b_cl, image_gather4_b_cl_o, - image_gather4_c_b, image_gather4_c_b_o, - image_gather4_c_b_cl, image_gather4_c_b_cl_o -""" -import math -import os -import re -import shutil -import struct -import subprocess -import sys -import tempfile -import unittest - -ROOT = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) -TOOLS = os.path.join(ROOT, "tools") -SEMANTIC = os.path.dirname(os.path.abspath(__file__)) -for _p in (TOOLS, SEMANTIC): - if _p not in sys.path: - sys.path.insert(0, _p) - -import rdna2spirv # noqa: E402 -import support # noqa: E402 - -SPIRV_AS = shutil.which("spirv-as") -SPIRV_VAL = shutil.which("spirv-val") -if not SPIRV_AS: - _sdk = r"C:\VulkanSDK\1.4.363.0\Bin\spirv-as.exe" - if os.path.isfile(_sdk): - SPIRV_AS = _sdk -if not SPIRV_VAL: - _sdk = r"C:\VulkanSDK\1.4.363.0\Bin\spirv-val.exe" - if os.path.isfile(_sdk): - SPIRV_VAL = _sdk - - -ALL_14_OPS = ( - # (op, vaddr_2d, vaddr_2d_array, vaddr_2d_a16, vaddr_2d_array_a16) - ("image_gather4_c_l", "v[0:3]", "v[0:4]", "v[0:2]", "v[0:2]"), - ("image_gather4_c_l_o", "v[0:4]", "v[0:5]", "v[0:3]", "v[0:3]"), - ("image_gather4_cl", "v[0:2]", "v[0:3]", "v[0:1]", "v[0:1]"), - ("image_gather4_cl_o", "v[0:3]", "v[0:4]", "v[0:2]", "v[0:2]"), - ("image_gather4_c_cl", "v[0:3]", "v[0:4]", "v[0:2]", "v[0:2]"), - ("image_gather4_c_cl_o", "v[0:4]", "v[0:5]", "v[0:3]", "v[0:3]"), - ("image_gather4_b", "v[0:2]", "v[0:3]", "v[0:1]", "v[0:2]"), - ("image_gather4_b_o", "v[0:3]", "v[0:4]", "v[0:2]", "v[0:3]"), - ("image_gather4_b_cl", "v[0:3]", "v[0:4]", "v[0:2]", "v[0:2]"), - ("image_gather4_b_cl_o", "v[0:4]", "v[0:5]", "v[0:3]", "v[0:3]"), - ("image_gather4_c_b", "v[0:3]", "v[0:4]", "v[0:2]", "v[0:3]"), - ("image_gather4_c_b_o", "v[0:4]", "v[0:5]", "v[0:3]", "v[0:4]"), - ("image_gather4_c_b_cl", "v[0:4]", "v[0:5]", "v[0:3]", "v[0:3]"), - ("image_gather4_c_b_cl_o", "v[0:5]", "v[0:6]", "v[0:4]", "v[0:4]"), -) - -PR_3201_OPS = ( - "image_gather4", - "image_gather4_o", - "image_gather4_c", - "image_gather4_c_o", - "image_gather4_c_lz", - "image_gather4_c_lz_o", -) - - -def _validate(spvasm: str) -> None: - if not (SPIRV_AS and SPIRV_VAL): - return - with tempfile.TemporaryDirectory() as d: - sa, sv = os.path.join(d, "m.spvasm"), os.path.join(d, "m.spv") - with open(sa, "w", encoding="utf-8", newline="\n") as f: - f.write(spvasm) - for cmd in ( - [SPIRV_AS, sa, "-o", sv, "--target-env", "vulkan1.2"], - [SPIRV_VAL, "--target-env", "vulkan1.2", sv], - ): - r = subprocess.run(cmd, capture_output=True, text=True) - if r.returncode != 0: - raise AssertionError(f"{cmd[0]} failed:\n{r.stderr}") - - -def _f32(x: float) -> float: - return struct.unpack(" float: - return struct.unpack(" int: - """Evaluate the emitted mip level operand of OpImageQuerySizeLod in binary32 (mirrors #4321).""" - defs = dict(re.findall(r"^\s*(%\w+) = (.+)$", spvasm, re.M)) - raw, = re.findall(r"= OpExtInst %float %glsl FClamp (%\w+) %\w+ %\w+$", spvasm, re.M) - env: dict[str, object] = {raw: _f32(lod), "%fhalf_g": 0.5} - - def ev(name: str): - if name in env: - return env[name] - e = defs[name].split() - op, args = e[0], e[2:] - if op == "OpConstant": - v = float(args[0]) if e[1] == "%float" else int(args[0], 0) - return v - (1 << 32) if e[1] == "%int" and v >= (1 << 31) else v - if op == "OpBitcast": - v = ev(args[0]) - if e[1] == "%float": - return _f32_bits(v & 0xFFFFFFFF) - return v if e[1] == "%int" else v & 0xFFFFFFFF - if op == "OpImageQueryLevels": - return levels - if op == "OpExtInst": - fn, a = args[1], [ev(x) for x in args[2:]] - out = { - "Floor": lambda: float(math.floor(a[0])), - "RoundEven": lambda: float(round(a[0])), - "FClamp": lambda: min(max(a[0], a[1]), a[2]), - "FMax": lambda: max(a), - "FMin": lambda: min(a), - "SMax": lambda: max(a), - "SMin": lambda: min(a), - "SClamp": lambda: min(max(a[0], a[1]), a[2]), - }[fn]() - return _f32(out) if isinstance(out, float) else out - a = [ev(x) for x in args] - return { - "OpFAdd": lambda: _f32(a[0] + a[1]), - "OpFSub": lambda: _f32(a[0] - a[1]), - "OpFMul": lambda: _f32(a[0] * a[1]), - "OpShiftRightArithmetic": lambda: a[0] >> a[1], - "OpIAdd": lambda: a[0] + a[1], - "OpISub": lambda: a[0] - a[1], - "OpConvertFToS": lambda: int(a[0]), - "OpFOrdGreaterThanEqual": lambda: a[0] >= a[1], - "OpSelect": lambda: a[1] if a[0] else a[2], - }[op]() - - level, = re.findall(r"= OpImageQuerySizeLod %v2int %\w+ (%\w+)$", spvasm, re.M) - return ev(level) - - -def _ps_shader(inst: str, s0_lit: int | None = 0x3092, runtime_s: bool = False, s1_lit: int = 0xc00000) -> list[str]: - lines = [ - "s_load_dwordx8 s[8:15], s[0:1], 0x0", - "s_waitcnt lgkmcnt(0)", - ] - if runtime_s: - lines += [ - "s_load_dwordx4 s[16:19], s[0:1], 0x20", - "s_waitcnt lgkmcnt(0)", - ] - else: - lines += [ - f"s_mov_b32 s16, {hex(s0_lit)}", - f"s_mov_b32 s17, {hex(s1_lit)}", - "s_mov_b32 s18, 0", - "s_mov_b32 s19, 0", - ] - lines += [ - "v_mov_b32_e32 v0, 0x0", - "v_mov_b32_e32 v1, 0.5", - "v_mov_b32_e32 v2, 0.5", - "v_mov_b32_e32 v3, 0.5", - "v_mov_b32_e32 v4, 0.5", - "v_mov_b32_e32 v5, 0.0", - "v_mov_b32_e32 v6, 0.0", - inst, - "s_waitcnt vmcnt(0)", - "exp mrt0 v8, v9, v10, v11 done vm", - "s_endpgm", - ] - return lines - - -def _cs_fssm() -> bytes: - blob = bytearray(0x148) - struct.pack_into("<4I", blob, 0x138, 0x8, 32, 1, 1) - return bytes(blob) - - -def _cs_shader(inst: str, s0_lit: int = 0x3092) -> list[str]: - return [ - "s_load_dwordx8 s[8:15], s[0:1], 0x0", - "s_waitcnt lgkmcnt(0)", - f"s_mov_b32 s16, {hex(s0_lit)}", - "s_mov_b32 s17, 0xc00000", - "s_mov_b32 s18, 0", - "s_mov_b32 s19, 0", - "v_mov_b32_e32 v0, 0x0", - "v_mov_b32_e32 v1, 0.5", - "v_mov_b32_e32 v2, 0.5", - "v_mov_b32_e32 v3, 0.5", - "v_mov_b32_e32 v4, 0.5", - "v_mov_b32_e32 v5, 0.0", - inst, - "s_waitcnt vmcnt(0)", - "s_endpgm", - ] - - -class TestImageGather4Variants(unittest.TestCase): - def test_no_overlap_with_pr_3201(self) -> None: - for op in PR_3201_OPS: - self.assertNotIn(op, rdna2spirv.Gen.GATHER4_LOD_OPS) - self.assertEqual(len(rdna2spirv.Gen.GATHER4_LOD_OPS), 14) - - def test_all_14_ops_2d_validate(self) -> None: - for op, vaddr_2d, _, _, _ in ALL_14_OPS: - with self.subTest(op=op, dim="2D"): - inst = f"{op} v[8:11], {vaddr_2d}, s[8:15], s[16:19] dmask:0x1 dim:SQ_RSRC_IMG_2D" - spv = support.translate_lines(f"ps_{op}_2d", _ps_shader(inst)) - _validate(spv) - self.assertIn("OpImageFetch", spv) - self.assertIn("OpCapability ImageQuery", spv) - if "_l" not in op: - self.assertIn("OpImageQueryLod %v2float", spv) - else: - self.assertNotIn("OpImageQueryLod", spv) - - def test_all_14_ops_2d_array_validate(self) -> None: - for op, _, vaddr_arr, _, _ in ALL_14_OPS: - with self.subTest(op=op, dim="2D_ARRAY"): - inst = f"{op} v[8:11], {vaddr_arr}, s[8:15], s[16:19] dmask:0x1 dim:SQ_RSRC_IMG_2D_ARRAY" - spv = support.translate_lines(f"ps_{op}_arr", _ps_shader(inst)) - _validate(spv) - self.assertIn("OpImageQuerySizeLod %v3int", spv) - self.assertIn("OpCompositeConstruct %v3int", spv) - - def test_all_14_ops_d16_validate(self) -> None: - for op, vaddr_2d, _, _, _ in ALL_14_OPS: - with self.subTest(op=op, d16=True): - inst = f"{op} v[8:9], {vaddr_2d}, s[8:15], s[16:19] dmask:0x1 dim:SQ_RSRC_IMG_2D d16" - spv = support.translate_lines(f"ps_{op}_d16", _ps_shader(inst)) - _validate(spv) - - def test_all_14_ops_a16_validate(self) -> None: - for op, _, _, vaddr_2d_a16, vaddr_arr_a16 in ALL_14_OPS: - with self.subTest(op=op, dim="2D", a16=True): - inst = f"{op} v[8:11], {vaddr_2d_a16}, s[8:15], s[16:19] dmask:0x1 dim:SQ_RSRC_IMG_2D a16" - spv = support.translate_lines(f"ps_{op}_a16", _ps_shader(inst)) - _validate(spv) - self.assertIn("UnpackHalf2x16", spv) - with self.subTest(op=op, dim="2D_ARRAY", a16=True): - inst = f"{op} v[8:11], {vaddr_arr_a16}, s[8:15], s[16:19] dmask:0x1 dim:SQ_RSRC_IMG_2D_ARRAY a16" - spv = support.translate_lines(f"ps_{op}_arr_a16", _ps_shader(inst)) - _validate(spv) - - def test_compute_stage_explicit_and_clamped(self) -> None: - cs_ops = ( - ("image_gather4_c_l", "v[0:3]"), - ("image_gather4_c_l_o", "v[0:4]"), - ("image_gather4_cl", "v[0:2]"), - ("image_gather4_cl_o", "v[0:3]"), - ("image_gather4_c_cl", "v[0:3]"), - ("image_gather4_c_cl_o", "v[0:4]"), - ) - for op, vaddr in cs_ops: - with self.subTest(op=op): - inst = f"{op} v[8:11], {vaddr}, s[8:15], s[16:19] dmask:0x1 dim:SQ_RSRC_IMG_2D" - spv = support.translate_lines(f"cs_{op}", _cs_shader(inst), fssm=_cs_fssm()) - _validate(spv) - self.assertNotIn("OpImageQueryLod", spv) - self.assertIn("OpImageFetch", spv) - - def test_compute_stage_rejects_biased(self) -> None: - for op, vaddr in (("image_gather4_b", "v[0:2]"), ("image_gather4_c_b_cl_o", "v[0:5]")): - with self.subTest(op=op): - inst = f"{op} v[8:11], {vaddr}, s[8:15], s[16:19] dmask:0x1 dim:SQ_RSRC_IMG_2D" - with self.assertRaises(rdna2spirv.Unsupported): - support.translate_lines(f"cs_{op}", _cs_shader(inst), fssm=_cs_fssm()) - - def test_all_8_depth_compare_funcs_literal_and_runtime(self) -> None: - expected_ops = { - 0: None, - 1: "OpFOrdLessThan %bool", - 2: "OpFOrdEqual %bool", - 3: "OpFOrdLessThanEqual %bool", - 4: "OpFOrdGreaterThan %bool", - 5: "OpFUnordNotEqual %bool", - 6: "OpFOrdGreaterThanEqual %bool", - 7: None, - } - inst = "image_gather4_c_l v[8:11], v[0:3], s[8:15], s[16:19] dmask:0x1 dim:SQ_RSRC_IMG_2D" - for func, spv_op in expected_ops.items(): - with self.subTest(depth_compare_func=func): - s0 = 0x92 | (func << 12) - spv = support.translate_lines(f"ps_cmp_{func}", _ps_shader(inst, s0_lit=s0)) - _validate(spv) - if spv_op is None: - self.assertNotIn("OpFOrdLessThan", spv) - self.assertNotIn("OpFOrdEqual", spv) - self.assertNotIn("OpFOrdGreaterThan", spv) - self.assertNotIn("OpFUnordNotEqual", spv) - else: - self.assertEqual(spv.count(spv_op), 4) - # Runtime S# decodes DEPTH_COMPARE_FUNC [14:12] dynamically - spv_rt = support.translate_lines("ps_cmp_rt", _ps_shader(inst, runtime_s=True)) - _validate(spv_rt) - self.assertIn("OpBitFieldUExtract %uint", spv_rt) - self.assertEqual(spv_rt.count("OpFOrdLessThan %bool"), 4) - self.assertEqual(spv_rt.count("OpFOrdEqual %bool"), 4) - self.assertEqual(spv_rt.count("OpFOrdGreaterThan %bool"), 4) - - def test_unorm_modifier(self) -> None: - for op, vaddr in (("image_gather4_c_l", "v[0:3]"), ("image_gather4_cl", "v[0:2]")): - with self.subTest(op=op): - inst = f"{op} v[8:11], {vaddr}, s[8:15], s[16:19] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm" - spv = support.translate_lines(f"ps_{op}_unorm", _ps_shader(inst)) - _validate(spv) - self.assertNotIn("OpFMul %v2float", spv) - - def test_dmask_channels_and_offset_extraction(self) -> None: - for ch, dmask in enumerate(("0x1", "0x2", "0x4", "0x8")): - with self.subTest(dmask=dmask): - inst = f"image_gather4_cl_o v[8:11], v[0:3], s[8:15], s[16:19] dmask:{dmask} dim:SQ_RSRC_IMG_2D" - spv = support.translate_lines(f"ps_cl_o_ch{ch}", _ps_shader(inst)) - _validate(spv) - self.assertIn("OpBitFieldSExtract %uint", spv) - self.assertIn(f"OpCompositeExtract %float", spv) - self.assertIn("OpExtInst %float %glsl FMax", spv) - - def test_border_modes_on_depth_compare_gather4(self) -> None: - # Mode 6 (clamp border) with opaque white (word3 [31:30] = 2) - inst = "image_gather4_c_l_o v[8:11], v[0:4], s[8:15], s[16:19] dmask:0x1 dim:SQ_RSRC_IMG_2D" - lines = _ps_shader(inst, s0_lit=0x3036) - lines = [ln.replace("s_mov_b32 s19, 0", "s_mov_b32 s19, 0x80000100") for ln in lines] - spv = support.translate_lines("ps_c_l_o_border", lines) - _validate(spv) - self.assertIn("OpSelect %float", spv) - - def test_explicit_lod_compare_mip_boundary_matches_rdna2(self) -> None: - # Both explicit-LOD depth-compare forms must match #4321's 8-fraction-bit LOD rounding - # (RoundEven(lod * 256) + 128) >> 8 so ordinary and compare gathers select the same mip - # at 0x3eff0000 (127.5/256) and 0x3eff0001 (mip 1) and one step below (0x3efeffff -> mip 0). - cases = ( - (0x100000, 0x3efeffff, 0), # one ULP below 127.5/256 -> mip 0 - (0x100000, 0x3eff0000, 1), # 127.5/256 -> rounds to 128/256 -> mip 1 - (0x100000, 0x3eff0001, 1), # one ULP above 127.5/256 -> mip 1 - (0x100000, 0x3f000000, 1), # 0.5 -> mip 1 - (0xfff000, 0x3fbfbfff, 1), # one ULP below 383.5/256 -> mip 1 - (0xfff000, 0x3fbfc000, 2), # 383.5/256 -> rounds to 384/256 -> mip 2 - (0xfff000, 0x3fc00000, 2), # 1.5 -> mip 2 - ) - for op, vaddr in (("image_gather4_c_l", "v[0:3]"), ("image_gather4_c_l_o", "v[0:4]")): - inst = f"{op} v[8:11], {vaddr}, s[8:15], s[16:19] dmask:0x1 dim:SQ_RSRC_IMG_2D" - for word1 in (0x100000, 0xfff000): - spv = support.translate_lines(f"ps_{op}_mip_{word1:x}", _ps_shader(inst, s1_lit=word1)) - _validate(spv) - self.assertNotRegex(spv, r"= OpFAdd %float %\w+ %fhalf_g") - self.assertRegex(spv, r"= OpExtInst %float %glsl RoundEven %\w+") - self.assertRegex(spv, r"= OpShiftRightArithmetic %int %\w+ %c8\b") - for w1, lod_bits, expected_mip in cases: - if w1 != word1: - continue - with self.subTest(op=op, word1=hex(word1), lod_bits=hex(lod_bits)): - self.assertEqual(_translated_gather_mip(spv, _f32_bits(lod_bits), 4), expected_mip) - - def test_ps_gather4_c_l_fixture_emits_dynamic_depth_compare(self) -> None: - # Guard against constant-folding S# word 0 in the GPU fixture's run-time S# case (G). - asm_path = os.path.join(ROOT, "runtime", "test", "shaders", "ps_gather4_c_l.asm") - with open(asm_path, "r", encoding="utf-8") as f: - lines = [ln.split(";")[0].strip() for ln in f if ln.split(";")[0].strip()] - spv = support.translate_lines("ps_gather4_c_l_fixture", lines) - _validate(spv) - self.assertRegex(spv, r"= OpBitFieldUExtract %uint %\w+ %cc %c3\b") - # Case G is the only case that emits OpFOrdEqual (4 taps) via the dynamic compare path. - self.assertEqual(spv.count("OpFOrdEqual %bool"), 4) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_image_sample_bias_nonps.py b/tests/semantic/test_image_sample_bias_nonps.py deleted file mode 100644 index aab97f6af..000000000 --- a/tests/semantic/test_image_sample_bias_nonps.py +++ /dev/null @@ -1,317 +0,0 @@ -"""Biased image_sample variants in non-PS stages (cs, vs, gs, ms). - -Covers all 8 RDNA2 biased sample opcodes: - - image_sample_b, image_sample_b_o, image_sample_b_cl, image_sample_b_cl_o - - image_sample_c_b, image_sample_c_b_o, image_sample_c_b_cl, image_sample_c_b_cl_o - -Outside a pixel shader there are no screen-space derivatives (implicit base LOD is 0), so -biased samples become explicit-LOD samples with `Lod = bias` (or `FMax(bias, minlod)` for -`_cl`). Pixel-shader behavior stays unchanged (`ImplicitLod` with `Bias` / `Bias|MinLod`). - -Standard library only (spirv-as/spirv-val and llvm-mc are used when available); no GPU, no -game files. -""" -import os -import re -import shutil -import struct -import subprocess -import sys -import tempfile -import unittest - -import support - -TOOLS_DIR = os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "..", "tools")) -if TOOLS_DIR not in sys.path: - sys.path.insert(0, TOOLS_DIR) - -import mc_command # noqa: E402 -import rdna2_decode # noqa: E402 - -DESC = "s[8:15], s[16:19]" -D2 = "dim:SQ_RSRC_IMG_2D" -PRO = [ - "v_mov_b32 v4, 1.0", - "v_mov_b32 v5, 0.5", - "v_mov_b32 v6, 0.25", - "v_mov_b32 v7, 0.75", - "v_mov_b32 v8, 0.125", - "v_mov_b32 v9, 0.0625", - "v_mov_b32 v10, 0", - "v_mov_b32 v11, 0", -] -CS_FSSM = bytearray(0x148) -struct.pack_into("<4I", CS_FSSM, 0x138, 0x8088, 32, 1, 1) -CS_FSSM = bytes(CS_FSSM) - - -def translate(name, line, *, texel_offset_fallback=False): - fssm = CS_FSSM if name.startswith("cs_") else None - body = PRO + [line] + (["exp mrt0 v0, v0, v0, v0 done vm"] if name.startswith("ps_") else []) + ["s_endpgm"] - prev = support.rdna2spirv.TEXEL_OFFSET_FALLBACK - support.rdna2spirv.TEXEL_OFFSET_FALLBACK = texel_offset_fallback - try: - return support.translate_lines(name, body, fssm=fssm) - finally: - support.rdna2spirv.TEXEL_OFFSET_FALLBACK = prev - - -def samples(spv): - return [ln.strip() for ln in spv.splitlines() if "= OpImageSample" in ln] - - -def source_vgpr(spv, value): - """The VGPR index `value` was loaded from (through bitcasts), or None.""" - consts = {k: int(v) for k, v in re.findall(r"^\s*(%\w+) = OpConstant %uint (\d+)", spv, re.M)} - for _ in range(8): - m = re.search(rf"^\s*{re.escape(value)} = (\w+) (?:%\w+ )?(%\w+)", spv, re.M) - if not m: - return None - op, src = m.groups() - if op == "OpLoad": - m2 = re.search(rf"^\s*{re.escape(src)} = OpAccessChain %\S+ %vgpr (%\w+)", spv, re.M) - return consts.get(m2.group(1)) if m2 else None - value = src - return None - - -def fmax_args(spv, value): - m = re.search(rf"^\s*{re.escape(value)} = OpExtInst %float %glsl FMax (%\w+) (%\w+)", spv, re.M) - return m.groups() if m else None - - -def spirv_validate(spv, *, allow_offset=False): - with tempfile.TemporaryDirectory() as tmp: - a, b = os.path.join(tmp, "m.spvasm"), os.path.join(tmp, "m.spv") - with open(a, "w", encoding="utf-8", newline="\n") as f: - f.write(spv) - subprocess.run(["spirv-as", "--target-env", "vulkan1.2", a, "-o", b], check=True) - cmd = ["spirv-val", "--target-env", "vulkan1.2"] - if allow_offset: - cmd.append("--allow-offset-texture-operand") - cmd.append(b) - subprocess.run(cmd, check=True) - - -def _llvm_mc(): - cmd = mc_command.mc_command() - try: - r = subprocess.run(cmd + ["-triple=amdgcn", "-mcpu=gfx1030", "-show-encoding"], - input="s_endpgm\n", capture_output=True, text=True, timeout=60) - except (OSError, subprocess.TimeoutExpired): - return None - return cmd if r.returncode == 0 and "encoding" in r.stdout else None - - -MC = _llvm_mc() - - -def assemble_gfx1030(lines): - r = subprocess.run(MC + ["-triple=amdgcn", "-mcpu=gfx1030", "-show-encoding"], - input="\n".join(lines) + "\n", capture_output=True, text=True, timeout=60) - if r.returncode != 0: - raise AssertionError(f"llvm-mc failed:\n{r.stderr}") - blob = bytearray() - for ln in r.stdout.splitlines(): - if "encoding: [" in ln: - body = ln.split("encoding: [", 1)[1].split("]", 1)[0] - blob.extend(int(b, 16) for b in body.split(",")) - return bytes(blob) - - -ALL_8_2D = [ - ("image_sample_b", "v[0:3]", "v[4:6]", 0xf, False, False, False), - ("image_sample_b_o", "v[0:3]", "v[4:7]", 0xf, False, True, False), - ("image_sample_b_cl", "v[0:3]", "v[4:7]", 0xf, False, False, True), - ("image_sample_b_cl_o", "v[0:3]", "v[4:8]", 0xf, False, True, True), - ("image_sample_c_b", "v0", "v[4:7]", 0x1, True, False, False), - ("image_sample_c_b_o", "v0", "v[4:8]", 0x1, True, True, False), - ("image_sample_c_b_cl", "v0", "v[4:8]", 0x1, True, False, True), - ("image_sample_c_b_cl_o", "v0", "v[4:9]", 0x1, True, True, True), -] - - -class NonPsBiasedSampleTests(unittest.TestCase): - def test_all_8_variants_in_cs_and_vs_emit_explicit_lod(self): - for stage in ("cs", "vs"): - for op, dst, regs, dmask, is_c, has_o, has_cl in ALL_8_2D: - with self.subTest(stage=stage, op=op): - spv = translate(f"{stage}_{op}", f"{op} {dst}, {regs}, {DESC} dmask:{dmask:#x} {D2}") - (s,) = samples(spv) - expected_op = "OpImageSampleDrefExplicitLod %float" if is_c else "OpImageSampleExplicitLod %v4float" - expected_mask = "Lod|Offset" if has_o else "Lod" - self.assertIn(expected_op, s) - self.assertIn(f" {expected_mask} ", s) - self.assertNotIn("Bias", s) - self.assertNotIn("MinLod", s) - - # Extract the Lod operand id (immediately after Lod or Lod|Offset) - m = re.search(rf" {re.escape(expected_mask)} (%\w+)", s) - self.assertIsNotNone(m, s) - lod_id = m.group(1) - - bias_vgpr = 5 if has_o else 4 - if has_cl: - args = fmax_args(spv, lod_id) - self.assertIsNotNone(args, f"expected FMax for {op}: {s}") - minlod_vgpr = bias_vgpr + (1 if is_c else 0) + 1 + 2 - self.assertEqual((source_vgpr(spv, args[0]), source_vgpr(spv, args[1])), - (bias_vgpr, minlod_vgpr)) - else: - self.assertEqual(source_vgpr(spv, lod_id), bias_vgpr) - - if is_c: - m_ref = re.search(r"OpImageSampleDrefExplicitLod %float %\w+ %\w+ (%\w+) ", s) - self.assertIsNotNone(m_ref, s) - self.assertEqual(source_vgpr(spv, m_ref.group(1)), bias_vgpr + 1) - - def test_ps_behavior_is_unchanged(self): - for op, dst, regs, dmask, is_c, has_o, has_cl in ALL_8_2D: - with self.subTest(op=op): - spv = translate(f"ps_{op}", f"{op} {dst}, {regs}, {DESC} dmask:{dmask:#x} {D2}") - (s,) = samples(spv) - expected_op = "OpImageSampleDrefImplicitLod %float" if is_c else "OpImageSampleImplicitLod %v4float" - masks = ["Bias"] - if has_o: - masks.append("Offset") - if has_cl: - masks.append("MinLod") - self.assertIn(expected_op, s) - self.assertIn(f" {'|'.join(masks)} ", s) - - def test_all_supported_dims(self): - # (dim_mod, ncoord, supports_dref) - dims = [ - ("dim:SQ_RSRC_IMG_1D", 1, True), - ("dim:SQ_RSRC_IMG_2D", 2, True), - ("dim:SQ_RSRC_IMG_2D_ARRAY", 3, True), - ("dim:SQ_RSRC_IMG_CUBE", 3, True), - ("dim:SQ_RSRC_IMG_3D", 3, False), - ] - for stage in ("cs", "vs"): - for dim_mod, ncoord, supports_dref in dims: - for is_c in (False, True): - if is_c and not supports_dref: - continue - for has_o in (False, True): - if has_o and "CUBE" in dim_mod: - continue - for has_cl in (False, True): - op = "image_sample" + ("_c" if is_c else "") + "_b" + ("_cl" if has_cl else "") + ("_o" if has_o else "") - naddr = (1 if has_o else 0) + 1 + (1 if is_c else 0) + ncoord + (1 if has_cl else 0) - regs = f"v[4:{4 + naddr - 1}]" - dst = "v0" if is_c else "v[0:3]" - dmask = 0x1 if is_c else 0xf - with self.subTest(stage=stage, op=op, dim=dim_mod): - spv = translate(f"{stage}_{op}", f"{op} {dst}, {regs}, {DESC} dmask:{dmask:#x} {dim_mod}") - (s,) = samples(spv) - self.assertIn("OpImageSampleDrefExplicitLod" if is_c else "OpImageSampleExplicitLod", s) - self.assertIn("Lod|Offset" if has_o else "Lod", s) - - def test_a16_and_d16_modifiers(self): - # 2D address VGPR counts under a16: offset(1), bias(1, low f16), ref(1, f32), uv(1), clamp(1, low f16) - a16_cases = [ - ("image_sample_b", "v[0:1]", "v[4:5]", 0xf, False, False, False), - ("image_sample_b_o", "v[0:1]", "v[4:6]", 0xf, False, True, False), - ("image_sample_b_cl", "v[0:1]", "v[4:6]", 0xf, False, False, True), - ("image_sample_b_cl_o", "v[0:1]", "v[4:7]", 0xf, False, True, True), - ("image_sample_c_b", "v0", "v[4:6]", 0x1, True, False, False), - ("image_sample_c_b_o", "v0", "v[4:7]", 0x1, True, True, False), - ("image_sample_c_b_cl", "v0", "v[4:7]", 0x1, True, False, True), - ("image_sample_c_b_cl_o", "v0", "v[4:8]", 0x1, True, True, True), - ] - for stage in ("cs", "vs"): - for op, dst, regs, dmask, is_c, has_o, has_cl in a16_cases: - with self.subTest(stage=stage, op=op): - spv = translate(f"{stage}_{op}_a16d16", - f"{op} {dst}, {regs}, {DESC} dmask:{dmask:#x} {D2} a16 d16") - (s,) = samples(spv) - self.assertIn("OpImageSampleDrefExplicitLod" if is_c else "OpImageSampleExplicitLod", s) - self.assertIn("UnpackHalf2x16", spv) - # d16 uses integer f16_bits / pack_f16_pair_int (never PackHalf2x16, #489) - self.assertNotIn("PackHalf2x16", spv) - if not is_c: - self.assertIn("OpShiftLeftLogical %uint", spv) - - def test_texel_offset_fallback_folds_at_bias_lod(self): - cases = [c for c in ALL_8_2D if c[5]] # all 4 _o variants - for stage in ("cs", "vs"): - for op, dst, regs, dmask, is_c, _has_o, has_cl in cases: - with self.subTest(stage=stage, op=op): - spv = translate(f"{stage}_{op}_fb", - f"{op} {dst}, {regs}, {DESC} dmask:{dmask:#x} {D2}", - texel_offset_fallback=True) - (s,) = samples(spv) - self.assertIn("OpImageSampleDrefExplicitLod" if is_c else "OpImageSampleExplicitLod", s) - self.assertNotIn("Offset", s) - self.assertNotIn("OpImageQueryLod", spv) - self.assertNotIn("OpDPdx", spv) - self.assertNotIn("Exp2", spv) - self.assertIn("OpImageQuerySizeLod", spv) - # Floor() in texel_offset_fold must consume bias_lod (not constant 0) - m_lod = re.search(r" Lod (%\w+)$", s) - self.assertIsNotNone(m_lod, s) - lod_id = m_lod.group(1) - self.assertIn(f"Floor {lod_id}", spv) - if has_cl: - self.assertIsNotNone(fmax_args(spv, lod_id)) - - @unittest.skipUnless(shutil.which("spirv-as") and shutil.which("spirv-val"), - "needs spirv-as and spirv-val on PATH") - def test_spirv_val_all_variants_stages_dims_and_fallback(self): - for stage in ("cs", "vs"): - for op, dst, regs, dmask, is_c, has_o, has_cl in ALL_8_2D: - with self.subTest(stage=stage, op=op, mode="direct"): - spv = translate(f"{stage}_val_{op}", f"{op} {dst}, {regs}, {DESC} dmask:{dmask:#x} {D2}") - spirv_validate(spv, allow_offset=has_o) - if has_o: - with self.subTest(stage=stage, op=op, mode="fallback"): - spv = translate(f"{stage}_valfb_{op}", f"{op} {dst}, {regs}, {DESC} dmask:{dmask:#x} {D2}", - texel_offset_fallback=True) - spirv_validate(spv, allow_offset=False) - - # Spot-check other dims + a16 + d16 in spirv-val - extra = [ - ("image_sample_b", "v[0:3]", "v[4:5]", 0xf, "dim:SQ_RSRC_IMG_1D", False), - ("image_sample_b_cl", "v[0:3]", "v[4:8]", 0xf, "dim:SQ_RSRC_IMG_2D_ARRAY", False), - ("image_sample_b", "v[0:3]", "v[4:7]", 0xf, "dim:SQ_RSRC_IMG_CUBE", False), - ("image_sample_b_cl_o", "v[0:3]", "v[4:9]", 0xf, "dim:SQ_RSRC_IMG_3D", True), - ("image_sample_c_b", "v0", "v[4:6]", 0x1, "dim:SQ_RSRC_IMG_1D", False), - ("image_sample_c_b_cl", "v0", "v[4:9]", 0x1, "dim:SQ_RSRC_IMG_2D_ARRAY", False), - ("image_sample_c_b", "v0", "v[4:8]", 0x1, "dim:SQ_RSRC_IMG_CUBE", False), - ("image_sample_b_cl_o", "v[0:1]", "v[4:7]", 0xf, "dim:SQ_RSRC_IMG_2D a16 d16", True), - ("image_sample_c_b_cl_o", "v0", "v[4:8]", 0x1, "dim:SQ_RSRC_IMG_2D a16 d16", True), - ] - for op, dst, regs, dmask, mods, has_o in extra: - with self.subTest(stage=stage, op=op, mods=mods): - spv = translate(f"{stage}_valx_{op}", f"{op} {dst}, {regs}, {DESC} dmask:{dmask:#x} {mods}") - spirv_validate(spv, allow_offset=has_o) - - @unittest.skipUnless(MC, "needs llvm-mc with AMDGPU gfx1030 target (set LLVM_MC)") - def test_llvm_mc_gfx1030_binary_decode_roundtrip(self): - for stage in ("cs", "vs"): - for op, dst, regs, dmask, is_c, has_o, has_cl in ALL_8_2D: - with self.subTest(stage=stage, op=op): - asm_lines = PRO + [ - f"{op} {dst}, {regs}, {DESC} dmask:{dmask:#x} {D2}", - "s_endpgm", - ] - blob = assemble_gfx1030(asm_lines) - decoded, unknown = rdna2_decode.disasm_bytes(blob) - self.assertEqual(unknown, 0, decoded) - self.assertIn(op, decoded) - decoded_lines = [ln for ln in decoded.splitlines() if ln.strip() and not ln.strip().startswith(";")] - fssm = CS_FSSM if stage == "cs" else None - spv = support.translate_lines(f"{stage}_rt_{op}", decoded_lines, fssm=fssm) - (s,) = samples(spv) - self.assertIn("OpImageSampleDrefExplicitLod" if is_c else "OpImageSampleExplicitLod", s) - self.assertIn("Lod|Offset" if has_o else "Lod", s) - if has_cl: - self.assertIn("FMax", spv) - if shutil.which("spirv-as") and shutil.which("spirv-val"): - spirv_validate(spv, allow_offset=has_o) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_image_store_d16.py b/tests/semantic/test_image_store_d16.py deleted file mode 100644 index 3a105d53c..000000000 --- a/tests/semantic/test_image_store_d16.py +++ /dev/null @@ -1,365 +0,0 @@ -"""Semantic and validation tests for RDNA2 image_store with d16 (packed 16-bit data VGPRs). - -Covers FSPX/FSR4 blocker `image_store 2D a16 d16` and all supported STORE_DIMS (1D, 2D, -2D_ARRAY, 3D), with and without a16 / glc, across full and sparse dmasks (0x0..0xf): - - Float/norm view: IEEE binary16 halves widened via UnpackHalf2x16 -> %v4float. - - UINT view: 16-bit unsigned halves zero-extended via OpBitFieldUExtract -> %v4uint_st. - - SINT view: 16-bit signed halves sign-extended via OpBitFieldSExtract -> %v4int_st. - - Missing dmask components default to 0. - - Executes the translated unpacking and coordinate extraction IR in spirv_mini_interp - to assert bit-exact texel values and unpacked a16 coordinates, plus spirv-val Vulkan 1.2 - (native and --wave64-emulate). -""" -import json -import os -import re -import shutil -import struct -import subprocess -import sys -import tempfile -import unittest - -ROOT = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) -TOOLS = os.path.join(ROOT, "tools") -SEMANTIC = os.path.dirname(os.path.abspath(__file__)) -for _p in (TOOLS, SEMANTIC): - if _p not in sys.path: - sys.path.insert(0, _p) - -import rdna2spirv # noqa: E402 -import spirv_mini_interp as si # noqa: E402 -import support # noqa: E402 - -SPIRV_AS = shutil.which("spirv-as") -SPIRV_VAL = shutil.which("spirv-val") - - -def _f16_bits(val: float) -> int: - return struct.unpack(" int: - return struct.unpack(" int: - return (lo & 0xFFFF) | ((hi & 0xFFFF) << 16) - - -def _validate(spvasm: str) -> None: - if not (SPIRV_AS and SPIRV_VAL): - return - with tempfile.TemporaryDirectory() as d: - sa, sv = os.path.join(d, "m.spvasm"), os.path.join(d, "m.spv") - with open(sa, "w", encoding="utf-8", newline="\n") as f: - f.write(spvasm) - for cmd in ( - [SPIRV_AS, sa, "-o", sv, "--target-env", "vulkan1.2"], - [SPIRV_VAL, "--target-env", "vulkan1.2", "--allow-offset-texture-operand", sv], - ): - r = subprocess.run(cmd, capture_output=True, text=True) - if r.returncode != 0: - raise AssertionError(f"{cmd[0]} failed:\n{r.stderr}") - - -def _eval_image_store_texels(setup_lines: list[str], store_line: str) -> dict[str, tuple[int, ...]]: - """Translate setup + image_store via rdna2spirv, cut right after the three texel - OpCompositeConstructs (and coordinate construct), and execute in spirv_mini_interp. - - Returns {"float": (u32, ...), "uint": (u32, ...), "sint": (u32, ...), "coords": (u32, ...)}. - """ - spv = support.translate_lines( - "ps_img_store_d16_eval", - setup_lines + [store_line, "exp mrt0 v0, v0, v0, v0 done vm", "s_endpgm"], - ) - _validate(spv) - - lines = spv.splitlines() - # Find the OpCompositeConstruct lines for %v4float, %v4uint_st, %v4int_st and coords (%v2int/%v3int) - # emitted by image_store, plus the first OpSelectionMerge (which starts the active/view branch). - v4f = v4u = v4s = coord_id = None - coord_ty = None - cut_idx = None - for idx, ln in enumerate(lines): - m = re.match(r"\s*(%\w+)\s*=\s*OpCompositeConstruct\s+(%\w+)\s+(.*)$", ln) - if m: - res, ty, _ = m.groups() - if ty in ("%v2int", "%v3int"): - coord_id, coord_ty = res, ty - elif ty == "%v4float": - v4f = res - elif ty == "%v4uint_st": - v4u = res - elif ty == "%v4int_st": - v4s = res - cut_idx = idx + 1 - break - assert v4f and v4u and v4s and cut_idx is not None, "image_store texel constructs not found" - - # Build a small runnable fragment ending right after v4s, writing each vector to an Output. - # For 1D coords (no %v2int/%v3int), capture the %int operand of the first OpImageWrite instead. - if coord_id is None: - for ln in lines[cut_idx:]: - m = re.match(r"\s*OpImageWrite\s+%\w+\s+(%\w+)\s+", ln) - if m: - coord_id = m.group(1) - coord_ty = "%int" - break - - # Extract header up to %main = OpFunction, add four Output vars, and emit stores at cut_idx. - out_decls = [ - "%_ptr_Out_f = OpTypePointer Output %v4float", - "%_ptr_Out_u = OpTypePointer Output %v4uint_st", - "%_ptr_Out_s = OpTypePointer Output %v4int_st", - f"%_ptr_Out_c = OpTypePointer Output {coord_ty}", - "%cap_f = OpVariable %_ptr_Out_f Output", - "%cap_u = OpVariable %_ptr_Out_u Output", - "%cap_s = OpVariable %_ptr_Out_s Output", - "%cap_c = OpVariable %_ptr_Out_c Output", - ] - fn_idx = next(i for i, ln in enumerate(lines) if " = OpFunction " in ln) - # Strip bindless/image OpVariables and OpDecorate/OpEntryPoint lines irrelevant to the mini-interp, - # keeping all types/constants and the function prefix up to cut_idx. - prefix = [] - skip_hdr = ( - "OpTypeImage", "OpTypeSampledImage", "OpTypeSampler", "OpTypeRuntimeArray", "UniformConstant", - "StorageBuffer", "Private", "OpConstantComposite", "%stv", "%stimg", "%desc", "%t_desc", - "%images", "%samplers", "%itx", "DescriptorSet", "Binding", "RuntimeDescriptorArray", - "StorageImage", "NonUniform", - ) - for ln in lines[:fn_idx]: - if re.search(r"OpEntryPoint ", ln): - prefix.append('OpEntryPoint Fragment %main "main" %cap_f %cap_u %cap_s %cap_c') - elif any(tok in ln for tok in skip_hdr): - continue - else: - prefix.append(ln) - body = lines[fn_idx:cut_idx] + [ - f"OpStore %cap_f {v4f}", - f"OpStore %cap_u {v4u}", - f"OpStore %cap_s {v4s}", - f"OpStore %cap_c {coord_id}", - "OpReturn", - "OpFunctionEnd", - ] - # Remove any OpLoad/OpAccessChain to %desc_tbl (only used for idx, never feeds v4f/v4u/v4s/coords) - # by seeding a dummy memory in spirv_mini_interp? Actually %desc_tbl is UniformConstant/StorageBuffer; - # filter out instructions in body whose results are not needed by v4f/v4u/v4s/coord_id. - mini_spv = "\n".join(prefix + out_decls + body) + "\n" - - # Strip desc_lookup_sgpr instructions that read %desc_tbl (not needed for texel/coord evaluation). - # Those live strictly between coords and v4f; remove lines referencing %desc_tbl or %t_desc or %user_data - # that aren't dependencies of v4f/v4u/v4s/coord_id. - def _prune_to_targets(src_lines: list[str], fn_start: int, targets: set[str]) -> str: - header = src_lines[:fn_start] - fn_lines = src_lines[fn_start:] - # Keep OpFunction, OpLabel, OpVariable, OpStore to %vgpr/%sgpr/%cap_*, and backward deps of targets. - needed = set(targets) - keep_idx: set[int] = set() - for i in range(len(fn_lines) - 1, -1, -1): - s = fn_lines[i].split(";", 1)[0].strip() - toks = s.split() - if not toks: - continue - if len(toks) >= 3 and toks[1] == "=": - res, op, args = toks[0], toks[2], toks[3:] - else: - res, op, args = None, toks[0], toks[1:] - if op in ("OpFunction", "OpLabel", "OpVariable", "OpReturn", "OpFunctionEnd"): - keep_idx.add(i) - continue - if op == "OpStore" and args and ( - args[0].startswith("%cap_") or "%vgpr" in fn_lines[i] - ): - keep_idx.add(i) - needed.update(t for t in args if t.startswith("%")) - continue - # Also keep OpStore into %vgpr pointers - if op == "OpStore": - # Check if ptr traces back to %vgpr - keep_idx.add(i) - needed.update(t for t in args if t.startswith("%")) - continue - if res in needed: - keep_idx.add(i) - needed.update(t for t in args if t.startswith("%")) - # Drop any OpStore that feeds %sgpr from %user_data (not needed here) - pruned_fn = [] - for i, ln in enumerate(fn_lines): - if i in keep_idx and "%desc_tbl" not in ln and "%user_data" not in ln and "%ud" not in ln: - pruned_fn.append(ln) - return "\n".join(header + pruned_fn) + "\n" - - pruned = _prune_to_targets( - prefix + out_decls + body, - len(prefix + out_decls), - {v4f, v4u, v4s, coord_id}, - ) - outs = si.run_fragment(pruned) - - def _as_words(v): - if isinstance(v, tuple): - return tuple(x & 0xFFFFFFFF for x in v) - return (v & 0xFFFFFFFF,) - - return { - "float": _as_words(outs["%cap_f"]), - "uint": _as_words(outs["%cap_u"]), - "sint": _as_words(outs["%cap_s"]), - "coords": _as_words(outs["%cap_c"]), - } - - -class ImageStoreD16Tests(unittest.TestCase): - def test_rgba_d16_a16_float_uint_sint_values_exact(self): - # FSPX pattern: image_store 2D a16 d16 with full dmask:0xf (2 packed VGPRs: v[4:5], 1 coord VGPR: v2). - # Test positive/negative normals, subnormal, negative integer (sign-extended in SINT, zero-extended in UINT). - lo0 = _f16_bits(1.5) # 0x3E00 - hi0 = _f16_bits(-2.25) # 0xC080 -> u16 49280, i16 -16256 (0xFFFFC080) - lo1 = 0xFFFF # f16 NaN (checked via u16/i16), u16 65535, i16 -1 (0xFFFFFFFF) - hi1 = 0x8000 # f16 -0.0 (0x80000000), u16 32768, i16 -32768 (0xFFFF8000) - w0 = _pack_u16(lo0, hi0) - w1 = _pack_u16(lo1, hi1) - coord_packed = _pack_u16(17, 42) - got = _eval_image_store_texels( - [ - f"v_mov_b32_e32 v4, 0x{w0:08x}", - f"v_mov_b32_e32 v5, 0x{w1:08x}", - f"v_mov_b32_e32 v2, 0x{coord_packed:08x}", - ], - "image_store v[4:5], v2, s[8:15] dmask:0xf dim:SQ_RSRC_IMG_2D unorm a16 d16", - ) - self.assertEqual(got["coords"], (17, 42)) - self.assertEqual(got["float"][0], _f32_bits(1.5)) - self.assertEqual(got["float"][1], _f32_bits(-2.25)) - self.assertEqual(got["float"][3], 0x80000000) # -0.0 - self.assertEqual(got["uint"], (lo0, hi0, lo1, hi1)) - self.assertEqual(got["sint"], (0x00003E00, 0xFFFFC080, 0xFFFFFFFF, 0xFFFF8000)) - - def test_sparse_dmasks_pack_enabled_components_consecutively(self): - # dmask:0x9 (R and A): both halves packed in a SINGLE VGPR v4 (R = low 16, A = high 16); G=B=0. - w_ra = _pack_u16(_f16_bits(0.5), _f16_bits(-4.0)) - got_ra = _eval_image_store_texels( - [ - f"v_mov_b32_e32 v4, 0x{w_ra:08x}", - "v_mov_b32_e32 v2, 3", - "v_mov_b32_e32 v3, 9", - ], - "image_store v4, v[2:3], s[8:15] dmask:0x9 dim:SQ_RSRC_IMG_2D unorm d16", - ) - self.assertEqual(got_ra["coords"], (3, 9)) - self.assertEqual(got_ra["float"], (_f32_bits(0.5), 0, 0, _f32_bits(-4.0))) - self.assertEqual(got_ra["uint"], (_f16_bits(0.5), 0, 0, _f16_bits(-4.0))) - self.assertEqual(got_ra["sint"], (0x00003800, 0, 0, 0xFFFFC400)) - - # dmask:0x7 (R, G, B): 2 VGPRs v[4:5] -> R=v4.lo, G=v4.hi, B=v5.lo, A=0. - w0 = _pack_u16(0x0007, 0xFFFE) # +7, -2 - w1 = _pack_u16(0x8001, 0x1234) # -32767 (high half 0x1234 unused!) - got_rgb = _eval_image_store_texels( - [ - f"v_mov_b32_e32 v4, 0x{w0:08x}", - f"v_mov_b32_e32 v5, 0x{w1:08x}", - "v_mov_b32_e32 v2, 1", - "v_mov_b32_e32 v3, 2", - ], - "image_store v[4:5], v[2:3], s[8:15] dmask:0x7 dim:SQ_RSRC_IMG_2D unorm d16", - ) - self.assertEqual(got_rgb["uint"], (0x0007, 0xFFFE, 0x8001, 0)) - self.assertEqual(got_rgb["sint"], (0x00000007, 0xFFFFFFFE, 0xFFFF8001, 0)) - - # dmask:0x4 (B only): 1 VGPR v4 -> B=v4.lo, R=G=A=0. - got_b = _eval_image_store_texels( - [ - "v_mov_b32_e32 v4, 0x12343c00", - "v_mov_b32_e32 v2, 5", - ], - "image_store v4, v2, s[8:15] dmask:0x4 dim:SQ_RSRC_IMG_1D unorm d16", - ) - self.assertEqual(got_b["coords"], (5,)) - self.assertEqual(got_b["float"], (0, 0, _f32_bits(1.0), 0)) - self.assertEqual(got_b["uint"], (0, 0, 0x3C00, 0)) - - def test_all_store_dims_a16_glc_and_wave64_emulate_validate(self): - cases = [ - ("1D", "v2", "dmask:0x1", "d16"), - ("2D", "v2", "dmask:0xf", "a16 d16"), - ("2D", "v[2:3]", "dmask:0x3", "glc d16"), - ("2D_ARRAY", "v[2:3]", "dmask:0xf", "a16 d16"), - ("3D", "v[2:4]", "dmask:0x7", "glc d16"), - ("2D", "v2", "dmask:0x0", "a16 d16"), - ] - for dim, addr, dmask, extra in cases: - with self.subTest(dim=dim, dmask=dmask, extra=extra): - spv = support.translate_lines( - f"ps_img_d16_{dim.lower()}", - [ - "v_mov_b32_e32 v2, 0", - "v_mov_b32_e32 v3, 0", - "v_mov_b32_e32 v4, 0", - "v_mov_b32_e32 v5, 0", - f"image_store v[4:5], {addr}, s[8:15] {dmask} dim:SQ_RSRC_IMG_{dim} unorm {extra}", - "exp mrt0 v4, v4, v4, v4 done vm", - "s_endpgm", - ], - ) - _validate(spv) - self.assertIn("OpImageWrite", spv) - if "glc" in extra: - self.assertIn("Coherent", spv) - - # Also validate a wave64 compute shader under --wave64-emulate (FSPX compute path). - with tempfile.TemporaryDirectory() as d: - os.makedirs(os.path.join(d, "disasm")) - os.makedirs(os.path.join(d, "fspx")) - s_path = os.path.join(d, "disasm", "cs_img_store_d16.s") - with open(s_path, "w", encoding="utf-8", newline="\n") as f: - f.write("; cs_img_store_d16 code 0x0..0x40, gfx1013, 0 invalid words\n") - for ln in ( - "s_mov_b64 s[16:17], exec", - "v_mov_b32_e32 v2, 0x00020001", - "v_mov_b32_e32 v4, 0x40003c00", - "v_mov_b32_e32 v5, 0x44004200", - "image_store v[4:5], v2, s[8:15] dmask:0xf dim:SQ_RSRC_IMG_2D unorm a16 d16", - "s_endpgm", - ): - f.write(f"\t{ln} ; encoding: [0x00,0x00,0x00,0x00]\n") - with open(os.path.join(d, "fspx", "cs_img_store_d16.json"), "w", encoding="utf-8", newline="\n") as f: - json.dump({"rsrc2": (16 << 1), "threads": [64, 1, 1]}, f) - old_w64 = rdna2spirv.WAVE64_EMULATE - try: - rdna2spirv.WAVE64_EMULATE = True - spv = rdna2spirv.translate(s_path) - finally: - rdna2spirv.WAVE64_EMULATE = old_w64 - _validate(spv) - - def test_cube_storage_image_d16_translates(self): - # Cube storage images are supported and bound as 6-layer 2D arrays (#6805) - spv = support.translate_lines( - "ps_img_store_cube_d16", - [ - "v_mov_b32_e32 v2, 0", - "image_store v[4:5], v[2:4], s[8:15] dmask:0xf dim:SQ_RSRC_IMG_CUBE unorm d16", - "exp mrt0 v2, v2, v2, v2 done vm", - "s_endpgm", - ], - ) - _validate(spv) - - def test_unsupported_dims_and_modifiers_still_refused(self): - for bad in ( - "image_store v[4:5], v[2:4], s[8:15] dmask:0xf dim:SQ_RSRC_IMG_1D_ARRAY unorm d16", - "image_store v[4:5], v2, s[8:15] dmask:0xf dim:SQ_RSRC_IMG_2D unorm d16 tfe", - "image_store v[4:5], v2, s[8:15] dmask:0xf dim:SQ_RSRC_IMG_2D unorm d16 lwe", - ): - with self.subTest(bad=bad): - with self.assertRaises(rdna2spirv.Unsupported): - support.translate_lines( - "ps_img_d16_bad", - ["v_mov_b32_e32 v2, 0", bad, "exp mrt0 v2, v2, v2, v2 done vm", "s_endpgm"], - ) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_image_store_dmask.py b/tests/semantic/test_image_store_dmask.py deleted file mode 100644 index 6d34e0561..000000000 --- a/tests/semantic/test_image_store_dmask.py +++ /dev/null @@ -1,358 +0,0 @@ -"""image_store dmask and format encoding: channel packing, sparse writes, and descriptor format decoding. - -RDNA2 ISA, MIMG DMASK: for writes, which components are written with data from VGPRs; enabled components come -from consecutive VGPRs (DMASK = 1001: red in VGPRn, alpha in VGPRn+1). docs/design.md "Typed image stores": -"writes the dmask components (missing ones = 0)". - -Covers: - - 256-bit AMD RDNA2 / GFX10 Image Resource Descriptor (T#) decoding and format bitfield [28:20] - - Reference oracle for 4-bit dmask component assignment and VGPR popcount packing - - Sparse target memory writes where unmasked channels retain their previous state - - Numeric format classification: *_UINT -> uint view, *_SINT -> sint view, otherwise -> float view - - Verification of SPIR-V code generation across all 16 dmask permutations -""" -from __future__ import annotations - -import os -import sys -import unittest - -HERE = os.path.dirname(os.path.abspath(__file__)) -TOOLS_DIR = os.environ.get("LEONIDA_TOOLS_DIR") or os.path.join(os.path.dirname(os.path.dirname(HERE)), "tools") -sys.dont_write_bytecode = True -if TOOLS_DIR not in sys.path: - sys.path.insert(0, TOOLS_DIR) - -import rdna2spirv # noqa: E402 -from shader_ir import parse_line # noqa: E402 - -MASK4 = 0xF -MASK9 = 0x1FF -MASK13 = 0x1FFF -MASK14 = 0x3FFF -MASK16 = 0xFFFF -MASK32 = 0xFFFFFFFF - - -class ImageResourceDescriptor: - """256-bit AMD RDNA2 / GFX10 Image Resource Descriptor (T#, 8 SGPRs).""" - - def __init__( - self, - d0: int = 0, - d1: int = 0, - d2: int = 0, - d3: int = 0, - d4: int = 0, - d5: int = 0, - d6: int = 0, - d7: int = 0, - ) -> None: - self.d0 = d0 & MASK32 - self.d1 = d1 & MASK32 - self.d2 = d2 & MASK32 - self.d3 = d3 & MASK32 - self.d4 = d4 & MASK32 - self.d5 = d5 & MASK32 - self.d6 = d6 & MASK32 - self.d7 = d7 & MASK32 - - @classmethod - def from_fields( - cls, - base_address: int = 0, - width: int = 1, - height: int = 1, - depth: int = 1, - format_code: int = 0, - min_lod: int = 0, - ) -> ImageResourceDescriptor: - d0 = base_address & MASK32 - base_hi = (base_address >> 32) & MASK16 - lod_field = (min_lod & 0xF) << 16 - fmt_field = (format_code & MASK9) << 20 - d1 = base_hi | lod_field | fmt_field - w_enc = max(0, width - 1) & MASK14 - h_enc = max(0, height - 1) & MASK14 - d2 = w_enc | (h_enc << 16) - d_enc = max(0, depth - 1) & MASK13 - d3 = d_enc - return cls(d0, d1, d2, d3, 0, 0, 0, 0) - - @property - def base_lo(self) -> int: - return self.d0 - - @property - def base_hi(self) -> int: - return self.d1 & MASK16 - - @property - def format_code(self) -> int: - return (self.d1 >> 20) & MASK9 - - @property - def format_name(self) -> str: - return rdna2spirv.GFX10_FORMATS.get(self.format_code, "UNKNOWN") - - @property - def is_uint(self) -> bool: - return self.format_name.endswith("_UINT") - - @property - def is_sint(self) -> bool: - return self.format_name.endswith("_SINT") - - @property - def is_float(self) -> bool: - return not (self.is_uint or self.is_sint) - - @property - def numeric_class(self) -> int: - if self.is_sint: - return 2 - if self.is_uint: - return 1 - return 0 - - @property - def width(self) -> int: - return (self.d2 & MASK14) + 1 - - @property - def height(self) -> int: - return ((self.d2 >> 16) & MASK14) + 1 - - @property - def depth(self) -> int: - return (self.d3 & MASK13) + 1 - - def as_words(self) -> tuple[int, int, int, int, int, int, int, int]: - return (self.d0, self.d1, self.d2, self.d3, self.d4, self.d5, self.d6, self.d7) - - -class ImageStoreOracle: - """Semantic reference oracle for RDNA2 image store operations.""" - - def __init__(self, surface: dict[tuple[int, ...], list[int]] | None = None) -> None: - self.surface = {} if surface is None else dict(surface) - - @staticmethod - def popcount(dmask: int) -> int: - return bin(dmask & MASK4).count("1") - - @classmethod - def unpack_source_vgprs(cls, vdata_base: int, dmask: int, vgprs: dict[int, int] | list[int]) -> list[int]: - """Maps enabled channels to consecutive source VGPRs, missing channels to 0.""" - reg_idx = vdata_base - texel = [0, 0, 0, 0] - for c in range(4): - if (dmask >> c) & 1: - val = vgprs[reg_idx] if isinstance(vgprs, (list, tuple)) else vgprs.get(reg_idx, 0) - texel[c] = val & MASK32 - reg_idx += 1 - else: - texel[c] = 0 - return texel - - @classmethod - def get_source_vgpr_indices(cls, vdata_base: int, dmask: int) -> list[int]: - """Returns the list of source VGPR register numbers read by an image_store instruction.""" - indices = [] - cur = vdata_base - for c in range(4): - if (dmask >> c) & 1: - indices.append(cur) - cur += 1 - return indices - - def store_sparse( - self, - coord: tuple[int, ...], - vdata_base: int, - dmask: int, - vgprs: dict[int, int] | list[int], - default_texel: list[int] | None = None, - ) -> list[int]: - """Applies sparse write: only channels enabled in dmask are updated in target surface.""" - if coord not in self.surface: - self.surface[coord] = list(default_texel) if default_texel is not None else [0, 0, 0, 0] - cur = self.surface[coord] - reg_idx = vdata_base - for c in range(4): - if (dmask >> c) & 1: - val = vgprs[reg_idx] if isinstance(vgprs, (list, tuple)) else vgprs.get(reg_idx, 0) - cur[c] = val & MASK32 - reg_idx += 1 - return list(cur) - - -def texels(line: str) -> dict[str, list[int | None]]: - """Analyzes Gen.image_store output and returns texel components for float, uint, and sint views.""" - ins = parse_line(line) - g = rdna2spirv.Gen("cs") - dim = next(m for m in ins["mods"] if m.startswith("dim:")) - g.image_store(ins["args"], ins["mods"], dim) - consts = {name: value for value, name in g.consts.items()} - src: dict[str, tuple[str, int]] = {} - out: dict[str, list[int | None]] = {} - for line_ in g.body: - w = line_.split() - if len(w) < 5 or w[1] != "=": - continue - res, op, ty, args = w[0], w[2], w[3], w[4:] - if op == "OpAccessChain" and args[0] == "%vgpr": - src[res] = ("p", consts[args[1]]) - elif op == "OpLoad" and src.get(args[0], (None,))[0] == "p": - src[res] = ("v", src[args[0]][1]) - elif op == "OpBitcast" and args[0] in src: - src[res] = src[args[0]] - elif op == "OpBitcast" and args[0] in consts: - consts[res] = consts[args[0]] - elif op == "OpCompositeConstruct" and ty in ("%v4float", "%v4uint_st", "%v4int_st"): - out[ty] = [src[x][1] if x in src and src[x][0] == "v" else consts.get(x) for x in args] - return out - - -class ImageStoreDmask(unittest.TestCase): - def check(self, line: str, want: list[int | None]) -> None: - got = texels(line) - self.assertEqual(len(got), 3) - for ty, t in got.items(): - with self.subTest(view=ty): - self.assertEqual(t, want) - - def test_full_mask(self) -> None: - self.check("image_store v[4:7], v[0:1], s[8:15] dmask:0xf dim:SQ_RSRC_IMG_2D unorm", [4, 5, 6, 7]) - - def test_low_mask(self) -> None: - self.check("image_store v[4:5], v[0:1], s[8:15] dmask:0x3 dim:SQ_RSRC_IMG_2D unorm", [4, 5, 0, 0]) - - def test_blue_only(self) -> None: - self.check("image_store v4, v[0:1], s[8:15] dmask:0x4 dim:SQ_RSRC_IMG_2D unorm", [0, 0, 4, 0]) - - def test_red_and_alpha(self) -> None: - self.check("image_store v[4:5], v[0:1], s[8:15] dmask:0x9 dim:SQ_RSRC_IMG_2D unorm", [4, 0, 0, 5]) - - def test_empty_mask(self) -> None: - self.check("image_store v4, v[0:1], s[8:15] dmask:0x0 dim:SQ_RSRC_IMG_2D unorm", [0, 0, 0, 0]) - - -class TestImageResourceDescriptor(unittest.TestCase): - def test_descriptor_fields_packing(self) -> None: - desc = ImageResourceDescriptor.from_fields( - base_address=0x123456789ABC, - width=1920, - height=1080, - depth=64, - format_code=5, # GFX10_FORMAT_8_UINT - min_lod=2, - ) - self.assertEqual(desc.width, 1920) - self.assertEqual(desc.height, 1080) - self.assertEqual(desc.depth, 64) - self.assertEqual(desc.format_code, 5) - self.assertEqual(desc.format_name, "GFX10_FORMAT_8_UINT") - self.assertTrue(desc.is_uint) - self.assertFalse(desc.is_sint) - self.assertFalse(desc.is_float) - self.assertEqual(desc.numeric_class, 1) - - def test_descriptor_sint_format(self) -> None: - desc = ImageResourceDescriptor.from_fields(format_code=6) # GFX10_FORMAT_8_SINT - self.assertEqual(desc.format_name, "GFX10_FORMAT_8_SINT") - self.assertFalse(desc.is_uint) - self.assertTrue(desc.is_sint) - self.assertFalse(desc.is_float) - self.assertEqual(desc.numeric_class, 2) - - def test_descriptor_float_format(self) -> None: - desc = ImageResourceDescriptor.from_fields(format_code=1) # GFX10_FORMAT_8_UNORM - self.assertEqual(desc.format_name, "GFX10_FORMAT_8_UNORM") - self.assertFalse(desc.is_uint) - self.assertFalse(desc.is_sint) - self.assertTrue(desc.is_float) - self.assertEqual(desc.numeric_class, 0) - - def test_descriptor_words_length(self) -> None: - desc = ImageResourceDescriptor() - words = desc.as_words() - self.assertEqual(len(words), 8) - self.assertTrue(all(isinstance(w, int) for w in words)) - - -class TestImageStoreChannelMasking(unittest.TestCase): - def test_all_16_dmask_permutations_oracle(self) -> None: - oracle = ImageStoreOracle() - vdata_base = 10 - vgprs = {10: 0x1111, 11: 0x2222, 12: 0x3333, 13: 0x4444} - for dmask in range(16): - with self.subTest(dmask=hex(dmask)): - pop = oracle.popcount(dmask) - indices = oracle.get_source_vgpr_indices(vdata_base, dmask) - self.assertEqual(len(indices), pop) - if pop > 0: - self.assertEqual(indices, list(range(vdata_base, vdata_base + pop))) - texel = oracle.unpack_source_vgprs(vdata_base, dmask, vgprs) - for c in range(4): - if (dmask >> c) & 1: - self.assertNotEqual(texel[c], 0) - else: - self.assertEqual(texel[c], 0) - - def test_sparse_channel_write_retention(self) -> None: - oracle = ImageStoreOracle() - coord = (10, 20) - oracle.surface[coord] = [0xAA, 0xBB, 0xCC, 0xDD] - - # Store only channel G (dmask 0x2) - oracle.store_sparse(coord, vdata_base=0, dmask=0x2, vgprs={0: 0x99}) - self.assertEqual(oracle.surface[coord], [0xAA, 0x99, 0xCC, 0xDD]) - - # Store channels R and A (dmask 0x9) - oracle.store_sparse(coord, vdata_base=4, dmask=0x9, vgprs={4: 0x11, 5: 0x44}) - self.assertEqual(oracle.surface[coord], [0x11, 0x99, 0xCC, 0x44]) - - # Store channels G and B (dmask 0x6) - oracle.store_sparse(coord, vdata_base=2, dmask=0x6, vgprs={2: 0x77, 3: 0x88}) - self.assertEqual(oracle.surface[coord], [0x11, 0x77, 0x88, 0x44]) - - def test_all_16_dmasks_in_spirv_gen(self) -> None: - for dmask in range(16): - with self.subTest(dmask=hex(dmask)): - pop = ImageStoreOracle.popcount(dmask) - vdata = f"v[{10}:{10 + max(0, pop - 1)}]" if pop > 1 else f"v{10}" - line = f"image_store {vdata}, v[0:1], s[8:15] dmask:{hex(dmask)} dim:SQ_RSRC_IMG_2D unorm" - got = texels(line) - self.assertIn("%v4float", got) - self.assertIn("%v4uint_st", got) - self.assertIn("%v4int_st", got) - reg = 10 - expected = [] - for c in range(4): - if (dmask >> c) & 1: - expected.append(reg) - reg += 1 - else: - expected.append(0) - for ty in ("%v4float", "%v4uint_st", "%v4int_st"): - self.assertEqual(got[ty], expected) - - -class TestImageStoreFormatEncoding(unittest.TestCase): - def test_format_masks_constants(self) -> None: - u_masks, si_masks = rdna2spirv.Gen.int_format_masks() - self.assertEqual(len(u_masks), 16) - self.assertEqual(len(si_masks), 16) - # Check that GFX10_FORMAT_8_UINT (code 5) is recorded in uint mask - word_idx = 5 >> 5 - bit_idx = 5 & 31 - self.assertTrue(bool((u_masks[word_idx] >> bit_idx) & 1)) - # Check that GFX10_FORMAT_8_SINT (code 6) is recorded in sint mask - word_idx = 6 >> 5 - bit_idx = 6 & 31 - self.assertTrue(bool((si_masks[word_idx] >> bit_idx) & 1)) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_insn_no_operands.py b/tests/semantic/test_insn_no_operands.py deleted file mode 100644 index 4a1849f33..000000000 --- a/tests/semantic/test_insn_no_operands.py +++ /dev/null @@ -1,75 +0,0 @@ -"""A disassembly line with no operands is a rejection, not a translator error. - -LLVM always prints an instruction's operands, so a bare line (`v_add_f32`) can only come from a -hand-written or corrupted listing. The first operand read used to surface as IndexError, which the -CLI reports as "translator error IndexError" and a broad `assertRaises(Exception)` negative control -accepts as if it were a deliberate rejection. Gen.insn now raises Unsupported(": no operands") -instead, so index.json names the offending instruction. Operands that are merely the wrong kind or -count still raise what they raised before, and genuinely operand-free instructions (s_endpgm, v_nop, -v_clrexcp, ds_nop, s_barrier in compute) are unaffected: they never fail an operand read, so no -IndexError is raised to convert. - - python -I tests/semantic/test_insn_no_operands.py - -Standard library only: no GPU, no LLVM, no game data. -""" -import os -import sys -import unittest - -sys.dont_write_bytecode = True -sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) -import support # noqa: E402 -from rdna2spirv import Unsupported # noqa: E402 - -END = ["exp mrt0 v0, v0, v0, v0 done vm", "s_endpgm"] - - -class NoOperandLines(unittest.TestCase): - def test_operandless_lines_raise_unsupported(self): - # One line per operand-list read site: plain, _sdwa (rewritten args), _dpp (dpp_insn), - # v_cmpx (a None-padded source slot, which used to be a TypeError), and branches/exports. - # Each must be Unsupported; several have a rejection of their own (DPP control, branch - # without encoding). The point is that none reaches a bare IndexError or TypeError. - for line in ("v_add_f32", "v_mov_b32", "v_lshrrev_b64", "v_add_f32_sdwa", - "v_add_f32_dpp", "v_cmpx_ne_f32", "s_mov_b32", "s_branch", - "ds_add_u32", "image_load"): - with self.subTest(line=line): - try: - support.translate_lines("ps_no_operand", [line] + END) - except Unsupported: - pass - except Exception as e: - self.fail(f"{line}: operand-less line raised {type(e).__name__}, not Unsupported") - else: - self.fail(f"{line}: operand-less line translated") - - def test_message_names_the_instruction(self): - # index.json counts rejections by message; the bare line must name itself, not - # "translator error IndexError". - try: - support.translate_lines("ps_no_operand", ["v_add_f32"] + END) - except Unsupported as e: - self.assertEqual(str(e), "v_add_f32: no operands") - else: - self.fail("v_add_f32 without operands must be rejected") - - def test_operandless_ok_ops_still_pass(self): - # Ops printed without operands by LLVM itself must keep translating. - for line in ("v_nop", "v_clrexcp", "ds_nop"): - with self.subTest(line=line): - self.assertIn("OpEntryPoint", support.translate_lines("ps_no_operand", [line] + END)) - - def test_operandless_s_barrier_still_reaches_its_check(self): - # s_barrier legitimately has no operands; in a pixel shader it is rejected by its own rule, - # proving the no-operands conversion did not swallow it earlier. - try: - support.translate_lines("ps_no_operand", ["s_barrier"] + END) - except Unsupported as e: - self.assertEqual(str(e), "s_barrier outside compute") - else: - self.fail("s_barrier in a pixel shader must stay Unsupported") - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_int32_to_f64.py b/tests/semantic/test_int32_to_f64.py deleted file mode 100644 index f8079dddf..000000000 --- a/tests/semantic/test_int32_to_f64.py +++ /dev/null @@ -1,83 +0,0 @@ -"""Exact binary64 conversion of 32-bit signed and unsigned register values.""" -import re -import shutil -import struct -import subprocess -import tempfile -import unittest -from pathlib import Path -from unittest.mock import patch - -from support import translate_fixture, translate_lines -import rdna2spirv -import spirv_interface - - -class Int32ToFloat64(unittest.TestCase): - @unittest.skipUnless(all(shutil.which(t) for t in ("spirv-as", "spirv-opt", "spirv-dis")), "needs SPIRV-Tools") - def test_constant_folded_mrt_words(self): - # Integer-to-double is exact. Float controls can prevent optimizers folding even these constants. - default = translate_fixture("ps_int32_to_f64") - with patch.object(rdna2spirv, "FLOAT_CONTROLS", False): - foldable = translate_fixture("ps_int32_to_f64") - float_controls = { - "OpCapability SignedZeroInfNanPreserve", "OpCapability DenormPreserve", - "OpExecutionMode %main SignedZeroInfNanPreserve 32", "OpExecutionMode %main DenormPreserve 16", - # SHADER-597 (#3290): a module that declares Float64 also preserves f64 signed zeros, infs and NaNs - "OpExecutionMode %main SignedZeroInfNanPreserve 64", - } - self.assertTrue(float_controls.issubset(line.strip() for line in default.splitlines())) - self.assertEqual([line for line in default.splitlines() if line.strip() not in float_controls], - foldable.splitlines()) - with tempfile.TemporaryDirectory() as tmp: - binary, folded = Path(tmp) / "int32.spv", Path(tmp) / "folded.spv" - subprocess.run(["spirv-as", "--target-env", "vulkan1.2", "-o", binary, "-"], - input=foldable, text=True, check=True) - subprocess.run(["spirv-opt", "-O", binary, "-o", folded], check=True) - listing = subprocess.check_output(["spirv-dis", "--raw-id", folded], text=True) - stored, = re.findall(r"OpStore %\d+ (%\d+)", listing) - components, = re.findall(rf"{stored} = OpConstantComposite %\d+ ((?:%\d+ ){{3}}%\d+)", listing) - # Read constant payloads directly to preserve every bit of the exported float channels. - words = spirv_interface.parse_words(folded.read_bytes()) - constants = {args[1]: args[2] for op, args, _ in spirv_interface.instructions(words) - if op == spirv_interface.OP_CONSTANT} - actual = tuple(constants[int(c[1:])] for c in components.split()) - expected = struct.unpack("<4I", struct.pack("<2d", -2147483647, 2147483649)) - self.assertEqual(actual, expected) - - def test_signed_and_unsigned_conversion_reach_both_destination_words(self): - text = translate_fixture("ps_int32_to_f64") - for opcode, first in (("OpConvertSToF", 4), ("OpConvertUToF", 6)): - with self.subTest(opcode=opcode): - value, = re.findall(rf"(%\w+) = {opcode} %double ", text) - pair, = re.findall(rf"(%\w+) = OpBitcast %v2uint_d {value}\b", text) - for i in range(2): - word, = re.findall(rf"(%\w+) = OpCompositeExtract %uint {pair} {i}\b", text) - sel = re.findall(rf"(%\w+) = OpSelect %uint %\w+ {word} %\w+", text) - selected, = sel or [word] - pointer, = re.findall(rf"OpStore (%\w+) {selected}\b", text) - self.assertIn(f"{pointer} = OpAccessChain %_ptr_Function_uint %vgpr %c{first + i}\n", text) - - def test_vop3_clamps_the_double_and_ignores_the_scaling(self): - # Measured on gfx1036 through tools/hw_oracle (wave32 and wave64 identical on every case, - # tools/f64_omod_probe.py): a binary64 destination ignores mul:2/mul:4/div:2 while - # denorm_mode_16_64 = 3, the MODE the translator assumes, and clamp still saturates. - # See docs/design.md, "32-bit integers to binary64". - for suffix, opcode in (("i32", "OpConvertSToF"), ("u32", "OpConvertUToF")): - with self.subTest(suffix=suffix): - text = translate_lines("ps_int32_to_f64_mods", [ - "v_mov_b32 v4, 3", - f"v_cvt_f64_{suffix}_e64 v[4:5], v4 clamp div:2", - "exp mrt0 v4, v5, v4, v5 done vm", "s_endpgm", - ]) - value, = re.findall(rf"(%\w+) = {opcode} %double ", text) - self.assertNotIn("OpFMul %double", text) - clamped, = re.findall(rf"(%\w+) = OpExtInst %double %glsl FClamp {value} ", text) - self.assertIn(f"OpBitcast %v2uint_d {clamped}\n", text) - omod_only = translate_lines("ps_int32_to_f64_omod", [ - "v_mov_b32 v4, 3", - f"v_cvt_f64_{suffix}_e64 v[4:5], v4 mul:2", - "exp mrt0 v4, v5, v4, v5 done vm", "s_endpgm", - ]) - self.assertNotRegex(omod_only, r"OpFMul %double") - self.assertNotIn("FClamp", omod_only) diff --git a/tests/semantic/test_int32_valu_validation.py b/tests/semantic/test_int32_valu_validation.py deleted file mode 100644 index 46306a16d..000000000 --- a/tests/semantic/test_int32_valu_validation.py +++ /dev/null @@ -1,324 +0,0 @@ -"""Validation and semantic tests for 8 32-bit integer 2-source VALU ops in tools/rdna2spirv.py. - -Covers: - VOP3-only: v_mul_lo_u32, v_mul_hi_u32, v_mul_hi_i32, v_bcnt_u32_b32 - VOP2/VOP3: v_min_u32, v_max_u32, v_min_i32, v_max_i32 - -Verifies that invalid destinations (non-VGPR / multi-VGPR), multi-register sources, -operand modifiers (neg/abs/sext where illegal), instruction modifiers (clamp, mul:*, -div:*, op_sel:*, unknown), unsupported _dpp/_sdwa forms, and wrong arity raise -rdna2spirv.Unsupported, while valid forms (including plain negative integer immediates -and valid _sdwa/_dpp on VOP2 min/max) assemble, pass spirv-val --target-env vulkan1.2, -and match reference semantics in spirv_mini_interp. -""" -import gc -import os -import shutil -import struct -import subprocess -import sys -import tempfile -import unittest -import warnings - -HERE = os.path.dirname(os.path.abspath(__file__)) -ROOT = os.path.dirname(os.path.dirname(HERE)) -TOOLS_DIR = os.environ.get("LEONIDA_TOOLS_DIR") or os.path.join(ROOT, "tools") - -sys.dont_write_bytecode = True -if TOOLS_DIR not in sys.path: - sys.path.insert(0, TOOLS_DIR) -if HERE not in sys.path: - sys.path.insert(0, HERE) - -import rdna2spirv # noqa: E402 -import spirv_mini_interp as si # noqa: E402 - -MASK32 = 0xFFFFFFFF -STUB_DXBC = b"DXBC" + bytes(24) + struct.pack(" str: - if _TMP_DIR is None: - setUpModule() - asm = "; test_int32_valu_validation\n" + "".join(f"\t{ln}\n" for ln in lines) + "\ts_endpgm\n" - with open(_SRC_PATH, "w", encoding="utf-8", newline="\n") as f: - f.write(asm) - with warnings.catch_warnings(): - warnings.simplefilter("ignore", ResourceWarning) - return rdna2spirv.translate(_SRC_PATH) - - -def validate_spirv(spvasm: str) -> None: - if not SPIRV_AS or not SPIRV_VAL: - raise unittest.SkipTest("spirv-as / spirv-val not found on PATH") - spvasm_path = os.path.join(_TMP_DIR.name, "check.spvasm") - spv_path = os.path.join(_TMP_DIR.name, "check.spv") - with open(spvasm_path, "w", encoding="utf-8", newline="\n") as f: - f.write(spvasm) - res_as = subprocess.run( - [SPIRV_AS, "--target-env", "vulkan1.2", spvasm_path, "-o", spv_path], - capture_output=True, - text=True, - ) - if res_as.returncode != 0: - raise AssertionError(f"spirv-as failed:\n{res_as.stderr}") - res_val = subprocess.run( - [SPIRV_VAL, "--target-env", "vulkan1.2", spv_path], - capture_output=True, - text=True, - ) - if res_val.returncode != 0: - raise AssertionError(f"spirv-val failed:\n{res_val.stderr}") - - -def run_mrt0(lines, regs=("v0", "v0", "v0", "v0"), *, validate=True) -> list[int]: - spv = translate_lines(list(lines) + [f"exp mrt0 {', '.join(regs)} done vm"]) - if validate: - validate_spirv(spv) - return list(si.run_fragment(spv)["%out_mrt0"]) - - -def s32(x: int) -> int: - v = x & MASK32 - return v - (1 << 32) if (v & 0x80000000) else v - - -def ref_op(op: str, x: int, y: int) -> int: - ux, uy = x & MASK32, y & MASK32 - if op == "v_mul_lo_u32": - return (ux * uy) & MASK32 - if op == "v_mul_hi_u32": - return ((ux * uy) >> 32) & MASK32 - if op == "v_mul_hi_i32": - return ((s32(ux) * s32(uy)) >> 32) & MASK32 - if op == "v_min_u32": - return min(ux, uy) - if op == "v_max_u32": - return max(ux, uy) - if op == "v_min_i32": - return min(s32(ux), s32(uy)) & MASK32 - if op == "v_max_i32": - return max(s32(ux), s32(uy)) & MASK32 - if op == "v_bcnt_u32_b32": - return (ux.bit_count() + uy) & MASK32 - raise ValueError(f"unknown op {op!r}") - - -class Int32ValuNegativeValidationTests(unittest.TestCase): - """Invalid destinations, operand widths, operand/instruction modifiers, forms, and arity.""" - - def _assert_unsupported(self, body_lines): - lines = [ - "v_mov_b32 v0, 1", - "v_mov_b32 v1, 2", - "v_mov_b32 v2, 3", - "v_mov_b32 v3, 4", - "s_mov_b32 s0, 5", - "s_mov_b32 s1, 6", - "s_mov_b32 s2, 7", - "s_mov_b32 s3, 8", - *body_lines, - "exp mrt0 v0, v0, v0, v0 done vm", - ] - with self.assertRaises(rdna2spirv.Unsupported): - translate_lines(lines) - - def test_non_vgpr_destinations_rejected(self): - bad_dsts = ("s0", "vcc_lo", "null", "exec_lo", "m0") - for op in ALL_OPS: - for dst in bad_dsts: - with self.subTest(op=op, dst=dst): - self._assert_unsupported([f"{op} {dst}, v1, v2"]) - - def test_multi_register_destinations_rejected(self): - for op in ALL_OPS: - for dst in ("v[0:1]", "s[0:1]"): - with self.subTest(op=op, dst=dst): - self._assert_unsupported([f"{op} {dst}, v1, v2"]) - - def test_multi_register_sources_rejected(self): - for op in ALL_OPS: - for args in ("v0, v[1:2], v3", "v0, v1, v[2:3]", "v0, s[2:3], v1", "v0, v1, s[2:3]"): - with self.subTest(op=op, args=args): - self._assert_unsupported([f"{op} {args}"]) - - def test_operand_neg_abs_sext_rejected_on_plain_form(self): - bad_arg_lists = ( - "-v0, v1, v2", - "|v0|, v1, v2", - "sext(v0), v1, v2", - "v0, -v1, v2", - "v0, |v1|, v2", - "v0, abs(v1), v2", - "v0, sext(v1), v2", - "v0, v1, -v2", - "v0, v1, |v2|", - "v0, v1, abs(v2)", - "v0, v1, sext(v2)", - "v0, neg(1), v2", - "v0, abs(1), v2", - "v0, v1, neg(2)", - ) - for op in ALL_OPS: - for args in bad_arg_lists: - with self.subTest(op=op, args=args): - self._assert_unsupported([f"{op} {args}"]) - - def test_instruction_modifiers_rejected_on_plain_and_e64(self): - bad_mods = ("clamp", "mul:2", "mul:4", "div:2", "op_sel:[1,0,0]", "bogus_mod") - for op in ALL_OPS: - for suffix in ("", "_e64"): - for mod in bad_mods: - with self.subTest(op=op + suffix, mod=mod): - self._assert_unsupported([f"{op}{suffix} v0, v1, v2 {mod}"]) - - def test_vop3_only_rejects_dpp_and_sdwa(self): - for op in VOP3_ONLY_OPS: - with self.subTest(op=op, form="_dpp"): - self._assert_unsupported([f"{op}_dpp v0, v1, v2 quad_perm:[1,0,3,2] row_mask:0xf bank_mask:0xf"]) - with self.subTest(op=op, form="_sdwa"): - self._assert_unsupported([ - f"{op}_sdwa v0, v1, v2 dst_sel:DWORD dst_unused:UNUSED_PAD src0_sel:DWORD src1_sel:DWORD" - ]) - - def test_minmax_sdwa_rejects_bad_mods_and_operand_mods(self): - for op in VOP2_MINMAX_OPS: - bad_cases = ( - f"{op}_sdwa s0, v1, v2 dst_sel:DWORD dst_unused:UNUSED_PAD src0_sel:DWORD src1_sel:DWORD", - f"{op}_sdwa v0, v1, v2 dst_sel:DWORD clamp", - f"{op}_sdwa v0, v1, v2 dst_sel:DWORD mul:2", - f"{op}_sdwa v0, v1, v2 dst_sel:DWORD div:2", - f"{op}_sdwa v0, v1, v2 dst_sel:DWORD op_sel:[0,0,0]", - f"{op}_sdwa v0, v1, v2 dst_sel:DWORD bogus_mod", - f"{op}_sdwa v0, v1, v2 dst_sel:BAD", - f"{op}_sdwa v0, v1, v2 dst_unused:BAD", - f"{op}_sdwa sext(v0), v1, v2 dst_sel:DWORD src0_sel:BYTE_0 src1_sel:BYTE_0", - f"{op}_sdwa v0, -v1, v2 dst_sel:DWORD src0_sel:BYTE_0 src1_sel:BYTE_0", - f"{op}_sdwa v0, |v1|, v2 dst_sel:DWORD src0_sel:BYTE_0 src1_sel:BYTE_0", - f"{op}_sdwa v0, v1, -v2 dst_sel:DWORD src0_sel:BYTE_0 src1_sel:BYTE_0", - f"{op}_sdwa v0, v1, |v2| dst_sel:DWORD src0_sel:BYTE_0 src1_sel:BYTE_0", - ) - for insn in bad_cases: - with self.subTest(insn=insn): - self._assert_unsupported([insn]) - - def test_minmax_dpp_rejects_non_dpp_mods_and_operand_mods(self): - for op in VOP2_MINMAX_OPS: - bad_cases = ( - f"{op}_dpp s0, v1, v2 quad_perm:[1,0,3,2] row_mask:0xf bank_mask:0xf", - f"{op}_dpp v0, v1, v2 quad_perm:[1,0,3,2] clamp", - f"{op}_dpp v0, v1, v2 quad_perm:[1,0,3,2] mul:2", - f"{op}_dpp v0, v1, v2 quad_perm:[1,0,3,2] div:2", - f"{op}_dpp v0, v1, v2 quad_perm:[1,0,3,2] op_sel:[0,0,0]", - f"{op}_dpp v0, v1, v2 quad_perm:[1,0,3,2] bogus_mod", - f"{op}_dpp v0, -v1, v2 quad_perm:[1,0,3,2]", - f"{op}_dpp v0, |v1|, v2 quad_perm:[1,0,3,2]", - f"{op}_dpp v0, sext(v1), v2 quad_perm:[1,0,3,2]", - f"{op}_dpp v0, v1, -v2 quad_perm:[1,0,3,2]", - f"{op}_dpp v0, v1, |v2| quad_perm:[1,0,3,2]", - f"{op}_dpp v0, v1, sext(v2) quad_perm:[1,0,3,2]", - f"{op}_dpp v0, v1, v[2:3] quad_perm:[1,0,3,2]", - ) - for insn in bad_cases: - with self.subTest(insn=insn): - self._assert_unsupported([insn]) - - def test_wrong_arity_rejected(self): - for op in ALL_OPS: - for insn in ( - op, - f"{op} v0", - f"{op} v0, v1", - f"{op} v0, v1, v2, v3", - ): - with self.subTest(insn=insn): - self._assert_unsupported([insn]) - - -class Int32ValuPositiveControlTests(unittest.TestCase): - """Positive controls verified with spirv-as, spirv-val --target-env vulkan1.2, and spirv_mini_interp.""" - - def test_all_eight_ops_vgpr_and_negative_immediate(self): - x = 0x80000013 - y = 0xFFFFFFF9 # -7 - for op in ALL_OPS: - with self.subTest(op=op): - got_vv, got_neg_imm, got_e64, _ = run_mrt0([ - f"v_mov_b32 v1, {x:#x}", - f"v_mov_b32 v2, {y:#x}", - f"{op} v10, v1, v2", - f"{op} v11, -7, v1", - f"{op}_e64 v12, v1, -7", - "v_mov_b32 v13, 0", - ], ("v10", "v11", "v12", "v13")) - self.assertEqual(got_vv, ref_op(op, x, y)) - self.assertEqual(got_neg_imm, ref_op(op, y, x)) - self.assertEqual(got_e64, ref_op(op, x, y)) - - def test_minmax_sdwa_positive_controls(self): - v1 = 0x8001007F - v2 = 0x0002FFFE - words = run_mrt0([ - f"v_mov_b32 v1, {v1:#x}", - f"v_mov_b32 v2, {v2:#x}", - "v_min_i32_sdwa v10, sext(v1), sext(v2) dst_sel:DWORD dst_unused:UNUSED_PAD src0_sel:BYTE_3 src1_sel:BYTE_0", - "v_max_i32_sdwa v11, sext(v1), sext(v2) dst_sel:DWORD dst_unused:UNUSED_PAD src0_sel:BYTE_3 src1_sel:BYTE_0", - "v_min_u32_sdwa v12, v1, v2 dst_sel:DWORD dst_unused:UNUSED_PAD src0_sel:BYTE_3 src1_sel:BYTE_0", - "v_max_u32_sdwa v13, v1, v2 dst_sel:DWORD dst_unused:UNUSED_PAD src0_sel:BYTE_3 src1_sel:BYTE_0", - ], ("v10", "v11", "v12", "v13")) - self.assertEqual(words, [0xFFFFFF80, 0xFFFFFFFE, 0x00000080, 0x000000FE]) - - def test_minmax_dpp_positive_controls_validate(self): - for op in VOP2_MINMAX_OPS: - with self.subTest(op=op): - spv = translate_lines([ - "v_mov_b32 v1, 0x12345678", - "v_mov_b32 v2, 0x87654321", - f"{op}_dpp v0, v1, v2 quad_perm:[1,0,3,2] row_mask:0xf bank_mask:0xf", - "exp mrt0 v0, v0, v0, v0 done vm", - ]) - validate_spirv(spv) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_int_compares.py b/tests/semantic/test_int_compares.py deleted file mode 100644 index 5a9b78bfa..000000000 --- a/tests/semantic/test_int_compares.py +++ /dev/null @@ -1,147 +0,0 @@ -"""Semantic interpreter tests for RDNA2 integer compares: v_cmp_{eq,ne,lt,le,gt,ge}_{u16,i16,u32,i32,u64,i64} -(e32 into VCC and e64 into an SGPR pair, read back with v_cndmask_b32) and s_cmp_{eq,lg,lt,le,gt,ge}_{u32,i32}, -s_cmp_{eq,lg}_u64 (SCC, read back with s_cselect_b32). - -Each case translates a synthetic pixel shader with tools/rdna2spirv.py, runs it in tests/semantic/spirv_mini_interp.py -and compares the result with Python's own comparison of the operands, read at the instruction's width and signedness -(16-bit compares ignore the high half of each 32-bit source). -""" -import itertools -import os -import struct -import sys -import tempfile -import unittest -import warnings - -HERE = os.path.dirname(os.path.abspath(__file__)) -ROOT = os.path.dirname(os.path.dirname(HERE)) -TOOLS_DIR = os.environ.get("LEONIDA_TOOLS_DIR") or os.path.join(ROOT, "tools") - -sys.dont_write_bytecode = True -sys.path.insert(0, TOOLS_DIR) -sys.path.insert(0, HERE) - -import rdna2spirv # noqa: E402 -import spirv_mini_interp as si # noqa: E402 - -MASK32 = 0xFFFFFFFF -STUB_DXBC = b"DXBC" + bytes(24) + struct.pack(" y, "ge": lambda x, y: x >= y, -} - - -def as_type(value: int, ty: str) -> int: - bits = int(ty[1:]) - value &= (1 << bits) - 1 - if ty[0] == "i" and value >> (bits - 1): - value -= 1 << bits - return value - - -# Operand pairs at the sign and width boundaries of each type. 32-bit pairs carry high-half noise so the 16-bit -# compares must ignore it. -PAIRS32 = [(0, 0), (1, 2), (2, 1), (0x7FFFFFFF, 0x80000000), (0x80000000, 0x7FFFFFFF), (0xFFFFFFFF, 0), - (0, 0xFFFFFFFF), (0x12347FFF, 0xABCD8000), (0xABCD8000, 0x12347FFF), (0xFFFF0001, 0x00010001)] -PAIRS64 = [(0, 0), (1, 1 << 32), (1 << 32, 1), (0x7FFFFFFFFFFFFFFF, 0x8000000000000000), - (0x8000000000000000, 0x7FFFFFFFFFFFFFFF), ((1 << 64) - 1, 0), (0xFFFFFFFF, 0x100000000), - (0x1234567800000000, 0x1234567800000000)] - -_TMP_DIR = None -_SRC_PATH = None - - -def setUpModule(): - global _TMP_DIR, _SRC_PATH - _TMP_DIR = tempfile.TemporaryDirectory() - disasm_dir = os.path.join(_TMP_DIR.name, "disasm") - os.mkdir(disasm_dir) - _SRC_PATH = os.path.join(disasm_dir, "ps_cmp.s") - with open(os.path.join(_TMP_DIR.name, "ps_cmp.dxbc"), "wb") as f: - f.write(STUB_DXBC) - - -def tearDownModule(): - global _TMP_DIR - if _TMP_DIR is not None: - _TMP_DIR.cleanup() - _TMP_DIR = None - - -def run_lines(lines) -> int: - if _TMP_DIR is None: - setUpModule() - asm = "; test_int_compares\n" + "".join(f"\t{ln}\n" for ln in lines) + "\texp mrt0 v0, v0, v0, v0 done vm\n\ts_endpgm\n" - with open(_SRC_PATH, "w", encoding="utf-8") as f: - f.write(asm) - with warnings.catch_warnings(): - warnings.simplefilter("ignore", ResourceWarning) - spv = rdna2spirv.translate(_SRC_PATH) - return si.run_fragment(spv)["%out_mrt0"][0] - - -def v_cmp32(op: str, x: int, y: int, form: str) -> int: - lines = [f"v_mov_b32 v2, {x:#x}", f"v_mov_b32 v3, {y:#x}"] - if form == "e32": - lines += [f"{op}_e32 vcc_lo, v2, v3", "v_cndmask_b32_e32 v0, 0, 1, vcc_lo"] - else: - lines += [f"{op}_e64 s4, v2, v3", "v_cndmask_b32_e64 v0, 0, 1, s4"] - return run_lines(lines) - - -def v_cmp64(op: str, x: int, y: int) -> int: - return run_lines([f"v_mov_b32 v2, {x & MASK32:#x}", f"v_mov_b32 v3, {x >> 32:#x}", - f"v_mov_b32 v4, {y & MASK32:#x}", f"v_mov_b32 v5, {y >> 32:#x}", - f"{op}_e64 s4, v[2:3], v[4:5]", "v_cndmask_b32_e64 v0, 0, 1, s4"]) - - -def s_cmp(op: str, x: int, y: int, wide: bool = False) -> int: - if wide: - lines = [f"s_mov_b32 s2, {x & MASK32:#x}", f"s_mov_b32 s3, {x >> 32:#x}", - f"s_mov_b32 s4, {y & MASK32:#x}", f"s_mov_b32 s5, {y >> 32:#x}", f"{op} s[2:3], s[4:5]"] - else: - lines = [f"s_mov_b32 s2, {x:#x}", f"s_mov_b32 s3, {y:#x}", f"{op} s2, s3"] - return run_lines(lines + ["s_cselect_b32 s0, 1, 0", "v_mov_b32 v0, s0"]) - - -class VectorCompares(unittest.TestCase): - def test_16_and_32_bit(self): - for rel, ty, form in itertools.product(("eq", "ne", "lt", "le", "gt", "ge"), ("u16", "i16", "u32", "i32"), - ("e32", "e64")): - op = f"v_cmp_{rel}_{ty}" - for x, y in PAIRS32: - with self.subTest(op=op, form=form, x=hex(x), y=hex(y)): - want = int(RELATIONS[rel](as_type(x, ty), as_type(y, ty))) - self.assertEqual(v_cmp32(op, x, y, form), want) - - def test_64_bit(self): - for rel, ty in itertools.product(("eq", "ne", "lt", "le", "gt", "ge"), ("u64", "i64")): - op = f"v_cmp_{rel}_{ty}" - for x, y in PAIRS64: - with self.subTest(op=op, x=hex(x), y=hex(y)): - want = int(RELATIONS[rel](as_type(x, ty), as_type(y, ty))) - self.assertEqual(v_cmp64(op, x, y), want) - - -class ScalarCompares(unittest.TestCase): - def test_32_bit(self): - for rel, ty in itertools.product(("eq", "lg", "lt", "le", "gt", "ge"), ("u32", "i32")): - op = f"s_cmp_{rel}_{ty}" - for x, y in PAIRS32: - with self.subTest(op=op, x=hex(x), y=hex(y)): - want = int(RELATIONS[rel](as_type(x, ty), as_type(y, ty))) - self.assertEqual(s_cmp(op, x, y), want) - - def test_64_bit_equality(self): - for rel in ("eq", "lg"): - op = f"s_cmp_{rel}_u64" - for x, y in PAIRS64: - with self.subTest(op=op, x=hex(x), y=hex(y)): - self.assertEqual(s_cmp(op, x, y, wide=True), int(RELATIONS[rel](x, y))) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_int_ext_fixture.py b/tests/semantic/test_int_ext_fixture.py deleted file mode 100644 index 1dda2f188..000000000 --- a/tests/semantic/test_int_ext_fixture.py +++ /dev/null @@ -1,81 +0,0 @@ -"""cs_w32_int_ext: the GPU test of integer ops that until now had CPU-only checks, run here on the CPU too. - -Standard library only; no GPU, no LLVM, no game files. - -runtime/test/shaders/cs_w32_int_ext.asm has lane 0 of a wave32 group store one result of each of s_absdiff_i32, -s_lshl2_add_u32, the SCC of s_lshl1_add_u32, s_pack_lh_b32_b16, s_mul_hi_i32, v_mul_hi_i32_i24, v_sad_u8 and v_lerp_u8 -(derivations in its header). This runs its fixture (tests/semantic/regen_fixtures.py) as one invocation through -spirv_mini_interp and checks the eight words against values computed here from the ISA definitions, and that -check.py and scripts/run_gpu_tests.py expect the same words on the GPU. -""" -import os -import re -import struct -import unittest - -import support -import spirv_mini_interp as si - -HERE = os.path.dirname(os.path.abspath(__file__)) -ROOT = os.path.dirname(os.path.dirname(HERE)) -M32 = 0xFFFFFFFF - -# 4 user SGPRs (the output V#), workgroup id in s4, 32x1x1 threads. -FSSM = bytearray(0x148) -struct.pack_into("<4I", FSSM, 0x138, 0x88, 32, 1, 1) -FSSM = bytes(FSSM) -VSHARP = [0, 0, 0x1000, 0x31016FAC] - - -def s32(x: int) -> int: - x &= M32 - return x - (1 << 32) if x >> 31 else x - - -def i24(x: int) -> int: - x &= 0xFFFFFF - return x - (1 << 24) if x >> 23 else x - - -def lerp_u8(a: int, b: int, c: int) -> int: - return sum((((a >> s) & 0xFF) + ((b >> s) & 0xFF) + ((c >> s) & 1)) >> 1 << s for s in (0, 8, 16, 24)) - - -EXPECTED = [ - abs(s32(0x7FFFFFFF - 0x80000000)) & M32, # s_absdiff_i32: wraps to -1 first - ((5 << 2) + 7) & M32, # s_lshl2_add_u32 - int((0x80000000 << 1) + 0 >= 1 << 32), # s_lshl1_add_u32 SCC - (0x33334444 & 0xFFFF0000) | (0x11112222 & 0xFFFF), # s_pack_lh_b32_b16 - ((s32(0x80000000) * s32(0x7FFFFFFF)) >> 32) & M32, # s_mul_hi_i32 - ((i24(0x800000) * i24(0x800000)) >> 32) & M32, # v_mul_hi_i32_i24 - 10 + sum(abs(((0x01020304 >> s) & 0xFF) - ((0x04030201 >> s) & 0xFF)) for s in (0, 8, 16, 24)), # v_sad_u8 - lerp_u8(0x10203040, 0x30405060, 0x01010101), # v_lerp_u8 -] - - -class IntExtFixture(unittest.TestCase): - def test_reference(self): - self.assertEqual(EXPECTED, [1, 27, 1, 0x33332222, 0xC0000000, 0x4000, 18, 0x20304050]) - - def test_translated_shader(self): - spv = support.translate_fixture("cs_w32_int_ext", fssm=FSSM) - mem = si.run_workgroup(spv, 1, 32, inputs_for=lambda i: {"%wg_id": (0, 0, 0), "%local_id": (i, 0, 0), - "%sg_lane": i}, - push_constants=VSHARP + [0] * 28, memory={}) - self.assertEqual(sorted(mem), [4 * k for k in range(8)]) - for k, want in enumerate(EXPECTED): - with self.subTest(word=k): - self.assertEqual(mem[4 * k], want) - - def test_gpu_runners_expect_the_same_words(self): - for rel in (("runtime", "test", "shaders", "check.py"), ("scripts", "run_gpu_tests.py")): - with open(os.path.join(ROOT, *rel), encoding="utf-8") as f: - text = f.read() - m = re.search(r'"cs_w32_int_ext"\)?[,:]\s*\[([^\]]*)\]', text) - with self.subTest(file="/".join(rel)): - self.assertIsNotNone(m) - self.assertEqual([int(v, 0) for v in m.group(1).split(",")], EXPECTED) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_int_to_float.py b/tests/semantic/test_int_to_float.py deleted file mode 100644 index 8d3be371d..000000000 --- a/tests/semantic/test_int_to_float.py +++ /dev/null @@ -1,274 +0,0 @@ -"""Translator tests for RDNA2 v_cvt_f32_i32 and v_cvt_f32_u32 (32-bit integer to binary32 float). - - v_cvt_f32_i32 D = exact (as binary32) signed int32 -> nearest f32, round to nearest even - v_cvt_f32_u32 D = exact (as binary32) unsigned int32 -> nearest f32, round to nearest even - -Every case translates a hand-written pixel-shader listing with tools/rdna2spirv.py and executes the resulting SPIR-V -via tests/semantic/spirv_mini_interp.py. Expected words are written by hand from the ISA formula and also recomputed -by a plain-Python reference, with seeded random operands. - -Standard library only: no GPU, no LLVM, no external tools, no game files. - -Until this file, test_int_to_float.py ran a private Python oracle (a plain-Python f32 model) that never called the -translator, as recorded in the DEBT table in tests/test_semantic_translator_use.py. -""" -import math -import os -import random -import struct -import sys -import unittest - -HERE = os.path.dirname(os.path.abspath(__file__)) -if HERE not in sys.path: - sys.path.insert(0, HERE) - -from support import mrt0_words, translate_lines # noqa: E402 - -MASK32 = 0xFFFFFFFF - - -def bits_from_f32(x): - """Pack a Python float into its IEEE-754 binary32 32-bit unsigned word.""" - try: - return struct.unpack(" f32, round to nearest even.""" - val &= MASK32 - if val >= 0x80000000: - x = val - 0x100000000 # two's complement to signed - else: - x = val - return bits_from_f32(float(x)) - - -def ref_cvt_f32_u32(val): - """Plain-Python reference for v_cvt_f32_u32: unsigned int32 -> f32, round to nearest even. - - Python's float is binary64, so any exact conversion is exact; the rounding to binary32 happens in - `bits_from_f32` via pack/unpack which follows round-to-nearest-even. - """ - return bits_from_f32(float(val & MASK32)) - - -def run_cvt_f32_i32(val, e64_mods=""): - """Translate and run v_cvt_f32_i32 on a uniform i32 value. Returns [mrt0 words].""" - v = val & MASK32 - if e64_mods: - lines = [ - f"v_mov_b32 v1, {v:#010x}", - f"v_cvt_f32_i32_e64 v0, {e64_mods}v1", - "exp mrt0 v0, v0, v0, v0 done vm", - "s_endpgm", - ] - else: - lines = [ - f"v_mov_b32 v1, {v:#010x}", - "v_cvt_f32_i32_e32 v0, v1", - "exp mrt0 v0, v0, v0, v0 done vm", - "s_endpgm", - ] - return mrt0_words(translate_lines("ps_cvt_f32_i32", lines))[0] - - -def run_cvt_f32_u32(val, e64_mods=""): - """Translate and run v_cvt_f32_u32 on a uniform u32 value. Returns one mrt0 word.""" - v = val & MASK32 - if e64_mods: - lines = [ - f"v_mov_b32 v1, {v:#010x}", - f"v_cvt_f32_u32_e64 v0, {e64_mods}v1", - "exp mrt0 v0, v0, v0, v0 done vm", - "s_endpgm", - ] - else: - lines = [ - f"v_mov_b32 v1, {v:#010x}", - "v_cvt_f32_u32_e32 v0, v1", - "exp mrt0 v0, v0, v0, v0 done vm", - "s_endpgm", - ] - return mrt0_words(translate_lines("ps_cvt_f32_u32", lines))[0] - - -# (input word, expected f32 word) for v_cvt_f32_i32. -# Computed from the formula: float(signed_int32), then f32 pack. -I32_HAND = [ - (0x00000000, 0x00000000), # 0 - (0x00000001, 0x3F800000), # 1 - (0x00000002, 0x40000000), # 2 - (0x0000002A, 0x42280000), # 42 - (0x00000064, 0x42C80000), # 100 - (0x7FFFFFFF, 0x4F000000), # max positive i32 = 2^31 - 1 - (0xFFFFFFFF, 0xBF800000), # -1 - (0xFFFFFFD6, 0xC2280000), # -42 - (0xFFFFFF9C, 0xC2C80000), # -100 - (0x80000000, 0xCF000000), # min negative i32 = -2^31 - (0x01000000, 0x4B800000), # 2^24 -> exact in f32 - (0x01000001, 0x4B800000), # 2^24 + 1 -> rounds down (tie, even is the 2^24 alternative) - (0x00FFFFFF, 0x4B7FFFFF), # 2^24 - 1 -> exact - (0x00400000, 0x4A800000), # 2^22 -> exact -] - -# (input word, expected f32 word) for v_cvt_f32_u32. -# Computed from the formula: float(unsigned_int32), then f32 pack. -U32_HAND = [ - (0x00000000, 0x00000000), # 0 - (0x00000001, 0x3F800000), # 1 - (0x00000002, 0x40000000), # 2 - (0x0000002A, 0x42280000), # 42 - (0x00000064, 0x42C80000), # 100 - (0x7FFFFFFF, 0x4F000000), # 2^31 - 1 -> exact in f32 - (0x80000000, 0x4F000000), # 2^31 -> exact - (0xFFFFFFFF, 0x4F800000), # max u32 -> exact - (0x01000000, 0x4B800000), # 2^24 -> exact - (0x01000001, 0x4B800000), # 2^24 + 1 -> rounds down (tie, even) - (0x00FFFFFF, 0x4B7FFFFF), # 2^24 - 1 -> exact - (0x00400000, 0x4A800000), # 2^22 -> exact - (0x80000001, 0x4F000000), # 2^31 + 1 -> rounds down (tie, even: the 2^31 mantissa ends in 0) - (0x0000000A, 0x41200000), # 10 -] - - -class HandWrittenCases(unittest.TestCase): - def test_v_cvt_f32_i32_hand_table(self): - for val, expected in I32_HAND: - with self.subTest(val=hex(val)): - self.assertEqual(run_cvt_f32_i32(val), expected) - - def test_v_cvt_f32_u32_hand_table(self): - for val, expected in U32_HAND: - with self.subTest(val=hex(val)): - self.assertEqual(run_cvt_f32_u32(val), expected) - - -class ReferenceCoherence(unittest.TestCase): - """The hand-written table matches the plain-Python reference for both ops.""" - - def test_i32_ref_matches_hand(self): - for val, expected in I32_HAND: - with self.subTest(val=hex(val)): - self.assertEqual(ref_cvt_f32_i32(val), expected) - - def test_u32_ref_matches_hand(self): - for val, expected in U32_HAND: - with self.subTest(val=hex(val)): - self.assertEqual(ref_cvt_f32_u32(val), expected) - - def test_translator_matches_reference(self): - rng = random.Random(0xC007C437) - for _ in range(60): - for op, ref_fn, run_fn in ( - ("v_cvt_f32_i32", ref_cvt_f32_i32, run_cvt_f32_i32), - ("v_cvt_f32_u32", ref_cvt_f32_u32, run_cvt_f32_u32), - ): - val = rng.getrandbits(32) - with self.subTest(op=op, val=hex(val)): - self.assertEqual(run_fn(val), ref_fn(val)) - - -class SGPRSource(unittest.TestCase): - def test_sgpr_source(self): - lines = [ - "s_mov_b32 s1, 0x0000002A", # 42 - "v_cvt_f32_i32_e64 v0, s1", - "exp mrt0 v0, v0, v0, v0 done vm", - "s_endpgm", - ] - spv = translate_lines("ps_cvt_sgpr", lines) - self.assertEqual(mrt0_words(spv)[0], 0x42280000) - - -class InlineConstantSource(unittest.TestCase): - def test_inline_literal(self): - lines = [ - "v_cvt_f32_i32_e32 v0, 10", - "exp mrt0 v0, v0, v0, v0 done vm", - "s_endpgm", - ] - spv = translate_lines("ps_cvt_lit", lines) - self.assertEqual(mrt0_words(spv)[0], 0x41200000) # 10.0 - - -class VOP3Modifiers(unittest.TestCase): - """VOP3 modifiers on v_cvt_f32_i32/v_cvt_f32_u32. - - The RDNA2 ISA applies source modifiers (neg/abs) to the integer source in two's complement (not to the float - result). The translator currently implements them via OpFAbs/OpFNegate on the bit pattern reinterpreted as float, - which gives wrong results for negative sources (where the bits are a NaN-narrowing pattern). These tests document - the actual translator output for positive sources (where the bits represent a normal float). - """ - - def test_omod_mul2(self): - # 1 * 2 = 2.0 - spv = translate_lines("ps_cvt_omod", [ - "v_mov_b32 v1, 0x00000001", - "v_cvt_f32_i32_e64 v0, v1 mul:2", - "exp mrt0 v0, v0, v0, v0 done vm", - "s_endpgm", - ]) - self.assertEqual(mrt0_words(spv)[0], 0x40000000) # 2.0 - - def test_omod_div2(self): - # 10 / 2 = 5.0 - spv = translate_lines("ps_cvt_omod_div2", [ - "v_mov_b32 v1, 0x0000000A", - "v_cvt_f32_i32_e64 v0, v1 div:2", - "exp mrt0 v0, v0, v0, v0 done vm", - "s_endpgm", - ]) - self.assertEqual(mrt0_words(spv)[0], 0x40A00000) # 5.0 - - def test_omod_mul4(self): - # 42 * 4 = 168.0 - spv = translate_lines("ps_cvt_omod_mul4", [ - "v_mov_b32 v1, 0x0000002A", - "v_cvt_f32_i32_e64 v0, v1 mul:4", - "exp mrt0 v0, v0, v0, v0 done vm", - "s_endpgm", - ]) - self.assertEqual(mrt0_words(spv)[0], 0x43280000) # 168.0 - - def test_clamp_negative_saturates_to_zero(self): - # -1.0 clamped -> 0.0 - spv = translate_lines("ps_cvt_clamp_neg", [ - "v_mov_b32 v1, 0xFFFFFFFF", - "v_cvt_f32_i32_e64 v0, v1 clamp", - "exp mrt0 v0, v0, v0, v0 done vm", - "s_endpgm", - ]) - self.assertEqual(mrt0_words(spv)[0], 0x00000000) - - def test_clamp_positive_large_saturates_to_one(self): - # 1000.0 clamped -> 1.0 - spv = translate_lines("ps_cvt_clamp_pos", [ - "v_mov_b32 v1, 0x000003E8", - "v_cvt_f32_i32_e64 v0, v1 clamp", - "exp mrt0 v0, v0, v0, v0 done vm", - "s_endpgm", - ]) - self.assertEqual(mrt0_words(spv)[0], 0x3F800000) # 1.0 - - def test_sgpr_with_modifiers(self): - # s_mov_b32 s1, 42 -> v_cvt_f32_i32_e64 v0, s1 mul:2 - lines = [ - "s_mov_b32 s1, 0x0000002A", - "v_cvt_f32_i32_e64 v0, s1 mul:4", - "exp mrt0 v0, v0, v0, v0 done vm", - "s_endpgm", - ] - spv = translate_lines("ps_cvt_sgpr_mod", lines) - self.assertEqual(mrt0_words(spv)[0], 0x43280000) # 168.0 - - -if __name__ == "__main__": - unittest.main() \ No newline at end of file diff --git a/tests/semantic/test_interp.py b/tests/semantic/test_interp.py deleted file mode 100644 index f38fe2681..000000000 --- a/tests/semantic/test_interp.py +++ /dev/null @@ -1,930 +0,0 @@ -"""Self-tests for the mini SPIR-V interpreter, using hand-written modules and expectations taken from the SPIR-V -and GLSL.std.450 specifications (not from the translator).""" -import math -import struct -import unittest - -import spirv_mini_interp as si -import spirv_wave_interp - -HEADER = """\ -OpCapability Shader -%glsl = OpExtInstImport "GLSL.std.450" -OpMemoryModel Logical GLSL450 -OpEntryPoint Fragment %main "main" %out -%void = OpTypeVoid -%fn = OpTypeFunction %void -%uint = OpTypeInt 32 0 -%float = OpTypeFloat 32 -%bool = OpTypeBool -%v2float = OpTypeVector %float 2 -%_ptr_Output_uint = OpTypePointer Output %uint -%out = OpVariable %_ptr_Output_uint Output -%c0 = OpConstant %uint 0 -%c1 = OpConstant %uint 1 -%c2 = OpConstant %uint 2 -%c4 = OpConstant %uint 4 -%c8 = OpConstant %uint 8 -%c31 = OpConstant %uint 31 -%c32 = OpConstant %uint 32 -%cF0 = OpConstant %uint 4294967280 -%cFF = OpConstant %uint 4294967295 -%cInf = OpConstant %uint 2139095040 -%c80 = OpConstant %uint 128 -%ch = OpConstant %uint 1073757184 -%f1 = OpConstant %float 1 -%f2 = OpConstant %float 2 -%f3 = OpConstant %float 3 -%f70000 = OpConstant %float 70000 -%f2p5 = OpConstant %float 2.5 -%f3p5 = OpConstant %float 3.5 -%f0p5 = OpConstant %float 0.5 -%int = OpTypeInt 32 1 -%t = OpConstantTrue %bool -%f = OpConstantFalse %bool -%_ptr_Function_uint = OpTypePointer Function %uint -%arr = OpTypeArray %uint %c4 -%_ptr_Function_arr = OpTypePointer Function %arr -%null_arr = OpConstantNull %arr -%ud = OpTypeStruct %uint -%umul = OpTypeStruct %uint %uint -%_ptr_PC = OpTypePointer PushConstant %ud -%pc = OpVariable %_ptr_PC PushConstant -%_ptr_PC_uint = OpTypePointer PushConstant %uint -%main = OpFunction %void None %fn -%entry = OpLabel -""" -FOOTER = "OpReturn\nOpFunctionEnd\n" - - -def run_word(body): - """Run `body` (instructions that must define %res as a uint) and return the word stored to %out.""" - return si.run_fragment(HEADER + body + "OpStore %out %res\n" + FOOTER)["%out"][0] - - -class InterpreterTests(unittest.TestCase): - def test_bitfield_extract(self): - # SPIR-V: Count 0 gives 0; SExtract replicates the field's top bit; UExtract zero-extends. - self.assertEqual(run_word("%res = OpBitFieldSExtract %uint %cF0 %c2 %c4\n"), 0xFFFFFFFC) # 0b1100 -> -4 - self.assertEqual(run_word("%res = OpBitFieldUExtract %uint %cF0 %c2 %c4\n"), 0xC) - self.assertEqual(run_word("%res = OpBitFieldSExtract %uint %c80 %c0 %c8\n"), 0xFFFFFF80) - self.assertEqual(run_word("%res = OpBitFieldSExtract %uint %cFF %c2 %c0\n"), 0) - - def test_bitfield_insert(self): - self.assertEqual(run_word("%res = OpBitFieldInsert %uint %cF0 %c1 %c0 %c4\n"), 0xFFFFFFF1) - - def test_half_pack_unpack(self): - self.assertEqual(run_word("%v = OpCompositeConstruct %v2float %f1 %f2\n" - "%res = OpExtInst %uint %glsl PackHalf2x16 %v\n"), 0x40003C00) - self.assertEqual(run_word("%v = OpCompositeConstruct %v2float %f70000 %f1\n" - "%res = OpExtInst %uint %glsl PackHalf2x16 %v\n"), 0x3C007C00) # 70000 -> +inf - self.assertEqual(run_word("%u = OpExtInst %v2float %glsl UnpackHalf2x16 %ch\n" # %ch = 0x40003c00 - "%x = OpCompositeExtract %float %u 1\n" - "%res = OpBitcast %uint %x\n"), 0x40000000) # 2.0f - - def test_float_sign_operations_use_result_width(self): - # The low word in 1 + 2**-30 and the finite magnitude 2**130 both need binary64. - text = """\ -OpCapability Shader -OpCapability Float64 -%glsl = OpExtInstImport "GLSL.std.450" -OpMemoryModel Logical GLSL450 -OpEntryPoint Fragment %main "main" %out %f32_control -OpExecutionMode %main OriginUpperLeft -OpDecorate %out Location 0 -OpDecorate %f32_control Location 1 -%void = OpTypeVoid -%fn = OpTypeFunction %void -%uint = OpTypeInt 32 0 -%float = OpTypeFloat 32 -%double = OpTypeFloat 64 -%u2 = OpTypeVector %uint 2 -%u4 = OpTypeVector %uint 4 -%precise64 = OpConstant %double 1.000000000931322574615478515625 -%large_negative64 = OpConstant %double -1361129467683753853853498429727072845824 -%zero32 = OpConstant %float 0 -%negative32 = OpConstant %float -1.25 -%ptr_out_words = OpTypePointer Output %u4 -%ptr_out_pair = OpTypePointer Output %u2 -%out = OpVariable %ptr_out_words Output -%f32_control = OpVariable %ptr_out_pair Output -%main = OpFunction %void None %fn -%entry = OpLabel -%neg64 = OpFNegate %double %precise64 -%abs64 = OpExtInst %double %glsl FAbs %large_negative64 -%neg_words = OpBitcast %u2 %neg64 -%abs_words = OpBitcast %u2 %abs64 -%neg_lo = OpCompositeExtract %uint %neg_words 0 -%neg_hi = OpCompositeExtract %uint %neg_words 1 -%abs_lo = OpCompositeExtract %uint %abs_words 0 -%abs_hi = OpCompositeExtract %uint %abs_words 1 -%words = OpCompositeConstruct %u4 %neg_lo %neg_hi %abs_lo %abs_hi -OpStore %out %words -%neg32 = OpFNegate %float %zero32 -%abs32 = OpExtInst %float %glsl FAbs %negative32 -%neg32_bits = OpBitcast %uint %neg32 -%abs32_bits = OpBitcast %uint %abs32 -%control = OpCompositeConstruct %u2 %neg32_bits %abs32_bits -OpStore %f32_control %control -""" - outputs = si.run_fragment(text + FOOTER) - self.assertEqual(outputs["%f32_control"], (0x80000000, 0x3FA00000)) - self.assertEqual(outputs["%out"], (0x00400000, 0xBFF00000, 0, 0x48100000)) - - def test_fma_select_bitcast(self): - self.assertEqual(run_word("%x = OpExtInst %float %glsl Fma %f2 %f3 %f1\n%res = OpBitcast %uint %x\n"), - 0x40E00000) # 7.0f - self.assertEqual(run_word("%res = OpSelect %uint %t %c1 %c2\n"), 1) - self.assertEqual(run_word("%res = OpSelect %uint %f %c1 %c2\n"), 2) - - def test_signed_unsigned_min_max(self): - self.assertEqual(run_word("%res = OpExtInst %uint %glsl SMax %cFF %c1\n"), 1) # -1 vs 1 signed - self.assertEqual(run_word("%res = OpExtInst %uint %glsl UMin %cFF %c1\n"), 1) # 2^32-1 vs 1 unsigned - - def test_integer_ops_wrap(self): - self.assertEqual(run_word("%res = OpIAdd %uint %cFF %c2\n"), 1) - self.assertEqual(run_word("%res = OpISub %uint %c1 %c2\n"), 0xFFFFFFFF) - self.assertEqual(run_word("%res = OpIMul %uint %cFF %c2\n"), 0xFFFFFFFE) - self.assertEqual(run_word("%res = OpShiftLeftLogical %uint %cFF %c4\n"), 0xFFFFFFF0) - self.assertEqual(run_word("%res = OpShiftRightLogical %uint %cF0 %c4\n"), 0x0FFFFFFF) - self.assertEqual(run_word("%res = OpBitwiseXor %uint %cF0 %cFF\n"), 0xF) - self.assertEqual(run_word("%res = OpNot %uint %cF0\n"), 0xF) - self.assertEqual(run_word("%res = OpBitCount %uint %cFF\n"), 32) - self.assertEqual(run_word("%res = OpBitCount %uint %c0\n"), 0) - - def test_float_ops(self): - self.assertEqual(run_word("%x = OpFMul %float %f2 %f3\n%res = OpBitcast %uint %x\n"), 0x40C00000) - self.assertEqual(run_word("%x = OpFSub %float %f2 %f3\n%res = OpBitcast %uint %x\n"), 0xBF800000) - self.assertEqual(run_word("%x = OpFAdd %float %f1 %f2\n%res = OpBitcast %uint %x\n"), 0x40400000) - self.assertEqual(run_word("%x = OpFNegate %float %f3\n%res = OpBitcast %uint %x\n"), 0xC0400000) - self.assertEqual(run_word("%b = OpFOrdEqual %bool %f2 %f2\n%res = OpSelect %uint %b %c1 %c0\n"), 1) - self.assertEqual(run_word("%b = OpFOrdLessThan %bool %f1 %f2\n%res = OpSelect %uint %b %c1 %c0\n"), 1) - self.assertEqual(run_word("%b = OpFUnordNotEqual %bool %f1 %f1\n" - "%res = OpSelect %uint %b %c1 %c0\n"), 0) - - def test_conversions(self): - # SToF reads its operand as signed; FToU and FToS round toward zero. - self.assertEqual(run_word("%x = OpConvertUToF %float %c8\n%res = OpBitcast %uint %x\n"), 0x41000000) - self.assertEqual(run_word("%x = OpConvertUToF %float %cFF\n%res = OpBitcast %uint %x\n"), 0x4F800000) - self.assertEqual(run_word("%x = OpConvertSToF %float %cFF\n%res = OpBitcast %uint %x\n"), 0xBF800000) - self.assertEqual(run_word("%x = OpConvertSToF %float %cF0\n%res = OpBitcast %uint %x\n"), 0xC1800000) - self.assertEqual(run_word("%x = OpFNegate %float %f2p5\n%res = OpConvertFToS %int %x\n"), 0xFFFFFFFE) - self.assertEqual(run_word("%res = OpConvertFToU %uint %f2p5\n"), 2) - self.assertEqual(run_word("%res = OpConvertFToU %uint %f70000\n"), 70000) - - def test_int32_to_float_uses_result_width(self): - # 2**24 + 1 is exact in binary64 but rounds to 2**24 in binary32. - text = """\ -OpCapability Shader -OpCapability Float64 -OpMemoryModel Logical GLSL450 -OpEntryPoint Fragment %main "main" %out %f32_control -OpExecutionMode %main OriginUpperLeft -OpDecorate %out Location 0 -OpDecorate %f32_control Location 1 -%void = OpTypeVoid -%fn = OpTypeFunction %void -%uint = OpTypeInt 32 0 -%sint = OpTypeInt 32 1 -%float = OpTypeFloat 32 -%double = OpTypeFloat 64 -%bool = OpTypeBool -%u2 = OpTypeVector %uint 2 -%u4 = OpTypeVector %uint 4 -%unsigned = OpConstant %uint 16777217 -%signed = OpConstant %sint -16777217 -%rounded_unsigned = OpConstant %float 16777216 -%rounded_signed = OpConstant %float -16777216 -%zero = OpConstant %uint 0 -%one = OpConstant %uint 1 -%ptr_out_words = OpTypePointer Output %u4 -%ptr_out_uint = OpTypePointer Output %uint -%out = OpVariable %ptr_out_words Output -%f32_control = OpVariable %ptr_out_uint Output -%main = OpFunction %void None %fn -%entry = OpLabel -%du = OpConvertUToF %double %unsigned -%ds = OpConvertSToF %double %signed -%bu = OpBitcast %u2 %du -%bs = OpBitcast %u2 %ds -%ulo = OpCompositeExtract %uint %bu 0 -%uhi = OpCompositeExtract %uint %bu 1 -%slo = OpCompositeExtract %uint %bs 0 -%shi = OpCompositeExtract %uint %bs 1 -%words = OpCompositeConstruct %u4 %ulo %uhi %slo %shi -OpStore %out %words -%fu = OpConvertUToF %float %unsigned -%fs = OpConvertSToF %float %signed -%u_ok = OpFOrdEqual %bool %fu %rounded_unsigned -%s_ok = OpFOrdEqual %bool %fs %rounded_signed -%f_ok = OpLogicalAnd %bool %u_ok %s_ok -%control = OpSelect %uint %f_ok %one %zero -OpStore %f32_control %control -""" - outputs = si.run_fragment(text + FOOTER) - self.assertEqual(outputs["%f32_control"], (1,)) - self.assertEqual(outputs["%out"], (0x10000000, 0x41700000, 0x10000000, 0xC1700000)) - - def test_floor_ceil_trunc_and_signed_zero(self): - def word(name, const, neg=False): - pre = f"%n = OpFNegate %float {const}\n" if neg else "" - x = "%n" if neg else const - return run_word(f"{pre}%x = OpExtInst %float %glsl {name} {x}\n%res = OpBitcast %uint %x\n") - self.assertEqual(word("Floor", "%f2p5"), 0x40000000) # 2.5 -> 2 - self.assertEqual(word("Floor", "%f2p5", neg=True), 0xC0400000) # -2.5 -> -3 - self.assertEqual(word("Ceil", "%f2p5"), 0x40400000) # 2.5 -> 3 - self.assertEqual(word("Ceil", "%f2p5", neg=True), 0xC0000000) # -2.5 -> -2 - self.assertEqual(word("Trunc", "%f3p5"), 0x40400000) # 3.5 -> 3 - self.assertEqual(word("Trunc", "%f3p5", neg=True), 0xC0400000) # -3.5 -> -3 - # A zero result keeps the operand's sign: -0.5 rounds to -0.0 (0x80000000), 0.5 to +0.0. - self.assertEqual(word("Ceil", "%f0p5", neg=True), 0x80000000) - self.assertEqual(word("Trunc", "%f0p5", neg=True), 0x80000000) - self.assertEqual(word("RoundEven", "%f0p5", neg=True), 0x80000000) - self.assertEqual(word("Floor", "%f0p5"), 0) - self.assertEqual(word("Floor", "%f70000"), 0x4788B800) # already integral: unchanged - # A vector operand rounds component by component (the translator emits a %v2float Floor/Ceil). - for name, want in (("Floor", (0xC0400000, 0x40000000)), ("Ceil", (0xC0000000, 0x40400000))): - got = tuple(run_word(f"%n = OpFNegate %float %f2p5\n%v = OpCompositeConstruct %v2float %n %f2p5\n" - f"%r = OpExtInst %v2float %glsl {name} %v\n%x = OpCompositeExtract %float %r {i}\n" - "%res = OpBitcast %uint %x\n") for i in (0, 1)) - self.assertEqual(got, want, name) - - def test_wide_integer_conversion_is_rejected(self): - # A 64-bit operand must not be silently truncated to 32 bits before the conversion. - text = HEADER.replace("%c0 = OpConstant %uint 0", - "%ulong = OpTypeInt 64 0\n" - "%c64_big = OpConstant %ulong 4294967296\n" - "%c0 = OpConstant %uint 0") - for op in ("OpConvertUToF", "OpConvertSToF"): - with self.subTest(op=op): - body = text + (f"%x = {op} %float %c64_big\n" - "%res = OpBitcast %uint %x\nOpStore %out %res\n" + FOOTER) - with self.assertRaises(si.UnsupportedConstruct): - si.run_fragment(body) - - def test_64bit_operand_below_2_32_is_rejected(self): - # A 64-bit operand is rejected by its type width, not its value: signed 2**31 in a 64-bit int would - # otherwise convert as -2147483648.0 under OpConvertSToF (follow-up to #346). - text = HEADER.replace("%c0 = OpConstant %uint 0", - "%ulong = OpTypeInt 64 0\n%long = OpTypeInt 64 1\n" - "%cl_one = OpConstant %ulong 1\n%cl_2p31 = OpConstant %long 2147483648\n" - "%c0 = OpConstant %uint 0") - for op in ("OpConvertUToF", "OpConvertSToF"): - for src in ("%cl_one", "%cl_2p31"): - with self.subTest(op=op, src=src): - body = text + (f"%x = {op} %float {src}\n" - "%res = OpBitcast %uint %x\nOpStore %out %res\n" + FOOTER) - with self.assertRaises(si.UnsupportedConstruct): - si.run_fragment(body) - - WIDE = HEADER.replace("%c0 = OpConstant %uint 0", - "%ulong = OpTypeInt 64 0\n" - "%cl_1 = OpConstant %ulong 1\n" - "%cl_2p31 = OpConstant %ulong 2147483648\n" - "%cl_2p32 = OpConstant %ulong 4294967296\n" - "%cl_2p32_5 = OpConstant %ulong 4294967301\n" - "%cl_hi = OpConstant %ulong 18446744069414584320\n" # 0xFFFFFFFF00000000 = -2**32 - "%cl_m1 = OpConstant %ulong 18446744073709551615\n" - "%c0 = OpConstant %uint 0") - - def test_bit_count_counts_every_bit_of_a_64bit_operand(self): - # OpBitCount counts the set bits of its operand, whatever the width of the (32-bit) result. - for src, want in (("%cl_hi", 32), ("%cl_m1", 64), ("%cl_2p32_5", 3), ("%cl_1", 1)): - with self.subTest(src=src): - out = si.run_fragment(self.WIDE + f"%res = OpBitCount %uint {src}\nOpStore %out %res\n" + FOOTER) - self.assertEqual(out["%out"], (want,)) - self.assertEqual(run_word("%res = OpBitCount %uint %cF0\n"), 28) - - def test_signed_min_max_clamp_abs_use_the_width_of_a_64bit_type(self): - # GLSL.std.450 SMin/SMax/SClamp/SAbs read their operands as signed at the width of their type. 2**31 is - # positive in a 64-bit integer and 0xFFFFFFFF00000000 is -2**32; a 32-bit reading takes them as - # -2**31 and 0. - for inst, want in (("SMin %cl_2p31 %cl_1", "%cl_1"), ("SMax %cl_2p31 %cl_1", "%cl_2p31"), - ("SMin %cl_hi %cl_1", "%cl_hi"), ("SMax %cl_hi %cl_m1", "%cl_m1"), - ("SClamp %cl_2p31 %cl_1 %cl_2p32", "%cl_2p31"), ("SClamp %cl_hi %cl_m1 %cl_1", "%cl_m1"), - ("SAbs %cl_hi", "%cl_2p32"), ("SAbs %cl_2p32_5", "%cl_2p32_5"), ("SAbs %cl_m1", "%cl_1")): - with self.subTest(inst=inst): - out = si.run_fragment(self.WIDE + f"%r = OpExtInst %ulong %glsl {inst}\n" - f"%eq = OpIEqual %bool %r {want}\n%res = OpSelect %uint %eq %c1 %c0\n" - "OpStore %out %res\n" + FOOTER) - self.assertEqual(out["%out"], (1,)) - - def test_glsl_integer_operations_reject_mixed_component_widths(self): - for inst in ("SAbs %cl_1", "SMin %c0 %cl_1", "SMax %cl_1 %c0", - "SClamp %c0 %c0 %cl_1", "FindILsb %cl_1", "FindSMsb %cl_1", "FindUMsb %cl_1"): - with self.subTest(inst=inst): - body = f"%res = OpExtInst %uint %glsl {inst}\n" - with self.assertRaisesRegex(si.UnsupportedConstruct, "64-bit.*32-bit"): - si.run_fragment(self.WIDE + body + "OpStore %out %res\n" + FOOTER) - - def test_find_bit_of_a_64bit_operand_is_rejected(self): - # GLSL.std.450 limits FindILsb, FindSMsb and FindUMsb to 32-bit components. - for name in ("FindILsb", "FindSMsb", "FindUMsb"): - with self.subTest(name=name): - with self.assertRaisesRegex(si.UnsupportedConstruct, "64-bit"): - si.run_fragment(self.WIDE + f"%r = OpExtInst %ulong %glsl {name} %cl_2p32\n" - "%res = OpUConvert %uint %r\nOpStore %out %res\n" + FOOTER) - - def test_round_even_clamp_max(self): - # RoundEven sends halves to the even neighbour: 2.5 -> 2, 3.5 -> 4. - self.assertEqual(run_word("%x = OpExtInst %float %glsl RoundEven %f2p5\n%res = OpBitcast %uint %x\n"), - 0x40000000) - self.assertEqual(run_word("%x = OpExtInst %float %glsl RoundEven %f3p5\n%res = OpBitcast %uint %x\n"), - 0x40800000) - self.assertEqual(run_word("%x = OpExtInst %float %glsl FClamp %f3 %f1 %f2\n%res = OpBitcast %uint %x\n"), - 0x40000000) - self.assertEqual(run_word("%n = OpFNegate %float %f3\n%x = OpExtInst %float %glsl FClamp %n %f1 %f2\n" - "%res = OpBitcast %uint %x\n"), 0x3F800000) - self.assertEqual(run_word("%x = OpExtInst %float %glsl FClamp %f2p5 %f1 %f3\n%res = OpBitcast %uint %x\n"), - 0x40200000) - self.assertEqual(run_word("%x = OpExtInst %float %glsl FMax %f1 %f3\n%res = OpBitcast %uint %x\n"), - 0x40400000) - - def test_64bit_arithmetic(self): - text = HEADER.replace("%c0 = OpConstant %uint 0", - "%ulong = OpTypeInt 64 0\n" - "%c64_1 = OpConstant %ulong 1\n" - "%c64_32 = OpConstant %ulong 32\n" - "%c0 = OpConstant %uint 0") - text += ("%sh = OpShiftLeftLogical %ulong %c64_1 %c64_32\n" - "%sum = OpIAdd %ulong %sh %c64_1\n" - "%prod = OpIMul %ulong %sum %c64_1\n" - "%res = OpUConvert %uint %prod\n" + "OpStore %out %res\n" + FOOTER) - self.assertEqual(si.run_fragment(text)["%out"][0], 1) - - def test_64bit_pointer_load(self): - text = HEADER.replace("OpMemoryModel Logical GLSL450", - 'OpCapability PhysicalStorageBufferAddresses\n' - 'OpExtension "SPV_KHR_physical_storage_buffer"\n' - "OpMemoryModel PhysicalStorageBuffer64 GLSL450") - decls = ("%ulong = OpTypeInt 64 0\n" - "%rt = OpTypeRuntimeArray %uint\n" - "%_ptr_PSB_rt = OpTypePointer PhysicalStorageBuffer %rt\n" - "%_ptr_PSB_uint = OpTypePointer PhysicalStorageBuffer %uint\n" - "%addr = OpConstant %ulong 4096\n") - text = text.replace("%main = OpFunction", decls + "%main = OpFunction") - text += ("%p = OpConvertUToPtr %_ptr_PSB_rt %addr\n" - "%q = OpAccessChain %_ptr_PSB_uint %p %c1\n" - "%res = OpLoad %uint %q\n" - "OpStore %out %res\n" + FOOTER) - self.assertEqual(si.run_fragment(text, memory={4100: 0x12345678})["%out"][0], 0x12345678) - - def test_physical_storage_buffer_access_is_one_aligned_32bit_word(self): - """The flat memory holds one 32-bit word per 4-byte-aligned address, so a PSB load or store of another - type, or at an address that is not 4-byte aligned (undefined under `Aligned 4`), must raise instead of - reading or writing one dictionary entry (a 64-bit load would give only its low word, a load at 4098 the - 0 of a key nobody wrote).""" - text = HEADER.replace("OpMemoryModel Logical GLSL450", - 'OpCapability PhysicalStorageBufferAddresses\n' - 'OpExtension "SPV_KHR_physical_storage_buffer"\n' - "OpMemoryModel PhysicalStorageBuffer64 GLSL450") - decls = ("%ulong = OpTypeInt 64 0\n" - "%_ptr_PSB_uint = OpTypePointer PhysicalStorageBuffer %uint\n" - "%_ptr_PSB_ulong = OpTypePointer PhysicalStorageBuffer %ulong\n" - "%_ptr_PSB_float = OpTypePointer PhysicalStorageBuffer %float\n" - "%a4096 = OpConstant %ulong 4096\n%a4098 = OpConstant %ulong 4098\n" - "%cl_big = OpConstant %ulong 4294967296\n") - text = text.replace("%main = OpFunction", decls + "%main = OpFunction") - memory = {4096: 0x11223344, 4100: 0x55667788} - - def run(body): - return si.run_fragment(text + body + "OpStore %out %res\n" + FOOTER, memory=dict(memory)) - - # Control: an aligned 32-bit load and store work. - self.assertEqual(run("%p = OpConvertUToPtr %_ptr_PSB_uint %a4096\n" - "%res = OpLoad %uint %p Aligned 4\n")["%out"][0], 0x11223344) - mem = dict(memory) - si.run_fragment(text + "%p = OpConvertUToPtr %_ptr_PSB_uint %a4096\nOpStore %p %c8 Aligned 4\n" - "%res = OpLoad %uint %p Aligned 4\nOpStore %out %res\n" + FOOTER, memory=mem) - self.assertEqual(mem, {4096: 8, 4100: 0x55667788}) - cases = { - "unaligned load": "%p = OpConvertUToPtr %_ptr_PSB_uint %a4098\n%res = OpLoad %uint %p Aligned 4\n", - "unaligned store": "%p = OpConvertUToPtr %_ptr_PSB_uint %a4098\nOpStore %p %c8 Aligned 4\n" - "%res = OpCopyObject %uint %c0\n", - "64-bit load": "%p = OpConvertUToPtr %_ptr_PSB_ulong %a4096\n%w = OpLoad %ulong %p Aligned 8\n" - "%res = OpUConvert %uint %w\n", - "64-bit store": "%p = OpConvertUToPtr %_ptr_PSB_ulong %a4096\nOpStore %p %cl_big Aligned 8\n" - "%res = OpCopyObject %uint %c0\n", - "float load": "%p = OpConvertUToPtr %_ptr_PSB_float %a4096\n%x = OpLoad %float %p Aligned 4\n" - "%res = OpBitcast %uint %x\n", - "float store": "%p = OpConvertUToPtr %_ptr_PSB_float %a4096\nOpStore %p %f1 Aligned 4\n" - "%res = OpCopyObject %uint %c0\n", - } - for name, body in cases.items(): - with self.subTest(name): - with self.assertRaises(si.UnsupportedConstruct): - run(body) - - def test_sconvert_sign_extends_and_truncates(self): - """OpSConvert: sign-extend from the operand's width, wrap to the result's (the global_* offset path).""" - text = HEADER.replace("OpCapability Shader", "OpCapability Shader\nOpCapability Int64") - text = text.replace("%main = OpFunction", "%long = OpTypeInt 64 1\n%ulong = OpTypeInt 64 0\n" - "%int = OpTypeInt 32 1\n%neg = OpConstant %int -16\n%main = OpFunction") - text += ("%w = OpSConvert %long %neg\n" # -16 as 64 bits - "%u = OpBitcast %ulong %w\n" - "%hi64 = OpShiftRightLogical %ulong %u %c64_32\n" - "%hi = OpUConvert %uint %hi64\n" - "%back = OpSConvert %int %w\n" # and back to 32 bits - "%lo = OpBitcast %uint %back\n" - "%res = OpBitwiseXor %uint %hi %lo\n" # 0xFFFFFFFF ^ 0xFFFFFFF0 - "OpStore %out %res\n" + FOOTER) - text = text.replace("%main = OpFunction", "%c64_32 = OpConstant %ulong 32\n%main = OpFunction") - self.assertEqual(si.run_fragment(text)["%out"][0], 0x0000000F) - - def test_physical_storage_buffer_atomics(self): - """Atomics on PhysicalStorageBuffer memory return the original value and write the combined one.""" - text = HEADER.replace("OpMemoryModel Logical GLSL450", - 'OpCapability PhysicalStorageBufferAddresses\n' - 'OpExtension "SPV_KHR_physical_storage_buffer"\n' - "OpMemoryModel PhysicalStorageBuffer64 GLSL450") - decls = ("%ulong = OpTypeInt 64 0\n" - "%_ptr_PSB_uint = OpTypePointer PhysicalStorageBuffer %uint\n" - "%addr = OpConstant %ulong 4096\n%cm1 = OpConstant %uint 4294967295\n%c5 = OpConstant %uint 5\n") - text = text.replace("%main = OpFunction", decls + "%main = OpFunction") - cases = [ # (instruction, memory before, expected memory after, expected result) - ("OpAtomicIAdd %uint %p %c1 %c0 %cm1", 7, 6, 7), - ("OpAtomicISub %uint %p %c1 %c0 %c2", 1, 0xFFFFFFFF, 1), - ("OpAtomicSMin %uint %p %c1 %c0 %cm1", 3, 0xFFFFFFFF, 3), - ("OpAtomicUMin %uint %p %c1 %c0 %cm1", 3, 3, 3), - ("OpAtomicSMax %uint %p %c1 %c0 %c2", 0x80000000, 2, 0x80000000), - ("OpAtomicXor %uint %p %c1 %c0 %c5", 6, 3, 6), - ("OpAtomicExchange %uint %p %c1 %c0 %c5", 9, 5, 9), - ("OpAtomicCompareExchange %uint %p %c1 %c0 %c0 %c5 %c2", 2, 5, 2), # equal: swapped - ("OpAtomicCompareExchange %uint %p %c1 %c0 %c0 %c5 %c2", 3, 3, 3), # not equal: kept - ] - for ins, before, after, result in cases: - with self.subTest(ins=ins, before=before): - body = (text + "%p = OpConvertUToPtr %_ptr_PSB_uint %addr\n" - f"%res = {ins}\nOpStore %out %res\n" + FOOTER) - memory = {4096: before} - self.assertEqual(si.run_fragment(body, memory=memory)["%out"][0], result) - self.assertEqual(memory[4096], after) - - def test_atomic_store_writes_the_word(self): - """OpAtomicStore has no result: it writes its value, to memory or to a variable's element.""" - text = HEADER.replace("OpMemoryModel Logical GLSL450", - 'OpCapability PhysicalStorageBufferAddresses\n' - 'OpExtension "SPV_KHR_physical_storage_buffer"\n' - "OpMemoryModel PhysicalStorageBuffer64 GLSL450") - decls = ("%ulong = OpTypeInt 64 0\n" - "%_ptr_PSB_uint = OpTypePointer PhysicalStorageBuffer %uint\n%addr = OpConstant %ulong 4096\n") - text = text.replace("%main = OpFunction", decls + "%main = OpFunction") - body = (text + "%p = OpConvertUToPtr %_ptr_PSB_uint %addr\nOpAtomicStore %p %c1 %c0 %cF0\n" - "%v = OpVariable %_ptr_Function_arr Function %null_arr\n" - "%e = OpAccessChain %_ptr_Function_uint %v %c2\nOpAtomicStore %e %c1 %c0 %c8\n" - "%res = OpLoad %uint %e\nOpStore %out %res\n" + FOOTER) - memory = {4096: 7} - self.assertEqual(si.run_fragment(body, memory=memory)["%out"][0], 8) - self.assertEqual(memory[4096], 0xFFFFFFF0) - - def test_inputs_and_push_constants_can_be_seeded(self): - text = HEADER.replace('OpEntryPoint Fragment %main "main" %out', - 'OpEntryPoint Fragment %main "main" %out %in') - decls = ("%v4float = OpTypeVector %float 4\n" - "%_ptr_Input_v4 = OpTypePointer Input %v4float\n" - "%_ptr_Input_float = OpTypePointer Input %float\n" - "%in = OpVariable %_ptr_Input_v4 Input\n") - text = text.replace("%main = OpFunction", decls + "%main = OpFunction") - text += ("%ip = OpAccessChain %_ptr_Input_float %in %c2\n" - "%iv = OpLoad %float %ip\n" - "%ib = OpBitcast %uint %iv\n" - "%pp = OpAccessChain %_ptr_PC_uint %pc %c0\n" - "%pv = OpLoad %uint %pp\n" - "%res = OpIAdd %uint %ib %pv\n" - "OpStore %out %res\n" + FOOTER) - out = si.run_fragment(text, inputs={"%in": (0.0, 0.0, 1.5, 0.0)}, push_constants=[0x100]) - self.assertEqual(out["%out"][0], 0x3FC00100) - - def test_sub_borrow_and_comparisons(self): - self.assertEqual(run_word("%s = OpISubBorrow %umul %c1 %c2\n" - "%d = OpCompositeExtract %uint %s 0\n" - "%b = OpCompositeExtract %uint %s 1\n" - "%res = OpBitwiseAnd %uint %d %b\n"), 1) - self.assertEqual(run_word("%s = OpISubBorrow %umul %c2 %c1\n" - "%res = OpCompositeExtract %uint %s 1\n"), 0) - self.assertEqual(run_word("%b = OpIEqual %bool %c2 %c2\n%res = OpSelect %uint %b %c1 %c0\n"), 1) - self.assertEqual(run_word("%b = OpINotEqual %bool %c2 %c1\n%res = OpSelect %uint %b %c1 %c0\n"), 1) - self.assertEqual(run_word("%b = OpSLessThan %bool %cFF %c0\n%res = OpSelect %uint %b %c1 %c0\n"), 1) - self.assertEqual(run_word("%b = OpLogicalAnd %bool %t %f\n%res = OpSelect %uint %b %c1 %c2\n"), 2) - self.assertEqual(run_word("%b = OpLogicalOr %bool %f %t\n%res = OpSelect %uint %b %c1 %c2\n"), 1) - - def test_a_nan_the_operation_creates_is_the_same_on_every_host(self): - floats = "%inf = OpBitcast %float %cInf\n%zero = OpBitcast %float %c0\n" - for op in ("OpFMul %float %zero %inf", "OpFMul %float %inf %zero", "OpFSub %float %inf %inf", - "OpFAdd %float %inf %ninf", "OpExtInst %float %glsl Fma %zero %inf %f1"): - with self.subTest(op=op): - body = floats + "%ninf = OpFNegate %float %inf\n" + f"%x = {op}\n%res = OpBitcast %uint %x\n" - self.assertEqual(run_word(body), 0xFFC00000) - header = HEADER.replace("%main = OpFunction", "%cNaN = OpConstant %uint 2143289345\n%main = OpFunction") - for op in ("OpFAdd %float %nan %f1", "OpFMul %float %nan %f2", "OpExtInst %float %glsl Fma %nan %f2 %f1"): - with self.subTest(op=op, propagated=True): - text = header + f"%nan = OpBitcast %float %cNaN\n%x = {op}\n%res = OpBitcast %uint %x\n" - self.assertEqual(si.run_fragment(text + "OpStore %out %res\n" + FOOTER)["%out"][0], 0x7FC00001) - - def test_created_nan_is_pinned_whatever_the_host_gives(self): - arm64_nan = math.copysign(math.nan, 1.0) - self.assertEqual(struct.pack(" -1 - for op, want in (("OpULessThan", 1), ("OpULessThanEqual", 1), ("OpUGreaterThan", 0), - ("OpUGreaterThanEqual", 0), ("OpSLessThan", 0), ("OpSLessThanEqual", 0), - ("OpSGreaterThan", 1), ("OpSGreaterThanEqual", 1)): - with self.subTest(op=op): - self.assertEqual(run_word(f"%b = {op} %bool %c2 %cFF\n%res = OpSelect %uint %b %c1 %c0\n"), want) - for op, want in (("OpULessThanEqual", 1), ("OpUGreaterThan", 0), ("OpSLessThanEqual", 1), - ("OpSGreaterThan", 0), ("OpSGreaterThanEqual", 1)): - with self.subTest(op=op, equal=True): - self.assertEqual(run_word(f"%b = {op} %bool %c2 %c2\n%res = OpSelect %uint %b %c1 %c0\n"), want) - - def test_signed_comparisons_use_the_operand_width(self): - # 0x80000000 as a 64-bit operand is positive; as a 32-bit one it is negative. - types = ("%ulong = OpTypeInt 64 0\n%L80 = OpConstant %ulong 2147483648\n%L1 = OpConstant %ulong 1\n" - "%Lneg = OpConstant %ulong 18446744073709551615\n%c8000 = OpConstant %uint 2147483648\n") - header = HEADER.replace("%main = OpFunction", types + "%main = OpFunction") - for a, b, want in (("%L80", "%L1", 1), ("%Lneg", "%L1", 0), ("%c8000", "%c1", 0)): - with self.subTest(a=a, b=b): - body = f"%b = OpSGreaterThan %bool {a} {b}\n%res = OpSelect %uint %b %c1 %c0\n" - self.assertEqual(si.run_fragment(header + body + "OpStore %out %res\n" + FOOTER)["%out"][0], want) - body = ("%x = OpIAdd %ulong %L80 %L80\n%b = OpSGreaterThan %bool %x %L1\n" # a result id keeps its width - "%res = OpSelect %uint %b %c1 %c0\n") - self.assertEqual(si.run_fragment(header + body + "OpStore %out %res\n" + FOOTER)["%out"][0], 1) - def test_add_carry(self): - # 0xFFFFFFFF + 2 = 1, carry 1; 1 + 2 = 3, carry 0 - self.assertEqual(run_word("%s = OpIAddCarry %umul %cFF %c2\n" - "%d = OpCompositeExtract %uint %s 0\n" - "%k = OpCompositeExtract %uint %s 1\n" - "%res = OpBitwiseAnd %uint %d %k\n"), 1) - self.assertEqual(run_word("%s = OpIAddCarry %umul %c1 %c2\n%res = OpCompositeExtract %uint %s 0\n"), 3) - self.assertEqual(run_word("%s = OpIAddCarry %umul %c1 %c2\n%res = OpCompositeExtract %uint %s 1\n"), 0) - - def test_float_mul_ord_equal_findsmsb_sin(self): - self.assertEqual(run_word("%x = OpFMul %float %f2 %f3\n%res = OpBitcast %uint %x\n"), 0x40C00000) - self.assertEqual(run_word("%b = OpFOrdEqual %bool %f2 %f2\n%res = OpSelect %uint %b %c1 %c0\n"), 1) - self.assertEqual(run_word("%nf = OpBitcast %float %cFF\n" - "%b = OpFOrdEqual %bool %nf %nf\n%res = OpSelect %uint %b %c1 %c0\n"), 0) - self.assertEqual(run_word("%res = OpExtInst %uint %glsl FindSMsb %c0\n"), 0xFFFFFFFF) - self.assertEqual(run_word("%res = OpExtInst %uint %glsl FindSMsb %cFF\n"), 0xFFFFFFFF) - self.assertEqual(run_word("%res = OpExtInst %uint %glsl FindSMsb %c80\n"), 7) - self.assertEqual(run_word("%res = OpExtInst %uint %glsl FindSMsb %cF0\n"), 3) - # FindILsb / FindUMsb: bit number of the lowest / highest 1 bit, -1 for 0 (GLSL.std.450). - self.assertEqual(run_word("%res = OpExtInst %uint %glsl FindILsb %c0\n"), 0xFFFFFFFF) - self.assertEqual(run_word("%res = OpExtInst %uint %glsl FindILsb %cF0\n"), 4) - self.assertEqual(run_word("%res = OpExtInst %uint %glsl FindUMsb %c0\n"), 0xFFFFFFFF) - self.assertEqual(run_word("%res = OpExtInst %uint %glsl FindUMsb %cF0\n"), 31) - self.assertEqual(run_word("%res = OpExtInst %uint %glsl FindUMsb %c80\n"), 7) - # UMax / SMin and the clamps compare as the name says: 0xffffffff is the largest unsigned, -1 signed. - self.assertEqual(run_word("%res = OpExtInst %uint %glsl UMax %cFF %c1\n"), 0xFFFFFFFF) - self.assertEqual(run_word("%res = OpExtInst %uint %glsl SMin %cFF %c1\n"), 0xFFFFFFFF) - self.assertEqual(run_word("%res = OpExtInst %uint %glsl UClamp %cFF %c1 %c8\n"), 8) - self.assertEqual(run_word("%res = OpExtInst %uint %glsl SClamp %cFF %c1 %c8\n"), 1) - self.assertEqual(run_word("%res = OpExtInst %uint %glsl SClamp %c4 %cF0 %c8\n"), 4) - with self.assertRaises(si.UnsupportedConstruct): # minVal > maxVal - run_word("%res = OpExtInst %uint %glsl UClamp %c4 %c8 %c1\n") - self.assertEqual(run_word("%b = OpUGreaterThanEqual %bool %c8 %c8\n%res = OpSelect %uint %b %c1 %c0\n"), 1) - self.assertEqual(run_word("%b = OpUGreaterThanEqual %bool %c1 %cFF\n%res = OpSelect %uint %b %c1 %c0\n"), 0) - self.assertEqual(run_word("%x = OpBitcast %float %c0\n%s = OpExtInst %float %glsl Sin %x\n" - "%res = OpBitcast %uint %s\n"), 0) - - def test_bit_reverse_and_sabs(self): - self.assertEqual(run_word("%res = OpBitReverse %uint %c1\n"), 0x80000000) - self.assertEqual(run_word("%res = OpBitReverse %uint %cF0\n"), 0x0FFFFFFF) - self.assertEqual(run_word("%res = OpExtInst %uint %glsl SAbs %cFF\n"), 1) # |-1| - self.assertEqual(run_word("%res = OpExtInst %uint %glsl SAbs %c2\n"), 2) - self.assertEqual(run_word("%m = OpShiftLeftLogical %uint %c1 %c31\n" # |INT_MIN| wraps - "%res = OpExtInst %uint %glsl SAbs %m\n"), 0x80000000) - - def test_forward_branch_and_kill(self): - live = (HEADER + "OpStore %out %c1\nOpSelectionMerge %live None\n" - "OpBranchConditional %t %live %dead\n%dead = OpLabel\nOpKill\n%live = OpLabel\n" + FOOTER) - dead = (HEADER + "OpStore %out %c1\nOpSelectionMerge %live None\n" - "OpBranchConditional %f %live %dead\n%dead = OpLabel\nOpKill\n%live = OpLabel\n" + FOOTER) - self.assertEqual(si.run_fragment(live)["%out"][0], 1) - self.assertEqual(si.run_fragment(dead), {}) - - def test_float_ordered_unordered_and_classify(self): - nan = "%nan = OpBitcast %float %cFF\n" # 0xFFFFFFFF is a NaN - for op, nan_result, ordered_result in (("OpFOrdNotEqual", 0, 1), ("OpFUnordNotEqual", 1, 1), - ("OpFUnordLessThan", 1, 1), ("OpFUnordLessThanEqual", 1, 1), - ("OpFUnordGreaterThan", 1, 0), ("OpFUnordGreaterThanEqual", 1, 0), - ("OpFUnordEqual", 1, 0)): - with self.subTest(op=op): # 2 vs NaN, then 2 vs 3 - self.assertEqual(run_word(nan + f"%b = {op} %bool %f2 %nan\n%res = OpSelect %uint %b %c1 %c0\n"), - nan_result) - self.assertEqual(run_word(f"%b = {op} %bool %f2 %f3\n%res = OpSelect %uint %b %c1 %c0\n"), - ordered_result) - self.assertEqual(run_word(nan + "%b = OpIsNan %bool %nan\n%res = OpSelect %uint %b %c1 %c0\n"), 1) - self.assertEqual(run_word("%b = OpIsNan %bool %f2\n%res = OpSelect %uint %b %c1 %c0\n"), 0) - self.assertEqual(run_word("%i = OpBitcast %float %cInf\n%b = OpIsInf %bool %i\n" - "%res = OpSelect %uint %b %c1 %c0\n"), 1) - self.assertEqual(run_word(nan + "%b = OpIsInf %bool %nan\n%res = OpSelect %uint %b %c1 %c0\n"), 0) - - def test_float_compares_with_equal_operands(self): - # 2 vs 2 for every ordered and unordered relation (asked in review on #262): without this an interpreter - # that dropped the equality part of an Equal / LessThanEqual / GreaterThanEqual compare, or that turned - # NotEqual into "unordered only", would still pass the NaN and 2-vs-3 cases above. - for op, want in (("OpFOrdEqual", 1), ("OpFOrdNotEqual", 0), ("OpFOrdLessThan", 0), - ("OpFOrdLessThanEqual", 1), ("OpFOrdGreaterThan", 0), ("OpFOrdGreaterThanEqual", 1), - ("OpFUnordEqual", 1), ("OpFUnordNotEqual", 0), ("OpFUnordLessThan", 0), - ("OpFUnordLessThanEqual", 1), ("OpFUnordGreaterThan", 0), ("OpFUnordGreaterThanEqual", 1)): - with self.subTest(op=op): - self.assertEqual(run_word(f"%b = {op} %bool %f2 %f2\n%res = OpSelect %uint %b %c1 %c0\n"), want) - # -0.0 equals +0.0 in both families. - for op, want in (("OpFOrdEqual", 1), ("OpFUnordEqual", 1), ("OpFOrdNotEqual", 0), ("OpFUnordNotEqual", 0)): - with self.subTest(op=op, operands="-0.0, +0.0"): - self.assertEqual(run_word("%z = OpBitcast %float %c0\n%n = OpFNegate %float %z\n" - f"%b = {op} %bool %n %z\n%res = OpSelect %uint %b %c1 %c0\n"), want) - - def test_phi_selects_the_value_from_the_taken_predecessor(self): - for cond, want in (("%t", 1), ("%f", 2)): - text = (HEADER + f"OpSelectionMerge %merge None\nOpBranchConditional {cond} %a %b\n" - "%a = OpLabel\nOpBranch %merge\n" - "%b = OpLabel\nOpBranch %merge\n" - "%merge = OpLabel\n%res = OpPhi %uint %c1 %a %c2 %b\n" - "OpStore %out %res\n" + FOOTER) - with self.subTest(cond=cond): - self.assertEqual(si.run_fragment(text)["%out"][0], want) - - def test_phi_without_a_matching_predecessor_names_the_result_and_edge(self): - body = "OpBranch %next\n%next = OpLabel\n%answer = OpPhi %uint %c1 %other\n" - with self.assertRaisesRegex(si.UnsupportedConstruct, r"%answer.*%entry"): - si.run_fragment(HEADER + body + FOOTER) - - def test_phi_before_the_first_label(self): - text = HEADER.replace("%entry = OpLabel\n", "") + "%answer = OpPhi %uint %c1 %other\nOpFunctionEnd\n" - with self.assertRaisesRegex(si.InvalidModule, r"%answer.*start of the function"): - si.run_fragment(text) - - def test_duplicate_phi_result_is_rejected(self): - body = ("OpBranch %next\n%next = OpLabel\n%a = OpPhi %uint %c1 %entry\n" - "%a = OpPhi %uint %c2 %entry\n") - with self.assertRaisesRegex(si.UnsupportedConstruct, r"duplicate.*%a"): - si.run_fragment(HEADER + body + FOOTER) - - def test_phis_of_a_block_take_their_values_together(self): - # A loop header that swaps %a and %b on every back edge: each OpPhi reads the other's value from before - # the block. Three iterations from (1, 2) leave (2, 1); assigning %a first would give %b the new %a, (2, 2). - text = (HEADER.replace('"main" %out', '"main" %out %out2') - .replace("%main = OpFunction", "%out2 = OpVariable %_ptr_Output_uint Output\n" - "%c3 = OpConstant %uint 3\n%main = OpFunction") + - "OpBranch %head\n" - "%head = OpLabel\n" - "%a = OpPhi %uint %c1 %entry %b %cont\n" - "%b = OpPhi %uint %c2 %entry %a %cont\n" - "%i = OpPhi %uint %c0 %entry %inext %cont\n" - "%more = OpULessThan %bool %i %c3\n" - "OpLoopMerge %done %cont None\nOpBranchConditional %more %cont %done\n" - "%cont = OpLabel\n%inext = OpIAdd %uint %i %c1\nOpBranch %head\n" - "%done = OpLabel\nOpStore %out %a\nOpStore %out2 %b\n" + FOOTER) - out = si.run_fragment(text) - self.assertEqual((out["%out"], out["%out2"]), ((2,), (1,))) - lane0 = spirv_wave_interp.run_wave(text, wave=32)["outputs"][0] # the other interpreter agrees - self.assertEqual((lane0["%out"], lane0["%out2"]), ((2,), (1,))) - - def test_function_array_access(self): - self.assertEqual(run_word("%arr_v = OpVariable %_ptr_Function_arr Function %null_arr\n" - "%p = OpAccessChain %_ptr_Function_uint %arr_v %c2\n" - "OpStore %p %cF0\n" - "%q = OpAccessChain %_ptr_Function_uint %arr_v %c2\n" - "%res = OpLoad %uint %q\n"), 0xFFFFFFF0) - - def test_unsupported_constructs_are_rejected(self): - for body in ("%res = OpUDiv %uint %c2 %c1\n", # opcode not modelled - "%res = OpExtInst %uint %glsl Ldexp %c2 %c1\n", # ext inst not modelled - "%res = OpBitFieldUExtract %uint %cFF %c32 %c1\n", # undefined per spec - "%res = OpShiftLeftLogical %uint %cFF %c32\n", # undefined per spec - "%res = OpShiftRightLogical %uint %cFF %c32\n", # undefined per spec - "%x = OpBitcast %float %cFF\n%res = OpConvertFToU %uint %x\n", # NaN: undefined per spec - "%x = OpFNegate %float %f1\n%res = OpConvertFToU %uint %x\n", # negative: out of range - "%x = OpExtInst %float %glsl FClamp %f1 %f2 %f1\n%res = OpBitcast %uint %x\n", # lo > hi - "%res = OpSelect %uint %c1 %c1 %c2\n", # condition not a bool - "OpBranch %entry\n%res = OpCopyObject %uint %c1\n", # unconditional branch - "OpBranchConditional %t %entry %entry\n%res = OpCopyObject %uint %c1\n"): # backward branch - with self.subTest(body=body.splitlines()[0]): - with self.assertRaises(si.UnsupportedConstruct): - run_word(body) - - def test_store_to_push_constant_is_rejected(self): - text = HEADER + "%p = OpAccessChain %_ptr_PC_uint %pc %c0\nOpStore %p %c1\n" + FOOTER - with self.assertRaises(si.UnsupportedConstruct): - si.run_fragment(text) - - # Signalling-NaN words (exponent all ones, bit 22 clear, mantissa not zero), a quiet NaN and two ordinary - # values. Issue #509: going through a Python float set bit 22 of the first four. - SNAN_WORDS = (0xFFA3A095, 0x7F800001, 0x7FBFFFFF, 0xFF800001, 0x7FC00001, 0x3F800000, 0x80000000) - - def test_bitcast_keeps_signalling_nan_bits(self): - # SPIR-V OpBitcast: the bit pattern is unchanged. The word goes uint -> float and on through - # OpCopyObject, a composite, OpSelect and a Function variable before it comes back as a uint and also - # leaves through a float Output; both must be the word that went in. - text = HEADER.replace('OpEntryPoint Fragment %main "main" %out', - 'OpEntryPoint Fragment %main "main" %out %outf').replace( - "%main = OpFunction", - "%_ptr_Output_float = OpTypePointer Output %float\n%outf = OpVariable %_ptr_Output_float Output\n" - "%_ptr_Function_float = OpTypePointer Function %float\n%main = OpFunction") - body = ("%fv = OpVariable %_ptr_Function_float Function\n" - "%p = OpAccessChain %_ptr_PC_uint %pc %c0\n" - "%w = OpLoad %uint %p\n" - "%x = OpBitcast %float %w\n" - "%y = OpCopyObject %float %x\n" - "%v = OpCompositeConstruct %v2float %f1 %y\n" - "%e = OpCompositeExtract %float %v 1\n" - "%s = OpSelect %float %t %e %f2\n" - "OpStore %fv %s\n" - "%l = OpLoad %float %fv\n" - "OpStore %outf %l\n" - "%res = OpBitcast %uint %l\n" - "OpStore %out %res\n") - for word in self.SNAN_WORDS: - with self.subTest(word=f"{word:#010x}"): - out = si.run_fragment(text + body + FOOTER, push_constants=[word]) - self.assertEqual(out["%out"], (word,)) - self.assertEqual(out["%outf"], (word,)) - - def test_bitcast_signalling_nan_is_still_a_nan(self): - # The value keeps its bits but is still a float NaN to the float operations (OpIsNan, OpFOrdEqual). - text = HEADER.replace("%main = OpFunction", "%cS = OpConstant %uint 4288913557\n%main = OpFunction") - for body, want in (("%x = OpBitcast %float %cS\n%n = OpIsNan %bool %x\n", 1), - ("%x = OpBitcast %float %cS\n%n = OpFOrdEqual %bool %x %x\n", 0)): - with self.subTest(body=body.splitlines()[1]): - out = si.run_fragment(text + body + "%res = OpSelect %uint %n %c1 %c0\nOpStore %out %res\n" - + FOOTER) - self.assertEqual(out["%out"], (want,)) - - def test_float_arithmetic_on_signalling_nan_gives_a_nan(self): - # Arithmetic drops the kept pattern: SPIR-V does not fix the bits of a NaN result, so only "a NaN" is - # asserted (exponent all ones, mantissa not zero). - text = HEADER.replace("%main = OpFunction", "%cS = OpConstant %uint 4288913557\n%main = OpFunction") - for op in ("%y = OpFAdd %float %x %f1\n", "%y = OpFMul %float %x %f2\n", "%y = OpFNegate %float %x\n"): - with self.subTest(op=op.split()[2]): - word = si.run_fragment(text + "%x = OpBitcast %float %cS\n" + op + - "%res = OpBitcast %uint %y\nOpStore %out %res\n" + FOOTER)["%out"][0] - self.assertEqual(word & 0x7F800000, 0x7F800000) - self.assertNotEqual(word & 0x007FFFFF, 0) - - def test_push_constant_reads_zero(self): - text = HEADER + "%p = OpAccessChain %_ptr_PC_uint %pc %c0\n%res = OpLoad %uint %p\nOpStore %out %res\n" + FOOTER - self.assertEqual(si.run_fragment(text)["%out"][0], 0) - - def test_a_module_run_twice_gives_the_same_words_and_the_same_parse_error(self): - # run_workgroup runs one generator per invocation over one text: each must see the same module. - text = HEADER + "%res = OpIAdd %uint %c1 %c2\nOpStore %out %res\n" + FOOTER - self.assertEqual(si.run_fragment(text)["%out"][0], 3) - self.assertEqual(si.run_fragment(text)["%out"][0], 3) - broken = HEADER + "%res = OpIAdd %uint %c1 %c2\nthis is not an instruction\n" + FOOTER - for _ in range(2): - with self.assertRaises(si.UnsupportedConstruct) as ctx: - si.run_fragment(broken) - self.assertIn("this is not an instruction", str(ctx.exception)) - - -class AggregateValueTests(unittest.TestCase): - HEADER = """\ -OpCapability Shader -OpMemoryModel Logical GLSL450 -OpEntryPoint Fragment %main "main" %out -OpExecutionMode %main OriginUpperLeft -OpDecorate %out Location 0 -%void = OpTypeVoid -%fn = OpTypeFunction %void -%uint = OpTypeInt 32 0 -%v2uint = OpTypeVector %uint 2 -%zero = OpConstant %uint 0 -%one = OpConstant %uint 1 -%seven = OpConstant %uint 7 -%array = OpTypeArray %uint %one -%nested = OpTypeArray %array %one -%null_array = OpConstantNull %array -%null_nested = OpConstantNull %nested -%const_array = OpConstantComposite %array %zero -%ptr_array = OpTypePointer Function %array -%ptr_nested = OpTypePointer Function %nested -%ptr_word = OpTypePointer Function %uint -%ptr_output = OpTypePointer Output %v2uint -%out = OpVariable %ptr_output Output -%main = OpFunction %void None %fn -%entry = OpLabel -""" - - def test_whole_array_store_does_not_alias_its_operand(self): - body = """\ -%src = OpVariable %ptr_array Function %null_array -%dst = OpVariable %ptr_array Function %null_array -%saved = OpLoad %array %src -OpStore %dst %saved -%element = OpAccessChain %ptr_word %dst %zero -OpStore %element %seven -%old = OpCompositeExtract %uint %saved 0 -%new = OpLoad %uint %element -%result = OpCompositeConstruct %v2uint %old %new -OpStore %out %result -""" - self.assertEqual(si.run_fragment(self.HEADER + body + FOOTER)["%out"], (0, 7)) - - def test_nested_array_load_keeps_its_original_elements(self): - body = """\ -%src = OpVariable %ptr_nested Function %null_nested -%saved = OpLoad %nested %src -%element = OpAccessChain %ptr_word %src %zero %zero -OpStore %element %seven -%old = OpCompositeExtract %uint %saved 0 0 -%new = OpLoad %uint %element -%result = OpCompositeConstruct %v2uint %old %new -OpStore %out %result -""" - self.assertEqual(si.run_fragment(self.HEADER + body + FOOTER)["%out"], (0, 7)) - - def test_shared_nested_initializer_creates_separate_storage(self): - body = """\ -%src = OpVariable %ptr_nested Function %null_nested -%other = OpVariable %ptr_nested Function %null_nested -%element = OpAccessChain %ptr_word %src %zero %zero -OpStore %element %seven -%independent = OpAccessChain %ptr_word %other %zero %zero -%old = OpLoad %uint %independent -%new = OpLoad %uint %element -%result = OpCompositeConstruct %v2uint %old %new -OpStore %out %result -""" - self.assertEqual(si.run_fragment(self.HEADER + body + FOOTER)["%out"], (0, 7)) - - def test_array_constant_store_preserves_the_constant(self): - body = """\ -%dst = OpVariable %ptr_array Function -OpStore %dst %const_array -%element = OpAccessChain %ptr_word %dst %zero -OpStore %element %seven -%old = OpCompositeExtract %uint %const_array 0 -%new = OpLoad %uint %element -%result = OpCompositeConstruct %v2uint %old %new -OpStore %out %result -""" - self.assertEqual(si.run_fragment(self.HEADER + body + FOOTER)["%out"], (0, 7)) - - -class MeshOutputTests(unittest.TestCase): - """A mesh shader's outputs (SPV_EXT_mesh_shader): arrays of vectors and of a Block struct holding a bool, and - OpSetMeshOutputsEXT, whose counts the result reports under its name.""" - HEADER = """\ -OpCapability MeshShadingEXT -OpExtension "SPV_EXT_mesh_shader" -OpMemoryModel Logical GLSL450 -OpEntryPoint MeshEXT %main "main" %idx %cull -OpExecutionMode %main LocalSize 1 1 1 -OpExecutionMode %main OutputVertices 3 -OpExecutionMode %main OutputPrimitivesEXT 2 -OpExecutionMode %main OutputTrianglesEXT -OpDecorate %idx BuiltIn PrimitiveTriangleIndicesEXT -OpDecorate %blk Block -OpMemberDecorate %blk 0 BuiltIn CullPrimitiveEXT -OpMemberDecorate %blk 0 PerPrimitiveEXT -%void = OpTypeVoid -%fn = OpTypeFunction %void -%uint = OpTypeInt 32 0 -%bool = OpTypeBool -%v3uint = OpTypeVector %uint 3 -%c0 = OpConstant %uint 0 -%c1 = OpConstant %uint 1 -%c2 = OpConstant %uint 2 -%c3 = OpConstant %uint 3 -%true = OpConstantTrue %bool -%arr_idx = OpTypeArray %v3uint %c2 -%blk = OpTypeStruct %bool -%arr_cull = OpTypeArray %blk %c2 -%ptr_idx = OpTypePointer Output %arr_idx -%ptr_cull = OpTypePointer Output %arr_cull -%ptr_v3 = OpTypePointer Output %v3uint -%ptr_bool = OpTypePointer Output %bool -%idx = OpVariable %ptr_idx Output -%cull = OpVariable %ptr_cull Output -%tri = OpConstantComposite %v3uint %c0 %c1 %c2 -%main = OpFunction %void None %fn -%entry = OpLabel -""" - BODY = """\ -%p = OpAccessChain %ptr_v3 %idx %c1 -OpStore %p %tri -%q = OpAccessChain %ptr_bool %cull %c1 %c0 -OpStore %q %true -""" - - def test_counts_and_arrayed_outputs(self): - out = si.run_fragment(self.HEADER + "OpSetMeshOutputsEXT %c3 %c2\n" + self.BODY + FOOTER) - self.assertEqual(out["OpSetMeshOutputsEXT"], (3, 2)) - self.assertEqual(out["%idx"], (0, 0, 0, 0, 1, 2)) # element 1 written, element 0 still zero - self.assertEqual(out["%cull"], (0, 1)) # the Block's bool member, per primitive - - def test_no_counts_before_the_instruction_runs(self): - self.assertNotIn("OpSetMeshOutputsEXT", si.run_fragment(self.HEADER + self.BODY + FOOTER)) - - def test_a_second_call_is_rejected(self): - twice = "OpSetMeshOutputsEXT %c3 %c2\nOpSetMeshOutputsEXT %c3 %c2\n" - with self.assertRaisesRegex(si.InvalidModule, "second time"): - si.run_fragment(self.HEADER + twice + FOOTER) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_interp_computed_ij.py b/tests/semantic/test_interp_computed_ij.py deleted file mode 100644 index 7b30f29f7..000000000 --- a/tests/semantic/test_interp_computed_ij.py +++ /dev/null @@ -1,315 +0,0 @@ -"""SHADER-177: v_interp_p1/p2 through a barycentric pair the program computed. - -Hardware weights the interpolation with the values the operand VGPRs hold at the two ops, not with the -hardware's own pair: Vonsek measured it on RDNA2 (#1224, synthetic 64x64 triangle, attr (0,0)/(2,0)/(0,2)) --- zeroing v0/v1 before the interp renders (0,0), i.e. P0, on every pixel, and reading the pair through -swapped copies renders (v,u). The single-lane model used to ignore the operand, so those translated as the -centre interpolation. Now the pair's attribute is read per-vertex and weighted with the operand values: - -* a v_mov of a constant into v0/v1 (snapped coordinates, the zero form of the evidence above); -* arithmetic on the saved pair (evaluate-at-offset: J' = J / 2 halves the second weight); -* copies in either role, swapped included -- as writes into the operand registers; a pristine plain - copy of the pair stays #1224's model (centre interpolation, bit-identical .spv); -* the corpus form where J is written between the p1 and the p2: the p1's I is kept and the p2's J is - loaded fresh, because hardware's final value uses the I of the p1 with the J of the p2; -* v_interp_mov_f32 still reads the provoking vertex when the location also has computed p1/p2. - -Refused instead of guessed (Unsupported, naming the pattern): a source that is neither v0/v1 nor -written, or a pristine copy in the wrong role, is the #1224 guard's refusal (interp_pair_src, at -emission); here: a computed pair whose p1 partial is rewritten or read between the ops (its hardware value P10*I is then -observable), one whose ops are not in a single basic block (the captured I would not dominate the p2), a -dangling op without its partner, and any computed pair under --bary-fallback, which has no PerVertexKHR -inputs. A pristine pair (v0/v1 nothing writes) keeps the interpolated-input read: no PerVertexKHR. - -Pipodi's straight-line scan over the corpus found the affected 213 PS (upper bound; issue #1218, -comment 7076614458); the classification and counts are in docs/design.md's SHADER-177 row. -""" -import struct -import unittest - -import support -import rdna2spirv - -# Barycentric weights of vertices 0, 1, 2 as Vulkan hands them over ((k, i, j); AMD's i, j are .y/.z). -BARY = (0.25, 0.25, 0.5) -I, J = BARY[1], BARY[2] -# Vonsek's triangle: attr0.x = u = 0/2/0, attr0.y = v = 0/0/2, plus channels for the mov and snap checks. -UV = ((0.0, 0.0, 1.0, 0.0), (2.0, 0.0, 3.0, 0.0), (0.0, 2.0, 5.0, 0.0)) -ATTR0 = [tuple(struct.unpack(" None: - _, words = run(["v_swap_b32 v0, v1", "exp mrt0 v0, v1, v0, v1 done vm", "s_endpgm"]) - self.assertEqual(floats(words), (J, I, J, I)) - - def test_swap_overwrites_interpolation_weight_in_second_operand(self) -> None: - # A copy of I ceases to be pristine too when it is the second operand of the swap. - for weight in ("v0", "v8"): - with self.subTest(weight=weight): - setup = ["v_mov_b32 v8, v0"] if weight == "v8" else [] - _, words = run(setup + [ - "v_mov_b32 v6, 0.125", f"v_swap_b32 v6, {weight}", - f"v_interp_p1_f32 v2, {weight}, attr0.x", "v_interp_p2_f32 v2, v1, attr0.x", - f"v_interp_p1_f32 v3, {weight}, attr0.y", "v_interp_p2_f32 v3, v1, attr0.y", - "exp mrt0 v2, v3, v6, v2 done vm", "s_endpgm", - ]) - self.assertEqual(floats(words), (0.25, 2 * J, I, 0.25)) - - def test_zeroed_pair_reads_the_provoking_vertex(self): - """Vonsek's zero-source row: I' = J' = 0 interpolate to P0 = (0, 0) on every pixel.""" - _, w = run(["v_mov_b32_e32 v0, 0", "v_mov_b32_e32 v1, 0", - "v_interp_p1_f32_e32 v2, v0, attr0.x", "v_interp_p2_f32_e32 v2, v1, attr0.x", - "v_interp_p1_f32_e32 v3, v0, attr0.y", "v_interp_p2_f32_e32 v3, v1, attr0.y", - "exp mrt0 v2, v3, v2, v3 done vm", "s_endpgm"]) - self.assertEqual(floats(w[:2]), (0.0, 0.0)) - - def test_constant_pair_snaps_to_a_point(self): - """Snapped coordinates: I' = J' = 0.25 pick the point a quarter along both edges.""" - _, w = run(["v_mov_b32_e32 v0, 0.25", "v_mov_b32_e32 v1, 0.25", - "v_interp_p1_f32_e32 v2, v0, attr0.x", "v_interp_p2_f32_e32 v2, v1, attr0.x", - "v_interp_p1_f32_e32 v3, v0, attr0.y", "v_interp_p2_f32_e32 v3, v1, attr0.y", - "v_interp_p1_f32_e32 v4, v0, attr0.z", "v_interp_p2_f32_e32 v4, v1, attr0.z", - "exp mrt0 v2, v3, v4, v2 done vm", "s_endpgm"]) - # P = 0.5*P0 + 0.25*P1 + 0.25*P2 - self.assertEqual(floats(w[:3]), (0.5, 0.5, 2.5)) - - def test_arithmetic_pair_evaluates_at_an_offset(self): - """Evaluate-at-offset: keeping I and halving J halves the second weight (u stays, v halves).""" - _, w = run(["v_mov_b32_e32 v10, v0", "v_mul_f32_e32 v11, 0.5, v1", - "v_mov_b32_e32 v0, v10", "v_mov_b32_e32 v1, v11", - "v_interp_p1_f32_e32 v2, v0, attr0.x", "v_interp_p2_f32_e32 v2, v1, attr0.x", - "v_interp_p1_f32_e32 v3, v0, attr0.y", "v_interp_p2_f32_e32 v3, v1, attr0.y", - "exp mrt0 v2, v3, v2, v3 done vm", "s_endpgm"]) - self.assertEqual(floats(w[:2]), (2 * I, J)) - - def test_swapped_copies_swap_the_weights(self): - """Vonsek's role-swap row as a computed pair: the saved J is written into v0 and the saved I - into v1, so the p1 weights with J and the p2 with I: (v, u). Pristine copies read in swapped - roles carry no computed value and stay the #1224 guard's refusal (root-role enforced).""" - _, w = run(["v_mov_b32_e32 v14, v1", "v_mov_b32_e32 v15, v0", # save J, save I - "v_mov_b32_e32 v0, v14", "v_mov_b32_e32 v1, v15", # swap into the operands - "v_interp_p1_f32_e32 v2, v0, attr0.x", "v_interp_p2_f32_e32 v2, v1, attr0.x", - "v_interp_p1_f32_e32 v3, v0, attr0.y", "v_interp_p2_f32_e32 v3, v1, attr0.y", - "exp mrt0 v2, v3, v2, v3 done vm", "s_endpgm"]) - self.assertEqual(floats(w[:2]), (2 * J, 2 * I)) - - def test_j_written_between_the_ops(self): - """The corpus form: the p1 runs with I already computed, and J is set up between the two ops.""" - _, w = run(["v_mov_b32_e32 v16, 1.0", "v_mov_b32_e32 v0, v15", # I' = 0 (v15 never written) - "v_interp_p1_f32_e32 v2, v0, attr0.x", - "v_mul_f32_e32 v1, 0.25, v16", # J' written after the p1 - "v_interp_p2_f32_e32 v2, v1, attr0.x", - "v_interp_p1_f32_e32 v3, v0, attr0.y", - "v_mul_f32_e32 v1, 0.5, v16", - "v_interp_p2_f32_e32 v3, v1, attr0.y", - "exp mrt0 v2, v3, v2, v3 done vm", "s_endpgm"]) - # x: 0 + 0*2 + 0.25*0 = 0; y: 0 + 0*0 + 0.5*2 = 1 - self.assertEqual(floats(w[:2]), (0.0, 1.0)) - - def test_mov_reads_the_provoking_vertex_of_a_computed_location(self): - """v_interp_mov_f32 of a location the computed pair also reads still gives vertex 0's value - (1.0; the perspective interpolation of 1/3/5 at these weights is 3.5).""" - _, w = run(["v_mov_b32_e32 v0, 0", "v_mov_b32_e32 v1, 0", - "v_interp_p1_f32_e32 v2, v0, attr0.x", "v_interp_p2_f32_e32 v2, v1, attr0.x", - "v_interp_mov_f32_e32 v3, p0, attr0.z", - "exp mrt0 v2, v3, v2, v3 done vm", "s_endpgm"]) - self.assertEqual(floats(w[:2]), (0.0, 1.0)) - - def test_f16_pair_through_a_computed_pair(self): - """The f16 forms weight with the computed pair too, both halves.""" - LO, HI = (0.5, 1.5, 2.5), (-4.0, 8.0, 16.0) - pack = lambda lo, hi: struct.unpack(" int: - return struct.unpack(" omod before clamp) - shader = """ -v_interp_p1_f32 v2, v0, attr0.x -v_interp_p2_f32_e64 v2, v1, attr0.x clamp -v_interp_p1_f32 v3, v0, attr0.y -v_interp_p2_f32_e64 v3, v1, attr0.y clamp -v_interp_p1_f32 v4, v0, attr0.z -v_interp_p2_f32_e64 v4, v1, attr0.z mul:2 -v_interp_p1_f32 v5, v0, attr0.w -v_interp_p2_f32_e64 v5, v1, attr0.w mul:2 clamp -exp mrt0 v2, v3, v4, v5 done vm -s_endpgm -""" - words = support.mrt0_words( - translate(shader), - inputs={"%in_attr0": (1.5, -0.25, 0.375, 0.625), "%in_attr1": (0.0,) * 4}, - ) - self.assertEqual(words, [fbits(1.0), fbits(0.0), fbits(0.75), fbits(1.0)]) - - def test_interp_p2_mul4_div2_and_mov_f32(self): - # attr0 = (0.25, 3.0, 0.0, 0.0), attr1 = (1.5, -0.5, 0.25, 4.0) (attr1 read only via mov -> Flat) - shader = """ -v_interp_p1_f32 v2, v0, attr0.x -v_interp_p2_f32_e64 v2, v1, attr0.x mul:4 -v_interp_p1_f32 v3, v0, attr0.y -v_interp_p2_f32_e64 v3, v1, attr0.y div:2 -v_interp_mov_f32_e64 v4, p0, attr1.x clamp -v_interp_mov_f32_e64 v5, p0, attr1.x div:2 clamp -exp mrt0 v2, v3, v4, v5 done vm -s_endpgm -""" - words = support.mrt0_words( - translate(shader, name="ps_interp_mov_f32_mods"), - inputs={"%in_attr0": (0.25, 3.0, 0.0, 0.0), "%in_attr1": (1.5, -0.5, 0.25, 4.0)}, - ) - self.assertEqual(words, [fbits(1.0), fbits(1.5), fbits(1.0), fbits(0.75)]) - - def test_plain_interp_without_mods_unchanged(self): - shader = """ -v_interp_p1_f32 v2, v0, attr0.x -v_interp_p2_f32 v2, v1, attr0.x -v_interp_p1_f32 v3, v0, attr0.y -v_interp_p2_f32 v3, v1, attr0.y -v_interp_mov_f32 v4, p0, attr1.x -v_mov_b32 v5, 0 -exp mrt0 v2, v3, v4, v5 done vm -s_endpgm -""" - words = support.mrt0_words( - translate(shader, name="ps_interp_plain"), - inputs={"%in_attr0": (1.5, -0.25, 0.0, 0.0), "%in_attr1": (2.5, 0.0, 0.0, 0.0)}, - ) - self.assertEqual(words, [fbits(1.5), fbits(-0.25), fbits(2.5), 0]) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_interp_guards.py b/tests/semantic/test_interp_guards.py deleted file mode 100644 index 08da4156d..000000000 --- a/tests/semantic/test_interp_guards.py +++ /dev/null @@ -1,226 +0,0 @@ -"""SHADER-177: v_interp reads the barycentric pair through its VGPR source (I = v0, J = v1), and -v_interp_mov_f32 names the vertex with p0 (p10/p20 would be the other two vertices). The single-lane -model returns the attribute's own value, which is only that when the operand really holds the pair, -so anything else is refused instead of silently translating wrong (docs/design.md, PS system inputs): - -* v_interp_p1/p2 (f32 and f16 forms) must read their OWN coordinate of the pair — p1 reads I = v0, - p2 reads J = v1, per op — as the hardware register or a qualifying copy: anything else, including a - swapped p1(v1)/p2(v0) pair or both-v0, -> Unsupported naming the register and the role (the corpus - has none: 117,001 v0 and 116,997 v1 over 26,503 shaders); -* v_interp_mov_f32 with p10/p20 was refused here; it is now modelled as P1 - P0 / P2 - P0 - (test_interp_mov_delta.py; all 6,926 in the corpus are p0); -* a plain v_mov_b32 copy of the op's coordinate (rooted at v0 for p1, at v1 for p2) is still accepted, - including a chain of copies: its single write in the whole shader is the mov, and its source v0/v1 - is itself unwritten up to the copy (a copy of an already-overwritten v0/v1 carries a computed value — - the zero-before-copy measurement renders (0,0) on hardware — while zeroing after the copy is fine, - the copy saved the value). One corpus shader reads its J through a copy of v1 and must keep - translating (bit-identical .spv); -* a register written twice (the mov, then anything else) no longer qualifies — and since the - computed-I/J model landed, a written-again register, a copy of an already-overwritten v0/v1, or a - modified (dpp) mov is no longer refused but modelled: the operand is a value the program wrote, - and the model weights the interpolation with the value loaded from %vgpr (Vonsek's zero-before-copy - row renders P0, which is exactly those loads' result). A pristine copy in the wrong role stays - refused: it carries no computed value to model; -* the standard forms (v0/v1 pairs, p0 mov) translate and compute exactly as before. - -On main (before the guards) the refused cases translated silently and passed spirv-val: the operand -was ignored outright, so a second-pair I/J produced the very module of the standard pair. -""" -import struct -import unittest - -import support -import rdna2spirv - -ATTR0 = (0.5, 0.25, 0.0, 1.0) -FLAT_ATTR1_X = 0x101 # attr1.x read through v_interp_mov only: the provoking vertex's word -BARY = (0.25, 0.25, 0.5) # (k, i, j): the weights the interpreter seeds v0/v1 from (.y/.z) -# Three DISTINCT vertices of attr0 (raw words), so a test's weights are visible in the result. -VERTS0 = ((0.0, 0.0, 1.0, 0.0), (2.0, 0.0, 3.0, 0.0), (0.0, 2.0, 5.0, 0.0)) - - -def f32_bits(x): - return struct.unpack(" (u, v). - lines = ["v_mov_b32_e32 v6, v0", "v_mov_b32_e32 v7, v6", "v_mov_b32_e32 v8, v1", - "v_interp_p1_f32_e32 v2, v7, attr0.x", - "v_interp_p2_f32_e32 v2, v8, attr0.x", - "exp mrt0 v2, v2, v2, v2 done vm", - "s_endpgm"] - spv = support.translate_lines("ps_rolk", lines) - words = support.mrt0_words(spv, inputs={"%in_attr0": ATTR0}) - self.assertEqual(words, [f32_bits(ATTR0[0])] * 4) - - def test_copy_saves_pair_from_later_zero(self): - # Vonsek measurement row 2: copy v0/v1 out first, then zero them, read through the copies - # -> (u, v): the copy saved the value, a write to the source after the copy does not - # disqualify it. - lines = ["v_mov_b32_e32 v6, v0", "v_mov_b32_e32 v7, v1", - "v_mov_b32_e32 v0, 0", "v_mov_b32_e32 v1, 0", - "v_interp_p1_f32_e32 v2, v6, attr0.x", - "v_interp_p2_f32_e32 v2, v7, attr0.x", - "exp mrt0 v2, v2, v2, v2 done vm", - "s_endpgm"] - spv = support.translate_lines("ps_rols", lines) - words = support.mrt0_words(spv, inputs={"%in_attr0": ATTR0}) - self.assertEqual(words, [f32_bits(ATTR0[0])] * 4) - - def test_copy_of_overwritten_source_is_computed(self): - # Vonsek measurement row 3: zeroing v0/v1 BEFORE the copy means the copy carries the - # computed (0) value, not the barycentric pair — hardware renders (0,0) = P0 — so the copy - # no longer qualifies for the guard. The computed-I/J model represents it exactly: the - # operand loads read the zeros the program wrote, and the weights (0, 0) pick vertex 0. - # (The corpus's one copy PS copies v1 while it is still unwritten, then overwrites it: the - # saved-copy case above, which keeps translating untouched by this.) - spv = support.translate_lines("ps_rolz", ["v_mov_b32_e32 v0, 0", "v_mov_b32_e32 v1, 0", - "v_mov_b32_e32 v6, v0", "v_mov_b32_e32 v7, v1", - "v_interp_p1_f32_e32 v2, v6, attr0.x", - "v_interp_p2_f32_e32 v2, v7, attr0.x", - "exp mrt0 v2, v2, v2, v2 done vm", - "s_endpgm"]) - words = support.mrt0_words(spv, inputs=support.varyings(spv, {0: WORDS0}, BARY)) - self.assertEqual(words, [f32_bits(VERTS0[0][0])] * 4) # weights (0, 0): the provoking vertex - self.assertIn("PerVertexKHR", spv) - - def test_standard_pairs_and_p0_mov_unchanged(self): - spv = support.translate_lines("ps_std", ["v_interp_p1_f32_e32 v2, v0, attr0.x", - "v_interp_p2_f32_e32 v2, v1, attr0.x", - "v_interp_mov_f32_e32 v3, p0, attr1.x", - "exp mrt0 v2, v3, v3, v3 done vm", - "s_endpgm"]) - words = support.mrt0_words(spv, inputs={"%in_attr0": ATTR0, "%in_attr1": (FLAT_ATTR1_X,) * 4}) - self.assertEqual(words, [f32_bits(ATTR0[0]), FLAT_ATTR1_X, FLAT_ATTR1_X, FLAT_ATTR1_X]) - self.assertIn("OpDecorate %in_attr1 Flat", spv) # mov-only input stays Flat - self.assertNotIn("OpDecorate %in_attr0 Flat", spv) - - def test_f16_standard_forms_still_translate(self): - spv = support.translate_lines("ps_f16", ["v_interp_p1ll_f16 v4, v0, attr1.x", - "v_interp_p2_f16 v4, v1, attr1.x, v4", - "exp mrt0 v4, v4, v4, v4 done vm", - "s_endpgm"]) - self.assertIn("OpEntryPoint Fragment", spv) - - def test_guard_uses_the_copy_analysis(self): - # Mutation check: with interp_copy_sources returning nothing, the copy case no longer takes - # the guard's centre-interpolated path; it falls through to the computed-I/J model - # (PerVertexKHR + operand loads), proving the acceptance above really flows through the - # tracking and not through a vacuous guard. Either path is exact for a real copy. - lines = ["v_mov_b32_e32 v6, v1", - "v_interp_p1_f32_e32 v2, v0, attr0.x", - "v_interp_p2_f32_e32 v2, v6, attr0.x", - "exp mrt0 v2, v2, v2, v2 done vm", - "s_endpgm"] - self.assertNotIn("PerVertexKHR", support.translate_lines("ps_vc", lines)) - orig = rdna2spirv.interp_copy_sources - rdna2spirv.interp_copy_sources = lambda insns: {} - try: - self.assertIn("PerVertexKHR", support.translate_lines("ps_vc", lines)) - finally: - rdna2spirv.interp_copy_sources = orig - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_interp_merge_check.py b/tests/semantic/test_interp_merge_check.py deleted file mode 100644 index 22156da60..000000000 --- a/tests/semantic/test_interp_merge_check.py +++ /dev/null @@ -1,149 +0,0 @@ -"""spirv_mini_interp and spirv_wave_interp reject a module that breaks spirv-val's merge or phi rule. - -OpSelectionMerge must directly precede OpBranchConditional / OpSwitch, and OpLoopMerge directly precede OpBranch / -OpBranchConditional (SPIR-V 2.16.2). Both interpreters used to skip merges, so #1633's first version, with an -`OpLoad %active` between the merge and its branch, passed every semantic test while spirv-val rejected every module -it produced (found by @mokkymiah, confirmed by @Impre-visible). Each case takes a translated module, which the -interpreters run, and moves one instruction to sit between a merge and its branch. Standard library only. -""" -import os -import re -import sys -import unittest - -HERE = os.path.dirname(os.path.abspath(__file__)) -sys.dont_write_bytecode = True -sys.path.insert(0, HERE) - -from test_salu64_bitwise_data import translate_ps # noqa: E402 (also puts tools/ on sys.path) -import spirv_mini_interp as si # noqa: E402 -import spirv_wave_interp as wi # noqa: E402 - -LINES = ["v_mbcnt_lo_u32_b32 v4, -1, 0", "v_cmpx_gt_u32_e32 5, v4", "v_mov_b32 v0, 1.0", - "exp mrt0 v0, v0, v0, v0 done vm", "s_endpgm"] - - -def spv(): - text = translate_ps(LINES) - assert text.count("OpSelectionMerge") >= 1 - return text - - -def break_merge(text): - """Put the instruction just before the first OpSelectionMerge between it and its branch.""" - lines = text.splitlines() - k = next(i for i, ln in enumerate(lines) if ln.strip().startswith("OpSelectionMerge")) - assert re.match(r"\s*%\S+ = Op", lines[k - 1]), lines[k - 1] - lines[k - 1], lines[k] = lines[k], lines[k - 1] - return "\n".join(lines) + "\n" - - -def drop_branch(text): - """Remove the branch after the first OpSelectionMerge, so the merge is followed by something else.""" - lines = text.splitlines() - k = next(i for i, ln in enumerate(lines) if ln.strip().startswith("OpSelectionMerge")) - return "\n".join(lines[:k + 1] + lines[k + 2:]) + "\n" - - -class MergeRule(unittest.TestCase): - def test_translated_module_runs(self): - text = spv() - self.assertEqual(si.run_fragment(text)["%out_mrt0"][0], 0x3F800000) - self.assertEqual(len(wi.run_wave(text, wave=32)["outputs"]), 32) - - def test_instruction_between_merge_and_branch(self): - bad = break_merge(spv()) - with self.assertRaisesRegex(si.InvalidModule, "OpSelectionMerge"): - si.run_fragment(bad) - with self.assertRaisesRegex(wi.InvalidModule, "OpSelectionMerge"): - wi.run_wave(bad, wave=32) - - def test_merge_without_its_branch(self): - bad = drop_branch(spv()) - with self.assertRaises(si.InvalidModule): - si.run_fragment(bad) - with self.assertRaises(wi.InvalidModule): - wi.run_wave(bad, wave=32) - - def test_loop_merge_rule(self): - ok = [(None, "OpLoopMerge", [], "OpLoopMerge %m %c None"), (None, "OpBranch", [], "OpBranch %h")] - si.check_structure(ok) - with self.assertRaisesRegex(si.InvalidModule, "OpLoopMerge"): - si.check_structure([ok[0], (None, "OpIAdd", [], "%x = OpIAdd %uint %a %b"), ok[1]]) - with self.assertRaisesRegex(si.InvalidModule, "end of the function"): - si.check_structure([ok[0]]) - - -CS_LINES = ["v_mov_b32_e32 v1, 0x40", "global_load_dword v2, v1, s[0:1]", "s_waitcnt vmcnt(0)", - "v_mov_b32_e32 v3, 0", "buffer_store_dword v2, v3, s[0:3], 0 offen", "s_endpgm"] - - -def cs_spv(): - from test_salu64_bitwise_data import translate_cs - text = translate_cs(CS_LINES) - assert " = OpPhi " in text - return text - - -def run_cs(text): - mem = {0x40: 0x1234} - si.run_workgroup(text, 1, 64, inputs_for=lambda i: {"%wg_id": (0, 0, 0), "%local_id": (i, 0, 0), "%sg_lane": i}, - push_constants=[0, 0, 0x1000, 0x31016FAC] + [0] * 32, memory=mem) - return mem - - -class PhiRule(unittest.TestCase): - """OpPhi must be the first instructions of its block: only OpLabel or OpPhi before it (SPIR-V 2.16.2).""" - - def test_translated_module_runs(self): - self.assertEqual(run_cs(cs_spv())[0], 0x1234) - - def test_phi_after_another_instruction(self): - lines = cs_spv().splitlines() - k = next(i for i, ln in enumerate(lines) if " = OpPhi " in ln) - lines[k], lines[k + 1] = lines[k + 1], lines[k] # the phi now follows a non-phi instruction - bad = "\n".join(lines) + "\n" - with self.assertRaisesRegex(si.InvalidModule, "OpPhi"): - run_cs(bad) - - def test_rule_directly(self): - lab = (None, "OpLabel", [], "%b = OpLabel") - phi = ("%p", "OpPhi", [], "%p = OpPhi %uint %a %x %c %y") - add = ("%q", "OpIAdd", [], "%q = OpIAdd %uint %a %a") - si.check_structure([lab, phi, phi, add]) - with self.assertRaisesRegex(si.InvalidModule, "OpPhi"): - si.check_structure([lab, add, phi]) - with self.assertRaisesRegex(wi.InvalidModule, "OpPhi"): - wi.run_wave("OpFunction %void None %f\n%b = OpLabel\n%q = OpIAdd %uint %a %a\n" - "%p = OpPhi %uint %a %x %c %y\nOpReturn\nOpFunctionEnd\n", wave=32) - - -class FunctionVariableRule(unittest.TestCase): - """A Function-storage OpVariable belongs in the function's first block (SPIR-V 2.16.1).""" - - def test_rule_directly(self): - lab = (None, "OpLabel", [], "%b = OpLabel") - var = ("%v", "OpVariable", ["%_ptr_Function_uint", "Function"], "%v = OpVariable %_ptr_Function_uint Function") - br = (None, "OpBranch", ["%c"], "OpBranch %c") - si.check_structure([lab, var, br, lab]) - with self.assertRaisesRegex(si.InvalidModule, "first block"): - si.check_structure([lab, br, lab, var]) - # a new function starts counting again - fn = ("%f", "OpFunction", [], "%f = OpFunction %void None %t") - si.check_structure([fn, lab, br, lab, fn, lab, var]) - - def test_translated_module_with_a_variable_moved(self): - lines = cs_spv().splitlines() - k = next(i for i, ln in enumerate(lines) if " OpVariable " in ln and " Function" in ln) - var = lines.pop(k) - last_label = max(i for i, ln in enumerate(lines) if ln.strip().endswith("= OpLabel")) - lines.insert(last_label + 1, var) - bad = "\n".join(lines) + "\n" - with self.assertRaisesRegex(si.InvalidModule, "first block"): - run_cs(bad) - with self.assertRaisesRegex(wi.InvalidModule, "first block"): - wi.run_wave(bad, wave=32) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_interp_mov_delta.py b/tests/semantic/test_interp_mov_delta.py deleted file mode 100644 index 40b04bcf8..000000000 --- a/tests/semantic/test_interp_mov_delta.py +++ /dev/null @@ -1,81 +0,0 @@ -"""v_interp_mov_f32 with the p10 / p20 vertex selects: the attribute deltas P1 - P0 and P2 - P0. - -RDNA2 ISA, VINTRP: v_interp_mov_f32 returns {P10, P20, P0}[S], the three values the hardware keeps per attribute -for the p1/p2 pair (P = P0 + i * P10 + j * P20). p0 is the provoking vertex (Flat); p10 and p20 read the location -PerVertexKHR (like the *_f16 interps) and subtract vertex 0's word from vertex 1's or 2's. Hand-written programs -only; no game files. - - python -m unittest discover -s tests/semantic -p test_interp_mov_delta.py -""" -import struct -import unittest - -import support -import rdna2spirv - -BARY = (0.25, 0.25, 0.5) -VERTS0 = ((1.0, 10.0, 100.0, -1.0), (3.0, 14.0, 107.5, 2.0), (6.0, 19.0, 115.25, -4.0)) - - -def f32_bits(x): - return struct.unpack(" float: - try: - return struct.unpack(" 0 else float("-inf") - - -def f32_to_bits(x: float) -> int: - try: - return struct.unpack(" 0 else 0xFF800000 - - -def bits_to_f32(b: int) -> float: - return struct.unpack(" int: - """Reference oracle for flat interpolation: exact component copy from provoking vertex.""" - if not (0 <= comp <= 3): - raise ValueError(f"Invalid component index: {comp}") - val = p0_vec4[comp] - if isinstance(val, float): - return f32_to_bits(val) - return val & MASK32 - - -def ref_barycentric_interp(p0_f: float, p1_f: float, p2_f: float, i: float, j: float) -> float: - """Reference oracle for perspective barycentric interpolation: P0 + i*(P1-P0) + j*(P2-P0).""" - return f32_round(p0_f + i * (p1_f - p0_f) + j * (p2_f - p0_f)) - - -_IGNORED = frozenset({ - "OpCapability", "OpExtInstImport", "OpMemoryModel", "OpEntryPoint", "OpExecutionMode", - "OpDecorate", "OpMemberDecorate", "OpTypeVoid", "OpTypeFunction", "OpLabel", "OpReturn", - "OpFunctionEnd", "OpName", "OpSource", -}) - -_LINE = re.compile(r"^(?:(%\S+)\s*=\s*)?(Op\w+)\s*(.*)$") - - -class FlatSpirvInterp: - """Mini SPIR-V interpreter with Input vector attribute support for flat constant interpolation.""" - - def __init__(self, spvasm: str, flat_inputs=None): - self.spvasm = spvasm - self.flat_inputs = flat_inputs or {} - self.types = {} - self.constants = {} - self.ptr_types = {} - self.var_class = {} - self.ptr_class = {} - self.var_box = {} - self.pointers = {} - self.values = {} - self.outputs = [] - self.body = [] - self._parse() - - def _parse(self): - in_body = False - for raw in self.spvasm.splitlines(): - line = raw.strip() - if not line: - continue - m = _LINE.match(line) - if not m: - raise UnsupportedConstruct(f"Cannot parse line: {line!r}") - res, op, rest = m.groups() - a = rest.split() - if in_body: - self.body.append((res, op, a)) - continue - if op == "OpFunction": - in_body = True - continue - if op in _IGNORED: - continue - if op == "OpTypeInt": - if int(a[0]) != 32: - raise UnsupportedConstruct("Only 32-bit int supported") - self.types[res] = ("int", int(a[0]), int(a[1])) - elif op == "OpTypeFloat": - if int(a[0]) != 32: - raise UnsupportedConstruct("Only 32-bit float supported") - self.types[res] = ("float",) - elif op == "OpTypeBool": - self.types[res] = ("bool",) - elif op == "OpTypeVector": - self.types[res] = ("vec", a[0], int(a[1])) - elif op == "OpTypeArray": - size = int(self.constants[a[1]]) - self.types[res] = ("arr", a[0], size) - elif op == "OpTypeStruct": - self.types[res] = ("struct", a) - elif op == "OpTypePointer": - self.ptr_types[res] = (a[0], a[1]) - elif op == "OpConstant": - k = self.types[a[0]] - if k[0] == "float": - self.constants[res] = self.values[res] = f32_round(float(a[1])) - elif k[0] == "int": - self.constants[res] = self.values[res] = int(a[1], 0) & MASK32 - elif op == "OpConstantTrue": - self.constants[res] = self.values[res] = True - elif op == "OpConstantFalse": - self.constants[res] = self.values[res] = False - elif op == "OpConstantNull": - k = self.types[a[0]] - if k[0] == "arr": - self.constants[res] = self.values[res] = [0] * k[2] - elif k[0] == "vec": - self.constants[res] = self.values[res] = (0.0,) * k[2] - else: - self.constants[res] = self.values[res] = 0 - elif op == "OpVariable": - cls, pointee = self.ptr_types[a[0]] - self.var_class[res] = cls - self.ptr_class[res] = cls - if cls == "PushConstant": - self.var_box[res] = [None] - elif cls == "Input": - m_idx = re.search(r"\d+", res) - attr_idx = int(m_idx.group()) if m_idx else 0 - raw_vec = self.flat_inputs.get(attr_idx, (0, 0, 0, 0)) - floats = [bits_to_f32(w) if isinstance(w, int) else f32_round(w) for w in raw_vec] - self.var_box[res] = [list(floats)] - elif cls in ("Function", "Output"): - if len(a) > 2: - init = self.values[a[2]] - self.var_box[res] = [list(init) if isinstance(init, (list, tuple)) else init] - else: - pty = self.types[pointee] - if pty[0] == "vec": - self.var_box[res] = [[0.0] * pty[2]] - elif pty[0] == "arr": - self.var_box[res] = [[0] * pty[2]] - else: - self.var_box[res] = [0] - if cls == "Output": - self.outputs.append(res) - else: - raise UnsupportedConstruct(f"Unsupported storage class {cls}") - self.pointers[res] = (self.var_box[res], 0) - - def run(self): - for res, op, a in self.body: - if op in _IGNORED: - continue - if op == "OpVariable": - cls, pointee = self.ptr_types[a[0]] - if cls != "Function": - raise UnsupportedConstruct("non-Function variable in body") - self.var_class[res] = cls - self.ptr_class[res] = cls - if len(a) > 2: - init = self.values[a[2]] - self.var_box[res] = [list(init) if isinstance(init, (list, tuple)) else init] - else: - self.var_box[res] = [0] - self.pointers[res] = (self.var_box[res], 0) - elif op == "OpAccessChain": - base = a[1] - b_cls = self.ptr_class.get(base, self.var_class.get(base)) - self.ptr_class[res] = b_cls - if b_cls == "PushConstant": - self.pointers[res] = ("pc", None) - continue - p = self.pointers[base] - for idx_id in a[2:]: - idx = self.values[idx_id] - container = p[0][p[1]] - if not isinstance(container, list) or not 0 <= idx < len(container): - raise UnsupportedConstruct("OpAccessChain index out of range") - p = (container, idx) - self.pointers[res] = p - elif op == "OpLoad": - p = self.pointers[a[1]] - if p[0] == "pc": - self.values[res] = 0 - else: - v = p[0][p[1]] - self.values[res] = list(v) if isinstance(v, list) else v - elif op == "OpStore": - p_cls = self.ptr_class.get(a[0], self.var_class.get(a[0])) - if p_cls in ("Input", "PushConstant"): - raise UnsupportedConstruct(f"Cannot store to {p_cls} variable") - p = self.pointers[a[0]] - p[0][p[1]] = self.values[a[1]] - elif op == "OpSelect": - cond = self.values[a[1]] - if not isinstance(cond, bool): - raise UnsupportedConstruct("OpSelect condition must be boolean") - self.values[res] = self.values[a[2]] if cond else self.values[a[3]] - elif op == "OpBitcast": - target_type = self.types[a[0]] - val = self.values[a[1]] - if target_type[0] == "float" and isinstance(val, int): - self.values[res] = bits_to_f32(val) - elif target_type[0] == "int" and isinstance(val, float): - self.values[res] = f32_to_bits(val) - elif target_type[0] == "int" and isinstance(val, int): - self.values[res] = val & MASK32 - else: - self.values[res] = val - elif op == "OpIAdd": - self.values[res] = (self.values[a[1]] + self.values[a[2]]) & MASK32 - elif op == "OpISub": - self.values[res] = (self.values[a[1]] - self.values[a[2]]) & MASK32 - elif op == "OpBitwiseAnd": - self.values[res] = (self.values[a[1]] & self.values[a[2]]) & MASK32 - elif op == "OpBitwiseOr": - self.values[res] = (self.values[a[1]] | self.values[a[2]]) & MASK32 - elif op == "OpBitwiseXor": - self.values[res] = (self.values[a[1]] ^ self.values[a[2]]) & MASK32 - elif op == "OpShiftLeftLogical": - sh = self.values[a[2]] - self.values[res] = (self.values[a[1]] << sh) & MASK32 if sh < 32 else 0 - elif op == "OpShiftRightLogical": - sh = self.values[a[2]] - self.values[res] = (self.values[a[1]] >> sh) & MASK32 if sh < 32 else 0 - elif op == "OpCompositeConstruct": - self.values[res] = tuple(self.values[x] for x in a[1:]) - elif op == "OpCompositeExtract": - v = self.values[a[1]] - for i in a[2:]: - v = v[int(i)] - self.values[res] = v - else: - raise UnsupportedConstruct(f"Unhandled opcode in body: {op}") - - result = {} - for out in self.outputs: - raw = self.var_box[out][0] - flat = raw if isinstance(raw, (tuple, list)) else (raw,) - result[out] = tuple(f32_to_bits(x) if isinstance(x, float) else x & MASK32 for x in flat) - return result - - -def translate_synthetic_ps(asm_instructions: str, shader_name: str = "ps_synthetic") -> str: - """Translates a straight-line fragment shader into SPIR-V assembly text.""" - with tempfile.TemporaryDirectory() as tmp: - disasm_dir = os.path.join(tmp, "disasm") - os.mkdir(disasm_dir) - s_path = os.path.join(disasm_dir, f"{shader_name}.s") - dxbc_path = os.path.join(tmp, f"{shader_name}.dxbc") - with open(dxbc_path, "wb") as f: - f.write(STUB_DXBC) - - full_asm = f"; {shader_name}\n" + asm_instructions - with open(s_path, "w", encoding="utf-8") as f: - f.write(full_asm) - - with warnings.catch_warnings(): - warnings.simplefilter("ignore", ResourceWarning) - spv = rdna2spirv.translate(s_path) - gc.collect() - return spv - - -class FlatInterpolationReferenceTests(unittest.TestCase): - """Verifies that flat copying preserves raw bits while barycentric interpolation alters them.""" - - def test_flat_copy_oracle_all_channels(self): - p0 = (0x101, 0x202, 0x303, 0x404) - for comp, name in enumerate("xyzw"): - with self.subTest(component=name): - self.assertEqual(ref_flat_copy(p0, comp), p0[comp]) - - def test_flat_copy_preserves_integer_ids_unmangled(self): - integer_ids = [0x0, 0x1, 0x101, 0x102, 0xCAFEBABE, 0xDEADBEEF, 0xFFFFFFFF] - for val in integer_ids: - with self.subTest(val=hex(val)): - vec = (val, 0, 0, 0) - self.assertEqual(ref_flat_copy(vec, 0), val) - - def test_barycentric_interpolation_distorts_integer_bits(self): - p0_int = 0x101 - p1_int = 0x102 - p2_int = 0x103 - p0_f = bits_to_f32(p0_int) - p1_f = bits_to_f32(p1_int) - p2_f = bits_to_f32(p2_int) - interp_f = ref_barycentric_interp(p0_f, p1_f, p2_f, 0.333, 0.333) - interp_bits = f32_to_bits(interp_f) - self.assertNotEqual(interp_bits, p0_int) - self.assertEqual(ref_flat_copy((p0_int, p1_int, p2_int, 0), 0), p0_int) - - -class FlatSpirvDirectInterpTests(unittest.TestCase): - """Direct tests of FlatSpirvInterp on hand-written SPIR-V modules.""" - - DIRECT_HEADER = """\ -OpCapability Shader -%glsl = OpExtInstImport "GLSL.std.450" -OpMemoryModel Logical GLSL450 -OpEntryPoint Fragment %main "main" %out_mrt0 %in_attr1 -OpExecutionMode %main OriginUpperLeft -OpDecorate %out_mrt0 Location 0 -OpDecorate %in_attr1 Location 1 -OpDecorate %in_attr1 Flat -%void = OpTypeVoid -%fn = OpTypeFunction %void -%uint = OpTypeInt 32 0 -%float = OpTypeFloat 32 -%v4float = OpTypeVector %float 4 -%_ptr_Output_v4 = OpTypePointer Output %v4float -%_ptr_Input_v4 = OpTypePointer Input %v4float -%_ptr_Input_float = OpTypePointer Input %float -%c0 = OpConstant %uint 0 -%c1 = OpConstant %uint 1 -%c2 = OpConstant %uint 2 -%c3 = OpConstant %uint 3 -%out_mrt0 = OpVariable %_ptr_Output_v4 Output -%in_attr1 = OpVariable %_ptr_Input_v4 Input -%main = OpFunction %void None %fn -%entry = OpLabel -""" - - def test_direct_flat_input_read_all_channels(self): - body = self.DIRECT_HEADER + """\ -%p0 = OpAccessChain %_ptr_Input_float %in_attr1 %c0 -%f0 = OpLoad %float %p0 -%p1 = OpAccessChain %_ptr_Input_float %in_attr1 %c1 -%f1 = OpLoad %float %p1 -%p2 = OpAccessChain %_ptr_Input_float %in_attr1 %c2 -%f2 = OpLoad %float %p2 -%p3 = OpAccessChain %_ptr_Input_float %in_attr1 %c3 -%f3 = OpLoad %float %p3 -%out_vec = OpCompositeConstruct %v4float %f0 %f1 %f2 %f3 -OpStore %out_mrt0 %out_vec -OpReturn -OpFunctionEnd -""" - inputs = {1: (0x11111111, 0x22222222, 0x33333333, 0x44444444)} - interp = FlatSpirvInterp(body, inputs) - res = interp.run() - self.assertEqual(res["%out_mrt0"], (0x11111111, 0x22222222, 0x33333333, 0x44444444)) - - def test_direct_flat_input_integer_bitcast_arithmetic(self): - body = self.DIRECT_HEADER + """\ -%p0 = OpAccessChain %_ptr_Input_float %in_attr1 %c0 -%f0 = OpLoad %float %p0 -%u0 = OpBitcast %uint %f0 -%u1 = OpIAdd %uint %u0 %c1 -%f1 = OpBitcast %float %u1 -%out_vec = OpCompositeConstruct %v4float %f0 %f1 %f0 %f1 -OpStore %out_mrt0 %out_vec -OpReturn -OpFunctionEnd -""" - inputs = {1: (0x101, 0, 0, 0)} - interp = FlatSpirvInterp(body, inputs) - res = interp.run() - self.assertEqual(res["%out_mrt0"], (0x101, 0x102, 0x101, 0x102)) - - def test_store_to_input_variable_is_rejected(self): - body = self.DIRECT_HEADER + """\ -%p0 = OpAccessChain %_ptr_Input_float %in_attr1 %c0 -%f0 = OpLoad %float %p0 -OpStore %p0 %f0 -OpReturn -OpFunctionEnd -""" - interp = FlatSpirvInterp(body, {1: (0x1, 0x2, 0x3, 0x4)}) - with self.assertRaises(UnsupportedConstruct): - interp.run() - - def test_out_of_bounds_input_component_access_is_rejected(self): - body = self.DIRECT_HEADER + """\ -%c4 = OpConstant %uint 4 -%p4 = OpAccessChain %_ptr_Input_float %in_attr1 %c4 -%f4 = OpLoad %float %p4 -OpReturn -OpFunctionEnd -""" - interp = FlatSpirvInterp(body, {1: (0x1, 0x2, 0x3, 0x4)}) - with self.assertRaises(UnsupportedConstruct): - interp.run() - - -class RdnaFlatTranslationTests(unittest.TestCase): - """Verifies that rdna2spirv translates v_interp_mov_f32 into flat decorated SPIR-V.""" - - def test_v_interp_mov_emits_flat_decoration(self): - asm = ( - "\tv_interp_mov_f32_e32 v2, p0, attr1.x\n" - "\texp mrt0 v2, v2, v2, v2 done vm\n" - "\ts_endpgm\n" - ) - spv = translate_synthetic_ps(asm) - self.assertIn("OpDecorate %in_attr1 Location 1", spv) - self.assertIn("OpDecorate %in_attr1 Flat", spv) - self.assertIn("%in_attr1 = OpVariable %_ptr_Input_v4 Input", spv) - self.assertIn("%_ptr_Input_float %in_attr1 %c0", spv) - - def test_all_four_components_map_to_correct_constants(self): - asm = ( - "\tv_interp_mov_f32 v2, p0, attr2.x\n" - "\tv_interp_mov_f32 v3, p0, attr2.y\n" - "\tv_interp_mov_f32 v4, p0, attr2.z\n" - "\tv_interp_mov_f32 v5, p0, attr2.w\n" - "\texp mrt0 v2, v3, v4, v5 done vm\n" - "\ts_endpgm\n" - ) - spv = translate_synthetic_ps(asm) - self.assertIn("OpDecorate %in_attr2 Flat", spv) - self.assertIn("%_ptr_Input_float %in_attr2 %c0", spv) - self.assertIn("%_ptr_Input_float %in_attr2 %c1", spv) - self.assertIn("%_ptr_Input_float %in_attr2 %c2", spv) - self.assertIn("%_ptr_Input_float %in_attr2 %c3", spv) - - def test_mixed_flat_and_interpolated_attributes(self): - asm = ( - "\tv_interp_mov_f32_e32 v2, p0, attr1.x\n" - "\tv_interp_p1_f32_e32 v4, v0, attr0.x\n" - "\tv_interp_p2_f32_e32 v4, v1, attr0.x\n" - "\texp mrt0 v2, v2, v4, v4 done vm\n" - "\ts_endpgm\n" - ) - spv = translate_synthetic_ps(asm) - self.assertIn("OpDecorate %in_attr1 Location 1", spv) - self.assertIn("OpDecorate %in_attr1 Flat", spv) - self.assertIn("OpDecorate %in_attr0 Location 0", spv) - self.assertNotIn("OpDecorate %in_attr0 Flat", spv) - - def test_attribute_read_both_flat_and_interpolated_is_not_flat(self): - asm = ( - "\tv_interp_mov_f32_e32 v2, p0, attr3.x\n" - "\tv_interp_p1_f32_e32 v4, v0, attr3.y\n" - "\tv_interp_p2_f32_e32 v4, v1, attr3.y\n" - "\texp mrt0 v2, v2, v4, v4 done vm\n" - "\ts_endpgm\n" - ) - spv = translate_synthetic_ps(asm) - self.assertIn("OpDecorate %in_attr3 Location 3", spv) - self.assertNotIn("OpDecorate %in_attr3 Flat", spv) - - def test_v_interp_mov_in_vertex_shader_is_rejected(self): - with tempfile.TemporaryDirectory() as tmp: - disasm_dir = os.path.join(tmp, "disasm") - os.mkdir(disasm_dir) - s_path = os.path.join(disasm_dir, "vs_test.s") - with open(s_path, "w", encoding="utf-8") as f: - f.write("; vs\n\tv_interp_mov_f32 v2, p0, attr1.x\n\texp pos0 v2, v2, v2, v2 done\n\ts_endpgm\n") - with warnings.catch_warnings(): - warnings.simplefilter("ignore", ResourceWarning) - with self.assertRaises(rdna2spirv.Unsupported): - rdna2spirv.translate(s_path) - gc.collect() - - def test_v_interp_mov_without_attr_is_rejected(self): - with tempfile.TemporaryDirectory() as tmp: - disasm_dir = os.path.join(tmp, "disasm") - os.mkdir(disasm_dir) - s_path = os.path.join(disasm_dir, "ps_test.s") - dxbc_path = os.path.join(tmp, "ps_test.dxbc") - with open(dxbc_path, "wb") as f: - f.write(STUB_DXBC) - with open(s_path, "w", encoding="utf-8") as f: - f.write("; ps\n\tv_interp_mov_f32 v2, p0, v1\n\texp mrt0 v2, v2, v2, v2 done vm\n\ts_endpgm\n") - with warnings.catch_warnings(): - warnings.simplefilter("ignore", ResourceWarning) - with self.assertRaises(rdna2spirv.Unsupported): - rdna2spirv.translate(s_path) - gc.collect() - - -class EndToEndFlatExecutionTests(unittest.TestCase): - """End-to-end translation and execution of RDNA2 flat pixel shaders.""" - - def test_p0_and_interpolated_read_of_one_f32_location(self) -> None: - with open(os.path.join(HERE, "fixtures", "mixed_f32_varying.asm"), encoding="ascii") as fixture: - lines = fixture.read().splitlines() - shader = support.translate_lines("ps_mixed_f32_varying", lines) - attrs = {0: [(f32_to_bits(x), 0, 0, 0) for x in (2.0, 6.0, 10.0)]} - for weights, interpolated in (((0.25, 0.25, 0.5), 7.0), ((0.5, 0.5, 0.0), 4.0)): - with self.subTest(weights=weights): - inputs = support.varyings(shader, attrs, weights) - self.assertEqual(si.run_fragment(shader, inputs)["%out_mrt0"], - (f32_to_bits(2.0), f32_to_bits(interpolated)) * 2) - - for fallback in ("BARY_FALLBACK", "F16_HALVES"): - with self.subTest(fallback=fallback), mock.patch.object(rdna2spirv, fallback, True): - with self.assertRaisesRegex(rdna2spirv.Unsupported, "need per-vertex inputs"): - support.translate_lines("ps_mixed_f32_varying", lines) - - def test_ps_flat_model_execution(self): - asm = ( - "\tv_interp_mov_f32_e32 v2, p0, attr1.x\n" - "\tv_add_nc_u32_e32 v3, 1, v2\n" - "\texp mrt0 v2, v3, v2, v3 done vm\n" - "\ts_endpgm\n" - ) - spv = translate_synthetic_ps(asm) - inputs = {1: (0x101, 0, 0, 0)} - interp = FlatSpirvInterp(spv, inputs) - res = interp.run() - self.assertEqual(res["%out_mrt0"], (0x101, 0x102, 0x101, 0x102)) - - def test_four_channel_vector_passthrough(self): - asm = ( - "\tv_interp_mov_f32_e32 v2, p0, attr1.x\n" - "\tv_interp_mov_f32_e32 v3, p0, attr1.y\n" - "\tv_interp_mov_f32_e32 v4, p0, attr1.z\n" - "\tv_interp_mov_f32_e32 v5, p0, attr1.w\n" - "\texp mrt0 v2, v3, v4, v5 done vm\n" - "\ts_endpgm\n" - ) - spv = translate_synthetic_ps(asm) - vec = (0xDEADBEEF, 0xCAFEBABE, 0x12345678, 0x87654321) - interp = FlatSpirvInterp(spv, {1: vec}) - res = interp.run() - self.assertEqual(res["%out_mrt0"], vec) - - def test_flat_boundary_bit_patterns(self): - asm = ( - "\tv_interp_mov_f32_e32 v2, p0, attr1.x\n" - "\texp mrt0 v2, v2, v2, v2 done vm\n" - "\ts_endpgm\n" - ) - spv = translate_synthetic_ps(asm) - patterns = [ - 0x00000000, - 0x00000001, - 0x7FFFFFFF, - 0x80000000, - 0xFFFFFFFF, - 0x7F800000, - 0xFF800000, - 0x7FC00000, - ] - for val in patterns: - with self.subTest(pattern=hex(val)): - interp = FlatSpirvInterp(spv, {1: (val, 0, 0, 0)}) - res = interp.run() - self.assertEqual(res["%out_mrt0"], (val, val, val, val)) - - def test_multiple_flat_attributes_interaction(self): - asm = ( - "\tv_interp_mov_f32_e32 v2, p0, attr1.x\n" - "\tv_interp_mov_f32_e32 v3, p0, attr2.y\n" - "\tv_add_nc_u32_e32 v4, v2, v3\n" - "\tv_subrev_nc_u32_e32 v5, v2, v3\n" - "\texp mrt0 v2, v3, v4, v5 done vm\n" - "\ts_endpgm\n" - ) - spv = translate_synthetic_ps(asm) - inputs = { - 1: (0x50, 0, 0, 0), - 2: (0, 0x30, 0, 0), - } - interp = FlatSpirvInterp(spv, inputs) - res = interp.run() - self.assertEqual(res["%out_mrt0"], (0x50, 0x30, 0x80, 0xFFFFFFE0)) - - def test_flat_bitwise_masking_arithmetic(self): - asm = ( - "\tv_interp_mov_f32_e32 v2, p0, attr1.x\n" - "\tv_and_b32_e32 v3, 0x00FF00FF, v2\n" - "\tv_lshlrev_b32_e32 v4, 8, v3\n" - "\tv_xor_b32_e32 v5, v2, v4\n" - "\texp mrt0 v2, v3, v4, v5 done vm\n" - "\ts_endpgm\n" - ) - spv = translate_synthetic_ps(asm) - inputs = {1: (0x12345678, 0, 0, 0)} - interp = FlatSpirvInterp(spv, inputs) - res = interp.run() - v2 = 0x12345678 - v3 = v2 & 0x00FF00FF - v4 = (v3 << 8) & MASK32 - v5 = v2 ^ v4 - self.assertEqual(res["%out_mrt0"], (v2, v3, v4, v5)) - - -class FlatNegativeControlTests(unittest.TestCase): - """Negative controls proving sensitivity to flat decoration and access sabotage.""" - - def test_sabotaged_flat_component_access_detected(self): - asm = ( - "\tv_interp_mov_f32_e32 v2, p0, attr1.x\n" - "\texp mrt0 v2, v2, v2, v2 done vm\n" - "\ts_endpgm\n" - ) - good_spv = translate_synthetic_ps(asm) - inputs = {1: (0x101, 0x202, 0x303, 0x404)} - good_res = FlatSpirvInterp(good_spv, inputs).run() - self.assertEqual(good_res["%out_mrt0"], (0x101, 0x101, 0x101, 0x101)) - - bad_spv = good_spv.replace("%_ptr_Input_float %in_attr1 %c0", "%_ptr_Input_float %in_attr1 %c1") - bad_res = FlatSpirvInterp(bad_spv, inputs).run() - self.assertNotEqual(bad_res["%out_mrt0"], good_res["%out_mrt0"]) - self.assertEqual(bad_res["%out_mrt0"], (0x202, 0x202, 0x202, 0x202)) - - def test_sabotaged_attribute_source_detected(self): - asm = ( - "\tv_interp_mov_f32_e32 v2, p0, attr1.x\n" - "\texp mrt0 v2, v2, v2, v2 done vm\n" - "\ts_endpgm\n" - ) - spv = translate_synthetic_ps(asm) - inputs_a = {1: (0xAAAA, 0, 0, 0)} - inputs_b = {1: (0xBBBB, 0, 0, 0)} - res_a = FlatSpirvInterp(spv, inputs_a).run()["%out_mrt0"] - res_b = FlatSpirvInterp(spv, inputs_b).run()["%out_mrt0"] - self.assertNotEqual(res_a, res_b) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_interp_p1_p2.py b/tests/semantic/test_interp_p1_p2.py deleted file mode 100644 index 9d608d68b..000000000 --- a/tests/semantic/test_interp_p1_p2.py +++ /dev/null @@ -1,401 +0,0 @@ -"""Semantic interpreter and translator tests for perspective interpolation parameter calculation. - -Covers RDNA2 perspective interpolation instructions: -- v_interp_p1_f32: computes D = P10 * S + P0 (first axis / barycentric weight i) -- v_interp_p2_f32: computes D = P20 * S + D (second axis / barycentric weight j, accumulating p1) -Combined result: D = P0 + i * (P1 - P0) + j * (P2 - P0) = (1 - i - j) * P0 + i * P1 + j * P2. - -Under perspective projection with clip-space depths W0, W1, W2 > 0 and screen-space -barycentric weights (l0, l1, l2), the hardware SPI computes perspective-corrected -barycentric coordinates: - inv_W = l0 / W0 + l1 / W1 + l2 / W2 - i_persp = (l1 / W1) / inv_W - j_persp = (l2 / W2) / inv_W -Feeding (i_persp, j_persp) into (v_interp_p1_f32, v_interp_p2_f32) yields the exact -perspective-correct attribute interpolation across the triangle. -""" -import gc -import math -import os -import struct -import sys -import tempfile -import unittest -import warnings - -HERE = os.path.dirname(os.path.abspath(__file__)) -ROOT = os.path.dirname(os.path.dirname(HERE)) -TOOLS_DIR = os.environ.get("LEONIDA_TOOLS_DIR") or os.path.join(ROOT, "tools") - -sys.dont_write_bytecode = True -if TOOLS_DIR not in sys.path: - sys.path.insert(0, TOOLS_DIR) -if HERE not in sys.path: - sys.path.insert(0, HERE) - -import rdna2spirv -import spirv_mini_interp as si - -STUB_DXBC = b"DXBC" + bytes(24) + struct.pack(" 0 else float("-inf") - - -def f32_to_bits(val): - try: - return struct.unpack(" 0 else 0xFF800000 - - -def bits_to_f32(bits): - return struct.unpack(" form") - rejection on non-PS stages (vs_, cs_) and missing `attr` operands for all three *_f16 opcodes. -""" -from __future__ import annotations - -import math -import os -import re -import struct -import sys -import unittest - -HERE = os.path.dirname(os.path.abspath(__file__)) -ROOT = os.path.dirname(os.path.dirname(HERE)) -TOOLS_DIR = os.environ.get("LEONIDA_TOOLS_DIR") or os.path.join(ROOT, "tools") - -sys.dont_write_bytecode = True -if TOOLS_DIR not in sys.path: - sys.path.insert(0, TOOLS_DIR) -if HERE not in sys.path: - sys.path.insert(0, HERE) - -import rdna2spirv # noqa: E402 -import support # noqa: E402 - -BARY = (0.25, 0.25, 0.5) # vertex 0, 1, 2 weights (AMD i = 0.25, j = 0.5) -LO = (0.5, 1.5, 2.5) # exact interpolated value: 1.75 (0x3f00) -HI = (-4.0, 8.0, 16.0) # exact interpolated value: 9.0 (0x4880) - - -def pack_f16(lo, hi): - """Pack two floats as (low_f16 | high_f16 << 16) in a 32-bit word.""" - return struct.unpack(" float: - """Round a float to binary16 precision.""" - try: - return struct.unpack(" 0 else float("-inf") - - -def f16_to_bits(val: float) -> int: - """Return uint16 bits of half-precision float.""" - try: - return struct.unpack(" 0 else 0xFC00 - - -def bits_to_f16(bits: int) -> float: - """Convert uint16 bits to float.""" - return struct.unpack(" float: - """Round a float to binary32 precision.""" - try: - return struct.unpack(" 0 else float("-inf") - - -def f32_to_bits(val: float) -> int: - """Return uint32 bits of single-precision float.""" - try: - return struct.unpack(" 0 else 0xFF800000 - - -def bits_to_f32(bits: int) -> float: - """Convert uint32 bits to float.""" - return struct.unpack(" tuple[float, float]: - """Unpack low and high f16 halves from a 32-bit packed word.""" - lo = bits_to_f16(word & 0xFFFF) - hi = bits_to_f16((word >> 16) & 0xFFFF) - return lo, hi - - -def compute_perspective_barycentrics(l0: float, l1: float, l2: float, - w0: float, w1: float, w2: float) -> tuple[float, float]: - """Compute perspective-corrected barycentric coordinates (i_persp, j_persp).""" - inv_w0 = 1.0 / w0 - inv_w1 = 1.0 / w1 - inv_w2 = 1.0 / w2 - inv_w_total = l0 * inv_w0 + l1 * inv_w1 + l2 * inv_w2 - i_persp = (l1 * inv_w1) / inv_w_total - j_persp = (l2 * inv_w2) / inv_w_total - return f32_round(i_persp), f32_round(j_persp) - - -def v_interp_p1lv_f16_ref(i_coord: float, p0: float, p1: float) -> float: - """Reference oracle for v_interp_p1lv_f16: D = P0 + i * (P1 - P0) in f32 intermediate precision.""" - d1 = f32_round(p1 - p0) - m1 = f32_round(d1 * i_coord) - return f32_round(p0 + m1) - - -def v_interp_p2_f16_ref(j_coord: float, p0: float, p2: float, - p1_accum: float, clamp: bool = False) -> int: - """Reference oracle for v_interp_p2_f16: D = p1_accum + j * (P2 - P0), optional clamp, narrowed to f16 bits.""" - d2 = f32_round(p2 - p0) - m2 = f32_round(d2 * j_coord) - res_f32 = f32_round(p1_accum + m2) - if clamp: - res_f32 = max(0.0, min(1.0, res_f32)) - return f16_to_bits(res_f32) - - -def v_interp_p1lv_eval_ref(i_coord: float, j_coord: float, - p0: float, p1: float, p2: float, - clamp: bool = False) -> tuple[float, int]: - """Evaluate paired v_interp_p1lv_f16 and v_interp_p2_f16: returns (f32_intermediate, f16_bits).""" - p1_accum = v_interp_p1lv_f16_ref(i_coord, p0, p1) - p2_res = v_interp_p2_f16_ref(j_coord, p0, p2, p1_accum, clamp=clamp) - return p1_accum, p2_res - - -def analytical_perspective_interp_f16(p0: float, p1: float, p2: float, - l0: float, l1: float, l2: float, - w0: float, w1: float, w2: float, - clamp: bool = False) -> int: - """Analytical perspective interpolation ground truth narrowed to f16 bits.""" - inv_w0 = 1.0 / w0 - inv_w1 = 1.0 / w1 - inv_w2 = 1.0 / w2 - inv_w_total = l0 * inv_w0 + l1 * inv_w1 + l2 * inv_w2 - numer = l0 * p0 * inv_w0 + l1 * p1 * inv_w1 + l2 * p2 * inv_w2 - val = numer / inv_w_total - if clamp: - val = max(0.0, min(1.0, val)) - return f16_to_bits(val) - - -def lerp(values, bary=BARY): - return sum(b * v for b, v in zip(bary, values)) - - -def isg1_dxbc(elements): - """Synthetic DXBC container with one ISG1 chunk: elements = (register, mask, rw_mask, sysv, ctype).""" - payload = bytearray(struct.pack(" clamp 0.0, hi=1.75 -> clamp 1.0); - # attr0.z: lo=(1.0, 3.0, 5.0) -> 3.5 as f32 intermediate; attr0.w: raw flat words. - y_lo = (-1.0, -1.0, 0.5) # 0.25*(-1.0) + 0.25*(-1.0) + 0.5*0.5 = -0.25 -> clamped to 0.0 - y_hi = (0.5, 1.5, 2.5) # 1.75 -> clamped to 1.0 - z_lo = (1.0, 3.0, 5.0) # 3.5 - w_raw = (0x1234, 0x5678, 0x9ABC) - attr0 = [(pack_f16(lo, hi), pack_f16(yl, yh), pack_f16(zl, 0.0), wr) - for lo, hi, yl, yh, zl, wr in zip(LO, HI, y_lo, y_hi, z_lo, w_raw)] - attr1 = [(f32_bits(x), 0, 0, 0) for x in (-2.0, 2.0, 4.0)] # 0.25*(-2)+0.25*2+0.5*4 = 2.0 - return {0: attr0, 1: attr1} - - def test_p1lv_low_high_clamp_and_intermediate_end_to_end(self): - spv, meta = translate_with_flags("ps_p1lv", P1LV_SHADER, dxbc=PS_ATTR01_DXBC) - - self.assertIn("OpCapability FragmentBarycentricKHR", spv) - self.assertIn('OpExtension "SPV_KHR_fragment_shader_barycentric"', spv) - self.assertIn("OpDecorate %in_attr0 PerVertexKHR", spv) - self.assertIn("OpDecorate %bary BuiltIn BaryCoordKHR", spv) - self.assertIn("OpDecorate %in_attr1 Location 1", spv) - self.assertNotIn("OpDecorate %in_attr1 PerVertexKHR", spv) - self.assertNotIn("OpDecorate %in_attr1 Flat", spv) - self.assertIn("UnpackHalf2x16", spv) - self.assertEqual(meta["features"], ["fragmentShaderBarycentric"]) - self.assertEqual(meta["inputs"], [0, 1]) - - attrs = self._default_attrs() - out = support.run_fragment(spv, inputs=support.varyings(spv, attrs, BARY)) - mrt0, mrt1 = out["%out_mrt0"], out["%out_mrt1"] - self.assertEqual([w & 0xFFFF for w in mrt0], [0x3F00, 0x4880, 0x0000, 0x3C00]) - # Standalone v_interp_p1lv_f16 exports the f32 intermediate (3.5), not f16 bits. - self.assertEqual(f"{mrt1[0]:#010x}", f"{f32_bits(3.5):#010x}") - self.assertEqual(f"{mrt1[1]:#010x}", f"{f32_bits(2.0):#010x}") - self.assertEqual(mrt1[2], 0x1234) - - def test_p1lv_clamp_vs_unclamped_and_in_range(self): - # attr0.x: lo=1.5 (clamp->1.0), hi=-0.25 (clamp->+0.0); attr0.y: lo=0.5 (in-range); attr0.z: lo=3.5 (p1lv) - attrs = {0: [(pack_f16(1.5, -0.25), pack_f16(0.5, 0.0), pack_f16(3.5, 0.0), 0)] * 3} - spv_clamp, _ = translate_with_flags("ps_p1lv_clamp", P1LV_CLAMP_PAIR, dxbc=PS_ATTR01_DXBC) - self.assertIn("FClamp", spv_clamp) - words_clamp = support.mrt0_words(spv_clamp, inputs=support.varyings(spv_clamp, attrs, BARY)) - self.assertEqual([w & 0xFFFF for w in words_clamp[:3]], [0x3C00, 0x0000, 0x3800]) - self.assertEqual(words_clamp[3], f32_bits(3.5)) - - no_clamp_lines = [ln.replace(" clamp", "") for ln in P1LV_CLAMP_PAIR] - spv_raw, _ = translate_with_flags("ps_p1lv_noclamp", no_clamp_lines, dxbc=PS_ATTR01_DXBC) - self.assertNotIn("FClamp", spv_raw) - words_raw = support.mrt0_words(spv_raw, inputs=support.varyings(spv_raw, attrs, BARY)) - self.assertEqual([w & 0xFFFF for w in words_raw[:3]], [f16_bits(1.5), f16_bits(-0.25), 0x3800]) - - def test_p1lv_nearest_even_rounding_and_subnormal_f16(self): - # Midpoint ties: - # 1.0 (0x3c00) and 1.0 + 2^-10 (0x3c01) averaged at (0.5, 0.5, 0.0) -> 1.0 + 2^-11 -> 0x3c00 (even) - # 1.0 + 2^-10 (0x3c01) and 1.0 + 2^-9 (0x3c02) averaged -> 1.0 + 3*2^-11 -> 0x3c02 (even) - # Subnormals 0x0002 and 0x0004 averaged -> 0x0003 (subnormal preserved by f16_bits) - lines = [ - "v_mov_b32_e32 v10, 0", - "v_interp_p1lv_f16 v2, v0, attr0.x, v10", - "v_interp_p2_f16 v2, v1, attr0.x, v2", - "v_interp_p1lv_f16 v3, v0, attr0.x, v10 high", - "v_interp_p2_f16 v3, v1, attr0.x, v3 high", - "v_interp_p1lv_f16 v4, v0, attr0.y, v10", - "v_interp_p2_f16 v4, v1, attr0.y, v4", - "exp mrt0 v2, v3, v4, v4 done vm", - "s_endpgm", - ] - h0 = 0x3C00 - h1 = 0x3C01 - h2 = 0x3C02 - attr0 = [ - ((h0 & 0xFFFF) | ((h1 & 0xFFFF) << 16), 0x0002, 0, 0), - ((h1 & 0xFFFF) | ((h2 & 0xFFFF) << 16), 0x0004, 0, 0), - ((h0 & 0xFFFF) | ((h1 & 0xFFFF) << 16), 0x0002, 0, 0), - ] - spv, _ = translate_with_flags("ps_p1lv_ties", lines, dxbc=PS_ATTR01_DXBC) - words = support.mrt0_words(spv, inputs=support.varyings(spv, {0: attr0}, (0.5, 0.5, 0.0))) - self.assertEqual([w & 0xFFFF for w in words[:3]], [0x3C00, 0x3C02, 0x0003]) - - def test_p1lv_with_sv_position_in_isg1(self): - # SV_Position at ISG1 reg 0 occupies v2..v5; v_interp_p1lv_f16 reads v0 and vsrc2=v10 without conflict. - lines = [ - "v_mov_b32_e32 v10, 0", - "v_interp_p1lv_f16 v6, v0, attr0.x, v10 high", - "v_interp_p2_f16 v6, v1, attr0.x, v6 high", - "v_add_f32_e32 v7, v2, v3", - "exp mrt0 v6, v7, v6, v7 done vm", - "s_endpgm", - ] - spv, meta = translate_with_flags("ps_p1lv_pos", lines, dxbc=PS_POS_ATTR0_DXBC) - self.assertEqual(meta["ps_system_inputs"], ["0", "1"]) - attr0 = [(pack_f16(0.5, hi), 0, 0, 0) for hi in HI] - inputs = support.varyings(spv, {0: attr0}, BARY) - inputs["%frag_coord"] = (1.25, 2.5, 0.0, 1.0) - words = support.mrt0_words(spv, inputs=inputs) - self.assertEqual(words[0] & 0xFFFF, 0x4880) - self.assertEqual(words[1], f32_bits(3.75)) - - def test_negative_controls_p1lv(self): - attrs = {0: [(pack_f16(1.5, -0.25), pack_f16(0.5, 0.0), pack_f16(3.5, 0.0), 0)] * 3} - spv, _ = translate_with_flags("ps_p1lv_neg", P1LV_CLAMP_PAIR, dxbc=PS_ATTR01_DXBC) - inputs = support.varyings(spv, attrs, BARY) - baseline = support.mrt0_words(spv, inputs=inputs) - self.assertEqual([w & 0xFFFF for w in baseline[:3]], [0x3C00, 0x0000, 0x3800]) - - # Sabotage 1: force high-half extract (component 1) to low half (component 0). - bad_half = re.sub(r"OpCompositeExtract %float (%\S+) 1", r"OpCompositeExtract %float \1 0", spv) - self.assertNotEqual(bad_half, spv) - self.assertNotEqual(support.mrt0_words(bad_half, inputs=inputs), baseline) - - # Sabotage 2: drop FClamp by replacing FClamp %v %f0 %f1 with FMax %v %f0. - bad_clamp = re.sub(r"OpExtInst %float %glsl FClamp (%\S+) %f0 %f1", r"OpExtInst %float %glsl FMax \1 %f0", spv) - self.assertNotEqual(bad_clamp, spv) - self.assertNotEqual(support.mrt0_words(bad_clamp, inputs=inputs), baseline) - - -class InterpP1lvF16HalvesFallbackTests(unittest.TestCase): - """--f16-interp-fallback (F16_HALVES) behaviour with v_interp_p1lv_f16.""" - - def test_p1lv_f16_halves_translation_and_execution(self): - spv, meta = translate_with_flags("ps_p1lv_fh", P1LV_CLAMP_PAIR, - dxbc=PS_ATTR01_DXBC, f16_halves=True) - self.assertNotIn("PerVertexKHR", spv) - self.assertNotIn("BaryCoordKHR", spv) - self.assertNotIn("FragmentBarycentricKHR", spv) - self.assertNotIn("fragmentShaderBarycentric", meta["features"]) - self.assertIn("OpDecorate %in_f16h0_0 Location 28", spv) - self.assertIn("OpDecorate %in_f16h0_1 Location 29", spv) - self.assertNotIn("OpDecorate %in_f16h0_0 Flat", spv) - self.assertEqual(meta["f16_halves"], {"0": [28, 29]}) - self.assertEqual(meta["inputs"], [28, 29]) - - inputs = { - "%in_f16h0_0": (lerp(LO), 0.5, 3.5, 0.0), # attr0 low: 1.75 (clamped->1.0), 0.5, 3.5 (p1lv f32) - "%in_f16h0_1": (lerp(HI), 0.0, 0.0, 0.0), # attr0 high: 9.0 (clamped->1.0) - } - words = support.mrt0_words(spv, inputs=inputs) - self.assertEqual([w & 0xFFFF for w in words[:3]], [0x3C00, 0x3C00, 0x3800]) - self.assertEqual(words[3], f32_bits(3.5)) - - def test_p1lv_f16_halves_location_clash_packs_and_overflow_rejects(self): - clash = [ - "v_mov_b32_e32 v10, 0", - "v_interp_p1lv_f16 v2, v0, attr0.x, v10", - "v_interp_p2_f16 v2, v1, attr0.x, v2", - "v_interp_p1_f32_e32 v3, v0, attr29.x", - "v_interp_p2_f32_e32 v3, v1, attr29.x", - "exp mrt0 v2, v3, v3, v3 done vm", - "s_endpgm", - ] - spv, meta = translate_with_flags("ps_p1lv_fh_packed", clash, f16_halves=True) - self.assertEqual(meta["f16_halves"], {"0": [27, 28]}) - self.assertIn("OpDecorate %in_f16h0_0 Location 27", spv) - self.assertIn("OpDecorate %in_attr29 Location 29", spv) - - overflow = ["v_mov_b32_e32 v10, 0"] - for a in range(29): - overflow += [f"v_interp_p1_f32_e32 v{20 + a}, v0, attr{a}.x", - f"v_interp_p2_f32_e32 v{20 + a}, v1, attr{a}.x"] - overflow += [ - "v_interp_p1lv_f16 v2, v0, attr0.x, v10", - "v_interp_p2_f16 v2, v1, attr0.x, v2", - "exp mrt0 v2, v20, v20, v20 done vm", - "s_endpgm", - ] - with self.assertRaises(rdna2spirv.Unsupported) as cm: - translate_with_flags("ps_p1lv_fh_overflow", overflow, f16_halves=True) - self.assertIn("decoded-half locations", str(cm.exception)) - - -class InterpF16BaryFallbackTests(unittest.TestCase): - """--bary-fallback (BARY_FALLBACK) translation and execution for *_f16 ops.""" - - def test_bary_fallback_for_p1ll_p1lv_p2_uses_smooth_inputs_without_per_vertex(self): - lines = [ - "v_mov_b32_e32 v10, 0", - "v_interp_p1ll_f16 v2, v0, attr0.x", - "v_interp_p2_f16 v2, v1, attr0.x, v2", - "v_interp_p1lv_f16 v3, v0, attr0.y, v10 high", - "v_interp_p2_f16 v3, v1, attr0.y, v3 high clamp", - "v_interp_p1lv_f16 v4, v0, attr0.z, v10", # standalone f32 intermediate - "exp mrt0 v2, v3, v4, v2 done vm", - "s_endpgm", - ] - spv, meta = translate_with_flags("ps_f16_bf", lines, dxbc=PS_ATTR01_DXBC, bary_fallback=True) - - self.assertNotIn("PerVertexKHR", spv) - self.assertNotIn("BaryCoordKHR", spv) - self.assertNotIn("FragmentBarycentricKHR", spv) - self.assertNotIn("SPV_KHR_fragment_shader_barycentric", spv) - self.assertNotIn("%bary", spv) - self.assertIn("OpDecorate %in_attr0 Location 0", spv) - self.assertNotIn("OpDecorate %in_attr0 Flat", spv) - self.assertEqual(meta["features"], []) - self.assertEqual(meta["inputs"], [0]) - self.assertNotIn("bary_fallback_input", meta) - self.assertNotIn("f16_halves", meta) - - # Under --bary-fallback there are no per-vertex inputs, so high reads the same smooth f32 channel. - attrs = {0: [(f32_bits(x), f32_bits(y), f32_bits(z), 0) - for x, y, z in zip((0.5, 1.5, 2.5), (-1.0, -1.0, 0.5), (1.0, 3.0, 5.0))]} - words = support.mrt0_words(spv, inputs=support.varyings(spv, attrs, BARY)) - self.assertEqual(words[0] & 0xFFFF, 0x3F00) # 1.75 - self.assertEqual(words[1] & 0xFFFF, 0x0000) # -0.25 clamped to +0.0 - self.assertEqual(words[2], f32_bits(3.5)) # standalone p1lv f32 intermediate - - # Confirm `high` and non-`high` read identically under --bary-fallback. - lines_same = [ - "v_mov_b32_e32 v10, 0", - "v_interp_p1ll_f16 v2, v0, attr0.x", - "v_interp_p2_f16 v2, v1, attr0.x, v2", - "v_interp_p1lv_f16 v3, v0, attr0.x, v10 high", - "v_interp_p2_f16 v3, v1, attr0.x, v3 high", - "exp mrt0 v2, v3, v2, v3 done vm", - "s_endpgm", - ] - spv_same, _ = translate_with_flags("ps_f16_bf_same", lines_same, dxbc=PS_ATTR01_DXBC, bary_fallback=True) - words_same = support.mrt0_words(spv_same, inputs={"%in_attr0": (1.75, 0.0, 0.0, 0.0)}) - self.assertEqual([w & 0xFFFF for w in words_same[:2]], [0x3F00, 0x3F00]) - - def test_bary_fallback_with_raw_bary_read_and_sparse_attr(self): - for attr_idx, want_bary_loc in ((0, 1), (30, 0)): - with self.subTest(attr=attr_idx): - lines = [ - "v_mov_b32_e32 v10, 0", - f"v_interp_p1lv_f16 v2, v0, attr{attr_idx}.x, v10", - f"v_interp_p2_f16 v2, v1, attr{attr_idx}.x, v2", - "v_mov_b32_e32 v4, v0", - "v_mov_b32_e32 v5, v1", - "exp mrt0 v2, v4, v5, v2 done vm", - "s_endpgm", - ] - spv, meta = translate_with_flags(f"ps_f16_bf_raw_{attr_idx}", lines, bary_fallback=True) - self.assertNotIn("PerVertexKHR", spv) - self.assertNotIn("BaryCoordKHR", spv) - self.assertNotIn("FragmentBarycentricKHR", spv) - self.assertIn(f"OpDecorate %in_attr{attr_idx} Location {attr_idx}", spv) - self.assertIn(f"OpDecorate %bary Location {want_bary_loc}", spv) - self.assertIsNone(re.search(r"OpDecorate %bary (Flat|NoPerspective)", spv)) - self.assertEqual(meta["bary_fallback_input"], {"location": want_bary_loc}) - self.assertEqual(meta["ps_system_inputs"], ["bary_i", "bary_j"]) - - words = support.mrt0_words(spv, inputs={ - f"%in_attr{attr_idx}": (1.75, 0.0, 0.0, 0.0), - "%bary": BARY, - }) - self.assertEqual(words[0] & 0xFFFF, 0x3F00) - self.assertEqual(words[1], f32_bits(BARY[1])) - self.assertEqual(words[2], f32_bits(BARY[2])) - - def test_f16_halves_takes_precedence_over_bary_fallback(self): - spv, meta = translate_with_flags("ps_both_flags", P1LV_CLAMP_PAIR, - dxbc=PS_ATTR01_DXBC, bary_fallback=True, f16_halves=True) - self.assertNotIn("PerVertexKHR", spv) - self.assertIn("OpDecorate %in_f16h0_0 Location 28", spv) - self.assertIn("OpDecorate %in_f16h0_1 Location 29", spv) - self.assertEqual(meta["f16_halves"], {"0": [28, 29]}) - - -class InterpF16GuardsAndRejectionsTests(unittest.TestCase): - """interp_pair_src guards and Unsupported(' form') stage/attr rejections.""" - - def test_p1lv_and_p1ll_i_source_guards(self): - bad_cases = [ - ("v_interp_p1lv_f16 I source v4", [ - "v_mov_b32_e32 v10, 0", - "v_interp_p1lv_f16 v2, v4, attr0.x, v10", - "v_interp_p2_f16 v2, v1, attr0.x, v2", - "exp mrt0 v2, v2, v2, v2 done vm", - "s_endpgm", - ]), - ("v_interp_p1lv_f16 I source v1", [ - "v_mov_b32_e32 v10, 0", - "v_interp_p1lv_f16 v2, v1, attr0.x, v10", - "v_interp_p2_f16 v2, v1, attr0.x, v2", - "exp mrt0 v2, v2, v2, v2 done vm", - "s_endpgm", - ]), - ("v_interp_p1ll_f16 I source v1", [ - "v_interp_p1ll_f16 v2, v1, attr0.x", - "v_interp_p2_f16 v2, v1, attr0.x, v2", - "exp mrt0 v2, v2, v2, v2 done vm", - "s_endpgm", - ]), - # An I source holding a zeroed v0 ("v_mov v0, 0; v_mov v6, v0") is a computed I of 0, which the translator - # models since #1545 (computed I/J barycentrics) instead of rejecting; it is no longer a bad case here. - ("v_interp_p2_f16 J source v0", [ - "v_mov_b32_e32 v10, 0", - "v_interp_p1lv_f16 v2, v0, attr0.x, v10", - "v_interp_p2_f16 v2, v0, attr0.x, v2", - "exp mrt0 v2, v2, v2, v2 done vm", - "s_endpgm", - ]), - ] - for msg, lines in bad_cases: - with self.subTest(msg=msg): - with self.assertRaises(rdna2spirv.Unsupported) as cm: - translate_with_flags("ps_guard_bad", lines, dxbc=PS_ATTR01_DXBC) - self.assertIn(msg, str(cm.exception)) - - def test_p1lv_accepts_saved_copy_of_v0_even_if_v0_later_zeroed(self): - lines = [ - "v_mov_b32_e32 v6, v0", - "v_mov_b32_e32 v7, v1", - "v_mov_b32_e32 v0, 0", - "v_mov_b32_e32 v1, 0", - "v_mov_b32_e32 v10, 0", - "v_interp_p1lv_f16 v2, v6, attr0.x, v10 high", - "v_interp_p2_f16 v2, v7, attr0.x, v2 high", - "exp mrt0 v2, v2, v2, v2 done vm", - "s_endpgm", - ] - spv, _ = translate_with_flags("ps_p1lv_copy", lines, dxbc=PS_ATTR01_DXBC) - attrs = {0: [(pack_f16(lo, hi), 0, 0, 0) for lo, hi in zip(LO, HI)]} - words = support.mrt0_words(spv, inputs=support.varyings(spv, attrs, BARY)) - self.assertEqual(words[0] & 0xFFFF, 0x4880) - - def test_non_ps_stages_rejected_for_all_f16_interp_ops(self): - ops = [ - ("v_interp_p1ll_f16", "v_interp_p1ll_f16 v2, v0, attr0.x"), - ("v_interp_p1lv_f16", "v_interp_p1lv_f16 v2, v0, attr0.x, v3"), - ("v_interp_p2_f16", "v_interp_p2_f16 v2, v1, attr0.x, v2"), - ] - for op, insn in ops: - with self.subTest(stage="vs", op=op): - with self.assertRaises(rdna2spirv.Unsupported) as cm: - translate_with_flags(f"vs_{op}", [insn, "exp pos0 v2, v2, v2, v2 done", "s_endpgm"]) - self.assertIn(f"{op} form", str(cm.exception)) - with self.subTest(stage="cs", op=op): - with self.assertRaises(rdna2spirv.Unsupported) as cm: - translate_with_flags(f"cs_{op}", [insn, "s_endpgm"], fssm=CS_FSSM) - self.assertIn(f"{op} form", str(cm.exception)) - - def test_missing_attr_operand_rejected_for_all_f16_interp_ops(self): - ops = [ - ("v_interp_p1ll_f16", "v_interp_p1ll_f16 v2, v0, v3"), - ("v_interp_p1lv_f16", "v_interp_p1lv_f16 v2, v0, v3, v4"), - ("v_interp_p2_f16", "v_interp_p2_f16 v2, v1, v3, v2"), - ] - for op, insn in ops: - with self.subTest(op=op): - with self.assertRaises(rdna2spirv.Unsupported) as cm: - translate_with_flags(f"ps_noattr_{op}", - [insn, "exp mrt0 v2, v2, v2, v2 done vm", "s_endpgm"], - dxbc=PS_ATTR01_DXBC) - self.assertIn(f"{op} form", str(cm.exception)) - - -class InterpP1lvF16ReferenceOracleTests(unittest.TestCase): - """Mathematical reference oracle tests for half-precision perspective interpolation.""" - - def test_vertex_boundary_conditions(self): - p0, p1, p2 = 2.0, 6.0, 14.0 - p1_acc, p2_bits = v_interp_p1lv_eval_ref(0.0, 0.0, p0, p1, p2) - self.assertEqual(p1_acc, 2.0) - self.assertEqual(p2_bits, f16_to_bits(2.0)) - - p1_acc, p2_bits = v_interp_p1lv_eval_ref(1.0, 0.0, p0, p1, p2) - self.assertEqual(p1_acc, 6.0) - self.assertEqual(p2_bits, f16_to_bits(6.0)) - - p1_acc, p2_bits = v_interp_p1lv_eval_ref(0.0, 1.0, p0, p1, p2) - self.assertEqual(p1_acc, 2.0) - self.assertEqual(p2_bits, f16_to_bits(14.0)) - - def test_edge_midpoints_and_centroid(self): - p0, p1, p2 = 4.0, 8.0, 16.0 - _, res_01 = v_interp_p1lv_eval_ref(0.5, 0.0, p0, p1, p2) - self.assertEqual(res_01, f16_to_bits(6.0)) - - _, res_02 = v_interp_p1lv_eval_ref(0.0, 0.5, p0, p1, p2) - self.assertEqual(res_02, f16_to_bits(10.0)) - - _, res_12 = v_interp_p1lv_eval_ref(0.5, 0.5, p0, p1, p2) - self.assertEqual(res_12, f16_to_bits(12.0)) - - third = f32_round(1.0 / 3.0) - _, res_c = v_interp_p1lv_eval_ref(third, third, p0, p1, p2) - expected_c = (4.0 + 8.0 + 16.0) / 3.0 - self.assertAlmostEqual(bits_to_f16(res_c), expected_c, delta=0.01) - - def test_perspective_parameter_calculation_equal_vs_varying_depth(self): - p0, p1, p2 = 10.0, 50.0, 100.0 - i_eq, j_eq = compute_perspective_barycentrics(0.2, 0.5, 0.3, 4.0, 4.0, 4.0) - self.assertAlmostEqual(i_eq, 0.5, places=5) - self.assertAlmostEqual(j_eq, 0.3, places=5) - _, res_eq = v_interp_p1lv_eval_ref(i_eq, j_eq, p0, p1, p2) - self.assertEqual(res_eq, analytical_perspective_interp_f16(p0, p1, p2, 0.2, 0.5, 0.3, 4.0, 4.0, 4.0)) - - cases = [ - (0.333333, 0.333333, 0.333334, 1.0, 2.0, 4.0, 1.0, 5.0, 10.0), - (0.1, 0.7, 0.2, 0.5, 5.0, 2.5, 0.0, 1.0, 0.5), - (0.6, 0.2, 0.2, 10.0, 1.0, 5.0, -10.0, 20.0, 50.0), - ] - for l0, l1, l2, w0, w1, w2, a0, a1, a2 in cases: - with self.subTest(w=(w0, w1, w2), a=(a0, a1, a2)): - i_p, j_p = compute_perspective_barycentrics(l0, l1, l2, w0, w1, w2) - _, got_bits = v_interp_p1lv_eval_ref(i_p, j_p, a0, a1, a2) - want_bits = analytical_perspective_interp_f16(a0, a1, a2, l0, l1, l2, w0, w1, w2) - self.assertAlmostEqual(bits_to_f16(got_bits), bits_to_f16(want_bits), delta=0.05) - - def test_standalone_p1lv_f32_precision(self): - p0 = 1.0009765625 - p1 = 1.001953125 - i_c = 0.3333333432674408 - p1_accum = v_interp_p1lv_f16_ref(i_c, p0, p1) - self.assertNotEqual(p1_accum, f16_round(p1_accum)) - - def test_unpack_f16_halves_and_pack(self): - lo_in, hi_in = 1.75, -9.5 - packed = pack_f16(lo_in, hi_in) - lo_out, hi_out = unpack_f16_halves(packed) - self.assertEqual(lo_out, lo_in) - self.assertEqual(hi_out, hi_in) - - def test_vop3_clamp_oracle(self): - _, clamped_neg = v_interp_p1lv_eval_ref(0.25, 0.5, -2.0, -4.0, 1.0, clamp=True) - self.assertEqual(clamped_neg, 0x0000) - - _, clamped_high = v_interp_p1lv_eval_ref(0.25, 0.5, 2.0, 4.0, 3.0, clamp=True) - self.assertEqual(clamped_high, 0x3C00) - - _, unclamped = v_interp_p1lv_eval_ref(0.25, 0.5, 0.0, 0.5, 1.0, clamp=False) - _, clamped_mid = v_interp_p1lv_eval_ref(0.25, 0.5, 0.0, 0.5, 1.0, clamp=True) - self.assertEqual(unclamped, clamped_mid) - - def test_nearest_even_tie_rounding_oracle(self): - tie_even = 1.0 + 2.0**-11 - self.assertEqual(f16_to_bits(tie_even), 0x3C00) - - tie_odd = 1.0 + 2.0**-10 + 2.0**-11 - self.assertEqual(f16_to_bits(tie_odd), 0x3C02) - - -class SimdWaveInterpP1lv: - """Simulates an RDNA2 SIMD wave (Wave32 or Wave64) executing perspective interpolation instructions. - - Models: - - Wave32 (32 lanes) and Wave64 (64 lanes). - - Per-lane VGPR bank (256 registers per lane). - - Shared SGPR bank (128 scalar registers). - - EXEC mask (32-bit or 64-bit) gating lane evaluation and register writes. - - Inactive lane preservation: disabled lanes keep their prior VGPR state. - - v_interp_p1lv_f16: evaluates first-axis perspective interpolation intermediate in f32. - - v_interp_p2_f16: accumulates second axis, applies optional clamp, narrows to f16 (nearest-even). - """ - - def __init__(self, wave_size: int = 32, exec_mask: int | None = None): - if wave_size not in (32, 64): - raise ValueError(f"Unsupported wave_size: {wave_size}") - self.wave_size = wave_size - self.mask_all = (1 << wave_size) - 1 - self.exec_mask = self.mask_all if exec_mask is None else (exec_mask & self.mask_all) - self.sgprs = [0] * 128 - self.vgprs = [[0] * 256 for _ in range(wave_size)] - - def is_lane_active(self, lane: int) -> bool: - return bool((self.exec_mask >> lane) & 1) - - def set_lane_barycentrics(self, lane: int, i_coord: float, j_coord: float, - v_i: int = 0, v_j: int = 1): - """Set barycentric I and J coordinates in given VGPRs for lane.""" - self.vgprs[lane][v_i] = f32_to_bits(i_coord) - self.vgprs[lane][v_j] = f32_to_bits(j_coord) - - def v_interp_p1lv_f16(self, vdst: int, vsrc_i: int, - attr_packed: tuple[int, int, int], - high: bool = False): - """Execute v_interp_p1lv_f16 across all active SIMD lanes.""" - vals = [unpack_f16_halves(p)[1 if high else 0] for p in attr_packed] - p0, p1 = vals[0], vals[1] - - for lane in range(self.wave_size): - if not self.is_lane_active(lane): - continue - i_coord = bits_to_f32(self.vgprs[lane][vsrc_i]) - accum_f32 = v_interp_p1lv_f16_ref(i_coord, p0, p1) - self.vgprs[lane][vdst] = f32_to_bits(accum_f32) - - def v_interp_p2_f16(self, vdst: int, vsrc_j: int, - attr_packed: tuple[int, int, int], - partial_src: int, - high: bool = False, clamp: bool = False): - """Execute v_interp_p2_f16 across all active SIMD lanes.""" - vals = [unpack_f16_halves(p)[1 if high else 0] for p in attr_packed] - p0, p2 = vals[0], vals[2] - - for lane in range(self.wave_size): - if not self.is_lane_active(lane): - continue - j_coord = bits_to_f32(self.vgprs[lane][vsrc_j]) - accum_f32 = bits_to_f32(self.vgprs[lane][partial_src]) - res_bits = v_interp_p2_f16_ref(j_coord, p0, p2, accum_f32, clamp=clamp) - self.vgprs[lane][vdst] = res_bits - - -class InterpP1lvSimdMultiLaneTests(unittest.TestCase): - """SIMD multi-lane wave evaluation tests for half-precision perspective interpolation.""" - - def test_wave32_uniform_triangle_raster_grid(self): - wave = SimdWaveInterpP1lv(wave_size=32) - attr0 = (pack_f16(1.0, 2.0), pack_f16(3.0, 6.0), pack_f16(5.0, 10.0)) - - bary_coords = [] - for lane in range(32): - i_val = (lane % 8) * 0.1 - j_val = (lane // 8) * 0.15 - bary_coords.append((i_val, j_val)) - wave.set_lane_barycentrics(lane, i_val, j_val) - - wave.v_interp_p1lv_f16(vdst=2, vsrc_i=0, attr_packed=attr0, high=False) - wave.v_interp_p2_f16(vdst=2, vsrc_j=1, attr_packed=attr0, partial_src=2, high=False) - - wave.v_interp_p1lv_f16(vdst=3, vsrc_i=0, attr_packed=attr0, high=True) - wave.v_interp_p2_f16(vdst=3, vsrc_j=1, attr_packed=attr0, partial_src=3, high=True) - - for lane, (i_val, j_val) in enumerate(bary_coords): - _, want_lo = v_interp_p1lv_eval_ref(i_val, j_val, 1.0, 3.0, 5.0) - _, want_hi = v_interp_p1lv_eval_ref(i_val, j_val, 2.0, 6.0, 10.0) - self.assertEqual(wave.vgprs[lane][2], want_lo) - self.assertEqual(wave.vgprs[lane][3], want_hi) - - def test_wave64_divergent_exec_masking(self): - wave = SimdWaveInterpP1lv(wave_size=64) - attr0 = (pack_f16(2.0, -1.0), pack_f16(4.0, 3.0), pack_f16(8.0, 7.0)) - - for lane in range(64): - wave.vgprs[lane][2] = 0xDEAD0000 | lane - - active_mask = 0 - for lane in range(64): - if lane % 3 != 0: - active_mask |= (1 << lane) - wave.exec_mask = active_mask - - for lane in range(64): - wave.set_lane_barycentrics(lane, 0.25, 0.5) - - wave.v_interp_p1lv_f16(vdst=2, vsrc_i=0, attr_packed=attr0, high=False) - wave.v_interp_p2_f16(vdst=2, vsrc_j=1, attr_packed=attr0, partial_src=2, high=False) - - _, want_bits = v_interp_p1lv_eval_ref(0.25, 0.5, 2.0, 4.0, 8.0) - for lane in range(64): - if lane % 3 != 0: - self.assertEqual(wave.vgprs[lane][2], want_bits) - else: - self.assertEqual(wave.vgprs[lane][2], 0xDEAD0000 | lane) - - def test_checkerboard_and_half_wave_divergence(self): - wave = SimdWaveInterpP1lv(wave_size=32, exec_mask=0x55555555) - for lane in range(32): - wave.vgprs[lane][4] = 0xCAFE0000 | lane - wave.set_lane_barycentrics(lane, 0.2, 0.4) - - attr0 = (pack_f16(10.0, 0.0), pack_f16(20.0, 0.0), pack_f16(30.0, 0.0)) - wave.v_interp_p1lv_f16(vdst=4, vsrc_i=0, attr_packed=attr0, high=False) - wave.v_interp_p2_f16(vdst=4, vsrc_j=1, attr_packed=attr0, partial_src=4, high=False) - - _, want_bits = v_interp_p1lv_eval_ref(0.2, 0.4, 10.0, 20.0, 30.0) - for lane in range(32): - if lane % 2 == 0: - self.assertEqual(wave.vgprs[lane][4], want_bits) - else: - self.assertEqual(wave.vgprs[lane][4], 0xCAFE0000 | lane) - - wave_odd = SimdWaveInterpP1lv(wave_size=32, exec_mask=0xAAAAAAAA) - for lane in range(32): - wave_odd.vgprs[lane][4] = 0xBEEF0000 | lane - wave_odd.set_lane_barycentrics(lane, 0.1, 0.7) - - wave_odd.v_interp_p1lv_f16(vdst=4, vsrc_i=0, attr_packed=attr0, high=False) - wave_odd.v_interp_p2_f16(vdst=4, vsrc_j=1, attr_packed=attr0, partial_src=4, high=False) - - _, want_bits_odd = v_interp_p1lv_eval_ref(0.1, 0.7, 10.0, 20.0, 30.0) - for lane in range(32): - if lane % 2 == 1: - self.assertEqual(wave_odd.vgprs[lane][4], want_bits_odd) - else: - self.assertEqual(wave_odd.vgprs[lane][4], 0xBEEF0000 | lane) - - def test_multi_lane_high_vs_low_packed_independence(self): - wave = SimdWaveInterpP1lv(wave_size=32) - attr0 = (pack_f16(-2.0, 100.0), pack_f16(0.0, 200.0), pack_f16(4.0, 300.0)) - for lane in range(32): - wave.set_lane_barycentrics(lane, lane / 64.0, (31 - lane) / 64.0) - - wave.v_interp_p1lv_f16(vdst=2, vsrc_i=0, attr_packed=attr0, high=False) - wave.v_interp_p2_f16(vdst=2, vsrc_j=1, attr_packed=attr0, partial_src=2, high=False) - - wave.v_interp_p1lv_f16(vdst=3, vsrc_i=0, attr_packed=attr0, high=True) - wave.v_interp_p2_f16(vdst=3, vsrc_j=1, attr_packed=attr0, partial_src=3, high=True) - - for lane in range(32): - i_c = lane / 64.0 - j_c = (31 - lane) / 64.0 - _, want_lo = v_interp_p1lv_eval_ref(i_c, j_c, -2.0, 0.0, 4.0) - _, want_hi = v_interp_p1lv_eval_ref(i_c, j_c, 100.0, 200.0, 300.0) - self.assertEqual(wave.vgprs[lane][2], want_lo) - self.assertEqual(wave.vgprs[lane][3], want_hi) - - def test_multi_sample_shader_translation_evaluation(self): - spv, _ = translate_with_flags("ps_p1lv_multi", P1LV_SHADER, dxbc=PS_ATTR01_DXBC) - y_lo = (-1.0, -1.0, 0.5) - y_hi = (0.5, 1.5, 2.5) - z_lo = (1.0, 3.0, 5.0) - w_raw = (0x1234, 0x5678, 0x9ABC) - attr0 = [(pack_f16(lo, hi), pack_f16(yl, yh), pack_f16(zl, 0.0), wr) - for lo, hi, yl, yh, zl, wr in zip(LO, HI, y_lo, y_hi, z_lo, w_raw)] - attr1 = [(f32_bits(x), 0, 0, 0) for x in (-2.0, 2.0, 4.0)] - - sample_points = [ - (0.1, 0.1), - (0.2, 0.3), - (0.5, 0.2), - (0.0, 0.8), - (0.33, 0.33), - (0.7, 0.1), - (0.1, 0.6), - (0.25, 0.5), - ] - for i_c, j_c in sample_points: - with self.subTest(i=i_c, j=j_c): - bary_w = (1.0 - i_c - j_c, i_c, j_c) - inputs = support.varyings(spv, {0: attr0, 1: attr1}, bary_w) - out = support.run_fragment(spv, inputs=inputs) - mrt0, mrt1 = out["%out_mrt0"], out["%out_mrt1"] - - _, want_x_lo = v_interp_p1lv_eval_ref(i_c, j_c, LO[0], LO[1], LO[2], clamp=False) - _, want_x_hi = v_interp_p1lv_eval_ref(i_c, j_c, HI[0], HI[1], HI[2], clamp=False) - _, want_y_lo = v_interp_p1lv_eval_ref(i_c, j_c, y_lo[0], y_lo[1], y_lo[2], clamp=True) - _, want_y_hi = v_interp_p1lv_eval_ref(i_c, j_c, y_hi[0], y_hi[1], y_hi[2], clamp=True) - want_z_lo_f32 = v_interp_p1lv_f16_ref(i_c, z_lo[0], z_lo[1]) + (z_lo[2] - z_lo[0]) * j_c - - self.assertEqual(mrt0[0] & 0xFFFF, want_x_lo) - self.assertEqual(mrt0[1] & 0xFFFF, want_x_hi) - self.assertEqual(mrt0[2] & 0xFFFF, want_y_lo) - self.assertEqual(mrt0[3] & 0xFFFF, want_y_hi) - self.assertAlmostEqual(bits_to_f32(mrt1[0]), want_z_lo_f32, delta=1e-4) - - -class InterpP1lvSubnormalAndClippingTests(unittest.TestCase): - """Subnormal weights, denormal attribute preservation, and clipping boundary tests.""" - - def test_subnormal_f16_attribute_interpolation(self): - p0 = bits_to_f16(0x0002) - p1 = bits_to_f16(0x0004) - p2 = bits_to_f16(0x0008) - - _, res_mid = v_interp_p1lv_eval_ref(0.5, 0.0, p0, p1, p2) - self.assertEqual(res_mid, 0x0003) - - _, res_v0 = v_interp_p1lv_eval_ref(0.0, 0.0, p0, p1, p2) - self.assertEqual(res_v0, 0x0002) - - _, res_v2 = v_interp_p1lv_eval_ref(0.0, 0.5, p0, p1, p2) - self.assertEqual(res_v2, 0x0005) - - def test_subnormal_barycentric_weights(self): - p0, p1, p2 = 5.0, 25.0, 50.0 - subnormal_w = 1e-15 - _, res = v_interp_p1lv_eval_ref(subnormal_w, subnormal_w, p0, p1, p2) - self.assertEqual(res, f16_to_bits(5.0)) - - def test_subnormal_to_normal_transition(self): - p0 = 0.0 - p1 = bits_to_f16(0x0400) - p2 = 0.0 - - _, res_half = v_interp_p1lv_eval_ref(0.5, 0.0, p0, p1, p2) - self.assertEqual(res_half, 0x0200) - - _, res_quarter = v_interp_p1lv_eval_ref(0.25, 0.0, p0, p1, p2) - self.assertEqual(res_quarter, 0x0100) - - _, res_one = v_interp_p1lv_eval_ref(1.0, 0.0, p0, p1, p2) - self.assertEqual(res_one, 0x0400) - - def test_hypotenuse_boundary_clipping(self): - p0, p1, p2 = 10.0, 20.0, 30.0 - for i_c, j_c in [(0.5, 0.5), (0.25, 0.75), (0.0, 1.0), (1.0, 0.0)]: - with self.subTest(i=i_c, j=j_c): - _, got_bits = v_interp_p1lv_eval_ref(i_c, j_c, p0, p1, p2) - expected_val = i_c * p1 + j_c * p2 - self.assertEqual(got_bits, f16_to_bits(expected_val)) - - def test_extreme_extrapolation_and_clamp_boundaries(self): - p0, p1, p2 = 0.5, 1.5, 2.5 - _, clamped_low = v_interp_p1lv_eval_ref(-2.0, 0.5, p0, p1, p2, clamp=True) - self.assertEqual(clamped_low, 0x0000) - - _, unclamped_low = v_interp_p1lv_eval_ref(-2.0, 0.5, p0, p1, p2, clamp=False) - self.assertLess(bits_to_f16(unclamped_low), 0.0) - - _, clamped_high = v_interp_p1lv_eval_ref(5.0, 2.0, p0, p1, p2, clamp=True) - self.assertEqual(clamped_high, 0x3C00) - - _, unclamped_high = v_interp_p1lv_eval_ref(5.0, 2.0, p0, p1, p2, clamp=False) - self.assertGreater(bits_to_f16(unclamped_high), 1.0) - - def test_negative_zero_clamping(self): - p0, p1, p2 = -0.1, -0.2, -0.5 - _, res_bits = v_interp_p1lv_eval_ref(0.3, 0.3, p0, p1, p2, clamp=True) - self.assertEqual(res_bits, 0x0000) - self.assertNotEqual(res_bits, 0x8000) - - -class InterpP1lvNegativeControlsTests(unittest.TestCase): - """Negative controls and mutation detection tests for half-precision interpolation.""" - - def test_mutation_axis_swap_detection(self): - p0, p1, p2 = 1.0, 5.0, 20.0 - i_c, j_c = 0.2, 0.7 - _, normal_bits = v_interp_p1lv_eval_ref(i_c, j_c, p0, p1, p2) - _, swapped_bits = v_interp_p1lv_eval_ref(j_c, i_c, p0, p1, p2) - self.assertNotEqual(normal_bits, swapped_bits) - - def test_mutation_half_selection_detection(self): - packed = pack_f16(1.5, 45.0) - lo, hi = unpack_f16_halves(packed) - self.assertEqual(lo, 1.5) - self.assertEqual(hi, 45.0) - self.assertNotEqual(lo, hi) - - def test_mutation_clamp_removal_detection(self): - p0, p1, p2 = 2.0, 4.0, 6.0 - _, clamped = v_interp_p1lv_eval_ref(0.5, 0.5, p0, p1, p2, clamp=True) - _, unclamped = v_interp_p1lv_eval_ref(0.5, 0.5, p0, p1, p2, clamp=False) - self.assertEqual(clamped, 0x3C00) - self.assertNotEqual(unclamped, clamped) - - def test_mutation_rtz_vs_nearest_even(self): - val = 1.0 + 2.0**-11 - rne_bits = f16_to_bits(val) - self.assertEqual(rne_bits, 0x3C00) - - val_odd = 1.0 + 2.0**-10 + 2.0**-11 - rne_odd_bits = f16_to_bits(val_odd) - self.assertEqual(rne_odd_bits, 0x3C02) - rtz_odd_bits = 0x3C01 - self.assertNotEqual(rne_odd_bits, rtz_odd_bits) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_interp_reaching_write.py b/tests/semantic/test_interp_reaching_write.py deleted file mode 100644 index c6f5000f6..000000000 --- a/tests/semantic/test_interp_reaching_write.py +++ /dev/null @@ -1,80 +0,0 @@ -"""interp_ij_analysis: a write of the I/J register at instruction index 0 (or after the site in a loop) reaches it. - -`reaching_write` tested predecessor blocks with `any(w for w in ws ...)`, so a write at instruction index 0 -(falsy) never counted, and it seeded the search with the site's own block, so a write later in that block that -a loop back-edge brings round was never seen. Either way a computed barycentric pair was treated as pristine. -The programs are hand-built instruction lists; no game data, no GPU. -""" -import os -import sys -import unittest -from types import SimpleNamespace - -HERE = os.path.dirname(os.path.abspath(__file__)) -ROOT = os.path.dirname(os.path.dirname(HERE)) -TOOLS_DIR = os.environ.get("LEONIDA_TOOLS_DIR") or os.path.join(ROOT, "tools") -sys.dont_write_bytecode = True -sys.path.insert(0, TOOLS_DIR) -import rdna2spirv # noqa: E402 - - -def make(op, args, pc, target=None): - ins = {"op": op, "args": args, "pc": pc, "enc": "00000000"} - if target is not None: - ins["target"] = target - return ins - - -def vg(r): - return {"k": "vgpr", "r": r} - - -def attr(): - return {"k": "attr", "a": 0, "c": 0} - - -def interp_pair(pc): - return [make("v_interp_p1_f32", [vg(2), vg(0), attr()], pc), - make("v_interp_p2_f32", [vg(2), vg(1), attr()], pc + 4)] - - -def analyse(insns): - g = SimpleNamespace(v_interp_copy={}, pixel_interpolants=None, frag_inputs={}) - return rdna2spirv.interp_ij_analysis(insns, g), insns - - -class ReachingWrite(unittest.TestCase): - def test_write_at_index_zero_reaches_branch_target(self): - insns = [make("v_mov_b32", [vg(0), {"k": "imm", "v": 0}], 0), - make("s_branch", [{"k": "imm", "v": 0}], 4, target=8)] + interp_pair(8) + \ - [make("s_endpgm", [], 16)] - attrs, insns = analyse(insns) - self.assertEqual(attrs, {0}) - self.assertIn("ij", insns[2]) - - def test_write_at_index_one_still_reaches(self): - insns = [make("s_nop", [], 0), - make("v_mov_b32", [vg(0), {"k": "imm", "v": 0}], 4), - make("s_branch", [{"k": "imm", "v": 0}], 8, target=12)] + interp_pair(12) + \ - [make("s_endpgm", [], 20)] - attrs, _ = analyse(insns) - self.assertEqual(attrs, {0}) - - def test_no_write_stays_pristine(self): - insns = [make("s_nop", [], 0), - make("s_branch", [{"k": "imm", "v": 0}], 4, target=8)] + interp_pair(8) + \ - [make("s_endpgm", [], 16)] - attrs, _ = analyse(insns) - self.assertEqual(attrs, set()) - - def test_loop_back_edge_write_after_site(self): - # block 0: interp pair, then v0 is rewritten and the loop branches back to the pair. - insns = interp_pair(0) + [make("v_mov_b32", [vg(0), {"k": "imm", "v": 0}], 8), - make("s_cbranch_scc1", [{"k": "imm", "v": 0}], 12, target=0), - make("s_endpgm", [], 16)] - attrs, _ = analyse(insns) - self.assertEqual(attrs, {0}) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_interp_shared_lds.py b/tests/semantic/test_interp_shared_lds.py deleted file mode 100644 index f97b7f406..000000000 --- a/tests/semantic/test_interp_shared_lds.py +++ /dev/null @@ -1,118 +0,0 @@ -"""spirv_mini_interp.run_workgroup shares Workgroup (LDS) memory between its invocations, and OpControlBarrier. - -Until this change every invocation of run_workgroup had its own zero-initialised Workgroup variables, so no CPU test -could check lanes communicating through LDS or racing on an LDS dword (each saw only its own writes), and -OpControlBarrier (s_barrier) was refused. Now the Workgroup boxes are the workgroup's, and a barrier is a point every -invocation must reach together, as a subgroup operation is; run_fragment still refuses it. The programs below are -translated compute shaders (one or two wave32 waves, 512 bytes of LDS) writing their results through the -vk_compute_test V#. Standard library only; no GPU, no game files. -""" -import os -import struct -import sys -import unittest - -HERE = os.path.dirname(os.path.abspath(__file__)) -if HERE not in sys.path: - sys.path.insert(0, HERE) # python -I leaves the script's folder off sys.path - -import support # noqa: E402 (support puts tools/ on sys.path, honouring LEONIDA_TOOLS_DIR) -import spirv_mini_interp as si # noqa: E402 - -VSHARP = [0, 0, 0xFFFFFFFF, 0x31016FAC] # base 0, num_records max, raw - - -def fssm(invocations): - b = bytearray(0x148) - struct.pack_into("<4I", b, 0x138, 0x8088, invocations, 1, 1) # 4 user SGPRs, wg id in s4, 512 B LDS - return bytes(b) - - -def run(name, lines, invocations=32): - spv = support.translate_lines(name, lines + ["s_endpgm"], fssm=fssm(invocations)) - mem = {} - si.run_workgroup(spv, invocations, 32, inputs_for=lambda i: {"%wg_id": (0, 0, 0), "%local_id": (i, 0, 0), - "%sg_lane": i % 32}, - push_constants=VSHARP + [0] * 28, memory=mem) - return [mem.get(4 * i) for i in range(invocations)] - - -STORE_V3 = ["v_lshlrev_b32_e32 v4, 2, v0", "buffer_store_dword v3, v4, s[0:3], 0 offen"] # out[lane] = v3 - - -class SharedLds(unittest.TestCase): - def test_one_lane_writes_every_lane_reads_after_the_barrier(self): - lines = ["v_mov_b32_e32 v1, 0x40", "v_cmpx_eq_u32_e32 0, v0", "v_mov_b32_e32 v2, 0x1234", - "ds_write_b32 v1, v2", "s_mov_b32 exec_lo, -1", "s_waitcnt lgkmcnt(0)", "s_barrier", - "ds_read_b32 v3, v1", "s_waitcnt lgkmcnt(0)"] + STORE_V3 - for n in (32, 64): # one wave, and two waves of one workgroup - with self.subTest(invocations=n): - self.assertEqual(run("cs_lds_bcast", lines, n), [0x1234] * n) - - def test_lanes_racing_on_one_dword(self): - # every lane adds 1 to one LDS dword (zero-initialised); after the barrier each reads the total - lines = ["v_mov_b32_e32 v1, 0x80", "v_mov_b32_e32 v2, 1", "ds_add_u32 v1, v2", "s_waitcnt lgkmcnt(0)", - "s_barrier", "ds_read_b32 v3, v1", "s_waitcnt lgkmcnt(0)"] + STORE_V3 - for n in (32, 64): - with self.subTest(invocations=n): - self.assertEqual(run("cs_lds_count", lines, n), [n] * n) - - def test_returned_values_are_each_old_value_once(self): - lines = ["v_mov_b32_e32 v1, 0x80", "v_mov_b32_e32 v2, 1", "ds_add_rtn_u32 v3, v1, v2", - "s_waitcnt lgkmcnt(0)"] + STORE_V3 - self.assertEqual(sorted(run("cs_lds_ticket", lines)), list(range(32))) - - def test_a_cas_loop_on_shared_lds(self): - # ds_add_f32 is an OpAtomicCompareExchange loop: 32 lanes each add 1.0 to one dword - lines = ["v_mov_b32_e32 v1, 0x80", "v_mov_b32_e32 v2, 1.0", "ds_add_f32 v1, v2", "s_waitcnt lgkmcnt(0)", - "s_barrier", "ds_read_b32 v3, v1", "s_waitcnt lgkmcnt(0)"] + STORE_V3 - self.assertEqual(run("cs_lds_fadd", lines), [struct.unpack(" int: - """Deterministic population count for 64-bit integer (Python 3.9 compatible).""" - return bin(val & MASK64).count("1") - - -def ref_popcount_u32(val: int) -> int: - """Deterministic population count for 32-bit integer.""" - return bin(val & MASK32).count("1") - - -def ref_find_first_one_u64(val: int) -> int: - """Find index of lowest set bit (0..63) in 64-bit uint, or -1 (0xFFFFFFFF) if zero.""" - val &= MASK64 - if val == 0: - return MASK32 - return (val & -val).bit_length() - 1 - - -def ref_find_first_one_u32(val: int) -> int: - """Find index of lowest set bit (0..31) in 32-bit uint, or -1 (0xFFFFFFFF) if zero.""" - val &= MASK32 - if val == 0: - return MASK32 - return (val & -val).bit_length() - 1 - - -def ref_bcnt1_i32_b64(src64: int) -> tuple[int, int]: - """Reference oracle for s_bcnt1_i32_b64: (result_u32, scc).""" - count = ref_popcount_u64(src64) - scc = 1 if count != 0 else 0 - return count, scc - - -def ref_ff1_i32_b64(src64: int) -> int: - """Reference oracle for s_ff1_i32_b64: lowest bit index 0..63 or 0xFFFFFFFF.""" - return ref_find_first_one_u64(src64) - - -def ref_subgroup_wave_mask_reduction(lane_bits: list[int] | dict[int, bool], wave_size: int = 64) -> tuple[int, int]: - """Model OpGroupNonUniformBitwiseOr Reduce across lanes for low and high halves.""" - lo_accum = 0 - hi_accum = 0 - for lane in range(wave_size): - bit_val = 1 if (lane_bits[lane] if isinstance(lane_bits, list) else lane_bits.get(lane, False)) else 0 - if bit_val: - if lane < 32: - lo_accum |= (1 << (lane & 31)) - else: - hi_accum |= (1 << (lane & 31)) - return lo_accum & MASK32, hi_accum & MASK32 - - -class LaneMaskReductionInterpreter: - """Semantic interpreter modeling whole-wave execution, lane reductions, and scalar ALU ops.""" - - def __init__(self, wave_size: int = 64, num_sgprs: int = 106): - if wave_size not in (32, 64): - raise ValueError(f"unsupported wave_size: {wave_size}") - self.wave_size = wave_size - self.num_sgprs = num_sgprs - self.sgprs = [0] * num_sgprs - self.scc = 0 - self.exec_mask = (1 << wave_size) - 1 - self.vcc_mask = 0 - self.cur_lane_masks = set() # set of SGPR indices or 'vcc', 'exec' that hold lane masks - - def reset(self): - self.sgprs = [0] * self.num_sgprs - self.scc = 0 - self.exec_mask = (1 << self.wave_size) - 1 - self.vcc_mask = 0 - self.cur_lane_masks.clear() - - def set_sgpr_u32(self, r: int, val: int): - self.sgprs[r] = val & MASK32 - - def get_sgpr_u32(self, r: int) -> int: - return self.sgprs[r] & MASK32 - - def set_sgpr_u64(self, r: int, val64: int): - self.sgprs[r] = val64 & MASK32 - self.sgprs[r + 1] = (val64 >> 32) & MASK32 - - def get_sgpr_u64(self, r: int) -> int: - lo = self.get_sgpr_u32(r) - hi = self.get_sgpr_u32(r + 1) - return (hi << 32) | lo - - def set_exec(self, mask64: int): - full_mask = (1 << self.wave_size) - 1 - self.exec_mask = mask64 & full_mask - - def set_vcc(self, mask64: int): - full_mask = (1 << self.wave_size) - 1 - self.vcc_mask = mask64 & full_mask - - def resolve_source_mask(self, operand: dict | str) -> tuple[int, int]: - """Resolve a 64-bit operand to (lo_word, hi_word). - - If the operand holds a lane mask, simulates the subgroup OpGroupNonUniformBitwiseOr Reduce. - Otherwise loads plain scalar dwords. - """ - if isinstance(operand, str): - operand_kind = operand - elif isinstance(operand, dict): - operand_kind = operand.get("t") or operand.get("k") - else: - raise TypeError(f"unsupported operand format: {operand}") - - if operand_kind in ("exec", "exec_b64"): - return ref_subgroup_wave_mask_reduction( - [(self.exec_mask & (1 << lane)) != 0 for lane in range(self.wave_size)], - self.wave_size, - ) - if operand_kind in ("vcc", "vcc_b64"): - return ref_subgroup_wave_mask_reduction( - [(self.vcc_mask & (1 << lane)) != 0 for lane in range(self.wave_size)], - self.wave_size, - ) - if isinstance(operand, dict) and operand.get("k") == "sgpr": - r = operand["r"] - n = operand.get("n", 2) - is_lane_mask = (r in self.cur_lane_masks) and (r + 1 in self.cur_lane_masks if n == 2 else True) - if is_lane_mask: - mask_val = self.get_sgpr_u64(r) - return ref_subgroup_wave_mask_reduction( - [(mask_val & (1 << lane)) != 0 for lane in range(self.wave_size)], - self.wave_size, - ) - lo = self.get_sgpr_u32(r) - hi = self.get_sgpr_u32(r + 1) if n == 2 else 0 - return lo, hi - if isinstance(operand, dict) and operand.get("k") == "imm": - imm = operand["v"] & MASK64 - return imm & MASK32, (imm >> 32) & MASK32 - raise ValueError(f"unsupported operand: {operand}") - - def eval_s_bcnt1_i32_b64(self, dst_r: int, src_operand: dict | str) -> int: - """Execute s_bcnt1_i32_b64: counts bits in 64-bit source, updates SCC.""" - lo, hi = self.resolve_source_mask(src_operand) - c1 = ref_popcount_u32(lo) - c2 = ref_popcount_u32(hi) - total = (c1 + c2) & MASK32 - self.set_sgpr_u32(dst_r, total) - self.scc = 1 if total != 0 else 0 - return total - - def eval_s_ff1_i32_b64(self, dst_r: int, src_operand: dict | str) -> int: - """Execute s_ff1_i32_b64: finds first set bit in 64-bit source, SCC unchanged.""" - lo, hi = self.resolve_source_mask(src_operand) - l = ref_find_first_one_u32(lo) - h = ref_find_first_one_u32(hi) - - if lo != 0: - result = l - elif hi != 0: - result = (h + 32) & MASK32 - else: - result = MASK32 # -1 - - self.set_sgpr_u32(dst_r, result) - # s_ff1 does NOT touch SCC - return result - - def eval_s_bcnt1_i32_b32(self, dst_r: int, src_operand: dict | str, half: str | None = None) -> int: - """Execute s_bcnt1_i32_b32: 32-bit count, updates SCC.""" - lo, hi = self.resolve_source_mask(src_operand) - if half == "hi": - lo, hi = hi, 0 - elif half == "lo": - hi = 0 - c1 = ref_popcount_u32(lo) - c2 = ref_popcount_u32(hi) - total = (c1 + c2) & MASK32 - self.set_sgpr_u32(dst_r, total) - self.scc = 1 if total != 0 else 0 - return total - - def eval_s_ff1_i32_b32(self, dst_r: int, src_operand: dict | str, half: str | None = None) -> int: - """Execute s_ff1_i32_b32: 32-bit find-first-one, SCC unchanged.""" - lo, hi = self.resolve_source_mask(src_operand) - if half == "hi": - lo = hi - result = ref_find_first_one_u32(lo) - self.set_sgpr_u32(dst_r, result) - return result - - -class TestLaneMaskReductionsReference(unittest.TestCase): - """Verify independent pure-Python mathematical reference oracles for bit reductions.""" - - def test_bcnt1_u64_empty_and_full(self): - self.assertEqual(ref_bcnt1_i32_b64(0), (0, 0)) - self.assertEqual(ref_bcnt1_i32_b64(MASK64), (64, 1)) - - def test_bcnt1_u64_single_bits_all_positions(self): - for bit in range(64): - val = 1 << bit - count, scc = ref_bcnt1_i32_b64(val) - self.assertEqual(count, 1, f"bit position {bit} must have count 1") - self.assertEqual(scc, 1, f"bit position {bit} must set SCC to 1") - - def test_bcnt1_u64_half_masks(self): - low_half = 0x00000000FFFFFFFF - high_half = 0xFFFFFFFF00000000 - self.assertEqual(ref_bcnt1_i32_b64(low_half), (32, 1)) - self.assertEqual(ref_bcnt1_i32_b64(high_half), (32, 1)) - - def test_bcnt1_u64_alternating_patterns(self): - self.assertEqual(ref_bcnt1_i32_b64(0x5555555555555555), (32, 1)) - self.assertEqual(ref_bcnt1_i32_b64(0xAAAAAAAAAAAAAAAA), (32, 1)) - self.assertEqual(ref_bcnt1_i32_b64(0x3333333333333333), (32, 1)) - self.assertEqual(ref_bcnt1_i32_b64(0x0F0F0F0F0F0F0F0F), (32, 1)) - - def test_bcnt1_u64_sparse_subgroup_strides(self): - # Selected lanes: (lane & 7) == 5 -> 8 lanes active in a 64-lane wave - sparse_mask = sum(1 << lane for lane in range(64) if (lane & 7) == 5) - self.assertEqual(ref_bcnt1_i32_b64(sparse_mask), (8, 1)) - - def test_ff1_u64_empty_mask_returns_all_ones(self): - # When no bit is set, FindILsb conventions return -1 (0xFFFFFFFF in uint) - self.assertEqual(ref_ff1_i32_b64(0), MASK32) - - def test_ff1_u64_single_bits_all_positions(self): - for bit in range(64): - val = 1 << bit - first = ref_ff1_i32_b64(val) - self.assertEqual(first, bit, f"bit position {bit} must be found as first one") - - def test_ff1_u64_precedence_low_over_high(self): - # When bits are set in both halves, low half takes precedence - val = (1 << 5) | (1 << 45) - self.assertEqual(ref_ff1_i32_b64(val), 5) - - val_boundary = (1 << 31) | (1 << 32) - self.assertEqual(ref_ff1_i32_b64(val_boundary), 31) - - val_ends = 1 | (1 << 63) - self.assertEqual(ref_ff1_i32_b64(val_ends), 0) - - def test_ff1_u64_high_half_only(self): - # When low half is 0, high half bits are biased by +32 - self.assertEqual(ref_ff1_i32_b64(1 << 32), 32) - self.assertEqual(ref_ff1_i32_b64(1 << 40), 40) - self.assertEqual(ref_ff1_i32_b64(1 << 63), 63) - self.assertEqual(ref_ff1_i32_b64(0xFFFFFFFF00000000), 32) - - def test_subgroup_wave_mask_reduction_logic(self): - # 64-lane test: lane 7 and lane 42 set - lane_bits = [i in (7, 42) for i in range(64)] - lo, hi = ref_subgroup_wave_mask_reduction(lane_bits, wave_size=64) - self.assertEqual(lo, 1 << 7) - self.assertEqual(hi, 1 << (42 - 32)) - - # Wave32 test: high half is strictly 0 - lane_bits_32 = [i == 10 for i in range(32)] - lo32, hi32 = ref_subgroup_wave_mask_reduction(lane_bits_32, wave_size=32) - self.assertEqual(lo32, 1 << 10) - self.assertEqual(hi32, 0) - - -class TestLaneMaskSemanticInterpreter(unittest.TestCase): - """Test full semantic interpreter execution across wave32 and wave64 configurations.""" - - def setUp(self): - self.interp64 = LaneMaskReductionInterpreter(wave_size=64) - self.interp32 = LaneMaskReductionInterpreter(wave_size=32) - - def test_exec_mask_bcnt1_population_counting(self): - # Full wave: 64 lanes active - self.interp64.set_exec(MASK64) - count = self.interp64.eval_s_bcnt1_i32_b64(dst_r=4, src_operand="exec") - self.assertEqual(count, 64) - self.assertEqual(self.interp64.get_sgpr_u32(4), 64) - self.assertEqual(self.interp64.scc, 1) - - # Empty wave: 0 lanes active - self.interp64.set_exec(0) - count_zero = self.interp64.eval_s_bcnt1_i32_b64(dst_r=4, src_operand="exec") - self.assertEqual(count_zero, 0) - self.assertEqual(self.interp64.get_sgpr_u32(4), 0) - self.assertEqual(self.interp64.scc, 0) - - def test_exec_mask_ff1_find_first_one(self): - # Full wave: first one is lane 0 - self.interp64.set_exec(MASK64) - first = self.interp64.eval_s_ff1_i32_b64(dst_r=6, src_operand="exec") - self.assertEqual(first, 0) - self.assertEqual(self.interp64.get_sgpr_u32(6), 0) - - # High half only: lanes 32..63 active - self.interp64.set_exec(0xFFFFFFFF00000000) - first_hi = self.interp64.eval_s_ff1_i32_b64(dst_r=6, src_operand="exec") - self.assertEqual(first_hi, 32) - self.assertEqual(self.interp64.get_sgpr_u32(6), 32) - - # Empty wave: returns 0xFFFFFFFF - self.interp64.set_exec(0) - first_empty = self.interp64.eval_s_ff1_i32_b64(dst_r=6, src_operand="exec") - self.assertEqual(first_empty, MASK32) - self.assertEqual(self.interp64.get_sgpr_u32(6), MASK32) - - def test_ff1_preserves_scc(self): - """s_ff1 must NOT modify the SCC condition register.""" - self.interp64.scc = 1 - self.interp64.set_exec(0) - self.interp64.eval_s_ff1_i32_b64(dst_r=2, src_operand="exec") - self.assertEqual(self.interp64.scc, 1, "s_ff1 on empty mask must preserve SCC == 1") - - self.interp64.scc = 0 - self.interp64.set_exec(MASK64) - self.interp64.eval_s_ff1_i32_b64(dst_r=2, src_operand="exec") - self.assertEqual(self.interp64.scc, 0, "s_ff1 on non-empty mask must preserve SCC == 0") - - def test_vcc_mask_reduction(self): - vcc_test_pattern = (1 << 12) | (1 << 37) | (1 << 50) - self.interp64.set_vcc(vcc_test_pattern) - - count = self.interp64.eval_s_bcnt1_i32_b64(dst_r=10, src_operand="vcc") - self.assertEqual(count, 3) - self.assertEqual(self.interp64.scc, 1) - - ff1 = self.interp64.eval_s_ff1_i32_b64(dst_r=11, src_operand="vcc") - self.assertEqual(ff1, 12) - - def test_sgpr_pair_lane_mask_vs_scalar(self): - """An SGPR pair marked as lane mask undergoes subgroup reduction; unmarked is scalar.""" - mask_val = (1 << 5) | (1 << 35) - - # 1. Marked as lane mask in cur_lane_masks - self.interp64.cur_lane_masks = {16, 17} - self.interp64.set_sgpr_u64(16, mask_val) - c_mask = self.interp64.eval_s_bcnt1_i32_b64(dst_r=20, src_operand={"k": "sgpr", "r": 16, "n": 2}) - ff1_mask = self.interp64.eval_s_ff1_i32_b64(dst_r=21, src_operand={"k": "sgpr", "r": 16, "n": 2}) - self.assertEqual(c_mask, 2) - self.assertEqual(ff1_mask, 5) - - # 2. Unmarked SGPR pair (scalar data) - self.interp64.cur_lane_masks.clear() - self.interp64.set_sgpr_u64(16, mask_val) - c_scalar = self.interp64.eval_s_bcnt1_i32_b64(dst_r=22, src_operand={"k": "sgpr", "r": 16, "n": 2}) - ff1_scalar = self.interp64.eval_s_ff1_i32_b64(dst_r=23, src_operand={"k": "sgpr", "r": 16, "n": 2}) - self.assertEqual(c_scalar, 2) - self.assertEqual(ff1_scalar, 5) - - def test_immediate_operand(self): - # Immediate constant is zero-extended in the high 32 bits - imm_op = {"k": "imm", "v": 0x80000001} - count = self.interp64.eval_s_bcnt1_i32_b64(dst_r=30, src_operand=imm_op) - first = self.interp64.eval_s_ff1_i32_b64(dst_r=31, src_operand=imm_op) - self.assertEqual(count, 2) - self.assertEqual(first, 0) - self.assertEqual(self.interp64.scc, 1) - - def test_wave32_lane_mask_reductions(self): - """In wave32 mode, masks only span 32 lanes (bits 32..63 are zero).""" - self.interp32.set_exec(MASK32) - count = self.interp32.eval_s_bcnt1_i32_b64(dst_r=0, src_operand="exec") - first = self.interp32.eval_s_ff1_i32_b64(dst_r=1, src_operand="exec") - self.assertEqual(count, 32) - self.assertEqual(first, 0) - - # Highest lane in wave32 - self.interp32.set_exec(1 << 31) - count_hi = self.interp32.eval_s_bcnt1_i32_b64(dst_r=0, src_operand="exec") - first_hi = self.interp32.eval_s_ff1_i32_b64(dst_r=1, src_operand="exec") - self.assertEqual(count_hi, 1) - self.assertEqual(first_hi, 31) - - def test_half_mask_operations(self): - """s_bcnt1_i32_b32 and s_ff1_i32_b32 targeting lo or hi halves.""" - self.interp64.set_exec(0x00000F0F000000F0) # lo has 4 bits (lanes 4..7), hi has 8 bits (lanes 32..35, 40..43) - - c_lo = self.interp64.eval_s_bcnt1_i32_b32(dst_r=0, src_operand="exec", half="lo") - c_hi = self.interp64.eval_s_bcnt1_i32_b32(dst_r=1, src_operand="exec", half="hi") - self.assertEqual(c_lo, 4) - self.assertEqual(c_hi, 8) - - ff1_lo = self.interp64.eval_s_ff1_i32_b32(dst_r=2, src_operand="exec", half="lo") - ff1_hi = self.interp64.eval_s_ff1_i32_b32(dst_r=3, src_operand="exec", half="hi") - self.assertEqual(ff1_lo, 4) - self.assertEqual(ff1_hi, 0) # lane 32 is bit 0 of the high half - - -class TestRdna2SpirvEmission(unittest.TestCase): - """Test SPIR-V translation emitted by rdna2spirv.Gen for lane mask reductions.""" - - def test_s_bcnt1_i32_b64_exec_emission(self): - g = rdna2spirv.Gen("ps") - g.wave64 = True - ins = { - "op": "s_bcnt1_i32_b64", - "args": [{"k": "sgpr", "r": 8}, {"k": "special", "t": "exec"}], - "mods": [], - } - g.insn(ins) - emitted = "\n".join(g.body) - - # Subgroup bitwise OR reduction over EXEC - self.assertIn("OpGroupNonUniformBitwiseOr %uint %c3 Reduce", emitted) - # Population count on both halves - self.assertIn("OpBitCount %uint", emitted) - self.assertIn("OpIAdd %uint", emitted) - # Result stored to destination SGPR s8 - self.assertIn("OpAccessChain %_ptr_Function_uint %sgpr %c8", emitted) - # Condition code SCC updated - self.assertIn("OpStore %scc", emitted) - self.assertTrue(g.uses_subgroup) - self.assertTrue(g.uses_wave_bits) - - def test_s_ff1_i32_b64_exec_emission(self): - g = rdna2spirv.Gen("ps") - g.wave64 = True - ins = { - "op": "s_ff1_i32_b64", - "args": [{"k": "sgpr", "r": 10}, {"k": "special", "t": "exec"}], - "mods": [], - } - g.insn(ins) - emitted = "\n".join(g.body) - - # GLSL.std.450 FindILsb for finding least significant set bit - self.assertIn("FindILsb", emitted) - # High-half +32 biasing (%c20 is 32) - self.assertIn("OpIAdd %uint", emitted) - self.assertIn("%c20", emitted) - # Fallback to -1 (%cffffffff) when both words are 0 - self.assertIn("%cffffffff", emitted) - # Store to destination SGPR s10 - self.assertIn("OpAccessChain %_ptr_Function_uint %sgpr %ca", emitted) - # s_ff1 does NOT store to SCC - self.assertNotIn("OpStore %scc", emitted) - - def test_s_bcnt1_i32_b64_scalar_sgpr_emission(self): - g = rdna2spirv.Gen("ps") - g.wave64 = True - ins = { - "op": "s_bcnt1_i32_b64", - "args": [{"k": "sgpr", "r": 4}, {"k": "sgpr", "r": 2, "n": 2}], - "mods": [], - } - # Not in lane_masks: treated as plain scalar SGPR pair - g.insn(ins) - emitted = "\n".join(g.body) - - # Must NOT emit subgroup reductions for plain scalar SGPR pair - self.assertNotIn("OpGroupNonUniformBitwiseOr", emitted) - # Loads s2 and s3 directly - self.assertIn("OpAccessChain %_ptr_Function_uint %sgpr %c2", emitted) - self.assertIn("OpAccessChain %_ptr_Function_uint %sgpr %c3", emitted) - # Counts bits and updates SCC - self.assertIn("OpBitCount %uint", emitted) - self.assertIn("OpIAdd %uint", emitted) - self.assertIn("OpStore %scc", emitted) - - def test_s_ff1_i32_b64_scalar_sgpr_emission(self): - g = rdna2spirv.Gen("ps") - g.wave64 = True - ins = { - "op": "s_ff1_i32_b64", - "args": [{"k": "sgpr", "r": 4}, {"k": "sgpr", "r": 2, "n": 2}], - "mods": [], - } - g.insn(ins) - emitted = "\n".join(g.body) - - self.assertNotIn("OpGroupNonUniformBitwiseOr", emitted) - self.assertIn("FindILsb", emitted) - self.assertNotIn("OpStore %scc", emitted) - - def test_s_bcnt1_i32_b64_immediate_emission(self): - g = rdna2spirv.Gen("ps") - ins = { - "op": "s_bcnt1_i32_b64", - "args": [{"k": "sgpr", "r": 0}, {"k": "imm", "v": 0x1234}], - "mods": [], - } - g.insn(ins) - emitted = "\n".join(g.body) - - self.assertIn("OpBitCount %uint", emitted) - self.assertIn("OpStore %scc", emitted) - - def test_s_ff1_i32_b64_immediate_emission(self): - g = rdna2spirv.Gen("ps") - ins = { - "op": "s_ff1_i32_b64", - "args": [{"k": "sgpr", "r": 0}, {"k": "imm", "v": 0x80}], - "mods": [], - } - g.insn(ins) - emitted = "\n".join(g.body) - - self.assertIn("FindILsb", emitted) - self.assertNotIn("OpStore %scc", emitted) - - -class TestTranslatorShaderIntegration(unittest.TestCase): - """Verify full end-to-end translation of disassembly listings with lane mask reductions.""" - - def test_translate_lines_exec_bcnt1_and_ff1(self): - lines = [ - "s_bcnt1_i32_b64 s4, exec", - "s_ff1_i32_b64 s6, exec", - "s_endpgm", - ] - spv = support.translate_lines("ps_test_exec_reductions", lines) - self.assertIn("OpGroupNonUniformBitwiseOr %uint %c3 Reduce", spv) - self.assertIn("OpBitCount %uint", spv) - self.assertIn("FindILsb", spv) - self.assertIn("OpStore %scc", spv) - - def test_translate_lines_vcc_lane_mask(self): - lines = [ - "v_cmp_gt_u32_e32 vcc, 10, v0", - "s_bcnt1_i32_b64 s4, vcc", - "s_ff1_i32_b64 s6, vcc", - "s_endpgm", - ] - spv = support.translate_lines("ps_test_vcc_reductions", lines) - self.assertIn("OpGroupNonUniformBitwiseOr %uint %c3 Reduce", spv) - self.assertIn("OpBitCount %uint", spv) - self.assertIn("FindILsb", spv) - - def test_translate_lines_sgpr_comparison_lane_mask(self): - lines = [ - "v_cmp_eq_u32_e64 s[4:5], v0, 5", - "s_bcnt1_i32_b64 s6, s[4:5]", - "s_ff1_i32_b64 s7, s[4:5]", - "s_endpgm", - ] - spv = support.translate_lines("ps_test_sgpr_cmp_mask", lines) - self.assertIn("OpGroupNonUniformBitwiseOr %uint %c3 Reduce", spv) - self.assertIn("OpBitCount %uint", spv) - self.assertIn("FindILsb", spv) - - def test_translate_lines_sgpr_scalar_data_no_reduction(self): - lines = [ - "s_bcnt1_i32_b64 s6, s[2:3]", - "s_ff1_i32_b64 s7, s[2:3]", - "s_endpgm", - ] - spv = support.translate_lines("ps_test_sgpr_data_scalar", lines) - self.assertNotIn("OpGroupNonUniformBitwiseOr", spv) - self.assertIn("OpBitCount %uint", spv) - self.assertIn("FindILsb", spv) - - -class TestNegativeControlsAndMutations(unittest.TestCase): - """Ensure tests are strictly sensitive to subtle mathematical and translator errors.""" - - def test_bcnt1_detects_omitted_high_word_addition(self): - """Saboteur: only counting low half bits (c1 without c2).""" - def sabotaged_bcnt1(lo: int, hi: int) -> int: - return ref_popcount_u32(lo) - - mask_high_only = (0, 0x00000001) - expected = 1 - sabotaged = sabotaged_bcnt1(*mask_high_only) - self.assertNotEqual(sabotaged, expected, "Omitted high word in bcnt1 must be detected") - - def test_ff1_detects_missing_high_word_offset(self): - """Saboteur: finding first bit in high half without adding +32.""" - def sabotaged_ff1(lo: int, hi: int) -> int: - l = ref_find_first_one_u32(lo) - h = ref_find_first_one_u32(hi) - if lo != 0: - return l - if hi != 0: - return h # BUG: omitted + 32! - return MASK32 - - # Bit 36 set (lane 36 -> high word bit 4) - lo, hi = 0, 1 << 4 - expected = 36 - sabotaged = sabotaged_ff1(lo, hi) - self.assertEqual(sabotaged, 4) - self.assertNotEqual(sabotaged, expected, "Missing +32 offset in high half must be detected") - - def test_ff1_detects_zero_instead_of_negative_one_on_empty(self): - """Saboteur: returning 0 instead of -1 (0xFFFFFFFF) when no bits are set.""" - def sabotaged_ff1_empty(lo: int, hi: int) -> int: - if lo == 0 and hi == 0: - return 0 # BUG: should be 0xFFFFFFFF - return 0 - - self.assertNotEqual(sabotaged_ff1_empty(0, 0), MASK32) - - def test_bcnt1_detects_inverted_scc(self): - """Saboteur: setting SCC = (total == 0) instead of (total != 0).""" - def sabotaged_scc(total: int) -> int: - return 1 if total == 0 else 0 - - self.assertNotEqual(sabotaged_scc(0), 0) - self.assertNotEqual(sabotaged_scc(1), 1) - - def test_detects_ff1_clobbering_scc(self): - """Ensure tests catch any implementation of s_ff1 that writes to SCC.""" - interp = LaneMaskReductionInterpreter(wave_size=64) - interp.scc = 0 - interp.set_exec(MASK64) - interp.eval_s_ff1_i32_b64(dst_r=0, src_operand="exec") - - # SCC must remain 0 - self.assertEqual(interp.scc, 0) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_lane_masks_edge_cases.py b/tests/semantic/test_lane_masks_edge_cases.py deleted file mode 100644 index defba4154..000000000 --- a/tests/semantic/test_lane_masks_edge_cases.py +++ /dev/null @@ -1,176 +0,0 @@ -"""End-to-end translator tests for lane_masks operand invalidation and SDWA/DPP guards. - -Each test translates a synthetic RDNA2 compute shader through tools/rdna2spirv.py and executes all -4 lanes via spirv_mini_interp.run_workgroup to confirm that lane_masks.py neither leaves stale -VGPR/parked-mask state nor forces write_all_lanes on SDWA/DPP ops nor wipes masks on stores. -""" -import struct -import unittest - -import spirv_mini_interp as si -import support - -FSSM = bytearray(0x148) -struct.pack_into("<4I", FSSM, 0x138, 0x88, 4, 1, 1) # 4 user SGPRs, workgroup id in s4, 4x1x1 -FSSM = bytes(FSSM) - -OUT_BASE = 0x1000 -SCRATCH_BASE = 0x2000 - - -def run_cs(name, asm, nlanes=4): - spv = support.translate_lines(name, asm, fssm=FSSM) - mem = {} - si.run_workgroup( - spv, - nlanes, - 32, - inputs_for=lambda i: {"%wg_id": (0, 0, 0), "%local_id": (i, 0, 0), "%sg_lane": i}, - push_constants=[OUT_BASE, 0, SCRATCH_BASE, 0] + [0] * 32, - memory=mem, - ) - return spv, [mem.get(OUT_BASE + 4 * i, 0) for i in range(nlanes)] - - -class LaneMasksEndToEndTests(unittest.TestCase): - def test_v_mov_of_a_mask_keeps_inactive_lanes(self): - """A plain v_mov_b32 of a mask SGPR is an ordinary VALU write: the lane that is off in EXEC keeps its VGPR.""" - _, got = run_cs("cs_vmov_mask_inactive", [ - "v_cmp_lt_u32_e64 s6, v0, 2", - "v_mov_b32_e32 v2, 0xdeadbeef", - "s_mov_b32 exec_lo, 7", - "v_mov_b32_e32 v2, s6", - "s_mov_b32 exec_lo, 0xf", - "v_lshlrev_b32_e32 v3, 2, v0", - "global_store_dword v3, v2, s[0:1]", - "s_endpgm", - ]) - # Lane 3 was off while v2 was written. The active lanes read s6 as data, which needs #293's mask - # materialization, so only the inactive lane is asserted. - self.assertEqual(got[3], 0xdeadbeef) - - def test_dpp_bitwise_respects_row_mask_on_mask_operands(self): - """v_or_b32_dpp must not enter mask_writes and bypass dpp_guard (row_mask:0x0 keeps old v2).""" - _, got = run_cs("cs_dpp_mask", [ - "s_mov_b32 s6, exec_lo", - "v_mov_b32_e32 v1, s6", - "v_mov_b32_e32 v2, 0x1234", - "v_or_b32_dpp v2, v1, v1 row_shr:1 row_mask:0x0 bank_mask:0xf", - "v_lshlrev_b32_e32 v3, 2, v0", - "global_store_dword v3, v2, s[0:1]", - "s_endpgm", - ]) - self.assertEqual(got, [0x1234] * 4) - - def test_sdwa_bitwise_respects_exec_on_mask_operands(self): - """v_or_b32_sdwa must not enter mask_writes and bypass EXEC on inactive lanes.""" - _, got = run_cs("cs_sdwa_mask", [ - "v_cmp_lt_u32_e64 s6, v0, 3", - "v_mov_b32_e32 v2, 0xdeadbeef", - "s_mov_b32 exec_lo, s6", - "v_or_b32_sdwa v2, s6, s6 dst_sel:BYTE_0 dst_unused:UNUSED_PRESERVE src0_sel:BYTE_0 src1_sel:BYTE_0", - "s_mov_b32 exec_lo, 0xf", - "v_lshlrev_b32_e32 v3, 2, v0", - "global_store_dword v3, v2, s[0:1]", - "s_endpgm", - ]) - # Only the inactive lane tests this EXEC regression. Active lanes read s6 as - # ordinary data, which needs mask materialization (#293); do not enshrine - # the translator's per-lane 0xff representation instead of hardware's 0x07. - self.assertEqual(got[3], 0xdeadbeef) - - def test_writelane_invalidates_vgpr_mask_before_readfirstlane(self): - """Overwriting lane 0 of a mask-holding VGPR via v_writelane_b32 must end ("v", r) tracking.""" - _, got = run_cs("cs_wl_after_or", [ - "v_cmp_eq_u32_e64 s6, v0, 2", - "v_or_b32_e32 v5, s6, s6", - "s_mov_b32 s7, 0x55aa", - "v_writelane_b32 v5, s7, 0", - "v_readfirstlane_b32 s8, v5", - "v_mov_b32_e32 v2, s8", - "v_lshlrev_b32_e32 v3, 2, v0", - "global_store_dword v3, v2, s[0:1]", - "s_endpgm", - ]) - self.assertEqual(got, [0x55aa] * 4) - - def test_v_swap_b32_invalidates_second_operand_parked_mask(self): - """v_swap_b32 writes a[1] as well as a[0]; reading back a[1] must not fetch a stale parked mask.""" - _, got = run_cs("cs_swap_parked", [ - "v_cmp_lt_u32_e64 s6, v0, 2", - "v_writelane_b32 v5, s6, 0", - "v_mov_b32_e32 v4, 0x7777", - "v_swap_b32_e32 v4, v5", - "v_readlane_b32 s7, v5, 0", - "v_mov_b32_e32 v2, s7", - "v_lshlrev_b32_e32 v3, 2, v0", - "global_store_dword v3, v2, s[0:1]", - "s_endpgm", - ]) - self.assertEqual(got, [0x7777] * 4) - - def test_v_movreld_and_v_swaprel_invalidate_parked_masks_above_base(self): - """Relative VGPR writes can overwrite any VGPR >= base and must invalidate parked masks there.""" - _, got_movrel = run_cs("cs_movreld_parked", [ - "v_cmp_lt_u32_e64 s6, v0, 2", - "v_writelane_b32 v6, s6, 0", - "v_mov_b32_e32 v7, 0x8888", - "s_mov_b32 m0, 2", - "v_movreld_b32_e32 v4, v7", - "v_readlane_b32 s7, v6, 0", - "v_mov_b32_e32 v2, s7", - "v_lshlrev_b32_e32 v3, 2, v0", - "global_store_dword v3, v2, s[0:1]", - "s_endpgm", - ]) - self.assertEqual(got_movrel, [0x8888] * 4) - - _, got_swaprel = run_cs("cs_swaprel_parked", [ - "v_cmp_lt_u32_e64 s6, v0, 2", - "v_writelane_b32 v6, s6, 0", - "v_mov_b32_e32 v4, 0x4444", - "s_mov_b32 m0, 0x00000002", # dst offset 0 (v4), src offset 2 (v4+2 = v6) - "v_swaprel_b32_e32 v4, v4", - "v_readlane_b32 s7, v6, 0", - "v_mov_b32_e32 v2, s7", - "v_lshlrev_b32_e32 v3, 2, v0", - "global_store_dword v3, v2, s[0:1]", - "s_endpgm", - ]) - self.assertEqual(got_swaprel, [0x4444] * 4) - - def test_store_and_non_returning_atomic_preserve_parked_mask_in_a0(self): - """Using a VGPR as a[0] of global_store_dword or non-returning ds_add_u32 must keep its parked mask.""" - _, got_gstore = run_cs("cs_store_parked", [ - "v_cmp_lt_u32_e64 s6, v0, 3", - "v_lshlrev_b32_e32 v5, 2, v0", - "v_writelane_b32 v5, s6, 3", - "v_mov_b32_e32 v6, 0x9999", - "global_store_dword v5, v6, s[2:3]", - "v_readlane_b32 s7, v5, 3", - "s_bcnt1_i32_b32 s8, s7", - "v_mov_b32_e32 v2, s8", - "v_lshlrev_b32_e32 v3, 2, v0", - "global_store_dword v3, v2, s[0:1]", - "s_endpgm", - ]) - self.assertEqual(got_gstore, [3, 3, 3, 3]) - - _, got_ds = run_cs("cs_ds_add_parked", [ - "v_cmp_lt_u32_e64 s6, v0, 3", - "v_lshlrev_b32_e32 v5, 2, v0", - "v_writelane_b32 v5, s6, 3", - "v_mov_b32_e32 v6, 1", - "ds_add_u32 v5, v6", - "v_readlane_b32 s7, v5, 3", - "s_bcnt1_i32_b32 s8, s7", - "v_mov_b32_e32 v2, s8", - "v_lshlrev_b32_e32 v3, 2, v0", - "global_store_dword v3, v2, s[0:1]", - "s_endpgm", - ]) - self.assertEqual(got_ds, [3, 3, 3, 3]) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_lane_masks_vector_bitwise.py b/tests/semantic/test_lane_masks_vector_bitwise.py deleted file mode 100644 index d4adde9a5..000000000 --- a/tests/semantic/test_lane_masks_vector_bitwise.py +++ /dev/null @@ -1,273 +0,0 @@ -"""Semantic interpreter tests for vector bitwise lane-mask tracking (`v_and_or_b32`, `v_xnor_b32`, `v_bfi_b32`).""" -import gc -import os -import struct -import sys -import tempfile -import unittest -import warnings - -HERE = os.path.dirname(os.path.abspath(__file__)) -ROOT = os.path.dirname(os.path.dirname(HERE)) -TOOLS_DIR = os.environ.get("LEONIDA_TOOLS_DIR") or os.path.join(ROOT, "tools") - -sys.dont_write_bytecode = True -if HERE not in sys.path: - sys.path.insert(0, HERE) -if TOOLS_DIR not in sys.path: - sys.path.insert(0, TOOLS_DIR) - -import rdna2spirv # noqa: E402 -import spirv_mini_interp as si # noqa: E402 - -STUB_DXBC = b"DXBC" + bytes(24) + struct.pack(" 4 user SGPRs (s[0:3] = output V#), TGID_X. - with open(os.path.join(tmp, "fssm", name + ".fssm"), "wb") as f: - f.write(bytes(0x138) + struct.pack("<4I", 0x8088, wave_size, 1, 1)) - with warnings.catch_warnings(): - warnings.simplefilter("ignore", ResourceWarning) - spv = rdna2spirv.translate(s_path) - gc.collect() - gen = rdna2spirv.translate.last_gen - assert gen.wave64 == (wave_size == 64), f"{name}: expected wave64={wave_size == 64}, got {gen.wave64}" - return spv, gen - finally: - rdna2spirv.WAVE64_EMULATE = prev_emu - - -def _run_cs(name, body_lines, wave_size=32, emulate=False): - """Translate a synthetic compute shader and execute every lane in spirv_mini_interp.""" - spv, _ = _translate_cs(name, body_lines, wave_size=wave_size, emulate=emulate) - sg_size = 32 if emulate else wave_size - pc = VSHARP + [0] * 28 - return si.run_workgroup( - spv, wave_size, sg_size, - inputs_for=lambda i: {"%wg_id": (0, 0, 0), "%local_id": (i, 0, 0), "%sg_lane": i % sg_size}, - push_constants=pc, memory={}, - ) - - -def _bitwise_mask_lines(wave_size): - """Build shader computing masks via v_and_or_b32, v_xnor_b32, and v_bfi_b32 under partial EXEC.""" - is64 = wave_size == 64 - r = { - "exec": "exec" if is64 else "exec_lo", - "mov": "s_mov_b64" if is64 else "s_mov_b32", - "saveexec": "s_and_saveexec_b64" if is64 else "s_and_saveexec_b32", - "bcnt": "s_bcnt1_i32_b64" if is64 else "s_bcnt1_i32_b32", - "s4": "s[4:5]" if is64 else "s4", - "s6": "s[6:7]" if is64 else "s6", - "s8": "s[8:9]" if is64 else "s8", - "s10": "s[10:11]" if is64 else "s10", - "s12": "s[12:13]" if is64 else "s12", - "s14": "s[14:15]" if is64 else "s14", - "s16": "s[16:17]" if is64 else "s16", - "s18": "s[18:19]" if is64 else "s18", - } - lines = [ - f"{r['mov']} {r['exec']}, -1", - "v_and_b32 v1, 1, v0", - f"v_cmp_eq_u32_e64 {r['s6']}, v1, 0", # even lanes - f"v_cmp_lt_u32_e64 {r['s8']}, v0, 10", # lanes < 10 - "v_and_b32 v1, 2, v0", - f"v_cmp_eq_u32_e64 {r['s10']}, v1, 0", # (lane & 2) == 0 - f"v_cmp_lt_u32_e64 {r['s12']}, v0, 8", # partial EXEC: lanes 0..7 active - "v_mov_b32 v2, 0", - "v_mov_b32 v3, 0", - "v_mov_b32 v4, 0", - ] - if is64: - lines += ["v_mov_b32 v5, 0", "v_mov_b32 v6, 0", "v_mov_b32 v7, 0"] - lines += [ - f"{r['saveexec']} {r['s4']}, {r['s12']}", - # Mask ops under partial EXEC must update inactive lanes too. - "v_and_or_b32 v2, s6, s8, s10", - "v_xnor_b32 v3, s6, s8", - "v_bfi_b32 v4, s6, s8, s10", - ] - if is64: - lines += [ - "v_and_or_b32 v5, s7, s9, s11", - "v_xnor_b32 v6, s7, s9", - "v_bfi_b32 v7, s7, s9, s11", - ] - lines += [ - f"{r['mov']} {r['exec']}, -1", - "v_readfirstlane_b32 s14, v2", - "v_readfirstlane_b32 s16, v3", - "v_readfirstlane_b32 s18, v4", - ] - if is64: - lines += [ - "v_readfirstlane_b32 s15, v5", - "v_readfirstlane_b32 s17, v6", - "v_readfirstlane_b32 s19, v7", - ] - lines += [ - f"{r['bcnt']} s20, {r['s14']}", - f"{r['bcnt']} s21, {r['s16']}", - f"{r['bcnt']} s22, {r['s18']}", - f"v_cndmask_b32_e64 v8, 10, 20, {r['s14']}", - f"v_cndmask_b32_e64 v9, 30, 40, {r['s16']}", - f"v_cndmask_b32_e64 v10, 50, 60, {r['s18']}", - "v_mov_b32 v11, s20", - "v_mov_b32 v12, s21", - "v_mov_b32 v13, s22", - "v_mul_lo_u32 v14, v0, 36", - ] - for off, vreg in enumerate((2, 3, 4, 8, 9, 10, 11, 12, 13)): - if off == 0: - lines.append(f"buffer_store_dword v{vreg}, v14, s[0:3], 0 offen") - else: - lines.append(f"v_add_nc_u32 v15, {off * 4}, v14") - lines.append(f"buffer_store_dword v{vreg}, v15, s[0:3], 0 offen") - return lines - - -def _vgpr_stores(spv): - """Return mapping `vgpr_idx -> [rhs_expression, ...]` for constant-index `%vgpr` OpStores.""" - const_uint = {} - ptr_vgpr = {} - defs = {} - stores = {} - for ln in spv.splitlines(): - s = ln.strip() - if " = " in s: - lhs, rhs = s.split(" = ", 1) - defs[lhs] = rhs - parts = rhs.split() - if parts[:2] == ["OpConstant", "%uint"] and len(parts) == 3: - const_uint[lhs] = int(parts[2]) - elif ( - len(parts) == 4 - and parts[0] == "OpAccessChain" - and parts[1] == "%_ptr_Function_uint" - and parts[2] == "%vgpr" - and parts[3] in const_uint - ): - ptr_vgpr[lhs] = const_uint[parts[3]] - elif s.startswith("OpStore "): - parts = s.split() - if len(parts) >= 3 and parts[1] in ptr_vgpr: - idx = ptr_vgpr[parts[1]] - stores.setdefault(idx, []).append(defs.get(parts[2], parts[2])) - return stores - - -class _VectorBitwiseMixin: - wave_size = 32 - - def test_vector_bitwise_masks_under_partial_exec(self): - mem = _run_cs( - f"cs_vec_bitwise_w{self.wave_size}", - _bitwise_mask_lines(self.wave_size), - wave_size=self.wave_size, - emulate=False, - ) - want_andor = [((i & 1 == 0) and i < 10) or (i & 2 == 0) for i in range(self.wave_size)] - want_xnor = [(i & 1 == 0) == (i < 10) for i in range(self.wave_size)] - want_bfi = [(i < 10) if (i & 1 == 0) else (i & 2 == 0) for i in range(self.wave_size)] - cnt_andor = sum(want_andor) - cnt_xnor = sum(want_xnor) - cnt_bfi = sum(want_bfi) - for lane in range(self.wave_size): - base = lane * 36 - self.assertEqual(mem[base], 0xFFFFFFFF if want_andor[lane] else 0, f"lane {lane} raw and_or") - self.assertEqual(mem[base + 4], 0xFFFFFFFF if want_xnor[lane] else 0, f"lane {lane} raw xnor") - self.assertEqual(mem[base + 8], 0xFFFFFFFF if want_bfi[lane] else 0, f"lane {lane} raw bfi") - self.assertEqual(mem[base + 12], 20 if want_andor[lane] else 10, f"lane {lane} cndmask and_or") - self.assertEqual(mem[base + 16], 40 if want_xnor[lane] else 30, f"lane {lane} cndmask xnor") - self.assertEqual(mem[base + 20], 60 if want_bfi[lane] else 50, f"lane {lane} cndmask bfi") - self.assertEqual(mem[base + 24], cnt_andor, f"lane {lane} bcnt and_or") - self.assertEqual(mem[base + 28], cnt_xnor, f"lane {lane} bcnt xnor") - self.assertEqual(mem[base + 32], cnt_bfi, f"lane {lane} bcnt bfi") - - -class TestVectorBitwiseMasksWave32(_VectorBitwiseMixin, unittest.TestCase): - wave_size = 32 - - -class TestVectorBitwiseMasksWave64Native(_VectorBitwiseMixin, unittest.TestCase): - wave_size = 64 - - -class TestVectorBitwiseMasksWave64Emulated(unittest.TestCase): - """Structural SPIR-V checks for `--wave64-emulate` (spirv_mini_interp rejects OpControlBarrier).""" - - def test_vector_bitwise_masks_emulate_spirv_structure(self): - spv, gen = _translate_cs( - "cs_vec_bitwise_w64_emu", - _bitwise_mask_lines(64), - wave_size=64, - emulate=True, - ) - self.assertTrue(gen.wave64 and gen.emulate) - self.assertEqual(len(gen.mask_writes), 6) - self.assertNotIn("FindILsb", spv) - self.assertIn("OpControlBarrier", spv) - self.assertIn("OpStore %x_it", spv) - stores = _vgpr_stores(spv) - for vreg in (2, 5): # v_and_or_b32 -> final OpBitwiseOr - self.assertTrue(stores[vreg][-1].startswith("OpBitwiseOr %uint "), stores[vreg][-1]) - for vreg in (3, 6): # v_xnor_b32 -> final OpNot - self.assertTrue(stores[vreg][-1].startswith("OpNot %uint "), stores[vreg][-1]) - for vreg in (4, 7): # v_bfi_b32 -> final OpBitwiseOr - self.assertTrue(stores[vreg][-1].startswith("OpBitwiseOr %uint "), stores[vreg][-1]) - - -class TestVectorBitwiseDataControl(unittest.TestCase): - def test_non_mask_data_stays_exec_gated_wave32(self): - lines = [ - "s_mov_b32 exec_lo, -1", - "v_cmp_lt_u32_e64 s8, v0, 16", - f"v_mov_b32 v2, {SENTINEL:#x}", - f"v_mov_b32 v3, {SENTINEL:#x}", - f"v_mov_b32 v4, {SENTINEL:#x}", - "s_and_saveexec_b32 s6, s8", - "v_and_or_b32 v2, v0, 1, 2", - "v_xnor_b32 v3, v0, 3", - "v_bfi_b32 v4, v0, 0x0f0f0f0f, 0x10101010", - "s_mov_b32 exec_lo, s6", - "v_mul_lo_u32 v10, v0, 12", - "buffer_store_dword v2, v10, s[0:3], 0 offen", - "v_add_nc_u32 v11, 4, v10", - "buffer_store_dword v3, v11, s[0:3], 0 offen", - "v_add_nc_u32 v11, 8, v10", - "buffer_store_dword v4, v11, s[0:3], 0 offen", - ] - mem = _run_cs("cs_vec_bitwise_data_w32", lines, wave_size=32, emulate=False) - for lane in range(32): - base = lane * 12 - if lane < 16: - self.assertEqual(mem[base], (lane & 1) | 2, f"lane {lane} data and_or") - self.assertEqual(mem[base + 4], (~(lane ^ 3)) & 0xFFFFFFFF, f"lane {lane} data xnor") - want_bfi = ((lane & 0x0F0F0F0F) | ((~lane) & 0x10101010)) & 0xFFFFFFFF - self.assertEqual(mem[base + 8], want_bfi, f"lane {lane} data bfi") - else: - self.assertEqual(mem[base], SENTINEL, f"inactive lane {lane} and_or") - self.assertEqual(mem[base + 4], SENTINEL, f"inactive lane {lane} xnor") - self.assertEqual(mem[base + 8], SENTINEL, f"inactive lane {lane} bfi") - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_ldexp_f16_mode_round.py b/tests/semantic/test_ldexp_f16_mode_round.py deleted file mode 100644 index f13fe1084..000000000 --- a/tests/semantic/test_ldexp_f16_mode_round.py +++ /dev/null @@ -1,153 +0,0 @@ -"""v_ldexp_f16 after a MODE.FP_ROUND[3:2] write (f16/f64 rounding), run in tests/semantic/spirv_mini_interp.py. - -`docs/design.md` (Known approximations, MODE) has every VALU f16 result except the transcendentals round toward zero -after `s_setreg_imm32_b32 hwreg(HW_REG_MODE, 2, 2), 3`. v_ldexp_f16 only rounds when the result leaves the normal -range: an overflow gives +-65504 instead of +-inf, and a result below the smallest normal is a denormal truncated -instead of rounded to nearest even. Exact results, zeros, infinities and NaNs are the same in both modes. The -toward-zero words are not measured on hardware for this op; tools/mode_round_probe.py has the cases to check them. - -The reference is exact rational arithmetic (fractions.Fraction) and shares no code with the translator. -""" -import os -import random -import sys -import unittest -from fractions import Fraction as Q - -HERE = os.path.dirname(os.path.abspath(__file__)) -ROOT = os.path.dirname(os.path.dirname(HERE)) -TOOLS_DIR = os.environ.get("LEONIDA_TOOLS_DIR") or os.path.join(ROOT, "tools") - -sys.dont_write_bytecode = True -if HERE not in sys.path: - sys.path.insert(0, HERE) -if TOOLS_DIR not in sys.path: - sys.path.insert(0, TOOLS_DIR) - -from support import translate_lines, mrt0_words # noqa: E402 - -RNE = "s_setreg_imm32_b32 hwreg(HW_REG_MODE, 2, 2), 0" -RTZ = "s_setreg_imm32_b32 hwreg(HW_REG_MODE, 2, 2), 3" - - -def run(mode_line, ops): - """ops: up to four (x, n) pairs; returns the low 16 bits of v_ldexp_f16_e32 for each, in that MODE.""" - lines = [mode_line] if mode_line else [] - for i, (x, n) in enumerate(ops): - lines += [f"v_mov_b32 v{2 * i}, 0x{x:04x}", f"v_mov_b32 v{2 * i + 1}, {n}", - f"v_ldexp_f16_e32 v{8 + i}, v{2 * i}, v{2 * i + 1}"] - lines += ["exp mrt0 v8, v9, v10, v11 done vm", "s_endpgm"] - return [w & 0xFFFF for w in mrt0_words(translate_lines("ps_ldexp_mode", lines))[:len(ops)]] - - -def half_value(h): - e, f = h >> 10 & 0x1F, h & 0x3FF - q = Q(f, 1 << 24) if e == 0 else Q(0x400 | f, 1 << 10) * Q(2) ** (e - 15) - return -q if h & 0x8000 else q - - -def exponent(a): - """The integer E with 2^E <= a < 2^(E+1), for a > 0.""" - e = 0 - while a >= Q(2) ** (e + 1): - e += 1 - while a < Q(2) ** e: - e -= 1 - return e - - -def ref_ldexp(x, n, rtz): - """x a finite non-zero half, n an integer; x * 2^n rounded to binary16 by the mode (nearest even or toward zero).""" - q = half_value(x) * Q(2) ** n - sign, a = (0x8000 if q < 0 else 0), abs(q) - ulp = Q(2) ** (max(exponent(a), -14) - 10) - k, r = divmod(a, ulp) - if not rtz and (r > ulp / 2 or (r == ulp / 2 and k % 2)): - k += 1 - v = k * ulp - if v >= 65536: - return sign | (0x7BFF if rtz else 0x7C00) - if v < Q(1, 1 << 14): - return sign | int(v * (1 << 24)) - e = exponent(v) - return sign | (e + 15) << 10 | int(v / Q(2) ** (e - 10)) - 0x400 - - -class LdexpF16ModeRound(unittest.TestCase): - # (mode line, x, n, want) - CASES = ( - (None, 0x7BFF, 1, 0x7C00), # 65504 * 2 overflows to inf under nearest even (no MODE write) - (RTZ, 0x7BFF, 1, 0x7BFF), # and saturates to 65504 toward zero - (RTZ, 0xFBFF, 1, 0xFBFF), - (RTZ, 0x3C00, 100, 0x7BFF), # n clamped to 64: still a finite overflow - (RTZ, 0x7C00, 1, 0x7C00), # inf stays inf - (RTZ, 0x8000, 5, 0x8000), # a signed zero stays one - (None, 0x3C03, -15, 0x0202), # (1 + 3 * 2^-10) * 2^-15 = 513.5 * 2^-24: nearest even rounds up - (RTZ, 0x3C03, -15, 0x0201), # toward zero truncates - (RTZ, 0xBC03, -15, 0x8201), - (RTZ, 0x3C01, -15, 0x0200), # 512.5 * 2^-24: a tie that both modes take to 0x0200 - (None, 0x3BFF, -14, 0x0400), # 1023.5 * 2^-24: nearest even carries into the smallest normal - (RTZ, 0x3BFF, -14, 0x03FF), # toward zero stays a denormal - (None, 0x3E00, -25, 0x0001), # 0.75 * 2^-24 - (RTZ, 0x3E00, -25, 0x0000), - (RTZ, 0x0003, 3, 0x0018), # exact: a denormal operand, a denormal result - (RTZ, 0x5BFF, 2, 0x63FF), # exact: a normal result - (RNE, 0x7BFF, 1, 0x7C00), # back to nearest even - ) - - def test_cases(self): - for mode, x, n, want in self.CASES: - with self.subTest(mode=mode, x=hex(x), n=n): - self.assertEqual(run(mode, [(x, n)])[0], want) - - def test_reference_agrees_with_the_cases(self): - for mode, x, n, want in self.CASES: - if x & 0x7C00 == 0x7C00 or not x & 0x7FFF: - continue - with self.subTest(mode=mode, x=hex(x), n=n): - self.assertEqual(ref_ldexp(x, max(-64, min(64, n)), mode == RTZ), want) - - def test_mode_switches_back_and_vop3(self): - lines = ["v_mov_b32 v1, 0x7bff", "v_mov_b32 v2, 1", RTZ, "v_ldexp_f16 v8, -v1, v2", RNE, - "v_ldexp_f16 v9, -v1, v2", "exp mrt0 v8, v9, v9, v9 done vm", "s_endpgm"] - w = mrt0_words(translate_lines("ps_ldexp_switch", lines)) - self.assertEqual((w[0] & 0xFFFF, w[1] & 0xFFFF), (0xFBFF, 0xFC00)) - - def test_seeded_sweep_against_exact_reference(self): - rng = random.Random(1369) - for mode in (RNE, RTZ): - for _ in range(10): - ops = [] - for _ in range(4): - k = rng.random() - if k < 0.3: # near the overflow edge - x, n = rng.getrandbits(1) << 15 | rng.randint(26, 30) << 10 | rng.getrandbits(10), \ - rng.randint(0, 4) - elif k < 0.8: # into the denormal range - x, n = rng.getrandbits(1) << 15 | rng.randint(1, 30) << 10 | rng.getrandbits(10), \ - rng.randint(-30, -1) - else: - x, n = rng.getrandbits(1) << 15 | rng.randint(1, 0x3FF), rng.randint(-4, 30) - ops.append((x, n)) - got = run(mode, ops) - for (x, n), g in zip(ops, got): - with self.subTest(mode=mode, x=hex(x), n=n): - self.assertEqual(g, ref_ldexp(x, n, mode == RTZ)) - - - def test_probe_cases_match_the_translator(self): - """tools/mode_round_probe.py's f16 words in both modes are the translator's, so a GPU run of the probe checks - the translation (the f64 cases are covered by tests/test_mode_round.py).""" - import mode_round_probe as probe - for name, setup, op, is_64, want_rne, want_rtz in probe.CASES: - if is_64: - continue - mask = 0xFFFFFFFF if want_rne > 0xFFFF else 0xFFFF - for mode, want in ((RNE, want_rne), (RTZ, want_rtz)): - with self.subTest(case=name, mode=mode): - lines = list(setup) + [mode, op, "exp mrt0 v3, v3, v3, v3 done vm", "s_endpgm"] - self.assertEqual(mrt0_words(translate_lines("ps_mode_probe", lines))[0] & mask, want) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_lds_add_f32.py b/tests/semantic/test_lds_add_f32.py deleted file mode 100644 index 383270247..000000000 --- a/tests/semantic/test_lds_add_f32.py +++ /dev/null @@ -1,98 +0,0 @@ -"""ds_add_f32 / ds_add_rtn_f32, run through spirv_mini_interp on the CPU. - -RDNA2 ISA, "Data Share Instructions": M = M + DATA as binary32 (round to nearest even); the _rtn_ form returns the old -M. The translator emits an OpAtomicCompareExchange loop with an OpFAdd. Each case runs one invocation: it seeds an LDS -dword, runs the op, reads the dword back and stores (vdst, M) as integer words, so no float round trip touches them. -The reference adds in double precision (exact for two binary32 values) and rounds once to binary32. Denormal and NaN -behaviour of the LDS adder is not measured and not tested here. Standard library only; no GPU, no game files. -""" -import os -import random -import struct -import sys -import unittest - -HERE = os.path.dirname(os.path.abspath(__file__)) -sys.dont_write_bytecode = True -sys.path.insert(0, HERE) - -from test_lds_atomics_values import run_atomic # noqa: E402 (also puts tools/ on sys.path) - - -def f32(b): - return struct.unpack(" 0 else 0xFF800000 - - -VALUES = [bits(v) for v in (0.0, -0.0, 1.0, -1.0, 0.5, 1.5, 3.0, 1e10, -1e10, 1e-10, 65504.0, 16777216.0, - 0.1, -2.75)] + [0x3F800001, 0x4B7FFFFF] - - -class LdsAddF32(unittest.TestCase): - def test_reference(self): - self.assertEqual(add_ref(bits(1.0), bits(2.0)), bits(3.0)) - self.assertEqual(add_ref(bits(16777216.0), bits(1.0)), bits(16777216.0)) # tie to even - self.assertEqual(add_ref(bits(-0.0), bits(-0.0)), bits(-0.0)) - self.assertEqual(add_ref(bits(3e38), bits(3e38)), 0x7F800000) - - def test_returning_form(self): - for m in VALUES: - for d in VALUES[::3]: - with self.subTest(m=hex(m), d=hex(d)): - self.assertEqual(run_atomic("ds_add_rtn_f32 v5, v1, v3", m, data=(d,)), (m, add_ref(m, d))) - - def test_non_returning_form_and_offset(self): - self.assertEqual(run_atomic("ds_add_f32 v1, v3", bits(1.25), data=(bits(2.5),)), (0xDEAD, bits(3.75))) - self.assertEqual(run_atomic("ds_add_rtn_f32 v5, v1, v3", bits(4.0), addr=0x20, offset=0x24, - data=(bits(-1.0),)), (bits(4.0), bits(3.0))) - - def test_rounding_and_signed_zero(self): - cases = ((16777216.0, 1.0), (16777218.0, 1.0), (1.0, 2.0 ** -24), (1.0, 3 * 2.0 ** -25), (-0.0, 0.0), - (3e38, 3e38), (-3e38, -3e38)) # ties to even, -0 + +0 = +0, overflow to +-inf - for m, d in cases: - with self.subTest(m=m, d=d): - self.assertEqual(run_atomic("ds_add_rtn_f32 v5, v1, v3", bits(m), data=(bits(d),))[1], - add_ref(bits(m), bits(d))) - - def test_signed_zeros_and_infinities(self): - # Hardware-verified on RDNA2 (gfx1036): signed zero preservation, infs, and NaN propagation - # -0.0 + -0.0 -> -0.0 - self.assertEqual(run_atomic("ds_add_rtn_f32 v5, v1, v3", 0x80000000, data=(0x80000000,)), (0x80000000, 0x80000000)) - # +0.0 + -0.0 -> +0.0 - self.assertEqual(run_atomic("ds_add_rtn_f32 v5, v1, v3", 0x00000000, data=(0x80000000,)), (0x00000000, 0x00000000)) - # +0.0 + +0.0 -> +0.0 - self.assertEqual(run_atomic("ds_add_rtn_f32 v5, v1, v3", 0x00000000, data=(0x00000000,)), (0x00000000, 0x00000000)) - # +Inf + 1.0 -> +Inf - self.assertEqual(run_atomic("ds_add_rtn_f32 v5, v1, v3", 0x7F800000, data=(bits(1.0),)), (0x7F800000, 0x7F800000)) - # +Inf + -Inf -> qNaN - rtn, res = run_atomic("ds_add_rtn_f32 v5, v1, v3", 0x7F800000, data=(0xFF800000,)) - self.assertEqual(rtn, 0x7F800000) - self.assertTrue((res & 0x7F800000) == 0x7F800000 and (res & 0x007FFFFF) != 0, f"Expected NaN, got {res:#x}") - # qNaN + 1.0 -> qNaN (verifies CAS loop terminates cleanly on NaN without hang) - rtn_nan, res_nan = run_atomic("ds_add_rtn_f32 v5, v1, v3", 0x7FC00000, data=(bits(1.0),)) - self.assertEqual(rtn_nan, 0x7FC00000) - self.assertTrue((res_nan & 0x7F800000) == 0x7F800000 and (res_nan & 0x007FFFFF) != 0, f"Expected NaN, got {res_nan:#x}") - - def test_seeded(self): - rng = random.Random(0xADDF) - for _ in range(25): - m = bits(rng.uniform(-1e6, 1e6)) - d = bits(rng.uniform(-1e6, 1e6)) - with self.subTest(m=hex(m), d=hex(d)): - self.assertEqual(run_atomic("ds_add_rtn_f32 v5, v1, v3", m, data=(d,)), (m, add_ref(m, d))) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_lds_addtid.py b/tests/semantic/test_lds_addtid.py deleted file mode 100644 index 036b04a6b..000000000 --- a/tests/semantic/test_lds_addtid.py +++ /dev/null @@ -1,54 +0,0 @@ -"""Translate ADDTID reads and writes and compare them with ordinary LDS accesses.""" -import struct -import sys -import unittest -from pathlib import Path -from unittest.mock import patch - -sys.path.insert(0, str(Path(__file__).resolve().parent)) -from support import rdna2spirv, translate_lines # noqa: E402 -from test_loop_ballot_barrier import run_compute_workgroup # noqa: E402 - - -def translate_addtid(wave, emulate=False, lines=None): - if lines is None: - fixture = Path(__file__).with_name("fixtures") / "lds_addtid.asm" - lines = [line for line in fixture.read_text(encoding="ascii").splitlines() - if line and not line.startswith(";")] - if wave == 64: - lines = ["s_mov_b64 exec, -1" if line == "s_mov_b32 exec_lo, -1" else line for line in lines] - fssm = bytearray(0x148) - struct.pack_into("> 2) & (lds_dwords - 1) - LDS[dword_idx] = LDS[dword_idx] & (vdata & 0xFFFFFFFF) - The prior value at LDS[dword_idx] is discarded. - - `ds_and_rtn_b32 vdst, vaddr, vdata [offset:N]`: - Returning form: - eff_byte = (vaddr + offset) & 0xFFFFFFFF - dword_idx = (eff_byte >> 2) & (lds_dwords - 1) - old_val = LDS[dword_idx] - LDS[dword_idx] = old_val & (vdata & 0xFFFFFFFF) - vdst = old_val - Preserves the pre-atomic memory contents in destination VGPR vdst. - - 64-bit Atomic AND: - - `ds_and_b64 vaddr, v[data_lo:data_hi] [offset:N]`: - Non-returning form: - eff_byte = (vaddr + offset) & 0xFFFFFFFF - dword_idx0 = (eff_byte >> 2) & (lds_dwords - 1) - dword_idx1 = (dword_idx0 + 1) & (lds_dwords - 1) - LDS[dword_idx0] &= vdata_lo - LDS[dword_idx1] &= vdata_hi - - `ds_and_rtn_b64 v[dst_lo:dst_hi], vaddr, v[data_lo:data_hi] [offset:N]`: - Returning form: returns pre-atomic 64-bit value in VGPR pair v[dst_lo:dst_hi]. - - Active lane masking: - - LDS instructions are vector operations governed by the execution mask (EXEC). - - Inactive lanes do not mutate LDS storage and leave destination VGPRs unmodified. - - Hardware wrapping & alignment: - - Byte addresses are shifted right by 2, dropping unaligned low bits [1:0]. - - The resulting dword index is masked with (lds_dwords - 1), wrapping out-of-bounds - offsets within the allocated power-of-two LDS capacity. - - Mathematical properties of Bitwise AND: - - Idempotency: x & x == x. - - Identity: x & 0xFFFFFFFF == x (all ones mask preserves value). - - Annihilator / Null element: x & 0 == 0 (zero mask clears all bits). - - Commutativity: x & y == y & x. - - Associativity: (x & y) & z == x & (y & z). - - Monotonic bit reduction: popcount(x & y) <= min(popcount(x), popcount(y)). -""" -from __future__ import annotations - -import os -import re -import struct -import sys -import tempfile -import unittest -import warnings - -HERE = os.path.dirname(os.path.abspath(__file__)) -ROOT = os.path.dirname(os.path.dirname(HERE)) -TOOLS_DIR = os.environ.get("LEONIDA_TOOLS_DIR") or os.path.join(ROOT, "tools") -if TOOLS_DIR not in sys.path: - sys.path.insert(0, TOOLS_DIR) - -import rdna2spirv # noqa: E402 - -MASK32 = 0xFFFFFFFF -MASK64 = 0xFFFFFFFFFFFFFFFF -DEFAULT_LDS_DWORDS = 16384 # 64 KiB default capacity in dwords - - -class UnsupportedConstruct(NotImplementedError): - """The module uses an unmodelled SPIR-V opcode, type, or storage class.""" - - -class WorkgroupBoundsError(ValueError): - """Workgroup dimension or memory bounds violation.""" - - -_IGNORED = frozenset({ - "OpCapability", "OpExtInstImport", "OpMemoryModel", "OpEntryPoint", "OpExecutionMode", - "OpDecorate", "OpMemberDecorate", "OpTypeVoid", "OpTypeFunction", "OpLabel", - "OpReturn", "OpFunctionEnd", "OpName", "OpSource", "OpSelectionMerge", -}) - -_LINE = re.compile(r"^(?:(%\S+)\s*=\s*)?(Op\w+)\s*(.*)$") - - -def reference_atomic_and_b32(current_val: int, and_mask: int) -> tuple[int, int]: - """Reference 32-bit atomic AND: returns (old_val, updated_mem_val).""" - old = current_val & MASK32 - new = (old & and_mask) & MASK32 - return old, new - - -def reference_atomic_and_b64(current_val: int, and_mask: int) -> tuple[int, int]: - """Reference 64-bit atomic AND: returns (old_val, updated_mem_val).""" - old = current_val & MASK64 - new = (old & and_mask) & MASK64 - return old, new - - -def split_u64_to_u32(val: int) -> tuple[int, int]: - """Splits a 64-bit unsigned integer into (low_u32, high_u32).""" - val = val & MASK64 - return val & MASK32, (val >> 32) & MASK32 - - -def combine_u32_to_u64(lo: int, hi: int) -> int: - """Combines two 32-bit unsigned integers (low_u32, high_u32) into a 64-bit unsigned integer.""" - return ((hi & MASK32) << 32) | (lo & MASK32) - - -def calc_lds_byte_offset( - vaddr: int, - byte_offset: int = 0, - lds_dwords: int = DEFAULT_LDS_DWORDS, -) -> tuple[int, int, int]: - """Reference ISA calculation for single LDS address: (effective_byte, dword_idx, byte_in_dword).""" - vaddr = vaddr & MASK32 - byte_offset = byte_offset & 0xFFFF # 16-bit unsigned offset in RDNA2 DS instructions - eff_byte = (vaddr + byte_offset) & MASK32 - dword_idx = (eff_byte >> 2) & (lds_dwords - 1) - byte_in_dword = eff_byte & 3 - return eff_byte, dword_idx, byte_in_dword - - -def calc_lds_dual_offsets( - vaddr: int, - offset0: int = 0, - offset1: int = 0, - lds_dwords: int = DEFAULT_LDS_DWORDS, - st64: bool = False, -) -> tuple[tuple[int, int], tuple[int, int]]: - """Reference ISA calculation for dual LDS addresses. - - Returns: - ((eff_byte0, dword_idx0), (eff_byte1, dword_idx1)) - """ - vaddr = vaddr & MASK32 - unit = 256 if st64 else 4 - off0_bytes = (offset0 & 0xFF) * unit - off1_bytes = (offset1 & 0xFF) * unit - eff_byte0 = (vaddr + off0_bytes) & MASK32 - eff_byte1 = (vaddr + off1_bytes) & MASK32 - dword_idx0 = (eff_byte0 >> 2) & (lds_dwords - 1) - dword_idx1 = (eff_byte1 >> 2) & (lds_dwords - 1) - return (eff_byte0, dword_idx0), (eff_byte1, dword_idx1) - - -def translate_cs_listing(body: list[str]) -> str: - """Translates a compute shader listing using rdna2spirv without external files.""" - with tempfile.TemporaryDirectory() as tmp: - os.mkdir(os.path.join(tmp, "disasm")) - os.mkdir(os.path.join(tmp, "fssm")) - name = "cs_lds_and" - with open(os.path.join(tmp, "disasm", name + ".s"), "w", encoding="utf-8") as f: - f.write(f"; {name}\n" + "".join(f"\t{ln}\n" for ln in body) + "\ts_endpgm\n") - stub_dxbc = b"DXBC" + bytes(24) + struct.pack(" None: - self.vgprs[lane][reg_idx] = value & MASK32 - - def get_vgpr(self, reg_idx: int, lane: int = 0) -> int: - return self.vgprs[lane][reg_idx] - - def set_lds_dword(self, dword_idx: int, value: int) -> None: - self.lds[dword_idx & (self.lds_dwords - 1)] = value & MASK32 - - def get_lds_dword(self, dword_idx: int) -> int: - return self.lds[dword_idx & (self.lds_dwords - 1)] - - def set_lane_active(self, lane: int, active: bool) -> None: - self.active_lanes[lane] = bool(active) - - def set_exec_mask(self, mask: int) -> None: - """Sets active lanes based on a 64-bit integer execution mask.""" - for lane in range(self.num_lanes): - self.active_lanes[lane] = bool((mask >> lane) & 1) - - def ds_write_b32(self, vaddr_reg: int, vdata_reg: int, offset: int = 0, lane: int = 0) -> int | None: - if not self.active_lanes[lane]: - return None - vaddr = self.vgprs[lane][vaddr_reg] - vdata = self.vgprs[lane][vdata_reg] - _, dword_idx, _ = calc_lds_byte_offset(vaddr, offset, self.lds_dwords) - self.lds[dword_idx] = vdata & MASK32 - return dword_idx - - def ds_read_b32(self, vdst_reg: int, vaddr_reg: int, offset: int = 0, lane: int = 0) -> int | None: - if not self.active_lanes[lane]: - return None - vaddr = self.vgprs[lane][vaddr_reg] - _, dword_idx, _ = calc_lds_byte_offset(vaddr, offset, self.lds_dwords) - self.vgprs[lane][vdst_reg] = self.lds[dword_idx] - return dword_idx - - def ds_and_b32(self, vaddr_reg: int, vdata_reg: int, offset: int = 0, lane: int = 0) -> int | None: - """Non-returning 32-bit atomic AND: updates LDS[target], returns dword_idx or None.""" - if not self.active_lanes[lane]: - return None - vaddr = self.vgprs[lane][vaddr_reg] - vdata = self.vgprs[lane][vdata_reg] - _, dword_idx, _ = calc_lds_byte_offset(vaddr, offset, self.lds_dwords) - self.lds[dword_idx] = (self.lds[dword_idx] & vdata) & MASK32 - return dword_idx - - def ds_and_rtn_b32( - self, - vdst_reg: int, - vaddr_reg: int, - vdata_reg: int, - offset: int = 0, - lane: int = 0, - ) -> tuple[int, int] | None: - """Returning 32-bit atomic AND: stores prior value into vdst and updates LDS[target]. - - Returns (dword_idx, old_val) if lane active, or None if inactive. - Handles destination register aliasing: reads vaddr and vdata before overwriting vdst. - """ - if not self.active_lanes[lane]: - return None - vaddr = self.vgprs[lane][vaddr_reg] - vdata = self.vgprs[lane][vdata_reg] - _, dword_idx, _ = calc_lds_byte_offset(vaddr, offset, self.lds_dwords) - old_val = self.lds[dword_idx] - self.lds[dword_idx] = (old_val & vdata) & MASK32 - self.vgprs[lane][vdst_reg] = old_val - return dword_idx, old_val - - def set_vgpr_u64(self, reg_idx: int, value: int, lane: int = 0) -> None: - lo, hi = split_u64_to_u32(value) - self.set_vgpr(reg_idx, lo, lane=lane) - self.set_vgpr(reg_idx + 1, hi, lane=lane) - - def get_vgpr_u64(self, reg_idx: int, lane: int = 0) -> int: - lo = self.get_vgpr(reg_idx, lane=lane) - hi = self.get_vgpr(reg_idx + 1, lane=lane) - return combine_u32_to_u64(lo, hi) - - def set_lds_u64(self, dword_idx: int, value: int) -> None: - lo, hi = split_u64_to_u32(value) - self.set_lds_dword(dword_idx, lo) - self.set_lds_dword((dword_idx + 1) & (self.lds_dwords - 1), hi) - - def get_lds_u64(self, dword_idx: int) -> int: - lo = self.get_lds_dword(dword_idx) - hi = self.get_lds_dword((dword_idx + 1) & (self.lds_dwords - 1)) - return combine_u32_to_u64(lo, hi) - - def ds_write_b64(self, vaddr_reg: int, vdata_lo_reg: int, offset: int = 0, lane: int = 0) -> tuple[int, int] | None: - if not self.active_lanes[lane]: - return None - vaddr = self.vgprs[lane][vaddr_reg] - _, dword_idx0, _ = calc_lds_byte_offset(vaddr, offset, self.lds_dwords) - dword_idx1 = (dword_idx0 + 1) & (self.lds_dwords - 1) - self.lds[dword_idx0] = self.vgprs[lane][vdata_lo_reg] & MASK32 - self.lds[dword_idx1] = self.vgprs[lane][vdata_lo_reg + 1] & MASK32 - return dword_idx0, dword_idx1 - - def ds_read_b64(self, vdst_lo_reg: int, vaddr_reg: int, offset: int = 0, lane: int = 0) -> tuple[int, int] | None: - if not self.active_lanes[lane]: - return None - vaddr = self.vgprs[lane][vaddr_reg] - _, dword_idx0, _ = calc_lds_byte_offset(vaddr, offset, self.lds_dwords) - dword_idx1 = (dword_idx0 + 1) & (self.lds_dwords - 1) - val_lo = self.lds[dword_idx0] - val_hi = self.lds[dword_idx1] - self.vgprs[lane][vdst_lo_reg] = val_lo - self.vgprs[lane][vdst_lo_reg + 1] = val_hi - return dword_idx0, dword_idx1 - - def ds_and_b64(self, vaddr_reg: int, vdata_lo_reg: int, offset: int = 0, lane: int = 0) -> tuple[int, int] | None: - """Non-returning 64-bit atomic AND: updates LDS[idx] and LDS[idx+1], returns (idx0, idx1) or None.""" - if not self.active_lanes[lane]: - return None - vaddr = self.vgprs[lane][vaddr_reg] - vdata_lo = self.vgprs[lane][vdata_lo_reg] - vdata_hi = self.vgprs[lane][vdata_lo_reg + 1] - _, dword_idx0, _ = calc_lds_byte_offset(vaddr, offset, self.lds_dwords) - dword_idx1 = (dword_idx0 + 1) & (self.lds_dwords - 1) - self.lds[dword_idx0] = (self.lds[dword_idx0] & vdata_lo) & MASK32 - self.lds[dword_idx1] = (self.lds[dword_idx1] & vdata_hi) & MASK32 - return dword_idx0, dword_idx1 - - def ds_and_rtn_b64( - self, - vdst_lo_reg: int, - vaddr_reg: int, - vdata_lo_reg: int, - offset: int = 0, - lane: int = 0, - ) -> tuple[int, int] | None: - """Returning 64-bit atomic AND: stores prior 64-bit value into vdst[0:1] and updates LDS[idx:idx+1]. - - Returns (dword_idx0, old_val_u64) if lane active, or None if inactive. - Reads all sources before writing vdst to handle aliasing safely. - """ - if not self.active_lanes[lane]: - return None - vaddr = self.vgprs[lane][vaddr_reg] - vdata_lo = self.vgprs[lane][vdata_lo_reg] - vdata_hi = self.vgprs[lane][vdata_lo_reg + 1] - _, dword_idx0, _ = calc_lds_byte_offset(vaddr, offset, self.lds_dwords) - dword_idx1 = (dword_idx0 + 1) & (self.lds_dwords - 1) - old_lo = self.lds[dword_idx0] - old_hi = self.lds[dword_idx1] - self.lds[dword_idx0] = (old_lo & vdata_lo) & MASK32 - self.lds[dword_idx1] = (old_hi & vdata_hi) & MASK32 - self.vgprs[lane][vdst_lo_reg] = old_lo - self.vgprs[lane][vdst_lo_reg + 1] = old_hi - return dword_idx0, combine_u32_to_u64(old_lo, old_hi) - - def parse_and_execute(self, instruction_text: str, lane: int = 0) -> int | tuple[int, int] | None: - line = instruction_text.strip() - if not line or line.startswith(";"): - return None - - offset = 0 - m_off = re.search(r"\boffset:(\S+)", line) - if m_off: - offset = int(m_off.group(1), 0) - line = re.sub(r"\boffset:\S+", "", line).strip() - - parts = line.split(None, 1) - op = parts[0] - args_str = parts[1] if len(parts) > 1 else "" - raw_args = [a.strip() for a in args_str.split(",") if a.strip()] - - def reg_num(tok: str) -> int: - cleaned = tok.replace("v", "").replace("[", "").replace("]", "") - if ":" in cleaned: - cleaned = cleaned.split(":")[0] - return int(cleaned) - - if op == "ds_and_b32": - vaddr = reg_num(raw_args[0]) - vdata = reg_num(raw_args[1]) - return self.ds_and_b32(vaddr, vdata, offset=offset, lane=lane) - - elif op == "ds_and_rtn_b32": - vdst = reg_num(raw_args[0]) - vaddr = reg_num(raw_args[1]) - vdata = reg_num(raw_args[2]) - res = self.ds_and_rtn_b32(vdst, vaddr, vdata, offset=offset, lane=lane) - return res[0] if res else None - - elif op == "ds_write_b32": - vaddr = reg_num(raw_args[0]) - vdata = reg_num(raw_args[1]) - return self.ds_write_b32(vaddr, vdata, offset=offset, lane=lane) - - elif op == "ds_read_b32": - vdst = reg_num(raw_args[0]) - vaddr = reg_num(raw_args[1]) - return self.ds_read_b32(vdst, vaddr, offset=offset, lane=lane) - - elif op == "ds_and_b64": - vaddr = reg_num(raw_args[0]) - vdata = reg_num(raw_args[1]) - res_b64 = self.ds_and_b64(vaddr, vdata, offset=offset, lane=lane) - return res_b64[0] if res_b64 else None - - elif op == "ds_and_rtn_b64": - vdst = reg_num(raw_args[0]) - vaddr = reg_num(raw_args[1]) - vdata = reg_num(raw_args[2]) - res_rtn_b64 = self.ds_and_rtn_b64(vdst, vaddr, vdata, offset=offset, lane=lane) - return res_rtn_b64[0] if res_rtn_b64 else None - - elif op == "ds_write_b64": - vaddr = reg_num(raw_args[0]) - vdata = reg_num(raw_args[1]) - res_w64 = self.ds_write_b64(vaddr, vdata, offset=offset, lane=lane) - return res_w64[0] if res_w64 else None - - elif op == "ds_read_b64": - vdst = reg_num(raw_args[0]) - vaddr = reg_num(raw_args[1]) - res_r64 = self.ds_read_b64(vdst, vaddr, offset=offset, lane=lane) - return res_r64[0] if res_r64 else None - - else: - raise UnsupportedConstruct(f"Opcode {op} not supported in interpreter") - - def run_simd_wave(self, instruction_text: str) -> list[int | tuple[int, int] | None]: - """Runs the instruction across all lanes in the wavefront in lockstep.""" - return [self.parse_and_execute(instruction_text, lane=lane) for lane in range(self.num_lanes)] - - -class LdsAtomicSpirvInterp: - """Strict semantic interpreter for compute SPIR-V modules exercising LDS atomic AND.""" - - def __init__(self, spvasm: str): - self.spvasm = spvasm - self.types: dict[str, tuple] = {} - self.constants: dict[str, int | bool] = {} - self.ptr_types: dict[str, tuple[str, str]] = {} - self.var_class: dict[str, str] = {} - self.local_size: tuple[int, int, int] = (1, 1, 1) - self.lds_var: str | None = None - self.lds_size: int = 0 - self.body: list[tuple[str | None, str, list[str], str]] = [] - self._parse() - - def _parse(self) -> None: - in_body = False - for raw in self.spvasm.splitlines(): - line = raw.strip() - if not line: - continue - m = _LINE.match(line) - if not m: - raise UnsupportedConstruct(f"Cannot parse line: {line!r}") - res, op, rest = m.groups() - a = rest.split() - if in_body: - self.body.append((res, op, a, line)) - continue - if op == "OpFunction": - in_body = True - continue - if op == "OpExecutionMode" and len(a) >= 5 and a[1] == "LocalSize": - lx, ly, lz = int(a[2]), int(a[3]), int(a[4]) - if lx < 1 or ly < 1 or lz < 1 or (lx * ly * lz) > 1024: - raise WorkgroupBoundsError(f"Invalid LocalSize {lx}x{ly}x{lz}") - self.local_size = (lx, ly, lz) - continue - if op in _IGNORED: - continue - if op == "OpTypeInt": - if int(a[0]) != 32: - raise UnsupportedConstruct("Only 32-bit int supported in interpreter") - self.types[res] = ("int", int(a[0]), int(a[1])) - elif op == "OpTypeBool": - self.types[res] = ("bool",) - elif op == "OpTypeVector": - self.types[res] = ("vec", a[0], int(a[1])) - elif op == "OpTypeArray": - size = int(self.constants[a[1]]) - self.types[res] = ("arr", a[0], size) - elif op == "OpTypePointer": - self.ptr_types[res] = (a[0], a[1]) - elif op == "OpConstant": - self.constants[res] = int(a[1], 0) & MASK32 - elif op == "OpConstantTrue": - self.constants[res] = True - elif op == "OpConstantFalse": - self.constants[res] = False - elif op == "OpVariable": - cls, pointee = self.ptr_types[a[0]] - if a[1] != cls: - raise UnsupportedConstruct("OpVariable storage class mismatch") - self.var_class[res] = cls - if cls == "Workgroup": - if self.lds_var is not None: - raise UnsupportedConstruct("Multiple Workgroup variables") - self.lds_var = res - arr_ty = self.types[pointee] - if arr_ty[0] != "arr": - raise UnsupportedConstruct("Workgroup variable must be an array") - self.lds_size = arr_ty[2] - elif cls not in ("Output", "Function"): - raise UnsupportedConstruct(f"Unsupported storage class {cls}") - else: - raise UnsupportedConstruct(f"Header opcode {op}") - - def run( - self, - num_invocations: int | None = None, - seed_lds: dict[int, int] | None = None, - lane_inputs: list[dict[str, int]] | None = None, - ) -> tuple[list[int], list[dict[str, int]]]: - """Executes the workgroup and returns (final_lds, outputs_per_lane).""" - lx, ly, lz = self.local_size - total_invocations = lx * ly * lz - count = total_invocations if num_invocations is None else min(num_invocations, total_invocations) - - lds = [0] * self.lds_size - if seed_lds: - for idx, val in seed_lds.items(): - if 0 <= idx < self.lds_size: - lds[idx] = val & MASK32 - - lane_outputs: list[dict[str, int]] = [] - for lidx in range(count): - inputs = lane_inputs[lidx] if lane_inputs and lidx < len(lane_inputs) else {} - out = self._run_lane(lidx, lds, inputs) - lane_outputs.append(out) - - return list(lds), lane_outputs - - def _run_lane(self, lidx: int, lds: list[int], inputs: dict[str, int]) -> dict[str, int]: - values: dict[str, int | bool] = dict(self.constants) - values.update(inputs) - var_box: dict[str, list[int]] = {} - pointers: dict[str, tuple[str, list[int], int | None]] = {} - outputs: list[str] = [] - - if self.lds_var: - pointers[self.lds_var] = ("lds", lds, None) - - for res, cls in self.var_class.items(): - if cls == "Output": - var_box[res] = [0] - pointers[res] = ("out", var_box[res], 0) - outputs.append(res) - elif cls == "Function": - var_box[res] = [0] - pointers[res] = ("fn", var_box[res], 0) - - def val(x: str) -> int: - if x in values: - return values[x] # type: ignore - raise UnsupportedConstruct(f"Undefined identifier {x}") - - for res, op, a, _ in self.body: - if op in _IGNORED or op in ("OpBranch", "OpBranchConditional"): - continue - if op == "OpVariable": - cls, _ = self.ptr_types[a[0]] - if cls != "Function": - raise UnsupportedConstruct("Non-Function variable in body") - var_box[res] = [val(a[2]) if len(a) > 2 else 0] - pointers[res] = ("fn", var_box[res], 0) - elif op == "OpAccessChain": - base = a[1] - if base not in pointers: - raise UnsupportedConstruct(f"OpAccessChain on non-pointer {base}") - ptag = pointers[base][0] - if ptag == "lds": - idx = val(a[2]) - if not (0 <= idx < len(lds)): - raise WorkgroupBoundsError(f"LDS access out of bounds: {idx} >= {len(lds)}") - pointers[res] = ("lds", lds, idx) - elif ptag in ("out", "fn"): - pointers[res] = pointers[base] - else: - raise UnsupportedConstruct(f"Access chain on {ptag}") - elif op == "OpLoad": - ptr = pointers[a[1]] - ptag = ptr[0] - if ptag in ("lds", "out", "fn"): - idx_val = ptr[2] - values[res] = ptr[1][idx_val] & MASK32 - elif op == "OpStore": - ptr = pointers[a[0]] - v = val(a[1]) & MASK32 - ptag = ptr[0] - if ptag in ("lds", "out", "fn"): - idx_val = ptr[2] - ptr[1][idx_val] = v - elif op == "OpAtomicAnd": - # %res = OpAtomicAnd %type %ptr %scope %semantics %val - ptr = pointers[a[1]] - ptag = ptr[0] - if ptag != "lds": - raise UnsupportedConstruct(f"OpAtomicAnd on non-LDS pointer {ptag}") - mask_val = val(a[4]) & MASK32 - idx_val = ptr[2] - old = ptr[1][idx_val] & MASK32 - ptr[1][idx_val] = (old & mask_val) & MASK32 - values[res] = old - elif op == "OpIAdd": - values[res] = (val(a[1]) + val(a[2])) & MASK32 - elif op == "OpISub": - values[res] = (val(a[1]) - val(a[2])) & MASK32 - elif op == "OpShiftRightLogical": - sh = val(a[2]) - if sh >= 32: - raise UnsupportedConstruct("Shift >= 32") - values[res] = (val(a[1]) >> sh) & MASK32 - elif op == "OpShiftLeftLogical": - sh = val(a[2]) - if sh >= 32: - raise UnsupportedConstruct("Shift >= 32") - values[res] = (val(a[1]) << sh) & MASK32 - elif op == "OpBitwiseAnd": - values[res] = val(a[1]) & val(a[2]) & MASK32 - elif op == "OpBitwiseOr": - values[res] = (val(a[1]) | val(a[2])) & MASK32 - elif op == "OpBitwiseXor": - values[res] = (val(a[1]) ^ val(a[2])) & MASK32 - elif op == "OpSelect": - cond = val(a[1]) - values[res] = val(a[2]) if cond else val(a[3]) - elif op == "OpCopyObject": - values[res] = val(a[1]) - elif op == "OpBitcast": - values[res] = val(a[1]) & MASK32 - else: - raise UnsupportedConstruct(f"Opcode {op} not modelled in body") - - return {name: var_box[name][0] & MASK32 for name in outputs} - - -class TestAtomicAndReferenceMath(unittest.TestCase): - """Verifies 32-bit and 64-bit atomic bitwise AND math, truth tables, and algebraic properties.""" - - def test_and_truth_tables_b32(self): - all_zeros = 0x00000000 - all_ones = 0xFFFFFFFF - alt_a = 0x55555555 - alt_b = 0xAAAAAAAA - - old, mem = reference_atomic_and_b32(all_zeros, all_zeros) - self.assertEqual(old, all_zeros) - self.assertEqual(mem, all_zeros) - - old, mem = reference_atomic_and_b32(all_zeros, all_ones) - self.assertEqual(old, all_zeros) - self.assertEqual(mem, all_zeros) - - old, mem = reference_atomic_and_b32(all_ones, all_zeros) - self.assertEqual(old, all_ones) - self.assertEqual(mem, all_zeros) - - old, mem = reference_atomic_and_b32(all_ones, all_ones) - self.assertEqual(old, all_ones) - self.assertEqual(mem, all_ones) - - old, mem = reference_atomic_and_b32(alt_a, alt_b) - self.assertEqual(old, alt_a) - self.assertEqual(mem, all_zeros) - - old, mem = reference_atomic_and_b32(alt_a, alt_a) - self.assertEqual(old, alt_a) - self.assertEqual(mem, alt_a) - - def test_identity_and_annihilator_properties(self): - test_values = [ - 0x00000000, - 0x00000001, - 0x12345678, - 0x7FFFFFFF, - 0x80000000, - 0xFFFFFFFF, - 0xDEADBEEF, - 0xCAFEBABE, - ] - for val in test_values: - with self.subTest(val=hex(val)): - old, mem = reference_atomic_and_b32(val, MASK32) - self.assertEqual(old, val) - self.assertEqual(mem, val) - - old, mem = reference_atomic_and_b32(val, 0) - self.assertEqual(old, val) - self.assertEqual(mem, 0) - - def test_idempotency_b32(self): - test_values = [ - 0x00000000, - 0x00000001, - 0x55555555, - 0xAAAAAAAA, - 0x12345678, - 0x87654321, - 0xFFFFFFFF, - ] - for val in test_values: - with self.subTest(val=hex(val)): - old, mem = reference_atomic_and_b32(val, val) - self.assertEqual(old, val) - self.assertEqual(mem, val) - - def test_commutativity_and_associativity_b32(self): - a, b = 0x3F2A1C8E, 0x9D4E7B01 - _, ab = reference_atomic_and_b32(a, b) - _, ba = reference_atomic_and_b32(b, a) - self.assertEqual(ab, ba) - - c = 0x55AA33CC - _, step_ab = reference_atomic_and_b32(a, b) - _, ab_c = reference_atomic_and_b32(step_ab, c) - - _, step_bc = reference_atomic_and_b32(b, c) - _, a_bc = reference_atomic_and_b32(a, step_bc) - self.assertEqual(ab_c, a_bc) - - def test_bitfield_clearing_and_isolation(self): - initial = 0xFFFFFFFF - for bit in range(32): - mask = ~(1 << bit) & MASK32 - old, mem = reference_atomic_and_b32(initial, mask) - self.assertEqual(old, initial) - self.assertEqual(mem, initial & mask) - self.assertEqual(mem & (1 << bit), 0) - self.assertEqual(bin(mem).count("1"), 31) - - val = 0x12345678 - low_byte_mask = 0x000000FF - _, low_byte = reference_atomic_and_b32(val, low_byte_mask) - self.assertEqual(low_byte, 0x00000078) - - high_byte_mask = 0xFF000000 - _, high_byte = reference_atomic_and_b32(val, high_byte_mask) - self.assertEqual(high_byte, 0x12000000) - - def test_monotonic_bit_reduction(self): - val = 0xFFFFFFFF - filters = [0xF0F0F0F0, 0x33333333, 0x0F0F0F0F, 0x00FF00FF, 0x0000FFFF] - current = val - pop = bin(current).count("1") - self.assertEqual(pop, 32) - for flt in filters: - old, current = reference_atomic_and_b32(current, flt) - self.assertEqual(old & flt, current) - new_pop = bin(current).count("1") - self.assertLessEqual(new_pop, pop) - pop = new_pop - - def test_de_morgans_laws_with_inversion(self): - cases = [ - (0x12345678, 0x9ABCDEF0), - (0x55555555, 0xAAAAAAAA), - (0x0000FFFF, 0xFFFF0000), - (0xFFFFFFFF, 0x00000000), - ] - for a, b in cases: - with self.subTest(a=hex(a), b=hex(b)): - _, and_ab = reference_atomic_and_b32(a, b) - not_and_ab = (~and_ab) & MASK32 - not_a = (~a) & MASK32 - not_b = (~b) & MASK32 - or_not_ab = (not_a | not_b) & MASK32 - self.assertEqual(not_and_ab, or_not_ab) - - def test_reference_atomic_and_b64_properties(self): - init = 0x0123456789ABCDEF - mask = 0xFEDCBA9876543210 - old, mem = reference_atomic_and_b64(init, mask) - self.assertEqual(old, init) - self.assertEqual(mem, init & mask) - - old, mem = reference_atomic_and_b64(init, MASK64) - self.assertEqual(old, init) - self.assertEqual(mem, init) - - old, mem = reference_atomic_and_b64(init, 0) - self.assertEqual(old, init) - self.assertEqual(mem, 0) - - cross1 = 0xFFFFFFFF00000000 - cross2 = 0x00000000FFFFFFFF - _, mem_cross = reference_atomic_and_b64(cross1, cross2) - self.assertEqual(mem_cross, 0) - - def test_split_and_combine_u64_u32(self): - v64 = 0xFEDCBA9876543210 - lo, hi = split_u64_to_u32(v64) - self.assertEqual(lo, 0x76543210) - self.assertEqual(hi, 0xFEDCBA98) - self.assertEqual(combine_u32_to_u64(lo, hi), v64) - - -class TestLdsAddressingAndOffsets(unittest.TestCase): - """Verifies single and dual LDS byte offsets, dword truncation, st64 strides, and wrapping.""" - - def test_aligned_dword_addressing(self): - lds_dwords = 256 - for dword in (0, 1, 2, 8, 16, 64, 127, 255): - byte_addr = dword * 4 - eff, dword_idx, byte_pos = calc_lds_byte_offset(byte_addr, 0, lds_dwords) - self.assertEqual(eff, byte_addr) - self.assertEqual(dword_idx, dword) - self.assertEqual(byte_pos, 0) - - def test_unaligned_byte_truncation(self): - lds_dwords = 128 - base_aligned = 64 # dword 16 - for b in (0, 1, 2, 3): - eff, dword_idx, byte_pos = calc_lds_byte_offset(base_aligned, b, lds_dwords) - self.assertEqual(eff, base_aligned + b) - self.assertEqual(dword_idx, 16) - self.assertEqual(byte_pos, b) - - def test_offset_16bit_masking(self): - lds_dwords = 512 - # RDNA2 DS instruction offset field is 16-bit unsigned (0x0000 - 0xFFFF) - eff, dword_idx, byte_pos = calc_lds_byte_offset(0, 0x10008, lds_dwords) - self.assertEqual(eff, 8) - self.assertEqual(dword_idx, 2) - self.assertEqual(byte_pos, 0) - - def test_dual_offset_unit_strides(self): - (eff0, idx0), (eff1, idx1) = calc_lds_dual_offsets(0, 3, 10, lds_dwords=1024, st64=False) - self.assertEqual(eff0, 12) - self.assertEqual(idx0, 3) - self.assertEqual(eff1, 40) - self.assertEqual(idx1, 10) - - def test_dual_offset_st64_stride(self): - (eff0, idx0), (eff1, idx1) = calc_lds_dual_offsets(0, 2, 5, lds_dwords=1024, st64=True) - self.assertEqual(eff0, 512) - self.assertEqual(idx0, 128) - self.assertEqual(eff1, 1280) - self.assertEqual(idx1, 320) - - def test_boundary_power_of_two_wrapping(self): - lds_dwords = 64 # 256 bytes total - # Byte address 256 wraps to dword 0 - _, idx0, _ = calc_lds_byte_offset(256, 0, lds_dwords) - self.assertEqual(idx0, 0) - # Byte address 260 wraps to dword 1 - _, idx1, _ = calc_lds_byte_offset(256, 4, lds_dwords) - self.assertEqual(idx1, 1) - # 32-bit unsigned overflow: 0xFFFFFFFC + 4 = 0x00000000 -> dword 0 - _, idx_wrap, _ = calc_lds_byte_offset(0xFFFFFFFC, 4, lds_dwords) - self.assertEqual(idx_wrap, 0) - - -class TestMultiLaneSimdDivergence(unittest.TestCase): - """Verifies SIMD wavefront divergence, execution mask filtering, and independent lane addresses.""" - - def test_simd_active_mask_filtering(self): - simd = LdsSemanticInterpreter(lds_dwords=256, num_lanes=64) - simd.set_lds_dword(0, 0xFFFFFFFF) - # Lower 32 lanes active, upper 32 lanes inactive - simd.set_exec_mask(0x00000000FFFFFFFF) - - for lane in range(64): - simd.set_vgpr(0, 0, lane=lane) # vaddr = 0 - simd.set_vgpr(1, 0x55555555, lane=lane) # vdata = 0x55555555 - simd.set_vgpr(2, 0xDEADBEEF, lane=lane) # vdst initial sentinel - - results = simd.run_simd_wave("ds_and_rtn_b32 v2, v0, v1") - # Active lanes 0..31: executed and returned dword 0 - for lane in range(32): - self.assertEqual(results[lane], 0) - self.assertIn(simd.get_vgpr(2, lane=lane), (0xFFFFFFFF, 0x55555555)) - - # Inactive lanes 32..63: did not execute, destination untouched - for lane in range(32, 64): - self.assertIsNone(results[lane]) - self.assertEqual(simd.get_vgpr(2, lane=lane), 0xDEADBEEF) - - # Final memory in LDS[0] must reflect active lane AND - self.assertEqual(simd.get_lds_dword(0), 0x55555555) - - def test_even_odd_divergent_lanes(self): - simd = LdsSemanticInterpreter(lds_dwords=256, num_lanes=64) - simd.set_lds_dword(4, 0xFFFFFFFF) - - for lane in range(64): - simd.set_vgpr(0, 16, lane=lane) # byte address 16 -> dword 4 - simd.set_vgpr(1, 0xFF00FF00 if (lane % 2 == 0) else 0x00FF00FF, lane=lane) - - # Path 1: even lanes active - simd.set_exec_mask(0x5555555555555555) - simd.run_simd_wave("ds_and_b32 v0, v1") - self.assertEqual(simd.get_lds_dword(4), 0xFF00FF00) - - # Path 2: odd lanes active - simd.set_exec_mask(0xAAAAAAAAAAAAAAAA) - simd.run_simd_wave("ds_and_b32 v0, v1") - # 0xFF00FF00 & 0x00FF00FF == 0x00000000 - self.assertEqual(simd.get_lds_dword(4), 0x00000000) - - def test_sparse_active_lanes(self): - simd = LdsSemanticInterpreter(lds_dwords=256, num_lanes=64) - simd.set_lds_dword(10, 0xFFFFFFFF) - sparse_lanes = [3, 17, 42, 60] - mask = 0 - for l in sparse_lanes: - mask |= (1 << l) - simd.set_exec_mask(mask) - - for lane in range(64): - simd.set_vgpr(0, 40, lane=lane) # byte 40 -> dword 10 - simd.set_vgpr(1, ~(1 << lane) & MASK32, lane=lane) - simd.set_vgpr(5, 0x11223344, lane=lane) - - results = simd.run_simd_wave("ds_and_rtn_b32 v5, v0, v1") - for lane in range(64): - if lane in sparse_lanes: - self.assertEqual(results[lane], 10) - self.assertNotEqual(simd.get_vgpr(5, lane=lane), 0x11223344) - else: - self.assertIsNone(results[lane]) - self.assertEqual(simd.get_vgpr(5, lane=lane), 0x11223344) - - # The bits of the sparse lanes must be cleared in LDS[10] - expected_mem = 0xFFFFFFFF - for l in sparse_lanes: - expected_mem &= ~(1 << l) & MASK32 - self.assertEqual(simd.get_lds_dword(10), expected_mem) - - def test_divergent_branch_paths_simd(self): - simd = LdsSemanticInterpreter(lds_dwords=256, num_lanes=64) - simd.set_lds_dword(8, 0xFFFFFFFF) - - for lane in range(64): - simd.set_vgpr(0, 32, lane=lane) # dword 8 - # Lower 32 lanes clear low 16 bits; upper 32 lanes clear high 16 bits - val = 0xFFFF0000 if lane < 32 else 0x0000FFFF - simd.set_vgpr(1, val, lane=lane) - simd.set_vgpr(7, 0x99999999, lane=lane) - - # Then-branch (lower half active) - simd.set_exec_mask(0x00000000FFFFFFFF) - simd.run_simd_wave("ds_and_rtn_b32 v7, v0, v1") - self.assertEqual(simd.get_lds_dword(8), 0xFFFF0000) - - # Else-branch (upper half active) - simd.set_exec_mask(0xFFFFFFFF00000000) - simd.run_simd_wave("ds_and_rtn_b32 v7, v0, v1") - self.assertEqual(simd.get_lds_dword(8), 0x00000000) - - def test_multi_lane_independent_addresses(self): - simd = LdsSemanticInterpreter(lds_dwords=256, num_lanes=64) - simd.set_exec_mask(MASK64) - - for lane in range(64): - simd.set_lds_dword(lane, 0xFFFFFFFF) - simd.set_vgpr(0, lane * 4, lane=lane) - simd.set_vgpr(1, ~(1 << (lane % 32)) & MASK32, lane=lane) - simd.set_vgpr(3, 0, lane=lane) - - results = simd.run_simd_wave("ds_and_rtn_b32 v3, v0, v1") - for lane in range(64): - self.assertEqual(results[lane], lane) - # Old value returned to lane was initial 0xFFFFFFFF - self.assertEqual(simd.get_vgpr(3, lane=lane), 0xFFFFFFFF) - # Memory has exactly bit (lane % 32) cleared - expected = ~(1 << (lane % 32)) & MASK32 - self.assertEqual(simd.get_lds_dword(lane), expected) - - -class TestSharedMemoryAddressClash(unittest.TestCase): - """Verifies atomic bitwise AND address clashing, bank contention, and cumulative reduction.""" - - def test_all_lanes_clash_on_single_address(self): - # All 32 lanes in Wave32 concurrently clash on LDS[5] - simd = LdsSemanticInterpreter(lds_dwords=256, num_lanes=32) - simd.set_lds_dword(5, 0xFFFFFFFF) - simd.set_exec_mask(0xFFFFFFFF) - - for lane in range(32): - simd.set_vgpr(0, 20, lane=lane) # byte 20 -> dword 5 - simd.set_vgpr(1, ~(1 << lane) & MASK32, lane=lane) - simd.set_vgpr(2, 0, lane=lane) - - simd.run_simd_wave("ds_and_rtn_b32 v2, v0, v1") - - # Every lane received an old value with its own bit still set - for lane in range(32): - ret_val = simd.get_vgpr(2, lane=lane) - self.assertTrue(ret_val & (1 << lane), f"Lane {lane} missed its set bit in return value {ret_val:#x}") - - # Final memory has all 32 bits cleared - self.assertEqual(simd.get_lds_dword(5), 0x00000000) - - def test_64_lane_address_clash_all_lanes(self): - # 64 lanes in Wave64 clash on LDS[0] - simd = LdsSemanticInterpreter(lds_dwords=256, num_lanes=64) - simd.set_lds_dword(0, 0xFFFFFFFF) - simd.set_exec_mask(MASK64) - - for lane in range(64): - simd.set_vgpr(0, 0, lane=lane) - # Lanes 0..31 clear single bits, lanes 32..63 clear all - mask = (~(1 << lane) & MASK32) if lane < 32 else 0 - simd.set_vgpr(1, mask, lane=lane) - - simd.run_simd_wave("ds_and_b32 v0, v1") - self.assertEqual(simd.get_lds_dword(0), 0) - - def test_bank_clash_interleaved_lanes(self): - # 64 lanes interleaved across 4 slots: LDS[0], LDS[1], LDS[2], LDS[3] - simd = LdsSemanticInterpreter(lds_dwords=256, num_lanes=64) - for s in range(4): - simd.set_lds_dword(s, 0xFFFFFFFF) - simd.set_exec_mask(MASK64) - - for lane in range(64): - slot = lane % 4 - simd.set_vgpr(0, slot * 4, lane=lane) - bit = (lane // 4) % 32 - simd.set_vgpr(1, ~(1 << bit) & MASK32, lane=lane) - - simd.run_simd_wave("ds_and_b32 v0, v1") - - # In each slot, bits 0..15 were cleared by 16 clashing lanes - for s in range(4): - expected = 0xFFFF0000 - self.assertEqual(simd.get_lds_dword(s), expected) - - def test_cumulative_mask_reduction_order_independence(self): - masks = [0xF0F0F0F0, 0xCCCCCCCC, 0xAAAAAAAA, 0x0F0F0F0F, 0x33333333, 0x55555555] - simd = LdsSemanticInterpreter(lds_dwords=64, num_lanes=6) - simd.set_lds_dword(2, 0xFFFFFFFF) - simd.set_exec_mask(0x3F) - - for lane in range(6): - simd.set_vgpr(0, 8, lane=lane) # byte 8 -> dword 2 - simd.set_vgpr(1, masks[lane], lane=lane) - - simd.run_simd_wave("ds_and_b32 v0, v1") - expected = 0xFFFFFFFF - for m in masks: - expected &= m - self.assertEqual(simd.get_lds_dword(2), expected) - - def test_multi_lane_atomic_reservation_ticket(self): - # Shared bitmask of 8 available resources (bits 0..7) - simd = LdsSemanticInterpreter(lds_dwords=64, num_lanes=8) - simd.set_lds_dword(0, 0x000000FF) - simd.set_exec_mask(0xFF) - - for lane in range(8): - simd.set_vgpr(0, 0, lane=lane) - # Each lane claims slot by clearing bit `lane` - simd.set_vgpr(1, ~(1 << lane) & MASK32, lane=lane) - simd.set_vgpr(4, 0, lane=lane) - - simd.run_simd_wave("ds_and_rtn_b32 v4, v0, v1") - # All 8 slots were claimed -> final memory is 0 - self.assertEqual(simd.get_lds_dword(0), 0) - # Every lane saw that slot `lane` was available at the time of claim - for lane in range(8): - self.assertTrue(simd.get_vgpr(4, lane=lane) & (1 << lane)) - - -class TestSpirvMultiLaneAtomicAnd(unittest.TestCase): - """Executes SPIR-V compute kernels testing OpAtomicAnd multi-lane workgroup behavior.""" - - def test_spirv_workgroup_shared_slot_and(self): - spvasm = """ -OpCapability Shader -OpMemoryModel Logical GLSL450 -OpEntryPoint GLCompute %main "main" -OpExecutionMode %main LocalSize 8 1 1 -%uint = OpTypeInt 32 0 -%c16 = OpConstant %uint 16 -%c2 = OpConstant %uint 2 -%c0 = OpConstant %uint 0 -%c0_slot = OpConstant %uint 0 -%c_mask = OpConstant %uint 4042322160 -%lds_arr = OpTypeArray %uint %c16 -%_ptr_WG_lds = OpTypePointer Workgroup %lds_arr -%_ptr_WG_uint = OpTypePointer Workgroup %uint -%lds = OpVariable %_ptr_WG_lds Workgroup -%void = OpTypeVoid -%fn = OpTypeFunction %void -%main = OpFunction %void None %fn -%entry = OpLabel -%ptr = OpAccessChain %_ptr_WG_uint %lds %c0_slot -%res = OpAtomicAnd %uint %ptr %c2 %c0 %c_mask -OpReturn -OpFunctionEnd -""" - interp = LdsAtomicSpirvInterp(spvasm) - final_lds, _ = interp.run(num_invocations=8, seed_lds={0: 0xFFFFFFFF}) - # 0xFFFFFFFF & 4042322160 (0xF0F0F0F0) = 0xF0F0F0F0 - self.assertEqual(final_lds[0], 0xF0F0F0F0) - - def test_spirv_returning_atomic_and_tickets(self): - spvasm = """ -OpCapability Shader -OpMemoryModel Logical GLSL450 -OpEntryPoint GLCompute %main "main" %out -OpExecutionMode %main LocalSize 4 1 1 -%uint = OpTypeInt 32 0 -%_ptr_Output_uint = OpTypePointer Output %uint -%out = OpVariable %_ptr_Output_uint Output -%c16 = OpConstant %uint 16 -%c2 = OpConstant %uint 2 -%c0 = OpConstant %uint 0 -%c1_slot = OpConstant %uint 1 -%c_half = OpConstant %uint 65535 -%lds_arr = OpTypeArray %uint %c16 -%_ptr_WG_lds = OpTypePointer Workgroup %lds_arr -%_ptr_WG_uint = OpTypePointer Workgroup %uint -%lds = OpVariable %_ptr_WG_lds Workgroup -%void = OpTypeVoid -%fn = OpTypeFunction %void -%main = OpFunction %void None %fn -%entry = OpLabel -%ptr = OpAccessChain %_ptr_WG_uint %lds %c1_slot -%old = OpAtomicAnd %uint %ptr %c2 %c0 %c_half -OpStore %out %old -OpReturn -OpFunctionEnd -""" - interp = LdsAtomicSpirvInterp(spvasm) - final_lds, lane_outs = interp.run(num_invocations=4, seed_lds={1: 0xFFFFFFFF}) - # First invocation got 0xFFFFFFFF, subsequent got 0x0000FFFF (65535) - self.assertEqual(lane_outs[0]["%out"], 0xFFFFFFFF) - for i in range(1, 4): - self.assertEqual(lane_outs[i]["%out"], 0x0000FFFF) - self.assertEqual(final_lds[1], 0x0000FFFF) - - def test_spirv_unaligned_byte_offset_access(self): - spvasm = """ -OpCapability Shader -OpMemoryModel Logical GLSL450 -OpEntryPoint GLCompute %main "main" %out -OpExecutionMode %main LocalSize 1 1 1 -%uint = OpTypeInt 32 0 -%_ptr_Output_uint = OpTypePointer Output %uint -%out = OpVariable %_ptr_Output_uint Output -%c16 = OpConstant %uint 16 -%c15 = OpConstant %uint 15 -%c2 = OpConstant %uint 2 -%c0 = OpConstant %uint 0 -%c_base = OpConstant %uint 60 -%c_offset = OpConstant %uint 16 -%c_mask = OpConstant %uint 2863311530 -%lds_arr = OpTypeArray %uint %c16 -%_ptr_WG_lds = OpTypePointer Workgroup %lds_arr -%_ptr_WG_uint = OpTypePointer Workgroup %uint -%lds = OpVariable %_ptr_WG_lds Workgroup -%void = OpTypeVoid -%fn = OpTypeFunction %void -%main = OpFunction %void None %fn -%entry = OpLabel -%s1 = OpIAdd %uint %c_base %c_offset -%i = OpShiftRightLogical %uint %s1 %c2 -%m = OpBitwiseAnd %uint %i %c15 -%ptr = OpAccessChain %_ptr_WG_uint %lds %m -%old = OpAtomicAnd %uint %ptr %c2 %c0 %c_mask -OpStore %out %old -OpReturn -OpFunctionEnd -""" - interp = LdsAtomicSpirvInterp(spvasm) - final_lds, lane_outs = interp.run(seed_lds={3: 0xFFFFFFFF}) - self.assertEqual(lane_outs[0]["%out"], 0xFFFFFFFF) - self.assertEqual(final_lds[3], 0xAAAAAAAA) - - -class TestLdsSemanticInterpreterB64(unittest.TestCase): - """Verifies 64-bit LDS atomic AND execution in multi-lane SIMD interpreter.""" - - def setUp(self): - self.interp = LdsSemanticInterpreter(lds_dwords=256, num_vgprs=64, num_lanes=32) - - def test_ds_and_b64_non_returning_mutates_both_dwords(self): - self.interp.set_lds_dword(10, 0x12345678) - self.interp.set_lds_dword(11, 0x9ABCDEF0) - self.interp.set_vgpr(0, 40) # byte 40 -> dword 10 - self.interp.set_vgpr(2, 0x000000FF) # data lo - self.interp.set_vgpr(3, 0x00FF0000) # data hi - self.interp.set_vgpr(4, 0xDEADBEEF) # dummy - - res = self.interp.ds_and_b64(vaddr_reg=0, vdata_lo_reg=2, offset=0, lane=0) - self.assertEqual(res, (10, 11)) - self.assertEqual(self.interp.get_lds_dword(10), 0x12345678 & 0x000000FF) - self.assertEqual(self.interp.get_lds_dword(11), 0x9ABCDEF0 & 0x00FF0000) - self.assertEqual(self.interp.get_vgpr(0), 40) - self.assertEqual(self.interp.get_vgpr(2), 0x000000FF) - self.assertEqual(self.interp.get_vgpr(3), 0x00FF0000) - self.assertEqual(self.interp.get_vgpr(4), 0xDEADBEEF) - - def test_ds_and_rtn_b64_returns_prior_64bit_value(self): - init_val = 0xCAFEBABE_DEADBEEF - mask_val = 0x0F0F0F0F_F0F0F0F0 - self.interp.set_lds_u64(12, init_val) - self.interp.set_vgpr(0, 48) # byte 48 -> dword 12 - self.interp.set_vgpr_u64(2, mask_val) - self.interp.set_vgpr_u64(4, 0) # vdst in v[4:5] - - res = self.interp.ds_and_rtn_b64(vdst_lo_reg=4, vaddr_reg=0, vdata_lo_reg=2, offset=0, lane=0) - self.assertEqual(res, (12, init_val)) - self.assertEqual(self.interp.get_vgpr_u64(4), init_val) - self.assertEqual(self.interp.get_lds_u64(12), init_val & mask_val) - - def test_ds_and_rtn_b64_with_offset(self): - init_val = 0x11112222_33334444 - mask_val = 0x55555555_AAAAAAAA - # vaddr = 32 (dword 8), offset = 24 bytes (6 dwords) -> target is dword 14 - self.interp.set_lds_u64(14, init_val) - self.interp.set_vgpr(0, 32) - self.interp.set_vgpr_u64(2, mask_val) - self.interp.set_vgpr_u64(6, 0) - - res = self.interp.ds_and_rtn_b64(vdst_lo_reg=6, vaddr_reg=0, vdata_lo_reg=2, offset=24, lane=0) - self.assertEqual(res, (14, init_val)) - self.assertEqual(self.interp.get_vgpr_u64(6), init_val) - self.assertEqual(self.interp.get_lds_u64(14), init_val & mask_val) - - def test_ds_and_rtn_b64_sequential_filter_chain(self): - init_val = 0xFFFFFFFF_FFFFFFFF - mask1 = 0xF0F0F0F0_0F0F0F0F - mask2 = 0x33333333_CCCCCCCC - self.interp.set_lds_u64(20, init_val) - self.interp.set_vgpr(0, 80) - self.interp.set_vgpr_u64(2, mask1) - - res1 = self.interp.ds_and_rtn_b64(vdst_lo_reg=4, vaddr_reg=0, vdata_lo_reg=2, offset=0, lane=0) - self.assertEqual(res1, (20, init_val)) - self.assertEqual(self.interp.get_vgpr_u64(4), init_val) - self.assertEqual(self.interp.get_lds_u64(20), init_val & mask1) - - self.interp.set_vgpr_u64(2, mask2) - res2 = self.interp.ds_and_rtn_b64(vdst_lo_reg=6, vaddr_reg=0, vdata_lo_reg=2, offset=0, lane=0) - self.assertEqual(res2, (20, init_val & mask1)) - self.assertEqual(self.interp.get_vgpr_u64(6), init_val & mask1) - self.assertEqual(self.interp.get_lds_u64(20), init_val & mask1 & mask2) - - def test_ds_and_rtn_b64_vdst_aliasing_vdata(self): - init_val = 0x88887777_66665555 - data_val = 0x11112222_33334444 - self.interp.set_lds_u64(16, init_val) - self.interp.set_vgpr(0, 64) - self.interp.set_vgpr_u64(2, data_val) - - # vdst is v[2:3], which aliases vdata in v[2:3] - res = self.interp.ds_and_rtn_b64(vdst_lo_reg=2, vaddr_reg=0, vdata_lo_reg=2, lane=0) - self.assertEqual(res, (16, init_val)) - self.assertEqual(self.interp.get_lds_u64(16), init_val & data_val) - self.assertEqual(self.interp.get_vgpr_u64(2), init_val) - - def test_ds_and_rtn_b64_vdst_aliasing_vaddr(self): - init_val = 0xAAAABBBB_CCCCDDDD - data_val = 0x0000FFFF_0000FFFF - self.interp.set_lds_u64(18, init_val) - self.interp.set_vgpr(0, 72) - self.interp.set_vgpr_u64(2, data_val) - - # vdst is v[0:1], aliasing vaddr in v0 - res = self.interp.ds_and_rtn_b64(vdst_lo_reg=0, vaddr_reg=0, vdata_lo_reg=2, lane=0) - self.assertEqual(res, (18, init_val)) - self.assertEqual(self.interp.get_lds_u64(18), init_val & data_val) - self.assertEqual(self.interp.get_vgpr_u64(0), init_val) - - def test_ds_and_b64_inactive_lane_under_exec_mask(self): - self.interp.set_lds_u64(4, 0x12345678_9ABCDEF0) - self.interp.set_vgpr(0, 16, lane=2) - self.interp.set_vgpr_u64(2, 0, lane=2) - self.interp.set_vgpr_u64(4, 0xFEEDFACE_CAFEBABE, lane=2) - self.interp.set_lane_active(2, False) - - res = self.interp.ds_and_rtn_b64(vdst_lo_reg=4, vaddr_reg=0, vdata_lo_reg=2, lane=2) - self.assertIsNone(res) - self.assertEqual(self.interp.get_vgpr_u64(4, lane=2), 0xFEEDFACE_CAFEBABE) - self.assertEqual(self.interp.get_lds_u64(4), 0x12345678_9ABCDEF0) - - def test_ds_and_rtn_b64_simd_wave_divergent(self): - # 32 lanes, each lane targeting its own 64-bit element - for lane in range(32): - val = (0x1000_0000_0000 + lane * 0x1_0000_0001) & MASK64 - self.interp.set_lds_u64(lane * 2, val) - self.interp.set_vgpr(0, lane * 8, lane=lane) - self.interp.set_vgpr_u64(2, 0x00FF00FF_00FF00FF, lane=lane) - self.interp.set_vgpr_u64(4, 0, lane=lane) - - for lane in range(32): - self.interp.ds_and_rtn_b64(vdst_lo_reg=4, vaddr_reg=0, vdata_lo_reg=2, offset=0, lane=lane) - - for lane in range(32): - orig_val = (0x1000_0000_0000 + lane * 0x1_0000_0001) & MASK64 - self.assertEqual(self.interp.get_vgpr_u64(4, lane=lane), orig_val) - self.assertEqual(self.interp.get_lds_u64(lane * 2), orig_val & 0x00FF00FF_00FF00FF) - - def test_ds_and_rtn_b64_simd_wave_convergent_shared_word(self): - # 32 lanes all targeting dword 30 (64-bit), each clearing bit lane and bit lane + 32 - self.interp.set_lds_u64(30, MASK64) - for lane in range(32): - self.interp.set_vgpr(0, 120, lane=lane) # byte 120 -> dword 30 - mask_64 = ~((1 << lane) | (1 << (lane + 32))) & MASK64 - self.interp.set_vgpr_u64(2, mask_64, lane=lane) - self.interp.set_vgpr_u64(4, 0, lane=lane) - - for lane in range(32): - self.interp.ds_and_rtn_b64(vdst_lo_reg=4, vaddr_reg=0, vdata_lo_reg=2, offset=0, lane=lane) - - self.assertEqual(self.interp.get_lds_u64(30), 0) - - def test_assembly_parser_dispatch_b64(self): - self.interp.set_lds_u64(8, 0xFFFFFFFF_FFFFFFFF) - self.interp.set_vgpr(0, 32) - self.interp.set_vgpr_u64(2, 0x55555555_AAAAAAAA) - - self.interp.parse_and_execute("ds_and_b64 v0, v[2:3] offset:0") - self.assertEqual(self.interp.get_lds_u64(8), 0x55555555_AAAAAAAA) - - self.interp.set_vgpr_u64(4, 0) - self.interp.parse_and_execute("ds_and_rtn_b64 v[4:5], v0, v[2:3] offset:0") - self.assertEqual(self.interp.get_vgpr_u64(4), 0x55555555_AAAAAAAA) - self.assertEqual(self.interp.get_lds_u64(8), 0x55555555_AAAAAAAA) - - # Test ds_write_b64 and ds_read_b64 through parser - self.interp.set_vgpr_u64(6, 0xCAFEBABE_12345678) - self.interp.parse_and_execute("ds_write_b64 v0, v[6:7] offset:8") - self.assertEqual(self.interp.get_lds_u64(10), 0xCAFEBABE_12345678) - - self.interp.set_vgpr_u64(8, 0) - self.interp.parse_and_execute("ds_read_b64 v[8:9], v0 offset:8") - self.assertEqual(self.interp.get_vgpr_u64(8), 0xCAFEBABE_12345678) - - def test_run_simd_wave_b64_with_exec_mask(self): - # Lanes 0..3 active (0x0F), lanes 4..7 inactive - self.interp.set_exec_mask(0x0F) - for lane in range(8): - self.interp.set_lds_u64(lane * 2, MASK64) - self.interp.set_vgpr(0, lane * 8, lane=lane) - self.interp.set_vgpr_u64(2, 0xFFFFFFFF_00000000, lane=lane) - self.interp.set_vgpr_u64(4, 0x55555555_55555555, lane=lane) - - results = self.interp.run_simd_wave("ds_and_rtn_b64 v[4:5], v0, v[2:3]") - for lane in range(4): - self.assertIsNotNone(results[lane]) - self.assertEqual(self.interp.get_vgpr_u64(4, lane=lane), MASK64) - self.assertEqual(self.interp.get_lds_u64(lane * 2), 0xFFFFFFFF_00000000) - for lane in range(4, 8): - self.assertIsNone(results[lane]) - self.assertEqual(self.interp.get_vgpr_u64(4, lane=lane), 0x55555555_55555555) - self.assertEqual(self.interp.get_lds_u64(lane * 2), MASK64) - - -class Test64BitAlignmentBoundariesAndWrapping(unittest.TestCase): - """Verifies 64-bit alignment boundaries, dual-dword spans, and power-of-two wrapping.""" - - def test_aligned_8byte_addressing(self): - interp = LdsSemanticInterpreter(lds_dwords=128, num_vgprs=16, num_lanes=1) - for dword_base in (0, 2, 4, 16, 64, 126): - byte_addr = dword_base * 4 - self.assertEqual(byte_addr % 8, 0) - interp.set_lds_u64(dword_base, 0xAAAAAAAA_55555555) - interp.set_vgpr(0, byte_addr) - interp.set_vgpr_u64(2, 0xFFFFFFFF_00000000) - res = interp.ds_and_rtn_b64(vdst_lo_reg=4, vaddr_reg=0, vdata_lo_reg=2, lane=0) - self.assertEqual(res, (dword_base, 0xAAAAAAAA_55555555)) - self.assertEqual(interp.get_lds_u64(dword_base), 0xAAAAAAAA_00000000) - - def test_unaligned_4byte_dword_boundary(self): - interp = LdsSemanticInterpreter(lds_dwords=128, num_vgprs=16, num_lanes=1) - # Byte address 20 -> dword 5 (odd dword index, not 8-byte aligned) - # 64-bit element spans dword 5 and dword 6 - interp.set_lds_dword(5, 0x12345678) - interp.set_lds_dword(6, 0x9ABCDEF0) - interp.set_vgpr(0, 20) - interp.set_vgpr(2, 0x000000FF) - interp.set_vgpr(3, 0x00FF0000) - res = interp.ds_and_rtn_b64(vdst_lo_reg=4, vaddr_reg=0, vdata_lo_reg=2, lane=0) - self.assertEqual(res, (5, combine_u32_to_u64(0x12345678, 0x9ABCDEF0))) - self.assertEqual(interp.get_lds_dword(5), 0x12345678 & 0x000000FF) - self.assertEqual(interp.get_lds_dword(6), 0x9ABCDEF0 & 0x00FF0000) - - def test_unaligned_byte_offset_truncation(self): - interp = LdsSemanticInterpreter(lds_dwords=64, num_vgprs=16, num_lanes=1) - # Byte offsets 16, 17, 18, 19 all truncate to dword 4 (and 5) - for byte_off in (16, 17, 18, 19): - interp.set_lds_dword(4, 0xFFFFFFFF) - interp.set_lds_dword(5, 0xFFFFFFFF) - interp.set_vgpr(0, byte_off) - interp.set_vgpr(2, 0xF0F0F0F0) - interp.set_vgpr(3, 0x0F0F0F0F) - res = interp.ds_and_b64(vaddr_reg=0, vdata_lo_reg=2, lane=0) - self.assertEqual(res, (4, 5)) - self.assertEqual(interp.get_lds_dword(4), 0xF0F0F0F0) - self.assertEqual(interp.get_lds_dword(5), 0x0F0F0F0F) - - def test_64bit_boundary_crossing_wrap(self): - interp = LdsSemanticInterpreter(lds_dwords=64, num_vgprs=16, num_lanes=1) - # LDS has 64 dwords (indices 0..63). - # A 64-bit element at dword 63 spans dword 63 and dword (63+1)%64 = 0. - interp.set_lds_dword(63, 0xFFFFFFFF) - interp.set_lds_dword(0, 0xFFFFFFFF) - interp.set_vgpr(0, 63 * 4) # byte address 252 -> dword 63 - interp.set_vgpr(2, 0xF0F0F0F0) - interp.set_vgpr(3, 0x0F0F0F0F) - interp.set_vgpr_u64(4, 0) - - res = interp.ds_and_rtn_b64(vdst_lo_reg=4, vaddr_reg=0, vdata_lo_reg=2, offset=0, lane=0) - self.assertEqual(res, (63, combine_u32_to_u64(0xFFFFFFFF, 0xFFFFFFFF))) - self.assertEqual(interp.get_vgpr(4), 0xFFFFFFFF) - self.assertEqual(interp.get_vgpr(5), 0xFFFFFFFF) - self.assertEqual(interp.get_lds_dword(63), 0xF0F0F0F0) - self.assertEqual(interp.get_lds_dword(0), 0x0F0F0F0F) - - def test_large_offset_overflow_wrap(self): - interp = LdsSemanticInterpreter(lds_dwords=128, num_vgprs=16, num_lanes=1) - # 32-bit unsigned wrapping: 0xFFFFFFFC + 8 = 0x00000004 -> dword 1 - interp.set_lds_dword(1, 0xFFFFFFFF) - interp.set_lds_dword(2, 0xFFFFFFFF) - interp.set_vgpr(0, 0xFFFFFFFC) - interp.set_vgpr(2, 0x000000FF) - interp.set_vgpr(3, 0x00FF0000) - - interp.ds_and_b64(vaddr_reg=0, vdata_lo_reg=2, offset=8, lane=0) - self.assertEqual(interp.get_lds_dword(1), 0x000000FF) - self.assertEqual(interp.get_lds_dword(2), 0x00FF0000) - - def test_calc_dual_offsets_st64_math(self): - (eff0, idx0), (eff1, idx1) = calc_lds_dual_offsets(0x100, 4, 8, lds_dwords=512, st64=False) - self.assertEqual(eff0, 0x100 + 16) - self.assertEqual(idx0, (0x100 + 16) >> 2) - self.assertEqual(eff1, 0x100 + 32) - self.assertEqual(idx1, (0x100 + 32) >> 2) - - (eff0_st, idx0_st), (eff1_st, idx1_st) = calc_lds_dual_offsets(0x100, 1, 2, lds_dwords=512, st64=True) - self.assertEqual(eff0_st, 0x100 + 256) - self.assertEqual(idx0_st, (0x100 + 256) >> 2) - self.assertEqual(eff1_st, 0x100 + 512) - self.assertEqual(idx1_st, (0x100 + 512) >> 2) - - def test_dual_offset_wrapping_power_of_two(self): - lds_dwords = 32 # 128 bytes total - (eff0, idx0), (eff1, idx1) = calc_lds_dual_offsets(0, 32, 33, lds_dwords=lds_dwords, st64=False) - self.assertEqual(idx0, 0) - self.assertEqual(idx1, 1) - - -class TestReturnValueRetention(unittest.TestCase): - """Verifies that non-returning forms do not modify destination registers and returning forms retain old values.""" - - def test_non_returning_forms_preserve_vdst_sentinel(self): - interp = LdsSemanticInterpreter(lds_dwords=64, num_vgprs=16, num_lanes=1) - interp.set_lds_dword(0, 0xFFFFFFFF) - interp.set_lds_dword(1, 0xFFFFFFFF) - interp.set_vgpr(0, 0) - interp.set_vgpr(1, 0x12345678) - interp.set_vgpr(2, 0x9ABCDEF0) - interp.set_vgpr(10, 0xDEADBEEF) - interp.set_vgpr(11, 0xCAFEBABE) - - interp.ds_and_b32(vaddr_reg=0, vdata_reg=1, lane=0) - self.assertEqual(interp.get_vgpr(10), 0xDEADBEEF) - - interp.ds_and_b64(vaddr_reg=0, vdata_lo_reg=1, lane=0) - self.assertEqual(interp.get_vgpr(10), 0xDEADBEEF) - self.assertEqual(interp.get_vgpr(11), 0xCAFEBABE) - - def test_returning_forms_capture_exact_old_values(self): - interp = LdsSemanticInterpreter(lds_dwords=64, num_vgprs=16, num_lanes=1) - interp.set_lds_dword(5, 0x5555AAAA) - interp.set_vgpr(0, 20) - interp.set_vgpr(1, 0x0F0F0F0F) - interp.set_vgpr(5, 0) - - res = interp.ds_and_rtn_b32(vdst_reg=5, vaddr_reg=0, vdata_reg=1, lane=0) - self.assertEqual(res, (5, 0x5555AAAA)) - self.assertEqual(interp.get_vgpr(5), 0x5555AAAA) - self.assertEqual(interp.get_lds_dword(5), 0x5555AAAA & 0x0F0F0F0F) - - def test_sequential_and_return_chain(self): - interp = LdsSemanticInterpreter(lds_dwords=64, num_vgprs=16, num_lanes=1) - interp.set_lds_dword(2, 0xFFFFFFFF) - interp.set_vgpr(0, 8) - - # Step 1: mask 0xF0F0F0F0 -> returns 0xFFFFFFFF, memory becomes 0xF0F0F0F0 - interp.set_vgpr(1, 0xF0F0F0F0) - res1 = interp.ds_and_rtn_b32(vdst_reg=3, vaddr_reg=0, vdata_reg=1, lane=0) - self.assertEqual(res1, (2, 0xFFFFFFFF)) - self.assertEqual(interp.get_vgpr(3), 0xFFFFFFFF) - self.assertEqual(interp.get_lds_dword(2), 0xF0F0F0F0) - - # Step 2: mask 0x33333333 -> returns 0xF0F0F0F0, memory becomes 0x30303030 - interp.set_vgpr(1, 0x33333333) - res2 = interp.ds_and_rtn_b32(vdst_reg=4, vaddr_reg=0, vdata_reg=1, lane=0) - self.assertEqual(res2, (2, 0xF0F0F0F0)) - self.assertEqual(interp.get_vgpr(4), 0xF0F0F0F0) - self.assertEqual(interp.get_lds_dword(2), 0x30303030) - - # Step 3: mask 0x0F0F0F0F -> returns 0x30303030, memory becomes 0x00000000 - interp.set_vgpr(1, 0x0F0F0F0F) - res3 = interp.ds_and_rtn_b32(vdst_reg=5, vaddr_reg=0, vdata_reg=1, lane=0) - self.assertEqual(res3, (2, 0x30303030)) - self.assertEqual(interp.get_vgpr(5), 0x30303030) - self.assertEqual(interp.get_lds_dword(2), 0x00000000) - - -class TestTranslatorIntegration(unittest.TestCase): - """Verifies that tools/rdna2spirv.py emits conforming SPIR-V for ds_and_b32, ds_and_rtn_b32, and b64 forms.""" - - def _make_mock_gen(self, stage: str = "cs"): - class MockGen: - def __init__(self): - self.stage = stage - self.uses_lds = False - self.lds_dwords = 256 - self.lds_bound = None # not bounds-checked (SHADER-309) - self.wave64 = True - self._tmp = 0 - self.emitted: list[str] = [] - self.stored_dsts: list[tuple[dict, str]] = [] - - def tmp(self): - self._tmp += 1 - return f"%t{self._tmp}" - - def cu(self, v): - return f"%c{v}" - - def active_b(self): - return "%exec_active" - - def src_u(self, arg): - return f"%v_{arg['r']}" - - def dst(self, d, v): - self.stored_dsts.append((d, v)) - - def emit(self, line): - self.emitted.append(line) - - def load_reg(self, kind, r): - return f"%v_{r}" - - LDS_ATOMICS = rdna2spirv.Gen.LDS_ATOMICS - mod_int = staticmethod(rdna2spirv.Gen.mod_int) - lds_ptr = rdna2spirv.Gen.lds_ptr - lds_access = rdna2spirv.Gen.lds_access - lds_atomic = rdna2spirv.Gen.lds_atomic - lds_op = rdna2spirv.Gen.lds_op - - return MockGen() - - def test_lds_atomics_table_contains_ds_and(self): - self.assertIn("ds_and_b32", rdna2spirv.Gen.LDS_ATOMICS) - self.assertEqual(rdna2spirv.Gen.LDS_ATOMICS["ds_and_b32"], "OpAtomicAnd") - - def test_ds_and_b32_non_returning_emission(self): - gen = self._make_mock_gen(stage="cs") - gen.lds_op("ds_and_b32", [{"r": 0}, {"r": 1}], ["offset:8"]) - self.assertTrue(gen.uses_lds) - emitted_str = "\n".join(gen.emitted) - - self.assertIn("OpBranchConditional %exec_active", emitted_str) - self.assertIn("OpIAdd %uint %v_0 %c8", emitted_str) - self.assertIn("OpShiftRightLogical %uint", emitted_str) - self.assertIn("OpBitwiseAnd %uint", emitted_str) - self.assertIn("OpAccessChain %_ptr_WG_uint %lds", emitted_str) - self.assertIn("OpAtomicAnd %uint", emitted_str) - self.assertIn("%c2 %c0 %v_1", emitted_str) - self.assertEqual(len(gen.stored_dsts), 0) - - def test_ds_and_rtn_b32_returning_emission(self): - gen = self._make_mock_gen(stage="cs") - gen.lds_op("ds_and_rtn_b32", [{"r": 5}, {"r": 0}, {"r": 1}], ["offset:12"]) - self.assertTrue(gen.uses_lds) - emitted_str = "\n".join(gen.emitted) - - self.assertIn("OpAtomicAnd %uint", emitted_str) - self.assertIn("%c2 %c0 %v_1", emitted_str) - self.assertEqual(len(gen.stored_dsts), 1) - dest_reg, val_id = gen.stored_dsts[0] - self.assertEqual(dest_reg["r"], 5) - self.assertTrue(val_id.startswith("%t")) - - def test_ds_and_b64_emission(self): - gen = self._make_mock_gen(stage="cs") - gen.lds_op("ds_and_b64", [{"r": 0}, {"r": 2, "n": 2, "k": "vgpr"}], ["offset:16"]) - self.assertTrue(gen.uses_lds) - emitted_str = "\n".join(gen.emitted) - - # Emits two 32-bit OpAtomicAnd instructions - atomic_lines = [ln for ln in gen.emitted if "OpAtomicAnd" in ln] - self.assertEqual(len(atomic_lines), 2) - self.assertEqual(len(gen.stored_dsts), 0) - - def test_ds_and_rtn_b64_emission(self): - gen = self._make_mock_gen(stage="cs") - gen.lds_op( - "ds_and_rtn_b64", - [{"r": 6, "n": 2, "k": "vgpr"}, {"r": 0}, {"r": 2, "n": 2, "k": "vgpr"}], - ["offset:0"], - ) - self.assertTrue(gen.uses_lds) - atomic_lines = [ln for ln in gen.emitted if "OpAtomicAnd" in ln] - self.assertEqual(len(atomic_lines), 2) - # Stores two registers: v6 and v7 - self.assertEqual(len(gen.stored_dsts), 2) - self.assertEqual(gen.stored_dsts[0][0]["r"], 6) - self.assertEqual(gen.stored_dsts[1][0]["r"], 7) - - -class TestSpirvAtomicAndB64Emission(unittest.TestCase): - """Verifies that 64-bit LDS atomic AND translates to conforming SPIR-V and executes correctly.""" - - def test_rdna2spirv_translate_b64_emission(self): - spv = translate_cs_listing([ - "ds_and_b64 v0, v[2:3]", - "ds_and_rtn_b64 v[4:5], v0, v[2:3] offset:16", - ]) - lines = [ln.strip() for ln in spv.splitlines() if "OpAtomicAnd" in ln] - self.assertEqual(len(lines), 4) - for ln in lines: - self.assertIn("OpAtomicAnd", ln) - self.assertIn("%uint", ln) - self.assertIn("%c2", ln) - self.assertIn("%c0", ln) - - def test_spirv_sequential_atomics_emulating_b64(self): - spvasm = """ -OpCapability Shader -OpMemoryModel Logical GLSL450 -OpEntryPoint GLCompute %main "main" %out_lo %out_hi -OpExecutionMode %main LocalSize 1 1 1 -%uint = OpTypeInt 32 0 -%c64 = OpConstant %uint 64 -%c2 = OpConstant %uint 2 -%c0 = OpConstant %uint 0 -%c10 = OpConstant %uint 10 -%c11 = OpConstant %uint 11 -%c_mask_lo = OpConstant %uint 3735928559 -%c_mask_hi = OpConstant %uint 3405691582 -%lds_arr = OpTypeArray %uint %c64 -%_ptr_WG_lds = OpTypePointer Workgroup %lds_arr -%_ptr_WG_uint = OpTypePointer Workgroup %uint -%_ptr_Out_uint = OpTypePointer Output %uint -%lds = OpVariable %_ptr_WG_lds Workgroup -%out_lo = OpVariable %_ptr_Out_uint Output -%out_hi = OpVariable %_ptr_Out_uint Output -%void = OpTypeVoid -%fn = OpTypeFunction %void -%main = OpFunction %void None %fn -%entry = OpLabel -%ptr_lo = OpAccessChain %_ptr_WG_uint %lds %c10 -%ptr_hi = OpAccessChain %_ptr_WG_uint %lds %c11 -%old_lo = OpAtomicAnd %uint %ptr_lo %c2 %c0 %c_mask_lo -%old_hi = OpAtomicAnd %uint %ptr_hi %c2 %c0 %c_mask_hi -OpStore %out_lo %old_lo -OpStore %out_hi %old_hi -OpReturn -OpFunctionEnd -""" - interp = LdsAtomicSpirvInterp(spvasm) - init_lo = 0xFFFFFFFF - init_hi = 0xFFFFFFFF - final_lds, lane_outputs = interp.run(seed_lds={10: init_lo, 11: init_hi}) - self.assertEqual(lane_outputs[0]["%out_lo"], init_lo) - self.assertEqual(lane_outputs[0]["%out_hi"], init_hi) - self.assertEqual(final_lds[10], 3735928559) - self.assertEqual(final_lds[11], 3405691582) - - -class TestNegativeControlsAndBounds(unittest.TestCase): - """Verifies that invalid operands, unmodelled opcodes, bad stages, and bound violations fail safely.""" - - def test_rdna2spirv_invalid_operand_shape_rejected(self): - with self.assertRaises(rdna2spirv.Unsupported): - translate_cs_listing(["ds_and_b64 v0, v1"]) - - def test_rdna2spirv_invalid_rtn_destination_shape_rejected(self): - with self.assertRaises(rdna2spirv.Unsupported): - translate_cs_listing(["ds_and_rtn_b64 v4, v0, v[2:3]"]) - - def test_rdna2spirv_non_compute_stage_rejected(self): - class MockPixelGen: - def __init__(self): - self.stage = "ps" - self.uses_lds = False - - lds_op = rdna2spirv.Gen.lds_op - - gen = MockPixelGen() - with self.assertRaises(rdna2spirv.Unsupported): - gen.lds_op("ds_and_b32", [{"r": 0}, {"r": 1}], []) - with self.assertRaises(rdna2spirv.Unsupported): - gen.lds_op("ds_and_b64", [{"r": 0}, {"r": 1, "n": 2, "k": "vgpr"}], []) - - def test_spirv_unsupported_storage_class(self): - spvasm = """ -OpCapability Shader -OpMemoryModel Logical GLSL450 -OpEntryPoint GLCompute %main "main" -OpExecutionMode %main LocalSize 1 1 1 -%uint = OpTypeInt 32 0 -%_ptr_UC = OpTypePointer UniformConstant %uint -%u = OpVariable %_ptr_UC UniformConstant -%void = OpTypeVoid -%fn = OpTypeFunction %void -%main = OpFunction %void None %fn -%entry = OpLabel -OpReturn -OpFunctionEnd -""" - with self.assertRaises(UnsupportedConstruct): - LdsAtomicSpirvInterp(spvasm) - - def test_spirv_unsupported_opcode_in_body(self): - spvasm = """ -OpCapability Shader -OpMemoryModel Logical GLSL450 -OpEntryPoint GLCompute %main "main" -OpExecutionMode %main LocalSize 1 1 1 -%uint = OpTypeInt 32 0 -%c10 = OpConstant %uint 10 -%void = OpTypeVoid -%fn = OpTypeFunction %void -%main = OpFunction %void None %fn -%entry = OpLabel -%bad = OpSDiv %uint %c10 %c10 -OpReturn -OpFunctionEnd -""" - interp = LdsAtomicSpirvInterp(spvasm) - with self.assertRaises(UnsupportedConstruct): - interp.run() - - def test_spirv_invalid_workgroup_local_sizes(self): - for bad_dims in [(0, 1, 1), (1025, 1, 1), (33, 32, 1)]: - with self.subTest(dims=bad_dims): - spvasm = f""" -OpCapability Shader -OpMemoryModel Logical GLSL450 -OpEntryPoint GLCompute %main "main" -OpExecutionMode %main LocalSize {bad_dims[0]} {bad_dims[1]} {bad_dims[2]} -%void = OpTypeVoid -%fn = OpTypeFunction %void -%main = OpFunction %void None %fn -%entry = OpLabel -OpReturn -OpFunctionEnd -""" - with self.assertRaises(WorkgroupBoundsError): - LdsAtomicSpirvInterp(spvasm) - - def test_spirv_atomic_on_non_lds_pointer(self): - spvasm = """ -OpCapability Shader -OpMemoryModel Logical GLSL450 -OpEntryPoint GLCompute %main "main" -OpExecutionMode %main LocalSize 1 1 1 -%uint = OpTypeInt 32 0 -%_ptr_fn_uint = OpTypePointer Function %uint -%c2 = OpConstant %uint 2 -%c0 = OpConstant %uint 0 -%c5 = OpConstant %uint 5 -%void = OpTypeVoid -%fn = OpTypeFunction %void -%main = OpFunction %void None %fn -%entry = OpLabel -%local_v = OpVariable %_ptr_fn_uint Function -%bad = OpAtomicAnd %uint %local_v %c2 %c0 %c5 -OpReturn -OpFunctionEnd -""" - interp = LdsAtomicSpirvInterp(spvasm) - with self.assertRaises(UnsupportedConstruct): - interp.run() - - def test_spirv_lds_access_out_of_bounds_rejected(self): - spvasm = """ -OpCapability Shader -OpMemoryModel Logical GLSL450 -OpEntryPoint GLCompute %main "main" -OpExecutionMode %main LocalSize 1 1 1 -%uint = OpTypeInt 32 0 -%c8 = OpConstant %uint 8 -%c2 = OpConstant %uint 2 -%c0 = OpConstant %uint 0 -%c20 = OpConstant %uint 20 -%c5 = OpConstant %uint 5 -%lds_arr = OpTypeArray %uint %c8 -%_ptr_WG_lds = OpTypePointer Workgroup %lds_arr -%_ptr_WG_uint = OpTypePointer Workgroup %uint -%lds = OpVariable %_ptr_WG_lds Workgroup -%void = OpTypeVoid -%fn = OpTypeFunction %void -%main = OpFunction %void None %fn -%entry = OpLabel -%ptr = OpAccessChain %_ptr_WG_uint %lds %c20 -%bad = OpAtomicAnd %uint %ptr %c2 %c0 %c5 -OpReturn -OpFunctionEnd -""" - interp = LdsAtomicSpirvInterp(spvasm) - with self.assertRaises(WorkgroupBoundsError): - interp.run() - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_lds_atomic_minmax.py b/tests/semantic/test_lds_atomic_minmax.py deleted file mode 100644 index 3c5cd3460..000000000 --- a/tests/semantic/test_lds_atomic_minmax.py +++ /dev/null @@ -1,101 +0,0 @@ -"""ds_min_u32, ds_max_u32, ds_min_i32, ds_max_i32 (and their _rtn_ forms) through the translator. - -Standard library only; no GPU, no LLVM, no game files. - -RDNA2 ISA, "Data Share Instructions": the atomic M = min(M, D) or max(M, D) on the dword at (vaddr + offset) / 4, -comparing as unsigned (_u32) or two's-complement signed (_i32); the _rtn_ form also returns the old M in vdst, the -plain form leaves vdst alone. The two comparisons differ exactly when the operands differ in bit 31: 0x80000000 is the -largest signed-negative and the 2^31-th unsigned value. - -Each case is a compute shader translated by tools/rdna2spirv.py (support.translate_lines) and run in -tests/semantic/spirv_mini_interp.py (one lane: that interpreter does not share LDS between lanes, see lds_run.py). -It writes a few LDS dwords, runs a sequence of atomics and stores each returned value and the final dwords. The -tables are written out by hand; seeded random sequences are checked against a plain-Python LDS. Until this file, the -LDS tests of this name ran a self-built interpreter that checked only the shape of the SPIR-V. -""" -import os -import random -import sys -import unittest - -sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) -import lds_run as L # noqa: E402 (also puts tools/ on sys.path) - -M32 = L.M32 - - -def s32(x): - return x - (1 << 32) if x >> 31 else x - - -FN = {"min_u32": min, "max_u32": max, - "min_i32": lambda m, d: m if s32(m) <= s32(d) else d, "max_i32": lambda m, d: m if s32(m) >= s32(d) else d} - - -def model(ops, init): - lds = dict(init) - rtns = [] - for name, addr, off, (d,) in ops: - a = addr + off - rtns.append(lds[a] if "_rtn_" in name else 0xDEAD) - lds[a] = FN[name.replace("_rtn_", "_")[3:]](lds[a], d) - return rtns, {a: lds[a] for a in sorted({addr + off for _, addr, off, _ in ops})} - - -class TestHandTable(unittest.TestCase): - # M D min_u max_u min_i max_i - TABLE = ((0, 0, 0, 0, 0, 0), - (1, 2, 1, 2, 1, 2), - (5, 3, 3, 5, 3, 5), - (0x7FFFFFFF, 0x80000000, 0x7FFFFFFF, 0x80000000, 0x80000000, 0x7FFFFFFF), - (0x80000000, 0x7FFFFFFF, 0x7FFFFFFF, 0x80000000, 0x80000000, 0x7FFFFFFF), - (0xFFFFFFFF, 0, 0, 0xFFFFFFFF, 0xFFFFFFFF, 0), - (0xFFFFFFFF, 1, 1, 0xFFFFFFFF, 0xFFFFFFFF, 1), - (0x80000000, 0x80000001, 0x80000000, 0x80000001, 0x80000000, 0x80000001), - (7, 7, 7, 7, 7, 7)) - - def test_one_operation(self): - for m, d, *want in self.TABLE: - for kind, w in zip(("min_u32", "max_u32", "min_i32", "max_i32"), want): - for rtn in (True, False): - name = f"ds_{kind[:3]}_rtn_{kind[4:]}" if rtn else f"ds_{kind}" - with self.subTest(op=name, m=hex(m), d=hex(d)): - rtns, fin = L.run_chain([(name, 0x40, 0, (d,))], {0x40: m}) - self.assertEqual((rtns, fin), ([m if rtn else 0xDEAD], {0x40: w})) - - def test_signed_and_unsigned_diverge_on_the_same_operands(self): - ops = [("ds_min_rtn_u32", 0x10, 0, (0x80000000,)), ("ds_min_rtn_i32", 0x14, 0, (0x80000000,))] - rtns, fin = L.run_chain(ops, {0x10: 1, 0x14: 1}) - self.assertEqual(rtns, [1, 1]) - self.assertEqual(fin, {0x10: 1, 0x14: 0x80000000}) - - def test_offset_adds_to_the_address_in_bytes(self): - rtns, fin = L.run_chain([("ds_max_rtn_u32", 0x20, 0x24, (9,))], {0x44: 4, 0x40: 100}) - self.assertEqual((rtns, fin), ([4], {0x44: 9})) - - def test_running_reduction_in_program_order(self): - # min of 50, 20, 70, 20, 5 into one dword starting at 100: each _rtn_ shows the minimum so far. - ops = [("ds_min_rtn_u32", 8, 0, (d,)) for d in (50, 20, 70, 20, 5)] - self.assertEqual(L.run_chain(ops, {8: 100}), ([100, 50, 20, 20, 20], {8: 5})) - - -class TestSeeded(unittest.TestCase): - def test_random_sequences(self): - rng = random.Random(0x3141) - edge = (0, 1, 0x7FFFFFFF, 0x80000000, 0x80000001, 0xFFFFFFFF) - for trial in range(8): - addrs = [0x10, 0x30, 0x7C, 0x100] - init = {a: rng.choice((rng.getrandbits(32), *edge)) for a in addrs} - ops = [] - for _ in range(12): - kind = rng.choice(tuple(FN)) - name = f"ds_{kind[:3]}_rtn_{kind[4:]}" if rng.random() < 0.6 else f"ds_{kind}" - eff = rng.choice(addrs) - off = rng.choice((0, 0, 0x10, 0x20)) - ops.append((name, eff - off, off, (rng.choice((rng.getrandbits(32), *edge)),))) - with self.subTest(trial=trial): - self.assertEqual(L.run_chain(ops, init), model(ops, init)) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_lds_atomic_or.py b/tests/semantic/test_lds_atomic_or.py deleted file mode 100644 index 35e353bd0..000000000 --- a/tests/semantic/test_lds_atomic_or.py +++ /dev/null @@ -1,1752 +0,0 @@ -"""Semantic interpreter tests for LDS atomic bitwise OR operations (ds_or_b32, ds_or_rtn_b32, ds_or_b64, ds_or_rtn_b64). - -Standard library only; no GPU, no LLVM, no external tools, no game files. - -Run directly: - python -I tests/semantic/test_lds_atomic_or.py -Or via unittest discovery: - python -m unittest discover -s tests/semantic -v - -Background & Specification Rules: - * AMD RDNA2 / GFX10 Local Data Share (LDS) Architecture: - - LDS is an on-chip, software-managed scratchpad memory shared across - all work-items (threads/lanes) in a workgroup. - - Single 32-bit Atomic OR: - - `ds_or_b32 vaddr, vdata [offset:N]`: - Non-returning form: - eff_byte = (vaddr + offset) & 0xFFFFFFFF - dword_idx = (eff_byte >> 2) & (lds_dwords - 1) - LDS[dword_idx] = (LDS[dword_idx] | vdata) & 0xFFFFFFFF - The pre-atomic memory contents are discarded. - - `ds_or_rtn_b32 vdst, vaddr, vdata [offset:N]`: - Returning form: - eff_byte = (vaddr + offset) & 0xFFFFFFFF - dword_idx = (eff_byte >> 2) & (lds_dwords - 1) - old_val = LDS[dword_idx] - LDS[dword_idx] = (old_val | vdata) & 0xFFFFFFFF - vdst = old_val - Preserves the old value before the OR into destination VGPR vdst. - - 64-bit Atomic OR: - - `ds_or_b64 vaddr, v[data_lo:data_hi] [offset:N]`: - Non-returning 64-bit bitwise OR on two consecutive 32-bit dwords (low dword first): - eff_byte = (vaddr + offset) & 0xFFFFFFFF - dword_idx = (eff_byte >> 2) & (lds_dwords - 1) - LDS[dword_idx] |= vdata_lo - LDS[dword_idx+1] |= vdata_hi - - `ds_or_rtn_b64 v[dst_lo:dst_hi], vaddr, v[data_lo:data_hi] [offset:N]`: - Returning form: writes prior 64 bits into destination VGPR pair v[dst_lo:dst_hi]. - - Active lane masking: - - LDS instructions are vector operations governed by the execution mask (EXEC). - - Inactive lanes do not mutate LDS storage and leave destination VGPRs unmodified. - - Hardware wrapping & alignment: - - Byte addresses are shifted right by 2, dropping unaligned low bits [1:0]. - - The resulting dword index is masked with (lds_dwords - 1), wrapping out-of-bounds - offsets within the allocated power-of-two LDS capacity. - - Mathematical properties of bitwise OR: - - Identity: x | 0 == x. - - Dominant / Saturation element: x | 0xFFFFFFFF == 0xFFFFFFFF. - - Idempotence: x | x == x. - - Commutative & Associative: (x | y) == (y | x), (x | y) | z == x | (y | z). - - Monotonicity: (x | y) & x == x (bits only transition 0 -> 1, never 1 -> 0). - - Bitmask union: fundamental for flag aggregation, multi-lane barrier signals, - and sparse occupancy tracking. -""" -from __future__ import annotations - -import os -import re -import struct -import sys -import tempfile -import unittest -import warnings - -HERE = os.path.dirname(os.path.abspath(__file__)) -ROOT = os.path.dirname(os.path.dirname(HERE)) -TOOLS_DIR = os.environ.get("LEONIDA_TOOLS_DIR") or os.path.join(ROOT, "tools") -if TOOLS_DIR not in sys.path: - sys.path.insert(0, TOOLS_DIR) - -import rdna2spirv # noqa: E402 - -MASK32 = 0xFFFFFFFF -MASK64 = 0xFFFFFFFFFFFFFFFF -DEFAULT_LDS_DWORDS = 16384 # 64 KiB default capacity in dwords - - -class UnsupportedConstruct(NotImplementedError): - """The module uses an unmodelled SPIR-V opcode, type, or storage class.""" - - -class WorkgroupBoundsError(ValueError): - """Workgroup dimension or memory bounds violation.""" - - -def reference_atomic_or_b32(current_val: int, or_mask: int) -> tuple[int, int]: - """Reference 32-bit atomic OR: returns (old_val, updated_mem_val).""" - old = current_val & MASK32 - new = (old | or_mask) & MASK32 - return old, new - - -def reference_atomic_or_b64(current_val: int, or_mask: int) -> tuple[int, int]: - """Reference 64-bit atomic OR: returns (old_val, updated_mem_val).""" - old = current_val & MASK64 - new = (old | or_mask) & MASK64 - return old, new - - -def split_u64_to_u32(val: int) -> tuple[int, int]: - """Splits a 64-bit unsigned integer into (low_u32, high_u32).""" - val = val & MASK64 - return val & MASK32, (val >> 32) & MASK32 - - -def combine_u32_to_u64(lo: int, hi: int) -> int: - """Combines two 32-bit unsigned integers (low_u32, high_u32) into a 64-bit unsigned integer.""" - return ((hi & MASK32) << 32) | (lo & MASK32) - - -def calc_lds_byte_offset( - vaddr: int, - byte_offset: int = 0, - lds_dwords: int = DEFAULT_LDS_DWORDS, -) -> tuple[int, int, int]: - """Reference ISA calculation for single LDS address: (effective_byte, dword_idx, byte_in_dword).""" - vaddr = vaddr & MASK32 - byte_offset = byte_offset & 0xFFFF # 16-bit unsigned offset in RDNA2 DS instructions - eff_byte = (vaddr + byte_offset) & MASK32 - dword_idx = (eff_byte >> 2) & (lds_dwords - 1) - byte_in_dword = eff_byte & 3 - return eff_byte, dword_idx, byte_in_dword - - -def calc_lds_dual_offsets( - vaddr: int, - offset0: int = 0, - offset1: int = 0, - lds_dwords: int = DEFAULT_LDS_DWORDS, - st64: bool = False, -) -> tuple[tuple[int, int], tuple[int, int]]: - """Reference ISA calculation for dual LDS addresses. - - Returns: - ((eff_byte0, dword_idx0), (eff_byte1, dword_idx1)) - """ - vaddr = vaddr & MASK32 - unit = 256 if st64 else 4 - off0_bytes = (offset0 & 0xFF) * unit - off1_bytes = (offset1 & 0xFF) * unit - eff_byte0 = (vaddr + off0_bytes) & MASK32 - eff_byte1 = (vaddr + off1_bytes) & MASK32 - dword_idx0 = (eff_byte0 >> 2) & (lds_dwords - 1) - dword_idx1 = (eff_byte1 >> 2) & (lds_dwords - 1) - return (eff_byte0, dword_idx0), (eff_byte1, dword_idx1) - - -class TestAtomicOrReferenceMath(unittest.TestCase): - """Verifies reference bitwise OR properties, algebraic laws, and edge cases.""" - - def test_identity_zero_mask_b32(self): - cases = [0, 1, 0x12345678, 0x80000000, 0x7FFFFFFF, 0xFFFFFFFF] - for val in cases: - with self.subTest(val=hex(val)): - old, new = reference_atomic_or_b32(val, 0) - self.assertEqual(old, val) - self.assertEqual(new, val) - - def test_saturation_all_ones_b32(self): - cases = [0, 1, 0x55555555, 0xAAAAAAAA, 0x80000000, 0xFFFFFFFF] - for val in cases: - with self.subTest(val=hex(val)): - old, new = reference_atomic_or_b32(val, MASK32) - self.assertEqual(old, val) - self.assertEqual(new, MASK32) - - def test_idempotence_b32(self): - cases = [0, 0x10203040, 0x55AA55AA, 0xFFFFFFFF] - for val in cases: - with self.subTest(val=hex(val)): - old, new = reference_atomic_or_b32(val, val) - self.assertEqual(old, val) - self.assertEqual(new, val) - - def test_commutativity_and_associativity_b32(self): - a, b = 0x3F2A1C8E, 0x9D4E7B01 - _, ab = reference_atomic_or_b32(a, b) - _, ba = reference_atomic_or_b32(b, a) - self.assertEqual(ab, ba) - - c = 0x55AA33CC - _, step_ab = reference_atomic_or_b32(a, b) - _, ab_c = reference_atomic_or_b32(step_ab, c) - - _, step_bc = reference_atomic_or_b32(b, c) - _, a_bc = reference_atomic_or_b32(a, step_bc) - self.assertEqual(ab_c, a_bc) - - def test_monotonicity_b32(self): - # Bitwise OR can only set bits from 0 to 1, never clears bits - cases = [ - (0, 0x00000001), - (0x10000000, 0x00000001), - (0x0F0F0F0F, 0xF0F0F0F0), - (0x7FFFFFFF, 0x80000000), - ] - for initial, mask in cases: - with self.subTest(initial=hex(initial), mask=hex(mask)): - old, new = reference_atomic_or_b32(initial, mask) - self.assertEqual(old, initial) - # All bits of initial must still be present in new - self.assertEqual(new & initial, initial) - # All bits of mask must be present in new - self.assertEqual(new & mask, mask) - self.assertGreaterEqual(bin(new).count("1"), bin(initial).count("1")) - - def test_disjoint_bit_patterns_b32(self): - # Alternating bit patterns - old, new = reference_atomic_or_b32(0x55555555, 0xAAAAAAAA) - self.assertEqual(old, 0x55555555) - self.assertEqual(new, MASK32) - - # Upper and lower half-words - old, new = reference_atomic_or_b32(0xFFFF0000, 0x0000FFFF) - self.assertEqual(old, 0xFFFF0000) - self.assertEqual(new, MASK32) - - # Nibble interleaving - old, new = reference_atomic_or_b32(0x0F0F0F0F, 0xF0F0F0F0) - self.assertEqual(old, 0x0F0F0F0F) - self.assertEqual(new, MASK32) - - def test_sequential_bit_accumulation_b32(self): - # Accumulate 32 individual bit flags across 32 sequential atomic operations - current = 0 - for bit in range(32): - flag = 1 << bit - old, current = reference_atomic_or_b32(current, flag) - self.assertEqual(old & flag, 0) - self.assertEqual(current & flag, flag) - self.assertEqual(current, MASK32) - - def test_sparse_bit_combinations_b32(self): - # Non-contiguous bits - val = 0 - steps = [1 << 3, 1 << 7, 1 << 15, 1 << 31] - expected = (1 << 3) | (1 << 7) | (1 << 15) | (1 << 31) - for s in steps: - _, val = reference_atomic_or_b32(val, s) - self.assertEqual(val, expected) - - def test_reference_atomic_or_b64_properties(self): - init = 0x0123456789ABCDEF - mask = 0xFEDCBA9876543210 - old, mem = reference_atomic_or_b64(init, mask) - self.assertEqual(old, init) - self.assertEqual(mem, init | mask) - - # 64-bit zero identity - old_id, mem_id = reference_atomic_or_b64(init, 0) - self.assertEqual(old_id, init) - self.assertEqual(mem_id, init) - - # 64-bit all-ones saturation - old_sat, mem_sat = reference_atomic_or_b64(init, MASK64) - self.assertEqual(old_sat, init) - self.assertEqual(mem_sat, MASK64) - - # 64-bit idempotence - old_idem, mem_idem = reference_atomic_or_b64(init, init) - self.assertEqual(old_idem, init) - self.assertEqual(mem_idem, init) - - def test_reference_atomic_or_b64_cross_dword_patterns(self): - # Low dword only mutated - init = 0xAAAAAAAA_00000000 - mask = 0x00000000_FFFFFFFF - _, res = reference_atomic_or_b64(init, mask) - self.assertEqual(res, 0xAAAAAAAA_FFFFFFFF) - - # High dword only mutated - init = 0x00000000_55555555 - mask = 0xFFFFFFFF_00000000 - _, res = reference_atomic_or_b64(init, mask) - self.assertEqual(res, 0xFFFFFFFF_55555555) - - # Cross dword boundaries - lo_word = 0x00000000_80000000 # bit 31 - hi_word = 0x00000001_00000000 # bit 32 - _, res = reference_atomic_or_b64(lo_word, hi_word) - self.assertEqual(res, 0x00000001_80000000) - - def test_split_and_combine_u64_u32(self): - v64 = 0xFEDCBA9876543210 - lo, hi = split_u64_to_u32(v64) - self.assertEqual(lo, 0x76543210) - self.assertEqual(hi, 0xFEDCBA98) - self.assertEqual(combine_u32_to_u64(lo, hi), v64) - - -class TestLdsAddressingAndOffsets(unittest.TestCase): - """Verifies single and dual LDS byte offsets, dword truncation, st64 strides, and wrapping.""" - - def test_aligned_dword_addressing(self): - lds_dwords = 256 - for dword in (0, 1, 2, 16, 64, 127, 255): - byte_addr = dword * 4 - eff, dword_idx, byte_pos = calc_lds_byte_offset(byte_addr, 0, lds_dwords) - self.assertEqual(eff, byte_addr) - self.assertEqual(dword_idx, dword) - self.assertEqual(byte_pos, 0) - - def test_unaligned_byte_truncation(self): - lds_dwords = 128 - base_aligned = 64 # dword 16 - for b in (0, 1, 2, 3): - eff, dword_idx, byte_pos = calc_lds_byte_offset(base_aligned, b, lds_dwords) - self.assertEqual(eff, base_aligned + b) - self.assertEqual(dword_idx, 16) - self.assertEqual(byte_pos, b) - - def test_offset_16bit_masking(self): - lds_dwords = 512 - # RDNA2 DS instruction offset field is 16-bit unsigned (0x0000 - 0xFFFF) - eff, dword_idx, byte_pos = calc_lds_byte_offset(0, 0x10008, lds_dwords) - self.assertEqual(eff, 8) - self.assertEqual(dword_idx, 2) - self.assertEqual(byte_pos, 0) - - def test_dual_offset_unit_strides(self): - (eff0, idx0), (eff1, idx1) = calc_lds_dual_offsets(0, 3, 10, lds_dwords=1024, st64=False) - self.assertEqual(eff0, 12) - self.assertEqual(idx0, 3) - self.assertEqual(eff1, 40) - self.assertEqual(idx1, 10) - - def test_dual_offset_st64_stride(self): - (eff0, idx0), (eff1, idx1) = calc_lds_dual_offsets(0, 2, 5, lds_dwords=1024, st64=True) - self.assertEqual(eff0, 512) - self.assertEqual(idx0, 128) - self.assertEqual(eff1, 1280) - self.assertEqual(idx1, 320) - - def test_boundary_power_of_two_wrapping(self): - lds_dwords = 64 # 256 bytes total - # Byte address 256 wraps to dword 0 - _, idx0, _ = calc_lds_byte_offset(256, 0, lds_dwords) - self.assertEqual(idx0, 0) - # Byte address 260 wraps to dword 1 - _, idx1, _ = calc_lds_byte_offset(256, 4, lds_dwords) - self.assertEqual(idx1, 1) - # 32-bit unsigned overflow: 0xFFFFFFFC + 4 = 0x00000000 -> dword 0 - _, idx_wrap, _ = calc_lds_byte_offset(0xFFFFFFFC, 4, lds_dwords) - self.assertEqual(idx_wrap, 0) - - -_IGNORED = frozenset({ - "OpCapability", "OpExtInstImport", "OpMemoryModel", "OpEntryPoint", "OpExecutionMode", - "OpDecorate", "OpMemberDecorate", "OpTypeVoid", "OpTypeFunction", "OpLabel", - "OpReturn", "OpFunctionEnd", "OpName", "OpSource", "OpSelectionMerge", -}) - -_LINE = re.compile(r"^(?:(%\S+)\s*=\s*)?(Op\w+)\s*(.*)$") - - -def translate_cs_listing(body: list[str]) -> str: - """Translates a compute shader listing using rdna2spirv without external files.""" - with tempfile.TemporaryDirectory() as tmp: - os.mkdir(os.path.join(tmp, "disasm")) - os.mkdir(os.path.join(tmp, "fssm")) - name = "cs_lds_or" - with open(os.path.join(tmp, "disasm", name + ".s"), "w", encoding="utf-8") as f: - f.write(f"; {name}\n" + "".join(f"\t{ln}\n" for ln in body) + "\ts_endpgm\n") - stub_dxbc = b"DXBC" + bytes(24) + struct.pack(" None: - self.vgprs[lane][reg_idx] = value & MASK32 - - def get_vgpr(self, reg_idx: int, lane: int = 0) -> int: - return self.vgprs[lane][reg_idx] - - def set_lds_dword(self, dword_idx: int, value: int) -> None: - self.lds[dword_idx & (self.lds_dwords - 1)] = value & MASK32 - - def get_lds_dword(self, dword_idx: int) -> int: - return self.lds[dword_idx & (self.lds_dwords - 1)] - - def set_lane_active(self, lane: int, active: bool) -> None: - self.active_lanes[lane] = bool(active) - - def set_exec_mask(self, mask: int) -> None: - """Sets active lanes based on a 64-bit integer execution mask.""" - for lane in range(self.num_lanes): - self.active_lanes[lane] = bool((mask >> lane) & 1) - - def ds_write_b32(self, vaddr_reg: int, vdata_reg: int, offset: int = 0, lane: int = 0) -> int | None: - if not self.active_lanes[lane]: - return None - vaddr = self.vgprs[lane][vaddr_reg] - vdata = self.vgprs[lane][vdata_reg] - _, dword_idx, _ = calc_lds_byte_offset(vaddr, offset, self.lds_dwords) - self.lds[dword_idx] = vdata & MASK32 - return dword_idx - - def ds_read_b32(self, vdst_reg: int, vaddr_reg: int, offset: int = 0, lane: int = 0) -> int | None: - if not self.active_lanes[lane]: - return None - vaddr = self.vgprs[lane][vaddr_reg] - _, dword_idx, _ = calc_lds_byte_offset(vaddr, offset, self.lds_dwords) - self.vgprs[lane][vdst_reg] = self.lds[dword_idx] - return dword_idx - - def ds_or_b32(self, vaddr_reg: int, vdata_reg: int, offset: int = 0, lane: int = 0) -> int | None: - """Non-returning 32-bit atomic OR: updates LDS[target], returns dword_idx or None.""" - if not self.active_lanes[lane]: - return None - vaddr = self.vgprs[lane][vaddr_reg] - vdata = self.vgprs[lane][vdata_reg] - _, dword_idx, _ = calc_lds_byte_offset(vaddr, offset, self.lds_dwords) - self.lds[dword_idx] = (self.lds[dword_idx] | vdata) & MASK32 - return dword_idx - - def ds_or_rtn_b32( - self, - vdst_reg: int, - vaddr_reg: int, - vdata_reg: int, - offset: int = 0, - lane: int = 0, - ) -> tuple[int, int] | None: - """Returning 32-bit atomic OR: stores prior value into vdst and updates LDS[target]. - - Returns (dword_idx, old_val) if lane active, or None if inactive. - Handles destination register aliasing: reads vaddr and vdata before overwriting vdst. - """ - if not self.active_lanes[lane]: - return None - vaddr = self.vgprs[lane][vaddr_reg] - vdata = self.vgprs[lane][vdata_reg] - _, dword_idx, _ = calc_lds_byte_offset(vaddr, offset, self.lds_dwords) - old_val = self.lds[dword_idx] - self.lds[dword_idx] = (old_val | vdata) & MASK32 - self.vgprs[lane][vdst_reg] = old_val - return dword_idx, old_val - - def set_vgpr_u64(self, reg_idx: int, value: int, lane: int = 0) -> None: - lo, hi = split_u64_to_u32(value) - self.set_vgpr(reg_idx, lo, lane=lane) - self.set_vgpr(reg_idx + 1, hi, lane=lane) - - def get_vgpr_u64(self, reg_idx: int, lane: int = 0) -> int: - lo = self.get_vgpr(reg_idx, lane=lane) - hi = self.get_vgpr(reg_idx + 1, lane=lane) - return combine_u32_to_u64(lo, hi) - - def set_lds_u64(self, dword_idx: int, value: int) -> None: - lo, hi = split_u64_to_u32(value) - self.set_lds_dword(dword_idx, lo) - self.set_lds_dword((dword_idx + 1) & (self.lds_dwords - 1), hi) - - def get_lds_u64(self, dword_idx: int) -> int: - lo = self.get_lds_dword(dword_idx) - hi = self.get_lds_dword((dword_idx + 1) & (self.lds_dwords - 1)) - return combine_u32_to_u64(lo, hi) - - def ds_write_b64(self, vaddr_reg: int, vdata_lo_reg: int, offset: int = 0, lane: int = 0) -> tuple[int, int] | None: - if not self.active_lanes[lane]: - return None - vaddr = self.vgprs[lane][vaddr_reg] - _, dword_idx0, _ = calc_lds_byte_offset(vaddr, offset, self.lds_dwords) - dword_idx1 = (dword_idx0 + 1) & (self.lds_dwords - 1) - self.lds[dword_idx0] = self.vgprs[lane][vdata_lo_reg] & MASK32 - self.lds[dword_idx1] = self.vgprs[lane][vdata_lo_reg + 1] & MASK32 - return dword_idx0, dword_idx1 - - def ds_read_b64(self, vdst_lo_reg: int, vaddr_reg: int, offset: int = 0, lane: int = 0) -> tuple[int, int] | None: - if not self.active_lanes[lane]: - return None - vaddr = self.vgprs[lane][vaddr_reg] - _, dword_idx0, _ = calc_lds_byte_offset(vaddr, offset, self.lds_dwords) - dword_idx1 = (dword_idx0 + 1) & (self.lds_dwords - 1) - val_lo = self.lds[dword_idx0] - val_hi = self.lds[dword_idx1] - self.vgprs[lane][vdst_lo_reg] = val_lo - self.vgprs[lane][vdst_lo_reg + 1] = val_hi - return dword_idx0, dword_idx1 - - def ds_or_b64(self, vaddr_reg: int, vdata_lo_reg: int, offset: int = 0, lane: int = 0) -> tuple[int, int] | None: - """Non-returning 64-bit atomic OR: updates LDS[idx] and LDS[idx+1], returns (idx0, idx1) or None.""" - if not self.active_lanes[lane]: - return None - vaddr = self.vgprs[lane][vaddr_reg] - vdata_lo = self.vgprs[lane][vdata_lo_reg] - vdata_hi = self.vgprs[lane][vdata_lo_reg + 1] - _, dword_idx0, _ = calc_lds_byte_offset(vaddr, offset, self.lds_dwords) - dword_idx1 = (dword_idx0 + 1) & (self.lds_dwords - 1) - self.lds[dword_idx0] = (self.lds[dword_idx0] | vdata_lo) & MASK32 - self.lds[dword_idx1] = (self.lds[dword_idx1] | vdata_hi) & MASK32 - return dword_idx0, dword_idx1 - - def ds_or_rtn_b64( - self, - vdst_lo_reg: int, - vaddr_reg: int, - vdata_lo_reg: int, - offset: int = 0, - lane: int = 0, - ) -> tuple[int, int] | None: - """Returning 64-bit atomic OR: stores prior 64-bit value into vdst[0:1] and updates LDS[idx:idx+1]. - - Returns (dword_idx0, old_val_u64) if lane active, or None if inactive. - Reads all sources before writing vdst to handle aliasing safely. - """ - if not self.active_lanes[lane]: - return None - vaddr = self.vgprs[lane][vaddr_reg] - vdata_lo = self.vgprs[lane][vdata_lo_reg] - vdata_hi = self.vgprs[lane][vdata_lo_reg + 1] - _, dword_idx0, _ = calc_lds_byte_offset(vaddr, offset, self.lds_dwords) - dword_idx1 = (dword_idx0 + 1) & (self.lds_dwords - 1) - old_lo = self.lds[dword_idx0] - old_hi = self.lds[dword_idx1] - self.lds[dword_idx0] = (old_lo | vdata_lo) & MASK32 - self.lds[dword_idx1] = (old_hi | vdata_hi) & MASK32 - self.vgprs[lane][vdst_lo_reg] = old_lo - self.vgprs[lane][vdst_lo_reg + 1] = old_hi - return dword_idx0, combine_u32_to_u64(old_lo, old_hi) - - def parse_and_execute(self, instruction_text: str, lane: int = 0) -> int | tuple[int, int] | None: - line = instruction_text.strip() - if not line or line.startswith(";"): - return None - - offset = 0 - m_off = re.search(r"\boffset:(\S+)", line) - if m_off: - offset = int(m_off.group(1), 0) - line = re.sub(r"\boffset:\S+", "", line).strip() - - parts = line.split(None, 1) - op = parts[0] - args_str = parts[1] if len(parts) > 1 else "" - raw_args = [a.strip() for a in args_str.split(",") if a.strip()] - - def reg_num(tok: str) -> int: - cleaned = tok.replace("v", "").replace("[", "").replace("]", "") - if ":" in cleaned: - cleaned = cleaned.split(":")[0] - return int(cleaned) - - if op == "ds_or_b32": - vaddr = reg_num(raw_args[0]) - vdata = reg_num(raw_args[1]) - return self.ds_or_b32(vaddr, vdata, offset=offset, lane=lane) - - elif op == "ds_or_rtn_b32": - vdst = reg_num(raw_args[0]) - vaddr = reg_num(raw_args[1]) - vdata = reg_num(raw_args[2]) - res = self.ds_or_rtn_b32(vdst, vaddr, vdata, offset=offset, lane=lane) - return res[0] if res else None - - elif op == "ds_write_b32": - vaddr = reg_num(raw_args[0]) - vdata = reg_num(raw_args[1]) - return self.ds_write_b32(vaddr, vdata, offset=offset, lane=lane) - - elif op == "ds_read_b32": - vdst = reg_num(raw_args[0]) - vaddr = reg_num(raw_args[1]) - return self.ds_read_b32(vdst, vaddr, offset=offset, lane=lane) - - elif op == "ds_or_b64": - vaddr = reg_num(raw_args[0]) - vdata = reg_num(raw_args[1]) - res_b64 = self.ds_or_b64(vaddr, vdata, offset=offset, lane=lane) - return res_b64[0] if res_b64 else None - - elif op == "ds_or_rtn_b64": - vdst = reg_num(raw_args[0]) - vaddr = reg_num(raw_args[1]) - vdata = reg_num(raw_args[2]) - res_rtn_b64 = self.ds_or_rtn_b64(vdst, vaddr, vdata, offset=offset, lane=lane) - return res_rtn_b64[0] if res_rtn_b64 else None - - elif op == "ds_write_b64": - vaddr = reg_num(raw_args[0]) - vdata = reg_num(raw_args[1]) - res_w64 = self.ds_write_b64(vaddr, vdata, offset=offset, lane=lane) - return res_w64[0] if res_w64 else None - - elif op == "ds_read_b64": - vdst = reg_num(raw_args[0]) - vaddr = reg_num(raw_args[1]) - res_r64 = self.ds_read_b64(vdst, vaddr, offset=offset, lane=lane) - return res_r64[0] if res_r64 else None - - else: - raise UnsupportedConstruct(f"Opcode {op} not supported in interpreter") - - def run_simd_wave(self, instruction_text: str) -> list[int | tuple[int, int] | None]: - """Runs the instruction across all lanes in the wavefront in lockstep.""" - return [self.parse_and_execute(instruction_text, lane=lane) for lane in range(self.num_lanes)] - - -class LdsAtomicSpirvInterp: - """Strict semantic interpreter for compute SPIR-V modules exercising LDS atomic OR.""" - - def __init__(self, spvasm: str): - self.spvasm = spvasm - self.types: dict[str, tuple] = {} - self.constants: dict[str, int | bool] = {} - self.ptr_types: dict[str, tuple[str, str]] = {} - self.var_class: dict[str, str] = {} - self.local_size: tuple[int, int, int] = (1, 1, 1) - self.lds_var: str | None = None - self.lds_size: int = 0 - self.body: list[tuple[str | None, str, list[str], str]] = [] - self._parse() - - def _parse(self) -> None: - in_body = False - for raw in self.spvasm.splitlines(): - line = raw.strip() - if not line: - continue - m = _LINE.match(line) - if not m: - raise UnsupportedConstruct(f"Cannot parse line: {line!r}") - res, op, rest = m.groups() - a = rest.split() - if in_body: - self.body.append((res, op, a, line)) - continue - if op == "OpFunction": - in_body = True - continue - if op == "OpExecutionMode" and len(a) >= 5 and a[1] == "LocalSize": - lx, ly, lz = int(a[2]), int(a[3]), int(a[4]) - if lx < 1 or ly < 1 or lz < 1 or (lx * ly * lz) > 1024: - raise WorkgroupBoundsError(f"Invalid LocalSize {lx}x{ly}x{lz}") - self.local_size = (lx, ly, lz) - continue - if op in _IGNORED: - continue - if op == "OpTypeInt": - if int(a[0]) != 32: - raise UnsupportedConstruct("Only 32-bit int supported in interpreter") - self.types[res] = ("int", int(a[0]), int(a[1])) - elif op == "OpTypeBool": - self.types[res] = ("bool",) - elif op == "OpTypeVector": - self.types[res] = ("vec", a[0], int(a[1])) - elif op == "OpTypeArray": - size = int(self.constants[a[1]]) - self.types[res] = ("arr", a[0], size) - elif op == "OpTypePointer": - self.ptr_types[res] = (a[0], a[1]) - elif op == "OpConstant": - self.constants[res] = int(a[1], 0) & MASK32 - elif op == "OpConstantTrue": - self.constants[res] = True - elif op == "OpConstantFalse": - self.constants[res] = False - elif op == "OpVariable": - cls, pointee = self.ptr_types[a[0]] - if a[1] != cls: - raise UnsupportedConstruct("OpVariable storage class mismatch") - self.var_class[res] = cls - if cls == "Workgroup": - if self.lds_var is not None: - raise UnsupportedConstruct("Multiple Workgroup variables") - self.lds_var = res - arr_ty = self.types[pointee] - if arr_ty[0] != "arr": - raise UnsupportedConstruct("Workgroup variable must be an array") - self.lds_size = arr_ty[2] - elif cls not in ("Output", "Function"): - raise UnsupportedConstruct(f"Unsupported storage class {cls}") - else: - raise UnsupportedConstruct(f"Header opcode {op}") - - def run( - self, - num_invocations: int | None = None, - seed_lds: dict[int, int] | None = None, - lane_inputs: list[dict[str, int]] | None = None, - ) -> tuple[list[int], list[dict[str, int]]]: - """Executes the workgroup and returns (final_lds, outputs_per_lane).""" - lx, ly, lz = self.local_size - total_invocations = lx * ly * lz - count = total_invocations if num_invocations is None else min(num_invocations, total_invocations) - - lds = [0] * self.lds_size - if seed_lds: - for idx, val in seed_lds.items(): - if 0 <= idx < self.lds_size: - lds[idx] = val & MASK32 - - lane_outputs: list[dict[str, int]] = [] - for lidx in range(count): - inputs = lane_inputs[lidx] if lane_inputs and lidx < len(lane_inputs) else {} - out = self._run_lane(lidx, lds, inputs) - lane_outputs.append(out) - - return list(lds), lane_outputs - - def _run_lane(self, lidx: int, lds: list[int], inputs: dict[str, int]) -> dict[str, int]: - values: dict[str, int | bool] = dict(self.constants) - values.update(inputs) - var_box: dict[str, list[int]] = {} - pointers: dict[str, tuple[str, list[int], int | None]] = {} - outputs: list[str] = [] - - if self.lds_var: - pointers[self.lds_var] = ("lds", lds, None) - - for res, cls in self.var_class.items(): - if cls == "Output": - var_box[res] = [0] - pointers[res] = ("out", var_box[res], 0) - outputs.append(res) - elif cls == "Function": - var_box[res] = [0] - pointers[res] = ("fn", var_box[res], 0) - - def val(x: str) -> int: - if x in values: - return values[x] # type: ignore - raise UnsupportedConstruct(f"Undefined identifier {x}") - - for res, op, a, _ in self.body: - if op in _IGNORED or op in ("OpBranch", "OpBranchConditional"): - continue - if op == "OpVariable": - cls, _ = self.ptr_types[a[0]] - if cls != "Function": - raise UnsupportedConstruct("Non-Function variable in body") - var_box[res] = [val(a[2]) if len(a) > 2 else 0] - pointers[res] = ("fn", var_box[res], 0) - elif op == "OpAccessChain": - base = a[1] - if base not in pointers: - raise UnsupportedConstruct(f"OpAccessChain on non-pointer {base}") - ptag = pointers[base][0] - if ptag == "lds": - idx = val(a[2]) - if not (0 <= idx < len(lds)): - raise WorkgroupBoundsError(f"LDS access out of bounds: {idx} >= {len(lds)}") - pointers[res] = ("lds", lds, idx) - elif ptag in ("out", "fn"): - pointers[res] = pointers[base] - else: - raise UnsupportedConstruct(f"Access chain on {ptag}") - elif op == "OpLoad": - ptr = pointers[a[1]] - ptag = ptr[0] - if ptag in ("lds", "out", "fn"): - idx_val = ptr[2] - values[res] = ptr[1][idx_val] & MASK32 - elif op == "OpStore": - ptr = pointers[a[0]] - v = val(a[1]) & MASK32 - ptag = ptr[0] - if ptag in ("lds", "out", "fn"): - idx_val = ptr[2] - ptr[1][idx_val] = v - elif op == "OpAtomicOr": - # %res = OpAtomicOr %type %ptr %scope %semantics %val - ptr = pointers[a[1]] - ptag = ptr[0] - if ptag != "lds": - raise UnsupportedConstruct(f"OpAtomicOr on non-LDS pointer {ptag}") - mask_val = val(a[4]) & MASK32 - idx_val = ptr[2] - old = ptr[1][idx_val] & MASK32 - ptr[1][idx_val] = (old | mask_val) & MASK32 - values[res] = old - elif op == "OpIAdd": - values[res] = (val(a[1]) + val(a[2])) & MASK32 - elif op == "OpISub": - values[res] = (val(a[1]) - val(a[2])) & MASK32 - elif op == "OpShiftRightLogical": - sh = val(a[2]) - if sh >= 32: - raise UnsupportedConstruct("Shift >= 32") - values[res] = (val(a[1]) >> sh) & MASK32 - elif op == "OpShiftLeftLogical": - sh = val(a[2]) - if sh >= 32: - raise UnsupportedConstruct("Shift >= 32") - values[res] = (val(a[1]) << sh) & MASK32 - elif op == "OpBitwiseAnd": - values[res] = val(a[1]) & val(a[2]) & MASK32 - elif op == "OpBitwiseOr": - values[res] = (val(a[1]) | val(a[2])) & MASK32 - elif op == "OpBitwiseXor": - values[res] = (val(a[1]) ^ val(a[2])) & MASK32 - elif op == "OpSelect": - cond = val(a[1]) - values[res] = val(a[2]) if cond else val(a[3]) - elif op == "OpCopyObject": - values[res] = val(a[1]) - elif op == "OpBitcast": - values[res] = val(a[1]) & MASK32 - else: - raise UnsupportedConstruct(f"Opcode {op} not modelled in body") - - return {name: var_box[name][0] & MASK32 for name in outputs} - - -class TestLdsSemanticInterpreterB32(unittest.TestCase): - """Verifies 32-bit LDS atomic OR execution in multi-lane SIMD interpreter.""" - - def setUp(self): - self.interp = LdsSemanticInterpreter(lds_dwords=256, num_vgprs=64, num_lanes=32) - - def test_ds_or_b32_non_returning_mutates_lds_only(self): - self.interp.set_lds_dword(5, 0x10002000) - self.interp.set_vgpr(0, 20) # byte 20 -> dword 5 - self.interp.set_vgpr(1, 0x00010002) # bitmask - self.interp.set_vgpr(2, 0xDEADBEEF) # dummy register - - res = self.interp.ds_or_b32(vaddr_reg=0, vdata_reg=1, offset=0, lane=0) - self.assertEqual(res, 5) - # LDS[5] updated with bitwise OR - self.assertEqual(self.interp.get_lds_dword(5), 0x10012002) - # Registers preserved - self.assertEqual(self.interp.get_vgpr(0), 20) - self.assertEqual(self.interp.get_vgpr(1), 0x00010002) - self.assertEqual(self.interp.get_vgpr(2), 0xDEADBEEF) - - def test_ds_or_rtn_b32_basic_returns_pre_atomic_value(self): - self.interp.set_lds_dword(7, 0x12340000) - self.interp.set_vgpr(0, 28) # byte 28 -> dword 7 - self.interp.set_vgpr(1, 0x00005678) # bitmask - self.interp.set_vgpr(2, 0) # vdst - - res = self.interp.ds_or_rtn_b32(vdst_reg=2, vaddr_reg=0, vdata_reg=1, offset=0, lane=0) - self.assertEqual(res, (7, 0x12340000)) - # vdst receives old memory value - self.assertEqual(self.interp.get_vgpr(2), 0x12340000) - # LDS memory receives updated value - self.assertEqual(self.interp.get_lds_dword(7), 0x12345678) - - def test_ds_or_rtn_b32_with_offset(self): - self.interp.set_lds_dword(8, 0x0F0F0000) - self.interp.set_vgpr(0, 16) # byte 16 (dword 4) - self.interp.set_vgpr(1, 0x0000F0F0) # bitmask - # offset = 16 bytes (+4 dwords) -> target is dword 8 - res = self.interp.ds_or_rtn_b32(vdst_reg=3, vaddr_reg=0, vdata_reg=1, offset=16, lane=0) - self.assertEqual(res, (8, 0x0F0F0000)) - self.assertEqual(self.interp.get_vgpr(3), 0x0F0F0000) - self.assertEqual(self.interp.get_lds_dword(8), 0x0F0FF0F0) - - def test_inactive_lane_under_exec_mask(self): - self.interp.set_lds_dword(2, 0x5555) - self.interp.set_vgpr(0, 8, lane=1) - self.interp.set_vgpr(1, 0xFFFF, lane=1) - self.interp.set_vgpr(5, 0xDEAD, lane=1) - self.interp.set_lane_active(1, False) - - res = self.interp.ds_or_rtn_b32(vdst_reg=5, vaddr_reg=0, vdata_reg=1, lane=1) - self.assertIsNone(res) - # Inactive lane must preserve both LDS memory and destination VGPR - self.assertEqual(self.interp.get_vgpr(5, lane=1), 0xDEAD) - self.assertEqual(self.interp.get_lds_dword(2), 0x5555) - - def test_multi_lane_divergent_destinations(self): - # 32 lanes, each lane targeting its own dword slot (lane 0 -> dword 0, etc.) - for lane in range(32): - self.interp.set_lds_dword(lane, 0x1000 + lane) - self.interp.set_vgpr(0, lane * 4, lane=lane) - self.interp.set_vgpr(1, 0x00FF, lane=lane) - self.interp.set_vgpr(2, 0, lane=lane) - - for lane in range(32): - self.interp.ds_or_rtn_b32(vdst_reg=2, vaddr_reg=0, vdata_reg=1, offset=0, lane=lane) - - for lane in range(32): - self.assertEqual(self.interp.get_vgpr(2, lane=lane), 0x1000 + lane) - self.assertEqual(self.interp.get_lds_dword(lane), (0x1000 + lane) | 0x00FF) - - def test_shared_address_clash_all_lanes_same_dword(self): - # All 32 lanes target dword 10, each lane setting exactly 1 distinct bit - self.interp.set_lds_dword(10, 0x00000000) - for lane in range(32): - self.interp.set_vgpr(0, 40, lane=lane) # byte 40 -> dword 10 - self.interp.set_vgpr(1, 1 << lane, lane=lane) - self.interp.set_vgpr(2, 0, lane=lane) - - old_values = [] - for lane in range(32): - _, old_val = self.interp.ds_or_rtn_b32(vdst_reg=2, vaddr_reg=0, vdata_reg=1, offset=0, lane=lane) - old_values.append(old_val) - - # Final memory has all 32 bits set - self.assertEqual(self.interp.get_lds_dword(10), MASK32) - - # First lane saw 0 - self.assertEqual(old_values[0], 0) - # Every return value is a subset of MASK32 and monotonically non-decreasing in bits - for i in range(1, 32): - self.assertGreaterEqual(bin(old_values[i]).count("1"), bin(old_values[i - 1]).count("1")) - # Lane i should see bits from lanes 0..i-1 - self.assertEqual(old_values[i], (1 << i) - 1) - - def test_shared_address_clash_overlapping_bitmasks(self): - self.interp.set_lds_dword(4, 0x00) - # 3 lanes clashing on dword 4 with overlapping masks: 0x0F, 0x3C, 0xF0 - masks = [0x0F, 0x3C, 0xF0] - for lane, m in enumerate(masks): - self.interp.set_vgpr(0, 16, lane=lane) # dword 4 - self.interp.set_vgpr(1, m, lane=lane) - self.interp.set_vgpr(2, 0, lane=lane) - - for lane in range(3): - self.interp.ds_or_rtn_b32(vdst_reg=2, vaddr_reg=0, vdata_reg=1, lane=lane) - - # 0x0F | 0x3C | 0xF0 = 0xFF - self.assertEqual(self.interp.get_lds_dword(4), 0xFF) - self.assertEqual(self.interp.get_vgpr(2, lane=0), 0x00) - self.assertEqual(self.interp.get_vgpr(2, lane=1), 0x0F) - self.assertEqual(self.interp.get_vgpr(2, lane=2), 0x3F) - - def test_vdst_aliasing_vdata(self): - # vdst is register 1, which also holds vdata - self.interp.set_lds_dword(4, 0x11110000) - self.interp.set_vgpr(0, 16) # dword 4 - self.interp.set_vgpr(1, 0x00002222) # vdata in v1 - - # vdst=1 aliases vdata=1 - self.interp.ds_or_rtn_b32(vdst_reg=1, vaddr_reg=0, vdata_reg=1, lane=0) - # LDS gets old | initial vdata - self.assertEqual(self.interp.get_lds_dword(4), 0x11112222) - # v1 receives old value 0x11110000 - self.assertEqual(self.interp.get_vgpr(1), 0x11110000) - - def test_vdst_aliasing_vaddr(self): - # vdst is register 0, which also holds vaddr - self.interp.set_lds_dword(6, 0x88880000) - self.interp.set_vgpr(0, 24) # vaddr = byte 24 (dword 6) - self.interp.set_vgpr(1, 0x00001111) - - self.interp.ds_or_rtn_b32(vdst_reg=0, vaddr_reg=0, vdata_reg=1, lane=0) - self.assertEqual(self.interp.get_lds_dword(6), 0x88881111) - self.assertEqual(self.interp.get_vgpr(0), 0x88880000) - - def test_assembly_parser_dispatch_b32(self): - self.interp.set_lds_dword(3, 0xAAAA0000) - self.interp.set_vgpr(0, 12) - self.interp.set_vgpr(1, 0x00005555) - - self.interp.parse_and_execute("ds_or_b32 v0, v1 offset:0") - self.assertEqual(self.interp.get_lds_dword(3), 0xAAAA5555) - - self.interp.set_vgpr(2, 0) - self.interp.set_vgpr(1, 0x11110000) - self.interp.parse_and_execute("ds_or_rtn_b32 v2, v0, v1 offset:0") - self.assertEqual(self.interp.get_vgpr(2), 0xAAAA5555) - self.assertEqual(self.interp.get_lds_dword(3), 0xBBBB5555) - - def test_run_simd_wave_with_exec_mask(self): - # Lanes 0..3 active, lanes 4..7 inactive - self.interp.set_exec_mask(0x0F) - for lane in range(8): - self.interp.set_vgpr(0, lane * 4, lane=lane) - self.interp.set_vgpr(1, 0xFF, lane=lane) - self.interp.set_vgpr(2, 0xAA, lane=lane) - - results = self.interp.run_simd_wave("ds_or_rtn_b32 v2, v0, v1") - for lane in range(4): - self.assertIsNotNone(results[lane]) - self.assertEqual(self.interp.get_vgpr(2, lane=lane), 0) - self.assertEqual(self.interp.get_lds_dword(lane), 0xFF) - for lane in range(4, 8): - self.assertIsNone(results[lane]) - self.assertEqual(self.interp.get_vgpr(2, lane=lane), 0xAA) - self.assertEqual(self.interp.get_lds_dword(lane), 0) - - def test_workgroup_barrier_bitmask_aggregation(self): - # 32 lanes signal arrival by setting their lane bit in LDS[0] - self.interp.set_lds_dword(0, 0) - for lane in range(32): - self.interp.set_vgpr(0, 0, lane=lane) - self.interp.set_vgpr(1, 1 << lane, lane=lane) - self.interp.set_vgpr(2, 0, lane=lane) - - for lane in range(32): - self.interp.ds_or_rtn_b32(vdst_reg=2, vaddr_reg=0, vdata_reg=1, lane=lane) - - # All 32 lanes have arrived - self.assertEqual(self.interp.get_lds_dword(0), MASK32) - # Last lane to check in observes all preceding bits set - self.assertEqual(self.interp.get_vgpr(2, lane=31), (1 << 31) - 1) - - -class TestSpirvAtomicOrInterpreterB32(unittest.TestCase): - """Executes SPIR-V compute kernels with LDS OpAtomicOr operations.""" - - def test_ds_or_b32_non_returning_semantic(self): - spvasm = """ -OpCapability Shader -OpMemoryModel Logical GLSL450 -OpEntryPoint GLCompute %main "main" -OpExecutionMode %main LocalSize 1 1 1 -%uint = OpTypeInt 32 0 -%c64 = OpConstant %uint 64 -%c2 = OpConstant %uint 2 -%c0 = OpConstant %uint 0 -%c3 = OpConstant %uint 3 -%c15 = OpConstant %uint 15 -%lds_arr = OpTypeArray %uint %c64 -%_ptr_WG_lds = OpTypePointer Workgroup %lds_arr -%_ptr_WG_uint = OpTypePointer Workgroup %uint -%lds = OpVariable %_ptr_WG_lds Workgroup -%void = OpTypeVoid -%fn = OpTypeFunction %void -%main = OpFunction %void None %fn -%entry = OpLabel -%ptr = OpAccessChain %_ptr_WG_uint %lds %c3 -%dummy = OpAtomicOr %uint %ptr %c2 %c0 %c15 -OpReturn -OpFunctionEnd -""" - interp = LdsAtomicSpirvInterp(spvasm) - final_lds, _ = interp.run(seed_lds={3: 0x1000}) - self.assertEqual(final_lds[3], 0x100F) - self.assertEqual(final_lds[0], 0) - self.assertEqual(final_lds[2], 0) - self.assertEqual(final_lds[4], 0) - - def test_ds_or_rtn_b32_returning_semantic(self): - spvasm = """ -OpCapability Shader -OpMemoryModel Logical GLSL450 -OpEntryPoint GLCompute %main "main" %out -OpExecutionMode %main LocalSize 1 1 1 -%uint = OpTypeInt 32 0 -%_ptr_Output_uint = OpTypePointer Output %uint -%out = OpVariable %_ptr_Output_uint Output -%c64 = OpConstant %uint 64 -%c2 = OpConstant %uint 2 -%c0 = OpConstant %uint 0 -%c7 = OpConstant %uint 7 -%c50 = OpConstant %uint 50 -%lds_arr = OpTypeArray %uint %c64 -%_ptr_WG_lds = OpTypePointer Workgroup %lds_arr -%_ptr_WG_uint = OpTypePointer Workgroup %uint -%lds = OpVariable %_ptr_WG_lds Workgroup -%void = OpTypeVoid -%fn = OpTypeFunction %void -%main = OpFunction %void None %fn -%entry = OpLabel -%ptr = OpAccessChain %_ptr_WG_uint %lds %c7 -%old = OpAtomicOr %uint %ptr %c2 %c0 %c50 -OpStore %out %old -OpReturn -OpFunctionEnd -""" - interp = LdsAtomicSpirvInterp(spvasm) - initial_val = 0x12340000 - final_lds, lane_out = interp.run(seed_lds={7: initial_val}) - self.assertEqual(lane_out[0]["%out"], initial_val) - self.assertEqual(final_lds[7], initial_val | 50) - - def test_multi_lane_shared_bitmask_reduction(self): - # 8 invocations in a workgroup each atomically OR their bit into LDS[0] - spvasm = """ -OpCapability Shader -OpMemoryModel Logical GLSL450 -OpEntryPoint GLCompute %main "main" %out -OpExecutionMode %main LocalSize 8 1 1 -%uint = OpTypeInt 32 0 -%_ptr_Output_uint = OpTypePointer Output %uint -%out = OpVariable %_ptr_Output_uint Output -%c16 = OpConstant %uint 16 -%c2 = OpConstant %uint 2 -%c0 = OpConstant %uint 0 -%c0_slot = OpConstant %uint 0 -%c1 = OpConstant %uint 1 -%lds_arr = OpTypeArray %uint %c16 -%_ptr_WG_lds = OpTypePointer Workgroup %lds_arr -%_ptr_WG_uint = OpTypePointer Workgroup %uint -%lds = OpVariable %_ptr_WG_lds Workgroup -%void = OpTypeVoid -%fn = OpTypeFunction %void -%main = OpFunction %void None %fn -%entry = OpLabel -%ptr = OpAccessChain %_ptr_WG_uint %lds %c0_slot -%ticket = OpAtomicOr %uint %ptr %c2 %c0 %c1 -OpStore %out %ticket -OpReturn -OpFunctionEnd -""" - interp = LdsAtomicSpirvInterp(spvasm) - final_lds, lane_outs = interp.run(num_invocations=8, seed_lds={0: 0}) - self.assertEqual(final_lds[0], 1) - # First invocation saw 0, others saw 1 - tickets = [o["%out"] for o in lane_outs] - self.assertEqual(tickets[0], 0) - self.assertEqual(tickets[1:], [1] * 7) - - def test_chained_atomic_ors_same_slot(self): - spvasm = """ -OpCapability Shader -OpMemoryModel Logical GLSL450 -OpEntryPoint GLCompute %main "main" %out -OpExecutionMode %main LocalSize 1 1 1 -%uint = OpTypeInt 32 0 -%_ptr_Output_uint = OpTypePointer Output %uint -%out = OpVariable %_ptr_Output_uint Output -%c16 = OpConstant %uint 16 -%c2 = OpConstant %uint 2 -%c0 = OpConstant %uint 0 -%c4_slot = OpConstant %uint 4 -%c1 = OpConstant %uint 1 -%c2_val = OpConstant %uint 2 -%c4_val = OpConstant %uint 4 -%lds_arr = OpTypeArray %uint %c16 -%_ptr_WG_lds = OpTypePointer Workgroup %lds_arr -%_ptr_WG_uint = OpTypePointer Workgroup %uint -%lds = OpVariable %_ptr_WG_lds Workgroup -%void = OpTypeVoid -%fn = OpTypeFunction %void -%main = OpFunction %void None %fn -%entry = OpLabel -%ptr = OpAccessChain %_ptr_WG_uint %lds %c4_slot -%r1 = OpAtomicOr %uint %ptr %c2 %c0 %c1 -%r2 = OpAtomicOr %uint %ptr %c2 %c0 %c2_val -%r3 = OpAtomicOr %uint %ptr %c2 %c0 %c4_val -OpStore %out %r3 -OpReturn -OpFunctionEnd -""" - interp = LdsAtomicSpirvInterp(spvasm) - final_lds, lane_out = interp.run(seed_lds={4: 0}) - # r1 got 0 (lds became 1) - # r2 got 1 (lds became 3) - # r3 got 3 (lds became 7) - self.assertEqual(lane_out[0]["%out"], 3) - self.assertEqual(final_lds[4], 7) - - def test_offset_and_wrapping_in_spirv(self): - spvasm = """ -OpCapability Shader -OpMemoryModel Logical GLSL450 -OpEntryPoint GLCompute %main "main" %out -OpExecutionMode %main LocalSize 1 1 1 -%uint = OpTypeInt 32 0 -%_ptr_Output_uint = OpTypePointer Output %uint -%out = OpVariable %_ptr_Output_uint Output -%c16 = OpConstant %uint 16 -%c15 = OpConstant %uint 15 -%c2 = OpConstant %uint 2 -%c0 = OpConstant %uint 0 -%c_base = OpConstant %uint 60 -%c_offset = OpConstant %uint 16 -%c_val = OpConstant %uint 42 -%lds_arr = OpTypeArray %uint %c16 -%_ptr_WG_lds = OpTypePointer Workgroup %lds_arr -%_ptr_WG_uint = OpTypePointer Workgroup %uint -%lds = OpVariable %_ptr_WG_lds Workgroup -%void = OpTypeVoid -%fn = OpTypeFunction %void -%main = OpFunction %void None %fn -%entry = OpLabel -%s1 = OpIAdd %uint %c_base %c_offset -%i = OpShiftRightLogical %uint %s1 %c2 -%m = OpBitwiseAnd %uint %i %c15 -%ptr = OpAccessChain %_ptr_WG_uint %lds %m -%old = OpAtomicOr %uint %ptr %c2 %c0 %c_val -OpStore %out %old -OpReturn -OpFunctionEnd -""" - # Base 60 + Offset 16 = 76 -> 76 >> 2 = 19 -> 19 & 15 = 3 - interp = LdsAtomicSpirvInterp(spvasm) - final_lds, lane_out = interp.run(seed_lds={3: 100}) - self.assertEqual(lane_out[0]["%out"], 100) - self.assertEqual(final_lds[3], 100 | 42) - - -class TestTranslatorIntegrationB32(unittest.TestCase): - """Verifies that tools/rdna2spirv.py emits conforming SPIR-V for ds_or_b32 and ds_or_rtn_b32.""" - - def _make_mock_gen(self, stage="cs"): - class MockGen: - def __init__(self): - self.stage = stage - self.uses_lds = False - self.lds_dwords = 256 - self.lds_bound = None # not bounds-checked (SHADER-309) - self.wave64 = True - self._tmp = 0 - self.emitted = [] - self.stored_dsts = [] - - def tmp(self): - self._tmp += 1 - return f"%t{self._tmp}" - - def cu(self, v): - return f"%c{v}" - - def active_b(self): - return "%exec_active" - - def src_u(self, arg): - return f"%v_{arg['r']}" - - def dst(self, d, v): - self.stored_dsts.append((d, v)) - - def emit(self, line): - self.emitted.append(line) - - LDS_ATOMICS = rdna2spirv.Gen.LDS_ATOMICS - mod_int = staticmethod(rdna2spirv.Gen.mod_int) - lds_ptr = rdna2spirv.Gen.lds_ptr - lds_access = rdna2spirv.Gen.lds_access - lds_atomic = rdna2spirv.Gen.lds_atomic - lds_op = rdna2spirv.Gen.lds_op - - return MockGen() - - def test_lds_atomics_table_contains_ds_or(self): - self.assertIn("ds_or_b32", rdna2spirv.Gen.LDS_ATOMICS) - self.assertEqual(rdna2spirv.Gen.LDS_ATOMICS["ds_or_b32"], "OpAtomicOr") - - def test_ds_or_b32_non_returning_emission(self): - gen = self._make_mock_gen(stage="cs") - gen.lds_op("ds_or_b32", [{"r": 0}, {"r": 1}], ["offset:8"]) - self.assertTrue(gen.uses_lds) - emitted_str = "\n".join(gen.emitted) - - self.assertIn("OpBranchConditional %exec_active", emitted_str) - self.assertIn("OpIAdd %uint %v_0 %c8", emitted_str) - self.assertIn("OpShiftRightLogical %uint", emitted_str) - self.assertIn("OpBitwiseAnd %uint", emitted_str) - self.assertIn("OpAccessChain %_ptr_WG_uint %lds", emitted_str) - self.assertIn("OpAtomicOr %uint", emitted_str) - self.assertIn("%c2 %c0 %v_1", emitted_str) - self.assertEqual(len(gen.stored_dsts), 0) - - def test_ds_or_rtn_b32_returning_emission(self): - gen = self._make_mock_gen(stage="cs") - gen.lds_op("ds_or_rtn_b32", [{"r": 5}, {"r": 0}, {"r": 1}], ["offset:12"]) - self.assertTrue(gen.uses_lds) - emitted_str = "\n".join(gen.emitted) - - self.assertIn("OpAtomicOr %uint", emitted_str) - self.assertIn("%c2 %c0 %v_1", emitted_str) - self.assertEqual(len(gen.stored_dsts), 1) - dest_reg, val_id = gen.stored_dsts[0] - self.assertEqual(dest_reg["r"], 5) - self.assertTrue(val_id.startswith("%t")) - - def test_full_shader_translation_ds_or_b32(self): - body = [ - "v_mov_b32_e32 v0, 16", - "v_mov_b32_e32 v1, 0x1234", - "ds_or_b32 v0, v1 offset:8", - "s_waitcnt lgkmcnt(0)", - ] - spv = translate_cs_listing(body) - self.assertIn("OpAtomicOr", spv) - self.assertIn("%lds", spv) - - -class TestLdsSemanticInterpreterB64(unittest.TestCase): - """Verifies 64-bit LDS atomic OR execution in multi-lane SIMD interpreter.""" - - def setUp(self): - self.interp = LdsSemanticInterpreter(lds_dwords=256, num_vgprs=64, num_lanes=32) - - def test_ds_or_b64_non_returning_mutates_both_dwords(self): - self.interp.set_lds_dword(10, 0x12340000) - self.interp.set_lds_dword(11, 0x9ABC0000) - self.interp.set_vgpr(0, 40) # byte 40 -> dword 10 - self.interp.set_vgpr(2, 0x00005678) # data lo - self.interp.set_vgpr(3, 0x0000DEF0) # data hi - self.interp.set_vgpr(4, 0xDEADBEEF) # dummy - - res = self.interp.ds_or_b64(vaddr_reg=0, vdata_lo_reg=2, offset=0, lane=0) - self.assertEqual(res, (10, 11)) - self.assertEqual(self.interp.get_lds_dword(10), 0x12345678) - self.assertEqual(self.interp.get_lds_dword(11), 0x9ABCDEF0) - self.assertEqual(self.interp.get_vgpr(0), 40) - self.assertEqual(self.interp.get_vgpr(2), 0x00005678) - self.assertEqual(self.interp.get_vgpr(3), 0x0000DEF0) - self.assertEqual(self.interp.get_vgpr(4), 0xDEADBEEF) - - def test_ds_or_rtn_b64_returns_prior_64bit_value(self): - init_val = 0xCAFEBABE_DEADBEEF - mask_val = 0x00000000_11111111 - self.interp.set_lds_u64(12, init_val) - self.interp.set_vgpr(0, 48) # byte 48 -> dword 12 - self.interp.set_vgpr_u64(2, mask_val) - self.interp.set_vgpr_u64(4, 0) # vdst in v[4:5] - - res = self.interp.ds_or_rtn_b64(vdst_lo_reg=4, vaddr_reg=0, vdata_lo_reg=2, offset=0, lane=0) - self.assertEqual(res, (12, init_val)) - self.assertEqual(self.interp.get_vgpr_u64(4), init_val) - self.assertEqual(self.interp.get_lds_u64(12), init_val | mask_val) - - def test_ds_or_rtn_b64_with_offset(self): - init_val = 0x11112222_33334444 - mask_val = 0x55555555_AAAAAAAA - # vaddr = 32 (dword 8), offset = 24 bytes (6 dwords) -> target is dword 14 - self.interp.set_lds_u64(14, init_val) - self.interp.set_vgpr(0, 32) - self.interp.set_vgpr_u64(2, mask_val) - self.interp.set_vgpr_u64(6, 0) - - res = self.interp.ds_or_rtn_b64(vdst_lo_reg=6, vaddr_reg=0, vdata_lo_reg=2, offset=24, lane=0) - self.assertEqual(res, (14, init_val)) - self.assertEqual(self.interp.get_vgpr_u64(6), init_val) - self.assertEqual(self.interp.get_lds_u64(14), init_val | mask_val) - - def test_ds_or_rtn_b64_saturation_chain(self): - # Initial 0; OR with 0x55555555_55555555, then 0xAAAAAAAA_AAAAAAAA -> MASK64 - self.interp.set_lds_u64(20, 0) - self.interp.set_vgpr(0, 80) - mask1 = 0x55555555_55555555 - mask2 = 0xAAAAAAAA_AAAAAAAA - self.interp.set_vgpr_u64(2, mask1) - - res1 = self.interp.ds_or_rtn_b64(vdst_lo_reg=4, vaddr_reg=0, vdata_lo_reg=2, offset=0, lane=0) - self.assertEqual(res1, (20, 0)) - self.assertEqual(self.interp.get_vgpr_u64(4), 0) - self.assertEqual(self.interp.get_lds_u64(20), mask1) - - self.interp.set_vgpr_u64(2, mask2) - res2 = self.interp.ds_or_rtn_b64(vdst_lo_reg=6, vaddr_reg=0, vdata_lo_reg=2, offset=0, lane=0) - self.assertEqual(res2, (20, mask1)) - self.assertEqual(self.interp.get_vgpr_u64(6), mask1) - self.assertEqual(self.interp.get_lds_u64(20), MASK64) - - def test_ds_or_rtn_b64_vdst_aliasing_vdata(self): - init_val = 0x88880000_66660000 - data_val = 0x00007777_00005555 - self.interp.set_lds_u64(16, init_val) - self.interp.set_vgpr(0, 64) - self.interp.set_vgpr_u64(2, data_val) - - # vdst is v[2:3], which aliases vdata in v[2:3] - res = self.interp.ds_or_rtn_b64(vdst_lo_reg=2, vaddr_reg=0, vdata_lo_reg=2, lane=0) - self.assertEqual(res, (16, init_val)) - self.assertEqual(self.interp.get_lds_u64(16), init_val | data_val) - self.assertEqual(self.interp.get_vgpr_u64(2), init_val) - - def test_ds_or_rtn_b64_vdst_aliasing_vaddr(self): - init_val = 0xAAAA0000_CCCC0000 - data_val = 0x0000BBBB_0000DDDD - self.interp.set_lds_u64(18, init_val) - self.interp.set_vgpr(0, 72) - self.interp.set_vgpr_u64(2, data_val) - - # vdst is v[0:1], aliasing vaddr in v0 - res = self.interp.ds_or_rtn_b64(vdst_lo_reg=0, vaddr_reg=0, vdata_lo_reg=2, lane=0) - self.assertEqual(res, (18, init_val)) - self.assertEqual(self.interp.get_lds_u64(18), init_val | data_val) - self.assertEqual(self.interp.get_vgpr_u64(0), init_val) - - def test_ds_or_b64_inactive_lane_under_exec_mask(self): - self.interp.set_lds_u64(4, 0x12345678_9ABCDEF0) - self.interp.set_vgpr(0, 16, lane=2) - self.interp.set_vgpr_u64(2, 0xFFFFFFFF_FFFFFFFF, lane=2) - self.interp.set_vgpr_u64(4, 0xFEEDFACE_CAFEBABE, lane=2) - self.interp.set_lane_active(2, False) - - res = self.interp.ds_or_rtn_b64(vdst_lo_reg=4, vaddr_reg=0, vdata_lo_reg=2, lane=2) - self.assertIsNone(res) - self.assertEqual(self.interp.get_vgpr_u64(4, lane=2), 0xFEEDFACE_CAFEBABE) - self.assertEqual(self.interp.get_lds_u64(4), 0x12345678_9ABCDEF0) - - def test_ds_or_rtn_b64_simd_wave_divergent(self): - # 32 lanes, each lane targeting its own 64-bit element (lane * 8 bytes = dword 2 * lane) - for lane in range(32): - val = (0x1000_0000_0000 + lane * 0x1_0000_0001) & MASK64 - self.interp.set_lds_u64(lane * 2, val) - self.interp.set_vgpr(0, lane * 8, lane=lane) - self.interp.set_vgpr_u64(2, 0x00FF00FF_00FF00FF, lane=lane) - self.interp.set_vgpr_u64(4, 0, lane=lane) - - for lane in range(32): - self.interp.ds_or_rtn_b64(vdst_lo_reg=4, vaddr_reg=0, vdata_lo_reg=2, offset=0, lane=lane) - - for lane in range(32): - orig_val = (0x1000_0000_0000 + lane * 0x1_0000_0001) & MASK64 - self.assertEqual(self.interp.get_vgpr_u64(4, lane=lane), orig_val) - self.assertEqual(self.interp.get_lds_u64(lane * 2), orig_val | 0x00FF00FF_00FF00FF) - - def test_ds_or_rtn_b64_simd_wave_convergent_shared_word(self): - # 32 lanes all targeting dword 30 (64-bit), each setting bit lane and bit lane + 32 - self.interp.set_lds_u64(30, 0) - for lane in range(32): - self.interp.set_vgpr(0, 120, lane=lane) # byte 120 -> dword 30 - mask_64 = (1 << lane) | (1 << (lane + 32)) - self.interp.set_vgpr_u64(2, mask_64, lane=lane) - self.interp.set_vgpr_u64(4, 0, lane=lane) - - for lane in range(32): - self.interp.ds_or_rtn_b64(vdst_lo_reg=4, vaddr_reg=0, vdata_lo_reg=2, offset=0, lane=lane) - - self.assertEqual(self.interp.get_lds_u64(30), MASK64) - - def test_assembly_parser_dispatch_b64(self): - self.interp.set_lds_u64(8, 0xAAAAAAAA_00000000) - self.interp.set_vgpr(0, 32) - self.interp.set_vgpr_u64(2, 0x00000000_55555555) - - self.interp.parse_and_execute("ds_or_b64 v0, v[2:3] offset:0") - self.assertEqual(self.interp.get_lds_u64(8), 0xAAAAAAAA_55555555) - - self.interp.set_vgpr_u64(4, 0) - self.interp.set_vgpr_u64(2, 0x55555555_AAAAAAAA) - self.interp.parse_and_execute("ds_or_rtn_b64 v[4:5], v0, v[2:3] offset:0") - self.assertEqual(self.interp.get_vgpr_u64(4), 0xAAAAAAAA_55555555) - self.assertEqual(self.interp.get_lds_u64(8), MASK64) - - # Test ds_write_b64 and ds_read_b64 through parser - self.interp.set_vgpr_u64(6, 0xCAFEBABE_12345678) - self.interp.parse_and_execute("ds_write_b64 v0, v[6:7] offset:8") - self.assertEqual(self.interp.get_lds_u64(10), 0xCAFEBABE_12345678) - - self.interp.set_vgpr_u64(8, 0) - self.interp.parse_and_execute("ds_read_b64 v[8:9], v0 offset:8") - self.assertEqual(self.interp.get_vgpr_u64(8), 0xCAFEBABE_12345678) - - def test_run_simd_wave_b64_with_exec_mask(self): - # Lanes 0..3 active (0x0F), lanes 4..7 inactive - self.interp.set_exec_mask(0x0F) - for lane in range(8): - self.interp.set_vgpr(0, lane * 8, lane=lane) - self.interp.set_vgpr_u64(2, 0xFFFFFFFF_00000000, lane=lane) - self.interp.set_vgpr_u64(4, 0x55555555_55555555, lane=lane) - - results = self.interp.run_simd_wave("ds_or_rtn_b64 v[4:5], v0, v[2:3]") - for lane in range(4): - self.assertIsNotNone(results[lane]) - self.assertEqual(self.interp.get_vgpr_u64(4, lane=lane), 0) - self.assertEqual(self.interp.get_lds_u64(lane * 2), 0xFFFFFFFF_00000000) - for lane in range(4, 8): - self.assertIsNone(results[lane]) - self.assertEqual(self.interp.get_vgpr_u64(4, lane=lane), 0x55555555_55555555) - self.assertEqual(self.interp.get_lds_u64(lane * 2), 0) - - -class TestLdsOffsetWrappingAndStrides(unittest.TestCase): - """Verifies edge-case address calculation, 64-bit element wrapping, and st64 dual offsets.""" - - def test_64bit_boundary_crossing_wrap(self): - interp = LdsSemanticInterpreter(lds_dwords=64, num_vgprs=16, num_lanes=1) - # LDS has 64 dwords (indices 0..63). - # A 64-bit element at dword 63 spans dword 63 and dword (63+1)%64 = 0. - interp.set_lds_dword(63, 0x11110000) - interp.set_lds_dword(0, 0x22220000) - interp.set_vgpr(0, 63 * 4) # byte address 252 -> dword 63 - interp.set_vgpr(2, 0x00003333) - interp.set_vgpr(3, 0x00004444) - interp.set_vgpr_u64(4, 0) - - res = interp.ds_or_rtn_b64(vdst_lo_reg=4, vaddr_reg=0, vdata_lo_reg=2, offset=0, lane=0) - self.assertEqual(res, (63, combine_u32_to_u64(0x11110000, 0x22220000))) - self.assertEqual(interp.get_vgpr(4), 0x11110000) - self.assertEqual(interp.get_vgpr(5), 0x22220000) - self.assertEqual(interp.get_lds_dword(63), 0x11113333) - self.assertEqual(interp.get_lds_dword(0), 0x22224444) - - def test_large_offset_overflow_wrap(self): - interp = LdsSemanticInterpreter(lds_dwords=128, num_vgprs=16, num_lanes=1) - # 32-bit unsigned wrapping: 0xFFFFFFFC + 8 = 0x00000004 -> dword 1 - interp.set_lds_dword(1, 0x55550000) - interp.set_lds_dword(2, 0xAAAA0000) - interp.set_vgpr(0, 0xFFFFFFFC) - interp.set_vgpr(2, 0x000000FF) - interp.set_vgpr(3, 0x00FF0000) - - interp.ds_or_b64(vaddr_reg=0, vdata_lo_reg=2, offset=8, lane=0) - self.assertEqual(interp.get_lds_dword(1), 0x555500FF) - self.assertEqual(interp.get_lds_dword(2), 0xAAFF0000) - - def test_calc_dual_offsets_st64_math(self): - # Non-st64: stride unit is 4 bytes for 32-bit (1 dword per offset unit) - (eff0, idx0), (eff1, idx1) = calc_lds_dual_offsets(0x100, 4, 8, lds_dwords=512, st64=False) - self.assertEqual(eff0, 0x100 + 16) - self.assertEqual(idx0, (0x100 + 16) >> 2) - self.assertEqual(eff1, 0x100 + 32) - self.assertEqual(idx1, (0x100 + 32) >> 2) - - # st64=True: stride unit is 4 * 64 = 256 bytes per offset unit - (eff0_st, idx0_st), (eff1_st, idx1_st) = calc_lds_dual_offsets(0x100, 1, 2, lds_dwords=512, st64=True) - self.assertEqual(eff0_st, 0x100 + 256) - self.assertEqual(idx0_st, (0x100 + 256) >> 2) - self.assertEqual(eff1_st, 0x100 + 512) - self.assertEqual(idx1_st, (0x100 + 512) >> 2) - - def test_dual_offset_wrapping_power_of_two(self): - lds_dwords = 32 # 128 bytes total - (eff0, idx0), (eff1, idx1) = calc_lds_dual_offsets(0, 32, 33, lds_dwords=lds_dwords, st64=False) - # offset 32 * 4 = 128 bytes -> wraps to dword 0 - self.assertEqual(idx0, 0) - # offset 33 * 4 = 132 bytes -> wraps to dword 1 - self.assertEqual(idx1, 1) - - -class TestSpirvAtomicOrB64Emission(unittest.TestCase): - """Verifies that 64-bit LDS atomic OR translates to conforming SPIR-V and executes correctly.""" - - def test_rdna2spirv_translate_b64_emission(self): - spv = translate_cs_listing([ - "ds_or_b64 v0, v[2:3]", - "ds_or_rtn_b64 v[4:5], v0, v[2:3] offset:16", - ]) - lines = [ln.strip() for ln in spv.splitlines() if "OpAtomicOr" in ln] - # Must emit 2 OpAtomicOr for ds_or_b64 + 2 OpAtomicOr for ds_or_rtn_b64 - self.assertEqual(len(lines), 4) - for ln in lines: - self.assertIn("OpAtomicOr", ln) - self.assertIn("%uint", ln) - self.assertIn("%c2", ln) # Workgroup scope - self.assertIn("%c0", ln) # Relaxed semantics - - def test_spirv_sequential_atomics_emulating_b64(self): - # Compute shader executing two sequential 32-bit OpAtomicOr operations simulating a 64-bit atomic - spvasm = """ -OpCapability Shader -OpMemoryModel Logical GLSL450 -OpEntryPoint GLCompute %main "main" %out_lo %out_hi -OpExecutionMode %main LocalSize 1 1 1 -%uint = OpTypeInt 32 0 -%c64 = OpConstant %uint 64 -%c2 = OpConstant %uint 2 -%c0 = OpConstant %uint 0 -%c10 = OpConstant %uint 10 -%c11 = OpConstant %uint 11 -%c_mask_lo = OpConstant %uint 3735928559 -%c_mask_hi = OpConstant %uint 3405691582 -%lds_arr = OpTypeArray %uint %c64 -%_ptr_WG_lds = OpTypePointer Workgroup %lds_arr -%_ptr_WG_uint = OpTypePointer Workgroup %uint -%_ptr_Out_uint = OpTypePointer Output %uint -%lds = OpVariable %_ptr_WG_lds Workgroup -%out_lo = OpVariable %_ptr_Out_uint Output -%out_hi = OpVariable %_ptr_Out_uint Output -%void = OpTypeVoid -%fn = OpTypeFunction %void -%main = OpFunction %void None %fn -%entry = OpLabel -%ptr_lo = OpAccessChain %_ptr_WG_uint %lds %c10 -%ptr_hi = OpAccessChain %_ptr_WG_uint %lds %c11 -%old_lo = OpAtomicOr %uint %ptr_lo %c2 %c0 %c_mask_lo -%old_hi = OpAtomicOr %uint %ptr_hi %c2 %c0 %c_mask_hi -OpStore %out_lo %old_lo -OpStore %out_hi %old_hi -OpReturn -OpFunctionEnd -""" - interp = LdsAtomicSpirvInterp(spvasm) - init_lo = 0x12340000 - init_hi = 0x9ABC0000 - final_lds, lane_outputs = interp.run(seed_lds={10: init_lo, 11: init_hi}) - self.assertEqual(lane_outputs[0]["%out_lo"], init_lo) - self.assertEqual(lane_outputs[0]["%out_hi"], init_hi) - self.assertEqual(final_lds[10], init_lo | 3735928559) - self.assertEqual(final_lds[11], init_hi | 3405691582) - - -class TestNegativeControlsAndBounds(unittest.TestCase): - """Verifies that invalid operands, unmodelled opcodes, bad stages, and bound violations fail safely.""" - - def test_rdna2spirv_invalid_operand_shape_rejected(self): - # ds_or_b64 requires VGPR pair for data: passing scalar v1 must raise Unsupported - with self.assertRaises(rdna2spirv.Unsupported): - translate_cs_listing(["ds_or_b64 v0, v1"]) - - def test_rdna2spirv_invalid_rtn_destination_shape_rejected(self): - # ds_or_rtn_b64 requires VGPR pair for destination: passing scalar v4 must raise Unsupported - with self.assertRaises(rdna2spirv.Unsupported): - translate_cs_listing(["ds_or_rtn_b64 v4, v0, v[2:3]"]) - - def test_rdna2spirv_non_compute_stage_rejected(self): - class MockPixelGen: - def __init__(self): - self.stage = "ps" - self.uses_lds = False - - lds_op = rdna2spirv.Gen.lds_op - - gen = MockPixelGen() - with self.assertRaises(rdna2spirv.Unsupported): - gen.lds_op("ds_or_b32", [{"r": 0}, {"r": 1}], []) - with self.assertRaises(rdna2spirv.Unsupported): - gen.lds_op("ds_or_b64", [{"r": 0}, {"r": 1, "k": "vgpr", "n": 2}], []) - - def test_spirv_unsupported_storage_class(self): - spvasm = """ -OpCapability Shader -OpMemoryModel Logical GLSL450 -OpEntryPoint GLCompute %main "main" -OpExecutionMode %main LocalSize 1 1 1 -%uint = OpTypeInt 32 0 -%_ptr_UC = OpTypePointer UniformConstant %uint -%u = OpVariable %_ptr_UC UniformConstant -%void = OpTypeVoid -%fn = OpTypeFunction %void -%main = OpFunction %void None %fn -%entry = OpLabel -OpReturn -OpFunctionEnd -""" - with self.assertRaises(UnsupportedConstruct): - LdsAtomicSpirvInterp(spvasm) - - def test_spirv_unsupported_opcode_in_body(self): - spvasm = """ -OpCapability Shader -OpMemoryModel Logical GLSL450 -OpEntryPoint GLCompute %main "main" -OpExecutionMode %main LocalSize 1 1 1 -%uint = OpTypeInt 32 0 -%c10 = OpConstant %uint 10 -%void = OpTypeVoid -%fn = OpTypeFunction %void -%main = OpFunction %void None %fn -%entry = OpLabel -%bad = OpSDiv %uint %c10 %c10 -OpReturn -OpFunctionEnd -""" - interp = LdsAtomicSpirvInterp(spvasm) - with self.assertRaises(UnsupportedConstruct): - interp.run() - - def test_spirv_invalid_workgroup_local_sizes(self): - for bad_dims in [(0, 1, 1), (1025, 1, 1), (33, 32, 1)]: - with self.subTest(dims=bad_dims): - spvasm = f""" -OpCapability Shader -OpMemoryModel Logical GLSL450 -OpEntryPoint GLCompute %main "main" -OpExecutionMode %main LocalSize {bad_dims[0]} {bad_dims[1]} {bad_dims[2]} -%void = OpTypeVoid -%fn = OpTypeFunction %void -%main = OpFunction %void None %fn -%entry = OpLabel -OpReturn -OpFunctionEnd -""" - with self.assertRaises(WorkgroupBoundsError): - LdsAtomicSpirvInterp(spvasm) - - def test_spirv_atomic_on_non_lds_pointer(self): - spvasm = """ -OpCapability Shader -OpMemoryModel Logical GLSL450 -OpEntryPoint GLCompute %main "main" -OpExecutionMode %main LocalSize 1 1 1 -%uint = OpTypeInt 32 0 -%_ptr_fn_uint = OpTypePointer Function %uint -%c2 = OpConstant %uint 2 -%c0 = OpConstant %uint 0 -%c7 = OpConstant %uint 7 -%void = OpTypeVoid -%fn = OpTypeFunction %void -%main = OpFunction %void None %fn -%entry = OpLabel -%fn_var = OpVariable %_ptr_fn_uint Function -%bad = OpAtomicOr %uint %fn_var %c2 %c0 %c7 -OpReturn -OpFunctionEnd -""" - interp = LdsAtomicSpirvInterp(spvasm) - with self.assertRaises(UnsupportedConstruct): - interp.run() - - def test_spirv_out_of_bounds_lds_access(self): - spvasm = """ -OpCapability Shader -OpMemoryModel Logical GLSL450 -OpEntryPoint GLCompute %main "main" -OpExecutionMode %main LocalSize 1 1 1 -%uint = OpTypeInt 32 0 -%c16 = OpConstant %uint 16 -%c99 = OpConstant %uint 99 -%c2 = OpConstant %uint 2 -%c0 = OpConstant %uint 0 -%lds_arr = OpTypeArray %uint %c16 -%_ptr_WG_lds = OpTypePointer Workgroup %lds_arr -%_ptr_WG_uint = OpTypePointer Workgroup %uint -%lds = OpVariable %_ptr_WG_lds Workgroup -%void = OpTypeVoid -%fn = OpTypeFunction %void -%main = OpFunction %void None %fn -%entry = OpLabel -%ptr = OpAccessChain %_ptr_WG_uint %lds %c99 -%bad = OpAtomicOr %uint %ptr %c2 %c0 %c16 -OpReturn -OpFunctionEnd -""" - interp = LdsAtomicSpirvInterp(spvasm) - with self.assertRaises(WorkgroupBoundsError): - interp.run() - - def test_simd_interp_unknown_opcode_rejected(self): - interp = LdsSemanticInterpreter() - with self.assertRaises(UnsupportedConstruct): - interp.parse_and_execute("ds_unknown_op v0, v1") - - def test_spirv_shift_bounds_rejected(self): - for op in ("OpShiftRightLogical", "OpShiftLeftLogical"): - with self.subTest(op=op): - spvasm = f""" -OpCapability Shader -OpMemoryModel Logical GLSL450 -OpEntryPoint GLCompute %main "main" -OpExecutionMode %main LocalSize 1 1 1 -%uint = OpTypeInt 32 0 -%c1 = OpConstant %uint 1 -%c32 = OpConstant %uint 32 -%void = OpTypeVoid -%fn = OpTypeFunction %void -%main = OpFunction %void None %fn -%entry = OpLabel -%bad = {op} %uint %c1 %c32 -OpReturn -OpFunctionEnd -""" - interp = LdsAtomicSpirvInterp(spvasm) - with self.assertRaises(UnsupportedConstruct): - interp.run() - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_lds_atomic_xchg.py b/tests/semantic/test_lds_atomic_xchg.py deleted file mode 100644 index 8ccb22364..000000000 --- a/tests/semantic/test_lds_atomic_xchg.py +++ /dev/null @@ -1,76 +0,0 @@ -"""ds_wrxchg_rtn_b32 through the translator (the two-dword form is in test_lds_wrxchg2.py). - -Standard library only; no GPU, no LLVM, no game files. - -RDNA2 ISA, "Data Share Instructions": ds_wrxchg_rtn_b32 vdst, vaddr, vdata is the atomic exchange: vdst receives the -old dword at (vaddr + offset) / 4 and the dword becomes vdata. There is no plain (non-returning) form of the -single-dword exchange. - -Each case is a compute shader translated by tools/rdna2spirv.py (support.translate_lines) and run in -tests/semantic/spirv_mini_interp.py (one lane: that interpreter does not share LDS between lanes, see lds_run.py). -It writes a few LDS dwords, runs exchanges on them and stores each returned value and the final dwords. The tables -are written out by hand; seeded random sequences are checked against a plain-Python LDS. Until this file, the LDS -tests of this name ran a self-built interpreter that checked only the shape of the SPIR-V. -""" -import os -import random -import sys -import unittest - -sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) -import lds_run as L # noqa: E402 (also puts tools/ on sys.path) -import rdna2spirv # noqa: E402 -import support # noqa: E402 - -XCHG = "ds_wrxchg_rtn_b32" - - -def model(ops, init): - lds = dict(init) - rtns = [] - for _, addr, off, (d,) in ops: - rtns.append(lds[addr + off]) - lds[addr + off] = d - return rtns, {a: lds[a] for a in sorted({addr + off for _, addr, off, _ in ops})} - - -class TestExchange(unittest.TestCase): - def test_by_hand(self): - for m, d in ((0, 0xFFFFFFFF), (0x12345678, 0), (0x80000000, 0x80000000), (0xFFFFFFFF, 0x7FFFFFFF), (5, 5)): - with self.subTest(m=hex(m), d=hex(d)): - self.assertEqual(L.run_chain([(XCHG, 0x40, 0, (d,))], {0x40: m}), ([m], {0x40: d})) - - def test_offset_adds_to_the_address_in_bytes(self): - rtns, fin = L.run_chain([(XCHG, 0x20, 0x24, (9,))], {0x44: 4, 0x40: 100, 0x48: 200}) - self.assertEqual((rtns, fin), ([4], {0x44: 9})) - - def test_a_chain_passes_each_value_on(self): - # Exchanging 2, 3, 4 into a dword that holds 1 returns 1, 2, 3 and leaves 4. - ops = [(XCHG, 8, 0, (v,)) for v in (2, 3, 4)] - self.assertEqual(L.run_chain(ops, {8: 1}), ([1, 2, 3], {8: 4})) - - def test_other_dwords_are_untouched(self): - ops = [(XCHG, 0x10, 0, (0xAAAA,)), (XCHG, 0x14, 0, (0xBBBB,))] - self.assertEqual(L.run_chain(ops, {0x10: 1, 0x14: 2, 0x18: 3}), ([1, 2], {0x10: 0xAAAA, 0x14: 0xBBBB})) - - def test_seeded_sequences(self): - rng = random.Random(0x7C6) - for trial in range(8): - addrs = [0x10, 0x30, 0x7C, 0x100] - init = {a: rng.getrandbits(32) for a in addrs} - ops = [] - for _ in range(12): - eff, off = rng.choice(addrs), rng.choice((0, 0, 0x10, 0x20)) - ops.append((XCHG, eff - off, off, (rng.getrandbits(32),))) - with self.subTest(trial=trial): - self.assertEqual(L.run_chain(ops, init), model(ops, init)) - - -class TestOutsideCompute(unittest.TestCase): - def test_pixel_shader_refuses_the_exchange(self): - with self.assertRaises(rdna2spirv.Unsupported): - support.translate_lines("ps_lds_xchg", [f"{XCHG} v1, v0, v2", "s_endpgm"]) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_lds_atomic_xor.py b/tests/semantic/test_lds_atomic_xor.py deleted file mode 100644 index f482ec8b9..000000000 --- a/tests/semantic/test_lds_atomic_xor.py +++ /dev/null @@ -1,1524 +0,0 @@ -"""Semantic interpreter tests for LDS atomic XOR operations (ds_xor_b32, ds_xor_rtn_b32, ds_xor_b64, ds_xor_rtn_b64). - -Standard library only; no GPU, no LLVM, no external tools, no game files. - -Run directly: - python -I tests/semantic/test_lds_atomic_xor.py -Or via unittest discovery: - python -m unittest discover -s tests/semantic -v - -Background & Specification Rules: - * AMD RDNA2 / GFX10 Local Data Share (LDS) Architecture: - - LDS is an on-chip, software-managed, high-throughput scratchpad memory shared across - all work-items (threads/lanes) in a workgroup. - - Single 32-bit Atomic XOR: - - `ds_xor_b32 vaddr, vdata [offset:N]`: - Non-returning form: - eff_byte = (vaddr + offset) & 0xFFFFFFFF - dword_idx = (eff_byte >> 2) & (lds_dwords - 1) - LDS[dword_idx] = LDS[dword_idx] ^ (vdata & 0xFFFFFFFF) - The pre-atomic memory contents are discarded. - - `ds_xor_rtn_b32 vdst, vaddr, vdata [offset:N]`: - Returning form: - eff_byte = (vaddr + offset) & 0xFFFFFFFF - dword_idx = (eff_byte >> 2) & (lds_dwords - 1) - old_val = LDS[dword_idx] - LDS[dword_idx] = old_val ^ (vdata & 0xFFFFFFFF) - vdst = old_val - Preserves the old value before the XOR into destination VGPR vdst. - - 64-bit Atomic XOR: - - `ds_xor_b64 vaddr, v[data_lo:data_hi] [offset:N]`: - Non-returning 64-bit XOR on two consecutive 32-bit dwords (low dword first): - eff_byte = (vaddr + offset) & 0xFFFFFFFF - dword_idx = (eff_byte >> 2) & (lds_dwords - 1) - LDS[dword_idx] ^= vdata_lo - LDS[dword_idx+1] ^= vdata_hi - - `ds_xor_rtn_b64 v[dst_lo:dst_hi], vaddr, v[data_lo:data_hi] [offset:N]`: - Returning form: writes prior 64 bits into destination VGPR pair v[dst_lo:dst_hi]. - - Active lane masking: - - LDS instructions are vector operations governed by the execution mask (EXEC). - - Inactive lanes do not mutate LDS storage and leave destination VGPRs unmodified. - - Hardware wrapping & alignment: - - Byte addresses are shifted right by 2, dropping unaligned low bits [1:0]. - - The resulting dword index is masked with (lds_dwords - 1), wrapping out-of-bounds - offsets within the allocated power-of-two LDS capacity. - - Mathematical properties of XOR: - - Involution (self-inverse): (x ^ k) ^ k == x. - - Identity: x ^ 0 == x. - - Complement: x ^ 0xFFFFFFFF == ~x. - - Commutative & Associative: lane execution order does not affect final LDS value. -""" -from __future__ import annotations - -import os -import re -import struct -import sys -import tempfile -import unittest -import warnings - -HERE = os.path.dirname(os.path.abspath(__file__)) -ROOT = os.path.dirname(os.path.dirname(HERE)) -TOOLS_DIR = os.environ.get("LEONIDA_TOOLS_DIR") or os.path.join(ROOT, "tools") -if TOOLS_DIR not in sys.path: - sys.path.insert(0, TOOLS_DIR) - -import rdna2spirv # noqa: E402 - -MASK32 = 0xFFFFFFFF -MASK64 = 0xFFFFFFFFFFFFFFFF -DEFAULT_LDS_DWORDS = 16384 # 64 KiB default capacity in dwords - - -class UnsupportedConstruct(NotImplementedError): - """The module uses an unmodelled SPIR-V opcode, type, or storage class.""" - - -class WorkgroupBoundsError(ValueError): - """Workgroup dimension or memory bounds violation.""" - - -_IGNORED = frozenset({ - "OpCapability", "OpExtInstImport", "OpMemoryModel", "OpEntryPoint", "OpExecutionMode", - "OpDecorate", "OpMemberDecorate", "OpTypeVoid", "OpTypeFunction", "OpLabel", - "OpReturn", "OpFunctionEnd", "OpName", "OpSource", "OpSelectionMerge", -}) - -_LINE = re.compile(r"^(?:(%\S+)\s*=\s*)?(Op\w+)\s*(.*)$") - - -def reference_atomic_xor_b32(current_val: int, xor_mask: int) -> tuple[int, int]: - """Reference 32-bit atomic XOR: returns (old_val, updated_mem_val).""" - old = current_val & MASK32 - new = (old ^ xor_mask) & MASK32 - return old, new - - -def reference_atomic_xor_b64(current_val: int, xor_mask: int) -> tuple[int, int]: - """Reference 64-bit atomic XOR: returns (old_val, updated_mem_val).""" - old = current_val & MASK64 - new = (old ^ xor_mask) & MASK64 - return old, new - - -def split_u64_to_u32(val: int) -> tuple[int, int]: - """Splits a 64-bit unsigned integer into (low_u32, high_u32).""" - val = val & MASK64 - return val & MASK32, (val >> 32) & MASK32 - - -def combine_u32_to_u64(lo: int, hi: int) -> int: - """Combines two 32-bit unsigned integers (low_u32, high_u32) into a 64-bit unsigned integer.""" - return ((hi & MASK32) << 32) | (lo & MASK32) - - -def calc_lds_byte_offset( - vaddr: int, - byte_offset: int = 0, - lds_dwords: int = DEFAULT_LDS_DWORDS, -) -> tuple[int, int, int]: - """Reference ISA calculation for single LDS address: (effective_byte, dword_idx, byte_in_dword).""" - vaddr = vaddr & MASK32 - byte_offset = byte_offset & 0xFFFF # 16-bit unsigned offset in RDNA2 DS instructions - eff_byte = (vaddr + byte_offset) & MASK32 - dword_idx = (eff_byte >> 2) & (lds_dwords - 1) - byte_in_dword = eff_byte & 3 - return eff_byte, dword_idx, byte_in_dword - - -def calc_lds_dual_offsets( - vaddr: int, - offset0: int = 0, - offset1: int = 0, - lds_dwords: int = DEFAULT_LDS_DWORDS, - st64: bool = False, -) -> tuple[tuple[int, int], tuple[int, int]]: - """Reference ISA calculation for dual LDS addresses. - - Returns: - ((eff_byte0, dword_idx0), (eff_byte1, dword_idx1)) - """ - vaddr = vaddr & MASK32 - unit = 256 if st64 else 4 - off0_bytes = (offset0 & 0xFF) * unit - off1_bytes = (offset1 & 0xFF) * unit - eff_byte0 = (vaddr + off0_bytes) & MASK32 - eff_byte1 = (vaddr + off1_bytes) & MASK32 - dword_idx0 = (eff_byte0 >> 2) & (lds_dwords - 1) - dword_idx1 = (eff_byte1 >> 2) & (lds_dwords - 1) - return (eff_byte0, dword_idx0), (eff_byte1, dword_idx1) - - -def translate_cs_listing(body: list[str]) -> str: - """Translates a compute shader listing using rdna2spirv without external files.""" - with tempfile.TemporaryDirectory() as tmp: - os.mkdir(os.path.join(tmp, "disasm")) - os.mkdir(os.path.join(tmp, "fssm")) - name = "cs_lds_xor" - with open(os.path.join(tmp, "disasm", name + ".s"), "w", encoding="utf-8") as f: - f.write(f"; {name}\n" + "".join(f"\t{ln}\n" for ln in body) + "\ts_endpgm\n") - stub_dxbc = b"DXBC" + bytes(24) + struct.pack(" None: - self.vgprs[lane][reg_idx] = value & MASK32 - - def get_vgpr(self, reg_idx: int, lane: int = 0) -> int: - return self.vgprs[lane][reg_idx] - - def set_lds_dword(self, dword_idx: int, value: int) -> None: - self.lds[dword_idx & (self.lds_dwords - 1)] = value & MASK32 - - def get_lds_dword(self, dword_idx: int) -> int: - return self.lds[dword_idx & (self.lds_dwords - 1)] - - def set_lane_active(self, lane: int, active: bool) -> None: - self.active_lanes[lane] = bool(active) - - def set_exec_mask(self, mask: int) -> None: - """Sets active lanes based on a 64-bit integer execution mask.""" - for lane in range(self.num_lanes): - self.active_lanes[lane] = bool((mask >> lane) & 1) - - def ds_write_b32(self, vaddr_reg: int, vdata_reg: int, offset: int = 0, lane: int = 0) -> int | None: - if not self.active_lanes[lane]: - return None - vaddr = self.vgprs[lane][vaddr_reg] - vdata = self.vgprs[lane][vdata_reg] - _, dword_idx, _ = calc_lds_byte_offset(vaddr, offset, self.lds_dwords) - self.lds[dword_idx] = vdata & MASK32 - return dword_idx - - def ds_read_b32(self, vdst_reg: int, vaddr_reg: int, offset: int = 0, lane: int = 0) -> int | None: - if not self.active_lanes[lane]: - return None - vaddr = self.vgprs[lane][vaddr_reg] - _, dword_idx, _ = calc_lds_byte_offset(vaddr, offset, self.lds_dwords) - self.vgprs[lane][vdst_reg] = self.lds[dword_idx] - return dword_idx - - def ds_xor_b32(self, vaddr_reg: int, vdata_reg: int, offset: int = 0, lane: int = 0) -> int | None: - """Non-returning 32-bit atomic XOR: updates LDS[target], returns dword_idx or None.""" - if not self.active_lanes[lane]: - return None - vaddr = self.vgprs[lane][vaddr_reg] - vdata = self.vgprs[lane][vdata_reg] - _, dword_idx, _ = calc_lds_byte_offset(vaddr, offset, self.lds_dwords) - self.lds[dword_idx] = (self.lds[dword_idx] ^ vdata) & MASK32 - return dword_idx - - def ds_xor_rtn_b32( - self, - vdst_reg: int, - vaddr_reg: int, - vdata_reg: int, - offset: int = 0, - lane: int = 0, - ) -> tuple[int, int] | None: - """Returning 32-bit atomic XOR: stores prior value into vdst and updates LDS[target]. - - Returns (dword_idx, old_val) if lane active, or None if inactive. - Handles destination register aliasing: reads vaddr and vdata before overwriting vdst. - """ - if not self.active_lanes[lane]: - return None - vaddr = self.vgprs[lane][vaddr_reg] - vdata = self.vgprs[lane][vdata_reg] - _, dword_idx, _ = calc_lds_byte_offset(vaddr, offset, self.lds_dwords) - old_val = self.lds[dword_idx] - self.lds[dword_idx] = (old_val ^ vdata) & MASK32 - self.vgprs[lane][vdst_reg] = old_val - return dword_idx, old_val - - def set_vgpr_u64(self, reg_idx: int, value: int, lane: int = 0) -> None: - lo, hi = split_u64_to_u32(value) - self.set_vgpr(reg_idx, lo, lane=lane) - self.set_vgpr(reg_idx + 1, hi, lane=lane) - - def get_vgpr_u64(self, reg_idx: int, lane: int = 0) -> int: - lo = self.get_vgpr(reg_idx, lane=lane) - hi = self.get_vgpr(reg_idx + 1, lane=lane) - return combine_u32_to_u64(lo, hi) - - def set_lds_u64(self, dword_idx: int, value: int) -> None: - lo, hi = split_u64_to_u32(value) - self.set_lds_dword(dword_idx, lo) - self.set_lds_dword((dword_idx + 1) & (self.lds_dwords - 1), hi) - - def get_lds_u64(self, dword_idx: int) -> int: - lo = self.get_lds_dword(dword_idx) - hi = self.get_lds_dword((dword_idx + 1) & (self.lds_dwords - 1)) - return combine_u32_to_u64(lo, hi) - - def ds_write_b64(self, vaddr_reg: int, vdata_lo_reg: int, offset: int = 0, lane: int = 0) -> tuple[int, int] | None: - if not self.active_lanes[lane]: - return None - vaddr = self.vgprs[lane][vaddr_reg] - _, dword_idx0, _ = calc_lds_byte_offset(vaddr, offset, self.lds_dwords) - dword_idx1 = (dword_idx0 + 1) & (self.lds_dwords - 1) - self.lds[dword_idx0] = self.vgprs[lane][vdata_lo_reg] & MASK32 - self.lds[dword_idx1] = self.vgprs[lane][vdata_lo_reg + 1] & MASK32 - return dword_idx0, dword_idx1 - - def ds_read_b64(self, vdst_lo_reg: int, vaddr_reg: int, offset: int = 0, lane: int = 0) -> tuple[int, int] | None: - if not self.active_lanes[lane]: - return None - vaddr = self.vgprs[lane][vaddr_reg] - _, dword_idx0, _ = calc_lds_byte_offset(vaddr, offset, self.lds_dwords) - dword_idx1 = (dword_idx0 + 1) & (self.lds_dwords - 1) - val_lo = self.lds[dword_idx0] - val_hi = self.lds[dword_idx1] - self.vgprs[lane][vdst_lo_reg] = val_lo - self.vgprs[lane][vdst_lo_reg + 1] = val_hi - return dword_idx0, dword_idx1 - - def ds_xor_b64(self, vaddr_reg: int, vdata_lo_reg: int, offset: int = 0, lane: int = 0) -> tuple[int, int] | None: - """Non-returning 64-bit atomic XOR: updates LDS[idx] and LDS[idx+1], returns (idx0, idx1) or None.""" - if not self.active_lanes[lane]: - return None - vaddr = self.vgprs[lane][vaddr_reg] - vdata_lo = self.vgprs[lane][vdata_lo_reg] - vdata_hi = self.vgprs[lane][vdata_lo_reg + 1] - _, dword_idx0, _ = calc_lds_byte_offset(vaddr, offset, self.lds_dwords) - dword_idx1 = (dword_idx0 + 1) & (self.lds_dwords - 1) - self.lds[dword_idx0] = (self.lds[dword_idx0] ^ vdata_lo) & MASK32 - self.lds[dword_idx1] = (self.lds[dword_idx1] ^ vdata_hi) & MASK32 - return dword_idx0, dword_idx1 - - def ds_xor_rtn_b64( - self, - vdst_lo_reg: int, - vaddr_reg: int, - vdata_lo_reg: int, - offset: int = 0, - lane: int = 0, - ) -> tuple[int, int] | None: - """Returning 64-bit atomic XOR: stores prior 64-bit value into vdst[0:1] and updates LDS[idx:idx+1]. - - Returns (dword_idx0, old_val_u64) if lane active, or None if inactive. - Reads all sources before writing vdst to handle aliasing safely. - """ - if not self.active_lanes[lane]: - return None - vaddr = self.vgprs[lane][vaddr_reg] - vdata_lo = self.vgprs[lane][vdata_lo_reg] - vdata_hi = self.vgprs[lane][vdata_lo_reg + 1] - _, dword_idx0, _ = calc_lds_byte_offset(vaddr, offset, self.lds_dwords) - dword_idx1 = (dword_idx0 + 1) & (self.lds_dwords - 1) - old_lo = self.lds[dword_idx0] - old_hi = self.lds[dword_idx1] - self.lds[dword_idx0] = (old_lo ^ vdata_lo) & MASK32 - self.lds[dword_idx1] = (old_hi ^ vdata_hi) & MASK32 - self.vgprs[lane][vdst_lo_reg] = old_lo - self.vgprs[lane][vdst_lo_reg + 1] = old_hi - return dword_idx0, combine_u32_to_u64(old_lo, old_hi) - - def parse_and_execute(self, instruction_text: str, lane: int = 0) -> int | tuple[int, int] | None: - line = instruction_text.strip() - if not line or line.startswith(";"): - return None - - offset = 0 - m_off = re.search(r"\boffset:(\S+)", line) - if m_off: - offset = int(m_off.group(1), 0) - line = re.sub(r"\boffset:\S+", "", line).strip() - - parts = line.split(None, 1) - op = parts[0] - args_str = parts[1] if len(parts) > 1 else "" - raw_args = [a.strip() for a in args_str.split(",") if a.strip()] - - def reg_num(tok: str) -> int: - cleaned = tok.replace("v", "").replace("[", "").replace("]", "") - if ":" in cleaned: - cleaned = cleaned.split(":")[0] - return int(cleaned) - - if op == "ds_xor_b32": - vaddr = reg_num(raw_args[0]) - vdata = reg_num(raw_args[1]) - return self.ds_xor_b32(vaddr, vdata, offset=offset, lane=lane) - - elif op == "ds_xor_rtn_b32": - vdst = reg_num(raw_args[0]) - vaddr = reg_num(raw_args[1]) - vdata = reg_num(raw_args[2]) - res = self.ds_xor_rtn_b32(vdst, vaddr, vdata, offset=offset, lane=lane) - return res[0] if res else None - - elif op == "ds_write_b32": - vaddr = reg_num(raw_args[0]) - vdata = reg_num(raw_args[1]) - return self.ds_write_b32(vaddr, vdata, offset=offset, lane=lane) - - elif op == "ds_read_b32": - vdst = reg_num(raw_args[0]) - vaddr = reg_num(raw_args[1]) - return self.ds_read_b32(vdst, vaddr, offset=offset, lane=lane) - - elif op == "ds_xor_b64": - vaddr = reg_num(raw_args[0]) - vdata = reg_num(raw_args[1]) - res_b64 = self.ds_xor_b64(vaddr, vdata, offset=offset, lane=lane) - return res_b64[0] if res_b64 else None - - elif op == "ds_xor_rtn_b64": - vdst = reg_num(raw_args[0]) - vaddr = reg_num(raw_args[1]) - vdata = reg_num(raw_args[2]) - res_rtn_b64 = self.ds_xor_rtn_b64(vdst, vaddr, vdata, offset=offset, lane=lane) - return res_rtn_b64[0] if res_rtn_b64 else None - - elif op == "ds_write_b64": - vaddr = reg_num(raw_args[0]) - vdata = reg_num(raw_args[1]) - res_w64 = self.ds_write_b64(vaddr, vdata, offset=offset, lane=lane) - return res_w64[0] if res_w64 else None - - elif op == "ds_read_b64": - vdst = reg_num(raw_args[0]) - vaddr = reg_num(raw_args[1]) - res_r64 = self.ds_read_b64(vdst, vaddr, offset=offset, lane=lane) - return res_r64[0] if res_r64 else None - - else: - raise UnsupportedConstruct(f"Opcode {op} not supported in interpreter") - - def run_simd_wave(self, instruction_text: str) -> list[int | tuple[int, int] | None]: - """Runs the instruction across all lanes in the wavefront in lockstep.""" - return [self.parse_and_execute(instruction_text, lane=lane) for lane in range(self.num_lanes)] - - -class LdsAtomicSpirvInterp: - """Strict semantic interpreter for compute SPIR-V modules exercising LDS atomic XOR.""" - - def __init__(self, spvasm: str): - self.spvasm = spvasm - self.types: dict[str, tuple] = {} - self.constants: dict[str, int | bool] = {} - self.ptr_types: dict[str, tuple[str, str]] = {} - self.var_class: dict[str, str] = {} - self.local_size: tuple[int, int, int] = (1, 1, 1) - self.lds_var: str | None = None - self.lds_size: int = 0 - self.body: list[tuple[str | None, str, list[str], str]] = [] - self._parse() - - def _parse(self) -> None: - in_body = False - for raw in self.spvasm.splitlines(): - line = raw.strip() - if not line: - continue - m = _LINE.match(line) - if not m: - raise UnsupportedConstruct(f"Cannot parse line: {line!r}") - res, op, rest = m.groups() - a = rest.split() - if in_body: - self.body.append((res, op, a, line)) - continue - if op == "OpFunction": - in_body = True - continue - if op == "OpExecutionMode" and len(a) >= 5 and a[1] == "LocalSize": - lx, ly, lz = int(a[2]), int(a[3]), int(a[4]) - if lx < 1 or ly < 1 or lz < 1 or (lx * ly * lz) > 1024: - raise WorkgroupBoundsError(f"Invalid LocalSize {lx}x{ly}x{lz}") - self.local_size = (lx, ly, lz) - continue - if op in _IGNORED: - continue - if op == "OpTypeInt": - if int(a[0]) != 32: - raise UnsupportedConstruct("Only 32-bit int supported in interpreter") - self.types[res] = ("int", int(a[0]), int(a[1])) - elif op == "OpTypeBool": - self.types[res] = ("bool",) - elif op == "OpTypeVector": - self.types[res] = ("vec", a[0], int(a[1])) - elif op == "OpTypeArray": - size = int(self.constants[a[1]]) - self.types[res] = ("arr", a[0], size) - elif op == "OpTypePointer": - self.ptr_types[res] = (a[0], a[1]) - elif op == "OpConstant": - self.constants[res] = int(a[1], 0) & MASK32 - elif op == "OpConstantTrue": - self.constants[res] = True - elif op == "OpConstantFalse": - self.constants[res] = False - elif op == "OpVariable": - cls, pointee = self.ptr_types[a[0]] - if a[1] != cls: - raise UnsupportedConstruct("OpVariable storage class mismatch") - self.var_class[res] = cls - if cls == "Workgroup": - if self.lds_var is not None: - raise UnsupportedConstruct("Multiple Workgroup variables") - self.lds_var = res - arr_ty = self.types[pointee] - if arr_ty[0] != "arr": - raise UnsupportedConstruct("Workgroup variable must be an array") - self.lds_size = arr_ty[2] - elif cls not in ("Output", "Function"): - raise UnsupportedConstruct(f"Unsupported storage class {cls}") - else: - raise UnsupportedConstruct(f"Header opcode {op}") - - def run( - self, - num_invocations: int | None = None, - seed_lds: dict[int, int] | None = None, - lane_inputs: list[dict[str, int]] | None = None, - ) -> tuple[list[int], list[dict[str, int]]]: - """Executes the workgroup and returns (final_lds, outputs_per_lane).""" - lx, ly, lz = self.local_size - total_invocations = lx * ly * lz - count = total_invocations if num_invocations is None else min(num_invocations, total_invocations) - - lds = [0] * self.lds_size - if seed_lds: - for idx, val in seed_lds.items(): - if 0 <= idx < self.lds_size: - lds[idx] = val & MASK32 - - lane_outputs: list[dict[str, int]] = [] - for lidx in range(count): - inputs = lane_inputs[lidx] if lane_inputs and lidx < len(lane_inputs) else {} - out = self._run_lane(lidx, lds, inputs) - lane_outputs.append(out) - - return list(lds), lane_outputs - - def _run_lane(self, lidx: int, lds: list[int], inputs: dict[str, int]) -> dict[str, int]: - values: dict[str, int | bool] = dict(self.constants) - values.update(inputs) - var_box: dict[str, list[int]] = {} - pointers: dict[str, tuple[str, list[int], int | None]] = {} - outputs: list[str] = [] - - if self.lds_var: - pointers[self.lds_var] = ("lds", lds, None) - - for res, cls in self.var_class.items(): - if cls == "Output": - var_box[res] = [0] - pointers[res] = ("out", var_box[res], 0) - outputs.append(res) - elif cls == "Function": - var_box[res] = [0] - pointers[res] = ("fn", var_box[res], 0) - - def val(x: str) -> int: - if x in values: - return values[x] # type: ignore - raise UnsupportedConstruct(f"Undefined identifier {x}") - - for res, op, a, _ in self.body: - if op in _IGNORED or op in ("OpBranch", "OpBranchConditional"): - continue - if op == "OpVariable": - cls, _ = self.ptr_types[a[0]] - if cls != "Function": - raise UnsupportedConstruct("Non-Function variable in body") - var_box[res] = [val(a[2]) if len(a) > 2 else 0] - pointers[res] = ("fn", var_box[res], 0) - elif op == "OpAccessChain": - base = a[1] - if base not in pointers: - raise UnsupportedConstruct(f"OpAccessChain on non-pointer {base}") - ptag = pointers[base][0] - if ptag == "lds": - idx = val(a[2]) - if not (0 <= idx < len(lds)): - raise WorkgroupBoundsError(f"LDS access out of bounds: {idx} >= {len(lds)}") - pointers[res] = ("lds", lds, idx) - elif ptag in ("out", "fn"): - pointers[res] = pointers[base] - else: - raise UnsupportedConstruct(f"Access chain on {ptag}") - elif op == "OpLoad": - ptr = pointers[a[1]] - ptag = ptr[0] - if ptag in ("lds", "out", "fn"): - idx_val = ptr[2] - values[res] = ptr[1][idx_val] & MASK32 - elif op == "OpStore": - ptr = pointers[a[0]] - v = val(a[1]) & MASK32 - ptag = ptr[0] - if ptag in ("lds", "out", "fn"): - idx_val = ptr[2] - ptr[1][idx_val] = v - elif op == "OpAtomicXor": - # %res = OpAtomicXor %type %ptr %scope %semantics %val - ptr = pointers[a[1]] - ptag = ptr[0] - if ptag != "lds": - raise UnsupportedConstruct(f"OpAtomicXor on non-LDS pointer {ptag}") - mask_val = val(a[4]) & MASK32 - idx_val = ptr[2] - old = ptr[1][idx_val] & MASK32 - ptr[1][idx_val] = (old ^ mask_val) & MASK32 - values[res] = old - elif op == "OpIAdd": - values[res] = (val(a[1]) + val(a[2])) & MASK32 - elif op == "OpISub": - values[res] = (val(a[1]) - val(a[2])) & MASK32 - elif op == "OpShiftRightLogical": - sh = val(a[2]) - if sh >= 32: - raise UnsupportedConstruct("Shift >= 32") - values[res] = (val(a[1]) >> sh) & MASK32 - elif op == "OpShiftLeftLogical": - sh = val(a[2]) - if sh >= 32: - raise UnsupportedConstruct("Shift >= 32") - values[res] = (val(a[1]) << sh) & MASK32 - elif op == "OpBitwiseAnd": - values[res] = val(a[1]) & val(a[2]) & MASK32 - elif op == "OpBitwiseOr": - values[res] = (val(a[1]) | val(a[2])) & MASK32 - elif op == "OpBitwiseXor": - values[res] = (val(a[1]) ^ val(a[2])) & MASK32 - elif op == "OpSelect": - cond = val(a[1]) - values[res] = val(a[2]) if cond else val(a[3]) - elif op == "OpCopyObject": - values[res] = val(a[1]) - elif op == "OpBitcast": - values[res] = val(a[1]) & MASK32 - else: - raise UnsupportedConstruct(f"Opcode {op} not modelled in body") - - return {name: var_box[name][0] & MASK32 for name in outputs} - - -class TestAtomicXorReferenceMath(unittest.TestCase): - """Verifies 32-bit and 64-bit atomic XOR math, truth tables, and algebraic properties.""" - - def test_xor_truth_tables_b32(self): - all_zeros = 0x00000000 - all_ones = 0xFFFFFFFF - alt_a = 0x55555555 - alt_b = 0xAAAAAAAA - - old, mem = reference_atomic_xor_b32(all_zeros, all_zeros) - self.assertEqual(old, all_zeros) - self.assertEqual(mem, all_zeros) - - old, mem = reference_atomic_xor_b32(all_zeros, all_ones) - self.assertEqual(old, all_zeros) - self.assertEqual(mem, all_ones) - - old, mem = reference_atomic_xor_b32(all_ones, all_zeros) - self.assertEqual(old, all_ones) - self.assertEqual(mem, all_ones) - - old, mem = reference_atomic_xor_b32(all_ones, all_ones) - self.assertEqual(old, all_ones) - self.assertEqual(mem, all_zeros) - - old, mem = reference_atomic_xor_b32(alt_a, alt_b) - self.assertEqual(old, alt_a) - self.assertEqual(mem, all_ones) - - def test_identity_and_complement_properties(self): - test_values = [ - 0x00000000, - 0x00000001, - 0x12345678, - 0x7FFFFFFF, - 0x80000000, - 0xFFFFFFFF, - 0xDEADBEEF, - ] - for val in test_values: - with self.subTest(val=hex(val)): - old, mem = reference_atomic_xor_b32(val, 0) - self.assertEqual(old, val) - self.assertEqual(mem, val) - - old, mem = reference_atomic_xor_b32(val, MASK32) - self.assertEqual(old, val) - self.assertEqual(mem, (~val) & MASK32) - - def test_involution_property_b32(self): - cases = [ - (0x12345678, 0xA5A5A5A5), - (0x00000000, 0xFFFFFFFF), - (0xFFFFFFFF, 0x12345678), - (0xCAFEBABE, 0x0F0F0F0F), - (0x80000000, 0x7FFFFFFF), - ] - for initial, key in cases: - with self.subTest(initial=hex(initial), key=hex(key)): - old1, step1 = reference_atomic_xor_b32(initial, key) - self.assertEqual(old1, initial) - self.assertNotEqual(step1, initial if key != 0 else -1) - - old2, step2 = reference_atomic_xor_b32(step1, key) - self.assertEqual(old2, step1) - self.assertEqual(step2, initial) - - def test_commutativity_and_associativity_b32(self): - a, b = 0x3F2A1C8E, 0x9D4E7B01 - _, ab = reference_atomic_xor_b32(a, b) - _, ba = reference_atomic_xor_b32(b, a) - self.assertEqual(ab, ba) - - c = 0x55AA33CC - _, step_ab = reference_atomic_xor_b32(a, b) - _, ab_c = reference_atomic_xor_b32(step_ab, c) - - _, step_bc = reference_atomic_xor_b32(b, c) - _, a_bc = reference_atomic_xor_b32(a, step_bc) - self.assertEqual(ab_c, a_bc) - - def test_multi_party_xor_checksum_accumulation(self): - lane_values = [1 << bit for bit in range(32)] - parity = 0 - for val in lane_values: - _, parity = reference_atomic_xor_b32(parity, val) - self.assertEqual(parity, MASK32) - - for val in lane_values: - _, parity = reference_atomic_xor_b32(parity, val) - self.assertEqual(parity, 0) - - def test_reference_atomic_xor_b64_properties(self): - init = 0x0123456789ABCDEF - mask = 0xFEDCBA9876543210 - old, mem = reference_atomic_xor_b64(init, mask) - self.assertEqual(old, init) - self.assertEqual(mem, init ^ mask) - - old2, restored = reference_atomic_xor_b64(mem, mask) - self.assertEqual(old2, mem) - self.assertEqual(restored, init) - - _, comp = reference_atomic_xor_b64(init, MASK64) - self.assertEqual(comp, (~init) & MASK64) - - def test_split_and_combine_u64_u32(self): - v64 = 0xFEDCBA9876543210 - lo, hi = split_u64_to_u32(v64) - self.assertEqual(lo, 0x76543210) - self.assertEqual(hi, 0xFEDCBA98) - self.assertEqual(combine_u32_to_u64(lo, hi), v64) - - -class TestLdsAddressingAndOffsets(unittest.TestCase): - """Verifies single and dual LDS byte offsets, dword truncation, st64 strides, and wrapping.""" - - def test_aligned_dword_addressing(self): - lds_dwords = 256 - for dword in (0, 1, 2, 16, 64, 127, 255): - byte_addr = dword * 4 - eff, dword_idx, byte_pos = calc_lds_byte_offset(byte_addr, 0, lds_dwords) - self.assertEqual(eff, byte_addr) - self.assertEqual(dword_idx, dword) - self.assertEqual(byte_pos, 0) - - def test_unaligned_byte_truncation(self): - lds_dwords = 128 - base_aligned = 64 - for b in (0, 1, 2, 3): - eff, dword_idx, byte_pos = calc_lds_byte_offset(base_aligned, b, lds_dwords) - self.assertEqual(eff, base_aligned + b) - self.assertEqual(dword_idx, 16) - self.assertEqual(byte_pos, b) - - def test_offset_16bit_masking(self): - lds_dwords = 512 - eff, dword_idx, byte_pos = calc_lds_byte_offset(0, 0x10008, lds_dwords) - self.assertEqual(eff, 8) - self.assertEqual(dword_idx, 2) - self.assertEqual(byte_pos, 0) - - def test_dual_offset_unit_strides(self): - (eff0, idx0), (eff1, idx1) = calc_lds_dual_offsets(0, 3, 10, lds_dwords=1024, st64=False) - self.assertEqual(eff0, 12) - self.assertEqual(idx0, 3) - self.assertEqual(eff1, 40) - self.assertEqual(idx1, 10) - - def test_dual_offset_st64_stride(self): - (eff0, idx0), (eff1, idx1) = calc_lds_dual_offsets(0, 2, 5, lds_dwords=1024, st64=True) - self.assertEqual(eff0, 512) - self.assertEqual(idx0, 128) - self.assertEqual(eff1, 1280) - self.assertEqual(idx1, 320) - - def test_boundary_power_of_two_wrapping(self): - lds_dwords = 64 - _, idx0, _ = calc_lds_byte_offset(256, 0, lds_dwords) - self.assertEqual(idx0, 0) - _, idx1, _ = calc_lds_byte_offset(256, 4, lds_dwords) - self.assertEqual(idx1, 1) - _, idx_wrap, _ = calc_lds_byte_offset(0xFFFFFFFC, 4, lds_dwords) - self.assertEqual(idx_wrap, 0) - - -class TestLdsSemanticInterpreterB32(unittest.TestCase): - """Verifies 32-bit LDS atomic XOR execution in multi-lane SIMD interpreter.""" - - def setUp(self): - self.interp = LdsSemanticInterpreter(lds_dwords=256, num_vgprs=64, num_lanes=32) - - def test_ds_xor_b32_non_returning_mutates_lds_only(self): - self.interp.set_lds_dword(5, 0xAA55AA55) - self.interp.set_vgpr(0, 20) # byte 20 -> dword 5 - self.interp.set_vgpr(1, 0x00FF00FF) # mask - self.interp.set_vgpr(2, 0xDEADBEEF) # dummy register - - res = self.interp.ds_xor_b32(vaddr_reg=0, vdata_reg=1, offset=0, lane=0) - self.assertEqual(res, 5) - # LDS[5] updated with XOR - self.assertEqual(self.interp.get_lds_dword(5), 0xAA55AA55 ^ 0x00FF00FF) - # Registers preserved - self.assertEqual(self.interp.get_vgpr(0), 20) - self.assertEqual(self.interp.get_vgpr(1), 0x00FF00FF) - self.assertEqual(self.interp.get_vgpr(2), 0xDEADBEEF) - - def test_ds_xor_rtn_b32_basic_returns_pre_atomic_value(self): - self.interp.set_lds_dword(7, 0x12345678) - self.interp.set_vgpr(0, 28) # byte 28 -> dword 7 - self.interp.set_vgpr(1, 0x000000FF) # mask - self.interp.set_vgpr(2, 0) # vdst - - res = self.interp.ds_xor_rtn_b32(vdst_reg=2, vaddr_reg=0, vdata_reg=1, offset=0, lane=0) - self.assertEqual(res, (7, 0x12345678)) - # vdst receives old memory value - self.assertEqual(self.interp.get_vgpr(2), 0x12345678) - # LDS memory receives updated value - self.assertEqual(self.interp.get_lds_dword(7), 0x12345687) - - def test_ds_xor_rtn_b32_with_offset(self): - self.interp.set_lds_dword(8, 0xF0F0F0F0) - self.interp.set_vgpr(0, 16) # byte 16 (dword 4) - self.interp.set_vgpr(1, 0x0F0F0F0F) # mask - # offset = 16 bytes (+4 dwords) -> target is dword 8 - res = self.interp.ds_xor_rtn_b32(vdst_reg=3, vaddr_reg=0, vdata_reg=1, offset=16, lane=0) - self.assertEqual(res, (8, 0xF0F0F0F0)) - self.assertEqual(self.interp.get_vgpr(3), 0xF0F0F0F0) - self.assertEqual(self.interp.get_lds_dword(8), 0xFFFFFFFF) - - def test_ds_xor_rtn_b32_involution_chain(self): - initial = 0xCAFEBABE - key = 0x5A5A5A5A - self.interp.set_lds_dword(3, initial) - self.interp.set_vgpr(0, 12) # dword 3 - self.interp.set_vgpr(1, key) - - # First operation: flips bits - res1 = self.interp.ds_xor_rtn_b32(vdst_reg=4, vaddr_reg=0, vdata_reg=1, offset=0, lane=0) - self.assertEqual(res1, (3, initial)) - self.assertEqual(self.interp.get_vgpr(4), initial) - self.assertEqual(self.interp.get_lds_dword(3), initial ^ key) - - # Second operation with same key: restores original - res2 = self.interp.ds_xor_rtn_b32(vdst_reg=5, vaddr_reg=0, vdata_reg=1, offset=0, lane=0) - self.assertEqual(res2, (3, initial ^ key)) - self.assertEqual(self.interp.get_vgpr(5), initial ^ key) - self.assertEqual(self.interp.get_lds_dword(3), initial) - - def test_inactive_lane_under_exec_mask(self): - self.interp.set_lds_dword(2, 0x5555) - self.interp.set_vgpr(0, 8, lane=1) - self.interp.set_vgpr(1, 0xFFFF, lane=1) - self.interp.set_vgpr(5, 0xDEAD, lane=1) - self.interp.set_lane_active(1, False) - - res = self.interp.ds_xor_rtn_b32(vdst_reg=5, vaddr_reg=0, vdata_reg=1, lane=1) - self.assertIsNone(res) - # Inactive lane must preserve both LDS memory and destination VGPR - self.assertEqual(self.interp.get_vgpr(5, lane=1), 0xDEAD) - self.assertEqual(self.interp.get_lds_dword(2), 0x5555) - - def test_multi_lane_divergent_destinations(self): - # 32 lanes, each lane targeting its own dword slot (lane 0 -> dword 0, etc.) - for lane in range(32): - self.interp.set_lds_dword(lane, 0x1000 + lane) - self.interp.set_vgpr(0, lane * 4, lane=lane) - self.interp.set_vgpr(1, 0x00FF, lane=lane) - self.interp.set_vgpr(2, 0, lane=lane) - - for lane in range(32): - self.interp.ds_xor_rtn_b32(vdst_reg=2, vaddr_reg=0, vdata_reg=1, offset=0, lane=lane) - - for lane in range(32): - self.assertEqual(self.interp.get_vgpr(2, lane=lane), 0x1000 + lane) - self.assertEqual(self.interp.get_lds_dword(lane), (0x1000 + lane) ^ 0x00FF) - - def test_multi_lane_convergent_single_destination(self): - # All 32 lanes target dword 10, each lane toggling exactly 1 bit - self.interp.set_lds_dword(10, 0x00000000) - for lane in range(32): - self.interp.set_vgpr(0, 40, lane=lane) # byte 40 -> dword 10 - self.interp.set_vgpr(1, 1 << lane, lane=lane) - self.interp.set_vgpr(2, 0, lane=lane) - - for lane in range(32): - self.interp.ds_xor_rtn_b32(vdst_reg=2, vaddr_reg=0, vdata_reg=1, offset=0, lane=lane) - - # Final memory has all 32 bits toggled - self.assertEqual(self.interp.get_lds_dword(10), MASK32) - - def test_vdst_aliasing_vdata(self): - # vdst is register 1, which also holds vdata - self.interp.set_lds_dword(4, 0x11112222) - self.interp.set_vgpr(0, 16) # dword 4 - self.interp.set_vgpr(1, 0x33334444) # vdata in v1 - - # vdst=1 aliases vdata=1 - self.interp.ds_xor_rtn_b32(vdst_reg=1, vaddr_reg=0, vdata_reg=1, lane=0) - # LDS gets old ^ initial vdata - self.assertEqual(self.interp.get_lds_dword(4), 0x11112222 ^ 0x33334444) - # v1 receives old value 0x11112222 - self.assertEqual(self.interp.get_vgpr(1), 0x11112222) - - def test_vdst_aliasing_vaddr(self): - # vdst is register 0, which also holds vaddr - self.interp.set_lds_dword(6, 0x88889999) - self.interp.set_vgpr(0, 24) # vaddr = byte 24 (dword 6) - self.interp.set_vgpr(1, 0x00001111) - - self.interp.ds_xor_rtn_b32(vdst_reg=0, vaddr_reg=0, vdata_reg=1, lane=0) - self.assertEqual(self.interp.get_lds_dword(6), 0x88889999 ^ 0x00001111) - self.assertEqual(self.interp.get_vgpr(0), 0x88889999) - - def test_assembly_parser_dispatch_b32(self): - self.interp.set_lds_dword(3, 0xAAAA) - self.interp.set_vgpr(0, 12) - self.interp.set_vgpr(1, 0x5555) - - self.interp.parse_and_execute("ds_xor_b32 v0, v1 offset:0") - self.assertEqual(self.interp.get_lds_dword(3), 0xFFFF) - - self.interp.set_vgpr(2, 0) - self.interp.parse_and_execute("ds_xor_rtn_b32 v2, v0, v1 offset:0") - self.assertEqual(self.interp.get_vgpr(2), 0xFFFF) - self.assertEqual(self.interp.get_lds_dword(3), 0xAAAA) - - def test_run_simd_wave_with_exec_mask(self): - # Lanes 0..3 active, lanes 4..7 inactive - self.interp.set_exec_mask(0x0F) - for lane in range(8): - self.interp.set_vgpr(0, lane * 4, lane=lane) - self.interp.set_vgpr(1, 0xFF, lane=lane) - self.interp.set_vgpr(2, 0xAA, lane=lane) - - results = self.interp.run_simd_wave("ds_xor_rtn_b32 v2, v0, v1") - for lane in range(4): - self.assertIsNotNone(results[lane]) - self.assertEqual(self.interp.get_vgpr(2, lane=lane), 0) - self.assertEqual(self.interp.get_lds_dword(lane), 0xFF) - for lane in range(4, 8): - self.assertIsNone(results[lane]) - self.assertEqual(self.interp.get_vgpr(2, lane=lane), 0xAA) - self.assertEqual(self.interp.get_lds_dword(lane), 0) - - -class TestSpirvAtomicXorInterpreterB32(unittest.TestCase): - """Verifies SPIR-V compute execution and rdna2spirv emission of OpAtomicXor.""" - - def test_spirv_ds_xor_b32_non_returning(self): - spvasm = """ -OpCapability Shader -OpMemoryModel Logical GLSL450 -OpEntryPoint GLCompute %main "main" -OpExecutionMode %main LocalSize 1 1 1 -%uint = OpTypeInt 32 0 -%c64 = OpConstant %uint 64 -%c2 = OpConstant %uint 2 -%c0 = OpConstant %uint 0 -%c4 = OpConstant %uint 4 -%c_mask = OpConstant %uint 255 -%lds_arr = OpTypeArray %uint %c64 -%_ptr_WG_lds = OpTypePointer Workgroup %lds_arr -%_ptr_WG_uint = OpTypePointer Workgroup %uint -%lds = OpVariable %_ptr_WG_lds Workgroup -%void = OpTypeVoid -%fn = OpTypeFunction %void -%main = OpFunction %void None %fn -%entry = OpLabel -%ptr = OpAccessChain %_ptr_WG_uint %lds %c4 -%dummy = OpAtomicXor %uint %ptr %c2 %c0 %c_mask -OpReturn -OpFunctionEnd -""" - interp = LdsAtomicSpirvInterp(spvasm) - final_lds, _ = interp.run(seed_lds={4: 0x1234}) - self.assertEqual(final_lds[4], 0x1234 ^ 0xFF) - - def test_spirv_ds_xor_rtn_b32_returning(self): - spvasm = """ -OpCapability Shader -OpMemoryModel Logical GLSL450 -OpEntryPoint GLCompute %main "main" -OpExecutionMode %main LocalSize 1 1 1 -%uint = OpTypeInt 32 0 -%c32 = OpConstant %uint 32 -%c2 = OpConstant %uint 2 -%c0 = OpConstant %uint 0 -%c1 = OpConstant %uint 1 -%c_mask = OpConstant %uint 4095 -%lds_arr = OpTypeArray %uint %c32 -%_ptr_WG_lds = OpTypePointer Workgroup %lds_arr -%_ptr_WG_uint = OpTypePointer Workgroup %uint -%_ptr_Out_uint = OpTypePointer Output %uint -%lds = OpVariable %_ptr_WG_lds Workgroup -%out_reg = OpVariable %_ptr_Out_uint Output -%void = OpTypeVoid -%fn = OpTypeFunction %void -%main = OpFunction %void None %fn -%entry = OpLabel -%ptr = OpAccessChain %_ptr_WG_uint %lds %c1 -%old = OpAtomicXor %uint %ptr %c2 %c0 %c_mask -OpStore %out_reg %old -OpReturn -OpFunctionEnd -""" - interp = LdsAtomicSpirvInterp(spvasm) - final_lds, lane_outputs = interp.run(seed_lds={1: 0xABCD}) - self.assertEqual(final_lds[1], 0xABCD ^ 4095) - self.assertEqual(lane_outputs[0]["%out_reg"], 0xABCD) - - def test_spirv_multi_lane_execution(self): - spvasm = """ -OpCapability Shader -OpMemoryModel Logical GLSL450 -OpEntryPoint GLCompute %main "main" -OpExecutionMode %main LocalSize 4 1 1 -%uint = OpTypeInt 32 0 -%c16 = OpConstant %uint 16 -%c2 = OpConstant %uint 2 -%c0 = OpConstant %uint 0 -%c_toggle = OpConstant %uint 15 -%lds_arr = OpTypeArray %uint %c16 -%_ptr_WG_lds = OpTypePointer Workgroup %lds_arr -%_ptr_WG_uint = OpTypePointer Workgroup %uint -%lds = OpVariable %_ptr_WG_lds Workgroup -%void = OpTypeVoid -%fn = OpTypeFunction %void -%main = OpFunction %void None %fn -%entry = OpLabel -%ptr = OpAccessChain %_ptr_WG_uint %lds %c0 -%res = OpAtomicXor %uint %ptr %c2 %c0 %c_toggle -OpReturn -OpFunctionEnd -""" - interp = LdsAtomicSpirvInterp(spvasm) - final_lds, _ = interp.run(seed_lds={0: 0}) - self.assertEqual(final_lds[0], 0) - - final_lds3, _ = interp.run(num_invocations=3, seed_lds={0: 0}) - self.assertEqual(final_lds3[0], 15) - - def test_rdna2spirv_translate_b32_emission(self): - spv = translate_cs_listing([ - "ds_xor_b32 v0, v1", - "ds_xor_rtn_b32 v2, v0, v1", - ]) - lines = [ln.strip() for ln in spv.splitlines() if "OpAtomicXor" in ln] - self.assertEqual(len(lines), 2) - for ln in lines: - self.assertIn("OpAtomicXor", ln) - self.assertIn("%uint", ln) - self.assertIn("%c2", ln) # Workgroup scope - self.assertIn("%c0", ln) # Relaxed semantics - - -class TestLdsSemanticInterpreterB64(unittest.TestCase): - """Verifies 64-bit LDS atomic XOR execution in multi-lane SIMD interpreter.""" - - def setUp(self): - self.interp = LdsSemanticInterpreter(lds_dwords=256, num_vgprs=64, num_lanes=32) - - def test_ds_xor_b64_non_returning_mutates_both_dwords(self): - self.interp.set_lds_dword(10, 0x12345678) - self.interp.set_lds_dword(11, 0x9ABCDEF0) - self.interp.set_vgpr(0, 40) # byte 40 -> dword 10 - self.interp.set_vgpr(2, 0x000000FF) # data lo - self.interp.set_vgpr(3, 0x00FF0000) # data hi - self.interp.set_vgpr(4, 0xDEADBEEF) # dummy - - res = self.interp.ds_xor_b64(vaddr_reg=0, vdata_lo_reg=2, offset=0, lane=0) - self.assertEqual(res, (10, 11)) - self.assertEqual(self.interp.get_lds_dword(10), 0x12345678 ^ 0x000000FF) - self.assertEqual(self.interp.get_lds_dword(11), 0x9ABCDEF0 ^ 0x00FF0000) - self.assertEqual(self.interp.get_vgpr(0), 40) - self.assertEqual(self.interp.get_vgpr(2), 0x000000FF) - self.assertEqual(self.interp.get_vgpr(3), 0x00FF0000) - self.assertEqual(self.interp.get_vgpr(4), 0xDEADBEEF) - - def test_ds_xor_rtn_b64_returns_prior_64bit_value(self): - init_val = 0xCAFEBABE_DEADBEEF - mask_val = 0x0F0F0F0F_F0F0F0F0 - self.interp.set_lds_u64(12, init_val) - self.interp.set_vgpr(0, 48) # byte 48 -> dword 12 - self.interp.set_vgpr_u64(2, mask_val) - self.interp.set_vgpr_u64(4, 0) # vdst in v[4:5] - - res = self.interp.ds_xor_rtn_b64(vdst_lo_reg=4, vaddr_reg=0, vdata_lo_reg=2, offset=0, lane=0) - self.assertEqual(res, (12, init_val)) - self.assertEqual(self.interp.get_vgpr_u64(4), init_val) - self.assertEqual(self.interp.get_lds_u64(12), init_val ^ mask_val) - - def test_ds_xor_rtn_b64_with_offset(self): - init_val = 0x11112222_33334444 - mask_val = 0x55555555_AAAAAAAA - # vaddr = 32 (dword 8), offset = 24 bytes (6 dwords) -> target is dword 14 - self.interp.set_lds_u64(14, init_val) - self.interp.set_vgpr(0, 32) - self.interp.set_vgpr_u64(2, mask_val) - self.interp.set_vgpr_u64(6, 0) - - res = self.interp.ds_xor_rtn_b64(vdst_lo_reg=6, vaddr_reg=0, vdata_lo_reg=2, offset=24, lane=0) - self.assertEqual(res, (14, init_val)) - self.assertEqual(self.interp.get_vgpr_u64(6), init_val) - self.assertEqual(self.interp.get_lds_u64(14), init_val ^ mask_val) - - def test_ds_xor_rtn_b64_involution_chain(self): - init_val = 0xFEDCBA98_76543210 - key_val = 0x13579BDF_02468ACE - self.interp.set_lds_u64(20, init_val) - self.interp.set_vgpr(0, 80) - self.interp.set_vgpr_u64(2, key_val) - - res1 = self.interp.ds_xor_rtn_b64(vdst_lo_reg=4, vaddr_reg=0, vdata_lo_reg=2, offset=0, lane=0) - self.assertEqual(res1, (20, init_val)) - self.assertEqual(self.interp.get_vgpr_u64(4), init_val) - self.assertEqual(self.interp.get_lds_u64(20), init_val ^ key_val) - - res2 = self.interp.ds_xor_rtn_b64(vdst_lo_reg=6, vaddr_reg=0, vdata_lo_reg=2, offset=0, lane=0) - self.assertEqual(res2, (20, init_val ^ key_val)) - self.assertEqual(self.interp.get_vgpr_u64(6), init_val ^ key_val) - self.assertEqual(self.interp.get_lds_u64(20), init_val) - - def test_ds_xor_rtn_b64_vdst_aliasing_vdata(self): - init_val = 0x88887777_66665555 - data_val = 0x11112222_33334444 - self.interp.set_lds_u64(16, init_val) - self.interp.set_vgpr(0, 64) - self.interp.set_vgpr_u64(2, data_val) - - # vdst is v[2:3], which aliases vdata in v[2:3] - res = self.interp.ds_xor_rtn_b64(vdst_lo_reg=2, vaddr_reg=0, vdata_lo_reg=2, lane=0) - self.assertEqual(res, (16, init_val)) - self.assertEqual(self.interp.get_lds_u64(16), init_val ^ data_val) - self.assertEqual(self.interp.get_vgpr_u64(2), init_val) - - def test_ds_xor_rtn_b64_vdst_aliasing_vaddr(self): - init_val = 0xAAAABBBB_CCCCDDDD - data_val = 0x0000FFFF_0000FFFF - self.interp.set_lds_u64(18, init_val) - self.interp.set_vgpr(0, 72) - self.interp.set_vgpr_u64(2, data_val) - - # vdst is v[0:1], aliasing vaddr in v0 - res = self.interp.ds_xor_rtn_b64(vdst_lo_reg=0, vaddr_reg=0, vdata_lo_reg=2, lane=0) - self.assertEqual(res, (18, init_val)) - self.assertEqual(self.interp.get_lds_u64(18), init_val ^ data_val) - self.assertEqual(self.interp.get_vgpr_u64(0), init_val) - - def test_ds_xor_b64_inactive_lane_under_exec_mask(self): - self.interp.set_lds_u64(4, 0x12345678_9ABCDEF0) - self.interp.set_vgpr(0, 16, lane=2) - self.interp.set_vgpr_u64(2, 0xFFFFFFFF_FFFFFFFF, lane=2) - self.interp.set_vgpr_u64(4, 0xFEEDFACE_CAFEBABE, lane=2) - self.interp.set_lane_active(2, False) - - res = self.interp.ds_xor_rtn_b64(vdst_lo_reg=4, vaddr_reg=0, vdata_lo_reg=2, lane=2) - self.assertIsNone(res) - self.assertEqual(self.interp.get_vgpr_u64(4, lane=2), 0xFEEDFACE_CAFEBABE) - self.assertEqual(self.interp.get_lds_u64(4), 0x12345678_9ABCDEF0) - - def test_ds_xor_rtn_b64_simd_wave_divergent(self): - # 32 lanes, each lane targeting its own 64-bit element (lane * 8 bytes = dword 2 * lane) - for lane in range(32): - val = (0x1000_0000_0000 + lane * 0x1_0000_0001) & MASK64 - self.interp.set_lds_u64(lane * 2, val) - self.interp.set_vgpr(0, lane * 8, lane=lane) - self.interp.set_vgpr_u64(2, 0x00FF00FF_00FF00FF, lane=lane) - self.interp.set_vgpr_u64(4, 0, lane=lane) - - for lane in range(32): - self.interp.ds_xor_rtn_b64(vdst_lo_reg=4, vaddr_reg=0, vdata_lo_reg=2, offset=0, lane=lane) - - for lane in range(32): - orig_val = (0x1000_0000_0000 + lane * 0x1_0000_0001) & MASK64 - self.assertEqual(self.interp.get_vgpr_u64(4, lane=lane), orig_val) - self.assertEqual(self.interp.get_lds_u64(lane * 2), orig_val ^ 0x00FF00FF_00FF00FF) - - def test_ds_xor_rtn_b64_simd_wave_convergent_shared_word(self): - # 32 lanes all targeting dword 30 (64-bit), each flipping bit lane and bit lane + 32 - self.interp.set_lds_u64(30, 0) - for lane in range(32): - self.interp.set_vgpr(0, 120, lane=lane) # byte 120 -> dword 30 - mask_64 = (1 << lane) | (1 << (lane + 32)) - self.interp.set_vgpr_u64(2, mask_64, lane=lane) - self.interp.set_vgpr_u64(4, 0, lane=lane) - - for lane in range(32): - self.interp.ds_xor_rtn_b64(vdst_lo_reg=4, vaddr_reg=0, vdata_lo_reg=2, offset=0, lane=lane) - - self.assertEqual(self.interp.get_lds_u64(30), MASK64) - - def test_assembly_parser_dispatch_b64(self): - self.interp.set_lds_u64(8, 0xAAAAAAAA_55555555) - self.interp.set_vgpr(0, 32) - self.interp.set_vgpr_u64(2, 0x55555555_AAAAAAAA) - - self.interp.parse_and_execute("ds_xor_b64 v0, v[2:3] offset:0") - self.assertEqual(self.interp.get_lds_u64(8), MASK64) - - self.interp.set_vgpr_u64(4, 0) - self.interp.parse_and_execute("ds_xor_rtn_b64 v[4:5], v0, v[2:3] offset:0") - self.assertEqual(self.interp.get_vgpr_u64(4), MASK64) - self.assertEqual(self.interp.get_lds_u64(8), 0xAAAAAAAA_55555555) - - # Test ds_write_b64 and ds_read_b64 through parser - self.interp.set_vgpr_u64(6, 0xCAFEBABE_12345678) - self.interp.parse_and_execute("ds_write_b64 v0, v[6:7] offset:8") - self.assertEqual(self.interp.get_lds_u64(10), 0xCAFEBABE_12345678) - - self.interp.set_vgpr_u64(8, 0) - self.interp.parse_and_execute("ds_read_b64 v[8:9], v0 offset:8") - self.assertEqual(self.interp.get_vgpr_u64(8), 0xCAFEBABE_12345678) - - def test_run_simd_wave_b64_with_exec_mask(self): - # Lanes 0..3 active (0x0F), lanes 4..7 inactive - self.interp.set_exec_mask(0x0F) - for lane in range(8): - self.interp.set_vgpr(0, lane * 8, lane=lane) - self.interp.set_vgpr_u64(2, 0xFFFFFFFF_00000000, lane=lane) - self.interp.set_vgpr_u64(4, 0x55555555_55555555, lane=lane) - - results = self.interp.run_simd_wave("ds_xor_rtn_b64 v[4:5], v0, v[2:3]") - for lane in range(4): - self.assertIsNotNone(results[lane]) - self.assertEqual(self.interp.get_vgpr_u64(4, lane=lane), 0) - self.assertEqual(self.interp.get_lds_u64(lane * 2), 0xFFFFFFFF_00000000) - for lane in range(4, 8): - self.assertIsNone(results[lane]) - self.assertEqual(self.interp.get_vgpr_u64(4, lane=lane), 0x55555555_55555555) - self.assertEqual(self.interp.get_lds_u64(lane * 2), 0) - - -class TestLdsOffsetWrappingAndStrides(unittest.TestCase): - """Verifies edge-case address calculation, 64-bit element wrapping, and st64 dual offsets.""" - - def test_64bit_boundary_crossing_wrap(self): - interp = LdsSemanticInterpreter(lds_dwords=64, num_vgprs=16, num_lanes=1) - # LDS has 64 dwords (indices 0..63). - # A 64-bit element at dword 63 spans dword 63 and dword (63+1)%64 = 0. - interp.set_lds_dword(63, 0x11111111) - interp.set_lds_dword(0, 0x22222222) - interp.set_vgpr(0, 63 * 4) # byte address 252 -> dword 63 - interp.set_vgpr(2, 0xF0F0F0F0) - interp.set_vgpr(3, 0x0F0F0F0F) - interp.set_vgpr_u64(4, 0) - - res = interp.ds_xor_rtn_b64(vdst_lo_reg=4, vaddr_reg=0, vdata_lo_reg=2, offset=0, lane=0) - self.assertEqual(res, (63, combine_u32_to_u64(0x11111111, 0x22222222))) - self.assertEqual(interp.get_vgpr(4), 0x11111111) - self.assertEqual(interp.get_vgpr(5), 0x22222222) - self.assertEqual(interp.get_lds_dword(63), 0x11111111 ^ 0xF0F0F0F0) - self.assertEqual(interp.get_lds_dword(0), 0x22222222 ^ 0x0F0F0F0F) - - def test_large_offset_overflow_wrap(self): - interp = LdsSemanticInterpreter(lds_dwords=128, num_vgprs=16, num_lanes=1) - # 32-bit unsigned wrapping: 0xFFFFFFFC + 8 = 0x00000004 -> dword 1 - interp.set_lds_dword(1, 0x55555555) - interp.set_lds_dword(2, 0xAAAAAAAA) - interp.set_vgpr(0, 0xFFFFFFFC) - interp.set_vgpr(2, 0x000000FF) - interp.set_vgpr(3, 0x00FF0000) - - interp.ds_xor_b64(vaddr_reg=0, vdata_lo_reg=2, offset=8, lane=0) - self.assertEqual(interp.get_lds_dword(1), 0x55555555 ^ 0x000000FF) - self.assertEqual(interp.get_lds_dword(2), 0xAAAAAAAA ^ 0x00FF0000) - - def test_calc_dual_offsets_st64_math(self): - # Non-st64: stride unit is 4 bytes for 32-bit (1 dword per offset unit) - (eff0, idx0), (eff1, idx1) = calc_lds_dual_offsets(0x100, 4, 8, lds_dwords=512, st64=False) - self.assertEqual(eff0, 0x100 + 16) - self.assertEqual(idx0, (0x100 + 16) >> 2) - self.assertEqual(eff1, 0x100 + 32) - self.assertEqual(idx1, (0x100 + 32) >> 2) - - # st64=True: stride unit is 4 * 64 = 256 bytes per offset unit - (eff0_st, idx0_st), (eff1_st, idx1_st) = calc_lds_dual_offsets(0x100, 1, 2, lds_dwords=512, st64=True) - self.assertEqual(eff0_st, 0x100 + 256) - self.assertEqual(idx0_st, (0x100 + 256) >> 2) - self.assertEqual(eff1_st, 0x100 + 512) - self.assertEqual(idx1_st, (0x100 + 512) >> 2) - - def test_dual_offset_wrapping_power_of_two(self): - lds_dwords = 32 # 128 bytes total - (eff0, idx0), (eff1, idx1) = calc_lds_dual_offsets(0, 32, 33, lds_dwords=lds_dwords, st64=False) - # offset 32 * 4 = 128 bytes -> wraps to dword 0 - self.assertEqual(idx0, 0) - # offset 33 * 4 = 132 bytes -> wraps to dword 1 - self.assertEqual(idx1, 1) - - -class TestSpirvAtomicXorB64Emission(unittest.TestCase): - """Verifies that 64-bit LDS atomic XOR translates to conforming SPIR-V and executes correctly.""" - - def test_rdna2spirv_translate_b64_emission(self): - spv = translate_cs_listing([ - "ds_xor_b64 v0, v[2:3]", - "ds_xor_rtn_b64 v[4:5], v0, v[2:3] offset:16", - ]) - lines = [ln.strip() for ln in spv.splitlines() if "OpAtomicXor" in ln] - # Must emit 2 OpAtomicXor for ds_xor_b64 + 2 OpAtomicXor for ds_xor_rtn_b64 - self.assertEqual(len(lines), 4) - for ln in lines: - self.assertIn("OpAtomicXor", ln) - self.assertIn("%uint", ln) - self.assertIn("%c2", ln) # Workgroup scope - self.assertIn("%c0", ln) # Relaxed semantics - - def test_spirv_sequential_atomics_emulating_b64(self): - # Compute shader executing two sequential 32-bit OpAtomicXor operations simulating a 64-bit atomic - spvasm = """ -OpCapability Shader -OpMemoryModel Logical GLSL450 -OpEntryPoint GLCompute %main "main" %out_lo %out_hi -OpExecutionMode %main LocalSize 1 1 1 -%uint = OpTypeInt 32 0 -%c64 = OpConstant %uint 64 -%c2 = OpConstant %uint 2 -%c0 = OpConstant %uint 0 -%c10 = OpConstant %uint 10 -%c11 = OpConstant %uint 11 -%c_mask_lo = OpConstant %uint 3735928559 -%c_mask_hi = OpConstant %uint 3405691582 -%lds_arr = OpTypeArray %uint %c64 -%_ptr_WG_lds = OpTypePointer Workgroup %lds_arr -%_ptr_WG_uint = OpTypePointer Workgroup %uint -%_ptr_Out_uint = OpTypePointer Output %uint -%lds = OpVariable %_ptr_WG_lds Workgroup -%out_lo = OpVariable %_ptr_Out_uint Output -%out_hi = OpVariable %_ptr_Out_uint Output -%void = OpTypeVoid -%fn = OpTypeFunction %void -%main = OpFunction %void None %fn -%entry = OpLabel -%ptr_lo = OpAccessChain %_ptr_WG_uint %lds %c10 -%ptr_hi = OpAccessChain %_ptr_WG_uint %lds %c11 -%old_lo = OpAtomicXor %uint %ptr_lo %c2 %c0 %c_mask_lo -%old_hi = OpAtomicXor %uint %ptr_hi %c2 %c0 %c_mask_hi -OpStore %out_lo %old_lo -OpStore %out_hi %old_hi -OpReturn -OpFunctionEnd -""" - interp = LdsAtomicSpirvInterp(spvasm) - init_lo = 0x12345678 - init_hi = 0x9ABCDEF0 - final_lds, lane_outputs = interp.run(seed_lds={10: init_lo, 11: init_hi}) - self.assertEqual(lane_outputs[0]["%out_lo"], init_lo) - self.assertEqual(lane_outputs[0]["%out_hi"], init_hi) - self.assertEqual(final_lds[10], init_lo ^ 3735928559) - self.assertEqual(final_lds[11], init_hi ^ 3405691582) - - -class TestNegativeControlsAndBounds(unittest.TestCase): - """Verifies that invalid operands, unmodelled opcodes, bad stages, and bound violations fail safely.""" - - def test_rdna2spirv_invalid_operand_shape_rejected(self): - # ds_xor_b64 requires VGPR pair for data: passing scalar v1 must raise Unsupported - with self.assertRaises(rdna2spirv.Unsupported): - translate_cs_listing(["ds_xor_b64 v0, v1"]) - - def test_rdna2spirv_invalid_rtn_destination_shape_rejected(self): - # ds_xor_rtn_b64 requires VGPR pair for destination: passing scalar v4 must raise Unsupported - with self.assertRaises(rdna2spirv.Unsupported): - translate_cs_listing(["ds_xor_rtn_b64 v4, v0, v[2:3]"]) - - def test_rdna2spirv_non_compute_stage_rejected(self): - class MockPixelGen: - def __init__(self): - self.stage = "ps" - self.uses_lds = False - - lds_op = rdna2spirv.Gen.lds_op - - gen = MockPixelGen() - with self.assertRaises(rdna2spirv.Unsupported): - gen.lds_op("ds_xor_b32", [{"r": 0}, {"r": 1}], []) - with self.assertRaises(rdna2spirv.Unsupported): - gen.lds_op("ds_xor_b64", [{"r": 0}, {"r": 1, "n": 2}], []) - - def test_spirv_unsupported_storage_class(self): - spvasm = """ -OpCapability Shader -OpMemoryModel Logical GLSL450 -OpEntryPoint GLCompute %main "main" -OpExecutionMode %main LocalSize 1 1 1 -%uint = OpTypeInt 32 0 -%_ptr_UC = OpTypePointer UniformConstant %uint -%u = OpVariable %_ptr_UC UniformConstant -%void = OpTypeVoid -%fn = OpTypeFunction %void -%main = OpFunction %void None %fn -%entry = OpLabel -OpReturn -OpFunctionEnd -""" - with self.assertRaises(UnsupportedConstruct): - LdsAtomicSpirvInterp(spvasm) - - def test_spirv_unsupported_opcode_in_body(self): - spvasm = """ -OpCapability Shader -OpMemoryModel Logical GLSL450 -OpEntryPoint GLCompute %main "main" -OpExecutionMode %main LocalSize 1 1 1 -%uint = OpTypeInt 32 0 -%c10 = OpConstant %uint 10 -%void = OpTypeVoid -%fn = OpTypeFunction %void -%main = OpFunction %void None %fn -%entry = OpLabel -%bad = OpSDiv %uint %c10 %c10 -OpReturn -OpFunctionEnd -""" - interp = LdsAtomicSpirvInterp(spvasm) - with self.assertRaises(UnsupportedConstruct): - interp.run() - - def test_spirv_invalid_workgroup_local_sizes(self): - for bad_dims in [(0, 1, 1), (1025, 1, 1), (33, 32, 1)]: - with self.subTest(dims=bad_dims): - spvasm = f""" -OpCapability Shader -OpMemoryModel Logical GLSL450 -OpEntryPoint GLCompute %main "main" -OpExecutionMode %main LocalSize {bad_dims[0]} {bad_dims[1]} {bad_dims[2]} -%void = OpTypeVoid -%fn = OpTypeFunction %void -%main = OpFunction %void None %fn -%entry = OpLabel -OpReturn -OpFunctionEnd -""" - with self.assertRaises(WorkgroupBoundsError): - LdsAtomicSpirvInterp(spvasm) - - def test_spirv_atomic_on_non_lds_pointer(self): - spvasm = """ -OpCapability Shader -OpMemoryModel Logical GLSL450 -OpEntryPoint GLCompute %main "main" -OpExecutionMode %main LocalSize 1 1 1 -%uint = OpTypeInt 32 0 -%_ptr_fn_uint = OpTypePointer Function %uint -%c2 = OpConstant %uint 2 -%c0 = OpConstant %uint 0 -%c7 = OpConstant %uint 7 -%void = OpTypeVoid -%fn = OpTypeFunction %void -%main = OpFunction %void None %fn -%entry = OpLabel -%fn_var = OpVariable %_ptr_fn_uint Function -%bad = OpAtomicXor %uint %fn_var %c2 %c0 %c7 -OpReturn -OpFunctionEnd -""" - interp = LdsAtomicSpirvInterp(spvasm) - with self.assertRaises(UnsupportedConstruct): - interp.run() - - def test_spirv_out_of_bounds_lds_access(self): - spvasm = """ -OpCapability Shader -OpMemoryModel Logical GLSL450 -OpEntryPoint GLCompute %main "main" -OpExecutionMode %main LocalSize 1 1 1 -%uint = OpTypeInt 32 0 -%c16 = OpConstant %uint 16 -%c99 = OpConstant %uint 99 -%c2 = OpConstant %uint 2 -%c0 = OpConstant %uint 0 -%lds_arr = OpTypeArray %uint %c16 -%_ptr_WG_lds = OpTypePointer Workgroup %lds_arr -%_ptr_WG_uint = OpTypePointer Workgroup %uint -%lds = OpVariable %_ptr_WG_lds Workgroup -%void = OpTypeVoid -%fn = OpTypeFunction %void -%main = OpFunction %void None %fn -%entry = OpLabel -%ptr = OpAccessChain %_ptr_WG_uint %lds %c99 -%bad = OpAtomicXor %uint %ptr %c2 %c0 %c16 -OpReturn -OpFunctionEnd -""" - interp = LdsAtomicSpirvInterp(spvasm) - with self.assertRaises(WorkgroupBoundsError): - interp.run() - - def test_simd_interp_unknown_opcode_rejected(self): - interp = LdsSemanticInterpreter() - with self.assertRaises(UnsupportedConstruct): - interp.parse_and_execute("ds_unknown_op v0, v1") - - def test_spirv_shift_bounds_rejected(self): - for op in ("OpShiftRightLogical", "OpShiftLeftLogical"): - with self.subTest(op=op): - spvasm = f""" -OpCapability Shader -OpMemoryModel Logical GLSL450 -OpEntryPoint GLCompute %main "main" -OpExecutionMode %main LocalSize 1 1 1 -%uint = OpTypeInt 32 0 -%c1 = OpConstant %uint 1 -%c32 = OpConstant %uint 32 -%void = OpTypeVoid -%fn = OpTypeFunction %void -%main = OpFunction %void None %fn -%entry = OpLabel -%bad = {op} %uint %c1 %c32 -OpReturn -OpFunctionEnd -""" - interp = LdsAtomicSpirvInterp(spvasm) - with self.assertRaises(UnsupportedConstruct): - interp.run() - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_lds_atomics_cas.py b/tests/semantic/test_lds_atomics_cas.py deleted file mode 100644 index 761471277..000000000 --- a/tests/semantic/test_lds_atomics_cas.py +++ /dev/null @@ -1,424 +0,0 @@ -"""Value tests for RDNA2 32-bit LDS CAS atomics via spirv_mini_interp: - ds_inc_u32 / ds_inc_rtn_u32, ds_dec_u32 / ds_dec_rtn_u32, ds_rsub_u32 / ds_rsub_rtn_u32, - ds_min_f32 / ds_min_rtn_f32, ds_max_f32 / ds_max_rtn_f32. - -Each lowers to a Workgroup-scope OpAtomicCompareExchange CAS loop inside Gen.lds_op(). Standard library only; -no GPU, no LLVM, no game files. -""" -import os -import random -import re -import shutil -import struct -import subprocess -import sys -import tempfile -import unittest -import warnings - -HERE = os.path.dirname(os.path.abspath(__file__)) -ROOT = os.path.dirname(os.path.dirname(HERE)) -sys.dont_write_bytecode = True -sys.path.insert(0, os.environ.get("LEONIDA_TOOLS_DIR") or os.path.join(ROOT, "tools")) -sys.path.insert(0, HERE) - -import rdna2spirv # noqa: E402 -import spirv_asm # noqa: E402 -import spirv_mini_interp as si # noqa: E402 - -M32 = 0xFFFFFFFF -STUB_DXBC = b"DXBC" + bytes(24) + struct.pack("= d else (m + 1) & M32, - "dec_u32": lambda m, d: d if (m == 0 or m > d) else (m - 1) & M32, - "rsub_u32": lambda m, d: (d - m) & M32, -} - - -def make_fssm(lds_units=1, threads=32): - fssm = bytearray(0x148) - struct.pack_into("<4I", fssm, 0x138, 0x88 | (lds_units << 15), threads, 1, 1) - return bytes(fssm) - - -def translate(body, stage="cs", lds_units=1, threads=32, emulate=False): - with tempfile.TemporaryDirectory() as tmp: - for d in ("disasm", "fssm"): - os.mkdir(os.path.join(tmp, d)) - name = f"{stage}_lds_cas" - with open(os.path.join(tmp, f"{name}.dxbc"), "wb") as f: - f.write(STUB_DXBC) - if stage == "cs": - with open(os.path.join(tmp, "fssm", f"{name}.fssm"), "wb") as f: - f.write(make_fssm(lds_units=lds_units, threads=threads)) - src = os.path.join(tmp, "disasm", f"{name}.s") - with open(src, "w", encoding="utf-8", newline="\n") as f: - f.write(f"; {name}\n" + "".join(f"\t{ln}\n" for ln in body) + "\ts_endpgm\n") - prev = rdna2spirv.WAVE64_EMULATE - rdna2spirv.WAVE64_EMULATE = emulate - try: - with warnings.catch_warnings(): - warnings.simplefilter("ignore", ResourceWarning) - return rdna2spirv.translate(src) - finally: - rdna2spirv.WAVE64_EMULATE = prev - - -def run_cs(body, nlanes=1, lds_units=1, threads=32): - spv = translate(body, stage="cs", lds_units=lds_units, threads=threads) - mem = {} - si.run_workgroup(spv, nlanes, threads, - inputs_for=lambda i: {"%wg_id": (0, 0, 0), "%local_id": (i, 0, 0), "%sg_lane": i}, - push_constants=[0] * 36, memory=mem) - return mem - - -def run_single(op_stem, m, d, rtn=True, offset=0, alias_dst=False): - addr = 16 - op = f"ds_{op_stem.replace('_', '_rtn_', 1)}" if rtn else f"ds_{op_stem}" - off = f" offset:{offset}" if offset else "" - body = [ - f"v_mov_b32_e32 v1, {addr}", - f"v_mov_b32_e32 v2, {m:#x}", - "ds_write_b32 v1, v2", - "s_waitcnt lgkmcnt(0)", - f"v_mov_b32_e32 v1, {addr - offset}", - f"v_mov_b32_e32 v3, {d:#x}", - "v_mov_b32_e32 v5, 0xdead", - ] - if rtn: - dst_reg = "v3" if alias_dst else "v5" - body.append(f"{op} {dst_reg}, v1, v3{off}") - else: - body.append(f"{op} v1, v3{off}") - body += [ - "s_waitcnt lgkmcnt(0)", - f"v_mov_b32_e32 v1, {addr}", - "ds_read_b32 v4, v1", - "s_waitcnt lgkmcnt(0)", - f"v_mov_b32_e32 v6, {OUT:#x}", - f"global_store_dword v6, {'v3' if (rtn and alias_dst) else 'v5'}, s[0:1]", - f"v_mov_b32_e32 v7, {OUT + 4:#x}", - "global_store_dword v7, v4, s[0:1]", - ] - mem = run_cs(body) - return mem.get(OUT), mem.get(OUT + 4) - - -class LdsCasAtomics(unittest.TestCase): - def test_int_edge_grid_rtn_and_non_rtn(self): - for stem, fn in INT_MODELS.items(): - for m in INT_VALUES: - for d in INT_VALUES[::2]: - with self.subTest(op=stem, m=hex(m), d=hex(d)): - self.assertEqual(run_single(stem, m, d, rtn=True), (m, fn(m, d))) - self.assertEqual(run_single(stem, m, d, rtn=False), (0xDEAD, fn(m, d))) - - def test_int_seeded_and_offsets_and_aliasing(self): - rng = random.Random(0x1D5C) - for _ in range(18): - stem = rng.choice(list(INT_MODELS)) - m, d = rng.getrandbits(32), rng.getrandbits(32) - with self.subTest(op=stem, m=hex(m), d=hex(d)): - self.assertEqual(run_single(stem, m, d, rtn=True, offset=8, alias_dst=True), - (m, INT_MODELS[stem](m, d))) - - def test_float_min_max_edge_cases(self): - pos0, neg0 = 0x00000000, 0x80000000 - one, neg2, half = 0x3F800000, 0xC0000000, 0x3F000000 - pinf, ninf, qnan = 0x7F800000, 0xFF800000, 0x7FC00001 - cases = [ - ("min_f32", one, half, half), - ("min_f32", half, one, half), - ("min_f32", one, neg2, neg2), - ("min_f32", pos0, neg0, neg0), - ("min_f32", neg0, pos0, neg0), - ("min_f32", one, pinf, one), - ("min_f32", one, ninf, ninf), - ("min_f32", qnan, one, one), - ("min_f32", one, qnan, one), - ("max_f32", one, half, one), - ("max_f32", half, one, one), - ("max_f32", neg2, one, one), - ("max_f32", pos0, neg0, pos0), - ("max_f32", neg0, pos0, pos0), - ("max_f32", one, pinf, pinf), - ("max_f32", one, ninf, one), - ("max_f32", qnan, one, one), - ("max_f32", one, qnan, one), - ] - for stem, m, d, expected in cases: - with self.subTest(op=stem, m=hex(m), d=hex(d)): - self.assertEqual(run_single(stem, m, d, rtn=True), (m, expected)) - self.assertEqual(run_single(stem, m, d, rtn=False), (0xDEAD, expected)) - - def test_inactive_lane_leaves_lds_and_vdst_alone(self): - # Under exec_lo = 0, every op must skip the atomic and leave both LDS and vdst intact. - for op, rtn in ( - ("ds_inc_rtn_u32", True), ("ds_inc_u32", False), - ("ds_dec_rtn_u32", True), ("ds_dec_u32", False), - ("ds_rsub_rtn_u32", True), ("ds_rsub_u32", False), - ("ds_min_rtn_f32", True), ("ds_min_f32", False), - ("ds_max_rtn_f32", True), ("ds_max_f32", False), - ): - with self.subTest(op=op): - body = [ - "v_mov_b32_e32 v1, 16", - "v_mov_b32_e32 v2, 0x3f800000", # 1.0f - "ds_write_b32 v1, v2", - "s_waitcnt lgkmcnt(0)", - "v_mov_b32_e32 v3, 0xc0000000", # -2.0f / large u32 - "v_mov_b32_e32 v5, 0xdead", - "s_mov_b32 s4, exec_lo", - "s_mov_b32 exec_lo, 0", - f"{op} v5, v1, v3" if rtn else f"{op} v1, v3", - "s_mov_b32 exec_lo, s4", - "s_waitcnt lgkmcnt(0)", - "ds_read_b32 v4, v1", - "s_waitcnt lgkmcnt(0)", - f"v_mov_b32_e32 v6, {OUT:#x}", - "global_store_dword v6, v5, s[0:1]", - f"v_mov_b32_e32 v7, {OUT + 4:#x}", - "global_store_dword v7, v4, s[0:1]", - ] - mem = run_cs(body) - self.assertEqual((mem.get(OUT), mem.get(OUT + 4)), (0xDEAD, 0x3F800000)) - - def test_sequential_wrap_and_cas_spirv_structure(self): - # 4 consecutive ds_inc_rtn_u32 with DATA=2 starting at 0 return 0, 1, 2, 0 and leave 1. - body = [ - "v_mov_b32_e32 v1, 16", "v_mov_b32_e32 v2, 0", - "ds_write_b32 v1, v2", "s_waitcnt lgkmcnt(0)", - "v_mov_b32_e32 v3, 2", - "ds_inc_rtn_u32 v10, v1, v3", - "ds_inc_rtn_u32 v11, v1, v3", - "ds_inc_rtn_u32 v12, v1, v3", - "ds_inc_rtn_u32 v13, v1, v3", - "s_waitcnt lgkmcnt(0)", - "ds_read_b32 v14, v1", "s_waitcnt lgkmcnt(0)", - ] - for idx, reg in enumerate(("v10", "v11", "v12", "v13", "v14")): - body += [f"v_mov_b32_e32 v6, {OUT + 4 * idx:#x}", f"global_store_dword v6, {reg}, s[0:1]"] - mem = run_cs(body) - self.assertEqual([mem.get(OUT + 4 * i) for i in range(5)], [0, 1, 2, 0, 1]) - - # Verify Workgroup-scope CAS loop emission and absence of float atomic capabilities. - spv = translate(["v_mov_b32_e32 v1, 0", "v_mov_b32_e32 v3, 0x3f800000", "ds_min_rtn_f32 v5, v1, v3"]) - exchange, = (line.split("OpAtomicCompareExchange ")[1].split() - for line in spv.splitlines() if "OpAtomicCompareExchange " in line) - loads = [line.split("OpAtomicLoad ")[1].split() for line in spv.splitlines() if "OpAtomicLoad " in line] - self.assertEqual(loads, [exchange[:4]]) # type, pointer, scope, memory semantics - self.assertIn("OpLoopMerge", spv) - self.assertIn("OpExtInst %float %glsl NMin", spv) - self.assertNotIn("AtomicFloat", spv) - - def test_rejected_forms_and_outside_compute(self): - for line in ( - "ds_inc_rtn_u32 v[4:5], v1, v3", - "ds_dec_u32 v1, v[2:3]", - "ds_rsub_rtn_u32 v1, v3", - "ds_min_f32 v5, v1, v3", - ): - with self.subTest(line=line): - with self.assertRaises(rdna2spirv.Unsupported): - translate(["v_mov_b32_e32 v1, 0", line]) - with self.assertRaises(rdna2spirv.Unsupported): - translate(["v_mov_b32_e32 v1, 0", "ds_inc_u32 v1, v1", "exp mrt0 v1, v1, v1, v1 done vm"], stage="ps") - - CAS_BOUNDS_CASES = ( - ("ds_inc_rtn_u32", True, 77, 999, 78), - ("ds_inc_u32", False, 77, 999, 78), - ("ds_dec_rtn_u32", True, 77, 999, 76), - ("ds_dec_u32", False, 77, 999, 76), - ("ds_rsub_rtn_u32", True, 77, 999, 922), - ("ds_rsub_u32", False, 77, 999, 922), - ("ds_min_rtn_f32", True, 0x3F800000, 0xC0000000, 0xC0000000), - ("ds_min_f32", False, 0x3F800000, 0xC0000000, 0xC0000000), - ("ds_max_rtn_f32", True, 0x3F800000, 0x40800000, 0x40800000), - ("ds_max_f32", False, 0x3F800000, 0x40800000, 0x40800000), - ) - - def test_oob_access_drops_write_and_returns_zero(self): - # With LDS_SIZE=1 (512 B = 128 dwords) and an out-of-range extent forcing lds_bound=128, - # accessing byte 512 (dword 128) must not wrap onto LDS[0]: _rtn_ returns 0 and the write is dropped. - for op, rtn, init_val, data_val, _ in self.CAS_BOUNDS_CASES: - with self.subTest(op=op): - body = [ - "v_mov_b32_e32 v0, 0", - f"v_mov_b32_e32 v1, {init_val:#x}", - "ds_write_b32 v0, v1", - "s_waitcnt lgkmcnt(0)", - "v_mov_b32_e32 v8, 0xfc00", - "ds_read_b32 v9, v8 offset:1024", - "v_mov_b32_e32 v2, 512", - f"v_mov_b32_e32 v3, {data_val:#x}", - "v_mov_b32_e32 v5, 0xdead", - f"{op} v5, v2, v3" if rtn else f"{op} v2, v3", - "s_waitcnt lgkmcnt(0)", - "ds_read_b32 v4, v0", - "s_waitcnt lgkmcnt(0)", - f"v_mov_b32_e32 v6, {OUT:#x}", - "global_store_dword v6, v5, s[0:1]", - f"v_mov_b32_e32 v7, {OUT + 4:#x}", - "global_store_dword v7, v4, s[0:1]", - ] - mem = run_cs(body, lds_units=1) - self.assertEqual(rdna2spirv.translate.last_gen.lds_bound, 128) - self.assertEqual((mem.get(OUT), mem.get(OUT + 4)), (0 if rtn else 0xDEAD, init_val)) - - def test_inactive_lane_oob_access_leaves_vdst_alone(self): - # Under exec_lo = 0 the out-of-range path must not run either: _rtn_ keeps vdst (no zero for an inactive - # lane) and LDS[0] is untouched, with lds_bound=128 as in test_oob_access_drops_write_and_returns_zero. - for op, rtn, init_val, data_val, _ in self.CAS_BOUNDS_CASES: - if not rtn: - continue - with self.subTest(op=op): - body = [ - "v_mov_b32_e32 v0, 0", - f"v_mov_b32_e32 v1, {init_val:#x}", - "ds_write_b32 v0, v1", - "s_waitcnt lgkmcnt(0)", - "v_mov_b32_e32 v8, 0xfc00", - "ds_read_b32 v9, v8 offset:1024", - "v_mov_b32_e32 v2, 512", - f"v_mov_b32_e32 v3, {data_val:#x}", - "v_mov_b32_e32 v5, 0xdead", - "s_mov_b32 s4, exec_lo", - "s_mov_b32 exec_lo, 0", - f"{op} v5, v2, v3", - "s_mov_b32 exec_lo, s4", - "s_waitcnt lgkmcnt(0)", - "ds_read_b32 v4, v0", - "s_waitcnt lgkmcnt(0)", - f"v_mov_b32_e32 v6, {OUT:#x}", - "global_store_dword v6, v5, s[0:1]", - f"v_mov_b32_e32 v7, {OUT + 4:#x}", - "global_store_dword v7, v4, s[0:1]", - ] - mem = run_cs(body, lds_units=1) - self.assertEqual(rdna2spirv.translate.last_gen.lds_bound, 128) - self.assertEqual((mem.get(OUT), mem.get(OUT + 4)), (0xDEAD, init_val)) - - def test_non_power_of_two_bound_addresses_valid_slot(self): - # With LDS_SIZE=3 (1536 B = 384 dwords) and lds_bound=384, wrapping with (384 - 1) = 0x17f - # would clear bit 7 (dword 128 -> dword 0); bounds checking must hit LDS[128] and preserve LDS[0]. - guard_val = 0xCAFE1234 - for op, rtn, init_val, data_val, expected in self.CAS_BOUNDS_CASES: - with self.subTest(op=op): - body = [ - "v_mov_b32_e32 v0, 0", - f"v_mov_b32_e32 v1, {guard_val:#x}", - "ds_write_b32 v0, v1", - "v_mov_b32_e32 v2, 512", - f"v_mov_b32_e32 v10, {init_val:#x}", - "ds_write_b32 v2, v10", - "s_waitcnt lgkmcnt(0)", - "v_mov_b32_e32 v8, 0xfc00", - "ds_read_b32 v9, v8 offset:1536", - f"v_mov_b32_e32 v3, {data_val:#x}", - "v_mov_b32_e32 v5, 0xdead", - f"{op} v5, v2, v3" if rtn else f"{op} v2, v3", - "s_waitcnt lgkmcnt(0)", - "ds_read_b32 v4, v0", - "ds_read_b32 v11, v2", - "s_waitcnt lgkmcnt(0)", - f"v_mov_b32_e32 v6, {OUT:#x}", - "global_store_dword v6, v5, s[0:1]", - f"v_mov_b32_e32 v7, {OUT + 4:#x}", - "global_store_dword v7, v4, s[0:1]", - f"v_mov_b32_e32 v12, {OUT + 8:#x}", - "global_store_dword v12, v11, s[0:1]", - ] - mem = run_cs(body, lds_units=3) - gen = rdna2spirv.translate.last_gen - self.assertEqual((gen.lds_bound, gen.lds_dwords), (384, 384)) - self.assertEqual( - (mem.get(OUT), mem.get(OUT + 4), mem.get(OUT + 8)), - (init_val if rtn else 0xDEAD, guard_val, expected), - ) - - def test_zero_lds_allocation_returns_zero_and_drops_write(self): - # LDS_SIZE=0 with a constant extent past 0 yields lds_bound=0; _rtn_ returns 0 and non-_rtn_ preserves vdst. - for op, rtn in (("ds_inc_rtn_u32", True), ("ds_inc_u32", False), ("ds_min_rtn_f32", True)): - with self.subTest(op=op): - body = [ - "v_mov_b32_e32 v1, 0", - "v_mov_b32_e32 v3, 7", - "v_mov_b32_e32 v5, 0xdead", - f"{op} v5, v1, v3 offset:4" if rtn else f"{op} v1, v3 offset:4", - "s_waitcnt lgkmcnt(0)", - f"v_mov_b32_e32 v6, {OUT:#x}", - "global_store_dword v6, v5, s[0:1]", - ] - mem = run_cs(body, lds_units=0) - self.assertEqual(rdna2spirv.translate.last_gen.lds_bound, 0) - self.assertEqual(mem.get(OUT), 0 if rtn else 0xDEAD) - - def test_wave64_emulate_shrunk_lds_checks_bounds_and_skips_wrap_mask(self): - # Under --wave64-emulate with LDS_SIZE=100 (51200 B = 12800 dwords) and 64 threads, - # fit_shared_memory shrinks %lds to 12800 dwords and sets lds_bound=12800 without offset tricks. - shrunk = translate( - ["s_mov_b64 exec, -1", "v_mov_b32_e32 v1, 0", "v_readfirstlane_b32 s16, v1", - "v_mov_b32_e32 v3, 2", "ds_inc_rtn_u32 v5, v1, v3"], - lds_units=100, threads=64, emulate=True, - ) - gen = rdna2spirv.translate.last_gen - self.assertTrue(gen.wave64 and gen.emulate) - self.assertEqual((gen.lds_bound, gen.lds_dwords), (12800, 12800)) - self.assertGreaterEqual(len(re.findall(r"^\s*%\w+_lin = OpLabel$", shrunk, re.M)), 1) - self.assertIsNone(re.search(r"= OpBitwiseAnd %uint %\w+ %\w+\n\s*%\w+ = OpAccessChain %_ptr_WG_uint\w* %lds ", - shrunk)) - - unbounded = translate(["v_mov_b32_e32 v1, 0", "v_mov_b32_e32 v3, 2", "ds_inc_rtn_u32 v5, v1, v3"]) - self.assertIsNone(rdna2spirv.translate.last_gen.lds_bound) - self.assertEqual(len(re.findall(r"^\s*%\w+_lin = OpLabel$", unbounded, re.M)), 0) - - def _bounds_validation_modules(self): - return ( - ("unbounded_min_rtn", translate( - ["v_mov_b32_e32 v1, 0", "v_mov_b32_e32 v3, 0x3f800000", "ds_min_rtn_f32 v5, v1, v3"])), - ("bounded_inc_rtn", translate([ - "v_mov_b32_e32 v8, 0xfc00", "ds_read_b32 v9, v8 offset:1024", - "v_mov_b32_e32 v1, 0", "v_mov_b32_e32 v3, 2", "ds_inc_rtn_u32 v5, v1, v3", - ], lds_units=1)), - ("bounded_inc_no_rtn", translate([ - "v_mov_b32_e32 v8, 0xfc00", "ds_read_b32 v9, v8 offset:1024", - "v_mov_b32_e32 v1, 0", "v_mov_b32_e32 v3, 2", "ds_inc_u32 v1, v3", - ], lds_units=1)), - ("npot_max_rtn", translate([ - "v_mov_b32_e32 v8, 0xfc00", "ds_read_b32 v9, v8 offset:1536", - "v_mov_b32_e32 v1, 512", "v_mov_b32_e32 v3, 0x40800000", "ds_max_rtn_f32 v5, v1, v3", - ], lds_units=3)), - ("zero_lds_dec_rtn", translate( - ["v_mov_b32_e32 v1, 0", "v_mov_b32_e32 v3, 7", "ds_dec_rtn_u32 v5, v1, v3 offset:4"], lds_units=0)), - ("emulate_shrunk_rsub_rtn", translate( - ["s_mov_b64 exec, -1", "v_mov_b32_e32 v1, 0", "v_readfirstlane_b32 s16, v1", - "v_mov_b32_e32 v3, 5", "ds_rsub_rtn_u32 v5, v1, v3"], - lds_units=100, threads=64, emulate=True)), - ) - - def test_bounds_checked_cas_spirv_assembly(self): - for label, spv in self._bounds_validation_modules(): - with self.subTest(case=label): - binary = spirv_asm.assemble(spv, target_env="vulkan1.2") - self.assertEqual(struct.unpack_from(" int: - x &= M32 - return x - (1 << 32) if x >> 31 else x - - -MODEL = { - "add_u32": lambda m, d: (m + d) & M32, - "sub_u32": lambda m, d: (m - d) & M32, - "min_u32": min, - "max_u32": max, - "min_i32": lambda m, d: m if s32(m) <= s32(d) else d, - "max_i32": lambda m, d: m if s32(m) >= s32(d) else d, - "and_b32": lambda m, d: m & d, - "or_b32": lambda m, d: m | d, - "xor_b32": lambda m, d: m ^ d, -} -VALUES = [0, 1, 7, 0x7FFFFFFF, 0x80000000, 0xFFFFFFFF, 0x12345678] - - -def run_listing(body: list) -> dict: - with tempfile.TemporaryDirectory() as tmp: - os.mkdir(os.path.join(tmp, "disasm")) - os.mkdir(os.path.join(tmp, "fssm")) - name = "cs_lds_atomics" - with open(os.path.join(tmp, "disasm", name + ".s"), "w", encoding="utf-8") as f: - f.write("; " + name + "\n" + "".join(f"\t{ln}\n" for ln in body) + "\ts_endpgm\n") - with open(os.path.join(tmp, name + ".dxbc"), "wb") as f: - f.write(STUB_DXBC) - with open(os.path.join(tmp, "fssm", name + ".fssm"), "wb") as f: - f.write(FSSM) - with warnings.catch_warnings(): - warnings.simplefilter("ignore", ResourceWarning) - spv = rdna2spirv.translate(os.path.join(tmp, "disasm", name + ".s")) - return si.run_workgroup(spv, 1, 32, inputs_for=lambda i: {"%wg_id": (0, 0, 0), "%local_id": (i, 0, 0), "%sg_lane": i}, - push_constants=VSHARP + [0] * 28, memory={}) - - -def run_atomic(line: str, init: int, addr: int = 0x40, offset: int = 0, data=()) -> tuple: - """LDS[addr + offset] = init; run `line` (v1 = addr, v3.. = data); return (v5, LDS[addr + offset]).""" - body = [f"v_mov_b32_e32 v1, {addr:#x}", f"v_mov_b32_e32 v2, {init:#x}", "v_mov_b32_e32 v5, 0xdead", - f"ds_write_b32 v1, v2 offset:{offset}", "s_waitcnt lgkmcnt(0)"] - body += [f"v_mov_b32_e32 v{3 + k}, {d:#x}" for k, d in enumerate(data)] - body += [line + (f" offset:{offset}" if offset else ""), "s_waitcnt lgkmcnt(0)", - f"ds_read_b32 v6, v1 offset:{offset}", "s_waitcnt lgkmcnt(0)", - "v_mov_b32_e32 v31, 0", "buffer_store_dword v5, v31, s[0:3], 0 offen", - "v_mov_b32_e32 v31, 4", "buffer_store_dword v6, v31, s[0:3], 0 offen"] - mem = run_listing(body) - return mem.get(0), mem.get(4) - - -class LdsAtomicValues(unittest.TestCase): - def test_returning_forms(self): - for kind, fn in MODEL.items(): - for m in VALUES: - for d in VALUES[::2]: - with self.subTest(op=f"ds_{kind[:-4]}_rtn_{kind[-3:]}", m=hex(m), d=hex(d)): - got = run_atomic(f"ds_{kind[:-4]}_rtn_{kind[-3:]} v5, v1, v3", m, data=(d,)) - self.assertEqual(got, (m, fn(m, d))) - - def test_non_returning_forms_leave_vdst_alone(self): - for kind, fn in MODEL.items(): - for m, d in ((5, 3), (0x80000000, 0x7FFFFFFF), (0xFFFFFFFF, 1)): - with self.subTest(op=f"ds_{kind}", m=hex(m), d=hex(d)): - self.assertEqual(run_atomic(f"ds_{kind} v1, v3", m, data=(d,)), (0xDEAD, fn(m, d))) - - def test_wrxchg(self): - for m, d in ((0, 0xFFFFFFFF), (0x12345678, 0), (0x80000000, 0x80000000)): - with self.subTest(m=hex(m), d=hex(d)): - self.assertEqual(run_atomic("ds_wrxchg_rtn_b32 v5, v1, v3", m, data=(d,)), (m, d)) - - def test_cmpst_rtn(self): - # data0 (v3) is the comparator, data1 (v4) the value written on a match. - for m, cmp_, new in ((5, 5, 9), (5, 6, 9), (0xFFFFFFFF, 0xFFFFFFFF, 0), (0, 1, 2)): - with self.subTest(m=hex(m), cmp=hex(cmp_), new=hex(new)): - got = run_atomic("ds_cmpst_rtn_b32 v5, v1, v3, v4", m, data=(cmp_, new)) - self.assertEqual(got, (m, new if m == cmp_ else m)) - - def test_cmpst_without_return(self): - # ds_cmpst_b32 vaddr, data0, data1: the same compare-and-store, vdst untouched. - for m, cmp_, new in ((5, 5, 9), (5, 6, 9), (0x80000000, 0x80000000, 1)): - with self.subTest(m=hex(m), cmp=hex(cmp_), new=hex(new)): - got = run_atomic("ds_cmpst_b32 v1, v3, v4", m, data=(cmp_, new)) - self.assertEqual(got, (0xDEAD, new if m == cmp_ else m)) - - def test_offset_addresses_the_same_dword(self): - self.assertEqual(run_atomic("ds_add_rtn_u32 v5, v1, v3", 40, addr=0x20, offset=0x24, data=(2,)), (40, 42)) - - def test_seeded(self): - rng = random.Random(0x1D5) - kinds = list(MODEL) - for _ in range(20): - kind, m, d = rng.choice(kinds), rng.getrandbits(32), rng.getrandbits(32) - with self.subTest(kind=kind, m=hex(m), d=hex(d)): - got = run_atomic(f"ds_{kind[:-4]}_rtn_{kind[-3:]} v5, v1, v3", m, data=(d,)) - self.assertEqual(got, (m, MODEL[kind](m, d))) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_lds_b96_b128.py b/tests/semantic/test_lds_b96_b128.py deleted file mode 100644 index b49ece340..000000000 --- a/tests/semantic/test_lds_b96_b128.py +++ /dev/null @@ -1,294 +0,0 @@ -"""Semantic tests for multi-dword LDS instructions: ds_write_b96, ds_read_b96, ds_write_b128, ds_read_b128. - -Standard library only; no GPU, no LLVM, no game files. - -RDNA2 ISA ("Data Share Instructions"): - * ds_write_b96 vaddr, vdata[0:2] [offset:imm]: - MEM[ADDR + 0] = vdata[0], MEM[ADDR + 4] = vdata[1], MEM[ADDR + 8] = vdata[2] - * ds_read_b96 vdst[0:2], vaddr [offset:imm]: - vdst[0] = MEM[ADDR + 0], vdst[1] = MEM[ADDR + 4], vdst[2] = MEM[ADDR + 8] - * ds_write_b128 vaddr, vdata[0:3] [offset:imm]: - MEM[ADDR + 0..12] = vdata[0..3] - * ds_read_b128 vdst[0:3], vaddr [offset:imm]: - vdst[0..3] = MEM[ADDR + 0..12] -where ADDR = (vaddr + offset) & 0xFFFFFFFF. Inactive lanes (EXEC = 0) must neither -modify LDS nor overwrite destination VGPRs. -""" -import os -import re -import struct -import sys -import unittest - -sys.dont_write_bytecode = True - -HERE = os.path.dirname(os.path.abspath(__file__)) -ROOT = os.path.dirname(os.path.dirname(HERE)) -sys.path.insert(0, HERE) -sys.path.insert(0, os.environ.get("LEONIDA_TOOLS_DIR") or os.path.join(ROOT, "tools")) - -import spirv_mini_interp # noqa: E402 -import support # noqa: E402 - - -def fssm(rsrc2, group): - """Build the minimal compute-shader FSSM header read by rdna2spirv (RSRC2 + threadgroup size).""" - header = bytearray(0x148) - struct.pack_into("<4I", header, 0x138, rsrc2, *group) - return bytes(header) - - -# 4 user SGPRs (the output V#), workgroup id in s4, 64x1x1 threads. -CS_FSSM = fssm(0x8088, (64, 1, 1)) -# Output V# passed in s[0:3]: base 0, num_records 0xffffffff, 32_FLOAT, OOB_SELECT 3. -OUT_VSHARP = [0, 0, 0xFFFFFFFF, 0x31016FAC] - -W3 = (0x11223344, 0x55667788, 0x99AABBCC) -W4 = (0xA1B2C3D4, 0xE5F60718, 0x293A4B5C, 0x6D7E8F90) - - -def run_spv(spv): - """Run a translated compute shader on lane 0 and return the output buffer memory dict.""" - memory = {} - outputs = spirv_mini_interp.run_fragment( - spv, - inputs={"%wg_id": (0, 0, 0), "%local_id": (0, 0, 0)}, - push_constants=OUT_VSHARP + [0] * 28, - memory=memory, - ) - assert outputs == {}, f"unexpected fragment outputs: {outputs}" - return memory - - -def translate_cs(name, lines): - """Translate a compute instruction list (ending with s_endpgm) to SPIR-V assembly.""" - return support.translate_lines(name, list(lines) + ["s_endpgm"], fssm=CS_FSSM) - - -def load_vgprs(base_reg, values): - """Emit v_mov_b32_e32 instructions to populate consecutive VGPRs.""" - return [f"v_mov_b32_e32 v{base_reg + i}, {val:#x}" for i, val in enumerate(values)] - - -def store_vgprs(regs, byte_offset=0): - """Emit buffer_store_dword instructions to dump VGPRs into the output buffer.""" - out = [] - for i, reg in enumerate(regs): - out.append(f"v_mov_b32_e32 v31, {byte_offset + 4 * i}") - out.append(f"buffer_store_dword v{reg}, v31, s[0:3], 0 offen") - return out - - -def seed_lds_b32(base_addr, values): - """Emit ds_write_b32 instructions to seed consecutive dwords in LDS.""" - out = [] - for i, val in enumerate(values): - out.append(f"v_mov_b32_e32 v30, {base_addr + 4 * i:#x}") - out.append(f"v_mov_b32_e32 v29, {val:#x}") - out.append("ds_write_b32 v30, v29") - return out - - -def read_lds_b32(base_addr, count, dst_base_reg): - """Emit ds_read_b32 instructions to read consecutive dwords from LDS.""" - out = [] - for i in range(count): - out.append(f"v_mov_b32_e32 v30, {base_addr + 4 * i:#x}") - out.append(f"ds_read_b32 v{dst_base_reg + i}, v30") - return out - - -class LdsB96B128Semantics(unittest.TestCase): - def test_roundtrip_b96(self): - lines = [ - "v_mov_b32_e32 v2, 0", - *load_vgprs(4, W3), - "ds_write_b96 v2, v[4:6]", - "s_waitcnt lgkmcnt(0)", - "ds_read_b96 v[10:12], v2", - "s_waitcnt lgkmcnt(0)", - *store_vgprs([10, 11, 12]), - ] - mem = run_spv(translate_cs("cs_lds_rt_b96", lines)) - self.assertEqual([mem.get(4 * i) for i in range(3)], list(W3)) - - def test_roundtrip_b128(self): - lines = [ - "v_mov_b32_e32 v2, 0", - *load_vgprs(4, W4), - "ds_write_b128 v2, v[4:7]", - "s_waitcnt lgkmcnt(0)", - "ds_read_b128 v[10:13], v2", - "s_waitcnt lgkmcnt(0)", - *store_vgprs([10, 11, 12, 13]), - ] - mem = run_spv(translate_cs("cs_lds_rt_b128", lines)) - self.assertEqual([mem.get(4 * i) for i in range(4)], list(W4)) - - def test_offset_imm_and_b32_cross_check(self): - # ds_write_b96 with vaddr=4, offset:16 -> effective byte address 20. - lines_w96 = [ - "v_mov_b32_e32 v2, 4", - *load_vgprs(4, W3), - "ds_write_b96 v2, v[4:6] offset:16", - "s_waitcnt lgkmcnt(0)", - *read_lds_b32(20, 3, 10), - "s_waitcnt lgkmcnt(0)", - *store_vgprs([10, 11, 12]), - ] - mem_w96 = run_spv(translate_cs("cs_lds_off_w96", lines_w96)) - self.assertEqual([mem_w96.get(4 * i) for i in range(3)], list(W3)) - - # ds_write_b128 with vaddr=8, offset:20 -> effective byte address 28. - lines_w128 = [ - "v_mov_b32_e32 v2, 8", - *load_vgprs(4, W4), - "ds_write_b128 v2, v[4:7] offset:20", - "s_waitcnt lgkmcnt(0)", - *read_lds_b32(28, 4, 10), - "s_waitcnt lgkmcnt(0)", - *store_vgprs([10, 11, 12, 13]), - ] - mem_w128 = run_spv(translate_cs("cs_lds_off_w128", lines_w128)) - self.assertEqual([mem_w128.get(4 * i) for i in range(4)], list(W4)) - - # Seed with ds_write_b32 and read back with ds_read_b96 / ds_read_b128 + offset. - lines_r = [ - *seed_lds_b32(20, W3), - *seed_lds_b32(44, W4), - "s_waitcnt lgkmcnt(0)", - "v_mov_b32_e32 v2, 4", - "ds_read_b96 v[10:12], v2 offset:16", - "v_mov_b32_e32 v3, 24", - "ds_read_b128 v[14:17], v3 offset:20", - "s_waitcnt lgkmcnt(0)", - *store_vgprs([10, 11, 12, 14, 15, 16, 17]), - ] - mem_r = run_spv(translate_cs("cs_lds_off_r", lines_r)) - self.assertEqual([mem_r.get(4 * i) for i in range(7)], list(W3) + list(W4)) - - def test_adjacent_lds_dwords_preserved(self): - # ds_write_b96 at offset 0 must not clobber the 4th dword at offset 12 (or offset 16). - sent_b96 = [0xDEAD0000 + i for i in range(5)] - lines_96 = [ - *seed_lds_b32(0, sent_b96), - "s_waitcnt lgkmcnt(0)", - "v_mov_b32_e32 v2, 0", - *load_vgprs(4, W3), - "ds_write_b96 v2, v[4:6]", - "s_waitcnt lgkmcnt(0)", - *read_lds_b32(0, 5, 10), - "s_waitcnt lgkmcnt(0)", - *store_vgprs([10, 11, 12, 13, 14]), - ] - mem_96 = run_spv(translate_cs("cs_lds_adj_b96", lines_96)) - self.assertEqual( - [mem_96.get(4 * i) for i in range(5)], - list(W3) + sent_b96[3:], - ) - - # ds_write_b128 at offset 0 must not clobber the 5th dword at offset 16 (or offset 20). - sent_b128 = [0xBEEF0000 + i for i in range(6)] - lines_128 = [ - *seed_lds_b32(0, sent_b128), - "s_waitcnt lgkmcnt(0)", - "v_mov_b32_e32 v2, 0", - *load_vgprs(4, W4), - "ds_write_b128 v2, v[4:7]", - "s_waitcnt lgkmcnt(0)", - *read_lds_b32(0, 6, 10), - "s_waitcnt lgkmcnt(0)", - *store_vgprs([10, 11, 12, 13, 14, 15]), - ] - mem_128 = run_spv(translate_cs("cs_lds_adj_b128", lines_128)) - self.assertEqual( - [mem_128.get(4 * i) for i in range(6)], - list(W4) + sent_b128[4:], - ) - - def test_inactive_lane_preserves_lds_and_vgprs(self): - lds_sent = [0xCAFE0001 + i for i in range(4)] - vgpr_sent = [0xFACE0001 + i for i in range(4)] - - for op_w, op_r, count in ( - ("ds_write_b128 v2, v[4:7]", "ds_read_b128 v[20:23], v2", 4), - ("ds_write_b96 v2, v[4:6]", "ds_read_b96 v[20:22], v2", 3), - ): - with self.subTest(op_w=op_w, op_r=op_r): - lines = [ - *seed_lds_b32(0, lds_sent), - *load_vgprs(20, vgpr_sent), - "v_mov_b32_e32 v2, 0", - *load_vgprs(4, W4[:count]), - "s_waitcnt lgkmcnt(0)", - "s_mov_b32 exec_lo, 0", - op_w, - op_r, - "s_mov_b32 exec_lo, 1", - "s_waitcnt lgkmcnt(0)", - *read_lds_b32(0, 4, 24), - "s_waitcnt lgkmcnt(0)", - *store_vgprs([20, 21, 22, 23, 24, 25, 26, 27]), - ] - mem = run_spv(translate_cs("cs_lds_inactive", lines)) - self.assertEqual([mem.get(4 * i) for i in range(4)], vgpr_sent) - self.assertEqual([mem.get(4 * i) for i in range(4, 8)], lds_sent) - - def test_negative_controls_spirv_mutations(self): - # 1. Corrupting the +4/+8 word-offset OpIAdd in ds_write_b128 must break the round-trip. - spv_rt = translate_cs("cs_lds_neg_off", [ - "v_mov_b32_e32 v2, 0", - *load_vgprs(4, W4), - "ds_write_b128 v2, v[4:7]", - "s_waitcnt lgkmcnt(0)", - "ds_read_b128 v[10:13], v2", - "s_waitcnt lgkmcnt(0)", - *store_vgprs([10, 11, 12, 13]), - ]) - mutated_off, n_off = re.subn( - r"(= OpIAdd %uint %\w+ )%c4\b", - r"\1%c8", - spv_rt, - count=1, - ) - self.assertEqual(n_off, 1) - mem_off = run_spv(mutated_off) - self.assertNotEqual([mem_off.get(4 * i) for i in range(4)], list(W4)) - - # 2. Removing the %active guard on OpBranchConditional in the inactive-lane shader - # must cause LDS or VGPRs to be overwritten when exec_lo = 0. - lds_sent = [0xCAFE0001 + i for i in range(4)] - vgpr_sent = [0xFACE0001 + i for i in range(4)] - spv_inact = translate_cs("cs_lds_neg_act", [ - *seed_lds_b32(0, lds_sent), - *load_vgprs(20, vgpr_sent), - "v_mov_b32_e32 v2, 0", - *load_vgprs(4, W4), - "s_waitcnt lgkmcnt(0)", - "s_mov_b32 exec_lo, 0", - "ds_write_b128 v2, v[4:7]", - "ds_read_b128 v[20:23], v2", - "s_mov_b32 exec_lo, 1", - "s_waitcnt lgkmcnt(0)", - *read_lds_b32(0, 4, 24), - "s_waitcnt lgkmcnt(0)", - *store_vgprs([20, 21, 22, 23, 24, 25, 26, 27]), - ]) - # Flip every OpBranchConditional condition to %true so the ds_write_b128/ds_read_b128 - # blocks execute unconditionally even while exec_lo = 0. - self.assertIn("%true = OpConstantTrue %bool", spv_inact) - mutated_act, n_act = re.subn( - r"OpBranchConditional %\w+ ", - "OpBranchConditional %true ", - spv_inact, - ) - self.assertGreater(n_act, 0) - mem_act = run_spv(mutated_act) - self.assertNotEqual( - [mem_act.get(4 * i) for i in range(8)], - vgpr_sent + lds_sent, - ) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_lds_basic_alloc.py b/tests/semantic/test_lds_basic_alloc.py deleted file mode 100644 index b32131ba9..000000000 --- a/tests/semantic/test_lds_basic_alloc.py +++ /dev/null @@ -1,162 +0,0 @@ -"""How big the translator makes a compute shader's LDS, when its accesses are bounds-checked, and the wrap. - -Standard library only; no GPU, no LLVM, no game files. - -COMPUTE_PGM_RSRC2 bits [23:15] (LDS_SIZE) declare the group-shared size in 512-byte units (128 dwords). Where the -translator puts the Workgroup array `%lds_arr`: - * every constant `offset:` (bytes) or offset0/offset1 (4-byte units, x64 for st64, 8-byte units for b64) reaches - some number of dwords from address 0 (offset / 4 + 1 for a dword access); while all of them stay inside the - declared size, the array is a power of two of at least 16 dwords covering the declared size, capped at 16384 - (64 KiB), and a dynamic address wraps at its size (dword (A / 4) mod size); - * a constant offset past the declared size (SHADER-309; RDNA2 LDS does not wrap, ISA 3.6.1/3.6.6) makes the array - exactly the declared size and every access bounds-checked: out of range reads 0 and writes are dropped; - * a declared size over 64 KiB and a thread group of more than 1024 invocations are refused; TG_SIZE_EN (RSRC2 - bit 10) is accepted (test_cs_tg_size.py). -test_cs_shared_memory_limit.py runs the bounds-checked reads, writes and atomics; this file pins the array size and -which of the two forms is chosen. - -Each case translates a hand-written listing with tools/rdna2spirv.py (support.translate_lines) and reads the array -length from the SPIR-V assembly; the wrap cases also run the shader in tests/semantic/spirv_mini_interp.py. The sizes -are worked out by hand from the rules above. Until this file, the LDS tests of this name ran a self-built -interpreter that copied the older rule (offsets grow the array) instead of calling the translator. -""" -import os -import re -import sys -import unittest - -sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) -import lds_run as L # noqa: E402 (also puts tools/ on sys.path) -import rdna2spirv # noqa: E402 - -LDS_SIZE_SHIFT = 15 - - -def rsrc2(units, extra=0): - """4 user SGPRs, workgroup id in s4 (0x88) with `units` x 512 bytes of LDS.""" - return 0x88 | (units << LDS_SIZE_SHIFT) | extra - - -def translate(line, units, size=(32, 1, 1)): - return L.translate(["v_mov_b32_e32 v1, 0", line], rsrc2(units), size) - - -def lds_dwords(line, units=0, size=(32, 1, 1)): - spv = translate(line, units, size) - m = re.search(r"%lds_arr = OpTypeArray %uint (%\S+)", spv) - assert m, "no LDS array declared" - c = re.search(re.escape(m.group(1)) + r" = OpConstant %uint (\d+)", spv) - return int(c.group(1)) - - -def bounds_checked(line, units=0): - """True when an `OpULessThan %bool %idx ` guards an access chain into %lds at the same %idx. An unrelated - OpULessThan (a v_cmp_lt_u32, an EXEC path) does not satisfy it. (With nothing declared the array is padded to - one dword and the limit is 0, so the limit is not compared with the array length.)""" - spv = translate(line, units) - for c in re.finditer(r"OpULessThan %bool (%\S+) %\S+\s", spv): - if re.search(r"OpAccessChain %_ptr_WG_uint %lds " + re.escape(c.group(1)) + r"\s", spv): - return True - return False - - -READ = "ds_read_b32 v2, v1" - - -class TestAllocationSize(unittest.TestCase): - def test_declared_size_by_hand(self): - # (LDS_SIZE units, dwords): 128 per unit rounded up to a power of two, 16 .. 16384. - for units, want in ((0, 16), (1, 128), (2, 256), (3, 512), (5, 1024), (8, 1024), (9, 2048), (32, 4096), - (33, 8192), (64, 8192), (65, 16384), (128, 16384)): - with self.subTest(units=units): - self.assertEqual(lds_dwords(READ, units), want) - self.assertFalse(bounds_checked(READ, units)) - - def test_offset_inside_the_declaration_changes_nothing(self): - # 1 unit = 128 dwords = 512 bytes: the last dword is at byte 0x1FC. - for off in (0, 0x40, 0x1FC): - with self.subTest(offset=hex(off)): - self.assertEqual(lds_dwords(f"ds_read_b32 v2, v1 offset:{off:#x}", 1), 128) - self.assertFalse(bounds_checked(f"ds_read_b32 v2, v1 offset:{off:#x}", 1)) - - def test_offset_past_the_declaration_bounds_checks_at_exactly_the_declared_size(self): - # byte 0x200 is dword 128: one past the end of a 1-unit allocation. A 3-unit one is 384 dwords (not a power of - # two): the array is 384 then, not rounded up to 512. - for units, off, want in ((1, 0x200, 128), (1, 0x1000, 128), (3, 0x600, 384), (2, 0x400, 256)): - line = f"ds_read_b32 v2, v1 offset:{off:#x}" - with self.subTest(units=units, offset=hex(off)): - self.assertEqual(lds_dwords(line, units), want) - self.assertTrue(bounds_checked(line, units)) - - def test_nothing_declared_and_an_offset_gives_an_empty_checked_array(self): - line = "ds_read_b32 v2, v1 offset:0x100" - self.assertTrue(bounds_checked(line, 0)) - self.assertEqual(lds_dwords(line, 0), 1) # a 0-length array is not legal SPIR-V; every access fails the check - - def test_two_address_and_wide_offsets_count_their_width(self): - # 1 unit = 128 dwords. read2_b32 offset1:127 ends at dword 127 (fits); 128 does not. st64: 64 dwords per unit, - # so offset1:1 ends at dword 64 (fits) and offset1:2 at dword 128 (does not). b64 elements are two dwords. - for line, over in (("ds_read2_b32 v[2:3], v1 offset1:127", False), ("ds_read2_b32 v[2:3], v1 offset1:128", True), - ("ds_read2st64_b32 v[2:3], v1 offset1:1", False), - ("ds_read2st64_b32 v[2:3], v1 offset1:2", True), - ("ds_read2_b64 v[2:5], v1 offset1:63", False), ("ds_read2_b64 v[2:5], v1 offset1:64", True), - ("ds_read_b128 v[2:5], v1 offset:0x1F0", False), ("ds_read_b128 v[2:5], v1 offset:0x1F4", True), - ("ds_read_u8 v2, v1 offset:0x1FF", False), ("ds_read_u8 v2, v1 offset:0x200", True)): - with self.subTest(line=line): - self.assertEqual(bounds_checked(line, 1), over) - - def test_non_ds_listing_declares_none(self): - self.assertNotIn("%lds_arr", L.translate(["v_mov_b32_e32 v1, 0"], rsrc2(8))) - - def test_declared_size_over_64k_is_refused(self): - with self.assertRaises(rdna2spirv.Unsupported): - translate(READ, 129) # 129 x 512 B = 66048 B - self.assertEqual(lds_dwords(READ, 128), 16384) - - -class TestRefusals(unittest.TestCase): - def test_tg_size_en_accepted(self): - self.assertIn("%lds_arr", L.translate([READ], rsrc2(8, extra=1 << 10))) - - def test_group_over_1024_refused(self): - for size in ((1025, 1, 1), (32, 33, 1), (16, 16, 5)): - with self.subTest(size=size), self.assertRaises(rdna2spirv.Unsupported): - L.translate([READ], rsrc2(8), size) - - def test_group_of_1024_accepted(self): - for size in ((1024, 1, 1), (32, 32, 1), (8, 8, 16)): - with self.subTest(size=size): - self.assertIn("%lds_arr", L.translate([READ], rsrc2(8), size)) - - -class TestWrap(unittest.TestCase): - # These pin the translator's current approximation of a dynamic address (dword (A / 4) mod array size). Real - # RDNA2 LDS does not wrap (ISA 3.6.1/3.6.6), so whoever fixes the wrap should update these, not treat the - # failure as a regression. - def wrap_case(self, units, write_addr, read_addr): - """Lane i writes 0x900 + i at write_addr + 4 i, then reads read_addr + 4 i (addresses held in VGPRs).""" - body = ["v_lshlrev_b32_e32 v3, 2, v0", "v_add_nc_u32_e32 v1, %#x, v3" % write_addr, - "v_add_nc_u32_e32 v2, 0x900, v0", "ds_write_b32 v1, v2", "s_waitcnt lgkmcnt(0)", - "v_add_nc_u32_e32 v4, %#x, v3" % read_addr, "ds_read_b32 v5, v4", "s_waitcnt lgkmcnt(0)"] \ - + L.store("v5", 0) - mem = L.run(body, rsrc2=rsrc2(units)) - return [L.out(mem, i, 0) for i in range(32)] - - def test_dynamic_address_wraps_at_the_array(self): - # 1 unit = 128 dwords = 512 bytes: byte 0x200 is byte 0, in either direction. - self.assertEqual(self.wrap_case(1, 0x200, 0), [0x900 + i for i in range(32)]) - self.assertEqual(self.wrap_case(1, 0, 0x400), [0x900 + i for i in range(32)]) - self.assertEqual(self.wrap_case(1, 0x100, 0x100), [0x900 + i for i in range(32)]) # no wrap: the same word - self.assertEqual(self.wrap_case(1, 0x80, 0x100), [0] * 32) # a different word - - def test_wraps_at_the_power_of_two_above_the_declaration(self): - # 3 units = 384 dwords, array 512 dwords = 2 KiB: byte 0x800 is byte 0, byte 0x600 (dword 384) is not byte 0. - self.assertEqual(self.wrap_case(3, 0x800, 0), [0x900 + i for i in range(32)]) - self.assertEqual(self.wrap_case(3, 0x600, 0), [0] * 32) - - def test_wraps_at_the_cap(self): - self.assertEqual(self.wrap_case(128, 0x10000, 0), [0x900 + i for i in range(32)]) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_lds_bitwise_b64.py b/tests/semantic/test_lds_bitwise_b64.py deleted file mode 100644 index 5b9f0bddf..000000000 --- a/tests/semantic/test_lds_bitwise_b64.py +++ /dev/null @@ -1,83 +0,0 @@ -"""Value tests for RDNA2 ds_and_b64, ds_or_b64, ds_xor_b64 and their _rtn_ forms, run through spirv_mini_interp. - -RDNA2 ISA, "Data Share Instructions": M = M op DATA on the 64-bit element at ADDR = vaddr + offset (the dwords at ADDR -and ADDR + 4, low first); the _rtn_ forms return the old 64 bits in vdst[0:1]. The translator does one 32-bit atomic -per dword, which leaves the same memory because a bitwise op works on each bit alone. Each case is a compute shader -run as one invocation: it seeds both dwords with ds_write_b64, runs the op, reads the element back with ds_read_b64 -and stores (vdst lo, vdst hi, M lo, M hi) to a buffer. Standard library only; no GPU, no LLVM, no game files. -""" -import os -import random -import sys -import unittest - -HERE = os.path.dirname(os.path.abspath(__file__)) -sys.dont_write_bytecode = True -sys.path.insert(0, HERE) - -from test_lds_atomics_values import run_listing # noqa: E402 (also puts tools/ on sys.path) -import rdna2spirv # noqa: E402 - -M32 = 0xFFFFFFFF -OPS = {"and": lambda m, d: m & d, "or": lambda m, d: m | d, "xor": lambda m, d: m ^ d} -VALUES = [0, (1 << 64) - 1, 0x00000000_FFFFFFFF, 0xFFFFFFFF_00000000, 0x12345678_9ABCDEF0, 0x80000000_00000001] - - -def run_b64(line: str, init: int, data: int, addr: int = 0x40, offset: int = 0): - body = [f"v_mov_b32_e32 v1, {addr:#x}", f"v_mov_b32_e32 v2, {init & M32:#x}", f"v_mov_b32_e32 v3, {init >> 32:#x}", - f"ds_write_b64 v1, v[2:3] offset:{offset}", "s_waitcnt lgkmcnt(0)", - f"v_mov_b32_e32 v4, {data & M32:#x}", f"v_mov_b32_e32 v5, {data >> 32:#x}", - "v_mov_b32_e32 v6, 0xdead", "v_mov_b32_e32 v7, 0xbeef", - line + (f" offset:{offset}" if offset else ""), "s_waitcnt lgkmcnt(0)", - f"ds_read_b64 v[8:9], v1 offset:{offset}", "s_waitcnt lgkmcnt(0)"] - for k, r in enumerate((6, 7, 8, 9)): - body += [f"v_mov_b32_e32 v31, {4 * k}", f"buffer_store_dword v{r}, v31, s[0:3], 0 offen"] - mem = run_listing(body) - return tuple(mem.get(4 * k) for k in range(4)) - - -def split(v: int): - return v & M32, v >> 32 - - -class LdsBitwiseB64(unittest.TestCase): - def test_returning_forms(self): - for kind, fn in OPS.items(): - for m in VALUES: - for d in VALUES[::2]: - with self.subTest(op=kind, m=hex(m), d=hex(d)): - got = run_b64(f"ds_{kind}_rtn_b64 v[6:7], v1, v[4:5]", m, d) - self.assertEqual(got, split(m) + split(fn(m, d))) - - def test_non_returning_forms_leave_vdst_alone(self): - for kind, fn in OPS.items(): - for m, d in ((0x12345678_9ABCDEF0, 0x0F0F0F0F_F0F0F0F0), (0, (1 << 64) - 1)): - with self.subTest(op=kind, m=hex(m), d=hex(d)): - self.assertEqual(run_b64(f"ds_{kind}_b64 v1, v[4:5]", m, d), (0xDEAD, 0xBEEF) + split(fn(m, d))) - - def test_offset(self): - m, d = 0x11111111_22222222, 0x0000FFFF_FFFF0000 - self.assertEqual(run_b64("ds_xor_rtn_b64 v[6:7], v1, v[4:5]", m, d, addr=0x20, offset=0x18), - split(m) + split(m ^ d)) - - def test_vdst_aliasing_data(self): - # vdst v[4:5] is also the data pair: the data is read before the old value is written back. - m, d = 0xF0F0F0F0_0F0F0F0F, 0xFF00FF00_00FF00FF - got = run_b64("ds_or_rtn_b64 v[4:5], v1, v[4:5]", m, d) - self.assertEqual(got[2:], split(m | d)) - - def test_seeded(self): - rng = random.Random(0xB64) - for _ in range(15): - kind, m, d = rng.choice(list(OPS)), rng.getrandbits(64), rng.getrandbits(64) - with self.subTest(op=kind, m=hex(m), d=hex(d)): - self.assertEqual(run_b64(f"ds_{kind}_rtn_b64 v[6:7], v1, v[4:5]", m, d), - split(m) + split(OPS[kind](m, d))) - - def test_bad_operands_rejected(self): - with self.assertRaises(rdna2spirv.Unsupported): - run_listing(["v_mov_b32_e32 v1, 0", "ds_and_b64 v1, v4"]) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_lds_direct.py b/tests/semantic/test_lds_direct.py deleted file mode 100644 index 9338b689c..000000000 --- a/tests/semantic/test_lds_direct.py +++ /dev/null @@ -1,96 +0,0 @@ -"""ds_write2_b32, ds_read2_b32, ds_write2st64_b32 and ds_read2st64_b32 through the translator. - -Standard library only; no GPU, no LLVM, no game files. - -RDNA2 ISA, "Data Share Instructions": the 2-address forms access two dwords at - ADDR0 = vaddr + offset0 * 4, ADDR1 = vaddr + offset1 * 4 (the st64 forms: offset * 4 * 64) - * ds_write2_b32 vaddr, vdata0, vdata1: MEM[ADDR0] = vdata0, MEM[ADDR1] = vdata1 - * ds_read2_b32 vdst[0:1], vaddr: vdst[0] = MEM[ADDR0], vdst[1] = MEM[ADDR1] -(offset0 and offset1 are 8-bit unit counts; the b64 forms are in test_lds_read2_write2_b64.py.) - -Each case is a compute shader translated by tools/rdna2spirv.py (support.translate_lines) and run for 32 lanes in -tests/semantic/spirv_mini_interp.py. Lane i uses vaddr = 4 i, so with offsets that are multiples of 32 dwords -(non-st64) or of 64 dwords (st64) the lanes never share a dword. A plain-Python LDS model, written from the -formula above, gives the expected words for seeded random offsets; the hand-written cases pin the unit. -""" -import os -import random -import sys -import unittest - -sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) -import lds_run as L # noqa: E402 (also puts tools/ on sys.path) -import rdna2spirv # noqa: E402 -import support # noqa: E402 - -RSRC2_8K = 0x80088 # 4 user SGPRs, workgroup id in s4, LDS_SIZE = 16 x 512 bytes -LDS_BYTES = 8192 - - -def lane_program(write, read, unit_bytes, off0, off1, roff0, roff1): - """Lane i writes (0x5000 + i, 0x6000 + i) with `write`, reads two dwords with `read`, and reads the dwords at - the write offsets back with plain ds_read_b32 (byte offsets off * unit_bytes).""" - body = ["v_lshlrev_b32_e32 v1, 2, v0", "v_add_nc_u32_e32 v2, 0x5000, v0", "v_add_nc_u32_e32 v3, 0x6000, v0", - f"{write} v1, v2, v3 offset0:{off0} offset1:{off1}", "s_waitcnt lgkmcnt(0)", - f"{read} v[4:5], v1 offset0:{roff0} offset1:{roff1}", - f"ds_read_b32 v6, v1 offset:{off0 * unit_bytes}", f"ds_read_b32 v7, v1 offset:{off1 * unit_bytes}", - "s_waitcnt lgkmcnt(0)"] - for k, r in enumerate(("v4", "v5", "v6", "v7")): - body += L.store(r, k) - return body - - -def model(lane, unit_bytes, off0, off1, roff0, roff1): - lds = {(4 * lane + off0 * unit_bytes) % LDS_BYTES: 0x5000 + lane, - (4 * lane + off1 * unit_bytes) % LDS_BYTES: 0x6000 + lane} # off1 wins a tie, as the later store - rd = lambda off: lds.get((4 * lane + off * unit_bytes) % LDS_BYTES, 0) # noqa: E731 - return [rd(roff0), rd(roff1), rd(off0), rd(off1)] - - -class TestRead2Write2(unittest.TestCase): - def run_case(self, write, read, unit_bytes, off0, off1, roff0, roff1): - mem = L.run(lane_program(write, read, unit_bytes, off0, off1, roff0, roff1), rsrc2=RSRC2_8K) - for i in range(32): - self.assertEqual([L.out(mem, i, k) for k in range(4)], model(i, unit_bytes, off0, off1, roff0, roff1), - f"lane {i}") - - def test_b32_by_hand(self): - # write at +0 and +128 bytes (offset 32 dwords); read2 with the offsets swapped returns [second, first]. - mem = L.run(lane_program("ds_write2_b32", "ds_read2_b32", 4, 0, 32, 32, 0), rsrc2=RSRC2_8K) - for i in range(32): - self.assertEqual([L.out(mem, i, k) for k in range(4)], [0x6000 + i, 0x5000 + i, 0x5000 + i, 0x6000 + i]) - - def test_st64_by_hand(self): - # st64: offsets count 256-byte units; writes at +0 and +256 (offset1:1), read2st64 with (1, 0). - mem = L.run(lane_program("ds_write2st64_b32", "ds_read2st64_b32", 256, 0, 1, 1, 0), rsrc2=RSRC2_8K) - for i in range(32): - self.assertEqual([L.out(mem, i, k) for k in range(4)], [0x6000 + i, 0x5000 + i, 0x5000 + i, 0x6000 + i]) - - def test_equal_offsets_read_the_same_dword_twice(self): - mem = L.run(lane_program("ds_write2_b32", "ds_read2_b32", 4, 0, 32, 32, 32), rsrc2=RSRC2_8K) - for i in range(32): - self.assertEqual([L.out(mem, i, k) for k in range(2)], [0x6000 + i, 0x6000 + i]) - - def test_seeded_offsets(self): - rng = random.Random(0xD1EC7) - for _ in range(8): - a, b = rng.sample(range(0, 255, 32), 2) - ra, rb = rng.choice((a, b)), rng.choice((a, b)) - with self.subTest(kind="b32", off0=a, off1=b, r0=ra, r1=rb): - self.run_case("ds_write2_b32", "ds_read2_b32", 4, a, b, ra, rb) - c, d = rng.sample(range(0, 8), 2) - rc, rd = rng.choice((c, d)), rng.choice((c, d)) - with self.subTest(kind="st64", off0=c, off1=d, r0=rc, r1=rd): - self.run_case("ds_write2st64_b32", "ds_read2st64_b32", 256, c, d, rc, rd) - - -class TestOutsideCompute(unittest.TestCase): - def test_pixel_shader_refuses_read2_and_write2(self): - for line in ("ds_read2_b32 v[0:1], v2 offset1:1", "ds_write2_b32 v0, v1, v2 offset1:1", - "ds_read2st64_b32 v[0:1], v2 offset1:1", "ds_write2st64_b32 v0, v1, v2 offset1:1"): - with self.subTest(line=line), self.assertRaises(rdna2spirv.Unsupported): - support.translate_lines("ps_lds_read2", [line, "s_endpgm"]) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_lds_inc_u32_hw.py b/tests/semantic/test_lds_inc_u32_hw.py deleted file mode 100644 index 6438658f8..000000000 --- a/tests/semantic/test_lds_inc_u32_hw.py +++ /dev/null @@ -1,672 +0,0 @@ -"""Semantic interpreter tests and translator verification for 32-bit unsigned LDS atomic increment with wrap (ds_inc_u32, ds_inc_rtn_u32). - -Standard library only; no GPU, no LLVM, no external tools, no game files. - - py -I tests/semantic/test_lds_inc_u32_hw.py - py -m unittest discover -s tests/semantic -p test_lds_inc_u32_hw.py -""" -from __future__ import annotations - -import os -import re -import struct -import sys -import unittest -from typing import Dict, List, Optional, Tuple, Union - -sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) -ROOT = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) -TOOLS_DIR = os.path.join(ROOT, "tools") -if TOOLS_DIR not in sys.path: - sys.path.insert(0, TOOLS_DIR) - -import support -import lds_run as L -import spirv_mini_interp as si -import rdna2spirv - -MASK32: int = 0xFFFFFFFF -UINT32_MAX: int = 0xFFFFFFFF - - -def ref_ds_inc_u32(curr_mem: int, data_val: int) -> int: - """Reference mathematical oracle for RDNA2 ds_inc_u32: M = (M >= DATA) ? 0 : M + 1 (unsigned).""" - cur = curr_mem & MASK32 - data = data_val & MASK32 - return 0 if cur >= data else (cur + 1) & MASK32 - - -def ref_ds_inc_rtn_u32(curr_mem: int, data_val: int) -> Tuple[int, int]: - """Reference returning atomic increment with wrap: returns (old_mem, new_mem).""" - old = curr_mem & MASK32 - new = ref_ds_inc_u32(old, data_val) - return old, new - - -class LDSMemory: - """Architectural model of RDNA2 Local Data Share (LDS) memory.""" - - def __init__(self, size_bytes: int = 4096) -> None: - if size_bytes <= 0 or (size_bytes & (size_bytes - 1)) != 0: - raise ValueError(f"LDS size must be a positive power of two, got {size_bytes}") - self.size_bytes = size_bytes - self.num_dwords = size_bytes // 4 - self.storage = [0] * self.num_dwords - - def resolve_dword_index(self, byte_addr: int, offset: int = 0) -> int: - eff_addr = (byte_addr + offset) & MASK32 - dword_idx = eff_addr >> 2 - return dword_idx & (self.num_dwords - 1) - - def read_dword(self, byte_addr: int, offset: int = 0) -> int: - idx = self.resolve_dword_index(byte_addr, offset) - return self.storage[idx] - - def write_dword(self, byte_addr: int, value: int, offset: int = 0) -> None: - idx = self.resolve_dword_index(byte_addr, offset) - self.storage[idx] = value & MASK32 - - def atomic_inc_u32(self, byte_addr: int, data_val: int, offset: int = 0, rtn: bool = False) -> Tuple[Optional[int], int]: - idx = self.resolve_dword_index(byte_addr, offset) - old_val = self.storage[idx] - new_val = ref_ds_inc_u32(old_val, data_val) - self.storage[idx] = new_val - return (old_val if rtn else None), new_val - - def get_bank(self, byte_addr: int, offset: int = 0) -> int: - eff_addr = (byte_addr + offset) & MASK32 - return (eff_addr >> 2) & 31 - -class TestDSIncU32OracleAndArchitecturalModel(unittest.TestCase): - """Part 1: Reference mathematical oracle and architectural model tests.""" - - def test_reference_oracle_basic_increments(self) -> None: - # Standard increment: cur < data - self.assertEqual(ref_ds_inc_u32(0, 10), 1) - self.assertEqual(ref_ds_inc_u32(1, 10), 2) - self.assertEqual(ref_ds_inc_u32(8, 10), 9) - - def test_reference_oracle_wrap_resets(self) -> None: - # Wrap when cur == data - self.assertEqual(ref_ds_inc_u32(10, 10), 0) - - # Wrap when cur > data - self.assertEqual(ref_ds_inc_u32(15, 10), 0) - - # When data == 0: cur >= 0 is always True (unsigned), so always resets to 0 - self.assertEqual(ref_ds_inc_u32(0, 0), 0) - self.assertEqual(ref_ds_inc_u32(5, 0), 0) - - def test_reference_oracle_returning_form(self) -> None: - old, new = ref_ds_inc_rtn_u32(3, 5) - self.assertEqual(old, 3) - self.assertEqual(new, 4) - - old, new = ref_ds_inc_rtn_u32(5, 5) - self.assertEqual(old, 5) - self.assertEqual(new, 0) - - def test_lds_memory_model(self) -> None: - lds = LDSMemory(size_bytes=4096) - addr = 0x40 - lds.write_dword(addr, 4) - - # Non-returning atomic inc with data=10: 4 < 10 -> 5 - old, new = lds.atomic_inc_u32(addr, 10, rtn=False) - self.assertIsNone(old) - self.assertEqual(new, 5) - self.assertEqual(lds.read_dword(addr), 5) - - # Returning atomic inc with data=5: 5 >= 5 -> resets to 0 - old, new = lds.atomic_inc_u32(addr, 5, rtn=True) - self.assertEqual(old, 5) - self.assertEqual(new, 0) - self.assertEqual(lds.read_dword(addr), 0) - -class Register: - def __init__(self, name: str, index: int) -> None: - self.name = name - self.index = index - - def __repr__(self) -> str: - return f"{self.name}{self.index}" - - def __eq__(self, other: object) -> bool: - if not isinstance(other, Register): - return False - return self.name == other.name and self.index == other.index - - def __hash__(self) -> int: - return hash((self.name, self.index)) - - -class VGPR(Register): - def __init__(self, index: int) -> None: - if not (0 <= index <= 255): - raise ValueError(f"VGPR index out of range [0, 255]: {index}") - super().__init__("v", index) - - -class DSIncU32Instruction: - """Symbolic AST node representing ds_inc_u32 and ds_inc_rtn_u32 instructions.""" - - def __init__( - self, - mnemonic: str, - vaddr: VGPR, - vdata0: VGPR, - vdst: Optional[VGPR] = None, - offset: int = 0, - gds: bool = False, - ) -> None: - if mnemonic not in ("ds_inc_u32", "ds_inc_rtn_u32"): - raise ValueError(f"Invalid mnemonic for ds_inc_u32 AST: {mnemonic}") - if mnemonic == "ds_inc_rtn_u32" and vdst is None: - raise ValueError("ds_inc_rtn_u32 requires vdst operand") - if mnemonic == "ds_inc_u32" and vdst is not None: - raise ValueError("ds_inc_u32 does not accept vdst operand") - if not (0 <= offset <= 65535): - raise ValueError(f"Offset out of range [0, 65535]: {offset}") - - self.mnemonic = mnemonic - self.vaddr = vaddr - self.vdata0 = vdata0 - self.vdst = vdst - self.offset = offset - self.gds = gds - - @property - def is_return(self) -> bool: - return self.mnemonic == "ds_inc_rtn_u32" - - def __repr__(self) -> str: - parts = [self.mnemonic] - if self.vdst is not None: - parts.append(str(self.vdst)) - parts.append(str(self.vaddr)) - parts.append(str(self.vdata0)) - text = f"{parts[0]} {', '.join(parts[1:])}" - if self.offset: - text += f" offset:{self.offset}" - if self.gds: - text += " gds" - return text - - @classmethod - def parse(cls, asm: str) -> "DSIncU32Instruction": - line = asm.strip() - if not line: - raise ValueError("Empty assembly string") - tokens = line.split() - mnem = tokens[0] - if mnem not in ("ds_inc_u32", "ds_inc_rtn_u32"): - raise ValueError(f"Unsupported mnemonic: {mnem}") - - rest = " ".join(tokens[1:]) - mod_tokens = rest.split() - clean_operands: list[str] = [] - offset = 0 - gds = False - - for tok in mod_tokens: - tok_clean = tok.rstrip(",") - if tok_clean.startswith("offset:"): - try: - offset = int(tok_clean.split(":", 1)[1], 0) - except ValueError: - raise ValueError(f"Invalid offset format: {tok_clean}") - elif tok_clean == "gds": - gds = True - elif tok_clean: - clean_operands.append(tok_clean) - - def parse_vgpr(reg_str: str) -> VGPR: - m = re.fullmatch(r"v(\d+)", reg_str) - if not m: - raise ValueError(f"Expected VGPR (e.g. v1), got: {reg_str}") - return VGPR(int(m.group(1))) - - if mnem == "ds_inc_u32": - if len(clean_operands) != 2: - raise ValueError(f"ds_inc_u32 requires 2 operands (vaddr, vdata0), got {len(clean_operands)}") - vaddr = parse_vgpr(clean_operands[0]) - vdata0 = parse_vgpr(clean_operands[1]) - return cls(mnem, vaddr, vdata0, vdst=None, offset=offset, gds=gds) - else: - if len(clean_operands) != 3: - raise ValueError(f"ds_inc_rtn_u32 requires 3 operands (vdst, vaddr, vdata0), got {len(clean_operands)}") - vdst = parse_vgpr(clean_operands[0]) - vaddr = parse_vgpr(clean_operands[1]) - vdata0 = parse_vgpr(clean_operands[2]) - return cls(mnem, vaddr, vdata0, vdst=vdst, offset=offset, gds=gds) - - -class TestDSIncU32ASTAndOpcodeDefinitions(unittest.TestCase): - """Part 2: Symbolic AST opcode definitions and typed expressions.""" - - def test_ast_construction_and_properties(self) -> None: - inst_non_rtn = DSIncU32Instruction("ds_inc_u32", VGPR(1), VGPR(2), offset=16) - self.assertFalse(inst_non_rtn.is_return) - self.assertEqual(inst_non_rtn.vaddr, VGPR(1)) - self.assertEqual(inst_non_rtn.vdata0, VGPR(2)) - self.assertIsNone(inst_non_rtn.vdst) - self.assertEqual(inst_non_rtn.offset, 16) - self.assertEqual(repr(inst_non_rtn), "ds_inc_u32 v1, v2 offset:16") - - inst_rtn = DSIncU32Instruction("ds_inc_rtn_u32", VGPR(3), VGPR(4), vdst=VGPR(5), offset=32, gds=True) - self.assertTrue(inst_rtn.is_return) - self.assertEqual(inst_rtn.vdst, VGPR(5)) - self.assertEqual(repr(inst_rtn), "ds_inc_rtn_u32 v5, v3, v4 offset:32 gds") - - def test_ast_parsing_valid(self) -> None: - inst1 = DSIncU32Instruction.parse("ds_inc_u32 v10, v20") - self.assertEqual(inst1.mnemonic, "ds_inc_u32") - self.assertEqual(inst1.vaddr, VGPR(10)) - self.assertEqual(inst1.vdata0, VGPR(20)) - - inst2 = DSIncU32Instruction.parse("ds_inc_rtn_u32 v5, v1, v2 offset:0x40") - self.assertEqual(inst2.mnemonic, "ds_inc_rtn_u32") - self.assertEqual(inst2.vdst, VGPR(5)) - self.assertEqual(inst2.offset, 64) - - def test_ast_parsing_invalid(self) -> None: - with self.assertRaises(ValueError): - DSIncU32Instruction.parse("") - with self.assertRaises(ValueError): - DSIncU32Instruction.parse("ds_inc_u32 v1") - with self.assertRaises(ValueError): - DSIncU32Instruction.parse("ds_inc_rtn_u32 v1, v2") - with self.assertRaises(ValueError): - DSIncU32Instruction.parse("ds_inc_u32 s1, v2") - -class ScalarThreadState: - """State of a single hardware execution lane / thread.""" - - def __init__(self, lds: LDSMemory) -> None: - self.vgprs: list[int] = [0] * 256 - self.sgprs: list[int] = [0] * 106 - self.lds = lds - self.lgkm_cnt = 0 - - def get_vgpr(self, reg: VGPR) -> int: - return self.vgprs[reg.index] - - def set_vgpr(self, reg: VGPR, val: int) -> None: - self.vgprs[reg.index] = val & MASK32 - - -class ScalarDSInterpreter: - """Deterministic instruction interpreter for scalar LDS increment executions.""" - - def __init__(self, lds: LDSMemory) -> None: - self.lds = lds - - def execute(self, state: ScalarThreadState, inst: DSIncU32Instruction) -> Optional[int]: - addr = state.get_vgpr(inst.vaddr) - data = state.get_vgpr(inst.vdata0) - - old_val, new_val = self.lds.atomic_inc_u32(addr, data, offset=inst.offset, rtn=inst.is_return) - - if inst.is_return and inst.vdst is not None: - assert old_val is not None - state.set_vgpr(inst.vdst, old_val) - - state.lgkm_cnt += 1 - return old_val - - -class TestDSIncU32ScalarInterpreter(unittest.TestCase): - """Part 3: Deterministic scalar instruction interpreter tests.""" - - def setUp(self) -> None: - self.lds = LDSMemory(size_bytes=4096) - self.interp = ScalarDSInterpreter(self.lds) - self.state = ScalarThreadState(self.lds) - - def test_scalar_execution_non_returning(self) -> None: - self.lds.write_dword(0x10, 5) - self.state.set_vgpr(VGPR(1), 0x10) - self.state.set_vgpr(VGPR(2), 10) - - inst = DSIncU32Instruction.parse("ds_inc_u32 v1, v2") - res = self.interp.execute(self.state, inst) - - self.assertIsNone(res) - self.assertEqual(self.lds.read_dword(0x10), 6) - - def test_scalar_execution_returning(self) -> None: - self.lds.write_dword(0x20, 10) - self.state.set_vgpr(VGPR(10), 0x20) - self.state.set_vgpr(VGPR(11), 10) - self.state.set_vgpr(VGPR(12), 0xDEADBEEF) - - # 10 >= 10 -> resets to 0 - inst = DSIncU32Instruction.parse("ds_inc_rtn_u32 v12, v10, v11") - res = self.interp.execute(self.state, inst) - - self.assertEqual(res, 10) - self.assertEqual(self.state.get_vgpr(VGPR(12)), 10) - self.assertEqual(self.lds.read_dword(0x20), 0) - - def test_scalar_execution_with_offset(self) -> None: - self.lds.write_dword(0x34, 0) - self.state.set_vgpr(VGPR(1), 0x30) - self.state.set_vgpr(VGPR(2), 5) - - inst = DSIncU32Instruction.parse("ds_inc_rtn_u32 v0, v1, v2 offset:4") - res = self.interp.execute(self.state, inst) - - self.assertEqual(res, 0) - self.assertEqual(self.state.get_vgpr(VGPR(0)), 0) - self.assertEqual(self.lds.read_dword(0x34), 1) - -class SIMDWaveState: - """Architectural state for a SIMD wavefront (Wave32 or Wave64).""" - - def __init__(self, lds: LDSMemory, wave_size: int = 32) -> None: - if wave_size not in (32, 64): - raise ValueError(f"Wave size must be 32 or 64, got {wave_size}") - self.wave_size = wave_size - self.lds = lds - self.exec_mask = (1 << wave_size) - 1 - self.lanes = [ScalarThreadState(lds) for _ in range(wave_size)] - - def is_lane_active(self, lane_id: int) -> bool: - return bool((self.exec_mask >> lane_id) & 1) - - -class SIMDDSInterpreter: - """Multi-lane SIMD interpreter modeling divergence and atomic address clashes.""" - - def __init__(self, lds: LDSMemory) -> None: - self.lds = lds - - def execute_wave( - self, - wave: SIMDWaveState, - inst: DSIncU32Instruction, - arbitration_order: Optional[List[int]] = None, - ) -> List[Optional[int]]: - results: List[Optional[int]] = [None] * wave.wave_size - active_lanes = [i for i in range(wave.wave_size) if wave.is_lane_active(i)] - - order = [i for i in arbitration_order if i in active_lanes] if arbitration_order is not None else active_lanes - - for lane_id in order: - lane_state = wave.lanes[lane_id] - addr = lane_state.get_vgpr(inst.vaddr) - data = lane_state.get_vgpr(inst.vdata0) - - old_val, new_val = self.lds.atomic_inc_u32(addr, data, offset=inst.offset, rtn=inst.is_return) - - if inst.is_return and inst.vdst is not None: - assert old_val is not None - lane_state.set_vgpr(inst.vdst, old_val) - results[lane_id] = old_val - - return results - - -class TestDSIncU32SIMDDivergenceAndExecMask(unittest.TestCase): - """Part 4: SIMD multi-lane divergence and 32/64-bit EXEC masking.""" - - def setUp(self) -> None: - self.lds = LDSMemory(size_bytes=4096) - self.interp = SIMDDSInterpreter(self.lds) - - def test_divergent_addresses_wave32(self) -> None: - wave = SIMDWaveState(self.lds, wave_size=32) - inst = DSIncU32Instruction.parse("ds_inc_rtn_u32 v5, v1, v2") - - for i in range(32): - self.lds.write_dword(i * 4, i) - wave.lanes[i].set_vgpr(VGPR(1), i * 4) - wave.lanes[i].set_vgpr(VGPR(2), 20) # limit 20 - - results = self.interp.execute_wave(wave, inst) - - for i in range(32): - expected_old = i - expected_new = 0 if i >= 20 else (i + 1) - self.assertEqual(results[i], expected_old) - self.assertEqual(wave.lanes[i].get_vgpr(VGPR(5)), expected_old) - self.assertEqual(self.lds.read_dword(i * 4), expected_new) - - def test_exec_masking_wave64(self) -> None: - lds = LDSMemory(size_bytes=8192) - interp = SIMDDSInterpreter(lds) - wave = SIMDWaveState(lds, wave_size=64) - mask = 0 - for i in range(0, 64, 2): - mask |= (1 << i) - wave.exec_mask = mask - - inst = DSIncU32Instruction.parse("ds_inc_rtn_u32 v3, v1, v2") - for i in range(64): - lds.write_dword(i * 4, 0) - wave.lanes[i].set_vgpr(VGPR(1), i * 4) - wave.lanes[i].set_vgpr(VGPR(2), 10) - wave.lanes[i].set_vgpr(VGPR(3), 0xCAFE) - - results = interp.execute_wave(wave, inst) - - for i in range(64): - if i % 2 == 0: - self.assertEqual(results[i], 0) - self.assertEqual(wave.lanes[i].get_vgpr(VGPR(3)), 0) - self.assertEqual(lds.read_dword(i * 4), 1) - else: - self.assertIsNone(results[i]) - self.assertEqual(wave.lanes[i].get_vgpr(VGPR(3)), 0xCAFE) - self.assertEqual(lds.read_dword(i * 4), 0) - - def test_address_clash_consecutive_increments(self) -> None: - # All 32 lanes increment same counter with threshold 50. - # Starting from 0, 32 increments yield 32. - inst = DSIncU32Instruction.parse("ds_inc_u32 v1, v2") - - lds = LDSMemory(size_bytes=1024) - interp = SIMDDSInterpreter(lds) - wave = SIMDWaveState(lds, wave_size=32) - - lds.write_dword(0x40, 0) - for i in range(32): - wave.lanes[i].set_vgpr(VGPR(1), 0x40) - wave.lanes[i].set_vgpr(VGPR(2), 50) - - interp.execute_wave(wave, inst) - self.assertEqual(lds.read_dword(0x40), 32) - -class TestDSIncU32RegisterAliasing(unittest.TestCase): - """Part 5: Register aliasing and in-place operand preservation.""" - - def setUp(self) -> None: - self.lds = LDSMemory(size_bytes=4096) - self.interp = ScalarDSInterpreter(self.lds) - - def test_aliasing_vdst_equals_vaddr(self) -> None: - state = ScalarThreadState(self.lds) - self.lds.write_dword(0x50, 7) - state.set_vgpr(VGPR(1), 0x50) - state.set_vgpr(VGPR(2), 20) - - inst = DSIncU32Instruction.parse("ds_inc_rtn_u32 v1, v1, v2") - res = self.interp.execute(state, inst) - - self.assertEqual(res, 7) - self.assertEqual(state.get_vgpr(VGPR(1)), 7) - self.assertEqual(self.lds.read_dword(0x50), 8) - - def test_aliasing_vdst_equals_vdata0(self) -> None: - state = ScalarThreadState(self.lds) - self.lds.write_dword(0x60, 10) - state.set_vgpr(VGPR(1), 0x60) - state.set_vgpr(VGPR(2), 10) - - inst = DSIncU32Instruction.parse("ds_inc_rtn_u32 v2, v1, v2") - res = self.interp.execute(state, inst) - - self.assertEqual(res, 10) - self.assertEqual(state.get_vgpr(VGPR(2)), 10) - self.assertEqual(self.lds.read_dword(0x60), 0) - - def test_aliasing_vaddr_equals_vdata0(self) -> None: - state = ScalarThreadState(self.lds) - self.lds.write_dword(0x40, 0) - state.set_vgpr(VGPR(1), 0x40) - - inst = DSIncU32Instruction.parse("ds_inc_u32 v1, v1") - self.interp.execute(state, inst) - - self.assertEqual(state.get_vgpr(VGPR(1)), 0x40) - self.assertEqual(self.lds.read_dword(0x40), 1) - -class TestDSIncU32ConditionCodesAndStatusFlags(unittest.TestCase): - """Part 6: Condition codes, status flags, and lgkmcnt tracking.""" - - def test_status_flags_invariance(self) -> None: - lds = LDSMemory(size_bytes=4096) - state = ScalarThreadState(lds) - state.sgprs[0] = 0xABCD1234 - lds.write_dword(0x10, 5) - state.set_vgpr(VGPR(1), 0x10) - state.set_vgpr(VGPR(2), 10) - - interp = ScalarDSInterpreter(lds) - inst = DSIncU32Instruction.parse("ds_inc_rtn_u32 v5, v1, v2") - interp.execute(state, inst) - - self.assertEqual(state.sgprs[0], 0xABCD1234) - self.assertEqual(state.lgkm_cnt, 1) - - def test_lgkmcnt_counter_tracking(self) -> None: - lds = LDSMemory(size_bytes=4096) - state = ScalarThreadState(lds) - interp = ScalarDSInterpreter(lds) - - for i in range(4): - inst = DSIncU32Instruction.parse(f"ds_inc_u32 v1, v2 offset:{i*4}") - interp.execute(state, inst) - - self.assertEqual(state.lgkm_cnt, 4) - -class TestDSIncU32BoundaryExtremes(unittest.TestCase): - """Part 7: Boundary extremes, wrap reset points, and address wrap.""" - - def setUp(self) -> None: - self.lds = LDSMemory(size_bytes=4096) - self.interp = ScalarDSInterpreter(self.lds) - self.state = ScalarThreadState(self.lds) - - def test_boundary_increments_and_resets(self) -> None: - # DATA = 0: any non-negative unsigned integer >= 0 is True -> always resets to 0 - self.assertEqual(ref_ds_inc_u32(0, 0), 0) - self.assertEqual(ref_ds_inc_u32(1, 0), 0) - self.assertEqual(ref_ds_inc_u32(0xFFFFFFFF, 0), 0) - - # DATA = UINT32_MAX: cur < UINT32_MAX increments - self.assertEqual(ref_ds_inc_u32(0, 0xFFFFFFFF), 1) - self.assertEqual(ref_ds_inc_u32(0xFFFFFFFE, 0xFFFFFFFF), 0xFFFFFFFF) - self.assertEqual(ref_ds_inc_u32(0xFFFFFFFF, 0xFFFFFFFF), 0) - - # 0x80000000 in unsigned is 2147483648 - self.assertEqual(ref_ds_inc_u32(0x7FFFFFFF, 0x80000000), 0x80000000) - self.assertEqual(ref_ds_inc_u32(0x80000000, 0x80000000), 0) - - def test_memory_address_wrapping_boundaries(self) -> None: - idx = self.lds.resolve_dword_index(0xFFFFFFFC, offset=4) - self.assertEqual(idx, 0) - idx2 = self.lds.resolve_dword_index(4096) - self.assertEqual(idx2, 0) - -class TestDSIncU32NegativeAndTranslator(unittest.TestCase): - """Part 8: Negative controls, syntax rejection, mutation detection, and translator execution.""" - - def test_syntax_rejection(self) -> None: - invalid_assemblies = [ - "ds_inc_u32", - "ds_inc_u32 v1", - "ds_inc_u32 v1, v2, v3", - "ds_inc_rtn_u32 v1, v2", - "ds_inc_u32 s1, v2", - "ds_inc_rtn_u32 s0, v1, v2", - "ds_inc_u32 v1, v2 offset:-1", - "ds_inc_u32 v1, v2 offset:70000", - "ds_inc_u32 v1, v2 bad_mod", - ] - for asm in invalid_assemblies: - with self.subTest(asm=asm): - with self.assertRaises(ValueError): - DSIncU32Instruction.parse(asm) - - def test_mutation_detection_signed_comparison(self) -> None: - # Mutant: treats operands as signed integers instead of unsigned - def mutant_inc_signed(cur: int, data: int) -> int: - s_cur = cur - (1 << 32) if (cur & 0x80000000) else cur - s_data = data - (1 << 32) if (data & 0x80000000) else data - return 0 if s_cur >= s_data else (cur + 1) & MASK32 - - # cur = 0xFFFFFFFF (-1 signed), data = 10 (+10 signed) - # Unsigned: cur (4294967295) >= data (10) -> resets to 0. - # Signed mutant: s_cur (-1) < s_data (10) -> increments to 0! - # Let's test with cur = 0x80000000 (-2147483648 signed), data = 10: - # Unsigned: 2147483648 >= 10 -> resets to 0. - # Signed: -2147483648 < 10 -> increments to 0x80000001! - oracle_res = ref_ds_inc_u32(0x80000000, 10) - mutant_res = mutant_inc_signed(0x80000000, 10) - self.assertEqual(oracle_res, 0) - self.assertEqual(mutant_res, 0x80000001) - self.assertNotEqual(oracle_res, mutant_res) - - def test_mutation_detection_strict_greater_instead_of_ge(self) -> None: - def mutant_strict_gt(cur: int, data: int) -> int: - return 0 if cur > data else (cur + 1) & MASK32 - - oracle_res = ref_ds_inc_u32(10, 10) - mutant_res = mutant_strict_gt(10, 10) - self.assertEqual(oracle_res, 0) - self.assertEqual(mutant_res, 11) - self.assertNotEqual(oracle_res, mutant_res) - - def test_translator_emits_cas_loop_with_ugreater_than_equal(self) -> None: - """Verifies tools/rdna2spirv.py emits OpAtomicCompareExchange and OpUGreaterThanEqual.""" - lines = [ - "v_mov_b32_e32 v1, 0x40", - "v_mov_b32_e32 v2, 10", - "ds_inc_u32 v1, v2", - "ds_inc_rtn_u32 v5, v1, v2 offset:16", - "s_waitcnt lgkmcnt(0)", - ] - spv = L.translate(lines) - self.assertIn("OpAtomicCompareExchange", spv) - self.assertIn("OpUGreaterThanEqual", spv) - - def test_translator_backed_execution_via_lds_run(self) -> None: - """Executes translated ds_inc_u32 and ds_inc_rtn_u32 in spirv_mini_interp.""" - # Test 1: Increment when cur < data (cur=3, data=10 -> 4) - init = {0x40: 3} - ops = [("ds_inc_rtn_u32", 0x40, 0, (10,))] - rtns, fin = L.run_chain(ops, init) - self.assertEqual(rtns, [3]) - self.assertEqual(fin, {0x40: 4}) - - # Test 2: Reset to 0 when cur >= data (cur=10, data=10 -> 0) - init2 = {0x44: 10} - ops2 = [("ds_inc_rtn_u32", 0x44, 0, (10,))] - rtns2, fin2 = L.run_chain(ops2, init2) - self.assertEqual(rtns2, [10]) - self.assertEqual(fin2, {0x44: 0}) - - # Test 3: Non-returning ds_inc_u32 with offset - init3 = {0x48: 5, 0x4C: 20} - ops3 = [ - ("ds_inc_u32", 0x48, 4, (20,)), # 0x48 + 4 = 0x4C: cur=20, data=20 -> resets to 0 - ("ds_inc_rtn_u32", 0x48, 0, (10,)), # 0x48: cur=5, data=10 -> 6 - ] - rtns3, fin3 = L.run_chain(ops3, init3) - self.assertEqual(rtns3, [0xDEAD, 5]) - self.assertEqual(fin3, {0x48: 6, 0x4C: 0}) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_lds_mskor.py b/tests/semantic/test_lds_mskor.py deleted file mode 100644 index bf232e743..000000000 --- a/tests/semantic/test_lds_mskor.py +++ /dev/null @@ -1,58 +0,0 @@ -"""Value tests for RDNA2 ds_mskor_b32 / ds_mskor_rtn_b32, run through spirv_mini_interp on the CPU. - -RDNA2 ISA, "Data Share Instructions": tmp = M[A]; M[A] = (tmp & ~DATA) | DATA2; the _rtn_ form returns tmp in vdst. -The translator does an atomic AND with ~DATA (whose result is tmp) and then an atomic OR with DATA2. Each case runs -one invocation (lane 0): it seeds the dword, runs the op and reads the dword back. Standard library only. -""" -import os -import random -import sys -import unittest - -HERE = os.path.dirname(os.path.abspath(__file__)) -sys.dont_write_bytecode = True -sys.path.insert(0, HERE) - -from test_lds_atomics_values import run_atomic # noqa: E402 (also puts tools/ on sys.path) - -M32 = 0xFFFFFFFF -VALUES = [0, M32, 0x12345678, 0xF0F0F0F0, 0x0000FFFF, 0x80000001] - - -def mskor(m, mask, data): - return (m & ~mask | data) & M32 - - -class LdsMskor(unittest.TestCase): - def test_returning_form(self): - for m in VALUES: - for mask in VALUES[::2]: - for data in VALUES[1::2]: - with self.subTest(m=hex(m), mask=hex(mask), data=hex(data)): - got = run_atomic("ds_mskor_rtn_b32 v5, v1, v3, v4", m, data=(mask, data)) - self.assertEqual(got, (m, mskor(m, mask, data))) - - def test_non_returning_form_leaves_vdst_alone(self): - for m, mask, data in ((0x12345678, 0x0000FF00, 0x0000AB00), (M32, M32, 0), (0, 0, 0x55)): - with self.subTest(m=hex(m)): - self.assertEqual(run_atomic("ds_mskor_b32 v1, v3, v4", m, data=(mask, data)), - (0xDEAD, mskor(m, mask, data))) - - def test_data_outside_the_mask_and_offset(self): - # DATA2 bits outside DATA are ORed in too: (tmp & ~DATA) | DATA2, not a masked insert. - self.assertEqual(run_atomic("ds_mskor_rtn_b32 v5, v1, v3, v4", 0x00FF00FF, data=(0x0000FFFF, 0xFFFF0000)), - (0x00FF00FF, 0xFFFF0000 | 0x00FF0000)) - self.assertEqual(run_atomic("ds_mskor_rtn_b32 v5, v1, v3, v4", 7, addr=0x20, offset=0x24, data=(3, 8)), - (7, 12)) - - def test_seeded(self): - rng = random.Random(0x3502) - for _ in range(20): - m, mask, data = rng.getrandbits(32), rng.getrandbits(32), rng.getrandbits(32) - with self.subTest(m=hex(m), mask=hex(mask), data=hex(data)): - self.assertEqual(run_atomic("ds_mskor_rtn_b32 v5, v1, v3, v4", m, data=(mask, data)), - (m, mskor(m, mask, data))) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_lds_or_b32_hw.py b/tests/semantic/test_lds_or_b32_hw.py deleted file mode 100644 index 525b92118..000000000 --- a/tests/semantic/test_lds_or_b32_hw.py +++ /dev/null @@ -1,688 +0,0 @@ -from __future__ import annotations - -import dataclasses -import enum -import os -import struct -import sys -import unittest - -HERE = os.path.dirname(os.path.abspath(__file__)) -ROOT = os.path.dirname(os.path.dirname(HERE)) -TOOLS_DIR = os.environ.get("LEONIDA_TOOLS_DIR") or os.path.join(ROOT, "tools") - -sys.dont_write_bytecode = True -if TOOLS_DIR not in sys.path: - sys.path.insert(0, TOOLS_DIR) -if HERE not in sys.path: - sys.path.insert(0, HERE) - -try: - import rdna2spirv # noqa: E402 - import support # noqa: E402 - import lds_run # noqa: E402 -except Exception: # noqa: E722 - rdna2spirv = None # type: ignore - support = None # type: ignore - lds_run = None # type: ignore - -MASK32: int = 0xFFFFFFFF -SIGN_BIT32: int = 0x80000000 -DEFAULT_LDS_DWORDS: int = 16384 # 64 KiB capacity in 32-bit dwords - - -# --------------------------------------------------------------------------- -# Reference Mathematical Oracle and Architectural Model -# --------------------------------------------------------------------------- - -def ref_ds_or_b32(curr_val: int, or_mask: int) -> int: - """Pure mathematical reference oracle for 32-bit bitwise OR: - - Computes: - LDS[addr] = (LDS[addr] | or_mask) & 0xFFFFFFFF - - Properties: - - Identity: x | 0 == x - - Saturation: x | 0xFFFFFFFF == 0xFFFFFFFF - - Idempotence: x | x == x - - Monotonicity: bits only transition 0 -> 1, never 1 -> 0 - """ - return ((curr_val & MASK32) | (or_mask & MASK32)) & MASK32 - - -def calc_lds_effective_address(vaddr: int, offset16: int = 0) -> int: - """Calculates 32-bit effective byte address with 16-bit unsigned offset.""" - return (vaddr + (offset16 & 0xFFFF)) & MASK32 - - -def calc_lds_dword_index(eff_addr: int, capacity_dwords: int = DEFAULT_LDS_DWORDS) -> int: - """Calculates aligned dword index, dropping unaligned low 2 bits and wrapping modulo capacity.""" - return (eff_addr >> 2) & (capacity_dwords - 1) - - -class LDSMemory: - """Architectural model of Local Data Share (LDS) scratchpad memory.""" - - def __init__(self, size_dwords: int = DEFAULT_LDS_DWORDS) -> None: - if size_dwords <= 0 or (size_dwords & (size_dwords - 1)) != 0: - raise ValueError(f"size_dwords must be a power of two, got {size_dwords}") - self.size_dwords: int = size_dwords - self.data: list[int] = [0] * size_dwords - - def read_dword(self, eff_addr: int) -> int: - idx = calc_lds_dword_index(eff_addr, self.size_dwords) - return self.data[idx] & MASK32 - - def write_dword(self, eff_addr: int, val: int) -> None: - idx = calc_lds_dword_index(eff_addr, self.size_dwords) - self.data[idx] = val & MASK32 - - def atomic_or_b32(self, vaddr: int, or_mask: int, offset16: int = 0) -> int: - """Executes non-returning 32-bit atomic OR; returns updated memory dword.""" - eff_addr = calc_lds_effective_address(vaddr, offset16) - curr = self.read_dword(eff_addr) - updated = ref_ds_or_b32(curr, or_mask) - self.write_dword(eff_addr, updated) - return updated - - -class TestLdsOrB32Oracle(unittest.TestCase): - """Unit tests for the reference mathematical oracle and architectural LDS models.""" - - def setUp(self) -> None: - self.lds = LDSMemory(size_dwords=1024) - - def test_oracle_basic_or(self) -> None: - self.lds.write_dword(0x40, 0xF0F00000) - updated = self.lds.atomic_or_b32(0x40, 0x0F0F0000) - self.assertEqual(updated, 0xFFFF0000) - self.assertEqual(self.lds.read_dword(0x40), 0xFFFF0000) - - def test_oracle_identity_zero_mask(self) -> None: - cases = [0x0, 0x1, 0x12345678, 0x80000000, 0x7FFFFFFF, 0xFFFFFFFF] - for val in cases: - with self.subTest(val=hex(val)): - self.assertEqual(ref_ds_or_b32(val, 0), val) - - def test_oracle_saturation_all_ones(self) -> None: - cases = [0x0, 0x1, 0x55555555, 0xAAAAAAAA, 0x80000000, 0xFFFFFFFF] - for val in cases: - with self.subTest(val=hex(val)): - self.assertEqual(ref_ds_or_b32(val, MASK32), MASK32) - - def test_oracle_idempotence(self) -> None: - cases = [0x0, 0x10203040, 0x55AA55AA, 0xFFFFFFFF] - for val in cases: - with self.subTest(val=hex(val)): - self.assertEqual(ref_ds_or_b32(val, val), val) - - def test_oracle_address_calculation_with_offset(self) -> None: - self.lds.write_dword(0x44, 0x10) - # vaddr=0x40, offset=4 -> eff_addr=0x44 - updated = self.lds.atomic_or_b32(0x40, 0x20, offset16=4) - self.assertEqual(updated, 0x30) - self.assertEqual(self.lds.read_dword(0x44), 0x30) - - def test_oracle_address_dword_alignment(self) -> None: - # Byte addresses 0x40, 0x41, 0x42, 0x43 all map to dword index 16 - self.lds.write_dword(0x40, 0x100) - self.lds.atomic_or_b32(0x41, 0x01) - self.lds.atomic_or_b32(0x42, 0x02) - self.lds.atomic_or_b32(0x43, 0x04) - self.assertEqual(self.lds.read_dword(0x40), 0x107) - - def test_oracle_capacity_wrapping(self) -> None: - # LDS with 1024 dwords (4096 bytes): address 4096 wraps to index 0 - self.lds.write_dword(0, 0x10) - self.lds.atomic_or_b32(4096, 0x20) - self.assertEqual(self.lds.read_dword(0), 0x30) - - -# --------------------------------------------------------------------------- -# Symbolic AST Opcode Definitions and Typed Expressions -# --------------------------------------------------------------------------- - -class RegKind(enum.Enum): - """Register kinds in RDNA2 architecture.""" - VGPR = "v" - SGPR = "s" - - -@dataclasses.dataclass(frozen=True) -class Register: - """Register operand with kind, index, and grouping.""" - kind: RegKind - index: int - count: int = 1 - - def format_asm(self) -> str: - if self.count == 1: - return f"{self.kind.value}{self.index}" - return f"{self.kind.value}[{self.index}:{self.index + self.count - 1}]" - - @property - def is_vgpr(self) -> bool: - return self.kind == RegKind.VGPR - - -@dataclasses.dataclass(frozen=True) -class LdsModifiers: - """Modifiers and options for LDS instructions.""" - offset: int = 0 - - def __post_init__(self) -> None: - if self.offset < 0 or self.offset > 65535: - raise ValueError(f"LDS offset must be in range [0, 65535]: {self.offset}") - - -class Opcode(enum.Enum): - """LDS instruction opcodes.""" - DS_OR_B32 = "ds_or_b32" - - -@dataclasses.dataclass(frozen=True) -class Instruction: - """Symbolic AST node representing a ds_or_b32 instruction.""" - opcode: Opcode - vaddr: Register - vdata: Register - mods: LdsModifiers = dataclasses.field(default_factory=LdsModifiers) - - def __post_init__(self) -> None: - if not self.vaddr.is_vgpr or self.vaddr.count != 1: - raise ValueError(f"vaddr must be a single VGPR: {self.vaddr}") - if not self.vdata.is_vgpr or self.vdata.count != 1: - raise ValueError(f"vdata must be a single VGPR: {self.vdata}") - - def to_assembly(self) -> str: - va_str = self.vaddr.format_asm() - vd_str = self.vdata.format_asm() - off_str = f" offset:{self.mods.offset}" if self.mods.offset != 0 else "" - return f"{self.opcode.value} {va_str}, {vd_str}{off_str}" - - -@dataclasses.dataclass -class Program: - """Symbolic sequence of LDS instructions.""" - instructions: list[Instruction] = dataclasses.field(default_factory=list) - - def append(self, inst: Instruction) -> None: - self.instructions.append(inst) - - def to_assembly(self) -> str: - return "\n".join(inst.to_assembly() for inst in self.instructions) - - -class TestLdsOrB32AST(unittest.TestCase): - """Unit tests for AST data structures and assembly emission.""" - - def test_ast_instruction_creation(self) -> None: - inst = Instruction( - opcode=Opcode.DS_OR_B32, - vaddr=Register(RegKind.VGPR, 0), - vdata=Register(RegKind.VGPR, 1), - ) - self.assertEqual(inst.opcode, Opcode.DS_OR_B32) - self.assertEqual(inst.vaddr.format_asm(), "v0") - self.assertEqual(inst.vdata.format_asm(), "v1") - self.assertEqual(inst.to_assembly(), "ds_or_b32 v0, v1") - - def test_ast_to_assembly_with_offset(self) -> None: - inst = Instruction( - opcode=Opcode.DS_OR_B32, - vaddr=Register(RegKind.VGPR, 2), - vdata=Register(RegKind.VGPR, 3), - mods=LdsModifiers(offset=64), - ) - self.assertEqual(inst.to_assembly(), "ds_or_b32 v2, v3 offset:64") - - def test_ast_program_assembly(self) -> None: - prog = Program() - prog.append(Instruction(Opcode.DS_OR_B32, Register(RegKind.VGPR, 0), Register(RegKind.VGPR, 1))) - prog.append(Instruction(Opcode.DS_OR_B32, Register(RegKind.VGPR, 0), Register(RegKind.VGPR, 2), LdsModifiers(offset=16))) - lines = prog.to_assembly().splitlines() - self.assertEqual(len(lines), 2) - self.assertEqual(lines[0], "ds_or_b32 v0, v1") - self.assertEqual(lines[1], "ds_or_b32 v0, v2 offset:16") - - -# --------------------------------------------------------------------------- -# Condition Codes and Status Flags -# --------------------------------------------------------------------------- - -@dataclasses.dataclass(frozen=True) -class LdsConditionCodes: - """Condition codes reflecting 32-bit bitwise operation result values.""" - zero: bool - negative: bool - positive: bool - - -def compute_lds_condition_codes(result: int) -> LdsConditionCodes: - """Computes condition codes from a 32-bit bitwise operation result.""" - val32 = result & MASK32 - return LdsConditionCodes( - zero=(val32 == 0), - negative=bool(val32 & SIGN_BIT32), - positive=(val32 > 0 and not bool(val32 & SIGN_BIT32)), - ) - - -# --------------------------------------------------------------------------- -# Deterministic Scalar Instruction Interpreter -# --------------------------------------------------------------------------- - -class ScalarLdsInterpreter: - """Deterministic scalar interpreter for ds_or_b32.""" - - def __init__(self, size_dwords: int = DEFAULT_LDS_DWORDS) -> None: - self.vgprs: list[int] = [0] * 256 - self.vcc: int = 0 - self.scc: int = 0 - self.lds: LDSMemory = LDSMemory(size_dwords) - self.trace: list[str] = [] - self.last_condition_codes: LdsConditionCodes | None = None - - def read_vgpr(self, idx: int) -> int: - if idx < 0 or idx >= 256: - raise IndexError(f"VGPR index out of bounds: v{idx}") - return self.vgprs[idx] & MASK32 - - def write_vgpr(self, idx: int, val: int) -> None: - if idx < 0 or idx >= 256: - raise IndexError(f"VGPR index out of bounds: v{idx}") - self.vgprs[idx] = val & MASK32 - - def step(self, inst: Instruction) -> int: - """Executes a single ds_or_b32 instruction; returns updated memory value.""" - vaddr = self.read_vgpr(inst.vaddr.index) - vdata = self.read_vgpr(inst.vdata.index) - updated = self.lds.atomic_or_b32(vaddr, vdata, offset16=inst.mods.offset) - - # ds_or_b32 is non-returning: VGPRs remain unchanged! - self.last_condition_codes = compute_lds_condition_codes(updated) - self.trace.append(f"{inst.to_assembly()} => lds={updated:#010x}") - return updated - - def run_program(self, prog: Program) -> list[int]: - """Executes all instructions in a program sequentially.""" - return [self.step(inst) for inst in prog.instructions] - - -class TestLdsOrB32ScalarInterpreter(unittest.TestCase): - """Unit tests for the deterministic scalar instruction interpreter.""" - - def setUp(self) -> None: - self.interp = ScalarLdsInterpreter(size_dwords=1024) - - def test_scalar_step_basic_or(self) -> None: - self.interp.lds.write_dword(0x10, 0x1100) - self.interp.write_vgpr(0, 0x10) # vaddr - self.interp.write_vgpr(1, 0x0022) # vdata - - inst = Instruction(Opcode.DS_OR_B32, Register(RegKind.VGPR, 0), Register(RegKind.VGPR, 1)) - updated = self.interp.step(inst) - self.assertEqual(updated, 0x1122) - self.assertEqual(self.interp.lds.read_dword(0x10), 0x1122) - - def test_scalar_step_with_immediate_offset(self) -> None: - self.interp.lds.write_dword(0x20, 0x0F) - self.interp.write_vgpr(2, 0x10) # vaddr=0x10 - self.interp.write_vgpr(3, 0xF0) # vdata - - # 0x10 + 0x10 offset = 0x20 - inst = Instruction( - Opcode.DS_OR_B32, - Register(RegKind.VGPR, 2), - Register(RegKind.VGPR, 3), - LdsModifiers(offset=0x10), - ) - updated = self.interp.step(inst) - self.assertEqual(updated, 0xFF) - self.assertEqual(self.interp.lds.read_dword(0x20), 0xFF) - - def test_scalar_non_returning_preserves_vgprs(self) -> None: - self.interp.write_vgpr(0, 0x40) - self.interp.write_vgpr(1, 0xDEADBEEF) - - inst = Instruction(Opcode.DS_OR_B32, Register(RegKind.VGPR, 0), Register(RegKind.VGPR, 1)) - self.interp.step(inst) - - # Neither vaddr nor vdata are modified - self.assertEqual(self.interp.read_vgpr(0), 0x40) - self.assertEqual(self.interp.read_vgpr(1), 0xDEADBEEF) - - -# --------------------------------------------------------------------------- -# SIMD Multi-Lane Wavefront Interpreter (Wave32 and Wave64) -# --------------------------------------------------------------------------- - -class SIMDLdsWavefrontInterpreter: - """SIMD wavefront interpreter supporting Wave32 and Wave64 execution modes.""" - - def __init__(self, wave_size: int = 32, size_dwords: int = DEFAULT_LDS_DWORDS) -> None: - if wave_size not in (32, 64): - raise ValueError(f"Wave size must be 32 or 64, got: {wave_size}") - self.wave_size: int = wave_size - self.vgprs: list[list[int]] = [[0] * 256 for _ in range(wave_size)] - self.exec_mask: int = (1 << wave_size) - 1 - self.lds: LDSMemory = LDSMemory(size_dwords) - - def read_lane_vgpr(self, lane: int, idx: int) -> int: - return self.vgprs[lane][idx] & MASK32 - - def write_lane_vgpr(self, lane: int, idx: int, val: int) -> None: - self.vgprs[lane][idx] = val & MASK32 - - def set_exec_mask(self, mask: int) -> None: - limit = (1 << self.wave_size) - 1 - self.exec_mask = mask & limit - - def step(self, inst: Instruction) -> list[int]: - """Executes ds_or_b32 across all active lanes; returns updated memory values.""" - results: list[int] = [] - for lane in range(self.wave_size): - lane_active = bool((self.exec_mask >> lane) & 1) - if not lane_active: - results.append(0) - continue - - vaddr = self.read_lane_vgpr(lane, inst.vaddr.index) - vdata = self.read_lane_vgpr(lane, inst.vdata.index) - updated = self.lds.atomic_or_b32(vaddr, vdata, offset16=inst.mods.offset) - results.append(updated) - return results - - -class TestLdsOrB32SIMD(unittest.TestCase): - """Unit tests for SIMD execution divergence across Wave32 and Wave64 wavefronts.""" - - def test_simd_wave32_all_active_independent_addresses(self) -> None: - simd = SIMDLdsWavefrontInterpreter(wave_size=32, size_dwords=1024) - for lane in range(32): - addr = lane * 4 - simd.lds.write_dword(addr, 0x1000) - simd.write_lane_vgpr(lane, 0, addr) # vaddr - simd.write_lane_vgpr(lane, 1, 1 << lane) # vdata - - inst = Instruction(Opcode.DS_OR_B32, Register(RegKind.VGPR, 0), Register(RegKind.VGPR, 1)) - simd.step(inst) - - for lane in range(32): - self.assertEqual(simd.lds.read_dword(lane * 4), 0x1000 | (1 << lane)) - - def test_simd_wave32_divergent_alternating_mask(self) -> None: - simd = SIMDLdsWavefrontInterpreter(wave_size=32, size_dwords=1024) - simd.set_exec_mask(0x55555555) # Even lanes active, odd inactive - - for lane in range(32): - addr = lane * 4 - simd.lds.write_dword(addr, 0x00FF) - simd.write_lane_vgpr(lane, 0, addr) - simd.write_lane_vgpr(lane, 1, 0xFF00) - - inst = Instruction(Opcode.DS_OR_B32, Register(RegKind.VGPR, 0), Register(RegKind.VGPR, 1)) - simd.step(inst) - - for lane in range(32): - if lane % 2 == 0: - self.assertEqual(simd.lds.read_dword(lane * 4), 0xFFFF) - else: - self.assertEqual(simd.lds.read_dword(lane * 4), 0x00FF) - - def test_simd_wave64_divergent_half_mask(self) -> None: - simd = SIMDLdsWavefrontInterpreter(wave_size=64, size_dwords=1024) - simd.set_exec_mask(0x00000000FFFFFFFF) # Lower 32 lanes active - - for lane in range(64): - addr = lane * 4 - simd.lds.write_dword(addr, 0x1200) - simd.write_lane_vgpr(lane, 0, addr) - simd.write_lane_vgpr(lane, 1, 0x0034) - - inst = Instruction(Opcode.DS_OR_B32, Register(RegKind.VGPR, 0), Register(RegKind.VGPR, 1)) - simd.step(inst) - - for lane in range(64): - if lane < 32: - self.assertEqual(simd.lds.read_dword(lane * 4), 0x1234) - else: - self.assertEqual(simd.lds.read_dword(lane * 4), 0x1200) - - def test_simd_multi_lane_atomic_reduction_to_same_address(self) -> None: - # Multiple active lanes targeting the exact same LDS dword atomically aggregate their bits - simd = SIMDLdsWavefrontInterpreter(wave_size=32, size_dwords=1024) - simd.lds.write_dword(0x80, 0x00000000) - - for lane in range(16): - simd.write_lane_vgpr(lane, 0, 0x80) # Same address - simd.write_lane_vgpr(lane, 1, 1 << lane) # Distinct bit - simd.set_exec_mask(0x0000FFFF) # First 16 lanes active - - inst = Instruction(Opcode.DS_OR_B32, Register(RegKind.VGPR, 0), Register(RegKind.VGPR, 1)) - simd.step(inst) - - # All 16 bits [0:15] must be atomically aggregated into memory - self.assertEqual(simd.lds.read_dword(0x80), 0x0000FFFF) - - -# --------------------------------------------------------------------------- -# Register Aliasing and In-Place Operand Preservation -# --------------------------------------------------------------------------- - -class TestLdsOrB32RegisterAliasing(unittest.TestCase): - """Unit tests for overlapping register allocations and in-place operand preservation.""" - - def setUp(self) -> None: - self.interp = ScalarLdsInterpreter(size_dwords=1024) - - def test_aliasing_vaddr_same_as_vdata(self) -> None: - # ds_or_b32 v0, v0: v0 is both address and data mask! - # When v0 = 0x40, effective byte address is 0x40, and OR mask is 0x40. - self.interp.lds.write_dword(0x40, 0x01) - self.interp.write_vgpr(0, 0x40) - - inst = Instruction(Opcode.DS_OR_B32, Register(RegKind.VGPR, 0), Register(RegKind.VGPR, 0)) - updated = self.interp.step(inst) - self.assertEqual(updated, 0x41) - self.assertEqual(self.interp.lds.read_dword(0x40), 0x41) - # Non-returning: v0 remains 0x40 - self.assertEqual(self.interp.read_vgpr(0), 0x40) - - def test_preserve_all_vgprs_post_execution(self) -> None: - # Verify that registers v0..v7 remain unmodified - for reg in range(8): - self.interp.write_vgpr(reg, 0x1000 + reg) - self.interp.lds.write_dword(0x1000, 0) - - inst = Instruction(Opcode.DS_OR_B32, Register(RegKind.VGPR, 0), Register(RegKind.VGPR, 1)) - self.interp.step(inst) - - for reg in range(8): - self.assertEqual(self.interp.read_vgpr(reg), 0x1000 + reg) - - -# --------------------------------------------------------------------------- -# Condition Codes, Status Flags, and Carry/Borrow Isolation Tests -# --------------------------------------------------------------------------- - -class TestLdsOrB32ConditionCodes(unittest.TestCase): - """Unit tests for condition code tracking and VCC/SCC isolation.""" - - def test_condition_codes_zero(self) -> None: - cc = compute_lds_condition_codes(0) - self.assertTrue(cc.zero) - self.assertFalse(cc.negative) - self.assertFalse(cc.positive) - - def test_condition_codes_negative(self) -> None: - cc = compute_lds_condition_codes(SIGN_BIT32 | 0x42) - self.assertFalse(cc.zero) - self.assertTrue(cc.negative) - self.assertFalse(cc.positive) - - def test_condition_codes_positive(self) -> None: - cc = compute_lds_condition_codes(0x00001234) - self.assertFalse(cc.zero) - self.assertFalse(cc.negative) - self.assertTrue(cc.positive) - - def test_vcc_and_scc_isolation(self) -> None: - interp = ScalarLdsInterpreter(size_dwords=1024) - interp.vcc = 0xDEADBEEFCAFEBABE - interp.scc = 1 - interp.lds.write_dword(0, 0) - interp.write_vgpr(0, 0) - interp.write_vgpr(1, 0xFF) - - inst = Instruction(Opcode.DS_OR_B32, Register(RegKind.VGPR, 0), Register(RegKind.VGPR, 1)) - interp.step(inst) - - # Neither VCC nor SCC can be modified by LDS instructions - self.assertEqual(interp.vcc, 0xDEADBEEFCAFEBABE) - self.assertEqual(interp.scc, 1) - - -# --------------------------------------------------------------------------- -# IEEE 754 Boundary Extremes, Subnormals, and NaN Handling -# --------------------------------------------------------------------------- - -class TestLdsOrB32BoundaryExtremes(unittest.TestCase): - """Unit tests for boundary extremes, integer wrapping, and IEEE 754 bit representations.""" - - def setUp(self) -> None: - self.lds = LDSMemory(size_dwords=1024) - - def test_32bit_integer_extremes(self) -> None: - # INT32_MAX | INT32_MIN = UINT32_MAX - self.lds.write_dword(0, 0x7FFFFFFF) - updated = self.lds.atomic_or_b32(0, 0x80000000) - self.assertEqual(updated, 0xFFFFFFFF) - - def test_float32_bit_pattern_preservation(self) -> None: - # Untyped bitwise OR operates on raw bits without float quietening or subnormal flushing - qnan_bits = 0x7FC00000 - subnormal_bits = 0x00000001 - self.lds.write_dword(0x10, qnan_bits) - updated = self.lds.atomic_or_b32(0x10, subnormal_bits) - self.assertEqual(updated, qnan_bits | subnormal_bits) - - # +0.0 (0x00000000) | -0.0 (0x80000000) = 0x80000000 - self.lds.write_dword(0x20, 0x00000000) - updated_zero = self.lds.atomic_or_b32(0x20, 0x80000000) - self.assertEqual(updated_zero, 0x80000000) - - def test_lds_offset_boundary_max_16bit(self) -> None: - # Max unsigned 16-bit offset = 0xFFFF (65535) - # 65535 bytes = dword index (65535 >> 2) & 1023 = 16383 & 1023 = 1023 - self.lds.write_dword(1023 * 4, 0x10) - updated = self.lds.atomic_or_b32(0, 0x20, offset16=0xFFFF) - self.assertEqual(updated, 0x30) - self.assertEqual(self.lds.read_dword(1023 * 4), 0x30) - - -# --------------------------------------------------------------------------- -# Negative Controls, Syntax Rejection, and Mutation Detection -# --------------------------------------------------------------------------- - -class TestLdsOrB32NegativeControls(unittest.TestCase): - """Negative controls and syntax rejection tests for ds_or_b32.""" - - def test_invalid_vaddr_kind_and_count(self) -> None: - with self.assertRaises(ValueError): - Instruction(Opcode.DS_OR_B32, Register(RegKind.SGPR, 0), Register(RegKind.VGPR, 1)) - with self.assertRaises(ValueError): - Instruction(Opcode.DS_OR_B32, Register(RegKind.VGPR, 0, count=2), Register(RegKind.VGPR, 1)) - - def test_invalid_vdata_kind_and_count(self) -> None: - with self.assertRaises(ValueError): - Instruction(Opcode.DS_OR_B32, Register(RegKind.VGPR, 0), Register(RegKind.SGPR, 1)) - with self.assertRaises(ValueError): - Instruction(Opcode.DS_OR_B32, Register(RegKind.VGPR, 0), Register(RegKind.VGPR, 1, count=2)) - - def test_invalid_offset_range(self) -> None: - with self.assertRaises(ValueError): - LdsModifiers(offset=-1) - with self.assertRaises(ValueError): - LdsModifiers(offset=65536) - - def test_invalid_wave_size(self) -> None: - with self.assertRaises(ValueError): - SIMDLdsWavefrontInterpreter(wave_size=16) - with self.assertRaises(ValueError): - SIMDLdsWavefrontInterpreter(wave_size=128) - - def test_register_bounds_scalar_interpreter(self) -> None: - interp = ScalarLdsInterpreter(size_dwords=1024) - with self.assertRaises(IndexError): - interp.read_vgpr(-1) - with self.assertRaises(IndexError): - interp.read_vgpr(256) - with self.assertRaises(IndexError): - interp.write_vgpr(-1, 0) - with self.assertRaises(IndexError): - interp.write_vgpr(256, 0) - - -class TestLdsOrB32MutationDetection(unittest.TestCase): - """Tests ensuring mutation kill for common semantic implementation errors.""" - - def test_mutant_and_instead_of_or_killed(self) -> None: - # A mutant computing bitwise AND instead of OR must be rejected - self.assertNotEqual(ref_ds_or_b32(0xF0, 0x0F), 0xF0 & 0x0F) - self.assertEqual(ref_ds_or_b32(0xF0, 0x0F), 0xFF) - - def test_mutant_xor_instead_of_or_killed(self) -> None: - # A mutant computing bitwise XOR instead of OR must be rejected - self.assertNotEqual(ref_ds_or_b32(0xFF, 0xFF), 0xFF ^ 0xFF) - self.assertEqual(ref_ds_or_b32(0xFF, 0xFF), 0xFF) - - def test_mutant_inactive_lane_leak_killed(self) -> None: - simd = SIMDLdsWavefrontInterpreter(wave_size=32, size_dwords=1024) - simd.lds.write_dword(0, 0x10) - simd.lds.write_dword(4, 0x20) - - # Enable only lane 0; lane 1 is inactive - simd.set_exec_mask(0x1) - - simd.write_lane_vgpr(0, 0, 0) # vaddr lane 0 = 0 - simd.write_lane_vgpr(0, 1, 0x01) # vdata lane 0 = 0x01 - simd.write_lane_vgpr(1, 0, 4) # vaddr lane 1 = 4 - simd.write_lane_vgpr(1, 1, 0x02) # vdata lane 1 = 0x02 - - inst = Instruction(Opcode.DS_OR_B32, Register(RegKind.VGPR, 0), Register(RegKind.VGPR, 1)) - simd.step(inst) - - # Lane 0 active: 0x10 | 0x01 = 0x11 - self.assertEqual(simd.lds.read_dword(0), 0x11) - # Lane 1 inactive: must remain untouched 0x20 - self.assertEqual(simd.lds.read_dword(4), 0x20) - - -class TestLdsOrB32TranslationAndExecution(unittest.TestCase): - """End-to-end SPIR-V translation and execution under support and spirv_mini_interp.""" - - def test_translator_ds_or_b32_basic(self) -> None: - if support is None or rdna2spirv is None or lds_run is None: - self.skipTest("support/rdna2spirv/lds_run not available in this Python environment") - - asm = [ - "v_mov_b32_e32 v0, 0x10", - "v_mov_b32_e32 v1, 0x0F", - "ds_or_b32 v0, v1", - "s_endpgm", - ] - spvasm = support.translate_lines("cs_lds_or_b32_basic", asm, fssm=lds_run.fssm()) - self.assertIn("OpAtomicOr", spvasm) - - def test_execution_ds_or_b32_chain(self) -> None: - if support is None or rdna2spirv is None or lds_run is None: - self.skipTest("support/rdna2spirv/lds_run not available in this Python environment") - - # Initialize LDS byte 0x20 with 0xF0, then execute ds_or_b32 with 0x0F - rets, mem = lds_run.run_chain([("ds_or_b32", 0x20, 0, [0x0F])], {0x20: 0xF0}) - self.assertEqual(mem[0x20], 0xFF) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_lds_read2_write2_b64.py b/tests/semantic/test_lds_read2_write2_b64.py deleted file mode 100644 index 6aaf5c284..000000000 --- a/tests/semantic/test_lds_read2_write2_b64.py +++ /dev/null @@ -1,147 +0,0 @@ -"""ds_read2_b64, ds_write2_b64, ds_read2st64_b64, ds_write2st64_b64: two 64-bit LDS elements per instruction. - -Standard library only; no GPU, no LLVM, no game files. - -RDNA2 ISA, "Data Share Instructions": the 2-address forms access two elements at - ADDR0 = vaddr + offset0 * unit, ADDR1 = vaddr + offset1 * unit -where unit is the element size in bytes (8 for b64), times 64 for the st64 ("stride 64") forms. A b64 element is two -consecutive dwords, low first: - * ds_write2_b64 vaddr, vdata0[0:1], vdata1[0:1]: MEM[ADDR0] = vdata0, MEM[ADDR1] = vdata1 - * ds_read2_b64 vdst[0:3], vaddr: vdst[0:1] = MEM[ADDR0], vdst[2:3] = MEM[ADDR1] -The b32 forms (ds_read2_b32 / ds_write2_b32 and their st64 variants) use unit 4 and are already translated; this -checks that the b64 forms use unit 8 and move both dwords of each element. - -Each case is a compute shader run as one invocation (lane 0) through tests/semantic/spirv_mini_interp.py, with LDS -as a Workgroup variable (#592). It writes LDS with one form, reads it back with plain ds_read_b32 (and with -ds_read2_b64), and stores the dwords it read to a buffer; those words are compared with a plain-Python model of LDS. -""" -import os -import struct -import sys -import tempfile -import unittest -import warnings - -HERE = os.path.dirname(os.path.abspath(__file__)) -ROOT = os.path.dirname(os.path.dirname(HERE)) -TOOLS_DIR = os.environ.get("LEONIDA_TOOLS_DIR") or os.path.join(ROOT, "tools") - -sys.dont_write_bytecode = True -sys.path.insert(0, TOOLS_DIR) -sys.path.insert(0, HERE) - -import rdna2spirv # noqa: E402 -import spirv_mini_interp as si # noqa: E402 - -STUB_DXBC = b"DXBC" + bytes(24) + struct.pack(" dict: - """LDS dword index -> value after ds_write2_* of A at element offset0 and B at offset1.""" - lds = {} - for (lo, hi), off in ((A, off0), (B, off1)): - addr = (base + off * unit) % LDS_BYTES - lds[addr // 4] = lo - lds[(addr // 4 + 1) % (LDS_BYTES // 4)] = hi - return lds - - -def run_listing(body: list) -> dict: - """Translate the compute listing `body` (it ends with buffer stores) and run lane 0; return buffer words.""" - with tempfile.TemporaryDirectory() as tmp: - os.mkdir(os.path.join(tmp, "disasm")) - os.mkdir(os.path.join(tmp, "fssm")) - name = "cs_lds_read2_b64" - with open(os.path.join(tmp, "disasm", name + ".s"), "w", encoding="utf-8") as f: - f.write("; " + name + "\n" + "".join(f"\t{ln}\n" for ln in body) + "\ts_endpgm\n") - with open(os.path.join(tmp, name + ".dxbc"), "wb") as f: - f.write(STUB_DXBC) - with open(os.path.join(tmp, "fssm", name + ".fssm"), "wb") as f: - f.write(FSSM) - with warnings.catch_warnings(): - warnings.simplefilter("ignore", ResourceWarning) - spv = rdna2spirv.translate(os.path.join(tmp, "disasm", name + ".s")) - return si.run_workgroup(spv, 1, 32, inputs_for=lambda i: {"%wg_id": (0, 0, 0), "%local_id": (i, 0, 0), "%sg_lane": i}, - push_constants=VSHARP + [0] * 28, memory={}) - - -def store_lines(regs) -> list: - out = [] - for k, r in enumerate(regs): - out += [f"v_mov_b32_e32 v31, {4 * k}", f"buffer_store_dword v{r}, v31, s[0:3], 0 offen"] - return out - - -def write_then_read_b32(op: str, base: int, off0: int, off1: int, unit: int) -> list: - """ds_write2(st64)_b64 with A, B; read the four dwords back with ds_read_b32; return them.""" - lines = [f"v_mov_b32_e32 v2, {base:#x}", f"v_mov_b32_e32 v4, {A[0]:#x}", f"v_mov_b32_e32 v5, {A[1]:#x}", - f"v_mov_b32_e32 v6, {B[0]:#x}", f"v_mov_b32_e32 v7, {B[1]:#x}", - f"{op} v2, v[4:5], v[6:7] offset0:{off0} offset1:{off1}", "s_waitcnt lgkmcnt(0)"] - regs = [] - for k, (off, w) in enumerate(((off0, 0), (off0, 4), (off1, 0), (off1, 4))): - addr = (base + off * unit + w) % LDS_BYTES - lines += [f"v_mov_b32_e32 v8, {addr:#x}", f"ds_read_b32 v{10 + k}, v8"] - regs.append(10 + k) - lines.append("s_waitcnt lgkmcnt(0)") - mem = run_listing(lines + store_lines(regs)) - return [mem.get(4 * k) for k in range(4)] - - -class LdsWrite2B64(unittest.TestCase): - def test_model(self): - lds = model_write2(16, 1, 3, 8) - self.assertEqual(lds, {6: A[0], 7: A[1], 10: B[0], 11: B[1]}) - - def test_ds_write2_b64_unit_is_8_bytes(self): - for base, off0, off1 in ((0, 0, 1), (16, 1, 3), (8, 2, 255), (0x100, 0, 7)): - with self.subTest(base=base, offset0=off0, offset1=off1): - self.assertEqual(write_then_read_b32("ds_write2_b64", base, off0, off1, 8), [*A, *B]) - - def test_ds_write2st64_b64_unit_is_512_bytes(self): - for base, off0, off1 in ((0, 0, 1), (8, 1, 3), (0x40, 2, 7)): - with self.subTest(base=base, offset0=off0, offset1=off1): - self.assertEqual(write_then_read_b32("ds_write2st64_b64", base, off0, off1, 8 * 64), [*A, *B]) - - -class LdsRead2B64(unittest.TestCase): - def read2(self, op: str, base: int, off0: int, off1: int, unit: int) -> list: - """Seed LDS with ds_write_b32 at the two elements' dwords, ds_read2(st64)_b64 them into v[10:13].""" - lines = [] - for k, (off, w) in enumerate(((off0, 0), (off0, 4), (off1, 0), (off1, 4))): - addr = (base + off * unit + w) % LDS_BYTES - lines += [f"v_mov_b32_e32 v8, {addr:#x}", f"v_mov_b32_e32 v9, {(A + B)[k]:#x}", "ds_write_b32 v8, v9"] - lines += ["s_waitcnt lgkmcnt(0)", f"v_mov_b32_e32 v2, {base:#x}", - f"{op} v[10:13], v2 offset0:{off0} offset1:{off1}", "s_waitcnt lgkmcnt(0)"] - mem = run_listing(lines + store_lines([10, 11, 12, 13])) - return [mem.get(4 * k) for k in range(4)] - - def test_ds_read2_b64(self): - for base, off0, off1 in ((0, 0, 1), (16, 1, 3), (8, 2, 255), (0x100, 7, 0)): - with self.subTest(base=base, offset0=off0, offset1=off1): - self.assertEqual(self.read2("ds_read2_b64", base, off0, off1, 8), [*A, *B]) - - def test_ds_read2st64_b64(self): - for base, off0, off1 in ((0, 0, 1), (8, 1, 3), (0x40, 2, 7)): - with self.subTest(base=base, offset0=off0, offset1=off1): - self.assertEqual(self.read2("ds_read2st64_b64", base, off0, off1, 8 * 64), [*A, *B]) - - def test_round_trip(self): - # write2_b64 then read2_b64 at the same offsets gives back both pairs. - lines = ["v_mov_b32_e32 v2, 0x20", f"v_mov_b32_e32 v4, {A[0]:#x}", f"v_mov_b32_e32 v5, {A[1]:#x}", - f"v_mov_b32_e32 v6, {B[0]:#x}", f"v_mov_b32_e32 v7, {B[1]:#x}", - "ds_write2_b64 v2, v[4:5], v[6:7] offset0:3 offset1:9", "s_waitcnt lgkmcnt(0)", - "ds_read2_b64 v[10:13], v2 offset0:9 offset1:3", "s_waitcnt lgkmcnt(0)"] - mem = run_listing(lines + store_lines([10, 11, 12, 13])) - self.assertEqual([mem.get(4 * k) for k in range(4)], [*B, *A]) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_lds_read_u8_d16.py b/tests/semantic/test_lds_read_u8_d16.py deleted file mode 100644 index d0f6cc486..000000000 --- a/tests/semantic/test_lds_read_u8_d16.py +++ /dev/null @@ -1,86 +0,0 @@ -"""ds_read_u8_d16, ds_read_u8_d16_hi, ds_read_i8_d16, ds_read_i8_d16_hi: 8-bit LDS reads into one half of a VGPR. - -Standard library only; no GPU, no LLVM, no game files. - - python -m unittest discover -s tests/semantic -p "test_lds_read_u8_d16.py" -v - -RDNA2 ISA, "Data Share Instructions" (DS opcodes 162-165), the d16 forms of the byte reads: - * ds_read_u8_d16 D[15:0] = zero-extend(MEM[ADDR][7:0]), D[31:16] unchanged - * ds_read_u8_d16_hi D[31:16] = zero-extend(MEM[ADDR][7:0]), D[15:0] unchanged - * ds_read_i8_d16 D[15:0] = sign-extend 8 -> 16 of MEM[ADDR][7:0], D[31:16] unchanged - * ds_read_i8_d16_hi D[31:16] = sign-extend 8 -> 16 of MEM[ADDR][7:0], D[15:0] unchanged -ADDR = vaddr + offset (bytes). The "other half kept" rule is the one the translator already applies to -ds_read_u16_d16 / ds_read_u16_d16_hi. - -The input is the GPU test runtime/test/shaders/cs_w32_lds_u8_d16.asm (fixture from regen_fixtures.py): it stores -LDS dword 0 = 0x7F80FF01, presets every destination to 0xBEEF1234 and reads single bytes with a non-zero offset -or base. It is translated for wave32 and run as one invocation (lane 0); the eight words it stores are compared -with values derived here from the ISA text above (the same values check.py / run_gpu_tests.py expect). -""" -import struct -import unittest - -import support -import spirv_mini_interp as si - -# 4 user SGPRs (the output V#), workgroup id in s4, 512 bytes of LDS, 32x1x1 threads. -FSSM = bytearray(0x148) -struct.pack_into("<4I", FSSM, 0x138, 0x8088, 32, 1, 1) -FSSM = bytes(FSSM) -VSHARP = [0, 0, 0x1000, 0x31016FAC] - -LDS_BYTES = (0x01, 0xFF, 0x80, 0x7F) # bytes at byte address 0..3 of LDS dword 0 = 0x7F80FF01 -OLD = 0xBEEF1234 # every destination before the read - - -def sext16(b): - return b | 0xFF00 if b & 0x80 else b - - -def to_lo(old, h): - return (old & 0xFFFF0000) | h - - -def to_hi(old, h): - return (old & 0xFFFF) | (h << 16) - - -# In the order the shader stores them. -EXPECTED = [ - to_lo(OLD, LDS_BYTES[1]), # u8_d16 offset:1 -> 0xFF - to_hi(OLD, LDS_BYTES[1]), # u8_d16_hi offset:1 - to_lo(OLD, sext16(LDS_BYTES[2])), # i8_d16 offset:2 -> 0x80 - to_hi(OLD, sext16(LDS_BYTES[2])), # i8_d16_hi offset:2 - to_lo(OLD, sext16(LDS_BYTES[3])), # i8_d16 offset:3 -> 0x7F - to_hi(OLD, sext16(LDS_BYTES[3])), # i8_d16_hi offset:3 - to_lo(OLD, LDS_BYTES[2]), # u8_d16 offset:2 -> 0x80 stays 0x0080 - to_hi(OLD, sext16(LDS_BYTES[1])), # i8_d16_hi v1 = 1, no offset -> 0xFF -] - - -def run(): - spv = support.translate_fixture("cs_w32_lds_u8_d16", fssm=FSSM) - memory = si.run_workgroup( - spv, 1, 32, - inputs_for=lambda i: {"%wg_id": (0, 0, 0), "%local_id": (i, 0, 0), "%sg_lane": i}, - push_constants=VSHARP + [0] * 28, memory={}) - stray = sorted(a for a in memory if not 0 <= a < 32 or a % 4) - if stray: - raise AssertionError(f"stores outside out[0..7]: {stray}") - return [memory.get(4 * k) for k in range(8)] - - -class LdsReadU8I8D16(unittest.TestCase): - def test_reference_values(self): - self.assertEqual(EXPECTED, [0xBEEF00FF, 0x00FF1234, 0xBEEFFF80, 0xFF801234, - 0xBEEF007F, 0x007F1234, 0xBEEF0080, 0xFFFF1234]) - - def test_translated_shader(self): - got = run() - for k, (g, w) in enumerate(zip(got, EXPECTED)): - with self.subTest(word=k): - self.assertEqual(g, w, f"out[{k}] = {g if g is None else hex(g)}, want {hex(w)}") - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_lds_read_write.py b/tests/semantic/test_lds_read_write.py deleted file mode 100644 index 904ba264d..000000000 --- a/tests/semantic/test_lds_read_write.py +++ /dev/null @@ -1,176 +0,0 @@ -"""ds_write_b32/b64/b96/b128, ds_read_b32/b64/b96/b128, ds_write_b8/b16 and ds_read_u8/i8/u16/i16 through the translator. - -Standard library only; no GPU, no LLVM, no game files. - -RDNA2 ISA, "Data Share Instructions": the address is vaddr + offset (bytes), the dword at ADDR / 4; the b64/b96/b128 -forms move 2/3/4 consecutive dwords, low first (the dword at ADDR + 4 k goes to / comes from VGPR k of the group). -LDS is `LDS_SIZE` bytes and the address wraps at that size. The 8/16-bit forms address a byte of the dword at ADDR / 4: -byte position (ADDR & 3), halfword (ADDR & 2), zero or sign extended on a read; a write replaces only those bits. - -Each case is a compute shader translated by tools/rdna2spirv.py (support.translate_lines) and run for 32 lanes in -tests/semantic/spirv_mini_interp.py; every lane works in its own LDS words and stores what it read to an output -buffer. The expected words are written out by hand from the rules above, and a plain-Python LDS model gives the same -words for seeded random data. Until this file, the LDS tests of this name ran a self-built interpreter that never -reached the translator. -""" -import os -import random -import sys -import unittest - -sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) -import lds_run as L # noqa: E402 (also puts tools/ on sys.path) -import rdna2spirv # noqa: E402 -import support # noqa: E402 - -M32 = L.M32 -LDS_BYTES = 4096 - - -class Model: - """Plain-Python LDS: a dict of dwords by index, addresses wrapping at LDS_BYTES.""" - - def __init__(self): - self.w = {} - - def write32(self, addr, v): - self.w[(addr % LDS_BYTES) // 4] = v & M32 - - def read32(self, addr): - return self.w.get((addr % LDS_BYTES) // 4, 0) - - def write_bits(self, addr, v, bits): - sh = (addr & 3) * 8 - m = ((1 << bits) - 1) << sh - self.w[(addr % LDS_BYTES) // 4] = (self.read32(addr) & ~m & M32) | ((v << sh) & m) - - def read_bits(self, addr, bits, signed): - v = (self.read32(addr) >> ((addr & 3) * 8)) & ((1 << bits) - 1) - if signed and v >> (bits - 1): - v = (v | (M32 << bits)) & M32 - return v - - -class TestDwordForms(unittest.TestCase): - def test_b32_offset_by_hand(self): - # lane i: v1 = 8 i; write 0x1000 + i at v1 + 0x10, read it back at v1 + 0x10 through a different split. - body = ["v_lshlrev_b32_e32 v1, 3, v0", "v_add_nc_u32_e32 v2, 0x1000, v0", - "ds_write_b32 v1, v2 offset:0x10", "s_waitcnt lgkmcnt(0)", - "v_add_nc_u32_e32 v3, 0x10, v1", "ds_read_b32 v4, v3", "s_waitcnt lgkmcnt(0)", - "ds_read_b32 v5, v1 offset:0x10", "s_waitcnt lgkmcnt(0)"] + L.store("v4", 0) + L.store("v5", 1) - mem = L.run(body) - for i in range(32): - self.assertEqual((L.out(mem, i, 0), L.out(mem, i, 1)), (0x1000 + i, 0x1000 + i), f"lane {i}") - - def test_wide_forms_by_hand(self): - # lane i: v1 = 16 i; v[4:7] = four known words; write as b128, read back as b128, b96, b64 and b32 + offsets. - body = ["v_lshlrev_b32_e32 v1, 4, v0", "v_add_nc_u32_e32 v4, 0x100, v0", "v_add_nc_u32_e32 v5, 0x200, v0", - "v_add_nc_u32_e32 v6, 0x300, v0", "v_add_nc_u32_e32 v7, 0x400, v0", - "ds_write_b128 v1, v[4:7]", "s_waitcnt lgkmcnt(0)", - "ds_read_b128 v[8:11], v1", "ds_read_b96 v[12:14], v1", "ds_read_b64 v[16:17], v1 offset:8", - "ds_read_b32 v18, v1 offset:12", "s_waitcnt lgkmcnt(0)"] - for k, r in enumerate(("v8", "v9", "v10", "v11", "v12", "v13", "v14")): - body += L.store(r, k) - body += L.store("v16", 7) - mem = L.run(body) - for i in range(32): - got = [L.out(mem, i, k) for k in range(8)] - want = [0x100 + i, 0x200 + i, 0x300 + i, 0x400 + i, 0x100 + i, 0x200 + i, 0x300 + i, 0x300 + i] - self.assertEqual(got, want, f"lane {i}") - - def test_b64_and_b96_write(self): - body = ["v_lshlrev_b32_e32 v1, 4, v0", "v_add_nc_u32_e32 v4, 0x11, v0", "v_add_nc_u32_e32 v5, 0x22, v0", - "v_add_nc_u32_e32 v6, 0x33, v0", - "ds_write_b64 v1, v[4:5] offset:4", "ds_write_b96 v1, v[4:6] offset:0x800", "s_waitcnt lgkmcnt(0)", - "ds_read_b32 v8, v1 offset:4", "ds_read_b32 v9, v1 offset:8", "ds_read_b32 v10, v1 offset:0x800", - "ds_read_b32 v11, v1 offset:0x808", "s_waitcnt lgkmcnt(0)"] - for k, r in enumerate(("v8", "v9", "v10", "v11")): - body += L.store(r, k) - mem = L.run(body) - for i in range(32): - self.assertEqual([L.out(mem, i, k) for k in range(4)], [0x11 + i, 0x22 + i, 0x11 + i, 0x33 + i], f"lane {i}") - - def test_address_wraps_at_lds_size(self): - # LDS_SIZE is 4 KiB here (and no offset grows it): byte 4096 + 8 is byte 8, with the offset or without. - body = ["v_mov_b32_e32 v1, 0x1008", "v_add_nc_u32_e32 v2, 0x7000, v0", - "v_lshlrev_b32_e32 v3, 6, v0", # lane i uses its own word: 64 i - "v_add_nc_u32_e32 v1, v1, v3", - "ds_write_b32 v1, v2", "s_waitcnt lgkmcnt(0)", - "v_add_nc_u32_e32 v4, 8, v3", "ds_read_b32 v5, v4", "ds_read_b32 v6, v3 offset:8", - "s_waitcnt lgkmcnt(0)"] + L.store("v5", 0) + L.store("v6", 1) - mem = L.run(body) - for i in range(32): - self.assertEqual((L.out(mem, i, 0), L.out(mem, i, 1)), (0x7000 + i, 0x7000 + i), f"lane {i}") - - -class TestSubDwordForms(unittest.TestCase): - WORD = 0x7F80FF01 # bytes 01 FF 80 7F - - def test_reads_by_hand(self): - body = ["v_lshlrev_b32_e32 v1, 3, v0", "v_mov_b32_e32 v2, 0x7f80ff01", - "ds_write_b32 v1, v2 offset:0x40", "s_waitcnt lgkmcnt(0)", - "ds_read_u8 v4, v1 offset:0x41", "ds_read_i8 v5, v1 offset:0x41", "ds_read_i8 v6, v1 offset:0x43", - "ds_read_u16 v7, v1 offset:0x42", "ds_read_i16 v8, v1 offset:0x40", "ds_read_i16 v9, v1 offset:0x42", - "s_waitcnt lgkmcnt(0)"] - for k, r in enumerate(("v4", "v5", "v6", "v7", "v8", "v9")): - body += L.store(r, k) - mem = L.run(body) - want = [0xFF, 0xFFFFFFFF, 0x7F, 0x7F80, 0xFFFFFF01, 0x7F80] - # i16 at byte 0 is 0xFF01 -> sign extended 0xFFFFFF01; at byte 2 is 0x7F80 (positive). - for i in range(32): - self.assertEqual([L.out(mem, i, k) for k in range(6)], want, f"lane {i}") - - def test_writes_replace_only_their_bits(self): - body = ["v_lshlrev_b32_e32 v1, 3, v0", "v_mov_b32_e32 v2, 0x11223344", "v_mov_b32_e32 v3, 0xaabbccdd", - "ds_write_b32 v1, v2", "s_waitcnt lgkmcnt(0)", - "ds_write_b8 v1, v3 offset:1", "ds_write_b16 v1, v3 offset:2", "s_waitcnt lgkmcnt(0)", - "ds_read_b32 v4, v1", "s_waitcnt lgkmcnt(0)", - "ds_write_b8_d16_hi v1, v3", "ds_write_b16_d16_hi v1, v3 offset:4", "s_waitcnt lgkmcnt(0)", - "ds_read_b32 v5, v1", "ds_read_b32 v6, v1 offset:4", "s_waitcnt lgkmcnt(0)"] - for k, r in enumerate(("v4", "v5", "v6")): - body += L.store(r, k) - mem = L.run(body) - # 0x11223344: b8 0xdd at byte 1 -> 0x1122dd44; b16 0xccdd at byte 2 -> 0xccdddd44; - # b8_d16_hi stores bits 23:16 of v3 (0xbb) at byte 0 -> 0xccdddbb... = 0xccddddbb; - # b16_d16_hi stores bits 31:16 of v3 (0xaabb) at byte 4: the neighbouring dword was never written (0) -> 0xaabb. - for i in range(32): - self.assertEqual([L.out(mem, i, k) for k in range(3)], [0xCCDDDD44, 0xCCDDDDBB, 0xAABB], f"lane {i}") - - def test_seeded_against_the_model(self): - rng = random.Random(0x1D5F) - for trial in range(6): - ops = [] - body = ["v_lshlrev_b32_e32 v1, 4, v0"] - model = Model() - base = 0 # the model is lane 0's words; every lane runs the same program on its own - word, wr = rng.getrandbits(32), rng.getrandbits(32) - body += [f"v_mov_b32_e32 v2, {word:#x}", f"v_mov_b32_e32 v3, {wr:#x}", "ds_write_b32 v1, v2", - "s_waitcnt lgkmcnt(0)"] - model.write32(base, word) - for _ in range(4): - kind = rng.choice(("b8", "b16")) - off = rng.randrange(0, 4 if kind == "b8" else 3, 1 if kind == "b8" else 2) - body += [f"ds_write_{kind} v1, v3 offset:{off}", "s_waitcnt lgkmcnt(0)"] - model.write_bits(base + off, wr, 8 if kind == "b8" else 16) - wr = rng.getrandbits(32) - body += [f"v_mov_b32_e32 v3, {wr:#x}"] - for k, (op, bits, sg) in enumerate((("u8", 8, 0), ("i8", 8, 1), ("u16", 16, 0), ("i16", 16, 1))): - off = rng.randrange(0, 4, bits // 8) - body += [f"ds_read_{op} v{4 + k}, v1 offset:{off}", "s_waitcnt lgkmcnt(0)"] + L.store(f"v{4 + k}", k) - ops.append(model.read_bits(base + off, bits, sg)) - body += ["ds_read_b32 v9, v1", "s_waitcnt lgkmcnt(0)"] + L.store("v9", 4) - ops.append(model.read32(base)) - mem = L.run(body) - for i in (0, 5, 31): - self.assertEqual([L.out(mem, i, k) for k in range(5)], ops, f"trial {trial} lane {i}") - - -class TestOutsideCompute(unittest.TestCase): - def test_pixel_shader_refuses_lds(self): - for line in ("ds_read_b32 v1, v0", "ds_write_b32 v0, v1", "ds_add_u32 v0, v1"): - with self.subTest(line=line), self.assertRaises(rdna2spirv.Unsupported): - support.translate_lines("ps_lds_refused", [line, "s_endpgm"]) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_lds_src2.py b/tests/semantic/test_lds_src2.py deleted file mode 100644 index 74adc4f9a..000000000 --- a/tests/semantic/test_lds_src2.py +++ /dev/null @@ -1,140 +0,0 @@ -"""The DS `*_src2_*` forms (`ds_add_src2_u32`, `ds_max_src2_f64`, ...): GFX10.1 encodings the translator refuses. - -These ops read their second operand from LDS instead of a VGPR. They exist in the GFX10.1 encoding the console's -gfx1013 shares, and not on gfx103x: llvm-mc 21.1.8 assembles all 31 forms below for `-mcpu=gfx1013` (DS opcodes -0x80-0x95 and 0xc0-0xd3) and rejects every one of them for `-mcpu=gfx1030` ("instruction not supported on this -GPU"), where it also decodes their bytes as an invalid encoding. They take one 16-bit `offset:`, not the -`offset0:`/`offset1:` pair of the two-address DS ops, which llvm-mc rejects on them ("not a valid operand"). The -address of the LDS operand is derived from that offset; neither the translator nor this file models it, and it has -not been measured on hardware. - -`tools/rdna2spirv.py` has no rule for them and raises `Unsupported` naming the op, so a listing that holds one is -refused rather than translated as something else. `RefusedTests` pins that, with the plain `ds_add_u32` as the -control that the program reaches the translator. `EncodingTests` checks the gfx1013/gfx1030 split and the operand -form with llvm-mc, and is skipped when no llvm-mc with the AMDGPU target is found (LLVM_MC, as for the tools). - -This replaces `test_lds_add_sub_src2_u32.py`, a stand-alone model of `ds_add_src2_u32`/`ds_sub_src2_u32` that never -ran the translator and wrote the ops with `offset0`/`offset1` (TEST-738, found by @Vonsek). - -Standard library only; no GPU and no game files (llvm-mc optional). -""" -import os -import struct -import subprocess -import sys -import tempfile -import unittest - -sys.dont_write_bytecode = True - -HERE = os.path.dirname(os.path.abspath(__file__)) -ROOT = os.path.dirname(os.path.dirname(HERE)) -sys.path.insert(0, HERE) -sys.path.insert(0, os.environ.get("LEONIDA_TOOLS_DIR") or os.path.join(ROOT, "tools")) - -import support # noqa: E402 -from mc_command import mc_command # noqa: E402 -from rdna2spirv import Unsupported # noqa: E402 - -SRC2_32 = [ - "ds_add_src2_u32", "ds_sub_src2_u32", "ds_rsub_src2_u32", "ds_inc_src2_u32", "ds_dec_src2_u32", - "ds_min_src2_i32", "ds_max_src2_i32", "ds_min_src2_u32", "ds_max_src2_u32", - "ds_and_src2_b32", "ds_or_src2_b32", "ds_xor_src2_b32", "ds_write_src2_b32", - "ds_min_src2_f32", "ds_max_src2_f32", "ds_add_src2_f32", -] -SRC2_64 = [ - "ds_add_src2_u64", "ds_sub_src2_u64", "ds_rsub_src2_u64", "ds_inc_src2_u64", "ds_dec_src2_u64", - "ds_min_src2_i64", "ds_max_src2_i64", "ds_min_src2_u64", "ds_max_src2_u64", - "ds_and_src2_b64", "ds_or_src2_b64", "ds_xor_src2_b64", "ds_write_src2_b64", - "ds_min_src2_f64", "ds_max_src2_f64", -] -SRC2 = SRC2_32 + SRC2_64 - -# Compute FSSM header: RSRC2 0x8088 (4 user SGPRs, workgroup id x, 128 bytes of LDS), 64x1x1 threads. -CS_FSSM = bytearray(0x148) -struct.pack_into("<4I", CS_FSSM, 0x138, 0x8088, 64, 1, 1) -CS_FSSM = bytes(CS_FSSM) - - -def translate(op_line): - return support.translate_lines("cs_ds_src2", ["v_mov_b32_e32 v1, 0", op_line, "s_endpgm"], fssm=CS_FSSM) - - -class RefusedTests(unittest.TestCase): - def test_plain_ds_add_reaches_the_translator(self): - self.assertIn("OpEntryPoint", translate("ds_add_u32 v1, v1")) - - def test_every_src2_form_is_refused_by_name(self): - for op in SRC2: - for operands in ("v1", "v1 offset:4", "v1 offset:65535"): - with self.subTest(op=op, operands=operands): - with self.assertRaises(Unsupported) as caught: - translate(f"{op} {operands}") - self.assertIn(op, str(caught.exception)) - - -def _llvm_mc(): - """llvm-mc's argv if it runs and has an AMDGPU target that knows gfx1013, else None.""" - cmd = mc_command() - try: - r = subprocess.run(cmd + ["-triple=amdgcn", "-mcpu=gfx1013", "-show-encoding"], input="s_endpgm\n", - capture_output=True, text=True, timeout=60) - except (OSError, subprocess.TimeoutExpired): - return None - return cmd if r.returncode == 0 and "encoding" in r.stdout else None - - -MC = _llvm_mc() - - -def assemble(cpu, text): - """(returncode, stdout, stderr) of llvm-mc assembling `text` for `cpu`, through a file (no BOM, no pipe).""" - with tempfile.TemporaryDirectory() as tmp: - path = os.path.join(tmp, "in.s") - with open(path, "w", encoding="ascii", newline="\n") as f: - f.write(text) - r = subprocess.run(MC + ["-triple=amdgcn", f"-mcpu={cpu}", "-show-encoding", path], - capture_output=True, text=True, timeout=60) - return r.returncode, r.stdout, r.stderr - - -def encodings(stdout): - """The encoding bytes llvm-mc printed, one list per instruction.""" - out = [] - for line in stdout.splitlines(): - if "encoding: [" in line: - body = line.split("encoding: [", 1)[1].split("]", 1)[0] - out.append([int(b, 16) for b in body.split(",")]) - return out - - -@unittest.skipUnless(MC, "needs llvm-mc with the AMDGPU target (set LLVM_MC)") -class EncodingTests(unittest.TestCase): - def test_gfx1013_has_every_form_with_a_16_bit_offset(self): - for op in SRC2: - with self.subTest(op=op): - rc, out, err = assemble("gfx1013", f"{op} v1 offset:4660\n") - self.assertEqual(rc, 0, err) - (enc,) = encodings(out) - word0 = int.from_bytes(bytes(enc[:4]), "little") - self.assertEqual(word0 >> 26, 0b110110, "not a DS encoding") - opcode = (word0 >> 18) & 0xFF - wide = op in SRC2_64 - self.assertTrue(0xC0 <= opcode <= 0xD3 if wide else 0x80 <= opcode <= 0x95, hex(opcode)) - self.assertEqual(word0 & 0xFFFF, 4660, "offset is not the 16-bit field") - - def test_gfx1030_has_none_of_them(self): - for op in SRC2: - with self.subTest(op=op): - rc, out, err = assemble("gfx1030", f"{op} v1\n") - self.assertNotEqual(rc, 0) - self.assertIn("not supported on this GPU", err) - - def test_offset0_offset1_is_not_their_operand_form(self): - rc, out, err = assemble("gfx1013", "ds_add_src2_u32 v1 offset0:1 offset1:2\n") - self.assertNotEqual(rc, 0) - self.assertIn("not a valid operand", err) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_lds_subdword_wide.py b/tests/semantic/test_lds_subdword_wide.py deleted file mode 100644 index 05f981346..000000000 --- a/tests/semantic/test_lds_subdword_wide.py +++ /dev/null @@ -1,147 +0,0 @@ -"""LDS accesses narrower and wider than a dword: ds_write_b8 / _b8_d16_hi / _b16 / _b16_d16_hi, ds_read_u8 / _i8 / -_u16 / _i16, ds_write_b64 / _b96 / _b128, ds_read_b64 / _b96 / _b128 and ds_read2st64_b32. - -Standard library only; no GPU, no LLVM, no game files. - - python -m unittest discover -s tests/semantic -p "test_lds_subdword_wide.py" -v - -RDNA2 ISA, "Data Share Instructions"; ADDR = vaddr + offset (bytes): - * ds_write_b8 MEM[ADDR][7:0] = DATA[7:0] ds_write_b8_d16_hi MEM[ADDR][7:0] = DATA[23:16] - * ds_write_b16 MEM[ADDR][15:0] = DATA[15:0] ds_write_b16_d16_hi MEM[ADDR][15:0] = DATA[31:16] - (the other bytes of the dword are kept) - * ds_read_u8 / ds_read_i8 D = zero / sign-extend 8 -> 32 of MEM[ADDR][7:0] - * ds_read_u16 / ds_read_i16 D = zero / sign-extend 16 -> 32 of MEM[ADDR][15:0] - * ds_{read,write}_b64/b96/b128: N consecutive dwords from ADDR, lowest register first - * ds_read2st64_b32: MEM[ADDR + offset0 * 256] and MEM[ADDR + offset1 * 256] - -The inputs are the GPU tests runtime/test/shaders/cs_w32_lds_subdword.asm and cs_w32_lds_wide.asm (fixtures from -regen_fixtures.py), translated for wave32 and run as one 32-lane subgroup in lockstep. The expected words are -computed below from a byte-level model of LDS written from the rules above; they are the words in the .asm -headers, check.py and run_gpu_tests.py. -""" -import re -import struct -import unittest - -import support -import spirv_mini_interp as si - -# 4 user SGPRs (the output V#), workgroup id in s4, 512 bytes of LDS, 32x1x1 threads. -FSSM = bytearray(0x148) -struct.pack_into("<4I", FSSM, 0x138, 0x8088, 32, 1, 1) -FSSM = bytes(FSSM) -VSHARP = [0, 0, 0x1000, 0x31016FAC] # word 3 as in test_lds_read_u8_d16.py (OOB_SELECT is honoured since 14887e68) - - -class Lds: - """Byte-addressed LDS, little endian, as the ISA describes it.""" - - def __init__(self): - self.b = bytearray(512) - - def write(self, addr, value, nbytes): - self.b[addr:addr + nbytes] = (value & ((1 << 8 * nbytes) - 1)).to_bytes(nbytes, "little") - - def read(self, addr, nbytes, signed=False): - return int.from_bytes(self.b[addr:addr + nbytes], "little", signed=signed) & 0xFFFFFFFF - - -def expected_subdword(): - m = Lds() - m.write(0, 0x11223344, 4) - m.write(4, 0x55667788, 4) - data = 0xA1B2C3D4 - m.write(1, data, 1) # ds_write_b8 offset:1 - m.write(2, data >> 16, 1) # ds_write_b8_d16_hi offset:2 - m.write(4, data, 2) # ds_write_b16 offset:4 - m.write(6, data >> 16, 2) # ds_write_b16_d16_hi offset:6 - return [m.read(0, 4), m.read(4, 4), m.read(2, 1, True), m.read(2, 1), m.read(3, 1, True), - m.read(6, 2, True), m.read(6, 2), m.read(4, 2, True)] - - -A, B, C, D, E, F, G, H = (0xCAFEF00D, 0x0BADBEEF, 0x600DD00D, 0xFEEDFACE, 0x8BADF00D, 0xDEADC0DE, 0x12345678, - 0x9ABCDEF0) - - -def expected_wide(): - m = Lds() - for k, v in enumerate((A, B, C, D)): # ds_write_b128 v[30:33] offset:16 - m.write(16 + 4 * k, v, 4) - m.write(60, 0, 4) # ds_write_b32 0 offset:60 - for k, v in enumerate((A, B, C)): # ds_write_b96 v[30:32] offset:48 - m.write(48 + 4 * k, v, 4) - m.write(64, E, 4) # ds_write_b64 v[34:35] offset:64 - m.write(68, F, 4) - m.write(0, G, 4) - m.write(256, H, 4) - b128 = [m.read(16 + 4 * k, 4) for k in range(4)] - b96 = [m.read(48 + 4 * k, 4) for k in range(3)] - b64 = [m.read(64 + 4 * k, 4) for k in range(2)] - st64 = [m.read(0 * 256, 4), m.read(1 * 256, 4)] # offset0:0 offset1:1 - return [b128[0], b128[3], b96[2], m.read(60, 4), b64[0], b64[1], st64[0], st64[1]] - - -def run(name, sabotage=None): - spv = support.translate_fixture(name, fssm=FSSM) - if sabotage: - spv = sabotage(spv) - memory = si.run_workgroup( - spv, 32, 32, - inputs_for=lambda i: {"%wg_id": (0, 0, 0), "%local_id": (i, 0, 0), "%sg_lane": i}, - push_constants=VSHARP + [0] * 28, memory={}) - stray = sorted(a for a in memory if not 0 <= a < 32 or a % 4) - if stray: - raise AssertionError(f"stores outside out[0..7]: {stray}") - return [memory.get(4 * k) for k in range(8)] - - -class LdsSubdwordWide(unittest.TestCase): - def test_reference_values(self): - # The words in the .asm headers, check.py and run_gpu_tests.py. - self.assertEqual(expected_subdword(), [0x11B2D444, 0xA1B2C3D4, 0xFFFFFFB2, 0x000000B2, 0x00000011, - 0xFFFFA1B2, 0x0000A1B2, 0xFFFFC3D4]) - self.assertEqual(expected_wide(), [A, D, C, 0, E, F, G, H]) - - def check(self, name, want): - got = run(name) - for k, (g, w) in enumerate(zip(got, want)): - with self.subTest(shader=name, word=k): - self.assertEqual(g, w, f"out[{k}] = {g if g is None else hex(g)}, want {hex(w)}") - - def test_subdword(self): - self.check("cs_w32_lds_subdword", expected_subdword()) - - def test_wide(self): - self.check("cs_w32_lds_wide", expected_wide()) - - def test_negative_controls(self): - # Each sabotage of the translated SPIR-V must change the result. - def const(t, value): # the scalar constant the translator's cu(value) made (not the array length) - names = re.findall(r"(%c\d+) = OpConstant %uint " + str(value) + r"\n", t) - self.assertEqual(len(names), 1, f"uint constant {value}: {names}") - return names[0] - - def unsigned(t): # ds_read_i8 / ds_read_i16 zero-extend - self.assertIn("OpBitFieldSExtract", t) - return t.replace("OpBitFieldSExtract", "OpBitFieldUExtract") - - def no_hi_shift(t): # the _d16_hi writes store DATA[7:0] / [15:0] instead of the high half - pat = r"= OpShiftRightLogical %uint (%\w+) " + const(t, 16) + r"\n" - self.assertEqual(len(re.findall(pat, t)), 2) - return re.sub(pat, r"= OpCopyObject %uint \1\n", t) - - def st64_unit(t): # ds_read2st64_b32 offset1:1 lands on dword 1 instead of dword 64 - pat = r"= OpIAdd %uint (%\w+) " + const(t, 256) + r"\n" - self.assertEqual(len(re.findall(pat, t)), 2) # ds_write_b32 offset:256 and the read2st64 element - last = list(re.finditer(pat, t))[-1] - return t[:last.start()] + f"= OpIAdd %uint {last.group(1)} {const(t, 4)}\n" + t[last.end():] - - for name, sab, want in (("cs_w32_lds_subdword", unsigned, expected_subdword()), - ("cs_w32_lds_subdword", no_hi_shift, expected_subdword()), - ("cs_w32_lds_wide", st64_unit, expected_wide())): - with self.subTest(sabotage=sab.__name__): - self.assertNotEqual(run(name, sab), want) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_lds_subword_d16.py b/tests/semantic/test_lds_subword_d16.py deleted file mode 100644 index 438aff60f..000000000 --- a/tests/semantic/test_lds_subword_d16.py +++ /dev/null @@ -1,352 +0,0 @@ -"""Semantic tests for LDS sub-dword and d16 read/write instructions. - -Standard library only; no GPU, no LLVM, no game files. - - python -I tests/semantic/test_lds_subword_d16.py -v - -Covers RDNA2 Data Share (DS) sub-dword and d16 operations translated by tools/rdna2spirv.py: - * ds_write_b8 (all 4 byte lanes 0..3) and ds_write_b16 (byte lanes 0 and 2), - verifying via ds_read_b32 that adjacent bytes/halfwords in the same dword stay intact. - * ds_write_b8_d16_hi (extracts source bits [23:16]) and ds_write_b16_d16_hi - (extracts source bits [31:16]), verifying low source bits are ignored and adjacent LDS bytes stay intact. - * ds_read_i8, ds_read_u8, ds_read_i16, ds_read_u16 on positive (0x7F, 0x7FFF) and - negative (0x80, 0xFF, 0x8000, 0xFFFF) values, verifying sign-extension vs zero-extension. - * ds_read_u16_d16 (writes [15:0], preserves dest [31:16]) and - ds_read_u16_d16_hi (writes [31:16], preserves dest [15:0]). - * In-memory SPIR-V negative controls (OpBitFieldSExtract <-> OpBitFieldUExtract, - d16 insert offset 0 <-> 16, and d16_hi source shift). -""" -import os -import re -import struct -import sys -import unittest - -sys.dont_write_bytecode = True - -HERE = os.path.dirname(os.path.abspath(__file__)) -if HERE not in sys.path: - sys.path.insert(0, HERE) - -import spirv_mini_interp as si # noqa: E402 -import support # noqa: E402 - -# 4 user SGPRs (the output V# in s[0:3]), workgroup id in s4, 512 bytes of LDS, 32x1x1 threads. -FSSM = bytearray(0x148) -struct.pack_into("<4I", FSSM, 0x138, 0x8088, 32, 1, 1) -FSSM = bytes(FSSM) -VSHARP = [0, 0, 0x1000, 0x31016FAC] - - -def translate_cs(lines, name="cs_lds_subword_d16"): - return support.translate_lines(name, lines, fssm=FSSM) - - -def run_cs(spv, out_words=1): - memory = {} - si.run_fragment( - spv, - inputs={"%wg_id": (0, 0, 0), "%local_id": (0, 0, 0), "%sg_lane": 0}, - push_constants=VSHARP + [0] * 28, - memory=memory, - ) - return [memory.get(4 * k) for k in range(out_words)] - - -def emit_stores(regs): - lines = [] - for k, reg in enumerate(regs): - lines.append(f"v_mov_b32_e32 v21, {4 * k}") - lines.append(f"buffer_store_dword {reg}, v21, s[0:3], 0 offen") - lines.append("s_endpgm") - return lines - - -class LdsSubwordD16Tests(unittest.TestCase): - def test_ds_write_b8_all_positions_preserve_neighbors(self): - # Start with dword 0 = 0xA1B2C3D4, overwrite byte 0..3 one by one, reading b32 after each write. - lines = [ - "v_mov_b32_e32 v1, 0", - "v_mov_b32_e32 v2, 0xa1b2c3d4", - "ds_write_b32 v1, v2", - "s_waitcnt lgkmcnt(0)", - # Byte 0 via vaddr=0 - "v_mov_b32_e32 v3, 0xffffff11", - "ds_write_b8 v1, v3", - "s_waitcnt lgkmcnt(0)", - "ds_read_b32 v10, v1", - # Byte 1 via vaddr=1 - "v_mov_b32_e32 v4, 1", - "v_mov_b32_e32 v3, 0xffffff22", - "ds_write_b8 v4, v3", - "s_waitcnt lgkmcnt(0)", - "ds_read_b32 v11, v1", - # Byte 2 via vaddr=0, offset:2 - "v_mov_b32_e32 v3, 0xffffff33", - "ds_write_b8 v1, v3 offset:2", - "s_waitcnt lgkmcnt(0)", - "ds_read_b32 v12, v1", - # Byte 3 via vaddr=2, offset:1 - "v_mov_b32_e32 v4, 2", - "v_mov_b32_e32 v3, 0xffffff44", - "ds_write_b8 v4, v3 offset:1", - "s_waitcnt lgkmcnt(0)", - "ds_read_b32 v13, v1", - "s_waitcnt lgkmcnt(0)", - ] + emit_stores(["v10", "v11", "v12", "v13"]) - spv = translate_cs(lines, "cs_ds_write_b8") - got = run_cs(spv, out_words=4) - self.assertEqual(got, [0xA1B2C311, 0xA1B22211, 0xA1332211, 0x44332211]) - - def test_ds_write_b16_positions_0_and_2_preserve_neighbors(self): - lines = [ - "v_mov_b32_e32 v1, 0", - "v_mov_b32_e32 v2, 0x12345678", - "ds_write_b32 v1, v2", - "s_waitcnt lgkmcnt(0)", - # Halfword 0 via vaddr=0 (high source bits 0xFFFF must be masked off) - "v_mov_b32_e32 v3, 0xffffaabb", - "ds_write_b16 v1, v3", - "s_waitcnt lgkmcnt(0)", - "ds_read_b32 v10, v1", - # Halfword 2 via vaddr=0, offset:2 - "v_mov_b32_e32 v3, 0xffffccdd", - "ds_write_b16 v1, v3 offset:2", - "s_waitcnt lgkmcnt(0)", - "ds_read_b32 v11, v1", - # Halfword 2 via vaddr=2 on fresh dword 1 = 0x89abcdef - "v_mov_b32_e32 v4, 4", - "v_mov_b32_e32 v2, 0x89abcdef", - "ds_write_b32 v4, v2", - "s_waitcnt lgkmcnt(0)", - "v_mov_b32_e32 v5, 6", - "v_mov_b32_e32 v3, 0xdead0055", - "ds_write_b16 v5, v3", - "s_waitcnt lgkmcnt(0)", - "ds_read_b32 v12, v4", - "s_waitcnt lgkmcnt(0)", - ] + emit_stores(["v10", "v11", "v12"]) - spv = translate_cs(lines, "cs_ds_write_b16") - got = run_cs(spv, out_words=3) - self.assertEqual(got, [0x1234AABB, 0xCCDDAABB, 0x0055CDEF]) - - def test_ds_write_b8_d16_hi_extracts_bits_23_16(self): - # Source 0xDE55BEEF: bits [23:16] = 0x55; [7:0]=0xEF, [15:8]=0xBE, [31:24]=0xDE must not be written. - lines = [ - "v_mov_b32_e32 v1, 0", - "v_mov_b32_e32 v2, 0xa1b2c3d4", - "ds_write_b32 v1, v2", - "s_waitcnt lgkmcnt(0)", - "v_mov_b32_e32 v3, 0xde55beef", - "ds_write_b8_d16_hi v1, v3 offset:1", - "s_waitcnt lgkmcnt(0)", - "ds_read_b32 v10, v1", - "v_mov_b32_e32 v3, 0xde77beef", - "ds_write_b8_d16_hi v1, v3 offset:3", - "s_waitcnt lgkmcnt(0)", - "ds_read_b32 v11, v1", - "s_waitcnt lgkmcnt(0)", - ] + emit_stores(["v10", "v11"]) - spv = translate_cs(lines, "cs_ds_write_b8_d16_hi") - got = run_cs(spv, out_words=2) - self.assertEqual(got, [0xA1B255D4, 0x77B255D4]) - - def test_ds_write_b16_d16_hi_extracts_bits_31_16(self): - # Source 0xCAFEBEEF: bits [31:16] = 0xCAFE; [15:0] = 0xBEEF must not be written. - lines = [ - "v_mov_b32_e32 v1, 0", - "v_mov_b32_e32 v2, 0x12345678", - "ds_write_b32 v1, v2", - "s_waitcnt lgkmcnt(0)", - "v_mov_b32_e32 v3, 0xcafebeef", - "ds_write_b16_d16_hi v1, v3", - "s_waitcnt lgkmcnt(0)", - "ds_read_b32 v10, v1", - "v_mov_b32_e32 v4, 2", - "v_mov_b32_e32 v3, 0xbabef00d", - "ds_write_b16_d16_hi v4, v3", - "s_waitcnt lgkmcnt(0)", - "ds_read_b32 v11, v1", - "s_waitcnt lgkmcnt(0)", - ] + emit_stores(["v10", "v11"]) - spv = translate_cs(lines, "cs_ds_write_b16_d16_hi") - got = run_cs(spv, out_words=2) - self.assertEqual(got, [0x1234CAFE, 0xBABECAFE]) - - def test_ds_read_i8_u8_sign_vs_zero_extension(self): - # Dword 0 = 0x00FF807F -> byte 0=0x7F, byte 1=0x80, byte 2=0xFF, byte 3=0x00. - lines = [ - "v_mov_b32_e32 v1, 0", - "v_mov_b32_e32 v2, 0x00ff807f", - "ds_write_b32 v1, v2", - "s_waitcnt lgkmcnt(0)", - "ds_read_i8 v10, v1 offset:0", - "ds_read_u8 v11, v1 offset:0", - "ds_read_i8 v12, v1 offset:1", - "ds_read_u8 v13, v1 offset:1", - "ds_read_i8 v14, v1 offset:2", - "ds_read_u8 v15, v1 offset:2", - "s_waitcnt lgkmcnt(0)", - ] + emit_stores(["v10", "v11", "v12", "v13", "v14", "v15"]) - spv = translate_cs(lines, "cs_ds_read_8") - got = run_cs(spv, out_words=6) - self.assertEqual(got, [ - 0x0000007F, # i8(0x7F) - 0x0000007F, # u8(0x7F) - 0xFFFFFF80, # i8(0x80) - 0x00000080, # u8(0x80) - 0xFFFFFFFF, # i8(0xFF) - 0x000000FF, # u8(0xFF) - ]) - - def test_ds_read_i16_u16_sign_vs_zero_extension(self): - # Dword 0 = 0x80007FFF (half0=0x7FFF, half2=0x8000); Dword 1 = 0x0001FFFF (half0=0xFFFF). - lines = [ - "v_mov_b32_e32 v1, 0", - "v_mov_b32_e32 v2, 0x80007fff", - "ds_write_b32 v1, v2", - "v_mov_b32_e32 v2, 0x0001ffff", - "ds_write_b32 v1, v2 offset:4", - "s_waitcnt lgkmcnt(0)", - "ds_read_i16 v10, v1 offset:0", - "ds_read_u16 v11, v1 offset:0", - "ds_read_i16 v12, v1 offset:2", - "ds_read_u16 v13, v1 offset:2", - "ds_read_i16 v14, v1 offset:4", - "ds_read_u16 v15, v1 offset:4", - "s_waitcnt lgkmcnt(0)", - ] + emit_stores(["v10", "v11", "v12", "v13", "v14", "v15"]) - spv = translate_cs(lines, "cs_ds_read_16") - got = run_cs(spv, out_words=6) - self.assertEqual(got, [ - 0x00007FFF, # i16(0x7FFF) - 0x00007FFF, # u16(0x7FFF) - 0xFFFF8000, # i16(0x8000) - 0x00008000, # u16(0x8000) - 0xFFFFFFFF, # i16(0xFFFF) - 0x0000FFFF, # u16(0xFFFF) - ]) - - def test_ds_read_u16_d16_and_d16_hi_preserve_opposite_half(self): - lines = [ - "v_mov_b32_e32 v1, 0", - "v_mov_b32_e32 v2, 0xcafebeef", - "ds_write_b32 v1, v2", - "s_waitcnt lgkmcnt(0)", - "v_mov_b32_e32 v10, 0x12345678", - "v_mov_b32_e32 v11, 0x12345678", - "v_mov_b32_e32 v12, 0x12345678", - "v_mov_b32_e32 v13, 0x12345678", - "ds_read_u16_d16 v10, v1 offset:0", - "ds_read_u16_d16 v11, v1 offset:2", - "ds_read_u16_d16_hi v12, v1 offset:0", - "ds_read_u16_d16_hi v13, v1 offset:2", - "s_waitcnt lgkmcnt(0)", - ] + emit_stores(["v10", "v11", "v12", "v13"]) - spv = translate_cs(lines, "cs_ds_read_u16_d16") - got = run_cs(spv, out_words=4) - self.assertEqual(got, [ - 0x1234BEEF, # u16_d16(0xBEEF) into [15:0], [31:16] preserved - 0x1234CAFE, # u16_d16(0xCAFE) into [15:0], [31:16] preserved - 0xBEEF5678, # u16_d16_hi(0xBEEF) into [31:16], [15:0] preserved - 0xCAFE5678, # u16_d16_hi(0xCAFE) into [31:16], [15:0] preserved - ]) - - def test_negative_controls_spirv_in_memory(self): - # 1) Signedness swap on ds_read_i8 (0x80 -> 0xFFFFFF80 must break if OpBitFieldUExtract is used). - spv_i8 = translate_cs([ - "v_mov_b32_e32 v1, 0", - "v_mov_b32_e32 v2, 0x00000080", - "ds_write_b32 v1, v2", - "s_waitcnt lgkmcnt(0)", - "ds_read_i8 v10, v1", - "s_waitcnt lgkmcnt(0)", - ] + emit_stores(["v10"]), "cs_neg_i8") - self.assertEqual(run_cs(spv_i8), [0xFFFFFF80]) - self.assertIn("OpBitFieldSExtract", spv_i8) - bad_i8 = spv_i8.replace("OpBitFieldSExtract", "OpBitFieldUExtract") - self.assertEqual(run_cs(bad_i8), [0x00000080]) - self.assertNotEqual(run_cs(bad_i8), [0xFFFFFF80]) - - # 2) Signedness swap on ds_read_u16 (0x8000 -> 0x00008000 must break if OpBitFieldSExtract is used). - spv_u16 = translate_cs([ - "v_mov_b32_e32 v1, 0", - "v_mov_b32_e32 v2, 0x00008000", - "ds_write_b32 v1, v2", - "s_waitcnt lgkmcnt(0)", - "ds_read_u16 v10, v1", - "s_waitcnt lgkmcnt(0)", - ] + emit_stores(["v10"]), "cs_neg_u16") - self.assertEqual(run_cs(spv_u16), [0x00008000]) - m_c16_u = re.search(r"^\s*(%\w+) = OpConstant %uint 16$", spv_u16, re.MULTILINE) - self.assertIsNotNone(m_c16_u) - m_uext = re.search( - rf"^(\s*%\w+ = )OpBitFieldUExtract( %uint %\w+ %\w+ {re.escape(m_c16_u.group(1))})$", - spv_u16, - re.MULTILINE, - ) - self.assertIsNotNone(m_uext) - bad_u16 = spv_u16.replace(m_uext.group(0), f"{m_uext.group(1)}OpBitFieldSExtract{m_uext.group(2)}") - self.assertEqual(run_cs(bad_u16), [0xFFFF8000]) - self.assertNotEqual(run_cs(bad_u16), [0x00008000]) - - # 3) d16 insert offset swap (0 <-> 16) on ds_read_u16_d16 and ds_read_u16_d16_hi. - base_d16 = [ - "v_mov_b32_e32 v1, 0", - "v_mov_b32_e32 v2, 0x0000beef", - "ds_write_b32 v1, v2", - "s_waitcnt lgkmcnt(0)", - "v_mov_b32_e32 v10, 0x12345678", - ] - spv_lo = translate_cs(base_d16 + [ - "ds_read_u16_d16 v10, v1", - "s_waitcnt lgkmcnt(0)", - ] + emit_stores(["v10"]), "cs_neg_d16_lo") - self.assertEqual(run_cs(spv_lo), [0x1234BEEF]) - m_lo = re.search(r"^(\s*%\w+ = OpBitFieldInsert %uint %\w+ %\w+) (%\w+) (%\w+)$", spv_lo, re.MULTILINE) - self.assertIsNotNone(m_lo) - # Swap offset=0 to offset=16 (reusing the 16-bit count constant). - bad_lo = spv_lo.replace(m_lo.group(0), f"{m_lo.group(1)} {m_lo.group(3)} {m_lo.group(3)}") - self.assertEqual(run_cs(bad_lo), [0xBEEF5678]) - - spv_hi = translate_cs(base_d16 + [ - "ds_read_u16_d16_hi v10, v1", - "s_waitcnt lgkmcnt(0)", - ] + emit_stores(["v10"]), "cs_neg_d16_hi") - self.assertEqual(run_cs(spv_hi), [0xBEEF5678]) - m_c0 = re.search(r"^\s*(%\w+) = OpConstant %uint 0$", spv_hi, re.MULTILINE) - m_hi = re.search(r"^(\s*%\w+ = OpBitFieldInsert %uint %\w+ %\w+) (%\w+) (%\w+)$", spv_hi, re.MULTILINE) - self.assertIsNotNone(m_c0) - self.assertIsNotNone(m_hi) - bad_hi = spv_hi.replace(m_hi.group(0), f"{m_hi.group(1)} {m_c0.group(1)} {m_hi.group(3)}") - self.assertEqual(run_cs(bad_hi), [0x1234BEEF]) - - # 4) d16_hi source shift swap (16 -> 0) on ds_write_b16_d16_hi. - spv_w_hi = translate_cs([ - "v_mov_b32_e32 v1, 0", - "v_mov_b32_e32 v2, 0x12345678", - "ds_write_b32 v1, v2", - "s_waitcnt lgkmcnt(0)", - "v_mov_b32_e32 v3, 0xcafebeef", - "ds_write_b16_d16_hi v1, v3", - "s_waitcnt lgkmcnt(0)", - "ds_read_b32 v10, v1", - "s_waitcnt lgkmcnt(0)", - ] + emit_stores(["v10"]), "cs_neg_w_hi") - self.assertEqual(run_cs(spv_w_hi), [0x1234CAFE]) - m_c0_w = re.search(r"^\s*(%\w+) = OpConstant %uint 0$", spv_w_hi, re.MULTILINE) - m_c16_w = re.search(r"^\s*(%\w+) = OpConstant %uint 16$", spv_w_hi, re.MULTILINE) - self.assertIsNotNone(m_c0_w) - self.assertIsNotNone(m_c16_w) - m_shr = re.search( - rf"^(\s*%\w+ = OpShiftRightLogical %uint %\w+) {re.escape(m_c16_w.group(1))}$", - spv_w_hi, - re.MULTILINE, - ) - self.assertIsNotNone(m_shr) - bad_w_hi = spv_w_hi.replace(m_shr.group(0), f"{m_shr.group(1)} {m_c0_w.group(1)}") - self.assertEqual(run_cs(bad_w_hi), [0x1234BEEF]) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_lds_u16_cross_dword.py b/tests/semantic/test_lds_u16_cross_dword.py deleted file mode 100644 index 064ea9ea4..000000000 --- a/tests/semantic/test_lds_u16_cross_dword.py +++ /dev/null @@ -1,120 +0,0 @@ -"""16-bit LDS reads and writes at byte 3 of a dword, which cross into the next dword. - -RDNA2 LDS in unaligned mode reads and writes bytes 3 and 4 for a halfword at byte 3: llc -mcpu=gfx1030 --mattr=+unaligned-access-mode emits a single `ds_read_u16 ... offset:3` / `ds_write_b16 ... offset:3` for an align-1 -i16 LDS access (without that mode it splits the access into two byte accesses). Before this fix the reads extracted -16 bits at bit 24 of one dword (undefined in SPIR-V) and the writes kept only byte 3. Hand-written wave32 compute -listings, translated and run in spirv_mini_interp; no GPU or game files. -""" -import os -import sys -import unittest - -HERE = os.path.dirname(os.path.abspath(__file__)) -if HERE not in sys.path: - sys.path.insert(0, HERE) - -import spirv_mini_interp as si # noqa: E402 -import support # noqa: E402 -from test_cs_shared_memory_limit import out, run_one # noqa: E402 -from test_lds_subword_d16 import FSSM, VSHARP # noqa: E402 - -WORDS = [0x44332211, 0x88776655, 0xCCBBAA99] -LDS = b"".join(w.to_bytes(4, "little") for w in WORDS) -PRE = 0xDEADBEEF -DATA = 0xA1B2C3D4 - - -def init_lds(): - lines = [] - for k, w in enumerate(WORDS): - lines += [f"v_mov_b32_e32 v1, {4 * k}", f"v_mov_b32_e32 v2, {w:#x}", "ds_write_b32 v1, v2"] - return lines + ["s_waitcnt lgkmcnt(0)"] - - -def run(lines, words): - spv = support.translate_lines("cs_lds_u16_cross", lines + out(*range(10, 10 + words)) + ["s_endpgm"], - fssm=FSSM) - memory = {} - si.run_fragment(spv, inputs={"%wg_id": (0, 0, 0), "%local_id": (0, 0, 0), "%sg_lane": 0}, - push_constants=VSHARP + [0] * 28, memory=memory) - return [memory.get(4 * k) for k in range(words)] - - -def sext16(v): - return (v - 0x10000 if v & 0x8000 else v) & 0xFFFFFFFF - - -def expected_read(op, addr): - h = int.from_bytes(LDS[addr:addr + 2], "little") - return {"ds_read_u16": h, "ds_read_i16": sext16(h), "ds_read_u16_d16": (PRE & 0xFFFF0000) | h, - "ds_read_u16_d16_hi": (PRE & 0xFFFF) | (h << 16)}[op] - - -def expected_words(addr, half): - b = bytearray(LDS) - b[addr:addr + 2] = half.to_bytes(2, "little") - return [int.from_bytes(b[4 * k:4 * k + 4], "little") for k in range(len(WORDS))] - - -class LdsU16CrossDwordTests(unittest.TestCase): - def test_reads(self): - # byte 3 (vaddr), byte 7 (offset:7), and the non-crossing halfwords around them, unchanged - for op in ("ds_read_u16", "ds_read_i16", "ds_read_u16_d16", "ds_read_u16_d16_hi"): - for vaddr, off in ((3, 0), (0, 7), (4, 3), (1, 0), (2, 0), (5, 0), (0, 6)): - with self.subTest(op=op, vaddr=vaddr, offset=off): - mod = f" offset:{off}" if off else "" - got = run(init_lds() + [f"v_mov_b32_e32 v4, {vaddr}", f"v_mov_b32_e32 v10, {PRE:#x}", - f"{op} v10, v4{mod}", "s_waitcnt lgkmcnt(0)"], 1) - self.assertEqual(got, [expected_read(op, vaddr + off)]) - - def test_writes(self): - for op, half in (("ds_write_b16", DATA & 0xFFFF), ("ds_write_b16_d16_hi", DATA >> 16)): - for vaddr, off in ((3, 0), (0, 7), (4, 3), (1, 0), (2, 0), (6, 0)): - with self.subTest(op=op, vaddr=vaddr, offset=off): - mod = f" offset:{off}" if off else "" - got = run(init_lds() + [f"v_mov_b32_e32 v4, {vaddr}", f"v_mov_b32_e32 v5, {DATA:#x}", - f"{op} v4, v5{mod}", "s_waitcnt lgkmcnt(0)", "v_mov_b32_e32 v1, 0", - "ds_read_b32 v10, v1", "ds_read_b32 v11, v1 offset:4", - "ds_read_b32 v12, v1 offset:8", "s_waitcnt lgkmcnt(0)"], 3) - self.assertEqual(got, expected_words(vaddr + off, half)) - - def test_chained_crossing_writes_keep_each_others_bytes(self): - # Halfwords at bytes 3, 7 and 11: each one's high byte and the next one's low byte share a dword, so each - # write must keep the other bytes of both dwords it touches. Read back as halfwords and as dwords. - lines = [] - for k in range(4): - lines += [f"v_mov_b32_e32 v1, {4 * k}", "v_mov_b32_e32 v2, 0", "ds_write_b32 v1, v2"] - lines += ["v_mov_b32_e32 v1, 0"] - for k, h in enumerate((0x1141, 0x2242, 0x3343)): - lines += [f"v_mov_b32_e32 v2, {h:#x}", f"ds_write_b16 v1, v2 offset:{4 * k + 3}"] - lines += ["s_waitcnt lgkmcnt(0)", "ds_read_u16 v10, v1 offset:3", "ds_read_u16 v11, v1 offset:7", - "ds_read_u16 v12, v1 offset:11", "ds_read_b32 v13, v1", "ds_read_b32 v14, v1 offset:4", - "ds_read_b32 v15, v1 offset:8", "ds_read_b32 v16, v1 offset:12", "s_waitcnt lgkmcnt(0)"] - self.assertEqual(run(lines, 7), [0x1141, 0x2242, 0x3343, 0x41000000, 0x42000011, 0x43000022, 0x33]) - - def test_crossing_past_the_allocation_drops_the_whole_halfword(self): - # 512 B allocated. A halfword at byte 511 ends past it: gfx1036 drops the whole access (TheMrBeez, #3817): - # neither byte is written (dword 127 and dword 0 keep their sentinels, no wrap to byte 0) and both reads - # give 0. Halfwords at bytes 507 (crossing into dword 127) and 510 stay inside it and are written and read. - # Both with the ordinary wrapped array and with offset:1024 elsewhere, which makes every access of the - # shader bounds-checked (SHADER-309). - for forced in (False, True): - with self.subTest(bounds_checked=forced): - lines = ["v_mov_b32_e32 v1, 0", "v_mov_b32_e32 v2, 0x5e17", "ds_write_b32 v1, v2", - "v_mov_b32_e32 v3, 0x1f8", "v_mov_b32_e32 v2, 0x7e7e7e7e", "ds_write_b32 v3, v2", - "v_mov_b32_e32 v2, 0x00ffffff", "ds_write_b32 v3, v2 offset:4", "s_waitcnt lgkmcnt(0)", - "v_mov_b32_e32 v4, 0xc3d4", "ds_write_b16 v3, v4 offset:7", "ds_write_b16 v3, v4 offset:3", - "v_mov_b32_e32 v4, 0xa5b6", "ds_write_b16 v3, v4 offset:6", "s_waitcnt lgkmcnt(0)"] - lines += [f"v_mov_b32_e32 v{r}, 0xdead" for r in range(5, 12)] - lines += ["ds_read_u16 v5, v3 offset:7", "ds_read_i16 v6, v3 offset:7", "ds_read_b32 v7, v1", - "ds_read_b32 v8, v3", "ds_read_b32 v9, v3 offset:4", "ds_read_u16 v10, v3 offset:3", - "ds_read_u16 v11, v3 offset:6"] - if forced: - lines.append("ds_read_b32 v12, v1 offset:1024") - _, mem = run_one(lines + ["s_waitcnt lgkmcnt(0)"] + out(5, 6, 7, 8, 9, 10, 11), 1) - self.assertEqual([mem.get(4 * k) for k in range(7)], - [0, 0, 0x5E17, 0xD47E7E7E, 0xA5B6FFC3, 0xC3D4, 0xA5B6]) - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_lds_unsupported.py b/tests/semantic/test_lds_unsupported.py deleted file mode 100644 index ff501ed11..000000000 --- a/tests/semantic/test_lds_unsupported.py +++ /dev/null @@ -1,70 +0,0 @@ -"""LDS operations the translator does not implement are refused, not translated as something else. - -Standard library only; no GPU, no LLVM, no game files. - -These are RDNA2 Data Share instructions that tools/rdna2spirv.py has no rule for: - * ds_add_src2_u32, ds_sub_src2_u32, ds_inc_src2_u32, ds_dec_src2_u32: the second operand is LDS[B] (B = vaddr + - offset1 * 4), not a register, and the result goes to LDS[A] (A = vaddr + offset0 * 4); - * ds_add_u64, ds_sub_u64 and their _rtn_ forms: a 64-bit atomic on two dwords (Workgroup memory has no Int64 - atomics here; only the exchange and the bitwise 64-bit forms are lowered, dword by dword); - * ds_condxchg32_rtn_b64 (the RDNA2 name; ds_condxchg32_rtn_b32 is not an RDNA2 mnemonic at all). -Until this file, one self-built model of each of these ran in tests/semantic, with an instruction decoder of its own, -and so tested nothing the translator does. A model that is not the translator's behaviour cannot catch a regression; -what the translator does is refuse them with `Unsupported`, and that is what is pinned here, in a compute shader (the -only stage with LDS). A separate test pins that LDS outside compute is refused, using a supported op. When a rule is added, move its entry out of this list and test its values. -""" -import os -import struct -import sys -import unittest - -sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) -import support # noqa: E402 (also puts tools/ on sys.path) - -rdna2spirv = support.rdna2spirv - -# RSRC2 0x40088: 4 user SGPRs, workgroup id in s4, 4 KiB LDS; 32x1x1 threads. -FSSM = bytearray(0x148) -struct.pack_into("<4I", FSSM, 0x138, 0x40088, 32, 1, 1) -FSSM = bytes(FSSM) - -UNSUPPORTED = ( - "ds_add_src2_u32 v1 offset0:1 offset1:2", - "ds_sub_src2_u32 v1 offset0:1 offset1:2", - "ds_inc_src2_u32 v1 offset0:1 offset1:2", - "ds_dec_src2_u32 v1 offset0:1 offset1:2", - "ds_add_u64 v1, v[2:3]", - "ds_sub_u64 v1, v[2:3]", - "ds_add_rtn_u64 v[4:5], v1, v[2:3]", - "ds_sub_rtn_u64 v[4:5], v1, v[2:3]", - "ds_sub_u64 v1, v[2:3] offset:8", - "ds_condxchg32_rtn_b64 v[4:5], v1, v[2:3]", - "ds_condxchg32_rtn_b32 v4, v1, v2, v3", -) - - -class TestRefused(unittest.TestCase): - def test_compute_shader_refuses_each(self): - for line in UNSUPPORTED: - with self.subTest(line=line): - with self.assertRaises(rdna2spirv.Unsupported) as cm: - support.translate_lines("cs_lds_unsupported", [line, "s_endpgm"], fssm=FSSM) - self.assertIn(line.split()[0], str(cm.exception)) - - def test_lds_outside_compute_is_refused(self): - # The translator refuses any LDS op outside a compute shader, supported ones included, so this uses a - # supported op: it pins that rule, not the unsupported list above. - with self.assertRaises(rdna2spirv.Unsupported) as cm: - support.translate_lines("ps_lds_outside_compute", ["ds_add_u32 v1, v2", "s_endpgm"]) - self.assertIn("outside compute", str(cm.exception)) - - def test_the_lowered_neighbours_still_translate(self): - # Guard against a blanket refusal: the supported relatives of the refused forms translate. - for line in ("ds_add_u32 v1, v2", "ds_sub_rtn_u32 v4, v1, v2", "ds_wrxchg_rtn_b64 v[4:5], v1, v[2:3]", - "ds_and_b64 v1, v[2:3]", "ds_inc_u32 v1, v2", "ds_min_f32 v1, v2"): - with self.subTest(line=line): - self.assertIn("OpAtomic", support.translate_lines("cs_lds_neighbour", [line, "s_endpgm"], fssm=FSSM)) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_lds_volatile.py b/tests/semantic/test_lds_volatile.py deleted file mode 100644 index fb2406c90..000000000 --- a/tests/semantic/test_lds_volatile.py +++ /dev/null @@ -1,155 +0,0 @@ -"""Plain LDS loads and stores are emitted Volatile (docs/design.md, "LDS access order within a wave"). - -RDNA2 runs a wave in lockstep: every lane's ds_write has happened when the next instruction starts, so a ds_read -issued after it sees the other lanes' writes with no s_barrier in between. Translated, each lane is one invocation -and the Vulkan memory model orders nothing between invocations without a barrier, so a driver's compiler may move -a lane's read ahead of the wave's writes, or merge two reads of one address. AMD's Windows driver 24.30.46 does -both on a Radeon 880M: the GPU tests cs_w64x_lds_raw and cs_w64x_lds_war read uninitialized Workgroup memory there -on every run, and pass once the accesses are Volatile. - -The first class checks the emitted SPIR-V of every plain access form, on the native wave32 and wave64 paths and -the wave64 emulation: every OpLoad / OpStore through a pointer into %lds carries the Volatile memory operand, and -nothing else does. The second executes Volatile accesses on a whole wave with the CPU interpreter. Standard library -only; no GPU, no LLVM, no game files. -""" -import re -import struct -import sys -import unittest -from pathlib import Path -from unittest.mock import patch - -sys.path.insert(0, str(Path(__file__).resolve().parent)) -from support import rdna2spirv, translate_lines # noqa: E402 -from test_loop_ballot_barrier import run_compute_workgroup # noqa: E402 - -VSHARP = [0, 0, 0x1000, 0x31016FAC] - -# (name, instruction lines, plain LDS loads, plain LDS stores). v1 holds an LDS byte address. -FORMS = ( - ("read_b32", ["ds_read_b32 v2, v1"], 1, 0), - ("read_b64", ["ds_read_b64 v[2:3], v1 offset:8"], 2, 0), - ("read_b96", ["ds_read_b96 v[2:4], v1"], 3, 0), - ("read_b128", ["ds_read_b128 v[2:5], v1"], 4, 0), - ("write_b32", ["ds_write_b32 v1, v2"], 0, 1), - ("write_b64", ["ds_write_b64 v1, v[2:3] offset:16"], 0, 2), - ("write_b96", ["ds_write_b96 v1, v[2:4]"], 0, 3), - ("write_b128", ["ds_write_b128 v1, v[2:5]"], 0, 4), - ("read2_b32", ["ds_read2_b32 v[2:3], v1 offset0:1 offset1:3"], 2, 0), - ("write2_b32", ["ds_write2_b32 v1, v2, v3 offset0:1 offset1:3"], 0, 2), - ("read2st64_b32", ["ds_read2st64_b32 v[2:3], v1 offset0:0 offset1:1"], 2, 0), - ("read2_b64", ["ds_read2_b64 v[2:5], v1 offset0:0 offset1:2"], 4, 0), - ("write2_b64", ["ds_write2_b64 v1, v[2:3], v[4:5] offset0:0 offset1:2"], 0, 4), - ("read_u8", ["ds_read_u8 v2, v1"], 1, 0), - ("read_i16", ["ds_read_i16 v2, v1"], 2, 0), # the dword, and the next one for a halfword at byte 3 - ("read_addtid", ["ds_read_addtid_b32 v2"], 1, 0), - ("write_addtid", ["ds_write_addtid_b32 v2"], 0, 1), - ("write_then_read", ["ds_write_b32 v1, v2", "ds_read_b32 v3, v1 offset:4"], 1, 1), -) - - -def fssm(wave, threads): - h = bytearray(0x148) - struct.pack_into("= 5 and words[2] == "OpLoad" and words[4] in pointers: - loads += 1 - vol_loads += volatile - elif len(words) >= 3 and words[0] == "OpStore" and words[1] in pointers: - stores += 1 - vol_stores += volatile - elif volatile: - other.append(line.strip()) - return loads, stores, vol_loads, vol_stores, other - - -class EveryPlainAccessIsVolatile(unittest.TestCase): - def test_forms(self): - for wave, emulate in ((32, False), (64, False), (64, True)): - for name, body, want_loads, want_stores in FORMS: - with self.subTest(form=name, wave=wave, emulate=emulate): - lines = (["v_mov_b32_e32 v1, 64"] + [f"v_mov_b32_e32 v{r}, {r}" for r in range(2, 6)] - + body + ["s_waitcnt lgkmcnt(0)", "s_endpgm"]) - spvasm = translate(name, lines, wave, emulate) - loads, stores, vol_loads, vol_stores, other = lds_accesses(spvasm) - self.assertEqual((loads, stores), (want_loads, want_stores), "plain LDS accesses emitted") - self.assertEqual((vol_loads, vol_stores), (loads, stores), "each one is Volatile") - self.assertEqual(other, [], "nothing but an LDS access is Volatile") - - def test_a_shader_without_lds_has_no_volatile_access(self): - spvasm = translate("no_lds", ["v_mov_b32_e32 v1, 7", "v_mov_b32_e32 v2, 0", - "buffer_store_dword v1, v2, s[0:3], 0 offen", "s_endpgm"], 32) - self.assertNotIn("Volatile", spvasm) - self.assertNotIn("%lds", spvasm) - - -def store_lane_word(reg, base): - """Every lane stores `reg` to out[base + lane].""" - return ["v_lshlrev_b32_e32 v21, 2, v1", f"v_add_nc_u32_e32 v21, {4 * base}, v21", - f"buffer_store_dword {reg}, v21, s[0:3], 0 offen"] - - -def lane_id(wave): - return ["v_mbcnt_lo_u32_b32 v1, -1, 0"] + (["v_mbcnt_hi_u32_b32 v1, -1, v1"] if wave == 64 else []) - - -class VolatileAccessesExecute(unittest.TestCase): - """The Volatile accesses run. The CPU interpreter runs the invocations of a subgroup one after another between - subgroup operations and barriers, so it cannot show the lockstep exchange of cs_w64x_lds_raw (a GPU test); these - two programs have the same answer in any order: a lane reads back its own slot, and the other half's slot only - after an s_barrier.""" - - def run_wave(self, name, lines, wave): - spvasm = translate(name, lines, wave) - loads, stores, vol_loads, vol_stores, _ = lds_accesses(spvasm) - self.assertEqual((vol_loads, vol_stores), (loads, stores)) - self.assertGreater(loads * stores, 0) - return run_compute_workgroup(spvasm, wave, wave, push_constants=VSHARP + [0] * 28, memory={}) - - def test_own_slot_round_trip(self): - for wave in (32, 64): - with self.subTest(wave=wave): - lines = (lane_id(wave) - + ["v_add_nc_u32_e32 v2, 100, v1", "v_lshlrev_b32_e32 v3, 2, v1", "ds_write_b32 v3, v2", - "ds_read_b32 v5, v3", "v_add_nc_u32_e32 v6, 2000, v1", "ds_write_b32 v3, v6", - "ds_read_b32 v8, v3", "s_waitcnt lgkmcnt(0)"] - + store_lane_word("v5", 0) + store_lane_word("v8", wave) + ["s_endpgm"]) - memory = self.run_wave("lds_own_slot", lines, wave) - for lane in range(wave): - self.assertEqual((memory[4 * lane], memory[4 * (wave + lane)]), (100 + lane, 2000 + lane), - f"lane {lane}") - - def test_other_half_after_a_barrier(self): - for wave in (32, 64): - with self.subTest(wave=wave): - half = wave // 2 - lines = (lane_id(wave) - + ["v_add_nc_u32_e32 v2, 100, v1", "v_lshlrev_b32_e32 v3, 2, v1", "ds_write_b32 v3, v2", - "s_waitcnt lgkmcnt(0)", "s_barrier", - f"v_xor_b32_e32 v4, {half}, v1", "v_lshlrev_b32_e32 v4, 2, v4", "ds_read_b32 v5, v4", - "s_waitcnt lgkmcnt(0)"] - + store_lane_word("v5", 0) + ["s_endpgm"]) - memory = self.run_wave("lds_barrier", lines, wave) - for lane in range(wave): - self.assertEqual(memory[4 * lane], 100 + (lane ^ half), f"lane {lane}") - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_lds_wrxchg2.py b/tests/semantic/test_lds_wrxchg2.py deleted file mode 100644 index 91aa235e4..000000000 --- a/tests/semantic/test_lds_wrxchg2.py +++ /dev/null @@ -1,66 +0,0 @@ -"""Value tests for RDNA2 ds_wrxchg2_rtn_b32 and ds_wrxchg2st64_rtn_b32, run through spirv_mini_interp on the CPU. - -RDNA2 ISA, "Data Share Instructions": two exchanges addressed as ds_write2_b32 addresses its two dwords, -ADDR0 = vaddr + offset0 * 4 and ADDR1 = vaddr + offset1 * 4 (offset * 256 bytes for st64): - vdst[0] = M[ADDR0]; M[ADDR0] = DATA - vdst[1] = M[ADDR1]; M[ADDR1] = DATA2 -Each case is a compute shader run as one invocation (lane 0): it seeds the LDS with ds_write_b32, runs the exchange, -reads both dwords back and stores (vdst[0], vdst[1], M[ADDR0], M[ADDR1]) to a buffer. Standard library only; no GPU, -no LLVM, no game files. -""" -import os -import sys -import unittest - -HERE = os.path.dirname(os.path.abspath(__file__)) -sys.dont_write_bytecode = True -sys.path.insert(0, HERE) - -from test_lds_atomics_values import run_listing # noqa: E402 (also puts tools/ on sys.path) -import rdna2spirv # noqa: E402 - - -def run_xchg2(op: str, addr: int, off0: int, off1: int, m0: int, m1: int, d0: int, d1: int, dst: str = "v[6:7]"): - unit = 4 * (64 if "st64" in op else 1) - a0, a1 = addr + off0 * unit, addr + off1 * unit - body = [f"v_mov_b32_e32 v1, {addr:#x}", f"v_mov_b32_e32 v10, {a0:#x}", f"v_mov_b32_e32 v11, {a1:#x}", - f"v_mov_b32_e32 v2, {m0:#x}", f"v_mov_b32_e32 v3, {m1:#x}", - "ds_write_b32 v10, v2", "ds_write_b32 v11, v3", "s_waitcnt lgkmcnt(0)", - f"v_mov_b32_e32 v4, {d0:#x}", f"v_mov_b32_e32 v5, {d1:#x}", - "v_mov_b32_e32 v6, 0xdead", "v_mov_b32_e32 v7, 0xbeef", - f"{op} {dst}, v1, v4, v5 offset0:{off0} offset1:{off1}", "s_waitcnt lgkmcnt(0)", - "ds_read_b32 v8, v10", "ds_read_b32 v9, v11", "s_waitcnt lgkmcnt(0)"] - for k, r in enumerate((6, 7, 8, 9)): - body += [f"v_mov_b32_e32 v31, {4 * k}", f"buffer_store_dword v{r}, v31, s[0:3], 0 offen"] - mem = run_listing(body) - return tuple(mem.get(4 * k) for k in range(4)) - - -class LdsWrxchg2(unittest.TestCase): - def test_two_exchanges(self): - for m0, m1, d0, d1 in ((1, 2, 3, 4), (0xFFFFFFFF, 0, 0x80000000, 0x7FFFFFFF), (0x12345678, 0x9ABCDEF0, 0, 0)): - for off0, off1 in ((0, 1), (3, 7), (255, 0)): - with self.subTest(m=(hex(m0), hex(m1)), d=(hex(d0), hex(d1)), offs=(off0, off1)): - got = run_xchg2("ds_wrxchg2_rtn_b32", 0x40, off0, off1, m0, m1, d0, d1) - self.assertEqual(got, (m0, m1, d0, d1)) - - def test_st64_offsets_are_256_bytes(self): - # offset1:1 is 256 bytes past vaddr, not 4: the seeded word there comes back. - self.assertEqual(run_xchg2("ds_wrxchg2st64_rtn_b32", 0x10, 0, 1, 11, 22, 33, 44), (11, 22, 33, 44)) - self.assertEqual(run_xchg2("ds_wrxchg2st64_rtn_b32", 0x8, 2, 3, 5, 6, 7, 8), (5, 6, 7, 8)) - - def test_same_dword_twice_returns_the_first_exchange(self): - # Both offsets name one dword: the second exchange sees DATA from the first and leaves DATA2. - self.assertEqual(run_xchg2("ds_wrxchg2_rtn_b32", 0x40, 2, 2, 9, 9, 100, 200), (9, 100, 200, 200)) - - def test_vdst_aliasing_vaddr_and_data(self): - # vdst v[4:5] overlaps the data registers: both exchanges read their data before either result is written. - self.assertEqual(run_xchg2("ds_wrxchg2_rtn_b32", 0x40, 0, 1, 1, 2, 3, 4, dst="v[4:5]")[2:], (3, 4)) - - def test_bad_destination_rejected(self): - with self.assertRaises(rdna2spirv.Unsupported): - run_listing(["v_mov_b32_e32 v1, 0", "ds_wrxchg2_rtn_b32 v6, v1, v4, v5 offset1:1"]) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_lds_wrxchg_b64.py b/tests/semantic/test_lds_wrxchg_b64.py deleted file mode 100644 index 10aa36b9a..000000000 --- a/tests/semantic/test_lds_wrxchg_b64.py +++ /dev/null @@ -1,107 +0,0 @@ -"""Value tests for RDNA2 ds_wrxchg_rtn_b64, ds_wrxchg2_rtn_b64 and ds_wrxchg2st64_rtn_b64, run through -spirv_mini_interp on the CPU. - -RDNA2 ISA, "Data Share Instructions": a 64-bit element is two dwords, low first. - ds_wrxchg_rtn_b64 vdst[0:1] = M[A]; M[A] = DATA A = vaddr + offset - ds_wrxchg2_rtn_b64 vdst[0:1] = M[A0]; M[A0] = DATA; vdst[2:3] = M[A1]; M[A1] = DATA2 - A0 / A1 = vaddr + offset0 / offset1 * 8 (* 512 for st64), as ds_write2_b64 addresses them -The translator does one 32-bit exchange per dword. Each case is a compute shader run as one invocation: it seeds the -LDS with ds_write_b64, runs the exchange, reads the element(s) back with ds_read_b64 and stores the words to a buffer. -Standard library only; no GPU, no LLVM, no game files. -""" -import os -import random -import sys -import unittest - -HERE = os.path.dirname(os.path.abspath(__file__)) -sys.dont_write_bytecode = True -sys.path.insert(0, HERE) - -from test_lds_atomics_values import run_listing # noqa: E402 (also puts tools/ on sys.path) -import rdna2spirv # noqa: E402 - -M32 = 0xFFFFFFFF - - -def split(v: int): - return v & M32, v >> 32 - - -def stores(regs): - body = [] - for k, r in enumerate(regs): - body += [f"v_mov_b32_e32 v31, {4 * k}", f"buffer_store_dword v{r}, v31, s[0:3], 0 offen"] - return body - - -def seed(reg_lo: int, value: int, addr_reg: int, addr: int): - lo, hi = split(value) - return [f"v_mov_b32_e32 v{addr_reg}, {addr:#x}", f"v_mov_b32_e32 v{reg_lo}, {lo:#x}", - f"v_mov_b32_e32 v{reg_lo + 1}, {hi:#x}", f"ds_write_b64 v{addr_reg}, v[{reg_lo}:{reg_lo + 1}]", - "s_waitcnt lgkmcnt(0)"] - - -def run_one(m: int, d: int, addr: int = 0x40, offset: int = 0, dst: str = "v[6:7]"): - """ds_wrxchg_rtn_b64 on M = m with DATA = d (in v[4:5]); returns (old lo, old hi, new lo, new hi).""" - body = seed(2, m, 10, addr + offset) + [f"v_mov_b32_e32 v1, {addr:#x}"] - body += [f"v_mov_b32_e32 v4, {split(d)[0]:#x}", f"v_mov_b32_e32 v5, {split(d)[1]:#x}", - f"ds_wrxchg_rtn_b64 {dst}, v1, v[4:5]" + (f" offset:{offset}" if offset else ""), "s_waitcnt lgkmcnt(0)", - "ds_read_b64 v[8:9], v10", "s_waitcnt lgkmcnt(0)"] - reg = int(dst[2:dst.index(":")]) - mem = run_listing(body + stores((reg, reg + 1, 8, 9))) - return tuple(mem.get(4 * k) for k in range(4)) - - -def run_two(op: str, m0: int, m1: int, d0: int, d1: int, off0: int, off1: int, addr: int = 0x40): - unit = 8 * (64 if "st64" in op else 1) - body = seed(2, m0, 10, addr + off0 * unit) + seed(2, m1, 11, addr + off1 * unit) - body += [f"v_mov_b32_e32 v1, {addr:#x}"] - for r, v in ((12, d0), (14, d1)): - body += [f"v_mov_b32_e32 v{r}, {split(v)[0]:#x}", f"v_mov_b32_e32 v{r + 1}, {split(v)[1]:#x}"] - body += [f"{op} v[16:19], v1, v[12:13], v[14:15] offset0:{off0} offset1:{off1}", "s_waitcnt lgkmcnt(0)", - "ds_read_b64 v[20:21], v10", "ds_read_b64 v[22:23], v11", "s_waitcnt lgkmcnt(0)"] - mem = run_listing(body + stores((16, 17, 18, 19, 20, 21, 22, 23))) - return tuple(mem.get(4 * k) for k in range(8)) - - -VALUES = [0, (1 << 64) - 1, 0x12345678_9ABCDEF0, 0x80000000_00000001, 0x00000000_FFFFFFFF] - - -class LdsWrxchgB64(unittest.TestCase): - def test_single_exchange(self): - for m in VALUES: - for d in VALUES[::2]: - with self.subTest(m=hex(m), d=hex(d)): - self.assertEqual(run_one(m, d), split(m) + split(d)) - - def test_single_offset_and_aliasing(self): - m, d = 0x11111111_22222222, 0x33333333_44444444 - self.assertEqual(run_one(m, d, addr=0x20, offset=0x18), split(m) + split(d)) - # vdst v[4:5] is the data pair: both dwords are read before the old value is written back. - self.assertEqual(run_one(m, d, dst="v[4:5]"), split(m) + split(d)) - - def test_two_exchanges(self): - rng = random.Random(0x2B64) - for op in ("ds_wrxchg2_rtn_b64", "ds_wrxchg2st64_rtn_b64"): - for off0, off1 in ((0, 1), (3, 5) if op == "ds_wrxchg2_rtn_b64" else (0, 2)): - m0, m1, d0, d1 = (rng.getrandbits(64) for _ in range(4)) - with self.subTest(op=op, offs=(off0, off1)): - self.assertEqual(run_two(op, m0, m1, d0, d1, off0, off1), - split(m0) + split(m1) + split(d0) + split(d1)) - - def test_st64_steps_are_512_bytes(self): - # offset1:1 is 512 bytes past vaddr for the b64 st64 form; the element seeded there comes back. - got = run_two("ds_wrxchg2st64_rtn_b64", 1, 2, 3, 4, 0, 1, addr=0x10) - self.assertEqual(got, (1, 0, 2, 0, 3, 0, 4, 0)) - - def test_bad_operands_rejected(self): - for line in ("ds_wrxchg_rtn_b64 v6, v1, v[4:5]", "ds_wrxchg_rtn_b64 v[6:7], v1, v4", - "ds_wrxchg2_rtn_b64 v[16:17], v1, v[12:13], v[14:15] offset1:1"): - with self.subTest(line=line): - with self.assertRaises(rdna2spirv.Unsupported): - run_listing(["v_mov_b32_e32 v1, 0", line]) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_loop_ballot_barrier.py b/tests/semantic/test_loop_ballot_barrier.py deleted file mode 100644 index 6d4aee659..000000000 --- a/tests/semantic/test_loop_ballot_barrier.py +++ /dev/null @@ -1,1561 +0,0 @@ -"""Semantic audit & regression tests for loop ballot masks and s_barrier in loops. - -Pure Python stdlib only (no llvm-mc, spirv-val, GPU, or game data). Translates synthetic hand-written -RDNA2 listings via tools/rdna2spirv.py and executes the emitted SPIR-V across every lane and wave: - - 1. Divergent loops with v_cmp / s_and_saveexec / s_or_b64 / s_and_b64 / s_andn2_b64 / - s_bcnt1_i32_b32/b64 / v_mbcnt / v_cndmask_b32 / v_readfirstlane_b32 in wave32, native wave64, - and --wave64-emulate (checked against tools/cf_ref.py and direct RDNA2 ISA oracles). - 2. Lane-mask / ballot bug regressions: - - wave32 32-bit SOP2 bitwise ops on EXEC with non-0/-1 immediates - - lane_masks.py preserving mask tracking on 64-bit mask + non-0/-1 immediate and s_mov_b64 vcc, imm - - wave64 SGPR pairs with separately-modified lo/hi halves (including (MASK_LO/HI, 0/-1) pairs and - loop-carried split pairs) in holds_lane_mask, mask_src, and --wave64-emulate wave_mask x_mcache - - v_mbcnt_lo/hi_u32_b32 respecting mask_half() in wave64 - 3. s_barrier inside group-uniform and wave-divergent loops with LDS writes/reads across: - - native wave32 CS (bar_scheduler / barrier rounds) - - native wave64 CS (structured OpLoopMerge with direct OpControlBarrier) - - --wave64-emulate CS (x_scheduler, 1 and 2 waves, multi-iteration ring wraparound) -""" -import gc -import os -import struct -import sys -import tempfile -import unittest -import warnings - -HERE = os.path.dirname(os.path.abspath(__file__)) -ROOT = os.path.dirname(os.path.dirname(HERE)) -TOOLS_DIR = os.environ.get("LEONIDA_TOOLS_DIR") or os.path.join(ROOT, "tools") - -sys.dont_write_bytecode = True -for _p in (HERE, TOOLS_DIR): - if _p not in sys.path: - sys.path.insert(0, _p) - -import cf_ref # noqa: E402 -import rdna2spirv # noqa: E402 -import spirv_wave_interp as wi # noqa: E402 - -M32 = 0xFFFFFFFF -M64 = 0xFFFFFFFFFFFFFFFF -STUB_DXBC = b"DXBC" + bytes(24) + struct.pack("= 0x80000000 else u - - -# --------------------------------------------------------------------------- -# Pure-Python multi-invocation SPIR-V compute workgroup interpreter -# --------------------------------------------------------------------------- - -def _parse_spv(asm): - """Parse SPIR-V assembly into constants, global/function var layouts, and labeled basic blocks.""" - consts = {} - types = {} - ptr_elem = {} - gvars = {} # %name -> (storage_class, elem_type) - fvars = [] # [(%name, elem_type, init_id_or_None)] - blocks = {} # %label -> [(res, op, args), ...] - helpers = {} # %fn -> ([params], [(res, op, args), ...]): single-block functions %main calls - cur = None - in_main = False - helper = None - - for raw in asm.splitlines(): - s = raw.strip() - if not s or s.startswith(";"): - continue - toks = s.split() - if len(toks) >= 3 and toks[1] == "=": - res, op, args = toks[0], toks[2], toks[3:] - else: - res, op, args = None, toks[0], toks[1:] - - if op == "OpFunction": - in_main = (res == "%main") - helper = None if in_main else res - if helper: - helpers[helper] = ([], []) - continue - if op == "OpFunctionEnd": - in_main = False - helper = None - cur = None - continue - if helper is not None: - # --wave64-emulate outlines the per-round exchange setup (%x_pre_*_fn, #2089) into single-block helpers - if op == "OpFunctionParameter": - helpers[helper][0].append(res) - elif op != "OpLabel": - helpers[helper][1].append((res, op, args)) - continue - - if not in_main: - if op == "OpTypeInt": - types[res] = ("int", int(args[0]), int(args[1])) - elif op == "OpTypeBool": - types[res] = ("bool",) - elif op == "OpTypeFloat": - types[res] = ("float", int(args[0])) - elif op == "OpTypeVector": - types[res] = ("vec", args[0], int(args[1])) - elif op == "OpTypeArray": - types[res] = ("arr", args[0], args[1]) - elif op == "OpTypeStruct": - types[res] = ("struct", list(args)) - elif op == "OpTypePointer": - ptr_elem[res] = (args[0], args[1]) - elif op == "OpConstant": - ty = types.get(args[0]) - if ty and ty[0] == "int": - val = int(args[1], 0) - consts[res] = val & M32 if ty[1] == 32 else val & M64 - elif ty and ty[0] == "float": - consts[res] = float(args[1]) - else: - consts[res] = int(args[1], 0) - elif op == "OpConstantTrue": - consts[res] = True - elif op == "OpConstantFalse": - consts[res] = False - elif op == "OpConstantNull": - consts[res] = ("null", args[0]) - elif op == "OpVariable": - sc = args[1] - _, elem = ptr_elem[args[0]] - gvars[res] = (sc, elem) - continue - - if op == "OpLabel": - cur = res - blocks[cur] = [] - continue - if op == "OpVariable": - _, elem = ptr_elem[args[0]] - init = args[2] if len(args) > 2 else None - fvars.append((res, elem, init)) - continue - if cur is not None: - blocks[cur].append((res, op, args)) - - # Expand each call of a single-block helper inline (fresh result ids per call); OpReturnValue becomes a copy into - # the call's result, so the lockstep interpreter only ever runs %main. - seq = 0 - for lbl, insns in blocks.items(): - if not any(op == "OpFunctionCall" for _, op, _ in insns): - continue - out = [] - for res, op, args in insns: - if op != "OpFunctionCall": - out.append((res, op, args)) - continue - seq += 1 - params, body = helpers[args[1]] - assert len(params) == len(args) - 2, f"OpFunctionCall {args[1]}: argument count" - ids = dict(zip(params, args[2:])) - for fres, fop, fargs in body: - fargs = [ids.get(x, x) for x in fargs] - if fop == "OpReturnValue": - out.append((res, "OpCopyObject", [args[0], fargs[0]])) - break - if fop == "OpReturn": - break - if fres: - ids[fres] = f"%call{seq}_{fres[1:]}" - out.append((ids.get(fres) if fres else None, fop, fargs)) - blocks[lbl] = out - - def make_zero(ty_id): - ty = types.get(ty_id) - if not ty: - return 0 - if ty[0] == "bool": - return False - if ty[0] == "int": - return 0 - if ty[0] == "float": - return 0.0 - if ty[0] == "vec": - return [make_zero(ty[1]) for _ in range(ty[2])] - if ty[0] == "arr": - n = consts[ty[2]] - return [make_zero(ty[1]) for _ in range(n)] - if ty[0] == "struct": - return [make_zero(f) for f in ty[1]] - return 0 - - return { - "consts": consts, - "types": types, - "ptr_elem": ptr_elem, - "gvars": gvars, - "fvars": fvars, - "blocks": blocks, - "make_zero": make_zero, - } - - -SUBGROUP_OPS = { - "OpGroupNonUniformAny", - "OpGroupNonUniformAll", - "OpGroupNonUniformBitwiseOr", - "OpGroupNonUniformBitwiseAnd", - "OpGroupNonUniformBitwiseXor", - "OpGroupNonUniformBroadcastFirst", - "OpGroupNonUniformShuffle", - "OpGroupNonUniformQuadSwap", - "OpGroupNonUniformBallot", - "OpGroupNonUniformBallotBitExtract", - "OpGroupNonUniformBallotBitCount", - "OpGroupNonUniformBallotFindLSB", -} - - -def run_compute_workgroup(asm, threads, subgroup_size, push_constants=None, memory=None, - wg_id=(0, 0, 0), size_xyz=None, reverse_subgroups=False, max_steps=500000): - """Execute a translated compute SPIR-V module across all invocations of one workgroup. - - Enforces: - - Lockstep subgroup execution on all OpGroupNonUniform* ops (raises SubgroupDivergenceError on mismatch). - - Uniform workgroup OpControlBarrier execution (raises NonUniformBarrierError if any invocation exits - or reaches a different barrier site while others wait). - - Shared Workgroup variables (%lds, %x_buf) and shared PhysicalStorageBuffer memory. - """ - mod = _parse_spv(asm) - consts = mod["consts"] - types = mod["types"] - gvars = mod["gvars"] - blocks = mod["blocks"] - make_zero = mod["make_zero"] - mem = {} if memory is None else memory - pc_words = list(push_constants or [0] * 32) - if len(pc_words) < 32: - pc_words += [0] * (32 - len(pc_words)) - sx, sy, sz = size_xyz if size_xyz is not None else (threads, 1, 1) - - # Shared Workgroup storage (initialized to 0xDEADBEEF to catch uninitialized reads!) - wg_storage = {} - for name, (sc, elem) in gvars.items(): - if sc == "Workgroup": - ty = types[elem] - if ty[0] == "arr": - wg_storage[name] = [0xDEADBEEF] * consts[ty[2]] - else: - wg_storage[name] = 0xDEADBEEF - - # PushConstant struct layout matches rdna2spirv: member 0 = array[32] of uint, members 1..4 = heap/code ptrs - pc_struct = [pc_words[:32], 0, 0, 0, 0] - - # Per-invocation state - class Inv: - __slots__ = ("gid", "sg_id", "sg_lane", "lid", "fn_mem", "ssa", "blk", "ip", "prev_blk", - "done", "waiting_barrier", "waiting_sg", "steps") - - def __init__(self, gid): - self.gid = gid - self.sg_id = gid // subgroup_size - self.sg_lane = gid % subgroup_size - x = gid % sx - y = (gid // sx) % sy - z = gid // (sx * sy) - self.lid = [x, y, z] - self.fn_mem = {} - for vname, elem, init in mod["fvars"]: - if init is None: - self.fn_mem[vname] = make_zero(elem) - elif isinstance(consts[init], tuple) and consts[init][0] == "null": - self.fn_mem[vname] = make_zero(consts[init][1]) - else: - self.fn_mem[vname] = consts[init] - self.ssa = dict(consts) - self.blk = "%entry" - self.ip = 0 - self.prev_blk = None - self.done = False - self.waiting_barrier = None # (blk, ip) when paused at OpControlBarrier - self.waiting_sg = None # (blk, ip, res, op, args) when paused at subgroup op - self.steps = 0 - - invs = [Inv(i) for i in range(threads)] - subgroups = [] - for s in range(0, threads, subgroup_size): - subgroups.append(invs[s:s + subgroup_size]) - - def val_of(inv, tok): - if tok in inv.ssa: - return inv.ssa[tok] - if tok in consts: - return consts[tok] - raise KeyError(f"Unknown SSA id {tok} in {inv.blk}") - - def read_ptr(inv, ptr): - kind = ptr[0] - if kind == "fn": - obj = inv.fn_mem[ptr[1]] - for idx in ptr[2:]: - obj = obj[idx] - return obj - if kind == "wg": - obj = wg_storage[ptr[1]] - for idx in ptr[2:]: - obj = obj[idx] - return obj - if kind == "pc": - obj = pc_struct - for idx in ptr[2:]: - obj = obj[idx] - return obj - if kind == "in": - name = ptr[1] - if name == "%wg_id": - return list(wg_id) - if name == "%local_id": - return list(inv.lid) - if name == "%sg_lane": - return inv.sg_lane - if name == "%local_index": - return inv.gid - raise KeyError(f"Unhandled input {name}") - if kind == "phys": - return mem.get(ptr[1], 0) - raise KeyError(f"Unhandled ptr kind {kind}") - - def write_ptr(inv, ptr, v): - kind = ptr[0] - if kind == "fn": - if len(ptr) == 2: - inv.fn_mem[ptr[1]] = v - else: - obj = inv.fn_mem[ptr[1]] - for idx in ptr[2:-1]: - obj = obj[idx] - obj[ptr[-1]] = v - return - if kind == "wg": - if len(ptr) == 2: - wg_storage[ptr[1]] = v - else: - obj = wg_storage[ptr[1]] - for idx in ptr[2:-1]: - obj = obj[idx] - obj[ptr[-1]] = v - return - if kind == "phys": - mem[ptr[1]] = v & M32 - return - raise KeyError(f"Cannot store to ptr {ptr}") - - def base_ptr(inv, tok): - if tok in inv.fn_mem: - return ("fn", tok) - if tok in gvars: - sc, _ = gvars[tok] - if sc == "Workgroup": - return ("wg", tok) - if sc == "PushConstant": - return ("pc", tok) - if sc == "Input": - return ("in", tok) - return val_of(inv, tok) - - def step_inv(inv): - """Step one invocation until OpControlBarrier, a subgroup op, or OpReturn.""" - while not inv.done and inv.waiting_barrier is None and inv.waiting_sg is None: - inv.steps += 1 - if inv.steps > max_steps: - raise TimeoutError(f"Invocation {inv.gid} exceeded {max_steps} steps at {inv.blk}:{inv.ip}") - insns = blocks[inv.blk] - res, op, args = insns[inv.ip] - - if op == "OpControlBarrier": - inv.waiting_barrier = (inv.blk, inv.ip) - return - if op in SUBGROUP_OPS: - inv.waiting_sg = (inv.blk, inv.ip, res, op, args) - return - - inv.ip += 1 - if op in ("OpSelectionMerge", "OpLoopMerge"): - continue - if op == "OpReturn": - inv.done = True - return - if op == "OpBranch": - inv.prev_blk = inv.blk - inv.blk = args[0] - inv.ip = 0 - continue - if op == "OpBranchConditional": - cond = val_of(inv, args[0]) - inv.prev_blk = inv.blk - inv.blk = args[1] if cond else args[2] - inv.ip = 0 - continue - if op == "OpSwitch": - sel = val_of(inv, args[0]) - tgt = args[1] - for k in range(2, len(args), 2): - if int(args[k], 0) == sel: - tgt = args[k + 1] - break - inv.prev_blk = inv.blk - inv.blk = tgt - inv.ip = 0 - continue - if op == "OpPhi": - found = False - for k in range(1, len(args), 2): - if args[k + 1] == inv.prev_blk: - inv.ssa[res] = val_of(inv, args[k]) - found = True - break - if not found: - raise RuntimeError(f"OpPhi in {inv.blk} missing predecessor {inv.prev_blk}") - continue - if op == "OpAccessChain": - p = base_ptr(inv, args[1]) - idxs = tuple(val_of(inv, a) for a in args[2:]) - inv.ssa[res] = p + idxs - elif op == "OpLoad": - p = base_ptr(inv, args[1]) - inv.ssa[res] = read_ptr(inv, p) - elif op == "OpStore": - p = base_ptr(inv, args[0]) - write_ptr(inv, p, val_of(inv, args[1])) - elif op == "OpConvertUToPtr": - inv.ssa[res] = ("phys", val_of(inv, args[1])) - elif op == "OpUConvert": - ty = types[args[0]] - v = val_of(inv, args[1]) - inv.ssa[res] = (v & M64) if ty[1] == 64 else (v & M32) - elif op == "OpCopyObject": - inv.ssa[res] = val_of(inv, args[1]) - elif op == "OpBitcast": - inv.ssa[res] = val_of(inv, args[1]) - elif op == "OpCompositeExtract": - inv.ssa[res] = val_of(inv, args[1])[int(args[2])] - elif op == "OpCompositeConstruct": - inv.ssa[res] = [val_of(inv, a) for a in args[1:]] - elif op == "OpSelect": - inv.ssa[res] = val_of(inv, args[2]) if val_of(inv, args[1]) else val_of(inv, args[3]) - elif op == "OpIAdd": - ty = types[args[0]] - mask = M64 if ty[1] == 64 else M32 - inv.ssa[res] = (val_of(inv, args[1]) + val_of(inv, args[2])) & mask - elif op == "OpIAddCarry": - s = (val_of(inv, args[1]) & M32) + (val_of(inv, args[2]) & M32) - inv.ssa[res] = [s & M32, 1 if s > M32 else 0] - elif op == "OpISubBorrow": - a, b = val_of(inv, args[1]) & M32, val_of(inv, args[2]) & M32 - inv.ssa[res] = [(a - b) & M32, 1 if a < b else 0] - elif op == "OpISub": - ty = types[args[0]] - mask = M64 if ty[1] == 64 else M32 - inv.ssa[res] = (val_of(inv, args[1]) - val_of(inv, args[2])) & mask - elif op == "OpIMul": - ty = types[args[0]] - mask = M64 if ty[1] == 64 else M32 - inv.ssa[res] = (val_of(inv, args[1]) * val_of(inv, args[2])) & mask - elif op == "OpUMod": - inv.ssa[res] = (val_of(inv, args[1]) % val_of(inv, args[2])) & M32 - elif op == "OpUDiv": - inv.ssa[res] = (val_of(inv, args[1]) // val_of(inv, args[2])) & M32 - elif op == "OpBitwiseAnd": - ty = types[args[0]] - mask = M64 if ty[1] == 64 else M32 - inv.ssa[res] = (val_of(inv, args[1]) & val_of(inv, args[2])) & mask - elif op == "OpBitwiseOr": - ty = types[args[0]] - mask = M64 if ty[1] == 64 else M32 - inv.ssa[res] = (val_of(inv, args[1]) | val_of(inv, args[2])) & mask - elif op == "OpBitwiseXor": - ty = types[args[0]] - mask = M64 if ty[1] == 64 else M32 - inv.ssa[res] = (val_of(inv, args[1]) ^ val_of(inv, args[2])) & mask - elif op == "OpNot": - ty = types[args[0]] - mask = M64 if ty[1] == 64 else M32 - inv.ssa[res] = (~val_of(inv, args[1])) & mask - elif op == "OpShiftLeftLogical": - ty = types[args[0]] - w = ty[1] - mask = M64 if w == 64 else M32 - sh = val_of(inv, args[2]) - inv.ssa[res] = ((val_of(inv, args[1]) << sh) & mask) if sh < w else 0 - elif op == "OpShiftRightLogical": - ty = types[args[0]] - w = ty[1] - mask = M64 if w == 64 else M32 - sh = val_of(inv, args[2]) - inv.ssa[res] = ((val_of(inv, args[1]) & mask) >> sh) if sh < w else 0 - elif op == "OpShiftRightArithmetic": - sh = val_of(inv, args[2]) - inv.ssa[res] = (_s32(val_of(inv, args[1])) >> min(sh, 31)) & M32 - elif op == "OpBitCount": - inv.ssa[res] = bin(val_of(inv, args[1]) & M32).count("1") - elif op == "OpBitReverse": - inv.ssa[res] = int(f"{val_of(inv, args[1]) & M32:032b}"[::-1], 2) - elif op == "OpBitFieldUExtract": - v, o, c = val_of(inv, args[1]) & M32, val_of(inv, args[2]), val_of(inv, args[3]) - inv.ssa[res] = 0 if c == 0 else ((v >> o) & ((1 << c) - 1)) - elif op == "OpIEqual": - inv.ssa[res] = (val_of(inv, args[1]) == val_of(inv, args[2])) - elif op == "OpINotEqual": - inv.ssa[res] = (val_of(inv, args[1]) != val_of(inv, args[2])) - elif op == "OpULessThan": - inv.ssa[res] = (val_of(inv, args[1]) < val_of(inv, args[2])) - elif op == "OpULessThanEqual": - inv.ssa[res] = (val_of(inv, args[1]) <= val_of(inv, args[2])) - elif op == "OpUGreaterThan": - inv.ssa[res] = (val_of(inv, args[1]) > val_of(inv, args[2])) - elif op == "OpUGreaterThanEqual": - inv.ssa[res] = (val_of(inv, args[1]) >= val_of(inv, args[2])) - elif op == "OpSLessThan": - inv.ssa[res] = (_s32(val_of(inv, args[1])) < _s32(val_of(inv, args[2]))) - elif op == "OpSLessThanEqual": - inv.ssa[res] = (_s32(val_of(inv, args[1])) <= _s32(val_of(inv, args[2]))) - elif op == "OpSGreaterThan": - inv.ssa[res] = (_s32(val_of(inv, args[1])) > _s32(val_of(inv, args[2]))) - elif op == "OpSGreaterThanEqual": - inv.ssa[res] = (_s32(val_of(inv, args[1])) >= _s32(val_of(inv, args[2]))) - elif op == "OpLogicalAnd": - inv.ssa[res] = bool(val_of(inv, args[1]) and val_of(inv, args[2])) - elif op == "OpLogicalOr": - inv.ssa[res] = bool(val_of(inv, args[1]) or val_of(inv, args[2])) - elif op == "OpLogicalNot": - inv.ssa[res] = not bool(val_of(inv, args[1])) - elif op == "OpLogicalEqual": - inv.ssa[res] = (bool(val_of(inv, args[1])) == bool(val_of(inv, args[2]))) - elif op == "OpLogicalNotEqual": - inv.ssa[res] = (bool(val_of(inv, args[1])) != bool(val_of(inv, args[2]))) - elif op == "OpExtInst": - fn = args[2] - xs = [val_of(inv, a) for a in args[3:]] - if fn == "UMin": - inv.ssa[res] = min(xs[0] & M32, xs[1] & M32) - elif fn == "UMax": - inv.ssa[res] = max(xs[0] & M32, xs[1] & M32) - elif fn == "SMin": - inv.ssa[res] = min(_s32(xs[0]), _s32(xs[1])) & M32 - elif fn == "SMax": - inv.ssa[res] = max(_s32(xs[0]), _s32(xs[1])) & M32 - elif fn == "FindILsb": - v = xs[0] & M32 - inv.ssa[res] = M32 if v == 0 else (v & -v).bit_length() - 1 - elif fn == "FindUMsb": - v = xs[0] & M32 - inv.ssa[res] = M32 if v == 0 else v.bit_length() - 1 - else: - raise NotImplementedError(f"OpExtInst {fn}") - elif op == "OpAtomicOr": - p = base_ptr(inv, args[1]) - old = read_ptr(inv, p) & M32 - write_ptr(inv, p, (old | (val_of(inv, args[4]) & M32)) & M32) - inv.ssa[res] = old - elif op == "OpAtomicIAdd": - p = base_ptr(inv, args[1]) - old = read_ptr(inv, p) & M32 - write_ptr(inv, p, (old + (val_of(inv, args[4]) & M32)) & M32) - inv.ssa[res] = old - elif op == "OpAtomicAnd": - p = base_ptr(inv, args[1]) - old = read_ptr(inv, p) & M32 - write_ptr(inv, p, (old & (val_of(inv, args[4]) & M32)) & M32) - inv.ssa[res] = old - elif op == "OpAtomicXor": - p = base_ptr(inv, args[1]) - old = read_ptr(inv, p) & M32 - write_ptr(inv, p, (old ^ (val_of(inv, args[4]) & M32)) & M32) - inv.ssa[res] = old - elif op == "OpAtomicExchange": - p = base_ptr(inv, args[1]) - old = read_ptr(inv, p) & M32 - write_ptr(inv, p, val_of(inv, args[4]) & M32) - inv.ssa[res] = old - else: - raise NotImplementedError(f"Unsupported SPIR-V op {op} in {inv.blk}") - - def resolve_subgroup(sg): - sites = {inv.waiting_sg[:2] for inv in sg} - if len(sites) != 1: - raise SubgroupDivergenceError(f"Subgroup diverged across sites {sites}") - _, _, res, op, args = sg[0].waiting_sg - if op == "OpGroupNonUniformAny": - ans = any(bool(val_of(inv, args[2])) for inv in sg) - for inv in sg: - inv.ssa[res] = ans - elif op == "OpGroupNonUniformAll": - ans = all(bool(val_of(inv, args[2])) for inv in sg) - for inv in sg: - inv.ssa[res] = ans - elif op == "OpGroupNonUniformBitwiseOr": - acc = 0 - for inv in sg: - acc |= val_of(inv, args[3]) & M32 - for inv in sg: - inv.ssa[res] = acc - elif op == "OpGroupNonUniformBitwiseAnd": - acc = M32 - for inv in sg: - acc &= val_of(inv, args[3]) & M32 - for inv in sg: - inv.ssa[res] = acc - elif op == "OpGroupNonUniformBitwiseXor": - acc = 0 - for inv in sg: - acc ^= val_of(inv, args[3]) & M32 - for inv in sg: - inv.ssa[res] = acc - elif op == "OpGroupNonUniformBroadcastFirst": - v0 = val_of(sg[0], args[2]) - for inv in sg: - inv.ssa[res] = v0 - elif op == "OpGroupNonUniformShuffle": - vals = [val_of(inv, args[2]) for inv in sg] - for inv in sg: - src = val_of(inv, args[3]) - if not (0 <= src < len(sg)): - raise RuntimeError(f"Out-of-range subgroup shuffle index {src} (size {len(sg)})") - inv.ssa[res] = vals[src] - elif op == "OpGroupNonUniformQuadSwap": - d = val_of(sg[0], args[3]) - xor = 1 if d == 0 else (2 if d == 1 else 3) - vals = [val_of(inv, args[2]) for inv in sg] - for i, inv in enumerate(sg): - inv.ssa[res] = vals[i ^ xor] - elif op == "OpGroupNonUniformBallot": - words = [0, 0, 0, 0] - for inv in sg: - if val_of(inv, args[2]): - words[inv.sg_lane >> 5] |= 1 << (inv.sg_lane & 31) - for inv in sg: - inv.ssa[res] = list(words) - elif op == "OpGroupNonUniformBallotBitExtract": - for inv in sg: - b = val_of(inv, args[2]) - idx = val_of(inv, args[3]) - inv.ssa[res] = bool((b[idx >> 5] >> (idx & 31)) & 1) if idx < 128 else False - elif op == "OpGroupNonUniformBallotBitCount": - op_kind = args[2] - for inv in sg: - b = val_of(inv, args[3]) - bits = b[0] | (b[1] << 32) - if op_kind == "Reduce": - inv.ssa[res] = bin(bits).count("1") - elif op_kind == "ExclusiveScan": - inv.ssa[res] = bin(bits & ((1 << inv.sg_lane) - 1)).count("1") - elif op_kind == "InclusiveScan": - inv.ssa[res] = bin(bits & ((1 << (inv.sg_lane + 1)) - 1)).count("1") - else: - raise NotImplementedError(op_kind) - elif op == "OpGroupNonUniformBallotFindLSB": - for inv in sg: - b = val_of(inv, args[2]) - bits = b[0] | (b[1] << 32) - inv.ssa[res] = M32 if bits == 0 else (bits & -bits).bit_length() - 1 - else: - raise NotImplementedError(op) - - for inv in sg: - inv.ip += 1 - inv.waiting_sg = None - - order = list(reversed(subgroups)) if reverse_subgroups else list(subgroups) - while not all(inv.done for inv in invs): - # Advance each subgroup until every lane in it is done or paused at a barrier - for sg in order: - while True: - if all(inv.done or inv.waiting_barrier is not None for inv in sg): - break - for inv in sg: - step_inv(inv) - # Check if some lanes hit a subgroup op while others finished or hit a barrier - sg_waiting = [inv for inv in sg if inv.waiting_sg is not None] - if sg_waiting: - if len(sg_waiting) != len(sg): - states = [(inv.gid, inv.blk, inv.done, inv.waiting_barrier, - inv.waiting_sg[:2] if inv.waiting_sg else None) for inv in sg] - raise SubgroupDivergenceError( - f"Only {len(sg_waiting)}/{len(sg)} lanes reached subgroup op: {states[:4]}" - ) - resolve_subgroup(sg) - - if all(inv.done for inv in invs): - break - # Barrier sync: EVERY invocation must be waiting at the SAME OpControlBarrier - bar_waiting = [inv for inv in invs if inv.waiting_barrier is not None] - if len(bar_waiting) != len(invs): - raise NonUniformBarrierError( - f"Non-uniform OpControlBarrier: {len(bar_waiting)}/{len(invs)} invocations arrived " - f"({sum(inv.done for inv in invs)} already returned)" - ) - sites = {inv.waiting_barrier for inv in invs} - if len(sites) != 1: - raise NonUniformBarrierError(f"Invocations reached different OpControlBarrier sites: {sites}") - for inv in invs: - inv.ip += 1 - inv.waiting_barrier = None - - return mem - - -# --------------------------------------------------------------------------- -# Synthetic listing helpers (pure hand-written RDNA2, zero game data) -# --------------------------------------------------------------------------- - -def _ins_size(text): - op = text.split()[0] - if op.startswith(("exp", "buffer_", "global_", "ds_", "image_")) or op.endswith("_e64"): - return 8 - if op in ("v_mbcnt_lo_u32_b32", "v_mbcnt_hi_u32_b32", "v_readlane_b32", "v_writelane_b32", - "v_lshl_add_u32", "v_cndmask_b32_e64"): - return 8 - if "0x" in text: - return 8 - if op.startswith("v_cmp") and not op.endswith("_e32") and "vcc" not in text: - return 8 - return 4 - - -def _resolve_labels(items): - """Turn a list of instructions and 'label:' markers into (text, size) with resolved branch offsets.""" - parsed = [] - labels = {} - pc = 0 - for it in items: - s = it.strip() - if not s or s.startswith(";"): - continue - if s.endswith(":"): - labels[s[:-1]] = pc - continue - sz = _ins_size(s) - parsed.append((s, sz, pc)) - pc += sz - - out = [] - for s, sz, ipc in parsed: - toks = s.split() - if toks[0].startswith(("s_branch", "s_cbranch_")) and len(toks) == 2 and toks[1] in labels: - delta = (labels[toks[1]] - (ipc + sz)) // 4 - s = f"{toks[0]} {delta}" - out.append((s, sz)) - return out - - -def _translate_cs(name, items, threads=64, lds_bytes=0, emulate=False, size_xyz=None, structured=True): - lines = _resolve_labels(items) - sx, sy, sz = size_xyz if size_xyz is not None else (threads, 1, 1) - lds_blocks = (lds_bytes + 511) // 512 - rsrc2 = 0x8090 | ((lds_blocks & 0x1FF) << 15) - with tempfile.TemporaryDirectory() as tmp: - os.mkdir(os.path.join(tmp, "disasm")) - os.mkdir(os.path.join(tmp, "fssm")) - src = os.path.join(tmp, "disasm", name + ".s") - with open(src, "w", encoding="utf-8", newline="\n") as f: - f.write(f"; {name} synthetic\n") - for text, size in lines: - f.write(f"\t{text} ; encoding: [{','.join(['0x00'] * size)}]\n") - with open(os.path.join(tmp, name + ".dxbc"), "wb") as f: - f.write(STUB_DXBC) - with open(os.path.join(tmp, "fssm", name + ".fssm"), "wb") as f: - f.write(bytes(0x138) + struct.pack("<4I", rsrc2, sx, sy, sz)) - old_em, old_st = rdna2spirv.WAVE64_EMULATE, rdna2spirv.STRUCTURED - rdna2spirv.WAVE64_EMULATE = emulate - rdna2spirv.STRUCTURED = structured # False: --dispatch-loop, which keeps the emulation's round scheduler - try: - with warnings.catch_warnings(): - warnings.simplefilter("ignore", ResourceWarning) - spv = rdna2spirv.translate(src) - gen = rdna2spirv.translate.last_gen - gc.collect() - finally: - rdna2spirv.WAVE64_EMULATE, rdna2spirv.STRUCTURED = old_em, old_st - return spv, gen - - -def _translate_and_ref_ps(name, items, wave, use_cf_ref=True): - """Translate a synthetic PS and run spirv_wave_interp.run_wave (and optionally cf_ref.WaveMachine).""" - lines = _resolve_labels(items) - with tempfile.TemporaryDirectory() as tmp: - os.mkdir(os.path.join(tmp, "disasm")) - src = os.path.join(tmp, "disasm", name + ".s") - with open(src, "w", encoding="utf-8", newline="\n") as f: - f.write(f"; {name} synthetic\n") - for text, size in lines: - f.write(f"\t{text} ; encoding: [{','.join(['0x00'] * size)}]\n") - with open(os.path.join(tmp, name + ".dxbc"), "wb") as f: - f.write(STUB_DXBC) - ref = cf_ref.run(src, wave=wave)["exports"] if use_cf_ref else None - with warnings.catch_warnings(): - warnings.simplefilter("ignore", ResourceWarning) - spv = rdna2spirv.translate(src) - gc.collect() - got = wi.run_wave(spv, wave=wave) - actual = {} - for lane, out in enumerate(got["outputs"]): - if out: - for k, v in out.items(): - if k.endswith(("mrt0", "out0")): - actual[lane] = tuple(v) - break - return ref, actual, spv - - -def _build_mask_from_s4_s5_w64(): - """RDNA2 snippet: sets vcc[lane] = bit (lane&31) of (s4 if lane<32 else s5), and marks wave64.""" - return [ - "v_mov_b32_e32 v11, s5", - "v_cmp_lt_u32_e64 vcc, v0, 32", - "v_cndmask_b32_e64 v1, v11, s4, vcc", - "v_and_b32_e32 v2, 31, v0", - "v_lshrrev_b32_e32 v3, v2, v1", - "v_and_b32_e32 v3, 1, v3", - "v_cmp_ne_u32_e64 vcc, 0, v3", - "s_and_b64 s[12:13], vcc, exec", - ] - - -# --------------------------------------------------------------------------- -# 1. Divergent loops with ballots, popcount, mbcnt, cndmask, saveexec -# --------------------------------------------------------------------------- - -class DivergentLoopBallotTests(unittest.TestCase): - """Audit Hazard 1: verify inactive/exited lanes never leave stale bits across loop iterations.""" - - def _divergent_loop_ps_program(self, wave): - """Each lane runs (lane & 3) + 1 iterations; tracks per-iteration active count, rank, - and a loop-accumulated mask of lanes that ever reached iter == 3. - """ - if wave == 32: - return [ - "v_mbcnt_lo_u32_b32 v0, -1, 0", - "v_and_b32_e32 v1, 3, v0", # limit = (lane & 3) + 1 (1..4 iters) - "v_add_nc_u32_e32 v1, 1, v1", - "v_mov_b32_e32 v2, 0", # iter counter - "v_mov_b32_e32 v3, 0", # sum of active wave counts seen by this lane - "v_mov_b32_e32 v4, 0", # sum of lane ranks seen by this lane - "s_mov_b32 s10, exec_lo", # save outer exec - "s_mov_b32 s14, 0", # accumulator mask across iterations (EITHER -> MASK) - "loop:", - "v_add_nc_u32_e32 v2, 1, v2", - "s_bcnt1_i32_b32 s6, exec_lo", - "v_add_nc_u32_e32 v3, s6, v3", - "v_mbcnt_lo_u32_b32 v7, exec_lo, 0", - "v_add_nc_u32_e32 v4, v7, v4", - # Compare inside divergent loop: inactive lanes MUST write 0, not keep stale vcc! - "v_cmp_eq_u32_e32 vcc_lo, 3, v2", - "s_or_b32 s14, s14, vcc_lo", - # Exit lanes where v2 >= v1 - "v_cmp_lt_u32_e32 vcc_lo, v2, v1", - "s_and_b32 exec_lo, exec_lo, vcc_lo", - "s_cbranch_execnz loop", - "s_mov_b32 exec_lo, s10", - # Verify s14 has exact lanes that reached iter 3 (i.e. limit >= 3, (lane & 3) >= 2) - "s_bcnt1_i32_b32 s15, s14", - "v_cndmask_b32_e64 v5, 0, s15, s14", - "exp mrt0 v2, v3, v4, v5 done vm", - "s_endpgm", - ] - return [ - "s_mov_b64 s[10:11], exec", - "v_mbcnt_lo_u32_b32 v0, -1, 0", - "v_mbcnt_hi_u32_b32 v0, -1, v0", - "v_and_b32_e32 v1, 3, v0", # limit = (lane & 3) + 1 (1..4 iters) - "v_add_nc_u32_e32 v1, 1, v1", - "v_mov_b32_e32 v2, 0", - "v_mov_b32_e32 v3, 0", - "v_mov_b32_e32 v4, 0", - "s_mov_b64 s[14:15], 0", # accumulator mask (EITHER -> MASK via back-edge) - "loop:", - "v_add_nc_u32_e32 v2, 1, v2", - "s_bcnt1_i32_b64 s6, exec", - "v_add_nc_u32_e32 v3, s6, v3", - "v_mbcnt_lo_u32_b32 v7, exec_lo, 0", - "v_mbcnt_hi_u32_b32 v7, exec_hi, v7", - "v_add_nc_u32_e32 v4, v7, v4", - # Compare inside divergent loop: inactive lanes MUST write 0 into vcc! - "v_cmp_eq_u32_e32 vcc, 3, v2", - "s_or_b64 s[14:15], s[14:15], vcc", - # Exit lanes where v2 >= v1 using s_and_saveexec_b64 - "v_cmp_lt_u32_e32 vcc, v2, v1", - "s_and_saveexec_b64 s[16:17], vcc", - "s_cbranch_execnz loop", - "s_mov_b64 exec, s[10:11]", - "s_bcnt1_i32_b64 s18, s[14:15]", - "v_cndmask_b32_e64 v5, 0, s18, s[14:15]", - "exp mrt0 v2, v3, v4, v5 done vm", - "s_endpgm", - ] - - def _cf_ref_divergent_loop(self, wave): - """Divergent loop using only ops modelled by tools/cf_ref.py (v_cmp, s_and_saveexec, s_or, s_and, v_cndmask).""" - if wave == 32: - return [ - "v_mbcnt_lo_u32_b32 v0, -1, 0", - "v_and_b32_e32 v1, 3, v0", - "v_add_nc_u32_e32 v1, 1, v1", - "v_mov_b32_e32 v2, 0", - "v_mov_b32_e32 v3, 0", - "s_mov_b32 s10, exec_lo", - "s_mov_b32 s14, 0", - "loop:", - "v_add_nc_u32_e32 v2, 1, v2", - "v_cmp_eq_u32_e32 vcc_lo, 3, v2", - "s_or_b32 s14, s14, vcc_lo", - "v_cndmask_b32_e64 v4, 0, 10, vcc_lo", - "v_add_nc_u32_e32 v3, v4, v3", - "v_cmp_lt_u32_e32 vcc_lo, v2, v1", - "s_and_saveexec_b32 s12, vcc_lo", - "s_cbranch_execnz loop", - "s_mov_b32 exec_lo, s10", - "v_cndmask_b32_e64 v5, 0, 77, s14", - "exp mrt0 v2, v3, v5, v1 done vm", - "s_endpgm", - ] - return [ - "s_mov_b64 s[10:11], exec", - "v_mbcnt_lo_u32_b32 v0, -1, 0", - "v_mbcnt_hi_u32_b32 v0, -1, v0", - "v_and_b32_e32 v1, 3, v0", - "v_add_nc_u32_e32 v1, 1, v1", - "v_mov_b32_e32 v2, 0", - "v_mov_b32_e32 v3, 0", - "s_mov_b64 s[14:15], 0", - "loop:", - "v_add_nc_u32_e32 v2, 1, v2", - "v_cmp_eq_u32_e32 vcc, 3, v2", - "s_or_b64 s[14:15], s[14:15], vcc", - "v_cndmask_b32_e64 v4, 0, 10, vcc", - "v_add_nc_u32_e32 v3, v4, v3", - "v_cmp_lt_u32_e32 vcc, v2, v1", - "s_and_saveexec_b64 s[12:13], vcc", - "s_cbranch_execnz loop", - "s_mov_b64 exec, s[10:11]", - "v_cndmask_b32_e64 v5, 0, 77, s[14:15]", - "exp mrt0 v2, v3, v5, v1 done vm", - "s_endpgm", - ] - - def test_divergent_loop_cf_ref_exact_match(self): - for wave in (32, 64): - with self.subTest(wave=wave): - ref, got, _ = _translate_and_ref_ps(f"ps_cf_ref_loop_w{wave}", self._cf_ref_divergent_loop(wave), - wave=wave, use_cf_ref=True) - self.assertEqual(len(got), wave) - self.assertEqual(got, ref) - - def test_divergent_loop_wave32_bcnt_mbcnt_oracle(self): - _, got, _ = _translate_and_ref_ps("ps_div_loop_w32", self._divergent_loop_ps_program(32), - wave=32, use_cf_ref=False) - self.assertEqual(len(got), 32) - for lane in range(32): - lim = (lane & 3) + 1 - counts = [32, 24, 16, 8] - want_v3 = sum(counts[:lim]) - want_v4 = sum(sum(1 for j in range(lane) if (j & 3) >= it) for it in range(lim)) - self.assertEqual(got[lane], (lim, want_v3, want_v4, 16 if lim >= 3 else 0), f"lane {lane}") - - def test_divergent_loop_wave64_bcnt_mbcnt_oracle(self): - _, got, _ = _translate_and_ref_ps("ps_div_loop_w64", self._divergent_loop_ps_program(64), - wave=64, use_cf_ref=False) - self.assertEqual(len(got), 64) - for lane in range(64): - lim = (lane & 3) + 1 - counts = [64, 48, 32, 16] - want_v3 = sum(counts[:lim]) - want_v4 = sum(sum(1 for j in range(lane) if (j & 3) >= it) for it in range(lim)) - self.assertEqual(got[lane], (lim, want_v3, want_v4, 32 if lim >= 3 else 0), f"lane {lane}") - - def test_divergent_loop_wave64_emulate_and_native_cs(self): - """Same divergent loop with ballot/bcnt1/mbcnt/readfirstlane/cndmask in compute shaders: - native wave64 (64 & 128 threads) AND --wave64-emulate (64, 128, and partial 40 threads on 32-wide subgroups). - """ - prog = [ - "s_mov_b64 s[10:11], exec", - "v_and_b32_e32 v1, 3, v0", # limit = (lane & 3) + 1 (1..4) - "v_add_nc_u32_e32 v1, 1, v1", - "v_mov_b32_e32 v2, 0", # iter - "v_mov_b32_e32 v3, 0", # sum of bcnt1(exec) - "v_mov_b32_e32 v4, 0", # sum of mbcnt(exec) - "v_mov_b32_e32 v8, 0", # sum of readfirstlane(v0) - "s_mov_b64 s[14:15], 0", # accumulated mask of lanes hitting iter == 3 - "loop:", - "v_add_nc_u32_e32 v2, 1, v2", - "s_bcnt1_i32_b64 s6, exec", - "v_add_nc_u32_e32 v3, s6, v3", - "v_mbcnt_lo_u32_b32 v7, exec_lo, 0", - "v_mbcnt_hi_u32_b32 v7, exec_hi, v7", - "v_add_nc_u32_e32 v4, v7, v4", - "v_readfirstlane_b32 s7, v0", - "v_add_nc_u32_e32 v8, s7, v8", - # Stale-bit probe: vcc is set only for active lanes with v2 == 3; exited lanes MUST NOT contribute - "v_cmp_eq_u32_e32 vcc, 3, v2", - "s_or_b64 s[14:15], s[14:15], vcc", - # Second bcnt1 in same block AFTER vcc changed (tests x_mcache invalidation!) - "s_bcnt1_i32_b64 s9, vcc", - "v_add_nc_u32_e32 v3, s9, v3", - "v_cmp_lt_u32_e32 vcc, v2, v1", - "s_and_saveexec_b64 s[16:17], vcc", - "s_cbranch_execnz loop", - "s_mov_b64 exec, s[10:11]", - "s_bcnt1_i32_b64 s18, s[14:15]", - "v_cndmask_b32_e64 v5, 0, s18, s[14:15]", - # Store 4 words per thread: [v2, v3, v4, v5 ^ (v8 << 16)] - "v_lshlrev_b32_e32 v9, 16, v8", - "v_xor_b32_e32 v5, v5, v9", - "v_lshlrev_b32_e32 v6, 4, v0", - "buffer_store_dword v2, v6, s[0:3], 0 offen offset:0", - "buffer_store_dword v3, v6, s[0:3], 0 offen offset:4", - "buffer_store_dword v4, v6, s[0:3], 0 offen offset:8", - "buffer_store_dword v5, v6, s[0:3], 0 offen offset:12", - "s_endpgm", - ] - - def expected_for(threads): - out = {} - for wbase in range(0, threads, 64): - wlen = min(64, threads - wbase) - active = list(range(wbase, wbase + wlen)) - iters = {t: 0 for t in active} - v3 = {t: 0 for t in active} - v4 = {t: 0 for t in active} - v8 = {t: 0 for t in active} - acc_mask = set() - cur = list(active) - while cur: - for t in cur: - iters[t] += 1 - cnt = len(cur) - first = cur[0] - vcc_eq3 = [t for t in cur if iters[t] == 3] - acc_mask.update(vcc_eq3) - for rank, t in enumerate(cur): - v3[t] += cnt + len(vcc_eq3) - v4[t] += rank - v8[t] += first - cur = [t for t in cur if iters[t] < ((t & 3) + 1)] - for t in active: - v5 = (len(acc_mask) if t in acc_mask else 0) ^ ((v8[t] << 16) & M32) - out[t] = (iters[t], v3[t], v4[t], v5) - return out - - configs = [ - ("native_64", 64, 64, False, True), - ("native_128", 128, 64, False, True), - # a reducible multi-block loop takes the structured emulation since #2089 (no round OpSwitch) ... - ("emulate_64_sg32", 64, 32, True, True), - ("emulate_128_sg32", 128, 32, True, True), - ("emulate_40_partial_sg32", 40, 32, True, True), - # ... and --dispatch-loop keeps the round scheduler: both must give the native words - ("emulate_64_sg32_rounds", 64, 32, True, False), - ("emulate_128_sg32_rounds", 128, 32, True, False), - ("emulate_40_partial_sg32_rounds", 40, 32, True, False), - ] - for label, threads, sg_sz, emulate, structured in configs: - with self.subTest(mode=label): - spv, gen = _translate_cs("cs_div_loop_" + label, prog, threads=threads, emulate=emulate, - structured=structured) - if emulate: - self.assertEqual(gen.control_flow, - "emulated wave64 structured" if structured else "emulated wave64 rounds") - mem = run_compute_workgroup(spv, threads, sg_sz, push_constants=VSHARP) - want = expected_for(threads) - for t in range(threads): - got = tuple(mem.get(16 * t + 4 * k, -1) for k in range(4)) - self.assertEqual(got, want[t], f"{label} thread {t}") - - def test_nested_divergent_loops_emulate(self): - """Nested divergent loops (outer s_and_saveexec, inner s_mov_b64 save/restore) - under --wave64-emulate: ensures x_buf ring buffer and outer/inner exec masks never leak bits. - """ - prog = [ - "s_mov_b64 s[10:11], exec", - "v_and_b32_e32 v1, 3, v0", # outer trips: (lane & 3) + 1 - "v_add_nc_u32_e32 v1, 1, v1", - "v_mov_b32_e32 v2, 0", # outer i - "v_mov_b32_e32 v5, 0", # total inner executions weighted by active inner count - "outer:", - "v_add_nc_u32_e32 v2, 1, v2", - # Inner loop: lanes with (v0 & 4) != 0 run 2 inner iters, others run 1 - "v_and_b32_e32 v3, 4, v0", - "v_cmp_ne_u32_e32 vcc, 0, v3", - "v_cndmask_b32_e64 v3, 1, 2, vcc", # inner limit = 2 if (lane & 4) else 1 - "v_mov_b32_e32 v4, 0", # inner j - "s_mov_b64 s[12:13], exec", # save outer active mask - "inner:", - "v_add_nc_u32_e32 v4, 1, v4", - "s_bcnt1_i32_b64 s6, exec", - "v_add_nc_u32_e32 v5, s6, v5", - "v_cmp_lt_u32_e32 vcc, v4, v3", - "s_and_b64 exec, exec, vcc", - "s_cbranch_execnz inner", - "s_mov_b64 exec, s[12:13]", # restore outer active mask - "v_cmp_lt_u32_e32 vcc, v2, v1", - "s_and_b64 exec, exec, vcc", - "s_cbranch_execnz outer", - "s_mov_b64 exec, s[10:11]", - "v_lshlrev_b32_e32 v6, 2, v0", - "buffer_store_dword v5, v6, s[0:3], 0 offen", - "s_endpgm", - ] - want = [0] * 64 - outer_active = list(range(64)) - outer_i = [0] * 64 - while outer_active: - for t in outer_active: - outer_i[t] += 1 - inner_active = list(outer_active) - inner_j = {t: 0 for t in inner_active} - while inner_active: - for t in inner_active: - inner_j[t] += 1 - want[t] += len(inner_active) - inner_active = [t for t in inner_active if inner_j[t] < (2 if (t & 4) else 1)] - outer_active = [t for t in outer_active if outer_i[t] < ((t & 3) + 1)] - - for emulate, sg_sz in ((False, 64), (True, 32)): - with self.subTest(emulate=emulate): - spv, _ = _translate_cs(f"cs_nested_loop_{int(emulate)}", prog, threads=64, emulate=emulate) - mem = run_compute_workgroup(spv, 64, sg_sz, push_constants=VSHARP) - self.assertEqual([mem.get(4 * t, -1) for t in range(64)], want) - - -# --------------------------------------------------------------------------- -# 2. Lane-mask / ballot bug reproducers & regressions -# --------------------------------------------------------------------------- - -class LaneMaskBugTests(unittest.TestCase): - """Targeted regressions for lane-mask tracking, split wave64 SGPR pairs, x_mcache, and v_mbcnt halves.""" - - def test_bug2a_wave32_bitwise_mask_with_non_trivial_imm(self): - """Wave32 32-bit bitwise ops writing EXEC with a non-0/-1 immediate (`s_and_b32 exec_lo, exec_lo, 0xFF`, - `s_andn2_b32 exec_lo, exec_lo, 5`) extract bit L per lane via mask_src(wide=False). - """ - prog = [ - "v_mbcnt_lo_u32_b32 v0, -1, 0", - "v_mov_b32_e32 v2, 0", - "v_mov_b32_e32 v3, 0", - "s_mov_b32 s10, exec_lo", - # Restrict active lanes to 0..7 - "s_and_b32 exec_lo, exec_lo, 0xFF", - "v_mov_b32_e32 v2, 1", - # Now clear lane 0 and lane 2 (mask 0x5) -> only lanes 1,3,4,5,6,7 stay active - "s_andn2_b32 exec_lo, exec_lo, 5", - "v_mov_b32_e32 v3, 1", - "s_bcnt1_i32_b32 s6, exec_lo", - "s_mov_b32 exec_lo, s10", - "v_mov_b32_e32 v4, s6", - "v_mov_b32_e32 v5, 0", - "exp mrt0 v2, v3, v4, v5 done vm", - "s_endpgm", - ] - _, got, _ = _translate_and_ref_ps("ps_bug2a_w32_mask_imm", prog, wave=32, use_cf_ref=False) - for lane in range(32): - want_v2 = 1 if lane < 8 else 0 - want_v3 = 1 if (lane < 8 and lane not in (0, 2)) else 0 - self.assertEqual(got[lane], (want_v2, want_v3, 6, 0), f"lane {lane}") - - def test_bug3a_lane_masks_preserves_b64_mask_on_non_trivial_imm(self): - """Combining a 64-bit lane mask with a non-0/-1 immediate (`s_and_b64 s[14:15], vcc, 0xFF`) or moving - a constant into VCC (`s_mov_b64 vcc, 0x3F`) stores a per-lane mask in rdna2spirv.py, so lane_masks.py - must keep tracking the destination as a lane mask for subsequent `s_bcnt1_i32_b64` / `v_cndmask_b32`. - """ - prog = [ - "s_mov_b64 s[10:11], exec", - "v_mbcnt_lo_u32_b32 v0, -1, 0", - "v_mbcnt_hi_u32_b32 v0, -1, v0", - "v_and_b32_e32 v1, 1, v0", - "v_cmp_eq_u32_e32 vcc, 0, v1", # even lanes: 0x55555555_55555555 - "s_and_b64 s[14:15], vcc, 0xFF", # lanes 0,2,4,6 -> popcount MUST be 4 in every lane! - "s_bcnt1_i32_b64 s6, s[14:15]", - "s_mov_b64 vcc, 0x3F", # lanes 0..5 -> popcount MUST be 6 in every lane! - "s_bcnt1_i32_b64 s7, vcc", - "v_mov_b32_e32 v2, s6", - "v_mov_b32_e32 v3, s7", - "v_cndmask_b32_e64 v4, 0, 1, s[14:15]", - "v_cndmask_b32_e64 v5, 0, 1, vcc", - "exp mrt0 v2, v3, v4, v5 done vm", - "s_endpgm", - ] - _, got, _ = _translate_and_ref_ps("ps_bug3a_mask_imm", prog, wave=64, use_cf_ref=False) - for lane in range(64): - self.assertEqual(got[lane], (4, 6, 1 if (lane < 8 and lane % 2 == 0) else 0, 1 if lane < 6 else 0), - f"lane {lane}") - - def test_bug4_wave64_split_sgpr_pair_halves(self): - """If a wave64 SGPR pair s[12:13] has its hi half s13 modified by a 32-bit op (`s_mov_b32 s13, 0`), - subsequent 64-bit mask reads of s[12:13] (`s_bcnt1_i32_b64`, `v_cndmask_b32`) must read s12 for - lanes 0-31 and s13 for lanes 32-63, and --wave64-emulate's x_mcache must invalidate when s13 changes! - """ - prog = _build_mask_from_s4_s5_w64() + [ - "s_bcnt1_i32_b64 s6, s[12:13]", # populates x_mcache for s[12:13] - "s_mov_b32 s13, 0", # clear ONLY hi half of s[12:13] (MASK_HI -> EITHER) - "s_bcnt1_i32_b64 s7, s[12:13]", # must NOT return stale cached count OR ignore s13! - "v_cndmask_b32_e64 v4, 0, 1, s[12:13]", - "v_mov_b32_e32 v5, s6", - "v_mov_b32_e32 v6, s7", - "v_lshlrev_b32_e32 v7, 4, v0", - "buffer_store_dword v4, v7, s[0:3], 0 offen offset:0", - "buffer_store_dword v5, v7, s[0:3], 0 offen offset:4", - "buffer_store_dword v6, v7, s[0:3], 0 offen offset:8", - "s_endpgm", - ] - for emulate, sg_sz in ((False, 64), (True, 32)): - with self.subTest(emulate=emulate): - spv, _ = _translate_cs(f"cs_bug4_split_pair_{int(emulate)}", prog, threads=64, emulate=emulate) - lo, hi = 0x00000007, 0x000000FF # 3 bits in lo, 8 bits in hi -> total 11, after clear hi -> 3 - mem = run_compute_workgroup(spv, 64, sg_sz, push_constants=VSHARP + [lo, hi, 0, 0]) - for lane in range(64): - want_bit = ((lo >> lane) & 1) if lane < 32 else 0 - self.assertEqual((mem[16 * lane], mem[16 * lane + 4], mem[16 * lane + 8]), - (want_bit, 11, 3), f"emulate={emulate} lane={lane}") - - def test_bug4b_loop_carried_split_sgpr_pair_ballot(self): - """Loop-carried split SGPR pairs in wave64 (native and --wave64-emulate): - - s[12:13] accumulates iter==2 in s12 (lanes 0-31) and iter==3 in s13 (lanes 32-63) via 32-bit s_or_b32, - with s_bcnt1_i32_b64 before and after the s13 update in the same loop block (testing x_mcache invalidation - on s13 across loop iterations and distinct half masks in mask_src). - - s[20:21] updates ONLY s20 in the loop while s21 remains 0 (EITHER) on every path, testing holds_lane_mask - for (MASK_LO, EITHER) pairs after loop exit. - """ - prog = [ - "s_mov_b64 s[10:11], exec", - "v_and_b32_e32 v1, 3, v0", # limit = (lane & 3) + 1 (1..4) - "v_add_nc_u32_e32 v1, 1, v1", - "v_mov_b32_e32 v2, 0", # iter - "v_mov_b32_e32 v3, 0", # sum of (before_s13_cnt + after_s13_cnt) - "s_mov_b32 s12, 0", # lo half accumulator (lanes 0-31 hitting iter==2) - "s_mov_b32 s13, 0", # hi half accumulator (lanes 32-63 hitting iter==3) - "s_mov_b32 s20, 0", # lo-only accumulator (lanes 0-31 hitting iter==3) - "s_mov_b32 s21, 0", # stays constant 0 (EITHER) across the entire loop! - "loop:", - "v_add_nc_u32_e32 v2, 1, v2", - "v_cmp_eq_u32_e32 vcc, 2, v2", - "s_or_b32 s12, s12, vcc_lo", - "s_bcnt1_i32_b64 s6, s[12:13]", # caches s[12:13] in x_mcache before s13 changes - "v_cmp_eq_u32_e32 vcc, 3, v2", - "s_or_b32 s13, s13, vcc_hi", # modifies ONLY s13! - "s_or_b32 s20, s20, vcc_lo", # s[20:21] is (MASK_LO, EITHER) - "s_bcnt1_i32_b64 s7, s[12:13]", # must see updated s13 in the same block! - "s_add_u32 s6, s6, s7", - "v_add_nc_u32_e32 v3, s6, v3", - "v_cmp_lt_u32_e32 vcc, v2, v1", - "s_and_saveexec_b64 s[16:17], vcc", - "s_cbranch_execnz loop", - "s_mov_b64 exec, s[10:11]", - "s_bcnt1_i32_b64 s18, s[12:13]", - "s_bcnt1_i32_b64 s19, s[20:21]", - "v_cndmask_b32_e64 v4, 0, 1, s[12:13]", - "v_cndmask_b32_e64 v5, 0, 1, s[20:21]", - "v_lshlrev_b32_e32 v6, 16, v5", - "v_or_b32_e32 v4, v6, v4", - "v_mov_b32_e32 v7, s19", - "v_lshlrev_b32_e32 v7, 16, v7", - "v_or_b32_e32 v8, s18, v7", - "v_lshlrev_b32_e32 v9, 4, v0", - "buffer_store_dword v3, v9, s[0:3], 0 offen offset:0", - "buffer_store_dword v4, v9, s[0:3], 0 offen offset:4", - "buffer_store_dword v8, v9, s[0:3], 0 offen offset:8", - "s_endpgm", - ] - # Per iteration (1..4): - # iter 1: s12=0 (0 bits), s13=0 (0 bits) -> s6=0, s7=0 (sum 0) - # iter 2: lanes with lim>=2 ((lane&3)>=1: 24 in lo, 24 in hi) hit iter==2 -> s12 gets 24 bits; s13 still 0 -> s6=24, s7=24 (sum 48) - # iter 3: s12 stays 24 bits -> s6=24; lanes with lim>=3 ((lane&3)>=2: 16 in lo, 16 in hi) hit iter==3 -> s13 gets 16 bits, s20 gets 16 bits -> s7=40 (sum 64) - # iter 4: s12=24, s13=16 -> s6=40, s7=40 (sum 80) - iter_sums = [0, 48, 64, 80] - for emulate, sg_sz in ((False, 64), (True, 32)): - with self.subTest(emulate=emulate): - spv, _ = _translate_cs(f"cs_bug4b_loop_split_{int(emulate)}", prog, threads=64, emulate=emulate) - mem = run_compute_workgroup(spv, 64, sg_sz, push_constants=VSHARP) - for lane in range(64): - lim = (lane & 3) + 1 - want_v3 = sum(iter_sums[:lim]) - in_s12_13 = (lim >= 2) if lane < 32 else (lim >= 3) - in_s20_21 = (lim >= 3) if lane < 32 else False - want_v4 = (1 if in_s12_13 else 0) | ((1 if in_s20_21 else 0) << 16) - want_v8 = 40 | (16 << 16) - self.assertEqual( - (mem[16 * lane], mem[16 * lane + 4], mem[16 * lane + 8]), - (want_v3, want_v4, want_v8), - f"emulate={emulate} lane={lane}", - ) - - def test_bug5_v_mbcnt_respects_mask_half_in_wave64(self): - """`v_mbcnt_lo_u32_b32 v4, vcc_hi, 0` and `v_mbcnt_hi_u32_b32 v5, vcc_lo, 0` in wave64 must select - the known 32-bit half (vcc_hi / vcc_lo) rather than hardcoding lo->0 and hi->1. - """ - prog = _build_mask_from_s4_s5_w64() + [ - "v_mbcnt_lo_u32_b32 v4, vcc_hi, 0", - "v_mbcnt_hi_u32_b32 v5, vcc_lo, 0", - "v_lshlrev_b32_e32 v6, 3, v0", - "buffer_store_dword v4, v6, s[0:3], 0 offen offset:0", - "buffer_store_dword v5, v6, s[0:3], 0 offen offset:4", - "s_endpgm", - ] - lo, hi = 0x000000A5, 0x0000000F # vcc_lo=0xA5 (4 bits), vcc_hi=0x0F (bits 0..3 set) - for emulate, sg_sz in ((False, 64), (True, 32)): - with self.subTest(emulate=emulate): - spv, _ = _translate_cs(f"cs_bug5_mbcnt_half_{int(emulate)}", prog, threads=64, emulate=emulate) - mem = run_compute_workgroup(spv, 64, sg_sz, push_constants=VSHARP + [lo, hi, 0, 0]) - for lane in range(64): - want_lo = bin(hi & ((1 << min(lane, 32)) - 1)).count("1") - want_hi = 0 if lane < 32 else bin(lo & ((1 << (lane - 32)) - 1)).count("1") - self.assertEqual((mem[8 * lane], mem[8 * lane + 4]), (want_lo, want_hi), - f"emulate={emulate} lane={lane}") - - -# --------------------------------------------------------------------------- -# 3. Barriers inside loops (uniform & wave-divergent) across all modes -# --------------------------------------------------------------------------- - -class BarrierInLoopsTests(unittest.TestCase): - """Audit Hazard 2: s_barrier inside loops with LDS exchange across wave32, wave64, emulate, bar_rounds.""" - - def _ring_shift_loop_cs(self, wave64, threads, iters=5): - """Group-uniform loop with TWO s_barriers per iteration performing `iters` ring shifts in LDS: - each iteration thread t writes val -> lds[t], s_barrier, reads lds[(t + 1) % threads], s_barrier. - After `iters` iterations, thread t holds initial((t + iters) % threads) + iters * 100. - """ - mask = threads - 1 # threads is power of 2 (64 or 128) - pro = ["s_mov_b64 s[10:11], exec"] if wave64 else [] - return pro + [ - "v_add_nc_u32_e32 v1, 1000, v0", # initial value = 1000 + tid - "v_lshlrev_b32_e32 v2, 2, v0", # my_lds_addr = tid * 4 - "v_add_nc_u32_e32 v3, 1, v0", - f"v_and_b32_e32 v3, {mask}, v3", - "v_lshlrev_b32_e32 v3, 2, v3", # next_lds_addr = ((tid + 1) % threads) * 4 - "s_mov_b32 s8, 0", # uniform loop counter - "loop:", - "ds_write_b32 v2, v1", - "s_waitcnt lgkmcnt(0)", - "s_barrier", - "ds_read_b32 v1, v3", - "s_waitcnt lgkmcnt(0)", - "v_add_nc_u32_e32 v1, 100, v1", - "s_barrier", - "s_add_u32 s8, s8, 1", - f"s_cmp_lt_u32 s8, {iters}", - "s_cbranch_scc1 loop", - "buffer_store_dword v1, v2, s[0:3], 0 offen", - "s_endpgm", - ] - - def test_uniform_loop_barrier_wave32_bar_rounds(self): - """Native wave32 CS (64 threads = 2 waves) with s_barrier in a group-uniform loop (5 iters = 10 barriers): - uses bar_scheduler ('barrier rounds'), survives mod-3 ring wraparound & reversed wave schedule. - """ - prog = self._ring_shift_loop_cs(wave64=False, threads=64, iters=5) - spv, gen = _translate_cs("cs_bar_loop_w32", prog, threads=64, lds_bytes=256, emulate=False) - self.assertTrue(gen.bar_rounds) - self.assertEqual(gen.control_flow, "barrier rounds") - for rev in (False, True): - with self.subTest(reverse_subgroups=rev): - mem = run_compute_workgroup(spv, 64, 32, push_constants=VSHARP, reverse_subgroups=rev) - want = [1000 + ((t + 5) % 64) + 500 for t in range(64)] - self.assertEqual([mem.get(4 * t, -1) for t in range(64)], want) - - def test_uniform_loop_barrier_wave64_native_structured(self): - """Native wave64 CS (128 threads = 2 waves) with s_barrier in a group-uniform loop: - stays in structured OpLoopMerge with direct OpControlBarrier and works cleanly. - """ - prog = self._ring_shift_loop_cs(wave64=True, threads=128, iters=5) - spv, gen = _translate_cs("cs_bar_loop_w64_native", prog, threads=128, lds_bytes=512, emulate=False) - self.assertFalse(gen.bar_rounds) - self.assertEqual(gen.control_flow, "structured") - for rev in (False, True): - with self.subTest(reverse_subgroups=rev): - mem = run_compute_workgroup(spv, 128, 64, push_constants=VSHARP, reverse_subgroups=rev) - want = [1000 + ((t + 5) % 128) + 500 for t in range(128)] - self.assertEqual([mem.get(4 * t, -1) for t in range(128)], want) - - def test_uniform_loop_barrier_wave64_emulate(self): - """--wave64-emulate CS (128 threads = 2 emulated waves on 4 subgroups of 32) with s_barrier - in a group-uniform loop (5 iters = 10 barriers): x_scheduler keeps all waves synchronized. - """ - prog = self._ring_shift_loop_cs(wave64=True, threads=128, iters=5) - spv, gen = _translate_cs("cs_bar_loop_w64_emulate", prog, threads=128, lds_bytes=512, emulate=True) - self.assertEqual(gen.control_flow, "emulated wave64 rounds") - for rev in (False, True): - with self.subTest(reverse_subgroups=rev): - mem = run_compute_workgroup(spv, 128, 32, push_constants=VSHARP, reverse_subgroups=rev) - want = [1000 + ((t + 5) % 128) + 500 for t in range(128)] - self.assertEqual([mem.get(4 * t, -1) for t in range(128)], want) - - def _wave_divergent_barrier_loop_cs(self, wave64): - """Wave 0 runs 2 iterations of a barrier loop and exits via s_endpgm; wave 1 runs 4 iterations. - On RDNA2, wave 0 exiting releases wave 1's remaining s_barriers cleanly. - """ - if wave64: - return [ - "s_mov_b64 s[10:11], exec", - "v_lshrrev_b32_e32 v1, 6, v0", - "v_readfirstlane_b32 s8, v1", # wave_id (0 or 1) - "s_lshl_b32 s9, s8, 1", # 0 or 2 - "s_add_u32 s9, s9, 2", # trip count: wave 0 -> 2, wave 1 -> 4 - "s_mov_b32 s12, 0", - "v_lshlrev_b32_e32 v2, 2, v0", - "v_mov_b32_e32 v3, 0", - "loop:", - "ds_write_b32 v2, v3", - "s_waitcnt lgkmcnt(0)", - "s_barrier", - "ds_read_b32 v4, v2", - "s_waitcnt lgkmcnt(0)", - "v_add_nc_u32_e32 v3, 1, v4", - "s_add_u32 s12, s12, 1", - "s_cmp_lt_u32 s12, s9", - "s_cbranch_scc1 loop", - "buffer_store_dword v3, v2, s[0:3], 0 offen", - "s_endpgm", - ] - return [ - "v_lshrrev_b32_e32 v1, 5, v0", - "v_readfirstlane_b32 s8, v1", - "s_lshl_b32 s9, s8, 1", - "s_add_u32 s9, s9, 2", # wave 0 -> 2 iters, wave 1 -> 4 iters - "s_mov_b32 s12, 0", - "v_lshlrev_b32_e32 v2, 2, v0", - "v_mov_b32_e32 v3, 0", - "loop:", - "ds_write_b32 v2, v3", - "s_waitcnt lgkmcnt(0)", - "s_barrier", - "ds_read_b32 v4, v2", - "s_waitcnt lgkmcnt(0)", - "v_add_nc_u32_e32 v3, 1, v4", - "s_add_u32 s12, s12, 1", - "s_cmp_lt_u32 s12, s9", - "s_cbranch_scc1 loop", - "buffer_store_dword v3, v2, s[0:3], 0 offen", - "s_endpgm", - ] - - def test_wave_divergent_barrier_loop_bar_rounds_and_emulate(self): - """Wave-divergent barrier loop (wave 0 runs 2 iters and exits, wave 1 runs 4 iters): - - native wave32 CS (bar_rounds): passes cleanly with uniform outer OpControlBarrier! - - --wave64-emulate CS (x_scheduler): passes cleanly with uniform outer OpControlBarrier! - - native wave64 CS (emulate=False): direct OpControlBarrier inside structured loop hits - NonUniformBarrierError (documented AMD-only native-wave64 limitation; non-AMD uses emulate). - """ - spv_w32, gen_w32 = _translate_cs( - "cs_div_bar_w32", self._wave_divergent_barrier_loop_cs(False), threads=64, lds_bytes=256, emulate=False - ) - self.assertTrue(gen_w32.bar_rounds) - mem32 = run_compute_workgroup(spv_w32, 64, 32, push_constants=VSHARP) - self.assertEqual([mem32[4 * t] for t in range(64)], [2] * 32 + [4] * 32) - - spv_em, gen_em = _translate_cs( - "cs_div_bar_em", self._wave_divergent_barrier_loop_cs(True), threads=128, lds_bytes=512, emulate=True - ) - self.assertEqual(gen_em.control_flow, "emulated wave64 rounds") - mem_em = run_compute_workgroup(spv_em, 128, 32, push_constants=VSHARP) - self.assertEqual([mem_em[4 * t] for t in range(128)], [2] * 64 + [4] * 64) - - spv_nat64, gen_nat64 = _translate_cs( - "cs_div_bar_nat64", self._wave_divergent_barrier_loop_cs(True), threads=128, lds_bytes=512, emulate=False - ) - self.assertEqual(gen_nat64.control_flow, "structured") - with self.assertRaises(NonUniformBarrierError): - run_compute_workgroup(spv_nat64, 128, 64, push_constants=VSHARP) - - def test_combined_barrier_and_divergent_ballot_in_same_loop(self): - """Group-uniform loop containing BOTH s_barrier + LDS exchange AND divergent lane-level - s_and_saveexec + s_bcnt1, tested across wave32 (bar_rounds), native wave64, and --wave64-emulate. - """ - def make_prog(wave64): - if wave64: - return [ - "s_mov_b64 s[10:11], exec", - "v_lshlrev_b32_e32 v2, 2, v0", - "v_mov_b32_e32 v1, v0", - "s_mov_b32 s8, 0", - "loop:", - "ds_write_b32 v2, v1", - "s_waitcnt lgkmcnt(0)", - "s_barrier", - "v_and_b32_e32 v3, 3, v0", - "v_cmp_ge_u32_e32 vcc, v3, s8", - "s_and_saveexec_b64 s[12:13], vcc", - "s_bcnt1_i32_b64 s6, exec", - "v_xor_b32_e32 v4, 1, v0", - "v_lshlrev_b32_e32 v4, 2, v4", - "ds_read_b32 v5, v4", - "s_waitcnt lgkmcnt(0)", - "v_add_nc_u32_e32 v1, v5, s6", - "s_mov_b64 exec, s[12:13]", - "s_barrier", - "s_add_u32 s8, s8, 1", - "s_cmp_lt_u32 s8, 4", - "s_cbranch_scc1 loop", - "buffer_store_dword v1, v2, s[0:3], 0 offen", - "s_endpgm", - ] - return [ - "s_mov_b32 s10, exec_lo", - "v_lshlrev_b32_e32 v2, 2, v0", - "v_mov_b32_e32 v1, v0", - "s_mov_b32 s8, 0", - "loop:", - "ds_write_b32 v2, v1", - "s_waitcnt lgkmcnt(0)", - "s_barrier", - "v_and_b32_e32 v3, 3, v0", - "v_cmp_ge_u32_e32 vcc_lo, v3, s8", - "s_and_saveexec_b32 s12, vcc_lo", - "s_bcnt1_i32_b32 s6, exec_lo", - "v_xor_b32_e32 v4, 1, v0", - "v_lshlrev_b32_e32 v4, 2, v4", - "ds_read_b32 v5, v4", - "s_waitcnt lgkmcnt(0)", - "v_add_nc_u32_e32 v1, v5, s6", - "s_mov_b32 exec_lo, s12", - "s_barrier", - "s_add_u32 s8, s8, 1", - "s_cmp_lt_u32 s8, 4", - "s_cbranch_scc1 loop", - "buffer_store_dword v1, v2, s[0:3], 0 offen", - "s_endpgm", - ] - - def oracle(threads, wave_size): - v1 = list(range(threads)) - for s8 in range(4): - lds = list(v1) - nxt = list(v1) - for wbase in range(0, threads, wave_size): - active = [t for t in range(wbase, wbase + wave_size) if (t & 3) >= s8] - cnt = len(active) - for t in active: - nxt[t] = (lds[t ^ 1] + cnt) & M32 - v1 = nxt - return v1 - - for label, wave64, threads, sg_sz, emulate in ( - ("w32_bar_rounds", False, 64, 32, False), - ("w64_native", True, 128, 64, False), - ("w64_emulate", True, 128, 32, True), - ): - with self.subTest(mode=label): - spv, _ = _translate_cs("cs_combo_" + label, make_prog(wave64), - threads=threads, lds_bytes=threads * 4, emulate=emulate) - mem = run_compute_workgroup(spv, threads, sg_sz, push_constants=VSHARP) - self.assertEqual([mem[4 * t] for t in range(threads)], oracle(threads, 64 if wave64 else 32)) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_mask_src_sgpr_const.py b/tests/semantic/test_mask_src_sgpr_const.py deleted file mode 100644 index ddeaff21f..000000000 --- a/tests/semantic/test_mask_src_sgpr_const.py +++ /dev/null @@ -1,114 +0,0 @@ -"""A constant lane mask that reaches a mask consumer through an SGPR: lane L takes bit L of the constant. - -`s_mov_b32 s20, 0x3ffffc00; s_and_saveexec_b32 s6, s20` leaves lanes 10..29 active on hardware. Gen.mask_src read the -SGPR's raw value, which is the same non-zero constant in every invocation, so every lane stayed on (found writing -#1771's GPU test; the immediate form `s_and_saveexec_b32 s6, 0x3ffffc00` was already right). Each case runs a -translated pixel shader in tests/semantic/spirv_wave_interp.py as one wave and compares every lane with the -immediate form and with the bits of the constant. Masks built by compares still work (they hold 0 / ~0 per lane). -Standard library only; no GPU, no game files. -""" -import os -import sys -import unittest - -HERE = os.path.dirname(os.path.abspath(__file__)) -sys.dont_write_bytecode = True -sys.path.insert(0, HERE) - -from test_salu64_bitwise_data import run_ps_wave # noqa: E402 (also puts tools/ on sys.path) - -EPILOGUE = ["v_mov_b32 v0, 0", "v_mov_b32 v2, 0", "v_mov_b32 v3, 0"] - - -def active_lanes(lines, wave): - """Lanes whose v1 ends as 0x22: the ones the mask under test left active.""" - outs, _ = run_ps_wave(["v_mov_b32 v1, 0x11"] + lines + ["v_mov_b32 v1, 0x22", f"s_mov_b{wave} exec, -1"] + - EPILOGUE, wave=wave) - return [lane for lane in range(wave) if outs[lane][1] == 0x22] - - -def bits(v, wave): - return [lane for lane in range(wave) if v >> lane & 1] - - -class SgprConstantMask(unittest.TestCase): - def test_saveexec_wave32(self): - for c in (0x3FFFFC00, 0x00000001, 0x80000000, 0x0000FF00, 0x55555555): - with self.subTest(c=hex(c)): - via_sgpr = active_lanes([f"s_mov_b32 s20, {c:#x}", "s_and_saveexec_b32 s6, s20"], 32) - via_imm = active_lanes([f"s_and_saveexec_b32 s6, {c:#x}"], 32) - self.assertEqual(via_sgpr, bits(c, 32)) - self.assertEqual(via_sgpr, via_imm) - - def test_exec_write_and_cndmask(self): - c = 0x0F0F00FF - self.assertEqual(active_lanes([f"s_mov_b32 s20, {c:#x}", "s_and_b32 exec_lo, exec_lo, s20"], 32), bits(c, 32)) - outs, _ = run_ps_wave([f"s_mov_b32 s20, {c:#x}", "v_cndmask_b32_e64 v1, 0, 1, s20"] + EPILOGUE, wave=32) - self.assertEqual([lane for lane in range(32) if outs[lane][1] == 1], bits(c, 32)) - - def test_sop2_with_a_constant_and_exec(self): - # 32-bit bitwise SOP2 on EXEC with a constant, inline or in an SGPR (both were taken whole before). - c, full = 0x0F0F00FF, 0xFFFFFFFF # EXEC starts with every lane on - for kind, want in (("and", full & c), ("andn2", full & ~c), ("or", full | c), ("xor", full ^ c)): - for src in (f"{c:#x}", "s20"): - with self.subTest(op=kind, src=src): - lines = [f"s_mov_b32 s20, {c:#x}", f"s_{kind}_b32 exec_lo, exec_lo, {src}"] - self.assertEqual(active_lanes(lines, 32), bits(want & full, 32)) - - def test_exec_lo_from_an_sgpr_constant(self): - c = 0x00FF00F0 - self.assertEqual(active_lanes([f"s_mov_b32 s20, {c:#x}", "s_mov_b32 exec_lo, s20"], 32), bits(c, 32)) - - def test_wave64_pair_takes_each_half_from_its_own_sgpr(self): - lo, hi = 0x0000FFFF, 0xF0000000 - lanes = active_lanes([f"s_mov_b32 s20, {lo:#x}", f"s_mov_b32 s21, {hi:#x}", - "s_and_saveexec_b64 s[6:7], s[20:21]"], 64) - self.assertEqual(lanes, bits(lo | hi << 32, 64)) - - def test_masks_from_compares_still_work(self): - lines = ["v_mbcnt_lo_u32_b32 v4, -1, 0", "v_cmp_gt_u32_e64 s20, 12, v4", "s_and_saveexec_b32 s6, s20"] - self.assertEqual(active_lanes(lines, 32), list(range(12))) - lines = ["v_mbcnt_lo_u32_b32 v4, -1, 0", "v_mbcnt_hi_u32_b32 v4, -1, v4", "v_cmp_lt_u32_e64 s[20:21], 40, v4", - "s_and_saveexec_b64 s[6:7], s[20:21]"] - self.assertEqual(active_lanes(lines, 64), list(range(41, 64))) - - -class MaskAndConstantIntoAnSgpr(unittest.TestCase): - """@Pierre-Kookis's case on #1792 (GPU-reproduced on AMD RDNA2 and an RTX 4070 Ti SUPER): an SOP2 of EXEC with a - constant into a plain SGPR is data, and s_bcnt1 counts the wave's bits. The first version of this fix put each - lane's bit there and got 32 / 0 instead of 1 / 8.""" - - def test_s_and_of_exec_with_a_constant_counts_the_wave_bits(self): - import struct - import tempfile - import warnings - import spirv_mini_interp as si - from support import STUB_DXBC, rdna2spirv - lines = ["s_and_b32 s20, exec_lo, 1", "s_bcnt1_i32_b32 s21, s20", "s_and_b32 s22, exec_lo, 0xff00", - "s_bcnt1_i32_b32 s23, s22", "v_lshlrev_b32 v3, 3, v0", "v_mov_b32_e32 v1, s21", - "buffer_store_dword v1, v3, s[0:3], 0 offen", "v_add_nc_u32 v3, 4, v3", "v_mov_b32_e32 v1, s23", - "buffer_store_dword v1, v3, s[0:3], 0 offen", "s_endpgm"] - with tempfile.TemporaryDirectory() as tmp: - os.mkdir(os.path.join(tmp, "disasm")) - os.mkdir(os.path.join(tmp, "fssm")) - with open(os.path.join(tmp, "cs_bcnt.dxbc"), "wb") as f: - f.write(STUB_DXBC) - hdr = bytearray(0x148) - struct.pack_into("<4I", hdr, 0x138, 0x88, 32, 1, 1) - with open(os.path.join(tmp, "fssm", "cs_bcnt.fssm"), "wb") as f: - f.write(hdr) - src = os.path.join(tmp, "disasm", "cs_bcnt.s") - with open(src, "w", encoding="utf-8") as f: - f.write("; cs_bcnt\n" + "".join(f"\t{ln}\n" for ln in lines)) - with warnings.catch_warnings(): - warnings.simplefilter("ignore", ResourceWarning) - spv = rdna2spirv.translate(src) - mem = si.run_workgroup(spv, 32, 32, inputs_for=lambda i: {"%wg_id": (0, 0, 0), "%local_id": (i, 0, 0), - "%sg_lane": i}, - push_constants=[0, 0, 0x1000, 0x31016FAC] + [0] * 28, memory={}) - for lane in range(32): - self.assertEqual((mem[8 * lane], mem[8 * lane + 4]), (1, 8), f"lane {lane}") - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_material_handle.py b/tests/semantic/test_material_handle.py deleted file mode 100644 index 877587276..000000000 --- a/tests/semantic/test_material_handle.py +++ /dev/null @@ -1,56 +0,0 @@ -"""Regression fixture for a per-draw handle word selecting an eight-word image descriptor.""" -import unittest - -from spirv_mini_interp import run_fragment -from support import translate_lines - - -class MaterialHandleTests(unittest.TestCase): - @classmethod - def setUpClass(cls): - # s0:s1 points to the root table, s2:s3 to the image heap, and s4 is - # a byte offset into the raw buffer. Export descriptor words as markers. - body = [ - "s_load_dwordx4 s[16:19], s[0:1], 0x40", - "s_waitcnt lgkmcnt(0)", - "s_add_u32 s7, s4, 8", - "s_buffer_load_dword s8, s[16:19], s7", - "s_waitcnt lgkmcnt(0)", - "s_lshl_b32 s9, s8, 5", - "s_load_dwordx8 s[24:31], s[2:3], s9", - "s_waitcnt lgkmcnt(0)", - ] - body += [f"v_mov_b32_e32 v{i}, s{24+i}" for i in range(8)] - body += ["exp mrt0 v0, v1, v2, v3", "exp mrt1 v4, v5, v6, v7 done vm", "s_endpgm"] - cls.shader = translate_lines("ps_material_handle", body) - - def test_effect_word_selects_descriptor_for_each_draw(self): - root, raw, heap = 0x1000, 0x2000, 0x3000 - # Build two material blocks from the same authored rows. One extra - # drawable-only parameter shifts the normal map from raw row 3 to effect word 2. - effect = ("paint", "detail", "normal") - authored = (("paint", 2), ("extra", 4), ("detail", 6), ("normal", 9)) - handles = dict(authored) - memory = {} - for i, word in enumerate((raw, 0, 128, 0)): - memory[root + 0x40 + i * 4] = word - descriptors = {} - for handle in handles.values(): - descriptors[handle] = tuple(0x3f000000 + 0x100 * handle + i for i in range(8)) - for i, word in enumerate(descriptors[handle]): - memory[heap + 32 * handle + 4 * i] = word - - for base, layout, expected_handle in ( - (0x14, effect, 9), - (0x38, tuple(handles), 6), - ): - with self.subTest(draw_base=base, layout=layout): - for i, name in enumerate(layout): - memory[raw + base + i * 4] = handles[name] - out = run_fragment(self.shader, push_constants=[root, 0, heap, 0, base], memory=memory) - words = tuple(out["%out_mrt0"]) + tuple(out["%out_mrt1"]) - self.assertEqual(words, descriptors[expected_handle]) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_mbcnt_lo_hi.py b/tests/semantic/test_mbcnt_lo_hi.py deleted file mode 100644 index 393c99ac9..000000000 --- a/tests/semantic/test_mbcnt_lo_hi.py +++ /dev/null @@ -1,622 +0,0 @@ -"""Semantic interpreter tests for AMD RDNA masked bit count instructions: - - v_mbcnt_lo_u32_b32: D.u32 = BitCount(S0.u32 & ((1 << lane) - 1)) + S1.u32 - - v_mbcnt_hi_u32_b32: - D.u32 = BitCount(S0.u32 & ((1 << (lane - 32)) - 1)) + S1.u32 - -Validates thread rank in wave (Wave32 and Wave64), stream compaction, -active-lane prefix scanning, accumulator addition wrapping, boundary -conditions at lane 0 / 31 / 32 / 63, and SPIR-V translation / execution. -Standard library only; zero game data. -""" -from __future__ import annotations - -import ctypes -import os -import struct -import sys -import tempfile -import unittest -import warnings - -# Polyfill int.bit_count for Python 3.9 so spirv_mini_interp can run OpBitCount -if not hasattr(int, "bit_count"): - try: - _mp = int.__dict__ - _dict_addr = ctypes.c_void_p.from_address(id(_mp) + 16).value - ctypes.pythonapi.PyDict_SetItemString( - ctypes.c_void_p(_dict_addr), - b"bit_count", - ctypes.py_object(lambda self: bin(self).count("1")), - ) - ctypes.pythonapi.PyType_Modified(ctypes.py_object(int)) - except Exception: - pass - -HERE = os.path.dirname(os.path.abspath(__file__)) -ROOT = os.path.dirname(os.path.dirname(HERE)) -TOOLS_DIR = os.environ.get("LEONIDA_TOOLS_DIR") or os.path.join(ROOT, "tools") - -if ROOT not in sys.path: - sys.path.insert(0, ROOT) -if TOOLS_DIR not in sys.path: - sys.path.insert(0, TOOLS_DIR) -if HERE not in sys.path: - sys.path.insert(0, HERE) - -import rdna2spirv # noqa: E402 -import spirv_mini_interp as si # noqa: E402 - -MASK32 = 0xFFFFFFFF -MASK64 = 0xFFFFFFFFFFFFFFFF -STUB_DXBC = b"DXBC" + bytes(24) + struct.pack(" int: - """Deterministic population count for unsigned integers.""" - return bin(x).count("1") - - -def ref_mbcnt_lo(lane: int, mask_lo: int, acc: int = 0) -> int: - """Reference oracle for v_mbcnt_lo_u32_b32. - - Counts set bits in mask_lo for lanes strictly below this lane (0..31). - For lane < 32: active bits are mask_lo & ((1 << lane) - 1). - For lane >= 32: all 32 bits of the low half are below this lane, so active - bits are mask_lo & 0xFFFFFFFF. - The bit count is added to acc with 32-bit unsigned wrapping. - """ - lane &= 0x3F # bounded to 6-bit wave lane (0..63) - mask_lo &= MASK32 - acc &= MASK32 - if lane < 32: - bitmask = (1 << lane) - 1 - else: - bitmask = MASK32 - cnt = popcount(mask_lo & bitmask) - return (cnt + acc) & MASK32 - - -def ref_mbcnt_hi(lane: int, mask_hi: int, acc: int = 0) -> int: - """Reference oracle for v_mbcnt_hi_u32_b32. - - Counts set bits in mask_hi for high-half lanes strictly below (32..63). - For lane < 32: there are no high-half lanes below this lane (count 0). - For lane >= 32: rel = lane - 32; active bits are: - mask_hi & ((1 << rel) - 1). - The bit count is added to acc with 32-bit unsigned wrapping. - """ - lane &= 0x3F # bounded to 6-bit wave lane (0..63) - mask_hi &= MASK32 - acc &= MASK32 - if lane < 32: - bitmask = 0 - else: - rel = lane - 32 - bitmask = (1 << rel) - 1 if rel < 32 else MASK32 - cnt = popcount(mask_hi & bitmask) - return (cnt + acc) & MASK32 - - -def ref_thread_rank_wave32( - lane: int, mask_lo: int = MASK32, base: int = 0 -) -> int: - """Computes thread rank in a 32-lane wave using v_mbcnt_lo.""" - return ref_mbcnt_lo(lane, mask_lo, base) - - -def ref_thread_rank_wave64( - lane: int, - mask_lo: int = MASK32, - mask_hi: int = MASK32, - base: int = 0, -) -> int: - """Computes thread rank in a 64-lane wave using paired lo/hi v_mbcnt.""" - lo_rank = ref_mbcnt_lo(lane, mask_lo, base) - return ref_mbcnt_hi(lane, mask_hi, lo_rank) - - -def ref_active_compaction( - active_lanes: set[int] | list[int], wave_size: int = 64 -) -> list[int]: - """Computes compacted rank for all lanes under a given active set.""" - active_set = set(active_lanes) - mask64 = 0 - for lane_idx in active_set: - if 0 <= lane_idx < wave_size: - mask64 |= 1 << lane_idx - mask_lo = mask64 & MASK32 - mask_hi = (mask64 >> 32) & MASK32 - - ranks = [] - for lane in range(wave_size): - if wave_size == 32: - ranks.append(ref_thread_rank_wave32(lane, mask_lo)) - else: - ranks.append(ref_thread_rank_wave64(lane, mask_lo, mask_hi)) - return ranks - - -# ----------------------------------------------------------------------------- -# 2. Multi-Lane SIMD Wave Interpreter -# ----------------------------------------------------------------------------- - -class SimdWave: - """Simulates an AMD RDNA SIMD wave executing vector mbcnt sequences.""" - - def __init__(self, wave_size: int = 64, exec_mask: int = MASK64): - if wave_size not in (32, 64): - raise ValueError("wave_size must be 32 or 64") - self.wave_size = wave_size - self.exec_mask = exec_mask & ((1 << wave_size) - 1) - self.vgprs = [[0] * 256 for _ in range(wave_size)] - self.sgprs = [0] * 128 - - def run_v_mbcnt_lo( - self, dst: int, src0_mask: int, src1_acc: int | list[int] - ): - """Executes v_mbcnt_lo_u32_b32 across all active lanes.""" - for lane in range(self.wave_size): - if (self.exec_mask >> lane) & 1: - acc = ( - src1_acc[lane] - if isinstance(src1_acc, list) - else src1_acc - ) - self.vgprs[lane][dst] = ref_mbcnt_lo(lane, src0_mask, acc) - - def run_v_mbcnt_hi( - self, dst: int, src0_mask: int, src1_acc: int | list[int] - ): - """Executes v_mbcnt_hi_u32_b32 across all active lanes.""" - for lane in range(self.wave_size): - if (self.exec_mask >> lane) & 1: - acc = ( - src1_acc[lane] - if isinstance(src1_acc, list) - else src1_acc - ) - self.vgprs[lane][dst] = ref_mbcnt_hi(lane, src0_mask, acc) - - def compute_thread_ranks( - self, dst: int = 0, mask_lo: int = MASK32, mask_hi: int = MASK32 - ): - """Executes the standard hardware thread-rank sequence into VGPR.""" - self.run_v_mbcnt_lo(dst, mask_lo, 0) - if self.wave_size == 64: - acc_list = [self.vgprs[ln][dst] for ln in range(self.wave_size)] - self.run_v_mbcnt_hi(dst, mask_hi, acc_list) - - -# ----------------------------------------------------------------------------- -# 3. Unit Tests: Pure Reference Semantics and Edge Cases -# ----------------------------------------------------------------------------- - -class TestMbcntReferenceSemantics(unittest.TestCase): - """Exhaustive validation of reference mathematical semantics.""" - - def test_wave32_all_lanes_identity(self): - """When mask is -1, lanes 0..31 compute their own lane index.""" - for lane in range(32): - with self.subTest(lane=lane): - rank = ref_thread_rank_wave32(lane, MASK32, 0) - self.assertEqual(rank, lane) - - def test_wave64_all_lanes_identity(self): - """When mask is -1, lanes 0..63 compute their own lane index.""" - for lane in range(64): - with self.subTest(lane=lane): - rank = ref_thread_rank_wave64(lane, MASK32, MASK32, 0) - self.assertEqual(rank, lane) - - def test_lane_zero_always_zero_count(self): - """Lane 0 has no lower lanes; count is 0 regardless of mask.""" - masks = [0, 1, 0xFFFFFFFF, 0x55555555, 0xAAAAAAAA, 0x80000000] - for m in masks: - with self.subTest(mask=hex(m)): - self.assertEqual(ref_mbcnt_lo(0, m, 0), 0) - self.assertEqual(ref_mbcnt_hi(0, m, 0), 0) - self.assertEqual(ref_mbcnt_lo(0, m, 42), 42) - self.assertEqual(ref_mbcnt_hi(0, m, 42), 42) - - def test_cross_half_boundary_lane31_and_32(self): - """Tests boundary semantics between halves (lanes 31 and 32).""" - # Lane 31 in Wave64 with full mask - lo_31 = ref_mbcnt_lo(31, MASK32, 0) - hi_31 = ref_mbcnt_hi(31, MASK32, lo_31) - self.assertEqual(lo_31, 31) - self.assertEqual(hi_31, 31) - - # Lane 32: lo counts all 32 low bits; hi has rel=0, so hi adds 0 - lo_32 = ref_mbcnt_lo(32, MASK32, 0) - hi_32 = ref_mbcnt_hi(32, MASK32, lo_32) - self.assertEqual(lo_32, 32) - self.assertEqual(hi_32, 32) - - def test_lane63_top_boundary(self): - """Lane 63: lo counts 32 bits, hi counts 31 bits; total is 63.""" - lo_63 = ref_mbcnt_lo(63, MASK32, 0) - hi_63 = ref_mbcnt_hi(63, MASK32, lo_63) - self.assertEqual(lo_63, 32) - self.assertEqual(hi_63, 63) - - def test_accumulator_addition_and_overflow_wrap(self): - """Accumulator addition wraps modulo 2^32.""" - self.assertEqual(ref_mbcnt_lo(5, MASK32, 100), 105) - # (1 + 0xFFFFFFFF) wraps to 0 - self.assertEqual(ref_mbcnt_lo(1, MASK32, MASK32), 0) - self.assertEqual(ref_mbcnt_hi(33, MASK32, MASK32), 0) - self.assertEqual(ref_mbcnt_lo(10, MASK32, 0xFFFFFFF8), 2) - - def test_zero_mask_returns_accumulator(self): - """Zero mask has no set bits; result is strictly equal to acc.""" - for lane in range(64): - self.assertEqual(ref_mbcnt_lo(lane, 0, 77), 77) - self.assertEqual(ref_mbcnt_hi(lane, 0, 88), 88) - - def test_single_active_bit_boundary(self): - """A mask with a single bit set at position k.""" - for k in (0, 1, 15, 30, 31): - mask = 1 << k - for lane in range(32): - expected = 1 if lane > k else 0 - got = ref_mbcnt_lo(lane, mask, 0) - self.assertEqual( - got, expected, f"Failed at k={k}, lane={lane}" - ) - - def test_sparse_active_compaction(self): - """Stream compaction matches the index within active lanes.""" - active = [3, 8, 19, 32, 45, 60] - ranks = ref_active_compaction(active, wave_size=64) - for expected_rank, lane in enumerate(active): - self.assertEqual(ranks[lane], expected_rank) - - # Inactive lanes strictly maintain prefix sum count - self.assertEqual(ranks[0], 0) - self.assertEqual(ranks[4], 1) - self.assertEqual(ranks[20], 3) - self.assertEqual(ranks[33], 4) - self.assertEqual(ranks[63], 6) - - def test_even_and_odd_alternating_masks(self): - """Tests even (0x55555555) and odd (0xAAAAAAAA) alternating masks.""" - even_mask = 0x55555555 - odd_mask = 0xAAAAAAAA - - for t in range(32): - self.assertEqual(ref_mbcnt_lo(t, even_mask, 0), (t + 1) // 2) - self.assertEqual(ref_mbcnt_lo(t, odd_mask, 0), t // 2) - - def test_duality_partition_property(self): - """Duality: popcnt(mask & below) + popcnt(~mask & below) == lane.""" - for lane in range(64): - for mask in (0x12345678, 0xDEADBEEF, 0x00FF00FF, 0x55555555): - inv_mask = (~mask) & MASK32 - if lane < 32: - cnt_1 = ref_mbcnt_lo(lane, mask, 0) - cnt_0 = ref_mbcnt_lo(lane, inv_mask, 0) - self.assertEqual(cnt_1 + cnt_0, lane) - else: - rel = lane - 32 - cnt_1 = ref_mbcnt_hi(lane, mask, 0) - cnt_0 = ref_mbcnt_hi(lane, inv_mask, 0) - self.assertEqual(cnt_1 + cnt_0, rel) - - def test_monotonicity(self): - """Thread rank is monotonically non-decreasing with lane index.""" - for mask_lo in (0xAAAAAAAA, 0x0F0F0F0F, 0x80000001): - for mask_hi in (0x55555555, 0xF0F0F0F0, 0x00000001): - prev = -1 - for lane in range(64): - cur = ref_thread_rank_wave64(lane, mask_lo, mask_hi, 0) - self.assertGreaterEqual(cur, prev) - if prev != -1: - diff = cur - prev - self.assertIn(diff, (0, 1)) - prev = cur - - -# ----------------------------------------------------------------------------- -# 4. Multi-Lane SIMD Wave Simulation Tests -# ----------------------------------------------------------------------------- - -class TestSimdWaveInterpreter(unittest.TestCase): - """Tests executing sequence through multi-lane SIMD wave interpreter.""" - - def test_wave32_full_exec_thread_rank(self): - wave = SimdWave(wave_size=32, exec_mask=MASK32) - wave.compute_thread_ranks(dst=5) - for lane in range(32): - self.assertEqual(wave.vgprs[lane][5], lane) - - def test_wave64_full_exec_thread_rank(self): - wave = SimdWave(wave_size=64, exec_mask=MASK64) - wave.compute_thread_ranks(dst=3) - for lane in range(64): - self.assertEqual(wave.vgprs[lane][3], lane) - - def test_inactive_lanes_preserve_vgpr(self): - """Lanes masked off by EXEC do not write destination VGPR.""" - exec_mask = (1 << 16) - 1 - wave = SimdWave(wave_size=64, exec_mask=exec_mask) - for lane in range(64): - wave.vgprs[lane][2] = 0xDEADBEEF - - wave.compute_thread_ranks(dst=2) - for lane in range(16): - self.assertEqual(wave.vgprs[lane][2], lane) - for lane in range(16, 64): - self.assertEqual(wave.vgprs[lane][2], 0xDEADBEEF) - - def test_compaction_with_simulated_ballot(self): - """Ballot condition followed by v_mbcnt compaction produces slots.""" - wave = SimdWave(wave_size=64, exec_mask=MASK64) - matching_lanes = [lane for lane in range(64) if (lane & 7) == 3] - ballot_mask = sum(1 << lane for lane in matching_lanes) - mask_lo = ballot_mask & MASK32 - mask_hi = (ballot_mask >> 32) & MASK32 - - wave.compute_thread_ranks(dst=0, mask_lo=mask_lo, mask_hi=mask_hi) - for expected_slot, lane in enumerate(matching_lanes): - self.assertEqual(wave.vgprs[lane][0], expected_slot) - - -# ----------------------------------------------------------------------------- -# 5. Translator Emission & AST Verification via rdna2spirv.Gen -# ----------------------------------------------------------------------------- - -class TestMbcntTranslatorEmission(unittest.TestCase): - """Verifies that rdna2spirv translates v_mbcnt into SPIR-V ops.""" - - def test_v_mbcnt_lo_emission_structure(self): - g = rdna2spirv.Gen("cs") - g.cs = {"size": (64, 1, 1)} - ins = { - "op": "v_mbcnt_lo_u32_b32", - "args": [ - {"k": "vgpr", "r": 0}, - {"k": "imm", "v": 0xFFFFFFFF}, - {"k": "imm", "v": 0}, - ], - "mods": [], - } - g.insn(ins) - emitted = "\n".join(g.body) - self.assertIn("OpULessThan %bool", emitted) - self.assertIn("OpShiftLeftLogical %uint", emitted) - self.assertIn("OpISub %uint", emitted) - self.assertIn("OpSelect %uint", emitted) - self.assertIn("OpBitwiseAnd %uint", emitted) - self.assertIn("OpBitCount %uint", emitted) - self.assertIn("OpIAdd %uint", emitted) - - def test_v_mbcnt_hi_emission_wave64(self): - g = rdna2spirv.Gen("cs") - g.wave64 = True - g.cs = {"size": (64, 1, 1)} - ins = { - "op": "v_mbcnt_hi_u32_b32", - "args": [ - {"k": "vgpr", "r": 0}, - {"k": "imm", "v": 0xFFFFFFFF}, - {"k": "vgpr", "r": 0}, - ], - "mods": [], - } - g.insn(ins) - emitted = "\n".join(g.body) - self.assertIn("OpISub %uint", emitted) - self.assertIn("OpULessThan %bool", emitted) - self.assertIn("OpShiftLeftLogical %uint", emitted) - self.assertIn("OpSelect %uint", emitted) - self.assertIn("OpBitCount %uint", emitted) - self.assertIn("OpIAdd %uint", emitted) - - -# ----------------------------------------------------------------------------- -# 6. End-to-End SPIR-V Shader Execution via spirv_mini_interp -# ----------------------------------------------------------------------------- - -_TMP_DIR: tempfile.TemporaryDirectory | None = None -_PS_PATH: str | None = None -_CS_PATH: str | None = None - - -def setUpModule(): - global _TMP_DIR, _PS_PATH, _CS_PATH - _TMP_DIR = tempfile.TemporaryDirectory() - disasm_dir = os.path.join(_TMP_DIR.name, "disasm") - fssm_dir = os.path.join(_TMP_DIR.name, "fssm") - os.mkdir(disasm_dir) - os.mkdir(fssm_dir) - - _PS_PATH = os.path.join(disasm_dir, "ps_mbcnt.s") - _CS_PATH = os.path.join(disasm_dir, "cs_mbcnt.s") - - # Pixel shader stub DXBC - with open(os.path.join(_TMP_DIR.name, "ps_mbcnt.dxbc"), "wb") as f: - f.write(STUB_DXBC) - - # Compute shader stub FSSM (COMPUTE_PGM_RSRC2 0x8090: 8 user SGPRs, 64x1x1) - cs_fssm_path = os.path.join(fssm_dir, "cs_mbcnt.fssm") - cs_hdr = bytes(0x138) + struct.pack("<4I", 0x8090, 64, 1, 1) - with open(cs_fssm_path, "wb") as f: - f.write(cs_hdr) - - -def tearDownModule(): - global _TMP_DIR - if _TMP_DIR is not None: - _TMP_DIR.cleanup() - _TMP_DIR = None - - -def run_ps_mbcnt_lines(lines: list[str], lane: int) -> int: - """Translates a synthetic pixel shader and evaluates mrt0 output word.""" - if _TMP_DIR is None: - setUpModule() - body = "".join(f"\t{ln}\n" for ln in lines) - asm = ( - "; test_ps_mbcnt\n" - f"{body}" - "\texp mrt0 v0, v0, v0, v0 done vm\n" - "\ts_endpgm\n" - ) - with open(_PS_PATH, "w", encoding="utf-8") as f: - f.write(asm) - with warnings.catch_warnings(): - warnings.simplefilter("ignore", ResourceWarning) - spv = rdna2spirv.translate(_PS_PATH) - out = si.run_fragment(spv, inputs={"%sg_lane": lane})["%out_mrt0"] - return out[0] - - -class TestSpirvMiniInterpMbcnt(unittest.TestCase): - """End-to-end SPIR-V interpreter validation of translated shaders.""" - - def test_ps_wave64_thread_rank_all_lanes(self): - """Lanes 0..63 compute exact lane index in translated SPIR-V shader.""" - lines = [ - "v_mbcnt_lo_u32_b32 v0, -1, 0", - "v_mbcnt_hi_u32_b32 v0, -1, v0", - ] - results = [run_ps_mbcnt_lines(lines, lane) for lane in range(64)] - self.assertEqual(results, list(range(64))) - - def test_ps_mbcnt_lo_wave32(self): - """A wave32 pixel shader counts lanes independently in both halves of a 64-lane subgroup.""" - lines = ["v_mbcnt_lo_u32_b32 v0, -1, 0"] - for lane in range(64): - with self.subTest(subgroup_lane=lane): - self.assertEqual(run_ps_mbcnt_lines(lines, lane), lane & 31) - - def test_ps_mbcnt_hi_lanes(self): - """v_mbcnt_hi on lanes < 32 adds 0; lanes >= 32 count relative bits.""" - lines = ["v_mbcnt_hi_u32_b32 v0, -1, 0"] - for lane in range(32): - self.assertEqual(run_ps_mbcnt_lines(lines, lane), 0) - for lane in range(32, 64): - self.assertEqual(run_ps_mbcnt_lines(lines, lane), lane - 32) - - def test_ps_accumulator_offset(self): - """Verifies base offset passed in accumulator operand.""" - base = 0x1000 - lines = [ - f"v_mov_b32 v1, {base:#x}", - "v_mbcnt_lo_u32_b32 v0, -1, v1", - "v_mbcnt_hi_u32_b32 v0, -1, v0", - ] - for lane in (0, 7, 31, 32, 63): - got = run_ps_mbcnt_lines(lines, lane) - self.assertEqual(got, base + lane) - - def test_ps_accumulator_wrapping(self): - """Verifies 32-bit wrapping in SPIR-V evaluation.""" - lines = [ - "v_mbcnt_lo_u32_b32 v0, -1, 0xFFFFFFFF", - ] - # lane 0: count is 0 -> 0xFFFFFFFF - self.assertEqual(run_ps_mbcnt_lines(lines, 0), 0xFFFFFFFF) - # lane 1: count is 1 -> 0 (wrapped) - self.assertEqual(run_ps_mbcnt_lines(lines, 1), 0) - # lane 2: count is 2 -> 1 - self.assertEqual(run_ps_mbcnt_lines(lines, 2), 1) - - def test_ps_arbitrary_mask(self): - """Verifies non-trivial mask through SGPR operand.""" - mask_lo = 0x55555555 - mask_hi = 0xAAAAAAAA - lines = [ - f"s_mov_b32 s4, {mask_lo:#x}", - f"s_mov_b32 s5, {mask_hi:#x}", - "v_mbcnt_lo_u32_b32 v0, s4, 0", - "v_mbcnt_hi_u32_b32 v0, s5, v0", - ] - for lane in (0, 1, 2, 3, 16, 31, 32, 33, 48, 63): - got = run_ps_mbcnt_lines(lines, lane) - want = ref_thread_rank_wave64(lane, mask_lo, mask_hi, 0) - self.assertEqual(got, want) - - def test_cs_workgroup_whole_wave_memory_dump(self): - """A 64-thread compute shader stores each thread's ID into memory.""" - if _TMP_DIR is None: - setUpModule() - asm = """; cs_mbcnt -\tv_mbcnt_lo_u32_b32 v0, -1, 0 -\tv_mbcnt_hi_u32_b32 v0, -1, v0 -\tv_lshlrev_b32_e32 v1, 2, v0 -\tbuffer_store_dword v0, v1, s[0:3], 0 offen -\ts_endpgm -""" - with open(_CS_PATH, "w", encoding="utf-8") as f: - f.write(asm) - with warnings.catch_warnings(): - warnings.simplefilter("ignore", ResourceWarning) - spv = rdna2spirv.translate(_CS_PATH) - - vsharp = [0, 0, MASK32, 0x31016FAC] - mem = {} - si.run_workgroup( - spv, - 64, - 64, - inputs_for=lambda i: { - "%wg_id": (0, 0, 0), - "%local_id": (i, 0, 0), - "%sg_lane": i % 64, - }, - push_constants=vsharp + [0] * 28, - memory=mem, - ) - stored = [mem.get(i * 4) for i in range(64)] - self.assertEqual(stored, list(range(64))) - - -# ----------------------------------------------------------------------------- -# 7. Negative Controls and Mutation Invariants -# ----------------------------------------------------------------------------- - -class TestNegativeControlsAndMutations(unittest.TestCase): - """Verifies that deliberate bugs or corruptions are detected.""" - - def test_inclusive_scan_rejected(self): - """Inclusive scan differs from exclusive scan for set lane 0 bit.""" - mask = 1 - inclusive_lane_0 = 1 - exclusive_lane_0 = ref_mbcnt_lo(0, mask, 0) - self.assertEqual(exclusive_lane_0, 0) - self.assertNotEqual(inclusive_lane_0, exclusive_lane_0) - - def test_swapped_lo_hi_masks_fail(self): - """Swapping lo and hi masks produces wrong rank for high-half lanes.""" - mask_lo = 0xFFFFFFFF - mask_hi = 0x00000000 - # Correct rank for lane 32 is 32 - correct = ref_thread_rank_wave64(32, mask_lo, mask_hi, 0) - self.assertEqual(correct, 32) - # Swapped: lo has 0, hi has -1 -> lo gives 0, hi gives 0 -> 0 != 32 - swapped = ref_thread_rank_wave64(32, mask_hi, mask_lo, 0) - self.assertEqual(swapped, 0) - self.assertNotEqual(correct, swapped) - - def test_unclamped_shift_mutation(self): - """Mutated calculation omitting clamp produces incorrect count.""" - # Simulated buggy implementation without lane - 32 - def buggy_mbcnt_hi(lane: int, mask_hi: int, acc: int) -> int: - bitmask = (1 << lane) - 1 - return (popcount(mask_hi & bitmask) + acc) & MASK32 - - # Lane 33: rel should be 1 (bitmask 1), buggy produces (1 << 33) - 1 - mask_hi = 0xFFFFFFFF - correct = ref_mbcnt_hi(33, mask_hi, 0) - self.assertEqual(correct, 1) - buggy = buggy_mbcnt_hi(33, mask_hi, 0) - self.assertNotEqual(correct, buggy) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_mem_crash_forms.py b/tests/semantic/test_mem_crash_forms.py deleted file mode 100644 index a809d157f..000000000 --- a/tests/semantic/test_mem_crash_forms.py +++ /dev/null @@ -1,42 +0,0 @@ -"""Memory-op forms that the assembler accepts and the translator must refuse cleanly, not crash on. - -An image instruction whose result operand is not a VGPR range (`image_sample off, v[1:2], s[16:23], s[24:27] ...`: -llvm-mc takes `off` there) used to raise a KeyError('r') in the translator when it wrote the result. It is a form no -compiler emits (a sample with a dmask and nowhere to put the texels); the translator now raises Unsupported for the -result operand instead. A probe of about 60,000 DS, MUBUF, MTBUF, MIMG, SMEM and FLAT/GLOBAL/SCRATCH operand and -modifier variations (glc, slc, dlc, lds, tfe, d16, a16, unorm, dmask, dim, offset, idxen, offen, addr64, format; as -written and as llvm-mc prints them; pixel and compute stages) found no other crash. Standard library only; no GPU. -""" -import unittest - -import support -import rdna2spirv - -CASES = ( - "image_sample off, v[1:2], s[16:23], s[24:27] dmask:0xf dim:SQ_RSRC_IMG_2D slc", - "image_sample off, v[1:2], s[16:23], s[24:27] dmask:0x3 dim:SQ_RSRC_IMG_2D tfe lwe", - "image_sample_c_lz off, v[4:6], s[8:15], s[16:19] dmask:0x1 dim:SQ_RSRC_IMG_2D", - "image_sample_c_lz off, v[1:4], s[16:23], s[24:27] dmask:0x3 dim:SQ_RSRC_IMG_CUBE d16", - "image_sample_o off, v[1:4], s[16:23], s[24:27] dmask:0x1 dim:SQ_RSRC_IMG_3D tfe", - "image_sample_l off, v[1:4], s[16:23], s[24:27] dmask:0x1 dim:SQ_RSRC_IMG_2D_ARRAY lwe", - "image_load off, v[1:2], s[16:23] dmask:0x1 dim:SQ_RSRC_IMG_2D", - "image_load_mip off, v[1:3], s[16:23] dmask:0x1 dim:SQ_RSRC_IMG_2D", - "image_gather4 off, v[1:2], s[16:23], s[24:27] dmask:0x1 dim:SQ_RSRC_IMG_2D", - "image_gather4_lz off, v[1:2], s[16:23], s[24:27] dmask:0x1 dim:SQ_RSRC_IMG_2D", - "image_get_lod off, v[1:2], s[16:23], s[24:27] dmask:0x1 dim:SQ_RSRC_IMG_2D", -) - - -class ImageResultOperand(unittest.TestCase): - def test_non_vgpr_result_is_unsupported_not_a_crash(self): - for line in CASES: - with self.subTest(line=line): - text = "; mem_crash\n\t" + line + "\n\tv_mov_b32 v50, 1\n\texp mrt0 v50, v50, v50, v50 done vm\n\ts_endpgm\n" - try: - support.translate_listing("ps_mem_crash", text.encode("utf-8")) - except rdna2spirv.Unsupported: - pass - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_mesh_cull_store.py b/tests/semantic/test_mesh_cull_store.py deleted file mode 100644 index 872d69e55..000000000 --- a/tests/semantic/test_mesh_cull_store.py +++ /dev/null @@ -1,95 +0,0 @@ -"""SHADER-575: a mesh shader's CullPrimitiveEXT is written as a constant on each side of a branch. - -llvmpipe (Mesa 25.2.8, LLVM 20) aborts compiling the wave64-emulated mesh epilogue when the per-primitive cull bool is -stored as a computed value ("Cannot emit physreg copy instruction"), and Mesa 26.3.1 drew no primitives for the same -shaders. Storing %true or %false behind a branch on the same bool means the same on every driver and compiles there. - -The program is runtime/test/shaders/ms_tri.asm, the mesh GPU test (128 threads, 64/64 outputs, triangles), translated -natively and with --wave64-emulate. Standard library only; the spirv-val check needs SPIRV-Tools. -""" -import os -import re -import shutil -import struct -import subprocess -import sys -import tempfile -import unittest - -sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) -import support # noqa: E402 (path set above) -import rdna2spirv # noqa: E402 - -MS_TRI = os.path.join(support.ROOT, "runtime", "test", "shaders", "ms_tri.asm") - - -def _dxbc(chunks): - """A DXBC container with the given (fourcc, payload) parts.""" - hdr = 32 + 4 * len(chunks) - offsets, body = [], bytearray() - for tag, payload in chunks: - offsets.append(hdr + len(body)) - body += tag + struct.pack(" None: - fixture = Path(__file__).with_name("fixtures") / "ps_minmax_f32_payload.asm" - module = translate_lines(fixture.stem, fixture.read_text(encoding="ascii").splitlines()) - - a, b, half = 0x7FE00080, 0xFFD10040, 0x3F000000 - for lhs, rhs, expected in ( - (a, b, (a, a, b, b)), - (a, half, (half, half, half, half)), - (half, b, (half, half, half, half)), - (0, 0x80000000, (0x80000000, 0, 0x80000000, 0)), - ): - with self.subTest(lhs=hex(lhs), rhs=hex(rhs)): - words = mrt0_words(module, push_constants=[lhs, rhs] + [0] * 30) - self.assertEqual(words, [word ^ 0x40C00000 for word in expected]) diff --git a/tests/semantic/test_misc_ext_fixture.py b/tests/semantic/test_misc_ext_fixture.py deleted file mode 100644 index 1bcd07ef8..000000000 --- a/tests/semantic/test_misc_ext_fixture.py +++ /dev/null @@ -1,97 +0,0 @@ -"""cs_w32_misc_ext: the GPU test of more ops that had CPU-only checks, run here on the CPU too. - -Standard library only; no GPU, no LLVM, no game files. - -runtime/test/shaders/cs_w32_misc_ext.asm has lane 0 of a wave32 group store one word of each of s_nand_b64, -s_xnor_b64, v_cvt_pk_u16_u32, v_cvt_pk_i16_i32, v_mad_u32_u16, v_mad_i32_i16, ds_cmpst_rtn_b32 (old value and the -LDS word after it) and ds_write2_b64 / ds_read2_b64 (derivations in its header). This runs the fixture -(tests/semantic/regen_fixtures.py) through spirv_mini_interp, checks the eight words against values computed here -from the ISA definitions, and checks that check.py and scripts/run_gpu_tests.py expect the same words on the GPU. -""" -import os -import re -import struct -import unittest - -import support -import spirv_mini_interp as si - -HERE = os.path.dirname(os.path.abspath(__file__)) -ROOT = os.path.dirname(os.path.dirname(HERE)) -M32 = 0xFFFFFFFF -M64 = (1 << 64) - 1 - -# 4 user SGPRs (the output V#), workgroup id in s4, 512 bytes of LDS (LDS_SIZE 1), 32x1x1 threads. -FSSM = bytearray(0x148) -struct.pack_into("<4I", FSSM, 0x138, 0x8088, 32, 1, 1) -FSSM = bytes(FSSM) -VSHARP = [0, 0, 0x1000, 0x31016FAC] - - -def s16(x: int) -> int: - x &= 0xFFFF - return x - 0x10000 if x >> 15 else x - - -def s32(x: int) -> int: - x &= M32 - return x - (1 << 32) if x >> 31 else x - - -def sat_u16(x: int) -> int: - return min(x & M32, 0xFFFF) - - -def sat_i16(x: int) -> int: - return max(-32768, min(32767, s32(x))) & 0xFFFF - - -A, B_NAND, B_XNOR = 0xF0F0F0F0_12345678, 0xFF00FF00_FFFFFFFF, 0xFF00FF00_0F0F0F0F -LDS_INIT, CMP, NEW = 5, 5, 9 -EXPECTED = [ - (~(A & B_NAND) & M64) >> 32, # s_nand_b64, high word - ~(A ^ B_XNOR) & M32, # s_xnor_b64, low word - sat_u16(0x12345) | sat_u16(7) << 16, # v_cvt_pk_u16_u32 - sat_i16(-40000) | sat_i16(40000) << 16, # v_cvt_pk_i16_i32 - (0xFFFF * 0xFFFF + 1) & M32, # v_mad_u32_u16 - (s16(0x8000) * 2 + 5) & M32, # v_mad_i32_i16 - LDS_INIT << 8 | (NEW if LDS_INIT == CMP else LDS_INIT), # ds_cmpst_rtn_b32: old, then LDS - 0xCAFEF00D, # ds_read2_b64: element 2, high dword -] - - -class MiscExtFixture(unittest.TestCase): - def test_reference(self): - self.assertEqual(EXPECTED, [0x0FFF0FFF, 0xE2C4A688, 0x0007FFFF, 0x7FFF8000, 0xFFFE0002, 0xFFFF0005, 0x509, - 0xCAFEF00D]) - - def test_translated_shader(self): - spv = support.translate_fixture("cs_w32_misc_ext", fssm=FSSM) - mem = si.run_workgroup(spv, 1, 32, inputs_for=lambda i: {"%wg_id": (0, 0, 0), "%local_id": (i, 0, 0), - "%sg_lane": i}, - push_constants=VSHARP + [0] * 28, memory={}) - self.assertEqual(sorted(mem), [4 * k for k in range(8)]) - for k, want in enumerate(EXPECTED): - with self.subTest(word=k): - self.assertEqual(mem[4 * k], want) - - def test_lds_ops_run_in_lane_0_only(self): - # spirv_mini_interp gives each invocation its own LDS, so lanes racing on one address are invisible here; - # the .asm must cut EXEC to lane 0 before its first ds_ op (#1850). - with open(os.path.join(ROOT, "runtime", "test", "shaders", "cs_w32_misc_ext.asm"), encoding="utf-8") as f: - lines = [ln.strip() for ln in f if ln.strip() and not ln.startswith(";")] - self.assertLess(lines.index("v_cmpx_eq_u32_e32 0, v0"), - min(i for i, ln in enumerate(lines) if ln.startswith("ds_"))) - - def test_gpu_runners_expect_the_same_words(self): - for rel in (("runtime", "test", "shaders", "check.py"), ("scripts", "run_gpu_tests.py")): - with open(os.path.join(ROOT, *rel), encoding="utf-8") as f: - text = f.read() - m = re.search(r'"cs_w32_misc_ext"\)?[,:]\s*\[([^\]]*)\]', text) - with self.subTest(file="/".join(rel)): - self.assertIsNotNone(m) - self.assertEqual([int(v, 0) for v in m.group(1).split(",")], EXPECTED) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_missing_encoding.py b/tests/semantic/test_missing_encoding.py deleted file mode 100644 index ceb5c663d..000000000 --- a/tests/semantic/test_missing_encoding.py +++ /dev/null @@ -1,56 +0,0 @@ -"""A hand-written listing without `; encoding:` bytes: instructions that need their own size are rejected cleanly. - -tools/shader_ir.parse_file advances the PC by each instruction's encoding bytes. Without them (a listing written by -hand, like the fixtures in tests/semantic/fixtures/disasm) the PC of the next instruction is unknown, which -s_getpc_b64 and every PC-relative branch need. Until 2026-11-22 both raised TypeError in the translator; now they -raise rdna2spirv.Unsupported, which callers such as the batch translator count as an unsupported shader. Straight-line -code without encodings still translates. Standard library only; no GPU, no game files. -""" -import os -import struct -import sys -import tempfile -import unittest -import warnings - -HERE = os.path.dirname(os.path.abspath(__file__)) -ROOT = os.path.dirname(os.path.dirname(HERE)) -sys.dont_write_bytecode = True -sys.path.insert(0, os.environ.get("LEONIDA_TOOLS_DIR") or os.path.join(ROOT, "tools")) - -import rdna2spirv # noqa: E402 - -STUB_DXBC = b"DXBC" + bytes(24) + struct.pack(" int: - return sum(1 << i for i in range(quads) if (x >> (4 * i)) & 0xF) - - -def bitreplicate(x: int) -> int: - return sum(3 << (2 * i) for i in range(32) if (x >> i) & 1) - - -def norm16(x: float, snorm: bool) -> int: - x = min(max(x, -1.0 if snorm else 0.0), 1.0) - return round(x * (32767 if snorm else 65535)) & 0xFFFF # round() is round-half-even - - -EXPECTED = [ - quadmask(0x01020408, 8), # s_quadmask_b32 - quadmask(0x80000000_00000001, 16) & M32, # s_quadmask_b64, low word - bitreplicate(0x80000001) >> 32, # s_bitreplicate_b64_b32, high word - norm16(0.5, True) | norm16(-1.0, True) << 16, # v_cvt_pknorm_i16_f32 - norm16(1.0, False) | norm16(0.25, False) << 16, # v_cvt_pknorm_u16_f32 - 0x77, # ds_wrxchg2_rtn_b32: old word at offset0 - 0x99, # LDS at offset1 after: DATA2 - 0x1234, # kept across ds_nop / v_clrexcp -] - - -class NewOpsFixture(unittest.TestCase): - def test_reference(self): - self.assertEqual(EXPECTED, [0x55, 0x8001, 0xC0000000, 0x80014000, 0x4000FFFF, 0x77, 0x99, 0x1234]) - - def test_translated_shader(self): - spv = support.translate_fixture("cs_w32_new_ops", fssm=FSSM) - mem = si.run_workgroup(spv, 1, 32, inputs_for=lambda i: {"%wg_id": (0, 0, 0), "%local_id": (i, 0, 0), - "%sg_lane": i}, - push_constants=VSHARP + [0] * 28, memory={}) - self.assertEqual(sorted(mem), [4 * k for k in range(8)]) - for k, want in enumerate(EXPECTED): - with self.subTest(word=k): - self.assertEqual(mem[4 * k], want) - - def test_lds_ops_run_in_lane_0_only(self): - # spirv_mini_interp gives each invocation its own LDS, so lanes racing on one address are invisible here; - # the .asm must cut EXEC to lane 0 before its first ds_ op (#1850). - with open(os.path.join(ROOT, "runtime", "test", "shaders", "cs_w32_new_ops.asm"), encoding="utf-8") as f: - lines = [ln.strip() for ln in f if ln.strip() and not ln.startswith(";")] - self.assertLess(lines.index("v_cmpx_eq_u32_e32 0, v0"), - min(i for i, ln in enumerate(lines) if ln.startswith("ds_"))) - - def test_gpu_runners_expect_the_same_words(self): - for rel in (("runtime", "test", "shaders", "check.py"), ("scripts", "run_gpu_tests.py")): - with open(os.path.join(ROOT, *rel), encoding="utf-8") as f: - text = f.read() - m = re.search(r'"cs_w32_new_ops"\)?[,:]\s*\[([^\]]*)\]', text) - with self.subTest(file="/".join(rel)): - self.assertIsNotNone(m) - self.assertEqual([int(v, 0) for v in m.group(1).split(",")], EXPECTED) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_norm_decode.py b/tests/semantic/test_norm_decode.py deleted file mode 100644 index e6f27fbb4..000000000 --- a/tests/semantic/test_norm_decode.py +++ /dev/null @@ -1,135 +0,0 @@ -"""Typed-buffer UNORM/SNORM decode (Gen.norm_bits in tools/rdna2spirv.py) against exact values. - -The RX 6700 returns the correctly rounded f32 of x / (2^n - 1) for UNORM and max(x / (2^(n-1) - 1), -1) for SNORM -(measured natively, #374). OpFDiv may be 2.5 ULP off and the AMD Windows and NVIDIA drivers return the reciprocal- -multiply result for it (#599), so the translation builds the quotient with integer ops. The expected values here come -from Fraction arithmetic; nothing in this file imports the translator's rounding. -""" -from __future__ import annotations - -import os -import random -import sys -import unittest -from fractions import Fraction - -HERE = os.path.dirname(os.path.abspath(__file__)) -ROOT = os.path.dirname(os.path.dirname(HERE)) -TOOLS_DIR = os.environ.get("LEONIDA_TOOLS_DIR") or os.path.join(ROOT, "tools") - -sys.dont_write_bytecode = True -sys.path.insert(0, TOOLS_DIR) -sys.path.insert(0, HERE) - -import rdna2spirv # noqa: E402 -import spirv_mini_interp as si # noqa: E402 -from test_buffer_load_format import BASE, FMT_U32, load_format # noqa: E402 - - -def f32_rne(x: Fraction) -> int: - """Bits of the binary32 nearest to x (ties to even); |x| <= 1 and x is 0 or at least 2^-126 here.""" - if x == 0: - return 0 - sign = 0x80000000 if x < 0 else 0 - a, e = abs(x), 0 - while a >= 2: - a /= 2 - e += 1 - while a < 1: - a *= 2 - e -= 1 - m = a * (1 << 23) - q, r = divmod(m.numerator, m.denominator) - if 2 * r > m.denominator or (2 * r == m.denominator and q & 1): - q += 1 - if q == 1 << 24: - q >>= 1 - e += 1 - return sign | (e + 127) << 23 | (q - (1 << 23)) - - -def norm_bits_on_interp(m: int, n: int) -> int: - """Run the SPIR-V that Gen.norm_bits emits for the constant m in the mini interpreter.""" - gen = rdna2spirv.Gen("ps") - res = gen.norm_bits(gen.cu(m), n) - consts = "".join(f"{name} = OpConstant %uint {v}\n" for v, name in gen.consts.items()) - consts += "".join(f"{name} = OpConstant %ulong {v}\n" for v, name in gen.lconsts.items()) - text = ("OpCapability Shader\nOpCapability Int64\n%glsl = OpExtInstImport \"GLSL.std.450\"\n" - "OpMemoryModel Logical GLSL450\nOpEntryPoint Fragment %main \"main\" %out\n" - "%void = OpTypeVoid\n%fn = OpTypeFunction %void\n%bool = OpTypeBool\n%uint = OpTypeInt 32 0\n" - "%int = OpTypeInt 32 1\n%ulong = OpTypeInt 64 0\n%_ptr_Output_uint = OpTypePointer Output %uint\n" - "%out = OpVariable %_ptr_Output_uint Output\n" + consts - + "%main = OpFunction %void None %fn\n%entry = OpLabel\n" - + "".join(line.strip() + "\n" for line in gen.body) - + f"OpStore %out {res}\nOpReturn\nOpFunctionEnd\n") - return si.run_fragment(text)["%out"][0] - - -def recip_mul(m: int, n: int) -> int: - """The decode before #599 (and what OpFDiv returns on those drivers): f32(m) * f32(1/(2^n-1)), rounded once.""" - c = Fraction(f32_rne_float(Fraction(1, (1 << n) - 1))) - return f32_rne(m * c) - - -def f32_rne_float(x: Fraction) -> float: - import struct - return struct.unpack(" -1.0 - self.assertEqual(load_format(2, 0, 1, memory=mem)[0], 0xBF800000) - # 8_8_SNORM (15): 0x81, 0xFF -> -1.0, -1/127 - self.assertEqual(load_format(15, 0, 2, memory=mem)[:2], (0xBF800000, f32_rne(Fraction(-1, 127)))) - # 16_SNORM (8): 0xFF81 = -127 -> -127/32767; high half 0x8001 = -32767 -> -1.0 - self.assertEqual(load_format(8, 0, 1, memory=mem)[0], f32_rne(Fraction(-127, 32767))) - self.assertEqual(load_format(8, 2, 1, memory=mem)[0], 0xBF800000) - # 16_SNORM: the most negative code, -32768, is -1.0 too - self.assertEqual(load_format(8, 0, 1, memory={BASE: 0x8000})[0], 0xBF800000) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_or_saveexec.py b/tests/semantic/test_or_saveexec.py deleted file mode 100644 index 7b9d317a7..000000000 --- a/tests/semantic/test_or_saveexec.py +++ /dev/null @@ -1,171 +0,0 @@ -"""Semantic interpreter test for s_or_saveexec_b32 (and its wave64 form, s_or_saveexec_b64). - -AMD "RDNA 2" Instruction Set Architecture, section 12.3 SOP1 Instructions (opcodes 37 and 61), with S0 the source -mask and EXEC the mask before the instruction: - - D = EXEC; EXEC = S0 | EXEC; SCC = (EXEC != 0) - -Each case translates a synthetic compute shader with tools/rdna2spirv.py and runs every lane of the wave in lockstep -with spirv_mini_interp.run_workgroup, in wave32 (_b32) and native wave64 (_b64); --wave64-emulate is checked to -translate only, since the interpreter does not run its workgroup barriers. Per lane the shader stores whether the -lane is on in the new EXEC, its bit of D, and SCC; the expected values come from a plain-Python model of the -pseudocode above. Before the op, D is set to all ones and SCC to the opposite of the expected value, so a result the -translator never writes cannot pass. The cases: S0 and EXEC overlapping in part; EXEC empty, so the op turns S0's -lanes back on and D = 0; and both empty, so EXEC stays 0 and SCC = 0. -""" -import os -import struct -import sys -import unittest - -HERE = os.path.dirname(os.path.abspath(__file__)) -if HERE not in sys.path: - sys.path.insert(0, HERE) # python -I leaves the script's folder off sys.path - -import support # noqa: E402 (support puts tools/ on sys.path, honouring LEONIDA_TOOLS_DIR) -import spirv_mini_interp as si # noqa: E402 - -rdna2spirv = support.rdna2spirv -VSHARP = [0, 0, 0xFFFFFFFF, 0x31016FAC] # raw buffer, every store in range (as in test_carry_exec_mask.py) - - -def ref(s0, exec_): - """(new EXEC, D) from the ISA pseudocode; masks are Python sets of lanes.""" - return s0 | exec_, exec_ - - -# (S0 lanes, EXEC lanes) per wave size: partial overlap; EXEC empty; both empty. The wave64 masks have lanes in both -# halves, so a result taken from one half only shows. -MASKS = { - 32: [({1, 3, 5, 20, 31}, {3, 4, 5, 17, 31}), ({2, 30}, set()), (set(), set())], - 64: [({1, 3, 33, 40, 63}, {3, 4, 33, 50, 63}), ({2, 45}, set()), (set(), set())], -} - - -def _regs(wave_size): - if wave_size == 64: - return {"op": "s_or_saveexec_b64", "exec": "exec", "mov": "s_mov_b64", "or": "s_or_b64", - "s0": "s[4:5]", "tmp": "s[6:7]", "old": "s[8:9]", "d": "s[10:11]"} - return {"op": "s_or_saveexec_b32", "exec": "exec_lo", "mov": "s_mov_b32", "or": "s_or_b32", - "s0": "s4", "tmp": "s6", "old": "s8", "d": "s10"} - - -def _mask_lines(lanes, dst, r): - """Build a lane mask in `dst` that is 1 for `lanes` and 0 elsewhere (v0 = lane index), under a full EXEC. - - Masks come from v_cmp; the only constants moved into a mask anywhere in this file are 0 and -1, the same for - every lane, so the test does not depend on how the translator splits a constant mask into lane bits (SHADER-198). - """ - if not lanes: - return [f"{r['mov']} {dst}, 0"] - lanes = sorted(lanes) - lines = [f"v_cmp_eq_u32_e64 {dst}, v0, {lanes[0]}"] - for lane in lanes[1:]: - lines.append(f"v_cmp_eq_u32_e64 {r['tmp']}, v0, {lane}") - lines.append(f"{r['or']} {dst}, {dst}, {r['tmp']}") - return lines - - -def _program(s0_lanes, exec_lanes, wave_size, scc_before): - """Lines that run the op with S0 = s0_lanes and EXEC = exec_lanes, then store per lane (12 bytes): the new EXEC - bit, the D bit and SCC. D starts as all ones and SCC as `scc_before`, so a value the op does not write shows.""" - r = _regs(wave_size) - lines = [f"{r['mov']} {r['exec']}, -1"] - lines += _mask_lines(s0_lanes, r["s0"], r) - lines += _mask_lines(exec_lanes, r["old"], r) - lines += [ - "v_mov_b32 v6, 0", # 1 below only on lanes the new EXEC keeps on - f"{r['mov']} {r['d']}, -1", - f"{r['mov']} {r['exec']}, {r['old']}", # EXEC before the op (s_mov does not write SCC) - "s_cmp_eq_u32 0, 0" if scc_before else "s_cmp_lg_u32 0, 0", - f"{r['op']} {r['d']}, {r['s0']}", - "v_mov_b32 v6, 1", - "s_cselect_b32 s14, 1, 0", # SCC of the op - f"{r['mov']} {r['exec']}, -1", - f"v_cndmask_b32_e64 v7, 0, 1, {r['d']}", - "v_mov_b32 v8, s14", - "v_mul_lo_u32 v11, v0, 12", - "buffer_store_dword v6, v11, s[0:3], 0 offen", - "v_add_nc_u32 v12, 4, v11", - "buffer_store_dword v7, v12, s[0:3], 0 offen", - "v_add_nc_u32 v12, 8, v11", - "buffer_store_dword v8, v12, s[0:3], 0 offen", - ] - return lines - - -def _fssm(wave_size): - """Compute-shader header: COMPUTE_PGM_RSRC2 0x8088 (4 user SGPRs, s[0:3] = output V#; TGID_X), then the - thread-group size: one wave of `wave_size` threads.""" - return bytes(0x138) + struct.pack("<4I", 0x8088, wave_size, 1, 1) - - -def _translate_cs(name, body_lines, wave_size, emulate): - """Translate a synthetic compute shader of one wave; returns the SPIR-V text.""" - prev_emu = rdna2spirv.WAVE64_EMULATE - rdna2spirv.WAVE64_EMULATE = emulate - try: - spv = support.translate_lines(name, [*body_lines, "s_endpgm"], fssm=_fssm(wave_size)) - finally: - rdna2spirv.WAVE64_EMULATE = prev_emu - got64 = rdna2spirv.translate.last_gen.wave64 - if got64 != (wave_size == 64): - raise AssertionError(f"{name}: expected wave64={wave_size == 64}, got {got64}") - return spv - - -def _run_cs(name, body_lines, wave_size): - """Translate a synthetic compute shader and run all lanes of one wave on one subgroup; returns the memory.""" - spv = _translate_cs(name, body_lines, wave_size, emulate=False) - return si.run_workgroup( - spv, wave_size, wave_size, - inputs_for=lambda i: {"%wg_id": (0, 0, 0), "%local_id": (i, 0, 0), "%sg_lane": i}, - push_constants=VSHARP + [0] * 28, memory={}, - ) - - -class ReferenceTests(unittest.TestCase): - def test_reference(self): - # The model itself, on hand-checked pairs. - self.assertEqual(ref({1, 3}, {3, 4}), ({1, 3, 4}, {3, 4})) - self.assertEqual(ref({2}, set()), ({2}, set())) - self.assertEqual(ref(set(), set()), (set(), set())) - - -class _OrSaveExecMixin: - wave_size = 32 - - def test_exec_d_and_scc(self): - for case, (s0, exec_) in enumerate(MASKS[self.wave_size]): - with self.subTest(case=case, wave=self.wave_size): - want_exec, want_d = ref(s0, exec_) - want_scc = 1 if want_exec else 0 - lines = _program(s0, exec_, self.wave_size, scc_before=1 - want_scc) - mem = _run_cs(f"cs_or_saveexec_w{self.wave_size}_{case}", lines, self.wave_size) - for lane in range(self.wave_size): - base = lane * 12 - self.assertEqual(mem[base], int(lane in want_exec), f"lane {lane}: new EXEC bit") - self.assertEqual(mem[base + 4], int(lane in want_d), f"lane {lane}: D bit") - self.assertEqual(mem[base + 8], want_scc, f"lane {lane}: SCC") - - -class Wave32Tests(_OrSaveExecMixin, unittest.TestCase): - wave_size = 32 - - -class Wave64Tests(_OrSaveExecMixin, unittest.TestCase): - wave_size = 64 - - -class Wave64EmulateTranslationTests(unittest.TestCase): - """--wave64-emulate: the emulated wave synchronises through workgroup barriers, which spirv_mini_interp does not - run (as in test_carry_exec_mask.py and test_salu64_bitwise_data.py), so only the translation is checked here.""" - - def test_translates(self): - s0, exec_ = MASKS[64][0] - spv = _translate_cs("cs_emu_or_saveexec", _program(s0, exec_, 64, scc_before=0), 64, emulate=True) - self.assertIn("OpStore %x_it", spv) # the exchange-round counter, declared only by the emulated translation - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_pack_b32_f16_mods.py b/tests/semantic/test_pack_b32_f16_mods.py deleted file mode 100644 index 13c021072..000000000 --- a/tests/semantic/test_pack_b32_f16_mods.py +++ /dev/null @@ -1,171 +0,0 @@ -"""Semantic tests for the neg/abs source modifiers on v_pack_b32_f16 (SHADER-260, abs follow-up). - -v_pack_b32_f16 packs the low 16 bits of src0 and of src1 into one dword (op_sel picks a source's high half -instead). On RDNA2 the VOP3 NEG and ABS fields act on the selected 16-bit half as plain bit moves, before the -half is packed: ABS clears bit 15 and NEG flips it, ABS first. Both NEG and ABS were measured on an AMD Radeon -Graphics RDNA2 iGPU (gfx1036, AMD Windows driver 32.0.21045.29003) with 1,088 hand-written raw kernels in wave32 -and wave64 (0 mismatches): ``|v0|`` clears bit 15, ``-v0`` flips bit 15, and ``-|v0|`` clears bit 15 and flips -it (setting bit 15) across all normals, zeros, infinities, subnormals, quiet NaNs, and signaling NaNs, in either -half and with op_sel. Under IEEE mode 1 signaling NaNs are quieted (bit 9 set); under IEEE mode 0 the half is -moved as pure bit operations without quieting. The translator used to reject any such operand as Unsupported. - -Not modelled here: IEEE mode 1 quieting a signalling NaN half (0x7c01 -> 0x7e01). Which mode the game's shaders -run in is SHADER-190; the NaN cases below are the plain bit moves of mode 0. - -The whole 16-bit half is moved, so an sNaN payload survives; the interpreter runs the integer SPIR-V -(OpBitwiseAnd/OpBitwiseXor), which is exact. -""" -import os -import struct -import sys -import tempfile -import unittest -import warnings - -HERE = os.path.dirname(os.path.abspath(__file__)) -ROOT = os.path.dirname(os.path.dirname(HERE)) -TOOLS_DIR = os.environ.get("LEONIDA_TOOLS_DIR") or os.path.join(ROOT, "tools") - -sys.dont_write_bytecode = True -sys.path.insert(0, TOOLS_DIR) -sys.path.insert(0, HERE) - -import rdna2spirv # noqa: E402 -import spirv_mini_interp as si # noqa: E402 - -STUB_DXBC = b"DXBC" + bytes(24) + struct.pack("> (16 if hi else 0) & 0xFFFF - if abs_: - bits &= MANT - if neg: - bits ^= SIGN - return bits - - -def operand(base, neg, abs_, hi): - text = f"{'-' if neg else ''}{'|' if abs_ else ''}{base}{'|' if abs_ else ''}" - return text, f"[{1 if hi else 0}]" - - -# (src0 word, src1 word, src0 neg/abs/hi, src1 neg/abs/hi) -CASES = [ - (W1, W2, (0, 0, 0), (0, 0, 0)), # plain pack (control) - (W2, W1, (1, 0, 0), (0, 0, 0)), # src0 neg flips the low half's sign - (W3, W4, (0, 1, 0), (0, 0, 0)), # src0 abs on an sNaN half keeps the payload - (W4, W4, (1, 1, 0), (0, 0, 0)), # neg(abs(-0.0)) -> -0.0 - (W3, W5, (1, 1, 1), (1, 1, 1)), # high halves of both, both modifiers: sNaN negated, -3.0 abs - (W2, W1, (0, 1, 1), (0, 0, 0)), # op_sel high with abs (the high half of W2 is 1.5) - (W1, W3, (1, 0, 0), (1, 0, 1)), # neg on both, src1 op_sel high: -1.5 | -sNaN -] - - -class PackModsTests(unittest.TestCase): - def test_neg_abs_are_bit_moves_on_the_selected_half(self): - for w1, w2, (n0, ab0, hi0), (n1, ab1, hi1) in CASES: - with self.subTest(w1=f"{w1:08x}", w2=f"{w2:08x}", mods=(n0, ab0, hi0, n1, ab1, hi1)): - s0, o0 = operand("v1", n0, ab0, hi0) - s1, o1 = operand("v2", n1, ab1, hi1) - mods = f" op_sel:[{o0[1]},{o1[1]},0]" if (hi0 or hi1) else "" - lines = [f"v_mov_b32 v1, {w1:#x}", f"v_mov_b32 v2, {w2:#x}", - f"v_pack_b32_f16 v0, {s0}, {s1}{mods}"] - want = half(w1, hi0, n0, ab0) | half(w2, hi1, n1, ab1) << 16 - self.assertEqual(run(lines)[0], want) - - def test_negative_inline_constant_keeps_its_sign(self): - # -1.0 as an inline constant arrives with the sign in the value, not as a NEG modifier. - self.assertEqual(run(["v_pack_b32_f16 v0, -1.0, v1"])[0], 0xBC00) - - def test_abs_inline_constant(self): - self.assertEqual(run(["v_pack_b32_f16 v0, 1.0, |v1|"])[0], 0x3C00) - - def test_snan_payload_is_kept(self): - # 0x7c01 is an sNaN half: the packer moves the whole 16 bits, it does not round a float. - self.assertEqual(run(["v_mov_b32 v1, 0x7c01", "v_pack_b32_f16 v0, v1, v2"])[0], 0x00007C01) - - def test_gpu_fixture_words(self): - # The words in runtime/test/shaders/ps_f16_pack_mods.asm are what a GPU must give. - words = run(["v_mov_b32 v0, 0x42003400", "v_mov_b32 v1, 0x34004400", - "v_pack_b32_f16 v2, -v0, |v1|", "v_pack_b32_f16 v3, v0, -v1", - "v_pack_b32_f16 v4, -|v0|, v1 op_sel:[1,0,0]", - "v_pack_b32_f16 v5, -v0, -|v1| op_sel:[0,1,0]"], export=("v2", "v3", "v4", "v5")) - self.assertEqual(list(words), [0x4400B400, 0xC4003400, 0x4400C200, 0xB400B400]) - - def test_abs_and_neg_abs_all_f16_edge_values(self): - # 16 edge values covering normals, zeros, infinities, subnormals, quiet NaNs, and signaling NaNs. - edge_vals = [ - 0x3C00, 0xBC00, # +1.0, -1.0 - 0x0000, 0x8000, # +0.0, -0.0 - 0x7C00, 0xFC00, # +Inf, -Inf - 0x0001, 0x8001, # +min_sub, -min_sub - 0x7E00, 0x7E55, # +qNaN1, +qNaN2 - 0xFE00, 0xFE55, # -qNaN1, -qNaN2 - 0x7C01, 0x7C96, # +sNaN1, +sNaN2 - 0xFC01, 0xFD55, # -sNaN1, -sNaN2 - ] - for val in edge_vals: - # test abs alone: clears bit 15 - res_abs = run([f"v_mov_b32 v1, {val:#x}", "v_pack_b32_f16 v0, |v1|, v1"])[0] & 0xFFFF - self.assertEqual(res_abs, val & MANT) - - # test neg alone: flips bit 15 - res_neg = run([f"v_mov_b32 v1, {val:#x}", "v_pack_b32_f16 v0, -v1, v1"])[0] & 0xFFFF - self.assertEqual(res_neg, val ^ SIGN) - - # test neg_abs (-|v1|): clears then flips bit 15 -> sets bit 15 - res_neg_abs = run([f"v_mov_b32 v1, {val:#x}", "v_pack_b32_f16 v0, -|v1|, v1"])[0] & 0xFFFF - self.assertEqual(res_neg_abs, (val & MANT) | SIGN) - - # test on high half via op_sel - w_hi = (val << 16) | 0x1234 - res_hi_abs = run([f"v_mov_b32 v1, {w_hi:#x}", "v_pack_b32_f16 v0, |v1|, v1 op_sel:[1,0,0]"])[0] & 0xFFFF - self.assertEqual(res_hi_abs, val & MANT) - - res_hi_neg_abs = run([f"v_mov_b32 v1, {w_hi:#x}", "v_pack_b32_f16 v0, -|v1|, v1 op_sel:[1,0,0]"])[0] & 0xFFFF - self.assertEqual(res_hi_neg_abs, (val & MANT) | SIGN) - - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_pack_u16.py b/tests/semantic/test_pack_u16.py deleted file mode 100644 index 3c06c678e..000000000 --- a/tests/semantic/test_pack_u16.py +++ /dev/null @@ -1,624 +0,0 @@ -"""Semantic interpreter tests for AMD RDNA vector integer packing (v_pack_b32_u16). - -AMD RDNA VALU Instruction Set Architecture (ISA): - v_pack_b32_u16 dst, src0, src1 [op_sel:[s0, s1]] [clamp] - Operation: Packs two 16-bit integer values into a 32-bit vector register (VGPR). - - dst[15:0] = half_word(src0, op_sel[0]) [clamped to [0, 0xFFFF] if clamp] - - dst[31:16] = half_word(src1, op_sel[1]) [clamped to [0, 0xFFFF] if clamp] - -Modifiers and Semantics: - - op_sel:[s0, s1]: - s0 = 0: select low half-word (bits 15:0) of src0 - s0 = 1: select high half-word (bits 31:16) of src0 - s1 = 0: select low half-word (bits 15:0) of src1 - s1 = 1: select high half-word (bits 31:16) of src1 - - Half-word Truncation: - When clamp is not asserted, bits outside the selected 16-bit window are - discarded (masked to 0xFFFF). - - Clamping / Saturation: - When clamp is asserted on integer packing, values outside [0, 65535] saturate - to the unsigned 16-bit limits: - - Unsigned saturation (UClamp): values > 0xFFFF saturate to 0xFFFF. - - Signed saturation (SClamp): values < 0 saturate to 0; values > 0xFFFF - saturate to 0xFFFF. - -In SPIR-V (as executed in spirv_mini_interp.py): - 1. Logical shift/mask/clamp formulation: - %s0_val = OpShiftRightLogical %uint %src0 %c16 (if op_sel[0]) - %h0 = OpExtInst %uint %glsl UClamp %s0_val %c0 %c65535 (or OpBitwiseAnd %s0_val %c65535) - %s1_val = OpShiftRightLogical %uint %src1 %c16 (if op_sel[1]) - %h1 = OpExtInst %uint %glsl UClamp %s1_val %c0 %c65535 (or OpBitwiseAnd %s1_val %c65535) - %h1_hi = OpShiftLeftLogical %uint %h1 %c16 - %res = OpBitwiseOr %uint %h0 %h1_hi - 2. Bitfield extract/insert formulation: - %h0 = OpBitFieldUExtract %uint %src0 %off0 %c16 - %h1 = OpBitFieldUExtract %uint %src1 %off1 %c16 - %res = OpBitFieldInsert %uint %h0 %h1 %c16 %c16 - -Standard library only: Python 3.9+ compatible, zero game data, zero proprietary assets. -""" -from __future__ import annotations - -import itertools -import os -import random -import struct -import sys -import tempfile -import unittest -import warnings - -HERE = os.path.dirname(os.path.abspath(__file__)) -ROOT = os.path.dirname(os.path.dirname(HERE)) -TOOLS_DIR = os.environ.get("LEONIDA_TOOLS_DIR") or os.path.join(ROOT, "tools") - -sys.dont_write_bytecode = True -if TOOLS_DIR not in sys.path: - sys.path.insert(0, TOOLS_DIR) -if HERE not in sys.path: - sys.path.insert(0, HERE) - -import rdna2spirv -import spirv_mini_interp as si - -MASK16 = 0xFFFF -MASK32 = 0xFFFFFFFF -STUB_DXBC = b"DXBC" + bytes(24) + struct.pack(" int: - """Interpret a 32-bit unsigned word as a signed two's-complement integer.""" - x &= MASK32 - return x - (1 << 32) if x & 0x80000000 else x - - -def ref_extract_half(val: int, hi: bool = False) -> int: - """Extract the low or high 16-bit half-word with 16-bit truncation.""" - val &= MASK32 - return ((val >> 16) if hi else val) & MASK16 - - -def ref_clamp_u16(val: int, signed: bool = False) -> int: - """Clamp integer value to unsigned 16-bit range [0, 65535].""" - if signed: - s = s32(val) - if s < 0: - return 0 - if s > MASK16: - return MASK16 - return s & MASK16 - u = val & MASK32 - return min(u, MASK16) - - -def ref_pack_b32_u16( - s0: int, - s1: int, - op_sel: tuple[int, int] = (0, 0), - clamp: bool = False, - signed: bool = False, -) -> int: - """Pure-Python reference oracle for RDNA2 vector integer packing v_pack_b32_u16.""" - s0 &= MASK32 - s1 &= MASK32 - val0 = (s0 >> 16) if op_sel[0] else s0 - val1 = (s1 >> 16) if op_sel[1] else s1 - - if clamp: - h0 = ref_clamp_u16(val0, signed=signed) - h1 = ref_clamp_u16(val1, signed=signed) - else: - h0 = val0 & MASK16 - h1 = val1 & MASK16 - - return (h0 & MASK16) | ((h1 & MASK16) << 16) - - -def ref_decompose_pack(dword: int) -> tuple[int, int]: - """Decompose a 32-bit packed word into (lo_u16, hi_u16).""" - dword &= MASK32 - return dword & MASK16, (dword >> 16) & MASK16 - - -class PackU16Interpreter: - """A lightweight semantic interpreter for VALU integer packing instructions. - - Maintains vector (VGPR) and scalar (SGPR) register banks and executes - tokenized or text assembly instructions modeling v_pack_b32_u16. - """ - - def __init__(self): - self.vgprs = [0] * 256 - self.sgprs = [0] * 106 - - def parse_operand(self, token: str) -> int: - """Resolve a register or literal operand to its current 32-bit unsigned value.""" - token = token.strip().rstrip(",") - if not token: - raise ValueError("Empty operand token") - lower = token.lower() - if lower.startswith("v") and lower[1:].isdigit(): - idx = int(lower[1:]) - if 0 <= idx < 256: - return self.vgprs[idx] & MASK32 - raise IndexError(f"VGPR index out of range: {token}") - if lower.startswith("s") and lower[1:].isdigit(): - idx = int(lower[1:]) - if 0 <= idx < 106: - return self.sgprs[idx] & MASK32 - raise IndexError(f"SGPR index out of range: {token}") - if lower.startswith("0x") or lower.startswith("-0x"): - return int(token, 16) & MASK32 - try: - return int(token) & MASK32 - except ValueError: - raise ValueError(f"Invalid operand token: {token}") - - def execute_line(self, line: str) -> None: - """Parse and execute a single RDNA assembly line.""" - line = line.split(";", 1)[0].split("//", 1)[0].strip() - if not line: - return - - parts = line.split(None, 1) - opcode = parts[0].lower() - args_str = parts[1] if len(parts) > 1 else "" - - # Tokenize args by commas/whitespace while preserving brackets like op_sel:[x,y] - tokens = [] - buf = [] - bracket_depth = 0 - for char in args_str: - if char == "[": - bracket_depth += 1 - buf.append(char) - elif char == "]": - bracket_depth = max(0, bracket_depth - 1) - buf.append(char) - elif char in (",", " ", "\t") and bracket_depth == 0: - if buf: - tokens.append("".join(buf).strip()) - buf = [] - else: - buf.append(char) - if buf: - tokens.append("".join(buf).strip()) - tokens = [t for t in tokens if t] - - if opcode in ("v_mov_b32", "s_mov_b32"): - if len(tokens) < 2: - raise ValueError(f"Instruction {opcode} requires at least dst and src") - dst_token = tokens[0].lower() - val = self.parse_operand(tokens[1]) - if dst_token.startswith("v") and dst_token[1:].isdigit(): - self.vgprs[int(dst_token[1:])] = val - elif dst_token.startswith("s") and dst_token[1:].isdigit(): - self.sgprs[int(dst_token[1:])] = val - else: - raise ValueError(f"Invalid destination register: {dst_token}") - - elif opcode == "v_pack_b32_u16": - if len(tokens) < 3: - raise ValueError("v_pack_b32_u16 requires at least dst, src0, src1") - dst_token = tokens[0].lower() - if not (dst_token.startswith("v") and dst_token[1:].isdigit()): - raise ValueError(f"Destination must be a VGPR: {dst_token}") - dst_idx = int(dst_token[1:]) - if not (0 <= dst_idx < 256): - raise IndexError(f"VGPR index out of range: {dst_token}") - - s0_val = self.parse_operand(tokens[1]) - s1_val = self.parse_operand(tokens[2]) - - op_sel = (0, 0) - clamp = False - - for mod in tokens[3:]: - mod_lower = mod.lower() - if mod_lower == "clamp": - clamp = True - elif mod_lower.startswith("op_sel:[") and mod_lower.endswith("]"): - inner = mod_lower[8:-1].split(",") - if len(inner) != 2: - raise ValueError(f"Malformed op_sel modifier: {mod}") - op_sel = (int(inner[0].strip()), int(inner[1].strip())) - else: - raise ValueError(f"Unrecognized modifier: {mod}") - - res = ref_pack_b32_u16(s0_val, s1_val, op_sel=op_sel, clamp=clamp) - self.vgprs[dst_idx] = res - - else: - raise NotImplementedError(f"Unsupported opcode: {opcode}") - - def execute_program(self, program: str) -> None: - """Execute a multiline assembly sequence.""" - for line in program.strip().splitlines(): - self.execute_line(line) - - -def run_spirv_pack_logical( - s0: int, - s1: int, - op_sel: tuple[int, int] = (0, 0), - clamp: bool = False, - signed: bool = False, -) -> int: - """Execute SPIR-V shader sequence modeling v_pack_b32_u16 via shift/bitwise/clamp ops.""" - s0_u = s0 & MASK32 - s1_u = s1 & MASK32 - - h0_extract = ( - "%s0_val = OpShiftRightLogical %uint %c_s0 %c16\n" - if op_sel[0] - else "%s0_val = OpCopyObject %uint %c_s0\n" - ) - h1_extract = ( - "%s1_val = OpShiftRightLogical %uint %c_s1 %c16\n" - if op_sel[1] - else "%s1_val = OpCopyObject %uint %c_s1\n" - ) - - if clamp: - clamp_op = "SClamp" if signed else "UClamp" - h0_proc = f"%h0 = OpExtInst %uint %glsl {clamp_op} %s0_val %c0 %c65535\n" - h1_proc = f"%h1 = OpExtInst %uint %glsl {clamp_op} %s1_val %c0 %c65535\n" - else: - h0_proc = "%h0 = OpBitwiseAnd %uint %s0_val %c65535\n" - h1_proc = "%h1 = OpBitwiseAnd %uint %s1_val %c65535\n" - - spv = f"""OpCapability Shader -%glsl = OpExtInstImport "GLSL.std.450" -OpMemoryModel Logical GLSL450 -OpEntryPoint Fragment %main "main" %out -%void = OpTypeVoid -%fn = OpTypeFunction %void -%uint = OpTypeInt 32 0 -%_ptr_Output_uint = OpTypePointer Output %uint -%out = OpVariable %_ptr_Output_uint Output -%c_s0 = OpConstant %uint {s0_u} -%c_s1 = OpConstant %uint {s1_u} -%c0 = OpConstant %uint 0 -%c16 = OpConstant %uint 16 -%c65535 = OpConstant %uint 65535 -%main = OpFunction %void None %fn -%entry = OpLabel -{h0_extract}{h0_proc}{h1_extract}{h1_proc}%h1_hi = OpShiftLeftLogical %uint %h1 %c16 -%res = OpBitwiseOr %uint %h0 %h1_hi -OpStore %out %res -OpReturn -OpFunctionEnd -""" - return si.run_fragment(spv)["%out"][0] - - -def run_spirv_pack_bitfield( - s0: int, - s1: int, - op_sel: tuple[int, int] = (0, 0), -) -> int: - """Execute SPIR-V shader sequence modeling unclamped v_pack_b32_u16 via bitfield ops.""" - off0 = 16 if op_sel[0] else 0 - off1 = 16 if op_sel[1] else 0 - spv = f"""OpCapability Shader -%glsl = OpExtInstImport "GLSL.std.450" -OpMemoryModel Logical GLSL450 -OpEntryPoint Fragment %main "main" %out -%void = OpTypeVoid -%fn = OpTypeFunction %void -%uint = OpTypeInt 32 0 -%_ptr_Output_uint = OpTypePointer Output %uint -%out = OpVariable %_ptr_Output_uint Output -%c_s0 = OpConstant %uint {s0 & MASK32} -%c_s1 = OpConstant %uint {s1 & MASK32} -%c16 = OpConstant %uint 16 -%c_off0 = OpConstant %uint {off0} -%c_off1 = OpConstant %uint {off1} -%main = OpFunction %void None %fn -%entry = OpLabel -%h0 = OpBitFieldUExtract %uint %c_s0 %c_off0 %c16 -%h1 = OpBitFieldUExtract %uint %c_s1 %c_off1 %c16 -%res = OpBitFieldInsert %uint %h0 %h1 %c16 %c16 -OpStore %out %res -OpReturn -OpFunctionEnd -""" - return si.run_fragment(spv)["%out"][0] - - -class TestPackU16ReferenceOracle(unittest.TestCase): - """Unit tests for the independent Python reference oracle modeling v_pack_b32_u16.""" - - def test_basic_packing_identity(self): - self.assertEqual(ref_pack_b32_u16(0, 0), 0) - self.assertEqual(ref_pack_b32_u16(0x1234, 0x5678), 0x56781234) - self.assertEqual(ref_pack_b32_u16(0x00FF, 0xFF00), 0xFF0000FF) - self.assertEqual(ref_pack_b32_u16(0xAAAA, 0x5555), 0x5555AAAA) - - def test_low_half_truncation_without_clamp(self): - self.assertEqual(ref_pack_b32_u16(0xDEAD1234, 0xBEEF5678), 0x56781234) - self.assertEqual(ref_pack_b32_u16(0xFFFFFFFF, 0xFFFFFFFF), 0xFFFFFFFF) - self.assertEqual(ref_pack_b32_u16(0xFFFF0000, 0xFFFF0000), 0x00000000) - self.assertEqual(ref_pack_b32_u16(0x12340001, 0x56780002), 0x00020001) - - def test_op_sel_permutations(self): - s0 = 0xA1B2C3D4 - s1 = 0xE5F60718 - - self.assertEqual(ref_pack_b32_u16(s0, s1, op_sel=(0, 0)), 0x0718C3D4) - self.assertEqual(ref_pack_b32_u16(s0, s1, op_sel=(1, 0)), 0x0718A1B2) - self.assertEqual(ref_pack_b32_u16(s0, s1, op_sel=(0, 1)), 0xE5F6C3D4) - self.assertEqual(ref_pack_b32_u16(s0, s1, op_sel=(1, 1)), 0xE5F6A1B2) - - def test_unsigned_clamping(self): - self.assertEqual(ref_pack_b32_u16(100, 200, clamp=True), (200 << 16) | 100) - self.assertEqual(ref_pack_b32_u16(65535, 65535, clamp=True), 0xFFFFFFFF) - - self.assertEqual(ref_pack_b32_u16(65536, 10, clamp=True), (10 << 16) | 0xFFFF) - self.assertEqual(ref_pack_b32_u16(10, 70000, clamp=True), (0xFFFF << 16) | 10) - self.assertEqual(ref_pack_b32_u16(0xFFFFFFFF, 0xFFFFFFFF, clamp=True), 0xFFFFFFFF) - self.assertEqual(ref_pack_b32_u16(0x80000000, 0x7FFFFFFF, clamp=True), 0xFFFFFFFF) - - def test_signed_clamping(self): - self.assertEqual(ref_pack_b32_u16(-1, 500, clamp=True, signed=True), 500 << 16) - self.assertEqual(ref_pack_b32_u16(500, -100, clamp=True, signed=True), 500) - self.assertEqual(ref_pack_b32_u16(0x80000000, 0x80000000, clamp=True, signed=True), 0) - - self.assertEqual(ref_pack_b32_u16(70000, -5, clamp=True, signed=True), 0x0000FFFF) - self.assertEqual(ref_pack_b32_u16(-5, 0x7FFFFFFF, clamp=True, signed=True), 0xFFFF0000) - - def test_clamping_with_op_sel(self): - s0 = 50 - s1 = 100000 - - self.assertEqual(ref_pack_b32_u16(s0, s1, op_sel=(0, 0), clamp=True), (0xFFFF << 16) | 50) - self.assertEqual(ref_pack_b32_u16(s0, s1, op_sel=(1, 0), clamp=True), 0xFFFF0000) - self.assertEqual(ref_pack_b32_u16(s0, s1, op_sel=(0, 1), clamp=True), (1 << 16) | 50) - self.assertEqual(ref_pack_b32_u16(s0, s1, op_sel=(1, 1), clamp=True), 1 << 16) - - def test_self_packing_broadcast_and_swap(self): - v = 0x12345678 - - self.assertEqual(ref_pack_b32_u16(v, v, op_sel=(0, 0)), 0x56785678) - self.assertEqual(ref_pack_b32_u16(v, v, op_sel=(1, 1)), 0x12341234) - self.assertEqual(ref_pack_b32_u16(v, v, op_sel=(1, 0)), 0x56781234) - self.assertEqual(ref_pack_b32_u16(v, v, op_sel=(0, 1)), 0x12345678) - - def test_decomposition_oracle(self): - self.assertEqual(ref_decompose_pack(0x56781234), (0x1234, 0x5678)) - self.assertEqual(ref_decompose_pack(0xFFFFFFFF), (0xFFFF, 0xFFFF)) - self.assertEqual(ref_decompose_pack(0x00000000), (0, 0)) - - test_pairs = [(0x1111, 0x2222), (0xDEAD, 0xBEEF), (0x0001, 0x8000), (0xFFFF, 0x0000)] - for lo, hi in test_pairs: - dword = ref_pack_b32_u16(lo, hi) - self.assertEqual(ref_decompose_pack(dword), (lo, hi)) - - -class TestPackU16InterpreterExecution(unittest.TestCase): - """Unit tests for the PackU16Interpreter executing assembly programs.""" - - def setUp(self): - self.interp = PackU16Interpreter() - - def test_single_pack_instruction(self): - program = """ - v_mov_b32 v1, 0x1234 - v_mov_b32 v2, 0x5678 - v_pack_b32_u16 v0, v1, v2 - """ - self.interp.execute_program(program) - self.assertEqual(self.interp.vgprs[0], 0x56781234) - - def test_op_sel_modifier_in_assembly(self): - program = """ - v_mov_b32 v1, 0xA1B2C3D4 - v_mov_b32 v2, 0xE5F60718 - v_pack_b32_u16 v0, v1, v2 op_sel:[1,0] - """ - self.interp.execute_program(program) - self.assertEqual(self.interp.vgprs[0], 0x0718A1B2) - - def test_clamp_modifier_in_assembly(self): - program = """ - v_mov_b32 v1, 100000 - v_mov_b32 v2, 20 - v_pack_b32_u16 v0, v1, v2 clamp - """ - self.interp.execute_program(program) - self.assertEqual(self.interp.vgprs[0], (20 << 16) | 0xFFFF) - - def test_vertex_attribute_packing_pipeline(self): - """Pack 4 normalized 16-bit halfword vertex attributes into 2 32-bit registers.""" - program = """ - v_mov_b32 v0, 0x0001 - v_mov_b32 v1, 0x0002 - v_mov_b32 v2, 0x0003 - v_mov_b32 v3, 0x0004 - v_pack_b32_u16 v4, v0, v1 - v_pack_b32_u16 v5, v2, v3 - """ - self.interp.execute_program(program) - self.assertEqual(self.interp.vgprs[4], 0x00020001) - self.assertEqual(self.interp.vgprs[5], 0x00040003) - - def test_high_halfword_swap(self): - program = """ - v_mov_b32 v1, 0x12345678 - v_pack_b32_u16 v0, v1, v1 op_sel:[1,0] - """ - self.interp.execute_program(program) - self.assertEqual(self.interp.vgprs[0], 0x56781234) - - def test_chained_packing_with_scalar_and_literals(self): - program = """ - s_mov_b32 s0, 0xABCD - v_mov_b32 v1, 0x1234 - v_pack_b32_u16 v0, v1, s0 - v_pack_b32_u16 v2, v0, 0x9999 op_sel:[1,0] - """ - self.interp.execute_program(program) - self.assertEqual(self.interp.vgprs[0], 0xABCD1234) - # v0 high half is 0xABCD, literal low half is 0x9999 - self.assertEqual(self.interp.vgprs[2], 0x9999ABCD) - - def test_invalid_syntax_and_bounds_handling(self): - with self.assertRaises(ValueError): - self.interp.execute_line("v_pack_b32_u16 v0, v1") - with self.assertRaises(NotImplementedError): - self.interp.execute_line("v_unknown_op v0, v1") - with self.assertRaises(IndexError): - self.interp.execute_line("v_pack_b32_u16 v999, v0, v1") - - -class TestPackU16SpirvInterp(unittest.TestCase): - """Semantic tests executing SPIR-V code in spirv_mini_interp and cross-checking oracles.""" - - VECTORS = ( - (0, 0), - (1, 1), - (0x1234, 0x5678), - (0xA1B2C3D4, 0xE5F60718), - (0xFFFFFFFF, 0x00000000), - (0x00000000, 0xFFFFFFFF), - (0x80000000, 0x7FFFFFFF), - (0x55555555, 0xAAAAAAAA), - (0x0000FFFF, 0xFFFF0000), - (0x00010000, 0x00020000), - ) - - def test_spirv_unclamped_all_op_sel_modes(self): - for s0, s1 in self.VECTORS: - for op_sel in itertools.product((0, 1), repeat=2): - with self.subTest(s0=hex(s0), s1=hex(s1), op_sel=op_sel): - expected = ref_pack_b32_u16(s0, s1, op_sel=op_sel, clamp=False) - got = run_spirv_pack_logical(s0, s1, op_sel=op_sel, clamp=False) - self.assertEqual(got, expected) - - def test_spirv_unsigned_clamping(self): - clamp_vectors = ( - (0, 0), - (100, 200), - (65535, 65535), - (65536, 100), - (100, 70000), - (0xFFFFFFFF, 0xFFFFFFFF), - (0x80000000, 0x7FFFFFFF), - (0x00010000, 0x00020000), - ) - for s0, s1 in clamp_vectors: - for op_sel in itertools.product((0, 1), repeat=2): - with self.subTest(s0=hex(s0), s1=hex(s1), op_sel=op_sel): - expected = ref_pack_b32_u16(s0, s1, op_sel=op_sel, clamp=True, signed=False) - got = run_spirv_pack_logical(s0, s1, op_sel=op_sel, clamp=True, signed=False) - self.assertEqual(got, expected) - - def test_spirv_signed_clamping(self): - signed_vectors = ( - (0, 0), - (-1, 500), - (500, -100), - (-5000, -5000), - (70000, -1), - (-1, 0x7FFFFFFF), - (0x80000000, 0x7FFFFFFF), - ) - for s0, s1 in signed_vectors: - for op_sel in itertools.product((0, 1), repeat=2): - with self.subTest(s0=s0, s1=s1, op_sel=op_sel): - expected = ref_pack_b32_u16(s0, s1, op_sel=op_sel, clamp=True, signed=True) - got = run_spirv_pack_logical(s0, s1, op_sel=op_sel, clamp=True, signed=True) - self.assertEqual(got, expected) - - def test_spirv_bitfield_equivalence(self): - for s0, s1 in self.VECTORS: - for op_sel in itertools.product((0, 1), repeat=2): - with self.subTest(s0=hex(s0), s1=hex(s1), op_sel=op_sel): - logical_res = run_spirv_pack_logical(s0, s1, op_sel=op_sel, clamp=False) - bitfield_res = run_spirv_pack_bitfield(s0, s1, op_sel=op_sel) - self.assertEqual(bitfield_res, logical_res) - - def test_deterministic_fuzzing_matches_oracle(self): - rng = random.Random(0x1616) - for _ in range(40): - s0 = rng.getrandbits(32) - s1 = rng.getrandbits(32) - op_sel = (rng.choice((0, 1)), rng.choice((0, 1))) - clamp = rng.choice((True, False)) - - expected = ref_pack_b32_u16(s0, s1, op_sel=op_sel, clamp=clamp) - got = run_spirv_pack_logical(s0, s1, op_sel=op_sel, clamp=clamp) - self.assertEqual(got, expected) - - -class TestNegativeControls(unittest.TestCase): - """Negative controls ensuring mutated packing or missing masks fail assertions.""" - - def test_operand_order_reversal_detected(self): - s0, s1 = 0x11112222, 0x33334444 - correct = ref_pack_b32_u16(s0, s1, op_sel=(0, 0)) - reversed_operands = ref_pack_b32_u16(s1, s0, op_sel=(0, 0)) - self.assertNotEqual(correct, reversed_operands) - - def test_missing_high_word_shift_detected(self): - s0, s1 = 0x1234, 0x5678 - correct = ref_pack_b32_u16(s0, s1) - sabotaged_no_shift = (s0 & MASK16) | (s1 & MASK16) - self.assertNotEqual(correct, sabotaged_no_shift) - - def test_off_by_one_shift_detected(self): - s0, s1 = 0x1234, 0x5678 - correct = ref_pack_b32_u16(s0, s1) - sabotaged_shift_15 = (s0 & MASK16) | ((s1 & MASK16) << 15) - self.assertNotEqual(correct, sabotaged_shift_15) - - def test_missing_mask_truncation_detected(self): - s0, s1 = 0xDEAD1234, 0xBEEF5678 - correct = ref_pack_b32_u16(s0, s1) - sabotaged_no_truncation = (s0 | (s1 << 16)) & MASK32 - self.assertNotEqual(correct, sabotaged_no_truncation) - - def test_modulo_wrap_instead_of_clamp_detected(self): - s0, s1 = 70000, 20 - clamped = ref_pack_b32_u16(s0, s1, clamp=True) - wrapped = ref_pack_b32_u16(s0, s1, clamp=False) - self.assertNotEqual(clamped, wrapped) - - def test_signed_vs_unsigned_clamp_discrepancy_detected(self): - s0, s1 = -10, 10 - uclamped = ref_pack_b32_u16(s0, s1, clamp=True, signed=False) - sclamped = ref_pack_b32_u16(s0, s1, clamp=True, signed=True) - self.assertNotEqual(uclamped, sclamped) - - def test_inverted_op_sel_detected(self): - s0, s1 = 0x12345678, 0x9ABCDEF0 - correct = ref_pack_b32_u16(s0, s1, op_sel=(0, 0)) - inverted = ref_pack_b32_u16(s0, s1, op_sel=(1, 1)) - self.assertNotEqual(correct, inverted) - - -class TestRdna2SpirvTranslatorStatus(unittest.TestCase): - """Verify translator behavior on synthetic RDNA assembly containing v_pack_b32_u16.""" - - def test_v_pack_b32_u16_assembly_translation_status(self): - shader_text = "; ps_pack_test\n\tv_pack_b32_u16 v0, v1, v2\n\texp mrt0 v0, v0, v0, v0 done vm\n\ts_endpgm\n" - with tempfile.TemporaryDirectory() as tmp: - disasm_dir = os.path.join(tmp, "disasm") - os.mkdir(disasm_dir) - src_path = os.path.join(disasm_dir, "ps_pack_test.s") - with open(src_path, "w", encoding="utf-8") as f: - f.write(shader_text) - with open(os.path.join(tmp, "ps_pack_test.dxbc"), "wb") as f: - f.write(STUB_DXBC) - - with warnings.catch_warnings(): - warnings.simplefilter("ignore", ResourceWarning) - try: - spv = rdna2spirv.translate(src_path) - self.assertIsInstance(spv, str) - except rdna2spirv.Unsupported as e: - self.assertIn("v_pack_b32_u16", str(e)) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_perm_known_selector.py b/tests/semantic/test_perm_known_selector.py deleted file mode 100644 index e413f4c0f..000000000 --- a/tests/semantic/test_perm_known_selector.py +++ /dev/null @@ -1,29 +0,0 @@ -"""Constant byte selectors use direct extracts; a clobbered SGPR uses the dynamic path.""" -import sys -import unittest -from pathlib import Path - -sys.path.insert(0, str(Path(__file__).resolve().parent)) -from support import mrt0_words, translate_lines # noqa: E402 - - -class PermKnownSelectorTests(unittest.TestCase): - @classmethod - def setUpClass(cls): - fixture = Path(__file__).with_name("fixtures") / "perm_known_selector.asm" - lines = [line for line in fixture.read_text(encoding="ascii").splitlines() - if line and not line.startswith(";")] - cls.spvasm = translate_lines("ps_perm_known_selector", lines) - - def test_selector_values(self): - self.assertEqual(mrt0_words(self.spvasm), [0xFF008C80, 0xFF0000FF, 0x80808080, 0x13E49B80]) - - def test_only_clobbered_selector_dispatches_at_runtime(self): - # The dynamic lowering emits one >= 13 check per byte, at most for the one clobbered selector; since SHADER-315 - # folds scalar ALU on constants, the clobbered selector is known at translate time too and none is emitted. - # test_selector_values still checks every word. - self.assertIn(self.spvasm.count("OpUGreaterThanEqual"), (0, 4)) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_permlane_fi.py b/tests/semantic/test_permlane_fi.py deleted file mode 100644 index f59b7d1ed..000000000 --- a/tests/semantic/test_permlane_fi.py +++ /dev/null @@ -1,45 +0,0 @@ -"""v_permlane16_b32 / v_permlanex16_b32 with the source lane off in EXEC (SHADER-74), wave32, CPU values. - -The input is the GPU test runtime/test/shaders/cs_w32_permlane_fi (hand-written, no game data; fixture from -regen_fixtures.py). EXEC is 0x55555555, so the source lane of every active lane is off, except in the identity -case. Expected words are the RDNA2 measurement from issue #374 (op_sel:[FI, BOUND_CTRL]): -FI=1 returns the off lane's value; FI=0 leaves the destination alone (BOUND_CTRL=0) or writes 0 (BOUND_CTRL=1); -a source lane that is on gives its value whatever FI / BOUND_CTRL are. -""" -import struct -import unittest - -import support -import spirv_mini_interp as si - -# 4 user SGPRs (the output V#), 32x1x1 threads: build.py's default header with a 32-wide group. -FSSM = bytearray(0x148) -struct.pack_into("<4I", FSSM, 0x138, 0x8088, 32, 1, 1) -FSSM = bytes(FSSM) -VSHARP = [0, 0, 0x1000, 0x31016FAC] - -# permlane16 / permlanex16 x (FI=0 BC=0, FI=0 BC=1, FI=1 BC=0, source on); see the .asm header. -EXPECTED = [1000, 0, 4, 1, 1000, 0, 52, 49] -NAMES = ["permlane16 FI=0 BC=0 (not written)", "permlane16 FI=0 BC=1 (0)", "permlane16 FI=1 (value)", - "permlane16 source on", "permlanex16 FI=0 BC=0 (not written)", "permlanex16 FI=0 BC=1 (0)", - "permlanex16 FI=1 (value)", "permlanex16 source on"] - - -def run(spv): - memory = si.run_workgroup( - spv, 32, 32, - inputs_for=lambda i: {"%wg_id": (0, 0, 0), "%local_id": (i, 0, 0), "%sg_lane": i}, - push_constants=VSHARP + [0] * 28, memory={}) - return [memory.get(4 * k) for k in range(8)] - - -class PermlaneSourceOff(unittest.TestCase): - def test_all_cases(self): - got = run(support.translate_fixture("cs_w32_permlane_fi", fssm=FSSM)) - for i, name in enumerate(NAMES): - with self.subTest(case=name): - self.assertEqual(got[i], EXPECTED[i]) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_pk_f16_clamp.py b/tests/semantic/test_pk_f16_clamp.py deleted file mode 100644 index deaf56bf1..000000000 --- a/tests/semantic/test_pk_f16_clamp.py +++ /dev/null @@ -1,95 +0,0 @@ -"""Semantic tests for the clamp bit on packed f16 VOP3P ops (v_pk_add/mul/fma/max/min_f16 ... clamp). - -With clamp, each f16 half of the result is clamped to [0.0, 1.0] (RDNA2 ISA, VOP3P CLMP), the same as the scalar -f16 ops. The translator clamps the vec2 with GLSL FClamp; the semantic interpreter used to take FClamp/FMax on -scalars only and failed with a TypeError on any packed clamp. Both halves leave through exp with a zero high half. -""" -import os -import struct -import sys -import tempfile -import unittest -import warnings - -HERE = os.path.dirname(os.path.abspath(__file__)) -ROOT = os.path.dirname(os.path.dirname(HERE)) -TOOLS_DIR = os.environ.get("LEONIDA_TOOLS_DIR") or os.path.join(ROOT, "tools") - -sys.dont_write_bytecode = True -sys.path.insert(0, TOOLS_DIR) -sys.path.insert(0, HERE) - -import rdna2spirv # noqa: E402 -import spirv_mini_interp as si # noqa: E402 - -STUB_DXBC = b"DXBC" + bytes(24) + struct.pack("> 16 == 0x4000 and hi >> 16 == 0x4000, (hex(lo), hex(hi)) - return (lo & 0xFFFF) | ((hi & 0xFFFF) << 16), spv - - -def _ps_case_lines(op, c, clamp): - return [ln.replace("v_mov_b32_e32 ", "v_mov_b32 ") for ln in probe.case_instruction(op, c, clamp)] - - -class PkInt16ClampSemanticTests(unittest.TestCase): - def test_all_probe_cases_plain_and_clamp(self): - ctrl_diffs = 0 - for op in probe.OPS: - for c in probe.CASES: - want_plain = probe.expected_pk_int16(op, c.src0, c.src1, sel=c.sel, selhi=c.selhi, clamp=False) - want_clamp = probe.expected_pk_int16(op, c.src0, c.src1, sel=c.sel, selhi=c.selhi, clamp=True) - with self.subTest(op=op, case=c.name): - got_plain, _ = _run_v2(_ps_case_lines(op, c, False)) - got_clamp, _ = _run_v2(_ps_case_lines(op, c, True)) - self.assertEqual(got_plain, want_plain) - self.assertEqual(got_clamp, want_clamp) - if op in probe.TARGET_OPS: - self.assertEqual(got_clamp, got_plain) - elif got_clamp != got_plain: - ctrl_diffs += 1 - self.assertGreater(ctrl_diffs, 0) - - def test_spirv_emits_no_saturation_on_target_ops(self): - for op in probe.TARGET_OPS: - with self.subTest(op=op): - got_plain, spv_plain = _run_v2([ - "v_mov_b32 v0, 0x02000100", - "v_mov_b32 v1, 0x01000200", - f"{op} v2, v0, v1", - ]) - got_clamp, spv_clamp = _run_v2([ - "v_mov_b32 v0, 0x02000100", - "v_mov_b32 v1, 0x01000200", - f"{op} v2, v0, v1 clamp", - ]) - self.assertEqual( - got_clamp, - probe.expected_pk_int16(op, 0x02000100, 0x01000200, clamp=True), - ) - self.assertEqual(got_clamp, got_plain) - self.assertEqual(spv_clamp, spv_plain) - self.assertNotIn("SClamp", spv_clamp) - if op != "v_pk_min_u16": - self.assertNotIn("UMin", spv_clamp) - else: - self.assertFalse(any("UMin " in ln and "%cffff" in ln for ln in spv_clamp.splitlines())) - - _, ctrl_spv = _run_v2([ - "v_mov_b32 v0, 0xffffffff", - "v_mov_b32 v1, 0x00020002", - "v_pk_add_u16 v2, v0, v1 clamp", - ]) - self.assertTrue(any("UMin " in ln and "%cffff" in ln for ln in ctrl_spv.splitlines())) - - def test_inactive_exec_preserves_dst(self): - sentinel = 0xA5A55A5A - for op in probe.TARGET_OPS: - with self.subTest(op=op): - got, _ = _run_v2([ - "v_mov_b32 v0, 0xffffffff", - "v_mov_b32 v1, 0x00020003", - f"v_mov_b32 v2, {sentinel:#010x}", - "s_mov_b32 exec_lo, 0", - f"{op} v2, v0, v1 clamp", - "s_mov_b32 exec_lo, -1", - ]) - self.assertEqual(got, sentinel) - - def test_rejected_invalid_modifiers(self): - for op in probe.TARGET_OPS: - for bad in ( - f"{op} v2, v0, v1 neg_lo:[1,0]", - f"{op} v2, v0, v1 neg_hi:[0,1]", - f"{op} v2, v0, v1 mul:2", - f"{op} v2, v0, v1 div:2", - f"{op} v2, v0, v1 op_sel:[0]", - f"{op} v2, v0, v1 clamp neg_lo:[1,0]", - ): - with self.subTest(line=bad): - with self.assertRaises(rdna2spirv.Unsupported): - _translate(["v_mov_b32 v0, 1", "v_mov_b32 v1, 2", bad, "exp mrt0 v2, v2, v2, v2 done vm", "s_endpgm"]) - - def test_spirv_val_vulkan12(self): - spirv_as = shutil.which("spirv-as") - spirv_val = shutil.which("spirv-val") - if not spirv_as or not spirv_val: - self.skipTest("spirv-as / spirv-val not on PATH") - body = [ - "s_mov_b32 s4, 0x0300fffe", - "v_mov_b32 v0, 0x80007fff", - "v_mov_b32 v1, 0x02000400", - "v_pk_mul_lo_u16 v2, v0, v1 clamp", - "v_pk_mul_lo_u16 v2, v2, -16 op_sel:[1,0] op_sel_hi:[0,1] clamp", - "v_pk_max_u16 v3, s4, 0x12345678 op_sel:[0,1] op_sel_hi:[1,0] clamp", - "v_pk_min_u16 v3, v3, v2 clamp", - "v_pk_max_i16 v4, v2, v3 clamp", - "v_pk_min_i16 v2, v4, v0 clamp", - "v_pk_add_u16 v3, v0, v1 clamp", - "v_xor_b32 v2, v2, v3", - ] - _, spv = _run_v2(body) - with tempfile.TemporaryDirectory() as td: - spvasm = os.path.join(td, "shader.spvasm") - spvbin = os.path.join(td, "shader.spv") - with open(spvasm, "w", encoding="utf-8", newline="\n") as f: - f.write(spv) - subprocess.run([spirv_as, "--target-env", "vulkan1.2", spvasm, "-o", spvbin], check=True) - subprocess.run([spirv_val, "--target-env", "vulkan1.2", spvbin], check=True) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_pk_mul_lo_const.py b/tests/semantic/test_pk_mul_lo_const.py deleted file mode 100644 index c438779b2..000000000 --- a/tests/semantic/test_pk_mul_lo_const.py +++ /dev/null @@ -1,38 +0,0 @@ -"""v_pk_mul_lo_u16 with a constant operand against the words measured natively on RDNA2 (cs_pk_mul_lo_const.asm). - -The low 16 bits of each product are formed as ((x << 16) * y) >> 16: the AMD Windows driver dropped the `& 0xffff` of -(x * y) & 0xffff when the other half of the result was a constant 0. The interpreter cannot show that, the GPU test does; -this checks the values and that no mask-after-multiply is left.""" -import os -import re -import sys -import unittest - -import support - -sys.path.insert(0, os.path.join(support.ROOT, "runtime", "test", "shaders")) -from check import PK_MUL_LO_WORDS -from compute_fixture import compute_header - -OUT_V = [0, 0, 512, 0x31016FAC] # the output V# in s[0:3]: base 0, 512 bytes, FORMAT 32_FLOAT, DST_SEL xyzw -FILL = 0xEEEEEEEE - - -class PkMulLoConstTest(unittest.TestCase): - def test_hardware_words(self): - asm = os.path.join(support.ROOT, "runtime", "test", "shaders", "cs_pk_mul_lo_const.asm") - spv = support.translate_fixture("cs_pk_mul_lo_const", fssm=bytes(compute_header(asm))) - # Structure: no multiplication result goes straight through a 0xffff mask (the 16-bit wrap is the shift pair) - self.assertNotRegex(spv, r"(%\S+) = OpIMul %uint \S+ \S+\n\s+%\S+ = OpBitwiseAnd %uint \1 %cffff\b") - self.assertGreaterEqual(len(re.findall(r"OpIMul %uint", spv)), 8) - for lane in (0, 1): - with self.subTest(lane=lane): - memory = {16 * lane + 4 * k: FILL for k in range(4)} # the buffer fill the shader reads back - support.run_fragment( - spv, inputs={"%wg_id": (0, 0, 0), "%local_id": (lane, 0, 0)}, - push_constants=OUT_V + [0] * 28, memory=memory) - self.assertEqual([memory[16 * lane + 4 * k] for k in range(4)], PK_MUL_LO_WORDS[:4]) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_printed_encoding.py b/tests/semantic/test_printed_encoding.py deleted file mode 100644 index 2664e9d2c..000000000 --- a/tests/semantic/test_printed_encoding.py +++ /dev/null @@ -1,121 +0,0 @@ -"""A listing from shader_disasm.py is translated only if its printed encodings are the bytes in its blob. - -llvm-mc prints the instruction it decoded, not the bytes it read. Its gfx1013 decoder drops the VOP3 op_sel bits -(word 0, bits 14:11) of a 16-bit VOPC compare and re-encodes them as 0, so `v_cmp_lt_f16_e64 ... op_sel:[1,0]` in a -blob reads as a low-half compare in the listing. translate() used to compare printed and stored bytes only for -listings with undecodable words (the re-anchoring path); now a clean listing with a code range and a blob next to it -is checked too, with the same exceptions (same_encoding). Hand-built listing and blob, no game data. - - python -I tests/semantic/test_printed_encoding.py -v -""" -import os -import sys -import unittest - -HERE = os.path.dirname(os.path.abspath(__file__)) -if HERE not in sys.path: - sys.path.insert(0, HERE) - -from support import rdna2spirv, translate_listing # noqa: E402 - -# llvm-mc -mcpu=gfx1013 -mattr=+wavefrontsize64 -show-encoding (LLVM 21.1.8). -PROGRAM = [ - ("v_cmp_lt_f16_e64 s[4:5], v1, v2", "04 00 c9 d4 01 05 02 00"), - ("v_cndmask_b32_e64 v0, 0, 1.0, s[4:5]", "00 00 01 d5 80 e4 11 00"), - ("exp mrt0 v0, v0, v0, v0 done vm", "0f 18 00 f8 00 00 00 00"), - ("s_endpgm", "00 00 81 bf"), -] -CODE_START = 0x100 -NAME = "ps_printed_encoding" - - -def listing(program, start=CODE_START, end=None, how="scan"): - size = sum(len(bytes.fromhex(enc)) for _, enc in program) - end = start + size if end is None else end - lines = [f"; {NAME} code 0x{start:x}..0x{end:x} ({how}), gfx1013, 0 invalid words"] - for text, enc in program: - printed = ",".join(f"0x{b:02x}" for b in bytes.fromhex(enc)) - lines.append(f"\t{text:<40}; encoding: [{printed}]") - return ("\n".join(lines) + "\n").encode("utf-8") - - -def blob(program, start=CODE_START): - return bytes(start) + b"".join(bytes.fromhex(enc) for _, enc in program) - - -def with_byte(program, index, offset, value): - """`program` with byte `offset` of instruction `index` replaced (the stored bytes, not what LLVM printed).""" - text, enc = program[index] - raw = bytearray(bytes.fromhex(enc)) - raw[offset] = value - out = list(program) - out[index] = (text, raw.hex(" ")) - return out - - -class PrintedEncodingTest(unittest.TestCase): - def translate(self, data, fssm): - return translate_listing(NAME, data, fssm=fssm) - - def test_matching_blob_translates(self): - self.assertIn("OpEntryPoint Fragment", self.translate(listing(PROGRAM), blob(PROGRAM))) - - def test_dropped_vopc_op_sel_is_refused(self): - # The blob holds v_cmp_lt_f16_e64 with op_sel:[1,0] (word 0 bit 11); LLVM printed it without. - stored = with_byte(PROGRAM, 0, 1, 0x08) - with self.assertRaises(rdna2spirv.Unsupported) as cm: - self.translate(listing(PROGRAM), blob(stored)) - self.assertIn("v_cmp_lt_f16_e64 at 0x100", str(cm.exception)) - self.assertIn("dropped", str(cm.exception)) - - def test_difference_in_a_later_instruction_is_refused(self): - stored = with_byte(PROGRAM, 1, 4, 0x81) # v_cndmask src0: inline 1 stored, 0 printed - with self.assertRaises(rdna2spirv.Unsupported) as cm: - self.translate(listing(PROGRAM), blob(stored)) - self.assertIn("v_cndmask_b32_e64 at 0x108", str(cm.exception)) - - def test_same_encoding_exceptions_still_apply(self): - # LLVM 23 prints an unused VOP3 SRC2 as 0x80 where the compiler stored 0 (same_encoding's exception). - printed = listing(with_byte(PROGRAM, 0, 7, 0x02)) - native = blob(PROGRAM) - self.assertIn("OpEntryPoint Fragment", self.translate(printed, native)) - self.assertIn("OpEntryPoint Fragment", self.translate( - printed + b"; warning: invalid instruction encoding\n", native + b"\xff" * 4)) - - def test_inline_zero_does_not_match_a_used_sgpr(self): - # Hand-encoded gfx1013 instructions: SRC1 for the compare and SRC2 for the FMA both read s0. - cases = ( - (("v_cmp_lt_f16_e64 s[4:5], v1, s0", "04 00 c9 d4 01 01 00 00"), - ("v_cmp_lt_f16_e64 s[4:5], v1, 0", "04 00 c9 d4 01 01 01 00")), - (("v_fma_f32 v0, v1, v2, s0", "00 00 4b d5 01 05 02 00"), - ("v_fma_f32 v0, v1, v2, 0", "00 00 4b d5 01 05 02 02")), - ) - for raw, encoded in cases: - for reanchor in (False, True): - with self.subTest(op=raw[0].split()[0], reanchor=reanchor): - native = blob([raw] + PROGRAM) - printed = listing([encoded] + PROGRAM) - error = "a field the disassembler dropped" - if reanchor: - native += b"\xff" * 4 - printed += b"; warning: invalid instruction encoding\n" - error = "reachable instruction with normalized encoding" - with self.assertRaisesRegex(rdna2spirv.Unsupported, error): - self.translate(printed, native) - - def test_listings_without_their_bytes_are_not_checked(self): - stored = with_byte(PROGRAM, 0, 1, 0x08) - # run_gpu_tests.py writes "code 0x0..0x0 (synthetic)". - synthetic = listing(PROGRAM, start=0, end=0, how="synthetic") - self.assertIn("OpEntryPoint Fragment", self.translate(synthetic, blob(stored, start=0))) - hand_written = b"; " + NAME.encode() + b" hand-written test program\n" + listing(PROGRAM).split(b"\n", 1)[1] - self.assertIn("OpEntryPoint Fragment", self.translate(hand_written, blob(stored))) - # A blob that doesn't hold the listing's code range (the tests' header-only FSSM) isn't its source. - self.assertIn("OpEntryPoint Fragment", self.translate(listing(PROGRAM), blob(stored)[:-4])) - - def test_no_blob_is_not_checked(self): - self.assertIn("OpEntryPoint Fragment", self.translate(listing(PROGRAM), None)) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_ps_semantics.py b/tests/semantic/test_ps_semantics.py deleted file mode 100644 index a6e1ffbca..000000000 --- a/tests/semantic/test_ps_semantics.py +++ /dev/null @@ -1,184 +0,0 @@ -"""Value-level regression tests for the RDNA2 -> SPIR-V translator on six straight-line pixel shaders. - -Each shader ends with `exp mrt0 v.., v.., v.., v..`, i.e. exactly four 32-bit words. Six shaders x four words = -the 24 values checked here. Every word is asserted individually (see the subTests), so no output component -is left unchecked, and the output variable set is asserted to be exactly {mrt0}. - -The expected words are written out as constants AND recomputed by plain-Python reference functions that -implement the ISA semantics below; a separate test checks the two agree. Neither depends on the SPIR-V -interpreter or on the translator. - -ISA semantics relied on (AMD RDNA2 "Instruction Set Architecture" reference, VALU/SDWA chapters): - SDWA source select BYTE_n / WORD_n: take that field of the 32-bit source, zero-extended; sext(x) sign-extends it. - SDWA dest select dst_sel BYTE_n / WORD_n: the 32-bit result is truncated to that width and written there; - dst_unused UNUSED_PRESERVE keeps the other destination bits, UNUSED_PAD zeroes them, - UNUSED_SEXT sign-extends the written field into the bits above it and zeroes those below. - v_subrev_nc_u32 D = S1 - S0. v_pk_fma_f16 per 16-bit half: D = S0 * S1 + S2 (IEEE half). - v_min3_u32 / v_max3_i32 minimum (unsigned) / maximum (signed) of three sources. - v_bfe_i32 D = sign_extend(S0[S1[4:0] +: S2[4:0]]) (bit-field extract, width in bits). - v_fma_f16 op_sel reads chosen 16-bit half of each source; writes chosen dst half while preserving the other. - v_subrev_co_ci_u32 D = S1 - S0 - borrow_in (where borrow_in = lane bit of carry-in mask). - v_cmp/cmpx_eq_u64 64-bit equality compare across register pairs; v_cmpx updates EXEC (active lane mask). - v_mul_i32_i24 sign-extends low 24 bits of S0 and S1, returns low 32 bits of signed product. - v_alignbyte_b32 (({S0, S1} as 64-bit) >> (8 * (S2 & 3))) low 32 bits. - v_xnor_b32 ~(S0 ^ S1). v_swap_b32 exchanges two VGPRs. - v_ffbh_i32 MSB-first index (0..31) of first bit differing from the sign bit, or -1 if all equal. - v_pk_lshlrev/lshrrev_b16 per-16-bit-half shift by the matching half of S0 (& 15). - v_add_nc_u16 16-bit add into low half of dst, preserving high half on GFX10. - v_sin_f16 sin(2*pi * f16(S0)) in turns, preserving high half of dst on GFX10. - v_mul_legacy_f32 IEEE f32 multiply except 0 * anything (including inf and NaN) == +0.0. - -Expectations were also recorded as GPU results in the header comments of runtime/test/shaders/ps_*.asm -(not re-confirmed on GPU here). -""" -import math -import struct -import unittest - -import support - -M = 0xFFFFFFFF -FINITE_EXPORT_XOR = 0x40000000 - -# Independent constants, written down by hand (see derivations in the reference functions below). -EXPECTED_PS_SDWA = [0x000000F1, 0xBFFEFFF2, 0x3C003344, 0xBFF70000] -EXPECTED_PS_OPS = [0x48804300, 0x00000005, 0x00000007, 0xBFFFFFFC] -EXPECTED_PS_OPS2 = [0xABCD4400, 0x46001234, 0xBFFFFFFA, 0x00000007] -EXPECTED_PS_OPS3 = [0xBFFFFFFA, 0x44660066, 0x44AABBCC, 0x00000010] -EXPECTED_PS_OPS4 = [0x34000010, 0x00120800, 0xBEEF0000, 0x12343C00] -EXPECTED_PS_LEGACY_MUL = [0x00000000, 0x00000000, 0x00000000, 0x40C00000] - - -def _half(x): - return struct.unpack("> 31 else x - - -def _f32_bits(x): - return struct.unpack("> 8) & 0xFF) + ((v1 >> 16) & 0xFFFF) # BYTE_1 of v0 + WORD_1 of v1 = 0xf0 + 1 - byte0 = v0 & 0xFF - sext_byte0 = byte0 - 0x100 if byte0 & 0x80 else byte0 # sext(v0) with BYTE_0 = -9 - r1 = (sext_byte0 - v1) & M # subrev: S1 - S0 = -9 - 0x10005 - r2 = (_half(1.0) << 16) | (0x11223344 & 0xFFFF) # WORD_1 <- f16(1.0), low half preserved - field = (v0 & 0xFF) | (v1 & 0xFF) # BYTE_0 | BYTE_0 = 0xf7 - r3 = (field << 16) | (0xFF000000 if field & 0x80 else 0) # BYTE_2, UNUSED_SEXT: sign above, zero below - return [r0, r1 ^ FINITE_EXPORT_XOR, r2, r3 ^ FINITE_EXPORT_XOR] - - -def reference_ps_ops(): - lo = _unhalf(0x3C00) * _unhalf(0x4200) + _unhalf(0x3800) # 1.0 * 3.0 + 0.5 - hi = _unhalf(0x4000) * _unhalf(0x4400) + _unhalf(0x3C00) # 2.0 * 4.0 + 1.0 - r0 = (_half(hi) << 16) | _half(lo) - r1 = min(7, 0xFFFFFFF0, 5) # v_min3_u32 (unsigned) - r2 = max(7, _s32(0xFFFFFFF0), 5) & M # v_max3_i32 (signed) - f = (0xFFFFFFF0 >> 2) & 0xF # bits [5:2] - r3 = (f - 16 if f & 8 else f) & M # v_bfe_i32 sign extension of a 4-bit field - return [r0, r1, r2, r3 ^ FINITE_EXPORT_XOR] - - -def reference_ps_ops2(): - v0, v1 = 0x40003C00, 0x44004200 # (1.0, 2.0) and (3.0, 4.0) - r0 = (0xABCD0000 & 0xFFFF0000) | _half(_unhalf(v0 & 0xFFFF) * _unhalf(v1 >> 16) + 0.0) # op_sel:[0,1,0,0] - r1 = (_half(_unhalf(v0 >> 16) * _unhalf(v1 & 0xFFFF) + 0.0) << 16) | (0x00001234 & 0xFFFF) # op_sel:[1,0,0,1] - r2 = (5 - 10 - 1) & M # v_subrev_co_ci_u32: v4 - 10 - borrow(1) - r3 = 7 if (0 == ((0 << 32) | 0)) else 0 # v_cmp_eq_u64 -> v_cndmask_b32 - return [r0, r1, r2 ^ FINITE_EXPORT_XOR, r3] - - -def reference_ps_ops3(): - s24 = 0x00FFFFFE - (1 << 24) # signed 24-bit -2 - r0 = (s24 * 3) & M # v_mul_i32_i24 - v3, v4 = 0x11223344, 0xAABBCCDD - v5 = (((v3 << 32) | v4) >> 8) & M # v_alignbyte_b32(..., 1) - v6 = (~(v3 ^ v4)) & M # v_xnor_b32 - v5, v6 = v6, v5 # v_swap_b32 - v7 = 0x0000FFFF - sign = (v7 >> 31) & 1 - msb_diff = next((bit for bit in range(30, -1, -1) if ((v7 >> bit) & 1) != sign), None) - r3 = M if msb_diff is None else (31 - msb_diff) # v_ffbh_i32 - return [r0 ^ FINITE_EXPORT_XOR, v5, v6, r3] - - -def reference_ps_ops4(): - v0, v2 = 0x12348001, 0x00080004 - lo0, hi0 = v0 & 0xFFFF, (v0 >> 16) & 0xFFFF - sh_lo, sh_hi = v2 & 0xF, (v2 >> 16) & 0xF - r0 = (((hi0 << sh_hi) & 0xFFFF) << 16) | ((lo0 << sh_lo) & 0xFFFF) # v_pk_lshlrev_b16 - r1 = ((hi0 >> sh_hi) << 16) | (lo0 >> sh_lo) # v_pk_lshrrev_b16 - r2 = (0xBEEF0000 & 0xFFFF0000) | ((0x0001 + 0xFFFF) & 0xFFFF) # v_add_nc_u16 keeps high half - r3 = (0x12340000 & 0xFFFF0000) | _half(math.sin(_unhalf(0x3400) * 2.0 * math.pi)) # v_sin_f16 (turns) - return [r0, r1, r2, r3] - - -def reference_ps_legacy_mul(): - def legacy(a_bits, b_bits): - a, b = _bits_f32(a_bits), _bits_f32(b_bits) - if (not math.isnan(a) and a == 0.0) or (not math.isnan(b) and b == 0.0): - return 0x00000000 - return _f32_bits(a * b) - - return [ - legacy(0x00000000, 0x7F800000), # +0.0 * +inf - legacy(0x00000000, 0x7FC00000), # +0.0 * qNaN - legacy(0x80000000, 0xFF800000), # -0.0 * -inf - legacy(_f32_bits(2.0), _f32_bits(3.0)), # 2.0 * 3.0 - ] - - -class OracleTests(unittest.TestCase): - """The hand-written constants and the plain-Python reference agree (so the oracle is self-consistent).""" - - def test_reference_matches_constants(self): - self.assertEqual(reference_ps_sdwa(), EXPECTED_PS_SDWA) - self.assertEqual(reference_ps_ops(), EXPECTED_PS_OPS) - self.assertEqual(reference_ps_ops2(), EXPECTED_PS_OPS2) - self.assertEqual(reference_ps_ops3(), EXPECTED_PS_OPS3) - self.assertEqual(reference_ps_ops4(), EXPECTED_PS_OPS4) - self.assertEqual(reference_ps_legacy_mul(), EXPECTED_PS_LEGACY_MUL) - - -class TranslatorSemantics(unittest.TestCase): - def check(self, name, expected): - words = support.mrt0_words(support.translate_fixture(name)) - self.assertEqual(len(words), 4, "mrt0 has four components") - for i, (got, want) in enumerate(zip(words, expected)): - with self.subTest(shader=name, component="xyzw"[i]): - self.assertEqual(f"{got:#010x}", f"{want:#010x}") - - def test_ps_sdwa(self): - self.check("ps_sdwa", EXPECTED_PS_SDWA) - - def test_ps_ops(self): - self.check("ps_ops", EXPECTED_PS_OPS) - - def test_ps_ops2(self): - self.check("ps_ops2", EXPECTED_PS_OPS2) - - def test_ps_ops3(self): - self.check("ps_ops3", EXPECTED_PS_OPS3) - - def test_ps_ops4(self): - self.check("ps_ops4", EXPECTED_PS_OPS4) - - def test_ps_legacy_mul(self): - self.check("ps_legacy_mul", EXPECTED_PS_LEGACY_MUL) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_reg_ptr_hoist.py b/tests/semantic/test_reg_ptr_hoist.py deleted file mode 100644 index 795d5b71f..000000000 --- a/tests/semantic/test_reg_ptr_hoist.py +++ /dev/null @@ -1,257 +0,0 @@ -"""Tests for entry-block hoisting of constant-index %vgpr/%sgpr OpAccessChain pointers.""" -import os -import re -import shutil -import struct -import subprocess -import sys -import tempfile -import unittest - -HERE = os.path.dirname(os.path.abspath(__file__)) -sys.path.insert(0, HERE) -import support # noqa: E402 -from support import rdna2spirv # noqa: E402 -from spirv_wave_interp import run_wave # noqa: E402 - - -def _make_fssm_cs(user_sgprs=4, tgid_mask=1, tid_cnt=0, threads=(64, 1, 1), wave32=True): - """Minimal FSSM blob carrying COMPUTE_PGM_RSRC2, workgroup size, and wave flag.""" - buf = bytearray(0x160) - buf[0xD4] = 0x20 if wave32 else 0x00 - rsrc2 = ((user_sgprs & 31) << 1) | ((tgid_mask & 7) << 7) | ((tid_cnt & 3) << 11) - struct.pack_into(" last_var for i, _ in hoisted)) - - # No duplicate hoisted pointer names, and zero constant-index %vgpr/%sgpr OpAccessChain in non-entry blocks. - names = [ln.split()[0] for _, ln in hoisted] - self.assertEqual(len(names), len(set(names))) - for lbl, blines in blocks[1:]: - for ln in blines: - if "OpAccessChain %_ptr_Function_uint %vgpr " in ln or "OpAccessChain %_ptr_Function_uint %sgpr " in ln: - self.fail(f"unexpected non-entry constant-index register OpAccessChain in {lbl}: {ln}") - - # Semantic check across 32 lanes via run_wave: lane 5 stays masked out; other 31 lanes run 4 iterations. - res = run_wave(spvasm, wave=32) - v0, v1, v2 = 10, 3, 7 - for s4 in range(4): - v0 = (v0 + v1) & 0xFFFFFFFF - v1 = (v1 * 2) & 0xFFFFFFFF - v2 = (v2 + s4) & 0xFFFFFFFF - active_expected = (v0, v1, v2, 0) - masked_expected = (10, 3, 7, 1) - for lane in range(32): - self.assertEqual( - tuple(res["outputs"][lane]["%out_mrt0"]), - masked_expected if lane == 5 else active_expected, - ) - - def test_heavy_alu_deduplication_and_exact_results(self): - """Repeated accesses to the same VGPRs reuse a single hoisted pointer and match exact math.""" - lines = [ - "v_mov_b32 v0, 1.0", - "v_mov_b32 v1, 0.5", - "v_mov_b32 v2, 0.25", - "v_mov_b32 v3, 2.0", - ] - for _ in range(30): - lines.append("v_fma_f32 v0, v0, v1, v2") - lines += ["exp mrt0 v0, v1, v2, v3 done vm", "s_endpgm"] - spvasm = support.translate_lines("ps_hoist_alu", lines) - _validate_spirv(spvasm) - - vgpr_ac = [ln.strip() for ln in spvasm.splitlines() - if "OpAccessChain %_ptr_Function_uint %vgpr " in ln] - self.assertEqual(len(vgpr_ac), 4, f"expected 4 VGPR OpAccessChain (v0..v3), got {len(vgpr_ac)}") - - v0 = 1.0 - for _ in range(30): - v0 = v0 * 0.5 + 0.25 - self.assertEqual( - support.mrt0_words(spvasm), - [_f32_bits(v0), _f32_bits(0.5), _f32_bits(0.25), _f32_bits(2.0)], - ) - - def test_dynamic_movrel_coexists_with_hoisted_ptrs(self): - """v_movrels_b32 keeps its dynamic OpAccessChain while static accesses use hoisted pointers.""" - lines = [ - "v_mov_b32 v4, 0x11111111", - "v_mov_b32 v5, 0x22222222", - "v_mov_b32 v6, 0x33333333", - "s_mov_b32 m0, 2", - "v_movrels_b32 v0, v4", - "v_mov_b32 v1, v5", - "v_mov_b32 v2, v6", - "v_mov_b32 v3, v0", - "exp mrt0 v0, v1, v2, v3 done vm", - "s_endpgm", - ] - spvasm = support.translate_lines("ps_hoist_movrel", lines) - _validate_spirv(spvasm) - self.assertEqual( - support.mrt0_words(spvasm), - [0x33333333, 0x22222222, 0x33333333, 0x33333333], - ) - - def test_compute_wave64_emulate_validates(self): - """Hoisted pointers dominate all blocks in --wave64-emulate compute shaders too.""" - body = [ - "s_mov_b32 s4, 0", - "s_mov_b32 s5, 2", - "v_mov_b32 v0, 1.0", - "v_mov_b32 v1, 2.0", - "BB_loop:", - "v_cmp_gt_f32 vcc, v0, 0.5", - "s_and_saveexec_b64 s[6:7], vcc", - "s_cbranch_execz BB_skip", - "v_add_f32 v0, v0, v1", - "v_mul_f32 v1, v1, v0", - "BB_skip:", - "s_or_b64 exec, exec, s[6:7]", - "s_add_u32 s4, s4, 1", - "s_cmp_lt_u32 s4, s5", - "s_cbranch_scc1 BB_loop", - "s_endpgm", - ] - fssm = _make_fssm_cs(user_sgprs=4, tgid_mask=1, tid_cnt=0, threads=(64, 1, 1), wave32=False) - old_emu = rdna2spirv.WAVE64_EMULATE - try: - rdna2spirv.WAVE64_EMULATE = True - spvasm = support.translate_listing("cs_hoist_w64", _encode_listing("cs_hoist_w64", body), fssm=fssm) - finally: - rdna2spirv.WAVE64_EMULATE = old_emu - _validate_spirv(spvasm) - self.assertIn("%reg_v0 = OpAccessChain %_ptr_Function_uint %vgpr %c0", spvasm) - self.assertIn("%reg_s4 = OpAccessChain %_ptr_Function_uint %sgpr %c4", spvasm) - - def test_direct_gen_keeps_inline_access_chains(self): - """Direct Gen() unit-test callers default to inline OpAccessChain inside g.body.""" - g = rdna2spirv.Gen("cs") - val = g.load_reg("vgpr", 7) - g.store_reg("vgpr", 8, val) - body = "\n".join(g.body) - self.assertIn("OpAccessChain %_ptr_Function_uint %vgpr %c7", body) - self.assertIn("OpAccessChain %_ptr_Function_uint %vgpr %c8", body) - self.assertEqual(g.reg_ptrs, {}) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_relative_vgpr_bounds.py b/tests/semantic/test_relative_vgpr_bounds.py deleted file mode 100644 index 61017b3b6..000000000 --- a/tests/semantic/test_relative_vgpr_bounds.py +++ /dev/null @@ -1,19 +0,0 @@ -import sys -import unittest -from pathlib import Path - -sys.path.insert(0, str(Path(__file__).resolve().parent)) -from support import mrt0_words, translate_lines # noqa: E402 - - -class RelativeVgprBoundsTests(unittest.TestCase): - def test_moves_and_swap_keep_vgpr_accesses_in_range(self): - fixture = Path(__file__).with_name("fixtures") / "relative_vgpr_bounds.asm" - lines = [line for line in fixture.read_text(encoding="ascii").splitlines() - if line and not line.startswith(";")] - spvasm = translate_lines("ps_relative_vgpr_bounds", lines) - self.assertEqual(mrt0_words(spvasm), [0x41100000, 0x3F800000, 0x3F800000, 0x40800000]) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_rule_gpu_fixtures.py b/tests/semantic/test_rule_gpu_fixtures.py deleted file mode 100644 index 0fdd0eec5..000000000 --- a/tests/semantic/test_rule_gpu_fixtures.py +++ /dev/null @@ -1,114 +0,0 @@ -"""The GPU fixtures for docs/design.md rules that used to be checked on the CPU only (TEST-175). - -Each fixture in runtime/test/shaders writes four mrt0 words that its .asm header derives by hand ("Expected mrt0 -bits"). These tests keep the three places that state those words in step with the translator: the interpreter run of -the translated fixture (tests/semantic/fixtures/disasm, made by regen_fixtures.py), check.py's PIXEL_BITS and -scripts/run_gpu_tests.py's table. A GPU run of check.py or run_gpu_tests.py then compares the same words with what -the device writes. The two interp fixtures are drawn with vs_interp_consts, whose params are constant over the -triangle; the interpreter gets those constants, read back from that vertex shader's source. -""" -import os -import re -import struct -import sys -import unittest - -HERE = os.path.dirname(os.path.abspath(__file__)) -ROOT = os.path.dirname(os.path.dirname(HERE)) -SHADERS = os.path.join(ROOT, "runtime", "test", "shaders") -sys.path.insert(0, HERE) -sys.path.insert(0, SHADERS) - -import support # noqa: E402 -import check # noqa: E402 (runtime/test/shaders/check.py; importing it runs nothing) - -FIXTURES = ("ps_cmp_nlg", "ps_cvt_off", "ps_fmac_f16_mods", "ps_vop3_const_mods", "ps_interp_f32_mods", - "ps_interp_mov_mods") -INTERP_VERTEX = "vs_interp_consts" -INLINE_F32 = {"0.5": 0x3F000000, "-0.5": 0xBF000000, "1.0": 0x3F800000, "-1.0": 0xBF800000, "2.0": 0x40000000, - "-2.0": 0xC0000000, "4.0": 0x40800000, "-4.0": 0xC0800000, "0.25": 0x3E800000, "-0.25": 0xBE800000} - - -def read(name): - with open(os.path.join(SHADERS, name + ".asm"), encoding="utf-8") as f: - return f.read() - - -def header_words(name): - m = re.search(r"Expected mrt0 bits: (.*)", read(name)) - return tuple(int(x, 16) for x in m.group(1).split(",")) - - -def runner_words(name): - """The tuple scripts/run_gpu_tests.py expects for `name` (its table is local to run_suite, so read the source).""" - with open(os.path.join(ROOT, "scripts", "run_gpu_tests.py"), encoding="utf-8") as f: - m = re.search(r'"%s": \(([^)]*)\)' % re.escape(name), f.read()) - return tuple(int(x, 16) for x in m.group(1).split(",")) if m else None - - -def vertex_params(name): - """{param n: four f32 values} exported by a vertex shader made of v_mov_b32 constants and `exp paramN` lines.""" - regs, params = {}, {} - for line in read(name).splitlines(): - line = line.split(";")[0].strip() - m = re.match(r"v_mov_b32(?:_e32)? v(\d+), (\S+)$", line) - if m: - v = m.group(2) - regs[int(m.group(1))] = INLINE_F32[v] if v in INLINE_F32 else int(v, 0) & 0xFFFFFFFF - continue - m = re.match(r"exp param(\d+) v(\d+), v(\d+), v(\d+), v(\d+)", line) - if m: - params[int(m.group(1))] = tuple(struct.unpack("> 23) & 0xFF - with self.subTest(name=name, word=f"{w:#010x}"): - self.assertTrue(w & 0x7FFFFFFF == 0 or 0 < exp < 0xFF) - - def test_interp_fixtures_are_drawn_with_the_constant_vertex_shader(self): - params = vertex_params(INTERP_VERTEX) - self.assertEqual(params[0], (1.5, -0.25, 0.375, 0.625)) - self.assertEqual(params[1], (1.5, -0.5, 0.25, 4.0)) - self.assertEqual(params[2], (0.25, 3.0, 0.0, 0.0)) - for name in ("ps_interp_f32_mods", "ps_interp_mov_mods"): - self.assertEqual(check.PIXEL_VERTEX[name], INTERP_VERTEX) - self.assertIn(f"vk_harness {INTERP_VERTEX}.spv {name}.spv", read(name)) - - def test_attr1_is_flat_and_the_others_interpolate(self): - # attr1 is read only with v_interp_mov, so the translator declares it Flat; attr2 goes through p1/p2. - spv = support.translate_fixture("ps_interp_mov_mods") - self.assertIn("OpDecorate %in_attr1 Flat", spv) - self.assertNotIn("OpDecorate %in_attr2 Flat", spv) - self.assertNotIn("PerVertexKHR", spv) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_salu64_bitwise_data.py b/tests/semantic/test_salu64_bitwise_data.py deleted file mode 100644 index c8e3f1838..000000000 --- a/tests/semantic/test_salu64_bitwise_data.py +++ /dev/null @@ -1,702 +0,0 @@ -"""Semantic tests for RDNA2 64-bit scalar bitwise ops on 64-bit data pairs vs lane masks. - -Covers s_and_b64, s_or_b64, s_xor_b64, s_andn2_b64, s_orn2_b64, s_nand_b64, s_nor_b64, s_xnor_b64, and s_not_b64: - * Distinct lo/hi 64-bit SGPR data pairs (verifying D.lo, D.hi, and SCC) - * Positive/negative immediates (0xFE, -2, -16, 0x80000000, 0, -1) and null src/dst - * SCC four-corner matrix: (lo==0, hi==0), (lo!=0, hi==0), (lo==0, hi!=0), (lo!=0, hi!=0) - * Destination aliasing (exact D==S0, D==S1, D==S0==S1, and partial overlap s[4:5] vs s[3:4]/s[5:6]) - * Overwriting a former lane-mask SGPR pair with 64-bit data clears stale mask state - * Lane-mask regression checks across wave32, wave64, compute workgroups, and --wave64-emulate - (verifying wave-wide SCC voting and EXEC/VCC/SGPR/null mask behavior) - -Run directly: - python -I tests/semantic/test_salu64_bitwise_data.py -v -""" -import atexit -import os -import re -import struct -import sys -import tempfile -import unittest -import warnings - -HERE = os.path.dirname(os.path.abspath(__file__)) -if HERE not in sys.path: - sys.path.insert(0, HERE) - -import spirv_mini_interp as si # noqa: E402 -import spirv_wave_interp as wi # noqa: E402 -from support import STUB_DXBC, mrt0_words, rdna2spirv # noqa: E402 - -MASK32 = 0xFFFFFFFF -MASK64 = 0xFFFFFFFFFFFFFFFF - -_TMP_DIR = None -_PS_PATH = None -_CS_PATH = None -_EXIT_CLEANUP = False - - -def setUpModule(): - global _TMP_DIR, _PS_PATH, _CS_PATH, _EXIT_CLEANUP - if _TMP_DIR is not None: - # translate_ps() and the importers' helpers (test_interp_merge_check, test_mask_src_sgpr_const, - # test_saveexec_variants) may have created it already; replacing it would leak the first one - return - _TMP_DIR = tempfile.TemporaryDirectory() - # A module that imports a helper from here and runs after this module's teardown recreates the folder through - # translate_ps(), and unittest never tears this module down again. Registered once, after the first - # TemporaryDirectory, so it runs before tempfile's own exit finalizer (atexit is last in, first out) and that - # finalizer stays quiet; tearDownModule() cleans whichever folder is live at exit. - if not _EXIT_CLEANUP: - atexit.register(tearDownModule) - _EXIT_CLEANUP = True - dis = os.path.join(_TMP_DIR.name, "disasm") - fssm = os.path.join(_TMP_DIR.name, "fssm") - os.mkdir(dis) - os.mkdir(fssm) - _PS_PATH = os.path.join(dis, "ps_salu64_bit.s") - _CS_PATH = os.path.join(dis, "cs_salu64_bit.s") - with open(os.path.join(_TMP_DIR.name, "ps_salu64_bit.dxbc"), "wb") as f: - f.write(STUB_DXBC) - with open(os.path.join(_TMP_DIR.name, "cs_salu64_bit.dxbc"), "wb") as f: - f.write(STUB_DXBC) - # Minimal FSSM header: 4 user SGPRs (V# in s[0:3]), TGID_X in s4, 64x1x1 threads. - hdr = bytearray(0x148) - struct.pack_into("<4I", hdr, 0x138, 0x8088, 64, 1, 1) - with open(os.path.join(fssm, "cs_salu64_bit.fssm"), "wb") as f: - f.write(hdr) - - -def tearDownModule(): - global _TMP_DIR - if _TMP_DIR is not None: - _TMP_DIR.cleanup() - _TMP_DIR = None - - -def translate_ps(lines): - if _TMP_DIR is None: - setUpModule() - asm = "; ps_salu64_bit\n" + "".join(f"\t{ln}\n" for ln in lines) - with open(_PS_PATH, "w", encoding="utf-8", newline="") as f: - f.write(asm) - with warnings.catch_warnings(): - warnings.simplefilter("ignore", ResourceWarning) - return rdna2spirv.translate(_PS_PATH) - - -def translate_cs(lines): - if _TMP_DIR is None: - setUpModule() - asm = "; cs_salu64_bit\n" + "".join(f"\t{ln}\n" for ln in lines) - with open(_CS_PATH, "w", encoding="utf-8", newline="") as f: - f.write(asm) - with warnings.catch_warnings(): - warnings.simplefilter("ignore", ResourceWarning) - return rdna2spirv.translate(_CS_PATH) - - -def run_ps(lines): - spv = translate_ps(lines + ["exp mrt0 v0, v1, v2, v3 done vm", "s_endpgm"]) - return mrt0_words(spv), spv - - -def run_ps_wave(lines, wave): - spv = translate_ps(lines + ["exp mrt0 v0, v1, v2, v3 done vm", "s_endpgm"]) - res = wi.run_wave(spv, wave=wave) - return [o[next(iter(o))] if o is not None else None for o in res["outputs"]], spv - - -def load_pair_lines(reg, val64): - lo = val64 & MASK32 - hi = (val64 >> 32) & MASK32 - return [f"s_mov_b32 s{reg}, {lo:#x}", f"s_mov_b32 s{reg + 1}, {hi:#x}"] - - -BIN_OPS = { - "s_and_b64": lambda x, y: (x & y) & MASK64, - "s_or_b64": lambda x, y: (x | y) & MASK64, - "s_xor_b64": lambda x, y: (x ^ y) & MASK64, - "s_andn2_b64": lambda x, y: (x & (~y & MASK64)) & MASK64, - "s_orn2_b64": lambda x, y: (x | (~y & MASK64)) & MASK64, - "s_nand_b64": lambda x, y: ~(x & y) & MASK64, - "s_nor_b64": lambda x, y: ~(x | y) & MASK64, - "s_xnor_b64": lambda x, y: ~(x ^ y) & MASK64, -} - - -class DataPairBitwiseTests(unittest.TestCase): - def test_all_six_ops_distinct_dwords(self): - pairs = [ - (0x55667788_11223344, 0x0F0F00FF_F0F0FF00), - (0xA5A55A5A_01234567, 0x5A5AA5A5_89ABCDEF), - (0x12345678_00000000, 0xFFFFFFFF_87654321), - ] - for op, fn in BIN_OPS.items(): - for a64, b64 in pairs: - with self.subTest(op=op, a=hex(a64), b=hex(b64)): - want = fn(a64, b64) - want_scc = 1 if want != 0 else 0 - lines = ( - load_pair_lines(4, a64) - + load_pair_lines(6, b64) - + [ - f"{op} s[2:3], s[4:5], s[6:7]", - "s_cselect_b32 s10, 1, 0", - "v_mov_b32 v0, s2", - "v_mov_b32 v1, s3", - "v_mov_b32 v2, s10", - "v_mov_b32 v3, 0", - ] - ) - words, _ = run_ps(lines) - self.assertEqual(words[:3], [want & MASK32, (want >> 32) & MASK32, want_scc]) - - for a64 in (0x55667788_11223344, 0xFFFFFFFF_00000000, 0x00000000_FFFFFFFF, 0, MASK64): - with self.subTest(op="s_not_b64", a=hex(a64)): - want = (~a64) & MASK64 - want_scc = 1 if want != 0 else 0 - lines = load_pair_lines(4, a64) + [ - "s_not_b64 s[2:3], s[4:5]", - "s_cselect_b32 s10, 1, 0", - "v_mov_b32 v0, s2", - "v_mov_b32 v1, s3", - "v_mov_b32 v2, s10", - "v_mov_b32 v3, 0", - ] - words, _ = run_ps(lines) - self.assertEqual(words[:3], [want & MASK32, (want >> 32) & MASK32, want_scc]) - - def test_scc_four_corners(self): - # Verify SCC = ((rlo | rhi) != 0) across all four (lo, hi) zero/nonzero combinations. - cases = { - "s_and_b64": [ - (0x00000000_00000000, 0xFFFFFFFF_FFFFFFFF, 0), - (0x00000000_00000008, 0xFFFFFFFF_0000000F, 1), - (0x00000010_00000000, 0x000000F0_FFFFFFFF, 1), # only hi non-zero! - (0x80000000_00000001, 0x80000000_00000001, 1), - ], - "s_or_b64": [ - (0x00000000_00000000, 0x00000000_00000000, 0), - (0x00000000_00000004, 0x00000000_00000000, 1), - (0x00000000_00000000, 0x00000020_00000000, 1), # only hi non-zero! - (0x00000001_00000000, 0x00000000_00000001, 1), - ], - "s_xor_b64": [ - (0x12345678_9ABCDEF0, 0x12345678_9ABCDEF0, 0), - (0x12345678_9ABCDEF0, 0x12345678_9ABCDEF1, 1), - (0x12345678_9ABCDEF0, 0x12345679_9ABCDEF0, 1), # only hi non-zero! - (0x00000001_00000001, 0x00000000_00000000, 1), - ], - "s_andn2_b64": [ - (0x0000000F_0000000F, 0x000000FF_000000FF, 0), - (0x0000000F_0000001F, 0x000000FF_0000000F, 1), - (0x00000100_0000000F, 0x000000FF_0000000F, 1), # only hi non-zero! - (0x00000100_00000100, 0x00000000_00000000, 1), - ], - "s_orn2_b64": [ - (0x00000000_00000000, 0xFFFFFFFF_FFFFFFFF, 0), - (0x00000000_00000001, 0xFFFFFFFF_FFFFFFFF, 1), - (0x00000001_00000000, 0xFFFFFFFF_FFFFFFFF, 1), # only hi non-zero! - (0x00000001_00000001, 0xFFFFFFFF_FFFFFFFF, 1), - ], - "s_nand_b64": [ - (MASK64, MASK64, 0), - (0xFFFFFFFF_FFFFFFFE, MASK64, 1), - (0xFFFFFFFE_FFFFFFFF, MASK64, 1), # only hi non-zero! - (0, 0, 1), - ], - "s_nor_b64": [ - (0xFFFFFFFF_00000000, 0x00000000_FFFFFFFF, 0), - (0xFFFFFFFF_FFFFFFFE, 0, 1), - (0xFFFFFFFE_FFFFFFFF, 0, 1), # only hi non-zero! - (0, 0, 1), - ], - "s_xnor_b64": [ - (0x12345678_9ABCDEF0, 0xEDCBA987_6543210F, 0), - (0x12345678_9ABCDEF0, 0xEDCBA987_6543210E, 1), - (0x12345678_9ABCDEF0, 0xEDCBA986_6543210F, 1), # only hi non-zero! - (0x12345678_9ABCDEF0, 0x12345678_9ABCDEF0, 1), - ], - } - for op, items in cases.items(): - fn = BIN_OPS[op] - for a64, b64, want_scc in items: - with self.subTest(op=op, a=hex(a64), b=hex(b64)): - want = fn(a64, b64) - self.assertEqual(1 if want != 0 else 0, want_scc) - lines = ( - load_pair_lines(4, a64) - + load_pair_lines(6, b64) - + [ - # Poison SCC with the opposite value beforehand to ensure the op overwrites it. - "s_cmp_eq_u32 0, 1" if want_scc else "s_cmp_eq_u32 1, 1", - f"{op} s[2:3], s[4:5], s[6:7]", - "s_cselect_b32 s10, 1, 0", - "v_mov_b32 v0, s2", - "v_mov_b32 v1, s3", - "v_mov_b32 v2, s10", - "v_mov_b32 v3, 0", - ] - ) - words, _ = run_ps(lines) - self.assertEqual(words[:3], [want & MASK32, (want >> 32) & MASK32, want_scc]) - - # s_not_b64 four corners: ~MASK64 == 0, ~0xFFFFFFFF_FFFFFFFE == lo-only, ~0xFFFFFFFE_FFFFFFFF == hi-only - for a64, want_scc in ( - (0xFFFFFFFF_FFFFFFFF, 0), - (0xFFFFFFFF_FFFFFFFE, 1), - (0xFFFFFFFE_FFFFFFFF, 1), # only hi non-zero! - (0x12345678_9ABCDEF0, 1), - ): - with self.subTest(op="s_not_b64", a=hex(a64)): - want = (~a64) & MASK64 - lines = load_pair_lines(4, a64) + [ - "s_cmp_eq_u32 0, 1" if want_scc else "s_cmp_eq_u32 1, 1", - "s_not_b64 s[2:3], s[4:5]", - "s_cselect_b32 s10, 1, 0", - "v_mov_b32 v0, s2", - "v_mov_b32 v1, s3", - "v_mov_b32 v2, s10", - "v_mov_b32 v3, 0", - ] - words, _ = run_ps(lines) - self.assertEqual(words[:3], [want & MASK32, (want >> 32) & MASK32, want_scc]) - - def test_immediates_sign_extension_and_zero_minus_one(self): - data64 = 0x55667788_112233FF - imms = [ - ("0xfe", 0x00000000_000000FE), - ("-2", 0xFFFFFFFF_FFFFFFFE), - ("-16", 0xFFFFFFFF_FFFFFFF0), - ("0x80000000", 0x00000000_80000000), - ("0", 0), - ("-1", MASK64), - ] - for op, fn in BIN_OPS.items(): - for imm_asm, imm_val in imms: - for data_first in (True, False): - s0_asm, s1_asm = ("s[4:5]", imm_asm) if data_first else (imm_asm, "s[4:5]") - s0_val, s1_val = (data64, imm_val) if data_first else (imm_val, data64) - with self.subTest(op=op, s0=s0_asm, s1=s1_asm): - want = fn(s0_val, s1_val) - want_scc = 1 if want != 0 else 0 - lines = load_pair_lines(4, data64) + [ - f"{op} s[2:3], {s0_asm}, {s1_asm}", - "s_cselect_b32 s10, 1, 0", - "v_mov_b32 v0, s2", - "v_mov_b32 v1, s3", - "v_mov_b32 v2, s10", - "v_mov_b32 v3, 0", - ] - words, _ = run_ps(lines) - self.assertEqual(words[:3], [want & MASK32, (want >> 32) & MASK32, want_scc]) - - # s_not_b64 on immediates (positive, negative, 0, -1). - for imm_asm, imm_val in imms: - with self.subTest(op="s_not_b64", imm=imm_asm): - want = (~imm_val) & MASK64 - want_scc = 1 if want != 0 else 0 - words, _ = run_ps([ - f"s_not_b64 s[2:3], {imm_asm}", - "s_cselect_b32 s10, 1, 0", - "v_mov_b32 v0, s2", - "v_mov_b32 v1, s3", - "v_mov_b32 v2, s10", - "v_mov_b32 v3, 0", - ]) - self.assertEqual(words[:3], [want & MASK32, (want >> 32) & MASK32, want_scc]) - - # Pure 0 / -1 binary ops into an SGPR pair (lane_masks EITHER). - for op, fn in BIN_OPS.items(): - for s0_asm, s0_val in (("0", 0), ("-1", MASK64)): - for s1_asm, s1_val in (("0", 0), ("-1", MASK64)): - with self.subTest(op=op, pure=(s0_asm, s1_asm)): - want = fn(s0_val, s1_val) - want_scc = 1 if want != 0 else 0 - words, _ = run_ps([ - f"{op} s[2:3], {s0_asm}, {s1_asm}", - "s_cselect_b32 s10, 1, 0", - "v_mov_b32 v0, s2", - "v_mov_b32 v1, s3", - "v_mov_b32 v2, s10", - "v_mov_b32 v3, 0", - ]) - self.assertEqual(words[:3], [want & MASK32, (want >> 32) & MASK32, want_scc]) - - def test_null_source_and_null_destination(self): - data64 = 0x55667788_00000000 # hi-only non-zero! - for op, fn in BIN_OPS.items(): - for s0_asm, s1_asm, s0_val, s1_val in ( - ("s[4:5]", "null", data64, 0), - ("null", "s[4:5]", 0, data64), - ): - with self.subTest(op=op, s0=s0_asm, s1=s1_asm): - want = fn(s0_val, s1_val) - want_scc = 1 if want != 0 else 0 - lines = load_pair_lines(4, data64) + [ - f"{op} s[2:3], {s0_asm}, {s1_asm}", - "s_cselect_b32 s10, 1, 0", - "v_mov_b32 v0, s2", - "v_mov_b32 v1, s3", - "v_mov_b32 v2, s10", - "v_mov_b32 v3, 0", - ] - words, _ = run_ps(lines) - self.assertEqual(words[:3], [want & MASK32, (want >> 32) & MASK32, want_scc]) - - # null destination discards the result while still updating SCC (including hi-only non-zero). - for op, a64, b64, want_scc in ( - ("s_and_b64", 0x00000010_00000000, 0x00000010_00000000, 1), - ("s_and_b64", 0x00000010_00000000, 0x00000001_FFFFFFFF, 0), - ("s_xor_b64", 0x12345678_9ABCDEF0, 0x12345678_9ABCDEF0, 0), - ("s_xor_b64", 0x12345678_9ABCDEF0, 0x12345679_9ABCDEF0, 1), - ("s_andn2_b64", 0x00000010_00000000, 0x00000000_FFFFFFFF, 1), - ("s_orn2_b64", 0x00000000_00000000, 0xFFFFFFFF_FFFFFFFF, 0), - ): - with self.subTest(null_dst=op, a=hex(a64), b=hex(b64)): - lines = ( - load_pair_lines(4, a64) - + load_pair_lines(6, b64) - + [ - "s_cmp_eq_u32 0, 1" if want_scc else "s_cmp_eq_u32 1, 1", - f"{op} null, s[4:5], s[6:7]", - "s_cselect_b32 s10, 1, 0", - "v_mov_b32 v0, s10", - "v_mov_b32 v1, 0", - "v_mov_b32 v2, 0", - "v_mov_b32 v3, 0", - ] - ) - words, _ = run_ps(lines) - self.assertEqual(words[0], want_scc) - - for a64, want_scc in ((MASK64, 0), (0xFFFFFFFE_FFFFFFFF, 1)): - with self.subTest(null_dst="s_not_b64", a=hex(a64)): - lines = load_pair_lines(4, a64) + [ - "s_cmp_eq_u32 0, 1" if want_scc else "s_cmp_eq_u32 1, 1", - "s_not_b64 null, s[4:5]", - "s_cselect_b32 s10, 1, 0", - "v_mov_b32 v0, s10", - "v_mov_b32 v1, 0", - "v_mov_b32 v2, 0", - "v_mov_b32 v3, 0", - ] - words, _ = run_ps(lines) - self.assertEqual(words[0], want_scc) - - # s_not_b64 with null source (~0 == MASK64, SCC == 1). - words, _ = run_ps([ - "s_not_b64 s[2:3], null", - "s_cselect_b32 s10, 1, 0", - "v_mov_b32 v0, s2", - "v_mov_b32 v1, s3", - "v_mov_b32 v2, s10", - "v_mov_b32 v3, 0", - ]) - self.assertEqual(words[:3], [MASK32, MASK32, 1]) - - def test_destination_aliasing(self): - a64 = 0x55667788_11223344 - b64 = 0xDDEEFF00_99AABBCC - for op, fn in BIN_OPS.items(): - for src0, src1, s0_val, s1_val in ( - ("s[4:5]", "s[6:7]", a64, b64), - ("s[6:7]", "s[4:5]", b64, a64), - ("s[4:5]", "s[4:5]", a64, a64), - ): - with self.subTest(op=op, src0=src0, src1=src1): - want = fn(s0_val, s1_val) - want_scc = 1 if want != 0 else 0 - lines = ( - load_pair_lines(4, a64) - + load_pair_lines(6, b64) - + [ - f"{op} s[4:5], {src0}, {src1}", - "s_cselect_b32 s10, 1, 0", - "v_mov_b32 v0, s4", - "v_mov_b32 v1, s5", - "v_mov_b32 v2, s10", - "v_mov_b32 v3, 0", - ] - ) - words, _ = run_ps(lines) - self.assertEqual(words[:3], [want & MASK32, (want >> 32) & MASK32, want_scc]) - - # Partial register overlap: dst s[4:5] overlaps both s[3:4] and s[5:6]. - s3, s4, s5, s6 = 0x10203040, 0x50607080, 0x90A0B0C0, 0xD0E0F001 - p34 = (s4 << 32) | s3 - p56 = (s6 << 32) | s5 - for op, fn in BIN_OPS.items(): - for src0, src1, s0_val, s1_val in ( - ("s[3:4]", "s[5:6]", p34, p56), - ("s[5:6]", "s[3:4]", p56, p34), - ): - with self.subTest(op=op, overlap=(src0, src1)): - want = fn(s0_val, s1_val) - want_scc = 1 if want != 0 else 0 - words, _ = run_ps([ - f"s_mov_b32 s3, {s3:#x}", - f"s_mov_b32 s4, {s4:#x}", - f"s_mov_b32 s5, {s5:#x}", - f"s_mov_b32 s6, {s6:#x}", - f"{op} s[4:5], {src0}, {src1}", - "s_cselect_b32 s10, 1, 0", - "v_mov_b32 v0, s4", - "v_mov_b32 v1, s5", - "v_mov_b32 v2, s10", - "v_mov_b32 v3, 0", - ]) - self.assertEqual(words[:3], [want & MASK32, (want >> 32) & MASK32, want_scc]) - - # Unary s_not_b64 aliasing: exact (s[4:5] <- s[4:5]) and partial overlaps (s[3:4], s[5:6]). - for src, s_val in (("s[4:5]", (s5 << 32) | s4), ("s[3:4]", p34), ("s[5:6]", p56)): - with self.subTest(op="s_not_b64", overlap=src): - want = (~s_val) & MASK64 - want_scc = 1 if want != 0 else 0 - words, _ = run_ps([ - f"s_mov_b32 s3, {s3:#x}", - f"s_mov_b32 s4, {s4:#x}", - f"s_mov_b32 s5, {s5:#x}", - f"s_mov_b32 s6, {s6:#x}", - f"s_not_b64 s[4:5], {src}", - "s_cselect_b32 s10, 1, 0", - "v_mov_b32 v0, s4", - "v_mov_b32 v1, s5", - "v_mov_b32 v2, s10", - "v_mov_b32 v3, 0", - ]) - self.assertEqual(words[:3], [want & MASK32, (want >> 32) & MASK32, want_scc]) - - def test_overwriting_stale_lane_mask_pair_clears_mask_state(self): - # s[4:5] first holds vcc (lane mask), then is overwritten with 64-bit data by s_and_b64 or s_not_b64. - # Subsequent s_bcnt1_i32_b64 must count the 64-bit data popcount, not active wave lanes. - a64 = 0x0F0F0000_00005555 - b64 = 0x00FF0000_000000FF - cases = [ - ("s_and_b64 s[4:5], s[6:7], s[8:9]", a64 & b64), - ("s_not_b64 s[4:5], s[6:7]", (~a64) & MASK64), - ] - for insn, want in cases: - want_cnt = want.bit_count() - for wave, mbcnt in ((32, ["v_mbcnt_lo_u32_b32 v4, -1, 0"]), - (64, ["v_mbcnt_lo_u32_b32 v4, -1, 0", "v_mbcnt_hi_u32_b32 v4, -1, v4"])): - with self.subTest(insn=insn, wave=wave): - lines = ( - mbcnt - + [ - "v_cmp_gt_u32_e32 vcc, 8, v4", - "s_mov_b64 s[4:5], vcc", # s[4:5] is a lane mask before overwrite - ] - + load_pair_lines(6, a64) - + load_pair_lines(8, b64) - + [ - insn, - "s_cselect_b32 s11, 1, 0", - "s_bcnt1_i32_b64 s10, s[4:5]", - "v_mov_b32 v0, s4", - "v_mov_b32 v1, s5", - "v_mov_b32 v2, s10", - "v_mov_b32 v3, s11", - ] - ) - outs, _ = run_ps_wave(lines, wave=wave) - expected = (want & MASK32, (want >> 32) & MASK32, want_cnt, 1 if want else 0) - for lane in range(wave): - self.assertEqual(outs[lane], expected, f"wave={wave} lane={lane}") - - def test_unsupported_destination_or_source_rejected(self): - for bad in ( - "s_and_b64 m0, s[4:5], s[6:7]", - "s_and_b64 s[2:3], s4, s[6:7]", - "s_not_b64 m0, s[4:5]", - "s_not_b64 s[2:3], s4", - ): - with self.subTest(bad=bad): - with self.assertRaises(rdna2spirv.Unsupported): - translate_ps([bad, "exp mrt0 v0, v0, v0, v0 done vm", "s_endpgm"]) - - -class LaneMaskPreservationTests(unittest.TestCase): - def test_wave32_all_six_ops_and_scc_vote(self): - # A = lanes 20..29 (10 lanes; lane 0 is OFF so per-lane SCC would differ from wave SCC!), - # B = lanes 25..31 (7 lanes). - # and(A, B) = 25..29 (5 lanes) SCC=1 - # or(A, B) = 20..31 (12 lanes) SCC=1 - # xor(A, B) = 20..24, 30..31 (7 lanes) SCC=1 - # andn2(A, B) = 20..24 (5 lanes) SCC=1 - # orn2(A, B) = 0..29 (30 lanes) SCC=1 - # not(A) = 0..19, 30..31 (22 lanes) SCC=1 - # and(A, not(A)) = empty (0 lanes) SCC=0 - cases = [ - ("s_and_b64 s[6:7], s[2:3], s[4:5]", lambda l: 25 <= l <= 29, 5, 1), - ("s_or_b64 s[6:7], s[2:3], s[4:5]", lambda l: 20 <= l <= 31, 12, 1), - ("s_xor_b64 s[6:7], s[2:3], s[4:5]", lambda l: (20 <= l <= 24) or (30 <= l <= 31), 7, 1), - ("s_andn2_b64 s[6:7], s[2:3], s[4:5]", lambda l: 20 <= l <= 24, 5, 1), - ("s_orn2_b64 s[6:7], s[2:3], s[4:5]", lambda l: l <= 29, 30, 1), - ("s_not_b64 s[6:7], s[2:3]", lambda l: not (20 <= l <= 29), 22, 1), - ("s_nand_b64 s[6:7], s[2:3], s[4:5]", lambda l: not (25 <= l <= 29), 27, 1), - ("s_nor_b64 s[6:7], s[2:3], s[4:5]", lambda l: l <= 19, 20, 1), - ("s_xnor_b64 s[6:7], s[2:3], s[4:5]", lambda l: l <= 19 or 25 <= l <= 29, 25, 1), - ] - for insn, pred, want_cnt, want_scc in cases: - with self.subTest(insn=insn): - lines = [ - "v_mbcnt_lo_u32_b32 v4, -1, 0", - "v_cmp_ge_u32_e64 s[2:3], v4, 20", - "v_cmp_lt_u32_e64 s[8:9], v4, 30", - "s_and_b64 s[2:3], s[2:3], s[8:9]", # A = 20..29 - "v_cmp_ge_u32_e64 s[4:5], v4, 25", # B = 25..31 - insn, - "s_cselect_b32 s10, 1, 0", - "s_bcnt1_i32_b64 s11, s[6:7]", - "v_mov_b32 v0, s11", - "v_mov_b32 v1, s10", - "v_mov_b32 v2, s6", - "v_mov_b32 v3, 0", - ] - outs, _ = run_ps_wave(lines, wave=32) - for lane in range(32): - want_bit = MASK32 if pred(lane) else 0 - self.assertEqual(outs[lane], (want_cnt, want_scc, want_bit, 0), f"lane={lane}") - - # Empty mask intersection -> SCC=0 across all lanes, and null dst on lane-mask path sets SCC. - lines = [ - "v_mbcnt_lo_u32_b32 v4, -1, 0", - "v_cmp_eq_u32_e32 vcc, 27, v4", - "s_and_b64 null, vcc, exec", - "s_cselect_b32 s10, 1, 0", - "s_not_b64 s[2:3], vcc", - "s_and_b64 null, vcc, s[2:3]", - "s_cselect_b32 s11, 1, 0", - "v_mov_b32 v0, s10", - "v_mov_b32 v1, s11", - "v_mov_b32 v2, 0", - "v_mov_b32 v3, 0", - ] - outs, _ = run_ps_wave(lines, wave=32) - for lane in range(32): - self.assertEqual(outs[lane], (1, 0, 0, 0), f"lane={lane}") - - def test_wave64_all_six_ops_exec_vcc_and_scc_vote(self): - # A = lanes 40..55 (16 lanes, strictly in upper half so lanes 0..31 are all OFF!), - # B = lanes 48..63 (16 lanes). - cases = [ - ("s_and_b64 s[6:7], vcc, s[4:5]", lambda l: 48 <= l <= 55, 8, 1), - ("s_or_b64 s[6:7], vcc, s[4:5]", lambda l: 40 <= l <= 63, 24, 1), - ("s_xor_b64 s[6:7], vcc, s[4:5]", lambda l: (40 <= l <= 47) or (56 <= l <= 63), 16, 1), - ("s_andn2_b64 s[6:7], vcc, s[4:5]", lambda l: 40 <= l <= 47, 8, 1), - ("s_orn2_b64 s[6:7], vcc, s[4:5]", lambda l: l <= 55, 56, 1), - ("s_not_b64 s[6:7], vcc", lambda l: not (40 <= l <= 55), 48, 1), - ("s_nand_b64 s[6:7], vcc, s[4:5]", lambda l: not (48 <= l <= 55), 56, 1), - ("s_nor_b64 s[6:7], vcc, s[4:5]", lambda l: l <= 39, 40, 1), - ("s_xnor_b64 s[6:7], vcc, s[4:5]", lambda l: l <= 39 or 48 <= l <= 55, 48, 1), - ] - for insn, pred, want_cnt, want_scc in cases: - with self.subTest(insn=insn): - lines = [ - "v_mbcnt_lo_u32_b32 v4, -1, 0", - "v_mbcnt_hi_u32_b32 v4, -1, v4", - "v_cmp_ge_u32_e32 vcc, v4, 40", - "v_cmp_lt_u32_e64 s[8:9], v4, 56", - "s_and_b64 vcc, vcc, s[8:9]", # vcc = 40..55 - "v_cmp_ge_u32_e64 s[4:5], v4, 48", # s[4:5] = 48..63 - insn, - "s_cselect_b32 s10, 1, 0", - "s_bcnt1_i32_b64 s11, s[6:7]", - "v_mov_b32 v1, 0x11", - "s_and_b64 exec, exec, s[6:7]", - "v_mov_b32 v1, 0x22", - "s_or_b64 exec, exec, -1", # restore all 64 lanes - "v_mov_b32 v0, s11", - "v_mov_b32 v2, s10", - "v_mov_b32 v3, 0", - ] - outs, _ = run_ps_wave(lines, wave=64) - for lane in range(64): - want_v1 = 0x22 if pred(lane) else 0x11 - self.assertEqual(outs[lane], (want_cnt, want_v1, want_scc, 0), f"lane={lane}") - - def test_wave64_compute_and_emulate_translation(self): - lines = [ - "v_cmp_lt_u32_e32 vcc, 39, v0", # lanes 40..63 (24 lanes) - "s_mov_b32 s6, 0x11223344", - "s_mov_b32 s7, 0x55667788", - "s_mov_b32 s8, 0x0F0F00FF", - "s_mov_b32 s9, 0xF0F0FF00", - "s_xor_b64 s[10:11], s[6:7], s[8:9]", # data xor: lo=0x1e2d33bb, hi=0xa5968888 - "s_not_b64 s[12:13], vcc", # mask not: 40 lanes set (0..39) - "s_bcnt1_i32_b64 s14, s[12:13]", - "v_cmp_eq_u32_e32 vcc, 0, v0", - "s_and_b64 exec, exec, vcc", - "v_mov_b32 v1, s10", - "v_mov_b32 v2, s11", - "v_mov_b32 v3, s14", - "v_mov_b32 v4, 0", - "buffer_store_dwordx4 v[1:4], v4, s[0:3], 0", - "s_or_b64 exec, exec, -1", - "s_endpgm", - ] - spv = translate_cs(lines) - mem = si.run_workgroup( - spv, - 64, - 64, - inputs_for=lambda i: {"%wg_id": (0, 0, 0), "%local_id": (i, 0, 0), "%sg_lane": i}, - push_constants=[0, 0, 0x1000, 0x31016FAC] + [0] * 28, - memory={}, - ) - self.assertEqual( - [mem.get(0), mem.get(4), mem.get(8), mem.get(12)], - [0x11223344 ^ 0x0F0F00FF, 0x55667788 ^ 0xF0F0FF00, 40, 0], - ) - - prev = rdna2spirv.WAVE64_EMULATE - try: - rdna2spirv.WAVE64_EMULATE = True - spv_emu = translate_cs(lines) - finally: - rdna2spirv.WAVE64_EMULATE = prev - self.assertIn("OpStore %x_it", spv_emu) - - -class NegativeControlTests(unittest.TestCase): - def test_sabotaging_high_dword_bitwise_breaks_result(self): - # Replacing the high-dword OpBitwiseXor with a copy of the low-dword result simulates - # the old mask_dst bug (duplicating lo into hi). - lines = ( - load_pair_lines(4, 0x55667788_11223344) - + load_pair_lines(6, 0xF0F0FF00_0F0F00FF) - + [ - "s_xor_b64 s[2:3], s[4:5], s[6:7]", - "v_mov_b32 v0, s2", - "v_mov_b32 v1, s3", - "v_mov_b32 v2, 0", - "v_mov_b32 v3, 0", - ] - ) - words, spv = run_ps(lines) - want_lo = 0x11223344 ^ 0x0F0F00FF - want_hi = 0x55667788 ^ 0xF0F0FF00 - self.assertEqual(words[:2], [want_lo, want_hi]) - m = re.search( - r"(%\w+) = OpBitwiseXor %uint %\w+ %\w+\s+" - r"(%\w+) = OpBitwiseXor %uint %\w+ %\w+", - spv, - ) - self.assertIsNotNone(m) - lo_id, hi_id = m.group(1), m.group(2) - bad = re.sub( - rf"{re.escape(hi_id)} = OpBitwiseXor %uint [^\n]+", - f"{hi_id} = OpCopyObject %uint {lo_id}", - spv, - count=1, - ) - self.assertNotEqual(bad, spv) - self.assertEqual(mrt0_words(bad)[:2], [want_lo, want_lo]) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_salu64_fixture.py b/tests/semantic/test_salu64_fixture.py deleted file mode 100644 index 3f48a731b..000000000 --- a/tests/semantic/test_salu64_fixture.py +++ /dev/null @@ -1,97 +0,0 @@ -"""cs_w32_salu64: the GPU test of the 64-bit scalar data ops and v_mad_u64_u32, run here on the CPU too. - -Standard library only; no GPU, no LLVM, no game files. - -runtime/test/shaders/cs_w32_salu64.asm has lane 0 of a wave32 group store one word of each of s_brev_b64, -s_bfe_u64, s_bfe_i64, s_bitset1_b64, s_flbit_i32_b64, s_flbit_i32_i64, s_cmov_b32 of s_sext_i32_i16 and -v_mad_u64_u32 (derivations in its header). These ops were checked on the CPU only. This runs the fixture -(tests/semantic/regen_fixtures.py) through spirv_mini_interp, checks the eight words against values computed here -from the ISA definitions, and checks that check.py and scripts/run_gpu_tests.py expect the same words on the GPU. -""" -import os -import re -import struct -import unittest - -import support -import spirv_mini_interp as si - -HERE = os.path.dirname(os.path.abspath(__file__)) -ROOT = os.path.dirname(os.path.dirname(HERE)) -M32 = 0xFFFFFFFF -M64 = (1 << 64) - 1 - -# 4 user SGPRs (the output V#), workgroup id in s4, 32x1x1 threads. -FSSM = bytearray(0x148) -struct.pack_into("<4I", FSSM, 0x138, 0x88, 32, 1, 1) -FSSM = bytes(FSSM) -VSHARP = [0, 0, 0x1000, 0x31016FAC] - - -def brev64(x: int) -> int: - return int(f"{x & M64:064b}"[::-1], 2) - - -def bfe64(x: int, s1: int, signed: bool) -> int: - off, width = s1 & 63, (s1 >> 16) & 127 - v = (x >> off) & ((1 << width) - 1) - if signed and width and v >> (width - 1): - v -= 1 << width - return v & M64 - - -def flbit_b64(x: int) -> int: - return 64 - x.bit_length() if x else M32 - - -def flbit_i64(x: int) -> int: - sign = x >> 63 - for i in range(62, -1, -1): - if (x >> i) & 1 != sign: - return 63 - i - return M32 - - -def sext16(x: int) -> int: - x &= 0xFFFF - return (x - 0x10000 if x >> 15 else x) & M32 - - -EXPECTED = [ - brev64(0x12345678_0000000F) & M32, # s_brev_b64, low word - bfe64(0x00000123_45678000, 0x10001C, False) & M32, # s_bfe_u64, low word - bfe64(0x00000001_80000000, 0x2001F, True) >> 32, # s_bfe_i64, high word - (1 << 40) >> 32, # s_bitset1_b64, high word - flbit_b64(0x00000000_00010000), # s_flbit_i32_b64 - flbit_i64(0xFFFFFFFF_FFFF0000), # s_flbit_i32_i64 - sext16(0x00018000), # s_cmov_b32 (SCC = 1) of s_sext_i32_i16 - ((M32 * M32 + M64) & M64) >> 32, # v_mad_u64_u32, high word -] - - -class Salu64Fixture(unittest.TestCase): - def test_reference(self): - self.assertEqual(EXPECTED, [0x1E6A2C48, 0x1234, 0xFFFFFFFF, 0x100, 47, 48, 0xFFFF8000, 0xFFFFFFFE]) - - def test_translated_shader(self): - spv = support.translate_fixture("cs_w32_salu64", fssm=FSSM) - mem = si.run_workgroup(spv, 1, 32, inputs_for=lambda i: {"%wg_id": (0, 0, 0), "%local_id": (i, 0, 0), - "%sg_lane": i}, - push_constants=VSHARP + [0] * 28, memory={}) - self.assertEqual(sorted(mem), [4 * k for k in range(8)]) - for k, want in enumerate(EXPECTED): - with self.subTest(word=k): - self.assertEqual(mem[4 * k], want) - - def test_gpu_runners_expect_the_same_words(self): - for rel in (("runtime", "test", "shaders", "check.py"), ("scripts", "run_gpu_tests.py")): - with open(os.path.join(ROOT, *rel), encoding="utf-8") as f: - text = f.read() - m = re.search(r'"cs_w32_salu64"\)?[,:]\s*\[([^\]]*)\]', text) - with self.subTest(file="/".join(rel)): - self.assertIsNotNone(m) - self.assertEqual([int(v, 0) for v in m.group(1).split(",")], EXPECTED) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_salu_absdiff_mul_hi.py b/tests/semantic/test_salu_absdiff_mul_hi.py deleted file mode 100644 index 2cb89a7c9..000000000 --- a/tests/semantic/test_salu_absdiff_mul_hi.py +++ /dev/null @@ -1,125 +0,0 @@ -"""Semantic interpreter tests for RDNA2 s_absdiff_i32 and s_mul_hi_i32. - -s_absdiff_i32 (RDNA2 ISA): D = S0 - S1 as a signed 32-bit value, negated if negative; SCC = (D != 0). The -subtraction wraps first, so 0x7FFFFFFF - 0x80000000 is -1 and gives 1, and a difference of -2^31 stays 0x80000000. -s_mul_hi_i32: D = the high 32 bits of the signed 64-bit product S0 * S1; SCC is not written. Each case translates a -synthetic pixel shader with tools/rdna2spirv.py, runs it in tests/semantic/spirv_mini_interp.py and compares the -exported words (D, and SCC through s_cselect_b32) with a plain-Python reference. -""" -import os -import random -import struct -import sys -import tempfile -import unittest -import warnings - -HERE = os.path.dirname(os.path.abspath(__file__)) -ROOT = os.path.dirname(os.path.dirname(HERE)) -TOOLS_DIR = os.environ.get("LEONIDA_TOOLS_DIR") or os.path.join(ROOT, "tools") - -sys.dont_write_bytecode = True -sys.path.insert(0, TOOLS_DIR) -sys.path.insert(0, HERE) - -import rdna2spirv # noqa: E402 -import spirv_mini_interp as si # noqa: E402 - -MASK32 = 0xFFFFFFFF -STUB_DXBC = b"DXBC" + bytes(24) + struct.pack(" int: - x &= MASK32 - return x - (1 << 32) if x >> 31 else x - - -def ref_absdiff(x: int, y: int) -> int: - d = s32(x - y) # the 32-bit difference, wrapped - return (-d if d < 0 else d) & MASK32 - - -def ref_mul_hi_i32(x: int, y: int) -> int: - return ((s32(x) * s32(y)) >> 32) & MASK32 - - -_TMP_DIR = None -_SRC_PATH = None - - -def setUpModule(): - global _TMP_DIR, _SRC_PATH - _TMP_DIR = tempfile.TemporaryDirectory() - disasm_dir = os.path.join(_TMP_DIR.name, "disasm") - os.mkdir(disasm_dir) - _SRC_PATH = os.path.join(disasm_dir, "ps_salu_absdiff.s") - with open(os.path.join(_TMP_DIR.name, "ps_salu_absdiff.dxbc"), "wb") as f: - f.write(STUB_DXBC) - - -def tearDownModule(): - global _TMP_DIR - if _TMP_DIR is not None: - _TMP_DIR.cleanup() - _TMP_DIR = None - - -def run_op(op: str, x: int, y: int, scc_in: int) -> tuple: - """SCC = scc_in, then s0 = op(s2, s3); return (s0, SCC after).""" - if _TMP_DIR is None: - setUpModule() - lines = [f"s_mov_b32 s2, {x:#x}", f"s_mov_b32 s3, {y:#x}", f"s_mov_b32 s4, {scc_in}", "s_cmp_eq_u32 s4, 1", - f"{op} s0, s2, s3", "s_cselect_b32 s1, 1, 0", "v_mov_b32 v0, s0", "v_mov_b32 v1, s1"] - asm = "; test_salu_absdiff\n" + "".join(f"\t{ln}\n" for ln in lines) + "\texp mrt0 v0, v1, v0, v0 done vm\n\ts_endpgm\n" - with open(_SRC_PATH, "w", encoding="utf-8") as f: - f.write(asm) - with warnings.catch_warnings(): - warnings.simplefilter("ignore", ResourceWarning) - spv = rdna2spirv.translate(_SRC_PATH) - return tuple(si.run_fragment(spv)["%out_mrt0"][:2]) - - -class AbsdiffTests(unittest.TestCase): - def test_reference(self): - self.assertEqual(ref_absdiff(1, 3), 2) - self.assertEqual(ref_absdiff(0x7FFFFFFF, 0x80000000), 1) # wraps to -1 first - self.assertEqual(ref_absdiff(0, 0x80000000), 0x80000000) # -2^31 is its own absolute value - self.assertEqual(ref_absdiff(0xFFFFFFFF, 1), 2) # -1 - 1 - - def test_values_and_scc(self): - for x in VALUES: - for y in VALUES: - want = ref_absdiff(x, y) - with self.subTest(x=hex(x), y=hex(y)): - self.assertEqual(run_op("s_absdiff_i32", x, y, 1 - int(want != 0)), (want, int(want != 0))) - - def test_seeded(self): - rng = random.Random(0xAD) - for _ in range(30): - x, y = rng.getrandbits(32), rng.getrandbits(32) - with self.subTest(x=hex(x), y=hex(y)): - self.assertEqual(run_op("s_absdiff_i32", x, y, 0), (ref_absdiff(x, y), int(x != y))) - - -class MulHiI32Tests(unittest.TestCase): - def test_reference(self): - self.assertEqual(ref_mul_hi_i32(0xFFFFFFFF, 1), 0xFFFFFFFF) # -1 * 1: high word -1 - self.assertEqual(ref_mul_hi_i32(0x80000000, 0x80000000), 0x40000000) - self.assertEqual(ref_mul_hi_i32(0x80000000, 0x7FFFFFFF), 0xC0000000) - - def test_values_and_scc_kept(self): - for x in VALUES: - for y in VALUES[::2]: - for scc_in in (0, 1): - with self.subTest(x=hex(x), y=hex(y), scc=scc_in): - self.assertEqual(run_op("s_mul_hi_i32", x, y, scc_in), (ref_mul_hi_i32(x, y), scc_in)) - - def test_differs_from_unsigned(self): - # Same operands, s_mul_hi_u32 gives the unsigned high word. - self.assertEqual(run_op("s_mul_hi_u32", 0xFFFFFFFF, 2, 0)[0], 1) - self.assertEqual(run_op("s_mul_hi_i32", 0xFFFFFFFF, 2, 0)[0], 0xFFFFFFFF) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_salu_add_co_u32.py b/tests/semantic/test_salu_add_co_u32.py deleted file mode 100644 index 3b7fe7ab9..000000000 --- a/tests/semantic/test_salu_add_co_u32.py +++ /dev/null @@ -1,282 +0,0 @@ -from __future__ import annotations - -"""Semantic interpreter tests for RDNA2 scalar add with carry out (s_add_co_u32 / s_add_u32). - -In the AMD RDNA2 ISA: - * s_add_u32 (scalar add with unsigned carry-out, functionally s_add_co_u32): - D.u = (S0.u + S1.u) mod 2^32 - SCC = (S0.u + S1.u >= 2^32) - * Lowers in SPIR-V (tools/rdna2spirv.py) to OpIAddCarry %umul %s0 %s1: - Member 0: 32-bit wrapped sum (stored in destination SGPR D) - Member 1: 32-bit unsigned carry-out (stored in SCC condition flag register) - -This test module verifies mathematical reference behavior, condition code updates, -modulo wrapping, boundary extremes, register aliasing, and translation lowering. -""" - -import os -import random -import struct -import sys -import tempfile -import unittest -import warnings - -HERE = os.path.dirname(os.path.abspath(__file__)) -ROOT = os.path.dirname(os.path.dirname(HERE)) -TOOLS_DIR = os.environ.get("LEONIDA_TOOLS_DIR") or os.path.join(ROOT, "tools") - -sys.dont_write_bytecode = True -if TOOLS_DIR not in sys.path: - sys.path.insert(0, TOOLS_DIR) -if HERE not in sys.path: - sys.path.insert(0, HERE) - -import rdna2spirv # noqa: E402 -import spirv_mini_interp as si # noqa: E402 - -M32 = 0xFFFFFFFF -MASK64 = (1 << 64) - 1 -STUB_DXBC = b"DXBC" + bytes(24) + struct.pack(" tuple[int, int]: - """Pure reference oracle for RDNA2 scalar add with carry-out (s_add_co_u32 / s_add_u32). - - Computes unsigned 32-bit sum (s0 + s1) mod 2^32 and the 1-bit carry-out flag SCC. - Returns (result, scc). - """ - a = s0 & M32 - b = s1 & M32 - full = a + b - return full & M32, 1 if full >= (1 << 32) else 0 - - -def oracle_add_co_u32_analysis(s0: int, s1: int) -> dict[str, int | bool]: - """Detailed arithmetic analysis for scalar add with carry: inputs, 64-bit sum, carry flag, and wrapped result.""" - a = s0 & M32 - b = s1 & M32 - full = a + b - has_carry = full >= (1 << 32) - wrapped = full & M32 - return { - "s0": a, - "s1": b, - "full_sum": full, - "carry": has_carry, - "scc": 1 if has_carry else 0, - "wrapped_result": wrapped, - } - - -class ScalarALUState: - """Minimal deterministic interpreter state modeling SGPR bank and SCC flag.""" - - def __init__(self, num_sgprs: int = 106) -> None: - self.sgpr = [0] * num_sgprs - self.scc = 0 - - def reset(self) -> None: - self.sgpr = [0] * len(self.sgpr) - self.scc = 0 - - def step(self, op: str, dst: int, s0: int | str, s1: int | str | None = None) -> tuple[int, int]: - """Execute a single scalar ALU instruction.""" - canonical_op = "s_add_u32" if op in ("s_add_co_u32", "s_add_u32") else op - v0 = self.sgpr[int(s0[1:])] if isinstance(s0, str) and s0.startswith("s") else int(s0) & M32 - v1 = 0 - if s1 is not None: - v1 = self.sgpr[int(s1[1:])] if isinstance(s1, str) and s1.startswith("s") else int(s1) & M32 - - if canonical_op == "s_mov_b32": - res = v0 - # SCC is not modified by s_mov_b32 - elif canonical_op == "s_add_u32": - res, scc = ref_s_add_co_u32(v0, v1) - self.scc = scc - elif canonical_op == "s_cselect_b32": - res = v0 if self.scc != 0 else v1 - else: - raise NotImplementedError(f"Unsupported op in ScalarALUState: {op}") - - self.sgpr[dst] = res & M32 - return self.sgpr[dst], self.scc - - -_TMP_DIR = None -_SRC_PATH = None - - -def setUpModule() -> None: - global _TMP_DIR, _SRC_PATH - _TMP_DIR = tempfile.TemporaryDirectory() - disasm_dir = os.path.join(_TMP_DIR.name, "disasm") - os.mkdir(disasm_dir) - _SRC_PATH = os.path.join(disasm_dir, "ps_salu_add_co.s") - with open(os.path.join(_TMP_DIR.name, "ps_salu_add_co.dxbc"), "wb") as f: - f.write(STUB_DXBC) - - -def tearDownModule() -> None: - global _TMP_DIR - if _TMP_DIR is not None: - _TMP_DIR.cleanup() - _TMP_DIR = None - - -def run_lines(lines: list[str]) -> tuple[int, int]: - """Assemble synthetic pixel shader lines, translate with rdna2spirv, run via mini-interpreter. - - Returns (v0, v1) where v0 is the 32-bit computation result and v1 is the extracted SCC flag. - """ - if _TMP_DIR is None: - setUpModule() - asm = "; test_salu_add_co_u32\n" + "".join(f"\t{ln}\n" for ln in lines) + "\texp mrt0 v0, v1, v0, v0 done vm\n\ts_endpgm\n" - with open(_SRC_PATH, "w", encoding="utf-8") as f: - f.write(asm) - with warnings.catch_warnings(): - warnings.simplefilter("ignore", ResourceWarning) - spv = rdna2spirv.translate(_SRC_PATH) - return tuple(si.run_fragment(spv)["%out_mrt0"][:2]) - - -def run_op(s0: int, s1: int, scc_in: int = 0, op: str = "s_add_co_u32") -> tuple[int, int]: - """Execute scalar add with carry via SPIR-V translator and interpreter. - - Preset SCC to `scc_in`, execute instruction, and read back result and post-op SCC. - Returns (result, scc_out). - """ - canonical_insn = "s_add_u32" if op in ("s_add_co_u32", "s_add_u32") else op - lines = [ - f"s_mov_b32 s2, {s0 & M32:#x}", - f"s_mov_b32 s3, {s1 & M32:#x}", - f"s_cmp_eq_u32 {1 if scc_in else 0}, 1", # preset SCC - f"{canonical_insn} s0, s2, s3", - "s_cselect_b32 s1, 1, 0", # read SCC into s1 - "v_mov_b32 v0, s0", - "v_mov_b32 v1, s1", - ] - return run_lines(lines) - - -class TestSaluAddCoU32ReferenceOracle(unittest.TestCase): - """Reference oracle tests for RDNA2 scalar add with carry out (s_add_co_u32).""" - - def test_oracle_zero_identity(self) -> None: - """Adding 0 to any value must return the original value with SCC = 0.""" - cases = [0, 1, 42, 0x12345678, 0x7FFFFFFF, 0x80000000, 0xFFFFFFFE, 0xFFFFFFFF] - for val in cases: - with self.subTest(val=hex(val)): - res0, scc0 = ref_s_add_co_u32(val, 0) - self.assertEqual(res0, val) - self.assertEqual(scc0, 0) - - res1, scc1 = ref_s_add_co_u32(0, val) - self.assertEqual(res1, val) - self.assertEqual(scc1, 0) - - def test_oracle_basic_addition_no_carry(self) -> None: - """Sums strictly below 2^32 must produce exact integer sum with SCC = 0.""" - cases = [ - (10, 20, 30), - (0x1000, 0x2000, 0x3000), - (0x12345678, 0x01020304, 0x1336597C), - (0x7FFFFFFE, 1, 0x7FFFFFFF), - (0x40000000, 0x3FFFFFFF, 0x7FFFFFFF), - (0x7FFFFFFF, 0x7FFFFFFF, 0xFFFFFFFE), - (0x7FFFFFFF, 0x80000000, 0xFFFFFFFF), - ] - for a, b, expected_sum in cases: - with self.subTest(a=hex(a), b=hex(b)): - res, scc = ref_s_add_co_u32(a, b) - self.assertEqual(res, expected_sum) - self.assertEqual(scc, 0) - - def test_oracle_carry_detection(self) -> None: - """Sums at or above 2^32 must set SCC = 1 and wrap modulo 2^32.""" - cases = [ - (0xFFFFFFFF, 1, 0, 1), - (0xFFFFFFFF, 2, 1, 1), - (0xFFFFFFFE, 2, 0, 1), - (0x80000000, 0x80000000, 0, 1), - (0x80000000, 0x80000001, 1, 1), - (0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFE, 1), - (0xC0000000, 0x50000000, 0x10000000, 1), - ] - for a, b, exp_res, exp_scc in cases: - with self.subTest(a=hex(a), b=hex(b)): - res, scc = ref_s_add_co_u32(a, b) - self.assertEqual(res, exp_res) - self.assertEqual(scc, exp_scc) - - def test_oracle_commutativity(self) -> None: - """s_add_co_u32 must be strictly commutative across all operand ranges.""" - test_pairs = [ - (0, 0), - (0, 0xFFFFFFFF), - (1, 0xFFFFFFFF), - (0x12345678, 0x87654321), - (0x80000000, 0x80000000), - (0x7FFFFFFF, 0x80000000), - (0xFFFFFFFF, 0xFFFFFFFF), - (0xCAFEBABE, 0xDEADBEEF), - (0xAAAAAAAA, 0x55555555), - ] - for a, b in test_pairs: - with self.subTest(a=hex(a), b=hex(b)): - r1, s1 = ref_s_add_co_u32(a, b) - r2, s2 = ref_s_add_co_u32(b, a) - self.assertEqual(r1, r2) - self.assertEqual(s1, s2) - - def test_oracle_analysis_breakdown(self) -> None: - """Detailed analysis oracle must accurately compute components.""" - info = oracle_add_co_u32_analysis(0xFFFFFFFF, 1) - self.assertEqual(info["s0"], 0xFFFFFFFF) - self.assertEqual(info["s1"], 1) - self.assertEqual(info["full_sum"], 0x100000000) - self.assertTrue(info["carry"]) - self.assertEqual(info["scc"], 1) - self.assertEqual(info["wrapped_result"], 0) - - info2 = oracle_add_co_u32_analysis(0x1234, 0x5678) - self.assertFalse(info2["carry"]) - self.assertEqual(info2["scc"], 0) - self.assertEqual(info2["wrapped_result"], 0x68AC) - - def test_state_interpreter_execution(self) -> None: - """ScalarALUState must correctly track register writes and SCC updates.""" - state = ScalarALUState() - state.step("s_mov_b32", dst=2, s0=0xFFFFFFFF) - state.step("s_mov_b32", dst=3, s0=1) - res, scc = state.step("s_add_co_u32", dst=4, s0="s2", s1="s3") - self.assertEqual(res, 0) - self.assertEqual(scc, 1) - self.assertEqual(state.sgpr[4], 0) - self.assertEqual(state.scc, 1) - - # Ensure s_cselect_b32 uses updated SCC - csel_res, _ = state.step("s_cselect_b32", dst=5, s0=0xCAFE, s1=0xBEEF) - self.assertEqual(csel_res, 0xCAFE) - - def test_spirv_translation_matches_oracle(self) -> None: - """SPIR-V translation and execution must match reference oracle for representative inputs.""" - sample_pairs = [ - (0, 0), - (100, 200), - (0x7FFFFFFF, 0), - (0x7FFFFFFF, 1), - (0xFFFFFFFF, 0), - (0xFFFFFFFF, 1), - (0x80000000, 0x80000000), - (0xFFFFFFFF, 0xFFFFFFFF), - ] - for a, b in sample_pairs: - with self.subTest(a=hex(a), b=hex(b)): - got_res, got_scc = run_op(a, b, scc_in=0, op="s_add_co_u32") - exp_res, exp_scc = ref_s_add_co_u32(a, b) - self.assertEqual((got_res, got_scc), (exp_res, exp_scc)) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_salu_add_sub_co_u32.py b/tests/semantic/test_salu_add_sub_co_u32.py deleted file mode 100644 index 497213d45..000000000 --- a/tests/semantic/test_salu_add_sub_co_u32.py +++ /dev/null @@ -1,99 +0,0 @@ -"""s_add_u32, s_addc_u32, s_sub_u32, s_subb_u32 (the scalar add/subtract with carry) through the translator. - -RDNA2 ISA, SOP2: - s_add_u32 D = S0 + S1 (mod 2^32), SCC = carry out of bit 31 - s_addc_u32 D = S0 + S1 + SCC (mod 2^32), SCC = carry out - s_sub_u32 D = S0 - S1 (mod 2^32), SCC = 1 if S1 > S0 (borrow) - s_subb_u32 D = S0 - S1 - SCC (mod 2^32), SCC = 1 if S1 + SCC > S0 (borrow) -The operands are SGPRs, 32-bit literals or inline constants (-16..64); the carry-in is made with s_cmp_eq_u32. - -Each case translates a hand-written pixel shader with tools/rdna2spirv.py (support.translate_lines), runs it -(support.mrt0_words) and compares the destination and SCC with a plain-Python reference and with hand-written words. -test_carry_chain.py already runs the 64-bit add/subtract chains and the vector forms; this file covers the operand -forms and the SCC in/out of the scalar ones. Until this file, the test of this name ran a self-built interpreter and -never called the translator. -""" -import os -import random -import sys -import unittest - -sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) -import support # noqa: E402 - -M32 = 0xFFFFFFFF - - -def ref(op, s0, s1, scc): - if op == "s_add_u32": - t = s0 + s1 - elif op == "s_addc_u32": - t = s0 + s1 + scc - elif op == "s_sub_u32": - t = s0 - s1 - else: - t = s0 - s1 - scc - return t & M32, int(t >= 1 << 32) if "add" in op else int(t < 0) - - -def operand(kind, reg, v): - """(setup lines, operand text) giving S0/S1 the value v.""" - if kind == "sgpr": - return [f"s_mov_b32 s{reg}, {v:#x}"], f"s{reg}" - return [], f"{v:#x}" # a literal (or inline constant when it is one) - - -def run(op, s0, s1, scc, k0="sgpr", k1="sgpr"): - a, t0 = operand(k0, 10, s0) - b, t1 = operand(k1, 11, s1) - lines = a + b + ["s_mov_b32 s12, 0", "s_cmp_eq_u32 s12, %d" % (0 if scc else 1), # SCC = scc - f"{op} s13, {t0}, {t1}", "s_cselect_b32 s14, 1, 0", "v_mov_b32_e32 v0, s13", "v_mov_b32_e32 v1, s14", - "exp mrt0 v0, v1, v0, v0 done vm", "s_endpgm"] - return tuple(support.mrt0_words(support.translate_lines("ps_salu_add_sub_co", lines))[:2]) - - -OPS = ("s_add_u32", "s_addc_u32", "s_sub_u32", "s_subb_u32") -EDGE = (0, 1, 2, 0x7FFFFFFF, 0x80000000, 0xFFFFFFFE, 0xFFFFFFFF) - - -class TestByHand(unittest.TestCase): - def test_words(self): - # (op, S0, S1, SCC in) -> (D, SCC out), written out from the formulas above. - for case, want in ( - (("s_add_u32", 0xFFFFFFFF, 1, 0), (0, 1)), (("s_add_u32", 0x7FFFFFFF, 1, 1), (0x80000000, 0)), - (("s_addc_u32", 0xFFFFFFFF, 0, 1), (0, 1)), (("s_addc_u32", 0xFFFFFFFF, 0, 0), (0xFFFFFFFF, 0)), - (("s_addc_u32", 5, 6, 1), (12, 0)), (("s_addc_u32", 0xFFFFFFFF, 0xFFFFFFFF, 1), (0xFFFFFFFF, 1)), - (("s_sub_u32", 0, 1, 0), (0xFFFFFFFF, 1)), (("s_sub_u32", 5, 5, 1), (0, 0)), - (("s_subb_u32", 5, 5, 1), (0xFFFFFFFF, 1)), (("s_subb_u32", 5, 5, 0), (0, 0)), - (("s_subb_u32", 0, 0xFFFFFFFF, 1), (0, 1)), (("s_subb_u32", 0x80000000, 1, 1), (0x7FFFFFFE, 0)), - ): - with self.subTest(case=case): - self.assertEqual(ref(*case), want) - self.assertEqual(run(*case), want) - - -class TestForms(unittest.TestCase): - def test_operand_forms(self): - for op in OPS: - for k0, k1 in (("sgpr", "sgpr"), ("literal", "sgpr"), ("sgpr", "literal")): - for s0, s1, scc in ((0xFFFFFFFF, 1, 1), (0x80000000, 0x80000000, 0), (7, 0x12345678, 1), (3, 3, 0)): - with self.subTest(op=op, forms=(k0, k1), s0=hex(s0), s1=hex(s1), scc=scc): - self.assertEqual(run(op, s0, s1, scc, k0, k1), ref(op, s0, s1, scc)) - - def test_inline_constants(self): - for op in OPS: - for s0, s1 in ((64, 1), (0, 16), (63, 64), (1, 0)): - with self.subTest(op=op, s0=s0, s1=s1): - self.assertEqual(run(op, s0, s1, 1, "literal", "literal"), ref(op, s0, s1, 1)) - - def test_seeded(self): - rng = random.Random(0x5CC) - for _ in range(30): - op, scc = rng.choice(OPS), rng.getrandbits(1) - s0, s1 = rng.choice((rng.getrandbits(32),) + EDGE), rng.choice((rng.getrandbits(32),) + EDGE) - with self.subTest(op=op, s0=hex(s0), s1=hex(s1), scc=scc): - self.assertEqual(run(op, s0, s1, scc), ref(op, s0, s1, scc)) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_salu_and_saveexec_b64.py b/tests/semantic/test_salu_and_saveexec_b64.py deleted file mode 100644 index 3d3fcbe00..000000000 --- a/tests/semantic/test_salu_and_saveexec_b64.py +++ /dev/null @@ -1,34 +0,0 @@ -"""s_and_saveexec_b64 through the translator, on every lane of a wave64. - -RDNA2 ISA, SOP1: - s_and_saveexec_b64: D = EXEC; EXEC = S0 & EXEC; SCC = (EXEC != 0). - -Each case translates a hand-written compute program with tools/rdna2spirv.py and runs 64 lanes in -tests/semantic/spirv_mini_interp.py (harness: saveexec_run.py), with S0 from VCC, an SGPR pair written by v_cmp, an -SGPR pair loaded with literals, and EXEC itself, against the ISA formula in plain Python. Until this file, the test of -this name ran a self-built interpreter and never called the translator. -""" -import os -import sys -import unittest - -sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) -import saveexec_run # noqa: E402 (support puts tools/ on sys.path) - - -class Saveexec(unittest.TestCase): - def test_and_by_hand(self): - # S0 = lanes 0..31, EXEC = lanes 16..47: EXEC = S0 & EXEC written out by hand. - lanes = lambda lo, hi: sum(1 << l for l in range(lo, hi)) - s0, e = lanes(0, 32), lanes(16, 48) - want = {"and": lanes(16, 32), "andn2": lanes(0, 16), "or": lanes(0, 48), "orn2": lanes(0, 32) | lanes(48, 64) | lanes(16, 32), - "xor": lanes(0, 16) | lanes(32, 48), "nand": lanes(0, 16) | lanes(32, 64), - "nor": lanes(48, 64), "xnor": lanes(16, 32) | lanes(48, 64)}["and"] - self.assertEqual(saveexec_run.model("and", s0, e), (want, e, 1)) - - def test_and_every_lane(self): - saveexec_run.check(self, "and") - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_salu_andn2_b64.py b/tests/semantic/test_salu_andn2_b64.py deleted file mode 100644 index d034ecdfd..000000000 --- a/tests/semantic/test_salu_andn2_b64.py +++ /dev/null @@ -1,552 +0,0 @@ -"""Semantic reference oracle and verification for RDNA2 64-bit inverted scalar logic. - -Covers: - - s_andn2_b64: D = S0 & (~S1) - - s_orn2_b64: D = S0 | (~S1) - - s_nand_b64: D = ~(S0 & S1) - - s_nor_b64: D = ~(S0 | S1) - - s_xnor_b64: D = ~(S0 ^ S1) - - Condition code SCC: SCC = 1 if D != 0 else 0 - -Tests standard library bitwise arithmetic, truth table exhaustion, boundary patterns, -four-corner SCC zero/nonzero matrix, and non-commutative operand asymmetry. -""" -from __future__ import annotations - -import os -import random -import sys -import unittest - -HERE = os.path.dirname(os.path.abspath(__file__)) -ROOT = os.path.dirname(os.path.dirname(HERE)) -TOOLS_DIR = os.environ.get("LEONIDA_TOOLS_DIR") or os.path.join(ROOT, "tools") - -sys.dont_write_bytecode = True -if HERE not in sys.path: - sys.path.insert(0, HERE) -if TOOLS_DIR not in sys.path: - sys.path.insert(0, TOOLS_DIR) - -from support import translate_lines, mrt0_words # noqa: E402 - -MASK32 = 0xFFFFFFFF -MASK64 = 0xFFFFFFFFFFFFFFFF - - -def ref_andn2_b64(s0: int, s1: int) -> int: - """RDNA2 s_andn2_b64: D = S0 & (~S1).""" - return (s0 & (~s1 & MASK64)) & MASK64 - - -def ref_orn2_b64(s0: int, s1: int) -> int: - """RDNA2 s_orn2_b64: D = S0 | (~S1).""" - return (s0 | (~s1 & MASK64)) & MASK64 - - -def ref_nand_b64(s0: int, s1: int) -> int: - """RDNA2 s_nand_b64: D = ~(S0 & S1).""" - return (~(s0 & s1)) & MASK64 - - -def ref_nor_b64(s0: int, s1: int) -> int: - """RDNA2 s_nor_b64: D = ~(S0 | S1).""" - return (~(s0 | s1)) & MASK64 - - -def ref_xnor_b64(s0: int, s1: int) -> int: - """RDNA2 s_xnor_b64: D = ~(S0 ^ S1).""" - return (~(s0 ^ s1)) & MASK64 - - -def ref_scc(val64: int) -> int: - """RDNA2 SCC condition flag: 1 if 64-bit result != 0, else 0.""" - return 1 if (val64 & MASK64) != 0 else 0 - - -REF_OPS = { - "s_andn2_b64": ref_andn2_b64, - "s_orn2_b64": ref_orn2_b64, - "s_nand_b64": ref_nand_b64, - "s_nor_b64": ref_nor_b64, - "s_xnor_b64": ref_xnor_b64, -} - - -class SaluInvertedLogicOracleTests(unittest.TestCase): - """Reference mathematical oracle tests for 64-bit inverted scalar logic.""" - - def test_truth_table_bit_by_bit(self): - """Verify 1-bit truth table combinations across all 5 inverted operations.""" - truth_tables = { - "s_andn2_b64": {(0, 0): 0, (0, 1): 0, (1, 0): 1, (1, 1): 0}, - "s_orn2_b64": {(0, 0): 1, (0, 1): 0, (1, 0): 1, (1, 1): 1}, - "s_nand_b64": {(0, 0): 1, (0, 1): 1, (1, 0): 1, (1, 1): 0}, - "s_nor_b64": {(0, 0): 1, (0, 1): 0, (1, 0): 0, (1, 1): 0}, - "s_xnor_b64": {(0, 0): 1, (0, 1): 0, (1, 0): 0, (1, 1): 1}, - } - for op, table in truth_tables.items(): - fn = REF_OPS[op] - for (b0, b1), expected_bit in table.items(): - with self.subTest(op=op, b0=b0, b1=b1): - s0 = MASK64 if b0 else 0 - s1 = MASK64 if b1 else 0 - want = MASK64 if expected_bit else 0 - got = fn(s0, s1) - self.assertEqual(got, want) - self.assertEqual(ref_scc(got), 1 if expected_bit else 0) - - def test_symmetry_and_asymmetry(self): - """Test commutativity for nand/nor/xnor and non-commutativity for andn2/orn2.""" - a = 0xF0F0F0F0_0F0F0F0F - b = 0x33333333_CCCCCCCC - for op in ("s_nand_b64", "s_nor_b64", "s_xnor_b64"): - fn = REF_OPS[op] - with self.subTest(op=op, prop="commutative"): - self.assertEqual(fn(a, b), fn(b, a)) - - for op in ("s_andn2_b64", "s_orn2_b64"): - fn = REF_OPS[op] - with self.subTest(op=op, prop="non-commutative"): - self.assertNotEqual(fn(a, b), fn(b, a)) - - def test_boundary_values(self): - """Test edge cases with 0, MASK64, MSB, LSB, and alternating bit patterns.""" - boundaries = [ - 0x00000000_00000000, - 0xFFFFFFFF_FFFFFFFF, - 0x80000000_00000000, - 0x00000000_00000001, - 0x55555555_55555555, - 0xAAAAAAAA_AAAAAAAA, - 0x00000000_FFFFFFFF, - 0xFFFFFFFF_00000000, - 0x12345678_9ABCDEF0, - 0xEDCBA987_6543210F, - ] - for op, fn in REF_OPS.items(): - for s0 in boundaries: - for s1 in boundaries: - with self.subTest(op=op, s0=hex(s0), s1=hex(s1)): - res = fn(s0, s1) - self.assertGreaterEqual(res, 0) - self.assertLessEqual(res, MASK64) - scc = ref_scc(res) - self.assertIn(scc, (0, 1)) - self.assertEqual(scc, 1 if res != 0 else 0) - - def test_scc_four_corners(self): - """Verify SCC accurately distinguishes all four (lo, hi) zero/nonzero pairs.""" - self.assertEqual(ref_scc(0x00000000_00000000), 0) - self.assertEqual(ref_scc(0x00000000_00000001), 1) - self.assertEqual(ref_scc(0x00000000_80000000), 1) - self.assertEqual(ref_scc(0x00000001_00000000), 1) - self.assertEqual(ref_scc(0x80000000_00000000), 1) - self.assertEqual(ref_scc(0x12345678_9ABCDEF0), 1) - self.assertEqual(ref_scc(0xFFFFFFFF_FFFFFFFF), 1) - - def test_zero_result_edge_cases(self): - """Verify inputs that explicitly evaluate to 0 clear SCC.""" - x = 0xA5A5A5A5_5A5A5A5A - self.assertEqual(ref_andn2_b64(x, x), 0) - self.assertEqual(ref_scc(ref_andn2_b64(x, x)), 0) - - self.assertEqual(ref_andn2_b64(0, x), 0) - self.assertEqual(ref_scc(ref_andn2_b64(0, x)), 0) - - self.assertEqual(ref_orn2_b64(0, MASK64), 0) - self.assertEqual(ref_scc(ref_orn2_b64(0, MASK64)), 0) - - self.assertEqual(ref_nand_b64(MASK64, MASK64), 0) - self.assertEqual(ref_scc(ref_nand_b64(MASK64, MASK64)), 0) - - not_x = (~x) & MASK64 - self.assertEqual(ref_nor_b64(x, not_x), 0) - self.assertEqual(ref_scc(ref_nor_b64(x, not_x)), 0) - - self.assertEqual(ref_nor_b64(MASK64, 0), 0) - self.assertEqual(ref_scc(ref_nor_b64(MASK64, 0)), 0) - - self.assertEqual(ref_xnor_b64(x, not_x), 0) - self.assertEqual(ref_scc(ref_xnor_b64(x, not_x)), 0) - - -class ScalarState: - """Models 64-bit RDNA2 scalar execution state: SGPRs, EXEC, VCC, SCC, and NULL.""" - - def __init__(self, num_sgprs: int = 106) -> None: - self.sgprs = [0] * num_sgprs - self.exec: int = MASK64 - self.vcc: int = 0 - self.scc: int = 0 - - def read_sgpr64(self, idx: int) -> int: - lo = self.sgprs[idx] & MASK32 - hi = self.sgprs[idx + 1] & MASK32 - return (hi << 32) | lo - - def write_sgpr64(self, idx: int, val: int) -> None: - self.sgprs[idx] = val & MASK32 - self.sgprs[idx + 1] = (val >> 32) & MASK32 - - def resolve_src64(self, src: int | str) -> int: - if isinstance(src, int): - return src & MASK64 - if src == "exec": - return self.exec & MASK64 - if src == "vcc": - return self.vcc & MASK64 - if src == "null": - return 0 - if src.startswith("s[") and ":" in src: - idx = int(src[2:].split(":")[0]) - return self.read_sgpr64(idx) - raise ValueError(f"Unknown 64-bit source operand: {src}") - - def write_dst64(self, dst: str, val: int) -> None: - val = val & MASK64 - if dst == "exec": - self.exec = val - elif dst == "vcc": - self.vcc = val - elif dst == "null": - pass - elif dst.startswith("s[") and ":" in dst: - idx = int(dst[2:].split(":")[0]) - self.write_sgpr64(idx, val) - else: - raise ValueError(f"Unknown 64-bit destination operand: {dst}") - - def execute(self, op: str, dst: str, src0: int | str, src1: int | str) -> int: - """Executes one 64-bit inverted scalar logic operation and updates SCC.""" - if op not in REF_OPS: - raise ValueError(f"Unsupported op: {op}") - s0_val = self.resolve_src64(src0) - s1_val = self.resolve_src64(src1) - res = REF_OPS[op](s0_val, s1_val) - self.write_dst64(dst, res) - self.scc = ref_scc(res) - return res - - -class SaluInterpreterTests(unittest.TestCase): - """Interpreter simulation tests covering SCC updates, operand aliasing, and wave64 exec masks.""" - - def test_interpreter_all_ops_against_reference(self): - state = ScalarState() - v0 = 0x01234567_89ABCDEF - v1 = 0xFEEDBEEF_CAFED00D - state.write_sgpr64(0, v0) - state.write_sgpr64(2, v1) - - for op, ref_fn in REF_OPS.items(): - with self.subTest(op=op): - res = state.execute(op, "s[4:5]", "s[0:1]", "s[2:3]") - expected = ref_fn(v0, v1) - self.assertEqual(res, expected) - self.assertEqual(state.read_sgpr64(4), expected) - self.assertEqual(state.scc, ref_scc(expected)) - - def test_destination_aliasing_exact(self): - state = ScalarState() - a = 0x11223344_55667788 - b = 0x88776655_44332211 - - state.write_sgpr64(0, a) - state.write_sgpr64(2, b) - state.execute("s_andn2_b64", "s[0:1]", "s[0:1]", "s[2:3]") - self.assertEqual(state.read_sgpr64(0), ref_andn2_b64(a, b)) - - state.write_sgpr64(0, a) - state.write_sgpr64(2, b) - state.execute("s_andn2_b64", "s[2:3]", "s[0:1]", "s[2:3]") - self.assertEqual(state.read_sgpr64(2), ref_andn2_b64(a, b)) - - state.write_sgpr64(0, a) - state.execute("s_andn2_b64", "s[0:1]", "s[0:1]", "s[0:1]") - self.assertEqual(state.read_sgpr64(0), 0) - self.assertEqual(state.scc, 0) - - state.write_sgpr64(0, a) - state.execute("s_xnor_b64", "s[0:1]", "s[0:1]", "s[0:1]") - self.assertEqual(state.read_sgpr64(0), MASK64) - self.assertEqual(state.scc, 1) - - def test_destination_aliasing_overlapping(self): - state = ScalarState() - state.sgprs[0] = 0xAAAAAAAA - state.sgprs[1] = 0xBBBBBBBB - state.sgprs[2] = 0xCCCCCCCC - state.sgprs[3] = 0xDDDDDDDD - - s0_val = state.read_sgpr64(0) - s1_val = state.read_sgpr64(2) - expected = ref_andn2_b64(s0_val, s1_val) - - state.execute("s_andn2_b64", "s[1:2]", "s[0:1]", "s[2:3]") - - self.assertEqual(state.sgprs[0], 0xAAAAAAAA) - self.assertEqual(state.read_sgpr64(1), expected) - self.assertEqual(state.sgprs[3], 0xDDDDDDDD) - - def test_inline_constants_and_literals(self): - state = ScalarState() - val = 0x01234567_89ABCDEF - state.write_sgpr64(0, val) - - state.execute("s_andn2_b64", "s[2:3]", "s[0:1]", 0) - self.assertEqual(state.read_sgpr64(2), val) - self.assertEqual(state.scc, 1) - - state.execute("s_andn2_b64", "s[2:3]", "s[0:1]", MASK64) - self.assertEqual(state.read_sgpr64(2), 0) - self.assertEqual(state.scc, 0) - - state.execute("s_orn2_b64", "s[2:3]", "s[0:1]", 0) - self.assertEqual(state.read_sgpr64(2), MASK64) - self.assertEqual(state.scc, 1) - - def test_scc_updates_matrix(self): - state = ScalarState() - cases = [ - (0, 0, 0), - (1, 0, 1), - (0x80000000, 0, 1), - (0, 1, 1), - (0, 0x80000000, 1), - (0x12345678, 0x9ABCDEF0, 1), - ] - for lo, hi, expected_scc in cases: - with self.subTest(lo=hex(lo), hi=hex(hi)): - val = (hi << 32) | lo - state.write_sgpr64(0, val) - state.execute("s_andn2_b64", "s[2:3]", "s[0:1]", 0) - self.assertEqual(state.read_sgpr64(2), val) - self.assertEqual(state.scc, expected_scc) - - def test_special_register_null(self): - state = ScalarState() - state.write_sgpr64(0, 0x12345678_9ABCDEF0) - state.write_sgpr64(2, 0x12345678_9ABCDEF0) - - state.execute("s_andn2_b64", "null", "s[0:1]", "s[2:3]") - self.assertEqual(state.scc, 0) - self.assertEqual(state.read_sgpr64(0), 0x12345678_9ABCDEF0) - self.assertEqual(state.read_sgpr64(2), 0x12345678_9ABCDEF0) - - state.execute("s_nor_b64", "null", "s[0:1]", 0) - self.assertEqual(state.scc, 1) - - def test_wave64_branch_divergence_exec_pruning(self): - state = ScalarState() - state.exec = MASK64 - state.vcc = 0x55555555_55555555 - - then_mask = state.vcc & state.exec - state.execute("s_andn2_b64", "exec", "exec", "vcc") - else_mask = state.exec - - self.assertEqual(then_mask & else_mask, 0) - self.assertEqual(then_mask | else_mask, MASK64) - self.assertEqual(else_mask, 0xAAAAAAAA_AAAAAAAA) - self.assertEqual(state.scc, 1) - - def test_wave64_all_lanes_disabled_scc(self): - state = ScalarState() - state.exec = MASK64 - state.vcc = MASK64 - - state.execute("s_andn2_b64", "exec", "exec", "vcc") - self.assertEqual(state.exec, 0) - self.assertEqual(state.scc, 0) - - for lane in range(64): - with self.subTest(single_lane=lane): - state.exec = 1 << lane - state.vcc = 0 - state.execute("s_andn2_b64", "exec", "exec", "vcc") - self.assertEqual(state.exec, 1 << lane) - self.assertEqual(state.scc, 1) - - def test_wave64_vcc_mask_manipulation(self): - state = ScalarState() - state.vcc = 0x00000000_FFFFFFFF - state.execute("s_nor_b64", "vcc", "vcc", 0) - self.assertEqual(state.vcc, 0xFFFFFFFF_00000000) - self.assertEqual(state.scc, 1) - - state.vcc = 0x0F0F0F0F_0F0F0F0F - state.execute("s_xnor_b64", "vcc", "vcc", MASK64) - self.assertEqual(state.vcc, 0x0F0F0F0F_0F0F0F0F) - self.assertEqual(state.scc, 1) - - -class SaluSpirvLoweringTests(unittest.TestCase): - """SPIR-V translation and mini-interpreter execution tests for 64-bit inverted logic.""" - - def test_spirv_lowering_all_five_ops(self): - test_pairs = [ - (0x01234567_89ABCDEF, 0x00FF00FF_0F0F0F0F), - (0x00000000_00000000, 0xFFFFFFFF_FFFFFFFF), - (0x55555555_55555555, 0xAAAAAAAA_AAAAAAAA), - (0x00000001_00000000, 0x00000000_00000000), - (0x00000000_00000001, 0x00000000_00000000), - ] - for op, ref_fn in REF_OPS.items(): - for idx, (v0, v1) in enumerate(test_pairs): - with self.subTest(op=op, idx=idx): - s0_lo = v0 & MASK32 - s0_hi = (v0 >> 32) & MASK32 - s1_lo = v1 & MASK32 - s1_hi = (v1 >> 32) & MASK32 - lines = [ - f"s_mov_b32 s0, {s0_lo:#x}", - f"s_mov_b32 s1, {s0_hi:#x}", - f"s_mov_b32 s2, {s1_lo:#x}", - f"s_mov_b32 s3, {s1_hi:#x}", - f"{op} s[4:5], s[0:1], s[2:3]", - "v_mov_b32 v0, s4", - "v_mov_b32 v1, s5", - "s_cselect_b32 s6, 1, 0", - "v_mov_b32 v2, s6", - "v_mov_b32 v3, 0", - "exp mrt0 v0, v1, v2, v3 done vm", - "s_endpgm", - ] - spv = translate_lines(f"ps_{op}_{idx}", lines) - out = mrt0_words(spv) - res64 = (out[1] << 32) | out[0] - expected = ref_fn(v0, v1) - expected_scc = ref_scc(expected) - self.assertEqual(res64, expected) - self.assertEqual(out[2], expected_scc) - - def test_spirv_destination_aliasing(self): - v0 = 0x12345678_9ABCDEF0 - v1 = 0x0F0F0F0F_F0F0F0F0 - lines = [ - f"s_mov_b32 s0, {v0 & MASK32:#x}", - f"s_mov_b32 s1, {(v0 >> 32) & MASK32:#x}", - f"s_mov_b32 s2, {v1 & MASK32:#x}", - f"s_mov_b32 s3, {(v1 >> 32) & MASK32:#x}", - "s_andn2_b64 s[0:1], s[0:1], s[2:3]", - "v_mov_b32 v0, s0", - "v_mov_b32 v1, s1", - "s_cselect_b32 s6, 1, 0", - "v_mov_b32 v2, s6", - "v_mov_b32 v3, 0", - "exp mrt0 v0, v1, v2, v3 done vm", - "s_endpgm", - ] - spv = translate_lines("ps_andn2_alias", lines) - out = mrt0_words(spv) - res64 = (out[1] << 32) | out[0] - expected = ref_andn2_b64(v0, v1) - self.assertEqual(res64, expected) - self.assertEqual(out[2], ref_scc(expected)) - - def test_spirv_null_destination(self): - v0 = 0x12345678_9ABCDEF0 - v1 = 0x12345678_9ABCDEF0 - lines = [ - f"s_mov_b32 s0, {v0 & MASK32:#x}", - f"s_mov_b32 s1, {(v0 >> 32) & MASK32:#x}", - f"s_mov_b32 s2, {v1 & MASK32:#x}", - f"s_mov_b32 s3, {(v1 >> 32) & MASK32:#x}", - "s_andn2_b64 null, s[0:1], s[2:3]", - "s_cselect_b32 s6, 1, 0", - "v_mov_b32 v0, s6", - "v_mov_b32 v1, 0", - "v_mov_b32 v2, 0", - "v_mov_b32 v3, 0", - "exp mrt0 v0, v1, v2, v3 done vm", - "s_endpgm", - ] - spv = translate_lines("ps_null_dst", lines) - out = mrt0_words(spv) - self.assertEqual(out[0], 0) - - def test_spirv_mask_lowering_instruction_stream(self): - lines = [ - "s_andn2_b64 exec, exec, vcc", - "s_orn2_b64 exec, exec, vcc", - "s_nor_b64 exec, exec, vcc", - "s_xnor_b64 exec, exec, vcc", - "exp mrt0 v0, v1, v2, v3 done vm", - "s_endpgm", - ] - spv = translate_lines("ps_mask_ops", lines) - self.assertIn("OpBitwiseAnd", spv) - self.assertIn("OpBitwiseOr", spv) - self.assertIn("OpBitwiseXor", spv) - self.assertIn("OpNot", spv) - - -class DeMorganDualityStressTests(unittest.TestCase): - """Stress tests verifying De Morgan dualities and algebraic identities on 64-bit logic.""" - - def test_de_morgan_dualities_patterns(self): - pattern_pairs = [] - for i in range(64): - pattern_pairs.append((1 << i, ~(1 << i) & MASK64)) - pattern_pairs.append((1 << i, 1 << ((i + 17) % 64))) - pattern_pairs.append((~(1 << i) & MASK64, ~(1 << ((i + 31) % 64)) & MASK64)) - - for a, b in pattern_pairs: - not_a = (~a) & MASK64 - not_b = (~b) & MASK64 - self.assertEqual(ref_nand_b64(a, b), ref_orn2_b64(not_a, b)) - self.assertEqual(ref_nor_b64(a, b), ref_andn2_b64(not_a, b)) - self.assertEqual(ref_andn2_b64(a, b), ref_nor_b64(not_a, b)) - self.assertEqual(ref_orn2_b64(a, b), ref_nand_b64(not_a, b)) - self.assertEqual(ref_xnor_b64(a, b), ref_xnor_b64(not_a, not_b)) - self.assertEqual(ref_xnor_b64(a, b), ((a & b) | ref_nor_b64(a, b)) & MASK64) - - def test_de_morgan_dualities_prng_stress(self): - rng = random.Random(0x7E01DA) - for _ in range(128): - a = rng.getrandbits(64) - b = rng.getrandbits(64) - not_a = (~a) & MASK64 - not_b = (~b) & MASK64 - self.assertEqual(ref_nand_b64(a, b), ref_orn2_b64(not_a, b)) - self.assertEqual(ref_nor_b64(a, b), ref_andn2_b64(not_a, b)) - self.assertEqual(ref_andn2_b64(a, b), ref_nor_b64(not_a, b)) - self.assertEqual(ref_orn2_b64(a, b), ref_nand_b64(not_a, b)) - self.assertEqual(ref_xnor_b64(a, b), ref_xnor_b64(not_a, not_b)) - self.assertEqual(ref_xnor_b64(a, b), ((a & b) | ref_nor_b64(a, b)) & MASK64) - for op, fn in REF_OPS.items(): - r = fn(a, b) - self.assertEqual(ref_scc(r), 1 if r != 0 else 0) - - -class NegativeControlsAndDefensesTests(unittest.TestCase): - """Defensive tests verifying detection of invalid states and distinct operation semantics.""" - - def test_inverted_vs_non_inverted_discrimination(self): - a = 0x12345678_9ABCDEF0 - b = 0x0F0F0F0F_F0F0F0F0 - self.assertNotEqual(ref_andn2_b64(a, b), (a & b) & MASK64) - self.assertNotEqual(ref_orn2_b64(a, b), (a | b) & MASK64) - self.assertNotEqual(ref_nand_b64(a, b), (a & b) & MASK64) - self.assertNotEqual(ref_nor_b64(a, b), (a | b) & MASK64) - self.assertNotEqual(ref_xnor_b64(a, b), (a ^ b) & MASK64) - - def test_non_commutative_asymmetry_defense(self): - a = 0xAAAAAAAA_55555555 - b = 0x12345678_87654321 - self.assertNotEqual(ref_andn2_b64(a, b), ref_andn2_b64(b, a)) - self.assertNotEqual(ref_orn2_b64(a, b), ref_orn2_b64(b, a)) - - def test_interpreter_negative_validations(self): - state = ScalarState() - with self.assertRaises(ValueError): - state.execute("s_unknown_b64", "s[0:1]", "s[2:3]", "s[4:5]") - with self.assertRaises(ValueError): - state.resolve_src64("invalid_src") - with self.assertRaises(ValueError): - state.write_dst64("invalid_dst", 123) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_salu_andn2_b64_hw.py b/tests/semantic/test_salu_andn2_b64_hw.py deleted file mode 100644 index 3d3cea378..000000000 --- a/tests/semantic/test_salu_andn2_b64_hw.py +++ /dev/null @@ -1,577 +0,0 @@ -from __future__ import annotations - -"""Semantic reference tests and translator hardware verification for AMD RDNA2 s_andn2_b64. - -RDNA2 Scalar Arithmetic Logic Unit (SALU) Architecture: - In AMD RDNA2 (GFX10/GFX1030) ISA, the s_andn2_b64 instruction belongs to SOP2 format. - Instruction: - s_andn2_b64 sdst, ssrc0, ssrc1 - - Operands: - sdst = 64-bit destination SGPR pair s[2k:2k+1] (or EXEC) - ssrc0 = 64-bit source operand: SGPR pair, literal 64-bit constant, inline constant, EXEC, or VCC - ssrc1 = 64-bit source operand: SGPR pair, literal 64-bit constant, inline constant, EXEC, or VCC - - Semantics: - sdst = ssrc0 & ~ssrc1 - SCC = 1 if sdst != 0 else 0 - -Standard library only: Python 3.9+ compatible, zero game data, zero external dependencies. -Exercises tools/rdna2spirv.py via support.translate_lines(...) and support.mrt0_words for hardware-accurate translation. -""" - -from dataclasses import dataclass -from enum import Enum, auto -import os -import struct -import sys -import unittest - -HERE = os.path.dirname(os.path.abspath(__file__)) -ROOT = os.path.dirname(os.path.dirname(HERE)) -TOOLS_DIR = os.environ.get("LEONIDA_TOOLS_DIR") or os.path.join(ROOT, "tools") -sys.path.insert(0, TOOLS_DIR) -sys.path.insert(0, HERE) - -import support # noqa: E402 -import rdna2spirv # noqa: E402 - -MASK32: int = 0xFFFFFFFF -MASK64: int = 0xFFFFFFFFFFFFFFFF -ALL_LANES_ACTIVE: int = 0xFFFFFFFFFFFFFFFF -ALL_LANES_INACTIVE: int = 0x0000000000000000 - - -def u64(val: int) -> int: - """Normalize integer to unsigned 64-bit integer range [0, 2^64 - 1].""" - return val & MASK64 - - -def u32(val: int) -> int: - """Normalize integer to unsigned 32-bit integer range [0, 2^32 - 1].""" - return val & MASK32 - - -def ref_andn2_b64(ssrc0: int, ssrc1: int) -> tuple[int, int]: - """Mathematical reference oracle for AMD RDNA2 s_andn2_b64 instruction. - - Args: - ssrc0: 64-bit first source operand (uint64) - ssrc1: 64-bit second source operand (uint64) - - Returns: - tuple (sdst, scc): - - sdst: 64-bit result = ssrc0 & ~ssrc1 - - scc: scalar condition code = 1 if sdst != 0 else 0 - """ - s0 = u64(ssrc0) - s1 = u64(ssrc1) - sdst = u64(s0 & (~s1 & MASK64)) - scc = 1 if sdst != 0 else 0 - return sdst, scc - - -class TestSaluAndn2B64Oracle(unittest.TestCase): - """Test suite for reference mathematical oracle of s_andn2_b64.""" - - def test_oracle_basic(self): - s0 = 0x123456789ABCDEF0 - s1 = 0x00FF00FF0F0F0F0F - sdst, scc = ref_andn2_b64(s0, s1) - expected = s0 & (~s1 & MASK64) - self.assertEqual(sdst, expected) - self.assertEqual(scc, 1) - - def test_oracle_zero_s0(self): - s1 = 0x123456789ABCDEF0 - sdst, scc = ref_andn2_b64(0, s1) - self.assertEqual(sdst, 0) - self.assertEqual(scc, 0) - - def test_oracle_all_ones_s1(self): - s0 = 0x123456789ABCDEF0 - sdst, scc = ref_andn2_b64(s0, ALL_LANES_ACTIVE) - self.assertEqual(sdst, 0) - self.assertEqual(scc, 0) - - def test_oracle_zero_s1(self): - s0 = 0x123456789ABCDEF0 - sdst, scc = ref_andn2_b64(s0, 0) - self.assertEqual(sdst, s0) - self.assertEqual(scc, 1) - - def test_oracle_operand_asymmetry(self): - # s0 & ~s1 != s1 & ~s0 (non-commutative) - s0 = 0x00000000FFFFFFFF - s1 = 0x0000FFFF0000FFFF - res_01, _ = ref_andn2_b64(s0, s1) - res_10, _ = ref_andn2_b64(s1, s0) - self.assertNotEqual(res_01, res_10) - self.assertEqual(res_01, 0x00000000FFFF0000) - self.assertEqual(res_10, 0x0000FFFF00000000) - - -class Opcode(Enum): - S_ANDN2_B64 = auto() - - -class OperandKind(Enum): - SGPR = auto() - EXEC = auto() - VCC = auto() - LITERAL64 = auto() - INLINE_CONST = auto() - - -@dataclass(frozen=True) -class ASTOperand: - kind: OperandKind - index: int = 0 - count: int = 2 - value: int = 0 - - @classmethod - def sgpr(cls, index: int, count: int = 2) -> ASTOperand: - if count != 2: - raise ValueError(f"s_andn2_b64 requires 64-bit register pair (count=2), got {count}") - if index < 0 or index > 104 or (index + count) > 106: - raise ValueError(f"SGPR index out of range: s[{index}:{index + count - 1}]") - if index % 2 != 0: - raise ValueError(f"SGPR pair must be 64-bit aligned (even index), got s{index}") - return cls(kind=OperandKind.SGPR, index=index, count=count) - - @classmethod - def exec_mask(cls) -> ASTOperand: - return cls(kind=OperandKind.EXEC, count=2) - - @classmethod - def vcc(cls) -> ASTOperand: - return cls(kind=OperandKind.VCC, count=2) - - @classmethod - def literal64(cls, val: int) -> ASTOperand: - return cls(kind=OperandKind.LITERAL64, count=2, value=u64(val)) - - @classmethod - def inline_const(cls, val: int) -> ASTOperand: - return cls(kind=OperandKind.INLINE_CONST, count=2, value=u64(val)) - - -@dataclass(frozen=True) -class ASTInstruction: - opcode: Opcode - dst: ASTOperand - src0: ASTOperand - src1: ASTOperand - - def validate(self) -> None: - if self.opcode != Opcode.S_ANDN2_B64: - raise ValueError(f"Unsupported opcode: {self.opcode}") - if self.dst.kind not in (OperandKind.SGPR, OperandKind.EXEC, OperandKind.VCC): - raise TypeError(f"Destination must be SGPR pair, EXEC, or VCC, got {self.dst.kind}") - if self.dst.count != 2: - raise ValueError(f"Destination must be 64-bit (2 registers), got {self.dst.count}") - if self.src0.count != 2 or self.src1.count != 2: - raise ValueError(f"Sources must be 64-bit operands, got {self.src0.count}, {self.src1.count}") - - -class TestSaluAndn2B64AST(unittest.TestCase): - """Test suite for AST opcode definitions and operand validation.""" - - def test_ast_construction_valid_operands(self): - inst = ASTInstruction( - opcode=Opcode.S_ANDN2_B64, - dst=ASTOperand.sgpr(4, 2), - src0=ASTOperand.sgpr(6, 2), - src1=ASTOperand.sgpr(8, 2), - ) - inst.validate() - self.assertEqual(inst.opcode, Opcode.S_ANDN2_B64) - self.assertEqual(inst.dst.kind, OperandKind.SGPR) - self.assertEqual(inst.dst.index, 4) - self.assertEqual(inst.src0.index, 6) - self.assertEqual(inst.src1.index, 8) - - def test_ast_rejects_unaligned_sgpr_pair(self): - with self.assertRaises(ValueError): - ASTOperand.sgpr(5, 2) - - def test_ast_rejects_single_sgpr(self): - with self.assertRaises(ValueError): - ASTOperand.sgpr(4, 1) - - def test_ast_rejects_invalid_dst_kind(self): - inst = ASTInstruction( - opcode=Opcode.S_ANDN2_B64, - dst=ASTOperand.literal64(0x123), - src0=ASTOperand.sgpr(6, 2), - src1=ASTOperand.sgpr(8, 2), - ) - with self.assertRaises(TypeError): - inst.validate() - - -class ScalarRegisterState: - """Simulated state of GCN/RDNA Scalar Registers (SGPRs, EXEC, and SCC).""" - - def __init__(self, exec_mask: int = ALL_LANES_ACTIVE): - self.sgpr = [0] * 106 - self.exec_mask = u64(exec_mask) - self.vcc = 0 - self.scc = 0 - - def read_operand_u64(self, op: ASTOperand) -> int: - if op.kind == OperandKind.SGPR: - lo = self.sgpr[op.index] - hi = self.sgpr[op.index + 1] - return (hi << 32) | lo - elif op.kind == OperandKind.EXEC: - return self.exec_mask - elif op.kind == OperandKind.VCC: - return self.vcc - elif op.kind in (OperandKind.LITERAL64, OperandKind.INLINE_CONST): - return op.value - raise ValueError(f"Unsupported operand kind for read: {op.kind}") - - def write_sgpr_u64(self, index: int, val: int) -> None: - val = u64(val) - self.sgpr[index] = val & MASK32 - self.sgpr[index + 1] = (val >> 32) & MASK32 - - def execute(self, inst: ASTInstruction) -> tuple[int, int]: - inst.validate() - s0 = self.read_operand_u64(inst.src0) - s1 = self.read_operand_u64(inst.src1) - sdst_val, scc = ref_andn2_b64(s0, s1) - - if inst.dst.kind == OperandKind.SGPR: - self.write_sgpr_u64(inst.dst.index, sdst_val) - elif inst.dst.kind == OperandKind.EXEC: - self.exec_mask = sdst_val - elif inst.dst.kind == OperandKind.VCC: - self.vcc = sdst_val - - self.scc = scc - return sdst_val, scc - - -class TestSaluAndn2B64ScalarInterpreter(unittest.TestCase): - """Test suite for deterministic scalar instruction execution.""" - - def test_scalar_interpreter_execution(self): - state = ScalarRegisterState() - state.write_sgpr_u64(0, 0x123456789ABCDEF0) - state.write_sgpr_u64(2, 0x00FF00FF0F0F0F0F) - inst = ASTInstruction( - opcode=Opcode.S_ANDN2_B64, - dst=ASTOperand.sgpr(4, 2), - src0=ASTOperand.sgpr(0, 2), - src1=ASTOperand.sgpr(2, 2), - ) - sdst, scc = state.execute(inst) - expected = 0x123456789ABCDEF0 & (~0x00FF00FF0F0F0F0F & MASK64) - self.assertEqual(sdst, expected) - self.assertEqual(state.sgpr[4], expected & MASK32) - self.assertEqual(state.sgpr[5], (expected >> 32) & MASK32) - self.assertEqual(state.scc, 1) - - -class TestSaluAndn2B64SimdDivergence(unittest.TestCase): - """Test suite for SIMD multi-lane divergence and 64-bit EXEC masking.""" - - def test_wave64_lane_mask_isolation(self): - lanes = lambda lo, hi: sum(1 << l for l in range(lo, hi)) - s0 = lanes(0, 48) # lanes 0..47 - s1 = lanes(16, 64) # lanes 16..63 - # s0 & ~s1 = lanes 0..15 - sdst, scc = ref_andn2_b64(s0, s1) - self.assertEqual(sdst, lanes(0, 16)) - self.assertEqual(scc, 1) - - def test_divergent_mask_checkerboard(self): - even_lanes = 0x5555555555555555 - odd_lanes = 0xAAAAAAAAAAAAAAAA - # even & ~odd = even & even = even - sdst, scc = ref_andn2_b64(even_lanes, odd_lanes) - self.assertEqual(sdst, even_lanes) - self.assertEqual(scc, 1) - - # even & ~even = even & odd = 0 - sdst_zero, scc_zero = ref_andn2_b64(even_lanes, even_lanes) - self.assertEqual(sdst_zero, 0) - self.assertEqual(scc_zero, 0) - - -class TestSaluAndn2B64RegisterAliasing(unittest.TestCase): - """Test suite for register aliasing and in-place operand preservation.""" - - def test_dst_aliases_src0(self): - # s[0:1] = s[0:1] & ~s[2:3] - state = ScalarRegisterState() - s0_val = 0x123456789ABCDEF0 - s1_val = 0x00000000FFFFFFFF - state.write_sgpr_u64(0, s0_val) - state.write_sgpr_u64(2, s1_val) - - inst = ASTInstruction( - opcode=Opcode.S_ANDN2_B64, - dst=ASTOperand.sgpr(0, 2), - src0=ASTOperand.sgpr(0, 2), - src1=ASTOperand.sgpr(2, 2), - ) - sdst, scc = state.execute(inst) - self.assertEqual(sdst, 0x1234567800000000) - self.assertEqual(state.sgpr[0], 0x00000000) - self.assertEqual(state.sgpr[1], 0x12345678) - self.assertEqual(scc, 1) - - def test_dst_aliases_src1(self): - # s[2:3] = s[0:1] & ~s[2:3] - state = ScalarRegisterState() - s0_val = 0x123456789ABCDEF0 - s1_val = 0x00000000FFFFFFFF - state.write_sgpr_u64(0, s0_val) - state.write_sgpr_u64(2, s1_val) - - inst = ASTInstruction( - opcode=Opcode.S_ANDN2_B64, - dst=ASTOperand.sgpr(2, 2), - src0=ASTOperand.sgpr(0, 2), - src1=ASTOperand.sgpr(2, 2), - ) - sdst, scc = state.execute(inst) - self.assertEqual(sdst, 0x1234567800000000) - self.assertEqual(state.sgpr[2], 0x00000000) - self.assertEqual(state.sgpr[3], 0x12345678) - self.assertEqual(scc, 1) - - def test_self_cancellation_aliasing(self): - # s[0:1] = s[0:1] & ~s[0:1] = 0 - state = ScalarRegisterState() - state.write_sgpr_u64(0, 0x123456789ABCDEF0) - inst = ASTInstruction( - opcode=Opcode.S_ANDN2_B64, - dst=ASTOperand.sgpr(0, 2), - src0=ASTOperand.sgpr(0, 2), - src1=ASTOperand.sgpr(0, 2), - ) - sdst, scc = state.execute(inst) - self.assertEqual(sdst, 0) - self.assertEqual(state.sgpr[0], 0) - self.assertEqual(state.sgpr[1], 0) - self.assertEqual(scc, 0) - - -class TestSaluAndn2B64ConditionCodes(unittest.TestCase): - """Test suite for condition codes, status flags, and SCC generation.""" - - def test_scc_set_when_result_nonzero(self): - sdst, scc = ref_andn2_b64(1, 0) - self.assertEqual(sdst, 1) - self.assertEqual(scc, 1) - - def test_scc_cleared_when_result_zero(self): - sdst, scc = ref_andn2_b64(0x1234, 0x1234) - self.assertEqual(sdst, 0) - self.assertEqual(scc, 0) - - def test_scc_cleared_when_src0_is_zero(self): - sdst, scc = ref_andn2_b64(0, 0x5555555555555555) - self.assertEqual(sdst, 0) - self.assertEqual(scc, 0) - - -class TestSaluAndn2B64BitwiseEdgeCases(unittest.TestCase): - """Test suite for 64-bit IEEE-754 bit representations and boundary bitmasks.""" - - def test_ieee754_double_precision_bit_patterns(self): - cases = [ - 0x7FF0000000000000, # +inf - 0xFFF0000000000000, # -inf - 0x7FF8000000000000, # Quiet NaN - 0x7FF0000000000001, # Signaling NaN - 0x0000000000000000, # +0.0 - 0x8000000000000000, # -0.0 - 0x0000000000000001, # Minimum subnormal - 0x000FFFFFFFFFFFFF, # Maximum subnormal - ] - for pattern0 in cases: - for pattern1 in cases: - with self.subTest(p0=hex(pattern0), p1=hex(pattern1)): - sdst, scc = ref_andn2_b64(pattern0, pattern1) - expected = pattern0 & (~pattern1 & MASK64) - self.assertEqual(sdst, expected) - self.assertEqual(scc, int(expected != 0)) - - def test_boundary_alternating_bitmasks(self): - checkerboards = [ - 0x5555555555555555, - 0xAAAAAAAAAAAAAAAA, - 0x3333333333333333, - 0xCCCCCCCCCCCCCCCC, - 0x0F0F0F0F0F0F0F0F, - 0xF0F0F0F0F0F0F0F0, - 0x00FF00FF00FF00FF, - 0xFF00FF00FF00FF00, - ] - for cb0 in checkerboards: - for cb1 in checkerboards: - sdst, scc = ref_andn2_b64(cb0, cb1) - self.assertEqual(sdst, cb0 & (~cb1 & MASK64)) - - -def parse_s_andn2_b64_asm(asm_line: str) -> ASTInstruction: - """Parse a single assembly instruction line for s_andn2_b64.""" - clean = asm_line.strip() - if not clean: - raise ValueError("Empty assembly line") - parts = clean.split(None, 1) - mnemonic = parts[0].lower() - if mnemonic != "s_andn2_b64": - raise ValueError(f"Expected mnemonic s_andn2_b64, got {mnemonic}") - if len(parts) < 2: - raise ValueError("Missing operands") - operands_str = [op.strip() for op in parts[1].split(",")] - if len(operands_str) != 3: - raise ValueError(f"Expected 3 operands (dst, src0, src1), got {len(operands_str)}") - - def parse_op(op_str: str) -> ASTOperand: - op_lower = op_str.lower() - if op_lower == "exec": - return ASTOperand.exec_mask() - elif op_lower == "vcc": - return ASTOperand.vcc() - elif op_lower.startswith("s[") and op_lower.endswith("]"): - idx_pair = op_lower[2:-1].split(":") - if len(idx_pair) != 2: - raise ValueError(f"Invalid SGPR pair syntax: {op_str}") - start, end = int(idx_pair[0]), int(idx_pair[1]) - if end != start + 1 or start % 2 != 0: - raise ValueError(f"SGPR pair must be even-aligned 2-register range: {op_str}") - return ASTOperand.sgpr(start, 2) - elif op_str.startswith("0x") or op_str.startswith("-") or op_str.isdigit(): - val = int(op_str, 0) - return ASTOperand.literal64(val) - else: - raise ValueError(f"Invalid operand: {op_str}") - - dst = parse_op(operands_str[0]) - src0 = parse_op(operands_str[1]) - src1 = parse_op(operands_str[2]) - - inst = ASTInstruction(Opcode.S_ANDN2_B64, dst, src0, src1) - inst.validate() - return inst - - -# Mutant functions for mutation testing -def mutant_and(s0: int, s1: int) -> tuple[int, int]: - """Mutant 1: uses regular AND (omits ~ negation).""" - res = (s0 & s1) & MASK64 - return res, 1 if res != 0 else 0 - - -def mutant_orn2(s0: int, s1: int) -> tuple[int, int]: - """Mutant 2: uses OR instead of AND.""" - res = (s0 | (~s1 & MASK64)) & MASK64 - return res, 1 if res != 0 else 0 - - -def mutant_swapped_operands(s0: int, s1: int) -> tuple[int, int]: - """Mutant 3: swaps operand order (s1 & ~s0).""" - res = (s1 & (~s0 & MASK64)) & MASK64 - return res, 1 if res != 0 else 0 - - -def mutant_invert_scc(s0: int, s1: int) -> tuple[int, int]: - """Mutant 4: inverts SCC logic.""" - res = (s0 & (~s1 & MASK64)) & MASK64 - return res, 1 if res == 0 else 0 - - -class TestSaluAndn2B64NegativeControlsAndMutations(unittest.TestCase): - """Test suite for syntax rejection, negative controls, mutation detection, and translator execution.""" - - def test_syntax_rejection_malformed_syntax(self): - with self.assertRaises(ValueError): - parse_s_andn2_b64_asm("") - - with self.assertRaises(ValueError): - parse_s_andn2_b64_asm("s_orn2_b64 s[0:1], s[2:3], s[4:5]") - - with self.assertRaises(ValueError): - parse_s_andn2_b64_asm("s_andn2_b64 s[0:1], s[2:3]") - - with self.assertRaises(ValueError): - parse_s_andn2_b64_asm("s_andn2_b64 s[1:2], s[2:3], s[4:5]") - - def test_mutation_detection_and(self): - s0, s1 = 0x0F, 0x0F - correct = ref_andn2_b64(s0, s1) - mutated = mutant_and(s0, s1) - self.assertNotEqual(correct, mutated) - - def test_mutation_detection_orn2(self): - s0, s1 = 0x00, 0x00 - correct = ref_andn2_b64(s0, s1) - mutated = mutant_orn2(s0, s1) - self.assertNotEqual(correct, mutated) - - def test_mutation_detection_swapped_operands(self): - s0, s1 = 0x0F, 0x00 - correct = ref_andn2_b64(s0, s1) - mutated = mutant_swapped_operands(s0, s1) - self.assertNotEqual(correct, mutated) - - def test_mutation_detection_invert_scc(self): - s0, s1 = 0x00, 0x00 - correct = ref_andn2_b64(s0, s1) - mutated = mutant_invert_scc(s0, s1) - self.assertNotEqual(correct, mutated) - - def test_andn2_spirv_emission(self): - """Verify that support.translate_lines emits expected SPIR-V logic for s_andn2_b64.""" - lines = [ - "s_mov_b32 s0, 0x12345678", - "s_mov_b32 s1, 0x9abcdef0", - "s_mov_b32 s2, 0x00ff00ff", - "s_mov_b32 s3, 0x0f0f0f0f", - "s_andn2_b64 s[4:5], s[0:1], s[2:3]", - "s_endpgm", - ] - spv = support.translate_lines("ps_test_andn2_b64_emit", lines) - self.assertIn("OpBitwiseAnd", spv) - self.assertIn("OpNot", spv) - - def test_andn2_hardware_execution(self): - """Verify hardware-accurate execution of s_andn2_b64 through support.mrt0_words.""" - s0_lo, s0_hi = 0x12345678, 0x9ABCDEF0 - s1_lo, s1_hi = 0x00FF00FF, 0x0F0F0F0F - expected_lo = (s0_lo & (~s1_lo & MASK32)) & MASK32 - expected_hi = (s0_hi & (~s1_hi & MASK32)) & MASK32 - - lines = [ - f"s_mov_b32 s0, {s0_lo:#x}", - f"s_mov_b32 s1, {s0_hi:#x}", - f"s_mov_b32 s2, {s1_lo:#x}", - f"s_mov_b32 s3, {s1_hi:#x}", - "s_andn2_b64 s[4:5], s[0:1], s[2:3]", - "s_cselect_b32 s6, 1, 0", - "v_mov_b32_e32 v0, s4", - "v_mov_b32_e32 v1, s5", - "v_mov_b32_e32 v2, s6", - "v_mov_b32_e32 v3, 0", - "exp mrt0, v0, v1, v2, v3 done", - "s_endpgm", - ] - spv = support.translate_lines("ps_andn2_b64_hw", lines) - words = support.mrt0_words(spv) - - self.assertEqual(words[0], expected_lo) - self.assertEqual(words[1], expected_hi) - self.assertEqual(words[2], 1) - self.assertEqual(words[3], 0) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_salu_andn2_saveexec_b64.py b/tests/semantic/test_salu_andn2_saveexec_b64.py deleted file mode 100644 index df6c62d38..000000000 --- a/tests/semantic/test_salu_andn2_saveexec_b64.py +++ /dev/null @@ -1,34 +0,0 @@ -"""s_andn2_saveexec_b64 through the translator, on every lane of a wave64. - -RDNA2 ISA, SOP1: - s_andn2_saveexec_b64: D = EXEC; EXEC = S0 & ~EXEC; SCC = (EXEC != 0). - -Each case translates a hand-written compute program with tools/rdna2spirv.py and runs 64 lanes in -tests/semantic/spirv_mini_interp.py (harness: saveexec_run.py), with S0 from VCC, an SGPR pair written by v_cmp, an -SGPR pair loaded with literals, and EXEC itself, against the ISA formula in plain Python. Until this file, the test of -this name ran a self-built interpreter and never called the translator. -""" -import os -import sys -import unittest - -sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) -import saveexec_run # noqa: E402 (support puts tools/ on sys.path) - - -class Saveexec(unittest.TestCase): - def test_andn2_by_hand(self): - # S0 = lanes 0..31, EXEC = lanes 16..47: EXEC = S0 & ~EXEC written out by hand. - lanes = lambda lo, hi: sum(1 << l for l in range(lo, hi)) - s0, e = lanes(0, 32), lanes(16, 48) - want = {"and": lanes(16, 32), "andn2": lanes(0, 16), "or": lanes(0, 48), "orn2": lanes(0, 32) | lanes(48, 64) | lanes(16, 32), - "xor": lanes(0, 16) | lanes(32, 48), "nand": lanes(0, 16) | lanes(32, 64), - "nor": lanes(48, 64), "xnor": lanes(16, 32) | lanes(48, 64)}["andn2"] - self.assertEqual(saveexec_run.model("andn2", s0, e), (want, e, 1)) - - def test_andn2_every_lane(self): - saveexec_run.check(self, "andn2") - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_salu_b32_lane_masks.py b/tests/semantic/test_salu_b32_lane_masks.py deleted file mode 100644 index 8130ab22f..000000000 --- a/tests/semantic/test_salu_b32_lane_masks.py +++ /dev/null @@ -1,410 +0,0 @@ -"""Semantic tests for 32-bit bitwise SALU ops on lane masks (wave32 and wave64 half-masks). - -Covers s_not_b32 and s_and/or/xor/andn2/orn2/nand/nor/xnor/cselect_b32 when operating on lane masks: - - Wave32 s_not_b32 on a lane mask (vcc_lo / exec_lo / mask SGPR): inverted per-lane bits AND uniform - wave-wide SCC (OpGroupNonUniformAny), not per-lane SCC. - - Wave32 s_not_b32 / s_and_b32 / s_or_b32 / s_xor_b32 with immediate or scalar-SGPR operands writing - exec_lo or vcc_lo: skips raw scalar constant folding and computes per-lane mask bits + wave-wide SCC. - - Wave64 32-bit bitwise ops on exec_lo / exec_hi / vcc_lo / vcc_hi / MASK_LO / MASK_HI: - * Writing exec_lo preserves exec_hi (lanes 32..63); writing exec_hi preserves exec_lo (lanes 0..31). - * Writing vcc_lo preserves vcc_hi; writing vcc_hi preserves vcc_lo. - * SCC votes over the written/read 32-lane half only (scc_any_half), unaffected by the other half. - * Opposite-half source (e.g. exec_lo <- vcc_hi, exec_hi <- vcc_lo) collects the source half cleanly. - * s_cselect_b32 into exec_lo / exec_hi preserves the untouched half. - - Preserves scalar constant folding for plain SGPR destinations and spirv-val Vulkan 1.2 validation in - both native and --wave64-emulate modes. - -Standard library only; no GPU, no game files. -""" -from __future__ import annotations - -import gc -import os -import shutil -import struct -import subprocess -import sys -import tempfile -import unittest -import warnings - -HERE = os.path.dirname(os.path.abspath(__file__)) -ROOT = os.path.dirname(os.path.dirname(HERE)) -TOOLS_DIR = os.environ.get("LEONIDA_TOOLS_DIR") or os.path.join(ROOT, "tools") - -sys.dont_write_bytecode = True -for _p in (HERE, TOOLS_DIR): - if _p not in sys.path: - sys.path.insert(0, _p) - -import rdna2spirv # noqa: E402 -import spirv_mini_interp as si # noqa: E402 - -M32 = 0xFFFFFFFF -STUB_DXBC = b"DXBC" + bytes(24) + struct.pack(" str: - with tempfile.TemporaryDirectory() as tmp: - os.mkdir(os.path.join(tmp, "disasm")) - os.mkdir(os.path.join(tmp, "fssm")) - src = os.path.join(tmp, "disasm", f"cs_{name}.s") - with open(src, "w", encoding="utf-8", newline="\n") as f: - f.write(f"; cs_{name}\n") - for ln in lines: - f.write(f"\t{ln}\n") - with open(os.path.join(tmp, f"cs_{name}.dxbc"), "wb") as f: - f.write(STUB_DXBC) - with open(os.path.join(tmp, "fssm", f"cs_{name}.fssm"), "wb") as f: - f.write(bytes(0x138) + struct.pack("<4I", 0x8090, threads, 1, 1)) - old_emulate = rdna2spirv.WAVE64_EMULATE - rdna2spirv.WAVE64_EMULATE = emulate - try: - with warnings.catch_warnings(): - warnings.simplefilter("ignore", ResourceWarning) - spv = rdna2spirv.translate(src) - gc.collect() - finally: - rdna2spirv.WAVE64_EMULATE = old_emulate - return spv - - -def run_cs(spv: str, threads: int, s4: int = 0, s5: int = 0, s6: int = 0, s7: int = 0) -> dict[int, int]: - pc = VSHARP + [s4 & M32, s5 & M32, s6 & M32, s7 & M32] + [0] * 24 - return si.run_workgroup( - spv, threads, threads, - inputs_for=lambda i: {"%wg_id": (0, 0, 0), "%local_id": (i, 0, 0), "%sg_lane": i}, - push_constants=pc, memory={}, - ) - - -def bits_list(mask: int, width: int) -> list[int]: - return [1 if (mask >> i) & 1 else 0 for i in range(width)] - - -class Wave32B32LaneMaskTests(unittest.TestCase): - def test_s_not_b32_on_vcc_into_sgpr_and_scc(self): - asm = W32_BUILD_VCC + [ - "s_not_b32 s10, vcc_lo", - "s_cselect_b32 s11, 1, 0", - "v_cndmask_b32_e64 v4, 0, 1, s10", - "v_mov_b32_e32 v5, s11", - "v_lshlrev_b32_e32 v6, 2, v0", - "buffer_store_dword v4, v6, s[0:3], 0 offen", - "buffer_store_dword v5, v6, s[0:3], 0 offen offset:128", - "s_endpgm", - ] - spv = translate_cs("w32_not_sgpr", asm, 32) - for mask in (0x00000001, 0x00000000, 0xFFFFFFFF, 0xA5A500FF, 0x80000000): - with self.subTest(mask=hex(mask)): - mem = run_cs(spv, 32, s4=mask) - want_mask = (~mask) & M32 - want_scc = 1 if want_mask != 0 else 0 - got_bits = [mem[4 * i] for i in range(32)] - got_scc = [mem[128 + 4 * i] for i in range(32)] - self.assertEqual(got_bits, bits_list(want_mask, 32)) - self.assertEqual(got_scc, [want_scc] * 32) - - def test_s_not_b32_exec_lo_imm_and_sgpr(self): - for src, c in (("1", 1), ("0x0f0f00ff", 0x0F0F00FF), ("-1", M32), ("0", 0), ("s4", 0x55550001)): - with self.subTest(src=src, c=hex(c)): - asm = [ - "v_mov_b32_e32 v4, 10", - f"s_not_b32 exec_lo, {src}", - "s_cselect_b32 s11, 1, 0", - "v_mov_b32_e32 v4, 20", - "s_mov_b32 exec_lo, -1", - "v_mov_b32_e32 v5, s11", - "v_lshlrev_b32_e32 v6, 2, v0", - "buffer_store_dword v4, v6, s[0:3], 0 offen", - "buffer_store_dword v5, v6, s[0:3], 0 offen offset:128", - "s_endpgm", - ] - spv = translate_cs("w32_not_exec", asm, 32) - mem = run_cs(spv, 32, s4=c) - want_mask = (~c) & M32 - want_scc = 1 if want_mask != 0 else 0 - got_v4 = [mem[4 * i] for i in range(32)] - got_scc = [mem[128 + 4 * i] for i in range(32)] - self.assertEqual(got_v4, [20 if (want_mask >> i) & 1 else 10 for i in range(32)]) - self.assertEqual(got_scc, [want_scc] * 32) - - def test_s_not_and_or_xor_imm_into_vcc_lo(self): - cases = [ - ("s_not_b32 vcc_lo, 1", (~1) & M32), - ("s_not_b32 vcc_lo, -1", 0), - ("s_and_b32 vcc_lo, 0x0f, 0x03", 0x03), - ("s_or_b32 vcc_lo, 0x05, 0x10", 0x15), - ("s_xor_b32 vcc_lo, 0x0f, 0x03", 0x0C), - ("s_xor_b32 vcc_lo, 0x0f, 0x0f", 0), - ] - for insn, want_mask in cases: - with self.subTest(insn=insn): - asm = [ - insn, - "s_cselect_b32 s11, 1, 0", - "s_bcnt1_i32_b32 s12, vcc_lo", - "v_cndmask_b32_e64 v4, 0, 1, vcc_lo", - "v_mov_b32_e32 v5, s11", - "v_mov_b32_e32 v7, s12", - "v_lshlrev_b32_e32 v6, 2, v0", - "buffer_store_dword v4, v6, s[0:3], 0 offen", - "buffer_store_dword v5, v6, s[0:3], 0 offen offset:128", - "buffer_store_dword v7, v6, s[0:3], 0 offen offset:256", - "s_endpgm", - ] - spv = translate_cs("w32_imm_vcc", asm, 32) - mem = run_cs(spv, 32) - want_scc = 1 if want_mask != 0 else 0 - want_cnt = bin(want_mask).count("1") - self.assertEqual([mem[4 * i] for i in range(32)], bits_list(want_mask, 32)) - self.assertEqual([mem[128 + 4 * i] for i in range(32)], [want_scc] * 32) - self.assertEqual([mem[256 + 4 * i] for i in range(32)], [want_cnt] * 32) - - -class Wave64HalfMaskBitwiseTests(unittest.TestCase): - def test_bitreplicate_writes_exec_and_keeps_scc(self): - asm = [ - "v_mov_b32 v4, 0", - "s_cmp_eq_u32 0, 0", - "s_bitreplicate_b64_b32 exec, s4", - "v_mov_b32 v4, 1", - "s_cselect_b32 s5, 1, 0", - "s_mov_b64 exec, -1", - "v_mov_b32 v5, s5", - "v_lshlrev_b32 v6, 2, v0", - "buffer_store_dword v4, v6, s[0:3], 0 offen", - "buffer_store_dword v5, v6, s[0:3], 0 offen offset:256", - "s_endpgm", - ] - spv = translate_cs("w64_bitreplicate_exec", asm, 64) - for word in (0, 0x80000001, 0x0f0f0f0f, M32): - with self.subTest(word=hex(word)): - mem = run_cs(spv, 64, s4=word) - expected = [word >> (lane // 2) & 1 for lane in range(64)] - self.assertEqual([mem[4 * lane] for lane in range(64)], expected) - self.assertEqual([mem[256 + 4 * lane] for lane in range(64)], [1] * 64) - - def test_exec_lo_and_exec_hi_preserve_other_half_and_vote_own_half_scc(self): - # Test s_not_b32 and all 8 binary ops writing exec_lo or exec_hi. - ops = ["s_not_b32"] + list(BIN_REFS.keys()) - # Pairs (lo_vcc, hi_vcc): include cases where lo==0 & hi!=0, lo!=0 & hi==0, single-bit, all-ones. - pairs = [ - (0x00000001, 0x00000000), - (0x00000000, 0x80000000), - (0xFFFFFFFF, 0x00000000), - (0x00000000, 0xFFFFFFFF), - (0x0F0F00FF, 0x55AA33CC), - ] - for op in ops: - for half in ("lo", "hi"): - reg_e = f"exec_{half}" - reg_v = f"vcc_{half}" - # Start with EXEC = 0x55555555_AAAAAAAA (alternating) so non-trivial ops are distinguished. - init_exec_lo, init_exec_hi = 0x55555555, 0xAAAAAAAA - insn = f"{op} {reg_e}, {reg_v}" if op == "s_not_b32" else f"{op} {reg_e}, {reg_e}, {reg_v}" - asm = W64_BUILD_VCC + [ - "s_mov_b64 s[14:15], exec", - f"s_mov_b32 exec_lo, {init_exec_lo:#x}", - f"s_mov_b32 exec_hi, {init_exec_hi:#x}", - "v_mov_b32_e32 v4, 10", - "s_mov_b64 exec, s[14:15]", - "v_mov_b32_e32 v4, 10", - f"s_mov_b32 exec_lo, {init_exec_lo:#x}", - f"s_mov_b32 exec_hi, {init_exec_hi:#x}", - insn, - "s_cselect_b32 s11, 1, 0", - "v_mov_b32_e32 v4, 20", - "s_mov_b64 exec, s[14:15]", - "v_mov_b32_e32 v5, s11", - "v_lshlrev_b32_e32 v6, 2, v0", - "buffer_store_dword v4, v6, s[0:3], 0 offen", - "buffer_store_dword v5, v6, s[0:3], 0 offen offset:256", - "s_endpgm", - ] - spv = translate_cs(f"w64_{op}_{half}", asm, 64) - for lo, hi in pairs: - with self.subTest(op=op, half=half, lo=hex(lo), hi=hex(hi)): - mem = run_cs(spv, 64, s4=lo, s5=hi) - if half == "lo": - new_h = ((~lo) & M32) if op == "s_not_b32" else BIN_REFS[op](init_exec_lo, lo) - want_exec = new_h | (init_exec_hi << 32) - else: - new_h = ((~hi) & M32) if op == "s_not_b32" else BIN_REFS[op](init_exec_hi, hi) - want_exec = init_exec_lo | (new_h << 32) - want_scc = 1 if new_h != 0 else 0 - got_v4 = [mem[4 * i] for i in range(64)] - got_scc = [mem[256 + 4 * i] for i in range(64)] - self.assertEqual(got_v4, [20 if (want_exec >> i) & 1 else 10 for i in range(64)]) - self.assertEqual(got_scc, [want_scc] * 64) - - def test_wave64_sgpr_half_mask_scc(self): - # Writing an SGPR from vcc_lo / vcc_hi (and MASK_LO s12 / MASK_HI s13) votes only over that half. - asm = W64_BUILD_VCC + [ - "s_and_b32 s10, exec_lo, vcc_lo", - "s_cselect_b32 s20, 1, 0", - "s_and_b32 s11, exec_hi, vcc_hi", - "s_cselect_b32 s21, 1, 0", - "s_not_b32 s16, s12", - "s_cselect_b32 s22, 1, 0", - "s_not_b32 s17, s13", - "s_cselect_b32 s23, 1, 0", - "v_lshlrev_b32_e32 v6, 2, v0", - "v_mov_b32_e32 v4, s20", - "buffer_store_dword v4, v6, s[0:3], 0 offen", - "v_mov_b32_e32 v4, s21", - "buffer_store_dword v4, v6, s[0:3], 0 offen offset:256", - "v_mov_b32_e32 v4, s22", - "buffer_store_dword v4, v6, s[0:3], 0 offen offset:512", - "v_mov_b32_e32 v4, s23", - "buffer_store_dword v4, v6, s[0:3], 0 offen offset:768", - "s_endpgm", - ] - spv = translate_cs("w64_sgpr_half_scc", asm, 64) - for lo, hi in ((0x00000001, 0x00000000), (0x00000000, 0x00000001), - (0xFFFFFFFF, 0x00000000), (0x00000000, 0xFFFFFFFF)): - with self.subTest(lo=hex(lo), hi=hex(hi)): - mem = run_cs(spv, 64, s4=lo, s5=hi) - self.assertEqual([mem[4 * i] for i in range(64)], [int(lo != 0)] * 64) - self.assertEqual([mem[256 + 4 * i] for i in range(64)], [int(hi != 0)] * 64) - self.assertEqual([mem[512 + 4 * i] for i in range(64)], [int(((~lo) & M32) != 0)] * 64) - self.assertEqual([mem[768 + 4 * i] for i in range(64)], [int(((~hi) & M32) != 0)] * 64) - - def test_wave64_vcc_half_const_and_cross_half_exec(self): - # 1) s_and_b32 vcc_lo, vcc_lo, 0x0f0f00ff preserves vcc_hi and sets SCC from lo only. - # 2) s_and_b32 exec_lo, exec_lo, vcc_hi applies vcc_hi bits to lanes 0..31 and preserves exec_hi. - # 3) s_cselect_b32 exec_hi, vcc_hi, 0x0000000f preserves exec_lo. - asm = W64_BUILD_VCC + [ - "s_and_b32 vcc_lo, vcc_lo, 0x0f0f00ff", - "s_cselect_b32 s20, 1, 0", - "v_cndmask_b32_e64 v4, 0, 1, vcc", - "s_mov_b64 s[14:15], exec", - "v_mov_b32_e32 v7, 10", - "s_and_b32 exec_lo, exec_lo, vcc_hi", - "s_cselect_b32 s21, 1, 0", - "v_mov_b32_e32 v7, 20", - "s_mov_b64 exec, s[14:15]", - "v_mov_b32_e32 v8, 30", - "s_cmp_eq_u32 s6, 1", - "s_cselect_b32 exec_hi, vcc_hi, 0x0000000f", - "v_mov_b32_e32 v8, 40", - "s_mov_b64 exec, s[14:15]", - "v_lshlrev_b32_e32 v6, 2, v0", - "buffer_store_dword v4, v6, s[0:3], 0 offen", - "v_mov_b32_e32 v5, s20", - "buffer_store_dword v5, v6, s[0:3], 0 offen offset:256", - "buffer_store_dword v7, v6, s[0:3], 0 offen offset:512", - "v_mov_b32_e32 v5, s21", - "buffer_store_dword v5, v6, s[0:3], 0 offen offset:768", - "buffer_store_dword v8, v6, s[0:3], 0 offen offset:1024", - "s_endpgm", - ] - spv = translate_cs("w64_vcc_const_cross", asm, 64) - for lo, hi, s6 in ((0xF0F0FF00, 0x00010005, 0), (0xFFFFFFFF, 0x80000001, 1), (0x00000001, 0x00000000, 1)): - with self.subTest(lo=hex(lo), hi=hex(hi), s6=s6): - mem = run_cs(spv, 64, s4=lo, s5=hi, s6=s6) - vcc_lo = lo & 0x0F0F00FF - vcc64 = vcc_lo | (hi << 32) - self.assertEqual([mem[4 * i] for i in range(64)], bits_list(vcc64, 64)) - self.assertEqual([mem[256 + 4 * i] for i in range(64)], [int(vcc_lo != 0)] * 64) - exec_cross = hi | (M32 << 32) - self.assertEqual([mem[512 + 4 * i] for i in range(64)], - [20 if (exec_cross >> i) & 1 else 10 for i in range(64)]) - self.assertEqual([mem[768 + 4 * i] for i in range(64)], [int(hi != 0)] * 64) - csel_hi = hi if s6 == 1 else 0x0000000F - exec_csel = M32 | (csel_hi << 32) - self.assertEqual([mem[1024 + 4 * i] for i in range(64)], - [40 if (exec_csel >> i) & 1 else 30 for i in range(64)]) - - def test_wave64_vcc_half_after_whole_vcc_const_write(self): - # Regression for @LloydNicholson's RX 9060 XT finding: s_mov_b64 vcc, -1 (or 0) must keep vcc - # in the lane-mask state so a subsequent 32-bit half op on vcc_lo / vcc_hi extracts per-lane bits - # and preserves the other half. - cases = [ - (["s_mov_b64 vcc, -1", "s_and_b32 vcc_lo, vcc_lo, 0xf0"], 0x000000F0 | (M32 << 32), 1), - (["s_mov_b64 vcc, 0", "s_or_b32 vcc_hi, vcc_hi, 0x0f"], 0x0000000F << 32, 1), - (["s_mov_b64 vcc, -1", "s_not_b32 vcc_hi, 0xfffffff0"], M32 | (0x0000000F << 32), 1), - (["s_mov_b64 vcc, -1", "s_and_b32 vcc_lo, vcc_lo, 0"], M32 << 32, 0), - ] - for idx, (setup, want_vcc, want_scc) in enumerate(cases): - with self.subTest(setup=setup): - asm = setup + [ - "s_cselect_b32 s20, 1, 0", - "v_cndmask_b32_e64 v4, 0, 1, vcc", - "v_mov_b32_e32 v5, s20", - "v_lshlrev_b32_e32 v6, 2, v0", - "buffer_store_dword v4, v6, s[0:3], 0 offen", - "buffer_store_dword v5, v6, s[0:3], 0 offen offset:256", - "s_endpgm", - ] - spv = translate_cs(f"w64_vcc_const_init_{idx}", asm, 64) - mem = run_cs(spv, 64) - self.assertEqual([mem[4 * i] for i in range(64)], bits_list(want_vcc, 64)) - self.assertEqual([mem[256 + 4 * i] for i in range(64)], [want_scc] * 64) - - def test_spirv_val_native_and_wave64_emulate(self): - spirv_as = shutil.which("spirv-as") - spirv_val = shutil.which("spirv-val") - if not (spirv_as and spirv_val): - self.skipTest("spirv-as / spirv-val not on PATH") - asm_w64 = W64_BUILD_VCC + [ - "s_mov_b64 s[14:15], exec", - "s_not_b32 exec_lo, vcc_lo", - "s_and_b32 exec_hi, exec_hi, 0x0f0f00ff", - "s_or_b32 exec_lo, exec_lo, vcc_hi", - "s_xor_b32 vcc_hi, vcc_hi, 0x55555555", - "s_cselect_b32 exec_hi, vcc_hi, 0x000000ff", - "s_mov_b64 exec, s[14:15]", - "s_endpgm", - ] - for emulate in (False, True): - spv = translate_cs(f"w64_val_{int(emulate)}", asm_w64, 64, emulate=emulate) - with tempfile.TemporaryDirectory() as tmp: - spvasm = os.path.join(tmp, "m.spvasm") - spvbin = os.path.join(tmp, "m.spv") - with open(spvasm, "w", encoding="utf-8", newline="\n") as f: - f.write(spv) - r1 = subprocess.run([spirv_as, "--target-env", "vulkan1.2", spvasm, "-o", spvbin], - capture_output=True, text=True) - self.assertEqual(r1.returncode, 0, r1.stderr) - r2 = subprocess.run([spirv_val, "--target-env", "vulkan1.2", spvbin], - capture_output=True, text=True) - self.assertEqual(r2.returncode, 0, r2.stderr) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_salu_bfe_64.py b/tests/semantic/test_salu_bfe_64.py deleted file mode 100644 index 2d515df5d..000000000 --- a/tests/semantic/test_salu_bfe_64.py +++ /dev/null @@ -1,940 +0,0 @@ -"""Semantic interpreter tests for RDNA2 s_bfe_u64 and s_bfe_i64. - -RDNA2 64-bit scalar bitfield extract instructions: - - s_bfe_u64 D, S0, S1: Unsigned 64-bit bitfield extract across SGPR pairs. - - s_bfe_i64 D, S0, S1: Signed 64-bit bitfield extract with sign extension. - -Operand layout and semantics: - - S0 is the 64-bit source operand (SGPR pair s[k:k+1], immediate, or constant). - - S1 is the packed 32-bit control word: - offset = S1[5:0] (bits [5:0], 0..63). - width = S1[22:16] (bits [22:16], 0..127). - Upper bits [15:6] and [31:23] of S1 are ignored. - - Width limit / clamping: - If width == 0: result is 0, SCC = 0. - When offset + width > 64, the extracted field stops at bit 63: - effective_width = min(width, 64 - offset). - - s_bfe_u64 zero-extends the extracted field into the 64-bit destination pair D[63:0]. - - s_bfe_i64 sign-extends the extracted field from bit (effective_width - 1) - across the entire 64-bit destination pair. - - Condition code (SCC): - SCC = 1 if D != 0 else 0 (both s_bfe_u64 and s_bfe_i64). - SCC reflects the logical OR of both destination dwords (D.lo != 0 or D.hi != 0). -""" -from __future__ import annotations - -import os -import random -import struct -import sys -import tempfile -import unittest -import warnings - -HERE = os.path.dirname(os.path.abspath(__file__)) -ROOT = os.path.dirname(os.path.dirname(HERE)) -TOOLS_DIR = os.environ.get("LEONIDA_TOOLS_DIR") or os.path.join(ROOT, "tools") - -sys.dont_write_bytecode = True -if ROOT not in sys.path: - sys.path.insert(0, ROOT) -if TOOLS_DIR not in sys.path: - sys.path.insert(0, TOOLS_DIR) -if HERE not in sys.path: - sys.path.insert(0, HERE) - -import rdna2spirv # noqa: E402 -import spirv_mini_interp as si # noqa: E402 - -MASK32 = 0xFFFFFFFF -MASK64 = (1 << 64) - 1 -M64 = MASK64 -SIGN_BIT_64 = 1 << 63 -STUB_DXBC = b"DXBC" + bytes(24) + struct.pack(" int: - """Pack 64-bit bitfield offset [5:0] and width [22:16] into an RDNA scalar control word.""" - return ((width & 0x7F) << 16) | (offset & 0x3F) - - -def unpack_bfe64_ctl(ctl: int) -> tuple[int, int]: - """Unpack offset [5:0] and width [22:16] from an RDNA 64-bit scalar control word.""" - offset = ctl & 0x3F - width = (ctl >> 16) & 0x7F - return offset, width - - -def ref_s_bfe_u64(src: int, ctl: int) -> tuple[int, int]: - """Pure-Python reference oracle for RDNA2 s_bfe_u64. - - Returns: - (result, scc): 64-bit unsigned extracted field and SCC flag (1 if res != 0 else 0). - """ - src &= MASK64 - offset, width = unpack_bfe64_ctl(ctl) - if width == 0 or offset >= 64: - return 0, 0 - eff_width = min(width, 64 - offset) - mask = (1 << eff_width) - 1 - res = (src >> offset) & mask - scc = 1 if res != 0 else 0 - return res & MASK64, scc - - -def ref_s_bfe_i64(src: int, ctl: int) -> tuple[int, int]: - """Pure-Python reference oracle for RDNA2 s_bfe_i64. - - Returns: - (result, scc): 64-bit sign-extended extracted field and SCC flag (1 if res != 0 else 0). - """ - src &= MASK64 - offset, width = unpack_bfe64_ctl(ctl) - if width == 0 or offset >= 64: - return 0, 0 - eff_width = min(width, 64 - offset) - mask = (1 << eff_width) - 1 - val = (src >> offset) & mask - sign_bit = 1 << (eff_width - 1) - if val & sign_bit: - val -= (1 << eff_width) - res = val & MASK64 - scc = 1 if res != 0 else 0 - return res, scc - - -# Legacy aliases matching existing suite -def ctl(off: int, width: int) -> int: - return pack_bfe64_ctl(off, width) - - -def ref(op: str, x: int, ctl_val: int) -> int: - if op == "s_bfe_u64": - return ref_s_bfe_u64(x, ctl_val)[0] - if op == "s_bfe_i64": - return ref_s_bfe_i64(x, ctl_val)[0] - raise ValueError(f"Unknown 64-bit bfe opcode: {op}") - - -class ScalarAlu64Interpreter: - """Deterministic semantic interpreter for RDNA2 64-bit scalar ALU bitfield instructions. - - Models SGPR register file (106 dwords) and 1-bit Scalar Condition Code (SCC). - """ - - def __init__(self, num_sgprs: int = 106) -> None: - self.num_sgprs = num_sgprs - self.sgpr = [0] * num_sgprs - self.scc = 0 - - def reset(self) -> None: - self.sgpr = [0] * self.num_sgprs - self.scc = 0 - - def get_sgpr(self, r: int) -> int: - return self.sgpr[r] & MASK32 - - def set_sgpr(self, r: int, val: int) -> None: - self.sgpr[r] = val & MASK32 - - def get_pair(self, r: int) -> int: - lo = self.get_sgpr(r) - hi = self.get_sgpr(r + 1) - return (lo | (hi << 32)) & MASK64 - - def set_pair(self, r: int, val: int) -> None: - self.set_sgpr(r, val & MASK32) - self.set_sgpr(r + 1, (val >> 32) & MASK32) - - def resolve_src64(self, opnd: int | dict | str) -> int: - """Resolve 64-bit scalar operand (SGPR pair, immediate, or int).""" - if isinstance(opnd, int): - return opnd & MASK64 - if isinstance(opnd, dict): - k = opnd.get("k") - if k == "imm": - return opnd["v"] & MASK64 - if k == "sgpr": - return self.get_pair(opnd["r"]) - raise ValueError(f"Unknown 64-bit operand dict: {opnd}") - if isinstance(opnd, str): - if opnd.startswith("s[") and opnd.endswith("]"): - parts = opnd[2:-1].split(":") - return self.get_pair(int(parts[0])) - if opnd.startswith("s"): - return self.get_pair(int(opnd[1:])) - return int(opnd, 0) & MASK64 - raise TypeError(f"Unsupported 64-bit operand type: {type(opnd)}") - - def resolve_src32(self, opnd: int | dict | str) -> int: - """Resolve 32-bit scalar operand (control word, single SGPR, immediate).""" - if isinstance(opnd, int): - return opnd & MASK32 - if isinstance(opnd, dict): - k = opnd.get("k") - if k == "imm": - return opnd["v"] & MASK32 - if k == "sgpr": - return self.get_sgpr(opnd["r"]) - raise ValueError(f"Unknown 32-bit operand dict: {opnd}") - if isinstance(opnd, str): - if opnd.startswith("s"): - return self.get_sgpr(int(opnd[1:])) - return int(opnd, 0) & MASK32 - raise TypeError(f"Unsupported 32-bit operand type: {type(opnd)}") - - def resolve_dst_pair(self, dst: int | dict | str) -> int: - """Resolve destination SGPR pair base index.""" - if isinstance(dst, int): - return dst - if isinstance(dst, dict) and dst.get("k") == "sgpr": - return dst["r"] - if isinstance(dst, str): - if dst.startswith("s[") and dst.endswith("]"): - parts = dst[2:-1].split(":") - return int(parts[0]) - if dst.startswith("s"): - return int(dst[1:]) - raise ValueError(f"Unsupported destination pair: {dst}") - - def step(self, op: str, dst: int | dict | str, s0: int | dict | str, s1: int | dict | str) -> tuple[int, int]: - """Execute a single 64-bit scalar ALU bitfield instruction.""" - # Read source values BEFORE writing destination to correctly handle aliased pairs - v0 = self.resolve_src64(s0) - v1 = self.resolve_src32(s1) - d_idx = self.resolve_dst_pair(dst) - - if op == "s_bfe_u64": - res, scc = ref_s_bfe_u64(v0, v1) - self.set_pair(d_idx, res) - self.scc = scc - return res, scc - if op == "s_bfe_i64": - res, scc = ref_s_bfe_i64(v0, v1) - self.set_pair(d_idx, res) - self.scc = scc - return res, scc - if op == "s_mov_b32": - self.set_sgpr(d_idx, v0 & MASK32) - return v0 & MASK32, self.scc - raise NotImplementedError(f"Instruction {op} not implemented in 64-bit interpreter") - - def run_sequence(self, instructions: list[tuple[str, int | dict | str, int | dict | str, int | dict | str]]) -> tuple[int, int]: - """Run a sequence of instructions, returning the last (res, scc).""" - last_res = 0 - last_scc = 0 - for op, dst, s0, s1 in instructions: - last_res, last_scc = self.step(op, dst, s0, s1) - return last_res, last_scc - - -class ReferenceOracleTests(unittest.TestCase): - """Validation of pure-Python 64-bit bitfield reference models and oracle behavior.""" - - def test_pack_unpack_ctl_64(self) -> None: - ctl_val = pack_bfe64_ctl(42, 60) - off, wid = unpack_bfe64_ctl(ctl_val) - self.assertEqual(off, 42) - self.assertEqual(wid, 60) - self.assertEqual(ctl_val, (60 << 16) | 42) - - # Upper bits [15:6] and [31:23] are ignored on unpack - dirty = ctl_val | 0xFF80FFC0 - off_dirty, wid_dirty = unpack_bfe64_ctl(dirty) - self.assertEqual(off_dirty, 42) - self.assertEqual(wid_dirty, 60) - - def test_ref_s_bfe_u64_basic_oracle(self) -> None: - # Extract 16 bits from offset 16 (within lower dword) - ctl_val = pack_bfe64_ctl(16, 16) - res, scc = ref_s_bfe_u64(0xDEADBEEFCAFE0000, ctl_val) - self.assertEqual(res, 0xCAFE) - self.assertEqual(scc, 1) - - # Extract 16 bits from offset 48 (within upper dword) - ctl_hi = pack_bfe64_ctl(48, 16) - res_hi, scc_hi = ref_s_bfe_u64(0xDEADBEEFCAFE0000, ctl_hi) - self.assertEqual(res_hi, 0xDEAD) - self.assertEqual(scc_hi, 1) - - def test_ref_s_bfe_u64_zero_width_oracle(self) -> None: - # Zero width must yield 0 and SCC=0 regardless of input or offset - for off in (0, 16, 31, 32, 48, 63): - ctl_val = pack_bfe64_ctl(off, 0) - res, scc = ref_s_bfe_u64(MASK64, ctl_val) - self.assertEqual(res, 0) - self.assertEqual(scc, 0) - - def test_ref_s_bfe_u64_full_64bit_oracle(self) -> None: - ctl_val = pack_bfe64_ctl(0, 64) - val = 0x0123456789ABCDEF - res, scc = ref_s_bfe_u64(val, ctl_val) - self.assertEqual(res, val) - self.assertEqual(scc, 1) - - def test_ref_s_bfe_i64_positive_oracle(self) -> None: - # 4-bit field with value 7 (msb 0) -> positive 7 - ctl_val = pack_bfe64_ctl(8, 4) - res, scc = ref_s_bfe_i64(0x700, ctl_val) - self.assertEqual(res, 7) - self.assertEqual(scc, 1) - - def test_ref_s_bfe_i64_negative_oracle(self) -> None: - # 4-bit field with value 8 (msb 1) -> negative -8 (0xFFFFFFFFFFFFFFF8) - ctl_val = pack_bfe64_ctl(8, 4) - res, scc = ref_s_bfe_i64(0x800, ctl_val) - self.assertEqual(res, (-8) & MASK64) - self.assertEqual(scc, 1) - - # 8-bit field with value 0x80 -> -128 - ctl_8 = pack_bfe64_ctl(16, 8) - res_8, scc_8 = ref_s_bfe_i64(0x00800000, ctl_8) - self.assertEqual(res_8, (-128) & MASK64) - self.assertEqual(scc_8, 1) - - def test_ref_s_bfe_i64_single_bit_sign_extension(self) -> None: - # 1-bit field with bit=1 -> sign extends to all 64 bits set (-1) - ctl_val = pack_bfe64_ctl(5, 1) - res_neg, scc_neg = ref_s_bfe_i64(1 << 5, ctl_val) - self.assertEqual(res_neg, MASK64) - self.assertEqual(scc_neg, 1) - - # 1-bit field with bit=0 -> 0, SCC=0 - res_zero, scc_zero = ref_s_bfe_i64(0, ctl_val) - self.assertEqual(res_zero, 0) - self.assertEqual(scc_zero, 0) - - def test_ref_s_bfe_clamping_past_bit_63_oracle(self) -> None: - # Offset 60, width 8 runs to bit 68 -> clamped to 4 bits - ctl_val = pack_bfe64_ctl(60, 8) - src = 0xF0000000_00000000 - res_u, scc_u = ref_s_bfe_u64(src, ctl_val) - self.assertEqual(res_u, 0xF) - self.assertEqual(scc_u, 1) - - # s_bfe_i64 sign-extends 0xF (4-bit -1) across all 64 bits - res_i, scc_i = ref_s_bfe_i64(src, ctl_val) - self.assertEqual(res_i, MASK64) - self.assertEqual(scc_i, 1) - - def test_interp_s_bfe_u64_basic(self) -> None: - interp = ScalarAlu64Interpreter() - interp.set_pair(2, 0x01234567_89ABCDEF) - interp.set_sgpr(4, pack_bfe64_ctl(32, 32)) - res, scc = interp.step("s_bfe_u64", "s[0:1]", "s[2:3]", "s4") - self.assertEqual(res, 0x01234567) - self.assertEqual(interp.get_pair(0), 0x01234567) - self.assertEqual(scc, 1) - self.assertEqual(interp.scc, 1) - - def test_interp_s_bfe_i64_basic(self) -> None: - interp = ScalarAlu64Interpreter() - interp.set_pair(2, 0x80000000_00000000) - interp.set_sgpr(4, pack_bfe64_ctl(60, 8)) - res, scc = interp.step("s_bfe_i64", "s[0:1]", "s[2:3]", "s4") - self.assertEqual(res, (-8) & MASK64) - self.assertEqual(interp.get_pair(0), (-8) & MASK64) - self.assertEqual(scc, 1) - self.assertEqual(interp.scc, 1) - - -class SgprPairAliasingTests(unittest.TestCase): - """Validation of full and overlapping SGPR pair aliasing for 64-bit scalar BFE.""" - - def setUp(self) -> None: - self.interp = ScalarAlu64Interpreter() - - def test_interp_exact_destination_aliasing(self) -> None: - # Dest is exact same register pair as source (s[0:1] = s_bfe_u64 s[0:1], ctl) - self.interp.set_pair(0, 0x12345678_9ABCDEF0) - ctl_val = pack_bfe64_ctl(16, 32) - res, scc = self.interp.step("s_bfe_u64", "s[0:1]", "s[0:1]", ctl_val) - expected = (0x12345678_9ABCDEF0 >> 16) & 0xFFFFFFFF - self.assertEqual(res, expected) - self.assertEqual(self.interp.get_pair(0), expected) - self.assertEqual(scc, 1) - - def test_interp_overlapping_pair_dest_high(self) -> None: - # Source is s[0:1], destination is s[1:2] (overlapping at s1) - self.interp.set_pair(0, 0x01234567_89ABCDEF) - self.interp.set_sgpr(2, 0xDEADBEEF) # guard - ctl_val = pack_bfe64_ctl(32, 32) - res, scc = self.interp.step("s_bfe_u64", "s[1:2]", "s[0:1]", ctl_val) - self.assertEqual(res, 0x01234567) - # s0 must be untouched by write to s[1:2] - self.assertEqual(self.interp.get_sgpr(0), 0x89ABCDEF) - # s1 gets low dword of result - self.assertEqual(self.interp.get_sgpr(1), 0x01234567) - # s2 gets high dword of result - self.assertEqual(self.interp.get_sgpr(2), 0) - self.assertEqual(scc, 1) - - def test_interp_overlapping_pair_dest_low(self) -> None: - # Source is s[1:2], destination is s[0:1] (overlapping at s1) - self.interp.set_sgpr(0, 0xCAFEBABE) # guard - self.interp.set_pair(1, 0x5555AAAA_3333CCCC) - ctl_val = pack_bfe64_ctl(16, 32) - expected, expected_scc = ref_s_bfe_u64(0x5555AAAA_3333CCCC, ctl_val) - res, scc = self.interp.step("s_bfe_u64", "s[0:1]", "s[1:2]", ctl_val) - self.assertEqual(res, expected) - self.assertEqual(self.interp.get_pair(0), expected) - # s2 is untouched by write to s[0:1] - self.assertEqual(self.interp.get_sgpr(2), 0x5555AAAA) - self.assertEqual(scc, expected_scc) - - def test_interp_ctl_register_aliased_with_source(self) -> None: - # Control word operand is s1 (the high dword of source pair s[0:1]) - ctl_val = pack_bfe64_ctl(8, 16) - self.interp.set_sgpr(0, 0x12345678) - self.interp.set_sgpr(1, ctl_val) - res, scc = self.interp.step("s_bfe_u64", "s[2:3]", "s[0:1]", "s1") - # Source value is (ctl_val << 32) | 0x12345678 - src = (ctl_val << 32) | 0x12345678 - expected, exp_scc = ref_s_bfe_u64(src, ctl_val) - self.assertEqual(res, expected) - self.assertEqual(self.interp.get_pair(2), expected) - self.assertEqual(scc, exp_scc) - - def test_interp_adjacent_sgprs_preserved(self) -> None: - # Ensure modifying s[4:5] does not corrupt s3 or s6 - self.interp.set_sgpr(3, 0x33333333) - self.interp.set_sgpr(6, 0x66666666) - self.interp.set_pair(0, 0xAAAAAAAAAAAAAAAA) - self.interp.step("s_bfe_u64", "s[4:5]", "s[0:1]", pack_bfe64_ctl(0, 32)) - self.assertEqual(self.interp.get_sgpr(3), 0x33333333) - self.assertEqual(self.interp.get_sgpr(6), 0x66666666) - - def test_shader_exact_destination_aliasing(self) -> None: - c = pack_bfe64_ctl(16, 32) - val = 0x12345678_9ABCDEF0 - expected = ref("s_bfe_u64", val, c) - lines = [ - f"s_mov_b32 s0, {val & MASK32:#x}", - f"s_mov_b32 s1, {(val >> 32) & MASK32:#x}", - f"s_mov_b32 s4, {c:#x}", - "s_bfe_u64 s[0:1], s[0:1], s4", - ] - got, scc = run_lines(lines) - self.assertEqual(got, expected) - self.assertEqual(scc, 1) - - def test_shader_overlapping_pair_s01_s12(self) -> None: - c = pack_bfe64_ctl(32, 16) - lines = [ - "s_mov_b32 s0, 0x12345678", - "s_mov_b32 s1, 0x9ABC", - f"s_mov_b32 s4, {c:#x}", - "s_bfe_u64 s[1:2], s[0:1], s4", - ] - got, scc = run_lines_dst(lines, dst_lo=1) - self.assertEqual(got, 0x9ABC) - self.assertEqual(scc, 1) - - -class SccUpdateTests(unittest.TestCase): - """Validation of Condition Code (SCC) semantics for 64-bit scalar bitfield instructions.""" - - def setUp(self) -> None: - self.interp = ScalarAlu64Interpreter() - - def test_scc_four_corners_matrix_u64(self) -> None: - # Four corners: (lo==0, hi==0), (lo!=0, hi==0), (lo==0, hi!=0), (lo!=0, hi!=0) - cases = [ - # (src, ctl, expected_scc, description) - (0, pack_bfe64_ctl(0, 32), 0, "lo=0, hi=0 -> scc=0"), - (0x12345678, pack_bfe64_ctl(0, 32), 1, "lo!=0, hi=0 -> scc=1"), - (0x12345678_00000000, pack_bfe64_ctl(32, 32), 1, "lo=0, hi!=0 extracted to lo -> scc=1"), - (0x00000001_00000000, pack_bfe64_ctl(0, 64), 1, "hi!=0 alone in 64-bit pair -> scc=1"), - (0x12345678_87654321, pack_bfe64_ctl(0, 64), 1, "lo!=0, hi!=0 -> scc=1"), - ] - for src, ctl_val, want_scc, desc in cases: - with self.subTest(desc=desc): - res, scc = self.interp.step("s_bfe_u64", "s[0:1]", src, ctl_val) - self.assertEqual(scc, want_scc) - lines = [ - f"s_mov_b32 s2, {src & MASK32:#x}", - f"s_mov_b32 s3, {(src >> 32) & MASK32:#x}", - f"s_mov_b32 s4, {ctl_val:#x}", - "s_bfe_u64 s[0:1], s[2:3], s4", - ] - _, shader_scc = run_lines(lines) - self.assertEqual(shader_scc, want_scc) - - def test_scc_four_corners_matrix_i64(self) -> None: - cases = [ - (0, pack_bfe64_ctl(0, 16), 0, "zero -> scc=0"), - (0x0005, pack_bfe64_ctl(0, 4), 1, "positive in lo -> scc=1"), - (0x0008, pack_bfe64_ctl(0, 4), 1, "negative in lo sign extends into hi -> scc=1"), - (0x00000001_00000000, pack_bfe64_ctl(0, 64), 1, "positive in hi alone -> scc=1"), - ] - for src, ctl_val, want_scc, desc in cases: - with self.subTest(desc=desc): - res, scc = self.interp.step("s_bfe_i64", "s[0:1]", src, ctl_val) - self.assertEqual(scc, want_scc) - lines = [ - f"s_mov_b32 s2, {src & MASK32:#x}", - f"s_mov_b32 s3, {(src >> 32) & MASK32:#x}", - f"s_mov_b32 s4, {ctl_val:#x}", - "s_bfe_i64 s[0:1], s[2:3], s4", - ] - _, shader_scc = run_lines(lines) - self.assertEqual(shader_scc, want_scc) - - def test_scc_cleared_on_zero_result(self) -> None: - lines = [ - "s_mov_b32 s5, 1", - "s_cmp_eq_u32 s5, 1", # sets SCC = 1 - "s_mov_b32 s2, 0", - "s_mov_b32 s3, 0", - f"s_mov_b32 s4, {pack_bfe64_ctl(0, 16):#x}", - "s_bfe_u64 s[0:1], s[2:3], s4", - ] - got, scc = run_lines(lines) - self.assertEqual(got, 0) - self.assertEqual(scc, 0) - - def test_scc_set_on_nonzero_result(self) -> None: - lines = [ - "s_mov_b32 s5, 0", - "s_cmp_eq_u32 s5, 1", # clears SCC = 0 - "s_mov_b32 s2, 0x42", - "s_mov_b32 s3, 0", - f"s_mov_b32 s4, {pack_bfe64_ctl(0, 8):#x}", - "s_bfe_u64 s[0:1], s[2:3], s4", - ] - got, scc = run_lines(lines) - self.assertEqual(got, 0x42) - self.assertEqual(scc, 1) - - def test_scc_transitions_sequence(self) -> None: - self.interp.scc = 0 - ctl_extract = pack_bfe64_ctl(0, 8) - ctl_zero = pack_bfe64_ctl(0, 0) - - # Step 1: non-zero -> scc=1 - self.interp.step("s_bfe_u64", "s[0:1]", 0xFF, ctl_extract) - self.assertEqual(self.interp.scc, 1) - - # Step 2: zero width -> scc=0 - self.interp.step("s_bfe_u64", "s[0:1]", 0xFF, ctl_zero) - self.assertEqual(self.interp.scc, 0) - - # Step 3: non-zero signed -> scc=1 - self.interp.step("s_bfe_i64", "s[0:1]", 0x80, ctl_extract) - self.assertEqual(self.interp.scc, 1) - - # Step 4: zero data -> scc=0 - self.interp.step("s_bfe_i64", "s[0:1]", 0, ctl_extract) - self.assertEqual(self.interp.scc, 0) - - -class MultiWordBitfieldTests(unittest.TestCase): - """Validation of multi-word extracts crossing and straddling 32-bit dword boundaries.""" - - def setUp(self) -> None: - self.interp = ScalarAlu64Interpreter() - - def test_dword_straddle_u64_various_widths(self) -> None: - cases = [ - ((1 << 32) | (1 << 31), 31, 2, 3), - ((1 << 32), 31, 2, 2), - ((1 << 31), 31, 2, 1), - ((0x5 << 32) | (0xA << 28), 28, 8, 0x5A), - ((0x12 << 32) | (0x34 << 24), 24, 16, 0x1234), - ((0xDEAD << 32) | (0xBEEF << 16), 16, 32, 0xDEADBEEF), - ((0x2ABCD << 32) | (0x3 << 30), 30, 20, (0x2ABCD << 2) | 3), - ] - for src, off, wid, want in cases: - with self.subTest(off=off, wid=wid): - ctl_val = pack_bfe64_ctl(off, wid) - res, scc = self.interp.step("s_bfe_u64", "s[0:1]", src, ctl_val) - self.assertEqual(res, want) - self.assertEqual(scc, 1 if want != 0 else 0) - - lines = [ - f"s_mov_b32 s2, {src & MASK32:#x}", - f"s_mov_b32 s3, {(src >> 32) & MASK32:#x}", - f"s_mov_b32 s4, {ctl_val:#x}", - "s_bfe_u64 s[0:1], s[2:3], s4", - ] - got, sh_scc = run_lines(lines) - self.assertEqual(got, want) - self.assertEqual(sh_scc, 1 if want != 0 else 0) - - def test_dword_straddle_i64_sign_extension(self) -> None: - ctl_val = pack_bfe64_ctl(28, 8) - - # Positive case: field value is 0x7F (msb 0) -> positive 0x7F - src_pos = (0x7 << 32) | (0xF << 28) - res_pos, scc_pos = self.interp.step("s_bfe_i64", "s[0:1]", src_pos, ctl_val) - self.assertEqual(res_pos, 0x7F) - self.assertEqual(scc_pos, 1) - - # Negative case: field value is 0x80 (msb 1) -> negative -128 - src_neg = (0x8 << 32) | (0x0 << 28) - res_neg, scc_neg = self.interp.step("s_bfe_i64", "s[0:1]", src_neg, ctl_val) - self.assertEqual(res_neg, (-128) & MASK64) - self.assertEqual(scc_neg, 1) - - def test_lo_dword_sign_extension_into_hi_dword(self) -> None: - ctl_val = pack_bfe64_ctl(0, 16) - src = 0x8000 - res, scc = self.interp.step("s_bfe_i64", "s[0:1]", src, ctl_val) - want = (-32768) & MASK64 - self.assertEqual(res, want) - self.assertEqual(scc, 1) - self.assertEqual(self.interp.get_sgpr(1), 0xFFFFFFFF) - self.assertEqual(self.interp.get_sgpr(0), 0xFFFF8000) - - lines = [ - f"s_mov_b32 s2, {src:#x}", - "s_mov_b32 s3, 0", - f"s_mov_b32 s4, {ctl_val:#x}", - "s_bfe_i64 s[0:1], s[2:3], s4", - ] - got, sh_scc = run_lines(lines) - self.assertEqual(got, want) - self.assertEqual(sh_scc, 1) - - def test_hi_dword_extraction_shifted_to_lo(self) -> None: - ctl_val = pack_bfe64_ctl(32, 16) - src = 0x00001234_00000000 - res, scc = self.interp.step("s_bfe_u64", "s[0:1]", src, ctl_val) - self.assertEqual(res, 0x1234) - self.assertEqual(scc, 1) - self.assertEqual(self.interp.get_sgpr(0), 0x1234) - self.assertEqual(self.interp.get_sgpr(1), 0) - - def test_full_64bit_span(self) -> None: - ctl_val = pack_bfe64_ctl(0, 64) - src = 0xCAFEBABE_DEADBEEF - res, scc = self.interp.step("s_bfe_u64", "s[0:1]", src, ctl_val) - self.assertEqual(res, src) - self.assertEqual(scc, 1) - - -class ClampBoundaryTests(unittest.TestCase): - """Validation of width / offset clamp boundaries and edge cases.""" - - def setUp(self) -> None: - self.interp = ScalarAlu64Interpreter() - - def test_width_zero_all_offsets(self) -> None: - # Zero width must return 0 and SCC=0 regardless of offset or input - for off in (0, 1, 15, 31, 32, 60, 63): - for op in ("s_bfe_u64", "s_bfe_i64"): - with self.subTest(op=op, off=off): - ctl_val = pack_bfe64_ctl(off, 0) - res, scc = self.interp.step(op, "s[0:1]", MASK64, ctl_val) - self.assertEqual(res, 0) - self.assertEqual(scc, 0) - - lines = [ - "s_mov_b32 s2, 0xFFFFFFFF", - "s_mov_b32 s3, 0xFFFFFFFF", - f"s_mov_b32 s4, {ctl_val:#x}", - f"{op} s[0:1], s[2:3], s4", - ] - got, sh_scc = run_lines(lines) - self.assertEqual(got, 0) - self.assertEqual(sh_scc, 0) - - def test_dirty_control_word_upper_bits_ignored(self) -> None: - # Bits [15:6] and [31:23] are ignored by RDNA2 hardware - clean_ctl = pack_bfe64_ctl(20, 16) - dirty_ctl = clean_ctl | 0xFF80FFC0 - val = 0x12345678_9ABCDEF0 - - res_clean_u, scc_clean_u = self.interp.step("s_bfe_u64", "s[0:1]", val, clean_ctl) - res_dirty_u, scc_dirty_u = self.interp.step("s_bfe_u64", "s[2:3]", val, dirty_ctl) - self.assertEqual(res_clean_u, res_dirty_u) - self.assertEqual(scc_clean_u, scc_dirty_u) - - res_clean_i, scc_clean_i = self.interp.step("s_bfe_i64", "s[0:1]", val, clean_ctl) - res_dirty_i, scc_dirty_i = self.interp.step("s_bfe_i64", "s[2:3]", val, dirty_ctl) - self.assertEqual(res_clean_i, res_dirty_i) - self.assertEqual(scc_clean_i, scc_dirty_i) - - # Cross-check in shader - lines = [ - f"s_mov_b32 s2, {val & MASK32:#x}", - f"s_mov_b32 s3, {(val >> 32) & MASK32:#x}", - f"s_mov_b32 s4, {dirty_ctl:#x}", - "s_bfe_u64 s[0:1], s[2:3], s4", - ] - got, sh_scc = run_lines(lines) - self.assertEqual(got, res_clean_u) - self.assertEqual(sh_scc, scc_clean_u) - - def test_width_clamping_past_bit_63_matrix(self) -> None: - # When off + wid > 64, effective width is min(wid, 64 - off) - cases = [ - # (off, wid, eff_wid) - (60, 8, 4), - (63, 64, 1), - (63, 127, 1), - (32, 64, 32), - (0, 127, 64), - (50, 20, 14), - ] - for off, wid, eff_wid in cases: - with self.subTest(off=off, wid=wid, eff_wid=eff_wid): - ctl_val = pack_bfe64_ctl(off, wid) - # Test with source having high bit of effective field set - # Bit (off + eff_wid - 1) is the top bit of the field - top_bit = 1 << (off + eff_wid - 1) - src = top_bit - - # For s_bfe_u64: extracts eff_wid bits -> 1 << (eff_wid - 1) - expected_u = 1 << (eff_wid - 1) - res_u, scc_u = self.interp.step("s_bfe_u64", "s[0:1]", src, ctl_val) - self.assertEqual(res_u, expected_u) - self.assertEqual(scc_u, 1) - - # For s_bfe_i64: top bit is set, so it sign-extends from eff_wid - expected_i = (expected_u - (1 << eff_wid)) & MASK64 - res_i, scc_i = self.interp.step("s_bfe_i64", "s[0:1]", src, ctl_val) - self.assertEqual(res_i, expected_i) - self.assertEqual(scc_i, 1) - - -class NegativeControlTests(unittest.TestCase): - """Sensitivity tests ensuring mutants in 64-bit BFE math are detected.""" - - def test_signed_vs_unsigned_mutation_caught(self) -> None: - # 16-bit field with top bit set (0x8000) - ctl_val = pack_bfe64_ctl(16, 16) - src = 0x80000000 # bits [31:16] = 0x8000 - res_u, _ = ref_s_bfe_u64(src, ctl_val) - res_i, _ = ref_s_bfe_i64(src, ctl_val) - self.assertEqual(res_u, 0x8000) - self.assertEqual(res_i, 0xFFFFFFFFFFFF8000) - self.assertNotEqual(res_u, res_i) - - def test_scc_hi_dword_mutation_caught(self) -> None: - # Result has lo=0, hi!=0 (0x12340000_00000000) - ctl_val = pack_bfe64_ctl(0, 64) - src = 0x12340000_00000000 - res, scc = ref_s_bfe_u64(src, ctl_val) - self.assertEqual(res & MASK32, 0) - self.assertEqual((res >> 32) & MASK32, 0x12340000) - # An implementation checking only (lo != 0) would fail here - self.assertEqual(scc, 1) - - def test_clamp_past_bit_63_mutation_caught(self) -> None: - # off=60, wid=8: field has 4 bits. Val at top 4 bits: 0xF - ctl_val = pack_bfe64_ctl(60, 8) - src = 0xF0000000_00000000 - res_u, _ = ref_s_bfe_u64(src, ctl_val) - # Without clamping, an implementation might take 8 bits - self.assertEqual(res_u, 0xF) - - def test_zero_width_mutation_caught(self) -> None: - ctl_val = pack_bfe64_ctl(0, 0) - res_u, scc_u = ref_s_bfe_u64(MASK64, ctl_val) - self.assertEqual(res_u, 0) - self.assertEqual(scc_u, 0) - - def test_offset_mask_32_vs_64_mutation_caught(self) -> None: - # Offset 32 should extract from the high dword - ctl_val = pack_bfe64_ctl(32, 32) - src = 0xDEADBEEF_00000000 - res, _ = ref_s_bfe_u64(src, ctl_val) - # If masked with 31 (copy-paste of 32-bit BFE), offset would become 0 -> extracting 0 - self.assertEqual(res, 0xDEADBEEF) - - -class PipelineAndEmissionTests(unittest.TestCase): - """Validation of compiler emission, multi-instruction pipelines, and operand rejections.""" - - def test_rdna2spirv_emission_u64(self) -> None: - g = rdna2spirv.Gen("ps") - ins = { - "op": "s_bfe_u64", - "args": [ - {"k": "sgpr", "r": 0, "n": 2}, - {"k": "sgpr", "r": 2, "n": 2}, - {"k": "sgpr", "r": 4}, - ], - "mods": [], - } - g.insn(ins) - emitted = "\n".join(g.body) - - self.assertIn("OpBitwiseAnd %uint", emitted) - self.assertIn("OpBitFieldUExtract %uint", emitted) - self.assertIn("OpISub %uint", emitted) - self.assertIn("OpULessThan %bool", emitted) - self.assertIn("OpSelect %uint", emitted) - self.assertIn("OpShiftRightLogical %ulong", emitted) - self.assertIn("OpBitwiseOr %uint", emitted) - self.assertIn("OpStore %scc", emitted) - self.assertTrue(g.uses_psb) - - def test_rdna2spirv_emission_i64(self) -> None: - g = rdna2spirv.Gen("ps") - ins = { - "op": "s_bfe_i64", - "args": [ - {"k": "sgpr", "r": 0, "n": 2}, - {"k": "sgpr", "r": 2, "n": 2}, - {"k": "sgpr", "r": 4}, - ], - "mods": [], - } - g.insn(ins) - emitted = "\n".join(g.body) - - self.assertIn("OpBitcast %long", emitted) - self.assertIn("OpShiftRightArithmetic %long", emitted) - self.assertIn("OpBitcast %ulong", emitted) - self.assertIn("OpStore %scc", emitted) - - def test_rdna2spirv_rejects_invalid_operands(self) -> None: - # Non-sgpr destination - g = rdna2spirv.Gen("ps") - with self.assertRaises(rdna2spirv.Unsupported): - g.insn({ - "op": "s_bfe_u64", - "args": [ - {"k": "vgpr", "r": 0, "n": 2}, - {"k": "sgpr", "r": 2, "n": 2}, - {"k": "sgpr", "r": 4}, - ], - "mods": [], - }) - - # Single SGPR destination (must have n=2) - with self.assertRaises(rdna2spirv.Unsupported): - g.insn({ - "op": "s_bfe_u64", - "args": [ - {"k": "sgpr", "r": 0, "n": 1}, - {"k": "sgpr", "r": 2, "n": 2}, - {"k": "sgpr", "r": 4}, - ], - "mods": [], - }) - - def test_chained_pipeline_execution(self) -> None: - ctl_val = pack_bfe64_ctl(16, 16) - src = 0x00000000_12340000 - # s_bfe_u64 extracts 0x1234, sets SCC=1 - # s_cselect_b32 writes 0x55 into s20 if SCC=1, else 0xAA - lines = [ - f"s_mov_b32 s2, {src & MASK32:#x}", - f"s_mov_b32 s3, {(src >> 32) & MASK32:#x}", - f"s_mov_b32 s4, {ctl_val:#x}", - "s_bfe_u64 s[0:1], s[2:3], s4", - ] - got, scc = run_lines(lines) - self.assertEqual(got, 0x1234) - self.assertEqual(scc, 1) - - def test_bitfield_roundtrip_insert_and_extract(self) -> None: - # Simulate inserting a 16-bit pattern at bit 24 of a 64-bit word, - # then extracting it back with s_bfe_u64 - base = 0xAAAAAAAA_55555555 - insert = 0xCAFE - offset = 24 - width = 16 - - mask = ((1 << width) - 1) << offset - combined = (base & ~mask) | ((insert << offset) & mask) - - ctl_val = pack_bfe64_ctl(offset, width) - extracted, scc = ref_s_bfe_u64(combined, ctl_val) - self.assertEqual(extracted, insert) - self.assertEqual(scc, 1) - - -VALUES = [0, M64, 1 << 63, 0x0123456789ABCDEF, 0xFEDCBA9876543210, 0x8000000080000000, 0x00000000FFFFFFFF] -CONTROLS = [ctl(0, 0), ctl(0, 1), ctl(0, 64), ctl(0, 127), ctl(1, 63), ctl(31, 2), ctl(32, 32), ctl(33, 31), - ctl(60, 8), ctl(63, 1), ctl(63, 64), ctl(4, 40), 0xFFC0FFFF, 0x00100020] - -_TMP_DIR = None -_SRC_PATH = None - - -def setUpModule(): - global _TMP_DIR, _SRC_PATH - _TMP_DIR = tempfile.TemporaryDirectory() - disasm_dir = os.path.join(_TMP_DIR.name, "disasm") - os.mkdir(disasm_dir) - _SRC_PATH = os.path.join(disasm_dir, "ps_salu_bfe64.s") - with open(os.path.join(_TMP_DIR.name, "ps_salu_bfe64.dxbc"), "wb") as f: - f.write(STUB_DXBC) - - -def tearDownModule(): - global _TMP_DIR - if _TMP_DIR is not None: - _TMP_DIR.cleanup() - _TMP_DIR = None - - -def run_lines_dst(lines, dst_lo: int = 0) -> tuple: - """Run the lines, return (s[dst_lo:dst_lo+1] as one 64-bit value, SCC).""" - if _TMP_DIR is None: - setUpModule() - tail = ["s_cselect_b32 s20, 0x40000001, 0x40000000"] - for i, (r_offset, sh) in enumerate(((0, 0), (0, 16), (1, 0), (1, 16))): - r = dst_lo + r_offset - tail += [f"s_lshr_b32 s{10 + i}, s{r}, {sh}", f"s_and_b32 s{10 + i}, s{10 + i}, 0xffff", - f"s_or_b32 s{10 + i}, s{10 + i}, 0x40000000", f"v_mov_b32 v{i}, s{10 + i}"] - tail.append("v_mov_b32 v4, s20") - asm = ("; test_salu_bfe64\n" + "".join(f"\t{ln}\n" for ln in list(lines) + tail) - + "\texp mrt0 v0, v1, v2, v3 vm\n\texp mrt1 v4, v4, v4, v4 done vm\n\ts_endpgm\n") - with open(_SRC_PATH, "w", encoding="utf-8") as f: - f.write(asm) - with warnings.catch_warnings(): - warnings.simplefilter("ignore", ResourceWarning) - spv = rdna2spirv.translate(_SRC_PATH) - out = si.run_fragment(spv) - w, scc = out["%out_mrt0"], out["%out_mrt1"][0] - assert all(x >> 16 == 0x4000 for x in w) and scc >> 1 == 0x20000000, ([hex(x) for x in w], hex(scc)) - return sum((x & 0xFFFF) << (16 * i) for i, x in enumerate(w)), scc & 1 - - -def run_lines(lines) -> tuple: - """Run the lines, return (s[0:1] as one 64-bit value, SCC).""" - return run_lines_dst(lines, dst_lo=0) - - -def run_op(op: str, x: int, c: int, scc_in: int = 0) -> tuple: - return run_lines([f"s_mov_b32 s2, {x & 0xFFFFFFFF:#x}", f"s_mov_b32 s3, {x >> 32:#x}", f"s_mov_b32 s4, {c:#x}", - f"s_mov_b32 s5, {scc_in}", "s_cmp_eq_u32 s5, 1", f"{op} s[0:1], s[2:3], s4"]) - - -class Bfe64Tests(unittest.TestCase): - def test_reference(self): - self.assertEqual(ref("s_bfe_u64", 0x0123456789ABCDEF, ctl(32, 32)), 0x01234567) - self.assertEqual(ref("s_bfe_i64", 1 << 63, ctl(60, 8)), (-8) & M64) # field past bit 63: >> 60 - self.assertEqual(ref("s_bfe_u64", M64, ctl(0, 127)), M64) # width cut to 64 - self.assertEqual(ref("s_bfe_i64", 0x80, ctl(4, 4)), (-8) & M64) - self.assertEqual(ref("s_bfe_u64", M64, ctl(5, 0)), 0) - - def test_values_and_scc(self): - for op in OPS: - for x in VALUES: - for c in CONTROLS: - want = ref(op, x, c) - with self.subTest(op=op, x=hex(x), ctl=hex(c)): - self.assertEqual(run_op(op, x, c, 1 - int(want != 0)), (want, int(want != 0))) - - def test_seeded(self): - rng = random.Random(0xBFE64) - for _ in range(30): - op, x = rng.choice(OPS), rng.getrandbits(64) - c = ctl(rng.randrange(64), rng.randrange(128)) if rng.random() < 0.8 else rng.getrandbits(32) - with self.subTest(op=op, x=hex(x), ctl=hex(c)): - self.assertEqual(run_op(op, x, c)[0], ref(op, x, c)) - - def test_lane_mask_source_is_rejected(self): - with self.assertRaises(rdna2spirv.Unsupported): - run_lines(["s_mov_b32 s4, 0x100000", "s_bfe_u64 s[0:1], exec, s4"]) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_salu_bfm64_add_i32.py b/tests/semantic/test_salu_bfm64_add_i32.py deleted file mode 100644 index aa024dca3..000000000 --- a/tests/semantic/test_salu_bfm64_add_i32.py +++ /dev/null @@ -1,290 +0,0 @@ -"""Semantic interpreter tests for RDNA2 s_bfm_b64 and s_add_i32. - -s_bfm_b64 (RDNA2 ISA): D = ((1 << (S0 & 63)) - 1) << (S1 & 63) as a 64-bit lane mask; SCC is not written. -Each case translates a synthetic wave64 pixel shader with tools/rdna2spirv.py, executes all 64 lanes in -tests/semantic/spirv_wave_interp.py, reads D via v_cndmask_b32_e64 and SCC via s_cselect_b32, and compares -all 64 lane bits against a plain-Python reference. - -s_add_i32 (RDNA2 ISA): D = (S0 + S1) & 0xFFFFFFFF; SCC = signed 32-bit overflow. -Each case translates a synthetic pixel shader with tools/rdna2spirv.py, runs it in -tests/semantic/spirv_mini_interp.py, and compares (D, SCC) against a plain-Python signed 32-bit reference, -including direct contrast with s_add_u32 on unsigned wrap without signed overflow. -""" -import os -import random -import sys -import unittest - -HERE = os.path.dirname(os.path.abspath(__file__)) -sys.dont_write_bytecode = True -if HERE not in sys.path: - sys.path.insert(0, HERE) - -import spirv_mini_interp as si # noqa: E402 -import spirv_wave_interp as wi # noqa: E402 -import support # noqa: E402 - -MASK32 = 0xFFFFFFFF -MASK64 = 0xFFFFFFFFFFFFFFFF - -# (size, offset) cases covering zero, low-half, high-half, straddling 31/32, truncation > 63, and mod-64 wrap. -BFM_CASES = [ - (0, 0), - (0, 31), - (0, 45), - (1, 0), - (1, 63), - (8, 4), # low half: offset < 32, offset + size <= 32 - (32, 0), # full low half - (12, 32), # high half: offset >= 32 - (16, 40), # high half: offset >= 32 - (32, 32), # full high half - (8, 28), # straddles bit 31/32 - (2, 31), # straddles bit 31/32 minimally - (64, 0), # size & 63 == 0 -> mask 0 - (63, 0), # lanes 0..62 - (63, 1), # lanes 1..63 - (32, 48), # truncated past lane 63 (offset + size > 64) - (63, 40), # truncated past lane 63 - (65, 66), # size=65 -> 1, offset=66 -> 2 - (128, 3), # size=128 -> 0 - (0x105, 0x120), # size=5, offset=32 -] - -ADD_BOUNDARY_CASES = [ - # (x, y, description) - (0, 0, "zero + zero"), - (0, 0x7FFFFFFF, "zero + INT32_MAX"), - (0, 0x80000000, "zero + INT32_MIN"), - (0x7FFFFFFF, 1, "positive overflow: INT32_MAX + 1"), - (0x7FFFFFFF, 0x7FFFFFFF, "positive overflow: INT32_MAX + INT32_MAX"), - (0x40000000, 0x40000000, "positive overflow: 2^30 + 2^30"), - (0x80000000, 0x80000000, "negative overflow: INT32_MIN + INT32_MIN"), - (0x80000000, 0xFFFFFFFF, "negative overflow: INT32_MIN + (-1)"), - (0xC0000000, 0xBFFFFFFF, "negative overflow: -2^30 + (-2^30 - 1)"), - (0xFFFFFFFF, 1, "unsigned wrap without signed overflow: (-1) + 1"), - (0xFFFFFFFF, 0xFFFFFFFF, "unsigned wrap without signed overflow: (-1) + (-1)"), - (0x80000000, 0x7FFFFFFF, "opposite signs: INT32_MIN + INT32_MAX"), - (0x7FFFFFFF, 0x80000000, "opposite signs: INT32_MAX + INT32_MIN"), - (0x12345678, 0xEDCBA988, "opposite signs cancelling to zero"), - (0x40000000, 0x3FFFFFFF, "exactly INT32_MAX, no overflow"), - (0xC0000000, 0xC0000000, "exactly INT32_MIN from two negatives, no overflow"), - (0x80000001, 0xFFFFFFFF, "(INT32_MIN + 1) + (-1) = INT32_MIN, no overflow"), - (0x80000000, 1, "INT32_MIN + 1, no overflow"), -] - - -def s32(x: int) -> int: - x &= MASK32 - return x - (1 << 32) if x >> 31 else x - - -def ref_bfm_b64(size: int, offset: int) -> int: - sz = size & 63 - off = offset & 63 - return (((1 << sz) - 1) << off) & MASK64 - - -def ref_add_i32(x: int, y: int) -> tuple: - total = s32(x) + s32(y) - ovf = int(total < -(1 << 31) or total >= (1 << 31)) - return total & MASK32, ovf - - -def ref_add_u32(x: int, y: int) -> tuple: - total = (x & MASK32) + (y & MASK32) - return total & MASK32, int(total > MASK32) - - -def run_bfm_b64(setup_lines, size_op: str, off_op: str, scc_in: int = 0) -> tuple: - lines = [ - "s_mov_b64 exec, -1", - *setup_lines, - f"s_mov_b32 s4, {scc_in}", - "s_cmp_eq_u32 s4, 1", - f"s_bfm_b64 s[0:1], {size_op}, {off_op}", - "s_cselect_b32 s5, 1, 0", - "v_cndmask_b32_e64 v0, 0, 1, s[0:1]", - "v_mov_b32 v1, s5", - "v_mov_b32 v2, 0", - "v_mov_b32 v3, 0", - "exp mrt0 v0, v1, v2, v3 done vm", - "s_endpgm", - ] - spv = support.translate_lines("ps_salu_bfm64", lines) - res = wi.run_wave(spv, wave=64) - outs = res["outputs"] - assert len(outs) == 64 - mask = 0 - for lane, out in enumerate(outs): - assert out is not None, f"lane {lane} killed" - bit, scc_out = out["%out_mrt0"][:2] - assert bit in (0, 1), f"lane {lane} unexpected mask bit {bit}" - assert scc_out == scc_in, f"lane {lane} SCC changed from {scc_in} to {scc_out}" - mask |= bit << lane - return mask, outs[0]["%out_mrt0"][1] - - -def run_add_op(op: str, setup_lines, x_op: str, y_op: str, scc_in: int = 0) -> tuple: - lines = [ - *setup_lines, - f"s_mov_b32 s4, {scc_in}", - "s_cmp_eq_u32 s4, 1", - f"{op} s0, {x_op}, {y_op}", - "s_cselect_b32 s1, 1, 0", - "v_mov_b32 v0, s0", - "v_mov_b32 v1, s1", - "exp mrt0 v0, v1, v0, v0 done vm", - "s_endpgm", - ] - spv = support.translate_lines("ps_salu_add", lines) - out = si.run_fragment(spv)["%out_mrt0"] - return out[0], out[1] - - -class BfmB64Tests(unittest.TestCase): - def test_reference(self): - self.assertEqual(ref_bfm_b64(0, 17), 0) - self.assertEqual(ref_bfm_b64(8, 28), 0x0000000FF0000000) - self.assertEqual(ref_bfm_b64(32, 48), 0xFFFF000000000000) - self.assertEqual(ref_bfm_b64(65, 66), 1 << 2) - - def test_sgpr_operands_wave64(self): - for size, offset in BFM_CASES: - for scc_in in (0, 1): - with self.subTest(size=size, offset=offset, scc_in=scc_in): - setup = [f"s_mov_b32 s2, {size:#x}", f"s_mov_b32 s3, {offset:#x}"] - got_mask, got_scc = run_bfm_b64(setup, "s2", "s3", scc_in=scc_in) - self.assertEqual(got_mask, ref_bfm_b64(size, offset)) - self.assertEqual(got_scc, scc_in) - - def test_immediate_operands_wave64(self): - imm_cases = [ - ("0", "0", 0, 0), - ("8", "28", 8, 28), - ("32", "48", 32, 48), - ("65", "66", 65, 66), - ("0x10", "0x24", 16, 36), - ] - for s_lit, o_lit, size, offset in imm_cases: - with self.subTest(size=s_lit, offset=o_lit): - got_mask, _ = run_bfm_b64([], s_lit, o_lit, scc_in=1) - self.assertEqual(got_mask, ref_bfm_b64(size, offset)) - # Mixed SGPR + immediate - got_mixed, _ = run_bfm_b64([f"s_mov_b32 s2, {size:#x}"], "s2", o_lit, scc_in=0) - self.assertEqual(got_mixed, ref_bfm_b64(size, offset)) - - def test_vcc_and_null_destinations_wave64(self): - # D = vcc (read back as a lane mask by v_cndmask_b32_e32); D = null discards the mask and keeps SCC. - for size, offset in ((8, 28), (20, 48), (32, 0)): - for scc_in in (0, 1): - with self.subTest(size=size, offset=offset, scc_in=scc_in): - spv = support.translate_lines("ps_salu_bfm64_vcc", [ - "s_mov_b64 exec, -1", - "s_mov_b64 vcc, 0", - f"s_bfm_b64 vcc, {size}, {offset}", - f"s_mov_b32 s4, {scc_in}", - "s_cmp_eq_u32 s4, 1", - "s_bfm_b64 null, 63, 1", - "s_cselect_b32 s5, 1, 0", - "v_cndmask_b32_e32 v0, 0, 1, vcc", - "v_mov_b32 v1, s5", - "v_mov_b32 v2, 0", - "v_mov_b32 v3, 0", - "exp mrt0 v0, v1, v2, v3 done vm", - "s_endpgm", - ]) - outs = wi.run_wave(spv, wave=64)["outputs"] - mask = sum(out["%out_mrt0"][0] << lane for lane, out in enumerate(outs)) - self.assertEqual(mask, ref_bfm_b64(size, offset)) - self.assertEqual({out["%out_mrt0"][1] for out in outs}, {scc_in}) - - def test_seeded_wave64(self): - rng = random.Random(0xBF64) - for _ in range(20): - size = rng.getrandbits(10) - offset = rng.getrandbits(10) - with self.subTest(size=size, offset=offset): - setup = [f"s_mov_b32 s2, {size:#x}", f"s_mov_b32 s3, {offset:#x}"] - got_mask, _ = run_bfm_b64(setup, "s2", "s3") - self.assertEqual(got_mask, ref_bfm_b64(size, offset)) - - -class AddI32Tests(unittest.TestCase): - def test_reference(self): - self.assertEqual(ref_add_i32(0x7FFFFFFF, 1), (0x80000000, 1)) - self.assertEqual(ref_add_i32(0x80000000, 0x80000000), (0, 1)) - self.assertEqual(ref_add_i32(0x80000000, 0xFFFFFFFF), (0x7FFFFFFF, 1)) - self.assertEqual(ref_add_i32(0xFFFFFFFF, 1), (0, 0)) - - def test_boundaries_and_scc(self): - for x, y, desc in ADD_BOUNDARY_CASES: - want = ref_add_i32(x, y) - # Seed SCC opposite to expected to verify s_add_i32 overwrites SCC in both directions. - scc_in = 1 - want[1] - with self.subTest(case=desc, x=hex(x), y=hex(y)): - setup = [f"s_mov_b32 s2, {x:#x}", f"s_mov_b32 s3, {y:#x}"] - self.assertEqual(run_add_op("s_add_i32", setup, "s2", "s3", scc_in=scc_in), want) - - def test_contrast_with_s_add_u32(self): - contrast_cases = [ - (0xFFFFFFFF, 1, (0, 0), (0, 1)), # unsigned wrap, no signed overflow - (0x7FFFFFFF, 1, (0x80000000, 1), (0x80000000, 0)), # signed overflow, no unsigned wrap - (0x80000000, 0x80000000, (0, 1), (0, 1)), # both overflow - (0x80000000, 0xFFFFFFFF, (0x7FFFFFFF, 1), (0x7FFFFFFF, 1)), # both overflow - ] - for x, y, want_i32, want_u32 in contrast_cases: - with self.subTest(x=hex(x), y=hex(y)): - setup = [f"s_mov_b32 s2, {x:#x}", f"s_mov_b32 s3, {y:#x}"] - self.assertEqual(run_add_op("s_add_i32", setup, "s2", "s3", scc_in=1 - want_i32[1]), want_i32) - self.assertEqual(run_add_op("s_add_u32", setup, "s2", "s3", scc_in=1 - want_u32[1]), want_u32) - self.assertEqual(want_i32, ref_add_i32(x, y)) - self.assertEqual(want_u32, ref_add_u32(x, y)) - - def test_immediate_operands(self): - self.assertEqual( - run_add_op("s_add_i32", ["s_mov_b32 s2, 0x7fffffff"], "s2", "1", scc_in=0), - (0x80000000, 1), - ) - self.assertEqual( - run_add_op("s_add_i32", ["s_mov_b32 s2, 0x80000000"], "s2", "-1", scc_in=0), - (0x7FFFFFFF, 1), - ) - self.assertEqual( - run_add_op("s_add_i32", ["s_mov_b32 s2, 0xffffffff"], "s2", "1", scc_in=1), - (0, 0), - ) - - def test_aliasing_m0_and_null_destination(self): - cases = [ - # (lines, want (D, SCC)); D is s0 afterwards, SCC the last s_add_i32's. - (["s_mov_b32 s0, 0x40000000", "s_add_i32 s0, s0, s0"], (0x80000000, 1)), # D == S0 == S1 - (["s_mov_b32 s0, 0x80000000", "s_mov_b32 s1, -1", "s_add_i32 s0, s1, s0"], (0x7FFFFFFF, 1)), # D == S1 - (["s_mov_b32 s0, 0x80000000", "s_mov_b32 m0, -1", "s_add_i32 s0, s0, m0"], (0x7FFFFFFF, 1)), # M0 source - # null D: the sum is dropped but SCC is still written (0 after an overflowing add left it 1). - (["s_mov_b32 s0, 5", "s_add_i32 s2, 0x7fffffff, 1", "s_add_i32 null, -1, 1"], (5, 0)), - (["s_mov_b32 s0, 5", "s_add_i32 s2, -1, 1", "s_add_i32 null, 0x80000000, -1"], (5, 1)), - ] - for body, want in cases: - with self.subTest(body=body[-1]): - spv = support.translate_lines("ps_salu_add_alias", body + [ - "s_cselect_b32 s1, 1, 0", - "v_mov_b32 v0, s0", - "v_mov_b32 v1, s1", - "exp mrt0 v0, v1, v0, v0 done vm", - "s_endpgm", - ]) - self.assertEqual(tuple(si.run_fragment(spv)["%out_mrt0"][:2]), want) - - def test_seeded_random(self): - rng = random.Random(0xADD32) - for _ in range(30): - x, y = rng.getrandbits(32), rng.getrandbits(32) - want = ref_add_i32(x, y) - with self.subTest(x=hex(x), y=hex(y)): - setup = [f"s_mov_b32 s2, {x:#x}", f"s_mov_b32 s3, {y:#x}"] - self.assertEqual(run_add_op("s_add_i32", setup, "s2", "s3", scc_in=1 - want[1]), want) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_salu_bitfield_ins_u32.py b/tests/semantic/test_salu_bitfield_ins_u32.py deleted file mode 100644 index 747b81436..000000000 --- a/tests/semantic/test_salu_bitfield_ins_u32.py +++ /dev/null @@ -1,134 +0,0 @@ -"""Translator tests for the scalar bitfield-insert sequence. - -RDNA2's SALU has no bitfield-insert instruction; shaders insert `insert` into `base` at [offset +: width] with - - s_bfm_b32 mask, width, offset mask = ((1 << (width & 31)) - 1) << (offset & 31), SCC unchanged - s_lshl_b32 field, insert, offset field = insert << (offset & 31) - s_and_b32 field, field, mask - s_andn2_b32 kept, base, mask kept = base & ~mask - s_or_b32 dst, kept, field SCC = dst != 0 - -Each case translates that listing through tools/rdna2spirv.py and executes it in tests/semantic/spirv_mini_interp.py, -with the operands as push constants (run-time values) and as s_mov_b32 immediates (folded at translation time). -Standard library only; no GPU, no game files. -""" -import os -import random -import sys -import unittest - -HERE = os.path.dirname(os.path.abspath(__file__)) -if HERE not in sys.path: - sys.path.insert(0, HERE) - -import support # noqa: E402 - -MASK32 = 0xFFFFFFFF - - -def ref_insert(base, insert, offset, width): - """(dst, scc, mask) of the sequence above, from the RDNA2 ISA pseudocode of each instruction.""" - mask = (((1 << (width & 31)) - 1) << (offset & 31)) & MASK32 - field = ((insert << (offset & 31)) & MASK32) & mask - dst = (base & ~mask & MASK32) | field - return dst, 1 if dst else 0, mask - - -SEQUENCE = [ - "s_bfm_b32 s4, s2, s1", - "s_lshl_b32 s5, s3, s1", - "s_and_b32 s5, s5, s4", - "s_andn2_b32 s6, s0, s4", - "s_or_b32 s7, s6, s5", -] -EXPORT = [ - "s_cselect_b32 s8, 1, 0", - "v_mov_b32 v0, s7", - "v_mov_b32 v1, s8", - "v_mov_b32 v2, s4", - "v_mov_b32 v3, 0", - "exp mrt0 v0, v1, v2, v3 done vm", - "s_endpgm", -] - -OFFSETS = (0, 1, 7, 16, 31, 33) -WIDTHS = (0, 1, 5, 16, 31, 32, 40) -VALUES = (0, MASK32, 0xA5A5A5A5, 0x12345678) - - -class BitfieldInsertSequenceTests(unittest.TestCase): - @classmethod - def setUpClass(cls): - cls.spv = support.translate_lines("ps_salu_bitfield_insert", SEQUENCE + EXPORT) - - def run_case(self, base, insert, offset, width): - out = support.mrt0_words(self.spv, push_constants=[base, offset, width, insert]) - return out[0], out[1], out[2] - - def test_reference_examples(self): - self.assertEqual(ref_insert(0xFFFFFFFF, 0, 4, 8), (0xFFFFF00F, 1, 0x00000FF0)) - self.assertEqual(ref_insert(0, 0xFF, 28, 8), (0xF0000000, 1, 0xF0000000)) - self.assertEqual(ref_insert(0x12345678, 0xABCD, 8, 0), (0x12345678, 1, 0)) - self.assertEqual(ref_insert(0, 0, 0, 31), (0, 0, 0x7FFFFFFF)) - - def test_offset_width_grid(self): - for offset in OFFSETS: - for width in WIDTHS: - for base in VALUES: - for insert in VALUES: - with self.subTest(base=hex(base), insert=hex(insert), offset=offset, width=width): - self.assertEqual(self.run_case(base, insert, offset, width), - ref_insert(base, insert, offset, width)) - - def test_scc_is_zero_only_for_a_zero_result(self): - # base cleared by the mask and nothing inserted: dst == 0, SCC == 0 - self.assertEqual(self.run_case(0x0000FF00, 0, 8, 8), (0, 0, 0x0000FF00)) - # s_bfm_b32 leaves SCC alone, so SCC is s_or_b32's even when the mask is zero - self.assertEqual(self.run_case(0, 0xFFFFFFFF, 3, 0), (0, 0, 0)) - self.assertEqual(self.run_case(1, 0, 3, 0), (1, 1, 0)) - - def test_seeded_random(self): - rng = random.Random(0xBF1) - for i in range(200): - base, insert = rng.getrandbits(32), rng.getrandbits(32) - offset, width = rng.getrandbits(6), rng.getrandbits(6) - with self.subTest(case=i): - self.assertEqual(self.run_case(base, insert, offset, width), - ref_insert(base, insert, offset, width)) - - def test_constant_operands_fold(self): - cases = ( - (0xFFFFFFFF, 0, 4, 8), - (0x12345678, 0xABCD, 8, 16), - (0x0000FF00, 0, 8, 8), - (0xDEADBEEF, 0x5, 30, 4), - (0x80000000, 0x7FFFFFFF, 1, 31), - ) - for base, insert, offset, width in cases: - with self.subTest(base=hex(base), insert=hex(insert), offset=offset, width=width): - movs = [f"s_mov_b32 s0, {base:#x}", f"s_mov_b32 s1, {offset}", f"s_mov_b32 s2, {width}", - f"s_mov_b32 s3, {insert:#x}"] - spv = support.translate_lines("ps_salu_bitfield_insert_const", movs + SEQUENCE + EXPORT) - self.assertEqual(tuple(support.mrt0_words(spv)[:3]), ref_insert(base, insert, offset, width)) - - def test_destination_aliases_base(self): - # dst written over base, as compilers emit it in place - spv = support.translate_lines("ps_salu_bitfield_insert_alias", SEQUENCE[:3] + [ - "s_andn2_b32 s0, s0, s4", - "s_or_b32 s0, s0, s5", - "s_cselect_b32 s8, 1, 0", - "v_mov_b32 v0, s0", - "v_mov_b32 v1, s8", - "v_mov_b32 v2, s4", - "v_mov_b32 v3, 0", - "exp mrt0 v0, v1, v2, v3 done vm", - "s_endpgm", - ]) - for base, insert, offset, width in ((0xFFFFFFFF, 0x3, 4, 2), (0x0F0F0F0F, 0xF, 28, 4)): - with self.subTest(base=hex(base)): - out = support.mrt0_words(spv, push_constants=[base, offset, width, insert]) - self.assertEqual(tuple(out[:3]), ref_insert(base, insert, offset, width)) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_salu_bitset_b64.py b/tests/semantic/test_salu_bitset_b64.py deleted file mode 100644 index df0765b85..000000000 --- a/tests/semantic/test_salu_bitset_b64.py +++ /dev/null @@ -1,117 +0,0 @@ -"""Semantic interpreter tests for RDNA2 s_bitset0_b64 and s_bitset1_b64. - -D[S0 & 63] = 0 (bitset0) or 1 (bitset1) in the SGPR pair D, which is both source and destination; the other 63 -bits are kept and SCC is not written. The pair is 64-bit data here, as for s_lshl_b64. Each case translates a -synthetic pixel shader with tools/rdna2spirv.py, runs it in tests/semantic/spirv_mini_interp.py and compares the pair -with a plain-Python reference. The pair leaves through exp as four 16-bit halves ORed into 0x40000000, so no export -channel is a NaN or denormal pattern that a float round trip could change; SCC comes back through s_cselect_b32. -""" -import os -import random -import struct -import sys -import tempfile -import unittest -import warnings - -HERE = os.path.dirname(os.path.abspath(__file__)) -ROOT = os.path.dirname(os.path.dirname(HERE)) -TOOLS_DIR = os.environ.get("LEONIDA_TOOLS_DIR") or os.path.join(ROOT, "tools") - -sys.dont_write_bytecode = True -sys.path.insert(0, TOOLS_DIR) -sys.path.insert(0, HERE) - -import rdna2spirv # noqa: E402 -import spirv_mini_interp as si # noqa: E402 - -M64 = (1 << 64) - 1 -STUB_DXBC = b"DXBC" + bytes(24) + struct.pack(" int: - m = 1 << (b & 63) - return (old | m) if op == "s_bitset1_b64" else (old & ~m & M64) - - -_TMP_DIR = None -_SRC_PATH = None - - -def setUpModule(): - global _TMP_DIR, _SRC_PATH - _TMP_DIR = tempfile.TemporaryDirectory() - disasm_dir = os.path.join(_TMP_DIR.name, "disasm") - os.mkdir(disasm_dir) - _SRC_PATH = os.path.join(disasm_dir, "ps_salu_bitset64.s") - with open(os.path.join(_TMP_DIR.name, "ps_salu_bitset64.dxbc"), "wb") as f: - f.write(STUB_DXBC) - - -def tearDownModule(): - global _TMP_DIR - if _TMP_DIR is not None: - _TMP_DIR.cleanup() - _TMP_DIR = None - - -def run_lines(lines) -> tuple: - """Run the lines, return (s[0:1] as one 64-bit value, SCC).""" - if _TMP_DIR is None: - setUpModule() - tail = ["s_cselect_b32 s20, 0x40000001, 0x40000000"] - for i, (r, sh) in enumerate(((0, 0), (0, 16), (1, 0), (1, 16))): - tail += [f"s_lshr_b32 s{10 + i}, s{r}, {sh}", f"s_and_b32 s{10 + i}, s{10 + i}, 0xffff", - f"s_or_b32 s{10 + i}, s{10 + i}, 0x40000000", f"v_mov_b32 v{i}, s{10 + i}"] - tail.append("v_mov_b32 v4, s20") - asm = ("; test_salu_bitset64\n" + "".join(f"\t{ln}\n" for ln in list(lines) + tail) - + "\texp mrt0 v0, v1, v2, v3 vm\n\texp mrt1 v4, v4, v4, v4 done vm\n\ts_endpgm\n") - with open(_SRC_PATH, "w", encoding="utf-8") as f: - f.write(asm) - with warnings.catch_warnings(): - warnings.simplefilter("ignore", ResourceWarning) - spv = rdna2spirv.translate(_SRC_PATH) - out = si.run_fragment(spv) - w, scc = out["%out_mrt0"], out["%out_mrt1"][0] - assert all(x >> 16 == 0x4000 for x in w) and scc >> 1 == 0x20000000, ([hex(x) for x in w], hex(scc)) - return sum((x & 0xFFFF) << (16 * i) for i, x in enumerate(w)), scc & 1 - - -def run_op(op: str, old: int, b: int, scc_in: int = 0) -> tuple: - return run_lines([f"s_mov_b32 s0, {old & 0xFFFFFFFF:#x}", f"s_mov_b32 s1, {old >> 32:#x}", f"s_mov_b32 s2, {b:#x}", - f"s_mov_b32 s4, {scc_in}", "s_cmp_eq_u32 s4, 1", f"{op} s[0:1], s2"]) - - -class BitsetB64Tests(unittest.TestCase): - def test_reference(self): - self.assertEqual(ref("s_bitset1_b64", 0, 33), 1 << 33) - self.assertEqual(ref("s_bitset0_b64", M64, 63), M64 >> 1) - self.assertEqual(ref("s_bitset1_b64", 0, 64), 1) # index taken mod 64 - - def test_values_and_scc_kept(self): - for op in ("s_bitset0_b64", "s_bitset1_b64"): - for old in OLD: - for b in BITS: - for scc_in in (0, 1): - with self.subTest(op=op, old=hex(old), bit=b, scc=scc_in): - self.assertEqual(run_op(op, old, b, scc_in), (ref(op, old, b), scc_in)) - - def test_seeded(self): - rng = random.Random(0xB17) - for _ in range(20): - op, old, b = rng.choice(("s_bitset0_b64", "s_bitset1_b64")), rng.getrandbits(64), rng.getrandbits(32) - with self.subTest(op=op, old=hex(old), bit=hex(b)): - self.assertEqual(run_op(op, old, b)[0], ref(op, old, b)) - - def test_inline_index(self): - self.assertEqual(run_lines(["s_mov_b32 s0, 0", "s_mov_b32 s1, 0", "s_bitset1_b64 s[0:1], 40"])[0], 1 << 40) - - def test_lane_mask_destination_is_rejected(self): - with self.assertRaises(rdna2spirv.Unsupported): - run_lines(["s_bitset1_b64 exec, 3"]) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_salu_brev_b64.py b/tests/semantic/test_salu_brev_b64.py deleted file mode 100644 index ee0cd3306..000000000 --- a/tests/semantic/test_salu_brev_b64.py +++ /dev/null @@ -1,116 +0,0 @@ -"""Semantic interpreter tests for RDNA2 s_brev_b64. - -D = the 64 bits of S0 in reverse order (bit i goes to bit 63 - i), so D.lo = reverse(S0.hi) and D.hi = -reverse(S0.lo). SCC is not written. The SGPR pair is 64-bit data here, as for s_lshl_b64. Each case translates a -synthetic pixel shader with tools/rdna2spirv.py, runs it in tests/semantic/spirv_mini_interp.py and compares the -pair with a plain-Python reference. The pair leaves through exp as four 16-bit halves ORed into 0x40000000, so no -export channel is a NaN or denormal pattern that a float round trip could change; SCC comes back through -s_cselect_b32. -""" -import os -import random -import struct -import sys -import tempfile -import unittest -import warnings - -HERE = os.path.dirname(os.path.abspath(__file__)) -ROOT = os.path.dirname(os.path.dirname(HERE)) -TOOLS_DIR = os.environ.get("LEONIDA_TOOLS_DIR") or os.path.join(ROOT, "tools") - -sys.dont_write_bytecode = True -sys.path.insert(0, TOOLS_DIR) -sys.path.insert(0, HERE) - -import rdna2spirv # noqa: E402 -import spirv_mini_interp as si # noqa: E402 - -M64 = (1 << 64) - 1 -STUB_DXBC = b"DXBC" + bytes(24) + struct.pack(" int: - return int(f"{x & M64:064b}"[::-1], 2) - - -_TMP_DIR = None -_SRC_PATH = None - - -def setUpModule(): - global _TMP_DIR, _SRC_PATH - _TMP_DIR = tempfile.TemporaryDirectory() - disasm_dir = os.path.join(_TMP_DIR.name, "disasm") - os.mkdir(disasm_dir) - _SRC_PATH = os.path.join(disasm_dir, "ps_salu_brev64.s") - with open(os.path.join(_TMP_DIR.name, "ps_salu_brev64.dxbc"), "wb") as f: - f.write(STUB_DXBC) - - -def tearDownModule(): - global _TMP_DIR - if _TMP_DIR is not None: - _TMP_DIR.cleanup() - _TMP_DIR = None - - -def run_lines(lines) -> tuple: - """Run the lines, return (s[0:1] as one 64-bit value, SCC).""" - if _TMP_DIR is None: - setUpModule() - tail = ["s_cselect_b32 s20, 0x40000001, 0x40000000"] - for i, (r, sh) in enumerate(((0, 0), (0, 16), (1, 0), (1, 16))): - tail += [f"s_lshr_b32 s{10 + i}, s{r}, {sh}", f"s_and_b32 s{10 + i}, s{10 + i}, 0xffff", - f"s_or_b32 s{10 + i}, s{10 + i}, 0x40000000", f"v_mov_b32 v{i}, s{10 + i}"] - tail.append("v_mov_b32 v4, s20") - asm = ("; test_salu_brev64\n" + "".join(f"\t{ln}\n" for ln in list(lines) + tail) - + "\texp mrt0 v0, v1, v2, v3 vm\n\texp mrt1 v4, v4, v4, v4 done vm\n\ts_endpgm\n") - with open(_SRC_PATH, "w", encoding="utf-8") as f: - f.write(asm) - with warnings.catch_warnings(): - warnings.simplefilter("ignore", ResourceWarning) - spv = rdna2spirv.translate(_SRC_PATH) - out = si.run_fragment(spv) - w, scc = out["%out_mrt0"], out["%out_mrt1"][0] - assert all(x >> 16 == 0x4000 for x in w) and scc >> 1 == 0x20000000, ([hex(x) for x in w], hex(scc)) - return sum((x & 0xFFFF) << (16 * i) for i, x in enumerate(w)), scc & 1 - - -def run_op(x: int, scc_in: int) -> tuple: - return run_lines([f"s_mov_b32 s2, {x & 0xFFFFFFFF:#x}", f"s_mov_b32 s3, {x >> 32:#x}", f"s_mov_b32 s4, {scc_in}", - "s_cmp_eq_u32 s4, 1", "s_brev_b64 s[0:1], s[2:3]"]) - - -class BrevB64Tests(unittest.TestCase): - def test_reference(self): - self.assertEqual(brev64(1), 1 << 63) - self.assertEqual(brev64(0xFFFFFFFF), 0xFFFFFFFF00000000) - self.assertEqual(brev64(brev64(0x0123456789ABCDEF)), 0x0123456789ABCDEF) - - def test_values_and_scc_kept(self): - for x in VALUES: - for scc_in in (0, 1): - with self.subTest(x=hex(x), scc=scc_in): - self.assertEqual(run_op(x, scc_in), (brev64(x), scc_in)) - - def test_seeded(self): - rng = random.Random(0xB64) - for _ in range(20): - x = rng.getrandbits(64) - with self.subTest(x=hex(x)): - self.assertEqual(run_op(x, 0)[0], brev64(x)) - - def test_inline_constant_source(self): - # -1 as a 64-bit inline constant is all ones; 1 reverses to bit 63. - self.assertEqual(run_lines(["s_brev_b64 s[0:1], -1"])[0], M64) - self.assertEqual(run_lines(["s_brev_b64 s[0:1], 1"])[0], 1 << 63) - - def test_lane_mask_source_is_rejected(self): - with self.assertRaises(rdna2spirv.Unsupported): - run_lines(["s_brev_b64 s[0:1], exec"]) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_salu_chained_const_prop.py b/tests/semantic/test_salu_chained_const_prop.py deleted file mode 100644 index b800d2e4a..000000000 --- a/tests/semantic/test_salu_chained_const_prop.py +++ /dev/null @@ -1,258 +0,0 @@ -from __future__ import annotations - -"""Semantic and regression tests for chained scalar ALU constant propagation in the translator. - -Verifies: -- Multi-step chained constant propagation across SGPRs (s_mov_b32 -> s_lshl_b32 -> s_add_u32). -- s_add_u32 and s_sub_u32 constant tracking in sgpr_imm. -- s_lshl{1..4}_add_u32 constant tracking in sgpr_imm. -- s_bfe_u32 and s_bfe_i32 constant folding and static operand emission. -- s_min/max_u32 and s_min/max_i32 constant tracking in sgpr_imm. -- s_andn2, s_orn2, s_nand, s_nor, s_xnor bitwise logic constant tracking in sgpr_imm. -- s_abs_i32, s_absdiff_i32, s_sext_i32_i8/i16 constant tracking in sgpr_imm. -- s_pack_*_b32_b16 and s_bfm_b32 constant tracking in sgpr_imm. -- s_buffer_load offset computed through chained SALU folds into a static load without branch diamonds, and the - load reads the word at the folded offset. -- v_bfe constant folding. -""" - -import os -import struct -import sys -import tempfile -import unittest -import warnings - -HERE = os.path.dirname(os.path.abspath(__file__)) -ROOT = os.path.dirname(os.path.dirname(HERE)) -TOOLS_DIR = os.environ.get("LEONIDA_TOOLS_DIR") or os.path.join(ROOT, "tools") - -sys.dont_write_bytecode = True -if TOOLS_DIR not in sys.path: - sys.path.insert(0, TOOLS_DIR) -if HERE not in sys.path: - sys.path.insert(0, HERE) - -import rdna2spirv # noqa: E402 -import support # noqa: E402 - -STUB_DXBC = b"DXBC" + bytes(24) + struct.pack(" str: - body = "\n".join("\t" + line for line in lines) - asm = f"; chained_salu_test\n{body}\n\texp mrt0 v0, v0, v0, v0 done vm\n\ts_endpgm\n" - with tempfile.TemporaryDirectory() as tmp: - d_dir = os.path.join(tmp, "disasm") - os.mkdir(d_dir) - s_path = os.path.join(d_dir, "ps_chained.s") - with open(s_path, "w", encoding="utf-8") as f: - f.write(asm) - with open(os.path.join(tmp, "ps_chained.dxbc"), "wb") as f: - f.write(STUB_DXBC) - with warnings.catch_warnings(): - warnings.simplefilter("ignore", ResourceWarning) - return rdna2spirv.translate(s_path) - - def assert_loads_offset(self, spv: str, offset: int) -> None: - # Each buffer word holds 0xA000 + its byte offset, so a wrong fold that stays in bounds still reads the wrong - # word. SMEM ignores the low two offset bits. - memory = {off: 0xA000 + off for off in range(0, 4096, 4)} - self.assertEqual(support.mrt0_words(spv, memory=memory)[0], 0xA000 + (offset & ~3)) - - def test_chained_propagation_and_folding(self): - # s_mov_b32 -> s_lshl_b32 -> s_add_u32 -> s_buffer_load_dword chains completely into static load - lines = [ - "s_mov_b32 s1, 0", # stride 0 - "s_mov_b32 s2, 2048", # NUM_RECORDS 2048 bytes - "s_mov_b32 s4, 0x100", - "s_lshl_b32 s5, s4, 2", # folds to 0x400 (1024) and records in sgpr_imm - "s_add_u32 s6, s5, 0x20", # computes 0x420 (1056) and records in sgpr_imm - "s_buffer_load_dword s8, s[0:3], s6", - "v_mov_b32 v0, s8", - ] - spv = self.translate_lines(lines) - # s_lshl_b32 folded completely without runtime shift on uint - self.assertNotIn("OpShiftLeftLogical %uint", spv) - # s_buffer_load evaluated offset 1056 <= 2048 statically: no branch diamond - self.assertNotIn("OpSelectionMerge", spv) - self.assertNotIn("OpBranchConditional", spv) - self.assertNotIn("OpPhi", spv) - self.assert_loads_offset(spv, 1056) - self.assertIn("OpLoad %uint", spv) - - def test_s_add_u32_and_s_sub_u32_folding(self): - # Chained addition into buffer offset: 16 + 32 = 48 - lines_add = [ - "s_mov_b32 s1, 0", - "s_mov_b32 s2, 256", - "s_mov_b32 s4, 16", - "s_add_u32 s5, s4, 32", - "s_buffer_load_dword s8, s[0:3], s5", - "v_mov_b32 v0, s8", - ] - spv_add = self.translate_lines(lines_add) - self.assertNotIn("OpSelectionMerge", spv_add) - self.assertNotIn("OpBranchConditional", spv_add) - self.assertNotIn("OpPhi", spv_add) - self.assert_loads_offset(spv_add, 48) - - # Chained subtraction into buffer offset: 80 - 16 = 64 - lines_sub = [ - "s_mov_b32 s1, 0", - "s_mov_b32 s2, 256", - "s_mov_b32 s4, 80", - "s_sub_u32 s5, s4, 16", - "s_buffer_load_dword s8, s[0:3], s5", - "v_mov_b32 v0, s8", - ] - spv_sub = self.translate_lines(lines_sub) - self.assertNotIn("OpSelectionMerge", spv_sub) - self.assertNotIn("OpBranchConditional", spv_sub) - self.assertNotIn("OpPhi", spv_sub) - self.assert_loads_offset(spv_sub, 64) - - def test_s_lshl_add_u32_folding(self): - # D = (S0 << N) + S1. (0x10 << 2) + 0x5 = 0x45 (69) - lines = [ - "s_mov_b32 s1, 0", - "s_mov_b32 s2, 256", - "s_mov_b32 s4, 0x10", - "s_lshl2_add_u32 s5, s4, 0x5", - "s_buffer_load_dword s8, s[0:3], s5", - "v_mov_b32 v0, s8", - ] - spv = self.translate_lines(lines) - self.assertNotIn("OpSelectionMerge", spv) - self.assertNotIn("OpBranchConditional", spv) - self.assertNotIn("OpPhi", spv) - self.assert_loads_offset(spv, 69) - self.assertIn("OpLoad %uint", spv) - - def test_s_bfe_u32_and_i32_constant_folding(self): - # Extract bits 4..11 (width 8, offset 4): 0x00080004 - # Input 0xAB40 >> 4 = 0xAB4 & 0xFF = 0xB4 = 180 - lines = [ - "s_mov_b32 s4, 0xAB40", - "s_bfe_u32 s5, s4, 0x00080004", - "v_mov_b32 v0, s5", - ] - spv = self.translate_lines(lines) - self.assertNotIn("OpBitFieldUExtract", spv) - self.assertIn("180", spv) - - def test_s_bfe_constant_control_dynamic_data(self): - # Control is constant (0x00080004), data is dynamic VGPR - lines = [ - "s_bfe_u32 s5, s1, 0x00080004", - "v_mov_b32 v0, s5", - ] - spv = self.translate_lines(lines) - # Should NOT emit dynamic width/offset calculation instructions - self.assertNotIn("OpULessThan", spv) - self.assertNotIn("OpISub", spv) - # Emits direct OpBitFieldUExtract with constant operands - self.assertIn("OpBitFieldUExtract", spv) - - def test_s_min_max_u32_and_i32_folding(self): - # Chained min into buffer offset: min(64, 128) = 64 - lines = [ - "s_mov_b32 s1, 0", - "s_mov_b32 s2, 256", - "s_mov_b32 s4, 64", - "s_min_u32 s5, s4, 128", - "s_buffer_load_dword s8, s[0:3], s5", - "v_mov_b32 v0, s8", - ] - spv = self.translate_lines(lines) - self.assertNotIn("OpSelectionMerge", spv) - self.assertNotIn("OpBranchConditional", spv) - self.assertNotIn("OpPhi", spv) - self.assert_loads_offset(spv, 64) - - def test_s_andn2_orn2_nand_nor_xnor_folding(self): - # Chained bitwise into buffer offset: 0xFF & ~0xBF = 0x40 (64) - lines = [ - "s_mov_b32 s1, 0", - "s_mov_b32 s2, 256", - "s_mov_b32 s4, 0xFF", - "s_andn2_b32 s5, s4, 0xBF", - "s_buffer_load_dword s8, s[0:3], s5", - "v_mov_b32 v0, s8", - ] - spv = self.translate_lines(lines) - self.assertNotIn("OpSelectionMerge", spv) - self.assertNotIn("OpBranchConditional", spv) - self.assertNotIn("OpPhi", spv) - self.assert_loads_offset(spv, 64) - - def test_s_abs_and_absdiff_and_sext_folding(self): - # Chained absdiff into buffer offset: |10 - 74| = 64 - lines = [ - "s_mov_b32 s1, 0", - "s_mov_b32 s2, 256", - "s_mov_b32 s4, 10", - "s_absdiff_i32 s5, s4, 74", - "s_buffer_load_dword s8, s[0:3], s5", - "v_mov_b32 v0, s8", - ] - spv = self.translate_lines(lines) - self.assertNotIn("OpSelectionMerge", spv) - self.assertNotIn("OpBranchConditional", spv) - self.assertNotIn("OpPhi", spv) - self.assert_loads_offset(spv, 64) - - def test_s_pack_and_bfm_folding(self): - # Chained bfm into buffer offset: ((1 << 4) - 1) << 2 = 15 << 2 = 60 - lines = [ - "s_mov_b32 s1, 0", - "s_mov_b32 s2, 256", - "s_mov_b32 s4, 4", - "s_bfm_b32 s5, s4, 2", - "s_buffer_load_dword s8, s[0:3], s5", - "v_mov_b32 v0, s8", - ] - spv = self.translate_lines(lines) - self.assertNotIn("OpSelectionMerge", spv) - self.assertNotIn("OpBranchConditional", spv) - self.assertNotIn("OpPhi", spv) - self.assert_loads_offset(spv, 60) - - def test_s_buffer_load_chained_offset_folding(self): - # Compute buffer offset through chained SALU: - # s4 = 16 - # s5 = s4 << 2 = 64 - # s6 = s5 + 32 = 96 - # s_buffer_load_dword through s[0:3] with descriptor limit 256. Offset 96 + 4 <= 256 is in bounds. - # Should fold offset to 96 and emit straight-line OpLoad without dynamic bounds check diamond. - lines = [ - "s_mov_b32 s1, 0", # descriptor word 1: stride 0 - "s_mov_b32 s2, 256", # descriptor word 2: NUM_RECORDS 256 bytes - "s_mov_b32 s4, 16", - "s_lshl_b32 s5, s4, 2", - "s_add_u32 s6, s5, 32", - "s_buffer_load_dword s8, s[0:3], s6", - "v_mov_b32 v0, s8", - ] - spv = self.translate_lines(lines) - # Static straight-line load: no OpSelectionMerge, OpBranchConditional, or OpPhi - self.assertNotIn("OpSelectionMerge", spv) - self.assertNotIn("OpBranchConditional", spv) - self.assertNotIn("OpPhi", spv) - self.assert_loads_offset(spv, 96) - # OpLoad is emitted directly - self.assertIn("OpLoad %uint", spv) - - def test_v_bfe_constant_folding(self): - # v_bfe_u32 with all constant operands folds to constant - lines = [ - "v_bfe_u32 v0, 0x1234, 4, 8", # (0x1234 >> 4) & 0xFF = 0x23 = 35 - ] - spv = self.translate_lines(lines) - self.assertNotIn("OpBitFieldUExtract", spv) - self.assertIn("35", spv) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_salu_cmov.py b/tests/semantic/test_salu_cmov.py deleted file mode 100644 index e67ccacbb..000000000 --- a/tests/semantic/test_salu_cmov.py +++ /dev/null @@ -1,109 +0,0 @@ -"""Semantic interpreter tests for RDNA2 s_cmov_b32 and s_cmovk_i32. - -s_cmov_b32: D = SCC ? S0 : D. s_cmovk_i32: D = SCC ? sign_extend(simm16) : D. Both read SCC and leave it unchanged. -Each case translates a synthetic pixel shader with tools/rdna2spirv.py, runs it in tests/semantic/spirv_mini_interp.py -and compares the result with a plain-Python reference. D leaves through exp as two 16-bit halves ORed into -0x40000000, so no export channel is a NaN or denormal pattern that a float round trip could change; SCC comes back -through s_cselect_b32. -""" -import os -import struct -import sys -import tempfile -import unittest -import warnings - -HERE = os.path.dirname(os.path.abspath(__file__)) -ROOT = os.path.dirname(os.path.dirname(HERE)) -TOOLS_DIR = os.environ.get("LEONIDA_TOOLS_DIR") or os.path.join(ROOT, "tools") - -sys.dont_write_bytecode = True -sys.path.insert(0, TOOLS_DIR) -sys.path.insert(0, HERE) - -import rdna2spirv # noqa: E402 -import spirv_mini_interp as si # noqa: E402 - -M32 = 0xFFFFFFFF -STUB_DXBC = b"DXBC" + bytes(24) + struct.pack(" int: - v &= 0xFFFF - return (v - 0x10000 if v & 0x8000 else v) & M32 - - -_TMP_DIR = None -_SRC_PATH = None - - -def setUpModule(): - global _TMP_DIR, _SRC_PATH - _TMP_DIR = tempfile.TemporaryDirectory() - disasm_dir = os.path.join(_TMP_DIR.name, "disasm") - os.mkdir(disasm_dir) - _SRC_PATH = os.path.join(disasm_dir, "ps_salu_cmov.s") - with open(os.path.join(_TMP_DIR.name, "ps_salu_cmov.dxbc"), "wb") as f: - f.write(STUB_DXBC) - - -def tearDownModule(): - global _TMP_DIR - if _TMP_DIR is not None: - _TMP_DIR.cleanup() - _TMP_DIR = None - - -def run_op(line: str, x: int, scc_in: int) -> tuple: - """s0 = OLD, s2 = x, SCC = scc_in, then ``line``; return (s0, SCC after).""" - if _TMP_DIR is None: - setUpModule() - lines = [f"s_mov_b32 s0, {OLD:#x}", f"s_mov_b32 s2, {x:#x}", f"s_mov_b32 s4, {scc_in}", "s_cmp_eq_u32 s4, 1", line, - "s_cselect_b32 s1, 0x40000001, 0x40000000", "s_and_b32 s5, s0, 0xffff", "s_lshr_b32 s6, s0, 16", - "s_or_b32 s5, s5, 0x40000000", "s_or_b32 s6, s6, 0x40000000", - "v_mov_b32 v0, s5", "v_mov_b32 v1, s6", "v_mov_b32 v2, s1"] - asm = "; test_salu_cmov\n" + "".join(f"\t{ln}\n" for ln in lines) + "\texp mrt0 v0, v1, v2, v2 done vm\n\ts_endpgm\n" - with open(_SRC_PATH, "w", encoding="utf-8") as f: - f.write(asm) - with warnings.catch_warnings(): - warnings.simplefilter("ignore", ResourceWarning) - spv = rdna2spirv.translate(_SRC_PATH) - lo, hi, scc = si.run_fragment(spv)["%out_mrt0"][:3] - assert lo >> 16 == hi >> 16 == 0x4000 and scc >> 1 == 0x20000000, (hex(lo), hex(hi), hex(scc)) - return (lo & 0xFFFF) | (hi & 0xFFFF) << 16, scc & 1 - - -class CmovTests(unittest.TestCase): - def test_reference(self): - self.assertEqual(sext16(0x8000), 0xFFFF8000) - self.assertEqual(sext16(0x7FFF), 0x7FFF) - - def test_s_cmov_b32(self): - for x in VALUES: - for scc_in in (0, 1): - with self.subTest(x=hex(x), scc=scc_in): - self.assertEqual(run_op("s_cmov_b32 s0, s2", x, scc_in), (x if scc_in else OLD, scc_in)) - - def test_s_cmov_b32_constant_source(self): - self.assertEqual(run_op("s_cmov_b32 s0, -1", 0, 1), (M32, 1)) - self.assertEqual(run_op("s_cmov_b32 s0, 0x12345678", 0, 0), (OLD, 0)) - - def test_s_cmovk_i32(self): - for k in SIMM16: - for scc_in in (0, 1): - with self.subTest(k=hex(k), scc=scc_in): - self.assertEqual(run_op(f"s_cmovk_i32 s0, {k:#x}", 0, scc_in), (sext16(k) if scc_in else OLD, scc_in)) - - def test_scc_from_a_compare(self): - # The usual shape: a compare sets SCC, then the move depends on it. - for x, moved in ((9, True), (5, False)): - with self.subTest(x=x): - got = run_op("s_cmp_gt_u32 s2, 5\n\ts_cmovk_i32 s0, 7", x, 0) - self.assertEqual(got, (7 if moved else OLD, int(moved))) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_salu_cmov_b64.py b/tests/semantic/test_salu_cmov_b64.py deleted file mode 100644 index e46686c45..000000000 --- a/tests/semantic/test_salu_cmov_b64.py +++ /dev/null @@ -1,579 +0,0 @@ -from __future__ import annotations - -"""Semantic tests for RDNA2 s_cmov_b64 and s_cselect_b64 on 64-bit scalar *data* pairs. - -Rule (s_cmov_b64): D[63:0] = SCC ? S0[63:0] : D[63:0]; SCC read, not written (RDNA2 ISA SOP1). -Rule (s_cselect_b64): D[63:0] = SCC ? S0[63:0] : S1[63:0]; SCC read, not written (RDNA2 ISA SOP2). - -Only plain data is supported. A lane-mask register holds one lane's bit in this -translator, so selecting it as 64-bit data would silently read back a per-lane -bool instead of the wave's mask (issue #210). Those operands stay rejected. - -Every program here is hand-written; the translator and mini interpreter from -this repository do the work. No LLVM, SPIR-V tools, GPU or game files are used. - -Run directly: - python -I tests/semantic/test_salu_cmov_b64.py -v -""" -import os -import re -import sys -import tempfile -import unittest -import warnings - -HERE = os.path.dirname(os.path.abspath(__file__)) -if HERE not in sys.path: - sys.path.insert(0, HERE) - -from support import STUB_DXBC, mrt0_words, rdna2spirv # noqa: E402 - -MASK32 = 0xFFFFFFFF -MASK64 = 0xFFFFFFFFFFFFFFFF - -_TMP_DIR = None -_PS_PATH = None - - -def setUpModule(): - global _TMP_DIR, _PS_PATH - _TMP_DIR = tempfile.TemporaryDirectory() - dis = os.path.join(_TMP_DIR.name, "disasm") - os.mkdir(dis) - _PS_PATH = os.path.join(dis, "ps_cmov64.s") - with open(os.path.join(_TMP_DIR.name, "ps_cmov64.dxbc"), "wb") as f: - f.write(STUB_DXBC) - - -def tearDownModule(): - global _TMP_DIR - if _TMP_DIR is not None: - _TMP_DIR.cleanup() - _TMP_DIR = None - - -def translate_ps(lines): - if _TMP_DIR is None: - setUpModule() - asm = "; ps_cmov64\n" + "".join(f"\t{ln}\n" for ln in lines) - with open(_PS_PATH, "w", encoding="utf-8", newline="") as f: - f.write(asm) - with warnings.catch_warnings(): - warnings.simplefilter("ignore", ResourceWarning) - return rdna2spirv.translate(_PS_PATH) - - -def run_ps(lines): - spv = translate_ps(lines + ["exp mrt0 v0, v1, v2, v3 done vm", "s_endpgm"]) - return mrt0_words(spv) - - -def scc_line(scc): - return "s_cmp_eq_u32 1, 1" if scc else "s_cmp_eq_u32 0, 1" - - -def load_pair_lines(reg, val64): - return [f"s_mov_b32 s{reg}, {val64 & MASK32:#x}", - f"s_mov_b32 s{reg + 1}, {(val64 >> 32) & MASK32:#x}"] - - -def export_pair_lines(reg): - return [f"v_mov_b32 v0, s{reg}", f"v_mov_b32 v1, s{reg + 1}"] - - -def ref_cmov64(old, src, scc): - return (src if scc else old) & MASK64 - - -def ref_cselect_b64(s0: int, s1: int, scc: int) -> int: - """Reference oracle for RDNA2 s_cselect_b64: D = SCC ? S0 : S1 (64-bit scalar data).""" - return (s0 if scc else s1) & MASK64 - - -class DataPairTests(unittest.TestCase): - def test_plain_data_pair_is_accepted(self): - # The explicit non-mask case: both dwords come from plain immediate moves, - # not from EXEC, VCC or a compare. D is an ordinary SGPR data pair. - old = 0xDEADBEEF_11223344 - src = 0x55667788_90ABCDEF - for scc in (0, 1): - with self.subTest(scc=scc): - want = ref_cmov64(old, src, scc) - words = run_ps( - load_pair_lines(2, old) - + load_pair_lines(4, src) - + [scc_line(scc), "s_cmov_b64 s[2:3], s[4:5]", - "s_cselect_b32 s10, 1, 0"] - + export_pair_lines(2) - + ["v_mov_b32 v2, s10", "v_mov_b32 v3, 0"] - ) - self.assertEqual(words, [want & MASK32, want >> 32, scc, 0]) - - def test_edge_values(self): - pairs = [ - (0, 0xFFFFFFFF_FFFFFFFF), - (0x00000001_00000000, 0x80000000_7FFFFFFF), - (0x7FFFFFFF_FFFFFFFF, 0x80000000_00000000), - (0x00000002_80000001, 0x00000002_80000002), - ] - for old, src in pairs: - for scc in (0, 1): - with self.subTest(old=hex(old), src=hex(src), scc=scc): - want = ref_cmov64(old, src, scc) - words = run_ps( - load_pair_lines(2, old) - + load_pair_lines(4, src) - + [scc_line(scc), "s_cmov_b64 s[2:3], s[4:5]"] - + export_pair_lines(2) - + ["v_mov_b32 v2, 0", "v_mov_b32 v3, 0"] - ) - self.assertEqual(words, [want & MASK32, want >> 32, 0, 0]) - - def test_immediate_and_null_sources(self): - old = 0x55667788_11223344 - # shader_ir leaves a literal wider than 32 bits as a raw operand, which - # src64_data does not accept (the same holds for s_mov_b64); use the - # immediate forms the parser actually delivers. - for src_asm, src in (("0x12345678", 0x12345678), ("42", 42), - ("0", 0), ("-1", MASK64), ("-2", MASK64 - 1), ("null", 0)): - for scc in (0, 1): - with self.subTest(src=src_asm, scc=scc): - want = ref_cmov64(old, src, scc) - words = run_ps( - load_pair_lines(2, old) - + [scc_line(scc), f"s_cmov_b64 s[2:3], {src_asm}"] - + export_pair_lines(2) - + ["v_mov_b32 v2, 0", "v_mov_b32 v3, 0"] - ) - self.assertEqual(words, [want & MASK32, want >> 32, 0, 0]) - - def test_destination_aliasing(self): - a64 = 0x55667788_11223344 - b64 = 0xDDEEFF00_99AABBCC - # s[3:4] = (s4 << 32) | s3, with s4 = low(a64), s3 = low(b64). - overlap_val = ((a64 & MASK32) << 32) | (b64 & MASK32) - for source, src_val in (("s[4:5]", a64), ("s[3:4]", overlap_val)): - for scc in (0, 1): - with self.subTest(source=source, scc=scc): - want = ref_cmov64(a64, src_val, scc) - lines = load_pair_lines(3, b64) + load_pair_lines(4, a64) - lines += [scc_line(scc), f"s_cmov_b64 s[4:5], {source}"] - lines += export_pair_lines(4) + ["v_mov_b32 v2, 0", "v_mov_b32 v3, 0"] - words = run_ps(lines) - self.assertEqual(words, [want & MASK32, want >> 32, 0, 0]) - - def test_constant_pairs_are_not_mistaken_for_masks(self): - # 0 / -1 are EITHER in tools/lane_masks.py (the same bits as data), so - # they must not be mistaken for lane masks here. - for src_asm, src in (("-1", MASK64), ("0", 0)): - for scc in (0, 1): - with self.subTest(src=src_asm, scc=scc): - want = ref_cmov64(0x11223344_55667788, src, scc) - words = run_ps( - load_pair_lines(2, 0x11223344_55667788) - + [f"s_mov_b64 s[4:5], {src_asm}", scc_line(scc), - "s_cmov_b64 s[2:3], s[4:5]"] - + export_pair_lines(2) - + ["v_mov_b32 v2, 0", "v_mov_b32 v3, 0"] - ) - self.assertEqual(words, [want & MASK32, want >> 32, 0, 0]) - - def test_scc_is_not_written(self): - old, src = 0x11111111_22222222, 0x33333333_44444444 - for scc in (0, 1): - with self.subTest(scc=scc): - want = ref_cmov64(old, src, scc) - words = run_ps( - load_pair_lines(2, old) - + load_pair_lines(4, src) - + [scc_line(scc), "s_cmov_b64 s[2:3], s[4:5]", - "s_addc_u32 s10, 10, 20"] - + export_pair_lines(2) - + ["v_mov_b32 v2, s10", "v_mov_b32 v3, 0"] - ) - self.assertEqual(words, [want & MASK32, want >> 32, 30 + scc, 0]) - - -class RejectionTests(unittest.TestCase): - MASK_SOURCE = "s_cmov_b64 lane-mask source" - MASK_DEST = "s_cmov_b64 lane-mask destination" - DEST = "s_cmov_b64 destination" - - def test_lane_mask_source_rejected_with_message(self): - cmp = "v_cmp_ne_u32_e64 s[20:21], 0, v0" - cases = [ - ([cmp, "s_mov_b64 s[22:23], s[20:21]"], "s[22:23]"), - (["s_mov_b64 s[22:23], exec"], "s[22:23]"), - ([], "exec"), - # A zero-extended 32-bit mask: one dword is a mask, the other is - # an EITHER constant. holds_lane_mask() alone misses this pair. - ([cmp, "s_mov_b32 s2, s20", "s_mov_b32 s3, 0"], "s[2:3]"), - ([cmp, "s_mov_b32 s2, 0", "s_mov_b32 s3, s20"], "s[2:3]"), - ] - for prologue, src in cases: - with self.subTest(src=src, prologue=prologue[-1] if prologue else "none"): - lines = prologue + [scc_line(1), f"s_cmov_b64 s[2:3], {src}", - "exp mrt0 v0, v0, v0, v0 done vm", "s_endpgm"] - with self.assertRaisesRegex(rdna2spirv.Unsupported, re.escape(self.MASK_SOURCE)): - translate_ps(lines) - - def test_mask_destination_rejected_with_message(self): - cmp = "v_cmp_ne_u32_e64 s[20:21], 0, v0" - cases = [ - [cmp, "s_cmov_b64 s[20:21], s[4:5]"], - [cmp, "s_mov_b32 s2, s20", "s_mov_b32 s3, 0", "s_cmov_b64 s[2:3], s[4:5]"], - ] - for lines in cases: - with self.subTest(lines=lines[-1]): - full = lines + ["exp mrt0 v0, v0, v0, v0 done vm", "s_endpgm"] - with self.assertRaisesRegex(rdna2spirv.Unsupported, re.escape(self.MASK_DEST)): - translate_ps(full) - - def test_ever_mask_pair_rejected_after_overwrite(self): - # A register that held a mask earlier, then plain data, is refused: at a - # CFG join lane_masks.py can drop the register (mask on one path, data on - # another), so "not a mask now" does not prove it is data on every path. - lines = ["v_cmp_ne_u32_e64 s[20:21], 0, v0", - "s_mov_b64 s[20:21], 0", "s_mov_b64 s[2:3], 0", - "s_cmov_b64 s[2:3], s[20:21]", - "exp mrt0 v0, v0, v0, v0 done vm", "s_endpgm"] - with self.assertRaisesRegex(rdna2spirv.Unsupported, re.escape(self.MASK_SOURCE)): - translate_ps(lines) - - def test_invalid_destinations_rejected_with_message(self): - for line in ("s_cmov_b64 exec, s[4:5]", "s_cmov_b64 vcc, s[4:5]", - "s_cmov_b64 m0, s[4:5]", "s_cmov_b64 s4, s[4:5]", - "s_cmov_b64 null, s[4:5]"): - with self.subTest(line=line): - full = [line, "exp mrt0 v0, v0, v0, v0 done vm", "s_endpgm"] - with self.assertRaisesRegex(rdna2spirv.Unsupported, re.escape(self.DEST)): - translate_ps(full) - - -class ScalarCselectB64OracleTests(unittest.TestCase): - def test_distinct_dword_data_pairs(self): - pairs = [ - (0x55667788_11223344, 0xDDEEFF00_99AABBCC), - (0x12345678_9ABCDEF0, 0xFEDCBA98_76543210), - (0x00000002_80000001, 0x80000000_7FFFFFFE), - (0x01020304_05060708, 0x11223344_55667788), - ] - for a64, b64 in pairs: - for scc in (0, 1): - with self.subTest(a=hex(a64), b=hex(b64), scc=scc): - want = ref_cselect_b64(a64, b64, scc) - words = run_ps( - load_pair_lines(4, a64) - + load_pair_lines(6, b64) - + [scc_line(scc), "s_cselect_b64 s[2:3], s[4:5], s[6:7]"] - + export_pair_lines(2) - + ["v_mov_b32 v2, 0", "v_mov_b32 v3, 0"] - ) - self.assertEqual(words[:2], [want & MASK32, (want >> 32) & MASK32]) - - def test_edge_and_boundary_patterns(self): - patterns = [ - (0, 0xFFFFFFFF_FFFFFFFF), - (0xFFFFFFFF_FFFFFFFF, 0), - (0x80000000_00000000, 0x7FFFFFFF_FFFFFFFF), - (0x00000000_00000001, 0x80000000_00000000), - (0xAAAAAAAAAAAAAAAA, 0x5555555555555555), - (0x00000000_FFFFFFFF, 0xFFFFFFFF_00000000), - ] - for a64, b64 in patterns: - for scc in (0, 1): - with self.subTest(a=hex(a64), b=hex(b64), scc=scc): - want = ref_cselect_b64(a64, b64, scc) - words = run_ps( - load_pair_lines(4, a64) - + load_pair_lines(6, b64) - + [scc_line(scc), "s_cselect_b64 s[2:3], s[4:5], s[6:7]"] - + export_pair_lines(2) - + ["v_mov_b32 v2, 0", "v_mov_b32 v3, 0"] - ) - self.assertEqual(words[:2], [want & MASK32, (want >> 32) & MASK32]) - - def test_immediate_operand_forms(self): - cases = [ - ("42", "-2", 42, 0xFFFFFFFF_FFFFFFFE), - ("0x10", "0x80000000", 0x10, 0x00000000_80000000), - ("-16", "64", 0xFFFFFFFF_FFFFFFF0, 64), - ("0x12345678", "0", 0x12345678, 0), - ("0", "-1", 0, 0xFFFFFFFF_FFFFFFFF), - ("-1", "0", 0xFFFFFFFF_FFFFFFFF, 0), - ("null", "0x55", 0, 0x55), - ("0xAA", "null", 0xAA, 0), - ] - for s0_asm, s1_asm, s0_val, s1_val in cases: - for scc in (0, 1): - with self.subTest(s0=s0_asm, s1=s1_asm, scc=scc): - want = ref_cselect_b64(s0_val, s1_val, scc) - words = run_ps( - [scc_line(scc), f"s_cselect_b64 s[2:3], {s0_asm}, {s1_asm}"] - + export_pair_lines(2) - + ["v_mov_b32 v2, 0", "v_mov_b32 v3, 0"] - ) - self.assertEqual(words[:2], [want & MASK32, (want >> 32) & MASK32]) - - def test_oracle_dwords_fidelity(self): - a64 = 0xBBBBBBBB_AAAAAAAA - b64 = 0xDDDDDDDD_CCCCCCCC - for scc in (0, 1): - with self.subTest(scc=scc): - want = ref_cselect_b64(a64, b64, scc) - words = run_ps( - load_pair_lines(4, a64) - + load_pair_lines(6, b64) - + [scc_line(scc), "s_cselect_b64 s[2:3], s[4:5], s[6:7]"] - + export_pair_lines(2) - + ["v_mov_b32 v2, 0", "v_mov_b32 v3, 0"] - ) - self.assertEqual(words[0], want & MASK32) - self.assertEqual(words[1], (want >> 32) & MASK32) - - -class ScalarCselectB64RoutingTests(unittest.TestCase): - def test_scc_generation_and_dependency(self): - # Verify SCC dependency when SCC is produced by different compare and arithmetic instructions. - a64 = 0x11111111_22222222 - b64 = 0x33333333_44444444 - cases = [ - ("s_cmp_eq_u32 7, 7", 1), - ("s_cmp_eq_u32 7, 8", 0), - ("s_cmp_lg_u32 10, 20", 1), - ("s_cmp_lg_u32 10, 10", 0), - ("s_cmp_gt_i32 5, -1", 1), - ("s_cmp_gt_i32 -5, 1", 0), - ("s_cmp_lt_u32 1, 100", 1), - ("s_cmp_lt_u32 100, 1", 0), - ("s_add_u32 s10, 0xFFFFFFFF, 1", 1), - ("s_add_u32 s10, 10, 20", 0), - ] - for scc_inst, expected_scc in cases: - with self.subTest(inst=scc_inst, expected_scc=expected_scc): - want = ref_cselect_b64(a64, b64, expected_scc) - words = run_ps( - load_pair_lines(4, a64) - + load_pair_lines(6, b64) - + [scc_inst, "s_cselect_b64 s[2:3], s[4:5], s[6:7]"] - + export_pair_lines(2) - + ["v_mov_b32 v2, 0", "v_mov_b32 v3, 0"] - ) - self.assertEqual(words[:2], [want & MASK32, (want >> 32) & MASK32]) - - def test_scc_preservation_and_chaining(self): - # s_cselect_b64 must not modify SCC. Verify by chaining multiple s_cselect_b64 ops - # followed by s_addc_u32 and s_cselect_b32 which consume SCC. - p1_a, p1_b = 0x01020304_05060708, 0x11121314_15161718 - p2_a, p2_b = 0x21222324_25262728, 0x31323334_35363738 - for scc in (0, 1): - with self.subTest(scc=scc): - want1 = ref_cselect_b64(p1_a, p1_b, scc) - want2 = ref_cselect_b64(p2_a, p2_b, scc) - words = run_ps( - load_pair_lines(4, p1_a) - + load_pair_lines(6, p1_b) - + load_pair_lines(8, p2_a) - + load_pair_lines(10, p2_b) - + [ - scc_line(scc), - "s_cselect_b64 s[2:3], s[4:5], s[6:7]", - "s_cselect_b64 s[12:13], s[8:9], s[10:11]", - "s_cselect_b32 s15, 1, 0", - "s_addc_u32 s14, 100, 200", - "v_mov_b32 v0, s2", - "v_mov_b32 v1, s12", - "v_mov_b32 v2, s14", - "v_mov_b32 v3, s15", - ] - ) - self.assertEqual(words[0], want1 & MASK32) - self.assertEqual(words[1], want2 & MASK32) - self.assertEqual(words[2], 300 + scc) - self.assertEqual(words[3], scc) - - def test_sgpr_pair_routing_layouts(self): - # Test routing between diverse register allocations and non-sequential pair positions. - a64 = 0xCAFEFEED_12345678 - b64 = 0xDEADBEEF_87654321 - routings = [ - (2, 4, 6), - (8, 12, 16), - (20, 24, 28), - (14, 6, 22), - (28, 2, 10), - (4, 18, 8), - ] - for dst, s0, s1 in routings: - for scc in (0, 1): - with self.subTest(dst=dst, s0=s0, s1=s1, scc=scc): - want = ref_cselect_b64(a64, b64, scc) - words = run_ps( - load_pair_lines(s0, a64) - + load_pair_lines(s1, b64) - + [scc_line(scc), f"s_cselect_b64 s[{dst}:{dst + 1}], s[{s0}:{s0 + 1}], s[{s1}:{s1 + 1}]"] - + export_pair_lines(dst) - + ["v_mov_b32 v2, 0", "v_mov_b32 v3, 0"] - ) - self.assertEqual(words[:2], [want & MASK32, (want >> 32) & MASK32]) - - def test_sgpr_pair_and_immediate_mixed_routing(self): - # Test routing when one operand is an SGPR pair and the other is an immediate constant. - val64 = 0x01234567_89ABCDEF - immediates = [ - ("0", 0), - ("-1", MASK64), - ("42", 42), - ("0x12345678", 0x12345678), - ("-2", MASK64 - 1), - ] - for imm_asm, imm_val in immediates: - for sgpr_first in (True, False): - for scc in (0, 1): - s0_asm, s1_asm = ("s[4:5]", imm_asm) if sgpr_first else (imm_asm, "s[4:5]") - s0_val, s1_val = (val64, imm_val) if sgpr_first else (imm_val, val64) - with self.subTest(s0=s0_asm, s1=s1_asm, scc=scc): - want = ref_cselect_b64(s0_val, s1_val, scc) - words = run_ps( - load_pair_lines(4, val64) - + [scc_line(scc), f"s_cselect_b64 s[2:3], {s0_asm}, {s1_asm}"] - + export_pair_lines(2) - + ["v_mov_b32 v2, 0", "v_mov_b32 v3, 0"] - ) - self.assertEqual(words[:2], [want & MASK32, (want >> 32) & MASK32]) - - def test_bidirectional_operand_swap_routing(self): - # Swapping operand positions between two register pairs routes opposing values. - pair_a = 0xAAAA0000_11112222 - pair_b = 0xBBBB0000_33334444 - for scc in (0, 1): - with self.subTest(scc=scc): - want_fwd = ref_cselect_b64(pair_a, pair_b, scc) - want_rev = ref_cselect_b64(pair_b, pair_a, scc) - words = run_ps( - load_pair_lines(4, pair_a) - + load_pair_lines(6, pair_b) - + [ - scc_line(scc), - "s_cselect_b64 s[2:3], s[4:5], s[6:7]", - "s_cselect_b64 s[8:9], s[6:7], s[4:5]", - "v_mov_b32 v0, s2", - "v_mov_b32 v1, s3", - "v_mov_b32 v2, s8", - "v_mov_b32 v3, s9", - ] - ) - self.assertEqual(words[:2], [want_fwd & MASK32, (want_fwd >> 32) & MASK32]) - self.assertEqual(words[2:], [want_rev & MASK32, (want_rev >> 32) & MASK32]) - - -class ScalarCselectB64AliasingAndControlsTests(unittest.TestCase): - DEST = "s_cselect_b64 destination" - - def test_destination_exact_aliasing(self): - # D == S0, D == S1, and D == S0 == S1. - a64 = 0x55667788_11223344 - b64 = 0xDDEEFF00_99AABBCC - cases = [ - ("s[4:5]", "s[6:7]", a64, b64), - ("s[6:7]", "s[4:5]", b64, a64), - ("s[4:5]", "s[4:5]", a64, a64), - ] - for s0_spec, s1_spec, s0_val, s1_val in cases: - for scc in (0, 1): - with self.subTest(s0=s0_spec, s1=s1_spec, scc=scc): - want = ref_cselect_b64(s0_val, s1_val, scc) - lines = ( - load_pair_lines(4, a64) - + load_pair_lines(6, b64) - + [scc_line(scc), f"s_cselect_b64 s[4:5], {s0_spec}, {s1_spec}"] - + export_pair_lines(4) - + ["v_mov_b32 v2, 0", "v_mov_b32 v3, 0"] - ) - words = run_ps(lines) - self.assertEqual(words[:2], [want & MASK32, (want >> 32) & MASK32]) - - def test_partial_register_overlap_aliasing(self): - # Destination s[4:5] overlaps s[3:4] on s4, and s[5:6] on s5. - s3, s4, s5, s6 = 0x10203040, 0x50607080, 0x90A0B0C0, 0xD0E0F001 - p34 = (s4 << 32) | s3 - p56 = (s6 << 32) | s5 - for s0_spec, s1_spec, s0_val, s1_val in ( - ("s[3:4]", "s[5:6]", p34, p56), - ("s[5:6]", "s[3:4]", p56, p34), - ): - for scc in (0, 1): - with self.subTest(s0=s0_spec, s1=s1_spec, scc=scc): - want = ref_cselect_b64(s0_val, s1_val, scc) - words = run_ps([ - f"s_mov_b32 s3, {s3:#x}", - f"s_mov_b32 s4, {s4:#x}", - f"s_mov_b32 s5, {s5:#x}", - f"s_mov_b32 s6, {s6:#x}", - scc_line(scc), - f"s_cselect_b64 s[4:5], {s0_spec}, {s1_spec}", - "v_mov_b32 v0, s4", - "v_mov_b32 v1, s5", - "v_mov_b32 v2, 0", - "v_mov_b32 v3, 0", - ]) - self.assertEqual(words[:2], [want & MASK32, (want >> 32) & MASK32]) - - def test_condition_inversion_equivalence(self): - # cselect(A, B, cond) == cselect(B, A, not cond). - # We test both external validation and explicit in-shader SCC inversion. - a64 = 0x13579BDF_02468ACE - b64 = 0xCAFE1234_BEEF5678 - for scc in (0, 1): - with self.subTest(scc=scc): - words = run_ps( - load_pair_lines(4, a64) - + load_pair_lines(6, b64) - + [ - scc_line(scc), - "s_cselect_b64 s[2:3], s[4:5], s[6:7]", - "s_cselect_b32 s10, 0, 1", - "s_cmp_lg_u32 s10, 0", - "s_cselect_b64 s[8:9], s[6:7], s[4:5]", - "v_mov_b32 v0, s2", - "v_mov_b32 v1, s3", - "v_mov_b32 v2, s8", - "v_mov_b32 v3, s9", - ] - ) - want = ref_cselect_b64(a64, b64, scc) - self.assertEqual(words[:2], [want & MASK32, (want >> 32) & MASK32]) - self.assertEqual(words[2:], [want & MASK32, (want >> 32) & MASK32]) - - def test_negative_controls_condition_exclusion(self): - # Negative control: verify that when SCC=0, S0 is NOT returned; when SCC=1, S1 is NOT returned. - a64 = 0xAAAAAAAAAAAAAAAA - b64 = 0x5555555555555555 - for scc, unselected in ((0, a64), (1, b64)): - with self.subTest(scc=scc, unselected=hex(unselected)): - words = run_ps( - load_pair_lines(4, a64) - + load_pair_lines(6, b64) - + [scc_line(scc), "s_cselect_b64 s[2:3], s[4:5], s[6:7]"] - + export_pair_lines(2) - + ["v_mov_b32 v2, 0", "v_mov_b32 v3, 0"] - ) - res64 = (words[1] << 32) | words[0] - self.assertNotEqual(res64, unselected) - - def test_invalid_destinations_rejected_with_message(self): - # Destination must be a 2-SGPR pair for 64-bit scalar data select. - for line in ( - "s_cselect_b64 s4, s[6:7], s[8:9]", - "s_cselect_b64 m0, s[6:7], s[8:9]", - "s_cselect_b64 null, s[6:7], s[8:9]", - "s_cselect_b64 s[4:7], s[8:9], s[10:11]", - ): - with self.subTest(line=line): - full = [line, "exp mrt0 v0, v0, v0, v0 done vm", "s_endpgm"] - with self.assertRaisesRegex(rdna2spirv.Unsupported, re.escape(self.DEST)): - translate_ps(full) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_salu_cmp_signed.py b/tests/semantic/test_salu_cmp_signed.py deleted file mode 100644 index 33149a6cc..000000000 --- a/tests/semantic/test_salu_cmp_signed.py +++ /dev/null @@ -1,118 +0,0 @@ -"""Semantic interpreter tests for the register-register scalar compares s_cmp_{eq,lg,gt,ge,lt,le}_{i32,u32}. - -RDNA2 ISA (SOPC): SCC = S0 S1, compared as signed 32-bit values for _i32 and unsigned for _u32. Only eq, lg, -gt, ge, lt and le on _u32 and gt/lt on _i32 had a translation test before; the signed ordering of operands that differ -in bit 31 (0x7FFFFFFF vs 0x80000000, -1 vs 0) is what a wrong signedness gets wrong. -Each case sets SCC, copies it with s_cselect_b32 into one bit of a mask, and the 32-bit mask leaves through exp as two -16-bit halves ORed into 0x40000000 (no NaN or denormal export pattern). The operands are set with s_mov_b32. The -expected bits come from plain-Python integer comparisons. -""" -import os -import struct -import sys -import tempfile -import unittest -import warnings - -HERE = os.path.dirname(os.path.abspath(__file__)) -ROOT = os.path.dirname(os.path.dirname(HERE)) -TOOLS_DIR = os.environ.get("LEONIDA_TOOLS_DIR") or os.path.join(ROOT, "tools") - -sys.dont_write_bytecode = True -sys.path.insert(0, TOOLS_DIR) -sys.path.insert(0, HERE) - -import rdna2spirv # noqa: E402 -import spirv_mini_interp as si # noqa: E402 - -M32 = 0xFFFFFFFF -STUB_DXBC = b"DXBC" + bytes(24) + struct.pack("> 31 else x - - -CONDS = { - "eq": lambda a, b: a == b, "lg": lambda a, b: a != b, "gt": lambda a, b: a > b, - "ge": lambda a, b: a >= b, "lt": lambda a, b: a < b, "le": lambda a, b: a <= b, -} - -PAIRS = [(0, 0), (1, 0), (0, 1), (M32, 0), (0, M32), (M32, 1), (1, M32), (0x7FFFFFFF, 0x80000000), - (0x80000000, 0x7FFFFFFF), (0x80000000, 0x80000000), (0x80000000, M32), (M32, M32), (5, 5), - (0x7FFFFFFF, 0x7FFFFFFF), (0xFFFFFFFE, M32), (0x00010000, 0x0000FFFF)] - -_TMP = None -_SRC = None - - -def setUpModule(): - global _TMP, _SRC - _TMP = tempfile.TemporaryDirectory() - d = os.path.join(_TMP.name, "disasm") - os.mkdir(d) - _SRC = os.path.join(d, "ps_salu_cmp.s") - with open(os.path.join(_TMP.name, "ps_salu_cmp.dxbc"), "wb") as f: - f.write(STUB_DXBC) - - -def tearDownModule(): - global _TMP - if _TMP is not None: - _TMP.cleanup() - _TMP = None - - -def run_mask(lines): - """Run lines that leave their result bits in s5; return s5.""" - if _TMP is None: - setUpModule() - tail = ["s_and_b32 s10, s5, 0xffff", "s_lshr_b32 s11, s5, 16", "s_or_b32 s10, s10, 0x40000000", - "s_or_b32 s11, s11, 0x40000000", "v_mov_b32 v0, s10", "v_mov_b32 v1, s11"] - asm = ("; test_salu_cmp_signed\n\ts_mov_b32 s5, 0\n" + "".join(f"\t{ln}\n" for ln in list(lines) + tail) - + "\texp mrt0 v0, v1, v1, v1 done vm\n\ts_endpgm\n") - with open(_SRC, "w", encoding="utf-8") as f: - f.write(asm) - with warnings.catch_warnings(): - warnings.simplefilter("ignore", ResourceWarning) - spv = rdna2spirv.translate(_SRC) - lo, hi = si.run_fragment(spv)["%out_mrt0"][:2] - assert lo >> 16 == hi >> 16 == 0x4000, (hex(lo), hex(hi)) - return (lo & 0xFFFF) | (hi & 0xFFFF) << 16 - - -def load(reg, value, dynamic=False): - return [f"s_mov_b32 s{reg}, {value & M32:#x}"] - - -def collect(k): - return [f"s_cselect_b32 s4, 1, 0", f"s_lshl_b32 s4, s4, {k}", "s_or_b32 s5, s5, s4"] - - -def bits(flags): - return sum(1 << i for i, f in enumerate(flags) if f) - - -class ScalarCompareTests(unittest.TestCase): - def check(self, make_lines, expect, label): - lines = [] - for k in range(len(expect)): - lines += make_lines(k, False) - with self.subTest(case=label): - self.assertEqual(run_mask(lines), bits(expect), label) - - def test_s_cmp_i32_u32(self): - for ty in ("i32", "u32"): - conv = s32 if ty == "i32" else (lambda x: x & M32) - for cond, fn in CONDS.items(): - def make(k, dynamic, ty=ty, cond=cond): - a, b = PAIRS[k] - return (load(2, a, dynamic) + load(3, b, dynamic) - + [f"s_cmp_{cond}_{ty} s2, s3"] + collect(k)) - expect = [fn(conv(a), conv(b)) for a, b in PAIRS] - self.check(make, expect, f"s_cmp_{cond}_{ty}") - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_salu_cmpk.py b/tests/semantic/test_salu_cmpk.py deleted file mode 100644 index d67fbd393..000000000 --- a/tests/semantic/test_salu_cmpk.py +++ /dev/null @@ -1,167 +0,0 @@ -"""Semantic interpreter tests for RDNA2 SOPK scalar 16-bit immediate compares. - -Covers all 12 s_cmpk_{eq,lg,gt,ge,lt,le}_{i32,u32} opcodes, verifying: -- 16-bit sign-extension for _i32 (0xFFFF -> -1, 0x8000 -> -32768, 0x7FFF -> +32767) - versus 16-bit zero-extension for _u32 (0xFFFF -> 65535, 0x8000 -> 32768); -- both SCC = 1 and SCC = 0 outcomes (pre-setting SCC = 1 before false compares - to verify SCC is cleared); -- in-memory negative controls on the generated SPIR-V text. -""" -import os -import sys -import unittest - -HERE = os.path.dirname(os.path.abspath(__file__)) -sys.dont_write_bytecode = True -sys.path.insert(0, HERE) - -import spirv_mini_interp as si # noqa: E402 -import support # noqa: E402 - -MASK32 = 0xFFFFFFFF - -S0_VALUES = [ - 0, - 1, - 0xFFFFFFFF, # -1 - 0x80000000, # INT32_MIN - 0x7FFFFFFF, # INT32_MAX - 32768, # 0x8000 - 65535, # 0xFFFF -] - -IMM16_VALUES = [0, 1, 0x7FFF, 0x8000, 0xFFFF] - -CONDS = { - "eq": lambda a, b: a == b, - "lg": lambda a, b: a != b, - "gt": lambda a, b: a > b, - "ge": lambda a, b: a >= b, - "lt": lambda a, b: a < b, - "le": lambda a, b: a <= b, -} - - -def s32(x: int) -> int: - x &= MASK32 - return x - 0x100000000 if (x & 0x80000000) else x - - -def sext16(imm: int) -> int: - imm &= 0xFFFF - return imm - 0x10000 if (imm & 0x8000) else imm - - -def run_cmpk(op: str, s0_val: int, imm16: int, preset_scc: bool = False) -> int: - """Translate and execute one s_cmpk_* instruction, returning SCC (0 or 1).""" - lines = [] - if preset_scc: - lines.append("s_cmp_eq_u32 1, 1") - lines.extend([ - f"s_mov_b32 s0, {s0_val:#x}", - f"{op} s0, {imm16:#x}", - "s_cselect_b32 s1, 1, 0", - "v_mov_b32 v0, s1", - "exp mrt0 v0, v0, v0, v0 done vm", - "s_endpgm", - ]) - spv = support.translate_lines("ps_salu_cmpk", lines) - return support.mrt0_words(spv)[0] - - -class SaluCmpkTests(unittest.TestCase): - def test_all_12_opcodes_signed_and_unsigned(self): - for cond, cmp_fn in CONDS.items(): - for ty in ("i32", "u32"): - op = f"s_cmpk_{cond}_{ty}" - for s0_val in S0_VALUES: - for imm16 in IMM16_VALUES: - lhs = s32(s0_val) if ty == "i32" else (s0_val & MASK32) - rhs = sext16(imm16) if ty == "i32" else (imm16 & 0xFFFF) - want = int(cmp_fn(lhs, rhs)) - with self.subTest(op=op, s0=hex(s0_val), imm16=hex(imm16)): - # Pre-set SCC=1 before expected-false compares to verify it clears. - got = run_cmpk(op, s0_val, imm16, preset_scc=(want == 0)) - self.assertEqual(got, want) - - def test_sign_vs_zero_extension_divergence(self): - # 0xFFFF is -1 in i32 (equal to 0xFFFFFFFF) vs 65535 in u32 (equal to 65535). - self.assertEqual(run_cmpk("s_cmpk_eq_i32", 0xFFFFFFFF, 0xFFFF, preset_scc=False), 1) - self.assertEqual(run_cmpk("s_cmpk_eq_u32", 0xFFFFFFFF, 0xFFFF, preset_scc=True), 0) - self.assertEqual(run_cmpk("s_cmpk_eq_u32", 65535, 0xFFFF, preset_scc=False), 1) - self.assertEqual(run_cmpk("s_cmpk_eq_i32", 65535, 0xFFFF, preset_scc=True), 0) - - # 0x8000 is -32768 in i32 (< 0) vs +32768 in u32 (> 0). - self.assertEqual(run_cmpk("s_cmpk_lt_i32", 0, 0x8000, preset_scc=True), 0) - self.assertEqual(run_cmpk("s_cmpk_gt_i32", 0, 0x8000, preset_scc=False), 1) - self.assertEqual(run_cmpk("s_cmpk_lt_u32", 0, 0x8000, preset_scc=False), 1) - self.assertEqual(run_cmpk("s_cmpk_gt_u32", 0, 0x8000, preset_scc=True), 0) - - def test_imm16_edges_decimal_tokens_and_s0_kept(self): - # S0 one below, at and one above the extended immediate (-32768 for _i32, 65535 for _u32), plus a - # high-bit S0 that equals sext16(0x8000) only when sign-extended; decimal immediates written signed. - # S0 must read back unchanged after the compare. - cases = [ - ("i32", 0xFFFF7FFF, "0x8000"), # -32769 vs -32768 - ("i32", 0xFFFF8000, "0x8000"), # -32768 vs -32768 - ("i32", 0xFFFF8001, "0x8000"), # -32767 vs -32768 - ("i32", 0xFFFF8000, "-32768"), - ("i32", 0xFFFFFFFE, "-1"), - ("i32", 0x00007FFE, "32767"), - ("u32", 0x0000FFFE, "0xffff"), # 65534 vs 65535 - ("u32", 0x00010000, "0xffff"), # 65536 vs 65535 - ("u32", 0xFFFF8000, "0x8000"), # not sign-extended: 0xffff8000 > 0x8000 - ] - for ty, s0_val, tok in cases: - imm16 = int(tok, 0) & 0xFFFF - for cond, cmp_fn in CONDS.items(): - lhs = s32(s0_val) if ty == "i32" else s0_val - rhs = sext16(imm16) if ty == "i32" else imm16 - want = int(cmp_fn(lhs, rhs)) - with self.subTest(op=f"s_cmpk_{cond}_{ty}", s0=hex(s0_val), imm=tok): - spv = support.translate_lines("ps_salu_cmpk_edge", [ - "s_cmp_eq_u32 1, 1" if want == 0 else "s_cmp_eq_u32 0, 1", - f"s_mov_b32 s0, {s0_val:#x}", - f"s_cmpk_{cond}_{ty} s0, {tok}", - "s_cselect_b32 s1, 1, 0", - "v_mov_b32 v0, s1", - "v_mov_b32 v1, s0", - "exp mrt0 v0, v1, v0, v0 done vm", - "s_endpgm", - ]) - self.assertEqual(support.mrt0_words(spv)[:2], [want, s0_val]) - - def test_negative_controls_catch_spirv_regressions(self): - # 1) Signed vs unsigned operator swap: s_cmpk_gt_i32 (0xFFFFFFFF vs -32768 -> True) - # becomes OpUGreaterThan (0xFFFFFFFF > 0xFFFF8000 -> True? No, let's pick 0 vs 0xFFFF: - # 0 > -1 is True in i32, 0 > 0xFFFFFFFF is False in u32). - spv_signed = support.translate_lines("ps_salu_cmpk_neg1", [ - "s_mov_b32 s0, 0x0", - "s_cmpk_gt_i32 s0, 0xffff", - "s_cselect_b32 s1, 1, 0", - "v_mov_b32 v0, s1", - "exp mrt0 v0, v0, v0, v0 done vm", - "s_endpgm", - ]) - self.assertIn("OpSGreaterThan %bool", spv_signed) - self.assertEqual(si.run_fragment(spv_signed)["%out_mrt0"][0], 1) - bad_unsigned = spv_signed.replace("OpSGreaterThan %bool", "OpUGreaterThan %bool", 1) - self.assertEqual(si.run_fragment(bad_unsigned)["%out_mrt0"][0], 0) - - # 2) Equality inversion: OpIEqual <-> OpINotEqual on s_cmpk_eq_u32 (65535 == 0xFFFF -> True). - spv_eq = support.translate_lines("ps_salu_cmpk_neg2", [ - "s_mov_b32 s0, 0xffff", - "s_cmpk_eq_u32 s0, 0xffff", - "s_cselect_b32 s1, 1, 0", - "v_mov_b32 v0, s1", - "exp mrt0 v0, v0, v0, v0 done vm", - "s_endpgm", - ]) - self.assertIn("OpIEqual %bool", spv_eq) - self.assertEqual(si.run_fragment(spv_eq)["%out_mrt0"][0], 1) - bad_ne = spv_eq.replace("OpIEqual %bool", "OpINotEqual %bool", 1) - self.assertEqual(si.run_fragment(bad_ne)["%out_mrt0"][0], 0) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_salu_flbit_64.py b/tests/semantic/test_salu_flbit_64.py deleted file mode 100644 index faf480eb3..000000000 --- a/tests/semantic/test_salu_flbit_64.py +++ /dev/null @@ -1,132 +0,0 @@ -"""Semantic interpreter tests for RDNA2 s_flbit_i32_b64 and s_flbit_i32_i64. - -Leading-bit counts of the 64-bit SGPR pair S0, from bit 63 down: - s_flbit_i32_b64: the number of 0 bits before the first 1; -1 (0xFFFFFFFF) when S0 is 0. - s_flbit_i32_i64: the number of bits before the first one that differs from the sign bit (bit 63 itself counts, - as for v_ffbh_i32 / s_flbit_i32); -1 when every bit equals the sign (0 and -1). -SCC is not written. Each case translates a synthetic pixel shader with tools/rdna2spirv.py, runs it in -tests/semantic/spirv_mini_interp.py and compares the result with a plain-Python reference. D leaves through exp as -two 16-bit halves ORed into 0x40000000, so no export channel is a NaN or denormal pattern that a float round trip -could change; SCC comes back through s_cselect_b32. -""" -import os -import random -import struct -import sys -import tempfile -import unittest -import warnings - -HERE = os.path.dirname(os.path.abspath(__file__)) -ROOT = os.path.dirname(os.path.dirname(HERE)) -TOOLS_DIR = os.environ.get("LEONIDA_TOOLS_DIR") or os.path.join(ROOT, "tools") - -sys.dont_write_bytecode = True -sys.path.insert(0, TOOLS_DIR) -sys.path.insert(0, HERE) - -import rdna2spirv # noqa: E402 -import spirv_mini_interp as si # noqa: E402 - -M32 = 0xFFFFFFFF -M64 = (1 << 64) - 1 -STUB_DXBC = b"DXBC" + bytes(24) + struct.pack(" int: - x &= M64 - return M32 if x == 0 else 64 - x.bit_length() - - -def flbit_i64(x: int) -> int: - x &= M64 - return flbit_b64(~x & M64 if x >> 63 else x) - - -OPS = {"s_flbit_i32_b64": flbit_b64, "s_flbit_i32_i64": flbit_i64} -VALUES = [0, 1, M64, 1 << 63, (1 << 63) - 1, 1 << 32, 0xFFFFFFFF, 0x80000000, 0x00000001FFFFFFFF, - 0xFFFFFFFF00000000, 0xFFFFFFFE00000000, 0xC000000000000000, 0x4000000000000000, 0xFFFFFFFFFFFFFFFE] - -_TMP_DIR = None -_SRC_PATH = None - - -def setUpModule(): - global _TMP_DIR, _SRC_PATH - _TMP_DIR = tempfile.TemporaryDirectory() - disasm_dir = os.path.join(_TMP_DIR.name, "disasm") - os.mkdir(disasm_dir) - _SRC_PATH = os.path.join(disasm_dir, "ps_salu_flbit64.s") - with open(os.path.join(_TMP_DIR.name, "ps_salu_flbit64.dxbc"), "wb") as f: - f.write(STUB_DXBC) - - -def tearDownModule(): - global _TMP_DIR - if _TMP_DIR is not None: - _TMP_DIR.cleanup() - _TMP_DIR = None - - -def run_lines(lines) -> tuple: - """Run the lines, return (s0, SCC).""" - if _TMP_DIR is None: - setUpModule() - tail = ["s_cselect_b32 s20, 0x40000001, 0x40000000", "s_and_b32 s10, s0, 0xffff", "s_lshr_b32 s11, s0, 16", - "s_or_b32 s10, s10, 0x40000000", "s_or_b32 s11, s11, 0x40000000", - "v_mov_b32 v0, s10", "v_mov_b32 v1, s11", "v_mov_b32 v2, s20"] - asm = ("; test_salu_flbit64\n" + "".join(f"\t{ln}\n" for ln in list(lines) + tail) - + "\texp mrt0 v0, v1, v2, v2 done vm\n\ts_endpgm\n") - with open(_SRC_PATH, "w", encoding="utf-8") as f: - f.write(asm) - with warnings.catch_warnings(): - warnings.simplefilter("ignore", ResourceWarning) - spv = rdna2spirv.translate(_SRC_PATH) - lo, hi, scc = si.run_fragment(spv)["%out_mrt0"][:3] - assert lo >> 16 == hi >> 16 == 0x4000 and scc >> 1 == 0x20000000, (hex(lo), hex(hi), hex(scc)) - return (lo & 0xFFFF) | (hi & 0xFFFF) << 16, scc & 1 - - -def run_op(op: str, x: int, scc_in: int = 0) -> tuple: - return run_lines([f"s_mov_b32 s2, {x & M32:#x}", f"s_mov_b32 s3, {x >> 32:#x}", f"s_mov_b32 s4, {scc_in}", - "s_cmp_eq_u32 s4, 1", f"{op} s0, s[2:3]"]) - - -class Flbit64Tests(unittest.TestCase): - def test_reference(self): - self.assertEqual(flbit_b64(1), 63) - self.assertEqual(flbit_b64(1 << 32), 31) - self.assertEqual(flbit_b64(0), M32) - self.assertEqual(flbit_i64(1), 63) - self.assertEqual(flbit_i64(0xFFFFFFFFFFFFFFFE), 63) # -2: bit 0 is the first to differ - self.assertEqual(flbit_i64(1 << 63), 1) - self.assertEqual(flbit_i64(M64), M32) - - def test_values_and_scc_kept(self): - for op, fn in OPS.items(): - for x in VALUES: - for scc_in in (0, 1): - with self.subTest(op=op, x=hex(x), scc=scc_in): - self.assertEqual(run_op(op, x, scc_in), (fn(x), scc_in)) - - def test_seeded(self): - rng = random.Random(0xF1B) - for _ in range(30): - op = rng.choice(list(OPS)) - x = rng.getrandbits(64) >> rng.randrange(64) - if rng.getrandbits(1): - x = ~x & M64 - with self.subTest(op=op, x=hex(x)): - self.assertEqual(run_op(op, x)[0], OPS[op](x)) - - def test_inline_source(self): - self.assertEqual(run_lines(["s_flbit_i32_b64 s0, 1"])[0], 63) - self.assertEqual(run_lines(["s_flbit_i32_i64 s0, -1"])[0], M32) - - def test_lane_mask_source_is_rejected(self): - with self.assertRaises(rdna2spirv.Unsupported): - run_lines(["s_flbit_i32_b64 s0, exec"]) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_salu_flbit_lane_mask.py b/tests/semantic/test_salu_flbit_lane_mask.py deleted file mode 100644 index 8c82856ee..000000000 --- a/tests/semantic/test_salu_flbit_lane_mask.py +++ /dev/null @@ -1,109 +0,0 @@ -"""s_flbit_i32_b32 and s_flbit_i32 of a lane mask (vcc_lo, vcc_hi), run across every lane of the translated SPIR-V. - -RDNA2 ISA: a lane mask is one bit per lane of the wave, so a scalar op that reads vcc_lo as a number sees lanes 0..31 -(vcc_hi: lanes 32..63) and gives the same answer in every lane: - s_flbit_i32_b32 D = the zeros above the highest set bit, -1 (0xFFFFFFFF) when the value is 0; - s_flbit_i32 D = the bits above the first bit that differs from the sign bit, -1 when there is none. -The translator holds a mask as this lane's 0 / ~0, so reading it as data gave each lane its own 0 or -1 (the -s_bcnt1 and s_ff1 forms already gather the whole wave). Every lane stores its D; the expected values are computed -here from the two lines above, not by the translator. Programs are hand-written (no game data) and run with -spirv_mini_interp.run_workgroup. s_ff1_i32_b32 of the same mask is stored as a control for the gather. -""" -import struct -import unittest - -import support -import spirv_mini_interp as si - -VSHARP = [0, 0, 0x1000, 0x31016FAC] -M32 = 0xFFFFFFFF - -# (multiplier, addend, and-mask): the lanes l with ((l * multiplier + addend) & and-mask) == 0 are in the mask. -CASES = ( - (1, 0, 8), # lanes 0..7, 16..23, 32..39, ... - (1, 0, 1), # even lanes - (1, 1, 1), # odd lanes - (1, 0, 0), # every lane - (1, 1, 0xFFFF), # no lane (l + 1 is never 0 mod 2^16 below lane 64) - (1, 0, 63), # lane 0 only - (1, 0, 32), # the low half of a wave64, none of a wave32 - (1, 32, 32), # the high half of a wave64, all of a wave32 (lane + 32 & 32 == 0 for lanes 32..63) - (3, 5, 14), -) - - -def fssm(threads): - h = bytearray(0x148) - struct.pack_into("<4I", h, 0x138, 0x8088, threads, 1, 1) - return bytes(h) - - -def flbit_u(x): - return 31 - (x.bit_length() - 1) if x else M32 - - -def flbit_i(x): - sign = x >> 31 - for n in range(1, 32): - if (x >> (31 - n)) & 1 != sign: - return n - return M32 - - -def ff1(x): - return (x & -x).bit_length() - 1 if x else M32 - - -def mask_words(lanes, mul, add, mask): - m = sum(1 << l for l in range(lanes) if ((l * mul + add) & mask) == 0) - return m & M32, m >> 32 - - -def program(lanes, reg, mul, add, mask): - def store(d, at): - return [f"v_mov_b32_e32 v20, {d}", f"v_add_nc_u32_e32 v21, {at}, v22", - "buffer_store_dword v20, v21, s[0:3], 0 offen"] - - return (["v_mbcnt_lo_u32_b32 v1, -1, 0"] + (["v_mbcnt_hi_u32_b32 v1, -1, v1"] if lanes == 64 else []) + - [f"v_mad_u32_u24 v3, v1, {mul}, {add}", f"v_and_b32_e32 v3, {mask}, v3", "v_cmp_eq_u32_e32 vcc, 0, v3", - f"s_flbit_i32_b32 s6, {reg}", f"s_flbit_i32 s7, {reg}", f"s_ff1_i32_b32 s8, {reg}", - "v_lshlrev_b32_e32 v22, 2, v1"] + - store("s6", 0) + store("s7", 256) + store("s8", 512) + ["s_endpgm"]) - - -def run(spv, lanes): - return si.run_workgroup( - spv, lanes, lanes, inputs_for=lambda i: {"%wg_id": (0, 0, 0), "%local_id": (i, 0, 0), "%sg_lane": i}, - push_constants=VSHARP + [0] * 28, memory={}) - - -class FlbitOfLaneMask(unittest.TestCase): - def check(self, lanes, reg): - for mul, add, mask in CASES: - with self.subTest(lanes=lanes, reg=reg, case=(mul, add, mask)): - lo, hi = mask_words(lanes, mul, add, mask) - word = hi if reg == "vcc_hi" else lo - spv = support.translate_lines("cs_flbit_mask", program(lanes, reg, mul, add, mask), - fssm=fssm(lanes)) - memory = run(spv, lanes) - for lane in range(lanes): - self.assertEqual(memory[4 * lane], flbit_u(word), f"s_flbit_i32_b32, lane {lane}") - self.assertEqual(memory[256 + 4 * lane], flbit_i(word), f"s_flbit_i32, lane {lane}") - self.assertEqual(memory[512 + 4 * lane], ff1(word), f"s_ff1_i32_b32, lane {lane}") - - def test_model(self): - self.assertEqual((flbit_u(1), flbit_u(0x80000000), flbit_u(0)), (31, 0, M32)) - self.assertEqual((flbit_i(1), flbit_i(0x40000000), flbit_i(M32), flbit_i(0)), (31, 1, M32, M32)) - - def test_wave32_vcc_lo(self): - self.check(32, "vcc_lo") - - def test_wave64_vcc_lo(self): - self.check(64, "vcc_lo") - - def test_wave64_vcc_hi(self): - self.check(64, "vcc_hi") - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_salu_lshl_add.py b/tests/semantic/test_salu_lshl_add.py deleted file mode 100644 index 33ddbf2ef..000000000 --- a/tests/semantic/test_salu_lshl_add.py +++ /dev/null @@ -1,644 +0,0 @@ -"""Semantic interpreter tests for RDNA2 s_lshl1_add_u32 ... s_lshl4_add_u32. - -RDNA2 scalar shift-and-add instructions: - - s_lshl1_add_u32 D, S0, S1: D = ((S0 << 1) + S1) & 0xFFFFFFFF - - s_lshl2_add_u32 D, S0, S1: D = ((S0 << 2) + S1) & 0xFFFFFFFF - - s_lshl3_add_u32 D, S0, S1: D = ((S0 << 3) + S1) & 0xFFFFFFFF - - s_lshl4_add_u32 D, S0, S1: D = ((S0 << 4) + S1) & 0xFFFFFFFF - -Semantics and Condition Code (SCC): - - D is the lower 32 bits of the scaled addition: ((S0 << N) + S1) mod 2^32. - - SCC represents unsigned overflow of the sum taken in 64 bits (RDNA ISA pseudocode): - tmp = (64'U(S0) << N) + 64'U(S1) - SCC = 1 if tmp >= 2^32 else 0 - Bits shifted out of S0 (upper N bits of S0) count as carry just like an addition - carry out of the 32-bit addition. - - Pre-existing SCC state is ignored and unconditionally overwritten. - -Each test case verifies mathematical semantics against pure-Python reference models -and executes synthetic shaders with tools/rdna2spirv.py in tests/semantic/spirv_mini_interp.py. -""" -from __future__ import annotations - -import os -import random -import struct -import sys -import tempfile -import unittest -import warnings - -HERE = os.path.dirname(os.path.abspath(__file__)) -ROOT = os.path.dirname(os.path.dirname(HERE)) -TOOLS_DIR = os.environ.get("LEONIDA_TOOLS_DIR") or os.path.join(ROOT, "tools") - -sys.dont_write_bytecode = True -if ROOT not in sys.path: - sys.path.insert(0, ROOT) -if TOOLS_DIR not in sys.path: - sys.path.insert(0, TOOLS_DIR) -if HERE not in sys.path: - sys.path.insert(0, HERE) - -import rdna2spirv # noqa: E402 -import spirv_mini_interp as si # noqa: E402 - -MASK32 = 0xFFFFFFFF -MASK64 = (1 << 64) - 1 -TWO_POW_32 = 1 << 32 -STUB_DXBC = b"DXBC" + bytes(24) + struct.pack(" tuple[int, int]: - """Pure-Python reference oracle for RDNA2 s_lshlN_add_u32 (N in {1, 2, 3, 4}). - - Computes 64-bit unsigned temporary sum: - tmp = (u64(s0) << n) + u64(s1) - result = tmp & 0xFFFFFFFF - scc = 1 if tmp >= 2^32 else 0 - - Returns: - (result, scc): 32-bit unsigned result and SCC overflow flag. - """ - if n not in (1, 2, 3, 4): - raise ValueError(f"Shift amount N must be in {1, 2, 3, 4}, got {n}") - s0_u32 = s0 & MASK32 - s1_u32 = s1 & MASK32 - tmp = (s0_u32 << n) + s1_u32 - res = tmp & MASK32 - scc = 1 if (tmp >= TWO_POW_32) else 0 - - # Cross-check against hardware decomposition: - # shifted_out_bits | addition_carry == scc - out_bits = s0_u32 >> (32 - n) - sh_low = (s0_u32 << n) & MASK32 - carry = 1 if (sh_low + s1_u32 > MASK32) else 0 - assert (1 if (out_bits != 0 or carry != 0) else 0) == scc - - return res, scc - - -def ref_s_lshl1_add_u32(s0: int, s1: int) -> tuple[int, int]: - """Reference oracle for s_lshl1_add_u32: D = ((S0 << 1) + S1) & 0xFFFFFFFF.""" - return ref_s_lshl_add_u32(1, s0, s1) - - -def ref_s_lshl2_add_u32(s0: int, s1: int) -> tuple[int, int]: - """Reference oracle for s_lshl2_add_u32: D = ((S0 << 2) + S1) & 0xFFFFFFFF.""" - return ref_s_lshl_add_u32(2, s0, s1) - - -def ref_s_lshl3_add_u32(s0: int, s1: int) -> tuple[int, int]: - """Reference oracle for s_lshl3_add_u32: D = ((S0 << 3) + S1) & 0xFFFFFFFF.""" - return ref_s_lshl_add_u32(3, s0, s1) - - -def ref_s_lshl4_add_u32(s0: int, s1: int) -> tuple[int, int]: - """Reference oracle for s_lshl4_add_u32: D = ((S0 << 4) + S1) & 0xFFFFFFFF.""" - return ref_s_lshl_add_u32(4, s0, s1) - - -def ref(n: int, x: int, y: int) -> tuple[int, int]: - """Backwards-compatible reference wrapper.""" - return ref_s_lshl_add_u32(n, x, y) - - -class ScalarAluInterpreter: - """Minimal deterministic software emulator for scalar ALU state.""" - - def __init__(self, num_sgprs: int = 106) -> None: - self.sgprs = [0] * num_sgprs - self.scc: int = 0 - - def reset(self) -> None: - for i in range(len(self.sgprs)): - self.sgprs[i] = 0 - self.scc = 0 - - def get_sgpr(self, reg: int | str) -> int: - idx = int(reg[1:]) if isinstance(reg, str) and reg.startswith("s") else int(reg) - return self.sgprs[idx] & MASK32 - - def set_sgpr(self, reg: int | str, val: int) -> None: - idx = int(reg[1:]) if isinstance(reg, str) and reg.startswith("s") else int(reg) - self.sgprs[idx] = val & MASK32 - - def parse_operand(self, op: str | int) -> int: - if isinstance(op, int): - return op & MASK32 - op = op.strip() - if op.startswith("s"): - return self.get_sgpr(op) - if op.startswith("0x") or op.startswith("0X"): - return int(op, 16) & MASK32 - return int(op) & MASK32 - - def step(self, op: str, *args: str | int) -> tuple[int, int]: - """Execute a single SALU instruction and update register state.""" - if op == "s_mov_b32": - dst, src = args[0], args[1] - val = self.parse_operand(src) - self.set_sgpr(dst, val) - return val, self.scc - - if op == "s_cmp_eq_u32": - s0, s1 = self.parse_operand(args[0]), self.parse_operand(args[1]) - self.scc = 1 if s0 == s1 else 0 - return 0, self.scc - - if op == "s_cselect_b32": - dst, s0, s1 = args[0], self.parse_operand(args[1]), self.parse_operand(args[2]) - val = s0 if self.scc != 0 else s1 - self.set_sgpr(dst, val) - return val, self.scc - - if op == "s_addc_u32": - dst, s0, s1 = args[0], self.parse_operand(args[1]), self.parse_operand(args[2]) - tot = s0 + s1 + self.scc - res = tot & MASK32 - self.scc = 1 if tot > MASK32 else 0 - self.set_sgpr(dst, res) - return res, self.scc - - if op in ("s_lshl1_add_u32", "s_lshl2_add_u32", "s_lshl3_add_u32", "s_lshl4_add_u32"): - n = int(op[6]) - dst = args[0] - s0 = self.parse_operand(args[1]) - s1 = self.parse_operand(args[2]) - res, scc = ref_s_lshl_add_u32(n, s0, s1) - self.set_sgpr(dst, res) - self.scc = scc - return res, self.scc - - raise ValueError(f"Unsupported instruction in ScalarAluInterpreter: {op}") - - -_TMP_DIR = None -_SRC_PATH = None - - -def setUpModule(): - global _TMP_DIR, _SRC_PATH - _TMP_DIR = tempfile.TemporaryDirectory() - disasm_dir = os.path.join(_TMP_DIR.name, "disasm") - os.mkdir(disasm_dir) - _SRC_PATH = os.path.join(disasm_dir, "ps_salu_lshl_add.s") - with open(os.path.join(_TMP_DIR.name, "ps_salu_lshl_add.dxbc"), "wb") as f: - f.write(STUB_DXBC) - - -def tearDownModule(): - global _TMP_DIR - if _TMP_DIR is not None: - _TMP_DIR.cleanup() - _TMP_DIR = None - - -def run_lines(lines) -> tuple: - """Run the lines, export v0 and v1, return those two words.""" - if _TMP_DIR is None: - setUpModule() - asm = "; test_salu_lshl_add\n" + "".join(f"\t{ln}\n" for ln in lines) + "\texp mrt0 v0, v1, v0, v0 done vm\n\ts_endpgm\n" - with open(_SRC_PATH, "w", encoding="utf-8") as f: - f.write(asm) - with warnings.catch_warnings(): - warnings.simplefilter("ignore", ResourceWarning) - spv = rdna2spirv.translate(_SRC_PATH) - return tuple(si.run_fragment(spv)["%out_mrt0"][:2]) - - -def run_op(n: int, x: int, y: int, scc_in: int) -> tuple: - """SCC = scc_in, then s0 = s_lshlN_add_u32(s2, s3); return (s0, SCC after).""" - return run_lines([ - f"s_mov_b32 s2, {x:#x}", - f"s_mov_b32 s3, {y:#x}", - f"s_mov_b32 s4, {scc_in}", - "s_cmp_eq_u32 s4, 1", - f"s_lshl{n}_add_u32 s0, s2, s3", - "s_cselect_b32 s1, 1, 0", - "v_mov_b32 v0, s0", - "v_mov_b32 v1, s1", - ]) - - -class ReferenceOracleTests(unittest.TestCase): - """Validation of pure-Python reference oracles and mathematical invariants.""" - - def test_reference_oracle_zero_identity(self): - for n in (1, 2, 3, 4): - with self.subTest(n=n): - res, scc = ref_s_lshl_add_u32(n, 0, 0) - self.assertEqual(res, 0) - self.assertEqual(scc, 0) - - def test_reference_oracle_address_scaling(self): - base_addr = 0x2000 - index = 25 - # Scale 1: 2 bytes (halfword) -> 2000 + 50 = 2050 - self.assertEqual(ref_s_lshl1_add_u32(index, base_addr), (base_addr + 50, 0)) - # Scale 2: 4 bytes (dword) -> 2000 + 100 = 2100 - self.assertEqual(ref_s_lshl2_add_u32(index, base_addr), (base_addr + 100, 0)) - # Scale 3: 8 bytes (qword) -> 2000 + 200 = 2200 - self.assertEqual(ref_s_lshl3_add_u32(index, base_addr), (base_addr + 200, 0)) - # Scale 4: 16 bytes (dqword) -> 2000 + 400 = 2400 - self.assertEqual(ref_s_lshl4_add_u32(index, base_addr), (base_addr + 400, 0)) - - def test_reference_oracle_shifted_out_decomposition(self): - # Bit shifted out of S0 alone sets SCC even with zero addend - self.assertEqual(ref_s_lshl1_add_u32(0x80000000, 0), (0, 1)) - self.assertEqual(ref_s_lshl2_add_u32(0x40000000, 0), (0, 1)) - self.assertEqual(ref_s_lshl3_add_u32(0x20000000, 0), (0, 1)) - self.assertEqual(ref_s_lshl4_add_u32(0x10000000, 0), (0, 1)) - - def test_reference_oracle_add_carry_alone(self): - # Addition overflow alone sets SCC even without shifted-out bits - self.assertEqual(ref_s_lshl1_add_u32(1, 0xFFFFFFFE), (0, 1)) - self.assertEqual(ref_s_lshl2_add_u32(1, 0xFFFFFFFC), (0, 1)) - self.assertEqual(ref_s_lshl3_add_u32(1, 0xFFFFFFF8), (0, 1)) - self.assertEqual(ref_s_lshl4_add_u32(1, 0xFFFFFFF0), (0, 1)) - - def test_reference_oracle_both_shift_and_add_carry(self): - # Both shifted out bits and addition carry present - res1, scc1 = ref_s_lshl1_add_u32(0x80000001, 0xFFFFFFFF) - self.assertEqual(res1, 1) - self.assertEqual(scc1, 1) - - res4, scc4 = ref_s_lshl4_add_u32(0xF0000001, 0xFFFFFFFF) - self.assertEqual(res4, 0x0000000F) - self.assertEqual(scc4, 1) - - def test_reference_oracle_invalid_shift_raises(self): - with self.assertRaises(ValueError): - ref_s_lshl_add_u32(0, 10, 20) - with self.assertRaises(ValueError): - ref_s_lshl_add_u32(5, 10, 20) - - def test_scalar_interpreter_basic_pipeline(self): - interp = ScalarAluInterpreter() - interp.step("s_mov_b32", "s2", 0x10) - interp.step("s_mov_b32", "s3", 0x20) - res, scc = interp.step("s_lshl2_add_u32", "s0", "s2", "s3") - self.assertEqual(res, 0x10 * 4 + 0x20) - self.assertEqual(scc, 0) - self.assertEqual(interp.get_sgpr("s0"), 0x60) - self.assertEqual(interp.scc, 0) - - -class TestSccCarryAndWrapping(unittest.TestCase): - """Validation of SCC carry generation, overflow mechanisms, and 32-bit modulo wrapping.""" - - def test_scc_from_shifted_out_bits_exact_boundaries(self): - # High bits shifted out of 32-bit range set SCC even when 32-bit sum has no carry. - # Boundary cases: - # N=1: bit 31 (0x80000000) shifts out -> SCC=1; bit 30 (0x40000000) does not -> SCC=0. - # N=2: bit 30 (0x40000000) shifts out -> SCC=1; bit 29 (0x20000000) does not -> SCC=0. - # N=3: bit 29 (0x20000000) shifts out -> SCC=1; bit 28 (0x10000000) does not -> SCC=0. - # N=4: bit 28 (0x10000000) shifts out -> SCC=1; bit 27 (0x08000000) does not -> SCC=0. - for n in (1, 2, 3, 4): - boundary_bit = 1 << (32 - n) - sub_boundary_bit = boundary_bit >> 1 - - # Threshold bit shifted out: - want_ovf = ref_s_lshl_add_u32(n, boundary_bit, 0) - self.assertEqual(want_ovf, (0, 1)) - got_ovf = run_op(n, boundary_bit, 0, scc_in=0) - self.assertEqual(got_ovf, want_ovf) - - # One bit below threshold (no bits shifted out, so SCC=0): - want_no_ovf = ref_s_lshl_add_u32(n, sub_boundary_bit, 0) - self.assertEqual(want_no_ovf, (0x80000000, 0)) - got_no_ovf = run_op(n, sub_boundary_bit, 0, scc_in=1) - self.assertEqual(got_no_ovf, want_no_ovf) - - # Max value that does not shift out any bits: - max_no_shift = (1 << (32 - n)) - 1 - want_max_no_shift = ref_s_lshl_add_u32(n, max_no_shift, 0) - self.assertEqual(want_max_no_shift[1], 0) - got_max_no_shift = run_op(n, max_no_shift, 0, scc_in=1) - self.assertEqual(got_max_no_shift, want_max_no_shift) - - def test_scc_from_addition_overflow_exact_boundaries(self): - # Shifted value fits completely in 32 bits, but addition with S1 overflows 2^32. - for n in (1, 2, 3, 4): - sh_val = 1 << n # s0 = 1, so (s0 << n) = 1 << n - - # Exact wrap to 0: s1 = 2^32 - (1 << n) -> sum is exactly 2^32 - s1_wrap = (1 << 32) - sh_val - want_wrap = ref_s_lshl_add_u32(n, 1, s1_wrap) - self.assertEqual(want_wrap, (0, 1)) - got_wrap = run_op(n, 1, s1_wrap, scc_in=0) - self.assertEqual(got_wrap, want_wrap) - - # Maximum sum without carry: s1 = (2^32 - 1) - (1 << n) -> sum is 0xFFFFFFFF - s1_no_wrap = ((1 << 32) - 1) - sh_val - want_no_wrap = ref_s_lshl_add_u32(n, 1, s1_no_wrap) - self.assertEqual(want_no_wrap, (MASK32, 0)) - got_no_wrap = run_op(n, 1, s1_no_wrap, scc_in=1) - self.assertEqual(got_no_wrap, want_no_wrap) - - def test_both_shift_out_and_addition_overflow(self): - # Both mechanisms fire simultaneously (S0 shifts out bits AND addition carries) - for n in (1, 2, 3, 4): - s0 = MASK32 - s1 = MASK32 - want = ref_s_lshl_add_u32(n, s0, s1) - # tmp = (MASK32 << n) + MASK32 = MASK32 * ((1 << n) + 1) - expected_res = ((MASK32 << n) + MASK32) & MASK32 - self.assertEqual(want, (expected_res, 1)) - got = run_op(n, s0, s1, scc_in=0) - self.assertEqual(got, want) - - def test_scc_input_independence(self): - # SCC must be completely overwritten regardless of whether incoming SCC is 0 or 1. - test_cases = [ - (1, 0x80000000, 0), # SCC becomes 1 (shift-out) - (1, 0x1000, 0x2000), # SCC becomes 0 (no carry) - (2, 0x40000000, 0), # SCC becomes 1 - (2, 1, 0xFFFFFFFC), # SCC becomes 1 (add overflow) - (3, 0x20000000, 0), # SCC becomes 1 - (3, 0x10, 0x20), # SCC becomes 0 - (4, 0x10000000, 0), # SCC becomes 1 - (4, 0x01, 0x02), # SCC becomes 0 - ] - for n, s0, s1 in test_cases: - want = ref_s_lshl_add_u32(n, s0, s1) - with self.subTest(n=n, s0=hex(s0), s1=hex(s1)): - # Run with SCC=0 before - got0 = run_op(n, s0, s1, scc_in=0) - self.assertEqual(got0, want) - # Run with SCC=1 before - got1 = run_op(n, s0, s1, scc_in=1) - self.assertEqual(got1, want) - - def test_scc_chaining_s_addc_all_scales(self): - # Multi-word 64-bit pointer/index arithmetic across all four shift scales: - # scale index into base pointer with s_lshlN_add_u32, feed carry into high dword via s_addc_u32. - for n in (1, 2, 3, 4): - idx = 1 << (32 - n) # generates carry via shift-out - base_lo = 0x00000100 - base_hi = 0x00000005 - lines = [ - f"s_mov_b32 s2, {idx:#x}", - f"s_mov_b32 s3, {base_lo:#x}", - f"s_mov_b32 s5, {base_hi:#x}", - f"s_lshl{n}_add_u32 s0, s2, s3", - "s_addc_u32 s1, s5, 0", - "v_mov_b32 v0, s0", - "v_mov_b32 v1, s1", - ] - got = run_lines(lines) - expected_lo = base_lo # idx << n wraps low bits to 0 - expected_hi = base_hi + 1 # carry added - self.assertEqual(got, (expected_lo, expected_hi)) - - def test_deterministic_differential_fuzzing(self): - # 500 pure-Python random vectors cross-checked against 64-bit mathematical definition - rng = random.Random(0x42A5C) - for _ in range(500): - n = rng.choice((1, 2, 3, 4)) - s0 = rng.getrandbits(32) - s1 = rng.getrandbits(32) - res, scc = ref_s_lshl_add_u32(n, s0, s1) - tmp = (s0 << n) + s1 - self.assertEqual(res, tmp & MASK32) - self.assertEqual(scc, int(tmp >= TWO_POW_32)) - - # 20 diverse random vectors translated and executed in SPIR-V mini interpreter - for _ in range(20): - n = rng.choice((1, 2, 3, 4)) - s0 = rng.getrandbits(32) - s1 = rng.getrandbits(32) - scc_in = rng.getrandbits(1) - want = ref_s_lshl_add_u32(n, s0, s1) - with self.subTest(n=n, s0=hex(s0), s1=hex(s1), scc_in=scc_in): - got = run_op(n, s0, s1, scc_in) - self.assertEqual(got, want) - - -class TestShiftBoundaryAndAliasing(unittest.TestCase): - """Validation of register aliasing, literal constants, and extreme bit boundary patterns.""" - - def test_register_aliasing_dst_src0(self): - # Destination register aliases source 0 (D == S0): s_lshlN_add_u32 s0, s0, s1 - for n in (1, 2, 3, 4): - x = 0x1234 - y = 0x5678 - lines = [ - f"s_mov_b32 s0, {x:#x}", - f"s_mov_b32 s1, {y:#x}", - f"s_lshl{n}_add_u32 s0, s0, s1", - "v_mov_b32 v0, s0", - "v_mov_b32 v1, s1", - ] - got_d, got_s1 = run_lines(lines) - expected_d, _ = ref_s_lshl_add_u32(n, x, y) - self.assertEqual(got_d, expected_d) - self.assertEqual(got_s1, y) # S1 must remain unmodified - - def test_register_aliasing_dst_src1(self): - # Destination register aliases source 1 (D == S1): s_lshlN_add_u32 s0, s1, s0 - for n in (1, 2, 3, 4): - x = 0x2000 - y = 0x0042 - lines = [ - f"s_mov_b32 s1, {x:#x}", - f"s_mov_b32 s0, {y:#x}", - f"s_lshl{n}_add_u32 s0, s1, s0", - "v_mov_b32 v0, s0", - "v_mov_b32 v1, s1", - ] - got_d, got_s1 = run_lines(lines) - expected_d, _ = ref_s_lshl_add_u32(n, x, y) - self.assertEqual(got_d, expected_d) - self.assertEqual(got_s1, x) # S1 must remain unmodified - - def test_register_aliasing_src0_src1(self): - # Source 0 aliases source 1 (S0 == S1): s_lshlN_add_u32 s0, s1, s1 - # Mathematically computes s1 * ((1 << n) + 1): - # N=1: * 3; N=2: * 5; N=3: * 9; N=4: * 17 - factors = {1: 3, 2: 5, 3: 9, 4: 17} - for n in (1, 2, 3, 4): - val = 0x1111 - lines = [ - f"s_mov_b32 s1, {val:#x}", - f"s_lshl{n}_add_u32 s0, s1, s1", - "v_mov_b32 v0, s0", - "v_mov_b32 v1, s1", - ] - got_d, got_s1 = run_lines(lines) - expected_d = (val * factors[n]) & MASK32 - self.assertEqual(got_d, expected_d) - self.assertEqual(got_s1, val) - - def test_register_aliasing_three_way(self): - # Full three-way aliasing (D == S0 == S1): s_lshlN_add_u32 s0, s0, s0 - factors = {1: 3, 2: 5, 3: 9, 4: 17} - for n in (1, 2, 3, 4): - val = 0x01020304 - lines = [ - f"s_mov_b32 s0, {val:#x}", - f"s_lshl{n}_add_u32 s0, s0, s0", - "v_mov_b32 v0, s0", - "v_mov_b32 v1, 0", - ] - got_d, _ = run_lines(lines) - expected_d = (val * factors[n]) & MASK32 - self.assertEqual(got_d, expected_d) - - def test_inline_constants_and_literals(self): - # SALU supports immediate/literal constants in S0 and S1 - # Literal in S0: - got = run_lines([ - "s_mov_b32 s1, 100", - "s_lshl1_add_u32 s0, 7, s1", - "v_mov_b32 v0, s0", - "v_mov_b32 v1, 0", - ]) - self.assertEqual(got[0], 7 * 2 + 100) - - # Literal in S1: - got2 = run_lines([ - "s_mov_b32 s0, 50", - "s_lshl2_add_u32 s0, s0, 42", - "v_mov_b32 v0, s0", - "v_mov_b32 v1, 0", - ]) - self.assertEqual(got2[0], 50 * 4 + 42) - - # Negative inline constant (-1): - got3 = run_lines([ - "s_mov_b32 s1, 5", - "s_lshl3_add_u32 s0, -1, s1", - "v_mov_b32 v0, s0", - "v_mov_b32 v1, 0", - ]) - expected3, _ = ref_s_lshl_add_u32(3, -1, 5) - self.assertEqual(got3[0], expected3) - - def test_walking_bit_patterns(self): - # Walk a 1-bit through all 32 positions of S0 across all four shift scales - for n in (1, 2, 3, 4): - for k in range(32): - s0 = 1 << k - res, scc = ref_s_lshl_add_u32(n, s0, 0) - expected_shifted = (s0 << n) & MASK32 - expected_scc = 1 if (k >= (32 - n)) else 0 - self.assertEqual(res, expected_shifted) - self.assertEqual(scc, expected_scc) - - def test_alternating_bit_patterns(self): - for n in (1, 2, 3, 4): - # 0xAAAAAAAA (1010...) and 0x55555555 (0101...) - s0 = 0xAAAAAAAA - s1 = 0x55555555 - want = ref_s_lshl_add_u32(n, s0, s1) - got = run_op(n, s0, s1, scc_in=0) - self.assertEqual(got, want) - - -class TestNegativeControls(unittest.TestCase): - """Negative controls ensuring mutated arithmetic or missing overflow checks fail assertions.""" - - def test_bitwise_or_mutation_is_detected(self): - # Mutating (shifted + S1) to (shifted | S1) must be detected when bits collide - s0 = 3 - s1 = 4 - # For N=2: (3 << 2) = 12 (0b1100). S1 = 4 (0b0100). - # ADD: 12 + 4 = 16 (0b10000) - # OR: 12 | 4 = 12 (0b01100) - correct_res, _ = ref_s_lshl_add_u32(2, s0, s1) - mutated_or = ((s0 << 2) | s1) & MASK32 - self.assertEqual(correct_res, 16) - self.assertEqual(mutated_or, 12) - self.assertNotEqual(correct_res, mutated_or) - - def test_missing_shift_out_carry_mutation_is_detected(self): - # If SCC only checks (shifted + s1) > 0xFFFFFFFF and ignores shifted-out bits: - s0 = 0x80000000 - s1 = 0 - _, correct_scc = ref_s_lshl_add_u32(1, s0, s1) - # Mutated: only checks 32-bit addition carry - shifted_low = (s0 << 1) & MASK32 - mutated_scc = 1 if (shifted_low + s1 > MASK32) else 0 - self.assertEqual(correct_scc, 1) - self.assertEqual(mutated_scc, 0) - self.assertNotEqual(correct_scc, mutated_scc) - - def test_missing_addition_carry_mutation_is_detected(self): - # If SCC only checks shifted-out bits and ignores addition carry: - s0 = 1 - s1 = 0xFFFFFFFF - _, correct_scc = ref_s_lshl_add_u32(1, s0, s1) - # Mutated: only checks shifted-out bits - shifted_out = (s0 & MASK32) >> 31 - mutated_scc = 1 if (shifted_out != 0) else 0 - self.assertEqual(correct_scc, 1) - self.assertEqual(mutated_scc, 0) - self.assertNotEqual(correct_scc, mutated_scc) - - def test_shift_amount_mutation_is_detected(self): - # Mutating shift amount N to N+1 produces wrong scaled address - s0 = 10 - s1 = 5 - correct_n2, _ = ref_s_lshl_add_u32(2, s0, s1) # 10 * 4 + 5 = 45 - mutated_n3, _ = ref_s_lshl_add_u32(3, s0, s1) # 10 * 8 + 5 = 85 - self.assertEqual(correct_n2, 45) - self.assertEqual(mutated_n3, 85) - self.assertNotEqual(correct_n2, mutated_n3) - - def test_unmasked_modulo_overflow_is_detected(self): - # Failing to mask with & 0xFFFFFFFF yields values >= 2^32 - s0 = 0x80000000 - s1 = 1 - correct_res, _ = ref_s_lshl_add_u32(1, s0, s1) - unmasked = (s0 << 1) + s1 - self.assertEqual(correct_res, 1) - self.assertEqual(unmasked, (1 << 32) + 1) - self.assertNotEqual(correct_res, unmasked) - - -class LshlAddTests(unittest.TestCase): - def test_reference(self): - self.assertEqual(ref(2, 3, 4), (16, 0)) - self.assertEqual(ref(1, 0x80000000, 0), (0, 1)) # the shifted-out bit alone sets SCC - self.assertEqual(ref(4, 0x0FFFFFFF, 0x10), (0, 1)) # carry out of the addition alone - self.assertEqual(ref(3, 0x1FFFFFFF, 7), (0xFFFFFFFF, 0)) # fits exactly - - def test_values_and_scc(self): - for n in (1, 2, 3, 4): - for x in VALUES: - for y in VALUES[::3]: - want = ref(n, x, y) - with self.subTest(n=n, x=hex(x), y=hex(y)): - self.assertEqual(run_op(n, x, y, 1 - want[1]), want) - - def test_seeded(self): - rng = random.Random(0x5A) - for _ in range(40): - n, x, y = rng.randint(1, 4), rng.getrandbits(32), rng.getrandbits(32) - with self.subTest(n=n, x=hex(x), y=hex(y)): - self.assertEqual(run_op(n, x, y, rng.getrandbits(1)), ref(n, x, y)) - - def test_scc_drives_s_addc(self): - # A 64-bit index scaled by 4 into a base: the carry from s_lshl2_add_u32 feeds the high word. - got = run_lines(["s_mov_b32 s2, 0x40000001", "s_mov_b32 s3, 0xfffffffc", "s_mov_b32 s5, 7", - "s_lshl2_add_u32 s0, s2, s3", "s_addc_u32 s1, s5, 0", "v_mov_b32 v0, s0", "v_mov_b32 v1, s1"]) - self.assertEqual(got, (0, 8)) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_salu_min_max_32.py b/tests/semantic/test_salu_min_max_32.py deleted file mode 100644 index c60623250..000000000 --- a/tests/semantic/test_salu_min_max_32.py +++ /dev/null @@ -1,306 +0,0 @@ -"""Semantic interpreter tests for RDNA2 32-bit scalar integer min/max ops. - -Covers s_min_i32, s_max_i32, s_min_u32 and s_max_u32: -- Result value and SCC flag across signed and unsigned 32-bit boundaries. -- Tie semantics (SCC == 0 when S0 == S1) including downstream s_cbranch_scc1 control flow. -- Translation-time constant folding and sgpr_imm propagation across chained SALU ops. -- Mixed SGPR, inline constant and 32-bit literal operands, plus destination aliasing. -- Negative controls verifying SPIR-V signed/unsigned and strict-inequality mutations fail. - -Each case translates a hand-written pixel shader through tools/rdna2spirv.py and executes it in -tests/semantic/spirv_mini_interp.py. Standard library only; no GPU, no game files. -""" -import os -import random -import sys -import unittest - -HERE = os.path.dirname(os.path.abspath(__file__)) -ROOT = os.path.dirname(os.path.dirname(HERE)) -sys.dont_write_bytecode = True -TOOLS_DIR = os.environ.get("LEONIDA_TOOLS_DIR") or os.path.join(ROOT, "tools") -if TOOLS_DIR not in sys.path: - sys.path.insert(0, TOOLS_DIR) -if HERE not in sys.path: - sys.path.insert(0, HERE) - -import support # noqa: E402 - -OPS = ("s_min_i32", "s_max_i32", "s_min_u32", "s_max_u32") -BOUNDARY_VALUES = ( - 0x00000000, - 0x00000001, - 0x00000005, - 0x7FFFFFFE, - 0x7FFFFFFF, - 0x80000000, - 0x80000001, - 0xFFFFFFFE, - 0xFFFFFFFF, -) - - -def s32(x): - x &= 0xFFFFFFFF - return x - 0x100000000 if x & 0x80000000 else x - - -def ref_salu_minmax(op, a, b): - """Independent RDNA2 ISA model returning (dst_u32, scc).""" - ua, ub = a & 0xFFFFFFFF, b & 0xFFFFFFFF - sa, sb = s32(ua), s32(ub) - if op == "s_min_i32": - scc = 1 if sa < sb else 0 - return (ua if scc else ub), scc - if op == "s_max_i32": - scc = 1 if sa > sb else 0 - return (ua if scc else ub), scc - if op == "s_min_u32": - scc = 1 if ua < ub else 0 - return (ua if scc else ub), scc - if op == "s_max_u32": - scc = 1 if ua > ub else 0 - return (ua if scc else ub), scc - raise ValueError(f"unexpected op {op}") - - -def translate_salu(lines): - return support.translate_lines("ps_salu_min_max_32", lines) - - -def run_op(op, src0="s0", src1="s1", push=None): - lines = [ - f"{op} s4, {src0}, {src1}", - "s_cselect_b32 s5, 1, 0", - "v_mov_b32 v0, s4", - "v_mov_b32 v1, s5", - "v_mov_b32 v2, 0", - "v_mov_b32 v3, 0", - "exp mrt0 v0, v1, v2, v3 done vm", - "s_endpgm", - ] - spv = translate_salu(lines) - out = support.mrt0_words(spv, push_constants=push) - return out[0], out[1], spv - - -class SaluMinMax32Tests(unittest.TestCase): - def test_reference_sanity(self): - self.assertEqual(ref_salu_minmax("s_min_i32", 0xFFFFFFFF, 1), (0xFFFFFFFF, 1)) - self.assertEqual(ref_salu_minmax("s_max_i32", 0xFFFFFFFF, 1), (1, 0)) - self.assertEqual(ref_salu_minmax("s_min_u32", 0xFFFFFFFF, 1), (1, 0)) - self.assertEqual(ref_salu_minmax("s_max_u32", 0xFFFFFFFF, 1), (0xFFFFFFFF, 1)) - for op in OPS: - self.assertEqual(ref_salu_minmax(op, 5, 5), (5, 0)) - self.assertEqual(ref_salu_minmax(op, 0x80000000, 0x80000000), (0x80000000, 0)) - - def test_boundary_grid_values_and_scc(self): - for op in OPS: - spv = translate_salu([ - f"{op} s4, s0, s1", - "s_cselect_b32 s5, 1, 0", - "v_mov_b32 v0, s4", - "v_mov_b32 v1, s5", - "v_mov_b32 v2, 0", - "v_mov_b32 v3, 0", - "exp mrt0 v0, v1, v2, v3 done vm", - "s_endpgm", - ]) - for a in BOUNDARY_VALUES: - for b in BOUNDARY_VALUES: - with self.subTest(op=op, a=hex(a), b=hex(b)): - out = support.mrt0_words(spv, push_constants=[a, b]) - self.assertEqual((out[0], out[1]), ref_salu_minmax(op, a, b)) - - def test_cbranch_scc_on_tie_and_inequality(self): - for op in OPS: - spv = translate_salu([ - "s_mov_b32 s4, 10 ; encoding: [0x8a,0x03,0x84,0xbe]", - f"{op} s5, s0, s1 ; encoding: [0x00,0x01,0x05,0x80]", - "s_cbranch_scc1 1 ; encoding: [0x01,0x00,0x85,0xbf]", - "s_mov_b32 s4, 20 ; encoding: [0x94,0x03,0x84,0xbe]", - "v_mov_b32 v0, s5 ; encoding: [0x05,0x02,0x00,0x7e]", - "v_mov_b32 v1, s4 ; encoding: [0x04,0x02,0x00,0x7e]", - "v_mov_b32 v2, 0 ; encoding: [0x80,0x00,0x00,0x7e]", - "v_mov_b32 v3, 0 ; encoding: [0x80,0x00,0x00,0x7e]", - "exp mrt0 v0, v1, v2, v3 done vm ; encoding: [0x0f,0x08,0x00,0xf8,0x00,0x00,0x00,0x00]", - "s_endpgm ; encoding: [0x00,0x00,0x81,0xbf]", - ]) - pairs = ( - (0, 0), - (5, 5), - (0x80000000, 0x80000000), - (0xFFFFFFFF, 0xFFFFFFFF), - (0xFFFFFFFF, 1), - (1, 0xFFFFFFFF), - (0x7FFFFFFF, 0x80000000), - (0x80000000, 0x7FFFFFFF), - ) - for a, b in pairs: - with self.subTest(op=op, a=hex(a), b=hex(b)): - want_val, want_scc = ref_salu_minmax(op, a, b) - want_branch_val = 10 if want_scc else 20 - out = support.mrt0_words(spv, push_constants=[a, b]) - self.assertEqual((out[0], out[1]), (want_val, want_branch_val)) - - def test_constant_folding_and_sgpr_imm_propagation(self): - cases = ( - ("s_min_i32", "-5", "1", -5, 1), - ("s_min_i32", "5", "5", 5, 5), - ("s_max_i32", "-5", "-1", -5, -1), - ("s_max_i32", "-1", "-1", -1, -1), - ("s_min_i32", "0x80000000", "0x7fffffff", 0x80000000, 0x7FFFFFFF), - ("s_max_i32", "0x7fffffff", "-1", 0x7FFFFFFF, 0xFFFFFFFF), - ("s_min_u32", "-1", "5", 0xFFFFFFFF, 5), - ("s_max_u32", "-1", "5", 0xFFFFFFFF, 5), - ("s_min_u32", "5", "5", 5, 5), - ("s_max_u32", "0x80000000", "1", 0x80000000, 1), - ) - for op, a_tok, b_tok, a_val, b_val in cases: - with self.subTest(op=op, a=a_tok, b=b_tok): - lines = [ - f"s_mov_b32 s0, {a_tok}", - f"s_mov_b32 s1, {b_tok}", - f"{op} s4, s0, s1", - "s_cselect_b32 s5, 1, 0", - "s_add_u32 s6, s4, 7", - "v_mov_b32 v0, s4", - "v_mov_b32 v1, s5", - "v_mov_b32 v2, s6", - "v_mov_b32 v3, 0", - "exp mrt0 v0, v1, v2, v3 done vm", - "s_endpgm", - ] - spv = translate_salu(lines) - want_val, want_scc = ref_salu_minmax(op, a_val, b_val) - want_add = (want_val + 7) & 0xFFFFFFFF - out = support.mrt0_words(spv) - self.assertEqual((out[0], out[1], out[2]), (want_val, want_scc, want_add)) - if op.endswith("_i32"): - self.assertNotIn("SMin", spv) - self.assertNotIn("SMax", spv) - - # Propagated sgpr_imm from s_min_u32 / s_max_u32 eliminates runtime SMEM bounds branches. - for op, a_tok, b_tok in ( - ("s_min_u32", "64", "200"), - ("s_max_u32", "16", "64"), - ): - with self.subTest(op=op, check="smem_const_prop"): - buf_spv = translate_salu([ - "s_mov_b32 s1, 0", - "s_mov_b32 s2, 256", - f"s_mov_b32 s4, {a_tok}", - f"s_mov_b32 s5, {b_tok}", - f"{op} s6, s4, s5", - "s_buffer_load_dword s8, s[0:3], s6", - "v_mov_b32 v0, s8", - "exp mrt0 v0, v0, v0, v0 done vm", - "s_endpgm", - ]) - self.assertNotIn("OpSelectionMerge", buf_spv) - self.assertNotIn("OpBranchConditional", buf_spv) - self.assertNotIn("OpPhi", buf_spv) - - # Multi-step chain through s_min_i32 -> s_max_i32 -> s_add_u32 with constant propagation. - chain_spv = translate_salu([ - "s_mov_b32 s0, -10", - "s_mov_b32 s1, 3", - "s_mov_b32 s2, -4", - "s_min_i32 s4, s0, s1", # -10 - "s_max_i32 s5, s4, s2", # -4 - "s_cselect_b32 s6, 1, 0", # 0 (s4 < s2 -> s2 chosen) - "s_add_u32 s7, s5, 10", # 6 - "v_mov_b32 v0, s4", - "v_mov_b32 v1, s5", - "v_mov_b32 v2, s6", - "v_mov_b32 v3, s7", - "exp mrt0 v0, v1, v2, v3 done vm", - "s_endpgm", - ]) - self.assertEqual(support.mrt0_words(chain_spv), [0xFFFFFFF6, 0xFFFFFFFC, 0, 6]) - self.assertNotIn("SMin", chain_spv) - self.assertNotIn("SMax", chain_spv) - - def test_mixed_operands_and_aliasing(self): - mixed_cases = ( - ("s_min_i32", "s0", "-16", [5], ref_salu_minmax("s_min_i32", 5, 0xFFFFFFF0)), - ("s_max_i32", "-16", "s0", [0xFFFFFFE0], ref_salu_minmax("s_max_i32", 0xFFFFFFF0, 0xFFFFFFE0)), - ("s_min_u32", "s0", "0x80000000", [0x7FFFFFFF], ref_salu_minmax("s_min_u32", 0x7FFFFFFF, 0x80000000)), - ("s_max_u32", "0x80000000", "s0", [0x7FFFFFFF], ref_salu_minmax("s_max_u32", 0x80000000, 0x7FFFFFFF)), - ("s_min_i32", "0x12345678", "s0", [0x12345678], ref_salu_minmax("s_min_i32", 0x12345678, 0x12345678)), - ("s_max_u32", "s0", "0", [0], ref_salu_minmax("s_max_u32", 0, 0)), - ) - for op, src0, src1, push, want in mixed_cases: - with self.subTest(op=op, src0=src0, src1=src1): - val, scc, _ = run_op(op, src0=src0, src1=src1, push=push) - self.assertEqual((val, scc), want) - - # Destination aliasing src0, src1, or both. - a, b = 0xFFFFFFF0, 0x00000007 - for op in OPS: - want_ab = ref_salu_minmax(op, a, b) - want_aa = ref_salu_minmax(op, a, a) - for pattern, push, want in ( - (f"{op} s0, s0, s1", [a, b], want_ab), - (f"{op} s1, s0, s1", [a, b], want_ab), - (f"{op} s0, s0, s0", [a, b], want_aa), - ): - dst_reg = pattern.split()[1].rstrip(",") - spv = translate_salu([ - pattern, - "s_cselect_b32 s4, 1, 0", - f"v_mov_b32 v0, {dst_reg}", - "v_mov_b32 v1, s4", - "v_mov_b32 v2, 0", - "v_mov_b32 v3, 0", - "exp mrt0 v0, v1, v2, v3 done vm", - "s_endpgm", - ]) - with self.subTest(pattern=pattern): - out = support.mrt0_words(spv, push_constants=push) - self.assertEqual((out[0], out[1]), want) - - def test_seeded_random_cases(self): - rng = random.Random(0x534D4D33) - for op in OPS: - spv = translate_salu([ - f"{op} s4, s0, s1", - "s_cselect_b32 s5, 1, 0", - "v_mov_b32 v0, s4", - "v_mov_b32 v1, s5", - "v_mov_b32 v2, 0", - "v_mov_b32 v3, 0", - "exp mrt0 v0, v1, v2, v3 done vm", - "s_endpgm", - ]) - for i in range(48): - a = rng.getrandbits(32) - b = a if i % 8 == 0 else rng.getrandbits(32) - with self.subTest(op=op, case=i): - out = support.mrt0_words(spv, push_constants=[a, b]) - self.assertEqual((out[0], out[1]), ref_salu_minmax(op, a, b)) - - def test_negative_controls(self): - # 1. Signed s_min_i32 tie comparison mutated to OpSLessThanEqual must corrupt SCC on ties. - _, _, spv_min_i = run_op("s_min_i32", push=[5, 5]) - self.assertIn("OpSLessThan ", spv_min_i) - self.assertIn("SMin", spv_min_i) - bad_tie = spv_min_i.replace("OpSLessThan ", "OpSLessThanEqual ") - self.assertEqual(support.mrt0_words(spv_min_i, push_constants=[5, 5])[:2], [5, 0]) - self.assertNotEqual(support.mrt0_words(bad_tie, push_constants=[5, 5])[:2], [5, 0]) - - # 2. Signed SMin mutated to unsigned UMin must fail on (-5, 1). - bad_sign = spv_min_i.replace("SMin", "UMin") - self.assertEqual(support.mrt0_words(spv_min_i, push_constants=[0xFFFFFFFB, 1])[:2], [0xFFFFFFFB, 1]) - self.assertNotEqual(support.mrt0_words(bad_sign, push_constants=[0xFFFFFFFB, 1])[:2], [0xFFFFFFFB, 1]) - - # 3. Unsigned s_min_u32 comparison mutated to signed OpSLessThan must corrupt SCC on (0xFFFFFFFF, 1). - _, _, spv_min_u = run_op("s_min_u32", push=[0xFFFFFFFF, 1]) - self.assertIn("OpULessThan ", spv_min_u) - bad_ucmp = spv_min_u.replace("OpULessThan ", "OpSLessThan ") - self.assertEqual(support.mrt0_words(spv_min_u, push_constants=[0xFFFFFFFF, 1])[:2], [1, 0]) - self.assertNotEqual(support.mrt0_words(bad_ucmp, push_constants=[0xFFFFFFFF, 1])[:2], [1, 0]) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_salu_movrels.py b/tests/semantic/test_salu_movrels.py deleted file mode 100644 index cd99d2454..000000000 --- a/tests/semantic/test_salu_movrels.py +++ /dev/null @@ -1,121 +0,0 @@ -"""Semantic interpreter tests for RDNA2 s_movrels_b32 and s_movrels_b64 (relative SGPR reads through M0). - -RDNA2 ISA SOP1: s_movrels_b32 D = SGPR[S0 + M0]; s_movrels_b64 reads the pair SGPR[S0 + M0], SGPR[S0 + M0 + 1]. -SCC is not written. Each case translates a synthetic pixel shader with tools/rdna2spirv.py and runs it in -tests/semantic/spirv_mini_interp.py; results leave through exp as 16-bit halves ORed into 0x40000000. s_movreld (the -relative write) stays Unsupported. Standard library only; no GPU, no game files. -""" -import os -import struct -import sys -import tempfile -import unittest -import warnings - -HERE = os.path.dirname(os.path.abspath(__file__)) -ROOT = os.path.dirname(os.path.dirname(HERE)) -TOOLS_DIR = os.environ.get("LEONIDA_TOOLS_DIR") or os.path.join(ROOT, "tools") - -sys.dont_write_bytecode = True -sys.path.insert(0, TOOLS_DIR) -sys.path.insert(0, HERE) - -import rdna2spirv # noqa: E402 -import spirv_mini_interp as si # noqa: E402 - -STUB_DXBC = b"DXBC" + bytes(24) + struct.pack(" str: - if _TMP_DIR is None: - setUpModule() - asm = "; test_movrels\n" + "".join(f"\t{ln}\n" for ln in lines) - with open(_SRC_PATH, "w", encoding="utf-8") as f: - f.write(asm) - with warnings.catch_warnings(): - warnings.simplefilter("ignore", ResourceWarning) - return rdna2spirv.translate(_SRC_PATH) - - -def run(lines): - """Run `lines`, which leave D.lo in s10, D.hi in s11 and SCC in s12; return (D.lo, D.hi, SCC).""" - tail = ["s_cselect_b32 s12, 1, 0"] - for i, s in enumerate((10, 11)): - tail += [f"v_mov_b32 v{10 + i}, s{s}", - f"v_and_b32 v{2 * i}, 0xffff, v{10 + i}", f"v_lshrrev_b32 v{2 * i + 1}, 16, v{10 + i}", - f"v_or_b32 v{2 * i}, 0x40000000, v{2 * i}", f"v_or_b32 v{2 * i + 1}, 0x40000000, v{2 * i + 1}"] - tail += ["v_mov_b32 v4, s12", "v_or_b32 v4, 0x40000000, v4"] - spv = translate(list(lines) + tail + ["exp mrt0 v0, v1, v2, v3 vm", "exp mrt1 v4, v4, v4, v4 done vm", - "s_endpgm"]) - out = si.run_fragment(spv) - w = list(out["%out_mrt0"]) + [out["%out_mrt1"][0]] - assert all(v >> 16 == 0x4000 for v in w), [hex(v) for v in w] - return (w[0] & 0xFFFF) | (w[1] & 0xFFFF) << 16, (w[2] & 0xFFFF) | (w[3] & 0xFFFF) << 16, w[4] & 0xFFFF - - -SEED = ["s_mov_b32 s20, 0x11111111", "s_mov_b32 s21, 0x22222222", "s_mov_b32 s22, 0x33333333", - "s_mov_b32 s23, 0x44444444", "s_mov_b32 s24, 0x55555555", "s_mov_b32 s25, 0x66666666"] -WORDS = [0x11111111 * k for k in range(1, 7)] - - -class MovrelsTests(unittest.TestCase): - def test_b32_reads_s0_plus_m0(self): - for m0 in range(6): - with self.subTest(m0=m0): - got = run(SEED + [f"s_mov_b32 m0, {m0}", "s_movrels_b32 s10, s20", "s_mov_b32 s11, 0x5eed"]) - self.assertEqual(got[:2], (WORDS[m0], 0x5eed)) - - def test_b32_base_register_and_m0_add(self): - # S0 = s22, M0 = 3: SGPR[25]. - self.assertEqual(run(SEED + ["s_mov_b32 m0, 3", "s_movrels_b32 s10, s22", "s_mov_b32 s11, 0"])[0], WORDS[5]) - - def test_b64_reads_the_pair(self): - for m0 in (0, 1, 2, 4): - with self.subTest(m0=m0): - got = run(SEED + [f"s_mov_b32 m0, {m0}", "s_movrels_b64 s[10:11], s[20:21]"]) - self.assertEqual(got[:2], (WORDS[m0], WORDS[m0 + 1])) - - def test_m0_from_a_register_and_scc_kept(self): - for poison in (0, 1): - with self.subTest(poison=poison): - got = run(SEED + ["s_mov_b32 s5, 4", "s_mov_b32 m0, s5", POISON_SCC[poison], - "s_movrels_b32 s10, s20", "s_mov_b32 s11, 0"]) - self.assertEqual(got, (WORDS[4], 0, 1 - poison)) - - def test_destination_overlapping_the_source(self): - # D = s[21:22] overlaps the pair read (s[21:22] with M0 = 0 -> itself; M0 = 1 -> s[22:23]). - got = run(SEED + ["s_mov_b32 m0, 1", "s_movrels_b64 s[21:22], s[21:22]", "s_mov_b32 s10, s21", - "s_mov_b32 s11, s22"]) - self.assertEqual(got[:2], (WORDS[2], WORDS[3])) - - def test_rejected_forms(self): - for lines in (["s_movreld_b32 s10, s20"], ["s_movrels_b32 s10, 5"], ["s_movrels_b64 s10, s[20:21]"]): - with self.subTest(lines=lines): - with self.assertRaises(rdna2spirv.Unsupported): - translate(lines + ["exp mrt0 v0, v0, v0, v0 done vm", "s_endpgm"]) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_salu_movrels_lane_mask.py b/tests/semantic/test_salu_movrels_lane_mask.py deleted file mode 100644 index 15a791609..000000000 --- a/tests/semantic/test_salu_movrels_lane_mask.py +++ /dev/null @@ -1,117 +0,0 @@ -"""s_movrels_b32 / s_movrels_b64 reading an SGPR that holds a lane mask (#1548, SHADER-284). - -A lane-mask SGPR (a saved EXEC, a v_cmp result) holds only this lane's bit in the translation, so a plain dynamic -load copied that bit as data: with EXEC saved as 5, `s_movrels_b32 s12, s10` then `s_bcnt1_i32_b32 s13, s12` gave -32 where the ISA gives 2. The translator now collects the whole wave's mask word for every mask SGPR and uses it -when the index lands there. Each case runs every lane of a synthetic compute shader in -spirv_mini_interp.run_workgroup (wave32 and native wave64) and stores D and the bit count per lane. Standard -library only; no GPU, no game files. -""" -import gc -import os -import struct -import sys -import tempfile -import unittest -import warnings - -HERE = os.path.dirname(os.path.abspath(__file__)) -ROOT = os.path.dirname(os.path.dirname(HERE)) -TOOLS_DIR = os.environ.get("LEONIDA_TOOLS_DIR") or os.path.join(ROOT, "tools") - -sys.dont_write_bytecode = True -if HERE not in sys.path: - sys.path.insert(0, HERE) -if TOOLS_DIR not in sys.path: - sys.path.insert(0, TOOLS_DIR) - -import rdna2spirv # noqa: E402 -import spirv_mini_interp as si # noqa: E402 - -STUB_DXBC = b"DXBC" + bytes(24) + struct.pack("> 16), -} -VALUES = [0, 0xFFFFFFFF, 0x0000FFFF, 0xFFFF0000, 0x12345678, 0x9ABCDEF0, 0x80008000, 0x00010001] - -_TMP_DIR = None -_SRC_PATH = None - - -def setUpModule(): - global _TMP_DIR, _SRC_PATH - _TMP_DIR = tempfile.TemporaryDirectory() - disasm_dir = os.path.join(_TMP_DIR.name, "disasm") - os.mkdir(disasm_dir) - _SRC_PATH = os.path.join(disasm_dir, "ps_salu_pack.s") - with open(os.path.join(_TMP_DIR.name, "ps_salu_pack.dxbc"), "wb") as f: - f.write(STUB_DXBC) - - -def tearDownModule(): - global _TMP_DIR - if _TMP_DIR is not None: - _TMP_DIR.cleanup() - _TMP_DIR = None - - -def run_lines(lines) -> tuple: - """Run the lines, export v0 and v1, return those two words.""" - if _TMP_DIR is None: - setUpModule() - asm = "; test_salu_pack\n" + "".join(f"\t{ln}\n" for ln in lines) + "\texp mrt0 v0, v1, v0, v0 done vm\n\ts_endpgm\n" - with open(_SRC_PATH, "w", encoding="utf-8") as f: - f.write(asm) - with warnings.catch_warnings(): - warnings.simplefilter("ignore", ResourceWarning) - spv = rdna2spirv.translate(_SRC_PATH) - return tuple(si.run_fragment(spv)["%out_mrt0"][:2]) - - -def run_op(op: str, x: int, y: int, scc_in: int) -> tuple: - """SCC = scc_in, then s0 = op(s2, s3); return (s0, SCC after).""" - return run_lines([f"s_mov_b32 s2, {x:#x}", f"s_mov_b32 s3, {y:#x}", f"s_mov_b32 s4, {scc_in}", "s_cmp_eq_u32 s4, 1", - f"{op} s0, s2, s3", "s_cselect_b32 s1, 1, 0", "v_mov_b32 v0, s0", "v_mov_b32 v1, s1"]) - - -class PackTests(unittest.TestCase): - def test_reference(self): - self.assertEqual(OPS["s_pack_ll_b32_b16"](0x11112222, 0x33334444), 0x44442222) - self.assertEqual(OPS["s_pack_lh_b32_b16"](0x11112222, 0x33334444), 0x33332222) - self.assertEqual(OPS["s_pack_hh_b32_b16"](0x11112222, 0x33334444), 0x33331111) - - def test_values_and_scc_kept(self): - for op, fn in OPS.items(): - for x in VALUES: - for y in VALUES: - for scc_in in (0, 1): - with self.subTest(op=op, x=hex(x), y=hex(y), scc=scc_in): - self.assertEqual(run_op(op, x, y, scc_in), (fn(x, y), scc_in)) - - def test_seeded(self): - rng = random.Random(0xB16) - for _ in range(30): - op = rng.choice(list(OPS)) - x, y = rng.getrandbits(32), rng.getrandbits(32) - with self.subTest(op=op, x=hex(x), y=hex(y)): - self.assertEqual(run_op(op, x, y, 0)[0], OPS[op](x, y)) - - def test_literal_and_inline_operands(self): - got = run_lines(["s_pack_ll_b32_b16 s0, 0x1234, -1", "s_pack_hh_b32_b16 s1, 0xabcd0000, 0x5678ffff", - "v_mov_b32 v0, s0", "v_mov_b32 v1, s1"]) - self.assertEqual(got, (0xFFFF1234, 0x5678ABCD)) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_salu_pack_b32.py b/tests/semantic/test_salu_pack_b32.py deleted file mode 100644 index 77295eb58..000000000 --- a/tests/semantic/test_salu_pack_b32.py +++ /dev/null @@ -1,371 +0,0 @@ -"""Semantic interpreter tests for RDNA2 scalar 16-bit pack instructions. - -This suite tests the following SOP2 scalar ALU instructions: - - s_pack_ll_b32_b16 D, S0, S1: D = (S1[15:0] << 16) | S0[15:0] - - s_pack_lh_b32_b16 D, S0, S1: D = (S1[31:16] << 16) | S0[15:0] - - s_pack_hh_b32_b16 D, S0, S1: D = (S1[31:16] << 16) | S0[31:16] - -Hardware semantics (RDNA2 ISA / SOP2 encoding): - - D[15:0] receives a 16-bit halfword selected from source S0: - - 'l' in first position: selects S0[15:0] (bits 15..0) - - 'h' in first position: selects S0[31:16] (bits 31..16) - - D[31:16] receives a 16-bit halfword selected from source S1: - - 'l' in second position: selects S1[15:0] (bits 15..0) - - 'h' in second position: selects S1[31:16] (bits 31..16) - - The scalar condition code (SCC) is NOT written and remains unaltered. - -Shaders are translated via tools/rdna2spirv.py and executed using -tests/semantic/spirv_mini_interp.py against a plain-Python reference oracle. - -Standard library only; zero game data, zero proprietary assets. -""" -from __future__ import annotations - -import os -import random -import struct -import sys -import tempfile -import unittest -import warnings - -HERE = os.path.dirname(os.path.abspath(__file__)) -ROOT = os.path.dirname(os.path.dirname(HERE)) -TOOLS_DIR = os.environ.get("LEONIDA_TOOLS_DIR") or os.path.join(ROOT, "tools") - -sys.dont_write_bytecode = True -sys.path.insert(0, TOOLS_DIR) -sys.path.insert(0, HERE) - -import rdna2spirv # noqa: E402 -import spirv_mini_interp as si # noqa: E402 - -MASK32 = 0xFFFFFFFF -MASK16 = 0xFFFF -STUB_DXBC = b"DXBC" + bytes(24) + struct.pack(" int: - """Reference oracle for s_pack_ll_b32_b16: D = (S1[15:0] << 16) | S0[15:0].""" - return (((s1 & MASK16) << 16) | (s0 & MASK16)) & MASK32 - - -def ref_pack_lh_b32_b16(s0: int, s1: int) -> int: - """Reference oracle for s_pack_lh_b32_b16: D = (S1[31:16] << 16) | S0[15:0].""" - return ((s1 & (MASK16 << 16)) | (s0 & MASK16)) & MASK32 - - -def ref_pack_hh_b32_b16(s0: int, s1: int) -> int: - """Reference oracle for s_pack_hh_b32_b16: D = (S1[31:16] << 16) | S0[31:16].""" - return ((s1 & (MASK16 << 16)) | ((s0 >> 16) & MASK16)) & MASK32 - - -PACK_OPS = { - "s_pack_ll_b32_b16": ref_pack_ll_b32_b16, - "s_pack_lh_b32_b16": ref_pack_lh_b32_b16, - "s_pack_hh_b32_b16": ref_pack_hh_b32_b16, -} - - -def ref_pack(op: str, s0: int, s1: int) -> int: - """Dispatch to the corresponding reference oracle function.""" - if op not in PACK_OPS: - raise ValueError(f"Unknown pack opcode: {op}") - return PACK_OPS[op](s0, s1) - - -_TMP_DIR: tempfile.TemporaryDirectory | None = None -_SRC_PATH: str | None = None - - -def setUpModule() -> None: - global _TMP_DIR, _SRC_PATH - _TMP_DIR = tempfile.TemporaryDirectory() - disasm_dir = os.path.join(_TMP_DIR.name, "disasm") - os.mkdir(disasm_dir) - _SRC_PATH = os.path.join(disasm_dir, "ps_salu_pack_b32.s") - dxbc_path = os.path.join(_TMP_DIR.name, "ps_salu_pack_b32.dxbc") - with open(dxbc_path, "wb") as f: - f.write(STUB_DXBC) - - -def tearDownModule() -> None: - global _TMP_DIR - if _TMP_DIR is not None: - try: - _TMP_DIR.cleanup() - except Exception: - pass - _TMP_DIR = None - - -def run_assembly_lines(lines: list[str]) -> tuple[int, int]: - """Assemble synthetic shader lines, run via mini interpreter, return (v0, v1).""" - global _TMP_DIR, _SRC_PATH - if _TMP_DIR is None: - setUpModule() - assert _SRC_PATH is not None - asm = ( - "; test_salu_pack_b32\n" - + "".join(f"\t{ln}\n" for ln in lines) - + "\texp mrt0 v0, v1, v0, v0 done vm\n" - + "\ts_endpgm\n" - ) - with open(_SRC_PATH, "w", encoding="utf-8") as f: - f.write(asm) - with warnings.catch_warnings(): - warnings.simplefilter("ignore", ResourceWarning) - spv = rdna2spirv.translate(_SRC_PATH) - out = si.run_fragment(spv) - mrt0 = out["%out_mrt0"] - return (mrt0[0], mrt0[1]) - - -def run_pack_op(op: str, s0: int, s1: int, scc_in: int = 0) -> tuple[int, int]: - """Execute pack operation with SCC pre-condition, return (result, scc_after).""" - lines = [ - f"s_mov_b32 s2, {s0 & MASK32:#x}", - f"s_mov_b32 s3, {s1 & MASK32:#x}", - f"s_mov_b32 s4, {scc_in}", - "s_cmp_eq_u32 s4, 1", - f"{op} s0, s2, s3", - "s_cselect_b32 s1, 1, 0", - "v_mov_b32 v0, s0", - "v_mov_b32 v1, s1", - ] - return run_assembly_lines(lines) - - -class TestSaluPackB32ReferenceOracle(unittest.TestCase): - """Unit tests verifying the Python reference oracle against hand-computed values.""" - - def test_oracle_hand_computed_bit_patterns(self): - s0 = 0x12345678 # S0: hi=0x1234, lo=0x5678 - s1 = 0x9ABCDEF0 # S1: hi=0x9ABC, lo=0xDEF0 - - # s_pack_ll_b32_b16: hi=S1[15:0]=0xDEF0, lo=S0[15:0]=0x5678 - self.assertEqual(ref_pack_ll_b32_b16(s0, s1), 0xDEF05678) - self.assertEqual(ref_pack("s_pack_ll_b32_b16", s0, s1), 0xDEF05678) - - # s_pack_lh_b32_b16: hi=S1[31:16]=0x9ABC, lo=S0[15:0]=0x5678 - self.assertEqual(ref_pack_lh_b32_b16(s0, s1), 0x9ABC5678) - self.assertEqual(ref_pack("s_pack_lh_b32_b16", s0, s1), 0x9ABC5678) - - # s_pack_hh_b32_b16: hi=S1[31:16]=0x9ABC, lo=S0[31:16]=0x1234 - self.assertEqual(ref_pack_hh_b32_b16(s0, s1), 0x9ABC1234) - self.assertEqual(ref_pack("s_pack_hh_b32_b16", s0, s1), 0x9ABC1234) - - def test_oracle_halfword_extraction_and_masking(self): - # High half of s0 must not affect s_pack_ll or s_pack_lh - val_a = ref_pack_ll_b32_b16(0x0000BEEF, 0x0000CAFE) - val_b = ref_pack_ll_b32_b16(0xFFFFBEEF, 0x0000CAFE) - self.assertEqual(val_a, val_b) - self.assertEqual(val_a, 0xCAFEBEEF) - - # Low half of s0 must not affect s_pack_hh - val_h1 = ref_pack_hh_b32_b16(0x11110000, 0x22220000) - val_h2 = ref_pack_hh_b32_b16(0x1111FFFF, 0x22220000) - self.assertEqual(val_h1, val_h2) - self.assertEqual(val_h1, 0x22221111) - - # Low half of s1 must not affect s_pack_lh or s_pack_hh - val_lh1 = ref_pack_lh_b32_b16(0x00003333, 0x44440000) - val_lh2 = ref_pack_lh_b32_b16(0x00003333, 0x4444FFFF) - self.assertEqual(val_lh1, val_lh2) - self.assertEqual(val_lh1, 0x44443333) - - def test_oracle_32bit_clamping(self): - # Oracle handles operands exceeding 32-bit representations cleanly - res = ref_pack_ll_b32_b16(0x1_0000_1234, 0x2_0000_5678) - self.assertEqual(res, 0x56781234) - - def test_oracle_unknown_opcode_rejection(self): - with self.assertRaises(ValueError): - ref_pack("s_pack_hl_b32_b16", 0, 0) - - -class TestSaluPackB32ExecutionBasics(unittest.TestCase): - """Basic semantic execution tests validating rdna2spirv and spirv_mini_interp.""" - - def test_basic_execution_matches_oracle(self): - s0, s1 = 0xA1B2C3D4, 0xE5F60718 - for op in PACK_OPS: - expected = ref_pack(op, s0, s1) - got, _ = run_pack_op(op, s0, s1, scc_in=0) - self.assertEqual(got, expected, f"Failed on op={op}") - - -class TestSaluPackB32PermutationsAndRouting(unittest.TestCase): - """Exhaustive testing of halfword permutations, register routing, and constants.""" - - def test_native_halfword_permutation_matrix(self): - # S0: hi=0x1111, lo=0x2222; S1: hi=0x3333, lo=0x4444 - s0 = 0x11112222 - s1 = 0x33334444 - - # s_pack_ll_b32_b16: S1[15:0] as hi, S0[15:0] as lo -> 0x44442222 - res_ll, _ = run_pack_op("s_pack_ll_b32_b16", s0, s1) - self.assertEqual(res_ll, 0x44442222) - self.assertEqual(res_ll, ref_pack_ll_b32_b16(s0, s1)) - - # s_pack_lh_b32_b16: S1[31:16] as hi, S0[15:0] as lo -> 0x33332222 - res_lh, _ = run_pack_op("s_pack_lh_b32_b16", s0, s1) - self.assertEqual(res_lh, 0x33332222) - self.assertEqual(res_lh, ref_pack_lh_b32_b16(s0, s1)) - - # s_pack_hh_b32_b16: S1[31:16] as hi, S0[31:16] as lo -> 0x33331111 - res_hh, _ = run_pack_op("s_pack_hh_b32_b16", s0, s1) - self.assertEqual(res_hh, 0x33331111) - self.assertEqual(res_hh, ref_pack_hh_b32_b16(s0, s1)) - - def test_halfword_permutation_matrix_second_vector(self): - # S0: hi=0xAAAA, lo=0x5555; S1: hi=0xCCCC, lo=0x3333 - s0 = 0xAAAA5555 - s1 = 0xCCCC3333 - - res_ll, _ = run_pack_op("s_pack_ll_b32_b16", s0, s1) - self.assertEqual(res_ll, 0x33335555) - self.assertEqual(res_ll, ref_pack_ll_b32_b16(s0, s1)) - - res_lh, _ = run_pack_op("s_pack_lh_b32_b16", s0, s1) - self.assertEqual(res_lh, 0xCCCC5555) - self.assertEqual(res_lh, ref_pack_lh_b32_b16(s0, s1)) - - res_hh, _ = run_pack_op("s_pack_hh_b32_b16", s0, s1) - self.assertEqual(res_hh, 0xCCCCAAAA) - self.assertEqual(res_hh, ref_pack_hh_b32_b16(s0, s1)) - - def test_synthesized_hl_packing_via_operand_swap(self): - # RDNA2 lacks an s_pack_hl instruction. HL packing (S0[31:16] as hi, S1[15:0] as lo) - # is synthesized by executing s_pack_lh with swapped source registers: - # s_pack_lh D, S1, S0 places S1[15:0] in D[15:0] and S0[31:16] in D[31:16]. - s0 = 0x11112222 - s1 = 0x33334444 - lines = [ - f"s_mov_b32 s2, {s0:#x}", - f"s_mov_b32 s3, {s1:#x}", - "s_pack_lh_b32_b16 s0, s3, s2", - "v_mov_b32 v0, s0", - "v_mov_b32 v1, 0", - ] - got, _ = run_assembly_lines(lines) - self.assertEqual(got, 0x11114444) - - def test_register_routing_different_sgpr_banks(self): - # Test routing through non-contiguous and higher-index SGPRs - lines = [ - "s_mov_b32 s6, 0x01234567", - "s_mov_b32 s8, 0x89ABCDEF", - "s_pack_ll_b32_b16 s10, s6, s8", - "s_pack_lh_b32_b16 s12, s6, s8", - "s_pack_hh_b32_b16 s14, s6, s8", - "v_mov_b32 v0, s10", - "v_mov_b32 v1, s12", - ] - res0, res1 = run_assembly_lines(lines) - self.assertEqual(res0, 0xCDEF4567) - self.assertEqual(res1, 0x89AB4567) - - def test_scc_preservation_across_all_opcodes(self): - # Test that both SCC=0 and SCC=1 are unmodified by all three pack opcodes - for op in PACK_OPS: - for scc_in in (0, 1): - with self.subTest(op=op, scc_in=scc_in): - _, scc_out = run_pack_op(op, 0x12345678, 0x9ABCDEF0, scc_in=scc_in) - self.assertEqual(scc_out, scc_in, f"SCC corrupted for {op}: expected {scc_in}, got {scc_out}") - - def test_literal_and_inline_constant_operands(self): - lines = [ - "s_mov_b32 s2, 0x11112222", - "s_pack_ll_b32_b16 s0, 0x1234, -1", - "s_pack_lh_b32_b16 s1, s2, 0x56780000", - "v_mov_b32 v0, s0", - "v_mov_b32 v1, s1", - ] - res0, res1 = run_assembly_lines(lines) - self.assertEqual(res0, 0xFFFF1234) - self.assertEqual(res1, 0x56782222) - - lines2 = [ - "s_pack_hh_b32_b16 s0, 0xABCD0000, 0x12340000", - "s_pack_ll_b32_b16 s1, 0, 1", - "v_mov_b32 v0, s0", - "v_mov_b32 v1, s1", - ] - res2_0, res2_1 = run_assembly_lines(lines2) - self.assertEqual(res2_0, 0x1234ABCD) - self.assertEqual(res2_1, 0x00010000) - - def test_seeded_pseudo_random_combinations(self): - rng = random.Random(0x5A1C) - for i in range(15): - op = rng.choice(list(PACK_OPS.keys())) - s0 = rng.getrandbits(32) - s1 = rng.getrandbits(32) - scc_in = i % 2 - expected = ref_pack(op, s0, s1) - with self.subTest(i=i, op=op, s0=hex(s0), s1=hex(s1), scc=scc_in): - got, scc_out = run_pack_op(op, s0, s1, scc_in=scc_in) - self.assertEqual(got, expected) - self.assertEqual(scc_out, scc_in) - - -class TestSaluPackB32BoundariesAliasingAndNegativeControls(unittest.TestCase): - """Tests boundary extremes (zeros, ones, sign bits), register aliasing, and negative controls.""" - - def test_boundary_extremes_zero_and_max(self): - extremes = [0x00000000, 0x0000FFFF, 0xFFFF0000, 0xFFFFFFFF, 0x80007FFF, 0x7FFF8000] - for s0 in extremes: - for s1 in extremes: - for op in PACK_OPS: - expected = ref_pack(op, s0, s1) - got, _ = run_pack_op(op, s0, s1) - self.assertEqual(got, expected, f"Failed at extreme s0={s0:#x}, s1={s1:#x}, op={op}") - - def test_register_aliasing_same_source_registers(self): - # S0 and S1 refer to the exact same scalar register - s0 = 0x12345678 - for op in PACK_OPS: - expected = ref_pack(op, s0, s0) - lines = [ - f"s_mov_b32 s2, {s0:#x}", - f"{op} s0, s2, s2", - "v_mov_b32 v0, s0", - "v_mov_b32 v1, 0", - ] - got, _ = run_assembly_lines(lines) - self.assertEqual(got, expected, f"Failed aliasing test on op={op}") - - def test_register_aliasing_destination_equals_source(self): - # Destination register is the same as source register S0 or S1 - lines = [ - "s_mov_b32 s2, 0x12345678", - "s_mov_b32 s3, 0x9ABCDEF0", - "s_pack_ll_b32_b16 s2, s2, s3", # D is S0 (s2) - "v_mov_b32 v0, s2", - "v_mov_b32 v1, 0", - ] - got, _ = run_assembly_lines(lines) - self.assertEqual(got, 0xDEF05678) - - lines2 = [ - "s_mov_b32 s2, 0x12345678", - "s_mov_b32 s3, 0x9ABCDEF0", - "s_pack_ll_b32_b16 s3, s2, s3", # D is S1 (s3) - "v_mov_b32 v0, s3", - "v_mov_b32 v1, 0", - ] - got2, _ = run_assembly_lines(lines2) - self.assertEqual(got2, 0xDEF05678) - - def test_negative_controls_invalid_instruction_or_malformed_encoding(self): - # Verify that malformed / unknown instruction mnemonics raise translation/assembly errors - bad_lines = [ - "s_pack_hl_b32_b16 s0, s2, s3", - ] - with self.assertRaises(Exception): - run_assembly_lines(bad_lines) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_salu_quadmask_bitreplicate.py b/tests/semantic/test_salu_quadmask_bitreplicate.py deleted file mode 100644 index 9fa67cbbf..000000000 --- a/tests/semantic/test_salu_quadmask_bitreplicate.py +++ /dev/null @@ -1,169 +0,0 @@ -"""Semantic interpreter tests for RDNA2 s_quadmask_b32, s_quadmask_b64 and s_bitreplicate_b64_b32 on scalar data. - -RDNA2 ISA SOP1: - * s_quadmask_b32: D[i] = OR of S0[4i+3:4i] for i in 0..7, the rest of D is 0; SCC = D != 0. - * s_quadmask_b64: the same for the 16 quads of the 64-bit S0, D[63:16] = 0; SCC = D != 0. - * s_bitreplicate_b64_b32: D[2i+1] = D[2i] = S0[i] for i in 0..31; SCC is not written. - -Each case translates a synthetic pixel shader with tools/rdna2spirv.py and runs it in -tests/semantic/spirv_mini_interp.py. Every result word leaves through exp as two 16-bit halves ORed into -0x40000000, so no export channel is a NaN or denormal pattern that a float round trip could change. A lane-mask -source or destination stays Unsupported: one invocation holds only its own lane's bit. -""" -import os -import random -import struct -import sys -import tempfile -import unittest -import warnings - -HERE = os.path.dirname(os.path.abspath(__file__)) -ROOT = os.path.dirname(os.path.dirname(HERE)) -TOOLS_DIR = os.environ.get("LEONIDA_TOOLS_DIR") or os.path.join(ROOT, "tools") - -sys.dont_write_bytecode = True -sys.path.insert(0, TOOLS_DIR) -sys.path.insert(0, HERE) - -import rdna2spirv # noqa: E402 -import spirv_mini_interp as si # noqa: E402 - -M32 = 0xFFFFFFFF -M64 = (1 << 64) - 1 -STUB_DXBC = b"DXBC" + bytes(24) + struct.pack(" int: - return sum(1 << i for i in range(quads) if (x >> (4 * i)) & 0xF) - - -def bitreplicate(x: int) -> int: - return sum(3 << (2 * i) for i in range(32) if (x >> i) & 1) - - -_TMP_DIR = None -_SRC_PATH = None - - -def setUpModule(): - global _TMP_DIR, _SRC_PATH - _TMP_DIR = tempfile.TemporaryDirectory() - disasm_dir = os.path.join(_TMP_DIR.name, "disasm") - os.mkdir(disasm_dir) - _SRC_PATH = os.path.join(disasm_dir, "ps_quadmask.s") - with open(os.path.join(_TMP_DIR.name, "ps_quadmask.dxbc"), "wb") as f: - f.write(STUB_DXBC) - - -def tearDownModule(): - global _TMP_DIR - if _TMP_DIR is not None: - _TMP_DIR.cleanup() - _TMP_DIR = None - - -def translate(lines) -> str: - if _TMP_DIR is None: - setUpModule() - asm = "; test_quadmask\n" + "".join(f"\t{ln}\n" for ln in lines) - with open(_SRC_PATH, "w", encoding="utf-8") as f: - f.write(asm) - with warnings.catch_warnings(): - warnings.simplefilter("ignore", ResourceWarning) - return rdna2spirv.translate(_SRC_PATH) - - -def run(lines): - """Run `lines`, which leave D.lo in s10, D.hi in s11 and SCC in s12; return (D.lo, D.hi, SCC).""" - tail = ["s_cselect_b32 s12, 1, 0"] - for i, s in enumerate((10, 11)): - tail += [f"v_mov_b32 v{10 + i}, s{s}", - f"v_and_b32 v{2 * i}, 0xffff, v{10 + i}", f"v_lshrrev_b32 v{2 * i + 1}, 16, v{10 + i}", - f"v_or_b32 v{2 * i}, 0x40000000, v{2 * i}", f"v_or_b32 v{2 * i + 1}, 0x40000000, v{2 * i + 1}"] - tail += ["v_mov_b32 v4, s12", "v_or_b32 v4, 0x40000000, v4"] - spv = translate(list(lines) + tail + ["exp mrt0 v0, v1, v2, v3 vm", "exp mrt1 v4, v4, v4, v4 done vm", - "s_endpgm"]) - out = si.run_fragment(spv) - w = list(out["%out_mrt0"]) + [out["%out_mrt1"][0]] - assert all(v >> 16 == 0x4000 for v in w), [hex(v) for v in w] - return (w[0] & 0xFFFF) | (w[1] & 0xFFFF) << 16, (w[2] & 0xFFFF) | (w[3] & 0xFFFF) << 16, w[4] & 0xFFFF - - -def load64(reg: int, v: int): - return [f"s_mov_b32 s{reg}, {v & M32:#x}", f"s_mov_b32 s{reg + 1}, {v >> 32:#x}"] - - -VALUES32 = [0, 1, 0xF, 0x10, 0x80000000, 0x10000000, 0x01020408, 0x12345678, 0xF0F0F0F0, 0x0F0F0F0F, 0x88888888, - 0x00010000, 0xFFFF, 0xFFFF0000, M32] -VALUES64 = [0, 1, 1 << 63, 1 << 32, 0x00000001_00000000, 0x80000000_00000001, 0x12345678_9ABCDEF0, - 0xF0F0F0F0_0F0F0F0F, 0x00000000_FFFFFFFF, 0xFFFFFFFF_00000000, M64] - - -class QuadmaskBitreplicateTests(unittest.TestCase): - def test_reference(self): - self.assertEqual(quadmask(0x01020408, 8), 0x55) - self.assertEqual(quadmask(0x80000000, 8), 0x80) - self.assertEqual(quadmask(1 << 63, 16), 0x8000) - self.assertEqual(bitreplicate(0x80000001), 0xC0000000_00000003) - self.assertEqual(bitreplicate(0x00010000), 1 << 32 | 1 << 33) - - def test_quadmask_b32(self): - for x in VALUES32: - for poison in (0, 1): - with self.subTest(x=hex(x), poison=poison): - want = quadmask(x, 8) - got = run([f"s_mov_b32 s2, {x:#x}", "s_mov_b32 s11, 0x5eed", POISON_SCC[poison], - "s_quadmask_b32 s10, s2"]) - self.assertEqual(got, (want, 0x5eed, int(want != 0))) - - def test_quadmask_b64(self): - for x in VALUES64: - for poison in (0, 1): - with self.subTest(x=hex(x), poison=poison): - want = quadmask(x, 16) - got = run(load64(2, x) + [POISON_SCC[poison], "s_quadmask_b64 s[10:11], s[2:3]"]) - self.assertEqual(got, (want, 0, int(want != 0))) - - def test_bitreplicate_keeps_scc(self): - for x in VALUES32: - for poison in (0, 1): - with self.subTest(x=hex(x), poison=poison): - want = bitreplicate(x) - got = run([f"s_mov_b32 s2, {x:#x}", POISON_SCC[poison], "s_bitreplicate_b64_b32 s[10:11], s2"]) - self.assertEqual(got, (want & M32, want >> 32, 1 - poison)) - - def test_immediates_and_aliasing(self): - # A b64 inline constant is sign-extended: -1 has all 16 quads set. - self.assertEqual(run(["s_quadmask_b64 s[10:11], -1"]), (0xFFFF, 0, 1)) - self.assertEqual(run(["s_quadmask_b32 s10, 0x80000010", "s_mov_b32 s11, 0"]), (0x82, 0, 1)) - self.assertEqual(run([POISON_SCC[0], "s_bitreplicate_b64_b32 s[10:11], 0x80000001"]), (3, 0xC0000000, 1)) - # Destination overlapping the source: all of S0 is read first. - self.assertEqual(run(["s_mov_b32 s10, 0x12345678", POISON_SCC[0], "s_bitreplicate_b64_b32 s[10:11], s10"]), - (bitreplicate(0x12345678) & M32, bitreplicate(0x12345678) >> 32, 1)) - self.assertEqual(run(load64(10, 0x10000000_00000001) + ["s_quadmask_b64 s[10:11], s[10:11]"]), - (0x8001, 0, 1)) - - def test_seeded(self): - rng = random.Random(0x0AD) - for _ in range(20): - x = rng.getrandbits(64) & rng.getrandbits(64) & rng.getrandbits(64) - with self.subTest(x=hex(x)): - self.assertEqual(run(load64(2, x) + ["s_quadmask_b64 s[10:11], s[2:3]"])[:2], (quadmask(x, 16), 0)) - lo = x & M32 - self.assertEqual(run([f"s_mov_b32 s2, {lo:#x}", "s_bitreplicate_b64_b32 s[10:11], s2"])[:2], - (bitreplicate(lo) & M32, bitreplicate(lo) >> 32)) - - def test_lane_masks_rejected(self): - for lines in (["v_cmp_gt_u32_e32 vcc, 5, v0", "s_quadmask_b64 s[10:11], vcc"], - ["s_quadmask_b32 s10, exec_lo"], - ["s_quadmask_b64 exec, s[2:3]"], - ["v_cmp_gt_u32_e64 s[2:3], 5, v0", "s_quadmask_b64 s[10:11], s[2:3]"]): - with self.subTest(lines=lines): - with self.assertRaises(rdna2spirv.Unsupported): - translate(lines + ["exp mrt0 v0, v0, v0, v0 done vm", "s_endpgm"]) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_salu_sext_flbit.py b/tests/semantic/test_salu_sext_flbit.py deleted file mode 100644 index a4a94725a..000000000 --- a/tests/semantic/test_salu_sext_flbit.py +++ /dev/null @@ -1,686 +0,0 @@ -"""Semantic interpreter tests for RDNA2 s_sext_i32_i8, s_sext_i32_i16, and s_flbit_i32. - -RDNA2 scalar ALU operations covered: - - s_sext_i32_i8 D, S0: - Sign-extends 8-bit signed integer in S0[7:0] to 32-bit signed integer in D. - Upper source bits S0[31:8] are completely ignored. - Destination D is in range [-128, 127] (0xFFFFFF80 .. 0x0000007F). - Scalar Condition Code (SCC) is preserved (SCC is not written). - - s_sext_i32_i16 D, S0: - Sign-extends 16-bit signed integer in S0[15:0] to 32-bit signed integer in D. - Upper source bits S0[31:16] are completely ignored. - Destination D is in range [-32768, 32767] (0xFFFF8000 .. 0x00007FFF). - Scalar Condition Code (SCC) is preserved (SCC is not written). - - s_flbit_i32 D, S0: - Find first bit from MSB down to LSB before the first bit that differs - from the sign bit (scalar equivalent of v_ffbh_i32 / FindSMsb). - Returns bit count from MSB (31 - bit_index) or -1 (0xFFFFFFFF) if all bits - match the sign bit (0 or -1). - Scalar Condition Code (SCC) is preserved (SCC is not written). - - s_flbit_i32_b32 D, S0: - Count leading zeros from MSB down to LSB (unsigned bit scan). - Returns bit count from MSB (31 - highest_set_bit) or -1 (0xFFFFFFFF) on zero. - Scalar Condition Code (SCC) is preserved. - -Condition Code (SCC) semantics: - - By RDNA2 ISA specification, s_sext_i32_i8, s_sext_i32_i16, and s_flbit_i32 do NOT - modify the SCC condition code. - - In SALU operations where SCC is updated based on result D (e.g. s_and_b32, s_or_b32, - s_not_b32, s_bfe_u32/i32): SCC = (D != 0). - -Zero game data; standard library Python only; Python 3.9+ compatible. -""" -from __future__ import annotations - -import os -import random -import struct -import sys -import tempfile -import unittest -import warnings - -HERE = os.path.dirname(os.path.abspath(__file__)) -ROOT = os.path.dirname(os.path.dirname(HERE)) -TOOLS_DIR = os.environ.get("LEONIDA_TOOLS_DIR") or os.path.join(ROOT, "tools") - -sys.dont_write_bytecode = True -if ROOT not in sys.path: - sys.path.insert(0, ROOT) -if TOOLS_DIR not in sys.path: - sys.path.insert(0, TOOLS_DIR) -if HERE not in sys.path: - sys.path.insert(0, HERE) - -import rdna2spirv # noqa: E402 -import spirv_mini_interp as si # noqa: E402 - -M32 = 0xFFFFFFFF -STUB_DXBC = b"DXBC" + bytes(24) + struct.pack(" int: - """Normalize integer to unsigned 32-bit word [0, 0xFFFFFFFF].""" - return x & M32 - - -def s32(x: int) -> int: - """Interpret 32-bit integer as signed [-2^31, 2^31 - 1].""" - x &= M32 - return x - (1 << 32) if x >> 31 else x - - -def ref_s_sext_i32_i8(s0: int) -> int: - """RDNA2 s_sext_i32_i8 reference: sign-extend S0[7:0] to 32-bit signed integer. - - Bits [31:8] of S0 are ignored. Returns unsigned 32-bit word representation. - """ - b = s0 & 0xFF - signed_val = b - 0x100 if (b & 0x80) else b - return signed_val & M32 - - -def ref_s_sext_i32_i16(s0: int) -> int: - """RDNA2 s_sext_i32_i16 reference: sign-extend S0[15:0] to 32-bit signed integer. - - Bits [31:16] of S0 are ignored. Returns unsigned 32-bit word representation. - """ - h = s0 & 0xFFFF - signed_val = h - 0x10000 if (h & 0x8000) else h - return signed_val & M32 - - -def ref_s_flbit_i32(s0: int) -> int: - """RDNA2 s_flbit_i32 reference: count bits from MSB before first differing bit. - - Signed MSB scan (FindSMsb): - - Returns M32 (0xFFFFFFFF, representing -1) if all bits equal the sign bit (0 or -1). - - For positive values (sign=0): counts bits from bit 31 before the first 1-bit. - - For negative values (sign=1): counts bits from bit 31 before the first 0-bit. - """ - s0 &= M32 - if s0 == 0 or s0 == M32: - return M32 - sign = (s0 >> 31) & 1 - for n in range(1, 32): - if ((s0 >> (31 - n)) & 1) != sign: - return n - return M32 - - -def ref_s_flbit_i32_b32(s0: int) -> int: - """RDNA2 s_flbit_i32_b32 reference: count leading zeros from MSB down to LSB. - - Unsigned MSB scan (FindUMsb): - - Returns M32 (0xFFFFFFFF, representing -1) if s0 == 0. - - Otherwise returns 31 - highest_set_bit_index (32 - s0.bit_length()). - """ - s0 &= M32 - if s0 == 0: - return M32 - return 32 - s0.bit_length() - - -def ref_scc_ne_zero(d: int) -> int: - """Standard RDNA2 SALU condition code rule: SCC = (D != 0).""" - return 1 if (d & M32) != 0 else 0 - - -flbit_i32 = ref_s_flbit_i32 - -OPS = { - "s_sext_i32_i8": ref_s_sext_i32_i8, - "s_sext_i32_i16": ref_s_sext_i32_i16, - "s_flbit_i32": ref_s_flbit_i32, -} - -VALUES = [ - 0, 1, 0x7F, 0x80, 0xFF, 0x7FFF, 0x8000, 0xFFFF, - 0x12345678, 0x87654321, 0x7FFFFFFF, 0x80000000, - 0xFFFFFFFF, 0xFFFFFFFE, 0x40000000, 0xC0000000, 0x00010000, -] - -_TMP_DIR = None -_SRC_PATH = None - - -def setUpModule() -> None: - global _TMP_DIR, _SRC_PATH - _TMP_DIR = tempfile.TemporaryDirectory() - disasm_dir = os.path.join(_TMP_DIR.name, "disasm") - os.mkdir(disasm_dir) - _SRC_PATH = os.path.join(disasm_dir, "ps_salu_sext.s") - with open(os.path.join(_TMP_DIR.name, "ps_salu_sext.dxbc"), "wb") as f: - f.write(STUB_DXBC) - - -def tearDownModule() -> None: - global _TMP_DIR - if _TMP_DIR is not None: - _TMP_DIR.cleanup() - _TMP_DIR = None - - -def run_op(op: str, x: int, scc_in: int) -> tuple[int, int]: - """Execute shader: SCC = scc_in, then s0 = op(s2); return (s0, SCC after).""" - if _TMP_DIR is None: - setUpModule() - lines = [ - f"s_mov_b32 s2, {x:#x}", - f"s_mov_b32 s4, {scc_in}", - "s_cmp_eq_u32 s4, 1", - f"{op} s0, s2", - "s_cselect_b32 s1, 0x40000001, 0x40000000", - "s_and_b32 s5, s0, 0xffff", - "s_lshr_b32 s6, s0, 16", - "s_or_b32 s5, s5, 0x40000000", - "s_or_b32 s6, s6, 0x40000000", - "v_mov_b32 v0, s5", - "v_mov_b32 v1, s6", - "v_mov_b32 v2, s1", - ] - asm = ( - "; test_salu_sext\n" - + "".join(f"\t{ln}\n" for ln in lines) - + "\texp mrt0 v0, v1, v2, v2 done vm\n\ts_endpgm\n" - ) - with open(_SRC_PATH, "w", encoding="utf-8") as f: - f.write(asm) - with warnings.catch_warnings(): - warnings.simplefilter("ignore", ResourceWarning) - spv = rdna2spirv.translate(_SRC_PATH) - lo, hi, scc = si.run_fragment(spv)["%out_mrt0"][:3] - assert lo >> 16 == hi >> 16 == 0x4000 and scc >> 1 == 0x20000000, (hex(lo), hex(hi), hex(scc)) - return (lo & 0xFFFF) | (hi & 0xFFFF) << 16, scc & 1 - - -def run_program(lines: list[str]) -> tuple[int, int]: - """Execute arbitrary assembly lines writing result to s0 and SCC to s1.""" - if _TMP_DIR is None: - setUpModule() - prologue = [ - "s_cselect_b32 s1, 0x40000001, 0x40000000", - "s_and_b32 s5, s0, 0xffff", - "s_lshr_b32 s6, s0, 16", - "s_or_b32 s5, s5, 0x40000000", - "s_or_b32 s6, s6, 0x40000000", - "v_mov_b32 v0, s5", - "v_mov_b32 v1, s6", - "v_mov_b32 v2, s1", - ] - all_lines = list(lines) + prologue - asm = ( - "; test_salu_program\n" - + "".join(f"\t{ln}\n" for ln in all_lines) - + "\texp mrt0 v0, v1, v2, v2 done vm\n\ts_endpgm\n" - ) - with open(_SRC_PATH, "w", encoding="utf-8") as f: - f.write(asm) - with warnings.catch_warnings(): - warnings.simplefilter("ignore", ResourceWarning) - spv = rdna2spirv.translate(_SRC_PATH) - lo, hi, scc = si.run_fragment(spv)["%out_mrt0"][:3] - assert lo >> 16 == hi >> 16 == 0x4000 and scc >> 1 == 0x20000000, (hex(lo), hex(hi), hex(scc)) - return (lo & 0xFFFF) | (hi & 0xFFFF) << 16, scc & 1 - - -class ScalarAluInterpreter: - """Deterministic semantic interpreter for RDNA2 scalar ALU instructions. - - Models an array of 106 32-bit SGPRs (s0..s105) and a 1-bit Scalar Condition Code (SCC). - Enforces register aliasing rules, unaligned/independent register preservation, - and exact condition code preservation/updates. - """ - - def __init__(self, num_sgprs: int = 106, initial_scc: int = 0) -> None: - self.num_sgprs = num_sgprs - self.sgprs = [0] * num_sgprs - self.scc = initial_scc & 1 - - def reset(self, initial_scc: int = 0) -> None: - self.sgprs = [0] * self.num_sgprs - self.scc = initial_scc & 1 - - def read_sgpr(self, idx: int) -> int: - assert 0 <= idx < self.num_sgprs, f"SGPR index {idx} out of range" - return self.sgprs[idx] & M32 - - def write_sgpr(self, idx: int, val: int) -> None: - assert 0 <= idx < self.num_sgprs, f"SGPR index {idx} out of range" - self.sgprs[idx] = val & M32 - - def resolve_src(self, src: int | str) -> int: - if isinstance(src, int): - return src & M32 - if isinstance(src, str) and src.startswith("s") and src[1:].isdigit(): - return self.read_sgpr(int(src[1:])) - raise ValueError(f"Unrecognized scalar source: {src}") - - def exec_s_mov_b32(self, dst: int, src: int | str) -> None: - val = self.resolve_src(src) - self.write_sgpr(dst, val) - - def exec_s_sext_i32_i8(self, dst: int, src: int | str) -> None: - val = self.resolve_src(src) - res = ref_s_sext_i32_i8(val) - self.write_sgpr(dst, res) - - def exec_s_sext_i32_i16(self, dst: int, src: int | str) -> None: - val = self.resolve_src(src) - res = ref_s_sext_i32_i16(val) - self.write_sgpr(dst, res) - - def exec_s_flbit_i32(self, dst: int, src: int | str) -> None: - val = self.resolve_src(src) - res = ref_s_flbit_i32(val) - self.write_sgpr(dst, res) - - def exec_s_flbit_i32_b32(self, dst: int, src: int | str) -> None: - val = self.resolve_src(src) - res = ref_s_flbit_i32_b32(val) - self.write_sgpr(dst, res) - - def exec_s_and_b32(self, dst: int, s0: int | str, s1: int | str) -> None: - v0 = self.resolve_src(s0) - v1 = self.resolve_src(s1) - res = (v0 & v1) & M32 - self.write_sgpr(dst, res) - self.scc = ref_scc_ne_zero(res) - - def exec_s_cmp_eq_u32(self, s0: int | str, s1: int | str) -> None: - v0 = self.resolve_src(s0) - v1 = self.resolve_src(s1) - self.scc = 1 if (v0 == v1) else 0 - - def exec_s_cmp_lg_u32(self, s0: int | str, s1: int | str) -> None: - v0 = self.resolve_src(s0) - v1 = self.resolve_src(s1) - self.scc = 1 if (v0 != v1) else 0 - - -class ReferenceSignExtensionTests(unittest.TestCase): - """Exhaustive and property-based verification of scalar sign extension oracles.""" - - def test_ref_s_sext_i32_i8_boundaries(self) -> None: - self.assertEqual(ref_s_sext_i32_i8(0x80), 0xFFFFFF80) - self.assertEqual(s32(ref_s_sext_i32_i8(0x80)), -128) - - self.assertEqual(ref_s_sext_i32_i8(0x7F), 0x0000007F) - self.assertEqual(s32(ref_s_sext_i32_i8(0x7F)), 127) - - self.assertEqual(ref_s_sext_i32_i8(0x00), 0x00000000) - self.assertEqual(ref_s_sext_i32_i8(0x01), 0x00000001) - - self.assertEqual(ref_s_sext_i32_i8(0xFF), 0xFFFFFFFF) - self.assertEqual(s32(ref_s_sext_i32_i8(0xFF)), -1) - - self.assertEqual(ref_s_sext_i32_i8(0xFE), 0xFFFFFFFE) - self.assertEqual(s32(ref_s_sext_i32_i8(0xFE)), -2) - - def test_ref_s_sext_i32_i16_boundaries(self) -> None: - self.assertEqual(ref_s_sext_i32_i16(0x8000), 0xFFFF8000) - self.assertEqual(s32(ref_s_sext_i32_i16(0x8000)), -32768) - - self.assertEqual(ref_s_sext_i32_i16(0x7FFF), 0x00007FFF) - self.assertEqual(s32(ref_s_sext_i32_i16(0x7FFF)), 32767) - - self.assertEqual(ref_s_sext_i32_i16(0x0000), 0x00000000) - self.assertEqual(ref_s_sext_i32_i16(0x0001), 0x00000001) - - self.assertEqual(ref_s_sext_i32_i16(0xFFFF), 0xFFFFFFFF) - self.assertEqual(s32(ref_s_sext_i32_i16(0xFFFF)), -1) - - self.assertEqual(ref_s_sext_i32_i16(0xFFFE), 0xFFFFFFFE) - self.assertEqual(s32(ref_s_sext_i32_i16(0xFFFE)), -2) - - def test_high_bits_ignored(self) -> None: - patterns_8 = [0xDEADBE00, 0x12345600, 0x7FFFFF00, 0x80000000, 0xFFFFFF00] - for p in patterns_8: - self.assertEqual(ref_s_sext_i32_i8(p | 0x80), 0xFFFFFF80) - self.assertEqual(ref_s_sext_i32_i8(p | 0x7F), 0x0000007F) - self.assertEqual(ref_s_sext_i32_i8(p | 0x00), 0x00000000) - self.assertEqual(ref_s_sext_i32_i8(p | 0xFF), 0xFFFFFFFF) - - patterns_16 = [0xDEAD0000, 0x12340000, 0x7FFF0000, 0x80000000, 0xFFFF0000] - for p in patterns_16: - self.assertEqual(ref_s_sext_i32_i16(p | 0x8000), 0xFFFF8000) - self.assertEqual(ref_s_sext_i32_i16(p | 0x7FFF), 0x00007FFF) - self.assertEqual(ref_s_sext_i32_i16(p | 0x0000), 0x00000000) - self.assertEqual(ref_s_sext_i32_i16(p | 0xFFFF), 0xFFFFFFFF) - - def test_exhaustive_i8_against_struct_pack(self) -> None: - for byte_val in range(256): - expected_signed = struct.unpack(" None: - for word_val in list(range(0, 512)) + list(range(0x7F00, 0x8100)) + list(range(0xFF00, 0x10000, 3)): - expected_signed = struct.unpack(" None: - for v in [0, 1, 0x7F, 0x80, 0xFF, 0x12345678, 0x80000000, 0xFFFFFFFF]: - res_i8 = ref_s_sext_i32_i8(v) - self.assertEqual(ref_s_sext_i32_i8(res_i8), res_i8) - res_i16 = ref_s_sext_i32_i16(v) - self.assertEqual(ref_s_sext_i32_i16(res_i16), res_i16) - - for v in range(256): - ext8 = ref_s_sext_i32_i8(v) - self.assertEqual(ref_s_sext_i32_i16(ext8), ext8) - - -class ReferenceMsbScanTests(unittest.TestCase): - """Reference oracle tests for scalar MSB scanning instructions s_flbit_i32 and s_flbit_i32_b32.""" - - def test_s_flbit_i32_powers_of_two(self) -> None: - self.assertEqual(ref_s_flbit_i32(0x40000000), 1) - self.assertEqual(ref_s_flbit_i32(0x20000000), 2) - self.assertEqual(ref_s_flbit_i32(0x10000000), 3) - self.assertEqual(ref_s_flbit_i32(0x00000002), 30) - self.assertEqual(ref_s_flbit_i32(0x00000001), 31) - - for bit in range(31): - val = 1 << bit - expected = 31 - bit - self.assertEqual(ref_s_flbit_i32(val), expected) - - def test_s_flbit_i32_negative_patterns(self) -> None: - self.assertEqual(ref_s_flbit_i32(0x80000000), 1) - self.assertEqual(ref_s_flbit_i32(0xC0000000), 2) - self.assertEqual(ref_s_flbit_i32(0xE0000000), 3) - self.assertEqual(ref_s_flbit_i32(0xFFFFFFFE), 31) - - def test_s_flbit_i32_uniform_cases(self) -> None: - self.assertEqual(ref_s_flbit_i32(0x00000000), M32) - self.assertEqual(ref_s_flbit_i32(0xFFFFFFFF), M32) - - def test_s_flbit_i32_bitwise_not_symmetry(self) -> None: - test_values = [ - 1, 2, 7, 0x40000000, 0x12345678, 0x7FFFFFFF, 0x55555555, - 0x80000000, 0xC0000000, 0xFFFFFFFE, 0x87654321, 0xAAAAAAAA, - ] - for v in test_values: - not_v = (~v) & M32 - self.assertEqual(ref_s_flbit_i32(v), ref_s_flbit_i32(not_v)) - - def test_s_flbit_i32_b32_unsigned_scan(self) -> None: - self.assertEqual(ref_s_flbit_i32_b32(0x80000000), 0) - self.assertEqual(ref_s_flbit_i32_b32(0x40000000), 1) - self.assertEqual(ref_s_flbit_i32_b32(0x00000001), 31) - self.assertEqual(ref_s_flbit_i32_b32(0x00000000), M32) - - for bit in range(32): - val = 1 << bit - self.assertEqual(ref_s_flbit_i32_b32(val), 31 - bit) - - -class ScalarAluInterpreterTests(unittest.TestCase): - """Interpreter test suite for register aliasing, unaffected registers, and state isolation.""" - - def setUp(self) -> None: - self.interp = ScalarAluInterpreter(num_sgprs=106, initial_scc=0) - - def test_exec_s_flbit_i32_immediate_and_reg(self) -> None: - self.interp.exec_s_flbit_i32(10, 0x40000000) - self.assertEqual(self.interp.read_sgpr(10), 1) - - self.interp.exec_s_mov_b32(11, 0xFFFFFFFE) - self.interp.exec_s_flbit_i32(12, "s11") - self.assertEqual(self.interp.read_sgpr(12), 31) - - def test_sgpr_aliasing_in_place(self) -> None: - self.interp.write_sgpr(4, 0x20000000) - self.interp.exec_s_flbit_i32(4, "s4") - self.assertEqual(self.interp.read_sgpr(4), 2) - - self.interp.write_sgpr(5, 0x80000000) - self.interp.exec_s_flbit_i32(5, "s5") - self.assertEqual(self.interp.read_sgpr(5), 1) - - self.interp.write_sgpr(6, 0x123480) - self.interp.exec_s_sext_i32_i8(6, "s6") - self.assertEqual(self.interp.read_sgpr(6), 0xFFFFFF80) - - self.interp.write_sgpr(7, 0xABCD7FFF) - self.interp.exec_s_sext_i32_i16(7, "s7") - self.assertEqual(self.interp.read_sgpr(7), 0x00007FFF) - - def test_sgpr_isolation_and_unaffected_registers(self) -> None: - for i in range(20): - self.interp.write_sgpr(i, 0x1000 + i) - - self.interp.exec_s_flbit_i32(10, 0x40000000) - self.assertEqual(self.interp.read_sgpr(10), 1) - - for i in range(20): - if i != 10: - self.assertEqual(self.interp.read_sgpr(i), 0x1000 + i) - - def test_scc_preserved_during_interpreter_execution(self) -> None: - for init_scc in (0, 1): - self.interp.reset(initial_scc=init_scc) - self.interp.exec_s_sext_i32_i8(1, 0x80) - self.assertEqual(self.interp.scc, init_scc) - - self.interp.exec_s_sext_i32_i16(2, 0x7FFF) - self.assertEqual(self.interp.scc, init_scc) - - self.interp.exec_s_flbit_i32(3, 0x40000000) - self.assertEqual(self.interp.scc, init_scc) - - self.interp.exec_s_flbit_i32(4, 0) - self.assertEqual(self.interp.scc, init_scc) - - def test_compound_sign_extend_then_flbit(self) -> None: - self.interp.write_sgpr(0, 0x80) - self.interp.exec_s_sext_i32_i8(1, "s0") - self.assertEqual(self.interp.read_sgpr(1), 0xFFFFFF80) - self.interp.exec_s_flbit_i32(2, "s1") - self.assertEqual(self.interp.read_sgpr(2), 25) - - self.interp.write_sgpr(3, 0x7F) - self.interp.exec_s_sext_i32_i8(4, "s3") - self.assertEqual(self.interp.read_sgpr(4), 0x0000007F) - self.interp.exec_s_flbit_i32(5, "s4") - self.assertEqual(self.interp.read_sgpr(5), 25) - - -class ConditionCodeAndEdgePatternTests(unittest.TestCase): - """Tests for SCC condition code updates, extreme boundaries, and edge bit patterns.""" - - def test_scc_ne_zero_rule(self) -> None: - # Zero yields SCC = 0 - self.assertEqual(ref_scc_ne_zero(0), 0) - self.assertEqual(ref_scc_ne_zero(0x00000000), 0) - - # Non-zero yields SCC = 1 - for val in [1, -1, 0x7F, 0x80, 0x7FFF, 0x8000, 0x80000000, 0xFFFFFFFF]: - self.assertEqual(ref_scc_ne_zero(val), 1) - - def test_extreme_boundaries_in_shaders(self) -> None: - # Explicit required boundaries: -128, 127, -32768, 32767, 0, -1 - boundaries = [-128, 127, -32768, 32767, 0, -1] - for val in boundaries: - uval = val & M32 - # Check s_sext_i32_i8 - res8, scc8 = run_op("s_sext_i32_i8", uval, 0) - self.assertEqual(res8, ref_s_sext_i32_i8(uval)) - self.assertEqual(scc8, 0) - - # Check s_sext_i32_i16 - res16, scc16 = run_op("s_sext_i32_i16", uval, 1) - self.assertEqual(res16, ref_s_sext_i32_i16(uval)) - self.assertEqual(scc16, 1) - - # Check s_flbit_i32 - res_fl, scc_fl = run_op("s_flbit_i32", uval, 0) - self.assertEqual(res_fl, ref_s_flbit_i32(uval)) - self.assertEqual(scc_fl, 0) - - def test_alternating_bit_patterns(self) -> None: - # 0x55555555: 0101 0101... - val5 = 0x55555555 - self.assertEqual(ref_s_sext_i32_i8(val5), 0x00000055) - self.assertEqual(ref_s_sext_i32_i16(val5), 0x00005555) - self.assertEqual(ref_s_flbit_i32(val5), 1) - - # 0xAAAAAAAA: 1010 1010... - valA = 0xAAAAAAAA - self.assertEqual(ref_s_sext_i32_i8(valA), 0xFFFFFFAA) - self.assertEqual(ref_s_sext_i32_i16(valA), 0xFFFFAAAA) - self.assertEqual(ref_s_flbit_i32(valA), 1) - - # Run both in synthetic shaders - for pat in (val5, valA): - self.assertEqual(run_op("s_sext_i32_i8", pat, 0)[0], ref_s_sext_i32_i8(pat)) - self.assertEqual(run_op("s_sext_i32_i16", pat, 0)[0], ref_s_sext_i32_i16(pat)) - self.assertEqual(run_op("s_flbit_i32", pat, 0)[0], ref_s_flbit_i32(pat)) - - def test_shader_aliasing_and_chaining(self) -> None: - # Shader doing in-place aliasing s0 = s_sext_i32_i8(s0) then s0 = s_flbit_i32(s0) - prog = [ - "s_mov_b32 s0, 0x80", - "s_sext_i32_i8 s0, s0", - "s_flbit_i32 s0, s0", - "s_cmp_eq_u32 s0, 25", - ] - res, scc = run_program(prog) - self.assertEqual(res, 25) - self.assertEqual(scc, 1) - - -class NegativeControlTests(unittest.TestCase): - """Sensitivity tests ensuring mutants in sign extension, scan, or condition codes fail.""" - - def test_mutant_zero_extension_caught(self) -> None: - # A buggy implementation that zero-extends instead of sign-extends - def mutant_sext_i8(x: int) -> int: - return x & 0xFF - - def mutant_sext_i16(x: int) -> int: - return x & 0xFFFF - - # Negative inputs must fail mutant check - negative_i8 = 0x80 - self.assertEqual(ref_s_sext_i32_i8(negative_i8), 0xFFFFFF80) - self.assertEqual(mutant_sext_i8(negative_i8), 0x00000080) - self.assertNotEqual(ref_s_sext_i32_i8(negative_i8), mutant_sext_i8(negative_i8)) - - negative_i16 = 0x8000 - self.assertEqual(ref_s_sext_i32_i16(negative_i16), 0xFFFF8000) - self.assertEqual(mutant_sext_i16(negative_i16), 0x00008000) - self.assertNotEqual(ref_s_sext_i32_i16(negative_i16), mutant_sext_i16(negative_i16)) - - def test_mutant_bit_width_caught(self) -> None: - # A buggy implementation that uses 7-bit instead of 8-bit sign extension - def mutant_sext_7bit(x: int) -> int: - b = x & 0x7F - return (b - 0x80 if (b & 0x40) else b) & M32 - - # Value 0x40 (+64 in 8-bit, but -64 in 7-bit) - self.assertEqual(ref_s_sext_i32_i8(0x40), 0x00000040) - self.assertEqual(mutant_sext_7bit(0x40), 0xFFFFFFC0) - self.assertNotEqual(ref_s_sext_i32_i8(0x40), mutant_sext_7bit(0x40)) - - def test_mutant_unmasked_high_bits_caught(self) -> None: - # A buggy implementation that fails to mask high bits before sign-extending - def mutant_sext_unmasked(x: int) -> int: - return ((x << 24) >> 24) & M32 # Python shifts preserve arbitrarily large integers - - dirty_input = 0x123480 - clean_res = ref_s_sext_i32_i8(dirty_input) - self.assertEqual(clean_res, 0xFFFFFF80) - - def test_mutant_lsb_scan_caught(self) -> None: - # A buggy implementation that scans from LSB instead of MSB - def mutant_flbit_lsb(x: int) -> int: - x &= M32 - if x == 0 or x == M32: - return M32 - # Find lowest set bit - for i in range(32): - if (x >> i) & 1: - return i - return M32 - - val = 0x40000000 - self.assertEqual(ref_s_flbit_i32(val), 1) - self.assertEqual(mutant_flbit_lsb(val), 30) - self.assertNotEqual(ref_s_flbit_i32(val), mutant_flbit_lsb(val)) - - def test_mutant_zero_handling_caught(self) -> None: - # A buggy implementation returning 0 instead of -1 (0xFFFFFFFF) on zero - def mutant_flbit_zero_as_0(x: int) -> int: - return 0 if x == 0 else ref_s_flbit_i32(x) - - self.assertEqual(ref_s_flbit_i32(0), M32) - self.assertEqual(mutant_flbit_zero_as_0(0), 0) - self.assertNotEqual(ref_s_flbit_i32(0), mutant_flbit_zero_as_0(0)) - - def test_mutant_inverted_scc_caught(self) -> None: - # Inverted SCC condition: SCC = (D == 0) instead of (D != 0) - def mutant_scc(d: int) -> int: - return 1 if (d & M32) == 0 else 0 - - self.assertEqual(ref_scc_ne_zero(0), 0) - self.assertEqual(mutant_scc(0), 1) - self.assertNotEqual(ref_scc_ne_zero(0), mutant_scc(0)) - - self.assertEqual(ref_scc_ne_zero(42), 1) - self.assertEqual(mutant_scc(42), 0) - self.assertNotEqual(ref_scc_ne_zero(42), mutant_scc(42)) - - def test_mutant_corrupted_neighbor_register_caught(self) -> None: - # A buggy interpreter that clobbers adjacent register - interp = ScalarAluInterpreter(num_sgprs=10, initial_scc=0) - interp.write_sgpr(4, 0x1111) - interp.write_sgpr(5, 0x2222) - interp.write_sgpr(6, 0x3333) - - # Standard execution preserves neighbors - interp.exec_s_sext_i32_i8(5, 0x7F) - self.assertEqual(interp.read_sgpr(4), 0x1111) - self.assertEqual(interp.read_sgpr(5), 0x7F) - self.assertEqual(interp.read_sgpr(6), 0x3333) - - -class SextFlbitLegacyTests(unittest.TestCase): - """Integration tests executing synthetic shaders through rdna2spirv and spirv_mini_interp.""" - - def test_legacy_reference(self) -> None: - self.assertEqual(ref_s_sext_i32_i8(0x80), 0xFFFFFF80) - self.assertEqual(ref_s_sext_i32_i8(0x1234807F), 0x7F) - self.assertEqual(ref_s_sext_i32_i16(0xABCD8000), 0xFFFF8000) - self.assertEqual(flbit_i32(1), 31) - self.assertEqual(flbit_i32(0x40000000), 1) - self.assertEqual(flbit_i32(0xFFFFFFFE), 31) - self.assertEqual(flbit_i32(0x80000000), 1) - self.assertEqual(flbit_i32(0), M32) - self.assertEqual(flbit_i32(M32), M32) - - def test_values_and_scc_kept(self) -> None: - for op, fn in OPS.items(): - for x in VALUES: - for scc_in in (0, 1): - with self.subTest(op=op, x=hex(x), scc=scc_in): - self.assertEqual(run_op(op, x, scc_in), (fn(x), scc_in)) - - def test_seeded(self) -> None: - rng = random.Random(0x5E) - for _ in range(30): - op, x = rng.choice(list(OPS)), rng.getrandbits(32) >> rng.randrange(32) - if rng.getrandbits(1): - x = ~x & M32 - with self.subTest(op=op, x=hex(x)): - self.assertEqual(run_op(op, x, 0)[0], OPS[op](x)) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_salu_shifts_bundle.py b/tests/semantic/test_salu_shifts_bundle.py deleted file mode 100644 index e1c443935..000000000 --- a/tests/semantic/test_salu_shifts_bundle.py +++ /dev/null @@ -1,424 +0,0 @@ -"""Bundle 28: SALU 32/64-bit Shift Operations Suite. - -Tests for 6 SALU shift instructions: -- s_lshl_b32: 32-bit scalar logical shift left (shift count & 31, SCC = result != 0) -- s_lshr_b32: 32-bit scalar logical shift right (shift count & 31, SCC = result != 0) -- s_ashr_i32: 32-bit scalar arithmetic shift right (shift count & 31, sign-extended, SCC = result != 0) -- s_lshl_b64: 64-bit scalar logical shift left (shift count & 63, SCC = result != 0) -- s_lshr_b64: 64-bit scalar logical shift right (shift count & 63, SCC = result != 0) -- s_ashr_i64: 64-bit scalar arithmetic shift right (shift count & 63, sign-extended, SCC = result != 0) - -Standard library only; zero game data. -""" -from __future__ import annotations - -import math -import os -import struct -import sys -import unittest - -HERE = os.path.dirname(os.path.abspath(__file__)) -ROOT = os.path.dirname(os.path.dirname(HERE)) -TOOLS_DIR = os.environ.get("LEONIDA_TOOLS_DIR") or os.path.join(ROOT, "tools") - -sys.dont_write_bytecode = True -if TOOLS_DIR not in sys.path: - sys.path.insert(0, TOOLS_DIR) -if HERE not in sys.path: - sys.path.insert(0, HERE) - -import rdna2spirv # noqa: E402 -import spirv_mini_interp as si # noqa: E402 -import support # noqa: E402 - -MASK32 = 0xFFFFFFFF -MASK64 = 0xFFFFFFFFFFFFFFFF - -FSSM = bytearray(0x148) -struct.pack_into("<4I", FSSM, 0x138, 0x40088, 32, 1, 1) -FSSM = bytes(FSSM) -VSHARP = [0, 0, 0x1000, 0x31016FAC] - - -def run_cs(body: list[str], lanes: int = 32, num_words: int = 32, name: str = "cs_bundle28") -> list[int]: - """Helper to translate and run a compute shader; stores outputs at out[lane*32 + word*4].""" - prologue = ["v_lshlrev_b32_e32 v30, 5, v0"] - full_body = prologue + list(body) + ["s_endpgm"] - spv = support.translate_lines(name, full_body, fssm=FSSM) - mem: dict[int, int] = {} - si.run_workgroup( - spv, - lanes, - 32, - inputs_for=lambda i: {"%wg_id": (0, 0, 0), "%local_id": (i, 0, 0), "%sg_lane": i}, - push_constants=VSHARP + [0] * 28, - memory=mem, - ) - return [mem.get(i * 32, 0) for i in range(num_words)] - - -class ASTNode: - """Base class for symbolic AST nodes.""" - pass - -def ref_s_lshl_b32(src: int, shift: int) -> tuple[int, int]: - """Reference mathematical oracle for s_lshl_b32 -> (result, scc).""" - sh = shift & 31 - res = (src << sh) & MASK32 - scc = 1 if res != 0 else 0 - return res, scc - - -class TestSLshlB32Oracle(unittest.TestCase): - def test_basic_shifts(self) -> None: - self.assertEqual(ref_s_lshl_b32(1, 0), (1, 1)) - self.assertEqual(ref_s_lshl_b32(1, 4), (16, 1)) - self.assertEqual(ref_s_lshl_b32(0x12345678, 8), (0x34567800, 1)) - - def test_zero_result_and_scc(self) -> None: - self.assertEqual(ref_s_lshl_b32(0, 5), (0, 0)) - self.assertEqual(ref_s_lshl_b32(0x80000000, 1), (0, 0)) - - def test_shift_count_masking(self) -> None: - # Shift count is masked with 31: 32 -> 0, 33 -> 1 - self.assertEqual(ref_s_lshl_b32(1, 32), (1, 1)) - self.assertEqual(ref_s_lshl_b32(1, 33), (2, 1)) - -class SLshlB32Expr(ASTNode): - def __init__(self, src: int, shift: int) -> None: - self.src = src - self.shift = shift - - def eval(self) -> tuple[int, int]: - return ref_s_lshl_b32(self.src, self.shift) - - -class TestSLshlB32AST(unittest.TestCase): - def test_ast_evaluation(self) -> None: - expr = SLshlB32Expr(0x0F, 4) - self.assertEqual(expr.eval(), (0xF0, 1)) - expr_zero = SLshlB32Expr(0, 10) - self.assertEqual(expr_zero.eval(), (0, 0)) - -class TestSLshlB32SCCAndMask(unittest.TestCase): - def test_scc_condition_code(self) -> None: - # Shift off all bits - res, scc = ref_s_lshl_b32(0x00000001, 31) - self.assertEqual((res, scc), (0x80000000, 1)) - # High bit shifted out by another bit - res, scc = ref_s_lshl_b32(0x80000000, 1) - self.assertEqual((res, scc), (0, 0)) - - def test_shift_counts_boundary(self) -> None: - for sh in range(32): - res, scc = ref_s_lshl_b32(1, sh) - self.assertEqual(res, 1 << sh) - self.assertEqual(scc, 1) - -class TestSLshlB32Translator(unittest.TestCase): - def test_translator_s_lshl_b32_execution(self) -> None: - body = [ - "s_mov_b32 s4, 0x12345678", - "s_lshl_b32 s5, s4, 4", - "s_cselect_b32 s6, 1, 0", - "v_mov_b32_e32 v1, s5", - "buffer_store_dword v1, v30, s[0:3], 0 offen", - ] - results = run_cs(body, name="cs_s_lshl_b32") - for l in range(32): - self.assertEqual(results[l], 0x23456780) - -def ref_s_lshr_b32(src: int, shift: int) -> tuple[int, int]: - """Reference mathematical oracle for s_lshr_b32 -> (result, scc).""" - sh = shift & 31 - res = (src & MASK32) >> sh - scc = 1 if res != 0 else 0 - return res, scc - - -class TestSLshrB32Oracle(unittest.TestCase): - def test_basic_shifts(self) -> None: - self.assertEqual(ref_s_lshr_b32(16, 4), (1, 1)) - self.assertEqual(ref_s_lshr_b32(0x12345678, 8), (0x00123456, 1)) - - def test_zero_result_and_scc(self) -> None: - self.assertEqual(ref_s_lshr_b32(0, 4), (0, 0)) - self.assertEqual(ref_s_lshr_b32(1, 1), (0, 0)) - - def test_shift_count_masking(self) -> None: - self.assertEqual(ref_s_lshr_b32(0x10, 32), (0x10, 1)) - self.assertEqual(ref_s_lshr_b32(0x10, 33), (0x08, 1)) - -class SLshrB32Expr(ASTNode): - def __init__(self, src: int, shift: int) -> None: - self.src = src - self.shift = shift - - def eval(self) -> tuple[int, int]: - return ref_s_lshr_b32(self.src, self.shift) - - -class TestSLshrB32AST(unittest.TestCase): - def test_ast_evaluation(self) -> None: - expr = SLshrB32Expr(0xF0, 4) - self.assertEqual(expr.eval(), (0x0F, 1)) - expr_zero = SLshrB32Expr(1, 1) - self.assertEqual(expr_zero.eval(), (0, 0)) - -class TestSLshrB32SCCAndMask(unittest.TestCase): - def test_scc_condition_code(self) -> None: - res, scc = ref_s_lshr_b32(0x80000000, 31) - self.assertEqual((res, scc), (1, 1)) - res, scc = ref_s_lshr_b32(0x80000000, 32) # shift 0 - self.assertEqual((res, scc), (0x80000000, 1)) - - def test_logical_zero_fill(self) -> None: - # Highest bit cleared on right shift - res, _ = ref_s_lshr_b32(0x80000000, 1) - self.assertEqual(res, 0x40000000) - -class TestSLshrB32Translator(unittest.TestCase): - def test_translator_s_lshr_b32_execution(self) -> None: - body = [ - "s_mov_b32 s4, 0x12345678", - "s_lshr_b32 s5, s4, 4", - "v_mov_b32_e32 v1, s5", - "buffer_store_dword v1, v30, s[0:3], 0 offen", - ] - results = run_cs(body, name="cs_s_lshr_b32") - for l in range(32): - self.assertEqual(results[l], 0x01234567) - -def ref_s_ashr_i32(src: int, shift: int) -> tuple[int, int]: - """Reference mathematical oracle for s_ashr_i32 -> (result, scc).""" - sh = shift & 31 - val = src & MASK32 - sval = val - 0x100000000 if val & 0x80000000 else val - res = (sval >> sh) & MASK32 - scc = 1 if res != 0 else 0 - return res, scc - - -class TestSAshrI32Oracle(unittest.TestCase): - def test_positive_numbers(self) -> None: - self.assertEqual(ref_s_ashr_i32(0x1000, 4), (0x0100, 1)) - - def test_negative_sign_extension(self) -> None: - # 0x80000000 >> 4 = 0xF8000000 - self.assertEqual(ref_s_ashr_i32(0x80000000, 4), (0xF8000000, 1)) - # -1 (0xFFFFFFFF) >> any = -1 (0xFFFFFFFF) - self.assertEqual(ref_s_ashr_i32(0xFFFFFFFF, 10), (0xFFFFFFFF, 1)) - -class SAshrI32Expr(ASTNode): - def __init__(self, src: int, shift: int) -> None: - self.src = src - self.shift = shift - - def eval(self) -> tuple[int, int]: - return ref_s_ashr_i32(self.src, self.shift) - - -class TestSAshrI32AST(unittest.TestCase): - def test_ast_evaluation(self) -> None: - expr = SAshrI32Expr(0x80000000, 1) - self.assertEqual(expr.eval(), (0xC0000000, 1)) - expr_pos = SAshrI32Expr(4, 2) - self.assertEqual(expr_pos.eval(), (1, 1)) - -class TestSAshrI32SignAndSCC(unittest.TestCase): - def test_sign_bit_propagation(self) -> None: - val = 0x80000000 - for sh in range(32): - res, scc = ref_s_ashr_i32(val, sh) - # Bit 31 must stay 1 - self.assertEqual(res & 0x80000000, 0x80000000) - self.assertEqual(scc, 1) - - def test_zero_result(self) -> None: - res, scc = ref_s_ashr_i32(0, 5) - self.assertEqual((res, scc), (0, 0)) - -class TestSAshrI32Translator(unittest.TestCase): - def test_translator_s_ashr_i32_execution(self) -> None: - body = [ - "s_mov_b32 s4, 0x80000000", - "s_ashr_i32 s5, s4, 4", - "v_mov_b32_e32 v1, s5", - "buffer_store_dword v1, v30, s[0:3], 0 offen", - ] - results = run_cs(body, name="cs_s_ashr_i32") - for l in range(32): - self.assertEqual(results[l], 0xF8000000) - -def ref_s_lshl_b64(src: int, shift: int) -> tuple[int, int]: - """Reference mathematical oracle for s_lshl_b64 -> (result, scc).""" - sh = shift & 63 - res = (src << sh) & MASK64 - scc = 1 if res != 0 else 0 - return res, scc - - -class TestSLshlB64Oracle(unittest.TestCase): - def test_cross_dword_shift(self) -> None: - # Shift lower dword into upper dword by 32 bits - self.assertEqual(ref_s_lshl_b64(0x0000000012345678, 32), (0x1234567800000000, 1)) - - def test_shift_count_masking_64(self) -> None: - self.assertEqual(ref_s_lshl_b64(1, 64), (1, 1)) - self.assertEqual(ref_s_lshl_b64(1, 65), (2, 1)) - -class SLshlB64Expr(ASTNode): - def __init__(self, src: int, shift: int) -> None: - self.src = src - self.shift = shift - - def eval(self) -> tuple[int, int]: - return ref_s_lshl_b64(self.src, self.shift) - - -class TestSLshlB64AST(unittest.TestCase): - def test_ast_evaluation(self) -> None: - expr = SLshlB64Expr(0x1, 40) - self.assertEqual(expr.eval(), (1 << 40, 1)) - -class TestSLshlB64CrossDwordAndSCC(unittest.TestCase): - def test_scc_zero_result(self) -> None: - res, scc = ref_s_lshl_b64(0, 10) - self.assertEqual((res, scc), (0, 0)) - # 1 shifted left by 63 is non-zero, but shift by another bit wraps via mask 63 - res, scc = ref_s_lshl_b64(1 << 63, 1) - self.assertEqual((res, scc), (0, 0)) - - def test_dword_boundary_transitions(self) -> None: - val = 0x00000000FFFFFFFF - res, scc = ref_s_lshl_b64(val, 16) - self.assertEqual(res, 0x0000FFFFFFFF0000) - self.assertEqual(scc, 1) - -class TestSLshlB64Translator(unittest.TestCase): - def test_translator_s_lshl_b64_execution(self) -> None: - body = [ - "s_mov_b64 s[4:5], 0x123456789abcdef0", - "s_lshl_b64 s[6:7], s[4:5], 8", - "v_mov_b32_e32 v1, s6", - "buffer_store_dword v1, v30, s[0:3], 0 offen", - ] - results = run_cs(body, name="cs_s_lshl_b64") - for l in range(32): - self.assertEqual(results[l], 0xBCDEF000) - -def ref_s_lshr_b64(src: int, shift: int) -> tuple[int, int]: - """Reference mathematical oracle for s_lshr_b64 -> (result, scc).""" - sh = shift & 63 - res = (src & MASK64) >> sh - scc = 1 if res != 0 else 0 - return res, scc - - -class TestSLshrB64Oracle(unittest.TestCase): - def test_cross_dword_shift(self) -> None: - # Shift upper dword into lower dword - self.assertEqual(ref_s_lshr_b64(0x1234567800000000, 32), (0x12345678, 1)) - - def test_shift_count_masking_64(self) -> None: - self.assertEqual(ref_s_lshr_b64(0x100, 64), (0x100, 1)) - self.assertEqual(ref_s_lshr_b64(0x100, 65), (0x80, 1)) - -class SLshrB64Expr(ASTNode): - def __init__(self, src: int, shift: int) -> None: - self.src = src - self.shift = shift - - def eval(self) -> tuple[int, int]: - return ref_s_lshr_b64(self.src, self.shift) - - -class TestSLshrB64AST(unittest.TestCase): - def test_ast_evaluation(self) -> None: - expr = SLshrB64Expr(0x10000000000, 40) - self.assertEqual(expr.eval(), (1, 1)) - -class TestSLshrB64CrossDwordAndSCC(unittest.TestCase): - def test_scc_condition_code(self) -> None: - res, scc = ref_s_lshr_b64(1, 1) - self.assertEqual((res, scc), (0, 0)) - - def test_upper_dword_drain(self) -> None: - val = 0x8000000000000000 - res, scc = ref_s_lshr_b64(val, 63) - self.assertEqual((res, scc), (1, 1)) - -class TestSLshrB64Translator(unittest.TestCase): - def test_translator_s_lshr_b64_execution(self) -> None: - body = [ - "s_mov_b64 s[4:5], 0x123456789abcdef0", - "s_lshr_b64 s[6:7], s[4:5], 8", - "v_mov_b32_e32 v1, s6", - "buffer_store_dword v1, v30, s[0:3], 0 offen", - ] - results = run_cs(body, name="cs_s_lshr_b64") - for l in range(32): - self.assertEqual(results[l], 0x789ABCDE) - -def ref_s_ashr_i64(src: int, shift: int) -> tuple[int, int]: - """Reference mathematical oracle for s_ashr_i64 -> (result, scc).""" - sh = shift & 63 - val = src & MASK64 - sval = val - (1 << 64) if val & (1 << 63) else val - res = (sval >> sh) & MASK64 - scc = 1 if res != 0 else 0 - return res, scc - - -class TestSAshrI64Oracle(unittest.TestCase): - def test_positive_numbers(self) -> None: - self.assertEqual(ref_s_ashr_i64(0x1000000000, 4), (0x0100000000, 1)) - - def test_negative_sign_extension(self) -> None: - # 0x8000000000000000 >> 8 = 0xFF80000000000000 - self.assertEqual(ref_s_ashr_i64(0x8000000000000000, 8), (0xFF80000000000000, 1)) - # -1 (0xFFFFFFFFFFFFFFFF) >> any = -1 - self.assertEqual(ref_s_ashr_i64(MASK64, 20), (MASK64, 1)) - -class SAshrI64Expr(ASTNode): - def __init__(self, src: int, shift: int) -> None: - self.src = src - self.shift = shift - - def eval(self) -> tuple[int, int]: - return ref_s_ashr_i64(self.src, self.shift) - - -class TestSAshrI64AST(unittest.TestCase): - def test_ast_evaluation(self) -> None: - expr = SAshrI64Expr(0x8000000000000000, 1) - self.assertEqual(expr.eval(), (0xC000000000000000, 1)) - -class TestSAshrI64SignAndSCC(unittest.TestCase): - def test_64bit_sign_propagation(self) -> None: - val = 0x8000000000000000 - for sh in range(64): - res, scc = ref_s_ashr_i64(val, sh) - self.assertEqual(res & (1 << 63), 1 << 63) - self.assertEqual(scc, 1) - - def test_zero_result(self) -> None: - res, scc = ref_s_ashr_i64(0, 10) - self.assertEqual((res, scc), (0, 0)) - -class TestSAshrI64Translator(unittest.TestCase): - def test_translator_s_ashr_i64_execution(self) -> None: - body = [ - "s_mov_b64 s[4:5], 0x8000000000000000", - "s_ashr_i64 s[6:7], s[4:5], 8", - "v_mov_b32_e32 v1, s7", # upper dword - "buffer_store_dword v1, v30, s[0:3], 0 offen", - ] - results = run_cs(body, name="cs_s_ashr_i64") - for l in range(32): - self.assertEqual(results[l], 0xFF800000) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_salu_sub_co_u32.py b/tests/semantic/test_salu_sub_co_u32.py deleted file mode 100644 index 72dc8b853..000000000 --- a/tests/semantic/test_salu_sub_co_u32.py +++ /dev/null @@ -1,285 +0,0 @@ -from __future__ import annotations - -"""Semantic interpreter tests for RDNA2 scalar subtract with carry out (s_sub_co_u32 / s_sub_u32). - -Covers: - * Reference mathematical oracle for 32-bit unsigned scalar subtraction with borrow: - D = (S0 - S1) mod 2^32 - SCC = 1 if (S0 < S1) else 0 (unsigned borrow-out / carry-out) - * Deterministic semantic interpreter for SALU operations tracking SGPRs and SCC state. - * Cross-validation of shader assembly execution via rdna2spirv lowering and spirv_mini_interp. - * Multi-precision 64-bit subtraction borrow chain oracle (s_sub_u32 + s_subb_u32). -""" - -import os -import random -import struct -import sys -import tempfile -import unittest -import warnings - -HERE = os.path.dirname(os.path.abspath(__file__)) -ROOT = os.path.dirname(os.path.dirname(HERE)) -TOOLS_DIR = os.environ.get("LEONIDA_TOOLS_DIR") or os.path.join(ROOT, "tools") - -sys.dont_write_bytecode = True -if TOOLS_DIR not in sys.path: - sys.path.insert(0, TOOLS_DIR) -if HERE not in sys.path: - sys.path.insert(0, HERE) - -import rdna2spirv # noqa: E402 -import spirv_mini_interp as si # noqa: E402 - -MASK32 = 0xFFFFFFFF -MASK64 = 0xFFFFFFFFFFFFFFFF -STUB_DXBC = b"DXBC" + bytes(24) + struct.pack(" None: - global _TMP_DIR, _SRC_PATH - _TMP_DIR = tempfile.TemporaryDirectory() - disasm_dir = os.path.join(_TMP_DIR.name, "disasm") - os.mkdir(disasm_dir) - _SRC_PATH = os.path.join(disasm_dir, "ps_salu_sub_co.s") - with open(os.path.join(_TMP_DIR.name, "ps_salu_sub_co.dxbc"), "wb") as f: - f.write(STUB_DXBC) - - -def tearDownModule() -> None: - global _TMP_DIR, _SRC_PATH - if _TMP_DIR is not None: - _TMP_DIR.cleanup() - _TMP_DIR = None - _SRC_PATH = None - - -def ref_sub_co_u32(s0: int, s1: int) -> tuple[int, int]: - """Reference implementation of scalar subtract with carry-out (borrow). - - Returns (difference, borrow_out) where: - difference = (s0 - s1) & 0xFFFFFFFF - borrow_out = 1 if (s0 & 0xFFFFFFFF) < (s1 & 0xFFFFFFFF) else 0 - """ - u0 = s0 & MASK32 - u1 = s1 & MASK32 - diff = (u0 - u1) & MASK32 - borrow = 1 if u0 < u1 else 0 - return diff, borrow - - -def ref_subb_co_u32(s0: int, s1: int, borrow_in: int) -> tuple[int, int]: - """Reference implementation of scalar subtract with borrow-in and borrow-out.""" - u0 = s0 & MASK32 - u1 = s1 & MASK32 - b_in = 1 if borrow_in else 0 - diff = (u0 - u1 - b_in) & MASK32 - borrow = 1 if u0 < (u1 + b_in) else 0 - return diff, borrow - - -def ref_sub64(a_lo: int, a_hi: int, b_lo: int, b_hi: int) -> tuple[int, int, int]: - """Reference 64-bit subtraction decomposed into 32-bit halves with borrow.""" - a64 = ((a_hi & MASK32) << 32) | (a_lo & MASK32) - b64 = ((b_hi & MASK32) << 32) | (b_lo & MASK32) - diff64 = (a64 - b64) & MASK64 - borrow64 = 1 if a64 < b64 else 0 - return diff64 & MASK32, (diff64 >> 32) & MASK32, borrow64 - - -class ScalarALUInterpreter: - """Deterministic semantic interpreter for RDNA2 scalar ALU operations.""" - - def __init__(self, num_sgprs: int = 106) -> None: - self.sgpr = [0] * num_sgprs - self.scc = 0 - - def reset(self) -> None: - self.sgpr = [0] * len(self.sgpr) - self.scc = 0 - - @staticmethod - def eval_sub_co_u32(s0: int, s1: int) -> tuple[int, int]: - return ref_sub_co_u32(s0, s1) - - @staticmethod - def eval_subb_co_u32(s0: int, s1: int, borrow_in: int) -> tuple[int, int]: - return ref_subb_co_u32(s0, s1, borrow_in) - - def _resolve_val(self, operand: int | str | dict) -> int: - if isinstance(operand, int): - return operand & MASK32 - if isinstance(operand, dict): - if operand.get("k") == "imm": - return operand["v"] & MASK32 - if operand.get("k") == "sgpr": - return self.sgpr[operand["r"]] & MASK32 - if isinstance(operand, str) and operand.startswith("s"): - return self.sgpr[int(operand[1:])] & MASK32 - raise ValueError(f"Unknown operand: {operand}") - - def _resolve_dst(self, operand: int | str | dict) -> int | None: - if isinstance(operand, dict) and operand.get("k") == "sgpr": - return operand["r"] - if isinstance(operand, str) and operand.startswith("s"): - return int(operand[1:]) - if isinstance(operand, int): - return operand - return None - - def step(self, insn: dict) -> tuple[int, int]: - op = insn["op"] - dst_idx = self._resolve_dst(insn["dst"]) - s0 = self._resolve_val(insn["s0"]) - s1 = self._resolve_val(insn.get("s1", 0)) - - if op in ("s_sub_u32", "s_sub_co_u32"): - res, scc = self.eval_sub_co_u32(s0, s1) - self.scc = scc - elif op == "s_subb_u32": - res, scc = self.eval_subb_co_u32(s0, s1, self.scc) - self.scc = scc - elif op == "s_mov_b32": - res = s0 & MASK32 - elif op == "s_cselect_b32": - res = s0 & MASK32 if self.scc else s1 & MASK32 - else: - raise NotImplementedError(f"Unsupported op: {op}") - - if dst_idx is not None: - self.sgpr[dst_idx] = res - return res, self.scc - - def run_sequence(self, instructions: list[dict]) -> int: - last_res = 0 - for insn in instructions: - last_res, _ = self.step(insn) - return last_res - - -def run_assembly_lines(lines: list[str]) -> tuple[int, int]: - """Assemble a shader snippet, translate via rdna2spirv, and execute in spirv_mini_interp.""" - if _TMP_DIR is None or _SRC_PATH is None: - setUpModule() - asm = "; test_salu_sub_co_u32\n" + "".join(f"\t{ln}\n" for ln in lines) + "\texp mrt0 v0, v1, v0, v0 done vm\n\ts_endpgm\n" - with open(_SRC_PATH, "w", encoding="utf-8") as f: - f.write(asm) - with warnings.catch_warnings(): - warnings.simplefilter("ignore", ResourceWarning) - spv = rdna2spirv.translate(_SRC_PATH) - words = si.run_fragment(spv)["%out_mrt0"] - return int(words[0]), int(words[1]) - - -def run_salu_sub(s0: int, s1: int) -> tuple[int, int]: - """Execute s_sub_u32 in a pixel shader and return (result, SCC).""" - lines = [ - f"s_mov_b32 s2, {s0:#x}", - f"s_mov_b32 s3, {s1:#x}", - "s_sub_u32 s0, s2, s3", - "s_cselect_b32 s1, 1, 0", - "v_mov_b32 v0, s0", - "v_mov_b32 v1, s1", - ] - return run_assembly_lines(lines) - - -class TestScalarSubCoU32ReferenceOracle(unittest.TestCase): - """Validation of reference mathematical oracle and interpreter semantics.""" - - def setUp(self) -> None: - self.interp = ScalarALUInterpreter() - - def test_zero_identity(self) -> None: - for val in (0, 1, 42, 0x12345678, 0x7FFFFFFF, 0x80000000, 0xFFFFFFFF): - with self.subTest(val=hex(val)): - diff, borrow = ref_sub_co_u32(val, 0) - self.assertEqual(diff, val) - self.assertEqual(borrow, 0) - - def test_identical_operands_yield_zero_no_borrow(self) -> None: - for val in (0, 1, 0x1000, 0x7FFFFFFF, 0x80000000, 0xFFFFFFFF): - with self.subTest(val=hex(val)): - diff, borrow = ref_sub_co_u32(val, val) - self.assertEqual(diff, 0) - self.assertEqual(borrow, 0) - - def test_basic_subtraction_no_borrow(self) -> None: - pairs = [ - (10, 3, 7, 0), - (100, 100, 0, 0), - (0xFFFFFFFF, 1, 0xFFFFFFFE, 0), - (0x80000000, 0x7FFFFFFF, 1, 0), - (0x10000000, 0x0FFFFFFF, 1, 0), - ] - for s0, s1, exp_diff, exp_borrow in pairs: - with self.subTest(s0=hex(s0), s1=hex(s1)): - diff, borrow = ref_sub_co_u32(s0, s1) - self.assertEqual(diff, exp_diff) - self.assertEqual(borrow, exp_borrow) - - def test_borrow_boundary_detection(self) -> None: - cases = [ - (0, 1, 0xFFFFFFFF, 1), - (0, 0xFFFFFFFF, 1, 1), - (5, 10, 0xFFFFFFFB, 1), - (0x7FFFFFFF, 0x80000000, 0xFFFFFFFF, 1), - (0xFFFFFFFE, 0xFFFFFFFF, 0xFFFFFFFF, 1), - ] - for s0, s1, exp_diff, exp_borrow in cases: - with self.subTest(s0=hex(s0), s1=hex(s1)): - diff, borrow = ref_sub_co_u32(s0, s1) - self.assertEqual(diff, exp_diff) - self.assertEqual(borrow, exp_borrow) - - def test_interpreter_step_and_state(self) -> None: - self.interp.step({"op": "s_mov_b32", "dst": "s0", "s0": 100}) - self.interp.step({"op": "s_mov_b32", "dst": "s1", "s0": 40}) - res, scc = self.interp.step({"op": "s_sub_co_u32", "dst": "s2", "s0": "s0", "s1": "s1"}) - self.assertEqual(res, 60) - self.assertEqual(scc, 0) - self.assertEqual(self.interp.sgpr[2], 60) - self.assertEqual(self.interp.scc, 0) - - # Underflow step - res, scc = self.interp.step({"op": "s_sub_co_u32", "dst": "s3", "s0": 10, "s1": 25}) - self.assertEqual(res, (10 - 25) & MASK32) - self.assertEqual(scc, 1) - self.assertEqual(self.interp.sgpr[3], (10 - 25) & MASK32) - self.assertEqual(self.interp.scc, 1) - - def test_spirv_lowering_matches_reference_oracle(self) -> None: - cases = [ - (0, 0), - (1, 0), - (0, 1), - (100, 35), - (35, 100), - (0xFFFFFFFF, 0), - (0, 0xFFFFFFFF), - (0xFFFFFFFF, 0xFFFFFFFF), - (0x80000000, 1), - (0x7FFFFFFF, 0x80000000), - ] - for s0, s1 in cases: - with self.subTest(s0=hex(s0), s1=hex(s1)): - expected_diff, expected_scc = ref_sub_co_u32(s0, s1) - got_diff, got_scc = run_salu_sub(s0, s1) - self.assertEqual((got_diff, got_scc), (expected_diff, expected_scc)) - - def test_spirv_lowering_random_sweep(self) -> None: - rng = random.Random(0x50B0) - for _ in range(25): - s0 = rng.getrandbits(32) - s1 = rng.getrandbits(32) - expected = ref_sub_co_u32(s0, s1) - got = run_salu_sub(s0, s1) - self.assertEqual(got, expected) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_salu_waveid.py b/tests/semantic/test_salu_waveid.py deleted file mode 100644 index 8073e9e92..000000000 --- a/tests/semantic/test_salu_waveid.py +++ /dev/null @@ -1,99 +0,0 @@ -"""s_get_waveid_in_workgroup: the index of the wave within its workgroup. - -Standard library only; no GPU, no LLVM, no game files. - -RDNA2 ISA, SOPP S_GET_WAVEID_IN_WORKGROUP: D = the wave's ID within the workgroup. Thread i of a workgroup runs in -wave i / W and lane i % W (W = 32 or 64), the same rule the translator already uses for the hardware lane -(Gen.wave_lane), so D = LocalInvocationIndex / W. Only compute and mesh shaders have a workgroup; elsewhere the -instruction stays Unsupported. - -Each case translates a 1-D compute listing (128 threads), runs every invocation with run_workgroup on the CPU and -has each one store its D at buffer word LocalInvocationIndex; the words are compared with i / W. -""" -import os -import struct -import sys -import tempfile -import unittest -import warnings - -HERE = os.path.dirname(os.path.abspath(__file__)) -ROOT = os.path.dirname(os.path.dirname(HERE)) -TOOLS_DIR = os.environ.get("LEONIDA_TOOLS_DIR") or os.path.join(ROOT, "tools") - -sys.dont_write_bytecode = True -sys.path.insert(0, TOOLS_DIR) -sys.path.insert(0, HERE) - -import rdna2spirv # noqa: E402 -import spirv_mini_interp as si # noqa: E402 - -STUB_DXBC = b"DXBC" + bytes(24) + struct.pack(" bytes: - """Synthetic compute header: 4 user SGPRs (the output V#), workgroup id in s4, thread ids x, y, z in v0, v1, v2 - (RSRC2 TIDIG_COMP_CNT = 2), group size x * y * z.""" - blob = bytearray(0x148) - struct.pack_into("<4I", blob, 0x138, 0x88 | 2 << 11, x, y, z) - return bytes(blob) - - -def run(body: list, wave64: bool, size=(THREADS, 1, 1), name: str = "cs_waveid", subgroup: int = 32) -> list: - """Translate `body` (each thread then stores s5 at buffer word = its flat index) and run every invocation.""" - sx, sy, sz = size - lines = (["s_mov_b64 exec, -1"] if wave64 else []) + list(body) + [ - # flat index = x + y * sx + z * sx * sy from the local id in v0 / v1 / v2, times 4 bytes - f"v_mad_u32_u24 v3, v1, {sx}, v0", f"v_mad_u32_u24 v3, v2, {sx * sy}, v3", "v_lshlrev_b32 v3, 2, v3", - "v_mov_b32 v4, s5", "buffer_store_dword v4, v3, s[0:3], 0 offen"] - with tempfile.TemporaryDirectory() as tmp: - for d in ("disasm", "fssm"): - os.mkdir(os.path.join(tmp, d)) - with open(os.path.join(tmp, "disasm", name + ".s"), "w", encoding="utf-8") as f: - f.write("; " + name + "\n" + "".join(f"\t{ln}\n" for ln in lines) + "\ts_endpgm\n") - with open(os.path.join(tmp, name + ".dxbc"), "wb") as f: - f.write(STUB_DXBC) - with open(os.path.join(tmp, "fssm", name + ".fssm"), "wb") as f: - f.write(fssm(*size)) - with warnings.catch_warnings(): - warnings.simplefilter("ignore", ResourceWarning) - spv = rdna2spirv.translate(os.path.join(tmp, "disasm", name + ".s")) - n = sx * sy * sz - - def inputs(i): - return {"%wg_id": (0, 0, 0), "%local_id": (i % sx, (i // sx) % sy, i // (sx * sy)), "%sg_lane": i % subgroup} - mem = si.run_workgroup(spv, n, subgroup, inputs_for=inputs, push_constants=VSHARP + [0] * 28, memory={}) - return [mem.get(4 * i) for i in range(n)] - - -class WaveIdTests(unittest.TestCase): - def test_wave32(self): - self.assertEqual(run(["s_get_waveid_in_workgroup s5"], wave64=False), [i // 32 for i in range(THREADS)]) - - def test_wave64(self): - self.assertEqual(run(["s_get_waveid_in_workgroup s5"], wave64=True), [i // 64 for i in range(THREADS)]) - - def test_three_dimensional_group(self): - # 8 x 4 x 4 = 128 threads: the flat index is x + 8y + 32z, so z alone picks the wave in wave32. - got = run(["s_get_waveid_in_workgroup s5"], wave64=False, size=(8, 4, 4)) - self.assertEqual(got, [i // 32 for i in range(128)]) - - def test_other_stages_are_rejected(self): - with tempfile.TemporaryDirectory() as tmp: - os.mkdir(os.path.join(tmp, "disasm")) - path = os.path.join(tmp, "disasm", "ps_waveid.s") - with open(path, "w", encoding="utf-8") as f: - f.write("; ps_waveid\n\ts_get_waveid_in_workgroup s0\n\tv_mov_b32 v0, s0\n" - "\texp mrt0 v0, v0, v0, v0 done vm\n\ts_endpgm\n") - with open(os.path.join(tmp, "ps_waveid.dxbc"), "wb") as f: - f.write(STUB_DXBC) - with self.assertRaises(rdna2spirv.Unsupported): - with warnings.catch_warnings(): - warnings.simplefilter("ignore", ResourceWarning) - rdna2spirv.translate(path) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_salu_wqm32.py b/tests/semantic/test_salu_wqm32.py deleted file mode 100644 index 5ab78a069..000000000 --- a/tests/semantic/test_salu_wqm32.py +++ /dev/null @@ -1,318 +0,0 @@ -"""Translator-to-interpreter semantic tests for s_wqm_b32: - - s_wqm_b32 D, S0 D = every 4-bit quad of S0 that has any bit set becomes 0xF (else 0x0); SCC = (D != 0). - -Covers both: - - Data path (32-bit nibble expansion + SCC) via tools/rdna2spirv.py -> spirv_mini_interp.py. - - Lane-mask path (32-lane wave32, 8 quads) via tools/rdna2spirv.py -> spirv_wave_interp.py (vertex stage - uses OpGroupNonUniformShuffle for quad_any; fragment/compute stages are checked for OpGroupNonUniformQuadSwap). - -Standard library only; no game data. -""" -import os -import random -import sys -import unittest - -HERE = os.path.dirname(os.path.abspath(__file__)) -if HERE not in sys.path: - sys.path.insert(0, HERE) - -import spirv_wave_interp as wi # noqa: E402 -from support import mrt0_words, translate_lines # noqa: E402 - -MASK32 = 0xFFFFFFFF - - -def ref_wqm32(x): - x &= MASK32 - out = 0 - for nibble in range(8): - shift = nibble * 4 - if (x >> shift) & 0xF: - out |= 0xF << shift - return out, int(out != 0) - - -HAND_CONSTANTS = [ - (0x00000000, 0x00000000, 0), - (0xFFFFFFFF, 0xFFFFFFFF, 1), - (0x00000001, 0x0000000F, 1), - (0x80000000, 0xF0000000, 1), - (0x80000001, 0xF000000F, 1), - (0x12480001, 0xFFFF000F, 1), - (0x01020408, 0x0F0F0F0F, 1), - (0x00100020, 0x00F000F0, 1), - (0x40000000, 0xF0000000, 1), -] - - -def run_ps(name, body_lines, export_regs=("v0", "v1", "v0", "v1")): - lines = list(body_lines) + [f"exp mrt0 {', '.join(export_regs)} done vm", "s_endpgm"] - spv = translate_lines(name, lines) - return mrt0_words(spv), spv - - -class ReferenceConstantsTests(unittest.TestCase): - def test_hand_computed_constants(self): - for val, exp_d, exp_scc in HAND_CONSTANTS: - with self.subTest(val=hex(val)): - self.assertEqual(ref_wqm32(val), (exp_d, exp_scc)) - - -class DataPathWqm32Tests(unittest.TestCase): - def test_single_bit_across_all_32_positions(self): - for bit in range(32): - src = 1 << bit - exp_d, exp_scc = ref_wqm32(src) - with self.subTest(bit=bit): - words, _ = run_ps( - "ps_wqm_bit", - [ - f"s_mov_b32 s0, {src:#x}", - "s_wqm_b32 s1, s0", - "s_cselect_b32 s2, 1, 0", - "v_mov_b32 v0, s1", - "v_mov_b32 v1, s2", - ], - ) - self.assertEqual((words[0], words[1]), (exp_d, exp_scc)) - - def test_multi_nibble_patterns_and_scc_toggling(self): - for val, exp_d, exp_scc in HAND_CONSTANTS: - with self.subTest(val=hex(val)): - words, _ = run_ps( - "ps_wqm_const", - [ - f"s_mov_b32 s0, {val:#x}", - "s_wqm_b32 s1, s0", - "s_cselect_b32 s2, 1, 0", - "v_mov_b32 v0, s1", - "v_mov_b32 v1, s2", - ], - ) - self.assertEqual((words[0], words[1]), (exp_d, exp_scc)) - - toggle_words, _ = run_ps( - "ps_wqm_toggle", - [ - "s_mov_b32 s0, 0", - "s_wqm_b32 s1, s0", - "s_cselect_b32 s4, 1, 0", - "s_mov_b32 s0, 0x00001000", - "s_wqm_b32 s2, s0", - "s_cselect_b32 s5, 1, 0", - "s_mov_b32 s0, 0", - "s_wqm_b32 s3, s0", - "s_cselect_b32 s6, 1, 0", - "v_mov_b32 v0, s4", - "v_mov_b32 v1, s5", - "v_mov_b32 v2, s6", - "v_mov_b32 v3, s2", - ], - export_regs=("v0", "v1", "v2", "v3"), - ) - self.assertEqual(toggle_words, [0, 1, 0, 0x0000F000]) - - def test_inline_and_literal_operands(self): - for operand, src_val in (("0", 0), ("1", 1), ("15", 15), ("-1", MASK32), ("0x10200004", 0x10200004)): - exp_d, exp_scc = ref_wqm32(src_val) - with self.subTest(operand=operand): - words, _ = run_ps( - "ps_wqm_imm", - [ - f"s_wqm_b32 s1, {operand}", - "s_cselect_b32 s2, 1, 0", - "v_mov_b32 v0, s1", - "v_mov_b32 v1, s2", - ], - ) - self.assertEqual((words[0], words[1]), (exp_d, exp_scc)) - - def test_seeded_random_values(self): - rng = random.Random(0x57514D32) - for _ in range(16): - val = rng.getrandbits(32) - exp_d, exp_scc = ref_wqm32(val) - with self.subTest(val=hex(val)): - words, _ = run_ps( - "ps_wqm_rand", - [ - f"s_mov_b32 s0, {val:#x}", - "s_wqm_b32 s1, s0", - "s_cselect_b32 s2, 1, 0", - "v_mov_b32 v0, s1", - "v_mov_b32 v1, s2", - ], - ) - self.assertEqual((words[0], words[1]), (exp_d, exp_scc)) - - def test_data_in_place_and_null_destination(self): - for x in (0x00000000, 0x00000020, 0x40080001): - want_d, want_scc = ref_wqm32(x) - with self.subTest(alias=hex(x)): - words, _ = run_ps("ps_wqm_alias", [ - f"s_mov_b32 s0, {x:#x}", - "s_cmp_eq_u32 0, 1" if want_scc else "s_cmp_eq_u32 1, 1", - "s_wqm_b32 s0, s0", - "s_cselect_b32 s2, 1, 0", - "v_mov_b32 v0, s0", - "v_mov_b32 v1, s2", - ]) - self.assertEqual((words[0], words[1]), (want_d, want_scc)) - for x, want_scc in ((0x00000000, 0), (0x80000000, 1)): - with self.subTest(null=hex(x)): - words, _ = run_ps("ps_wqm_null", [ - f"s_mov_b32 s0, {x:#x}", - "s_cmp_eq_u32 0, 1" if want_scc else "s_cmp_eq_u32 1, 1", - "s_wqm_b32 null, s0", - "s_cselect_b32 s2, 1, 0", - "v_mov_b32 v0, s0", - "v_mov_b32 v1, s2", - ]) - self.assertEqual((words[0], words[1]), (x, want_scc)) - - -class LaneMaskWqm32Tests(unittest.TestCase): - def test_lane_mask_wave32_quad_expansion_in_wave_interp(self): - test_masks = (0x00000000, 0x00000001, 0x00000080, 0x12480001, 0x80000000, 0xFFFFFFFF) - for mask in test_masks: - exp_mask, exp_scc = ref_wqm32(mask) - with self.subTest(mask=hex(mask)): - spv = translate_lines( - "vs_wqm_mask", - [ - "v_and_b32_e32 v1, 31, v0", - "v_lshlrev_b32_e32 v2, v1, 1", - f"v_and_b32_e32 v2, {mask:#x}, v2", - "v_cmp_ne_u32_e32 vcc_lo, 0, v2", - "s_wqm_b32 s0, vcc_lo", - "s_cselect_b32 s1, 1, 0", - "v_cndmask_b32_e64 v3, 0, 1, s0", - "v_mov_b32 v4, s1", - "exp pos0 v3, v4, v1, v1 done", - "s_endpgm", - ], - ) - outputs = wi.run_wave( - spv, - wave=32, - builtins={"VertexIndex": lambda lane: lane, "InstanceIndex": lambda lane: 0}, - )["outputs"] - self.assertEqual(len(outputs), 32) - got_mask = 0 - for lane, out in enumerate(outputs): - self.assertIsNotNone(out) - self.assertEqual(len(out), 1) - active_word, scc_word, lane_word, _ = out[next(iter(out))] - self.assertEqual(lane_word, lane) - self.assertEqual(scc_word, exp_scc) - if active_word: - got_mask |= 1 << lane - self.assertEqual(got_mask, exp_mask) - - def run_vs32(self, name, lines, wave=32): - """Run a vertex shader on one wave; return each lane's param0 words.""" - spv = translate_lines(name, lines + [ - "v_mov_b32_e32 v20, 0", - "exp pos0 v20, v20, v20, v20 done", - "exp param0 v0, v1, v2, v3", - "s_endpgm", - ]) - outs = wi.run_wave(spv, wave=wave, - builtins={"VertexIndex": lambda lane: lane, "InstanceIndex": lambda lane: 0})["outputs"] - return [next(v for k, v in o.items() if k.endswith("param0")) for o in outs] - - def test_exec_lo_sgpr_and_null_destinations(self): - # v1 = 0x22 on the lanes the new EXEC keeps, v2 = D's bit for this lane; SCC is seeded to the other value. - masks = (0x00000000, 0x00000020, 0x80000000, 0x40080021, 0xFFFFFFFF) - forms = [ - # (dst, src, EXEC set from the mask first) - ("exec_lo", "vcc_lo", False), - ("exec_lo", "exec_lo", True), - ("exec_lo", "literal", False), # data, not a lane mask, written to EXEC - ("s4", "s2", False), # lane mask in an SGPR - ("null", "vcc_lo", False), - ] - for dst, src, from_exec in forms: - for mask in masks: - want_d, want_scc = ref_wqm32(mask) - with self.subTest(dst=dst, src=src, mask=hex(mask)): - lines = ["v_mbcnt_lo_u32_b32 v4, -1, 0", "v_lshlrev_b32_e32 v5, v4, 1", - f"v_and_b32_e32 v6, {mask:#x}, v5", "v_mov_b32_e32 v1, 0x11"] - if from_exec: - lines.append("v_cmpx_ne_u32_e32 0, v6") - elif src == "vcc_lo": - lines.append("v_cmp_ne_u32_e32 vcc_lo, 0, v6") - elif src == "s2": - lines.append("v_cmp_ne_u32_e64 s2, 0, v6") - operand = f"{mask:#x}" if src == "literal" else src - lines += [ - "s_cmp_eq_u32 0, 1" if want_scc else "s_cmp_eq_u32 1, 1", - f"s_wqm_b32 {dst}, {operand}", - "s_cselect_b32 s10, 1, 0", - "v_mov_b32_e32 v1, 0x22", - "s_mov_b32 exec_lo, -1", - "v_mov_b32_e32 v0, s10", - f"v_cndmask_b32_e64 v2, 0, 1, {dst}" if dst == "s4" else "v_mov_b32_e32 v2, 0", - "v_mov_b32_e32 v3, 0", - ] - outs = self.run_vs32("vs_wqm_dst", lines) - new_exec = want_d if dst == "exec_lo" else MASK32 - for lane in range(32): - want = (want_scc, 0x22 if new_exec >> lane & 1 else 0x11, - want_d >> lane & 1 if dst == "s4" else 0, 0) - self.assertEqual(outs[lane], want, f"lane {lane}") - - def test_wave64_exec_half_changes_and_votes_only_its_half(self): - # In wave64, s_wqm_b32 exec_lo, exec_lo expands lanes 0..31 only and SCC votes over them (likewise exec_hi): - # the other half is kept, and an empty half gives SCC = 0 even when the other half has lanes on. - cases = [ - # (half, exec_lo, exec_hi, new exec_lo, new exec_hi, SCC) - ("exec_lo", 0x00000020, 0x00000001, 0x000000F0, 0x00000001, 1), - ("exec_lo", 0x00000000, 0x00000001, 0x00000000, 0x00000001, 0), - ("exec_hi", 0x00000001, 0x00000020, 0x00000001, 0x000000F0, 1), - ("exec_hi", 0x00000001, 0x00000000, 0x00000001, 0x00000000, 0), - ] - for half, lo, hi, want_lo, want_hi, want_scc in cases: - want_exec = want_lo | want_hi << 32 - with self.subTest(half=half, lo=hex(lo), hi=hex(hi)): - outs = self.run_vs32("vs_wqm_w64half", [ - "s_mov_b64 s[12:13], exec", - "v_mov_b32_e32 v1, 0x11", - f"s_mov_b32 exec_lo, {lo:#x}", - f"s_mov_b32 exec_hi, {hi:#x}", - "s_cmp_eq_u32 0, 1" if want_scc else "s_cmp_eq_u32 1, 1", - f"s_wqm_b32 {half}, {half}", - "s_cselect_b32 s10, 1, 0", - "v_mov_b32_e32 v1, 0x22", - "s_mov_b64 exec, -1", - "v_mov_b32_e32 v0, s10", - "v_mov_b32_e32 v2, 0", - "v_mov_b32_e32 v3, 0", - ], wave=64) - for lane in range(64): - self.assertEqual(outs[lane], (want_scc, 0x22 if want_exec >> lane & 1 else 0x11, 0, 0), - f"lane {lane}") - - def test_ps_lane_mask_emits_quad_swap_and_vote_any(self): - spv = translate_lines( - "ps_wqm_mask_struct", - [ - "v_mbcnt_lo_u32_b32 v0, -1, 0", - "v_cmp_eq_u32_e32 vcc_lo, 0, v0", - "s_wqm_b32 s0, vcc_lo", - "s_cselect_b32 s1, 1, 0", - "v_cndmask_b32_e64 v1, 0, 1, s0", - "v_mov_b32 v2, s1", - "exp mrt0 v1, v2, v1, v2 done vm", - "s_endpgm", - ], - ) - self.assertGreaterEqual(spv.count("OpGroupNonUniformQuadSwap %uint"), 2) - self.assertIn("OpGroupNonUniformBallot %v4uint_bal", spv) - self.assertIn("%c20", spv) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_salu_wqm_b32.py b/tests/semantic/test_salu_wqm_b32.py deleted file mode 100644 index 26aa5adc5..000000000 --- a/tests/semantic/test_salu_wqm_b32.py +++ /dev/null @@ -1,153 +0,0 @@ -"""Semantic interpreter tests for RDNA2 s_wqm_b32 (Whole-Quad Mode). - -Verifies both the 32-bit result D (each 4-bit quad becomes 0xF if any bit in the -quad is 1, else 0x0) and the SCC flag (1 when D != 0, 0 when D == 0), across -SGPR, inline, and literal sources, plus in-memory SPIR-V negative controls. -""" -import os -import re -import sys -import unittest - -sys.dont_write_bytecode = True - -HERE = os.path.dirname(os.path.abspath(__file__)) -if HERE not in sys.path: - sys.path.insert(0, HERE) - -import spirv_mini_interp as si # noqa: E402 -import support # noqa: E402 - -MASK32 = 0xFFFFFFFF - - -def ref_wqm_b32(x: int) -> int: - """Plain-Python reference for s_wqm_b32 on 32-bit data.""" - out = 0 - for q in range(8): - if (x >> (4 * q)) & 0xF: - out |= 0xF << (4 * q) - return out & MASK32 - - -def build_lines(body_lines) -> list: - """Wrap s_wqm_b32 test instructions with SCC capture and mrt0 export.""" - return list(body_lines) + [ - "s_cselect_b32 s1, 1, 0", - "v_mov_b32 v0, s0", - "v_mov_b32 v1, s1", - "exp mrt0 v0, v1, v0, v0 done vm", - "s_endpgm", - ] - - -def run_wqm(body_lines) -> tuple: - """Translate and run lines, returning (D, SCC).""" - spv = support.translate_lines("ps_salu_wqm_b32", build_lines(body_lines)) - return tuple(si.run_fragment(spv)["%out_mrt0"][:2]) - - -class SaluWqmB32Tests(unittest.TestCase): - def test_single_bit_all_quads_and_positions(self): - for q in range(8): - for b in range(4): - x = 1 << (4 * q + b) - want = 0xF << (4 * q) - self.assertEqual(want, ref_wqm_b32(x)) - with self.subTest(quad=q, bit=b, x=hex(x)): - got = run_wqm([ - f"s_mov_b32 s2, {x:#x}", - "s_wqm_b32 s0, s2", - ]) - self.assertEqual(got, (want, 1)) - - def test_boundary_and_non_adjacent_quad_patterns(self): - cases = [ - 0x00000000, - 0xFFFFFFFF, - 0x80000000, - 0x00000001, - 0x10402081, - 0x80040201, - 0x050A0C03, - 0xA0000005, - 0x0F00F000, - 0x12345678, - ] - for x in cases: - want = ref_wqm_b32(x) - with self.subTest(x=hex(x)): - got = run_wqm([ - f"s_mov_b32 s2, {x:#x}", - "s_wqm_b32 s0, s2", - ]) - self.assertEqual(got, (want, int(want != 0))) - - def test_zero_clears_preset_scc(self): - for src in ("s2", "0"): - with self.subTest(src=src): - lines = [ - "s_mov_b32 s4, 7", - "s_cmp_eq_u32 s4, s4", # pre-set SCC = 1 - ] - if src == "s2": - lines.append("s_mov_b32 s2, 0") - lines.append(f"s_wqm_b32 s0, {src}") - self.assertEqual(run_wqm(lines), (0, 0)) - - def test_inline_and_literal_sources(self): - cases = [ - ("0", 0), - ("1", 1), - ("8", 8), - ("16", 16), - ("-1", 0xFFFFFFFF), - ("0x80000000", 0x80000000), - ("0x10400201", 0x10400201), - ("0x00800002", 0x00800002), - ] - for asm_imm, val in cases: - want = ref_wqm_b32(val) - with self.subTest(imm=asm_imm): - got = run_wqm([f"s_wqm_b32 s0, {asm_imm}"]) - self.assertEqual(got, (want, int(want != 0))) - - def test_negative_controls_spirv_mutations(self): - # 1) Mutate quad mask constant 0x11111111 (286331153 -> 286331152, dropping quad 0). - spv_mask = support.translate_lines( - "ps_wqm_neg_mask", - build_lines(["s_mov_b32 s2, 1", "s_wqm_b32 s0, s2"]), - ) - self.assertIn("OpConstant %uint 286331153", spv_mask) - bad_mask = spv_mask.replace("OpConstant %uint 286331153", "OpConstant %uint 286331152", 1) - got_bad_mask = tuple(si.run_fragment(bad_mask)["%out_mrt0"][:2]) - self.assertNotEqual(got_bad_mask, (0x0000000F, 1)) - - # 2) Mutate shift-by-3 in wqm_word (%c3 -> %c2) so bit 3 of quad 0 fails to reach bit 0. - spv_shift = support.translate_lines( - "ps_wqm_neg_shift", - build_lines(["s_mov_b32 s2, 8", "s_wqm_b32 s0, s2"]), - ) - bad_shift, n_sub = re.subn( - r"(OpShiftRightLogical %uint %\w+ )%c3\b", - r"\1%c2", - spv_shift, - count=1, - ) - self.assertEqual(n_sub, 1) - got_bad_shift = tuple(si.run_fragment(bad_shift)["%out_mrt0"][:2]) - self.assertNotEqual(got_bad_shift, (0x0000000F, 1)) - - # 3) Mutate SCC nonzero check (OpINotEqual -> OpIEqual) on s_wqm_b32. - spv_scc = support.translate_lines( - "ps_wqm_neg_scc", - build_lines(["s_mov_b32 s2, 1", "s_wqm_b32 s0, s2"]), - ) - self.assertIn("OpINotEqual %bool", spv_scc) - bad_scc = spv_scc.replace("OpINotEqual %bool", "OpIEqual %bool", 1) - got_bad_scc = tuple(si.run_fragment(bad_scc)["%out_mrt0"][:2]) - self.assertNotEqual(got_bad_scc, (0x0000000F, 1)) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_salu_wrexec_flbit32.py b/tests/semantic/test_salu_wrexec_flbit32.py deleted file mode 100644 index b16554fee..000000000 --- a/tests/semantic/test_salu_wrexec_flbit32.py +++ /dev/null @@ -1,224 +0,0 @@ -"""Semantic interpreter tests for RDNA2 s_andn1_wrexec_b32, s_andn2_wrexec_b32, -s_andn1_wrexec_b64, and s_flbit_i32_b32. - -s_andn1_wrexec_b{32,64} (RDNA2 ISA): EXEC = ~S0 & EXEC; D = EXEC; SCC = (EXEC != 0). -s_andn2_wrexec_b{32,64} (RDNA2 ISA): EXEC = S0 & ~EXEC; D = EXEC; SCC = (EXEC != 0). -Each wrexec case translates a synthetic pixel shader with tools/rdna2spirv.py, runs all 32 or 64 -lanes in tests/semantic/spirv_wave_interp.py, and checks per-lane EXEC update, D mask, and SCC. - -s_flbit_i32_b32 (RDNA2 ISA): D = leading-zero count from MSB (32 - bit_length(S0), or 0xFFFFFFFF if -S0 == 0); SCC is not written. Each case translates a synthetic pixel shader with tools/rdna2spirv.py, -runs it in tests/semantic/spirv_mini_interp.py, and checks D and preserved SCC. -""" -import os -import random -import sys -import unittest - -HERE = os.path.dirname(os.path.abspath(__file__)) -sys.dont_write_bytecode = True -if HERE not in sys.path: - sys.path.insert(0, HERE) - -import spirv_mini_interp as si # noqa: E402 -import spirv_wave_interp as wi # noqa: E402 -import support # noqa: E402 - -MASK32 = 0xFFFFFFFF -ALL64 = 0xFFFFFFFFFFFFFFFF - - -def ref_wrexec(op: str, s0: int, old_exec: int, wave: int) -> tuple: - mask = (1 << wave) - 1 - if "andn1" in op: - new_exec = (~s0 & old_exec) & mask - else: - new_exec = (s0 & ~old_exec) & mask - return new_exec, new_exec, int(new_exec != 0) - - -def ref_flbit_i32_b32(x: int) -> int: - x &= MASK32 - return MASK32 if x == 0 else 32 - x.bit_length() - - -def run_wrexec_wave(op: str, wave: int, s0_mask: int, old_exec: int) -> tuple: - """Run `op` on a `wave`-lane PS; return (new_exec_mask, d_mask, scc).""" - w64 = wave == 64 - s0_reg, d_reg = ("s[2:3]", "s[4:5]") if w64 else ("s2", "s4") - # Build S0 in s0_reg from per-lane bit tests against v4 (lane id). - if w64: - s0_setup = [ - f"s_mov_b32 s6, {s0_mask & MASK32:#x}", - f"s_mov_b32 s7, {(s0_mask >> 32) & MASK32:#x}", - "v_and_b32_e32 v5, 31, v4", - "v_lshlrev_b32_e32 v5, v5, 1", - "v_and_b32_e32 v6, v5, s6", - "v_and_b32_e32 v7, v5, s7", - "v_cmp_lt_u32_e32 vcc, 31, v4", - "v_cndmask_b32_e32 v5, v6, v7, vcc", - f"v_cmp_ne_u32_e64 {s0_reg}, 0, v5", - ] - exec_setup = [ - f"s_mov_b32 exec_lo, {old_exec & MASK32:#x}", - f"s_mov_b32 exec_hi, {(old_exec >> 32) & MASK32:#x}", - ] - else: - s0_setup = [ - f"s_mov_b32 s6, {s0_mask & MASK32:#x}", - "v_lshlrev_b32_e32 v5, v4, 1", - "v_and_b32_e32 v5, v5, s6", - f"v_cmp_ne_u32_e64 {s0_reg}, 0, v5", - ] - exec_setup = [f"s_mov_b32 exec_lo, {old_exec & MASK32:#x}"] - - lines = ( - ["v_mbcnt_lo_u32_b32 v4, -1, 0"] - + (["v_mbcnt_hi_u32_b32 v4, -1, v4"] if w64 else []) - + s0_setup - + ["v_mov_b32 v1, 0x11"] - + exec_setup - + [ - f"{op} {d_reg}, {s0_reg}", - "s_cselect_b32 s10, 1, 0", - "v_mov_b32 v1, 0x22", - f"s_mov_b{wave} exec, -1", - f"v_cndmask_b32_e64 v2, 0, 1, {d_reg}", - "v_mov_b32 v0, s10", - "v_mov_b32 v3, 0", - "exp mrt0 v0, v1, v2, v3 done vm", - "s_endpgm", - ] - ) - spv = support.translate_lines(f"ps_{op}", lines) - res = wi.run_wave(spv, wave=wave) - outs = res["outputs"] - assert len(outs) == wave - new_exec = 0 - d_mask = 0 - scc = outs[0]["%out_mrt0"][0] - for lane, out in enumerate(outs): - assert out is not None, f"lane {lane} killed" - lane_scc, exec_tag, d_bit, _ = out["%out_mrt0"] - assert lane_scc == scc, f"lane {lane} SCC mismatch" - assert exec_tag in (0x11, 0x22), f"lane {lane} unexpected exec_tag {exec_tag:#x}" - assert d_bit in (0, 1), f"lane {lane} unexpected d_bit {d_bit}" - if exec_tag == 0x22: - new_exec |= 1 << lane - d_mask |= d_bit << lane - return new_exec, d_mask, scc - - -def run_flbit(setup_lines, src_op: str, scc_in: int) -> tuple: - lines = [ - *setup_lines, - f"s_mov_b32 s4, {scc_in}", - "s_cmp_eq_u32 s4, 1", - f"s_flbit_i32_b32 s0, {src_op}", - "s_cselect_b32 s1, 1, 0", - "v_mov_b32 v0, s0", - "v_mov_b32 v1, s1", - "exp mrt0 v0, v1, v0, v0 done vm", - "s_endpgm", - ] - spv = support.translate_lines("ps_salu_flbit32", lines) - out = si.run_fragment(spv)["%out_mrt0"] - return out[0], out[1] - - -class WrexecB32Tests(unittest.TestCase): - CASES_32 = [ - (0x0000FFFF, 0x00FF00FF), # mixed overlap - (0xFFFFFFFF, 0xFFFFFFFF), # andn1 -> 0 (SCC=0), andn2 -> 0 (SCC=0) - (0x00000000, 0xFFFFFFFF), # andn1 -> ALL32 (SCC=1), andn2 -> 0 (SCC=0) - (0xFFFFFFFF, 0x00000000), # andn1 -> 0 (SCC=0), andn2 -> ALL32 (SCC=1) - (0xAAAAAAAA, 0x55555555), # disjoint alternating lanes - (0x80000001, 0xFFFFFFFF), # boundary lanes 0 and 31 - (0x00000000, 0x00000000), # both zero -> 0 (SCC=0) - ] - - def test_wrexec_b32_and_contrast(self): - for s0, old_exec in self.CASES_32: - for op in ("s_andn1_wrexec_b32", "s_andn2_wrexec_b32"): - with self.subTest(op=op, s0=hex(s0), exec=hex(old_exec)): - self.assertEqual( - run_wrexec_wave(op, 32, s0, old_exec), - ref_wrexec(op, s0, old_exec, 32), - ) - - -class WrexecB64Tests(unittest.TestCase): - CASES_64 = [ - (0xFFFFFFFF00000000, 0x00000000FFFFFFFF, "low-half only"), - (0x00000000FFFFFFFF, 0xFFFFFFFF00000000, "high-half only"), - (0xFFFF00000000FFFF, 0x0000FFFFFFFF0000, "straddling bit 31/32"), - (0x0000FFFF0000FFFF, 0x000001FFFE000000, "straddling 25..40"), - (0x0000000000000000, ALL64, "all-ones for andn1, all-zero for andn2"), - (ALL64, 0x0000000000000000, "all-zero for andn1, all-ones for andn2"), - (ALL64, ALL64, "all-zero for both (SCC=0)"), - (0x5555555555555555, 0xF0F0F0F00F0F0F0F, "mixed alternating"), - ] - - def test_wrexec_b64_and_contrast(self): - for s0, old_exec, desc in self.CASES_64: - for op in ("s_andn1_wrexec_b64", "s_andn2_wrexec_b64"): - with self.subTest(op=op, case=desc): - self.assertEqual( - run_wrexec_wave(op, 64, s0, old_exec), - ref_wrexec(op, s0, old_exec, 64), - ) - - -class FlbitI32B32Tests(unittest.TestCase): - BOUNDARIES = [ - (0, 0xFFFFFFFF), - (0x80000000, 0), - (0x40000000, 1), - (1, 31), - (0x00010000, 15), - (0xFFFFFFFF, 0), - (0x7FFFFFFF, 1), - (0x00000002, 30), - ] - - def test_reference(self): - for val, want in self.BOUNDARIES: - self.assertEqual(ref_flbit_i32_b32(val), want) - - def test_boundaries_and_scc_preserved(self): - for val, want in self.BOUNDARIES: - for scc_in in (0, 1): - with self.subTest(val=hex(val), scc_in=scc_in): - self.assertEqual( - run_flbit([f"s_mov_b32 s2, {val:#x}"], "s2", scc_in), - (want, scc_in), - ) - - def test_all_single_bits(self): - for bit in range(32): - val = 1 << bit - with self.subTest(bit=bit): - self.assertEqual( - run_flbit([f"s_mov_b32 s2, {val:#x}"], "s2", bit & 1), - (31 - bit, bit & 1), - ) - - def test_inline_and_literal_operands(self): - for lit, val in [("0", 0), ("1", 1), ("-1", 0xFFFFFFFF), ("0x40000000", 0x40000000), ("0x00010000", 0x00010000)]: - with self.subTest(lit=lit): - self.assertEqual(run_flbit([], lit, 1), (ref_flbit_i32_b32(val), 1)) - - def test_seeded_random(self): - rng = random.Random(0xF1B17) - for _ in range(30): - val = rng.getrandbits(32) >> rng.randint(0, 31) - scc_in = rng.randint(0, 1) - with self.subTest(val=hex(val)): - self.assertEqual( - run_flbit([f"s_mov_b32 s2, {val:#x}"], "s2", scc_in), - (ref_flbit_i32_b32(val), scc_in), - ) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_salu_xnor_saveexec_b64.py b/tests/semantic/test_salu_xnor_saveexec_b64.py deleted file mode 100644 index 3282883ea..000000000 --- a/tests/semantic/test_salu_xnor_saveexec_b64.py +++ /dev/null @@ -1,34 +0,0 @@ -"""s_xnor_saveexec_b64 through the translator, on every lane of a wave64. - -RDNA2 ISA, SOP1: - s_xnor_saveexec_b64: D = EXEC; EXEC = ~(S0 ^ EXEC); SCC = (EXEC != 0). - -Each case translates a hand-written compute program with tools/rdna2spirv.py and runs 64 lanes in -tests/semantic/spirv_mini_interp.py (harness: saveexec_run.py), with S0 from VCC, an SGPR pair written by v_cmp, an -SGPR pair loaded with literals, and EXEC itself, against the ISA formula in plain Python. Until this file, the test of -this name ran a self-built interpreter and never called the translator. -""" -import os -import sys -import unittest - -sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) -import saveexec_run # noqa: E402 (support puts tools/ on sys.path) - - -class Saveexec(unittest.TestCase): - def test_xnor_by_hand(self): - # S0 = lanes 0..31, EXEC = lanes 16..47: EXEC = ~(S0 ^ EXEC) written out by hand. - lanes = lambda lo, hi: sum(1 << l for l in range(lo, hi)) - s0, e = lanes(0, 32), lanes(16, 48) - want = {"and": lanes(16, 32), "andn2": lanes(0, 16), "or": lanes(0, 48), "orn2": lanes(0, 32) | lanes(48, 64) | lanes(16, 32), - "xor": lanes(0, 16) | lanes(32, 48), "nand": lanes(0, 16) | lanes(32, 64), - "nor": lanes(48, 64), "xnor": lanes(16, 32) | lanes(48, 64)}["xnor"] - self.assertEqual(saveexec_run.model("xnor", s0, e), (want, e, 1)) - - def test_xnor_every_lane(self): - saveexec_run.check(self, "xnor") - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_salu_xor_saveexec_b64.py b/tests/semantic/test_salu_xor_saveexec_b64.py deleted file mode 100644 index 70f8dcb9f..000000000 --- a/tests/semantic/test_salu_xor_saveexec_b64.py +++ /dev/null @@ -1,34 +0,0 @@ -"""s_xor_saveexec_b64 through the translator, on every lane of a wave64. - -RDNA2 ISA, SOP1: - s_xor_saveexec_b64: D = EXEC; EXEC = S0 ^ EXEC; SCC = (EXEC != 0). - -Each case translates a hand-written compute program with tools/rdna2spirv.py and runs 64 lanes in -tests/semantic/spirv_mini_interp.py (harness: saveexec_run.py), with S0 from VCC, an SGPR pair written by v_cmp, an -SGPR pair loaded with literals, and EXEC itself, against the ISA formula in plain Python. Until this file, the test of -this name ran a self-built interpreter and never called the translator. -""" -import os -import sys -import unittest - -sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) -import saveexec_run # noqa: E402 (support puts tools/ on sys.path) - - -class Saveexec(unittest.TestCase): - def test_xor_by_hand(self): - # S0 = lanes 0..31, EXEC = lanes 16..47: EXEC = S0 ^ EXEC written out by hand. - lanes = lambda lo, hi: sum(1 << l for l in range(lo, hi)) - s0, e = lanes(0, 32), lanes(16, 48) - want = {"and": lanes(16, 32), "andn2": lanes(0, 16), "or": lanes(0, 48), "orn2": lanes(0, 32) | lanes(48, 64) | lanes(16, 32), - "xor": lanes(0, 16) | lanes(32, 48), "nand": lanes(0, 16) | lanes(32, 64), - "nor": lanes(48, 64), "xnor": lanes(16, 32) | lanes(48, 64)}["xor"] - self.assertEqual(saveexec_run.model("xor", s0, e), (want, e, 1)) - - def test_xor_every_lane(self): - saveexec_run.check(self, "xor") - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_sample_c.py b/tests/semantic/test_sample_c.py deleted file mode 100644 index 61fe3c432..000000000 --- a/tests/semantic/test_sample_c.py +++ /dev/null @@ -1,111 +0,0 @@ -"""image_sample_c and image_sample_c_b (and their _o forms): depth-compare samples with implicit LOD / bias. - -Standard library only (spirv-val is used when it is on PATH); no GPU, no LLVM, no game files. - -The GPU fixtures are runtime/test/shaders/ps_sample_c.asm and ps_sample_c_b.asm (vk_texture_test dref_c, dref_c_b). Here: -the shape of the SPIR-V in a pixel shader (OpImageSampleDrefImplicitLod, a Bias operand for _c_b, the Offset for _o), -LOD 0 for _c and explicit bias LOD for _c_b outside the pixel stage, d16 and a16 forms, and that the module validates. -""" -import os -import re -import shutil -import struct -import subprocess -import tempfile -import unittest - -import support - -DESC = "s[8:15], s[16:19]" -CS_FSSM = bytearray(0x148) -struct.pack_into("<4I", CS_FSSM, 0x138, 0x8088, 32, 1, 1) -CS_FSSM = bytes(CS_FSSM) -PRO = ["v_mov_b32 v4, 1.0", "v_mov_b32 v5, 0.5", "v_mov_b32 v6, 0.25", "v_mov_b32 v7, 0.75", "v_mov_b32 v8, 0"] - - -def translate(name, line): - fssm = CS_FSSM if name.startswith("cs_") else None - return support.translate_lines(name, PRO + [line, "exp mrt0 v9, v9, v9, v9 done vm", "s_endpgm"] - if name.startswith("ps_") else PRO + [line, "s_endpgm"], fssm=fssm) - - -def samples(spv): - return [ln.strip() for ln in spv.splitlines() if "= OpImageSample" in ln] - - -class SampleC(unittest.TestCase): - def test_c_is_dref_implicit_lod_in_a_pixel_shader(self): - spv = translate("ps_samplec", f"image_sample_c v9, v[4:6], {DESC} dmask:0x1 dim:SQ_RSRC_IMG_2D") - (line,) = samples(spv) - self.assertRegex(line, r"= OpImageSampleDrefImplicitLod %float %\w+ %\w+ %\w+$") - - def test_c_b_has_a_bias_operand(self): - spv = translate("ps_samplecb", f"image_sample_c_b v9, v[4:7], {DESC} dmask:0x1 dim:SQ_RSRC_IMG_2D") - (line,) = samples(spv) - self.assertRegex(line, r"= OpImageSampleDrefImplicitLod %float %\w+ %\w+ %\w+ Bias %\w+$") - - def test_offset_forms_carry_the_offset(self): - for op, regs in (("image_sample_c_o", "v[4:7]"), ("image_sample_c_b_o", "v[4:8]")): - with self.subTest(op=op): - spv = translate("ps_sampleco", f"{op} v9, {regs}, {DESC} dmask:0x1 dim:SQ_RSRC_IMG_2D") - (line,) = samples(spv) - self.assertIn("OpImageSampleDrefImplicitLod", line) - self.assertIn("Offset", line) - - def test_d16_result_is_an_f16_in_the_low_half(self): - spv = translate("ps_sampled16", f"image_sample_c v9, v[4:6], {DESC} dmask:0x1 dim:SQ_RSRC_IMG_2D d16") - self.assertIn("OpImageSampleDrefImplicitLod", spv) - self.assertNotIn("PackHalf2x16", spv) - - def test_c_outside_a_pixel_shader_samples_lod_zero(self): - for name, fssm in (("vs_samplec", None), ("cs_samplec", CS_FSSM)): - with self.subTest(shader=name): - spv = translate(name, f"image_sample_c v9, v[4:6], {DESC} dmask:0x1 dim:SQ_RSRC_IMG_2D") - (line,) = samples(spv) - self.assertRegex(line, r"= OpImageSampleDrefExplicitLod %float %\w+ %\w+ %\w+ Lod %f0$") - - def test_c_b_outside_a_pixel_shader_samples_bias_as_explicit_lod(self): - for name in ("vs_samplecb", "cs_samplecb"): - with self.subTest(shader=name): - spv = translate(name, f"image_sample_c_b v9, v[4:7], {DESC} dmask:0x1 dim:SQ_RSRC_IMG_2D") - (line,) = samples(spv) - self.assertRegex(line, r"= OpImageSampleDrefExplicitLod %float %\w+ %\w+ %\w+ Lod %\w+$") - - def test_the_bias_comes_before_the_compare(self): - # GFX10 address order after the offset: bias, z-compare, coordinates (the compare in v5, the bias in v4). - spv = translate("ps_sampleorder", f"image_sample_c_b v9, v[4:7], {DESC} dmask:0x1 dim:SQ_RSRC_IMG_2D") - (line,) = samples(spv) - ref, bias = re.search(r"%\w+ %\w+ (%\w+) Bias (%\w+)$", line).groups() - - def loaded_from(value): - """The VGPR index a value was loaded from: the OpLoad of %vgpr[k] behind it, through bitcasts.""" - for _ in range(6): - m = re.search(rf"^\s*{re.escape(value)} = (\w+) (?:%\w+ )?(%\w+)", spv, re.M) - if not m: - return None - op, src = m.groups() - if op == "OpLoad": - m2 = re.search(rf"^\s*{re.escape(src)} = OpAccessChain %\S+ %vgpr (%\w+)", spv, re.M) - consts = {k: int(v) for k, v in re.findall(r"^\s*(%\w+) = OpConstant %uint (\d+)", spv, re.M)} - return consts.get(m2.group(1)) if m2 else None - value = src - return None - self.assertEqual((loaded_from(bias), loaded_from(ref)), (4, 5)) - - @unittest.skipUnless(shutil.which("spirv-as") and shutil.which("spirv-val"), "needs spirv-as and spirv-val on PATH") - def test_modules_validate(self): - for op, regs in (("image_sample_c", "v[4:6]"), ("image_sample_c_b", "v[4:7]"), ("image_sample_c_o", "v[4:7]"), - ("image_sample_c_b_o", "v[4:8]")): - with self.subTest(op=op): - spv = translate("ps_sampleval", f"{op} v9, {regs}, {DESC} dmask:0x1 dim:SQ_RSRC_IMG_2D") - with tempfile.TemporaryDirectory() as tmp: - a, b = os.path.join(tmp, "m.spvasm"), os.path.join(tmp, "m.spv") - with open(a, "w", encoding="utf-8", newline="\n") as f: - f.write(spv) - subprocess.run(["spirv-as", "--target-env", "vulkan1.2", a, "-o", b], check=True) - # a texel offset that comes from a register needs VK_KHR_maintenance8 (design.md, Texel offsets) - subprocess.run(["spirv-val", "--target-env", "vulkan1.2", "--allow-offset-texture-operand", b], check=True) - - -if __name__ == "__main__": - unittest.main() \ No newline at end of file diff --git a/tests/semantic/test_sample_cl.py b/tests/semantic/test_sample_cl.py deleted file mode 100644 index 464d313f6..000000000 --- a/tests/semantic/test_sample_cl.py +++ /dev/null @@ -1,129 +0,0 @@ -"""image_sample_cl, _b_cl, _c_cl, _c_b_cl (and their _o forms): implicit-LOD samples with a min-LOD clamp. - -Standard library only (spirv-val is used when it is on PATH); no GPU, no LLVM, no game files. - -GPU tests: ps_texture_cl and ps_texture_b_cl (two-mip texture, check.py GRADIENT_TESTS / CLAMP_TESTS). Here the shape -of the SPIR-V: the clamp is the component after the coordinates and becomes MinLod (with Bias, with the compare, after -Offset), outside the pixel stage the LOD is max(0, clamp), a16 packs the clamp with the coordinates, and the module -declares MinLod and validates. -""" -import os -import re -import shutil -import struct -import subprocess -import tempfile -import unittest - -import support - -DESC = "s[8:15], s[16:19]" -D2 = "dim:SQ_RSRC_IMG_2D" -PRO = ["v_mov_b32 v4, 1.0", "v_mov_b32 v5, 0.5", "v_mov_b32 v6, 0.25", "v_mov_b32 v7, 0.75", "v_mov_b32 v8, 0.125", - "v_mov_b32 v9, 0"] -CS_FSSM = bytearray(0x148) -struct.pack_into("<4I", CS_FSSM, 0x138, 0x8088, 32, 1, 1) -CS_FSSM = bytes(CS_FSSM) - - -def translate(name, line): - fssm = CS_FSSM if name.startswith("cs_") else None - body = PRO + [line] + (["exp mrt0 v9, v9, v9, v9 done vm"] if name.startswith("ps_") else []) + ["s_endpgm"] - return support.translate_lines(name, body, fssm=fssm) - - -def samples(spv): - return [ln.strip() for ln in spv.splitlines() if "= OpImageSample" in ln] - - -def source_vgpr(spv, value): - """The VGPR index the id `value` was loaded from (through bitcasts), or None.""" - consts = {k: int(v) for k, v in re.findall(r"^\s*(%\w+) = OpConstant %uint (\d+)", spv, re.M)} - for _ in range(8): - m = re.search(rf"^\s*{re.escape(value)} = (\w+) (?:%\w+ )?(%\w+)", spv, re.M) - if not m: - return None - op, src = m.groups() - if op == "OpLoad": - m2 = re.search(rf"^\s*{re.escape(src)} = OpAccessChain %\S+ %vgpr (%\w+)", spv, re.M) - return consts.get(m2.group(1)) if m2 else None - value = src - return None - - -class SampleCl(unittest.TestCase): - def one(self, name, line): - (s,) = samples(translate(name, line)) - return s - - def test_cl_is_implicit_lod_with_min_lod(self): - s = self.one("ps_cl", f"image_sample_cl v[0:3], v[4:6], {DESC} dmask:0xf {D2}") - self.assertRegex(s, r"= OpImageSampleImplicitLod %v4float %\w+ %\w+ MinLod %\w+$") - - def test_the_clamp_is_the_component_after_the_coordinates(self): - spv = translate("ps_cl", f"image_sample_cl v[0:3], v[4:6], {DESC} dmask:0xf {D2}") - (s,) = samples(spv) - self.assertEqual(source_vgpr(spv, s.split()[-1]), 6) - - def test_b_cl_has_bias_and_min_lod(self): - spv = translate("ps_bcl", f"image_sample_b_cl v[0:3], v[4:7], {DESC} dmask:0xf {D2}") - (s,) = samples(spv) - self.assertRegex(s, r"= OpImageSampleImplicitLod %v4float %\w+ %\w+ Bias\|MinLod %\w+ %\w+$") - bias, minlod = s.split()[-2:] - self.assertEqual((source_vgpr(spv, bias), source_vgpr(spv, minlod)), (4, 7)) - - def test_dref_forms(self): - s = self.one("ps_ccl", f"image_sample_c_cl v9, v[4:7], {DESC} dmask:0x1 {D2}") - self.assertRegex(s, r"= OpImageSampleDrefImplicitLod %float %\w+ %\w+ %\w+ MinLod %\w+$") - s = self.one("ps_cbcl", f"image_sample_c_b_cl v9, v[4:8], {DESC} dmask:0x1 {D2}") - self.assertRegex(s, r"= OpImageSampleDrefImplicitLod %float %\w+ %\w+ %\w+ Bias\|MinLod %\w+ %\w+$") - - def test_offset_comes_before_the_min_lod(self): - s = self.one("ps_clo", f"image_sample_cl_o v[0:3], v[4:7], {DESC} dmask:0xf {D2}") - self.assertRegex(s, r"= OpImageSampleImplicitLod %v4float %\w+ %\w+ Offset\|MinLod %\w+ %\w+$") - - def test_a16_packs_the_clamp_with_the_coordinates(self): - # u, v in one VGPR, the clamp in the low half of the next; no whole-VGPR extra for _cl itself - s = self.one("ps_clo16", f"image_sample_cl v[0:3], v[4:5], {DESC} dmask:0xf {D2} a16") - self.assertIn("MinLod", s) - s = self.one("ps_bclo16", f"image_sample_b_cl v[0:3], v[4:6], {DESC} dmask:0xf {D2} a16") - self.assertIn("Bias|MinLod", s) - - def test_without_derivatives_the_lod_is_the_clamp_or_zero(self): - for name, fssm in (("vs_cl", None), ("cs_cl", CS_FSSM)): - with self.subTest(shader=name): - spv = translate(name, f"image_sample_cl v[0:3], v[4:6], {DESC} dmask:0xf {D2}") - (s,) = samples(spv) - self.assertRegex(s, r"= OpImageSampleExplicitLod %v4float %\w+ %\w+ Lod %\w+$") - self.assertIn("FMax %f0", spv) - self.assertNotIn("MinLod", s) - - def test_module_declares_min_lod(self): - self.assertIn("OpCapability MinLod", translate("ps_cl", f"image_sample_cl v[0:3], v[4:6], {DESC} dmask:0xf {D2}")) - self.assertNotIn("OpCapability MinLod", translate("ps_noc", f"image_sample v[0:3], v[4:5], {DESC} dmask:0xf {D2}")) - - def test_forms_with_no_clamp_variant_stay_refused(self): - for op, regs in (("image_sample_l_cl", "v[4:7]"), ("image_sample_lz_cl", "v[4:6]")): - with self.subTest(op=op), self.assertRaises(support.rdna2spirv.Unsupported): - translate("ps_x", f"{op} v[0:3], {regs}, {DESC} dmask:0xf {D2}") - - @unittest.skipUnless(shutil.which("spirv-as") and shutil.which("spirv-val"), "needs spirv-as and spirv-val on PATH") - def test_modules_validate(self): - cases = [("image_sample_cl", "v[0:3]", "v[4:6]", 0xf), ("image_sample_b_cl", "v[0:3]", "v[4:7]", 0xf), - ("image_sample_c_cl", "v9", "v[4:7]", 1), ("image_sample_c_b_cl", "v9", "v[4:8]", 1), - ("image_sample_cl_o", "v[0:3]", "v[4:7]", 0xf)] - for op, dst, regs, dmask in cases: - for name in ("ps_val", "vs_val"): - with self.subTest(op=op, shader=name): - spv = translate(name, f"{op} {dst}, {regs}, {DESC} dmask:{dmask:#x} {D2}") - with tempfile.TemporaryDirectory() as tmp: - a, b = os.path.join(tmp, "m.spvasm"), os.path.join(tmp, "m.spv") - with open(a, "w", encoding="utf-8", newline="\n") as f: - f.write(spv) - subprocess.run(["spirv-as", "--target-env", "vulkan1.2", a, "-o", b], check=True) - subprocess.run(["spirv-val", "--target-env", "vulkan1.2", "--allow-offset-texture-operand", b], - check=True) - - -if __name__ == "__main__": - unittest.main() \ No newline at end of file diff --git a/tests/semantic/test_sample_typed_dims.py b/tests/semantic/test_sample_typed_dims.py deleted file mode 100644 index 590cad6c3..000000000 --- a/tests/semantic/test_sample_typed_dims.py +++ /dev/null @@ -1,88 +0,0 @@ -"""image_sample_l / image_sample_lz read a UINT/SINT image through its integer view in every dimension. - -Standard library only (spirv-as and spirv-val are used when they are on PATH); no GPU, no game files. - -The hardware picks the sampled view from T# word 1 FORMAT in every dimension, and image_load has read the uint/sint -alias of the dimension's sampled binding in all of them (SHADER-151). Sampling took that path for 2D only, so a UINT -2D-array, 3D, cube or 1D texture was read through the float view and the VGPRs held a converted float instead of the -integer texel. Here: the alias each dimension loads, the sampled-image type it pairs with the sampler, that the float -view is still sampled for a float format, and that the modules validate. The GPU pixel fixtures are -runtime/test/shaders/ps_sample_implicit_uint.asm and ps_sample_implicit_sint.asm (2D); a non-2D integer texture is the -remaining pixel check. -""" -import os -import re -import shutil -import subprocess -import tempfile -import unittest - -import support - -DESC = "s[8:15], s[16:19]" -PRO = ["v_mov_b32 v4, 1.0", "v_mov_b32 v5, 0.5", "v_mov_b32 v6, 0.25", "v_mov_b32 v7, 0.75", - "v_mov_b32 v8, 0"] - -# dim -> (address range, vdata, dmask, STORE_DIMS index the typed aliases are declared for, sampled binding) -DIMS = { - "1D": ("v[4:5]", "v9", "0x1", 3, 5), - "2D": ("v[4:6]", "v[9:12]", "0xf", 0, 0), - "2D_ARRAY": ("v[4:7]", "v[9:12]", "0xf", 1, 3), - "3D": ("v[4:7]", "v[9:12]", "0xf", 2, 6), - "CUBE": ("v[4:7]", "v[9:12]", "0xf", 1, 3), # a cube samples its 6-layer 2D-array view -} - - -def translate(name, line): - return support.translate_lines(name, PRO + [line, "exp mrt0 v9, v9, v9, v9 done vm", "s_endpgm"]) - - -def sample(op, dim): - addr, vdata, dmask, _, _ = DIMS[dim] - return f"{op} {vdata}, {addr}, {DESC} dmask:{dmask} dim:SQ_RSRC_IMG_{dim}" - - -class SampleTypedDims(unittest.TestCase): - def test_both_integer_classes_alias_the_dimension_sampled_binding(self): - for op in ("image_sample_l", "image_sample_lz"): - for dim, (_, _, _, di, binding) in DIMS.items(): - with self.subTest(op=op, dim=dim): - spv = translate("ps_sampletyped", sample(op, dim)) - for cls in (1, 2): - self.assertRegex(spv, rf"OpAccessChain %_ptr_UC_itx{cls}_{di} %itx{cls}_{di} ") - self.assertIn(f"OpDecorate %itx{cls}_{di} Binding {binding}", spv) - self.assertIn(f"%itxsamp{cls}_{di} = OpTypeSampledImage %itximg{cls}_{di}", spv) - self.assertRegex(spv, r"= OpImageSampleExplicitLod %v4uint_st %") - self.assertRegex(spv, r"= OpImageSampleExplicitLod %v4int_st %") - # A float format still samples the float view the runtime binds at the same index. - self.assertRegex(spv, r"= OpImageSampleExplicitLod %v4float %") - - def test_cube_samples_its_2d_array_view_with_three_coordinates(self): - spv = translate("ps_samplecubetyped", sample("image_sample_lz", "CUBE")) - self.assertRegex(spv, r"OpAccessChain %_ptr_UC_imga %images_arr ") - self.assertRegex(spv, r"OpAccessChain %_ptr_UC_itx1_1 %itx1_1 ") - self.assertIn("OpSampledImage %simg2da", spv) - self.assertIn("OpCompositeConstruct %v3float", spv) - - def test_the_2d_form_is_unchanged(self): - spv = translate("ps_sample2dtyped", sample("image_sample_lz", "2D")) - self.assertRegex(spv, r"OpAccessChain %_ptr_UC_itx1_0 %itx1_0 ") - self.assertNotIn("%itx1_1", spv) - - @unittest.skipUnless(shutil.which("spirv-as") and shutil.which("spirv-val"), - "needs spirv-as and spirv-val on PATH") - def test_modules_validate(self): - for op in ("image_sample_l", "image_sample_lz"): - for dim in DIMS: - with self.subTest(op=op, dim=dim): - spv = translate("ps_sampletypedval", sample(op, dim)) - with tempfile.TemporaryDirectory() as tmp: - a, b = os.path.join(tmp, "m.spvasm"), os.path.join(tmp, "m.spv") - with open(a, "w", encoding="utf-8", newline="\n") as f: - f.write(spv) - subprocess.run(["spirv-as", "--target-env", "vulkan1.2", a, "-o", b], check=True) - subprocess.run(["spirv-val", "--target-env", "vulkan1.2", b], check=True) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_sampled_dynamic_index.py b/tests/semantic/test_sampled_dynamic_index.py deleted file mode 100644 index b00065a26..000000000 --- a/tests/semantic/test_sampled_dynamic_index.py +++ /dev/null @@ -1,116 +0,0 @@ -"""Each declaration and Vulkan device feature follows its own dynamic descriptor accesses.""" -from pathlib import Path -import re -import unittest - -import support -import rdna2spirv - - -CAPABILITY = "SampledImageArrayDynamicIndexing" -FEATURE = "shaderSampledImageArrayDynamicIndexing" -STORAGE_CAPABILITY = "StorageImageArrayDynamicIndexing" -STORAGE_FEATURE = "shaderStorageImageArrayDynamicIndexing" -EPILOGUE = ["exp mrt0 v0, v1, v2, v3 done vm", "s_endpgm"] - - -def translate(instruction): - return support.translate_lines("ps_dynamic_index", [instruction, *EPILOGUE]) - - -class SampledDynamicIndex(unittest.TestCase): - def check_accesses(self, asm, sampled_bindings, storage_bindings=()): - bindings = {var: int(binding) for var, binding in re.findall(r"OpDecorate (%\w+) Binding (\d+)", asm)} - lookups = set(re.findall(r"(%\w+) = OpFunctionCall %uint %desc_lookup_fn ", asm)) - broadcasts = re.findall(r"(%\w+) = OpGroupNonUniformBroadcastFirst %uint %\w+ (%\w+)", asm) - # a wave32 pixel shader in a 64-lane subgroup takes its own half's first lane with a shuffle (design.md, - # "Execution model": shuffle sources keep the current half) - broadcasts += re.findall(r"(%\w+) = OpGroupNonUniformShuffle %uint %\w+ (%\w+) %\w+", asm) - lookup_indices = lookups | {result for result, source in broadcasts if source in lookups} - sampled, storage = set(), set() - for var, index in re.findall(r"OpAccessChain %_ptr_UC_\w+ (%\w+) (%\w+)$", asm, re.M): - self.assertIn(index, lookup_indices) - (storage if var.startswith(("%simages", "%stv")) else sampled).add(bindings[var]) - self.assertEqual(sampled, set(sampled_bindings)) - self.assertEqual(storage, set(storage_bindings)) - meta = rdna2spirv.shader_meta(rdna2spirv.translate.last_gen, asm) - self.assertEqual(sum(line.strip() == f"OpCapability {CAPABILITY}" for line in asm.splitlines()), bool(sampled)) - self.assertEqual(FEATURE in meta["features"], bool(sampled)) - self.assertEqual(sum(line.strip() == f"OpCapability {STORAGE_CAPABILITY}" for line in asm.splitlines()), - bool(storage)) - self.assertEqual(STORAGE_FEATURE in meta["features"], bool(storage)) - self.assertNotIn("SampledImageArrayNonUniformIndexing", meta["capabilities"]) - self.assertNotIn("StorageImageArrayNonUniformIndexing", meta["capabilities"]) - - def test_sample_with_literal_sampler_still_indexes_both_arrays_dynamically(self): - fixture = Path(__file__).with_name("fixtures") / "sampled_dynamic_index.asm" - asm = support.translate_lines("ps_dynamic_index", fixture.read_text(encoding="utf-8").splitlines()) - self.check_accesses(asm, (0, 1)) - self.assertIn("OpSampledImage", asm) - self.assertIn("OpImageSampleExplicitLod", asm) - for signedness in (1, 2): # UINT/SINT alias the same sampled binding as the float view. - self.assertRegex(asm, rf"OpAccessChain %_ptr_UC_itx{signedness}_0 %itx{signedness}_0 ") - - def test_fetch_and_query_paths(self): - for op, dim, coords, sampler, expected_op, bindings in ( - ("image_load", "1D", "v4", "", "OpImageFetch", (5,)), - ("image_load", "2D_ARRAY", "v[4:6]", "", "OpImageFetch", (3,)), - ("image_load_mip", "2D", "v[4:6]", "", "OpImageFetch", (0,)), - ("image_load_mip", "3D", "v[4:7]", "", "OpImageFetch", (6,)), - ("image_get_resinfo", "2D", "v4", "", "OpImageQuerySizeLod", (0,)), - ("image_get_resinfo", "2D_ARRAY", "v4", "", "OpImageQuerySizeLod", (3,)), - ("image_get_lod", "2D_ARRAY", "v[4:6]", ", s[8:11]", "OpImageQueryLod", (1, 3)), - ("image_gather4_lz", "2D", "v[4:5]", ", s[8:11]", "OpImageGather", (0, 1)), - ("image_gather4_l", "2D", "v[4:6]", ", s[8:11]", "OpImageFetch", (0, 1)), - ): - with self.subTest(op=op, dim=dim): - asm = translate(f"{op} v[0:3], {coords}, s[0:7]{sampler} dmask:0x1 dim:SQ_RSRC_IMG_{dim}") - self.check_accesses(asm, bindings) - self.assertIn(expected_op, asm) - if op == "image_gather4_l": - self.assertNotIn("OpSampledImage", asm) # manual taps use the S# words directly - - def test_storage_only_and_constant_register_indices(self): - for instruction, bindings in ( - ("image_load v0, v[4:5], s[0:7] dmask:0x1 dim:SQ_RSRC_IMG_2D glc", (8, 9, 10)), - ("image_store v0, v[4:5], s[0:7] dmask:0x1 dim:SQ_RSRC_IMG_2D", (8, 9, 10)), - ("image_atomic_add v0, v[4:5], s[0:7] dmask:0x1 dim:SQ_RSRC_IMG_2D", (4,)), - ("image_atomic_add v0, v[4:6], s[0:7] dmask:0x1 dim:SQ_RSRC_IMG_3D", (7,)), - ("v_mov_b32_e32 v0, 1", ()), - ): - with self.subTest(instruction=instruction): - asm = translate(instruction) - self.check_accesses(asm, (), bindings) - if bindings: - self.assertIn("OpCapability RuntimeDescriptorArray", asm) - - def test_literal_storage_descriptor_and_mixed_sampled_load(self): - fixture = Path(__file__).with_name("fixtures") / "storage_dynamic_index.asm" - lines = fixture.read_text(encoding="utf-8").splitlines() - self.check_accesses(support.translate_lines("ps_storage_index", lines), (), (8, 9, 10)) - load = "image_load v0, v[4:5], s[8:15] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm" - asm = support.translate_lines("ps_mixed_index", lines[:-2] + [load, "s_waitcnt vmcnt(0)"] + lines[-2:]) - self.check_accesses(asm, (0,), (8, 9, 10)) - self.assertIn("OpImageFetch", asm) - self.assertIn("OpImageWrite", asm) - - def test_storage_aliases_in_every_dimension(self): - for dim, coords, first_binding in (("2D", "v[4:5]", 8), ("2D_ARRAY", "v[4:6]", 11), - ("3D", "v[4:6]", 14), ("1D", "v4", 17)): - for op, mods, expected in (("image_load", "glc dlc d16", "OpImageRead"), - ("image_store", "", "OpImageWrite")): - with self.subTest(dim=dim, op=op): - asm = translate(f"{op} v0, {coords}, s[0:7] dmask:0x1 dim:SQ_RSRC_IMG_{dim} unorm {mods}") - self.check_accesses(asm, (), range(first_binding, first_binding + 3)) - self.assertIn(expected, asm) - - def test_atomic_texel_pointers_use_storage_indices(self): - for dim, coords, binding in (("2D", "v[4:5]", 4), ("3D", "v[4:6]", 7)): - for op, data, expected in (("image_atomic_add", "v0", "OpAtomicIAdd"), - ("image_atomic_cmpswap", "v[0:1]", "OpAtomicCompareExchange")): - with self.subTest(dim=dim, op=op): - asm = translate(f"{op} {data}, {coords}, s[0:7] dmask:0x1 dim:SQ_RSRC_IMG_{dim} glc") - self.check_accesses(asm, (), (binding,)) - (texel, image), = re.findall(r"(%\w+) = OpImageTexelPointer %_ptr_Image_uint (%\w+)", asm) - self.assertIn(f"{expected} %uint {texel} ", asm) - self.assertIn(f"{image} = OpAccessChain %_ptr_UC_simg", asm) diff --git a/tests/semantic/test_saveexec_b64.py b/tests/semantic/test_saveexec_b64.py deleted file mode 100644 index 391a19b67..000000000 --- a/tests/semantic/test_saveexec_b64.py +++ /dev/null @@ -1,139 +0,0 @@ -"""The 64-bit EXEC-saving ops with a compare result in VCC or in an SGPR pair, run across every lane of a wave64. - -RDNA2 ISA: - s_and_saveexec_b64 D = EXEC; EXEC = S0 & EXEC; SCC = (EXEC != 0). - s_or_saveexec_b64 D = EXEC; EXEC = S0 | EXEC; SCC = (EXEC != 0). - s_andn2_saveexec_b64 D = EXEC; EXEC = S0 & ~EXEC; SCC = (EXEC != 0). - s_andn2_wrexec_b64 EXEC = S0 & ~EXEC; D = EXEC (the new one); SCC = (EXEC != 0). - -Programs are written here (no game data) and translated by tools/rdna2spirv.py; spirv_mini_interp.run_workgroup runs -one workgroup of 64 lanes on a 64-wide subgroup. S0 is written by v_cmp into VCC (_e32) or into s[10:11] (_e64), -EXEC is a constant in each half. Every lane stores whether it is on in the new EXEC, and lane 0 stores SCC and the -population count and lowest lane of D. The expected values come from the ISA lines above, written as integers in -`model`, not from the translator. Constant sources are in test_value_semantics.py (cs_w64_mask_imm); the VCC form of -the andn2 ops is in test_andn2_exec_b64.py. - -The GPU test is runtime/test/shaders/cs_w64x_saveexec_b64.asm; its fixture also runs here. The --wave64-emulate -output needs Workgroup memory, which the interpreter rejects, so it is covered by the GPU test only. -""" -import struct -import unittest - -import support -import spirv_mini_interp as si - -VSHARP = [0, 0, 0x1000, 0x31016FAC] -ALL64 = (1 << 64) - 1 -EXPECTED_FIXTURE = [6160, 12304, 5120, 2088, 6168, 8192, 7176, 1837171] # derivation in cs_w64x_saveexec_b64.asm -SCC_AT, BCNT_AT, FF1_AT = 256, 260, 264 # bytes in out[], after the 64 lane words -OPS = ("s_and_saveexec_b64", "s_or_saveexec_b64", "s_andn2_saveexec_b64", "s_andn2_wrexec_b64") -SOURCES = ("vcc", "s[10:11]") - -# (multiplier, addend, and-mask, EXEC): S0 = the lanes l with ((l * multiplier + addend) & and-mask) == 0. -CASES = ( - (1, 0, 8, 0x0000FFFFFFFF0000), # S0 in both halves, EXEC across the middle - (1, 0, 32, 0xFFFFFFFF00000000), # S0 = the low half, EXEC = the high half - (1, 32, 32, 0x0000FFFF0000FFFF), # S0 = the high half - (1, 32, 32, 0xFF00000000000000), # S0 = the high half, EXEC = lanes 56..63: every result is high only - (3, 1, 5, 0x5555555555555555), - (7, 2, 12, 0xF0F0F0F00F0F0F0F), - (1, 0, 0, 0), # S0 = every lane, EXEC = 0 - (1, 0, 0, ALL64), # S0 = every lane, EXEC = every lane - (1, 0, 64, 0x123456789ABCDEF0), # S0 = every lane (bit 6 is never set) - (1, 0, 127, 0), # S0 = lane 0 only, EXEC = 0 - (1, 0, 63, 0x8000000000000000), # S0 = lane 0, EXEC = lane 63 - (5, 3, 63, 0x00000000FFFFFFFF), # a single lane in S0, EXEC = the low half - (1, 64, 64, 0), # S0 = no lane (bit 6 of l + 64 is always set), EXEC = 0 -) - - -def fssm(threads): - h = bytearray(0x148) - struct.pack_into("<4I", h, 0x138, 0x8088, threads, 1, 1) - return bytes(h) - - -def s0_mask(mul, add, mask): - return sum(1 << lane for lane in range(64) if ((lane * mul + add) & mask) == 0) - - -def model(op, s0, old_exec): - """(new EXEC, D, SCC) from the ISA's definition.""" - new_exec = {"s_and_saveexec_b64": s0 & old_exec, "s_or_saveexec_b64": s0 | old_exec, - "s_andn2_saveexec_b64": s0 & ~old_exec, "s_andn2_wrexec_b64": s0 & ~old_exec}[op] & ALL64 - return new_exec, (new_exec if op == "s_andn2_wrexec_b64" else old_exec), int(new_exec != 0) - - -def program(op, src, mul, add, mask, old_exec): - def store(reg, at): - return [f"v_mov_b32_e32 v20, {reg}", f"v_mov_b32_e32 v21, {at}", "buffer_store_dword v20, v21, s[0:3], 0 offen"] - - cmp = "v_cmp_eq_u32_e32 vcc, 0, v3" if src == "vcc" else f"v_cmp_eq_u32_e64 {src}, 0, v3" - return (["v_mbcnt_lo_u32_b32 v1, -1, 0", "v_mbcnt_hi_u32_b32 v1, -1, v1", "v_mov_b32_e32 v2, 0", - f"v_mad_u32_u24 v3, v1, {mul}, {add}", f"v_and_b32_e32 v3, {mask}, v3", cmp, - f"s_mov_b32 exec_lo, {old_exec & 0xFFFFFFFF:#x}", f"s_mov_b32 exec_hi, {old_exec >> 32:#x}", - f"{op} s[6:7], {src}", "s_cselect_b32 s8, 1, 0", - "v_mov_b32_e32 v2, 1", # only the lanes the instruction left on - "s_mov_b64 exec, -1", - "s_bcnt1_i32_b64 s9, s[6:7]", "s_ff1_i32_b64 s10, s[6:7]", - "v_lshlrev_b32_e32 v21, 2, v1", "buffer_store_dword v2, v21, s[0:3], 0 offen", - "v_cmpx_eq_u32_e32 0, v1"] - + store("s8", SCC_AT) + store("s9", BCNT_AT) + store("s10", FF1_AT) + ["s_endpgm"]) - - -def run(spv, subgroup=64): - return si.run_workgroup( - spv, 64, subgroup, inputs_for=lambda i: {"%wg_id": (0, 0, 0), "%local_id": (i, 0, 0), "%sg_lane": i % subgroup}, - push_constants=VSHARP + [0] * 28, memory={}) - - -class SaveexecB64(unittest.TestCase): - def test_model_examples(self): - # The ISA lines on the masks of cs_w64x_saveexec_b64.asm, by hand. - lanes = lambda lo, hi: sum(1 << l for l in range(lo, hi)) - self.assertEqual(model("s_and_saveexec_b64", lanes(0, 40), lanes(16, 64)), (lanes(16, 40), lanes(16, 64), 1)) - self.assertEqual(model("s_or_saveexec_b64", lanes(0, 12), lanes(40, 48)), - (lanes(0, 12) | lanes(40, 48), lanes(40, 48), 1)) - self.assertEqual(model("s_or_saveexec_b64", 0, 0), (0, 0, 0)) - self.assertEqual(model("s_and_saveexec_b64", lanes(0, 32), lanes(32, 64)), (0, lanes(32, 64), 0)) - self.assertEqual(model("s_and_saveexec_b64", lanes(48, 64), lanes(0, 16) | lanes(32, 64)), - (lanes(48, 64), lanes(0, 16) | lanes(32, 64), 1)) - self.assertEqual(model("s_andn2_saveexec_b64", lanes(24, 64), lanes(0, 16) | lanes(48, 64)), - (lanes(24, 48), lanes(0, 16) | lanes(48, 64), 1)) - self.assertEqual(model("s_andn2_wrexec_b64", lanes(0, 36), lanes(0, 8)), (lanes(8, 36), lanes(8, 36), 1)) - - def test_every_lane(self): - for op in OPS: - for src in SOURCES: - for mul, add, mask, old_exec in CASES: - with self.subTest(op=op, src=src, s0=(mul, add, mask), exec=hex(old_exec)): - new_exec, d, scc = model(op, s0_mask(mul, add, mask), old_exec) - spv = support.translate_lines("cs_saveexec_b64", program(op, src, mul, add, mask, old_exec), - fssm=fssm(64)) - memory = run(spv) - got_exec = sum(memory[4 * lane] << lane for lane in range(64)) - self.assertEqual(got_exec, new_exec, f"EXEC {got_exec:#018x}, ISA {new_exec:#018x}") - self.assertEqual(memory[SCC_AT], scc, "SCC") - self.assertEqual(memory[BCNT_AT], bin(d).count("1"), "population count of D") - lowest = (d & -d).bit_length() - 1 if d else 0xFFFFFFFF # s_ff1 of 0 is -1 - self.assertEqual(memory[FF1_AT], lowest, "lowest lane of D") - - def test_cases_cover_both_halves(self): - # For each op the table has results in the low half only, in the high half only, in both and in neither. - for op in OPS: - seen = set() - for mul, add, mask, old_exec in CASES: - new_exec = model(op, s0_mask(mul, add, mask), old_exec)[0] - seen.add((bool(new_exec & 0xFFFFFFFF), bool(new_exec >> 32))) - self.assertEqual(seen, {(False, False), (True, False), (False, True), (True, True)}, op) - - def test_gpu_test_fixture(self): - """cs_w64x_saveexec_b64.asm: the words check.py expects (lane 0 stores them).""" - spv = support.translate_fixture("cs_w64x_saveexec_b64", fssm=fssm(64)) - memory = run(spv) - self.assertEqual(sorted(memory), list(range(0, 32, 4)), "lane 0 stores out[0..7] only") - self.assertEqual([memory[4 * k] for k in range(8)], EXPECTED_FIXTURE) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_saveexec_variants.py b/tests/semantic/test_saveexec_variants.py deleted file mode 100644 index 76467f218..000000000 --- a/tests/semantic/test_saveexec_variants.py +++ /dev/null @@ -1,272 +0,0 @@ -"""Lane-level tests for every RDNA2 s__saveexec_b32/b64 and s_andn1/andn2_wrexec, against tools/cf_ref.py. - -D = EXEC; EXEC = f(S0, EXEC); SCC = (EXEC != 0) for saveexec, and EXEC = f(S0, EXEC); D = EXEC for wrexec. Each case -runs a translated pixel shader in tests/semantic/spirv_wave_interp.py as one wave whose EXEC starts partial (v_cmpx), -with S0 a different lane range, and checks every lane's saved bit, new EXEC bit and the wave's SCC against the ISA -model in tools/cf_ref.py (_SAVEEXEC, the table the FUZZ-8 differential fuzzer uses). Lanes that EXEC had off and that -f turns on (nand, nor, orn1, orn2, xnor, ...) become active, as on hardware. Standard library only; no game files. -""" -import os -import sys -import unittest -from pathlib import Path - -HERE = os.path.dirname(os.path.abspath(__file__)) -sys.dont_write_bytecode = True -sys.path.insert(0, HERE) - -from test_salu64_bitwise_data import run_ps_wave # noqa: E402 (also puts tools/ on sys.path) -import cf_ref # noqa: E402 - -KINDS = ["and", "or", "xor", "andn1", "andn2", "orn1", "orn2", "nand", "nor", "xnor"] - - -def lanes(lo, hi, wave): - return sum(1 << i for i in range(wave) if lo <= i < hi) - - -def case(op_line, wave, exec_hi, s0_lo, s0_hi): - """EXEC = lanes [0, exec_hi), S0 = lanes [s0_lo, s0_hi); run `op_line` (D in s[4:5] / s4, S0 in s[2:3] / s2).""" - w64 = wave == 64 - s0, d = ("s[2:3]", "s[4:5]") if w64 else ("s2", "s4") - lines = ["v_mbcnt_lo_u32_b32 v4, -1, 0"] + (["v_mbcnt_hi_u32_b32 v4, -1, v4"] if w64 else []) + [ - f"v_cmp_ge_u32_e64 {s0}, v4, {s0_lo}", - f"v_cmp_lt_u32_e64 {'s[6:7]' if w64 else 's6'}, v4, {s0_hi}", - f"s_and_b{wave} {s0}, {s0}, {'s[6:7]' if w64 else 's6'}", - "v_mov_b32 v1, 0x11", - f"v_cmpx_gt_u32_e32 {exec_hi}, v4", - op_line.format(d=d, s0=s0), - "s_cselect_b32 s10, 1, 0", - "v_mov_b32 v1, 0x22", - f"s_mov_b{wave} exec, -1", - f"v_cndmask_b32_e64 v2, 0, 1, {d}", - "v_mov_b32 v0, s10", - "v_mov_b32 v3, 0", - ] - outs, _ = run_ps_wave(lines, wave=wave) - return outs - - -class SaveexecVariants(unittest.TestCase): - def test_null_mask_source(self) -> None: - fixture = Path(HERE) / "fixtures" / "null_mask_source.asm" - lines = [line for line in fixture.read_text(encoding="utf-8").splitlines() - if line and not line.startswith(";")] - outputs, _ = run_ps_wave(lines, wave=64) - self.assertEqual(outputs, [(1, 64, 0xFFFFFFFF, 7)] * 64) - - def check(self, kind, wave, exec_hi, s0_lo, s0_hi, wrexec=False): - m = (1 << wave) - 1 - e, s = lanes(0, exec_hi, wave), lanes(s0_lo, s0_hi, wave) - new = cf_ref._SAVEEXEC[kind](s, e, m) & m - saved = new if wrexec else e - op = f"s_{kind}_{'wrexec' if wrexec else 'saveexec'}_b{wave} {{d}}, {{s0}}" - outs = case(op, wave, exec_hi, s0_lo, s0_hi) - for lane in range(wave): - want = (int(new != 0), 0x22 if new >> lane & 1 else 0x11, saved >> lane & 1, 0) - self.assertEqual(outs[lane], want, f"{op} lane {lane}") - - def test_saveexec_wave32(self): - for kind in KINDS: - for exec_hi, s0 in ((24, (10, 30)), (32, (0, 32)), (8, (8, 16))): - with self.subTest(kind=kind, exec_hi=exec_hi, s0=s0): - self.check(kind, 32, exec_hi, *s0) - - def test_saveexec_wave64(self): - for kind in KINDS: - for exec_hi, s0 in ((40, (20, 50)), (64, (0, 64))): - with self.subTest(kind=kind, exec_hi=exec_hi, s0=s0): - self.check(kind, 64, exec_hi, *s0) - - def test_wrexec(self): - for kind in ("andn1", "andn2"): - for wave, exec_hi, s0 in ((32, 24, (10, 30)), (64, 40, (20, 50)), (32, 16, (16, 32))): - with self.subTest(kind=kind, wave=wave): - self.check(kind, wave, exec_hi, *s0, wrexec=True) - - def test_sdst_src0_aliasing(self): - # 1. s_nand_saveexec_b32 s4, s4 - lines32 = [ - "v_mbcnt_lo_u32_b32 v4, -1, 0", - "v_cmp_ge_u32_e64 s4, v4, 8", - "v_cmp_lt_u32_e64 s6, v4, 24", - "s_and_b32 s4, s4, s6", - "v_mov_b32 v1, 0x11", - "v_cmpx_gt_u32_e32 16, v4", - "s_nand_saveexec_b32 s4, s4", - "s_cselect_b32 s10, 1, 0", - "v_mov_b32 v1, 0x22", - "s_mov_b32 exec, -1", - "v_cndmask_b32_e64 v2, 0, 1, s4", - "v_mov_b32 v0, s10", - "v_mov_b32 v3, 0", - ] - outs32, _ = run_ps_wave(lines32, wave=32) - for lane in range(32): - want_scc = 1 - want_exec = 0x11 if 8 <= lane < 16 else 0x22 - want_saved = 1 if lane < 16 else 0 - self.assertEqual(outs32[lane], (want_scc, want_exec, want_saved, 0), f"lane {lane}") - - # 2. s_nand_saveexec_b64 s[4:5], s[4:5] - lines64 = [ - "v_mbcnt_lo_u32_b32 v4, -1, 0", - "v_mbcnt_hi_u32_b32 v4, -1, v4", - "v_cmp_ge_u32_e64 s[4:5], v4, 16", - "v_cmp_lt_u32_e64 s[6:7], v4, 48", - "s_and_b64 s[4:5], s[4:5], s[6:7]", - "v_mov_b32 v1, 0x11", - "v_cmpx_gt_u32_e32 32, v4", - "s_nand_saveexec_b64 s[4:5], s[4:5]", - "s_cselect_b32 s10, 1, 0", - "v_mov_b32 v1, 0x22", - "s_mov_b64 exec, -1", - "v_cndmask_b32_e64 v2, 0, 1, s[4:5]", - "v_mov_b32 v0, s10", - "v_mov_b32 v3, 0", - ] - outs64, _ = run_ps_wave(lines64, wave=64) - for lane in range(64): - want_scc = 1 - want_exec = 0x11 if 16 <= lane < 32 else 0x22 - want_saved = 1 if lane < 32 else 0 - self.assertEqual(outs64[lane], (want_scc, want_exec, want_saved, 0), f"lane {lane}") - - # 3. s_andn1_wrexec_b32 s4, s4 - lines_wr = [ - "v_mbcnt_lo_u32_b32 v4, -1, 0", - "v_cmp_ge_u32_e64 s4, v4, 8", - "v_cmp_lt_u32_e64 s6, v4, 24", - "s_and_b32 s4, s4, s6", - "v_mov_b32 v1, 0x11", - "v_cmpx_gt_u32_e32 16, v4", - "s_andn1_wrexec_b32 s4, s4", - "s_cselect_b32 s10, 1, 0", - "v_mov_b32 v1, 0x22", - "s_mov_b32 exec, -1", - "v_cndmask_b32_e64 v2, 0, 1, s4", - "v_mov_b32 v0, s10", - "v_mov_b32 v3, 0", - ] - outs_wr, _ = run_ps_wave(lines_wr, wave=32) - for lane in range(32): - want_scc = 1 - want_exec = 0x22 if lane < 8 else 0x11 - want_saved = 1 if lane < 8 else 0 - self.assertEqual(outs_wr[lane], (want_scc, want_exec, want_saved, 0), f"lane {lane}") - - def test_wave64_upper_dword_scc_boundary(self): - # src0 = 0x00000001_00000000 (only lane 32 active) - lines = [ - "v_mbcnt_lo_u32_b32 v4, -1, 0", - "v_mbcnt_hi_u32_b32 v4, -1, v4", - "v_cmp_eq_u32_e64 s[2:3], v4, 32", - "s_mov_b64 exec, -1", - "s_and_saveexec_b64 s[4:5], s[2:3]", - "s_cselect_b32 s10, 1, 0", - "s_mov_b64 exec, -1", - "v_cndmask_b32_e64 v2, 0, 1, s[4:5]", - "v_mov_b32 v0, s10", - "v_mov_b32 v1, 0", - "v_mov_b32 v3, 0", - ] - outs, _ = run_ps_wave(lines, wave=64) - for lane in range(64): - self.assertEqual(outs[lane][0], 1, "SCC should be 1 when bit 32 is non-zero") - self.assertEqual(outs[lane][2], 1, "saved exec should be all 1s") - - # paired with src0 = 0 -> SCC must be 0 - lines_zero = [ - "v_mbcnt_lo_u32_b32 v4, -1, 0", - "v_mbcnt_hi_u32_b32 v4, -1, v4", - "s_mov_b64 exec, -1", - "s_and_saveexec_b64 s[4:5], 0", - "s_cselect_b32 s10, 1, 0", - "s_mov_b64 exec, -1", - "v_cndmask_b32_e64 v2, 0, 1, s[4:5]", - "v_mov_b32 v0, s10", - "v_mov_b32 v1, 0", - "v_mov_b32 v3, 0", - ] - outs_zero, _ = run_ps_wave(lines_zero, wave=64) - for lane in range(64): - self.assertEqual(outs_zero[lane][0], 0, "SCC should be 0 when new EXEC is 0") - - def test_asymmetric_operand_order_guard(self): - # exec = [0, 20), s0 = [10, 30) in wave32 - m = (1 << 32) - 1 - e, s = lanes(0, 20, 32), lanes(10, 30, 32) - cases = [ - ("andn1", (~s & e) & m), - ("andn2", (s & ~e) & m), - ("orn1", (~s | e) & m), - ("orn2", (s | ~e) & m), - ] - for kind, want_new in cases: - with self.subTest(kind=kind): - op = f"s_{kind}_saveexec_b32 {{d}}, {{s0}}" - outs = case(op, 32, 20, 10, 30) - for lane in range(32): - want_bit = (want_new >> lane) & 1 - self.assertEqual(outs[lane][1], 0x22 if want_bit else 0x11, f"{kind} lane {lane}") - - def test_lane_reactivation(self): - # Initial EXEC = [0, 16). s_nor_saveexec_b32 with s2 = [8, 24) reactivates lanes [24, 32). - lines = [ - "v_mbcnt_lo_u32_b32 v4, -1, 0", - "v_cmp_ge_u32_e64 s2, v4, 8", - "v_cmp_lt_u32_e64 s6, v4, 24", - "s_and_b32 s2, s2, s6", - "v_mov_b32 v1, 0x55", - "v_cmpx_gt_u32_e32 16, v4", - "s_nor_saveexec_b32 s4, s2", - "v_mov_b32 v1, 0xAA", - "s_mov_b32 exec, -1", - "v_mov_b32 v0, v1", - "v_mov_b32 v2, 0", - "v_mov_b32 v3, 0", - ] - outs, _ = run_ps_wave(lines, wave=32) - for lane in range(32): - want = 0xAA if 24 <= lane < 32 else 0x55 - self.assertEqual(outs[lane][0], want, f"lane {lane}") - - def test_inline_constants_and_null_dst(self): - # 1. inline constant -1 in wave64 - lines_imm = [ - "v_mbcnt_lo_u32_b32 v4, -1, 0", - "v_mbcnt_hi_u32_b32 v4, -1, v4", - "s_mov_b64 exec, -1", - "s_andn1_saveexec_b64 s[4:5], -1", - "s_cselect_b32 s10, 1, 0", - "s_mov_b64 exec, -1", - "v_cndmask_b32_e64 v2, 0, 1, s[4:5]", - "v_mov_b32 v0, s10", - "v_mov_b32 v1, 0", - "v_mov_b32 v3, 0", - ] - outs_imm, _ = run_ps_wave(lines_imm, wave=64) - for lane in range(64): - self.assertEqual(outs_imm[lane][0], 0, "SCC should be 0 because ~(-1) & EXEC == 0") - self.assertEqual(outs_imm[lane][2], 1, "saved exec should be all 1s") - - # 2. null dst: s_nand_saveexec_b32 null, s4 - lines_null = [ - "v_mbcnt_lo_u32_b32 v4, -1, 0", - "s_mov_b32 s4, 0x0F0F0F0F", - "s_mov_b32 exec, -1", - "s_nand_saveexec_b32 null, s4", - "s_cselect_b32 s10, 1, 0", - "s_mov_b32 exec, -1", - "v_mov_b32 v0, s10", - "v_mov_b32 v1, 0", - "v_mov_b32 v2, 0", - "v_mov_b32 v3, 0", - ] - outs_null, _ = run_ps_wave(lines_null, wave=32) - for lane in range(32): - self.assertEqual(outs_null[lane][0], 1, "SCC should be 1") - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_scalar_alu_abs_neg.py b/tests/semantic/test_scalar_alu_abs_neg.py deleted file mode 100644 index 854e7f8c5..000000000 --- a/tests/semantic/test_scalar_alu_abs_neg.py +++ /dev/null @@ -1,973 +0,0 @@ -"""Semantic interpreter tests for RDNA2 scalar absolute value and bitwise NOT negation. - -Covers: - - s_abs_i32: D.i = abs(S0.i), SCC = (D != 0). - Two's complement 32-bit signed integer absolute value. - Boundary wrap: 0x80000000 (-2147483648) maps to 0x80000000, SCC = 1. - Zero maps to 0, SCC = 0. - - s_not_b32: D = ~S0 (bitwise NOT 32-bit), SCC = (D != 0). - Inverts all 32 bits. - Boundary: 0xFFFFFFFF maps to 0, SCC = 0. All other inputs produce SCC = 1. - - s_not_b64: D = ~S0 (bitwise NOT 64-bit), SCC = (D != 0). - Inverts all 64 bits across SGPR pairs or special registers (EXEC, VCC). - Boundary: 0xFFFFFFFFFFFFFFFF maps to 0, SCC = 0. All other inputs produce SCC = 1. - - Involution: ~(~x) == x for both 32-bit and 64-bit negation. - - Two's complement relationship: -x == ~x + 1 (mod 2^32), abs(x) == (x < 0 ? (~x + 1) : x). - - De Morgan's laws: ~(A & B) == (~A) | (~B), ~(A | B) == (~A) & (~B). - - Interaction with SCC condition code across sequences and conditional selects. - - SPIR-V translation validation via rdna2spirv.Gen. - - Synthetic fragment shader execution via spirv_mini_interp. - -Run directly: - python -I tests/semantic/test_scalar_alu_abs_neg.py -Or via unittest discovery: - python -m unittest discover -s tests/semantic -p 'test_scalar_alu_abs_neg.py' -""" -from __future__ import annotations - -import gc -import os -import random -import struct -import sys -import tempfile -import unittest -import warnings - -HERE = os.path.dirname(os.path.abspath(__file__)) -ROOT = os.path.dirname(os.path.dirname(HERE)) -TOOLS_DIR = os.environ.get("LEONIDA_TOOLS_DIR") or os.path.join(ROOT, "tools") - -sys.dont_write_bytecode = True -if ROOT not in sys.path: - sys.path.insert(0, ROOT) -if TOOLS_DIR not in sys.path: - sys.path.insert(0, TOOLS_DIR) -if HERE not in sys.path: - sys.path.insert(0, HERE) - -import rdna2spirv # noqa: E402 -import spirv_mini_interp as si # noqa: E402 - -MASK32 = 0xFFFFFFFF -MASK64 = 0xFFFFFFFFFFFFFFFF -SIGN32 = 0x80000000 -SIGN64 = 0x8000000000000000 -STUB_DXBC = b"DXBC" + bytes(24) + struct.pack(" int: - """Normalize integer to 32-bit unsigned.""" - return v & MASK32 - - -def s32(v: int) -> int: - """Interpret 32-bit unsigned integer as signed two's complement.""" - v &= MASK32 - return v - (1 << 32) if (v & SIGN32) else v - - -def u64(v: int) -> int: - """Normalize integer to 64-bit unsigned.""" - return v & MASK64 - - -def s64(v: int) -> int: - """Interpret 64-bit unsigned integer as signed two's complement.""" - v &= MASK64 - return v - (1 << 64) if (v & SIGN64) else v - - -def split_dwords(v64: int) -> tuple[int, int]: - """Split 64-bit integer into (low_u32, high_u32).""" - v = v64 & MASK64 - return v & MASK32, (v >> 32) & MASK32 - - -def join_dwords(lo: int, hi: int) -> int: - """Join (low_u32, high_u32) into a 64-bit unsigned integer.""" - return (((hi & MASK32) << 32) | (lo & MASK32)) & MASK64 - - -def ref_s_abs_i32(s0: int) -> tuple[int, int]: - """Reference implementation of s_abs_i32. - - D = |(signed)S0| mod 2^32. - SCC = 1 if D != 0 else 0. - In two's complement, 0x80000000 (-2147483648) wraps to 0x80000000, with SCC = 1. - """ - v = s0 & MASK32 - signed_val = v - (1 << 32) if (v & SIGN32) else v - abs_val = abs(signed_val) & MASK32 - scc = 1 if abs_val != 0 else 0 - return abs_val, scc - - -def ref_s_not_b32(s0: int) -> tuple[int, int]: - """Reference implementation of s_not_b32. - - D = ~S0 mod 2^32 (bitwise NOT). - SCC = 1 if D != 0 else 0. - """ - res = (~s0) & MASK32 - scc = 1 if res != 0 else 0 - return res, scc - - -def ref_s_not_b64(s0: int) -> tuple[int, int]: - """Reference implementation of s_not_b64. - - D = ~S0 mod 2^64 (bitwise NOT). - SCC = 1 if D != 0 else 0. - """ - res = (~s0) & MASK64 - scc = 1 if res != 0 else 0 - return res, scc - - -class ScalarAbsNegInterpreter: - """Deterministic semantic interpreter for RDNA2 scalar absolute value and negation. - - Tracks 32-bit SGPRs (paired for 64-bit operations), 64-bit EXEC, 64-bit VCC, - and the 1-bit SCC (Scalar Condition Code) register. - """ - - def __init__(self, num_sgprs: int = 106) -> None: - self.num_sgprs = num_sgprs - self.sgpr = [0] * num_sgprs - self.exec_mask = MASK64 - self.vcc = 0 - self.scc = 0 - - def reset(self) -> None: - self.sgpr = [0] * self.num_sgprs - self.exec_mask = MASK64 - self.vcc = 0 - self.scc = 0 - - def get_sgpr_u32(self, r: int) -> int: - return self.sgpr[r] & MASK32 - - def set_sgpr_u32(self, r: int, val: int) -> None: - self.sgpr[r] = val & MASK32 - - def get_sgpr_u64(self, r: int) -> int: - lo = self.get_sgpr_u32(r) - hi = self.get_sgpr_u32(r + 1) - return join_dwords(lo, hi) - - def set_sgpr_u64(self, r: int, val64: int) -> None: - lo, hi = split_dwords(val64) - self.set_sgpr_u32(r, lo) - self.set_sgpr_u32(r + 1, hi) - - def _resolve_src32(self, operand: int | dict | str) -> int: - """Resolve a 32-bit source operand (SGPR, immediate, or special register half).""" - if isinstance(operand, int): - return operand & MASK32 - if isinstance(operand, dict): - k = operand.get("k") - if k == "imm": - return operand["v"] & MASK32 - if k == "sgpr": - return self.get_sgpr_u32(operand["r"]) - if k == "special": - t = operand.get("t", "") - if t in ("exec", "exec_lo"): - return self.exec_mask & MASK32 - if t == "exec_hi": - return (self.exec_mask >> 32) & MASK32 - if t in ("vcc", "vcc_lo"): - return self.vcc & MASK32 - if t == "vcc_hi": - return (self.vcc >> 32) & MASK32 - if t == "scc": - return self.scc - raise ValueError(f"Unknown 32-bit operand dictionary: {operand}") - if isinstance(operand, str): - op_lower = operand.lower() - if op_lower in ("exec", "exec_lo"): - return self.exec_mask & MASK32 - if op_lower == "exec_hi": - return (self.exec_mask >> 32) & MASK32 - if op_lower in ("vcc", "vcc_lo"): - return self.vcc & MASK32 - if op_lower == "vcc_hi": - return (self.vcc >> 32) & MASK32 - if op_lower == "scc": - return self.scc - if op_lower.startswith("s"): - return self.get_sgpr_u32(int(op_lower[1:])) - raise TypeError(f"Unsupported 32-bit operand type: {type(operand)} ({operand})") - - def _resolve_src64(self, operand: int | dict | str) -> int: - """Resolve a 64-bit source operand (SGPR pair, immediate, or special register).""" - if isinstance(operand, int): - return operand & MASK64 - if isinstance(operand, dict): - k = operand.get("k") - if k == "imm": - return operand["v"] & MASK64 - if k == "sgpr": - return self.get_sgpr_u64(operand["r"]) - if k == "special": - t = operand.get("t", "") - if t in ("exec", "exec_lo", "exec_hi"): - return self.exec_mask - if t in ("vcc", "vcc_lo", "vcc_hi"): - return self.vcc - raise ValueError(f"Unknown 64-bit operand dictionary: {operand}") - if isinstance(operand, str): - op_lower = operand.lower() - if op_lower in ("exec", "exec_lo", "exec_hi"): - return self.exec_mask - if op_lower in ("vcc", "vcc_lo", "vcc_hi"): - return self.vcc - if op_lower.startswith("s[") and ":" in op_lower: - lo_idx = int(op_lower[2:-1].split(":")[0]) - return self.get_sgpr_u64(lo_idx) - if op_lower.startswith("s"): - return self.get_sgpr_u64(int(op_lower[1:])) - raise TypeError(f"Unsupported 64-bit operand type: {type(operand)} ({operand})") - - def _write_dst32(self, dst: int | dict | str, val: int) -> None: - """Write 32-bit result into target SGPR or special register.""" - val = val & MASK32 - if isinstance(dst, int): - self.set_sgpr_u32(dst, val) - elif isinstance(dst, dict): - k = dst.get("k") - if k == "sgpr": - self.set_sgpr_u32(dst["r"], val) - elif k == "special": - t = dst.get("t", "") - if t in ("exec", "exec_lo"): - self.exec_mask = (self.exec_mask & (MASK32 << 32)) | val - elif t == "exec_hi": - self.exec_mask = (self.exec_mask & MASK32) | (val << 32) - elif t in ("vcc", "vcc_lo"): - self.vcc = (self.vcc & (MASK32 << 32)) | val - elif t == "vcc_hi": - self.vcc = (self.vcc & MASK32) | (val << 32) - elif t == "scc": - self.scc = 1 if val != 0 else 0 - elif isinstance(dst, str): - d_lower = dst.lower() - if d_lower.startswith("s"): - self.set_sgpr_u32(int(d_lower[1:]), val) - elif d_lower in ("exec", "exec_lo"): - self.exec_mask = (self.exec_mask & (MASK32 << 32)) | val - elif d_lower == "exec_hi": - self.exec_mask = (self.exec_mask & MASK32) | (val << 32) - elif d_lower in ("vcc", "vcc_lo"): - self.vcc = (self.vcc & (MASK32 << 32)) | val - elif d_lower == "vcc_hi": - self.vcc = (self.vcc & MASK32) | (val << 32) - elif d_lower == "scc": - self.scc = 1 if val != 0 else 0 - - def _write_dst64(self, dst: int | dict | str, val: int) -> None: - """Write 64-bit result into target SGPR pair or special register.""" - val = val & MASK64 - if isinstance(dst, int): - self.set_sgpr_u64(dst, val) - elif isinstance(dst, dict): - k = dst.get("k") - if k == "sgpr": - self.set_sgpr_u64(dst["r"], val) - elif k == "special": - t = dst.get("t", "") - if t in ("exec", "exec_lo", "exec_hi"): - self.exec_mask = val - elif t in ("vcc", "vcc_lo", "vcc_hi"): - self.vcc = val - elif isinstance(dst, str): - d_lower = dst.lower() - if d_lower in ("exec", "exec_lo", "exec_hi"): - self.exec_mask = val - elif d_lower in ("vcc", "vcc_lo", "vcc_hi"): - self.vcc = val - elif d_lower.startswith("s[") and ":" in d_lower: - lo_idx = int(d_lower[2:-1].split(":")[0]) - self.set_sgpr_u64(lo_idx, val) - elif d_lower.startswith("s"): - self.set_sgpr_u64(int(d_lower[1:]), val) - - def step(self, op: str, dst: int | dict | str, s0: int | dict | str, - s1: int | dict | str | None = None) -> tuple[int, int]: - """Execute a single scalar ALU instruction and return (result, scc).""" - if op == "s_abs_i32": - val = self._resolve_src32(s0) - res, scc = ref_s_abs_i32(val) - self._write_dst32(dst, res) - self.scc = scc - return res, self.scc - - if op == "s_not_b32": - val = self._resolve_src32(s0) - res, scc = ref_s_not_b32(val) - self._write_dst32(dst, res) - self.scc = scc - return res, self.scc - - if op == "s_not_b64": - val = self._resolve_src64(s0) - res, scc = ref_s_not_b64(val) - self._write_dst64(dst, res) - self.scc = scc - return res, self.scc - - if op == "s_mov_b32": - val = self._resolve_src32(s0) - self._write_dst32(dst, val) - return val, self.scc - - if op == "s_mov_b64": - val = self._resolve_src64(s0) - self._write_dst64(dst, val) - return val, self.scc - - if op == "s_add_u32": - v0 = self._resolve_src32(s0) - v1 = self._resolve_src32(s1 if s1 is not None else 0) - full = v0 + v1 - res = full & MASK32 - self.scc = 1 if full >= (1 << 32) else 0 - self._write_dst32(dst, res) - return res, self.scc - - if op == "s_and_b32": - v0 = self._resolve_src32(s0) - v1 = self._resolve_src32(s1 if s1 is not None else 0) - res = (v0 & v1) & MASK32 - self.scc = 1 if res != 0 else 0 - self._write_dst32(dst, res) - return res, self.scc - - if op == "s_and_b64": - v0 = self._resolve_src64(s0) - v1 = self._resolve_src64(s1 if s1 is not None else 0) - res = (v0 & v1) & MASK64 - self.scc = 1 if res != 0 else 0 - self._write_dst64(dst, res) - return res, self.scc - - if op == "s_or_b32": - v0 = self._resolve_src32(s0) - v1 = self._resolve_src32(s1 if s1 is not None else 0) - res = (v0 | v1) & MASK32 - self.scc = 1 if res != 0 else 0 - self._write_dst32(dst, res) - return res, self.scc - - if op == "s_or_b64": - v0 = self._resolve_src64(s0) - v1 = self._resolve_src64(s1 if s1 is not None else 0) - res = (v0 | v1) & MASK64 - self.scc = 1 if res != 0 else 0 - self._write_dst64(dst, res) - return res, self.scc - - if op == "s_xor_b32": - v0 = self._resolve_src32(s0) - v1 = self._resolve_src32(s1 if s1 is not None else 0) - res = (v0 ^ v1) & MASK32 - self.scc = 1 if res != 0 else 0 - self._write_dst32(dst, res) - return res, self.scc - - if op == "s_xor_b64": - v0 = self._resolve_src64(s0) - v1 = self._resolve_src64(s1 if s1 is not None else 0) - res = (v0 ^ v1) & MASK64 - self.scc = 1 if res != 0 else 0 - self._write_dst64(dst, res) - return res, self.scc - - if op == "s_cselect_b32": - v0 = self._resolve_src32(s0) - v1 = self._resolve_src32(s1 if s1 is not None else 0) - res = v0 if self.scc != 0 else v1 - self._write_dst32(dst, res) - return res, self.scc - - if op == "s_cselect_b64": - v0 = self._resolve_src64(s0) - v1 = self._resolve_src64(s1 if s1 is not None else 0) - res = v0 if self.scc != 0 else v1 - self._write_dst64(dst, res) - return res, self.scc - - raise NotImplementedError(f"Unsupported scalar opcode: {op}") - - def execute_ir(self, insn: dict) -> tuple[int, int]: - """Execute an instruction dictionary matching the rdna2spirv parser IR format.""" - op = insn["op"] - args = insn["args"] - dst = args[0] - s0 = args[1] - s1 = args[2] if len(args) > 2 else None - return self.step(op, dst, s0, s1) - - def run_sequence(self, instructions: list[dict | tuple]) -> tuple[int, int]: - """Execute an ordered sequence of instructions and return the final (result, scc).""" - last_res, last_scc = 0, self.scc - for item in instructions: - if isinstance(item, dict): - last_res, last_scc = self.execute_ir(item) - else: - op = item[0] - dst = item[1] - s0 = item[2] - s1 = item[3] if len(item) > 3 else None - last_res, last_scc = self.step(op, dst, s0, s1) - return last_res, last_scc - - -class TestScalarAbsI32Reference(unittest.TestCase): - """Direct mathematical unit tests for 32-bit scalar integer absolute value (s_abs_i32).""" - - def test_abs_zero(self): - res, scc = ref_s_abs_i32(0) - self.assertEqual(res, 0) - self.assertEqual(scc, 0) - - def test_abs_positive_values(self): - positives = [1, 2, 42, 100, 1000, 0x12345678, 0x7FFFFFFF] - for val in positives: - with self.subTest(val=hex(val)): - res, scc = ref_s_abs_i32(val) - self.assertEqual(res, val) - self.assertEqual(scc, 1) - - def test_abs_negative_values(self): - cases = [ - (-1, 1), - (-2, 2), - (-42, 42), - (-1000, 1000), - (-0x7FFFFFFF, 0x7FFFFFFF), - (0xFFFFFFFF, 1), - (0xFFFFFFFE, 2), - (0x80000001, 0x7FFFFFFF), - ] - for inp, want in cases: - with self.subTest(inp=hex(inp & MASK32)): - res, scc = ref_s_abs_i32(inp) - self.assertEqual(res, want) - self.assertEqual(scc, 1) - - def test_abs_int_min_overflow_wrap(self): - # 0x80000000 (-2147483648) wraps back to 0x80000000 in two's complement. - # Hardware SCC = (D != 0) is 1. - res, scc = ref_s_abs_i32(0x80000000) - self.assertEqual(res, 0x80000000) - self.assertEqual(scc, 1) - - def test_abs_idempotence(self): - samples = [0, 1, -1, 42, -42, 0x7FFFFFFF, 0x80000000, 0x80000001, 0xFFFFFFFF, 0xDEADBEEF] - for val in samples: - with self.subTest(val=hex(val & MASK32)): - first_res, first_scc = ref_s_abs_i32(val) - second_res, second_scc = ref_s_abs_i32(first_res) - self.assertEqual(second_res, first_res) - self.assertEqual(second_scc, first_scc) - - def test_abs_non_negative_range(self): - for val in range(-250, 251): - res, scc = ref_s_abs_i32(val) - self.assertGreaterEqual(res, 0) - self.assertLessEqual(res, 0x7FFFFFFF) - self.assertEqual(scc, 0 if val == 0 else 1) - - -class TestScalarNotB32Reference(unittest.TestCase): - """Direct mathematical unit tests for 32-bit scalar bitwise NOT (s_not_b32).""" - - def test_not_zero_to_all_ones(self): - res, scc = ref_s_not_b32(0) - self.assertEqual(res, 0xFFFFFFFF) - self.assertEqual(scc, 1) - - def test_not_all_ones_to_zero(self): - # 0xFFFFFFFF is the only 32-bit input that yields 0 and clears SCC. - res, scc = ref_s_not_b32(0xFFFFFFFF) - self.assertEqual(res, 0) - self.assertEqual(scc, 0) - - def test_not_alternating_bits(self): - self.assertEqual(ref_s_not_b32(0x55555555), (0xAAAAAAAA, 1)) - self.assertEqual(ref_s_not_b32(0xAAAAAAAA), (0x55555555, 1)) - self.assertEqual(ref_s_not_b32(0x33333333), (0xCCCCCCCC, 1)) - self.assertEqual(ref_s_not_b32(0x0F0F0F0F), (0xF0F0F0F0, 1)) - - def test_not_walking_ones(self): - for bit in range(32): - pattern = 1 << bit - res, scc = ref_s_not_b32(pattern) - expected = (~pattern) & MASK32 - self.assertEqual(res, expected) - self.assertEqual(scc, 1) - - def test_not_walking_zeroes(self): - for bit in range(32): - pattern = (~(1 << bit)) & MASK32 - res, scc = ref_s_not_b32(pattern) - expected = 1 << bit - self.assertEqual(res, expected) - self.assertEqual(scc, 1) - - def test_not_involution(self): - samples = [0, 1, 0xFFFFFFFF, 0x7FFFFFFF, 0x80000000, 0x12345678, 0xCAFEBABE] - for val in samples: - with self.subTest(val=hex(val)): - r1, _ = ref_s_not_b32(val) - r2, _ = ref_s_not_b32(r1) - self.assertEqual(r2, val & MASK32) - - def test_not_xor_equivalence(self): - rng = random.Random(42) - for _ in range(100): - val = rng.getrandbits(32) - res, _ = ref_s_not_b32(val) - self.assertEqual(res, val ^ MASK32) - - -class TestScalarNotB64Reference(unittest.TestCase): - """Direct mathematical unit tests for 64-bit scalar bitwise NOT (s_not_b64).""" - - def test_not_b64_zero_to_all_ones(self): - res, scc = ref_s_not_b64(0) - self.assertEqual(res, MASK64) - self.assertEqual(scc, 1) - - def test_not_b64_all_ones_to_zero(self): - # MASK64 is the only 64-bit input that yields 0 and clears SCC. - res, scc = ref_s_not_b64(MASK64) - self.assertEqual(res, 0) - self.assertEqual(scc, 0) - - def test_not_b64_half_zeros(self): - res1, scc1 = ref_s_not_b64(0x00000000FFFFFFFF) - self.assertEqual(res1, 0xFFFFFFFF00000000) - self.assertEqual(scc1, 1) - - res2, scc2 = ref_s_not_b64(0xFFFFFFFF00000000) - self.assertEqual(res2, 0x00000000FFFFFFFF) - self.assertEqual(scc2, 1) - - def test_not_b64_alternating_bits(self): - res1, scc1 = ref_s_not_b64(0x5555555555555555) - self.assertEqual(res1, 0xAAAAAAAAAAAAAAAA) - self.assertEqual(scc1, 1) - - res2, scc2 = ref_s_not_b64(0xAAAAAAAAAAAAAAAA) - self.assertEqual(res2, 0x5555555555555555) - self.assertEqual(scc2, 1) - - def test_not_b64_walking_bits(self): - for bit in range(64): - pattern = 1 << bit - res, scc = ref_s_not_b64(pattern) - expected = (~pattern) & MASK64 - self.assertEqual(res, expected) - self.assertEqual(scc, 1) - - def test_not_b64_involution(self): - samples = [ - 0, - 1, - MASK64, - 0x7FFFFFFFFFFFFFFF, - 0x8000000000000000, - 0x123456789ABCDEF0, - 0xDEADBEEFCAFEBABE, - ] - for val in samples: - with self.subTest(val=hex(val)): - r1, _ = ref_s_not_b64(val) - r2, _ = ref_s_not_b64(r1) - self.assertEqual(r2, val & MASK64) - - -class TestScalarAbsNegInterpreter(unittest.TestCase): - """Unit tests for ScalarAbsNegInterpreter state tracking and instruction execution.""" - - def setUp(self): - self.interp = ScalarAbsNegInterpreter() - - def test_interpreter_abs_i32_state(self): - # s_abs_i32 with negative input: -42 -> 42, SCC = 1 - self.interp.step("s_mov_b32", "s0", -42) - res, scc = self.interp.step("s_abs_i32", "s1", "s0") - self.assertEqual(res, 42) - self.assertEqual(scc, 1) - self.assertEqual(self.interp.get_sgpr_u32(1), 42) - self.assertEqual(self.interp.scc, 1) - - # s_abs_i32 with zero: 0 -> 0, SCC = 0 - self.interp.step("s_mov_b32", "s0", 0) - res, scc = self.interp.step("s_abs_i32", "s1", "s0") - self.assertEqual(res, 0) - self.assertEqual(scc, 0) - self.assertEqual(self.interp.get_sgpr_u32(1), 0) - self.assertEqual(self.interp.scc, 0) - - # s_abs_i32 with 0x80000000: wraps to 0x80000000, SCC = 1 - self.interp.step("s_mov_b32", "s0", 0x80000000) - res, scc = self.interp.step("s_abs_i32", "s1", "s0") - self.assertEqual(res, 0x80000000) - self.assertEqual(scc, 1) - self.assertEqual(self.interp.get_sgpr_u32(1), 0x80000000) - self.assertEqual(self.interp.scc, 1) - - def test_interpreter_not_b32_state(self): - # Inverting 0 produces 0xFFFFFFFF with SCC = 1 - self.interp.step("s_mov_b32", "s0", 0) - res, scc = self.interp.step("s_not_b32", "s1", "s0") - self.assertEqual(res, 0xFFFFFFFF) - self.assertEqual(scc, 1) - self.assertEqual(self.interp.get_sgpr_u32(1), 0xFFFFFFFF) - self.assertEqual(self.interp.scc, 1) - - # Inverting 0xFFFFFFFF produces 0 with SCC = 0 - res, scc = self.interp.step("s_not_b32", "s2", "s1") - self.assertEqual(res, 0) - self.assertEqual(scc, 0) - self.assertEqual(self.interp.get_sgpr_u32(2), 0) - self.assertEqual(self.interp.scc, 0) - - def test_interpreter_not_b64_state(self): - # Write 64-bit value to s[0:1], negate into s[2:3] - val64 = 0x12345678_9ABCDEF0 - self.interp.set_sgpr_u64(0, val64) - res, scc = self.interp.step("s_not_b64", "s2", "s0") - expected = (~val64) & MASK64 - self.assertEqual(res, expected) - self.assertEqual(scc, 1) - self.assertEqual(self.interp.get_sgpr_u64(2), expected) - - # Inverting all ones produces 0 and clears SCC - self.interp.set_sgpr_u64(0, MASK64) - res, scc = self.interp.step("s_not_b64", "s4", "s0") - self.assertEqual(res, 0) - self.assertEqual(scc, 0) - self.assertEqual(self.interp.get_sgpr_u64(4), 0) - self.assertEqual(self.interp.scc, 0) - - def test_adjacent_registers_remain_untouched(self): - self.interp.set_sgpr_u32(0, 0xAAAAAAAA) - self.interp.set_sgpr_u32(1, 0xBBBBBBBB) - self.interp.set_sgpr_u32(4, 0xCCCCCCCC) - self.interp.set_sgpr_u32(5, 0xDDDDDDDD) - - # Write 64-bit result into s[2:3] - self.interp.step("s_not_b64", 2, 0x0000000000000000) - self.assertEqual(self.interp.get_sgpr_u32(0), 0xAAAAAAAA) - self.assertEqual(self.interp.get_sgpr_u32(1), 0xBBBBBBBB) - self.assertEqual(self.interp.get_sgpr_u32(2), 0xFFFFFFFF) - self.assertEqual(self.interp.get_sgpr_u32(3), 0xFFFFFFFF) - self.assertEqual(self.interp.get_sgpr_u32(4), 0xCCCCCCCC) - self.assertEqual(self.interp.get_sgpr_u32(5), 0xDDDDDDDD) - - def test_special_registers_exec_and_vcc(self): - # Invert EXEC lane mask: 0xFFFFFFFF_00000000 -> 0x00000000_FFFFFFFF - self.interp.exec_mask = 0xFFFFFFFF_00000000 - res, scc = self.interp.step("s_not_b64", "exec", "exec") - self.assertEqual(res, 0x00000000_FFFFFFFF) - self.assertEqual(self.interp.exec_mask, 0x00000000_FFFFFFFF) - self.assertEqual(scc, 1) - - # Invert VCC mask: 0 -> MASK64 - self.interp.vcc = 0 - res, scc = self.interp.step("s_not_b64", "vcc", "vcc") - self.assertEqual(res, MASK64) - self.assertEqual(self.interp.vcc, MASK64) - self.assertEqual(scc, 1) - - # Lane partition properties: (exec & ~exec) == 0, (exec | ~exec) == MASK64 - self.interp.exec_mask = 0xAAAAAAAAAAAAAAAA - self.interp.step("s_not_b64", "s0", "exec") - self.assertEqual(self.interp.get_sgpr_u64(0), 0x5555555555555555) - self.assertEqual(self.interp.exec_mask & self.interp.get_sgpr_u64(0), 0) - self.assertEqual(self.interp.exec_mask | self.interp.get_sgpr_u64(0), MASK64) - - def test_two_complement_negation_via_not_and_add(self): - # Mathematical identity: -x == ~x + 1 - test_values = [1, 2, 42, 100, 0x12345678, 0x7FFFFFFF, 0x80000000] - for val in test_values: - with self.subTest(val=hex(val)): - self.interp.step("s_mov_b32", "s0", val) - self.interp.step("s_not_b32", "s1", "s0") - neg_res, _ = self.interp.step("s_add_u32", "s2", "s1", 1) - - expected_neg = ((-val) & MASK32) - self.assertEqual(neg_res, expected_neg) - - # For negative inputs, s_abs_i32 matches two's complement negation - abs_res, _ = self.interp.step("s_abs_i32", "s3", neg_res) - self.assertEqual(abs_res, val if val != 0x80000000 else 0x80000000) - - def test_de_morgans_laws_32(self): - # ~(A & B) == (~A) | (~B) - # ~(A | B) == (~A) & (~B) - pairs = [ - (0x12345678, 0x9ABCDEF0), - (0x55555555, 0xAAAAAAAA), - (0x0000FFFF, 0xFFFF0000), - (0xFFFFFFFF, 0x12345678), - ] - for a, b in pairs: - with self.subTest(a=hex(a), b=hex(b)): - # Left side: ~(A & B) - self.interp.step("s_and_b32", "s0", a, b) - lhs1, _ = self.interp.step("s_not_b32", "s1", "s0") - - # Right side: (~A) | (~B) - self.interp.step("s_not_b32", "s2", a) - self.interp.step("s_not_b32", "s3", b) - rhs1, _ = self.interp.step("s_or_b32", "s4", "s2", "s3") - self.assertEqual(lhs1, rhs1) - - # Left side: ~(A | B) - self.interp.step("s_or_b32", "s0", a, b) - lhs2, _ = self.interp.step("s_not_b32", "s1", "s0") - - # Right side: (~A) & (~B) - rhs2, _ = self.interp.step("s_and_b32", "s5", "s2", "s3") - self.assertEqual(lhs2, rhs2) - - def test_de_morgans_laws_64(self): - pairs = [ - (0x12345678_9ABCDEF0, 0x0FEDCBA9_87654321), - (0x55555555_55555555, 0xAAAAAAA_AAAAAAAA), - (0x00000000_FFFFFFFF, 0xFFFFFFFF_00000000), - ] - for a, b in pairs: - with self.subTest(a=hex(a), b=hex(b)): - # Left side: ~(A & B) - self.interp.step("s_and_b64", "s0", a, b) - lhs1, _ = self.interp.step("s_not_b64", "s2", "s0") - - # Right side: (~A) | (~B) - self.interp.step("s_not_b64", "s4", a) - self.interp.step("s_not_b64", "s6", b) - rhs1, _ = self.interp.step("s_or_b64", "s8", "s4", "s6") - self.assertEqual(lhs1, rhs1) - - # Left side: ~(A | B) - self.interp.step("s_or_b64", "s0", a, b) - lhs2, _ = self.interp.step("s_not_b64", "s2", "s0") - - # Right side: (~A) & (~B) - rhs2, _ = self.interp.step("s_and_b64", "s10", "s4", "s6") - self.assertEqual(lhs2, rhs2) - - def test_cselect_branching_on_scc(self): - # When s_abs_i32 result is zero, SCC is 0 -> s_cselect_b32 chooses S1 - self.interp.step("s_abs_i32", "s0", 0) - self.interp.step("s_cselect_b32", "s1", 100, 200) - self.assertEqual(self.interp.get_sgpr_u32(1), 200) - - # When s_abs_i32 result is non-zero, SCC is 1 -> s_cselect_b32 chooses S0 - self.interp.step("s_abs_i32", "s0", -5) - self.interp.step("s_cselect_b32", "s1", 100, 200) - self.assertEqual(self.interp.get_sgpr_u32(1), 100) - - # When s_not_b32 result is zero (input 0xFFFFFFFF), SCC is 0 -> S1 chosen - self.interp.step("s_not_b32", "s0", 0xFFFFFFFF) - self.interp.step("s_cselect_b32", "s2", 300, 400) - self.assertEqual(self.interp.get_sgpr_u32(2), 400) - - -class TestSpirvTranslatorIntegration(unittest.TestCase): - """Validation of rdna2spirv instruction lowering for s_abs_i32, s_not_b32, and s_not_b64.""" - - def test_rdna2spirv_abs_i32_emission(self): - gen = rdna2spirv.Gen("ps") - insn = { - "op": "s_abs_i32", - "args": [{"k": "sgpr", "r": 0}, {"k": "sgpr", "r": 1}], - "mods": [], - } - gen._insn(insn) - body = "\n".join(gen.body) - - self.assertIn("OpBitcast %int", body) - self.assertIn("OpExtInst %int %glsl SAbs", body) - self.assertIn("OpBitcast %uint", body) - self.assertIn("OpINotEqual %bool", body) - self.assertIn("OpSelect %uint", body) - self.assertIn("OpStore %scc", body) - - def test_rdna2spirv_not_b32_emission(self): - gen = rdna2spirv.Gen("ps") - insn = { - "op": "s_not_b32", - "args": [{"k": "sgpr", "r": 2}, {"k": "sgpr", "r": 3}], - "mods": [], - } - gen._insn(insn) - body = "\n".join(gen.body) - - self.assertIn("OpNot %uint", body) - self.assertIn("OpINotEqual %bool", body) - self.assertIn("OpSelect %uint", body) - self.assertIn("OpStore %scc", body) - - def test_rdna2spirv_not_b64_emission(self): - # 1. Scalar SGPR pair negation - gen = rdna2spirv.Gen("ps") - insn = { - "op": "s_not_b64", - "args": [{"k": "sgpr", "r": 4, "n": 2}, {"k": "sgpr", "r": 6, "n": 2}], - "mods": [], - } - gen._insn(insn) - body = "\n".join(gen.body) - - self.assertIn("OpNot %uint", body) - self.assertIn("OpBitwiseOr %uint", body) - self.assertIn("OpStore %scc", body) - - # 2. Mask register (EXEC) negation emits wave-vote reduction - gen_exec = rdna2spirv.Gen("ps") - insn_exec = { - "op": "s_not_b64", - "args": [{"k": "special", "t": "exec"}, {"k": "special", "t": "exec"}], - "mods": [], - } - gen_exec._insn(insn_exec) - body_exec = "\n".join(gen_exec.body) - - self.assertIn("OpNot %uint", body_exec) - self.assertIn("OpGroupNonUniformBallot", body_exec) - self.assertIn("%c20", body_exec) - self.assertIn("OpStore %scc", body_exec) - - def test_spirv_math_model_equivalence(self): - rng = random.Random(1337) - for _ in range(300): - val = rng.getrandbits(32) - - # 1. SPIR-V s_abs_i32 math emulation: - # OpBitcast %int -> OpExtInst %glsl SAbs -> OpBitcast %uint -> OpINotEqual -> OpSelect - signed_i = val - (1 << 32) if (val & SIGN32) else val - spv_abs = abs(signed_i) & MASK32 - spv_scc_abs = 1 if spv_abs != 0 else 0 - - ref_abs_val, ref_abs_scc = ref_s_abs_i32(val) - self.assertEqual(spv_abs, ref_abs_val) - self.assertEqual(spv_scc_abs, ref_abs_scc) - - # 2. SPIR-V s_not_b32 math emulation: - # OpNot %uint -> OpINotEqual -> OpSelect - spv_not = (~val) & MASK32 - spv_scc_not = 1 if spv_not != 0 else 0 - - ref_not_val, ref_not_scc = ref_s_not_b32(val) - self.assertEqual(spv_not, ref_not_val) - self.assertEqual(spv_scc_not, ref_not_scc) - - -class TestFragmentShaderExecution(unittest.TestCase): - """End-to-end execution of synthetic shaders exercising s_abs_i32 and s_not_b32 via spirv_mini_interp.""" - - @classmethod - def setUpClass(cls): - cls.tmp_dir = tempfile.TemporaryDirectory() - cls.disasm_dir = os.path.join(cls.tmp_dir.name, "disasm") - os.mkdir(cls.disasm_dir) - cls.src_path = os.path.join(cls.disasm_dir, "ps_abs_neg_test.s") - with open(os.path.join(cls.tmp_dir.name, "ps_abs_neg_test.dxbc"), "wb") as f: - f.write(STUB_DXBC) - - @classmethod - def tearDownClass(cls): - gc.collect() - if cls.tmp_dir is not None: - cls.tmp_dir.cleanup() - - def _run_ps_lines(self, lines: list[str]) -> tuple[int, int]: - """Translate assembly snippet into SPIR-V, execute in mini-interp, and return (mrt0[0], mrt0[1]).""" - asm = "; synthetic test\n" + "".join(f"\t{line}\n" for line in lines) + \ - "\texp mrt0 v0, v1, v0, v0 done vm\n\ts_endpgm\n" - with open(self.src_path, "w", encoding="utf-8") as f: - f.write(asm) - with warnings.catch_warnings(): - warnings.simplefilter("ignore", ResourceWarning) - spv = rdna2spirv.translate(self.src_path) - out = si.run_fragment(spv)["%out_mrt0"] - return out[0], out[1] - - def test_synthetic_shader_s_abs_i32(self): - values = [0, 1, 42, 0x7FFFFFFF, 0x80000000, 0xFFFFFFFF, 0xFFFFFFFE, 0x12345678] - for x in values: - with self.subTest(x=hex(x)): - want_val, want_scc = ref_s_abs_i32(x) - lines = [ - f"s_mov_b32 s2, {x:#x}", - "s_abs_i32 s0, s2", - "s_cselect_b32 s1, 1, 0", - "v_mov_b32 v0, s0", - "v_mov_b32 v1, s1", - ] - got_val, got_scc = self._run_ps_lines(lines) - self.assertEqual(got_val, want_val) - self.assertEqual(got_scc, want_scc) - - def test_synthetic_shader_s_not_b32(self): - values = [0, 1, 0xFFFFFFFF, 0x55555555, 0xAAAAAAAA, 0x12345678, 0x0000FFFF] - for x in values: - with self.subTest(x=hex(x)): - want_val, want_scc = ref_s_not_b32(x) - lines = [ - f"s_mov_b32 s2, {x:#x}", - "s_not_b32 s0, s2", - "s_cselect_b32 s1, 1, 0", - "v_mov_b32 v0, s0", - "v_mov_b32 v1, s1", - ] - got_val, got_scc = self._run_ps_lines(lines) - self.assertEqual(got_val, want_val) - self.assertEqual(got_scc, want_scc) - - def test_synthetic_shader_s_not_b64(self): - cases = [ - (0x12345678_9ABCDEF0, 0x12345678, 0x9ABCDEF0), - (0x00000000_00000000, 0x00000000, 0x00000000), - (0xFFFFFFFF_FFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF), - (0x55555555_AAAAAAAA, 0x55555555, 0xAAAAAAAA), - ] - for val64, hi, lo in cases: - with self.subTest(val=hex(val64)): - want_lo, _ = split_dwords((~val64) & MASK64) - want_scc = 1 if ((~val64) & MASK64) != 0 else 0 - lines = [ - f"s_mov_b32 s4, {lo:#x}", - f"s_mov_b32 s5, {hi:#x}", - "s_not_b64 s[2:3], s[4:5]", - "s_cselect_b32 s10, 1, 0", - "v_mov_b32 v0, s2", - "v_mov_b32 v1, s10", - ] - got_val, got_scc = self._run_ps_lines(lines) - self.assertEqual(got_val, want_lo) - self.assertEqual(got_scc, want_scc) - - def test_synthetic_shader_negation_chain(self): - # In a shader, negate an integer by bitwise NOT followed by adding 1: - # -42 -> 42 - lines = [ - "s_mov_b32 s2, -42", - "s_not_b32 s0, s2", - "s_add_u32 s0, s0, 1", - "v_mov_b32 v0, s0", - "v_mov_b32 v1, 0", - ] - got_val, _ = self._run_ps_lines(lines) - self.assertEqual(got_val, 42) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_scalar_alu_add_sub.py b/tests/semantic/test_scalar_alu_add_sub.py deleted file mode 100644 index e001046cf..000000000 --- a/tests/semantic/test_scalar_alu_add_sub.py +++ /dev/null @@ -1,689 +0,0 @@ -"""Semantic interpreter tests for RDNA2 64-bit scalar addition and subtraction with carry. - -Covers: - * s_add_u32 (D = S0 + S1, SCC = unsigned carry-out) - * s_addc_u32 (D = S0 + S1 + SCC, SCC = unsigned carry-out) - * s_sub_u32 (D = S0 - S1, SCC = unsigned borrow-out) - * s_subb_u32 (D = S0 - S1 - SCC, SCC = unsigned borrow-out) - * Chained 64-bit scalar addition: - s_add_u32 d_lo, s0_lo, s1_lo - s_addc_u32 d_hi, s0_hi, s1_hi - * Chained 64-bit scalar subtraction: - s_sub_u32 d_lo, s0_lo, s1_lo - s_subb_u32 d_hi, s0_hi, s1_hi - * SPIR-V translation lowering equivalence (OpIAddCarry / OpISubBorrow lowering in tools/rdna2spirv.py). - -Run directly: - python -I tests/semantic/test_scalar_alu_add_sub.py -Or via unittest discovery: - python -m unittest discover -s tests/semantic -v -""" -import os -import random -import sys -import unittest - -HERE = os.path.dirname(os.path.abspath(__file__)) -ROOT = os.path.dirname(os.path.dirname(HERE)) -TOOLS_DIR = os.environ.get("LEONIDA_TOOLS_DIR") or os.path.join(ROOT, "tools") - -if ROOT not in sys.path: - sys.path.insert(0, ROOT) -if TOOLS_DIR not in sys.path: - sys.path.insert(0, TOOLS_DIR) - -import rdna2spirv - -MASK32 = 0xFFFFFFFF -MASK64 = 0xFFFFFFFFFFFFFFFF - - -class ScalarALUInterpreter: - """Deterministic semantic interpreter for RDNA2 scalar ALU add/sub operations. - - Tracks 32-bit SGPRs and the 1-bit SCC (Scalar Condition Code) register. - """ - - def __init__(self, num_sgprs=106): - self.sgpr = [0] * num_sgprs - self.scc = 0 - - def reset(self): - self.sgpr = [0] * len(self.sgpr) - self.scc = 0 - - @staticmethod - def eval_s_add_u32(s0, s1): - """Execute s_add_u32: D = (S0 + S1) mod 2^32; SCC = (S0 + S1 >= 2^32).""" - s0 = s0 & MASK32 - s1 = s1 & MASK32 - full = s0 + s1 - d = full & MASK32 - scc = 1 if full >= (1 << 32) else 0 - return d, scc - - @staticmethod - def eval_s_addc_u32(s0, s1, scc_in): - """Execute s_addc_u32: D = (S0 + S1 + SCC) mod 2^32; SCC = (S0 + S1 + SCC >= 2^32).""" - s0 = s0 & MASK32 - s1 = s1 & MASK32 - cin = 1 if scc_in else 0 - full = s0 + s1 + cin - d = full & MASK32 - scc = 1 if full >= (1 << 32) else 0 - return d, scc - - @staticmethod - def eval_s_sub_u32(s0, s1): - """Execute s_sub_u32: D = (S0 - S1) mod 2^32; SCC = (S0 < S1).""" - s0 = s0 & MASK32 - s1 = s1 & MASK32 - d = (s0 - s1) & MASK32 - scc = 1 if s0 < s1 else 0 - return d, scc - - @staticmethod - def eval_s_subb_u32(s0, s1, scc_in): - """Execute s_subb_u32: D = (S0 - S1 - SCC) mod 2^32; SCC = (S0 < S1 + SCC).""" - s0 = s0 & MASK32 - s1 = s1 & MASK32 - bin_ = 1 if scc_in else 0 - d = (s0 - s1 - bin_) & MASK32 - scc = 1 if s0 < (s1 + bin_) else 0 - return d, scc - - def step(self, insn): - """Execute an instruction dictionary with 'op', 'dst', 's0', 's1'.""" - op = insn["op"] - s0 = self._resolve_val(insn["s0"]) - s1 = self._resolve_val(insn["s1"]) - dst_idx = self._resolve_dst(insn["dst"]) - - if op == "s_add_u32": - res, scc = self.eval_s_add_u32(s0, s1) - elif op == "s_addc_u32": - res, scc = self.eval_s_addc_u32(s0, s1, self.scc) - elif op == "s_sub_u32": - res, scc = self.eval_s_sub_u32(s0, s1) - elif op == "s_subb_u32": - res, scc = self.eval_s_subb_u32(s0, s1, self.scc) - elif op == "s_mov_b32": - res, scc = s0 & MASK32, self.scc - else: - raise NotImplementedError(f"Unsupported op: {op}") - - if dst_idx is not None: - self.sgpr[dst_idx] = res - if op in ("s_add_u32", "s_addc_u32", "s_sub_u32", "s_subb_u32"): - self.scc = scc - return res, self.scc - - def run_sequence(self, instructions): - """Execute a list of instruction dictionaries sequentially.""" - last_res = 0 - for insn in instructions: - last_res, _ = self.step(insn) - return last_res - - def _resolve_val(self, operand): - if isinstance(operand, int): - return operand & MASK32 - if isinstance(operand, dict): - if operand.get("k") == "imm": - return operand["v"] & MASK32 - if operand.get("k") == "sgpr": - return self.sgpr[operand["r"]] & MASK32 - if isinstance(operand, str) and operand.startswith("s"): - return self.sgpr[int(operand[1:])] & MASK32 - raise ValueError(f"Unknown operand format: {operand}") - - def _resolve_dst(self, operand): - if isinstance(operand, dict) and operand.get("k") == "sgpr": - return operand["r"] - if isinstance(operand, str) and operand.startswith("s"): - return int(operand[1:]) - if isinstance(operand, int): - return operand - return None - - -def reference_add_64(a_lo, a_hi, b_lo, b_hi): - """Reference implementation of 64-bit integer addition.""" - a64 = ((a_hi & MASK32) << 32) | (a_lo & MASK32) - b64 = ((b_hi & MASK32) << 32) | (b_lo & MASK32) - sum64 = a64 + b64 - carry_out = 1 if sum64 >= (1 << 64) else 0 - res = sum64 & MASK64 - return res & MASK32, (res >> 32) & MASK32, carry_out - - -def reference_sub_64(a_lo, a_hi, b_lo, b_hi): - """Reference implementation of 64-bit integer subtraction.""" - a64 = ((a_hi & MASK32) << 32) | (a_lo & MASK32) - b64 = ((b_hi & MASK32) << 32) | (b_lo & MASK32) - borrow_out = 1 if a64 < b64 else 0 - diff64 = (a64 - b64) & MASK64 - return diff64 & MASK32, (diff64 >> 32) & MASK32, borrow_out - - -def spirv_lowering_model_add_sub(op, x, y, scc_in): - """Mathematical emulation of the SPIR-V lowering emitted by tools/rdna2spirv.py. - - Emulates OpIAddCarry / OpISubBorrow with OpCompositeExtract and OpBitwiseOr. - """ - x = x & MASK32 - y = y & MASK32 - sub = op.startswith("s_sub") - - if not sub: - full1 = x + y - r1 = full1 & MASK32 - c1 = 1 if full1 >= (1 << 32) else 0 - else: - full1 = x - y - r1 = full1 & MASK32 - c1 = 1 if x < y else 0 - - r, carry = r1, c1 - - if op in ("s_addc_u32", "s_subb_u32"): - cin = 1 if scc_in else 0 - if not sub: - full2 = r1 + cin - r2 = full2 & MASK32 - c2 = 1 if full2 >= (1 << 32) else 0 - else: - full2 = r1 - cin - r2 = full2 & MASK32 - c2 = 1 if r1 < cin else 0 - cc = c1 | c2 - r, carry = r2, cc - - return r, carry - - -class TestScalarAddU32(unittest.TestCase): - """Unit tests for s_add_u32 semantics and condition code updates.""" - - def setUp(self): - self.interp = ScalarALUInterpreter() - - def test_zero_addition(self): - res, scc = self.interp.eval_s_add_u32(0, 0) - self.assertEqual(res, 0) - self.assertEqual(scc, 0) - - def test_identity_operand(self): - for val in (1, 42, 0x12345678, 0xFFFFFFFF): - with self.subTest(val=val): - res1, scc1 = self.interp.eval_s_add_u32(val, 0) - res2, scc2 = self.interp.eval_s_add_u32(0, val) - self.assertEqual(res1, val) - self.assertEqual(scc1, 0) - self.assertEqual(res2, val) - self.assertEqual(scc2, 0) - - def test_basic_addition_no_carry(self): - res, scc = self.interp.eval_s_add_u32(100, 200) - self.assertEqual(res, 300) - self.assertEqual(scc, 0) - - def test_carry_boundary_single_overflow(self): - res, scc = self.interp.eval_s_add_u32(0xFFFFFFFF, 1) - self.assertEqual(res, 0x00000000) - self.assertEqual(scc, 1) - - def test_carry_boundary_just_below_overflow(self): - res, scc = self.interp.eval_s_add_u32(0xFFFFFFFF, 0) - self.assertEqual(res, 0xFFFFFFFF) - self.assertEqual(scc, 0) - - def test_carry_boundary_high_bit_addition(self): - res, scc = self.interp.eval_s_add_u32(0x80000000, 0x80000000) - self.assertEqual(res, 0x00000000) - self.assertEqual(scc, 1) - - def test_max_inputs_carry_overflow(self): - res, scc = self.interp.eval_s_add_u32(0xFFFFFFFF, 0xFFFFFFFF) - self.assertEqual(res, 0xFFFFFFFE) - self.assertEqual(scc, 1) - - def test_commutativity(self): - pairs = [ - (0, 0), - (12345, 67890), - (0xFFFFFFFF, 2), - (0x7FFFFFFF, 0x80000001), - (0xDEADBEEF, 0xCAFEBABE), - ] - for a, b in pairs: - with self.subTest(a=a, b=b): - r1, s1 = self.interp.eval_s_add_u32(a, b) - r2, s2 = self.interp.eval_s_add_u32(b, a) - self.assertEqual(r1, r2) - self.assertEqual(s1, s2) - - def test_interpreter_step_and_state(self): - self.interp.step({"op": "s_mov_b32", "dst": "s0", "s0": 10, "s1": 0}) - self.interp.step({"op": "s_mov_b32", "dst": "s1", "s0": 25, "s1": 0}) - res, scc = self.interp.step({"op": "s_add_u32", "dst": "s2", "s0": "s0", "s1": "s1"}) - self.assertEqual(res, 35) - self.assertEqual(scc, 0) - self.assertEqual(self.interp.sgpr[2], 35) - self.assertEqual(self.interp.scc, 0) - - -class TestScalarAddcU32(unittest.TestCase): - """Unit tests for s_addc_u32 semantics and carry-in propagation.""" - - def setUp(self): - self.interp = ScalarALUInterpreter() - - def test_carry_in_zero_matches_add(self): - cases = [(0, 0), (10, 20), (0xFFFFFFFF, 1), (0xFFFFFFFF, 0xFFFFFFFF)] - for s0, s1 in cases: - with self.subTest(s0=s0, s1=s1): - r_add, s_add = self.interp.eval_s_add_u32(s0, s1) - r_addc, s_addc = self.interp.eval_s_addc_u32(s0, s1, 0) - self.assertEqual(r_add, r_addc) - self.assertEqual(s_add, s_addc) - - def test_carry_in_one_no_overflow(self): - res, scc = self.interp.eval_s_addc_u32(100, 200, 1) - self.assertEqual(res, 301) - self.assertEqual(scc, 0) - - def test_carry_in_one_first_sum_overflows(self): - res, scc = self.interp.eval_s_addc_u32(0xFFFFFFFF, 5, 1) - self.assertEqual(res, 5) - self.assertEqual(scc, 1) - - def test_carry_in_one_second_sum_overflows(self): - res, scc = self.interp.eval_s_addc_u32(0xFFFFFFFF, 0, 1) - self.assertEqual(res, 0) - self.assertEqual(scc, 1) - - def test_carry_in_one_split_overflow(self): - res, scc = self.interp.eval_s_addc_u32(0x7FFFFFFF, 0x80000000, 1) - self.assertEqual(res, 0) - self.assertEqual(scc, 1) - - def test_carry_in_all_ones(self): - res, scc = self.interp.eval_s_addc_u32(0xFFFFFFFF, 0xFFFFFFFF, 1) - self.assertEqual(res, 0xFFFFFFFF) - self.assertEqual(scc, 1) - - def test_carry_in_only_zero_operands(self): - res, scc = self.interp.eval_s_addc_u32(0, 0, 1) - self.assertEqual(res, 1) - self.assertEqual(scc, 0) - - -class TestScalarSubU32(unittest.TestCase): - """Unit tests for s_sub_u32 semantics and condition code updates.""" - - def setUp(self): - self.interp = ScalarALUInterpreter() - - def test_zero_subtraction(self): - res, scc = self.interp.eval_s_sub_u32(0, 0) - self.assertEqual(res, 0) - self.assertEqual(scc, 0) - - def test_identity_zero_subtrahend(self): - for val in (1, 42, 0x12345678, 0xFFFFFFFF): - with self.subTest(val=val): - res, scc = self.interp.eval_s_sub_u32(val, 0) - self.assertEqual(res, val) - self.assertEqual(scc, 0) - - def test_identical_operands(self): - for val in (0, 1, 0x7FFFFFFF, 0xFFFFFFFF): - with self.subTest(val=val): - res, scc = self.interp.eval_s_sub_u32(val, val) - self.assertEqual(res, 0) - self.assertEqual(scc, 0) - - def test_basic_subtraction_no_borrow(self): - res, scc = self.interp.eval_s_sub_u32(300, 100) - self.assertEqual(res, 200) - self.assertEqual(scc, 0) - - def test_borrow_boundary_zero_minus_one(self): - res, scc = self.interp.eval_s_sub_u32(0, 1) - self.assertEqual(res, 0xFFFFFFFF) - self.assertEqual(scc, 1) - - def test_borrow_underflow(self): - res, scc = self.interp.eval_s_sub_u32(10, 20) - self.assertEqual(res, 0xFFFFFFF6) - self.assertEqual(scc, 1) - - def test_max_underflow(self): - res, scc = self.interp.eval_s_sub_u32(0, 0xFFFFFFFF) - self.assertEqual(res, 1) - self.assertEqual(scc, 1) - - def test_max_min_difference(self): - res, scc = self.interp.eval_s_sub_u32(0xFFFFFFFF, 1) - self.assertEqual(res, 0xFFFFFFFE) - self.assertEqual(scc, 0) - - -class TestScalarSubbU32(unittest.TestCase): - """Unit tests for s_subb_u32 semantics and borrow-in propagation.""" - - def setUp(self): - self.interp = ScalarALUInterpreter() - - def test_borrow_in_zero_matches_sub(self): - cases = [(0, 0), (30, 10), (0, 1), (10, 20), (0, 0xFFFFFFFF)] - for s0, s1 in cases: - with self.subTest(s0=s0, s1=s1): - r_sub, s_sub = self.interp.eval_s_sub_u32(s0, s1) - r_subb, s_subb = self.interp.eval_s_subb_u32(s0, s1, 0) - self.assertEqual(r_sub, r_subb) - self.assertEqual(s_sub, s_subb) - - def test_borrow_in_one_no_underflow(self): - res, scc = self.interp.eval_s_subb_u32(50, 20, 1) - self.assertEqual(res, 29) - self.assertEqual(scc, 0) - - def test_borrow_in_one_exact_zero_result(self): - res, scc = self.interp.eval_s_subb_u32(10, 9, 1) - self.assertEqual(res, 0) - self.assertEqual(scc, 0) - - def test_borrow_in_one_first_sub_borrows(self): - res, scc = self.interp.eval_s_subb_u32(0, 5, 1) - self.assertEqual(res, 0xFFFFFFFA) - self.assertEqual(scc, 1) - - def test_borrow_in_one_second_sub_borrows(self): - res, scc = self.interp.eval_s_subb_u32(5, 5, 1) - self.assertEqual(res, 0xFFFFFFFF) - self.assertEqual(scc, 1) - - def test_borrow_in_one_zero_minus_zero(self): - res, scc = self.interp.eval_s_subb_u32(0, 0, 1) - self.assertEqual(res, 0xFFFFFFFF) - self.assertEqual(scc, 1) - - def test_borrow_in_all_ones(self): - res, scc = self.interp.eval_s_subb_u32(0xFFFFFFFF, 0xFFFFFFFF, 1) - self.assertEqual(res, 0xFFFFFFFF) - self.assertEqual(scc, 1) - - -class Test64BitScalarArithmetic(unittest.TestCase): - """Semantic tests for chained 64-bit scalar addition and subtraction with carry/borrow.""" - - def setUp(self): - self.interp = ScalarALUInterpreter() - - def run_add64(self, a_lo, a_hi, b_lo, b_hi): - seq = [ - {"op": "s_mov_b32", "dst": "s0", "s0": a_lo, "s1": 0}, - {"op": "s_mov_b32", "dst": "s1", "s0": a_hi, "s1": 0}, - {"op": "s_mov_b32", "dst": "s2", "s0": b_lo, "s1": 0}, - {"op": "s_mov_b32", "dst": "s3", "s0": b_hi, "s1": 0}, - {"op": "s_add_u32", "dst": "s4", "s0": "s0", "s1": "s2"}, - {"op": "s_addc_u32", "dst": "s5", "s0": "s1", "s1": "s3"}, - ] - self.interp.run_sequence(seq) - return self.interp.sgpr[4], self.interp.sgpr[5], self.interp.scc - - def run_sub64(self, a_lo, a_hi, b_lo, b_hi): - seq = [ - {"op": "s_mov_b32", "dst": "s0", "s0": a_lo, "s1": 0}, - {"op": "s_mov_b32", "dst": "s1", "s0": a_hi, "s1": 0}, - {"op": "s_mov_b32", "dst": "s2", "s0": b_lo, "s1": 0}, - {"op": "s_mov_b32", "dst": "s3", "s0": b_hi, "s1": 0}, - {"op": "s_sub_u32", "dst": "s4", "s0": "s0", "s1": "s2"}, - {"op": "s_subb_u32", "dst": "s5", "s0": "s1", "s1": "s3"}, - ] - self.interp.run_sequence(seq) - return self.interp.sgpr[4], self.interp.sgpr[5], self.interp.scc - - def test_add64_without_carry(self): - r_lo, r_hi, scc = self.run_add64(0x00000002, 0x00000001, 0x00000004, 0x00000003) - self.assertEqual(r_lo, 0x00000006) - self.assertEqual(r_hi, 0x00000004) - self.assertEqual(scc, 0) - - def test_add64_low_to_high_carry_propagation(self): - r_lo, r_hi, scc = self.run_add64(0xFFFFFFFF, 0x00000001, 0x00000001, 0x00000002) - self.assertEqual(r_lo, 0x00000000) - self.assertEqual(r_hi, 0x00000004) - self.assertEqual(scc, 0) - - def test_add64_full_chain_overflow(self): - r_lo, r_hi, scc = self.run_add64(0xFFFFFFFF, 0xFFFFFFFF, 0x00000001, 0x00000000) - self.assertEqual(r_lo, 0x00000000) - self.assertEqual(r_hi, 0x00000000) - self.assertEqual(scc, 1) - - def test_add64_max_unsigned(self): - r_lo, r_hi, scc = self.run_add64(0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF) - self.assertEqual(r_lo, 0xFFFFFFFE) - self.assertEqual(r_hi, 0xFFFFFFFF) - self.assertEqual(scc, 1) - - def test_sub64_without_borrow(self): - r_lo, r_hi, scc = self.run_sub64(0x00000005, 0x00000008, 0x00000002, 0x00000003) - self.assertEqual(r_lo, 0x00000003) - self.assertEqual(r_hi, 0x00000005) - self.assertEqual(scc, 0) - - def test_sub64_low_to_high_borrow_propagation(self): - r_lo, r_hi, scc = self.run_sub64(0x00000000, 0x00000005, 0x00000001, 0x00000002) - self.assertEqual(r_lo, 0xFFFFFFFF) - self.assertEqual(r_hi, 0x00000002) - self.assertEqual(scc, 0) - - def test_sub64_full_chain_underflow(self): - r_lo, r_hi, scc = self.run_sub64(0x00000000, 0x00000000, 0x00000001, 0x00000000) - self.assertEqual(r_lo, 0xFFFFFFFF) - self.assertEqual(r_hi, 0xFFFFFFFF) - self.assertEqual(scc, 1) - - def test_add64_sub64_roundtrip(self): - test_vectors = [ - (0x12345678, 0x9ABCDEF0, 0x0FEDCBA9, 0x87654321), - (0xFFFFFFFF, 0x00000000, 0x00000001, 0x00000000), - (0x00000000, 0x80000000, 0x00000000, 0x40000000), - (0xCAFEBABE, 0xDEADBEEF, 0x11111111, 0x22222222), - ] - for a_lo, a_hi, b_lo, b_hi in test_vectors: - with self.subTest(a_lo=a_lo, a_hi=a_hi, b_lo=b_lo, b_hi=b_hi): - sum_lo, sum_hi, _ = self.run_add64(a_lo, a_hi, b_lo, b_hi) - res_lo, res_hi, _ = self.run_sub64(sum_lo, sum_hi, b_lo, b_hi) - self.assertEqual(res_lo, a_lo) - self.assertEqual(res_hi, a_hi) - - def test_deterministic_pseudorandom_64bit_sweep(self): - rng = random.Random(42) - for i in range(250): - a_lo = rng.getrandbits(32) - a_hi = rng.getrandbits(32) - b_lo = rng.getrandbits(32) - b_hi = rng.getrandbits(32) - - exp_add_lo, exp_add_hi, exp_add_c = reference_add_64(a_lo, a_hi, b_lo, b_hi) - got_add_lo, got_add_hi, got_add_c = self.run_add64(a_lo, a_hi, b_lo, b_hi) - self.assertEqual(got_add_lo, exp_add_lo, f"Add iter {i} lo mismatch") - self.assertEqual(got_add_hi, exp_add_hi, f"Add iter {i} hi mismatch") - self.assertEqual(got_add_c, exp_add_c, f"Add iter {i} carry mismatch") - - exp_sub_lo, exp_sub_hi, exp_sub_b = reference_sub_64(a_lo, a_hi, b_lo, b_hi) - got_sub_lo, got_sub_hi, got_sub_b = self.run_sub64(a_lo, a_hi, b_lo, b_hi) - self.assertEqual(got_sub_lo, exp_sub_lo, f"Sub iter {i} lo mismatch") - self.assertEqual(got_sub_hi, exp_sub_hi, f"Sub iter {i} hi mismatch") - self.assertEqual(got_sub_b, exp_sub_b, f"Sub iter {i} borrow mismatch") - - -class TestRdna2SpirvLoweringSemantics(unittest.TestCase): - """Tests cross-checking RDNA2 scalar ALU semantics against the SPIR-V lowering emitted by rdna2spirv.py.""" - - def test_gen_spirv_emission_add_u32(self): - gen = rdna2spirv.Gen("ps") - insn = { - "op": "s_add_u32", - "args": [{"k": "sgpr", "r": 4}, {"k": "imm", "v": 0xFFFFFFFF}, {"k": "imm", "v": 1}], - "mods": [], - } - gen._insn(insn) - body = "\n".join(gen.body) - self.assertIn("OpIAddCarry %umul", body) - self.assertIn("OpCompositeExtract %uint", body) - self.assertIn("OpStore %scc", body) - - def test_gen_spirv_emission_addc_u32(self): - gen = rdna2spirv.Gen("ps") - insn = { - "op": "s_addc_u32", - "args": [{"k": "sgpr", "r": 5}, {"k": "imm", "v": 10}, {"k": "imm", "v": 20}], - "mods": [], - } - gen._insn(insn) - body = "\n".join(gen.body) - self.assertEqual(body.count("OpIAddCarry %umul"), 2) - self.assertIn("OpLoad %uint %scc", body) - self.assertIn("OpBitwiseOr %uint", body) - - def test_gen_spirv_emission_sub_u32(self): - gen = rdna2spirv.Gen("ps") - insn = { - "op": "s_sub_u32", - "args": [{"k": "sgpr", "r": 6}, {"k": "imm", "v": 50}, {"k": "imm", "v": 30}], - "mods": [], - } - gen._insn(insn) - body = "\n".join(gen.body) - self.assertIn("OpISubBorrow %umul", body) - self.assertIn("OpCompositeExtract %uint", body) - self.assertIn("OpStore %scc", body) - - def test_gen_spirv_emission_subb_u32(self): - gen = rdna2spirv.Gen("ps") - insn = { - "op": "s_subb_u32", - "args": [{"k": "sgpr", "r": 7}, {"k": "imm", "v": 50}, {"k": "imm", "v": 30}], - "mods": [], - } - gen._insn(insn) - body = "\n".join(gen.body) - self.assertEqual(body.count("OpISubBorrow %umul"), 2) - self.assertIn("OpLoad %uint %scc", body) - self.assertIn("OpBitwiseOr %uint", body) - - def test_spirv_model_equivalence_sweep(self): - rng = random.Random(1337) - for _ in range(200): - x = rng.getrandbits(32) - y = rng.getrandbits(32) - cin = rng.choice([0, 1]) - - # s_add_u32 - isa_res, isa_scc = ScalarALUInterpreter.eval_s_add_u32(x, y) - spv_res, spv_scc = spirv_lowering_model_add_sub("s_add_u32", x, y, 0) - self.assertEqual(isa_res, spv_res) - self.assertEqual(isa_scc, spv_scc) - - # s_addc_u32 - isa_res, isa_scc = ScalarALUInterpreter.eval_s_addc_u32(x, y, cin) - spv_res, spv_scc = spirv_lowering_model_add_sub("s_addc_u32", x, y, cin) - self.assertEqual(isa_res, spv_res) - self.assertEqual(isa_scc, spv_scc) - - # s_sub_u32 - isa_res, isa_scc = ScalarALUInterpreter.eval_s_sub_u32(x, y) - spv_res, spv_scc = spirv_lowering_model_add_sub("s_sub_u32", x, y, 0) - self.assertEqual(isa_res, spv_res) - self.assertEqual(isa_scc, spv_scc) - - # s_subb_u32 - isa_res, isa_scc = ScalarALUInterpreter.eval_s_subb_u32(x, y, cin) - spv_res, spv_scc = spirv_lowering_model_add_sub("s_subb_u32", x, y, cin) - self.assertEqual(isa_res, spv_res) - self.assertEqual(isa_scc, spv_scc) - - -class TestAddressArithmeticUseCases(unittest.TestCase): - """Simulates real-world 64-bit scalar address arithmetic patterns seen in shaders.""" - - def setUp(self): - self.interp = ScalarALUInterpreter() - - def test_s_getpc_b64_forward_displacement(self): - pc_base = 0x00007FF8_10000000 - offset = 0x00000000_00002A40 - - pc_lo = pc_base & MASK32 - pc_hi = (pc_base >> 32) & MASK32 - off_lo = offset & MASK32 - off_hi = (offset >> 32) & MASK32 - - self.interp.step({"op": "s_mov_b32", "dst": "s4", "s0": pc_lo, "s1": 0}) - self.interp.step({"op": "s_mov_b32", "dst": "s5", "s0": pc_hi, "s1": 0}) - self.interp.step({"op": "s_add_u32", "dst": "s4", "s0": "s4", "s1": off_lo}) - self.interp.step({"op": "s_addc_u32", "dst": "s5", "s0": "s5", "s1": off_hi}) - - final_addr = ((self.interp.sgpr[5] & MASK32) << 32) | (self.interp.sgpr[4] & MASK32) - self.assertEqual(final_addr, pc_base + offset) - - def test_s_getpc_b64_forward_displacement_spanning_4gb_boundary(self): - pc_base = 0x00007FF8_FFFF8000 - offset = 0x00000000_00010000 - - pc_lo = pc_base & MASK32 - pc_hi = (pc_base >> 32) & MASK32 - off_lo = offset & MASK32 - off_hi = (offset >> 32) & MASK32 - - self.interp.step({"op": "s_mov_b32", "dst": "s4", "s0": pc_lo, "s1": 0}) - self.interp.step({"op": "s_mov_b32", "dst": "s5", "s0": pc_hi, "s1": 0}) - self.interp.step({"op": "s_add_u32", "dst": "s4", "s0": "s4", "s1": off_lo}) - self.interp.step({"op": "s_addc_u32", "dst": "s5", "s0": "s5", "s1": off_hi}) - - final_addr = ((self.interp.sgpr[5] & MASK32) << 32) | (self.interp.sgpr[4] & MASK32) - self.assertEqual(final_addr, pc_base + offset) - - def test_backward_loop_edge_displacement(self): - pc_base = 0x00007FF8_00001000 - offset = 0x00000000_00000500 - - pc_lo = pc_base & MASK32 - pc_hi = (pc_base >> 32) & MASK32 - off_lo = offset & MASK32 - off_hi = (offset >> 32) & MASK32 - - self.interp.step({"op": "s_mov_b32", "dst": "s4", "s0": pc_lo, "s1": 0}) - self.interp.step({"op": "s_mov_b32", "dst": "s5", "s0": pc_hi, "s1": 0}) - self.interp.step({"op": "s_sub_u32", "dst": "s4", "s0": "s4", "s1": off_lo}) - self.interp.step({"op": "s_subb_u32", "dst": "s5", "s0": "s5", "s1": off_hi}) - - final_addr = ((self.interp.sgpr[5] & MASK32) << 32) | (self.interp.sgpr[4] & MASK32) - self.assertEqual(final_addr, pc_base - offset) - - def test_backward_loop_edge_spanning_4gb_boundary(self): - pc_base = 0x00007FF8_00002000 - offset = 0x00000000_00008000 - - pc_lo = pc_base & MASK32 - pc_hi = (pc_base >> 32) & MASK32 - off_lo = offset & MASK32 - off_hi = (offset >> 32) & MASK32 - - self.interp.step({"op": "s_mov_b32", "dst": "s4", "s0": pc_lo, "s1": 0}) - self.interp.step({"op": "s_mov_b32", "dst": "s5", "s0": pc_hi, "s1": 0}) - self.interp.step({"op": "s_sub_u32", "dst": "s4", "s0": "s4", "s1": off_lo}) - self.interp.step({"op": "s_subb_u32", "dst": "s5", "s0": "s5", "s1": off_hi}) - - final_addr = ((self.interp.sgpr[5] & MASK32) << 32) | (self.interp.sgpr[4] & MASK32) - self.assertEqual(final_addr, pc_base - offset) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_scalar_alu_and_smem_folding.py b/tests/semantic/test_scalar_alu_and_smem_folding.py deleted file mode 100644 index f17476663..000000000 --- a/tests/semantic/test_scalar_alu_and_smem_folding.py +++ /dev/null @@ -1,220 +0,0 @@ -from __future__ import annotations - -"""Regression and semantic tests for scalar ALU and s_buffer_load constant folding in the translator. - -Verifies that: -- Constant scalar ALU operations (s_and_b32, s_or_b32, s_xor_b32, s_not_b32, s_lshl_b32, s_lshr_b32, s_mul_i32) - fold at translate time without emitting runtime SPIR-V instructions. -- s_buffer_load with known descriptor limits folds limit calculations at translate time, eliminating - OpBitFieldUExtract, OpIMul, OpIEqual, and OpSelect. -- In-bounds s_buffer_load dwords emit direct straight-line OpLoad without OpSelectionMerge, OpBranchConditional, or OpPhi. -- Out-of-bounds s_buffer_load dwords emit constant zero without memory load or branch. -- Constant SGPR offsets in scalar loads fold directly into the 64-bit address calculation. -""" -import os -import struct -import sys -import tempfile -import unittest -import warnings - -HERE = os.path.dirname(os.path.abspath(__file__)) -ROOT = os.path.dirname(os.path.dirname(HERE)) -TOOLS_DIR = os.environ.get("LEONIDA_TOOLS_DIR") or os.path.join(ROOT, "tools") - -sys.dont_write_bytecode = True -if TOOLS_DIR not in sys.path: - sys.path.insert(0, TOOLS_DIR) -if HERE not in sys.path: - sys.path.insert(0, HERE) - -import rdna2spirv # noqa: E402 -from shader_ir import parse_line # noqa: E402 -import spirv_mini_interp as si # noqa: E402 - -STUB_DXBC = b"DXBC" + bytes(24) + struct.pack(" str: - body = "\n".join("\t" + line for line in lines) - asm = f"; scalar_fold_test\n{body}\n\texp mrt0 v0, v0, v0, v0 done vm\n\ts_endpgm\n" - with tempfile.TemporaryDirectory() as tmp: - d_dir = os.path.join(tmp, "disasm") - os.mkdir(d_dir) - s_path = os.path.join(d_dir, "ps_scalar.s") - with open(s_path, "w", encoding="utf-8") as f: - f.write(asm) - with open(os.path.join(tmp, "ps_scalar.dxbc"), "wb") as f: - f.write(STUB_DXBC) - with warnings.catch_warnings(): - warnings.simplefilter("ignore", ResourceWarning) - return rdna2spirv.translate(s_path) - - def test_s_and_b32_and_s_or_b32_constant_folding(self): - # Bitwise s_and_b32 / s_or_b32 fold constants without runtime bitwise instructions - lines = [ - "s_and_b32 s4, 0xFF00, 0x0FF0", - "v_mov_b32 v0, s4", - ] - spv = self.translate_lines(lines) - self.assertNotIn("OpBitwiseAnd %uint", spv) - res = si.run_fragment(spv)["%out_mrt0"][0] - self.assertEqual(res, 0x0F00) - - lines_or = [ - "s_or_b32 s4, 0xF0, 0x0F", - "v_mov_b32 v0, s4", - ] - spv_or = self.translate_lines(lines_or) - self.assertNotIn("OpBitwiseOr %uint", spv_or) - res_or = si.run_fragment(spv_or)["%out_mrt0"][0] - self.assertEqual(res_or, 0xFF) - - def test_s_xor_b32_and_s_not_b32_constant_folding(self): - # Bitwise s_xor_b32 and s_not_b32 fold constants - lines_xor = [ - "s_xor_b32 s4, 0xAAAA5555, 0x5555AAAA", - "v_mov_b32 v0, s4", - ] - spv_xor = self.translate_lines(lines_xor) - self.assertNotIn("OpBitwiseXor %uint", spv_xor) - res_xor = si.run_fragment(spv_xor)["%out_mrt0"][0] - self.assertEqual(res_xor, 0xFFFFFFFF) - - lines_not = [ - "s_not_b32 s4, 0", - "v_mov_b32 v0, s4", - ] - spv_not = self.translate_lines(lines_not) - self.assertNotIn("OpNot %uint", spv_not) - res_not = si.run_fragment(spv_not)["%out_mrt0"][0] - self.assertEqual(res_not, 0xFFFFFFFF) - - def test_s_lshl_b32_s_lshr_b32_s_mul_i32_folding(self): - # Shifts and multiply fold constants - lines_shl = [ - "s_lshl_b32 s4, 3, 4", # 3 << 4 = 48 - "v_mov_b32 v0, s4", - ] - spv_shl = self.translate_lines(lines_shl) - self.assertNotIn("OpShiftLeftLogical %uint", spv_shl) - res_shl = si.run_fragment(spv_shl)["%out_mrt0"][0] - self.assertEqual(res_shl, 48) - - lines_mul = [ - "s_mul_i32 s4, 6, 7", - "v_mov_b32 v0, s4", - ] - spv_mul = self.translate_lines(lines_mul) - self.assertNotIn("OpIMul %uint", spv_mul) - res_mul = si.run_fragment(spv_mul)["%out_mrt0"][0] - self.assertEqual(res_mul, 42) - - lines_shr = [ - "s_lshr_b32 s4, 96, 3", # 96 >> 3 = 12 - "v_mov_b32 v0, s4", - ] - spv_shr = self.translate_lines(lines_shr) - self.assertNotIn("OpShiftRightLogical %uint", spv_shr) - res_shr = si.run_fragment(spv_shr)["%out_mrt0"][0] - self.assertEqual(res_shr, 12) - - def test_s_buffer_load_in_bounds_eliminates_branch_diamond(self): - # When V# limits and offset are constants with offset in bounds: - # eliminates limit setup and conditional branch diamond. - g = rdna2spirv.Gen("ps") - # Load literal V# into s[4:7]: - # s4: base lo, s5: base hi (0) + stride 4 in bits 16..29 (0x00040000) - # s6: num_records = 256 (limit = 256 * 4 = 1024 bytes) - # s7: word3 - g.sgpr_imm[4] = 0x1000 - g.sgpr_imm[5] = 0x00040000 - g.sgpr_imm[6] = 256 - g.sgpr_imm[7] = 0x31000FAC - - ins = parse_line("s_buffer_load_dword s0, s[4:7], 0x10") - g.scalar_load(ins["op"], ins["args"], ins["mods"]) - text = "\n".join(g.body) - - # No dynamic limit calculation instructions - self.assertNotIn("OpBitFieldUExtract %uint", text) - self.assertNotIn("OpIMul %ulong", text) - self.assertNotIn("OpSelect %ulong", text) - - # In bounds (0x10 + 4 = 20 <= 1024): no branch or phi - self.assertNotIn("OpBranchConditional", text) - self.assertNotIn("OpSelectionMerge", text) - self.assertNotIn("OpPhi", text) - - # Emits direct aligned load - self.assertIn("OpAccessChain %_ptr_PSB_uint", text) - self.assertIn("OpLoad %uint", text) - - def test_s_buffer_load_out_of_bounds_emits_constant_zero(self): - # When V# limits and offset are constants with offset out of bounds: - # emits constant 0 without memory load or branches. - g = rdna2spirv.Gen("ps") - g.sgpr_imm[4] = 0x1000 - g.sgpr_imm[5] = 0x00040000 - g.sgpr_imm[6] = 16 # limit = 16 * 4 = 64 bytes - g.sgpr_imm[7] = 0x31000FAC - - ins = parse_line("s_buffer_load_dword s0, s[4:7], 0x80") # offset 128 > limit 64 - g.scalar_load(ins["op"], ins["args"], ins["mods"]) - text = "\n".join(g.body) - - # No branch or PSB memory load emitted for out of bounds - self.assertNotIn("OpBranchConditional", text) - self.assertNotIn("OpSelectionMerge", text) - self.assertNotIn("OpPhi", text) - self.assertNotIn("OpAccessChain %_ptr_PSB_uint", text) - self.assertNotIn("Aligned 4", text) - - # Directly stores %c0 to sgpr 0 - self.assertTrue(any(ln.strip().startswith("OpStore %t") and ln.strip().endswith(g.cu(0)) for ln in g.body)) - - def test_s_buffer_load_sgpr_offset_folded_from_sgpr_imm(self): - # When offset is passed via SGPR holding a known literal: - # folded into constant offset without runtime OpBitwiseAnd / OpUConvert on the offset register. - g = rdna2spirv.Gen("ps") - g.sgpr_imm[2] = 0x20 # s2 = 32 - ins = parse_line("s_load_dword s0, s[4:5], s2") - g.scalar_load(ins["op"], ins["args"], ins["mods"]) - text = "\n".join(g.body) - - # The offset is folded into constant ulong %cl20 - self.assertIn("%cl20", text) - # Only base lo is masked with %cfffffffc; offset s2 is not dynamically masked - self.assertEqual(text.count("%cfffffffc"), 1) - - def test_s_buffer_load_constant_negative_sgpr_offset_does_not_wrap(self): - # SHADER-328: s8 = -4 with offset:20 is 0xFFFFFFFC + 20 in 64 bits (RDNA2 reads 0, measured in #1686), not - # 16 after a 32-bit wrap. The constant must give what the run-time path gives: out of bounds, 0. - g = rdna2spirv.Gen("ps") - g.sgpr_imm.update({0: 0x1000, 1: 0, 2: 64, 3: 0x31000FAC, 8: 0xFFFFFFFC}) # raw V#, limit 64 bytes - ins = parse_line("s_buffer_load_dword s10, s[0:3], s8 offset:20") - g.scalar_load(ins["op"], ins["args"], ins["mods"]) - text = "\n".join(g.body) - self.assertNotIn("OpAccessChain %_ptr_PSB_uint", text) # no read: the dword is out of bounds - self.assertTrue(any(ln.strip().startswith("OpStore %t") and ln.strip().endswith(g.cu(0)) for ln in g.body)) - - # The same offsets inside the limit still read memory. - g = rdna2spirv.Gen("ps") - g.sgpr_imm.update({0: 0x1000, 1: 0, 2: 64, 3: 0x31000FAC, 8: 4}) - ins = parse_line("s_buffer_load_dword s10, s[0:3], s8 offset:20") - g.scalar_load(ins["op"], ins["args"], ins["mods"]) - self.assertIn("OpAccessChain %_ptr_PSB_uint", "\n".join(g.body)) - - def test_s_load_constant_sgpr_offset_is_not_sign_extended(self): - # The run-time path adds zext(sOFF & ~3) to the 21-bit immediate; a constant sOFF of 2^20 must not pass - # through the immediate's 21-bit sign extension (it would become -2^20). - g = rdna2spirv.Gen("ps") - g.sgpr_imm[2] = 0x100000 - ins = parse_line("s_load_dword s0, s[4:5], s2 offset:0x10") - g.scalar_load(ins["op"], ins["args"], ins["mods"]) - self.assertIn("%cl100010", "\n".join(g.body)) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_scalar_alu_bitfield.py b/tests/semantic/test_scalar_alu_bitfield.py deleted file mode 100644 index 83f0bb7f7..000000000 --- a/tests/semantic/test_scalar_alu_bitfield.py +++ /dev/null @@ -1,719 +0,0 @@ -"""Semantic interpreter tests for RDNA2 scalar bitfield operations. - -Instructions tested: - - s_bfe_u32 D, S0, S1: Unsigned scalar bitfield extract. - - s_bfe_i32 D, S0, S1: Signed scalar bitfield extract (sign-extended). - - s_bfm_b32 D, S0, S1: Scalar bitfield mask generation. - -RDNA2 ISA rules: - - s_bfe_u32 / s_bfe_i32: - * S0 is the source dword (SGPR, immediate, or constant). - * S1 is the packed control word: - offset = S1[4:0] (bits [4:0], 0..31). - width = S1[22:16] (bits [22:16], 0..127). - Other bits of S1 are ignored. - * Width limit / clamping: SPIR-V specifies that offset + count <= 32. In RDNA2 - hardware and LLVM constantFoldBFE, an extract running past bit 31 is clamped - such that the effective width is min(width, 32 - offset). - * If width == 0 or offset >= 32: result is 0. - * s_bfe_u32 zero-extends the extracted field into D. - * s_bfe_i32 sign-extends the extracted field from bit (effective_width - 1). - * Condition Code (SCC): SCC = 1 if D != 0 else 0 (both signed and unsigned). - - s_bfm_b32: - * S0 is the width operand (only low 5 bits S0[4:0] are used). - * S1 is the offset operand (only low 5 bits S1[4:0] are used). - * D = ((1 << (S0 & 31)) - 1) << (S1 & 31). - * If (S0 & 31) == 0, result is 0. - * s_bfm_b32 does NOT alter the SCC flag. - - Scalar bitfield insert composition: - * Scalar bitfield insert is composed via s_bfm_b32 and bitwise selection: - mask = s_bfm_b32(width, offset) - result = (base & ~mask) | ((insert << offset) & mask) - * Matches SPIR-V OpBitFieldInsert semantics when offset + count <= 32. - -Verification approach: - 1. Pure Python reference models verifying exact RDNA2 bitfield math. - 2. Deterministic ScalarAluInterpreter tracking SGPR state and SCC. - 3. rdna2spirv translation emission checks via rdna2spirv.Gen. - 4. spirv_mini_interp execution cross-checking lowered SPIR-V modules. - 5. Negative controls ensuring test sensitivity to subtle bitfield errors. -""" -from __future__ import annotations - -import os -import sys -import unittest - -HERE = os.path.dirname(os.path.abspath(__file__)) -ROOT = os.path.dirname(os.path.dirname(HERE)) -TOOLS_DIR = os.environ.get("LEONIDA_TOOLS_DIR") or os.path.join(ROOT, "tools") - -if ROOT not in sys.path: - sys.path.insert(0, ROOT) -if TOOLS_DIR not in sys.path: - sys.path.insert(0, TOOLS_DIR) - -if HERE not in sys.path: - sys.path.insert(0, HERE) - -import rdna2spirv -import spirv_mini_interp as si - -MASK32 = 0xFFFFFFFF - - -def pack_bfe_ctl(offset: int, width: int) -> int: - """Pack bitfield offset [4:0] and width [22:16] into an RDNA scalar control word.""" - return ((width & 0x7F) << 16) | (offset & 0x1F) - - -def unpack_bfe_ctl(ctl: int) -> tuple[int, int]: - """Unpack offset [4:0] and width [22:16] from an RDNA scalar control word.""" - offset = ctl & 0x1F - width = (ctl >> 16) & 0x7F - return offset, width - - -def ref_s_bfe_u32(src: int, ctl: int) -> tuple[int, int]: - """Reference implementation of RDNA2 s_bfe_u32. - - Returns: - (result, scc): 32-bit unsigned extracted field and SCC flag (1 if res != 0 else 0). - """ - src &= MASK32 - offset, width = unpack_bfe_ctl(ctl) - if width == 0 or offset >= 32: - return 0, 0 - eff_width = min(width, 32 - offset) - mask = (1 << eff_width) - 1 - res = (src >> offset) & mask - scc = 1 if res != 0 else 0 - return res & MASK32, scc - - -def ref_s_bfe_i32(src: int, ctl: int) -> tuple[int, int]: - """Reference implementation of RDNA2 s_bfe_i32. - - Returns: - (result, scc): 32-bit sign-extended extracted field and SCC flag (1 if res != 0 else 0). - """ - src &= MASK32 - offset, width = unpack_bfe_ctl(ctl) - if width == 0 or offset >= 32: - return 0, 0 - eff_width = min(width, 32 - offset) - mask = (1 << eff_width) - 1 - val = (src >> offset) & mask - sign_bit = 1 << (eff_width - 1) - if val & sign_bit: - val -= (1 << eff_width) - res = val & MASK32 - scc = 1 if res != 0 else 0 - return res, scc - - -def ref_s_bfm_b32(width: int, offset: int) -> int: - """Reference implementation of RDNA2 s_bfm_b32. - - Mask generator: ((1 << (width & 31)) - 1) << (offset & 31). - Note: Does NOT alter SCC. - """ - w = width & 31 - o = offset & 31 - if w == 0: - return 0 - mask = ((1 << w) - 1) & MASK32 - return (mask << o) & MASK32 - - -def ref_bitfield_insert(base: int, insert: int, offset: int, count: int) -> int: - """Reference implementation of bitfield insert matching SPIR-V OpBitFieldInsert.""" - base &= MASK32 - insert &= MASK32 - if count == 0: - return base - mk = (((1 << count) - 1) << offset) & MASK32 - return ((base & ~mk) | ((insert << offset) & mk)) & MASK32 - - -class ScalarAluInterpreter: - """Deterministic semantic interpreter for RDNA2 scalar ALU bitfield instructions. - - Models SGPR file (106 registers) and 1-bit Scalar Condition Code (SCC). - """ - - def __init__(self, num_sgprs: int = 106) -> None: - self.num_sgprs = num_sgprs - self.sgpr = [0] * num_sgprs - self.scc = 0 - - def reset(self) -> None: - self.sgpr = [0] * self.num_sgprs - self.scc = 0 - - def get_sgpr(self, r: int) -> int: - return self.sgpr[r] & MASK32 - - def set_sgpr(self, r: int, val: int) -> None: - self.sgpr[r] = val & MASK32 - - def resolve_src(self, opnd: int | dict | str) -> int: - """Resolve scalar operand to 32-bit unsigned value.""" - if isinstance(opnd, int): - return opnd & MASK32 - if isinstance(opnd, dict): - k = opnd.get("k") - if k == "imm": - return opnd["v"] & MASK32 - if k == "sgpr": - return self.get_sgpr(opnd["r"]) - raise ValueError(f"Unknown operand dict: {opnd}") - if isinstance(opnd, str): - if opnd.startswith("s"): - return self.get_sgpr(int(opnd[1:])) - return int(opnd, 0) & MASK32 - raise TypeError(f"Unsupported operand type: {type(opnd)}") - - def resolve_dst(self, dst: int | dict | str) -> int: - """Resolve scalar destination to SGPR register index.""" - if isinstance(dst, int): - return dst - if isinstance(dst, dict) and dst.get("k") == "sgpr": - return dst["r"] - if isinstance(dst, str) and dst.startswith("s"): - return int(dst[1:]) - raise ValueError(f"Unsupported destination operand: {dst}") - - def step(self, op: str, dst: int | dict | str, s0: int | dict | str, s1: int | dict | str) -> int: - """Execute a single scalar ALU instruction.""" - v0 = self.resolve_src(s0) - v1 = self.resolve_src(s1) - d_idx = self.resolve_dst(dst) - - if op == "s_bfe_u32": - res, scc = ref_s_bfe_u32(v0, v1) - self.set_sgpr(d_idx, res) - self.scc = scc - return res - if op == "s_bfe_i32": - res, scc = ref_s_bfe_i32(v0, v1) - self.set_sgpr(d_idx, res) - self.scc = scc - return res - if op == "s_bfm_b32": - res = ref_s_bfm_b32(v0, v1) - self.set_sgpr(d_idx, res) - # RDNA2 s_bfm_b32 does not update SCC - return res - if op == "s_mov_b32": - self.set_sgpr(d_idx, v0) - return v0 - if op == "s_and_b32": - res = (v0 & v1) & MASK32 - self.set_sgpr(d_idx, res) - self.scc = 1 if res != 0 else 0 - return res - if op == "s_or_b32": - res = (v0 | v1) & MASK32 - self.set_sgpr(d_idx, res) - self.scc = 1 if res != 0 else 0 - return res - if op == "s_lshl_b32": - sh = v1 & 31 - res = (v0 << sh) & MASK32 - self.set_sgpr(d_idx, res) - self.scc = 1 if res != 0 else 0 - return res - raise NotImplementedError(f"Instruction {op} not implemented in interpreter") - - def run_sequence(self, instructions: list[tuple[str, int | dict | str, int | dict | str, int | dict | str]]) -> int: - """Run a sequence of instructions (op, dst, s0, s1).""" - last_res = 0 - for op, dst, s0, s1 in instructions: - last_res = self.step(op, dst, s0, s1) - return last_res - - -class ReferenceModelTests(unittest.TestCase): - """Validation of pure-Python bitfield reference models.""" - - def test_pack_unpack_ctl(self) -> None: - ctl = pack_bfe_ctl(5, 12) - off, wid = unpack_bfe_ctl(ctl) - self.assertEqual(off, 5) - self.assertEqual(wid, 12) - self.assertEqual(ctl, (12 << 16) | 5) - - # Upper bits [15:5] and [31:23] ignored on unpack - dirty = ctl | 0xFF80FFE0 - off_dirty, wid_dirty = unpack_bfe_ctl(dirty) - self.assertEqual(off_dirty, 5) - self.assertEqual(wid_dirty, 12) - - def test_ref_s_bfe_u32_basic(self) -> None: - # Extract 8 bits from offset 8 - ctl = pack_bfe_ctl(8, 8) - res, scc = ref_s_bfe_u32(0x12345678, ctl) - self.assertEqual(res, 0x56) - self.assertEqual(scc, 1) - - def test_ref_s_bfe_u32_zero_width(self) -> None: - ctl = pack_bfe_ctl(8, 0) - res, scc = ref_s_bfe_u32(0xFFFFFFFF, ctl) - self.assertEqual(res, 0) - self.assertEqual(scc, 0) - - def test_ref_s_bfe_u32_full_width(self) -> None: - ctl = pack_bfe_ctl(0, 32) - res, scc = ref_s_bfe_u32(0xDEADBEEF, ctl) - self.assertEqual(res, 0xDEADBEEF) - self.assertEqual(scc, 1) - - def test_ref_s_bfe_u32_clamping_past_bit_31(self) -> None: - # Offset 28, width 8 runs to bit 36: effective width is min(8, 4) = 4 bits - ctl = pack_bfe_ctl(28, 8) - res, scc = ref_s_bfe_u32(0xF0000000, ctl) - self.assertEqual(res, 0xF) - self.assertEqual(scc, 1) - - # Width up to 127 - ctl127 = pack_bfe_ctl(16, 127) - res127, scc127 = ref_s_bfe_u32(0xABCD0000, ctl127) - self.assertEqual(res127, 0xABCD) - self.assertEqual(scc127, 1) - - def test_ref_s_bfe_i32_positive(self) -> None: - ctl = pack_bfe_ctl(4, 4) - # 0x70 >> 4 is 0x7 (sign bit 3 is 0 -> positive 7) - res, scc = ref_s_bfe_i32(0x70, ctl) - self.assertEqual(res, 7) - self.assertEqual(scc, 1) - - def test_ref_s_bfe_i32_negative(self) -> None: - ctl = pack_bfe_ctl(4, 4) - # 0x80 >> 4 is 0x8 (sign bit 3 is 1 -> negative, -8 = 0xFFFFFFF8) - res, scc = ref_s_bfe_i32(0x80, ctl) - self.assertEqual(res, 0xFFFFFFF8) - self.assertEqual(scc, 1) - - # 0xF0 >> 4 is 0xF (sign bit 3 is 1 -> -1 = 0xFFFFFFFF) - res, scc = ref_s_bfe_i32(0xF0, ctl) - self.assertEqual(res, 0xFFFFFFFF) - self.assertEqual(scc, 1) - - def test_ref_s_bfe_i32_zero_width(self) -> None: - ctl = pack_bfe_ctl(10, 0) - res, scc = ref_s_bfe_i32(0xFFFFFFFF, ctl) - self.assertEqual(res, 0) - self.assertEqual(scc, 0) - - def test_ref_s_bfe_i32_clamping_past_bit_31(self) -> None: - # Offset 28, width 8: effective width is 4. Value 0x80000000 >> 28 is 8 (negative in 4-bit) - ctl = pack_bfe_ctl(28, 8) - res, scc = ref_s_bfe_i32(0x80000000, ctl) - self.assertEqual(res, 0xFFFFFFF8) - self.assertEqual(scc, 1) - - def test_ref_s_bfm_b32_basic(self) -> None: - # width = 8, offset = 8 -> 0x0000FF00 - mask = ref_s_bfm_b32(8, 8) - self.assertEqual(mask, 0x0000FF00) - - # width = 4, offset = 28 -> 0xF0000000 - mask = ref_s_bfm_b32(4, 28) - self.assertEqual(mask, 0xF0000000) - - # width = 0 -> 0 - mask = ref_s_bfm_b32(0, 16) - self.assertEqual(mask, 0) - - # width = 31, offset = 0 -> 0x7FFFFFFF - mask = ref_s_bfm_b32(31, 0) - self.assertEqual(mask, 0x7FFFFFFF) - - # width = 32 (32 & 31 = 0) -> 0 - mask = ref_s_bfm_b32(32, 0) - self.assertEqual(mask, 0) - - # width modulo 32 and offset modulo 32 - self.assertEqual(ref_s_bfm_b32(8 + 32, 8 + 64), 0x0000FF00) - - def test_ref_bitfield_insert(self) -> None: - base = 0x12345678 - insert = 0xAB - # insert 8 bits at offset 8 - res = ref_bitfield_insert(base, insert, 8, 8) - self.assertEqual(res, 0x1234AB78) - - # count = 0 returns base unchanged - self.assertEqual(ref_bitfield_insert(base, insert, 8, 0), base) - - # full 32-bit replace - self.assertEqual(ref_bitfield_insert(base, 0xCAFEBABE, 0, 32), 0xCAFEBABE) - - -class ScalarAluInterpreterTests(unittest.TestCase): - """Execution tests for the ScalarAluInterpreter modeling RDNA2 scalar instructions.""" - - def setUp(self) -> None: - self.interp = ScalarAluInterpreter() - - def test_s_bfe_u32_all_single_bit_positions(self) -> None: - # Verify single bit extraction across all 32 positions (0..31) - for pos in range(32): - pattern = 1 << pos - ctl = pack_bfe_ctl(pos, 1) - self.interp.set_sgpr(0, pattern) - self.interp.set_sgpr(1, ctl) - - res = self.interp.step("s_bfe_u32", 2, {"k": "sgpr", "r": 0}, {"k": "sgpr", "r": 1}) - self.assertEqual(res, 1) - self.assertEqual(self.interp.get_sgpr(2), 1) - self.assertEqual(self.interp.scc, 1) - - # Inverted bit test (bit is 0) - self.interp.set_sgpr(0, pattern ^ (1 << pos)) - res_zero = self.interp.step("s_bfe_u32", 2, {"k": "sgpr", "r": 0}, {"k": "sgpr", "r": 1}) - self.assertEqual(res_zero, 0) - self.assertEqual(self.interp.get_sgpr(2), 0) - self.assertEqual(self.interp.scc, 0) - - def test_s_bfe_u32_scc_transitions(self) -> None: - # Start with scc = 0 - self.interp.scc = 0 - self.interp.set_sgpr(0, 0xFF) - self.interp.set_sgpr(1, pack_bfe_ctl(0, 4)) - self.interp.step("s_bfe_u32", "s2", "s0", "s1") - self.assertEqual(self.interp.scc, 1) - - # Non-zero to zero: SCC must clear - self.interp.set_sgpr(0, 0x00) - self.interp.step("s_bfe_u32", "s2", "s0", "s1") - self.assertEqual(self.interp.scc, 0) - - def test_s_bfe_i32_sign_extension_matrix(self) -> None: - cases = [ - # (val, offset, width, expected_result, expected_scc) - (0x00000007, 0, 4, 7, 1), - (0x00000008, 0, 4, 0xFFFFFFF8, 1), - (0x0000000F, 0, 4, 0xFFFFFFFF, 1), - (0x00000000, 0, 4, 0, 0), - (0x00008000, 8, 8, 0xFFFFFF80, 1), - (0x00007F00, 8, 8, 0x0000007F, 1), - (0x80000000, 16, 16, 0xFFFF8000, 1), - (0x7FFF0000, 16, 16, 0x00007FFF, 1), - (0x00000001, 0, 1, 0xFFFFFFFF, 1), - (0x00000000, 0, 1, 0x00000000, 0), - ] - for val, off, wid, want_res, want_scc in cases: - with self.subTest(val=hex(val), off=off, wid=wid): - ctl = pack_bfe_ctl(off, wid) - self.interp.set_sgpr(0, val) - self.interp.set_sgpr(1, ctl) - res = self.interp.step("s_bfe_i32", "s2", "s0", "s1") - self.assertEqual(res, want_res) - self.assertEqual(self.interp.get_sgpr(2), want_res) - self.assertEqual(self.interp.scc, want_scc) - - def test_s_bfm_b32_mask_generation(self) -> None: - test_vectors = [ - # (width, offset, expected_mask) - (1, 0, 0x00000001), - (1, 31, 0x80000000), - (8, 0, 0x000000FF), - (8, 8, 0x0000FF00), - (8, 16, 0x00FF0000), - (8, 24, 0xFF000000), - (16, 0, 0x0000FFFF), - (16, 16, 0xFFFF0000), - (31, 0, 0x7FFFFFFF), - (0, 0, 0x00000000), - (0, 16, 0x00000000), - (32, 0, 0x00000000), # 32 & 31 == 0 - ] - for w, o, want in test_vectors: - with self.subTest(w=w, o=o): - self.interp.set_sgpr(0, w) - self.interp.set_sgpr(1, o) - res = self.interp.step("s_bfm_b32", "s2", "s0", "s1") - self.assertEqual(res, want) - self.assertEqual(self.interp.get_sgpr(2), want) - - def test_s_bfm_b32_preserves_scc(self) -> None: - # s_bfm_b32 must not overwrite SCC whether SCC is 0 or 1 - for initial_scc in (0, 1): - self.interp.scc = initial_scc - self.interp.set_sgpr(0, 8) - self.interp.set_sgpr(1, 4) - self.interp.step("s_bfm_b32", "s2", "s0", "s1") - self.assertEqual(self.interp.scc, initial_scc) - - def test_in_place_destination_aliasing(self) -> None: - # Destination aliases source operand - ctl = pack_bfe_ctl(8, 8) - self.interp.set_sgpr(0, 0x12345678) - self.interp.set_sgpr(1, ctl) - res = self.interp.step("s_bfe_u32", "s0", "s0", "s1") - self.assertEqual(res, 0x56) - self.assertEqual(self.interp.get_sgpr(0), 0x56) - - # Dest aliases control word - self.interp.set_sgpr(0, 0x12345678) - self.interp.set_sgpr(1, ctl) - res = self.interp.step("s_bfe_u32", "s1", "s0", "s1") - self.assertEqual(res, 0x56) - self.assertEqual(self.interp.get_sgpr(1), 0x56) - - def test_adjacent_registers_untouched(self) -> None: - self.interp.set_sgpr(0, 0x11111111) - self.interp.set_sgpr(1, 0x22222222) - self.interp.set_sgpr(2, 0x33333333) - self.interp.set_sgpr(3, 0x44444444) - - ctl = pack_bfe_ctl(4, 4) - self.interp.step("s_bfe_u32", "s1", "s2", ctl) - self.assertEqual(self.interp.get_sgpr(0), 0x11111111) - self.assertEqual(self.interp.get_sgpr(2), 0x33333333) - self.assertEqual(self.interp.get_sgpr(3), 0x44444444) - - def test_scalar_bitfield_insert_composition_pipeline(self) -> None: - # Simulate scalar bitfield insert: - # s_bfm_b32 s_mask, count, offset - # s_lshl_b32 s_ins_shifted, s_ins, offset - # s_and_b32 s_ins_masked, s_ins_shifted, s_mask - # s_and_b32 s_base_cleared, s_base, ~s_mask - # s_or_b32 s_res, s_base_cleared, s_ins_masked - base_val = 0xAA55AA55 - ins_val = 0x3F - offset = 12 - count = 6 - - mask = ref_s_bfm_b32(count, offset) - expected = ref_bitfield_insert(base_val, ins_val, offset, count) - - self.interp.set_sgpr(0, base_val) - self.interp.set_sgpr(1, ins_val) - self.interp.set_sgpr(2, count) - self.interp.set_sgpr(3, offset) - - seq = [ - ("s_bfm_b32", "s4", "s2", "s3"), # s4 = mask - ("s_lshl_b32", "s5", "s1", "s3"), # s5 = ins << offset - ("s_and_b32", "s5", "s5", "s4"), # s5 = (ins << offset) & mask - ("s_and_b32", "s6", "s0", {"k": "imm", "v": ~mask}), # s6 = base & ~mask - ("s_or_b32", "s7", "s6", "s5"), # s7 = s6 | s5 - ] - result = self.interp.run_sequence(seq) - self.assertEqual(result, expected) - self.assertEqual(self.interp.get_sgpr(7), expected) - - # Roundtrip: extract the inserted field back out with s_bfe_u32 - ctl = pack_bfe_ctl(offset, count) - extracted = self.interp.step("s_bfe_u32", "s8", "s7", ctl) - self.assertEqual(extracted, ins_val) - - -class TranslatorEmissionTests(unittest.TestCase): - """Verify that rdna2spirv.Gen correctly emits SPIR-V for s_bfe and s_bfm instructions.""" - - def test_translate_s_bfe_u32_emission(self) -> None: - g = rdna2spirv.Gen("ps") - ins = { - "op": "s_bfe_u32", - "args": [ - {"k": "sgpr", "r": 2}, - {"k": "sgpr", "r": 0}, - {"k": "sgpr", "r": 1}, - ], - "mods": [], - } - g.insn(ins) - emitted = "\n".join(g.body) - - # Unpack offset [4:0] and width [22:16] - self.assertIn("OpBitwiseAnd %uint", emitted) - self.assertIn("OpBitFieldUExtract %uint", emitted) - # Clamping via bfe_width - self.assertIn("OpISub %uint", emitted) - self.assertIn("OpULessThan %bool", emitted) - # Store result and SCC - self.assertIn("OpStore %scc", emitted) - - def test_translate_s_bfe_i32_emission(self) -> None: - g = rdna2spirv.Gen("ps") - ins = { - "op": "s_bfe_i32", - "args": [ - {"k": "sgpr", "r": 3}, - {"k": "sgpr", "r": 4}, - {"k": "sgpr", "r": 5}, - ], - "mods": [], - } - g.insn(ins) - emitted = "\n".join(g.body) - - self.assertIn("OpBitFieldSExtract %int", emitted) - self.assertIn("OpBitcast %int", emitted) - self.assertIn("OpBitcast %uint", emitted) - self.assertIn("OpStore %scc", emitted) - - def test_translate_s_bfm_b32_emission(self) -> None: - g = rdna2spirv.Gen("ps") - ins = { - "op": "s_bfm_b32", - "args": [ - {"k": "sgpr", "r": 6}, - {"k": "sgpr", "r": 7}, - {"k": "sgpr", "r": 8}, - ], - "mods": [], - } - g.insn(ins) - emitted = "\n".join(g.body) - - self.assertIn("OpShiftLeftLogical %uint", emitted) - self.assertIn("OpISub %uint", emitted) - self.assertIn("OpBitwiseAnd %uint", emitted) - # s_bfm_b32 must NOT emit SCC store - self.assertNotIn("OpStore %scc", emitted) - - def test_translation_determinism(self) -> None: - def emit_sequence() -> str: - g = rdna2spirv.Gen("ps") - for op in ("s_bfe_u32", "s_bfe_i32", "s_bfm_b32"): - g.insn({ - "op": op, - "args": [ - {"k": "sgpr", "r": 0}, - {"k": "sgpr", "r": 1}, - {"k": "sgpr", "r": 2}, - ], - "mods": [], - }) - return "\n".join(g.body) - - self.assertEqual(emit_sequence(), emit_sequence()) - - -SPIRV_HEADER = """\ -OpCapability Shader -%glsl = OpExtInstImport "GLSL.std.450" -OpMemoryModel Logical GLSL450 -OpEntryPoint Fragment %main "main" %out -%void = OpTypeVoid -%fn = OpTypeFunction %void -%uint = OpTypeInt 32 0 -%int = OpTypeInt 32 1 -%bool = OpTypeBool -%_ptr_Output_uint = OpTypePointer Output %uint -%out = OpVariable %_ptr_Output_uint Output -{constants} -%main = OpFunction %void None %fn -%entry = OpLabel -{body} -OpStore %out %res -OpReturn -OpFunctionEnd -""" - - -def run_spv(body: str, const_defs: dict[str, int]) -> int: - """Assemble and run a SPIR-V fragment module defining %res.""" - consts_text = "\n".join(f"%{name} = OpConstant %uint {val & MASK32}" for name, val in const_defs.items()) - mod_text = SPIRV_HEADER.format(constants=consts_text, body=body) - return si.run_fragment(mod_text)["%out"][0] - - -class SpirvMiniInterpTests(unittest.TestCase): - """Cross-validation between interpreter models and direct spirv_mini_interp execution.""" - - def test_direct_uextract_in_spirv(self) -> None: - consts = {"x": 0xDEADBEEF, "off": 8, "wid": 8} - body = "%res = OpBitFieldUExtract %uint %x %off %wid\n" - self.assertEqual(run_spv(body, consts), 0xBE) - - def test_direct_sextract_in_spirv(self) -> None: - # Negative 4-bit field: 0xF0 >> 4 is 0xF -> sign extended to 0xFFFFFFFF - consts = {"x": 0xF0, "off": 4, "wid": 4} - body = """\ -%xi = OpBitcast %int %x -%ri = OpBitFieldSExtract %int %xi %off %wid -%res = OpBitcast %uint %ri -""" - self.assertEqual(run_spv(body, consts), 0xFFFFFFFF) - - def test_direct_insert_in_spirv(self) -> None: - consts = {"base": 0xFFFFFFFF, "ins": 0x12, "off": 8, "cnt": 8} - body = "%res = OpBitFieldInsert %uint %base %ins %off %cnt\n" - self.assertEqual(run_spv(body, consts), 0xFFFF12FF) - - def test_lowered_s_bfe_u32_with_large_width_avoids_rejection(self) -> None: - # SPIR-V rejects offset + count > 32 if passed directly to OpBitFieldUExtract. - # But rdna2spirv lowers width via bfe_width: - # room = 32 - off; fits = wid < room; clamped_wid = fits ? wid : room - # Here offset = 28, raw width = 16 (28 + 16 = 44 > 32). - # Clamped width becomes 4, extracting the top 4 bits (0xA). - ctl = pack_bfe_ctl(28, 16) - consts = {"x": 0xA0000000, "ctl": ctl, "c31": 31, "c16": 16, "c7": 7, "c32": 32} - body = """\ -%off = OpBitwiseAnd %uint %ctl %c31 -%raw_wid = OpBitFieldUExtract %uint %ctl %c16 %c7 -%room = OpISub %uint %c32 %off -%fits = OpULessThan %bool %raw_wid %room -%clamped_wid = OpSelect %uint %fits %raw_wid %room -%res = OpBitFieldUExtract %uint %x %off %clamped_wid -""" - got = run_spv(body, consts) - self.assertEqual(got, 0xA) - expected, _ = ref_s_bfe_u32(0xA0000000, ctl) - self.assertEqual(got, expected) - - def test_direct_out_of_bounds_raises_unsupported(self) -> None: - # Direct raw OpBitFieldUExtract with off + wid > 32 must be rejected by spirv_mini_interp - consts = {"x": 0xFF, "off": 30, "wid": 4} - body = "%res = OpBitFieldUExtract %uint %x %off %wid\n" - with self.assertRaises(si.UnsupportedConstruct): - run_spv(body, consts) - - consts_ins = {"base": 0, "ins": 1, "off": 25, "cnt": 10} - body_ins = "%res = OpBitFieldInsert %uint %base %ins %off %cnt\n" - with self.assertRaises(si.UnsupportedConstruct): - run_spv(body_ins, consts_ins) - - -class NegativeControlTests(unittest.TestCase): - """Sensitivity tests ensuring mutations in bitfield logic are detected.""" - - def test_signed_vs_unsigned_mutation_caught(self) -> None: - # Extracting 0x00008000 with offset 8, width 8 gives 0x80. - # Signed gives 0xFFFFFF80, unsigned gives 0x00000080. - ctl = pack_bfe_ctl(8, 8) - signed_res, _ = ref_s_bfe_i32(0x00008000, ctl) - unsigned_res, _ = ref_s_bfe_u32(0x00008000, ctl) - self.assertEqual(signed_res, 0xFFFFFF80) - self.assertEqual(unsigned_res, 0x00000080) - self.assertNotEqual(signed_res, unsigned_res) - - def test_dropped_offset_mutation_caught(self) -> None: - ctl_good = pack_bfe_ctl(4, 8) - ctl_mutated = pack_bfe_ctl(0, 8) - val = 0x12345678 - res_good, _ = ref_s_bfe_u32(val, ctl_good) - res_mutated, _ = ref_s_bfe_u32(val, ctl_mutated) - self.assertEqual(res_good, 0x67) - self.assertEqual(res_mutated, 0x78) - self.assertNotEqual(res_good, res_mutated) - - def test_scc_zero_flag_mutation_caught(self) -> None: - # An implementation that fails to clear SCC when the result is 0 - ctl = pack_bfe_ctl(0, 4) - res_nonzero, scc_nonzero = ref_s_bfe_u32(0x5, ctl) - res_zero, scc_zero = ref_s_bfe_u32(0x0, ctl) - self.assertEqual(scc_nonzero, 1) - self.assertEqual(scc_zero, 0) - self.assertNotEqual(scc_nonzero, scc_zero) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_scalar_alu_imm_bitset.py b/tests/semantic/test_scalar_alu_imm_bitset.py deleted file mode 100644 index a41b5b99e..000000000 --- a/tests/semantic/test_scalar_alu_imm_bitset.py +++ /dev/null @@ -1,826 +0,0 @@ -"""Semantic interpreter tests for RDNA2 scalar inline-immediate and bit-set ALU instructions. - -Covers end-to-end translation via ``tools/rdna2spirv.py`` and execution via -``tests/semantic/spirv_mini_interp.py`` for: - * s_movk_i32 (SOPK: D = signext(simm16); SCC unchanged) - * s_addk_i32 (SOPK: D = D + signext(simm16) mod 2^32; SCC = signed 32-bit overflow) - * s_mulk_i32 (SOPK: D = D * signext(simm16) mod 2^32; SCC unchanged) - * s_bitset0_b32 (SOP1: D = D & ~(1 << (S0 & 31)); SCC unchanged) - * s_bitset1_b32 (SOP1: D = D | (1 << (S0 & 31)); SCC unchanged) - * s_bfm_b32 (SOP2: D = ((1 << (S0 & 31)) - 1) << (S1 & 31) mod 2^32; SCC unchanged) - -RDNA2 ISA rules (AMD RDNA2 "Instruction Set Architecture" reference, SOP1/SOP2/SOPK): - * SOPK 16-bit literals (``simm16``) are sign-extended from bit 15 to 32 bits before use. - * ``s_addk_i32`` performs in-place signed 32-bit addition and sets SCC on signed overflow - (positive + positive -> negative, or negative + negative -> positive). Unsigned wraparound - such as ``0xFFFFFFFF + 1 -> 0`` produces SCC = 0. - * ``s_movk_i32``, ``s_mulk_i32``, ``s_bitset0_b32``, ``s_bitset1_b32``, and ``s_bfm_b32`` - do not modify SCC. - * ``s_bitset0_b32`` / ``s_bitset1_b32`` mask the bit index with ``& 31``. - * ``s_bfm_b32`` masks both width (``S0 & 31``) and offset (``S1 & 31``) to 5 bits, so - width = 32 masks to 0 (yielding 0, not 0xFFFFFFFF), and bits shifted past bit 31 are - truncated (zeroed), not wrapped around to bit 0. - -Translator notes observed in ``tools/rdna2spirv.py``: - * ``s_mulk_i32``, ``s_bitset0_b32``, and ``s_bitset1_b32`` read their in-place destination - with ``src_u(a[0])`` (matching ``s_addk_i32``), supporting SGPR and non-SGPR targets - such as ``m0``, ``vcc_lo``, ``vcc_hi``, and ``null``. - * ``s_bfm_b32`` has a duplicate unreachable handler shadowed by its earlier branch. - -Run directly: - python -I tests/semantic/test_scalar_alu_imm_bitset.py -Or via unittest discovery: - python -m unittest discover -s tests/semantic -v -""" -import os -import struct -import sys -import tempfile -import unittest -import warnings - -HERE = os.path.dirname(os.path.abspath(__file__)) -ROOT = os.path.dirname(os.path.dirname(HERE)) -TOOLS_DIR = os.environ.get("LEONIDA_TOOLS_DIR") or os.path.join(ROOT, "tools") - -sys.dont_write_bytecode = True # never drop __pycache__ into the tree under test -sys.path.insert(0, TOOLS_DIR) -sys.path.insert(0, HERE) - -import rdna2spirv # noqa: E402 -import spirv_mini_interp as si # noqa: E402 - -MASK32 = 0xFFFFFFFF -STUB_DXBC = b"DXBC" + bytes(24) + struct.pack(" int: - v = val & 0xFFFF - return v - 0x10000 if v & 0x8000 else v - - -def _s32(val: int) -> int: - v = val & MASK32 - return v - (1 << 32) if v >> 31 else v - - -def ref_s_movk_i32(simm16: int) -> int: - return _s16(simm16) & MASK32 - - -def ref_s_addk_i32(dst_val: int, simm16: int) -> tuple[int, int]: - total = _s32(dst_val) + _s16(simm16) - scc = 1 if (total < -(1 << 31) or total >= (1 << 31)) else 0 - return total & MASK32, scc - - -def ref_s_mulk_i32(dst_val: int, simm16: int) -> int: - return (_s32(dst_val) * _s16(simm16)) & MASK32 - - -def ref_s_bitset0_b32(dst_val: int, bit_idx: int) -> int: - return (dst_val & MASK32) & ~(1 << (bit_idx & 31)) - - -def ref_s_bitset1_b32(dst_val: int, bit_idx: int) -> int: - return ((dst_val & MASK32) | (1 << (bit_idx & 31))) & MASK32 - - -def ref_s_bfm_b32(width: int, offset: int) -> int: - return (((1 << (width & 31)) - 1) << (offset & 31)) & MASK32 - - -def translate_lines(lines: list[str]) -> str: - if _TMP_DIR is None: - setUpModule() - asm = "; test_scalar_alu_imm_bitset\n" + "".join(f"\t{ln}\n" for ln in lines) - with open(_SRC_PATH, "w", encoding="utf-8") as f: - f.write(asm) - with warnings.catch_warnings(): - warnings.simplefilter("ignore", ResourceWarning) - return rdna2spirv.translate(_SRC_PATH) - - -def run_pair(lines: list[str]) -> tuple[int, int]: - """Run shader lines writing v0 and v1; return (v0, v1).""" - spv = translate_lines(lines + ["exp mrt0 v0, v1, v0, v0 done vm", "s_endpgm"]) - out = si.run_fragment(spv)["%out_mrt0"] - return out[0], out[1] - - -def run_quad(lines: list[str]) -> tuple[int, int, int, int]: - """Run shader lines writing v0..v3; return all 4 exported words.""" - spv = translate_lines(lines + ["exp mrt0 v0, v1, v2, v3 done vm", "s_endpgm"]) - out = si.run_fragment(spv)["%out_mrt0"] - return (out[0], out[1], out[2], out[3]) - - -def scc_seed_line(pre_scc: int) -> str: - return "s_cmp_eq_u32 1, 1" if pre_scc else "s_cmp_eq_u32 0, 1" - - -def fmt_imm16(imm) -> str: - return imm if isinstance(imm, str) else f"{imm:#x}" - - -# Hand-written boundary constants checked against reference functions in OracleTests. -ORACLE_MOVK = [ - (0x0000, 0x00000000), - (0x0001, 0x00000001), - (0x7FFF, 0x00007FFF), - (0x8000, 0xFFFF8000), - (0xABCD, 0xFFFFABCD), - (0xFFFF, 0xFFFFFFFF), -] - -ORACLE_ADDK = [ - (0x00000000, 0x0000, 0x00000000, 0), - (0x7FFFFFFF, 0x0001, 0x80000000, 1), # positive signed overflow - (0x7FFF8000, 0x7FFF, 0x7FFFFFFF, 0), # max non-overflowing positive add - (0x7FFF8001, 0x7FFF, 0x80000000, 1), # min overflowing positive add with max simm16 - (0x80000000, 0xFFFF, 0x7FFFFFFF, 1), # negative signed overflow (-2^31 + -1) - (0x80008000, 0x8000, 0x80000000, 0), # min non-overflowing negative add - (0x80007FFF, 0x8000, 0x7FFFFFFF, 1), # max overflowing negative add with min simm16 - (0xFFFFFFFF, 0x0001, 0x00000000, 0), # unsigned wrap without signed overflow - (0x00000005, 0xFFF6, 0xFFFFFFFB, 0), # 5 + (-10) = -5 -] - -ORACLE_MULK = [ - (0x00000000, 0x7FFF, 0x00000000), - (0x12345678, 0x0000, 0x00000000), - (0x00000001, 0x8000, 0xFFFF8000), # 1 * -32768 (sign-extension check) - (0x80000000, 0xFFFF, 0x80000000), # INT32_MIN * -1 wraps to INT32_MIN - (0x80000000, 0x8000, 0x00000000), # -2^31 * -2^15 = 2^46 -> low 32 bits 0 - (0x80000001, 0x8000, 0xFFFF8000), # (-2^31 + 1) * -32768 - (0x7FFFFFFF, 0x7FFF, 0x7FFF8001), # (2^31 - 1) * 32767 mod 2^32 - (0xFFFFFFFB, 0x8000, 0x00028000), # -5 * -32768 = 163840 -] - -ORACLE_BITSET = [ - # (op, init, bit_idx, expected) - ("bitset0", 0xFFFFFFFF, 0, 0xFFFFFFFE), - ("bitset0", 0xFFFFFFFF, 31, 0x7FFFFFFF), - ("bitset0", 0xFFFFFFFF, 32, 0xFFFFFFFE), - ("bitset0", 0xFFFFFFFF, 0xFFFFFFFF, 0x7FFFFFFF), - ("bitset0", 0xA5A55A5A, 3, 0xA5A55A52), - ("bitset1", 0x00000000, 0, 0x00000001), - ("bitset1", 0x00000000, 31, 0x80000000), - ("bitset1", 0x00000000, 32, 0x00000001), - ("bitset1", 0x00000000, 0xFFFFFFFF, 0x80000000), - ("bitset1", 0xA5A55A5A, 2, 0xA5A55A5E), -] - -ORACLE_BFM = [ - # (width, offset, expected) - (0, 0, 0x00000000), - (0, 31, 0x00000000), - (32, 0, 0x00000000), # width masked & 31 -> 0 - (32, 16, 0x00000000), - (31, 0, 0x7FFFFFFF), - (31, 1, 0xFFFFFFFE), - (31, 2, 0xFFFFFFFC), # shifted past bit 31: truncated, not wrapped - (31, 31, 0x80000000), - (8, 28, 0xF0000000), # overflow beyond bit 31 truncated - (16, 20, 0xFFF00000), - (4, 32, 0x0000000F), # offset masked & 31 -> 0 - (33, 35, 0x00000008), # width 1, offset 3 - (0xFFFFFFFF, 0xFFFFFFFF, 0x80000000), # width 31, offset 31 -] - - -class OracleTests(unittest.TestCase): - """Self-consistency check between hand-written constants and plain-Python ISA formulas.""" - - def test_reference_matches_constants(self): - for imm, want in ORACLE_MOVK: - self.assertEqual(ref_s_movk_i32(imm), want) - for init, imm, want_res, want_scc in ORACLE_ADDK: - self.assertEqual(ref_s_addk_i32(init, imm), (want_res, want_scc)) - for init, imm, want in ORACLE_MULK: - self.assertEqual(ref_s_mulk_i32(init, imm), want) - for kind, init, bit, want in ORACLE_BITSET: - fn = ref_s_bitset0_b32 if kind == "bitset0" else ref_s_bitset1_b32 - self.assertEqual(fn(init, bit), want) - for width, offset, want in ORACLE_BFM: - self.assertEqual(ref_s_bfm_b32(width, offset), want) - - -class TestScalarMovkI32(unittest.TestCase): - """End-to-end semantic tests for s_movk_i32.""" - - def test_sign_extension_and_overwriting_upper_bits(self): - cases = [ - (0, 0x00000000), - (1, 0x00000001), - (0x1234, 0x00001234), - (0x7FFF, 0x00007FFF), - (0x8000, 0xFFFF8000), - (0x8001, 0xFFFF8001), - (0xABCD, 0xFFFFABCD), - (0xFFFF, 0xFFFFFFFF), - ("-1", 0xFFFFFFFF), - ("-123", 0xFFFFFF85), - ("-32768", 0xFFFF8000), - ] - for imm, want in cases: - imm_val = int(imm, 0) if isinstance(imm, str) else imm - self.assertEqual(ref_s_movk_i32(imm_val), want) - for pre_scc in (0, 1): - with self.subTest(imm=imm, pre_scc=pre_scc): - got, got_scc = run_pair([ - "s_mov_b32 s0, 0xdeadbeef", - scc_seed_line(pre_scc), - f"s_movk_i32 s0, {fmt_imm16(imm)}", - "s_cselect_b32 s1, 1, 0", - "v_mov_b32 v0, s0", - "v_mov_b32 v1, s1", - ]) - self.assertEqual(got, want) - self.assertEqual(got_scc, pre_scc) - - def test_special_destinations_and_register_isolation(self): - for dst in ("m0", "vcc_lo", "vcc_hi"): - with self.subTest(dst=dst): - got, _ = run_pair([ - f"s_movk_i32 {dst}, 0x8005", - f"s_mov_b32 s0, {dst}", - "v_mov_b32 v0, s0", - "v_mov_b32 v1, 0", - ]) - self.assertEqual(got, 0xFFFF8005) - - w0, w1, w2, w3 = run_quad([ - "s_mov_b32 s0, 0x11111111", - "s_mov_b32 s1, 0x22222222", - "s_mov_b32 s2, 0x33333333", - "s_movk_i32 s1, 0x8001", - "s_movk_i32 null, 0x7fff", - "v_mov_b32 v0, s0", - "v_mov_b32 v1, s1", - "v_mov_b32 v2, s2", - "v_mov_b32 v3, 0", - ]) - self.assertEqual((w0, w1, w2, w3), (0x11111111, 0xFFFF8001, 0x33333333, 0)) - - -class TestScalarAddkI32(unittest.TestCase): - """End-to-end semantic tests for s_addk_i32 and signed-overflow SCC.""" - - def test_in_place_add_and_signed_overflow_scc(self): - cases = [ - (0x00000000, 0), - (0x00000064, 50), - (0x00000064, -30), - (0x00000005, -10), - (0x7FFFFFFF, 1), # positive overflow -> 0x80000000, SCC = 1 - (0x7FFF8000, 0x7FFF), # exact positive boundary -> 0x7FFFFFFF, SCC = 0 - (0x7FFF8001, 0x7FFF), # positive overflow with max simm16 -> SCC = 1 - (0x7FFFFFFF, 0x7FFF), # large positive overflow -> SCC = 1 - (0x80000000, "-1"), # negative overflow -> 0x7FFFFFFF, SCC = 1 - (0x80000000, 0xFFFF), # negative overflow (hex -1) -> SCC = 1 - (0x80008000, 0x8000), # exact negative boundary -> 0x80000000, SCC = 0 - (0x80007FFF, 0x8000), # negative overflow with min simm16 -> SCC = 1 - (0x80000000, "-32768"), # large negative overflow -> SCC = 1 - (0xFFFFFFFF, 1), # unsigned wraparound (-1 + 1 = 0), NO signed overflow -> SCC = 0 - (0xFFFFFFFF, 0x7FFF), # unsigned wraparound (-1 + 32767), NO signed overflow -> SCC = 0 - (0xFFFF0000, 0x7FFF), # negative + positive -> negative, SCC = 0 - ] - for init, imm in cases: - imm_val = int(imm, 0) if isinstance(imm, str) else imm - want_res, want_scc = ref_s_addk_i32(init, imm_val) - # Pre-seed SCC opposite of expected when non-overflowing to verify SCC is actively cleared. - pre_scc = 0 if want_scc else 1 - with self.subTest(init=hex(init), imm=imm): - got_res, got_scc = run_pair([ - f"s_mov_b32 s0, {init:#x}", - scc_seed_line(pre_scc), - f"s_addk_i32 s0, {fmt_imm16(imm)}", - "s_cselect_b32 s1, 1, 0", - "v_mov_b32 v0, s0", - "v_mov_b32 v1, s1", - ]) - self.assertEqual(got_res, want_res) - self.assertEqual(got_scc, want_scc) - - def test_chained_in_place_accumulation(self): - # Step 1: 0x7fff0000 + 0x7fff -> 0x7fff7fff, SCC = 0 - # Step 2: + 0x7fff -> 0x7ffffffe, SCC = 0 - # Step 3: + 2 -> 0x80000000, SCC = 1 (overflow) - # Step 4: + (-1) -> 0x7fffffff, SCC = 1 (negative overflow back) - w0, w1, w2, w3 = run_quad([ - "s_mov_b32 s0, 0x7fff0000", - "s_addk_i32 s0, 0x7fff", - "s_addk_i32 s0, 0x7fff", - "s_cselect_b32 s1, 1, 0", - "s_addk_i32 s0, 2", - "s_cselect_b32 s2, 1, 0", - "s_addk_i32 s0, -1", - "s_cselect_b32 s3, 1, 0", - "v_mov_b32 v0, s0", - "v_mov_b32 v1, s1", - "v_mov_b32 v2, s2", - "v_mov_b32 v3, s3", - ]) - self.assertEqual((w0, w1, w2, w3), (0x7FFFFFFF, 0, 1, 1)) - - def test_special_destinations_and_register_isolation(self): - for dst in ("m0", "vcc_lo", "vcc_hi"): - with self.subTest(dst=dst): - got_res, got_scc = run_pair([ - f"s_mov_b32 {dst}, 0x7ffffff0", - f"s_addk_i32 {dst}, 0x20", - "s_cselect_b32 s1, 1, 0", - f"s_mov_b32 s0, {dst}", - "v_mov_b32 v0, s0", - "v_mov_b32 v1, s1", - ]) - self.assertEqual(got_res, 0x80000010) - self.assertEqual(got_scc, 1) - - w0, w1, w2, w3 = run_quad([ - "s_mov_b32 s0, 0x11111111", - "s_mov_b32 s1, 0x00000010", - "s_mov_b32 s2, 0x33333333", - "s_addk_i32 s1, -5", - "v_mov_b32 v0, s0", - "v_mov_b32 v1, s1", - "v_mov_b32 v2, s2", - "v_mov_b32 v3, 0", - ]) - self.assertEqual((w0, w1, w2, w3), (0x11111111, 0x0000000B, 0x33333333, 0)) - - -class TestScalarMulkI32(unittest.TestCase): - """End-to-end semantic tests for s_mulk_i32.""" - - def test_signed_imm16_multiply_wrap_and_scc_preserved(self): - cases = [ - (0x00000000, 0x7FFF), - (0x12345678, 0), - (0x80000000, 0), - (0x00000001, 0x8000), # 1 * -32768 -> 0xFFFF8000 (sign extension) - (0x00000001, "-32768"), - (0x00000001, 0xFFFF), # 1 * -1 -> 0xFFFFFFFF - (0x00000007, "-3"), # 7 * -3 -> -21 (0xFFFFFFEB) - (0xFFFFFFFB, 0x8000), # -5 * -32768 -> 163840 - (0x00010001, 0x7FFF), # 32-bit positive wrap - (0x7FFFFFFF, 0x7FFF), # INT32_MAX * 32767 mod 2^32 - (0x80000000, "-1"), # INT32_MIN * -1 wraps to INT32_MIN - (0x80000000, 0x8000), # -2^31 * -32768 -> low 32 bits 0 - (0x80000001, 0x8000), # (-2^31 + 1) * -32768 -> 0xFFFF8000 - (0xFFFFFFFF, 2), # -1 * 2 -> -2 - (0x12345678, "-7"), - ] - for init, imm in cases: - imm_val = int(imm, 0) if isinstance(imm, str) else imm - want = ref_s_mulk_i32(init, imm_val) - for pre_scc in (0, 1): - with self.subTest(init=hex(init), imm=imm, pre_scc=pre_scc): - got, got_scc = run_pair([ - f"s_mov_b32 s0, {init:#x}", - scc_seed_line(pre_scc), - f"s_mulk_i32 s0, {fmt_imm16(imm)}", - "s_cselect_b32 s1, 1, 0", - "v_mov_b32 v0, s0", - "v_mov_b32 v1, s1", - ]) - self.assertEqual(got, want) - self.assertEqual(got_scc, pre_scc) - - def test_chained_multiply_and_register_isolation(self): - w0, w1, w2, w3 = run_quad([ - "s_mov_b32 s0, 0x11111111", - "s_movk_i32 s1, 3", - "s_mov_b32 s2, 0x22222222", - "s_mulk_i32 s1, -5", - "s_mulk_i32 s1, 0x7fff", - "v_mov_b32 v0, s0", - "v_mov_b32 v1, s1", - "v_mov_b32 v2, s2", - "v_mov_b32 v3, 0", - ]) - want_s1 = ref_s_mulk_i32(ref_s_mulk_i32(3, -5), 0x7FFF) - self.assertEqual((w0, w1, w2, w3), (0x11111111, want_s1, 0x22222222, 0)) - - def test_special_destinations_and_register_isolation(self): - cases = [ - (0x00000007, -3), - (0x00000001, 0x8000), - (0xFFFFFFFB, 0x8000), - (0x7FFFFFFF, 0x7FFF), - (0x80000000, 0xFFFF), - ] - for dst in ("m0", "vcc_lo", "vcc_hi"): - for init, imm in cases: - want = ref_s_mulk_i32(init, imm) - for pre_scc in (0, 1): - with self.subTest(dst=dst, init=hex(init), imm=imm, pre_scc=pre_scc): - got, got_scc = run_pair([ - f"s_mov_b32 {dst}, {init:#x}", - scc_seed_line(pre_scc), - f"s_mulk_i32 {dst}, {fmt_imm16(imm)}", - "s_cselect_b32 s1, 1, 0", - f"s_mov_b32 s0, {dst}", - "v_mov_b32 v0, s0", - "v_mov_b32 v1, s1", - ]) - self.assertEqual(got, want) - self.assertEqual(got_scc, pre_scc) - - for target, other1, other2 in ( - ("m0", "vcc_lo", "vcc_hi"), - ("vcc_lo", "m0", "vcc_hi"), - ("vcc_hi", "m0", "vcc_lo"), - ): - with self.subTest(isolated_target=target): - w0, w1, w2, w3 = run_quad([ - "s_mov_b32 s0, 0x11111111", - f"s_mov_b32 {target}, 3", - f"s_mov_b32 {other1}, 0x22222222", - f"s_mov_b32 {other2}, 0x33333333", - f"s_mulk_i32 {target}, -5", - f"s_mulk_i32 {target}, 0x7fff", - "s_mulk_i32 null, 0x7fff", - f"s_mov_b32 s1, {target}", - f"s_mov_b32 s2, {other1}", - f"s_mov_b32 s3, {other2}", - "v_mov_b32 v0, s0", - "v_mov_b32 v1, s1", - "v_mov_b32 v2, s2", - "v_mov_b32 v3, s3", - ]) - want_target = ref_s_mulk_i32(ref_s_mulk_i32(3, -5), 0x7FFF) - self.assertEqual((w0, w1, w2, w3), (0x11111111, want_target, 0x22222222, 0x33333333)) - - -class TestScalarBitsetB32(unittest.TestCase): - """End-to-end semantic tests for s_bitset0_b32 and s_bitset1_b32.""" - - def test_all_32_bit_positions_and_neighbor_preservation(self): - # Check every bit 0..31 on complementary non-NaN patterns (0xA5A55A5A / 0x5A5AA5A5) plus - # all-ones (0xFFFFFFFF) and all-zeros (0). Note: exp mrt0 bitcasts through float in - # spirv_mini_interp, which quiets signaling NaNs (bit 22 cleared on 0xFFFFFFFF -> 0xFFBFFFFF - # becomes 0xFFFFFFFF); flipping bit 30 (or bit 29 for bit==30) on s0 avoids NaN patterns - # while still verifying every bit 0..31 of 0xFFFFFFFF after s_bitset0_b32. - pat_a, pat_b = 0xA5A55A5A, 0x5A5AA5A5 - for bit in range(32): - guard = 0x20000000 if bit == 30 else 0x40000000 - with self.subTest(bit=bit): - w0, w1, w2, w3 = run_quad([ - "s_mov_b32 s0, 0xffffffff", - "s_mov_b32 s1, 0", - f"s_mov_b32 s2, {pat_a:#x}", - f"s_mov_b32 s3, {pat_b:#x}", - f"s_bitset0_b32 s0, {bit}", - f"s_xor_b32 s0, s0, {guard:#x}", - f"s_bitset1_b32 s1, {bit}", - f"s_bitset0_b32 s2, {bit}", - f"s_bitset1_b32 s3, {bit}", - "v_mov_b32 v0, s0", - "v_mov_b32 v1, s1", - "v_mov_b32 v2, s2", - "v_mov_b32 v3, s3", - ]) - self.assertEqual(w0, ref_s_bitset0_b32(0xFFFFFFFF, bit) ^ guard) - self.assertEqual(w1, ref_s_bitset1_b32(0, bit)) - self.assertEqual(w2, ref_s_bitset0_b32(pat_a, bit)) - self.assertEqual(w3, ref_s_bitset1_b32(pat_b, bit)) - # Also verify s_bitset1_b32 on pat_a and s_bitset0_b32 on pat_b. - p0, p1 = run_pair([ - f"s_mov_b32 s0, {pat_a:#x}", - f"s_mov_b32 s1, {pat_b:#x}", - f"s_bitset1_b32 s0, {bit}", - f"s_bitset0_b32 s1, {bit}", - "v_mov_b32 v0, s0", - "v_mov_b32 v1, s1", - ]) - self.assertEqual(p0, ref_s_bitset1_b32(pat_a, bit)) - self.assertEqual(p1, ref_s_bitset0_b32(pat_b, bit)) - - def test_bit_index_masking_mod_32_and_scc_preserved(self): - indices = [0, 1, 31, 32, 33, 63, 64, 0x80000000, 0x12345625, 0xFFFFFFFF, "-1"] - for idx in indices: - idx_val = int(idx, 0) if isinstance(idx, str) else idx - for use_sgpr in (False, True): - for pre_scc in (0, 1): - with self.subTest(idx=idx, use_sgpr=use_sgpr, pre_scc=pre_scc): - src_op = "s2" if use_sgpr else (idx if isinstance(idx, str) else f"{idx:#x}") - setup = [f"s_mov_b32 s2, {idx_val & MASK32:#x}"] if use_sgpr else [] - w0, w1, w2, w3 = run_quad(setup + [ - "s_mov_b32 s0, 0xff7fffff", - "s_mov_b32 s1, 0", - scc_seed_line(pre_scc), - f"s_bitset0_b32 s0, {src_op}", - f"s_bitset1_b32 s1, {src_op}", - "s_cselect_b32 s3, 1, 0", - "v_mov_b32 v0, s0", - "v_mov_b32 v1, s1", - "v_mov_b32 v2, s3", - "v_mov_b32 v3, 0", - ]) - self.assertEqual(w0, ref_s_bitset0_b32(0xFF7FFFFF, idx_val)) - self.assertEqual(w1, ref_s_bitset1_b32(0, idx_val)) - self.assertEqual(w2, pre_scc) - - def test_idempotency_aliasing_and_special_sources(self): - # Clearing bit in 0 or setting bit in 0xFFFFFFFF leaves value unchanged; aliasing sD == sS0 works; - # s_bitset0_b32 clearing the last 1 bit to 0 still preserves SCC=1. - w0, w1, w2, w3 = run_quad([ - "s_mov_b32 s0, 0", - "s_mov_b32 s1, 0xffffffff", - "s_mov_b32 s2, 0x80000000", - "s_cmp_eq_u32 1, 1", - "s_bitset0_b32 s0, 17", - "s_bitset1_b32 s1, 17", - "s_bitset0_b32 s2, 31", - "s_cselect_b32 s3, 1, 0", - "v_mov_b32 v0, s0", - "v_mov_b32 v1, s1", - "v_mov_b32 v2, s2", - "v_mov_b32 v3, s3", - ]) - self.assertEqual((w0, w1, w2, w3), (0, 0xFFFFFFFF, 0, 1)) - - # Aliasing: s_bitset0_b32 s0, s0 (s0 = 0x25 -> 0x25 & 31 = bit 5 -> clears bit 5 -> 0x05) - # s_bitset1_b32 s1, s1 (s1 = 0x04 -> 0x04 & 31 = bit 4 -> sets bit 4 -> 0x14) - # Also test m0 and null as bit-index source, plus s3 untouched. - w0, w1, w2, w3 = run_quad([ - "s_mov_b32 s0, 0x25", - "s_mov_b32 s1, 0x04", - "s_mov_b32 m0, 7", - "s_mov_b32 s2, 0", - "s_mov_b32 s3, 0x55aa55aa", - "s_bitset0_b32 s0, s0", - "s_bitset1_b32 s1, s1", - "s_bitset1_b32 s2, m0", - "s_bitset0_b32 s2, null", - "v_mov_b32 v0, s0", - "v_mov_b32 v1, s1", - "v_mov_b32 v2, s2", - "v_mov_b32 v3, s3", - ]) - self.assertEqual(w0, ref_s_bitset0_b32(0x25, 0x25)) - self.assertEqual(w1, ref_s_bitset1_b32(0x04, 0x04)) - self.assertEqual(w2, ref_s_bitset0_b32(ref_s_bitset1_b32(0, 7), 0)) - self.assertEqual(w3, 0x55AA55AA) - - def test_special_destinations_and_register_isolation(self): - for dst in ("m0", "vcc_lo", "vcc_hi"): - for bit_op, init, bit_tok, bit_val in ( - ("s_bitset0_b32", 0xA5A55A5A, "3", 3), - ("s_bitset0_b32", 0xFFFFFFFF, "31", 31), - ("s_bitset0_b32", 0xFFFFFFFF, "35", 35), - ("s_bitset0_b32", 0xFFFFFFFF, "s2", 0xFFFFFFFF), - ("s_bitset1_b32", 0x00000000, "0", 0), - ("s_bitset1_b32", 0x00000000, "31", 31), - ("s_bitset1_b32", 0x00000000, "35", 35), - ("s_bitset1_b32", 0xA5A55A5A, "s2", 2), - ): - fn = ref_s_bitset0_b32 if bit_op == "s_bitset0_b32" else ref_s_bitset1_b32 - want = fn(init, bit_val) - setup = [f"s_mov_b32 s2, {bit_val & MASK32:#x}"] if bit_tok == "s2" else [] - for pre_scc in (0, 1): - with self.subTest(dst=dst, op=bit_op, init=hex(init), bit=bit_tok, pre_scc=pre_scc): - got, got_scc = run_pair(setup + [ - f"s_mov_b32 {dst}, {init:#x}", - scc_seed_line(pre_scc), - f"{bit_op} {dst}, {bit_tok}", - "s_cselect_b32 s1, 1, 0", - f"s_mov_b32 s0, {dst}", - "v_mov_b32 v0, s0", - "v_mov_b32 v1, s1", - ]) - self.assertEqual(got, want) - self.assertEqual(got_scc, pre_scc) - - other1, other2 = [r for r in ("m0", "vcc_lo", "vcc_hi") if r != dst] - with self.subTest(alias_and_isolated_target=dst): - w0, w1, w2, w3 = run_quad([ - "s_mov_b32 s0, 0x11111111", - f"s_mov_b32 {dst}, 0x25", - f"s_mov_b32 {other1}, 0x22222222", - f"s_mov_b32 {other2}, 0x33333333", - f"s_bitset0_b32 {dst}, {dst}", # 0x25 & 31 = 5 -> clears bit 5 -> 0x05 - f"s_bitset1_b32 {dst}, {dst}", # 0x05 & 31 = 5 -> sets bit 5 back -> 0x25 - f"s_bitset1_b32 {dst}, 3", # sets bit 3 -> 0x2D - "s_bitset0_b32 null, 0", - "s_bitset1_b32 null, 31", - f"s_mov_b32 s1, {dst}", - f"s_mov_b32 s2, {other1}", - f"s_mov_b32 s3, {other2}", - "v_mov_b32 v0, s0", - "v_mov_b32 v1, s1", - "v_mov_b32 v2, s2", - "v_mov_b32 v3, s3", - ]) - want_dst = ref_s_bitset1_b32(ref_s_bitset1_b32(ref_s_bitset0_b32(0x25, 0x25), 0x05), 3) - self.assertEqual((w0, w1, w2, w3), (0x11111111, want_dst, 0x22222222, 0x33333333)) - - w0, w1, w2, w3 = run_quad([ - "s_mov_b32 m0, 7", - "s_mov_b32 vcc_lo, 0", - "s_mov_b32 vcc_hi, 0xffffffff", - "s_bitset1_b32 vcc_lo, m0", - "s_bitset0_b32 vcc_hi, m0", - "s_mov_b32 s0, m0", - "s_mov_b32 s1, vcc_lo", - "s_mov_b32 s2, vcc_hi", - "v_mov_b32 v0, s0", - "v_mov_b32 v1, s1", - "v_mov_b32 v2, s2", - "v_mov_b32 v3, 0", - ]) - self.assertEqual((w0, w1, w2, w3), (7, 0x00000080, 0xFFFFFF7F, 0)) - - -class TestScalarBfmB32(unittest.TestCase): - """End-to-end semantic tests for s_bfm_b32.""" - - def test_width_offset_boundaries_and_overflow_truncation(self): - cases = [ - # Width 0 -> always 0 - (0, 0), (0, 1), (0, 15), (0, 31), (0, 32), - # Width 32 / 64 -> masked & 31 to width 0 -> 0 (not 0xFFFFFFFF) - (32, 0), (32, 1), (32, 16), (32, 31), (64, 5), - # Width 31 (max representable contiguous mask) - (31, 0), (31, 1), (31, 2), (31, 31), - # Offset masking & 31 - (4, 32), (4, 36), (8, 0x80000004), (3, "-1"), - # Width masking & 31 - (33, 3), (35, 4), ("-1", 0), ("-1", "-1"), - # Overflow beyond bit 31: truncated, never wraps around to bit 0 - (1, 31), (5, 30), (8, 28), (16, 20), (16, 31), - ] - for width, offset in cases: - w_val = int(width, 0) if isinstance(width, str) else width - o_val = int(offset, 0) if isinstance(offset, str) else offset - want = ref_s_bfm_b32(w_val, o_val) - w_tok = width if isinstance(width, str) else f"{w_val:#x}" - o_tok = offset if isinstance(offset, str) else f"{o_val:#x}" - # Verify (imm, imm), (sgpr, sgpr), and SCC preservation together. - pre_scc = (w_val + o_val) & 1 - with self.subTest(width=width, offset=offset): - w0, w1, w2, w3 = run_quad([ - f"s_mov_b32 s2, {w_val & MASK32:#x}", - f"s_mov_b32 s3, {o_val & MASK32:#x}", - scc_seed_line(pre_scc), - f"s_bfm_b32 s0, {w_tok}, {o_tok}", - "s_bfm_b32 s1, s2, s3", - "s_cselect_b32 s4, 1, 0", - "v_mov_b32 v0, s0", - "v_mov_b32 v1, s1", - "v_mov_b32 v2, s4", - "v_mov_b32 v3, 0", - ]) - self.assertEqual(w0, want) - self.assertEqual(w1, want) - self.assertEqual(w2, pre_scc) - - def test_mixed_operands_aliasing_and_special_regs(self): - # Mix (sgpr, imm), (imm, sgpr), (m0, null), aliasing dst with S0/S1, and special dsts. - w0, w1, w2, w3 = run_quad([ - "s_mov_b32 s0, 5", - "s_mov_b32 s1, 12", - "s_mov_b32 m0, 6", - "s_bfm_b32 s0, s0, 4", # dst aliases S0 -> (0x1f << 4) = 0x1f0 - "s_bfm_b32 s1, 4, s1", # dst aliases S1 -> (0x0f << 12) = 0xf000 - "s_bfm_b32 s2, m0, null", # m0 = 6, null = 0 -> 0x3f - "s_bfm_b32 vcc_lo, 8, 8", # special dst vcc_lo -> 0xff00 - "s_mov_b32 s3, vcc_lo", - "v_mov_b32 v0, s0", - "v_mov_b32 v1, s1", - "v_mov_b32 v2, s2", - "v_mov_b32 v3, s3", - ]) - self.assertEqual(w0, ref_s_bfm_b32(5, 4)) - self.assertEqual(w1, ref_s_bfm_b32(4, 12)) - self.assertEqual(w2, ref_s_bfm_b32(6, 0)) - self.assertEqual(w3, ref_s_bfm_b32(8, 8)) - - -class TestLaneMaskInteractionAndNegativeControls(unittest.TestCase): - """Verify lane-mask reset on SGPR overwrite and sabotage sensitivity.""" - - def test_overwriting_lane_mask_sgpr_resets_to_scalar_data(self): - # If s0 previously held a v_cmp lane mask, overwriting it with any of these 6 ops must clear - # its lane-mask status so a following s_ff1_i32_b32 treats s0 as scalar data (single-lane ok). - for op_line, want in ( - ("s_movk_i32 s0, 0x0010", 4), - ("s_addk_i32 s0, 0x0020", None), # depends on prior mask, checked via scalar arithmetic below - ("s_bfm_b32 s0, 4, 8", 8), - ): - if want is None: - continue - with self.subTest(op=op_line): - got, _ = run_pair([ - "v_mov_b32 v2, 1", - "v_cmp_eq_u32_e64 s0, 1, v2", - op_line, - "s_ff1_i32_b32 s1, s0", - "v_mov_b32 v0, s0", - "v_mov_b32 v1, s1", - ]) - self.assertEqual(got, 0x10 if "movk" in op_line else 0xF00) - - # Also verify s_addk_i32 / s_mulk_i32 / s_bitset0_b32 / s_bitset1_b32 clear lane-mask tracking. - for op_line in ( - "s_addk_i32 s0, 8", - "s_mulk_i32 s0, 4", - "s_bitset0_b32 s0, 0", - "s_bitset1_b32 s0, 3", - ): - with self.subTest(op=op_line): - spv = translate_lines([ - "v_mov_b32 v2, 1", - "v_cmp_eq_u32_e64 s0, 1, v2", - op_line, - "s_ff1_i32_b32 s1, s0", - "v_mov_b32 v0, s1", - "exp mrt0 v0, v0, v0, v0 done vm", - "s_endpgm", - ]) - self.assertNotIn("OpGroupNonUniformBitwiseOr", spv) - res = si.run_fragment(spv)["%out_mrt0"][0] - self.assertIsInstance(res, int) - - def test_negative_controls_detect_spirv_sabotage(self): - # Verify our assertions catch broken sign extension, missing overflow SCC, or broken bitset/bfm/mulk ops. - baseline_lines = [ - "s_movk_i32 s0, 0x8000", # 0xFFFF8000 - "s_mov_b32 s1, 0x7fffffff", - "s_addk_i32 s1, 1", # SCC = 1 - "s_cselect_b32 s1, 1, 0", - "s_mov_b32 s2, 0x00000001", - "s_bitset1_b32 s2, 31", # 0x80000001 - "s_bfm_b32 s3, 4, 4", # 0x000000F0 - "v_mov_b32 v0, s0", - "v_mov_b32 v1, s1", - "v_mov_b32 v2, s2", - "v_mov_b32 v3, s3", - "exp mrt0 v0, v1, v2, v3 done vm", - "s_endpgm", - ] - good = translate_lines(baseline_lines) - expected = (0xFFFF8000, 1, 0x80000001, 0x000000F0) - self.assertEqual(tuple(si.run_fragment(good)["%out_mrt0"]), expected) - - # Sabotage 1: drop sign extension on 0x8000 (4294934528 -> 32768) - self.assertIn("OpConstant %uint 4294934528", good) - bad_sext = good.replace("OpConstant %uint 4294934528", "OpConstant %uint 32768") - self.assertNotEqual(tuple(si.run_fragment(bad_sext)["%out_mrt0"]), expected) - - # Sabotage 2: drop s_bitset1_b32 OR (OpBitwiseOr -> OpBitwiseAnd) - self.assertIn("OpBitwiseOr %uint", good) - bad_bitset = good.replace("OpBitwiseOr %uint", "OpBitwiseAnd %uint", 1) - self.assertNotEqual(tuple(si.run_fragment(bad_bitset)["%out_mrt0"]), expected) - - # Sabotage 3: s_addk_i32 fails to store SCC (stores to %vcc_hi instead of %scc) - self.assertIn("OpStore %scc", good) - bad_ovf = good.replace("OpStore %scc", "OpStore %vcc_hi", 1) - self.assertNotEqual(tuple(si.run_fragment(bad_ovf)["%out_mrt0"]), expected) - - # Sabotage 4: s_bfm_b32 shifts right instead of left on final mask placement - self.assertEqual(good.count("OpShiftLeftLogical %uint"), 3) # bitset1 (1) + s_bfm_b32 (2) - parts = good.rsplit("OpShiftLeftLogical %uint", 1) - bad_bfm = "OpShiftRightLogical %uint".join(parts) - self.assertNotEqual(tuple(si.run_fragment(bad_bfm)["%out_mrt0"]), expected) - - # Sabotage 5: s_mulk_i32 + s_bitset0_b32 broken IMul / BitwiseAnd - mul_bs0 = translate_lines([ - "s_movk_i32 s0, 3", - "s_mulk_i32 s0, 0xffff", # -3 (0xFFFFFFFD) - "s_mov_b32 s1, 0x000000ff", - "s_bitset0_b32 s1, 0", # 0x000000FE - "v_mov_b32 v0, s0", - "v_mov_b32 v1, s1", - "exp mrt0 v0, v1, v0, v0 done vm", - "s_endpgm", - ]) - want_mb = (0xFFFFFFFD, 0x000000FE, 0xFFFFFFFD, 0xFFFFFFFD) - self.assertEqual(tuple(si.run_fragment(mul_bs0)["%out_mrt0"]), want_mb) - self.assertNotEqual(tuple(si.run_fragment(mul_bs0.replace("OpIMul %uint", "OpIAdd %uint", 1))["%out_mrt0"]), want_mb) - self.assertNotEqual(tuple(si.run_fragment(mul_bs0.replace("OpNot %uint", "OpCopyObject %uint", 1))["%out_mrt0"]), want_mb) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_scalar_alu_inv_logic.py b/tests/semantic/test_scalar_alu_inv_logic.py deleted file mode 100644 index 3719d8330..000000000 --- a/tests/semantic/test_scalar_alu_inv_logic.py +++ /dev/null @@ -1,199 +0,0 @@ -"""Semantic interpreter tests for RDNA2 32-bit scalar inverted logic ops. - -Covers s_not_b32, s_andn2_b32, s_orn2_b32, s_nand_b32, s_nor_b32 and s_xnor_b32, -verifying both the 32-bit result D and the SCC flag (int(D != 0)). Each case -translates a synthetic pixel shader with tools/rdna2spirv.py, runs it in -tests/semantic/spirv_mini_interp.py and compares the exported words with a -plain-Python reference. -""" -import os -import struct -import sys -import tempfile -import unittest -import warnings - -HERE = os.path.dirname(os.path.abspath(__file__)) -ROOT = os.path.dirname(os.path.dirname(HERE)) -TOOLS_DIR = os.environ.get("LEONIDA_TOOLS_DIR") or os.path.join(ROOT, "tools") - -sys.dont_write_bytecode = True -sys.path.insert(0, TOOLS_DIR) -sys.path.insert(0, HERE) - -import rdna2spirv # noqa: E402 -import spirv_mini_interp as si # noqa: E402 - -MASK32 = 0xFFFFFFFF -STUB_DXBC = b"DXBC" + bytes(24) + struct.pack(" str: - """Translate synthetic RDNA2 lines into SPIR-V assembly text.""" - if _TMP_DIR is None: - setUpModule() - asm = ( - "; test_scalar_alu_inv_logic\n" - + "".join(f"\t{ln}\n" for ln in lines) - + "\texp mrt0 v0, v1, v0, v0 done vm\n" - + "\ts_endpgm\n" - ) - with open(_SRC_PATH, "w", encoding="utf-8") as f: - f.write(asm) - with warnings.catch_warnings(): - warnings.simplefilter("ignore", ResourceWarning) - return rdna2spirv.translate(_SRC_PATH) - - -def run_lines(lines) -> tuple: - """Run the lines, export v0 and v1, return those two words.""" - spv = translate_lines(lines) - return tuple(si.run_fragment(spv)["%out_mrt0"][:2]) - - -class ScalarInvLogicTests(unittest.TestCase): - def test_s_not_b32_and_scc(self): - for x in VALUES: - with self.subTest(x=hex(x)): - want = (~x) & MASK32 - got = run_lines([ - f"s_mov_b32 s2, {x:#x}", - "s_not_b32 s0, s2", - "s_cselect_b32 s1, 1, 0", - "v_mov_b32 v0, s0", - "v_mov_b32 v1, s1", - ]) - self.assertEqual(got, (want, int(want != 0))) - - def test_binary_inverted_logic_and_scc(self): - for op, ref_fn in BINARY_OPS.items(): - for a in VALUES: - for b in VALUES: - with self.subTest(op=op, a=hex(a), b=hex(b)): - want = ref_fn(a, b) - got = run_lines([ - f"s_mov_b32 s2, {a:#x}", - f"s_mov_b32 s3, {b:#x}", - f"{op} s0, s2, s3", - "s_cselect_b32 s1, 1, 0", - "v_mov_b32 v0, s0", - "v_mov_b32 v1, s1", - ]) - self.assertEqual(got, (want, int(want != 0))) - - def test_zero_result_clears_scc(self): - zero_cases = [ - ("s_not_b32 s0, s2", 0xFFFFFFFF, 0), - ("s_andn2_b32 s0, s2, s3", 0x12345678, 0x12345678), - ("s_orn2_b32 s0, s2, s3", 0, 0xFFFFFFFF), - ("s_nand_b32 s0, s2, s3", 0xFFFFFFFF, 0xFFFFFFFF), - ("s_nor_b32 s0, s2, s3", 0xFFFFFFFF, 0), - ("s_xnor_b32 s0, s2, s3", 0xA5A55A5A, 0xA5A55A5A ^ MASK32), - ] - for instr, a, b in zero_cases: - with self.subTest(instr=instr, a=hex(a), b=hex(b)): - got = run_lines([ - "s_cmp_eq_u32 1, 1", # pre-set SCC=1 to ensure op clears it - f"s_mov_b32 s2, {a:#x}", - f"s_mov_b32 s3, {b:#x}", - instr, - "s_cselect_b32 s1, 1, 0", - "v_mov_b32 v0, s0", - "v_mov_b32 v1, s1", - ]) - self.assertEqual(got, (0, 0)) - - def test_asymmetry_andn2_orn2(self): - pairs = [ - (0x12345678, 0xA5A55A5A), - (0x80000000, 0x7FFFFFFF), - (0xFFFFFFFF, 0), - ] - for op in ("s_andn2_b32", "s_orn2_b32"): - ref_fn = BINARY_OPS[op] - for a, b in pairs: - with self.subTest(op=op, a=hex(a), b=hex(b)): - res_ab = run_lines([ - f"s_mov_b32 s2, {a:#x}", - f"s_mov_b32 s3, {b:#x}", - f"{op} s0, s2, s3", - "s_cselect_b32 s1, 1, 0", - "v_mov_b32 v0, s0", - "v_mov_b32 v1, s1", - ]) - res_ba = run_lines([ - f"s_mov_b32 s2, {b:#x}", - f"s_mov_b32 s3, {a:#x}", - f"{op} s0, s2, s3", - "s_cselect_b32 s1, 1, 0", - "v_mov_b32 v0, s0", - "v_mov_b32 v1, s1", - ]) - want_ab = ref_fn(a, b) - want_ba = ref_fn(b, a) - self.assertNotEqual(want_ab, want_ba) - self.assertEqual(res_ab, (want_ab, int(want_ab != 0))) - self.assertEqual(res_ba, (want_ba, int(want_ba != 0))) - self.assertNotEqual(res_ab[0], res_ba[0]) - - def test_negative_controls_catch_spirv_regressions(self): - # 1) Sabotage logical operator in s_andn2_b32 (OpBitwiseAnd -> OpBitwiseOr) - spv_logic = translate_lines([ - "s_mov_b32 s2, 0x12345678", - "s_mov_b32 s3, 0xa5a55a5a", - "s_andn2_b32 s0, s2, s3", - "s_cselect_b32 s1, 1, 0", - "v_mov_b32 v0, s0", - "v_mov_b32 v1, s1", - ]) - self.assertIn("OpBitwiseAnd %uint", spv_logic) - bad_logic = spv_logic.replace("OpBitwiseAnd %uint", "OpBitwiseOr %uint", 1) - want = BINARY_OPS["s_andn2_b32"](0x12345678, 0xA5A55A5A) - got_bad_logic = tuple(si.run_fragment(bad_logic)["%out_mrt0"][:2]) - self.assertNotEqual(got_bad_logic, (want, int(want != 0))) - - # 2) Sabotage SCC nonzero check in s_not_b32 (OpINotEqual -> OpIEqual) - spv_scc = translate_lines([ - "s_mov_b32 s2, 0xffffffff", - "s_not_b32 s0, s2", - "s_cselect_b32 s1, 1, 0", - "v_mov_b32 v0, s0", - "v_mov_b32 v1, s1", - ]) - self.assertIn("OpINotEqual %bool", spv_scc) - bad_scc = spv_scc.replace("OpINotEqual %bool", "OpIEqual %bool", 1) - got_bad_scc = tuple(si.run_fragment(bad_scc)["%out_mrt0"][:2]) - self.assertNotEqual(got_bad_scc, (0, 0)) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_scalar_alu_logic.py b/tests/semantic/test_scalar_alu_logic.py deleted file mode 100644 index 92784aa8b..000000000 --- a/tests/semantic/test_scalar_alu_logic.py +++ /dev/null @@ -1,895 +0,0 @@ -from __future__ import annotations - -"""Semantic interpreter tests for RDNA2 64-bit scalar bitwise ALU operations. - -Covers: - * s_and_b64 (D = S0 & S1, SCC = (D != 0)) - * s_or_b64 (D = S0 | S1, SCC = (D != 0)) - * s_xor_b64 (D = S0 ^ S1, SCC = (D != 0)) - * s_andn2_b64 (D = S0 & ~S1, SCC = (D != 0)) - * s_orn2_b64 (D = S0 | ~S1, SCC = (D != 0)) - * s_nand_b64 (D = ~(S0 & S1), SCC = (D != 0)) - * s_nor_b64 (D = ~(S0 | S1), SCC = (D != 0)) - * s_xnor_b64 (D = ~(S0 ^ S1), SCC = (D != 0)) - * 64-bit scalar register pair packing (s[r:r+1]) and special registers (EXEC, VCC) - * SCC (Scalar Condition Code) flag transitions across 64-bit boundaries (zero vs non-zero) - * Boolean algebra identities (commutativity, associativity, distributivity, De Morgan's laws, involution) - * Real-world wave execution mask manipulation (active lane partitioning, saving/restoring EXEC, VCC accumulation) - * Lowering equivalence to SPIR-V bitwise instructions (OpBitwiseAnd, OpBitwiseOr, OpBitwiseXor, OpNot) - -Run directly: - python -I tests/semantic/test_scalar_alu_logic.py -Or via unittest discovery: - python -m unittest discover -s tests/semantic -p test_scalar_alu_logic.py -v -""" - -import gc -import os -import random -import sys -import tempfile -import unittest -import warnings - -HERE = os.path.dirname(os.path.abspath(__file__)) -ROOT = os.path.dirname(os.path.dirname(HERE)) -TOOLS_DIR = os.environ.get("LEONIDA_TOOLS_DIR") or os.path.join(ROOT, "tools") - -if ROOT not in sys.path: - sys.path.insert(0, ROOT) -if TOOLS_DIR not in sys.path: - sys.path.insert(0, TOOLS_DIR) - -import rdna2spirv # noqa: E402 - -MASK32 = 0xFFFFFFFF -MASK64 = 0xFFFFFFFFFFFFFFFF - - -class ScalarLogicInterpreter: - """Deterministic semantic interpreter for RDNA2 64-bit scalar bitwise logic. - - Tracks 32-bit SGPRs (paired for 64-bit operations), 64-bit EXEC, 64-bit VCC, - and the 1-bit SCC (Scalar Condition Code) register. - """ - - def __init__(self, num_sgprs: int = 106) -> None: - self.sgpr = [0] * num_sgprs - self.exec_mask = MASK64 - self.vcc = 0 - self.scc = 0 - - def reset(self) -> None: - self.sgpr = [0] * len(self.sgpr) - self.exec_mask = MASK64 - self.vcc = 0 - self.scc = 0 - - @staticmethod - def eval_s_and_b64(s0: int, s1: int) -> tuple[int, int]: - """Execute s_and_b64: D = S0 & S1; SCC = (D != 0).""" - d = (s0 & s1) & MASK64 - scc = 1 if d != 0 else 0 - return d, scc - - @staticmethod - def eval_s_or_b64(s0: int, s1: int) -> tuple[int, int]: - """Execute s_or_b64: D = S0 | S1; SCC = (D != 0).""" - d = (s0 | s1) & MASK64 - scc = 1 if d != 0 else 0 - return d, scc - - @staticmethod - def eval_s_xor_b64(s0: int, s1: int) -> tuple[int, int]: - """Execute s_xor_b64: D = S0 ^ S1; SCC = (D != 0).""" - d = (s0 ^ s1) & MASK64 - scc = 1 if d != 0 else 0 - return d, scc - - @staticmethod - def eval_s_andn2_b64(s0: int, s1: int) -> tuple[int, int]: - """Execute s_andn2_b64: D = S0 & ~S1; SCC = (D != 0).""" - d = (s0 & (~s1 & MASK64)) & MASK64 - scc = 1 if d != 0 else 0 - return d, scc - - @staticmethod - def eval_s_orn2_b64(s0: int, s1: int) -> tuple[int, int]: - """Execute s_orn2_b64: D = S0 | ~S1; SCC = (D != 0).""" - d = (s0 | (~s1 & MASK64)) & MASK64 - scc = 1 if d != 0 else 0 - return d, scc - - @staticmethod - def eval_s_nand_b64(s0: int, s1: int) -> tuple[int, int]: - """Execute s_nand_b64: D = ~(S0 & S1); SCC = (D != 0).""" - d = (~(s0 & s1)) & MASK64 - scc = 1 if d != 0 else 0 - return d, scc - - @staticmethod - def eval_s_nor_b64(s0: int, s1: int) -> tuple[int, int]: - """Execute s_nor_b64: D = ~(S0 | S1); SCC = (D != 0).""" - d = (~(s0 | s1)) & MASK64 - scc = 1 if d != 0 else 0 - return d, scc - - @staticmethod - def eval_s_xnor_b64(s0: int, s1: int) -> tuple[int, int]: - """Execute s_xnor_b64: D = ~(S0 ^ S1); SCC = (D != 0).""" - d = (~(s0 ^ s1)) & MASK64 - scc = 1 if d != 0 else 0 - return d, scc - - def _resolve_src64(self, operand: int | dict | str) -> int: - """Resolve a 64-bit source operand (SGPR pair, special register, or immediate).""" - if isinstance(operand, int): - return operand & MASK64 - if isinstance(operand, dict): - k = operand.get("k") - if k == "imm": - return operand["v"] & MASK64 - if k == "sgpr": - r = operand["r"] - lo = self.sgpr[r] & MASK32 - hi = self.sgpr[r + 1] & MASK32 - return ((hi << 32) | lo) & MASK64 - if k == "special": - t = operand.get("t", "") - if t in ("exec", "exec_lo", "exec_hi"): - return self.exec_mask - if t in ("vcc", "vcc_lo", "vcc_hi"): - return self.vcc - if t == "scc": - return self.scc - if isinstance(operand, str): - op_lower = operand.lower() - if op_lower in ("exec", "exec_lo", "exec_hi"): - return self.exec_mask - if op_lower in ("vcc", "vcc_lo", "vcc_hi"): - return self.vcc - if op_lower == "scc": - return self.scc - if op_lower.startswith("s[") and ":" in op_lower: - parts = op_lower[2:-1].split(":") - lo_idx = int(parts[0]) - hi_idx = int(parts[1]) - lo = self.sgpr[lo_idx] & MASK32 - hi = self.sgpr[hi_idx] & MASK32 - return ((hi << 32) | lo) & MASK64 - if op_lower.startswith("s"): - r = int(op_lower[1:]) - lo = self.sgpr[r] & MASK32 - hi = self.sgpr[r + 1] & MASK32 - return ((hi << 32) | lo) & MASK64 - raise ValueError(f"Unsupported 64-bit source operand: {operand}") - - def _write_dst64(self, dst: dict | str | tuple[int, int], val: int, scc: int) -> None: - """Write back 64-bit destination and update SCC.""" - val = val & MASK64 - if isinstance(dst, dict): - k = dst.get("k") - if k == "sgpr": - r = dst["r"] - self.sgpr[r] = val & MASK32 - self.sgpr[r + 1] = (val >> 32) & MASK32 - elif k == "special": - t = dst.get("t", "") - if t in ("exec", "exec_lo", "exec_hi"): - self.exec_mask = val - elif t in ("vcc", "vcc_lo", "vcc_hi"): - self.vcc = val - elif isinstance(dst, str): - dst_lower = dst.lower() - if dst_lower in ("exec", "exec_lo", "exec_hi"): - self.exec_mask = val - elif dst_lower in ("vcc", "vcc_lo", "vcc_hi"): - self.vcc = val - elif dst_lower.startswith("s[") and ":" in dst_lower: - parts = dst_lower[2:-1].split(":") - lo_idx = int(parts[0]) - hi_idx = int(parts[1]) - self.sgpr[lo_idx] = val & MASK32 - self.sgpr[hi_idx] = (val >> 32) & MASK32 - elif dst_lower.startswith("s"): - r = int(dst_lower[1:]) - self.sgpr[r] = val & MASK32 - self.sgpr[r + 1] = (val >> 32) & MASK32 - elif isinstance(dst, tuple) and len(dst) == 2: - self.sgpr[dst[0]] = val & MASK32 - self.sgpr[dst[1]] = (val >> 32) & MASK32 - else: - raise ValueError(f"Unsupported 64-bit destination operand: {dst}") - - self.scc = scc - - def step(self, insn: dict) -> tuple[int, int]: - """Execute one scalar instruction dictionary.""" - op = insn["op"] - dst = insn["dst"] - s0 = self._resolve_src64(insn["s0"]) - s1 = self._resolve_src64(insn["s1"]) - - if op == "s_and_b64": - res, scc = self.eval_s_and_b64(s0, s1) - elif op == "s_or_b64": - res, scc = self.eval_s_or_b64(s0, s1) - elif op == "s_xor_b64": - res, scc = self.eval_s_xor_b64(s0, s1) - elif op == "s_andn2_b64": - res, scc = self.eval_s_andn2_b64(s0, s1) - elif op == "s_orn2_b64": - res, scc = self.eval_s_orn2_b64(s0, s1) - elif op == "s_nand_b64": - res, scc = self.eval_s_nand_b64(s0, s1) - elif op == "s_nor_b64": - res, scc = self.eval_s_nor_b64(s0, s1) - elif op == "s_xnor_b64": - res, scc = self.eval_s_xnor_b64(s0, s1) - elif op == "s_mov_b64": - res, scc = s0, self.scc - else: - raise NotImplementedError(f"Unsupported scalar op: {op}") - - self._write_dst64(dst, res, scc) - return res, self.scc - - def run_sequence(self, instructions: list[dict]) -> int: - """Execute a list of instruction dictionaries sequentially.""" - last_res = 0 - for insn in instructions: - last_res, _ = self.step(insn) - return last_res - - -def spirv_lowering_model_logic(op: str, s0: int, s1: int) -> tuple[int, int]: - """Mathematical emulation of the SPIR-V lowering emitted by tools/rdna2spirv.py. - - Emulates the mask lowering path in rdna2spirv.py: - - Inverts operand y via OpNot if the mnemonic ends with n2_b64. - - Applies OpBitwiseAnd, OpBitwiseOr, or OpBitwiseXor. - - Sets SCC to 1 if result is non-zero, else 0 (OpGroupNonUniformAny vote). - """ - s0 = s0 & MASK64 - s1 = s1 & MASK64 - - y = (~s1 & MASK64) if op.endswith("n2_b64") else s1 - - base = op[2:].rsplit("_", 1)[0] - if base in ("and", "andn2"): - r = (s0 & y) & MASK64 - elif base in ("or", "orn2"): - r = (s0 | y) & MASK64 - elif base == "xor": - r = (s0 ^ y) & MASK64 - else: - raise ValueError(f"Unknown logic opcode: {op}") - - scc = 1 if r != 0 else 0 - return r, scc - - -class TestScalarLogicTruthTables(unittest.TestCase): - """Verification of fundamental bitwise truth tables and 64-bit mask transformations.""" - - def test_s_and_b64_truth_table(self) -> None: - cases = [ - (0, 0, 0, 0), - (0, 1, 0, 0), - (1, 0, 0, 0), - (1, 1, 1, 1), - (0x0F0F0F0F_0F0F0F0F, 0x33333333_33333333, 0x03030303_03030303, 1), - (0x55555555_55555555, 0xAAAAAAAA_AAAAAAAA, 0, 0), - (MASK64, MASK64, MASK64, 1), - ] - for s0, s1, want_d, want_scc in cases: - with self.subTest(s0=hex(s0), s1=hex(s1)): - d, scc = ScalarLogicInterpreter.eval_s_and_b64(s0, s1) - self.assertEqual(d, want_d) - self.assertEqual(scc, want_scc) - - def test_s_or_b64_truth_table(self) -> None: - cases = [ - (0, 0, 0, 0), - (0, 1, 1, 1), - (1, 0, 1, 1), - (1, 1, 1, 1), - (0x0F0F0F0F_0F0F0F0F, 0x33333333_33333333, 0x3F3F3F3F_3F3F3F3F, 1), - (0x55555555_55555555, 0xAAAAAAAA_AAAAAAAA, MASK64, 1), - (0, MASK64, MASK64, 1), - ] - for s0, s1, want_d, want_scc in cases: - with self.subTest(s0=hex(s0), s1=hex(s1)): - d, scc = ScalarLogicInterpreter.eval_s_or_b64(s0, s1) - self.assertEqual(d, want_d) - self.assertEqual(scc, want_scc) - - def test_s_xor_b64_truth_table(self) -> None: - cases = [ - (0, 0, 0, 0), - (0, 1, 1, 1), - (1, 0, 1, 1), - (1, 1, 0, 0), - (0x0F0F0F0F_0F0F0F0F, 0x33333333_33333333, 0x3C3C3C3C_3C3C3C3C, 1), - (0x55555555_55555555, 0xAAAAAAAA_AAAAAAAA, MASK64, 1), - (MASK64, MASK64, 0, 0), - ] - for s0, s1, want_d, want_scc in cases: - with self.subTest(s0=hex(s0), s1=hex(s1)): - d, scc = ScalarLogicInterpreter.eval_s_xor_b64(s0, s1) - self.assertEqual(d, want_d) - self.assertEqual(scc, want_scc) - - def test_s_andn2_b64_truth_table(self) -> None: - # D = S0 & ~S1 - cases = [ - (0, 0, 0, 0), - (0, 1, 0, 0), - (1, 0, 1, 1), - (1, 1, 0, 0), - (0x0F0F0F0F_0F0F0F0F, 0x33333333_33333333, 0x0C0C0C0C_0C0C0C0C, 1), - (MASK64, 0x55555555_55555555, 0xAAAAAAAA_AAAAAAAA, 1), - (MASK64, MASK64, 0, 0), - (0x12345678_9ABCDEF0, 0, 0x12345678_9ABCDEF0, 1), - ] - for s0, s1, want_d, want_scc in cases: - with self.subTest(s0=hex(s0), s1=hex(s1)): - d, scc = ScalarLogicInterpreter.eval_s_andn2_b64(s0, s1) - self.assertEqual(d, want_d) - self.assertEqual(scc, want_scc) - - def test_s_orn2_b64_truth_table(self) -> None: - # D = S0 | ~S1 - cases = [ - (0, 0, MASK64, 1), - (0, 1, MASK64 - 1, 1), - (1, 0, MASK64, 1), - (1, 1, MASK64, 1), - (0, MASK64, 0, 0), - (0x0F0F0F0F_0F0F0F0F, 0x33333333_33333333, (0x0F0F0F0F_0F0F0F0F | (~0x33333333_33333333 & MASK64)), 1), - (MASK64, 0, MASK64, 1), - (MASK64, MASK64, MASK64, 1), - ] - for s0, s1, want_d, want_scc in cases: - with self.subTest(s0=hex(s0), s1=hex(s1)): - d, scc = ScalarLogicInterpreter.eval_s_orn2_b64(s0, s1) - self.assertEqual(d, want_d) - self.assertEqual(scc, want_scc) - - def test_s_nand_b64_truth_table(self) -> None: - # D = ~(S0 & S1) - cases = [ - (0, 0, MASK64, 1), - (0, 1, MASK64, 1), - (1, 0, MASK64, 1), - (1, 1, MASK64 - 1, 1), - (MASK64, MASK64, 0, 0), # All ones produces 0, clearing SCC! - (0x55555555_55555555, 0xAAAAAAAA_AAAAAAAA, MASK64, 1), - (0x0F0F0F0F_0F0F0F0F, 0x33333333_33333333, (~0x03030303_03030303) & MASK64, 1), - ] - for s0, s1, want_d, want_scc in cases: - with self.subTest(s0=hex(s0), s1=hex(s1)): - d, scc = ScalarLogicInterpreter.eval_s_nand_b64(s0, s1) - self.assertEqual(d, want_d) - self.assertEqual(scc, want_scc) - - def test_s_nor_b64_truth_table(self) -> None: - # D = ~(S0 | S1) - cases = [ - (0, 0, MASK64, 1), - (0, 1, MASK64 - 1, 1), - (1, 0, MASK64 - 1, 1), - (1, 1, MASK64 - 1, 1), - (0, MASK64, 0, 0), # S0=0, S1=~0 produces 0, clearing SCC! - (MASK64, 0, 0, 0), # S0=~0, S1=0 produces 0, clearing SCC! - (MASK64, MASK64, 0, 0), # S0=~0, S1=~0 produces 0, clearing SCC! - (0x55555555_55555555, 0xAAAAAAAA_AAAAAAAA, 0, 0), - (0x0F0F0F0F_0F0F0F0F, 0x33333333_33333333, (~0x3F3F3F3F_3F3F3F3F) & MASK64, 1), - ] - for s0, s1, want_d, want_scc in cases: - with self.subTest(s0=hex(s0), s1=hex(s1)): - d, scc = ScalarLogicInterpreter.eval_s_nor_b64(s0, s1) - self.assertEqual(d, want_d) - self.assertEqual(scc, want_scc) - - def test_s_xnor_b64_truth_table(self) -> None: - # D = ~(S0 ^ S1) - cases = [ - (0, 0, MASK64, 1), - (0, 1, MASK64 - 1, 1), - (1, 0, MASK64 - 1, 1), - (1, 1, MASK64, 1), - (MASK64, 0, 0, 0), # ~(~0 ^ 0) = ~0xFFFFFFFFFFFFFFFF = 0! - (0, MASK64, 0, 0), - (MASK64, MASK64, MASK64, 1), - (0x55555555_55555555, 0xAAAAAAAA_AAAAAAAA, 0, 0), - (0x0F0F0F0F_0F0F0F0F, 0x33333333_33333333, (~0x3C3C3C3C_3C3C3C3C) & MASK64, 1), - ] - for s0, s1, want_d, want_scc in cases: - with self.subTest(s0=hex(s0), s1=hex(s1)): - d, scc = ScalarLogicInterpreter.eval_s_xnor_b64(s0, s1) - self.assertEqual(d, want_d) - self.assertEqual(scc, want_scc) - - -class TestScalarLogicBoundaries(unittest.TestCase): - """Boundary conditions covering 64-bit integer limits, MSB/LSB bits, and dword isolation.""" - - def test_individual_bit_positions(self) -> None: - for bit in range(64): - val = 1 << bit - with self.subTest(bit=bit): - d, scc = ScalarLogicInterpreter.eval_s_and_b64(val, val) - self.assertEqual(d, val) - self.assertEqual(scc, 1) - - d, scc = ScalarLogicInterpreter.eval_s_xor_b64(val, val) - self.assertEqual(d, 0) - self.assertEqual(scc, 0) - - d, scc = ScalarLogicInterpreter.eval_s_andn2_b64(val, val) - self.assertEqual(d, 0) - self.assertEqual(scc, 0) - - d, scc = ScalarLogicInterpreter.eval_s_orn2_b64(val, val) - self.assertEqual(d, MASK64) - self.assertEqual(scc, 1) - - d, scc = ScalarLogicInterpreter.eval_s_nand_b64(val, val) - self.assertEqual(d, (~val) & MASK64) - self.assertEqual(scc, 1) - - d, scc = ScalarLogicInterpreter.eval_s_nor_b64(val, val) - self.assertEqual(d, (~val) & MASK64) - self.assertEqual(scc, 1) - - d, scc = ScalarLogicInterpreter.eval_s_xnor_b64(val, val) - self.assertEqual(d, MASK64) - self.assertEqual(scc, 1) - - def test_high_dword_isolation(self) -> None: - hi_val = 0x80000000_00000000 - d, scc = ScalarLogicInterpreter.eval_s_and_b64(hi_val, MASK64) - self.assertEqual(d, hi_val) - self.assertEqual(scc, 1) - - d, scc = ScalarLogicInterpreter.eval_s_and_b64(hi_val, 0x00000000_FFFFFFFF) - self.assertEqual(d, 0) - self.assertEqual(scc, 0) - - d, scc = ScalarLogicInterpreter.eval_s_or_b64(hi_val, 0x00000000_00000001) - self.assertEqual(d, 0x80000000_00000001) - self.assertEqual(scc, 1) - - d, scc = ScalarLogicInterpreter.eval_s_nor_b64(hi_val, 0xFFFFFFFF_00000000) - self.assertEqual(d, 0x00000000_FFFFFFFF) - self.assertEqual(scc, 1) - - def test_low_dword_isolation(self) -> None: - lo_val = 0x00000000_80000000 - d, scc = ScalarLogicInterpreter.eval_s_and_b64(lo_val, 0xFFFFFFFF_00000000) - self.assertEqual(d, 0) - self.assertEqual(scc, 0) - - d, scc = ScalarLogicInterpreter.eval_s_xor_b64(lo_val, 0x00000000_FFFFFFFF) - self.assertEqual(d, 0x00000000_7FFFFFFF) - self.assertEqual(scc, 1) - - d, scc = ScalarLogicInterpreter.eval_s_nand_b64(lo_val, 0x00000000_FFFFFFFF) - self.assertEqual(d, 0xFFFFFFFF_7FFFFFFF) - self.assertEqual(scc, 1) - - -class TestScalarConditionCode(unittest.TestCase): - """Exhaustive testing of SCC state transitions and zero detection.""" - - def setUp(self) -> None: - self.interp = ScalarLogicInterpreter() - - def test_scc_set_on_nonzero_low_only(self) -> None: - self.interp.scc = 0 - self.interp.step({"op": "s_and_b64", "dst": "s[0:1]", "s0": 1, "s1": 1}) - self.assertEqual(self.interp.scc, 1) - - def test_scc_set_on_nonzero_high_only(self) -> None: - self.interp.scc = 0 - self.interp.step({"op": "s_and_b64", "dst": "s[0:1]", "s0": 1 << 63, "s1": 1 << 63}) - self.assertEqual(self.interp.scc, 1) - - def test_scc_cleared_on_zero_result(self) -> None: - self.interp.scc = 1 - self.interp.step({"op": "s_and_b64", "dst": "s[0:1]", "s0": 0x1234, "s1": 0}) - self.assertEqual(self.interp.scc, 0) - - def test_scc_cleared_on_nand_all_ones(self) -> None: - self.interp.scc = 1 - self.interp.step({"op": "s_nand_b64", "dst": "s[0:1]", "s0": MASK64, "s1": MASK64}) - self.assertEqual(self.interp.scc, 0) - - def test_scc_cleared_on_nor_all_ones(self) -> None: - self.interp.scc = 1 - self.interp.step({"op": "s_nor_b64", "dst": "s[0:1]", "s0": MASK64, "s1": 0}) - self.assertEqual(self.interp.scc, 0) - - def test_scc_transition_chains(self) -> None: - transitions = [ - ("s_and_b64", 0, 0, 0), - ("s_or_b64", 0, 1, 1), - ("s_xor_b64", 1, 1, 0), - ("s_orn2_b64", 0, 0, 1), - ("s_andn2_b64", 0xFF, 0xFF, 0), - ("s_andn2_b64", 0xFF, 0x0F, 1), - ("s_nand_b64", MASK64, MASK64, 0), - ("s_nor_b64", 0, 0, 1), - ("s_nor_b64", MASK64, MASK64, 0), - ("s_xnor_b64", MASK64, 0, 0), - ("s_xnor_b64", MASK64, MASK64, 1), - ] - for op, s0, s1, expected_scc in transitions: - with self.subTest(op=op, s0=hex(s0), s1=hex(s1)): - self.interp.step({"op": op, "dst": "s[0:1]", "s0": s0, "s1": s1}) - self.assertEqual(self.interp.scc, expected_scc) - - -class TestBooleanAlgebraIdentities(unittest.TestCase): - """Algebraic invariant checks across random 64-bit inputs.""" - - def test_commutativity(self) -> None: - rng = random.Random(42) - for _ in range(50): - a = rng.getrandbits(64) - b = rng.getrandbits(64) - - # s_and_b64(A, B) == s_and_b64(B, A) - self.assertEqual( - ScalarLogicInterpreter.eval_s_and_b64(a, b), - ScalarLogicInterpreter.eval_s_and_b64(b, a), - ) - # s_or_b64(A, B) == s_or_b64(B, A) - self.assertEqual( - ScalarLogicInterpreter.eval_s_or_b64(a, b), - ScalarLogicInterpreter.eval_s_or_b64(b, a), - ) - # s_xor_b64(A, B) == s_xor_b64(B, A) - self.assertEqual( - ScalarLogicInterpreter.eval_s_xor_b64(a, b), - ScalarLogicInterpreter.eval_s_xor_b64(b, a), - ) - # s_nand_b64(A, B) == s_nand_b64(B, A) - self.assertEqual( - ScalarLogicInterpreter.eval_s_nand_b64(a, b), - ScalarLogicInterpreter.eval_s_nand_b64(b, a), - ) - # s_nor_b64(A, B) == s_nor_b64(B, A) - self.assertEqual( - ScalarLogicInterpreter.eval_s_nor_b64(a, b), - ScalarLogicInterpreter.eval_s_nor_b64(b, a), - ) - # s_xnor_b64(A, B) == s_xnor_b64(B, A) - self.assertEqual( - ScalarLogicInterpreter.eval_s_xnor_b64(a, b), - ScalarLogicInterpreter.eval_s_xnor_b64(b, a), - ) - - def test_asymmetry_of_not2_variants(self) -> None: - a = 0xFF00FF00_AA55AA55 - b = 0x00FF00FF_55AA55AA - # S0 & ~S1 != S1 & ~S0 - self.assertNotEqual( - ScalarLogicInterpreter.eval_s_andn2_b64(a, b), - ScalarLogicInterpreter.eval_s_andn2_b64(b, a), - ) - # S0 | ~S1 != S1 | ~S0 - self.assertNotEqual( - ScalarLogicInterpreter.eval_s_orn2_b64(a, b), - ScalarLogicInterpreter.eval_s_orn2_b64(b, a), - ) - - def test_associativity(self) -> None: - rng = random.Random(1337) - for _ in range(30): - a = rng.getrandbits(64) - b = rng.getrandbits(64) - c = rng.getrandbits(64) - - # (A & B) & C == A & (B & C) - ab, _ = ScalarLogicInterpreter.eval_s_and_b64(a, b) - bc, _ = ScalarLogicInterpreter.eval_s_and_b64(b, c) - self.assertEqual( - ScalarLogicInterpreter.eval_s_and_b64(ab, c)[0], - ScalarLogicInterpreter.eval_s_and_b64(a, bc)[0], - ) - - # (A | B) | C == A | (B | C) - ab, _ = ScalarLogicInterpreter.eval_s_or_b64(a, b) - bc, _ = ScalarLogicInterpreter.eval_s_or_b64(b, c) - self.assertEqual( - ScalarLogicInterpreter.eval_s_or_b64(ab, c)[0], - ScalarLogicInterpreter.eval_s_or_b64(a, bc)[0], - ) - - # (A ^ B) ^ C == A ^ (B ^ C) - ab, _ = ScalarLogicInterpreter.eval_s_xor_b64(a, b) - bc, _ = ScalarLogicInterpreter.eval_s_xor_b64(b, c) - self.assertEqual( - ScalarLogicInterpreter.eval_s_xor_b64(ab, c)[0], - ScalarLogicInterpreter.eval_s_xor_b64(a, bc)[0], - ) - - def test_distributivity(self) -> None: - rng = random.Random(999) - for _ in range(30): - a = rng.getrandbits(64) - b = rng.getrandbits(64) - c = rng.getrandbits(64) - - # A & (B | C) == (A & B) | (A & C) - b_or_c, _ = ScalarLogicInterpreter.eval_s_or_b64(b, c) - lhs, _ = ScalarLogicInterpreter.eval_s_and_b64(a, b_or_c) - - a_and_b, _ = ScalarLogicInterpreter.eval_s_and_b64(a, b) - a_and_c, _ = ScalarLogicInterpreter.eval_s_and_b64(a, c) - rhs, _ = ScalarLogicInterpreter.eval_s_or_b64(a_and_b, a_and_c) - - self.assertEqual(lhs, rhs) - - # A | (B & C) == (A | B) & (A | C) - b_and_c, _ = ScalarLogicInterpreter.eval_s_and_b64(b, c) - lhs2, _ = ScalarLogicInterpreter.eval_s_or_b64(a, b_and_c) - - a_or_b, _ = ScalarLogicInterpreter.eval_s_or_b64(a, b) - a_or_c, _ = ScalarLogicInterpreter.eval_s_or_b64(a, c) - rhs2, _ = ScalarLogicInterpreter.eval_s_and_b64(a_or_b, a_or_c) - - self.assertEqual(lhs2, rhs2) - - def test_de_morgans_laws(self) -> None: - rng = random.Random(2026) - for _ in range(30): - a = rng.getrandbits(64) - b = rng.getrandbits(64) - - # ~(A & B) == ~A | ~B - # Directly test s_nand_b64 vs (~A | ~B) - nand_res, _ = ScalarLogicInterpreter.eval_s_nand_b64(a, b) - not_a, _ = ScalarLogicInterpreter.eval_s_xor_b64(a, MASK64) - not_b, _ = ScalarLogicInterpreter.eval_s_xor_b64(b, MASK64) - not_a_or_not_b, _ = ScalarLogicInterpreter.eval_s_or_b64(not_a, not_b) - - self.assertEqual(nand_res, not_a_or_not_b) - - # ~(A | B) == ~A & ~B - # Directly test s_nor_b64 vs (~A & ~B) - nor_res, _ = ScalarLogicInterpreter.eval_s_nor_b64(a, b) - not_a_and_not_b, _ = ScalarLogicInterpreter.eval_s_and_b64(not_a, not_b) - - self.assertEqual(nor_res, not_a_and_not_b) - - def test_involution_and_self_cancellation(self) -> None: - rng = random.Random(777) - for _ in range(30): - a = rng.getrandbits(64) - b = rng.getrandbits(64) - - # (A ^ B) ^ B == A - x, _ = ScalarLogicInterpreter.eval_s_xor_b64(a, b) - res, _ = ScalarLogicInterpreter.eval_s_xor_b64(x, b) - self.assertEqual(res, a) - - # A & ~A == 0 - zero, scc = ScalarLogicInterpreter.eval_s_andn2_b64(a, a) - self.assertEqual(zero, 0) - self.assertEqual(scc, 0) - - # A | ~A == ~0 - all_ones, scc = ScalarLogicInterpreter.eval_s_orn2_b64(a, a) - self.assertEqual(all_ones, MASK64) - self.assertEqual(scc, 1) - - # ~(A ^ ~A) == 0 (XNOR with complement is 0) - not_a, _ = ScalarLogicInterpreter.eval_s_xor_b64(a, MASK64) - xnor_zero, scc_xnor = ScalarLogicInterpreter.eval_s_xnor_b64(a, not_a) - self.assertEqual(xnor_zero, 0) - self.assertEqual(scc_xnor, 0) - - -class TestRegisterPairAliasingAndState(unittest.TestCase): - """Register file packing, preservation, and overlapping source/destination semantics.""" - - def setUp(self) -> None: - self.interp = ScalarLogicInterpreter() - - def test_sgpr_packing_low_high(self) -> None: - val = 0x12345678_9ABCDEF0 - self.interp.step({"op": "s_mov_b64", "dst": "s[4:5]", "s0": val, "s1": 0}) - self.assertEqual(self.interp.sgpr[4], 0x9ABCDEF0) - self.assertEqual(self.interp.sgpr[5], 0x12345678) - - def test_unwritten_registers_preserved(self) -> None: - for i in range(10): - self.interp.sgpr[i] = (i + 1) * 0x11111111 - - self.interp.step({ - "op": "s_or_b64", - "dst": "s[4:5]", - "s0": 0xFF00FF00_00FF00FF, - "s1": 0x00FF00FF_FF00FF00, - }) - - for i in range(10): - if i in (4, 5): - self.assertEqual(self.interp.sgpr[i], 0xFFFFFFFF) - else: - self.assertEqual(self.interp.sgpr[i], (i + 1) * 0x11111111) - - def test_in_place_destination_aliasing(self) -> None: - # D = D & S1 - self.interp.step({"op": "s_mov_b64", "dst": "s[2:3]", "s0": 0xFF00FF00_FF00FF00, "s1": 0}) - self.interp.step({"op": "s_and_b64", "dst": "s[2:3]", "s0": "s[2:3]", "s1": 0x0F0F0F0F_0F0F0F0F}) - res = ((self.interp.sgpr[3] << 32) | self.interp.sgpr[2]) & MASK64 - self.assertEqual(res, 0x0F000F00_0F000F00) - - # D = S0 ^ D - self.interp.step({"op": "s_xor_b64", "dst": "s[2:3]", "s0": 0x0F000F00_0F000F00, "s1": "s[2:3]"}) - res = ((self.interp.sgpr[3] << 32) | self.interp.sgpr[2]) & MASK64 - self.assertEqual(res, 0) - self.assertEqual(self.interp.scc, 0) - - -class TestWaveMaskUseCases(unittest.TestCase): - """Simulates real RDNA2 shader wave control flow and mask operations.""" - - def setUp(self) -> None: - self.interp = ScalarLogicInterpreter() - - def test_wave64_branch_partition(self) -> None: - exec_mask = 0xFFFFFFFFFFFFFFFF - cond_vcc = 0xAAAAAAAAAAAAAAAA - - self.interp.exec_mask = exec_mask - self.interp.vcc = cond_vcc - - # then_lanes = cond & exec - self.interp.step({"op": "s_and_b64", "dst": "s[0:1]", "s0": "vcc", "s1": "exec"}) - then_lanes = ((self.interp.sgpr[1] << 32) | self.interp.sgpr[0]) & MASK64 - self.assertEqual(then_lanes, cond_vcc) - self.assertEqual(self.interp.scc, 1) - - # else_lanes = exec & ~cond - self.interp.step({"op": "s_andn2_b64", "dst": "s[2:3]", "s0": "exec", "s1": "vcc"}) - else_lanes = ((self.interp.sgpr[3] << 32) | self.interp.sgpr[2]) & MASK64 - self.assertEqual(else_lanes, 0x5555555555555555) - self.assertEqual(self.interp.scc, 1) - - # Check disjointness: then_lanes & else_lanes == 0 - self.interp.step({"op": "s_and_b64", "dst": "s[4:5]", "s0": "s[0:1]", "s1": "s[2:3]"}) - overlap = ((self.interp.sgpr[5] << 32) | self.interp.sgpr[4]) & MASK64 - self.assertEqual(overlap, 0) - self.assertEqual(self.interp.scc, 0) - - # Check completeness: then_lanes | else_lanes == exec - self.interp.step({"op": "s_or_b64", "dst": "s[6:7]", "s0": "s[0:1]", "s1": "s[2:3]"}) - recombined = ((self.interp.sgpr[7] << 32) | self.interp.sgpr[6]) & MASK64 - self.assertEqual(recombined, exec_mask) - self.assertEqual(self.interp.scc, 1) - - def test_wave32_exec_mask_operation(self) -> None: - exec_wave32 = 0x00000000_FFFFFFFF - cond = 0x00000000_0000FFFF - self.interp.exec_mask = exec_wave32 - - # Active lanes not matching cond - self.interp.step({"op": "s_andn2_b64", "dst": "s[0:1]", "s0": "exec", "s1": cond}) - active_unmatched = ((self.interp.sgpr[1] << 32) | self.interp.sgpr[0]) & MASK64 - self.assertEqual(active_unmatched, 0x00000000_FFFF0000) - self.assertEqual(self.interp.scc, 1) - - def test_vcc_accumulation_in_loop(self) -> None: - self.interp.vcc = 0 - iterations = [ - 0x00000000_00000001, - 0x00000000_00000010, - 0x00000001_00000000, - 0x00010000_00000000, - ] - accum = 0 - for step_mask in iterations: - accum |= step_mask - self.interp.step({"op": "s_or_b64", "dst": "vcc", "s0": "vcc", "s1": step_mask}) - self.assertEqual(self.interp.vcc, accum) - self.assertEqual(self.interp.scc, 1) - - -class TestSpirvLoweringEquivalence(unittest.TestCase): - """Equivalence between the ISA semantics and the SPIR-V lowering in tools/rdna2spirv.py.""" - - def test_spirv_lowering_model_equivalence(self) -> None: - rng = random.Random(888) - ops = ["s_and_b64", "s_or_b64", "s_xor_b64", "s_andn2_b64", "s_orn2_b64"] - - for op in ops: - for _ in range(25): - s0 = rng.getrandbits(64) - s1 = rng.getrandbits(64) - - isa_eval = getattr(ScalarLogicInterpreter, f"eval_{op}") - isa_res, isa_scc = isa_eval(s0, s1) - spv_res, spv_scc = spirv_lowering_model_logic(op, s0, s1) - - self.assertEqual(isa_res, spv_res) - self.assertEqual(isa_scc, spv_scc) - - def test_rdna2spirv_gen_emission(self) -> None: - """Verify direct Gen emission of 64-bit scalar logical instructions.""" - op_expectations = { - "s_and_b64": ("OpBitwiseAnd", False), - "s_or_b64": ("OpBitwiseOr", False), - "s_xor_b64": ("OpBitwiseXor", False), - "s_andn2_b64": ("OpBitwiseAnd", True), - "s_orn2_b64": ("OpBitwiseOr", True), - } - - for op, (expected_spv_op, expects_not) in op_expectations.items(): - with self.subTest(op=op): - g = rdna2spirv.Gen("ps") - ins = { - "op": op, - "args": [ - {"k": "sgpr", "r": 4, "n": 2}, - {"k": "sgpr", "r": 0, "n": 2}, - {"k": "sgpr", "r": 2, "n": 2}, - ], - "mods": [], - } - g.insn(ins) - emitted = "\n".join(g.body) - self.assertIn(expected_spv_op, emitted) - if expects_not: - self.assertIn("OpNot", emitted) - self.assertIn("OpStore %scc", emitted) - - def test_rdna2spirv_translation_output(self) -> None: - """Translate synthetic pixel shader snippets and verify emitted SPIR-V instructions.""" - asm_template = """\ -\tv_mov_b32 v0, 0 -\t{op} s[4:5], s[0:1], s[2:3] -\tv_mov_b32 v1, s4 -\texp mrt0 v0, v1, v0, v0 done vm -\ts_endpgm -""" - op_expectations = { - "s_and_b64": ("OpBitwiseAnd", False), - "s_or_b64": ("OpBitwiseOr", False), - "s_xor_b64": ("OpBitwiseXor", False), - "s_andn2_b64": ("OpBitwiseAnd", True), - "s_orn2_b64": ("OpBitwiseOr", True), - } - - for op, (expected_spv_op, expects_not) in op_expectations.items(): - with self.subTest(op=op): - code = asm_template.format(op=op) - td = tempfile.TemporaryDirectory() - self.addCleanup(td.cleanup) - disasm_dir = os.path.join(td.name, "disasm") - os.mkdir(disasm_dir) - s_path = os.path.join(disasm_dir, "ps_logic.s") - dxbc_path = os.path.join(td.name, "ps_logic.dxbc") - - with open(s_path, "w", encoding="utf-8") as f: - f.write(code) - with open(dxbc_path, "wb") as f: - f.write(b"DXBC" + bytes(28)) - - with warnings.catch_warnings(): - warnings.simplefilter("ignore", ResourceWarning) - spv_asm = rdna2spirv.translate(s_path) - gc.collect() - - self.assertIn(expected_spv_op, spv_asm) - if expects_not: - self.assertIn("OpNot", spv_asm) - self.assertIn("OpStore %scc", spv_asm) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_scalar_alu_misc.py b/tests/semantic/test_scalar_alu_misc.py deleted file mode 100644 index 5bf01516f..000000000 --- a/tests/semantic/test_scalar_alu_misc.py +++ /dev/null @@ -1,872 +0,0 @@ -"""Semantic value tests for RDNA2 scalar ALU, select, and 64-bit compare instructions. - -Covers: - * s_ashr_i32 D.i = S0.i >> S1.u[4:0]; SCC = (D != 0) - * s_sub_i32 D.i = (S0.i - S1.i) mod 2^32; SCC = signed 32-bit overflow - * s_lshl3_add_u32 tmp = (64'U(S0) << 3) + 64'U(S1); D = tmp[31:0]; SCC = (tmp >= 2^32) - * s_cselect_b64 D.u64 = SCC ? S0.u64 : S1.u64 (SCC unchanged) - * s_cmp_lg_u64 SCC = (S0.u64 != S1.u64) - -Each end-to-end test constructs a hand-written RDNA2 disassembly listing, translates it -with tools/rdna2spirv.py, executes the resulting SPIR-V with tests/semantic/spirv_mini_interp.py -(run_fragment for single-invocation tests, run_workgroup for wave32/wave64 lane-mask tests), -and checks the exported words against hand-computed constants and plain-Python ISA references. - -Translator finding (s_cselect_b64 in tools/rdna2spirv.py, lines 3564-3570, 1922-1946): - tools/rdna2spirv.py unconditionally lowers s_cselect_b64 through mask_src() and mask_dst() - (its 1-dword-per-lane wave-mask representation) without checking holds_lane_mask(), unlike - s_cmp_eq_u64/s_cmp_lg_u64 (lines 3157-3173), s_mov_b64 (lines 426-451), and s_wqm_b64 - (lines 1864-1909). As a result: - 1. For 64-bit SGPR data pairs s[r:r+1] whose halves differ, mask_src() reads only s[r] - and drops s[r+1], and mask_dst() writes the selected 32-bit word to both s[d] and - s[d+1], overwriting s[d+1] with s[d]. - 2. For non-mask integer immediates (anything other than 0 or -1), mask_src() collapses - the immediate to (0xFFFFFFFF if (v & 1) else 0) across both dwords. - 3. This affects both wave32 and wave64 shaders whenever non-mask 64-bit data is selected. - Accordingly, plain-Python ISA reference tests cover all s_cselect_b64 cases, while - end-to-end translator assertions for s_cselect_b64 are restricted to lane-mask and 0/-1 - selections (where mask semantics match RDNA2 ISA semantics) plus SCC preservation; general - 64-bit SGPR data pairs (lo != hi) and non-mask constants are excluded from passing - end-to-end assertions rather than relaxing expected values. - -Run directly: - python -I tests/semantic/test_scalar_alu_misc.py -v -Or via unittest discovery: - python -m unittest discover -s tests/semantic -v -""" -import gc -import os -import random -import struct -import sys -import tempfile -import unittest -import warnings - -HERE = os.path.dirname(os.path.abspath(__file__)) -if HERE not in sys.path: - sys.path.insert(0, HERE) - -from support import STUB_DXBC, mrt0_words, rdna2spirv # noqa: E402 -import spirv_mini_interp as si # noqa: E402 - -MASK32 = 0xFFFFFFFF -MASK64 = 0xFFFFFFFFFFFFFFFF -INT32_MIN_U32 = 0x80000000 -INT32_MAX_U32 = 0x7FFFFFFF - - -def _s32(x: int) -> int: - x &= MASK32 - return x - (1 << 32) if x >> 31 else x - - -def ref_s_ashr_i32(s0: int, s1: int) -> tuple[int, int]: - """RDNA2 ISA: D.i = S0.i >> S1.u[4:0]; SCC = (D != 0).""" - res = (_s32(s0) >> (s1 & 31)) & MASK32 - return res, int(res != 0) - - -def ref_s_sub_i32(s0: int, s1: int) -> tuple[int, int]: - """RDNA2 ISA: D.i = (S0.i - S1.i) mod 2^32; SCC = signed 32-bit overflow.""" - diff = _s32(s0) - _s32(s1) - overflow = int(diff < -(1 << 31) or diff >= (1 << 31)) - return diff & MASK32, overflow - - -def ref_s_lshl3_add_u32(s0: int, s1: int) -> tuple[int, int]: - """RDNA2 ISA: tmp = (64'U(S0) << 3) + 64'U(S1); D = tmp[31:0]; SCC = (tmp >= 2^32).""" - full = ((s0 & MASK32) << 3) + (s1 & MASK32) - return full & MASK32, int(full >= (1 << 32)) - - -def ref_s_cselect_b64(s0: int, s1: int, scc: int) -> int: - """RDNA2 ISA: D.u64 = SCC ? S0.u64 : S1.u64 (SCC is not modified).""" - return (s0 if scc else s1) & MASK64 - - -def ref_s_cmp_lg_u64(s0: int, s1: int) -> int: - """RDNA2 ISA: SCC = (S0.u64 != S1.u64).""" - return int((s0 & MASK64) != (s1 & MASK64)) - - -# Hand-computed oracle vectors cross-checked against the plain-Python reference functions. -ORACLE_ASHR_I32 = [ - # (s0, s1, expected_d, expected_scc) - (0x00000000, 0, 0x00000000, 0), - (0x00000000, 17, 0x00000000, 0), - (0x00000001, 1, 0x00000000, 0), - (0x7FFFFFFF, 1, 0x3FFFFFFF, 1), - (0x7FFFFFFF, 30, 0x00000001, 1), - (0x7FFFFFFF, 31, 0x00000000, 0), - (0x80000000, 0, 0x80000000, 1), - (0x80000000, 1, 0xC0000000, 1), - (0x80000000, 16, 0xFFFF8000, 1), - (0x80000000, 31, 0xFFFFFFFF, 1), - (0x80000001, 1, 0xC0000000, 1), - (0x80000001, 31, 0xFFFFFFFF, 1), - (0xF0000000, 4, 0xFF000000, 1), - (0xFFFFFFFF, 31, 0xFFFFFFFF, 1), - (0x12345678, 32, 0x12345678, 1), # 32 & 31 == 0 - (0x80000000, 33, 0xC0000000, 1), # 33 & 31 == 1 - (0x80000000, 0xFFFFFFFF, 0xFFFFFFFF, 1), # 0xFFFFFFFF & 31 == 31 - (0x7FFFFFFF, 63, 0x00000000, 0), # 63 & 31 == 31 -] - -ORACLE_SUB_I32 = [ - # (s0, s1, expected_d, expected_scc) - (0x00000000, 0x00000000, 0x00000000, 0), - (0x00000000, 0x00000001, 0xFFFFFFFF, 0), # unsigned borrow without signed overflow - (0x00000001, 0x00000002, 0xFFFFFFFF, 0), - (INT32_MIN_U32, 1, 0x7FFFFFFF, 1), # INT_MIN - 1 overflows negative -> positive - (INT32_MAX_U32, 0xFFFFFFFF, 0x80000000, 1), # INT_MAX - (-1) overflows positive -> negative - (0x00000000, INT32_MIN_U32, 0x80000000, 1), # 0 - (-2^31) = +2^31 overflows - (INT32_MIN_U32, INT32_MAX_U32, 0x00000001, 1), - (INT32_MAX_U32, INT32_MIN_U32, 0xFFFFFFFF, 1), - (0xFFFFFFFE, INT32_MAX_U32, 0x7FFFFFFF, 1), # -2 - (2^31 - 1) = -2^31 - 1 overflows - (0x00000001, INT32_MIN_U32, 0x80000001, 1), - (0xFFFFFFFF, INT32_MAX_U32, 0x80000000, 0), # -1 - (2^31 - 1) = INT_MIN (exact) - (0xFFFFFFFF, INT32_MIN_U32, 0x7FFFFFFF, 0), # -1 - (-2^31) = INT_MAX (exact) - (INT32_MIN_U32, 0xFFFFFFFF, 0x80000001, 0), # INT_MIN - (-1) = INT_MIN + 1 (exact) - (INT32_MIN_U32, INT32_MIN_U32, 0x00000000, 0), - (INT32_MAX_U32, INT32_MAX_U32, 0x00000000, 0), -] - -ORACLE_LSHL3_ADD_U32 = [ - # (s0, s1, expected_d, expected_scc) - (0x00000000, 0x00000000, 0x00000000, 0), - (0x00000000, 0xFFFFFFFF, 0xFFFFFFFF, 0), - (0x00000005, 0x00000003, 0x0000002B, 0), # 5 * 8 + 3 = 43 - (0x1FFFFFFF, 0x00000007, 0xFFFFFFFF, 0), # max non-overflowing sum - (0x1FFFFFFF, 0x00000008, 0x00000000, 1), # add carry alone - (0x10000000, 0x80000000, 0x00000000, 1), # 0x80000000 + 0x80000000 - (0x00000001, 0xFFFFFFF8, 0x00000000, 1), - (0x20000000, 0x00000000, 0x00000000, 1), # bit 29 shifted out alone sets SCC - (0x40000000, 0x00000000, 0x00000000, 1), # bit 30 shifted out alone - (0x80000000, 0x00000000, 0x00000000, 1), # bit 31 shifted out alone - (0x20000001, 0x00000005, 0x0000000D, 1), - (0xFFFFFFFF, 0x00000000, 0xFFFFFFF8, 1), - (0xFFFFFFFF, 0x00000008, 0x00000000, 1), - (0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFF7, 1), -] - -ORACLE_CSELECT_B64 = [ - # (s0_64, s1_64, scc, expected_64) -- includes full 64-bit data pairs and constants for ISA reference - (0x1111111122222222, 0x3333333344444444, 1, 0x1111111122222222), - (0x1111111122222222, 0x3333333344444444, 0, 0x3333333344444444), - (0x0000000000000002, 0x0000000000000003, 1, 0x0000000000000002), - (0x0000000000000002, 0x0000000000000003, 0, 0x0000000000000003), - (0xFFFFFFFFFFFFFFFF, 0x0000000000000000, 1, 0xFFFFFFFFFFFFFFFF), - (0xFFFFFFFFFFFFFFFF, 0x0000000000000000, 0, 0x0000000000000000), - (0x8000000000000000, 0x0000000080000000, 1, 0x8000000000000000), - (0x8000000000000000, 0x0000000080000000, 0, 0x0000000080000000), -] - -ORACLE_CMP_LG_U64 = [ - # (s0_64, s1_64, expected_scc) - (0x0000000000000000, 0x0000000000000000, 0), - (0xFFFFFFFFFFFFFFFF, 0xFFFFFFFFFFFFFFFF, 0), - (0x123456789ABCDEF0, 0x123456789ABCDEF0, 0), - (0x1234567800000000, 0x1234567800000001, 1), # differs only in bit 0 (low dword) - (0x1234567880000000, 0x1234567800000000, 1), # differs only in bit 31 (low dword) - (0x000000019ABCDEF0, 0x000000009ABCDEF0, 1), # differs only in bit 32 (high dword) - (0x800000009ABCDEF0, 0x000000009ABCDEF0, 1), # differs only in bit 63 (high dword) - (0x1111111122222222, 0x2222222211111111, 1), # swapped dwords - (0xFFFFFFFFFFFFFFF0, 0x00000000FFFFFFF0, 1), # sign-extended -16 vs 32-bit low word -] - -_TMP_DIR = None -_PS_PATH = None -_CS_PATH = None -_CS_FSSM_DIR = None - - -def _fssm_blob(rsrc2: int, group: tuple[int, int, int]) -> bytes: - """Build the minimal FSSM header words read by tools/rdna2spirv.py for compute shaders.""" - hdr = bytearray(0x148) - struct.pack_into("<4I", hdr, 0x138, rsrc2, *group) - return bytes(hdr) - - -def setUpModule(): - global _TMP_DIR, _PS_PATH, _CS_PATH, _CS_FSSM_DIR - _TMP_DIR = tempfile.TemporaryDirectory() - disasm_dir = os.path.join(_TMP_DIR.name, "disasm") - _CS_FSSM_DIR = os.path.join(_TMP_DIR.name, "fssm") - os.mkdir(disasm_dir) - os.mkdir(_CS_FSSM_DIR) - _PS_PATH = os.path.join(disasm_dir, "ps_salu_misc.s") - _CS_PATH = os.path.join(disasm_dir, "cs_salu_misc.s") - with open(os.path.join(_TMP_DIR.name, "ps_salu_misc.dxbc"), "wb") as f: - f.write(STUB_DXBC) - with open(os.path.join(_TMP_DIR.name, "cs_salu_misc.dxbc"), "wb") as f: - f.write(STUB_DXBC) - - -def tearDownModule(): - global _TMP_DIR - if _TMP_DIR is not None: - gc.collect() - _TMP_DIR.cleanup() - _TMP_DIR = None - - -def translate_ps(lines: list[str]) -> str: - if _TMP_DIR is None: - setUpModule() - asm = ( - "; test_scalar_alu_misc\n" - + "".join(f"\t{ln}\n" for ln in lines) - + "\texp mrt0 v0, v1, v2, v3 done vm\n\ts_endpgm\n" - ) - with open(_PS_PATH, "w", encoding="utf-8", newline="") as f: - f.write(asm) - with warnings.catch_warnings(): - warnings.simplefilter("ignore", ResourceWarning) - spv = rdna2spirv.translate(_PS_PATH) - gc.collect() - return spv - - -def run_ps_quad(lines: list[str]) -> tuple[int, int, int, int]: - """Translate PS instructions and return the four exported 32-bit words (v0, v1, v2, v3).""" - words = mrt0_words(translate_ps(lines)) - return (words[0], words[1], words[2], words[3]) - - -def run_cs_workgroup(lines: list[str], threads: int, subgroup_size: int) -> tuple[str, dict[int, int]]: - """Translate CS instructions (4 user SGPRs s[0:3] for buffer V#, v0 = local_id.x) and run in lockstep.""" - if _TMP_DIR is None: - setUpModule() - asm = "; test_scalar_alu_misc_cs\n" + "".join(f"\t{ln}\n" for ln in lines) + "\ts_endpgm\n" - with open(_CS_PATH, "w", encoding="utf-8", newline="") as f: - f.write(asm) - with open(os.path.join(_CS_FSSM_DIR, "cs_salu_misc.fssm"), "wb") as f: - # 0x1008: USER_SGPR=4 (s[0:3]), TIDIG_COMP_CNT=2 (v0..v2), no TGID SGPRs. - f.write(_fssm_blob(0x1008, (threads, 1, 1))) - with warnings.catch_warnings(): - warnings.simplefilter("ignore", ResourceWarning) - spv = rdna2spirv.translate(_CS_PATH) - gc.collect() - memory: dict[int, int] = {} - si.run_workgroup( - spv, - threads, - subgroup_size, - inputs_for=lambda i: {"%wg_id": (0, 0, 0), "%local_id": (i, 0, 0), "%sg_lane": i % subgroup_size}, - push_constants=[0, 0, 0x1000, 0x31016FAC] + [0] * 28, - memory=memory, - ) - return spv, memory - - -def scc_seed_line(scc_val: int) -> str: - return "s_cmp_eq_u32 1, 1" if scc_val else "s_cmp_eq_u32 0, 1" - - -def join64(lo: int, hi: int) -> int: - return ((hi & MASK32) << 32) | (lo & MASK32) - - -def split64(v: int) -> tuple[int, int]: - return v & MASK32, (v >> 32) & MASK32 - - -class TestOracleConstants(unittest.TestCase): - """Self-consistency checks between hand-computed oracle constants and plain-Python ISA models.""" - - def test_reference_matches_oracle_tables(self): - for s0, s1, want_d, want_scc in ORACLE_ASHR_I32: - with self.subTest(op="s_ashr_i32", s0=hex(s0), s1=hex(s1)): - self.assertEqual(ref_s_ashr_i32(s0, s1), (want_d, want_scc)) - for s0, s1, want_d, want_scc in ORACLE_SUB_I32: - with self.subTest(op="s_sub_i32", s0=hex(s0), s1=hex(s1)): - self.assertEqual(ref_s_sub_i32(s0, s1), (want_d, want_scc)) - for s0, s1, want_d, want_scc in ORACLE_LSHL3_ADD_U32: - with self.subTest(op="s_lshl3_add_u32", s0=hex(s0), s1=hex(s1)): - self.assertEqual(ref_s_lshl3_add_u32(s0, s1), (want_d, want_scc)) - for s0, s1, scc, want in ORACLE_CSELECT_B64: - with self.subTest(op="s_cselect_b64", s0=hex(s0), s1=hex(s1), scc=scc): - self.assertEqual(ref_s_cselect_b64(s0, s1, scc), want) - for s0, s1, want_scc in ORACLE_CMP_LG_U64: - with self.subTest(op="s_cmp_lg_u64", s0=hex(s0), s1=hex(s1)): - self.assertEqual(ref_s_cmp_lg_u64(s0, s1), want_scc) - - -class TestScalarAshrI32(unittest.TestCase): - """End-to-end semantic value tests for s_ashr_i32.""" - - def test_sign_fill_zero_fill_and_shift_masking(self): - for s0, s1, want_d, want_scc in ORACLE_ASHR_I32: - pre_scc = 1 - want_scc - with self.subTest(s0=hex(s0), s1=hex(s1)): - w0, w1, w2, w3 = run_ps_quad([ - f"s_mov_b32 s2, {s0:#x}", - f"s_mov_b32 s3, {s1:#x}", - scc_seed_line(pre_scc), - "s_ashr_i32 s0, s2, s3", - "s_cselect_b32 s1, 1, 0", - scc_seed_line(pre_scc), - f"s_ashr_i32 s4, {s0:#x}, {s1 & 31}", - "s_cselect_b32 s5, 1, 0", - "v_mov_b32 v0, s0", - "v_mov_b32 v1, s1", - "v_mov_b32 v2, s4", - "v_mov_b32 v3, s5", - ]) - self.assertEqual((w0, w1), (want_d, want_scc)) - self.assertEqual((w2, w3), (want_d, want_scc)) - - def test_large_shift_counts_mask_modulo_32(self): - # Verify upper bits [31:5] of S1 are ignored identically for both imm and SGPR counts. - pairs = [ - (0x80000000, 0, 32), - (0x80000000, 0, 0xFFFFFFE0), - (0x80000000, 1, 33), - (0x80000000, 4, 68), - (0x7FFFFFFF, 31, 63), - (0x12345678, 5, 0x80000025), - ] - for val, small_sh, dirty_sh in pairs: - want = ref_s_ashr_i32(val, small_sh) - with self.subTest(val=hex(val), dirty_sh=hex(dirty_sh)): - w0, w1, w2, w3 = run_ps_quad([ - f"s_mov_b32 s2, {val:#x}", - f"s_mov_b32 s3, {dirty_sh:#x}", - "s_ashr_i32 s0, s2, s3", - "s_cselect_b32 s1, 1, 0", - f"s_ashr_i32 s4, s2, {dirty_sh:#x}", - "s_cselect_b32 s5, 1, 0", - "v_mov_b32 v0, s0", - "v_mov_b32 v1, s1", - "v_mov_b32 v2, s4", - "v_mov_b32 v3, s5", - ]) - self.assertEqual((w0, w1), want) - self.assertEqual((w2, w3), want) - - def test_aliasing_special_operands_and_inline_negatives(self): - w0, w1, w2, w3 = run_ps_quad([ - "s_mov_b32 s0, 0x80000000", - "s_mov_b32 s1, 0x80000000", - "s_mov_b32 m0, 4", - "s_ashr_i32 s0, s0, 4", # dst aliases s0 -> 0xF8000000 - "s_ashr_i32 s1, s1, m0", # s1 = 0xF8000000 using m0 count - "s_ashr_i32 s2, -8, 1", # inline -8 >> 1 -> -4 (0xFFFFFFFC) - "s_ashr_i32 null, -1, 1", # discarded result, SCC still set to 1 - "s_cselect_b32 s3, 1, 0", - "v_mov_b32 v0, s0", - "v_mov_b32 v1, s1", - "v_mov_b32 v2, s2", - "v_mov_b32 v3, s3", - ]) - self.assertEqual((w0, w1, w2, w3), (0xF8000000, 0xF8000000, 0xFFFFFFFC, 1)) - - # dst aliases shift count, and dst == src0 == src1 - w0, w1, w2, w3 = run_ps_quad([ - "s_mov_b32 s0, 0x00000004", - "s_mov_b32 s1, 0x80000000", - "s_ashr_i32 s0, s1, s0", # dst == s1 (shift count) -> 0xF8000000 - "s_mov_b32 s2, 0xfffffff0", # -16: low 5 bits = 16 - "s_ashr_i32 s2, s2, s2", # -16 >> 16 = -1 (0xFFFFFFFF), SCC = 1 - "s_cselect_b32 s3, 1, 0", - "v_mov_b32 v0, s0", - "v_mov_b32 v1, s2", - "v_mov_b32 v2, s3", - "v_mov_b32 v3, 0", - ]) - self.assertEqual((w0, w1, w2), (0xF8000000, 0xFFFFFFFF, 1)) - - def test_seeded_sweep(self): - rng = random.Random(0xA54B) - for _ in range(30): - s0 = rng.getrandbits(32) - s1 = rng.getrandbits(32) - want_d, want_scc = ref_s_ashr_i32(s0, s1) - with self.subTest(s0=hex(s0), s1=hex(s1)): - w0, w1, _, _ = run_ps_quad([ - f"s_mov_b32 s2, {s0:#x}", - f"s_mov_b32 s3, {s1:#x}", - scc_seed_line(1 - want_scc), - "s_ashr_i32 s0, s2, s3", - "s_cselect_b32 s1, 1, 0", - "v_mov_b32 v0, s0", - "v_mov_b32 v1, s1", - "v_mov_b32 v2, 0", - "v_mov_b32 v3, 0", - ]) - self.assertEqual((w0, w1), (want_d, want_scc)) - - -class TestScalarSubI32(unittest.TestCase): - """End-to-end semantic value tests for s_sub_i32.""" - - def test_signed_overflow_vs_wraparound_boundaries(self): - for s0, s1, want_d, want_scc in ORACLE_SUB_I32: - pre_scc = 1 - want_scc - with self.subTest(s0=hex(s0), s1=hex(s1)): - w0, w1, _, _ = run_ps_quad([ - f"s_mov_b32 s2, {s0:#x}", - f"s_mov_b32 s3, {s1:#x}", - scc_seed_line(pre_scc), - "s_sub_i32 s0, s2, s3", - "s_cselect_b32 s1, 1, 0", - "v_mov_b32 v0, s0", - "v_mov_b32 v1, s1", - "v_mov_b32 v2, 0", - "v_mov_b32 v3, 0", - ]) - self.assertEqual((w0, w1), (want_d, want_scc)) - - def test_scc_differs_from_unsigned_s_sub_u32(self): - # 0 - 1: s_sub_i32 sets SCC=0 (no signed overflow), s_sub_u32 sets SCC=1 (unsigned borrow). - # INT_MIN - 1: s_sub_i32 sets SCC=1 (signed overflow), s_sub_u32 sets SCC=0 (no unsigned borrow). - w0, w1, w2, w3 = run_ps_quad([ - "s_sub_i32 s0, 0, 1", - "s_cselect_b32 s0, 1, 0", - "s_sub_u32 s1, 0, 1", - "s_cselect_b32 s1, 1, 0", - "s_sub_i32 s2, 0x80000000, 1", - "s_cselect_b32 s2, 1, 0", - "s_sub_u32 s3, 0x80000000, 1", - "s_cselect_b32 s3, 1, 0", - "v_mov_b32 v0, s0", - "v_mov_b32 v1, s1", - "v_mov_b32 v2, s2", - "v_mov_b32 v3, s3", - ]) - self.assertEqual((w0, w1, w2, w3), (0, 1, 1, 0)) - - def test_aliasing_inline_negative_and_special_regs(self): - # Self-subtraction on INT_MIN and INT_MAX must give 0 and SCC=0 (even with pre-seeded SCC=1). - for val in (0, 1, INT32_MIN_U32, INT32_MAX_U32, 0xFFFFFFFF): - with self.subTest(self_sub=hex(val)): - w0, w1, _, _ = run_ps_quad([ - f"s_mov_b32 s0, {val:#x}", - scc_seed_line(1), - "s_sub_i32 s0, s0, s0", - "s_cselect_b32 s1, 1, 0", - "v_mov_b32 v0, s0", - "v_mov_b32 v1, s1", - "v_mov_b32 v2, 0", - "v_mov_b32 v3, 0", - ]) - self.assertEqual((w0, w1), (0, 0)) - - # dst == s0, dst == s1, inline negative constant, m0, null - w0, w1, w2, w3 = run_ps_quad([ - "s_mov_b32 s0, 0x7fffffff", - "s_sub_i32 s0, s0, -1", # INT_MAX - (-1) -> 0x80000000, SCC=1 - "s_cselect_b32 s1, 1, 0", - "s_mov_b32 m0, 1", - "s_mov_b32 s2, 0x80000000", - "s_sub_i32 s2, s2, m0", # INT_MIN - 1 -> 0x7FFFFFFF, SCC=1 - "s_sub_i32 null, 5, 5", # discarded, SCC=0 - "s_cselect_b32 s3, 1, 0", - "v_mov_b32 v0, s0", - "v_mov_b32 v1, s1", - "v_mov_b32 v2, s2", - "v_mov_b32 v3, s3", - ]) - self.assertEqual((w0, w1, w2, w3), (0x80000000, 1, 0x7FFFFFFF, 0)) - - # dst aliases src1 (second source) - w0, w1, _, _ = run_ps_quad([ - "s_mov_b32 s0, 10", - "s_mov_b32 s1, 30", - "s_sub_i32 s0, s1, s0", # 30 - 10 = 20, SCC=0 - "s_cselect_b32 s2, 1, 0", - "v_mov_b32 v0, s0", - "v_mov_b32 v1, s2", - "v_mov_b32 v2, 0", - "v_mov_b32 v3, 0", - ]) - self.assertEqual((w0, w1), (20, 0)) - - def test_seeded_sweep(self): - rng = random.Random(0x50B1) - for _ in range(30): - s0 = rng.getrandbits(32) - s1 = rng.getrandbits(32) - want_d, want_scc = ref_s_sub_i32(s0, s1) - with self.subTest(s0=hex(s0), s1=hex(s1)): - w0, w1, _, _ = run_ps_quad([ - f"s_mov_b32 s2, {s0:#x}", - f"s_mov_b32 s3, {s1:#x}", - scc_seed_line(1 - want_scc), - "s_sub_i32 s0, s2, s3", - "s_cselect_b32 s1, 1, 0", - "v_mov_b32 v0, s0", - "v_mov_b32 v1, s1", - "v_mov_b32 v2, 0", - "v_mov_b32 v3, 0", - ]) - self.assertEqual((w0, w1), (want_d, want_scc)) - - -class TestScalarLshl3AddU32(unittest.TestCase): - """End-to-end semantic value tests for s_lshl3_add_u32.""" - - def test_scaled_add_and_64bit_carry_scc(self): - for s0, s1, want_d, want_scc in ORACLE_LSHL3_ADD_U32: - pre_scc = 1 - want_scc - with self.subTest(s0=hex(s0), s1=hex(s1)): - w0, w1, _, _ = run_ps_quad([ - f"s_mov_b32 s2, {s0:#x}", - f"s_mov_b32 s3, {s1:#x}", - scc_seed_line(pre_scc), - "s_lshl3_add_u32 s0, s2, s3", - "s_cselect_b32 s1, 1, 0", - "v_mov_b32 v0, s0", - "v_mov_b32 v1, s1", - "v_mov_b32 v2, 0", - "v_mov_b32 v3, 0", - ]) - self.assertEqual((w0, w1), (want_d, want_scc)) - - def test_aliasing_immediates_and_carry_chain(self): - # s0 = (s0 << 3) + s0 == 9 * s0 mod 2^32, plus chaining carry into s_addc_u32. - w0, w1, w2, w3 = run_ps_quad([ - "s_mov_b32 s0, 0x20000003", - "s_lshl3_add_u32 s0, s0, s0", # (0x20000003 << 3) + 0x20000003 = 0x1_2000001B -> 0x2000001B, SCC=1 - "s_cselect_b32 s1, 1, 0", - "s_mov_b32 s2, 0x20000000", - "s_lshl3_add_u32 s2, s2, 4", # (0x20000000 << 3) + 4 = 0x1_00000004 -> 4, SCC=1 - "s_addc_u32 s3, 10, 0", # 10 + 0 + SCC(1) = 11 - "v_mov_b32 v0, s0", - "v_mov_b32 v1, s1", - "v_mov_b32 v2, s2", - "v_mov_b32 v3, s3", - ]) - self.assertEqual((w0, w1, w2, w3), (0x2000001B, 1, 4, 11)) - - def test_seeded_sweep(self): - rng = random.Random(0x13A3) - for _ in range(30): - s0 = rng.getrandbits(32) - s1 = rng.getrandbits(32) - want_d, want_scc = ref_s_lshl3_add_u32(s0, s1) - with self.subTest(s0=hex(s0), s1=hex(s1)): - w0, w1, _, _ = run_ps_quad([ - f"s_mov_b32 s2, {s0:#x}", - f"s_mov_b32 s3, {s1:#x}", - scc_seed_line(1 - want_scc), - "s_lshl3_add_u32 s0, s2, s3", - "s_cselect_b32 s1, 1, 0", - "v_mov_b32 v0, s0", - "v_mov_b32 v1, s1", - "v_mov_b32 v2, 0", - "v_mov_b32 v3, 0", - ]) - self.assertEqual((w0, w1), (want_d, want_scc)) - - -class TestScalarCmpLgU64(unittest.TestCase): - """End-to-end semantic value tests for s_cmp_lg_u64.""" - - def test_sgpr_pair_inequality_low_and_high_halves(self): - for s0_64, s1_64, want_scc in ORACLE_CMP_LG_U64: - lo0, hi0 = split64(s0_64) - lo1, hi1 = split64(s1_64) - with self.subTest(s0=hex(s0_64), s1=hex(s1_64)): - w0, _, _, _ = run_ps_quad([ - f"s_mov_b32 s0, {lo0:#x}", - f"s_mov_b32 s1, {hi0:#x}", - f"s_mov_b32 s2, {lo1:#x}", - f"s_mov_b32 s3, {hi1:#x}", - scc_seed_line(1 - want_scc), - "s_cmp_lg_u64 s[0:1], s[2:3]", - "s_cselect_b32 s4, 1, 0", - "v_mov_b32 v0, s4", - "v_mov_b32 v1, 0", - "v_mov_b32 v2, 0", - "v_mov_b32 v3, 0", - ]) - self.assertEqual(w0, want_scc) - - def test_self_compare_and_overlapping_pairs(self): - # Self-compare must clear pre-seeded SCC=1; overlapping s[0:1] vs s[1:2] reads both halves accurately. - w0, w1, w2, w3 = run_ps_quad([ - "s_mov_b32 s0, 0xdeadbeef", - "s_mov_b32 s1, 0xdeadbeef", - "s_mov_b32 s2, 0xdeadbeef", - scc_seed_line(1), - "s_cmp_lg_u64 s[0:1], s[0:1]", # identical pair -> SCC = 0 - "s_cselect_b32 s4, 1, 0", - scc_seed_line(1), - "s_cmp_lg_u64 s[0:1], s[1:2]", # all 0xdeadbeef -> SCC = 0 - "s_cselect_b32 s5, 1, 0", - "s_mov_b32 s2, 0xdeadbee0", - "s_cmp_lg_u64 s[0:1], s[1:2]", # differs in s2 (high word of s[1:2]) -> SCC = 1 - "s_cselect_b32 s6, 1, 0", - "v_mov_b32 v0, s4", - "v_mov_b32 v1, s5", - "v_mov_b32 v2, s6", - "v_mov_b32 v3, 0", - ]) - self.assertEqual((w0, w1, w2), (0, 0, 1)) - - def test_inline_and_literal_constants(self): - # Inline -1 sign-extends to 0xFFFFFFFF_FFFFFFFF; -16 -> 0xFFFFFFFF_FFFFFFF0; - # positive inline 64 and 32-bit literals zero-extend high 32 bits to 0. - cases = [ - (0x00000000, 0x00000000, "0", 0), - (0x00000000, 0x00000001, "0", 1), # high dword non-zero vs 0 - (0xFFFFFFFF, 0xFFFFFFFF, "-1", 0), # sign-extended -1 matches all-ones - (0xFFFFFFFF, 0x00000000, "-1", 1), # high dword 0 != 0xFFFFFFFF - (0xFFFFFFF0, 0xFFFFFFFF, "-16", 0), - (0xFFFFFFF0, 0x00000000, "-16", 1), - (64, 0, "64", 0), - (64, 1, "64", 1), - (0x12345678, 0, "0x12345678", 0), - (0x12345678, 1, "0x12345678", 1), - (0x80000000, 0, "0x80000000", 0), - (0x80000000, 0xFFFFFFFF, "0x80000000", 1), - ] - for lo, hi, imm_tok, want_scc in cases: - with self.subTest(lo=hex(lo), hi=hex(hi), imm=imm_tok): - w0, w1, _, _ = run_ps_quad([ - f"s_mov_b32 s0, {lo:#x}", - f"s_mov_b32 s1, {hi:#x}", - scc_seed_line(1 - want_scc), - f"s_cmp_lg_u64 s[0:1], {imm_tok}", - "s_cselect_b32 s2, 1, 0", - scc_seed_line(1 - want_scc), - f"s_cmp_lg_u64 {imm_tok}, s[0:1]", - "s_cselect_b32 s3, 1, 0", - "v_mov_b32 v0, s2", - "v_mov_b32 v1, s3", - "v_mov_b32 v2, 0", - "v_mov_b32 v3, 0", - ]) - self.assertEqual((w0, w1), (want_scc, want_scc)) - - def test_wave32_and_wave64_lane_mask_comparisons(self): - # Wave64: lane 45 sets only the upper half of VCC; s_cmp_lg_u64 vcc, 0 must see it (SCC=1). - _, mem64 = run_cs_workgroup([ - "v_cmp_eq_u32_e32 vcc, 45, v0", - "s_cmp_lg_u64 vcc, 0", - "s_cselect_b32 s4, 1, 0", - "v_cmp_eq_u32_e32 vcc, 99, v0", - "s_cmp_lg_u64 vcc, 0", - "s_cselect_b32 s5, 1, 0", - "s_mov_b64 s[6:7], exec", - "s_cmp_lg_u64 exec, s[6:7]", # exec == saved exec -> SCC = 0 - "s_cselect_b32 s8, 1, 0", - "s_cmp_lg_u64 exec, 0", # active lanes present -> SCC = 1 - "s_cselect_b32 s9, 1, 0", - "v_mov_b32 v1, s4", - "v_mov_b32 v2, s5", - "v_mov_b32 v3, s8", - "v_mov_b32 v4, s9", - "v_lshlrev_b32 v5, 4, v0", - "buffer_store_dwordx4 v[1:4], v5, s[0:3], 0 offen", - ], threads=64, subgroup_size=64) - self.assertEqual((mem64[0], mem64[4], mem64[8], mem64[12]), (1, 0, 0, 1)) - - # Wave32: lane 20 in vcc_lo / s[4:5]; s_cmp_lg_u64 detects inequality across the 32-lane wave. - _, mem32 = run_cs_workgroup([ - "v_cmp_eq_u32_e64 s[4:5], 20, v0", - "s_cmp_lg_u64 s[4:5], 0", # lane 20 active -> SCC = 1 - "s_cselect_b32 s6, 1, 0", - "v_cmp_eq_u32_e64 s[4:5], 45, v0", - "s_cmp_lg_u64 s[4:5], 0", # only 32 lanes (0..31) -> SCC = 0 - "s_cselect_b32 s7, 1, 0", - "v_mov_b32 v1, s6", - "v_mov_b32 v2, s7", - "v_lshlrev_b32 v3, 3, v0", - "buffer_store_dwordx2 v[1:2], v3, s[0:3], 0 offen", - ], threads=32, subgroup_size=32) - self.assertEqual((mem32[0], mem32[4]), (1, 0)) - - def test_seeded_sweep(self): - rng = random.Random(0xC391) - for _ in range(30): - a = rng.getrandbits(64) - # Half the trials change only one dword (lo or hi) so both halves are stressed equally. - if rng.random() < 0.5: - b = a ^ (1 << rng.randrange(64)) - else: - b = a - alo, ahi = split64(a) - blo, bhi = split64(b) - want = ref_s_cmp_lg_u64(a, b) - with self.subTest(a=hex(a), b=hex(b)): - w0, _, _, _ = run_ps_quad([ - f"s_mov_b32 s0, {alo:#x}", - f"s_mov_b32 s1, {ahi:#x}", - f"s_mov_b32 s2, {blo:#x}", - f"s_mov_b32 s3, {bhi:#x}", - scc_seed_line(1 - want), - "s_cmp_lg_u64 s[0:1], s[2:3]", - "s_cselect_b32 s4, 1, 0", - "v_mov_b32 v0, s4", - "v_mov_b32 v1, 0", - "v_mov_b32 v2, 0", - "v_mov_b32 v3, 0", - ]) - self.assertEqual(w0, want) - - -class TestScalarCselectB64LaneMasks(unittest.TestCase): - """End-to-end semantic tests for s_cselect_b64 on uniform 0/-1 masks and wave lane masks. - - Excluded due to translator finding (tools/rdna2spirv.py lines 3564-3570, 1922-1946): - 64-bit SGPR data pairs with lo != hi and non-mask constants (anything other than 0 or -1) - are miscompiled by mask_src()/mask_dst(), which drops the high dword of SGPR pair sources, - duplicates the low 32-bit result into both destination dwords, and collapses constants to - (0xFFFFFFFF if (v & 1) else 0). Those data-pair and constant assertions are covered by the - plain-Python RDNA2 ISA reference tests in TestOracleConstants and excluded here. - """ - - def test_zero_and_all_ones_selection_and_scc_preserved(self): - # Uniform 0 and -1 (0xFFFFFFFF_FFFFFFFF) agree in both dwords and preserve SCC untouched. - for scc_in in (0, 1): - want_a = MASK64 if scc_in else 0 - want_b = 0 if scc_in else MASK64 - with self.subTest(scc_in=scc_in): - w0, w1, w2, w3 = run_ps_quad([ - scc_seed_line(scc_in), - "s_cselect_b64 s[0:1], -1, 0", - "s_cselect_b64 s[2:3], 0, -1", - "s_cselect_b32 s4, 1, 0", # verify SCC was not modified by s_cselect_b64 - "v_mov_b32 v0, s0", - "v_mov_b32 v1, s1", - "v_mov_b32 v2, s2", - "v_mov_b32 v3, s4", - ]) - self.assertEqual((w0, w1), split64(want_a)) - self.assertEqual(w2, split64(want_b)[0]) - self.assertEqual(w3, scc_in) - - def test_wave64_exec_and_vcc_lane_mask_selection(self): - # Test s_cselect_b64 on EXEC, VCC, and lane-mask SGPR pairs across a 64-lane wave. - _, mem = run_cs_workgroup([ - "v_mov_b32 v1, 0", - "v_cmp_lt_u32_e32 vcc, v0, 40", # lanes 0..39 -> count 40 - "s_mov_b64 s[4:5], exec", # all 64 lanes -> count 64 - "s_cmp_eq_u32 1, 1", # SCC = 1 - "s_cselect_b64 s[6:7], vcc, s[4:5]", # selects vcc (40 lanes) - "s_bcnt1_i32_b64 s8, s[6:7]", - "s_cmp_eq_u32 0, 1", # SCC = 0 - "s_cselect_b64 s[6:7], vcc, s[4:5]", # selects s[4:5] (64 lanes) - "s_cselect_b32 s10, 1, 0", # SCC must still be 0 right after s_cselect_b64 - "s_bcnt1_i32_b64 s9, s[6:7]", # note: s_bcnt1 overwrites SCC = (s9 != 0) - "s_cmp_eq_u32 1, 1", # SCC = 1 - "s_cselect_b64 exec, vcc, s[4:5]", # restrict EXEC to lanes 0..39 - "v_mov_b32 v1, 1", # written only by active lanes 0..39 - "s_cselect_b64 exec, -1, exec", # restore EXEC to all 64 lanes - "v_mov_b32 v2, s8", - "v_mov_b32 v3, s9", - "v_mov_b32 v4, s10", - "v_lshlrev_b32 v5, 4, v0", - "buffer_store_dwordx4 v[1:4], v5, s[0:3], 0 offen", - ], threads=64, subgroup_size=64) - for lane in range(64): - base = 16 * lane - self.assertEqual(mem[base], 1 if lane < 40 else 0) - self.assertEqual((mem[base + 4], mem[base + 8], mem[base + 12]), (40, 64, 0)) - - def test_wave32_lane_mask_selection(self): - # Same lane-mask selection under a 32-wide wave (pure wave32 subgroup). - _, mem = run_cs_workgroup([ - "v_cmp_lt_u32_e64 s[4:5], v0, 12", # lanes 0..11 - "s_cmp_eq_u32 1, 1", # SCC = 1 - "s_cselect_b64 s[6:7], s[4:5], -1", # selects s[4:5] (lanes 0..11) - "s_cmp_lg_u64 s[6:7], s[4:5]", # equal -> SCC = 0 - "s_cselect_b32 s8, 1, 0", - "s_cmp_eq_u32 0, 1", # SCC = 0 - "s_cselect_b64 s[6:7], 0, s[4:5]", # selects s[4:5] (lanes 0..11) - "s_cmp_lg_u64 s[6:7], 0", # non-zero -> SCC = 1 - "s_cselect_b32 s9, 1, 0", - "v_mov_b32 v1, s8", - "v_mov_b32 v2, s9", - "v_lshlrev_b32 v3, 3, v0", - "buffer_store_dwordx2 v[1:2], v3, s[0:3], 0 offen", - ], threads=32, subgroup_size=32) - self.assertEqual((mem[0], mem[4]), (0, 1)) - - -class TestNegativeControls(unittest.TestCase): - """Sabotage checks confirming the SPIR-V assertions catch broken translations.""" - - def test_sabotage_ashr_sub_lshl3_cmp_and_cselect(self): - # 1. s_ashr_i32: replacing arithmetic shift with logical shift breaks negative sign extension. - spv_ashr = translate_ps([ - "s_mov_b32 s2, 0x80000000", - "s_ashr_i32 s0, s2, 1", - "v_mov_b32 v0, s0", - "v_mov_b32 v1, 0", - "v_mov_b32 v2, 0", - "v_mov_b32 v3, 0", - ]) - self.assertEqual(mrt0_words(spv_ashr)[0], 0xC0000000) - bad_ashr = spv_ashr.replace("OpShiftRightArithmetic %int", "OpShiftRightLogical %int", 1) - self.assertNotEqual(bad_ashr, spv_ashr) - self.assertNotEqual(mrt0_words(bad_ashr)[0], 0xC0000000) - - # 2. s_sub_i32: losing overflow detection breaks SCC on INT_MIN - 1. - spv_sub = translate_ps([ - "s_mov_b32 s2, 0x80000000", - "s_sub_i32 s0, s2, 1", - "s_cselect_b32 s1, 1, 0", - "v_mov_b32 v0, s0", - "v_mov_b32 v1, s1", - "v_mov_b32 v2, 0", - "v_mov_b32 v3, 0", - ]) - self.assertEqual(tuple(mrt0_words(spv_sub)[:2]), (0x7FFFFFFF, 1)) - bad_sub = spv_sub.replace("OpStore %scc", "OpStore %vcc_hi", 1) - self.assertNotEqual(bad_sub, spv_sub) - self.assertNotEqual(tuple(mrt0_words(bad_sub)[:2]), (0x7FFFFFFF, 1)) - - # 3. s_lshl3_add_u32: dropping shifted-out carry bits breaks SCC on 0x20000000 << 3 + 0. - spv_lshl3 = translate_ps([ - "s_mov_b32 s2, 0x20000000", - "s_lshl3_add_u32 s0, s2, 0", - "s_cselect_b32 s1, 1, 0", - "v_mov_b32 v0, s0", - "v_mov_b32 v1, s1", - "v_mov_b32 v2, 0", - "v_mov_b32 v3, 0", - ]) - self.assertEqual(tuple(mrt0_words(spv_lshl3)[:2]), (0, 1)) - bad_lshl3 = spv_lshl3.replace("OpShiftRightLogical %uint", "OpBitwiseAnd %uint", 1) - self.assertNotEqual(bad_lshl3, spv_lshl3) - self.assertNotEqual(tuple(mrt0_words(bad_lshl3)[:2]), (0, 1)) - - # 4. s_cmp_lg_u64: omitting OpLogicalNot flips inequality into equality. - spv_cmp = translate_ps([ - "s_mov_b32 s0, 1", - "s_mov_b32 s1, 2", - "s_mov_b32 s2, 1", - "s_mov_b32 s3, 3", - "s_cmp_lg_u64 s[0:1], s[2:3]", - "s_cselect_b32 s4, 1, 0", - "v_mov_b32 v0, s4", - "v_mov_b32 v1, 0", - "v_mov_b32 v2, 0", - "v_mov_b32 v3, 0", - ]) - self.assertEqual(mrt0_words(spv_cmp)[0], 1) - bad_cmp = spv_cmp.replace("OpLogicalNot %bool", "OpCopyObject %bool", 1) - self.assertNotEqual(bad_cmp, spv_cmp) - self.assertNotEqual(mrt0_words(bad_cmp)[0], 1) - - # 5. s_cselect_b64: reversing select polarity breaks 0/-1 mask selection. - spv_csel = translate_ps([ - "s_cmp_eq_u32 1, 1", - "s_cselect_b64 s[0:1], -1, 0", - "v_mov_b32 v0, s0", - "v_mov_b32 v1, s1", - "v_mov_b32 v2, 0", - "v_mov_b32 v3, 0", - ]) - self.assertEqual(tuple(mrt0_words(spv_csel)[:2]), (0xFFFFFFFF, 0xFFFFFFFF)) - bad_csel = spv_csel.replace("OpINotEqual %bool", "OpIEqual %bool", 2) - self.assertNotEqual(bad_csel, spv_csel) - self.assertNotEqual(tuple(mrt0_words(bad_csel)[:2]), (0xFFFFFFFF, 0xFFFFFFFF)) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_scalar_alu_shifts.py b/tests/semantic/test_scalar_alu_shifts.py deleted file mode 100644 index 3bcc2d2d8..000000000 --- a/tests/semantic/test_scalar_alu_shifts.py +++ /dev/null @@ -1,522 +0,0 @@ -"""Semantic interpreter tests for RDNA2 scalar logical and arithmetic shifts. - -Instructions tested: - - s_lshl_b64 D, S0, S1: Logical Shift Left 64-bit - - s_lshr_b64 D, S0, S1: Logical Shift Right 64-bit (zero extended) - - s_ashr_i64 D, S0, S1: Arithmetic Shift Right 64-bit (sign extended) - -RDNA2 ISA rules (Scalar ALU Operations / SOP2): - - D is an even-aligned 64-bit SGPR pair s[d:d+1]. - - S0 is a 64-bit scalar operand: SGPR pair s[s:s+1] or 64-bit immediate constant. - - S1 is a 32-bit shift count operand: SGPR or immediate constant. Only bits [5:0] - (S1 & 63) are used by hardware; upper bits [31:6] are ignored. - - Logical shifts (s_lshl_b64, s_lshr_b64) treat S0 as an unsigned 64-bit integer, - shifting in zeroes from the right or left. - - Arithmetic shift (s_ashr_i64) treats S0 as a signed two's complement 64-bit integer, - replicating bit 63 into the vacated upper bit positions. - - Condition code SCC: SCC = 1 if D != 0 else 0 (set to 1 if the 64-bit result is - non-zero; cleared to 0 if the 64-bit result is all zeroes). - -Translator integration (rdna2spirv): - - s_lshl_b64, s_lshr_b64 and s_ashr_i64 pack SGPR pairs into %ulong, mask the shift count with 63, - perform OpShiftLeftLogical / OpShiftRightLogical / OpShiftRightArithmetic, unpack to low and high dwords, - and update %scc via OpSelect. -""" -import os -import sys -import unittest - -ROOT = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) -TOOLS_DIR = os.path.join(ROOT, "tools") -if TOOLS_DIR not in sys.path: - sys.path.insert(0, TOOLS_DIR) - -import rdna2spirv # noqa: E402 - -MASK32 = 0xFFFFFFFF -MASK64 = 0xFFFFFFFFFFFFFFFF -SIGN64 = 1 << 63 - - -def u64(v): - """Normalize integer to 64-bit unsigned.""" - return v & MASK64 - - -def s64(v): - """Interpret 64-bit unsigned integer as signed two's complement.""" - v &= MASK64 - return v - (1 << 64) if v & SIGN64 else v - - -def split_dwords(v64): - """Split 64-bit uint into (low_u32, high_u32).""" - v = v64 & MASK64 - return v & MASK32, (v >> 32) & MASK32 - - -def join_dwords(lo, hi): - """Join (low_u32, high_u32) into a 64-bit uint.""" - return ((hi & MASK32) << 32) | (lo & MASK32) - - -def ref_s_lshl_b64(src0, src1): - """Reference implementation of s_lshl_b64: D = src0 << (src1 & 63), SCC = D != 0.""" - sh = src1 & 63 - res = (u64(src0) << sh) & MASK64 - scc = 1 if res != 0 else 0 - return res, scc - - -def ref_s_lshr_b64(src0, src1): - """Reference implementation of s_lshr_b64: D = (unsigned)src0 >> (src1 & 63), SCC = D != 0.""" - sh = src1 & 63 - res = (u64(src0) >> sh) & MASK64 - scc = 1 if res != 0 else 0 - return res, scc - - -def ref_s_ashr_i64(src0, src1): - """Reference implementation of s_ashr_i64: D = (signed)src0 >> (src1 & 63), SCC = D != 0.""" - sh = src1 & 63 - signed_src = s64(src0) - res = (signed_src >> sh) & MASK64 - scc = 1 if res != 0 else 0 - return res, scc - - -class ScalarAluInterpreter: - """Minimal semantic interpreter for RDNA2 scalar ALU 64-bit shift operations.""" - - def __init__(self, num_sgprs=106): - self.num_sgprs = num_sgprs - self.sgpr = [0] * num_sgprs - self.scc = 0 - - def reset(self): - self.sgpr = [0] * self.num_sgprs - self.scc = 0 - - def get_sgpr_u32(self, r): - return self.sgpr[r] & MASK32 - - def set_sgpr_u32(self, r, val): - self.sgpr[r] = val & MASK32 - - def get_sgpr_u64(self, r): - lo = self.get_sgpr_u32(r) - hi = self.get_sgpr_u32(r + 1) - return join_dwords(lo, hi) - - def set_sgpr_u64(self, r, val64): - lo, hi = split_dwords(val64) - self.set_sgpr_u32(r, lo) - self.set_sgpr_u32(r + 1, hi) - - def resolve_src64(self, opnd): - """Resolve a 64-bit source operand (SGPR pair or immediate constant).""" - if isinstance(opnd, dict): - k = opnd.get("k") - if k == "sgpr": - r = opnd["r"] - return self.get_sgpr_u64(r) - if k == "imm": - return opnd["v"] & MASK64 - raise ValueError(f"unknown 64-bit operand kind: {k}") - if isinstance(opnd, int): - return opnd & MASK64 - raise TypeError(f"unsupported operand type: {type(opnd)}") - - def resolve_src32(self, opnd): - """Resolve a 32-bit shift count operand (SGPR or immediate constant).""" - if isinstance(opnd, dict): - k = opnd.get("k") - if k == "sgpr": - r = opnd["r"] - return self.get_sgpr_u32(r) - if k == "imm": - return opnd["v"] & MASK32 - raise ValueError(f"unknown 32-bit operand kind: {k}") - if isinstance(opnd, int): - return opnd & MASK32 - raise TypeError(f"unsupported operand type: {type(opnd)}") - - def step(self, op, dst, src0, src1): - """Execute a single scalar shift instruction. - - Arguments: - op: 's_lshl_b64', 's_lshr_b64', or 's_ashr_i64' - dst: dict {'k': 'sgpr', 'r': int, 'n': 2} or int register index - src0: 64-bit source (dict or int) - src1: 32-bit shift count (dict or int) - """ - val64 = self.resolve_src64(src0) - sh32 = self.resolve_src32(src1) - - if op == "s_lshl_b64": - res64, scc = ref_s_lshl_b64(val64, sh32) - elif op == "s_lshr_b64": - res64, scc = ref_s_lshr_b64(val64, sh32) - elif op == "s_ashr_i64": - res64, scc = ref_s_ashr_i64(val64, sh32) - else: - raise KeyError(f"unsupported scalar shift opcode: {op}") - - dst_r = dst["r"] if isinstance(dst, dict) else dst - self.set_sgpr_u64(dst_r, res64) - self.scc = scc - return res64, scc - - def execute_ir(self, ins): - """Execute an IR instruction dictionary matching tools/rdna2spirv.py parser format.""" - op = ins["op"] - args = ins["args"] - return self.step(op, args[0], args[1], args[2]) - - -class TestScalarShiftDirectSemantics(unittest.TestCase): - """Direct mathematical unit tests for 64-bit scalar logical and arithmetic shifts.""" - - def test_lshl_b64_basic_powers_of_two(self): - for shift in range(64): - with self.subTest(shift=shift): - res, scc = ref_s_lshl_b64(1, shift) - expected = (1 << shift) & MASK64 - self.assertEqual(res, expected) - self.assertEqual(scc, 1) - - def test_lshl_b64_zero_yields_zero_and_clears_scc(self): - for shift in (0, 1, 31, 32, 63): - with self.subTest(shift=shift): - res, scc = ref_s_lshl_b64(0, shift) - self.assertEqual(res, 0) - self.assertEqual(scc, 0) - - def test_lshl_b64_overflow_shifts_out_to_zero(self): - # 0x8000000000000000 shifted left by 1 drops off the 64-bit boundary. - res, scc = ref_s_lshl_b64(0x8000000000000000, 1) - self.assertEqual(res, 0) - self.assertEqual(scc, 0) - - def test_lshr_b64_basic_powers_of_two(self): - msb = 0x8000000000000000 - for shift in range(64): - with self.subTest(shift=shift): - res, scc = ref_s_lshr_b64(msb, shift) - expected = msb >> shift - self.assertEqual(res, expected) - self.assertEqual(scc, 1) - - def test_lshr_b64_underflow_shifts_out_to_zero(self): - res, scc = ref_s_lshr_b64(1, 1) - self.assertEqual(res, 0) - self.assertEqual(scc, 0) - - res, scc = ref_s_lshr_b64(0x00000000FFFFFFFF, 32) - self.assertEqual(res, 0) - self.assertEqual(scc, 0) - - def test_ashr_i64_positive_matches_lshr(self): - positive_samples = [ - 0x0000000000000001, - 0x000000007FFFFFFF, - 0x0000000100000000, - 0x7FFFFFFFFFFFFFFF, - 0x123456789ABCDEF0, - 0x0000000000000000, - ] - for val in positive_samples: - for shift in (0, 1, 15, 31, 32, 48, 63): - with self.subTest(val=hex(val), shift=shift): - ashr_res, ashr_scc = ref_s_ashr_i64(val, shift) - lshr_res, lshr_scc = ref_s_lshr_b64(val, shift) - self.assertEqual(ashr_res, lshr_res) - self.assertEqual(ashr_scc, lshr_scc) - - def test_ashr_i64_negative_sign_extension(self): - # All ones (-1) shifted arithmetically right by any count remains -1 (0xFFFFFFFFFFFFFFFF). - for shift in range(64): - with self.subTest(shift=shift): - res, scc = ref_s_ashr_i64(MASK64, shift) - self.assertEqual(res, MASK64) - self.assertEqual(scc, 1) - - # 0x8000000000000000 shifted right arithmetically replicates 1s. - res, scc = ref_s_ashr_i64(0x8000000000000000, 1) - self.assertEqual(res, 0xC000000000000000) - self.assertEqual(scc, 1) - - res, scc = ref_s_ashr_i64(0x8000000000000000, 32) - self.assertEqual(res, 0xFFFFFFFF80000000) - self.assertEqual(scc, 1) - - res, scc = ref_s_ashr_i64(0x8000000000000000, 63) - self.assertEqual(res, MASK64) - self.assertEqual(scc, 1) - - def test_contrast_lshr_vs_ashr_on_negative_operands(self): - negative_val = 0x8000000000000000 - lshr_res, _ = ref_s_lshr_b64(negative_val, 1) - ashr_res, _ = ref_s_ashr_i64(negative_val, 1) - self.assertEqual(lshr_res, 0x4000000000000000) - self.assertEqual(ashr_res, 0xC000000000000000) - self.assertNotEqual(lshr_res, ashr_res) - - lshr_full, _ = ref_s_lshr_b64(negative_val, 63) - ashr_full, _ = ref_s_ashr_i64(negative_val, 63) - self.assertEqual(lshr_full, 1) - self.assertEqual(ashr_full, MASK64) - - def test_shift_count_modulo_64_masking(self): - # RDNA2 SOP2 uses S1[5:0] (src1 & 63). Shifts by multiples of 64 must equal shift by 0. - val = 0x123456789ABCDEF0 - for base_shift in (0, 5, 31, 32, 63): - for extra in (64, 128, 256, 1024, 0x10000000): - dirty_count = base_shift + extra - with self.subTest(base_shift=base_shift, extra=extra): - self.assertEqual(ref_s_lshl_b64(val, dirty_count), ref_s_lshl_b64(val, base_shift)) - self.assertEqual(ref_s_lshr_b64(val, dirty_count), ref_s_lshr_b64(val, base_shift)) - self.assertEqual(ref_s_ashr_i64(val, dirty_count), ref_s_ashr_i64(val, base_shift)) - - # Shift by 0xFFFFFFFF (all 32 bits 1) masks to 63. - self.assertEqual(ref_s_lshl_b64(1, MASK32), ref_s_lshl_b64(1, 63)) - self.assertEqual(ref_s_lshr_b64(0x8000000000000000, MASK32), ref_s_lshr_b64(0x8000000000000000, 63)) - self.assertEqual(ref_s_ashr_i64(0x8000000000000000, MASK32), ref_s_ashr_i64(0x8000000000000000, 63)) - - def test_cross_dword_migration(self): - # Shifting 32 bits moves low dword into high dword or vice versa. - pattern = 0xDEADBEEFCAFEBABE - lo, hi = split_dwords(pattern) - self.assertEqual(lo, 0xCAFEBABE) - self.assertEqual(hi, 0xDEADBEEF) - - # Logical left shift by 32: low dword becomes high dword, low dword zeroed. - shl32, _ = ref_s_lshl_b64(pattern, 32) - shl_lo, shl_hi = split_dwords(shl32) - self.assertEqual(shl_lo, 0) - self.assertEqual(shl_hi, 0xCAFEBABE) - - # Logical right shift by 32: high dword becomes low dword, high dword zeroed. - shr32, _ = ref_s_lshr_b64(pattern, 32) - shr_lo, shr_hi = split_dwords(shr32) - self.assertEqual(shr_lo, 0xDEADBEEF) - self.assertEqual(shr_hi, 0) - - def test_scc_condition_code_transitions(self): - # Confirm SCC is 0 when result is 0, and 1 when result is non-zero. - _, scc_zero = ref_s_lshl_b64(0, 5) - self.assertEqual(scc_zero, 0) - - _, scc_nonzero = ref_s_lshl_b64(1, 5) - self.assertEqual(scc_nonzero, 1) - - # Verify low-only and high-only non-zero words set SCC to 1. - low_only = 0x0000000000000001 - high_only = 0x0000000100000000 - self.assertEqual(ref_s_lshl_b64(low_only, 0)[1], 1) - self.assertEqual(ref_s_lshl_b64(high_only, 0)[1], 1) - - -class TestScalarAluInterpreter(unittest.TestCase): - """Interpreter execution tests modeling SGPR register file state and SCC updates.""" - - def setUp(self): - self.interp = ScalarAluInterpreter() - - def test_initial_state_clean(self): - self.assertEqual(self.interp.scc, 0) - self.assertEqual(self.interp.get_sgpr_u64(0), 0) - - def test_lshl_execution_and_register_update(self): - # Set s[4:5] = 0x0000000000000001, s6 = 16. - # Execute s_lshl_b64 s[0:1], s[4:5], s6. - self.interp.set_sgpr_u64(4, 1) - self.interp.set_sgpr_u32(6, 16) - - ins = { - "op": "s_lshl_b64", - "args": [ - {"k": "sgpr", "r": 0, "n": 2}, - {"k": "sgpr", "r": 4, "n": 2}, - {"k": "sgpr", "r": 6}, - ], - "mods": [], - } - res64, scc = self.interp.execute_ir(ins) - self.assertEqual(res64, 0x10000) - self.assertEqual(scc, 1) - self.assertEqual(self.interp.get_sgpr_u64(0), 0x10000) - self.assertEqual(self.interp.scc, 1) - # Source registers must be untouched. - self.assertEqual(self.interp.get_sgpr_u64(4), 1) - self.assertEqual(self.interp.get_sgpr_u32(6), 16) - - def test_lshr_execution_with_immediate_count(self): - # Set s[8:9] = 0x1234567800000000. - # Execute s_lshr_b64 s[10:11], s[8:9], 32. - self.interp.set_sgpr_u64(8, 0x1234567800000000) - - ins = { - "op": "s_lshr_b64", - "args": [ - {"k": "sgpr", "r": 10, "n": 2}, - {"k": "sgpr", "r": 8, "n": 2}, - {"k": "imm", "v": 32}, - ], - "mods": [], - } - res64, scc = self.interp.execute_ir(ins) - self.assertEqual(res64, 0x12345678) - self.assertEqual(scc, 1) - self.assertEqual(self.interp.get_sgpr_u64(10), 0x12345678) - self.assertEqual(self.interp.scc, 1) - - def test_ashr_execution_sign_propagation(self): - # Set s[0:1] = -8 (0xFFFFFFFFFFFFFFF8). - # Execute s_ashr_i64 s[2:3], s[0:1], 1. - # Expected: -4 (0xFFFFFFFFFFFFFFFC). - self.interp.set_sgpr_u64(0, 0xFFFFFFFFFFFFFFF8) - - ins = { - "op": "s_ashr_i64", - "args": [ - {"k": "sgpr", "r": 2, "n": 2}, - {"k": "sgpr", "r": 0, "n": 2}, - {"k": "imm", "v": 1}, - ], - "mods": [], - } - res64, scc = self.interp.execute_ir(ins) - self.assertEqual(res64, 0xFFFFFFFFFFFFFFFC) - self.assertEqual(scc, 1) - self.assertEqual(self.interp.get_sgpr_u64(2), 0xFFFFFFFFFFFFFFFC) - - def test_in_place_shift_aliasing(self): - # Hardware supports dst aliasing src0: s[2:3] = s[2:3] << 4. - self.interp.set_sgpr_u64(2, 0x0F) - self.interp.step("s_lshl_b64", 2, {"k": "sgpr", "r": 2, "n": 2}, 4) - self.assertEqual(self.interp.get_sgpr_u64(2), 0xF0) - self.assertEqual(self.interp.scc, 1) - - def test_scc_cleared_when_result_becomes_zero(self): - # Pre-set SCC to 1. - self.interp.scc = 1 - # Shift 1 right by 1 -> 0, SCC must become 0. - self.interp.set_sgpr_u64(0, 1) - self.interp.step("s_lshr_b64", 0, {"k": "sgpr", "r": 0, "n": 2}, 1) - self.assertEqual(self.interp.get_sgpr_u64(0), 0) - self.assertEqual(self.interp.scc, 0) - - def test_adjacent_registers_remain_untouched(self): - # Set canary values in s0, s1, s4, s5. Write to s[2:3]. - self.interp.set_sgpr_u32(0, 0x11111111) - self.interp.set_sgpr_u32(1, 0x22222222) - self.interp.set_sgpr_u32(4, 0x44444444) - self.interp.set_sgpr_u32(5, 0x55555555) - - self.interp.step("s_lshl_b64", 2, 0x1234567890ABCDEF, 8) - self.assertEqual(self.interp.get_sgpr_u32(0), 0x11111111) - self.assertEqual(self.interp.get_sgpr_u32(1), 0x22222222) - self.assertEqual(self.interp.get_sgpr_u32(4), 0x44444444) - self.assertEqual(self.interp.get_sgpr_u32(5), 0x55555555) - - -class TestSpirvTranslatorIntegration(unittest.TestCase): - """Cross-validation between interpreter reference semantics and rdna2spirv code generation.""" - - def test_rdna2spirv_lshl_b64_emission(self): - g = rdna2spirv.Gen("ps") - ins = { - "op": "s_lshl_b64", - "args": [ - {"k": "sgpr", "r": 0, "n": 2}, - {"k": "sgpr", "r": 2, "n": 2}, - {"k": "imm", "v": 12}, - ], - "mods": [], - } - g.insn(ins) - emitted = "\n".join(g.body) - - # Verify key SPIR-V instructions are present per translation rules: - self.assertIn("OpShiftLeftLogical %ulong", emitted) - self.assertIn("OpBitwiseAnd %uint", emitted) - self.assertIn("%c3f", emitted) - self.assertIn("OpStore %scc", emitted) - self.assertTrue(g.uses_psb) - - def test_rdna2spirv_lshr_b64_emission(self): - g = rdna2spirv.Gen("ps") - ins = { - "op": "s_lshr_b64", - "args": [ - {"k": "sgpr", "r": 4, "n": 2}, - {"k": "sgpr", "r": 6, "n": 2}, - {"k": "sgpr", "r": 8}, - ], - "mods": [], - } - g.insn(ins) - emitted = "\n".join(g.body) - - self.assertIn("OpShiftRightLogical %ulong", emitted) - self.assertIn("OpStore %scc", emitted) - self.assertTrue(g.uses_psb) - - def test_rdna2spirv_ashr_i64_emission(self): - g = rdna2spirv.Gen("ps") - ins = { - "op": "s_ashr_i64", - "args": [ - {"k": "sgpr", "r": 0, "n": 2}, - {"k": "sgpr", "r": 2, "n": 2}, - {"k": "imm", "v": 4}, - ], - "mods": [], - } - g.insn(ins) - emitted = "\n".join(g.body) - - self.assertIn("OpBitcast %long", emitted) - self.assertIn("OpShiftRightArithmetic %long", emitted) - self.assertIn("OpBitcast %ulong", emitted) - self.assertIn("OpBitwiseAnd %uint", emitted) - self.assertIn("OpStore %scc", emitted) - self.assertTrue(g.uses_psb) - - def test_spirv_expansion_logic_matches_interpreter(self): - # Simulate the exact SPIR-V sequence emitted by rdna2spirv and verify equivalence with ref_s_lshl_b64. - vectors = [ - (0x12345678, 0x9ABCDEF0, 4), - (0xFFFFFFFF, 0x00000000, 32), - (0x00000001, 0x00000000, 63), - (0x00000000, 0x80000000, 1), - (0x00000000, 0x00000000, 16), - (0xDEADBEEF, 0xCAFEBABE, 70), # 70 & 63 = 6 - ] - for lo, hi, sh in vectors: - with self.subTest(lo=hex(lo), hi=hex(hi), sh=sh): - # 1. SPIR-V expansion logic from rdna2spirv.py lines 2614-2630: - l64 = lo & MASK64 - h64 = hi & MASK64 - t = (h64 << 32) & MASK64 - v64 = t | l64 - m = sh & 63 - s64 = m & MASK64 - r = (v64 << s64) & MASK64 - rlo = r & MASK32 - rh = (r >> 32) & MASK64 - rhi = rh & MASK32 - orr = (rlo | rhi) & MASK32 - spirv_scc = 1 if orr != 0 else 0 - spirv_res = join_dwords(rlo, rhi) - - # 2. Reference interpreter output: - ref_res, ref_scc = ref_s_lshl_b64(join_dwords(lo, hi), sh) - - self.assertEqual(spirv_res, ref_res) - self.assertEqual(spirv_scc, ref_scc) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_scalar_bcnt.py b/tests/semantic/test_scalar_bcnt.py deleted file mode 100644 index fc47406fe..000000000 --- a/tests/semantic/test_scalar_bcnt.py +++ /dev/null @@ -1,726 +0,0 @@ -"""Semantic interpreter tests for RDNA2 scalar zero-bit count instructions. - -Covers: - - s_bcnt0_i32_b32: D = count_zero_bits(S0.u32), SCC = (D != 0) - - s_bcnt0_i32_b64: D = count_zero_bits(S0.u64), SCC = (D != 0) - - s_ff0_i32_b32: D = find_first_zero_bit(S0.u32), -1 if none (SCC unchanged) - - s_flbit_i32_b32: D = count_leading_zeros(S0.u32), -1 if zero (SCC unchanged) - -RDNA2 ISA rules: - - s_bcnt0_i32_b32 counts the number of zero bits in a 32-bit scalar operand. - D receives a value in range [0, 32]. SCC is set to 1 if D != 0, else 0 - (i.e. SCC is 0 if and only if S0 is 0xFFFFFFFF). - - s_bcnt0_i32_b64 counts the number of zero bits in a 64-bit scalar operand - (SGPR pair, 64-bit mask, or constant). D receives a value in range [0, 64]. - SCC is set to 1 if D != 0, else 0 (SCC is 0 if and only if S0 is all 1s). - - s_ff0_i32_b32 scans the 32-bit scalar operand starting from LSB (bit 0) - towards MSB (bit 31) for the first 0 bit. If found, D is the bit index - [0, 31]. If no zero bit is found (S0 == 0xFFFFFFFF), D receives -1 (0xFFFFFFFF). - SCC is not modified. - - s_flbit_i32_b32 scans the 32-bit scalar operand starting from MSB (bit 31) - down towards LSB (bit 0) for the first set bit (1), counting leading zero bits. - D receives 31 - msb_index (range [0, 31]). If S0 == 0, D receives -1 (0xFFFFFFFF). - SCC is not modified. - -Lowering & Translation (tools/rdna2spirv.py): - - s_bcnt0_i32_b32: bitwise NOT of low word, OpBitCount, sets %scc via OpSelect. - - s_bcnt0_i32_b64: bitwise NOT of both halves, two OpBitCount, OpIAdd, sets %scc. - - s_ff0_i32_b32: bitwise NOT of source, FindILsb (GLSL.std.450), no SCC store. - - s_flbit_i32_b32: FindUMsb (GLSL.std.450), 31 - FindUMsb, select -1 if zero, no SCC store. -""" -from __future__ import annotations - -import os -import struct -import sys -import unittest - -HERE = os.path.dirname(os.path.abspath(__file__)) -ROOT = os.path.dirname(os.path.dirname(HERE)) -TOOLS_DIR = os.environ.get("LEONIDA_TOOLS_DIR") or os.path.join(ROOT, "tools") - -if ROOT not in sys.path: - sys.path.insert(0, ROOT) -if TOOLS_DIR not in sys.path: - sys.path.insert(0, TOOLS_DIR) - -import rdna2spirv # noqa: E402 - -MASK32 = 0xFFFFFFFF -MASK64 = 0xFFFFFFFFFFFFFFFF - - -def ref_bcnt0_b32(s0: int) -> tuple[int, int]: - """Reference oracle for s_bcnt0_i32_b32: returns (count, scc).""" - val = (s0 & MASK32) ^ MASK32 - count = bin(val).count("1") - scc = 1 if count != 0 else 0 - return count, scc - - -def ref_bcnt0_b64(s0_64: int) -> tuple[int, int]: - """Reference oracle for s_bcnt0_i32_b64: returns (count, scc).""" - val = (s0_64 & MASK64) ^ MASK64 - count = bin(val).count("1") - scc = 1 if count != 0 else 0 - return count, scc - - -def ref_ff0_b32(s0: int) -> int: - """Reference oracle for s_ff0_i32_b32: returns first zero bit from LSB, or -1.""" - val = (s0 & MASK32) ^ MASK32 - if val == 0: - return -1 - return (val & -val).bit_length() - 1 - - -def ref_flbit_b32(s0: int) -> int: - """Reference oracle for s_flbit_i32_b32: returns leading zeros before first 1, or -1.""" - val = s0 & MASK32 - if val == 0: - return -1 - return 32 - val.bit_length() - - -class ScalarBcntInterpreter: - """Deterministic semantic interpreter for RDNA2 scalar zero-bit count instructions. - - Models SGPR register file (s0-s105), condition code SCC, and special registers - (m0, vcc, exec). - """ - - def __init__(self, num_sgprs: int = 106) -> None: - self.num_sgprs = num_sgprs - self.sgpr = [0] * num_sgprs - self.scc = 0 - self.m0 = 0 - self.vcc = 0 - self.exec = MASK64 - - def reset(self) -> None: - self.sgpr = [0] * self.num_sgprs - self.scc = 0 - self.m0 = 0 - self.vcc = 0 - self.exec = MASK64 - - def get_sgpr_u32(self, r: int) -> int: - return self.sgpr[r] & MASK32 - - def set_sgpr_u32(self, r: int, val: int) -> None: - self.sgpr[r] = val & MASK32 - - def get_sgpr_u64(self, r: int) -> int: - lo = self.get_sgpr_u32(r) - hi = self.get_sgpr_u32(r + 1) - return ((hi & MASK32) << 32) | lo - - def set_sgpr_u64(self, r: int, val64: int) -> None: - val64 &= MASK64 - self.set_sgpr_u32(r, val64 & MASK32) - self.set_sgpr_u32(r + 1, (val64 >> 32) & MASK32) - - def resolve_src_u32(self, opnd: int | dict | str) -> int: - """Resolve a 32-bit scalar source operand.""" - if isinstance(opnd, int): - return opnd & MASK32 - if isinstance(opnd, dict): - k = opnd.get("k") - if k == "imm": - return opnd["v"] & MASK32 - if k == "fimm": - packed = struct.pack("> 32) & MASK32 - if t == "exec_lo": - return self.exec & MASK32 - if t == "exec_hi": - return (self.exec >> 32) & MASK32 - if t == "scc": - return self.scc & 1 - raise ValueError(f"Unknown 32-bit dict operand: {opnd}") - if isinstance(opnd, str): - if opnd.startswith("s") and opnd[1:].isdigit(): - return self.get_sgpr_u32(int(opnd[1:])) - if opnd == "m0": - return self.m0 & MASK32 - if opnd == "vcc_lo": - return self.vcc & MASK32 - if opnd == "vcc_hi": - return (self.vcc >> 32) & MASK32 - if opnd == "exec_lo": - return self.exec & MASK32 - if opnd == "exec_hi": - return (self.exec >> 32) & MASK32 - if opnd == "scc": - return self.scc & 1 - raise TypeError(f"Unsupported 32-bit operand format: {opnd}") - - def resolve_src_u64(self, opnd: int | dict | str) -> int: - """Resolve a 64-bit scalar source operand.""" - if isinstance(opnd, int): - return opnd & MASK64 - if isinstance(opnd, dict): - k = opnd.get("k") - if k == "imm": - return opnd["v"] & MASK64 - if k == "sgpr": - return self.get_sgpr_u64(opnd["r"]) - if k == "special": - t = opnd.get("t") - if t == "vcc": - return self.vcc & MASK64 - if t == "exec": - return self.exec & MASK64 - raise ValueError(f"Unknown 64-bit dict operand: {opnd}") - if isinstance(opnd, str): - if opnd.startswith("s[") and ":" in opnd: - idx = int(opnd[2:].split(":")[0]) - return self.get_sgpr_u64(idx) - if opnd == "vcc": - return self.vcc & MASK64 - if opnd == "exec": - return self.exec & MASK64 - raise TypeError(f"Unsupported 64-bit operand format: {opnd}") - - def resolve_dst(self, opnd: int | dict | str) -> int: - """Resolve destination SGPR index.""" - if isinstance(opnd, int): - return opnd - if isinstance(opnd, dict) and opnd.get("k") == "sgpr": - return opnd["r"] - if isinstance(opnd, str) and opnd.startswith("s") and opnd[1:].isdigit(): - return int(opnd[1:]) - raise ValueError(f"Cannot resolve destination operand: {opnd}") - - def step(self, insn: dict) -> tuple[int, int]: - """Execute one instruction dictionary. - - Accepts either: - {"op": op, "args": [dst, src]} - or: - {"op": op, "dst": dst, "s0": src} - """ - op = insn["op"] - if "args" in insn: - dst_opnd = insn["args"][0] - src_opnd = insn["args"][1] - else: - dst_opnd = insn["dst"] - src_opnd = insn.get("src0", insn.get("s0")) - - dst_r = self.resolve_dst(dst_opnd) - - if op == "s_bcnt0_i32_b32": - s0 = self.resolve_src_u32(src_opnd) - res, scc = ref_bcnt0_b32(s0) - self.set_sgpr_u32(dst_r, res) - self.scc = scc - return res, self.scc - - if op == "s_bcnt0_i32_b64": - s0_64 = self.resolve_src_u64(src_opnd) - res, scc = ref_bcnt0_b64(s0_64) - self.set_sgpr_u32(dst_r, res) - self.scc = scc - return res, self.scc - - if op == "s_ff0_i32_b32": - s0 = self.resolve_src_u32(src_opnd) - res = ref_ff0_b32(s0) - self.set_sgpr_u32(dst_r, res & MASK32) - # SCC is not modified by s_ff0_i32_b32 - return res & MASK32, self.scc - - if op == "s_flbit_i32_b32": - s0 = self.resolve_src_u32(src_opnd) - res = ref_flbit_b32(s0) - self.set_sgpr_u32(dst_r, res & MASK32) - # SCC is not modified by s_flbit_i32_b32 - return res & MASK32, self.scc - - if op == "s_mov_b32": - val = self.resolve_src_u32(src_opnd) - self.set_sgpr_u32(dst_r, val) - return val, self.scc - - if op == "s_mov_b64": - val64 = self.resolve_src_u64(src_opnd) - self.set_sgpr_u64(dst_r, val64) - return val64 & MASK32, self.scc - - raise NotImplementedError(f"Unsupported instruction op: {op}") - - def run_sequence(self, instructions: list[dict]) -> tuple[int, int]: - """Execute a sequence of instruction dictionaries sequentially.""" - last_res = 0 - for insn in instructions: - last_res, _ = self.step(insn) - return last_res, self.scc - - -class TestScalarBcntReferenceOracles(unittest.TestCase): - """Unit tests for the standalone mathematical reference models.""" - - def test_bcnt0_b32_all_single_zeros(self): - for bit in range(32): - pattern = (~(1 << bit)) & MASK32 - count, scc = ref_bcnt0_b32(pattern) - self.assertEqual(count, 1, f"Expected 1 zero bit for pattern with bit {bit} cleared") - self.assertEqual(scc, 1) - - def test_bcnt0_b32_all_single_ones(self): - for bit in range(32): - pattern = (1 << bit) & MASK32 - count, scc = ref_bcnt0_b32(pattern) - self.assertEqual(count, 31, f"Expected 31 zero bits for single bit {bit} set") - self.assertEqual(scc, 1) - - def test_bcnt0_b32_extrema_and_patterns(self): - self.assertEqual(ref_bcnt0_b32(0), (32, 1)) - self.assertEqual(ref_bcnt0_b32(MASK32), (0, 0)) - self.assertEqual(ref_bcnt0_b32(0x55555555), (16, 1)) - self.assertEqual(ref_bcnt0_b32(0xAAAAAAAA), (16, 1)) - self.assertEqual(ref_bcnt0_b32(0x0000FFFF), (16, 1)) - self.assertEqual(ref_bcnt0_b32(0xFFFF0000), (16, 1)) - self.assertEqual(ref_bcnt0_b32(0x0F0F0F0F), (16, 1)) - self.assertEqual(ref_bcnt0_b32(0x000000FF), (24, 1)) - - def test_bcnt0_b64_all_single_zeros(self): - for bit in range(64): - pattern = (~(1 << bit)) & MASK64 - count, scc = ref_bcnt0_b64(pattern) - self.assertEqual(count, 1, f"Expected 1 zero bit for 64-bit pattern with bit {bit} cleared") - self.assertEqual(scc, 1) - - def test_bcnt0_b64_all_single_ones(self): - for bit in range(64): - pattern = (1 << bit) & MASK64 - count, scc = ref_bcnt0_b64(pattern) - self.assertEqual(count, 63, f"Expected 63 zero bits for 64-bit single bit {bit} set") - self.assertEqual(scc, 1) - - def test_bcnt0_b64_extrema_and_patterns(self): - self.assertEqual(ref_bcnt0_b64(0), (64, 1)) - self.assertEqual(ref_bcnt0_b64(MASK64), (0, 0)) - self.assertEqual(ref_bcnt0_b64(0x5555555555555555), (32, 1)) - self.assertEqual(ref_bcnt0_b64(0xAAAAAAAAAAAAAAAA), (32, 1)) - self.assertEqual(ref_bcnt0_b64(0x00000000FFFFFFFF), (32, 1)) - self.assertEqual(ref_bcnt0_b64(0xFFFFFFFF00000000), (32, 1)) - self.assertEqual(ref_bcnt0_b64(0x0000FFFF0000FFFF), (32, 1)) - - def test_ff0_b32_exhaustive_single_zeros(self): - for bit in range(32): - pattern = (~(1 << bit)) & MASK32 - self.assertEqual(ref_ff0_b32(pattern), bit, f"First zero bit should be {bit}") - - def test_ff0_b32_dense_patterns(self): - self.assertEqual(ref_ff0_b32(0), 0) - self.assertEqual(ref_ff0_b32(1), 1) - self.assertEqual(ref_ff0_b32(0b11), 2) - self.assertEqual(ref_ff0_b32(0b111), 3) - self.assertEqual(ref_ff0_b32(0b1111), 4) - self.assertEqual(ref_ff0_b32(0x7FFFFFFF), 31) - self.assertEqual(ref_ff0_b32(MASK32), -1) - self.assertEqual(ref_ff0_b32(0xAAAAAAA0), 0) - self.assertEqual(ref_ff0_b32(0xAAAAAAA1), 1) - self.assertEqual(ref_ff0_b32(0xAAAAAAA3), 2) - - def test_flbit_b32_exhaustive_powers_of_two(self): - for bit in range(32): - pattern = 1 << bit - expected_leading_zeros = 31 - bit - self.assertEqual( - ref_flbit_b32(pattern), - expected_leading_zeros, - f"Leading zeros for 1 << {bit} should be {expected_leading_zeros}", - ) - - def test_flbit_b32_dense_patterns(self): - self.assertEqual(ref_flbit_b32(0), -1) - self.assertEqual(ref_flbit_b32(0x80000000), 0) - self.assertEqual(ref_flbit_b32(0xC0000000), 0) - self.assertEqual(ref_flbit_b32(0xFFFFFFFF), 0) - self.assertEqual(ref_flbit_b32(0x7FFFFFFF), 1) - self.assertEqual(ref_flbit_b32(0x40000000), 1) - self.assertEqual(ref_flbit_b32(0x3FFFFFFF), 2) - self.assertEqual(ref_flbit_b32(0x20000000), 2) - self.assertEqual(ref_flbit_b32(0x00000001), 31) - self.assertEqual(ref_flbit_b32(0x00000003), 30) - - def test_mathematical_duality_and_invariants(self): - for v in (0, 1, 42, 0x12345678, 0x55555555, 0x7FFFFFFF, MASK32): - pop32 = bin(v & MASK32).count("1") - zeros32, _ = ref_bcnt0_b32(v) - self.assertEqual(pop32 + zeros32, 32) - - pop64 = bin(v & MASK64).count("1") - zeros64, _ = ref_bcnt0_b64(v) - self.assertEqual(pop64 + zeros64, 64) - - # ff0(x) finds least significant 0; for any pattern with at least one 0: - ff0 = ref_ff0_b32(v) - if v == MASK32: - self.assertEqual(ff0, -1) - else: - self.assertTrue(0 <= ff0 < 32) - self.assertEqual((v >> ff0) & 1, 0) - # Lower bits before ff0 must all be 1 - lower_mask = (1 << ff0) - 1 - self.assertEqual(v & lower_mask, lower_mask) - - -class TestScalarBcntInterpreterExecution(unittest.TestCase): - """Semantic tests executing instructions through ScalarBcntInterpreter.""" - - def setUp(self): - self.interp = ScalarBcntInterpreter() - - def test_s_bcnt0_i32_b32_registers(self): - self.interp.set_sgpr_u32(1, 0x0000FFFF) - res, scc = self.interp.step({ - "op": "s_bcnt0_i32_b32", - "dst": {"k": "sgpr", "r": 0}, - "src0": {"k": "sgpr", "r": 1}, - }) - self.assertEqual(res, 16) - self.assertEqual(scc, 1) - self.assertEqual(self.interp.get_sgpr_u32(0), 16) - self.assertEqual(self.interp.scc, 1) - - def test_s_bcnt0_i32_b32_in_place(self): - self.interp.set_sgpr_u32(5, 0x0) - res, scc = self.interp.step({ - "op": "s_bcnt0_i32_b32", - "dst": "s5", - "src0": "s5", - }) - self.assertEqual(res, 32) - self.assertEqual(scc, 1) - self.assertEqual(self.interp.get_sgpr_u32(5), 32) - - def test_s_bcnt0_i32_b32_immediate_and_float_imm(self): - res, scc = self.interp.step({ - "op": "s_bcnt0_i32_b32", - "dst": "s0", - "src0": {"k": "imm", "v": 0xFFFFFFFF}, - }) - self.assertEqual(res, 0) - self.assertEqual(scc, 0) - - # 1.0f in IEEE-754: 0x3F800000 -> 0011 1111 1000 ... (seven 1s, twenty-five 0s) - res, scc = self.interp.step({ - "op": "s_bcnt0_i32_b32", - "dst": "s0", - "src0": {"k": "fimm", "v": 1.0}, - }) - self.assertEqual(res, 25) - self.assertEqual(scc, 1) - - def test_s_bcnt0_i32_b32_special_registers(self): - self.interp.m0 = 0b11110000 - res, scc = self.interp.step({ - "op": "s_bcnt0_i32_b32", - "dst": "s0", - "src0": {"k": "special", "t": "m0"}, - }) - self.assertEqual(res, 28) - self.assertEqual(scc, 1) - - self.interp.exec = 0x00000000FFFFFFFF - res, scc = self.interp.step({ - "op": "s_bcnt0_i32_b32", - "dst": "s0", - "src0": {"k": "special", "t": "exec_lo"}, - }) - self.assertEqual(res, 0) - self.assertEqual(scc, 0) - - res, scc = self.interp.step({ - "op": "s_bcnt0_i32_b32", - "dst": "s0", - "src0": {"k": "special", "t": "exec_hi"}, - }) - self.assertEqual(res, 32) - self.assertEqual(scc, 1) - - def test_s_bcnt0_i32_b32_scc_transitions(self): - # Start with SCC = 1 - self.interp.scc = 1 - # 0xFFFFFFFF has 0 zero bits -> sets SCC to 0 - self.interp.step({"op": "s_bcnt0_i32_b32", "dst": "s0", "src0": 0xFFFFFFFF}) - self.assertEqual(self.interp.scc, 0) - - # Non-0xFFFFFFFF has >0 zero bits -> sets SCC to 1 - self.interp.step({"op": "s_bcnt0_i32_b32", "dst": "s0", "src0": 0x7FFFFFFF}) - self.assertEqual(self.interp.scc, 1) - - def test_s_bcnt0_i32_b64_sgpr_pairs(self): - # s[2:3] = 0x00000000_FFFFFFFF - self.interp.set_sgpr_u32(2, 0xFFFFFFFF) - self.interp.set_sgpr_u32(3, 0x00000000) - res, scc = self.interp.step({ - "op": "s_bcnt0_i32_b64", - "dst": {"k": "sgpr", "r": 0}, - "src0": {"k": "sgpr", "r": 2, "n": 2}, - }) - self.assertEqual(res, 32) - self.assertEqual(scc, 1) - self.assertEqual(self.interp.get_sgpr_u32(0), 32) - - def test_s_bcnt0_i32_b64_in_place_dst_is_low_sgpr(self): - # s[4:5] = 0 - self.interp.set_sgpr_u64(4, 0) - res, scc = self.interp.step({ - "op": "s_bcnt0_i32_b64", - "dst": "s4", - "src0": "s[4:5]", - }) - self.assertEqual(res, 64) - self.assertEqual(scc, 1) - self.assertEqual(self.interp.get_sgpr_u32(4), 64) - - def test_s_bcnt0_i32_b64_lane_masks(self): - self.interp.exec = 0xAAAAAAAAAAAAAAAA - res, scc = self.interp.step({ - "op": "s_bcnt0_i32_b64", - "dst": "s0", - "src0": {"k": "special", "t": "exec"}, - }) - self.assertEqual(res, 32) - self.assertEqual(scc, 1) - - self.interp.vcc = MASK64 - res, scc = self.interp.step({ - "op": "s_bcnt0_i32_b64", - "dst": "s0", - "src0": "vcc", - }) - self.assertEqual(res, 0) - self.assertEqual(scc, 0) - - def test_s_ff0_i32_b32_registers(self): - self.interp.set_sgpr_u32(1, 0b10111) # bit 3 is first zero - res, _ = self.interp.step({ - "op": "s_ff0_i32_b32", - "dst": "s0", - "src0": "s1", - }) - self.assertEqual(res, 3) - self.assertEqual(self.interp.get_sgpr_u32(0), 3) - - def test_s_ff0_i32_b32_all_ones_returns_minus_one(self): - res, _ = self.interp.step({ - "op": "s_ff0_i32_b32", - "dst": "s0", - "src0": 0xFFFFFFFF, - }) - self.assertEqual(res, MASK32) # -1 represented as unsigned 32-bit - self.assertEqual(self.interp.get_sgpr_u32(0), 0xFFFFFFFF) - - def test_s_ff0_i32_b32_scc_invariance(self): - # s_ff0_i32_b32 must preserve preexisting SCC - for initial_scc in (0, 1): - self.interp.scc = initial_scc - self.interp.step({"op": "s_ff0_i32_b32", "dst": "s0", "src0": 0x7FFFFFFF}) - self.assertEqual( - self.interp.scc, - initial_scc, - f"s_ff0_i32_b32 mutated SCC when initial was {initial_scc}", - ) - - # Test also when result is -1 (input is 0xFFFFFFFF) - self.interp.scc = initial_scc - self.interp.step({"op": "s_ff0_i32_b32", "dst": "s0", "src0": 0xFFFFFFFF}) - self.assertEqual( - self.interp.scc, - initial_scc, - f"s_ff0_i32_b32 mutated SCC on all-ones when initial was {initial_scc}", - ) - - def test_s_flbit_i32_b32_registers(self): - self.interp.set_sgpr_u32(1, 0x00020000) # bit 17 set -> 31 - 17 = 14 leading zeros - res, _ = self.interp.step({ - "op": "s_flbit_i32_b32", - "dst": "s0", - "src0": "s1", - }) - self.assertEqual(res, 14) - self.assertEqual(self.interp.get_sgpr_u32(0), 14) - - def test_s_flbit_i32_b32_zero_returns_minus_one(self): - res, _ = self.interp.step({ - "op": "s_flbit_i32_b32", - "dst": "s0", - "src0": 0x0, - }) - self.assertEqual(res, MASK32) # -1 as uint32 - self.assertEqual(self.interp.get_sgpr_u32(0), 0xFFFFFFFF) - - def test_s_flbit_i32_b32_scc_invariance(self): - # s_flbit_i32_b32 must preserve preexisting SCC - for initial_scc in (0, 1): - self.interp.scc = initial_scc - self.interp.step({"op": "s_flbit_i32_b32", "dst": "s0", "src0": 0x80000000}) - self.assertEqual( - self.interp.scc, - initial_scc, - f"s_flbit_i32_b32 mutated SCC when initial was {initial_scc}", - ) - - # Test also when input is 0 (returns -1) - self.interp.scc = initial_scc - self.interp.step({"op": "s_flbit_i32_b32", "dst": "s0", "src0": 0x0}) - self.assertEqual( - self.interp.scc, - initial_scc, - f"s_flbit_i32_b32 mutated SCC on zero input when initial was {initial_scc}", - ) - - def test_chained_instruction_sequences(self): - # Sequence: Priority search and mask clearing loop emulation - # 1. Initialize s1 = 0b10011 (bits 2, 5, 6, 7 are zero) - # 2. Find first zero with s_ff0_i32_b32 -> should find bit 2 - # 3. Count zeros with s_bcnt0_i32_b32 -> 32 - 3 = 29 zeros, SCC = 1 - # 4. Find leading zeros with s_flbit_i32_b32 on s1 -> bit 4 is MSB set, 31 - 4 = 27 - seq = [ - {"op": "s_mov_b32", "dst": "s1", "src0": 0b10011}, - {"op": "s_ff0_i32_b32", "dst": "s2", "src0": "s1"}, - {"op": "s_bcnt0_i32_b32", "dst": "s3", "src0": "s1"}, - {"op": "s_flbit_i32_b32", "dst": "s4", "src0": "s1"}, - ] - self.interp.run_sequence(seq) - self.assertEqual(self.interp.get_sgpr_u32(2), 2) - self.assertEqual(self.interp.get_sgpr_u32(3), 29) - self.assertEqual(self.interp.scc, 1) - self.assertEqual(self.interp.get_sgpr_u32(4), 27) - - -class TestRdna2SpirvScalarBcntEmission(unittest.TestCase): - """Verifies that rdna2spirv generates conforming SPIR-V for all zero-counting ops.""" - - def test_s_bcnt0_i32_b32_emission_sgpr(self): - g = rdna2spirv.Gen("ps") - g.insn({ - "op": "s_bcnt0_i32_b32", - "args": [{"k": "sgpr", "r": 0}, {"k": "sgpr", "r": 1}], - "mods": [], - }) - emitted = "\n".join(g.body) - self.assertIn("OpNot %uint", emitted) - self.assertIn("OpBitCount %uint", emitted) - self.assertIn("OpStore %scc", emitted) - - def test_s_bcnt0_i32_b32_emission_imm(self): - g = rdna2spirv.Gen("ps") - g.insn({ - "op": "s_bcnt0_i32_b32", - "args": [{"k": "sgpr", "r": 0}, {"k": "imm", "v": 0x12345678}], - "mods": [], - }) - emitted = "\n".join(g.body) - self.assertIn("OpNot %uint %c12345678", emitted) - self.assertIn("OpBitCount %uint", emitted) - self.assertIn("OpStore %scc", emitted) - - def test_s_bcnt0_i32_b32_emission_lane_mask(self): - g = rdna2spirv.Gen("ps") - g.insn({ - "op": "s_bcnt0_i32_b32", - "args": [{"k": "sgpr", "r": 0}, {"k": "special", "t": "vcc_lo"}], - "mods": [], - }) - emitted = "\n".join(g.body) - self.assertIn("OpNot %uint", emitted) - self.assertIn("OpBitCount %uint", emitted) - self.assertIn("OpStore %scc", emitted) - - def test_s_bcnt0_i32_b64_emission_sgpr_pair(self): - g = rdna2spirv.Gen("ps") - g.insn({ - "op": "s_bcnt0_i32_b64", - "args": [{"k": "sgpr", "r": 0}, {"k": "sgpr", "r": 2, "n": 2}], - "mods": [], - }) - emitted = "\n".join(g.body) - self.assertEqual(emitted.count("OpNot %uint"), 2) - self.assertEqual(emitted.count("OpBitCount %uint"), 2) - self.assertIn("OpIAdd %uint", emitted) - self.assertIn("OpStore %scc", emitted) - - def test_s_bcnt0_i32_b64_emission_exec_mask(self): - g = rdna2spirv.Gen("ps") - g.insn({ - "op": "s_bcnt0_i32_b64", - "args": [{"k": "sgpr", "r": 0}, {"k": "special", "t": "exec"}], - "mods": [], - }) - emitted = "\n".join(g.body) - self.assertIn("OpNot %uint", emitted) - self.assertIn("OpBitCount %uint", emitted) - self.assertIn("OpIAdd %uint", emitted) - self.assertIn("OpStore %scc", emitted) - - def test_s_ff0_i32_b32_emission_sgpr(self): - g = rdna2spirv.Gen("ps") - g.insn({ - "op": "s_ff0_i32_b32", - "args": [{"k": "sgpr", "r": 0}, {"k": "sgpr", "r": 1}], - "mods": [], - }) - emitted = "\n".join(g.body) - self.assertIn("OpNot %uint", emitted) - self.assertIn("FindILsb", emitted) - self.assertNotIn("OpStore %scc", emitted) - - def test_s_ff0_i32_b32_emission_imm(self): - g = rdna2spirv.Gen("ps") - g.insn({ - "op": "s_ff0_i32_b32", - "args": [{"k": "sgpr", "r": 0}, {"k": "imm", "v": 7}], - "mods": [], - }) - emitted = "\n".join(g.body) - self.assertIn("OpNot %uint %c7", emitted) - self.assertIn("FindILsb", emitted) - self.assertNotIn("OpStore %scc", emitted) - - def test_s_flbit_i32_b32_emission_sgpr(self): - g = rdna2spirv.Gen("ps") - g.insn({ - "op": "s_flbit_i32_b32", - "args": [{"k": "sgpr", "r": 0}, {"k": "sgpr", "r": 1}], - "mods": [], - }) - emitted = "\n".join(g.body) - self.assertIn("FindUMsb", emitted) - self.assertIn("OpISub %uint %c1f", emitted) - self.assertIn("OpSelect %uint", emitted) - self.assertIn("%cffffffff", emitted) - self.assertNotIn("OpStore %scc", emitted) - - def test_s_flbit_i32_b32_emission_imm(self): - g = rdna2spirv.Gen("ps") - g.insn({ - "op": "s_flbit_i32_b32", - "args": [{"k": "sgpr", "r": 0}, {"k": "imm", "v": 0x40000000}], - "mods": [], - }) - emitted = "\n".join(g.body) - self.assertIn("FindUMsb", emitted) - self.assertIn("OpISub %uint %c1f", emitted) - self.assertIn("OpSelect %uint", emitted) - self.assertNotIn("OpStore %scc", emitted) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_scalar_bitcmp.py b/tests/semantic/test_scalar_bitcmp.py deleted file mode 100644 index ba8c4d59e..000000000 --- a/tests/semantic/test_scalar_bitcmp.py +++ /dev/null @@ -1,454 +0,0 @@ -"""Semantic tests for RDNA2 scalar bit test and zero-counting instructions. - -Covers: - - s_bitcmp0_b32: SCC = ((S0 >> (S1 & 31)) & 1) == 0 - - s_bitcmp1_b32: SCC = ((S0 >> (S1 & 31)) & 1) == 1 - - s_bitcmp0_b64: SCC = ((S0_64 >> (S1 & 63)) & 1) == 0 - - s_bitcmp1_b64: SCC = ((S0_64 >> (S1 & 63)) & 1) == 1 - - s_bcnt0_i32_b32: D = count_zero_bits(S0), SCC = (D != 0) - - s_bcnt0_i32_b64: D = count_zero_bits(S0_64), SCC = (D != 0) - - s_ff0_i32_b32: D = find_first_zero_bit(S0), -1 if none - - s_ff0_i32_b64: D = find_first_zero_bit(S0_64), -1 if none - - s_ff1_i32_b32/b64: D = find_first_set_bit(S0), -1 if none - - Non-mask `_b32` sources for s_ff0/s_ff1 are scalar values, including float immediates and m0 - - Lane mask awareness: testing bits on lane-mask registers (exec / vcc) - - SPIR-V translation validation via rdna2spirv.Gen -""" -import os -import sys -import unittest - -HERE = os.path.dirname(os.path.abspath(__file__)) -ROOT = os.path.dirname(os.path.dirname(HERE)) -TOOLS_DIR = os.environ.get("LEONIDA_TOOLS_DIR") or os.path.join(ROOT, "tools") - -if ROOT not in sys.path: - sys.path.insert(0, ROOT) -if TOOLS_DIR not in sys.path: - sys.path.insert(0, TOOLS_DIR) - -import rdna2spirv - -MASK32 = 0xFFFFFFFF -MASK64 = 0xFFFFFFFFFFFFFFFF - - -def ref_bitcmp0_b32(s0: int, s1: int) -> int: - bit = ((s0 & MASK32) >> (s1 & 31)) & 1 - return 1 if bit == 0 else 0 - - -def ref_bitcmp1_b32(s0: int, s1: int) -> int: - bit = ((s0 & MASK32) >> (s1 & 31)) & 1 - return 1 if bit == 1 else 0 - - -def ref_bitcmp0_b64(s0_64: int, s1: int) -> int: - bit = ((s0_64 & MASK64) >> (s1 & 63)) & 1 - return 1 if bit == 0 else 0 - - -def ref_bitcmp1_b64(s0_64: int, s1: int) -> int: - bit = ((s0_64 & MASK64) >> (s1 & 63)) & 1 - return 1 if bit == 1 else 0 - - -def ref_bcnt0_b32(s0: int) -> tuple[int, int]: - val = (s0 & MASK32) ^ MASK32 - count = bin(val).count("1") - return count, 1 if count != 0 else 0 - - -def ref_bcnt0_b64(s0_64: int) -> tuple[int, int]: - val = (s0_64 & MASK64) ^ MASK64 - count = bin(val).count("1") - return count, 1 if count != 0 else 0 - - -def ref_ff0_b32(s0: int) -> int: - val = (s0 & MASK32) ^ MASK32 - if val == 0: - return -1 - return (val & -val).bit_length() - 1 - - -def ref_ff0_b64(s0_64: int) -> int: - val = (s0_64 & MASK64) ^ MASK64 - if val == 0: - return -1 - return (val & -val).bit_length() - 1 - - -class TestBitcmpAndBcnt0Semantics(unittest.TestCase): - """Unit tests for reference models of bit test and zero-counting instructions.""" - - def test_bitcmp_b32_all_bits(self): - for bit_idx in range(32): - pattern = 1 << bit_idx - self.assertEqual(ref_bitcmp1_b32(pattern, bit_idx), 1) - self.assertEqual(ref_bitcmp0_b32(pattern, bit_idx), 0) - # Test inverted pattern - self.assertEqual(ref_bitcmp1_b32(~pattern, bit_idx), 0) - self.assertEqual(ref_bitcmp0_b32(~pattern, bit_idx), 1) - - def test_bitcmp_b64_all_bits(self): - for bit_idx in range(64): - pattern = 1 << bit_idx - self.assertEqual(ref_bitcmp1_b64(pattern, bit_idx), 1) - self.assertEqual(ref_bitcmp0_b64(pattern, bit_idx), 0) - # Test inverted pattern - self.assertEqual(ref_bitcmp1_b64(~pattern, bit_idx), 0) - self.assertEqual(ref_bitcmp0_b64(~pattern, bit_idx), 1) - - def test_bitcmp_modulo_shift(self): - # 32-bit: bits [31:5] are ignored (s1 & 31) - self.assertEqual(ref_bitcmp1_b32(0x80000000, 31 + 64), 1) - self.assertEqual(ref_bitcmp0_b32(0x80000000, 31 + 64), 0) - # 64-bit: bits [31:6] are ignored (s1 & 63) - self.assertEqual(ref_bitcmp1_b64(0x8000000000000000, 63 + 128), 1) - self.assertEqual(ref_bitcmp0_b64(0x8000000000000000, 63 + 128), 0) - - def test_bcnt0_b32_boundaries(self): - self.assertEqual(ref_bcnt0_b32(0), (32, 1)) - self.assertEqual(ref_bcnt0_b32(MASK32), (0, 0)) - self.assertEqual(ref_bcnt0_b32(0x55555555), (16, 1)) - self.assertEqual(ref_bcnt0_b32(0x0000FFFF), (16, 1)) - - def test_bcnt0_b64_boundaries(self): - self.assertEqual(ref_bcnt0_b64(0), (64, 1)) - self.assertEqual(ref_bcnt0_b64(MASK64), (0, 0)) - self.assertEqual(ref_bcnt0_b64(0x5555555555555555), (32, 1)) - self.assertEqual(ref_bcnt0_b64(0x00000000FFFFFFFF), (32, 1)) - - def test_ff0_b32(self): - self.assertEqual(ref_ff0_b32(MASK32), -1) - self.assertEqual(ref_ff0_b32(0), 0) - self.assertEqual(ref_ff0_b32(1), 1) - self.assertEqual(ref_ff0_b32(0b111), 3) - self.assertEqual(ref_ff0_b32(0x7FFFFFFF), 31) - - def test_ff0_b64(self): - self.assertEqual(ref_ff0_b64(MASK64), -1) - self.assertEqual(ref_ff0_b64(0), 0) - self.assertEqual(ref_ff0_b64(1), 1) - self.assertEqual(ref_ff0_b64(MASK32), 32) - self.assertEqual(ref_ff0_b64(0x7FFFFFFFFFFFFFFF), 63) - - -class TestRdna2SpirvBitcmpEmission(unittest.TestCase): - """Test SPIR-V code generation in rdna2spirv for bitcmp, bcnt0, ff0.""" - - def test_s_bitcmp1_b32_emission(self): - g = rdna2spirv.Gen("ps") - ins = { - "op": "s_bitcmp1_b32", - "args": [ - {"k": "sgpr", "r": 0}, - {"k": "imm", "v": 7}, - ], - "mods": [], - } - g.insn(ins) - emitted = "\n".join(g.body) - self.assertIn("OpShiftRightLogical %uint", emitted) - self.assertIn("OpBitwiseAnd %uint", emitted) - self.assertIn("OpINotEqual %bool", emitted) - self.assertIn("OpStore %scc", emitted) - - def test_s_bitcmp0_b32_emission(self): - g = rdna2spirv.Gen("ps") - ins = { - "op": "s_bitcmp0_b32", - "args": [ - {"k": "sgpr", "r": 2}, - {"k": "sgpr", "r": 3}, - ], - "mods": [], - } - g.insn(ins) - emitted = "\n".join(g.body) - self.assertIn("OpShiftRightLogical %uint", emitted) - self.assertIn("OpBitwiseAnd %uint", emitted) - self.assertIn("OpIEqual %bool", emitted) - self.assertIn("OpStore %scc", emitted) - - def test_s_bitcmp1_b64_emission(self): - g = rdna2spirv.Gen("ps") - ins = { - "op": "s_bitcmp1_b64", - "args": [ - {"k": "sgpr", "r": 4, "n": 2}, - {"k": "imm", "v": 45}, - ], - "mods": [], - } - g.insn(ins) - emitted = "\n".join(g.body) - self.assertIn("OpUGreaterThanEqual %bool", emitted) - self.assertIn("OpSelect %uint", emitted) - self.assertIn("OpShiftRightLogical %uint", emitted) - self.assertIn("OpStore %scc", emitted) - - def test_s_bitcmp1_b64_exec_lane_mask(self): - g = rdna2spirv.Gen("ps") - ins = { - "op": "s_bitcmp1_b64", - "args": [ - {"k": "special", "t": "exec"}, - {"k": "imm", "v": 16}, - ], - "mods": [], - } - g.insn(ins) - emitted = "\n".join(g.body) - self.assertIn("OpGroupNonUniformBallot %v4uint_bal", emitted) - self.assertIn("%c20", emitted) - self.assertIn("OpStore %scc", emitted) - - def test_s_bcnt0_i32_b32_emission(self): - g = rdna2spirv.Gen("ps") - ins = { - "op": "s_bcnt0_i32_b32", - "args": [ - {"k": "sgpr", "r": 0}, - {"k": "sgpr", "r": 1}, - ], - "mods": [], - } - g.insn(ins) - emitted = "\n".join(g.body) - self.assertIn("OpNot %uint", emitted) - self.assertIn("OpBitCount %uint", emitted) - self.assertIn("OpStore %scc", emitted) - - def test_s_bcnt0_i32_b64_emission(self): - g = rdna2spirv.Gen("ps") - ins = { - "op": "s_bcnt0_i32_b64", - "args": [ - {"k": "sgpr", "r": 0}, - {"k": "sgpr", "r": 2, "n": 2}, - ], - "mods": [], - } - g.insn(ins) - emitted = "\n".join(g.body) - self.assertIn("OpNot %uint", emitted) - self.assertIn("OpBitCount %uint", emitted) - self.assertIn("OpIAdd %uint", emitted) - self.assertIn("OpStore %scc", emitted) - - def test_s_ff0_i32_b32_emission(self): - g = rdna2spirv.Gen("ps") - ins = { - "op": "s_ff0_i32_b32", - "args": [ - {"k": "sgpr", "r": 0}, - {"k": "sgpr", "r": 1}, - ], - "mods": [], - } - g.insn(ins) - emitted = "\n".join(g.body) - self.assertIn("OpNot %uint", emitted) - self.assertIn("FindILsb", emitted) - - def test_s_ff0_i32_b32_immediate_is_scalar(self): - for value in (5, 61): - with self.subTest(value=value): - g = rdna2spirv.Gen("ps") - ins = { - "op": "s_ff0_i32_b32", - "args": [ - {"k": "sgpr", "r": 0}, - {"k": "imm", "v": value}, - ], - "mods": [], - } - g.insn(ins) - emitted = "\n".join(g.body) - self.assertIn(f"OpNot %uint %c{value:x}", emitted) - self.assertNotIn("OpNot %uint %cffffffff", emitted) - - def test_s_ff0_i32_b32_float_immediate_is_scalar(self): - g = rdna2spirv.Gen("ps") - ins = { - "op": "s_ff0_i32_b32", - "args": [ - {"k": "sgpr", "r": 0}, - {"k": "fimm", "v": 1.0}, - ], - "mods": [], - } - g.insn(ins) - emitted = "\n".join(g.body) - self.assertIn("OpNot %uint %c3f80000", emitted) - self.assertNotIn("OpNot %uint %cffffffff", emitted) - - def test_s_ff0_i32_b32_m0_is_scalar(self): - g = rdna2spirv.Gen("ps") - ins = { - "op": "s_ff0_i32_b32", - "args": [ - {"k": "sgpr", "r": 0}, - {"k": "special", "t": "m0"}, - ], - "mods": [], - } - g.insn(ins) - emitted = "\n".join(g.body) - self.assertIn("OpLoad %uint %m0", emitted) - self.assertIn("FindILsb", emitted) - self.assertNotIn("OpNot %uint %cffffffff", emitted) - - def test_s_ff1_i32_b32_immediate_is_scalar(self): - g = rdna2spirv.Gen("ps") - ins = { - "op": "s_ff1_i32_b32", - "args": [ - {"k": "sgpr", "r": 0}, - {"k": "imm", "v": 5}, - ], - "mods": [], - } - g.insn(ins) - emitted = "\n".join(g.body) - self.assertIn("FindILsb", emitted) - self.assertIn("%c5", emitted) - self.assertNotIn("%cffffffff", emitted) - - def test_s_ff0_i32_b64_immediate_is_scalar(self): - g = rdna2spirv.Gen("ps") - ins = { - "op": "s_ff0_i32_b64", - "args": [ - {"k": "sgpr", "r": 0}, - {"k": "imm", "v": 5}, - ], - "mods": [], - } - g.insn(ins) - emitted = "\n".join(g.body) - self.assertIn("OpNot %uint %c5", emitted) - self.assertIn("OpNot %uint %c0", emitted) - self.assertNotIn("OpNot %uint %cffffffff", emitted) - - def test_s_ff1_i32_b64_immediate_is_scalar(self): - g = rdna2spirv.Gen("ps") - ins = { - "op": "s_ff1_i32_b64", - "args": [ - {"k": "sgpr", "r": 0}, - {"k": "imm", "v": 5}, - ], - "mods": [], - } - g.insn(ins) - emitted = "\n".join(g.body) - self.assertIn("FindILsb", emitted) - self.assertIn("OpBitcast %int %c5", emitted) - self.assertNotIn("OpBitcast %int %cffffffff", emitted) - - def test_s_ff0_i32_b64_emission(self): - g = rdna2spirv.Gen("ps") - ins = { - "op": "s_ff0_i32_b64", - "args": [ - {"k": "sgpr", "r": 0}, - {"k": "sgpr", "r": 2, "n": 2}, - ], - "mods": [], - } - g.insn(ins) - emitted = "\n".join(g.body) - self.assertIn("OpNot %uint", emitted) - self.assertIn("FindILsb", emitted) - self.assertIn("OpIAdd %uint", emitted) - - def test_s_ff0_s_ff1_b64_negative_inline_and_literal_immediates(self): - """s_ff0_i32_b64 / s_ff1_i32_b64 sign-extend negative inline constants (-1..-16) and zero-extend literals.""" - import shutil - import struct - import subprocess - import tempfile - import warnings - if HERE not in sys.path: - sys.path.insert(0, HERE) - import spirv_mini_interp as si - - stub_dxbc = b"DXBC" + bytes(24) + struct.pack(" no 0 bit - ("s_ff0_i32_b64 s10, -2", 0), # 0xFFFFFFFF_FFFFFFFE -> bit 0 is 0 - ("s_ff0_i32_b64 s10, -16", 0), # 0xFFFFFFFF_FFFFFFF0 -> bit 0 is 0 - ("s_ff0_i32_b64 s10, 0xffffffff", 32), # 0x00000000_FFFFFFFF -> bit 32 is first 0 - ("s_ff0_i32_b64 s10, 0", 0), # 0x00000000_00000000 -> bit 0 is 0 - ("s_ff0_i32_b64 s10, 0x5", 1), # 0b101 -> bit 1 is 0 - ("s_ff1_i32_b64 s10, -1", 0), # 0xFFFFFFFF_FFFFFFFF -> bit 0 is 1 - ("s_ff1_i32_b64 s10, -16", 4), # 0xFFFFFFFF_FFFFFFF0 -> bit 4 is 1 - ("s_ff1_i32_b64 s10, 0", 0xFFFFFFFF), # no 1 bit - ("s_ff1_i32_b64 s10, 0x80000000", 31), # literal bit 31 - ("s_ff0_i32_b64 s10, null", 0), # null -> 0 - ("s_ff1_i32_b64 s10, null", 0xFFFFFFFF), # null -> 0 - ] - asm_lines = [] - for idx, (insn, _) in enumerate(cases): - asm_lines += [ - insn, - "v_mov_b32_e32 v1, s10", - f"v_mov_b32_e32 v2, {idx * 4}", - "buffer_store_dword v1, v2, s[0:3], 0 offen", - ] - asm_lines.append("s_endpgm") - with tempfile.TemporaryDirectory() as tmp: - os.mkdir(os.path.join(tmp, "disasm")) - os.mkdir(os.path.join(tmp, "fssm")) - src = os.path.join(tmp, "disasm", "cs_ff_b64_imm.s") - with open(src, "w", encoding="utf-8", newline="\n") as f: - f.write("; cs_ff_b64_imm\n" + "".join(f"\t{ln}\n" for ln in asm_lines)) - with open(os.path.join(tmp, "cs_ff_b64_imm.dxbc"), "wb") as f: - f.write(stub_dxbc) - with open(os.path.join(tmp, "fssm", "cs_ff_b64_imm.fssm"), "wb") as f: - f.write(bytes(0x138) + struct.pack("<4I", 0x8090, 64, 1, 1)) - with warnings.catch_warnings(): - warnings.simplefilter("ignore", ResourceWarning) - spv = rdna2spirv.translate(src) - spirv_as = shutil.which("spirv-as") - spirv_val = shutil.which("spirv-val") - if spirv_as and spirv_val: - spvasm = os.path.join(tmp, "m.spvasm") - spvbin = os.path.join(tmp, "m.spv") - with open(spvasm, "w", encoding="utf-8", newline="\n") as f: - f.write(spv) - r1 = subprocess.run([spirv_as, "--target-env", "vulkan1.2", spvasm, "-o", spvbin], - capture_output=True, text=True) - self.assertEqual(r1.returncode, 0, r1.stderr) - r2 = subprocess.run([spirv_val, "--target-env", "vulkan1.2", spvbin], - capture_output=True, text=True) - self.assertEqual(r2.returncode, 0, r2.stderr) - mem = si.run_workgroup( - spv, 64, 64, - inputs_for=lambda i: {"%wg_id": (0, 0, 0), "%local_id": (i, 0, 0), "%sg_lane": i}, - push_constants=vsharp + [0] * 28, memory={}, - ) - for idx, (insn, want) in enumerate(cases): - with self.subTest(insn=insn): - self.assertEqual(mem[idx * 4], want) - - def test_s_ff1_i32_b64_high_word_immediate(self): - """Synthetic 64-bit immediate with only high-word bits set uses hi via src64_data.""" - g = rdna2spirv.Gen("ps") - g.insn({ - "op": "s_ff1_i32_b64", - "args": [{"k": "sgpr", "r": 0}, {"k": "imm", "v": 0x0000000100000000}], - "mods": [], - }) - emitted = "\n".join(g.body) - self.assertIn("OpBitcast %int %c0", emitted) - self.assertIn("OpBitcast %int %c1", emitted) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_scalar_brev.py b/tests/semantic/test_scalar_brev.py deleted file mode 100644 index c1a4c0277..000000000 --- a/tests/semantic/test_scalar_brev.py +++ /dev/null @@ -1,832 +0,0 @@ -"""Semantic interpreter tests for RDNA2 scalar bit-reversal operations and FFT index permutations. - -Covers: - - s_brev_b32 D, S0: 32-bit scalar bit reversal (SOP1 format). - Reverses all 32 bits of scalar source S0 into 32-bit SGPR destination D. - Bit i (0 <= i <= 31) moves to bit (31 - i). - Scalar Condition Code (SCC) is preserved (NOT modified). - - s_brev_b64 D, S0: 64-bit scalar bit reversal across SGPR pairs s[d:d+1] from s[s:s+1]. - Reverses all 64 bits of 64-bit scalar source S0 into 64-bit SGPR destination D. - Bit i (0 <= i <= 63) moves to bit (63 - i). - Equivalence with 32-bit dwords: D[31:0] = brev32(S0[63:32]), D[63:32] = brev32(S0[31:0]). - Scalar Condition Code (SCC) is preserved (NOT modified). - - FFT Index Permutations (Bit-Reversal Permutations): - Radix-2 Cooley-Tukey decimation-in-time (DIT) FFT address generation. - Index reversal: rev_k(n) = s_lshr_b32(s_brev_b32(n), 32 - k) for N = 2^k points. - 64-bit FFT index permutation: rev_k(n) = s_lshr_b64(s_brev_b64(n), 64 - k). - Involution property: rev_k(rev_k(n)) == n (self-inverse permutation). - Bijective mapping and in-place butterfly pair swapping (i < rev_k(i)). - Dual packed FFT index reversals (packed 16-bit or 32-bit sub-indices). - - Deterministic semantic interpreter ScalarBrevInterpreter: - SGPR state table (106 registers), 32-bit and 64-bit reads/writes, in-place execution, - overlapping SGPR pairs, immediate constant operands, and SCC preservation. - - SPIR-V lowering and mini-interpreter validation: - OpBitReverse %uint and OpBitReverse %ulong execution in spirv_mini_interp, - rdna2spirv AST generation, and synthetic shader translation. - -Deterministic, zero game data, Python 3.9+ compatible. -""" -from __future__ import annotations - -import os -import struct -import sys -import tempfile -import unittest -import warnings - -HERE = os.path.dirname(os.path.abspath(__file__)) -ROOT = os.path.dirname(os.path.dirname(HERE)) -TOOLS_DIR = os.environ.get("LEONIDA_TOOLS_DIR") or os.path.join(ROOT, "tools") - -if ROOT not in sys.path: - sys.path.insert(0, ROOT) -if TOOLS_DIR not in sys.path: - sys.path.insert(0, TOOLS_DIR) -if HERE not in sys.path: - sys.path.insert(0, HERE) - -import rdna2spirv # noqa: E402 -import spirv_mini_interp as si # noqa: E402 - -MASK32 = 0xFFFFFFFF -MASK64 = 0xFFFFFFFFFFFFFFFF -STUB_DXBC = b"DXBC" + bytes(24) + struct.pack(" int: - """Normalize integer to 32-bit unsigned.""" - return v & MASK32 - - -def u64(v: int) -> int: - """Normalize integer to 64-bit unsigned.""" - return v & MASK64 - - -def split_dwords(v64: int) -> tuple[int, int]: - """Split 64-bit unsigned integer into (lo32, hi32).""" - v = v64 & MASK64 - return v & MASK32, (v >> 32) & MASK32 - - -def join_dwords(lo: int, hi: int) -> int: - """Join (lo32, hi32) into 64-bit unsigned integer.""" - return ((hi & MASK32) << 32) | (lo & MASK32) - - -def popcount(v: int) -> int: - """Count number of set bits (Python 3.9 compatible without int.bit_count).""" - return bin(v).count("1") - - -def ref_brev32(x: int) -> int: - """Plain-Python 32-bit bit-reversal reference oracle.""" - return int(f"{x & MASK32:032b}"[::-1], 2) - - -def ref_brev64(x: int) -> int: - """Plain-Python 64-bit bit-reversal reference oracle.""" - return int(f"{x & MASK64:064b}"[::-1], 2) - - -def fft_bitrev_index_32(index: int, log2_n: int) -> int: - """Compute bit-reversed index for an N = 2^log2_n point FFT using 32-bit bit reversal. - - In RDNA2 shaders: - s_brev_b32 s_rev, s_idx - s_lshr_b32 s_rev, s_rev, (32 - log2_n) - """ - assert 0 <= log2_n <= 32 - if log2_n == 0: - return 0 - shift = 32 - log2_n - return ref_brev32(index) >> shift - - -def fft_bitrev_index_64(index: int, log2_n: int) -> int: - """Compute bit-reversed index for an N = 2^log2_n point FFT using 64-bit bit reversal. - - In RDNA2 shaders: - s_brev_b64 s[rev_lo:rev_hi], s[idx_lo:idx_hi] - s_lshr_b64 s[rev_lo:rev_hi], s[rev_lo:rev_hi], (64 - log2_n) - """ - assert 0 <= log2_n <= 64 - if log2_n == 0: - return 0 - shift = 64 - log2_n - return ref_brev64(index) >> shift - - -def ref_fft_butterfly_pairs(n_points: int) -> list[tuple[int, int]]: - """Return pairs of indices (i, j) with i < j to swap during in-place radix-2 DIT FFT reordering.""" - assert n_points > 0 and (n_points & (n_points - 1)) == 0 - log2_n = (n_points - 1).bit_length() - pairs = [] - for i in range(n_points): - j = fft_bitrev_index_32(i, log2_n) - if i < j: - pairs.append((i, j)) - return pairs - - -class ScalarBrevInterpreter: - """Deterministic semantic interpreter for RDNA2 scalar bit-reversal operations. - - Tracks 32-bit SGPRs and SCC (Scalar Condition Code). - In RDNA2 ISA: - - s_brev_b32 D, S0 reverses all 32 bits of S0 and writes to 32-bit SGPR D. - SCC is preserved (NOT modified). - - s_brev_b64 D, S0 reverses all 64 bits of 64-bit operand S0 and writes - to 64-bit SGPR pair s[d:d+1]. - Equivalently: D_lo = ref_brev32(S0_hi), D_hi = ref_brev32(S0_lo). - SCC is preserved (NOT modified). - """ - - def __init__(self, num_sgprs: int = 106, initial_scc: int = 0) -> None: - self.num_sgprs = num_sgprs - self.sgpr = [0] * num_sgprs - self.scc = initial_scc & 1 - - def reset(self, initial_scc: int = 0) -> None: - self.sgpr = [0] * self.num_sgprs - self.scc = initial_scc & 1 - - def get_sgpr_u32(self, r: int) -> int: - if not (0 <= r < self.num_sgprs): - raise IndexError(f"SGPR index {r} out of range [0, {self.num_sgprs})") - return self.sgpr[r] & MASK32 - - def set_sgpr_u32(self, r: int, val: int) -> None: - if not (0 <= r < self.num_sgprs): - raise IndexError(f"SGPR index {r} out of range [0, {self.num_sgprs})") - self.sgpr[r] = val & MASK32 - - def get_sgpr_u64(self, r: int) -> int: - if not (0 <= r < self.num_sgprs - 1): - raise IndexError(f"64-bit SGPR base {r} out of range [0, {self.num_sgprs - 1})") - return join_dwords(self.get_sgpr_u32(r), self.get_sgpr_u32(r + 1)) - - def set_sgpr_u64(self, r: int, val64: int) -> None: - if not (0 <= r < self.num_sgprs - 1): - raise IndexError(f"64-bit SGPR base {r} out of range [0, {self.num_sgprs - 1})") - lo, hi = split_dwords(val64) - self.set_sgpr_u32(r, lo) - self.set_sgpr_u32(r + 1, hi) - - def resolve_src32(self, opnd: int | dict) -> int: - """Resolve a 32-bit source operand (integer, SGPR dict, or imm dict).""" - if isinstance(opnd, int): - return opnd & MASK32 - if isinstance(opnd, dict): - k = opnd.get("k") - if k == "sgpr": - return self.get_sgpr_u32(opnd["r"]) - if k == "imm": - return opnd["v"] & MASK32 - raise ValueError(f"Unsupported 32-bit operand kind: {k}") - raise TypeError(f"Unsupported operand type: {type(opnd)}") - - def resolve_src64(self, opnd: int | dict) -> int: - """Resolve a 64-bit source operand (integer, SGPR pair dict, or imm dict).""" - if isinstance(opnd, int): - return opnd & MASK64 - if isinstance(opnd, dict): - k = opnd.get("k") - if k == "sgpr": - return self.get_sgpr_u64(opnd["r"]) - if k == "imm": - return opnd["v"] & MASK64 - raise ValueError(f"Unsupported 64-bit operand kind: {k}") - raise TypeError(f"Unsupported operand type: {type(opnd)}") - - def step_s_brev_b32(self, dst: int | dict, src: int | dict) -> int: - """Execute s_brev_b32: D = ref_brev32(S0). SCC is preserved.""" - val = self.resolve_src32(src) - res = ref_brev32(val) - dst_r = dst["r"] if isinstance(dst, dict) else dst - self.set_sgpr_u32(dst_r, res) - return res - - def step_s_brev_b64(self, dst: int | dict, src: int | dict) -> int: - """Execute s_brev_b64: D = ref_brev64(S0). SCC is preserved.""" - val = self.resolve_src64(src) - res = ref_brev64(val) - dst_r = dst["r"] if isinstance(dst, dict) else dst - self.set_sgpr_u64(dst_r, res) - return res - - def step_s_lshr_b32(self, dst: int | dict, src0: int | dict, src1: int | dict) -> int: - """Execute s_lshr_b32 helper: D = S0 >> (S1 & 31), SCC = (D != 0).""" - v0 = self.resolve_src32(src0) - cnt = self.resolve_src32(src1) & 31 - res = (v0 >> cnt) & MASK32 - dst_r = dst["r"] if isinstance(dst, dict) else dst - self.set_sgpr_u32(dst_r, res) - self.scc = 1 if res != 0 else 0 - return res - - def step_s_lshr_b64(self, dst: int | dict, src0: int | dict, src1: int | dict) -> int: - """Execute s_lshr_b64 helper: D = S0 >> (S1 & 63), SCC = (D != 0).""" - v0 = self.resolve_src64(src0) - cnt = self.resolve_src32(src1) & 63 - res = (v0 >> cnt) & MASK64 - dst_r = dst["r"] if isinstance(dst, dict) else dst - self.set_sgpr_u64(dst_r, res) - self.scc = 1 if res != 0 else 0 - return res - - def step_s_mov_b32(self, dst: int | dict, src: int | dict) -> int: - """Execute s_mov_b32 helper.""" - val = self.resolve_src32(src) - dst_r = dst["r"] if isinstance(dst, dict) else dst - self.set_sgpr_u32(dst_r, val) - return val - - def step_s_mov_b64(self, dst: int | dict, src: int | dict) -> int: - """Execute s_mov_b64 helper.""" - val = self.resolve_src64(src) - dst_r = dst["r"] if isinstance(dst, dict) else dst - self.set_sgpr_u64(dst_r, val) - return val - - def execute_ir(self, insn: dict) -> int: - """Execute an IR instruction dictionary matching tools/rdna2spirv.py AST format.""" - op = insn["op"] - args = insn["args"] - if op == "s_brev_b32": - return self.step_s_brev_b32(args[0], args[1]) - elif op == "s_brev_b64": - return self.step_s_brev_b64(args[0], args[1]) - elif op == "s_lshr_b32": - return self.step_s_lshr_b32(args[0], args[1], args[2]) - elif op == "s_lshr_b64": - return self.step_s_lshr_b64(args[0], args[1], args[2]) - elif op == "s_mov_b32": - return self.step_s_mov_b32(args[0], args[1]) - elif op == "s_mov_b64": - return self.step_s_mov_b64(args[0], args[1]) - raise KeyError(f"Unsupported instruction opcode: {op}") - - -_TMP_DIR: tempfile.TemporaryDirectory | None = None -_SRC_PATH: str | None = None - - -def setUpModule() -> None: - global _TMP_DIR, _SRC_PATH - _TMP_DIR = tempfile.TemporaryDirectory() - disasm_dir = os.path.join(_TMP_DIR.name, "disasm") - os.mkdir(disasm_dir) - _SRC_PATH = os.path.join(disasm_dir, "ps_brev_test.s") - with open(os.path.join(_TMP_DIR.name, "ps_brev_test.dxbc"), "wb") as f: - f.write(STUB_DXBC) - - -def tearDownModule() -> None: - global _TMP_DIR, _SRC_PATH - if _TMP_DIR is not None: - _TMP_DIR.cleanup() - _TMP_DIR = None - _SRC_PATH = None - - -def run_synthetic_s_brev_b32(x: int) -> int: - """Translate and run a synthetic pixel shader with s_brev_b32 through rdna2spirv and mini_interp.""" - if _TMP_DIR is None: - setUpModule() - assert _SRC_PATH is not None - asm = ( - "; test_s_brev_b32\n" - f"\ts_mov_b32 s2, {x:#x}\n" - "\ts_brev_b32 s0, s2\n" - "\tv_mov_b32 v0, s0\n" - "\tv_mov_b32 v1, 0\n" - "\texp mrt0 v0, v1, v0, v0 done vm\n" - "\ts_endpgm\n" - ) - with open(_SRC_PATH, "w", encoding="utf-8") as f: - f.write(asm) - with warnings.catch_warnings(): - warnings.simplefilter("ignore", ResourceWarning) - spv = rdna2spirv.translate(_SRC_PATH) - return si.run_fragment(spv)["%out_mrt0"][0] - - -def run_synthetic_s_brev_b64(x64: int) -> int: - """Translate and run a synthetic pixel shader with s_brev_b64 through rdna2spirv and mini_interp.""" - if _TMP_DIR is None: - setUpModule() - assert _SRC_PATH is not None - lo, hi = split_dwords(x64) - asm = ( - "; test_s_brev_b64\n" - f"\ts_mov_b32 s2, {lo:#x}\n" - f"\ts_mov_b32 s3, {hi:#x}\n" - "\ts_brev_b64 s[0:1], s[2:3]\n" - "\tv_mov_b32 v0, s0\n" - "\tv_mov_b32 v1, s1\n" - "\texp mrt0 v0, v1, v0, v0 done vm\n" - "\ts_endpgm\n" - ) - with open(_SRC_PATH, "w", encoding="utf-8") as f: - f.write(asm) - with warnings.catch_warnings(): - warnings.simplefilter("ignore", ResourceWarning) - spv = rdna2spirv.translate(_SRC_PATH) - r = si.run_fragment(spv)["%out_mrt0"] - return join_dwords(r[0], r[1]) - - -class TestReferenceBitReversal(unittest.TestCase): - """Mathematical invariants, identities, and edge cases for 32-bit and 64-bit bit reversals.""" - - VALUES32 = [ - 0, - 1, - 2, - 0x80000000, - 0x7FFFFFFF, - 0xFFFFFFFF, - 0xFFFFFFFE, - 0x12345678, - 0x0000FFFF, - 0xFFFF0000, - 0x55555555, - 0xAAAAAAAA, - 0x33333333, - 0xCCCCCCCC, - 0x0F0F0F0F, - 0xF0F0F0F0, - 0x00FF00FF, - 0xFF00FF00, - 0xA5A5A5A5, - 0xDEADBEEF, - 0xCAFEBABE, - ] - - VALUES64 = [ - 0, - 1, - 2, - 0x8000000000000000, - 0x7FFFFFFFFFFFFFFF, - 0xFFFFFFFFFFFFFFFF, - 0xFFFFFFFFFFFFFFFE, - 0x00000000FFFFFFFF, - 0xFFFFFFFF00000000, - 0x123456789ABCDEF0, - 0x5555555555555555, - 0xAAAAAAAAAAAAAAAA, - 0x3333333333333333, - 0xCCCCCCCCCCCCCCCC, - 0x0F0F0F0F0F0F0F0F, - 0xF0F0F0F0F0F0F0F0, - 0x0000000100000000, - 0x0000000080000000, - 0xDEADBEEFCAFEBABE, - ] - - def test_ref_brev32_known_values(self): - self.assertEqual(ref_brev32(0), 0) - self.assertEqual(ref_brev32(1), 0x80000000) - self.assertEqual(ref_brev32(2), 0x40000000) - self.assertEqual(ref_brev32(0x80000000), 1) - self.assertEqual(ref_brev32(0xFFFFFFFF), 0xFFFFFFFF) - self.assertEqual(ref_brev32(0x12345678), 0x1E6A2C48) - self.assertEqual(ref_brev32(0x0000FFFF), 0xFFFF0000) - self.assertEqual(ref_brev32(0xFFFF0000), 0x0000FFFF) - self.assertEqual(ref_brev32(0x55555555), 0xAAAAAAAA) - self.assertEqual(ref_brev32(0xAAAAAAAA), 0x55555555) - self.assertEqual(ref_brev32(0x33333333), 0xCCCCCCCC) - self.assertEqual(ref_brev32(0x0F0F0F0F), 0xF0F0F0F0) - - def test_ref_brev32_single_bit_walk(self): - for bit in range(32): - val = 1 << bit - expected = 1 << (31 - bit) - self.assertEqual(ref_brev32(val), expected) - - def test_ref_brev32_involution(self): - for val in self.VALUES32: - with self.subTest(val=hex(val)): - self.assertEqual(ref_brev32(ref_brev32(val)), val) - - def test_ref_brev32_popcount_invariant(self): - for val in self.VALUES32: - with self.subTest(val=hex(val)): - self.assertEqual(popcount(ref_brev32(val)), popcount(val)) - - def test_ref_brev32_bitwise_not_duality(self): - for val in self.VALUES32: - with self.subTest(val=hex(val)): - not_val = (~val) & MASK32 - self.assertEqual(ref_brev32(not_val), (~ref_brev32(val)) & MASK32) - - def test_ref_brev32_palindromes(self): - palindromes = [ - 0, - 0xFFFFFFFF, - 0x80000001, - 0xC0000003, - 0x81818181, - 0x42424242, - 0x24242424, - 0x18181818, - 0x99999999, - ] - for p in palindromes: - with self.subTest(palindrome=hex(p)): - self.assertEqual(ref_brev32(p), p) - - def test_ref_brev64_known_values(self): - self.assertEqual(ref_brev64(0), 0) - self.assertEqual(ref_brev64(1), 0x8000000000000000) - self.assertEqual(ref_brev64(2), 0x4000000000000000) - self.assertEqual(ref_brev64(0x8000000000000000), 1) - self.assertEqual(ref_brev64(0xFFFFFFFFFFFFFFFF), 0xFFFFFFFFFFFFFFFF) - self.assertEqual(ref_brev64(0x00000000FFFFFFFF), 0xFFFFFFFF00000000) - self.assertEqual(ref_brev64(0xFFFFFFFF00000000), 0x00000000FFFFFFFF) - self.assertEqual(ref_brev64(0x123456789ABCDEF0), 0x0F7B3D591E6A2C48) - self.assertEqual(ref_brev64(0x5555555555555555), 0xAAAAAAAAAAAAAAAA) - self.assertEqual(ref_brev64(0xAAAAAAAAAAAAAAAA), 0x5555555555555555) - - def test_ref_brev64_single_bit_walk(self): - for bit in range(64): - val = 1 << bit - expected = 1 << (63 - bit) - self.assertEqual(ref_brev64(val), expected) - - def test_ref_brev64_involution(self): - for val in self.VALUES64: - with self.subTest(val=hex(val)): - self.assertEqual(ref_brev64(ref_brev64(val)), val) - - def test_ref_brev64_popcount_invariant(self): - for val in self.VALUES64: - with self.subTest(val=hex(val)): - self.assertEqual(popcount(ref_brev64(val)), popcount(val)) - - def test_ref_brev64_dword_decomposition(self): - for val in self.VALUES64: - with self.subTest(val=hex(val)): - lo = val & MASK32 - hi = (val >> 32) & MASK32 - expected_lo = ref_brev32(hi) - expected_hi = ref_brev32(lo) - expected_64 = (expected_hi << 32) | expected_lo - self.assertEqual(ref_brev64(val), expected_64) - - -class TestScalarBrevInterpreter(unittest.TestCase): - """Semantic interpreter execution of s_brev_b32 and s_brev_b64.""" - - def setUp(self): - self.interp = ScalarBrevInterpreter(num_sgprs=106, initial_scc=0) - - def test_sgpr_register_access_and_bounds(self): - self.interp.set_sgpr_u32(0, 0x12345678) - self.assertEqual(self.interp.get_sgpr_u32(0), 0x12345678) - - self.interp.set_sgpr_u64(2, 0x123456789ABCDEF0) - self.assertEqual(self.interp.get_sgpr_u64(2), 0x123456789ABCDEF0) - self.assertEqual(self.interp.get_sgpr_u32(2), 0x9ABCDEF0) - self.assertEqual(self.interp.get_sgpr_u32(3), 0x12345678) - - with self.assertRaises(IndexError): - self.interp.get_sgpr_u32(106) - with self.assertRaises(IndexError): - self.interp.set_sgpr_u32(-1, 0) - with self.assertRaises(IndexError): - self.interp.get_sgpr_u64(105) - - def test_s_brev_b32_basic(self): - test_cases = [0, 1, 0x12345678, 0x80000000, 0x55555555, 0xFFFFFFFF] - for x in test_cases: - with self.subTest(x=hex(x)): - self.interp.set_sgpr_u32(4, x) - res = self.interp.step_s_brev_b32(0, {"k": "sgpr", "r": 4}) - self.assertEqual(res, ref_brev32(x)) - self.assertEqual(self.interp.get_sgpr_u32(0), ref_brev32(x)) - - def test_s_brev_b32_in_place(self): - self.interp.set_sgpr_u32(7, 0x12345678) - self.interp.step_s_brev_b32(7, {"k": "sgpr", "r": 7}) - self.assertEqual(self.interp.get_sgpr_u32(7), 0x1E6A2C48) - self.interp.step_s_brev_b32(7, {"k": "sgpr", "r": 7}) - self.assertEqual(self.interp.get_sgpr_u32(7), 0x12345678) - - def test_s_brev_b32_immediate_operand(self): - self.interp.step_s_brev_b32(1, {"k": "imm", "v": 0x0000FFFF}) - self.assertEqual(self.interp.get_sgpr_u32(1), 0xFFFF0000) - - def test_s_brev_b32_preserves_scc(self): - for initial_scc in (0, 1): - for x in (0, 1, 0xFFFFFFFF, 0x80000000): - with self.subTest(scc=initial_scc, x=hex(x)): - self.interp.reset(initial_scc=initial_scc) - self.interp.set_sgpr_u32(10, x) - self.interp.step_s_brev_b32(11, {"k": "sgpr", "r": 10}) - self.assertEqual(self.interp.scc, initial_scc) - - def test_s_brev_b64_basic(self): - test_cases = [0, 1, 0x8000000000000000, 0x123456789ABCDEF0, 0xFFFFFFFFFFFFFFFF] - for val64 in test_cases: - with self.subTest(val=hex(val64)): - self.interp.set_sgpr_u64(2, val64) - res = self.interp.step_s_brev_b64(0, {"k": "sgpr", "r": 2}) - self.assertEqual(res, ref_brev64(val64)) - self.assertEqual(self.interp.get_sgpr_u64(0), ref_brev64(val64)) - - def test_s_brev_b64_in_place(self): - val = 0x123456789ABCDEF0 - self.interp.set_sgpr_u64(4, val) - self.interp.step_s_brev_b64(4, {"k": "sgpr", "r": 4}) - self.assertEqual(self.interp.get_sgpr_u64(4), ref_brev64(val)) - self.interp.step_s_brev_b64(4, {"k": "sgpr", "r": 4}) - self.assertEqual(self.interp.get_sgpr_u64(4), val) - - def test_s_brev_b64_overlapping_sgprs(self): - val = 0x0123456789ABCDEF - self.interp.set_sgpr_u64(2, val) - self.interp.step_s_brev_b64(1, {"k": "sgpr", "r": 2}) - self.assertEqual(self.interp.get_sgpr_u64(1), ref_brev64(val)) - - def test_s_brev_b64_immediate_operand(self): - imm = 0x00000000FFFFFFFF - self.interp.step_s_brev_b64(8, {"k": "imm", "v": imm}) - self.assertEqual(self.interp.get_sgpr_u64(8), 0xFFFFFFFF00000000) - - def test_s_brev_b64_preserves_scc(self): - for initial_scc in (0, 1): - for x in (0, 1, 0xFFFFFFFFFFFFFFFF, 0x8000000000000000): - with self.subTest(scc=initial_scc, x=hex(x)): - self.interp.reset(initial_scc=initial_scc) - self.interp.set_sgpr_u64(10, x) - self.interp.step_s_brev_b64(12, {"k": "sgpr", "r": 10}) - self.assertEqual(self.interp.scc, initial_scc) - - def test_s_brev_b64_vs_lowered_dual_s_brev_b32(self): - val64 = 0x123456789ABCDEF0 - self.interp.set_sgpr_u64(0, val64) - self.interp.step_s_brev_b64(2, {"k": "sgpr", "r": 0}) - - self.interp.step_s_brev_b32(4, {"k": "sgpr", "r": 1}) - self.interp.step_s_brev_b32(5, {"k": "sgpr", "r": 0}) - - self.assertEqual(self.interp.get_sgpr_u64(2), self.interp.get_sgpr_u64(4)) - self.assertEqual(self.interp.get_sgpr_u64(2), ref_brev64(val64)) - - def test_execute_ir(self): - ins_b32 = { - "op": "s_brev_b32", - "args": [{"k": "sgpr", "r": 0}, {"k": "imm", "v": 0x12345678}], - } - res32 = self.interp.execute_ir(ins_b32) - self.assertEqual(res32, 0x1E6A2C48) - self.assertEqual(self.interp.get_sgpr_u32(0), 0x1E6A2C48) - - ins_b64 = { - "op": "s_brev_b64", - "args": [{"k": "sgpr", "r": 2}, {"k": "imm", "v": 1}], - } - res64 = self.interp.execute_ir(ins_b64) - self.assertEqual(res64, 0x8000000000000000) - self.assertEqual(self.interp.get_sgpr_u64(2), 0x8000000000000000) - - -class TestFFTIndexPermutations(unittest.TestCase): - """Radix-2 Cooley-Tukey FFT bit-reversal address permutations and butterfly swaps.""" - - def test_fft_known_permutations_n4(self): - expected_n4 = [0, 2, 1, 3] - for i in range(4): - self.assertEqual(fft_bitrev_index_32(i, 2), expected_n4[i]) - - def test_fft_known_permutations_n8(self): - expected_n8 = [0, 4, 2, 6, 1, 5, 3, 7] - for i in range(8): - self.assertEqual(fft_bitrev_index_32(i, 3), expected_n8[i]) - - def test_fft_known_permutations_n16(self): - expected_n16 = [0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15] - for i in range(16): - self.assertEqual(fft_bitrev_index_32(i, 4), expected_n16[i]) - - def test_fft_permutation_bijection_and_fixed_points(self): - for log2_n in (1, 2, 3, 4, 5, 6, 8, 10, 12): - n = 1 << log2_n - with self.subTest(n=n, log2_n=log2_n): - permuted = [fft_bitrev_index_32(i, log2_n) for i in range(n)] - self.assertEqual(len(set(permuted)), n) - self.assertEqual(min(permuted), 0) - self.assertEqual(max(permuted), n - 1) - self.assertEqual(permuted[0], 0) - self.assertEqual(permuted[n - 1], n - 1) - for i in range(n): - rev = permuted[i] - self.assertEqual(fft_bitrev_index_32(rev, log2_n), i) - - def test_fft_butterfly_pairs(self): - pairs_n8 = ref_fft_butterfly_pairs(8) - self.assertEqual(pairs_n8, [(1, 4), (3, 6)]) - - pairs_n16 = ref_fft_butterfly_pairs(16) - expected_n16 = [(1, 8), (2, 4), (3, 12), (5, 10), (7, 14), (11, 13)] - self.assertEqual(pairs_n16, expected_n16) - - def test_fft_in_place_array_reordering(self): - for log2_n in (3, 4, 6): - n = 1 << log2_n - data = [f"sample_{i}" for i in range(n)] - pairs = ref_fft_butterfly_pairs(n) - for i, j in pairs: - data[i], data[j] = data[j], data[i] - for idx in range(n): - rev_idx = fft_bitrev_index_32(idx, log2_n) - self.assertEqual(data[idx], f"sample_{rev_idx}") - for i, j in pairs: - data[i], data[j] = data[j], data[i] - self.assertEqual(data, [f"sample_{i}" for i in range(n)]) - - def test_fft_64bit_huge_index_permutations(self): - for log2_n in (33, 40, 48, 60, 64): - with self.subTest(log2_n=log2_n): - self.assertEqual(fft_bitrev_index_64(0, log2_n), 0) - self.assertEqual(fft_bitrev_index_64(1, log2_n), 1 << (log2_n - 1)) - self.assertEqual(fft_bitrev_index_64(1 << (log2_n - 1), log2_n), 1) - - max_idx = (1 << log2_n) - 1 - self.assertEqual(fft_bitrev_index_64(max_idx, log2_n), max_idx) - - test_indices = [ - 0x12345678, - (1 << (log2_n - 2)) | 0x55, - (1 << (log2_n - 1)) | 0x3, - ] - for idx in test_indices: - rev = fft_bitrev_index_64(idx, log2_n) - self.assertEqual(fft_bitrev_index_64(rev, log2_n), idx) - - def test_dual_fft_packed_indices(self): - idx0 = 5 - idx1 = 9 - log2_sub = 4 - rev0 = fft_bitrev_index_32(idx0, log2_sub) - rev1 = fft_bitrev_index_32(idx1, log2_sub) - - packed = (idx1 << 16) | idx0 - brev_packed = ref_brev32(packed) - extracted_rev0 = (brev_packed >> (32 - log2_sub)) & 0xF - extracted_rev1 = (brev_packed >> (16 - log2_sub)) & 0xF - self.assertEqual(extracted_rev0, rev0) - self.assertEqual(extracted_rev1, rev1) - - def test_scalar_interpreter_fft_shader_loop(self): - interp = ScalarBrevInterpreter(num_sgprs=32) - log2_n = 4 - n_points = 1 << log2_n - shift = 32 - log2_n - base_addr = 0x1000 - element_stride = 8 - - generated_addrs = [] - for i in range(n_points): - interp.step_s_mov_b32(0, i) - interp.step_s_brev_b32(1, {"k": "sgpr", "r": 0}) - interp.step_s_lshr_b32(2, {"k": "sgpr", "r": 1}, shift) - rev_idx = interp.get_sgpr_u32(2) - addr = base_addr + rev_idx * element_stride - generated_addrs.append(addr) - - for i in range(n_points): - expected_rev = fft_bitrev_index_32(i, log2_n) - expected_addr = base_addr + expected_rev * element_stride - self.assertEqual(generated_addrs[i], expected_addr) - - -class TestSpirvTranslationAndExecution(unittest.TestCase): - """SPIR-V translation and mini-interpreter execution for bit-reversal operations.""" - - def test_rdna2spirv_gen_s_brev_b32(self): - g = rdna2spirv.Gen("ps") - ins = { - "op": "s_brev_b32", - "args": [ - {"k": "sgpr", "r": 0}, - {"k": "sgpr", "r": 1}, - ], - "mods": [], - } - g.insn(ins) - emitted = "\n".join(g.body) - self.assertIn("OpBitReverse %uint", emitted) - self.assertIn("OpStore", emitted) - - def test_rdna2spirv_gen_s_brev_b64(self): - g = rdna2spirv.Gen("ps") - ins = { - "op": "s_brev_b64", - "args": [ - {"k": "sgpr", "r": 0, "n": 2}, - {"k": "sgpr", "r": 2, "n": 2}, - ], - "mods": [], - } - g.insn(ins) - emitted = "\n".join(g.body) - self.assertEqual(emitted.count("OpBitReverse %uint"), 2) - self.assertEqual(emitted.count("OpStore"), 2) - - def test_spirv_mini_interp_op_bitreverse_u32(self): - test_patterns = [0, 1, 0x12345678, 0x80000000, 0x0000FFFF, 0x55555555, 0xFFFFFFFF] - for val in test_patterns: - with self.subTest(val=hex(val)): - mod = "\n".join([ - "OpCapability Shader", - "%glsl = OpExtInstImport 'GLSL.std.450'", - "OpMemoryModel Logical GLSL450", - "OpEntryPoint Fragment %main 'main' %out", - "%void = OpTypeVoid", - "%fn = OpTypeFunction %void", - "%uint = OpTypeInt 32 0", - "%_ptr_Output_uint = OpTypePointer Output %uint", - "%out = OpVariable %_ptr_Output_uint Output", - f"%cin = OpConstant %uint {val}", - "%main = OpFunction %void None %fn", - "%entry = OpLabel", - "%res = OpBitReverse %uint %cin", - "OpStore %out %res", - "OpReturn", - "OpFunctionEnd", - ]) - res = si.run_fragment(mod)["%out"][0] - self.assertEqual(res, ref_brev32(val)) - - def test_spirv_mini_interp_op_bitreverse_u64(self): - test_patterns = [ - 0, - 1, - 0x8000000000000000, - 0x123456789ABCDEF0, - 0x00000000FFFFFFFF, - 0xFFFFFFFFFFFFFFFF, - ] - for val in test_patterns: - with self.subTest(val=hex(val)): - mod = "\n".join([ - "OpCapability Shader", - "OpCapability Int64", - "%glsl = OpExtInstImport 'GLSL.std.450'", - "OpMemoryModel Logical GLSL450", - "OpEntryPoint Fragment %main 'main' %out_lo %out_hi", - "%void = OpTypeVoid", - "%fn = OpTypeFunction %void", - "%uint = OpTypeInt 32 0", - "%ulong = OpTypeInt 64 0", - "%_ptr_Output_uint = OpTypePointer Output %uint", - "%out_lo = OpVariable %_ptr_Output_uint Output", - "%out_hi = OpVariable %_ptr_Output_uint Output", - f"%c64 = OpConstant %ulong {val}", - "%c32 = OpConstant %ulong 32", - "%main = OpFunction %void None %fn", - "%entry = OpLabel", - "%rev = OpBitReverse %ulong %c64", - "%lo = OpUConvert %uint %rev", - "%sh = OpShiftRightLogical %ulong %rev %c32", - "%hi = OpUConvert %uint %sh", - "OpStore %out_lo %lo", - "OpStore %out_hi %hi", - "OpReturn", - "OpFunctionEnd", - ]) - r = si.run_fragment(mod) - res_lo = r["%out_lo"][0] - res_hi = r["%out_hi"][0] - res_64 = join_dwords(res_lo, res_hi) - self.assertEqual(res_64, ref_brev64(val)) - - def test_synthetic_shader_pipeline_32(self): - test_values = [0, 1, 0x12345678, 0x80000000, 0x0000FFFF, 0xFFFFFFFF] - for val in test_values: - with self.subTest(val=hex(val)): - res = run_synthetic_s_brev_b32(val) - self.assertEqual(res, ref_brev32(val)) - - def test_synthetic_shader_pipeline_64(self): - test_values = [ - 0, - 1, - 0x8000000000000000, - 0x123456789ABCDEF0, - 0x00000000FFFFFFFF, - 0xFFFFFFFFFFFFFFFF, - ] - for val in test_values: - with self.subTest(val=hex(val)): - res = run_synthetic_s_brev_b64(val) - self.assertEqual(res, ref_brev64(val)) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_scalar_debug_branch.py b/tests/semantic/test_scalar_debug_branch.py deleted file mode 100644 index c327ecde5..000000000 --- a/tests/semantic/test_scalar_debug_branch.py +++ /dev/null @@ -1,1169 +0,0 @@ -"""Semantic interpreter tests for AMD RDNA2 scalar debug branching and halt controls. - -Covers: - - s_cbranch_cdbgsys: conditional branch taken iff COND_DBG_SYS is non-zero - - s_cbranch_cdbguser: conditional branch taken iff COND_DBG_USER is non-zero - - s_cbranch_cdbgsys_or_user: conditional branch taken iff COND_DBG_SYS or COND_DBG_USER is non-zero - - s_cbranch_cdbgsys_and_user: conditional branch taken iff both COND_DBG_SYS and COND_DBG_USER are non-zero - - s_sethalt: set or clear wavefront execution halt state based on simm16 & 1, with fatal halt - detection (simm16 & 4) and privileged trap handler deferral (PRIV == 1) - - SOPP binary instruction encoding/decoding and 16-bit signed immediate offset arithmetic - - STATUS register packing/unpacking and hardware debug flag isolation - - Control-flow graph execution (skipping, polling loops, if-then-else joins) - - Privilege mode trap handler execution and pending halt commit upon exception return (s_rfe_b64) - - Negative controls and mutation sensitivity verification - -Standard library only; zero game data. -Compatible with Python 3.9+. - -Run: - python -I tests/semantic/test_scalar_debug_branch.py - python -m unittest discover -s tests/semantic -v -""" -from __future__ import annotations - -import dataclasses -import os -import random -import sys -import unittest - -HERE = os.path.dirname(os.path.abspath(__file__)) -ROOT = os.path.dirname(os.path.dirname(HERE)) -TOOLS_DIR = os.environ.get("LEONIDA_TOOLS_DIR") or os.path.join(ROOT, "tools") - -if ROOT not in sys.path: - sys.path.insert(0, ROOT) -if TOOLS_DIR not in sys.path: - sys.path.insert(0, TOOLS_DIR) - -import rdna2spirv # noqa: E402 -import shader_profile # noqa: E402 - -MASK16 = 0xFFFF -MASK32 = 0xFFFFFFFF -MASK64 = 0xFFFFFFFFFFFFFFFF - -# ----------------------------------------------------------------------------- -# 1. SOPP Binary Constants and Encodings (AMD RDNA2 / GFX10 Architecture) -# ----------------------------------------------------------------------------- - -# SOPP 32-bit instruction header: bits [31:23] = 0b101111111 (0x17F) -SOPP_HEADER = 0x17F - -# SOPP Opcodes -SOPP_OP_NOP = 0 -SOPP_OP_ENDPGM = 1 -SOPP_OP_BRANCH = 2 -SOPP_OP_CBRANCH_SCC0 = 4 -SOPP_OP_CBRANCH_SCC1 = 5 -SOPP_OP_CBRANCH_VCCZ = 6 -SOPP_OP_CBRANCH_VCCNZ = 7 -SOPP_OP_CBRANCH_EXECZ = 8 -SOPP_OP_CBRANCH_EXECNZ = 9 -SOPP_OP_SETHALT = 13 -SOPP_OP_TRAP = 18 -SOPP_OP_CBRANCH_CDBGSYS = 23 -SOPP_OP_CBRANCH_CDBGUSER = 24 -SOPP_OP_CBRANCH_CDBGSYS_OR_USER = 25 -SOPP_OP_CBRANCH_CDBGSYS_AND_USER = 26 - -SOPP_MNEMONIC_TO_OPCODE = { - "s_nop": SOPP_OP_NOP, - "s_endpgm": SOPP_OP_ENDPGM, - "s_branch": SOPP_OP_BRANCH, - "s_cbranch_scc0": SOPP_OP_CBRANCH_SCC0, - "s_cbranch_scc1": SOPP_OP_CBRANCH_SCC1, - "s_cbranch_vccz": SOPP_OP_CBRANCH_VCCZ, - "s_cbranch_vccnz": SOPP_OP_CBRANCH_VCCNZ, - "s_cbranch_execz": SOPP_OP_CBRANCH_EXECZ, - "s_cbranch_execnz": SOPP_OP_CBRANCH_EXECNZ, - "s_sethalt": SOPP_OP_SETHALT, - "s_trap": SOPP_OP_TRAP, - "s_cbranch_cdbgsys": SOPP_OP_CBRANCH_CDBGSYS, - "s_cbranch_cdbguser": SOPP_OP_CBRANCH_CDBGUSER, - "s_cbranch_cdbgsys_or_user": SOPP_OP_CBRANCH_CDBGSYS_OR_USER, - "s_cbranch_cdbgsys_and_user": SOPP_OP_CBRANCH_CDBGSYS_AND_USER, -} - -SOPP_OPCODE_TO_MNEMONIC = {v: k for k, v in SOPP_MNEMONIC_TO_OPCODE.items()} - - -# ----------------------------------------------------------------------------- -# 2. Pure Reference Oracles & Bit Arithmetic -# ----------------------------------------------------------------------------- - -def decode_simm16(raw16: int) -> int: - """Decode a 16-bit unsigned value to a signed Python integer in range [-32768, 32767].""" - raw = raw16 & MASK16 - return raw - 0x10000 if (raw & 0x8000) else raw - - -def encode_simm16(val: int) -> int: - """Encode a signed integer in range [-32768, 32767] to a 16-bit unsigned bit pattern.""" - if not -32768 <= val <= 32767: - raise ValueError(f"Immediate value {val} out of signed 16-bit range [-32768, 32767]") - return val & MASK16 - - -def compute_branch_target_bytes(current_pc_bytes: int, simm16: int) -> int: - """Calculate byte-address branch target: target = PC + 4 + (simm16 * 4) mod 2^32.""" - return (current_pc_bytes + 4 + (simm16 * 4)) & MASK32 - - -def compute_branch_target_dwords(current_pc_dwords: int, simm16: int) -> int: - """Calculate dword-indexed branch target: target = PC_dwords + 1 + simm16.""" - return current_pc_dwords + 1 + simm16 - - -def eval_cbranch_cdbgsys(cond_dbg_sys: bool) -> bool: - """s_cbranch_cdbgsys: branch taken iff COND_DBG_SYS is non-zero.""" - return bool(cond_dbg_sys) - - -def eval_cbranch_cdbguser(cond_dbg_user: bool) -> bool: - """s_cbranch_cdbguser: branch taken iff COND_DBG_USER is non-zero.""" - return bool(cond_dbg_user) - - -def eval_cbranch_cdbgsys_or_user(cond_dbg_sys: bool, cond_dbg_user: bool) -> bool: - """s_cbranch_cdbgsys_or_user: branch taken iff COND_DBG_SYS or COND_DBG_USER is non-zero.""" - return bool(cond_dbg_sys or cond_dbg_user) - - -def eval_cbranch_cdbgsys_and_user(cond_dbg_sys: bool, cond_dbg_user: bool) -> bool: - """s_cbranch_cdbgsys_and_user: branch taken iff both COND_DBG_SYS and COND_DBG_USER are non-zero.""" - return bool(cond_dbg_sys and cond_dbg_user) - - -def eval_sethalt(simm16: int, priv: bool = False) -> tuple[bool, bool, bool]: - """Evaluate s_sethalt immediate against current privilege mode. - - Returns: - (halt_immediate, pending_halt, fatal_halt) - - simm16[0] (bit 0): Halt flag (1 = halt, 0 = resume). - - simm16[2] (bit 2): Fatal halt flag. - - If priv is True (privileged execution in trap handler), halt cannot take - immediate effect; it is deferred into pending_halt until exception return. - """ - halt_req = bool(simm16 & 1) - fatal_req = bool((simm16 >> 2) & 1) - if priv: - return False, halt_req, fatal_req - return halt_req, False, fatal_req - - -def encode_sopp(opcode: int, simm16: int) -> int: - """Encode a 32-bit machine word for an SOPP instruction.""" - if not (0 <= opcode <= 0x7F): - raise ValueError(f"Opcode {opcode} out of 7-bit range [0, 127]") - raw16 = encode_simm16(simm16) - return (SOPP_HEADER << 23) | ((opcode & 0x7F) << 16) | raw16 - - -def decode_sopp(word: int) -> tuple[int, int]: - """Decode a 32-bit machine word into (opcode, simm16).""" - header = (word >> 23) & 0x1FF - if header != SOPP_HEADER: - raise ValueError(f"Invalid SOPP header: 0x{header:03X} (expected 0x{SOPP_HEADER:03X})") - opcode = (word >> 16) & 0x7F - raw16 = word & MASK16 - return opcode, decode_simm16(raw16) - - -# ----------------------------------------------------------------------------- -# 3. Wavefront Status Register & Hardware Simulation -# ----------------------------------------------------------------------------- - -@dataclasses.dataclass -class WaveStatus: - """AMD GPU Wavefront STATUS register bitfield representation. - - Bit layout follows AMD RDNA / GCN architecture conventions: - - Bit 0: SCC (Scalar Condition Code) - - Bit 10: HALT (Wavefront execution halted) - - Bit 12: COND_DBG_SYS (Conditional debug system flag) - - Bit 13: COND_DBG_USER (Conditional debug user flag) - - Bit 14: PENDING_HALT (Deferred halt bit while in privileged mode) - - Bit 16: PRIV (Privileged trap mode active) - - Bit 20: FATAL_HALT (Fatal halt occurred) - """ - scc: int = 0 - halt: bool = False - cond_dbg_sys: bool = False - cond_dbg_user: bool = False - pending_halt: bool = False - priv: bool = False - fatal_halt: bool = False - - def to_dword(self) -> int: - val = 0 - if self.scc: - val |= (1 << 0) - if self.halt: - val |= (1 << 10) - if self.cond_dbg_sys: - val |= (1 << 12) - if self.cond_dbg_user: - val |= (1 << 13) - if self.pending_halt: - val |= (1 << 14) - if self.priv: - val |= (1 << 16) - if self.fatal_halt: - val |= (1 << 20) - return val - - @classmethod - def from_dword(cls, dword: int) -> WaveStatus: - return cls( - scc=(dword >> 0) & 1, - halt=bool((dword >> 10) & 1), - cond_dbg_sys=bool((dword >> 12) & 1), - cond_dbg_user=bool((dword >> 13) & 1), - pending_halt=bool((dword >> 14) & 1), - priv=bool((dword >> 16) & 1), - fatal_halt=bool((dword >> 20) & 1), - ) - - -# ----------------------------------------------------------------------------- -# 4. Scalar Debug & Control Flow Interpreter -# ----------------------------------------------------------------------------- - -class ScalarDebugInterpreter: - """Semantic interpreter modeling scalar debug branching, halt, and trap mechanisms. - - Features: - 1. Dual execution modes: - - Symbolic CFG mode: executes a directed graph of labelled basic blocks. - - Binary bytecode mode: executes sequential 32-bit machine dwords with - real relative PC arithmetic (PC = PC + 1 + simm16). - 2. Hardware register simulation: - - SGPRs (128 scalar general-purpose registers). - - STATUS register (COND_DBG_SYS, COND_DBG_USER, HALT, PENDING_HALT, PRIV). - 3. Wavefront control: - - s_sethalt: immediately halts user execution or defers when in PRIV mode. - - s_trap: enters privileged mode (PRIV=1), saves PC, jumps to trap handler. - - s_rfe_b64: exits privileged mode (PRIV=0), restores PC, commits pending halt. - 4. Complete execution tracing and step counter for deterministic verification. - """ - - def __init__(self, num_sgprs: int = 128, status: WaveStatus | None = None): - self.sgprs = [0] * num_sgprs - self.status = status if status is not None else WaveStatus() - self.pc = 0 - self.saved_pc = 0 - self.trap_handler_entry: str | int | None = None - self.trace: list[str | int] = [] - self.step_count = 0 - - def reset_registers(self): - self.sgprs = [0] * len(self.sgprs) - self.pc = 0 - self.saved_pc = 0 - self.trace.clear() - self.step_count = 0 - - def unhalt(self): - """External debugger intervention: clear wavefront halt state and resume.""" - self.status.halt = False - self.status.pending_halt = False - self.status.fatal_halt = False - - def is_halted(self) -> bool: - return self.status.halt - - # --- Symbolic Basic Block Execution Mode --- - - def run_program( - self, - blocks: dict[str, list[tuple[str, ...] | str]], - start_block: str, - max_steps: int = 2000, - ): - """Execute a graph of basic blocks until s_endpgm, halt, or max_steps.""" - cur = start_block - self.trace = [] - self.step_count = 0 - - while cur is not None and self.step_count < max_steps: - if self.status.halt: - break - - self.step_count += 1 - self.trace.append(cur) - block = blocks.get(cur) - if block is None: - raise ValueError(f"Unknown block label: {cur}") - - next_block = None - for ins in block: - if isinstance(ins, str): - next_block = ins - break - - op = ins[0] - args = ins[1:] - - if op == "s_endpgm": - return - - elif op == "s_branch": - next_block = str(args[0]) - break - - elif op == "s_cbranch_cdbgsys": - target = str(args[0]) - if eval_cbranch_cdbgsys(self.status.cond_dbg_sys): - next_block = target - break - - elif op == "s_cbranch_cdbguser": - target = str(args[0]) - if eval_cbranch_cdbguser(self.status.cond_dbg_user): - next_block = target - break - - elif op == "s_cbranch_cdbgsys_or_user": - target = str(args[0]) - if eval_cbranch_cdbgsys_or_user(self.status.cond_dbg_sys, self.status.cond_dbg_user): - next_block = target - break - - elif op == "s_cbranch_cdbgsys_and_user": - target = str(args[0]) - if eval_cbranch_cdbgsys_and_user(self.status.cond_dbg_sys, self.status.cond_dbg_user): - next_block = target - break - - elif op == "s_sethalt": - imm = int(args[0]) - halt_now, pending, fatal = eval_sethalt(imm, priv=self.status.priv) - if halt_now: - self.status.halt = True - if pending: - self.status.pending_halt = True - if not (imm & 1): - self.status.halt = False - self.status.pending_halt = False - if fatal: - self.status.fatal_halt = True - if self.status.halt: - return - - elif op == "s_trap": - trap_id = int(args[0]) - self.status.priv = True - # Fallthrough target within the block or next block becomes saved_pc - if self.trap_handler_entry is not None: - next_block = str(self.trap_handler_entry) - break - - elif op == "s_rfe_b64": - self.status.priv = False - if self.status.pending_halt: - self.status.halt = True - self.status.pending_halt = False - return - if args: - next_block = str(args[0]) - break - - elif op == "s_mov_b32": - dst_s = int(args[0][1:]) if isinstance(args[0], str) and args[0].startswith("s") else int(args[0]) - if isinstance(args[1], str) and args[1].startswith("s"): - val = self.sgprs[int(args[1][1:])] - else: - val = int(args[1]) & MASK32 - self.sgprs[dst_s] = val - - elif op == "s_add_u32": - dst_s = int(args[0][1:]) if isinstance(args[0], str) and args[0].startswith("s") else int(args[0]) - s0 = int(args[1][1:]) if isinstance(args[1], str) and args[1].startswith("s") else int(args[1]) - val0 = self.sgprs[s0] - if isinstance(args[2], str) and args[2].startswith("s"): - val1 = self.sgprs[int(args[2][1:])] - else: - val1 = int(args[2]) & MASK32 - self.sgprs[dst_s] = (val0 + val1) & MASK32 - - elif op == "s_nop": - pass - - else: - raise ValueError(f"Unsupported instruction in interpreter: {op}") - - cur = next_block - - if self.step_count >= max_steps: - raise RuntimeError(f"Program exceeded maximum execution steps ({max_steps}); potential infinite loop.") - - # --- Binary Bytecode Execution Mode --- - - def run_bytecode( - self, - bytecode: list[int | tuple[str, ...]], - entry_pc: int = 0, - max_steps: int = 2000, - ): - """Execute a linear sequence of machine instructions (dwords or decoded tuples).""" - self.pc = entry_pc - self.trace = [] - self.step_count = 0 - - while 0 <= self.pc < len(bytecode) and self.step_count < max_steps: - if self.status.halt: - break - - self.step_count += 1 - curr_pc = self.pc - self.trace.append(curr_pc) - entry = bytecode[curr_pc] - - # Decode instruction if represented as raw 32-bit machine word - if isinstance(entry, int): - opcode, simm16 = decode_sopp(entry) - mnemonic = SOPP_OPCODE_TO_MNEMONIC.get(opcode) - if mnemonic is None: - raise ValueError(f"Unknown SOPP opcode: {opcode}") - op = mnemonic - args = (simm16,) - else: - op = entry[0] - args = entry[1:] - - next_pc = curr_pc + 1 - - if op == "s_endpgm": - self.pc = len(bytecode) - return - - elif op == "s_nop": - pass - - elif op == "s_branch": - simm16 = int(args[0]) - next_pc = compute_branch_target_dwords(curr_pc, simm16) - - elif op == "s_cbranch_cdbgsys": - simm16 = int(args[0]) - if eval_cbranch_cdbgsys(self.status.cond_dbg_sys): - next_pc = compute_branch_target_dwords(curr_pc, simm16) - - elif op == "s_cbranch_cdbguser": - simm16 = int(args[0]) - if eval_cbranch_cdbguser(self.status.cond_dbg_user): - next_pc = compute_branch_target_dwords(curr_pc, simm16) - - elif op == "s_cbranch_cdbgsys_or_user": - simm16 = int(args[0]) - if eval_cbranch_cdbgsys_or_user(self.status.cond_dbg_sys, self.status.cond_dbg_user): - next_pc = compute_branch_target_dwords(curr_pc, simm16) - - elif op == "s_cbranch_cdbgsys_and_user": - simm16 = int(args[0]) - if eval_cbranch_cdbgsys_and_user(self.status.cond_dbg_sys, self.status.cond_dbg_user): - next_pc = compute_branch_target_dwords(curr_pc, simm16) - - elif op == "s_sethalt": - simm16 = int(args[0]) - halt_now, pending, fatal = eval_sethalt(simm16, priv=self.status.priv) - if halt_now: - self.status.halt = True - if pending: - self.status.pending_halt = True - if not (simm16 & 1): - self.status.halt = False - self.status.pending_halt = False - if fatal: - self.status.fatal_halt = True - if self.status.halt: - self.pc = next_pc - return - - elif op == "s_trap": - trap_imm = int(args[0]) - self.saved_pc = next_pc - self.status.priv = True - if self.trap_handler_entry is not None: - next_pc = int(self.trap_handler_entry) - - elif op == "s_rfe_b64": - self.status.priv = False - if self.status.pending_halt: - self.status.halt = True - self.status.pending_halt = False - self.pc = self.saved_pc - return - next_pc = self.saved_pc - - elif op == "s_mov_b32": - dst_s = int(args[0][1:]) if isinstance(args[0], str) and args[0].startswith("s") else int(args[0]) - if isinstance(args[1], str) and args[1].startswith("s"): - val = self.sgprs[int(args[1][1:])] - else: - val = int(args[1]) & MASK32 - self.sgprs[dst_s] = val - - elif op == "s_add_u32": - dst_s = int(args[0][1:]) if isinstance(args[0], str) and args[0].startswith("s") else int(args[0]) - s0 = int(args[1][1:]) if isinstance(args[1], str) and args[1].startswith("s") else int(args[1]) - val0 = self.sgprs[s0] - if isinstance(args[2], str) and args[2].startswith("s"): - val1 = self.sgprs[int(args[2][1:])] - else: - val1 = int(args[2]) & MASK32 - self.sgprs[dst_s] = (val0 + val1) & MASK32 - - else: - raise ValueError(f"Unknown instruction in bytecode interpreter: {op}") - - self.pc = next_pc - - if self.step_count >= max_steps: - raise RuntimeError(f"Bytecode execution exceeded {max_steps} steps.") - - -# ============================================================================= -# Unit Tests -# ============================================================================= - -class TestDebugBranchReferenceOracles(unittest.TestCase): - """Mathematical reference oracle and truth table verification.""" - - def test_cbranch_cdbgsys_truth_table(self): - """s_cbranch_cdbgsys strictly follows the COND_DBG_SYS bit.""" - self.assertFalse(eval_cbranch_cdbgsys(False)) - self.assertTrue(eval_cbranch_cdbgsys(True)) - - def test_cbranch_cdbguser_truth_table(self): - """s_cbranch_cdbguser strictly follows the COND_DBG_USER bit.""" - self.assertFalse(eval_cbranch_cdbguser(False)) - self.assertTrue(eval_cbranch_cdbguser(True)) - - def test_cbranch_cdbgsys_or_user_truth_table(self): - """s_cbranch_cdbgsys_or_user behaves as logical OR.""" - self.assertFalse(eval_cbranch_cdbgsys_or_user(False, False)) - self.assertTrue(eval_cbranch_cdbgsys_or_user(False, True)) - self.assertTrue(eval_cbranch_cdbgsys_or_user(True, False)) - self.assertTrue(eval_cbranch_cdbgsys_or_user(True, True)) - - def test_cbranch_cdbgsys_and_user_truth_table(self): - """s_cbranch_cdbgsys_and_user behaves as logical AND.""" - self.assertFalse(eval_cbranch_cdbgsys_and_user(False, False)) - self.assertFalse(eval_cbranch_cdbgsys_and_user(False, True)) - self.assertFalse(eval_cbranch_cdbgsys_and_user(True, False)) - self.assertTrue(eval_cbranch_cdbgsys_and_user(True, True)) - - def test_de_morgan_duality(self): - """Verifies Boolean algebraic duality between OR and AND forms.""" - for sys_flag in (False, True): - for user_flag in (False, True): - or_res = eval_cbranch_cdbgsys_or_user(sys_flag, user_flag) - and_res = eval_cbranch_cdbgsys_and_user(sys_flag, user_flag) - # De Morgan: not (A or B) == (not A and not B) - self.assertEqual(not or_res, (not sys_flag) and (not user_flag)) - # De Morgan: not (A and B) == (not A or not B) - self.assertEqual(not and_res, (not sys_flag) or (not user_flag)) - - def test_simm16_offset_decoding_boundaries(self): - """Signed 16-bit offset decoding at extreme numerical limits.""" - self.assertEqual(decode_simm16(0x0000), 0) - self.assertEqual(decode_simm16(0x0001), 1) - self.assertEqual(decode_simm16(0x7FFF), 32767) - self.assertEqual(decode_simm16(0x8000), -32768) - self.assertEqual(decode_simm16(0xFFFF), -1) - self.assertEqual(decode_simm16(0xFFFE), -2) - - def test_simm16_offset_encoding_boundaries(self): - """Signed 16-bit offset encoding at extreme numerical limits.""" - self.assertEqual(encode_simm16(0), 0x0000) - self.assertEqual(encode_simm16(1), 0x0001) - self.assertEqual(encode_simm16(32767), 0x7FFF) - self.assertEqual(encode_simm16(-32768), 0x8000) - self.assertEqual(encode_simm16(-1), 0xFFFF) - self.assertEqual(encode_simm16(-2), 0xFFFE) - - with self.assertRaises(ValueError): - encode_simm16(32768) - with self.assertRaises(ValueError): - encode_simm16(-32769) - - def test_branch_target_byte_calculation(self): - """AMD ISA byte-address target arithmetic: target = PC + 4 + (simm16 * 4).""" - # PC at 0x1000, branch +0 -> next instruction at 0x1004 - self.assertEqual(compute_branch_target_bytes(0x1000, 0), 0x1004) - # Forward branch by 5 instructions (20 bytes) - self.assertEqual(compute_branch_target_bytes(0x1000, 5), 0x1018) - # Backward branch by 2 instructions (-8 bytes) -> 0x1004 - 8 = 0x0FFC - self.assertEqual(compute_branch_target_bytes(0x1000, -2), 0x0FFC) - # Wraparound around 32-bit address boundary - self.assertEqual(compute_branch_target_bytes(0xFFFFFFFC, 0), 0x00000000) - - -class TestSoppBinaryEncoding(unittest.TestCase): - """Verifies SOPP machine instruction binary layout and field encoding.""" - - def test_sopp_header_prefix(self): - """Bits [31:23] of SOPP instructions must match header 0b101111111 (0x17F).""" - encoded = encode_sopp(SOPP_OP_CBRANCH_CDBGSYS, 0) - self.assertEqual((encoded >> 23) & 0x1FF, SOPP_HEADER) - self.assertEqual(encoded & 0xFF800000, 0xBF800000) - - def test_sopp_opcode_extraction(self): - """Verify opcodes are correctly packed into bits [22:16].""" - ops_to_test = [ - ("s_cbranch_cdbgsys", SOPP_OP_CBRANCH_CDBGSYS), - ("s_cbranch_cdbguser", SOPP_OP_CBRANCH_CDBGUSER), - ("s_cbranch_cdbgsys_or_user", SOPP_OP_CBRANCH_CDBGSYS_OR_USER), - ("s_cbranch_cdbgsys_and_user", SOPP_OP_CBRANCH_CDBGSYS_AND_USER), - ("s_sethalt", SOPP_OP_SETHALT), - ("s_branch", SOPP_OP_BRANCH), - ("s_nop", SOPP_OP_NOP), - ] - for name, op_val in ops_to_test: - word = encode_sopp(op_val, 42) - extracted_op, extracted_imm = decode_sopp(word) - self.assertEqual(extracted_op, op_val, f"Mismatch for opcode {name}") - self.assertEqual(extracted_imm, 42) - - def test_sopp_negative_immediate_roundtrip(self): - """Preserves two's-complement sign extension across pack/unpack.""" - for imm in (-1, -16, -256, -1024, -32768, 0, 1, 127, 4096, 32767): - word = encode_sopp(SOPP_OP_CBRANCH_CDBGSYS, imm) - _, recovered_imm = decode_sopp(word) - self.assertEqual(recovered_imm, imm) - - def test_sopp_invalid_header_rejection(self): - """decode_sopp must reject words missing the valid SOPP prefix.""" - bad_word = 0x00000000 # Zero header - with self.assertRaises(ValueError): - decode_sopp(bad_word) - - -class TestWaveStatusRegister(unittest.TestCase): - """Verifies STATUS register bit packing, unpacking, and flag isolation.""" - - def test_status_roundtrip_default(self): - st = WaveStatus() - dword = st.to_dword() - self.assertEqual(dword, 0) - st_recovered = WaveStatus.from_dword(dword) - self.assertEqual(st, st_recovered) - - def test_status_individual_bits(self): - """Verify each flag maps to its exact expected hardware bit position.""" - self.assertEqual(WaveStatus(scc=1).to_dword(), 1 << 0) - self.assertEqual(WaveStatus(halt=True).to_dword(), 1 << 10) - self.assertEqual(WaveStatus(cond_dbg_sys=True).to_dword(), 1 << 12) - self.assertEqual(WaveStatus(cond_dbg_user=True).to_dword(), 1 << 13) - self.assertEqual(WaveStatus(pending_halt=True).to_dword(), 1 << 14) - self.assertEqual(WaveStatus(priv=True).to_dword(), 1 << 16) - self.assertEqual(WaveStatus(fatal_halt=True).to_dword(), 1 << 20) - - def test_status_compound_packing(self): - """Verify multiple active status bits unpack without crosstalk.""" - st = WaveStatus( - scc=1, - halt=False, - cond_dbg_sys=True, - cond_dbg_user=False, - pending_halt=True, - priv=True, - fatal_halt=False, - ) - dword = st.to_dword() - st2 = WaveStatus.from_dword(dword) - self.assertEqual(st, st2) - self.assertTrue(st2.cond_dbg_sys) - self.assertFalse(st2.cond_dbg_user) - self.assertTrue(st2.priv) - self.assertTrue(st2.pending_halt) - - -class TestScalarDebugBranchInterpreterCFG(unittest.TestCase): - """Verifies scalar debug branching within symbolic control-flow graphs.""" - - def test_cdbgsys_branch_taken_when_flag_set(self): - """When COND_DBG_SYS is True, s_cbranch_cdbgsys jumps to target block.""" - blocks = { - "entry": [ - ("s_mov_b32", 0, 100), - ("s_cbranch_cdbgsys", "debug_block"), - "release_block", - ], - "release_block": [ - ("s_mov_b32", 1, 200), - ("s_endpgm",), - ], - "debug_block": [ - ("s_mov_b32", 1, 999), - ("s_endpgm",), - ], - } - - interp = ScalarDebugInterpreter(status=WaveStatus(cond_dbg_sys=True)) - interp.run_program(blocks, "entry") - - self.assertEqual(interp.trace, ["entry", "debug_block"]) - self.assertEqual(interp.sgprs[0], 100) - self.assertEqual(interp.sgprs[1], 999) - - def test_cdbgsys_fallthrough_when_flag_clear(self): - """When COND_DBG_SYS is False, s_cbranch_cdbgsys falls through.""" - blocks = { - "entry": [ - ("s_mov_b32", 0, 100), - ("s_cbranch_cdbgsys", "debug_block"), - "release_block", - ], - "release_block": [ - ("s_mov_b32", 1, 200), - ("s_endpgm",), - ], - "debug_block": [ - ("s_mov_b32", 1, 999), - ("s_endpgm",), - ], - } - - interp = ScalarDebugInterpreter(status=WaveStatus(cond_dbg_sys=False)) - interp.run_program(blocks, "entry") - - self.assertEqual(interp.trace, ["entry", "release_block"]) - self.assertEqual(interp.sgprs[0], 100) - self.assertEqual(interp.sgprs[1], 200) - - def test_cdbguser_branch_taken_when_flag_set(self): - """When COND_DBG_USER is True, s_cbranch_cdbguser jumps to target block.""" - blocks = { - "entry": [ - ("s_mov_b32", 5, 50), - ("s_cbranch_cdbguser", "user_debug"), - "user_normal", - ], - "user_normal": [ - ("s_mov_b32", 6, 1), - ("s_endpgm",), - ], - "user_debug": [ - ("s_mov_b32", 6, 2), - ("s_endpgm",), - ], - } - - interp = ScalarDebugInterpreter(status=WaveStatus(cond_dbg_user=True)) - interp.run_program(blocks, "entry") - - self.assertEqual(interp.trace, ["entry", "user_debug"]) - self.assertEqual(interp.sgprs[5], 50) - self.assertEqual(interp.sgprs[6], 2) - - def test_flag_isolation_sys_does_not_trigger_user_branch(self): - """COND_DBG_SYS=True must not trigger s_cbranch_cdbguser.""" - blocks = { - "entry": [ - ("s_cbranch_cdbguser", "user_target"), - "fallthrough", - ], - "user_target": [ - ("s_mov_b32", 0, 0xBAD), - ("s_endpgm",), - ], - "fallthrough": [ - ("s_mov_b32", 0, 0x600D), - ("s_endpgm",), - ], - } - - interp = ScalarDebugInterpreter(status=WaveStatus(cond_dbg_sys=True, cond_dbg_user=False)) - interp.run_program(blocks, "entry") - - self.assertEqual(interp.trace, ["entry", "fallthrough"]) - self.assertEqual(interp.sgprs[0], 0x600D) - - def test_flag_isolation_user_does_not_trigger_sys_branch(self): - """COND_DBG_USER=True must not trigger s_cbranch_cdbgsys.""" - blocks = { - "entry": [ - ("s_cbranch_cdbgsys", "sys_target"), - "fallthrough", - ], - "sys_target": [ - ("s_mov_b32", 0, 0xBAD), - ("s_endpgm",), - ], - "fallthrough": [ - ("s_mov_b32", 0, 0x600D), - ("s_endpgm",), - ], - } - - interp = ScalarDebugInterpreter(status=WaveStatus(cond_dbg_sys=False, cond_dbg_user=True)) - interp.run_program(blocks, "entry") - - self.assertEqual(interp.trace, ["entry", "fallthrough"]) - self.assertEqual(interp.sgprs[0], 0x600D) - - def test_cdbgsys_or_user_branch_combinations(self): - """s_cbranch_cdbgsys_or_user branches if either or both flags are active.""" - for sys_flag in (False, True): - for user_flag in (False, True): - blocks = { - "entry": [ - ("s_cbranch_cdbgsys_or_user", "target"), - "fallthrough", - ], - "target": [ - ("s_mov_b32", 0, 1), - ("s_endpgm",), - ], - "fallthrough": [ - ("s_mov_b32", 0, 0), - ("s_endpgm",), - ], - } - - interp = ScalarDebugInterpreter( - status=WaveStatus(cond_dbg_sys=sys_flag, cond_dbg_user=user_flag) - ) - interp.run_program(blocks, "entry") - - expected_taken = sys_flag or user_flag - expected_trace = ["entry", "target"] if expected_taken else ["entry", "fallthrough"] - expected_val = 1 if expected_taken else 0 - - self.assertEqual(interp.trace, expected_trace) - self.assertEqual(interp.sgprs[0], expected_val) - - def test_cdbgsys_and_user_branch_combinations(self): - """s_cbranch_cdbgsys_and_user branches only when both flags are active.""" - for sys_flag in (False, True): - for user_flag in (False, True): - blocks = { - "entry": [ - ("s_cbranch_cdbgsys_and_user", "target"), - "fallthrough", - ], - "target": [ - ("s_mov_b32", 0, 1), - ("s_endpgm",), - ], - "fallthrough": [ - ("s_mov_b32", 0, 0), - ("s_endpgm",), - ], - } - - interp = ScalarDebugInterpreter( - status=WaveStatus(cond_dbg_sys=sys_flag, cond_dbg_user=user_flag) - ) - interp.run_program(blocks, "entry") - - expected_taken = sys_flag and user_flag - expected_trace = ["entry", "target"] if expected_taken else ["entry", "fallthrough"] - expected_val = 1 if expected_taken else 0 - - self.assertEqual(interp.trace, expected_trace) - self.assertEqual(interp.sgprs[0], expected_val) - - def test_structured_if_then_else_convergence(self): - """Diamond control-flow where debug and release paths re-converge.""" - blocks = { - "entry": [ - ("s_mov_b32", 0, 10), - ("s_cbranch_cdbgsys", "debug_path"), - "release_path", - ], - "release_path": [ - ("s_add_u32", 0, 0, 5), # 10 + 5 = 15 - ("s_branch", "join"), - ], - "debug_path": [ - ("s_add_u32", 0, 0, 100), # 10 + 100 = 110 - ("s_branch", "join"), - ], - "join": [ - ("s_add_u32", 0, 0, 1), # Final increment - ("s_endpgm",), - ], - } - - # Release mode run - interp_rel = ScalarDebugInterpreter(status=WaveStatus(cond_dbg_sys=False)) - interp_rel.run_program(blocks, "entry") - self.assertEqual(interp_rel.trace, ["entry", "release_path", "join"]) - self.assertEqual(interp_rel.sgprs[0], 16) - - # Debug mode run - interp_dbg = ScalarDebugInterpreter(status=WaveStatus(cond_dbg_sys=True)) - interp_dbg.run_program(blocks, "entry") - self.assertEqual(interp_dbg.trace, ["entry", "debug_path", "join"]) - self.assertEqual(interp_dbg.sgprs[0], 111) - - -class TestScalarSetHaltSemantics(unittest.TestCase): - """Verifies s_sethalt wavefront halting, resumption, and privilege handling.""" - - def test_immediate_halt_stops_wave(self): - """s_sethalt 1 terminates instruction progression immediately.""" - blocks = { - "entry": [ - ("s_mov_b32", 0, 42), - ("s_sethalt", 1), - ("s_mov_b32", 0, 999), # Should never be reached - ("s_endpgm",), - ], - } - - interp = ScalarDebugInterpreter() - interp.run_program(blocks, "entry") - - self.assertTrue(interp.is_halted()) - self.assertEqual(interp.sgprs[0], 42) - self.assertEqual(interp.trace, ["entry"]) - - def test_sethalt_zero_does_not_halt(self): - """s_sethalt 0 allows execution to proceed normally.""" - blocks = { - "entry": [ - ("s_mov_b32", 0, 42), - ("s_sethalt", 0), - ("s_mov_b32", 1, 84), - ("s_endpgm",), - ], - } - - interp = ScalarDebugInterpreter() - interp.run_program(blocks, "entry") - - self.assertFalse(interp.is_halted()) - self.assertEqual(interp.sgprs[0], 42) - self.assertEqual(interp.sgprs[1], 84) - - def test_sethalt_bitmask_evaluation(self): - """Only bit 0 dictates halt state (odd values halt, even values do not).""" - test_immediates = [ - (1, True, False), # Halt, not fatal - (0, False, False), # Resume, not fatal - (3, True, False), # Halt (bits 0 and 1) - (5, True, True), # Halt and Fatal (bits 0 and 2) - (4, False, True), # Fatal request without halt bit - (0xFFFF, True, True), # All bits set - (0xFFFE, False, True), # Bit 0 clear - ] - for imm, expect_halt, expect_fatal in test_immediates: - halt, _, fatal = eval_sethalt(imm, priv=False) - self.assertEqual(halt, expect_halt, f"Halt mismatch for imm={hex(imm)}") - self.assertEqual(fatal, expect_fatal, f"Fatal mismatch for imm={hex(imm)}") - - def test_unhalt_and_resumption(self): - """An external unhalt intervention allows execution to resume.""" - blocks = { - "entry": [ - ("s_mov_b32", 0, 1), - ("s_sethalt", 1), - "resumed", - ], - "resumed": [ - ("s_mov_b32", 0, 2), - ("s_endpgm",), - ], - } - - interp = ScalarDebugInterpreter() - interp.run_program(blocks, "entry") - self.assertTrue(interp.is_halted()) - self.assertEqual(interp.sgprs[0], 1) - - # Debugger unhalts the wave and continues execution from resumed block - interp.unhalt() - self.assertFalse(interp.is_halted()) - interp.run_program(blocks, "resumed") - self.assertEqual(interp.sgprs[0], 2) - - def test_privileged_trap_halt_deferral(self): - """s_sethalt 1 inside privileged trap mode defers halt until exception return.""" - blocks = { - "entry": [ - ("s_mov_b32", 0, 10), - ("s_trap", 1), - "after_trap", - ], - "trap_handler": [ - ("s_mov_b32", 1, 20), - ("s_sethalt", 1), # Inside PRIV mode: deferred! - ("s_mov_b32", 1, 30), # Trap handler continues executing - ("s_rfe_b64", "after_trap"), # Return from exception: commits halt! - ], - "after_trap": [ - ("s_mov_b32", 0, 999), # Should NOT execute because wave halted upon rfe - ("s_endpgm",), - ], - } - - interp = ScalarDebugInterpreter() - interp.trap_handler_entry = "trap_handler" - interp.run_program(blocks, "entry") - - # The wave should have executed entry -> trap_handler, then halted at rfe - self.assertTrue(interp.is_halted()) - self.assertEqual(interp.sgprs[0], 10) # User code did not advance to 999 - self.assertEqual(interp.sgprs[1], 30) # Trap handler ran fully to completion - self.assertIn("trap_handler", interp.trace) - self.assertNotIn("after_trap", interp.trace) - - -class TestLinearBytecodeExecution(unittest.TestCase): - """Verifies binary SOPP bytecode execution and PC-relative jump arithmetic.""" - - def test_bytecode_forward_branch_cdbgsys(self): - """Verify binary s_cbranch_cdbgsys skipping instructions when taken.""" - # Program: - # 0: s_mov_b32 s0, 10 - # 1: s_cbranch_cdbgsys +2 (jumps to instruction 1 + 1 + 2 = 4) - # 2: s_mov_b32 s0, 20 (skipped if taken) - # 3: s_mov_b32 s1, 30 (skipped if taken) - # 4: s_mov_b32 s2, 40 (target) - # 5: s_endpgm - insn_branch = encode_sopp(SOPP_OP_CBRANCH_CDBGSYS, 2) - insn_end = encode_sopp(SOPP_OP_ENDPGM, 0) - - bytecode: list[int | tuple[str, ...]] = [ - ("s_mov_b32", 0, 10), - insn_branch, - ("s_mov_b32", 0, 20), - ("s_mov_b32", 1, 30), - ("s_mov_b32", 2, 40), - insn_end, - ] - - # Case A: Debug flag True -> branch taken, jumps over 2 and 3 - interp_taken = ScalarDebugInterpreter(status=WaveStatus(cond_dbg_sys=True)) - interp_taken.run_bytecode(bytecode) - self.assertEqual(interp_taken.trace, [0, 1, 4, 5]) - self.assertEqual(interp_taken.sgprs[0], 10) - self.assertEqual(interp_taken.sgprs[1], 0) # Not executed - self.assertEqual(interp_taken.sgprs[2], 40) - - # Case B: Debug flag False -> branch not taken, falls through - interp_fallthrough = ScalarDebugInterpreter(status=WaveStatus(cond_dbg_sys=False)) - interp_fallthrough.run_bytecode(bytecode) - self.assertEqual(interp_fallthrough.trace, [0, 1, 2, 3, 4, 5]) - self.assertEqual(interp_fallthrough.sgprs[0], 20) # Overwritten - self.assertEqual(interp_fallthrough.sgprs[1], 30) - self.assertEqual(interp_fallthrough.sgprs[2], 40) - - def test_bytecode_backward_branch_loop(self): - """Verify binary backward branch looping with s_branch.""" - # Program: Count down s0 from 3 to 0 - # 0: s_mov_b32 s0, 3 - # 1: s_add_u32 s0, s0, -1 (in two's complement: 0xFFFFFFFF) - # 2: s_cbranch_cdbgsys -2 (if debug is active, loop back to 1; target = 2 + 1 - 2 = 1) - # 3: s_endpgm - loop_branch = encode_sopp(SOPP_OP_CBRANCH_CDBGSYS, -2) - bytecode: list[int | tuple[str, ...]] = [ - ("s_mov_b32", 0, 3), - ("s_add_u32", 0, 0, MASK32), # Subtract 1 - loop_branch, - encode_sopp(SOPP_OP_ENDPGM, 0), - ] - - # Single step through without loop (flag False) - interp = ScalarDebugInterpreter(status=WaveStatus(cond_dbg_sys=False)) - interp.run_bytecode(bytecode) - self.assertEqual(interp.trace, [0, 1, 2, 3]) - self.assertEqual(interp.sgprs[0], 2) - - def test_bytecode_sethalt_binary_encoded(self): - """Verify binary encoded s_sethalt execution.""" - insn_halt = encode_sopp(SOPP_OP_SETHALT, 1) - bytecode = [ - ("s_mov_b32", 0, 777), - insn_halt, - ("s_mov_b32", 0, 888), - encode_sopp(SOPP_OP_ENDPGM, 0), - ] - - interp = ScalarDebugInterpreter() - interp.run_bytecode(bytecode) - - self.assertTrue(interp.is_halted()) - self.assertEqual(interp.sgprs[0], 777) - self.assertEqual(interp.trace, [0, 1]) - - -class TestToolingIntegrationAndClassification(unittest.TestCase): - """Verifies that debug branch instructions integrate properly with shader tooling.""" - - def test_shader_profile_classification(self): - """shader_profile must classify scalar debug branches as 'branch'.""" - self.assertEqual(shader_profile.classify_instruction("s_cbranch_cdbgsys"), "branch") - self.assertEqual(shader_profile.classify_instruction("s_cbranch_cdbguser"), "branch") - self.assertEqual(shader_profile.classify_instruction("s_cbranch_cdbgsys_or_user"), "branch") - self.assertEqual(shader_profile.classify_instruction("s_cbranch_cdbgsys_and_user"), "branch") - - self.assertTrue(shader_profile.is_branch("s_cbranch_cdbgsys")) - self.assertTrue(shader_profile.is_branch("s_cbranch_cdbguser")) - self.assertTrue(shader_profile.is_branch("s_cbranch_cdbgsys_or_user")) - self.assertTrue(shader_profile.is_branch("s_cbranch_cdbgsys_and_user")) - - def test_rdna2spirv_branches_separation(self): - """Debug branches are hardware/debugger specific and excluded from standard SPIR-V CFG branches.""" - self.assertNotIn("s_cbranch_cdbgsys", rdna2spirv.BRANCHES) - self.assertNotIn("s_cbranch_cdbguser", rdna2spirv.BRANCHES) - self.assertIn("s_branch", rdna2spirv.BRANCHES) - self.assertIn("s_cbranch_scc0", rdna2spirv.BRANCHES) - self.assertIn("s_cbranch_scc1", rdna2spirv.BRANCHES) - - -class TestNegativeControlsAndMutations(unittest.TestCase): - """Verifies test assertions detect mutations or inverted logic.""" - - def test_inverted_cdbgsys_condition_detected(self): - """Mutating eval_cbranch_cdbgsys to invert logic must fail.""" - def inverted_eval(flag: bool) -> bool: - return not flag - - self.assertNotEqual(eval_cbranch_cdbgsys(True), inverted_eval(True)) - self.assertNotEqual(eval_cbranch_cdbgsys(False), inverted_eval(False)) - - def test_inverted_sethalt_bit_detected(self): - """Mutating eval_sethalt to check bit 1 instead of bit 0 must fail on odd values.""" - def bad_sethalt(imm: int) -> bool: - return bool((imm >> 1) & 1) - - self.assertNotEqual(eval_sethalt(1)[0], bad_sethalt(1)) - self.assertNotEqual(eval_sethalt(2)[0], bad_sethalt(2)) - - def test_unsigned_offset_interpretation_detected(self): - """Treating SIMM16 as unsigned converts negative jumps into out-of-range positive jumps.""" - def unsigned_decode(raw: int) -> int: - return raw & 0xFFFF - - negative_pattern = 0xFFFF # -1 in two's complement - self.assertEqual(decode_simm16(negative_pattern), -1) - self.assertEqual(unsigned_decode(negative_pattern), 65535) - self.assertNotEqual(decode_simm16(negative_pattern), unsigned_decode(negative_pattern)) - - def test_missing_trap_deferral_detected(self): - """If halt is not deferred in privileged mode, trap handlers would freeze prematurely.""" - halt_immediate, pending, _ = eval_sethalt(1, priv=True) - self.assertFalse(halt_immediate, "Halt must not be immediate when in privileged trap handler") - self.assertTrue(pending, "Halt must be stored as pending when in privileged trap handler") - - def test_infinite_loop_guard(self): - """Interpreter must raise RuntimeError if branch loop exceeds max_steps.""" - blocks = { - "loop": [ - ("s_branch", "loop"), - ], - } - interp = ScalarDebugInterpreter() - with self.assertRaises(RuntimeError): - interp.run_program(blocks, "loop", max_steps=50) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_scalar_mem_smem.py b/tests/semantic/test_scalar_mem_smem.py deleted file mode 100644 index 1ea98ba3e..000000000 --- a/tests/semantic/test_scalar_mem_smem.py +++ /dev/null @@ -1,913 +0,0 @@ -"""Semantic interpreter tests for scalar memory read offsets and descriptor address calculation (s_load_dword). - -Covers AMD RDNA2 / GFX10 SMEM (Scalar Memory) ISA semantics and tools/rdna2spirv.py translation: - * 64-bit base pointer reconstruction from SGPR pair s[p:p+1] - * Buffer Resource Descriptor (V#) 128-bit layout and base address extraction: - - Dword 0: Base address low 32 bits [31:0] - - Dword 1: Base address high 16 bits [47:32] in bits [15:0]; bits [31:16] are format/stride/flags - - Proper masking (dword1 & 0xFFFF) preventing descriptor flags from polluting the 64-bit pointer - * Read offset calculations: - - Zero offset, immediate byte offsets, and SGPR dynamic offsets - - 32-bit carry propagation across the 4GB boundary into the upper 32 bits - - 64-bit address wrapping modulo 2^64 - * Multi-dword scalar loads (s_load_dword, s_load_dwordx2, x4, x8, x16) with sequential 4-byte address strides - * Destination register targeting: SGPR ranges and special registers (vcc_lo, vcc_hi, vcc pair, m0) - * tools/rdna2spirv.py translator validation (Gen.scalar_load instruction sequences and operand validation) - * SMEM loads with a register offset and an immediate at once ("sOFF offset:IMM"): address = base + sOFF + IMM, - checked by running the emitted code (SmemBodyEvaluator, SmemSoffsetImmTranslatorTests) - * The hardware-measured SMEM rules (SmemHardwareRuleTests): base, sOFF and IMM truncated to 4 each, the - s_buffer_load NUM_RECORDS bound per dword (no read past it), the stride limit, the signed s_load immediate - * spirv_mini_interp strictness validation (rejecting unmodelled 64-bit types and PhysicalStorageBuffer) -""" -import os -import sys -import unittest - -HERE = os.path.dirname(os.path.abspath(__file__)) -ROOT = os.path.dirname(os.path.dirname(HERE)) -TOOLS_DIR = os.environ.get("LEONIDA_TOOLS_DIR") or os.path.join(ROOT, "tools") - -sys.dont_write_bytecode = True -if TOOLS_DIR not in sys.path: - sys.path.insert(0, TOOLS_DIR) -if HERE not in sys.path: - sys.path.insert(0, HERE) - -import rdna2spirv # noqa: E402 -from shader_ir import parse_line # noqa: E402 -import spirv_mini_interp as si # noqa: E402 - -MASK32 = 0xFFFFFFFF -MASK64 = 0xFFFFFFFFFFFFFFFF - - -def compute_smem_pointer_address(base_lo: int, base_hi: int, offset: int) -> int: - """Compute 64-bit effective address for s_load_dword from 64-bit pointer and offset.""" - base_64 = ((base_hi & MASK32) << 32) | (base_lo & MASK32) - return (base_64 + (offset & MASK32)) & MASK64 - - -def compute_smem_descriptor_address(desc_dw0: int, desc_dw1: int, offset: int) -> int: - """Compute 64-bit effective address for s_buffer_load_dword from buffer descriptor V# and offset. - - Per AMD RDNA2 ISA: - - dword0: Base address [31:0] - - dword1: Base address [47:32] in bits [15:0]. Bits [31:16] are format/stride metadata. - """ - base_hi = desc_dw1 & 0xFFFF - base_64 = (base_hi << 32) | (desc_dw0 & MASK32) - return (base_64 + (offset & MASK32)) & MASK64 - - -class SmemMemoryBank: - """Deterministic simulated memory bank for SMEM load validation.""" - - def __init__(self): - self._mem = {} - - def write_dword(self, byte_addr: int, val: int) -> None: - self._mem[byte_addr & MASK64] = val & MASK32 - - def read_dword(self, byte_addr: int) -> int: - return self._mem.get(byte_addr & MASK64, 0) - - -class SmemReferenceInterpreter: - """Reference execution engine for RDNA2 scalar memory loads.""" - - def __init__(self, memory: SmemMemoryBank): - self.mem = memory - self.sgpr = [0] * 106 - self.vcc_lo = 0 - self.vcc_hi = 0 - self.m0 = 0 - - def load_register(self, name: str, reg_idx: int = 0) -> int: - if name == "sgpr": - return self.sgpr[reg_idx] & MASK32 - if name == "vcc_lo": - return self.vcc_lo & MASK32 - if name == "vcc_hi": - return self.vcc_hi & MASK32 - if name == "m0": - return self.m0 & MASK32 - raise ValueError(f"unknown register {name}") - - def store_register(self, name: str, reg_idx: int, val: int) -> None: - val &= MASK32 - if name == "sgpr": - self.sgpr[reg_idx] = val - elif name == "vcc_lo": - self.vcc_lo = val - elif name == "vcc_hi": - self.vcc_hi = val - elif name == "m0": - self.m0 = val - else: - raise ValueError(f"unknown register {name}") - - def execute_s_load(self, count: int, dest_reg: str, dest_idx: int, - base_lo_idx: int, offset: int) -> int: - lo = self.load_register("sgpr", base_lo_idx) - hi = self.load_register("sgpr", base_lo_idx + 1) - addr = compute_smem_pointer_address(lo, hi, offset) - for i in range(count): - dword_val = self.mem.read_dword(addr + i * 4) - if dest_reg == "sgpr": - self.store_register("sgpr", dest_idx + i, dword_val) - elif dest_reg == "vcc": - if i == 0: - self.store_register("vcc_lo", 0, dword_val) - elif i == 1: - self.store_register("vcc_hi", 0, dword_val) - elif dest_reg in ("vcc_lo", "vcc_hi", "m0"): - self.store_register(dest_reg, 0, dword_val) - return addr - - def execute_s_buffer_load(self, count: int, dest_reg: str, dest_idx: int, - desc_dw0_idx: int, offset: int) -> int: - dw0 = self.load_register("sgpr", desc_dw0_idx) - dw1 = self.load_register("sgpr", desc_dw0_idx + 1) - addr = compute_smem_descriptor_address(dw0, dw1, offset) - for i in range(count): - dword_val = self.mem.read_dword(addr + i * 4) - if dest_reg == "sgpr": - self.store_register("sgpr", dest_idx + i, dword_val) - elif dest_reg == "vcc": - if i == 0: - self.store_register("vcc_lo", 0, dword_val) - elif i == 1: - self.store_register("vcc_hi", 0, dword_val) - elif dest_reg in ("vcc_lo", "vcc_hi", "m0"): - self.store_register(dest_reg, 0, dword_val) - return addr - - -class SmemAddressOracleTests(unittest.TestCase): - """Verifies SMEM 64-bit effective address calculations and V# descriptor masking.""" - - def test_s_load_pointer_address_basic(self): - cases = [ - (0x1000, 0x0, 0, 0x1000), - (0x1000, 0x0, 16, 0x1010), - (0x1000, 0x0, 0x40, 0x1040), - (0x2000, 0x1, 0x100, 0x100002100), - (0x00000000, 0x00000008, 0x200, 0x800000200), - ] - for lo, hi, off, expected in cases: - with self.subTest(lo=hex(lo), hi=hex(hi), off=hex(off)): - self.assertEqual(compute_smem_pointer_address(lo, hi, off), expected) - - def test_s_load_pointer_carry_into_upper_32_bits(self): - # Adding offset to low dword crossing 0xFFFFFFFF boundary must carry into hi dword. - cases = [ - (0xFFFFFFFC, 0x00000001, 8, 0x0000000200000004), - (0xFFFFFFFF, 0x00000000, 1, 0x0000000100000000), - (0xFFFFFFF0, 0x00000005, 0x20, 0x0000000600000010), - (0xFFFFFFFF, 0x0000000F, 0xFFFFFFFF, 0x00000010FFFFFFFE), - ] - for lo, hi, off, expected in cases: - with self.subTest(lo=hex(lo), hi=hex(hi), off=hex(off)): - self.assertEqual(compute_smem_pointer_address(lo, hi, off), expected) - - def test_s_load_pointer_wrap_modulo_64(self): - # 64-bit overflow wraps around to 0 - self.assertEqual(compute_smem_pointer_address(0xFFFFFFF0, 0xFFFFFFFF, 0x20), 0x0000000000000010) - self.assertEqual(compute_smem_pointer_address(0xFFFFFFFF, 0xFFFFFFFF, 1), 0) - - def test_s_buffer_load_descriptor_masking(self): - # Bits [31:16] of dword 1 contain format/stride/cache attributes; - # only bits [15:0] participate in base address formation. - cases = [ - # dw0, dw1, offset, expected_addr - (0x00001000, 0x00000002, 0x10, 0x0000000200001010), - # dw1 has 0x8004 in bits [31:16] (typical buffer resource metadata) - (0x00001000, 0x80040002, 0x10, 0x0000000200001010), - # dw1 has all upper 16 bits set (0xFFFF0000) - (0x12345678, 0xFFFF0007, 0x0, 0x0000000712345678), - # dw1 has format bits set, address bits 0 - (0x00000040, 0x3F000000, 0x20, 0x0000000000000060), - # Carry from dw0 into masked dw1 - (0xFFFFFFF8, 0x80000001, 0x10, 0x0000000200000008), - ] - for dw0, dw1, off, expected in cases: - with self.subTest(dw0=hex(dw0), dw1=hex(dw1), off=hex(off)): - self.assertEqual(compute_smem_descriptor_address(dw0, dw1, off), expected) - - -class SmemExecutionTests(unittest.TestCase): - """Verifies multi-dword scalar loads, sequential strides, and register targets.""" - - def setUp(self): - self.bank = SmemMemoryBank() - self.interp = SmemReferenceInterpreter(self.bank) - - def test_s_load_dword_single(self): - # Base s[2:3] = 0x1_00000000, offset = 0x20 -> address 0x1_00000020 - self.interp.store_register("sgpr", 2, 0x00000000) - self.interp.store_register("sgpr", 3, 0x00000001) - self.bank.write_dword(0x100000020, 0xCAFEBABE) - - addr = self.interp.execute_s_load(1, "sgpr", 4, 2, 0x20) - self.assertEqual(addr, 0x100000020) - self.assertEqual(self.interp.load_register("sgpr", 4), 0xCAFEBABE) - - def test_s_load_dwordx2_sequential_stride(self): - self.interp.store_register("sgpr", 6, 0x00001000) - self.interp.store_register("sgpr", 7, 0x00000000) - self.bank.write_dword(0x1000, 0x11112222) - self.bank.write_dword(0x1004, 0x33334444) - - addr = self.interp.execute_s_load(2, "sgpr", 8, 6, 0) - self.assertEqual(addr, 0x1000) - self.assertEqual(self.interp.load_register("sgpr", 8), 0x11112222) - self.assertEqual(self.interp.load_register("sgpr", 9), 0x33334444) - - def test_s_load_dwordx4_sequential_stride(self): - self.interp.store_register("sgpr", 0, 0x00002000) - self.interp.store_register("sgpr", 1, 0x00000000) - expected_words = [0xA0000001, 0xA0000002, 0xA0000003, 0xA0000004] - for i, val in enumerate(expected_words): - self.bank.write_dword(0x2010 + i * 4, val) - - addr = self.interp.execute_s_load(4, "sgpr", 12, 0, 0x10) - self.assertEqual(addr, 0x2010) - for i, val in enumerate(expected_words): - self.assertEqual(self.interp.load_register("sgpr", 12 + i), val) - - def test_s_load_dwordx8_sequential_stride(self): - self.interp.store_register("sgpr", 0, 0x00004000) - self.interp.store_register("sgpr", 1, 0x00000000) - for i in range(8): - self.bank.write_dword(0x4000 + i * 4, 0xB0000000 | i) - - addr = self.interp.execute_s_load(8, "sgpr", 16, 0, 0) - self.assertEqual(addr, 0x4000) - for i in range(8): - self.assertEqual(self.interp.load_register("sgpr", 16 + i), 0xB0000000 | i) - - def test_s_load_dwordx16_sequential_stride(self): - self.interp.store_register("sgpr", 0, 0x00008000) - self.interp.store_register("sgpr", 1, 0x00000000) - for i in range(16): - self.bank.write_dword(0x8000 + i * 4, 0xC0000000 | i) - - addr = self.interp.execute_s_load(16, "sgpr", 32, 0, 0) - self.assertEqual(addr, 0x8000) - for i in range(16): - self.assertEqual(self.interp.load_register("sgpr", 32 + i), 0xC0000000 | i) - - def test_s_buffer_load_dword_with_descriptor_masking(self): - # V# descriptor: dw0 = 0x5000, dw1 = 0x80040003 (stride=0x8004, hi_addr=3) - self.interp.store_register("sgpr", 8, 0x00005000) - self.interp.store_register("sgpr", 9, 0x80040003) - self.interp.store_register("sgpr", 10, 0x00010000) # num_records - self.interp.store_register("sgpr", 11, 0x00140000) # flags - - expected_addr = 0x0000000300005040 - self.bank.write_dword(expected_addr, 0x99887766) - - addr = self.interp.execute_s_buffer_load(1, "sgpr", 20, 8, 0x40) - self.assertEqual(addr, expected_addr) - self.assertEqual(self.interp.load_register("sgpr", 20), 0x99887766) - - def test_special_destination_registers(self): - self.interp.store_register("sgpr", 0, 0x1000) - self.interp.store_register("sgpr", 1, 0x0) - self.bank.write_dword(0x1000, 0x12345678) - self.bank.write_dword(0x1004, 0x9ABCDEF0) - - # Single dword to vcc_lo - self.interp.execute_s_load(1, "vcc_lo", 0, 0, 0) - self.assertEqual(self.interp.load_register("vcc_lo"), 0x12345678) - - # Single dword to vcc_hi - self.interp.execute_s_load(1, "vcc_hi", 0, 0, 4) - self.assertEqual(self.interp.load_register("vcc_hi"), 0x9ABCDEF0) - - # Single dword to m0 - self.interp.execute_s_load(1, "m0", 0, 0, 0) - self.assertEqual(self.interp.load_register("m0"), 0x12345678) - - # Two dwords to vcc pair (low to vcc_lo, high to vcc_hi) - self.interp.execute_s_load(2, "vcc", 0, 0, 0) - self.assertEqual(self.interp.load_register("vcc_lo"), 0x12345678) - self.assertEqual(self.interp.load_register("vcc_hi"), 0x9ABCDEF0) - - -class SmemTranslatorGenTests(unittest.TestCase): - """Tests tools/rdna2spirv.py Gen.scalar_load SPIR-V emission structure and validation rules.""" - - def test_s_load_dword_emits_64bit_shift_or_add(self): - g = rdna2spirv.Gen("ps") - ins = parse_line("s_load_dword s0, s[2:3], 0x10") - g.scalar_load(ins["op"], ins["args"], ins["mods"]) - text = "\n".join(g.body) - - self.assertIn("OpShiftLeftLogical %ulong", text) - self.assertIn("OpBitwiseOr %ulong", text) - self.assertIn("OpIAdd %ulong", text) - self.assertIn("OpConvertUToPtr %_ptr_PSB_arr", text) - self.assertIn("OpAccessChain %_ptr_PSB_uint", text) - self.assertIn("OpLoad %uint", text) - self.assertIn("Aligned 4", text) - self.assertTrue(g.uses_psb) - - def test_s_buffer_load_dword_emits_cffff_mask(self): - g = rdna2spirv.Gen("ps") - ins = parse_line("s_buffer_load_dword s4, s[8:11], 0x20") - g.scalar_load(ins["op"], ins["args"], ins["mods"]) - text = "\n".join(g.body) - - self.assertIn("OpBitwiseAnd %uint", text) - self.assertIn("%cffff", text) - self.assertIn("OpConvertUToPtr %_ptr_PSB_arr", text) - self.assertTrue(g.uses_psb) - - def test_multi_dword_emission_counts(self): - cases = [ - ("s_load_dword s0, s[2:3], 0", 1), - ("s_load_dwordx2 s[0:1], s[2:3], 0", 2), - ("s_load_dwordx4 s[0:3], s[4:5], 0", 4), - ("s_load_dwordx8 s[0:7], s[8:9], 0", 8), - ("s_load_dwordx16 s[0:15], s[16:17], 0", 16), - ("s_buffer_load_dword s0, s[4:7], 0", 1), - ("s_buffer_load_dwordx4 s[0:3], s[8:11], 0", 4), - ("s_buffer_load_dwordx8 s[0:7], s[8:11], 0", 8), - ] - for line, expected_n in cases: - with self.subTest(line=line): - g = rdna2spirv.Gen("ps") - ins = parse_line(line) - g.scalar_load(ins["op"], ins["args"], ins["mods"]) - psb_chains = [ln for ln in g.body if "OpAccessChain %_ptr_PSB_uint" in ln] - psb_loads = [ln for ln in g.body if "OpLoad %uint" in ln and "Aligned 4" in ln] - self.assertEqual(len(psb_chains), expected_n) - self.assertEqual(len(psb_loads), expected_n) - - def test_special_destinations_emission(self): - for line in ("s_buffer_load_dword vcc_lo, s[0:3], 0", - "s_buffer_load_dword vcc_hi, s[0:3], 4", - "s_buffer_load_dword m0, s[0:3], 8", - "s_load_dwordx2 vcc, s[0:1], 0"): - with self.subTest(line=line): - g = rdna2spirv.Gen("ps") - ins = parse_line(line) - g.scalar_load(ins["op"], ins["args"], ins["mods"]) - self.assertTrue(g.uses_psb) - - def test_unsupported_operands_raise_cleanly(self): - # Base must have n=2 for s_load - g = rdna2spirv.Gen("ps") - ins_bad_sload_base = parse_line("s_load_dword s0, s[0:3], 0") - with self.assertRaises(rdna2spirv.Unsupported) as ctx: - g.scalar_load(ins_bad_sload_base["op"], ins_bad_sload_base["args"], ins_bad_sload_base["mods"]) - self.assertIn("s_load without 64-bit pointer", str(ctx.exception)) - - # Base must have n=4 for s_buffer_load - ins_bad_sbuf_base = parse_line("s_buffer_load_dword s0, s[0:1], 0") - with self.assertRaises(rdna2spirv.Unsupported) as ctx: - g.scalar_load(ins_bad_sbuf_base["op"], ins_bad_sbuf_base["args"], ins_bad_sbuf_base["mods"]) - self.assertIn("s_buffer_load without V#", str(ctx.exception)) - - # Non-SGPR base must raise - ins_vgpr_base = parse_line("s_load_dword s0, v[0:1], 0") - with self.assertRaises(rdna2spirv.Unsupported): - g.scalar_load(ins_vgpr_base["op"], ins_vgpr_base["args"], ins_vgpr_base["mods"]) - - -class SmemBodyEvaluator: - """Runs the SPIR-V that Gen.scalar_load emits, against concrete SGPR values and a dword memory. - - spirv_mini_interp refuses 64-bit integers and PhysicalStorageBuffer by design, so the address a scalar load - reads cannot be checked there. This evaluator knows only the handful of instructions scalar_load uses and - raises on anything else, so a change in the emitted code cannot be approximated silently. It follows the - forward selection constructs the bounds check emits (OpSelectionMerge, OpBranchConditional, OpBranch to a later - label, OpPhi naming the block it came from). The heap base (push constant dwords 32..33) is 0 unless given, - which makes every address read an Xbox VA. - """ - - def __init__(self, gen, sgpr, memory, heap_base=0): - self.consts = {name: value for value, name in gen.consts.items()} - self.consts.update({name: value for value, name in gen.lconsts.items()}) - self.sgpr = dict(sgpr) - self.memory = memory - self.heap_base = heap_base - self.ids = {} - self.reads = [] # byte address of every PhysicalStorageBuffer dword load, in order - lines = [line.split() for line in gen.body] - labels = {w[0]: i for i, w in enumerate(lines) if len(w) == 3 and w[1:] == ["=", "OpLabel"]} - self.block, self.came_from = "%entry", None - pc = 0 - while pc < len(lines): - words = lines[pc] - if words[0] == "OpSelectionMerge": - pc += 1 - continue - target = None - if words[0] == "OpBranch": - target = words[1] - elif words[0] == "OpBranchConditional": - cond = self._value(words[1]) - if not isinstance(cond, bool): - raise AssertionError("OpBranchConditional on a non-bool") - target = words[2] if cond else words[3] - if target is not None: - if labels.get(target, -1) <= pc: - raise AssertionError("branch backwards or to an unknown label: " + " ".join(words)) - self.came_from, pc = self.block, labels[target] - continue - if len(words) == 3 and words[1:] == ["=", "OpLabel"]: - if self.block != words[0] and pc > 0 and lines[pc - 1][0] not in ("OpBranch", "OpBranchConditional"): - raise AssertionError("fall-through into " + words[0]) - self.block = words[0] - pc += 1 - continue - self._step(words) - pc += 1 - - def _value(self, name): - if name == "%heap_base": # built once in the entry block, outside the body run here - return self.heap_base - if name == "%c64_32": - return 32 - if name in self.ids: - return self.ids[name] - if name in self.consts: - return self.consts[name] - raise AssertionError(f"unknown id {name}") - - def _step(self, words): - if words[0] == "OpStore": - kind, index = self._value(words[1]) - if kind != "sgpr": - raise AssertionError(f"store through {kind}") - self.sgpr[index] = self._value(words[2]) - return - if len(words) < 4 or words[1] != "=": - raise AssertionError("unmodelled line: " + " ".join(words)) - result, op, ty, args = words[0], words[2], words[3], words[4:] - if op == "OpAccessChain" and ty == "%_ptr_Function_uint" and args[0] == "%sgpr": - value = ("sgpr", self._value(args[1])) - elif op == "OpAccessChain" and ty == "%_ptr_PSB_uint": - kind, address = self._value(args[0]) - if kind != "psb": - raise AssertionError(f"PSB access chain on {kind}") - value = ("mem", (address + 4 * self._value(args[1])) & MASK64) - elif op == "OpLoad" and ty == "%uint": - kind, where = self._value(args[0]) - if kind == "sgpr": - value = self.sgpr.get(where, 0) & MASK32 - elif kind == "mem" and args[1:] == ["Aligned", "4"]: - self.reads.append(where) - value = self.memory.read_dword(where) - else: - raise AssertionError("unmodelled load: " + " ".join(words)) - elif op == "OpPhi" and ty == "%uint": - pairs = dict(zip(args[1::2], args[0::2])) - if len(args) % 2 or self.came_from not in pairs: - raise AssertionError("OpPhi without the block it came from: " + " ".join(words)) - value = self._value(pairs[self.came_from]) - elif op == "OpBitwiseAnd" and ty == "%uint": - value = self._value(args[0]) & self._value(args[1]) - elif op == "OpBitFieldUExtract" and ty == "%uint": - value = (self._value(args[0]) >> self._value(args[1])) & ((1 << self._value(args[2])) - 1) - elif op == "OpIAdd" and ty == "%uint": - value = (self._value(args[0]) + self._value(args[1])) & MASK32 - elif op == "OpUConvert" and ty == "%ulong": - value = self._value(args[0]) & MASK32 - elif op == "OpShiftLeftLogical" and ty == "%ulong": - value = (self._value(args[0]) << self._value(args[1])) & MASK64 - elif op == "OpBitwiseOr" and ty == "%ulong": - value = self._value(args[0]) | self._value(args[1]) - elif op == "OpIAdd" and ty == "%ulong": - value = (self._value(args[0]) + self._value(args[1])) & MASK64 - elif op == "OpIMul" and ty == "%ulong": - value = (self._value(args[0]) * self._value(args[1])) & MASK64 - elif op == "OpIEqual" and ty == "%bool": - value = self._value(args[0]) == self._value(args[1]) - elif op == "OpUGreaterThanEqual" and ty == "%bool": - value = self._value(args[0]) >= self._value(args[1]) - elif op == "OpSelect" and ty in ("%ulong", "%uint"): - cond = self._value(args[0]) - if not isinstance(cond, bool): - raise AssertionError("OpSelect on a non-bool") - value = self._value(args[1] if cond else args[2]) - elif op == "OpConvertUToPtr" and ty == "%_ptr_PSB_arr": - value = ("psb", self._value(args[0])) - else: - raise AssertionError("unmodelled instruction: " + " ".join(words)) - self.ids[result] = value - - -class SmemSoffsetImmTranslatorTests(unittest.TestCase): - """SMEM loads that carry a register offset and an immediate at once: llvm-mc prints "sOFF offset:IMM". - - Rule: address = base + soffset + imm (+ 4*i for dword i). - Measured on an AMD Radeon RX 6800 (gfx1030) by running s_buffer_load_dword/x2/x4/x8 as a raw compute kernel: - soffset 8 + imm 4 reads the dword at +12. s_load_dword with both offsets was measured later (soffset 8 + imm 4 - reads +12 too, SmemHardwareRuleTests.test_s_load_truncates_pointer_and_offsets). - Every case here is dword-aligned and in bounds; truncation and NUM_RECORDS are SmemHardwareRuleTests. - - The instruction lines are hand-written. Each case runs the code Gen.scalar_load emits with SmemBodyEvaluator - and asserts both the addresses read and the values that land in the destination SGPRs. - """ - - VSHARP_BASE = 0x0000000200001000 # s24 = 0x00001000, s25 = 0x80040002 (flags above bit 15 are not address) - POINTER = 0x0000000300004000 # s[24:25] for s_load - - def run_load(self, line, pointer=False): - ins = parse_line(line) - g = rdna2spirv.Gen("ps") - g.scalar_load(ins["op"], ins["args"], ins["mods"]) - base = self.POINTER if pointer else self.VSHARP_BASE - bank = SmemMemoryBank() - for off in range(0, 0x40, 4): # every dword near the base holds its own offset, tagged - bank.write_dword(base + off, 0x5EED0000 | off) - sgpr = {40: 8} # the register offset used by every case - if pointer: - sgpr.update({24: 0x00004000, 25: 0x00000003}) - else: - sgpr.update({24: 0x00001000, 25: 0x80040002, 26: 0x00010000, 27: 0x00140000}) - ev = SmemBodyEvaluator(g, sgpr, bank) - return ev, [a - base for a in ev.reads], g - - def test_s_buffer_load_dword_soffset_plus_imm(self): - # The measured case: soffset 8 + imm 4 reads the dword at +12 (not +8, which is what dropping the imm gives). - ev, offsets, _ = self.run_load("s_buffer_load_dword s12, s[24:27], s40 offset:0x4") - self.assertEqual(offsets, [12]) - self.assertEqual(ev.sgpr[12], 0x5EED000C) - - def test_s_load_dword_soffset_plus_imm(self): - # Measured on the same GPU later (soffset 8 + imm 4 reads +12). - ev, offsets, _ = self.run_load("s_load_dword s12, s[24:25], s40 offset:0x4", pointer=True) - self.assertEqual(offsets, [12]) - self.assertEqual(ev.sgpr[12], 0x5EED000C) - - def test_multi_dword_soffset_plus_imm(self): - cases = [ - ("s_buffer_load_dwordx2 s[12:13], s[24:27], s40 offset:0x4", False, 2, 0x0C), - ("s_buffer_load_dwordx4 s[12:15], s[24:27], s40 offset:0x10", False, 4, 0x18), - ("s_buffer_load_dwordx8 s[12:19], s[24:27], s40 offset:0x14", False, 8, 0x1C), - ("s_load_dwordx2 s[12:13], s[24:25], s40 offset:0x4", True, 2, 0x0C), - ("s_load_dwordx4 s[12:15], s[24:25], s40 offset:0x10", True, 4, 0x18), - ] - for line, pointer, n, first in cases: - with self.subTest(line=line): - ev, offsets, _ = self.run_load(line, pointer) - self.assertEqual(offsets, [first + 4 * i for i in range(n)]) - self.assertEqual([ev.sgpr[12 + i] for i in range(n)], [0x5EED0000 | (first + 4 * i) for i in range(n)]) - - def test_imm_only_and_soffset_only_addresses_unchanged(self): - cases = [ - ("s_buffer_load_dword s12, s[24:27], 0x4", False, [0x04]), - ("s_buffer_load_dword s12, s[24:27], s40", False, [0x08]), - ("s_buffer_load_dwordx2 s[12:13], s[24:27], 0x10", False, [0x10, 0x14]), - ("s_buffer_load_dwordx4 s[12:15], s[24:27], s40", False, [0x08, 0x0C, 0x10, 0x14]), - ("s_load_dword s12, s[24:25], 0x4", True, [0x04]), - ("s_load_dword s12, s[24:25], s40", True, [0x08]), - ("s_load_dwordx2 s[12:13], s[24:25], 0", True, [0x00, 0x04]), - ("s_load_dwordx2 s[12:13], s[24:25], s40", True, [0x08, 0x0C]), - ] - for line, pointer, want in cases: - with self.subTest(line=line): - ev, offsets, _ = self.run_load(line, pointer) - self.assertEqual(offsets, want) - self.assertEqual([ev.sgpr[12 + i] for i in range(len(want))], [0x5EED0000 | o for o in want]) - - def test_zero_imm_with_soffset_reads_the_soffset_address(self): - ev, offsets, _ = self.run_load("s_buffer_load_dword s12, s[24:27], s40 offset:0x0") - self.assertEqual(offsets, [8]) - self.assertEqual(ev.sgpr[12], 0x5EED0008) - - def test_non_sgpr_scalar_register_offset_plus_imm(self): - # llvm-mc also accepts m0, vcc_lo or null as the register offset. null reads as zero; m0 is not an SGPR slot, - # so only check that the form still translates and that the immediate changes the code. - ev, offsets, _ = self.run_load("s_buffer_load_dword s12, s[24:27], null offset:0x14") - self.assertEqual(offsets, [0x14]) - self.assertEqual(ev.sgpr[12], 0x5EED0014) - bodies = [] - for line in ("s_buffer_load_dword s12, s[24:27], m0", "s_buffer_load_dword s12, s[24:27], m0 offset:0x4"): - ins = parse_line(line) - g = rdna2spirv.Gen("ps") - g.scalar_load(ins["op"], ins["args"], ins["mods"]) - bodies.append(g.body) - self.assertNotEqual(bodies[0], bodies[1]) - - def test_offset_modifier_changes_the_emitted_code(self): - for line, pointer in (("s_buffer_load_dword s12, s[24:27], s40", False), - ("s_load_dword s12, s[24:25], s40", True)): - with self.subTest(line=line): - _, _, plain = self.run_load(line, pointer) - _, _, both = self.run_load(line + " offset:0x4", pointer) - self.assertNotEqual(plain.body, both.body) - - def test_heap_base_is_added_once(self): - # The V# needs a NUM_RECORDS that covers +12: with s26 unset (NUM_RECORDS 0) the measured bound makes the - # load return 0 without reading memory (SmemHardwareRuleTests), and there would be no address to check. - ins = parse_line("s_buffer_load_dword s12, s[24:27], s40 offset:0x4") - g = rdna2spirv.Gen("ps") - g.scalar_load(ins["op"], ins["args"], ins["mods"]) - ev = SmemBodyEvaluator(g, {24: 0x1000, 25: 0, 26: 0x10000, 40: 8}, SmemMemoryBank(), - heap_base=0x0000007F00000000) - self.assertEqual(ev.reads, [0x0000007F00000000 + 0x1000 + 12]) - - def test_offset_forms_the_assembler_rejects_raise(self): - # llvm-mc accepts none of these; hand-written or damaged listings must not translate to a guessed address. - for line in ("s_buffer_load_dword s12, s[24:27], 0x8 offset:0x4", # immediate operand and offset modifier - "s_buffer_load_dword s12, s[24:27], s40 offset:zz", # unparseable immediate - "s_buffer_load_dword s12, s[24:27], s40 offset:0x4 offset:0x8", - "s_buffer_load_dword s12, s[24:27], s40, 0x4", # a fourth operand - "s_load_dword s12, s[24:25], 0x8 offset:0x4"): - with self.subTest(line=line): - ins = parse_line(line) - g = rdna2spirv.Gen("ps") - with self.assertRaises(rdna2spirv.Unsupported): - g.scalar_load(ins["op"], ins["args"], ins["mods"]) - - -class PatternMemory: - """Byte-addressed memory: byte n of the region at `region` holds (0x40 + n) & 0xff, for any n (also n < 0). - - The measurement filled its buffer the same way, so "data@+X" in the oracle's model is the dword this returns at - region + X; an unaligned read returns the bytes at that exact address.""" - - def __init__(self, region): - self.region = region - - def read_dword(self, address): - return int.from_bytes(bytes((0x40 + address + k - self.region) & 0xFF for k in range(4)), "little") - - def data(self, offset): - return self.read_dword(self.region + offset) - - -class SmemHardwareRuleTests(unittest.TestCase): - """The SMEM rules measured on an AMD Radeon RX 6800 (gfx1030), raw compute kernel, wave32 and wave64: - - off = (sOFF & ~3) + (IMM & ~3); dword i reads (base & ~3) + off + 4*i - s_buffer_load*: dword i is 0 and is not read when off + 4*i + 4 > limit; - limit = NUM_RECORDS * stride (stride = V# dword1[29:16]) or NUM_RECORDS when stride is 0 - s_load*: IMM is sign-extended from 21 bits, the sum is 64-bit, no bound - - Each case is a row of that measurement (the row names of the oracle's model are in the comments; the rule is in - docs/design.md, Scalar/buffer memory). Every case checks the value in the destination SGPRs and the set of - dword addresses read: an out-of-range dword must not be read at all. In `want`, an int X is the data at - region offset X and None is 0. The lines are hand-written; the evaluator runs the code Gen.scalar_load emits. - """ - - REGION = 0x0000000500002000 - - def run_line(self, line, sgpr, *, pointer=False, base_low=0, known=None): - ins = parse_line(line) - g = rdna2spirv.Gen("ps") - g.sgpr_imm.update(known or {}) # SGPRs the translator knows as constants (an s_mov before) - g.scalar_load(ins["op"], ins["args"], ins["mods"]) - regs = dict(sgpr) - address = self.REGION + base_low - regs[24] = address & MASK32 - if pointer: - regs[25] = address >> 32 - else: - regs[25] = (regs.pop("stride", 0) << 16) | (address >> 32) - regs[26] = regs.pop("nr") - regs[27] = 0x31016FAC # word3 of the measurement (OOB_SELECT 3) - mem = PatternMemory(self.REGION) - ev = SmemBodyEvaluator(g, regs, mem) - return ev, [a - self.REGION for a in ev.reads], mem - - def check(self, line, sgpr, want, reads, **kw): - ev, got_reads, mem = self.run_line(line, sgpr, **kw) - values = [0 if w is None else mem.data(w) for w in want] - self.assertEqual([f"{ev.sgpr.get(12 + i, 0):#010x}" for i in range(len(want))], - [f"{v:#010x}" for v in values], line) - # The addresses read, as a set: an out-of-range dword re-reads the load's first dword (in range whenever any - # dword is) instead of taking a branch of its own, so a dword may be read twice; what must hold is that - # nothing outside the bound is read at all. - self.assertEqual(sorted({hex(r) for r in got_reads}), sorted({hex(r) for r in reads}), line) - - # s_buffer_load_dword, stride 0 - def test_bound_counts_the_whole_dword(self): - # q1imm-k0-1[1]: imm 0x10, NR 18 -> 0 (a start-only check, 0x10 < 18, would read it) - self.check("s_buffer_load_dword s12, s[24:27], 0x10", {"nr": 18}, [None], []) - # q1imm-k0-3[11]: imm 0x14, NR 21 -> 0 - self.check("s_buffer_load_dword s12, s[24:27], 0x14", {"nr": 21}, [None], []) - # the last dword that fits: imm 0x10, NR 20 -> data - self.check("s_buffer_load_dword s12, s[24:27], 0x10", {"nr": 20}, [0x10], [0x10]) - - def test_bound_uses_the_truncated_offset(self): - # q1imm-k0-3[10]: imm 0x13, NR 21 -> data@+0x10 (raw 0x13 + 4 > 21 would give 0) - self.check("s_buffer_load_dword s12, s[24:27], 0x13", {"nr": 21}, [0x10], [0x10]) - # q1imm-k0-1[2]: imm 0x11, NR 18 -> 0 - self.check("s_buffer_load_dword s12, s[24:27], 0x11", {"nr": 18}, [None], []) - - def test_soffset_and_imm_are_truncated_before_they_are_added(self): - # q1pair-k0-0[1]: soffset 0xe + imm 2, NR 16 -> data@+0xc (truncating the sum, 0x10, would be out) - self.check("s_buffer_load_dword s12, s[24:27], s40 offset:0x2", {"nr": 16, 40: 0xE}, [0xC], [0xC]) - # q1pair-k0-3[6]: soffset 0x10 + imm 4, NR 20 -> 0 - self.check("s_buffer_load_dword s12, s[24:27], s40 offset:0x4", {"nr": 20, 40: 0x10}, [None], []) - # s0-k1[6], s0-k1[7]: soffset 3 + imm 3 -> data@+0; soffset 2 + imm 6 -> data@+4 - self.check("s_buffer_load_dword s12, s[24:27], s40 offset:0x3", {"nr": 0x1000, 40: 3}, [0x0], [0x0]) - self.check("s_buffer_load_dword s12, s[24:27], s40 offset:0x6", {"nr": 0x1000, 40: 2}, [0x4], [0x4]) - # q1soff-k0-3[7], [11]: soffset alone 0x13 -> data@+0x10, 0x14 -> 0 (NR 21) - self.check("s_buffer_load_dword s12, s[24:27], s40", {"nr": 21, 40: 0x13}, [0x10], [0x10]) - self.check("s_buffer_load_dword s12, s[24:27], s40", {"nr": 21, 40: 0x14}, [None], []) - - def test_base_low_bits_are_dropped_and_not_part_of_the_bound(self): - # s0-k1[1]: base & 3 = 1, imm 3 -> data@+0 (the unaligned sum would read bytes 4..7) - self.check("s_buffer_load_dword s12, s[24:27], 0x3", {"nr": 0x1000}, [0x0], [0x0], base_low=1) - # q1imm-k3-2[10], [13]: base & 3 = 3, imm 0x10 and 0x13, NR 20 -> data@+0x10 - self.check("s_buffer_load_dword s12, s[24:27], 0x10", {"nr": 20}, [0x10], [0x10], base_low=3) - self.check("s_buffer_load_dword s12, s[24:27], 0x13", {"nr": 20}, [0x10], [0x10], base_low=3) - - def test_multi_dword_loads_are_bounded_per_dword(self): - # multi-k0-3: x4 at 0xc, NR 21 -> data, data, 0, 0; x8 at 0, NR 21 -> d0..d4 data, d5..d7 0 - self.check("s_buffer_load_dwordx4 s[12:15], s[24:27], 0xc", {"nr": 21}, - [0xC, 0x10, None, None], [0xC, 0x10]) - self.check("s_buffer_load_dwordx8 s[12:19], s[24:27], 0x0", {"nr": 21}, - [0x0, 0x4, 0x8, 0xC, 0x10, None, None, None], [0x0, 0x4, 0x8, 0xC, 0x10]) - # multi-k0-0: x4 at 0xc, NR 17 -> d0 data, d1..d3 0 - self.check("s_buffer_load_dwordx4 s[12:15], s[24:27], 0xc", {"nr": 17}, - [0xC, None, None, None], [0xC]) - # x2 with a soffset: 0x10 + 0, NR 0x16 -> data, 0 - self.check("s_buffer_load_dwordx2 s[12:13], s[24:27], s40", {"nr": 0x16, 40: 0x10}, - [0x10, None], [0x10]) - - def test_stride_makes_the_limit_num_records_times_stride(self): - # q2stride-k0-0[1], [3], [4]: stride 4, NR 5 -> limit 20: imm 4 and 0x10 data, 0x14 -> 0 - self.check("s_buffer_load_dword s12, s[24:27], 0x4", {"nr": 5, "stride": 4}, [0x4], [0x4]) - self.check("s_buffer_load_dword s12, s[24:27], 0x10", {"nr": 5, "stride": 4}, [0x10], [0x10]) - self.check("s_buffer_load_dword s12, s[24:27], 0x14", {"nr": 5, "stride": 4}, [None], []) - # stride 1, NR 17, imm 0x10 -> 0 (the index rule, 16 < 17, would read it) - self.check("s_buffer_load_dword s12, s[24:27], 0x10", {"nr": 17, "stride": 1}, [None], []) - # stride 16, NR 2: 0x1c data, 0x20 0 - self.check("s_buffer_load_dword s12, s[24:27], 0x1c", {"nr": 2, "stride": 16}, [0x1C], [0x1C]) - self.check("s_buffer_load_dword s12, s[24:27], 0x20", {"nr": 2, "stride": 16}, [None], []) - - def test_immediate_is_unsigned(self): - # big[0], big[1]: imm 0xffffc, NR 0x100000 -> data@+0xffffc; NR 0xfffff -> 0 - self.check("s_buffer_load_dword s12, s[24:27], 0xffffc", {"nr": 0x100000}, [0xFFFFC], [0xFFFFC]) - self.check("s_buffer_load_dword s12, s[24:27], 0xffffc", {"nr": 0xFFFFF}, [None], []) - - def test_num_records_zero_reads_nothing(self): - self.check("s_buffer_load_dwordx4 s[12:15], s[24:27], 0x0", {"nr": 0}, [None] * 4, []) - - # SHADER-336, measured on gfx1036 (Ryzen 9 9950X3D iGPU, tools/smem_neg_probe.py --oracle hw), wave32 = wave64. - # Each row runs twice: sOFF in a register, and sOFF known to the translator (folded into the constant). - def both(self, line, soff, want, reads, extra=None, **kw): - self.check(line, {40: soff, **(extra or {})}, want, reads, **kw) - self.check(line, {40: soff, **(extra or {})}, want, reads, known={40: soff}, **kw) - - def test_s_load_negative_sum_is_a_64_bit_signed_offset(self): - self.check("s_load_dword s12, s[24:25], -0x4", {}, [-4], [-4], pointer=True) - self.check("s_load_dword s12, s[24:25], -0x40", {}, [-0x40], [-0x40], pointer=True) - self.both("s_load_dword s12, s[24:25], s40 offset:-0x8", 4, [-4], [-4], pointer=True) - self.both("s_load_dword s12, s[24:25], s40 offset:-0x1", 6, [0], [0], pointer=True) # 4 + -4, not 5 & ~3 - self.both("s_load_dword s12, s[24:25], s40 offset:-0x20", 0xC, [-0x14], [-0x14], pointer=True) - self.both("s_load_dwordx2 s[12:13], s[24:25], s40 offset:-0x10", 4, [-0xC, -8], [-0xC, -8], pointer=True) - - def test_s_buffer_load_soffset_sum_does_not_wrap_at_32_bits(self): - # sOFF 0xfffffffc + IMM 8 is 0x1_0000_0004, past NUM_RECORDS: 0 on hardware, in both translator forms - self.both("s_buffer_load_dword s12, s[24:27], s40 offset:0x8", 0xFFFFFFFC, [None], [], extra={"nr": 0x100}) - self.both("s_buffer_load_dword s12, s[24:27], s40 offset:0x20", 0xFFFFFFF0, [None], [], extra={"nr": 0x100}) - for soff in (0xFFFFFFFC, 0x80000000, 0x7FFFFFFC): - self.both("s_buffer_load_dword s12, s[24:27], s40", soff, [None], [], extra={"nr": 0x100}) - self.both("s_buffer_load_dword s12, s[24:27], s40", 8, [8], [8], extra={"nr": 0x100}) - - # Measured on gfx1036 (RDNA2, Ryzen 9 9950X3D iGPU, AMD Windows driver 32.0.21045.16010) through tools/hw_oracle, - # wave32 = wave64, every read inside a seeded region so only the bound decides: the edges docs/design.md listed - # as not measured. - def test_x16_is_bounded_per_dword(self): - # x16 at 0, NR 0x14 -> d0..d4 data, d5..d15 0; NR 0x40 -> all 16 data - line = "s_buffer_load_dwordx16 s[40:55], s[24:27], 0x0" - self.check_wide(line, {"nr": 0x14}, [4 * i if i < 5 else None for i in range(16)]) - self.check_wide(line, {"nr": 0x40}, [4 * i for i in range(16)]) - # x16 with imm 8 or soffset 8, NR 0x20 -> d0..d5 data (bytes 8..0x1f), d6..d15 0 - self.check_wide("s_buffer_load_dwordx16 s[40:55], s[24:27], 0x8", {"nr": 0x20}, - [8 + 4 * i if i < 6 else None for i in range(16)]) - self.check_wide("s_buffer_load_dwordx16 s[40:55], s[24:27], s20", {"nr": 0x20, 20: 8}, - [8 + 4 * i if i < 6 else None for i in range(16)]) - - def test_num_records_times_stride_does_not_wrap_at_4gib(self): - # stride 0x1000 x NR 0x100000 and 0x2000 x 0x80000 = 2^32, stride 8 x NR 0x20000001 = 2^32 + 8: all four - # dwords are data. A 32-bit product (0, 0, 8) would give 0 for every dword, or for d2 and d3. - for stride, nr in ((0x1000, 0x100000), (0x2000, 0x80000), (8, 0x20000001)): - self.check("s_buffer_load_dwordx4 s[12:15], s[24:27], 0x0", {"nr": nr, "stride": stride}, - [0x0, 0x4, 0x8, 0xC], [0x0, 0x4, 0x8, 0xC]) - # control from the same run: stride 8 x NR 1 = 8 bytes -> d0, d1 data, d2, d3 0 - self.check("s_buffer_load_dwordx4 s[12:15], s[24:27], 0x0", {"nr": 1, "stride": 8}, - [0x0, 0x4, None, None], [0x0, 0x4]) - - def test_num_records_at_or_above_2_31_is_unsigned(self): - for nr in (0x80000000, 0xFFFFFFFF): - self.check("s_buffer_load_dwordx4 s[12:15], s[24:27], 0x0", {"nr": nr}, - [0x0, 0x4, 0x8, 0xC], [0x0, 0x4, 0x8, 0xC]) - - def check_wide(self, line, sgpr, want): - """check() for a destination starting at s40 (a 16-dword load does not fit below the V# in s[24:27]).""" - ev, got_reads, mem = self.run_line(line, sgpr) - values = [0 if w is None else mem.data(w) for w in want] - self.assertEqual([f"{ev.sgpr.get(40 + i, 0):#010x}" for i in range(len(want))], - [f"{v:#010x}" for v in values], line) - self.assertEqual(sorted({hex(r) for r in got_reads}), sorted({hex(w) for w in want if w is not None}), line) - - # s_load: 64-bit pointer, no bound - def test_s_load_truncates_pointer_and_offsets(self): - # p0-k1[0]: ptr & 3 = 1, imm 1 -> data@+0; p0-k1[6]: soffset 3 + imm 3 -> data@+0; p0-k1[8]: 8 + 4 -> +0xc - self.check("s_load_dword s12, s[24:25], 0x1", {}, [0x0], [0x0], pointer=True, base_low=1) - self.check("s_load_dword s12, s[24:25], s40 offset:0x3", {40: 3}, [0x0], [0x0], pointer=True) - self.check("s_load_dword s12, s[24:25], s40 offset:0x4", {40: 8}, [0xC], [0xC], pointer=True) - # p1-0: nothing clamps - self.check("s_load_dword s12, s[24:25], s40 offset:0xffffc", {40: 0x100000}, [0x1FFFFC], [0x1FFFFC], - pointer=True) - - def test_s_load_immediate_is_signed(self): - # neg[0], neg[1]: soffset 8, imm -4 -> data@+4; imm -8 -> data@+0 (zero-extension reads 4 GiB further) - self.check("s_load_dword s12, s[24:25], s40 offset:-0x4", {40: 8}, [0x4], [0x4], pointer=True) - self.check("s_load_dword s12, s[24:25], s40 offset:-0x8", {40: 8}, [0x0], [0x0], pointer=True) - # neg[3], neg[10]: soffset 0xb, imm -1 -> data@+4 (8 + -4; truncating the sum 0xa would read +8) - self.check("s_load_dword s12, s[24:25], s40 offset:-0x1", {40: 0xB}, [0x4], [0x4], pointer=True) - self.check("s_load_dword s12, s[24:25], s40 offset:-0x1", {40: 0xB}, [0x4], [0x4], pointer=True, - base_low=3) - # neg[6]: soffset 0x100000, imm -0x100000 -> data@+0 - self.check("s_load_dword s12, s[24:25], s40 offset:-0x100000", {40: 0x100000}, [0x0], [0x0], pointer=True) - self.check("s_load_dwordx2 s[12:13], s[24:25], s40 offset:-0x8", {40: 0x10}, [0x8, 0xC], [0x8, 0xC], - pointer=True) - - def test_s_load_negative_total_is_the_signed_sum(self): - # NOT measured (it could not be probed safely): an immediate-only negative offset, i.e. soffset + imm < 0. - # The translator uses the 64-bit signed sum, which reads below the pointer; this pins that inference. - self.check("s_load_dword s12, s[24:25], -0x4", {}, [-0x4], [-0x4], pointer=True) - - -class SmemMiniInterpStrictnessTests(unittest.TestCase): - """Verifies that spirv_mini_interp rejects storage classes and constructs it does not model. - - As documented in tests/semantic/README.md, the mini-interpreter shares no code with the translator - and raises UnsupportedConstruct for anything not explicitly modelled (such as physical-storage-buffer - OpVariables, odd integer widths, or pointer-to-int casts), guaranteeing that translator regressions fail - tests immediately. 64-bit integers, OpConvertUToPtr and physical-storage-buffer loads are modelled; their - positive paths are covered in test_interp.py and test_value_semantics.py. - """ - - def test_rejects_unsupported_integer_widths(self): - module = """\ -OpCapability Shader -OpMemoryModel Logical GLSL450 -OpEntryPoint Fragment %main "main" -%void = OpTypeVoid -%ushort = OpTypeInt 16 0 -%fn = OpTypeFunction %void -%main = OpFunction %void None %fn -%entry = OpLabel -OpReturn -OpFunctionEnd -""" - with self.assertRaises(si.UnsupportedConstruct) as ctx: - si.run_fragment(module) - self.assertIn("integer type that is not 32 or 64 bits", str(ctx.exception)) - - def test_rejects_physical_storage_buffer_storage_class(self): - module = """\ -OpCapability Shader -OpCapability PhysicalStorageBufferAddresses -OpMemoryModel PhysicalStorageBuffer64 GLSL450 -OpEntryPoint Fragment %main "main" -%void = OpTypeVoid -%uint = OpTypeInt 32 0 -%_ptr_PSB = OpTypePointer PhysicalStorageBuffer %uint -%var = OpVariable %_ptr_PSB PhysicalStorageBuffer -%fn = OpTypeFunction %void -%main = OpFunction %void None %fn -%entry = OpLabel -OpReturn -OpFunctionEnd -""" - with self.assertRaises(si.UnsupportedConstruct) as ctx: - si.run_fragment(module) - self.assertIn("storage class PhysicalStorageBuffer", str(ctx.exception)) - - def test_rejects_convert_ptr_to_u_in_body(self): - module = """\ -OpCapability Shader -OpMemoryModel Logical GLSL450 -OpEntryPoint Fragment %main "main" -%void = OpTypeVoid -%uint = OpTypeInt 32 0 -%_ptr_Func = OpTypePointer Function %uint -%fn = OpTypeFunction %void -%c1 = OpConstant %uint 1 -%main = OpFunction %void None %fn -%entry = OpLabel -%p = OpConvertUToPtr %_ptr_Func %c1 -%u = OpConvertPtrToU %uint %p -OpReturn -OpFunctionEnd -""" - with self.assertRaises(si.UnsupportedConstruct) as ctx: - si.run_fragment(module) - self.assertIn("OpConvertPtrToU", str(ctx.exception)) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_scalar_mem_store.py b/tests/semantic/test_scalar_mem_store.py deleted file mode 100644 index 17b8a3b40..000000000 --- a/tests/semantic/test_scalar_mem_store.py +++ /dev/null @@ -1,729 +0,0 @@ -from __future__ import annotations - -"""Semantic interpreter tests for scalar memory write / store operations (s_store_dword). - -Covers AMD RDNA2 / GFX10 SMEM (Scalar Memory) store instruction semantics: - * s_store_dword: writes 1 dword (32 bits / 4 bytes) from SGPR into memory - * s_store_dwordx2: writes 2 dwords (64 bits / 8 bytes) from SGPR pair into memory - * s_store_dwordx4: writes 4 dwords (128 bits / 16 bytes) from SGPR quad into memory - * s_buffer_store_dword, s_buffer_store_dwordx2, s_buffer_store_dwordx4: - writes 1, 2, or 4 dwords into buffer memory described by a 128-bit Buffer Resource Descriptor (V#) - * 64-bit base pointer reconstruction from SGPR pair s[p:p+1]: - base_address = (s[p+1] << 32) | s[p] - * Buffer Resource Descriptor (V#) 128-bit layout and base address extraction: - - Dword 0: Base address low 32 bits [31:0] - - Dword 1: Base address high 16 bits [47:32] in bits [15:0]; bits [31:16] are format/stride/flags - - Proper masking (dword1 & 0xFFFF) preventing descriptor flags from polluting the 64-bit pointer - - Dword 2: num_records defining buffer size bounds - * Address calculations & arithmetic edge cases: - - Zero offset, immediate byte offsets, and dynamic SGPR offsets - - Combined register offset + immediate offset ("sOFF offset:IMM"): address = base + sOFF + IMM - - 32-bit carry propagation across the 4GB boundary into upper 32 bits - - 64-bit address wrapping modulo 2^64 - - 4-byte dword alignment enforcement (hardware drops low 2 bits) - * Multi-dword sequential strides: - - Writes sequential dwords at 4-byte offsets (addr + 0, addr + 4, addr + 8, addr + 12) - - Non-interference with neighboring memory locations - - Memory overwrites and latest-write persistence - * Destination / Source register targeting: - - Source data from SGPRs, SGPR ranges, and special registers (vcc_lo, vcc_hi, vcc pair, m0, null) - * Shader IR parsing (tools/shader_ir.py): - - Tokenization and AST validation for scalar store instructions and operand variants - - Validation of invalid operand configurations (wrong register counts, vgpr base) - * Translator and mini-interpreter contracts: - - rdna2spirv.Gen dispatch validation (raises Unsupported until translator implements scalar store) - - spirv_mini_interp strictness validation (rejection of unmodelled storage classes) -""" - -import os -import sys -import unittest - -HERE = os.path.dirname(os.path.abspath(__file__)) -ROOT = os.path.dirname(os.path.dirname(HERE)) -TOOLS_DIR = os.environ.get("LEONIDA_TOOLS_DIR") or os.path.join(ROOT, "tools") - -sys.dont_write_bytecode = True -if TOOLS_DIR not in sys.path: - sys.path.insert(0, TOOLS_DIR) -if HERE not in sys.path: - sys.path.insert(0, HERE) - -import rdna2spirv # noqa: E402 -from shader_ir import parse_line # noqa: E402 -import spirv_mini_interp as si # noqa: E402 - -MASK32 = 0xFFFFFFFF -MASK64 = 0xFFFFFFFFFFFFFFFF - - -def compute_smem_store_pointer_address(base_lo: int, base_hi: int, offset: int, imm: int = 0) -> int: - """Compute 64-bit effective byte address for s_store_dword from 64-bit pointer and offsets. - - Per AMD RDNA2 ISA SMEM addressing: - address = ((base_64 + offset + imm) & 0xFFFFFFFFFFFFFFFF) & ~3 - The low 2 bits are truncated to enforce 4-byte dword alignment. - """ - base_64 = ((base_hi & MASK32) << 32) | (base_lo & MASK32) - eff = (base_64 + (offset & MASK32) + (imm & MASK32)) & MASK64 - return eff & ~3 - - -def compute_smem_store_descriptor_address(desc_dw0: int, desc_dw1: int, offset: int, imm: int = 0) -> int: - """Compute 64-bit effective byte address for s_buffer_store_dword from buffer descriptor V# and offsets. - - Per AMD RDNA2 ISA: - - dword0: Base address [31:0] - - dword1: Base address [47:32] in bits [15:0]. Bits [31:16] are format/stride metadata. - """ - base_hi = desc_dw1 & 0xFFFF - base_64 = (base_hi << 32) | (desc_dw0 & MASK32) - eff = (base_64 + (offset & MASK32) + (imm & MASK32)) & MASK64 - return eff & ~3 - - -def check_buffer_store_bounds(offset: int, imm: int, count: int, num_records: int) -> bool: - """Check if buffer store range is within descriptor num_records. - - Buffer store is dropped (no-op) if (offset + imm + count * 4) exceeds num_records. - """ - total_offset = (offset & MASK32) + (imm & MASK32) - store_bytes = count * 4 - return (total_offset + store_bytes) <= (num_records & MASK32) - - -class SmemStoreMemoryBank: - """Deterministic simulated memory bank for SMEM store validation.""" - - def __init__(self) -> None: - self._mem: dict[int, int] = {} - - def write_dword(self, byte_addr: int, val: int) -> None: - aligned_addr = (byte_addr & MASK64) & ~3 - self._mem[aligned_addr] = val & MASK32 - - def read_dword(self, byte_addr: int) -> int: - aligned_addr = (byte_addr & MASK64) & ~3 - return self._mem.get(aligned_addr, 0) - - def write_dwords(self, byte_addr: int, values: list[int]) -> None: - aligned_addr = (byte_addr & MASK64) & ~3 - for i, val in enumerate(values): - self._mem[aligned_addr + i * 4] = val & MASK32 - - def read_dwords(self, byte_addr: int, count: int) -> list[int]: - aligned_addr = (byte_addr & MASK64) & ~3 - return [self._mem.get(aligned_addr + i * 4, 0) for i in range(count)] - - def has_address(self, byte_addr: int) -> bool: - aligned_addr = (byte_addr & MASK64) & ~3 - return aligned_addr in self._mem - - def dump(self) -> dict[int, int]: - return dict(self._mem) - - -class SmemStoreReferenceInterpreter: - """Reference execution engine for RDNA2 scalar memory stores.""" - - def __init__(self, memory: SmemStoreMemoryBank) -> None: - self.mem = memory - self.sgpr: list[int] = [0] * 106 - self.vcc_lo: int = 0 - self.vcc_hi: int = 0 - self.m0: int = 0 - - def load_register(self, name: str, reg_idx: int = 0) -> int: - if name == "sgpr": - return self.sgpr[reg_idx] & MASK32 - if name == "vcc_lo": - return self.vcc_lo & MASK32 - if name == "vcc_hi": - return self.vcc_hi & MASK32 - if name == "m0": - return self.m0 & MASK32 - if name == "null": - return 0 - raise ValueError(f"unknown register {name}") - - def store_register(self, name: str, reg_idx: int, val: int) -> None: - val &= MASK32 - if name == "sgpr": - self.sgpr[reg_idx] = val - elif name == "vcc_lo": - self.vcc_lo = val - elif name == "vcc_hi": - self.vcc_hi = val - elif name == "m0": - self.m0 = val - else: - raise ValueError(f"unknown register {name}") - - def get_source_dwords(self, src_reg: str, src_idx: int, count: int) -> list[int]: - words = [] - for i in range(count): - if src_reg == "sgpr": - words.append(self.load_register("sgpr", src_idx + i)) - elif src_reg == "vcc": - if i == 0: - words.append(self.load_register("vcc_lo", 0)) - elif i == 1: - words.append(self.load_register("vcc_hi", 0)) - else: - words.append(0) - elif src_reg in ("vcc_lo", "vcc_hi", "m0", "null"): - if i == 0: - words.append(self.load_register(src_reg, 0)) - else: - words.append(0) - else: - raise ValueError(f"unsupported source register {src_reg}") - return words - - def execute_s_store(self, count: int, src_reg: str, src_idx: int, - base_lo_idx: int, offset: int, imm_offset: int = 0) -> int: - lo = self.load_register("sgpr", base_lo_idx) - hi = self.load_register("sgpr", base_lo_idx + 1) - addr = compute_smem_store_pointer_address(lo, hi, offset, imm_offset) - values = self.get_source_dwords(src_reg, src_idx, count) - for i, val in enumerate(values): - self.mem.write_dword(addr + i * 4, val) - return addr - - def execute_s_buffer_store(self, count: int, src_reg: str, src_idx: int, - desc_dw0_idx: int, offset: int, imm_offset: int = 0) -> tuple[int, bool]: - dw0 = self.load_register("sgpr", desc_dw0_idx) - dw1 = self.load_register("sgpr", desc_dw0_idx + 1) - num_records = self.load_register("sgpr", desc_dw0_idx + 2) - addr = compute_smem_store_descriptor_address(dw0, dw1, offset, imm_offset) - in_bounds = check_buffer_store_bounds(offset, imm_offset, count, num_records) - if in_bounds: - values = self.get_source_dwords(src_reg, src_idx, count) - for i, val in enumerate(values): - self.mem.write_dword(addr + i * 4, val) - return addr, in_bounds - - -class SmemStoreAddressOracleTests(unittest.TestCase): - """Verifies SMEM 64-bit store effective address calculations and V# descriptor masking.""" - - def test_s_store_pointer_address_basic(self): - cases = [ - (0x1000, 0x0, 0, 0, 0x1000), - (0x1000, 0x0, 16, 0, 0x1010), - (0x1000, 0x0, 0x40, 0, 0x1040), - (0x2000, 0x1, 0x100, 0, 0x100002100), - (0x00000000, 0x00000008, 0x200, 0, 0x800000200), - ] - for lo, hi, off, imm, expected in cases: - with self.subTest(lo=hex(lo), hi=hex(hi), off=hex(off), imm=hex(imm)): - self.assertEqual(compute_smem_store_pointer_address(lo, hi, off, imm), expected) - - def test_s_store_pointer_carry_into_upper_32_bits(self): - cases = [ - (0xFFFFFFFC, 0x00000001, 8, 0, 0x0000000200000004), - (0xFFFFFFFF, 0x00000000, 1, 0, 0x0000000100000000), - (0xFFFFFFF0, 0x00000005, 0x20, 0, 0x0000000600000010), - (0xFFFFFFFF, 0x0000000F, 0xFFFFFFFF, 0, 0x00000010FFFFFFFC), - ] - for lo, hi, off, imm, expected in cases: - with self.subTest(lo=hex(lo), hi=hex(hi), off=hex(off)): - self.assertEqual(compute_smem_store_pointer_address(lo, hi, off, imm), expected) - - def test_s_store_pointer_wrap_modulo_64(self): - self.assertEqual(compute_smem_store_pointer_address(0xFFFFFFF0, 0xFFFFFFFF, 0x20, 0), 0x10) - self.assertEqual(compute_smem_store_pointer_address(0xFFFFFFFF, 0xFFFFFFFF, 1, 0), 0) - - def test_s_store_combined_register_and_imm_offset(self): - # address = base + soffset + imm - base_lo, base_hi = 0x00004000, 0x00000003 - soffset = 0x20 - imm = 0x0C - expected = 0x000000030000402C - self.assertEqual(compute_smem_store_pointer_address(base_lo, base_hi, soffset, imm), expected) - - def test_s_store_dword_alignment_truncation(self): - # Low 2 bits of address are cleared (multiple of 4) - for offset in (0x1000, 0x1001, 0x1002, 0x1003): - with self.subTest(offset=hex(offset)): - self.assertEqual(compute_smem_store_pointer_address(offset, 0, 0, 0), 0x1000) - - def test_s_buffer_store_descriptor_masking(self): - cases = [ - (0x00001000, 0x00000002, 0x10, 0, 0x0000000200001010), - # dw1 has 0x8004 in bits [31:16] (format/stride/flags) - (0x00001000, 0x80040002, 0x10, 0, 0x0000000200001010), - # dw1 has all upper 16 bits set (0xFFFF0000) - (0x12345678, 0xFFFF0007, 0x0, 0, 0x0000000712345678), - # dw1 format bits set, address bits 0 - (0x00000040, 0x3F000000, 0x20, 0, 0x0000000000000060), - # Carry from dw0 into masked dw1 - (0xFFFFFFF8, 0x80000001, 0x10, 0, 0x0000000200000008), - ] - for dw0, dw1, off, imm, expected in cases: - with self.subTest(dw0=hex(dw0), dw1=hex(dw1), off=hex(off)): - self.assertEqual(compute_smem_store_descriptor_address(dw0, dw1, off, imm), expected) - - def test_buffer_store_bounds_calculation(self): - num_records = 0x1000 - # In bounds: offset 0x0, 1 dword (4 bytes) -> 4 <= 0x1000 - self.assertTrue(check_buffer_store_bounds(0, 0, 1, num_records)) - # Exact boundary: offset 0xFFC, 1 dword (4 bytes) -> 0x1000 <= 0x1000 - self.assertTrue(check_buffer_store_bounds(0xFFC, 0, 1, num_records)) - # Out of bounds: offset 0xFFD, 1 dword (4 bytes) -> 0x1001 > 0x1000 - self.assertFalse(check_buffer_store_bounds(0xFFD, 0, 1, num_records)) - # Exact boundary with 4 dwords (16 bytes): offset 0xFF0 -> 0xFF0 + 16 = 0x1000 - self.assertTrue(check_buffer_store_bounds(0xFF0, 0, 4, num_records)) - # 1 byte over with 4 dwords: offset 0xFF4 -> 0xFF4 + 16 = 0x1004 > 0x1000 - self.assertFalse(check_buffer_store_bounds(0xFF4, 0, 4, num_records)) - # Combined soffset + imm exceeding bounds - self.assertFalse(check_buffer_store_bounds(0xF00, 0x110, 1, num_records)) - - -class SmemStoreExecutionTests(unittest.TestCase): - """Verifies single and multi-dword scalar store execution, strides, overwriting, and isolation.""" - - def setUp(self) -> None: - self.bank = SmemStoreMemoryBank() - self.interp = SmemStoreReferenceInterpreter(self.bank) - - def test_s_store_dword_single(self): - # Base s[2:3] = 0x1_00000000, offset = 0x20 -> address 0x1_00000020 - self.interp.store_register("sgpr", 2, 0x00000000) - self.interp.store_register("sgpr", 3, 0x00000001) - self.interp.store_register("sgpr", 4, 0xCAFEBABE) - - addr = self.interp.execute_s_store(1, "sgpr", 4, 2, 0x20) - self.assertEqual(addr, 0x100000020) - self.assertEqual(self.bank.read_dword(0x100000020), 0xCAFEBABE) - - def test_s_store_dwordx2_sequential_stride(self): - self.interp.store_register("sgpr", 6, 0x00001000) - self.interp.store_register("sgpr", 7, 0x00000000) - self.interp.store_register("sgpr", 8, 0x11112222) - self.interp.store_register("sgpr", 9, 0x33334444) - - addr = self.interp.execute_s_store(2, "sgpr", 8, 6, 0) - self.assertEqual(addr, 0x1000) - self.assertEqual(self.bank.read_dword(0x1000), 0x11112222) - self.assertEqual(self.bank.read_dword(0x1004), 0x33334444) - - def test_s_store_dwordx4_sequential_stride(self): - self.interp.store_register("sgpr", 0, 0x00002000) - self.interp.store_register("sgpr", 1, 0x00000000) - test_words = [0xA0000001, 0xA0000002, 0xA0000003, 0xA0000004] - for i, val in enumerate(test_words): - self.interp.store_register("sgpr", 12 + i, val) - - addr = self.interp.execute_s_store(4, "sgpr", 12, 0, 0x10) - self.assertEqual(addr, 0x2010) - for i, val in enumerate(test_words): - self.assertEqual(self.bank.read_dword(0x2010 + i * 4), val) - - def test_s_store_overwriting_and_persistence(self): - self.interp.store_register("sgpr", 0, 0x1000) - self.interp.store_register("sgpr", 1, 0) - self.interp.store_register("sgpr", 4, 0x11111111) - - # First store - self.interp.execute_s_store(1, "sgpr", 4, 0, 0) - self.assertEqual(self.bank.read_dword(0x1000), 0x11111111) - - # Overwrite with second store - self.interp.store_register("sgpr", 4, 0x22222222) - self.interp.execute_s_store(1, "sgpr", 4, 0, 0) - self.assertEqual(self.bank.read_dword(0x1000), 0x22222222) - - def test_s_store_memory_isolation_and_adjacent_untouched(self): - # Pre-seed adjacent memory locations - self.bank.write_dword(0x2FFC, 0xAAAAAAAA) - self.bank.write_dword(0x3010, 0xBBBBBBBB) - - self.interp.store_register("sgpr", 0, 0x3000) - self.interp.store_register("sgpr", 1, 0) - self.interp.store_register("sgpr", 4, 0xC001D00D) - self.interp.store_register("sgpr", 5, 0xF00DCAFE) - - # Store 2 dwords to [0x3000, 0x3008) - self.interp.execute_s_store(2, "sgpr", 4, 0, 0) - - # Target locations written - self.assertEqual(self.bank.read_dword(0x3000), 0xC001D00D) - self.assertEqual(self.bank.read_dword(0x3004), 0xF00DCAFE) - # Adjacent locations remain uncorrupted - self.assertEqual(self.bank.read_dword(0x2FFC), 0xAAAAAAAA) - self.assertEqual(self.bank.read_dword(0x3010), 0xBBBBBBBB) - - def test_s_store_special_source_registers(self): - self.interp.store_register("sgpr", 0, 0x1000) - self.interp.store_register("sgpr", 1, 0) - - # Single dword from vcc_lo - self.interp.store_register("vcc_lo", 0, 0x12345678) - self.interp.execute_s_store(1, "vcc_lo", 0, 0, 0) - self.assertEqual(self.bank.read_dword(0x1000), 0x12345678) - - # Single dword from vcc_hi - self.interp.store_register("vcc_hi", 0, 0x9ABCDEF0) - self.interp.execute_s_store(1, "vcc_hi", 0, 0, 4) - self.assertEqual(self.bank.read_dword(0x1004), 0x9ABCDEF0) - - # Single dword from m0 - self.interp.store_register("m0", 0, 0xFEEDFACE) - self.interp.execute_s_store(1, "m0", 0, 0, 8) - self.assertEqual(self.bank.read_dword(0x1008), 0xFEEDFACE) - - # Single dword from null (writes 0) - self.bank.write_dword(0x100C, 0xFFFFFFFF) - self.interp.execute_s_store(1, "null", 0, 0, 12) - self.assertEqual(self.bank.read_dword(0x100C), 0) - - # Two dwords from vcc pair (vcc_lo and vcc_hi) - self.interp.store_register("vcc_lo", 0, 0xAAAA5555) - self.interp.store_register("vcc_hi", 0, 0x5555AAAA) - self.interp.execute_s_store(2, "vcc", 0, 0, 0x20) - self.assertEqual(self.bank.read_dword(0x1020), 0xAAAA5555) - self.assertEqual(self.bank.read_dword(0x1024), 0x5555AAAA) - - def test_s_buffer_store_in_bounds(self): - # V# descriptor: dw0 = 0x5000, dw1 = 0x80040003 (stride=0x8004, hi_addr=3) - self.interp.store_register("sgpr", 8, 0x00005000) - self.interp.store_register("sgpr", 9, 0x80040003) - self.interp.store_register("sgpr", 10, 0x00010000) # num_records = 64KB - self.interp.store_register("sgpr", 11, 0x00140000) # flags - - self.interp.store_register("sgpr", 20, 0x99887766) - expected_addr = 0x0000000300005040 - - addr, written = self.interp.execute_s_buffer_store(1, "sgpr", 20, 8, 0x40) - self.assertTrue(written) - self.assertEqual(addr, expected_addr) - self.assertEqual(self.bank.read_dword(expected_addr), 0x99887766) - - def test_s_buffer_store_out_of_bounds_dropped(self): - # V# descriptor with small buffer: num_records = 0x40 (64 bytes) - self.interp.store_register("sgpr", 8, 0x00005000) - self.interp.store_register("sgpr", 9, 0x00000000) - self.interp.store_register("sgpr", 10, 0x00000040) - self.interp.store_register("sgpr", 11, 0x00000000) - - self.interp.store_register("sgpr", 20, 0xBADF00D) - # Offset 0x40 is at boundary (offset 0x40 + 4 bytes = 0x44 > 0x40) - addr, written = self.interp.execute_s_buffer_store(1, "sgpr", 20, 8, 0x40) - self.assertFalse(written) - self.assertFalse(self.bank.has_address(addr)) - - def test_s_buffer_store_multi_dword_partial_out_of_bounds_dropped(self): - # V# descriptor with num_records = 0x10 (16 bytes) - self.interp.store_register("sgpr", 8, 0x00006000) - self.interp.store_register("sgpr", 9, 0x00000000) - self.interp.store_register("sgpr", 10, 0x00000010) - self.interp.store_register("sgpr", 11, 0x00000000) - - for i in range(4): - self.interp.store_register("sgpr", 12 + i, 0x1000 + i) - - # 4 dwords (16 bytes) starting at offset 4 -> 4 + 16 = 20 > 16 -> dropped - addr, written = self.interp.execute_s_buffer_store(4, "sgpr", 12, 8, 4) - self.assertFalse(written) - for i in range(4): - self.assertFalse(self.bank.has_address(addr + i * 4)) - - -class SmemStoreAstParsingTests(unittest.TestCase): - """Verifies shader_ir.parse_line correctly parses scalar memory store instructions.""" - - def test_parse_s_store_dword_immediate_offset(self): - ins = parse_line("s_store_dword s0, s[2:3], 0x10") - self.assertEqual(ins["op"], "s_store_dword") - self.assertEqual(ins["args"][0], {"k": "sgpr", "r": 0, "n": 1, "neg": False, "abs": False}) - self.assertEqual(ins["args"][1], {"k": "sgpr", "r": 2, "n": 2, "neg": False, "abs": False}) - self.assertEqual(ins["args"][2], {"k": "imm", "v": 16}) - self.assertEqual(ins["mods"], []) - - def test_parse_s_store_dwordx2_immediate_offset(self): - ins = parse_line("s_store_dwordx2 s[0:1], s[4:5], 0x20") - self.assertEqual(ins["op"], "s_store_dwordx2") - self.assertEqual(ins["args"][0], {"k": "sgpr", "r": 0, "n": 2, "neg": False, "abs": False}) - self.assertEqual(ins["args"][1], {"k": "sgpr", "r": 4, "n": 2, "neg": False, "abs": False}) - self.assertEqual(ins["args"][2], {"k": "imm", "v": 32}) - self.assertEqual(ins["mods"], []) - - def test_parse_s_store_dwordx4_immediate_offset(self): - ins = parse_line("s_store_dwordx4 s[4:7], s[8:9], 0x40") - self.assertEqual(ins["op"], "s_store_dwordx4") - self.assertEqual(ins["args"][0], {"k": "sgpr", "r": 4, "n": 4, "neg": False, "abs": False}) - self.assertEqual(ins["args"][1], {"k": "sgpr", "r": 8, "n": 2, "neg": False, "abs": False}) - self.assertEqual(ins["args"][2], {"k": "imm", "v": 64}) - self.assertEqual(ins["mods"], []) - - def test_parse_s_store_dword_register_offset(self): - ins = parse_line("s_store_dword s0, s[2:3], s4") - self.assertEqual(ins["op"], "s_store_dword") - self.assertEqual(ins["args"][2], {"k": "sgpr", "r": 4, "n": 1, "neg": False, "abs": False}) - self.assertEqual(ins["mods"], []) - - def test_parse_s_store_dword_register_offset_with_imm_mod(self): - ins = parse_line("s_store_dword s0, s[2:3], s4 offset:0x10") - self.assertEqual(ins["op"], "s_store_dword") - self.assertEqual(ins["args"][2], {"k": "sgpr", "r": 4, "n": 1, "neg": False, "abs": False}) - self.assertEqual(ins["mods"], ["offset:0x10"]) - - def test_parse_s_buffer_store_instructions(self): - cases = [ - ("s_buffer_store_dword s0, s[0:3], 0", "s_buffer_store_dword", 1, 4), - ("s_buffer_store_dwordx2 s[0:1], s[4:7], 0x10", "s_buffer_store_dwordx2", 2, 4), - ("s_buffer_store_dwordx4 s[0:3], s[8:11], s12 offset:0x20", "s_buffer_store_dwordx4", 4, 4), - ] - for line, op, src_n, base_n in cases: - with self.subTest(line=line): - ins = parse_line(line) - self.assertEqual(ins["op"], op) - self.assertEqual(ins["args"][0]["n"], src_n) - self.assertEqual(ins["args"][1]["n"], base_n) - - def test_parse_special_source_registers(self): - specials = [ - ("s_store_dword vcc_lo, s[0:1], 0", "vcc_lo"), - ("s_store_dword vcc_hi, s[0:1], 4", "vcc_hi"), - ("s_store_dword m0, s[0:1], 8", "m0"), - ("s_store_dword null, s[0:1], 12", "null"), - ("s_store_dwordx2 vcc, s[0:1], 0", "vcc"), - ] - for line, reg_name in specials: - with self.subTest(line=line): - ins = parse_line(line) - self.assertEqual(ins["args"][0]["k"], "special") - self.assertEqual(ins["args"][0]["t"], reg_name) - - -class SmemStoreValidationTests(unittest.TestCase): - """Verifies semantic validation rules for scalar store operands.""" - - @staticmethod - def validate_smem_store_args(op: str, args: list[dict], mods: list[str]) -> None: - """Validates SMEM store operand structure, mirroring RDNA2 hardware constraints.""" - n = 1 if op.endswith("dword") else int(op.rsplit("x", 1)[1]) - src, base = args[0], args[1] - special_src = (n == 1 and src.get("k") == "special" and src.get("t") in ("vcc_lo", "vcc_hi", "m0", "null", "vcc")) or \ - (n == 2 and src.get("k") == "special" and src.get("t") == "vcc") - - if src.get("k") != "sgpr" and not special_src: - raise ValueError(f"invalid source register for {op}: {src}") - if src.get("k") == "sgpr" and src.get("n", 1) != n: - raise ValueError(f"expected {n} source SGPRs, got {src.get('n', 1)}") - - if base.get("k") != "sgpr": - raise ValueError(f"base must be SGPR, got {base.get('k')}") - - if op.startswith("s_buffer_store"): - if base.get("n") != 4: - raise ValueError(f"s_buffer_store requires 128-bit V# descriptor (4 SGPRs), got {base.get('n')}") - else: - if base.get("n") != 2: - raise ValueError(f"s_store requires 64-bit pointer (2 SGPRs), got {base.get('n')}") - - # Validate modifiers: only offset:IMM is permitted - for m in mods: - if not m.startswith("offset:"): - raise ValueError(f"unsupported modifier {m}") - try: - int(m.split(":", 1)[1], 0) - except ValueError as e: - raise ValueError(f"invalid offset modifier value: {m}") from e - - def test_valid_store_args_pass_validation(self): - cases = [ - "s_store_dword s0, s[2:3], 0", - "s_store_dwordx2 s[0:1], s[2:3], 0x10", - "s_store_dwordx4 s[0:3], s[2:3], s4 offset:0x20", - "s_buffer_store_dword s0, s[0:3], 0", - "s_buffer_store_dwordx2 s[0:1], s[0:3], 0", - "s_buffer_store_dwordx4 s[0:3], s[0:3], 0", - "s_store_dword vcc_lo, s[2:3], 0", - "s_store_dwordx2 vcc, s[2:3], 0", - ] - for line in cases: - with self.subTest(line=line): - ins = parse_line(line) - self.validate_smem_store_args(ins["op"], ins["args"], ins["mods"]) - - def test_invalid_source_count_rejected(self): - # s_store_dwordx2 expects 2 SGPRs, given 1 - ins = parse_line("s_store_dwordx2 s0, s[2:3], 0") - with self.assertRaises(ValueError) as ctx: - self.validate_smem_store_args(ins["op"], ins["args"], ins["mods"]) - self.assertIn("expected 2 source SGPRs", str(ctx.exception)) - - # s_store_dwordx4 expects 4 SGPRs, given 2 - ins = parse_line("s_store_dwordx4 s[0:1], s[2:3], 0") - with self.assertRaises(ValueError) as ctx: - self.validate_smem_store_args(ins["op"], ins["args"], ins["mods"]) - self.assertIn("expected 4 source SGPRs", str(ctx.exception)) - - def test_invalid_base_count_rejected(self): - # s_store_dword requires 2 SGPRs, given 4 - ins = parse_line("s_store_dword s0, s[0:3], 0") - with self.assertRaises(ValueError) as ctx: - self.validate_smem_store_args(ins["op"], ins["args"], ins["mods"]) - self.assertIn("s_store requires 64-bit pointer (2 SGPRs)", str(ctx.exception)) - - # s_buffer_store requires 4 SGPRs, given 2 - ins = parse_line("s_buffer_store_dword s0, s[0:1], 0") - with self.assertRaises(ValueError) as ctx: - self.validate_smem_store_args(ins["op"], ins["args"], ins["mods"]) - self.assertIn("s_buffer_store requires 128-bit V# descriptor", str(ctx.exception)) - - def test_vgpr_base_rejected(self): - ins = parse_line("s_store_dword s0, v[0:1], 0") - with self.assertRaises(ValueError) as ctx: - self.validate_smem_store_args(ins["op"], ins["args"], ins["mods"]) - self.assertIn("base must be SGPR", str(ctx.exception)) - - def test_invalid_modifier_rejected(self): - ins = parse_line("s_store_dword s0, s[2:3], s4 offset:badval") - with self.assertRaises(ValueError) as ctx: - self.validate_smem_store_args(ins["op"], ins["args"], ins["mods"]) - self.assertIn("invalid offset modifier value", str(ctx.exception)) - - -class SmemStoreEvaluator: - """Straight-line evaluator executing a program sequence of SMEM stores against a memory bank.""" - - def __init__(self, initial_sgpr: dict[int, int], memory: SmemStoreMemoryBank) -> None: - self.interp = SmemStoreReferenceInterpreter(memory) - for r, v in initial_sgpr.items(): - self.interp.store_register("sgpr", r, v) - self.stores: list[tuple[str, int, int]] = [] # (op, address, dword_count) - - def execute_line(self, line: str) -> int: - ins = parse_line(line) - op = ins["op"] - n = 1 if op.endswith("dword") else int(op.rsplit("x", 1)[1]) - src = ins["args"][0] - base = ins["args"][1] - off_arg = ins["args"][2] - - offset = off_arg["v"] if off_arg["k"] == "imm" else self.interp.load_register("sgpr", off_arg["r"]) - imm = 0 - for m in ins["mods"]: - if m.startswith("offset:"): - imm = int(m.split(":", 1)[1], 0) - - src_reg = src.get("t", "sgpr") if src.get("k") == "special" else "sgpr" - src_idx = src.get("r", 0) - - if op.startswith("s_buffer_store"): - addr, written = self.interp.execute_s_buffer_store(n, src_reg, src_idx, base["r"], offset, imm) - if written: - self.stores.append((op, addr, n)) - return addr - else: - addr = self.interp.execute_s_store(n, src_reg, src_idx, base["r"], offset, imm) - self.stores.append((op, addr, n)) - return addr - - -class SmemStoreProgramEvaluatorTests(unittest.TestCase): - """Verifies multi-instruction sequences of scalar stores and cross-instruction memory integrity.""" - - def test_interleaved_store_sequence(self): - bank = SmemStoreMemoryBank() - sgpr = { - 0: 0x00004000, 1: 0x00000000, # Base pointer: 0x4000 - 4: 0x11111111, # Data 1 - 6: 0x22222222, 7: 0x33333333, # Data 2 (pair) - 8: 0x44444444, 9: 0x55555555, # Data 4 (quad) - 10: 0x66666666, 11: 0x77777777, - 20: 0x10, # Register offset 16 - } - ev = SmemStoreEvaluator(sgpr, bank) - - # Store 1 dword at 0x4000 - addr1 = ev.execute_line("s_store_dword s4, s[0:1], 0") - self.assertEqual(addr1, 0x4000) - self.assertEqual(bank.read_dword(0x4000), 0x11111111) - - # Store 2 dwords at 0x4010 (using register offset s20) - addr2 = ev.execute_line("s_store_dwordx2 s[6:7], s[0:1], s20") - self.assertEqual(addr2, 0x4010) - self.assertEqual(bank.read_dword(0x4010), 0x22222222) - self.assertEqual(bank.read_dword(0x4014), 0x33333333) - - # Store 4 dwords at 0x4020 (using register offset + immediate offset: 0x10 + 0x10 = 0x20) - addr3 = ev.execute_line("s_store_dwordx4 s[8:11], s[0:1], s20 offset:0x10") - self.assertEqual(addr3, 0x4020) - self.assertEqual(bank.read_dword(0x4020), 0x44444444) - self.assertEqual(bank.read_dword(0x4024), 0x55555555) - self.assertEqual(bank.read_dword(0x4028), 0x66666666) - self.assertEqual(bank.read_dword(0x402C), 0x77777777) - - # Confirm all prior stores remained undisturbed - self.assertEqual(bank.read_dword(0x4000), 0x11111111) - self.assertEqual(bank.read_dword(0x4010), 0x22222222) - self.assertEqual(bank.read_dword(0x4014), 0x33333333) - - -class SmemStoreTranslatorContractTests(unittest.TestCase): - """Verifies translator handling of scalar stores. - - tools/rdna2spirv.py Gen currently raises Unsupported on s_store_dword, protecting against - silent miscompilations until SMEM store PhysicalStorageBuffer write emission is supported. - """ - - def test_translator_raises_unsupported_on_s_store(self): - g = rdna2spirv.Gen("cs") - for line in ("s_store_dword s0, s[2:3], 0", - "s_store_dwordx2 s[0:1], s[2:3], 0", - "s_store_dwordx4 s[0:3], s[4:5], 0", - "s_buffer_store_dword s0, s[0:3], 0"): - with self.subTest(line=line): - ins = parse_line(line) - with self.assertRaises(rdna2spirv.Unsupported) as ctx: - g.insn(ins) - self.assertIn(ins["op"], str(ctx.exception)) - - -class SmemStoreMiniInterpStrictnessTests(unittest.TestCase): - """Verifies that spirv_mini_interp strictly rejects unmodelled SPIR-V constructs for stores.""" - - def test_rejects_unsupported_integer_widths(self): - module = """\ -OpCapability Shader -OpMemoryModel Logical GLSL450 -OpEntryPoint Fragment %main "main" -%void = OpTypeVoid -%ushort = OpTypeInt 16 0 -%fn = OpTypeFunction %void -%main = OpFunction %void None %fn -%entry = OpLabel -OpReturn -OpFunctionEnd -""" - with self.assertRaises(si.UnsupportedConstruct) as ctx: - si.run_fragment(module) - self.assertIn("integer type that is not 32 or 64 bits", str(ctx.exception)) - - def test_rejects_physical_storage_buffer_storage_class(self): - module = """\ -OpCapability Shader -OpCapability PhysicalStorageBufferAddresses -OpMemoryModel PhysicalStorageBuffer64 GLSL450 -OpEntryPoint Fragment %main "main" -%void = OpTypeVoid -%uint = OpTypeInt 32 0 -%_ptr_PSB = OpTypePointer PhysicalStorageBuffer %uint -%var = OpVariable %_ptr_PSB PhysicalStorageBuffer -%fn = OpTypeFunction %void -%main = OpFunction %void None %fn -%entry = OpLabel -OpReturn -OpFunctionEnd -""" - with self.assertRaises(si.UnsupportedConstruct) as ctx: - si.run_fragment(module) - self.assertIn("storage class PhysicalStorageBuffer", str(ctx.exception)) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_scalar_noop_waitcnt.py b/tests/semantic/test_scalar_noop_waitcnt.py deleted file mode 100644 index c2079bce9..000000000 --- a/tests/semantic/test_scalar_noop_waitcnt.py +++ /dev/null @@ -1,672 +0,0 @@ -"""Semantic and translation tests for RDNA2 scalar no-op, hint, waitcnt, and mode instructions. - -Covers the 11 named scalar instructions and their syntax variants in tools/shader_ir.py and tools/rdna2spirv.py: - * In rdna2spirv.NOOPS (emits no SPIR-V instructions, preserves VGPRs, SGPRs, VCC, SCC, and EXEC): - s_clause, s_delay_alu (RDNA3 hint kept in NOOPS), s_inst_prefetch, s_setprio, s_sleep, - s_waitcnt_depctr, s_waitcnt_expcnt, s_waitcnt_lgkmcnt, s_waitcnt_vmcnt, - plus the sibling wait/no-op forms s_waitcnt, s_waitcnt_vscnt, s_nop, and v_nop. - * s_round_mode and s_setreg_imm32_b32 can select nearest-even or toward-zero FP16/64 rounding while - retaining nearest-even FP32. These writes leave VGPRs, SGPRs, VCC, SCC, and EXEC intact. Tests also cover - rejection of unmodelled modes and the no-op behavior of non-MODE s_setreg* writes. - -Standard library only (runs with python -I); hand-written RDNA2 listings, no GPU or game data. -""" -from __future__ import annotations - -import gc -import os -import struct -import sys -import tempfile -import unittest -import warnings - -HERE = os.path.dirname(os.path.abspath(__file__)) -ROOT = os.path.dirname(os.path.dirname(HERE)) -TOOLS_DIR = os.environ.get("LEONIDA_TOOLS_DIR") or os.path.join(ROOT, "tools") - -sys.dont_write_bytecode = True -for _p in (HERE, TOOLS_DIR): - if _p not in sys.path: - sys.path.insert(0, _p) - -import rdna2spirv # noqa: E402 -import shader_ir # noqa: E402 -import spirv_mini_interp as si # noqa: E402 - -M32 = 0xFFFFFFFF -STUB_DXBC = b"DXBC" + bytes(24) + struct.pack(" None: - global _TMP_DIR - _TMP_DIR = tempfile.TemporaryDirectory() - os.mkdir(os.path.join(_TMP_DIR.name, "disasm")) - os.mkdir(os.path.join(_TMP_DIR.name, "fssm")) - - -def tearDownModule() -> None: - global _TMP_DIR - if _TMP_DIR is not None: - gc.collect() - _TMP_DIR.cleanup() - _TMP_DIR = None - - -def _ensure_dir() -> str: - if _TMP_DIR is None: - setUpModule() - assert _TMP_DIR is not None - return _TMP_DIR.name - - -def make_fssm(threads: int, user_sgprs: int = 4) -> bytes: - """Synthetic compute FSSM header: user_sgprs USER_SGPRs, TGID_X_EN=0, TIDIG_COMP_CNT=0, size=(threads,1,1).""" - blob = bytearray(0x148) - rsrc2 = (user_sgprs & 31) << 1 - struct.pack_into("<4I", blob, 0x138, rsrc2, threads, 1, 1) - return bytes(blob) - - -def translate_ps(name: str, lines: list[str]) -> str: - root = _ensure_dir() - src = os.path.join(root, "disasm", name + ".s") - with open(src, "w", encoding="utf-8", newline="\n") as f: - f.write(f"; {name}\n" + "".join(f"\t{ln}\n" for ln in lines)) - with open(os.path.join(root, name + ".dxbc"), "wb") as f: - f.write(STUB_DXBC) - with warnings.catch_warnings(): - warnings.simplefilter("ignore", ResourceWarning) - return rdna2spirv.translate(src) - - -def translate_cs(name: str, lines: list[str], threads: int) -> str: - root = _ensure_dir() - src = os.path.join(root, "disasm", name + ".s") - with open(src, "w", encoding="utf-8", newline="\n") as f: - f.write(f"; {name}\n" + "".join(f"\t{ln}\n" for ln in lines)) - with open(os.path.join(root, name + ".dxbc"), "wb") as f: - f.write(STUB_DXBC) - with open(os.path.join(root, "fssm", name + ".fssm"), "wb") as f: - f.write(make_fssm(threads)) - with warnings.catch_warnings(): - warnings.simplefilter("ignore", ResourceWarning) - return rdna2spirv.translate(src) - - -def ps_program(middle: list[str], *, scc_one: bool = True, vcc_one: bool = True, - exec_lo: int = 0xAAAA5555, add_k: int = 0x10) -> list[str]: - """Synthetic PS testing VGPRs, SGPRs, SCC, VCC, and EXEC across interleaved arithmetic and `middle`.""" - s_rhs = 5 if scc_one else 0 - s_lhs = 0xFFFFFFFF if scc_one else 0x12340000 - cmp_val = (0x11112222 + add_k) & M32 if vcc_one else 0x00000000 - return [ - "v_mov_b32 v0, 0x11112222", - "v_mov_b32 v1, 0x33334444", - "v_mov_b32 v2, 0x55556666", - "v_mov_b32 v3, 0x77778888", - f"s_mov_b32 s2, {s_lhs:#x}", - f"s_mov_b32 s3, {s_rhs:#x}", - "s_add_u32 s4, s2, s3", # SCC = 1 iff s_lhs + s_rhs overflows 32 bits - f"v_add_nc_u32 v0, v0, {add_k:#x}", - f"v_cmp_eq_u32 vcc_lo, v0, {cmp_val:#x}", # VCC = 1 iff vcc_one - f"s_mov_b32 exec_lo, {exec_lo:#x}", - *middle, - "s_cselect_b32 s5, 0x10000001, 0x20000002", # reads SCC - "s_add_u32 s6, s4, s5", # reads SGPR s4 and selected s5 - "v_cndmask_b32 v1, 0x99990000, v1, vcc_lo", # reads VCC (and VGPR v1 when VCC=1) - "v_add_nc_u32 v2, v2, s6", # reads EXEC, VGPR v2, SGPR s6 - "exp mrt0 v0, v1, v2, v3 done vm", - "s_endpgm", - ] - - -def expected_ps_mrt0(*, scc_one: bool = True, vcc_one: bool = True, - exec_lo: int = 0xAAAA5555, add_k: int = 0x10) -> tuple[int, int, int, int]: - """Plain-Python reference for ps_program().""" - active = bool(exec_lo & 1) - s_lhs = 0xFFFFFFFF if scc_one else 0x12340000 - s_rhs = 5 if scc_one else 0 - s4 = (s_lhs + s_rhs) & M32 - scc = (s_lhs + s_rhs) > M32 - v0 = ((0x11112222 + add_k) & M32) # executed while EXEC=1 initially - vcc = vcc_one # evaluated while EXEC=1 initially - s5 = 0x10000001 if scc else 0x20000002 - s6 = (s4 + s5) & M32 - v1 = (0x33334444 if vcc else 0x99990000) if active else 0x33334444 - v2 = ((0x55556666 + s6) & M32) if active else 0x55556666 - v3 = 0x77778888 - if not active: - return (0, 0, 0, 0) - return (v0, v1, v2, v3) - - -def cs_program(middle: list[str], *, wave64: bool, scc_one: bool = True, - exec_lo: int = 0xA5A55A5A, exec_hi: int = 0x3C3C6969) -> list[str]: - """Synthetic wave32/wave64 CS checking VGPRs, SGPRs, SCC, VCC, and EXEC across all lanes.""" - s_lhs = 0xFFFFFFFF if scc_one else 0x10203040 - s_rhs = 3 if scc_one else 1 - if wave64: - lane_setup = [ - "s_mov_b64 exec, -1", - "v_mbcnt_lo_u32_b32 v0, -1, 0", - "v_mbcnt_hi_u32_b32 v0, -1, v0", - ] - vcc_cmp = "v_cmp_eq_u32 vcc, v4, 0" - set_exec = [f"s_mov_b32 exec_lo, {exec_lo:#x}", f"s_mov_b32 exec_hi, {exec_hi:#x}"] - reset_exec = "s_mov_b64 exec, -1" - vcc_cnd = "v_cndmask_b32 v2, 0x99990000, v2, vcc" - else: - lane_setup = [] # v0 is seeded directly from LocalInvocationId.x - vcc_cmp = "v_cmp_eq_u32 vcc_lo, v4, 0" - set_exec = [f"s_mov_b32 exec_lo, {exec_lo:#x}"] - reset_exec = "s_mov_b32 exec_lo, -1" - vcc_cnd = "v_cndmask_b32 v2, 0x99990000, v2, vcc_lo" - - return [ - *lane_setup, - "v_mov_b32 v1, v0", - "v_add_nc_u32 v1, v1, 10", - "v_mov_b32 v2, 0x77770000", - "v_add_nc_u32 v2, v2, v0", - "v_mov_b32 v3, 0x1000", - "v_and_b32 v4, v0, 1", - vcc_cmp, # even lanes: VCC = 1; odd lanes: VCC = 0 - "s_mov_b32 s8, 0x01020304", - "s_mov_b32 s9, 0x55667788", - f"s_mov_b32 s10, {s_lhs:#x}", - f"s_add_u32 s11, s10, {s_rhs:#x}", # SCC = 1 iff scc_one - *set_exec, - *middle, - "v_add_nc_u32 v1, v1, 0x100", # updates v1 only in lanes where EXEC=1 - "s_cselect_b32 s12, 0x10000, 0x20000", # reads SCC - reset_exec, - vcc_cnd, # reads VCC across all lanes (even keeps v2, odd gets 0x99990000) - "v_add_nc_u32 v3, v3, s8", # reads SGPR s8 - "v_add_nc_u32 v3, v3, s12", # reads s12 (SCC outcome) - "v_add_nc_u32 v3, v3, s11", # reads s11 (s_add_u32 sum) - "v_mov_b32 v4, s9", # reads SGPR s9 - "v_lshlrev_b32 v5, 4, v0", # byte offset = 16 * lane - "buffer_store_dwordx4 v[1:4], v5, s[0:3], 0 offen", - "s_endpgm", - ] - - -def expected_cs_words(lanes: int, *, scc_one: bool = True, - exec_lo: int = 0xA5A55A5A, exec_hi: int = 0x3C3C6969) -> list[tuple[int, int, int, int]]: - """Plain-Python reference for cs_program().""" - s_lhs = 0xFFFFFFFF if scc_one else 0x10203040 - s_rhs = 3 if scc_one else 1 - s11 = (s_lhs + s_rhs) & M32 - s12 = 0x10000 if ((s_lhs + s_rhs) > M32) else 0x20000 - exec_mask = (exec_hi << 32) | exec_lo - out = [] - for lane in range(lanes): - active = bool((exec_mask >> lane) & 1) - w0 = (lane + 10 + (0x100 if active else 0)) & M32 - w1 = (0x77770000 + lane) if (lane % 2 == 0) else 0x99990000 - w2 = (0x1000 + 0x01020304 + s12 + s11) & M32 - w3 = 0x55667788 - out.append((w0, w1, w2, w3)) - return out - - -def run_cs(spv: str, lanes: int) -> list[tuple[int, int, int, int]]: - mem = si.run_workgroup( - spv, lanes, lanes, - inputs_for=lambda i: {"%wg_id": (0, 0, 0), "%local_id": (i, 0, 0), "%sg_lane": i}, - push_constants=VSHARP + [0] * 28, - memory={}, - ) - return [tuple(mem[16 * lane + 4 * c] for c in range(4)) for lane in range(lanes)] - - -class ScalarNoopWaitcntParsingTests(unittest.TestCase): - """Exact syntax and operand parsing in tools/shader_ir.py for all 11 scalar ops and variants.""" - - def test_parse_all_scalar_noop_waitcnt_and_mode_forms(self): - cases = [ - ("s_clause 0x1", "s_clause", [{"k": "imm", "v": 1}]), - ("s_delay_alu 0", "s_delay_alu", [{"k": "imm", "v": 0}]), - ( - "s_delay_alu instid0(VALU_DEP_1) | instskip(NEXT) | instid1(SALU_CYCLE_1)", - "s_delay_alu", - [{"k": "special", "t": "instid0(VALU_DEP_1) | instskip(NEXT) | instid1(SALU_CYCLE_1)"}], - ), - ("s_denorm_mode 0x3", "s_denorm_mode", [{"k": "imm", "v": 3}]), - ("s_inst_prefetch 0x0", "s_inst_prefetch", [{"k": "imm", "v": 0}]), - ("s_inst_prefetch -1", "s_inst_prefetch", [{"k": "imm", "v": -1}]), - ("s_round_mode 0x3", "s_round_mode", [{"k": "imm", "v": 3}]), - ("s_setprio 0x2", "s_setprio", [{"k": "imm", "v": 2}]), - ("s_sleep 0x1", "s_sleep", [{"k": "imm", "v": 1}]), - ("s_waitcnt_depctr 0xffe3", "s_waitcnt_depctr", [{"k": "imm", "v": 0xFFE3}]), - ( - "s_waitcnt_depctr depctr_vm_vsrc(0) depctr_va_sdst(0)", - "s_waitcnt_depctr", - [{"k": "special", "t": "depctr_vm_vsrc(0)"}, {"k": "special", "t": "depctr_va_sdst(0)"}], - ), - ( - "s_waitcnt_depctr depctr_hold_cnt(0) depctr_sa_sdst(0) depctr_va_vdst(0)", - "s_waitcnt_depctr", - [ - {"k": "special", "t": "depctr_hold_cnt(0)"}, - {"k": "special", "t": "depctr_sa_sdst(0)"}, - {"k": "special", "t": "depctr_va_vdst(0)"}, - ], - ), - ( - "s_waitcnt_expcnt null, 0x0", - "s_waitcnt_expcnt", - [{"k": "special", "t": "null", "neg": False, "abs": False}, {"k": "imm", "v": 0}], - ), - ( - "s_waitcnt_lgkmcnt null, 0x3f", - "s_waitcnt_lgkmcnt", - [{"k": "special", "t": "null", "neg": False, "abs": False}, {"k": "imm", "v": 0x3F}], - ), - ( - "s_waitcnt_vmcnt null, 0x0", - "s_waitcnt_vmcnt", - [{"k": "special", "t": "null", "neg": False, "abs": False}, {"k": "imm", "v": 0}], - ), - ( - "s_waitcnt_vscnt null, 0x0", - "s_waitcnt_vscnt", - [{"k": "special", "t": "null", "neg": False, "abs": False}, {"k": "imm", "v": 0}], - ), - ("s_waitcnt vmcnt(0)", "s_waitcnt", [{"k": "special", "t": "vmcnt(0)"}]), - ("s_waitcnt expcnt(0)", "s_waitcnt", [{"k": "special", "t": "expcnt(0)"}]), - ("s_waitcnt lgkmcnt(0)", "s_waitcnt", [{"k": "special", "t": "lgkmcnt(0)"}]), - ( - "s_waitcnt vmcnt(1) lgkmcnt(2)", - "s_waitcnt", - [{"k": "special", "t": "vmcnt(1)"}, {"k": "special", "t": "lgkmcnt(2)"}], - ), - ( - "s_waitcnt vmcnt(0) expcnt(0) lgkmcnt(0)", - "s_waitcnt", - [ - {"k": "special", "t": "vmcnt(0)"}, - {"k": "special", "t": "expcnt(0)"}, - {"k": "special", "t": "lgkmcnt(0)"}, - ], - ), - ("s_waitcnt 0", "s_waitcnt", [{"k": "imm", "v": 0}]), - ( - "s_setreg_b32 hwreg(HW_REG_MODE, 2, 2), s0", - "s_setreg_b32", - [ - {"k": "special", "t": "hwreg(HW_REG_MODE, 2, 2)"}, - {"k": "sgpr", "r": 0, "n": 1, "neg": False, "abs": False}, - ], - ), - ( - "s_setreg_imm32_b32 hwreg(HW_REG_MODE, 2, 2), 3", - "s_setreg_imm32_b32", - [{"k": "special", "t": "hwreg(HW_REG_MODE, 2, 2)"}, {"k": "imm", "v": 3}], - ), - ("s_nop 0", "s_nop", [{"k": "imm", "v": 0}]), - ("v_nop", "v_nop", []), - ] - for text, want_op, want_args in cases: - with self.subTest(line=text): - parsed = shader_ir.parse_line("\t" + text) - self.assertIsNotNone(parsed) - self.assertEqual(parsed["op"], want_op) - self.assertEqual(parsed["args"], want_args) - self.assertEqual(parsed["mods"], []) - self.assertTrue(all(arg["k"] != "raw" for arg in parsed["args"])) - - -class PixelShaderNoopWaitcntTests(unittest.TestCase): - """PS translation and spirv_mini_interp execution across all handled NOOPS and waitcnt variants.""" - - def test_variants_emit_no_extra_spirv_and_preserve_state_active_scc1_vcc1(self): - baseline = translate_ps("ps_noop_base_11", ps_program([], scc_one=True, vcc_one=True)) - want = expected_ps_mrt0(scc_one=True, vcc_one=True) - self.assertEqual(want, (0x11112232, 0x33334444, 0x6555666B, 0x77778888)) - self.assertEqual(tuple(si.run_fragment(baseline, inputs={"%sg_lane": 0})["%out_mrt0"]), want) - self.assertNotIn("OpControlBarrier", baseline) - self.assertNotIn("OpMemoryBarrier", baseline) - - for variant in SCALAR_NOOP_VARIANTS: - with self.subTest(insn=variant): - spv = translate_ps("ps_noop_var", ps_program([variant], scc_one=True, vcc_one=True)) - self.assertEqual(spv, baseline, f"{variant} emitted unexpected SPIR-V operations") - self.assertEqual(tuple(si.run_fragment(spv, inputs={"%sg_lane": 0})["%out_mrt0"]), want) - - def test_variants_preserve_scc0_and_vcc0(self): - baseline = translate_ps("ps_noop_base_00", ps_program([], scc_one=False, vcc_one=False)) - want = expected_ps_mrt0(scc_one=False, vcc_one=False) - self.assertEqual(want, (0x11112232, 0x99990000, 0x87896668, 0x77778888)) - self.assertEqual(tuple(si.run_fragment(baseline, inputs={"%sg_lane": 0})["%out_mrt0"]), want) - - for variant in SCALAR_NOOP_VARIANTS: - with self.subTest(insn=variant): - spv = translate_ps("ps_noop_var00", ps_program([variant], scc_one=False, vcc_one=False)) - self.assertEqual(spv, baseline) - self.assertEqual(tuple(si.run_fragment(spv, inputs={"%sg_lane": 0})["%out_mrt0"]), want) - - def test_interleaved_across_every_arithmetic_step(self): - base_lines = ps_program([], scc_one=True, vcc_one=True) - baseline = translate_ps("ps_interleave_base", base_lines) - want = expected_ps_mrt0(scc_one=True, vcc_one=True) - interleaved = [ - "v_mov_b32 v0, 0x11112222", - "v_mov_b32 v1, 0x33334444", - "v_mov_b32 v2, 0x55556666", - "v_mov_b32 v3, 0x77778888", - "s_clause 0x1", - "s_mov_b32 s2, 0xffffffff", - "s_mov_b32 s3, 5", - "s_delay_alu instid0(VALU_DEP_1) | instskip(NEXT) | instid1(SALU_CYCLE_1)", - "s_add_u32 s4, s2, s3", - "s_inst_prefetch 0x0", - "s_setprio 0x2", - "v_add_nc_u32 v0, v0, 0x10", - "s_sleep 0x1", - "v_cmp_eq_u32 vcc_lo, v0, 0x11112232", - "s_waitcnt_depctr depctr_vm_vsrc(0) depctr_va_sdst(0)", - "s_mov_b32 exec_lo, 0xaaaa5555", - "s_waitcnt_expcnt null, 0x0", - "s_waitcnt_lgkmcnt null, 0x0", - "s_waitcnt_vmcnt null, 0x0", - "s_waitcnt vmcnt(0) expcnt(0) lgkmcnt(0)", - "s_waitcnt_vscnt null, 0x0", - "s_nop 0", - "v_nop", - "s_cselect_b32 s5, 0x10000001, 0x20000002", - "s_add_u32 s6, s4, s5", - "v_cndmask_b32 v1, 0x99990000, v1, vcc_lo", - "v_add_nc_u32 v2, v2, s6", - "exp mrt0 v0, v1, v2, v3 done vm", - "s_endpgm", - ] - spv = translate_ps("ps_interleave", interleaved) - self.assertEqual(spv, baseline) - self.assertEqual(tuple(si.run_fragment(spv, inputs={"%sg_lane": 0})["%out_mrt0"]), want) - - def test_inactive_exec_stays_zero_for_vgpr_writes_and_exports(self): - # Part 1: EXEC=0 around all handled no-ops blocks VGPR writes, then restoring EXEC exports intact values. - base_vgpr = [ - "v_mov_b32 v0, 0x10000001", - "v_mov_b32 v1, 0x20000002", - "v_mov_b32 v2, 0x30000003", - "v_mov_b32 v3, 0x40000004", - "s_mov_b32 exec_lo, 0", - "v_add_nc_u32 v2, v2, 0x1234", - "v_mov_b32 v3, 0xdeadbeef", - "s_mov_b32 exec_lo, -1", - "exp mrt0 v0, v1, v2, v3 done vm", - "s_endpgm", - ] - with_noops = base_vgpr[:5] + REPRESENTATIVE_NOOPS + base_vgpr[5:] - spv_base = translate_ps("ps_exec0_vgpr_base", base_vgpr) - spv_noops = translate_ps("ps_exec0_vgpr_noops", with_noops) - self.assertEqual(spv_noops, spv_base) - self.assertEqual(tuple(si.run_fragment(spv_noops, inputs={"%sg_lane": 0})["%out_mrt0"]), - (0x10000001, 0x20000002, 0x30000003, 0x40000004)) - - # Part 2: EXEC=0 across all handled no-ops keeps the lane inactive through end of shader (OpKill -> {}). - base_exp = [ - "v_mov_b32 v0, 0x10000001", - "v_mov_b32 v1, 0x20000002", - "v_mov_b32 v2, 0x30000003", - "v_mov_b32 v3, 0x40000004", - "exp mrt0 v0, v1, v2, v3 vm", - "s_mov_b32 exec_lo, 0xaaaa5554", - "v_mov_b32 v0, 0xbad00000", - "exp mrt0 v0, v0, v0, v0 done vm", - "s_endpgm", - ] - spv_exp_base = translate_ps("ps_exec0_exp_base", base_exp) - spv_exp_noops = translate_ps("ps_exec0_exp_noops", base_exp[:6] + REPRESENTATIVE_NOOPS + base_exp[6:]) - self.assertEqual(spv_exp_noops, spv_exp_base) - self.assertEqual(si.run_fragment(spv_exp_noops, inputs={"%sg_lane": 0}), {}) - - -class ComputeShaderNoopWaitcntTests(unittest.TestCase): - """FSSM compute shader translation and multi-lane execution (wave32 & wave64).""" - - def test_wave32_each_and_all_preserve_registers_vcc_scc_and_exec(self): - for scc_one in (True, False): - baseline = translate_cs("cs_w32_base", cs_program([], wave64=False, scc_one=scc_one), threads=32) - want = expected_cs_words(32, scc_one=scc_one) - self.assertEqual(run_cs(baseline, 32), want) - self.assertNotIn("OpControlBarrier", baseline) - self.assertNotIn("OpMemoryBarrier", baseline) - - for variant in SCALAR_NOOP_VARIANTS: - with self.subTest(scc_one=scc_one, insn=variant): - spv = translate_cs("cs_w32_var", cs_program([variant], wave64=False, scc_one=scc_one), threads=32) - self.assertEqual(spv, baseline) - self.assertEqual(run_cs(spv, 32), want) - - spv_all = translate_cs("cs_w32_all", cs_program(REPRESENTATIVE_NOOPS, wave64=False, scc_one=scc_one), - threads=32) - self.assertEqual(spv_all, baseline) - self.assertEqual(run_cs(spv_all, 32), want) - - def test_wave64_preserves_state_across_all_64_lanes(self): - for scc_one in (True, False): - baseline = translate_cs("cs_w64_base", cs_program([], wave64=True, scc_one=scc_one), threads=64) - want = expected_cs_words(64, scc_one=scc_one) - self.assertEqual(run_cs(baseline, 64), want) - self.assertNotIn("OpControlBarrier", baseline) - self.assertNotIn("OpMemoryBarrier", baseline) - - with self.subTest(scc_one=scc_one): - spv_all = translate_cs("cs_w64_all", cs_program(REPRESENTATIVE_NOOPS, wave64=True, scc_one=scc_one), - threads=64) - self.assertEqual(spv_all, baseline) - self.assertEqual(run_cs(spv_all, 64), want) - - -class ModeInstructionsTests(unittest.TestCase): - """Tests for s_denorm_mode, s_round_mode, and s_setreg* hardware MODE writes.""" - - def test_round_mode_switches_half_precision_color_rounding(self) -> None: - # Each magnitude is three quarters of the way from half 1.0 to its next neighbour. - spv = translate_ps("ps_immediate_round_mode", [ - "v_mov_b32 v0, 0x3f801800", "v_mov_b32 v1, 0xbf801800", - "s_round_mode 0xfffc", # only SIMM16[3:0] contributes to FP_ROUND - "v_cvt_f16_f32 v2, v0", "v_cvt_f16_f32 v3, v1", - "s_round_mode 0", - "v_cvt_f16_f32 v4, v0", "v_cvt_f16_f32 v5, v1", - "exp mrt0 v2, v3, v4, v5 done vm", "s_endpgm", - ]) - self.assertEqual(tuple(si.run_fragment(spv)["%out_mrt0"]), (0x3c00, 0xbc00, 0x3c01, 0xbc01)) - - def test_unmodelled_immediate_modes_raise_unsupported(self): - for insn in REFUSED_MODE_VARIANTS: - op = insn.split()[0] - with self.subTest(stage="ps", insn=insn): - with self.assertRaises(rdna2spirv.Unsupported) as ctx: - translate_ps("ps_refused_mode", ps_program([insn])) - self.assertIn(op, str(ctx.exception)) - self.assertIn("mode" if op == "s_denorm_mode" else "rounding", str(ctx.exception)) - - with self.subTest(stage="cs", insn=insn): - with self.assertRaises(rdna2spirv.Unsupported) as ctx: - translate_cs("cs_refused_mode", cs_program([insn], wave64=False), threads=32) - self.assertIn(op, str(ctx.exception)) - self.assertIn("mode" if op == "s_denorm_mode" else "rounding", str(ctx.exception)) - - def test_fp_round_emits_only_mode_r16_and_preserves_state(self): - ps_base = translate_ps("ps_mode_base", ps_program([])) - want_ps = expected_ps_mrt0() - cs_base = translate_cs("cs_mode_base", cs_program([], wave64=False), threads=32) - want_cs = expected_cs_words(32) - - for insn, mode_const in MODELLED_MODE_VARIANTS: - with self.subTest(stage="ps", insn=insn): - spv = translate_ps("ps_mode_setreg", ps_program([insn])) - self.assertIn("%mode_r16 = OpVariable %_ptr_Function_uint Function %c0", spv) - self.assertIn(f"OpStore %mode_r16 {mode_const}", spv) - self.assertNotIn("OpControlBarrier", spv) - # Removing the two mode lines recovers the exact baseline SPIR-V (modulo unused %c3 if added). - self.assertEqual(spv.count("OpStore %mode_r16"), 1) - self.assertEqual(tuple(si.run_fragment(spv, inputs={"%sg_lane": 0})["%out_mrt0"]), want_ps) - self.assertEqual(tuple(si.run_fragment(ps_base, inputs={"%sg_lane": 0})["%out_mrt0"]), want_ps) - - with self.subTest(stage="cs", insn=insn): - spv = translate_cs("cs_mode_setreg", cs_program([insn], wave64=False), threads=32) - self.assertIn("%mode_r16 = OpVariable %_ptr_Function_uint Function %c0", spv) - self.assertIn(f"OpStore %mode_r16 {mode_const}", spv) - self.assertEqual(run_cs(spv, 32), want_cs) - self.assertEqual(run_cs(cs_base, 32), want_cs) - - def test_unmodelled_s_setreg_mode_forms_raise_unsupported(self): - bad_mode_writes = [ - "s_setreg_imm32_b32 hwreg(HW_REG_MODE, 0, 2), 3", - "s_setreg_imm32_b32 hwreg(HW_REG_MODE, 4, 4), 15", - "s_setreg_imm32_b32 hwreg(HW_REG_MODE), 0", - "s_setreg_imm32_b32 hwreg(HW_REG_MODE, 2, 2), 1", - "s_setreg_imm32_b32 hwreg(HW_REG_MODE, 2, 2), 2", - "s_setreg_b32 hwreg(HW_REG_MODE, 2, 2), s2", - ] - for insn in bad_mode_writes: - with self.subTest(insn=insn): - with self.assertRaises(rdna2spirv.Unsupported): - translate_ps("ps_bad_mode", ps_program([insn])) - - -class NegativeControlTests(unittest.TestCase): - """Negative controls: sabotaging arithmetic or using unknown mnemonics must be detected.""" - - def test_sabotaging_arithmetic_around_noop_waitcnt_changes_output(self): - good_spv = translate_ps("ps_neg_good", ps_program(["s_waitcnt_vmcnt null, 0x0", "s_clause 0x1"])) - good_out = si.run_fragment(good_spv, inputs={"%sg_lane": 0}) - self.assertEqual(tuple(good_out["%out_mrt0"]), expected_ps_mrt0(scc_one=True, vcc_one=True)) - - # Assembly-level sabotage around the waitcnt/clause instructions: - sabotaged_cases = [ - ("SCC flipped 1->0", ps_program(["s_waitcnt_vmcnt null, 0x0", "s_clause 0x1"], scc_one=False)), - ("VCC flipped 1->0", ps_program(["s_waitcnt_vmcnt null, 0x0", "s_clause 0x1"], vcc_one=False)), - ("v_add_nc_u32 addend changed", ps_program(["s_waitcnt_vmcnt null, 0x0", "s_clause 0x1"], add_k=0x20)), - ("EXEC bit 0 cleared", ps_program(["s_waitcnt_vmcnt null, 0x0", "s_clause 0x1"], exec_lo=0xAAAA5554)), - ] - for label, bad_lines in sabotaged_cases: - with self.subTest(sabotage=label): - bad_spv = translate_ps("ps_neg_bad", bad_lines) - bad_out = si.run_fragment(bad_spv, inputs={"%sg_lane": 0}) - self.assertNotEqual(bad_out, good_out) - - # SPIR-V-level sabotage on the translated output around the no-op/waitcnt block: - for old, new, label in ( - ("OpIAdd %uint", "OpISub %uint", "v_add_nc_u32/s_add_u32 turned into OpISub"), - ("OpIEqual %bool", "OpINotEqual %bool", "v_cmp_eq_u32 inverted"), - ): - with self.subTest(spirv_sabotage=label): - self.assertIn(old, good_spv) - mutated = good_spv.replace(old, new) - self.assertNotEqual(si.run_fragment(mutated, inputs={"%sg_lane": 0}), good_out) - - # CS multi-lane negative control: - cs_good = translate_cs("cs_neg_good", cs_program(["s_sleep 0x1", "s_waitcnt_depctr 0xffe3"], wave64=False), - threads=32) - cs_good_words = run_cs(cs_good, 32) - cs_bad = translate_cs("cs_neg_bad", cs_program(["s_sleep 0x1", "s_waitcnt_depctr 0xffe3"], - wave64=False, scc_one=False), threads=32) - self.assertNotEqual(run_cs(cs_bad, 32), cs_good_words) - - def test_unknown_waitcnt_and_noop_mnemonics_fail_with_unsupported(self): - for bogus in ("s_bogus_waitcnt 0x0", "s_bogus_waitcnt", "s_bogus_noop 0"): - with self.subTest(stage="ps", insn=bogus): - with self.assertRaises(rdna2spirv.Unsupported) as ctx: - translate_ps("ps_bogus", ps_program([bogus])) - self.assertIn(bogus.split()[0], str(ctx.exception)) - - with self.subTest(stage="cs", insn=bogus): - with self.assertRaises(rdna2spirv.Unsupported) as ctx: - translate_cs("cs_bogus", cs_program([bogus], wave64=False), threads=32) - self.assertIn(bogus.split()[0], str(ctx.exception)) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_scmp_u64_mask_pairs.py b/tests/semantic/test_scmp_u64_mask_pairs.py deleted file mode 100644 index 633c7c807..000000000 --- a/tests/semantic/test_scmp_u64_mask_pairs.py +++ /dev/null @@ -1,295 +0,0 @@ -"""Semantic regression tests for s_cmp_eq_u64 / s_cmp_lg_u64 on SGPR mask pairs. - -Covers wave64 and wave32 SGPR pairs whose two 32-bit halves come from different sources: - - half mask + 0 or -1: (vcc_lo, 0), (0, vcc_hi), (vcc_lo, -1) on full and partial waves - - split (MASK_LO, MASK_HI) pair from two distinct masks: (vcc_lo, exec_hi) - - swapped halves: (vcc_hi, vcc_lo) - - mixed mask + plain scalar data: (vcc_lo, s7) and (s6, vcc_hi) - - preservation of the fast wave_equal vote path for canonical (MASK_LO, MASK_HI) pairs - and zero subgroup ops for plain-data pairs. -""" -from __future__ import annotations - -import gc -import os -import struct -import sys -import tempfile -import unittest -import warnings - -HERE = os.path.dirname(os.path.abspath(__file__)) -ROOT = os.path.dirname(os.path.dirname(HERE)) -TOOLS_DIR = os.environ.get("LEONIDA_TOOLS_DIR") or os.path.join(ROOT, "tools") - -sys.dont_write_bytecode = True -if HERE not in sys.path: - sys.path.insert(0, HERE) -if TOOLS_DIR not in sys.path: - sys.path.insert(0, TOOLS_DIR) - -import rdna2spirv # noqa: E402 -import spirv_asm # noqa: E402 -import spirv_mini_interp as si # noqa: E402 - -STUB_DXBC = b"DXBC" + bytes(24) + struct.pack(" 8 user SGPRs (s[0:3]=V#, s4=lo, s5=hi, s6=cmp_lo, s7=cmp_hi). -VSHARP = [0, 0, 0xFFFFFFFF, 0x31016FAC] - - -def make_fssm(threads: int, wave32: bool = False) -> bytes: - header = bytearray(0x138 + 16) - if wave32: - struct.pack_into(" str: - with tempfile.TemporaryDirectory() as tmp: - os.mkdir(os.path.join(tmp, "disasm")) - os.mkdir(os.path.join(tmp, "fssm")) - s_path = os.path.join(tmp, "disasm", name + ".s") - with open(s_path, "w", encoding="utf-8", newline="\n") as f: - f.write(f"; {name} synthetic\n") - for ln in asm.splitlines(): - st = ln.strip() - if st and not st.startswith(";"): - f.write(f"\t{st}\n") - with open(os.path.join(tmp, name + ".dxbc"), "wb") as f: - f.write(STUB_DXBC) - with open(os.path.join(tmp, "fssm", name + ".fssm"), "wb") as f: - f.write(make_fssm(threads, wave32=wave32)) - prev = rdna2spirv.WAVE64_EMULATE - rdna2spirv.WAVE64_EMULATE = emulate - try: - with warnings.catch_warnings(): - warnings.simplefilter("ignore", ResourceWarning) - spv = rdna2spirv.translate(s_path) - gc.collect() - return spv - finally: - rdna2spirv.WAVE64_EMULATE = prev - - -def run_cs(spv: str, threads: int, wave: int, s4: int = 0, s5: int = 0, s6: int = 0, s7: int = 0) -> dict[int, int]: - pc = VSHARP + [s4 & 0xFFFFFFFF, s5 & 0xFFFFFFFF, s6 & 0xFFFFFFFF, s7 & 0xFFFFFFFF] + [0] * 24 - return si.run_workgroup( - spv, threads, wave, - inputs_for=lambda i: {"%wg_id": (0, 0, 0), "%local_id": (i, 0, 0), "%sg_lane": i % wave}, - push_constants=pc, memory={}, - ) - - -def emit_store_scc(slot: int) -> str: - return ( - "s_cselect_b32 s20, 1, 0\n" - "v_mov_b32_e32 v4, s20\n" - f"v_mov_b32_e32 v5, {slot * 4}\n" - "buffer_store_dword v4, v5, s[0:3], 0 offen\n" - ) - - -# Builds wave64 vcc whose bit i is ((s4 if i < 32 else s5) >> (i & 31)) & 1. -WAVE64_BUILD_VCC = """\ -v_mov_b32_e32 v11, s5 -v_cmp_lt_u32_e64 vcc, v0, 32 -v_cndmask_b32_e64 v1, v11, s4, vcc -v_and_b32_e32 v2, 31, v0 -v_lshrrev_b32_e32 v3, v2, v1 -v_and_b32_e32 v3, 1, v3 -v_cmp_ne_u32_e64 vcc, 0, v3 -""" - -# Builds wave32 vcc_lo whose bit i is (s4 >> i) & 1. -WAVE32_BUILD_VCC = """\ -v_mov_b32_e32 v1, s4 -v_and_b32_e32 v2, 31, v0 -v_lshrrev_b32_e32 v3, v2, v1 -v_and_b32_e32 v3, 1, v3 -v_cmp_ne_u32_e64 vcc_lo, 0, v3 -""" - - -class Wave64SplitMaskPairTests(unittest.TestCase): - @classmethod - def setUpClass(cls): - asm = ( - WAVE64_BUILD_VCC - # Pair A: s[10:11] = (vcc_lo, 0) - + "s_mov_b32 s10, vcc_lo\n" - + "s_mov_b32 s11, 0\n" - + "s_cmp_eq_u64 s[10:11], 0\n" + emit_store_scc(0) - + "s_cmp_lg_u64 s[10:11], 0\n" + emit_store_scc(1) - + "s_cmp_eq_u64 s[10:11], vcc\n" + emit_store_scc(2) - # Pair B: s[12:13] = (0, vcc_hi) - + "s_mov_b32 s12, 0\n" - + "s_mov_b32 s13, vcc_hi\n" - + "s_cmp_eq_u64 s[12:13], 0\n" + emit_store_scc(3) - + "s_cmp_eq_u64 s[12:13], vcc\n" + emit_store_scc(4) - # Pair C: s[14:15] = (vcc_lo, -1) - + "s_mov_b32 s14, vcc_lo\n" - + "s_mov_b32 s15, -1\n" - + "s_cmp_eq_u64 s[14:15], vcc\n" + emit_store_scc(5) - + "s_cmp_eq_u64 s[14:15], 0\n" + emit_store_scc(6) - # Pair D: s[16:17] = (vcc_lo, exec_hi) -> canonical (MASK_LO, MASK_HI) from two different sources - + "s_mov_b32 s16, vcc_lo\n" - + "s_mov_b32 s17, exec_hi\n" - + "s_cmp_eq_u64 s[16:17], vcc\n" + emit_store_scc(7) - + "s_cmp_eq_u64 s[16:17], exec\n" + emit_store_scc(8) - # Pair E: s[18:19] = (vcc_hi, vcc_lo) -> swapped halves (MASK_HI, MASK_LO) - + "s_mov_b32 s18, vcc_hi\n" - + "s_mov_b32 s19, vcc_lo\n" - + "s_cmp_eq_u64 s[18:19], s[6:7]\n" + emit_store_scc(9) - + "s_cmp_eq_u64 s[18:19], vcc\n" + emit_store_scc(10) - # Pair F: s[22:23] = (vcc_lo, s7) -> mixed mask + plain data - + "s_mov_b32 s22, vcc_lo\n" - + "s_mov_b32 s23, s7\n" - + "s_cmp_eq_u64 s[22:23], s[6:7]\n" + emit_store_scc(11) - # Pair G: s[24:25] = (s6, vcc_hi) -> mixed plain data + high mask - + "s_mov_b32 s24, s6\n" - + "s_mov_b32 s25, vcc_hi\n" - + "s_cmp_eq_u64 s[24:25], s[6:7]\n" + emit_store_scc(12) - # Pair H: s[26:27] = (vcc_lo, vcc_lo) -> duplicated low half - + "s_mov_b32 s26, vcc_lo\n" - + "s_mov_b32 s27, vcc_lo\n" - + "s_cmp_eq_u64 s[26:27], vcc\n" + emit_store_scc(13) - + "s_endpgm\n" - ) - cls.spv = translate_cs("cs_w64_split_u64", asm, threads=64) - - def test_split_swapped_and_mixed_pairs_wave64(self): - cases = [ - (0x00000000, 0x00000001, 0x00000001, 0x00000000), - (0x00000001, 0x00000000, 0x00000000, 0x00000001), - (0x00000005, 0xFFFFFFFF, 0xFFFFFFFF, 0x00000005), - (0xFFFFFFFF, 0x00000005, 0xFFFFFFFF, 0x00000005), - (0x00000003, 0x80000001, 0x00000003, 0x12345678), - (0x12345678, 0x9ABCDEF0, 0x12345678, 0x9ABCDEF0), - (0x00000000, 0x00000000, 0x00000000, 0x00000000), - (0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF), - ] - for lo, hi, s6, s7 in cases: - with self.subTest(lo=hex(lo), hi=hex(hi), s6=hex(s6), s7=hex(s7)): - mem = run_cs(self.spv, 64, 64, s4=lo, s5=hi, s6=s6, s7=s7) - got = [mem[4 * k] for k in range(14)] - want = [ - int(lo == 0), # 0: (vcc_lo, 0) == 0 - int(lo != 0), # 1: (vcc_lo, 0) != 0 - int(hi == 0), # 2: (vcc_lo, 0) == vcc - int(hi == 0), # 3: (0, vcc_hi) == 0 - int(lo == 0), # 4: (0, vcc_hi) == vcc - int(hi == 0xFFFFFFFF), # 5: (vcc_lo, -1) == vcc - 0, # 6: (vcc_lo, -1) == 0 - int(hi == 0xFFFFFFFF), # 7: (vcc_lo, exec_hi=all1) == vcc - int(lo == 0xFFFFFFFF), # 8: (vcc_lo, exec_hi) == exec - int(hi == s6 and lo == s7), # 9: (vcc_hi, vcc_lo) == s[6:7] - int(hi == lo), # 10: (vcc_hi, vcc_lo) == vcc - int(lo == s6), # 11: (vcc_lo, s7) == s[6:7] - int(hi == s7), # 12: (s6, vcc_hi) == s[6:7] - int(lo == hi), # 13: (vcc_lo, vcc_lo) == vcc - ] - self.assertEqual(got, want) - - def test_partial_wave64_either_minus_one_high_half(self): - """On a 40-thread wave64, vcc_hi is 0x000000FF while s15 = -1 is 0xFFFFFFFF; they must not compare equal.""" - asm = ( - "v_cmp_eq_u32_e64 vcc, v0, v0\n" - + "s_mov_b32 s14, vcc_lo\n" - + "s_mov_b32 s15, -1\n" - + "s_cmp_eq_u64 s[14:15], vcc\n" + emit_store_scc(0) - + "s_cmp_lg_u64 s[14:15], vcc\n" + emit_store_scc(1) - + "s_mov_b32 s16, vcc_lo\n" - + "s_mov_b32 s17, exec_hi\n" - + "s_cmp_eq_u64 s[16:17], vcc\n" + emit_store_scc(2) - + "s_endpgm\n" - ) - spv = translate_cs("cs_w64_partial_split", asm, threads=40) - mem = run_cs(spv, threads=40, wave=64) - self.assertEqual([mem[0], mem[4], mem[8]], [0, 1, 1]) - - def test_wave64_emulate_split_pair_assembles_without_subgroup_ops(self): - """Split mask pairs translate and assemble cleanly under --wave64-emulate without subgroup ops.""" - asm = ( - WAVE64_BUILD_VCC - + "s_mov_b32 s10, vcc_lo\n" - + "s_mov_b32 s11, 0\n" - + "s_cmp_eq_u64 s[10:11], 0\n" + emit_store_scc(0) - + "s_mov_b32 s16, vcc_lo\n" - + "s_mov_b32 s17, exec_hi\n" - + "s_cmp_eq_u64 s[16:17], vcc\n" + emit_store_scc(1) - + "s_mov_b32 s18, vcc_hi\n" - + "s_mov_b32 s19, vcc_lo\n" - + "s_cmp_eq_u64 s[18:19], s[6:7]\n" + emit_store_scc(2) - + "s_endpgm\n" - ) - spv = translate_cs("cs_w64_emul_split", asm, threads=64, emulate=True) - self.assertNotIn("OpGroupNonUniform", spv) - self.assertIn("%x_buf", spv) - binary = spirv_asm.assemble(spv, target_env="vulkan1.2") - self.assertGreater(len(binary), 20) - - -class Wave32U64MaskPairTests(unittest.TestCase): - @classmethod - def setUpClass(cls): - asm = ( - WAVE32_BUILD_VCC - # 0, 1: (vcc_lo, 0) vs 0 - + "s_mov_b32 s10, vcc_lo\n" - + "s_mov_b32 s11, 0\n" - + "s_cmp_eq_u64 s[10:11], 0\n" + emit_store_scc(0) - + "s_cmp_lg_u64 s[10:11], 0\n" + emit_store_scc(1) - # 2: (vcc_lo, -1) vs 0 -> always 0 - + "s_mov_b32 s12, vcc_lo\n" - + "s_mov_b32 s13, -1\n" - + "s_cmp_eq_u64 s[12:13], 0\n" + emit_store_scc(2) - # 3: (vcc_lo, s7) vs s[6:7] -> mixed mask + plain data - + "s_mov_b32 s14, vcc_lo\n" - + "s_mov_b32 s15, s7\n" - + "s_cmp_eq_u64 s[14:15], s[6:7]\n" + emit_store_scc(3) - + "s_endpgm\n" - ) - cls.spv = translate_cs("cs_w32_u64_pair", asm, threads=32, wave32=True) - - def test_wave32_mask_pairs(self): - for lo, s6, s7 in ( - (0x00000000, 0x00000000, 0x12345678), - (0x00000003, 0x00000003, 0x12345678), - (0x00000001, 0xFFFFFFFF, 0x12345678), - (0xFFFFFFFF, 0xFFFFFFFF, 0x00000000), - ): - with self.subTest(lo=hex(lo), s6=hex(s6)): - mem = run_cs(self.spv, threads=32, wave=32, s4=lo, s6=s6, s7=s7) - want = [int(lo == 0), int(lo != 0), 0, int(lo == s6)] - self.assertEqual([mem[4 * k] for k in range(4)], want) - - -class FastPathAndPlainDataTests(unittest.TestCase): - def test_canonical_split_mask_pair_keeps_vote_fast_path(self): - asm = ( - WAVE64_BUILD_VCC - + "s_mov_b32 s16, vcc_lo\n" - + "s_mov_b32 s17, exec_hi\n" - + "s_cmp_eq_u64 s[16:17], vcc\n" - + "s_cmp_lg_u64 s[16:17], 0\n" - + "s_endpgm\n" - ) - spv = translate_cs("cs_w64_split_fast", asm, threads=64) - self.assertIn("OpGroupNonUniformAll", spv) - self.assertNotIn("OpGroupNonUniformBitwiseOr", spv) - - def test_plain_data_pair_emits_no_subgroup_ops(self): - asm = ( - "s_cmp_eq_u64 s[4:5], s[6:7]\n" - + emit_store_scc(0) - + "s_endpgm\n" - ) - spv = translate_cs("cs_w64_plain_u64", asm, threads=64) - self.assertNotIn("OpGroupNonUniform", spv) - mem = run_cs(spv, threads=64, wave=64, s4=0x11, s5=0x22, s6=0x11, s7=0x22) - self.assertEqual(mem[0], 1) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_scselect_b64_data.py b/tests/semantic/test_scselect_b64_data.py deleted file mode 100644 index 2dd7032b3..000000000 --- a/tests/semantic/test_scselect_b64_data.py +++ /dev/null @@ -1,507 +0,0 @@ -"""Semantic tests for RDNA2 s_cselect_b64 on 64-bit scalar data pairs vs lane masks. - -Covers: - * 64-bit SGPR data pairs with distinct low/high dwords for SCC=0 and SCC=1 - * Non-mask integer constants (positive, hex literals, small negative sign-extended, - and mixed 0/-1 with a 64-bit SGPR data pair) - * Destination aliasing (exact D==S0, D==S1, D==S0==S1, and overlapping pairs) - * SCC preservation across s_cselect_b64 - * Overwriting a former lane-mask SGPR pair with 64-bit data clears stale mask state - * Regression checks for lane-mask s_cselect_b64 (vcc, exec, lane-mask SGPR pairs) - across wave32, wave64, compute workgroups, and --wave64-emulate translation - -Run directly: - python -I tests/semantic/test_scselect_b64_data.py -v -""" -import os -import re -import struct -import sys -import tempfile -import unittest -import warnings - -HERE = os.path.dirname(os.path.abspath(__file__)) -if HERE not in sys.path: - sys.path.insert(0, HERE) - -import spirv_mini_interp as si # noqa: E402 -import spirv_wave_interp as wi # noqa: E402 -from support import STUB_DXBC, mrt0_words, rdna2spirv # noqa: E402 - -MASK32 = 0xFFFFFFFF -MASK64 = 0xFFFFFFFFFFFFFFFF - -_TMP_DIR = None -_PS_PATH = None -_CS_PATH = None - - -def setUpModule(): - global _TMP_DIR, _PS_PATH, _CS_PATH - _TMP_DIR = tempfile.TemporaryDirectory() - dis = os.path.join(_TMP_DIR.name, "disasm") - fssm = os.path.join(_TMP_DIR.name, "fssm") - os.mkdir(dis) - os.mkdir(fssm) - _PS_PATH = os.path.join(dis, "ps_cselect64.s") - _CS_PATH = os.path.join(dis, "cs_cselect64.s") - with open(os.path.join(_TMP_DIR.name, "ps_cselect64.dxbc"), "wb") as f: - f.write(STUB_DXBC) - with open(os.path.join(_TMP_DIR.name, "cs_cselect64.dxbc"), "wb") as f: - f.write(STUB_DXBC) - # Minimal FSSM header: 4 user SGPRs (V# in s[0:3]), TGID_X in s4, 64x1x1 threads. - hdr = bytearray(0x148) - struct.pack_into("<4I", hdr, 0x138, 0x8088, 64, 1, 1) - with open(os.path.join(fssm, "cs_cselect64.fssm"), "wb") as f: - f.write(hdr) - - -def tearDownModule(): - global _TMP_DIR - if _TMP_DIR is not None: - _TMP_DIR.cleanup() - _TMP_DIR = None - - -def translate_ps(lines): - if _TMP_DIR is None: - setUpModule() - asm = "; ps_cselect64\n" + "".join(f"\t{ln}\n" for ln in lines) - with open(_PS_PATH, "w", encoding="utf-8", newline="") as f: - f.write(asm) - with warnings.catch_warnings(): - warnings.simplefilter("ignore", ResourceWarning) - return rdna2spirv.translate(_PS_PATH) - - -def translate_cs(lines): - if _TMP_DIR is None: - setUpModule() - asm = "; cs_cselect64\n" + "".join(f"\t{ln}\n" for ln in lines) - with open(_CS_PATH, "w", encoding="utf-8", newline="") as f: - f.write(asm) - with warnings.catch_warnings(): - warnings.simplefilter("ignore", ResourceWarning) - return rdna2spirv.translate(_CS_PATH) - - -def run_ps(lines): - spv = translate_ps(lines + ["exp mrt0 v0, v1, v2, v3 done vm", "s_endpgm"]) - return mrt0_words(spv), spv - - -def run_ps_wave(lines, wave): - spv = translate_ps(lines + ["exp mrt0 v0, v1, v2, v3 done vm", "s_endpgm"]) - res = wi.run_wave(spv, wave=wave) - return [o[next(iter(o))] if o is not None else None for o in res["outputs"]], spv - - -def scc_line(scc): - return "s_cmp_eq_u32 1, 1" if scc else "s_cmp_eq_u32 0, 1" - - -def load_pair_lines(reg, val64): - lo = val64 & MASK32 - hi = (val64 >> 32) & MASK32 - return [f"s_mov_b32 s{reg}, {lo:#x}", f"s_mov_b32 s{reg + 1}, {hi:#x}"] - - -def ref_cselect_b64(s0, s1, scc): - return (s0 if scc else s1) & MASK64 - - -class DataPairSelectionTests(unittest.TestCase): - def test_sgpr_data_pairs_distinct_dwords(self): - pairs = [ - (0x55667788_11223344, 0xDDEEFF00_99AABBCC), - (0x12345678_00000000, 0xFFFFFFFF_87654321), - (0x00000002_80000001, 0x80000000_7FFFFFFE), - ] - for a64, b64 in pairs: - for scc in (0, 1): - with self.subTest(a=hex(a64), b=hex(b64), scc=scc): - want = ref_cselect_b64(a64, b64, scc) - lines = ( - load_pair_lines(4, a64) - + load_pair_lines(6, b64) - + [ - scc_line(scc), - "s_cselect_b64 s[2:3], s[4:5], s[6:7]", - "s_cselect_b32 s10, 1, 0", - "v_mov_b32 v0, s2", - "v_mov_b32 v1, s3", - "v_mov_b32 v2, s10", - "v_mov_b32 v3, 0", - ] - ) - words, _ = run_ps(lines) - self.assertEqual(words[:3], [want & MASK32, (want >> 32) & MASK32, scc]) - - def test_non_mask_constants(self): - cases = [ - ("42", "-2", 42, 0xFFFFFFFF_FFFFFFFE), - ("0x10", "0x80000000", 0x10, 0x00000000_80000000), - ("-16", "64", 0xFFFFFFFF_FFFFFFF0, 64), - ("0x12345678", "0", 0x12345678, 0), - ] - for s0_asm, s1_asm, s0_val, s1_val in cases: - for scc in (0, 1): - with self.subTest(s0=s0_asm, s1=s1_asm, scc=scc): - want = ref_cselect_b64(s0_val, s1_val, scc) - words, _ = run_ps([ - scc_line(scc), - f"s_cselect_b64 s[2:3], {s0_asm}, {s1_asm}", - "s_cselect_b32 s10, 1, 0", - "v_mov_b32 v0, s2", - "v_mov_b32 v1, s3", - "v_mov_b32 v2, s10", - "v_mov_b32 v3, 0", - ]) - self.assertEqual(words[:3], [want & MASK32, (want >> 32) & MASK32, scc]) - - def test_mixed_zero_minus_one_with_data_pair(self): - data64 = 0x55667788_11223344 - for imm_asm, imm_val in (("0", 0), ("-1", MASK64)): - for data_first in (True, False): - for scc in (0, 1): - s0_asm, s1_asm = ("s[4:5]", imm_asm) if data_first else (imm_asm, "s[4:5]") - s0_val, s1_val = (data64, imm_val) if data_first else (imm_val, data64) - with self.subTest(s0=s0_asm, s1=s1_asm, scc=scc): - want = ref_cselect_b64(s0_val, s1_val, scc) - lines = load_pair_lines(4, data64) + [ - scc_line(scc), - f"s_cselect_b64 s[2:3], {s0_asm}, {s1_asm}", - "s_cselect_b32 s10, 1, 0", - "v_mov_b32 v0, s2", - "v_mov_b32 v1, s3", - "v_mov_b32 v2, s10", - "v_mov_b32 v3, 0", - ] - words, _ = run_ps(lines) - self.assertEqual(words[:3], [want & MASK32, (want >> 32) & MASK32, scc]) - - # Mixed -1/0 via s_mov_b64 (lane_masks EITHER) and a plain 64-bit SGPR data pair. - for imm_asm, imm_val in (("0", 0), ("-1", MASK64)): - for scc in (0, 1): - with self.subTest(mov_imm=imm_asm, scc=scc): - want = ref_cselect_b64(imm_val, data64, scc) - lines = load_pair_lines(4, data64) + [ - f"s_mov_b64 s[8:9], {imm_asm}", - scc_line(scc), - "s_cselect_b64 s[2:3], s[8:9], s[4:5]", - "v_mov_b32 v0, s2", - "v_mov_b32 v1, s3", - "v_mov_b32 v2, 0", - "v_mov_b32 v3, 0", - ] - words, _ = run_ps(lines) - self.assertEqual(words[:2], [want & MASK32, (want >> 32) & MASK32]) - - # Pure 0 / -1 selection into an SGPR pair. - for scc in (0, 1): - want = ref_cselect_b64(MASK64, 0, scc) - words, _ = run_ps([ - scc_line(scc), - "s_cselect_b64 s[2:3], -1, 0", - "v_mov_b32 v0, s2", - "v_mov_b32 v1, s3", - "v_mov_b32 v2, 0", - "v_mov_b32 v3, 0", - ]) - self.assertEqual(words[:2], [want & MASK32, (want >> 32) & MASK32]) - - def test_destination_aliasing(self): - a64 = 0x55667788_11223344 - b64 = 0xDDEEFF00_99AABBCC - for src0, src1, s0_val, s1_val in ( - ("s[4:5]", "s[6:7]", a64, b64), - ("s[6:7]", "s[4:5]", b64, a64), - ("s[4:5]", "s[4:5]", a64, a64), - ): - for scc in (0, 1): - with self.subTest(src0=src0, src1=src1, scc=scc): - want = ref_cselect_b64(s0_val, s1_val, scc) - lines = ( - load_pair_lines(4, a64) - + load_pair_lines(6, b64) - + [ - scc_line(scc), - f"s_cselect_b64 s[4:5], {src0}, {src1}", - "s_cselect_b32 s10, 1, 0", - "v_mov_b32 v0, s4", - "v_mov_b32 v1, s5", - "v_mov_b32 v2, s10", - "v_mov_b32 v3, 0", - ] - ) - words, _ = run_ps(lines) - self.assertEqual(words[:3], [want & MASK32, (want >> 32) & MASK32, scc]) - - # Partial register overlap: dst s[4:5] overlaps both s[3:4] and s[5:6]. - s3, s4, s5, s6 = 0x10203040, 0x50607080, 0x90A0B0C0, 0xD0E0F001 - p34 = (s4 << 32) | s3 - p56 = (s6 << 32) | s5 - for src0, src1, s0_val, s1_val in ( - ("s[3:4]", "s[5:6]", p34, p56), - ("s[5:6]", "s[3:4]", p56, p34), - ): - for scc in (0, 1): - with self.subTest(overlap=(src0, src1), scc=scc): - want = ref_cselect_b64(s0_val, s1_val, scc) - words, _ = run_ps([ - f"s_mov_b32 s3, {s3:#x}", - f"s_mov_b32 s4, {s4:#x}", - f"s_mov_b32 s5, {s5:#x}", - f"s_mov_b32 s6, {s6:#x}", - scc_line(scc), - f"s_cselect_b64 s[4:5], {src0}, {src1}", - "v_mov_b32 v0, s4", - "v_mov_b32 v1, s5", - "v_mov_b32 v2, 0", - "v_mov_b32 v3, 0", - ]) - self.assertEqual(words[:2], [want & MASK32, (want >> 32) & MASK32]) - - def test_scc_preservation(self): - # Chained s_cselect_b64 + s_addc_u32 verify SCC is left untouched. - a64 = 0x22222222_11111111 - b64 = 0x44444444_33333333 - for scc in (0, 1): - with self.subTest(scc=scc): - want = ref_cselect_b64(a64, b64, scc) - lines = ( - load_pair_lines(4, a64) - + load_pair_lines(6, b64) - + [ - scc_line(scc), - "s_cselect_b64 s[2:3], s[4:5], s[6:7]", - "s_cselect_b64 s[8:9], s[6:7], s[4:5]", - "s_addc_u32 s10, 10, 20", - "v_mov_b32 v0, s2", - "v_mov_b32 v1, s3", - "v_mov_b32 v2, s8", - "v_mov_b32 v3, s10", - ] - ) - words, _ = run_ps(lines) - want_second = ref_cselect_b64(b64, a64, scc) - self.assertEqual( - words, - [want & MASK32, (want >> 32) & MASK32, want_second & MASK32, 30 + scc], - ) - - def test_overwriting_stale_lane_mask_pair_clears_mask_state(self): - # s[4:5] first holds EXEC (lane mask), then is overwritten by 64-bit data via s_cselect_b64. - # Subsequent s_bcnt1_i32_b64 and s_cmp_eq_u64 must treat s[4:5] as 64-bit data, not a wave mask. - a64 = 0x0F0F0000_00005555 # popcount: 8 + 8 = 16 - b64 = 0x00FF0000_00000007 # popcount: 8 + 3 = 11 - for wave, mbcnt in ((32, ["v_mbcnt_lo_u32_b32 v4, -1, 0"]), - (64, ["v_mbcnt_lo_u32_b32 v4, -1, 0", "v_mbcnt_hi_u32_b32 v4, -1, v4"])): - for scc in (0, 1): - with self.subTest(wave=wave, scc=scc): - want = ref_cselect_b64(a64, b64, scc) - want_cnt = want.bit_count() - lines = ( - mbcnt - + [ - "v_cmp_gt_u32_e32 vcc, 8, v4", - "s_mov_b64 s[4:5], vcc", # s[4:5] is a lane mask before s_cselect_b64 - ] - + load_pair_lines(6, a64) - + load_pair_lines(8, b64) - + [ - scc_line(scc), - "s_cselect_b64 s[4:5], s[6:7], s[8:9]", - "s_bcnt1_i32_b64 s10, s[4:5]", - "s_cmp_eq_u64 s[4:5], s[6:7]", - "s_cselect_b32 s11, 1, 0", - "v_mov_b32 v0, s4", - "v_mov_b32 v1, s5", - "v_mov_b32 v2, s10", - "v_mov_b32 v3, s11", - ] - ) - outs, _ = run_ps_wave(lines, wave=wave) - expected = (want & MASK32, (want >> 32) & MASK32, want_cnt, scc) - for lane in range(wave): - self.assertEqual(outs[lane], expected, f"wave={wave} lane={lane}") - - def test_null_source_reads_zero(self): - data64 = 0x55667788_11223344 - for s0_asm, s1_asm, s0_val, s1_val in ( - ("s[4:5]", "null", data64, 0), - ("null", "s[4:5]", 0, data64), - ): - for scc in (0, 1): - with self.subTest(s0=s0_asm, s1=s1_asm, scc=scc): - want = ref_cselect_b64(s0_val, s1_val, scc) - lines = load_pair_lines(4, data64) + [ - scc_line(scc), - f"s_cselect_b64 s[2:3], {s0_asm}, {s1_asm}", - "v_mov_b32 v0, s2", - "v_mov_b32 v1, s3", - "v_mov_b32 v2, 0", - "v_mov_b32 v3, 0", - ] - words, _ = run_ps(lines) - self.assertEqual(words[:2], [want & MASK32, (want >> 32) & MASK32]) - - def test_unsupported_destination_or_source_rejected(self): - with self.assertRaises(rdna2spirv.Unsupported): - translate_ps(["s_cselect_b64 m0, s[4:5], s[6:7]", "exp mrt0 v0, v0, v0, v0 done vm", "s_endpgm"]) - with self.assertRaises(rdna2spirv.Unsupported): - translate_ps(["s_cselect_b64 s[2:3], s4, s[6:7]", "exp mrt0 v0, v0, v0, v0 done vm", "s_endpgm"]) - - -class LaneMaskPreservationTests(unittest.TestCase): - def test_wave32_vcc_exec_and_sgpr_masks(self): - for scc in (0, 1): - with self.subTest(scc=scc): - # vcc = lanes 0..9 (10 lanes), s[2:3] = lanes 16..31 (16 lanes). - lines = [ - "v_mbcnt_lo_u32_b32 v4, -1, 0", - "v_cmp_gt_u32_e32 vcc, 10, v4", - "v_cmp_lt_u32_e64 s[2:3], 15, v4", - scc_line(scc), - "s_cselect_b64 s[4:5], vcc, s[2:3]", - "s_cselect_b32 s10, 1, 0", # SCC preserved across mask s_cselect_b64 - "s_bcnt1_i32_b64 s8, s[4:5]", - "v_mov_b32 v1, 0xAA", - "s_mov_b32 s12, 0", - "s_cmp_eq_u32 s10, 1", - "s_cselect_b64 exec, s[4:5], exec", - "v_mov_b32 v1, 0x55", - "s_cmp_eq_u32 1, 1", - "s_cselect_b64 exec, -1, exec", - "v_mov_b32 v0, s8", - "v_mov_b32 v2, s10", - "v_mov_b32 v3, s4", - ] - outs, _ = run_ps_wave(lines, wave=32) - want_cnt = 10 if scc else 16 - for lane in range(32): - in_mask = (lane < 10) if scc else (lane >= 16) - want_v1 = 0x55 if (scc == 0 or in_mask) else 0xAA - want_s4 = MASK32 if in_mask else 0 - self.assertEqual(outs[lane], (want_cnt, want_v1, scc, want_s4), f"lane={lane}") - - def test_wave64_vcc_exec_and_sgpr_masks(self): - for scc in (0, 1): - with self.subTest(scc=scc): - # vcc = lanes 0..19 (20 lanes), s[2:3] = lanes 36..63 (28 lanes, upper half only). - lines = [ - "v_mbcnt_lo_u32_b32 v4, -1, 0", - "v_mbcnt_hi_u32_b32 v4, -1, v4", - "v_cmp_gt_u32_e32 vcc, 20, v4", - "v_cmp_lt_u32_e64 s[2:3], 35, v4", - scc_line(scc), - "s_cselect_b64 s[4:5], vcc, s[2:3]", - "s_cselect_b32 s10, 1, 0", # SCC preserved - "s_bcnt1_i32_b64 s8, s[4:5]", - # Also test vcc as destination (with 0/-1 sources) and vcc as source into SGPR pair. - scc_line(scc), - "s_cselect_b64 vcc, -1, 0", - "s_cmp_eq_u32 1, 1", - "s_cselect_b64 s[6:7], vcc, 0", - "s_bcnt1_i32_b64 s9, s[6:7]", - "v_mov_b32 v1, 0x11", - "s_cmp_eq_u32 1, 1", - "s_cselect_b64 exec, s[4:5], 0", - "v_mov_b32 v1, 0x22", - "s_cmp_eq_u32 0, 1", - "s_cselect_b64 exec, 0, -1", # scc=0 -> select -1 -> restore all 64 lanes - "v_mov_b32 v0, s8", - "v_mov_b32 v2, s9", - "v_mov_b32 v3, s10", - ] - outs, _ = run_ps_wave(lines, wave=64) - want_cnt = 20 if scc else 28 - want_vcc_cnt = 64 if scc else 0 - for lane in range(64): - in_mask = (lane < 20) if scc else (lane >= 36) - want_v1 = 0x22 if in_mask else 0x11 - self.assertEqual(outs[lane], (want_cnt, want_v1, want_vcc_cnt, scc), f"lane={lane}") - - def test_wave64_compute_and_emulate_translation(self): - # Compute shader using both wave64 lane-mask s_cselect_b64 and 64-bit data-pair s_cselect_b64. - lines = [ - "v_cmp_lt_u32_e32 vcc, 39, v0", # lanes 40..63 (24 lanes) - "s_mov_b32 s6, 0x11223344", - "s_mov_b32 s7, 0x55667788", - "s_mov_b32 s8, 0x99aabbcc", - "s_mov_b32 s9, 0xddeeff00", - "s_cmp_eq_u32 1, 1", - "s_cselect_b64 s[10:11], s[6:7], s[8:9]", # data select -> s10=0x11223344, s11=0x55667788 - "s_cselect_b64 s[12:13], vcc, 0", # mask select -> 24 lanes set - "s_bcnt1_i32_b64 s14, s[12:13]", - "v_cmp_eq_u32_e32 vcc, 0, v0", - "s_cmp_eq_u32 1, 1", - "s_cselect_b64 exec, vcc, 0", - "v_mov_b32 v1, s10", - "v_mov_b32 v2, s11", - "v_mov_b32 v3, s14", - "v_mov_b32 v4, 0", - "buffer_store_dwordx4 v[1:4], v4, s[0:3], 0", - "s_cselect_b64 exec, -1, exec", - "s_endpgm", - ] - spv = translate_cs(lines) - mem = si.run_workgroup( - spv, - 64, - 64, - inputs_for=lambda i: {"%wg_id": (0, 0, 0), "%local_id": (i, 0, 0), "%sg_lane": i}, - push_constants=[0, 0, 0x1000, 0x31016FAC] + [0] * 28, - memory={}, - ) - self.assertEqual([mem.get(0), mem.get(4), mem.get(8), mem.get(12)], [0x11223344, 0x55667788, 24, 0]) - - # Also verify --wave64-emulate translation succeeds cleanly on the same wave64 compute shader. - prev = rdna2spirv.WAVE64_EMULATE - try: - rdna2spirv.WAVE64_EMULATE = True - spv_emu = translate_cs(lines) - finally: - rdna2spirv.WAVE64_EMULATE = prev - self.assertIn("OpStore %x_it", spv_emu) - - -class NegativeControlTests(unittest.TestCase): - def test_sabotaging_high_dword_select_breaks_result(self): - # The fix emits two OpSelect %uint instructions (lo and hi); replacing the second - # with the first simulates the old mask_dst bug (duplicating lo into hi). - lines = ( - load_pair_lines(4, 0x55667788_11223344) - + load_pair_lines(6, 0xDDEEFF00_99AABBCC) - + [ - scc_line(1), - "s_cselect_b64 s[2:3], s[4:5], s[6:7]", - "v_mov_b32 v0, s2", - "v_mov_b32 v1, s3", - "v_mov_b32 v2, 0", - "v_mov_b32 v3, 0", - ] - ) - words, spv = run_ps(lines) - self.assertEqual(words[:2], [0x11223344, 0x55667788]) - m = re.search( - r"(%\w+) = OpINotEqual %bool %\w+ %c0\s+" - r"(%\w+) = OpSelect %uint \1 %\w+ %\w+\s+" - r"(%\w+) = OpSelect %uint \1 %\w+ %\w+", - spv, - ) - self.assertIsNotNone(m) - lo_id, hi_id = m.group(2), m.group(3) - bad = re.sub( - rf"{re.escape(hi_id)} = OpSelect %uint [^\n]+", - f"{hi_id} = OpCopyObject %uint {lo_id}", - spv, - count=1, - ) - self.assertNotEqual(bad, spv) - self.assertEqual(mrt0_words(bad)[:2], [0x11223344, 0x11223344]) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_sdwa_broadcast.py b/tests/semantic/test_sdwa_broadcast.py deleted file mode 100644 index 73a51e556..000000000 --- a/tests/semantic/test_sdwa_broadcast.py +++ /dev/null @@ -1,305 +0,0 @@ -"""Semantic interpreter tests for SDWA source sub-register selection. - -Covers sub-dword addressing (SDWA) source selection for RDNA2 -> SPIR-V: - - Byte extraction: BYTE_0 (bits 7:0), BYTE_1 (bits 15:8), BYTE_2 (bits 23:16), BYTE_3 (bits 31:24) - - Word extraction: WORD_0 (bits 15:0), WORD_1 (bits 31:16) - - Full dword selection: DWORD (bits 31:0) - - Unsigned zero-extension (default) vs signed sign-extension (under sext()) - - Sub-register broadcast to multiple ALU operands and self-broadcast patterns - - Negative controls: ensuring sign-extension and field offset saboteurs are caught -""" -import gc -import os -import struct -import sys -import tempfile -import unittest -import warnings - -HERE = os.path.dirname(os.path.abspath(__file__)) -ROOT = os.path.dirname(os.path.dirname(HERE)) -TOOLS_DIR = os.environ.get("LEONIDA_TOOLS_DIR") or os.path.join(ROOT, "tools") - -sys.dont_write_bytecode = True -if TOOLS_DIR not in sys.path: - sys.path.insert(0, TOOLS_DIR) -if HERE not in sys.path: - sys.path.insert(0, HERE) - -import rdna2spirv -import spirv_mini_interp as si -import support - -MASK = 0xFFFFFFFF - -SDWA_SEL_OFF_WIDTH = { - "BYTE_0": (0, 8), - "BYTE_1": (8, 8), - "BYTE_2": (16, 8), - "BYTE_3": (24, 8), - "WORD_0": (0, 16), - "WORD_1": (16, 16), - "DWORD": (0, 32), -} - - -def ref_sdwa_extract(val, sel, sext=False): - """Pure-Python reference implementation of SDWA source sub-register selection.""" - off, width = SDWA_SEL_OFF_WIDTH[sel] - if width == 32: - return val & MASK - field = (val >> off) & ((1 << width) - 1) - if sext and (field >> (width - 1)): - field -= 1 << width - return field & MASK - - -def run_sdwa_fragment(instructions): - """Translate and execute a synthetic branch-free pixel shader with given instructions. - - Returns the four 32-bit words written to %out_mrt0 (v1, v2, v3, v4). - """ - body = "\n".join("\t" + line.strip() for line in instructions if line.strip()) - shader_text = f"; ps_sdwa_test\n{body}\n\texp mrt0 v1, v2, v3, v4 done vm\n\ts_endpgm\n" - with tempfile.TemporaryDirectory() as tmp: - os.mkdir(os.path.join(tmp, "disasm")) - src_path = os.path.join(tmp, "disasm", "ps_sdwa_test.s") - with open(src_path, "w", encoding="utf-8") as f: - f.write(shader_text) - with open(os.path.join(tmp, "ps_sdwa_test.dxbc"), "wb") as f: - f.write(support.STUB_DXBC) - with warnings.catch_warnings(): - warnings.simplefilter("ignore", ResourceWarning) - spv = rdna2spirv.translate(src_path) - gc.collect() - return support.mrt0_words(spv) - - -class SdwaReferenceOracleTests(unittest.TestCase): - """Verify that the independent reference oracle matches expected ISA calculations.""" - - def test_byte_extractions_unsigned(self): - val = 0x8192A3B4 - self.assertEqual(ref_sdwa_extract(val, "BYTE_0", sext=False), 0xB4) - self.assertEqual(ref_sdwa_extract(val, "BYTE_1", sext=False), 0xA3) - self.assertEqual(ref_sdwa_extract(val, "BYTE_2", sext=False), 0x92) - self.assertEqual(ref_sdwa_extract(val, "BYTE_3", sext=False), 0x81) - - def test_byte_extractions_signed(self): - val = 0x8192A3B4 - self.assertEqual(ref_sdwa_extract(val, "BYTE_0", sext=True), 0xFFFFFFB4) - self.assertEqual(ref_sdwa_extract(val, "BYTE_1", sext=True), 0xFFFFFFA3) - self.assertEqual(ref_sdwa_extract(val, "BYTE_2", sext=True), 0xFFFFFF92) - self.assertEqual(ref_sdwa_extract(val, "BYTE_3", sext=True), 0xFFFFFF81) - - def test_byte_extractions_positive_sign_bit(self): - val = 0x12345678 - for sel, expected in [("BYTE_0", 0x78), ("BYTE_1", 0x56), ("BYTE_2", 0x34), ("BYTE_3", 0x12)]: - self.assertEqual(ref_sdwa_extract(val, sel, sext=False), expected) - self.assertEqual(ref_sdwa_extract(val, sel, sext=True), expected) - - def test_word_extractions_unsigned_and_signed(self): - val = 0x89ABCDEF - self.assertEqual(ref_sdwa_extract(val, "WORD_0", sext=False), 0xCDEF) - self.assertEqual(ref_sdwa_extract(val, "WORD_1", sext=False), 0x89AB) - self.assertEqual(ref_sdwa_extract(val, "WORD_0", sext=True), 0xFFFFCDEF) - self.assertEqual(ref_sdwa_extract(val, "WORD_1", sext=True), 0xFFFF89AB) - - def test_dword_selection(self): - val = 0xDEADBEEF - self.assertEqual(ref_sdwa_extract(val, "DWORD", sext=False), 0xDEADBEEF) - self.assertEqual(ref_sdwa_extract(val, "DWORD", sext=True), 0xDEADBEEF) - - -class SdwaDirectInterpreterTests(unittest.TestCase): - """Directly test the mini SPIR-V interpreter on OpBitFieldUExtract / OpBitFieldSExtract.""" - - def eval_extract(self, op_name, base_val, offset, count): - header = """\ -OpCapability Shader -%glsl = OpExtInstImport "GLSL.std.450" -OpMemoryModel Logical GLSL450 -OpEntryPoint Fragment %main "main" %out -%void = OpTypeVoid -%fn = OpTypeFunction %void -%uint = OpTypeInt 32 0 -%_ptr_Output_uint = OpTypePointer Output %uint -%out = OpVariable %_ptr_Output_uint Output -""" - c_base = f"%c_base = OpConstant %uint {base_val}\n" - c_off = f"%c_off = OpConstant %uint {offset}\n" - c_cnt = f"%c_cnt = OpConstant %uint {count}\n" - body = f"""\ -%main = OpFunction %void None %fn -%entry = OpLabel -%res = {op_name} %uint %c_base %c_off %c_cnt -OpStore %out %res -OpReturn -OpFunctionEnd -""" - text = header + c_base + c_off + c_cnt + body - return si.run_fragment(text)["%out"][0] - - def test_all_sdwa_sub_register_slices_in_interp(self): - pattern = 0x89ABCDEF - for sel, (off, width) in SDWA_SEL_OFF_WIDTH.items(): - if width == 32: - continue - with self.subTest(sel=sel, mode="unsigned"): - got_u = self.eval_extract("OpBitFieldUExtract", pattern, off, width) - want_u = ref_sdwa_extract(pattern, sel, sext=False) - self.assertEqual(got_u, want_u) - with self.subTest(sel=sel, mode="signed"): - got_s = self.eval_extract("OpBitFieldSExtract", pattern, off, width) - want_s = ref_sdwa_extract(pattern, sel, sext=True) - self.assertEqual(got_s, want_s) - - def test_out_of_bounds_extract_rejected(self): - with self.assertRaises(si.UnsupportedConstruct): - self.eval_extract("OpBitFieldUExtract", 0x12345678, 28, 8) - - -class SdwaSourceSelectionSemanticTests(unittest.TestCase): - """Test full translation and execution of RDNA2 SDWA source sub-register selection.""" - - def test_byte_selection_unsigned_all_positions(self): - val = 0x8192A3B4 - results = run_sdwa_fragment([ - f"v_mov_b32 v0, {val:#x}", - "v_mov_b32_sdwa v1, v0 dst_sel:DWORD dst_unused:UNUSED_PAD src0_sel:BYTE_0", - "v_mov_b32_sdwa v2, v0 dst_sel:DWORD dst_unused:UNUSED_PAD src0_sel:BYTE_1", - "v_mov_b32_sdwa v3, v0 dst_sel:DWORD dst_unused:UNUSED_PAD src0_sel:BYTE_2", - "v_mov_b32_sdwa v4, v0 dst_sel:DWORD dst_unused:UNUSED_PAD src0_sel:BYTE_3", - ]) - expected = [ref_sdwa_extract(val, f"BYTE_{i}", sext=False) for i in range(4)] - self.assertEqual(results, expected) - self.assertEqual(results, [0xB4, 0xA3, 0x92, 0x81]) - - def test_byte_selection_sign_extended_all_positions(self): - val = 0x8192A3B4 - results = run_sdwa_fragment([ - f"v_mov_b32 v0, {val:#x}", - "v_mov_b32_sdwa v1, sext(v0) dst_sel:DWORD dst_unused:UNUSED_PAD src0_sel:BYTE_0", - "v_mov_b32_sdwa v2, sext(v0) dst_sel:DWORD dst_unused:UNUSED_PAD src0_sel:BYTE_1", - "v_mov_b32_sdwa v3, sext(v0) dst_sel:DWORD dst_unused:UNUSED_PAD src0_sel:BYTE_2", - "v_mov_b32_sdwa v4, sext(v0) dst_sel:DWORD dst_unused:UNUSED_PAD src0_sel:BYTE_3", - ]) - expected = [ref_sdwa_extract(val, f"BYTE_{i}", sext=True) for i in range(4)] - self.assertEqual(results, expected) - self.assertEqual(results, [0xFFFFFFB4, 0xFFFFFFA3, 0xFFFFFF92, 0xFFFFFF81]) - - def test_word_selection_unsigned_and_sign_extended(self): - val = 0x89ABCDEF - results = run_sdwa_fragment([ - f"v_mov_b32 v0, {val:#x}", - "v_mov_b32_sdwa v1, v0 dst_sel:DWORD dst_unused:UNUSED_PAD src0_sel:WORD_0", - "v_mov_b32_sdwa v2, v0 dst_sel:DWORD dst_unused:UNUSED_PAD src0_sel:WORD_1", - "v_mov_b32_sdwa v3, sext(v0) dst_sel:DWORD dst_unused:UNUSED_PAD src0_sel:WORD_0", - "v_mov_b32_sdwa v4, sext(v0) dst_sel:DWORD dst_unused:UNUSED_PAD src0_sel:WORD_1", - ]) - expected = [ - ref_sdwa_extract(val, "WORD_0", sext=False), - ref_sdwa_extract(val, "WORD_1", sext=False), - ref_sdwa_extract(val, "WORD_0", sext=True), - ref_sdwa_extract(val, "WORD_1", sext=True), - ] - self.assertEqual(results, expected) - self.assertEqual(results, [0xCDEF, 0x89AB, 0xFFFFCDEF, 0xFFFF89AB]) - - def test_boundary_sign_bit_values(self): - results = run_sdwa_fragment([ - "v_mov_b32 v0, 0x0000807F", - "v_mov_b32_sdwa v1, sext(v0) dst_sel:DWORD dst_unused:UNUSED_PAD src0_sel:BYTE_0", - "v_mov_b32_sdwa v2, sext(v0) dst_sel:DWORD dst_unused:UNUSED_PAD src0_sel:BYTE_1", - "v_mov_b32 v5, 0x80007FFF", - "v_mov_b32_sdwa v3, sext(v5) dst_sel:DWORD dst_unused:UNUSED_PAD src0_sel:WORD_0", - "v_mov_b32_sdwa v4, sext(v5) dst_sel:DWORD dst_unused:UNUSED_PAD src0_sel:WORD_1", - ]) - self.assertEqual(results, [0x7F, 0xFFFFFF80, 0x7FFF, 0xFFFF8000]) - - -class SdwaBroadcastPatternsSemanticTests(unittest.TestCase): - """Test SDWA sub-register broadcasting where one register/field feeds multiple operands.""" - - def test_same_register_sub_byte_broadcast_to_both_operands(self): - val = 0x04030201 - results = run_sdwa_fragment([ - f"v_mov_b32 v0, {val:#x}", - "v_add_nc_u32_sdwa v1, v0, v0 dst_sel:DWORD dst_unused:UNUSED_PAD src0_sel:BYTE_0 src1_sel:BYTE_0", - "v_add_nc_u32_sdwa v2, v0, v0 dst_sel:DWORD dst_unused:UNUSED_PAD src0_sel:BYTE_1 src1_sel:BYTE_1", - "v_add_nc_u32_sdwa v3, v0, v0 dst_sel:DWORD dst_unused:UNUSED_PAD src0_sel:BYTE_2 src1_sel:BYTE_2", - "v_add_nc_u32_sdwa v4, v0, v0 dst_sel:DWORD dst_unused:UNUSED_PAD src0_sel:BYTE_3 src1_sel:BYTE_3", - ]) - self.assertEqual(results, [2, 4, 6, 8]) - - def test_broadcast_with_asymmetric_sign_extension(self): - val = 0x80 - results = run_sdwa_fragment([ - f"v_mov_b32 v0, {val:#x}", - "v_sub_nc_u32_sdwa v1, sext(v0), v0 dst_sel:DWORD dst_unused:UNUSED_PAD src0_sel:BYTE_0 src1_sel:BYTE_0", - "v_sub_nc_u32_sdwa v2, v0, sext(v0) dst_sel:DWORD dst_unused:UNUSED_PAD src0_sel:BYTE_0 src1_sel:BYTE_0", - "v_and_b32_sdwa v3, sext(v0), v0 dst_sel:DWORD dst_unused:UNUSED_PAD src0_sel:BYTE_0 src1_sel:BYTE_0", - "v_or_b32_sdwa v4, sext(v0), v0 dst_sel:DWORD dst_unused:UNUSED_PAD src0_sel:BYTE_0 src1_sel:BYTE_0", - ]) - s_val = ref_sdwa_extract(val, "BYTE_0", sext=True) - u_val = ref_sdwa_extract(val, "BYTE_0", sext=False) - self.assertEqual(results[0], (s_val - u_val) & MASK) - self.assertEqual(results[1], (u_val - s_val) & MASK) - self.assertEqual(results[2], (s_val & u_val) & MASK) - self.assertEqual(results[3], (s_val | u_val) & MASK) - self.assertEqual(results, [0xFFFFFF00, 0x00000100, 0x80, 0xFFFFFF80]) - - def test_cross_field_recombination_from_same_source(self): - val = 0x11223344 - results = run_sdwa_fragment([ - f"v_mov_b32 v0, {val:#x}", - "v_or_b32_sdwa v1, v0, v0 dst_sel:DWORD dst_unused:UNUSED_PAD src0_sel:BYTE_0 src1_sel:BYTE_1", - "v_or_b32_sdwa v2, v0, v0 dst_sel:DWORD dst_unused:UNUSED_PAD src0_sel:BYTE_2 src1_sel:BYTE_3", - "v_sub_nc_u32_sdwa v3, v0, v0 dst_sel:DWORD dst_unused:UNUSED_PAD src0_sel:WORD_1 src1_sel:WORD_0", - "v_and_b32_sdwa v4, v0, v0 dst_sel:DWORD dst_unused:UNUSED_PAD src0_sel:WORD_0 src1_sel:WORD_1", - ]) - self.assertEqual(results[0], 0x44 | 0x33) - self.assertEqual(results[1], 0x22 | 0x11) - self.assertEqual(results[2], (0x1122 - 0x3344) & MASK) - self.assertEqual(results[3], 0x3344 & 0x1122) - - def test_dual_source_mixed_width_selectors(self): - v0_val = 0xF0E0D0C0 - v1_val = 0x00020003 - results = run_sdwa_fragment([ - f"v_mov_b32 v0, {v0_val:#x}", - f"v_mov_b32 v5, {v1_val:#x}", - "v_add_nc_u32_sdwa v1, sext(v0), v5 dst_sel:DWORD dst_unused:UNUSED_PAD src0_sel:BYTE_0 src1_sel:WORD_1", - "v_add_nc_u32_sdwa v2, v0, sext(v5) dst_sel:DWORD dst_unused:UNUSED_PAD src0_sel:BYTE_1 src1_sel:WORD_0", - "v_add_nc_u32_sdwa v3, v0, v5 dst_sel:DWORD dst_unused:UNUSED_PAD src0_sel:DWORD src1_sel:BYTE_0", - "v_sub_nc_u32_sdwa v4, sext(v0), sext(v5) dst_sel:DWORD dst_unused:UNUSED_PAD src0_sel:WORD_1 src1_sel:WORD_0", - ]) - w0 = (ref_sdwa_extract(v0_val, "BYTE_0", sext=True) + ref_sdwa_extract(v1_val, "WORD_1", sext=False)) & MASK - w1 = (ref_sdwa_extract(v0_val, "BYTE_1", sext=False) + ref_sdwa_extract(v1_val, "WORD_0", sext=True)) & MASK - w2 = (ref_sdwa_extract(v0_val, "DWORD", sext=False) + ref_sdwa_extract(v1_val, "BYTE_0", sext=False)) & MASK - w3 = (ref_sdwa_extract(v0_val, "WORD_1", sext=True) - ref_sdwa_extract(v1_val, "WORD_0", sext=True)) & MASK - self.assertEqual(results, [w0, w1, w2, w3]) - - -class SdwaNegativeControlsTests(unittest.TestCase): - """Negative controls proving the tests detect sabotage in SDWA source extraction.""" - - def test_sabotaging_sign_extension_fails_assertions(self): - val = 0x80 - s_val = ref_sdwa_extract(val, "BYTE_0", sext=True) - u_val = ref_sdwa_extract(val, "BYTE_0", sext=False) - self.assertNotEqual(s_val, u_val) - self.assertEqual(s_val, 0xFFFFFF80) - self.assertEqual(u_val, 0x00000080) - - def test_sabotaging_offset_or_width_fails_assertions(self): - val = 0x12345678 - b0 = ref_sdwa_extract(val, "BYTE_0", sext=False) - b1 = ref_sdwa_extract(val, "BYTE_1", sext=False) - w0 = ref_sdwa_extract(val, "WORD_0", sext=False) - self.assertNotEqual(b0, b1) - self.assertNotEqual(b0, w0) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_sdwa_dst_mask.py b/tests/semantic/test_sdwa_dst_mask.py deleted file mode 100644 index 042e08367..000000000 --- a/tests/semantic/test_sdwa_dst_mask.py +++ /dev/null @@ -1,492 +0,0 @@ -"""Semantic interpreter tests for SDWA destination sub-register write masks and unused bit preservation. - -AMD RDNA2 VALU Instruction Set Architecture (ISA) - SDWA (Sub-Dword Addressing): -In RDNA2, SDWA instructions allow selecting sub-dword fields for destination and sources. -For destination sub-register write masks (dst_sel) and unused bit handling (dst_unused): - -Destination sub-register selectors (dst_sel): - - BYTE_0: bits [7:0] (offset 0, width 8) - - BYTE_1: bits [15:8] (offset 8, width 8) - - BYTE_2: bits [23:16] (offset 16, width 8) - - BYTE_3: bits [31:24] (offset 24, width 8) - - WORD_0: bits [15:0] (offset 0, width 16) - - WORD_1: bits [31:16] (offset 16, width 16) - - DWORD: bits [31:0] (offset 0, width 32) - -Destination unused bit preservation modes (dst_unused): - - UNUSED_PAD (default when dst_unused is omitted): - The sub-register field [offset : offset + width - 1] is updated with the truncated ALU result. - All bits outside the written sub-register field (both above and below) are zeroed (padded with 0). - - UNUSED_SEXT: - The sub-register field is updated with the truncated ALU result. - Bits above the written sub-register field are sign-extended (replicated MSB of the sub-dword value). - Bits below the sub-register field offset are strictly zeroed. - - UNUSED_PRESERVE: - The sub-register field is updated with the truncated ALU result. - All bits outside the written sub-register field (both below offset and above offset + width) - strictly retain their previous values from the destination VGPR. - -SPIR-V translation semantics (tools/rdna2spirv.py): - - UNUSED_PRESERVE translates to OpBitFieldInsert %uint %old_vgpr %alu_val %off %width - - UNUSED_PAD translates to OpBitFieldUExtract %uint %alu_val %c0 %width followed by OpShiftLeftLogical %off - - UNUSED_SEXT translates to OpBitFieldSExtract %uint %alu_val %c0 %width followed by OpShiftLeftLogical %off - - DWORD width (32 bits) passes the ALU result through unchanged. - -Standard library only: no GPU, no LLVM, no external tools, zero game data. -""" -from __future__ import annotations - -import gc -import os -from pathlib import Path -import struct -import sys -import tempfile -import unittest -import warnings - -HERE = os.path.dirname(os.path.abspath(__file__)) -ROOT = os.path.dirname(os.path.dirname(HERE)) -TOOLS_DIR = os.environ.get("LEONIDA_TOOLS_DIR") or os.path.join(ROOT, "tools") -if TOOLS_DIR not in sys.path: - sys.path.insert(0, TOOLS_DIR) -if HERE not in sys.path: - sys.path.insert(0, HERE) - -import rdna2spirv -import spirv_mini_interp as si -import support -from shader_ir import parse_line - -MASK32 = 0xFFFFFFFF -STUB_DXBC = b"DXBC" + bytes(24) + struct.pack(" int: - """Reference implementation of SDWA destination sub-register write mask and unused bit preservation.""" - old_val &= MASK32 - alu_val &= MASK32 - off, width = SDWA_SEL_PARAMS[sel] - if width == 32: - return alu_val - - field_mask = (1 << width) - 1 - field = alu_val & field_mask - - if unused == "UNUSED_PRESERVE": - preserve_mask = ~(field_mask << off) & MASK32 - return (old_val & preserve_mask) | (field << off) - elif unused == "UNUSED_PAD": - return (field << off) & MASK32 - elif unused == "UNUSED_SEXT": - sign = (field >> (width - 1)) & 1 - sext = (field | ((~0 << width) & MASK32)) if sign else field - return (sext << off) & MASK32 - else: - raise ValueError(f"Unknown dst_unused mode: {unused}") - - -DIRECT_SPV_HEADER = """OpCapability Shader -%glsl = OpExtInstImport "GLSL.std.450" -OpMemoryModel Logical GLSL450 -OpEntryPoint Fragment %main "main" %out -%void = OpTypeVoid -%fn = OpTypeFunction %void -%uint = OpTypeInt 32 0 -%_ptr_Output_uint = OpTypePointer Output %uint -%out = OpVariable %_ptr_Output_uint Output -%c0 = OpConstant %uint 0 -""" - - -def run_direct_sdwa_dst_spv(old_val: int, alu_val: int, sel: str, unused: str) -> int: - """Execute the exact SPIR-V instruction sequence emitted by rdna2spirv.sdwa_dst in spirv_mini_interp.""" - off, width = SDWA_SEL_PARAMS[sel] - c_decls = [f"%cval = OpConstant %uint {alu_val & MASK32}"] - if width == 32: - body = "%res = OpCopyObject %uint %cval\n" - elif unused == "UNUSED_PRESERVE": - c_decls.extend([ - f"%cold = OpConstant %uint {old_val & MASK32}", - f"%coff = OpConstant %uint {off}", - f"%cwidth = OpConstant %uint {width}", - ]) - body = "%res = OpBitFieldInsert %uint %cold %cval %coff %cwidth\n" - else: - ext = "OpBitFieldSExtract" if unused == "UNUSED_SEXT" else "OpBitFieldUExtract" - c_decls.extend([ - f"%coff = OpConstant %uint {off}", - f"%cwidth = OpConstant %uint {width}", - ]) - body = ( - f"%lo = {ext} %uint %cval %c0 %cwidth\n" - f"%res = OpShiftLeftLogical %uint %lo %coff\n" - ) - - spv = ( - DIRECT_SPV_HEADER - + "\n".join(c_decls) - + "\n%main = OpFunction %void None %fn\n%entry = OpLabel\n" - + body - + "OpStore %out %res\nOpReturn\nOpFunctionEnd\n" - ) - res = si.run_fragment(spv) - return res["%out"][0] - - -def translate_snippet(asm_body: str, name: str = "ps_sdwa_dst") -> str: - """Translate straight-line assembly snippet via rdna2spirv.translate without external tools.""" - with tempfile.TemporaryDirectory() as tmp: - disasm_dir = os.path.join(tmp, "disasm") - os.mkdir(disasm_dir) - with open(os.path.join(disasm_dir, f"{name}.s"), "w", encoding="utf-8") as f: - f.write(f"; {name}\n{asm_body}\n") - with open(os.path.join(tmp, f"{name}.dxbc"), "wb") as f: - f.write(STUB_DXBC) - with warnings.catch_warnings(): - warnings.simplefilter("ignore", ResourceWarning) - res = rdna2spirv.translate(os.path.join(disasm_dir, f"{name}.s")) - gc.collect() - return res - - -class SdwaDstReferenceTests(unittest.TestCase): - """Verify correctness of pure Python reference model against hand-derived golden vectors.""" - - def test_golden_vectors_pad(self): - self.assertEqual(ref_sdwa_dst(0x12345678, 0xFF, "BYTE_0", "UNUSED_PAD"), 0x000000FF) - self.assertEqual(ref_sdwa_dst(0x12345678, 0xFF, "BYTE_1", "UNUSED_PAD"), 0x0000FF00) - self.assertEqual(ref_sdwa_dst(0x12345678, 0xFF, "BYTE_2", "UNUSED_PAD"), 0x00FF0000) - self.assertEqual(ref_sdwa_dst(0x12345678, 0xFF, "BYTE_3", "UNUSED_PAD"), 0xFF000000) - self.assertEqual(ref_sdwa_dst(0x12345678, 0xFFFF, "WORD_0", "UNUSED_PAD"), 0x0000FFFF) - self.assertEqual(ref_sdwa_dst(0x12345678, 0xFFFF, "WORD_1", "UNUSED_PAD"), 0xFFFF0000) - self.assertEqual(ref_sdwa_dst(0x12345678, 0xCAFEBABE, "DWORD", "UNUSED_PAD"), 0xCAFEBABE) - - def test_golden_vectors_sext_positive(self): - self.assertEqual(ref_sdwa_dst(0x12345678, 0x7F, "BYTE_0", "UNUSED_SEXT"), 0x0000007F) - self.assertEqual(ref_sdwa_dst(0x12345678, 0x7F, "BYTE_1", "UNUSED_SEXT"), 0x00007F00) - self.assertEqual(ref_sdwa_dst(0x12345678, 0x7F, "BYTE_2", "UNUSED_SEXT"), 0x007F0000) - self.assertEqual(ref_sdwa_dst(0x12345678, 0x7F, "BYTE_3", "UNUSED_SEXT"), 0x7F000000) - self.assertEqual(ref_sdwa_dst(0x12345678, 0x7FFF, "WORD_0", "UNUSED_SEXT"), 0x00007FFF) - self.assertEqual(ref_sdwa_dst(0x12345678, 0x7FFF, "WORD_1", "UNUSED_SEXT"), 0x7FFF0000) - - def test_golden_vectors_sext_negative(self): - self.assertEqual(ref_sdwa_dst(0x12345678, 0x80, "BYTE_0", "UNUSED_SEXT"), 0xFFFFFF80) - self.assertEqual(ref_sdwa_dst(0x12345678, 0x90, "BYTE_1", "UNUSED_SEXT"), 0xFFFF9000) - self.assertEqual(ref_sdwa_dst(0x12345678, 0xF7, "BYTE_2", "UNUSED_SEXT"), 0xFFF70000) - self.assertEqual(ref_sdwa_dst(0x12345678, 0x80, "BYTE_3", "UNUSED_SEXT"), 0x80000000) - self.assertEqual(ref_sdwa_dst(0x12345678, 0x8001, "WORD_0", "UNUSED_SEXT"), 0xFFFF8001) - self.assertEqual(ref_sdwa_dst(0x12345678, 0x8001, "WORD_1", "UNUSED_SEXT"), 0x80010000) - - def test_golden_vectors_preserve(self): - base = 0x12345678 - self.assertEqual(ref_sdwa_dst(base, 0xAA, "BYTE_0", "UNUSED_PRESERVE"), 0x123456AA) - self.assertEqual(ref_sdwa_dst(base, 0xBB, "BYTE_1", "UNUSED_PRESERVE"), 0x1234BB78) - self.assertEqual(ref_sdwa_dst(base, 0xCC, "BYTE_2", "UNUSED_PRESERVE"), 0x12CC5678) - self.assertEqual(ref_sdwa_dst(base, 0xDD, "BYTE_3", "UNUSED_PRESERVE"), 0xDD345678) - self.assertEqual(ref_sdwa_dst(base, 0xBEEF, "WORD_0", "UNUSED_PRESERVE"), 0x1234BEEF) - self.assertEqual(ref_sdwa_dst(base, 0xCAFE, "WORD_1", "UNUSED_PRESERVE"), 0xCAFE5678) - self.assertEqual(ref_sdwa_dst(base, 0x99887766, "DWORD", "UNUSED_PRESERVE"), 0x99887766) - - def test_input_truncation_to_field_width(self): - base = 0x11223344 - wide_val = 0xFFFFFFFF - self.assertEqual(ref_sdwa_dst(base, wide_val, "BYTE_1", "UNUSED_PRESERVE"), 0x1122FF44) - self.assertEqual(ref_sdwa_dst(base, wide_val, "BYTE_1", "UNUSED_PAD"), 0x0000FF00) - self.assertEqual(ref_sdwa_dst(base, wide_val, "BYTE_1", "UNUSED_SEXT"), 0xFFFFFF00) - - -class SdwaDstInterpreterDirectTests(unittest.TestCase): - """Direct semantic interpreter execution of the emitted SPIR-V instruction sequences for all SDWA dst modes.""" - - def test_all_selector_and_unused_mode_combinations(self): - test_values = [ - 0x00, 0x01, 0x5A, 0x7F, 0x80, 0xA5, 0xEF, 0xFF, - 0x1234, 0x7FFF, 0x8000, 0x8001, 0xDEAD, 0xFFFF, - 0x12345678, 0x87654321, 0xDEADBEEF, 0xFFFFFFFF, - ] - bases = [0x00000000, 0x12345678, 0x87654321, 0xFFFFFFFF] - - for sel in ["BYTE_0", "BYTE_1", "BYTE_2", "BYTE_3", "WORD_0", "WORD_1", "DWORD"]: - for unused in ["UNUSED_PAD", "UNUSED_SEXT", "UNUSED_PRESERVE"]: - for base in bases: - for val in test_values: - with self.subTest(sel=sel, unused=unused, base=hex(base), val=hex(val)): - expected = ref_sdwa_dst(base, val, sel, unused) - got = run_direct_sdwa_dst_spv(base, val, sel, unused) - self.assertEqual( - got, - expected, - f"Direct SPIR-V mismatch for {sel} {unused} base={hex(base)} val={hex(val)}: got {hex(got)}, expected {hex(expected)}", - ) - - -class SdwaDstTranslatorTranslationTests(unittest.TestCase): - """End-to-end RDNA2 -> SPIR-V translation and semantic interpreter execution of pixel shaders with SDWA dst.""" - - def test_first_partial_write_keeps_barycentric_input_bits(self) -> None: - fixture = Path(HERE) / "fixtures" / "sdwa_bary_input.asm" - spv = support.translate_listing("ps_sdwa_bary_input", fixture.read_bytes()) - words = support.mrt0_words(spv, inputs={"%bary": (0.25, 0.25, 0.5)}) - self.assertEqual(words, [0x3e8000ab, 0x3f00abcd] * 2) - - def test_only_a_preserving_subword_write_reads_the_destination(self) -> None: - for select, unused, reads_dest in (("BYTE_2", "PRESERVE", True), ("WORD_0", "PRESERVE", True), - ("DWORD", "PRESERVE", False), ("WORD_0", "PAD", False), - ("BYTE_1", "SEXT", False)): - with self.subTest(select=select, unused=unused): - ins = parse_line(f"\tv_mov_b32_sdwa v0, v4 dst_sel:{select} dst_unused:UNUSED_{unused} src0_sel:DWORD") - reads = {0, 4} if reads_dest else {4} - self.assertEqual(rdna2spirv.read_before_write_vgprs([ins]), reads) - self.assertEqual(rdna2spirv.reg_reads_writes([ins]), (reads, {0})) - - def test_unused_pad_all_subreg_slices(self): - asm = """\ -\tv_mov_b32 v0, 0xffffffff -\tv_mov_b32_sdwa v1, v0 dst_sel:BYTE_0 dst_unused:UNUSED_PAD src0_sel:DWORD -\tv_mov_b32_sdwa v2, v0 dst_sel:BYTE_1 dst_unused:UNUSED_PAD src0_sel:DWORD -\tv_mov_b32_sdwa v3, v0 dst_sel:BYTE_2 dst_unused:UNUSED_PAD src0_sel:DWORD -\tv_mov_b32_sdwa v4, v0 dst_sel:BYTE_3 dst_unused:UNUSED_PAD src0_sel:DWORD -\texp mrt0 v1, v2, v3, v4 done vm -\ts_endpgm -""" - spv = translate_snippet(asm, "ps_pad_bytes") - words = support.mrt0_words(spv) - expected = [0x000000FF, 0x0000FF00, 0x00FF0000, 0xFF000000] - self.assertEqual(words, expected) - - def test_unused_pad_words_and_dword(self): - asm = """\ -\tv_mov_b32 v0, 0xffffffff -\tv_mov_b32_sdwa v1, v0 dst_sel:WORD_0 dst_unused:UNUSED_PAD src0_sel:DWORD -\tv_mov_b32_sdwa v2, v0 dst_sel:WORD_1 dst_unused:UNUSED_PAD src0_sel:DWORD -\tv_mov_b32_sdwa v3, v0 dst_sel:DWORD dst_unused:UNUSED_PAD src0_sel:DWORD -\texp mrt0 v1, v2, v3, v3 done vm -\ts_endpgm -""" - spv = translate_snippet(asm, "ps_pad_words") - words = support.mrt0_words(spv) - expected = [0x0000FFFF, 0xFFFF0000, 0xFFFFFFFF, 0xFFFFFFFF] - self.assertEqual(words, expected) - - def test_unused_pad_default_when_omitted(self): - """Omitting dst_unused defaults to UNUSED_PAD behavior in rdna2spirv.""" - asm = """\ -\tv_mov_b32 v0, 0x12345678 -\tv_mov_b32 v1, 0xaa -\tv_mov_b32_sdwa v0, v1 dst_sel:BYTE_1 src0_sel:DWORD -\texp mrt0 v0, v0, v0, v0 done vm -\ts_endpgm -""" - spv = translate_snippet(asm, "ps_default_pad") - words = support.mrt0_words(spv) - self.assertEqual(words[0], 0x0000AA00) - - def test_unused_sext_positive_and_negative(self): - asm = """\ -\tv_mov_b32 v0, 0x80 -\tv_mov_b32 v1, 0x90 -\tv_mov_b32 v2, 0xF0 -\tv_mov_b32 v3, 0x8001 -\tv_mov_b32_sdwa v4, v0 dst_sel:BYTE_0 dst_unused:UNUSED_SEXT src0_sel:DWORD -\tv_mov_b32_sdwa v5, v1 dst_sel:BYTE_1 dst_unused:UNUSED_SEXT src0_sel:DWORD -\tv_mov_b32_sdwa v6, v2 dst_sel:BYTE_2 dst_unused:UNUSED_SEXT src0_sel:DWORD -\tv_mov_b32_sdwa v7, v3 dst_sel:WORD_0 dst_unused:UNUSED_SEXT src0_sel:DWORD -\texp mrt0 v4, v5, v6, v7 done vm -\ts_endpgm -""" - spv = translate_snippet(asm, "ps_sext_neg") - words = support.mrt0_words(spv) - expected = [0xFFFFFF80, 0xFFFF9000, 0xFFF00000, 0xFFFF8001] - self.assertEqual(words, expected) - - def test_unused_sext_byte3_and_word1(self): - asm = """\ -\tv_mov_b32 v0, 0x80 -\tv_mov_b32 v1, 0x8001 -\tv_mov_b32 v2, 0x7F -\tv_mov_b32 v3, 0x7FFF -\tv_mov_b32_sdwa v4, v0 dst_sel:BYTE_3 dst_unused:UNUSED_SEXT src0_sel:DWORD -\tv_mov_b32_sdwa v5, v1 dst_sel:WORD_1 dst_unused:UNUSED_SEXT src0_sel:DWORD -\tv_mov_b32_sdwa v6, v2 dst_sel:BYTE_3 dst_unused:UNUSED_SEXT src0_sel:DWORD -\tv_mov_b32_sdwa v7, v3 dst_sel:WORD_1 dst_unused:UNUSED_SEXT src0_sel:DWORD -\texp mrt0 v4, v5, v6, v7 done vm -\ts_endpgm -""" - spv = translate_snippet(asm, "ps_sext_b3_w1") - words = support.mrt0_words(spv) - expected = [0x80000000, 0x80010000, 0x7F000000, 0x7FFF0000] - self.assertEqual(words, expected) - - def test_unused_preserve_subreg_slices(self): - asm = """\ -\tv_mov_b32 v0, 0x12345678 -\tv_mov_b32 v1, 0x12345678 -\tv_mov_b32 v2, 0x12345678 -\tv_mov_b32 v3, 0x12345678 -\tv_mov_b32 v4, 0xDEADBEEF -\tv_mov_b32_sdwa v0, v4 dst_sel:BYTE_0 dst_unused:UNUSED_PRESERVE src0_sel:DWORD -\tv_mov_b32_sdwa v1, v4 dst_sel:BYTE_1 dst_unused:UNUSED_PRESERVE src0_sel:DWORD -\tv_mov_b32_sdwa v2, v4 dst_sel:BYTE_2 dst_unused:UNUSED_PRESERVE src0_sel:DWORD -\tv_mov_b32_sdwa v3, v4 dst_sel:BYTE_3 dst_unused:UNUSED_PRESERVE src0_sel:DWORD -\texp mrt0 v0, v1, v2, v3 done vm -\ts_endpgm -""" - spv = translate_snippet(asm, "ps_pres_bytes") - words = support.mrt0_words(spv) - expected = [0x123456EF, 0x1234EF78, 0x12EF5678, 0xEF345678] - self.assertEqual(words, expected) - - def test_unused_preserve_words(self): - asm = """\ -\tv_mov_b32 v0, 0x12345678 -\tv_mov_b32 v1, 0x12345678 -\tv_mov_b32 v2, 0xDEADBEEF -\tv_mov_b32_sdwa v0, v2 dst_sel:WORD_0 dst_unused:UNUSED_PRESERVE src0_sel:DWORD -\tv_mov_b32_sdwa v1, v2 dst_sel:WORD_1 dst_unused:UNUSED_PRESERVE src0_sel:DWORD -\texp mrt0 v0, v1, v0, v1 done vm -\ts_endpgm -""" - spv = translate_snippet(asm, "ps_pres_words") - words = support.mrt0_words(spv) - expected = [0x1234BEEF, 0xBEEF5678, 0x1234BEEF, 0xBEEF5678] - self.assertEqual(words, expected) - - def test_sequential_byte_packing(self): - asm = """\ -\tv_mov_b32 v0, 0x00000000 -\tv_mov_b32 v1, 0xAA -\tv_mov_b32 v2, 0xBB -\tv_mov_b32 v3, 0xCC -\tv_mov_b32 v4, 0xDD -\tv_mov_b32_sdwa v0, v1 dst_sel:BYTE_0 dst_unused:UNUSED_PRESERVE src0_sel:DWORD -\tv_mov_b32_sdwa v0, v2 dst_sel:BYTE_1 dst_unused:UNUSED_PRESERVE src0_sel:DWORD -\tv_mov_b32_sdwa v0, v3 dst_sel:BYTE_2 dst_unused:UNUSED_PRESERVE src0_sel:DWORD -\tv_mov_b32_sdwa v0, v4 dst_sel:BYTE_3 dst_unused:UNUSED_PRESERVE src0_sel:DWORD -\texp mrt0 v0, v0, v0, v0 done vm -\ts_endpgm -""" - spv = translate_snippet(asm, "ps_pack_bytes") - words = support.mrt0_words(spv) - self.assertEqual(words[0], 0xDDCCBBAA) - - def test_sequential_word_packing(self): - asm = """\ -\tv_mov_b32 v0, 0x00000000 -\tv_mov_b32 v1, 0xCAFE -\tv_mov_b32 v2, 0xBABE -\tv_mov_b32_sdwa v0, v1 dst_sel:WORD_0 dst_unused:UNUSED_PRESERVE src0_sel:DWORD -\tv_mov_b32_sdwa v0, v2 dst_sel:WORD_1 dst_unused:UNUSED_PRESERVE src0_sel:DWORD -\texp mrt0 v0, v0, v0, v0 done vm -\ts_endpgm -""" - spv = translate_snippet(asm, "ps_pack_words") - words = support.mrt0_words(spv) - self.assertEqual(words[0], 0xBABECAFE) - - def test_combined_src_and_dst_sdwa(self): - asm = """\ -\tv_mov_b32 v0, 0x12345678 -\tv_mov_b32 v1, 0xAABBCCDD -\tv_mov_b32_sdwa v1, v0 dst_sel:BYTE_0 dst_unused:UNUSED_PRESERVE src0_sel:BYTE_3 -\texp mrt0 v1, v1, v1, v1 done vm -\ts_endpgm -""" - spv = translate_snippet(asm, "ps_combined_sdwa") - words = support.mrt0_words(spv) - self.assertEqual(words[0], 0xAABBCC12) - - def test_alu_operations_with_sdwa_dst(self): - asm = """\ -\tv_mov_b32 v0, 0x11223344 -\tv_mov_b32 v1, 0x00000010 -\tv_mov_b32 v2, 0x00000020 -\tv_add_nc_u32_sdwa v0, v1, v2 dst_sel:BYTE_1 dst_unused:UNUSED_PRESERVE src0_sel:DWORD src1_sel:DWORD -\tv_mov_b32 v3, 0x00000050 -\tv_mov_b32 v4, 0x00000010 -\tv_subrev_nc_u32_sdwa v5, v4, v3 dst_sel:BYTE_2 dst_unused:UNUSED_PAD src0_sel:DWORD src1_sel:DWORD -\tv_mov_b32 v6, 0x000000F0 -\tv_mov_b32 v7, 0x00000007 -\tv_or_b32_sdwa v8, v6, v7 dst_sel:BYTE_2 dst_unused:UNUSED_SEXT src0_sel:DWORD src1_sel:DWORD -\tv_mov_b32 v9, 0xAABBCCDD -\tv_mov_b32 v10, 0x00001234 -\tv_mov_b32 v11, 0x0000FFFF -\tv_and_b32_sdwa v9, v10, v11 dst_sel:WORD_1 dst_unused:UNUSED_PRESERVE src0_sel:DWORD src1_sel:DWORD -\texp mrt0 v0, v5, v8, v9 done vm -\ts_endpgm -""" - spv = translate_snippet(asm, "ps_alu_sdwa") - words = support.mrt0_words(spv) - expected = [0x11223044, 0x00400000, 0xFFF70000, 0x1234CCDD] - self.assertEqual(words, expected) - - -class SdwaDstNegativeControlTests(unittest.TestCase): - """Verify that test suite detects regressions and sabotaged SDWA destination instructions.""" - - def test_detect_bitfield_insert_sabotage(self): - asm = """\ -\tv_mov_b32 v0, 0x12345678 -\tv_mov_b32 v1, 0x000000AA -\tv_mov_b32_sdwa v0, v1 dst_sel:BYTE_1 dst_unused:UNUSED_PRESERVE src0_sel:DWORD -\texp mrt0 v0, v0, v0, v0 done vm -\ts_endpgm -""" - spv = translate_snippet(asm, "ps_sabotage_bfi") - good_words = support.mrt0_words(spv) - self.assertEqual(good_words[0], 0x1234AA78) - - self.assertIn("OpBitFieldInsert", spv) - bad_spv = spv.replace("OpBitFieldInsert", "OpBitFieldUExtract") - try: - bad_words = support.mrt0_words(bad_spv) - self.assertNotEqual(bad_words[0], 0x1234AA78) - except Exception: - pass - - def test_detect_sext_vs_uext_sabotage(self): - asm = """\ -\tv_mov_b32 v0, 0x000000F0 -\tv_mov_b32 v1, 0x00000007 -\tv_or_b32_sdwa v2, v0, v1 dst_sel:BYTE_2 dst_unused:UNUSED_SEXT src0_sel:DWORD src1_sel:DWORD -\texp mrt0 v2, v2, v2, v2 done vm -\ts_endpgm -""" - spv = translate_snippet(asm, "ps_sabotage_sext") - good_words = support.mrt0_words(spv) - self.assertEqual(good_words[0], 0xFFF70000) - - self.assertIn("OpBitFieldSExtract", spv) - bad_spv = spv.replace("OpBitFieldSExtract", "OpBitFieldUExtract") - bad_words = support.mrt0_words(bad_spv) - self.assertEqual(bad_words[0], 0x00F70000) - self.assertNotEqual(bad_words[0], 0xFFF70000) - - def test_sabotage_reference_model_pad_fails(self): - val = 0xAA - good = ref_sdwa_dst(0x12345678, val, "BYTE_1", "UNUSED_PAD") - bad = (val << 8) | 0x78 # failing to zero low byte - self.assertEqual(good, 0xAA00) - self.assertNotEqual(good, bad) - - def test_sabotage_reference_model_preserve_fails(self): - base = 0x12345678 - val = 0xAA - good = ref_sdwa_dst(base, val, "BYTE_1", "UNUSED_PRESERVE") - bad = 0x0000AA00 # padding instead of preserving - self.assertEqual(good, 0x1234AA78) - self.assertNotEqual(good, bad) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_short_asm_forms.py b/tests/semantic/test_short_asm_forms.py deleted file mode 100644 index 50cbdc431..000000000 --- a/tests/semantic/test_short_asm_forms.py +++ /dev/null @@ -1,85 +0,0 @@ -"""Hand-written assembly forms that the assembler accepts and canonicalises, but that tests copy unchanged. - -tests/semantic/regen_fixtures.py writes a hand-written .asm into a fixture as it is, without the llvm-mc pass that -the GPU runner applies, so the translator sees the source spelling. Two spellings used to end in an IndexError -instead of a result: - * the short VOP2 carry form `v_add_co_ci_u32 vD, src0, src1` (llvm-mc prints it as - `v_add_co_ci_u32_e32 vD, vcc_lo, src0, src1, vcc_lo`), also v_sub_co_ci_u32 and v_subrev_co_ci_u32; - * a modifier list shorter than the operands, `op_sel_hi:[0,0]` or `neg_lo:[1,0]` on a three-source op - (v_fma_mix_*, v_pk_fma_f16); llvm-mc pads the missing entries with 0, so `[0,0]` is `[0,0,0]`. -Each test checks that the short spelling gives the same words as the long one, and one value from the ISA. -Standard library only; no GPU, no game files. -""" -import unittest - -import support - -TAIL = ["exp mrt0 v10, v11, v12, v13 done vm", "s_endpgm"] - - -def run(lines): - text = "; short_form\n" + "".join("\t" + ln + "\n" for ln in lines + TAIL) - return support.mrt0_words(support.translate_listing("ps_short_form", text.encode("utf-8"))) - - -def hexes(words): - return [f"{w:#010x}" for w in words] - - -class ShortCarryForms(unittest.TestCase): - SETUP = ["v_mov_b32 v1, 0xfffffff0", "v_mov_b32 v2, 0x20", "v_cmp_eq_u32 vcc_lo, v1, v1"] # VCC = 1 (carry in) - - def check(self, op, want): - short = run(self.SETUP + [f"{op} v10, v1, v2", f"v_cndmask_b32 v11, 0, 1, vcc_lo", "v_mov_b32 v12, 0", - "v_mov_b32 v13, 0"]) - explicit = run(self.SETUP + [f"{op}_e32 v10, vcc_lo, v1, v2, vcc_lo", f"v_cndmask_b32 v11, 0, 1, vcc_lo", - "v_mov_b32 v12, 0", "v_mov_b32 v13, 0"]) - self.assertEqual(hexes(short), hexes(explicit)) - self.assertEqual(short[0], want[0]) - self.assertEqual(short[1], want[1]) - - def test_add_co_ci(self): - # 0xfffffff0 + 0x20 + 1 = 0x1_0000_0011: result 0x11, carry out 1 - self.check("v_add_co_ci_u32", (0x11, 1)) - - def test_sub_co_ci(self): - # 0xfffffff0 - 0x20 - 1 = 0xffffffcf, no borrow - self.check("v_sub_co_ci_u32", (0xFFFFFFCF, 0)) - - def test_subrev_co_ci(self): - # 0x20 - 0xfffffff0 - 1 = 0x2f with a borrow - self.check("v_subrev_co_ci_u32", (0x2F, 1)) - - -class ShortModifierLists(unittest.TestCase): - INPUT = ["v_mov_b32 v1, 0x40003c00", "v_mov_b32 v2, 0xc4004200", "v_mov_b32 v3, 0x3c004000"] # (1,2) (3,-4) (2,1) - - def same(self, short, full): - a = run(self.INPUT + [short, "v_mov_b32 v11, 0", "v_mov_b32 v12, 0", "v_mov_b32 v13, 0"]) - b = run(self.INPUT + [full, "v_mov_b32 v11, 0", "v_mov_b32 v12, 0", "v_mov_b32 v13, 0"]) - self.assertEqual(hexes(a), hexes(b)) - return a[0] - - def test_pk_fma_op_sel(self): - # op_sel:[1,0] is op_sel:[1,0,0]: the low half takes src0's high half (2.0), src1's low (3.0), src2's low (2.0) - # = 2*3 + 2 = 8.0 (0x4800); the high half takes src0 hi (2.0), src1 hi (-4.0), src2 hi (1.0) = -7.0 (0xc700) - got = self.same("v_pk_fma_f16 v10, v1, v2, v3 op_sel:[1,0]", "v_pk_fma_f16 v10, v1, v2, v3 op_sel:[1,0,0]") - self.assertEqual(got, 0xC7004800) - - def test_pk_fma_neg_lo(self): - # neg_lo:[1,0] is neg_lo:[1,0,0]: lo = -(1.0) * 3.0 + 2.0 = -1.0 (0xbc00); hi = 2.0 * -4.0 + 1.0 = -7.0 (0xc700) - got = self.same("v_pk_fma_f16 v10, v1, v2, v3 neg_lo:[1,0]", "v_pk_fma_f16 v10, v1, v2, v3 neg_lo:[1,0,0]") - self.assertEqual(got, 0xC700BC00) - - def test_pk_fma_op_sel_hi(self): - # op_sel_hi:[0,0] is [0,0,0]: the high half uses the low halves too: 1.0 * 3.0 + 2.0 = 5.0 (0x4500) - got = self.same("v_pk_fma_f16 v10, v1, v2, v3 op_sel_hi:[0,0]", "v_pk_fma_f16 v10, v1, v2, v3 op_sel_hi:[0,0,0]") - self.assertEqual(got >> 16, 0x4500) - - def test_fma_mix_op_sel_hi(self): - # [0,0] is [0,0,0]: all three operands read as f32 (the registers' bit patterns), none as a half - self.same("v_fma_mix_f32 v10, v1, v2, v3 op_sel_hi:[0,0]", "v_fma_mix_f32 v10, v1, v2, v3 op_sel_hi:[0,0,0]") - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_smem_clock.py b/tests/semantic/test_smem_clock.py deleted file mode 100644 index 0ecc28238..000000000 --- a/tests/semantic/test_smem_clock.py +++ /dev/null @@ -1,93 +0,0 @@ -"""test_smem_clock.py: s_memtime / s_memrealtime as OpReadClockKHR (VK_KHR_shader_clock).""" -import os -import shutil -import subprocess -import sys -import tempfile -import unittest - -HERE = os.path.dirname(os.path.abspath(__file__)) -ROOT = os.path.dirname(os.path.dirname(HERE)) -sys.path.insert(0, os.environ.get("LEONIDA_TOOLS_DIR") or os.path.join(ROOT, "tools")) -sys.path.insert(0, HERE) - -import rdna2spirv # noqa: E402 -from support import translate_lines # noqa: E402 - -EXIT = ["s_waitcnt lgkmcnt(0)", "v_mov_b32 v0, s4", "v_mov_b32 v1, s5", "v_mov_b32 v2, s6", "v_mov_b32 v3, s7", - "exp mrt0 v0, v1, v2, v3 done vm", "s_endpgm"] - - -def translate(ops, clock=True): - old = rdna2spirv.SHADER_CLOCK - rdna2spirv.SHADER_CLOCK = clock - try: - spv = translate_lines("ps_smem_clock", ops + EXIT) - finally: - rdna2spirv.SHADER_CLOCK = old - return spv, rdna2spirv.shader_meta(rdna2spirv.translate.last_gen, spv) - - -def spirv_val(spv): - if not (shutil.which("spirv-as") and shutil.which("spirv-val")): - return None - with tempfile.TemporaryDirectory() as d: - src, out = os.path.join(d, "s.spvasm"), os.path.join(d, "s.spv") - with open(src, "w", encoding="utf-8") as f: - f.write(spv) - for cmd in (["spirv-as", "--target-env", "vulkan1.2", src, "-o", out], - ["spirv-val", "--target-env", "vulkan1.2", out]): - r = subprocess.run(cmd, capture_output=True, text=True) - if r.returncode: - return r.stderr or r.stdout - return "" - - -class SmemClockTests(unittest.TestCase): - def test_memtime_is_subgroup_clock(self): - spv, meta = translate(["s_memtime s[4:5]", "s_mov_b32 s6, 0", "s_mov_b32 s7, 0"]) - self.assertIn("OpReadClockKHR %v2uint_d %c3", spv) - self.assertIn("OpCapability ShaderClockKHR", spv) - self.assertIn('OpExtension "SPV_KHR_shader_clock"', spv) - self.assertIn("shaderSubgroupClock", meta["features"]) - self.assertNotIn("shaderDeviceClock", meta["features"]) - - def test_memrealtime_is_device_clock(self): - spv, meta = translate(["s_memrealtime s[6:7]", "s_mov_b32 s4, 0", "s_mov_b32 s5, 0"]) - self.assertIn("OpReadClockKHR %v2uint_d %c1", spv) - self.assertIn("shaderDeviceClock", meta["features"]) - self.assertNotIn("shaderSubgroupClock", meta["features"]) - - def test_both_with_f64_share_one_vector_type(self): - spv, meta = translate(["s_memtime s[4:5]", "s_memrealtime s[6:7]", "v_add_f64 v[8:9], v[8:9], v[8:9]"]) - self.assertEqual(spv.count("OpTypeVector %uint 2"), 1) - self.assertEqual(spv.count("OpCapability ShaderClockKHR"), 1) - self.assertEqual(sorted(f for f in meta["features"] if "Clock" in f), - ["shaderDeviceClock", "shaderSubgroupClock"]) - - def test_no_clock_no_capability(self): - spv, meta = translate(["s_mov_b32 s4, 0", "s_mov_b32 s5, 0", "s_mov_b32 s6, 0", "s_mov_b32 s7, 0"]) - self.assertNotIn("ShaderClockKHR", spv) - self.assertNotIn("SPV_KHR_shader_clock", spv) - self.assertFalse([f for f in meta["features"] if "Clock" in f]) - - def test_single_sgpr_destination_is_unsupported(self): - with self.assertRaises(rdna2spirv.Unsupported): - translate(["s_memtime s4"]) - - def test_off_by_default(self): - self.assertFalse(rdna2spirv.SHADER_CLOCK) - for op in ("s_memtime s[4:5]", "s_memrealtime s[6:7]"): - with self.subTest(op=op), self.assertRaises(rdna2spirv.Unsupported): - translate([op], clock=False) - - def test_spirv_val(self): - spv, _ = translate(["s_memtime s[4:5]", "s_memrealtime s[6:7]"]) - err = spirv_val(spv) - if err is None: - self.skipTest("spirv-as / spirv-val not on PATH") - self.assertEqual(err, "") - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_smem_const_offset.py b/tests/semantic/test_smem_const_offset.py deleted file mode 100644 index d69c03f7a..000000000 --- a/tests/semantic/test_smem_const_offset.py +++ /dev/null @@ -1,110 +0,0 @@ -"""s_buffer_load / s_load with a constant SGPR offset give what the run-time path gives (no 32-bit wrap). - -The translator folds an SGPR offset it knows (s_mov_b32 s12, C) into the immediate. #1686 added the fold before the -32-bit truncation, so s12 = -4 with offset:20 summed to 16 and read in-bounds data, where hardware (0xFFFFFFFC + 20, -not reduced mod 2^32, measured by @Pierre-Kookis on gfx1036) and the run-time path read 0 (found by @Impre-visible, -reproduced on a GTX 1660). Each case runs the same load twice, once with the offset as a constant and once arriving -through v_readfirstlane_b32 (which the translator cannot fold), and checks both against the rule in the -Gen.scalar_load docstring (measured on gfx1030): off = (sOFF & ~3) + (IMM & ~3); for s_buffer_load dword i is 0 -when off + 4 * i + 4 > NUM_RECORDS (stride 0). Standard library only; no GPU, no game files. -""" -import os -import struct -import sys -import tempfile -import unittest -import warnings - -HERE = os.path.dirname(os.path.abspath(__file__)) -ROOT = os.path.dirname(os.path.dirname(HERE)) -sys.dont_write_bytecode = True -sys.path.insert(0, os.environ.get("LEONIDA_TOOLS_DIR") or os.path.join(ROOT, "tools")) -sys.path.insert(0, HERE) - -import rdna2spirv # noqa: E402 -import spirv_mini_interp as si # noqa: E402 - -M32 = 0xFFFFFFFF -STUB_DXBC = b"DXBC" + bytes(24) + struct.pack(" RECORDS else SEED[BASE + off] - - -class SmemConstOffset(unittest.TestCase): - def test_s_buffer_load_constant_and_run_time_offset_agree(self): - for sgpr_off, imm in ((-4, 20), (-16, 0x20), (0xFFFFFFF0, 0x10), (-1, 4), (4, 8), (0x3C, 0), (0x40, 0), - (0x10, 0x2C), (0x80000000, 0x10), (0, 0x3C)): - with self.subTest(sgpr_off=hex(sgpr_off & M32), imm=hex(imm)): - line = f"s_buffer_load_dword s14, s[8:11], s12 offset:{imm:#x}" - const = run(line, sgpr_off, constant=True) - dyn = run(line, sgpr_off, constant=False) - self.assertEqual(const, dyn) - self.assertEqual(const, sbuf_ref(sgpr_off, imm)) - - def test_the_reported_case(self): - # Impre-visible's listing: s8 = -4, offset:20 -> out of range, 0 (it read the word at byte 16 before). - line = "s_buffer_load_dword s14, s[8:11], s12 offset:20" - self.assertEqual(run(line, -4, constant=True), 0) - self.assertEqual(run(line, 12, constant=True), SEED[BASE + 32]) - - def test_s_load_constant_and_run_time_offset_agree(self): - for sgpr_off, imm in ((8, 4), (0x20, -8), (0, 0x3C), (0x10, -0x10)): - with self.subTest(sgpr_off=hex(sgpr_off), imm=imm): - line = f"s_load_dword s14, s[16:17], s12 offset:{imm}" - const = run(line, sgpr_off, constant=True) - dyn = run(line, sgpr_off, constant=False) - self.assertEqual(const, dyn) - self.assertEqual(const, SEED[BASE + sgpr_off + imm]) - - - def test_s_load_constant_offset_at_or_above_2_20(self): - # The old fold put sOFF into the 21-bit signed immediate, so sOFF = 0x100000 became -0x100000. Hardware and - # the run-time path add the zero-extended 32-bit sOFF; the loaded words agree (an address past the seeded - # words reads the interpreter's unset memory, the same either way). - for sgpr_off in (0x100000, 0x1FFFFC, 0x80000000): - with self.subTest(sgpr_off=hex(sgpr_off)): - line = "s_load_dword s14, s[16:17], s12 offset:0" - self.assertEqual(run(line, sgpr_off, constant=True), run(line, sgpr_off, constant=False)) - self.assertEqual(run("s_load_dword s14, s[16:17], s12 offset:0", 0x100000, constant=True), 0xA5A50000) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_sopc_validation.py b/tests/semantic/test_sopc_validation.py deleted file mode 100644 index e9a5ee024..000000000 --- a/tests/semantic/test_sopc_validation.py +++ /dev/null @@ -1,324 +0,0 @@ -"""Validation and positive-control semantic tests for all 18 RDNA2 SOPC instructions. - -Covers the exact 18 RDNA2 SOPC mnemonics (tools/rdna2_isa_tables.py SOPC): - - 12 32-bit scalar compares: s_cmp_{eq,lg,gt,ge,lt,le}_{i32,u32} - - 2 64-bit scalar compares: s_cmp_{eq,lg}_u64 - - 4 scalar bit tests: s_bitcmp{0,1}_{b32,b64} - -Verifies: - - Exact ISA table parity with tools/rdna2_isa_tables.SOPC. - - Rejection (Unsupported) of nonexistent s_cmp_* / s_bitcmp* mnemonics. - - Rejection of encoding suffixes (_e32/_e64/_sdwa/_dpp), instruction modifiers, wrong arity, - operand modifiers (neg/abs/sext), VGPRs/vlist/slist, and mismatched 32-bit vs 64-bit widths. - - Positive controls across all 18 ops and valid scalar operand kinds (including negative integer - immediates, float immediates, m0, null, vcc_lo/hi, exec_lo/hi, scc/src_scc, 64-bit pairs, - vcc, exec), validated with spirv-as + spirv-val --target-env vulkan1.2 and executed in - spirv_mini_interp. -""" -from __future__ import annotations - -import gc -import os -import shutil -import struct -import subprocess -import sys -import tempfile -import unittest -import warnings - -HERE = os.path.dirname(os.path.abspath(__file__)) -ROOT = os.path.dirname(os.path.dirname(HERE)) -TOOLS_DIR = os.environ.get("LEONIDA_TOOLS_DIR") or os.path.join(ROOT, "tools") - -sys.dont_write_bytecode = True -if HERE not in sys.path: - sys.path.insert(0, HERE) -if TOOLS_DIR not in sys.path: - sys.path.insert(0, TOOLS_DIR) - -import rdna2_isa_tables # noqa: E402 -import rdna2spirv # noqa: E402 -import shader_ir # noqa: E402 -import spirv_mini_interp as si # noqa: E402 - -STUB_DXBC = b"DXBC" + bytes(24) + struct.pack(" tuple[str, str]: - if op in rdna2spirv.SOPC_CMP64_OPS: - return "s[4:5]", "s[6:7]" - if op.endswith("_b64"): - return "s[4:5]", "s6" - return "s4", "s5" - - -def _run_insn_line(line: str) -> rdna2spirv.Gen: - ins = shader_ir.parse_line(line) - assert ins is not None, f"failed to parse line: {line!r}" - g = rdna2spirv.Gen("cs") - g.insn(ins) - return g - - -def _translate_and_validate_cs(name: str, asm_lines: list[str], threads: int = 64) -> str: - with tempfile.TemporaryDirectory() as tmp: - os.mkdir(os.path.join(tmp, "disasm")) - os.mkdir(os.path.join(tmp, "fssm")) - s_path = os.path.join(tmp, "disasm", f"{name}.s") - with open(s_path, "w", encoding="utf-8", newline="\n") as f: - f.write(f"; {name} synthetic\n") - for ln in asm_lines: - f.write(f"\t{ln}\n") - with open(os.path.join(tmp, f"{name}.dxbc"), "wb") as f: - f.write(STUB_DXBC) - with open(os.path.join(tmp, "fssm", f"{name}.fssm"), "wb") as f: - f.write(bytes(0x138) + struct.pack("<4I", 0x8090, threads, 1, 1)) - with warnings.catch_warnings(): - warnings.simplefilter("ignore", ResourceWarning) - spv = rdna2spirv.translate(s_path) - gc.collect() - spirv_as = shutil.which("spirv-as") - spirv_val = shutil.which("spirv-val") - if not (spirv_as and spirv_val): - if os.environ.get("LEONIDA_REQUIRE_SPIRV_TOOLS") == "1": - raise AssertionError("spirv-as / spirv-val required but not found on PATH") - return spv - spvasm = os.path.join(tmp, f"{name}.spvasm") - spvbin = os.path.join(tmp, f"{name}.spv") - with open(spvasm, "w", encoding="utf-8", newline="\n") as f: - f.write(spv) - r1 = subprocess.run( - [spirv_as, "--target-env", "vulkan1.2", spvasm, "-o", spvbin], - capture_output=True, text=True, - ) - assert r1.returncode == 0, f"spirv-as failed:\n{r1.stderr}" - r2 = subprocess.run( - [spirv_val, "--target-env", "vulkan1.2", spvbin], - capture_output=True, text=True, - ) - assert r2.returncode == 0, f"spirv-val failed:\n{r2.stderr}" - return spv - - -def _store_scc(slot: int) -> list[str]: - return [ - "s_cselect_b32 s20, 1, 0", - "v_mov_b32_e32 v4, s20", - f"v_mov_b32_e32 v5, {slot * 4}", - "buffer_store_dword v4, v5, s[0:3], 0 offen", - ] - - -class TestSopcIsaParity(unittest.TestCase): - def test_exact_18_sopc_ops_match_isa_table(self): - isa_sopc = {entry[0] for entry in rdna2_isa_tables.SOPC.values()} - translator_sopc = rdna2spirv.SOPC_CMP32_OPS | rdna2spirv.SOPC_CMP64_OPS | rdna2spirv.SOPC_BITCMP_OPS - self.assertEqual(len(isa_sopc), 18) - self.assertEqual(translator_sopc, isa_sopc) - - -class TestSopcNegativeValidation(unittest.TestCase): - def test_nonexistent_mnemonics_rejected(self): - bad_lines = [ - "s_cmp_eq_f32 s0, s1", - "s_cmp_lt_f16 s0, s1", - "s_cmp_eq_f64 s[0:1], s[2:3]", - "s_cmp_ne_i32 s0, s1", - "s_cmp_ne_u32 s0, s1", - "s_cmp_f_u32 s0, s1", - "s_cmp_t_i32 s0, s1", - "s_cmp_eq_u16 s0, s1", - "s_cmp_lt_u64 s[0:1], s[2:3]", - "s_cmp_le_u64 s[0:1], s[2:3]", - "s_cmp_gt_u64 s[0:1], s[2:3]", - "s_cmp_ge_u64 s[0:1], s[2:3]", - "s_cmp_eq_i64 s[0:1], s[2:3]", - "s_cmp_lg_i64 s[0:1], s[2:3]", - "s_bitcmp2_b32 s0, s1", - "s_bitcmp0_b16 s0, s1", - "s_bitcmp1_b16 s0, s1", - "s_bitcmp_b32 s0, s1", - ] - for line in bad_lines: - with self.subTest(line=line): - with self.assertRaises(rdna2spirv.Unsupported): - _run_insn_line(line) - - def test_invalid_encoding_suffixes_rejected_all_18(self): - for op in ALL_SOPC: - a0, a1 = _valid_pair_asm(op) - cases = [ - f"{op}_e32 {a0}, {a1}", - f"{op}_e64 {a0}, {a1}", - f"{op}_sdwa {a0}, {a1}", - f"{op}_sdwa {a0}, {a1} src0_sel:WORD_0", - f"{op}_dpp {a0}, {a1} quad_perm:[0,1,2,3]", - f"{op}_dpp v0, v1 quad_perm:[0,1,2,3]", - ] - for line in cases: - with self.subTest(op=op, line=line): - with self.assertRaises(rdna2spirv.Unsupported): - _run_insn_line(line) - - def test_instruction_modifiers_rejected_all_18(self): - for op in ALL_SOPC: - a0, a1 = _valid_pair_asm(op) - for mod in ("clamp", "mul:2", "op_sel:[0,0]", "glc"): - line = f"{op} {a0}, {a1} {mod}" - with self.subTest(op=op, mod=mod): - with self.assertRaises(rdna2spirv.Unsupported): - _run_insn_line(line) - - def test_wrong_arity_rejected_all_18(self): - for op in ALL_SOPC: - a0, a1 = _valid_pair_asm(op) - for line in (op, f"{op} {a0}", f"{op} {a0}, {a1}, s8"): - with self.subTest(op=op, line=line): - with self.assertRaises(rdna2spirv.Unsupported): - _run_insn_line(line) - - def test_operand_modifiers_rejected_all_18(self): - for op in ALL_SOPC: - a0, a1 = _valid_pair_asm(op) - bad_a0 = [f"-{a0}", f"|{a0}|", f"neg({a0})", f"abs({a0})", f"sext({a0})", "neg(1)", "|1|"] - bad_a1 = [f"-{a1}", f"|{a1}|", f"neg({a1})", f"abs({a1})", f"sext({a1})", "neg(1)", "|1|"] - if op in rdna2spirv.SOPC_CMP32_OPS or op in ("s_bitcmp0_b32", "s_bitcmp1_b32"): - bad_a0.extend(["neg(1.0)", "|1.0|"]) - bad_a1.extend(["neg(1.0)", "|1.0|"]) - for x in bad_a0: - with self.subTest(op=op, slot=0, arg=x): - with self.assertRaises(rdna2spirv.Unsupported): - _run_insn_line(f"{op} {x}, {a1}") - for y in bad_a1: - with self.subTest(op=op, slot=1, arg=y): - with self.assertRaises(rdna2spirv.Unsupported): - _run_insn_line(f"{op} {a0}, {y}") - - def test_vgpr_vlist_slist_ttmp_rejected_all_18(self): - bad_operands = ["v0", "v[0:1]", "[v0, v1]", "[s0, s1]", "ttmp0"] - for op in ALL_SOPC: - a0, a1 = _valid_pair_asm(op) - for bad in bad_operands: - with self.subTest(op=op, slot=0, arg=bad): - with self.assertRaises(rdna2spirv.Unsupported): - _run_insn_line(f"{op} {bad}, {a1}") - with self.subTest(op=op, slot=1, arg=bad): - with self.assertRaises(rdna2spirv.Unsupported): - _run_insn_line(f"{op} {a0}, {bad}") - - def test_width_mismatch_rejected_32bit_ops(self): - wide_operands = ["s[0:1]", "s[0:3]", "vcc", "exec"] - for op in ALL_CMP32 + ["s_bitcmp0_b32", "s_bitcmp1_b32"]: - for bad in wide_operands: - with self.subTest(op=op, slot=0, arg=bad): - with self.assertRaises(rdna2spirv.Unsupported): - _run_insn_line(f"{op} {bad}, s5") - with self.subTest(op=op, slot=1, arg=bad): - with self.assertRaises(rdna2spirv.Unsupported): - _run_insn_line(f"{op} s4, {bad}") - - def test_width_mismatch_rejected_64bit_cmp(self): - bad_64 = ["s0", "s[0:3]", "vcc_lo", "vcc_hi", "exec_lo", "exec_hi", "m0", "scc", "src_scc", "1.0"] - for op in ALL_CMP64: - for bad in bad_64: - with self.subTest(op=op, slot=0, arg=bad): - with self.assertRaises(rdna2spirv.Unsupported): - _run_insn_line(f"{op} {bad}, s[6:7]") - with self.subTest(op=op, slot=1, arg=bad): - with self.assertRaises(rdna2spirv.Unsupported): - _run_insn_line(f"{op} s[4:5], {bad}") - - def test_width_mismatch_rejected_64bit_bitcmp(self): - bad_src0 = ["s0", "s[0:3]", "vcc_lo", "vcc_hi", "exec_lo", "exec_hi", "m0", "scc", "src_scc", "1.0"] - bad_src1 = ["s[0:1]", "s[0:3]", "vcc", "exec"] - for op in ("s_bitcmp0_b64", "s_bitcmp1_b64"): - for bad in bad_src0: - with self.subTest(op=op, slot=0, arg=bad): - with self.assertRaises(rdna2spirv.Unsupported): - _run_insn_line(f"{op} {bad}, 5") - for bad in bad_src1: - with self.subTest(op=op, slot=1, arg=bad): - with self.assertRaises(rdna2spirv.Unsupported): - _run_insn_line(f"{op} s[4:5], {bad}") - - -class TestSopcPositiveControls(unittest.TestCase): - def test_all_18_ops_and_valid_scalar_operands_spirv_val_and_interp(self): - asm: list[str] = [ - "s_mov_b32 m0, 0x00000005", - "s_mov_b32 s8, -1", - "s_mov_b32 s9, 0x3f800000", # 1.0f bits (bit 29 is 1, bit 30 is 0) - "s_mov_b32 s10, 0xbf800000", # -1.0f bits - "s_mov_b32 s12, 0x00000010", # bit 4 set - "s_mov_b32 s13, 0x00000100", # bit 40 set in s[12:13] - "s_mov_b32 vcc_lo, s12", - "s_mov_b32 vcc_hi, s13", - ] - expected: list[tuple[str, int]] = [] - - def add_case(label: str, insn: str, want: int): - slot = len(expected) - asm.append(insn) - asm.extend(_store_scc(slot)) - expected.append((label, want)) - - # 12 32-bit scalar compares covering sgpr, null, m0, vcc_lo/hi, exec_lo/hi, scc/src_scc, - # plain negative integer immediates, positive immediates, and float immediates. - add_case("s_cmp_eq_i32 sgpr/neg_imm", "s_cmp_eq_i32 s8, -1", 1) - add_case("s_cmp_lg_i32 sgpr/neg_imm", "s_cmp_lg_i32 s8, -16", 1) - add_case("s_cmp_gt_i32 null/neg_imm", "s_cmp_gt_i32 null, -1", 1) - add_case("s_cmp_ge_i32 m0/imm", "s_cmp_ge_i32 m0, 5", 1) - add_case("s_cmp_lt_i32 neg_imm/null", "s_cmp_lt_i32 -1, null", 1) - add_case("s_cmp_le_i32 scc/imm", "s_cmp_le_i32 scc, 1", 1) - add_case("s_cmp_eq_u32 sgpr/fimm", "s_cmp_eq_u32 s9, 1.0", 1) - add_case("s_cmp_eq_u32 sgpr/neg_fimm", "s_cmp_eq_u32 s10, -1.0", 1) - add_case("s_cmp_lg_u32 vcc_lo/null", "s_cmp_lg_u32 vcc_lo, null", 1) - add_case("s_cmp_gt_u32 vcc_hi/m0", "s_cmp_gt_u32 vcc_hi, m0", 1) - add_case("s_cmp_ge_u32 exec_lo/exec_hi", "s_cmp_ge_u32 exec_lo, exec_hi", 1) - add_case("s_cmp_lt_u32 src_scc/m0", "s_cmp_lt_u32 src_scc, m0", 1) - add_case("s_cmp_le_u32 m0/vcc_lo", "s_cmp_le_u32 m0, vcc_lo", 1) - - # 2 64-bit scalar compares covering s[a:b], vcc, exec, null, 0, -1, hex imm. - add_case("s_cmp_eq_u64 pair/vcc", "s_cmp_eq_u64 s[12:13], vcc", 1) - add_case("s_cmp_lg_u64 pair/null", "s_cmp_lg_u64 s[12:13], null", 1) - add_case("s_cmp_eq_u64 null/0", "s_cmp_eq_u64 null, 0", 1) - add_case("s_cmp_eq_u64 exec/-1", "s_cmp_eq_u64 exec, -1", 1) - add_case("s_cmp_lg_u64 exec/0", "s_cmp_lg_u64 exec, 0", 1) - - # 4 bit-test ops covering b32 and b64 with valid scalar operands. - add_case("s_bitcmp1_b32 s12/4", "s_bitcmp1_b32 s12, 4", 1) - add_case("s_bitcmp0_b32 m0/1", "s_bitcmp0_b32 m0, 1", 1) - add_case("s_bitcmp1_b32 fimm/29", "s_bitcmp1_b32 1.0, 29", 1) - add_case("s_bitcmp0_b32 fimm/30", "s_bitcmp0_b32 1.0, 30", 1) - add_case("s_bitcmp0_b32 null/0", "s_bitcmp0_b32 null, 0", 1) - add_case("s_bitcmp1_b32 exec_lo/0", "s_bitcmp1_b32 exec_lo, 0", 1) - add_case("s_bitcmp1_b64 pair/40", "s_bitcmp1_b64 s[12:13], 40", 1) - add_case("s_bitcmp0_b64 pair/41", "s_bitcmp0_b64 s[12:13], 41", 1) - add_case("s_bitcmp1_b64 vcc/40", "s_bitcmp1_b64 vcc, 40", 1) - add_case("s_bitcmp1_b64 exec/63", "s_bitcmp1_b64 exec, 63", 1) - add_case("s_bitcmp0_b64 null/35", "s_bitcmp0_b64 null, 35", 1) - add_case("s_bitcmp1_b64 neg_imm/63", "s_bitcmp1_b64 -1, 63", 1) - add_case("s_bitcmp1_b64 pair/m0", "s_bitcmp1_b64 s[12:13], m0", 0) - - asm.append("s_endpgm") - spv = _translate_and_validate_cs("cs_sopc_pos", asm, threads=64) - mem = si.run_workgroup( - spv, 64, 64, - inputs_for=lambda i: {"%wg_id": (0, 0, 0), "%local_id": (i, 0, 0), "%sg_lane": i}, - push_constants=VSHARP + [0] * 28, - memory={}, - ) - for slot, (label, want) in enumerate(expected): - with self.subTest(case=label): - self.assertEqual(mem[slot * 4], want, label) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_sopp_noops.py b/tests/semantic/test_sopp_noops.py deleted file mode 100644 index 7ad87b800..000000000 --- a/tests/semantic/test_sopp_noops.py +++ /dev/null @@ -1,90 +0,0 @@ -"""Semantic interpreter tests for the GFX10 instructions translated as nothing. - -s_icache_inv (instruction-cache invalidate), s_ttracedata / s_ttracedata_imm (thread-trace data), s_code_end (end of -code padding), s_version (ISA version marker), ds_nop (the DS no-operation), v_clrexcp (clears TRAPSTS exception -bits, which nothing translated reads), s_atc_probe / s_atc_probe_buffer (an address-translation-cache prefetch) and -s_incperflevel / s_decperflevel (performance-counter step) / s_wakeup (early wake of s_sleep waves) have no register, memory, SCC, VCC or EXEC effect, so the translator -emits nothing for them, as for s_nop or v_nop. Each case translates a synthetic pixel shader with -tools/rdna2spirv.py, runs it in tests/semantic/spirv_mini_interp.py and checks that values, SCC and VCC set before the -instruction come out unchanged, and that the program behaves as without it. The data-cache invalidations -(buffer_gl0_inv, buffer_gl1_inv, s_dcache_inv, s_gl1_inv) are about coherence between waves and stay Unsupported. -""" -import os -import struct -import sys -import tempfile -import unittest -import warnings - -HERE = os.path.dirname(os.path.abspath(__file__)) -ROOT = os.path.dirname(os.path.dirname(HERE)) -TOOLS_DIR = os.environ.get("LEONIDA_TOOLS_DIR") or os.path.join(ROOT, "tools") - -sys.dont_write_bytecode = True -sys.path.insert(0, TOOLS_DIR) -sys.path.insert(0, HERE) - -import rdna2spirv # noqa: E402 -import spirv_mini_interp as si # noqa: E402 - -STUB_DXBC = b"DXBC" + bytes(24) + struct.pack(" str: - if _TMP_DIR is None: - setUpModule() - asm = "; test_sopp_noops\n" + "".join(f"\t{ln}\n" for ln in lines) + "\texp mrt0 v0, v1, v2, v3 done vm\n\ts_endpgm\n" - with open(_SRC_PATH, "w", encoding="utf-8") as f: - f.write(asm) - with warnings.catch_warnings(): - warnings.simplefilter("ignore", ResourceWarning) - return rdna2spirv.translate(_SRC_PATH) - - -class SoppNoopTests(unittest.TestCase): - def test_each_leaves_values_scc_and_vcc_alone(self): - for line in NOOP_LINES: - with self.subTest(line=line): - out = si.run_fragment(translate(PROLOGUE + [line] + EPILOGUE))["%out_mrt0"] - self.assertEqual(out, (0x40000001, 0x40000002, 0x40000003, 0x40000004)) - - def test_same_outputs_as_without_them(self): - without = si.run_fragment(translate(PROLOGUE + EPILOGUE)) - self.assertEqual(si.run_fragment(translate(PROLOGUE + NOOP_LINES + EPILOGUE)), without) - - def test_data_cache_invalidations_stay_unsupported(self): - for line in ("buffer_gl0_inv", "buffer_gl1_inv", "s_dcache_inv", "s_gl1_inv"): - with self.subTest(line=line): - with self.assertRaises(rdna2spirv.Unsupported): - translate(PROLOGUE + [line] + EPILOGUE) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_sparse_sv_target.py b/tests/semantic/test_sparse_sv_target.py deleted file mode 100644 index 9d29c7f63..000000000 --- a/tests/semantic/test_sparse_sv_target.py +++ /dev/null @@ -1,85 +0,0 @@ -"""A pixel shader's colour exports are packed: exp mrtK writes the K-th declared SV_Target, not render target K. - -A pixel shader that declares SV_Target0 and SV_Target2 exports mrt0 and mrt1 (SHADER-210: all 221 such pixel shaders -of the 1.0.2.1 corpus, docs/design.md "Pixel colour exports"). The translator used to decorate mrt1 with Location 1, -so the second value went to render target 1. It now maps export K to the K-th SV_Target of the shader's OSG1. -Hand-built OSG1 containers and listings, no game data. - - python -I tests/semantic/test_sparse_sv_target.py -v -""" -import os -import re -import struct -import sys -import unittest - -HERE = os.path.dirname(os.path.abspath(__file__)) -if HERE not in sys.path: - sys.path.insert(0, HERE) - -import support # noqa: E402 -from support import rdna2spirv # noqa: E402 - -D3D_NAME_TARGET = 64 - - -def osg1_dxbc(targets): - """Synthetic DXBC container with one OSG1 chunk declaring SV_Target (float4, register n) for each n.""" - payload = bytearray(struct.pack(" None: - for width, text in ((32, self.FRAGMENT), (64, self.WIDE_SELECTOR)): - with self.subTest(width=width): - self.assertEqual(run_wave(text)["outputs"], [{"%color": (10,)}] * 32) - - def test_constant_null_selector_still_matches_zero(self) -> None: - text = self.FRAGMENT.replace("OpSwitch %selector %default -1", "OpSwitch %zero %default 0") - self.assertEqual(run_wave(text)["outputs"], [{"%color": (10,)}] * 32) - - -class LoopConvergence(unittest.TestCase): - # Lane L runs (L & 3) + 1 iterations. Each iteration adds the number of lanes still in the loop, so with - # 32 lanes: iteration 0 has 32, 1 has 24 (L & 3 >= 1), 2 has 16, 3 has 8. - BODY = """OpBranch %head -%head = OpLabel -%i = OpPhi %uint %c0 %entry %inext %cont -%acc = OpPhi %uint %c0 %entry %accn %cont -OpLoopMerge %end %cont None -OpBranch %body -%body = OpLabel -%bal = OpGroupNonUniformBallot %v4uint %c3 %true -%n = OpGroupNonUniformBallotBitCount %uint %c3 Reduce %bal -%accn = OpIAdd %uint %acc %n -%inext = OpIAdd %uint %i %c1 -%lim = OpBitwiseAnd %uint %l %c3 -%go = OpULessThanEqual %bool %inext %lim -OpBranchConditional %go %cont %end -%cont = OpLabel -OpBranch %head -%end = OpLabel -%after = OpGroupNonUniformBallot %v4uint %c3 %true -%all = OpCompositeExtract %uint %after 0 -%v = OpCompositeConstruct %v4uint %accn %inext %all %l -OpStore %out %v -""" - - def test_lanes_leave_the_loop_one_by_one(self): - expect = {0: 32, 1: 32 + 24, 2: 32 + 24 + 16, 3: 32 + 24 + 16 + 8} - got = outs(self.BODY, 32) - for lane in range(32): - self.assertEqual(got[lane], (expect[lane & 3], (lane & 3) + 1, 0xFFFFFFFF, lane)) - - -class Kill(unittest.TestCase): - BODY = """%hi = OpUGreaterThanEqual %bool %l %c16 -OpSelectionMerge %merge None -OpBranchConditional %hi %dead %merge -%dead = OpLabel -OpKill -%merge = OpLabel -%b = OpGroupNonUniformBallot %v4uint %c3 %true -%x = OpCompositeExtract %uint %b 0 -%v = OpCompositeConstruct %v4uint %x %l %c0 %c0 -OpStore %out %v -""" - - def test_killed_lanes_write_nothing_and_leave_the_subgroup(self): - got = outs(self.BODY, 32) - for lane in range(32): - self.assertEqual(got[lane], (0xFFFF, lane, 0, 0) if lane < 16 else None) - - -class UndefinedValues(unittest.TestCase): - def test_discarded_shift_by_width_is_fine(self): - body = """%s = OpShiftLeftLogical %uint %c1 %c32 -%m = OpISub %uint %s %c1 -%sel = OpSelect %uint %false %m %c3 -%v = OpCompositeConstruct %v4uint %sel %c0 %c0 %c0 -OpStore %out %v -""" - self.assertEqual(outs(body)[5], (3, 0, 0, 0)) - - def test_branch_on_undefined_value_raises(self): - body = """%s = OpShiftLeftLogical %uint %c1 %c32 -%z = OpIEqual %bool %s %c0 -OpSelectionMerge %merge None -OpBranchConditional %z %merge %merge -%merge = OpLabel -""" - with self.assertRaises(UnsupportedConstruct): - outs(body) - - def test_undefined_value_in_an_output_raises(self): - body = """%s = OpShiftLeftLogical %uint %c1 %c32 -%v = OpCompositeConstruct %v4uint %s %c0 %c0 %c0 -OpStore %out %v -""" - with self.assertRaises(UnsupportedConstruct): - outs(body) - - -class WideIntegers(unittest.TestCase): - """OpBitCount and the GLSL.std.450 signed integer operations on a 64-bit type.""" - HEAD64 = (HEAD.replace("OpMemoryModel", '%glsl = OpExtInstImport "GLSL.std.450"\nOpMemoryModel') - .replace("%c0 = OpConstant %uint 0", - "%ulong = OpTypeInt 64 0\n" - "%cl_1 = OpConstant %ulong 1\n" - "%cl_2p31 = OpConstant %ulong 2147483648\n" - "%cl_2p32 = OpConstant %ulong 4294967296\n" - "%cl_2p32_5 = OpConstant %ulong 4294967301\n" - "%cl_hi = OpConstant %ulong 18446744069414584320\n" # 0xFFFFFFFF00000000 = -2**32 - "%cl_m1 = OpConstant %ulong 18446744073709551615\n" - "%c0 = OpConstant %uint 0")) - - def lane0(self, body): - return run_wave(self.HEAD64 + body + "%v = OpCompositeConstruct %v4uint %res %c0 %c0 %c0\n" - "OpStore %out %v\n" + TAIL, wave=32)["outputs"][0]["%out"][0] - - def test_bit_count_counts_every_bit_of_a_64bit_operand(self): - for src, want in (("%cl_hi", 32), ("%cl_m1", 64), ("%cl_2p32_5", 3), ("%cl_1", 1), ("%c3", 2)): - with self.subTest(src=src): - self.assertEqual(self.lane0(f"%res = OpBitCount %uint {src}\n"), want) - - def test_signed_min_max_clamp_abs_use_the_width_of_a_64bit_type(self): - # 2**31 is positive in a 64-bit integer and 0xFFFFFFFF00000000 is -2**32; a 32-bit reading takes them - # as -2**31 and 0. - for inst, want in (("SMin %cl_2p31 %cl_1", "%cl_1"), ("SMax %cl_2p31 %cl_1", "%cl_2p31"), - ("SMin %cl_hi %cl_1", "%cl_hi"), ("SMax %cl_hi %cl_m1", "%cl_m1"), - ("SClamp %cl_2p31 %cl_1 %cl_2p32", "%cl_2p31"), ("SClamp %cl_hi %cl_m1 %cl_1", "%cl_m1"), - ("SAbs %cl_hi", "%cl_2p32"), ("SAbs %cl_2p32_5", "%cl_2p32_5"), ("SAbs %cl_m1", "%cl_1")): - with self.subTest(inst=inst): - self.assertEqual(self.lane0(f"%r = OpExtInst %ulong %glsl {inst}\n" - f"%eq = OpIEqual %bool %r {want}\n" - "%res = OpSelect %uint %eq %c1 %c0\n"), 1) - - def test_32bit_signed_operations_are_unchanged(self): - self.assertEqual(self.lane0("%m1 = OpISub %uint %c0 %c1\n%res = OpExtInst %uint %glsl SMin %m1 %c1\n"), - 0xFFFFFFFF) - self.assertEqual(self.lane0("%m1 = OpISub %uint %c0 %c1\n%res = OpExtInst %uint %glsl SAbs %m1\n"), 1) - self.assertEqual(self.lane0("%res = OpExtInst %uint %glsl FindUMsb %c8\n"), 3) - - def test_glsl_integer_operations_reject_mixed_component_widths(self): - for inst in ("SAbs %cl_1", "SMin %c0 %cl_1", "SMax %cl_1 %c0", - "SClamp %c0 %c0 %cl_1", "FindILsb %cl_1", "FindSMsb %cl_1", "FindUMsb %cl_1"): - with self.subTest(inst=inst): - body = f"%res = OpExtInst %uint %glsl {inst}\n" - with self.assertRaisesRegex(UnsupportedConstruct, "64-bit.*32-bit"): - self.lane0(body) - - def test_find_bit_of_a_64bit_operand_is_rejected(self): - # GLSL.std.450 limits FindILsb, FindSMsb and FindUMsb to 32-bit components. - for name in ("FindILsb", "FindSMsb", "FindUMsb"): - with self.subTest(name=name): - with self.assertRaisesRegex(UnsupportedConstruct, "64-bit"): - self.lane0(f"%r = OpExtInst %ulong %glsl {name} %cl_2p32\n%res = OpUConvert %uint %r\n") - - -class Strictness(unittest.TestCase): - def test_float_arithmetic_is_rejected(self): - body = """%f = OpBitcast %uint %c1 -%g = OpFAdd %uint %f %f -""" - with self.assertRaises(UnsupportedConstruct): - outs(body) - - def test_split_without_merge_is_rejected(self): - body = """%lt = OpULessThan %bool %l %c8 -OpBranchConditional %lt %a %b -%a = OpLabel -OpReturn -%b = OpLabel -""" - with self.assertRaises(UnsupportedConstruct): - outs(body) - - - - -class WaveInterpExtensions(unittest.TestCase): - def test_location_inputs_float_ops_and_convert(self): - mod = """OpCapability Shader -OpMemoryModel Logical GLSL450 -OpEntryPoint Fragment %main "main" %out %in0 %l -OpDecorate %out Location 0 -OpDecorate %in0 Location 0 -OpDecorate %l BuiltIn SubgroupLocalInvocationId -%void = OpTypeVoid -%fn = OpTypeFunction %void -%uint = OpTypeInt 32 0 -%float = OpTypeFloat 32 -%v4float = OpTypeVector %float 4 -%v4uint = OpTypeVector %uint 4 -%_ptr_Output = OpTypePointer Output %v4uint -%_ptr_Input = OpTypePointer Input %v4float -%_ptr_Input_f = OpTypePointer Input %float -%_ptr_Builtin = OpTypePointer Input %uint -%out = OpVariable %_ptr_Output Output -%in0 = OpVariable %_ptr_Input Input -%l = OpVariable %_ptr_Builtin Input -%c0 = OpConstant %uint 0 -%c1 = OpConstant %uint 1 -%f64 = OpConstant %float 64.0 -%main = OpFunction %void None %fn -%entry = OpLabel -%px = OpAccessChain %_ptr_Input_f %in0 %c0 -%py = OpAccessChain %_ptr_Input_f %in0 %c1 -%fx = OpLoad %float %px -%fy = OpLoad %float %py -%sx = OpFMul %float %fx %f64 -%sy = OpFMul %float %fy %f64 -%ux = OpConvertFToU %uint %sx -%uy = OpConvertFToU %uint %sy -%sum = OpFAdd %float %fx %fy -%us = OpConvertFToU %uint %sum -%v = OpCompositeConstruct %v4uint %ux %uy %us %c0 -OpStore %out %v -OpReturn -OpFunctionEnd -""" - res = run_wave(mod, wave=32, inputs={0: lambda lane: ((lane + 0.5) / 64.0, 1.5 / 64.0, 0.0, 0.0)}) - for lane in range(32): - self.assertEqual(res["outputs"][lane]["%out"], (lane, 1, 0, 0)) - - def test_physical_storage_buffer_atomic_and_store(self): - mod = """OpCapability Shader -OpCapability Int64 -OpCapability PhysicalStorageBufferAddresses -OpMemoryModel PhysicalStorageBuffer64 GLSL450 -OpEntryPoint GLCompute %main "main" %out %l -OpDecorate %out Location 0 -OpDecorate %l BuiltIn SubgroupLocalInvocationId -OpDecorate %arr ArrayStride 4 -%void = OpTypeVoid -%fn = OpTypeFunction %void -%uint = OpTypeInt 32 0 -%ulong = OpTypeInt 64 0 -%v4uint = OpTypeVector %uint 4 -%arr = OpTypeRuntimeArray %uint -%_ptr_Output = OpTypePointer Output %v4uint -%_ptr_Builtin = OpTypePointer Input %uint -%_ptr_PSB_arr = OpTypePointer PhysicalStorageBuffer %arr -%_ptr_PSB_u = OpTypePointer PhysicalStorageBuffer %uint -%out = OpVariable %_ptr_Output Output -%l = OpVariable %_ptr_Builtin Input -%c0 = OpConstant %uint 0 -%c1 = OpConstant %uint 1 -%c0_64 = OpConstant %ulong 0 -%c64_64 = OpConstant %ulong 64 -%c4_64 = OpConstant %ulong 4 -%main = OpFunction %void None %fn -%entry = OpLabel -%lane = OpLoad %uint %l -%base = OpConvertUToPtr %_ptr_PSB_arr %c0_64 -%p0 = OpAccessChain %_ptr_PSB_u %base %c0 -%slot = OpAtomicIAdd %uint %p0 %c1 %c0 %c1 -%slot64 = OpUConvert %ulong %slot -%off = OpIMul %ulong %slot64 %c4_64 -%addr = OpIAdd %ulong %c64_64 %off -%sptr_arr = OpConvertUToPtr %_ptr_PSB_arr %addr -%sptr = OpAccessChain %_ptr_PSB_u %sptr_arr %c0 -OpStore %sptr %lane Aligned 4 -%v = OpCompositeConstruct %v4uint %slot %c0 %c0 %c0 -OpStore %out %v -OpReturn -OpFunctionEnd -""" - mem = {0: 0} - res = run_wave(mod, wave=32, memory=mem) - self.assertEqual(mem[0], 32) - self.assertEqual({mem[64 + 4 * i] for i in range(32)}, set(range(32))) - - def test_quad_swap_and_broadcast(self): - mod = """OpCapability Shader -OpCapability GroupNonUniformQuad -OpMemoryModel Logical GLSL450 -OpEntryPoint Fragment %main "main" %out %l -OpDecorate %out Location 0 -OpDecorate %l BuiltIn SubgroupLocalInvocationId -%void = OpTypeVoid -%fn = OpTypeFunction %void -%uint = OpTypeInt 32 0 -%v4uint = OpTypeVector %uint 4 -%_ptr_Output = OpTypePointer Output %v4uint -%_ptr_Builtin = OpTypePointer Input %uint -%out = OpVariable %_ptr_Output Output -%l = OpVariable %_ptr_Builtin Input -%c0 = OpConstant %uint 0 -%c1 = OpConstant %uint 1 -%c2 = OpConstant %uint 2 -%c3 = OpConstant %uint 3 -%main = OpFunction %void None %fn -%entry = OpLabel -%lane = OpLoad %uint %l -%sh = OpGroupNonUniformQuadSwap %uint %c3 %lane %c0 -%sv = OpGroupNonUniformQuadSwap %uint %c3 %lane %c1 -%sd = OpGroupNonUniformQuadSwap %uint %c3 %lane %c2 -%sb = OpGroupNonUniformQuadBroadcast %uint %c3 %lane %c0 -%v = OpCompositeConstruct %v4uint %sh %sv %sd %sb -OpStore %out %v -OpReturn -OpFunctionEnd -""" - res = run_wave(mod, wave=32) - for lane in range(32): - self.assertEqual(res["outputs"][lane]["%out"], (lane ^ 1, lane ^ 2, lane ^ 3, lane & ~3)) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_store_liveins.py b/tests/semantic/test_store_liveins.py deleted file mode 100644 index e5aed90bb..000000000 --- a/tests/semantic/test_store_liveins.py +++ /dev/null @@ -1,29 +0,0 @@ -"""Store operands in the register analysis used by production translation.""" -from pathlib import Path -import unittest - -from support import mrt0_words, rdna2spirv, translate_lines -from shader_ir import parse_line - - -class StoreLiveIns(unittest.TestCase): - def test_address_and_payload_are_sources(self): - for op, reads in (("flat_store_dwordx2 v[0:1], v[4:5]", {0, 1, 4, 5}), - ("scratch_store_dwordx2 v0, v[4:5], off", {0, 4, 5})): - with self.subTest(op=op): - ins = parse_line(op) - self.assertEqual(rdna2spirv.reg_reads_writes([ins]), (reads, set())) - self.assertEqual(rdna2spirv.read_before_write_vgprs([ins]), reads) - - def test_branch_exports_live_barycentrics(self): - fixture = Path(__file__).parent / "fixtures" / "ps_flat_store_livein.asm" - program = fixture.read_text(encoding="ascii").splitlines() - # gfx1013 llvm-mc -show-encoding. The taken branch skips END and an eight-byte store. - scratch = ("scratch_store_dword v0, v4, off ; encoding: " - "[0x00,0x40,0x70,0xdc,0x00,0x04,0x7d,0x00]") - for store in (program[4], scratch): - with self.subTest(store=store): - lines = program[:4] + [store] + program[5:] - spv = translate_lines("ps_store_livein", lines) - self.assertEqual(mrt0_words(spv, inputs={"%bary": (0.125, 0.25, 0.625)}), - [0x3e800000, 0x3f200000] * 2) diff --git a/tests/semantic/test_tbuffer_load_format.py b/tests/semantic/test_tbuffer_load_format.py deleted file mode 100644 index 6ec84e8a4..000000000 --- a/tests/semantic/test_tbuffer_load_format.py +++ /dev/null @@ -1,243 +0,0 @@ -"""Semantic interpreter tests for 32-bit (non-d16) tbuffer_load_format_{x,xy,xyz,xyzw}. - -Covers: -- All 4 component widths (x, xy, xyz, xyzw) with 32_32_32_32_FLOAT and 16_16_16_16_FLOAT, - verifying that unloaded trailing VGPRs retain their pre-loaded sentinel values. -- Normalized and integer formats: 8_8_8_8_UNORM, 8_8_8_8_SNORM (with negatives), - 16_16_16_16_UINT, and 16_16_16_16_SINT (with negatives). -- Precedence of the MTBUF format:[BUF_FMT_...] modifier (and identity DST_SEL) over - an incompatible V# FORMAT / DST_SEL. -- Out-of-bounds behavior on num_records (returns 0 without touching trailing VGPRs). -- In-memory negative controls on the translated SPIR-V text. -""" -from __future__ import annotations - -import os -import re -import struct -import sys -import unittest - -sys.dont_write_bytecode = True - -HERE = os.path.dirname(os.path.abspath(__file__)) -ROOT = os.path.dirname(os.path.dirname(HERE)) -TOOLS_DIR = os.environ.get("LEONIDA_TOOLS_DIR") or os.path.join(ROOT, "tools") - -sys.path.insert(0, TOOLS_DIR) -sys.path.insert(0, HERE) - -import spirv_mini_interp # noqa: E402 -import support # noqa: E402 - - -def fssm(rsrc2: int, group: tuple[int, int, int]) -> bytes: - """Build the compute-shader FSSM header (COMPUTE_PGM_RSRC2 and thread-group size).""" - header = bytearray(0x148) - struct.pack_into("<4I", header, 0x138, rsrc2, *group) - return bytes(header) - - -# 4 user SGPRs (s[0:3] output V#), workgroup id in s4, 64x1x1 threads. -CS_FSSM = fssm(0x8088, (64, 1, 1)) -# Output V# passed via push constants in s[0:3]: base 0, num_records 0xffffffff, 32_FLOAT, OOB_SELECT 3. -OUT_VSHARP = [0, 0, 0xFFFFFFFF, 0x31016FAC] - -IN_BASE = 0x1000 -OUT_BASE = 0x200 -SENTINELS = (0xAAAAAAAA, 0xBBBBBBBB, 0xCCCCCCCC, 0xDDDDDDDD) - -# V# word3 fields (bits 0..11 DST_SEL, bits 12..18 FORMAT, bits 28..29 OOB_SELECT). -DST_SEL_XYZW = 4 | (5 << 3) | (6 << 6) | (7 << 9) -DST_SEL_ZERO_ONE = 0 | (0 << 3) | (1 << 6) | (1 << 9) -FMT_U32 = 20 -FMT_UINT8X4 = 60 -FMT_U32X4 = 75 - - -def f32_bits(val: float) -> int: - return struct.unpack(" int: - return struct.unpack(" str: - return "v2" if ncomp == 1 else f"v[2:{1 + ncomp}]" - - -def build_tbuffer_load_spv( - ncomp: int, - fmt_mod: str, - *, - offset: int = 0, - num_records: int = 0x100, - vsharp_word3: int = (FMT_U32 << 12) | DST_SEL_XYZW | 0x30000000, -) -> str: - """Translate a compute shader that pre-loads v[2:5] with sentinels, runs tbuffer_load_format_*, - and stores v[2:5] to OUT_BASE.""" - suffix = "xyzw"[:ncomp] - vdst = vdst_for_width(ncomp) - mod_str = f" format:[{fmt_mod}]" if fmt_mod else "" - lines = [ - f"s_mov_b32 s8, {IN_BASE:#x}", - "s_mov_b32 s9, 0", - f"s_mov_b32 s10, {num_records:#x}", - f"s_mov_b32 s11, {vsharp_word3:#x}", - *(f"v_mov_b32 v{2 + i}, {val:#x}" for i, val in enumerate(SENTINELS)), - f"v_mov_b32 v1, {offset:#x}", - f"tbuffer_load_format_{suffix} {vdst}, v1, s[8:11], 0{mod_str} offen", - "s_waitcnt vmcnt(0)", - f"v_mov_b32 v0, {OUT_BASE:#x}", - "buffer_store_dwordx4 v[2:5], v0, s[0:3], 0 offen", - "s_endpgm", - ] - return support.translate_lines(f"cs_tbuf_load_{suffix}", lines, fssm=CS_FSSM) - - -def run_spv(spv: str, memory: dict[int, int]) -> list[int]: - mem = dict(memory) - outputs = spirv_mini_interp.run_fragment( - spv, - inputs={"%wg_id": (0, 0, 0), "%local_id": (0, 0, 0)}, - push_constants=OUT_VSHARP + [0] * 28, - memory=mem, - ) - if outputs: - raise AssertionError(f"unexpected shader outputs: {outputs}") - return [mem.get(OUT_BASE + 4 * i, 0) for i in range(4)] - - -class TbufferLoadWidthsFloatTests(unittest.TestCase): - def test_f32x4_all_widths_preserve_trailing_vgprs(self): - vals = (1.5, -2.25, 0.125, 42.0) - words = [f32_bits(v) for v in vals] - mem = {IN_BASE + 4 * i: w for i, w in enumerate(words)} - for ncomp in (1, 2, 3, 4): - with self.subTest(ncomp=ncomp): - spv = build_tbuffer_load_spv(ncomp, "BUF_FMT_32_32_32_32_FLOAT") - got = run_spv(spv, mem) - want = words[:ncomp] + list(SENTINELS[ncomp:]) - self.assertEqual(got, want) - - def test_f16x4_all_widths_preserve_trailing_vgprs(self): - vals = (1.0, -0.5, 3.5, -16.0) - halves = [f16_bits(v) for v in vals] - mem = { - IN_BASE: halves[0] | (halves[1] << 16), - IN_BASE + 4: halves[2] | (halves[3] << 16), - } - expected = [f32_bits(v) for v in vals] - for ncomp in (1, 2, 3, 4): - with self.subTest(ncomp=ncomp): - spv = build_tbuffer_load_spv(ncomp, "BUF_FMT_16_16_16_16_FLOAT") - got = run_spv(spv, mem) - want = expected[:ncomp] + list(SENTINELS[ncomp:]) - self.assertEqual(got, want) - - -class TbufferLoadNormAndIntTests(unittest.TestCase): - def test_unorm8x4(self): - # 0x00 -> 0.0, 0x33 -> 51/255 = 0.2, 0xCC -> 204/255 = 0.8, 0xFF -> 1.0 - packed = 0x00 | (0x33 << 8) | (0xCC << 16) | (0xFF << 24) - mem = {IN_BASE: packed} - spv = build_tbuffer_load_spv(4, "BUF_FMT_8_8_8_8_UNORM") - got = run_spv(spv, mem) - want = [f32_bits(0.0), f32_bits(51.0 / 255.0), f32_bits(204.0 / 255.0), f32_bits(1.0)] - self.assertEqual(got, want) - - def test_snorm8x4_with_negatives(self): - # 0x80 (-128) -> -1.0, 0x81 (-127) -> -1.0, 0xC0 (-64) -> -64/127, 0x7F (127) -> 1.0 - packed = 0x80 | (0x81 << 8) | (0xC0 << 16) | (0x7F << 24) - mem = {IN_BASE: packed} - spv = build_tbuffer_load_spv(4, "BUF_FMT_8_8_8_8_SNORM") - got = run_spv(spv, mem) - want = [f32_bits(-1.0), f32_bits(-1.0), f32_bits(-64.0 / 127.0), f32_bits(1.0)] - self.assertEqual(got, want) - - def test_uint16x4(self): - mem = { - IN_BASE: 0x0000 | (0x0001 << 16), - IN_BASE + 4: 0x7FFF | (0xFFFF << 16), - } - spv = build_tbuffer_load_spv(4, "BUF_FMT_16_16_16_16_UINT") - got = run_spv(spv, mem) - self.assertEqual(got, [0x00000000, 0x00000001, 0x00007FFF, 0x0000FFFF]) - - def test_sint16x4_with_negatives(self): - mem = { - IN_BASE: 0x8000 | (0xFFFF << 16), - IN_BASE + 4: 0x0000 | (0x7FFF << 16), - } - spv = build_tbuffer_load_spv(4, "BUF_FMT_16_16_16_16_SINT") - got = run_spv(spv, mem) - self.assertEqual(got, [0xFFFF8000, 0xFFFFFFFF, 0x00000000, 0x00007FFF]) - - -class TbufferPrecedenceAndOobTests(unittest.TestCase): - def test_modifier_overrides_incompatible_vsharp_format_and_dst_sel(self): - # V# has incompatible FORMAT (FMT_U32X4) and non-identity DST_SEL (0, 0, 1, 1). - # MTBUF instruction format:[BUF_FMT_16_16_16_16_SINT] and identity XYZW must win. - mem = { - IN_BASE: 0xFFF0 | (0x0002 << 16), - IN_BASE + 4: 0xFFFE | (0x1234 << 16), - } - incompatible_w3 = (FMT_U32X4 << 12) | DST_SEL_ZERO_ONE | 0x30000000 - spv = build_tbuffer_load_spv(4, "BUF_FMT_16_16_16_16_SINT", vsharp_word3=incompatible_w3) - got = run_spv(spv, mem) - self.assertEqual(got, [0xFFFFFFF0, 0x00000002, 0xFFFFFFFE, 0x00001234]) - - def test_out_of_bounds_returns_zero_and_preserves_trailing_vgpr(self): - mem = {IN_BASE + 4 * i: 0x12345670 + i for i in range(4)} - # num_records = 16 bytes; offset = 16 is OOB, and offset = 4 with 16-byte element straddles OOB. - for offset in (16, 4): - with self.subTest(offset=offset): - spv = build_tbuffer_load_spv( - 3, "BUF_FMT_32_32_32_32_FLOAT", offset=offset, num_records=16 - ) - got = run_spv(spv, mem) - self.assertEqual(got, [0, 0, 0, SENTINELS[3]]) - - -class TbufferNegativeControlsTests(unittest.TestCase): - def test_mutated_swizzle_selector_breaks_result(self): - mem = { - IN_BASE: 0x11111111, - IN_BASE + 4: 0x22222222, - IN_BASE + 8: 0x33333333, - IN_BASE + 12: 0x44444444, - } - spv = build_tbuffer_load_spv(4, "BUF_FMT_32_32_32_32_FLOAT") - self.assertEqual(run_spv(spv, mem), [0x11111111, 0x22222222, 0x33333333, 0x44444444]) - - # Mutate the DST_SEL selector check for code 5 (Y) so it matches code 4 (X) instead. - mutated, count = re.subn( - r"(OpIEqual %bool %\S+ )%c5\b", - r"\1%c4", - spv, - ) - self.assertGreater(count, 0, "expected DST_SEL selector comparison against %c5 in SPIR-V") - got_mutated = run_spv(mutated, mem) - self.assertNotEqual(got_mutated, [0x11111111, 0x22222222, 0x33333333, 0x44444444]) - - def test_mutated_oob_guard_breaks_oob_zero_result(self): - mem = {IN_BASE + 4 * i: f32_bits(float(i + 1)) for i in range(4)} - spv = build_tbuffer_load_spv( - 4, "BUF_FMT_32_32_32_32_FLOAT", offset=16, num_records=16 - ) - self.assertEqual(run_spv(spv, mem), [0, 0, 0, 0]) - - # Mutate the final OOB OpSelect (%uint %c0) to return %c1 (1) instead of 0 on OOB. - mutated, count = re.subn( - r"(OpSelect %uint %\S+ %\S+ )%c0\b", - r"\1%c1", - spv, - ) - self.assertGreater(count, 0, "expected OOB OpSelect against %c0 in SPIR-V") - got_mutated = run_spv(mutated, mem) - self.assertNotEqual(got_mutated, [0, 0, 0, 0]) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_tbuffer_store.py b/tests/semantic/test_tbuffer_store.py deleted file mode 100644 index 2586bd3b8..000000000 --- a/tests/semantic/test_tbuffer_store.py +++ /dev/null @@ -1,87 +0,0 @@ -"""tbuffer_store_format_* (MTBUF stores with the instruction's own format) through the translator and the interpreter. - -cs_tbuffer_store.asm stores into 13 sentinel-filled regions through V#s whose FORMAT differs from the instruction's, -then reads every region back into out[0..51]. check.py's TBUFFER_STORE_WORDS holds the words a Radeon 680M (gfx1035) -gives natively; the rules are in the .asm header. Here the translated fixture runs on the CPU and must give the same -words, so the GPU test, the hardware and the translation are kept in step. -""" -import os -import struct -import sys -import unittest - -HERE = os.path.dirname(os.path.abspath(__file__)) -ROOT = os.path.dirname(os.path.dirname(HERE)) -sys.path.insert(0, HERE) -sys.path.insert(0, os.path.join(ROOT, "runtime", "test", "shaders")) -sys.path.insert(0, os.environ.get("LEONIDA_TOOLS_DIR") or os.path.join(ROOT, "tools")) - -import check # noqa: E402 (runtime/test/shaders/check.py; importing it runs nothing) -import rdna2spirv # noqa: E402 -import support # noqa: E402 - - -def fssm(rsrc2, group): - """The compute-shader header words the translator reads: COMPUTE_PGM_RSRC2 and the thread-group size.""" - header = bytearray(0x148) - struct.pack_into("<4I", header, 0x138, rsrc2, *group) - return bytes(header) - - -# 4 user SGPRs (the output V#), workgroup id in s4, 64x1x1 threads: the header build.py gives the GPU tests. -CS_FSSM = fssm(0x8088, (64, 1, 1)) -# The output V# vk_compute_test passes in s[0:3]: base 0, num_records 0xffffffff, 32_FLOAT, OOB_SELECT 3. -OUT_VSHARP = [0, 0, 0xFFFFFFFF, 0x31016FAC] - - -def run(spv): - memory = {} - outputs = support.run_fragment(spv, inputs={"%wg_id": (0, 0, 0), "%local_id": (0, 0, 0)}, - push_constants=OUT_VSHARP + [0] * 28, memory=memory) - return outputs, memory - - -class TbufferStoreFixture(unittest.TestCase): - def test_words_match_the_native_measurement(self): - outputs, memory = run(support.translate_fixture("cs_tbuffer_store", fssm=CS_FSSM)) - self.assertEqual(outputs, {}) - want = check.TBUFFER_STORE_WORDS - got = [memory.get(4 * i, 0) for i in range(len(want))] - for i, (g, w) in enumerate(zip(got, want)): - with self.subTest(out=i, region=hex(0x200 + 16 * (i // 4))): - self.assertEqual(f"{g:#010x}", f"{w:#010x}") - # The regions themselves hold the same words, and nothing lands between out[] and the regions. - self.assertEqual([memory.get(0x200 + 4 * i, 0) for i in range(len(want))], want) - self.assertEqual(sorted(a for a in memory if len(want) * 4 <= a < 0x200), []) - - -class TbufferStoreTranslation(unittest.TestCase): - def store(self, fmt_mod): - return support.translate_lines("cs_tbuf_one", [ - "v_mov_b32_e32 v20, 1.0", "v_mov_b32_e32 v5, 0x200", - f"tbuffer_store_format_x v20, v5, s[0:3], 0{fmt_mod} offen", "s_endpgm"], fssm=CS_FSSM) - - def test_format_outside_formats_is_unsupported(self): - # BUF_FMT_INVALID (code 0) has no encoder: reported, never guessed. Every code 1-77 has one now (BUF_FMT_8_UINT - # was the example until #1871 added the 8/16-bit UINT/SINT formats, BUF_FMT_8_USCALED and BUF_FMT_10_11_11_UNORM - # until the SCALED and 10_11_11 formats). - with self.assertRaises(rdna2spirv.Unsupported): - self.store(" format:[BUF_FMT_INVALID]") - - def test_default_format_is_one_unorm_byte(self): - # No modifier is GFX10's default, BUF_FMT_8_UNORM: 1.0 is 0xff in the low byte, the other three kept. - spv = self.store("") - memory = {0x200: 0x11223344} - support.run_fragment(spv, inputs={"%wg_id": (0, 0, 0), "%local_id": (0, 0, 0)}, - push_constants=OUT_VSHARP + [0] * 28, memory=memory) - self.assertEqual(f"{memory[0x200]:#010x}", "0x112233ff") - - def test_data_vgprs_are_read(self): - # read_before_write_vgprs: a store's vdata is a source, as for buffer_store. - import shader_ir - ins = shader_ir.parse_line("\ttbuffer_store_format_xy v[7:8], v5, s[4:7], 0 format:[BUF_FMT_32_32_FLOAT] offen") - self.assertEqual(sorted(rdna2spirv.read_before_write_vgprs([ins])), [5, 7, 8]) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_unary_f16_validation.py b/tests/semantic/test_unary_f16_validation.py deleted file mode 100644 index ed4a7bdee..000000000 --- a/tests/semantic/test_unary_f16_validation.py +++ /dev/null @@ -1,267 +0,0 @@ -"""Validation and op_sel semantic tests for all 12 unary f16 VALU ops.""" -import math -import os -import shutil -import struct -import subprocess -import sys -import tempfile -import unittest - -HERE = os.path.dirname(os.path.abspath(__file__)) -if HERE not in sys.path: - sys.path.insert(0, HERE) - -from support import mrt0_words, translate_lines # noqa: E402 -import rdna2spirv # noqa: E402 - -UNARY_F16_OPS = ( - "v_rsq_f16", - "v_rcp_f16", - "v_sqrt_f16", - "v_exp_f16", - "v_log_f16", - "v_floor_f16", - "v_fract_f16", - "v_ceil_f16", - "v_trunc_f16", - "v_rndne_f16", - "v_sin_f16", - "v_cos_f16", -) - - -def f2h(x): - return struct.unpack(" sin(0.0) = 0.0, cos(0.0) = 1.0 - # hi = 0.25 -> sin(0.25) = 1.0, cos(0.25) = 0.0 - h_lo = f2h(0.0) - h_hi = f2h(0.25) - v1_val = (h_hi << 16) | h_lo - old = 0xBEEF1234 - - expected = { - ("v_sin_f16", 0, 0): (old & 0xFFFF0000) | f2h(0.0), - ("v_sin_f16", 1, 0): (old & 0xFFFF0000) | f2h(1.0), - ("v_sin_f16", 0, 1): (f2h(0.0) << 16) | (old & 0xFFFF), - ("v_sin_f16", 1, 1): (f2h(1.0) << 16) | (old & 0xFFFF), - ("v_cos_f16", 0, 0): (old & 0xFFFF0000) | f2h(1.0), - ("v_cos_f16", 1, 0): (old & 0xFFFF0000) | f2h(0.0), - ("v_cos_f16", 0, 1): (f2h(1.0) << 16) | (old & 0xFFFF), - ("v_cos_f16", 1, 1): (f2h(0.0) << 16) | (old & 0xFFFF), - } - - for op in ("v_sin_f16", "v_cos_f16"): - for suffix in ("_e64", ""): - lines = [f"v_mov_b32 v4, {v1_val:#x}"] - combos = ((0, 0), (1, 0), (0, 1), (1, 1)) - for idx, (shi, dhi) in enumerate(combos): - lines.append(f"v_mov_b32 v{idx}, {old:#x}") - lines.append(f"{op}{suffix} v{idx}, v4 op_sel:[{shi},{dhi}]") - lines.append("exp mrt0 v0, v1, v2, v3 done vm") - lines.append("s_endpgm") - words = run_ps(lines, f"ps_{op}_{suffix or 'bare'}_opsel") - for idx, (shi, dhi) in enumerate(combos): - with self.subTest(op=op, suffix=suffix or "bare", shi=shi, dhi=dhi): - self.assertEqual(words[idx], expected[(op, shi, dhi)]) - - def test_sin_cos_opsel_nontrivial_angles_and_mods(self): - # lo = 0.125 turns (45 deg): sin ~= 0.707, cos ~= 0.707 - # hi = 0.75 turns (270 deg): sin = -1.0, cos = 0.0 - h_lo = f2h(0.125) - h_hi = f2h(0.75) - v1_val = (h_hi << 16) | h_lo - old = 0xCAFE5678 - - words = run_ps([ - f"v_mov_b32 v4, {v1_val:#x}", - f"v_mov_b32 v0, {old:#x}", - "v_sin_f16_e64 v0, v4 op_sel:[1,1]", # hi = sin(0.75) = -1.0, lo preserved - f"v_mov_b32 v1, {old:#x}", - "v_sin_f16_e64 v1, -v4 op_sel:[1,0]", # lo = sin(-0.75) = +1.0, hi preserved - f"v_mov_b32 v2, {old:#x}", - "v_sin_f16_e64 v2, v4 op_sel:[1,1] clamp", # hi = clamp(-1.0) = 0.0, lo preserved - f"v_mov_b32 v3, {old:#x}", - "v_cos_f16_e64 v3, |v4| op_sel:[0,1]", # hi = cos(0.125) ~= sqrt(2)/2, lo preserved - "exp mrt0 v0, v1, v2, v3 done vm", - "s_endpgm", - ], "ps_sincos_opsel_mods") - - self.assertEqual(words[0], (f2h(-1.0) << 16) | (old & 0xFFFF)) - self.assertEqual(words[1], (old & 0xFFFF0000) | f2h(1.0)) - self.assertEqual(words[2], (f2h(0.0) << 16) | (old & 0xFFFF)) - self.assertEqual(words[3] & 0xFFFF, old & 0xFFFF) - self.assertAlmostEqual(h2f(words[3] >> 16), math.cos(2.0 * math.pi * 0.125), delta=2e-3) - - def test_sin_cos_opsel_inplace_and_sdwa(self): - # In-place op_sel:[1,0] reads hi before overwriting lo; SDWA reads WORD_1 and writes WORD_1. - v0_init = (f2h(0.25) << 16) | f2h(0.0) - old = 0x0000BEEF - words = run_ps([ - f"v_mov_b32 v0, {v0_init:#x}", - "v_sin_f16_e64 v0, v0 op_sel:[1,0]", # lo = sin(0.25) = 1.0, hi stays 0.25 - f"v_mov_b32 v1, {v0_init:#x}", - "v_cos_f16_e64 v1, v1 op_sel:[0,1]", # hi = cos(0.0) = 1.0, lo stays 0.0 - f"v_mov_b32 v4, {v0_init:#x}", - f"v_mov_b32 v2, {old:#x}", - "v_sin_f16_sdwa v2, v4 dst_sel:WORD_1 dst_unused:UNUSED_PRESERVE src0_sel:WORD_1", - f"v_mov_b32 v3, {old:#x}", - "v_cos_f16_sdwa v3, v4 dst_sel:WORD_1 dst_unused:UNUSED_PRESERVE src0_sel:WORD_0", - "exp mrt0 v0, v1, v2, v3 done vm", - "s_endpgm", - ], "ps_sincos_inplace_sdwa") - - self.assertEqual(words[0], (f2h(0.25) << 16) | f2h(1.0)) - self.assertEqual(words[1], (f2h(1.0) << 16) | f2h(0.0)) - self.assertEqual(words[2], (f2h(1.0) << 16) | (old & 0xFFFF)) - self.assertEqual(words[3], (f2h(1.0) << 16) | (old & 0xFFFF)) - - -class UnaryF16ValidationTests(unittest.TestCase): - """Positive and negative operand/encoding/modifier validation across all 12 unary f16 ops.""" - - def test_positive_controls_all_12_ops(self): - for op in UNARY_F16_OPS: - valid_forms = [ - f"{op} v0, v1", - f"{op}_e32 v0, v1", - f"{op}_e64 v0, -|v1| op_sel:[1,1] clamp mul:2", - f"{op} v0, |v1| op_sel:[1,0] div:2 clamp", - f"{op}_sdwa v0, -v1 clamp mul:2 dst_sel:WORD_1 dst_unused:UNUSED_PRESERVE src0_sel:WORD_1", - ] - lines = [ - "v_mov_b32 v0, 0xaaaa3c00", - "v_mov_b32 v1, 0x40003800", - *valid_forms, - "exp mrt0 v0, v0, v0, v0 done vm", - "s_endpgm", - ] - with self.subTest(op=op): - spv = translate_lines(f"ps_pos_{op}", lines) - validate_spirv(spv) - - def test_negative_validation_all_12_ops(self): - invalid_templates = [ - # Arity - ("arity_1", "{op} v0"), - ("arity_3", "{op} v0, v1, v2"), - # Destination validation - ("dst_sgpr", "{op} s0, v1"), - ("dst_vgpr64", "{op} v[0:1], v1"), - ("dst_special", "{op} exec_lo, v1"), - ("dst_neg", "{op} -v0, v1"), - ("dst_abs", "{op} |v0|, v1"), - ("dst_sext", "{op} sext(v0), v1"), - # Source validation - ("src_vgpr64", "{op} v0, v[1:2]"), - ("src_sgpr64", "{op} v0, s[0:1]"), - ("src_sext", "{op} v0, sext(v1)"), - # _dpp rejected - ("dpp_quad", "{op}_dpp v0, v1 quad_perm:[1,0,3,2]"), - ("dpp8", "{op}_dpp v0, v1 dpp8:[0,1,2,3,4,5,6,7]"), - # _e32 rejects source modifiers and all instruction modifiers - ("e32_neg", "{op}_e32 v0, -v1"), - ("e32_abs", "{op}_e32 v0, |v1|"), - ("e32_clamp", "{op}_e32 v0, v1 clamp"), - ("e32_opsel", "{op}_e32 v0, v1 op_sel:[1,0]"), - ("e32_mul2", "{op}_e32 v0, v1 mul:2"), - ("e32_div2", "{op}_e32 v0, v1 div:2"), - # VOP3 (_e64 / bare) duplicate & invalid modifiers - ("e64_dup_clamp", "{op}_e64 v0, v1 clamp clamp"), - ("e64_dup_omod", "{op}_e64 v0, v1 mul:2 mul:2"), - ("e64_conflict_omod", "{op}_e64 v0, v1 mul:2 div:2"), - ("e64_bad_omod", "{op}_e64 v0, v1 mul:8"), - ("e64_dup_opsel", "{op}_e64 v0, v1 op_sel:[0,0] op_sel:[1,1]"), - ("e64_opsel_oob", "{op}_e64 v0, v1 op_sel:[2,0]"), - ("e64_opsel_too_long", "{op}_e64 v0, v1 op_sel:[0,0,0]"), - ("e64_opsel_empty", "{op}_e64 v0, v1 op_sel:[]"), - ("e64_opsel_malformed", "{op}_e64 v0, v1 op_sel:bad"), - ("e64_opsel_hi", "{op}_e64 v0, v1 op_sel_hi:[1,1]"), - ("e64_neg_lo", "{op}_e64 v0, v1 neg_lo:[1,0]"), - ("e64_neg_hi", "{op}_e64 v0, v1 neg_hi:[1,0]"), - ("e64_sdwa_mod", "{op}_e64 v0, v1 src0_sel:WORD_1"), - ("e64_unknown_mod", "{op}_e64 v0, v1 bogus_mod"), - ("bare_opsel_hi", "{op} v0, v1 op_sel_hi:[1,1]"), - ("bare_dup_clamp", "{op} v0, v1 clamp clamp"), - ("bare_conflict_omod", "{op} v0, v1 mul:4 div:2"), - # _sdwa invalid modifiers - ("sdwa_opsel", "{op}_sdwa v0, v1 op_sel:[1,0] src0_sel:WORD_1"), - ("sdwa_src1_sel", "{op}_sdwa v0, v1 src0_sel:WORD_0 src1_sel:WORD_1"), - ("sdwa_bad_dst_sel", "{op}_sdwa v0, v1 dst_sel:BAD"), - ("sdwa_bad_src0_sel", "{op}_sdwa v0, v1 src0_sel:BAD"), - ("sdwa_bad_dst_unused", "{op}_sdwa v0, v1 dst_unused:BAD"), - ("sdwa_dup_clamp", "{op}_sdwa v0, v1 clamp clamp src0_sel:WORD_0"), - ("sdwa_dup_omod", "{op}_sdwa v0, v1 mul:2 div:2 src0_sel:WORD_0"), - ("sdwa_dup_src0_sel", "{op}_sdwa v0, v1 src0_sel:WORD_0 src0_sel:WORD_1"), - ("sdwa_sext_src", "{op}_sdwa v0, sext(v1) src0_sel:WORD_0"), - ("sdwa_unknown_mod", "{op}_sdwa v0, v1 bogus_mod"), - ] - for op in UNARY_F16_OPS: - for case_name, tmpl in invalid_templates: - inst = tmpl.format(op=op) - with self.subTest(op=op, case=case_name, inst=inst): - with self.assertRaises(rdna2spirv.Unsupported): - translate_single(inst) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_valu_add_f16.py b/tests/semantic/test_valu_add_f16.py deleted file mode 100644 index 73793907d..000000000 --- a/tests/semantic/test_valu_add_f16.py +++ /dev/null @@ -1,149 +0,0 @@ -"""v_add_f16 (RDNA2 VOP2 / VOP3): D.f16 = S0.f16 + S1.f16, binary16 with round to nearest even. - -Every case is translated by tools/rdna2spirv.py and executed with tests/semantic/spirv_mini_interp.py; the expected -word is written down by hand (from the ISA) next to each case, rechecked against the plain-Python binary16 reference in -tests/semantic/f16_ref.py, and extended with seeded random operands. Covers the _e32 form (the high half of the -destination is kept), the _e64 form with op_sel, SGPR / literal / inline-constant sources, neg/abs, omod and clamp. -Standard library only: no GPU, no LLVM, no game data. -""" -import os -import random -import sys -import unittest - -HERE = os.path.dirname(os.path.abspath(__file__)) -sys.dont_write_bytecode = True -sys.path.insert(0, HERE) -import support # noqa: E402 -from f16_ref import OLD, ref_add, same_f16, scale # noqa: E402 - -ONE, TWO, THREE, HALF, QUARTER = 0x3C00, 0x4000, 0x4200, 0x3800, 0x3400 -MAXH, INF, NINF, QNAN = 0x7BFF, 0x7C00, 0xFC00, 0x7E00 -MIN_NORMAL, MIN_SUB, MAX_SUB = 0x0400, 0x0001, 0x03FF - - -def run(line, seeds, old=OLD, hi=0x5A5A): - """Run one instruction on a one-lane pixel shader and return v0 as exported to mrt0. - - `seeds` maps a register ("v1", "s2", ...) to the word it starts with; a value that fits in 16 bits gets `hi` in its - upper half, so reading the wrong half of a source shows. v0 starts as `old`. - """ - prog = [f"v_mov_b32 v0, {old:#x}"] - for reg, w in seeds.items(): - w = w if w > 0xFFFF else (hi << 16) | w - prog.append(f"{'s' if reg[0] == 's' else 'v'}_mov_b32 {reg}, {w:#x}") - prog += [line, "exp mrt0 v0, v0, v0, v0 done vm", "s_endpgm"] - return support.mrt0_words(support.translate_lines("ps_add_f16", prog))[0] - - -# (src0, src1, D), written by hand. -CASES = [ - (ONE, TWO, THREE), # 1 + 2 = 3 - (HALF, QUARTER, 0x3A00), # 0.5 + 0.25 = 0.75 - (THREE, 0xBC00, TWO), # 3 + -1 = 2 - (0x3E00, 0xBE00, 0x0000), # 1.5 + -1.5 = +0 (exact cancellation gives +0) - (0x8000, 0x8000, 0x8000), # -0 + -0 = -0 - (0x0000, 0x8000, 0x0000), # +0 + -0 = +0 - (MAXH, MAXH, INF), # 65504 * 2 overflows - (MAXH, 0x4C00, INF), # 65504 + 16 = 65520: tie between 65504 and 2^16, even is the overflow - (MIN_SUB, MIN_SUB, 0x0002), # 2^-24 + 2^-24 = 2^-23 - (MIN_NORMAL, 0x8001, MAX_SUB), # 2^-14 - 2^-24 = the largest subnormal - (ONE, 0x1000, ONE), # 1 + 2^-11: half an ulp above 1 ties to even, stays 1 - (ONE, 0x1001, 0x3C01), # a little over half an ulp rounds up - (0x6800, ONE, 0x6800), # 2048 + 1: tie, even mantissa is 2048 - (0x6801, ONE, 0x6802), # 2050 + 1 = 2051: tie, even mantissa is 2052 - (INF, ONE, INF), - (INF, NINF, QNAN), # inf + -inf = NaN - (QNAN, ONE, QNAN), -] - -SPECIAL = [0x0000, 0x8000, ONE, 0xBC00, TWO, 0xC000, HALF, 0xB800, THREE, 0x3E00, MAXH, 0xFBFF, INF, NINF, QNAN, - MIN_NORMAL, MIN_SUB, 0x8001, MAX_SUB, 0x3C01, 0x3BFF, 0x1000, 0x6800, 0x6801, 0x4C00] - - -class AddF16(unittest.TestCase): - def test_hand_written_table_matches_reference(self): - for a, b, want in CASES: - self.assertTrue(same_f16(ref_add(a, b), want), (hex(a), hex(b), hex(ref_add(a, b)))) - - def test_e32_writes_low_half_and_keeps_high_half(self): - for a, b, want in CASES: - with self.subTest(a=hex(a), b=hex(b)): - got = run("v_add_f16 v0, v1, v2", {"v1": a, "v2": b}) - self.assertEqual(got >> 16, OLD >> 16) - self.assertTrue(same_f16(got & 0xFFFF, want), hex(got)) - - def test_vop3_sgpr_and_literal_sources(self): - for a, b, want in CASES[:14]: - forms = [ - ("e64 vgpr", "v_add_f16_e64 v0, v1, v2", {"v1": a, "v2": b}), - ("e64 sgpr", "v_add_f16_e64 v0, s1, s2", {"s1": a, "s2": b}), - ("e32 sgpr src0", "v_add_f16 v0, s1, v2", {"s1": a, "v2": b}), - ("e32 literal src0", f"v_add_f16 v0, {a:#x}, v2", {"v2": b}), - ("e64 literal src1", f"v_add_f16_e64 v0, v1, {b:#x}", {"v1": a}), - ] - for form, line, seeds in forms: - with self.subTest(a=hex(a), b=hex(b), form=form): - got = run(line, seeds) - self.assertEqual(got >> 16, OLD >> 16) - self.assertTrue(same_f16(got & 0xFFFF, want), hex(got)) - - def test_inline_constants(self): - # (inline constant as src0, its binary16 value, v1 low half, D), by hand - for text, c, b, want in (("2.0", TWO, 0xB800, 0x3E00), ("-1.0", 0xBC00, HALF, 0xB800), ("0.5", HALF, QUARTER, 0x3A00), - ("4.0", 0x4400, 0xB800, 0x4300), ("1.0", ONE, ONE, TWO)): - with self.subTest(const=text): - self.assertEqual(run(f"v_add_f16 v0, {text}, v1", {"v1": b}) & 0xFFFF, want) - self.assertEqual(ref_add(c, b), want) - - def test_op_sel_selects_source_and_destination_halves(self): - # src0 = (lo 1.0, hi 3.0), src1 = (lo 0.5, hi -0.25); D by hand for each (src0 half, src1 half). - s0, s1 = (THREE << 16) | ONE, (0xB400 << 16) | HALF - expect_lo = {(0, 0): 0x3E00, (1, 0): 0x4300, (0, 1): 0x3A00, (1, 1): 0x4180} # 1.5, 3.5, 0.75, 2.75 - for h0 in (0, 1): - for h1 in (0, 1): - for dh in (0, 1): - want = expect_lo[(h0, h1)] - expect = ((want << 16) | (OLD & 0xFFFF)) if dh else ((OLD & 0xFFFF0000) | want) - with self.subTest(op_sel=(h0, h1, dh)): - got = run(f"v_add_f16_e64 v0, v1, v2 op_sel:[{h0},{h1},{dh}]", {"v1": s0, "v2": s1}) - self.assertEqual(got, expect) - - def test_neg_and_abs_source_modifiers(self): - # v1 = 1.0, v2 = -0.5; (operand text, D) by hand - for ops, want in (("v1, v2", HALF), ("-v1, v2", 0xBE00), ("v1, -v2", 0x3E00), ("|v1|, |v2|", 0x3E00), - ("-|v1|, v2", 0xBE00), ("v1, -|v2|", HALF)): - with self.subTest(ops=ops): - got = run(f"v_add_f16_e64 v0, {ops}", {"v1": ONE, "v2": 0xB800}) - self.assertEqual(got & 0xFFFF, want) - - def test_output_modifiers_and_clamp(self): - # #4542, measured on gfx1036: an f16 destination ignores omod (mul:2/mul:4/div:2) under the game's MODE - # (IEEE=0, f16 denormals kept) and keeps clamp (docs/design.md, f16 output modifiers). - # unmodified result: 1.5 + 0.5 = 2.0; clamp limits it to [0, 1] (negatives and NaN become +0) - for suffix, want in ((" mul:2", 0x4000), (" mul:4", 0x4000), (" div:2", 0x4000), (" clamp", ONE)): - with self.subTest(mod=suffix): - got = run("v_add_f16_e64 v0, v1, v2" + suffix, {"v1": 0x3E00, "v2": HALF}) - self.assertEqual(got & 0xFFFF, want) - for (a, b), suffix, want in (((HALF, QUARTER), " clamp", 0x3A00), ((0xBC00, QUARTER), " clamp", 0x0000), - ((ONE, HALF), " div:2 clamp", ONE), ((HALF, QUARTER), " mul:2 clamp", 0x3A00)): - with self.subTest(a=hex(a), b=hex(b), mod=suffix): - self.assertEqual(run("v_add_f16_e64 v0, v1, v2" + suffix, {"v1": a, "v2": b}) & 0xFFFF, want) - for suffix, f in ((" mul:2", 2.0), (" mul:4", 4.0), (" div:2", 0.5)): - got = run("v_add_f16_e64 v0, v1, v2" + suffix, {"v1": 0x4900, "v2": 0xC100}) # 10 and -2.5 - self.assertEqual(got & 0xFFFF, ref_add(0x4900, 0xC100)) - - def test_random_operands(self): - rng = random.Random(0xADD16) - pool = SPECIAL + [rng.getrandbits(16) for _ in range(40)] - for _ in range(120): - a = rng.choice(pool) if rng.random() < 0.5 else rng.getrandbits(16) - b = rng.choice(pool) if rng.random() < 0.5 else rng.getrandbits(16) - with self.subTest(a=hex(a), b=hex(b)): - got = run("v_add_f16 v0, v1, v2", {"v1": a, "v2": b}) - self.assertEqual(got >> 16, OLD >> 16) - self.assertTrue(same_f16(got & 0xFFFF, ref_add(a, b)), (hex(got), hex(ref_add(a, b)))) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_valu_add_f64.py b/tests/semantic/test_valu_add_f64.py deleted file mode 100644 index 88c58ed1c..000000000 --- a/tests/semantic/test_valu_add_f64.py +++ /dev/null @@ -1,214 +0,0 @@ -"""Value tests for v_add_f64 (IEEE-754 binary64 addition, VOP3 modifiers, and MODE.FP_ROUND): - - v_add_f64 D = S0 + S1 (53-bit significand precision, signed zeros, inf/NaN, - neg/abs/clamp/mul:2/mul:4/div:2, MODE.FP_ROUND 0 vs 3) - -Each case translates a hand-written pixel-shader listing with tools/rdna2spirv.py -and executes the resulting SPIR-V via tests/spirv_interp.py (which supports OpTypeFloat 64, -whereas spirv_mini_interp.py is 32-bit float only). Standard library only. -""" -import math -import os -import struct -import sys -import unittest - -HERE = os.path.dirname(os.path.abspath(__file__)) -TESTS_DIR = os.path.dirname(HERE) -for p in (HERE, TESTS_DIR): - if p not in sys.path: - sys.path.insert(0, p) - -import spirv_interp # noqa: E402 -from support import translate_lines # noqa: E402 (support puts tools/ on sys.path) - -MASK32 = 0xFFFFFFFF -MASK64 = 0xFFFFFFFFFFFFFFFF -POS_ZERO = 0x0000000000000000 -NEG_ZERO = 0x8000000000000000 -POS_INF = 0x7FF0000000000000 -NEG_INF = 0xFFF0000000000000 -DBL_MAX = 0x7FEFFFFFFFFFFFFF -NEG_DBL_MAX = 0xFFEFFFFFFFFFFFFF - - -def f64_to_bits(x): - """Pack a Python float into its IEEE-754 binary64 64-bit unsigned word.""" - try: - return struct.unpack(" 0 else NEG_INF - - -def bits_to_f64(bits): - """Unpack a 64-bit unsigned word as an IEEE-754 binary64 Python float.""" - return struct.unpack("` via spirv_interp; return (u64_bits, spv).""" - if setup is None: - setup = [ - f"v_mov_b32 v0, {a_bits & MASK32:#010x}", - f"v_mov_b32 v1, {(a_bits >> 32) & MASK32:#010x}", - f"v_mov_b32 v2, {b_bits & MASK32:#010x}", - f"v_mov_b32 v3, {(b_bits >> 32) & MASK32:#010x}", - ] - lines = list(setup) - if mode is not None: - lines.append(f"s_setreg_imm32_b32 hwreg(HW_REG_MODE, 2, 2), {mode}") - lines += [ - f"v_add_f64 v[4:5], {operands}", - "exp mrt0 v4, v5, v4, v5 done vm", - "s_endpgm", - ] - spv = translate_lines("ps_add_f64", lines) - res = spirv_interp.run(spv) - got = (res.vgpr[4] & MASK32) | ((res.vgpr[5] & MASK32) << 32) - return got, spv - - -class AddF64PrecisionAndSpecialsTests(unittest.TestCase): - def test_precision_beyond_f32(self): - cases = [ - (float(2**24), 1.0, float(2**24 + 1)), - (float(2**40), 1.0, float(2**40 + 1)), - (float(2**52), 1.0, float(2**52 + 1)), - (1.0, 2.0**-52, 1.0 + 2.0**-52), - # 2^53 + 1.0 rounds to 2^53 (ties to even at the 53-bit significand boundary) - (float(2**53), 1.0, float(2**53)), - ] - for a, b, exp in cases: - with self.subTest(a=a, b=b): - got, _ = run_add_f64(f64_to_bits(a), f64_to_bits(b)) - self.assertEqual(got, f64_to_bits(exp)) - - def test_cancellation(self): - cases = [ - (float(2**50) + 1.0, -float(2**50), 1.0), - (1.0 + 2.0**-52, -1.0, 2.0**-52), - (123.456, -123.456, 0.0), - ] - for a, b, exp in cases: - with self.subTest(a=a, b=b): - got, _ = run_add_f64(f64_to_bits(a), f64_to_bits(b)) - self.assertEqual(got, f64_to_bits(exp)) - - def test_signed_zeros(self): - cases = [ - (POS_ZERO, POS_ZERO, POS_ZERO), - (POS_ZERO, NEG_ZERO, POS_ZERO), - (NEG_ZERO, POS_ZERO, POS_ZERO), - (NEG_ZERO, NEG_ZERO, NEG_ZERO), - ] - for a, b, exp in cases: - with self.subTest(a=hex(a), b=hex(b)): - got, _ = run_add_f64(a, b) - self.assertEqual(got, exp) - - def test_infinities_and_nan(self): - one = f64_to_bits(1.0) - for a, b, exp in ( - (POS_INF, one, POS_INF), - (NEG_INF, one, NEG_INF), - (POS_INF, POS_INF, POS_INF), - (NEG_INF, NEG_INF, NEG_INF), - ): - with self.subTest(a=hex(a), b=hex(b)): - got, _ = run_add_f64(a, b) - self.assertEqual(got, exp) - - got, _ = run_add_f64(POS_INF, NEG_INF) - self.assertTrue(math.isnan(bits_to_f64(got)), f"expected NaN, got {got:#018x}") - - -class AddF64ModifiersAndOperandsTests(unittest.TestCase): - def test_neg_and_abs_modifiers(self): - # neg preserves full 53-bit precision - a = f64_to_bits(float(2**52)) - b = f64_to_bits(1.0) - got, _ = run_add_f64(a, b, operands="v[0:1], -v[2:3]") - self.assertEqual(got, f64_to_bits(float(2**52 - 1))) - - got, _ = run_add_f64(a, b, operands="-v[0:1], v[2:3]") - self.assertEqual(got, f64_to_bits(float(-(2**52) + 1))) - - # abs / neg-abs (using f32-exact values because spirv_interp.FAbs passes through f32) - for a_val, b_val, ops, exp in ( - (-1.5, 0.25, "|v[0:1]|, v[2:3]", 1.75), - (1.5, -0.25, "v[0:1], |v[2:3]|", 1.75), - (-1.5, 0.25, "-|v[0:1]|, v[2:3]", -1.25), - ): - with self.subTest(ops=ops): - got, _ = run_add_f64(f64_to_bits(a_val), f64_to_bits(b_val), operands=ops) - self.assertEqual(got, f64_to_bits(exp)) - - def test_output_modifiers(self): - # Use f32-exact values for clamp cases because spirv_interp.FClamp rounds via f32 - cases = [ - (0.75, 0.5, "v[0:1], v[2:3] mul:2", 2.5), - (0.75, 0.5, "v[0:1], v[2:3] mul:4", 5.0), - (0.75, 0.5, "v[0:1], v[2:3] div:2", 0.625), - (0.75, 0.5, "v[0:1], v[2:3] clamp", 1.0), - (-1.5, 0.5, "v[0:1], v[2:3] clamp", 0.0), - (0.75, 0.5, "v[0:1], v[2:3] mul:2 clamp", 1.0), - # div:2 before clamp: (1.0 + 0.5) * 0.5 = 0.75 -> clamp -> 0.75 (not 0.5) - (1.0, 0.5, "v[0:1], v[2:3] div:2 clamp", 0.75), - ] - for a_val, b_val, ops, exp in cases: - with self.subTest(ops=ops): - got, _ = run_add_f64(f64_to_bits(a_val), f64_to_bits(b_val), operands=ops) - self.assertEqual(got, f64_to_bits(exp)) - - # Verify mul:2/mul:4/div:2 keep full f64 precision - got, _ = run_add_f64(f64_to_bits(float(2**50)), f64_to_bits(1.0), operands="v[0:1], v[2:3] mul:2") - self.assertEqual(got, f64_to_bits(float(2**51 + 2))) - - def test_sgpr_pair_and_inline_float_operands(self): - a = f64_to_bits(float(2**40)) - b = f64_to_bits(3.5) - # SGPR-pair src0 + VGPR-pair src1 - setup_s0 = [ - f"s_mov_b32 s0, {a & MASK32:#010x}", - f"s_mov_b32 s1, {(a >> 32) & MASK32:#010x}", - f"v_mov_b32 v2, {b & MASK32:#010x}", - f"v_mov_b32 v3, {(b >> 32) & MASK32:#010x}", - ] - got, _ = run_add_f64(0, 0, setup=setup_s0, operands="s[0:1], v[2:3]") - self.assertEqual(got, f64_to_bits(float(2**40) + 3.5)) - - # Inline float constants - got, _ = run_add_f64(a, 0, operands="v[0:1], 0.5") - self.assertEqual(got, f64_to_bits(float(2**40) + 0.5)) - - got, _ = run_add_f64(0, b, operands="-1.0, v[2:3]") - self.assertEqual(got, f64_to_bits(2.5)) - - -class AddF64RoundingModeTests(unittest.TestCase): - def test_mode_fp_round_toward_zero_vs_nearest_even(self): - # 1.0 + (2^-52 + 2^-53) = 1.0 + 3 * 2^-53: - # nearest-even (MODE.FP_ROUND=0) -> 1.0 + 2^-51 (0x3FF0000000000002) - # toward-zero (MODE.FP_ROUND=3) -> 1.0 + 2^-52 (0x3FF0000000000001) - one = 0x3FF0000000000000 - three_half_ulp = 0x3CB8000000000000 # 1.5 * 2^-52 = 3 * 2^-53 - self.assertEqual(run_add_f64(one, three_half_ulp, mode=0)[0], 0x3FF0000000000002) - self.assertEqual(run_add_f64(one, three_half_ulp, mode=3)[0], 0x3FF0000000000001) - - # Negative mirror: -(1.0 + 3 * 2^-53) - neg_one = 0xBFF0000000000000 - neg_three_half_ulp = 0xBCB8000000000000 - self.assertEqual(run_add_f64(neg_one, neg_three_half_ulp, mode=0)[0], 0xBFF0000000000002) - self.assertEqual(run_add_f64(neg_one, neg_three_half_ulp, mode=3)[0], 0xBFF0000000000001) - - # Overflow: DBL_MAX + DBL_MAX -> +inf in nearest-even, DBL_MAX in toward-zero - self.assertEqual(run_add_f64(DBL_MAX, DBL_MAX, mode=0)[0], POS_INF) - self.assertEqual(run_add_f64(DBL_MAX, DBL_MAX, mode=3)[0], DBL_MAX) - - # Negative overflow: -DBL_MAX + (-DBL_MAX) -> -inf in nearest-even, -DBL_MAX in toward-zero - self.assertEqual(run_add_f64(NEG_DBL_MAX, NEG_DBL_MAX, mode=0)[0], NEG_INF) - self.assertEqual(run_add_f64(NEG_DBL_MAX, NEG_DBL_MAX, mode=3)[0], NEG_DBL_MAX) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_valu_add_sub_minmax_f16.py b/tests/semantic/test_valu_add_sub_minmax_f16.py deleted file mode 100644 index 8b9e30ac4..000000000 --- a/tests/semantic/test_valu_add_sub_minmax_f16.py +++ /dev/null @@ -1,187 +0,0 @@ -"""Value tests for f16 add/sub/min/max VALU instructions: - - v_add_f16 D.f16 = S0.f16 + S1.f16 - v_sub_f16 D.f16 = S0.f16 - S1.f16 - v_min_f16 D.f16 = min(S0.f16, S1.f16) (-0.0 < +0.0, NaN -> other) - v_max_f16 D.f16 = max(S0.f16, S1.f16) (-0.0 < +0.0, NaN -> other) - -Each case translates a hand-written pixel-shader listing with tools/rdna2spirv.py -and executes the resulting SPIR-V via tests/semantic/spirv_mini_interp.py. -GFX10 partial-register preservation (the untouched 16-bit half of vdst keeps its -prior sentinel bits) and VOP3 op_sel/neg/abs/clamp modifiers are verified directly. -Standard library only. -""" -import math -import os -import struct -import sys -import unittest - -HERE = os.path.dirname(os.path.abspath(__file__)) -if HERE not in sys.path: - sys.path.insert(0, HERE) - -from support import mrt0_words, translate_lines # noqa: E402 (support puts tools/ on sys.path) - -MASK32 = 0xFFFFFFFF -POS_ZERO = 0x0000 -NEG_ZERO = 0x8000 -POS_INF = 0x7C00 -NEG_INF = 0xFC00 -QNAN = 0x7E00 - - -def f16_to_bits(x): - """Pack a Python float into its IEEE-754 binary16 16-bit unsigned word.""" - try: - return struct.unpack(" 0 else NEG_INF - - -def bits_to_f16(h): - """Unpack a 16-bit unsigned word as an IEEE-754 binary16 Python float.""" - return struct.unpack("` with v0 preloaded; return the full 32-bit v0 word.""" - if setup is None: - setup = [ - f"v_mov_b32 v1, {a_word & MASK32:#010x}", - f"v_mov_b32 v2, {b_word & MASK32:#010x}", - ] - lines = [f"v_mov_b32 v0, {v0_init & MASK32:#010x}"] + list(setup) + [ - f"{op} v0, {operands}", - "exp mrt0 v0, v0, v0, v0 done vm", - "s_endpgm", - ] - spv = translate_lines(f"ps_{op.split()[0]}", lines) - words = mrt0_words(spv) - if len(set(words)) != 1: - raise AssertionError(f"{op}: exported mrt0 words differ: {[hex(w) for w in words]}") - return words[0] - - -class AddSubF16Tests(unittest.TestCase): - def test_exact_cancellation_and_overflow(self): - cases = [ - ("v_add_f16", 1.5, 2.25, 3.75), - ("v_add_f16", -2.5, 0.75, -1.75), - ("v_add_f16", 1.5, -1.5, 0.0), # cancellation -> +0.0 - ("v_add_f16", 65504.0, 32.0, math.inf), - ("v_add_f16", -65504.0, -32.0, -math.inf), - ("v_sub_f16", 5.0, 1.25, 3.75), - ("v_sub_f16", 1.25, 5.0, -3.75), # non-commutative - ("v_sub_f16", 1.5, 1.5, 0.0), # cancellation -> +0.0 - ("v_sub_f16", -65504.0, 32.0, -math.inf), - ] - for op_base, a, b, exp in cases: - ab, bb, eb = f16_to_bits(a), f16_to_bits(b), f16_to_bits(exp) - for suffix in ("", "_e32", "_e64"): - op = op_base + suffix - with self.subTest(op=op, a=a, b=b): - got = run_f16(op, ab, bb) - self.assertEqual(got & 0xFFFF, eb) - self.assertEqual(got >> 16, 0xBEEF) # upper half preserved - - def test_signed_zeros(self): - cases = [ - ("v_add_f16", POS_ZERO, NEG_ZERO, POS_ZERO), - ("v_add_f16", NEG_ZERO, NEG_ZERO, NEG_ZERO), - ("v_sub_f16", NEG_ZERO, POS_ZERO, NEG_ZERO), - ("v_sub_f16", POS_ZERO, NEG_ZERO, POS_ZERO), - ("v_sub_f16", NEG_ZERO, NEG_ZERO, POS_ZERO), - ] - for op, ab, bb, eb in cases: - with self.subTest(op=op, a=hex(ab), b=hex(bb)): - got = run_f16(op, ab, bb) - self.assertEqual(got & 0xFFFF, eb) - - -class MinMaxF16Tests(unittest.TestCase): - def test_signed_zero_ordering_and_nan(self): - # Hardware NMin/NMax orders -0.0 < +0.0 and returns the non-NaN operand. - self.assertEqual(run_f16("v_min_f16", NEG_ZERO, POS_ZERO) & 0xFFFF, NEG_ZERO) - self.assertEqual(run_f16("v_min_f16", POS_ZERO, NEG_ZERO) & 0xFFFF, NEG_ZERO) - self.assertEqual(run_f16("v_max_f16", NEG_ZERO, POS_ZERO) & 0xFFFF, POS_ZERO) - self.assertEqual(run_f16("v_max_f16", POS_ZERO, NEG_ZERO) & 0xFFFF, POS_ZERO) - - one = f16_to_bits(1.0) - self.assertEqual(run_f16("v_min_f16", QNAN, one) & 0xFFFF, one) - self.assertEqual(run_f16("v_min_f16", one, QNAN) & 0xFFFF, one) - self.assertEqual(run_f16("v_max_f16", QNAN, one) & 0xFFFF, one) - self.assertEqual(run_f16("v_max_f16", one, QNAN) & 0xFFFF, one) - - def test_boundary_pairs_and_forms(self): - vals = (NEG_INF, f16_to_bits(-65504.0), f16_to_bits(-1.0), NEG_ZERO, POS_ZERO, f16_to_bits(1.0), - f16_to_bits(65504.0), POS_INF) - for suffix in ("", "_e32", "_e64"): - for i, ab in enumerate(vals): - for bb in vals[i:]: - with self.subTest(suffix=suffix, a=hex(ab), b=hex(bb)): - self.assertEqual(run_f16("v_min_f16" + suffix, ab, bb) & 0xFFFF, ab) - self.assertEqual(run_f16("v_max_f16" + suffix, ab, bb) & 0xFFFF, bb) - - -class Gfx10PartialRegOpselAndModifiersTests(unittest.TestCase): - def test_partial_register_preservation_and_opsel(self): - # Pack distinct f16 values into lo/hi halves of v1 and v2 - v1_packed = (f16_to_bits(10.0) << 16) | f16_to_bits(1.5) - v2_packed = (f16_to_bits(20.0) << 16) | f16_to_bits(2.5) - - # dst=lo (0): preserves 0xBEEF in bits 31:16 - got = run_f16("v_add_f16_e64", v1_packed, v2_packed, operands="v1, v2 op_sel:[1,0,0]") - self.assertEqual(got, (0xBEEF << 16) | f16_to_bits(12.5)) - - got = run_f16("v_sub_f16_e64", v1_packed, v2_packed, operands="v1, v2 op_sel:[0,1,0]") - self.assertEqual(got, (0xBEEF << 16) | f16_to_bits(-18.5)) - - # dst=hi (1): preserves 0xDEAD in bits 15:0 - got = run_f16("v_add_f16_e64", v1_packed, v2_packed, operands="v1, v2 op_sel:[1,1,1]") - self.assertEqual(got, (f16_to_bits(30.0) << 16) | 0xDEAD) - - got = run_f16("v_min_f16_e64", v1_packed, v2_packed, operands="v1, v2 op_sel:[1,0,1]") - self.assertEqual(got, (f16_to_bits(2.5) << 16) | 0xDEAD) - - got = run_f16("v_max_f16_e64", v1_packed, v2_packed, operands="v1, v2 op_sel:[0,1,1]") - self.assertEqual(got, (f16_to_bits(20.0) << 16) | 0xDEAD) - - def test_vop3_modifiers_and_operand_kinds(self): - a, b = f16_to_bits(-1.5), f16_to_bits(0.75) - cases = [ - ("v_add_f16_e64", "-v1, v2", 2.25), - ("v_add_f16_e64", "|v1|, v2", 2.25), - ("v_sub_f16_e64", "v1, -v2", -0.75), - ("v_add_f16_e64", "|v1|, v2 clamp", 1.0), - ("v_sub_f16_e64", "v1, v2 clamp", 0.0), - ("v_min_f16_e64", "-v1, v2", 0.75), - ("v_max_f16_e64", "v1, -v2 clamp", 0.0), - ] - for op, operands, exp in cases: - with self.subTest(op=op, operands=operands): - got = run_f16(op, a, b, operands=operands) - self.assertEqual(got & 0xFFFF, f16_to_bits(exp)) - self.assertEqual(got >> 16, 0xBEEF) - - # SGPR, literal, and inline-float operands - sgpr_got = run_f16("v_add_f16_e32", 0, 0, - setup=[f"s_mov_b32 s0, {f16_to_bits(2.5):#010x}", - f"v_mov_b32 v2, {f16_to_bits(1.25):#010x}"], - operands="s0, v2") - self.assertEqual(sgpr_got & 0xFFFF, f16_to_bits(3.75)) - - lit_got = run_f16("v_sub_f16_e32", 0, 0, - setup=[f"v_mov_b32 v2, {f16_to_bits(1.25):#010x}"], - operands=f"{f16_to_bits(4.5):#010x}, v2") - self.assertEqual(lit_got & 0xFFFF, f16_to_bits(3.25)) - - imm_got = run_f16("v_max_f16_e64", f16_to_bits(0.25), 0, operands="v1, 0.5") - self.assertEqual(imm_got & 0xFFFF, f16_to_bits(0.5)) - - imm_neg_got = run_f16("v_add_f16_e32", 0, f16_to_bits(2.5), operands="-1.0, v2") - self.assertEqual(imm_neg_got & 0xFFFF, f16_to_bits(1.5)) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_valu_add_sub_nc_i16.py b/tests/semantic/test_valu_add_sub_nc_i16.py deleted file mode 100644 index 3b23921ce..000000000 --- a/tests/semantic/test_valu_add_sub_nc_i16.py +++ /dev/null @@ -1,164 +0,0 @@ -"""Semantic interpreter tests for RDNA2 v_add_nc_i16 and v_sub_nc_i16 (VOP3-only, GFX10). - -D.i16 = S0.i16 +/- S1.i16; the low 16 bits wrap like v_add_nc_u16 / v_sub_nc_u16, and clamp saturates the exact -signed result to [-32768, 32767]. op_sel:[s0,s1,dst] picks each source's half and the destination half; the other -half of D is kept (opsel-capable VOP3, as for the u16 forms). Each case translates a synthetic pixel shader and runs it -in tests/semantic/spirv_mini_interp.py; D leaves through exp as 16-bit halves ORed into 0x40000000, so no channel is a -NaN pattern a float round trip could change. Standard library only; no GPU, no game files. -""" -import os -import random -import struct -import sys -import tempfile -import unittest -import warnings - -HERE = os.path.dirname(os.path.abspath(__file__)) -ROOT = os.path.dirname(os.path.dirname(HERE)) -sys.dont_write_bytecode = True -sys.path.insert(0, os.environ.get("LEONIDA_TOOLS_DIR") or os.path.join(ROOT, "tools")) -sys.path.insert(0, HERE) - -import rdna2spirv # noqa: E402 -import spirv_mini_interp as si # noqa: E402 - -STUB_DXBC = b"DXBC" + bytes(24) + struct.pack("> 15 else x - - -def ref(op, a, b, sel=(0, 0, 0), clamp=False, old=OLD): - x, y = s16(a >> (16 * sel[0])), s16(b >> (16 * sel[1])) - r = x + y if op == "v_add_nc_i16" else x - y - if clamp: - r = max(-32768, min(32767, r)) - r &= 0xFFFF - return (old & 0xFFFF0000) | r if not sel[2] else (old & 0xFFFF) | r << 16 - - -def translate(lines): - global _TMP - if _TMP is None: - _TMP = tempfile.TemporaryDirectory() - os.mkdir(os.path.join(_TMP.name, "disasm")) - with open(os.path.join(_TMP.name, "ps_nci16.dxbc"), "wb") as f: - f.write(STUB_DXBC) - src = os.path.join(_TMP.name, "disasm", "ps_nci16.s") - with open(src, "w", encoding="utf-8") as f: - f.write("; ps_nci16\n" + "".join(f"\t{ln}\n" for ln in lines)) - with warnings.catch_warnings(): - warnings.simplefilter("ignore", ResourceWarning) - return rdna2spirv.translate(src) - - -def tearDownModule(): - if _TMP is not None: - _TMP.cleanup() - - -def run(line, a, b, old=OLD): - lines = [f"v_mov_b32 v1, {a:#x}", f"v_mov_b32 v2, {b:#x}", f"v_mov_b32 v0, {old:#x}", line, - "v_and_b32 v5, 0xffff, v0", "v_lshrrev_b32 v6, 16, v0", "v_or_b32 v5, 0x40000000, v5", - "v_or_b32 v6, 0x40000000, v6", "exp mrt0 v5, v6, v5, v5 done vm", "s_endpgm"] - lo, hi = si.run_fragment(translate(lines))["%out_mrt0"][:2] - assert lo >> 16 == 0x4000 and hi >> 16 == 0x4000, (hex(lo), hex(hi)) - return (lo & 0xFFFF) | (hi & 0xFFFF) << 16 - - -def mods(sel, clamp): - m = f" op_sel:[{sel[0]},{sel[1]},{sel[2]}]" if any(sel) else "" - return m + (" clamp" if clamp else "") - - -OPS = ("v_add_nc_i16", "v_sub_nc_i16") -VALUES = [0, 1, 0x7FFF, 0x8000, 0xFFFF, 0x7FFE, 0x8001, 0x1234, 0x7FFF8000, 0x80017FFF] - - -class AddSubNcI16(unittest.TestCase): - def test_reference(self): - self.assertEqual(ref("v_add_nc_i16", 0x7FFF, 1) & 0xFFFF, 0x8000) # wraps - self.assertEqual(ref("v_add_nc_i16", 0x7FFF, 1, clamp=True) & 0xFFFF, 0x7FFF) # saturates - self.assertEqual(ref("v_sub_nc_i16", 0x8000, 1, clamp=True) & 0xFFFF, 0x8000) - self.assertEqual(ref("v_sub_nc_i16", 0x0000, 0x8000, clamp=True) & 0xFFFF, 0x7FFF) # 0 - (-32768) - - def test_values_with_and_without_clamp(self): - for op in OPS: - for a in VALUES: - for b in VALUES[::2]: - for clamp in (False, True): - with self.subTest(op=op, a=hex(a), b=hex(b), clamp=clamp): - self.assertEqual(run(f"{op} v0, v1, v2" + mods((0, 0, 0), clamp), a, b), - ref(op, a, b, clamp=clamp)) - - def test_op_sel(self): - a, b = 0x7FFF1234, 0x80000001 - for op in OPS: - for sel in ((1, 0, 0), (0, 1, 0), (1, 1, 1), (0, 0, 1)): - for clamp in (False, True): - with self.subTest(op=op, sel=sel, clamp=clamp): - self.assertEqual(run(f"{op} v0, v1, v2" + mods(sel, clamp), a, b), - ref(op, a, b, sel, clamp)) - - def test_without_clamp_same_as_u16(self): - rng = random.Random(0x16A) - for _ in range(20): - a, b = rng.getrandbits(32), rng.getrandbits(32) - for i16, u16 in (("v_add_nc_i16", "v_add_nc_u16"), ("v_sub_nc_i16", "v_sub_nc_u16")): - with self.subTest(op=i16, a=hex(a), b=hex(b)): - self.assertEqual(run(f"{i16} v0, v1, v2", a, b), run(f"{u16} v0, v1, v2", a, b)) - - def test_sgpr_and_inline_constants(self): - for op in OPS: - with self.subTest(op=op): - # s4 as src0, 1 as src1 - lines = [ - "s_mov_b32 s4, 0x00000005", - "v_mov_b32 v0, 0xAAAA0000", - f"{op} v0, s4, 1", - "v_and_b32 v5, 0xffff, v0", "v_lshrrev_b32 v6, 16, v0", - "v_or_b32 v5, 0x40000000, v5", "v_or_b32 v6, 0x40000000, v6", - "exp mrt0 v5, v6, v5, v5 done vm", "s_endpgm", - ] - lo, hi = si.run_fragment(translate(lines))["%out_mrt0"][:2] - got = (lo & 0xFFFF) | (hi & 0xFFFF) << 16 - want_lo = 6 if op == "v_add_nc_i16" else 4 - self.assertEqual(got, 0xAAAA0000 | want_lo) - - def test_literal_and_high_half_preservation(self): - for op in OPS: - with self.subTest(op=op): - # 32-bit literal operand preserving high half (0xAAAA) - lines = [ - "v_mov_b32 v1, 0x00000002", - "v_mov_b32 v0, 0xAAAA0000", - f"{op} v0, 0x1234, v1", - "v_and_b32 v5, 0xffff, v0", "v_lshrrev_b32 v6, 16, v0", - "v_or_b32 v5, 0x40000000, v5", "v_or_b32 v6, 0x40000000, v6", - "exp mrt0 v5, v6, v5, v5 done vm", "s_endpgm", - ] - lo, hi = si.run_fragment(translate(lines))["%out_mrt0"][:2] - got = (lo & 0xFFFF) | (hi & 0xFFFF) << 16 - want_lo = (0x1234 + 2) if op == "v_add_nc_i16" else (0x1234 - 2) - self.assertEqual(got, 0xAAAA0000 | want_lo) - - def test_non_vgpr_opsel_dst_rejected(self): - for op in OPS: - with self.subTest(op=op): - lines = [ - "v_mov_b32 v1, 1", - "v_mov_b32 v2, 2", - f"{op} s4, v1, v2 op_sel:[0,0,1]", - "s_endpgm", - ] - with self.assertRaises(rdna2spirv.Unsupported): - translate(lines) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_valu_alignbyte_b32.py b/tests/semantic/test_valu_alignbyte_b32.py deleted file mode 100644 index d4c75b88d..000000000 --- a/tests/semantic/test_valu_alignbyte_b32.py +++ /dev/null @@ -1,104 +0,0 @@ -"""v_alignbyte_b32 (RDNA2 VOP3): D = low 32 bits of ({S0, S1} >> (8 * (S2 & 3))), S0 the high dword. - -Each case is translated by tools/rdna2spirv.py and executed with tests/semantic/spirv_mini_interp.py; the expected -words are written by hand and also recomputed by a plain-Python reference. Standard library only: no GPU, no LLVM, -no game data. -""" -import os -import random -import sys -import unittest - -HERE = os.path.dirname(os.path.abspath(__file__)) -sys.dont_write_bytecode = True -sys.path.insert(0, HERE) - -import support # noqa: E402 - -MASK32 = 0xFFFFFFFF - - -def ref_alignbyte(s0, s1, s2): - return ((((s0 & MASK32) << 32) | (s1 & MASK32)) >> (8 * (s2 & 3))) & MASK32 - - -def run(s0, s1, s2, form="vgpr", dst=None): - """dst: None for a fresh v0, or 0/1/2 to write the result over S0/S1/S2 (vgpr form) and export that register.""" - if dst is not None: - lines = [f"v_mov_b32 v1, {s0:#x}", f"v_mov_b32 v2, {s1:#x}", f"v_mov_b32 v3, {s2 & MASK32:#x}", - f"v_alignbyte_b32 v{dst + 1}, v1, v2, v3", f"exp mrt0 v{dst + 1}, v{dst + 1}, v{dst + 1}, v{dst + 1} done vm", - "s_endpgm"] - return support.mrt0_words(support.translate_lines("ps_alignbyte", lines))[0] - if form == "vgpr": - setup = [f"v_mov_b32 v1, {s0:#x}", f"v_mov_b32 v2, {s1:#x}", f"v_mov_b32 v3, {s2 & MASK32:#x}"] - srcs = "v1, v2, v3" - elif form == "sgpr": - setup = [f"s_mov_b32 s1, {s0:#x}", f"s_mov_b32 s2, {s1:#x}", f"s_mov_b32 s3, {s2 & MASK32:#x}"] - srcs = "s1, s2, s3" - else: # the shift as an inline constant - setup = [f"v_mov_b32 v1, {s0:#x}", f"v_mov_b32 v2, {s1:#x}"] - srcs = f"v1, v2, {s2}" - lines = setup + [f"v_alignbyte_b32 v0, {srcs}", "exp mrt0 v0, v0, v0, v0 done vm", "s_endpgm"] - return support.mrt0_words(support.translate_lines("ps_alignbyte", lines))[0] - - -# (name, S0, S1, S2, expected word), written by hand. -CASES = [ - ("shift 0 returns S1", 0xDEADBEEF, 0xCAFEBABE, 0, 0xCAFEBABE), - ("shift 1", 0x88776655, 0x44332211, 1, 0x55443322), - ("shift 2", 0x88776655, 0x44332211, 2, 0x66554433), - ("shift 3", 0x88776655, 0x44332211, 3, 0x77665544), - ("rotate idiom, shift 1", 0x12345678, 0x12345678, 1, 0x78123456), - ("rotate idiom, shift 2", 0x12345678, 0x12345678, 2, 0x56781234), - ("rotate idiom, shift 3", 0x12345678, 0x12345678, 3, 0x34567812), - ("S0 = 0 is a logical shift right", 0, 0x89ABCDEF, 1, 0x0089ABCD), - ("S1 = 0 is a shift left", 0x89ABCDEF, 0, 1, 0xEF000000), - ("S1 = 0, shift 3", 0x89ABCDEF, 0, 3, 0xABCDEF00), - ("top byte of S0 never reaches D", 0xFF000000, 0, 3, 0x00000000), - ("shift uses only the low two bits (4+1)", 0x9ABCDEF0, 0x12345678, 5, 0xF0123456), - ("shift uses only the low two bits (0xFFFFFFFC+2)", 0x9ABCDEF0, 0x12345678, 0xFFFFFFFE, 0xDEF01234), - ("negative shift -1 is 3", 0x11223344, 0xAABBCCDD, 0xFFFFFFFF, 0x223344AA), -] - - -class AlignByte(unittest.TestCase): - def test_hand_written_table_matches_reference(self): - for name, s0, s1, s2, want in CASES: - self.assertEqual(ref_alignbyte(s0, s1, s2), want, name) - - def test_translated_cases(self): - for name, s0, s1, s2, want in CASES: - with self.subTest(name): - self.assertEqual(run(s0, s1, s2), want) - - def test_sgpr_and_inline_constant_shift(self): - for name, s0, s1, s2, want in CASES[:11]: - with self.subTest(name, form="sgpr"): - self.assertEqual(run(s0, s1, s2, "sgpr"), want) - with self.subTest(name, form="inline"): - self.assertEqual(run(s0, s1, s2, "inline"), want) - - def test_inline_shift_above_three(self): - # Immediate shifts 4 and 5 use only the low two bits (0 and 1); a mask of 7 would give other words. - for shift, want in ((4, 0x12345678), (5, 0xF0123456), (6, 0xDEF01234), (7, 0xBCDEF012)): - self.assertEqual(ref_alignbyte(0x9ABCDEF0, 0x12345678, shift), want) - with self.subTest(shift=shift): - self.assertEqual(run(0x9ABCDEF0, 0x12345678, shift, "inline"), want) - - def test_destination_overlaps_each_source(self): - # Distinct operand values, so a destination that is cleared or overwritten before a source is read changes D. - for name, s0, s1, s2, want in CASES: - for dst, what in ((0, "S0"), (1, "S1"), (2, "S2 (the shift)")): - with self.subTest(name, dst=what): - self.assertEqual(run(s0, s1, s2, dst=dst), want) - - def test_random_operands(self): - rng = random.Random(0x616C676E) - for _ in range(60): - s0, s1, s2 = (rng.getrandbits(32) for _ in range(3)) - with self.subTest(s0=hex(s0), s1=hex(s1), s2=hex(s2)): - self.assertEqual(run(s0, s1, s2), ref_alignbyte(s0, s1, s2)) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_valu_cmp_class.py b/tests/semantic/test_valu_cmp_class.py deleted file mode 100644 index f1a48bb84..000000000 --- a/tests/semantic/test_valu_cmp_class.py +++ /dev/null @@ -1,227 +0,0 @@ -"""Translator-driven semantic tests for v_cmp_class_f32, v_cmp_class_f64, and v_cmpx_class_*. - -Translates hand-written RDNA2 listings through tools/rdna2spirv.py, validates with spirv-as/spirv-val when on PATH, -and executes them in spirv_mini_interp: - - exhaustive 10-bit IEEE 754 class matrix for v_cmp_class_f32 and v_cmp_class_f64 - (bit 0 sNaN, 1 qNaN, 2 -Inf, 3 -Normal, 4 -Subnormal, 5 -0.0, 6 +0.0, 7 +Subnormal, 8 +Normal, 9 +Inf); - - composite masks (NaN, Inf, Zero, Subnormal, Normal, All 0x3FF, None 0x000, high bits 0xFC00 ignored); - - VOP3 source modifiers (-src0, |src0|, -|src0|) on both f32 and f64; - - v_cmpx_class_f32_e32 and v_cmpx_class_f64_e32 updating EXEC per lane in a 32-lane compute wave. - - python -I tests/semantic/test_valu_cmp_class.py -v -""" -import os -import shutil -import subprocess -import sys -import tempfile -import unittest - -HERE = os.path.dirname(os.path.abspath(__file__)) -if HERE not in sys.path: - sys.path.insert(0, HERE) - -import spirv_mini_interp as si # noqa: E402 -import support # noqa: E402 - -SHADERS = os.path.join(support.ROOT, "runtime", "test", "shaders") - -F32_CLASSES = [ - ("snan", 0x7F800001, 0), - ("qnan", 0x7FC00000, 1), - ("neg_inf", 0xFF800000, 2), - ("neg_norm", 0xBF800000, 3), - ("neg_den", 0x80000001, 4), - ("neg_zero", 0x80000000, 5), - ("pos_zero", 0x00000000, 6), - ("pos_den", 0x00000001, 7), - ("pos_norm", 0x3F800000, 8), - ("pos_inf", 0x7F800000, 9), -] - -F64_CLASSES = [ - ("snan", 0x7FF0000000000001, 0), - ("qnan", 0x7FF8000000000000, 1), - ("neg_inf", 0xFFF0000000000000, 2), - ("neg_norm", 0xBFF0000000000000, 3), - ("neg_den", 0x8000000000000001, 4), - ("neg_zero", 0x8000000000000000, 5), - ("pos_zero", 0x0000000000000000, 6), - ("pos_den", 0x0000000000000001, 7), - ("pos_norm", 0x3FF0000000000000, 8), - ("pos_inf", 0x7FF0000000000000, 9), -] - - -def _validate_spv(spvasm): - spirv_as, spirv_val = shutil.which("spirv-as"), shutil.which("spirv-val") - if not (spirv_as and spirv_val): - return - with tempfile.TemporaryDirectory() as tmp: - spv = os.path.join(tmp, "out.spv") - r = subprocess.run([spirv_as, "--target-env", "vulkan1.2", "-o", spv, "-"], - input=spvasm, text=True, capture_output=True) - if r.returncode: - raise AssertionError(f"spirv-as failed:\n{r.stderr}") - r = subprocess.run([spirv_val, "--target-env", "vulkan1.2", spv], - capture_output=True, text=True) - if r.returncode: - raise AssertionError(f"spirv-val failed:\n{r.stderr}") - - -def _w32_fssm(): - if SHADERS not in sys.path: - sys.path.insert(0, SHADERS) - from compute_fixture import compute_header - return bytes(compute_header(os.path.join(SHADERS, "cs_w32_mask_imm.asm"))) - - -def _run_cs_w32(name, lines, n_words=32): - spvasm = support.translate_lines(name, lines, fssm=_w32_fssm()) - _validate_spv(spvasm) - mem = {4 * i: 0 for i in range(n_words)} - si.run_workgroup( - spvasm, 32, 32, - inputs_for=lambda i: {"%wg_id": (0, 0, 0), "%local_id": (i, 0, 0), "%sg_lane": i}, - push_constants=[0, 0, 0xFFFFFFFF, 0x31016FAC] + [0] * 28, - memory=mem, - ) - return [mem[4 * i] for i in range(n_words)] - - -class ValuCmpClassTests(unittest.TestCase): - def test_f32_all_ten_ieee_classes_exact(self): - # Pack all 10 single-bit class probes into a 10-bit bitmask per input value in one shader batch. - for tag, bits, expected_bit in F32_CLASSES: - with self.subTest(f32=tag): - lines = [f"v_mov_b32_e32 v1, {bits:#x}", "v_mov_b32_e32 v4, 0"] - for b in range(10): - lines += [ - f"v_cmp_class_f32_e64 vcc_lo, v1, {1 << b:#x}", - "v_cndmask_b32_e64 v3, 0, 1, vcc_lo", - f"v_lshlrev_b32_e32 v3, {b}, v3", - "v_or_b32_e32 v4, v4, v3", - ] - lines += [ - "v_mov_b32_e32 v2, 0", - "v_cmpx_eq_u32_e32 0, v0", - "buffer_store_dword v4, v2, s[0:3], 0 offen", - "s_endpgm", - ] - got = _run_cs_w32(f"cs_cmp_class_f32_{tag}", lines, n_words=1)[0] - self.assertEqual(got, 1 << expected_bit) - - def test_f64_all_ten_ieee_classes_exact(self): - for tag, bits, expected_bit in F64_CLASSES: - with self.subTest(f64=tag): - lo, hi = bits & 0xFFFFFFFF, (bits >> 32) & 0xFFFFFFFF - lines = [ - f"v_mov_b32_e32 v2, {lo:#x}", - f"v_mov_b32_e32 v3, {hi:#x}", - "v_mov_b32_e32 v4, 0", - ] - for b in range(10): - lines += [ - f"v_cmp_class_f64_e64 vcc_lo, v[2:3], {1 << b:#x}", - "v_cndmask_b32_e64 v6, 0, 1, vcc_lo", - f"v_lshlrev_b32_e32 v6, {b}, v6", - "v_or_b32_e32 v4, v4, v6", - ] - lines += [ - "v_mov_b32_e32 v5, 0", - "v_cmpx_eq_u32_e32 0, v0", - "buffer_store_dword v4, v5, s[0:3], 0 offen", - "s_endpgm", - ] - got = _run_cs_w32(f"cs_cmp_class_f64_{tag}", lines, n_words=1)[0] - self.assertEqual(got, 1 << expected_bit) - - def test_composite_masks_e32_and_ignored_high_mask_bits(self): - lines = [ - "v_mov_b32_e32 v1, 0x7FC00000", # qNaN (bit 1) - "v_mov_b32_e32 v2, 0xFF800000", # -Inf (bit 2) - "v_mov_b32_e32 v3, 0x80000000", # -0.0 (bit 5) - "v_mov_b32_e32 v10, 0x00000003", # NaN mask - "v_cmp_class_f32_e32 vcc_lo, v1, v10", - "v_cndmask_b32_e64 v20, 0, 1, vcc_lo", - "v_mov_b32_e32 v11, 0x00000204", # +/-Inf mask - "v_cmp_class_f32_e32 vcc_lo, v2, v11", - "v_cndmask_b32_e64 v21, 0, 1, vcc_lo", - "v_mov_b32_e32 v12, 0x00000060", # +/-0 mask - "v_cmp_class_f32_e32 vcc_lo, v3, v12", - "v_cndmask_b32_e64 v22, 0, 1, vcc_lo", - # Only bits >= 10 set -> must return 0 for every class - "v_mov_b32_e32 v13, 0xFFFFFC00", - "v_cmp_class_f32_e32 vcc_lo, v3, v13", - "v_cndmask_b32_e64 v23, 0, 1, vcc_lo", - "v_mov_b32_e32 v5, 0", - "v_cmpx_eq_u32_e32 0, v0", - "buffer_store_dwordx4 v[20:23], v5, s[0:3], 0 offen", - "s_endpgm", - ] - self.assertEqual(_run_cs_w32("cs_cmp_class_composite", lines, n_words=4), [1, 1, 1, 0]) - - def test_vop3_abs_and_neg_modifiers_f32_and_f64(self): - lines = [ - "v_mov_b32_e32 v1, 0x3F800000", # +1.0 - "v_mov_b32_e32 v2, 0xFF800000", # -Inf - "v_mov_b32_e32 v3, 0x00000000", # +0.0 - "v_mov_b32_e32 v6, 0x00000000", - "v_mov_b32_e32 v7, 0xFFF00000", # f64 -Inf - # -(+1.0) -> neg_normal (bit 3 = 0x008) - "v_cmp_class_f32_e64 vcc_lo, -v1, 0x008", - "v_cndmask_b32_e64 v20, 0, 1, vcc_lo", - # |-Inf| -> pos_inf (bit 9 = 0x200) - "v_cmp_class_f32_e64 vcc_lo, |v2|, 0x200", - "v_cndmask_b32_e64 v21, 0, 1, vcc_lo", - # -|+0.0| -> neg_zero (bit 5 = 0x020) - "v_cmp_class_f32_e64 vcc_lo, -|v3|, 0x020", - "v_cndmask_b32_e64 v22, 0, 1, vcc_lo", - # f64 |-Inf| -> pos_inf (bit 9 = 0x200) - "v_cmp_class_f64_e64 vcc_lo, |v[6:7]|, 0x200", - "v_cndmask_b32_e64 v23, 0, 1, vcc_lo", - "v_mov_b32_e32 v5, 0", - "v_cmpx_eq_u32_e32 0, v0", - "buffer_store_dwordx4 v[20:23], v5, s[0:3], 0 offen", - "s_endpgm", - ] - self.assertEqual(_run_cs_w32("cs_cmp_class_mods", lines, n_words=4), [1, 1, 1, 1]) - - def test_cmpx_class_f32_and_f64_update_exec_per_lane(self): - # Even lanes hold +Inf, odd lanes hold +0.0 -> v_cmpx_class_* with pos_inf (0x200) keeps even lanes active. - lines_f32 = [ - "v_and_b32_e32 v1, 1, v0", - "v_cmp_eq_u32_e32 vcc_lo, 0, v1", - "v_cndmask_b32_e64 v2, 0, 0x7F800000, vcc_lo", - "v_mov_b32_e32 v3, 0x1111", - "v_mov_b32_e32 v4, 0x200", - "v_cmpx_class_f32_e32 v2, v4", - "v_mov_b32_e32 v3, 0x2222", - "s_mov_b32 exec_lo, -1", - "v_lshlrev_b32_e32 v5, 2, v0", - "buffer_store_dword v3, v5, s[0:3], 0 offen", - "s_endpgm", - ] - want = [0x2222 if (i % 2 == 0) else 0x1111 for i in range(32)] - self.assertEqual(_run_cs_w32("cs_cmpx_class_f32", lines_f32, n_words=32), want) - - lines_f64 = [ - "v_and_b32_e32 v1, 1, v0", - "v_cmp_eq_u32_e32 vcc_lo, 0, v1", - "v_mov_b32_e32 v2, 0", - "v_cndmask_b32_e64 v3, 0, 0x7FF00000, vcc_lo", - "v_mov_b32_e32 v4, 0x3333", - "v_mov_b32_e32 v6, 0x200", - "v_cmpx_class_f64_e32 v[2:3], v6", - "v_mov_b32_e32 v4, 0x4444", - "s_mov_b32 exec_lo, -1", - "v_lshlrev_b32_e32 v5, 2, v0", - "buffer_store_dword v4, v5, s[0:3], 0 offen", - "s_endpgm", - ] - want64 = [0x4444 if (i % 2 == 0) else 0x3333 for i in range(32)] - self.assertEqual(_run_cs_w32("cs_cmpx_class_f64", lines_f64, n_words=32), want64) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_valu_cube.py b/tests/semantic/test_valu_cube.py deleted file mode 100644 index e964be024..000000000 --- a/tests/semantic/test_valu_cube.py +++ /dev/null @@ -1,355 +0,0 @@ -"""Semantic value tests for RDNA2 cube-map VALU ops: v_cubeid_f32, v_cubesc_f32, v_cubetc_f32, v_cubema_f32. - -Each test translates a synthetic pixel shader with tools/rdna2spirv.py, runs it in tests/semantic/spirv_mini_interp.py, -and compares the four exported mrt0 binary32 words (face_id, sc, tc, ma) against a plain-Python reference oracle. - -RDNA2 ISA cube-map formulas for inputs (S0.f, S1.f, S2.f) = (x, y, z): - Major axis & face selection (Z wins ties over Y and X; Y wins ties over X): - if |z| >= |x| and |z| >= |y|: major = Z (z < 0 -> face 5.0 [-Z], else 4.0 [+Z]) - elif |y| >= |x|: major = Y (y < 0 -> face 3.0 [-Y], else 2.0 [+Y]) - else: major = X (x < 0 -> face 1.0 [-X], else 0.0 [+X]) - - Projected face coordinates (sc, tc) and major axis (ma): - +X (0.0): sc = -z, tc = -y, ma = 2.0 * x - -X (1.0): sc = +z, tc = -y, ma = 2.0 * x - +Y (2.0): sc = +x, tc = +z, ma = 2.0 * y - -Y (3.0): sc = +x, tc = -z, ma = 2.0 * y - +Z (4.0): sc = +x, tc = -y, ma = 2.0 * z - -Z (5.0): sc = -x, tc = -y, ma = 2.0 * z - -Note on v_cubema_f32: RDNA2 ISA returns 2.0 * signed_major_axis (negative on -X/-Y/-Z faces), so |v_cubema_f32| equals -2.0 * max(|x|, |y|, |z|). That is why hardware cube-sampling sequences such as runtime/test/shaders/ps_cube_sample.asm -follow v_cubema_f32 with `v_rcp_f32_e64 dst, |src|`. -""" -import itertools -import math -import os -import struct -import sys -import tempfile -import unittest -import warnings - -HERE = os.path.dirname(os.path.abspath(__file__)) -ROOT = os.path.dirname(os.path.dirname(HERE)) -TOOLS_DIR = os.environ.get("LEONIDA_TOOLS_DIR") or os.path.join(ROOT, "tools") - -sys.dont_write_bytecode = True -sys.path.insert(0, TOOLS_DIR) -sys.path.insert(0, HERE) - -import rdna2spirv # noqa: E402 -import spirv_mini_interp as si # noqa: E402 - -STUB_DXBC = b"DXBC" + bytes(24) + struct.pack(" float: - try: - return struct.unpack(" int: - return struct.unpack(" float: - return struct.unpack(" tuple[float, float, float, float]: - """Independent RDNA2 ISA reference returning binary32 (face_id, sc, tc, ma).""" - x, y, z = f32(x), f32(y), f32(z) - ax, ay, az = abs(x), abs(y), abs(z) - # Measured natively on RDNA2 (gfx1036): v_cubema_f32 returns +0.0 (never -0.0) when the major axis is ±0.0. - ma = lambda v: 0.0 if v == 0.0 else f32(2.0 * v) # noqa: E731 - if az >= ax and az >= ay: - if z < 0.0: - return (5.0, f32(-x), f32(-y), ma(z)) - return (4.0, x, f32(-y), ma(z)) - if ay >= ax: - if y < 0.0: - return (3.0, x, f32(-z), ma(y)) - return (2.0, x, z, ma(y)) - if x < 0.0: - return (1.0, z, f32(-y), ma(x)) - return (0.0, f32(-z), f32(-y), ma(x)) - - -def ref_cube_words(x: float, y: float, z: float) -> tuple[int, int, int, int]: - return tuple(f32_bits(v) for v in ref_cube(x, y, z)) - - -# Hand-worked (x, y, z) -> expected (face_id, sc, tc, ma) constants across all 6 faces and ties. -HAND_WORKED = ( - # All 6 faces with asymmetric coordinates - ((4.0, -1.5, 0.75), (0.0, -0.75, 1.5, 8.0)), # +X - ((-4.0, 1.5, -0.75), (1.0, -0.75, -1.5, -8.0)), # -X - ((1.25, 3.0, -0.5), (2.0, 1.25, -0.5, 6.0)), # +Y - ((-1.25, -3.0, 0.5), (3.0, -1.25, -0.5, -6.0)), # -Y - ((-0.5, 1.25, 2.5), (4.0, -0.5, -1.25, 5.0)), # +Z - ((0.5, -1.25, -2.5), (5.0, -0.5, 1.25, -5.0)), # -Z - # Tie cases: |x| == |y| (> |z|) -> Y wins; |y| == |z| (> |x|) -> Z wins; |x| == |y| == |z| -> Z wins - ((2.0, 2.0, 0.5), (2.0, 2.0, 0.5, 4.0)), # +Y beats +X - ((2.0, -2.0, 0.5), (3.0, 2.0, -0.5, -4.0)), # -Y beats +X - ((-2.0, 2.0, -0.5), (2.0, -2.0, -0.5, 4.0)), # +Y beats -X - ((-2.0, -2.0, -0.5), (3.0, -2.0, 0.5, -4.0)), # -Y beats -X - ((0.5, 2.0, 2.0), (4.0, 0.5, -2.0, 4.0)), # +Z beats +Y - ((0.5, -2.0, -2.0), (5.0, -0.5, 2.0, -4.0)), # -Z beats -Y - ((1.5, -1.5, 1.5), (4.0, 1.5, 1.5, 3.0)), # +Z wins 3-way tie - ((-1.5, 1.5, -1.5), (5.0, 1.5, -1.5, -3.0)), # -Z wins 3-way tie -) - - -_TMP_DIR = None -_SRC_PATH = None - - -def setUpModule(): - global _TMP_DIR, _SRC_PATH - _TMP_DIR = tempfile.TemporaryDirectory() - disasm_dir = os.path.join(_TMP_DIR.name, "disasm") - os.mkdir(disasm_dir) - _SRC_PATH = os.path.join(disasm_dir, "ps_cube.s") - with open(os.path.join(_TMP_DIR.name, "ps_cube.dxbc"), "wb") as f: - f.write(STUB_DXBC) - - -def tearDownModule(): - global _TMP_DIR - if _TMP_DIR is not None: - _TMP_DIR.cleanup() - _TMP_DIR = None - - -def run_lines(lines: list[str]) -> tuple[int, int, int, int]: - """Translate `lines` with exp mrt0 v0, v1, v5, v6 and return the four 32-bit words.""" - if _TMP_DIR is None: - setUpModule() - asm = ("; test_valu_cube\n" - + "".join(f"\t{ln}\n" for ln in lines) - + "\texp mrt0 v0, v1, v5, v6 done vm\n\ts_endpgm\n") - with open(_SRC_PATH, "w", encoding="utf-8") as f: - f.write(asm) - with warnings.catch_warnings(): - warnings.simplefilter("ignore", ResourceWarning) - spv = rdna2spirv.translate(_SRC_PATH) - return tuple(si.run_fragment(spv)["%out_mrt0"]) - - -def run_cube(x_bits: int, y_bits: int, z_bits: int, suffix: str = "", srcs: str = "v2, v3, v4", - mods: str = "") -> tuple[int, int, int, int]: - mod_s = f" {mods}" if mods else "" - return run_lines([ - f"v_mov_b32 v2, {x_bits:#x}", - f"v_mov_b32 v3, {y_bits:#x}", - f"v_mov_b32 v4, {z_bits:#x}", - f"v_cubeid_f32{suffix} v0, {srcs}{mod_s}", - f"v_cubesc_f32{suffix} v1, {srcs}{mod_s}", - f"v_cubetc_f32{suffix} v5, {srcs}{mod_s}", - f"v_cubema_f32{suffix} v6, {srcs}{mod_s}", - ]) - - -class OracleTests(unittest.TestCase): - """Hand-worked constants agree with the plain-Python reference oracle.""" - - def test_hand_worked_cases(self): - for xyz, want in HAND_WORKED: - with self.subTest(xyz=xyz): - self.assertEqual(ref_cube(*xyz), want) - self.assertEqual(ref_cube_words(*xyz), tuple(f32_bits(v) for v in want)) - - def test_signed_zero_negations_and_origin(self): - # (1, 0, 0) on +X: sc = -z = -0.0, tc = -y = -0.0 - self.assertEqual(ref_cube_words(1.0, 0.0, 0.0), (0x00000000, 0x80000000, 0x80000000, 0x40000000)) - # (0, 0, 0) picks +Z (|z| >= |x| and |z| >= |y|, z not < 0): tc = -y = -0.0 - self.assertEqual(ref_cube_words(0.0, 0.0, 0.0), (0x40800000, 0x00000000, 0x80000000, 0x00000000)) - - -class CubeValuTests(unittest.TestCase): - def assert_cube(self, x: float, y: float, z: float, suffix: str = ""): - xb, yb, zb = f32_bits(x), f32_bits(y), f32_bits(z) - got = run_cube(xb, yb, zb, suffix=suffix) - want = ref_cube_words(x, y, z) - self.assertEqual(got, want, f"xyz=({x}, {y}, {z}) got={[hex(w) for w in got]} want={[hex(w) for w in want]}") - # Also confirm |v_cubema_f32| == 2.0 * max(|x|, |y|, |z|). - got_ma = bits_f32(got[3]) - self.assertEqual(abs(got_ma), f32(2.0 * max(abs(f32(x)), abs(f32(y)), abs(f32(z))))) - - def test_all_six_faces(self): - faces = [ - ("+X", (4.0, -1.5, 0.75)), - ("+X_unit", (1.0, 0.5, -0.25)), - ("-X", (-4.0, 1.5, -0.75)), - ("-X_unit", (-2.0, -0.5, 1.25)), - ("+Y", (1.25, 3.0, -0.5)), - ("+Y_asym", (-0.75, 2.5, 1.5)), - ("-Y", (-1.25, -3.0, 0.5)), - ("-Y_asym", (0.75, -2.5, -1.5)), - ("+Z", (-0.5, 1.25, 2.5)), - ("+Z_asym", (1.5, -0.75, 4.0)), - ("-Z", (0.5, -1.25, -2.5)), - ("-Z_asym", (-1.5, 0.75, -4.0)), - ] - for label, (x, y, z) in faces: - with self.subTest(face=label, x=x, y=y, z=z): - self.assert_cube(x, y, z) - - def test_major_axis_doubling_boundary(self): - for major_bits, expected_ma in ((0x7EFFFFFF, 0x7F7FFFFF), (0x7F000000, 0x7F800000), - (0xFEFFFFFF, 0xFF7FFFFF), (0xFF000000, 0xFF800000)): - with self.subTest(major_bits=hex(major_bits)): - major = bits_f32(major_bits) - self.assertEqual(ref_cube_words(major, 1.0, 1.0)[3], expected_ma) - self.assert_cube(major, 1.0, 1.0) - - def test_axis_tie_cases(self): - # |x| == |y| with |z| < |x| -> Y wins over X for all sign combinations. - for sx, sy, sz in itertools.product((-1.0, 1.0), repeat=3): - x, y, z = 2.0 * sx, 2.0 * sy, 0.5 * sz - with self.subTest(tie="xy", x=x, y=y, z=z): - got = run_cube(f32_bits(x), f32_bits(y), f32_bits(z)) - self.assertIn(bits_f32(got[0]), (2.0, 3.0)) - self.assertEqual(got, ref_cube_words(x, y, z)) - - # |y| == |z| with |x| < |z| -> Z wins over Y for all sign combinations. - for sx, sy, sz in itertools.product((-1.0, 1.0), repeat=3): - x, y, z = 0.5 * sx, 2.0 * sy, 2.0 * sz - with self.subTest(tie="yz", x=x, y=y, z=z): - got = run_cube(f32_bits(x), f32_bits(y), f32_bits(z)) - self.assertIn(bits_f32(got[0]), (4.0, 5.0)) - self.assertEqual(got, ref_cube_words(x, y, z)) - - # |x| == |z| with |y| < |z| -> Z wins over X for all sign combinations. - for sx, sy, sz in itertools.product((-1.0, 1.0), repeat=3): - x, y, z = 2.0 * sx, 0.5 * sy, 2.0 * sz - with self.subTest(tie="xz", x=x, y=y, z=z): - got = run_cube(f32_bits(x), f32_bits(y), f32_bits(z)) - self.assertIn(bits_f32(got[0]), (4.0, 5.0)) - self.assertEqual(got, ref_cube_words(x, y, z)) - - # 3-way tie |x| == |y| == |z| -> Z wins for all 8 sign combinations. - for sx, sy, sz in itertools.product((-1.0, 1.0), repeat=3): - x, y, z = 1.5 * sx, 1.5 * sy, 1.5 * sz - with self.subTest(tie="xyz", x=x, y=y, z=z): - got = run_cube(f32_bits(x), f32_bits(y), f32_bits(z)) - self.assertIn(bits_f32(got[0]), (4.0, 5.0)) - self.assertEqual(got, ref_cube_words(x, y, z)) - - def test_zero_and_negative_coordinates(self): - cases = [ - (0.0, 0.0, 0.0), - (1.0, 0.0, 0.0), - (-1.0, 0.0, 0.0), - (0.0, 1.0, 0.0), - (0.0, -1.0, 0.0), - (0.0, 0.0, 1.0), - (0.0, 0.0, -1.0), - (-0.125, -0.375, -0.25), - (-0.6, -0.3, -0.9), - (-64.5, -12.25, -3.75), - (0.3, -0.6, -0.15), - ] - for x, y, z in cases: - with self.subTest(x=x, y=y, z=z): - self.assert_cube(x, y, z) - - def test_signed_zero_triples_and_nan_cubema(self): - # Measured natively on RDNA2 (gfx1036, wave32 & wave64, all 4 IEEE/DX10_CLAMP modes): - # v_cubema_f32 returns +0.0 (0x00000000) for every (±0.0, ±0.0, ±0.0) triple, including - # when z is -0.0 (or negated from +0.0 via -v4) and with output modifiers like mul:2. - for xb, yb, zb in itertools.product((0x00000000, 0x80000000), repeat=3): - with self.subTest(bits=(hex(xb), hex(yb), hex(zb))): - got = run_cube(xb, yb, zb) - want = ref_cube_words(bits_f32(xb), bits_f32(yb), bits_f32(zb)) - self.assertEqual(got, want) - self.assertEqual(got[3], 0x00000000) - self.assertEqual(run_cube(0x00000000, 0x00000000, 0x00000000, srcs="v2, v3, -v4")[3], 0x00000000) - self.assertEqual(run_cube(0x00000000, 0x00000000, 0x80000000, mods="mul:2")[3], 0x00000000) - # NaN on the selected major axis is preserved; -0.0 selected with NaN on other axes still gives +0.0. - self.assertEqual(run_cube(0xFFC00000, 0x3F800000, 0x3F800000)[3], 0xFFC00000) - self.assertEqual(run_cube(0x80000000, 0x7FC00000, 0x7FC00000)[3], 0x00000000) - - def test_vop3_e64_suffix_and_source_modifiers(self): - # _e64 form matches unsuffixed VOP3 form. - self.assert_cube(-0.75, 2.5, -3.25, suffix="_e64") - - # Source modifiers apply before face selection: (-v2, |v3|, -|v4|). - vectors = [ - (1.0, -3.0, 2.0), - (-4.0, -1.5, -0.5), - (0.25, 0.5, -2.5), - ] - for x, y, z in vectors: - with self.subTest(x=x, y=y, z=z): - got = run_cube(f32_bits(x), f32_bits(y), f32_bits(z), srcs="-v2, |v3|, -|v4|") - want = ref_cube_words(-f32(x), abs(f32(y)), -abs(f32(z))) - self.assertEqual(got, want) - - def test_inline_constants_sgpr_and_dst_aliasing(self): - # Inline float constants + SGPR operand. - got = run_lines([ - f"s_mov_b32 s4, {f32_bits(-2.0):#x}", - "v_cubeid_f32 v0, 1.0, s4, 0.5", - "v_cubesc_f32 v1, 1.0, s4, 0.5", - "v_cubetc_f32 v5, 1.0, s4, 0.5", - "v_cubema_f32 v6, 1.0, s4, 0.5", - ]) - self.assertEqual(got, ref_cube_words(1.0, -2.0, 0.5)) - - # Destination register aliasing one of the source registers (v2). - got_alias = run_lines([ - f"v_mov_b32 v2, {f32_bits(1.25):#x}", - f"v_mov_b32 v3, {f32_bits(-3.0):#x}", - f"v_mov_b32 v4, {f32_bits(0.5):#x}", - "v_cubesc_f32 v1, v2, v3, v4", - "v_cubetc_f32 v5, v2, v3, v4", - "v_cubema_f32 v6, v2, v3, v4", - "v_cubeid_f32 v2, v2, v3, v4", - "v_mov_b32 v0, v2", - ]) - self.assertEqual(got_alias, ref_cube_words(1.25, -3.0, 0.5)) - - def test_output_modifiers_mul_div_clamp(self): - x, y, z = 0.75, -0.5, -2.0 # -Z: id=5.0, sc=-0.75, tc=0.5, ma=-4.0 - # clamp saturates to [0.0, 1.0]: 5.0 -> 1.0, -0.75 -> 0.0, 0.5 -> 0.5, -4.0 -> 0.0 - got_clamp = run_cube(f32_bits(x), f32_bits(y), f32_bits(z), mods="clamp") - self.assertEqual(got_clamp, tuple(f32_bits(v) for v in (1.0, 0.0, 0.5, 0.0))) - - # div:2 halves each result (giving signed major axis directly on v_cubema_f32). - got_div2 = run_cube(f32_bits(x), f32_bits(y), f32_bits(z), mods="div:2") - self.assertEqual(got_div2, tuple(f32_bits(v * 0.5) for v in ref_cube(x, y, z))) - - # mul:2 doubles each result. - got_mul2 = run_cube(f32_bits(x), f32_bits(y), f32_bits(z), mods="mul:2") - self.assertEqual(got_mul2, tuple(f32_bits(v * 2.0) for v in ref_cube(x, y, z))) - - def test_exec_mask_preserves_inactive_lane(self): - got = run_lines([ - "v_mov_b32 v0, 0x11111111", - "v_mov_b32 v1, 0x22222222", - "v_mov_b32 v5, 0x33333333", - "v_mov_b32 v6, 0x44444444", - f"v_mov_b32 v2, {f32_bits(1.0):#x}", - f"v_mov_b32 v3, {f32_bits(2.0):#x}", - f"v_mov_b32 v4, {f32_bits(-3.0):#x}", - "s_mov_b32 exec_lo, 0", - "v_cubeid_f32 v0, v2, v3, v4", - "v_cubesc_f32 v1, v2, v3, v4", - "v_cubetc_f32 v5, v2, v3, v4", - "v_cubema_f32 v6, v2, v3, v4", - "s_mov_b32 exec_lo, 1", - ]) - self.assertEqual(got, (0x11111111, 0x22222222, 0x33333333, 0x44444444)) - - def test_negative_control_swapped_axes_changes_output(self): - base = run_cube(f32_bits(1.25), f32_bits(-3.0), f32_bits(0.5)) - swapped = run_cube(f32_bits(1.25), f32_bits(-3.0), f32_bits(0.5), srcs="v3, v2, v4") - self.assertNotEqual(base, swapped) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_valu_cvt_f16_int16_mods.py b/tests/semantic/test_valu_cvt_f16_int16_mods.py deleted file mode 100644 index 7141fbf19..000000000 --- a/tests/semantic/test_valu_cvt_f16_int16_mods.py +++ /dev/null @@ -1,80 +0,0 @@ -"""Value tests for v_cvt_f16_{u16,i16} output modifiers (clamp, mul:2, mul:4, div:2) and SDWA clamp. - -Each case translates a hand-written pixel-shader listing with tools/rdna2spirv.py -and executes the resulting SPIR-V via tests/semantic/spirv_mini_interp.py. -Standard library only. -""" -import os -import sys -import unittest - -HERE = os.path.dirname(os.path.abspath(__file__)) -if HERE not in sys.path: - sys.path.insert(0, HERE) - -from support import mrt0_words, translate_lines # noqa: E402 (support puts tools/ on sys.path) -import rdna2spirv # noqa: E402 - - -def run_ps(lines): - return mrt0_words(translate_lines("ps_cvt_f16_mods", lines)) - - -class CvtF16Int16OutputMods(unittest.TestCase): - def test_vop3_clamp_u16_and_i16(self): - words = run_ps([ - "v_mov_b32 v0, 0xdead0005", - "v_cvt_f16_u16 v0, v0 clamp", - "v_mov_b32 v1, 0xbeef0000", - "v_cvt_f16_u16 v1, v1 clamp", - "v_mov_b32 v2, 0xcafeffff", - "v_cvt_f16_i16 v2, v2 clamp", - "v_mov_b32 v3, 0x0003abcd", - "v_cvt_f16_i16_sdwa v3, v3 clamp dst_sel:WORD_0 dst_unused:UNUSED_PRESERVE src0_sel:WORD_1", - "exp mrt0 v0, v1, v2, v3 done vm", - "s_endpgm", - ]) - self.assertEqual(words[0], 0xDEAD3C00) # 5 -> clamped to 1.0 (0x3c00), high half kept - self.assertEqual(words[1], 0xBEEF0000) # 0 -> 0.0 - self.assertEqual(words[2], 0xCAFE0000) # -1 -> clamped to +0.0 - self.assertEqual(words[3], 0x00033C00) # SDWA src0_sel:WORD_1 (3) -> clamped to 1.0 in WORD_0, WORD_1 kept - - def test_vop3_omod_scaling_and_clamp(self): - words = run_ps([ - "v_mov_b32 v0, 3", - "v_cvt_f16_u16 v0, v0 mul:2", - "v_mov_b32 v1, 0xffff", - "v_cvt_f16_i16 v1, v1 mul:4", - "v_mov_b32 v2, 3", - "v_cvt_f16_i16 v2, v2 div:2", - "v_mov_b32 v3, 1", - "v_cvt_f16_u16 v3, v3 clamp div:2", - "exp mrt0 v0, v1, v2, v3 done vm", - "s_endpgm", - ]) - # Under default MODE (denorm16_64=3), RDNA2 silicon ignores omod on f16 destinations while clamp applies. - self.assertEqual(words[0] & 0xFFFF, 0x4200) # 3.0 (omod ignored) - self.assertEqual(words[1] & 0xFFFF, 0xBC00) # -1.0 (omod ignored) - self.assertEqual(words[2] & 0xFFFF, 0x4200) # 3.0 (omod ignored) - self.assertEqual(words[3] & 0xFFFF, 0x3C00) # 1.0 (clamped, omod ignored) - - def test_sdwa_clamp(self): - words = run_ps([ - "v_mov_b32 v0, 0x1234fffe", - "v_cvt_f16_i16_sdwa v0, v0 clamp dst_sel:WORD_1 dst_unused:UNUSED_PRESERVE src0_sel:WORD_0", - "v_mov_b32 v1, 0x00020000", - "v_cvt_f16_u16_sdwa v1, v1 clamp dst_sel:WORD_0 dst_unused:UNUSED_PAD src0_sel:WORD_1", - "exp mrt0 v0, v1, v1, v1 done vm", - "s_endpgm", - ]) - self.assertEqual(words[0], 0x0000FFFE) # -2 clamped to +0.0 in WORD_1, WORD_0 preserved - self.assertEqual(words[1], 0x00003C00) # 2 clamped to 1.0 in WORD_0, WORD_1 padded with 0 - - def test_f16_to_int16_output_modifiers_still_rejected(self): - for op in ("v_cvt_u16_f16", "v_cvt_i16_f16"): - with self.subTest(op=op), self.assertRaises(rdna2spirv.Unsupported): - translate_lines("ps_cvt_f16_reject", [f"{op} v0, v0 clamp", "exp mrt0 v0, v0, v0, v0 done vm", "s_endpgm"]) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_valu_cvt_f32_f64.py b/tests/semantic/test_valu_cvt_f32_f64.py deleted file mode 100644 index b860ecc98..000000000 --- a/tests/semantic/test_valu_cvt_f32_f64.py +++ /dev/null @@ -1,1825 +0,0 @@ -"""Semantic interpreter tests and reference mathematical oracle for RDNA2 v_cvt_f32_f64 and v_cvt_f64_f32. - -Models IEEE 754-2008 / IEEE 754-2019 binary32 <-> binary64 floating-point conversions and AMD RDNA2 / GFX10 -Vector Arithmetic Logic Unit (VALU) architectural semantics: - - v_cvt_f32_f64: D.f = (float)S0.d (double-precision binary64 to single-precision binary32) - - v_cvt_f64_f32: D.d = (double)S0.f (single-precision binary32 to double-precision binary64) - -RDNA2 Floating-Point Conversion ISA Rules: - 1. Register Widths and Alignment: - - v_cvt_f32_f64: Destination is a single 32-bit VGPR (v[d]). Source is an aligned 64-bit pair - (v[s:s+1] or s[s:s+1]) or 64-bit immediate. - - v_cvt_f64_f32: Destination is an aligned 64-bit pair (v[d:d+1]). Source is a single 32-bit - VGPR (v[s]) or SGPR (s[s]) or 32-bit immediate. - 2. Rounding Mode: - - Round-to-nearest-even (IEEE 754 roundTiesToEven) is standard. - - v_cvt_f64_f32 is exact for all finite binary32 values without loss of precision. - - v_cvt_f32_f64 rounds 53 mantissa bits to 24 bits with tie-breaking to even LSB. - 3. Boundary Extremes & Special Values: - - Signed Zeros: +0.0 and -0.0 are preserved across conversions (+0.0 <-> +0.0, -0.0 <-> -0.0). - - Infinities: +inf and -inf convert to corresponding target infinities (+inf <-> +inf, -inf <-> -inf). - - Overflow: In v_cvt_f32_f64, magnitudes >= 2^128 - 2^104 round to +-infinity. - - Subnormals: - * f32 subnormals convert exactly to normalized f64 numbers without precision loss. - * f64 subnormals (magnitudes < 2^-1022) underflow and round to +-0.0 in f32. - * f64 numbers in range [2^-149, 2^-126) convert to f32 subnormals under roundTiesToEven. - 4. NaN Propagation: - - Input NaN produces a canonical quiet NaN in the target format (f32: 0x7FC00000, f64: 0x7FF8000000000000). - - Signaling NaN inputs trigger the IEEE invalid operation status flag. - 5. VOP1 / VOP3 Encoding and Modifiers: - - VOP1 (e32): Compact encoding without modifiers. - - VOP3 (e64): Extended encoding supporting input modifiers: - * abs (|x|): Clears sign bit before conversion. - * neg (-x): Inverts sign bit before conversion. - * neg(abs(x)): Inverts sign after abs (forcing negative). - * clamp: Clamps converted result to [0.0, 1.0]. Clamping negative values or -0.0 yields +0.0. - Clamping NaN returns NaN unclamped. - -Standard library Python only; zero third-party dependencies; zero game data. -Python 3.9+ compatible (from __future__ import annotations). -""" -from __future__ import annotations - -import dataclasses -import enum -import math -import struct -import unittest - -MASK32: int = 0xFFFFFFFF -MASK64: int = 0xFFFFFFFFFFFFFFFF - -# IEEE 754 binary32 Bit Patterns -SIGN_MASK_F32: int = 0x80000000 -EXP_MASK_F32: int = 0x7F800000 -MANT_MASK_F32: int = 0x007FFFFF -QUIET_NAN_BIT_F32: int = 0x00400000 - -POS_ZERO_F32: int = 0x00000000 -NEG_ZERO_F32: int = 0x80000000 -POS_ONE_F32: int = 0x3F800000 # 1.0f -NEG_ONE_F32: int = 0xBF800000 # -1.0f -POS_TWO_F32: int = 0x40000000 # 2.0f -NEG_TWO_F32: int = 0xC0000000 # -2.0f -HALF_F32: int = 0x3F000000 # 0.5f -NEG_HALF_F32: int = 0xBF000000 # -0.5f -POS_TEN_F32: int = 0x41200000 # 10.0f -NEG_TEN_F32: int = 0xC1200000 # -10.0f - -FLT_MIN: int = 0x00800000 # Smallest positive normal f32: 2^-126 -NEG_FLT_MIN: int = 0x80800000 # -2^-126 -FLT_MAX: int = 0x7F7FFFFF # Largest positive normal f32: (2 - 2^-23) * 2^127 -NEG_FLT_MAX: int = 0xFF7FFFFF -POS_INF_F32: int = 0x7F800000 # +infinity f32 -NEG_INF_F32: int = 0xFF800000 # -infinity f32 -QNAN_F32: int = 0x7FC00000 # Canonical quiet NaN f32 -NEG_QNAN_F32: int = 0xFFC00000 # Negative quiet NaN f32 -QNAN_PAYLOAD_A_F32: int = 0x7FC00001 -QNAN_PAYLOAD_B_F32: int = 0xFFC10002 -SNAN_F32: int = 0x7F800001 # Signaling NaN (MSB of mantissa is 0, payload != 0) -SUBNORM_MIN_F32: int = 0x00000001 # Smallest positive subnormal f32: 2^-149 -SUBNORM_MAX_F32: int = 0x007FFFFF # Largest positive subnormal f32: (1 - 2^-23) * 2^-126 -NEG_SUBNORM_MIN_F32: int = 0x80000001 -NEG_SUBNORM_MAX_F32: int = 0x807FFFFF - -# IEEE 754 binary64 Bit Patterns -SIGN_MASK_F64: int = 0x8000000000000000 -EXP_MASK_F64: int = 0x7FF0000000000000 -MANT_MASK_F64: int = 0x000FFFFFFFFFFFFF -QUIET_NAN_BIT_F64: int = 0x0008000000000000 - -POS_ZERO_F64: int = 0x0000000000000000 -NEG_ZERO_F64: int = 0x8000000000000000 -POS_ONE_F64: int = 0x3FF0000000000000 # 1.0 -NEG_ONE_F64: int = 0xBFF0000000000000 # -1.0 -POS_TWO_F64: int = 0x4000000000000000 # 2.0 -NEG_TWO_F64: int = 0xC000000000000000 # -2.0 -HALF_F64: int = 0x3FE0000000000000 # 0.5 -NEG_HALF_F64: int = 0xBFE0000000000000 # -0.5 -POS_TEN_F64: int = 0x4024000000000000 # 10.0 -NEG_TEN_F64: int = 0xC024000000000000 # -10.0 - -DBL_MIN: int = 0x0010000000000000 # Smallest positive normal f64: 2^-1022 -NEG_DBL_MIN: int = 0x8010000000000000 # -2^-1022 -DBL_MAX: int = 0x7FEFFFFFFFFFFFFF # Largest positive normal f64 -NEG_DBL_MAX: int = 0xFFEFFFFFFFFFFFFF -POS_INF_F64: int = 0x7FF0000000000000 # +infinity f64 -NEG_INF_F64: int = 0xFFF0000000000000 # -infinity f64 -QNAN_F64: int = 0x7FF8000000000000 # Canonical quiet NaN f64 -NEG_QNAN_F64: int = 0xFFF8000000000000 # Negative quiet NaN f64 -QNAN_PAYLOAD_A_F64: int = 0x7FF8000000000001 -QNAN_PAYLOAD_B_F64: int = 0xFFF9000000000002 -SNAN_F64: int = 0x7FF0000000000001 # Signaling NaN -SUBNORM_MIN_F64: int = 0x0000000000000001 # Smallest positive subnormal f64: 2^-1074 -SUBNORM_MAX_F64: int = 0x000FFFFFFFFFFFFF # Largest positive subnormal f64 -NEG_SUBNORM_MIN_F64: int = 0x8000000000000001 -NEG_SUBNORM_MAX_F64: int = 0x800FFFFFFFFFFFFF - -# Boundary overflow threshold: 2^128 - 2^104 (doubles >= this magnitude round to f32 inf in roundTiesToEven) -OVERFLOW_THRESHOLD_F64: float = 3.4028235677973366e+38 - - -def u32(val: int) -> int: - """Normalize integer to unsigned 32-bit range [0, 2^32 - 1].""" - return val & MASK32 - - -def u64(val: int) -> int: - """Normalize integer to unsigned 64-bit range [0, 2^64 - 1].""" - return val & MASK64 - - -def s32(val: int) -> int: - """Interpret a 32-bit unsigned word as a signed two's-complement integer.""" - val &= MASK32 - return val - (1 << 32) if (val & 0x80000000) else val - - -def s64(val: int) -> int: - """Interpret a 64-bit unsigned word as a signed two's-complement integer.""" - val &= MASK64 - return val - (1 << 64) if (val & SIGN_MASK_F64) else val - - -def split_dwords(val64: int) -> tuple[int, int]: - """Split an unsigned 64-bit integer into (low_dword, high_dword).""" - val = val64 & MASK64 - return val & MASK32, (val >> 32) & MASK32 - - -def join_dwords(lo: int, hi: int) -> int: - """Join (low_dword, high_dword) into an unsigned 64-bit integer.""" - return ((hi & MASK32) << 32) | (lo & MASK32) - - -def bits_to_f32(bits: int) -> float: - """Decode 32-bit unsigned integer to IEEE 754 single-precision float.""" - return struct.unpack(" int: - """Encode float to IEEE 754 single-precision 32-bit unsigned integer.""" - try: - return struct.unpack(" 0 else NEG_INF_F32 - - -def bits_to_f64(bits: int) -> float: - """Decode 64-bit unsigned integer to IEEE 754 double-precision float.""" - return struct.unpack(" int: - """Encode double float to IEEE 754 double-precision 64-bit unsigned integer.""" - try: - return struct.unpack(" 0 else NEG_INF_F64 - - -def is_nan_f32(bits: int) -> bool: - """True if 32-bit integer represents an IEEE 754 single-precision NaN.""" - bits &= MASK32 - return (bits & EXP_MASK_F32) == EXP_MASK_F32 and (bits & MANT_MASK_F32) != 0 - - -def is_qnan_f32(bits: int) -> bool: - """True if bits represent a quiet single-precision NaN (bit 22 is 1).""" - bits &= MASK32 - return is_nan_f32(bits) and bool(bits & QUIET_NAN_BIT_F32) - - -def is_snan_f32(bits: int) -> bool: - """True if bits represent a signaling single-precision NaN (bit 22 is 0).""" - bits &= MASK32 - return is_nan_f32(bits) and not bool(bits & QUIET_NAN_BIT_F32) - - -def is_subnormal_f32(bits: int) -> bool: - """True if bits represent an IEEE 754 single-precision subnormal number.""" - bits &= MASK32 - return (bits & EXP_MASK_F32) == 0 and (bits & MANT_MASK_F32) != 0 - - -def is_nan_f64(bits: int) -> bool: - """True if 64-bit integer represents an IEEE 754 double-precision NaN.""" - bits &= MASK64 - return (bits & EXP_MASK_F64) == EXP_MASK_F64 and (bits & MANT_MASK_F64) != 0 - - -def is_qnan_f64(bits: int) -> bool: - """True if bits represent a quiet double-precision NaN (bit 51 is 1).""" - bits &= MASK64 - return is_nan_f64(bits) and bool(bits & QUIET_NAN_BIT_F64) - - -def is_snan_f64(bits: int) -> bool: - """True if bits represent a signaling double-precision NaN (bit 51 is 0).""" - bits &= MASK64 - return is_nan_f64(bits) and not bool(bits & QUIET_NAN_BIT_F64) - - -def is_subnormal_f64(bits: int) -> bool: - """True if bits represent an IEEE 754 double-precision subnormal number.""" - bits &= MASK64 - return (bits & EXP_MASK_F64) == 0 and (bits & MANT_MASK_F64) != 0 - - -def apply_f64_modifiers(bits: int, neg: bool = False, abs_val: bool = False) -> int: - """Applies VOP3 input modifiers to 64-bit float: abs (|x|) first, then neg (-x).""" - bits &= MASK64 - if abs_val: - bits &= ~SIGN_MASK_F64 - if neg: - bits ^= SIGN_MASK_F64 - return bits & MASK64 - - -def apply_f32_modifiers(bits: int, neg: bool = False, abs_val: bool = False) -> int: - """Applies VOP3 input modifiers to 32-bit float: abs (|x|) first, then neg (-x).""" - bits &= MASK32 - if abs_val: - bits &= ~SIGN_MASK_F32 - if neg: - bits ^= SIGN_MASK_F32 - return bits & MASK32 - - -def apply_f32_clamp(bits: int) -> int: - """Applies VOP3 clamp modifier to 32-bit float: clamps result to [0.0, 1.0].""" - bits &= MASK32 - if is_nan_f32(bits): - return bits - val = bits_to_f32(bits) - if val < 0.0 or (val == 0.0 and (bits & SIGN_MASK_F32)): - return POS_ZERO_F32 - if val > 1.0: - return POS_ONE_F32 - return bits - - -def apply_f64_clamp(bits: int) -> int: - """Applies VOP3 clamp modifier to 64-bit float: clamps result to [0.0, 1.0].""" - bits &= MASK64 - if is_nan_f64(bits): - return bits - val = bits_to_f64(bits) - if val < 0.0 or (val == 0.0 and (bits & SIGN_MASK_F64)): - return POS_ZERO_F64 - if val > 1.0: - return POS_ONE_F64 - return bits - - -def ref_cvt_f32_f64( - src64: int, - clamp: bool = False, - neg: bool = False, - abs_val: bool = False, -) -> int: - """Reference mathematical oracle for RDNA2 v_cvt_f32_f64. - - Converts 64-bit double-precision IEEE 754 value to 32-bit single-precision IEEE 754 value. - """ - s64_mod = apply_f64_modifiers(src64, neg=neg, abs_val=abs_val) - - # 1. NaN handling: canonical quiet NaN - if is_nan_f64(s64_mod): - res = QNAN_F32 - return apply_f32_clamp(res) if clamp else res - - # 2. Signed zeros - if (s64_mod & ~SIGN_MASK_F64) == 0: - res = NEG_ZERO_F32 if (s64_mod & SIGN_MASK_F64) else POS_ZERO_F32 - return apply_f32_clamp(res) if clamp else res - - # 3. Infinities - if (s64_mod & ~SIGN_MASK_F64) == EXP_MASK_F64: - res = NEG_INF_F32 if (s64_mod & SIGN_MASK_F64) else POS_INF_F32 - return apply_f32_clamp(res) if clamp else res - - # 4. Finite double-precision value conversion with roundTiesToEven - d_val = bits_to_f64(s64_mod) - try: - res = struct.unpack(" 0 else NEG_INF_F32 - - return apply_f32_clamp(res) if clamp else res - - -def ref_cvt_f64_f32( - src32: int, - clamp: bool = False, - neg: bool = False, - abs_val: bool = False, -) -> int: - """Reference mathematical oracle for RDNA2 v_cvt_f64_f32. - - Converts 32-bit single-precision IEEE 754 value to 64-bit double-precision IEEE 754 value. - This conversion is exact for all finite single-precision values. - """ - s32_mod = apply_f32_modifiers(src32, neg=neg, abs_val=abs_val) - - # 1. NaN handling: canonical quiet NaN - if is_nan_f32(s32_mod): - res = QNAN_F64 - return apply_f64_clamp(res) if clamp else res - - # 2. Signed zeros - if (s32_mod & ~SIGN_MASK_F32) == 0: - res = NEG_ZERO_F64 if (s32_mod & SIGN_MASK_F32) else POS_ZERO_F64 - return apply_f64_clamp(res) if clamp else res - - # 3. Infinities - if (s32_mod & ~SIGN_MASK_F32) == EXP_MASK_F32: - res = NEG_INF_F64 if (s32_mod & SIGN_MASK_F32) else POS_INF_F64 - return apply_f64_clamp(res) if clamp else res - - # 4. Finite single-precision value conversion (exact) - f_val = bits_to_f32(s32_mod) - res = struct.unpack(" None: - # 1.0f <-> 1.0 - self.assertEqual(ref_cvt_f32_f64(POS_ONE_F64), POS_ONE_F32) - self.assertEqual(ref_cvt_f64_f32(POS_ONE_F32), POS_ONE_F64) - - # -1.0f <-> -1.0 - self.assertEqual(ref_cvt_f32_f64(NEG_ONE_F64), NEG_ONE_F32) - self.assertEqual(ref_cvt_f64_f32(NEG_ONE_F32), NEG_ONE_F64) - - # 2.0f <-> 2.0 - self.assertEqual(ref_cvt_f32_f64(POS_TWO_F64), POS_TWO_F32) - self.assertEqual(ref_cvt_f64_f32(POS_TWO_F32), POS_TWO_F64) - - # 0.5f <-> 0.5 - self.assertEqual(ref_cvt_f32_f64(HALF_F64), HALF_F32) - self.assertEqual(ref_cvt_f64_f32(HALF_F32), HALF_F64) - - # 10.0f <-> 10.0 - self.assertEqual(ref_cvt_f32_f64(POS_TEN_F64), POS_TEN_F32) - self.assertEqual(ref_cvt_f64_f32(POS_TEN_F32), POS_TEN_F64) - - def test_signed_zeros(self) -> None: - self.assertEqual(ref_cvt_f32_f64(POS_ZERO_F64), POS_ZERO_F32) - self.assertEqual(ref_cvt_f32_f64(NEG_ZERO_F64), NEG_ZERO_F32) - self.assertEqual(ref_cvt_f64_f32(POS_ZERO_F32), POS_ZERO_F64) - self.assertEqual(ref_cvt_f64_f32(NEG_ZERO_F32), NEG_ZERO_F64) - - def test_infinities(self) -> None: - self.assertEqual(ref_cvt_f32_f64(POS_INF_F64), POS_INF_F32) - self.assertEqual(ref_cvt_f32_f64(NEG_INF_F64), NEG_INF_F32) - self.assertEqual(ref_cvt_f64_f32(POS_INF_F32), POS_INF_F64) - self.assertEqual(ref_cvt_f64_f32(NEG_INF_F32), NEG_INF_F64) - - def test_nan_conversions(self) -> None: - self.assertEqual(ref_cvt_f32_f64(QNAN_F64), QNAN_F32) - self.assertEqual(ref_cvt_f32_f64(NEG_QNAN_F64), QNAN_F32) - self.assertEqual(ref_cvt_f32_f64(SNAN_F64), QNAN_F32) - self.assertEqual(ref_cvt_f64_f32(QNAN_F32), QNAN_F64) - self.assertEqual(ref_cvt_f64_f32(NEG_QNAN_F32), QNAN_F64) - self.assertEqual(ref_cvt_f64_f32(SNAN_F32), QNAN_F64) - - def test_modifiers(self) -> None: - # abs modifier clears sign bit - self.assertEqual(ref_cvt_f32_f64(NEG_ONE_F64, abs_val=True), POS_ONE_F32) - self.assertEqual(ref_cvt_f64_f32(NEG_ONE_F32, abs_val=True), POS_ONE_F64) - - # neg modifier flips sign bit - self.assertEqual(ref_cvt_f32_f64(POS_ONE_F64, neg=True), NEG_ONE_F32) - self.assertEqual(ref_cvt_f64_f32(POS_ONE_F32, neg=True), NEG_ONE_F64) - - # neg(abs) forces negative - self.assertEqual(ref_cvt_f32_f64(POS_ONE_F64, neg=True, abs_val=True), NEG_ONE_F32) - self.assertEqual(ref_cvt_f64_f32(NEG_ONE_F32, neg=True, abs_val=True), NEG_ONE_F64) - - # clamp modifier - self.assertEqual(ref_cvt_f32_f64(POS_TWO_F64, clamp=True), POS_ONE_F32) - self.assertEqual(ref_cvt_f32_f64(NEG_TWO_F64, clamp=True), POS_ZERO_F32) - self.assertEqual(ref_cvt_f64_f32(POS_TWO_F32, clamp=True), POS_ONE_F64) - self.assertEqual(ref_cvt_f64_f32(NEG_TWO_F32, clamp=True), POS_ZERO_F64) - - def test_dword_utilities(self) -> None: - lo, hi = split_dwords(POS_ONE_F64) - self.assertEqual(lo, 0x00000000) - self.assertEqual(hi, 0x3FF00000) - self.assertEqual(join_dwords(lo, hi), POS_ONE_F64) - - -# --------------------------------------------------------------------------- -# Symbolic AST Opcode Definitions and Typed Expressions -# --------------------------------------------------------------------------- - -class RegKind(enum.Enum): - """Register file domain.""" - VGPR = "v" - SGPR = "s" - - -@dataclasses.dataclass(frozen=True) -class Register: - """Symbolic register operand representing a 32-bit register or 64-bit pair.""" - kind: RegKind - index: int - count: int = 1 - - def __post_init__(self) -> None: - if self.index < 0 or self.index >= 256: - raise ValueError(f"Register index out of range [0, 255]: {self.index}") - if self.count not in (1, 2): - raise ValueError(f"Unsupported register count (must be 1 or 2): {self.count}") - if self.count == 2 and self.index + 1 >= 256: - raise ValueError(f"64-bit register pair exceeds register file boundary: {self.index}") - - @property - def is_vgpr(self) -> bool: - return self.kind == RegKind.VGPR - - @property - def is_sgpr(self) -> bool: - return self.kind == RegKind.SGPR - - def format_asm(self) -> str: - if self.count == 2: - return f"{self.kind.value}[{self.index}:{self.index + 1}]" - return f"{self.kind.value}{self.index}" - - -@dataclasses.dataclass(frozen=True) -class Immediate: - """Symbolic 32-bit or 64-bit immediate operand.""" - bits: int - is_64bit: bool = False - - def __init__(self, val: int | float, is_64bit: bool = False) -> None: - if isinstance(val, float): - b = f64_to_bits(val) if is_64bit else f32_to_bits(val) - else: - b = (val & MASK64) if is_64bit else (val & MASK32) - object.__setattr__(self, "bits", b) - object.__setattr__(self, "is_64bit", is_64bit) - - @property - def as_float(self) -> float: - return bits_to_f64(self.bits) if self.is_64bit else bits_to_f32(self.bits) - - def format_asm(self) -> str: - if self.is_64bit: - return f"{self.bits:#018x}" - return f"{self.bits:#010x}" - - -@dataclasses.dataclass(frozen=True) -class OperandModifiers: - """Input modifiers for VALU floating-point instructions (abs and neg).""" - neg: bool = False - abs_val: bool = False - - def apply(self, bits: int, is_64bit: bool) -> int: - if is_64bit: - return apply_f64_modifiers(bits, neg=self.neg, abs_val=self.abs_val) - return apply_f32_modifiers(bits, neg=self.neg, abs_val=self.abs_val) - - def format_asm(self, base_str: str) -> str: - res = base_str - if self.abs_val: - res = f"|{res}|" - if self.neg: - res = f"-{res}" - return res - - -@dataclasses.dataclass(frozen=True) -class InstructionModifiers: - """Output modifiers for VALU instructions (clamp).""" - clamp: bool = False - - def apply_f32(self, bits: int) -> int: - return apply_f32_clamp(bits) if self.clamp else (bits & MASK32) - - def apply_f64(self, bits: int) -> int: - return apply_f64_clamp(bits) if self.clamp else (bits & MASK64) - - def format_asm(self) -> str: - return " clamp" if self.clamp else "" - - -class Opcode(enum.Enum): - """VALU floating-point conversion opcodes.""" - V_CVT_F32_F64 = "v_cvt_f32_f64" - V_CVT_F64_F32 = "v_cvt_f64_f32" - - -class Encoding(enum.Enum): - """Instruction encoding format.""" - VOP1 = "e32" - VOP3 = "e64" - - -@dataclasses.dataclass(frozen=True) -class Instruction: - """Symbolic AST node representing a floating-point conversion VALU instruction.""" - opcode: Opcode - dst: Register - src0: Register | Immediate - src0_mods: OperandModifiers = dataclasses.field(default_factory=OperandModifiers) - inst_mods: InstructionModifiers = dataclasses.field(default_factory=InstructionModifiers) - encoding: Encoding = Encoding.VOP3 - - def __post_init__(self) -> None: - if not self.dst.is_vgpr: - raise ValueError(f"VALU instruction destination must be a VGPR: {self.dst}") - - if self.opcode == Opcode.V_CVT_F32_F64: - if self.dst.count != 1: - raise ValueError(f"v_cvt_f32_f64 destination must be 32-bit single VGPR (count=1): {self.dst}") - if isinstance(self.src0, Register) and self.src0.count != 2: - raise ValueError(f"v_cvt_f32_f64 source register must be 64-bit pair (count=2): {self.src0}") - elif self.opcode == Opcode.V_CVT_F64_F32: - if self.dst.count != 2: - raise ValueError(f"v_cvt_f64_f32 destination must be 64-bit pair VGPR (count=2): {self.dst}") - if isinstance(self.src0, Register) and self.src0.count != 1: - raise ValueError(f"v_cvt_f64_f32 source register must be 32-bit single register (count=1): {self.src0}") - - has_mods = self.src0_mods.neg or self.src0_mods.abs_val or self.inst_mods.clamp - if self.encoding == Encoding.VOP1 and has_mods: - raise ValueError("VOP1 (e32) encoding does not support input modifiers or clamp (requires VOP3/e64)") - - def to_assembly(self) -> str: - s0_str = self.src0.format_asm() - s0_fmt = self.src0_mods.format_asm(s0_str) - dst_str = self.dst.format_asm() - clamp_str = self.inst_mods.format_asm() - enc_suffix = f"_{self.encoding.value}" if self.encoding == Encoding.VOP1 else "" - return f"{self.opcode.value}{enc_suffix} {dst_str}, {s0_fmt}{clamp_str}" - - -@dataclasses.dataclass -class Program: - """Symbolic sequence of VALU instructions.""" - instructions: list[Instruction] = dataclasses.field(default_factory=list) - - def append(self, inst: Instruction) -> None: - self.instructions.append(inst) - - def to_assembly(self) -> str: - return "\n".join(inst.to_assembly() for inst in self.instructions) - - -class TestValuCvtF32F64AST(unittest.TestCase): - """Unit tests for symbolic AST opcode definitions and typed expressions.""" - - def test_register_formatting(self) -> None: - v0 = Register(RegKind.VGPR, 0, count=1) - v_pair = Register(RegKind.VGPR, 2, count=2) - s_single = Register(RegKind.SGPR, 4, count=1) - s_pair = Register(RegKind.SGPR, 6, count=2) - - self.assertEqual(v0.format_asm(), "v0") - self.assertEqual(v_pair.format_asm(), "v[2:3]") - self.assertEqual(s_single.format_asm(), "s4") - self.assertEqual(s_pair.format_asm(), "s[6:7]") - - def test_immediate_formatting(self) -> None: - imm32 = Immediate(1.0, is_64bit=False) - imm64 = Immediate(1.0, is_64bit=True) - self.assertEqual(imm32.format_asm(), f"{POS_ONE_F32:#010x}") - self.assertEqual(imm64.format_asm(), f"{POS_ONE_F64:#018x}") - - def test_operand_modifiers_formatting(self) -> None: - mods_abs = OperandModifiers(abs_val=True) - mods_neg = OperandModifiers(neg=True) - mods_both = OperandModifiers(neg=True, abs_val=True) - - self.assertEqual(mods_abs.format_asm("v[2:3]"), "|v[2:3]|") - self.assertEqual(mods_neg.format_asm("v[2:3]"), "-v[2:3]") - self.assertEqual(mods_both.format_asm("v[2:3]"), "-|v[2:3]|") - - def test_instruction_formatting(self) -> None: - # v_cvt_f32_f64 VOP3 - inst1 = Instruction( - opcode=Opcode.V_CVT_F32_F64, - dst=Register(RegKind.VGPR, 0, count=1), - src0=Register(RegKind.VGPR, 2, count=2), - src0_mods=OperandModifiers(neg=True, abs_val=True), - inst_mods=InstructionModifiers(clamp=True), - ) - self.assertEqual(inst1.to_assembly(), "v_cvt_f32_f64 v0, -|v[2:3]| clamp") - - # v_cvt_f32_f64 VOP1 - inst1_e32 = Instruction( - opcode=Opcode.V_CVT_F32_F64, - dst=Register(RegKind.VGPR, 0, count=1), - src0=Register(RegKind.VGPR, 2, count=2), - encoding=Encoding.VOP1, - ) - self.assertEqual(inst1_e32.to_assembly(), "v_cvt_f32_f64_e32 v0, v[2:3]") - - # v_cvt_f64_f32 VOP3 - inst2 = Instruction( - opcode=Opcode.V_CVT_F64_F32, - dst=Register(RegKind.VGPR, 0, count=2), - src0=Register(RegKind.VGPR, 2, count=1), - inst_mods=InstructionModifiers(clamp=True), - ) - self.assertEqual(inst2.to_assembly(), "v_cvt_f64_f32 v[0:1], v2 clamp") - - # v_cvt_f64_f32 VOP1 - inst2_e32 = Instruction( - opcode=Opcode.V_CVT_F64_F32, - dst=Register(RegKind.VGPR, 0, count=2), - src0=Register(RegKind.VGPR, 2, count=1), - encoding=Encoding.VOP1, - ) - self.assertEqual(inst2_e32.to_assembly(), "v_cvt_f64_f32_e32 v[0:1], v2") - - def test_instruction_validation(self) -> None: - # Destination must be VGPR - with self.assertRaises(ValueError): - Instruction( - opcode=Opcode.V_CVT_F32_F64, - dst=Register(RegKind.SGPR, 0, count=1), - src0=Register(RegKind.VGPR, 2, count=2), - ) - - # v_cvt_f32_f64 dst must be count=1 - with self.assertRaises(ValueError): - Instruction( - opcode=Opcode.V_CVT_F32_F64, - dst=Register(RegKind.VGPR, 0, count=2), - src0=Register(RegKind.VGPR, 2, count=2), - ) - - # v_cvt_f32_f64 src0 must be count=2 - with self.assertRaises(ValueError): - Instruction( - opcode=Opcode.V_CVT_F32_F64, - dst=Register(RegKind.VGPR, 0, count=1), - src0=Register(RegKind.VGPR, 2, count=1), - ) - - # v_cvt_f64_f32 dst must be count=2 - with self.assertRaises(ValueError): - Instruction( - opcode=Opcode.V_CVT_F64_F32, - dst=Register(RegKind.VGPR, 0, count=1), - src0=Register(RegKind.VGPR, 2, count=1), - ) - - # v_cvt_f64_f32 src0 must be count=1 - with self.assertRaises(ValueError): - Instruction( - opcode=Opcode.V_CVT_F64_F32, - dst=Register(RegKind.VGPR, 0, count=2), - src0=Register(RegKind.VGPR, 2, count=2), - ) - - # VOP1 rejects modifiers - with self.assertRaises(ValueError): - Instruction( - opcode=Opcode.V_CVT_F32_F64, - dst=Register(RegKind.VGPR, 0, count=1), - src0=Register(RegKind.VGPR, 2, count=2), - src0_mods=OperandModifiers(neg=True), - encoding=Encoding.VOP1, - ) - - def test_program_assembly(self) -> None: - prog = Program() - prog.append(Instruction( - opcode=Opcode.V_CVT_F32_F64, - dst=Register(RegKind.VGPR, 0, count=1), - src0=Register(RegKind.VGPR, 2, count=2), - )) - prog.append(Instruction( - opcode=Opcode.V_CVT_F64_F32, - dst=Register(RegKind.VGPR, 4, count=2), - src0=Register(RegKind.VGPR, 0, count=1), - inst_mods=InstructionModifiers(clamp=True), - )) - expected = ( - "v_cvt_f32_f64 v0, v[2:3]\n" - "v_cvt_f64_f32 v[4:5], v0 clamp" - ) - self.assertEqual(prog.to_assembly(), expected) - - -# --------------------------------------------------------------------------- -# Deterministic Scalar Instruction Interpreter -# --------------------------------------------------------------------------- - -class ScalarVALUInterpreter: - """Deterministic scalar interpreter for GFX10/RDNA2 VALU conversion instructions.""" - - def __init__(self) -> None: - self.vgprs: list[int] = [0] * 256 - self.sgprs: list[int] = [0] * 106 - self.vcc: int = 0 - self.trace: list[str] = [] - - def read_reg_u32(self, kind: RegKind, idx: int) -> int: - if idx < 0 or (kind == RegKind.VGPR and idx >= 256) or (kind == RegKind.SGPR and idx >= 106): - raise IndexError(f"Register index out of bounds: {kind.value}{idx}") - return (self.vgprs[idx] if kind == RegKind.VGPR else self.sgprs[idx]) & MASK32 - - def write_reg_u32(self, kind: RegKind, idx: int, val: int) -> None: - if idx < 0 or (kind == RegKind.VGPR and idx >= 256) or (kind == RegKind.SGPR and idx >= 106): - raise IndexError(f"Register index out of bounds: {kind.value}{idx}") - val32 = val & MASK32 - if kind == RegKind.VGPR: - self.vgprs[idx] = val32 - else: - self.sgprs[idx] = val32 - - def read_reg_u64(self, kind: RegKind, idx: int) -> int: - lo = self.read_reg_u32(kind, idx) - hi = self.read_reg_u32(kind, idx + 1) - return join_dwords(lo, hi) - - def write_reg_u64(self, kind: RegKind, idx: int, val: int) -> None: - lo, hi = split_dwords(val) - self.write_reg_u32(kind, idx, lo) - self.write_reg_u32(kind, idx + 1, hi) - - def read_operand(self, op: Register | Immediate, mods: OperandModifiers, is_64bit: bool) -> int: - if isinstance(op, Immediate): - raw = op.bits - elif isinstance(op, Register): - raw = self.read_reg_u64(op.kind, op.index) if is_64bit else self.read_reg_u32(op.kind, op.index) - else: - raise TypeError(f"Unsupported operand type: {type(op)}") - return mods.apply(raw, is_64bit) - - def step(self, inst: Instruction) -> int: - """Executes a single VALU conversion instruction deterministically.""" - # Read-before-write semantics: latch operand - if inst.opcode == Opcode.V_CVT_F32_F64: - s0 = self.read_operand(inst.src0, inst.src0_mods, is_64bit=True) - res = ref_cvt_f32_f64(s0) - final_res = inst.inst_mods.apply_f32(res) - self.write_reg_u32(inst.dst.kind, inst.dst.index, final_res) - self.trace.append(f"{inst.to_assembly()} => {final_res:#010x}") - return final_res - elif inst.opcode == Opcode.V_CVT_F64_F32: - s0 = self.read_operand(inst.src0, inst.src0_mods, is_64bit=False) - res = ref_cvt_f64_f32(s0) - final_res = inst.inst_mods.apply_f64(res) - self.write_reg_u64(inst.dst.kind, inst.dst.index, final_res) - self.trace.append(f"{inst.to_assembly()} => {final_res:#018x}") - return final_res - else: - raise NotImplementedError(f"Unsupported opcode in scalar interpreter: {inst.opcode}") - - def run_program(self, prog: Program) -> list[int]: - """Executes all instructions in a program sequentially.""" - return [self.step(inst) for inst in prog.instructions] - - -class TestValuCvtF32F64ScalarInterpreter(unittest.TestCase): - """Unit tests for the deterministic scalar VALU instruction interpreter.""" - - def test_scalar_register_read_write(self) -> None: - interp = ScalarVALUInterpreter() - interp.write_reg_u32(RegKind.VGPR, 0, POS_ONE_F32) - interp.write_reg_u64(RegKind.VGPR, 2, POS_TWO_F64) - interp.write_reg_u64(RegKind.SGPR, 4, NEG_ONE_F64) - - self.assertEqual(interp.read_reg_u32(RegKind.VGPR, 0), POS_ONE_F32) - self.assertEqual(interp.read_reg_u64(RegKind.VGPR, 2), POS_TWO_F64) - self.assertEqual(interp.read_reg_u64(RegKind.SGPR, 4), NEG_ONE_F64) - - def test_scalar_cvt_f32_f64_vgpr(self) -> None: - interp = ScalarVALUInterpreter() - interp.write_reg_u64(RegKind.VGPR, 2, POS_TEN_F64) - - inst = Instruction( - opcode=Opcode.V_CVT_F32_F64, - dst=Register(RegKind.VGPR, 0, count=1), - src0=Register(RegKind.VGPR, 2, count=2), - ) - res = interp.step(inst) - self.assertEqual(res, POS_TEN_F32) - self.assertEqual(interp.read_reg_u32(RegKind.VGPR, 0), POS_TEN_F32) - - def test_scalar_cvt_f32_f64_sgpr(self) -> None: - interp = ScalarVALUInterpreter() - interp.write_reg_u64(RegKind.SGPR, 4, NEG_HALF_F64) - - inst = Instruction( - opcode=Opcode.V_CVT_F32_F64, - dst=Register(RegKind.VGPR, 0, count=1), - src0=Register(RegKind.SGPR, 4, count=2), - ) - res = interp.step(inst) - self.assertEqual(res, NEG_HALF_F32) - self.assertEqual(interp.read_reg_u32(RegKind.VGPR, 0), NEG_HALF_F32) - - def test_scalar_cvt_f64_f32_vgpr(self) -> None: - interp = ScalarVALUInterpreter() - interp.write_reg_u32(RegKind.VGPR, 2, POS_TEN_F32) - - inst = Instruction( - opcode=Opcode.V_CVT_F64_F32, - dst=Register(RegKind.VGPR, 0, count=2), - src0=Register(RegKind.VGPR, 2, count=1), - ) - res = interp.step(inst) - self.assertEqual(res, POS_TEN_F64) - self.assertEqual(interp.read_reg_u64(RegKind.VGPR, 0), POS_TEN_F64) - - def test_scalar_cvt_f64_f32_sgpr(self) -> None: - interp = ScalarVALUInterpreter() - interp.write_reg_u32(RegKind.SGPR, 4, NEG_HALF_F32) - - inst = Instruction( - opcode=Opcode.V_CVT_F64_F32, - dst=Register(RegKind.VGPR, 0, count=2), - src0=Register(RegKind.SGPR, 4, count=1), - ) - res = interp.step(inst) - self.assertEqual(res, NEG_HALF_F64) - self.assertEqual(interp.read_reg_u64(RegKind.VGPR, 0), NEG_HALF_F64) - - def test_scalar_immediate_operands(self) -> None: - interp = ScalarVALUInterpreter() - - # Immediate f64 -> f32 - inst1 = Instruction( - opcode=Opcode.V_CVT_F32_F64, - dst=Register(RegKind.VGPR, 0, count=1), - src0=Immediate(2.0, is_64bit=True), - ) - res1 = interp.step(inst1) - self.assertEqual(res1, POS_TWO_F32) - - # Immediate f32 -> f64 - inst2 = Instruction( - opcode=Opcode.V_CVT_F64_F32, - dst=Register(RegKind.VGPR, 2, count=2), - src0=Immediate(2.0, is_64bit=False), - ) - res2 = interp.step(inst2) - self.assertEqual(res2, POS_TWO_F64) - - def test_scalar_modifiers_abs_neg_clamp(self) -> None: - interp = ScalarVALUInterpreter() - interp.write_reg_u64(RegKind.VGPR, 2, NEG_TWO_F64) - - # v_cvt_f32_f64 with abs and clamp: |-2.0| = 2.0 clamped to [0,1] = 1.0f - inst1 = Instruction( - opcode=Opcode.V_CVT_F32_F64, - dst=Register(RegKind.VGPR, 0, count=1), - src0=Register(RegKind.VGPR, 2, count=2), - src0_mods=OperandModifiers(abs_val=True), - inst_mods=InstructionModifiers(clamp=True), - ) - res1 = interp.step(inst1) - self.assertEqual(res1, POS_ONE_F32) - - # v_cvt_f64_f32 with neg and clamp: -2.0f clamped to [0,1] = +0.0 - interp.write_reg_u32(RegKind.VGPR, 4, POS_TWO_F32) - inst2 = Instruction( - opcode=Opcode.V_CVT_F64_F32, - dst=Register(RegKind.VGPR, 6, count=2), - src0=Register(RegKind.VGPR, 4, count=1), - src0_mods=OperandModifiers(neg=True), - inst_mods=InstructionModifiers(clamp=True), - ) - res2 = interp.step(inst2) - self.assertEqual(res2, POS_ZERO_F64) - - def test_scalar_program_round_trip(self) -> None: - interp = ScalarVALUInterpreter() - interp.write_reg_u32(RegKind.VGPR, 2, POS_TEN_F32) - - prog = Program() - # v[4:5] = (double)v2 - prog.append(Instruction( - opcode=Opcode.V_CVT_F64_F32, - dst=Register(RegKind.VGPR, 4, count=2), - src0=Register(RegKind.VGPR, 2, count=1), - )) - # v6 = (float)v[4:5] - prog.append(Instruction( - opcode=Opcode.V_CVT_F32_F64, - dst=Register(RegKind.VGPR, 6, count=1), - src0=Register(RegKind.VGPR, 4, count=2), - )) - - results = interp.run_program(prog) - self.assertEqual(results, [POS_TEN_F64, POS_TEN_F32]) - self.assertEqual(interp.read_reg_u64(RegKind.VGPR, 4), POS_TEN_F64) - self.assertEqual(interp.read_reg_u32(RegKind.VGPR, 6), POS_TEN_F32) - self.assertEqual(len(interp.trace), 2) - - -# --------------------------------------------------------------------------- -# SIMD Wavefront Interpreter (Multi-Lane Divergence & 32/64-Bit EXEC Masking) -# --------------------------------------------------------------------------- - -class SIMDWavefrontInterpreter: - """Multi-lane SIMD interpreter modeling Wave32 and Wave64 execution on RDNA2.""" - - def __init__(self, wave_size: int = 64) -> None: - if wave_size not in (32, 64): - raise ValueError(f"Invalid wave_size: {wave_size} (must be 32 or 64)") - self.wave_size: int = wave_size - self.exec_mask: int = (1 << wave_size) - 1 - # Per-lane VGPR files: [wave_size][256] 32-bit registers - self.vgprs: list[list[int]] = [[0] * 256 for _ in range(wave_size)] - # Wavefront-shared SGPR file: [106] 32-bit registers - self.sgprs: list[int] = [0] * 106 - self.vcc: int = 0 - - def set_exec_mask(self, mask: int) -> None: - valid_mask = (1 << self.wave_size) - 1 - self.exec_mask = mask & valid_mask - - def read_lane_reg_u32(self, lane: int, kind: RegKind, idx: int) -> int: - if kind == RegKind.VGPR: - return self.vgprs[lane][idx] & MASK32 - return self.sgprs[idx] & MASK32 - - def write_lane_reg_u32(self, lane: int, kind: RegKind, idx: int, val: int) -> None: - val32 = val & MASK32 - if kind == RegKind.VGPR: - self.vgprs[lane][idx] = val32 - else: - self.sgprs[idx] = val32 - - def read_lane_reg_u64(self, lane: int, kind: RegKind, idx: int) -> int: - lo = self.read_lane_reg_u32(lane, kind, idx) - hi = self.read_lane_reg_u32(lane, kind, idx + 1) - return join_dwords(lo, hi) - - def write_lane_reg_u64(self, lane: int, kind: RegKind, idx: int, val: int) -> None: - lo, hi = split_dwords(val) - self.write_lane_reg_u32(lane, kind, idx, lo) - self.write_lane_reg_u32(lane, kind, idx + 1, hi) - - def read_lane_operand(self, lane: int, op: Register | Immediate, mods: OperandModifiers, is_64bit: bool) -> int: - if isinstance(op, Immediate): - raw = op.bits - elif isinstance(op, Register): - raw = self.read_lane_reg_u64(lane, op.kind, op.index) if is_64bit else self.read_lane_reg_u32(lane, op.kind, op.index) - else: - raise TypeError(f"Unsupported operand type: {type(op)}") - return mods.apply(raw, is_64bit) - - def step(self, inst: Instruction) -> list[int | None]: - """Executes a conversion instruction across all wavefront lanes under EXEC mask.""" - is_64 = (inst.opcode == Opcode.V_CVT_F32_F64) - - # 1. Latch all inputs before write-back (read-before-write across wavefront) - latched_inputs: list[int] = [] - for lane in range(self.wave_size): - s0 = self.read_lane_operand(lane, inst.src0, inst.src0_mods, is_64bit=is_64) - latched_inputs.append(s0) - - # 2. Compute and write back strictly for active lanes - lane_results: list[int | None] = [] - for lane in range(self.wave_size): - is_active = bool((self.exec_mask >> lane) & 1) - if not is_active: - lane_results.append(None) - continue - - s0 = latched_inputs[lane] - if inst.opcode == Opcode.V_CVT_F32_F64: - res = ref_cvt_f32_f64(s0) - final_res = inst.inst_mods.apply_f32(res) - self.write_lane_reg_u32(lane, inst.dst.kind, inst.dst.index, final_res) - elif inst.opcode == Opcode.V_CVT_F64_F32: - res = ref_cvt_f64_f32(s0) - final_res = inst.inst_mods.apply_f64(res) - self.write_lane_reg_u64(lane, inst.dst.kind, inst.dst.index, final_res) - else: - raise NotImplementedError(f"Unsupported opcode in SIMD interpreter: {inst.opcode}") - - lane_results.append(final_res) - - return lane_results - - -class TestValuCvtF32F64SIMD(unittest.TestCase): - """Unit tests for SIMD multi-lane divergence and 32/64-bit EXEC masking.""" - - def test_wave32_uniform_execution(self) -> None: - simd = SIMDWavefrontInterpreter(wave_size=32) - inst = Instruction( - opcode=Opcode.V_CVT_F32_F64, - dst=Register(RegKind.VGPR, 0, count=1), - src0=Register(RegKind.VGPR, 2, count=2), - ) - for lane in range(32): - simd.write_lane_reg_u64(lane, RegKind.VGPR, 2, POS_TWO_F64) - - results = simd.step(inst) - self.assertEqual(len(results), 32) - for lane in range(32): - self.assertEqual(results[lane], POS_TWO_F32) - self.assertEqual(simd.read_lane_reg_u32(lane, RegKind.VGPR, 0), POS_TWO_F32) - - def test_wave64_multi_lane_divergence(self) -> None: - simd = SIMDWavefrontInterpreter(wave_size=64) - inst_f64_f32 = Instruction( - opcode=Opcode.V_CVT_F64_F32, - dst=Register(RegKind.VGPR, 4, count=2), - src0=Register(RegKind.VGPR, 2, count=1), - ) - expected: list[int] = [] - for lane in range(64): - f_val = f32_to_bits(float(lane) * 1.5) - simd.write_lane_reg_u32(lane, RegKind.VGPR, 2, f_val) - expected.append(ref_cvt_f64_f32(f_val)) - - results = simd.step(inst_f64_f32) - self.assertEqual(len(results), 64) - for lane in range(64): - self.assertEqual(results[lane], expected[lane]) - self.assertEqual(simd.read_lane_reg_u64(lane, RegKind.VGPR, 4), expected[lane]) - - def test_wave32_exec_masking_partial(self) -> None: - simd = SIMDWavefrontInterpreter(wave_size=32) - # Checkerboard EXEC mask (even lanes active) - exec_mask = 0x55555555 - simd.set_exec_mask(exec_mask) - - canary_u32 = 0xDEADBEEF - for lane in range(32): - simd.write_lane_reg_u32(lane, RegKind.VGPR, 0, canary_u32) - simd.write_lane_reg_u64(lane, RegKind.VGPR, 2, POS_TEN_F64) - - inst = Instruction( - opcode=Opcode.V_CVT_F32_F64, - dst=Register(RegKind.VGPR, 0, count=1), - src0=Register(RegKind.VGPR, 2, count=2), - ) - results = simd.step(inst) - - for lane in range(32): - if (exec_mask >> lane) & 1: - self.assertEqual(results[lane], POS_TEN_F32) - self.assertEqual(simd.read_lane_reg_u32(lane, RegKind.VGPR, 0), POS_TEN_F32) - else: - self.assertIsNone(results[lane]) - # Inactive lanes strictly retain prior canary value - self.assertEqual(simd.read_lane_reg_u32(lane, RegKind.VGPR, 0), canary_u32) - - def test_wave64_exec_masking_all_inactive(self) -> None: - simd = SIMDWavefrontInterpreter(wave_size=64) - simd.set_exec_mask(0) - - canary_u64 = 0xBAADF00DCAFE1234 - for lane in range(64): - simd.write_lane_reg_u64(lane, RegKind.VGPR, 0, canary_u64) - simd.write_lane_reg_u32(lane, RegKind.VGPR, 2, POS_TWO_F32) - - inst = Instruction( - opcode=Opcode.V_CVT_F64_F32, - dst=Register(RegKind.VGPR, 0, count=2), - src0=Register(RegKind.VGPR, 2, count=1), - ) - results = simd.step(inst) - self.assertEqual(results, [None] * 64) - for lane in range(64): - self.assertEqual(simd.read_lane_reg_u64(lane, RegKind.VGPR, 0), canary_u64) - - def test_simd_with_shared_sgpr_scalar_broadcast(self) -> None: - simd = SIMDWavefrontInterpreter(wave_size=32) - # Shared SGPR pair s[4:5] holds double 10.0 - simd.write_lane_reg_u64(0, RegKind.SGPR, 4, POS_TEN_F64) - - inst = Instruction( - opcode=Opcode.V_CVT_F32_F64, - dst=Register(RegKind.VGPR, 0, count=1), - src0=Register(RegKind.SGPR, 4, count=2), - ) - results = simd.step(inst) - for lane in range(32): - self.assertEqual(results[lane], POS_TEN_F32) - self.assertEqual(simd.read_lane_reg_u32(lane, RegKind.VGPR, 0), POS_TEN_F32) - - -# --------------------------------------------------------------------------- -# Register Aliasing and In-Place Operand Preservation -# --------------------------------------------------------------------------- - -class TestValuCvtF32F64RegisterAliasing(unittest.TestCase): - """Unit tests for register aliasing and in-place operand preservation.""" - - def test_aliasing_cvt_f32_f64_dst_equals_src_low_dword(self) -> None: - interp = ScalarVALUInterpreter() - # v[0:1] = 2.0 (lo=0, hi=0x40000000) - interp.write_reg_u64(RegKind.VGPR, 0, POS_TWO_F64) - self.assertEqual(interp.read_reg_u32(RegKind.VGPR, 0), 0) - self.assertEqual(interp.read_reg_u32(RegKind.VGPR, 1), 0x40000000) - - # v0 = (float)v[0:1] - inst = Instruction( - opcode=Opcode.V_CVT_F32_F64, - dst=Register(RegKind.VGPR, 0, count=1), - src0=Register(RegKind.VGPR, 0, count=2), - ) - res = interp.step(inst) - self.assertEqual(res, POS_TWO_F32) - # Low dword v0 now holds f32 2.0f - self.assertEqual(interp.read_reg_u32(RegKind.VGPR, 0), POS_TWO_F32) - # High dword v1 remains undisturbed - self.assertEqual(interp.read_reg_u32(RegKind.VGPR, 1), 0x40000000) - - def test_aliasing_cvt_f32_f64_dst_equals_src_high_dword(self) -> None: - interp = ScalarVALUInterpreter() - # v[0:1] = 10.0 (lo=0, hi=0x40240000) - interp.write_reg_u64(RegKind.VGPR, 0, POS_TEN_F64) - self.assertEqual(interp.read_reg_u32(RegKind.VGPR, 0), 0) - self.assertEqual(interp.read_reg_u32(RegKind.VGPR, 1), 0x40240000) - - # v1 = (float)v[0:1] - inst = Instruction( - opcode=Opcode.V_CVT_F32_F64, - dst=Register(RegKind.VGPR, 1, count=1), - src0=Register(RegKind.VGPR, 0, count=2), - ) - res = interp.step(inst) - self.assertEqual(res, POS_TEN_F32) - # High dword v1 now holds f32 10.0f - self.assertEqual(interp.read_reg_u32(RegKind.VGPR, 1), POS_TEN_F32) - # Low dword v0 remains undisturbed - self.assertEqual(interp.read_reg_u32(RegKind.VGPR, 0), 0) - - def test_aliasing_cvt_f64_f32_dst_low_equals_src(self) -> None: - interp = ScalarVALUInterpreter() - # v0 = 2.0f, v1 = canary - interp.write_reg_u32(RegKind.VGPR, 0, POS_TWO_F32) - interp.write_reg_u32(RegKind.VGPR, 1, 0xAAAAAAAA) - - # v[0:1] = (double)v0 - inst = Instruction( - opcode=Opcode.V_CVT_F64_F32, - dst=Register(RegKind.VGPR, 0, count=2), - src0=Register(RegKind.VGPR, 0, count=1), - ) - res = interp.step(inst) - self.assertEqual(res, POS_TWO_F64) - self.assertEqual(interp.read_reg_u64(RegKind.VGPR, 0), POS_TWO_F64) - - def test_aliasing_cvt_f64_f32_dst_high_equals_src(self) -> None: - interp = ScalarVALUInterpreter() - # v1 = 1.0f, v0 = canary - interp.write_reg_u32(RegKind.VGPR, 1, POS_ONE_F32) - interp.write_reg_u32(RegKind.VGPR, 0, 0xBBBBBBBB) - - # v[0:1] = (double)v1 - inst = Instruction( - opcode=Opcode.V_CVT_F64_F32, - dst=Register(RegKind.VGPR, 0, count=2), - src0=Register(RegKind.VGPR, 1, count=1), - ) - res = interp.step(inst) - self.assertEqual(res, POS_ONE_F64) - self.assertEqual(interp.read_reg_u64(RegKind.VGPR, 0), POS_ONE_F64) - - def test_unmodified_registers_preserved(self) -> None: - interp = ScalarVALUInterpreter() - for idx in range(10, 20): - interp.write_reg_u32(RegKind.VGPR, idx, 0x22220000 + idx) - - inst = Instruction( - opcode=Opcode.V_CVT_F32_F64, - dst=Register(RegKind.VGPR, 0, count=1), - src0=Immediate(1.0, is_64bit=True), - ) - interp.step(inst) - - for idx in range(10, 20): - self.assertEqual(interp.read_reg_u32(RegKind.VGPR, idx), 0x22220000 + idx) - - def test_simd_aliasing_with_divergent_exec_mask(self) -> None: - simd = SIMDWavefrontInterpreter(wave_size=32) - exec_mask = 0x0000000F # First 4 lanes active - simd.set_exec_mask(exec_mask) - - # All lanes: v[0:1] = 10.0 - for lane in range(32): - simd.write_lane_reg_u64(lane, RegKind.VGPR, 0, POS_TEN_F64) - - # v0 = (float)v[0:1] - inst = Instruction( - opcode=Opcode.V_CVT_F32_F64, - dst=Register(RegKind.VGPR, 0, count=1), - src0=Register(RegKind.VGPR, 0, count=2), - ) - simd.step(inst) - - for lane in range(32): - if lane < 4: - # Active lane wrote f32 10.0f to v0 - self.assertEqual(simd.read_lane_reg_u32(lane, RegKind.VGPR, 0), POS_TEN_F32) - else: - # Inactive lane preserved low dword of POS_TEN_F64 (which is 0) - self.assertEqual(simd.read_lane_reg_u32(lane, RegKind.VGPR, 0), 0) - # High dword v1 remains undisturbed in all lanes - self.assertEqual(simd.read_lane_reg_u32(lane, RegKind.VGPR, 1), 0x40240000) - - -# --------------------------------------------------------------------------- -# Condition Codes, Status Flags, and Carry/Borrow Isolation -# --------------------------------------------------------------------------- - -@dataclasses.dataclass(frozen=True) -class ConditionCodes: - """Architectural condition codes for floating-point conversion operations.""" - equal: bool - less: bool - greater: bool - unordered: bool - zero: bool - negative: bool - - -@dataclasses.dataclass(frozen=True) -class FPStatusFlags: - """IEEE 754 floating-point status flags for conversion operations.""" - invalid: bool # e.g., sNaN operand - denormal: bool # e.g., subnormal operand or result - inexact: bool # precision loss in conversion - overflow: bool # exponent overflow to infinity - underflow: bool # exponent underflow - - -def compute_condition_codes_f32(result: int) -> ConditionCodes: - """Computes condition codes evaluating attributes of a 32-bit floating-point result.""" - result &= MASK32 - if is_nan_f32(result): - return ConditionCodes( - equal=False, - less=False, - greater=False, - unordered=True, - zero=False, - negative=False, - ) - val = bits_to_f32(result) - is_zero = (result in (POS_ZERO_F32, NEG_ZERO_F32)) - is_neg = bool(result & SIGN_MASK_F32) - return ConditionCodes( - equal=(val == 0.0), - less=(val < 0.0), - greater=(val > 0.0), - unordered=False, - zero=is_zero, - negative=is_neg, - ) - - -def compute_condition_codes_f64(result: int) -> ConditionCodes: - """Computes condition codes evaluating attributes of a 64-bit floating-point result.""" - result &= MASK64 - if is_nan_f64(result): - return ConditionCodes( - equal=False, - less=False, - greater=False, - unordered=True, - zero=False, - negative=False, - ) - val = bits_to_f64(result) - is_zero = (result in (POS_ZERO_F64, NEG_ZERO_F64)) - is_neg = bool(result & SIGN_MASK_F64) - return ConditionCodes( - equal=(val == 0.0), - less=(val < 0.0), - greater=(val > 0.0), - unordered=False, - zero=is_zero, - negative=is_neg, - ) - - -def compute_fp_status_flags_cvt_f32_f64(s64: int, result32: int) -> FPStatusFlags: - """Computes IEEE 754 status flags for double to single float conversion.""" - s64 &= MASK64 - result32 &= MASK32 - - invalid = is_snan_f64(s64) - denormal = is_subnormal_f64(s64) or is_subnormal_f32(result32) - - is_s64_inf = (s64 & ~SIGN_MASK_F64) == EXP_MASK_F64 - is_res_inf = (result32 & ~SIGN_MASK_F32) == EXP_MASK_F32 - overflow = not is_nan_f64(s64) and not is_s64_inf and is_res_inf - - is_s64_zero = (s64 & ~SIGN_MASK_F64) == 0 - is_res_zero = (result32 & ~SIGN_MASK_F32) == 0 - underflow = not is_nan_f64(s64) and not is_s64_zero and (is_subnormal_f32(result32) or is_res_zero) - - if is_nan_f64(s64): - inexact = False - elif overflow or underflow: - inexact = True - else: - d_val = bits_to_f64(s64) - f_val = float(bits_to_f32(result32)) - inexact = (d_val != f_val) - - return FPStatusFlags( - invalid=invalid, - denormal=denormal, - inexact=inexact, - overflow=overflow, - underflow=underflow, - ) - - -def compute_fp_status_flags_cvt_f64_f32(s32: int, result64: int) -> FPStatusFlags: - """Computes IEEE 754 status flags for single to double float conversion.""" - s32 &= MASK32 - result64 &= MASK64 - - invalid = is_snan_f32(s32) - # f32 subnormal converted to f64 is a denormal input operand - denormal = is_subnormal_f32(s32) - - return FPStatusFlags( - invalid=invalid, - denormal=denormal, - inexact=False, - overflow=False, - underflow=False, - ) - - -class TestValuCvtF32F64ConditionCodes(unittest.TestCase): - """Unit tests for condition codes, status flags, and carry/borrow isolation.""" - - def test_condition_codes_f32_and_f64(self) -> None: - cc_pos = compute_condition_codes_f32(POS_ONE_F32) - self.assertTrue(cc_pos.greater) - self.assertFalse(cc_pos.less) - self.assertFalse(cc_pos.zero) - self.assertFalse(cc_pos.negative) - self.assertFalse(cc_pos.unordered) - - cc_neg = compute_condition_codes_f64(NEG_TWO_F64) - self.assertTrue(cc_neg.less) - self.assertFalse(cc_neg.greater) - self.assertTrue(cc_neg.negative) - self.assertFalse(cc_neg.unordered) - - cc_zero = compute_condition_codes_f32(NEG_ZERO_F32) - self.assertTrue(cc_zero.zero) - self.assertTrue(cc_zero.equal) - self.assertTrue(cc_zero.negative) - self.assertFalse(cc_zero.unordered) - - cc_nan = compute_condition_codes_f64(QNAN_F64) - self.assertTrue(cc_nan.unordered) - self.assertFalse(cc_nan.zero) - self.assertFalse(cc_nan.equal) - - def test_status_flags_snan_invalid(self) -> None: - flags_f32_f64 = compute_fp_status_flags_cvt_f32_f64(SNAN_F64, QNAN_F32) - self.assertTrue(flags_f32_f64.invalid) - - flags_f64_f32 = compute_fp_status_flags_cvt_f64_f32(SNAN_F32, QNAN_F64) - self.assertTrue(flags_f64_f32.invalid) - - # Quiet NaN does not trigger invalid flag - flags_qnan = compute_fp_status_flags_cvt_f32_f64(QNAN_F64, QNAN_F32) - self.assertFalse(flags_qnan.invalid) - - def test_status_flags_denormal(self) -> None: - # f32 subnormal converted to f64 normal flags denormal operand - flags = compute_fp_status_flags_cvt_f64_f32(SUBNORM_MIN_F32, 0x36A0000000000000) - self.assertTrue(flags.denormal) - self.assertFalse(flags.invalid) - self.assertFalse(flags.inexact) - - def test_status_flags_overflow_inexact(self) -> None: - # 1e39 exceeds float32 max (~3.4e38), overflowing to +infinity - d_large = f64_to_bits(1e39) - res32 = ref_cvt_f32_f64(d_large) - self.assertEqual(res32, POS_INF_F32) - - flags = compute_fp_status_flags_cvt_f32_f64(d_large, res32) - self.assertTrue(flags.overflow) - self.assertTrue(flags.inexact) - self.assertFalse(flags.invalid) - - def test_status_flags_f32_to_f64_exact(self) -> None: - # Any finite float32 converts to float64 with zero precision loss - res64 = ref_cvt_f64_f32(POS_ONE_F32) - flags = compute_fp_status_flags_cvt_f64_f32(POS_ONE_F32, res64) - self.assertFalse(flags.inexact) - self.assertFalse(flags.overflow) - self.assertFalse(flags.underflow) - - def test_carry_borrow_vcc_isolation(self) -> None: - # In RDNA2 ISA, VALU floating-point conversion instructions never write or disturb VCC - interp = ScalarVALUInterpreter() - canary_vcc = 0xAAAAAAAAAAAAAAAA - interp.vcc = canary_vcc - - inst = Instruction( - opcode=Opcode.V_CVT_F32_F64, - dst=Register(RegKind.VGPR, 0, count=1), - src0=Immediate(1.0, is_64bit=True), - ) - interp.step(inst) - self.assertEqual(interp.vcc, canary_vcc) - - simd = SIMDWavefrontInterpreter(wave_size=64) - simd.vcc = canary_vcc - simd.step(inst) - self.assertEqual(simd.vcc, canary_vcc) - - -# --------------------------------------------------------------------------- -# IEEE 754 Boundary Extremes, Subnormals, and NaN Handling -# --------------------------------------------------------------------------- - -class TestValuCvtF32F64IEEE754Boundaries(unittest.TestCase): - """Exhaustive unit tests for IEEE 754 boundary extremes, subnormals, and NaN handling.""" - - def test_signed_zero_matrix(self) -> None: - # v_cvt_f32_f64 signed zeros - self.assertEqual(ref_cvt_f32_f64(POS_ZERO_F64), POS_ZERO_F32) - self.assertEqual(ref_cvt_f32_f64(NEG_ZERO_F64), NEG_ZERO_F32) - self.assertEqual(ref_cvt_f32_f64(POS_ZERO_F64) & SIGN_MASK_F32, 0) - self.assertEqual(ref_cvt_f32_f64(NEG_ZERO_F64) & SIGN_MASK_F32, SIGN_MASK_F32) - - # v_cvt_f64_f32 signed zeros - self.assertEqual(ref_cvt_f64_f32(POS_ZERO_F32), POS_ZERO_F64) - self.assertEqual(ref_cvt_f64_f32(NEG_ZERO_F32), NEG_ZERO_F64) - self.assertEqual(ref_cvt_f64_f32(POS_ZERO_F32) & SIGN_MASK_F64, 0) - self.assertEqual(ref_cvt_f64_f32(NEG_ZERO_F32) & SIGN_MASK_F64, SIGN_MASK_F64) - - def test_infinities_matrix(self) -> None: - self.assertEqual(ref_cvt_f32_f64(POS_INF_F64), POS_INF_F32) - self.assertEqual(ref_cvt_f32_f64(NEG_INF_F64), NEG_INF_F32) - self.assertEqual(ref_cvt_f64_f32(POS_INF_F32), POS_INF_F64) - self.assertEqual(ref_cvt_f64_f32(NEG_INF_F32), NEG_INF_F64) - - def test_subnormals_f32_to_f64_exact(self) -> None: - # All subnormals in float32 convert to exact normalized floats in float64 - subnormals_f32 = [ - SUBNORM_MIN_F32, - SUBNORM_MAX_F32, - NEG_SUBNORM_MIN_F32, - NEG_SUBNORM_MAX_F32, - 0x00000042, - 0x80000042, - ] - for sub in subnormals_f32: - with self.subTest(sub=f"{sub:#010x}"): - self.assertTrue(is_subnormal_f32(sub)) - res64 = ref_cvt_f64_f32(sub) - # In float64, these exponent bits are non-zero (normalized!) - self.assertFalse(is_subnormal_f64(res64)) - self.assertEqual(bits_to_f32(sub), bits_to_f64(res64)) - - def test_subnormals_f64_to_f32(self) -> None: - # A double representing 2^-140 converts to a subnormal float32 - d_val = 2.0 ** -140 - d_bits = f64_to_bits(d_val) - res32 = ref_cvt_f32_f64(d_bits) - self.assertTrue(is_subnormal_f32(res32)) - - # A double subnormal (magnitude < 2^-1022) is far smaller than f32 min subnormal (2^-149) - # and therefore underflows to signed zero under IEEE 754 roundTiesToEven - self.assertEqual(ref_cvt_f32_f64(SUBNORM_MIN_F64), POS_ZERO_F32) - self.assertEqual(ref_cvt_f32_f64(SUBNORM_MAX_F64), POS_ZERO_F32) - self.assertEqual(ref_cvt_f32_f64(NEG_SUBNORM_MIN_F64), NEG_ZERO_F32) - self.assertEqual(ref_cvt_f32_f64(NEG_SUBNORM_MAX_F64), NEG_ZERO_F32) - - def test_overflow_boundaries_f64_to_f32(self) -> None: - # FLT_MAX as double - flt_max_as_double = f64_to_bits(bits_to_f32(FLT_MAX)) - self.assertEqual(ref_cvt_f32_f64(flt_max_as_double), FLT_MAX) - - # Value just below overflow threshold rounds to FLT_MAX - val_below_thresh = f64_to_bits(3.4028234e+38) - self.assertEqual(ref_cvt_f32_f64(val_below_thresh), FLT_MAX) - - # Value >= overflow threshold rounds to +inf - val_at_thresh = f64_to_bits(OVERFLOW_THRESHOLD_F64) - self.assertEqual(ref_cvt_f32_f64(val_at_thresh), POS_INF_F32) - - # Negative counterpart rounds to -inf - val_neg_thresh = f64_to_bits(-OVERFLOW_THRESHOLD_F64) - self.assertEqual(ref_cvt_f32_f64(val_neg_thresh), NEG_INF_F32) - - def test_nan_suppression_and_propagation(self) -> None: - f64_nans = [QNAN_F64, NEG_QNAN_F64, QNAN_PAYLOAD_A_F64, QNAN_PAYLOAD_B_F64, SNAN_F64] - for nan in f64_nans: - with self.subTest(nan=f"{nan:#018x}"): - res32 = ref_cvt_f32_f64(nan) - self.assertTrue(is_nan_f32(res32)) - self.assertTrue(is_qnan_f32(res32)) - - f32_nans = [QNAN_F32, NEG_QNAN_F32, QNAN_PAYLOAD_A_F32, QNAN_PAYLOAD_B_F32, SNAN_F32] - for nan in f32_nans: - with self.subTest(nan=f"{nan:#010x}"): - res64 = ref_cvt_f64_f32(nan) - self.assertTrue(is_nan_f64(res64)) - self.assertTrue(is_qnan_f64(res64)) - - def test_modifiers_on_boundary_values(self) -> None: - # abs on negative infinity and negative zero - self.assertEqual(ref_cvt_f32_f64(NEG_INF_F64, abs_val=True), POS_INF_F32) - self.assertEqual(ref_cvt_f32_f64(NEG_ZERO_F64, abs_val=True), POS_ZERO_F32) - self.assertEqual(ref_cvt_f64_f32(NEG_INF_F32, abs_val=True), POS_INF_F64) - self.assertEqual(ref_cvt_f64_f32(NEG_ZERO_F32, abs_val=True), POS_ZERO_F64) - - # neg on positive infinity and positive zero - self.assertEqual(ref_cvt_f32_f64(POS_INF_F64, neg=True), NEG_INF_F32) - self.assertEqual(ref_cvt_f32_f64(POS_ZERO_F64, neg=True), NEG_ZERO_F32) - self.assertEqual(ref_cvt_f64_f32(POS_INF_F32, neg=True), NEG_INF_F64) - self.assertEqual(ref_cvt_f64_f32(POS_ZERO_F32, neg=True), NEG_ZERO_F64) - - # clamp on overflow and boundaries - self.assertEqual(ref_cvt_f32_f64(POS_INF_F64, clamp=True), POS_ONE_F32) - self.assertEqual(ref_cvt_f32_f64(NEG_INF_F64, clamp=True), POS_ZERO_F32) - self.assertEqual(ref_cvt_f32_f64(NEG_ONE_F64, clamp=True), POS_ZERO_F32) - self.assertEqual(ref_cvt_f32_f64(QNAN_F64, clamp=True), QNAN_F32) - - self.assertEqual(ref_cvt_f64_f32(POS_INF_F32, clamp=True), POS_ONE_F64) - self.assertEqual(ref_cvt_f64_f32(NEG_INF_F32, clamp=True), POS_ZERO_F64) - self.assertEqual(ref_cvt_f64_f32(NEG_ONE_F32, clamp=True), POS_ZERO_F64) - self.assertEqual(ref_cvt_f64_f32(QNAN_F32, clamp=True), QNAN_F64) - - -# --------------------------------------------------------------------------- -# Mutated Oracles and Negative Controls / Syntax Rejection -# --------------------------------------------------------------------------- - -def mutant_drop_sign(src: int, is_f64_to_f32: bool) -> int: - """Mutant A: incorrectly clears sign bit regardless of input sign.""" - if is_f64_to_f32: - return ref_cvt_f32_f64(src) & ~SIGN_MASK_F32 - return ref_cvt_f64_f32(src) & ~SIGN_MASK_F64 - - -def mutant_nan_flush_zero(src: int, is_f64_to_f32: bool) -> int: - """Mutant B: improperly flushes NaNs to zero instead of returning NaN.""" - if is_f64_to_f32: - if is_nan_f64(src): - return POS_ZERO_F32 - return ref_cvt_f32_f64(src) - if is_nan_f32(src): - return POS_ZERO_F64 - return ref_cvt_f64_f32(src) - - -def mutant_no_clamp(src: int, is_f64_to_f32: bool) -> int: - """Mutant C: ignores clamp modifier and returns unclamped value.""" - if is_f64_to_f32: - return ref_cvt_f32_f64(src, clamp=False) - return ref_cvt_f64_f32(src, clamp=False) - - -def mutant_f64_to_f32_truncation(src64: int) -> int: - """Mutant D: uses truncation towards zero instead of roundTiesToEven.""" - s64_mod = src64 & MASK64 - if is_nan_f64(s64_mod): - return QNAN_F32 - d_val = bits_to_f64(s64_mod) - sign = (s64_mod >> 63) & 1 - abs_d = abs(d_val) - if abs_d >= 2.0 ** 128: - return NEG_INF_F32 if sign else POS_INF_F32 - if abs_d < 2.0 ** -149: - return NEG_ZERO_F32 if sign else POS_ZERO_F32 - m, e = math.frexp(abs_d) # abs_d = m * 2^e, 0.5 <= m < 1.0 - scale = 2.0 ** (e - 24) - int_mant = int(math.floor(abs_d / scale)) - bits = (int_mant << (1 - 1)) if e < -125 else int_mant - return ((sign << 31) | (bits & 0x7FFFFFFF)) & MASK32 - - -def mutant_f32_to_f64_precision_truncate(src32: int) -> int: - """Mutant E: corrupts low mantissa bits during f32 to f64 conversion.""" - res = ref_cvt_f64_f32(src32) - # Artificially drop low 8 bits of the 23-bit converted mantissa (bits 36..29) - return res & 0xFFFFFFFE00000000 - - -def mutant_leak_vcc(interp: ScalarVALUInterpreter, inst: Instruction) -> None: - """Mutant F: improperly modifies VCC register during VALU FP execution.""" - interp.step(inst) - interp.vcc ^= 0x1 - - -def mutant_exec_leak(sim: SIMDWavefrontInterpreter, inst: Instruction) -> None: - """Mutant G: improperly writes inactive lanes under EXEC mask.""" - sim.step(inst) - # Overwrite lane 0 regardless of EXEC - if inst.opcode == Opcode.V_CVT_F32_F64: - sim.write_lane_reg_u32(0, inst.dst.kind, inst.dst.index, 0x12345678) - else: - sim.write_lane_reg_u64(0, inst.dst.kind, inst.dst.index, 0x1234567890ABCDEF) - - -def parse_register(tok: str) -> Register: - """Parses a register string like 'v0', 'v[2:3]', 's4', 's[4:5]'.""" - tok = tok.strip() - if tok.startswith("v[") or tok.startswith("s["): - kind = RegKind.VGPR if tok.startswith("v") else RegKind.SGPR - inside = tok[2:-1] - lo_str, hi_str = inside.split(":") - lo, hi = int(lo_str), int(hi_str) - if hi != lo + 1: - raise ValueError(f"Non-contiguous register pair: {tok}") - return Register(kind=kind, index=lo, count=2) - elif tok.startswith("v") or tok.startswith("s"): - kind = RegKind.VGPR if tok.startswith("v") else RegKind.SGPR - idx = int(tok[1:]) - return Register(kind=kind, index=idx, count=1) - else: - raise ValueError(f"Unrecognized register token: {tok}") - - -def parse_vop_cvt(asm_str: str) -> Instruction: - """Parses assembly text for v_cvt_f32_f64 or v_cvt_f64_f32.""" - asm_str = asm_str.strip() - tokens = asm_str.split(None, 1) - if not tokens: - raise ValueError("Empty assembly string") - op_str = tokens[0] - rest = tokens[1] if len(tokens) > 1 else "" - - encoding = Encoding.VOP3 - if op_str.endswith("_e32"): - encoding = Encoding.VOP1 - base_op = op_str[:-4] - else: - base_op = op_str - - if base_op == "v_cvt_f32_f64": - opcode = Opcode.V_CVT_F32_F64 - elif base_op == "v_cvt_f64_f32": - opcode = Opcode.V_CVT_F64_F32 - else: - raise ValueError(f"Unsupported opcode: {op_str}") - - clamp = False - if rest.endswith(" clamp"): - clamp = True - rest = rest[:-6].strip() - - args = [a.strip() for a in rest.split(",")] - if len(args) != 2: - raise ValueError(f"Instruction requires exactly 2 operands, got {len(args)}: {rest}") - - dst = parse_register(args[0]) - - s0_str = args[1] - neg = False - abs_val = False - if s0_str.startswith("-"): - neg = True - s0_str = s0_str[1:].strip() - if s0_str.startswith("|") and s0_str.endswith("|"): - abs_val = True - s0_str = s0_str[1:-1].strip() - - if s0_str.startswith("0x") or s0_str.startswith("-0x"): - is_64 = (opcode == Opcode.V_CVT_F32_F64) - src0 = Immediate(int(s0_str, 0), is_64bit=is_64) - else: - src0 = parse_register(s0_str) - - return Instruction( - opcode=opcode, - dst=dst, - src0=src0, - src0_mods=OperandModifiers(neg=neg, abs_val=abs_val), - inst_mods=InstructionModifiers(clamp=clamp), - encoding=encoding, - ) - - -class TestValuCvtF32F64NegativeControlsAndMutations(unittest.TestCase): - """Negative controls, syntax rejection, and mutation detection for v_cvt_f32_f64 and v_cvt_f64_f32.""" - - def test_syntax_rejection_invalid_opcode(self) -> None: - with self.assertRaises(ValueError): - parse_vop_cvt("v_add_f64 v0, v[2:3]") - - def test_syntax_rejection_insufficient_operands(self) -> None: - with self.assertRaises(ValueError): - parse_vop_cvt("v_cvt_f32_f64 v0") - - def test_syntax_rejection_dst_type_mismatch(self) -> None: - # v_cvt_f32_f64 destination must be 32-bit single VGPR (count=1), rejecting pair v[0:1] - with self.assertRaises(ValueError): - parse_vop_cvt("v_cvt_f32_f64 v[0:1], v[2:3]") - - # v_cvt_f64_f32 destination must be 64-bit pair VGPR (count=2), rejecting single v0 - with self.assertRaises(ValueError): - parse_vop_cvt("v_cvt_f64_f32 v0, v2") - - def test_syntax_rejection_src_type_mismatch(self) -> None: - # v_cvt_f32_f64 source must be 64-bit pair (count=2), rejecting single v2 - with self.assertRaises(ValueError): - parse_vop_cvt("v_cvt_f32_f64 v0, v2") - - # v_cvt_f64_f32 source must be 32-bit single (count=1), rejecting pair v[2:3] - with self.assertRaises(ValueError): - parse_vop_cvt("v_cvt_f64_f32 v[0:1], v[2:3]") - - def test_syntax_rejection_sgpr_destination(self) -> None: - # Destination of VALU instruction cannot be SGPR - with self.assertRaises(ValueError): - parse_vop_cvt("v_cvt_f32_f64 s0, v[2:3]") - with self.assertRaises(ValueError): - parse_vop_cvt("v_cvt_f64_f32 s[0:1], v2") - - def test_syntax_rejection_vop1_modifiers(self) -> None: - # VOP1 encoding (_e32) does not support clamp or modifiers - with self.assertRaises(ValueError): - parse_vop_cvt("v_cvt_f32_f64_e32 v0, v[2:3] clamp") - with self.assertRaises(ValueError): - parse_vop_cvt("v_cvt_f32_f64_e32 v0, -v[2:3]") - - def test_syntax_rejection_register_out_of_range(self) -> None: - with self.assertRaises(ValueError): - parse_vop_cvt("v_cvt_f32_f64 v256, v[2:3]") - with self.assertRaises(ValueError): - parse_vop_cvt("v_cvt_f32_f64 v0, v[255:256]") - - def test_mutation_detection_drop_sign(self) -> None: - # Negative float must retain negative sign bit - correct = ref_cvt_f32_f64(NEG_TWO_F64) - mutant = mutant_drop_sign(NEG_TWO_F64, is_f64_to_f32=True) - self.assertEqual(correct, NEG_TWO_F32) - self.assertEqual(mutant, POS_TWO_F32) - self.assertNotEqual(correct, mutant) - - def test_mutation_detection_nan_flush_zero(self) -> None: - # NaN must propagate, not flush to zero - correct = ref_cvt_f32_f64(QNAN_F64) - mutant = mutant_nan_flush_zero(QNAN_F64, is_f64_to_f32=True) - self.assertTrue(is_nan_f32(correct)) - self.assertEqual(mutant, POS_ZERO_F32) - self.assertNotEqual(correct, mutant) - - def test_mutation_detection_no_clamp(self) -> None: - correct = ref_cvt_f32_f64(POS_TWO_F64, clamp=True) - mutant = mutant_no_clamp(POS_TWO_F64, is_f64_to_f32=True) - self.assertEqual(correct, POS_ONE_F32) - self.assertEqual(mutant, POS_TWO_F32) - self.assertNotEqual(correct, mutant) - - def test_mutation_detection_truncation_vs_ties_to_even(self) -> None: - # 1.0 + 1.5 * 2^-23 in double precision: - # Ties to even will round up to 1.0 + 2^-22 in f32 - d_val = f64_to_bits(1.0 + 1.5 * (2.0 ** -23)) - correct = ref_cvt_f32_f64(d_val) - mutant = mutant_f64_to_f32_truncation(d_val) - self.assertNotEqual(correct, mutant) - - def test_mutation_detection_precision_truncate(self) -> None: - # 1.0f + 2^-20 has low mantissa bits in f64 that mutant zeroes out - f_val = f32_to_bits(1.0 + (2.0 ** -20)) - correct = ref_cvt_f64_f32(f_val) - mutant = mutant_f32_to_f64_precision_truncate(f_val) - self.assertEqual(bits_to_f64(correct), 1.0 + (2.0 ** -20)) - self.assertNotEqual(correct, mutant) - - def test_mutation_detection_corrupt_vcc(self) -> None: - interp = ScalarVALUInterpreter() - interp.vcc = 0x5555555555555555 - interp.write_reg_u64(RegKind.VGPR, 2, POS_ONE_F64) - inst = parse_vop_cvt("v_cvt_f32_f64 v0, v[2:3]") - - interp.step(inst) - self.assertEqual(interp.vcc, 0x5555555555555555) - - mutant_leak_vcc(interp, inst) - self.assertNotEqual(interp.vcc, 0x5555555555555555) - - def test_mutation_detection_exec_leak(self) -> None: - sim = SIMDWavefrontInterpreter(wave_size=32) - sim.set_exec_mask(0) # all lanes disabled - sim.write_lane_reg_u32(0, RegKind.VGPR, 0, 0xAAAAAAAA) - inst = parse_vop_cvt("v_cvt_f32_f64 v0, v[2:3]") - - sim.step(inst) - self.assertEqual(sim.read_lane_reg_u32(0, RegKind.VGPR, 0), 0xAAAAAAAA) - - mutant_exec_leak(sim, inst) - self.assertNotEqual(sim.read_lane_reg_u32(0, RegKind.VGPR, 0), 0xAAAAAAAA) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_valu_cvt_int_f64.py b/tests/semantic/test_valu_cvt_int_f64.py deleted file mode 100644 index c1b86f18b..000000000 --- a/tests/semantic/test_valu_cvt_int_f64.py +++ /dev/null @@ -1,40 +0,0 @@ -"""v_cvt_i32_f64 and v_cvt_u32_f64 are not implemented in tools/rdna2spirv.py. v_cvt_f64_i32 and v_cvt_f64_u32 are -since #2521, and tests/semantic/test_int32_to_f64.py runs them through the translator. - -The previous version of this file tested a private Python model of the four conversions and never called the -translator, so it passed whatever the translator did. Until the ops are lowered, the honest test is that the -translator refuses each of them by name (instead of emitting wrong code); when one gets implemented, this test fails -and is replaced by a run through the translator against the ISA semantics (exact int->f64, truncating f64->int with -saturation, NaN -> 0). -""" -import os -import sys -import unittest - -sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) -import support # noqa: E402 -import rdna2spirv # noqa: E402 - -CASES = [ - ("v_cvt_i32_f64", "v_cvt_i32_f64_e32 v2, v[0:1]"), - ("v_cvt_u32_f64", "v_cvt_u32_f64_e32 v2, v[0:1]"), - ("v_cvt_i32_f64", "v_cvt_i32_f64_e64 v2, -|v[0:1]|"), -] - - -class CvtIntF64Unsupported(unittest.TestCase): - def test_each_op_is_refused_by_name(self): - for name, ins in CASES: - with self.subTest(ins=ins): - lines = ["v_mov_b32 v1, 5", ins, "exp mrt0 v2, v2, v2, v2 done vm", "s_endpgm"] - with self.assertRaises(rdna2spirv.Unsupported) as refused: - support.translate_lines("ps_cvt_int_f64", lines) - self.assertEqual(str(refused.exception), name) - - def test_a_listing_without_them_still_translates(self): - lines = ["v_mov_b32 v1, 5", "v_cvt_f32_i32_e32 v2, v1", "exp mrt0 v2, v2, v2, v2 done vm", "s_endpgm"] - self.assertIn("OpFunction", support.translate_lines("ps_cvt_i32_ok", lines)) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_valu_cvt_pk_u8_f32.py b/tests/semantic/test_valu_cvt_pk_u8_f32.py deleted file mode 100644 index 18d10ab33..000000000 --- a/tests/semantic/test_valu_cvt_pk_u8_f32.py +++ /dev/null @@ -1,752 +0,0 @@ -"""Semantic value tests for RDNA2 v_cvt_pk_u8_f32 (VOP3). - -AMD RDNA2 ISA semantics for `v_cvt_pk_u8_f32 vD, src0, src1, src2`: - - Converts binary32 `src0` to an 8-bit unsigned integer using IEEE-754 round-to-nearest-even (`RoundEven`), - clamped to [0, 255] (negative values and -inf -> 0; values >= 255.0 and +inf -> 255; NaN -> 0). - - Inserts that byte into byte lane `src1[1:0]` (`src1 & 3`, i.e. bits [7:0], [15:8], [23:16], or [31:24]) - of `src2`, leaving the other 3 bytes of `src2` untouched in `vD`. - -Executed end-to-end through tools/rdna2spirv.py and tests/semantic/spirv_mini_interp.py (single-lane pixel -shaders via run_fragment and multi-lane compute shaders via run_workgroup), and checked against hand-worked -constants and an independent pure-Python binary32 Fraction/RTE reference oracle. Standard library only; -hand-written RDNA2 disassembly listings only. - -NaN inputs (docs/design.md, "Float-to-byte pack" row): `FClamp` with a NaN operand is undefined in - GLSL.std.450, so tools/rdna2spirv.py finds a NaN from its bits and selects +0 before `FClamp`, then - `RoundEven` + `OpConvertFToU`. `OracleTests` verifies the RDNA2 ISA `NaN -> 0` rule (also measured on - hardware, #358), and `NaNHandlingTests` runs qNaN, -qNaN, sNaN and NaN under `abs`/`neg` through - `spirv_mini_interp.py` and checks byte 0. -""" -import gc -import os -import random -import re -import struct -import sys -import tempfile -import unittest -import warnings -from fractions import Fraction - -HERE = os.path.dirname(os.path.abspath(__file__)) -ROOT = os.path.dirname(os.path.dirname(HERE)) -TOOLS_DIR = os.environ.get("LEONIDA_TOOLS_DIR") or os.path.join(ROOT, "tools") - -sys.dont_write_bytecode = True -if TOOLS_DIR not in sys.path: - sys.path.insert(0, TOOLS_DIR) -if HERE not in sys.path: - sys.path.insert(0, HERE) - -import rdna2spirv # noqa: E402 -import spirv_mini_interp as si # noqa: E402 - -MASK32 = 0xFFFFFFFF -OLD = 0xDEADBEEF -CANARY = 0xCAFEBABE -HEAP_FILL = 0xEEEEEEEE -STUB_DXBC = b"DXBC" + bytes(24) + struct.pack(" int: - try: - return struct.unpack(" 0 else F32_NEG_INF - - -def bits_f32(bits: int) -> float: - return struct.unpack(" bool: - return (bits & 0x7F800000) == 0x7F800000 and (bits & 0x007FFFFF) != 0 - - -# ----------------------------------------------------------------------------- -# Independent IEEE-754 Binary32 Fraction/RTE Reference Oracle -# ----------------------------------------------------------------------------- - -def f32_bits_to_fraction(bits: int) -> Fraction: - """Exact rational value of a finite IEEE-754 binary32 bit encoding.""" - bits &= MASK32 - sign = -1 if (bits >> 31) else 1 - exp = (bits >> 23) & 0xFF - man = bits & 0x7FFFFF - if exp == 0xFF: - raise ValueError(f"non-finite binary32 {bits:#010x}") - if exp == 0: - return sign * Fraction(man, 1 << 23) * (Fraction(2) ** -126) - return sign * Fraction((1 << 23) | man, 1 << 23) * (Fraction(2) ** (exp - 127)) - - -def rne_nonneg_fraction(q: Fraction) -> int: - """Round a non-negative rational to the nearest integer, ties to even.""" - n = q.numerator // q.denominator - rem = q - n - half = Fraction(1, 2) - if rem > half or (rem == half and (n & 1)): - n += 1 - return n - - -def ref_cvt_pk_u8_byte(x_bits: int) -> int: - """RDNA2 flt32_to_uint8: binary32 bits -> IEEE-754 RTE clamped [0, 255] (NaN -> 0).""" - bits = x_bits & MASK32 - if is_f32_nan_bits(bits): - return 0 - if (bits >> 31) or (bits & 0x7FFFFFFF) == 0: - return 0 - if bits == F32_POS_INF: - return 255 - q = f32_bits_to_fraction(bits) - if q >= 255: - return 255 - return min(255, rne_nonneg_fraction(q)) - - -def ref_cvt_pk_u8_f32(x_bits: int, slot: int, base: int) -> int: - """RDNA2 V_CVT_PK_U8_F32: insert ref_cvt_pk_u8_byte(x_bits) at byte (slot & 3) of base.""" - u = ref_cvt_pk_u8_byte(x_bits) - sh = 8 * (slot & 3) - return ((base & MASK32) & ~(0xFF << sh)) | (u << sh) - - -# Hand-worked reference expectations: (label, x_bits, slot, base, expected_dword). -HAND_WORKED = ( - ("slot0_old", f32_bits(18.0), 0, OLD, 0xDEADBE12), - ("slot1_old", f32_bits(52.0), 1, OLD, 0xDEAD34EF), - ("slot2_old", f32_bits(86.0), 2, OLD, 0xDE56BEEF), - ("slot3_old", f32_bits(120.0), 3, OLD, 0x78ADBEEF), - ("slot4_wraps_0", f32_bits(0xAB), 4, OLD, 0xDEADBEAB), - ("slot5_wraps_1", f32_bits(0xCD), 5, OLD, 0xDEADCDEF), - ("slot7_wraps_3", f32_bits(0x42), 7, OLD, 0x42ADBEEF), - ("slot_neg1_wraps_3", f32_bits(0x99), -1, OLD, 0x99ADBEEF), - ("tie_0_5_even", f32_bits(0.5), 0, OLD, 0xDEADBE00), - ("tie_1_5_even", f32_bits(1.5), 1, OLD, 0xDEAD02EF), - ("tie_2_5_even", f32_bits(2.5), 2, OLD, 0xDE02BEEF), - ("tie_253_5_even", f32_bits(253.5), 0, OLD, 0xDEADBEFE), - ("tie_254_5_even", f32_bits(254.5), 1, OLD, 0xDEADFEEF), - ("clamp_255_49", f32_bits(255.49), 2, OLD, 0xDEFFBEEF), - ("clamp_255_5", f32_bits(255.5), 3, OLD, 0xFFADBEEF), - ("neg_0_001", f32_bits(-0.001), 0, OLD, 0xDEADBE00), - ("neg_1000", f32_bits(-1000.0), 1, OLD, 0xDEAD00EF), - ("neg_inf", F32_NEG_INF, 2, OLD, 0xDE00BEEF), - ("pos_inf", F32_POS_INF, 3, OLD, 0xFFADBEEF), - ("subnormal_pos", F32_POS_SUB_MIN, 0, OLD, 0xDEADBE00), - ("subnormal_neg", F32_NEG_SUB_MAX, 1, OLD, 0xDEAD00EF), - ("qnan", F32_QNAN, 0, OLD, 0xDEADBE00), - ("neg_qnan", F32_NEG_QNAN, 2, OLD, 0xDE00BEEF), - ("snan", F32_SNAN, 3, OLD, 0x00ADBEEF), -) - - -# ----------------------------------------------------------------------------- -# Translation & Execution Helpers -# ----------------------------------------------------------------------------- - -_TMP_DIR = None -_PS_PATH = None -_CS_PATH = None -_CS_FSSM = None - - -def _make_fssm(rsrc2: int, group: tuple[int, int, int]) -> bytes: - header = bytearray(0x148) - struct.pack_into("<4I", header, 0x138, rsrc2, *group) - return bytes(header) - - -def setUpModule(): - global _TMP_DIR, _PS_PATH, _CS_PATH, _CS_FSSM - _TMP_DIR = tempfile.TemporaryDirectory() - disasm_dir = os.path.join(_TMP_DIR.name, "disasm") - fssm_dir = os.path.join(_TMP_DIR.name, "fssm") - os.mkdir(disasm_dir) - os.mkdir(fssm_dir) - _PS_PATH = os.path.join(disasm_dir, "ps_valu_cvt_pk_u8_f32.s") - _CS_PATH = os.path.join(disasm_dir, "cs_valu_cvt_pk_u8_f32.s") - _CS_FSSM = os.path.join(fssm_dir, "cs_valu_cvt_pk_u8_f32.fssm") - with open(os.path.join(_TMP_DIR.name, "ps_valu_cvt_pk_u8_f32.dxbc"), "wb") as f: - f.write(STUB_DXBC) - - -def tearDownModule(): - global _TMP_DIR, _PS_PATH, _CS_PATH, _CS_FSSM - if _TMP_DIR is not None: - gc.collect() - _TMP_DIR.cleanup() - _TMP_DIR = None - _PS_PATH = None - _CS_PATH = None - _CS_FSSM = None - - -def translate_ps(lines: list[str]) -> str: - if _TMP_DIR is None: - setUpModule() - asm = "; test_valu_cvt_pk_u8_f32\n" + "".join(f"\t{ln}\n" for ln in lines) + "\ts_endpgm\n" - with open(_PS_PATH, "w", encoding="utf-8", newline="") as f: - f.write(asm) - with warnings.catch_warnings(): - warnings.simplefilter("ignore", ResourceWarning) - spv = rdna2spirv.translate(_PS_PATH) - gc.collect() - return spv - - -def run_ps_mrt0(lines: list[str], regs: tuple[str, str, str, str] = ("v0", "v0", "v0", "v0")) -> tuple[int, ...]: - spv = translate_ps(list(lines) + [f"exp mrt0 {', '.join(regs)} done vm"]) - out = si.run_fragment(spv) - if list(out) != ["%out_mrt0"]: - raise AssertionError(f"expected %out_mrt0 only; got {sorted(out)}") - return tuple(out["%out_mrt0"]) - - -def run_cs(lines: list[str], group_size: int, subgroup_size: int, memory: dict[int, int]) -> dict[int, int]: - if _TMP_DIR is None: - setUpModule() - # rsrc2 = 0x0088: USER_SGPR = 4 (s[0:3] V#), TGID_X_EN = 1 (s4), TIDIG_COMP_CNT = 0 (v0 = local_id.x). - with open(_CS_FSSM, "wb") as f: - f.write(_make_fssm(0x0088, (group_size, 1, 1))) - asm = "; test_cs_valu_cvt_pk_u8_f32\n" + "".join(f"\t{ln}\n" for ln in lines) + "\ts_endpgm\n" - with open(_CS_PATH, "w", encoding="utf-8", newline="") as f: - f.write(asm) - with warnings.catch_warnings(): - warnings.simplefilter("ignore", ResourceWarning) - spv = rdna2spirv.translate(_CS_PATH) - gc.collect() - return si.run_workgroup( - spv, group_size, subgroup_size, - inputs_for=lambda i: {"%wg_id": (0, 0, 0), "%local_id": (i, 0, 0)}, - push_constants=VSHARP + [0] * 28, - memory=memory, - ) - - -class _Heap(dict): - def get(self, key, default=None): - return super().get(key, HEAP_FILL) - - -# ----------------------------------------------------------------------------- -# 1. Reference Oracle Self-Tests -# ----------------------------------------------------------------------------- - -class OracleTests(unittest.TestCase): - def test_hand_worked_constants_match_oracle(self): - for label, x_bits, slot, base, want in HAND_WORKED: - with self.subTest(case=label): - self.assertEqual(ref_cvt_pk_u8_f32(x_bits, slot, base), want) - - def test_oracle_agrees_with_python_float_round_for_finite_values(self): - for k in range(256): - for delta in (-0.25, 0.0, 0.25, 0.5): - x = k + delta - xb = f32_bits(x) - expected_u = min(255, max(0, round(bits_f32(xb)))) - self.assertEqual(ref_cvt_pk_u8_byte(xb), expected_u, f"x={x}") - # Verify 1-ULP neighbors around .5 ties. - for tie in (0.5, 1.5, 2.5, 127.5, 128.5, 253.5, 254.5): - tb = f32_bits(tie) - for b in (tb - 1, tb, tb + 1): - expected_u = min(255, max(0, round(bits_f32(b)))) - self.assertEqual(ref_cvt_pk_u8_byte(b), expected_u, f"b={b:#010x}") - - -# ----------------------------------------------------------------------------- -# 2. Byte Slots (0..3), Slot Masking (slot & 3), and Untouched Bytes -# ----------------------------------------------------------------------------- - -class ByteSlotAndMaskingTests(unittest.TestCase): - def test_all_four_slots_preserve_other_three_bytes_of_base(self): - # Distinct byte values including 0x00 and 0xFF (slot 3 gives 0xFFADBEEF / 0x00ADBEEF). - byte_vals = (0.0, 1.0, 18.0, 127.0, 128.0, 254.0, 255.0) - for suffix in ("", "_e64"): - for slot in range(4): - for start in range(0, len(byte_vals), 4): - chunk = byte_vals[start:start + 4] - lines, expected = [f"v_mov_b32 v3, {OLD:#x}"], [] - for lane, val in enumerate(chunk): - xb = f32_bits(val) - dst = f"v{10 + lane}" - lines += [ - f"v_mov_b32 {dst}, {CANARY:#x}", - f"v_mov_b32 v1, {xb:#x}", - f"v_mov_b32 v2, {slot}", - f"v_cvt_pk_u8_f32{suffix} {dst}, v1, v2, v3", - ] - expected.append(ref_cvt_pk_u8_f32(xb, slot, OLD)) - while len(expected) < 4: - lines.append(f"v_mov_b32 v{10 + len(expected)}, 0") - expected.append(0) - with self.subTest(suffix=suffix or "bare", slot=slot, batch=start // 4): - got = run_ps_mrt0(lines, ("v10", "v11", "v12", "v13")) - self.assertEqual(got, tuple(expected)) - - def test_slot_and_3_masking_across_vgpr_sgpr_and_inline_operands(self): - slots = [0, 1, 2, 3, 4, 5, 6, 7, 8, -1, 0xFFFFFFFF, 0xFFFFFFFC, 0x80000001, 0x1234567A] - payloads = [17.0, 65.0, 145.0, 243.0] - - for op_kind in ("vgpr", "sgpr", "inline"): - for start in range(0, len(slots), 4): - chunk = slots[start:start + 4] - lines, expected = [f"v_mov_b32 v3, {OLD:#x}"], [] - for idx, slot in enumerate(chunk): - x = payloads[(start + idx) % len(payloads)] - xb = f32_bits(x) - dst = f"v{10 + idx}" - lines.append(f"v_mov_b32 {dst}, {CANARY:#x}") - lines.append(f"v_mov_b32 v1, {xb:#x}") - if op_kind == "vgpr": - lines.append(f"v_mov_b32 v2, {slot & MASK32:#x}") - slot_arg = "v2" - elif op_kind == "sgpr": - lines.append(f"s_mov_b32 s4, {slot & MASK32:#x}") - slot_arg = "s4" - else: - slot_arg = str(slot) if -16 <= slot <= 64 else f"{slot & MASK32:#x}" - lines.append(f"v_cvt_pk_u8_f32_e64 {dst}, v1, {slot_arg}, v3") - expected.append(ref_cvt_pk_u8_f32(xb, slot, OLD)) - while len(expected) < 4: - lines.append(f"v_mov_b32 v{10 + len(expected)}, 0") - expected.append(0) - with self.subTest(op_kind=op_kind, chunk=chunk): - got = run_ps_mrt0(lines, ("v10", "v11", "v12", "v13")) - self.assertEqual(got, tuple(expected)) - - def test_base_from_sgpr_inline_and_sequential_four_byte_pack(self): - # src2 from SGPR, inline 0, and inline -1. - got_bases = run_ps_mrt0([ - f"v_mov_b32 v1, {f32_bits(0x4A):#x}", - f"s_mov_b32 s5, {OLD:#x}", - "v_cvt_pk_u8_f32 v10, v1, 2, s5", # 0xDE4ABEEF - "v_cvt_pk_u8_f32 v11, v1, 1, 0", # 0x00004A00 - "v_cvt_pk_u8_f32 v12, v1, 3, -1", # 0x4AFFFFFF - "v_cvt_pk_u8_f32 v13, v1, 0, -1", # 0xFFFFFF4A - ], ("v10", "v11", "v12", "v13")) - self.assertEqual(got_bases, ( - ref_cvt_pk_u8_f32(f32_bits(0x4A), 2, OLD), - ref_cvt_pk_u8_f32(f32_bits(0x4A), 1, 0), - ref_cvt_pk_u8_f32(f32_bits(0x4A), 3, MASK32), - ref_cvt_pk_u8_f32(f32_bits(0x4A), 0, MASK32), - )) - - # Pack 4 floats sequentially into bytes 0, 1, 2, 3 of v0 starting from OLD. - got_packed = run_ps_mrt0([ - f"v_mov_b32 v0, {OLD:#x}", - f"v_mov_b32 v1, {f32_bits(0x11):#x}", - f"v_mov_b32 v2, {f32_bits(0x22):#x}", - f"v_mov_b32 v3, {f32_bits(0x33):#x}", - f"v_mov_b32 v4, {f32_bits(0x44):#x}", - "v_cvt_pk_u8_f32 v0, v1, 0, v0", - "v_cvt_pk_u8_f32 v0, v2, 1, v0", - "v_cvt_pk_u8_f32 v0, v3, 2, v0", - "v_cvt_pk_u8_f32 v0, v4, 3, v0", - ])[0] - self.assertEqual(got_packed, 0x44332211) - - -# ----------------------------------------------------------------------------- -# 3. Clamping, Special Float Inputs, and .5 Round-to-Nearest-Even Ties -# ----------------------------------------------------------------------------- - -class ClampingAndSpecialInputsTests(unittest.TestCase): - def test_negative_overflow_and_subnormal_clamping(self): - cases = [ - # Negatives -> 0 - ("pos_zero", F32_POS_ZERO), - ("neg_zero", F32_NEG_ZERO), - ("neg_tiny", f32_bits(-1e-30)), - ("neg_0_001", f32_bits(-0.001)), - ("neg_half", f32_bits(-0.5)), - ("neg_one", f32_bits(-1.0)), - ("neg_127_5", f32_bits(-127.5)), - ("neg_1000", f32_bits(-1000.0)), - ("neg_flt_max", F32_NEG_FLT_MAX), - ("neg_inf", F32_NEG_INF), - # Overflow -> 255 - ("255_0", f32_bits(255.0)), - ("255_001", f32_bits(255.001)), - ("255_49", f32_bits(255.49)), - ("255_5", f32_bits(255.5)), - ("256_0", f32_bits(256.0)), - ("512_0", f32_bits(512.0)), - ("1e10", f32_bits(1e10)), - ("flt_max", F32_FLT_MAX), - ("pos_inf", F32_POS_INF), - # Tiny subnormals & near-zero normals -> 0 - ("pos_sub_min", F32_POS_SUB_MIN), - ("pos_sub_mid", F32_POS_SUB_MID), - ("pos_sub_max", F32_POS_SUB_MAX), - ("neg_sub_min", F32_NEG_SUB_MIN), - ("neg_sub_max", F32_NEG_SUB_MAX), - ("pos_norm_min", F32_POS_NORM_MIN), - ("neg_norm_min", F32_NEG_NORM_MIN), - # ULP boundaries around 0.5, 1.5, 254.5, 255.0 - ("0_5_minus_ulp", f32_bits(0.5) - 1), - ("0_5_plus_ulp", f32_bits(0.5) + 1), - ("1_5_minus_ulp", f32_bits(1.5) - 1), - ("1_5_plus_ulp", f32_bits(1.5) + 1), - ("254_5_minus_ulp", f32_bits(254.5) - 1), - ("254_5_plus_ulp", f32_bits(254.5) + 1), - ("255_0_minus_ulp", f32_bits(255.0) - 1), - ("255_0_plus_ulp", f32_bits(255.0) + 1), - ] - for start in range(0, len(cases), 4): - chunk = cases[start:start + 4] - lines, expected = [f"v_mov_b32 v3, {OLD:#x}"], [] - for idx, (_, xb) in enumerate(chunk): - slot = (start + idx) & 3 - dst = f"v{10 + idx}" - lines += [ - f"v_mov_b32 v1, {xb:#x}", - f"v_cvt_pk_u8_f32 {dst}, v1, {slot}, v3", - ] - expected.append(ref_cvt_pk_u8_f32(xb, slot, OLD)) - while len(expected) < 4: - lines.append(f"v_mov_b32 v{10 + len(expected)}, 0") - expected.append(0) - with self.subTest(cases=[lbl for lbl, _ in chunk]): - got = run_ps_mrt0(lines, ("v10", "v11", "v12", "v13")) - self.assertEqual(got, tuple(expected)) - - def test_seeded_finite_sweep(self): - rng = random.Random(0xC08E) - samples = [(f32_bits(rng.uniform(-20.0, 280.0)), rng.randrange(0, 8)) for _ in range(64)] - for start in range(0, len(samples), 4): - chunk = samples[start:start + 4] - lines, expected = [f"v_mov_b32 v3, {OLD:#x}"], [] - for idx, (xb, slot) in enumerate(chunk): - dst = f"v{10 + idx}" - lines += [ - f"v_mov_b32 v1, {xb:#x}", - f"v_cvt_pk_u8_f32 {dst}, v1, {slot}, v3", - ] - expected.append(ref_cvt_pk_u8_f32(xb, slot, OLD)) - with self.subTest(batch=start // 4): - self.assertEqual(run_ps_mrt0(lines, ("v10", "v11", "v12", "v13")), tuple(expected)) - - -class RoundToNearestEvenTieTests(unittest.TestCase): - def test_all_half_ties_from_0_5_to_255_5_and_255_49(self): - ties = [k + 0.5 for k in range(256)] + [255.49] - for start in range(0, len(ties), 4): - chunk = ties[start:start + 4] - lines, expected = [f"v_mov_b32 v3, {OLD:#x}"], [] - for idx, x in enumerate(chunk): - xb = f32_bits(x) - slot = (start + idx) & 3 - dst = f"v{10 + idx}" - lines += [ - f"v_mov_b32 v1, {xb:#x}", - f"v_cvt_pk_u8_f32 {dst}, v1, {slot}, v3", - ] - expected.append(ref_cvt_pk_u8_f32(xb, slot, OLD)) - while len(expected) < 4: - lines.append(f"v_mov_b32 v{10 + len(expected)}, 0") - expected.append(0) - with self.subTest(ties=chunk): - got = run_ps_mrt0(lines, ("v10", "v11", "v12", "v13")) - self.assertEqual(got, tuple(expected)) - - def test_all_exact_integers_0_to_255(self): - for start in range(0, 256, 4): - chunk = range(start, start + 4) - lines, expected = [f"v_mov_b32 v3, {OLD:#x}"], [] - for idx, k in enumerate(chunk): - xb = f32_bits(float(k)) - dst = f"v{10 + idx}" - lines += [ - f"v_mov_b32 v1, {xb:#x}", - f"v_cvt_pk_u8_f32 {dst}, v1, {idx}, v3", - ] - expected.append(ref_cvt_pk_u8_f32(xb, idx, OLD)) - with self.subTest(start=start): - self.assertEqual(run_ps_mrt0(lines, ("v10", "v11", "v12", "v13")), tuple(expected)) - - -# ----------------------------------------------------------------------------- -# 4. VOP3 Modifiers, SGPR/Inline Float Sources, Destination Aliasing, EXEC -# ----------------------------------------------------------------------------- - -class SourceModifiersAndOperandsTests(unittest.TestCase): - def test_vop3_source_modifiers(self): - cases = [ - (f32_bits(-42.5), "-v1", 0, 42), # -(-42.5) = 42.5 -> 42 (even) - (f32_bits(-43.5), "-v1", 1, 44), # -(-43.5) = 43.5 -> 44 (even) - (f32_bits(42.5), "-v1", 2, 0), # -(42.5) = -42.5 -> 0 - (F32_NEG_INF, "-v1", 3, 255), # -(-inf) = +inf -> 255 - (F32_POS_INF, "-v1", 0, 0), # -(+inf) = -inf -> 0 - (f32_bits(-13.5), "|v1|", 1, 14), # |-13.5| = 13.5 -> 14 (even) - (f32_bits(-14.5), "|v1|", 2, 14), # |-14.5| = 14.5 -> 14 (even) - (f32_bits(-300.0), "|v1|", 3, 255), # |-300.0| = 300.0 -> 255 - (F32_NEG_INF, "|v1|", 0, 255), # |-inf| = +inf -> 255 - (f32_bits(10.0), "-|v1|", 1, 0), # -|10.0| = -10.0 -> 0 - (f32_bits(-10.0), "-|v1|", 2, 0), # -|-10.0| = -10.0 -> 0 - (F32_NEG_INF, "-|v1|", 3, 0), # -|-inf| = -inf -> 0 - (f32_bits(-1.5), "neg(v1)", 0, 2), # neg(-1.5) = 1.5 -> 2 - (f32_bits(-2.5), "abs(v1)", 1, 2), # abs(-2.5) = 2.5 -> 2 - (f32_bits(-7.5), "-|s4|", 2, 0), - (f32_bits(-7.5), "|s4|", 3, 8), - ] - for start in range(0, len(cases), 4): - chunk = cases[start:start + 4] - lines, expected = [f"v_mov_b32 v3, {OLD:#x}"], [] - for idx, (xb, expr, slot, want_byte) in enumerate(chunk): - dst = f"v{10 + idx}" - reg = "s4" if "s4" in expr else "v1" - lines += [ - f"{'s_mov_b32' if reg == 's4' else 'v_mov_b32'} {reg}, {xb:#x}", - f"v_cvt_pk_u8_f32_e64 {dst}, {expr}, {slot}, v3", - ] - sh = 8 * (slot & 3) - expected.append((OLD & ~(0xFF << sh)) | (want_byte << sh)) - while len(expected) < 4: - lines.append(f"v_mov_b32 v{10 + len(expected)}, 0") - expected.append(0) - with self.subTest(cases=[(e, s) for _, e, s, _ in chunk]): - got = run_ps_mrt0(lines, ("v10", "v11", "v12", "v13")) - self.assertEqual(got, tuple(expected)) - - def test_inline_constant_and_sgpr_float_sources(self): - inline_cases = [ - ("0.5", 0, 0), - ("1.0", 1, 1), - ("2.0", 2, 2), - ("4.0", 3, 4), - ("-1.0", 0, 0), - ("-0.5", 1, 0), - ("-2.0", 2, 0), - ("-4.0", 3, 0), - ("0.0", 0, 0), - ("0", 1, 0), - ] - for start in range(0, len(inline_cases), 4): - chunk = inline_cases[start:start + 4] - lines, expected = [f"v_mov_b32 v3, {OLD:#x}"], [] - for idx, (lit, slot, want_byte) in enumerate(chunk): - dst = f"v{10 + idx}" - lines.append(f"v_cvt_pk_u8_f32 {dst}, {lit}, {slot}, v3") - sh = 8 * (slot & 3) - expected.append((OLD & ~(0xFF << sh)) | (want_byte << sh)) - while len(expected) < 4: - lines.append(f"v_mov_b32 v{10 + len(expected)}, 0") - expected.append(0) - with self.subTest(inlines=[c[0] for c in chunk]): - got = run_ps_mrt0(lines, ("v10", "v11", "v12", "v13")) - self.assertEqual(got, tuple(expected)) - - # SGPR float sources across edge values. - sgpr_cases = [ - (f32_bits(0.5), 0), - (f32_bits(1.0), 1), - (f32_bits(2.0), 2), - (f32_bits(4.0), 3), - (f32_bits(-1.0), 0), - (f32_bits(127.5), 1), - (f32_bits(254.5), 2), - (F32_POS_INF, 3), - ] - for start in range(0, len(sgpr_cases), 4): - chunk = sgpr_cases[start:start + 4] - lines, expected = [f"v_mov_b32 v3, {OLD:#x}"], [] - for idx, (xb, slot) in enumerate(chunk): - dst = f"v{10 + idx}" - lines += [ - f"s_mov_b32 s4, {xb:#x}", - f"v_cvt_pk_u8_f32_e64 {dst}, s4, {slot}, v3", - ] - expected.append(ref_cvt_pk_u8_f32(xb, slot, OLD)) - with self.subTest(batch=start // 4): - got = run_ps_mrt0(lines, ("v10", "v11", "v12", "v13")) - self.assertEqual(got, tuple(expected)) - - def test_destination_aliasing(self): - # 1. dst == src2: v_cvt_pk_u8_f32 v0, v1, 2, v0 - # 2. dst == src0: v_cvt_pk_u8_f32 v0, v0, 1, v3 - # 3. dst == src1: v_cvt_pk_u8_f32 v0, v1, v0, v3 - # 4. dst == src0 == src2: v_cvt_pk_u8_f32 v0, v0, 1, v0 (v0 holds 12.5 = 0x41480000 -> byte 12 at slot 1) - got = run_ps_mrt0([ - f"v_mov_b32 v3, {OLD:#x}", - f"v_mov_b32 v1, {f32_bits(86.0):#x}", - f"v_mov_b32 v10, {OLD:#x}", - "v_cvt_pk_u8_f32 v10, v1, 2, v10", - f"v_mov_b32 v11, {f32_bits(35.5):#x}", - "v_cvt_pk_u8_f32 v11, v11, 1, v3", - "v_mov_b32 v12, 7", - "v_cvt_pk_u8_f32 v12, v1, v12, v3", - f"v_mov_b32 v13, {f32_bits(12.5):#x}", - "v_cvt_pk_u8_f32 v13, v13, 1, v13", - ], ("v10", "v11", "v12", "v13")) - self.assertEqual(got, ( - ref_cvt_pk_u8_f32(f32_bits(86.0), 2, OLD), - ref_cvt_pk_u8_f32(f32_bits(35.5), 1, OLD), - ref_cvt_pk_u8_f32(f32_bits(86.0), 7, OLD), - ref_cvt_pk_u8_f32(f32_bits(12.5), 1, f32_bits(12.5)), - )) - - # 5. All four operands alias v0: 0x41480003 is 12.500003 -> byte 13 (0x0D) at slot (0x41480003 & 3 == 3). - all_alias_in = 0x41480003 - got_all = run_ps_mrt0([ - f"v_mov_b32 v0, {all_alias_in:#x}", - "v_cvt_pk_u8_f32 v0, v0, v0, v0", - ])[0] - self.assertEqual(got_all, ref_cvt_pk_u8_f32(all_alias_in, all_alias_in, all_alias_in)) - self.assertEqual(got_all, 0x0D480003) - - -class ExecMaskingTests(unittest.TestCase): - def test_single_lane_exec_mask_preserves_destination(self): - # Inactive lane leaves v0 untouched; disabled instruction before re-enabling EXEC is skipped. - got = run_ps_mrt0([ - f"v_mov_b32 v1, {f32_bits(77.0):#x}", - f"v_mov_b32 v3, {CANARY:#x}", - f"v_mov_b32 v10, {OLD:#x}", - f"v_mov_b32 v11, {OLD:#x}", - "s_mov_b32 exec_lo, 0", - "v_cvt_pk_u8_f32 v10, v1, 1, v3", - "v_cvt_pk_u8_f32 v11, v1, 0, v3", - "s_mov_b32 exec_lo, -1", - "v_cvt_pk_u8_f32 v11, v1, 2, v3", - ], ("v10", "v11", "v10", "v11")) - self.assertEqual(got[:2], (OLD, ref_cvt_pk_u8_f32(f32_bits(77.0), 2, CANARY))) - - def test_multilane_compute_exec_masking(self): - # 16 lanes in lockstep: odd lanes are masked off via v_cmpx_eq_u32 before v_cvt_pk_u8_f32, - # so active even lanes write the converted byte into OLD while inactive odd lanes keep OLD. - lane_floats = [f32_bits(float(i * 15) + 0.5) for i in range(16)] - mem = _Heap({0x100 + 4 * i: w for i, w in enumerate(lane_floats)}) - run_cs([ - "v_lshlrev_b32_e32 v5, 2, v0", - "v_add_nc_u32_e32 v6, 0x100, v5", - "buffer_load_dword v1, v6, s[0:3], 0 offen", - f"v_mov_b32_e32 v2, {OLD:#x}", - f"v_mov_b32_e32 v3, {OLD:#x}", - "v_and_b32_e32 v4, 1, v0", - "v_cmpx_eq_u32_e32 0, v4", # keep even lanes active - "v_cvt_pk_u8_f32_e64 v2, v1, v0, v3", - "s_mov_b32 exec_lo, -1", - "buffer_store_dword v2, v5, s[0:3], 0 offen", - ], group_size=16, subgroup_size=32, memory=mem) - - got = [mem.get(4 * i) for i in range(16)] - want = [ - ref_cvt_pk_u8_f32(lane_floats[i], i, OLD) if (i & 1) == 0 else OLD - for i in range(16) - ] - self.assertEqual(got, want) - - -# ----------------------------------------------------------------------------- -# 5. NaN Inputs -# ----------------------------------------------------------------------------- - -class NaNHandlingTests(unittest.TestCase): - """A NaN source gives byte 0 (measured on RDNA2, #358): the translator selects +0 before FClamp, - which GLSL.std.450 leaves undefined for a NaN operand, so the interpreter now runs these cases.""" - - def test_nan_gives_zero_byte(self): - nan_cases = [ - ("qnan", F32_QNAN, "v1"), - ("neg_qnan", F32_NEG_QNAN, "v1"), - ("qnan_payload", F32_QNAN_PAYLOAD, "v1"), - ("snan", F32_SNAN, "v1"), - ("neg_snan", F32_NEG_SNAN, "v1"), - ("qnan_abs", F32_NEG_QNAN, "|v1|"), - ("qnan_neg", F32_QNAN, "-v1"), - ] - for label, xb, expr in nan_cases: - with self.subTest(case=label): - spv = translate_ps([ - f"v_mov_b32 v1, {xb:#x}", - f"v_mov_b32 v3, {OLD:#x}", - f"v_cvt_pk_u8_f32_e64 v0, {expr}, 0, v3", - "exp mrt0 v0, v0, v0, v0 done vm", - ]) - self.assertIn("glsl FClamp", spv) - self.assertIn("glsl RoundEven", spv) - self.assertIn("OpConvertFToU", spv) - self.assertEqual(si.run_fragment(spv)["%out_mrt0"][0], ref_cvt_pk_u8_f32(xb, 0, OLD)) - - -# ----------------------------------------------------------------------------- -# 6. Negative Controls (SPIR-V Sabotage Detection) -# ----------------------------------------------------------------------------- - -class NegativeControlsTests(unittest.TestCase): - def test_sabotage_round_even_to_trunc(self): - # 1.5 -> RoundEven gives 2, whereas Trunc gives 1. - good = translate_ps([ - f"v_mov_b32 v1, {f32_bits(1.5):#x}", - f"v_mov_b32 v3, {OLD:#x}", - "v_cvt_pk_u8_f32 v0, v1, 1, v3", - "exp mrt0 v0, v0, v0, v0 done vm", - ]) - want = ref_cvt_pk_u8_f32(f32_bits(1.5), 1, OLD) - self.assertEqual(si.run_fragment(good)["%out_mrt0"][0], want) - - bad, n = re.subn(r"\bRoundEven\b", "Trunc", good) - self.assertEqual(n, 1) - got_bad = si.run_fragment(bad)["%out_mrt0"][0] - self.assertNotEqual(got_bad, want) - self.assertEqual(got_bad, 0xDEAD01EF) - - def test_sabotage_missing_slot_shift(self): - # Removing the * 8 shift (OpIMul %uint %slot3 %c8 -> %c0) writes slot 0 instead of slot 2. - good = translate_ps([ - f"v_mov_b32 v1, {f32_bits(0x42):#x}", - f"v_mov_b32 v3, {OLD:#x}", - "v_cvt_pk_u8_f32 v0, v1, 2, v3", - "exp mrt0 v0, v0, v0, v0 done vm", - ]) - want = ref_cvt_pk_u8_f32(f32_bits(0x42), 2, OLD) - self.assertEqual(si.run_fragment(good)["%out_mrt0"][0], want) - - bad, n = re.subn(r"OpIMul %uint (%\w+) %c8\b", r"OpIMul %uint \1 %c0", good) - self.assertEqual(n, 1) - got_bad = si.run_fragment(bad)["%out_mrt0"][0] - self.assertNotEqual(got_bad, want) - self.assertEqual(got_bad, ref_cvt_pk_u8_f32(f32_bits(0x42), 0, OLD)) - - def test_sabotage_missing_slot_mask(self): - # Widening slot & 3 to slot & 7 breaks slot 5 (shift = 40 >= 32 -> undefined in SPIR-V). - good = translate_ps([ - f"v_mov_b32 v1, {f32_bits(0x42):#x}", - f"v_mov_b32 v2, 5", - f"v_mov_b32 v3, {OLD:#x}", - "v_cvt_pk_u8_f32 v0, v1, v2, v3", - "exp mrt0 v0, v0, v0, v0 done vm", - ]) - want = ref_cvt_pk_u8_f32(f32_bits(0x42), 5, OLD) - self.assertEqual(si.run_fragment(good)["%out_mrt0"][0], want) - - bad, n = re.subn(r"OpBitwiseAnd %uint (%\w+) %c3\b", r"OpBitwiseAnd %uint \1 %c7", good) - self.assertEqual(n, 1) - with self.assertRaises(si.UnsupportedConstruct): - si.run_fragment(bad) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_valu_cvt_u32_f32.py b/tests/semantic/test_valu_cvt_u32_f32.py deleted file mode 100644 index 7e24d50db..000000000 --- a/tests/semantic/test_valu_cvt_u32_f32.py +++ /dev/null @@ -1,177 +0,0 @@ -"""Value tests for v_cvt_u32_f32 (f32 -> u32 with truncation toward zero and saturation): - - v_cvt_u32_f32 D = 0 if x is NaN or x <= -0.0 (negative) - 0xFFFFFFFF if x >= 2^32 (including +inf) - trunc(x) as uint32 otherwise (0.0 <= x < 2^32) - -Each case translates a hand-written pixel-shader listing with tools/rdna2spirv.py -and executes the resulting SPIR-V via tests/semantic/spirv_mini_interp.py. -Standard library only. -""" -import math -import os -import random -import struct -import sys -import unittest - -HERE = os.path.dirname(os.path.abspath(__file__)) -if HERE not in sys.path: - sys.path.insert(0, HERE) - -from support import mrt0_words, translate_lines # noqa: E402 (support puts tools/ on sys.path) - -MASK32 = 0xFFFFFFFF - - -def f32_to_bits(x): - """Pack a Python float into its IEEE-754 binary32 32-bit unsigned word.""" - try: - return struct.unpack(" 0 else 0xFF800000 - - -def bits_to_f32(bits): - """Unpack a 32-bit unsigned word as an IEEE-754 binary32 Python float.""" - return struct.unpack("= 4294967296.0: # 2^32 - return 0xFFFFFFFF - return math.trunc(v) & MASK32 - - -def ref_cvt_i32_f32(bits): - """Plain-Python reference for RDNA2 v_cvt_i32_f32 given a binary32 word.""" - v = bits_to_f32(bits) - if math.isnan(v): - return 0 - if v >= 2147483648.0: # 2^31 - return 0x7FFFFFFF - if v <= -2147483648.0: # -2^31 - return 0x80000000 - return math.trunc(v) & MASK32 - - -def run_cvt(op, src_bits, *, setup=None, src_expr="v1"): - """Translate and run `op v0, ` on a pixel shader; return the uniform mrt0 word.""" - if setup is None: - setup = [f"v_mov_b32 v1, {src_bits & MASK32:#010x}"] - lines = list(setup) + [ - f"{op} v0, {src_expr}", - "exp mrt0 v0, v0, v0, v0 done vm", - "s_endpgm", - ] - spv = translate_lines(f"ps_{op.split()[0]}", lines) - words = mrt0_words(spv) - if len(set(words)) != 1: - raise AssertionError(f"{op}: exported mrt0 words differ: {[hex(w) for w in words]}") - return words[0] - - -# Hand-verified (input_bits, expected_u32) -HAND_CASES = [ - (f32_to_bits(0.0), 0), - (f32_to_bits(0.5), 0), - (0x3F7FFFFF, 0), # 0.99999994 (largest f32 < 1.0) - (f32_to_bits(1.0), 1), - (f32_to_bits(1.9), 1), - (f32_to_bits(42.75), 42), - (f32_to_bits(float(2**24)), 2**24), - (0x4F7FFFFF, 4294967040), # largest f32 < 2^32 - (0x4F800000, 0xFFFFFFFF), # 2^32 -> saturates - (f32_to_bits(1e20), 0xFFFFFFFF), - (0x7F800000, 0xFFFFFFFF), # +inf -> saturates - (0x80000000, 0), # -0.0 -> 0 - (f32_to_bits(-0.5), 0), - (f32_to_bits(-1.0), 0), - (f32_to_bits(-1e20), 0), - (0xFF800000, 0), # -inf -> 0 - (0x7FC00000, 0), # +qNaN -> 0 - (0xFFC00000, 0), # -qNaN -> 0 - (0x7F800001, 0), # +sNaN -> 0 - (0xFF800001, 0), # -sNaN -> 0 -] - - -class ReferenceTests(unittest.TestCase): - def test_hand_constants(self): - for bits, expected in HAND_CASES: - with self.subTest(bits=hex(bits)): - self.assertEqual(ref_cvt_u32_f32(bits), expected) - - -class CvtU32F32Tests(unittest.TestCase): - def test_exact_fractional_overflow_negative_and_nan(self): - for op in ("v_cvt_u32_f32", "v_cvt_u32_f32_e32", "v_cvt_u32_f32_e64"): - for bits, expected in HAND_CASES: - with self.subTest(op=op, bits=hex(bits)): - got = run_cvt(op, bits) - self.assertEqual( - got, expected, - f"{op}({bits:#010x}): got {got:#010x}, expected {expected:#010x}", - ) - - def test_contrast_with_v_cvt_i32_f32(self): - # [2^31, 2^32): u32 converts exact, i32 saturates to 0x7FFFFFFF - upper_range = [ - (f32_to_bits(float(2**31)), 2**31, 0x7FFFFFFF), - (f32_to_bits(3e9), 3000000000, 0x7FFFFFFF), - (0x4F7FFFFF, 4294967040, 0x7FFFFFFF), - ] - for bits, exp_u32, exp_i32 in upper_range: - with self.subTest(bits=hex(bits)): - self.assertEqual(run_cvt("v_cvt_u32_f32", bits), exp_u32) - self.assertEqual(run_cvt("v_cvt_i32_f32", bits), exp_i32) - - # Negative values: u32 gives 0, i32 gives negative signed integer - neg_cases = [ - (f32_to_bits(-1.5), 0, (-1) & MASK32), - (f32_to_bits(-42.75), 0, (-42) & MASK32), - (0xCF000000, 0, 0x80000000), # -2^31 - ] - for bits, exp_u32, exp_i32 in neg_cases: - with self.subTest(bits=hex(bits)): - self.assertEqual(run_cvt("v_cvt_u32_f32", bits), exp_u32) - self.assertEqual(run_cvt("v_cvt_i32_f32", bits), exp_i32) - - def test_operand_kinds_and_vop3_modifiers(self): - cases = [ - ("v_cvt_u32_f32_e32", ["s_mov_b32 s0, 0x422b0000"], "s0", 42), # 42.75 - ("v_cvt_u32_f32_e32", [], "0x42c88000", 100), # 100.25 literal - ("v_cvt_u32_f32_e32", [], "4.0", 4), # inline float - ("v_cvt_u32_f32_e32", [], "-1.0", 0), # inline float -1.0 -> 0 - ("v_cvt_u32_f32_e64", ["s_mov_b32 s0, 0x447a8000"], "s0", 1002), # 1002.0 - ("v_cvt_u32_f32_e64", [], "2.0", 2), - # VOP3 source modifiers (neg / abs) - ("v_cvt_u32_f32_e64", [f"v_mov_b32 v1, {f32_to_bits(-7.5):#010x}"], "-v1", 7), - ("v_cvt_u32_f32_e64", [f"v_mov_b32 v1, {f32_to_bits(-7.5):#010x}"], "|v1|", 7), - ("v_cvt_u32_f32_e64", [f"v_mov_b32 v1, {f32_to_bits(7.5):#010x}"], "-|v1|", 0), - ] - for op, setup, src_expr, expected in cases: - with self.subTest(op=op, src_expr=src_expr): - got = run_cvt(op, 0, setup=setup, src_expr=src_expr) - self.assertEqual(got, expected) - - def test_seeded_random_f32_patterns(self): - rng = random.Random(0xC7032F32) - for _ in range(40): - # Mix exponents across subnormal, normal [0, 2^32), overflow, negative, and NaN/inf - sign = rng.choice((0, 0x80000000)) - exp = rng.choice((0, 127, 128, 150, 158, 159, 200, 255)) - mant = rng.randrange(0, 1 << 23) - bits = sign | (exp << 23) | mant - expected = ref_cvt_u32_f32(bits) - with self.subTest(bits=hex(bits)): - got = run_cvt("v_cvt_u32_f32", bits) - self.assertEqual(got, expected) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_valu_div_fixup.py b/tests/semantic/test_valu_div_fixup.py deleted file mode 100644 index b886e92ef..000000000 --- a/tests/semantic/test_valu_div_fixup.py +++ /dev/null @@ -1,913 +0,0 @@ -"""Standalone idealized IEEE-754 / ISA-PDF reference model tests for v_div_fixup_f32 and v_div_fixup_f16. - -RDNA2 VALU floating-point division fixup instructions: - v_div_fixup_f32 vdst, s0, s1, s2 - v_div_fixup_f16 vdst, s0, s1, s2 [op_sel:[s0_hi, s1_hi, s2_hi, dst_hi]] - -Arguments: - s0: quotient estimate (computed from preliminary reciprocal / Newton-Raphson sequence) - s1: denominator (y in x / y) - s2: numerator (x in x / y) - -Scope note: - This file tests a self-contained textbook IEEE-754 / ISA-PDF model (IEEE=1, denorm32=3, - s1-before-s2 NaN priority, positive canonical +qNaN 0x7FC00000 / 0x7E00); it does NOT invoke - tools/rdna2spirv.py and does NOT match real RDNA2 silicon in the game's inferred MODE. - For the hardware-measured RDNA2 (gfx1036, IEEE=0, denorm32=0, DX10_CLAMP=1) translator contract, - see the ``v_div_fixup_f32`` row in docs/design.md and tests/semantic/test_alu_div_fixup_f32.py. - Key divergences measured natively on gfx1036 (wave32 and wave64): - - NaN priority: hardware prefers s2 (numerator) over s1 (denominator), even under IEEE=1/denorm32=3. - - 0/0 and +-inf/+-inf: hardware returns -qNaN (0xFFC00000), not +qNaN (0x7FC00000). - - sNaN quieting: hardware passes sNaN unchanged under IEEE=0 (quieting only when IEEE=1). - - Subnormals: under denorm32=0, s1/s2 subnormals flush to signed zero (s0 subnormals are kept); - hardware also applies exp(s2) - exp(s1) <= -151 -> +-0.0, NaN(s0) -> +-inf, and - copysign(s0, sign(s1) ^ sign(s2)). - -Idealized IEEE=1 / denorm32=3 model truth table tested in this file: - 1. If s1 is NaN, return quiet NaN (quiet_f32(s1) or quiet_f16(s1)). - 2. If s2 is NaN, return quiet NaN (quiet_f32(s2) or quiet_f16(s2)). - 3. If s1 == 0 and s2 == 0, return NaN (canonical QNaN: 0x7FC00000 for f32, 0x7E00 for f16). - 4. If s1 == 0 and s2 != 0, return sign(s1 ^ s2) * inf. - 5. If s1 == +-inf and s2 == +-inf, return NaN. - 6. If s1 == +-inf and s2 != +-inf, return sign(s1 ^ s2) * 0.0. - 7. If s2 == 0, return sign(s1 ^ s2) * 0.0. - 8. Otherwise return s0. - -Zero game data; standard library Python only; Python 3.9+ compatible. -""" -from __future__ import annotations - -import itertools -import math -import struct -import unittest - -MASK16 = 0xFFFF -MASK32 = 0xFFFFFFFF - -# IEEE-754 binary32 bit constants -F32_POS_ZERO = 0x00000000 -F32_NEG_ZERO = 0x80000000 -F32_POS_INF = 0x7F800000 -F32_NEG_INF = 0xFF800000 -F32_QNAN = 0x7FC00000 -F32_NEG_QNAN = 0xFFC00000 -F32_SNAN = 0x7F800001 -F32_NEG_SNAN = 0xFF800001 - -F32_ONE = 0x3F800000 -F32_NEG_ONE = 0xBF800000 -F32_TWO = 0x40000000 -F32_HALF = 0x3F000000 -F32_NORM_MIN = 0x00800000 -F32_NORM_MAX = 0x7F7FFFFF -F32_SUB_MIN = 0x00000001 -F32_SUB_MAX = 0x007FFFFF -F32_NEG_SUB_MIN = 0x80000001 -F32_NEG_SUB_MAX = 0x807FFFFF - -# IEEE-754 binary16 bit constants -F16_POS_ZERO = 0x0000 -F16_NEG_ZERO = 0x8000 -F16_POS_INF = 0x7C00 -F16_NEG_INF = 0xFC00 -F16_QNAN = 0x7E00 -F16_NEG_QNAN = 0xFE00 -F16_SNAN = 0x7C01 -F16_NEG_SNAN = 0xFC01 - -F16_ONE = 0x3C00 -F16_NEG_ONE = 0xBC00 -F16_TWO = 0x4000 -F16_HALF = 0x3800 -F16_NORM_MIN = 0x0400 -F16_NORM_MAX = 0x7BFF -F16_SUB_MIN = 0x0001 -F16_SUB_MAX = 0x03FF -F16_NEG_SUB_MIN = 0x8001 -F16_NEG_SUB_MAX = 0x83FF - -OLD_VGPR_SENTINEL = 0xDEADBEEF - - -def f32_to_bits(val: float) -> int: - try: - return struct.unpack(" float: - return struct.unpack(" int: - return (bits >> 31) & 1 - - -def is_f32_nan(bits: int) -> bool: - return ((bits & 0x7F800000) == 0x7F800000) and ((bits & 0x007FFFFF) != 0) - - -def is_f32_snan(bits: int) -> bool: - return is_f32_nan(bits) and ((bits & 0x00400000) == 0) - - -def is_f32_qnan(bits: int) -> bool: - return is_f32_nan(bits) and ((bits & 0x00400000) != 0) - - -def is_f32_zero(bits: int) -> bool: - return (bits & 0x7FFFFFFF) == 0 - - -def is_f32_inf(bits: int) -> bool: - return (bits & 0x7FFFFFFF) == 0x7F800000 - - -def is_f32_subnormal(bits: int) -> bool: - return ((bits & 0x7F800000) == 0) and ((bits & 0x007FFFFF) != 0) - - -def is_f32_normal(bits: int) -> bool: - exp = (bits >> 23) & 0xFF - return 0 < exp < 255 - - -def quiet_f32(bits: int) -> int: - """Ensure quiet NaN bit (bit 22) is set on single-precision NaN while preserving payload.""" - if not is_f32_nan(bits): - return F32_QNAN - return (bits & MASK32) | 0x00400000 - - -def ref_v_div_fixup_f32(s0: int, s1: int, s2: int) -> int: - """Idealized IEEE=1 / denorm32=3 reference model for v_div_fixup_f32 (not gfx1036 silicon). - - For the hardware-measured RDNA2 (gfx1036, IEEE=0, denorm32=0) translator contract, see - ``docs/design.md`` and ``tests/semantic/test_alu_div_fixup_f32.py``. - - s0 = quotient estimate - s1 = denominator - s2 = numerator - """ - s0 &= MASK32 - s1 &= MASK32 - s2 &= MASK32 - - sign_xor = f32_sign(s1) ^ f32_sign(s2) - sign_bit = 0x80000000 if sign_xor else 0x00000000 - - if is_f32_nan(s1): - return quiet_f32(s1) - if is_f32_nan(s2): - return quiet_f32(s2) - if is_f32_zero(s1) and is_f32_zero(s2): - return F32_QNAN - if is_f32_zero(s1): - return sign_bit | F32_POS_INF - if is_f32_inf(s1) and is_f32_inf(s2): - return F32_QNAN - if is_f32_inf(s1): - return sign_bit | F32_POS_ZERO - if is_f32_zero(s2): - return sign_bit | F32_POS_ZERO - return s0 - - -def f16_to_bits(val: float) -> int: - try: - return struct.unpack(" float: - return struct.unpack(" int: - return (bits >> 15) & 1 - - -def is_f16_nan(bits: int) -> bool: - return ((bits & 0x7C00) == 0x7C00) and ((bits & 0x03FF) != 0) - - -def is_f16_snan(bits: int) -> bool: - return is_f16_nan(bits) and ((bits & 0x0200) == 0) - - -def is_f16_qnan(bits: int) -> bool: - return is_f16_nan(bits) and ((bits & 0x0200) != 0) - - -def is_f16_zero(bits: int) -> bool: - return (bits & 0x7FFF) == 0 - - -def is_f16_inf(bits: int) -> bool: - return (bits & 0x7FFF) == 0x7C00 - - -def is_f16_subnormal(bits: int) -> bool: - return ((bits & 0x7C00) == 0) and ((bits & 0x03FF) != 0) - - -def is_f16_normal(bits: int) -> bool: - exp = (bits >> 10) & 0x1F - return 0 < exp < 31 - - -def quiet_f16(bits: int) -> int: - """Ensure quiet NaN bit (bit 9) is set on half-precision NaN while preserving payload.""" - if not is_f16_nan(bits): - return F16_QNAN - return (bits & MASK16) | 0x0200 - - -def ref_v_div_fixup_f16(s0: int, s1: int, s2: int) -> int: - """Idealized IEEE=1 / subnormals-kept reference model for v_div_fixup_f16 (not silicon-measured). - - s0 = quotient estimate - s1 = denominator - s2 = numerator - """ - s0 &= MASK16 - s1 &= MASK16 - s2 &= MASK16 - - sign_xor = f16_sign(s1) ^ f16_sign(s2) - sign_bit = 0x8000 if sign_xor else 0x0000 - - if is_f16_nan(s1): - return quiet_f16(s1) - if is_f16_nan(s2): - return quiet_f16(s2) - if is_f16_zero(s1) and is_f16_zero(s2): - return F16_QNAN - if is_f16_zero(s1): - return sign_bit | F16_POS_INF - if is_f16_inf(s1) and is_f16_inf(s2): - return F16_QNAN - if is_f16_inf(s1): - return sign_bit | F16_POS_ZERO - if is_f16_zero(s2): - return sign_bit | F16_POS_ZERO - return s0 - - -def merge_half(old_val: int, half_val: int, dst_hi: int) -> int: - """Write 16-bit half to VGPR word while preserving the unwritten 16-bit half.""" - h = half_val & MASK16 - old = old_val & MASK32 - return ((h << 16) | (old & 0xFFFF)) if dst_hi else ((old & 0xFFFF0000) | h) - - -class WaveDivFixupInterpreter: - """Multi-lane SIMD wave reference interpreter modeling RDNA2 Wave32/Wave64 VALU execution.""" - - def __init__(self, wave_size: int = 32) -> None: - self.wave_size = wave_size - self.exec_mask = (1 << wave_size) - 1 - self.vgprs = [[OLD_VGPR_SENTINEL] * 256 for _ in range(wave_size)] - - def set_lane_vgpr(self, lane: int, reg: int, val: int) -> None: - self.vgprs[lane][reg] = val & MASK32 - - def get_lane_vgpr(self, lane: int, reg: int) -> int: - return self.vgprs[lane][reg] & MASK32 - - def v_div_fixup_f32(self, vdst: int, s0_reg: int, s1_reg: int, s2_reg: int) -> None: - """Executes v_div_fixup_f32 across all lanes conditioned on the exec mask.""" - for lane in range(self.wave_size): - if (self.exec_mask >> lane) & 1: - s0 = self.get_lane_vgpr(lane, s0_reg) - s1 = self.get_lane_vgpr(lane, s1_reg) - s2 = self.get_lane_vgpr(lane, s2_reg) - self.vgprs[lane][vdst] = ref_v_div_fixup_f32(s0, s1, s2) - - def v_div_fixup_f16( - self, - vdst: int, - s0_reg: int, - s1_reg: int, - s2_reg: int, - op_sel: tuple[int, int, int, int] = (0, 0, 0, 0), - ) -> None: - """Executes v_div_fixup_f16 with op_sel across all lanes conditioned on exec mask.""" - s0_hi, s1_hi, s2_hi, dst_hi = op_sel - for lane in range(self.wave_size): - if (self.exec_mask >> lane) & 1: - r0 = self.get_lane_vgpr(lane, s0_reg) - r1 = self.get_lane_vgpr(lane, s1_reg) - r2 = self.get_lane_vgpr(lane, s2_reg) - - s0 = (r0 >> 16) & MASK16 if s0_hi else (r0 & MASK16) - s1 = (r1 >> 16) & MASK16 if s1_hi else (r1 & MASK16) - s2 = (r2 >> 16) & MASK16 if s2_hi else (r2 & MASK16) - - res = ref_v_div_fixup_f16(s0, s1, s2) - curr = self.get_lane_vgpr(lane, vdst) - self.vgprs[lane][vdst] = merge_half(curr, res, dst_hi) - - -class TestF32Classification(unittest.TestCase): - def test_zero_classification(self): - self.assertTrue(is_f32_zero(F32_POS_ZERO)) - self.assertTrue(is_f32_zero(F32_NEG_ZERO)) - self.assertFalse(is_f32_zero(F32_ONE)) - self.assertEqual(f32_sign(F32_POS_ZERO), 0) - self.assertEqual(f32_sign(F32_NEG_ZERO), 1) - - def test_inf_classification(self): - self.assertTrue(is_f32_inf(F32_POS_INF)) - self.assertTrue(is_f32_inf(F32_NEG_INF)) - self.assertFalse(is_f32_inf(F32_QNAN)) - self.assertEqual(f32_sign(F32_POS_INF), 0) - self.assertEqual(f32_sign(F32_NEG_INF), 1) - - def test_nan_classification_and_quieting(self): - self.assertTrue(is_f32_nan(F32_QNAN)) - self.assertTrue(is_f32_nan(F32_SNAN)) - self.assertTrue(is_f32_qnan(F32_QNAN)) - self.assertTrue(is_f32_snan(F32_SNAN)) - self.assertFalse(is_f32_qnan(F32_SNAN)) - self.assertFalse(is_f32_snan(F32_QNAN)) - - quieted = quiet_f32(F32_SNAN) - self.assertTrue(is_f32_qnan(quieted)) - self.assertEqual(quieted, F32_SNAN | 0x00400000) - - # NaN payload preservation on quieting - custom_snan = 0x7F800042 - self.assertTrue(is_f32_snan(custom_snan)) - custom_qnan = quiet_f32(custom_snan) - self.assertTrue(is_f32_qnan(custom_qnan)) - self.assertEqual(custom_qnan & 0x003FFFFF, 0x00000042) - - def test_subnormal_classification(self): - self.assertTrue(is_f32_subnormal(F32_SUB_MIN)) - self.assertTrue(is_f32_subnormal(F32_SUB_MAX)) - self.assertTrue(is_f32_subnormal(F32_NEG_SUB_MIN)) - self.assertTrue(is_f32_subnormal(F32_NEG_SUB_MAX)) - self.assertFalse(is_f32_subnormal(F32_POS_ZERO)) - self.assertFalse(is_f32_subnormal(F32_NORM_MIN)) - - -class TestDivFixupF32ZeroAndInfCases(unittest.TestCase): - def test_zero_divided_by_zero_produces_qnan(self): - for s1 in (F32_POS_ZERO, F32_NEG_ZERO): - for s2 in (F32_POS_ZERO, F32_NEG_ZERO): - with self.subTest(s1=hex(s1), s2=hex(s2)): - res = ref_v_div_fixup_f32(F32_ONE, s1, s2) - self.assertTrue(is_f32_qnan(res)) - self.assertEqual(res, F32_QNAN) - - def test_finite_divided_by_zero_produces_signed_inf(self): - test_cases = [ - (F32_POS_ZERO, F32_ONE, F32_POS_INF), # (+1) / (+0) = +inf - (F32_NEG_ZERO, F32_ONE, F32_NEG_INF), # (+1) / (-0) = -inf - (F32_POS_ZERO, F32_NEG_ONE, F32_NEG_INF), # (-1) / (+0) = -inf - (F32_NEG_ZERO, F32_NEG_ONE, F32_POS_INF), # (-1) / (-0) = +inf - (F32_POS_ZERO, F32_TWO, F32_POS_INF), # (+2) / (+0) = +inf - (F32_NEG_ZERO, F32_TWO, F32_NEG_INF), # (+2) / (-0) = -inf - ] - for s1, s2, expected in test_cases: - with self.subTest(s1=hex(s1), s2=hex(s2)): - res = ref_v_div_fixup_f32(0x12345678, s1, s2) - self.assertEqual(res, expected) - - def test_inf_divided_by_inf_produces_qnan(self): - for s1 in (F32_POS_INF, F32_NEG_INF): - for s2 in (F32_POS_INF, F32_NEG_INF): - with self.subTest(s1=hex(s1), s2=hex(s2)): - res = ref_v_div_fixup_f32(F32_ONE, s1, s2) - self.assertTrue(is_f32_qnan(res)) - self.assertEqual(res, F32_QNAN) - - def test_finite_divided_by_inf_produces_signed_zero(self): - test_cases = [ - (F32_POS_INF, F32_ONE, F32_POS_ZERO), # (+1) / (+inf) = +0.0 - (F32_NEG_INF, F32_ONE, F32_NEG_ZERO), # (+1) / (-inf) = -0.0 - (F32_POS_INF, F32_NEG_ONE, F32_NEG_ZERO), # (-1) / (+inf) = -0.0 - (F32_NEG_INF, F32_NEG_ONE, F32_POS_ZERO), # (-1) / (-inf) = +0.0 - (F32_POS_INF, F32_TWO, F32_POS_ZERO), # (+2) / (+inf) = +0.0 - (F32_NEG_INF, F32_TWO, F32_NEG_ZERO), # (+2) / (-inf) = -0.0 - ] - for s1, s2, expected in test_cases: - with self.subTest(s1=hex(s1), s2=hex(s2)): - res = ref_v_div_fixup_f32(0xCAFEBABE, s1, s2) - self.assertEqual(res, expected) - - def test_zero_divided_by_finite_produces_signed_zero(self): - test_cases = [ - (F32_ONE, F32_POS_ZERO, F32_POS_ZERO), # (+0.0) / (+1) = +0.0 - (F32_NEG_ONE, F32_POS_ZERO, F32_NEG_ZERO), # (+0.0) / (-1) = -0.0 - (F32_ONE, F32_NEG_ZERO, F32_NEG_ZERO), # (-0.0) / (+1) = -0.0 - (F32_NEG_ONE, F32_NEG_ZERO, F32_POS_ZERO), # (-0.0) / (-1) = +0.0 - (F32_TWO, F32_POS_ZERO, F32_POS_ZERO), # (+0.0) / (+2) = +0.0 - (f32_to_bits(-5.0), F32_POS_ZERO, F32_NEG_ZERO), - ] - for s1, s2, expected in test_cases: - with self.subTest(s1=hex(s1), s2=hex(s2)): - res = ref_v_div_fixup_f32(0x99887766, s1, s2) - self.assertEqual(res, expected) - - -class TestDivFixupF32NaNCases(unittest.TestCase): - def test_denominator_nan_propagates_quiet_nan(self): - snan = 0x7F800007 - qnan = 0x7FC00010 - # s1 is sNaN: quiets s1 - res_snan = ref_v_div_fixup_f32(F32_ONE, snan, F32_ONE) - self.assertTrue(is_f32_qnan(res_snan)) - self.assertEqual(res_snan, snan | 0x00400000) - - # s1 is qNaN: returns qNaN - res_qnan = ref_v_div_fixup_f32(F32_ONE, qnan, F32_ONE) - self.assertEqual(res_qnan, qnan) - - def test_numerator_nan_propagates_quiet_nan_when_denom_not_nan(self): - snan = 0x7F80002A - qnan = 0x7FC00055 - res_snan = ref_v_div_fixup_f32(F32_ONE, F32_ONE, snan) - self.assertTrue(is_f32_qnan(res_snan)) - self.assertEqual(res_snan, snan | 0x00400000) - - res_qnan = ref_v_div_fixup_f32(F32_ONE, F32_ONE, qnan) - self.assertEqual(res_qnan, qnan) - - def test_denominator_nan_takes_precedence_over_numerator_nan(self): - s1_nan = 0x7F800111 - s2_nan = 0x7F800222 - res = ref_v_div_fixup_f32(F32_ONE, s1_nan, s2_nan) - self.assertEqual(res, s1_nan | 0x00400000) - - -class TestDivFixupF32NormalPassThrough(unittest.TestCase): - def test_regular_quotient_estimate_passes_through_intact(self): - s0_estimates = [ - f32_to_bits(1.0), - f32_to_bits(0.5), - f32_to_bits(0.25), - f32_to_bits(-3.14159), - 0x12345678, - 0xAABBCCDD, - ] - s1_denom = f32_to_bits(3.0) - s2_num = f32_to_bits(6.0) - - for s0 in s0_estimates: - with self.subTest(s0=hex(s0)): - res = ref_v_div_fixup_f32(s0, s1_denom, s2_num) - self.assertEqual(res, s0) - - -class TestDivFixupF32SimdWaveExecution(unittest.TestCase): - def test_wave32_divergence_under_exec_mask(self): - wave = WaveDivFixupInterpreter(wave_size=32) - wave.exec_mask = 0x55555555 - - vdst, s0_reg, s1_reg, s2_reg = 0, 1, 2, 3 - for lane in range(32): - wave.set_lane_vgpr(lane, s0_reg, F32_HALF) - if lane % 2 == 0: - wave.set_lane_vgpr(lane, s1_reg, F32_POS_ZERO) - wave.set_lane_vgpr(lane, s2_reg, F32_ONE) - else: - wave.set_lane_vgpr(lane, s1_reg, F32_ONE) - wave.set_lane_vgpr(lane, s2_reg, F32_POS_ZERO) - wave.set_lane_vgpr(lane, vdst, OLD_VGPR_SENTINEL) - - wave.v_div_fixup_f32(vdst, s0_reg, s1_reg, s2_reg) - - for lane in range(32): - val = wave.get_lane_vgpr(lane, vdst) - if lane % 2 == 0: - self.assertEqual(val, F32_POS_INF, f"Active lane {lane} failed") - else: - self.assertEqual(val, OLD_VGPR_SENTINEL, f"Inactive lane {lane} mutated") - - def test_wave64_execution(self): - wave = WaveDivFixupInterpreter(wave_size=64) - wave.exec_mask = 0x00000000FFFFFFFF - - vdst, s0_reg, s1_reg, s2_reg = 10, 11, 12, 13 - for lane in range(64): - wave.set_lane_vgpr(lane, s0_reg, F32_ONE) - wave.set_lane_vgpr(lane, s1_reg, F32_POS_ZERO) - wave.set_lane_vgpr(lane, s2_reg, F32_POS_ZERO) - wave.set_lane_vgpr(lane, vdst, 0x11223344) - - wave.v_div_fixup_f32(vdst, s0_reg, s1_reg, s2_reg) - - for lane in range(64): - val = wave.get_lane_vgpr(lane, vdst) - if lane < 32: - self.assertEqual(val, F32_QNAN) - else: - self.assertEqual(val, 0x11223344) - - -class TestF16Classification(unittest.TestCase): - def test_zero_classification(self): - self.assertTrue(is_f16_zero(F16_POS_ZERO)) - self.assertTrue(is_f16_zero(F16_NEG_ZERO)) - self.assertFalse(is_f16_zero(F16_ONE)) - self.assertEqual(f16_sign(F16_POS_ZERO), 0) - self.assertEqual(f16_sign(F16_NEG_ZERO), 1) - - def test_inf_classification(self): - self.assertTrue(is_f16_inf(F16_POS_INF)) - self.assertTrue(is_f16_inf(F16_NEG_INF)) - self.assertFalse(is_f16_inf(F16_QNAN)) - self.assertEqual(f16_sign(F16_POS_INF), 0) - self.assertEqual(f16_sign(F16_NEG_INF), 1) - - def test_nan_classification_and_quieting(self): - self.assertTrue(is_f16_nan(F16_QNAN)) - self.assertTrue(is_f16_nan(F16_SNAN)) - self.assertTrue(is_f16_qnan(F16_QNAN)) - self.assertTrue(is_f16_snan(F16_SNAN)) - self.assertFalse(is_f16_qnan(F16_SNAN)) - self.assertFalse(is_f16_snan(F16_QNAN)) - - quieted = quiet_f16(F16_SNAN) - self.assertTrue(is_f16_qnan(quieted)) - self.assertEqual(quieted, F16_SNAN | 0x0200) - - # Custom payload preservation - custom_snan = 0x7C15 - self.assertTrue(is_f16_snan(custom_snan)) - custom_qnan = quiet_f16(custom_snan) - self.assertTrue(is_f16_qnan(custom_qnan)) - self.assertEqual(custom_qnan & 0x01FF, 0x0015) - - def test_subnormal_classification(self): - self.assertTrue(is_f16_subnormal(F16_SUB_MIN)) - self.assertTrue(is_f16_subnormal(F16_SUB_MAX)) - self.assertTrue(is_f16_subnormal(F16_NEG_SUB_MIN)) - self.assertTrue(is_f16_subnormal(F16_NEG_SUB_MAX)) - self.assertFalse(is_f16_subnormal(F16_POS_ZERO)) - self.assertFalse(is_f16_subnormal(F16_NORM_MIN)) - - -class TestDivFixupF16ZeroAndInfCases(unittest.TestCase): - def test_zero_divided_by_zero_produces_qnan(self): - for s1 in (F16_POS_ZERO, F16_NEG_ZERO): - for s2 in (F16_POS_ZERO, F16_NEG_ZERO): - with self.subTest(s1=hex(s1), s2=hex(s2)): - res = ref_v_div_fixup_f16(F16_ONE, s1, s2) - self.assertTrue(is_f16_qnan(res)) - self.assertEqual(res, F16_QNAN) - - def test_finite_divided_by_zero_produces_signed_inf(self): - test_cases = [ - (F16_POS_ZERO, F16_ONE, F16_POS_INF), # (+1) / (+0) = +inf - (F16_NEG_ZERO, F16_ONE, F16_NEG_INF), # (+1) / (-0) = -inf - (F16_POS_ZERO, F16_NEG_ONE, F16_NEG_INF), # (-1) / (+0) = -inf - (F16_NEG_ZERO, F16_NEG_ONE, F16_POS_INF), # (-1) / (-0) = +inf - (F16_POS_ZERO, F16_TWO, F16_POS_INF), # (+2) / (+0) = +inf - (F16_NEG_ZERO, F16_TWO, F16_NEG_INF), # (+2) / (-0) = -inf - ] - for s1, s2, expected in test_cases: - with self.subTest(s1=hex(s1), s2=hex(s2)): - res = ref_v_div_fixup_f16(0x5678, s1, s2) - self.assertEqual(res, expected) - - def test_inf_divided_by_inf_produces_qnan(self): - for s1 in (F16_POS_INF, F16_NEG_INF): - for s2 in (F16_POS_INF, F16_NEG_INF): - with self.subTest(s1=hex(s1), s2=hex(s2)): - res = ref_v_div_fixup_f16(F16_ONE, s1, s2) - self.assertTrue(is_f16_qnan(res)) - self.assertEqual(res, F16_QNAN) - - def test_finite_divided_by_inf_produces_signed_zero(self): - test_cases = [ - (F16_POS_INF, F16_ONE, F16_POS_ZERO), # (+1) / (+inf) = +0.0 - (F16_NEG_INF, F16_ONE, F16_NEG_ZERO), # (+1) / (-inf) = -0.0 - (F16_POS_INF, F16_NEG_ONE, F16_NEG_ZERO), # (-1) / (+inf) = -0.0 - (F16_NEG_INF, F16_NEG_ONE, F16_POS_ZERO), # (-1) / (-inf) = +0.0 - (F16_POS_INF, F16_TWO, F16_POS_ZERO), # (+2) / (+inf) = +0.0 - (F16_NEG_INF, F16_TWO, F16_NEG_ZERO), # (+2) / (-inf) = -0.0 - ] - for s1, s2, expected in test_cases: - with self.subTest(s1=hex(s1), s2=hex(s2)): - res = ref_v_div_fixup_f16(0xBABE, s1, s2) - self.assertEqual(res, expected) - - def test_zero_divided_by_finite_produces_signed_zero(self): - test_cases = [ - (F16_ONE, F16_POS_ZERO, F16_POS_ZERO), # (+0.0) / (+1) = +0.0 - (F16_NEG_ONE, F16_POS_ZERO, F16_NEG_ZERO), # (+0.0) / (-1) = -0.0 - (F16_ONE, F16_NEG_ZERO, F16_NEG_ZERO), # (-0.0) / (+1) = -0.0 - (F16_NEG_ONE, F16_NEG_ZERO, F16_POS_ZERO), # (-0.0) / (-1) = +0.0 - (F16_TWO, F16_POS_ZERO, F16_POS_ZERO), # (+0.0) / (+2) = +0.0 - (f16_to_bits(-4.0), F16_POS_ZERO, F16_NEG_ZERO), - ] - for s1, s2, expected in test_cases: - with self.subTest(s1=hex(s1), s2=hex(s2)): - res = ref_v_div_fixup_f16(0x7766, s1, s2) - self.assertEqual(res, expected) - - -class TestDivFixupF16NaNCases(unittest.TestCase): - def test_denominator_nan_propagates_quiet_nan(self): - snan = 0x7C05 - qnan = 0x7E12 - res_snan = ref_v_div_fixup_f16(F16_ONE, snan, F16_ONE) - self.assertTrue(is_f16_qnan(res_snan)) - self.assertEqual(res_snan, snan | 0x0200) - - res_qnan = ref_v_div_fixup_f16(F16_ONE, qnan, F16_ONE) - self.assertEqual(res_qnan, qnan) - - def test_numerator_nan_propagates_quiet_nan_when_denom_not_nan(self): - snan = 0x7C2B - qnan = 0x7E5A - res_snan = ref_v_div_fixup_f16(F16_ONE, F16_ONE, snan) - self.assertTrue(is_f16_qnan(res_snan)) - self.assertEqual(res_snan, snan | 0x0200) - - res_qnan = ref_v_div_fixup_f16(F16_ONE, F16_ONE, qnan) - self.assertEqual(res_qnan, qnan) - - def test_denominator_nan_takes_precedence_over_numerator_nan(self): - s1_nan = 0x7C11 - s2_nan = 0x7C22 - res = ref_v_div_fixup_f16(F16_ONE, s1_nan, s2_nan) - self.assertEqual(res, s1_nan | 0x0200) - - -class TestDivFixupF16OpSelAndHalfPreservation(unittest.TestCase): - def test_op_sel_all_combinations_and_half_preservation(self): - r0 = (F16_HALF << 16) | F16_ONE - r1 = (F16_POS_ZERO << 16) | F16_TWO - r2 = (F16_TWO << 16) | F16_POS_ZERO - - wave = WaveDivFixupInterpreter(wave_size=1) - wave.set_lane_vgpr(0, 1, r0) - wave.set_lane_vgpr(0, 2, r1) - wave.set_lane_vgpr(0, 3, r2) - - for s0_hi, s1_hi, s2_hi, dst_hi in itertools.product((0, 1), repeat=4): - with self.subTest(op_sel=(s0_hi, s1_hi, s2_hi, dst_hi)): - initial_vdst = 0xBEEFCAFE - wave.set_lane_vgpr(0, 0, initial_vdst) - wave.v_div_fixup_f16(0, 1, 2, 3, op_sel=(s0_hi, s1_hi, s2_hi, dst_hi)) - - s0 = (r0 >> 16) & MASK16 if s0_hi else (r0 & MASK16) - s1 = (r1 >> 16) & MASK16 if s1_hi else (r1 & MASK16) - s2 = (r2 >> 16) & MASK16 if s2_hi else (r2 & MASK16) - expected_h = ref_v_div_fixup_f16(s0, s1, s2) - - res = wave.get_lane_vgpr(0, 0) - if dst_hi: - self.assertEqual(res >> 16, expected_h) - self.assertEqual(res & 0xFFFF, 0xCAFE, "Low half clobbered when writing high half") - else: - self.assertEqual(res & 0xFFFF, expected_h) - self.assertEqual(res >> 16, 0xBEEF, "High half clobbered when writing low half") - - -class TestDivFixupF16SimdWaveExecution(unittest.TestCase): - def test_wave32_divergence_f16(self): - wave = WaveDivFixupInterpreter(wave_size=32) - wave.exec_mask = 0xAAAAAAAA - - vdst, s0_reg, s1_reg, s2_reg = 0, 1, 2, 3 - for lane in range(32): - wave.set_lane_vgpr(lane, s0_reg, F16_HALF) - wave.set_lane_vgpr(lane, s1_reg, F16_POS_ZERO) - wave.set_lane_vgpr(lane, s2_reg, F16_ONE) - wave.set_lane_vgpr(lane, vdst, 0x12345678) - - wave.v_div_fixup_f16(vdst, s0_reg, s1_reg, s2_reg, op_sel=(0, 0, 0, 0)) - - for lane in range(32): - val = wave.get_lane_vgpr(lane, vdst) - if lane % 2 == 1: - self.assertEqual(val & 0xFFFF, F16_POS_INF) - self.assertEqual(val >> 16, 0x1234) - else: - self.assertEqual(val, 0x12345678) - - -class TestDivFixupSubnormalOperands(unittest.TestCase): - def test_f32_subnormal_quotient_pass_through(self): - # Normal inputs producing subnormal quotient in s0 pass through untouched - for sub in (F32_SUB_MIN, F32_SUB_MAX, F32_NEG_SUB_MIN, F32_NEG_SUB_MAX): - with self.subTest(sub=hex(sub)): - res = ref_v_div_fixup_f32(sub, F32_TWO, F32_ONE) - self.assertEqual(res, sub) - - def test_f32_subnormal_numerator_and_denominator(self): - # Subnormal denominator with normal numerator passes through s0 - s0 = f32_to_bits(123456.0) - res1 = ref_v_div_fixup_f32(s0, F32_SUB_MIN, F32_ONE) - self.assertEqual(res1, s0) - - # Normal denominator with subnormal numerator passes through s0 - res2 = ref_v_div_fixup_f32(s0, F32_ONE, F32_SUB_MAX) - self.assertEqual(res2, s0) - - # Both subnormal passes through s0 - res3 = ref_v_div_fixup_f32(s0, F32_SUB_MIN, F32_SUB_MAX) - self.assertEqual(res3, s0) - - def test_f32_subnormal_with_zero_and_inf(self): - # subnormal / zero -> signed inf - self.assertEqual(ref_v_div_fixup_f32(0, F32_POS_ZERO, F32_SUB_MIN), F32_POS_INF) - self.assertEqual(ref_v_div_fixup_f32(0, F32_NEG_ZERO, F32_SUB_MIN), F32_NEG_INF) - self.assertEqual(ref_v_div_fixup_f32(0, F32_POS_ZERO, F32_NEG_SUB_MIN), F32_NEG_INF) - self.assertEqual(ref_v_div_fixup_f32(0, F32_NEG_ZERO, F32_NEG_SUB_MIN), F32_POS_INF) - - # zero / subnormal -> signed zero - self.assertEqual(ref_v_div_fixup_f32(0, F32_SUB_MIN, F32_POS_ZERO), F32_POS_ZERO) - self.assertEqual(ref_v_div_fixup_f32(0, F32_NEG_SUB_MIN, F32_POS_ZERO), F32_NEG_ZERO) - self.assertEqual(ref_v_div_fixup_f32(0, F32_SUB_MIN, F32_NEG_ZERO), F32_NEG_ZERO) - self.assertEqual(ref_v_div_fixup_f32(0, F32_NEG_SUB_MIN, F32_NEG_ZERO), F32_POS_ZERO) - - # subnormal / inf -> signed zero - self.assertEqual(ref_v_div_fixup_f32(0, F32_POS_INF, F32_SUB_MAX), F32_POS_ZERO) - self.assertEqual(ref_v_div_fixup_f32(0, F32_NEG_INF, F32_SUB_MAX), F32_NEG_ZERO) - - def test_f16_subnormal_quotient_pass_through(self): - for sub in (F16_SUB_MIN, F16_SUB_MAX, F16_NEG_SUB_MIN, F16_NEG_SUB_MAX): - with self.subTest(sub=hex(sub)): - res = ref_v_div_fixup_f16(sub, F16_TWO, F16_ONE) - self.assertEqual(res, sub) - - def test_f16_subnormal_with_zero_and_inf(self): - # subnormal / zero -> signed inf - self.assertEqual(ref_v_div_fixup_f16(0, F16_POS_ZERO, F16_SUB_MIN), F16_POS_INF) - self.assertEqual(ref_v_div_fixup_f16(0, F16_NEG_ZERO, F16_SUB_MIN), F16_NEG_INF) - self.assertEqual(ref_v_div_fixup_f16(0, F16_POS_ZERO, F16_NEG_SUB_MIN), F16_NEG_INF) - self.assertEqual(ref_v_div_fixup_f16(0, F16_NEG_ZERO, F16_NEG_SUB_MIN), F16_POS_INF) - - # zero / subnormal -> signed zero - self.assertEqual(ref_v_div_fixup_f16(0, F16_SUB_MIN, F16_POS_ZERO), F16_POS_ZERO) - self.assertEqual(ref_v_div_fixup_f16(0, F16_NEG_SUB_MIN, F16_POS_ZERO), F16_NEG_ZERO) - self.assertEqual(ref_v_div_fixup_f16(0, F16_SUB_MIN, F16_NEG_ZERO), F16_NEG_ZERO) - self.assertEqual(ref_v_div_fixup_f16(0, F16_NEG_SUB_MIN, F16_NEG_ZERO), F16_POS_ZERO) - - -class TestDivFixupExhaustiveSignMatrix(unittest.TestCase): - def test_f32_sign_xor_rule_exhaustive_matrix(self): - signs = [(0, "+"), (1, "-")] - nonzeros = [ - (F32_ONE, F32_NEG_ONE, "normal"), - (F32_SUB_MIN, F32_NEG_SUB_MIN, "subnormal"), - ] - - for (s1_sign, s1_label), (s2_sign, s2_label) in itertools.product(signs, repeat=2): - expected_sign = s1_sign ^ s2_sign - - # 1. Nonzero / 0 -> Inf - s1_zero = F32_NEG_ZERO if s1_sign else F32_POS_ZERO - for pos_val, neg_val, val_label in nonzeros: - s2_val = neg_val if s2_sign else pos_val - with self.subTest(op=f"{val_label}/{s1_label}0", s1=s1_label, s2=s2_label): - res = ref_v_div_fixup_f32(0, s1_zero, s2_val) - self.assertTrue(is_f32_inf(res)) - self.assertEqual(f32_sign(res), expected_sign) - - # 2. Nonzero / Inf -> 0.0 - s1_inf = F32_NEG_INF if s1_sign else F32_POS_INF - for pos_val, neg_val, val_label in nonzeros: - s2_val = neg_val if s2_sign else pos_val - with self.subTest(op=f"{val_label}/{s1_label}inf", s1=s1_label, s2=s2_label): - res = ref_v_div_fixup_f32(0, s1_inf, s2_val) - self.assertTrue(is_f32_zero(res)) - self.assertEqual(f32_sign(res), expected_sign) - - # 3. 0 / Nonzero -> 0.0 - s2_zero = F32_NEG_ZERO if s2_sign else F32_POS_ZERO - for pos_val, neg_val, val_label in nonzeros: - s1_val = neg_val if s1_sign else pos_val - with self.subTest(op=f"{s2_label}0/{val_label}", s1=s1_label, s2=s2_label): - res = ref_v_div_fixup_f32(0, s1_val, s2_zero) - self.assertTrue(is_f32_zero(res)) - self.assertEqual(f32_sign(res), expected_sign) - - def test_f16_sign_xor_rule_exhaustive_matrix(self): - signs = [(0, "+"), (1, "-")] - nonzeros = [ - (F16_ONE, F16_NEG_ONE, "normal"), - (F16_SUB_MIN, F16_NEG_SUB_MIN, "subnormal"), - ] - - for (s1_sign, s1_label), (s2_sign, s2_label) in itertools.product(signs, repeat=2): - expected_sign = s1_sign ^ s2_sign - - # Nonzero / 0 -> Inf - s1_zero = F16_NEG_ZERO if s1_sign else F16_POS_ZERO - for pos_val, neg_val, val_label in nonzeros: - s2_val = neg_val if s2_sign else pos_val - with self.subTest(op=f"f16_{val_label}/{s1_label}0", s1=s1_label, s2=s2_label): - res = ref_v_div_fixup_f16(0, s1_zero, s2_val) - self.assertTrue(is_f16_inf(res)) - self.assertEqual(f16_sign(res), expected_sign) - - -class TestDivFixupNegativeControls(unittest.TestCase): - def test_sabotaged_sign_xor_fails(self): - # Sabotage: replace sign_xor with AND (fails when one operand is negative and other positive) - def bad_ref_f32(s0: int, s1: int, s2: int) -> int: - sign_and = f32_sign(s1) & f32_sign(s2) # Sabotaged: AND instead of XOR - sign_bit = 0x80000000 if sign_and else 0x00000000 - if is_f32_zero(s1) and not is_f32_zero(s2): - return sign_bit | F32_POS_INF - return s0 - - # (+1) / (-0) should be -inf, but sabotaged sign gives +inf - correct = ref_v_div_fixup_f32(0, F32_NEG_ZERO, F32_ONE) - sabotaged = bad_ref_f32(0, F32_NEG_ZERO, F32_ONE) - self.assertEqual(correct, F32_NEG_INF) - self.assertEqual(sabotaged, F32_POS_INF) - self.assertNotEqual(correct, sabotaged) - - def test_sabotaged_snan_quieting_fails(self): - # Sabotage: returning sNaN directly without setting quiet bit - def bad_ref_f32(s0: int, s1: int, s2: int) -> int: - if is_f32_nan(s1): - return s1 # Sabotaged: forgot quiet_f32 - return s0 - - res_correct = ref_v_div_fixup_f32(F32_ONE, F32_SNAN, F32_ONE) - res_bad = bad_ref_f32(F32_ONE, F32_SNAN, F32_ONE) - self.assertTrue(is_f32_qnan(res_correct)) - self.assertTrue(is_f32_snan(res_bad)) - self.assertNotEqual(res_correct, res_bad) - - def test_sabotaged_zero_div_zero_fails(self): - # Sabotage: returning 0 instead of NaN for 0 / 0 - def bad_ref_f32(s0: int, s1: int, s2: int) -> int: - if is_f32_zero(s1) and is_f32_zero(s2): - return F32_POS_ZERO # Sabotaged: returns 0 instead of QNaN - return s0 - - res_correct = ref_v_div_fixup_f32(F32_ONE, F32_POS_ZERO, F32_POS_ZERO) - res_bad = bad_ref_f32(F32_ONE, F32_POS_ZERO, F32_POS_ZERO) - self.assertTrue(is_f32_qnan(res_correct)) - self.assertFalse(is_f32_nan(res_bad)) - self.assertNotEqual(res_correct, res_bad) - - def test_sabotaged_inf_div_inf_fails(self): - # Sabotage: returning 1.0 instead of NaN for inf / inf - def bad_ref_f32(s0: int, s1: int, s2: int) -> int: - if is_f32_inf(s1) and is_f32_inf(s2): - return F32_ONE # Sabotaged: returns 1.0 instead of QNaN - return s0 - - res_correct = ref_v_div_fixup_f32(F32_ONE, F32_POS_INF, F32_POS_INF) - res_bad = bad_ref_f32(F32_ONE, F32_POS_INF, F32_POS_INF) - self.assertTrue(is_f32_qnan(res_correct)) - self.assertEqual(res_bad, F32_ONE) - self.assertNotEqual(res_correct, res_bad) - - def test_sabotaged_nan_precedence_fails(self): - # Sabotage: checking s2 (numerator) before s1 (denominator) - def bad_ref_f32(s0: int, s1: int, s2: int) -> int: - if is_f32_nan(s2): # Sabotaged: inverted priority - return quiet_f32(s2) - if is_f32_nan(s1): - return quiet_f32(s1) - return s0 - - s1_nan = 0x7F8000AA - s2_nan = 0x7F8000BB - correct = ref_v_div_fixup_f32(F32_ONE, s1_nan, s2_nan) - sabotaged = bad_ref_f32(F32_ONE, s1_nan, s2_nan) - self.assertEqual(correct, s1_nan | 0x00400000) - self.assertEqual(sabotaged, s2_nan | 0x00400000) - self.assertNotEqual(correct, sabotaged) - - def test_sabotaged_inactive_lane_bleed_fails(self): - # Sabotage: interpreter mutates inactive lanes - wave = WaveDivFixupInterpreter(wave_size=4) - wave.exec_mask = 0b0001 # only lane 0 active - - for lane in range(4): - wave.set_lane_vgpr(lane, 0, OLD_VGPR_SENTINEL) - wave.set_lane_vgpr(lane, 1, F32_ONE) - wave.set_lane_vgpr(lane, 2, F32_POS_ZERO) - wave.set_lane_vgpr(lane, 3, F32_ONE) - - # Correct execution - wave.v_div_fixup_f32(0, 1, 2, 3) - self.assertEqual(wave.get_lane_vgpr(0, 0), F32_POS_INF) - self.assertEqual(wave.get_lane_vgpr(1, 0), OLD_VGPR_SENTINEL) - self.assertEqual(wave.get_lane_vgpr(2, 0), OLD_VGPR_SENTINEL) - self.assertEqual(wave.get_lane_vgpr(3, 0), OLD_VGPR_SENTINEL) - - # Sabotaged execution: clobber all lanes regardless of exec - for lane in range(4): - wave.vgprs[lane][0] = 0x00000000 - self.assertNotEqual(wave.get_lane_vgpr(1, 0), OLD_VGPR_SENTINEL) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_valu_dot4_int.py b/tests/semantic/test_valu_dot4_int.py deleted file mode 100644 index 5f7b73e40..000000000 --- a/tests/semantic/test_valu_dot4_int.py +++ /dev/null @@ -1,113 +0,0 @@ -"""v_dot4_u32_u8 and v_dot4_i32_i8 (RDNA2 VOP3P): D = S2 + sum of the four byte products of S0 and S1 (unsigned bytes -for u8, signed for i8), modulo 2^32; with `clamp` the result saturates to [0, 2^32-1] (u8) or [-2^31, 2^31-1] (i8). - -Each case is translated by tools/rdna2spirv.py and executed with tests/semantic/spirv_mini_interp.py; the expected -words are written by hand and also recomputed by a plain-Python reference. v_dot4acc_u32_u8 is not a RDNA2 opcode the -translator knows, and stays refused. Standard library only: no GPU, no LLVM, no game data. -""" -import os -import random -import sys -import unittest - -HERE = os.path.dirname(os.path.abspath(__file__)) -sys.dont_write_bytecode = True -sys.path.insert(0, HERE) - -import support # noqa: E402 -from rdna2spirv import Unsupported # noqa: E402 - -MASK32 = 0xFFFFFFFF -INT32_MIN, INT32_MAX = -0x80000000, 0x7FFFFFFF - - -def pk(*b): - """Pack four bytes, byte 0 first, into a dword.""" - return sum((x & 0xFF) << (8 * i) for i, x in enumerate(b)) - - -def ref(op, s0, s1, s2, clamp=False): - signed = "i8" in op - def byte(v, i): - x = (v >> (8 * i)) & 0xFF - return x - 256 if signed and x & 0x80 else x - total = sum(byte(s0, i) * byte(s1, i) for i in range(4)) - if signed: - acc = s2 - (1 << 32) if s2 & 0x80000000 else s2 - total += acc - if clamp: - total = max(INT32_MIN, min(INT32_MAX, total)) - else: - total += s2 - if clamp: - total = min(MASK32, total) - return total & MASK32 - - -def run(op, s0, s1, s2, clamp=False, form="vgpr"): - if form == "vgpr": - setup = [f"v_mov_b32 v1, {s0:#x}", f"v_mov_b32 v2, {s1:#x}", f"v_mov_b32 v3, {s2:#x}"] - srcs = "v1, v2, v3" - else: - setup = [f"s_mov_b32 s1, {s0:#x}", f"s_mov_b32 s2, {s1:#x}", f"s_mov_b32 s3, {s2:#x}"] - srcs = "s1, s2, s3" - lines = setup + [f"{op} v0, {srcs}{' clamp' if clamp else ''}", "exp mrt0 v0, v0, v0, v0 done vm", "s_endpgm"] - return support.mrt0_words(support.translate_lines("ps_dot4", lines))[0] - - -# (name, op, S0, S1, S2, clamp, expected word), written by hand. -CASES = [ - ("u8 basic: 1*5+2*6+3*7+4*8", "v_dot4_u32_u8", pk(1, 2, 3, 4), pk(5, 6, 7, 8), 0, False, 70), - ("u8 basic with accumulator", "v_dot4_u32_u8", pk(1, 2, 3, 4), pk(5, 6, 7, 8), 1000, False, 1070), - ("u8 zero operand keeps S2", "v_dot4_u32_u8", 0, 0x12345678, 0xDEADBEEF, False, 0xDEADBEEF), - ("u8 zero operand keeps S2 (swapped)", "v_dot4_u32_u8", 0x12345678, 0, 0xCAFEBABE, False, 0xCAFEBABE), - ("u8 maximum: 4*255*255", "v_dot4_u32_u8", MASK32, MASK32, 0, False, 260100), - ("u8 maximum plus 100", "v_dot4_u32_u8", MASK32, MASK32, 100, False, 260200), - ("u8 wraps to 0", "v_dot4_u32_u8", MASK32, MASK32, 0xFFFC07FC, False, 0), - ("u8 wraps to 1", "v_dot4_u32_u8", MASK32, MASK32, 0xFFFC07FD, False, 1), - ("u8 wraps without clamp", "v_dot4_u32_u8", MASK32, MASK32, 0xFFFF0000, False, 0x0002F804), - ("u8 clamp saturates", "v_dot4_u32_u8", MASK32, MASK32, 0xFFFF0000, True, 0xFFFFFFFF), - ("i8 basic", "v_dot4_i32_i8", pk(1, 2, 3, 4), pk(5, 6, 7, 8), 0, False, 70), - ("i8 basic with accumulator", "v_dot4_i32_i8", pk(1, 2, 3, 4), pk(5, 6, 7, 8), 500, False, 570), - ("i8 mixed signs: -5-12+21-32", "v_dot4_i32_i8", pk(-1, 2, -3, -4), pk(5, -6, -7, 8), 0, False, 0xFFFFFFE4), - ("i8 max positive: 4*(-128)^2", "v_dot4_i32_i8", pk(-128, -128, -128, -128), pk(-128, -128, -128, -128), 0, False, 65536), - ("i8 max negative: 4*(-128*127)", "v_dot4_i32_i8", pk(-128, -128, -128, -128), pk(127, 127, 127, 127), 0, False, 0xFFFF0200), - ("i8 wraps negative", "v_dot4_i32_i8", pk(-128, -128, -128, -128), pk(-128, -128, -128, -128), INT32_MAX, False, 0x8000FFFF), - ("i8 clamp to INT32_MAX", "v_dot4_i32_i8", pk(-128, -128, -128, -128), pk(-128, -128, -128, -128), INT32_MAX, True, 0x7FFFFFFF), - ("i8 clamp to INT32_MIN", "v_dot4_i32_i8", pk(-128, -128, -128, -128), pk(127, 127, 127, 127), 0x80000000, True, 0x80000000), - ("0xFF is 255 unsigned", "v_dot4_u32_u8", pk(255, 0, 0, 0), pk(1, 0, 0, 0), 0, False, 255), - ("0xFF is -1 signed", "v_dot4_i32_i8", pk(255, 0, 0, 0), pk(1, 0, 0, 0), 0, False, 0xFFFFFFFF), -] - - -class Dot4Int(unittest.TestCase): - def test_hand_written_table_matches_reference(self): - for name, op, s0, s1, s2, clamp, want in CASES: - self.assertEqual(ref(op, s0, s1, s2, clamp), want, name) - - def test_translated_cases(self): - for name, op, s0, s1, s2, clamp, want in CASES: - with self.subTest(name): - self.assertEqual(run(op, s0, s1, s2, clamp), want) - - def test_sgpr_sources(self): - for name, op, s0, s1, s2, clamp, want in CASES[:6] + CASES[10:13]: - with self.subTest(name): - self.assertEqual(run(op, s0, s1, s2, clamp, "sgpr"), want) - - def test_random_operands(self): - rng = random.Random(0x646F7434) - for _ in range(40): - s0, s1, s2 = (rng.getrandbits(32) for _ in range(3)) - for op in ("v_dot4_u32_u8", "v_dot4_i32_i8"): - for clamp in (False, True): - with self.subTest(op=op, clamp=clamp, s0=hex(s0), s1=hex(s1), s2=hex(s2)): - self.assertEqual(run(op, s0, s1, s2, clamp), ref(op, s0, s1, s2, clamp)) - - def test_dot4acc_is_refused_not_guessed(self): - with self.assertRaises(Unsupported): - run("v_dot4acc_u32_u8", pk(1, 2, 3, 4), pk(5, 6, 7, 8), 1000) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_valu_dot4acc_refused.py b/tests/semantic/test_valu_dot4acc_refused.py deleted file mode 100644 index 2dfee8b5e..000000000 --- a/tests/semantic/test_valu_dot4acc_refused.py +++ /dev/null @@ -1,28 +0,0 @@ -"""v_dot4acc_u32_u8 is not an RDNA2 opcode the translator implements: it must stay refused, not guessed. - -This replaces the one translator-level check of the deleted test_alu_dot4acc_u8.py. test_valu_dot4_int.py (#3472) pins -the same refusal once it lands; until then this keeps it. Standard library only: no GPU, no LLVM, no game data. -""" -import os -import sys -import unittest - -sys.dont_write_bytecode = True -sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) -import support # noqa: E402 -from rdna2spirv import Unsupported # noqa: E402 - - -class Dot4AccRefused(unittest.TestCase): - def test_refused_in_each_operand_form(self): - for src in ("v1, v2, v3", "s1, s2, s3", "v1, v2, 0"): - with self.subTest(src=src): - lines = ["v_mov_b32 v1, 1", "v_mov_b32 v2, 1", "v_mov_b32 v3, 0", "s_mov_b32 s1, 1", "s_mov_b32 s2, 1", - "s_mov_b32 s3, 0", f"v_dot4acc_u32_u8 v8, {src}", "exp mrt0 v8, v8, v8, v8 done vm", "s_endpgm"] - with self.assertRaises(Unsupported) as cm: - support.translate_lines("ps_dot4acc_refused", lines) - self.assertIn("v_dot4acc_u32_u8", str(cm.exception)) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_valu_dot8_int.py b/tests/semantic/test_valu_dot8_int.py deleted file mode 100644 index fb3b94184..000000000 --- a/tests/semantic/test_valu_dot8_int.py +++ /dev/null @@ -1,112 +0,0 @@ -"""v_dot8_u32_u4 and v_dot8_i32_i4 (RDNA2 VOP3P): D = S2 + sum of the eight nibble products of S0 and S1 (unsigned -nibbles for u4, signed for i4), modulo 2^32; with `clamp` the result saturates to [0, 2^32-1] (u4) or -[-2^31, 2^31-1] (i4). - -Each case is translated by tools/rdna2spirv.py and executed with tests/semantic/spirv_mini_interp.py; the expected -words are written by hand and also recomputed by a plain-Python reference. Standard library only: no GPU, no LLVM, -no game data. -""" -import os -import random -import sys -import unittest - -HERE = os.path.dirname(os.path.abspath(__file__)) -sys.dont_write_bytecode = True -sys.path.insert(0, HERE) - -import support # noqa: E402 - -MASK32 = 0xFFFFFFFF -INT32_MIN, INT32_MAX = -0x80000000, 0x7FFFFFFF - - -def pk(*n): - """Pack eight nibbles, nibble 0 first, into a dword.""" - return sum((x & 0xF) << (4 * i) for i, x in enumerate(n)) - - -def ref(op, s0, s1, s2, clamp=False): - signed = "i4" in op - def nib(v, i): - x = (v >> (4 * i)) & 0xF - return x - 16 if signed and x & 8 else x - total = sum(nib(s0, i) * nib(s1, i) for i in range(8)) - if signed: - total += s2 - (1 << 32) if s2 & 0x80000000 else s2 - if clamp: - total = max(INT32_MIN, min(INT32_MAX, total)) - else: - total += s2 - if clamp: - total = min(MASK32, total) - return total & MASK32 - - -def run(op, s0, s1, s2, clamp=False, form="vgpr"): - if form == "vgpr": - setup = [f"v_mov_b32 v1, {s0:#x}", f"v_mov_b32 v2, {s1:#x}", f"v_mov_b32 v3, {s2:#x}"] - srcs = "v1, v2, v3" - else: - setup = [f"s_mov_b32 s1, {s0:#x}", f"s_mov_b32 s2, {s1:#x}", f"s_mov_b32 s3, {s2:#x}"] - srcs = "s1, s2, s3" - lines = setup + [f"{op} v0, {srcs}{' clamp' if clamp else ''}", "exp mrt0 v0, v0, v0, v0 done vm", "s_endpgm"] - return support.mrt0_words(support.translate_lines("ps_dot8", lines))[0] - - -U, I = "v_dot8_u32_u4", "v_dot8_i32_i4" -ALL_M8 = pk(*[-8] * 8) # eight nibbles of -8 (0x8 each) -ALL_7 = pk(*[7] * 8) - -# (name, op, S0, S1, S2, clamp, expected word), written by hand. -CASES = [ - ("u4 basic: 0*1+1*2+...+7*8 = 168", U, pk(0, 1, 2, 3, 4, 5, 6, 7), pk(1, 2, 3, 4, 5, 6, 7, 8), 0, False, 168), - ("u4 basic with accumulator", U, pk(0, 1, 2, 3, 4, 5, 6, 7), pk(1, 2, 3, 4, 5, 6, 7, 8), 500, False, 668), - ("u4 zero operand keeps S2", U, 0, 0x12345678, 0x1234ABCD, False, 0x1234ABCD), - ("u4 zero operand keeps S2 (swapped)", U, 0x12345678, 0, 0xCAFEBABE, False, 0xCAFEBABE), - ("u4 maximum: 8*15*15", U, MASK32, MASK32, 0, False, 1800), - ("u4 maximum plus 200", U, MASK32, MASK32, 200, False, 2000), - ("u4 wraps to 0", U, MASK32, MASK32, 0xFFFFF8F8, False, 0), - ("u4 wraps to 1", U, MASK32, MASK32, 0xFFFFF8F9, False, 1), - ("u4 without clamp wraps", U, MASK32, MASK32, 0xFFFFFFF0, False, 0x000006F8), - ("u4 clamp saturates", U, MASK32, MASK32, 0xFFFFFFF0, True, 0xFFFFFFFF), - ("i4 basic: 1+2+3+4-1-2-3-4 = 0", I, pk(1, 2, 3, 4, -1, -2, -3, -4), pk(*[1] * 8), 0, False, 0), - ("i4 basic with accumulator", I, pk(1, 2, 3, 4, -1, -2, -3, -4), pk(*[1] * 8), 77, False, 77), - ("i4 negative operands: 2 * -20 = -40", I, pk(-1, -2, -3, -4, -1, -2, -3, -4), pk(*[2] * 8), 0, False, 0xFFFFFFD8), - ("i4 max positive: 8*(-8)^2", I, ALL_M8, ALL_M8, 0, False, 512), - ("i4 max negative: 8*(-8*7)", I, ALL_M8, ALL_7, 0, False, 0xFFFFFE40), - ("i4 wraps negative", I, ALL_M8, ALL_M8, INT32_MAX, False, 0x800001FF), - ("i4 clamp to INT32_MAX", I, ALL_M8, ALL_M8, INT32_MAX, True, 0x7FFFFFFF), - ("i4 clamp to INT32_MIN", I, ALL_M8, ALL_7, 0x80000000, True, 0x80000000), - ("0xF is 15 unsigned", U, pk(15, 0, 0, 0, 0, 0, 0, 0), pk(1, 0, 0, 0, 0, 0, 0, 0), 0, False, 15), - ("0xF is -1 signed", I, pk(15, 0, 0, 0, 0, 0, 0, 0), pk(1, 0, 0, 0, 0, 0, 0, 0), 0, False, 0xFFFFFFFF), -] - - -class Dot8Int(unittest.TestCase): - def test_hand_written_table_matches_reference(self): - for name, op, s0, s1, s2, clamp, want in CASES: - self.assertEqual(ref(op, s0, s1, s2, clamp), want, name) - - def test_translated_cases(self): - for name, op, s0, s1, s2, clamp, want in CASES: - with self.subTest(name): - self.assertEqual(run(op, s0, s1, s2, clamp), want) - - def test_sgpr_sources(self): - for name, op, s0, s1, s2, clamp, want in CASES[:6] + CASES[10:14]: - with self.subTest(name): - self.assertEqual(run(op, s0, s1, s2, clamp, "sgpr"), want) - - def test_random_operands(self): - rng = random.Random(0x646F7438) - for _ in range(40): - s0, s1, s2 = (rng.getrandbits(32) for _ in range(3)) - for op in (U, I): - for clamp in (False, True): - with self.subTest(op=op, clamp=clamp, s0=hex(s0), s1=hex(s1), s2=hex(s2)): - self.assertEqual(run(op, s0, s1, s2, clamp), ref(op, s0, s1, s2, clamp)) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_valu_f16_exp_log_rsq_mul.py b/tests/semantic/test_valu_f16_exp_log_rsq_mul.py deleted file mode 100644 index 0bf8717e6..000000000 --- a/tests/semantic/test_valu_f16_exp_log_rsq_mul.py +++ /dev/null @@ -1,312 +0,0 @@ -"""Semantic interpreter tests for RDNA2 v_mul_f16, v_exp_f16, v_log_f16, and v_rsq_f16. - -Covers: - - v_mul_f16: S0.f16 * S1.f16 (powers of two, fractions, negatives, +-0.0, +-inf, overflow, subnormals/underflow, NaN) - - v_exp_f16: 2 ** S0.f16 - - v_log_f16: log2(S0.f16) (for S0 > 0; spirv_mini_interp rejects Log2(x <= 0) as undefined in GLSL.std.450) - - v_rsq_f16: 1 / sqrt(S0.f16) (for S0 > 0; spirv_mini_interp rejects InverseSqrt(x <= 0) as undefined) - -Per docs/design.md ("16-bit results"), GFX10+ 16-bit VALU ops write one 16-bit half of the destination VGPR -while preserving the other 16-bit half: _e32 writes bits 15:0 (preserving bits 31:16), and _e64 with -op_sel:[...,1] writes bits 31:16 (preserving bits 15:0). -""" -import math -import os -import struct -import sys -import unittest - -HERE = os.path.dirname(os.path.abspath(__file__)) -sys.dont_write_bytecode = True -if HERE not in sys.path: - sys.path.insert(0, HERE) - -import spirv_mini_interp as si # noqa: E402 -import support # noqa: E402 - -OLD = 0xBEEF1234 - -# Representative binary16 encodings. -H_POS_ZERO = 0x0000 -H_NEG_ZERO = 0x8000 -H_SUB_MIN = 0x0001 # 2^-24 -H_NORM_MIN = 0x0400 # 2^-14 -H_0P0625 = 0x2C00 # 0.0625 (2^-4) -H_0P25 = 0x3400 # 0.25 -H_0P3 = 0x34CD # ~0.3 -H_0P5 = 0x3800 # 0.5 -H_NEG_0P5 = 0xB800 # -0.5 -H_1P0 = 0x3C00 # 1.0 -H_NEG_1P0 = 0xBC00 # -1.0 -H_1P25 = 0x3D00 # 1.25 -H_1P5 = 0x3E00 # 1.5 -H_NEG_1P5 = 0xBE00 # -1.5 -H_1P75 = 0x3F00 # 1.75 -H_2P0 = 0x4000 # 2.0 -H_NEG_2P0 = 0xC000 # -2.0 -H_3P0 = 0x4200 # 3.0 -H_NEG_3P0 = 0xC200 # -3.0 -H_4P0 = 0x4400 # 4.0 -H_NEG_4P0 = 0xC400 # -4.0 -H_5P5 = 0x4580 # 5.5 -H_10P0 = 0x4900 # 10.0 -H_15P0 = 0x4B80 # 15.0 -H_16P0 = 0x4C00 # 16.0 -H_NEG_25P0 = 0xCE40 # -25.0 -H_1024 = 0x6400 # 1024.0 -H_MAX = 0x7BFF # 65504.0 -H_NEG_MAX = 0xFBFF # -65504.0 -H_POS_INF = 0x7C00 # +inf -H_NEG_INF = 0xFC00 # -inf -H_QNAN = 0x7E01 # +qNaN - - -def h2f(h: int) -> float: - return struct.unpack(" float: - try: - return struct.unpack(" 0 else -math.inf - - -def f2h(x: float) -> int: - try: - return struct.unpack(" 0 else H_NEG_INF - - -def is_f16_nan(h: int) -> bool: - return (h & 0x7FFF) > 0x7C00 - - -def pack_expected(h: int, old: int = OLD, dst_hi: bool = False) -> int: - return ((h << 16) | (old & 0xFFFF)) if dst_hi else ((old & 0xFFFF0000) | h) - - -def clamp01(x: float) -> float: - if x < 0.0: - return 0.0 - if x > 1.0: - return 1.0 - return x - - -def ref_mul_f16(a: int, b: int, clamp: bool = False) -> int: - r = f32(h2f(a) * h2f(b)) - if clamp and not math.isnan(r): - r = clamp01(r) - return f2h(r) - - -def ref_exp_f16(a: int, clamp: bool = False) -> int: - x = h2f(a) - if math.isnan(x): - return H_QNAN - r = (math.inf if x > 0 else 0.0) if math.isinf(x) else (f32(2.0 ** x) if x < 1024.0 else math.inf) - if clamp: - r = clamp01(r) - return f2h(r) - - -def ref_log_f16(a: int, clamp: bool = False) -> int: - x = h2f(a) - if math.isnan(x): - return H_QNAN - r = math.inf if math.isinf(x) else f32(math.log2(x)) - if clamp: - r = clamp01(r) - return f2h(r) - - -def ref_rsq_f16(a: int, clamp: bool = False) -> int: - x = h2f(a) - if math.isnan(x): - return H_QNAN - r = 0.0 if math.isinf(x) else f32(1.0 / math.sqrt(x)) - if clamp: - r = clamp01(r) - return f2h(r) - - -def run_ps(setup_lines, op_line: str, old: int = OLD) -> int: - lines = list(setup_lines) + [ - f"v_mov_b32 v0, {old:#x}", - op_line, - "exp mrt0 v0, v0, v0, v0 done vm", - "s_endpgm", - ] - spv = support.translate_lines("ps_f16_ops", lines) - return si.run_fragment(spv)["%out_mrt0"][0] - - -class MulF16Tests(unittest.TestCase): - EXACT_CASES = [ - (H_1P0, H_2P0, "1.0 * 2.0"), - (H_0P5, H_4P0, "0.5 * 4.0"), - (H_0P25, H_0P5, "0.25 * 0.5"), - (H_1P5, H_1P5, "1.5 * 1.5"), - (H_1P25, H_1P75, "1.25 * 1.75"), - (H_NEG_1P5, H_2P0, "-1.5 * 2.0"), - (H_NEG_2P0, H_NEG_3P0, "-2.0 * -3.0"), - (H_POS_ZERO, H_1P0, "+0.0 * 1.0"), - (H_NEG_ZERO, H_1P0, "-0.0 * 1.0"), - (H_NEG_ZERO, H_NEG_1P0, "-0.0 * -1.0"), - (H_POS_INF, H_2P0, "+inf * 2.0"), - (H_NEG_INF, H_2P0, "-inf * 2.0"), - (H_POS_INF, H_NEG_0P5, "+inf * -0.5"), - (H_MAX, H_2P0, "overflow to +inf"), - (H_NEG_MAX, H_2P0, "overflow to -inf"), - (H_NORM_MIN, 0x1400, "2^-14 * 2^-10 = 2^-24 (min subnormal)"), - (H_NORM_MIN, 0x1000, "2^-14 * 2^-11 = underflow to +0.0"), - ] - - def test_exact_cases_e32_and_e64(self): - for a, b, desc in self.EXACT_CASES: - want = ref_mul_f16(a, b) - for form, op_line in ( - ("e32", "v_mul_f16_e32 v0, v1, v2"), - ("e64", "v_mul_f16_e64 v0, v1, v2"), - ): - with self.subTest(case=desc, form=form): - got = run_ps([f"v_mov_b32 v1, {a:#x}", f"v_mov_b32 v2, {b:#x}"], op_line) - self.assertEqual(got, pack_expected(want)) - - def test_nan_propagation(self): - got = run_ps([f"v_mov_b32 v1, {H_QNAN:#x}", f"v_mov_b32 v2, {H_1P0:#x}"], "v_mul_f16_e32 v0, v1, v2") - self.assertEqual(got >> 16, OLD >> 16) - self.assertTrue(is_f16_nan(got & 0xFFFF)) - - def test_opsel_and_half_preservation(self): - v1 = (H_1P5 << 16) | H_2P0 - v2 = (H_4P0 << 16) | H_0P5 - cases = [ - ("op_sel:[0,0,0]", False, ref_mul_f16(H_2P0, H_0P5)), - ("op_sel:[1,0,0]", False, ref_mul_f16(H_1P5, H_0P5)), - ("op_sel:[0,1,0]", False, ref_mul_f16(H_2P0, H_4P0)), - ("op_sel:[1,1,1]", True, ref_mul_f16(H_1P5, H_4P0)), - ("op_sel:[0,0,1]", True, ref_mul_f16(H_2P0, H_0P5)), - ] - for opsel, dst_hi, want in cases: - with self.subTest(opsel=opsel): - got = run_ps([f"v_mov_b32 v1, {v1:#x}", f"v_mov_b32 v2, {v2:#x}"], - f"v_mul_f16_e64 v0, v1, v2 {opsel}") - self.assertEqual(got, pack_expected(want, OLD, dst_hi=dst_hi)) - - def test_modifiers_and_operand_kinds(self): - # neg, abs, neg-abs, clamp - self.assertEqual( - run_ps([f"v_mov_b32 v1, {H_1P5:#x}", f"v_mov_b32 v2, {H_2P0:#x}"], "v_mul_f16_e64 v0, -v1, v2"), - pack_expected(ref_mul_f16(H_NEG_1P5, H_2P0)), - ) - self.assertEqual( - run_ps([f"v_mov_b32 v1, {H_NEG_1P5:#x}", f"v_mov_b32 v2, {H_2P0:#x}"], "v_mul_f16_e64 v0, |v1|, v2"), - pack_expected(ref_mul_f16(H_1P5, H_2P0)), - ) - self.assertEqual( - run_ps([f"v_mov_b32 v1, {H_NEG_1P5:#x}", f"v_mov_b32 v2, {H_2P0:#x}"], "v_mul_f16_e64 v0, -|v1|, v2"), - pack_expected(ref_mul_f16(H_NEG_1P5, H_2P0)), - ) - self.assertEqual( - run_ps([f"v_mov_b32 v1, {H_2P0:#x}", f"v_mov_b32 v2, {H_2P0:#x}"], "v_mul_f16_e64 v0, v1, v2 clamp"), - pack_expected(H_1P0), - ) - # SGPR, inline float constant, and literal - self.assertEqual( - run_ps([f"s_mov_b32 s4, {H_1P5:#x}", f"v_mov_b32 v2, {H_2P0:#x}"], "v_mul_f16_e32 v0, s4, v2"), - pack_expected(ref_mul_f16(H_1P5, H_2P0)), - ) - self.assertEqual( - run_ps([f"v_mov_b32 v2, {H_4P0:#x}"], "v_mul_f16_e32 v0, 0.5, v2"), - pack_expected(H_2P0), - ) - self.assertEqual( - run_ps([f"v_mov_b32 v2, {H_2P0:#x}"], f"v_mul_f16_e32 v0, {H_1P5:#x}, v2"), - pack_expected(ref_mul_f16(H_1P5, H_2P0)), - ) - - -class UnaryTranscendentalF16Tests(unittest.TestCase): - EXP_CASES = [ - H_NEG_25P0, H_NEG_4P0, H_NEG_2P0, H_NEG_1P0, H_NEG_ZERO, H_POS_ZERO, - H_0P5, H_1P0, H_1P5, H_2P0, H_3P0, H_15P0, H_16P0, H_POS_INF, H_NEG_INF, - ] - LOG_CASES = [ - H_SUB_MIN, H_NORM_MIN, H_0P0625, H_0P25, H_0P3, H_0P5, - H_1P0, H_1P5, H_2P0, H_3P0, H_4P0, H_5P5, H_10P0, H_1024, H_POS_INF, - ] - RSQ_CASES = [ - H_SUB_MIN, H_NORM_MIN, H_0P0625, H_0P25, H_0P3, H_0P5, - H_1P0, H_1P5, H_4P0, H_5P5, H_10P0, H_16P0, H_1024, H_POS_INF, - ] - - def test_exp_log_rsq_values(self): - table = [ - ("v_exp_f16", self.EXP_CASES, ref_exp_f16), - ("v_log_f16", self.LOG_CASES, ref_log_f16), - ("v_rsq_f16", self.RSQ_CASES, ref_rsq_f16), - ] - for op, cases, ref_fn in table: - for a in cases: - want = ref_fn(a) - for suffix in ("_e32", "_e64"): - with self.subTest(op=op + suffix, a=hex(a)): - got = run_ps([f"v_mov_b32 v1, {a:#x}"], f"{op}{suffix} v0, v1") - self.assertEqual(got, pack_expected(want)) - - def test_nan_propagation(self): - for op in ("v_exp_f16", "v_log_f16", "v_rsq_f16"): - with self.subTest(op=op): - got = run_ps([f"v_mov_b32 v1, {H_QNAN:#x}"], f"{op}_e32 v0, v1") - self.assertEqual(got >> 16, OLD >> 16) - self.assertTrue(is_f16_nan(got & 0xFFFF)) - - def test_opsel_and_half_preservation(self): - v1 = (H_4P0 << 16) | H_0P25 - for op, ref_fn in (("v_exp_f16", ref_exp_f16), ("v_log_f16", ref_log_f16), ("v_rsq_f16", ref_rsq_f16)): - for src_hi, dst_hi, src_h in ((0, 0, H_0P25), (1, 0, H_4P0), (0, 1, H_0P25), (1, 1, H_4P0)): - with self.subTest(op=op, src_hi=src_hi, dst_hi=dst_hi): - got = run_ps([f"v_mov_b32 v1, {v1:#x}"], f"{op}_e64 v0, v1 op_sel:[{src_hi},{dst_hi}]") - self.assertEqual(got, pack_expected(ref_fn(src_h), OLD, dst_hi=bool(dst_hi))) - - def test_modifiers_and_operand_kinds(self): - # VOP3 neg/abs/clamp - self.assertEqual( - run_ps([f"v_mov_b32 v1, {H_2P0:#x}"], "v_exp_f16_e64 v0, -v1"), - pack_expected(H_0P25), - ) - self.assertEqual( - run_ps([f"v_mov_b32 v1, {H_NEG_2P0:#x}"], "v_exp_f16_e64 v0, |v1|"), - pack_expected(H_4P0), - ) - self.assertEqual( - run_ps([f"v_mov_b32 v1, {H_2P0:#x}"], "v_exp_f16_e64 v0, v1 clamp"), - pack_expected(H_1P0), - ) - self.assertEqual( - run_ps([f"v_mov_b32 v1, {H_NEG_4P0:#x}"], "v_log_f16_e64 v0, |v1|"), - pack_expected(H_2P0), - ) - self.assertEqual( - run_ps([f"v_mov_b32 v1, {H_0P5:#x}"], "v_log_f16_e64 v0, v1 clamp"), - pack_expected(H_POS_ZERO), - ) - self.assertEqual( - run_ps([f"v_mov_b32 v1, {H_NEG_4P0:#x}"], "v_rsq_f16_e64 v0, |v1|"), - pack_expected(H_0P5), - ) - self.assertEqual( - run_ps([f"v_mov_b32 v1, {H_0P25:#x}"], "v_rsq_f16_e64 v0, v1 clamp"), - pack_expected(H_1P0), - ) - # SGPR, inline constant, and literal operands - self.assertEqual(run_ps([f"s_mov_b32 s4, {H_2P0:#x}"], "v_exp_f16_e32 v0, s4"), pack_expected(H_4P0)) - self.assertEqual(run_ps([], "v_log_f16_e32 v0, 4.0"), pack_expected(H_2P0)) - self.assertEqual(run_ps([], f"v_rsq_f16_e32 v0, {H_0P25:#x}"), pack_expected(H_2P0)) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_valu_f16_round.py b/tests/semantic/test_valu_f16_round.py deleted file mode 100644 index a2cc2fa8e..000000000 --- a/tests/semantic/test_valu_f16_round.py +++ /dev/null @@ -1,995 +0,0 @@ -"""Semantic interpreter tests for RDNA2 16-bit float rounding/fraction VALU ops. - -Covers: - - v_floor_f16: floor(S0.f16) - - v_ceil_f16: ceil(S0.f16) - - v_trunc_f16: trunc(S0.f16) - - v_rndne_f16: roundToEven(S0.f16) - - v_fract_f16: S0.f16 - floor(S0.f16) - -Per docs/design.md ("16-bit results"), all five write one 16-bit half of the destination VGPR while preserving the -other 16-bit half (VOP2 _e32 writes the low half; VOP3 _e64 op_sel:[src,dst] selects source/destination halves). - -All five ops are executed end-to-end through tools/rdna2spirv.py and tests/semantic/spirv_mini_interp.py across -finite values, subnormals, +-0.0, .5 ties, +-inf, NaNs, op_sel:[src,dst], VOP3 source/output modifiers, inline f16 -constants, SGPR sources, destination aliasing, and EXEC masking. - -tools/rdna2spirv.py lowers v_fract_f16 to GLSL.std.450 Fract, which tests/semantic/spirv_mini_interp.py computes -exactly. A Fract result that rounded up to 1.0 is mapped to 0x3bff (the largest f16 below 1.0); ref_fract_f16 below -models that fix-up for the end-to-end cases. -""" -from __future__ import annotations - -import itertools -import math -import os -import re -import struct -import sys -import tempfile -import unittest -import warnings - -HERE = os.path.dirname(os.path.abspath(__file__)) -ROOT = os.path.dirname(os.path.dirname(HERE)) -TOOLS_DIR = os.environ.get("LEONIDA_TOOLS_DIR") or os.path.join(ROOT, "tools") - -sys.dont_write_bytecode = True -sys.path.insert(0, TOOLS_DIR) -sys.path.insert(0, HERE) - -import rdna2spirv # noqa: E402 -import spirv_mini_interp as si # noqa: E402 - -STUB_DXBC = b"DXBC" + bytes(24) + struct.pack(" 1024.0) -H_NEG_1022P5 = 0xE3FD # -1022.5 -H_NEG_1023P5 = 0xE3FF # -1023.5 -H_1024 = 0x6400 # 1024.0 -H_MAX = 0x7BFF # 65504.0 -H_NEG_MAX = 0xFBFF # -65504.0 -H_POS_INF = 0x7C00 # +inf -H_NEG_INF = 0xFC00 # -inf -H_QNAN = 0x7E01 # +qNaN -H_NEG_QNAN = 0xFE01 # -qNaN -H_SNAN = 0x7C01 # +sNaN -H_NEAR_ONE = 0x3BFF # largest f16 below 1.0 (the translator's Fract fix-up result) - - -def h2f(h: int) -> float: - return struct.unpack(" int: - try: - return struct.unpack(" 0 else H_NEG_INF - - -def ref_integral(fn, h: int) -> int: - x = h2f(h) - if not math.isfinite(x): - return h & 0xFFFF - return f2h(math.copysign(float(fn(x)), x)) - - -def ref_floor(h: int) -> int: - return ref_integral(math.floor, h) - - -def ref_ceil(h: int) -> int: - return ref_integral(math.ceil, h) - - -def ref_trunc(h: int) -> int: - return ref_integral(math.trunc, h) - - -def ref_rndne(h: int) -> int: - return ref_integral(round, h) - - -def ref_fract(h: int) -> int: - x = h2f(h) - if not math.isfinite(x): - return H_QNAN - return f2h(x - math.copysign(float(math.floor(x)), x)) - - -def ref_fract_f16(h: int) -> int: - """Oracle for end-to-end v_fract_f16: ref_fract plus the translator's 0x3c00 -> 0x3bff fix-up.""" - r = ref_fract(h) - return H_NEAR_ONE if r == H_1P0 else r - - -def merge_half(old: int, half: int, dst_hi: int) -> int: - h = half & 0xFFFF - return ((h << 16) | (old & 0xFFFF)) if dst_hi else ((old & 0xFFFF0000) | h) - - -def is_f16_nan(half: int) -> bool: - return (half & 0x7FFF) > 0x7C00 - - -def is_f16_inf(half: int) -> bool: - return (half & 0x7FFF) == 0x7C00 - - -def is_f16_subnormal(half: int) -> bool: - return (half & 0x7C00) == 0 and (half & 0x03FF) != 0 - - -def is_f16_zero(half: int) -> bool: - return (half & 0x7FFF) == 0 - - -f16_to_float = h2f -float_to_f16 = f2h - - -def pack_f16x2(lo: int, hi: int) -> int: - return (lo & 0xFFFF) | ((hi & 0xFFFF) << 16) - - -def unpack_f16x2(dword: int) -> tuple[int, int]: - return dword & 0xFFFF, (dword >> 16) & 0xFFFF - - -def ref_pk_floor(dword: int) -> int: - lo, hi = unpack_f16x2(dword) - return pack_f16x2(ref_floor(lo), ref_floor(hi)) - - -def ref_pk_ceil(dword: int) -> int: - lo, hi = unpack_f16x2(dword) - return pack_f16x2(ref_ceil(lo), ref_ceil(hi)) - - -def ref_pk_trunc(dword: int) -> int: - lo, hi = unpack_f16x2(dword) - return pack_f16x2(ref_trunc(lo), ref_trunc(hi)) - - -def ref_pk_rndne(dword: int) -> int: - lo, hi = unpack_f16x2(dword) - return pack_f16x2(ref_rndne(lo), ref_rndne(hi)) - - -class SimdWavefront: - """RDNA2 SIMD Wavefront state holding per-lane VGPRs, SGPRs, and 64-bit EXEC mask.""" - - def __init__(self, wave_size: int = 64, initial_exec: int = 0xFFFFFFFFFFFFFFFF) -> None: - if wave_size not in (32, 64): - raise ValueError(f"Unsupported wave size: {wave_size}") - self.wave_size = wave_size - self.vgpr: list[list[int]] = [[0] * 256 for _ in range(wave_size)] - self.sgpr: list[int] = [0] * 106 - self.mask_all = (1 << wave_size) - 1 - self.exec_mask: int = initial_exec & self.mask_all - - def set_exec(self, mask: int) -> None: - self.exec_mask = mask & self.mask_all - - def is_lane_active(self, lane: int) -> bool: - return bool((self.exec_mask >> lane) & 1) - - def set_vgpr(self, lane: int, reg: int, val: int) -> None: - self.vgpr[lane][reg & 0xFF] = val & 0xFFFFFFFF - - def get_vgpr(self, lane: int, reg: int) -> int: - return self.vgpr[lane][reg & 0xFF] - - def set_sgpr(self, reg: int, val: int) -> None: - if not (0 <= reg < 106): - raise IndexError(f"SGPR index {reg} out of range") - self.sgpr[reg] = val & 0xFFFFFFFF - - def get_sgpr(self, reg: int) -> int: - if not (0 <= reg < 106): - raise IndexError(f"SGPR index {reg} out of range") - return self.sgpr[reg] - - -class F16RoundingInterpreter: - """Deterministic instruction interpreter for RDNA2 VALU f16 rounding and SIMD wavefront ops.""" - - def __init__(self, wave_size: int = 64) -> None: - self.wave = SimdWavefront(wave_size=wave_size) - - def parse_reg(self, token: str) -> tuple[str, int]: - token = token.strip().lower() - if token.startswith("v") and token[1:].isdigit(): - return "vgpr", int(token[1:]) - if token.startswith("s") and token[1:].isdigit(): - return "sgpr", int(token[1:]) - raise ValueError(f"Unrecognized register name: {token}") - - def parse_imm(self, token: str) -> int: - token = token.strip() - if token.startswith("0x") or token.startswith("-0x"): - return int(token, 16) & 0xFFFFFFFF - try: - return int(token) & 0xFFFFFFFF - except ValueError: - f_val = float(token) - return f2h(f_val) - - def read_operand_half(self, token: str, lane: int, hi: int) -> int: - token = token.strip() - is_neg = token.startswith("-") - if is_neg: - token = token[1:].strip() - is_abs = token.startswith("|") and token.endswith("|") - if is_abs: - token = token[1:-1].strip() - - if token.startswith("v") and token[1:].isdigit(): - reg_val = self.wave.get_vgpr(lane, int(token[1:])) - half = (reg_val >> 16) & 0xFFFF if hi else reg_val & 0xFFFF - elif token.startswith("s") and token[1:].isdigit(): - reg_val = self.wave.get_sgpr(int(token[1:])) - half = (reg_val >> 16) & 0xFFFF if hi else reg_val & 0xFFFF - else: - imm = self.parse_imm(token) - half = imm & 0xFFFF - - if is_abs: - half &= 0x7FFF - if is_neg: - half ^= 0x8000 - return half - - def execute_line(self, line: str) -> None: - line = line.split(";")[0].strip() - if not line: - return - parts = line.split(None, 1) - mnemonic = parts[0].lower() - rest = parts[1] if len(parts) > 1 else "" - - if mnemonic == "s_mov_b32": - dst, src = [t.strip() for t in rest.split(",")] - dst_type, dst_idx = self.parse_reg(dst) - if dst_type == "sgpr": - val = self.wave.get_sgpr(int(src[1:])) if (src.startswith("s") and src[1:].isdigit()) else self.parse_imm(src) - self.wave.set_sgpr(dst_idx, val) - return - - if mnemonic in ("s_mov_b64", "s_mov_b32_exec"): - dst, src = [t.strip() for t in rest.split(",")] - if dst.lower() in ("exec", "exec_lo"): - val = int(src, 16) if (src.startswith("0x") or src.startswith("-0x")) else int(src) - self.wave.set_exec(val) - return - - if mnemonic == "v_mov_b32": - dst, src = [t.strip() for t in rest.split(",")] - dst_type, dst_idx = self.parse_reg(dst) - for lane in range(self.wave.wave_size): - if not self.wave.is_lane_active(lane): - continue - if src.startswith("v") and src[1:].isdigit(): - val = self.wave.get_vgpr(lane, int(src[1:])) - elif src.startswith("s") and src[1:].isdigit(): - val = self.wave.get_sgpr(int(src[1:])) - else: - val = self.parse_imm(src) - self.wave.set_vgpr(lane, dst_idx, val) - return - - base_op = mnemonic.replace("_e32", "").replace("_e64", "") - if base_op in OPS: - _, ref_fn = OPS[base_op] - m_opsel = re.search(r"op_sel:\[(\d+),(\d+)\]", rest, re.IGNORECASE) - src_hi = int(m_opsel.group(1)) if m_opsel else 0 - dst_hi = int(m_opsel.group(2)) if m_opsel else 0 - has_clamp = bool(re.search(r"\bclamp\b", rest, re.IGNORECASE)) - has_mul2 = bool(re.search(r"\bmul:2\b", rest, re.IGNORECASE)) - has_mul4 = bool(re.search(r"\bmul:4\b", rest, re.IGNORECASE)) - has_div2 = bool(re.search(r"\bdiv:2\b", rest, re.IGNORECASE)) - - clean = re.sub(r"(?:op_sel:\[\d+,\d+\]|clamp|mul:2|mul:4|div:2)", "", rest, flags=re.IGNORECASE) - operands = [t.strip() for t in clean.split(",") if t.strip()] - dst_tok, src_tok = operands[0], operands[1] - dst_type, dst_idx = self.parse_reg(dst_tok) - - for lane in range(self.wave.wave_size): - if not self.wave.is_lane_active(lane): - continue - src_half = self.read_operand_half(src_tok, lane, src_hi) - res_half = ref_fn(src_half) - if has_mul2 or has_mul4 or has_div2 or has_clamp: - val = h2f(res_half) - if has_mul2: - val *= 2.0 - elif has_mul4: - val *= 4.0 - elif has_div2: - val *= 0.5 - if has_clamp: - val = max(0.0, min(1.0, val)) if not math.isnan(val) else 0.0 - res_half = f2h(val) - - old_val = self.wave.get_vgpr(lane, dst_idx) - new_val = merge_half(old_val, res_half, dst_hi) - self.wave.set_vgpr(lane, dst_idx, new_val) - return - - raise ValueError(f"Unsupported mnemonic: {mnemonic}") - - def execute_program(self, lines: list[str]) -> None: - for line in lines: - self.execute_line(line) - - -OPS = { - "v_floor_f16": ("Floor", ref_floor), - "v_ceil_f16": ("Ceil", ref_ceil), - "v_trunc_f16": ("Trunc", ref_trunc), - "v_rndne_f16": ("RoundEven", ref_rndne), -} - -_TMP_DIR = None -_PS_PATH = None - - -def setUpModule(): - global _TMP_DIR, _PS_PATH - _TMP_DIR = tempfile.TemporaryDirectory() - disasm_dir = os.path.join(_TMP_DIR.name, "disasm") - os.mkdir(disasm_dir) - _PS_PATH = os.path.join(disasm_dir, "ps_f16_round.s") - with open(os.path.join(_TMP_DIR.name, "ps_f16_round.dxbc"), "wb") as f: - f.write(STUB_DXBC) - - -def tearDownModule(): - global _TMP_DIR - if _TMP_DIR is not None: - _TMP_DIR.cleanup() - _TMP_DIR = None - - -def translate_ps(lines: list[str]) -> str: - if _TMP_DIR is None: - setUpModule() - asm = "; test_valu_f16_round\n" + "".join(f"\t{ln}\n" for ln in lines) + "\texp mrt0 v0, v0, v0, v0 done vm\n\ts_endpgm\n" - with open(_PS_PATH, "w", encoding="utf-8") as f: - f.write(asm) - with warnings.catch_warnings(): - warnings.simplefilter("ignore", ResourceWarning) - return rdna2spirv.translate(_PS_PATH) - - -def run_ps(lines: list[str]) -> int: - return si.run_fragment(translate_ps(lines))["%out_mrt0"][0] - - -def run_op(line: str, v1: int, old: int = OLD, s4: int = 0) -> int: - lines = [f"s_mov_b32 s4, {s4:#x}", f"v_mov_b32 v1, {v1:#x}", f"v_mov_b32 v0, {old:#x}", line] - return run_ps(lines) - - -class ReferenceOracleTests(unittest.TestCase): - def test_integral_and_fract_edge_values(self): - self.assertEqual(ref_floor(H_NEG_0P25), H_NEG_1P0) - self.assertEqual(ref_floor(H_NEG_ZERO), H_NEG_ZERO) - self.assertEqual(ref_ceil(H_NEG_0P25), H_NEG_ZERO) - self.assertEqual(ref_ceil(H_0P25), H_1P0) - self.assertEqual(ref_trunc(H_NEG_0P75), H_NEG_ZERO) - self.assertEqual(ref_trunc(H_1P75), H_1P0) - self.assertEqual(ref_rndne(H_0P5), H_POS_ZERO) - self.assertEqual(ref_rndne(H_NEG_0P5), H_NEG_ZERO) - self.assertEqual(ref_rndne(H_1P5), H_2P0) - self.assertEqual(ref_rndne(H_2P5), H_2P0) - self.assertEqual(ref_rndne(H_1022P5), f2h(1022.0)) - self.assertEqual(ref_rndne(H_1023P5), H_1024) - self.assertEqual(ref_fract(H_1P25), H_0P25) - self.assertEqual(ref_fract(H_NEG_0P25), H_0P75) - self.assertEqual(ref_fract(H_NEG_1P75), H_0P25) - self.assertEqual(ref_fract(H_NEG_ZERO), H_POS_ZERO) - self.assertTrue(is_f16_nan(ref_fract(H_POS_INF))) - self.assertEqual(merge_half(OLD, H_1P0, 0), 0xBEEF3C00) - self.assertEqual(merge_half(OLD, H_1P0, 1), 0x3C001234) - - def test_exact_integers_identity(self): - """Exact integer representations in binary16 are unchanged by all 4 rounding modes.""" - for i in range(-100, 101): - h = f2h(float(i)) - self.assertEqual(ref_floor(h), h, f"floor({i}) failed") - self.assertEqual(ref_ceil(h), h, f"ceil({i}) failed") - self.assertEqual(ref_trunc(h), h, f"trunc({i}) failed") - self.assertEqual(ref_rndne(h), h, f"rndne({i}) failed") - - def test_exponent_ge_10_no_fractional_bits(self): - """Values with magnitude >= 2^10 = 1024 have no fractional bits in binary16 mantissa. - - In IEEE 754 binary16 (5 exponent bits, 10 mantissa bits), when unbiased exponent >= 10, - the unit in the last place (ulp) is >= 1.0. Therefore, all representable binary16 numbers - with |x| >= 1024 are already exact integers and rounding is guaranteed to be an identity. - """ - large_magnitudes = [ - 1024.0, 1025.0, 1026.0, 1200.0, 1536.0, 2048.0, 4096.0, - 8192.0, 16384.0, 32768.0, 65504.0, - ] - for val in large_magnitudes: - for sign in (1.0, -1.0): - x = sign * val - h = f2h(x) - self.assertEqual(ref_floor(h), h, f"floor({x}) failed") - self.assertEqual(ref_ceil(h), h, f"ceil({x}) failed") - self.assertEqual(ref_trunc(h), h, f"trunc({x}) failed") - self.assertEqual(ref_rndne(h), h, f"rndne({x}) failed") - - def test_signed_zeros_round_to_integral_rules(self): - """IEEE 754-2008 / 2019 roundToIntegral rules for negative fractional numbers and signed zeros. - - Strict rules: - - floor(-0.5) = -1.0, floor(-0.0) = -0.0, floor(+0.0) = +0.0 - - ceil(-0.5) = -0.0, ceil(-0.0) = -0.0, ceil(+0.0) = +0.0 - - trunc(-0.5) = -0.0, trunc(-0.0) = -0.0, trunc(+0.0) = +0.0 - - rndne(-0.4) = -0.0, rndne(-0.5) = -0.0 - """ - self.assertEqual(ref_floor(H_NEG_0P5), H_NEG_1P0) - self.assertEqual(ref_ceil(H_NEG_0P5), H_NEG_ZERO) - self.assertEqual(ref_trunc(H_NEG_0P5), H_NEG_ZERO) - self.assertEqual(ref_rndne(f2h(-0.4)), H_NEG_ZERO) - self.assertEqual(ref_rndne(H_NEG_0P5), H_NEG_ZERO) - - # Signed zero inputs produce identical signed zero outputs - for h_zero in (H_POS_ZERO, H_NEG_ZERO): - self.assertEqual(ref_floor(h_zero), h_zero) - self.assertEqual(ref_ceil(h_zero), h_zero) - self.assertEqual(ref_trunc(h_zero), h_zero) - self.assertEqual(ref_rndne(h_zero), h_zero) - - def test_tie_breaking_to_even_halfway(self): - """Halfway cases (n + 0.5) must tie-break to the nearest even integer.""" - cases = [ - (H_0P5, H_POS_ZERO), # 0.5 -> 0.0 (0 is even) - (H_1P5, H_2P0), # 1.5 -> 2.0 (2 is even) - (H_2P5, H_2P0), # 2.5 -> 2.0 (2 is even) - (H_3P5, H_4P0), # 3.5 -> 4.0 (4 is even) - (f2h(4.5), H_4P0), # 4.5 -> 4.0 - (f2h(5.5), f2h(6.0)), # 5.5 -> 6.0 - (H_NEG_0P5, H_NEG_ZERO), # -0.5 -> -0.0 (-0 is even) - (H_NEG_1P5, H_NEG_2P0), # -1.5 -> -2.0 - (H_NEG_2P5, H_NEG_2P0), # -2.5 -> -2.0 - (H_NEG_3P5, H_NEG_4P0), # -3.5 -> -4.0 - (f2h(-4.5), H_NEG_4P0), # -4.5 -> -4.0 - (f2h(-5.5), f2h(-6.0)), # -5.5 -> -6.0 - (H_1022P5, f2h(1022.0)), # 1022.5 -> 1022.0 (even) - (H_1023P5, H_1024), # 1023.5 -> 1024.0 (odd -> even) - (H_NEG_1022P5, f2h(-1022.0)), - (H_NEG_1023P5, f2h(-1024.0)), - ] - for inp, expected in cases: - with self.subTest(inp=hex(inp), expected=hex(expected)): - self.assertEqual(ref_rndne(inp), expected) - - def test_subnormals_and_special_values(self): - """Subnormals (< 2^-14) and infinities/NaNs handling in reference oracle.""" - for sub in (H_SUB_MIN, H_SUB_MAX): - self.assertEqual(ref_floor(sub), H_POS_ZERO) - self.assertEqual(ref_ceil(sub), H_1P0) - self.assertEqual(ref_trunc(sub), H_POS_ZERO) - self.assertEqual(ref_rndne(sub), H_POS_ZERO) - - for neg_sub in (H_NEG_SUB_MIN, H_NEG_SUB_MAX): - self.assertEqual(ref_floor(neg_sub), H_NEG_1P0) - self.assertEqual(ref_ceil(neg_sub), H_NEG_ZERO) - self.assertEqual(ref_trunc(neg_sub), H_NEG_ZERO) - self.assertEqual(ref_rndne(neg_sub), H_NEG_ZERO) - - for inf in (H_POS_INF, H_NEG_INF): - self.assertEqual(ref_floor(inf), inf) - self.assertEqual(ref_ceil(inf), inf) - self.assertEqual(ref_trunc(inf), inf) - self.assertEqual(ref_rndne(inf), inf) - - for nan in (H_QNAN, H_NEG_QNAN, H_SNAN): - self.assertTrue(is_f16_nan(ref_floor(nan))) - self.assertTrue(is_f16_nan(ref_ceil(nan))) - self.assertTrue(is_f16_nan(ref_trunc(nan))) - self.assertTrue(is_f16_nan(ref_rndne(nan))) - - -class F16RoundingExecutionTests(unittest.TestCase): - def test_edge_values_across_e32_e64_and_bare(self): - samples = [ - H_POS_ZERO, H_NEG_ZERO, - H_SUB_MIN, H_NEG_SUB_MIN, H_SUB_MAX, H_NEG_SUB_MAX, - H_0P25, H_NEG_0P25, H_0P5, H_NEG_0P5, H_0P75, H_NEG_0P75, - H_1P0, H_NEG_1P0, H_1P25, H_NEG_1P25, H_1P5, H_NEG_1P5, H_1P75, H_NEG_1P75, - H_2P0, H_NEG_2P0, H_2P5, H_NEG_2P5, H_3P0, H_NEG_3P0, H_3P5, H_NEG_3P5, - H_1022P5, H_1023P5, H_NEG_1022P5, H_NEG_1023P5, - H_MAX, H_NEG_MAX, H_POS_INF, H_NEG_INF, - ] - for op, (_, ref) in OPS.items(): - for suffix in ("_e32", "_e64", ""): - for h in samples: - v1 = 0x55550000 | h - with self.subTest(op=op + suffix, h=hex(h)): - got = run_op(f"{op}{suffix} v0, v1", v1) - self.assertEqual(got, merge_half(OLD, ref(h), 0)) - - def test_signed_zero_and_subnormal_signs_preserved(self): - # IEEE-754 roundToIntegral keeps -0.0 when rounding values in (-1.0, -0.0] to zero. - self.assertEqual(run_op("v_floor_f16_e32 v0, v1", 0xABCD0000 | H_NEG_ZERO), merge_half(OLD, H_NEG_ZERO, 0)) - self.assertEqual(run_op("v_floor_f16_e32 v0, v1", 0xABCD0000 | H_POS_ZERO), merge_half(OLD, H_POS_ZERO, 0)) - self.assertEqual(run_op("v_floor_f16_e32 v0, v1", 0xABCD0000 | H_SUB_MIN), merge_half(OLD, H_POS_ZERO, 0)) - self.assertEqual(run_op("v_floor_f16_e32 v0, v1", 0xABCD0000 | H_NEG_SUB_MIN), merge_half(OLD, H_NEG_1P0, 0)) - for op in ("v_ceil_f16", "v_trunc_f16", "v_rndne_f16"): - for h in (H_NEG_ZERO, H_NEG_SUB_MIN, H_NEG_SUB_MAX, H_NEG_0P25): - with self.subTest(op=op, h=hex(h)): - self.assertEqual(run_op(f"{op}_e32 v0, v1", 0xABCD0000 | h), merge_half(OLD, H_NEG_ZERO, 0)) - - def test_nan_preserves_nan_and_other_half(self): - for op in OPS: - for h in (H_QNAN, H_NEG_QNAN, H_SNAN): - with self.subTest(op=op, h=hex(h)): - got = run_op(f"{op}_e32 v0, v1", 0xCAFE0000 | h) - self.assertEqual(got & 0xFFFF0000, OLD & 0xFFFF0000) - self.assertTrue(is_f16_nan(got & 0xFFFF), f"expected NaN in low half, got {got:#x}") - - def test_op_sel_all_combinations(self): - # v1 = (hi: -2.5, lo: 3.5) -> clear, distinct results across every op and half. - v1 = (H_NEG_2P5 << 16) | H_3P5 - for op, (_, ref) in OPS.items(): - for src_hi, dst_hi in itertools.product((0, 1), repeat=2): - h_in = H_NEG_2P5 if src_hi else H_3P5 - line = f"{op}_e64 v0, v1 op_sel:[{src_hi},{dst_hi}]" - with self.subTest(line=line): - self.assertEqual(run_op(line, v1), merge_half(OLD, ref(h_in), dst_hi)) - - def test_vop3_source_and_output_modifiers(self): - v1 = (H_NEG_1P5 << 16) | H_2P5 - # Source modifiers apply to the selected half before the rounding op. - self.assertEqual(run_op("v_floor_f16_e64 v0, -v1 op_sel:[0,0]", v1), merge_half(OLD, f2h(-3.0), 0)) - self.assertEqual(run_op("v_ceil_f16_e64 v0, |v1| op_sel:[1,1]", v1), merge_half(OLD, H_2P0, 1)) - self.assertEqual(run_op("v_rndne_f16_e64 v0, -|v1| op_sel:[1,0]", v1), merge_half(OLD, H_NEG_2P0, 0)) - - # Output modifiers: on RDNA2 with denorms kept, omod is ignored on f16; clamp applies to [0.0, 1.0]. - # trunc(2.5) = 2.0; mul:2/mul:4/div:2 ignored; clamp -> 1.0. - self.assertEqual(run_op("v_trunc_f16_e64 v0, v1 mul:2", v1), merge_half(OLD, H_2P0, 0)) - self.assertEqual(run_op("v_trunc_f16_e64 v0, v1 mul:4", v1), merge_half(OLD, H_2P0, 0)) - self.assertEqual(run_op("v_trunc_f16_e64 v0, v1 div:2", v1), merge_half(OLD, H_2P0, 0)) - self.assertEqual(run_op("v_trunc_f16_e64 v0, v1 mul:2 clamp", v1), merge_half(OLD, H_1P0, 0)) - # floor(-1.5) = -2.0 -> clamp -> 0.0 (preserving low half when dst_hi=1). - self.assertEqual(run_op("v_floor_f16_e64 v0, v1 op_sel:[1,1] clamp", v1), merge_half(OLD, H_POS_ZERO, 1)) - # rndne(0.5) = 0.0 -> div:2 = 0.0; trunc(1.25) = 1.0 (div:2 ignored). - self.assertEqual(run_op("v_trunc_f16_e64 v0, v1 div:2", H_1P25), merge_half(OLD, H_1P0, 0)) - - def test_inline_constants_sgpr_and_aliasing(self): - # Inline float constants populate the low half as f16 (docs/design.md). - self.assertEqual(run_op("v_ceil_f16_e32 v0, 0.5", 0), merge_half(OLD, H_1P0, 0)) - self.assertEqual(run_op("v_floor_f16_e32 v0, -0.5", 0), merge_half(OLD, H_NEG_1P0, 0)) - self.assertEqual(run_op("v_rndne_f16_e64 v0, -1.0", 0), merge_half(OLD, H_NEG_1P0, 0)) - - # SGPR source (reading high half via op_sel). - s4 = (H_NEG_1P25 << 16) | H_0P75 - self.assertEqual(run_op("v_floor_f16_e32 v0, s4", 0, s4=s4), merge_half(OLD, H_POS_ZERO, 0)) - self.assertEqual(run_op("v_floor_f16_e64 v0, s4 op_sel:[1,1]", 0, s4=s4), merge_half(OLD, H_NEG_2P0, 1)) - - # In-place aliasing: dst == src reading high half and writing low half keeps the original high half. - v0_init = (H_3P5 << 16) | H_0P25 - self.assertEqual(run_ps([f"v_mov_b32 v0, {v0_init:#x}", "v_rndne_f16_e64 v0, v0 op_sel:[1,0]"]), - (H_3P5 << 16) | H_4P0) - self.assertEqual(run_ps([f"v_mov_b32 v0, {v0_init:#x}", "v_trunc_f16_e32 v0, v0"]), - (H_3P5 << 16) | H_POS_ZERO) - - def test_exec_masking(self): - # Inactive single lane preserves pre-existing v0. - got = run_ps([ - f"v_mov_b32 v1, {H_1P5:#x}", - f"v_mov_b32 v0, {OLD:#x}", - "s_mov_b32 exec_lo, 0", - "v_ceil_f16_e32 v0, v1", - "s_mov_b32 exec_lo, 1", - ]) - self.assertEqual(got, OLD) - - # Disabled ops leave both halves untouched; re-enabling EXEC runs the subsequent op. - got_toggled = run_ps([ - f"v_mov_b32 v1, {(H_2P5 << 16) | H_NEG_1P25:#x}", - f"v_mov_b32 v0, {OLD:#x}", - "s_mov_b32 exec_lo, 0", - "v_floor_f16_e64 v0, v1 op_sel:[0,0]", - "v_ceil_f16_e64 v0, v1 op_sel:[1,1]", - "s_mov_b32 exec_lo, 1", - "v_trunc_f16_e64 v0, v1 op_sel:[1,0]", - ]) - self.assertEqual(got_toggled, merge_half(OLD, H_2P0, 0)) - - def test_negative_control_sabotaged_spirv(self): - spv = translate_ps([f"v_mov_b32 v1, {H_2P5:#x}", f"v_mov_b32 v0, {OLD:#x}", "v_floor_f16_e32 v0, v1"]) - sabotaged, n = re.subn(r"\bFloor\b", "Ceil", spv, count=1) - self.assertEqual(n, 1) - got = si.run_fragment(sabotaged)["%out_mrt0"][0] - self.assertNotEqual(got, merge_half(OLD, H_2P0, 0)) - self.assertEqual(got, merge_half(OLD, H_3P0, 0)) - - -class PackedF16SimdTests(unittest.TestCase): - """Packed half-precision floating-point rounding and multi-lane SIMD tests. - - Models: - - Packed pairs: v_pk_floor_f16 and v_pk_ceil_f16 behavior processing two 16-bit - halfwords packed into a 32-bit dword. - - SIMD Wavefront execution across 32 and 64 lanes. - - Inactive lane preservation under EXEC execution masks. - - End-to-end RDNA2 packed SIMD emulation via op_sel:[0,0] and op_sel:[1,1]. - - Negative rejection test for unsupported packed pseudo-opcodes in translator. - """ - - def test_packed_floor_and_ceil_reference_oracle(self): - """Packed half-precision oracle validates low and high halves independently.""" - pairs = [ - (H_1P5, H_2P5), - (H_NEG_0P5, H_0P5), - (H_SUB_MIN, H_NEG_SUB_MIN), - (H_1022P5, H_1023P5), - (H_POS_ZERO, H_NEG_ZERO), - (H_POS_INF, H_NEG_INF), - (H_0P25, H_NEG_0P75), - ] - for lo, hi in pairs: - dword = pack_f16x2(lo, hi) - with self.subTest(lo=hex(lo), hi=hex(hi)): - exp_floor = pack_f16x2(ref_floor(lo), ref_floor(hi)) - exp_ceil = pack_f16x2(ref_ceil(lo), ref_ceil(hi)) - exp_trunc = pack_f16x2(ref_trunc(lo), ref_trunc(hi)) - exp_rndne = pack_f16x2(ref_rndne(lo), ref_rndne(hi)) - self.assertEqual(ref_pk_floor(dword), exp_floor) - self.assertEqual(ref_pk_ceil(dword), exp_ceil) - self.assertEqual(ref_pk_trunc(dword), exp_trunc) - self.assertEqual(ref_pk_rndne(dword), exp_rndne) - - def test_simd_wavefront_uniform_packed_execution(self): - """Simulate packed floor and ceil across all 64 lanes of a SIMD wavefront.""" - interp = F16RoundingInterpreter(wave_size=64) - v1 = pack_f16x2(H_1P5, H_NEG_2P5) - # Low half floor(1.5)=1.0, high half floor(-2.5)=-3.0 - interp.execute_program([ - f"v_mov_b32 v1, {v1:#x}", - f"v_mov_b32 v0, {OLD:#x}", - "v_floor_f16_e64 v0, v1 op_sel:[0,0]", - "v_floor_f16_e64 v0, v1 op_sel:[1,1]", - ]) - expected_floor = ref_pk_floor(v1) - for lane in range(64): - self.assertEqual(interp.wave.get_vgpr(lane, 0), expected_floor, f"Lane {lane} floor mismatch") - - # Ceil sequence: ceil(1.5)=2.0, ceil(-2.5)=-2.0 - interp.execute_program([ - f"v_mov_b32 v1, {v1:#x}", - f"v_mov_b32 v0, {OLD:#x}", - "v_ceil_f16_e64 v0, v1 op_sel:[0,0]", - "v_ceil_f16_e64 v0, v1 op_sel:[1,1]", - ]) - expected_ceil = ref_pk_ceil(v1) - for lane in range(64): - self.assertEqual(interp.wave.get_vgpr(lane, 0), expected_ceil, f"Lane {lane} ceil mismatch") - - def test_simd_wavefront_divergent_lanes(self): - """Each lane in a 64-lane wave processes distinct packed half-precision pairs.""" - interp = F16RoundingInterpreter(wave_size=64) - per_lane_inputs = [] - for lane in range(64): - lo_val = float(lane % 8) + 0.5 - hi_val = -(float(lane // 8) + 0.5) - h_lo = f2h(lo_val) - h_hi = f2h(hi_val) - dword = pack_f16x2(h_lo, h_hi) - per_lane_inputs.append(dword) - interp.wave.set_vgpr(lane, 1, dword) - interp.wave.set_vgpr(lane, 0, OLD) - - interp.execute_program([ - "v_floor_f16_e64 v0, v1 op_sel:[0,0]", - "v_floor_f16_e64 v0, v1 op_sel:[1,1]", - ]) - for lane in range(64): - expected = ref_pk_floor(per_lane_inputs[lane]) - self.assertEqual(interp.wave.get_vgpr(lane, 0), expected, f"Divergent lane {lane} floor mismatch") - - def test_simd_wavefront_exec_mask_inactive_lanes_preserved(self): - """Inactive lanes under EXEC mask must strictly retain their previous values.""" - interp = F16RoundingInterpreter(wave_size=64) - v1 = pack_f16x2(H_1P5, H_NEG_1P5) - # Enable only lower 32 lanes (exec = 0x00000000FFFFFFFF) - for lane in range(64): - interp.wave.set_vgpr(lane, 0, OLD) - interp.wave.set_vgpr(lane, 1, v1) - - interp.execute_program([ - "s_mov_b64 exec, 0x00000000FFFFFFFF", - "v_floor_f16_e64 v0, v1 op_sel:[0,0]", - "v_floor_f16_e64 v0, v1 op_sel:[1,1]", - ]) - - expected_floor = ref_pk_floor(v1) - for lane in range(32): - self.assertEqual(interp.wave.get_vgpr(lane, 0), expected_floor, f"Active lane {lane} failed") - for lane in range(32, 64): - self.assertEqual(interp.wave.get_vgpr(lane, 0), OLD, f"Inactive lane {lane} was modified") - - def test_end_to_end_rdna2_simd_packed_sequence(self): - """End-to-end translation and execution of RDNA2 packed f16 floor/ceil sequences.""" - samples = [ - pack_f16x2(H_1P5, H_2P5), - pack_f16x2(H_NEG_0P5, H_0P75), - pack_f16x2(H_1022P5, H_1023P5), - pack_f16x2(H_SUB_MIN, H_NEG_SUB_MIN), - ] - for dword in samples: - with self.subTest(dword=hex(dword)): - got_floor = run_ps([ - f"v_mov_b32 v1, {dword:#x}", - f"v_mov_b32 v0, {OLD:#x}", - "v_floor_f16_e64 v0, v1 op_sel:[0,0]", - "v_floor_f16_e64 v0, v1 op_sel:[1,1]", - ]) - self.assertEqual(got_floor, ref_pk_floor(dword)) - - got_ceil = run_ps([ - f"v_mov_b32 v1, {dword:#x}", - f"v_mov_b32 v0, {OLD:#x}", - "v_ceil_f16_e64 v0, v1 op_sel:[0,0]", - "v_ceil_f16_e64 v0, v1 op_sel:[1,1]", - ]) - self.assertEqual(got_ceil, ref_pk_ceil(dword)) - - def test_unsupported_packed_pseudo_opcodes_rejected(self): - """In RDNA2 ISA, packed rounding is achieved via scalar half ops; packed mnemonics are unsupported.""" - with self.assertRaises(rdna2spirv.Unsupported): - translate_ps(["v_pk_floor_f16 v0, v1"]) - with self.assertRaises(rdna2spirv.Unsupported): - translate_ps(["v_pk_ceil_f16 v0, v1"]) - - -class FractF16TranslationTests(unittest.TestCase): - """v_fract_f16 lowers to GLSL.std.450 Fract (spirv_mini_interp.py computes it exactly, rounded once).""" - - def test_fract_f16_emits_glsl_fract_op_sel_mods_and_half_keep(self): - spv = translate_ps([ - f"v_mov_b32 v1, {(H_NEG_1P25 << 16) | H_2P5:#x}", - f"v_mov_b32 v0, {OLD:#x}", - "v_fract_f16_e64 v0, v1 op_sel:[1,1] clamp", - ]) - self.assertIn("UnpackHalf2x16", spv) - self.assertRegex(spv, r"OpExtInst %float %glsl Fract %\w+") - self.assertRegex(spv, r"OpExtInst %float %glsl FClamp %\w+ %f0 %f1") - # op_sel:[1,1]: fract of the high half (-1.25 -> 0.75 = 0x3a00) into the high half; the low half is kept. - self.assertEqual(si.run_fragment(spv)["%out_mrt0"][0], (0x3A00 << 16) | (OLD & 0xFFFF)) - - def test_edge_values_across_e32_e64_and_bare(self): - samples = [ - H_POS_ZERO, H_NEG_ZERO, - H_SUB_MIN, H_NEG_SUB_MIN, H_SUB_MAX, H_NEG_SUB_MAX, - H_0P25, H_NEG_0P25, H_0P5, H_NEG_0P5, H_0P75, H_NEG_0P75, - H_1P0, H_NEG_1P0, H_1P25, H_NEG_1P25, H_1P5, H_NEG_1P5, H_1P75, H_NEG_1P75, - H_2P0, H_NEG_2P0, H_2P5, H_NEG_2P5, H_3P5, H_NEG_3P5, - H_1022P5, H_1023P5, H_NEG_1022P5, H_NEG_1023P5, - H_MAX, H_NEG_MAX, - ] - for suffix in ("_e32", "_e64", ""): - for h in samples: - v1 = 0x55550000 | h - with self.subTest(op="v_fract_f16" + suffix, h=hex(h)): - got = run_op(f"v_fract_f16{suffix} v0, v1", v1) - self.assertEqual(got, merge_half(OLD, ref_fract_f16(h), 0)) - - def test_inf_and_nan_give_nan_and_keep_other_half(self): - for h in (H_POS_INF, H_NEG_INF, H_QNAN, H_NEG_QNAN, H_SNAN): - for suffix in ("_e32", "_e64"): - with self.subTest(h=hex(h), suffix=suffix): - got = run_op(f"v_fract_f16{suffix} v0, v1", 0xCAFE0000 | h) - self.assertEqual(got & 0xFFFF0000, OLD & 0xFFFF0000) - self.assertTrue(is_f16_nan(got & 0xFFFF), f"expected NaN in low half, got {got:#x}") - - def test_op_sel_all_combinations(self): - # v1 = (hi: -1.25, lo: 2.5) -> distinct fractions 0.75 and 0.5 across every src/dst half. - v1 = (H_NEG_1P25 << 16) | H_2P5 - for src_hi, dst_hi in itertools.product((0, 1), repeat=2): - h_in = H_NEG_1P25 if src_hi else H_2P5 - line = f"v_fract_f16_e64 v0, v1 op_sel:[{src_hi},{dst_hi}]" - with self.subTest(line=line): - self.assertEqual(run_op(line, v1), merge_half(OLD, ref_fract_f16(h_in), dst_hi)) - - def test_vop3_source_and_output_modifiers(self): - v1 = (H_NEG_1P25 << 16) | H_2P5 - # Source modifiers apply to the selected half before Fract. - self.assertEqual(run_op("v_fract_f16_e64 v0, -v1 op_sel:[0,0]", v1), merge_half(OLD, H_0P5, 0)) - self.assertEqual(run_op("v_fract_f16_e64 v0, |v1| op_sel:[1,1]", v1), merge_half(OLD, H_0P25, 1)) - self.assertEqual(run_op("v_fract_f16_e64 v0, -|v1| op_sel:[1,0]", v1), merge_half(OLD, H_0P75, 0)) - - # On RDNA2 with denorms kept, omod is ignored on f16 results; clamp applies. - self.assertEqual(run_op("v_fract_f16_e64 v0, v1 mul:2", v1), merge_half(OLD, H_0P5, 0)) - self.assertEqual(run_op("v_fract_f16_e64 v0, v1 mul:4", v1), merge_half(OLD, H_0P5, 0)) - self.assertEqual(run_op("v_fract_f16_e64 v0, v1 div:2", v1), merge_half(OLD, H_0P5, 0)) - self.assertEqual(run_op("v_fract_f16_e64 v0, v1 mul:2 clamp", v1), merge_half(OLD, H_0P5, 0)) - self.assertEqual(run_op("v_fract_f16_e64 v0, v1 op_sel:[1,1] clamp", v1), merge_half(OLD, H_0P75, 1)) - - def test_inline_constants_sgpr_and_aliasing(self): - self.assertEqual(run_op("v_fract_f16_e32 v0, 0.5", 0), merge_half(OLD, H_0P5, 0)) - self.assertEqual(run_op("v_fract_f16_e32 v0, -0.5", 0), merge_half(OLD, H_0P5, 0)) - self.assertEqual(run_op("v_fract_f16_e64 v0, -1.0", 0), merge_half(OLD, H_POS_ZERO, 0)) - - s4 = (H_NEG_1P25 << 16) | H_0P25 - self.assertEqual(run_op("v_fract_f16_e32 v0, s4", 0, s4=s4), merge_half(OLD, H_0P25, 0)) - self.assertEqual(run_op("v_fract_f16_e64 v0, s4 op_sel:[1,1]", 0, s4=s4), merge_half(OLD, H_0P75, 1)) - - # In-place aliasing: dst == src reading the high half keeps the original high half. - v0_init = (H_3P5 << 16) | H_0P25 - self.assertEqual(run_ps([f"v_mov_b32 v0, {v0_init:#x}", "v_fract_f16_e64 v0, v0 op_sel:[1,0]"]), - (H_3P5 << 16) | H_0P5) - - def test_exec_masking(self): - # Inactive single lane preserves pre-existing v0. - got = run_ps([ - f"v_mov_b32 v1, {H_1P5:#x}", - f"v_mov_b32 v0, {OLD:#x}", - "s_mov_b32 exec_lo, 0", - "v_fract_f16_e32 v0, v1", - "s_mov_b32 exec_lo, 1", - ]) - self.assertEqual(got, OLD) - - # Disabled ops leave both halves untouched; re-enabling EXEC runs the subsequent op. - got_toggled = run_ps([ - f"v_mov_b32 v1, {(H_NEG_1P25 << 16) | H_2P5:#x}", - f"v_mov_b32 v0, {OLD:#x}", - "s_mov_b32 exec_lo, 0", - "v_fract_f16_e64 v0, v1 op_sel:[0,0]", - "v_fract_f16_e64 v0, v1 op_sel:[1,1]", - "s_mov_b32 exec_lo, 1", - "v_fract_f16_e64 v0, v1 op_sel:[1,0]", - ]) - self.assertEqual(got_toggled, merge_half(OLD, H_0P75, 0)) - - -class TieBreakingSignedZerosAndNegativeControlTests(unittest.TestCase): - """End-to-end and negative control tests for tie-breaking to even, signed zeros, and mutants.""" - - def test_e2e_rndne_halfway_tie_breaking_even_matrix(self): - """End-to-end v_rndne_f16 execution strictly enforces round-to-nearest-even on halfway ties.""" - ties = [ - (H_0P5, H_POS_ZERO), # 0.5 -> 0.0 (0 is even) - (H_1P5, H_2P0), # 1.5 -> 2.0 (2 is even) - (H_2P5, H_2P0), # 2.5 -> 2.0 (2 is even) - (H_3P5, H_4P0), # 3.5 -> 4.0 (4 is even) - (f2h(4.5), H_4P0), # 4.5 -> 4.0 (4 is even) - (f2h(5.5), f2h(6.0)), # 5.5 -> 6.0 (6 is even) - (H_NEG_0P5, H_NEG_ZERO), # -0.5 -> -0.0 (-0 is even, preserving sign) - (H_NEG_1P5, H_NEG_2P0), # -1.5 -> -2.0 - (H_NEG_2P5, H_NEG_2P0), # -2.5 -> -2.0 - (H_NEG_3P5, H_NEG_4P0), # -3.5 -> -4.0 - (f2h(-4.5), H_NEG_4P0), # -4.5 -> -4.0 - (f2h(-5.5), f2h(-6.0)), # -5.5 -> -6.0 - (H_1022P5, f2h(1022.0)), # 1022.5 -> 1022.0 - (H_1023P5, H_1024), # 1023.5 -> 1024.0 (odd -> even) - (H_NEG_1022P5, f2h(-1022.0)), - (H_NEG_1023P5, f2h(-1024.0)), - ] - for inp, expected in ties: - with self.subTest(inp=hex(inp), expected=hex(expected)): - got = run_op("v_rndne_f16_e32 v0, v1", 0x12340000 | inp) - self.assertEqual(got, merge_half(OLD, expected, 0)) - - def test_e2e_rndne_opsel_high_half_destination(self): - """v_rndne_f16_e64 with op_sel:[0,1] writes to the high half while preserving the low half.""" - v1 = (0x9999 << 16) | H_2P5 # low half is 2.5 (ties to 2.0) - got = run_op("v_rndne_f16_e64 v0, v1 op_sel:[0,1]", v1) - self.assertEqual(got, merge_half(OLD, H_2P0, 1)) - - v1_hi = (H_1P5 << 16) | 0x9999 # high half is 1.5 (ties to 2.0) - got_hi = run_op("v_rndne_f16_e64 v0, v1 op_sel:[1,1]", v1_hi) - self.assertEqual(got_hi, merge_half(OLD, H_2P0, 1)) - - def test_e2e_signed_zeros_exact_bit_patterns(self): - """Strict IEEE 754-2008 / 2019 roundToIntegral signed zero bit preservation (0x8000 vs 0x0000).""" - cases = [ - ("v_floor_f16_e32", H_NEG_0P5, H_NEG_1P0), - ("v_ceil_f16_e32", H_NEG_0P5, H_NEG_ZERO), - ("v_trunc_f16_e32", H_NEG_0P5, H_NEG_ZERO), - ("v_rndne_f16_e32", f2h(-0.4), H_NEG_ZERO), - ("v_rndne_f16_e32", H_NEG_0P5, H_NEG_ZERO), - ("v_floor_f16_e32", H_NEG_ZERO, H_NEG_ZERO), - ("v_ceil_f16_e32", H_NEG_ZERO, H_NEG_ZERO), - ("v_trunc_f16_e32", H_NEG_ZERO, H_NEG_ZERO), - ("v_rndne_f16_e32", H_NEG_ZERO, H_NEG_ZERO), - ("v_floor_f16_e32", H_POS_ZERO, H_POS_ZERO), - ("v_ceil_f16_e32", H_POS_ZERO, H_POS_ZERO), - ("v_trunc_f16_e32", H_POS_ZERO, H_POS_ZERO), - ("v_rndne_f16_e32", H_POS_ZERO, H_POS_ZERO), - ] - for op, inp, expected in cases: - with self.subTest(op=op, inp=hex(inp), expected=hex(expected)): - got = run_op(f"{op} v0, v1", 0xFACE0000 | inp) - self.assertEqual(got, merge_half(OLD, expected, 0)) - # Verify exact bitwise sign bit 0x8000 - got_half = got & 0xFFFF - self.assertEqual(got_half & 0x8000, expected & 0x8000, f"Sign bit mismatch for {op} on {inp:#x}") - - def test_negative_control_roundeven_sabotaged_to_trunc(self): - """Sabotaging RoundEven to Trunc in SPIR-V fails halfway tie-breaking.""" - spv = translate_ps([f"v_mov_b32 v1, {H_1P5:#x}", f"v_mov_b32 v0, {OLD:#x}", "v_rndne_f16_e32 v0, v1"]) - sabotaged, n = re.subn(r"\bRoundEven\b", "Trunc", spv, count=1) - self.assertEqual(n, 1) - got = si.run_fragment(sabotaged)["%out_mrt0"][0] - self.assertNotEqual(got, merge_half(OLD, H_2P0, 0)) - self.assertEqual(got, merge_half(OLD, H_1P0, 0)) - - def test_negative_control_roundeven_sabotaged_to_ceil(self): - """Sabotaging RoundEven to Ceil in SPIR-V fails halfway tie-breaking on odd rounds.""" - spv = translate_ps([f"v_mov_b32 v1, {H_2P5:#x}", f"v_mov_b32 v0, {OLD:#x}", "v_rndne_f16_e32 v0, v1"]) - sabotaged, n = re.subn(r"\bRoundEven\b", "Ceil", spv, count=1) - self.assertEqual(n, 1) - got = si.run_fragment(sabotaged)["%out_mrt0"][0] - self.assertNotEqual(got, merge_half(OLD, H_2P0, 0)) - self.assertEqual(got, merge_half(OLD, H_3P0, 0)) - - def test_negative_control_ceil_sabotaged_to_floor(self): - """Sabotaging Ceil to Floor in SPIR-V fails ceiling assertion.""" - spv = translate_ps([f"v_mov_b32 v1, {H_1P25:#x}", f"v_mov_b32 v0, {OLD:#x}", "v_ceil_f16_e32 v0, v1"]) - sabotaged, n = re.subn(r"\bCeil\b", "Floor", spv, count=1) - self.assertEqual(n, 1) - got = si.run_fragment(sabotaged)["%out_mrt0"][0] - self.assertNotEqual(got, merge_half(OLD, H_2P0, 0)) - self.assertEqual(got, merge_half(OLD, H_1P0, 0)) - - def test_negative_control_clamp_omitted(self): - """Omitting FClamp in SPIR-V produces out-of-bounds unclamped float.""" - spv = translate_ps([f"v_mov_b32 v1, {H_2P5:#x}", f"v_mov_b32 v0, {OLD:#x}", "v_trunc_f16_e64 v0, v1 mul:2 clamp"]) - sabotaged, n = re.subn(r"OpExtInst %float %glsl FClamp (%\w+) %f0 %f1", r"OpCopyObject %float \1", spv) - self.assertEqual(n, 1) - got = si.run_fragment(sabotaged)["%out_mrt0"][0] - self.assertNotEqual(got, merge_half(OLD, H_1P0, 0)) - self.assertEqual(got, merge_half(OLD, H_2P0, 0)) - - def test_negative_control_dropped_signed_zero_detected(self): - """A mutant that strips sign bits from -0.0 results is detected by bitwise check.""" - for op, inp in [("v_ceil_f16_e32", H_NEG_0P5), ("v_trunc_f16_e32", H_NEG_0P5), ("v_rndne_f16_e32", f2h(-0.4))]: - got = run_op(f"{op} v0, v1", 0x11110000 | inp) - mutated = got & 0xFFFF7FFF - self.assertNotEqual(mutated, got, f"Sign bit mutation must differ for {op} on {inp:#x}") - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_valu_f16_sub.py b/tests/semantic/test_valu_f16_sub.py deleted file mode 100644 index ffd1dca42..000000000 --- a/tests/semantic/test_valu_f16_sub.py +++ /dev/null @@ -1,647 +0,0 @@ -"""Semantic interpreter tests for AMD RDNA2 half-precision float subtraction (v_sub_f16, v_pk_sub_f16). - -Covers: - - v_sub_f16: D.f16 = S0.f16 - S1.f16 (VOP2 0x33 on GFX10). - - VOP2 _e32 form: writes low 16-bit half of destination VGPR and keeps the high 16-bit half - (per docs/design.md, "16-bit results"). - - VOP3 _e64 form: op_sel:[src0, src1, dst] selects low (0) or high (1) 16-bit half for operands - and destination. - - VOP3 modifiers: source negation (-s), absolute value (|s|), negative absolute value (-|s|), - and output modifiers (clamp to [0.0, 1.0], scale mul:2, mul:4, div:2). - - Inline constants, SGPR scalar broadcast sources, destination aliasing, and duality with v_subrev_f16. - - v_pk_sub_f16: packed 2x f16 SIMD vector subtraction across Wave32 and Wave64 execution waves. - - Packed modifiers: op_sel, op_sel_hi, neg_lo, neg_hi, and independent half clamping. - - EXEC mask gating: inactive lanes strictly preserve prior 32-bit register contents. - - Hardware ISA equivalence: packed subtraction implemented via v_pk_add_f16 with operand negation - (neg_lo:[0,1] neg_hi:[0,1]), and translator rejection of untranslated pseudo-op v_pk_sub_f16. - -All operations are executed end-to-end through tools/rdna2spirv.py and -tests/semantic/spirv_mini_interp.py and verified against a deterministic reference oracle. - -Standard library only: zero game data, no GPU hardware required. -""" -from __future__ import annotations - -import gc -import itertools -import math -import os -import random -import struct -import sys -import tempfile -import unittest -import warnings - -HERE = os.path.dirname(os.path.abspath(__file__)) -ROOT = os.path.dirname(os.path.dirname(HERE)) -TOOLS_DIR = os.environ.get("LEONIDA_TOOLS_DIR") or os.path.join(ROOT, "tools") - -sys.dont_write_bytecode = True -if TOOLS_DIR not in sys.path: - sys.path.insert(0, TOOLS_DIR) -if HERE not in sys.path: - sys.path.insert(0, HERE) - -import rdna2spirv # noqa: E402 -import spirv_mini_interp as si # noqa: E402 - -STUB_DXBC = b"DXBC" + bytes(24) + struct.pack(" float: - """Unpack 16-bit half-precision float to Python float.""" - return struct.unpack(" int: - """Pack Python float to 16-bit half-precision bit pattern.""" - try: - return struct.unpack(" 0 else H_NEG_INF - - -def half(word: int, hi: int) -> float: - """Extract half-precision float from low (hi=0) or high (hi=1) word half.""" - return h2f((word >> 16) if hi else word) - - -def merge_half(old: int, h: int, dst_hi: int) -> int: - """Merge 16-bit result into 32-bit register, preserving unwritten half.""" - h &= 0xFFFF - return ((h << 16) | (old & 0xFFFF)) if dst_hi else ((old & 0xFFFF0000) | h) - - -def pack_f16x2(lo: int, hi: int) -> int: - """Pack two 16-bit half-precision floats into a 32-bit dword.""" - return ((hi & 0xFFFF) << 16) | (lo & 0xFFFF) - - -def unpack_f16x2(word: int) -> tuple[int, int]: - """Unpack 32-bit dword into low and high 16-bit half-precision words.""" - return word & 0xFFFF, (word >> 16) & 0xFFFF - - -def clamp01(x: float) -> float: - """Clamp float to [0.0, 1.0].""" - return min(max(x, 0.0), 1.0) - - -def ref_v_sub_f16(s0: int, s1: int) -> int: - """Reference oracle for v_sub_f16: S0.f16 - S1.f16.""" - return f2h(h2f(s0) - h2f(s1)) - - -def ref_v_subrev_f16(s0: int, s1: int) -> int: - """Reference oracle for v_subrev_f16: S1.f16 - S0.f16.""" - return f2h(h2f(s1) - h2f(s0)) - - -def ref_v_pk_sub_f16( - s0: int, - s1: int, - op_sel: tuple[int, int] = (0, 0), - op_sel_hi: tuple[int, int] = (1, 1), - neg_lo: tuple[int, int] = (0, 0), - neg_hi: tuple[int, int] = (0, 0), - clamp: bool = False, -) -> int: - """Reference oracle for packed half-precision subtraction v_pk_sub_f16.""" - val0_lo = half(s0, op_sel[0]) - val1_lo = half(s1, op_sel[1]) - if neg_lo[0]: - val0_lo = -val0_lo - if neg_lo[1]: - val1_lo = -val1_lo - diff_lo = val0_lo - val1_lo - if clamp: - diff_lo = clamp01(diff_lo) - - val0_hi = half(s0, op_sel_hi[0]) - val1_hi = half(s1, op_sel_hi[1]) - if neg_hi[0]: - val0_hi = -val0_hi - if neg_hi[1]: - val1_hi = -val1_hi - diff_hi = val0_hi - val1_hi - if clamp: - diff_hi = clamp01(diff_hi) - - return pack_f16x2(f2h(diff_lo), f2h(diff_hi)) - - -class SimdF16WaveInterpreter: - """Deterministic semantic interpreter for multi-lane SIMD packed f16 execution. - - Models: - - 32-lane (Wave32) or 64-lane (Wave64) vector execution. - - 32-bit VGPRs holding 2x packed f16 values per lane. - - 32-bit SGPRs holding scalar/broadcast constants. - - EXEC mask gating active lanes (inactive lanes preserve prior values). - - Packed VOP3P modifiers: op_sel, op_sel_hi, neg_lo, neg_hi, clamp. - - Scalar VOP2/VOP3 f16 operations preserving unwritten register halves. - """ - - def __init__(self, num_vgprs: int = 64, num_sgprs: int = 106, wave_size: int = 64) -> None: - self.num_vgprs = num_vgprs - self.num_sgprs = num_sgprs - self.wave_size = wave_size - self.vgprs = [[0] * wave_size for _ in range(num_vgprs)] - self.sgprs = [0] * num_sgprs - self.exec_mask = (1 << wave_size) - 1 - - def reset(self) -> None: - self.vgprs = [[0] * self.wave_size for _ in range(self.num_vgprs)] - self.sgprs = [0] * self.num_sgprs - self.exec_mask = (1 << self.wave_size) - 1 - - def set_vgpr(self, reg_idx: int, lane: int, val: int) -> None: - self.vgprs[reg_idx][lane] = val & 0xFFFFFFFF - - def get_vgpr(self, reg_idx: int, lane: int) -> int: - return self.vgprs[reg_idx][lane] & 0xFFFFFFFF - - def set_sgpr(self, reg_idx: int, val: int) -> None: - self.sgprs[reg_idx] = val & 0xFFFFFFFF - - def get_sgpr(self, reg_idx: int) -> int: - return self.sgprs[reg_idx] & 0xFFFFFFFF - - def set_exec(self, mask: int) -> None: - self.exec_mask = mask & ((1 << self.wave_size) - 1) - - def resolve_src(self, op: str | int, lane: int) -> int: - if isinstance(op, int): - return op & 0xFFFFFFFF - op_str = op.strip().lower() - if op_str.startswith("v"): - idx = int(op_str[1:]) - return self.vgprs[idx][lane] & 0xFFFFFFFF - if op_str.startswith("s"): - idx = int(op_str[1:]) - return self.sgprs[idx] & 0xFFFFFFFF - return int(op_str, 0) & 0xFFFFFFFF - - def execute_v_pk_sub_f16( - self, - dst_idx: int, - src0: str | int, - src1: str | int, - op_sel: tuple[int, int] = (0, 0), - op_sel_hi: tuple[int, int] = (1, 1), - neg_lo: tuple[int, int] = (0, 0), - neg_hi: tuple[int, int] = (0, 0), - clamp: bool = False, - ) -> None: - for lane in range(self.wave_size): - if (self.exec_mask >> lane) & 1: - s0 = self.resolve_src(src0, lane) - s1 = self.resolve_src(src1, lane) - self.vgprs[dst_idx][lane] = ref_v_pk_sub_f16( - s0, - s1, - op_sel=op_sel, - op_sel_hi=op_sel_hi, - neg_lo=neg_lo, - neg_hi=neg_hi, - clamp=clamp, - ) - - def execute_v_sub_f16( - self, - dst_idx: int, - src0: str | int, - src1: str | int, - op_sel: tuple[int, int, int] = (0, 0, 0), - clamp: bool = False, - ) -> None: - for lane in range(self.wave_size): - if (self.exec_mask >> lane) & 1: - s0 = self.resolve_src(src0, lane) - s1 = self.resolve_src(src1, lane) - v0 = half(s0, op_sel[0]) - v1 = half(s1, op_sel[1]) - diff = v0 - v1 - if clamp: - diff = clamp01(diff) - old_val = self.vgprs[dst_idx][lane] - self.vgprs[dst_idx][lane] = merge_half(old_val, f2h(diff), op_sel[2]) - - -_TMP_DIR: tempfile.TemporaryDirectory | None = None -_SRC_PATH: str | None = None - - -def setUpModule() -> None: - global _TMP_DIR, _SRC_PATH - _TMP_DIR = tempfile.TemporaryDirectory() - disasm_dir = os.path.join(_TMP_DIR.name, "disasm") - os.mkdir(disasm_dir) - _SRC_PATH = os.path.join(disasm_dir, "ps_sub_f16.s") - with open(os.path.join(_TMP_DIR.name, "ps_sub_f16.dxbc"), "wb") as f: - f.write(STUB_DXBC) - - -def tearDownModule() -> None: - global _TMP_DIR - if _TMP_DIR is not None: - gc.collect() - _TMP_DIR.cleanup() - _TMP_DIR = None - - -def run_sub_f16(line: str, v1: int, v2: int, old: int = OLD) -> int: - """Seed v1, v2 and destination v0, run instruction line, return v0.""" - if _TMP_DIR is None: - setUpModule() - lines = [ - f"v_mov_b32 v1, {v1:#x}", - f"v_mov_b32 v2, {v2:#x}", - f"v_mov_b32 v0, {old:#x}", - line, - ] - asm = ( - "; test_valu_f16_sub\n" - + "".join(f"\t{ln}\n" for ln in lines) - + "\texp mrt0 v0, v0, v0, v0 done vm\n\ts_endpgm\n" - ) - with open(_SRC_PATH, "w", encoding="utf-8") as f: - f.write(asm) - with warnings.catch_warnings(): - warnings.simplefilter("ignore", ResourceWarning) - spv = rdna2spirv.translate(_SRC_PATH) - return si.run_fragment(spv)["%out_mrt0"][0] - - -class VectorSubF16ReferenceTests(unittest.TestCase): - """Tests for the reference mathematical oracle of half-precision subtraction.""" - - def test_basic_subtraction(self): - self.assertEqual(ref_v_sub_f16(H_1P5, H_0P5), H_1P0) - self.assertEqual(ref_v_sub_f16(H_5P0, H_2P5), H_2P5) - self.assertEqual(ref_v_sub_f16(H_0P5, H_1P5), H_NEG_1P0) - self.assertEqual(ref_v_sub_f16(H_2P0, H_4P0), H_NEG_2P0) - - def test_identity_and_cancellation(self): - for val in (H_0P5, H_1P0, H_1P5, H_2P0, H_3P0, H_MAX): - self.assertEqual(ref_v_sub_f16(val, H_POS_ZERO), val) - self.assertEqual(ref_v_sub_f16(H_POS_ZERO, val), f2h(-h2f(val))) - # Cancellation x - x = +0.0 in round-to-nearest - self.assertEqual(ref_v_sub_f16(val, val) & 0x7FFF, 0x0000) - - def test_duality_with_subrev(self): - pairs = [ - (H_1P5, H_0P5), - (H_0P5, H_1P5), - (H_3P0, H_1P0), - (H_2P5, H_4P0), - (H_0P25, H_0P75), - ] - for a, b in pairs: - self.assertEqual(ref_v_sub_f16(a, b), ref_v_subrev_f16(b, a)) - - def test_merge_half_preserves_unwritten_half(self): - self.assertEqual(merge_half(OLD, H_1P0, dst_hi=0), 0xAAAA3C00) - self.assertEqual(merge_half(OLD, H_1P0, dst_hi=1), 0x3C005555) - - -class VectorSubF16SpirvTests(unittest.TestCase): - """Tests for v_sub_f16 lowering to SPIR-V OpFSub and execution in spirv_mini_interp.""" - - def test_vop2_e32_computes_s0_minus_s1_and_preserves_dst_hi(self): - # 1.5 (0x3E00) - 0.5 (0x3800) = 1.0 (0x3C00) - got = run_sub_f16("v_sub_f16_e32 v0, v1, v2", H_1P5, H_0P5) - self.assertEqual(got, merge_half(OLD, H_1P0, 0)) - - def test_vop2_e32_negative_difference(self): - # 0.5 (0x3800) - 1.5 (0x3E00) = -1.0 (0xBC00) - got = run_sub_f16("v_sub_f16_e32 v0, v1, v2", H_0P5, H_1P5) - self.assertEqual(got, merge_half(OLD, H_NEG_1P0, 0)) - - def test_vop3_op_sel_all_combinations(self): - # v1: lo = 1.5 (0x3E00), hi = 4.0 (0x4400) - # v2: lo = 0.5 (0x3800), hi = 2.0 (0x4000) - v1 = (H_4P0 << 16) | H_1P5 - v2 = (H_2P0 << 16) | H_0P5 - for s0_hi, s1_hi, d_hi in itertools.product((0, 1), repeat=3): - line = f"v_sub_f16_e64 v0, v1, v2 op_sel:[{s0_hi},{s1_hi},{d_hi}]" - with self.subTest(line=line): - val0 = half(v1, s0_hi) - val1 = half(v2, s1_hi) - expected_diff = f2h(val0 - val1) - expected = merge_half(OLD, expected_diff, d_hi) - self.assertEqual(run_sub_f16(line, v1, v2), expected) - - def test_vop3_source_modifiers(self): - v1 = H_1P5 - v2 = H_0P5 - # Negation: -v1 - v2 = -1.5 - 0.5 = -2.0 - self.assertEqual( - run_sub_f16("v_sub_f16_e64 v0, -v1, v2", v1, v2), - merge_half(OLD, H_NEG_2P0, 0), - ) - # Negation on src1: v1 - (-v2) = 1.5 - (-0.5) = 2.0 - self.assertEqual( - run_sub_f16("v_sub_f16_e64 v0, v1, -v2", v1, v2), - merge_half(OLD, H_2P0, 0), - ) - # Absolute value: |v1| - |v2| with negative input - v1_neg = H_NEG_1P5 - v2_neg = H_NEG_0P5 - self.assertEqual( - run_sub_f16("v_sub_f16_e64 v0, |v1|, |v2|", v1_neg, v2_neg), - merge_half(OLD, H_1P0, 0), - ) - # Negative absolute value: -|v1| - v2 = -1.5 - 0.5 = -2.0 - self.assertEqual( - run_sub_f16("v_sub_f16_e64 v0, -|v1|, v2", v1, v2), - merge_half(OLD, H_NEG_2P0, 0), - ) - - def test_vop3_clamp_modifier(self): - v1 = H_1P5 - v2 = H_0P5 - # 1.5 - (-0.5) = 2.0; clamped to 1.0 - self.assertEqual( - run_sub_f16("v_sub_f16_e64 v0, v1, -v2 clamp", v1, v2), - merge_half(OLD, H_1P0, 0), - ) - # 0.5 - 1.5 = -1.0; clamped to 0.0 - self.assertEqual( - run_sub_f16("v_sub_f16_e64 v0, v2, v1 clamp", v1, v2), - merge_half(OLD, H_POS_ZERO, 0), - ) - - def test_vop3_scale_output_modifiers(self): - v1 = H_1P5 - v2 = H_0P5 - # 1.5 - 0.5 = 1.0; on RDNA2 with denorms kept, mul:2 / mul:4 / div:2 are ignored on f16. - self.assertEqual( - run_sub_f16("v_sub_f16_e64 v0, v1, v2 mul:2", v1, v2), - merge_half(OLD, H_1P0, 0), - ) - self.assertEqual( - run_sub_f16("v_sub_f16_e64 v0, v1, v2 mul:4", v1, v2), - merge_half(OLD, H_1P0, 0), - ) - self.assertEqual( - run_sub_f16("v_sub_f16_e64 v0, v1, v2 div:2", v1, v2), - merge_half(OLD, H_1P0, 0), - ) - - def test_inline_constants_and_sgpr(self): - if _TMP_DIR is None: - setUpModule() - # Inline float constant 1.0 (0x3C00) in s0: 1.0 - 0.5 = 0.5 - lines = [ - f"v_mov_b32 v0, {OLD:#x}", - f"v_mov_b32 v1, {H_0P5:#x}", - "v_sub_f16_e32 v0, 1.0, v1", - "exp mrt0 v0, v0, v0, v0 done vm", - "s_endpgm", - ] - asm = "; test_inline_const\n" + "".join(f"\t{ln}\n" for ln in lines) - with open(_SRC_PATH, "w", encoding="utf-8") as f: - f.write(asm) - with warnings.catch_warnings(): - warnings.simplefilter("ignore", ResourceWarning) - spv = rdna2spirv.translate(_SRC_PATH) - got = si.run_fragment(spv)["%out_mrt0"][0] - self.assertEqual(got, merge_half(OLD, H_0P5, 0)) - - # SGPR scalar source: s0 loaded with 2.5 - lines_sgpr = [ - f"v_mov_b32 v0, {OLD:#x}", - f"s_mov_b32 s0, {H_2P5:#x}", - f"v_mov_b32 v1, {H_1P5:#x}", - "v_sub_f16_e32 v0, s0, v1", - "exp mrt0 v0, v0, v0, v0 done vm", - "s_endpgm", - ] - asm_sgpr = "; test_sgpr\n" + "".join(f"\t{ln}\n" for ln in lines_sgpr) - with open(_SRC_PATH, "w", encoding="utf-8") as f: - f.write(asm_sgpr) - with warnings.catch_warnings(): - warnings.simplefilter("ignore", ResourceWarning) - spv_sgpr = rdna2spirv.translate(_SRC_PATH) - got_sgpr = si.run_fragment(spv_sgpr)["%out_mrt0"][0] - self.assertEqual(got_sgpr, merge_half(OLD, H_1P0, 0)) - - def test_destination_aliasing(self): - if _TMP_DIR is None: - setUpModule() - # Aliasing dst with src0: v1 = v1 - v2 - lines = [ - f"v_mov_b32 v1, {OLD:#x}", - f"v_mov_b32 v2, {H_0P5:#x}", - "v_mov_b32 v1, 0xAAAA3E00", - "v_sub_f16_e32 v1, v1, v2", - "exp mrt0 v1, v1, v1, v1 done vm", - "s_endpgm", - ] - asm = "; test_dst_alias\n" + "".join(f"\t{ln}\n" for ln in lines) - with open(_SRC_PATH, "w", encoding="utf-8") as f: - f.write(asm) - with warnings.catch_warnings(): - warnings.simplefilter("ignore", ResourceWarning) - spv = rdna2spirv.translate(_SRC_PATH) - got = si.run_fragment(spv)["%out_mrt0"][0] - self.assertEqual(got, merge_half(0xAAAA3E00, H_1P0, 0)) - - def test_differential_fuzz_finite_pairs(self): - rng = random.Random(0x516) - candidates = [ - H_0P25, H_NEG_0P25, H_0P5, H_NEG_0P5, H_0P75, H_NEG_0P75, - H_1P0, H_NEG_1P0, H_1P5, H_NEG_1P5, H_2P0, H_NEG_2P0, - H_2P5, H_3P0, H_4P0, - ] - for _ in range(30): - x = rng.choice(candidates) - y = rng.choice(candidates) - expected = ref_v_sub_f16(x, y) - with self.subTest(x=hex(x), y=hex(y)): - got = run_sub_f16("v_sub_f16_e32 v0, v1, v2", x, y) - self.assertEqual(got, merge_half(OLD, expected, 0)) - - -class PackedF16SIMDExecutionTests(unittest.TestCase): - """Tests for packed half-precision v_pk_sub_f16 multi-lane SIMD execution and hardware equivalence.""" - - def test_packed_sub_reference_basic(self): - # [1.5, 3.0] - [0.5, 1.0] = [1.0, 2.0] - s0 = pack_f16x2(H_1P5, H_3P0) - s1 = pack_f16x2(H_0P5, H_1P0) - expected = pack_f16x2(H_1P0, H_2P0) - self.assertEqual(ref_v_pk_sub_f16(s0, s1), expected) - - def test_packed_sub_wave64_simd_execution(self): - interp = SimdF16WaveInterpreter(wave_size=64) - for lane in range(64): - lo_0 = f2h(1.0 + lane * 0.25) - hi_0 = f2h(2.0 + lane * 0.5) - lo_1 = f2h(0.5) - hi_1 = f2h(1.0) - interp.set_vgpr(1, lane, pack_f16x2(lo_0, hi_0)) - interp.set_vgpr(2, lane, pack_f16x2(lo_1, hi_1)) - - interp.execute_v_pk_sub_f16(0, "v1", "v2") - - for lane in range(64): - expected_lo = f2h((1.0 + lane * 0.25) - 0.5) - expected_hi = f2h((2.0 + lane * 0.5) - 1.0) - got = interp.get_vgpr(0, lane) - self.assertEqual(got, pack_f16x2(expected_lo, expected_hi)) - - def test_packed_sub_wave32_simd_execution(self): - interp = SimdF16WaveInterpreter(wave_size=32) - for lane in range(32): - interp.set_vgpr(1, lane, pack_f16x2(H_4P0, H_5P0)) - interp.set_vgpr(2, lane, pack_f16x2(H_1P5, H_2P5)) - - interp.execute_v_pk_sub_f16(0, "v1", "v2") - - for lane in range(32): - self.assertEqual(interp.get_vgpr(0, lane), pack_f16x2(H_2P5, H_2P5)) - - def test_packed_sub_exec_mask_gating_preserves_lanes(self): - interp = SimdF16WaveInterpreter(wave_size=64) - SENTINEL = 0xDEADBEEF - for lane in range(64): - interp.set_vgpr(0, lane, SENTINEL) - interp.set_vgpr(1, lane, pack_f16x2(H_2P0, H_4P0)) - interp.set_vgpr(2, lane, pack_f16x2(H_0P5, H_1P0)) - - # Even lanes active only - interp.set_exec(0x5555555555555555) - interp.execute_v_pk_sub_f16(0, "v1", "v2") - - expected_active = pack_f16x2(H_1P5, H_3P0) - for lane in range(64): - if lane % 2 == 0: - self.assertEqual(interp.get_vgpr(0, lane), expected_active) - else: - self.assertEqual(interp.get_vgpr(0, lane), SENTINEL) - - # Inactive wave (exec = 0): nothing changes - interp.set_exec(0) - interp.execute_v_pk_sub_f16(0, "v1", "v2") - self.assertEqual(interp.get_vgpr(0, 1), SENTINEL) - - def test_packed_sub_cross_half_op_sel(self): - s0 = pack_f16x2(H_1P0, H_4P0) - s1 = pack_f16x2(H_0P5, H_2P0) - - # Cross halves: lo computes s0.hi - s1.lo (4.0 - 0.5 = 3.5), hi computes s0.lo - s1.hi (1.0 - 2.0 = -1.0) - got = ref_v_pk_sub_f16(s0, s1, op_sel=(1, 0), op_sel_hi=(0, 1)) - expected = pack_f16x2(H_3P5, H_NEG_1P0) - self.assertEqual(got, expected) - - # Broadcast s0.hi to both halves: lo computes s0.hi - s1.lo (4.0 - 0.5 = 3.5), - # hi computes s0.hi - s1.hi (4.0 - 2.0 = 2.0) - got_bcast = ref_v_pk_sub_f16(s0, s1, op_sel=(1, 0), op_sel_hi=(1, 1)) - self.assertEqual(got_bcast, pack_f16x2(H_3P5, H_2P0)) - - def test_packed_sub_negation_modifiers(self): - s0 = pack_f16x2(H_1P5, H_2P0) - s1 = pack_f16x2(H_0P5, H_1P0) - - # neg_lo:[1, 0] -> -1.5 - 0.5 = -2.0 - # neg_hi:[0, 1] -> 2.0 - (-1.0) = 3.0 - got = ref_v_pk_sub_f16(s0, s1, neg_lo=(1, 0), neg_hi=(0, 1)) - self.assertEqual(got, pack_f16x2(H_NEG_2P0, H_3P0)) - - def test_packed_sub_independent_half_clamp(self): - # lo: 0.5 - 1.5 = -1.0 -> clamp -> 0.0 - # hi: 1.5 - (-0.5) = 2.0 -> clamp -> 1.0 - s0 = pack_f16x2(H_0P5, H_1P5) - s1 = pack_f16x2(H_1P5, H_NEG_0P5) - got = ref_v_pk_sub_f16(s0, s1, clamp=True) - self.assertEqual(got, pack_f16x2(H_POS_ZERO, H_1P0)) - - def test_packed_sub_hardware_equivalence_with_negated_add(self): - pairs = [ - (pack_f16x2(H_1P5, H_4P0), pack_f16x2(H_0P5, H_1P0)), - (pack_f16x2(H_0P75, H_2P5), pack_f16x2(H_0P25, H_1P5)), - (pack_f16x2(H_3P0, H_0P5), pack_f16x2(H_1P0, H_1P5)), - ] - for s0, s1 in pairs: - sub_res = ref_v_pk_sub_f16(s0, s1) - lo0, hi0 = unpack_f16x2(s0) - lo1, hi1 = unpack_f16x2(s1) - add_neg = pack_f16x2(f2h(h2f(lo0) + (-h2f(lo1))), f2h(h2f(hi0) + (-h2f(hi1)))) - self.assertEqual(sub_res, add_neg) - - def test_spirv_pipeline_packed_negated_add_matches_oracle(self): - if _TMP_DIR is None: - setUpModule() - s0 = pack_f16x2(H_1P5, H_4P0) - s1 = pack_f16x2(H_0P5, H_1P0) - lines = [ - f"v_mov_b32 v1, {s0:#x}", - f"v_mov_b32 v2, {s1:#x}", - "v_pk_add_f16 v0, v1, v2 neg_lo:[0,1] neg_hi:[0,1]", - "exp mrt0 v0, v0, v0, v0 done vm", - "s_endpgm", - ] - asm = "; test_pk_pipeline\n" + "".join(f"\t{ln}\n" for ln in lines) - with open(_SRC_PATH, "w", encoding="utf-8") as f: - f.write(asm) - with warnings.catch_warnings(): - warnings.simplefilter("ignore", ResourceWarning) - spv = rdna2spirv.translate(_SRC_PATH) - got = si.run_fragment(spv)["%out_mrt0"][0] - expected = ref_v_pk_sub_f16(s0, s1) - self.assertEqual(got, expected) - - def test_translator_rejects_untranslated_v_pk_sub_f16_mnemonic(self): - if _TMP_DIR is None: - setUpModule() - lines = [ - f"v_mov_b32 v1, {H_1P0:#x}", - f"v_mov_b32 v2, {H_0P5:#x}", - "v_pk_sub_f16 v0, v1, v2", - "exp mrt0 v0, v0, v0, v0 done vm", - "s_endpgm", - ] - asm = "; test_unsupported_pk_sub\n" + "".join(f"\t{ln}\n" for ln in lines) - with open(_SRC_PATH, "w", encoding="utf-8") as f: - f.write(asm) - with warnings.catch_warnings(): - warnings.simplefilter("ignore", ResourceWarning) - with self.assertRaises(rdna2spirv.Unsupported) as ctx: - rdna2spirv.translate(_SRC_PATH) - self.assertIn("v_pk_sub_f16", str(ctx.exception)) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_valu_f32_class_rndne.py b/tests/semantic/test_valu_f32_class_rndne.py deleted file mode 100644 index 618a2a94d..000000000 --- a/tests/semantic/test_valu_f32_class_rndne.py +++ /dev/null @@ -1,847 +0,0 @@ -"""Semantic value tests for f32 class, round-to-even, and rcp_iflag VALU ops: - v_cmp_class_f32 D.u[lane] = ((class_bit(S0.f32) & S1.u[9:0]) != 0) if EXEC[lane] else 0 - v_cmpx_class_f32 EXEC[lane] &= ((class_bit(S0.f32) & S1.u[9:0]) != 0) (preserves VCC) - v_rndne_f32 D.f32 = roundToIntegralTiesToEven(S0.f32) - v_rcp_iflag_f32 D.f32 = 1.0 / S0.f32 (RDNA2 1-ULP approximate reciprocal, no FP flags) - -IEEE-754 binary32 class mask bits for v_cmp_class_f32 / v_cmpx_class_f32 (AMD RDNA2 ISA, S1[9:0]): - bit 0 (0x001): sNaN bit 5 (0x020): -0.0 - bit 1 (0x002): qNaN bit 6 (0x040): +0.0 - bit 2 (0x004): -inf bit 7 (0x080): +subnormal - bit 3 (0x008): -normal bit 8 (0x100): +normal - bit 4 (0x010): -subnormal bit 9 (0x200): +inf -Bits [31:10] of the mask operand are ignored. - -Executed end-to-end through tools/rdna2spirv.py and tests/semantic/spirv_mini_interp.py (both single-lane -run_fragment and multi-lane compute run_workgroup), and checked against hand-computed constants and independent -plain-Python RDNA2 ISA reference functions. Standard library only; hand-written RDNA2 listings only. - -Findings & exclusions (no shared files modified): - 1. v_rcp_iflag_f32 lowers to `OpFDiv %float %f1 {x}` followed by the VOP3 output modifiers (`clamp`, `mul:2`, - `mul:4`, `div:2`) through `clamp_mods`, as `v_rcp_f32` does. When this file was written the translator dropped - those modifiers and spirv_mini_interp.py had no `OpFDiv`; both have changed since (FUZZ-3, ed6da6b6), so - RcpIflagF32OracleAndTranslationTests now executes it on exact inputs (powers of two, so the 1-ULP hardware - approximation and the interpreter's exact division agree) with each output modifier. A zero operand stays - out: `OpFDiv` by zero is undefined in SPIR-V and the interpreter refuses it (docs/design.md, "Denormal flush - and special results", Not modelled yet). gfx1036 hardware agrees with the translator on 2,570 of 3,000 fuzzed - programs with clamp/omod and differs on none (`tools/f32_fuzz.py --oracle translator,hw --ops - v_rcp_iflag_f32`, seeds 1 to 3; the rest are division by zero or cases the model does not judge). - 2. NaN caveats in SPIR-V / spirv_mini_interp.py: - - For `v_rndne_f32` on NaN (`qNaN` / `sNaN`), SPIR-V / GLSL.std.450 `RoundEven` leaves NaN payload/quieting - unspecified (spirv_mini_interp.py returns the input NaN unchanged; hardware quiets `sNaN`). Tests assert - that the result is a binary32 NaN rather than pinning an exact NaN payload. - - For `v_cmp_class_f32` / `v_cmpx_class_f32` VOP3 source modifiers (`-`, `|..|`), tools/rdna2spirv.py emits - float `OpFNegate`/`FAbs`, which in spirv_mini_interp.py goes through Python float packing and quiets `sNaN` - (see tests/semantic/test_interp.py). Source modifiers are therefore tested on `+-inf`, `+-normal`, - `+-subnormal`, `+-0.0`, and `qNaN`; raw `sNaN` (`+sNaN` / `-sNaN`) is tested without float modifiers. -""" -import gc -import math -import os -import re -import struct -import sys -import tempfile -import unittest -import warnings - -HERE = os.path.dirname(os.path.abspath(__file__)) -ROOT = os.path.dirname(os.path.dirname(HERE)) -TOOLS_DIR = os.environ.get("LEONIDA_TOOLS_DIR") or os.path.join(ROOT, "tools") - -sys.dont_write_bytecode = True -if TOOLS_DIR not in sys.path: - sys.path.insert(0, TOOLS_DIR) -if HERE not in sys.path: - sys.path.insert(0, HERE) - -import rdna2spirv # noqa: E402 -import spirv_mini_interp as si # noqa: E402 - -MASK32 = 0xFFFFFFFF -STUB_DXBC = b"DXBC" + bytes(24) + struct.pack(" float: - try: - return struct.unpack(" int: - try: - return struct.unpack(" 0 else 0xFF800000 - - -def bits_f32(bits: int) -> float: - return struct.unpack(" bool: - return (bits & 0x7F800000) == 0x7F800000 and (bits & 0x007FFFFF) != 0 - - -# ----------------------------------------------------------------------------- -# Independent RDNA2 ISA Reference Functions & Hand-Worked Constants -# ----------------------------------------------------------------------------- - -def f32_class_bit(bits: int) -> int: - """Return the single RDNA2 class bit (1 << 0..9) for IEEE-754 binary32 word `bits`.""" - bits &= MASK32 - sign = (bits >> 31) & 1 - exp = (bits >> 23) & 0xFF - man = bits & 0x7FFFFF - if exp == 0xFF: - if man == 0: - return CLASS_NINF if sign else CLASS_PINF - return CLASS_QNAN if (man & 0x400000) else CLASS_SNAN - if exp == 0: - if man == 0: - return CLASS_NZERO if sign else CLASS_PZERO - return CLASS_NSUBNORM if sign else CLASS_PSUBNORM - return CLASS_NNORM if sign else CLASS_PNORM - - -def ref_cmp_class_f32(x_bits: int, mask: int) -> bool: - """RDNA2 ISA V_CMP_CLASS_F32: True iff x's IEEE-754 class bit is selected in mask[9:0].""" - return bool(f32_class_bit(x_bits) & (mask & ALL_CLASS_MASK)) - - -def ref_rndne_f32(x_bits: int) -> int: - """RDNA2 ISA V_RNDNE_F32: IEEE-754 roundToIntegralTiesToEven preserving sign of zero.""" - bits = x_bits & MASK32 - if is_f32_nan_bits(bits): - return bits | 0x00400000 - x = bits_f32(bits) - if not math.isfinite(x): - return bits - return f32_bits(math.copysign(float(round(x)), x)) - - -def ref_rcp_iflag_f32(x_bits: int) -> int: - """RDNA2 ISA V_RCP_IFLAG_F32 (idealized exact 1/x for powers of two, specials, and normals).""" - bits = x_bits & MASK32 - if is_f32_nan_bits(bits): - return 0x7FC00000 - sign = bits & 0x80000000 - absu = bits & 0x7FFFFFFF - if absu == 0: - return sign | 0x7F800000 # +-0.0 -> +-inf - if absu == 0x7F800000: - return sign # +-inf -> +-0.0 - return f32_bits(1.0 / bits_f32(bits)) - - -# Hand-worked classification samples covering all 10 IEEE-754 classes (including boundaries and signs). -CLASS_SAMPLES = ( - ("pos_snan_min", 0x7F800001, CLASS_SNAN), - ("pos_snan_max", 0x7FBFFFFF, CLASS_SNAN), - ("neg_snan_min", 0xFF800001, CLASS_SNAN), - ("neg_snan_max", 0xFFBFFFFF, CLASS_SNAN), - ("pos_qnan", 0x7FC00000, CLASS_QNAN), - ("pos_qnan_payload", 0x7FFFFFFF, CLASS_QNAN), - ("neg_qnan", 0xFFC00000, CLASS_QNAN), - ("neg_qnan_payload", 0xFFFFFFFF, CLASS_QNAN), - ("neg_inf", 0xFF800000, CLASS_NINF), - ("neg_one", 0xBF800000, CLASS_NNORM), - ("neg_norm_min", 0x80800000, CLASS_NNORM), - ("neg_norm_max", 0xFF7FFFFF, CLASS_NNORM), - ("neg_subnorm_min", 0x80000001, CLASS_NSUBNORM), - ("neg_subnorm_max", 0x807FFFFF, CLASS_NSUBNORM), - ("neg_zero", 0x80000000, CLASS_NZERO), - ("pos_zero", 0x00000000, CLASS_PZERO), - ("pos_subnorm_min", 0x00000001, CLASS_PSUBNORM), - ("pos_subnorm_max", 0x007FFFFF, CLASS_PSUBNORM), - ("pos_one", 0x3F800000, CLASS_PNORM), - ("pos_norm_min", 0x00800000, CLASS_PNORM), - ("pos_norm_max", 0x7F7FFFFF, CLASS_PNORM), - ("pos_inf", 0x7F800000, CLASS_PINF), -) - -# Hand-worked V_RNDNE_F32 expectations (binary32 bits in -> binary32 bits out). -RNDNE_HAND_WORKED = ( - ("pos_zero", 0x00000000, 0x00000000), - ("neg_zero", 0x80000000, 0x80000000), - ("pos_half", 0x3F000000, 0x00000000), # +0.5 -> +0.0 (even) - ("neg_half", 0xBF000000, 0x80000000), # -0.5 -> -0.0 (even, sign preserved) - ("pos_1_5", 0x3FC00000, 0x40000000), # +1.5 -> +2.0 (even) - ("neg_1_5", 0xBFC00000, 0xC0000000), # -1.5 -> -2.0 (even) - ("pos_2_5", 0x40200000, 0x40000000), # +2.5 -> +2.0 (even) - ("neg_2_5", 0xC0200000, 0xC0000000), # -2.5 -> -2.0 (even) - ("pos_3_5", 0x40600000, 0x40800000), # +3.5 -> +4.0 (even) - ("neg_3_5", 0xC0600000, 0xC0800000), # -3.5 -> -4.0 (even) - ("pos_4_5", 0x40900000, 0x40800000), # +4.5 -> +4.0 (even) - ("neg_4_5", 0xC0900000, 0xC0800000), # -4.5 -> -4.0 (even) - ("pos_half_minus_ulp", 0x3EFFFFFF, 0x00000000), - ("pos_half_plus_ulp", 0x3F000001, 0x3F800000), - ("neg_half_plus_ulp", 0xBEFFFFFF, 0x80000000), - ("neg_half_minus_ulp", 0xBF000001, 0xBF800000), - ("pos_1_5_minus_ulp", 0x3FBFFFFF, 0x3F800000), - ("pos_1_5_plus_ulp", 0x3FC00001, 0x40000000), - ("pos_2_5_minus_ulp", 0x401FFFFF, 0x40000000), - ("pos_2_5_plus_ulp", 0x40200001, 0x40400000), - ("pos_quarter", 0x3E800000, 0x00000000), - ("neg_quarter", 0xBE800000, 0x80000000), - ("pos_three_quarter", 0x3F400000, 0x3F800000), - ("neg_three_quarter", 0xBF400000, 0xBF800000), - ("pos_subnorm_min", 0x00000001, 0x00000000), - ("pos_subnorm_max", 0x007FFFFF, 0x00000000), - ("neg_subnorm_min", 0x80000001, 0x80000000), - ("neg_subnorm_max", 0x807FFFFF, 0x80000000), - ("pos_norm_min", 0x00800000, 0x00000000), - ("neg_norm_min", 0x80800000, 0x80000000), - ("pos_2p22_plus_half", 0x4A800001, 0x4A800000), # 4194304.5 -> 4194304.0 (even) - ("pos_2p22_plus_1_5", 0x4A800003, 0x4A800004), # 4194305.5 -> 4194306.0 (even) - ("neg_2p22_minus_half", 0xCA800001, 0xCA800000), # -4194304.5 -> -4194304.0 (even) - ("neg_2p22_minus_1_5", 0xCA800003, 0xCA800004), # -4194305.5 -> -4194306.0 (even) - ("pos_2p23_minus_half", 0x4AFFFFFF, 0x4B000000), # 8388607.5 -> 8388608.0 (even) - ("pos_2p23_plus_1", 0x4B000001, 0x4B000001), # 8388609.0 -> exact - ("neg_2p23_minus_1", 0xCB000001, 0xCB000001), # -8388609.0 -> exact - ("flt_max", 0x7F7FFFFF, 0x7F7FFFFF), - ("neg_flt_max", 0xFF7FFFFF, 0xFF7FFFFF), - ("pos_inf", 0x7F800000, 0x7F800000), - ("neg_inf", 0xFF800000, 0xFF800000), -) - -# Hand-worked V_RCP_IFLAG_F32 expectations (reference oracle only; excluded from spirv_mini_interp execution). -RCP_IFLAG_HAND_WORKED = ( - ("pos_one", 0x3F800000, 0x3F800000), # 1.0 -> 1.0 - ("neg_one", 0xBF800000, 0xBF800000), # -1.0 -> -1.0 - ("pos_two", 0x40000000, 0x3F000000), # 2.0 -> 0.5 - ("neg_two", 0xC0000000, 0xBF000000), # -2.0 -> -0.5 - ("pos_half", 0x3F000000, 0x40000000), # 0.5 -> 2.0 - ("neg_half", 0xBF000000, 0xC0000000), # -0.5 -> -2.0 - ("pos_four", 0x40800000, 0x3E800000), # 4.0 -> 0.25 - ("neg_quarter", 0xBE800000, 0xC0800000), # -0.25 -> -4.0 - ("pos_2p20", 0x49800000, 0x35800000), # 2^20 -> 2^-20 - ("neg_2pm20", 0xB5800000, 0xC9800000), # -2^-20 -> -2^20 - ("pos_1_5", 0x3FC00000, 0x3F2AAAAB), # 1.5 -> ~0.6666667 - ("neg_3_0", 0xC0400000, 0xBEAAAAAB), # -3.0 -> ~-0.33333334 - ("pos_zero", 0x00000000, 0x7F800000), # +0.0 -> +inf - ("neg_zero", 0x80000000, 0xFF800000), # -0.0 -> -inf - ("pos_inf", 0x7F800000, 0x00000000), # +inf -> +0.0 - ("neg_inf", 0xFF800000, 0x80000000), # -inf -> -0.0 - ("pos_qnan", 0x7FC00000, 0x7FC00000), # qNaN -> qNaN - ("pos_snan", 0x7F800001, 0x7FC00000), # sNaN -> qNaN -) - - -# ----------------------------------------------------------------------------- -# Translation & Execution Helpers -# ----------------------------------------------------------------------------- - -_TMP_DIR = None -_PS_PATH = None -_CS_PATH = None -_CS_FSSM = None - - -def _make_fssm(rsrc2: int, group: tuple[int, int, int]) -> bytes: - header = bytearray(0x148) - struct.pack_into("<4I", header, 0x138, rsrc2, *group) - return bytes(header) - - -def setUpModule(): - global _TMP_DIR, _PS_PATH, _CS_PATH, _CS_FSSM - _TMP_DIR = tempfile.TemporaryDirectory() - disasm_dir = os.path.join(_TMP_DIR.name, "disasm") - fssm_dir = os.path.join(_TMP_DIR.name, "fssm") - os.mkdir(disasm_dir) - os.mkdir(fssm_dir) - _PS_PATH = os.path.join(disasm_dir, "ps_valu_f32_class_rndne.s") - _CS_PATH = os.path.join(disasm_dir, "cs_valu_f32_class_rndne.s") - _CS_FSSM = os.path.join(fssm_dir, "cs_valu_f32_class_rndne.fssm") - with open(os.path.join(_TMP_DIR.name, "ps_valu_f32_class_rndne.dxbc"), "wb") as f: - f.write(STUB_DXBC) - - -def tearDownModule(): - global _TMP_DIR, _PS_PATH, _CS_PATH, _CS_FSSM - if _TMP_DIR is not None: - gc.collect() - _TMP_DIR.cleanup() - _TMP_DIR = None - _PS_PATH = None - _CS_PATH = None - _CS_FSSM = None - - -def translate_ps(lines: list[str]) -> str: - if _TMP_DIR is None: - setUpModule() - asm = "; test_valu_f32_class_rndne\n" + "".join(f"\t{ln}\n" for ln in lines) + "\ts_endpgm\n" - with open(_PS_PATH, "w", encoding="utf-8", newline="") as f: - f.write(asm) - with warnings.catch_warnings(): - warnings.simplefilter("ignore", ResourceWarning) - spv = rdna2spirv.translate(_PS_PATH) - gc.collect() - return spv - - -def run_ps_mrt0(lines: list[str], regs: tuple[str, str, str, str] = ("v0", "v0", "v0", "v0")) -> tuple[int, ...]: - spv = translate_ps(list(lines) + [f"exp mrt0 {', '.join(regs)} done vm"]) - out = si.run_fragment(spv) - if list(out) != ["%out_mrt0"]: - raise AssertionError(f"expected %out_mrt0 only; got {sorted(out)}") - return tuple(out["%out_mrt0"]) - - -def run_ps_raw(lines: list[str]) -> dict: - spv = translate_ps(lines) - return si.run_fragment(spv) - - -def run_cs(lines: list[str], group_size: int, subgroup_size: int, memory: dict[int, int]) -> dict[int, int]: - if _TMP_DIR is None: - setUpModule() - # rsrc2 = 0x0088: USER_SGPR = 4 (s[0:3] V#), TGID_X_EN = 1 (s4), TIDIG_COMP_CNT = 0 (v0 = local_id.x). - with open(_CS_FSSM, "wb") as f: - f.write(_make_fssm(0x0088, (group_size, 1, 1))) - asm = "; test_cs_valu_f32_class_rndne\n" + "".join(f"\t{ln}\n" for ln in lines) + "\ts_endpgm\n" - with open(_CS_PATH, "w", encoding="utf-8", newline="") as f: - f.write(asm) - with warnings.catch_warnings(): - warnings.simplefilter("ignore", ResourceWarning) - spv = rdna2spirv.translate(_CS_PATH) - gc.collect() - return si.run_workgroup( - spv, group_size, subgroup_size, - inputs_for=lambda i: {"%wg_id": (0, 0, 0), "%local_id": (i, 0, 0)}, - push_constants=VSHARP + [0] * 28, - memory=memory, - ) - - -class _Heap(dict): - """Flat memory initialized to HEAP_FILL for unwritten addresses.""" - - def get(self, key, default=None): - return super().get(key, HEAP_FILL) - - -# ----------------------------------------------------------------------------- -# Oracle Self-Tests -# ----------------------------------------------------------------------------- - -class OracleTests(unittest.TestCase): - """Independent hand-worked constants agree with the plain-Python ISA reference functions.""" - - def test_class_samples_each_match_exactly_one_bit(self): - self.assertEqual(len({bit for _, _, bit in CLASS_SAMPLES}), 10) - for name, x_bits, expected_bit in CLASS_SAMPLES: - with self.subTest(sample=name, bits=f"{x_bits:#010x}"): - self.assertEqual(f32_class_bit(x_bits), expected_bit) - for b in range(10): - self.assertEqual(ref_cmp_class_f32(x_bits, 1 << b), (1 << b) == expected_bit) - self.assertFalse(ref_cmp_class_f32(x_bits, 0)) - self.assertTrue(ref_cmp_class_f32(x_bits, ALL_CLASS_MASK)) - - def test_rndne_hand_worked_constants_match_reference(self): - for name, x_bits, want in RNDNE_HAND_WORKED: - with self.subTest(case=name, x=f"{x_bits:#010x}"): - self.assertEqual(ref_rndne_f32(x_bits), want) - - def test_rcp_iflag_hand_worked_constants_match_reference(self): - for name, x_bits, want in RCP_IFLAG_HAND_WORKED: - with self.subTest(case=name, x=f"{x_bits:#010x}"): - self.assertEqual(ref_rcp_iflag_f32(x_bits), want) - - -# ----------------------------------------------------------------------------- -# 1. v_cmp_class_f32 -# ----------------------------------------------------------------------------- - -class CmpClassF32Tests(unittest.TestCase): - def test_all_10_class_bits_exhaustive_matrix_e32_and_e64(self): - # Every sample x every single-bit mask (0..9) + mask 0 + 0x3FF, batched 4 per shader. - masks = [1 << b for b in range(10)] + [0, ALL_CLASS_MASK] - cases = [(name, x_bits, mask) for name, x_bits, _ in CLASS_SAMPLES for mask in masks] - for form in ("e32", "e64"): - for start in range(0, len(cases), 4): - chunk = cases[start:start + 4] - lines = [] - expected = [] - for slot, (_, x_bits, mask) in enumerate(chunk): - dst = f"v{10 + slot}" - lines += [f"v_mov_b32 v1, {x_bits:#x}", f"v_mov_b32 v2, {mask:#x}"] - if form == "e32": - lines += ["v_cmp_class_f32_e32 vcc_lo, v1, v2", f"v_cndmask_b32_e32 {dst}, 0, 1, vcc_lo"] - else: - lines += ["v_cmp_class_f32_e64 s4, v1, v2", f"v_cndmask_b32_e64 {dst}, 0, 1, s4"] - expected.append(int(ref_cmp_class_f32(x_bits, mask))) - while len(expected) < 4: - lines.append(f"v_mov_b32 v{10 + len(expected)}, 0") - expected.append(0) - with self.subTest(form=form, batch=start // 4): - self.assertEqual(run_ps_mrt0(lines, ("v10", "v11", "v12", "v13")), tuple(expected)) - - def test_multi_bit_masks_and_ignored_upper_mask_bits(self): - multi_masks = [ - 0x000, # none - 0x3FF, # all 10 classes - 0x003, # any NaN (sNaN | qNaN) - 0x204, # any Inf (-inf | +inf) - 0x060, # any zero (-0.0 | +0.0) - 0x090, # any subnormal (-subnorm | +subnorm) - 0x108, # any normal (-norm | +norm) - 0x1E0, # non-negative finite (+0 | +subnorm | +norm) - 0x03C, # negative non-NaN (-inf | -norm | -subnorm | -0) - 0x207, # non-finite (NaNs | Infs) - 0xFFFFFC00, # upper bits [31:10] only -> always 0 - 0x80000100, # upper bit + +normal -> matches +normal only - ] - # Representative value from each of the 10 classes. - reps = [ - 0x7F800001, 0x7FC00000, 0xFF800000, 0xBF800000, 0x80000001, - 0x80000000, 0x00000000, 0x00000001, 0x3F800000, 0x7F800000, - ] - cases = [(x_bits, m) for x_bits in reps for m in multi_masks] - for start in range(0, len(cases), 4): - chunk = cases[start:start + 4] - lines, expected = [], [] - for slot, (x_bits, mask) in enumerate(chunk): - dst = f"v{10 + slot}" - lines += [ - f"v_mov_b32 v1, {x_bits:#x}", - f"v_mov_b32 v2, {mask:#x}", - "v_cmp_class_f32_e64 s4, v1, v2", - f"v_cndmask_b32_e64 {dst}, 0, 1, s4", - ] - expected.append(int(ref_cmp_class_f32(x_bits, mask))) - while len(expected) < 4: - lines.append(f"v_mov_b32 v{10 + len(expected)}, 0") - expected.append(0) - with self.subTest(batch=start // 4): - self.assertEqual(run_ps_mrt0(lines, ("v10", "v11", "v12", "v13")), tuple(expected)) - - def test_encodings_inline_constants_sgprs_and_modifiers(self): - # 2-arg _e32 (implicit vcc), bare mnemonic, inline float/int constants, SGPR src0/src1, and wave64 s[4:5]. - got = run_ps_mrt0([ - "v_mov_b32 v1, 0x3f800000", # +1.0 (+normal) - "v_mov_b32 v2, 0x100", - "v_cmp_class_f32_e32 v1, v2", # 2-operand form writes %vcc - "v_cndmask_b32_e32 v10, 0, 1, vcc_lo", - "v_cmp_class_f32 vcc_lo, -0.0, 32", # bare mnemonic, inline -0.0 and mask 32 (-0.0) - "v_cndmask_b32_e32 v11, 0, 1, vcc_lo", - "s_mov_b32 s5, 0x80000001", # -subnormal in SGPR - "s_mov_b32 s6, 0x010", - "v_cmp_class_f32_e64 s4, s5, s6", - "v_cndmask_b32_e64 v12, 0, 1, s4", - "v_cmp_class_f32_e64 vcc_lo, 0.5, -1", # inline 0.5 & -1 (all 10 class bits) - "v_cndmask_b32_e32 v13, 0, 1, vcc_lo", - ], ("v10", "v11", "v12", "v13")) - self.assertEqual(got, (1, 1, 1, 1)) - - # Source modifiers (-, |..|, -|..|) apply before classification on non-sNaN values. - mod_cases = [ - (0x80000000, "|v1|", CLASS_PZERO, 1), # |-0.0| -> +0.0 - (0x80000000, "|v1|", CLASS_NZERO, 0), - (0x00000000, "-v1", CLASS_NZERO, 1), # -(+0.0) -> -0.0 - (0xFF800000, "-v1", CLASS_PINF, 1), # -(-inf) -> +inf - (0x7F800000, "-|v1|", CLASS_NINF, 1), # -|+inf| -> -inf - (0x80000001, "|v1|", CLASS_PSUBNORM, 1), # |-subnorm| -> +subnorm - (0x00000001, "-v1", CLASS_NSUBNORM, 1), # -(+subnorm) -> -subnorm - (0x3F800000, "-v1", CLASS_NNORM, 1), # -(+1.0) -> -1.0 - (0xFFC00000, "|v1|", CLASS_QNAN, 1), # |-qNaN| -> qNaN - ] - for x_bits, src_expr, mask, want in mod_cases: - with self.subTest(x=f"{x_bits:#010x}", src=src_expr, mask=hex(mask)): - res = run_ps_mrt0([ - f"v_mov_b32 v1, {x_bits:#x}", - f"v_mov_b32 v2, {mask:#x}", - f"v_cmp_class_f32_e64 s4, {src_expr}, v2", - "v_cndmask_b32_e64 v0, 0, 1, s4", - ])[0] - self.assertEqual(res, want) - - # Wave64 s[4:5] and vcc destinations. - w64 = run_ps_mrt0([ - "s_mov_b64 exec, -1", - "v_mov_b32 v1, 0x7f800000", # +inf - "v_mov_b32 v2, 0x200", - "v_cmp_class_f32_e64 s[4:5], v1, v2", - "v_cndmask_b32_e64 v10, 0, 1, s[4:5]", - "v_cmp_class_f32_e32 vcc, 0x7f800000, v2", - "v_cndmask_b32_e32 v11, 0, 1, vcc", - "v_mov_b32 v12, 0", - "v_mov_b32 v13, 0", - ], ("v10", "v11", "v12", "v13")) - self.assertEqual(w64, (1, 1, 0, 0)) - - def test_inactive_exec_lane_writes_zero_to_mask_dst(self): - # Hardware VOPC rule: inactive lanes write 0 into the destination mask even when operands match. - got = run_ps_mrt0([ - "v_mov_b32 v1, 0x3f800000", # +1.0 (+normal) - "v_mov_b32 v2, 0x100", # matches +normal when active - "s_mov_b32 vcc_lo, -1", # pre-fill with all-1s; must be cleared to 0 - "s_mov_b32 s4, -1", - "s_mov_b32 exec_lo, 0", # disable lane BEFORE cmp_class - "v_cmp_class_f32_e32 vcc_lo, v1, v2", - "v_cmp_class_f32_e64 s4, v1, v2", - "s_mov_b32 exec_lo, -1", - "v_cndmask_b32_e32 v10, 0, 1, vcc_lo", - "v_cndmask_b32_e64 v11, 0, 1, s4", - "v_mov_b32 v12, 0", - "v_mov_b32 v13, 0", - ], ("v10", "v11", "v12", "v13")) - self.assertEqual(got, (0, 0, 0, 0)) - - -# ----------------------------------------------------------------------------- -# 2. v_cmpx_class_f32 -# ----------------------------------------------------------------------------- - -class CmpxClassF32Tests(unittest.TestCase): - def test_single_lane_exec_update_vcc_preservation_and_kill(self): - # Matching lane keeps EXEC active and preserves VCC; non-matching lane disables EXEC and preserves v0. - for mnemonic in ("v_cmpx_class_f32_e32", "v_cmpx_class_f32_e64", "v_cmpx_class_f32"): - with self.subTest(mnemonic=mnemonic, match=True): - got = run_ps_mrt0([ - "s_mov_b32 vcc_lo, -1", - "v_mov_b32 v0, 0x11111111", - "v_mov_b32 v1, 0x7fc00000", # qNaN - "v_mov_b32 v2, 0x002", - f"{mnemonic} v1, v2", # matches -> EXEC stays 1, VCC stays -1 - "v_cndmask_b32_e32 v0, 0x22222222, 0x33333333, vcc_lo", - "s_mov_b32 exec_lo, -1", - ])[0] - self.assertEqual(got, 0x33333333) - - with self.subTest(mnemonic=mnemonic, match=False): - got = run_ps_mrt0([ - "s_mov_b32 vcc_lo, -1", - "v_mov_b32 v0, 0x11111111", - "v_mov_b32 v1, 0x80000000", # -0.0 - "v_mov_b32 v2, 0x040", # +0.0 only -> mismatch - f"{mnemonic} v1, v2", # clears EXEC, must NOT alter VCC - "v_mov_b32 v0, 0x99999999", # masked out while EXEC == 0 - "s_mov_b32 exec_lo, -1", - "v_cndmask_b32_e32 v10, 0x44, 0x55, vcc_lo", - ], ("v0", "v10", "v0", "v10")) - self.assertEqual(got, (0x11111111, 0x55, 0x11111111, 0x55)) - - # Without restoring EXEC before exp/s_endpgm, a non-matching PS lane executes OpKill -> {}. - self.assertEqual(run_ps_raw([ - "v_mov_b32 v1, 0x80000000", - "v_mov_b32 v2, 0x040", - "v_cmpx_class_f32_e32 v1, v2", - "exp mrt0 v0, v0, v0, v0 done vm", - ]), {}) - self.assertEqual(run_ps_raw([ - "v_mov_b32 v0, 0x12345678", - "v_mov_b32 v1, 0x80000000", - "v_mov_b32 v2, 0x020", - "v_cmpx_class_f32_e32 v1, v2", - "exp mrt0 v0, v0, v0, v0 done vm", - ]), {"%out_mrt0": (0x12345678,) * 4}) - - def test_single_lane_intersects_exec_and_supports_source_modifiers(self): - # A pre-disabled lane MUST stay disabled even when v_cmpx_class_f32 matches. - got = run_ps_mrt0([ - "v_mov_b32 v0, 0xAAAAAAAA", - "v_mov_b32 v1, 0x7f800000", # +inf - "v_mov_b32 v2, 0x200", # +inf mask - "s_mov_b32 exec_lo, 0", - "v_cmpx_class_f32_e64 v1, v2", - "v_mov_b32 v0, 0xBBBBBBBB", # must NOT write - "s_mov_b32 exec_lo, -1", - ])[0] - self.assertEqual(got, 0xAAAAAAAA) - - # VOP3 source modifiers: |-0.0| matches +0.0 (0x040). - got_mod = run_ps_mrt0([ - "v_mov_b32 v0, 0x11111111", - "v_mov_b32 v1, 0x80000000", - "v_mov_b32 v2, 0x040", - "v_cmpx_class_f32_e64 |v1|, v2", - "v_mov_b32 v0, 0x22222222", - "s_mov_b32 exec_lo, -1", - ])[0] - self.assertEqual(got_mod, 0x22222222) - - def test_multilane_exec_masking_intersection_and_vcc_preservation(self): - # 16 lanes in lockstep: lanes 0..11 hold distinct floats covering all 10 IEEE-754 classes; - # lanes 12..15 hold matching values too, but lane 0 and lane 15 are disabled BEFORE v_cmpx_class_f32. - # Stage 1 (e32): keep {sNaN, qNaN, -inf, -subnorm, -0.0, +0.0, +inf} = 0x277. - # Stage 2 (e64): narrow further to {qNaN, -0.0, +0.0, +inf} = 0x262. - # VCC is set beforehand for odd lanes (`(lane & 1) != 0`): active surviving lanes write 0x22 (VCC=1) - # or 0x11 (VCC=0), while dropped or pre-disabled lanes leave memory at HEAP_FILL (0xEEEEEEEE). - lane_inputs = [ - 0x7FC00000, # lane 0: +qNaN (matches both, BUT pre-disabled -> must NOT write) - 0x7F800001, # lane 1: +sNaN (matches stage 1, dropped by stage 2) - 0x7FC00000, # lane 2: +qNaN (survives both, even -> 0x11) - 0xFF800000, # lane 3: -inf (matches stage 1, dropped by stage 2) - 0xBF800000, # lane 4: -1.0 (-normal, dropped by stage 1) - 0x80000001, # lane 5: -subnorm (matches stage 1, dropped by stage 2) - 0x80000000, # lane 6: -0.0 (survives both, even -> 0x11) - 0x00000000, # lane 7: +0.0 (survives both, odd -> 0x22) - 0x00000001, # lane 8: +subnorm (dropped by stage 1) - 0x3F800000, # lane 9: +1.0 (+normal, dropped by stage 1) - 0x7F800000, # lane 10: +inf (survives both, even -> 0x11) - 0xFFC00000, # lane 11: -qNaN (survives both, odd -> 0x22) - 0xFF800001, # lane 12: -sNaN (dropped by stage 2) - 0x7F800000, # lane 13: +inf (survives both, odd -> 0x22) - 0x80000000, # lane 14: -0.0 (survives both, even -> 0x11) - 0x7FC00000, # lane 15: +qNaN (matches both, BUT pre-disabled -> must NOT write) - ] - mask1 = CLASS_SNAN | CLASS_QNAN | CLASS_NINF | CLASS_NSUBNORM | CLASS_NZERO | CLASS_PZERO | CLASS_PINF # 0x277 - mask2 = CLASS_QNAN | CLASS_NZERO | CLASS_PZERO | CLASS_PINF # 0x262 - - mem = _Heap({0x100 + 4 * i: w for i, w in enumerate(lane_inputs)}) - run_cs([ - "v_lshlrev_b32_e32 v5, 2, v0", - "v_add_nc_u32_e32 v6, 0x100, v5", - "buffer_load_dword v1, v6, s[0:3], 0 offen", - f"v_mov_b32_e32 v2, {mask1:#x}", - f"v_mov_b32_e32 v7, {mask2:#x}", - "v_and_b32_e32 v8, 1, v0", - "v_cmp_ne_u32_e32 vcc_lo, 0, v8", # VCC = 1 on odd lanes; must survive both cmpx - "v_cmpx_ne_u32_e32 0, v0", # disable lane 0 - "v_cmpx_ne_u32_e32 15, v0", # disable lane 15 - "v_cmpx_class_f32_e32 v1, v2", - "v_cmpx_class_f32_e64 v1, v7", - "v_mov_b32_e32 v3, 0x11", - "v_mov_b32_e32 v4, 0x22", - "v_cndmask_b32_e32 v9, v3, v4, vcc_lo", - "buffer_store_dword v9, v5, s[0:3], 0 offen", - ], group_size=16, subgroup_size=32, memory=mem) - - got = [mem.get(4 * i) for i in range(16)] - want = [] - for lane, x_bits in enumerate(lane_inputs): - active = (lane not in (0, 15)) and ref_cmp_class_f32(x_bits, mask1) and ref_cmp_class_f32(x_bits, mask2) - want.append((0x22 if (lane & 1) else 0x11) if active else HEAP_FILL) - self.assertEqual(got, want) - self.assertEqual(got, [ - HEAP_FILL, HEAP_FILL, 0x11, HEAP_FILL, - HEAP_FILL, HEAP_FILL, 0x11, 0x22, - HEAP_FILL, HEAP_FILL, 0x11, 0x22, - HEAP_FILL, 0x22, 0x11, HEAP_FILL, - ]) - - def test_wave64_multilane_cmpx_class_updates_all_64_lanes(self): - # 64-lane Wave64 compute run verifying both low half (lanes 0..31) and high half (lanes 32..63). - lane_inputs = [CLASS_SAMPLES[i % len(CLASS_SAMPLES)][1] for i in range(64)] - mask = CLASS_SNAN | CLASS_NSUBNORM | CLASS_PINF # 0x211 - mem = _Heap({0x200 + 4 * i: w for i, w in enumerate(lane_inputs)}) - run_cs([ - "s_mov_b64 exec, -1", # WAVE64_RE marker -> wave64 mode - "v_lshlrev_b32_e32 v5, 2, v0", - "v_add_nc_u32_e32 v6, 0x200, v5", - "buffer_load_dword v1, v6, s[0:3], 0 offen", - f"v_mov_b32_e32 v2, {mask:#x}", - "v_cmpx_class_f32_e32 v1, v2", - "v_add_nc_u32_e32 v3, 0x100, v0", - "buffer_store_dword v3, v5, s[0:3], 0 offen", - ], group_size=64, subgroup_size=64, memory=mem) - - got = [mem.get(4 * i) for i in range(64)] - want = [(0x100 + i) if ref_cmp_class_f32(x_bits, mask) else HEAP_FILL for i, x_bits in enumerate(lane_inputs)] - self.assertEqual(got, want) - - -# ----------------------------------------------------------------------------- -# 3. v_rndne_f32 -# ----------------------------------------------------------------------------- - -class RndneF32Tests(unittest.TestCase): - def test_edge_values_e32_e64_and_bare(self): - for suffix in ("_e32", "_e64", ""): - for start in range(0, len(RNDNE_HAND_WORKED), 4): - chunk = RNDNE_HAND_WORKED[start:start + 4] - lines, expected = [], [] - for slot, (_, x_bits, want) in enumerate(chunk): - dst = f"v{10 + slot}" - lines += [f"v_mov_b32 v1, {x_bits:#x}", f"v_rndne_f32{suffix} {dst}, v1"] - expected.append(want) - while len(expected) < 4: - lines.append(f"v_mov_b32 v{10 + len(expected)}, 0") - expected.append(0) - with self.subTest(suffix=suffix or "bare", batch=start // 4): - got = run_ps_mrt0(lines, ("v10", "v11", "v12", "v13")) - self.assertEqual(got, tuple(expected), - f"got {[hex(w) for w in got]}, want {[hex(w) for w in expected]}") - - def test_nan_inputs_preserve_nan(self): - nan_words = (0x7FC00000, 0xFFC00000, 0x7FC12345, 0x7F800001, 0xFF800001) - for suffix in ("_e32", "_e64"): - for x_bits in nan_words: - with self.subTest(suffix=suffix, x=f"{x_bits:#010x}"): - got = run_ps_mrt0([f"v_mov_b32 v1, {x_bits:#x}", f"v_rndne_f32{suffix} v0, v1"])[0] - self.assertTrue(is_f32_nan_bits(got), f"expected NaN, got {got:#010x}") - - def test_modifiers_inline_constants_sgpr_aliasing_and_exec(self): - # Source modifiers (-v1, |v1|, -|v1|) and output modifiers (clamp, mul:2, mul:4, div:2). - got_mods = run_ps_mrt0([ - "v_mov_b32 v1, 0x40200000", # +2.5 - "v_mov_b32 v2, 0xc0200000", # -2.5 - "v_mov_b32 v3, 0x3fc00000", # +1.5 -> rndne = 2.0 - "v_rndne_f32_e64 v10, -v1", # rndne(-2.5) = -2.0 - "v_rndne_f32_e64 v11, |v2|", # rndne(2.5) = 2.0 - "v_rndne_f32_e64 v12, -|v1| clamp", # max(min(-2.0, 1.0), 0.0) = 0.0 - "v_rndne_f32_e64 v13, v3 mul:2", # 2.0 * 2 = 4.0 - ], ("v10", "v11", "v12", "v13")) - self.assertEqual(got_mods, (f32_bits(-2.0), f32_bits(2.0), f32_bits(0.0), f32_bits(4.0))) - - got_mods2 = run_ps_mrt0([ - "v_mov_b32 v1, 0x3fc00000", # +1.5 -> rndne = 2.0 - "v_mov_b32 v2, 0x3ecccccd", # ~0.4 -> rndne = +0.0 - "v_rndne_f32_e64 v10, v1 mul:4", # 2.0 * 4 = 8.0 - "v_rndne_f32_e64 v11, v1 div:2", # 2.0 * 0.5 = 1.0 - "v_rndne_f32_e64 v12, v2 mul:2 clamp", # 0.0 - "v_rndne_f32_e64 v13, v1 clamp", # clamp(2.0, 0, 1) = 1.0 - ], ("v10", "v11", "v12", "v13")) - self.assertEqual(got_mods2, (f32_bits(8.0), f32_bits(1.0), f32_bits(0.0), f32_bits(1.0))) - - # Inline float constants, SGPR source, dst aliasing (v0, v0), and inactive EXEC lane preservation. - got_misc = run_ps_mrt0([ - "v_rndne_f32_e32 v10, -0.5", # inline -0.5 -> -0.0 - "s_mov_b32 s4, 0xbf000000", # -0.5 in SGPR - "v_rndne_f32_e32 v11, s4", - "v_mov_b32 v12, 0xc0600000", # -3.5 - "v_rndne_f32_e64 v12, v12", # aliases source -> -4.0 - "v_mov_b32 v13, 0xdeadbeef", - "s_mov_b32 exec_lo, 0", - "v_rndne_f32_e32 v13, 1.0", # inactive lane: must keep 0xdeadbeef - "s_mov_b32 exec_lo, -1", - ], ("v10", "v11", "v12", "v13")) - self.assertEqual(got_misc, (0x80000000, 0x80000000, f32_bits(-4.0), 0xDEADBEEF)) - - -# ----------------------------------------------------------------------------- -# 4. v_rcp_iflag_f32 -# ----------------------------------------------------------------------------- - -class RcpIflagF32OracleAndTranslationTests(unittest.TestCase): - """Checks the translation of v_rcp_iflag_f32 and executes it with source and output modifiers. - - See module docstring, finding 1: exact (power-of-two) inputs only, and no zero operand. - """ - - def test_executes_with_output_modifiers(self): - got = run_ps_mrt0([ - "v_mov_b32 v1, 0x40000000", # +2.0 - "v_rcp_iflag_f32_e64 v10, v1 mul:2", # 0.5 * 2 = 1.0 - "v_rcp_iflag_f32_e64 v11, v1 mul:4", # 0.5 * 4 = 2.0 - "v_rcp_iflag_f32_e64 v12, v1 div:2", # 0.5 / 2 = 0.25 - "v_rcp_iflag_f32_e64 v13, -v1 clamp", # clamp(-0.5, 0, 1) = +0.0 - ], ("v10", "v11", "v12", "v13")) - self.assertEqual(got, (f32_bits(1.0), f32_bits(2.0), f32_bits(0.25), f32_bits(0.0))) - - got2 = run_ps_mrt0([ - "v_mov_b32 v1, 0x3e800000", # +0.25 - "v_rcp_iflag_f32_e64 v10, v1 clamp", # clamp(4.0, 0, 1) = 1.0 - "v_rcp_iflag_f32_e64 v11, -|v1|", # -4.0 - "v_rcp_iflag_f32_e64 v12, v1 div:2 clamp", # clamp(2.0, 0, 1) = 1.0 - "v_rcp_iflag_f32_e32 v13, v1", # 4.0, no modifiers - ], ("v10", "v11", "v12", "v13")) - self.assertEqual(got2, (f32_bits(1.0), f32_bits(-4.0), f32_bits(1.0), f32_bits(4.0))) - for x_bits, want in ((0x40000000, 0x3F000000), (0x3E800000, 0x40800000), (0xC0000000, 0xBF000000)): - with self.subTest(x=f"{x_bits:#010x}"): - self.assertEqual(ref_rcp_iflag_f32(x_bits), want) - - def test_dropping_output_modifiers_is_detected(self): - # Negative control: if the translator stopped applying the modifier, mul:2 would read back 0.5, not 1.0. - good = translate_ps(["v_mov_b32 v1, 0x40000000", "v_rcp_iflag_f32_e64 v0, v1 mul:2", - "exp mrt0 v0, v0, v0, v0 done vm"]) - self.assertEqual(si.run_fragment(good)["%out_mrt0"][0], f32_bits(1.0)) - bad, n = re.subn(r"^(\s*%\w+) = OpFMul %float (%\w+) %\w+$", r"\1 = OpFMul %float \2 %f1", good, - count=1, flags=re.M) - self.assertEqual(n, 1) - self.assertNotEqual(si.run_fragment(bad)["%out_mrt0"][0], f32_bits(1.0)) - - def test_translates_to_op_fdiv_with_no_contraction(self): - for line in ( - "v_rcp_iflag_f32_e32 v0, v1", - "v_rcp_iflag_f32_e64 v0, v1", - "v_rcp_iflag_f32 v0, v1", - "v_rcp_iflag_f32_e64 v0, -|s4|", - "v_rcp_iflag_f32_e32 v0, 2.0", - ): - with self.subTest(line=line): - spv = translate_ps([ - "v_mov_b32 v1, 0x40000000", - "s_mov_b32 s4, 0xbf800000", - line, - "exp mrt0 v0, v0, v0, v0 done vm", - ]) - m = re.search(r"^\s*(%\w+) = OpFDiv %float %f1 %\w+$", spv, re.M) - self.assertIsNotNone(m, f"expected OpFDiv %float %f1 in translated SPIR-V for {line!r}") - self.assertIn(f"OpDecorate {m.group(1)} NoContraction", spv) - - -# ----------------------------------------------------------------------------- -# 5. Negative Controls (SPIR-V sabotage detection) -# ----------------------------------------------------------------------------- - -class NegativeControlsTests(unittest.TestCase): - def test_sabotaged_spirv_is_detected(self): - # 1. v_cmp_class_f32: inverting quiet NaN bit check (UGreaterThanEqual -> ULessThan) swaps sNaN and qNaN. - good_cls = translate_ps([ - "v_mov_b32 v1, 0x7f800001", # +sNaN - "v_mov_b32 v2, 0x001", # CLASS_SNAN - "v_cmp_class_f32_e32 vcc_lo, v1, v2", - "v_cndmask_b32_e32 v0, 0, 1, vcc_lo", - "exp mrt0 v0, v0, v0, v0 done vm", - ]) - self.assertEqual(si.run_fragment(good_cls)["%out_mrt0"][0], 1) - bad_cls, n = re.subn(r"OpUGreaterThanEqual %bool (%\w+) %c400000", - r"OpULessThan %bool \1 %c400000", good_cls) - self.assertEqual(n, 1) - self.assertNotEqual(si.run_fragment(bad_cls)["%out_mrt0"][0], 1) - - # 2. v_cmpx_class_f32: replacing active intersection AND with OR reactivates a pre-disabled lane. - good_cmpx = translate_ps([ - "v_mov_b32 v0, 0xAAAAAAAA", - "v_mov_b32 v1, 0x3f800000", - "v_mov_b32 v2, 0x100", - "s_mov_b32 exec_lo, 0", - "v_cmpx_class_f32_e32 v1, v2", - "v_mov_b32 v0, 0xBBBBBBBB", - "s_mov_b32 exec_lo, -1", - "exp mrt0 v0, v0, v0, v0 done vm", - ]) - self.assertEqual(si.run_fragment(good_cmpx)["%out_mrt0"][0], 0xAAAAAAAA) - # Sabotage the final `acc = acc & active` right before `OpStore %active`. - bad_cmpx, n = re.subn( - r"(%\w+) = OpLogicalAnd %bool (%\w+) (%\w+)\s*\n\s*OpStore %active \1", - r"\1 = OpLogicalOr %bool \2 \3\n OpStore %active \1", - good_cmpx, - ) - self.assertEqual(n, 1) - self.assertNotEqual(si.run_fragment(bad_cmpx)["%out_mrt0"][0], 0xAAAAAAAA) - - # 3. v_rndne_f32: replacing RoundEven with Trunc breaks tie-to-even (2.5 -> 2.0) and -0.5 (-0.0). - good_rnd = translate_ps([ - "v_mov_b32 v1, 0x3fc00000", # +1.5 -> 2.0 (Trunc gives 1.0) - "v_rndne_f32_e32 v0, v1", - "exp mrt0 v0, v0, v0, v0 done vm", - ]) - self.assertEqual(si.run_fragment(good_rnd)["%out_mrt0"][0], f32_bits(2.0)) - bad_rnd, n = re.subn(r"OpExtInst %float %glsl RoundEven", "OpExtInst %float %glsl Trunc", good_rnd) - self.assertEqual(n, 1) - self.assertNotEqual(si.run_fragment(bad_rnd)["%out_mrt0"][0], f32_bits(2.0)) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_valu_f32_min3_max3_mad.py b/tests/semantic/test_valu_f32_min3_max3_mad.py deleted file mode 100644 index 58d06bbd9..000000000 --- a/tests/semantic/test_valu_f32_min3_max3_mad.py +++ /dev/null @@ -1,1011 +0,0 @@ -"""Semantic value tests for 3-input f32 VALU ops: - v_min3_f32 D = min(S0, S1, S2) - v_max3_f32 D = max(S0, S1, S2) - v_mad_f32 D = f32(f32(S0 * S1) + S2) (unfused, NoContraction) - v_fmac_f32 D = fma(S0, S1, D) (fused, accumulates into vdst) - v_mad_legacy_f32 D = f32(legacy_mul(S0, S1) + S2) (0 * anything -> +0.0, unfused) - -Each test builds a hand-written RDNA2 pixel or compute shader listing, translates it with tools/rdna2spirv.py, -executes the SPIR-V in tests/semantic/spirv_mini_interp.py, and compares the result words against an independent -plain-Python IEEE-754 binary32 / RDNA2 ISA reference oracle (stdlib only, no game data). - -Observed translator / interpreter findings (kept out of failing assertions and documented here): - 1. v_min3_f32 / v_max3_f32 with NaN operands: tools/rdna2spirv.py emits GLSL.std.450 NMin / NMax, which give the - other operand for a NaN, as RDNA2 hardware does. Those rows are asserted in tests/semantic/ - test_float_nan_fract.py; NaN inputs stay out of the value assertions here (clamp-on-NaN is still FClamp, which - spirv_mini_interp.py rejects). NaN semantics are tested on v_mad_f32, v_fmac_f32, and v_mad_legacy_f32. - 2. v_min3_f32 / v_max3_f32 signed-zero ties: RDNA2 hardware orders -0.0 below +0.0 (measured on an AMD Radeon - RX 6800: min(+0, -0) = -0 and max(+0, -0) = +0 in either operand order), and spirv_mini_interp.py's NMin / NMax - do the same, so every zero triple asserts exact bit patterns. - 3. Fma double-rounding in spirv_mini_interp.py: spirv_mini_interp.py implements GLSL.std.450 Fma as Python - binary64 `f32(x * y + z)`. Binary32 products require at most 48 <= 53 significand bits and never overflow - binary64, so intermediate rounding differences vs unfused v_mad_f32 are modeled accurately except for extreme - exponent-gap (>53-bit) midpoint ties (e.g. 2^30*(1+3*2^-12) * 2^30*(1+2^-12) - 2^-10), which double-round. -""" -from __future__ import annotations - -from fractions import Fraction -import gc -import itertools -import math -import os -import re -import struct -import sys -import tempfile -import unittest -import warnings - -HERE = os.path.dirname(os.path.abspath(__file__)) -ROOT = os.path.dirname(os.path.dirname(HERE)) -TOOLS_DIR = os.environ.get("LEONIDA_TOOLS_DIR") or os.path.join(ROOT, "tools") - -sys.dont_write_bytecode = True -if TOOLS_DIR not in sys.path: - sys.path.insert(0, TOOLS_DIR) -if HERE not in sys.path: - sys.path.insert(0, HERE) - -import rdna2spirv # noqa: E402 -import spirv_mini_interp as si # noqa: E402 - -MASK32 = 0xFFFFFFFF -STUB_DXBC = b"DXBC" + bytes(24) + struct.pack(" float: - return struct.unpack(" int: - try: - return struct.unpack(" 0 else NEG_INF - - -def is_nan_bits(bits: int) -> bool: - bits &= MASK32 - return (bits & 0x7F800000) == 0x7F800000 and (bits & 0x007FFFFF) != 0 - - -def exact_f32_to_fraction(bits: int) -> Fraction: - """Decode a finite binary32 bit pattern into an exact rational Fraction.""" - bits &= MASK32 - sign = -1 if (bits >> 31) else 1 - exp = (bits >> 23) & 0xFF - frac = bits & 0x7FFFFF - if exp == 0xFF: - raise ValueError(f"non-finite bits {bits:#010x}") - if exp == 0: - return Fraction(sign * frac, 1 << 149) - mant = (1 << 23) | frac - shift = exp - 150 - if shift >= 0: - return Fraction(sign * (mant << shift), 1) - return Fraction(sign * mant, 1 << (-shift)) - - -def round_fraction_to_f32_bits(val: Fraction, zero_sign: int = 0) -> int: - """Round an exact Fraction to IEEE-754 binary32 (round-to-nearest-even).""" - if val == 0: - return NEG_ZERO if zero_sign else POS_ZERO - sign = 1 if val < 0 else 0 - aval = -val if sign else val - num, den = aval.numerator, aval.denominator - # Binary exponent floor(log2(aval)): - e = num.bit_length() - den.bit_length() - if (num << max(0, -e)) < (den << max(0, e)): - e -= 1 - - if e >= 128: - return (sign << 31) | POS_INF - - # Scale to integer significand q with 1-ulp unit = 2^shift_exp. - if e < -126: - # Subnormal range: quantum is 2^-149 - target_shift = 149 - else: - # Normal range: quantum is 2^(e - 23) - target_shift = 23 - e - - if target_shift >= 0: - scaled_num = num << target_shift - else: - scaled_num = num - den = den << (-target_shift) - - q, rem = divmod(scaled_num, den) - twice_rem = rem << 1 - if twice_rem > den or (twice_rem == den and (q & 1)): - q += 1 - - if e < -126: - if q >= (1 << 23): - # Rounded up into smallest normal (exp=1, frac=0) - return (sign << 31) | (1 << 23) - return (sign << 31) | q - - if q >= (1 << 24): - q >>= 1 - e += 1 - if e >= 128: - return (sign << 31) | POS_INF - - exp_field = e + 127 - frac_field = q & 0x7FFFFF - return (sign << 31) | (exp_field << 23) | frac_field - - -def _zero_sign_bit(bits: int) -> int: - return 1 if (bits & MASK32) == NEG_ZERO else 0 - - -def _zero_ordered(v: float): - """Sort key with -0.0 below +0.0, the order RDNA2 v_min/v_max use (measured on an AMD Radeon RX 6800: - min(+0, -0) = -0 and max(+0, -0) = +0 in either operand order; docs/design.md, float min/max/med3).""" - return (v, math.copysign(1.0, v)) - - -def ref_min3_f32(xb: int, yb: int, zb: int) -> int: - """Reference for v_min3_f32 = min(min(x, y), z) on non-NaN f32s, with -0.0 < +0.0.""" - x, y, z = bits_to_f32(xb), bits_to_f32(yb), bits_to_f32(zb) - if math.isnan(x) or math.isnan(y) or math.isnan(z): - raise ValueError("NaN operands are covered by tests/semantic/test_float_nan_fract.py") - return f32_to_bits(min((x, y, z), key=_zero_ordered)) - - -def ref_max3_f32(xb: int, yb: int, zb: int) -> int: - """Reference for v_max3_f32 = max(max(x, y), z) on non-NaN f32s, with -0.0 < +0.0.""" - x, y, z = bits_to_f32(xb), bits_to_f32(yb), bits_to_f32(zb) - if math.isnan(x) or math.isnan(y) or math.isnan(z): - raise ValueError("NaN operands are covered by tests/semantic/test_float_nan_fract.py") - return f32_to_bits(max((x, y, z), key=_zero_ordered)) - - -def _mul_bits_f32(xb: int, yb: int) -> int: - x, y = bits_to_f32(xb), bits_to_f32(yb) - if math.isnan(x) or math.isnan(y): - return QNAN - if (x == 0.0 and math.isinf(y)) or (math.isinf(x) and y == 0.0): - return QNAN - sign = ((xb ^ yb) >> 31) & 1 - if math.isinf(x) or math.isinf(y): - return (sign << 31) | POS_INF - if x == 0.0 or y == 0.0: - return NEG_ZERO if sign else POS_ZERO - return round_fraction_to_f32_bits(exact_f32_to_fraction(xb) * exact_f32_to_fraction(yb), zero_sign=sign) - - -def _add_bits_f32(ab: int, bb: int) -> int: - a, b = bits_to_f32(ab), bits_to_f32(bb) - if math.isnan(a) or math.isnan(b): - return QNAN - if math.isinf(a) and math.isinf(b): - if (ab >> 31) != (bb >> 31): - return QNAN - return ab & MASK32 - if math.isinf(a): - return ab & MASK32 - if math.isinf(b): - return bb & MASK32 - if a == 0.0 and b == 0.0: - # IEEE-754 RTN: (-0.0) + (-0.0) = -0.0; (+0.0) + (-0.0) = +0.0. - return NEG_ZERO if (_zero_sign_bit(ab) and _zero_sign_bit(bb)) else POS_ZERO - total = exact_f32_to_fraction(ab) + exact_f32_to_fraction(bb) - # Exact cancellation of non-zero opposites yields +0.0 under RTN. - return round_fraction_to_f32_bits(total, zero_sign=0) - - -def ref_mad_f32(xb: int, yb: int, zb: int) -> int: - """Unfused IEEE-754 binary32 multiply followed by binary32 add.""" - return _add_bits_f32(_mul_bits_f32(xb, yb), zb) - - -def ref_fmac_f32(xb: int, yb: int, accb: int) -> int: - """True IEEE-754 binary32 fused multiply-add: fma(x, y, acc).""" - x, y, acc = bits_to_f32(xb), bits_to_f32(yb), bits_to_f32(accb) - if math.isnan(x) or math.isnan(y) or math.isnan(acc): - return QNAN - if (x == 0.0 and math.isinf(y)) or (math.isinf(x) and y == 0.0): - return QNAN - prod_sign = ((xb ^ yb) >> 31) & 1 - if math.isinf(x) or math.isinf(y): - prod_inf = (prod_sign << 31) | POS_INF - return _add_bits_f32(prod_inf, accb) - if math.isinf(acc): - return accb & MASK32 - prod = exact_f32_to_fraction(xb) * exact_f32_to_fraction(yb) - total = prod + exact_f32_to_fraction(accb) - if total == 0: - # (-0.0) + (-0.0) -> -0.0 only if product is signed zero with sign=1 and acc is -0.0. - if (x == 0.0 or y == 0.0) and acc == 0.0 and prod_sign == 1 and _zero_sign_bit(accb) == 1: - return NEG_ZERO - return POS_ZERO - return round_fraction_to_f32_bits(total, zero_sign=0) - - -def ref_mad_legacy_f32(xb: int, yb: int, zb: int) -> int: - """RDNA2 v_mad_legacy_f32: 0 * anything (inf/NaN/-0) -> +0.0, then unfused binary32 add.""" - x, y = bits_to_f32(xb), bits_to_f32(yb) - if (not math.isnan(x) and x == 0.0) or (not math.isnan(y) and y == 0.0): - prod_bits = POS_ZERO - else: - prod_bits = _mul_bits_f32(xb, yb) - return _add_bits_f32(prod_bits, zb) - - -def apply_src_mod(bits: int, neg: bool = False, absm: bool = False) -> int: - """RDNA2 source modifier order: abs first, then neg (operates on sign bit, even for inf/NaN/0).""" - bits &= MASK32 - if absm: - bits &= 0x7FFFFFFF - if neg: - bits ^= 0x80000000 - return bits - - -def apply_out_mods(bits: int, omod: str | None = None, clamp: bool = False) -> int: - """RDNA2 output modifiers: mul:2 / mul:4 / div:2 applied before clamp [0.0, 1.0].""" - if omod is not None: - factor = {"mul:2": TWO, "mul:4": FOUR, "div:2": HALF}[omod] - bits = _mul_bits_f32(bits, factor) - if clamp: - v = bits_to_f32(bits) - if math.isnan(v): - raise ValueError("clamp on NaN is undefined in GLSL FClamp") - if v < 0.0: - return POS_ZERO - if v > 1.0: - return ONE - return bits & MASK32 - - -_TMP_DIR = None -_PS_PATH = None -_CS_PATH = None - - -def setUpModule(): - global _TMP_DIR, _PS_PATH, _CS_PATH - _TMP_DIR = tempfile.TemporaryDirectory() - disasm_dir = os.path.join(_TMP_DIR.name, "disasm") - fssm_dir = os.path.join(_TMP_DIR.name, "fssm") - os.mkdir(disasm_dir) - os.mkdir(fssm_dir) - _PS_PATH = os.path.join(disasm_dir, "ps_f32_valu3.s") - _CS_PATH = os.path.join(disasm_dir, "cs_f32_valu3.s") - with open(os.path.join(_TMP_DIR.name, "ps_f32_valu3.dxbc"), "wb") as f: - f.write(STUB_DXBC) - with open(os.path.join(fssm_dir, "cs_f32_valu3.fssm"), "wb") as f: - f.write(CS_FSSM_BYTES) - - -def tearDownModule(): - global _TMP_DIR, _PS_PATH, _CS_PATH - if _TMP_DIR is not None: - gc.collect() - _TMP_DIR.cleanup() - _TMP_DIR = None - _PS_PATH = None - _CS_PATH = None - - -def translate_ps(lines: list[str], export_regs: tuple[str, str, str, str] = ("v0", "v0", "v0", "v0")) -> str: - if _TMP_DIR is None: - setUpModule() - assert _PS_PATH is not None - asm = ( - "; test_valu_f32_min3_max3_mad\n" - + "".join(f"\t{ln}\n" for ln in lines) - + f"\texp mrt0 {', '.join(export_regs)} done vm\n" - + "\ts_endpgm\n" - ) - with open(_PS_PATH, "w", encoding="utf-8", newline="") as f: - f.write(asm) - with warnings.catch_warnings(): - warnings.simplefilter("ignore", ResourceWarning) - spv = rdna2spirv.translate(_PS_PATH) - gc.collect() - return spv - - -def run_ps_mrt0(lines: list[str], export_regs: tuple[str, str, str, str] = ("v0", "v0", "v0", "v0")) -> list[int]: - spv = translate_ps(lines, export_regs=export_regs) - return list(si.run_fragment(spv)["%out_mrt0"]) - - -def run_three_input(op: str, a_bits: int, b_bits: int, c_bits: int, mods: str = "") -> int: - """Translate and run a single 3-operand instruction (`v_min3_f32`, `v_max3_f32`, `v_mad_f32`, - `v_mad_legacy_f32`, or `v_fmac_f32` where `c_bits` initializes the `v0` accumulator).""" - mod_s = f" {mods}" if mods else "" - if op.startswith(("v_fmac_f32", "v_mac_f32", "v_mac_legacy_f32")): - lines = [ - f"v_mov_b32 v1, {a_bits & MASK32:#x}", - f"v_mov_b32 v2, {b_bits & MASK32:#x}", - f"v_mov_b32 v0, {c_bits & MASK32:#x}", - f"{op} v0, v1, v2{mod_s}", - ] - else: - lines = [ - f"v_mov_b32 v1, {a_bits & MASK32:#x}", - f"v_mov_b32 v2, {b_bits & MASK32:#x}", - f"v_mov_b32 v3, {c_bits & MASK32:#x}", - f"{op} v0, v1, v2, v3{mod_s}", - ] - return run_ps_mrt0(lines)[0] - - -def run_cs_workgroup_exec(lines: list[str], lanes: int = 4) -> dict[int, int]: - """Translate and run a compute shader storing `v1` per lane at byte address `4 * lane`.""" - if _TMP_DIR is None: - setUpModule() - assert _CS_PATH is not None - asm = "; test_valu_f32_min3_max3_mad_cs\n" + "".join(f"\t{ln}\n" for ln in lines) + "\ts_endpgm\n" - with open(_CS_PATH, "w", encoding="utf-8", newline="") as f: - f.write(asm) - with warnings.catch_warnings(): - warnings.simplefilter("ignore", ResourceWarning) - spv = rdna2spirv.translate(_CS_PATH) - gc.collect() - mem: dict[int, int] = {} - si.run_workgroup( - spv, - lanes, - 32, - inputs_for=lambda i: {"%local_id": (i, 0, 0), "%wg_id": (0, 0, 0)}, - push_constants=[0, 0, 64, 0x31016FAC] + [0] * 28, - memory=mem, - ) - return mem - - -class ReferenceOracleTests(unittest.TestCase): - """Cross-check plain-Python Fraction/IEEE-754 reference against hand-derived binary32 bit constants.""" - - def test_hand_worked_constants(self): - # v_min3_f32 / v_max3_f32 - self.assertEqual(ref_min3_f32(ONE, NEG_TWO, HALF), NEG_TWO) - self.assertEqual(ref_max3_f32(ONE, NEG_TWO, THREE), THREE) - self.assertEqual(ref_min3_f32(POS_INF, FLT_MAX, NEG_INF), NEG_INF) - self.assertEqual(ref_max3_f32(POS_INF, FLT_MAX, NEG_INF), POS_INF) - self.assertEqual(ref_min3_f32(NEG_ZERO, NEG_ZERO, ONE), NEG_ZERO) - self.assertEqual(ref_max3_f32(POS_ZERO, POS_ZERO, NEG_ONE), POS_ZERO) - - # Fused vs unfused divergence: (1 + 2^-20)*(1 - 2^-20) - 1 = -2^-40 (0xAB800000) - a = 0x3F800008 # 1 + 2^-20 - b = 0x3F7FFFF0 # 1 - 2^-20 - self.assertEqual(ref_mad_f32(a, b, NEG_ONE), POS_ZERO) - self.assertEqual(ref_fmac_f32(a, b, NEG_ONE), 0xAB800000) - - # (1 + 2^-23)^2 - (1 + 2^-22) = 2^-46 (0x28800000) - one_plus_ulp = 0x3F800001 - neg_one_plus_2ulp = 0xBF800002 - self.assertEqual(ref_mad_f32(one_plus_ulp, one_plus_ulp, neg_one_plus_2ulp), POS_ZERO) - self.assertEqual(ref_fmac_f32(one_plus_ulp, one_plus_ulp, neg_one_plus_2ulp), 0x28800000) - - # Intermediate overflow: 2^100 * 2^28 - 2^127 - p100 = 0x71800000 # 2^100 - p28 = 0x4D800000 # 2^28 - n127 = 0xFF000000 # -2^127 - self.assertEqual(ref_mad_f32(p100, p28, n127), POS_INF) - self.assertEqual(ref_fmac_f32(p100, p28, n127), 0x7F000000) - - # Legacy 0 * anything -> +0.0 - self.assertEqual(ref_mad_legacy_f32(POS_ZERO, POS_INF, NEG_TWO), NEG_TWO) - self.assertEqual(ref_mad_legacy_f32(NEG_ZERO, NEG_INF, NEG_ZERO), POS_ZERO) - self.assertEqual(ref_mad_legacy_f32(POS_ZERO, QNAN, THREE), THREE) - self.assertEqual(ref_mad_legacy_f32(NEG_ZERO, TWO, NEG_ZERO), POS_ZERO) - self.assertEqual(ref_mad_f32(NEG_ZERO, TWO, NEG_ZERO), NEG_ZERO) - self.assertEqual(ref_fmac_f32(NEG_ZERO, TWO, NEG_ZERO), NEG_ZERO) - self.assertTrue(is_nan_bits(ref_mad_f32(POS_ZERO, POS_INF, ONE))) - self.assertTrue(is_nan_bits(ref_fmac_f32(POS_ZERO, POS_INF, ONE))) - - # Source and output modifiers match reference composition: neg/abs apply before mul+add, omod before clamp. - self.assertEqual( - apply_out_mods( - ref_mad_f32(apply_src_mod(NEG_TWO, neg=True), apply_src_mod(THREE, neg=True, absm=True), FOUR), - "mul:2", - clamp=True, - ), - POS_ZERO, # (2.0 * (-3.0) + 4.0) * 2.0 = -4.0 -> clamp -> 0.0 - ) - self.assertEqual( - apply_out_mods( - ref_mad_f32(apply_src_mod(NEG_TWO, neg=True), apply_src_mod(0xC0400000, absm=True), FOUR), - "mul:2", - clamp=True, - ), - ONE, # (2.0 * 3.0 + 4.0) * 2.0 = 20.0 -> clamp -> 1.0 - ) - self.assertEqual(apply_out_mods(0x3EC00000, "mul:2", clamp=True), 0x3F400000) # 0.375 * 2 = 0.75 - self.assertEqual(apply_out_mods(0x3F400000, "mul:2", clamp=True), ONE) # 0.75 * 2 = 1.5 -> 1.0 - self.assertEqual(apply_out_mods(THREE, "div:2", clamp=True), ONE) # 1.5 -> 1.0 - self.assertEqual(apply_out_mods(NEG_TWO, None, clamp=True), POS_ZERO) - - -class Min3Max3F32Tests(unittest.TestCase): - """Semantic tests for v_min3_f32 and v_max3_f32 (NaNs excluded; see module docstring).""" - - def test_every_permutation_across_value_classes(self): - triples = ( - (NEG_INF, NEG_FLT_MAX, FLT_MAX), - (NEG_INF, NEG_ZERO, POS_INF), - (NEG_TWO, ONE_HALF, THREE), - (NEG_FLT_MIN, NEG_SUBNORM_MIN, SUBNORM_MIN), - (FLT_MIN, HALF, FLT_MAX), - (NEG_ONE, NEG_ONE, TWO), - (THREE, HALF, THREE), - (TWO_HALF, TWO_HALF, TWO_HALF), - ) - for op, ref_fn in (("v_min3_f32", ref_min3_f32), ("v_max3_f32", ref_max3_f32)): - for triple in triples: - for perm in sorted(set(itertools.permutations(triple))): - with self.subTest(op=op, perm=[hex(w) for w in perm]): - self.assertEqual(run_three_input(op, *perm), ref_fn(*perm)) - - def test_grid_sweep_batched(self): - # 7^3 = 343 triples per op, batched 4 components per pixel shader export. - grid = (NEG_INF, NEG_TWO, NEG_ONE, POS_ZERO, ONE, TWO_HALF, POS_INF) - triples = list(itertools.product(grid, repeat=3)) - for op, ref_fn in (("v_min3_f32", ref_min3_f32), ("v_max3_f32", ref_max3_f32)): - for start in range(0, len(triples), 4): - chunk = triples[start:start + 4] - lines, expected = [], [] - for slot, (a, b, c) in enumerate(chunk): - base = 10 + 4 * slot - lines += [ - f"v_mov_b32 v{base + 1}, {a:#x}", - f"v_mov_b32 v{base + 2}, {b:#x}", - f"v_mov_b32 v{base + 3}, {c:#x}", - f"{op} v{base}, v{base + 1}, v{base + 2}, v{base + 3}", - ] - expected.append(ref_fn(a, b, c)) - regs = [f"v{10 + 4 * slot}" for slot in range(len(chunk))] - while len(regs) < 4: - regs.append(regs[0]) - expected.append(expected[0]) - with self.subTest(op=op, batch=start // 4): - self.assertEqual(run_ps_mrt0(lines, tuple(regs)), expected) - - def test_signed_zeros(self): - # Unambiguous signed-zero triples (same-sign zeros or strictly ordered non-zero extreme). - exact_cases = [ - ("v_min3_f32", (NEG_ZERO, NEG_ZERO, ONE), NEG_ZERO), - ("v_min3_f32", (ONE, NEG_ZERO, NEG_ZERO), NEG_ZERO), - ("v_min3_f32", (POS_ZERO, POS_ZERO, ONE), POS_ZERO), - ("v_min3_f32", (POS_ZERO, NEG_ZERO, NEG_ONE), NEG_ONE), - ("v_max3_f32", (NEG_ZERO, NEG_ZERO, NEG_ONE), NEG_ZERO), - ("v_max3_f32", (NEG_ONE, NEG_ZERO, NEG_ZERO), NEG_ZERO), - ("v_max3_f32", (POS_ZERO, POS_ZERO, NEG_ONE), POS_ZERO), - ("v_max3_f32", (POS_ZERO, NEG_ZERO, ONE), ONE), - ] - for op, xs, want in exact_cases: - with self.subTest(op=op, xs=[hex(w) for w in xs]): - self.assertEqual(run_three_input(op, *xs), want) - - # Mixed (+0.0, -0.0) cases: -0.0 is the smaller zero, as on hardware. - for op, ref_fn, third in (("v_min3_f32", ref_min3_f32, ONE), ("v_max3_f32", ref_max3_f32, NEG_ONE)): - for perm in sorted(set(itertools.permutations((POS_ZERO, NEG_ZERO, third)))): - with self.subTest(op=op, perm=[hex(w) for w in perm]): - got = run_three_input(op, *perm) - self.assertIn(got, (POS_ZERO, NEG_ZERO)) - self.assertEqual(got, ref_fn(*perm)) - - def test_e64_inline_constants_sgprs_source_and_output_modifiers(self): - # _e64 suffix, inline float constants (including 0.15915494), SGPRs, neg/abs, mul/div/clamp. - words = run_ps_mrt0([ - f"s_mov_b32 s4, {THREE:#x}", - f"v_mov_b32 v1, {NEG_TWO:#x}", - "v_min3_f32_e64 v10, -v1, 0.15915494, |-4.0|", # min(2.0, 1/(2*pi), 4.0) -> 0.15915494 - "v_max3_f32_e64 v11, -|s4|, -0.5, neg(2.0) div:2 clamp", # max(-3.0, -0.5, -2.0)=-0.5 -> -0.25 -> +0.0 - "v_min3_f32 v12, s4, 0.5, 4.0 mul:4 clamp", # 0.5 * 4 -> 2.0 -> clamp -> 1.0 - f"v_mov_b32 v2, {FLT_MAX:#x}", - "v_max3_f32 v13, v2, 1.0, 2.0 mul:2", # FLT_MAX * 2 -> +inf - ], ("v10", "v11", "v12", "v13")) - self.assertEqual(words, [0x3E22F983, POS_ZERO, ONE, POS_INF]) - - # clamp on +-inf saturates to [0.0, 1.0]. - self.assertEqual(run_three_input("v_max3_f32", POS_INF, ONE, TWO, mods="clamp"), ONE) - self.assertEqual(run_three_input("v_min3_f32", NEG_INF, ONE, TWO, mods="clamp"), POS_ZERO) - - # div:2 on FLT_MAX halves exponent cleanly. - self.assertEqual(run_three_input("v_max3_f32", FLT_MAX, ONE, TWO, mods="div:2"), 0x7EFFFFFF) - - def test_destination_aliasing(self): - for op, ref_fn in (("v_min3_f32", ref_min3_f32), ("v_max3_f32", ref_max3_f32)): - for expr, a, b, c in ( - ("v0, v0, v1, v2", NEG_TWO, THREE, ONE), - ("v0, v1, v0, v2", ONE, NEG_TWO, THREE), - ("v0, v1, v2, v0", THREE, ONE, NEG_TWO), - ("v0, v0, v0, v1", FOUR, FOUR, HALF), - ): - with self.subTest(op=op, expr=expr): - got = run_ps_mrt0([ - f"v_mov_b32 v0, {a:#x}", - f"v_mov_b32 v1, {b:#x}", - f"v_mov_b32 v2, {c:#x}", - f"{op} {expr}", - ])[0] - # Order (v0, v1, v2) corresponds to the register values placed into the source slots. - regs = {"v0": a, "v1": b, "v2": c} - s0, s1, s2 = (regs[r.strip()] for r in expr.split(",")[1:]) - self.assertEqual(got, ref_fn(s0, s1, s2)) - - -class MadAndFmacF32Tests(unittest.TestCase): - """Semantic tests for unfused v_mad_f32 and fused accumulating v_fmac_f32.""" - - def test_fused_vs_unfused_divergence(self): - # Normalized cases where intermediate product rounding, overflow, or underflow separates mad from fmac. - cases = [ - # (a, b, c, want_mad, want_fmac) - (0x3F800008, 0x3F7FFFF0, NEG_ONE, POS_ZERO, 0xAB800000), # (1+2^-20)*(1-2^-20) - 1 = -2^-40 - (0x3F800001, 0x3F800001, 0xBF800002, POS_ZERO, 0x28800000), # (1+2^-23)^2 - (1+2^-22) = 2^-46 - (0x3FC00001, 0x3FBFFFFF, 0xC0100000, POS_ZERO, 0xA8800000), # (1.5+2^-23)*(1.5-2^-23) - 2.25 = -2^-46 - (0x71800000, 0x4D800000, 0xFF000000, POS_INF, 0x7F000000), # 2^100*2^28 - 2^127: ovf vs finite - (0xF1800000, 0x4D800000, 0x7F000000, NEG_INF, 0xFF000000), # -2^100*2^28 + 2^127: -ovf vs finite - # Subnormal operands or products: see DenormalFlushTests (RDNA2 mad flushes them). - ] - for a, b, c, want_mad, want_fmac in cases: - with self.subTest(a=hex(a), b=hex(b), c=hex(c)): - self.assertEqual(ref_mad_f32(a, b, c), want_mad) - self.assertEqual(ref_fmac_f32(a, b, c), want_fmac) - self.assertNotEqual(want_mad, want_fmac) - self.assertEqual(run_three_input("v_mad_f32", a, b, c), want_mad) - self.assertEqual(run_three_input("v_fmac_f32", a, b, c), want_fmac) - - def test_signed_zeros_infinities_and_nans(self): - exact_cases = [ - (NEG_ZERO, TWO, NEG_ZERO, NEG_ZERO), # (-0)*2 + (-0) -> -0 - (POS_ZERO, TWO, NEG_ZERO, POS_ZERO), # (+0)*2 + (-0) -> +0 - (NEG_TWO, THREE, 0x40C00000, POS_ZERO), # -6 + 6 -> +0 - (NEG_ZERO, NEG_ONE, NEG_ZERO, POS_ZERO), # (+0) + (-0) -> +0 - (ONE, NEG_ZERO, NEG_ZERO, NEG_ZERO), # 1*(-0) + (-0) -> -0 - (POS_INF, TWO, POS_INF, POS_INF), - (NEG_INF, TWO, ONE, NEG_INF), - (TWO, THREE, NEG_INF, NEG_INF), - (NEG_INF, NEG_TWO, NEG_ONE, POS_INF), - (ONE_HALF, TWO_HALF, HALF, 0x40880000), # 1.5 * 2.5 + 0.5 = 4.25 - ] - for op, ref_fn in (("v_mad_f32", ref_mad_f32), ("v_fmac_f32", ref_fmac_f32)): - for a, b, c, want in exact_cases: - with self.subTest(op=op, a=hex(a), b=hex(b), c=hex(c)): - self.assertEqual(ref_fn(a, b, c), want) - self.assertEqual(run_three_input(op, a, b, c), want) - - nan_cases = [ - (POS_ZERO, POS_INF, ONE), - (NEG_INF, NEG_ZERO, TWO), - (POS_ZERO, QNAN, THREE), - (QNAN, ONE, TWO), - (ONE, TWO, SNAN), - (POS_INF, ONE, NEG_INF), - (NEG_INF, ONE, POS_INF), - ] - for op, ref_fn in (("v_mad_f32", ref_mad_f32), ("v_fmac_f32", ref_fmac_f32)): - for a, b, c in nan_cases: - with self.subTest(op=op, nan_case=(hex(a), hex(b), hex(c))): - self.assertTrue(is_nan_bits(ref_fn(a, b, c))) - self.assertTrue(is_nan_bits(run_three_input(op, a, b, c))) - - def test_fmac_accumulator_aliasing_and_chaining(self): - # vdst aliases src0, src1, or both, and chains across consecutive accumulations. - chained = run_ps_mrt0([ - f"v_mov_b32 v0, {TWO:#x}", - f"v_mov_b32 v1, {THREE:#x}", - "v_fmac_f32 v0, v0, v1", # 2*3 + 2 = 8.0 - f"v_mov_b32 v2, {TWO:#x}", - f"v_mov_b32 v3, {FOUR:#x}", - "v_fmac_f32 v2, v3, v2", # 4*2 + 2 = 10.0 - f"v_mov_b32 v4, {THREE:#x}", - "v_fmac_f32 v4, v4, v4", # 3*3 + 3 = 12.0 - f"v_mov_b32 v5, {HALF:#x}", - f"v_mov_b32 v6, {ONE_HALF:#x}", - f"v_mov_b32 v7, {TWO:#x}", - f"v_mov_b32 v8, {TWO_HALF:#x}", - "v_fmac_f32_e32 v5, v6, v7", # 1.5*2.0 + 0.5 = 3.5 - "v_fmac_f32_e32 v5, v8, v7", # 2.5*2.0 + 3.5 = 8.5 - ], ("v0", "v2", "v4", "v5")) - self.assertEqual(chained, [f32_to_bits(v) for v in (8.0, 10.0, 12.0, 8.5)]) - - def test_mad_destination_aliasing(self): - for expr, want in ( - ("v0, v0, v1, v2", f32_to_bits(2.0 * 3.0 + 4.0)), - ("v0, v1, v0, v2", f32_to_bits(3.0 * 2.0 + 4.0)), - ("v0, v1, v2, v0", f32_to_bits(3.0 * 4.0 + 2.0)), - ("v0, v0, v0, v0", f32_to_bits(2.0 * 2.0 + 2.0)), - ): - with self.subTest(expr=expr): - got = run_ps_mrt0([ - f"v_mov_b32 v0, {TWO:#x}", - f"v_mov_b32 v1, {THREE:#x}", - f"v_mov_b32 v2, {FOUR:#x}", - f"v_mad_f32 {expr}", - ])[0] - self.assertEqual(got, want) - - def test_variants_modifiers_and_nocontraction(self): - # _e32 literal in src0, _e64 source/output modifiers, SGPRs, inline float constants. - words = run_ps_mrt0([ - f"s_mov_b32 s4, {THREE:#x}", - f"v_mov_b32 v1, {TWO:#x}", - f"v_mov_b32 v10, {ONE:#x}", - "v_fmac_f32_e32 v10, 0x3fc00000, v1", # 1.5 * 2.0 + 1.0 = 4.0 - f"v_mov_b32 v11, {HALF:#x}", - "v_fmac_f32_e64 v11, -v1, |s4| mul:2", # (-2.0 * 3.0 + 0.5) * 2 = -11.0 - f"v_mov_b32 v12, {THREE:#x}", - "v_fmac_f32_e64 v12, s4, -0.5 div:2 clamp", # (3.0 * -0.5 + 3.0) * 0.5 = 0.75 - "v_mad_f32_e64 v13, -v1, -|s4|, 4.0 mul:2 clamp", # (-2 * -3 + 4) * 2 = 20 -> clamp -> 1.0 - ], ("v10", "v11", "v12", "v13")) - self.assertEqual(words, [f32_to_bits(4.0), f32_to_bits(-11.0), f32_to_bits(0.75), ONE]) - - # Verify v_mad_f32's OpFMul and OpFAdd carry NoContraction so drivers cannot fuse them into FMA. - spv = translate_ps([ - f"v_mov_b32 v1, {ONE:#x}", - f"v_mov_b32 v2, {TWO:#x}", - f"v_mov_b32 v3, {THREE:#x}", - "v_mad_f32 v0, v1, v2, v3", - ]) - fmul_ids = re.findall(r"(%\w+)\s*=\s*OpFMul %float", spv) - fadd_ids = re.findall(r"(%\w+)\s*=\s*OpFAdd %float", spv) - self.assertEqual(len(fmul_ids), 1) - self.assertEqual(len(fadd_ids), 1) - self.assertIn(f"OpDecorate {fmul_ids[0]} NoContraction", spv) - self.assertIn(f"OpDecorate {fadd_ids[0]} NoContraction", spv) - self.assertNotIn("Fma", spv) - - -def flush_bits(b: int) -> int: - """RDNA2 flush of v_mad_f32, v_mac_f32 and v_mad_legacy_f32: a subnormal reads as signed zero.""" - b &= MASK32 - return b & 0x80000000 if (b & 0x7FFFFFFF) < 0x00800000 else b - - -def ref_mad_f32_ftz(xb: int, yb: int, zb: int) -> int: - """v_mad_f32 with the denormal flush: inputs, the rounded product and the sum flush.""" - prod = flush_bits(_mul_bits_f32(flush_bits(xb), flush_bits(yb))) - return flush_bits(_add_bits_f32(prod, flush_bits(zb))) - - -def ref_mad_legacy_f32_ftz(xb: int, yb: int, zb: int) -> int: - """v_mad_legacy_f32 with the denormal flush, then the legacy 0 * anything -> +0.0 rule.""" - x, y = flush_bits(xb), flush_bits(yb) - prod = POS_ZERO if (x & 0x7FFFFFFF) == 0 or (y & 0x7FFFFFFF) == 0 else flush_bits(_mul_bits_f32(x, y)) - return flush_bits(_add_bits_f32(prod, flush_bits(zb))) - - -class DenormalFlushTests(unittest.TestCase): - """v_mad_f32, v_mac_f32 and v_mad_legacy_f32 have no f32 denormal support on RDNA2: a subnormal operand, - the rounded product or the result reads as signed zero, whatever the MODE register says (SHADER-118). Source: - LLVM AMDGPU SIISelLowering.cpp, SITargetLowering::isFMADLegal (llvm-project - 1922c0c9244e41ed056f71e897512c72e24c7022), which only forms these instructions when f32 denormals are - flushed. The translator emulates that with Gen.flush_f32, so the RDNA2 column below is what it computes. - 9,297 of the 26,503 shaders in shaders.rpf use at least one of the three (440,858 occurrences, 0.99% of the - corpus), counted with tools/shader_profile.py over the gfx1013 disassembly. - """ - - CASES = [ - # (op, a, b, c, mods, want) -- c is the addend (v_mad*) or the accumulator (v_mac_f32) - ("v_mad_f32", 0x17800000, 0x1C800000, SUBNORM_MIN, "", POS_ZERO), # 2^-80*2^-70 + 2^-149 - ("v_mad_f32", 0x17800000, 0x21800000, 0x00000200, "", POS_ZERO), # product 2^-140 (subnormal) - ("v_mad_f32", NEG_SUBNORM_MIN, ONE, NEG_SUBNORM_MIN, "", NEG_ZERO), # flushed to -0, -0 + -0 = -0 - ("v_mac_f32", SUBNORM_MIN, ONE, SUBNORM_MIN, "", POS_ZERO), # 2^-149*1 + 2^-149 - ("v_mac_f32", ONE, ONE, SUBNORM_MIN, "", ONE), # 1 + 2^-149 = 1 - ("v_mad_legacy_f32", SUBNORM_MIN, POS_INF, NEG_ONE, "", NEG_ONE), # 2^-149 -> +0, 0*inf -> +0 - ("v_mad_legacy_f32", NEG_SUBNORM_MIN, POS_INF, ONE, "", ONE), # -2^-149 -> -0, 0*inf -> +0 - ("v_mad_f32", 0x00800000, ONE, POS_ZERO, "div:2", POS_ZERO), # FLT_MIN/2 flushed after omod - ("v_mad_f32", 0x00C00000, ONE, NEG_FLT_MIN, "mul:2", POS_ZERO), # (1.5*2^-126 - 2^-126) flushed before mul:2 - ("v_mad_f32", 0x00C00000, ONE, NEG_FLT_MIN, "mul:4", POS_ZERO), # (1.5*2^-126 - 2^-126) flushed before mul:4 - ("v_mad_legacy_f32", 0x00C00000, ONE, NEG_FLT_MIN, "mul:2", POS_ZERO), - ] - - def test_flush_matches_the_rdna2_column(self): - refs = {"v_mad_f32": ref_mad_f32_ftz, "v_mac_f32": ref_mad_f32_ftz, - "v_mad_legacy_f32": ref_mad_legacy_f32_ftz} - for op, a, b, c, mods, want in self.CASES: - with self.subTest(op=op, a=hex(a), b=hex(b), c=hex(c), mods=mods): - got = run_three_input(op, a, b, c, mods) - self.assertEqual(got, want) - if mods == "": - self.assertEqual(refs[op](a, b, c), want) - - def test_normal_values_nan_and_inf_pass_through(self): - for op in ("v_mad_f32", "v_mac_f32"): - with self.subTest(op=op): - self.assertEqual(run_three_input(op, TWO, THREE, FOUR), f32_to_bits(10.0)) - self.assertTrue(is_nan_bits(run_three_input(op, QNAN, ONE, ONE))) - self.assertTrue(is_nan_bits(run_three_input(op, POS_INF, ONE, NEG_INF))) # inf - inf - self.assertEqual(run_three_input(op, NEG_ZERO, TWO, NEG_ZERO), NEG_ZERO) - # The legacy 0 * anything -> +0 rule still runs on the flushed operands. - self.assertEqual(run_three_input("v_mad_legacy_f32", TWO, THREE, FOUR), f32_to_bits(10.0)) - self.assertTrue(is_nan_bits(run_three_input("v_mad_legacy_f32", QNAN, ONE, ONE))) - self.assertTrue(is_nan_bits(run_three_input("v_mad_legacy_f32", POS_INF, ONE, NEG_INF))) - self.assertEqual(run_three_input("v_mad_legacy_f32", NEG_ZERO, TWO, NEG_ZERO), POS_ZERO) - - def test_denormal_divergence_is_still_detectable(self): - # Sabotage: turn every flush select into a pass-through; the subnormal cases above now differ. - cases = [ - ("v_mad_f32", 0x17800000, 0x1C800000, SUBNORM_MIN, POS_ZERO), - ("v_mac_f32", SUBNORM_MIN, ONE, SUBNORM_MIN, POS_ZERO), - ("v_mad_legacy_f32", SUBNORM_MIN, POS_INF, NEG_ONE, NEG_ONE), - ] - for op, a, b, c, want in cases: - with self.subTest(op=op): - if op == "v_mac_f32": - lines = [f"v_mov_b32 v1, {a:#x}", f"v_mov_b32 v2, {b:#x}", - f"v_mov_b32 v0, {c:#x}", f"{op} v0, v1, v2"] - else: - lines = [f"v_mov_b32 v1, {a:#x}", f"v_mov_b32 v2, {b:#x}", - f"v_mov_b32 v3, {c:#x}", f"{op} v0, v1, v2, v3"] - spv = translate_ps(lines) - self.assertEqual(si.run_fragment(spv)["%out_mrt0"][0], want) - unflushed, count = re.subn(r"(%\w+) = OpSelect %float (%\w+) (%\w+) (%\w+)", - r"\1 = OpCopyObject %float \4", spv) - self.assertGreaterEqual(count, 3) - self.assertNotEqual(si.run_fragment(unflushed)["%out_mrt0"][0], want) - - -class MadLegacyF32Tests(unittest.TestCase): - """Semantic tests for v_mad_legacy_f32 (0 * inf/NaN/-0 -> +0.0, then unfused f32 add).""" - - def test_zero_times_inf_and_nan_rules(self): - cases = [ - # 0 in src0 or src1 (either +0.0 or -0.0) * inf/NaN/0 -> +0.0, then + src2 - (POS_ZERO, POS_INF, NEG_TWO, NEG_TWO), - (POS_INF, POS_ZERO, NEG_TWO, NEG_TWO), - (NEG_ZERO, NEG_INF, THREE, THREE), - (NEG_INF, NEG_ZERO, THREE, THREE), - (POS_ZERO, NEG_INF, POS_INF, POS_INF), - (NEG_ZERO, POS_INF, NEG_INF, NEG_INF), - (POS_ZERO, QNAN, ONE_HALF, ONE_HALF), - (QNAN, NEG_ZERO, NEG_ONE, NEG_ONE), - (NEG_ZERO, SNAN, TWO, TWO), - (SNAN, POS_ZERO, HALF, HALF), - (POS_ZERO, POS_INF, NEG_ZERO, POS_ZERO), # +0.0 + (-0.0) = +0.0 - (NEG_ZERO, TWO, NEG_ZERO, POS_ZERO), # legacy (-0.0)*2 -> +0.0; +0.0 + (-0.0) = +0.0 - (TWO, NEG_ZERO, NEG_ZERO, POS_ZERO), # legacy 2*(-0.0) -> +0.0; +0.0 + (-0.0) = +0.0 - # Non-zero tiny values must NOT trigger zero-override. - (FLT_MIN, POS_INF, ONE, POS_INF), - # Subnormal multipliers: see DenormalFlushTests (RDNA2 flushes them to 0 first). - # Unfused rounding matches v_mad_f32 when neither multiplier is 0. - (0x3F800008, 0x3F7FFFF0, NEG_ONE, POS_ZERO), - (0x71800000, 0x4D800000, 0xFF000000, POS_INF), - ] - for a, b, c, want in cases: - with self.subTest(a=hex(a), b=hex(b), c=hex(c)): - self.assertEqual(ref_mad_legacy_f32(a, b, c), want) - self.assertEqual(run_three_input("v_mad_legacy_f32", a, b, c), want) - - # Legacy only overrides the product; + z with NaN still yields NaN. - for a, b, c in ((POS_ZERO, ONE, QNAN), (TWO, THREE, NEG_QNAN), (ONE, QNAN, QNAN)): - with self.subTest(nan_z=(hex(a), hex(b), hex(c))): - self.assertTrue(is_nan_bits(ref_mad_legacy_f32(a, b, c))) - self.assertTrue(is_nan_bits(run_three_input("v_mad_legacy_f32", a, b, c))) - - def test_e64_modifiers_inline_constants_aliasing_and_nocontraction(self): - words = run_ps_mrt0([ - f"s_mov_b32 s4, {POS_INF:#x}", - f"v_mov_b32 v1, {POS_ZERO:#x}", - "v_mad_legacy_f32_e64 v10, -v1, s4, -1.5", # (-0)*inf + (-1.5) -> -1.5 - "v_mad_legacy_f32 v11, neg(0), s4, 0.25 mul:4 clamp", # (+0) + 0.25 -> *4 = 1.0 - "v_mad_legacy_f32 v12, 0, s4, 2.0 div:2", # (+0) + 2.0 -> /2 = 1.0 - f"v_mov_b32 v13, {QNAN:#x}", - "v_mad_legacy_f32 v13, v13, 0, 2.5", # dst aliases src0: qNaN * 0 + 2.5 = 2.5 - ], ("v10", "v11", "v12", "v13")) - self.assertEqual(words, [f32_to_bits(-1.5), ONE, ONE, TWO_HALF]) - - spv = translate_ps([ - f"v_mov_b32 v1, {POS_ZERO:#x}", - f"v_mov_b32 v2, {POS_INF:#x}", - f"v_mov_b32 v3, {ONE:#x}", - "v_mad_legacy_f32 v0, v1, v2, v3", - ]) - fmul_ids = re.findall(r"(%\w+)\s*=\s*OpFMul %float", spv) - fadd_ids = re.findall(r"(%\w+)\s*=\s*OpFAdd %float", spv) - self.assertEqual(len(fmul_ids), 1) - self.assertEqual(len(fadd_ids), 1) - self.assertIn(f"OpDecorate {fmul_ids[0]} NoContraction", spv) - self.assertIn(f"OpDecorate {fadd_ids[0]} NoContraction", spv) - - -class ExecMaskingTests(unittest.TestCase): - """Inactive lanes under EXEC must leave destination registers untouched across all 5 ops.""" - - def test_pixel_shader_inactive_exec_preserves_destination(self): - sentinel = 0x3E4CCCCD # 0.2f (safe non-NaN bit pattern) - insns = [ - "v_min3_f32 v0, v1, v2, v3", - "v_max3_f32 v0, v1, v2, v3", - "v_mad_f32 v0, v1, v2, v3", - "v_fmac_f32_e32 v0, v1, v2", - "v_fmac_f32_e64 v0, v1, v2", - "v_mad_legacy_f32 v0, v1, v2, v3", - ] - for disable_exec in ("s_mov_b32 exec_lo, 0", "v_cmpx_eq_u32_e32 vcc_lo, 0, 1"): - for insn in insns: - with self.subTest(disable=disable_exec, insn=insn): - got = run_ps_mrt0([ - f"v_mov_b32 v0, {sentinel:#x}", - f"v_mov_b32 v1, {TWO:#x}", - f"v_mov_b32 v2, {THREE:#x}", - f"v_mov_b32 v3, {FOUR:#x}", - disable_exec, - insn, - "s_mov_b32 exec_lo, 1", - ])[0] - self.assertEqual(got, sentinel) - - def test_compute_workgroup_partial_exec_mask(self): - sentinel = ONE - cases = [ - ("v_min3_f32 v1, v2, v4, v5", NEG_TWO), - ("v_max3_f32 v1, v2, v4, v5", FOUR), - ("v_mad_f32 v1, v2, v4, v5", f32_to_bits(3.0 * (-2.0) + 4.0)), - ("v_fmac_f32 v1, v2, v4", f32_to_bits(3.0 * (-2.0) + 1.0)), - ("v_mad_legacy_f32 v1, v2, v4, v5", f32_to_bits(3.0 * (-2.0) + 4.0)), - ] - for insn, active_val in cases: - with self.subTest(insn=insn): - mem = run_cs_workgroup_exec([ - "v_lshlrev_b32 v3, 2, v0", - f"v_mov_b32 v1, {sentinel:#x}", - f"v_mov_b32 v2, {THREE:#x}", - f"v_mov_b32 v4, {NEG_TWO:#x}", - f"v_mov_b32 v5, {FOUR:#x}", - "s_mov_b32 exec_lo, 5", # lanes 0 and 2 active; lanes 1 and 3 inactive - insn, - "s_mov_b32 exec_lo, 0xf", - "buffer_store_dword v1, v3, s[0:3], 0 offen", - ]) - self.assertEqual(mem, {0x0: active_val, 0x4: sentinel, 0x8: active_val, 0xC: sentinel}) - - -class NegativeControlsTests(unittest.TestCase): - """Sabotage translated SPIR-V output and confirm value assertions catch each mutation.""" - - def test_sabotaged_spirv_is_detected(self): - # 1. v_min3_f32 mutated to NMax - spv_min3 = translate_ps([ - f"v_mov_b32 v1, {ONE:#x}", - f"v_mov_b32 v2, {TWO:#x}", - f"v_mov_b32 v3, {THREE:#x}", - "v_min3_f32 v0, v1, v2, v3", - ]) - self.assertEqual(si.run_fragment(spv_min3)["%out_mrt0"][0], ONE) - self.assertNotEqual(si.run_fragment(spv_min3.replace("glsl NMin", "glsl NMax"))["%out_mrt0"][0], ONE) - - # 2. v_max3_f32 mutated to NMin - spv_max3 = translate_ps([ - f"v_mov_b32 v1, {ONE:#x}", - f"v_mov_b32 v2, {TWO:#x}", - f"v_mov_b32 v3, {THREE:#x}", - "v_max3_f32 v0, v1, v2, v3", - ]) - self.assertEqual(si.run_fragment(spv_max3)["%out_mrt0"][0], THREE) - self.assertNotEqual(si.run_fragment(spv_max3.replace("glsl NMax", "glsl NMin"))["%out_mrt0"][0], THREE) - - # 3. v_mad_f32 OpFAdd mutated to OpFSub - spv_mad = translate_ps([ - f"v_mov_b32 v1, {TWO:#x}", - f"v_mov_b32 v2, {THREE:#x}", - f"v_mov_b32 v3, {FOUR:#x}", - "v_mad_f32 v0, v1, v2, v3", - ]) - want_mad = f32_to_bits(10.0) - self.assertEqual(si.run_fragment(spv_mad)["%out_mrt0"][0], want_mad) - self.assertNotEqual(si.run_fragment(spv_mad.replace("OpFAdd %float", "OpFSub %float"))["%out_mrt0"][0], want_mad) - - # 4. v_fmac_f32 Fma replaced with unfused OpFMul + OpFAdd fails on intermediate cancellation case - spv_fmac = translate_ps([ - "v_mov_b32 v1, 0x3f800008", - "v_mov_b32 v2, 0x3f7ffff0", - f"v_mov_b32 v0, {NEG_ONE:#x}", - "v_fmac_f32 v0, v1, v2", - ]) - want_fmac = 0xAB800000 - self.assertEqual(si.run_fragment(spv_fmac)["%out_mrt0"][0], want_fmac) - bad_fmac, count = re.subn( - r"(%\w+) = OpExtInst %float %glsl Fma (%\w+) (%\w+) (%\w+)", - r"%unfused_m = OpFMul %float \2 \3\n \1 = OpFAdd %float %unfused_m \4", - spv_fmac, - ) - self.assertEqual(count, 1) - self.assertNotEqual(si.run_fragment(bad_fmac)["%out_mrt0"][0], want_fmac) - - # 5. v_mad_legacy_f32 zero check weakened from LogicalOr to LogicalAnd breaks 0 * inf + 2.0 - spv_leg = translate_ps([ - f"v_mov_b32 v1, {POS_ZERO:#x}", - f"v_mov_b32 v2, {POS_INF:#x}", - f"v_mov_b32 v3, {TWO:#x}", - "v_mad_legacy_f32 v0, v1, v2, v3", - ]) - self.assertEqual(si.run_fragment(spv_leg)["%out_mrt0"][0], TWO) - bad_leg = spv_leg.replace("OpLogicalOr %bool", "OpLogicalAnd %bool") - self.assertTrue(is_nan_bits(si.run_fragment(bad_leg)["%out_mrt0"][0])) - - # 6. clamp output modifier dropped - spv_clamp = translate_ps([ - f"v_mov_b32 v1, {TWO:#x}", - f"v_mov_b32 v2, {THREE:#x}", - f"v_mov_b32 v3, {FOUR:#x}", - "v_mad_f32 v0, v1, v2, v3 clamp", - ]) - self.assertEqual(si.run_fragment(spv_clamp)["%out_mrt0"][0], ONE) - bad_clamp, clamp_cnt = re.subn( - r"(%\w+) = OpExtInst %float %glsl FClamp (%\w+) %f0 %f1", - r"\1 = OpCopyObject %float \2", - spv_clamp, - ) - self.assertEqual(clamp_cnt, 1) - self.assertNotEqual(si.run_fragment(bad_clamp)["%out_mrt0"][0], ONE) - - -class MacLegacyF32Tests(unittest.TestCase): - """v_mac_legacy_f32 (GFX10.1 VOP2): v_mad_legacy_f32 with D as the addend, D = legacy(S0 * S1) + D, with the same - denormal flush. Until 2026-11-22 the translator rejected it.""" - - VALUES = [POS_ZERO, NEG_ZERO, SUBNORM_MIN, NEG_SUBNORM_MIN, FLT_MIN, HALF, ONE, NEG_ONE, TWO, NEG_TWO, THREE, - FLT_MAX, POS_INF, NEG_INF, QNAN] - - def test_matches_mad_legacy_reference(self): - for a in self.VALUES: - for b in self.VALUES[::2]: - for c in (POS_ZERO, NEG_ZERO, NEG_ONE, TWO_HALF, POS_INF, SUBNORM_MIN): - with self.subTest(a=hex(a), b=hex(b), c=hex(c)): - want = ref_mad_legacy_f32_ftz(a, b, c) - got = run_three_input("v_mac_legacy_f32", a, b, c) - if is_nan_bits(want): - self.assertTrue(is_nan_bits(got), hex(got)) - else: - self.assertEqual(got, want) - - def test_zero_times_inf_is_zero_and_d_is_the_addend(self): - self.assertEqual(run_three_input("v_mac_legacy_f32", POS_ZERO, POS_INF, NEG_TWO), NEG_TWO) - self.assertEqual(run_three_input("v_mac_legacy_f32", QNAN, NEG_ZERO, THREE), THREE) - self.assertEqual(run_three_input("v_mac_legacy_f32", TWO, THREE, FOUR), f32_to_bits(10.0)) - self.assertEqual(run_three_input("v_mac_legacy_f32", NEG_ZERO, TWO, NEG_ZERO), POS_ZERO) - - def test_e64_modifiers_and_accumulator_aliasing(self): - # VOP3 form: neg on a source, clamp on the result. - self.assertEqual(run_three_input("v_mac_legacy_f32_e64", TWO, THREE, FOUR, "clamp"), ONE) - lines = [f"v_mov_b32 v1, {TWO:#x}", f"v_mov_b32 v2, {THREE:#x}", f"v_mov_b32 v0, {FOUR:#x}", - "v_mac_legacy_f32_e64 v0, -v1, v2"] - self.assertEqual(run_ps_mrt0(lines)[0], NEG_TWO) # -2*3 + 4 - # D read as src0 and as the addend: 3*3 + 3 = 12; chained: 12*2 + 12 = 36. - lines = [f"v_mov_b32 v0, {THREE:#x}", f"v_mov_b32 v2, {TWO:#x}", - "v_mac_legacy_f32 v0, v0, v0", "v_mac_legacy_f32 v0, v0, v2"] - self.assertEqual(run_ps_mrt0(lines)[0], f32_to_bits(36.0)) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_valu_f32_round_sub.py b/tests/semantic/test_valu_f32_round_sub.py deleted file mode 100644 index ffe5829dc..000000000 --- a/tests/semantic/test_valu_f32_round_sub.py +++ /dev/null @@ -1,345 +0,0 @@ -"""Value and structural tests for f32 rounding and subtraction VALU instructions: - - v_floor_f32 D = floor(S0) - v_ceil_f32 D = ceil(S0) - v_trunc_f32 D = trunc(S0) - v_sub_f32 D = S0 - S1 - v_subrev_f32 D = S1 - S0 - -Each case translates a hand-written pixel-shader listing with tools/rdna2spirv.py -and executes the resulting SPIR-V via tests/semantic/spirv_mini_interp.py. -Results are compared as raw 32-bit IEEE-754 binary32 words so +0.0 (0x00000000) -and -0.0 (0x80000000) are strictly distinguished. Standard library only. -""" -import math -import os -import re -import struct -import sys -import unittest - -HERE = os.path.dirname(os.path.abspath(__file__)) -if HERE not in sys.path: - sys.path.insert(0, HERE) - -from support import mrt0_words, translate_lines # noqa: E402 (support puts tools/ on sys.path) - -POS_ZERO = 0x00000000 -NEG_ZERO = 0x80000000 -POS_INF = 0x7F800000 -NEG_INF = 0xFF800000 - - -def f32_to_bits(x): - """Pack a Python float into its IEEE-754 binary32 32-bit unsigned word.""" - try: - return struct.unpack(" 0 else NEG_INF - - -def bits_to_f32(bits): - """Unpack a 32-bit unsigned word as an IEEE-754 binary32 Python float.""" - return struct.unpack("`, and return (mrt0_word, spv).""" - lines = [ - f"v_mov_b32 v1, {src_bits & 0xFFFFFFFF:#010x}", - f"{op} v0, {src_expr}", - "exp mrt0 v0, v0, v0, v0 done vm", - "s_endpgm", - ] - return run_ps(lines, name=f"ps_{op.split()[0]}") - - -def run_binary(op, a_bits, b_bits, *, setup=None, operands="v1, v2"): - """Execute `op v0, ` with default v1/v2 setup and return (mrt0_word, spv).""" - if setup is None: - setup = [ - f"v_mov_b32 v1, {a_bits & 0xFFFFFFFF:#010x}", - f"v_mov_b32 v2, {b_bits & 0xFFFFFFFF:#010x}", - ] - lines = list(setup) + [ - f"{op} v0, {operands}", - "exp mrt0 v0, v0, v0, v0 done vm", - "s_endpgm", - ] - return run_ps(lines, name=f"ps_{op.split()[0]}") - - -ROUND_OPS = { - "v_floor_f32": math.floor, - "v_ceil_f32": math.ceil, - "v_trunc_f32": math.trunc, -} - -# Hand-verified (input_float, expected_floor, expected_ceil, expected_trunc) -ROUND_HAND_CONSTANTS = [ - (-1.75, -2.0, -1.0, -1.0), - (-1.5, -2.0, -1.0, -1.0), - (-1.25, -2.0, -1.0, -1.0), - (-0.5, -1.0, -0.0, -0.0), - (-0.0, -0.0, -0.0, -0.0), - (0.0, 0.0, 0.0, 0.0), - (0.5, 0.0, 1.0, 0.0), - (1.25, 1.0, 2.0, 1.0), - (1.5, 1.0, 2.0, 1.0), - (1.75, 1.0, 2.0, 1.0), - (-2.0, -2.0, -2.0, -2.0), - (-1.0, -1.0, -1.0, -1.0), - (1.0, 1.0, 1.0, 1.0), - (2.0, 2.0, 2.0, 2.0), - (float(2**22) + 0.5, float(2**22), float(2**22 + 1), float(2**22)), - (float(2**23), float(2**23), float(2**23), float(2**23)), - (float(-(2**23)), float(-(2**23)), float(-(2**23)), float(-(2**23))), - (float(2**24), float(2**24), float(2**24), float(2**24)), - (float(-(2**24)), float(-(2**24)), float(-(2**24)), float(-(2**24))), -] - - -class ReferenceConstantsTests(unittest.TestCase): - def test_rounding_hand_constants(self): - for x, exp_fl, exp_ce, exp_tr in ROUND_HAND_CONSTANTS: - xb = f32_to_bits(x) - with self.subTest(x=x, xb=hex(xb)): - self.assertEqual(ref_round_op(math.floor, xb), f32_to_bits(exp_fl)) - self.assertEqual(ref_round_op(math.ceil, xb), f32_to_bits(exp_ce)) - self.assertEqual(ref_round_op(math.trunc, xb), f32_to_bits(exp_tr)) - - def test_sub_hand_constants(self): - pairs = [ - (5.0, 2.0, 3.0, -3.0), - (1.5, 4.25, -2.75, 2.75), - (0.0, 0.0, 0.0, 0.0), - (-0.0, 0.0, -0.0, 0.0), - (0.0, -0.0, 0.0, -0.0), - (-0.0, -0.0, 0.0, 0.0), - ] - for a, b, exp_sub, exp_subrev in pairs: - ab, bb = f32_to_bits(a), f32_to_bits(b) - with self.subTest(a=a, b=b): - self.assertEqual(ref_sub_f32(ab, bb), f32_to_bits(exp_sub)) - self.assertEqual(ref_subrev_f32(ab, bb), f32_to_bits(exp_subrev)) - - -class RoundingOpsTests(unittest.TestCase): - def test_fractional_integer_and_large_values(self): - for op_base, py_fn in ROUND_OPS.items(): - for suffix in ("", "_e32", "_e64"): - op = op_base + suffix - for x, *_ in ROUND_HAND_CONSTANTS: - xb = f32_to_bits(x) - expected = ref_round_op(py_fn, xb) - with self.subTest(op=op, x=x, xb=hex(xb)): - got, _ = run_unary(op, xb) - self.assertEqual( - got, expected, - f"{op}({x} / {xb:#010x}): got {got:#010x}, expected {expected:#010x}", - ) - - def test_infinities(self): - for op_base in ROUND_OPS: - for inf_bits in (POS_INF, NEG_INF): - with self.subTest(op=op_base, inf=hex(inf_bits)): - got, _ = run_unary(op_base, inf_bits) - self.assertEqual(got, inf_bits) - - def test_vop3_modifiers(self): - # neg (-v1), abs (|v1|), neg-abs (-|v1|), clamp, mul:2, div:2, and omod-before-clamp - cases = [ - ("v_floor_f32_e64", -1.25, "-v1", 1.0), # floor(-(-1.25)) = floor(1.25) = 1.0 - ("v_floor_f32_e64", -1.25, "|v1|", 1.0), # floor(|-1.25|) = 1.0 - ("v_floor_f32_e64", 1.25, "-|v1|", -2.0), # floor(-|1.25|) = floor(-1.25) = -2.0 - ("v_ceil_f32_e64", 1.25, "-v1", -1.0), # ceil(-1.25) = -1.0 - ("v_ceil_f32_e64", -1.25, "|v1|", 2.0), # ceil(1.25) = 2.0 - ("v_trunc_f32_e64", -0.5, "|v1|", 0.0), # trunc(0.5) = +0.0 (bit-exact) - ("v_trunc_f32_e64", 0.5, "-v1", -0.0), # trunc(-0.5) = -0.0 (bit-exact) - ("v_floor_f32_e64", -0.5, "v1 clamp", 0.0), # clamp(-1.0) = +0.0 - ("v_ceil_f32_e64", 1.25, "v1 clamp", 1.0), # clamp(2.0) = 1.0 - ("v_trunc_f32_e64", 0.5, "v1 clamp", 0.0), # clamp(+0.0) = +0.0 - ("v_floor_f32_e64", 1.75, "v1 mul:2", 2.0), # floor(1.75) * 2 = 2.0 - ("v_ceil_f32_e64", 1.25, "v1 div:2", 1.0), # ceil(1.25) / 2 = 1.0 - ("v_trunc_f32_e64", 1.75, "v1 mul:2 clamp", 1.0), # (1.0 * 2) clamped = 1.0 - ] - for op, x, expr, exp in cases: - xb = f32_to_bits(x) - expected = f32_to_bits(exp) - with self.subTest(op=op, x=x, expr=expr): - got, _ = run_unary(op, xb, src_expr=expr) - self.assertEqual( - got, expected, - f"{op} v0, {expr} (v1={x}): got {got:#010x}, expected {expected:#010x}", - ) - - -class SubAndSubrevTests(unittest.TestCase): - def test_non_commutativity_and_forms(self): - pairs = [ - (5.0, 2.0), - (1.5, 4.25), - (-3.5, 1.25), - (-7.0, -2.5), - (0.125, -0.375), - ] - for a, b in pairs: - ab, bb = f32_to_bits(a), f32_to_bits(b) - for suffix in ("", "_e32", "_e64"): - with self.subTest(a=a, b=b, suffix=suffix): - got_sub, _ = run_binary("v_sub_f32" + suffix, ab, bb) - got_rev, _ = run_binary("v_subrev_f32" + suffix, ab, bb) - self.assertEqual(got_sub, ref_sub_f32(ab, bb)) - self.assertEqual(got_rev, ref_subrev_f32(ab, bb)) - self.assertNotEqual(got_sub, got_rev) - - def test_signed_zeros(self): - zero_cases = [ - (POS_ZERO, POS_ZERO, POS_ZERO, POS_ZERO), - (NEG_ZERO, POS_ZERO, NEG_ZERO, POS_ZERO), - (POS_ZERO, NEG_ZERO, POS_ZERO, NEG_ZERO), - (NEG_ZERO, NEG_ZERO, POS_ZERO, POS_ZERO), - (f32_to_bits(1.0), f32_to_bits(1.0), POS_ZERO, POS_ZERO), - (f32_to_bits(-1.0), f32_to_bits(-1.0), POS_ZERO, POS_ZERO), - ] - for ab, bb, exp_sub, exp_rev in zero_cases: - with self.subTest(a=hex(ab), b=hex(bb)): - got_sub, _ = run_binary("v_sub_f32", ab, bb) - got_rev, _ = run_binary("v_subrev_f32", ab, bb) - self.assertEqual(got_sub, exp_sub) - self.assertEqual(got_rev, exp_rev) - - def test_infinities(self): - one = f32_to_bits(1.0) - inf_cases = [ - (POS_INF, one, POS_INF, NEG_INF), - (NEG_INF, one, NEG_INF, POS_INF), - (POS_INF, NEG_INF, POS_INF, NEG_INF), - ] - for ab, bb, exp_sub, exp_rev in inf_cases: - with self.subTest(a=hex(ab), b=hex(bb)): - got_sub, _ = run_binary("v_sub_f32", ab, bb) - got_rev, _ = run_binary("v_subrev_f32", ab, bb) - self.assertEqual(got_sub, exp_sub) - self.assertEqual(got_rev, exp_rev) - - # inf - inf = NaN - for op in ("v_sub_f32", "v_subrev_f32"): - with self.subTest(op=op): - got, _ = run_binary(op, POS_INF, POS_INF) - self.assertTrue(math.isnan(bits_to_f32(got)), f"expected NaN, got {got:#010x}") - - def test_operand_kinds(self): - # SGPR, literal, and inline-float operands in _e32 and _e64 forms - cases = [ - ("v_sub_f32_e32", ["s_mov_b32 s0, 0x40a00000", "v_mov_b32 v2, 0x40000000"], "s0, v2", 3.0), - ("v_subrev_f32_e32", ["s_mov_b32 s0, 0x40a00000", "v_mov_b32 v2, 0x40000000"], "s0, v2", -3.0), - ("v_sub_f32_e32", ["v_mov_b32 v2, 0x3fc00000"], "0x40400000, v2", 1.5), - ("v_subrev_f32_e32", ["v_mov_b32 v2, 0x3fc00000"], "0x40400000, v2", -1.5), - ("v_sub_f32_e32", ["v_mov_b32 v2, 0x3e800000"], "0.5, v2", 0.25), - ("v_subrev_f32_e32", ["v_mov_b32 v2, 0x3e800000"], "0.5, v2", -0.25), - ("v_sub_f32_e64", ["v_mov_b32 v1, 0x40800000", "s_mov_b32 s0, 0x3fc00000"], "v1, s0", 2.5), - ("v_subrev_f32_e64", ["v_mov_b32 v1, 0x40800000", "s_mov_b32 s0, 0x3fc00000"], "v1, s0", -2.5), - ("v_sub_f32_e64", ["v_mov_b32 v1, 0x3f000000"], "v1, -1.0", 1.5), - ("v_subrev_f32_e64", ["v_mov_b32 v1, 0x3f000000"], "v1, -1.0", -1.5), - ] - for op, setup, operands, exp in cases: - with self.subTest(op=op, operands=operands): - got, _ = run_binary(op, 0, 0, setup=setup, operands=operands) - self.assertEqual(got, f32_to_bits(exp)) - - def test_vop3_modifiers(self): - # v1 = 1.5, v2 = -2.25 - a, b = f32_to_bits(1.5), f32_to_bits(-2.25) - cases = [ - # neg / abs on sources - ("v_sub_f32_e64", "-v1, v2", -1.5 - (-2.25)), # 0.75 - ("v_sub_f32_e64", "v1, -v2", 1.5 - 2.25), # -0.75 - ("v_sub_f32_e64", "|v1|, |v2|", 1.5 - 2.25), # -0.75 - ("v_sub_f32_e64", "-|v1|, -|v2|", -1.5 - (-2.25)), # 0.75 - ("v_subrev_f32_e64", "-v1, v2", -2.25 - (-1.5)), # -0.75 - ("v_subrev_f32_e64", "v1, |v2|", 2.25 - 1.5), # 0.75 - # clamp, mul:2, div:2 - ("v_sub_f32_e64", "v1, v2 clamp", 1.0), # 3.75 -> 1.0 - ("v_subrev_f32_e64", "v1, v2 clamp", 0.0), # -3.75 -> 0.0 - ("v_sub_f32_e64", "v1, v2 mul:2", 7.5), # 3.75 * 2 - ("v_sub_f32_e64", "v1, v2 div:2", 1.875), # 3.75 / 2 - ("v_subrev_f32_e64", "v1, v2 mul:2", -7.5), # -3.75 * 2 - ("v_subrev_f32_e64", "v1, v2 div:2", -1.875), # -3.75 / 2 - ] - for op, operands, exp in cases: - with self.subTest(op=op, operands=operands): - got, _ = run_binary(op, a, b, operands=operands) - self.assertEqual(got, f32_to_bits(exp)) - - # Verify omod applies before clamp: (1.5 - 0.0) = 1.5 -> div:2 = 0.75 -> clamp = 0.75 - # (if clamp ran before div:2, result would be 0.5). - got, _ = run_binary("v_sub_f32_e64", f32_to_bits(1.5), POS_ZERO, operands="v1, v2 div:2 clamp") - self.assertEqual(got, f32_to_bits(0.75)) - - -class StructuralEmissionTests(unittest.TestCase): - def test_subrev_swaps_opfsub_operands(self): - a, b = f32_to_bits(7.0), f32_to_bits(2.0) - _, spv_sub = run_binary("v_sub_f32", a, b) - _, spv_rev = run_binary("v_subrev_f32", a, b) - - m_sub = re.search(r"%\w+\s*=\s*OpFSub\s+%float\s+(%\w+)\s+(%\w+)", spv_sub) - m_rev = re.search(r"%\w+\s*=\s*OpFSub\s+%float\s+(%\w+)\s+(%\w+)", spv_rev) - self.assertIsNotNone(m_sub, "expected OpFSub in v_sub_f32 SPIR-V output") - self.assertIsNotNone(m_rev, "expected OpFSub in v_subrev_f32 SPIR-V output") - - # Trace each OpFSub operand back to its bitcasted constant word (%c_ or similar). - def operand_const(spv, ssa): - m = re.search(rf"{re.escape(ssa)}\s*=\s*OpBitcast\s+%float\s+(%\w+)", spv) - self.assertIsNotNone(m, f"expected OpBitcast for {ssa}") - return m.group(1) - - sub_lhs = operand_const(spv_sub, m_sub.group(1)) - sub_rhs = operand_const(spv_sub, m_sub.group(2)) - rev_lhs = operand_const(spv_rev, m_rev.group(1)) - rev_rhs = operand_const(spv_rev, m_rev.group(2)) - self.assertNotEqual(sub_lhs, sub_rhs) - self.assertEqual((rev_lhs, rev_rhs), (sub_rhs, sub_lhs)) - - def test_rounding_ops_emit_glsl_extinst(self): - expected_inst = { - "v_floor_f32": "Floor", - "v_ceil_f32": "Ceil", - "v_trunc_f32": "Trunc", - } - for op, glsl_name in expected_inst.items(): - with self.subTest(op=op): - _, spv = run_unary(op, f32_to_bits(1.5)) - self.assertRegex(spv, rf"%\w+\s*=\s*OpExtInst\s+%float\s+%glsl\s+{glsl_name}\s+%\w+") - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_valu_f32_transcendentals.py b/tests/semantic/test_valu_f32_transcendentals.py deleted file mode 100644 index c7c3b856c..000000000 --- a/tests/semantic/test_valu_f32_transcendentals.py +++ /dev/null @@ -1,233 +0,0 @@ -"""Translator-to-interpreter semantic tests for float32 transcendental VALU instructions: - - v_exp_f32 D = 2^S0 - v_log_f32 D = log2(S0) - v_sqrt_f32 D = sqrt(S0) - v_rsq_f32 D = 1 / sqrt(S0) - -Every test translates synthetic hand-written RDNA2 disassembly via tools/rdna2spirv.py and executes the emitted -SPIR-V in tests/semantic/spirv_mini_interp.py. Undefined domains (log2/rsq of x <= 0, sqrt of x < 0) are verified -to raise UnsupportedConstruct in spirv_mini_interp.py. Standard library only; no game data. -""" -import math -import os -import struct -import sys -import unittest - -HERE = os.path.dirname(os.path.abspath(__file__)) -if HERE not in sys.path: - sys.path.insert(0, HERE) - -import spirv_mini_interp as si # noqa: E402 -from support import mrt0_words, translate_lines # noqa: E402 - -POS_ZERO = 0x00000000 -NEG_ZERO = 0x80000000 -POS_INF = 0x7F800000 -NEG_INF = 0xFF800000 -QNAN = 0x7FC00000 - - -def f32_to_bits(x): - return struct.unpack(" 0 else POS_ZERO - return f32_to_bits(math.pow(2.0, x)) - - -def ref_log2(w): - x = bits_to_f32(w) - if math.isnan(x): - return w - if math.isinf(x): - return POS_INF - return f32_to_bits(math.log2(x)) - - -def ref_sqrt(w): - x = bits_to_f32(w) - if math.isnan(x): - return w - if x == 0.0: - return w - if math.isinf(x): - return POS_INF - return f32_to_bits(math.sqrt(x)) - - -def ref_rsq(w): - x = bits_to_f32(w) - if math.isnan(x): - return w - if math.isinf(x): - return POS_ZERO - return f32_to_bits(1.0 / math.sqrt(x)) - - -def run_ps(name, body_lines): - lines = list(body_lines) + ["exp mrt0 v0, v0, v0, v0 done vm", "s_endpgm"] - spv = translate_lines(name, lines) - words = mrt0_words(spv) - return words[0], spv - - -class ExactPowersAndSquaresTests(unittest.TestCase): - def test_v_exp_f32_powers_of_two(self): - for exp_val in (-126.0, -10.0, -2.0, -1.0, 0.0, 1.0, 2.0, 10.0, 127.0): - w = f32_to_bits(exp_val) - with self.subTest(exp_val=exp_val): - got, _ = run_ps("ps_exp_pow2", [f"v_mov_b32 v1, {w:#x}", "v_exp_f32 v0, v1"]) - self.assertEqual(got, ref_exp2(w)) - - def test_v_log_f32_powers_of_two(self): - for k in (-126, -4, -2, -1, 0, 1, 2, 10, 127): - w = f32_to_bits(math.ldexp(1.0, k)) - with self.subTest(k=k): - got, _ = run_ps("ps_log_pow2", [f"v_mov_b32 v1, {w:#x}", "v_log_f32 v0, v1"]) - self.assertEqual(got, f32_to_bits(float(k))) - - def test_v_sqrt_f32_perfect_squares(self): - for root in (0.0, 0.5, 1.0, 2.0, 3.0, 4.0, 25.0, 256.0): - w = f32_to_bits(root * root) - with self.subTest(root=root): - got, _ = run_ps("ps_sqrt_sq", [f"v_mov_b32 v1, {w:#x}", "v_sqrt_f32 v0, v1"]) - self.assertEqual(got, f32_to_bits(root)) - - def test_v_rsq_f32_reciprocal_squares(self): - cases = [(0.0625, 4.0), (0.25, 2.0), (1.0, 1.0), (4.0, 0.5), (16.0, 0.25), (64.0, 0.125)] - for x, expected in cases: - w = f32_to_bits(x) - with self.subTest(x=x): - got, _ = run_ps("ps_rsq_sq", [f"v_mov_b32 v1, {w:#x}", "v_rsq_f32 v0, v1"]) - self.assertEqual(got, f32_to_bits(expected)) - - -class NonPowerFiniteTests(unittest.TestCase): - def test_non_power_of_two_values(self): - cases = [ - ("v_exp_f32", (0.5, -0.5, 1.5, 3.25), ref_exp2), - ("v_log_f32", (3.0, 5.5, 10.0, 0.3), ref_log2), - ("v_sqrt_f32", (2.0, 3.0, 5.0, 0.75), ref_sqrt), - ("v_rsq_f32", (2.0, 3.0, 5.0, 0.75), ref_rsq), - ] - for op, inputs, ref_fn in cases: - for val in inputs: - w = f32_to_bits(val) - with self.subTest(op=op, val=val): - got, _ = run_ps("ps_trans_finite", [f"v_mov_b32 v1, {w:#x}", f"{op} v0, v1"]) - self.assertEqual(got, ref_fn(w)) - - -class SpecialValuesAndDomainsTests(unittest.TestCase): - def test_special_valid_values(self): - cases = [ - ("v_sqrt_f32", POS_ZERO, POS_ZERO), - ("v_sqrt_f32", NEG_ZERO, NEG_ZERO), - ("v_exp_f32", POS_INF, POS_INF), - ("v_exp_f32", NEG_INF, POS_ZERO), - ("v_log_f32", POS_INF, POS_INF), - ("v_sqrt_f32", POS_INF, POS_INF), - ("v_rsq_f32", POS_INF, POS_ZERO), - ] - for op, src_bits, expected_bits in cases: - with self.subTest(op=op, src=hex(src_bits)): - got, _ = run_ps("ps_trans_spec", [f"v_mov_b32 v1, {src_bits:#x}", f"{op} v0, v1"]) - self.assertEqual(got, expected_bits) - - def test_nan_propagation(self): - for op in ("v_exp_f32", "v_log_f32", "v_sqrt_f32", "v_rsq_f32"): - with self.subTest(op=op): - got, _ = run_ps("ps_trans_nan", [f"v_mov_b32 v1, {QNAN:#x}", f"{op} v0, v1"]) - self.assertTrue(math.isnan(bits_to_f32(got)), f"{op} did not propagate NaN: {got:#x}") - - def test_undefined_domains_raise_in_interpreter(self): - cases = [ - ("v_log_f32", POS_ZERO), - ("v_log_f32", f32_to_bits(-1.0)), - ("v_sqrt_f32", f32_to_bits(-1.0)), - ("v_rsq_f32", POS_ZERO), - ("v_rsq_f32", f32_to_bits(-1.0)), - ] - for op, src_bits in cases: - with self.subTest(op=op, src=hex(src_bits)): - with self.assertRaises(si.UnsupportedConstruct): - run_ps("ps_trans_undef", [f"v_mov_b32 v1, {src_bits:#x}", f"{op} v0, v1"]) - - -class ModifiersAndOperandFormsTests(unittest.TestCase): - def test_vop3_src_and_output_modifiers(self): - w4 = f32_to_bits(4.0) - wn4 = f32_to_bits(-4.0) - w2 = f32_to_bits(2.0) - - got_abs, _ = run_ps("ps_sqrt_abs", [f"v_mov_b32 v1, {wn4:#x}", "v_sqrt_f32_e64 v0, |v1|"]) - self.assertEqual(got_abs, w2) - - got_neg, _ = run_ps("ps_exp_neg", [f"v_mov_b32 v1, {w2:#x}", "v_exp_f32_e64 v0, -v1"]) - self.assertEqual(got_neg, f32_to_bits(0.25)) - - got_clamp, _ = run_ps("ps_exp_clamp", [f"v_mov_b32 v1, {w2:#x}", "v_exp_f32_e64 v0, v1 clamp"]) - self.assertEqual(got_clamp, f32_to_bits(1.0)) - - got_mul2, _ = run_ps("ps_sqrt_mul2", [f"v_mov_b32 v1, {w4:#x}", "v_sqrt_f32_e64 v0, v1 mul:2"]) - self.assertEqual(got_mul2, w4) - - got_div2, _ = run_ps("ps_rsq_div2", [f"v_mov_b32 v1, {w4:#x}", "v_rsq_f32_e64 v0, v1 div:2"]) - self.assertEqual(got_div2, f32_to_bits(0.25)) - - def test_e32_e64_sgpr_inline_and_literal_operands(self): - w4 = f32_to_bits(4.0) - w16 = f32_to_bits(16.0) - for op, inline_s, lit_w, exp_inline, exp_lit in ( - ("v_exp_f32", "2.0", f32_to_bits(3.0), 4.0, 8.0), - ("v_log_f32", "4.0", w16, 2.0, 4.0), - ("v_sqrt_f32", "4.0", f32_to_bits(9.0), 2.0, 3.0), - ("v_rsq_f32", "4.0", w16, 0.5, 0.25), - ): - for suffix in ("", "_e32", "_e64"): - with self.subTest(op=op + suffix, form="sgpr"): - got, _ = run_ps("ps_trans_sgpr", [f"s_mov_b32 s0, {w4:#x}", f"{op}{suffix} v0, s0"]) - self.assertEqual(got, { - "v_exp_f32": f32_to_bits(16.0), - "v_log_f32": f32_to_bits(2.0), - "v_sqrt_f32": f32_to_bits(2.0), - "v_rsq_f32": f32_to_bits(0.5), - }[op]) - with self.subTest(op=op + suffix, form="inline"): - got, _ = run_ps("ps_trans_inline", [f"{op}{suffix} v0, {inline_s}"]) - self.assertEqual(got, f32_to_bits(exp_inline)) - with self.subTest(op=op + suffix, form="literal"): - got, _ = run_ps("ps_trans_lit", [f"{op}{suffix} v0, {lit_w:#x}"]) - self.assertEqual(got, f32_to_bits(exp_lit)) - - -class SpirvStructureTests(unittest.TestCase): - def test_emitted_glsl_ext_insts(self): - for op, glsl_name in ( - ("v_exp_f32", "Exp2"), - ("v_log_f32", "Log2"), - ("v_sqrt_f32", "Sqrt"), - ("v_rsq_f32", "InverseSqrt"), - ): - with self.subTest(op=op): - _, spv = run_ps("ps_trans_struct", ["v_mov_b32 v1, 1.0", f"{op} v0, v1"]) - self.assertIn(f"= OpExtInst %float %glsl {glsl_name}", spv) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_valu_fma_f16.py b/tests/semantic/test_valu_fma_f16.py deleted file mode 100644 index d9d7b5c7b..000000000 --- a/tests/semantic/test_valu_fma_f16.py +++ /dev/null @@ -1,165 +0,0 @@ -"""v_fma_f16 (RDNA2 VOP3): D.f16 = S0.f16 * S1.f16 + S2.f16 with a single rounding (binary16, nearest even). - -Every case is translated by tools/rdna2spirv.py and executed with tests/semantic/spirv_mini_interp.py; the expected -word is written down by hand (from the ISA) next to each case, rechecked against the plain-Python binary16 reference in -tests/semantic/f16_ref.py, and extended with seeded random operands. Covers the fused (not double-rounded) result, op_sel -for all three sources and the destination, SGPR / literal / inline-constant sources, neg/abs, omod and clamp. -Standard library only: no GPU, no LLVM, no game data. -""" -import os -import random -import sys -import unittest - -HERE = os.path.dirname(os.path.abspath(__file__)) -sys.dont_write_bytecode = True -sys.path.insert(0, HERE) -import support # noqa: E402 -from f16_ref import OLD, ref_fma, same_f16, scale # noqa: E402 - -ONE, TWO, THREE, HALF, QUARTER = 0x3C00, 0x4000, 0x4200, 0x3800, 0x3400 -MAXH, INF, NINF, QNAN = 0x7BFF, 0x7C00, 0xFC00, 0x7E00 -MIN_NORMAL, MIN_SUB, MAX_SUB = 0x0400, 0x0001, 0x03FF - - -def run(line, seeds, old=OLD, hi=0x5A5A): - """Run one instruction on a one-lane pixel shader and return v0 as exported to mrt0. - - `seeds` maps a register ("v1", "s2", ...) to the word it starts with; a value that fits in 16 bits gets `hi` in its - upper half, so reading the wrong half of a source shows. v0 starts as `old`. - """ - prog = [f"v_mov_b32 v0, {old:#x}"] - for reg, w in seeds.items(): - w = w if w > 0xFFFF else (hi << 16) | w - prog.append(f"{'s' if reg[0] == 's' else 'v'}_mov_b32 {reg}, {w:#x}") - prog += [line, "exp mrt0 v0, v0, v0, v0 done vm", "s_endpgm"] - return support.mrt0_words(support.translate_lines("ps_fma_f16", prog))[0] - - -# (src0, src1, src2, D), written by hand. -CASES = [ - (TWO, THREE, ONE, 0x4700), # 2 * 3 + 1 = 7 - (0x3E00, TWO, 0xC200, 0x0000), # 1.5 * 2 + -3 = +0 - (HALF, HALF, QUARTER, HALF), # 0.5 * 0.5 + 0.25 = 0.5 - (0x3C01, 0x3C01, 0xBC02, 0x0010), # (1+2^-10)^2 - (1+2^-9) = 2^-20 exactly; unfused it would be 0 - (0x3C01, 0x3C01, 0xBC00, 0x1800), # 2^-9 + 2^-20: half a quantum of 2^-9 ties to even - (MAXH, TWO, 0xFBFF, MAXH), # 131008 - 65504: the product alone would overflow, the fused sum does not - (0x8000, ONE, 0x8000, 0x8000), # -0 * 1 + -0 = -0 - (0x0000, ONE, 0x8000, 0x0000), # +0 * 1 + -0 = +0 - (0x8000, ONE, 0x0000, 0x0000), # -0 * 1 + +0 = +0 - (ONE, ONE, MIN_SUB, ONE), # 1 + 2^-24 rounds back to 1 - (MIN_SUB, HALF, MIN_SUB, 0x0002), # 1.5 quanta ties to even: 2 quanta - (MIN_NORMAL, MIN_NORMAL, 0x0000, 0x0000), # 2^-28 underflows to +0 - (INF, 0x0000, ONE, QNAN), # inf * 0 = NaN - (INF, ONE, NINF, QNAN), # inf - inf = NaN - (INF, TWO, ONE, INF), - (ONE, ONE, QNAN, QNAN), -] - -SPECIAL = [0x0000, 0x8000, ONE, 0xBC00, TWO, 0xC000, HALF, 0xB800, THREE, 0x3E00, MAXH, 0xFBFF, INF, NINF, QNAN, - MIN_NORMAL, MIN_SUB, 0x8001, MAX_SUB, 0x3C01, 0x3BFF, 0xBC02, 0x6800, 0x6801, 0x4C00] - - -class FmaF16(unittest.TestCase): - def test_hand_written_table_matches_reference(self): - for a, b, c, want in CASES: - self.assertTrue(same_f16(ref_fma(a, b, c), want), (hex(a), hex(b), hex(c), hex(ref_fma(a, b, c)))) - - def test_vgpr_sources_write_low_half_and_keep_high_half(self): - for a, b, c, want in CASES: - with self.subTest(a=hex(a), b=hex(b), c=hex(c)): - got = run("v_fma_f16 v0, v1, v2, v3", {"v1": a, "v2": b, "v3": c}) - self.assertEqual(got >> 16, OLD >> 16) - self.assertTrue(same_f16(got & 0xFFFF, want), hex(got)) - - def test_sgpr_and_literal_sources(self): - for a, b, c, want in CASES[:12]: - forms = [ - ("sgpr all", "v_fma_f16 v0, s1, s2, s3", {"s1": a, "s2": b, "s3": c}), - ("sgpr src0 and src2", "v_fma_f16 v0, s1, v2, s3", {"s1": a, "v2": b, "s3": c}), - ("literal src0", f"v_fma_f16 v0, {a:#x}, v2, v3", {"v2": b, "v3": c}), - ("literal src2", f"v_fma_f16 v0, v1, v2, {c:#x}", {"v1": a, "v2": b}), - ] - for form, line, seeds in forms: - with self.subTest(a=hex(a), b=hex(b), c=hex(c), form=form): - got = run(line, seeds) - self.assertEqual(got >> 16, OLD >> 16) - self.assertTrue(same_f16(got & 0xFFFF, want), hex(got)) - - def test_inline_constants(self): - # (src0 inline constant, its binary16 value, v1 = src1, v2 = src2, D), by hand - for text, a, b, c, want in (("2.0", TWO, 0x3E00, ONE, 0x4400), # 2 * 1.5 + 1 = 4 - ("-1.0", 0xBC00, HALF, HALF, 0x0000), # -0.5 + 0.5 - ("0.5", HALF, 0x4400, 0xBC00, ONE), # 0.5 * 4 - 1 = 1 - ("4.0", 0x4400, QUARTER, QUARTER, 0x3D00)): # 4 * 0.25 + 0.25 = 1.25 - with self.subTest(const=text): - self.assertEqual(run(f"v_fma_f16 v0, {text}, v1, v2", {"v1": b, "v2": c}) & 0xFFFF, want) - self.assertEqual(ref_fma(a, b, c), want) - self.assertEqual(run("v_fma_f16 v0, v1, v2, 1.0", {"v1": TWO, "v2": THREE}) & 0xFFFF, 0x4700) - - def test_op_sel_selects_source_and_destination_halves(self): - # src0 = (lo 1.0, hi 3.0), src1 = (lo 0.5, hi -0.25), src2 = (lo 0.25, hi -1.0); D by hand for each - # (src0 half, src1 half, src2 half): a * b + c. - s0, s1, s2 = (THREE << 16) | ONE, (0xB400 << 16) | HALF, (0xBC00 << 16) | QUARTER - expect_lo = { - (0, 0, 0): 0x3A00, # 1 * 0.5 + 0.25 = 0.75 - (0, 0, 1): 0xB800, # 1 * 0.5 - 1 = -0.5 - (0, 1, 0): 0x0000, # 1 * -0.25 + 0.25 = +0 - (0, 1, 1): 0xBD00, # -0.25 - 1 = -1.25 - (1, 0, 0): 0x3F00, # 3 * 0.5 + 0.25 = 1.75 - (1, 0, 1): 0x3800, # 1.5 - 1 = 0.5 - (1, 1, 0): 0xB800, # -0.75 + 0.25 = -0.5 - (1, 1, 1): 0xBF00, # -0.75 - 1 = -1.75 - } - for (h0, h1, h2), want in expect_lo.items(): - for dh in (0, 1): - expect = ((want << 16) | (OLD & 0xFFFF)) if dh else ((OLD & 0xFFFF0000) | want) - with self.subTest(op_sel=(h0, h1, h2, dh)): - got = run(f"v_fma_f16 v0, v1, v2, v3 op_sel:[{h0},{h1},{h2},{dh}]", {"v1": s0, "v2": s1, "v3": s2}) - self.assertEqual(got, expect) - - def test_neg_and_abs_source_modifiers(self): - # v1 = 2.0, v2 = 0.5, v3 = -0.25; (operand text, D) by hand - for ops, want in (("v1, v2, v3", 0x3A00), # 1 - 0.25 = 0.75 - ("-v1, v2, v3", 0xBD00), # -1 - 0.25 = -1.25 - ("v1, -v2, v3", 0xBD00), # -1 - 0.25 - ("|v1|, |v2|, |v3|", 0x3D00), # 1 + 0.25 - ("v1, v2, -v3", 0x3D00), # 1 + 0.25 - ("v1, v2, -|v3|", 0x3A00), # 1 - 0.25 - ("-|v1|, v2, |v3|", 0xBA00)): # -1 + 0.25 = -0.75 - with self.subTest(ops=ops): - got = run(f"v_fma_f16 v0, {ops}", {"v1": TWO, "v2": HALF, "v3": 0xB400}) - self.assertEqual(got & 0xFFFF, want) - - def test_output_modifiers_and_clamp(self): - # #4542, measured on gfx1036: an f16 destination ignores omod (mul:2/mul:4/div:2) under the game's MODE - # (IEEE=0, f16 denormals kept) and keeps clamp (docs/design.md, f16 output modifiers). - # unmodified result: 1.5 * 2 + -1 = 2.0; clamp limits it to [0, 1] - for suffix, want in ((" mul:2", 0x4000), (" mul:4", 0x4000), (" div:2", 0x4000), (" clamp", ONE)): - with self.subTest(mod=suffix): - got = run("v_fma_f16 v0, v1, v2, v3" + suffix, {"v1": 0x3E00, "v2": TWO, "v3": 0xBC00}) - self.assertEqual(got & 0xFFFF, want) - for (a, b, c), suffix, want in (((HALF, HALF, 0x0000), " clamp", QUARTER), # inside [0, 1]: unchanged - ((HALF, 0xB800, 0x0000), " clamp", 0x0000), # -0.25 -> +0 - ((ONE, 0x3E00, 0x0000), " div:2 clamp", ONE), # 1.5 -> 1 - ((0x3A00, ONE, 0x0000), " mul:2 clamp", 0x3A00)): # 0.75, unscaled - with self.subTest(a=hex(a), b=hex(b), c=hex(c), mod=suffix): - got = run("v_fma_f16 v0, v1, v2, v3" + suffix, {"v1": a, "v2": b, "v3": c}) - self.assertEqual(got & 0xFFFF, want) - for suffix, f in ((" mul:2", 2.0), (" mul:4", 4.0), (" div:2", 0.5)): - got = run("v_fma_f16 v0, v1, v2, v3" + suffix, {"v1": 0x4900, "v2": 0xC100, "v3": 0x4C00}) # 10 * -2.5 + 16 - self.assertEqual(got & 0xFFFF, ref_fma(0x4900, 0xC100, 0x4C00)) - - def test_random_operands(self): - rng = random.Random(0xF3A16) - pool = SPECIAL + [rng.getrandbits(16) for _ in range(40)] - for _ in range(160): - a, b, c = (rng.choice(pool) if rng.random() < 0.5 else rng.getrandbits(16) for _ in range(3)) - with self.subTest(a=hex(a), b=hex(b), c=hex(c)): - got = run("v_fma_f16 v0, v1, v2, v3", {"v1": a, "v2": b, "v3": c}) - self.assertEqual(got >> 16, OLD >> 16) - self.assertTrue(same_f16(got & 0xFFFF, ref_fma(a, b, c)), (hex(got), hex(ref_fma(a, b, c)))) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_valu_fma_f64.py b/tests/semantic/test_valu_fma_f64.py deleted file mode 100644 index a109758f8..000000000 --- a/tests/semantic/test_valu_fma_f64.py +++ /dev/null @@ -1,1750 +0,0 @@ -from __future__ import annotations - -"""Semantic interpreter tests and reference mathematical oracle for RDNA2 v_fma_f64. - -Tests the double-precision fused multiply-add instruction: - v_fma_f64 D, S0, S1, S2 -Lowered semantics: - D = (S0 * S1) + S2 -with single-rounding precision per IEEE 754-2008 (binary64). -Supports input modifiers: - - abs (|src|: clear sign bit) - - neg (-src: invert sign bit) -Supports output modifiers: - - clamp: saturates result to [0.0, 1.0], with NaN clamped to +0.0 - - omod: mul:2, mul:4, div:2 -Architectural model: - 64-bit floating point registers mapped onto aligned VGPR/SGPR pairs: - [lo: 32-bit dword, hi: 32-bit dword]. -""" - -from enum import Enum, auto -from fractions import Fraction -import math -import struct -import sys -import unittest - -# IEEE 754 double precision bitwise constants -F64_POS_ZERO = 0x0000000000000000 -F64_NEG_ZERO = 0x8000000000000000 -F64_ONE = 0x3FF0000000000000 -F64_NEG_ONE = 0xBFF0000000000000 -F64_TWO = 0x4000000000000000 -F64_HALF = 0x3FE0000000000000 -F64_POS_INF = 0x7FF0000000000000 -F64_NEG_INF = 0xFFF0000000000000 -F64_CANONICAL_QNAN = 0x7FF8000000000000 -F64_SNAN = 0x7FF0000000000001 -F64_SUB_MIN = 0x0000000000000001 -F64_SUB_MAX = 0x000FFFFFFFFFFFFF -F64_MIN_NORMAL = 0x0010000000000000 -F64_MAX_NORMAL = 0x7FEFFFFFFFFFFFFF - -MASK32 = 0xFFFFFFFF -MASK64 = 0xFFFFFFFFFFFFFFFF - - -def f64_to_u64(val: float) -> int: - """Pack Python float (IEEE 754 binary64) into unsigned 64-bit integer.""" - return struct.unpack(" float: - """Unpack unsigned 64-bit integer into Python float (IEEE 754 binary64).""" - return struct.unpack(" tuple[int, int]: - """Split 64-bit word into (low 32-bit dword, high 32-bit dword).""" - return val & MASK32, (val >> 32) & MASK32 - - -def dwords_to_u64(lo: int, hi: int) -> int: - """Combine (low 32-bit dword, high 32-bit dword) into 64-bit word.""" - return (lo & MASK32) | ((hi & MASK32) << 32) - - -def apply_src_mods_u64(val_u64: int, *, neg: bool = False, abs_: bool = False) -> int: - """Apply bit-exact RDNA2 source modifiers (|src|, -src) to a 64-bit float bit pattern.""" - bits = val_u64 & MASK64 - if abs_: - bits &= ~F64_NEG_ZERO # clear sign bit - if neg: - bits ^= F64_NEG_ZERO # invert sign bit - return bits - - -def apply_clamp_f64(val: float) -> float: - """Apply RDNA2 clamp modifier [0.0, 1.0] to float64, mapping NaNs to +0.0.""" - if math.isnan(val): - return 0.0 - if val < 0.0: - return 0.0 - if val > 1.0: - return 1.0 - return val - - -def apply_omod_f64(val: float, omod: int) -> float: - """Apply RDNA2 output modifier: 0: none, 1: mul:2, 2: mul:4, 3: div:2.""" - if omod == 0: - return val - elif omod == 1: - return val * 2.0 - elif omod == 2: - return val * 4.0 - elif omod == 3: - return val * 0.5 - else: - raise ValueError(f"Invalid omod value: {omod}") - - -def raw_fma_f64(v0: float, v1: float, v2: float) -> float: - """Compute exact IEEE 754 double precision FMA (v0 * v1) + v2.""" - if math.isnan(v0) or math.isnan(v1) or math.isnan(v2): - return math.nan - - if (math.isinf(v0) and v1 == 0.0) or (v0 == 0.0 and math.isinf(v1)): - return math.nan - - p_inf = math.isinf(v0) or math.isinf(v1) - if p_inf: - p_sign = -1.0 if (math.copysign(1.0, v0) * math.copysign(1.0, v1) < 0) else 1.0 - if math.isinf(v2): - v2_sign = math.copysign(1.0, v2) - if p_sign != v2_sign: - return math.nan - return math.copysign(float("inf"), p_sign) - - if math.isinf(v2): - return v2 - - if v0 == 0.0 or v1 == 0.0: - prod_sign = -1.0 if (math.copysign(1.0, v0) * math.copysign(1.0, v1) < 0) else 1.0 - if v2 == 0.0: - v2_sign = math.copysign(1.0, v2) - if prod_sign < 0 and v2_sign < 0: - return -0.0 - return 0.0 - return v2 - - frac = Fraction(v0) * Fraction(v1) + Fraction(v2) - if frac == 0: - return 0.0 - try: - return float(frac) - except OverflowError: - return math.copysign(float("inf"), 1.0 if frac > 0 else -1.0) - - -def ref_fma_f64( - s0: float, - s1: float, - s2: float, - *, - neg0: bool = False, - neg1: bool = False, - neg2: bool = False, - abs0: bool = False, - abs1: bool = False, - abs2: bool = False, - clamp: bool = False, - omod: int = 0, -) -> float: - """Reference mathematical oracle for v_fma_f64 calculating (s0 * s1) + s2 in binary64.""" - u0 = apply_src_mods_u64(f64_to_u64(s0), neg=neg0, abs_=abs0) - u1 = apply_src_mods_u64(f64_to_u64(s1), neg=neg1, abs_=abs1) - u2 = apply_src_mods_u64(f64_to_u64(s2), neg=neg2, abs_=abs2) - - v0 = u64_to_f64(u0) - v1 = u64_to_f64(u1) - v2 = u64_to_f64(u2) - - res = raw_fma_f64(v0, v1, v2) - - if omod != 0: - res = apply_omod_f64(res, omod) - if clamp: - res = apply_clamp_f64(res) - - return res - - -def ref_fma_f64_u64( - u0: int, - u1: int, - u2: int, - *, - neg0: bool = False, - neg1: bool = False, - neg2: bool = False, - abs0: bool = False, - abs1: bool = False, - abs2: bool = False, - clamp: bool = False, - omod: int = 0, -) -> int: - """Bit-exact reference mathematical oracle for v_fma_f64 using 64-bit integer words.""" - res_f = ref_fma_f64( - u64_to_f64(u0), - u64_to_f64(u1), - u64_to_f64(u2), - neg0=neg0, - neg1=neg1, - neg2=neg2, - abs0=abs0, - abs1=abs1, - abs2=abs2, - clamp=clamp, - omod=omod, - ) - return f64_to_u64(res_f) - - -class RegisterPair: - """Architectural model of a 64-bit register pair (e.g. v[0:1] or s[0:1]).""" - - def __init__(self, lo: int = 0, hi: int = 0) -> None: - self.lo = lo & MASK32 - self.hi = hi & MASK32 - - @classmethod - def from_u64(cls, val: int) -> RegisterPair: - lo, hi = u64_to_dwords(val) - return cls(lo, hi) - - @classmethod - def from_f64(cls, val: float) -> RegisterPair: - return cls.from_u64(f64_to_u64(val)) - - @property - def as_u64(self) -> int: - return dwords_to_u64(self.lo, self.hi) - - @property - def as_f64(self) -> float: - return u64_to_f64(self.as_u64) - - def set_u64(self, val: int) -> None: - self.lo, self.hi = u64_to_dwords(val) - - def set_f64(self, val: float) -> None: - self.set_u64(f64_to_u64(val)) - - def __repr__(self) -> str: - return f"RegisterPair(lo={self.lo:#010x}, hi={self.hi:#010x}, f64={self.as_f64})" - - def __eq__(self, other: object) -> bool: - if not isinstance(other, RegisterPair): - return NotImplemented - return self.lo == other.lo and self.hi == other.hi - - -class TestFmaF64MathematicalOracle(unittest.TestCase): - """Test suite for reference mathematical oracle and architectural register models.""" - - def test_basic_fma_identities(self): - # 1.0 * 1.0 + 0.0 == 1.0 - self.assertEqual(ref_fma_f64(1.0, 1.0, 0.0), 1.0) - # 2.0 * 3.0 + 4.0 == 10.0 - self.assertEqual(ref_fma_f64(2.0, 3.0, 4.0), 10.0) - # -2.5 * 4.0 + 1.25 == -8.75 - self.assertEqual(ref_fma_f64(-2.5, 4.0, 1.25), -8.75) - # 0.0 * 100.0 + 5.5 == 5.5 - self.assertEqual(ref_fma_f64(0.0, 100.0, 5.5), 5.5) - - def test_fused_precision_single_rounding(self): - # FMA retains full intermediate product precision without intermediate rounding. - # Let a = 1.0 + 2**-52, b = 1.0 - 2**-52, c = -1.0 - # (a * b) = 1.0 - 2**-104 - # Unfused: (a * b) rounds to 1.0, so (a * b) - 1.0 == 0.0 - # Fused: (a * b) - 1.0 retains -2**-104, rounding to -2**-104 != 0.0 - a = 1.0 + (2.0 ** -52) - b = 1.0 - (2.0 ** -52) - c = -1.0 - unfused = (a * b) + c - fused = ref_fma_f64(a, b, c) - self.assertEqual(unfused, 0.0) - self.assertNotEqual(fused, 0.0) - self.assertEqual(fused, -(2.0 ** -104)) - - def test_source_modifiers(self): - # abs(|src|): clears sign bit - self.assertEqual(ref_fma_f64(-3.5, 2.0, 1.0, abs0=True), 8.0) - self.assertEqual(ref_fma_f64(3.5, -2.0, 1.0, abs1=True), 8.0) - self.assertEqual(ref_fma_f64(3.5, 2.0, -1.0, abs2=True), 8.0) - - # neg(-src): inverts sign bit - self.assertEqual(ref_fma_f64(3.5, 2.0, 1.0, neg0=True), -6.0) - self.assertEqual(ref_fma_f64(3.5, 2.0, 1.0, neg1=True), -6.0) - self.assertEqual(ref_fma_f64(3.5, 2.0, 1.0, neg2=True), 6.0) - - # combined neg and abs: -|src| - self.assertEqual(ref_fma_f64(-3.5, 2.0, 1.0, neg0=True, abs0=True), -6.0) - - def test_output_modifiers_clamp_and_omod(self): - # clamp saturates to [0.0, 1.0] - self.assertEqual(ref_fma_f64(2.0, 3.0, 0.0, clamp=True), 1.0) - self.assertEqual(ref_fma_f64(-2.0, 3.0, 0.0, clamp=True), 0.0) - self.assertEqual(ref_fma_f64(0.5, 1.0, 0.25, clamp=True), 0.75) - - # omod: mul:2, mul:4, div:2 - self.assertEqual(ref_fma_f64(1.5, 2.0, 0.5, omod=1), 7.0) # (3.5) * 2 = 7.0 - self.assertEqual(ref_fma_f64(1.5, 2.0, 0.5, omod=2), 14.0) # (3.5) * 4 = 14.0 - self.assertEqual(ref_fma_f64(1.5, 2.0, 0.5, omod=3), 1.75) # (3.5) * 0.5 = 1.75 - - # omod combined with clamp: (omod applies before clamp) - self.assertEqual(ref_fma_f64(0.2, 2.0, 0.0, omod=1, clamp=True), 0.8) - self.assertEqual(ref_fma_f64(0.4, 2.0, 0.0, omod=2, clamp=True), 1.0) - - def test_register_pair_architecture(self): - rp = RegisterPair.from_f64(1.0) - self.assertEqual(rp.as_f64, 1.0) - self.assertEqual(rp.as_u64, F64_ONE) - self.assertEqual(rp.lo, 0x00000000) - self.assertEqual(rp.hi, 0x3FF00000) - - rp.set_f64(-2.0) - self.assertEqual(rp.as_f64, -2.0) - self.assertEqual(rp.hi, 0xC0000000) - - # bit-exact oracle roundtrip - u_res = ref_fma_f64_u64(F64_TWO, F64_HALF, F64_ONE) - self.assertEqual(u_res, f64_to_u64(2.0)) - - -class Opcode(Enum): - V_FMA_F64 = "v_fma_f64" - - -class OperandKind(Enum): - VGPR_PAIR = auto() - SGPR_PAIR = auto() - INLINE_CONST = auto() - LITERAL_CONST = auto() - - -class TypeKind(Enum): - FLOAT64 = "f64" - UINT64 = "u64" - UINT32 = "u32" - - -class OMod(Enum): - NONE = 0 - MUL2 = 1 - MUL4 = 2 - DIV2 = 3 - - def to_asm(self) -> str: - if self == OMod.MUL2: - return "mul:2" - elif self == OMod.MUL4: - return "mul:4" - elif self == OMod.DIV2: - return "div:2" - return "" - - -class ASTOperand: - """Symbolic AST operand representing a register pair, constant, or literal with modifiers.""" - - def __init__( - self, - kind: OperandKind, - index: int = 0, - value: float | int | None = None, - *, - neg: bool = False, - abs_: bool = False, - type_kind: TypeKind = TypeKind.FLOAT64, - ) -> None: - self.kind = kind - self.index = index - self.value = value - self.neg = neg - self.abs_ = abs_ - self.type_kind = type_kind - - @classmethod - def vgpr(cls, index: int, *, neg: bool = False, abs_: bool = False) -> ASTOperand: - return cls(OperandKind.VGPR_PAIR, index=index, neg=neg, abs_=abs_) - - @classmethod - def sgpr(cls, index: int, *, neg: bool = False, abs_: bool = False) -> ASTOperand: - return cls(OperandKind.SGPR_PAIR, index=index, neg=neg, abs_=abs_) - - @classmethod - def inline_const(cls, value: float, *, neg: bool = False, abs_: bool = False) -> ASTOperand: - return cls(OperandKind.INLINE_CONST, value=value, neg=neg, abs_=abs_) - - @classmethod - def literal_const(cls, value: float, *, neg: bool = False, abs_: bool = False) -> ASTOperand: - return cls(OperandKind.LITERAL_CONST, value=value, neg=neg, abs_=abs_) - - def disasm(self) -> str: - if self.kind == OperandKind.VGPR_PAIR: - body = f"v[{self.index}:{self.index + 1}]" - elif self.kind == OperandKind.SGPR_PAIR: - body = f"s[{self.index}:{self.index + 1}]" - elif self.kind in (OperandKind.INLINE_CONST, OperandKind.LITERAL_CONST): - body = str(self.value) - else: - raise ValueError(f"Unknown operand kind: {self.kind}") - - if self.abs_: - body = f"|{body}|" - if self.neg: - body = f"-{body}" - return body - - def __repr__(self) -> str: - return f"ASTOperand({self.disasm()}, type={self.type_kind.value})" - - -class ASTInstruction: - """Symbolic AST instruction representation for v_fma_f64.""" - - def __init__( - self, - opcode: Opcode, - dst: ASTOperand, - src0: ASTOperand, - src1: ASTOperand, - src2: ASTOperand, - *, - clamp: bool = False, - omod: OMod = OMod.NONE, - ) -> None: - self.opcode = opcode - self.dst = dst - self.src0 = src0 - self.src1 = src1 - self.src2 = src2 - self.clamp = clamp - self.omod = omod - - def validate(self) -> None: - if self.opcode != Opcode.V_FMA_F64: - raise ValueError(f"Invalid opcode for v_fma_f64 AST: {self.opcode}") - if self.dst.kind != OperandKind.VGPR_PAIR: - raise TypeError("Destination must be a VGPR pair") - if self.dst.type_kind != TypeKind.FLOAT64: - raise TypeError(f"Destination type must be FLOAT64, got {self.dst.type_kind}") - if not (0 <= self.dst.index <= 254): - raise ValueError(f"Destination VGPR pair index out of range: {self.dst.index}") - if self.dst.neg or self.dst.abs_: - raise ValueError("Destination operand cannot have neg/abs modifiers") - - for i, src in enumerate((self.src0, self.src1, self.src2)): - if src.type_kind != TypeKind.FLOAT64: - raise TypeError(f"Source operand {i} type must be FLOAT64, got {src.type_kind}") - if src.kind == OperandKind.VGPR_PAIR and not (0 <= src.index <= 254): - raise ValueError(f"Source {i} VGPR pair index out of range: {src.index}") - if src.kind == OperandKind.SGPR_PAIR and not (0 <= src.index <= 104): - raise ValueError(f"Source {i} SGPR pair index out of range: {src.index}") - - def disasm(self) -> str: - parts = [ - self.opcode.value, - f"{self.dst.disasm()},", - f"{self.src0.disasm()},", - f"{self.src1.disasm()},", - self.src2.disasm(), - ] - if self.omod != OMod.NONE: - parts.append(self.omod.to_asm()) - if self.clamp: - parts.append("clamp") - return " ".join(parts) - - def __repr__(self) -> str: - return f"ASTInstruction({self.disasm()})" - - -class TypedExpr: - """Base class for typed symbolic expressions.""" - - def __init__(self, type_kind: TypeKind = TypeKind.FLOAT64) -> None: - self.type_kind = type_kind - - def evaluate(self, env: dict[str, float]) -> float: - raise NotImplementedError - - def simplify(self) -> TypedExpr: - return self - - -class VariableExpr(TypedExpr): - """Named variable in symbolic expression tree (e.g. representing a register value).""" - - def __init__(self, name: str, type_kind: TypeKind = TypeKind.FLOAT64) -> None: - super().__init__(type_kind) - self.name = name - - def evaluate(self, env: dict[str, float]) -> float: - if self.name not in env: - raise KeyError(f"Variable {self.name} not found in evaluation environment") - return env[self.name] - - def __repr__(self) -> str: - return f"Var({self.name})" - - -class ConstantExpr(TypedExpr): - """Constant literal in symbolic expression tree.""" - - def __init__(self, value: float, type_kind: TypeKind = TypeKind.FLOAT64) -> None: - super().__init__(type_kind) - self.value = value - - def evaluate(self, env: dict[str, float]) -> float: - return self.value - - def __repr__(self) -> str: - return f"Const({self.value})" - - -class UnaryOpExpr(TypedExpr): - """Unary modifier applied to a typed expression ('neg' or 'abs').""" - - def __init__(self, op: str, expr: TypedExpr, type_kind: TypeKind = TypeKind.FLOAT64) -> None: - super().__init__(type_kind) - if op not in ("neg", "abs"): - raise ValueError(f"Unknown unary operator: {op}") - self.op = op - self.expr = expr - - def evaluate(self, env: dict[str, float]) -> float: - val = self.expr.evaluate(env) - if self.op == "abs": - return math.fabs(val) - elif self.op == "neg": - return -val - return val - - def simplify(self) -> TypedExpr: - sub = self.expr.simplify() - if isinstance(sub, ConstantExpr): - if self.op == "abs": - return ConstantExpr(math.fabs(sub.value), self.type_kind) - elif self.op == "neg": - return ConstantExpr(-sub.value, self.type_kind) - return UnaryOpExpr(self.op, sub, self.type_kind) - - def __repr__(self) -> str: - return f"{self.op}({self.expr})" - - -class FMAExpr(TypedExpr): - """Symbolic FMA ternary typed expression: (src0 * src1) + src2 with modifiers.""" - - def __init__( - self, - src0: TypedExpr, - src1: TypedExpr, - src2: TypedExpr, - *, - clamp: bool = False, - omod: OMod = OMod.NONE, - type_kind: TypeKind = TypeKind.FLOAT64, - ) -> None: - super().__init__(type_kind) - self.src0 = src0 - self.src1 = src1 - self.src2 = src2 - self.clamp = clamp - self.omod = omod - - def evaluate(self, env: dict[str, float]) -> float: - v0 = self.src0.evaluate(env) - v1 = self.src1.evaluate(env) - v2 = self.src2.evaluate(env) - return ref_fma_f64(v0, v1, v2, clamp=self.clamp, omod=self.omod.value) - - def simplify(self) -> TypedExpr: - s0 = self.src0.simplify() - s1 = self.src1.simplify() - s2 = self.src2.simplify() - if isinstance(s0, ConstantExpr) and isinstance(s1, ConstantExpr) and isinstance(s2, ConstantExpr): - res = ref_fma_f64(s0.value, s1.value, s2.value, clamp=self.clamp, omod=self.omod.value) - return ConstantExpr(res, self.type_kind) - return FMAExpr(s0, s1, s2, clamp=self.clamp, omod=self.omod, type_kind=self.type_kind) - - def __repr__(self) -> str: - return f"FMA({self.src0}, {self.src1}, {self.src2}, clamp={self.clamp}, omod={self.omod.name})" - - -class TestFmaF64SymbolicAST(unittest.TestCase): - """Test suite for symbolic AST opcode definitions and typed expressions.""" - - def test_ast_construction_and_validation(self): - inst = ASTInstruction( - opcode=Opcode.V_FMA_F64, - dst=ASTOperand.vgpr(0), - src0=ASTOperand.vgpr(2), - src1=ASTOperand.vgpr(4), - src2=ASTOperand.vgpr(6), - ) - inst.validate() - self.assertEqual(inst.disasm(), "v_fma_f64 v[0:1], v[2:3], v[4:5], v[6:7]") - - def test_ast_with_modifiers_and_disasm(self): - inst = ASTInstruction( - opcode=Opcode.V_FMA_F64, - dst=ASTOperand.vgpr(0), - src0=ASTOperand.vgpr(2, neg=True, abs_=True), - src1=ASTOperand.sgpr(4), - src2=ASTOperand.inline_const(1.0), - clamp=True, - omod=OMod.MUL2, - ) - inst.validate() - self.assertEqual(inst.disasm(), "v_fma_f64 v[0:1], -|v[2:3]|, s[4:5], 1.0 mul:2 clamp") - - def test_ast_validation_errors(self): - # Invalid destination kind - bad_dst = ASTInstruction( - opcode=Opcode.V_FMA_F64, - dst=ASTOperand.sgpr(0), - src0=ASTOperand.vgpr(2), - src1=ASTOperand.vgpr(4), - src2=ASTOperand.vgpr(6), - ) - with self.assertRaises(TypeError): - bad_dst.validate() - - # Destination has modifiers (illegal in RDNA2) - bad_dst_mod = ASTInstruction( - opcode=Opcode.V_FMA_F64, - dst=ASTOperand.vgpr(0, neg=True), - src0=ASTOperand.vgpr(2), - src1=ASTOperand.vgpr(4), - src2=ASTOperand.vgpr(6), - ) - with self.assertRaises(ValueError): - bad_dst_mod.validate() - - # Destination out of bounds - bad_index = ASTInstruction( - opcode=Opcode.V_FMA_F64, - dst=ASTOperand.vgpr(256), - src0=ASTOperand.vgpr(2), - src1=ASTOperand.vgpr(4), - src2=ASTOperand.vgpr(6), - ) - with self.assertRaises(ValueError): - bad_index.validate() - - def test_typed_expressions_and_evaluation(self): - # Symbolic: (a * b) + c - expr = FMAExpr( - VariableExpr("a"), - VariableExpr("b"), - VariableExpr("c"), - ) - env = {"a": 2.5, "b": 4.0, "c": -3.0} - self.assertEqual(expr.evaluate(env), 7.0) - - def test_typed_expression_constant_folding(self): - # FMA(Const(2.0), Const(3.0), Const(4.0)) -> Const(10.0) - c_expr = FMAExpr( - ConstantExpr(2.0), - ConstantExpr(3.0), - ConstantExpr(4.0), - ) - folded = c_expr.simplify() - self.assertIsInstance(folded, ConstantExpr) - self.assertEqual(folded.value, 10.0) - - # Unary folding - u_expr = UnaryOpExpr("neg", ConstantExpr(5.5)) - u_folded = u_expr.simplify() - self.assertIsInstance(u_folded, ConstantExpr) - self.assertEqual(u_folded.value, -5.5) - - -class ScalarRegisterFile: - """Register file for a single scalar lane with 256 VGPRs and 106 SGPRs.""" - - def __init__(self) -> None: - self.vgprs = [0] * 256 - self.sgprs = [0] * 106 - - def read_vgpr(self, idx: int) -> int: - return self.vgprs[idx] - - def write_vgpr(self, idx: int, val: int) -> None: - self.vgprs[idx] = val & MASK32 - - def read_sgpr(self, idx: int) -> int: - return self.sgprs[idx] - - def write_sgpr(self, idx: int, val: int) -> None: - self.sgprs[idx] = val & MASK32 - - def read_vgpr_pair_u64(self, idx: int) -> int: - return dwords_to_u64(self.vgprs[idx], self.vgprs[idx + 1]) - - def write_vgpr_pair_u64(self, idx: int, val: int) -> None: - lo, hi = u64_to_dwords(val) - self.vgprs[idx] = lo - self.vgprs[idx + 1] = hi - - def read_vgpr_pair_f64(self, idx: int) -> float: - return u64_to_f64(self.read_vgpr_pair_u64(idx)) - - def write_vgpr_pair_f64(self, idx: int, val: float) -> None: - self.write_vgpr_pair_u64(idx, f64_to_u64(val)) - - def read_sgpr_pair_u64(self, idx: int) -> int: - return dwords_to_u64(self.sgprs[idx], self.sgprs[idx + 1]) - - def write_sgpr_pair_u64(self, idx: int, val: int) -> None: - lo, hi = u64_to_dwords(val) - self.sgprs[idx] = lo - self.sgprs[idx + 1] = hi - - def read_sgpr_pair_f64(self, idx: int) -> float: - return u64_to_f64(self.read_sgpr_pair_u64(idx)) - - def write_sgpr_pair_f64(self, idx: int, val: float) -> None: - self.write_sgpr_pair_u64(idx, f64_to_u64(val)) - - -class FmaF64ScalarInterpreter: - """Deterministic scalar instruction interpreter for v_fma_f64.""" - - def __init__(self, reg_file: ScalarRegisterFile | None = None) -> None: - self.reg_file = reg_file if reg_file is not None else ScalarRegisterFile() - - def resolve_source_f64(self, src: ASTOperand) -> float: - if src.kind == OperandKind.VGPR_PAIR: - val = self.reg_file.read_vgpr_pair_f64(src.index) - elif src.kind == OperandKind.SGPR_PAIR: - val = self.reg_file.read_sgpr_pair_f64(src.index) - elif src.kind in (OperandKind.INLINE_CONST, OperandKind.LITERAL_CONST): - val = float(src.value) if src.value is not None else 0.0 - else: - raise ValueError(f"Unsupported operand kind: {src.kind}") - - # Apply source modifiers - u = apply_src_mods_u64(f64_to_u64(val), neg=src.neg, abs_=src.abs_) - return u64_to_f64(u) - - def execute(self, inst: ASTInstruction) -> None: - inst.validate() - s0 = self.resolve_source_f64(inst.src0) - s1 = self.resolve_source_f64(inst.src1) - s2 = self.resolve_source_f64(inst.src2) - - res = ref_fma_f64(s0, s1, s2, clamp=inst.clamp, omod=inst.omod.value) - self.reg_file.write_vgpr_pair_f64(inst.dst.index, res) - - -class TestFmaF64ScalarInterpreter(unittest.TestCase): - """Test suite for deterministic scalar instruction interpreter.""" - - def setUp(self) -> None: - self.rf = ScalarRegisterFile() - self.interp = FmaF64ScalarInterpreter(self.rf) - - def test_scalar_interpreter_vgprs(self): - # v[0:1] = v[2:3] * v[4:5] + v[6:7] - self.rf.write_vgpr_pair_f64(2, 3.0) - self.rf.write_vgpr_pair_f64(4, 4.0) - self.rf.write_vgpr_pair_f64(6, 5.0) - - inst = ASTInstruction( - opcode=Opcode.V_FMA_F64, - dst=ASTOperand.vgpr(0), - src0=ASTOperand.vgpr(2), - src1=ASTOperand.vgpr(4), - src2=ASTOperand.vgpr(6), - ) - self.interp.execute(inst) - self.assertEqual(self.rf.read_vgpr_pair_f64(0), 17.0) - - def test_scalar_interpreter_sgpr_and_constants(self): - # v[0:1] = s[0:1] * v[2:3] + inline_const(10.0) - self.rf.write_sgpr_pair_f64(0, 2.5) - self.rf.write_vgpr_pair_f64(2, 4.0) - - inst = ASTInstruction( - opcode=Opcode.V_FMA_F64, - dst=ASTOperand.vgpr(0), - src0=ASTOperand.sgpr(0), - src1=ASTOperand.vgpr(2), - src2=ASTOperand.inline_const(10.0), - ) - self.interp.execute(inst) - self.assertEqual(self.rf.read_vgpr_pair_f64(0), 20.0) - - def test_scalar_interpreter_modifiers(self): - # v[0:1] = -|v[2:3]| * v[4:5] + 5.0 with clamp - # v[2:3] = -2.0 -> abs -> 2.0 -> neg -> -2.0 - # -2.0 * 3.0 + 5.0 = -1.0 -> clamp -> 0.0 - self.rf.write_vgpr_pair_f64(2, -2.0) - self.rf.write_vgpr_pair_f64(4, 3.0) - - inst = ASTInstruction( - opcode=Opcode.V_FMA_F64, - dst=ASTOperand.vgpr(0), - src0=ASTOperand.vgpr(2, neg=True, abs_=True), - src1=ASTOperand.vgpr(4), - src2=ASTOperand.inline_const(5.0), - clamp=True, - ) - self.interp.execute(inst) - self.assertEqual(self.rf.read_vgpr_pair_f64(0), 0.0) - - def test_scalar_interpreter_deterministic_repeatability(self): - # Verify that repeating operations produces identical bit patterns - self.rf.write_vgpr_pair_f64(2, 1.23456789012345) - self.rf.write_vgpr_pair_f64(4, 9.87654321098765) - self.rf.write_vgpr_pair_f64(6, -3.14159265358979) - - inst = ASTInstruction( - opcode=Opcode.V_FMA_F64, - dst=ASTOperand.vgpr(0), - src0=ASTOperand.vgpr(2), - src1=ASTOperand.vgpr(4), - src2=ASTOperand.vgpr(6), - ) - self.interp.execute(inst) - res1 = self.rf.read_vgpr_pair_u64(0) - - self.interp.execute(inst) - res2 = self.rf.read_vgpr_pair_u64(0) - self.assertEqual(res1, res2) - - -class SIMDWaveState: - """Architectural model of a SIMD wavefront (Wave32 or Wave64) with EXEC masking.""" - - def __init__(self, wave_size: int = 64) -> None: - if wave_size not in (32, 64): - raise ValueError(f"Wave size must be 32 or 64, got {wave_size}") - self.wave_size = wave_size - self._exec_mask = (1 << wave_size) - 1 - self.vgprs = [[0] * 256 for _ in range(wave_size)] - self.sgprs = [0] * 106 - - @property - def exec_mask(self) -> int: - return self._exec_mask - - @exec_mask.setter - def exec_mask(self, val: int) -> None: - mask_limit = (1 << self.wave_size) - 1 - self._exec_mask = val & mask_limit - - @property - def exec_lo(self) -> int: - return self._exec_mask & MASK32 - - @exec_lo.setter - def exec_lo(self, val: int) -> None: - self._exec_mask = (self._exec_mask & ~MASK32) | (val & MASK32) - - @property - def exec_hi(self) -> int: - return (self._exec_mask >> 32) & MASK32 - - @exec_hi.setter - def exec_hi(self, val: int) -> None: - if self.wave_size == 32: - raise ValueError("Cannot set exec_hi on Wave32") - self._exec_mask = (self._exec_mask & MASK32) | ((val & MASK32) << 32) - - def set_lane_vgpr_pair_u64(self, lane: int, idx: int, val: int) -> None: - lo, hi = u64_to_dwords(val) - self.vgprs[lane][idx] = lo - self.vgprs[lane][idx + 1] = hi - - def get_lane_vgpr_pair_u64(self, lane: int, idx: int) -> int: - return dwords_to_u64(self.vgprs[lane][idx], self.vgprs[lane][idx + 1]) - - def set_lane_vgpr_pair_f64(self, lane: int, idx: int, val: float) -> None: - self.set_lane_vgpr_pair_u64(lane, idx, f64_to_u64(val)) - - def get_lane_vgpr_pair_f64(self, lane: int, idx: int) -> float: - return u64_to_f64(self.get_lane_vgpr_pair_u64(lane, idx)) - - def set_sgpr_pair_u64(self, idx: int, val: int) -> None: - lo, hi = u64_to_dwords(val) - self.sgprs[idx] = lo - self.sgprs[idx + 1] = hi - - def get_sgpr_pair_u64(self, idx: int) -> int: - return dwords_to_u64(self.sgprs[idx], self.sgprs[idx + 1]) - - def set_sgpr_pair_f64(self, idx: int, val: float) -> None: - self.set_sgpr_pair_u64(idx, f64_to_u64(val)) - - def get_sgpr_pair_f64(self, idx: int) -> float: - return u64_to_f64(self.get_sgpr_pair_u64(idx)) - - def _resolve_operand_f64(self, src: ASTOperand, lane: int) -> float: - if src.kind == OperandKind.VGPR_PAIR: - val = self.get_lane_vgpr_pair_f64(lane, src.index) - elif src.kind == OperandKind.SGPR_PAIR: - val = self.get_sgpr_pair_f64(src.index) - elif src.kind in (OperandKind.INLINE_CONST, OperandKind.LITERAL_CONST): - val = float(src.value) if src.value is not None else 0.0 - else: - raise ValueError(f"Unsupported operand kind: {src.kind}") - - u = apply_src_mods_u64(f64_to_u64(val), neg=src.neg, abs_=src.abs_) - return u64_to_f64(u) - - def execute(self, inst: ASTInstruction) -> None: - inst.validate() - for lane in range(self.wave_size): - if (self._exec_mask >> lane) & 1: - s0 = self._resolve_operand_f64(inst.src0, lane) - s1 = self._resolve_operand_f64(inst.src1, lane) - s2 = self._resolve_operand_f64(inst.src2, lane) - res = ref_fma_f64(s0, s1, s2, clamp=inst.clamp, omod=inst.omod.value) - self.set_lane_vgpr_pair_f64(lane, inst.dst.index, res) - - -class TestFmaF64SIMDMultiLane(unittest.TestCase): - """Test suite for SIMD multi-lane divergence and 32/64-bit EXEC masking.""" - - CANARY_OLD = 0xDEADBEEFCAFEBABE - - def test_wave32_full_exec(self): - wave = SIMDWaveState(wave_size=32) - wave.exec_mask = 0xFFFFFFFF - for lane in range(32): - wave.set_lane_vgpr_pair_f64(lane, 2, float(lane)) - wave.set_lane_vgpr_pair_f64(lane, 4, 2.0) - wave.set_lane_vgpr_pair_f64(lane, 6, 1.0) - - inst = ASTInstruction( - opcode=Opcode.V_FMA_F64, - dst=ASTOperand.vgpr(0), - src0=ASTOperand.vgpr(2), - src1=ASTOperand.vgpr(4), - src2=ASTOperand.vgpr(6), - ) - wave.execute(inst) - - for lane in range(32): - expected = float(lane * 2 + 1) - self.assertEqual(wave.get_lane_vgpr_pair_f64(lane, 0), expected) - - def test_wave64_full_exec(self): - wave = SIMDWaveState(wave_size=64) - wave.exec_lo = 0xFFFFFFFF - wave.exec_hi = 0xFFFFFFFF - for lane in range(64): - wave.set_lane_vgpr_pair_f64(lane, 2, float(lane) * 0.5) - wave.set_lane_vgpr_pair_f64(lane, 4, 4.0) - wave.set_lane_vgpr_pair_f64(lane, 6, -10.0) - - inst = ASTInstruction( - opcode=Opcode.V_FMA_F64, - dst=ASTOperand.vgpr(0), - src0=ASTOperand.vgpr(2), - src1=ASTOperand.vgpr(4), - src2=ASTOperand.vgpr(6), - ) - wave.execute(inst) - - for lane in range(64): - expected = float(lane * 0.5) * 4.0 - 10.0 - self.assertEqual(wave.get_lane_vgpr_pair_f64(lane, 0), expected) - - def test_wave64_divergence_exec_masking(self): - wave = SIMDWaveState(wave_size=64) - # Even lanes in low 32, odd lanes in high 32 - wave.exec_lo = 0x55555555 - wave.exec_hi = 0xAAAAAAAA - - for lane in range(64): - wave.set_lane_vgpr_pair_u64(lane, 0, self.CANARY_OLD) - wave.set_lane_vgpr_pair_f64(lane, 2, 3.0) - wave.set_lane_vgpr_pair_f64(lane, 4, 5.0) - wave.set_lane_vgpr_pair_f64(lane, 6, 2.0) - - inst = ASTInstruction( - opcode=Opcode.V_FMA_F64, - dst=ASTOperand.vgpr(0), - src0=ASTOperand.vgpr(2), - src1=ASTOperand.vgpr(4), - src2=ASTOperand.vgpr(6), - ) - wave.execute(inst) - - for lane in range(64): - is_active = bool((wave.exec_mask >> lane) & 1) - if is_active: - self.assertEqual(wave.get_lane_vgpr_pair_f64(lane, 0), 17.0) - else: - self.assertEqual(wave.get_lane_vgpr_pair_u64(lane, 0), self.CANARY_OLD) - - def test_wave64_halves_masking(self): - wave = SIMDWaveState(wave_size=64) - # Only low 32 lanes active - wave.exec_lo = 0xFFFFFFFF - wave.exec_hi = 0x00000000 - - for lane in range(64): - wave.set_lane_vgpr_pair_u64(lane, 0, self.CANARY_OLD) - wave.set_lane_vgpr_pair_f64(lane, 2, 2.0) - wave.set_lane_vgpr_pair_f64(lane, 4, 2.0) - wave.set_lane_vgpr_pair_f64(lane, 6, 2.0) - - inst = ASTInstruction( - opcode=Opcode.V_FMA_F64, - dst=ASTOperand.vgpr(0), - src0=ASTOperand.vgpr(2), - src1=ASTOperand.vgpr(4), - src2=ASTOperand.vgpr(6), - ) - wave.execute(inst) - - for lane in range(32): - self.assertEqual(wave.get_lane_vgpr_pair_f64(lane, 0), 6.0) - for lane in range(32, 64): - self.assertEqual(wave.get_lane_vgpr_pair_u64(lane, 0), self.CANARY_OLD) - - def test_single_active_lane(self): - wave = SIMDWaveState(wave_size=64) - wave.exec_mask = 1 << 17 # only lane 17 - - for lane in range(64): - wave.set_lane_vgpr_pair_u64(lane, 0, self.CANARY_OLD) - wave.set_lane_vgpr_pair_f64(lane, 2, 7.0) - wave.set_lane_vgpr_pair_f64(lane, 4, 3.0) - wave.set_lane_vgpr_pair_f64(lane, 6, 1.0) - - inst = ASTInstruction( - opcode=Opcode.V_FMA_F64, - dst=ASTOperand.vgpr(0), - src0=ASTOperand.vgpr(2), - src1=ASTOperand.vgpr(4), - src2=ASTOperand.vgpr(6), - ) - wave.execute(inst) - - for lane in range(64): - if lane == 17: - self.assertEqual(wave.get_lane_vgpr_pair_f64(lane, 0), 22.0) - else: - self.assertEqual(wave.get_lane_vgpr_pair_u64(lane, 0), self.CANARY_OLD) - - def test_zero_exec_preserves_all_lanes(self): - wave = SIMDWaveState(wave_size=64) - wave.exec_mask = 0 - - for lane in range(64): - wave.set_lane_vgpr_pair_u64(lane, 0, self.CANARY_OLD) - - inst = ASTInstruction( - opcode=Opcode.V_FMA_F64, - dst=ASTOperand.vgpr(0), - src0=ASTOperand.inline_const(1.0), - src1=ASTOperand.inline_const(1.0), - src2=ASTOperand.inline_const(1.0), - ) - wave.execute(inst) - - for lane in range(64): - self.assertEqual(wave.get_lane_vgpr_pair_u64(lane, 0), self.CANARY_OLD) - - -class TestFmaF64RegisterAliasing(unittest.TestCase): - """Test suite for register aliasing and in-place operand preservation.""" - - def test_accumulator_aliasing_dst_equals_src2(self): - # Accumulator in-place: v[0:1] = v[2:3] * v[4:5] + v[0:1] - rf = ScalarRegisterFile() - interp = FmaF64ScalarInterpreter(rf) - - rf.write_vgpr_pair_f64(0, 10.0) # accumulator initial value - rf.write_vgpr_pair_f64(2, 2.0) - rf.write_vgpr_pair_f64(4, 3.0) - - inst = ASTInstruction( - opcode=Opcode.V_FMA_F64, - dst=ASTOperand.vgpr(0), - src0=ASTOperand.vgpr(2), - src1=ASTOperand.vgpr(4), - src2=ASTOperand.vgpr(0), - ) - - # Iteration 1: 10.0 + 6.0 = 16.0 - interp.execute(inst) - self.assertEqual(rf.read_vgpr_pair_f64(0), 16.0) - - # Iteration 2: 16.0 + 6.0 = 22.0 - interp.execute(inst) - self.assertEqual(rf.read_vgpr_pair_f64(0), 22.0) - - # Iteration 3: 22.0 + 6.0 = 28.0 - interp.execute(inst) - self.assertEqual(rf.read_vgpr_pair_f64(0), 28.0) - - def test_multiplicand_aliasing_dst_equals_src0(self): - # v[0:1] = v[0:1] * v[2:3] + v[4:5] - rf = ScalarRegisterFile() - interp = FmaF64ScalarInterpreter(rf) - - rf.write_vgpr_pair_f64(0, 5.0) - rf.write_vgpr_pair_f64(2, 2.0) - rf.write_vgpr_pair_f64(4, 3.0) - - inst = ASTInstruction( - opcode=Opcode.V_FMA_F64, - dst=ASTOperand.vgpr(0), - src0=ASTOperand.vgpr(0), - src1=ASTOperand.vgpr(2), - src2=ASTOperand.vgpr(4), - ) - interp.execute(inst) - self.assertEqual(rf.read_vgpr_pair_f64(0), 13.0) - - def test_multiplier_aliasing_dst_equals_src1(self): - # v[0:1] = v[2:3] * v[0:1] + v[4:5] - rf = ScalarRegisterFile() - interp = FmaF64ScalarInterpreter(rf) - - rf.write_vgpr_pair_f64(0, 3.0) - rf.write_vgpr_pair_f64(2, 4.0) - rf.write_vgpr_pair_f64(4, -5.0) - - inst = ASTInstruction( - opcode=Opcode.V_FMA_F64, - dst=ASTOperand.vgpr(0), - src0=ASTOperand.vgpr(2), - src1=ASTOperand.vgpr(0), - src2=ASTOperand.vgpr(4), - ) - interp.execute(inst) - self.assertEqual(rf.read_vgpr_pair_f64(0), 7.0) - - def test_self_fma_dst_equals_all_sources(self): - # v[0:1] = v[0:1] * v[0:1] + v[0:1] -> x^2 + x - rf = ScalarRegisterFile() - interp = FmaF64ScalarInterpreter(rf) - - rf.write_vgpr_pair_f64(0, 3.0) - - inst = ASTInstruction( - opcode=Opcode.V_FMA_F64, - dst=ASTOperand.vgpr(0), - src0=ASTOperand.vgpr(0), - src1=ASTOperand.vgpr(0), - src2=ASTOperand.vgpr(0), - ) - interp.execute(inst) - self.assertEqual(rf.read_vgpr_pair_f64(0), 12.0) - - def test_partial_dword_misaligned_aliasing(self): - # Misaligned overlap: dst is v[1:2], reading src0 from v[0:1] - # v0 and v1 encode 2.0 (f64: lo=0, hi=0x40000000) - rf = ScalarRegisterFile() - interp = FmaF64ScalarInterpreter(rf) - - rf.write_vgpr_pair_f64(0, 2.0) # v0=0, v1=0x40000000 - rf.write_vgpr_pair_f64(4, 5.0) # src1 - rf.write_vgpr_pair_f64(6, 1.0) # src2 - - inst = ASTInstruction( - opcode=Opcode.V_FMA_F64, - dst=ASTOperand.vgpr(1), # dst writes v1 and v2 - src0=ASTOperand.vgpr(0), # src0 reads v0 and v1 - src1=ASTOperand.vgpr(4), - src2=ASTOperand.vgpr(6), - ) - interp.execute(inst) - # Result = 2.0 * 5.0 + 1.0 = 11.0, committed to v[1:2] - self.assertEqual(rf.read_vgpr_pair_f64(1), 11.0) - # v0 remains untouched - self.assertEqual(rf.read_vgpr(0), 0) - - def test_simd_multi_lane_aliased_accumulation(self): - # Multi-lane wave with dst == src2 accumulation under active/inactive EXEC - wave = SIMDWaveState(wave_size=64) - wave.exec_lo = 0xFF00FF00 - wave.exec_hi = 0x00FF00FF - - initial_acc = 100.0 - for lane in range(64): - wave.set_lane_vgpr_pair_f64(lane, 0, initial_acc) - wave.set_lane_vgpr_pair_f64(lane, 2, float(lane)) - wave.set_lane_vgpr_pair_f64(lane, 4, 2.0) - - inst = ASTInstruction( - opcode=Opcode.V_FMA_F64, - dst=ASTOperand.vgpr(0), - src0=ASTOperand.vgpr(2), - src1=ASTOperand.vgpr(4), - src2=ASTOperand.vgpr(0), - ) - wave.execute(inst) - - for lane in range(64): - is_active = bool((wave.exec_mask >> lane) & 1) - if is_active: - expected = float(lane * 2) + initial_acc - self.assertEqual(wave.get_lane_vgpr_pair_f64(lane, 0), expected) - else: - self.assertEqual(wave.get_lane_vgpr_pair_f64(lane, 0), initial_acc) - - -class StatusFlags: - """IEEE 754 exception flags and architectural condition codes for an operation.""" - - def __init__( - self, - *, - invalid: bool = False, - overflow: bool = False, - underflow: bool = False, - inexact: bool = False, - is_negative: bool = False, - is_zero: bool = False, - is_inf: bool = False, - is_nan: bool = False, - is_subnormal: bool = False, - ) -> None: - self.invalid = invalid - self.overflow = overflow - self.underflow = underflow - self.inexact = inexact - self.is_negative = is_negative - self.is_zero = is_zero - self.is_inf = is_inf - self.is_nan = is_nan - self.is_subnormal = is_subnormal - - def __repr__(self) -> str: - flags = [k for k, v in self.__dict__.items() if v] - return f"StatusFlags({', '.join(flags)})" - - -def compute_fma_status_flags( - s0: float, - s1: float, - s2: float, - *, - neg0: bool = False, - neg1: bool = False, - neg2: bool = False, - abs0: bool = False, - abs1: bool = False, - abs2: bool = False, - clamp: bool = False, - omod: int = 0, -) -> tuple[float, StatusFlags]: - """Compute FMA result along with IEEE 754 status flags and condition codes.""" - u0 = apply_src_mods_u64(f64_to_u64(s0), neg=neg0, abs_=abs0) - u1 = apply_src_mods_u64(f64_to_u64(s1), neg=neg1, abs_=abs1) - u2 = apply_src_mods_u64(f64_to_u64(s2), neg=neg2, abs_=abs2) - - v0 = u64_to_f64(u0) - v1 = u64_to_f64(u1) - v2 = u64_to_f64(u2) - - invalid = False - overflow = False - underflow = False - inexact = False - - # Check for invalid operation exceptions - if math.isnan(v0) or math.isnan(v1) or math.isnan(v2): - # Signaling NaN or NaN arithmetic - if (u0 & F64_CANONICAL_QNAN == F64_POS_INF) or (u1 & F64_CANONICAL_QNAN == F64_POS_INF) or (u2 & F64_CANONICAL_QNAN == F64_POS_INF): - invalid = True - - if (math.isinf(v0) and v1 == 0.0) or (v0 == 0.0 and math.isinf(v1)): - invalid = True - - p_inf = math.isinf(v0) or math.isinf(v1) - if p_inf and math.isinf(v2): - p_sign = -1.0 if (math.copysign(1.0, v0) * math.copysign(1.0, v1) < 0) else 1.0 - if p_sign != math.copysign(1.0, v2): - invalid = True - - res = ref_fma_f64( - s0, s1, s2, - neg0=neg0, neg1=neg1, neg2=neg2, - abs0=abs0, abs1=abs1, abs2=abs2, - clamp=clamp, omod=omod, - ) - - # Inexact & Overflow/Underflow determination for finite inputs - if not math.isnan(res) and math.isfinite(v0) and math.isfinite(v1) and math.isfinite(v2): - exact_frac = Fraction(v0) * Fraction(v1) + Fraction(v2) - if omod == 1: - exact_frac *= Fraction(2) - elif omod == 2: - exact_frac *= Fraction(4) - elif omod == 3: - exact_frac /= Fraction(2) - - if math.isinf(res): - overflow = True - inexact = True - else: - if Fraction(res) != exact_frac: - inexact = True - u_res = f64_to_u64(res) - # Check subnormal - exp_bits = (u_res >> 52) & 0x7FF - mant_bits = u_res & 0x000FFFFFFFFFFFFF - if exp_bits == 0 and mant_bits != 0: - underflow = True - - u_res = f64_to_u64(res) - is_neg = (u_res & F64_NEG_ZERO) != 0 - is_nan = math.isnan(res) - is_inf = math.isinf(res) - is_zero = (res == 0.0) - exp = (u_res >> 52) & 0x7FF - mant = u_res & 0x000FFFFFFFFFFFFF - is_subnormal = (exp == 0 and mant != 0) - - flags = StatusFlags( - invalid=invalid, - overflow=overflow, - underflow=underflow, - inexact=inexact, - is_negative=is_neg, - is_zero=is_zero, - is_inf=is_inf, - is_nan=is_nan, - is_subnormal=is_subnormal, - ) - return res, flags - - -def evaluate_vcc_predicate(wave: SIMDWaveState, reg_idx: int, predicate: str) -> int: - """Generate 64-bit VCC mask evaluating condition on reg_idx across all active lanes.""" - vcc = 0 - for lane in range(wave.wave_size): - if (wave.exec_mask >> lane) & 1: - val = wave.get_lane_vgpr_pair_f64(lane, reg_idx) - cond = False - if predicate == "eq_zero": - cond = (val == 0.0) - elif predicate == "ge_zero": - cond = not math.isnan(val) and val >= 0.0 - elif predicate == "lt_zero": - cond = not math.isnan(val) and val < 0.0 - elif predicate == "is_nan": - cond = math.isnan(val) - elif predicate == "is_finite": - cond = math.isfinite(val) - else: - raise ValueError(f"Unknown predicate: {predicate}") - - if cond: - vcc |= (1 << lane) - return vcc - - -class TestFmaF64StatusFlagsAndConditionCodes(unittest.TestCase): - """Test suite for IEEE 754 status flags, condition codes, and VCC carry/predicate generation.""" - - def test_inexact_flag_detection(self): - # Exact calculation: 2.0 * 3.0 + 1.0 = 7.0 (exact in float) - _, flags_exact = compute_fma_status_flags(2.0, 3.0, 1.0) - self.assertFalse(flags_exact.inexact) - - # Inexact calculation: inputs are exact, but product has term 2**-104 that is rounded - a = 1.0 + (2.0 ** -52) - _, flags_inexact = compute_fma_status_flags(a, a, 0.0) - self.assertTrue(flags_inexact.inexact) - - def test_overflow_flag(self): - max_f64 = u64_to_f64(F64_MAX_NORMAL) - res, flags = compute_fma_status_flags(max_f64, 2.0, 0.0) - self.assertTrue(math.isinf(res)) - self.assertTrue(flags.overflow) - self.assertTrue(flags.inexact) - self.assertTrue(flags.is_inf) - - def test_underflow_flag(self): - min_normal = u64_to_f64(F64_MIN_NORMAL) - res, flags = compute_fma_status_flags(min_normal, 0.5, 0.0) - self.assertTrue(flags.is_subnormal) - self.assertTrue(flags.underflow) - - def test_invalid_operation_flags(self): - # inf * 0.0 -> invalid - res, flags1 = compute_fma_status_flags(float("inf"), 0.0, 1.0) - self.assertTrue(math.isnan(res)) - self.assertTrue(flags1.invalid) - self.assertTrue(flags1.is_nan) - - # (+inf) * 1.0 + (-inf) -> invalid - res, flags2 = compute_fma_status_flags(float("inf"), 1.0, float("-inf")) - self.assertTrue(math.isnan(res)) - self.assertTrue(flags2.invalid) - self.assertTrue(flags2.is_nan) - - def test_condition_codes_signed_zeros(self): - # -0.0 * 1.0 + -0.0 -> -0.0 - res, flags = compute_fma_status_flags(-0.0, 1.0, -0.0) - self.assertTrue(flags.is_zero) - self.assertTrue(flags.is_negative) - - # 1.0 * 1.0 + -1.0 -> +0.0 - res, flags2 = compute_fma_status_flags(1.0, 1.0, -1.0) - self.assertTrue(flags2.is_zero) - self.assertFalse(flags2.is_negative) - - def test_vcc_predicate_mask_generation(self): - wave = SIMDWaveState(wave_size=64) - # EXEC active for lanes 0..31 - wave.exec_lo = 0xFFFFFFFF - wave.exec_hi = 0x00000000 - - # Alternate positive and negative numbers in v[0:1] - for lane in range(64): - val = 5.0 if (lane % 2 == 0) else -5.0 - wave.set_lane_vgpr_pair_f64(lane, 0, val) - - # Evaluate ge_zero: should match even lanes in 0..31 (0x55555555) - vcc_ge = evaluate_vcc_predicate(wave, 0, "ge_zero") - self.assertEqual(vcc_ge, 0x55555555) - - # Evaluate lt_zero: should match odd lanes in 0..31 (0xAAAAAAAA) - vcc_lt = evaluate_vcc_predicate(wave, 0, "lt_zero") - self.assertEqual(vcc_lt, 0xAAAAAAAA) - - # High lanes 32..63 are inactive in EXEC, so VCC bits 32..63 must be 0 - self.assertEqual(vcc_ge >> 32, 0) - self.assertEqual(vcc_lt >> 32, 0) - - -class TestFmaF64IEEE754Boundaries(unittest.TestCase): - """Test suite for IEEE 754 boundary extremes, subnormals, and NaN handling.""" - - def test_subnormal_operands_and_results(self): - sub_min = u64_to_f64(F64_SUB_MIN) # 2**-1074 - min_norm = u64_to_f64(F64_MIN_NORMAL) # 2**-1022 - - # subnormal * 1.0 + 0.0 retains subnormal - res = ref_fma_f64_u64(F64_SUB_MIN, F64_ONE, F64_POS_ZERO) - self.assertEqual(res, F64_SUB_MIN) - - # subnormal * 2.0 + 0.0 scales subnormal mantissa - res2 = ref_fma_f64_u64(F64_SUB_MIN, F64_TWO, F64_POS_ZERO) - self.assertEqual(res2, 0x0000000000000002) - - # normal * 0.5 produces maximum subnormal - res_sub = ref_fma_f64_u64(F64_MIN_NORMAL, F64_HALF, F64_POS_ZERO) - self.assertEqual(res_sub, 0x0008000000000000) - - # subnormal underflow rounds to zero - # sub_min * 0.25 rounds to 0.0 - u_quarter = f64_to_u64(0.25) - res_zero = ref_fma_f64_u64(F64_SUB_MIN, u_quarter, F64_POS_ZERO) - self.assertEqual(res_zero, F64_POS_ZERO) - - def test_signed_zeros_bitwise_representation(self): - # +0.0 * +0.0 + +0.0 = +0.0 (0x0000000000000000) - res_pp = ref_fma_f64_u64(F64_POS_ZERO, F64_POS_ZERO, F64_POS_ZERO) - self.assertEqual(res_pp, F64_POS_ZERO) - - # -0.0 * 1.0 + -0.0 = -0.0 (0x8000000000000000) - res_nn = ref_fma_f64_u64(F64_NEG_ZERO, F64_ONE, F64_NEG_ZERO) - self.assertEqual(res_nn, F64_NEG_ZERO) - - # -0.0 * -1.0 + +0.0 = +0.0 - res_np = ref_fma_f64_u64(F64_NEG_ZERO, F64_NEG_ONE, F64_POS_ZERO) - self.assertEqual(res_np, F64_POS_ZERO) - - # Cancellation: 1.0 * 1.0 + -1.0 = +0.0 in round-to-nearest - res_cancel = ref_fma_f64_u64(F64_ONE, F64_ONE, F64_NEG_ONE) - self.assertEqual(res_cancel, F64_POS_ZERO) - - def test_infinities_propagation_and_invalids(self): - # (+inf) * 2.0 + 10.0 = +inf - u_ten = f64_to_u64(10.0) - res_inf = ref_fma_f64_u64(F64_POS_INF, F64_TWO, u_ten) - self.assertEqual(res_inf, F64_POS_INF) - - # (-inf) * 2.0 + 10.0 = -inf - res_ninf = ref_fma_f64_u64(F64_NEG_INF, F64_TWO, u_ten) - self.assertEqual(res_ninf, F64_NEG_INF) - - # (+inf) * -2.0 + 10.0 = -inf - res_ninf2 = ref_fma_f64_u64(F64_POS_INF, f64_to_u64(-2.0), u_ten) - self.assertEqual(res_ninf2, F64_NEG_INF) - - # (+inf) * 0.0 + 1.0 -> NaN - res_nan1 = ref_fma_f64(float("inf"), 0.0, 1.0) - self.assertTrue(math.isnan(res_nan1)) - - # (+inf) * 1.0 + (-inf) -> NaN - res_nan2 = ref_fma_f64(float("inf"), 1.0, float("-inf")) - self.assertTrue(math.isnan(res_nan2)) - - def test_nan_handling_and_clamp_mapping(self): - # NaN propagation: any NaN input produces NaN - self.assertTrue(math.isnan(ref_fma_f64(float("nan"), 1.0, 2.0))) - self.assertTrue(math.isnan(ref_fma_f64(1.0, float("nan"), 2.0))) - self.assertTrue(math.isnan(ref_fma_f64(1.0, 2.0, float("nan")))) - - # RDNA2 clamp modifier: clamp maps NaN to +0.0 (0x0000000000000000) - clamped_nan = ref_fma_f64(float("nan"), 1.0, 2.0, clamp=True) - self.assertEqual(clamped_nan, 0.0) - self.assertEqual(f64_to_u64(clamped_nan), F64_POS_ZERO) - - # Source modifiers on NaN bit patterns - # -NaN inverts sign bit - qnan_neg = apply_src_mods_u64(F64_CANONICAL_QNAN, neg=True) - self.assertEqual(qnan_neg, F64_CANONICAL_QNAN | F64_NEG_ZERO) - - # | -NaN | clears sign bit - qnan_abs = apply_src_mods_u64(F64_CANONICAL_QNAN | F64_NEG_ZERO, abs_=True) - self.assertEqual(qnan_abs, F64_CANONICAL_QNAN) - - def test_boundary_max_normal_extremes(self): - max_f64 = u64_to_f64(F64_MAX_NORMAL) - - # MAX_NORMAL * 1.0 + 0.0 == MAX_NORMAL - res_max = ref_fma_f64(max_f64, 1.0, 0.0) - self.assertEqual(res_max, max_f64) - - # MAX_NORMAL * 1.0 - ULP is less than MAX_NORMAL - # 1 ULP at 2**1024 is 2**(1024 - 53) = 2**971 - ulp_max = 2.0 ** 971 - res_minus_ulp = ref_fma_f64(max_f64, 1.0, -ulp_max) - self.assertLess(res_minus_ulp, max_f64) - - # MAX_NORMAL * 2.0 overflows to +inf - res_overflow = ref_fma_f64(max_f64, 2.0, 0.0) - self.assertEqual(res_overflow, float("inf")) - - -def parse_operand_asm(op_str: str) -> ASTOperand: - """Parse a single operand string with potential neg/abs modifiers.""" - op_str = op_str.strip() - neg = False - abs_ = False - - if op_str.startswith("-"): - neg = True - op_str = op_str[1:].strip() - - if op_str.startswith("|") and op_str.endswith("|"): - abs_ = True - op_str = op_str[1:-1].strip() - - if op_str.startswith("v[") and op_str.endswith("]"): - inner = op_str[2:-1] - parts = inner.split(":") - if len(parts) != 2: - raise ValueError(f"Malformed VGPR pair: {op_str}") - lo = int(parts[0]) - hi = int(parts[1]) - if hi != lo + 1: - raise ValueError(f"VGPR pair must be consecutive registers [n:n+1], got {op_str}") - return ASTOperand.vgpr(lo, neg=neg, abs_=abs_) - - if op_str.startswith("s[") and op_str.endswith("]"): - inner = op_str[2:-1] - parts = inner.split(":") - if len(parts) != 2: - raise ValueError(f"Malformed SGPR pair: {op_str}") - lo = int(parts[0]) - hi = int(parts[1]) - if hi != lo + 1: - raise ValueError(f"SGPR pair must be consecutive registers [n:n+1], got {op_str}") - return ASTOperand.sgpr(lo, neg=neg, abs_=abs_) - - # Try parsing constant - try: - val = float(op_str) - return ASTOperand.inline_const(val, neg=neg, abs_=abs_) - except ValueError: - raise ValueError(f"Unrecognized operand syntax: {op_str}") - - -def parse_fma_f64_asm(line: str) -> ASTInstruction: - """Parse a complete v_fma_f64 assembly instruction string.""" - line = line.strip() - if not line: - raise ValueError("Empty assembly line") - - tokens = line.split(None, 1) - if not tokens or tokens[0] != Opcode.V_FMA_F64.value: - raise ValueError(f"Expected opcode '{Opcode.V_FMA_F64.value}', got '{tokens[0] if tokens else ''}'") - - if len(tokens) < 2: - raise ValueError("Missing operands in assembly line") - - rest = tokens[1].strip() - # Separate operands from optional trailing modifiers (clamp, mul:2, etc.) - # Operands are comma-separated - parts = [p.strip() for p in rest.split(",")] - if len(parts) < 4: - raise ValueError(f"Expected at least 4 comma-separated fields, got {len(parts)}") - - dst_str = parts[0] - src0_str = parts[1] - src1_str = parts[2] - # Fourth part contains src2 and optional modifiers - last_tokens = parts[3].split() - if not last_tokens: - raise ValueError("Missing third source operand") - - src2_str = last_tokens[0] - mod_tokens = last_tokens[1:] - - clamp = False - omod = OMod.NONE - - for mod in mod_tokens: - if mod == "clamp": - clamp = True - elif mod == "mul:2": - omod = OMod.MUL2 - elif mod == "mul:4": - omod = OMod.MUL4 - elif mod == "div:2": - omod = OMod.DIV2 - else: - raise ValueError(f"Unknown instruction modifier: {mod}") - - dst = parse_operand_asm(dst_str) - src0 = parse_operand_asm(src0_str) - src1 = parse_operand_asm(src1_str) - src2 = parse_operand_asm(src2_str) - - inst = ASTInstruction( - opcode=Opcode.V_FMA_F64, - dst=dst, - src0=src0, - src1=src1, - src2=src2, - clamp=clamp, - omod=omod, - ) - inst.validate() - return inst - - -class TestFmaF64NegativeControlsAndMutations(unittest.TestCase): - """Test suite for syntax rejection, negative controls, and mutation detection.""" - - def test_syntax_rejection_malformed_instructions(self): - # Empty line - with self.assertRaises(ValueError): - parse_fma_f64_asm("") - - # Wrong opcode - with self.assertRaises(ValueError): - parse_fma_f64_asm("v_add_f64 v[0:1], v[2:3], v[4:5], v[6:7]") - - # Missing operands - with self.assertRaises(ValueError): - parse_fma_f64_asm("v_fma_f64 v[0:1], v[2:3], v[4:5]") - - # Destination is SGPR - with self.assertRaises(TypeError): - parse_fma_f64_asm("v_fma_f64 s[0:1], v[2:3], v[4:5], v[6:7]") - - # Destination has negative modifier - with self.assertRaises(ValueError): - parse_fma_f64_asm("v_fma_f64 -v[0:1], v[2:3], v[4:5], v[6:7]") - - # Non-consecutive register pair - with self.assertRaises(ValueError): - parse_fma_f64_asm("v_fma_f64 v[0:2], v[2:3], v[4:5], v[6:7]") - - # Out of bounds register index - with self.assertRaises(ValueError): - parse_fma_f64_asm("v_fma_f64 v[256:257], v[2:3], v[4:5], v[6:7]") - - # Unknown modifier - with self.assertRaises(ValueError): - parse_fma_f64_asm("v_fma_f64 v[0:1], v[2:3], v[4:5], v[6:7] clamp_invalid") - - def test_mutation_detection_unfused_double_rounding(self): - # Mutation 1: Replace fused multiply-add with sequential unfused rounding - def mutated_unfused_fma(s0: float, s1: float, s2: float) -> float: - # Unfused: rounds intermediate product to binary64 - prod = s0 * s1 - return prod + s2 - - a = 1.0 + (2.0 ** -52) - b = 1.0 - (2.0 ** -52) - c = -1.0 - - oracle_result = ref_fma_f64(a, b, c) - mutated_result = mutated_unfused_fma(a, b, c) - - # Mutation must be detected and distinguished by test oracle! - self.assertNotEqual(oracle_result, mutated_result) - self.assertEqual(mutated_result, 0.0) - self.assertEqual(oracle_result, -(2.0 ** -104)) - - def test_mutation_detection_inverted_clamp_bounds(self): - # Mutation 2: Inverted clamp bounds [1.0, 0.0] - def mutated_clamp(val: float) -> float: - return min(max(val, 1.0), 0.0) - - # For val = 0.5, correct clamp returns 0.5. Inverted clamp returns 0.0. - correct = apply_clamp_f64(0.5) - mutated = mutated_clamp(0.5) - self.assertNotEqual(correct, mutated) - - def test_mutation_detection_nan_clamp_omission(self): - # Mutation 3: Clamp fails to map NaN to +0.0 - def mutated_clamp_nan(val: float) -> float: - if val < 0.0: - return 0.0 - if val > 1.0: - return 1.0 - return val # leaves NaN untouched - - correct = apply_clamp_f64(float("nan")) - mutated = mutated_clamp_nan(float("nan")) - self.assertEqual(correct, 0.0) - self.assertTrue(math.isnan(mutated)) - self.assertNotEqual(correct, mutated) - - def test_mutation_detection_exec_mask_leak(self): - # Mutation 4: Wave executor ignores EXEC mask and mutates inactive lanes - wave = SIMDWaveState(wave_size=64) - wave.exec_mask = 0 # all lanes inactive - old_val = 0x1122334455667788 - for lane in range(64): - wave.set_lane_vgpr_pair_u64(lane, 0, old_val) - - # Simulating buggy execution that writes even when EXEC bit is 0 - def buggy_execute(wave: SIMDWaveState, inst: ASTInstruction) -> None: - for lane in range(wave.wave_size): - # Bug: ignoring self.exec_mask check - wave.set_lane_vgpr_pair_f64(lane, inst.dst.index, 999.0) - - inst = ASTInstruction( - opcode=Opcode.V_FMA_F64, - dst=ASTOperand.vgpr(0), - src0=ASTOperand.inline_const(1.0), - src1=ASTOperand.inline_const(1.0), - src2=ASTOperand.inline_const(1.0), - ) - - # Check correct wave behavior - wave.execute(inst) - for lane in range(64): - self.assertEqual(wave.get_lane_vgpr_pair_u64(lane, 0), old_val) - - # Check that mutation modifies lane and is detected - buggy_execute(wave, inst) - self.assertNotEqual(wave.get_lane_vgpr_pair_u64(0, 0), old_val) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_valu_fma_mix.py b/tests/semantic/test_valu_fma_mix.py deleted file mode 100644 index 6c2a39cc6..000000000 --- a/tests/semantic/test_valu_fma_mix.py +++ /dev/null @@ -1,296 +0,0 @@ -"""Semantic interpreter tests for RDNA2 v_fma_mix_f32, v_fma_mixlo_f16 and v_fma_mixhi_f16. - -Each VOP3P mixed-precision FMA computes fma(src0, src1, src2) in f32: -- op_sel_hi[i] == 0: src[i] is an f32 word. -- op_sel_hi[i] == 1: src[i] is an f16 packed in the low half (op_sel[i] == 0) or high half (op_sel[i] == 1), - widened to f32 before applying neg/abs modifiers. -- v_fma_mix_f32 writes the f32 result; v_fma_mixlo_f16 narrows to f16 in the low half (keeping bits [31:16]); - v_fma_mixhi_f16 narrows to f16 in the high half (keeping bits [15:0]). - -Each case translates a synthetic pixel shader with tools/rdna2spirv.py, runs it in -tests/semantic/spirv_mini_interp.py and compares the exported word with a plain-Python reference. -""" -from fractions import Fraction -import itertools -import math -import os -import re -import struct -import sys -import tempfile -import unittest -import warnings - -HERE = os.path.dirname(os.path.abspath(__file__)) -ROOT = os.path.dirname(os.path.dirname(HERE)) -TOOLS_DIR = os.environ.get("LEONIDA_TOOLS_DIR") or os.path.join(ROOT, "tools") - -sys.dont_write_bytecode = True -sys.path.insert(0, TOOLS_DIR) -sys.path.insert(0, HERE) - -import rdna2spirv # noqa: E402 -import spirv_mini_interp as si # noqa: E402 - -STUB_DXBC = b"DXBC" + bytes(24) + struct.pack(" int: - return struct.unpack(" float: - return struct.unpack(" float: - return struct.unpack(" int: - try: - return struct.unpack(" 0 else 0xFC00 - - -def pack_h(lo: float, hi: float) -> int: - return (f2h(hi) << 16) | f2h(lo) - - -def unpack_src(word: int, is_f16: int, sel_hi_half: int, neg: bool = False, abs_: bool = False) -> float: - v = h2f((word >> 16) if sel_hi_half else word) if is_f16 else u2f(word) - if abs_: - v = math.copysign(v, 1.0) - if neg: - v = -v - return v - - -def ref_fma(w0: int, w1: int, w2: int, sel_hi, sel, mods_src=((False, False),) * 3, clamp: bool = False) -> float: - x = unpack_src(w0, sel_hi[0], sel[0], *mods_src[0]) - y = unpack_src(w1, sel_hi[1], sel[1], *mods_src[1]) - z = unpack_src(w2, sel_hi[2], sel[2], *mods_src[2]) - r = u2f(f2u(float(Fraction(x) * Fraction(y) + Fraction(z)))) - if clamp: - r = min(max(r, 0.0), 1.0) - return r - - -_TMP_DIR = None -_SRC_PATH = None - - -def setUpModule(): - global _TMP_DIR, _SRC_PATH - _TMP_DIR = tempfile.TemporaryDirectory() - disasm_dir = os.path.join(_TMP_DIR.name, "disasm") - os.mkdir(disasm_dir) - _SRC_PATH = os.path.join(disasm_dir, "ps_fma_mix.s") - with open(os.path.join(_TMP_DIR.name, "ps_fma_mix.dxbc"), "wb") as f: - f.write(STUB_DXBC) - - -def tearDownModule(): - global _TMP_DIR - if _TMP_DIR is not None: - _TMP_DIR.cleanup() - _TMP_DIR = None - - -def translate_and_run(line: str, v1: int, v2: int, v3: int, old: int = OLD): - if _TMP_DIR is None: - setUpModule() - lines = [ - f"v_mov_b32 v1, {v1:#x}", - f"v_mov_b32 v2, {v2:#x}", - f"v_mov_b32 v3, {v3:#x}", - f"v_mov_b32 v0, {old:#x}", - line, - ] - asm = ( - "; test_valu_fma_mix\n" - + "".join(f"\t{ln}\n" for ln in lines) - + "\texp mrt0 v0, v0, v0, v0 done vm\n\ts_endpgm\n" - ) - with open(_SRC_PATH, "w", encoding="utf-8") as f: - f.write(asm) - with warnings.catch_warnings(): - warnings.simplefilter("ignore", ResourceWarning) - spv = rdna2spirv.translate(_SRC_PATH) - return spv, si.run_fragment(spv)["%out_mrt0"][0] - - -def run(line: str, v1: int, v2: int, v3: int, old: int = OLD) -> int: - return translate_and_run(line, v1, v2, v3, old=old)[1] - - -class FmaMixF32Tests(unittest.TestCase): - """v_fma_mix_f32 across op_sel_hi/op_sel combinations, source modifiers and clamp.""" - - # Each word is valid both as a finite f32 and as two distinct finite f16 halves. - W0 = pack_h(1.5, -3.25) # f16: (1.5, -3.25), also finite f32 - W1 = pack_h(2.25, 0.75) # f16: (2.25, 0.75) - W2 = pack_h(-0.5, 4.5) # f16: (-0.5, 4.5) - - def test_all_f32_default_no_modifiers(self): - a, b, c = f2u(2.5), f2u(-1.25), f2u(0.75) - got = run("v_fma_mix_f32 v0, v1, v2, v3", a, b, c) - want = f2u(ref_fma(a, b, c, (0, 0, 0), (0, 0, 0))) - self.assertEqual(got, want) - - def test_all_64_op_sel_and_op_sel_hi_combinations(self): - for sel_hi in itertools.product((0, 1), repeat=3): - for sel in itertools.product((0, 1), repeat=3): - # When op_sel_hi[i] == 0, supply a clean f32; when 1, supply packed f16 lo/hi. - w0 = self.W0 if sel_hi[0] else f2u(1.75) - w1 = self.W1 if sel_hi[1] else f2u(-2.5) - w2 = self.W2 if sel_hi[2] else f2u(0.375) - line = ( - f"v_fma_mix_f32 v0, v1, v2, v3 " - f"op_sel:[{sel[0]},{sel[1]},{sel[2]}] " - f"op_sel_hi:[{sel_hi[0]},{sel_hi[1]},{sel_hi[2]}]" - ) - with self.subTest(sel_hi=sel_hi, sel=sel): - got = run(line, w0, w1, w2) - want = f2u(ref_fma(w0, w1, w2, sel_hi, sel)) - self.assertEqual(got, want) - - def test_source_neg_abs_modifiers(self): - w0 = pack_h(-2.0, 3.0) - w1 = f2u(-1.5) - w2 = pack_h(0.25, -4.0) - line = "v_fma_mix_f32 v0, -|v1|, -v2, |v3| op_sel:[0,0,1] op_sel_hi:[1,0,1]" - got = run(line, w0, w1, w2) - want = f2u(ref_fma(w0, w1, w2, (1, 0, 1), (0, 0, 1), mods_src=((True, True), (True, False), (False, True)))) - self.assertEqual(got, want) - - def test_clamp_modifier(self): - cases = [ - (pack_h(2.0, 0.0), f2u(3.0), pack_h(1.0, 0.0), 1.0), # > 1.0 -> 1.0 - (pack_h(-2.0, 0.0), f2u(3.0), pack_h(-1.0, 0.0), 0.0), # < 0.0 -> 0.0 - (pack_h(0.5, 0.0), f2u(0.5), pack_h(0.25, 0.0), 0.5), # in [0, 1] -> unchanged - ] - for w0, w1, w2, expected in cases: - with self.subTest(expected=expected): - got = run("v_fma_mix_f32 v0, v1, v2, v3 op_sel_hi:[1,0,1] clamp", w0, w1, w2) - self.assertEqual(got, f2u(expected)) - - -class FmaMixF16Tests(unittest.TestCase): - """v_fma_mixlo_f16 and v_fma_mixhi_f16: half preservation, mixed inputs, modifiers, clamp and aliasing.""" - - def test_mixlo_and_mixhi_preserve_untouched_half(self): - w0 = pack_h(1.5, -2.5) - w1 = f2u(2.0) - w2 = pack_h(0.25, 3.0) - for op, dst_hi in (("v_fma_mixlo_f16", 0), ("v_fma_mixhi_f16", 1)): - for sel in ((0, 0, 0), (1, 0, 1), (1, 0, 0), (0, 0, 1)): - line = f"{op} v0, v1, v2, v3 op_sel:[{sel[0]},{sel[1]},{sel[2]}] op_sel_hi:[1,0,1]" - with self.subTest(op=op, sel=sel): - got = run(line, w0, w1, w2, old=OLD) - h = f2h(ref_fma(w0, w1, w2, (1, 0, 1), sel)) - want = ((h << 16) | (OLD & 0xFFFF)) if dst_hi else ((OLD & 0xFFFF0000) | h) - self.assertEqual(got, want) - - def test_mixlo_and_mixhi_neg_abs_and_clamp(self): - w0 = pack_h(-3.0, 1.0) - w1 = pack_h(2.0, -0.5) - w2 = f2u(0.5) - # -|-3.0| * (-0.5) + 0.5 = -3.0 * -0.5 + 0.5 = 2.0 -> clamped to 1.0 (0x3c00) - got_lo = run("v_fma_mixlo_f16 v0, -|v1|, v2, v3 op_sel:[0,1,0] op_sel_hi:[1,1,0] clamp", w0, w1, w2, old=OLD) - self.assertEqual(got_lo, (OLD & 0xFFFF0000) | f2h(1.0)) - - # -|-3.0| * 2.0 + 0.5 = -5.5 -> clamped to 0.0 (0x0000) - got_hi = run("v_fma_mixhi_f16 v0, -|v1|, v2, v3 op_sel:[0,0,0] op_sel_hi:[1,1,0] clamp", w0, w1, w2, old=OLD) - self.assertEqual(got_hi, (f2h(0.0) << 16) | (OLD & 0xFFFF)) - - def test_destination_aliases_source(self): - # v0 starts as pack_h(1.5, 4.0); compute mixhi using v0.lo (1.5) * 2.0 + 0.5 = 3.5 -> keep lo (1.5) - old = pack_h(1.5, 4.0) - got = run("v_fma_mixhi_f16 v0, v0, v1, v2 op_sel:[0,0,0] op_sel_hi:[1,0,1]", f2u(2.0), pack_h(0.5, 9.0), 0, old=old) - self.assertEqual(got, pack_h(1.5, 3.5)) - - def test_single_rounding_discriminating_cases(self): - # Discriminating test cases A through G from tools/fma_mix_probe.py where - # hardware single rounding gives 1 ulp difference from double rounding. - # Case A: 1 * 2^-40 + (1 + 2^-11) -> single: 0x3c01, double: 0x3c00 - got_a = run("v_fma_mixlo_f16 v0, v1, v2, v3", 0x3F800000, 0x2B800000, 0x3F801000, old=OLD) - self.assertEqual(got_a, (OLD & 0xFFFF0000) | 0x3C01) - - # Case B: 1 * -2^-40 + (1 + 3 * 2^-11) -> single: 0x3c01, double: 0x3c02 - got_b = run("v_fma_mixhi_f16 v0, v1, v2, v3", 0x3F800000, 0xAB800000, 0x3F803000, old=OLD) - self.assertEqual(got_b, (0x3C01 << 16) | (OLD & 0xFFFF)) - - # Case C: -1 * 2^-40 - (1 + 2^-11) -> single: 0xbc01, double: 0xbc00 - got_c = run("v_fma_mixlo_f16 v0, v1, v2, v3", 0xBF800000, 0x2B800000, 0xBF801000, old=OLD) - self.assertEqual(got_c, (OLD & 0xFFFF0000) | 0xBC01) - - # Case G (f16 operands): (1 + 2^-7) * (2^-11 - 2^-18) + (1 + 2^-10) -> single: 0x3c01, double: 0x3c02 - got_g = run("v_fma_mixlo_f16 v0, v1, v2, v3 op_sel_hi:[1,1,1]", 0x3C08, 0x0FF0, 0x3C01, old=OLD) - self.assertEqual(got_g, (OLD & 0xFFFF0000) | 0x3C01) - - -class NegativeControls(unittest.TestCase): - """Sabotaging the translated SPIR-V must change the observed output.""" - - def test_sabotage_mixhi_half_mask_detected(self): - w0, w1, w2 = pack_h(1.5, 2.0), f2u(2.0), pack_h(0.5, 1.0) - spv, good = translate_and_run("v_fma_mixhi_f16 v0, v1, v2, v3 op_sel_hi:[1,0,1]", w0, w1, w2, old=OLD) - self.assertEqual(good, (f2h(3.5) << 16) | (OLD & 0xFFFF)) - # Replacing the preserved-low-half mask 0xFFFF with 0 wipes OLD's low half. - bad, n = re.subn(r"(OpConstant %uint )65535\b", r"\g<1>0", spv) - self.assertGreaterEqual(n, 1) - self.assertNotEqual(si.run_fragment(bad)["%out_mrt0"][0], good) - - -class FmaMixF32DenormalOperandTests(unittest.TestCase): - """SHADER-298: an f32 operand of v_fma_mix* that is denormal reads as a zero of its sign (the game's MODE has - denorm_mode_32 = 0), measured on gfx1036 by @Sanonymous01 for 0x00000001, 0x807fffff and the integer inline - constants 1 and 64. The result is not flushed here (not measured), so 0 * y + denormal keeps the denormal only - when the denormal is not an operand, which cannot happen; the checks below use operands only.""" - - BIG = f2u(1.0e30) - ZERO = 0x00000000 - NEG_ZERO = 0x80000000 - - def test_denormal_multiplicand_reads_as_zero(self): - # 1.4e-45 * 1e30 = 1.4e-15 if the denormal is kept; 0 if it is flushed. - for d in (0x00000001, 0x007FFFFF): - with self.subTest(denormal=hex(d), slot="src0"): - self.assertEqual(run("v_fma_mix_f32 v0, v1, v2, v3", d, self.BIG, self.ZERO), 0x00000000) - with self.subTest(denormal=hex(d), slot="src1"): - self.assertEqual(run("v_fma_mix_f32 v0, v1, v2, v3", self.BIG, d, self.ZERO), 0x00000000) - - def test_negative_denormal_reads_as_negative_zero(self): - # (-0) * 1e30 + (-0) = -0; a kept denormal would give -1.1e-8-ish tiny non-zero. - for d in (0x80000001, 0x807FFFFF): - with self.subTest(denormal=hex(d)): - self.assertEqual(run("v_fma_mix_f32 v0, v1, v2, v3", d, self.BIG, self.NEG_ZERO), 0x80000000) - - def test_denormal_addend_reads_as_zero(self): - # 0 * y + denormal: the denormal addend is flushed, so the result is +0 (kept it would be the denormal). - self.assertEqual(run("v_fma_mix_f32 v0, v1, v2, v3", self.ZERO, self.BIG, 0x00000001), 0x00000000) - - def test_integer_inline_constants_are_denormal_f32_operands(self): - # `1` and `64` in an f32 operand slot are the words 0x00000001 and 0x00000040: denormal, flushed to +0. - for const in ("1", "64"): - with self.subTest(const=const): - self.assertEqual(run(f"v_fma_mix_f32 v0, {const}, v2, v3", self.ZERO, self.BIG, self.ZERO), 0x00000000) - - def test_normal_operands_are_untouched(self): - a, b, c = f2u(2.5), f2u(-1.25), f2u(0.75) - self.assertEqual(run("v_fma_mix_f32 v0, v1, v2, v3", a, b, c), f2u(ref_fma(a, b, c, (0, 0, 0), (0, 0, 0)))) - smallest_normal = 0x00800000 # 2**-126 is the first value that is not flushed - got = run("v_fma_mix_f32 v0, v1, v2, v3", smallest_normal, f2u(1.0), self.ZERO) - self.assertEqual(got, smallest_normal) - - def test_the_flush_reaches_the_f16_result(self): - # 1.4e-45 * 3e37 = 4.2e-8 rounds to the f16 subnormal 0x0001 if the denormal is kept, and is 0 flushed. - got = run("v_fma_mixlo_f16 v0, v1, v2, v3", 0x00000001, f2u(3.0e37), self.ZERO, old=0xAAAA0000) - self.assertEqual(got, 0xAAAA0000) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_valu_fmamk_fmaak_f16.py b/tests/semantic/test_valu_fmamk_fmaak_f16.py deleted file mode 100644 index 56f2bdeee..000000000 --- a/tests/semantic/test_valu_fmamk_fmaak_f16.py +++ /dev/null @@ -1,102 +0,0 @@ -"""v_fmamk_f16 / v_fmaak_f16 (VOP2 with a literal K) against v_fma_f16, run through spirv_mini_interp on the CPU. - -RDNA2 ISA: v_fmamk_f16 D = S0 * K + S1 (printed `vdst, src0, K, vsrc1`), v_fmaak_f16 D = S0 * S1 + K (printed `vdst, -src0, vsrc1, K`), one rounding to f16; the literal's low 16 bits are K, and the GFX10 f16 VOP2 write keeps D's high -half. Each case must give the bits v_fma_f16 gives with K in a VGPR (v_fma_f16's rounding is tested elsewhere), in the -low half, with the high half kept. Halves are exported ORed into 0x40000000, so no channel is a NaN pattern a float -round trip could change. Standard library only; no GPU, no game files. -""" -import os -import random -import struct -import sys -import tempfile -import unittest -import warnings - -HERE = os.path.dirname(os.path.abspath(__file__)) -ROOT = os.path.dirname(os.path.dirname(HERE)) -sys.dont_write_bytecode = True -sys.path.insert(0, os.environ.get("LEONIDA_TOOLS_DIR") or os.path.join(ROOT, "tools")) -sys.path.insert(0, HERE) - -import rdna2spirv # noqa: E402 -import spirv_mini_interp as si # noqa: E402 - -STUB_DXBC = b"DXBC" + bytes(24) + struct.pack("> 16 == 0x4000 and hi >> 16 == 0x4000, (hex(lo), hex(hi)) - return (lo & 0xFFFF) | (hi & 0xFFFF) << 16 - - -F16 = [0x3C00, 0xBC00, 0x3800, 0x4900, 0x7BFF, 0x0001, 0x8400, 0x3555, 0xC500, 0x0000, 0x8000, 0x7C00] - - -def fma_ref(x, y, z): - """v_fma_f16 v0, v1, v2, v3 with those f16 halves: the reference both literal forms must match.""" - return run("v_fma_f16 v0, v1, v2, v3", {1: x, 2: y, 3: z}) - - -class FmamkFmaakF16(unittest.TestCase): - def test_fmamk_is_s0_times_k_plus_s1(self): - for x in F16[::2]: - for k in F16: - for y in F16[::3]: - with self.subTest(x=hex(x), k=hex(k), y=hex(y)): - got = run(f"v_fmamk_f16 v0, v1, {k:#x}, v2", {1: x, 2: y}) - self.assertEqual(got, fma_ref(x, k, y)) - self.assertEqual(got >> 16, OLD >> 16) # high half kept - - def test_fmaak_is_s0_times_s1_plus_k(self): - for x in F16[::2]: - for y in F16[1::3]: - for k in F16: - with self.subTest(x=hex(x), y=hex(y), k=hex(k)): - got = run(f"v_fmaak_f16 v0, v1, v2, {k:#x}", {1: x, 2: y}) - self.assertEqual(got, fma_ref(x, y, k)) - - def test_float_literal_k_and_operand_order(self): - # A float literal is the f16 of its value; fmamk multiplies by K, fmaak adds it. - two, three, half = 0x4000, 0x4200, 0x3800 - self.assertEqual(run("v_fmamk_f16 v0, v1, 0.5, v2", {1: two, 2: three}) & 0xFFFF, 0x4400) # 2*0.5+3 = 4 - self.assertEqual(run("v_fmaak_f16 v0, v1, v2, 0.5", {1: two, 2: three}) & 0xFFFF, 0x4680) # 2*3+0.5 = 6.5 - self.assertEqual(run(f"v_fmamk_f16 v0, v1, {half:#x}, v2", {1: two, 2: three}) & 0xFFFF, 0x4400) - - def test_seeded(self): - rng = random.Random(0xF16A) - for _ in range(25): - x, y, k = (rng.getrandbits(16) & 0x7BFF | rng.getrandbits(1) << 15 for _ in range(3)) - with self.subTest(x=hex(x), y=hex(y), k=hex(k)): - self.assertEqual(run(f"v_fmamk_f16 v0, v1, {k:#x}, v2", {1: x, 2: y}), fma_ref(x, k, y)) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_valu_fract_f16.py b/tests/semantic/test_valu_fract_f16.py deleted file mode 100644 index 0739f2bda..000000000 --- a/tests/semantic/test_valu_fract_f16.py +++ /dev/null @@ -1,46 +0,0 @@ -"""v_fract_f16 (RDNA2 VOP1 / VOP3): D.f16 = S0.f16 - floor(S0.f16), rounded once to binary16. - -A result that rounds up to 1.0 (a tiny negative operand) is 0x3bff, the largest word below 1; fract(+-0) = +0, fract(+-inf) -is a NaN (0xfe00 on the hardware, a quiet NaN here: compared by class) and a NaN passes through (docs/design.md, -"Float min/max/med3 with NaN, v_fract"). - -Every case is translated by tools/rdna2spirv.py and executed with tests/semantic/spirv_mini_interp.py; the expected -word is written down by hand (from the ISA, values checked independently with float64) next to each case, rechecked -against the plain-Python reference in tests/semantic/f16_unary_cases.py, and extended with seeded random operands, -neg/abs, omod/clamp, op_sel, and SGPR / literal / inline-constant sources. A NaN result is compared by class, not -payload. Standard library only: no GPU, no LLVM, no game data. -""" -import os -import sys -import unittest - -sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) -from f16_unary_cases import (HALF, INF, MAXH, MAX_SUB, MIN_NORMAL, MIN_SUB, NINF, ONE, QNAN, QUARTER, TWO, # noqa: E402,F401 - UnaryF16, ref_fract, run, same_f16) # noqa: F401 - - -class FractF16(UnaryF16, unittest.TestCase): - OP = "v_fract_f16" - ref = staticmethod(ref_fract) - CASES = [ - (0x4180, 0x3A00), (0xC180, 0x3400), # fract(2.75) = 0.75, fract(-2.75) = 0.25 - (HALF, HALF), (0xB800, HALF), (0x3E00, HALF), - (ONE, 0x0000), (0xBC00, 0x0000), (0x6800, 0x0000), (MAXH, 0x0000), (0xFBFF, 0x0000), - (0x1400, 0x1400), # 2^-10 is already below 1 - (0x9400, 0x3BFE), # fract(-2^-10) = 1 - 2^-10 is exact - (0xBBFF, 0x1000), # fract(-0.99951171875) = 2^-11 - (0x3BFF, 0x3BFF), - (MIN_SUB, MIN_SUB), (MAX_SUB, MAX_SUB), - (0x8001, 0x3BFF), # fract(-2^-24) = 1 - 2^-24 rounds to 1.0, which is written 0x3bff - (0x8400, 0x3BFF), # likewise -2^-14 - (0x0000, 0x0000), (0x8000, 0x0000), # fract(-0) = +0 - (INF, QNAN), (NINF, QNAN), (QNAN, QNAN), - ] - MOD_INPUTS = [0x4180, 0x3E00, 0xC180, 0x3400] - INLINE = [("0.5", HALF, HALF), ("-0.5", 0xB800, HALF), ("2.0", TWO, 0x0000), ("-1.0", 0xBC00, 0x0000), - ("0.15915494", 0x3118, 0x3118)] - OP_SEL = [((0xC180 << 16) | 0x4180, 0x3A00, 0x3400)] # lo 2.75 / hi -2.75 - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_valu_fract_f32.py b/tests/semantic/test_valu_fract_f32.py deleted file mode 100644 index 200339c3f..000000000 --- a/tests/semantic/test_valu_fract_f32.py +++ /dev/null @@ -1,1239 +0,0 @@ -from __future__ import annotations - -"""End-to-end semantic value tests for RDNA2 v_fract_f32 and v_fract_f16. - -Covers v_fract_f32 (single-precision) and v_fract_f16 (half-precision) executed -end-to-end through tools/rdna2spirv.py and tests/semantic/spirv_mini_interp.py -against independent Fraction-based IEEE-754 `x - floor(x)` reference oracles: - - Formula: D = S0 - floor(S0), returning values in [0.0, 1.0). - - Non-negative property: for any finite input x, fract(x) >= 0.0 and fract(x) < 1.0. - - Negative number fractional part: fract(-0.25) == 0.75, fract(-1.75) == 0.25, - fract(-0.5) == 0.5, fract(-0.75) == 0.25. - - Exact integers: fract(N.0) == +0.0 (0.0, 1.0, -1.0, 2.0, -2.0, 42.0, etc.). - - Large numbers with no fractional bits in mantissa: - * Single-precision (|x| >= 2^23 = 8388608.0 for f32) yields +0.0, while - 2^23 - 0.5 (8388607.5) preserves fractional part 0.5. - * Half-precision (|x| >= 2^10 = 1024.0 for f16) yields +0.0, while - 1023.5 preserves fractional part 0.5. - - Special IEEE-754 values: - * +0.0 -> +0.0 and -0.0 -> +0.0 (sign bit strictly 0). - * +-inf -> NaN and NaN -> NaN. - - Subnormal bounds and rounding transitions: - * Positive subnormals (x in (0, 2^-126) for f32, (0, 2^-14) for f16) have - floor(x) == 0, so fract(x) == x exact. - * Negative subnormals and tiny negatives: x - floor(x) = 1.0 - |x|, which - rounds to 1.0 in IEEE-754 nearest-even. The RDNA2 hardware contract and - translator clamp any result that rounded up to 1.0 to 0x3F7FFFFF (f32, - largest float < 1.0) and 0x3BFF (f16, largest half < 1.0). - - Forms: _e32, _e64, and bare mnemonics. - - Half-precision op_sel combinations ([0,0], [1,0], [0,1], [1,1]) preserving - untouched halves of destination VGPRs. - - VOP3 source modifiers (-v1, |v1|, -|v1|) and output modifiers - (clamp, mul:2, mul:4, div:2, mul:2 clamp, mul:4 clamp). - - Inline constants (0.5, -0.5, 1.0, -1.0), SGPR sources (s4), destination - aliasing (v0, v0), and runtime memory inputs via s_buffer_load_dwordx4. - - Negative controls: mutating SPIR-V Fract to Trunc/Floor or removing the - rounding clamp fails test assertions. - - Multi-lane SIMD divergence under EXEC mask across 8-thread, 16-thread, and - 32-thread compute wavefronts. - -Zero game data; hand-written RDNA2 assembly only; standard library Python only. -""" - -from fractions import Fraction -import gc -import itertools -import math -import os -import re -import struct -import sys -import tempfile -import unittest -import warnings - -HERE = os.path.dirname(os.path.abspath(__file__)) -ROOT = os.path.dirname(os.path.dirname(HERE)) -TOOLS_DIR = os.environ.get("LEONIDA_TOOLS_DIR") or os.path.join(ROOT, "tools") - -sys.dont_write_bytecode = True -if TOOLS_DIR not in sys.path: - sys.path.insert(0, TOOLS_DIR) -if HERE not in sys.path: - sys.path.insert(0, HERE) - -import rdna2spirv # noqa: E402 -import spirv_mini_interp as si # noqa: E402 - -STUB_DXBC = b"DXBC" + bytes(24) + struct.pack(" 0.0) -H_NEG_1024 = 0xE400 # -1024.0 -H_2048 = 0x6800 # 2048.0 -H_MAX = 0x7BFF # 65504.0 -H_NEG_MAX = 0xFBFF # -65504.0 -H_POS_INF = 0x7C00 # +inf -H_NEG_INF = 0xFC00 # -inf -H_QNAN = 0x7E01 # +qNaN -H_NEG_QNAN = 0xFE01 # -qNaN -H_SNAN = 0x7C01 # +sNaN -H_NEG_SNAN = 0xFC01 # -sNaN - - -# ----------------------------------------------------------------------------- -# Independent Fraction-Based IEEE-754 Binary32 Oracle -# ----------------------------------------------------------------------------- - -def f32_is_finite(w: int) -> bool: - return ((w >> 23) & 0xFF) != 0xFF - - -def f32_is_nan(w: int) -> bool: - return ((w >> 23) & 0xFF) == 0xFF and (w & 0x7FFFFF) != 0 - - -def f32_is_inf(w: int) -> bool: - return (w & 0x7FFFFFFF) == 0x7F800000 - - -def f32_to_fraction(w: int) -> Fraction: - """Decode finite IEEE-754 binary32 bit pattern ``w`` into an exact Fraction.""" - w &= 0xFFFFFFFF - exp = (w >> 23) & 0xFF - if exp == 0xFF: - raise ValueError(f"non-finite binary32 {w:#010x}") - sign = -1 if (w >> 31) else 1 - mant = w & 0x7FFFFF - if exp == 0: - return Fraction(0) if mant == 0 else Fraction(sign * mant, 1 << 149) - return Fraction(sign * ((1 << 23) | mant)) * (Fraction(2) ** (exp - 150)) - - -def fraction_to_f32(q: Fraction) -> int: - """Round an exact Fraction to IEEE-754 binary32 (round-to-nearest, ties-to-even).""" - if q == 0: - return F_POS_ZERO - sgn = 0x80000000 if q < 0 else 0 - a = abs(q) - e = max(a.numerator.bit_length() - a.denominator.bit_length(), -126) - if e > -126 and Fraction(2) ** e > a: - e -= 1 - m = a / (Fraction(2) ** (e - 23)) - n = m.numerator // m.denominator - rem = m - n - if rem > Fraction(1, 2) or (rem == Fraction(1, 2) and (n & 1)): - n += 1 - if e == -126 and n < (1 << 23): - return sgn | n - if n >= (1 << 24): - n >>= 1 - e += 1 - if e > 127: - return sgn | F_POS_INF - return sgn | ((e + 127) << 23) | (n - (1 << 23)) - - -def exact_fract_f32_fraction(w: int) -> Fraction | None: - """Exact ``x - floor(x)`` as a Fraction in [0, 1), or None for +-inf / NaN.""" - if not f32_is_finite(w): - return None - q = f32_to_fraction(w) - return q - math.floor(q) - - -def oracle_fract_f32( - w: int, - *, - abs_: bool = False, - neg: bool = False, - mul: int = 1, - div: int = 1, - clamp: bool = False, -) -> int | None: - """Independent binary32 reference for v_fract_f32, returning 32-bit int or None for NaN. - - Models RDNA2 source modifiers (abs before neg), exact ``x - floor(x)``, - the hardware/translator 0x3f800000 -> 0x3f7fffff clamp when no output multiplier is - active, and VOP3 output scaling (mul/div) + [0, 1] clamp. - """ - w &= 0xFFFFFFFF - if abs_: - w &= 0x7FFFFFFF - if neg: - w ^= 0x80000000 - if w & 0x7F800000 == 0: - w = 0 # a denormal (or -0) operand reads as +0 with f32 denormals flushed, as on RDNA2 in the game's MODE - r = exact_fract_f32_fraction(w) - if r is None: - return None - if mul == 1 and div == 1: - res = fraction_to_f32(r) - return F_NEAR_ONE if res == F_1P0 else res - scaled = r * Fraction(mul, div) - if clamp: - scaled = min(max(scaled, Fraction(0)), Fraction(1)) - return fraction_to_f32(scaled) - - -# ----------------------------------------------------------------------------- -# Independent Fraction-Based IEEE-754 Binary16 Oracle -# ----------------------------------------------------------------------------- - -def h16_is_finite(h: int) -> bool: - return ((h >> 10) & 0x1F) != 0x1F - - -def h16_is_nan(h: int) -> bool: - return (h & 0x7FFF) > 0x7C00 - - -def h16_is_inf(h: int) -> bool: - return (h & 0x7FFF) == 0x7C00 - - -def h16_to_fraction(h: int) -> Fraction: - """Decode finite IEEE-754 binary16 bit pattern ``h`` into an exact Fraction.""" - h &= 0xFFFF - exp = (h >> 10) & 0x1F - if exp == 0x1F: - raise ValueError(f"non-finite binary16 {h:#06x}") - sign = -1 if (h >> 15) else 1 - mant = h & 0x3FF - if exp == 0: - return Fraction(0) if mant == 0 else Fraction(sign * mant, 1 << 24) - return Fraction(sign * ((1 << 10) | mant)) * (Fraction(2) ** (exp - 25)) - - -def fraction_to_h16(q: Fraction) -> int: - """Round an exact Fraction to IEEE-754 binary16 (nearest, ties to even).""" - if q == 0: - return H_POS_ZERO - sgn = 0x8000 if q < 0 else 0 - a = abs(q) - e = max(a.numerator.bit_length() - a.denominator.bit_length(), -14) - if e > -14 and Fraction(2) ** e > a: - e -= 1 - m = a / (Fraction(2) ** (e - 10)) - n = m.numerator // m.denominator - rem = m - n - if rem > Fraction(1, 2) or (rem == Fraction(1, 2) and (n & 1)): - n += 1 - if e == -14 and n < 1024: - return sgn | n - if n >= 2048: - n >>= 1 - e += 1 - if e > 15: - return sgn | H_POS_INF - return sgn | ((e + 15) << 10) | (n - 1024) - - -def exact_fract_f16_fraction(h: int) -> Fraction | None: - """Exact ``x - floor(x)`` as a Fraction in [0, 1), or None for +-inf / NaN.""" - if not h16_is_finite(h): - return None - q = h16_to_fraction(h) - return q - math.floor(q) - - -def oracle_fract_f16( - h: int, - *, - abs_: bool = False, - neg: bool = False, - mul: int = 1, - div: int = 1, - clamp: bool = False, -) -> int | None: - """Independent binary16 reference for v_fract_f16, returning 16-bit int or None for NaN.""" - h &= 0xFFFF - if abs_: - h &= 0x7FFF - if neg: - h ^= 0x8000 - r = exact_fract_f16_fraction(h) - if r is None: - return None - if mul == 1 and div == 1: - res = fraction_to_h16(r) - return H_NEAR_ONE if res == H_1P0 else res - scaled = r * Fraction(mul, div) - if clamp: - scaled = min(max(scaled, Fraction(0)), Fraction(1)) - return fraction_to_h16(scaled) - - -def merge_half(old: int, half: int, dst_hi: int) -> int: - h = half & 0xFFFF - return ((h << 16) | (old & 0xFFFF)) if dst_hi else ((old & 0xFFFF0000) | h) - - -# ----------------------------------------------------------------------------- -# Translation & Execution Helpers -# ----------------------------------------------------------------------------- - -_TMP_DIR = None -_PS_PATH = None -_CS_PATH = None -_CS_FSSM = None - - -def _make_fssm(rsrc2: int, group: tuple[int, int, int]) -> bytes: - header = bytearray(0x148) - struct.pack_into("<4I", header, 0x138, rsrc2, *group) - return bytes(header) - - -def setUpModule(): - global _TMP_DIR, _PS_PATH, _CS_PATH, _CS_FSSM - _TMP_DIR = tempfile.TemporaryDirectory() - disasm_dir = os.path.join(_TMP_DIR.name, "disasm") - fssm_dir = os.path.join(_TMP_DIR.name, "fssm") - os.mkdir(disasm_dir) - os.mkdir(fssm_dir) - _PS_PATH = os.path.join(disasm_dir, "ps_fract_f32.s") - _CS_PATH = os.path.join(disasm_dir, "cs_fract_f32.s") - _CS_FSSM = os.path.join(fssm_dir, "cs_fract_f32.fssm") - with open(os.path.join(_TMP_DIR.name, "ps_fract_f32.dxbc"), "wb") as f: - f.write(STUB_DXBC) - - -def tearDownModule(): - global _TMP_DIR, _PS_PATH, _CS_PATH, _CS_FSSM - if _TMP_DIR is not None: - gc.collect() - _TMP_DIR.cleanup() - _TMP_DIR = None - _PS_PATH = None - _CS_PATH = None - _CS_FSSM = None - - -def translate_ps(lines: list[str]) -> str: - if _TMP_DIR is None: - setUpModule() - asm = ( - "; test_valu_fract_f32\n" - + "".join(f"\t{ln}\n" for ln in lines) - + "\texp mrt0 v0, v0, v0, v0 done vm\n\ts_endpgm\n" - ) - with open(_PS_PATH, "w", encoding="utf-8", newline="\n") as f: - f.write(asm) - with warnings.catch_warnings(): - warnings.simplefilter("ignore", ResourceWarning) - spv = rdna2spirv.translate(_PS_PATH) - gc.collect() - return spv - - -def run_ps(lines: list[str], *, push_constants=None, memory=None) -> int: - out = si.run_fragment(translate_ps(lines), push_constants=push_constants, memory=memory) - return out["%out_mrt0"][0] - - -def run_op(line: str, v1: int = 0, *, old: int = OLD, s4: int = 0) -> int: - return run_ps([ - f"s_mov_b32 s4, {s4:#x}", - f"v_mov_b32 v1, {v1:#x}", - f"v_mov_b32 v0, {old:#x}", - line, - ]) - - -def run_cs(lines: list[str], group_size: int, memory: dict[int, int]) -> None: - if _TMP_DIR is None: - setUpModule() - # rsrc2 = 0x0088: USER_SGPR = 4 (s[0:3] V#), TGID_X_EN = 1 (s4), TIDIG_COMP_CNT = 0 (v0 = local_id.x). - with open(_CS_FSSM, "wb") as f: - f.write(_make_fssm(0x0088, (group_size, 1, 1))) - asm = "; test_cs_valu_fract_f32\n" + "".join(f"\t{ln}\n" for ln in lines) + "\ts_endpgm\n" - with open(_CS_PATH, "w", encoding="utf-8", newline="\n") as f: - f.write(asm) - with warnings.catch_warnings(): - warnings.simplefilter("ignore", ResourceWarning) - spv = rdna2spirv.translate(_CS_PATH) - gc.collect() - si.run_workgroup( - spv, - group_size, - 32, - inputs_for=lambda i: {"%wg_id": (0, 0, 0), "%local_id": (i, 0, 0)}, - push_constants=VSHARP_CS + [0] * 28, - memory=memory, - ) - - -class _Heap(dict): - def get(self, key, default=None): - return super().get(key, HEAP_FILL) - - -# ----------------------------------------------------------------------------- -# Oracle Unit Tests -# ----------------------------------------------------------------------------- - -class OracleF32Tests(unittest.TestCase): - """Verifies the independent Fraction-based binary32 oracle against IEEE-754 semantics.""" - - def test_fraction_decode_and_roundtrip(self): - samples = [ - F_POS_ZERO, F_NEG_ZERO, - F_SUB_MIN, F_NEG_SUB_MIN, F_SUB_1E40, F_NEG_SUB_1E40, - F_SUB_MAX, F_NEG_SUB_MAX, F_NORM_MIN, F_NEG_NORM_MIN, - F_NEG_1E10, F_NEG_2PM26, F_NEG_2PM25, F_NEG_2PM24, F_NEG_2PM23, - F_0P125, F_0P25, F_NEG_0P25, F_0P375, - F_0P5, F_NEG_0P5, F_0P75, F_NEG_0P75, - F_NEAR_ONE, F_1P0, F_NEG_1P0, - F_1P25, F_NEG_1P25, F_1P5, F_NEG_1P5, F_1P75, F_NEG_1P75, - F_2P0, F_NEG_2P0, F_2P5, F_NEG_2P5, F_3P0, F_NEG_3P0, - F_3P75, F_NEG_3P75, F_42P0, F_NEG_42P0, - F_1023P5, F_1024P0, F_1024P25, - F_2P23_M0P5, F_2P23, F_NEG_2P23, F_2P24, F_NEG_2P24, - ] - for w in samples: - with self.subTest(w=hex(w)): - self.assertTrue(f32_is_finite(w)) - q = f32_to_fraction(w) - expected_float = struct.unpack("= 0.0 and fract(x) < 1.0 for all finite numbers - test_inputs = [ - -100.5, -42.25, -10.75, -2.5, -1.75, -1.25, -0.75, -0.5, -0.25, -0.0, - 0.0, 0.25, 0.5, 0.75, 1.0, 1.25, 1.5, 1.75, 2.0, 42.125, 100.875, - ] - for val in test_inputs: - bits = struct.unpack("= 2^23 has no fractional bits in IEEE binary32 mantissa -> fract(x) == 0.0 - for exp in range(23, 31): - val_pos = float(1 << exp) - val_neg = -val_pos - w_pos = struct.unpack("= 2^10 (1024.0) has no fractional bits. - for h in (H_1024, H_NEG_1024, H_2048, H_MAX, H_NEG_MAX): - with self.subTest(h=hex(h)): - self.assertEqual(oracle_fract_f16(h), H_POS_ZERO) - - def test_special_ieee_oracle_f16(self): - self.assertEqual(oracle_fract_f16(H_POS_ZERO), H_POS_ZERO) - self.assertEqual(oracle_fract_f16(H_NEG_ZERO), H_POS_ZERO) - self.assertIsNone(oracle_fract_f16(H_POS_INF)) - self.assertIsNone(oracle_fract_f16(H_NEG_INF)) - self.assertIsNone(oracle_fract_f16(H_QNAN)) - self.assertIsNone(oracle_fract_f16(H_NEG_QNAN)) - self.assertIsNone(oracle_fract_f16(H_SNAN)) - self.assertIsNone(oracle_fract_f16(H_NEG_SNAN)) - - -class PrecisionF32VsF16Tests(unittest.TestCase): - """Contrasts precision limits and verifies mathematical agreement between f32 and f16.""" - - def test_common_exact_fractions_identical_mathematics(self): - pairs = [ - (F_0P25, H_0P25), - (F_NEG_0P25, H_NEG_0P25), - (F_0P5, H_0P5), - (F_NEG_0P5, H_NEG_0P5), - (F_0P75, H_0P75), - (F_NEG_0P75, H_NEG_0P75), - (F_1P25, H_1P25), - (F_NEG_1P25, H_NEG_1P25), - (F_1P75, H_1P75), - (F_NEG_1P75, H_NEG_1P75), - (F_3P75, H_3P75), - (F_NEG_3P75, H_NEG_3P75), - (F_1023P5, H_1023P5), - ] - for f_w, h_w in pairs: - q32 = f32_to_fraction(oracle_fract_f32(f_w)) - q16 = h16_to_fraction(oracle_fract_f16(h_w)) - with self.subTest(f_w=hex(f_w), h_w=hex(h_w)): - self.assertEqual(q32, q16) - - def test_mantissa_exhaustion_divergence_between_precisions(self): - # At 1024.25: - # In f32, 1024.25 is exact -> fract is 0.25 (0x3E800000). - self.assertEqual(oracle_fract_f32(F_1024P25), F_0P25) - # In f16, 1024.25 cannot be represented: it rounds to 1024.0 -> fract is +0.0 (0x0000). - f16_rounded_1024p25 = fraction_to_h16(Fraction(102425, 100)) - self.assertEqual(f16_rounded_1024p25, H_1024) - self.assertEqual(oracle_fract_f16(f16_rounded_1024p25), H_POS_ZERO) - - # At 2^23 - 0.5 (8388607.5): - # In f32, 8388607.5 is exact -> fract is 0.5 (0x3F000000). - self.assertEqual(oracle_fract_f32(F_2P23_M0P5), F_0P5) - # At 2^23 (8388608.0): - # In f32, mantissa bits are exhausted -> fract is +0.0 (0x00000000). - self.assertEqual(oracle_fract_f32(F_2P23), F_POS_ZERO) - - -# ----------------------------------------------------------------------------- -# End-to-End Execution Tests -# ----------------------------------------------------------------------------- - -class FractF32ExecutionTests(unittest.TestCase): - """End-to-end execution of RDNA2 v_fract_f32 through rdna2spirv and spirv_mini_interp.""" - - def test_finite_values_across_e32_e64_and_bare(self): - samples = [ - F_POS_ZERO, F_NEG_ZERO, - F_0P125, F_0P25, F_NEG_0P25, F_0P375, - F_0P5, F_NEG_0P5, F_0P75, F_NEG_0P75, - F_NEAR_ONE, F_1P0, F_NEG_1P0, - F_1P25, F_NEG_1P25, F_1P5, F_NEG_1P5, F_1P75, F_NEG_1P75, - F_2P0, F_NEG_2P0, F_2P5, F_NEG_2P5, F_3P0, F_NEG_3P0, - F_3P75, F_NEG_3P75, F_42P0, F_NEG_42P0, - F_1023P5, F_1024P0, F_1024P25, - F_2P23_M0P5, F_2P23, F_NEG_2P23, F_2P24, F_NEG_2P24, - ] - for suffix in ("_e32", "_e64", ""): - for w in samples: - want = oracle_fract_f32(w) - with self.subTest(form="v_fract_f32" + suffix, w=hex(w)): - self.assertEqual(run_op(f"v_fract_f32{suffix} v0, v1", w), want) - - def test_negative_number_fractional_part(self): - # Specific assertion: fract(-0.25) == 0.75, fract(-1.75) == 0.25 - self.assertEqual(run_op("v_fract_f32_e32 v0, v1", F_NEG_0P25), F_0P75) - self.assertEqual(run_op("v_fract_f32_e32 v0, v1", F_NEG_1P75), F_0P25) - self.assertEqual(run_op("v_fract_f32_e32 v0, v1", F_NEG_0P5), F_0P5) - self.assertEqual(run_op("v_fract_f32_e32 v0, v1", F_NEG_0P75), F_0P25) - self.assertEqual(run_op("v_fract_f32_e32 v0, v1", F_NEG_1P25), F_0P75) - self.assertEqual(run_op("v_fract_f32_e32 v0, v1", F_NEG_2P5), F_0P5) - self.assertEqual(run_op("v_fract_f32_e32 v0, v1", F_NEG_3P75), F_0P25) - - def test_exact_integers_and_signed_zero(self): - # Integers and +-0.0 must yield +0.0 (sign bit must be 0) - cases = [ - F_POS_ZERO, F_NEG_ZERO, - F_1P0, F_NEG_1P0, - F_2P0, F_NEG_2P0, - F_3P0, F_NEG_3P0, - F_42P0, F_NEG_42P0, - F_1024P0, - F_2P23, F_NEG_2P23, - F_2P24, F_NEG_2P24, - ] - for w in cases: - with self.subTest(w=hex(w)): - got = run_op("v_fract_f32_e32 v0, v1", w) - self.assertEqual(got, F_POS_ZERO) - self.assertNotEqual(got, F_NEG_ZERO) - - def test_large_numbers_no_fractional_bits(self): - # 2^23 has no fractional bits -> 0.0 - self.assertEqual(run_op("v_fract_f32_e32 v0, v1", F_2P23), F_POS_ZERO) - self.assertEqual(run_op("v_fract_f32_e32 v0, v1", F_NEG_2P23), F_POS_ZERO) - self.assertEqual(run_op("v_fract_f32_e32 v0, v1", F_2P24), F_POS_ZERO) - self.assertEqual(run_op("v_fract_f32_e32 v0, v1", F_NEG_2P24), F_POS_ZERO) - # 2^23 - 0.5 has fractional bit 0.5 - self.assertEqual(run_op("v_fract_f32_e32 v0, v1", F_2P23_M0P5), F_0P5) - - def test_special_ieee_values_execution(self): - for w in (F_POS_INF, F_NEG_INF, F_QNAN, F_NEG_QNAN, F_SNAN, F_NEG_SNAN): - for suffix in ("_e32", "_e64", ""): - with self.subTest(w=hex(w), suffix=suffix): - got = run_op(f"v_fract_f32{suffix} v0, v1", w) - self.assertTrue(f32_is_nan(got), f"expected NaN, got {got:#010x}") - - def test_vop3_source_modifiers(self): - cases = [ - ("v_fract_f32_e64 v0, -v1", F_0P25, False, True), # -(0.25) -> 0.75 - ("v_fract_f32_e64 v0, -v1", F_NEG_0P25, False, True), # -(-0.25) -> 0.25 - ("v_fract_f32_e64 v0, -v1", F_1P75, False, True), # -(1.75) -> 0.25 - ("v_fract_f32_e64 v0, -v1", F_POS_ZERO, False, True), # -(0.0) -> +0.0 - ("v_fract_f32_e64 v0, -v1", F_1P0, False, True), # -(1.0) -> +0.0 - ("v_fract_f32_e64 v0, |v1|", F_NEG_0P25, True, False), # |-0.25| = 0.25 -> 0.25 - ("v_fract_f32_e64 v0, |v1|", F_NEG_1P75, True, False), # |-1.75| = 1.75 -> 0.75 - ("v_fract_f32_e64 v0, -|v1|", F_0P25, True, True), # -|0.25| = -0.25 -> 0.75 - ("v_fract_f32_e64 v0, -|v1|", F_NEG_0P25, True, True), # -|-0.25| = -0.25 -> 0.75 - ("v_fract_f32_e64 v0, -|v1|", F_1P75, True, True), # -|1.75| = -1.75 -> 0.25 - ] - for line, w, abs_, neg in cases: - with self.subTest(line=line, w=hex(w)): - want = oracle_fract_f32(w, abs_=abs_, neg=neg) - self.assertEqual(run_op(line, w), want) - - def test_vop3_output_modifiers(self): - cases = [ - ("clamp", F_0P75, dict(clamp=True)), - ("clamp", F_NEG_0P25, dict(clamp=True)), - ("clamp", F_NEG_ZERO, dict(clamp=True)), - ("mul:2", F_0P5, dict(mul=2)), - ("mul:2", F_0P75, dict(mul=2)), - ("mul:2", F_NEG_0P25, dict(mul=2)), - ("mul:4", F_0P25, dict(mul=4)), - ("mul:4", F_0P5, dict(mul=4)), - ("mul:4", F_NEG_1P25, dict(mul=4)), - ("div:2", F_0P5, dict(div=2)), - ("div:2", F_NEG_1P25, dict(div=2)), - ("div:2", F_0P25, dict(div=2)), - ("mul:2 clamp", F_0P25, dict(mul=2, clamp=True)), - ("mul:2 clamp", F_0P5, dict(mul=2, clamp=True)), - ("mul:2 clamp", F_0P75, dict(mul=2, clamp=True)), - ("mul:2 clamp", F_NEG_0P25, dict(mul=2, clamp=True)), - ("mul:4 clamp", F_0P5, dict(mul=4, clamp=True)), - ] - for suffix, w, kw in cases: - line = f"v_fract_f32_e64 v0, v1 {suffix}" - want = oracle_fract_f32(w, **kw) - with self.subTest(line=line, w=hex(w)): - self.assertEqual(run_op(line, w), want) - - # Explicit verification of key omod scaling values - self.assertEqual(run_op("v_fract_f32_e64 v0, v1 mul:2", F_0P5), F_1P0) - self.assertEqual(run_op("v_fract_f32_e64 v0, v1 mul:2 clamp", F_0P75), F_1P0) - self.assertEqual(run_op("v_fract_f32_e64 v0, v1 mul:4", F_0P5), F_2P0) - self.assertEqual(run_op("v_fract_f32_e64 v0, v1 div:2", F_0P5), F_0P25) - - def test_inline_float_constants(self): - for lit, w in (("0.5", F_0P5), ("-0.5", F_NEG_0P5), ("1.0", F_1P0), ("-1.0", F_NEG_1P0)): - want = oracle_fract_f32(w) - for form in ("_e32", "_e64", ""): - with self.subTest(lit=lit, form=form or "bare"): - self.assertEqual(run_op(f"v_fract_f32{form} v0, {lit}"), want) - - self.assertEqual(run_op("v_fract_f32_e64 v0, -0.5 mul:2"), F_1P0) - self.assertEqual(run_op("v_fract_f32_e64 v0, -0.5 div:2"), F_0P25) - - def test_sgpr_sources_and_destination_aliasing(self): - s4 = F_NEG_0P25 - self.assertEqual(run_op("v_fract_f32_e32 v0, s4", s4=s4), F_0P75) - self.assertEqual(run_op("v_fract_f32_e64 v0, s4", s4=s4), F_0P75) - self.assertEqual(run_op("v_fract_f32_e64 v0, -s4", s4=s4), F_0P25) - self.assertEqual(run_op("v_fract_f32_e64 v0, |s4|", s4=s4), F_0P25) - - # Destination aliasing: dst == src (v0, v0) - self.assertEqual( - run_ps([f"v_mov_b32 v0, {F_NEG_0P25:#x}", "v_fract_f32_e32 v0, v0"]), - F_0P75, - ) - self.assertEqual( - run_ps([f"v_mov_b32 v0, {F_3P75:#x}", "v_fract_f32 v0, v0"]), - F_0P75, - ) - self.assertEqual( - run_ps([f"v_mov_b32 v0, {F_NEG_1P75:#x}", "v_fract_f32_e64 v0, v0"]), - F_0P25, - ) - - def test_runtime_memory_inputs_via_s_buffer_load(self): - lanes = [F_NEG_0P25, F_3P75, F_NEG_1P75, F_POS_ZERO] - mem = {0x1000 + 4 * i: w for i, w in enumerate(lanes)} - for idx, w in enumerate(lanes): - reg = f"v{idx + 1}" - lines = [ - "s_buffer_load_dwordx4 s[4:7], s[0:3], 0", - "s_waitcnt lgkmcnt(0)", - "v_mov_b32_e32 v1, s4", - "v_mov_b32_e32 v2, s5", - "v_mov_b32_e32 v3, s6", - "v_mov_b32_e32 v4, s7", - f"v_mov_b32_e32 v0, {OLD:#x}", - f"v_fract_f32_e32 v0, {reg}", - ] - got = run_ps(lines, push_constants=PUSH_ADDR, memory=mem) - self.assertEqual(got, oracle_fract_f32(w)) - - -class FractF16AndEdgeCaseExecutionTests(unittest.TestCase): - """Execution tests for v_fract_f16, op_sel, and joint IEEE-754 edge cases.""" - - def test_f16_basic_execution_and_opsel(self): - samples = [ - H_POS_ZERO, H_NEG_ZERO, - H_0P125, H_0P25, H_NEG_0P25, H_0P375, - H_0P5, H_NEG_0P5, H_0P75, H_NEG_0P75, - H_NEAR_ONE, H_1P0, H_NEG_1P0, - H_1P25, H_NEG_1P25, H_1P5, H_NEG_1P5, H_1P75, H_NEG_1P75, - H_2P0, H_NEG_2P0, H_2P5, H_NEG_2P5, H_3P0, H_NEG_3P0, - H_3P75, H_NEG_3P75, H_1023P5, H_1024, H_NEG_1024, - H_MAX, H_NEG_MAX, - ] - for h in samples: - want = oracle_fract_f16(h) - v1_lo = 0x55550000 | h - self.assertEqual(run_op("v_fract_f16_e32 v0, v1", v1_lo), merge_half(OLD, want, 0)) - self.assertEqual(run_op("v_fract_f16 v0, v1", v1_lo), merge_half(OLD, want, 0)) - - # Test op_sel across all 4 combinations - v1 = (H_NEG_1P75 << 16) | H_NEG_0P25 # hi: -1.75 -> 0.25; lo: -0.25 -> 0.75 - for src_hi, dst_hi in itertools.product((0, 1), repeat=2): - h_in = H_NEG_1P75 if src_hi else H_NEG_0P25 - want_h = oracle_fract_f16(h_in) - line = f"v_fract_f16_e64 v0, v1 op_sel:[{src_hi},{dst_hi}]" - with self.subTest(src_hi=src_hi, dst_hi=dst_hi): - self.assertEqual(run_op(line, v1), merge_half(OLD, want_h, dst_hi)) - - def test_f16_negative_number_fractional_part(self): - # Specific assertions for half-precision: fract(-0.25) == 0.75, fract(-1.75) == 0.25 - v_lo_0p25 = 0xAAAA0000 | H_NEG_0P25 - v_lo_1p75 = 0xAAAA0000 | H_NEG_1P75 - self.assertEqual(run_op("v_fract_f16_e32 v0, v1", v_lo_0p25), merge_half(OLD, H_0P75, 0)) - self.assertEqual(run_op("v_fract_f16_e32 v0, v1", v_lo_1p75), merge_half(OLD, H_0P25, 0)) - - def test_f16_mantissa_exhaustion_execution(self): - # Numbers >= 1024.0 in f16 yield 0.0, while 1023.5 yields 0.5 - self.assertEqual(run_op("v_fract_f16_e32 v0, v1", H_1024), merge_half(OLD, H_POS_ZERO, 0)) - self.assertEqual(run_op("v_fract_f16_e32 v0, v1", H_NEG_1024), merge_half(OLD, H_POS_ZERO, 0)) - self.assertEqual(run_op("v_fract_f16_e32 v0, v1", H_MAX), merge_half(OLD, H_POS_ZERO, 0)) - self.assertEqual(run_op("v_fract_f16_e32 v0, v1", H_NEG_MAX), merge_half(OLD, H_POS_ZERO, 0)) - self.assertEqual(run_op("v_fract_f16_e32 v0, v1", H_1023P5), merge_half(OLD, H_0P5, 0)) - - def test_f16_vop3_modifiers(self): - # Source modifiers - v1 = (H_0P25 << 16) | H_NEG_0P25 - self.assertEqual( - run_op("v_fract_f16_e64 v0, -v1 op_sel:[0,0]", v1), - merge_half(OLD, H_0P25, 0), # -(-0.25) = 0.25 -> 0.25 - ) - self.assertEqual( - run_op("v_fract_f16_e64 v0, |v1| op_sel:[0,0]", v1), - merge_half(OLD, H_0P25, 0), # |-0.25| = 0.25 -> 0.25 - ) - # Output modifiers: on RDNA2 with denorms kept, omod is ignored on f16. - self.assertEqual( - run_op("v_fract_f16_e64 v0, v1 mul:2", H_0P5), - merge_half(OLD, H_0P5, 0), - ) - self.assertEqual( - run_op("v_fract_f16_e64 v0, v1 div:2", H_0P5), - merge_half(OLD, H_0P5, 0), - ) - - def test_ieee754_zero_sign_clearing_joint(self): - # Both f32 and f16 with -0.0 must return +0.0 (sign bit cleared) - got_f32 = run_op("v_fract_f32_e32 v0, v1", F_NEG_ZERO) - self.assertEqual(got_f32, F_POS_ZERO) - self.assertEqual(got_f32 & 0x80000000, 0) - - got_f16 = run_op("v_fract_f16_e32 v0, v1", H_NEG_ZERO) - self.assertEqual(got_f16 & 0xFFFF, H_POS_ZERO) - self.assertEqual((got_f16 & 0x8000), 0) - - def test_ieee754_inf_nan_joint(self): - # Both f32 and f16 with +-inf or NaN must return NaN - for w in (F_POS_INF, F_NEG_INF, F_QNAN, F_SNAN): - got = run_op("v_fract_f32_e32 v0, v1", w) - self.assertTrue(f32_is_nan(got), f"expected f32 NaN for {w:#010x}") - - for h in (H_POS_INF, H_NEG_INF, H_QNAN, H_SNAN): - got = run_op("v_fract_f16_e32 v0, v1", h) - self.assertTrue(h16_is_nan(got & 0xFFFF), f"expected f16 NaN for {h:#06x}") - - def test_joint_f32_f16_shader_pipeline(self): - lines = [ - f"v_mov_b32 v1, {F_NEG_0P25:#x}", - f"v_mov_b32 v2, {H_NEG_1P75:#x}", - "v_fract_f32_e32 v0, v1", - "v_fract_f16_e32 v3, v2", - "exp mrt0 v0, v3, v0, v3 done vm", - "s_endpgm", - ] - spv = translate_ps(lines) - out = si.run_fragment(spv)["%out_mrt0"] - self.assertEqual(out[0], F_0P75) - self.assertEqual(out[1] & 0xFFFF, H_0P25) - self.assertEqual(out[2], F_0P75) - self.assertEqual(out[3] & 0xFFFF, H_0P25) - - -# ----------------------------------------------------------------------------- -# Subnormal Bounds, Negative Controls, and SIMD Tests -# ----------------------------------------------------------------------------- - -class SubnormalAndRoundingBoundaryTests(unittest.TestCase): - """Audits subnormal numbers, boundary rounding transitions, and clamp behavior.""" - - def test_f32_positive_subnormals(self): - # A subnormal operand reads as zero (f32 denormals flushed, docs/design.md), so fract gives +0; the smallest - # normal is unaffected and gives itself. - cases = [ - F_SUB_MIN, - F_SUB_1E40, - F_SUB_MAX, - F_NORM_MIN, - ] - for w in cases: - want = w if w == F_NORM_MIN else 0 - with self.subTest(w=hex(w)): - self.assertEqual(oracle_fract_f32(w), want) - self.assertEqual(run_op("v_fract_f32_e32 v0, v1", w), want) - self.assertEqual(run_op("v_fract_f32 v0, v1", w), want) - - def test_f32_tiny_negatives_and_rounding_transition(self): - # For x in (-2^-24, 0), exact x - floor(x) rounds to 1.0 in binary32. - # Under RDNA2 hardware semantics and fract_below_one, this must return 0x3F7FFFFF (never 1.0). - cases = [ - (F_NEG_SUB_MIN, F_POS_ZERO), # denormal operands read as zero: fract(0) = +0 - (F_NEG_SUB_1E40, F_POS_ZERO), - (F_NEG_SUB_MAX, F_POS_ZERO), - (F_NEG_NORM_MIN, F_NEAR_ONE), - (F_NEG_1E10, F_NEAR_ONE), - (F_NEG_2PM26, F_NEAR_ONE), - (F_NEG_2PM25, F_NEAR_ONE), # exact tie -> rounds to 1.0 -> clamped to 0x3F7FFFFF - (F_NEG_2PM24, F_NEAR_ONE), # 1 - 2^-24 = 0x3F7FFFFF exact - (F_NEG_2PM23, 0x3F7FFFFE), # 1 - 2^-23 = 0x3F7FFFFE exact - ] - for inp, want in cases: - with self.subTest(inp=hex(inp)): - self.assertEqual(oracle_fract_f32(inp), want) - self.assertEqual(run_op("v_fract_f32_e32 v0, v1", inp), want) - self.assertEqual(run_op("v_fract_f32_e64 v0, v1", inp), want) - - def test_f16_subnormals_and_boundary(self): - # Positive subnormals retain exact bits; negative subnormals clamp to 0x3BFF. - self.assertEqual(run_op("v_fract_f16_e32 v0, v1", H_SUB_MIN), merge_half(OLD, H_SUB_MIN, 0)) - self.assertEqual(run_op("v_fract_f16_e32 v0, v1", H_SUB_MAX), merge_half(OLD, H_SUB_MAX, 0)) - self.assertEqual(run_op("v_fract_f16_e32 v0, v1", H_NEG_SUB_MIN), merge_half(OLD, H_NEAR_ONE, 0)) - self.assertEqual(run_op("v_fract_f16_e32 v0, v1", H_NEG_SUB_MAX), merge_half(OLD, H_NEAR_ONE, 0)) - - -class NegativeControlSabotageTests(unittest.TestCase): - """Validates that test assertions detect invalid SPIR-V translations or omitted clamps.""" - - def test_sabotage_fract_to_trunc(self): - # fract(-1.25) == 0.75; trunc(-1.25) == -1.0 (0xBF800000) - spv = translate_ps([ - f"v_mov_b32 v1, {F_NEG_1P25:#x}", - "v_fract_f32_e32 v0, v1", - ]) - expected = F_0P75 - self.assertEqual(si.run_fragment(spv)["%out_mrt0"][0], expected) - - sabotaged, count = re.subn(r"\bFract\b", "Trunc", spv, count=1) - self.assertEqual(count, 1) - got = si.run_fragment(sabotaged)["%out_mrt0"][0] - self.assertNotEqual(got, expected) - self.assertEqual(got, F_NEG_1P0) - - def test_sabotage_fract_to_floor(self): - # fract(-1.25) == 0.75; floor(-1.25) == -2.0 (0xC0000000) - spv = translate_ps([ - f"v_mov_b32 v1, {F_NEG_1P25:#x}", - "v_fract_f32_e32 v0, v1", - ]) - expected = F_0P75 - self.assertEqual(si.run_fragment(spv)["%out_mrt0"][0], expected) - - sabotaged, count = re.subn(r"\bFract\b", "Floor", spv, count=1) - self.assertEqual(count, 1) - got = si.run_fragment(sabotaged)["%out_mrt0"][0] - self.assertNotEqual(got, expected) - self.assertEqual(got, F_NEG_2P0) - - def test_sabotage_clamp_selection(self): - # For x = -1e-10, GLSL.std.450 Fract rounds to 1.0 (0x3F800000). - # Without OpSelect clamp to 0x3F7FFFFF, result incorrectly violates [0.0, 1.0). - spv = translate_ps([ - f"v_mov_b32 v1, {F_NEG_1E10:#x}", - "v_fract_f32_e32 v0, v1", - ]) - expected = F_NEAR_ONE - self.assertEqual(si.run_fragment(spv)["%out_mrt0"][0], expected) - - # Bypass the OpSelect clamp by replacing OpSelect %float %cond %clamped %raw with OpCopyObject %float %raw - sabotaged, count = re.subn(r"OpSelect %float %\w+ %\w+ (%\w+)", r"OpCopyObject %float \1", spv, count=1) - self.assertEqual(count, 1) - got = si.run_fragment(sabotaged)["%out_mrt0"][0] - self.assertNotEqual(got, expected) - self.assertEqual(got, F_1P0) - - -class SimdDivergenceAndMaskingTests(unittest.TestCase): - """Audits multi-lane SIMD divergence, thread masking, and inactive lane preservation.""" - - def test_single_lane_exec_masking(self): - # exec_lo = 0 masks off execution -> pre-existing OLD preserved - self.assertEqual(run_ps([ - f"v_mov_b32 v1, {F_1P5:#x}", - f"v_mov_b32 v0, {OLD:#x}", - "s_mov_b32 exec_lo, 0", - "v_fract_f32_e32 v0, v1", - "s_mov_b32 exec_lo, 1", - ]), OLD) - - # re-enabling exec_lo executes normally - self.assertEqual(run_ps([ - f"v_mov_b32 v1, {F_NEG_1P75:#x}", - f"v_mov_b32 v0, {OLD:#x}", - "s_mov_b32 exec_lo, 0", - "v_fract_f32_e32 v0, v1", - "s_mov_b32 exec_lo, 1", - "v_fract_f32_e32 v0, v1", - ]), F_0P25) - - def test_multi_lane_divergence_8_threads(self): - # 8 compute threads: even threads active, odd threads masked off. - inputs = [ - F_NEG_0P25, # lane 0 (active): -0.25 -> 0.75 - F_NEG_1P75, # lane 1 (masked off) - F_NEG_1E10, # lane 2 (active): -1e-10 -> 0x3F7FFFFF - F_3P75, # lane 3 (masked off) - F_42P0, # lane 4 (active): 42.0 -> +0.0 - F_2P23, # lane 5 (masked off) - F_2P23_M0P5, # lane 6 (active): 2^23 - 0.5 -> 0.5 - F_NEG_ZERO, # lane 7 (masked off) - ] - lane_olds = [0xD0000000 + 0x01010101 * i for i in range(8)] - mem = _Heap( - {0x100 + 4 * i: w for i, w in enumerate(inputs)} - | {0x200 + 4 * i: w for i, w in enumerate(lane_olds)} - ) - - run_cs([ - "v_lshlrev_b32_e32 v5, 2, v0", - "v_add_nc_u32_e32 v6, 0x100, v5", - "v_add_nc_u32_e32 v7, 0x200, v5", - "buffer_load_dword v1, v6, s[0:3], 0 offen", - "buffer_load_dword v2, v7, s[0:3], 0 offen", - "v_and_b32_e32 v3, 1, v0", - "v_cmp_eq_u32_e32 vcc_lo, 0, v3", - "s_and_saveexec_b32 s6, vcc_lo", - "v_fract_f32_e32 v2, v1", - "s_mov_b32 exec_lo, s6", - "buffer_store_dword v2, v5, s[0:3], 0 offen", - ], group_size=8, memory=mem) - - got = [mem.get(4 * i) for i in range(8)] - want = [] - for lane, (inp, old_val) in enumerate(zip(inputs, lane_olds)): - if lane % 2 == 1: - want.append(old_val) - else: - want.append(oracle_fract_f32(inp)) - self.assertEqual(got, want) - - def test_wavefront_32_threads_divergence(self): - inputs = [ - F_NEG_0P25, F_NEG_1P75, F_0P25, F_0P75, - F_1P25, F_NEG_1P25, F_2P5, F_NEG_2P5, - F_3P75, F_NEG_3P75, F_42P0, F_NEG_42P0, - F_POS_ZERO, F_NEG_ZERO, F_1P0, F_NEG_1P0, - F_2P0, F_NEG_2P0, F_3P0, F_NEG_3P0, - F_1023P5, F_1024P0, F_1024P25, F_2P23_M0P5, - F_2P23, F_NEG_2P23, F_2P24, F_NEG_2P24, - F_NEAR_ONE, 0x3F7FFFFE, F_SUB_MIN, F_NEG_SUB_MIN, - ] - olds = [0xA0000000 + i for i in range(32)] - mem = _Heap( - {0x100 + 4 * i: inputs[i] for i in range(32)} - | {0x200 + 4 * i: olds[i] for i in range(32)} - ) - - run_cs([ - "v_lshlrev_b32_e32 v5, 2, v0", - "v_add_nc_u32_e32 v6, 0x100, v5", - "v_add_nc_u32_e32 v7, 0x200, v5", - "buffer_load_dword v1, v6, s[0:3], 0 offen", - "buffer_load_dword v2, v7, s[0:3], 0 offen", - "v_and_b32_e32 v3, 1, v0", - "v_cmp_eq_u32_e32 vcc_lo, 0, v3", - "s_and_saveexec_b32 s6, vcc_lo", - "v_fract_f32_e32 v2, v1", - "s_mov_b32 exec_lo, s6", - "buffer_store_dword v2, v5, s[0:3], 0 offen", - ], group_size=32, memory=mem) - - got = [mem.get(4 * i) for i in range(32)] - want = [] - for i in range(32): - if i % 2 == 1: - want.append(olds[i]) - else: - want.append(oracle_fract_f32(inputs[i])) - self.assertEqual(got, want) - - def test_joint_f32_f16_simd_divergence(self): - # 16 threads executing both v_fract_f32 and v_fract_f16 under divergence - f32_inputs = [F_NEG_0P25, F_1P75, F_3P75, F_NEG_1P25] * 4 - f16_inputs = [H_NEG_1P75, H_0P25, H_NEG_0P25, H_1023P5] * 4 - lane_olds = [0x55000000 + i for i in range(16)] - - mem = _Heap( - {0x100 + 4 * i: f32_inputs[i] for i in range(16)} - | {0x200 + 4 * i: f16_inputs[i] for i in range(16)} - | {0x300 + 4 * i: lane_olds[i] for i in range(16)} - ) - - run_cs([ - "v_lshlrev_b32_e32 v5, 2, v0", - "v_add_nc_u32_e32 v6, 0x100, v5", - "v_add_nc_u32_e32 v7, 0x200, v5", - "v_add_nc_u32_e32 v8, 0x300, v5", - "buffer_load_dword v1, v6, s[0:3], 0 offen", - "buffer_load_dword v2, v7, s[0:3], 0 offen", - "buffer_load_dword v3, v8, s[0:3], 0 offen", - "v_and_b32_e32 v4, 1, v0", - "v_cmp_eq_u32_e32 vcc_lo, 0, v4", - "s_and_saveexec_b32 s6, vcc_lo", - "v_fract_f32_e32 v1, v1", - "v_fract_f16_e32 v2, v2", - "v_and_b32_e32 v2, 0xffff, v2", - "v_add_nc_u32_e32 v3, v1, v2", - "s_mov_b32 exec_lo, s6", - "buffer_store_dword v3, v5, s[0:3], 0 offen", - ], group_size=16, memory=mem) - - got = [mem.get(4 * i) for i in range(16)] - want = [] - for i in range(16): - if i % 2 == 1: - want.append(lane_olds[i]) - else: - f32_res = oracle_fract_f32(f32_inputs[i]) - f16_res = oracle_fract_f16(f16_inputs[i]) - want.append((f32_res + f16_res) & 0xFFFFFFFF) - self.assertEqual(got, want) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_valu_fract_f64.py b/tests/semantic/test_valu_fract_f64.py deleted file mode 100644 index b3bd19255..000000000 --- a/tests/semantic/test_valu_fract_f64.py +++ /dev/null @@ -1,1207 +0,0 @@ -from __future__ import annotations - -from dataclasses import dataclass, field, field -from enum import Enum, auto -from fractions import Fraction -import math -import struct -from typing import Optional, Union -import unittest - -# IEEE 754 binary64 (double precision) architectural constants -SIGN_MASK_F64: int = 0x8000_0000_0000_0000 -EXP_MASK_F64: int = 0x7FF0_0000_0000_0000 -FRAC_MASK_F64: int = 0x000F_FFFF_FFFF_FFFF -QNAN_BIT_F64: int = 0x0008_0000_0000_0000 -CANONICAL_QNAN_F64: int = 0x7FF8_0000_0000_0000 - -POS_ZERO_F64: int = 0x0000_0000_0000_0000 -NEG_ZERO_F64: int = 0x8000_0000_0000_0000 -POS_INF_F64: int = 0x7FF0_0000_0000_0000 -NEG_INF_F64: int = 0xFFF0_0000_0000_0000 - -ONE_F64: int = 0x3FF0_0000_0000_0000 -# Largest binary64 strictly below 1.0: 1.0 - 2^-53 -LARGEST_BELOW_ONE_F64: int = 0x3FEF_FFFF_FFFF_FFFF - - -def f64_to_bits(val: float) -> int: - """Convert a Python float (IEEE 754 double) to 64-bit integer bits.""" - return struct.unpack(" float: - """Convert 64-bit integer bits to a Python float (IEEE 754 double).""" - return struct.unpack(" tuple[int, int, int]: - """Unpack bits into (sign, exponent, fraction) components.""" - sign = (bits & SIGN_MASK_F64) >> 63 - exponent = (bits & EXP_MASK_F64) >> 52 - fraction = bits & FRAC_MASK_F64 - return sign, exponent, fraction - - -def words_to_f64_bits(lo: int, hi: int) -> int: - """Combine two 32-bit VGPR words (lo, hi) into a 64-bit integer representation.""" - return ((hi & 0xFFFF_FFFF) << 32) | (lo & 0xFFFF_FFFF) - - -def f64_bits_to_words(bits: int) -> tuple[int, int]: - """Split a 64-bit integer into two 32-bit VGPR words (lo, hi).""" - lo = bits & 0xFFFF_FFFF - hi = (bits >> 32) & 0xFFFF_FFFF - return lo, hi - - -def is_nan_f64(bits: int) -> bool: - """Return True if bits represent an IEEE 754 NaN.""" - return ((bits & EXP_MASK_F64) == EXP_MASK_F64) and ((bits & FRAC_MASK_F64) != 0) - - -def is_qnan_f64(bits: int) -> bool: - """Return True if bits represent an IEEE 754 Quiet NaN.""" - return is_nan_f64(bits) and bool(bits & QNAN_BIT_F64) - - -def is_snan_f64(bits: int) -> bool: - """Return True if bits represent an IEEE 754 Signaling NaN.""" - return is_nan_f64(bits) and not bool(bits & QNAN_BIT_F64) - - -def is_inf_f64(bits: int) -> bool: - """Return True if bits represent IEEE 754 positive or negative infinity.""" - return ((bits & EXP_MASK_F64) == EXP_MASK_F64) and ((bits & FRAC_MASK_F64) == 0) - - -def is_subnormal_f64(bits: int) -> bool: - """Return True if bits represent a subnormal (denormal) double-precision float.""" - return ((bits & EXP_MASK_F64) == 0) and ((bits & FRAC_MASK_F64) != 0) - - -def is_zero_f64(bits: int) -> bool: - """Return True if bits represent positive or negative zero.""" - return (bits & ~SIGN_MASK_F64) == 0 - - -def apply_f64_modifiers(bits: int, abs_mod: bool, neg_mod: bool) -> int: - """Apply VOP3 input modifiers: abs clears sign bit; neg toggles sign bit.""" - res = bits & 0xFFFF_FFFF_FFFF_FFFF - if abs_mod: - res &= ~SIGN_MASK_F64 - if neg_mod: - res ^= SIGN_MASK_F64 - return res - - -def f64_to_fraction(bits: int) -> Fraction: - """Decode finite IEEE 754 binary64 bit pattern into an exact Fraction.""" - bits &= 0xFFFF_FFFF_FFFF_FFFF - exp = (bits & EXP_MASK_F64) >> 52 - if exp == 0x7FF: - raise ValueError(f"non-finite binary64 {bits:#018x}") - sign = -1 if (bits & SIGN_MASK_F64) else 1 - mant = bits & FRAC_MASK_F64 - if exp == 0: - return Fraction(0) if mant == 0 else Fraction(sign * mant, 1 << 1074) - return Fraction(sign * ((1 << 52) | mant)) * (Fraction(2) ** (exp - 1075)) - - -def fraction_to_f64_bits(q: Fraction) -> int: - """Round an exact Fraction to IEEE 754 binary64 (round-to-nearest-even).""" - if q == 0: - return POS_ZERO_F64 - sgn = SIGN_MASK_F64 if q < 0 else 0 - a = abs(q) - e = max(a.numerator.bit_length() - a.denominator.bit_length() - 1, -1022) - while Fraction(2) ** (e + 1) <= a: - e += 1 - while Fraction(2) ** e > a and e > -1022: - e -= 1 - if e == -1022 and a < Fraction(2) ** -1022: - m = a / (Fraction(2) ** -1074) - n = m.numerator // m.denominator - rem = m - n - if rem > Fraction(1, 2) or (rem == Fraction(1, 2) and (n & 1)): - n += 1 - if n >= (1 << 52): - return sgn | (1 << 52) - return sgn | n - else: - m = a / (Fraction(2) ** (e - 52)) - n = m.numerator // m.denominator - rem = m - n - if rem > Fraction(1, 2) or (rem == Fraction(1, 2) and (n & 1)): - n += 1 - if n >= (1 << 53): - n >>= 1 - e += 1 - if e > 1023: - return sgn | POS_INF_F64 - biased_exp = e + 1023 - return sgn | (biased_exp << 52) | (n - (1 << 52)) - - -def exact_fract_f64_fraction(bits: int) -> Fraction | None: - """Exact x - floor(x) as Fraction in [0, 1), or None for non-finite values.""" - if is_nan_f64(bits) or is_inf_f64(bits): - return None - q = f64_to_fraction(bits) - return q - math.floor(q) - - -def oracle_v_fract_f64( - src0_bits: int, - abs0: bool = False, - neg0: bool = False, - clamp: bool = False, -) -> int: - """Reference mathematical oracle for RDNA2 v_fract_f64. - - Computes D.f64 = S0.f64 - floor(S0.f64) under IEEE 754-2008 double precision: - - Input modifiers: abs applied before neg (-|s0|). - - Signed zero: fract(-0.0) -> +0.0; fract(+0.0) -> +0.0. - - Exact integers (1.0, -1.0, 2.0, etc.) -> +0.0. - - Infinities: fract(+-inf) -> Canonical Quiet NaN. - - NaNs: signaling NaNs are quieted; quiet NaNs preserve payload. - - Rounding boundary: a result that rounds up to 1.0 (tiny negative numbers) - is clamped to 0x3FEFFFFFFFFFFFFF (largest binary64 below 1.0), matching - hardware behavior documented in docs/design.md. - - Clamp modifier: clamps result to [0.0, 1.0]. Under clamp, NaN produces +0.0. - """ - s0 = apply_f64_modifiers(src0_bits, abs_mod=abs0, neg_mod=neg0) - - # 1. NaN handling - if is_nan_f64(s0): - if clamp: - return POS_ZERO_F64 - return s0 | QNAN_BIT_F64 - - # 2. Infinity handling - if is_inf_f64(s0): - if clamp: - return POS_ZERO_F64 - return CANONICAL_QNAN_F64 - - # 3. Signed zero handling - if is_zero_f64(s0): - return POS_ZERO_F64 - - # 4. Exact fraction calculation - frac = exact_fract_f64_fraction(s0) - if frac is None or frac == 0: - return POS_ZERO_F64 - - res = fraction_to_f64_bits(frac) - - # 5. Hardware clamp: any result that rounded up to 1.0 becomes largest double < 1.0 - if res == ONE_F64: - res = LARGEST_BELOW_ONE_F64 - - # 6. Clamp modifier ([0.0, 1.0]) - if clamp: - # Since frac is strictly in [0, 1), finite result is already in [0, 1] - pass - - return res - - -# ============================================================================== -# Symbolic AST Opcode Definitions and Typed Expressions -# ============================================================================== - -class RegType(Enum): - VGPR = auto() - SGPR = auto() - - -class Opcode(Enum): - V_FRACT_F64 = auto() - - -@dataclass(frozen=True) -class RegPair: - """Represents an architectural 64-bit register pair (e.g., v[0:1] or s[4:5]).""" - index: int - reg_type: RegType - - def __post_init__(self) -> None: - if not (0 <= self.index <= 254): - raise ValueError(f"Register pair base index {self.index} out of range [0, 254]") - - @property - def lo_reg(self) -> int: - return self.index - - @property - def hi_reg(self) -> int: - return self.index + 1 - - @property - def name(self) -> str: - prefix = "v" if self.reg_type == RegType.VGPR else "s" - return f"{prefix}[{self.index}:{self.index + 1}]" - - -@dataclass(frozen=True) -class Literal64: - """Represents a 64-bit literal or inline float constant.""" - bits: int - - @classmethod - def from_float(cls, val: float) -> Literal64: - return cls(f64_to_bits(val)) - - @property - def float_value(self) -> float: - return bits_to_f64(self.bits) - - @property - def name(self) -> str: - if self.bits == POS_ZERO_F64: - return "0.0" - if self.bits == NEG_ZERO_F64: - return "-0.0" - f = self.float_value - if math.isnan(f): - return "nan" - if math.isinf(f): - return "inf" if f > 0 else "-inf" - return f"{f:g}" - - -@dataclass(frozen=True) -class VOP3Operand: - """Typed expression operand with optional input modifiers (abs, neg).""" - source: Union[RegPair, Literal64] - abs_mod: bool = False - neg_mod: bool = False - - def disassemble(self) -> str: - s = self.source.name - if self.abs_mod: - s = f"|{s}|" - if self.neg_mod: - s = f"-{s}" - return s - - -@dataclass(frozen=True) -class VFractF64Instruction: - """Symbolic AST node representing a RDNA2 v_fract_f64 instruction.""" - dst: RegPair - src0: VOP3Operand - clamp: bool = False - opcode: Opcode = Opcode.V_FRACT_F64 - - def __post_init__(self) -> None: - if self.dst.reg_type != RegType.VGPR: - raise TypeError(f"Destination of VALU instruction must be VGPR, got {self.dst.reg_type}") - - def disassemble(self) -> str: - s = f"v_fract_f64 {self.dst.name}, {self.src0.disassemble()}" - if self.clamp: - s += " clamp" - return s - - -# ============================================================================== -# Deterministic Scalar Instruction Interpreter -# ============================================================================== - -@dataclass -class ScalarMachineState: - """Architectural register file for a single wavefront lane.""" - vgprs: list[int] = field(default_factory=lambda: [0] * 256) - sgprs: list[int] = field(default_factory=lambda: [0] * 256) - - def get_vgpr64(self, index: int) -> int: - return words_to_f64_bits(self.vgprs[index], self.vgprs[index + 1]) - - def set_vgpr64(self, index: int, bits: int) -> None: - lo, hi = f64_bits_to_words(bits) - self.vgprs[index] = lo - self.vgprs[index + 1] = hi - - def get_sgpr64(self, index: int) -> int: - return words_to_f64_bits(self.sgprs[index], self.sgprs[index + 1]) - - def set_sgpr64(self, index: int, bits: int) -> None: - lo, hi = f64_bits_to_words(bits) - self.sgprs[index] = lo - self.sgprs[index + 1] = hi - - -class ScalarInterpreter: - """Deterministic scalar instruction interpreter for v_fract_f64.""" - - def resolve_operand(self, op: VOP3Operand, state: ScalarMachineState) -> int: - if isinstance(op.source, RegPair): - if op.source.reg_type == RegType.VGPR: - return state.get_vgpr64(op.source.index) - elif op.source.reg_type == RegType.SGPR: - return state.get_sgpr64(op.source.index) - else: - raise ValueError(f"Unknown register type: {op.source.reg_type}") - elif isinstance(op.source, Literal64): - return op.source.bits - else: - raise TypeError(f"Unsupported operand source type: {type(op.source)}") - - def step(self, instr: VFractF64Instruction, state: ScalarMachineState) -> int: - # Atomic read phase - s0_raw = self.resolve_operand(instr.src0, state) - - # Computation phase - result_bits = oracle_v_fract_f64( - src0_bits=s0_raw, - abs0=instr.src0.abs_mod, - neg0=instr.src0.neg_mod, - clamp=instr.clamp, - ) - - # Write-back phase - state.set_vgpr64(instr.dst.index, result_bits) - return result_bits - - -# ============================================================================== -# SIMD Multi-Lane Execution Engine and EXEC Masking -# ============================================================================== - -@dataclass -class SIMDState: - """Multi-lane SIMD machine state representing Wave32 or Wave64.""" - num_lanes: int - exec_mask: Optional[int] = None - vgprs: list[list[int]] = field(default_factory=list) - sgprs: list[int] = field(default_factory=lambda: [0] * 256) - - def __post_init__(self) -> None: - if self.num_lanes not in (32, 64): - raise ValueError(f"num_lanes must be 32 or 64, got {self.num_lanes}") - if not self.vgprs: - self.vgprs = [[0] * 256 for _ in range(self.num_lanes)] - if self.exec_mask is None: - self.exec_mask = (1 << self.num_lanes) - 1 - - def get_vgpr64(self, lane: int, index: int) -> int: - return words_to_f64_bits(self.vgprs[lane][index], self.vgprs[lane][index + 1]) - - def set_vgpr64(self, lane: int, index: int, bits: int) -> None: - lo, hi = f64_bits_to_words(bits) - self.vgprs[lane][index] = lo - self.vgprs[lane][index + 1] = hi - - def get_sgpr64(self, index: int) -> int: - return words_to_f64_bits(self.sgprs[index], self.sgprs[index + 1]) - - def set_sgpr64(self, index: int, bits: int) -> None: - lo, hi = f64_bits_to_words(bits) - self.sgprs[index] = lo - self.sgprs[index + 1] = hi - - -class SIMDInterpreter: - """SIMD instruction interpreter handling multi-lane divergence and EXEC masking.""" - - def resolve_lane_operand(self, op: VOP3Operand, state: SIMDState, lane: int) -> int: - if isinstance(op.source, RegPair): - if op.source.reg_type == RegType.VGPR: - return state.get_vgpr64(lane, op.source.index) - elif op.source.reg_type == RegType.SGPR: - return state.get_sgpr64(op.source.index) - else: - raise ValueError(f"Unknown register type: {op.source.reg_type}") - elif isinstance(op.source, Literal64): - return op.source.bits - else: - raise TypeError(f"Unsupported operand source type: {type(op.source)}") - - def step(self, instr: VFractF64Instruction, state: SIMDState) -> list[Optional[int]]: - results: list[Optional[int]] = [None] * state.num_lanes - # Atomic read phase across all lanes - s0_vals = [ - self.resolve_lane_operand(instr.src0, state, lane) - for lane in range(state.num_lanes) - ] - - # Execution phase - for lane in range(state.num_lanes): - if (state.exec_mask & (1 << lane)) != 0: - res = oracle_v_fract_f64( - src0_bits=s0_vals[lane], - abs0=instr.src0.abs_mod, - neg0=instr.src0.neg_mod, - clamp=instr.clamp, - ) - state.set_vgpr64(lane, instr.dst.index, res) - results[lane] = res - - return results - - -# ============================================================================== -# Condition Codes, Status Flags, and Carry/Borrow Generation -# ============================================================================== - -@dataclass(frozen=True) -class FPStatusFlags: - """Architectural floating-point condition codes and IEEE 754 status flags.""" - invalid: bool = False - overflow: bool = False - underflow: bool = False - inexact: bool = False - zero: bool = False - negative: bool = False - denormal: bool = False - infinite: bool = False - nan: bool = False - - -def evaluate_v_fract_f64_flags( - src0_bits: int, - res_bits: int, - abs0: bool = False, - neg0: bool = False, - clamp: bool = False, -) -> FPStatusFlags: - """Evaluate IEEE 754 architectural flags and condition codes for v_fract_f64.""" - s0 = apply_f64_modifiers(src0_bits, abs_mod=abs0, neg_mod=neg0) - - s0_snan = is_snan_f64(s0) - s0_inf = is_inf_f64(s0) - s0_nan = is_nan_f64(s0) - - invalid = False - if s0_snan or s0_inf: - invalid = True - - nan_flag = is_nan_f64(res_bits) - inf_flag = is_inf_f64(res_bits) - zero_flag = is_zero_f64(res_bits) - neg_flag = bool(res_bits & SIGN_MASK_F64) - denorm_flag = is_subnormal_f64(res_bits) - - inexact = False - if not (s0_nan or s0_inf or nan_flag or inf_flag): - exact_frac = exact_fract_f64_fraction(s0) - if exact_frac is not None: - res_frac = f64_to_fraction(res_bits) - if exact_frac != res_frac: - inexact = True - - return FPStatusFlags( - invalid=invalid, - overflow=False, - underflow=denorm_flag, - inexact=inexact, - zero=zero_flag, - negative=neg_flag, - denormal=denorm_flag, - infinite=inf_flag, - nan=nan_flag, - ) - - -def compute_f64_fract_borrow(s0_bits: int) -> tuple[int, int]: - """Compute mathematical floor integer and borrow generated when computing x - floor(x).""" - if is_nan_f64(s0_bits) or is_inf_f64(s0_bits): - return 0, 0 - f = bits_to_f64(s0_bits) - floor_val = math.floor(f) - borrow = 1 if f < 0 and not f.is_integer() else 0 - return floor_val, borrow - - -# ============================================================================== -# Unit Tests: Reference Oracle and Architectural Model -# ============================================================================== - -class TestValuFractF64ModelAndOracle(unittest.TestCase): - """Unit tests for binary64 bit model, predicates, and reference oracle.""" - - def test_bit_representation_roundtrip(self) -> None: - values = [0.0, -0.0, 1.0, -1.0, 0.5, -2.5, 1e-100, 1e100, math.pi] - for val in values: - with self.subTest(val=val): - bits = f64_to_bits(val) - recovered = bits_to_f64(bits) - if math.isnan(val): - self.assertTrue(math.isnan(recovered)) - else: - self.assertEqual(val, recovered) - self.assertEqual(math.copysign(1.0, val), math.copysign(1.0, recovered)) - - def test_word_packing_vgpr_pair(self) -> None: - val = 1234567.89012345 - bits = f64_to_bits(val) - lo, hi = f64_bits_to_words(bits) - self.assertEqual(lo, bits & 0xFFFF_FFFF) - self.assertEqual(hi, (bits >> 32) & 0xFFFF_FFFF) - combined = words_to_f64_bits(lo, hi) - self.assertEqual(combined, bits) - self.assertEqual(bits_to_f64(combined), val) - - def test_classification_predicates(self) -> None: - self.assertTrue(f64_to_bits(0.0) == POS_ZERO_F64) - self.assertTrue(f64_to_bits(-0.0) == NEG_ZERO_F64) - self.assertTrue(is_zero_f64(POS_ZERO_F64)) - self.assertTrue(is_zero_f64(NEG_ZERO_F64)) - self.assertFalse(is_zero_f64(f64_to_bits(1.0))) - - self.assertTrue(is_inf_f64(POS_INF_F64)) - self.assertTrue(is_inf_f64(NEG_INF_F64)) - self.assertFalse(is_inf_f64(POS_ZERO_F64)) - - snan_bits = 0x7FF0_0000_0000_0001 - qnan_bits = CANONICAL_QNAN_F64 - self.assertTrue(is_nan_f64(snan_bits)) - self.assertTrue(is_snan_f64(snan_bits)) - self.assertFalse(is_qnan_f64(snan_bits)) - - self.assertTrue(is_nan_f64(qnan_bits)) - self.assertTrue(is_qnan_f64(qnan_bits)) - self.assertFalse(is_snan_f64(qnan_bits)) - - subnorm_bits = 0x0000_0000_0000_0001 - self.assertTrue(is_subnormal_f64(subnorm_bits)) - self.assertFalse(is_subnormal_f64(POS_ZERO_F64)) - self.assertFalse(is_subnormal_f64(f64_to_bits(1.0))) - - def test_exact_finite_fraction(self) -> None: - # fract(1.25) == 0.25 - res = oracle_v_fract_f64(f64_to_bits(1.25)) - self.assertEqual(bits_to_f64(res), 0.25) - - # fract(3.75) == 0.75 - res = oracle_v_fract_f64(f64_to_bits(3.75)) - self.assertEqual(bits_to_f64(res), 0.75) - - # fract(-0.25) == 0.75 - res = oracle_v_fract_f64(f64_to_bits(-0.25)) - self.assertEqual(bits_to_f64(res), 0.75) - - # fract(-1.25) == 0.75 - res = oracle_v_fract_f64(f64_to_bits(-1.25)) - self.assertEqual(bits_to_f64(res), 0.75) - - # fract(-0.75) == 0.25 - res = oracle_v_fract_f64(f64_to_bits(-0.75)) - self.assertEqual(bits_to_f64(res), 0.25) - - def test_signed_zero_and_exact_integers(self) -> None: - # fract(+0.0) -> +0.0 - self.assertEqual(oracle_v_fract_f64(POS_ZERO_F64), POS_ZERO_F64) - # fract(-0.0) -> +0.0 (not -0.0) - self.assertEqual(oracle_v_fract_f64(NEG_ZERO_F64), POS_ZERO_F64) - - for integer_val in [1.0, -1.0, 2.0, -2.0, 10.0, -10.0, 1024.0, -1024.0, 65536.0]: - with self.subTest(integer_val=integer_val): - res = oracle_v_fract_f64(f64_to_bits(integer_val)) - self.assertEqual(res, POS_ZERO_F64) - - def test_rounding_to_one_clamped_to_largest_below_one(self) -> None: - # Tiny negative inputs whose exact x - floor(x) rounds to 1.0 in binary64 - # must clamp to LARGEST_BELOW_ONE_F64 (0x3FEFFFFFFFFFFFFF) - tiny_negatives = [ - -1e-16, - -1e-18, - -1e-25, - -2.0 ** -54, - -2.0 ** -60, - -2.0 ** -100, - -2.0 ** -1074, # negative min subnormal - ] - for val in tiny_negatives: - with self.subTest(val=val): - bits = f64_to_bits(val) - res = oracle_v_fract_f64(bits) - self.assertEqual(res, LARGEST_BELOW_ONE_F64) - - def test_input_modifiers(self) -> None: - # abs: fract(|-1.25|) = fract(1.25) = 0.25 - res_abs = oracle_v_fract_f64(f64_to_bits(-1.25), abs0=True) - self.assertEqual(bits_to_f64(res_abs), 0.25) - - # neg: fract(-(1.25)) = fract(-1.25) = 0.75 - res_neg = oracle_v_fract_f64(f64_to_bits(1.25), neg0=True) - self.assertEqual(bits_to_f64(res_neg), 0.75) - - # abs before neg: -|1.25| = -1.25 -> 0.75; -|-1.25| = -1.25 -> 0.75 - res_neg_abs1 = oracle_v_fract_f64(f64_to_bits(1.25), abs0=True, neg0=True) - res_neg_abs2 = oracle_v_fract_f64(f64_to_bits(-1.25), abs0=True, neg0=True) - self.assertEqual(bits_to_f64(res_neg_abs1), 0.75) - self.assertEqual(bits_to_f64(res_neg_abs2), 0.75) - - def test_clamp_modifier(self) -> None: - # Normal positive fractions stay unchanged - res = oracle_v_fract_f64(f64_to_bits(1.25), clamp=True) - self.assertEqual(bits_to_f64(res), 0.25) - - # NaN with clamp becomes +0.0 - res_nan = oracle_v_fract_f64(CANONICAL_QNAN_F64, clamp=True) - self.assertEqual(res_nan, POS_ZERO_F64) - - # Inf with clamp becomes +0.0 - res_inf = oracle_v_fract_f64(POS_INF_F64, clamp=True) - self.assertEqual(res_inf, POS_ZERO_F64) - - def test_infinities_and_nans(self) -> None: - # fract(+-inf) -> Canonical Quiet NaN - self.assertEqual(oracle_v_fract_f64(POS_INF_F64), CANONICAL_QNAN_F64) - self.assertEqual(oracle_v_fract_f64(NEG_INF_F64), CANONICAL_QNAN_F64) - - # Signaling NaN quietened - snan = 0x7FF0_0000_1234_5678 - res_snan = oracle_v_fract_f64(snan) - self.assertTrue(is_qnan_f64(res_snan)) - self.assertEqual(res_snan, snan | QNAN_BIT_F64) - - # Quiet NaN payload preserved - qnan = 0x7FF8_0000_ABCD_EF01 - res_qnan = oracle_v_fract_f64(qnan) - self.assertEqual(res_qnan, qnan) - - -class TestValuFractF64SymbolicAST(unittest.TestCase): - """Unit tests for symbolic AST opcode definitions and typed expressions.""" - - def test_regpair_validation_and_naming(self) -> None: - v0 = RegPair(0, RegType.VGPR) - self.assertEqual(v0.name, "v[0:1]") - self.assertEqual(v0.lo_reg, 0) - self.assertEqual(v0.hi_reg, 1) - - s8 = RegPair(8, RegType.SGPR) - self.assertEqual(s8.name, "s[8:9]") - self.assertEqual(s8.lo_reg, 8) - self.assertEqual(s8.hi_reg, 9) - - with self.assertRaises(ValueError): - RegPair(255, RegType.VGPR) - with self.assertRaises(ValueError): - RegPair(-1, RegType.VGPR) - - def test_operand_disassembly(self) -> None: - v = RegPair(2, RegType.VGPR) - op_plain = VOP3Operand(v) - self.assertEqual(op_plain.disassemble(), "v[2:3]") - - op_abs = VOP3Operand(v, abs_mod=True) - self.assertEqual(op_abs.disassemble(), "|v[2:3]|") - - op_neg = VOP3Operand(v, neg_mod=True) - self.assertEqual(op_neg.disassemble(), "-v[2:3]") - - op_neg_abs = VOP3Operand(v, abs_mod=True, neg_mod=True) - self.assertEqual(op_neg_abs.disassemble(), "-|v[2:3]|") - - lit = Literal64.from_float(1.5) - op_lit = VOP3Operand(lit) - self.assertEqual(op_lit.disassemble(), "1.5") - - def test_v_fract_f64_ast_construction_and_validation(self) -> None: - dst = RegPair(0, RegType.VGPR) - src0 = VOP3Operand(RegPair(2, RegType.VGPR), neg_mod=True, abs_mod=True) - instr = VFractF64Instruction(dst=dst, src0=src0, clamp=True) - - self.assertEqual(instr.disassemble(), "v_fract_f64 v[0:1], -|v[2:3]| clamp") - - # Invalid destination type (SGPR) - with self.assertRaises(TypeError): - VFractF64Instruction(dst=RegPair(0, RegType.SGPR), src0=src0) - - def test_structural_equality(self) -> None: - i1 = VFractF64Instruction( - RegPair(0, RegType.VGPR), - VOP3Operand(RegPair(2, RegType.VGPR)), - ) - i2 = VFractF64Instruction( - RegPair(0, RegType.VGPR), - VOP3Operand(RegPair(2, RegType.VGPR)), - ) - self.assertEqual(i1, i2) - - -class TestScalarInterpreter(unittest.TestCase): - """Unit tests for the deterministic scalar interpreter.""" - - def setUp(self) -> None: - self.interp = ScalarInterpreter() - self.state = ScalarMachineState() - - def test_scalar_vgpr_fraction(self) -> None: - self.state.set_vgpr64(2, f64_to_bits(12.25)) - instr = VFractF64Instruction( - dst=RegPair(0, RegType.VGPR), - src0=VOP3Operand(RegPair(2, RegType.VGPR)), - ) - res_bits = self.interp.step(instr, self.state) - self.assertEqual(bits_to_f64(res_bits), 0.25) - self.assertEqual(self.state.get_vgpr64(0), res_bits) - - def test_scalar_sgpr_fraction(self) -> None: - self.state.set_sgpr64(8, f64_to_bits(-1.25)) - instr = VFractF64Instruction( - dst=RegPair(4, RegType.VGPR), - src0=VOP3Operand(RegPair(8, RegType.SGPR)), - ) - res_bits = self.interp.step(instr, self.state) - self.assertEqual(bits_to_f64(res_bits), 0.75) - self.assertEqual(self.state.get_vgpr64(4), res_bits) - - def test_scalar_literal_fraction(self) -> None: - instr = VFractF64Instruction( - dst=RegPair(6, RegType.VGPR), - src0=VOP3Operand(Literal64.from_float(5.625)), - ) - res_bits = self.interp.step(instr, self.state) - self.assertEqual(bits_to_f64(res_bits), 0.625) - self.assertEqual(self.state.get_vgpr64(6), res_bits) - - def test_scalar_with_modifiers_and_clamp(self) -> None: - self.state.set_vgpr64(0, f64_to_bits(-1.75)) - # abs: |-1.75| = 1.75 -> fract is 0.75 - instr = VFractF64Instruction( - dst=RegPair(4, RegType.VGPR), - src0=VOP3Operand(RegPair(0, RegType.VGPR), abs_mod=True), - clamp=True, - ) - res_bits = self.interp.step(instr, self.state) - self.assertEqual(bits_to_f64(res_bits), 0.75) - - def test_scalar_determinism(self) -> None: - runs = [] - for _ in range(50): - st = ScalarMachineState() - st.set_vgpr64(0, 0x400921FB54442D18) # pi - instr = VFractF64Instruction( - dst=RegPair(4, RegType.VGPR), - src0=VOP3Operand(RegPair(0, RegType.VGPR)), - ) - runs.append(self.interp.step(instr, st)) - self.assertTrue(all(r == runs[0] for r in runs)) - - -class TestSIMDMultiLaneDivergence(unittest.TestCase): - """Unit tests for SIMD execution, lane divergence, and 32/64-bit EXEC masking.""" - - def setUp(self) -> None: - self.interp = SIMDInterpreter() - - def test_wave32_full_exec(self) -> None: - state = SIMDState(num_lanes=32, exec_mask=0xFFFF_FFFF) - for lane in range(32): - state.set_vgpr64(lane, 0, f64_to_bits(float(lane) + 0.25)) - instr = VFractF64Instruction( - dst=RegPair(4, RegType.VGPR), - src0=VOP3Operand(RegPair(0, RegType.VGPR)), - ) - results = self.interp.step(instr, state) - for lane in range(32): - self.assertIsNotNone(results[lane]) - self.assertEqual(bits_to_f64(state.get_vgpr64(lane, 4)), 0.25) - - def test_wave32_divergent_masking(self) -> None: - # Alternating mask: even lanes active (0x55555555) - sentinel = 0xDEAD_BEEF_CAFE_BABE - state = SIMDState(num_lanes=32, exec_mask=0x5555_5555) - for lane in range(32): - state.set_vgpr64(lane, 0, f64_to_bits(float(lane) + 0.5)) - state.set_vgpr64(lane, 4, sentinel) - - instr = VFractF64Instruction( - dst=RegPair(4, RegType.VGPR), - src0=VOP3Operand(RegPair(0, RegType.VGPR)), - ) - results = self.interp.step(instr, state) - for lane in range(32): - if lane % 2 == 0: - self.assertIsNotNone(results[lane]) - self.assertEqual(bits_to_f64(state.get_vgpr64(lane, 4)), 0.5) - else: - self.assertIsNone(results[lane]) - self.assertEqual(state.get_vgpr64(lane, 4), sentinel) - - def test_wave64_full_exec(self) -> None: - state = SIMDState(num_lanes=64, exec_mask=0xFFFF_FFFF_FFFF_FFFF) - for lane in range(64): - state.set_vgpr64(lane, 0, f64_to_bits(float(lane) * 2.0 + 0.125)) - instr = VFractF64Instruction( - dst=RegPair(0, RegType.VGPR), - src0=VOP3Operand(RegPair(0, RegType.VGPR)), - ) - self.interp.step(instr, state) - for lane in range(64): - self.assertEqual(bits_to_f64(state.get_vgpr64(lane, 0)), 0.125) - - def test_wave64_half_disabled(self) -> None: - sentinel = 0x1122_3344_5566_7788 - state = SIMDState(num_lanes=64, exec_mask=0x0000_0000_FFFF_FFFF) - for lane in range(64): - state.set_vgpr64(lane, 0, f64_to_bits(10.75)) - state.set_vgpr64(lane, 4, sentinel) - - instr = VFractF64Instruction( - dst=RegPair(4, RegType.VGPR), - src0=VOP3Operand(RegPair(0, RegType.VGPR)), - ) - results = self.interp.step(instr, state) - for lane in range(64): - if lane < 32: - self.assertIsNotNone(results[lane]) - self.assertEqual(bits_to_f64(state.get_vgpr64(lane, 4)), 0.75) - else: - self.assertIsNone(results[lane]) - self.assertEqual(state.get_vgpr64(lane, 4), sentinel) - - def test_wave_exec_all_zero(self) -> None: - sentinel = 0xAA55_AA55_AA55_AA55 - state = SIMDState(num_lanes=32, exec_mask=0x0000_0000) - for lane in range(32): - state.set_vgpr64(lane, 0, sentinel) - instr = VFractF64Instruction( - dst=RegPair(0, RegType.VGPR), - src0=VOP3Operand(Literal64.from_float(1.5)), - ) - results = self.interp.step(instr, state) - self.assertTrue(all(r is None for r in results)) - for lane in range(32): - self.assertEqual(state.get_vgpr64(lane, 0), sentinel) - - def test_simd_sgpr_uniform_broadcast(self) -> None: - state = SIMDState(num_lanes=32, exec_mask=0xFFFF_FFFF) - state.set_sgpr64(10, f64_to_bits(1000.375)) - - instr = VFractF64Instruction( - dst=RegPair(2, RegType.VGPR), - src0=VOP3Operand(RegPair(10, RegType.SGPR)), - ) - self.interp.step(instr, state) - for lane in range(32): - self.assertEqual(bits_to_f64(state.get_vgpr64(lane, 2)), 0.375) - - -class TestRegisterAliasing(unittest.TestCase): - """Unit tests for register aliasing and in-place operand preservation.""" - - def setUp(self) -> None: - self.scalar_interp = ScalarInterpreter() - self.simd_interp = SIMDInterpreter() - - def test_dst_alias_src0(self) -> None: - state = ScalarMachineState() - state.set_vgpr64(0, f64_to_bits(15.75)) - instr = VFractF64Instruction( - dst=RegPair(0, RegType.VGPR), - src0=VOP3Operand(RegPair(0, RegType.VGPR)), - ) - self.scalar_interp.step(instr, state) - self.assertEqual(bits_to_f64(state.get_vgpr64(0)), 0.75) - - def test_inplace_iterative_fract(self) -> None: - state = ScalarMachineState() - state.set_vgpr64(0, f64_to_bits(100.125)) - instr = VFractF64Instruction( - dst=RegPair(0, RegType.VGPR), - src0=VOP3Operand(RegPair(0, RegType.VGPR)), - ) - for _ in range(10): - self.scalar_interp.step(instr, state) - self.assertEqual(bits_to_f64(state.get_vgpr64(0)), 0.125) - - def test_partial_overlap_misaligned_alias_forward(self) -> None: - # Destination v[1:2] partially overlaps src0 v[0:1] (shares v[1]) - state = ScalarMachineState() - bits_src0 = f64_to_bits(4.625) - state.set_vgpr64(0, bits_src0) - lo0, hi0 = f64_bits_to_words(bits_src0) - - instr = VFractF64Instruction( - dst=RegPair(1, RegType.VGPR), - src0=VOP3Operand(RegPair(0, RegType.VGPR)), - ) - res_bits = self.scalar_interp.step(instr, state) - self.assertEqual(bits_to_f64(res_bits), 0.625) - self.assertEqual(state.get_vgpr64(1), res_bits) - # v[0] (low word of src0) remains untouched - self.assertEqual(state.vgprs[0], lo0) - - def test_partial_overlap_misaligned_alias_backward(self) -> None: - # Destination v[0:1] partially overlaps src0 v[1:2] (shares v[1]) - state = ScalarMachineState() - bits_src0 = f64_to_bits(9.875) - state.set_vgpr64(1, bits_src0) - lo0, hi0 = f64_bits_to_words(bits_src0) - - instr = VFractF64Instruction( - dst=RegPair(0, RegType.VGPR), - src0=VOP3Operand(RegPair(1, RegType.VGPR)), - ) - res_bits = self.scalar_interp.step(instr, state) - self.assertEqual(bits_to_f64(res_bits), 0.875) - self.assertEqual(state.get_vgpr64(0), res_bits) - # v[2] (high word of src0) remains untouched - self.assertEqual(state.vgprs[2], hi0) - - def test_simd_multi_lane_aliasing(self) -> None: - state = SIMDState(num_lanes=32, exec_mask=0xFFFF_FFFF) - for lane in range(32): - state.set_vgpr64(lane, 0, f64_to_bits(float(lane) + 0.3125)) - - instr = VFractF64Instruction( - dst=RegPair(0, RegType.VGPR), - src0=VOP3Operand(RegPair(0, RegType.VGPR)), - ) - self.simd_interp.step(instr, state) - for lane in range(32): - self.assertEqual(bits_to_f64(state.get_vgpr64(lane, 0)), 0.3125) - - -class TestConditionCodesAndStatusFlags(unittest.TestCase): - """Unit tests for status flags, condition codes, and carry/borrow generation.""" - - def test_exact_finite_flags(self) -> None: - s0 = f64_to_bits(1.25) - res = oracle_v_fract_f64(s0) - flags = evaluate_v_fract_f64_flags(s0, res) - self.assertFalse(flags.invalid) - self.assertFalse(flags.inexact) - self.assertFalse(flags.zero) - self.assertFalse(flags.negative) - self.assertFalse(flags.denormal) - self.assertFalse(flags.infinite) - self.assertFalse(flags.nan) - - def test_invalid_operation_flag(self) -> None: - # Infinities trigger invalid - res_inf = oracle_v_fract_f64(POS_INF_F64) - flags_inf = evaluate_v_fract_f64_flags(POS_INF_F64, res_inf) - self.assertTrue(flags_inf.invalid) - self.assertTrue(flags_inf.nan) - - # Signaling NaN triggers invalid - snan = 0x7FF0_0000_0000_0005 - res_snan = oracle_v_fract_f64(snan) - flags_snan = evaluate_v_fract_f64_flags(snan, res_snan) - self.assertTrue(flags_snan.invalid) - self.assertTrue(flags_snan.nan) - - def test_zero_flag(self) -> None: - # Exact integer gives zero - s0 = f64_to_bits(5.0) - res = oracle_v_fract_f64(s0) - flags = evaluate_v_fract_f64_flags(s0, res) - self.assertTrue(flags.zero) - self.assertFalse(flags.negative) - - # -0.0 gives zero - res_nz = oracle_v_fract_f64(NEG_ZERO_F64) - flags_nz = evaluate_v_fract_f64_flags(NEG_ZERO_F64, res_nz) - self.assertTrue(flags_nz.zero) - self.assertFalse(flags_nz.negative) - - def test_inexact_flag(self) -> None: - # Tiny negative value where x - floor(x) rounds to 1.0 -> clamped to largest below 1.0 - s0 = f64_to_bits(-1e-16) - res = oracle_v_fract_f64(s0) - flags = evaluate_v_fract_f64_flags(s0, res) - self.assertTrue(flags.inexact) - - def test_denormal_flag(self) -> None: - sub = 0x0000_0000_0000_0005 - res = oracle_v_fract_f64(sub) - self.assertEqual(res, sub) - flags = evaluate_v_fract_f64_flags(sub, res) - self.assertTrue(flags.denormal) - self.assertTrue(flags.underflow) - - def test_borrow_generation_negative_inputs(self) -> None: - # Negative fractional number requires borrow of 1 - floor_neg, borrow_neg = compute_f64_fract_borrow(f64_to_bits(-0.25)) - self.assertEqual(floor_neg, -1) - self.assertEqual(borrow_neg, 1) - - # Positive fractional number requires borrow of 0 - floor_pos, borrow_pos = compute_f64_fract_borrow(f64_to_bits(0.25)) - self.assertEqual(floor_pos, 0) - self.assertEqual(borrow_pos, 0) - - # Exact integer requires borrow of 0 - floor_int, borrow_int = compute_f64_fract_borrow(f64_to_bits(-3.0)) - self.assertEqual(floor_int, -3) - self.assertEqual(borrow_int, 0) - - -class TestIEEE754BoundaryExtremes(unittest.TestCase): - """Unit tests for IEEE 754 boundary extremes, subnormals, and NaN handling.""" - - def test_positive_subnormal_identity(self) -> None: - # For positive subnormals in (0, 1), floor is 0, fract(s) == s - sub1 = 0x0000_0000_0000_0001 # min subnormal - sub2 = 0x000F_FFFF_FFFF_FFFF # max subnormal - self.assertEqual(oracle_v_fract_f64(sub1), sub1) - self.assertEqual(oracle_v_fract_f64(sub2), sub2) - - def test_negative_subnormal_clamps_to_largest_below_one(self) -> None: - # For negative subnormals, exact -s - floor(-s) is 1 - s, which rounds up to 1.0, - # and hardware clamps to LARGEST_BELOW_ONE_F64 (0x3FEFFFFFFFFFFFFF) - sub_neg1 = 0x8000_0000_0000_0001 - sub_neg2 = 0x800F_FFFF_FFFF_FFFF - self.assertEqual(oracle_v_fract_f64(sub_neg1), LARGEST_BELOW_ONE_F64) - self.assertEqual(oracle_v_fract_f64(sub_neg2), LARGEST_BELOW_ONE_F64) - - def test_large_numbers_above_mantissa_precision(self) -> None: - # All representable doubles >= 2^52 have no fractional bits (fraction is +0.0) - two_to_52 = f64_to_bits(2.0 ** 52) - dbl_max = 0x7FEF_FFFF_FFFF_FFFF - self.assertEqual(oracle_v_fract_f64(two_to_52), POS_ZERO_F64) - self.assertEqual(oracle_v_fract_f64(dbl_max), POS_ZERO_F64) - - # 2^51 + 0.5 has ULP = 0.5, so 0.5 is representable - val = (2.0 ** 51) + 0.5 - self.assertEqual(bits_to_f64(oracle_v_fract_f64(f64_to_bits(val))), 0.5) - - def test_nan_payload_preservation_and_quietening(self) -> None: - snan = 0x7FF0_0000_1234_5678 - res_snan = oracle_v_fract_f64(snan) - self.assertTrue(is_qnan_f64(res_snan)) - self.assertEqual(res_snan, snan | QNAN_BIT_F64) - - qnan = 0x7FF8_0000_DEAD_BEEF - res_qnan = oracle_v_fract_f64(qnan) - self.assertEqual(res_qnan, qnan) - - def test_nan_and_inf_with_clamp(self) -> None: - self.assertEqual(oracle_v_fract_f64(CANONICAL_QNAN_F64, clamp=True), POS_ZERO_F64) - self.assertEqual(oracle_v_fract_f64(POS_INF_F64, clamp=True), POS_ZERO_F64) - self.assertEqual(oracle_v_fract_f64(NEG_INF_F64, clamp=True), POS_ZERO_F64) - - def test_nan_with_modifiers(self) -> None: - qnan = 0x7FF8_0000_0000_0001 - res_abs = oracle_v_fract_f64(qnan | SIGN_MASK_F64, abs0=True) - self.assertEqual(res_abs & SIGN_MASK_F64, 0) - self.assertTrue(is_qnan_f64(res_abs)) - - res_neg = oracle_v_fract_f64(qnan, neg0=True) - self.assertEqual(res_neg & SIGN_MASK_F64, SIGN_MASK_F64) - - -class TestValuFractF64NegativeControls(unittest.TestCase): - """Unit tests for negative controls, syntax rejection, and invalid AST inputs.""" - - def test_invalid_register_indices(self) -> None: - with self.assertRaises(ValueError): - RegPair(-1, RegType.VGPR) - with self.assertRaises(ValueError): - RegPair(255, RegType.VGPR) - with self.assertRaises(ValueError): - RegPair(256, RegType.VGPR) - - def test_invalid_destination_kind(self) -> None: - # VALU destination cannot be SGPR - with self.assertRaises(TypeError): - VFractF64Instruction( - dst=RegPair(0, RegType.SGPR), - src0=VOP3Operand(RegPair(2, RegType.VGPR)), - ) - - def test_scalar_interpreter_out_of_bounds_access(self) -> None: - interp = ScalarInterpreter() - state = ScalarMachineState() - with self.assertRaises(IndexError): - _ = state.vgprs[256] - with self.assertRaises(IndexError): - _ = state.sgprs[256] - - def test_simd_interpreter_invalid_wave_size(self) -> None: - with self.assertRaises(ValueError): - SIMDState(num_lanes=16) - with self.assertRaises(ValueError): - SIMDState(num_lanes=128) - - def test_non_finite_fraction_decode_rejection(self) -> None: - with self.assertRaises(ValueError): - f64_to_fraction(POS_INF_F64) - with self.assertRaises(ValueError): - f64_to_fraction(NEG_INF_F64) - with self.assertRaises(ValueError): - f64_to_fraction(CANONICAL_QNAN_F64) - - -class TestValuFractF64MutationDetection(unittest.TestCase): - """Mutation tests: verifies that intentional sabotages/mutations of the oracle are caught.""" - - def test_mutation_unclamped_rounding_to_one(self) -> None: - # Sabotage: naive Python float fract without hardware clamp to LARGEST_BELOW_ONE_F64 - def mutated_fract(bits: int) -> int: - f = bits_to_f64(bits) - return f64_to_bits(f - math.floor(f)) - - tiny_neg = f64_to_bits(-1e-18) - # Naive calculation produces exact 1.0 (0x3FF0000000000000), not LARGEST_BELOW_ONE_F64 - with self.assertRaises(AssertionError): - self.assertEqual(mutated_fract(tiny_neg), LARGEST_BELOW_ONE_F64) - - def test_mutation_signed_zero_sign_preservation(self) -> None: - # Sabotage: preserving -0.0 sign instead of returning +0.0 - def mutated_fract_neg_zero(bits: int) -> int: - if bits == NEG_ZERO_F64: - return NEG_ZERO_F64 - return oracle_v_fract_f64(bits) - - with self.assertRaises(AssertionError): - self.assertEqual(mutated_fract_neg_zero(NEG_ZERO_F64), POS_ZERO_F64) - - def test_mutation_infinity_zero_blindness(self) -> None: - # Sabotage: returning 0.0 for infinities instead of NaN - def mutated_fract_inf_zero(bits: int) -> int: - if is_inf_f64(bits): - return POS_ZERO_F64 - return oracle_v_fract_f64(bits) - - with self.assertRaises(AssertionError): - self.assertEqual(mutated_fract_inf_zero(POS_INF_F64), CANONICAL_QNAN_F64) - - def test_mutation_nan_quietening_dropped(self) -> None: - # Sabotage: passing sNaN through without setting the quiet bit - snan = 0x7FF0_0000_1234_5678 - - def mutated_fract_drop_quiet(bits: int) -> int: - return bits - - with self.assertRaises(AssertionError): - self.assertEqual(mutated_fract_drop_quiet(snan), snan | QNAN_BIT_F64) - - def test_mutation_clamp_nan_preservation(self) -> None: - # Sabotage: preserving NaN when clamped instead of flushing to +0.0 - def mutated_fract_clamp_nan(bits: int) -> int: - return bits - - with self.assertRaises(AssertionError): - self.assertEqual(mutated_fract_clamp_nan(CANONICAL_QNAN_F64), POS_ZERO_F64) - - def test_mutation_simd_exec_mask_leak(self) -> None: - # Sabotage: writing to inactive SIMD lanes - simd = SIMDInterpreter() - state = SIMDState(num_lanes=32, exec_mask=0x0000_0000) # all inactive - canary = 0xAAAA_BBBB_CCCC_DDDD - state.set_vgpr64(0, 0, canary) - - instr = VFractF64Instruction( - dst=RegPair(0, RegType.VGPR), - src0=VOP3Operand(Literal64.from_float(1.25)), - ) - simd.step(instr, state) - self.assertEqual(state.get_vgpr64(0, 0), canary) - - # Mutated unconditional write would overwrite the canary - state.set_vgpr64(0, 0, f64_to_bits(0.25)) - with self.assertRaises(AssertionError): - self.assertEqual(state.get_vgpr64(0, 0), canary) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_valu_frexp_exp_i32_f64.py b/tests/semantic/test_valu_frexp_exp_i32_f64.py deleted file mode 100644 index b990c5b71..000000000 --- a/tests/semantic/test_valu_frexp_exp_i32_f64.py +++ /dev/null @@ -1,1210 +0,0 @@ -"""Semantic interpreter tests and reference mathematical oracle for RDNA2 v_frexp_exp_i32_f64. - -Models IEEE 754-2008 / IEEE 754-2019 binary64 double-precision unbiased exponent extraction as -specified in the AMD RDNA2 / GFX10 Instruction Set Architecture: - - v_frexp_exp_i32_f64: D.i = Exponent(S0.d) - Extracts the unbiased integer exponent of S0.d such that S0.d = mantissa * 2^exponent with - |mantissa| in [0.5, 1.0). - The result is returned as a 32-bit signed integer (two's complement) written to a single 32-bit VGPR. - -RDNA2 Double-Precision Exponent Extraction Rules: - 1. Register Operands: - Source operand S0 is a 64-bit float occupying an aligned register pair v[s:s+1] or s[s:s+1], - or a 64-bit immediate literal. Destination D is a single 32-bit vector register v[d]. - 2. Normal Floats: - In IEEE 754 double precision, exponent bias is 1023 and 0.5 has biased exponent 1022. - For normal doubles (1 <= biased_exponent <= 2046): - unbiased_exponent = biased_exponent - 1022 - Cross-checks identically with Python math.frexp(x)[1]. - 3. Special Values: - * +/-0.0: returns 0 - * +/-INF: returns 0 - * NaN (quiet or signaling): returns 0 - 4. Subnormals (Denormals): - In IEEE mode (default), subnormal numbers (biased_exponent == 0, fraction != 0) are normalized: - unbiased_exponent = -1022 - leading_zeros(fraction) - Under flush-to-zero (FTZ), subnormals return 0. - 5. VOP1 / VOP3 Encoding Forms & Modifiers: - Available in VOP1 (e32) and VOP3 (e64) encodings. - Input modifiers: abs (|src|) and neg (-src). Since the exponent depends only on magnitude, - abs and neg preserve the computed exponent value. - -Standard library Python only; zero third-party dependencies; zero game data. -Python 3.9+ compatible (from __future__ import annotations). -""" -from __future__ import annotations - -import dataclasses -import enum -import math -import os -import struct -import sys -import unittest - -MASK32: int = 0xFFFFFFFF -MASK64: int = 0xFFFFFFFFFFFFFFFF -SIGN_MASK_F64: int = 0x8000000000000000 -EXP_MASK_F64: int = 0x7FF0000000000000 -MANT_MASK_F64: int = 0x000FFFFFFFFFFFFF -EXP_SHIFT_F64: int = 52 -EXP_BIAS_F64: int = 1023 -EXP_FREXP_BIASED_F64: int = 1022 # 2^-1 has biased exponent 1022 (0x3FE) in double precision - -# Canonical IEEE 754 binary64 bit patterns -POS_ZERO_F64: int = 0x0000000000000000 -NEG_ZERO_F64: int = 0x8000000000000000 -POS_ONE_F64: int = 0x3FF0000000000000 # 1.0 -> exp = 1 -NEG_ONE_F64: int = 0xBFF0000000000000 # -1.0 -> exp = 1 -HALF_F64: int = 0x3FE0000000000000 # 0.5 -> exp = 0 -NEG_HALF_F64: int = 0xBFE0000000000000 # -0.5 -> exp = 0 -POS_TWO_F64: int = 0x4000000000000000 # 2.0 -> exp = 2 -NEG_TWO_F64: int = 0xC000000000000000 # -2.0 -> exp = 2 -POS_FOUR_F64: int = 0x4010000000000000 # 4.0 -> exp = 3 -QUARTER_F64: int = 0x3FD0000000000000 # 0.25 -> exp = -1 - -DBL_MIN: int = 0x0010000000000000 # 2^-1022 -> exp = -1021 -NEG_DBL_MIN: int = 0x8010000000000000 # -2^-1022 -> exp = -1021 -DBL_MAX: int = 0x7FEFFFFFFFFFFFFF # ~1.797e+308 -> exp = 1024 -NEG_DBL_MAX: int = 0xFFEFFFFFFFFFFFFF -POS_INF_F64: int = 0x7FF0000000000000 # +infinity -> exp = 0 -NEG_INF_F64: int = 0xFFF0000000000000 # -infinity -> exp = 0 -QNAN_F64: int = 0x7FF8000000000000 # Quiet NaN -> exp = 0 -NEG_QNAN_F64: int = 0xFFF8000000000000 # Negative quiet NaN -> exp = 0 -SNAN_F64: int = 0x7FF0000000000001 # Signaling NaN -> exp = 0 -SUBNORM_MIN_F64: int = 0x0000000000000001 # 2^-1074 -> exp = -1073 -SUBNORM_MAX_F64: int = 0x000FFFFFFFFFFFFF # (1 - 2^-52)*2^-1022 -> exp = -1022 -NEG_SUBNORM_MIN_F64: int = 0x8000000000000001 -NEG_SUBNORM_MAX_F64: int = 0x800FFFFFFFFFFFFF - - -def u32(val: int) -> int: - """Normalize integer to unsigned 32-bit range [0, 2^32 - 1].""" - return val & MASK32 - - -def u64(val: int) -> int: - """Normalize integer to unsigned 64-bit range [0, 2^64 - 1].""" - return val & MASK64 - - -def s32(val: int) -> int: - """Interpret a 32-bit unsigned word as a signed two's-complement integer.""" - val &= MASK32 - return val - (1 << 32) if (val & 0x80000000) else val - - -def s64(val: int) -> int: - """Interpret a 64-bit unsigned word as a signed two's-complement integer.""" - val &= MASK64 - return val - (1 << 64) if (val & SIGN_MASK_F64) else val - - -def split_dwords(val64: int) -> tuple[int, int]: - """Split an unsigned 64-bit integer into (low_dword, high_dword).""" - val = val64 & MASK64 - return val & MASK32, (val >> 32) & MASK32 - - -def join_dwords(lo: int, hi: int) -> int: - """Join (low_dword, high_dword) into an unsigned 64-bit integer.""" - return ((hi & MASK32) << 32) | (lo & MASK32) - - -def bits_to_f64(bits: int) -> float: - """Decode 64-bit unsigned integer to IEEE 754 double-precision float.""" - return struct.unpack(" int: - """Encode double float to IEEE 754 double-precision 64-bit unsigned integer.""" - try: - return struct.unpack(" 0 else NEG_INF_F64 - - -def is_nan_f64(bits: int) -> bool: - """True if 64-bit integer represents an IEEE 754 double NaN.""" - bits &= MASK64 - return (bits & EXP_MASK_F64) == EXP_MASK_F64 and (bits & MANT_MASK_F64) != 0 - - -def is_subnormal_f64(bits: int) -> bool: - """True if bits represent an IEEE 754 double subnormal number.""" - bits &= MASK64 - return (bits & EXP_MASK_F64) == 0 and (bits & MANT_MASK_F64) != 0 - - -def apply_f64_modifiers(bits: int, neg: bool = False, abs_val: bool = False) -> int: - """Applies VOP3 input modifiers: abs (|x|) first, then neg (-x).""" - bits &= MASK64 - if abs_val: - bits &= ~SIGN_MASK_F64 - if neg: - bits ^= SIGN_MASK_F64 - return bits & MASK64 - - -def ref_frexp_exp_i32_f64(s0_bits: int, ftz: bool = False) -> int: - """Pure bitwise reference oracle for RDNA2 v_frexp_exp_i32_f64. - - Rules: - - If NaN or +/-INF: returns 0. - - If +/-0.0: returns 0. - - If normal double: returns (biased_exp - 1022) as 32-bit two's complement. - - If subnormal double: returns (-1022 - leading_zeros) under IEEE mode, or 0 under FTZ. - """ - s0_bits &= MASK64 - exp_biased = (s0_bits & EXP_MASK_F64) >> EXP_SHIFT_F64 - frac = s0_bits & MANT_MASK_F64 - - # Special case: +/-INF or NaN - if exp_biased == 0x7FF: - return 0 - - # Special case: zero or subnormal - if exp_biased == 0: - if frac == 0 or ftz: - return 0 - # In double precision, mantissa has 52 bits - lz = 52 - frac.bit_length() - unbiased = -1022 - lz - return unbiased & MASK32 - - # Normal double float - unbiased = exp_biased - EXP_FREXP_BIASED_F64 - return unbiased & MASK32 - - -def ref_frexp_exp_i32_ext( - s0_bits: int, - neg: bool = False, - abs_val: bool = False, - ftz: bool = False, -) -> int: - """Reference oracle for v_frexp_exp_i32_f64 with input modifiers.""" - mod = apply_f64_modifiers(s0_bits, neg=neg, abs_val=abs_val) - return ref_frexp_exp_i32_f64(mod, ftz=ftz) - - -# --------------------------------------------------------------------------- -# Symbolic AST Opcode Definitions and Typed Expressions -# --------------------------------------------------------------------------- - -class RegKind(enum.Enum): - """Register file domain.""" - VGPR = "v" - SGPR = "s" - - -@dataclasses.dataclass(frozen=True) -class Register: - """Symbolic register operand representing a 32-bit register or 64-bit pair.""" - kind: RegKind - index: int - count: int = 1 - - def __post_init__(self) -> None: - if self.index < 0 or self.index >= 256: - raise ValueError(f"Register index out of range [0, 255]: {self.index}") - if self.count not in (1, 2): - raise ValueError(f"Unsupported register count (must be 1 or 2): {self.count}") - if self.count == 2 and self.index + 1 >= 256: - raise ValueError(f"64-bit register pair exceeds register file boundary: {self.index}") - - @property - def is_vgpr(self) -> bool: - return self.kind == RegKind.VGPR - - @property - def is_sgpr(self) -> bool: - return self.kind == RegKind.SGPR - - def format_asm(self) -> str: - if self.count == 2: - return f"{self.kind.value}[{self.index}:{self.index + 1}]" - return f"{self.kind.value}{self.index}" - - -@dataclasses.dataclass(frozen=True) -class Immediate: - """Symbolic 64-bit immediate float operand.""" - bits: int - - def __init__(self, val: int | float) -> None: - if isinstance(val, float): - b = f64_to_bits(val) - else: - b = val & MASK64 - object.__setattr__(self, "bits", b) - - @property - def as_float(self) -> float: - return bits_to_f64(self.bits) - - def format_asm(self) -> str: - return f"{self.bits:#018x}" - - -@dataclasses.dataclass(frozen=True) -class OperandModifiers: - """Input modifiers for VALU floating-point instructions (abs and neg).""" - neg: bool = False - abs_val: bool = False - - def apply(self, bits: int) -> int: - return apply_f64_modifiers(bits, neg=self.neg, abs_val=self.abs_val) - - def format_asm(self, base_str: str) -> str: - res = base_str - if self.abs_val: - res = f"|{res}|" - if self.neg: - res = f"-{res}" - return res - - -class Opcode(enum.Enum): - """VALU exponent extraction opcode.""" - V_FREXP_EXP_I32_F64 = "v_frexp_exp_i32_f64" - - -class Encoding(enum.Enum): - """Instruction encoding format.""" - VOP1 = "e32" - VOP3 = "e64" - - -@dataclasses.dataclass(frozen=True) -class Instruction: - """Symbolic AST node representing a v_frexp_exp_i32_f64 instruction.""" - opcode: Opcode - dst: Register - src0: Register | Immediate - src0_mods: OperandModifiers = dataclasses.field(default_factory=OperandModifiers) - encoding: Encoding = Encoding.VOP3 - - def __post_init__(self) -> None: - if not self.dst.is_vgpr: - raise ValueError(f"VALU instruction destination must be a VGPR: {self.dst}") - if self.dst.count != 1: - raise ValueError(f"v_frexp_exp_i32_f64 destination must be 32-bit (count=1): {self.dst}") - if isinstance(self.src0, Register) and self.src0.count != 2: - raise ValueError(f"v_frexp_exp_i32_f64 source register must be a 64-bit pair (count=2): {self.src0}") - # VOP1 (e32) does not support input modifiers - has_mods = self.src0_mods.neg or self.src0_mods.abs_val - if self.encoding == Encoding.VOP1 and has_mods: - raise ValueError("VOP1 encoding does not support input modifiers (requires VOP3/e64)") - - def to_assembly(self) -> str: - s0_str = self.src0.format_asm() - s0_fmt = self.src0_mods.format_asm(s0_str) - dst_str = self.dst.format_asm() - enc_suffix = f"_{self.encoding.value}" if self.encoding == Encoding.VOP1 else "" - return f"{self.opcode.value}{enc_suffix} {dst_str}, {s0_fmt}" - - -@dataclasses.dataclass -class Program: - """Symbolic sequence of VALU instructions.""" - instructions: list[Instruction] = dataclasses.field(default_factory=list) - - def append(self, inst: Instruction) -> None: - self.instructions.append(inst) - - def to_assembly(self) -> str: - return "\n".join(inst.to_assembly() for inst in self.instructions) - - -# --------------------------------------------------------------------------- -# Condition Codes, Status Flags, and Carry/Borrow Isolation -# --------------------------------------------------------------------------- - -@dataclasses.dataclass(frozen=True) -class ConditionCodes: - """Architectural integer condition codes for v_frexp_exp_i32_f64 output.""" - zero: bool - negative: bool - positive: bool - - -@dataclasses.dataclass(frozen=True) -class FPStatusFlags: - """IEEE 754 floating-point status flags for the input operand.""" - invalid: bool # e.g. signaling NaN input - denormal: bool # e.g. subnormal double input - inexact: bool = False - overflow: bool = False - underflow: bool = False - - -def compute_condition_codes(result: int) -> ConditionCodes: - """Computes condition codes evaluating the extracted 32-bit integer exponent.""" - signed_val = s32(result) - return ConditionCodes( - zero=(signed_val == 0), - negative=(signed_val < 0), - positive=(signed_val > 0), - ) - - -def compute_fp_status_flags(s0_bits: int) -> FPStatusFlags: - """Computes IEEE 754 status flags for double-precision input.""" - bits = s0_bits & MASK64 - invalid = bool((bits & EXP_MASK_F64) == EXP_MASK_F64 and (bits & MANT_MASK_F64) != 0 and not (bits & 0x0008000000000000)) - denormal = is_subnormal_f64(bits) - return FPStatusFlags( - invalid=invalid, - denormal=denormal, - inexact=False, - overflow=False, - underflow=False, - ) - - -# --------------------------------------------------------------------------- -# Deterministic Scalar Instruction Interpreter -# --------------------------------------------------------------------------- - -class ScalarVALUInterpreter: - """Deterministic scalar interpreter for GFX10/RDNA2 v_frexp_exp_i32_f64.""" - - def __init__(self, mode_ftz: bool = False) -> None: - self.vgprs: list[int] = [0] * 256 - self.sgprs: list[int] = [0] * 106 - self.mode_ftz: bool = mode_ftz - self.vcc: int = 0 - self.last_condition_codes: ConditionCodes | None = None - self.last_status_flags: FPStatusFlags | None = None - self.trace: list[str] = [] - - def read_reg_u32(self, kind: RegKind, idx: int) -> int: - if idx < 0 or (kind == RegKind.VGPR and idx >= 256) or (kind == RegKind.SGPR and idx >= 106): - raise IndexError(f"Register index out of bounds: {kind.value}{idx}") - return (self.vgprs[idx] if kind == RegKind.VGPR else self.sgprs[idx]) & MASK32 - - def write_reg_u32(self, kind: RegKind, idx: int, val: int) -> None: - if idx < 0 or (kind == RegKind.VGPR and idx >= 256) or (kind == RegKind.SGPR and idx >= 106): - raise IndexError(f"Register index out of bounds: {kind.value}{idx}") - val32 = val & MASK32 - if kind == RegKind.VGPR: - self.vgprs[idx] = val32 - else: - self.sgprs[idx] = val32 - - def read_reg_u64(self, kind: RegKind, idx: int) -> int: - lo = self.read_reg_u32(kind, idx) - hi = self.read_reg_u32(kind, idx + 1) - return join_dwords(lo, hi) - - def write_reg_u64(self, kind: RegKind, idx: int, val: int) -> None: - lo, hi = split_dwords(val) - self.write_reg_u32(kind, idx, lo) - self.write_reg_u32(kind, idx + 1, hi) - - def read_operand(self, op: Register | Immediate, mods: OperandModifiers) -> int: - if isinstance(op, Immediate): - raw = op.bits - elif isinstance(op, Register): - raw = self.read_reg_u64(op.kind, op.index) - else: - raise TypeError(f"Unsupported operand type: {type(op)}") - return mods.apply(raw) - - def step(self, inst: Instruction) -> int: - """Executes a single v_frexp_exp_i32_f64 instruction deterministically.""" - # Read 64-bit float source before writing 32-bit integer destination - s0_val = self.read_operand(inst.src0, inst.src0_mods) - - if inst.opcode == Opcode.V_FREXP_EXP_I32_F64: - res = ref_frexp_exp_i32_f64(s0_val, ftz=self.mode_ftz) - else: - raise NotImplementedError(f"Unsupported opcode in scalar interpreter: {inst.opcode}") - - self.write_reg_u32(inst.dst.kind, inst.dst.index, res) - self.last_condition_codes = compute_condition_codes(res) - self.last_status_flags = compute_fp_status_flags(s0_val) - # Note: v_frexp_exp_i32_f64 does not generate carry or borrow; VCC is isolated and unchanged - self.trace.append(f"{inst.to_assembly()} => {res:#010x} ({s32(res)})") - return res - - def run_program(self, prog: Program) -> list[int]: - """Executes all instructions in a program sequentially.""" - return [self.step(inst) for inst in prog.instructions] - - -# --------------------------------------------------------------------------- -# SIMD Wavefront Interpreter (Multi-Lane Divergence & 32/64-Bit EXEC Masking) -# --------------------------------------------------------------------------- - -class SIMDWavefrontInterpreter: - """Multi-lane SIMD interpreter modeling Wave32 and Wave64 execution on RDNA2.""" - - def __init__(self, wave_size: int = 64, mode_ftz: bool = False) -> None: - if wave_size not in (32, 64): - raise ValueError(f"Invalid wave_size: {wave_size} (must be 32 or 64)") - self.wave_size: int = wave_size - self.mode_ftz: bool = mode_ftz - self.exec_mask: int = (1 << wave_size) - 1 - # Per-lane VGPR files: [wave_size][256] 32-bit registers - self.vgprs: list[list[int]] = [[0] * 256 for _ in range(wave_size)] - # Wavefront-shared SGPR file: [106] 32-bit registers - self.sgprs: list[int] = [0] * 106 - self.vcc: int = 0 - - def set_exec_mask(self, mask: int) -> None: - valid_mask = (1 << self.wave_size) - 1 - self.exec_mask = mask & valid_mask - - def read_lane_reg_u32(self, lane: int, kind: RegKind, idx: int) -> int: - if kind == RegKind.VGPR: - return self.vgprs[lane][idx] & MASK32 - return self.sgprs[idx] & MASK32 - - def write_lane_reg_u32(self, lane: int, kind: RegKind, idx: int, val: int) -> None: - val32 = val & MASK32 - if kind == RegKind.VGPR: - self.vgprs[lane][idx] = val32 - else: - self.sgprs[idx] = val32 - - def read_lane_reg_u64(self, lane: int, kind: RegKind, idx: int) -> int: - lo = self.read_lane_reg_u32(lane, kind, idx) - hi = self.read_lane_reg_u32(lane, kind, idx + 1) - return join_dwords(lo, hi) - - def write_lane_reg_u64(self, lane: int, kind: RegKind, idx: int, val: int) -> None: - lo, hi = split_dwords(val) - self.write_lane_reg_u32(lane, kind, idx, lo) - self.write_lane_reg_u32(lane, kind, idx + 1, hi) - - def read_lane_operand(self, lane: int, op: Register | Immediate, mods: OperandModifiers) -> int: - if isinstance(op, Immediate): - raw = op.bits - elif isinstance(op, Register): - raw = self.read_lane_reg_u64(lane, op.kind, op.index) - else: - raise TypeError(f"Unsupported operand type: {type(op)}") - return mods.apply(raw) - - def step(self, inst: Instruction) -> list[int | None]: - """Executes a VALU instruction across all lanes in the wavefront governed by EXEC mask.""" - # 1. Latch inputs for all lanes (read-before-write semantics) - latched_inputs: list[int] = [] - for lane in range(self.wave_size): - s0_val = self.read_lane_operand(lane, inst.src0, inst.src0_mods) - latched_inputs.append(s0_val) - - # 2. Compute and write back strictly for active lanes - lane_results: list[int | None] = [] - for lane in range(self.wave_size): - is_active = bool((self.exec_mask >> lane) & 1) - if not is_active: - lane_results.append(None) - continue - - s0_val = latched_inputs[lane] - if inst.opcode == Opcode.V_FREXP_EXP_I32_F64: - res = ref_frexp_exp_i32_f64(s0_val, ftz=self.mode_ftz) - else: - raise NotImplementedError(f"Unsupported opcode in SIMD interpreter: {inst.opcode}") - - self.write_lane_reg_u32(lane, inst.dst.kind, inst.dst.index, res) - lane_results.append(res) - - return lane_results - - -class TestValuFrexpExpI32F64Oracle(unittest.TestCase): - """Unit tests for the reference mathematical oracle and architectural model.""" - - def test_powers_of_two(self) -> None: - self.assertEqual(s32(ref_frexp_exp_i32_f64(HALF_F64)), 0) - self.assertEqual(s32(ref_frexp_exp_i32_f64(POS_ONE_F64)), 1) - self.assertEqual(s32(ref_frexp_exp_i32_f64(POS_TWO_F64)), 2) - self.assertEqual(s32(ref_frexp_exp_i32_f64(POS_FOUR_F64)), 3) - self.assertEqual(s32(ref_frexp_exp_i32_f64(QUARTER_F64)), -1) - - def test_cross_check_math_frexp_normals(self) -> None: - test_floats = [ - 1.0, -1.0, 0.5, -0.5, 2.0, -2.0, 3.141592653589793, -100.25, - 1e10, 1e-10, 1e300, 1e-300, - ] - for f in test_floats: - with self.subTest(val=f): - expected_exp = math.frexp(f)[1] - bits = f64_to_bits(f) - computed_exp = s32(ref_frexp_exp_i32_f64(bits)) - self.assertEqual(computed_exp, expected_exp) - - def test_zeros_return_zero(self) -> None: - self.assertEqual(ref_frexp_exp_i32_f64(POS_ZERO_F64), 0) - self.assertEqual(ref_frexp_exp_i32_f64(NEG_ZERO_F64), 0) - - def test_infinities_return_zero(self) -> None: - self.assertEqual(ref_frexp_exp_i32_f64(POS_INF_F64), 0) - self.assertEqual(ref_frexp_exp_i32_f64(NEG_INF_F64), 0) - - def test_nans_return_zero(self) -> None: - self.assertEqual(ref_frexp_exp_i32_f64(QNAN_F64), 0) - self.assertEqual(ref_frexp_exp_i32_f64(NEG_QNAN_F64), 0) - self.assertEqual(ref_frexp_exp_i32_f64(SNAN_F64), 0) - - def test_subnormals_unbiased_exponent(self) -> None: - # SUBNORM_MAX: leading bit is at 51, lz = 0 -> exp = -1022 - self.assertEqual(s32(ref_frexp_exp_i32_f64(SUBNORM_MAX_F64)), -1022) - # SUBNORM_MIN: fraction is 1, lz = 51 -> exp = -1073 - self.assertEqual(s32(ref_frexp_exp_i32_f64(SUBNORM_MIN_F64)), -1073) - - def test_modifiers_abs_neg(self) -> None: - # Sign does not alter exponent magnitude - self.assertEqual(ref_frexp_exp_i32_ext(NEG_ONE_F64, abs_val=True), 1) - self.assertEqual(ref_frexp_exp_i32_ext(POS_ONE_F64, neg=True), 1) - self.assertEqual(ref_frexp_exp_i32_ext(POS_TWO_F64, neg=True, abs_val=True), 2) - - def test_ftz_mode(self) -> None: - self.assertEqual(ref_frexp_exp_i32_f64(SUBNORM_MIN_F64, ftz=True), 0) - self.assertEqual(ref_frexp_exp_i32_f64(SUBNORM_MAX_F64, ftz=True), 0) - # Normal floats unaffected by FTZ - self.assertEqual(ref_frexp_exp_i32_f64(POS_ONE_F64, ftz=True), 1) - - -class TestValuFrexpExpI32F64AST(unittest.TestCase): - """Unit tests for symbolic AST opcode definitions and typed expressions.""" - - def test_register_types_and_validation(self) -> None: - dst = Register(RegKind.VGPR, 0, count=1) - src = Register(RegKind.VGPR, 2, count=2) - sgpr_src = Register(RegKind.SGPR, 4, count=2) - - self.assertTrue(dst.is_vgpr) - self.assertFalse(dst.is_sgpr) - self.assertEqual(dst.format_asm(), "v0") - self.assertEqual(src.format_asm(), "v[2:3]") - self.assertEqual(sgpr_src.format_asm(), "s[4:5]") - - def test_immediate_representation(self) -> None: - imm = Immediate(1.0) - self.assertEqual(imm.bits, POS_ONE_F64) - self.assertEqual(imm.as_float, 1.0) - self.assertEqual(imm.format_asm(), f"{POS_ONE_F64:#018x}") - - def test_instruction_formatting(self) -> None: - inst_vop3 = Instruction( - opcode=Opcode.V_FREXP_EXP_I32_F64, - dst=Register(RegKind.VGPR, 0, count=1), - src0=Register(RegKind.VGPR, 2, count=2), - src0_mods=OperandModifiers(neg=True, abs_val=True), - ) - self.assertEqual(inst_vop3.to_assembly(), "v_frexp_exp_i32_f64 v0, -|v[2:3]|") - - inst_vop1 = Instruction( - opcode=Opcode.V_FREXP_EXP_I32_F64, - dst=Register(RegKind.VGPR, 5, count=1), - src0=Register(RegKind.VGPR, 6, count=2), - encoding=Encoding.VOP1, - ) - self.assertEqual(inst_vop1.to_assembly(), "v_frexp_exp_i32_f64_e32 v5, v[6:7]") - - def test_instruction_validation(self) -> None: - # Invalid destination kind (must be VGPR) - with self.assertRaises(ValueError): - Instruction( - opcode=Opcode.V_FREXP_EXP_I32_F64, - dst=Register(RegKind.SGPR, 0, count=1), - src0=Register(RegKind.VGPR, 2, count=2), - ) - - # Invalid destination count (must be 1 for i32) - with self.assertRaises(ValueError): - Instruction( - opcode=Opcode.V_FREXP_EXP_I32_F64, - dst=Register(RegKind.VGPR, 0, count=2), - src0=Register(RegKind.VGPR, 2, count=2), - ) - - # Invalid source count (must be 2 for 64-bit float) - with self.assertRaises(ValueError): - Instruction( - opcode=Opcode.V_FREXP_EXP_I32_F64, - dst=Register(RegKind.VGPR, 0, count=1), - src0=Register(RegKind.VGPR, 2, count=1), - ) - - # VOP1 does not support input modifiers - with self.assertRaises(ValueError): - Instruction( - opcode=Opcode.V_FREXP_EXP_I32_F64, - dst=Register(RegKind.VGPR, 0, count=1), - src0=Register(RegKind.VGPR, 2, count=2), - src0_mods=OperandModifiers(neg=True), - encoding=Encoding.VOP1, - ) - - def test_program_assembly(self) -> None: - prog = Program() - prog.append(Instruction( - opcode=Opcode.V_FREXP_EXP_I32_F64, - dst=Register(RegKind.VGPR, 0, count=1), - src0=Register(RegKind.VGPR, 2, count=2), - )) - prog.append(Instruction( - opcode=Opcode.V_FREXP_EXP_I32_F64, - dst=Register(RegKind.VGPR, 1, count=1), - src0=Immediate(2.0), - )) - expected = ( - "v_frexp_exp_i32_f64 v0, v[2:3]\n" - f"v_frexp_exp_i32_f64 v1, {POS_TWO_F64:#018x}" - ) - self.assertEqual(prog.to_assembly(), expected) - - -class TestValuFrexpExpI32F64ScalarInterpreter(unittest.TestCase): - """Unit tests for the deterministic scalar VALU instruction interpreter.""" - - def test_scalar_register_read_write(self) -> None: - interp = ScalarVALUInterpreter() - interp.write_reg_u32(RegKind.VGPR, 0, 0x12345678) - interp.write_reg_u64(RegKind.VGPR, 2, POS_TWO_F64) - interp.write_reg_u64(RegKind.SGPR, 4, NEG_HALF_F64) - - self.assertEqual(interp.read_reg_u32(RegKind.VGPR, 0), 0x12345678) - self.assertEqual(interp.read_reg_u64(RegKind.VGPR, 2), POS_TWO_F64) - self.assertEqual(interp.read_reg_u64(RegKind.SGPR, 4), NEG_HALF_F64) - - def test_scalar_execution_from_vgpr_pair(self) -> None: - interp = ScalarVALUInterpreter() - # Set v[2:3] = 4.0 -> exp = 3 - interp.write_reg_u64(RegKind.VGPR, 2, POS_FOUR_F64) - - inst = Instruction( - opcode=Opcode.V_FREXP_EXP_I32_F64, - dst=Register(RegKind.VGPR, 0, count=1), - src0=Register(RegKind.VGPR, 2, count=2), - ) - res = interp.step(inst) - self.assertEqual(s32(res), 3) - self.assertEqual(s32(interp.read_reg_u32(RegKind.VGPR, 0)), 3) - - def test_scalar_execution_from_sgpr_pair(self) -> None: - interp = ScalarVALUInterpreter() - # Set s[0:1] = 0.5 -> exp = 0 - interp.write_reg_u64(RegKind.SGPR, 0, HALF_F64) - - inst = Instruction( - opcode=Opcode.V_FREXP_EXP_I32_F64, - dst=Register(RegKind.VGPR, 5, count=1), - src0=Register(RegKind.SGPR, 0, count=2), - ) - res = interp.step(inst) - self.assertEqual(s32(res), 0) - self.assertEqual(s32(interp.read_reg_u32(RegKind.VGPR, 5)), 0) - - def test_scalar_execution_from_immediate(self) -> None: - interp = ScalarVALUInterpreter() - inst = Instruction( - opcode=Opcode.V_FREXP_EXP_I32_F64, - dst=Register(RegKind.VGPR, 0, count=1), - src0=Immediate(1.0), - ) - res = interp.step(inst) - self.assertEqual(s32(res), 1) - self.assertEqual(s32(interp.read_reg_u32(RegKind.VGPR, 0)), 1) - - def test_scalar_modifiers_abs_neg(self) -> None: - interp = ScalarVALUInterpreter() - interp.write_reg_u64(RegKind.VGPR, 2, NEG_TWO_F64) - - # v0 = frexp_exp(-|-2.0|) -> exp(-2.0) = 2 - inst = Instruction( - opcode=Opcode.V_FREXP_EXP_I32_F64, - dst=Register(RegKind.VGPR, 0, count=1), - src0=Register(RegKind.VGPR, 2, count=2), - src0_mods=OperandModifiers(neg=True, abs_val=True), - ) - res = interp.step(inst) - self.assertEqual(s32(res), 2) - self.assertEqual(s32(interp.read_reg_u32(RegKind.VGPR, 0)), 2) - - def test_scalar_program_execution_chain(self) -> None: - interp = ScalarVALUInterpreter() - interp.write_reg_u64(RegKind.VGPR, 2, POS_FOUR_F64) # 4.0 -> exp = 3 - interp.write_reg_u64(RegKind.VGPR, 4, QUARTER_F64) # 0.25 -> exp = -1 - - prog = Program() - prog.append(Instruction( - opcode=Opcode.V_FREXP_EXP_I32_F64, - dst=Register(RegKind.VGPR, 0, count=1), - src0=Register(RegKind.VGPR, 2, count=2), - )) - prog.append(Instruction( - opcode=Opcode.V_FREXP_EXP_I32_F64, - dst=Register(RegKind.VGPR, 1, count=1), - src0=Register(RegKind.VGPR, 4, count=2), - )) - - results = interp.run_program(prog) - self.assertEqual([s32(r) for r in results], [3, -1]) - self.assertEqual(s32(interp.read_reg_u32(RegKind.VGPR, 0)), 3) - self.assertEqual(s32(interp.read_reg_u32(RegKind.VGPR, 1)), -1) - self.assertEqual(len(interp.trace), 2) - - -class TestValuFrexpExpI32F64SIMD(unittest.TestCase): - """Unit tests for SIMD multi-lane divergence and 32/64-bit EXEC masking.""" - - def test_wave32_uniform_inputs(self) -> None: - simd = SIMDWavefrontInterpreter(wave_size=32) - inst = Instruction( - opcode=Opcode.V_FREXP_EXP_I32_F64, - dst=Register(RegKind.VGPR, 0, count=1), - src0=Register(RegKind.VGPR, 2, count=2), - ) - for lane in range(32): - simd.write_lane_reg_u64(lane, RegKind.VGPR, 2, POS_TWO_F64) - - results = simd.step(inst) - self.assertEqual(len(results), 32) - for lane in range(32): - self.assertEqual(s32(results[lane]), 2) - self.assertEqual(s32(simd.read_lane_reg_u32(lane, RegKind.VGPR, 0)), 2) - - def test_wave64_multi_lane_divergence(self) -> None: - simd = SIMDWavefrontInterpreter(wave_size=64) - inst = Instruction( - opcode=Opcode.V_FREXP_EXP_I32_F64, - dst=Register(RegKind.VGPR, 0, count=1), - src0=Register(RegKind.VGPR, 2, count=2), - ) - expected: list[int] = [] - for lane in range(64): - # Powers of 2: 2^(lane - 30) - val = math.ldexp(1.0, lane - 30) - bits = f64_to_bits(val) - simd.write_lane_reg_u64(lane, RegKind.VGPR, 2, bits) - expected.append(s32(ref_frexp_exp_i32_f64(bits))) - - results = simd.step(inst) - for lane in range(64): - self.assertEqual(s32(results[lane]), expected[lane]) - self.assertEqual(s32(simd.read_lane_reg_u32(lane, RegKind.VGPR, 0)), expected[lane]) - - def test_wave32_exec_masking_partial(self) -> None: - simd = SIMDWavefrontInterpreter(wave_size=32) - exec_mask = 0x55555555 # Even lanes active - simd.set_exec_mask(exec_mask) - - canary = 0xDEADBEEF - for lane in range(32): - simd.write_lane_reg_u32(lane, RegKind.VGPR, 0, canary) - simd.write_lane_reg_u64(lane, RegKind.VGPR, 2, POS_FOUR_F64) # exp = 3 - - inst = Instruction( - opcode=Opcode.V_FREXP_EXP_I32_F64, - dst=Register(RegKind.VGPR, 0, count=1), - src0=Register(RegKind.VGPR, 2, count=2), - ) - results = simd.step(inst) - - for lane in range(32): - if (exec_mask >> lane) & 1: - self.assertEqual(s32(results[lane]), 3) - self.assertEqual(s32(simd.read_lane_reg_u32(lane, RegKind.VGPR, 0)), 3) - else: - self.assertIsNone(results[lane]) - self.assertEqual(simd.read_lane_reg_u32(lane, RegKind.VGPR, 0), canary) - - def test_wave64_exec_masking_all_inactive(self) -> None: - simd = SIMDWavefrontInterpreter(wave_size=64) - simd.set_exec_mask(0) - - canary = 0xBAADF00D - for lane in range(64): - simd.write_lane_reg_u32(lane, RegKind.VGPR, 0, canary) - simd.write_lane_reg_u64(lane, RegKind.VGPR, 2, POS_ONE_F64) - - inst = Instruction( - opcode=Opcode.V_FREXP_EXP_I32_F64, - dst=Register(RegKind.VGPR, 0, count=1), - src0=Register(RegKind.VGPR, 2, count=2), - ) - results = simd.step(inst) - self.assertEqual(results, [None] * 64) - for lane in range(64): - self.assertEqual(simd.read_lane_reg_u32(lane, RegKind.VGPR, 0), canary) - - def test_simd_with_shared_sgpr_scalar_source(self) -> None: - simd = SIMDWavefrontInterpreter(wave_size=32) - # Shared SGPR source s[4:5] = 2.0 -> exp = 2 - simd.write_lane_reg_u64(0, RegKind.SGPR, 4, POS_TWO_F64) - - inst = Instruction( - opcode=Opcode.V_FREXP_EXP_I32_F64, - dst=Register(RegKind.VGPR, 0, count=1), - src0=Register(RegKind.SGPR, 4, count=2), - ) - results = simd.step(inst) - for lane in range(32): - self.assertEqual(s32(results[lane]), 2) - self.assertEqual(s32(simd.read_lane_reg_u32(lane, RegKind.VGPR, 0)), 2) - - -class TestValuFrexpExpI32F64RegisterAliasing(unittest.TestCase): - """Unit tests for register aliasing and in-place operand preservation.""" - - def test_aliasing_dst_equals_src0_low_dword(self) -> None: - # dst = v0, src0 = v[0:1] - interp = ScalarVALUInterpreter() - # Set v[0:1] = 4.0 -> exp = 3 - interp.write_reg_u64(RegKind.VGPR, 0, POS_FOUR_F64) - lo_orig, hi_orig = split_dwords(POS_FOUR_F64) - - inst = Instruction( - opcode=Opcode.V_FREXP_EXP_I32_F64, - dst=Register(RegKind.VGPR, 0, count=1), - src0=Register(RegKind.VGPR, 0, count=2), - ) - res = interp.step(inst) - self.assertEqual(s32(res), 3) - # v0 overwritten with result 3 - self.assertEqual(s32(interp.read_reg_u32(RegKind.VGPR, 0)), 3) - # v1 (high dword) remains undisturbed - self.assertEqual(interp.read_reg_u32(RegKind.VGPR, 1), hi_orig) - - def test_aliasing_dst_equals_src0_high_dword(self) -> None: - # dst = v1, src0 = v[0:1] - interp = ScalarVALUInterpreter() - # Set v[0:1] = 0.25 -> exp = -1 - interp.write_reg_u64(RegKind.VGPR, 0, QUARTER_F64) - lo_orig, hi_orig = split_dwords(QUARTER_F64) - - inst = Instruction( - opcode=Opcode.V_FREXP_EXP_I32_F64, - dst=Register(RegKind.VGPR, 1, count=1), - src0=Register(RegKind.VGPR, 0, count=2), - ) - res = interp.step(inst) - self.assertEqual(s32(res), -1) - # v0 (low dword) remains undisturbed - self.assertEqual(interp.read_reg_u32(RegKind.VGPR, 0), lo_orig) - # v1 overwritten with result -1 (0xFFFFFFFF) - self.assertEqual(interp.read_reg_u32(RegKind.VGPR, 1), 0xFFFFFFFF) - - def test_unrelated_registers_preserved(self) -> None: - interp = ScalarVALUInterpreter() - for idx in range(10, 20): - interp.write_reg_u32(RegKind.VGPR, idx, 0x55000000 + idx) - - inst = Instruction( - opcode=Opcode.V_FREXP_EXP_I32_F64, - dst=Register(RegKind.VGPR, 0, count=1), - src0=Immediate(2.0), - ) - interp.step(inst) - - for idx in range(10, 20): - self.assertEqual(interp.read_reg_u32(RegKind.VGPR, idx), 0x55000000 + idx) - - def test_simd_aliasing_with_divergent_exec_mask(self) -> None: - simd = SIMDWavefrontInterpreter(wave_size=32) - exec_mask = 0x0000000F # Lanes 0..3 active - simd.set_exec_mask(exec_mask) - - for lane in range(32): - simd.write_lane_reg_u64(lane, RegKind.VGPR, 0, POS_TWO_F64) # exp = 2 - - lo_orig, hi_orig = split_dwords(POS_TWO_F64) - - inst = Instruction( - opcode=Opcode.V_FREXP_EXP_I32_F64, - dst=Register(RegKind.VGPR, 0, count=1), - src0=Register(RegKind.VGPR, 0, count=2), - ) - simd.step(inst) - - for lane in range(32): - if lane < 4: - # Active: v0 updated to 2, v1 unchanged - self.assertEqual(s32(simd.read_lane_reg_u32(lane, RegKind.VGPR, 0)), 2) - self.assertEqual(simd.read_lane_reg_u32(lane, RegKind.VGPR, 1), hi_orig) - else: - # Inactive: v0 and v1 both preserved - self.assertEqual(simd.read_lane_reg_u32(lane, RegKind.VGPR, 0), lo_orig) - self.assertEqual(simd.read_lane_reg_u32(lane, RegKind.VGPR, 1), hi_orig) - - -class TestValuFrexpExpI32F64ConditionCodes(unittest.TestCase): - """Unit tests for condition codes, status flags, and carry/borrow isolation.""" - - def test_condition_codes_zero_pos_neg(self) -> None: - interp = ScalarVALUInterpreter() - - # Input 0.5 -> exp = 0 - interp.step(Instruction( - opcode=Opcode.V_FREXP_EXP_I32_F64, - dst=Register(RegKind.VGPR, 0, count=1), - src0=Immediate(0.5), - )) - cc_zero = interp.last_condition_codes - self.assertIsNotNone(cc_zero) - assert cc_zero is not None - self.assertTrue(cc_zero.zero) - self.assertFalse(cc_zero.negative) - self.assertFalse(cc_zero.positive) - - # Input 2.0 -> exp = 2 (positive) - interp.step(Instruction( - opcode=Opcode.V_FREXP_EXP_I32_F64, - dst=Register(RegKind.VGPR, 0, count=1), - src0=Immediate(2.0), - )) - cc_pos = interp.last_condition_codes - self.assertIsNotNone(cc_pos) - assert cc_pos is not None - self.assertFalse(cc_pos.zero) - self.assertFalse(cc_pos.negative) - self.assertTrue(cc_pos.positive) - - # Input 0.25 -> exp = -1 (negative) - interp.step(Instruction( - opcode=Opcode.V_FREXP_EXP_I32_F64, - dst=Register(RegKind.VGPR, 0, count=1), - src0=Immediate(0.25), - )) - cc_neg = interp.last_condition_codes - self.assertIsNotNone(cc_neg) - assert cc_neg is not None - self.assertFalse(cc_neg.zero) - self.assertTrue(cc_neg.negative) - self.assertFalse(cc_neg.positive) - - def test_status_flags_snan_invalid(self) -> None: - flags_snan = compute_fp_status_flags(SNAN_F64) - self.assertTrue(flags_snan.invalid) - self.assertFalse(flags_snan.denormal) - - flags_qnan = compute_fp_status_flags(QNAN_F64) - self.assertFalse(flags_qnan.invalid) - - def test_status_flags_denormal(self) -> None: - flags_sub = compute_fp_status_flags(SUBNORM_MIN_F64) - self.assertTrue(flags_sub.denormal) - self.assertFalse(flags_sub.invalid) - - flags_norm = compute_fp_status_flags(POS_ONE_F64) - self.assertFalse(flags_norm.denormal) - self.assertFalse(flags_norm.invalid) - - def test_carry_borrow_vcc_isolation(self) -> None: - interp = ScalarVALUInterpreter() - canary = 0xCAFEBABE - interp.vcc = canary - - inst = Instruction( - opcode=Opcode.V_FREXP_EXP_I32_F64, - dst=Register(RegKind.VGPR, 0, count=1), - src0=Immediate(1.0), - ) - interp.step(inst) - self.assertEqual(interp.vcc, canary) - - simd = SIMDWavefrontInterpreter(wave_size=64) - simd.vcc = canary - simd.step(inst) - self.assertEqual(simd.vcc, canary) - - -class TestValuFrexpExpI32F64IEEE754Boundaries(unittest.TestCase): - """Exhaustive unit tests for IEEE 754 boundary extremes, subnormals, and NaN handling.""" - - def test_signed_zeros(self) -> None: - self.assertEqual(ref_frexp_exp_i32_f64(POS_ZERO_F64), 0) - self.assertEqual(ref_frexp_exp_i32_f64(NEG_ZERO_F64), 0) - - def test_infinities(self) -> None: - self.assertEqual(ref_frexp_exp_i32_f64(POS_INF_F64), 0) - self.assertEqual(ref_frexp_exp_i32_f64(NEG_INF_F64), 0) - - def test_nans_payloads(self) -> None: - nan_payloads = [ - QNAN_F64, - NEG_QNAN_F64, - 0x7FF8000000000001, - 0xFFF8000012345678, - SNAN_F64, - 0xFFF0000000000001, - ] - for nan in nan_payloads: - with self.subTest(nan=f"{nan:#018x}"): - self.assertEqual(ref_frexp_exp_i32_f64(nan), 0) - - def test_normal_extremes(self) -> None: - # DBL_MIN: 2^-1022 -> exp = -1021 - self.assertEqual(s32(ref_frexp_exp_i32_f64(DBL_MIN)), -1021) - self.assertEqual(s32(ref_frexp_exp_i32_f64(NEG_DBL_MIN)), -1021) - - # DBL_MAX: biased exp 2046 -> exp = 1024 - self.assertEqual(s32(ref_frexp_exp_i32_f64(DBL_MAX)), 1024) - self.assertEqual(s32(ref_frexp_exp_i32_f64(NEG_DBL_MAX)), 1024) - - def test_subnormals_range(self) -> None: - # SUBNORM_MIN: 2^-1074 -> exp = -1073 - self.assertEqual(s32(ref_frexp_exp_i32_f64(SUBNORM_MIN_F64)), -1073) - self.assertEqual(s32(ref_frexp_exp_i32_f64(NEG_SUBNORM_MIN_F64)), -1073) - - # SUBNORM_MAX: frac bit 51 set -> lz = 0 -> exp = -1022 - self.assertEqual(s32(ref_frexp_exp_i32_f64(SUBNORM_MAX_F64)), -1022) - self.assertEqual(s32(ref_frexp_exp_i32_f64(NEG_SUBNORM_MAX_F64)), -1022) - - # Intermediate subnormals with varying leading zeros - for lz in range(52): - frac = 1 << (51 - lz) - subnorm_bits = frac # biased_exp = 0 - expected_exp = -1022 - lz - self.assertEqual(s32(ref_frexp_exp_i32_f64(subnorm_bits)), expected_exp) - - def test_subnormals_ftz(self) -> None: - for lz in range(0, 52, 5): - frac = 1 << (51 - lz) - self.assertEqual(ref_frexp_exp_i32_f64(frac, ftz=True), 0) - - def test_modifiers_on_boundary_values(self) -> None: - boundary_values = [ - POS_ZERO_F64, NEG_ZERO_F64, POS_INF_F64, NEG_INF_F64, - QNAN_F64, SNAN_F64, DBL_MIN, NEG_DBL_MIN, DBL_MAX, NEG_DBL_MAX, - SUBNORM_MIN_F64, SUBNORM_MAX_F64, - ] - for val in boundary_values: - base_exp = ref_frexp_exp_i32_f64(val) - self.assertEqual(ref_frexp_exp_i32_ext(val, neg=True), base_exp) - self.assertEqual(ref_frexp_exp_i32_ext(val, abs_val=True), base_exp) - self.assertEqual(ref_frexp_exp_i32_ext(val, neg=True, abs_val=True), base_exp) - - -class TestValuFrexpExpI32F64NegativeControls(unittest.TestCase): - """Unit tests for negative controls, syntax rejection, and invalid AST inputs.""" - - def test_invalid_register_indices(self) -> None: - with self.assertRaises(ValueError): - Register(RegKind.VGPR, -1, count=1) - with self.assertRaises(ValueError): - Register(RegKind.VGPR, 256, count=1) - with self.assertRaises(ValueError): - Register(RegKind.VGPR, 255, count=2) - - def test_invalid_register_counts(self) -> None: - with self.assertRaises(ValueError): - Register(RegKind.VGPR, 0, count=0) - with self.assertRaises(ValueError): - Register(RegKind.VGPR, 0, count=3) - - def test_invalid_destination_kind(self) -> None: - # VALU destination cannot be SGPR - with self.assertRaises(ValueError): - Instruction( - opcode=Opcode.V_FREXP_EXP_I32_F64, - dst=Register(RegKind.SGPR, 0, count=1), - src0=Register(RegKind.VGPR, 2, count=2), - ) - - def test_invalid_operand_counts(self) -> None: - # Destination must be count=1 - with self.assertRaises(ValueError): - Instruction( - opcode=Opcode.V_FREXP_EXP_I32_F64, - dst=Register(RegKind.VGPR, 0, count=2), - src0=Register(RegKind.VGPR, 2, count=2), - ) - # Source must be count=2 - with self.assertRaises(ValueError): - Instruction( - opcode=Opcode.V_FREXP_EXP_I32_F64, - dst=Register(RegKind.VGPR, 0, count=1), - src0=Register(RegKind.VGPR, 2, count=1), - ) - - def test_vop1_rejects_modifiers(self) -> None: - with self.assertRaises(ValueError): - Instruction( - opcode=Opcode.V_FREXP_EXP_I32_F64, - dst=Register(RegKind.VGPR, 0, count=1), - src0=Register(RegKind.VGPR, 2, count=2), - src0_mods=OperandModifiers(neg=True), - encoding=Encoding.VOP1, - ) - - def test_scalar_interpreter_out_of_bounds_access(self) -> None: - interp = ScalarVALUInterpreter() - with self.assertRaises(IndexError): - interp.read_reg_u32(RegKind.VGPR, 256) - with self.assertRaises(IndexError): - interp.write_reg_u32(RegKind.SGPR, 106, 0) - - def test_simd_interpreter_invalid_wave_size(self) -> None: - with self.assertRaises(ValueError): - SIMDWavefrontInterpreter(wave_size=16) - with self.assertRaises(ValueError): - SIMDWavefrontInterpreter(wave_size=128) - - -class TestValuFrexpExpI32F64MutationDetection(unittest.TestCase): - """Mutation tests: verifies that intentional sabotages/mutations of the oracle are caught.""" - - def test_mutation_wrong_bias(self) -> None: - # Sabotage: biased exponent - 1023 instead of biased exponent - 1022 - def mutated_frexp_exp(bits: int) -> int: - exp_biased = (bits & EXP_MASK_F64) >> EXP_SHIFT_F64 - if exp_biased in (0, 0x7FF): - return 0 - return (exp_biased - 1023) & MASK32 - - with self.assertRaises(AssertionError): - self.assertEqual(s32(mutated_frexp_exp(POS_ONE_F64)), 1) - - def test_mutation_subnormal_omission(self) -> None: - # Sabotage: flushing subnormals to zero in IEEE mode - def mutated_frexp_exp(bits: int) -> int: - exp_biased = (bits & EXP_MASK_F64) >> EXP_SHIFT_F64 - if exp_biased == 0: - return 0 - return (exp_biased - 1022) & MASK32 - - with self.assertRaises(AssertionError): - self.assertEqual(s32(mutated_frexp_exp(SUBNORM_MIN_F64)), -1073) - - def test_mutation_special_value_leak(self) -> None: - # Sabotage: computing unbiased exponent for infinities and NaNs instead of returning 0 - def mutated_frexp_exp(bits: int) -> int: - exp_biased = (bits & EXP_MASK_F64) >> EXP_SHIFT_F64 - return (exp_biased - 1022) & MASK32 - - with self.assertRaises(AssertionError): - self.assertEqual(mutated_frexp_exp(POS_INF_F64), 0) - with self.assertRaises(AssertionError): - self.assertEqual(mutated_frexp_exp(QNAN_F64), 0) - - def test_mutation_simd_exec_mask_leak(self) -> None: - # Sabotage: inactive lanes write to destination register - simd = SIMDWavefrontInterpreter(wave_size=32) - simd.set_exec_mask(0) # all inactive - canary = 0x11223344 - simd.write_lane_reg_u32(0, RegKind.VGPR, 0, canary) - - inst = Instruction( - opcode=Opcode.V_FREXP_EXP_I32_F64, - dst=Register(RegKind.VGPR, 0, count=1), - src0=Immediate(2.0), - ) - simd.step(inst) - self.assertEqual(simd.read_lane_reg_u32(0, RegKind.VGPR, 0), canary) - - # Mutated unconditional write - simd.write_lane_reg_u32(0, RegKind.VGPR, 0, 2) - with self.assertRaises(AssertionError): - self.assertEqual(simd.read_lane_reg_u32(0, RegKind.VGPR, 0), canary) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_valu_frexp_f64.py b/tests/semantic/test_valu_frexp_f64.py deleted file mode 100644 index 4335674db..000000000 --- a/tests/semantic/test_valu_frexp_f64.py +++ /dev/null @@ -1,1572 +0,0 @@ -from __future__ import annotations - -"""Semantic interpreter tests and reference mathematical oracle for RDNA2 v_frexp_f64. - -Instructions: - 1. v_frexp_mant_f64 dst, src0 (VOP1 e32 / VOP3 e64) - D.f64 = Mantissa(S0.f64) - Decomposes S0 such that S0 = mantissa * (2 ^ exponent) with |mantissa| in [0.5, 1.0). - For normal inputs, the IEEE 754 11-bit biased exponent field [62:52] is replaced with 1022 - (0x3FE, representing 2^-1), preserving the original sign bit (bit 63) and 52-bit fraction (bits [51:0]). - Special values: - * +/-0.0: returns +/-0.0 (sign bit preserved). - * +/-INF: returns +/-INF unchanged. - * NaN: returns NaN unchanged (quiet / signaling payload bits preserved). - * Subnormals: normalized into [0.5, 1.0) with exponent set to 1022. - - 2. v_frexp_exp_i32_f64 dst, src0 (VOP1 e32 / VOP3 e64) - D.i32 = Exponent(S0.f64) - Extracts the unbiased integer base-2 exponent of S0, returned as a signed 32-bit integer. - For normal inputs, computes (biased_exponent - 1022). - Special values: - * +/-0.0: returns 0. - * +/-INF: returns 0. - * NaN: returns 0. - * Subnormals: returns -1022 - leading_zeros. - -Architecture: - - RDNA2 Vector ALU (GFX10) double-precision floating-point extraction. - - S0: 64-bit IEEE 754 binary64 operand (VGPR pair, SGPR pair, or literal / inline constant). - - D (mantissa): 64-bit IEEE 754 binary64 destination (VGPR pair). - - D (exponent): 32-bit signed integer destination (single VGPR). - - Modifiers: - * Input modifiers on S0: abs (|S0|), neg (-S0). - * Output modifiers on mantissa: clamp (clamps to [0.0, 1.0]), omod (mul:2, mul:4, div:2). -""" - -from fractions import Fraction -import math -import os -import re -import struct -import sys -import unittest -from dataclasses import dataclass -from enum import Enum, auto - -MASK32 = 0xFFFFFFFF -MASK64 = 0xFFFFFFFFFFFFFFFF - -SIGN_MASK_F64 = 0x8000000000000000 -EXP_MASK_F64 = 0x7FF0000000000000 -MANT_MASK_F64 = 0x000FFFFFFFFFFFFF -BIAS_F64 = 1023 -EXP_SHIFT_F64 = 52 - -EXP_FREXP_BIASED_F64 = 1022 # 2^-1 has biased exponent 1022 in IEEE 754 double precision -EXP_FREXP_BITS_F64 = EXP_FREXP_BIASED_F64 << EXP_SHIFT_F64 # 0x3FE0000000000000 (0.5) - -POS_ZERO_F64 = 0x0000000000000000 -NEG_ZERO_F64 = 0x8000000000000000 -POS_INF_F64 = 0x7FF0000000000000 -NEG_INF_F64 = 0xFFF0000000000000 -QNAN_F64 = 0x7FF8000000000000 -SNAN_F64 = 0x7FF0000000000001 - -ONE_F64 = 0x3FF0000000000000 # 1.0 -TWO_F64 = 0x4000000000000000 # 2.0 -HALF_F64 = 0x3FE0000000000000 # 0.5 -MAX_FINITE_F64 = 0x7FEFFFFFFFFFFFFF # ~1.7976931348623157e+308 -MIN_NORMAL_F64 = 0x0010000000000000 # 2^-1022 (~2.2250738585072014e-308) -MAX_SUBNORMAL_F64 = 0x000FFFFFFFFFFFFF -MIN_SUBNORMAL_F64 = 0x0000000000000001 # 2^-1074 (~4.9406564584124654e-324) - - -def u32(val: int) -> int: - """Normalize integer to unsigned 32-bit dword.""" - return val & MASK32 - - -def u64(val: int) -> int: - """Normalize integer to unsigned 64-bit qword.""" - return val & MASK64 - - -def s32(val: int) -> int: - """Interpret a 32-bit unsigned dword as a signed two's-complement integer.""" - val &= MASK32 - return val - (1 << 32) if (val & 0x80000000) else val - - -def s64(val: int) -> int: - """Interpret a 64-bit unsigned qword as a signed two's-complement integer.""" - val &= MASK64 - return val - (1 << 64) if (val & (1 << 63)) else val - - -def split_dwords(val64: int) -> tuple[int, int]: - """Split an unsigned 64-bit integer into (low_dword, high_dword).""" - val = val64 & MASK64 - return val & MASK32, (val >> 32) & MASK32 - - -def join_dwords(lo: int, hi: int) -> int: - """Join (low_dword, high_dword) into an unsigned 64-bit integer.""" - return ((hi & MASK32) << 32) | (lo & MASK32) - - -def bits_to_f64(bits: int) -> float: - """Unpack an unsigned 64-bit integer into an IEEE 754 double precision float.""" - return struct.unpack(" int: - """Pack an IEEE 754 double precision float into an unsigned 64-bit integer word.""" - if math.isnan(val): - return QNAN_F64 - try: - return struct.unpack(" bool: - """Check if binary64 bit pattern represents any NaN.""" - return ((bits & EXP_MASK_F64) == EXP_MASK_F64) and ((bits & MANT_MASK_F64) != 0) - - -def is_snan_f64(bits: int) -> bool: - """Check if binary64 bits represent a signaling NaN (quiet bit 51 is zero).""" - if not is_nan_f64(bits): - return False - return ((bits >> 51) & 1) == 0 - - -def is_inf_f64(bits: int) -> bool: - """Check if binary64 bit pattern represents +/- infinity.""" - return ((bits & EXP_MASK_F64) == EXP_MASK_F64) and ((bits & MANT_MASK_F64) == 0) - - -def is_zero_f64(bits: int) -> bool: - """Check if binary64 bit pattern represents +/- 0.0.""" - return (bits & ~SIGN_MASK_F64) == 0 - - -def is_subnormal_f64(bits: int) -> bool: - """Check if binary64 bit pattern represents a subnormal float.""" - return ((bits & EXP_MASK_F64) == 0) and ((bits & MANT_MASK_F64) != 0) - - -def is_normal_f64(bits: int) -> bool: - """Check if binary64 bit pattern represents a normalized finite float.""" - exp = (bits & EXP_MASK_F64) >> EXP_SHIFT_F64 - return 1 <= exp <= 2046 - - -@dataclass -class FPStatusFlags: - """IEEE 754 floating-point status exception flags.""" - invalid: bool = False - div_by_zero: bool = False - overflow: bool = False - underflow: bool = False - inexact: bool = False - - def merge(self, other: FPStatusFlags) -> None: - self.invalid |= other.invalid - self.div_by_zero |= other.div_by_zero - self.overflow |= other.overflow - self.underflow |= other.underflow - self.inexact |= other.inexact - - -def calc_frexp_f64_status_flags(src0_bits: int, opcode: str) -> FPStatusFlags: - """Determine IEEE 754 exception flags for v_frexp_mant_f64 / v_frexp_exp_i32_f64.""" - flags = FPStatusFlags() - # Signaling NaN generates invalid operation exception - if is_snan_f64(src0_bits): - flags.invalid = True - return flags - - -def ref_frexp_mant_f64( - src0_bits: int, - *, - clamp: bool = False, - abs_src0: bool = False, - neg_src0: bool = False, - omod: str = "none", -) -> int: - """Bit-accurate reference mathematical oracle for RDNA2 v_frexp_mant_f64. - - Extracts significand normalized into [0.5, 1.0) with original sign preserved. - """ - src0_bits &= MASK64 - if abs_src0: - src0_bits &= ~SIGN_MASK_F64 - if neg_src0: - src0_bits ^= SIGN_MASK_F64 - - sign = src0_bits & SIGN_MASK_F64 - exp_field = (src0_bits >> EXP_SHIFT_F64) & 0x7FF - mant_field = src0_bits & MANT_MASK_F64 - - # 1. NaN handling - if exp_field == 0x7FF and mant_field != 0: - if clamp: - return POS_ZERO_F64 - # Quiet signaling NaN if needed, preserve payload - return src0_bits | 0x0008000000000000 - - # 2. Infinity handling - if exp_field == 0x7FF and mant_field == 0: - if clamp: - return POS_ZERO_F64 if sign != 0 else ONE_F64 - return src0_bits - - # 3. Zero handling - if exp_field == 0 and mant_field == 0: - if clamp and sign != 0: - return POS_ZERO_F64 - return src0_bits - - # 4. Subnormal handling: normalized into [0.5, 1.0) - if exp_field == 0 and mant_field != 0: - lz = 52 - mant_field.bit_length() - norm_mant = (mant_field << (lz + 1)) & MANT_MASK_F64 - res_bits = sign | EXP_FREXP_BITS_F64 | norm_mant - else: - # 5. Normal float: replace exponent with 1022 (0x3FE) - res_bits = sign | EXP_FREXP_BITS_F64 | mant_field - - # Output modifiers - if omod != "none": - val = bits_to_f64(res_bits) - if omod == "mul:2": - val *= 2.0 - elif omod == "mul:4": - val *= 4.0 - elif omod == "div:2": - val *= 0.5 - res_bits = f64_to_bits(val) - - if clamp: - val = bits_to_f64(res_bits) - if math.isnan(val) or val < 0.0: - res_bits = POS_ZERO_F64 - elif val > 1.0: - res_bits = ONE_F64 - - return res_bits - - -def ref_frexp_exp_i32_f64( - src0_bits: int, - *, - abs_src0: bool = False, - neg_src0: bool = False, -) -> int: - """Bit-accurate reference mathematical oracle for RDNA2 v_frexp_exp_i32_f64. - - Extracts unbiased exponent as signed 32-bit two's-complement integer. - Special values (+/-0, +/-inf, NaN) return 0. - """ - src0_bits &= MASK64 - if abs_src0: - src0_bits &= ~SIGN_MASK_F64 - if neg_src0: - src0_bits ^= SIGN_MASK_F64 - - exp_field = (src0_bits >> EXP_SHIFT_F64) & 0x7FF - mant_field = src0_bits & MANT_MASK_F64 - - # Special values: NaN, Inf, Zero return 0 - if exp_field == 0x7FF or (exp_field == 0 and mant_field == 0): - return 0 - - # Subnormal - if exp_field == 0: - lz = 52 - mant_field.bit_length() - unbiased = -1022 - lz - return u32(unbiased) - - # Normal float: unbiased = exp_field - 1022 - unbiased = exp_field - 1022 - return u32(unbiased) - - -def ref_frexp_reconstruct_f64(src0_bits: int) -> float: - """Reconstruct S0 = mantissa * 2^exponent from frexp decomposition.""" - mant_bits = ref_frexp_mant_f64(src0_bits) - exp_i32 = s32(ref_frexp_exp_i32_f64(src0_bits)) - m = bits_to_f64(mant_bits) - return math.ldexp(m, exp_i32) - - -class DataType(Enum): - """Data types supported by RDNA2 VALU instructions.""" - F64 = auto() - I32 = auto() - U32 = auto() - U64 = auto() - - -class OperandKind(Enum): - """Classification of instruction operands.""" - VGPR_PAIR = auto() - VGPR_SINGLE = auto() - SGPR_PAIR = auto() - SGPR_SINGLE = auto() - LITERAL_I32 = auto() - LITERAL_F64 = auto() - INLINE_CONST = auto() - - -@dataclass -class Operand: - """Typed operand representation in symbolic AST.""" - kind: OperandKind - data_type: DataType - reg_index: int = 0 - literal_val: int = 0 - abs_mod: bool = False - neg_mod: bool = False - - def validate(self) -> None: - if self.kind in (OperandKind.VGPR_PAIR, OperandKind.VGPR_SINGLE): - limit = 255 if self.kind == OperandKind.VGPR_PAIR else 256 - if not (0 <= self.reg_index < limit): - raise ValueError(f"VGPR index {self.reg_index} out of valid range [0, {limit})") - elif self.kind in (OperandKind.SGPR_PAIR, OperandKind.SGPR_SINGLE): - limit = 105 if self.kind == OperandKind.SGPR_PAIR else 106 - if not (0 <= self.reg_index < limit): - raise ValueError(f"SGPR index {self.reg_index} out of valid range [0, {limit})") - - def to_asm(self) -> str: - s = "" - if self.kind == OperandKind.VGPR_PAIR: - s = f"v[{self.reg_index}:{self.reg_index + 1}]" - elif self.kind == OperandKind.VGPR_SINGLE: - s = f"v{self.reg_index}" - elif self.kind == OperandKind.SGPR_PAIR: - s = f"s[{self.reg_index}:{self.reg_index + 1}]" - elif self.kind == OperandKind.SGPR_SINGLE: - s = f"s{self.reg_index}" - elif self.kind == OperandKind.LITERAL_I32: - s = str(s32(self.literal_val)) - elif self.kind == OperandKind.LITERAL_F64: - s = f"{bits_to_f64(self.literal_val)}" - elif self.kind == OperandKind.INLINE_CONST: - s = str(self.literal_val) - - if self.abs_mod: - s = f"|{s}|" - if self.neg_mod: - s = f"-{s}" - return s - - -@dataclass -class InstructionAST: - """Symbolic AST node for v_frexp_mant_f64 and v_frexp_exp_i32_f64.""" - opcode: str - dst: Operand - src0: Operand - clamp: bool = False - omod: str = "none" - - def validate(self) -> None: - if self.opcode not in ("v_frexp_mant_f64", "v_frexp_exp_i32_f64"): - raise ValueError(f"Unsupported opcode {self.opcode}") - - if self.opcode == "v_frexp_mant_f64": - if self.dst.kind != OperandKind.VGPR_PAIR or self.dst.data_type != DataType.F64: - raise TypeError("v_frexp_mant_f64 destination must be a 64-bit VGPR pair (DataType.F64)") - elif self.opcode == "v_frexp_exp_i32_f64": - if self.dst.kind != OperandKind.VGPR_SINGLE or self.dst.data_type != DataType.I32: - raise TypeError("v_frexp_exp_i32_f64 destination must be a 32-bit single VGPR (DataType.I32)") - if self.clamp: - raise ValueError("v_frexp_exp_i32_f64 does not support clamp modifier") - if self.omod != "none": - raise ValueError("v_frexp_exp_i32_f64 does not support omod modifier") - - if self.dst.abs_mod or self.dst.neg_mod: - raise ValueError("Destination does not support input modifiers") - if self.src0.data_type != DataType.F64: - raise TypeError("src0 must be DataType.F64") - if self.omod not in ("none", "mul:2", "mul:4", "div:2"): - raise ValueError(f"Invalid omod modifier '{self.omod}'") - self.dst.validate() - self.src0.validate() - - def to_asm(self) -> str: - tokens = [f"{self.opcode} {self.dst.to_asm()}, {self.src0.to_asm()}"] - if self.clamp: - tokens.append("clamp") - if self.omod != "none": - tokens.append(self.omod) - return " ".join(tokens) - - -def parse_valu_frexp_f64(asm_line: str) -> InstructionAST: - """Parse assembly string for v_frexp_mant_f64 or v_frexp_exp_i32_f64 into InstructionAST.""" - line = asm_line.strip() - m_op = re.match(r"^(v_frexp_mant_f64|v_frexp_exp_i32_f64)(?:_e32|_e64)?\b", line) - if not m_op: - raise ValueError(f"Expected instruction starting with v_frexp_mant_f64 or v_frexp_exp_i32_f64, got: {line}") - - opcode = m_op.group(1) - remainder = line[m_op.end():].strip() - - tokens = remainder.split() - operands_tokens = [] - clamp = False - omod = "none" - - for tok in tokens: - if tok == "clamp": - clamp = True - elif tok in ("mul:2", "mul:4", "div:2"): - omod = tok - else: - operands_tokens.append(tok) - - op_str = " ".join(operands_tokens) - parts = [p.strip() for p in op_str.split(",") if p.strip()] - if len(parts) != 2: - raise ValueError(f"Expected 2 operands (dst, src0), got {len(parts)} in '{line}'") - - dst_str, src0_str = parts[0], parts[1] - - # Parse DST - m_vpair = re.match(r"^v\[(\d+):(\d+)\]$", dst_str) - m_vsingle = re.match(r"^v(\d+)$", dst_str) - - if opcode == "v_frexp_mant_f64": - if not m_vpair: - raise ValueError(f"v_frexp_mant_f64 destination must be VGPR pair v[lo:hi], got: {dst_str}") - lo, hi = int(m_vpair.group(1)), int(m_vpair.group(2)) - if hi != lo + 1: - raise ValueError(f"Destination register pair must be contiguous: {dst_str}") - dst_op = Operand(kind=OperandKind.VGPR_PAIR, data_type=DataType.F64, reg_index=lo) - else: # v_frexp_exp_i32_f64 - if m_vpair: - raise ValueError(f"v_frexp_exp_i32_f64 destination must be single VGPR, got pair: {dst_str}") - if not m_vsingle: - raise ValueError(f"v_frexp_exp_i32_f64 destination must be VGPR vN, got: {dst_str}") - dst_op = Operand(kind=OperandKind.VGPR_SINGLE, data_type=DataType.I32, reg_index=int(m_vsingle.group(1))) - - # Parse SRC0 - neg_s0 = False - abs_s0 = False - s0_clean = src0_str - if s0_clean.startswith("-"): - neg_s0 = True - s0_clean = s0_clean[1:].strip() - if s0_clean.startswith("|") and s0_clean.endswith("|"): - abs_s0 = True - s0_clean = s0_clean[1:-1].strip() - if s0_clean.startswith("-"): - neg_s0 = not neg_s0 - s0_clean = s0_clean[1:].strip() - - m_v0 = re.match(r"^v\[(\d+):(\d+)\]$", s0_clean) - m_s0 = re.match(r"^s\[(\d+):(\d+)\]$", s0_clean) - if m_v0: - lo, hi = int(m_v0.group(1)), int(m_v0.group(2)) - if hi != lo + 1: - raise ValueError(f"Source register pair must be contiguous: {src0_str}") - src0_op = Operand( - kind=OperandKind.VGPR_PAIR, - data_type=DataType.F64, - reg_index=lo, - abs_mod=abs_s0, - neg_mod=neg_s0, - ) - elif m_s0: - lo, hi = int(m_s0.group(1)), int(m_s0.group(2)) - if hi != lo + 1: - raise ValueError(f"Source register pair must be contiguous: {src0_str}") - src0_op = Operand( - kind=OperandKind.SGPR_PAIR, - data_type=DataType.F64, - reg_index=lo, - abs_mod=abs_s0, - neg_mod=neg_s0, - ) - else: - try: - if s0_clean.startswith("0x") or s0_clean.startswith("0X"): - val64 = int(s0_clean, 16) - else: - val64 = f64_to_bits(float(s0_clean)) - src0_op = Operand( - kind=OperandKind.LITERAL_F64, - data_type=DataType.F64, - literal_val=val64, - abs_mod=abs_s0, - neg_mod=neg_s0, - ) - except ValueError: - raise ValueError(f"Unrecognized src0 operand format: {src0_str}") - - ast = InstructionAST( - opcode=opcode, - dst=dst_op, - src0=src0_op, - clamp=clamp, - omod=omod, - ) - ast.validate() - return ast - - -class ScalarVALUInterpreter: - """Deterministic scalar instruction interpreter for RDNA2 VALU instructions.""" - - def __init__(self) -> None: - self.num_vgprs = 256 - self.num_sgprs = 106 - self.vgpr = [0] * self.num_vgprs - self.sgpr = [0] * self.num_sgprs - self.vcc = 0 - self.exec = MASK64 - self.status_flags = FPStatusFlags() - - def reset(self) -> None: - self.vgpr = [0] * self.num_vgprs - self.sgpr = [0] * self.num_sgprs - self.vcc = 0 - self.exec = MASK64 - self.status_flags = FPStatusFlags() - - def get_vgpr_u32(self, idx: int) -> int: - if not (0 <= idx < self.num_vgprs): - raise IndexError(f"VGPR index {idx} out of range [0, {self.num_vgprs})") - return self.vgpr[idx] & MASK32 - - def set_vgpr_u32(self, idx: int, val: int) -> None: - if not (0 <= idx < self.num_vgprs): - raise IndexError(f"VGPR index {idx} out of range [0, {self.num_vgprs})") - self.vgpr[idx] = val & MASK32 - - def get_vgpr_u64(self, idx: int) -> int: - if not (0 <= idx < self.num_vgprs - 1): - raise IndexError(f"64-bit VGPR base {idx} out of range [0, {self.num_vgprs - 1})") - lo = self.get_vgpr_u32(idx) - hi = self.get_vgpr_u32(idx + 1) - return join_dwords(lo, hi) - - def set_vgpr_u64(self, idx: int, val64: int) -> None: - if not (0 <= idx < self.num_vgprs - 1): - raise IndexError(f"64-bit VGPR base {idx} out of range [0, {self.num_vgprs - 1})") - lo, hi = split_dwords(val64) - self.set_vgpr_u32(idx, lo) - self.set_vgpr_u32(idx + 1, hi) - - def get_sgpr_u32(self, idx: int) -> int: - if not (0 <= idx < self.num_sgprs): - raise IndexError(f"SGPR index {idx} out of range [0, {self.num_sgprs})") - return self.sgpr[idx] & MASK32 - - def set_sgpr_u32(self, idx: int, val: int) -> None: - if not (0 <= idx < self.num_sgprs): - raise IndexError(f"SGPR index {idx} out of range [0, {self.num_sgprs})") - self.sgpr[idx] = val & MASK32 - - def get_sgpr_u64(self, idx: int) -> int: - if not (0 <= idx < self.num_sgprs - 1): - raise IndexError(f"64-bit SGPR base {idx} out of range [0, {self.num_sgprs - 1})") - lo = self.get_sgpr_u32(idx) - hi = self.get_sgpr_u32(idx + 1) - return join_dwords(lo, hi) - - def set_sgpr_u64(self, idx: int, val64: int) -> None: - if not (0 <= idx < self.num_sgprs - 1): - raise IndexError(f"64-bit SGPR base {idx} out of range [0, {self.num_sgprs - 1})") - lo, hi = split_dwords(val64) - self.set_sgpr_u32(idx, lo) - self.set_sgpr_u32(idx + 1, hi) - - def eval_operand_f64(self, op: Operand) -> int: - if op.data_type != DataType.F64: - raise TypeError(f"Expected DataType.F64, got {op.data_type}") - if op.kind == OperandKind.VGPR_PAIR: - val = self.get_vgpr_u64(op.reg_index) - elif op.kind == OperandKind.SGPR_PAIR: - val = self.get_sgpr_u64(op.reg_index) - elif op.kind == OperandKind.LITERAL_F64: - val = op.literal_val & MASK64 - else: - raise ValueError(f"Unsupported operand kind for f64: {op.kind}") - - if op.abs_mod: - val &= ~SIGN_MASK_F64 - if op.neg_mod: - val ^= SIGN_MASK_F64 - return val - - def execute(self, ast: InstructionAST) -> int: - ast.validate() - s0_val = self.eval_operand_f64(ast.src0) - - flags = calc_frexp_f64_status_flags(s0_val, ast.opcode) - self.status_flags.merge(flags) - - if ast.opcode == "v_frexp_mant_f64": - res = ref_frexp_mant_f64( - s0_val, - clamp=ast.clamp, - omod=ast.omod, - ) - self.set_vgpr_u64(ast.dst.reg_index, res) - return res - elif ast.opcode == "v_frexp_exp_i32_f64": - res = ref_frexp_exp_i32_f64(s0_val) - self.set_vgpr_u32(ast.dst.reg_index, res) - return res - - raise NotImplementedError(f"Opcode {ast.opcode} not implemented in scalar interpreter") - - def execute_asm(self, asm_line: str) -> int: - ast = parse_valu_frexp_f64(asm_line) - return self.execute(ast) - - -class SIMDVALUInterpreter: - """SIMD multi-lane execution model supporting Wave32 and Wave64 with EXEC masking.""" - - def __init__(self, wave_size: int = 64) -> None: - if wave_size not in (32, 64): - raise ValueError(f"Invalid wave_size: {wave_size}. Must be 32 or 64.") - self.wave_size = wave_size - self.num_vgprs = 256 - self.num_sgprs = 106 - self.vgpr = [[0] * self.wave_size for _ in range(self.num_vgprs)] - self.sgpr = [0] * self.num_sgprs - self.vcc = 0 - self.exec = (1 << self.wave_size) - 1 - self.status_flags = FPStatusFlags() - - def reset(self) -> None: - self.vgpr = [[0] * self.wave_size for _ in range(self.num_vgprs)] - self.sgpr = [0] * self.num_sgprs - self.vcc = 0 - self.exec = (1 << self.wave_size) - 1 - self.status_flags = FPStatusFlags() - - def get_vgpr_u32(self, reg: int, lane: int) -> int: - if not (0 <= reg < self.num_vgprs): - raise IndexError(f"VGPR index {reg} out of range [0, {self.num_vgprs})") - if not (0 <= lane < self.wave_size): - raise IndexError(f"Lane {lane} out of range [0, {self.wave_size})") - return self.vgpr[reg][lane] & MASK32 - - def set_vgpr_u32(self, reg: int, lane: int, val: int) -> None: - if not (0 <= reg < self.num_vgprs): - raise IndexError(f"VGPR index {reg} out of range [0, {self.num_vgprs})") - if not (0 <= lane < self.wave_size): - raise IndexError(f"Lane {lane} out of range [0, {self.wave_size})") - self.vgpr[reg][lane] = val & MASK32 - - def get_vgpr_u64(self, reg_base: int, lane: int) -> int: - if not (0 <= reg_base < self.num_vgprs - 1): - raise IndexError(f"64-bit VGPR base {reg_base} out of range [0, {self.num_vgprs - 1})") - lo = self.get_vgpr_u32(reg_base, lane) - hi = self.get_vgpr_u32(reg_base + 1, lane) - return join_dwords(lo, hi) - - def set_vgpr_u64(self, reg_base: int, lane: int, val64: int) -> None: - if not (0 <= reg_base < self.num_vgprs - 1): - raise IndexError(f"64-bit VGPR base {reg_base} out of range [0, {self.num_vgprs - 1})") - lo, hi = split_dwords(val64) - self.set_vgpr_u32(reg_base, lane, lo) - self.set_vgpr_u32(reg_base + 1, lane, hi) - - def get_sgpr_u32(self, reg: int) -> int: - if not (0 <= reg < self.num_sgprs): - raise IndexError(f"SGPR index {reg} out of range [0, {self.num_sgprs})") - return self.sgpr[reg] & MASK32 - - def set_sgpr_u32(self, reg: int, val: int) -> None: - if not (0 <= reg < self.num_sgprs): - raise IndexError(f"SGPR index {reg} out of range [0, {self.num_sgprs})") - self.sgpr[reg] = val & MASK32 - - def get_sgpr_u64(self, reg_base: int) -> int: - if not (0 <= reg_base < self.num_sgprs - 1): - raise IndexError(f"64-bit SGPR base {reg_base} out of range [0, {self.num_sgprs - 1})") - lo = self.get_sgpr_u32(reg_base) - hi = self.get_sgpr_u32(reg_base + 1) - return join_dwords(lo, hi) - - def set_sgpr_u64(self, reg_base: int, val64: int) -> None: - if not (0 <= reg_base < self.num_sgprs - 1): - raise IndexError(f"64-bit SGPR base {reg_base} out of range [0, {self.num_sgprs - 1})") - lo, hi = split_dwords(val64) - self.set_sgpr_u32(reg_base, lo) - self.set_sgpr_u32(reg_base + 1, hi) - - def eval_operand_f64_lane(self, op: Operand, lane: int) -> int: - if op.kind == OperandKind.VGPR_PAIR: - val = self.get_vgpr_u64(op.reg_index, lane) - elif op.kind == OperandKind.SGPR_PAIR: - val = self.get_sgpr_u64(op.reg_index) - elif op.kind == OperandKind.LITERAL_F64: - val = op.literal_val & MASK64 - else: - raise ValueError(f"Unsupported operand kind for f64: {op.kind}") - - if op.abs_mod: - val &= ~SIGN_MASK_F64 - if op.neg_mod: - val ^= SIGN_MASK_F64 - return val - - def execute(self, ast: InstructionAST) -> list[int]: - ast.validate() - results: list[int] = [] - - # Latch src0 across active lanes first - src0_latched: list[int] = [0] * self.wave_size - for lane in range(self.wave_size): - if (self.exec >> lane) & 1: - src0_latched[lane] = self.eval_operand_f64_lane(ast.src0, lane) - - for lane in range(self.wave_size): - if not ((self.exec >> lane) & 1): - # Inactive lane: preserve existing destination register contents - if ast.opcode == "v_frexp_mant_f64": - results.append(self.get_vgpr_u64(ast.dst.reg_index, lane)) - else: - results.append(self.get_vgpr_u32(ast.dst.reg_index, lane)) - continue - - s0_val = src0_latched[lane] - flags = calc_frexp_f64_status_flags(s0_val, ast.opcode) - self.status_flags.merge(flags) - - if ast.opcode == "v_frexp_mant_f64": - res = ref_frexp_mant_f64( - s0_val, - clamp=ast.clamp, - omod=ast.omod, - ) - self.set_vgpr_u64(ast.dst.reg_index, lane, res) - elif ast.opcode == "v_frexp_exp_i32_f64": - res = ref_frexp_exp_i32_f64(s0_val) - self.set_vgpr_u32(ast.dst.reg_index, lane, res) - else: - raise NotImplementedError(f"Opcode {ast.opcode} not implemented") - - results.append(res) - - return results - - def execute_asm(self, asm_line: str) -> list[int]: - ast = parse_valu_frexp_f64(asm_line) - return self.execute(ast) - - -# --- Mutated Oracles for Mutation Testing and Negative Controls --- - -def mutant_frexp_bias_off_by_one(src0: int) -> int: - """Mutant A: uses incorrect biased exponent 1021 instead of 1022 for 0.5f64.""" - mant_bits = ref_frexp_mant_f64(src0) - if is_normal_f64(mant_bits): - # Corrupt exponent field to 1021 - return (mant_bits & ~EXP_MASK_F64) | (1021 << EXP_SHIFT_F64) - return mant_bits - - -def mutant_frexp_flush_subnormal(src0: int) -> int: - """Mutant B: prematurely flushes subnormals to zero instead of normalizing.""" - if is_subnormal_f64(src0): - return src0 & SIGN_MASK_F64 - return ref_frexp_mant_f64(src0) - - -def mutant_frexp_no_clamp(src0: int) -> int: - """Mutant C: ignores clamp modifier on mantissa.""" - return ref_frexp_mant_f64(src0, clamp=False) - - -def mutant_frexp_exp_wrong_special(src0: int) -> int: - """Mutant D: returns non-zero for NaN/Infinity on exponent extraction.""" - if is_nan_f64(src0) or is_inf_f64(src0): - return 0x7FF - return ref_frexp_exp_i32_f64(src0) - - -def mutant_leak_vcc(interp: ScalarVALUInterpreter, ast: InstructionAST) -> None: - """Mutant E: improperly corrupts VCC register during VALU execution.""" - interp.execute(ast) - interp.vcc ^= 0x1 - - -def mutant_exec_leak(sim: SIMDVALUInterpreter, ast: InstructionAST) -> None: - """Mutant F: writes inactive lanes under EXEC mask.""" - sim.execute(ast) - # Overwrite lane 0 regardless of EXEC - if ast.opcode == "v_frexp_mant_f64": - sim.set_vgpr_u64(ast.dst.reg_index, 0, 0x1234567890ABCDEF) - else: - sim.set_vgpr_u32(ast.dst.reg_index, 0, 0x12345678) - - -class TestValuFrexpF64NegativeControlsAndMutations(unittest.TestCase): - """Negative controls, syntax rejection, and mutation detection for v_frexp_f64.""" - - def test_syntax_rejection_invalid_opcode(self): - with self.assertRaises(ValueError): - parse_valu_frexp_f64("v_add_f64 v[0:1], v[2:3]") - - def test_syntax_rejection_insufficient_operands(self): - with self.assertRaises(ValueError): - parse_valu_frexp_f64("v_frexp_mant_f64 v[0:1]") - - def test_syntax_rejection_non_contiguous_dst_mant(self): - with self.assertRaises(ValueError): - parse_valu_frexp_f64("v_frexp_mant_f64 v[0:2], v[2:3]") - - def test_syntax_rejection_non_contiguous_src0(self): - with self.assertRaises(ValueError): - parse_valu_frexp_f64("v_frexp_mant_f64 v[0:1], v[2:4]") - - def test_syntax_rejection_dst_type_mismatch_mant(self): - # Single VGPR not allowed for 64-bit mantissa - with self.assertRaises(ValueError): - parse_valu_frexp_f64("v_frexp_mant_f64 v0, v[2:3]") - - def test_syntax_rejection_dst_type_mismatch_exp(self): - # VGPR pair not allowed for 32-bit integer exponent - with self.assertRaises(ValueError): - parse_valu_frexp_f64("v_frexp_exp_i32_f64 v[0:1], v[2:3]") - - def test_syntax_rejection_out_of_range_registers(self): - with self.assertRaises(ValueError): - parse_valu_frexp_f64("v_frexp_mant_f64 v[255:256], v[2:3]") - with self.assertRaises(ValueError): - parse_valu_frexp_f64("v_frexp_mant_f64 v[0:1], s[105:106]") - - def test_syntax_rejection_invalid_modifier(self): - with self.assertRaises(ValueError): - ast = parse_valu_frexp_f64("v_frexp_mant_f64 v[0:1], v[2:3]") - ast.omod = "mul:3" - ast.validate() - - with self.assertRaises(ValueError): - parse_valu_frexp_f64("v_frexp_exp_i32_f64 v0, v[2:3] clamp") - - def test_mutation_detection_bias_off_by_one(self): - correct = ref_frexp_mant_f64(ONE_F64) - mutant = mutant_frexp_bias_off_by_one(ONE_F64) - self.assertEqual(bits_to_f64(correct), 0.5) - self.assertNotEqual(correct, mutant) - self.assertEqual((mutant >> EXP_SHIFT_F64) & 0x7FF, 1021) - - def test_mutation_detection_flush_subnormal(self): - correct = ref_frexp_mant_f64(MIN_SUBNORMAL_F64) - mutant = mutant_frexp_flush_subnormal(MIN_SUBNORMAL_F64) - self.assertEqual(bits_to_f64(correct), 0.5) - self.assertEqual(mutant, POS_ZERO_F64) - self.assertNotEqual(correct, mutant) - - def test_mutation_detection_no_clamp(self): - neg_val = f64_to_bits(-2.0) - correct_clamped = ref_frexp_mant_f64(neg_val, clamp=True) - mutant = mutant_frexp_no_clamp(neg_val) - self.assertEqual(correct_clamped, POS_ZERO_F64) - self.assertEqual(bits_to_f64(mutant), -0.5) - self.assertNotEqual(correct_clamped, mutant) - - def test_mutation_detection_exp_special_values(self): - correct = ref_frexp_exp_i32_f64(POS_INF_F64) - mutant = mutant_frexp_exp_wrong_special(POS_INF_F64) - self.assertEqual(correct, 0) - self.assertNotEqual(correct, mutant) - - def test_mutation_detection_corrupt_vcc(self): - interp = ScalarVALUInterpreter() - interp.vcc = 0x5555555555555555 - interp.set_vgpr_u64(2, ONE_F64) - ast = parse_valu_frexp_f64("v_frexp_mant_f64 v[0:1], v[2:3]") - interp.execute(ast) - self.assertEqual(interp.vcc, 0x5555555555555555) - - mutant_leak_vcc(interp, ast) - self.assertNotEqual(interp.vcc, 0x5555555555555555) - - def test_mutation_detection_exec_mask_leak(self): - sim = SIMDVALUInterpreter(wave_size=32) - sim.exec = 0x0 - sim.set_vgpr_u64(0, 0, 0xAAAAAAAAAAAAAAAA) - ast = parse_valu_frexp_f64("v_frexp_mant_f64 v[0:1], v[2:3]") - sim.execute(ast) - self.assertEqual(sim.get_vgpr_u64(0, 0), 0xAAAAAAAAAAAAAAAA) - - mutant_exec_leak(sim, ast) - self.assertNotEqual(sim.get_vgpr_u64(0, 0), 0xAAAAAAAAAAAAAAAA) - - -class TestValuFrexpF64IEEE754Boundaries(unittest.TestCase): - """Deep verification of IEEE 754 boundary extremes, subnormals, and NaN handling.""" - - def test_subnormal_normalization_boundaries(self): - # MIN_SUBNORMAL_F64 = 2^-1074 -> mantissa 0.5, exp -1073 - m_min = ref_frexp_mant_f64(MIN_SUBNORMAL_F64) - e_min = ref_frexp_exp_i32_f64(MIN_SUBNORMAL_F64) - self.assertEqual(bits_to_f64(m_min), 0.5) - self.assertEqual(s32(e_min), -1073) - - # MAX_SUBNORMAL_F64 = 2^-1022 - 2^-1074 -> exp -1022 - m_max = ref_frexp_mant_f64(MAX_SUBNORMAL_F64) - e_max = ref_frexp_exp_i32_f64(MAX_SUBNORMAL_F64) - self.assertEqual(s32(e_max), -1022) - # Fraction bits in mantissa should match MAX_SUBNORMAL shifted left by 1 - expected_mant = EXP_FREXP_BITS_F64 | ((MAX_SUBNORMAL_F64 << 1) & MANT_MASK_F64) - self.assertEqual(m_max, expected_mant) - - # Powers of 2 across subnormals - for p in range(52): - val_bits = 1 << p - m = ref_frexp_mant_f64(val_bits) - e = s32(ref_frexp_exp_i32_f64(val_bits)) - self.assertEqual(bits_to_f64(m), 0.5) - self.assertEqual(e, -1073 + p) - - def test_all_normal_exponent_boundaries(self): - # Test lower, middle, upper normal exponents - for exp in (1, 2, 1022, 1023, 1024, 2045, 2046): - word = exp << EXP_SHIFT_F64 - m = ref_frexp_mant_f64(word) - e = s32(ref_frexp_exp_i32_f64(word)) - self.assertEqual(bits_to_f64(m), 0.5) - self.assertEqual(e, exp - 1022) - - def test_walking_fraction_bits(self): - for bit_idx in range(52): - frac = 1 << bit_idx - word = (1023 << EXP_SHIFT_F64) | frac - m = ref_frexp_mant_f64(word) - e = s32(ref_frexp_exp_i32_f64(word)) - self.assertEqual(m & MANT_MASK_F64, frac) - self.assertEqual((m >> EXP_SHIFT_F64) & 0x7FF, 1022) - self.assertEqual(e, 1) - - def test_signed_zero_preservation(self): - self.assertEqual(ref_frexp_mant_f64(POS_ZERO_F64), POS_ZERO_F64) - self.assertEqual(ref_frexp_mant_f64(NEG_ZERO_F64), NEG_ZERO_F64) - self.assertEqual(ref_frexp_exp_i32_f64(POS_ZERO_F64), 0) - self.assertEqual(ref_frexp_exp_i32_f64(NEG_ZERO_F64), 0) - - def test_signed_infinity_preservation(self): - self.assertEqual(ref_frexp_mant_f64(POS_INF_F64), POS_INF_F64) - self.assertEqual(ref_frexp_mant_f64(NEG_INF_F64), NEG_INF_F64) - self.assertEqual(ref_frexp_exp_i32_f64(POS_INF_F64), 0) - self.assertEqual(ref_frexp_exp_i32_f64(NEG_INF_F64), 0) - - def test_nan_payloads_and_quieting(self): - # Quiet NaN payload preserved - qnan_payload = QNAN_F64 | 0x0000123456789ABC - m_qnan = ref_frexp_mant_f64(qnan_payload) - self.assertTrue(is_nan_f64(m_qnan)) - self.assertEqual(m_qnan & 0x0000123456789ABC, 0x0000123456789ABC) - self.assertEqual(ref_frexp_exp_i32_f64(qnan_payload), 0) - - # Signaling NaN quiet bit set - snan_payload = SNAN_F64 | 0x0000FEDCBA987654 - m_snan = ref_frexp_mant_f64(snan_payload) - self.assertTrue(is_nan_f64(m_snan)) - self.assertFalse(is_snan_f64(m_snan), "Signaling NaN must be quieted") - self.assertEqual(ref_frexp_exp_i32_f64(snan_payload), 0) - - def test_clamp_behavior_on_all_special_values(self): - # NaNs clamp to +0.0 - self.assertEqual(ref_frexp_mant_f64(QNAN_F64, clamp=True), POS_ZERO_F64) - self.assertEqual(ref_frexp_mant_f64(SNAN_F64, clamp=True), POS_ZERO_F64) - # +inf clamps to 1.0, -inf clamps to +0.0 - self.assertEqual(ref_frexp_mant_f64(POS_INF_F64, clamp=True), ONE_F64) - self.assertEqual(ref_frexp_mant_f64(NEG_INF_F64, clamp=True), POS_ZERO_F64) - # -0.0 clamps to +0.0 - self.assertEqual(ref_frexp_mant_f64(NEG_ZERO_F64, clamp=True), POS_ZERO_F64) - # Positive mantissas in [0.5, 1.0) remain unchanged - self.assertEqual(bits_to_f64(ref_frexp_mant_f64(ONE_F64, clamp=True)), 0.5) - # Negative mantissas clamp to +0.0 - self.assertEqual(ref_frexp_mant_f64(ONE_F64 | SIGN_MASK_F64, clamp=True), POS_ZERO_F64) - - def test_omod_interactions_with_clamp(self): - # 0.5 * mul:4 = 2.0 -> clamped to 1.0 - res_mul4 = ref_frexp_mant_f64(ONE_F64, clamp=True, omod="mul:4") - self.assertEqual(bits_to_f64(res_mul4), 1.0) - - # 0.5 * mul:2 = 1.0 -> within [0.0, 1.0] -> 1.0 - res_mul2 = ref_frexp_mant_f64(ONE_F64, clamp=True, omod="mul:2") - self.assertEqual(bits_to_f64(res_mul2), 1.0) - - # 0.75 * div:2 = 0.375 -> within [0.0, 1.0] -> 0.375 - f_1p5 = f64_to_bits(1.5) - res_div2 = ref_frexp_mant_f64(f_1p5, clamp=True, omod="div:2") - self.assertEqual(bits_to_f64(res_div2), 0.375) - - -class TestValuFrexpF64StatusFlags(unittest.TestCase): - """Unit tests for condition codes, status flags, and carry/borrow generation.""" - - def test_vcc_strictly_preserved_scalar(self): - interp = ScalarVALUInterpreter() - initial_vcc = 0x123456789ABCDEF0 - interp.vcc = initial_vcc - interp.set_vgpr_u64(2, f64_to_bits(1.0)) - - interp.execute_asm("v_frexp_mant_f64 v[0:1], v[2:3]") - self.assertEqual(interp.vcc, initial_vcc, "VCC must remain unmodified by v_frexp_mant_f64") - - interp.execute_asm("v_frexp_exp_i32_f64 v4, v[2:3]") - self.assertEqual(interp.vcc, initial_vcc, "VCC must remain unmodified by v_frexp_exp_i32_f64") - - def test_vcc_strictly_preserved_simd_wave64(self): - sim = SIMDVALUInterpreter(wave_size=64) - initial_vcc = 0xCAFEBABE0000FFFF - sim.vcc = initial_vcc - for lane in range(64): - sim.set_vgpr_u64(2, lane, f64_to_bits(2.0)) - - sim.execute_asm("v_frexp_mant_f64 v[0:1], v[2:3]") - self.assertEqual(sim.vcc, initial_vcc, "Wave64 VCC must remain untouched by mantissa") - - sim.execute_asm("v_frexp_exp_i32_f64 v4, v[2:3]") - self.assertEqual(sim.vcc, initial_vcc, "Wave64 VCC must remain untouched by exponent") - - def test_fp_flags_exact_normal_no_exceptions(self): - interp = ScalarVALUInterpreter() - interp.set_vgpr_u64(2, f64_to_bits(3.5)) - interp.execute_asm("v_frexp_mant_f64 v[0:1], v[2:3]") - interp.execute_asm("v_frexp_exp_i32_f64 v4, v[2:3]") - self.assertFalse(interp.status_flags.invalid) - self.assertFalse(interp.status_flags.overflow) - self.assertFalse(interp.status_flags.underflow) - self.assertFalse(interp.status_flags.inexact) - - def test_fp_flags_invalid_snan_mant(self): - interp = ScalarVALUInterpreter() - interp.set_vgpr_u64(2, SNAN_F64) - interp.execute_asm("v_frexp_mant_f64 v[0:1], v[2:3]") - self.assertTrue(interp.status_flags.invalid) - - def test_fp_flags_invalid_snan_exp(self): - interp = ScalarVALUInterpreter() - interp.set_vgpr_u64(2, SNAN_F64) - interp.execute_asm("v_frexp_exp_i32_f64 v0, v[2:3]") - self.assertTrue(interp.status_flags.invalid) - - def test_fp_flags_no_invalid_on_qnan(self): - interp = ScalarVALUInterpreter() - interp.set_vgpr_u64(2, QNAN_F64) - interp.execute_asm("v_frexp_mant_f64 v[0:1], v[2:3]") - interp.execute_asm("v_frexp_exp_i32_f64 v4, v[2:3]") - self.assertFalse(interp.status_flags.invalid) - - def test_fp_flags_subnormals_exact(self): - interp = ScalarVALUInterpreter() - interp.set_vgpr_u64(2, MIN_SUBNORMAL_F64) - interp.execute_asm("v_frexp_mant_f64 v[0:1], v[2:3]") - interp.execute_asm("v_frexp_exp_i32_f64 v4, v[2:3]") - # Frexp decomposition is exact; no underflow or overflow flags are raised - self.assertFalse(interp.status_flags.underflow) - self.assertFalse(interp.status_flags.overflow) - self.assertFalse(interp.status_flags.invalid) - - def test_fp_flags_infinities_and_zeros(self): - interp = ScalarVALUInterpreter() - for val in (POS_ZERO_F64, NEG_ZERO_F64, POS_INF_F64, NEG_INF_F64): - interp.reset() - interp.set_vgpr_u64(2, val) - interp.execute_asm("v_frexp_mant_f64 v[0:1], v[2:3]") - interp.execute_asm("v_frexp_exp_i32_f64 v4, v[2:3]") - self.assertFalse(interp.status_flags.invalid) - self.assertFalse(interp.status_flags.overflow) - self.assertFalse(interp.status_flags.underflow) - - -class TestValuFrexpF64RegisterAliasing(unittest.TestCase): - """Unit tests for register aliasing and in-place operand preservation.""" - - def test_full_aliasing_mant_dst_src0_scalar(self): - interp = ScalarVALUInterpreter() - initial_val = 6.0 # mantissa 0.75 - interp.set_vgpr_u64(0, f64_to_bits(initial_val)) - res = interp.execute_asm("v_frexp_mant_f64 v[0:1], v[0:1]") - self.assertEqual(bits_to_f64(res), 0.75) - self.assertEqual(bits_to_f64(interp.get_vgpr_u64(0)), 0.75) - - def test_aliasing_exp_dst_low_src0_scalar(self): - interp = ScalarVALUInterpreter() - # v0 = v_frexp_exp_i32_f64 v[0:1] (dst is low dword of src0) - interp.set_vgpr_u64(0, f64_to_bits(12.0)) # 12.0 = 0.75 * 2^4 -> exp = 4 - res = interp.execute_asm("v_frexp_exp_i32_f64 v0, v[0:1]") - self.assertEqual(s32(res), 4) - self.assertEqual(s32(interp.get_vgpr_u32(0)), 4) - - def test_aliasing_exp_dst_high_src0_scalar(self): - interp = ScalarVALUInterpreter() - # v1 = v_frexp_exp_i32_f64 v[0:1] (dst is high dword of src0) - interp.set_vgpr_u64(0, f64_to_bits(0.25)) # 0.25 = 0.5 * 2^-1 -> exp = -1 - res = interp.execute_asm("v_frexp_exp_i32_f64 v1, v[0:1]") - self.assertEqual(s32(res), -1) - self.assertEqual(s32(interp.get_vgpr_u32(1)), -1) - - def test_partial_overlap_dst_hi_src0_lo_scalar(self): - interp = ScalarVALUInterpreter() - # v[1:2] = v_frexp_mant_f64 v[0:1] - interp.set_vgpr_u64(0, f64_to_bits(10.0)) # 10.0 = 0.625 * 2^4 - res = interp.execute_asm("v_frexp_mant_f64 v[1:2], v[0:1]") - self.assertEqual(bits_to_f64(res), 0.625) - self.assertEqual(bits_to_f64(interp.get_vgpr_u64(1)), 0.625) - - def test_partial_overlap_dst_lo_src0_hi_scalar(self): - interp = ScalarVALUInterpreter() - # v[0:1] = v_frexp_mant_f64 v[1:2] - interp.set_vgpr_u64(1, f64_to_bits(0.125)) # 0.125 = 0.5 * 2^-2 - res = interp.execute_asm("v_frexp_mant_f64 v[0:1], v[1:2]") - self.assertEqual(bits_to_f64(res), 0.5) - self.assertEqual(bits_to_f64(interp.get_vgpr_u64(0)), 0.5) - - def test_simd_wave64_aliasing_with_exec_mask(self): - sim = SIMDVALUInterpreter(wave_size=64) - canary = 0xABABABABCDCDEFEF - for lane in range(64): - if lane % 2 == 0: - sim.set_vgpr_u64(0, lane, f64_to_bits(2.0)) - else: - sim.set_vgpr_u64(0, lane, canary) - - sim.exec = 0x5555555555555555 - results = sim.execute_asm("v_frexp_mant_f64 v[0:1], v[0:1]") - for lane in range(64): - if lane % 2 == 0: - self.assertEqual(bits_to_f64(results[lane]), 0.5) - self.assertEqual(bits_to_f64(sim.get_vgpr_u64(0, lane)), 0.5) - else: - self.assertEqual(results[lane], canary) - self.assertEqual(sim.get_vgpr_u64(0, lane), canary) - - def test_simd_wave32_partial_overlap_divergent(self): - sim = SIMDVALUInterpreter(wave_size=32) - expected: list[float] = [] - for lane in range(32): - val = (lane + 1) * 1.5 - sim.set_vgpr_u64(1, lane, f64_to_bits(val)) - py_m, _ = math.frexp(val) - expected.append(py_m) - - results = sim.execute_asm("v_frexp_mant_f64 v[0:1], v[1:2]") - for lane in range(32): - self.assertEqual(bits_to_f64(results[lane]), expected[lane]) - self.assertEqual(bits_to_f64(sim.get_vgpr_u64(0, lane)), expected[lane]) - - def test_simd_wave64_exp_aliasing_with_exec_mask(self): - sim = SIMDVALUInterpreter(wave_size=64) - canary = 0xCAFE1234 - for lane in range(64): - sim.set_vgpr_u64(0, lane, f64_to_bits(8.0)) # 8.0 = 0.5 * 2^4 -> exp = 4 - if lane % 2 != 0: - sim.set_vgpr_u32(0, lane, canary) - - sim.exec = 0x5555555555555555 - results = sim.execute_asm("v_frexp_exp_i32_f64 v0, v[0:1]") - for lane in range(64): - if lane % 2 == 0: - self.assertEqual(s32(results[lane]), 4) - self.assertEqual(s32(sim.get_vgpr_u32(0, lane)), 4) - else: - self.assertEqual(results[lane], canary) - self.assertEqual(sim.get_vgpr_u32(0, lane), canary) - - -class TestValuFrexpF64SIMDMultiLane(unittest.TestCase): - """Unit tests for SIMD multi-lane divergence and 32/64-bit EXEC masking.""" - - def test_wave32_uniform_execution(self): - sim = SIMDVALUInterpreter(wave_size=32) - base = f64_to_bits(6.0) - for lane in range(32): - sim.set_vgpr_u64(2, lane, base) - - results_m = sim.execute_asm("v_frexp_mant_f64 v[0:1], v[2:3]") - results_e = sim.execute_asm("v_frexp_exp_i32_f64 v4, v[2:3]") - self.assertEqual(len(results_m), 32) - self.assertEqual(len(results_e), 32) - for lane in range(32): - self.assertEqual(bits_to_f64(results_m[lane]), 0.75) - self.assertEqual(s32(results_e[lane]), 3) - - def test_wave64_uniform_execution(self): - sim = SIMDVALUInterpreter(wave_size=64) - base = f64_to_bits(0.125) - for lane in range(64): - sim.set_vgpr_u64(6, lane, base) - - results_m = sim.execute_asm("v_frexp_mant_f64 v[4:5], v[6:7]") - results_e = sim.execute_asm("v_frexp_exp_i32_f64 v8, v[6:7]") - self.assertEqual(len(results_m), 64) - for lane in range(64): - self.assertEqual(bits_to_f64(results_m[lane]), 0.5) - self.assertEqual(s32(results_e[lane]), -2) - - def test_wave32_divergent_lanes(self): - sim = SIMDVALUInterpreter(wave_size=32) - expected_m: list[float] = [] - expected_e: list[int] = [] - for lane in range(32): - val = float(lane + 1) * 0.75 - sim.set_vgpr_u64(0, lane, f64_to_bits(val)) - py_m, py_e = math.frexp(val) - expected_m.append(py_m) - expected_e.append(py_e) - - results_m = sim.execute_asm("v_frexp_mant_f64 v[4:5], v[0:1]") - results_e = sim.execute_asm("v_frexp_exp_i32_f64 v6, v[0:1]") - for lane in range(32): - self.assertEqual(bits_to_f64(results_m[lane]), expected_m[lane]) - self.assertEqual(s32(results_e[lane]), expected_e[lane]) - - def test_wave64_divergent_lanes(self): - sim = SIMDVALUInterpreter(wave_size=64) - expected_m: list[float] = [] - expected_e: list[int] = [] - for lane in range(64): - val = 0.375 * (lane + 1) - sim.set_vgpr_u64(2, lane, f64_to_bits(val)) - py_m, py_e = math.frexp(val) - expected_m.append(py_m) - expected_e.append(py_e) - - results_m = sim.execute_asm("v_frexp_mant_f64 v[0:1], v[2:3]") - results_e = sim.execute_asm("v_frexp_exp_i32_f64 v4, v[2:3]") - for lane in range(64): - self.assertEqual(bits_to_f64(results_m[lane]), expected_m[lane]) - self.assertEqual(s32(results_e[lane]), expected_e[lane]) - - def test_exec_mask_partial_inactivity_wave32(self): - sim = SIMDVALUInterpreter(wave_size=32) - canary64 = 0xDEADBEEFCAFEBABE - canary32 = 0x55AA55AA - for lane in range(32): - sim.set_vgpr_u64(0, lane, canary64) - sim.set_vgpr_u32(4, lane, canary32) - sim.set_vgpr_u64(2, lane, f64_to_bits(1.0)) - - # Only even lanes active: 0x55555555 - sim.exec = 0x55555555 - results_m = sim.execute_asm("v_frexp_mant_f64 v[0:1], v[2:3]") - results_e = sim.execute_asm("v_frexp_exp_i32_f64 v4, v[2:3]") - - for lane in range(32): - if lane % 2 == 0: - self.assertEqual(bits_to_f64(results_m[lane]), 0.5) - self.assertEqual(s32(results_e[lane]), 1) - self.assertEqual(bits_to_f64(sim.get_vgpr_u64(0, lane)), 0.5) - self.assertEqual(sim.get_vgpr_u32(4, lane), 1) - else: - self.assertEqual(results_m[lane], canary64) - self.assertEqual(results_e[lane], canary32) - self.assertEqual(sim.get_vgpr_u64(0, lane), canary64) - self.assertEqual(sim.get_vgpr_u32(4, lane), canary32) - - def test_exec_mask_partial_inactivity_wave64(self): - sim = SIMDVALUInterpreter(wave_size=64) - canary64 = 0x1122334455667788 - for lane in range(64): - sim.set_vgpr_u64(0, lane, canary64) - sim.set_vgpr_u64(2, lane, f64_to_bits(2.0)) - - # Low 32 lanes active, high 32 lanes inactive - sim.exec = 0x00000000FFFFFFFF - results_m = sim.execute_asm("v_frexp_mant_f64 v[0:1], v[2:3]") - - for lane in range(64): - if lane < 32: - self.assertEqual(bits_to_f64(results_m[lane]), 0.5) - else: - self.assertEqual(results_m[lane], canary64) - self.assertEqual(sim.get_vgpr_u64(0, lane), canary64) - - def test_exec_mask_all_inactive(self): - sim = SIMDVALUInterpreter(wave_size=64) - canary64 = 0xCAFEBABE12345678 - canary32 = 0x77777777 - for lane in range(64): - sim.set_vgpr_u64(0, lane, canary64) - sim.set_vgpr_u32(2, lane, canary32) - sim.set_vgpr_u64(4, lane, f64_to_bits(1.0)) - - sim.exec = 0x0 - results_m = sim.execute_asm("v_frexp_mant_f64 v[0:1], v[4:5]") - results_e = sim.execute_asm("v_frexp_exp_i32_f64 v2, v[4:5]") - for lane in range(64): - self.assertEqual(results_m[lane], canary64) - self.assertEqual(results_e[lane], canary32) - self.assertEqual(sim.get_vgpr_u64(0, lane), canary64) - self.assertEqual(sim.get_vgpr_u32(2, lane), canary32) - - -class TestValuFrexpF64ScalarInterpreter(unittest.TestCase): - """Unit tests for deterministic scalar instruction interpreter.""" - - def setUp(self): - self.interp = ScalarVALUInterpreter() - - def test_scalar_interpreter_mant_vgpr_sources(self): - # Set v[2:3] = 6.0 - self.interp.set_vgpr_u64(2, f64_to_bits(6.0)) - ast = parse_valu_frexp_f64("v_frexp_mant_f64 v[0:1], v[2:3]") - res = self.interp.execute(ast) - self.assertEqual(bits_to_f64(res), 0.75) - self.assertEqual(self.interp.get_vgpr_u64(0), res) - - def test_scalar_interpreter_exp_vgpr_sources(self): - # Set v[2:3] = 6.0 (6.0 = 0.75 * 2^3) - self.interp.set_vgpr_u64(2, f64_to_bits(6.0)) - ast = parse_valu_frexp_f64("v_frexp_exp_i32_f64 v0, v[2:3]") - res = self.interp.execute(ast) - self.assertEqual(s32(res), 3) - self.assertEqual(s32(self.interp.get_vgpr_u32(0)), 3) - - def test_scalar_interpreter_sgpr_sources(self): - # Set s[0:1] = 0.5 - self.interp.set_sgpr_u64(0, f64_to_bits(0.5)) - ast_m = parse_valu_frexp_f64("v_frexp_mant_f64 v[6:7], s[0:1]") - res_m = self.interp.execute(ast_m) - self.assertEqual(bits_to_f64(res_m), 0.5) - - ast_e = parse_valu_frexp_f64("v_frexp_exp_i32_f64 v8, s[0:1]") - res_e = self.interp.execute(ast_e) - self.assertEqual(s32(res_e), 0) - - def test_scalar_interpreter_literal_source(self): - ast_m = parse_valu_frexp_f64("v_frexp_mant_f64 v[2:3], 1.5") - res_m = self.interp.execute(ast_m) - self.assertEqual(bits_to_f64(res_m), 0.75) - - ast_e = parse_valu_frexp_f64("v_frexp_exp_i32_f64 v4, 1.5") - res_e = self.interp.execute(ast_e) - self.assertEqual(s32(res_e), 1) - - def test_scalar_interpreter_input_modifiers(self): - self.interp.set_vgpr_u64(2, f64_to_bits(4.0)) - # -|v[2:3]| -> mantissa = -0.5 - ast_m = parse_valu_frexp_f64("v_frexp_mant_f64 v[0:1], -|v[2:3]|") - res_m = self.interp.execute(ast_m) - self.assertEqual(bits_to_f64(res_m), -0.5) - - # exp of -|v[2:3]| is still 3 (4.0 = 0.5 * 2^3) - ast_e = parse_valu_frexp_f64("v_frexp_exp_i32_f64 v5, -|v[2:3]|") - res_e = self.interp.execute(ast_e) - self.assertEqual(s32(res_e), 3) - - def test_scalar_interpreter_output_modifiers_clamp_omod(self): - # 0.5 with mul:4 -> 2.0; with clamp -> 1.0 - self.interp.set_vgpr_u64(0, f64_to_bits(0.5)) - ast = parse_valu_frexp_f64("v_frexp_mant_f64 v[4:5], v[0:1] clamp mul:4") - res = self.interp.execute(ast) - self.assertEqual(bits_to_f64(res), 1.0) - - def test_scalar_interpreter_asm_execution(self): - self.interp.set_vgpr_u64(10, f64_to_bits(2.5)) - res_m = self.interp.execute_asm("v_frexp_mant_f64 v[0:1], v[10:11]") - res_e = self.interp.execute_asm("v_frexp_exp_i32_f64 v2, v[10:11]") - self.assertEqual(bits_to_f64(res_m), 0.625) - self.assertEqual(s32(res_e), 2) - - -class TestValuFrexpF64SymbolicAST(unittest.TestCase): - """Unit tests for symbolic AST opcode definitions and typed expressions.""" - - def test_ast_construction_and_validation(self): - dst_mant = Operand(OperandKind.VGPR_PAIR, DataType.F64, reg_index=0) - src0_mant = Operand(OperandKind.VGPR_PAIR, DataType.F64, reg_index=2) - ast_mant = InstructionAST("v_frexp_mant_f64", dst_mant, src0_mant, clamp=True, omod="mul:2") - ast_mant.validate() - self.assertEqual(ast_mant.to_asm(), "v_frexp_mant_f64 v[0:1], v[2:3] clamp mul:2") - - dst_exp = Operand(OperandKind.VGPR_SINGLE, DataType.I32, reg_index=5) - src0_exp = Operand(OperandKind.SGPR_PAIR, DataType.F64, reg_index=4) - ast_exp = InstructionAST("v_frexp_exp_i32_f64", dst_exp, src0_exp) - ast_exp.validate() - self.assertEqual(ast_exp.to_asm(), "v_frexp_exp_i32_f64 v5, s[4:5]") - - def test_parser_mant_f64_vgpr_sgpr_operands(self): - ast = parse_valu_frexp_f64("v_frexp_mant_f64 v[4:5], v[6:7]") - self.assertEqual(ast.dst.reg_index, 4) - self.assertEqual(ast.src0.kind, OperandKind.VGPR_PAIR) - self.assertEqual(ast.src0.reg_index, 6) - self.assertFalse(ast.clamp) - self.assertEqual(ast.omod, "none") - - ast_sgpr = parse_valu_frexp_f64("v_frexp_mant_f64_e32 v[0:1], s[2:3]") - self.assertEqual(ast_sgpr.src0.kind, OperandKind.SGPR_PAIR) - self.assertEqual(ast_sgpr.src0.reg_index, 2) - - def test_parser_exp_i32_f64_operands(self): - ast = parse_valu_frexp_f64("v_frexp_exp_i32_f64 v3, v[8:9]") - self.assertEqual(ast.dst.kind, OperandKind.VGPR_SINGLE) - self.assertEqual(ast.dst.reg_index, 3) - self.assertEqual(ast.src0.kind, OperandKind.VGPR_PAIR) - self.assertEqual(ast.src0.reg_index, 8) - - def test_parser_literal_and_constant_operands(self): - ast = parse_valu_frexp_f64("v_frexp_mant_f64 v[0:1], 1.5") - self.assertEqual(ast.src0.kind, OperandKind.LITERAL_F64) - self.assertEqual(bits_to_f64(ast.src0.literal_val), 1.5) - - ast_exp = parse_valu_frexp_f64("v_frexp_exp_i32_f64 v2, 2.0") - self.assertEqual(ast_exp.src0.kind, OperandKind.LITERAL_F64) - self.assertEqual(bits_to_f64(ast_exp.src0.literal_val), 2.0) - - def test_parser_modifiers_abs_neg_clamp_omod(self): - ast = parse_valu_frexp_f64("v_frexp_mant_f64_e64 v[0:1], -|v[2:3]| clamp mul:4") - self.assertTrue(ast.src0.abs_mod) - self.assertTrue(ast.src0.neg_mod) - self.assertTrue(ast.clamp) - self.assertEqual(ast.omod, "mul:4") - self.assertEqual(ast.to_asm(), "v_frexp_mant_f64 v[0:1], -|v[2:3]| clamp mul:4") - - def test_ast_type_checking_and_invariants(self): - # Invalid dst type for mantissa (must be VGPR_PAIR F64) - bad_dst_mant = Operand(OperandKind.VGPR_SINGLE, DataType.F64, reg_index=0) - src0 = Operand(OperandKind.VGPR_PAIR, DataType.F64, reg_index=2) - with self.assertRaises(TypeError): - InstructionAST("v_frexp_mant_f64", bad_dst_mant, src0).validate() - - # Invalid dst type for exponent (must be VGPR_SINGLE I32) - bad_dst_exp = Operand(OperandKind.VGPR_PAIR, DataType.I32, reg_index=0) - with self.assertRaises(TypeError): - InstructionAST("v_frexp_exp_i32_f64", bad_dst_exp, src0).validate() - - # Clamp not supported on v_frexp_exp_i32_f64 - good_dst_exp = Operand(OperandKind.VGPR_SINGLE, DataType.I32, reg_index=0) - with self.assertRaises(ValueError): - InstructionAST("v_frexp_exp_i32_f64", good_dst_exp, src0, clamp=True).validate() - - -class TestValuFrexpF64Oracle(unittest.TestCase): - """Unit tests for the reference mathematical oracle and architectural model.""" - - def test_oracle_normal_values(self): - # 1.0 -> mantissa = 0.5, exp = 1 - m1 = ref_frexp_mant_f64(ONE_F64) - e1 = ref_frexp_exp_i32_f64(ONE_F64) - self.assertEqual(bits_to_f64(m1), 0.5) - self.assertEqual(s32(e1), 1) - - # 2.0 -> mantissa = 0.5, exp = 2 - m2 = ref_frexp_mant_f64(TWO_F64) - e2 = ref_frexp_exp_i32_f64(TWO_F64) - self.assertEqual(bits_to_f64(m2), 0.5) - self.assertEqual(s32(e2), 2) - - # 0.5 -> mantissa = 0.5, exp = 0 - m05 = ref_frexp_mant_f64(HALF_F64) - e05 = ref_frexp_exp_i32_f64(HALF_F64) - self.assertEqual(bits_to_f64(m05), 0.5) - self.assertEqual(s32(e05), 0) - - # 1.5 -> mantissa = 0.75, exp = 1 - f_1p5 = f64_to_bits(1.5) - self.assertEqual(bits_to_f64(ref_frexp_mant_f64(f_1p5)), 0.75) - self.assertEqual(s32(ref_frexp_exp_i32_f64(f_1p5)), 1) - - # -4.0 -> mantissa = -0.5, exp = 3 - f_neg4 = f64_to_bits(-4.0) - self.assertEqual(bits_to_f64(ref_frexp_mant_f64(f_neg4)), -0.5) - self.assertEqual(s32(ref_frexp_exp_i32_f64(f_neg4)), 3) - - def test_oracle_powers_of_two(self): - for p in range(-50, 50): - val = math.ldexp(1.0, p) - val_bits = f64_to_bits(val) - m_bits = ref_frexp_mant_f64(val_bits) - e_bits = ref_frexp_exp_i32_f64(val_bits) - self.assertEqual(bits_to_f64(m_bits), 0.5) - self.assertEqual(s32(e_bits), p + 1) - - def test_oracle_cross_check_math_frexp(self): - test_floats = [0.125, 0.3333333333333333, 1.0, 2.5, 42.0, 1000.125, -7.5, -0.0625] - for f in test_floats: - f_bits = f64_to_bits(f) - oracle_m = bits_to_f64(ref_frexp_mant_f64(f_bits)) - oracle_e = s32(ref_frexp_exp_i32_f64(f_bits)) - py_m, py_e = math.frexp(f) - self.assertEqual(oracle_m, py_m) - self.assertEqual(oracle_e, py_e) - - def test_oracle_exact_reconstruction(self): - test_floats = [ - 1.5, 3.25, -0.75, 10.125, -12345.6789, 1.0e-100, 1.0e100, - bits_to_f64(MIN_NORMAL_F64), - bits_to_f64(MAX_SUBNORMAL_F64), - bits_to_f64(MIN_SUBNORMAL_F64), - ] - for f in test_floats: - f_bits = f64_to_bits(f) - reconstructed = ref_frexp_reconstruct_f64(f_bits) - self.assertEqual(reconstructed, f) - - def test_oracle_special_values(self): - # +0.0 and -0.0 - self.assertEqual(ref_frexp_mant_f64(POS_ZERO_F64), POS_ZERO_F64) - self.assertEqual(ref_frexp_mant_f64(NEG_ZERO_F64), NEG_ZERO_F64) - self.assertEqual(ref_frexp_exp_i32_f64(POS_ZERO_F64), 0) - self.assertEqual(ref_frexp_exp_i32_f64(NEG_ZERO_F64), 0) - - # +inf and -inf - self.assertEqual(ref_frexp_mant_f64(POS_INF_F64), POS_INF_F64) - self.assertEqual(ref_frexp_mant_f64(NEG_INF_F64), NEG_INF_F64) - self.assertEqual(ref_frexp_exp_i32_f64(POS_INF_F64), 0) - self.assertEqual(ref_frexp_exp_i32_f64(NEG_INF_F64), 0) - - # NaNs - res_qnan_m = ref_frexp_mant_f64(QNAN_F64) - self.assertTrue(is_nan_f64(res_qnan_m)) - self.assertEqual(ref_frexp_exp_i32_f64(QNAN_F64), 0) - - res_snan_m = ref_frexp_mant_f64(SNAN_F64) - self.assertTrue(is_nan_f64(res_snan_m)) - self.assertEqual(ref_frexp_exp_i32_f64(SNAN_F64), 0) - - def test_oracle_subnormal_normalization(self): - # Max subnormal - max_sub_m = ref_frexp_mant_f64(MAX_SUBNORMAL_F64) - max_sub_e = ref_frexp_exp_i32_f64(MAX_SUBNORMAL_F64) - py_m, py_e = math.frexp(bits_to_f64(MAX_SUBNORMAL_F64)) - self.assertEqual(bits_to_f64(max_sub_m), py_m) - self.assertEqual(s32(max_sub_e), py_e) - self.assertEqual(s32(max_sub_e), -1022) - - # Min subnormal - min_sub_m = ref_frexp_mant_f64(MIN_SUBNORMAL_F64) - min_sub_e = ref_frexp_exp_i32_f64(MIN_SUBNORMAL_F64) - py_min_m, py_min_e = math.frexp(bits_to_f64(MIN_SUBNORMAL_F64)) - self.assertEqual(bits_to_f64(min_sub_m), py_min_m) - self.assertEqual(s32(min_sub_e), py_min_e) - self.assertEqual(s32(min_sub_e), -1073) - - def test_oracle_modifiers(self): - f_neg2 = f64_to_bits(-2.0) - # abs modifier on mantissa - self.assertEqual(bits_to_f64(ref_frexp_mant_f64(f_neg2, abs_src0=True)), 0.5) - # neg modifier on positive mantissa - f_pos2 = f64_to_bits(2.0) - self.assertEqual(bits_to_f64(ref_frexp_mant_f64(f_pos2, neg_src0=True)), -0.5) - # abs and neg on exponent (no effect on magnitude/value) - self.assertEqual(s32(ref_frexp_exp_i32_f64(f_neg2, abs_src0=True)), 2) - self.assertEqual(s32(ref_frexp_exp_i32_f64(f_pos2, neg_src0=True)), 2) - - # clamp modifier on mantissa - # positive mantissa in [0.5, 1.0) is unchanged by clamp - self.assertEqual(bits_to_f64(ref_frexp_mant_f64(f_pos2, clamp=True)), 0.5) - # negative mantissa is clamped to +0.0 - self.assertEqual(ref_frexp_mant_f64(f_neg2, clamp=True), POS_ZERO_F64) - - # omod modifiers - # 0.5 * 2 = 1.0 - self.assertEqual(bits_to_f64(ref_frexp_mant_f64(ONE_F64, omod="mul:2")), 1.0) - # 0.5 * 4 = 2.0 - self.assertEqual(bits_to_f64(ref_frexp_mant_f64(ONE_F64, omod="mul:4")), 2.0) - # 0.5 / 2 = 0.25 - self.assertEqual(bits_to_f64(ref_frexp_mant_f64(ONE_F64, omod="div:2")), 0.25) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_valu_frexp_mant_f64.py b/tests/semantic/test_valu_frexp_mant_f64.py deleted file mode 100644 index 697618b96..000000000 --- a/tests/semantic/test_valu_frexp_mant_f64.py +++ /dev/null @@ -1,1239 +0,0 @@ -from __future__ import annotations - -"""Semantic interpreter tests and reference mathematical oracle for RDNA2 v_frexp_mant_f64. - -Instruction: - v_frexp_mant_f64 dst, src0 (VOP1 / VOP3) - D.f64 = mantissa(S0.f64) - -Architecture: - - RDNA2 Vector ALU (GFX10) double-precision mantissa extraction. - - S0: 64-bit IEEE 754 binary64 floating-point operand (VGPR pair, SGPR pair, or literal). - - D: 64-bit IEEE 754 binary64 floating-point destination (VGPR pair). - - Result: - * For finite non-zero S0: returns mantissa in [0.5, 1.0) with sign of S0. - * For +0.0 / -0.0: returns +0.0 / -0.0. - * For +inf / -inf: returns +inf / -inf. - * For NaN: returns quiet NaN (payload preserved/quieted). - * Subnormal inputs are normalized in IEEE preserve mode before extracting mantissa. - - Modifiers (VOP3): - * Input modifiers on S0: abs (|S0|), neg (-S0). - * Output modifiers: clamp (clamps result to [0.0, 1.0]), omod (mul:2, mul:4, div:2). -""" - -from fractions import Fraction -import math -import os -import re -import struct -import sys -import unittest -from dataclasses import dataclass -from enum import Enum, auto - -MASK32 = 0xFFFFFFFF -MASK64 = 0xFFFFFFFFFFFFFFFF - -SIGN_MASK_F64 = 0x8000000000000000 -EXP_MASK_F64 = 0x7FF0000000000000 -MANT_MASK_F64 = 0x000FFFFFFFFFFFFF -BIAS_F64 = 1023 -FREXP_EXP_F64 = 1022 # Biased exponent for range [0.5, 1.0) - -POS_ZERO_F64 = 0x0000000000000000 -NEG_ZERO_F64 = 0x8000000000000000 -POS_INF_F64 = 0x7FF0000000000000 -NEG_INF_F64 = 0xFFF0000000000000 -QNAN_F64 = 0x7FF8000000000000 -SNAN_F64 = 0x7FF0000000000001 - -ONE_F64 = 0x3FF0000000000000 # 1.0 -TWO_F64 = 0x4000000000000000 # 2.0 -HALF_F64 = 0x3FE0000000000000 # 0.5 -MAX_FINITE_F64 = 0x7FEFFFFFFFFFFFFF # ~1.7976931348623157e+308 -MIN_NORMAL_F64 = 0x0010000000000000 # 2^-1022 (~2.2250738585072014e-308) -MAX_SUBNORMAL_F64 = 0x000FFFFFFFFFFFFF -MIN_SUBNORMAL_F64 = 0x0000000000000001 # 2^-1074 (~4.9406564584124654e-324) - - -def u32(val: int) -> int: - """Normalize integer to unsigned 32-bit dword.""" - return val & MASK32 - - -def u64(val: int) -> int: - """Normalize integer to unsigned 64-bit qword.""" - return val & MASK64 - - -def s32(val: int) -> int: - """Interpret a 32-bit unsigned dword as a signed two's-complement integer.""" - val &= MASK32 - return val - (1 << 32) if (val & 0x80000000) else val - - -def s64(val: int) -> int: - """Interpret a 64-bit unsigned qword as a signed two's-complement integer.""" - val &= MASK64 - return val - (1 << 64) if (val & (1 << 63)) else val - - -def split_dwords(val64: int) -> tuple[int, int]: - """Split an unsigned 64-bit integer into (low_dword, high_dword).""" - val = val64 & MASK64 - return val & MASK32, (val >> 32) & MASK32 - - -def join_dwords(lo: int, hi: int) -> int: - """Join (low_dword, high_dword) into an unsigned 64-bit integer.""" - return ((hi & MASK32) << 32) | (lo & MASK32) - - -def bits_to_f64(bits: int) -> float: - """Unpack an unsigned 64-bit integer into an IEEE 754 double precision float.""" - return struct.unpack(" int: - """Pack an IEEE 754 double precision float into an unsigned 64-bit integer word.""" - if math.isnan(val): - return QNAN_F64 - try: - return struct.unpack(" bool: - """Check if binary64 bit pattern represents any NaN.""" - return ((bits & EXP_MASK_F64) == EXP_MASK_F64) and ((bits & MANT_MASK_F64) != 0) - - -def is_inf_f64(bits: int) -> bool: - """Check if binary64 bit pattern represents +/- infinity.""" - return ((bits & EXP_MASK_F64) == EXP_MASK_F64) and ((bits & MANT_MASK_F64) == 0) - - -def is_zero_f64(bits: int) -> bool: - """Check if binary64 bit pattern represents +/- 0.0.""" - return (bits & ~SIGN_MASK_F64) == 0 - - -def is_subnormal_f64(bits: int) -> bool: - """Check if binary64 bit pattern represents a subnormal float.""" - return ((bits & EXP_MASK_F64) == 0) and ((bits & MANT_MASK_F64) != 0) - - -def is_normal_f64(bits: int) -> bool: - """Check if binary64 bit pattern represents a normalized finite float.""" - exp = (bits & EXP_MASK_F64) >> 52 - return 1 <= exp <= 2046 - - -def ref_frexp_mant_f64( - src0_bits: int, - *, - clamp: bool = False, - abs_src0: bool = False, - neg_src0: bool = False, - omod: str = "none", -) -> int: - """Bit-accurate reference mathematical oracle for RDNA2 v_frexp_mant_f64. - - Extracts the normalized mantissa in [0.5, 1.0) with the sign of S0. - """ - src0_bits &= MASK64 - - if abs_src0: - src0_bits &= ~SIGN_MASK_F64 - if neg_src0: - src0_bits ^= SIGN_MASK_F64 - - sign = (src0_bits >> 63) & 1 - exp_field = (src0_bits >> 52) & 0x7FF - mant_field = src0_bits & MANT_MASK_F64 - - # 1. NaN handling - if exp_field == 0x7FF and mant_field != 0: - if clamp: - return POS_ZERO_F64 - return src0_bits | 0x0008000000000000 - - # 2. Infinity handling - if exp_field == 0x7FF and mant_field == 0: - if clamp: - return POS_ZERO_F64 if sign else ONE_F64 - return src0_bits - - # 3. Zero handling (+/- 0.0) - if exp_field == 0 and mant_field == 0: - if clamp and sign: - return POS_ZERO_F64 - return src0_bits - - # 4. Extract mantissa bits - if exp_field == 0: - # Subnormal input: normalize mantissa - F = mant_field - shift_left = 52 - (F.bit_length() - 1) - normalized_mant = (F << shift_left) & MANT_MASK_F64 - else: - # Normal input: directly use mantissa bits - normalized_mant = mant_field - - # Base exponent for [0.5, 1.0) is 1022 (unbiased -1) - target_exp = FREXP_EXP_F64 - - # Apply omod multiplier - if omod == "mul:2": - target_exp += 1 - elif omod == "mul:4": - target_exp += 2 - elif omod == "div:2": - target_exp -= 1 - - res = (sign << 63) | (target_exp << 52) | normalized_mant - - if clamp: - if sign: - return POS_ZERO_F64 - if res > ONE_F64: - return ONE_F64 - - return res - - -def ref_frexp_mant_f64_math(src0_bits: int) -> int: - """Cross-check using Python's math.frexp.""" - src0_bits &= MASK64 - if is_nan_f64(src0_bits): - return src0_bits | 0x0008000000000000 - if is_inf_f64(src0_bits) or is_zero_f64(src0_bits): - return src0_bits - - f = bits_to_f64(src0_bits) - m, _ = math.frexp(f) - return f64_to_bits(m) - - -def ref_frexp_mant_f64_fraction(src0_bits: int) -> int: - """Exact rational mathematical cross-check using fractions.Fraction.""" - src0_bits &= MASK64 - if is_nan_f64(src0_bits): - return src0_bits | 0x0008000000000000 - if is_inf_f64(src0_bits) or is_zero_f64(src0_bits): - return src0_bits - - sign = (src0_bits >> 63) & 1 - exp_field = (src0_bits >> 52) & 0x7FF - mant_field = src0_bits & MANT_MASK_F64 - - if exp_field == 0: - frac = Fraction(mant_field, 1 << 52) * (Fraction(2) ** -1022) - else: - frac = (Fraction(1) + Fraction(mant_field, 1 << 52)) * (Fraction(2) ** (exp_field - 1023)) - - frac_abs = abs(frac) - # Find power of two such that frac_abs * 2^p is in [0.5, 1.0) - p = 0 - while frac_abs >= 1: - frac_abs /= 2 - p -= 1 - while frac_abs < Fraction(1, 2): - frac_abs *= 2 - p += 1 - - res_float = float(frac_abs) if sign == 0 else -float(frac_abs) - return f64_to_bits(res_float) - - -class DataType(Enum): - """Data types supported by RDNA2 VALU instructions.""" - F64 = auto() - - -class OperandKind(Enum): - """Classification of instruction operands.""" - VGPR_PAIR = auto() - SGPR_PAIR = auto() - LITERAL_F64 = auto() - INLINE_CONST = auto() - - -@dataclass -class Operand: - """Typed operand representation in symbolic AST.""" - kind: OperandKind - data_type: DataType - reg_index: int = 0 - literal_val: int = 0 - abs_mod: bool = False - neg_mod: bool = False - - def validate(self) -> None: - if self.kind == OperandKind.VGPR_PAIR: - if not (0 <= self.reg_index < 255): - raise ValueError(f"VGPR pair base {self.reg_index} out of valid range [0, 255)") - elif self.kind == OperandKind.SGPR_PAIR: - if not (0 <= self.reg_index < 105): - raise ValueError(f"SGPR pair base {self.reg_index} out of valid range [0, 105)") - - def to_asm(self) -> str: - s = "" - if self.kind == OperandKind.VGPR_PAIR: - s = f"v[{self.reg_index}:{self.reg_index + 1}]" - elif self.kind == OperandKind.SGPR_PAIR: - s = f"s[{self.reg_index}:{self.reg_index + 1}]" - elif self.kind == OperandKind.LITERAL_F64: - s = f"{bits_to_f64(self.literal_val)}" - elif self.kind == OperandKind.INLINE_CONST: - s = str(self.literal_val) - - if self.abs_mod: - s = f"|{s}|" - if self.neg_mod: - s = f"-{s}" - return s - - -@dataclass -class InstructionAST: - """Symbolic AST node for v_frexp_mant_f64.""" - opcode: str - dst: Operand - src0: Operand - clamp: bool = False - omod: str = "none" - - def validate(self) -> None: - if self.opcode != "v_frexp_mant_f64": - raise ValueError(f"Unsupported opcode {self.opcode}") - if self.dst.kind != OperandKind.VGPR_PAIR or self.dst.data_type != DataType.F64: - raise TypeError("Destination must be a 64-bit VGPR pair (DataType.F64)") - if self.dst.abs_mod or self.dst.neg_mod: - raise ValueError("Destination does not support input modifiers") - if self.src0.data_type != DataType.F64: - raise TypeError("src0 must be DataType.F64") - if self.omod not in ("none", "mul:2", "mul:4", "div:2"): - raise ValueError(f"Invalid omod modifier '{self.omod}'") - self.dst.validate() - self.src0.validate() - - def to_asm(self) -> str: - tokens = [f"{self.opcode} {self.dst.to_asm()}, {self.src0.to_asm()}"] - if self.clamp: - tokens.append("clamp") - if self.omod != "none": - tokens.append(self.omod) - return " ".join(tokens) - - -def parse_vop_frexp_mant_f64(asm_line: str) -> InstructionAST: - """Parse assembly string into an InstructionAST.""" - line = asm_line.strip() - if not line.startswith("v_frexp_mant_f64"): - raise ValueError(f"Expected instruction starting with 'v_frexp_mant_f64', got: {line}") - - if ";" in line: - line = line.split(";", 1)[0].strip() - if "//" in line: - line = line.split("//", 1)[0].strip() - - parts = line.split(None, 1) - if len(parts) < 2: - raise ValueError(f"Incomplete instruction: {line}") - - opcode = parts[0] - rest = parts[1] - - tokens = [t.strip() for t in rest.split(",") if t.strip()] - if len(tokens) < 2: - raise ValueError(f"v_frexp_mant_f64 requires 2 operand sections, got: {len(tokens)}") - - dst_str = tokens[0] - last_section = tokens[1].split() - src0_str = last_section[0] - mod_tokens = [m.lower() for m in last_section[1:]] - - clamp = "clamp" in mod_tokens - omod = "none" - for m in mod_tokens: - if m in ("mul:2", "mul:4", "div:2"): - omod = m - - # Parse DST - m_dst = re.match(r"^v\[(\d+):(\d+)\]$", dst_str.strip()) - if not m_dst: - raise ValueError(f"Invalid 64-bit VGPR destination format: {dst_str}") - d_lo, d_hi = int(m_dst.group(1)), int(m_dst.group(2)) - if d_hi != d_lo + 1: - raise ValueError(f"Destination register pair must be contiguous: {dst_str}") - dst_op = Operand(kind=OperandKind.VGPR_PAIR, data_type=DataType.F64, reg_index=d_lo) - - # Parse SRC0 - s0_str = src0_str.strip() - neg_s0 = False - abs_s0 = False - if s0_str.startswith("-"): - neg_s0 = True - s0_str = s0_str[1:].strip() - if s0_str.startswith("|") and s0_str.endswith("|"): - abs_s0 = True - s0_str = s0_str[1:-1].strip() - - m_v0 = re.match(r"^v\[(\d+):(\d+)\]$", s0_str) - m_s0 = re.match(r"^s\[(\d+):(\d+)\]$", s0_str) - if m_v0: - lo, hi = int(m_v0.group(1)), int(m_v0.group(2)) - if hi != lo + 1: - raise ValueError(f"Source register pair must be contiguous: {s0_str}") - src0_op = Operand( - kind=OperandKind.VGPR_PAIR, - data_type=DataType.F64, - reg_index=lo, - abs_mod=abs_s0, - neg_mod=neg_s0, - ) - elif m_s0: - lo, hi = int(m_s0.group(1)), int(m_s0.group(2)) - if hi != lo + 1: - raise ValueError(f"Source register pair must be contiguous: {s0_str}") - src0_op = Operand( - kind=OperandKind.SGPR_PAIR, - data_type=DataType.F64, - reg_index=lo, - abs_mod=abs_s0, - neg_mod=neg_s0, - ) - else: - try: - if s0_str.startswith("0x") or s0_str.startswith("0X"): - val64 = int(s0_str, 16) - else: - val64 = f64_to_bits(float(s0_str)) - src0_op = Operand( - kind=OperandKind.LITERAL_F64, - data_type=DataType.F64, - literal_val=val64, - abs_mod=abs_s0, - neg_mod=neg_s0, - ) - except ValueError: - raise ValueError(f"Unrecognized src0 operand format: {s0_str}") - - ast = InstructionAST( - opcode=opcode, - dst=dst_op, - src0=src0_op, - clamp=clamp, - omod=omod, - ) - ast.validate() - return ast - - -@dataclass -class FPStatusFlags: - """IEEE 754 floating-point status exception flags.""" - invalid: bool = False - div_by_zero: bool = False - overflow: bool = False - underflow: bool = False - inexact: bool = False - - def merge(self, other: FPStatusFlags) -> None: - self.invalid |= other.invalid - self.div_by_zero |= other.div_by_zero - self.overflow |= other.overflow - self.underflow |= other.underflow - self.inexact |= other.inexact - - -def is_snan_f64(bits: int) -> bool: - """Check if binary64 bits represent a signaling NaN.""" - if not is_nan_f64(bits): - return False - return ((bits >> 51) & 1) == 0 - - -def calc_frexp_mant_f64_status_flags(src0_bits: int, res_bits: int) -> FPStatusFlags: - """Determine IEEE 754 exception flags for v_frexp_mant_f64.""" - flags = FPStatusFlags() - if is_snan_f64(src0_bits): - flags.invalid = True - return flags - - -class ScalarVALUInterpreter: - """Deterministic scalar instruction interpreter for RDNA2 VALU instructions.""" - - def __init__(self) -> None: - self.num_vgprs = 256 - self.num_sgprs = 106 - self.vgpr = [0] * self.num_vgprs - self.sgpr = [0] * self.num_sgprs - self.vcc = 0 - self.exec = MASK64 - self.status_flags = FPStatusFlags() - - def reset(self) -> None: - self.vgpr = [0] * self.num_vgprs - self.sgpr = [0] * self.num_sgprs - self.vcc = 0 - self.exec = MASK64 - self.status_flags = FPStatusFlags() - - def get_vgpr_u32(self, idx: int) -> int: - if not (0 <= idx < self.num_vgprs): - raise IndexError(f"VGPR index {idx} out of range [0, {self.num_vgprs})") - return self.vgpr[idx] & MASK32 - - def set_vgpr_u32(self, idx: int, val: int) -> None: - if not (0 <= idx < self.num_vgprs): - raise IndexError(f"VGPR index {idx} out of range [0, {self.num_vgprs})") - self.vgpr[idx] = val & MASK32 - - def get_vgpr_u64(self, idx: int) -> int: - if not (0 <= idx < self.num_vgprs - 1): - raise IndexError(f"64-bit VGPR base {idx} out of range [0, {self.num_vgprs - 1})") - lo = self.get_vgpr_u32(idx) - hi = self.get_vgpr_u32(idx + 1) - return join_dwords(lo, hi) - - def set_vgpr_u64(self, idx: int, val64: int) -> None: - if not (0 <= idx < self.num_vgprs - 1): - raise IndexError(f"64-bit VGPR base {idx} out of range [0, {self.num_vgprs - 1})") - lo, hi = split_dwords(val64) - self.set_vgpr_u32(idx, lo) - self.set_vgpr_u32(idx + 1, hi) - - def get_sgpr_u32(self, idx: int) -> int: - if not (0 <= idx < self.num_sgprs): - raise IndexError(f"SGPR index {idx} out of range [0, {self.num_sgprs})") - return self.sgpr[idx] & MASK32 - - def set_sgpr_u32(self, idx: int, val: int) -> None: - if not (0 <= idx < self.num_sgprs): - raise IndexError(f"SGPR index {idx} out of range [0, {self.num_sgprs})") - self.sgpr[idx] = val & MASK32 - - def get_sgpr_u64(self, idx: int) -> int: - if not (0 <= idx < self.num_sgprs - 1): - raise IndexError(f"64-bit SGPR base {idx} out of range [0, {self.num_sgprs - 1})") - lo = self.get_sgpr_u32(idx) - hi = self.get_sgpr_u32(idx + 1) - return join_dwords(lo, hi) - - def set_sgpr_u64(self, idx: int, val64: int) -> None: - if not (0 <= idx < self.num_sgprs - 1): - raise IndexError(f"64-bit SGPR base {idx} out of range [0, {self.num_sgprs - 1})") - lo, hi = split_dwords(val64) - self.set_sgpr_u32(idx, lo) - self.set_sgpr_u32(idx + 1, hi) - - def eval_operand_f64(self, op: Operand) -> int: - if op.data_type != DataType.F64: - raise TypeError(f"Expected DataType.F64, got {op.data_type}") - if op.kind == OperandKind.VGPR_PAIR: - val = self.get_vgpr_u64(op.reg_index) - elif op.kind == OperandKind.SGPR_PAIR: - val = self.get_sgpr_u64(op.reg_index) - elif op.kind == OperandKind.LITERAL_F64: - val = op.literal_val & MASK64 - else: - raise ValueError(f"Unsupported operand kind for f64: {op.kind}") - - if op.abs_mod: - val &= ~SIGN_MASK_F64 - if op.neg_mod: - val ^= SIGN_MASK_F64 - return val - - def execute(self, ast: InstructionAST) -> int: - ast.validate() - if ast.opcode == "v_frexp_mant_f64": - s0_val = self.eval_operand_f64(ast.src0) - res = ref_frexp_mant_f64( - s0_val, - clamp=ast.clamp, - omod=ast.omod, - ) - flags = calc_frexp_mant_f64_status_flags(s0_val, res) - self.status_flags.merge(flags) - self.set_vgpr_u64(ast.dst.reg_index, res) - return res - raise NotImplementedError(f"Opcode {ast.opcode} not implemented in scalar interpreter") - - def execute_asm(self, asm_line: str) -> int: - ast = parse_vop_frexp_mant_f64(asm_line) - return self.execute(ast) - - -class SIMDVALUInterpreter: - """SIMD multi-lane execution model supporting Wave32 and Wave64 with EXEC masking.""" - - def __init__(self, wave_size: int = 64) -> None: - if wave_size not in (32, 64): - raise ValueError(f"Invalid wave_size: {wave_size}. Must be 32 or 64.") - self.wave_size = wave_size - self.num_vgprs = 256 - self.num_sgprs = 106 - self.vgpr = [[0] * self.wave_size for _ in range(self.num_vgprs)] - self.sgpr = [0] * self.num_sgprs - self.vcc = 0 - self.exec = (1 << self.wave_size) - 1 - self.status_flags = FPStatusFlags() - - def reset(self) -> None: - self.vgpr = [[0] * self.wave_size for _ in range(self.num_vgprs)] - self.sgpr = [0] * self.num_sgprs - self.vcc = 0 - self.exec = (1 << self.wave_size) - 1 - self.status_flags = FPStatusFlags() - - def get_vgpr_u32(self, reg: int, lane: int) -> int: - if not (0 <= reg < self.num_vgprs): - raise IndexError(f"VGPR index {reg} out of range [0, {self.num_vgprs})") - if not (0 <= lane < self.wave_size): - raise IndexError(f"Lane {lane} out of range [0, {self.wave_size})") - return self.vgpr[reg][lane] & MASK32 - - def set_vgpr_u32(self, reg: int, lane: int, val: int) -> None: - if not (0 <= reg < self.num_vgprs): - raise IndexError(f"VGPR index {reg} out of range [0, {self.num_vgprs})") - if not (0 <= lane < self.wave_size): - raise IndexError(f"Lane {lane} out of range [0, {self.wave_size})") - self.vgpr[reg][lane] = val & MASK32 - - def get_vgpr_u64(self, reg_base: int, lane: int) -> int: - if not (0 <= reg_base < self.num_vgprs - 1): - raise IndexError(f"64-bit VGPR base {reg_base} out of range [0, {self.num_vgprs - 1})") - lo = self.get_vgpr_u32(reg_base, lane) - hi = self.get_vgpr_u32(reg_base + 1, lane) - return join_dwords(lo, hi) - - def set_vgpr_u64(self, reg_base: int, lane: int, val64: int) -> None: - if not (0 <= reg_base < self.num_vgprs - 1): - raise IndexError(f"64-bit VGPR base {reg_base} out of range [0, {self.num_vgprs - 1})") - lo, hi = split_dwords(val64) - self.set_vgpr_u32(reg_base, lane, lo) - self.set_vgpr_u32(reg_base + 1, lane, hi) - - def get_sgpr_u32(self, reg: int) -> int: - if not (0 <= reg < self.num_sgprs): - raise IndexError(f"SGPR index {reg} out of range [0, {self.num_sgprs})") - return self.sgpr[reg] & MASK32 - - def set_sgpr_u32(self, reg: int, val: int) -> None: - if not (0 <= reg < self.num_sgprs): - raise IndexError(f"SGPR index {reg} out of range [0, {self.num_sgprs})") - self.sgpr[reg] = val & MASK32 - - def get_sgpr_u64(self, reg_base: int) -> int: - if not (0 <= reg_base < self.num_sgprs - 1): - raise IndexError(f"64-bit SGPR base {reg_base} out of range [0, {self.num_sgprs - 1})") - lo = self.get_sgpr_u32(reg_base) - hi = self.get_sgpr_u32(reg_base + 1) - return join_dwords(lo, hi) - - def set_sgpr_u64(self, reg_base: int, val64: int) -> None: - if not (0 <= reg_base < self.num_sgprs - 1): - raise IndexError(f"64-bit SGPR base {reg_base} out of range [0, {self.num_sgprs - 1})") - lo, hi = split_dwords(val64) - self.set_sgpr_u32(reg_base, lo) - self.set_sgpr_u32(reg_base + 1, hi) - - def eval_operand_f64_lane(self, op: Operand, lane: int) -> int: - if op.kind == OperandKind.VGPR_PAIR: - val = self.get_vgpr_u64(op.reg_index, lane) - elif op.kind == OperandKind.SGPR_PAIR: - val = self.get_sgpr_u64(op.reg_index) - elif op.kind == OperandKind.LITERAL_F64: - val = op.literal_val & MASK64 - else: - raise ValueError(f"Unsupported operand kind for f64: {op.kind}") - - if op.abs_mod: - val &= ~SIGN_MASK_F64 - if op.neg_mod: - val ^= SIGN_MASK_F64 - return val - - def execute(self, ast: InstructionAST) -> list[int]: - ast.validate() - results: list[int] = [] - effective_exec = self.exec & ((1 << self.wave_size) - 1) - - src0_latched = [0] * self.wave_size - for lane in range(self.wave_size): - if (effective_exec >> lane) & 1: - src0_latched[lane] = self.eval_operand_f64_lane(ast.src0, lane) - - for lane in range(self.wave_size): - if not ((effective_exec >> lane) & 1): - results.append(self.get_vgpr_u64(ast.dst.reg_index, lane)) - continue - - res = ref_frexp_mant_f64( - src0_latched[lane], - clamp=ast.clamp, - omod=ast.omod, - ) - flags = calc_frexp_mant_f64_status_flags(src0_latched[lane], res) - self.status_flags.merge(flags) - self.set_vgpr_u64(ast.dst.reg_index, lane, res) - results.append(res) - - return results - - def execute_asm(self, asm_line: str) -> list[int]: - ast = parse_vop_frexp_mant_f64(asm_line) - return self.execute(ast) - - -# --- Mutated Oracles for Mutation Testing and Negative Controls --- - -def mutant_exponent_off_by_one(src0: int) -> int: - """Mutant A: uses biased exponent 1023 ([1.0, 2.0)) instead of 1022 ([0.5, 1.0)).""" - res = ref_frexp_mant_f64(src0) - if is_zero_f64(res) or is_nan_f64(res) or is_inf_f64(res): - return res - # Force exponent 1023 - sign = res & SIGN_MASK_F64 - mant = res & MANT_MASK_F64 - return sign | (1023 << 52) | mant - - -def mutant_no_subnormal_normalization(src0: int) -> int: - """Mutant B: skips normalization of subnormal mantissa.""" - src0 &= MASK64 - exp_field = (src0 >> 52) & 0x7FF - if exp_field == 0 and (src0 & MANT_MASK_F64) != 0: - # Erroneously uses raw mantissa without shifting - return (src0 & SIGN_MASK_F64) | (FREXP_EXP_F64 << 52) | (src0 & MANT_MASK_F64) - return ref_frexp_mant_f64(src0) - - -def mutant_no_clamp(src0: int) -> int: - """Mutant C: ignores clamp modifier.""" - return ref_frexp_mant_f64(src0, clamp=False) - - -def mutant_leak_vcc(interp: ScalarVALUInterpreter, ast: InstructionAST) -> None: - """Mutant D: corrupts VCC register during VALU FP execution.""" - interp.execute(ast) - interp.vcc ^= 0x1 - - -def mutant_exec_leak(sim: SIMDVALUInterpreter, ast: InstructionAST) -> None: - """Mutant E: writes inactive lanes under EXEC mask.""" - sim.execute(ast) - sim.set_vgpr_u64(ast.dst.reg_index, 0, 0x1234567890ABCDEF) - - -class TestValuFrexpMantF64NegativeControlsAndMutations(unittest.TestCase): - """Negative controls, syntax rejection, and mutation detection for v_frexp_mant_f64.""" - - def test_syntax_rejection_invalid_opcode(self): - with self.assertRaises(ValueError): - parse_vop_frexp_mant_f64("v_add_f64 v[0:1], v[2:3]") - - def test_syntax_rejection_insufficient_operands(self): - with self.assertRaises(ValueError): - parse_vop_frexp_mant_f64("v_frexp_mant_f64 v[0:1]") - - def test_syntax_rejection_non_contiguous_dst(self): - with self.assertRaises(ValueError): - parse_vop_frexp_mant_f64("v_frexp_mant_f64 v[0:2], v[2:3]") - - def test_syntax_rejection_non_contiguous_src0(self): - with self.assertRaises(ValueError): - parse_vop_frexp_mant_f64("v_frexp_mant_f64 v[0:1], v[2:4]") - - def test_syntax_rejection_out_of_range_registers(self): - with self.assertRaises(ValueError): - parse_vop_frexp_mant_f64("v_frexp_mant_f64 v[255:256], v[2:3]") - with self.assertRaises(ValueError): - parse_vop_frexp_mant_f64("v_frexp_mant_f64 v[0:1], s[105:106]") - - def test_syntax_rejection_invalid_modifier(self): - with self.assertRaises(ValueError): - ast = parse_vop_frexp_mant_f64("v_frexp_mant_f64 v[0:1], v[2:3]") - ast.omod = "mul:3" - ast.validate() - - def test_syntax_rejection_invalid_types(self): - with self.assertRaises(ValueError): - parse_vop_frexp_mant_f64("v_frexp_mant_f64 v0, v[2:3]") - with self.assertRaises(ValueError): - parse_vop_frexp_mant_f64("v_frexp_mant_f64 v[0:1], v2") - - def test_mutation_detection_exponent_off_by_one(self): - correct = ref_frexp_mant_f64(ONE_F64) - mutant = mutant_exponent_off_by_one(ONE_F64) - self.assertEqual(bits_to_f64(correct), 0.5) - self.assertEqual(bits_to_f64(mutant), 1.0) - self.assertNotEqual(correct, mutant) - - def test_mutation_detection_no_subnormal_normalization(self): - correct = ref_frexp_mant_f64(MIN_SUBNORMAL_F64) - mutant = mutant_no_subnormal_normalization(MIN_SUBNORMAL_F64) - self.assertEqual(bits_to_f64(correct), 0.5) - self.assertNotEqual(correct, mutant) - - def test_mutation_detection_no_clamp(self): - val = f64_to_bits(-2.0) - correct_clamped = ref_frexp_mant_f64(val, clamp=True) - mutant = mutant_no_clamp(val) - self.assertEqual(bits_to_f64(correct_clamped), 0.0) - self.assertEqual(bits_to_f64(mutant), -0.5) - self.assertNotEqual(correct_clamped, mutant) - - def test_mutation_detection_corrupt_vcc(self): - interp = ScalarVALUInterpreter() - interp.vcc = 0x5555555555555555 - interp.set_vgpr_u64(2, ONE_F64) - ast = parse_vop_frexp_mant_f64("v_frexp_mant_f64 v[0:1], v[2:3]") - interp.execute(ast) - self.assertEqual(interp.vcc, 0x5555555555555555) - mutant_leak_vcc(interp, ast) - self.assertNotEqual(interp.vcc, 0x5555555555555555) - - def test_mutation_detection_exec_mask_leak(self): - sim = SIMDVALUInterpreter(wave_size=32) - sim.exec = 0x0 - sim.set_vgpr_u64(0, 0, 0xAAAAAAAAAAAAAAAA) - ast = parse_vop_frexp_mant_f64("v_frexp_mant_f64 v[0:1], v[2:3]") - sim.execute(ast) - self.assertEqual(sim.get_vgpr_u64(0, 0), 0xAAAAAAAAAAAAAAAA) - mutant_exec_leak(sim, ast) - self.assertNotEqual(sim.get_vgpr_u64(0, 0), 0xAAAAAAAAAAAAAAAA) - - -class TestValuFrexpMantF64IEEE754Boundaries(unittest.TestCase): - """Deep verification of IEEE 754 boundary extremes, subnormals, and NaN handling.""" - - def test_subnormal_normalization_extremes(self): - # MIN_SUBNORMAL_F64 (2^-1074) -> mantissa is 0.5 - res_min = ref_frexp_mant_f64(MIN_SUBNORMAL_F64) - self.assertEqual(bits_to_f64(res_min), 0.5) - self.assertEqual(res_min, HALF_F64) - - # Negative MIN_SUBNORMAL -> -0.5 - res_neg_min = ref_frexp_mant_f64(MIN_SUBNORMAL_F64 | SIGN_MASK_F64) - self.assertEqual(bits_to_f64(res_neg_min), -0.5) - - # MAX_SUBNORMAL_F64 (all 52 mantissa bits set, exp=0) - # Normalized: implicit 1 at bit 52, leaving 51 ones and lowest bit 0 - res_max = ref_frexp_mant_f64(MAX_SUBNORMAL_F64) - self.assertEqual(res_max, (FREXP_EXP_F64 << 52) | (MANT_MASK_F64 ^ 1)) - self.assertAlmostEqual(bits_to_f64(res_max), 1.0 - (2.0 ** -52), places=15) - - def test_normal_boundary_extremes(self): - # MIN_NORMAL_F64 (2^-1022) -> 0.5 - res_min_norm = ref_frexp_mant_f64(MIN_NORMAL_F64) - self.assertEqual(bits_to_f64(res_min_norm), 0.5) - - # MAX_FINITE_F64 -> mantissa is 1.0 - 2^-53 - res_max_finite = ref_frexp_mant_f64(MAX_FINITE_F64) - self.assertEqual(res_max_finite, (FREXP_EXP_F64 << 52) | MANT_MASK_F64) - - def test_signed_zero_preservation(self): - self.assertEqual(ref_frexp_mant_f64(POS_ZERO_F64), POS_ZERO_F64) - self.assertEqual(ref_frexp_mant_f64(NEG_ZERO_F64), NEG_ZERO_F64) - # With abs: -0.0 becomes +0.0 - self.assertEqual(ref_frexp_mant_f64(NEG_ZERO_F64, abs_src0=True), POS_ZERO_F64) - # With neg: +0.0 becomes -0.0 - self.assertEqual(ref_frexp_mant_f64(POS_ZERO_F64, neg_src0=True), NEG_ZERO_F64) - # With clamp: -0.0 becomes +0.0 - self.assertEqual(ref_frexp_mant_f64(NEG_ZERO_F64, clamp=True), POS_ZERO_F64) - - def test_signed_infinity_preservation(self): - self.assertEqual(ref_frexp_mant_f64(POS_INF_F64), POS_INF_F64) - self.assertEqual(ref_frexp_mant_f64(NEG_INF_F64), NEG_INF_F64) - # With clamp: +inf -> 1.0, -inf -> +0.0 - self.assertEqual(ref_frexp_mant_f64(POS_INF_F64, clamp=True), ONE_F64) - self.assertEqual(ref_frexp_mant_f64(NEG_INF_F64, clamp=True), POS_ZERO_F64) - - def test_nan_payloads_and_quietening(self): - qnan_custom = QNAN_F64 | 0x00000000CAFEBABE - res_qnan = ref_frexp_mant_f64(qnan_custom) - self.assertTrue(is_nan_f64(res_qnan)) - self.assertEqual(res_qnan & 0x00000000CAFEBABE, 0x00000000CAFEBABE) - - snan_custom = SNAN_F64 | 0x0000000012345678 - res_snan = ref_frexp_mant_f64(snan_custom) - self.assertTrue(is_nan_f64(res_snan)) - self.assertFalse(is_snan_f64(res_snan), "Signaling NaN must be quieted") - - def test_clamp_behavior_on_all_special_values(self): - self.assertEqual(ref_frexp_mant_f64(QNAN_F64, clamp=True), POS_ZERO_F64) - self.assertEqual(ref_frexp_mant_f64(SNAN_F64, clamp=True), POS_ZERO_F64) - self.assertEqual(ref_frexp_mant_f64(POS_INF_F64, clamp=True), ONE_F64) - self.assertEqual(ref_frexp_mant_f64(NEG_INF_F64, clamp=True), POS_ZERO_F64) - self.assertEqual(ref_frexp_mant_f64(NEG_ZERO_F64, clamp=True), POS_ZERO_F64) - # Negative normal clamps to +0.0 - self.assertEqual(ref_frexp_mant_f64(f64_to_bits(-5.0), clamp=True), POS_ZERO_F64) - # Positive normal [0.5, 1.0) stays untouched - f_pos = f64_to_bits(1.5) - self.assertEqual(bits_to_f64(ref_frexp_mant_f64(f_pos, clamp=True)), 0.75) - - -class TestValuFrexpMantF64StatusFlags(unittest.TestCase): - """Unit tests for condition codes, status flags, and carry/borrow behavior.""" - - def test_vcc_strictly_preserved_scalar(self): - interp = ScalarVALUInterpreter() - initial_vcc = 0x123456789ABCDEF0 - interp.vcc = initial_vcc - interp.set_vgpr_u64(2, f64_to_bits(1.0)) - interp.execute_asm("v_frexp_mant_f64 v[0:1], v[2:3]") - self.assertEqual(interp.vcc, initial_vcc, "VCC must remain unmodified by v_frexp_mant_f64") - - def test_vcc_strictly_preserved_simd_wave64(self): - sim = SIMDVALUInterpreter(wave_size=64) - initial_vcc = 0xCAFEBABE0000FFFF - sim.vcc = initial_vcc - for lane in range(64): - sim.set_vgpr_u64(2, lane, f64_to_bits(2.0)) - sim.execute_asm("v_frexp_mant_f64 v[0:1], v[2:3]") - self.assertEqual(sim.vcc, initial_vcc, "Wave64 VCC must remain untouched") - - def test_fp_flags_exact_normal_no_exceptions(self): - interp = ScalarVALUInterpreter() - interp.set_vgpr_u64(2, f64_to_bits(1.0)) - interp.execute_asm("v_frexp_mant_f64 v[0:1], v[2:3]") - self.assertFalse(interp.status_flags.invalid) - self.assertFalse(interp.status_flags.overflow) - self.assertFalse(interp.status_flags.underflow) - self.assertFalse(interp.status_flags.inexact) - - def test_fp_flags_invalid_snan(self): - interp = ScalarVALUInterpreter() - interp.set_vgpr_u64(2, SNAN_F64) - interp.execute_asm("v_frexp_mant_f64 v[0:1], v[2:3]") - self.assertTrue(interp.status_flags.invalid) - - def test_fp_flags_no_invalid_on_qnan(self): - interp = ScalarVALUInterpreter() - interp.set_vgpr_u64(2, QNAN_F64) - interp.execute_asm("v_frexp_mant_f64 v[0:1], v[2:3]") - self.assertFalse(interp.status_flags.invalid) - - def test_fp_flags_no_overflow_underflow_on_extremes(self): - interp = ScalarVALUInterpreter() - interp.set_vgpr_u64(2, MAX_FINITE_F64) - interp.execute_asm("v_frexp_mant_f64 v[0:1], v[2:3]") - self.assertFalse(interp.status_flags.overflow) - self.assertFalse(interp.status_flags.underflow) - - -class TestValuFrexpMantF64RegisterAliasing(unittest.TestCase): - """Unit tests for register aliasing and in-place operand preservation.""" - - def test_full_aliasing_dst_src0_scalar(self): - interp = ScalarVALUInterpreter() - # In-place mantissa: v[0:1] = v_frexp_mant_f64 v[0:1] - interp.set_vgpr_u64(0, f64_to_bits(14.0)) # 14 = 0.875 * 2^4 - res = interp.execute_asm("v_frexp_mant_f64 v[0:1], v[0:1]") - self.assertEqual(bits_to_f64(res), 0.875) - self.assertEqual(bits_to_f64(interp.get_vgpr_u64(0)), 0.875) - - def test_partial_overlap_dst_hi_src0_lo_scalar(self): - interp = ScalarVALUInterpreter() - # v[1:2] = v_frexp_mant_f64 v[0:1] - interp.set_vgpr_u64(0, f64_to_bits(6.0)) # 6 = 0.75 * 2^3 - res = interp.execute_asm("v_frexp_mant_f64 v[1:2], v[0:1]") - self.assertEqual(bits_to_f64(res), 0.75) - self.assertEqual(bits_to_f64(interp.get_vgpr_u64(1)), 0.75) - - def test_partial_overlap_dst_lo_src0_hi_scalar(self): - interp = ScalarVALUInterpreter() - # v[0:1] = v_frexp_mant_f64 v[1:2] - interp.set_vgpr_u64(1, f64_to_bits(-10.0)) # -10 = -0.625 * 2^4 - res = interp.execute_asm("v_frexp_mant_f64 v[0:1], v[1:2]") - self.assertEqual(bits_to_f64(res), -0.625) - self.assertEqual(bits_to_f64(interp.get_vgpr_u64(0)), -0.625) - - def test_simd_wave64_aliasing_with_exec_mask(self): - sim = SIMDVALUInterpreter(wave_size=64) - canary = 0xABABABABCDCDEFEF - for lane in range(64): - if lane % 2 == 0: - sim.set_vgpr_u64(0, lane, f64_to_bits(4.0)) - else: - sim.set_vgpr_u64(0, lane, canary) - - sim.exec = 0x5555555555555555 - results = sim.execute_asm("v_frexp_mant_f64 v[0:1], v[0:1]") - - for lane in range(64): - if lane % 2 == 0: - self.assertEqual(bits_to_f64(results[lane]), 0.5) - self.assertEqual(bits_to_f64(sim.get_vgpr_u64(0, lane)), 0.5) - else: - self.assertEqual(results[lane], canary) - - def test_simd_wave32_partial_overlap_divergent(self): - sim = SIMDVALUInterpreter(wave_size=32) - for lane in range(32): - sim.set_vgpr_u64(1, lane, f64_to_bits(1.0 + lane)) - - results = sim.execute_asm("v_frexp_mant_f64 v[0:1], v[1:2]") - for lane in range(32): - m, _ = math.frexp(1.0 + lane) - self.assertEqual(bits_to_f64(results[lane]), m) - - -class TestValuFrexpMantF64SIMDMultiLane(unittest.TestCase): - """Unit tests for SIMD multi-lane divergence and 32/64-bit EXEC masking.""" - - def test_wave32_uniform_execution(self): - sim = SIMDVALUInterpreter(wave_size=32) - base = f64_to_bits(12.0) - for lane in range(32): - sim.set_vgpr_u64(2, lane, base) - - results = sim.execute_asm("v_frexp_mant_f64 v[0:1], v[2:3]") - self.assertEqual(len(results), 32) - for lane in range(32): - self.assertEqual(bits_to_f64(results[lane]), 0.75) - self.assertEqual(bits_to_f64(sim.get_vgpr_u64(0, lane)), 0.75) - - def test_wave64_uniform_execution(self): - sim = SIMDVALUInterpreter(wave_size=64) - base = f64_to_bits(3.0) - for lane in range(64): - sim.set_vgpr_u64(6, lane, base) - - results = sim.execute_asm("v_frexp_mant_f64 v[4:5], v[6:7]") - self.assertEqual(len(results), 64) - for lane in range(64): - self.assertEqual(bits_to_f64(results[lane]), 0.75) - - def test_wave32_divergent_lanes(self): - sim = SIMDVALUInterpreter(wave_size=32) - expected: list[float] = [] - for lane in range(32): - val = float(lane + 1) - sim.set_vgpr_u64(0, lane, f64_to_bits(val)) - m, _ = math.frexp(val) - expected.append(m) - - results = sim.execute_asm("v_frexp_mant_f64 v[4:5], v[0:1]") - for lane in range(32): - self.assertEqual(bits_to_f64(results[lane]), expected[lane]) - - def test_wave64_divergent_lanes(self): - sim = SIMDVALUInterpreter(wave_size=64) - expected: list[float] = [] - for lane in range(64): - val = -0.125 * (lane + 1) - sim.set_vgpr_u64(2, lane, f64_to_bits(val)) - m, _ = math.frexp(val) - expected.append(m) - - results = sim.execute_asm("v_frexp_mant_f64 v[0:1], v[2:3]") - for lane in range(64): - self.assertEqual(bits_to_f64(results[lane]), expected[lane]) - - def test_exec_mask_partial_inactivity_wave32(self): - sim = SIMDVALUInterpreter(wave_size=32) - canary = 0xDEADBEEFCAFEBABE - for lane in range(32): - sim.set_vgpr_u64(0, lane, canary) - sim.set_vgpr_u64(2, lane, f64_to_bits(4.0)) - - sim.exec = 0x55555555 - results = sim.execute_asm("v_frexp_mant_f64 v[0:1], v[2:3]") - - for lane in range(32): - if lane % 2 == 0: - self.assertEqual(bits_to_f64(results[lane]), 0.5) - else: - self.assertEqual(results[lane], canary) - - def test_exec_mask_partial_inactivity_wave64(self): - sim = SIMDVALUInterpreter(wave_size=64) - canary = 0x1122334455667788 - for lane in range(64): - sim.set_vgpr_u64(0, lane, canary) - sim.set_vgpr_u64(2, lane, f64_to_bits(8.0)) - - sim.exec = 0x00000000FFFFFFFF - results = sim.execute_asm("v_frexp_mant_f64 v[0:1], v[2:3]") - - for lane in range(64): - if lane < 32: - self.assertEqual(bits_to_f64(results[lane]), 0.5) - else: - self.assertEqual(results[lane], canary) - - def test_exec_mask_all_inactive(self): - sim = SIMDVALUInterpreter(wave_size=64) - canary = 0xCAFEBABE12345678 - for lane in range(64): - sim.set_vgpr_u64(0, lane, canary) - sim.set_vgpr_u64(2, lane, f64_to_bits(1.0)) - - sim.exec = 0x0 - results = sim.execute_asm("v_frexp_mant_f64 v[0:1], v[2:3]") - for lane in range(64): - self.assertEqual(results[lane], canary) - - -class TestValuFrexpMantF64ScalarInterpreter(unittest.TestCase): - """Unit tests for deterministic scalar instruction interpreter.""" - - def setUp(self): - self.interp = ScalarVALUInterpreter() - - def test_scalar_interpreter_vgpr_sources(self): - # v[2:3] = 6.0 = 0.75 * 2^3 -> mantissa is 0.75 - self.interp.set_vgpr_u64(2, f64_to_bits(6.0)) - ast = parse_vop_frexp_mant_f64("v_frexp_mant_f64 v[0:1], v[2:3]") - res = self.interp.execute(ast) - self.assertEqual(bits_to_f64(res), 0.75) - self.assertEqual(self.interp.get_vgpr_u64(0), res) - - def test_scalar_interpreter_sgpr_sources(self): - # s[0:1] = -12.0 -> mantissa is -0.75 - self.interp.set_sgpr_u64(0, f64_to_bits(-12.0)) - ast = parse_vop_frexp_mant_f64("v_frexp_mant_f64 v[4:5], s[0:1]") - res = self.interp.execute(ast) - self.assertEqual(bits_to_f64(res), -0.75) - - def test_scalar_interpreter_literal_operand(self): - ast = parse_vop_frexp_mant_f64("v_frexp_mant_f64 v[2:3], 32.0") - res = self.interp.execute(ast) - self.assertEqual(bits_to_f64(res), 0.5) - - def test_scalar_interpreter_input_modifiers(self): - # -|v[2:3]| with v[2:3] = 2.0 -> mantissa is -0.5 - self.interp.set_vgpr_u64(2, f64_to_bits(2.0)) - ast = parse_vop_frexp_mant_f64("v_frexp_mant_f64 v[0:1], -|v[2:3]|") - res = self.interp.execute(ast) - self.assertEqual(bits_to_f64(res), -0.5) - - def test_scalar_interpreter_output_modifiers_clamp_omod(self): - # 1.0 -> mantissa 0.5, with mul:2 -> 1.0, clamp -> 1.0 - self.interp.set_vgpr_u64(0, f64_to_bits(1.0)) - ast = parse_vop_frexp_mant_f64("v_frexp_mant_f64 v[4:5], v[0:1] clamp mul:2") - res = self.interp.execute(ast) - self.assertEqual(bits_to_f64(res), 1.0) - - -class TestValuFrexpMantF64SymbolicAST(unittest.TestCase): - """Unit tests for symbolic AST opcode definitions and typed expressions.""" - - def test_ast_construction_and_validation(self): - dst = Operand(OperandKind.VGPR_PAIR, DataType.F64, reg_index=0) - src0 = Operand(OperandKind.VGPR_PAIR, DataType.F64, reg_index=2) - ast = InstructionAST("v_frexp_mant_f64", dst, src0, clamp=True, omod="mul:2") - ast.validate() - self.assertEqual(ast.to_asm(), "v_frexp_mant_f64 v[0:1], v[2:3] clamp mul:2") - - def test_parser_vgpr_sgpr_operands(self): - ast = parse_vop_frexp_mant_f64("v_frexp_mant_f64 v[4:5], v[6:7]") - self.assertEqual(ast.dst.reg_index, 4) - self.assertEqual(ast.src0.kind, OperandKind.VGPR_PAIR) - self.assertEqual(ast.src0.reg_index, 6) - self.assertFalse(ast.clamp) - self.assertEqual(ast.omod, "none") - - ast_sgpr = parse_vop_frexp_mant_f64("v_frexp_mant_f64 v[0:1], s[2:3]") - self.assertEqual(ast_sgpr.src0.kind, OperandKind.SGPR_PAIR) - self.assertEqual(ast_sgpr.src0.reg_index, 2) - - def test_parser_literal_operand(self): - ast = parse_vop_frexp_mant_f64("v_frexp_mant_f64 v[0:1], 1.5") - self.assertEqual(ast.src0.kind, OperandKind.LITERAL_F64) - self.assertEqual(bits_to_f64(ast.src0.literal_val), 1.5) - - def test_parser_modifiers_abs_neg_clamp_omod(self): - ast = parse_vop_frexp_mant_f64("v_frexp_mant_f64 v[0:1], -|v[2:3]| clamp mul:4") - self.assertTrue(ast.src0.abs_mod) - self.assertTrue(ast.src0.neg_mod) - self.assertTrue(ast.clamp) - self.assertEqual(ast.omod, "mul:4") - self.assertEqual(ast.to_asm(), "v_frexp_mant_f64 v[0:1], -|v[2:3]| clamp mul:4") - - def test_ast_type_checking(self): - bad_dst = Operand(OperandKind.SGPR_PAIR, DataType.F64, reg_index=0) - src0 = Operand(OperandKind.VGPR_PAIR, DataType.F64, reg_index=2) - with self.assertRaises(TypeError): - InstructionAST("v_frexp_mant_f64", bad_dst, src0).validate() - - -class TestValuFrexpMantF64Oracle(unittest.TestCase): - """Unit tests for the reference mathematical oracle and architectural model.""" - - def test_oracle_normal_values(self): - # 1.0 = 0.5 * 2^1 -> mantissa is 0.5 - self.assertEqual(bits_to_f64(ref_frexp_mant_f64(ONE_F64)), 0.5) - # 1.5 = 0.75 * 2^1 -> mantissa is 0.75 - f_1p5 = f64_to_bits(1.5) - self.assertEqual(bits_to_f64(ref_frexp_mant_f64(f_1p5)), 0.75) - # -4.0 = -0.5 * 2^3 -> mantissa is -0.5 - f_neg4 = f64_to_bits(-4.0) - self.assertEqual(bits_to_f64(ref_frexp_mant_f64(f_neg4)), -0.5) - - def test_oracle_powers_of_two(self): - for p in range(-50, 50): - val = math.ldexp(1.0, p) - val_bits = f64_to_bits(val) - self.assertEqual(bits_to_f64(ref_frexp_mant_f64(val_bits)), 0.5) - - def test_oracle_cross_check_math_frexp(self): - test_floats = [ - 0.125, 0.3333333333333333, 1.0, 2.5, 42.0, 1000.125, - -7.5, -0.0625, 1.7976931348623157e+308, 2.2250738585072014e-308 - ] - for f in test_floats: - f_bits = f64_to_bits(f) - oracle_res = ref_frexp_mant_f64(f_bits) - math_res = ref_frexp_mant_f64_math(f_bits) - self.assertEqual(oracle_res, math_res) - - def test_oracle_cross_check_fraction(self): - for f in [1.5, 3.25, -0.75, 10.125, 0.03125]: - f_bits = f64_to_bits(f) - self.assertEqual(ref_frexp_mant_f64(f_bits), ref_frexp_mant_f64_fraction(f_bits)) - - def test_oracle_special_values(self): - # +0.0 and -0.0 preserved - self.assertEqual(ref_frexp_mant_f64(POS_ZERO_F64), POS_ZERO_F64) - self.assertEqual(ref_frexp_mant_f64(NEG_ZERO_F64), NEG_ZERO_F64) - # +inf and -inf preserved - self.assertEqual(ref_frexp_mant_f64(POS_INF_F64), POS_INF_F64) - self.assertEqual(ref_frexp_mant_f64(NEG_INF_F64), NEG_INF_F64) - # NaNs preserved and quieted - self.assertTrue(is_nan_f64(ref_frexp_mant_f64(QNAN_F64))) - self.assertTrue(is_nan_f64(ref_frexp_mant_f64(SNAN_F64))) - - def test_oracle_subnormal_normalization(self): - # Smallest subnormal 2^-1074: normalized mantissa must be 0.5 - res_sub_min = ref_frexp_mant_f64(MIN_SUBNORMAL_F64) - self.assertEqual(bits_to_f64(res_sub_min), 0.5) - - # Negative subnormal: normalized mantissa is -0.5 - res_neg_sub = ref_frexp_mant_f64(MIN_SUBNORMAL_F64 | SIGN_MASK_F64) - self.assertEqual(bits_to_f64(res_neg_sub), -0.5) - - def test_oracle_modifiers(self): - # abs modifier - f_neg2 = f64_to_bits(-2.0) - self.assertEqual(bits_to_f64(ref_frexp_mant_f64(f_neg2, abs_src0=True)), 0.5) - # neg modifier - f_pos2 = f64_to_bits(2.0) - self.assertEqual(bits_to_f64(ref_frexp_mant_f64(f_pos2, neg_src0=True)), -0.5) - # clamp modifier - self.assertEqual(bits_to_f64(ref_frexp_mant_f64(f_neg2, clamp=True)), 0.0) - # omod modifiers - self.assertEqual(bits_to_f64(ref_frexp_mant_f64(ONE_F64, omod="mul:2")), 1.0) - self.assertEqual(bits_to_f64(ref_frexp_mant_f64(ONE_F64, omod="mul:4")), 2.0) - self.assertEqual(bits_to_f64(ref_frexp_mant_f64(ONE_F64, omod="div:2")), 0.25) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_valu_int16.py b/tests/semantic/test_valu_int16.py deleted file mode 100644 index 13b1b242c..000000000 --- a/tests/semantic/test_valu_int16.py +++ /dev/null @@ -1,479 +0,0 @@ -"""Semantic value tests for RDNA2 16-bit integer VALU instructions. - -Covers all 6 ops end-to-end through tools/rdna2spirv.py and tests/semantic/spirv_mini_interp.py: - v_min_u16 D.u16 = min(S0.u16, S1.u16) (unsigned 16-bit) - v_max_u16 D.u16 = max(S0.u16, S1.u16) (unsigned 16-bit) - v_min_i16 D.i16 = min(S0.i16, S1.i16) (signed 16-bit two's complement) - v_max_i16 D.i16 = max(S0.i16, S1.i16) (signed 16-bit two's complement) - v_mul_lo_u16 D.u16 = (S0.u16 * S1.u16) & 0xffff (low 16 bits, mod 2^16) - v_sub_nc_u16 D.u16 = (S0.u16 - S1.u16) & 0xffff (no carry, mod 2^16; VOP3-only on GFX10) - -16-bit destination and op_sel semantics (AMD RDNA2 ISA, VOP3 OP_SEL; docs/design.md "16-bit results"): - - VOP3 (_e64, 8-byte encoding, or VOP3-only v_sub_nc_u16): op_sel:[s0,s1,dst] picks the low (0) or high (1) - 16-bit half of src0, src1 and dst; the untouched half of dst is preserved. - - VOP2 (_e32 / encoding-less non-_e64 mnemonic for the other five ops): reads low halves, writes dst[15:0] - and zeroes dst[31:16]; source op_sel is rejected as Unsupported. -""" -import gc -import itertools -import os -import re -import struct -import sys -import tempfile -import unittest -import warnings - -HERE = os.path.dirname(os.path.abspath(__file__)) -ROOT = os.path.dirname(os.path.dirname(HERE)) -TOOLS_DIR = os.environ.get("LEONIDA_TOOLS_DIR") or os.path.join(ROOT, "tools") - -sys.dont_write_bytecode = True -if TOOLS_DIR not in sys.path: - sys.path.insert(0, TOOLS_DIR) -if HERE not in sys.path: - sys.path.insert(0, HERE) - -import rdna2spirv # noqa: E402 -import spirv_mini_interp as si # noqa: E402 - -MASK16 = 0xFFFF -MASK32 = 0xFFFFFFFF -STUB_DXBC = b"DXBC" + bytes(24) + struct.pack(" 0xd4..0xd7). -VOP3_ENC12 = "; encoding: [0x00,0x00,0x03,0xd7,0xff,0x02,0x02,0x00,0x34,0x12,0x00,0x00]" -# 8-byte VOP2 encoding with a 32-bit literal constant (byte 3 bit 31 = 0 -> not VOP3). -VOP2_ENC8_LIT = "; encoding: [0xff,0x02,0x00,0x64,0x34,0x12,0x00,0x00]" - -BOUNDARY_HALVES = (0x0000, 0x0001, 0x7FFF, 0x8000, 0x8001, 0xFFFE, 0xFFFF) - -# Distinct halves across all four slots: unsigned order 0x1234 < 0x7FFF < 0x8001 < 0xABCD, -# signed order 0x8001 (-32767) < 0xABCD (-21555) < 0x1234 (+4660) < 0x7FFF (+32767). -OPSEL_A = 0x12348001 -OPSEL_B = 0xABCD7FFF - - -def u16(x: int) -> int: - return x & MASK16 - - -def s16(x: int) -> int: - v = x & MASK16 - return v - 0x10000 if (v & 0x8000) else v - - -def half16(word: int, hi: int) -> int: - return ((word >> 16) & MASK16) if hi else (word & MASK16) - - -def merge16(old: int, res16: int, dst_hi: int = 0, preserve_high: bool = True) -> int: - res16 &= MASK16 - if dst_hi: - return ((res16 << 16) | (old & MASK16)) & MASK32 - if preserve_high: - return ((old & 0xFFFF0000) | res16) & MASK32 - return res16 - - -def ref_op16(op: str, x: int, y: int) -> int: - """Plain-Python RDNA2 ISA reference for the 16-bit result in [0, 0xFFFF].""" - ux, uy = u16(x), u16(y) - if op == "v_min_u16": - return min(ux, uy) - if op == "v_max_u16": - return max(ux, uy) - if op == "v_min_i16": - return min(s16(ux), s16(uy)) & MASK16 - if op == "v_max_i16": - return max(s16(ux), s16(uy)) & MASK16 - if op == "v_mul_lo_u16": - return (ux * uy) & MASK16 - if op == "v_sub_nc_u16": - return (ux - uy) & MASK16 - raise ValueError(f"unknown op {op!r}") - - -def ref_word(op: str, src0: int, src1: int, old: int = OLD, sel=(0, 0, 0), preserve_high: bool = True) -> int: - """Plain-Python 32-bit destination word reference including op_sel and half preservation.""" - res16 = ref_op16(op, half16(src0, sel[0]), half16(src1, sel[1])) - return merge16(old, res16, dst_hi=sel[2], preserve_high=preserve_high) - - -_TMP_DIR = None -_SRC_PATH = None - - -def setUpModule(): - global _TMP_DIR, _SRC_PATH - _TMP_DIR = tempfile.TemporaryDirectory() - disasm_dir = os.path.join(_TMP_DIR.name, "disasm") - os.mkdir(disasm_dir) - _SRC_PATH = os.path.join(disasm_dir, "ps_valu_int16.s") - with open(os.path.join(_TMP_DIR.name, "ps_valu_int16.dxbc"), "wb") as f: - f.write(STUB_DXBC) - - -def tearDownModule(): - global _TMP_DIR, _SRC_PATH - if _TMP_DIR is not None: - gc.collect() - _TMP_DIR.cleanup() - _TMP_DIR = None - _SRC_PATH = None - - -def translate_lines(lines) -> str: - if _TMP_DIR is None: - setUpModule() - asm = "; test_valu_int16\n" + "".join(f"\t{ln}\n" for ln in lines) + "\ts_endpgm\n" - with open(_SRC_PATH, "w", encoding="utf-8") as f: - f.write(asm) - with warnings.catch_warnings(): - warnings.simplefilter("ignore", ResourceWarning) - return rdna2spirv.translate(_SRC_PATH) - - -def run_mrt0(lines, regs=("v0", "v0", "v0", "v0")) -> list[int]: - spv = translate_lines(list(lines) + [f"exp mrt0 {', '.join(regs)} done vm"]) - return list(si.run_fragment(spv)["%out_mrt0"]) - - -def run_one(line: str, v1: int, v2: int, old: int = OLD) -> int: - return run_mrt0([f"v_mov_b32 v1, {v1 & MASK32:#x}", f"v_mov_b32 v2, {v2 & MASK32:#x}", - f"v_mov_b32 v0, {old & MASK32:#x}", line])[0] - - -def vop3_mnemonic(op: str) -> str: - return op if op == "v_sub_nc_u16" else f"{op}_e64" - - -class ReferenceOracleTests(unittest.TestCase): - """Cross-check plain-Python reference against hand-worked constants.""" - - def test_hand_worked_constants(self): - cases = [ - ("v_min_u16", 0x11117FFF, 0x22228000, (0, 0, 0), True, 0xAAAA7FFF), - ("v_max_u16", 0x11117FFF, 0x22228000, (0, 0, 0), True, 0xAAAA8000), - ("v_min_i16", 0x11117FFF, 0x22228000, (0, 0, 0), True, 0xAAAA8000), - ("v_max_i16", 0x11117FFF, 0x22228000, (0, 0, 0), True, 0xAAAA7FFF), - ("v_min_i16", 0x11110000, 0x2222FFFF, (0, 0, 0), True, 0xAAAAFFFF), - ("v_max_u16", 0x11110000, 0x2222FFFF, (0, 0, 0), True, 0xAAAAFFFF), - ("v_mul_lo_u16", 0x1111FFFF, 0x2222FFFF, (0, 0, 0), True, 0xAAAA0001), - ("v_mul_lo_u16", 0x11118000, 0x22220002, (0, 0, 0), True, 0xAAAA0000), - ("v_sub_nc_u16", 0x11110000, 0x22220001, (0, 0, 0), True, 0xAAAAFFFF), - ("v_sub_nc_u16", 0x11110005, 0x2222000A, (0, 0, 1), True, 0xFFFB5555), - ("v_min_u16", 0x1111AAAA, 0x22225555, (0, 0, 0), False, 0x00005555), - ] - for op, x, y, sel, keep_hi, want in cases: - with self.subTest(op=op, x=hex(x), y=hex(y), sel=sel, keep_hi=keep_hi): - self.assertEqual(ref_word(op, x, y, OLD, sel, keep_hi), want) - - -class ValuInt16BoundaryTests(unittest.TestCase): - """Exhaustive boundary matrix and high-half noise isolation for all 10 ops.""" - - def test_boundary_matrix_all_ops(self): - # Batch 4 pairs per shader (mrt0 xyzw) to test all 49 boundary pairs x 10 ops cleanly and fast. - pairs = list(itertools.product(BOUNDARY_HALVES, repeat=2)) - for op in ALL_OPS: - mnemonic = vop3_mnemonic(op) - for start in range(0, len(pairs), 4): - chunk = pairs[start:start + 4] - lines = [] - expected = [] - for slot, (hx, hy) in enumerate(chunk): - dst = f"v{10 + slot}" - s0 = 0xCAFE0000 | hx - s1 = 0xBEEF0000 | hy - lines += [ - f"v_mov_b32 v1, {s0:#x}", - f"v_mov_b32 v2, {s1:#x}", - f"v_mov_b32 {dst}, {OLD:#x}", - f"{mnemonic} {dst}, v1, v2", - ] - expected.append(ref_word(op, s0, s1, OLD)) - while len(expected) < 4: - lines.append(f"v_mov_b32 v{10 + len(expected)}, 0") - expected.append(0) - with self.subTest(op=op, batch=start // 4): - self.assertEqual(run_mrt0(lines, ("v10", "v11", "v12", "v13")), expected) - - def test_signed_vs_unsigned_minmax_disagreements(self): - # Pairs where signed i16 and unsigned u16 order invert; high halves carry misleading signs. - cases = [ - (0x00000000, 0x0000FFFF), # 0 vs -1 (i16) / 65535 (u16) - (0x00007FFF, 0x00008000), # +32767 vs -32768 (i16) / 32768 (u16) - (0x80007FFF, 0x7FFF8000), # opposite signs in high halves must be ignored - (0xFFFF0001, 0x00018000), # +1 vs -32768 (i16) / 32768 (u16) - (0x12348000, 0x56780001), # -32768 vs +1 (i16) / 32768 vs 1 (u16) - ] - for x, y in cases: - with self.subTest(x=hex(x), y=hex(y)): - min_u, max_u, min_i, max_i = run_mrt0([ - f"v_mov_b32 v1, {x:#x}", - f"v_mov_b32 v2, {y:#x}", - f"v_mov_b32 v10, {OLD:#x}", - f"v_mov_b32 v11, {OLD:#x}", - f"v_mov_b32 v12, {OLD:#x}", - f"v_mov_b32 v13, {OLD:#x}", - "v_min_u16_e64 v10, v1, v2", - "v_max_u16_e64 v11, v1, v2", - "v_min_i16_e64 v12, v1, v2", - "v_max_i16_e64 v13, v1, v2", - ], ("v10", "v11", "v12", "v13")) - self.assertEqual(min_u, ref_word("v_min_u16", x, y)) - self.assertEqual(max_u, ref_word("v_max_u16", x, y)) - self.assertEqual(min_i, ref_word("v_min_i16", x, y)) - self.assertEqual(max_i, ref_word("v_max_i16", x, y)) - self.assertNotEqual(min_u, min_i) - self.assertNotEqual(max_u, max_i) - - def test_mul_lo_u16_wraparound_and_high_half_isolation(self): - cases = [ - (0xABCD0100, 0xDCBA0100, 0x0000), # 256 * 256 = 65536 -> 0 mod 2^16 - (0x1111FFFF, 0x2222FFFF, 0x0001), # 65535^2 = 0xFFFE0001 -> 1 - (0x33338001, 0x44440003, 0x8003), # 32769 * 3 = 0x18003 -> 0x8003 - (0x55551234, 0x66665678, 0x0060), # 0x1234 * 0x5678 = 0x06260060 -> 0x0060 - ] - for x, y, want16 in cases: - with self.subTest(x=hex(x), y=hex(y)): - self.assertEqual(ref_op16("v_mul_lo_u16", x, y), want16) - self.assertEqual(run_one("v_mul_lo_u16_e64 v0, v1, v2", x, y), (OLD & 0xFFFF0000) | want16) - - def test_sub_nc_u16_wraparound_and_high_half_isolation(self): - pairs = [(0x12340000, 0x56780001), (0xAAAA000A, 0xBBBB0005), (0xFFFF7FFF, 0x00008000), (0xDEAD8001, 0xBEEF0001)] - for x, y in pairs: - with self.subTest(x=hex(x), y=hex(y)): - sub = run_one("v_sub_nc_u16 v0, v1, v2", x, y) - self.assertEqual(sub, ref_word("v_sub_nc_u16", x, y)) - - def test_min_max_sub_does_not_leak_high_half_bits(self): - # Upper halves are all-1s / disjoint bits; only low 16 bits participate and dst[31:16] stays OLD. - x, y = 0xFFFF0F5A, 0xFFFFF03C - words = run_mrt0([ - f"v_mov_b32 v1, {x:#x}", - f"v_mov_b32 v2, {y:#x}", - f"v_mov_b32 v10, {OLD:#x}", - f"v_mov_b32 v11, {OLD:#x}", - f"v_mov_b32 v12, {OLD:#x}", - f"v_mov_b32 v13, {OLD:#x}", - "v_min_u16_e64 v10, v1, v2", - "v_max_u16_e64 v11, v1, v2", - "v_min_i16_e64 v12, v1, v2", - "v_sub_nc_u16 v13, v1, 0", - ], ("v10", "v11", "v12", "v13")) - self.assertEqual(words, [ - ref_word("v_min_u16", x, y), - ref_word("v_max_u16", x, y), - ref_word("v_min_i16", x, y), - ref_word("v_sub_nc_u16", x, 0), - ]) - - -class ValuInt16OpSelAndEncodingTests(unittest.TestCase): - """VOP3 op_sel:[s0,s1,dst], 8-byte VOP3 disassembly encodings, VOP3-only v_sub_nc_u16, and VOP2 _e32.""" - - def test_all_ops_vop3_op_sel_combinations(self): - for op in ALL_OPS: - mnemonic = vop3_mnemonic(op) - for bits in itertools.product((0, 1), repeat=3): - line = f"{mnemonic} v0, v1, v2 op_sel:[{bits[0]},{bits[1]},{bits[2]}]" - with self.subTest(op=op, op_sel=bits): - self.assertEqual(run_one(line, OPSEL_A, OPSEL_B), ref_word(op, OPSEL_A, OPSEL_B, OLD, bits)) - - def test_bare_mnemonic_with_8byte_vop3_encoding_keeps_other_half(self): - # LLVM 21 prints VOP3 16-bit ops without _e64, distinguished by an 8-byte (16 hex char) encoding. - for op in ALL_OPS: - with self.subTest(op=op): - got_lo = run_one(f"{op} v0, v1, v2 {VOP3_ENC8}", OPSEL_A, OPSEL_B) - got_hi = run_one(f"{op} v0, v1, v2 op_sel:[1,0,1] {VOP3_ENC8}", OPSEL_A, OPSEL_B) - self.assertEqual(got_lo, ref_word(op, OPSEL_A, OPSEL_B, OLD, (0, 0, 0), preserve_high=True)) - self.assertEqual(got_hi, ref_word(op, OPSEL_A, OPSEL_B, OLD, (1, 0, 1), preserve_high=True)) - - def test_v_sub_nc_u16_is_always_vop3_without_suffix_or_encoding(self): - # v_sub_nc_u16 is VOP3-only on GFX10, so even bare without _e64/encoding it keeps the untouched half. - self.assertEqual(run_one("v_sub_nc_u16 v0, v1, v2", OPSEL_A, OPSEL_B), - ref_word("v_sub_nc_u16", OPSEL_A, OPSEL_B, OLD, (0, 0, 0), preserve_high=True)) - self.assertEqual(run_one("v_sub_nc_u16 v0, v1, v2 op_sel:[1,1,1]", OPSEL_A, OPSEL_B), - ref_word("v_sub_nc_u16", OPSEL_A, OPSEL_B, OLD, (1, 1, 1), preserve_high=True)) - - def test_vop2_e32_zeroes_high_half_and_rejects_source_op_sel(self): - for op in VOP2_MODELLED_OPS: - with self.subTest(op=op, mode="e32"): - self.assertEqual(run_one(f"{op}_e32 v0, v1, v2", OPSEL_A, OPSEL_B), - ref_word(op, OPSEL_A, OPSEL_B, OLD, (0, 0, 0), preserve_high=False)) - for sel in ("op_sel:[1,0,0]", "op_sel:[0,1,0]", "op_sel:[0,0,1]"): - with self.subTest(op=op, mode=sel): - with self.assertRaises(rdna2spirv.Unsupported): - translate_lines([ - "v_mov_b32 v0, 0xaaaa5555", - "v_mov_b32 v1, 0x12348001", - "v_mov_b32 v2, 0xabcd7fff", - f"{op}_e32 v0, v1, v2 {sel}", - "exp mrt0 v0, v0, v0, v0 done vm", - ]) - - def test_12byte_vop3_literal_encoding_preserves_other_half_and_honours_op_sel(self): - # GFX10 VOP3 instructions with a 32-bit literal constant have a 12-byte (24-hex-char) encoding - # with byte 3 bits [31:26] == 0x35; they must still be recognized as VOP3 (e64=True). - lit = 0x56781234 - for op in ALL_OPS: - with self.subTest(op=op, mode="lo"): - got = run_one(f"{op} v0, {lit:#x}, v2 {VOP3_ENC12}", OPSEL_A, OPSEL_B) - self.assertEqual(got, ref_word(op, lit, OPSEL_B, OLD, (0, 0, 0), preserve_high=True)) - with self.subTest(op=op, mode="dst_hi"): - got = run_one(f"{op} v0, {lit:#x}, v2 op_sel:[0,0,1] {VOP3_ENC12}", OPSEL_A, OPSEL_B) - self.assertEqual(got, ref_word(op, lit, OPSEL_B, OLD, (0, 0, 1), preserve_high=True)) - with self.subTest(op=op, mode="src1_hi"): - got = run_one(f"{op} v0, {lit:#x}, v2 op_sel:[0,1,0] {VOP3_ENC12}", OPSEL_A, OPSEL_B) - self.assertEqual(got, ref_word(op, lit, OPSEL_B, OLD, (0, 1, 0), preserve_high=True)) - # Also verify VOP3-only v_add_nc_u16 with a 12-byte literal encoding. - self.assertEqual( - run_one(f"v_add_nc_u16 v0, {lit:#x}, v2 {VOP3_ENC12}", OPSEL_A, OPSEL_B), - merge16(OLD, (u16(lit) + u16(OPSEL_B)) & MASK16, dst_hi=0, preserve_high=True), - ) - self.assertEqual( - run_one(f"v_add_nc_u16 v0, {lit:#x}, v2 op_sel:[0,1,1] {VOP3_ENC12}", OPSEL_A, OPSEL_B), - merge16(OLD, (u16(lit) + half16(OPSEL_B, 1)) & MASK16, dst_hi=1, preserve_high=True), - ) - - def test_8byte_vop2_literal_encoding_stays_vop2(self): - # An 8-byte VOP2 encoding with a 32-bit literal has byte 3 bit 31 == 0 (not VOP3 0x35), - # so it must stay VOP2 (zeroing dst[31:16] and rejecting op_sel). - lit = 0x00001234 - for op in VOP2_MODELLED_OPS: - with self.subTest(op=op, mode="e32_lit"): - got = run_one(f"{op}_e32 v0, {lit:#x}, v2 {VOP2_ENC8_LIT}", OPSEL_A, OPSEL_B) - self.assertEqual(got, ref_word(op, lit, OPSEL_B, OLD, (0, 0, 0), preserve_high=False)) - with self.subTest(op=op, mode="e32_lit_opsel"): - with self.assertRaises(rdna2spirv.Unsupported): - translate_lines([ - f"v_mov_b32 v0, {OLD:#x}", - f"v_mov_b32 v2, {OPSEL_B:#x}", - f"{op}_e32 v0, {lit:#x}, v2 op_sel:[0,1,0] {VOP2_ENC8_LIT}", - "exp mrt0 v0, v0, v0, v0 done vm", - ]) - - -class ValuInt16OperandsAndExecTests(unittest.TestCase): - """Register aliasing, SGPR and inline-constant operands, and EXEC lane masking.""" - - def test_dst_aliases_source_with_op_sel(self): - # v0 starts as 0x1234ABCD and v1 as 0x567800FF; reading v0 before writing must keep the other half intact. - init_v0, init_v1 = 0x1234ABCD, 0x567800FF - for op in ALL_OPS: - mnemonic = vop3_mnemonic(op) - for order, sel in (("v0, v0, v1", (1, 0, 0)), ("v0, v1, v0", (0, 0, 1)), ("v0, v0, v0", (0, 1, 1))): - s0 = init_v0 if order.split(", ")[1] == "v0" else init_v1 - s1 = init_v0 if order.split(", ")[2] == "v0" else init_v1 - with self.subTest(op=op, order=order, sel=sel): - got = run_mrt0([ - f"v_mov_b32 v0, {init_v0:#x}", - f"v_mov_b32 v1, {init_v1:#x}", - f"{mnemonic} {order} op_sel:[{sel[0]},{sel[1]},{sel[2]}]", - ])[0] - self.assertEqual(got, ref_word(op, s0, s1, init_v0, sel)) - - def test_sgpr_and_inline_constant_operands(self): - # -16 is 0xFFFFFFF0 (lo=0xFFF0, hi=0xFFFF); 64 is 0x00000040; -1 is 0xFFFFFFFF. - s4_val = 0xCAFE8005 - v1_val = 0xBEEF0010 - cases = [ - ("v_min_i16", "v_min_i16_e64 v0, s4, -16", s4_val, 0xFFFFFFF0, (0, 0, 0)), - ("v_min_u16", "v_min_u16_e64 v0, s4, -16", s4_val, 0xFFFFFFF0, (0, 0, 0)), - ("v_max_i16", "v_max_i16_e64 v0, -1, v1", 0xFFFFFFFF, v1_val, (0, 0, 0)), - ("v_max_u16", "v_max_u16_e64 v0, v1, -1", v1_val, 0xFFFFFFFF, (0, 0, 0)), - ("v_mul_lo_u16", "v_mul_lo_u16_e64 v0, s4, 64", s4_val, 64, (0, 0, 0)), - ("v_sub_nc_u16", "v_sub_nc_u16 v0, 1, s4", 1, s4_val, (0, 0, 0)), - ("v_sub_nc_u16", "v_sub_nc_u16 v0, s4, 1", s4_val, 1, (0, 0, 0)), - ("v_min_u16", "v_min_u16_e64 v0, s4, -16 op_sel:[1,0,1]", s4_val, 0xFFFFFFF0, (1, 0, 1)), - ("v_max_u16", "v_max_u16_e64 v0, 64, s4", 64, s4_val, (0, 0, 0)), - ("v_mul_lo_u16", "v_mul_lo_u16_e64 v0, v1, -1", v1_val, 0xFFFFFFFF, (0, 0, 0)), - ] - for op, insn, x, y, sel in cases: - with self.subTest(insn=insn): - got = run_mrt0([ - f"s_mov_b32 s4, {s4_val:#x}", - f"v_mov_b32 v1, {v1_val:#x}", - f"v_mov_b32 v0, {OLD:#x}", - insn, - ])[0] - self.assertEqual(got, ref_word(op, x, y, OLD, sel)) - - def test_inactive_exec_lane_preserves_destination(self): - for op in ALL_OPS: - for suffix in (vop3_mnemonic(op), f"{op}_e32") if op != "v_sub_nc_u16" else (op,): - with self.subTest(insn=suffix): - got = run_mrt0([ - f"v_mov_b32 v0, {OLD:#x}", - "v_mov_b32 v1, 0x12345678", - "v_mov_b32 v2, 0x9abcdef0", - "v_cmpx_eq_u32_e32 vcc_lo, 0, 1", - f"{suffix} v0, v1, v2", - "s_mov_b32 exec_lo, -1", - ])[0] - self.assertEqual(got, OLD) - - -class ValuInt16NegativeControlsTests(unittest.TestCase): - """Sabotage translated SPIR-V output and confirm the checks detect each mutation.""" - - def test_sabotaged_spirv_is_detected(self): - controls = [ - ("v_min_i16 treated as unsigned extract", - "v_min_i16_e64 v0, v1, v2", 0x11117FFF, 0x22228000, - r"OpBitFieldSExtract", "OpBitFieldUExtract", 2, - ref_word("v_min_i16", 0x11117FFF, 0x22228000)), - ("v_max_i16 using unsigned max", - "v_max_i16_e64 v0, v1, v2", 0x11117FFF, 0x22228000, - r"glsl SMax", "glsl UMax", 1, - ref_word("v_max_i16", 0x11117FFF, 0x22228000)), - ("v_min_u16 swapped to max", - "v_min_u16_e64 v0, v1, v2", 0x11117FFF, 0x22228000, - r"glsl UMin", "glsl UMax", 1, - ref_word("v_min_u16", 0x11117FFF, 0x22228000)), - ("v_sub_nc_u16 drops operand order", - "v_sub_nc_u16 v0, v1, v2", 0x0000000A, 0x00000005, - r"OpISub %uint (%\w+) (%\w+)", r"OpISub %uint \2 \1", 1, - ref_word("v_sub_nc_u16", 0x0000000A, 0x00000005)), - ("v_mul_lo_u16 drops 16-bit result mask", - "v_mul_lo_u16_e64 v0, v1, v2", 0x00000101, 0x00000101, - r"(%\w+) = OpIMul %uint (%\w+) (%\w+)\n(\s*%\w+) = OpBitwiseAnd %uint \1 %cffff", - r"\1 = OpIMul %uint \2 \3\n\4 = OpCopyObject %uint \1", 1, - ref_word("v_mul_lo_u16", 0x00000101, 0x00000101)), - ("v_min_u16 drops high-half preservation", - "v_min_u16_e64 v0, v1, v2", 0x00000F0F, 0x000000FF, - r"OpBitwiseAnd %uint (%\w+) %cffff0000", r"OpBitwiseAnd %uint \1 %c0", 1, - ref_word("v_min_u16", 0x00000F0F, 0x000000FF)), - ] - for label, line, v1, v2, pattern, repl, want_count, want in controls: - with self.subTest(what=label): - good = translate_lines([ - f"v_mov_b32 v1, {v1:#x}", - f"v_mov_b32 v2, {v2:#x}", - f"v_mov_b32 v0, {OLD:#x}", - line, - "exp mrt0 v0, v0, v0, v0 done vm", - ]) - self.assertEqual(si.run_fragment(good)["%out_mrt0"][0], want) - bad, count = re.subn(pattern, repl, good) - self.assertEqual(count, want_count, f"unexpected match count for {pattern}") - self.assertNotEqual(si.run_fragment(bad)["%out_mrt0"][0], want) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_valu_ldexp_f64.py b/tests/semantic/test_valu_ldexp_f64.py deleted file mode 100644 index 6b96d0b92..000000000 --- a/tests/semantic/test_valu_ldexp_f64.py +++ /dev/null @@ -1,1644 +0,0 @@ -from __future__ import annotations - -"""Semantic interpreter tests and reference mathematical oracle for RDNA2 v_ldexp_f64. - -Instruction: - v_ldexp_f64 dst, src0, src1 (VOP3) - D.f64 = S0.f64 * (2 ^ S1.i32) - -Architecture: - - RDNA2 Vector ALU (GFX10) double-precision load exponent. - - S0: 64-bit IEEE 754 binary64 floating-point operand (VGPR pair, SGPR pair, or literal). - - S1: 32-bit signed two's complement integer exponent (VGPR, SGPR, or literal). - - D: 64-bit IEEE 754 binary64 floating-point destination (VGPR pair). - - Modifiers: - * Input modifiers on S0: abs (|S0|), neg (-S0). - * Output modifiers: clamp (clamps result to [0.0, 1.0]), omod (mul:2, mul:4, div:2). - -Translator-backed cases (SHADER-1039): a hand-written pixel-shader listing goes through -tools/rdna2spirv.py and is executed with tests/semantic/spirv_mini_interp.py. The lowering is pure 32-bit -integer work, so that interpreter can run it and the module carries no OpCapability Float64. The expected -words there are written by hand from the rules above, never taken from the oracle below, so a rule the -translator and the oracle share cannot hide a mistake. -""" - -from fractions import Fraction -import math -import os -import re -import struct -import sys -import unittest -from dataclasses import dataclass -from enum import Enum, auto - -sys.dont_write_bytecode = True -HERE = os.path.dirname(os.path.abspath(__file__)) -TESTS_DIR = os.path.dirname(HERE) -for _p in (HERE, TESTS_DIR): - if _p not in sys.path: - sys.path.insert(0, _p) -# The translator-backed cases at the end run a hand-written listing through tools/rdna2spirv.py, so the -# file is a translator regression test and not only a private oracle (SHADER-1039). -from support import mrt0_words, translate_lines # noqa: E402 (tests/semantic is sys.path, see above) -import rdna2spirv # noqa: E402 - -MASK32 = 0xFFFFFFFF -MASK64 = 0xFFFFFFFFFFFFFFFF - -SIGN_MASK_F64 = 0x8000000000000000 -EXP_MASK_F64 = 0x7FF0000000000000 -MANT_MASK_F64 = 0x000FFFFFFFFFFFFF -BIAS_F64 = 1023 - -POS_ZERO_F64 = 0x0000000000000000 -NEG_ZERO_F64 = 0x8000000000000000 -POS_INF_F64 = 0x7FF0000000000000 -NEG_INF_F64 = 0xFFF0000000000000 -QNAN_F64 = 0x7FF8000000000000 -SNAN_F64 = 0x7FF0000000000001 - -ONE_F64 = 0x3FF0000000000000 # 1.0 -TWO_F64 = 0x4000000000000000 # 2.0 -HALF_F64 = 0x3FE0000000000000 # 0.5 -MAX_FINITE_F64 = 0x7FEFFFFFFFFFFFFF # ~1.7976931348623157e+308 -MIN_NORMAL_F64 = 0x0010000000000000 # 2^-1022 (~2.2250738585072014e-308) -MAX_SUBNORMAL_F64 = 0x000FFFFFFFFFFFFF -MIN_SUBNORMAL_F64 = 0x0000000000000001 # 2^-1074 (~4.9406564584124654e-324) - - -def u32(val: int) -> int: - """Normalize integer to unsigned 32-bit dword.""" - return val & MASK32 - - -def u64(val: int) -> int: - """Normalize integer to unsigned 64-bit qword.""" - return val & MASK64 - - -def s32(val: int) -> int: - """Interpret a 32-bit unsigned dword as a signed two's-complement integer.""" - val &= MASK32 - return val - (1 << 32) if (val & 0x80000000) else val - - -def s64(val: int) -> int: - """Interpret a 64-bit unsigned qword as a signed two's-complement integer.""" - val &= MASK64 - return val - (1 << 64) if (val & (1 << 63)) else val - - -def split_dwords(val64: int) -> tuple[int, int]: - """Split an unsigned 64-bit integer into (low_dword, high_dword).""" - val = val64 & MASK64 - return val & MASK32, (val >> 32) & MASK32 - - -def join_dwords(lo: int, hi: int) -> int: - """Join (low_dword, high_dword) into an unsigned 64-bit integer.""" - return ((hi & MASK32) << 32) | (lo & MASK32) - - -def bits_to_f64(bits: int) -> float: - """Unpack an unsigned 64-bit integer into an IEEE 754 double precision float.""" - return struct.unpack(" int: - """Pack an IEEE 754 double precision float into an unsigned 64-bit integer word.""" - if math.isnan(val): - return QNAN_F64 - try: - return struct.unpack(" bool: - """Check if binary64 bit pattern represents any NaN.""" - return ((bits & EXP_MASK_F64) == EXP_MASK_F64) and ((bits & MANT_MASK_F64) != 0) - - -def is_inf_f64(bits: int) -> bool: - """Check if binary64 bit pattern represents +/- infinity.""" - return ((bits & EXP_MASK_F64) == EXP_MASK_F64) and ((bits & MANT_MASK_F64) == 0) - - -def is_zero_f64(bits: int) -> bool: - """Check if binary64 bit pattern represents +/- 0.0.""" - return (bits & ~SIGN_MASK_F64) == 0 - - -def is_subnormal_f64(bits: int) -> bool: - """Check if binary64 bit pattern represents a subnormal float.""" - return ((bits & EXP_MASK_F64) == 0) and ((bits & MANT_MASK_F64) != 0) - - -def is_normal_f64(bits: int) -> bool: - """Check if binary64 bit pattern represents a normalized finite float.""" - exp = (bits & EXP_MASK_F64) >> 52 - return 1 <= exp <= 2046 - - -def ref_ldexp_f64( - src0_bits: int, - src1_i32: int, - *, - clamp: bool = False, - abs_src0: bool = False, - neg_src0: bool = False, - omod: str = "none", -) -> int: - """Bit-accurate reference mathematical oracle for RDNA2 v_ldexp_f64. - - Computes: D = S0 * 2^S1 - Where S0 is IEEE 754 binary64 and S1 is signed 32-bit integer. - """ - src0_bits &= MASK64 - scale = s32(src1_i32) - - if abs_src0: - src0_bits &= ~SIGN_MASK_F64 - if neg_src0: - src0_bits ^= SIGN_MASK_F64 - - sign = (src0_bits >> 63) & 1 - exp_field = (src0_bits >> 52) & 0x7FF - mant_field = src0_bits & MANT_MASK_F64 - - # 1. NaN handling - if exp_field == 0x7FF and mant_field != 0: - if clamp: - return POS_ZERO_F64 - # Quiet the NaN if signaling - return src0_bits | 0x0008000000000000 - - # 2. Infinity handling - if exp_field == 0x7FF and mant_field == 0: - if clamp: - return POS_ZERO_F64 if sign else ONE_F64 - return src0_bits - - # 3. Zero handling (+/- 0.0) - if exp_field == 0 and mant_field == 0: - if clamp and sign: - return POS_ZERO_F64 - return src0_bits - - # 4. Extract mantissa and unbiased exponent - if exp_field == 0: - # Subnormal input - F = mant_field - E = -1022 - shift_left = 52 - (F.bit_length() - 1) - F = F << shift_left - E = E - shift_left - else: - # Normal input - E = exp_field - BIAS_F64 - F = (1 << 52) | mant_field - - # Apply omod multiplier to exponent - omod_exp_shift = 0 - if omod == "mul:2": - omod_exp_shift = 1 - elif omod == "mul:4": - omod_exp_shift = 2 - elif omod == "div:2": - omod_exp_shift = -1 - - E_scaled = E + scale + omod_exp_shift - target_exp = E_scaled + BIAS_F64 - - # 5. Overflow check - if target_exp >= 2047: - if clamp: - return POS_ZERO_F64 if sign else ONE_F64 - return (sign << 63) | POS_INF_F64 - - # 6. Normal float range - if target_exp >= 1: - res = (sign << 63) | (target_exp << 52) | (F & MANT_MASK_F64) - if clamp: - if sign: - return POS_ZERO_F64 - if res > ONE_F64: - return ONE_F64 - return res - - # 7. Subnormal range / Gradual underflow (round-to-nearest-even) - shift_right = 1 - target_exp - if shift_right > 55: - # Complete underflow - return POS_ZERO_F64 if (clamp and sign) else (sign << 63) - - q = F >> shift_right - mask = (1 << shift_right) - 1 - half = 1 << (shift_right - 1) - remainder = F & mask - - # Round to nearest even - if remainder > half: - q += 1 - elif remainder == half: - if q & 1: - q += 1 - - if q >= (1 << 52): - # Rounded up into normal range (min normal) - res = (sign << 63) | (1 << 52) - else: - res = (sign << 63) | (q & MANT_MASK_F64) - - if clamp: - if sign: - return POS_ZERO_F64 - if res > ONE_F64: - return ONE_F64 - return res - - -def ref_ldexp_f64_rational(src0_bits: int, src1_i32: int) -> int: - """Exact rational mathematical oracle using fractions.Fraction.""" - src0_bits &= MASK64 - scale = s32(src1_i32) - - if is_nan_f64(src0_bits): - return src0_bits | 0x0008000000000000 - if is_inf_f64(src0_bits) or is_zero_f64(src0_bits): - return src0_bits - - sign = (src0_bits >> 63) & 1 - exp_field = (src0_bits >> 52) & 0x7FF - mant_field = src0_bits & MANT_MASK_F64 - - if exp_field == 0: - frac = Fraction(mant_field, 1 << 52) * (Fraction(2) ** -1022) - else: - frac = (Fraction(1) + Fraction(mant_field, 1 << 52)) * (Fraction(2) ** (exp_field - 1023)) - - scaled_frac = frac * (Fraction(2) ** scale) - scaled_float = float(scaled_frac) - res_bits = f64_to_bits(scaled_float) - if sign: - res_bits |= SIGN_MASK_F64 - return res_bits - - -class DataType(Enum): - """Data types supported by RDNA2 VALU instructions.""" - F64 = auto() - I32 = auto() - U32 = auto() - U64 = auto() - - -class OperandKind(Enum): - """Classification of instruction operands.""" - VGPR_PAIR = auto() - VGPR_SINGLE = auto() - SGPR_PAIR = auto() - SGPR_SINGLE = auto() - LITERAL_I32 = auto() - LITERAL_F64 = auto() - INLINE_CONST = auto() - - -@dataclass -class Operand: - """Typed operand representation in symbolic AST.""" - kind: OperandKind - data_type: DataType - reg_index: int = 0 - literal_val: int = 0 - abs_mod: bool = False - neg_mod: bool = False - - def validate(self) -> None: - if self.kind in (OperandKind.VGPR_PAIR, OperandKind.VGPR_SINGLE): - limit = 255 if self.kind == OperandKind.VGPR_PAIR else 256 - if not (0 <= self.reg_index < limit): - raise ValueError(f"VGPR index {self.reg_index} out of valid range [0, {limit})") - elif self.kind in (OperandKind.SGPR_PAIR, OperandKind.SGPR_SINGLE): - limit = 105 if self.kind == OperandKind.SGPR_PAIR else 106 - if not (0 <= self.reg_index < limit): - raise ValueError(f"SGPR index {self.reg_index} out of valid range [0, {limit})") - - def to_asm(self) -> str: - s = "" - if self.kind == OperandKind.VGPR_PAIR: - s = f"v[{self.reg_index}:{self.reg_index + 1}]" - elif self.kind == OperandKind.VGPR_SINGLE: - s = f"v{self.reg_index}" - elif self.kind == OperandKind.SGPR_PAIR: - s = f"s[{self.reg_index}:{self.reg_index + 1}]" - elif self.kind == OperandKind.SGPR_SINGLE: - s = f"s{self.reg_index}" - elif self.kind == OperandKind.LITERAL_I32: - s = str(s32(self.literal_val)) - elif self.kind == OperandKind.LITERAL_F64: - s = f"{bits_to_f64(self.literal_val)}" - elif self.kind == OperandKind.INLINE_CONST: - s = str(self.literal_val) - - if self.abs_mod: - s = f"|{s}|" - if self.neg_mod: - s = f"-{s}" - return s - - -@dataclass -class InstructionAST: - """Symbolic AST node for v_ldexp_f64.""" - opcode: str - dst: Operand - src0: Operand - src1: Operand - clamp: bool = False - omod: str = "none" - - def validate(self) -> None: - if self.opcode != "v_ldexp_f64": - raise ValueError(f"Unsupported opcode {self.opcode}") - if self.dst.kind != OperandKind.VGPR_PAIR or self.dst.data_type != DataType.F64: - raise TypeError("Destination must be a 64-bit VGPR pair (DataType.F64)") - if self.dst.abs_mod or self.dst.neg_mod: - raise ValueError("Destination does not support input modifiers") - if self.src0.data_type != DataType.F64: - raise TypeError("src0 must be DataType.F64") - if self.src1.data_type != DataType.I32: - raise TypeError("src1 must be DataType.I32") - if self.src1.abs_mod or self.src1.neg_mod: - raise ValueError("src1 (integer exponent) does not support float abs/neg modifiers") - if self.omod not in ("none", "mul:2", "mul:4", "div:2"): - raise ValueError(f"Invalid omod modifier '{self.omod}'") - self.dst.validate() - self.src0.validate() - self.src1.validate() - - def to_asm(self) -> str: - tokens = [f"{self.opcode} {self.dst.to_asm()}, {self.src0.to_asm()}, {self.src1.to_asm()}"] - if self.clamp: - tokens.append("clamp") - if self.omod != "none": - tokens.append(self.omod) - return " ".join(tokens) - - -def parse_vop3_ldexp_f64(asm_line: str) -> InstructionAST: - """Parse assembly string into an InstructionAST.""" - line = asm_line.strip() - if not line.startswith("v_ldexp_f64"): - raise ValueError(f"Expected instruction starting with 'v_ldexp_f64', got: {line}") - - # Remove comments - if ";" in line: - line = line.split(";", 1)[0].strip() - if "//" in line: - line = line.split("//", 1)[0].strip() - - parts = line.split(None, 1) - if len(parts) < 2: - raise ValueError(f"Incomplete instruction: {line}") - - opcode = parts[0] - rest = parts[1] - - # Tokenize operands and modifiers - tokens = [t.strip() for t in rest.split(",") if t.strip()] - if len(tokens) < 3: - raise ValueError(f"v_ldexp_f64 requires 3 operand sections, got: {len(tokens)}") - - dst_str = tokens[0] - src0_str = tokens[1] - last_section = tokens[2].split() - src1_str = last_section[0] - mod_tokens = [m.lower() for m in last_section[1:]] - - clamp = "clamp" in mod_tokens - omod = "none" - for m in mod_tokens: - if m in ("mul:2", "mul:4", "div:2"): - omod = m - - # Parse DST - m_dst = re.match(r"^v\[(\d+):(\d+)\]$", dst_str.strip()) - if not m_dst: - raise ValueError(f"Invalid 64-bit VGPR destination format: {dst_str}") - d_lo, d_hi = int(m_dst.group(1)), int(m_dst.group(2)) - if d_hi != d_lo + 1: - raise ValueError(f"Destination register pair must be contiguous: {dst_str}") - dst_op = Operand(kind=OperandKind.VGPR_PAIR, data_type=DataType.F64, reg_index=d_lo) - - # Parse SRC0 - s0_str = src0_str.strip() - neg_s0 = False - abs_s0 = False - if s0_str.startswith("-"): - neg_s0 = True - s0_str = s0_str[1:].strip() - if s0_str.startswith("|") and s0_str.endswith("|"): - abs_s0 = True - s0_str = s0_str[1:-1].strip() - - m_v0 = re.match(r"^v\[(\d+):(\d+)\]$", s0_str) - m_s0 = re.match(r"^s\[(\d+):(\d+)\]$", s0_str) - if m_v0: - lo, hi = int(m_v0.group(1)), int(m_v0.group(2)) - if hi != lo + 1: - raise ValueError(f"Source register pair must be contiguous: {s0_str}") - src0_op = Operand( - kind=OperandKind.VGPR_PAIR, - data_type=DataType.F64, - reg_index=lo, - abs_mod=abs_s0, - neg_mod=neg_s0, - ) - elif m_s0: - lo, hi = int(m_s0.group(1)), int(m_s0.group(2)) - if hi != lo + 1: - raise ValueError(f"Source register pair must be contiguous: {s0_str}") - src0_op = Operand( - kind=OperandKind.SGPR_PAIR, - data_type=DataType.F64, - reg_index=lo, - abs_mod=abs_s0, - neg_mod=neg_s0, - ) - else: - # Literal float or hex constant - try: - if s0_str.startswith("0x") or s0_str.startswith("0X"): - val64 = int(s0_str, 16) - else: - val64 = f64_to_bits(float(s0_str)) - src0_op = Operand( - kind=OperandKind.LITERAL_F64, - data_type=DataType.F64, - literal_val=val64, - abs_mod=abs_s0, - neg_mod=neg_s0, - ) - except ValueError: - raise ValueError(f"Unrecognized src0 operand format: {s0_str}") - - # Parse SRC1 (i32) - s1_str = src1_str.strip() - m_v1 = re.match(r"^v(\d+)$", s1_str) - m_s1 = re.match(r"^s(\d+)$", s1_str) - if m_v1: - src1_op = Operand(kind=OperandKind.VGPR_SINGLE, data_type=DataType.I32, reg_index=int(m_v1.group(1))) - elif m_s1: - src1_op = Operand(kind=OperandKind.SGPR_SINGLE, data_type=DataType.I32, reg_index=int(m_s1.group(1))) - else: - # Literal integer - if s1_str.startswith("0x") or s1_str.startswith("0X"): - lit_val = int(s1_str, 16) - else: - lit_val = int(s1_str) - src1_op = Operand(kind=OperandKind.LITERAL_I32, data_type=DataType.I32, literal_val=lit_val) - - ast = InstructionAST( - opcode=opcode, - dst=dst_op, - src0=src0_op, - src1=src1_op, - clamp=clamp, - omod=omod, - ) - ast.validate() - return ast - - -class ScalarVALUInterpreter: - """Deterministic scalar instruction interpreter for RDNA2 VALU instructions.""" - - def __init__(self) -> None: - self.num_vgprs = 256 - self.num_sgprs = 106 - self.vgpr = [0] * self.num_vgprs - self.sgpr = [0] * self.num_sgprs - self.vcc = 0 - self.exec = MASK64 - self.status_flags = FPStatusFlags() - - def reset(self) -> None: - self.vgpr = [0] * self.num_vgprs - self.sgpr = [0] * self.num_sgprs - self.vcc = 0 - self.exec = MASK64 - self.status_flags = FPStatusFlags() - - def get_vgpr_u32(self, idx: int) -> int: - if not (0 <= idx < self.num_vgprs): - raise IndexError(f"VGPR index {idx} out of range [0, {self.num_vgprs})") - return self.vgpr[idx] & MASK32 - - def set_vgpr_u32(self, idx: int, val: int) -> None: - if not (0 <= idx < self.num_vgprs): - raise IndexError(f"VGPR index {idx} out of range [0, {self.num_vgprs})") - self.vgpr[idx] = val & MASK32 - - def get_vgpr_u64(self, idx: int) -> int: - if not (0 <= idx < self.num_vgprs - 1): - raise IndexError(f"64-bit VGPR base {idx} out of range [0, {self.num_vgprs - 1})") - lo = self.get_vgpr_u32(idx) - hi = self.get_vgpr_u32(idx + 1) - return join_dwords(lo, hi) - - def set_vgpr_u64(self, idx: int, val64: int) -> None: - if not (0 <= idx < self.num_vgprs - 1): - raise IndexError(f"64-bit VGPR base {idx} out of range [0, {self.num_vgprs - 1})") - lo, hi = split_dwords(val64) - self.set_vgpr_u32(idx, lo) - self.set_vgpr_u32(idx + 1, hi) - - def get_sgpr_u32(self, idx: int) -> int: - if not (0 <= idx < self.num_sgprs): - raise IndexError(f"SGPR index {idx} out of range [0, {self.num_sgprs})") - return self.sgpr[idx] & MASK32 - - def set_sgpr_u32(self, idx: int, val: int) -> None: - if not (0 <= idx < self.num_sgprs): - raise IndexError(f"SGPR index {idx} out of range [0, {self.num_sgprs})") - self.sgpr[idx] = val & MASK32 - - def get_sgpr_u64(self, idx: int) -> int: - if not (0 <= idx < self.num_sgprs - 1): - raise IndexError(f"64-bit SGPR base {idx} out of range [0, {self.num_sgprs - 1})") - lo = self.get_sgpr_u32(idx) - hi = self.get_sgpr_u32(idx + 1) - return join_dwords(lo, hi) - - def set_sgpr_u64(self, idx: int, val64: int) -> None: - if not (0 <= idx < self.num_sgprs - 1): - raise IndexError(f"64-bit SGPR base {idx} out of range [0, {self.num_sgprs - 1})") - lo, hi = split_dwords(val64) - self.set_sgpr_u32(idx, lo) - self.set_sgpr_u32(idx + 1, hi) - - def eval_operand_f64(self, op: Operand) -> int: - if op.data_type != DataType.F64: - raise TypeError(f"Expected DataType.F64, got {op.data_type}") - if op.kind == OperandKind.VGPR_PAIR: - val = self.get_vgpr_u64(op.reg_index) - elif op.kind == OperandKind.SGPR_PAIR: - val = self.get_sgpr_u64(op.reg_index) - elif op.kind == OperandKind.LITERAL_F64: - val = op.literal_val & MASK64 - else: - raise ValueError(f"Unsupported operand kind for f64: {op.kind}") - - if op.abs_mod: - val &= ~SIGN_MASK_F64 - if op.neg_mod: - val ^= SIGN_MASK_F64 - return val - - def eval_operand_i32(self, op: Operand) -> int: - if op.data_type != DataType.I32: - raise TypeError(f"Expected DataType.I32, got {op.data_type}") - if op.kind == OperandKind.VGPR_SINGLE: - return s32(self.get_vgpr_u32(op.reg_index)) - elif op.kind == OperandKind.SGPR_SINGLE: - return s32(self.get_sgpr_u32(op.reg_index)) - elif op.kind in (OperandKind.LITERAL_I32, OperandKind.INLINE_CONST): - return s32(op.literal_val) - else: - raise ValueError(f"Unsupported operand kind for i32: {op.kind}") - - def execute(self, ast: InstructionAST) -> int: - ast.validate() - if ast.opcode == "v_ldexp_f64": - s0_val = self.eval_operand_f64(ast.src0) - s1_val = self.eval_operand_i32(ast.src1) - res = ref_ldexp_f64( - s0_val, - s1_val, - clamp=ast.clamp, - omod=ast.omod, - ) - # Track FP status flags - flags = calc_ldexp_f64_status_flags(s0_val, s1_val, res) - self.status_flags.merge(flags) - self.set_vgpr_u64(ast.dst.reg_index, res) - return res - raise NotImplementedError(f"Opcode {ast.opcode} not implemented in scalar interpreter") - - def execute_asm(self, asm_line: str) -> int: - ast = parse_vop3_ldexp_f64(asm_line) - return self.execute(ast) - - -@dataclass -class FPStatusFlags: - """IEEE 754 floating-point status exception flags.""" - invalid: bool = False - div_by_zero: bool = False - overflow: bool = False - underflow: bool = False - inexact: bool = False - - def merge(self, other: FPStatusFlags) -> None: - self.invalid |= other.invalid - self.div_by_zero |= other.div_by_zero - self.overflow |= other.overflow - self.underflow |= other.underflow - self.inexact |= other.inexact - - -def is_snan_f64(bits: int) -> bool: - """Check if binary64 bits represent a signaling NaN.""" - if not is_nan_f64(bits): - return False - # Quiet bit is bit 51 (MSB of mantissa). If 0, it is signaling NaN. - return ((bits >> 51) & 1) == 0 - - -def calc_ldexp_f64_status_flags(src0_bits: int, src1_i32: int, res_bits: int) -> FPStatusFlags: - """Determine IEEE 754 exception flags for v_ldexp_f64 computation.""" - flags = FPStatusFlags() - scale = s32(src1_i32) - - # Signaling NaN generates invalid exception - if is_snan_f64(src0_bits): - flags.invalid = True - return flags - - if is_nan_f64(src0_bits) or is_inf_f64(src0_bits) or is_zero_f64(src0_bits): - return flags - - # Non-zero finite operand - if is_inf_f64(res_bits): - flags.overflow = True - flags.inexact = True - elif is_subnormal_f64(res_bits): - flags.underflow = True - # Check if inexact - exp_field = (src0_bits >> 52) & 0x7FF - orig_exp = (exp_field - BIAS_F64) if exp_field != 0 else -1022 - if (orig_exp + scale) < -1074: - flags.inexact = True - else: - # Check if bits were rounded - shift = 1 - ((orig_exp + scale) + BIAS_F64) - mant = src0_bits & MANT_MASK_F64 - if exp_field != 0: - mant |= (1 << 52) - if shift > 0 and (mant & ((1 << shift) - 1)) != 0: - flags.inexact = True - elif is_zero_f64(res_bits): - flags.underflow = True - flags.inexact = True - - return flags - - -class SIMDVALUInterpreter: - """SIMD multi-lane execution model supporting Wave32 and Wave64 with EXEC masking.""" - - def __init__(self, wave_size: int = 64) -> None: - if wave_size not in (32, 64): - raise ValueError(f"Invalid wave_size: {wave_size}. Must be 32 or 64.") - self.wave_size = wave_size - self.num_vgprs = 256 - self.num_sgprs = 106 - self.vgpr = [[0] * self.wave_size for _ in range(self.num_vgprs)] - self.sgpr = [0] * self.num_sgprs - self.vcc = 0 - self.exec = (1 << self.wave_size) - 1 - self.status_flags = FPStatusFlags() - - def reset(self) -> None: - self.vgpr = [[0] * self.wave_size for _ in range(self.num_vgprs)] - self.sgpr = [0] * self.num_sgprs - self.vcc = 0 - self.exec = (1 << self.wave_size) - 1 - self.status_flags = FPStatusFlags() - - def get_vgpr_u32(self, reg: int, lane: int) -> int: - if not (0 <= reg < self.num_vgprs): - raise IndexError(f"VGPR index {reg} out of range [0, {self.num_vgprs})") - if not (0 <= lane < self.wave_size): - raise IndexError(f"Lane {lane} out of range [0, {self.wave_size})") - return self.vgpr[reg][lane] & MASK32 - - def set_vgpr_u32(self, reg: int, lane: int, val: int) -> None: - if not (0 <= reg < self.num_vgprs): - raise IndexError(f"VGPR index {reg} out of range [0, {self.num_vgprs})") - if not (0 <= lane < self.wave_size): - raise IndexError(f"Lane {lane} out of range [0, {self.wave_size})") - self.vgpr[reg][lane] = val & MASK32 - - def get_vgpr_u64(self, reg_base: int, lane: int) -> int: - if not (0 <= reg_base < self.num_vgprs - 1): - raise IndexError(f"64-bit VGPR base {reg_base} out of range [0, {self.num_vgprs - 1})") - lo = self.get_vgpr_u32(reg_base, lane) - hi = self.get_vgpr_u32(reg_base + 1, lane) - return join_dwords(lo, hi) - - def set_vgpr_u64(self, reg_base: int, lane: int, val64: int) -> None: - if not (0 <= reg_base < self.num_vgprs - 1): - raise IndexError(f"64-bit VGPR base {reg_base} out of range [0, {self.num_vgprs - 1})") - lo, hi = split_dwords(val64) - self.set_vgpr_u32(reg_base, lane, lo) - self.set_vgpr_u32(reg_base + 1, lane, hi) - - def get_sgpr_u32(self, reg: int) -> int: - if not (0 <= reg < self.num_sgprs): - raise IndexError(f"SGPR index {reg} out of range [0, {self.num_sgprs})") - return self.sgpr[reg] & MASK32 - - def set_sgpr_u32(self, reg: int, val: int) -> None: - if not (0 <= reg < self.num_sgprs): - raise IndexError(f"SGPR index {reg} out of range [0, {self.num_sgprs})") - self.sgpr[reg] = val & MASK32 - - def get_sgpr_u64(self, reg_base: int) -> int: - if not (0 <= reg_base < self.num_sgprs - 1): - raise IndexError(f"64-bit SGPR base {reg_base} out of range [0, {self.num_sgprs - 1})") - lo = self.get_sgpr_u32(reg_base) - hi = self.get_sgpr_u32(reg_base + 1) - return join_dwords(lo, hi) - - def set_sgpr_u64(self, reg_base: int, val64: int) -> None: - if not (0 <= reg_base < self.num_sgprs - 1): - raise IndexError(f"64-bit SGPR base {reg_base} out of range [0, {self.num_sgprs - 1})") - lo, hi = split_dwords(val64) - self.set_sgpr_u32(reg_base, lo) - self.set_sgpr_u32(reg_base + 1, hi) - - def eval_operand_f64_lane(self, op: Operand, lane: int) -> int: - if op.kind == OperandKind.VGPR_PAIR: - val = self.get_vgpr_u64(op.reg_index, lane) - elif op.kind == OperandKind.SGPR_PAIR: - val = self.get_sgpr_u64(op.reg_index) - elif op.kind == OperandKind.LITERAL_F64: - val = op.literal_val & MASK64 - else: - raise ValueError(f"Unsupported operand kind for f64: {op.kind}") - - if op.abs_mod: - val &= ~SIGN_MASK_F64 - if op.neg_mod: - val ^= SIGN_MASK_F64 - return val - - def eval_operand_i32_lane(self, op: Operand, lane: int) -> int: - if op.kind == OperandKind.VGPR_SINGLE: - return s32(self.get_vgpr_u32(op.reg_index, lane)) - elif op.kind == OperandKind.SGPR_SINGLE: - return s32(self.get_sgpr_u32(op.reg_index)) - elif op.kind in (OperandKind.LITERAL_I32, OperandKind.INLINE_CONST): - return s32(op.literal_val) - else: - raise ValueError(f"Unsupported operand kind for i32: {op.kind}") - - def execute(self, ast: InstructionAST) -> list[int]: - ast.validate() - results: list[int] = [] - effective_exec = self.exec & ((1 << self.wave_size) - 1) - - # Latch inputs across all lanes before write-back (hardware pipeline semantics) - src0_latched = [0] * self.wave_size - src1_latched = [0] * self.wave_size - - for lane in range(self.wave_size): - if (effective_exec >> lane) & 1: - src0_latched[lane] = self.eval_operand_f64_lane(ast.src0, lane) - src1_latched[lane] = self.eval_operand_i32_lane(ast.src1, lane) - - # Compute and write back - for lane in range(self.wave_size): - if not ((effective_exec >> lane) & 1): - results.append(self.get_vgpr_u64(ast.dst.reg_index, lane)) - continue - - res = ref_ldexp_f64( - src0_latched[lane], - src1_latched[lane], - clamp=ast.clamp, - omod=ast.omod, - ) - # Accumulate FP flags across active lanes - flags = calc_ldexp_f64_status_flags(src0_latched[lane], src1_latched[lane], res) - self.status_flags.merge(flags) - self.set_vgpr_u64(ast.dst.reg_index, lane, res) - results.append(res) - - return results - - def execute_asm(self, asm_line: str) -> list[int]: - ast = parse_vop3_ldexp_f64(asm_line) - return self.execute(ast) - - -# --- Mutated Oracles for Mutation Testing and Negative Controls --- - -def mutant_bias_off_by_one(src0: int, src1: int) -> int: - """Mutant A: uses incorrect bias 1022 instead of 1023 on re-bias.""" - scale = s32(src1) - exp = ((src0 >> 52) & 0x7FF) - BIAS_F64 - rebiased = exp + scale + 1022 # Off by one: 1022 instead of 1023 - return (src0 & SIGN_MASK_F64) | (rebiased << 52) | (src0 & MANT_MASK_F64) - - -def mutant_flush_subnormal(src0: int, src1: int) -> int: - """Mutant B: prematurely flushes all subnormals to zero.""" - res = ref_ldexp_f64(src0, src1) - if is_subnormal_f64(res): - return src0 & SIGN_MASK_F64 - return res - - -def mutant_no_clamp(src0: int, src1: int) -> int: - """Mutant C: ignores clamp modifier.""" - return ref_ldexp_f64(src0, src1, clamp=False) - - -def mutant_truncation_rounding(src0: int, src1: int) -> int: - """Mutant D: uses truncation (round toward zero) instead of round-to-nearest-even.""" - scale = s32(src1) - exp_field = (src0 >> 52) & 0x7FF - mant_field = src0 & MANT_MASK_F64 - sign = (src0 >> 63) & 1 - E = (exp_field - BIAS_F64) if exp_field != 0 else -1022 - F = (1 << 52) | mant_field if exp_field != 0 else mant_field - target_exp = E + scale + BIAS_F64 - if target_exp < 1: - shift_right = 1 - target_exp - q = F >> shift_right # purely truncated without rounding - return (sign << 63) | (q & MANT_MASK_F64) - return ref_ldexp_f64(src0, src1) - - -def mutant_leak_vcc(interp: ScalarVALUInterpreter, ast: InstructionAST) -> None: - """Mutant E: improperly corrupts VCC register during VALU FP execution.""" - interp.execute(ast) - interp.vcc ^= 0x1 - - -def mutant_exec_leak(sim: SIMDVALUInterpreter, ast: InstructionAST) -> None: - """Mutant F: writes inactive lanes under EXEC mask.""" - sim.execute(ast) - # Overwrite lane 0 regardless of EXEC - sim.set_vgpr_u64(ast.dst.reg_index, 0, 0x1234567890ABCDEF) - - -class TestValuLdexpF64NegativeControlsAndMutations(unittest.TestCase): - """Negative controls, syntax rejection, and mutation detection for v_ldexp_f64.""" - - def test_syntax_rejection_invalid_opcode(self): - with self.assertRaises(ValueError): - parse_vop3_ldexp_f64("v_add_f64 v[0:1], v[2:3], v4") - - def test_syntax_rejection_insufficient_operands(self): - with self.assertRaises(ValueError): - parse_vop3_ldexp_f64("v_ldexp_f64 v[0:1], v[2:3]") - - def test_syntax_rejection_non_contiguous_dst(self): - with self.assertRaises(ValueError): - parse_vop3_ldexp_f64("v_ldexp_f64 v[0:2], v[2:3], v4") - - def test_syntax_rejection_non_contiguous_src0(self): - with self.assertRaises(ValueError): - parse_vop3_ldexp_f64("v_ldexp_f64 v[0:1], v[2:4], v4") - - def test_syntax_rejection_out_of_range_registers(self): - with self.assertRaises(ValueError): - parse_vop3_ldexp_f64("v_ldexp_f64 v[255:256], v[2:3], v4") - with self.assertRaises(ValueError): - parse_vop3_ldexp_f64("v_ldexp_f64 v[0:1], s[105:106], v4") - - def test_syntax_rejection_invalid_modifier(self): - # Invalid omod - with self.assertRaises(ValueError): - ast = parse_vop3_ldexp_f64("v_ldexp_f64 v[0:1], v[2:3], v4") - ast.omod = "mul:3" - ast.validate() - - def test_syntax_rejection_invalid_types(self): - # Single VGPR as destination (must be 64-bit pair) - with self.assertRaises(ValueError): - parse_vop3_ldexp_f64("v_ldexp_f64 v0, v[2:3], v4") - # Single VGPR as src0 (must be 64-bit pair) - with self.assertRaises(ValueError): - parse_vop3_ldexp_f64("v_ldexp_f64 v[0:1], v2, v4") - - def test_mutation_detection_bias_off_by_one(self): - # Correct oracle gives 8.0 for 1.0 * 2^3 - correct = ref_ldexp_f64(ONE_F64, 3) - mutant = mutant_bias_off_by_one(ONE_F64, 3) - # Mutant computes with wrong bias, causing discrepancy - self.assertEqual(bits_to_f64(correct), 8.0) - # In fact, with exp = -1022 + 3 + 1022 = exp, it dropped scale or gave wrong exponent! - # Let's ensure discrepancy is caught - mutant_scaled = mutant_bias_off_by_one(ONE_F64, 1) - self.assertNotEqual(mutant_scaled, ref_ldexp_f64(ONE_F64, 1)) - - def test_mutation_detection_flush_subnormal(self): - # Subnormal must be preserved in IEEE mode, not flushed to zero - correct = ref_ldexp_f64(MIN_NORMAL_F64, -1) - self.assertTrue(is_subnormal_f64(correct)) - mutant = mutant_flush_subnormal(MIN_NORMAL_F64, -1) - self.assertEqual(mutant, POS_ZERO_F64) - self.assertNotEqual(correct, mutant) - - def test_mutation_detection_no_clamp(self): - val = f64_to_bits(4.0) - correct_clamped = ref_ldexp_f64(val, 0, clamp=True) - mutant = mutant_no_clamp(val, 0) - self.assertEqual(bits_to_f64(correct_clamped), 1.0) - self.assertEqual(bits_to_f64(mutant), 4.0) - self.assertNotEqual(correct_clamped, mutant) - - def test_mutation_detection_truncation_vs_tiesto_even(self): - # Odd remainder that rounds up under TiesToEven - f_odd = MIN_NORMAL_F64 | 2 - correct = ref_ldexp_f64(f_odd, -53) - mutant = mutant_truncation_rounding(f_odd, -53) - self.assertEqual(correct, MIN_SUBNORMAL_F64) - self.assertEqual(mutant, POS_ZERO_F64) - self.assertNotEqual(correct, mutant) - - def test_mutation_detection_corrupt_vcc(self): - interp = ScalarVALUInterpreter() - interp.vcc = 0x5555555555555555 - interp.set_vgpr_u64(2, ONE_F64) - interp.set_vgpr_u32(4, 1) - ast = parse_vop3_ldexp_f64("v_ldexp_f64 v[0:1], v[2:3], v4") - # Under normal execution VCC is preserved - interp.execute(ast) - self.assertEqual(interp.vcc, 0x5555555555555555) - # Mutant corrupts VCC - mutant_leak_vcc(interp, ast) - self.assertNotEqual(interp.vcc, 0x5555555555555555) - - def test_mutation_detection_exec_mask_leak(self): - sim = SIMDVALUInterpreter(wave_size=32) - sim.exec = 0x0 # all lanes disabled - sim.set_vgpr_u64(0, 0, 0xAAAAAAAAAAAAAAAA) - ast = parse_vop3_ldexp_f64("v_ldexp_f64 v[0:1], v[2:3], v4") - # Normal execution preserves lane 0 - sim.execute(ast) - self.assertEqual(sim.get_vgpr_u64(0, 0), 0xAAAAAAAAAAAAAAAA) - # Mutant writes inactive lane - mutant_exec_leak(sim, ast) - self.assertNotEqual(sim.get_vgpr_u64(0, 0), 0xAAAAAAAAAAAAAAAA) - - -class TestValuLdexpF64IEEE754Boundaries(unittest.TestCase): - """Deep verification of IEEE 754 boundary extremes, subnormals, and NaN handling.""" - - def test_subnormal_exact_tiesto_even_rounding(self): - # Construct an unscaled float that underflows to a half-way tie in subnormal range - # Min normal is 2^-1022 (exp_field = 1, mant = 0). - # Scale = -53 -> target_exp = -52 -> shift_right = 53. - # Mantissa F has 53 bits (1 << 52). - # Shifted by 53: q = 0, remainder = 1 << 52, half = 1 << 52. - # This is an exact half-way tie with q = 0 (even)! - # In TiesToEven rounding, it rounds down to 0! - res_even = ref_ldexp_f64(MIN_NORMAL_F64, -53) - self.assertEqual(res_even, POS_ZERO_F64) - - # Now test with F = (1 << 52) | (1 << 1), so after shift by 53, - # remainder > half, so it rounds up to 1 (MIN_SUBNORMAL_F64)! - f_odd = MIN_NORMAL_F64 | 2 - res_odd = ref_ldexp_f64(f_odd, -53) - self.assertEqual(res_odd, MIN_SUBNORMAL_F64) - - def test_subnormal_scaling_transitions(self): - # Scaling MIN_SUBNORMAL (2^-1074) up to normal range - res = ref_ldexp_f64(MIN_SUBNORMAL_F64, 52) - self.assertEqual(res, MIN_NORMAL_F64) - self.assertEqual(bits_to_f64(res), 2.2250738585072014e-308) - - # Scaling MAX_SUBNORMAL up by 1 - res_max_sub = ref_ldexp_f64(MAX_SUBNORMAL_F64, 1) - self.assertTrue(is_normal_f64(res_max_sub)) - - # Scaling MIN_SUBNORMAL down by 1 -> rounds to 0 - res_sub_down = ref_ldexp_f64(MIN_SUBNORMAL_F64, -1) - self.assertEqual(res_sub_down, POS_ZERO_F64) - - def test_extreme_scale_integers(self): - # Extreme large positive exponents (e.g. 0x7FFFFFFF, 1000000) - for s in (0x7FFFFFFF, 1000000, 2048, 1024): - self.assertEqual(ref_ldexp_f64(ONE_F64, s), POS_INF_F64) - self.assertEqual(ref_ldexp_f64(ONE_F64 | SIGN_MASK_F64, s), NEG_INF_F64) - - # Extreme large negative exponents (e.g. -0x80000000, -1000000) - for s in (-0x80000000, -1000000, -2048, -1075): - self.assertEqual(ref_ldexp_f64(ONE_F64, s), POS_ZERO_F64) - self.assertEqual(ref_ldexp_f64(ONE_F64 | SIGN_MASK_F64, s), NEG_ZERO_F64) - - def test_max_finite_overflow_boundaries(self): - # MAX_FINITE with scale 0 is MAX_FINITE - self.assertEqual(ref_ldexp_f64(MAX_FINITE_F64, 0), MAX_FINITE_F64) - # MAX_FINITE with scale +1 overflows to +inf - self.assertEqual(ref_ldexp_f64(MAX_FINITE_F64, 1), POS_INF_F64) - # Negative MAX_FINITE with scale +1 overflows to -inf - self.assertEqual(ref_ldexp_f64(MAX_FINITE_F64 | SIGN_MASK_F64, 1), NEG_INF_F64) - - def test_signed_zero_preservation_under_extremes(self): - # +0.0 and -0.0 must be preserved for all scale values - for s in (-0x80000000, -1000, -1, 0, 1, 1000, 0x7FFFFFFF): - self.assertEqual(ref_ldexp_f64(POS_ZERO_F64, s), POS_ZERO_F64) - self.assertEqual(ref_ldexp_f64(NEG_ZERO_F64, s), NEG_ZERO_F64) - - def test_signed_infinity_preservation(self): - for s in (-1000, -1, 0, 1, 1000): - self.assertEqual(ref_ldexp_f64(POS_INF_F64, s), POS_INF_F64) - self.assertEqual(ref_ldexp_f64(NEG_INF_F64, s), NEG_INF_F64) - - def test_nan_payloads_and_quietening(self): - # Quiet NaN payload preserved - qnan_payload = QNAN_F64 | 0x0000000012345678 - res_qnan = ref_ldexp_f64(qnan_payload, 5) - self.assertTrue(is_nan_f64(res_qnan)) - self.assertEqual(res_qnan & 0x0000000012345678, 0x0000000012345678) - - # Signaling NaN quiet bit set - snan_payload = SNAN_F64 | 0x0000000087654321 - res_snan = ref_ldexp_f64(snan_payload, -3) - self.assertTrue(is_nan_f64(res_snan)) - self.assertFalse(is_snan_f64(res_snan), "Signaling NaN must be quieted") - - def test_clamp_behavior_on_all_special_values(self): - # NaNs clamp to +0.0 - self.assertEqual(ref_ldexp_f64(QNAN_F64, 0, clamp=True), POS_ZERO_F64) - self.assertEqual(ref_ldexp_f64(SNAN_F64, 0, clamp=True), POS_ZERO_F64) - # +inf clamps to 1.0, -inf clamps to +0.0 - self.assertEqual(ref_ldexp_f64(POS_INF_F64, 0, clamp=True), ONE_F64) - self.assertEqual(ref_ldexp_f64(NEG_INF_F64, 0, clamp=True), POS_ZERO_F64) - # -0.0 clamps to +0.0 - self.assertEqual(ref_ldexp_f64(NEG_ZERO_F64, 0, clamp=True), POS_ZERO_F64) - # Values > 1.0 clamp to 1.0 - self.assertEqual(ref_ldexp_f64(TWO_F64, 0, clamp=True), ONE_F64) - # Values < 0.0 clamp to +0.0 - self.assertEqual(ref_ldexp_f64(TWO_F64 | SIGN_MASK_F64, 0, clamp=True), POS_ZERO_F64) - - -class TestValuLdexpF64StatusFlags(unittest.TestCase): - """Unit tests for condition codes, status flags, and carry/borrow behavior.""" - - def test_vcc_strictly_preserved_scalar(self): - interp = ScalarVALUInterpreter() - initial_vcc = 0x123456789ABCDEF0 - interp.vcc = initial_vcc - interp.set_vgpr_u64(2, f64_to_bits(1.0)) - interp.set_vgpr_u32(4, 5) - - interp.execute_asm("v_ldexp_f64 v[0:1], v[2:3], v4") - self.assertEqual(interp.vcc, initial_vcc, "VCC must remain unmodified by v_ldexp_f64") - - def test_vcc_strictly_preserved_simd_wave64(self): - sim = SIMDVALUInterpreter(wave_size=64) - initial_vcc = 0xCAFEBABE0000FFFF - sim.vcc = initial_vcc - for lane in range(64): - sim.set_vgpr_u64(2, lane, f64_to_bits(2.0)) - sim.set_vgpr_u32(4, lane, 1) - - sim.execute_asm("v_ldexp_f64 v[0:1], v[2:3], v4") - self.assertEqual(sim.vcc, initial_vcc, "Wave64 VCC must remain untouched") - - def test_fp_flags_exact_normal_no_exceptions(self): - interp = ScalarVALUInterpreter() - interp.set_vgpr_u64(2, f64_to_bits(1.0)) - interp.set_vgpr_u32(4, 3) - interp.execute_asm("v_ldexp_f64 v[0:1], v[2:3], v4") - self.assertFalse(interp.status_flags.invalid) - self.assertFalse(interp.status_flags.overflow) - self.assertFalse(interp.status_flags.underflow) - self.assertFalse(interp.status_flags.inexact) - - def test_fp_flags_overflow(self): - interp = ScalarVALUInterpreter() - interp.set_vgpr_u64(2, MAX_FINITE_F64) - interp.set_vgpr_u32(4, 5) # Overflows to +inf - res = interp.execute_asm("v_ldexp_f64 v[0:1], v[2:3], v4") - self.assertEqual(res, POS_INF_F64) - self.assertTrue(interp.status_flags.overflow) - self.assertTrue(interp.status_flags.inexact) - - def test_fp_flags_underflow_subnormal(self): - interp = ScalarVALUInterpreter() - interp.set_vgpr_u64(2, MIN_NORMAL_F64) - interp.set_vgpr_u32(4, -2) # Underflows into subnormal - res = interp.execute_asm("v_ldexp_f64 v[0:1], v[2:3], v4") - self.assertTrue(is_subnormal_f64(res)) - self.assertTrue(interp.status_flags.underflow) - - def test_fp_flags_underflow_flush_to_zero(self): - interp = ScalarVALUInterpreter() - interp.set_vgpr_u64(2, MIN_NORMAL_F64) - interp.set_vgpr_u32(4, -100) # Complete underflow to 0.0 - res = interp.execute_asm("v_ldexp_f64 v[0:1], v[2:3], v4") - self.assertEqual(res, POS_ZERO_F64) - self.assertTrue(interp.status_flags.underflow) - self.assertTrue(interp.status_flags.inexact) - - def test_fp_flags_invalid_snan(self): - interp = ScalarVALUInterpreter() - interp.set_vgpr_u64(2, SNAN_F64) - interp.set_vgpr_u32(4, 0) - interp.execute_asm("v_ldexp_f64 v[0:1], v[2:3], v4") - self.assertTrue(interp.status_flags.invalid) - - def test_fp_flags_no_invalid_on_qnan(self): - interp = ScalarVALUInterpreter() - interp.set_vgpr_u64(2, QNAN_F64) - interp.set_vgpr_u32(4, 0) - interp.execute_asm("v_ldexp_f64 v[0:1], v[2:3], v4") - self.assertFalse(interp.status_flags.invalid) - - -class TestValuLdexpF64RegisterAliasing(unittest.TestCase): - """Unit tests for register aliasing and in-place operand preservation.""" - - def test_full_aliasing_dst_src0_scalar(self): - interp = ScalarVALUInterpreter() - # In-place scaling: v[0:1] = v_ldexp_f64 v[0:1], v2 - initial_val = 3.5 - interp.set_vgpr_u64(0, f64_to_bits(initial_val)) - interp.set_vgpr_u32(2, 2) - res = interp.execute_asm("v_ldexp_f64 v[0:1], v[0:1], v2") - self.assertEqual(bits_to_f64(res), 14.0) - self.assertEqual(bits_to_f64(interp.get_vgpr_u64(0)), 14.0) - - def test_aliasing_dst_low_src1_scalar(self): - interp = ScalarVALUInterpreter() - # v[0:1] = v_ldexp_f64 v[2:3], v0 (dst low overlaps src1) - interp.set_vgpr_u32(0, 3) # src1 exponent = 3 - interp.set_vgpr_u64(2, f64_to_bits(1.5)) - res = interp.execute_asm("v_ldexp_f64 v[0:1], v[2:3], v0") - self.assertEqual(bits_to_f64(res), 12.0) - self.assertEqual(bits_to_f64(interp.get_vgpr_u64(0)), 12.0) - - def test_aliasing_dst_high_src1_scalar(self): - interp = ScalarVALUInterpreter() - # v[0:1] = v_ldexp_f64 v[2:3], v1 (dst high overlaps src1) - interp.set_vgpr_u32(1, -2) # src1 exponent = -2 - interp.set_vgpr_u64(2, f64_to_bits(8.0)) - res = interp.execute_asm("v_ldexp_f64 v[0:1], v[2:3], v1") - self.assertEqual(bits_to_f64(res), 2.0) - self.assertEqual(bits_to_f64(interp.get_vgpr_u64(0)), 2.0) - - def test_partial_overlap_dst_hi_src0_lo_scalar(self): - interp = ScalarVALUInterpreter() - # v[1:2] = v_ldexp_f64 v[0:1], v3 - # v1 is shared between src0 high dword and dst low dword! - val = 10.0 - interp.set_vgpr_u64(0, f64_to_bits(val)) - interp.set_vgpr_u32(3, 1) - res = interp.execute_asm("v_ldexp_f64 v[1:2], v[0:1], v3") - self.assertEqual(bits_to_f64(res), 20.0) - self.assertEqual(bits_to_f64(interp.get_vgpr_u64(1)), 20.0) - - def test_partial_overlap_dst_lo_src0_hi_scalar(self): - interp = ScalarVALUInterpreter() - # v[0:1] = v_ldexp_f64 v[1:2], v3 - val = 0.75 - interp.set_vgpr_u64(1, f64_to_bits(val)) - interp.set_vgpr_u32(3, 4) - res = interp.execute_asm("v_ldexp_f64 v[0:1], v[1:2], v3") - self.assertEqual(bits_to_f64(res), 12.0) - self.assertEqual(bits_to_f64(interp.get_vgpr_u64(0)), 12.0) - - def test_full_aliasing_dual_src0_src1_scalar(self): - interp = ScalarVALUInterpreter() - # v[0:1] = v_ldexp_f64 v[0:1], v0 - # Low dword of v[0:1] is also the exponent - # Let's craft a double whose low dword is a valid integer exponent (e.g. 2) - # In little endian IEEE 754: v0 is bits 0..31 of float, v1 is bits 32..63 - # If v0 = 2, and v1 = 0x3FF00000 (1.0) - # Then src0 is a valid float close to 1.0, and exponent is 2! - interp.set_vgpr_u32(0, 2) - interp.set_vgpr_u32(1, 0x3FF00000) - float_val = bits_to_f64(join_dwords(2, 0x3FF00000)) - expected = math.ldexp(float_val, 2) - res = interp.execute_asm("v_ldexp_f64 v[0:1], v[0:1], v0") - self.assertEqual(bits_to_f64(res), expected) - - def test_simd_wave64_aliasing_with_exec_mask(self): - sim = SIMDVALUInterpreter(wave_size=64) - canary = 0xABABABABCDCDEFEF - for lane in range(64): - # v[0:1] initialized with 2.0 on even lanes, canary on odd lanes - if lane % 2 == 0: - sim.set_vgpr_u64(0, lane, f64_to_bits(2.0)) - else: - sim.set_vgpr_u64(0, lane, canary) - sim.set_vgpr_u32(2, lane, 3) - - # Only even lanes active - sim.exec = 0x5555555555555555 - # In-place execution: v[0:1] = v_ldexp_f64 v[0:1], v2 - results = sim.execute_asm("v_ldexp_f64 v[0:1], v[0:1], v2") - - for lane in range(64): - if lane % 2 == 0: - self.assertEqual(bits_to_f64(results[lane]), 16.0) - self.assertEqual(bits_to_f64(sim.get_vgpr_u64(0, lane)), 16.0) - else: - self.assertEqual(results[lane], canary) - self.assertEqual(sim.get_vgpr_u64(0, lane), canary) - - def test_simd_wave32_partial_overlap_divergent(self): - sim = SIMDVALUInterpreter(wave_size=32) - for lane in range(32): - sim.set_vgpr_u64(1, lane, f64_to_bits(1.0 + lane)) - sim.set_vgpr_u32(3, lane, 1) - - # v[0:1] = v_ldexp_f64 v[1:2], v3 - results = sim.execute_asm("v_ldexp_f64 v[0:1], v[1:2], v3") - for lane in range(32): - self.assertEqual(bits_to_f64(results[lane]), (1.0 + lane) * 2.0) - - -class TestValuLdexpF64SIMDMultiLane(unittest.TestCase): - """Unit tests for SIMD multi-lane divergence and 32/64-bit EXEC masking.""" - - def test_wave32_uniform_execution(self): - sim = SIMDVALUInterpreter(wave_size=32) - base = f64_to_bits(1.5) - for lane in range(32): - sim.set_vgpr_u64(2, lane, base) - sim.set_vgpr_u32(4, lane, 3) - - results = sim.execute_asm("v_ldexp_f64 v[0:1], v[2:3], v4") - self.assertEqual(len(results), 32) - for lane in range(32): - self.assertEqual(bits_to_f64(results[lane]), 12.0) - self.assertEqual(bits_to_f64(sim.get_vgpr_u64(0, lane)), 12.0) - - def test_wave64_uniform_execution(self): - sim = SIMDVALUInterpreter(wave_size=64) - base = f64_to_bits(0.125) - for lane in range(64): - sim.set_vgpr_u64(6, lane, base) - sim.set_vgpr_u32(8, lane, 4) - - results = sim.execute_asm("v_ldexp_f64 v[4:5], v[6:7], v8") - self.assertEqual(len(results), 64) - for lane in range(64): - self.assertEqual(bits_to_f64(results[lane]), 2.0) - - def test_wave32_divergent_lanes(self): - sim = SIMDVALUInterpreter(wave_size=32) - expected: list[float] = [] - for lane in range(32): - val = float(lane + 1) - exp = (lane % 5) - 2 # exponents in [-2, 2] - sim.set_vgpr_u64(0, lane, f64_to_bits(val)) - sim.set_vgpr_u32(2, lane, exp) - expected.append(math.ldexp(val, exp)) - - results = sim.execute_asm("v_ldexp_f64 v[4:5], v[0:1], v2") - for lane in range(32): - self.assertEqual(bits_to_f64(results[lane]), expected[lane]) - - def test_wave64_divergent_lanes(self): - sim = SIMDVALUInterpreter(wave_size=64) - expected: list[float] = [] - for lane in range(64): - val = 0.5 * (lane + 1) - exp = (lane % 7) - 3 - sim.set_vgpr_u64(2, lane, f64_to_bits(val)) - sim.set_vgpr_u32(4, lane, exp) - expected.append(math.ldexp(val, exp)) - - results = sim.execute_asm("v_ldexp_f64 v[0:1], v[2:3], v4") - for lane in range(64): - self.assertEqual(bits_to_f64(results[lane]), expected[lane]) - - def test_exec_mask_partial_inactivity_wave32(self): - sim = SIMDVALUInterpreter(wave_size=32) - canary = 0xDEADBEEFCAFEBABE - for lane in range(32): - sim.set_vgpr_u64(0, lane, canary) - sim.set_vgpr_u64(2, lane, f64_to_bits(1.0)) - sim.set_vgpr_u32(4, lane, 2) - - # Only even lanes active: 0x55555555 - sim.exec = 0x55555555 - results = sim.execute_asm("v_ldexp_f64 v[0:1], v[2:3], v4") - - for lane in range(32): - if lane % 2 == 0: - self.assertEqual(bits_to_f64(results[lane]), 4.0) - self.assertEqual(bits_to_f64(sim.get_vgpr_u64(0, lane)), 4.0) - else: - self.assertEqual(results[lane], canary) - self.assertEqual(sim.get_vgpr_u64(0, lane), canary) - - def test_exec_mask_partial_inactivity_wave64(self): - sim = SIMDVALUInterpreter(wave_size=64) - canary = 0x1122334455667788 - for lane in range(64): - sim.set_vgpr_u64(0, lane, canary) - sim.set_vgpr_u64(2, lane, f64_to_bits(2.0)) - sim.set_vgpr_u32(4, lane, 1) - - # Low 32 lanes active, high 32 lanes inactive - sim.exec = 0x00000000FFFFFFFF - results = sim.execute_asm("v_ldexp_f64 v[0:1], v[2:3], v4") - - for lane in range(64): - if lane < 32: - self.assertEqual(bits_to_f64(results[lane]), 4.0) - else: - self.assertEqual(results[lane], canary) - self.assertEqual(sim.get_vgpr_u64(0, lane), canary) - - def test_exec_mask_all_inactive(self): - sim = SIMDVALUInterpreter(wave_size=64) - canary = 0xCAFEBABE12345678 - for lane in range(64): - sim.set_vgpr_u64(0, lane, canary) - sim.set_vgpr_u64(2, lane, f64_to_bits(1.0)) - sim.set_vgpr_u32(4, lane, 1) - - sim.exec = 0x0 - results = sim.execute_asm("v_ldexp_f64 v[0:1], v[2:3], v4") - for lane in range(64): - self.assertEqual(results[lane], canary) - self.assertEqual(sim.get_vgpr_u64(0, lane), canary) - - -class TestValuLdexpF64ScalarInterpreter(unittest.TestCase): - """Unit tests for deterministic scalar instruction interpreter.""" - - def setUp(self): - self.interp = ScalarVALUInterpreter() - - def test_scalar_interpreter_vgpr_sources(self): - # Set v[2:3] = 3.0, v4 = 2 - self.interp.set_vgpr_u64(2, f64_to_bits(3.0)) - self.interp.set_vgpr_u32(4, 2) - ast = parse_vop3_ldexp_f64("v_ldexp_f64 v[0:1], v[2:3], v4") - res = self.interp.execute(ast) - self.assertEqual(bits_to_f64(res), 12.0) - self.assertEqual(self.interp.get_vgpr_u64(0), res) - - def test_scalar_interpreter_sgpr_sources(self): - # Set s[0:1] = 0.5, s2 = 4 -> 8.0 - self.interp.set_sgpr_u64(0, f64_to_bits(0.5)) - self.interp.set_sgpr_u32(2, 4) - ast = parse_vop3_ldexp_f64("v_ldexp_f64 v[6:7], s[0:1], s2") - res = self.interp.execute(ast) - self.assertEqual(bits_to_f64(res), 8.0) - self.assertEqual(self.interp.get_vgpr_u64(6), res) - - def test_scalar_interpreter_literal_exponent(self): - self.interp.set_vgpr_u64(0, f64_to_bits(1.25)) - ast = parse_vop3_ldexp_f64("v_ldexp_f64 v[2:3], v[0:1], 3") - res = self.interp.execute(ast) - self.assertEqual(bits_to_f64(res), 10.0) - - def test_scalar_interpreter_input_modifiers(self): - # -|v[2:3]| * 2^1 with v[2:3] = 4.0 -> -8.0 - self.interp.set_vgpr_u64(2, f64_to_bits(4.0)) - self.interp.set_vgpr_u32(5, 1) - ast = parse_vop3_ldexp_f64("v_ldexp_f64 v[0:1], -|v[2:3]|, v5") - res = self.interp.execute(ast) - self.assertEqual(bits_to_f64(res), -8.0) - - def test_scalar_interpreter_output_modifiers_clamp_omod(self): - self.interp.set_vgpr_u64(0, f64_to_bits(0.25)) - self.interp.set_vgpr_u32(2, 1) # 0.25 * 2^1 = 0.5 - # With mul:4 -> 2.0; with clamp -> 1.0 - ast = parse_vop3_ldexp_f64("v_ldexp_f64 v[4:5], v[0:1], v2 clamp mul:4") - res = self.interp.execute(ast) - self.assertEqual(bits_to_f64(res), 1.0) - - def test_scalar_interpreter_asm_execution(self): - self.interp.set_vgpr_u64(10, f64_to_bits(2.5)) - res = self.interp.execute_asm("v_ldexp_f64 v[0:1], v[10:11], -1") - self.assertEqual(bits_to_f64(res), 1.25) - - -class TestValuLdexpF64SymbolicAST(unittest.TestCase): - """Unit tests for symbolic AST opcode definitions and typed expressions.""" - - def test_ast_construction_and_validation(self): - dst = Operand(OperandKind.VGPR_PAIR, DataType.F64, reg_index=0) - src0 = Operand(OperandKind.VGPR_PAIR, DataType.F64, reg_index=2) - src1 = Operand(OperandKind.SGPR_SINGLE, DataType.I32, reg_index=4) - ast = InstructionAST("v_ldexp_f64", dst, src0, src1, clamp=True, omod="mul:2") - ast.validate() - self.assertEqual(ast.to_asm(), "v_ldexp_f64 v[0:1], v[2:3], s4 clamp mul:2") - - def test_parser_vgpr_sgpr_operands(self): - ast = parse_vop3_ldexp_f64("v_ldexp_f64 v[4:5], v[6:7], v8") - self.assertEqual(ast.dst.reg_index, 4) - self.assertEqual(ast.src0.kind, OperandKind.VGPR_PAIR) - self.assertEqual(ast.src0.reg_index, 6) - self.assertEqual(ast.src1.kind, OperandKind.VGPR_SINGLE) - self.assertEqual(ast.src1.reg_index, 8) - self.assertFalse(ast.clamp) - self.assertEqual(ast.omod, "none") - - def test_parser_literal_and_constant_operands(self): - ast = parse_vop3_ldexp_f64("v_ldexp_f64 v[0:1], s[2:3], 5") - self.assertEqual(ast.src0.kind, OperandKind.SGPR_PAIR) - self.assertEqual(ast.src1.kind, OperandKind.LITERAL_I32) - self.assertEqual(ast.src1.literal_val, 5) - - def test_parser_modifiers_abs_neg_clamp_omod(self): - ast = parse_vop3_ldexp_f64("v_ldexp_f64 v[0:1], -|v[2:3]|, s0 clamp mul:4") - self.assertTrue(ast.src0.abs_mod) - self.assertTrue(ast.src0.neg_mod) - self.assertTrue(ast.clamp) - self.assertEqual(ast.omod, "mul:4") - self.assertEqual(ast.to_asm(), "v_ldexp_f64 v[0:1], -|v[2:3]|, s0 clamp mul:4") - - def test_ast_type_checking_and_invariants(self): - # Invalid dst type - bad_dst = Operand(OperandKind.VGPR_SINGLE, DataType.F64, reg_index=0) - src0 = Operand(OperandKind.VGPR_PAIR, DataType.F64, reg_index=2) - src1 = Operand(OperandKind.SGPR_SINGLE, DataType.I32, reg_index=4) - with self.assertRaises(TypeError): - InstructionAST("v_ldexp_f64", bad_dst, src0, src1).validate() - - # Invalid src1 type - bad_src1 = Operand(OperandKind.SGPR_SINGLE, DataType.F64, reg_index=4) - with self.assertRaises(TypeError): - InstructionAST("v_ldexp_f64", Operand(OperandKind.VGPR_PAIR, DataType.F64, 0), src0, bad_src1).validate() - - -class TestValuLdexpF64Oracle(unittest.TestCase): - """Unit tests for the reference mathematical oracle and architectural model.""" - - def test_oracle_normal_values(self): - # 1.0 * 2^3 = 8.0 - res = ref_ldexp_f64(ONE_F64, 3) - self.assertEqual(bits_to_f64(res), 8.0) - # 1.5 * 2^2 = 6.0 - f_1p5 = f64_to_bits(1.5) - self.assertEqual(bits_to_f64(ref_ldexp_f64(f_1p5, 2)), 6.0) - # -4.0 * 2^-2 = -1.0 - f_neg4 = f64_to_bits(-4.0) - self.assertEqual(bits_to_f64(ref_ldexp_f64(f_neg4, -2)), -1.0) - - def test_oracle_powers_of_two(self): - for p in range(-50, 50): - res = ref_ldexp_f64(ONE_F64, p) - expected = math.ldexp(1.0, p) - self.assertEqual(bits_to_f64(res), expected) - - def test_oracle_cross_check_math_ldexp(self): - test_floats = [0.125, 0.3333333333333333, 1.0, 2.5, 42.0, 1000.125, -7.5, -0.0625] - test_scales = [-10, -5, -2, -1, 0, 1, 2, 5, 10] - for f in test_floats: - f_bits = f64_to_bits(f) - for s in test_scales: - oracle_res = bits_to_f64(ref_ldexp_f64(f_bits, s)) - expected = math.ldexp(f, s) - self.assertEqual(oracle_res, expected) - - def test_oracle_cross_check_rational(self): - for f in [1.5, 3.25, -0.75, 10.125]: - f_bits = f64_to_bits(f) - for s in [-4, -1, 0, 3, 7]: - self.assertEqual(ref_ldexp_f64(f_bits, s), ref_ldexp_f64_rational(f_bits, s)) - - def test_oracle_special_values(self): - # +0.0 and -0.0 preserved - self.assertEqual(ref_ldexp_f64(POS_ZERO_F64, 10), POS_ZERO_F64) - self.assertEqual(ref_ldexp_f64(NEG_ZERO_F64, 10), NEG_ZERO_F64) - # +inf and -inf preserved - self.assertEqual(ref_ldexp_f64(POS_INF_F64, 5), POS_INF_F64) - self.assertEqual(ref_ldexp_f64(NEG_INF_F64, 5), NEG_INF_F64) - # NaNs preserved and quieted - res_qnan = ref_ldexp_f64(QNAN_F64, 2) - self.assertTrue(is_nan_f64(res_qnan)) - res_snan = ref_ldexp_f64(SNAN_F64, 2) - self.assertTrue(is_nan_f64(res_snan)) - - def test_oracle_subnormal_and_gradual_underflow(self): - # Smallest normal shifted down into subnormal - sub_bits = ref_ldexp_f64(MIN_NORMAL_F64, -1) - self.assertTrue(is_subnormal_f64(sub_bits)) - self.assertEqual(sub_bits, 0x0008000000000000) - # Subnormal shifted back to normal - norm_bits = ref_ldexp_f64(sub_bits, 1) - self.assertEqual(norm_bits, MIN_NORMAL_F64) - # Complete underflow to zero - zero_bits = ref_ldexp_f64(MIN_NORMAL_F64, -100) - self.assertEqual(zero_bits, POS_ZERO_F64) - - def test_oracle_overflow(self): - # Overflow to infinity - res_overflow = ref_ldexp_f64(MAX_FINITE_F64, 2) - self.assertEqual(res_overflow, POS_INF_F64) - res_neg_overflow = ref_ldexp_f64(MAX_FINITE_F64 | SIGN_MASK_F64, 2) - self.assertEqual(res_neg_overflow, NEG_INF_F64) - - def test_oracle_modifiers(self): - # abs modifier - f_neg2 = f64_to_bits(-2.0) - self.assertEqual(bits_to_f64(ref_ldexp_f64(f_neg2, 1, abs_src0=True)), 4.0) - # neg modifier - f_pos2 = f64_to_bits(2.0) - self.assertEqual(bits_to_f64(ref_ldexp_f64(f_pos2, 1, neg_src0=True)), -4.0) - # clamp modifier - self.assertEqual(bits_to_f64(ref_ldexp_f64(f_pos2, 2, clamp=True)), 1.0) - self.assertEqual(bits_to_f64(ref_ldexp_f64(f_neg2, 1, clamp=True)), 0.0) - # omod modifiers - self.assertEqual(bits_to_f64(ref_ldexp_f64(ONE_F64, 0, omod="mul:2")), 2.0) - self.assertEqual(bits_to_f64(ref_ldexp_f64(ONE_F64, 0, omod="mul:4")), 4.0) - self.assertEqual(bits_to_f64(ref_ldexp_f64(ONE_F64, 0, omod="div:2")), 0.5) - - -# --- translator-backed cases (SHADER-1039) ------------------------------------------------------- -# Each case translates a hand-written pixel shader with tools/rdna2spirv.py and runs it through -# tests/semantic/spirv_mini_interp.py; the expected word is the rule above applied by hand. - - -def run_ldexp(src_bits, exp_bits, src_text="v[0:1]", tail="", setup=()): - """Translate and run `v_ldexp_f64 v[4:5], , v2`; return (bits, SPIR-V text).""" - lines = list(setup) + [ - "v_mov_b32 v0, %#010x" % (src_bits & MASK32), - "v_mov_b32 v1, %#010x" % ((src_bits >> 32) & MASK32), - "v_mov_b32 v2, %#010x" % (exp_bits & MASK32), - "v_ldexp_f64 v[4:5], %s, v2%s" % (src_text, tail), - "exp mrt0 v4, v5, v4, v5 done vm", - "s_endpgm", - ] - spv = translate_lines("ps_ldexp_f64", lines) - words = mrt0_words(spv) - return (words[0] | words[1] << 32), spv - - -class TranslatedLdexpF64(unittest.TestCase): - """The translated instruction against words written by hand from the rules above (SHADER-1039).""" - - CASES = [ - # (source bits, exponent, expected bits, what it pins) - (ONE_F64, 5, 0x4040000000000000, "1.0 * 2^5 = 32.0"), - (0x3FF8000000000000, -1, 0x3FE8000000000000, "1.5 * 2^-1 = 0.75"), - (0xBFF8000000000000, 2, 0xC018000000000000, "-1.5 * 2^2 = -6.0"), - (ONE_F64, -1074, MIN_SUBNORMAL_F64, "1.0 * 2^-1074 is the smallest subnormal"), - (MIN_SUBNORMAL_F64, 1, 0x0000000000000002, "a subnormal input is normalised before scaling"), - (ONE_F64, -1075, POS_ZERO_F64, "half an ulp ties to even"), - (0x3FF8000000000000, -1075, MIN_SUBNORMAL_F64, "three quarters of an ulp rounds up"), - (POS_ZERO_F64, 900, POS_ZERO_F64, "+0 passes through"), - (NEG_ZERO_F64, 900, NEG_ZERO_F64, "-0 keeps its sign"), - (POS_INF_F64, 900, POS_INF_F64, "+inf passes through"), - (NEG_INF_F64, -900, NEG_INF_F64, "-inf passes through"), - (QNAN_F64, 7, QNAN_F64, "qNaN passes through unchanged"), - (MAX_FINITE_F64, 2, POS_INF_F64, "overflow gives +inf"), - ] - - def test_scaling_specials_and_subnormals(self): - for src_bits, exponent, want, why in self.CASES: - with self.subTest(why=why): - got, spv = run_ldexp(src_bits, exponent) - self.assertEqual(got, want, why) - self.assertNotIn("OpCapability Float64", spv, "the lowering is 32-bit integer only") - - def test_source_modifiers(self): - got, _ = run_ldexp(0xC008000000000000, 3, src_text="|v[0:1]|") # |-3.0| * 8 - self.assertEqual(got, 0x4038000000000000) - got, _ = run_ldexp(0x3FF8000000000000, 1, src_text="-v[0:1]") # -(1.5 * 2) - self.assertEqual(got, 0xC008000000000000) - - def test_clamp(self): - # dx10_clamp: NaN, -0 and negatives give +0.0; anything above 1.0 gives 1.0. - for src_bits, exponent, want in ((ONE_F64, 2000, ONE_F64), - (0xBFF0000000000000, 3, POS_ZERO_F64), - (QNAN_F64, 3, POS_ZERO_F64), - (0x3FE0000000000000, 1, ONE_F64)): - with self.subTest(src=hex(src_bits), exponent=exponent): - got, _ = run_ldexp(src_bits, exponent, tail=" clamp") - self.assertEqual(got, want) - - def test_32_bit_literal_lands_in_the_high_word(self): - # RDNA2 places a 32-bit literal constant in bits [63:32] of an f64 operand (measured on gfx1036). - got, _ = run_ldexp(0, 3, src_text="0x3ff00000") - self.assertEqual(got, 0x4020000000000000) # 1.0 * 2^3 - - def test_sgpr_pair_source(self): - setup = ("s_mov_b32 s0, 0x00000000", "s_mov_b32 s1, 0xc0000000") # -2.0 - got, _ = run_ldexp(0, 2, src_text="s[0:1]", setup=setup) - self.assertEqual(got, 0xC020000000000000) # -2.0 * 4 - - def test_mode_dependent_omod_is_refused(self): - # Hardware ignores mul:2/mul:4/div:2 with denorm16_64 = 3 and applies them with 0, so the - # translator refuses them rather than guessing. - with self.assertRaisesRegex(rdna2spirv.Unsupported, "output modifier"): - run_ldexp(ONE_F64, 5, tail=" mul:2") - - def test_single_register_destination_is_refused(self): - lines = ["v_mov_b32 v0, 0", "v_mov_b32 v1, 0x3ff00000", "v_mov_b32 v2, 3", - "v_ldexp_f64 v4, v[0:1], v2", "exp mrt0 v4, v4, v4, v4 done vm", "s_endpgm"] - with self.assertRaisesRegex(rdna2spirv.Unsupported, "destination"): - translate_lines("ps_ldexp_bad_dst", lines) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_valu_lerp_u8.py b/tests/semantic/test_valu_lerp_u8.py deleted file mode 100644 index f22fc971f..000000000 --- a/tests/semantic/test_valu_lerp_u8.py +++ /dev/null @@ -1,89 +0,0 @@ -"""v_lerp_u8 (RDNA2 VOP3): per byte i, D.b[i] = (S0.b[i] + S1.b[i] + S2.b[i][0]) >> 1: the unsigned average of the -two bytes, rounded up when bit 0 of that byte of S2 is set and down otherwise; bits 7:1 of S2's bytes are ignored and -no byte can carry into its neighbour (255 + 255 + 1 = 511, shifted 255). - -Each case is translated by tools/rdna2spirv.py (support.translate_lines) and executed with -tests/semantic/spirv_mini_interp.py; the expected words are written by hand from that formula and also recomputed by a -plain-Python reference, with VGPR, SGPR and literal sources and seeded random operands. Standard library only: no GPU, -no LLVM, no game data. (The old file modelled the instruction in its own classes and never ran the translator; -test_alu_lerp_u8.py is the older real test. `clamp` is refused by the translator and is not pinned here.) -""" -import os -import random -import sys -import unittest - -sys.dont_write_bytecode = True -sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) -import support # noqa: E402 - - -def pk(*b): - return sum((x & 0xFF) << (8 * i) for i, x in enumerate(b)) - - -def ref(s0, s1, s2): - out = 0 - for i in range(4): - b0, b1, r = (s0 >> 8 * i) & 0xFF, (s1 >> 8 * i) & 0xFF, (s2 >> 8 * i) & 1 - out |= ((b0 + b1 + r) >> 1) << 8 * i - return out - - -def run(s0, s1, s2, form="vgpr"): - if form == "vgpr": - lines = [f"v_mov_b32 v1, {s0:#x}", f"v_mov_b32 v2, {s1:#x}", f"v_mov_b32 v3, {s2:#x}", "v_lerp_u8 v0, v1, v2, v3"] - elif form == "sgpr": - lines = [f"s_mov_b32 s1, {s0:#x}", f"s_mov_b32 s2, {s1:#x}", f"s_mov_b32 s3, {s2:#x}", "v_lerp_u8 v0, s1, s2, s3"] - elif form == "literal": - lines = [f"v_mov_b32 v1, {s0:#x}", f"v_mov_b32 v3, {s2:#x}", f"v_lerp_u8 v0, v1, {s1:#x}, v3"] - else: - raise ValueError(form) - lines += ["exp mrt0 v0, v0, v0, v0 done vm", "s_endpgm"] - return support.mrt0_words(support.translate_lines("ps_lerp_u8", lines))[0] - - -# (S0, S1, S2, expected word), written by hand, byte 0 first in pk(). -CASES = [ - (pk(0, 0, 0, 0), pk(0, 0, 0, 0), 0, 0), - (pk(10, 20, 30, 40), pk(20, 40, 60, 80), 0, pk(15, 30, 45, 60)), # exact averages - (pk(1, 2, 3, 4), pk(2, 3, 4, 5), 0, pk(1, 2, 3, 4)), # .5 rounds down with bit 0 clear - (pk(1, 2, 3, 4), pk(2, 3, 4, 5), 0x01010101, pk(2, 3, 4, 5)), # and up with it set - (pk(1, 2, 3, 4), pk(2, 3, 4, 5), pk(1, 0, 1, 0), pk(2, 2, 4, 4)), # per byte rounding - (pk(1, 2, 3, 4), pk(2, 3, 4, 5), 0xFEFEFEFE, pk(1, 2, 3, 4)), # bits 7:1 of S2 ignored - (pk(255, 255, 255, 255), pk(255, 255, 255, 255), 0x01010101, 0xFFFFFFFF), # 511 >> 1, no carry out of a byte - (pk(255, 0, 255, 0), pk(255, 0, 0, 255), 0x01010101, pk(255, 0, 128, 128)), - (pk(0, 0, 0, 0), pk(1, 1, 1, 1), 0x01010101, pk(1, 1, 1, 1)), - (pk(0x80, 0x7F, 0x81, 0xFE), pk(0x80, 0x80, 0x7F, 0xFF), 0, pk(0x80, 0x7F, 0x80, 0xFE)), -] - - -class LerpU8(unittest.TestCase): - def test_hand_table_matches_reference(self): - for s0, s1, s2, want in CASES: - self.assertEqual(ref(s0, s1, s2), want, (hex(s0), hex(s1), hex(s2))) - - def test_translated_forms(self): - for form in ("vgpr", "sgpr", "literal"): - for s0, s1, s2, want in CASES: - with self.subTest(form=form, s0=hex(s0), s1=hex(s1), s2=hex(s2)): - self.assertEqual(run(s0, s1, s2, form), want) - - def test_symmetric_and_identity(self): - rng = random.Random(0x1E8) - for _ in range(20): - a, b, c = (rng.getrandbits(32) for _ in range(3)) - self.assertEqual(run(a, b, c), run(b, a, c)) - self.assertEqual(run(a, a, c), a) - - def test_random_operands(self): - rng = random.Random(0x1E8B) - for _ in range(60): - s0, s1, s2 = (rng.getrandbits(32) for _ in range(3)) - for form in ("vgpr", "sgpr", "literal"): - with self.subTest(form=form, s0=hex(s0), s1=hex(s1), s2=hex(s2)): - self.assertEqual(run(s0, s1, s2, form), ref(s0, s1, s2)) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_valu_mad_lit.py b/tests/semantic/test_valu_mad_lit.py deleted file mode 100644 index 3884c4418..000000000 --- a/tests/semantic/test_valu_mad_lit.py +++ /dev/null @@ -1,774 +0,0 @@ -"""Semantic value tests for RDNA2 literal-operand f32 multiply-add VALU ops: - v_madak_f32 vdst, src0, vsrc1, K -> D = f32(f32(src0 * vsrc1) + K) (unfused, NoContraction) - v_madmk_f32 vdst, src0, K, vsrc1 -> D = f32(f32(src0 * K) + vsrc1) (unfused, NoContraction) - -Both are GFX10.1 VOP2-only instructions that carry an inline 32-bit literal K (no VOP3 source/output modifiers). -In LLVM AMDGPU disassembly print order, both compute a[1] * a[2] + a[3], with the literal K occupying the addend -slot in v_madak_f32 and the second multiplicand slot in v_madmk_f32. - -Each test builds a hand-written RDNA2 pixel or compute shader listing (stdlib only, zero game data), translates it -with tools/rdna2spirv.py, executes the SPIR-V in tests/semantic/spirv_mini_interp.py, and checks the output words -against an independent plain-Python IEEE-754 binary32 Fraction reference oracle. -""" -from __future__ import annotations - -from fractions import Fraction -import gc -import math -import os -import re -import struct -import sys -import tempfile -import unittest -import warnings - -HERE = os.path.dirname(os.path.abspath(__file__)) -ROOT = os.path.dirname(os.path.dirname(HERE)) -TOOLS_DIR = os.environ.get("LEONIDA_TOOLS_DIR") or os.path.join(ROOT, "tools") - -sys.dont_write_bytecode = True -if TOOLS_DIR not in sys.path: - sys.path.insert(0, TOOLS_DIR) -if HERE not in sys.path: - sys.path.insert(0, HERE) - -import rdna2spirv # noqa: E402 -import spirv_mini_interp as si # noqa: E402 - -MASK32 = 0xFFFFFFFF -STUB_DXBC = b"DXBC" + bytes(24) + struct.pack(" float: - return struct.unpack(" int: - try: - return struct.unpack(" 0 else NEG_INF - - -def is_nan_bits(bits: int) -> bool: - bits &= MASK32 - return (bits & 0x7F800000) == 0x7F800000 and (bits & 0x007FFFFF) != 0 - - -def exact_f32_to_fraction(bits: int) -> Fraction: - """Decode a finite binary32 bit pattern into an exact rational Fraction.""" - bits &= MASK32 - sign = -1 if (bits >> 31) else 1 - exp = (bits >> 23) & 0xFF - frac = bits & 0x7FFFFF - if exp == 0xFF: - raise ValueError(f"non-finite bits {bits:#010x}") - if exp == 0: - return Fraction(sign * frac, 1 << 149) - mant = (1 << 23) | frac - shift = exp - 150 - if shift >= 0: - return Fraction(sign * (mant << shift), 1) - return Fraction(sign * mant, 1 << (-shift)) - - -def round_fraction_to_f32_bits(val: Fraction, zero_sign: int = 0) -> int: - """Round an exact Fraction to IEEE-754 binary32 (round-to-nearest-even).""" - if val == 0: - return NEG_ZERO if zero_sign else POS_ZERO - sign = 1 if val < 0 else 0 - aval = -val if sign else val - num, den = aval.numerator, aval.denominator - e = num.bit_length() - den.bit_length() - if (num << max(0, -e)) < (den << max(0, e)): - e -= 1 - - if e >= 128: - return (sign << 31) | POS_INF - - target_shift = 149 if e < -126 else 23 - e - if target_shift >= 0: - scaled_num = num << target_shift - else: - scaled_num = num - den = den << (-target_shift) - - q, rem = divmod(scaled_num, den) - twice_rem = rem << 1 - if twice_rem > den or (twice_rem == den and (q & 1)): - q += 1 - - if e < -126: - if q >= (1 << 23): - return (sign << 31) | (1 << 23) - return (sign << 31) | q - - if q >= (1 << 24): - q >>= 1 - e += 1 - if e >= 128: - return (sign << 31) | POS_INF - - return (sign << 31) | ((e + 127) << 23) | (q & 0x7FFFFF) - - -def _zero_sign_bit(bits: int) -> int: - return 1 if (bits & MASK32) == NEG_ZERO else 0 - - -def _mul_bits_f32(xb: int, yb: int) -> int: - x, y = bits_to_f32(xb), bits_to_f32(yb) - if math.isnan(x) or math.isnan(y): - return QNAN - if (x == 0.0 and math.isinf(y)) or (math.isinf(x) and y == 0.0): - return QNAN - sign = ((xb ^ yb) >> 31) & 1 - if math.isinf(x) or math.isinf(y): - return (sign << 31) | POS_INF - if x == 0.0 or y == 0.0: - return NEG_ZERO if sign else POS_ZERO - return round_fraction_to_f32_bits(exact_f32_to_fraction(xb) * exact_f32_to_fraction(yb), zero_sign=sign) - - -def _add_bits_f32(ab: int, bb: int) -> int: - a, b = bits_to_f32(ab), bits_to_f32(bb) - if math.isnan(a) or math.isnan(b): - return QNAN - if math.isinf(a) and math.isinf(b): - if (ab >> 31) != (bb >> 31): - return QNAN - return ab & MASK32 - if math.isinf(a): - return ab & MASK32 - if math.isinf(b): - return bb & MASK32 - if a == 0.0 and b == 0.0: - return NEG_ZERO if (_zero_sign_bit(ab) and _zero_sign_bit(bb)) else POS_ZERO - total = exact_f32_to_fraction(ab) + exact_f32_to_fraction(bb) - return round_fraction_to_f32_bits(total, zero_sign=0) - - -def ref_madak_f32(src0_bits: int, src1_bits: int, k_bits: int) -> int: - """Reference for v_madak_f32 vdst, src0, vsrc1, K -> f32(f32(src0 * vsrc1) + K).""" - return _add_bits_f32(_mul_bits_f32(src0_bits, src1_bits), k_bits) - - -def ref_madmk_f32(src0_bits: int, k_bits: int, src1_bits: int) -> int: - """Reference for v_madmk_f32 vdst, src0, K, vsrc1 -> f32(f32(src0 * K) + vsrc1).""" - return _add_bits_f32(_mul_bits_f32(src0_bits, k_bits), src1_bits) - - -def ref_fma_f32(xb: int, yb: int, zb: int) -> int: - """True IEEE-754 binary32 fused multiply-add: fma(x, y, z) (used to verify unfused divergence).""" - x, y, z = bits_to_f32(xb), bits_to_f32(yb), bits_to_f32(zb) - if math.isnan(x) or math.isnan(y) or math.isnan(z): - return QNAN - if (x == 0.0 and math.isinf(y)) or (math.isinf(x) and y == 0.0): - return QNAN - prod_sign = ((xb ^ yb) >> 31) & 1 - if math.isinf(x) or math.isinf(y): - return _add_bits_f32((prod_sign << 31) | POS_INF, zb) - if math.isinf(z): - return zb & MASK32 - total = exact_f32_to_fraction(xb) * exact_f32_to_fraction(yb) + exact_f32_to_fraction(zb) - if total == 0: - if (x == 0.0 or y == 0.0) and z == 0.0 and prod_sign == 1 and _zero_sign_bit(zb) == 1: - return NEG_ZERO - return POS_ZERO - return round_fraction_to_f32_bits(total, zero_sign=0) - - -_TMP_DIR = None -_PS_PATH = None -_CS_PATH = None - - -def setUpModule(): - global _TMP_DIR, _PS_PATH, _CS_PATH - _TMP_DIR = tempfile.TemporaryDirectory() - disasm_dir = os.path.join(_TMP_DIR.name, "disasm") - fssm_dir = os.path.join(_TMP_DIR.name, "fssm") - os.mkdir(disasm_dir) - os.mkdir(fssm_dir) - _PS_PATH = os.path.join(disasm_dir, "ps_mad_lit.s") - _CS_PATH = os.path.join(disasm_dir, "cs_mad_lit.s") - with open(os.path.join(_TMP_DIR.name, "ps_mad_lit.dxbc"), "wb") as f: - f.write(STUB_DXBC) - with open(os.path.join(fssm_dir, "cs_mad_lit.fssm"), "wb") as f: - f.write(CS_FSSM_BYTES) - - -def tearDownModule(): - global _TMP_DIR, _PS_PATH, _CS_PATH - if _TMP_DIR is not None: - gc.collect() - _TMP_DIR.cleanup() - _TMP_DIR = None - _PS_PATH = None - _CS_PATH = None - - -def translate_ps(lines: list[str], export_regs: tuple[str, str, str, str] = ("v0", "v0", "v0", "v0")) -> str: - if _TMP_DIR is None: - setUpModule() - assert _PS_PATH is not None - asm = ( - "; test_valu_mad_lit\n" - + "".join(f"\t{ln}\n" for ln in lines) - + f"\texp mrt0 {', '.join(export_regs)} done vm\n" - + "\ts_endpgm\n" - ) - with open(_PS_PATH, "w", encoding="utf-8", newline="\n") as f: - f.write(asm) - with warnings.catch_warnings(): - warnings.simplefilter("ignore", ResourceWarning) - spv = rdna2spirv.translate(_PS_PATH) - gc.collect() - return spv - - -def run_ps_mrt0( - lines: list[str], - export_regs: tuple[str, str, str, str] = ("v0", "v0", "v0", "v0"), - **run_options, -) -> list[int]: - spv = translate_ps(lines, export_regs=export_regs) - return list(si.run_fragment(spv, **run_options)["%out_mrt0"]) - - -def run_madak(src0_bits: int, src1_bits: int, k_bits: int, op: str = "v_madak_f32") -> int: - return run_ps_mrt0([ - f"v_mov_b32 v1, {src0_bits & MASK32:#x}", - f"v_mov_b32 v2, {src1_bits & MASK32:#x}", - f"{op} v0, v1, v2, {k_bits & MASK32:#x}", - ])[0] - - -def run_madmk(src0_bits: int, k_bits: int, src1_bits: int, op: str = "v_madmk_f32") -> int: - return run_ps_mrt0([ - f"v_mov_b32 v1, {src0_bits & MASK32:#x}", - f"v_mov_b32 v2, {src1_bits & MASK32:#x}", - f"{op} v0, v1, {k_bits & MASK32:#x}, v2", - ])[0] - - -def run_cs_workgroup_exec(lines: list[str], lanes: int = 4) -> dict[int, int]: - """Translate and run a compute shader storing `v1` per lane at byte address `4 * lane`.""" - if _TMP_DIR is None: - setUpModule() - assert _CS_PATH is not None - asm = "; test_valu_mad_lit_cs\n" + "".join(f"\t{ln}\n" for ln in lines) + "\ts_endpgm\n" - with open(_CS_PATH, "w", encoding="utf-8", newline="\n") as f: - f.write(asm) - with warnings.catch_warnings(): - warnings.simplefilter("ignore", ResourceWarning) - spv = rdna2spirv.translate(_CS_PATH) - gc.collect() - mem: dict[int, int] = {} - si.run_workgroup( - spv, - lanes, - 32, - inputs_for=lambda i: {"%local_id": (i, 0, 0), "%wg_id": (0, 0, 0)}, - push_constants=[0, 0, 64, 0x31016FAC] + [0] * 28, - memory=mem, - ) - return mem - - -class ReferenceOracleTests(unittest.TestCase): - """Cross-check the plain-Python IEEE-754 Fraction oracle against hand-derived binary32 constants.""" - - def test_hand_worked_constants(self): - # Asymmetric operands prove operand order: madak = 2*3 + 5 = 11, madmk = 2*5 + 3 = 13. - self.assertEqual(ref_madak_f32(TWO, THREE, FIVE), f32_to_bits(11.0)) - self.assertEqual(ref_madmk_f32(TWO, FIVE, THREE), f32_to_bits(13.0)) - self.assertNotEqual(ref_madak_f32(TWO, THREE, FIVE), ref_madmk_f32(TWO, FIVE, THREE)) - - # Negative and fractional values: (-1.5) * 2.5 + (-0.5) = -4.25; (-1.5) * (-0.5) + 2.5 = 3.25. - self.assertEqual(ref_madak_f32(NEG_ONE_HALF, TWO_HALF, NEG_HALF), f32_to_bits(-4.25)) - self.assertEqual(ref_madmk_f32(NEG_ONE_HALF, NEG_HALF, TWO_HALF), f32_to_bits(3.25)) - - # Signed zeros: (-0)*2 + (-0) = -0; (+0)*2 + (-0) = +0; exact cancellation -> +0. - self.assertEqual(ref_madak_f32(NEG_ZERO, TWO, NEG_ZERO), NEG_ZERO) - self.assertEqual(ref_madmk_f32(NEG_ZERO, TWO, NEG_ZERO), NEG_ZERO) - self.assertEqual(ref_madak_f32(POS_ZERO, TWO, NEG_ZERO), POS_ZERO) - self.assertEqual(ref_madmk_f32(POS_ZERO, TWO, NEG_ZERO), POS_ZERO) - self.assertEqual(ref_madak_f32(NEG_TWO, THREE, SIX), POS_ZERO) - self.assertEqual(ref_madmk_f32(NEG_TWO, THREE, SIX), POS_ZERO) - - # Unfused vs fused divergence: (1 + 2^-20)*(1 - 2^-20) - 1 = +0.0 (unfused) vs -2^-40 (fused). - a, b = 0x3F800008, 0x3F7FFFF0 - self.assertEqual(ref_madak_f32(a, b, NEG_ONE), POS_ZERO) - self.assertEqual(ref_madmk_f32(a, b, NEG_ONE), POS_ZERO) - self.assertEqual(ref_fma_f32(a, b, NEG_ONE), 0xAB800000) - - # Intermediate overflow: 2^100 * 2^28 - 2^127 = +inf (unfused) vs 2^127 (fused). - p100, p28, n127 = 0x71800000, 0x4D800000, 0xFF000000 - self.assertEqual(ref_madak_f32(p100, p28, n127), POS_INF) - self.assertEqual(ref_madmk_f32(p100, p28, n127), POS_INF) - self.assertEqual(ref_fma_f32(p100, p28, n127), 0x7F000000) - - -class MadLitBasicAndOrderingTests(unittest.TestCase): - """Normal floats, fractions, zeros, _e32 spellings, and operand ordering distinction.""" - - def test_operand_ordering_distinction(self): - # For the exact same (src0, vsrc1, K), madak computes src0 * vsrc1 + K while madmk computes src0 * K + vsrc1. - cases = [ - # (src0, vsrc1, K) - (TWO, THREE, FIVE), # madak = 2*3+5 = 11.0; madmk = 2*5+3 = 13.0 - (FOUR, FIVE, f32_to_bits(1.5)), # madak = 4*5+1.5 = 21.5; madmk = 4*1.5+5 = 11.0 - (NEG_ONE_HALF, TWO_HALF, NEG_HALF), # madak = -4.25; madmk = 3.25 - (THREE, POS_ZERO, FOUR), # madak = 0+4 = 4.0; madmk = 12+0 = 12.0 - (THREE, FOUR, POS_ZERO), # madak = 12+0 = 12.0; madmk = 0+4 = 4.0 - (NEG_TWO, QUARTER, ONE_HALF), # madak = -0.5+1.5 = 1.0; madmk = -3.0+0.25 = -2.75 - (f32_to_bits(0.1), f32_to_bits(7.0), f32_to_bits(-3.25)), - ] - for s0, s1, k in cases: - want_ak = ref_madak_f32(s0, s1, k) - want_mk = ref_madmk_f32(s0, k, s1) - self.assertNotEqual(want_ak, want_mk, "test triple must distinguish madak from madmk") - with self.subTest(s0=hex(s0), s1=hex(s1), k=hex(k)): - words = run_ps_mrt0([ - f"v_mov_b32 v1, {s0:#x}", - f"v_mov_b32 v2, {s1:#x}", - f"v_madak_f32 v10, v1, v2, {k:#x}", - f"v_madmk_f32 v11, v1, {k:#x}, v2", - f"v_madak_f32_e32 v12, v1, v2, {k:#x}", - f"v_madmk_f32_e32 v13, v1, {k:#x}, v2", - ], ("v10", "v11", "v12", "v13")) - self.assertEqual(words, [want_ak, want_mk, want_ak, want_mk]) - - # Special boundary: when src0 == 0 and one of (vsrc1, K) is +inf while the other is finite, - # the op that multiplies by +inf produces NaN while the op that adds +inf produces +inf. - words = run_ps_mrt0([ - f"v_mov_b32 v1, {POS_ZERO:#x}", - f"v_mov_b32 v2, {TWO:#x}", - f"v_madak_f32 v10, v1, v2, {POS_INF:#x}", # 0 * 2 + inf = +inf - f"v_madmk_f32 v11, v1, {POS_INF:#x}, v2", # 0 * inf + 2 = NaN - f"v_mov_b32 v3, {POS_INF:#x}", - f"v_madak_f32 v12, v1, v3, {TWO:#x}", # 0 * inf + 2 = NaN - f"v_madmk_f32 v13, v1, {TWO:#x}, v3", # 0 * 2 + inf = +inf - ], ("v10", "v11", "v12", "v13")) - self.assertEqual(words[0], POS_INF) - self.assertTrue(is_nan_bits(words[1]), hex(words[1])) - self.assertTrue(is_nan_bits(words[2]), hex(words[2])) - self.assertEqual(words[3], POS_INF) - - def test_normal_fractional_and_zero_sweep_batched(self): - # 5 * 5 * 4 = 100 triples per instruction covering positives, negatives, fractions, and zeros. - src0_vals = (NEG_THREE, NEG_HALF, POS_ZERO, QUARTER, TWO_HALF) - src1_vals = (NEG_ONE_HALF, NEG_ZERO, ONE, f32_to_bits(1.0 / 3.0), SIX) - k_vals = (NEG_TWO, POS_ZERO, f32_to_bits(0.1), f32_to_bits(3.75)) - triples = [(a, b, k) for a in src0_vals for b in src1_vals for k in k_vals] - - for op in ("v_madak_f32", "v_madmk_f32"): - for start in range(0, len(triples), 4): - chunk = triples[start:start + 4] - lines, expected = [], [] - for slot, (a, b, k) in enumerate(chunk): - base = 10 + 3 * slot - lines.append(f"v_mov_b32 v{base + 1}, {a:#x}") - lines.append(f"v_mov_b32 v{base + 2}, {b:#x}") - if op == "v_madak_f32": - lines.append(f"{op} v{base}, v{base + 1}, v{base + 2}, {k:#x}") - expected.append(ref_madak_f32(a, b, k)) - else: - lines.append(f"{op} v{base}, v{base + 1}, {k:#x}, v{base + 2}") - expected.append(ref_madmk_f32(a, k, b)) - regs = [f"v{10 + 3 * slot}" for slot in range(len(chunk))] - while len(regs) < 4: - regs.append(regs[0]) - expected.append(expected[0]) - with self.subTest(op=op, batch=start // 4): - self.assertEqual(run_ps_mrt0(lines, tuple(regs)), expected) - - -class LiteralAndOperandEncodingTests(unittest.TestCase): - """Hex literals, decimal float literals, inline constants, SGPR src0, and destination aliasing.""" - - def test_hex_and_float_literal_encodings(self): - # Mix hex 32-bit float encodings and decimal float literal spellings in K. - words = run_ps_mrt0([ - f"v_mov_b32 v1, {TWO:#x}", - f"v_mov_b32 v2, {THREE:#x}", - "v_madak_f32 v10, v1, v2, 0x3f800000", # 2.0 * 3.0 + 1.0 = 7.0 - "v_madak_f32 v11, v1, v2, 2.5", # 2.0 * 3.0 + 2.5 = 8.5 - "v_madmk_f32 v12, v1, 0xbf000000, v2", # 2.0 * (-0.5) + 3.0 = 2.0 - "v_madmk_f32 v13, v1, -0.5, v2", # 2.0 * (-0.5) + 3.0 = 2.0 - ], ("v10", "v11", "v12", "v13")) - self.assertEqual(words, [f32_to_bits(7.0), f32_to_bits(8.5), TWO, TWO]) - - # Scientific-notation float literals and negative hex / float literals. - words2 = run_ps_mrt0([ - f"v_mov_b32 v1, {FOUR:#x}", - f"v_mov_b32 v2, {ONE_HALF:#x}", - "v_madak_f32 v10, v1, v2, -0.5", # 4.0 * 1.5 - 0.5 = 5.5 - "v_madak_f32 v11, v1, v2, 1.25e1", # 4.0 * 1.5 + 12.5 = 18.5 - "v_madmk_f32 v12, v1, 2.5, v2", # 4.0 * 2.5 + 1.5 = 11.5 - "v_madmk_f32 v13, v1, 2.5e-1, v2", # 4.0 * 0.25 + 1.5 = 2.5 - ], ("v10", "v11", "v12", "v13")) - self.assertEqual(words2, [f32_to_bits(v) for v in (5.5, 18.5, 11.5, 2.5)]) - - def test_inline_constants_as_src0(self): - # VOP2 src0 accepts RDNA inline constants (0, 1.0, -1.0, 0.5, -0.5, 2.0, -2.0, 4.0, -4.0, 0.15915494). - words_ak = run_ps_mrt0([ - f"v_mov_b32 v2, {THREE:#x}", - "v_madak_f32 v10, 0, v2, 2.5", # 0.0 * 3.0 + 2.5 = 2.5 - "v_madak_f32 v11, 1.0, v2, -0.5", # 1.0 * 3.0 + (-0.5) = 2.5 - "v_madak_f32 v12, -1.0, v2, 0x40a00000", # (-1.0) * 3.0 + 5.0 = 2.0 - "v_madak_f32 v13, 0.15915494, v2, 0x3f800000", - ], ("v10", "v11", "v12", "v13")) - self.assertEqual(words_ak, [ - TWO_HALF, - TWO_HALF, - TWO, - ref_madak_f32(INV_TWO_PI, THREE, ONE), - ]) - - words_mk = run_ps_mrt0([ - f"v_mov_b32 v2, {THREE:#x}", - "v_madmk_f32 v10, 0, 2.5, v2", # 0.0 * 2.5 + 3.0 = 3.0 - "v_madmk_f32 v11, 1.0, -0.5, v2", # 1.0 * (-0.5) + 3.0 = 2.5 - "v_madmk_f32 v12, -1.0, 0x40a00000, v2", # (-1.0) * 5.0 + 3.0 = -2.0 - "v_madmk_f32 v13, 0.5, 0x40400000, v2", # 0.5 * 3.0 + 3.0 = 4.5 - ], ("v10", "v11", "v12", "v13")) - self.assertEqual(words_mk, [THREE, TWO_HALF, NEG_TWO, f32_to_bits(4.5)]) - - def test_sgpr_as_src0(self): - # VOP2 src0 may be an SGPR (either loaded by s_mov_b32 or supplied via push constants in s0..s3). - words = run_ps_mrt0([ - f"s_mov_b32 s4, {TWO_HALF:#x}", - f"s_mov_b32 s5, {NEG_TWO:#x}", - f"v_mov_b32 v2, {FOUR:#x}", - "v_madak_f32 v10, s4, v2, 0x3fc00000", # 2.5 * 4.0 + 1.5 = 11.5 - "v_madmk_f32 v11, s4, 0x3fc00000, v2", # 2.5 * 1.5 + 4.0 = 7.75 - "v_madak_f32 v12, s5, v2, 2.5", # (-2.0) * 4.0 + 2.5 = -5.5 - "v_madmk_f32 v13, s0, -0.5, v2", # s0(=6.0) * (-0.5) + 4.0 = 1.0 - ], ("v10", "v11", "v12", "v13"), push_constants=[SIX] + [0] * 31) - self.assertEqual(words, [f32_to_bits(11.5), f32_to_bits(7.75), f32_to_bits(-5.5), ONE]) - - def test_destination_register_aliasing(self): - # vdst aliasing src0, vsrc1, or both must read pre-write operand values cleanly. - cases = [ - ("v_madak_f32 v0, v0, v1, 5.0", ref_madak_f32(TWO, THREE, FIVE)), # 2*3 + 5 = 11.0 - ("v_madak_f32 v0, v1, v0, 5.0", ref_madak_f32(THREE, TWO, FIVE)), # 3*2 + 5 = 11.0 - ("v_madak_f32 v0, v0, v0, 5.0", ref_madak_f32(TWO, TWO, FIVE)), # 2*2 + 5 = 9.0 - ("v_madmk_f32 v0, v0, 5.0, v1", ref_madmk_f32(TWO, FIVE, THREE)), # 2*5 + 3 = 13.0 - ("v_madmk_f32 v0, v1, 5.0, v0", ref_madmk_f32(THREE, FIVE, TWO)), # 3*5 + 2 = 17.0 - ("v_madmk_f32 v0, v0, 5.0, v0", ref_madmk_f32(TWO, FIVE, TWO)), # 2*5 + 2 = 12.0 - ] - for insn, want in cases: - with self.subTest(insn=insn): - got = run_ps_mrt0([ - f"v_mov_b32 v0, {TWO:#x}", - f"v_mov_b32 v1, {THREE:#x}", - insn, - ])[0] - self.assertEqual(got, want) - - -class EdgeCaseAndRoundingTests(unittest.TestCase): - """Unfused rounding, NoContraction, signed zeros, infinities, NaN propagation, and chains.""" - - def test_unfused_rounding_and_nocontraction(self): - # Cases where unfused binary32 mul-then-add differs from fused FMA (v_fmaak_f32 / v_fmamk_f32). - cases = [ - # (a, b, c, want_unfused, want_fused) - (0x3F800008, 0x3F7FFFF0, NEG_ONE, POS_ZERO, 0xAB800000), # (1+2^-20)*(1-2^-20) - 1 - (0x3F800001, 0x3F800001, 0xBF800002, POS_ZERO, 0x28800000), # (1+2^-23)^2 - (1+2^-22) - (0x3FC00001, 0x3FBFFFFF, 0xC0100000, POS_ZERO, 0xA8800000), # (1.5+2^-23)*(1.5-2^-23) - 2.25 - (0x71800000, 0x4D800000, 0xFF000000, POS_INF, 0x7F000000), # 2^100*2^28 - 2^127 (mul ovf) - (0xF1800000, 0x4D800000, 0x7F000000, NEG_INF, 0xFF000000), # -2^100*2^28 + 2^127 (mul -ovf) - ] - for a, b, c, want_mad, want_fma in cases: - with self.subTest(a=hex(a), b=hex(b), c=hex(c)): - self.assertEqual(ref_madak_f32(a, b, c), want_mad) - self.assertEqual(ref_madmk_f32(a, b, c), want_mad) - self.assertEqual(ref_fma_f32(a, b, c), want_fma) - self.assertNotEqual(want_mad, want_fma) - self.assertEqual(run_madak(a, b, c), want_mad) - self.assertEqual(run_madmk(a, b, c), want_mad) - # Cross-check that the fused literal counterparts really diverge on the same inputs. - self.assertEqual(run_madak(a, b, c, op="v_fmaak_f32"), want_fma) - self.assertEqual(run_madmk(a, b, c, op="v_fmamk_f32"), want_fma) - - # Verify both ops emit unfused OpFMul + OpFAdd decorated with NoContraction (never Fma). - for insn in ( - f"v_madak_f32 v0, v1, v2, {THREE:#x}", - f"v_madmk_f32 v0, v1, {TWO:#x}, v2", - ): - with self.subTest(insn=insn): - spv = translate_ps([ - f"v_mov_b32 v1, {ONE:#x}", - f"v_mov_b32 v2, {TWO:#x}", - insn, - ]) - fmul_ids = re.findall(r"(%\w+)\s*=\s*OpFMul %float", spv) - fadd_ids = re.findall(r"(%\w+)\s*=\s*OpFAdd %float", spv) - self.assertEqual(len(fmul_ids), 1) - self.assertEqual(len(fadd_ids), 1) - self.assertIn(f"OpDecorate {fmul_ids[0]} NoContraction", spv) - self.assertIn(f"OpDecorate {fadd_ids[0]} NoContraction", spv) - self.assertNotIn("Fma", spv) - - def test_signed_zeros(self): - # IEEE-754 RTN signed-zero rules for (a * b) + c with both VGPR and literal operands. - cases = [ - (NEG_ZERO, TWO, NEG_ZERO, NEG_ZERO), # (-0.0)*2.0 + (-0.0) = -0.0 - (TWO, NEG_ZERO, NEG_ZERO, NEG_ZERO), # 2.0*(-0.0) + (-0.0) = -0.0 - (POS_ZERO, TWO, NEG_ZERO, POS_ZERO), # (+0.0)*2.0 + (-0.0) = +0.0 - (NEG_ZERO, TWO, POS_ZERO, POS_ZERO), # (-0.0)*2.0 + (+0.0) = +0.0 - (NEG_ZERO, NEG_ONE, NEG_ZERO, POS_ZERO), # (-0.0)*(-1.0) + (-0.0) = (+0.0)+(-0.0) = +0.0 - (NEG_TWO, THREE, SIX, POS_ZERO), # -6.0 + 6.0 = +0.0 (exact cancellation) - (TWO, NEG_THREE, SIX, POS_ZERO), # -6.0 + 6.0 = +0.0 - ] - for a, b, c, want in cases: - with self.subTest(a=hex(a), b=hex(b), c=hex(c)): - self.assertEqual(ref_madak_f32(a, b, c), want) - self.assertEqual(ref_madmk_f32(a, b, c), want) - self.assertEqual(run_madak(a, b, c), want) - self.assertEqual(run_madmk(a, b, c), want) - - # Decimal `-0.0` literal spelling also preserves the negative zero sign bit. - words = run_ps_mrt0([ - f"v_mov_b32 v1, {NEG_ZERO:#x}", - f"v_mov_b32 v2, {TWO:#x}", - f"v_mov_b32 v3, {NEG_ZERO:#x}", - "v_madak_f32 v10, v1, v2, -0.0", # (-0.0)*2.0 + (-0.0) = -0.0 - "v_madmk_f32 v11, v2, -0.0, v3", # 2.0*(-0.0) + (-0.0) = -0.0 - "v_madak_f32 v12, v1, v2, 0.0", # (-0.0)*2.0 + (+0.0) = +0.0 - "v_madmk_f32 v13, v2, 0.0, v3", # 2.0*(+0.0) + (-0.0) = +0.0 - ], ("v10", "v11", "v12", "v13")) - self.assertEqual(words, [NEG_ZERO, NEG_ZERO, POS_ZERO, POS_ZERO]) - - def test_infinities_and_overflow(self): - exact_cases = [ - (POS_INF, TWO, ONE, POS_INF), - (NEG_INF, TWO, ONE, NEG_INF), - (NEG_INF, NEG_TWO, NEG_ONE, POS_INF), - (TWO, POS_INF, NEG_THREE, POS_INF), - (TWO, THREE, NEG_INF, NEG_INF), - (POS_INF, TWO, POS_INF, POS_INF), - (NEG_INF, TWO, NEG_INF, NEG_INF), - (FLT_MAX, TWO, NEG_FLT_MAX, POS_INF), # mul overflows to +inf - (NEG_FLT_MAX, TWO, FLT_MAX, NEG_INF), # mul overflows to -inf - (FLT_MAX, ONE, FLT_MAX, POS_INF), # add overflows to +inf - (NEG_FLT_MAX, ONE, NEG_FLT_MAX, NEG_INF), # add overflows to -inf - ] - for a, b, c, want in exact_cases: - with self.subTest(a=hex(a), b=hex(b), c=hex(c)): - self.assertEqual(ref_madak_f32(a, b, c), want) - self.assertEqual(ref_madmk_f32(a, b, c), want) - self.assertEqual(run_madak(a, b, c), want) - self.assertEqual(run_madmk(a, b, c), want) - - def test_nan_propagation_and_invalid_operations(self): - nan_cases = [ - # NaN in src0, second multiplicand, or addend (including literal K for both ops). - (QNAN, ONE, TWO), - (ONE, QNAN, TWO), - (ONE, TWO, QNAN), - (NEG_QNAN, TWO, THREE), - (TWO, NEG_QNAN, THREE), - (TWO, THREE, NEG_QNAN), - (SNAN, ONE, TWO), - (ONE, SNAN, TWO), - (ONE, TWO, SNAN), - # 0 * inf -> NaN - (POS_ZERO, POS_INF, ONE), - (POS_INF, POS_ZERO, ONE), - (NEG_ZERO, NEG_INF, TWO), - (NEG_INF, NEG_ZERO, TWO), - # (+inf) + (-inf) -> NaN - (POS_INF, ONE, NEG_INF), - (NEG_INF, ONE, POS_INF), - (ONE, POS_INF, NEG_INF), - (NEG_ONE, POS_INF, POS_INF), - ] - for a, b, c in nan_cases: - with self.subTest(a=hex(a), b=hex(b), c=hex(c)): - self.assertTrue(is_nan_bits(ref_madak_f32(a, b, c))) - self.assertTrue(is_nan_bits(ref_madmk_f32(a, b, c))) - self.assertTrue(is_nan_bits(run_madak(a, b, c))) - self.assertTrue(is_nan_bits(run_madmk(a, b, c))) - - def test_chained_madak_and_madmk(self): - # 1. Horner evaluation of p(x) = ((2.5*x - 1.5)*x + 0.5)*x + 3.0 at x = 2.0 using v_madak_f32: - # step1: 2.5 * 2.0 + (-1.5) = 3.5 - # step2: 3.5 * 2.0 + 0.5 = 7.5 - # step3: 7.5 * 2.0 + 3.0 = 18.0 - # 2. Chained v_madmk_f32 scale-and-accumulate: - # v2 = 1.5, v3 = 0.25 -> v4 = v2 * 2.0 + v3 = 3.25 - # -> v4 = v4 * (-0.5) + v2 = -1.625 + 1.5 = -0.125 - # -> v4 = v4 * 4.0 + v3 = -0.5 + 0.25 = -0.25 - # 3. Interleaved v_madmk_f32 -> v_madak_f32 -> v_madmk_f32: - # v5 = 3.0, v6 = 0.5 -> v7 = v5 * 2.5 + v6 = 8.0 - # -> v7 = v7 * v6 + (-1.0) = 3.0 - # -> v7 = v7 * 0xbf000000 + v5 = 3.0*(-0.5) + 3.0 = 1.5 - # 4. Non-power-of-two fractional chain checked against exact reference oracle. - x0 = f32_to_bits(0.3) - y0 = f32_to_bits(1.7) - k1 = f32_to_bits(-0.7) - k2 = f32_to_bits(2.3) - k3 = f32_to_bits(0.1) - want_chain = ref_madak_f32(ref_madmk_f32(ref_madak_f32(x0, y0, k1), k2, x0), y0, k3) - - words = run_ps_mrt0([ - f"v_mov_b32 v1, {TWO:#x}", - f"v_mov_b32 v10, {TWO_HALF:#x}", - "v_madak_f32 v10, v10, v1, -1.5", - "v_madak_f32 v10, v10, v1, 0.5", - "v_madak_f32 v10, v10, v1, 3.0", - f"v_mov_b32 v2, {ONE_HALF:#x}", - f"v_mov_b32 v3, {QUARTER:#x}", - "v_madmk_f32 v11, v2, 2.0, v3", - "v_madmk_f32 v11, v11, -0.5, v2", - "v_madmk_f32 v11, v11, 4.0, v3", - f"v_mov_b32 v5, {THREE:#x}", - f"v_mov_b32 v6, {HALF:#x}", - "v_madmk_f32 v12, v5, 2.5, v6", - "v_madak_f32 v12, v12, v6, -1.0", - "v_madmk_f32 v12, v12, 0xbf000000, v5", - f"v_mov_b32 v8, {x0:#x}", - f"v_mov_b32 v9, {y0:#x}", - f"v_madak_f32 v13, v8, v9, {k1:#x}", - f"v_madmk_f32 v13, v13, {k2:#x}, v8", - f"v_madak_f32 v13, v13, v9, {k3:#x}", - ], ("v10", "v11", "v12", "v13")) - self.assertEqual(words, [f32_to_bits(18.0), f32_to_bits(-0.25), ONE_HALF, want_chain]) - - -class ExecMaskingTests(unittest.TestCase): - """Inactive lanes under EXEC must leave destination registers untouched for v_madak_f32 and v_madmk_f32.""" - - def test_pixel_shader_inactive_exec_preserves_destination(self): - sentinel = 0x3E4CCCCD # 0.2f - insns = [ - f"v_madak_f32 v0, v1, v2, {FIVE:#x}", - f"v_madak_f32_e32 v0, v1, v2, 2.5", - f"v_madmk_f32 v0, v1, {FIVE:#x}, v2", - f"v_madmk_f32_e32 v0, v1, -0.5, v2", - ] - for disable_exec in ("s_mov_b32 exec_lo, 0", "v_cmpx_eq_u32_e32 vcc_lo, 0, 1"): - for insn in insns: - with self.subTest(disable=disable_exec, insn=insn): - got = run_ps_mrt0([ - f"v_mov_b32 v0, {sentinel:#x}", - f"v_mov_b32 v1, {TWO:#x}", - f"v_mov_b32 v2, {THREE:#x}", - disable_exec, - insn, - "s_mov_b32 exec_lo, 1", - ])[0] - self.assertEqual(got, sentinel) - - def test_compute_workgroup_partial_exec_mask(self): - sentinel = ONE - cases = [ - (f"v_madak_f32 v1, v2, v4, {FIVE:#x}", f32_to_bits(3.0 * (-2.0) + 5.0)), # -1.0 - (f"v_madmk_f32 v1, v2, {FIVE:#x}, v4", f32_to_bits(3.0 * 5.0 + (-2.0))), # 13.0 - ] - for insn, active_val in cases: - with self.subTest(insn=insn): - mem = run_cs_workgroup_exec([ - "v_lshlrev_b32 v3, 2, v0", - f"v_mov_b32 v1, {sentinel:#x}", - f"v_mov_b32 v2, {THREE:#x}", - f"v_mov_b32 v4, {NEG_TWO:#x}", - "s_mov_b32 exec_lo, 5", # lanes 0 and 2 active; lanes 1 and 3 inactive - insn, - "s_mov_b32 exec_lo, 0xf", - "buffer_store_dword v1, v3, s[0:3], 0 offen", - ]) - self.assertEqual(mem, {0x0: active_val, 0x4: sentinel, 0x8: active_val, 0xC: sentinel}) - - -class NegativeControlsTests(unittest.TestCase): - """Sabotage translated SPIR-V output and confirm value assertions catch each mutation.""" - - def test_sabotaged_spirv_is_detected(self): - # 1. v_madak_f32 OpFAdd mutated to OpFSub. - spv_ak = translate_ps([ - f"v_mov_b32 v1, {TWO:#x}", - f"v_mov_b32 v2, {THREE:#x}", - f"v_madak_f32 v0, v1, v2, {FIVE:#x}", - ]) - want_ak = f32_to_bits(11.0) - self.assertEqual(si.run_fragment(spv_ak)["%out_mrt0"][0], want_ak) - self.assertNotEqual(si.run_fragment(spv_ak.replace("OpFAdd %float", "OpFSub %float"))["%out_mrt0"][0], want_ak) - - # 2. v_madmk_f32 multiplicand/addend swap (reproducing the pre-2026-11-21 S0*S1+K bug). - spv_mk = translate_ps([ - f"v_mov_b32 v1, {TWO:#x}", - f"v_mov_b32 v2, {THREE:#x}", - f"v_madmk_f32 v0, v1, {FIVE:#x}, v2", - ]) - want_mk = f32_to_bits(13.0) - self.assertEqual(si.run_fragment(spv_mk)["%out_mrt0"][0], want_mk) - bad_mk, count = re.subn( - r"(%\w+) = OpFMul %float (%\w+) (%\w+)\n(\s*)(%\w+) = OpFAdd %float \1 (%\w+)", - r"\1 = OpFMul %float \2 \6\n\4\5 = OpFAdd %float \1 \3", - spv_mk, - ) - self.assertEqual(count, 1) - self.assertEqual(si.run_fragment(bad_mk)["%out_mrt0"][0], want_ak) - self.assertNotEqual(si.run_fragment(bad_mk)["%out_mrt0"][0], want_mk) - - # 3. Replacing unfused OpFMul + OpFAdd with fused Fma breaks the cancellation case. - spv_unfused = translate_ps([ - "v_mov_b32 v1, 0x3f800008", - "v_mov_b32 v2, 0x3f7ffff0", - f"v_madak_f32 v0, v1, v2, {NEG_ONE:#x}", - ]) - self.assertEqual(si.run_fragment(spv_unfused)["%out_mrt0"][0], POS_ZERO) - bad_fused, fcnt = re.subn( - r"(%\w+) = OpFMul %float (%\w+) (%\w+)\n(\s*)(%\w+) = OpFAdd %float \1 (%\w+)", - r"\5 = OpExtInst %float %glsl Fma \2 \3 \6", - spv_unfused, - ) - self.assertEqual(fcnt, 1) - # Drop any dangling OpDecorate on the removed OpFMul id so spirv_mini_interp parses cleanly. - fmul_id = re.search(r"(%\w+) = OpFMul %float", spv_unfused).group(1) - bad_fused = re.sub(rf"^\s*OpDecorate {re.escape(fmul_id)} NoContraction\n", "", bad_fused, flags=re.M) - self.assertNotEqual(si.run_fragment(bad_fused)["%out_mrt0"][0], POS_ZERO) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_valu_minmax_f64.py b/tests/semantic/test_valu_minmax_f64.py deleted file mode 100644 index 21d88a467..000000000 --- a/tests/semantic/test_valu_minmax_f64.py +++ /dev/null @@ -1,1483 +0,0 @@ -"""Semantic interpreter tests and reference mathematical oracle for RDNA2 v_min_f64 and v_max_f64. - -Models IEEE 754-2008 / IEEE 754-2019 binary64 double-precision minNum/maxNum and AMD RDNA2 / GFX10 -Vector Arithmetic Logic Unit (VALU) architectural semantics: - - v_min_f64: D.d = min(S0.d, S1.d) - - v_max_f64: D.d = max(S0.d, S1.d) - -RDNA2 Double-Precision Floating-Point ISA Rules: - 1. Register Pair Allocation: - Double-precision 64-bit values occupy aligned pairs of 32-bit vector registers: - v[d:d+1] where low 32 bits reside in v[d] and high 32 bits in v[d+1]. - 2. NaN Suppression (IEEE 754-2008 / 2019 minNum / maxNum): - If one operand is NaN and the other is a valid floating-point number, the valid number is - returned unchanged. If both operands are NaN, a quiet NaN is returned. - 3. Signed Zero Ordering (-0.0 < +0.0): - RDNA2 orders -0.0 strictly less than +0.0: - min(+0.0, -0.0) = -0.0, min(-0.0, +0.0) = -0.0 - max(+0.0, -0.0) = +0.0, max(-0.0, +0.0) = +0.0 - 4. Infinities & Subnormals: - -INF < all finite numbers < +INF. - Subnormal double values are preserved without flushing to zero in IEEE mode. - 5. VOP3 Encoding Modifiers: - Input modifiers: abs (|x|) clears sign bit 63; neg (-x) inverts sign bit 63. - When both abs and neg are set, neg(abs(x)) clears then sets sign bit (forcing negative). - Output modifier: clamp clamps final result to [0.0, 1.0]. Clamping negative values or -0.0 - yields +0.0. Clamping NaN returns NaN unchanged. - -Standard library Python only; zero third-party dependencies; zero game data. -Python 3.9+ compatible (from __future__ import annotations). -""" -from __future__ import annotations - -import dataclasses -import enum -import math -import os -import struct -import sys -import unittest - -MASK32: int = 0xFFFFFFFF -MASK64: int = 0xFFFFFFFFFFFFFFFF -SIGN_MASK_F64: int = 0x8000000000000000 -EXP_MASK_F64: int = 0x7FF0000000000000 -MANT_MASK_F64: int = 0x000FFFFFFFFFFFFF -QUIET_NAN_BIT_F64: int = 0x0008000000000000 - -# Canonical IEEE 754 binary64 bit patterns -POS_ZERO_F64: int = 0x0000000000000000 -NEG_ZERO_F64: int = 0x8000000000000000 -POS_ONE_F64: int = 0x3FF0000000000000 # 1.0 -NEG_ONE_F64: int = 0xBFF0000000000000 # -1.0 -POS_TWO_F64: int = 0x4000000000000000 # 2.0 -NEG_TWO_F64: int = 0xC000000000000000 # -2.0 -HALF_F64: int = 0x3FE0000000000000 # 0.5 -NEG_HALF_F64: int = 0xBFE0000000000000 # -0.5 -POS_THREE_F64: int = 0x4008000000000000 # 3.0 -POS_TEN_F64: int = 0x4024000000000000 # 10.0 -NEG_TEN_F64: int = 0xC024000000000000 # -10.0 - -DBL_MIN: int = 0x0010000000000000 # Smallest positive normal: 2^-1022 -NEG_DBL_MIN: int = 0x8010000000000000 # -2^-1022 -DBL_MAX: int = 0x7FEFFFFFFFFFFFFF # (2 - 2^-52) * 2^1023 -NEG_DBL_MAX: int = 0xFFEFFFFFFFFFFFFF -POS_INF_F64: int = 0x7FF0000000000000 # +infinity -NEG_INF_F64: int = 0xFFF0000000000000 # -infinity -QNAN_F64: int = 0x7FF8000000000000 # Canonical quiet NaN -NEG_QNAN_F64: int = 0xFFF8000000000000 # Negative quiet NaN -QNAN_PAYLOAD_A: int = 0x7FF8000000000001 # Quiet NaN with payload A -QNAN_PAYLOAD_B: int = 0xFFF9000000000002 # Quiet NaN with payload B -SNAN_F64: int = 0x7FF0000000000001 # Signaling NaN (MSB of mantissa is 0, payload != 0) -SUBNORM_MIN_F64: int = 0x0000000000000001 # Smallest subnormal: 2^-1074 -SUBNORM_MAX_F64: int = 0x000FFFFFFFFFFFFF # Largest positive subnormal: (1 - 2^-52) * 2^-1022 -NEG_SUBNORM_MIN_F64: int = 0x8000000000000001 -NEG_SUBNORM_MAX_F64: int = 0x800FFFFFFFFFFFFF - - -def u32(val: int) -> int: - """Normalize integer to unsigned 32-bit range [0, 2^32 - 1].""" - return val & MASK32 - - -def u64(val: int) -> int: - """Normalize integer to unsigned 64-bit range [0, 2^64 - 1].""" - return val & MASK64 - - -def s64(val: int) -> int: - """Interpret a 64-bit unsigned word as a signed two's-complement integer.""" - val &= MASK64 - return val - (1 << 64) if (val & SIGN_MASK_F64) else val - - -def split_dwords(val64: int) -> tuple[int, int]: - """Split an unsigned 64-bit integer into (low_dword, high_dword).""" - val = val64 & MASK64 - return val & MASK32, (val >> 32) & MASK32 - - -def join_dwords(lo: int, hi: int) -> int: - """Join (low_dword, high_dword) into an unsigned 64-bit integer.""" - return ((hi & MASK32) << 32) | (lo & MASK32) - - -def bits_to_f64(bits: int) -> float: - """Decode 64-bit unsigned integer to IEEE 754 double-precision float.""" - return struct.unpack(" int: - """Encode double float to IEEE 754 double-precision 64-bit unsigned integer.""" - try: - return struct.unpack(" 0 else NEG_INF_F64 - - -def is_nan_f64(bits: int) -> bool: - """True if 64-bit integer represents an IEEE 754 double NaN.""" - bits &= MASK64 - return (bits & EXP_MASK_F64) == EXP_MASK_F64 and (bits & MANT_MASK_F64) != 0 - - -def is_qnan_f64(bits: int) -> bool: - """True if bits represent a quiet NaN (MSB of mantissa bit 51 is 1).""" - bits &= MASK64 - return is_nan_f64(bits) and bool(bits & QUIET_NAN_BIT_F64) - - -def is_snan_f64(bits: int) -> bool: - """True if bits represent a signaling NaN (MSB of mantissa bit 51 is 0).""" - bits &= MASK64 - return is_nan_f64(bits) and not bool(bits & QUIET_NAN_BIT_F64) - - -def is_subnormal_f64(bits: int) -> bool: - """True if bits represent an IEEE 754 double subnormal number.""" - bits &= MASK64 - return (bits & EXP_MASK_F64) == 0 and (bits & MANT_MASK_F64) != 0 - - -def zero_ordered_key(v: float) -> tuple[float, float]: - """Sort key ordering -0.0 strictly below +0.0.""" - return (v, math.copysign(1.0, v)) - - -def ref_min_f64(s0: int, s1: int) -> int: - """Pure bitwise reference oracle for RDNA2 v_min_f64. - - Rules: - - If one operand is NaN, return the non-NaN operand unchanged. - - If both operands are NaN, return canonical quiet NaN (0x7FF8000000000000). - - If non-NaN values, order -0.0 < +0.0. - """ - s0 &= MASK64 - s1 &= MASK64 - nan0 = is_nan_f64(s0) - nan1 = is_nan_f64(s1) - if nan0 and nan1: - return QNAN_F64 - if nan0: - return s1 - if nan1: - return s0 - - f0 = bits_to_f64(s0) - f1 = bits_to_f64(s1) - k0 = zero_ordered_key(f0) - k1 = zero_ordered_key(f1) - return s0 if k0 <= k1 else s1 - - -def ref_max_f64(s0: int, s1: int) -> int: - """Pure bitwise reference oracle for RDNA2 v_max_f64. - - Rules: - - If one operand is NaN, return the non-NaN operand unchanged. - - If both operands are NaN, return canonical quiet NaN (0x7FF8000000000000). - - If non-NaN values, order -0.0 < +0.0. - """ - s0 &= MASK64 - s1 &= MASK64 - nan0 = is_nan_f64(s0) - nan1 = is_nan_f64(s1) - if nan0 and nan1: - return QNAN_F64 - if nan0: - return s1 - if nan1: - return s0 - - f0 = bits_to_f64(s0) - f1 = bits_to_f64(s1) - k0 = zero_ordered_key(f0) - k1 = zero_ordered_key(f1) - return s0 if k0 >= k1 else s1 - - -def apply_f64_modifiers(bits: int, neg: bool = False, abs_val: bool = False) -> int: - """Applies VOP3 input modifiers: abs (|x|) first, then neg (-x).""" - bits &= MASK64 - if abs_val: - bits &= ~SIGN_MASK_F64 - if neg: - bits ^= SIGN_MASK_F64 - return bits & MASK64 - - -def apply_f64_clamp(bits: int) -> int: - """Applies VOP3 clamp modifier: clamps result to [0.0, 1.0].""" - bits &= MASK64 - if is_nan_f64(bits): - return bits - val = bits_to_f64(bits) - if val < 0.0 or (val == 0.0 and (bits & SIGN_MASK_F64)): - return POS_ZERO_F64 - if val > 1.0: - return POS_ONE_F64 - return bits - - -def ref_min_f64_ext( - s0: int, - s1: int, - neg0: bool = False, - abs0: bool = False, - neg1: bool = False, - abs1: bool = False, - clamp: bool = False, -) -> int: - """Reference oracle for v_min_f64 with input and output modifiers.""" - mod0 = apply_f64_modifiers(s0, neg=neg0, abs_val=abs0) - mod1 = apply_f64_modifiers(s1, neg=neg1, abs_val=abs1) - res = ref_min_f64(mod0, mod1) - return apply_f64_clamp(res) if clamp else res - - -def ref_max_f64_ext( - s0: int, - s1: int, - neg0: bool = False, - abs0: bool = False, - neg1: bool = False, - abs1: bool = False, - clamp: bool = False, -) -> int: - """Reference oracle for v_max_f64 with input and output modifiers.""" - mod0 = apply_f64_modifiers(s0, neg=neg0, abs_val=abs0) - mod1 = apply_f64_modifiers(s1, neg=neg1, abs_val=abs1) - res = ref_max_f64(mod0, mod1) - return apply_f64_clamp(res) if clamp else res - - -# --------------------------------------------------------------------------- -# Symbolic AST Opcode Definitions and Typed Expressions -# --------------------------------------------------------------------------- - -class RegKind(enum.Enum): - """Register file domain.""" - VGPR = "v" - SGPR = "s" - - -@dataclasses.dataclass(frozen=True) -class Register: - """Symbolic register operand representing an aligned 64-bit pair or 32-bit register.""" - kind: RegKind - index: int - count: int = 2 - - def __post_init__(self) -> None: - if self.index < 0 or self.index >= 256: - raise ValueError(f"Register index out of range [0, 255]: {self.index}") - if self.count not in (1, 2): - raise ValueError(f"Unsupported register count (must be 1 or 2): {self.count}") - if self.count == 2 and self.index + 1 >= 256: - raise ValueError(f"64-bit register pair exceeds register file boundary: {self.index}") - - @property - def is_vgpr(self) -> bool: - return self.kind == RegKind.VGPR - - @property - def is_sgpr(self) -> bool: - return self.kind == RegKind.SGPR - - def format_asm(self) -> str: - if self.count == 2: - return f"{self.kind.value}[{self.index}:{self.index + 1}]" - return f"{self.kind.value}{self.index}" - - -@dataclasses.dataclass(frozen=True) -class Immediate: - """Symbolic 64-bit immediate operand (float or bit pattern).""" - bits: int - - def __init__(self, val: int | float) -> None: - if isinstance(val, float): - b = f64_to_bits(val) - else: - b = val & MASK64 - object.__setattr__(self, "bits", b) - - @property - def as_float(self) -> float: - return bits_to_f64(self.bits) - - def format_asm(self) -> str: - return f"{self.bits:#018x}" - - -@dataclasses.dataclass(frozen=True) -class OperandModifiers: - """Input modifiers for VALU floating-point instructions (abs and neg).""" - neg: bool = False - abs_val: bool = False - - def apply(self, bits: int) -> int: - return apply_f64_modifiers(bits, neg=self.neg, abs_val=self.abs_val) - - def format_asm(self, base_str: str) -> str: - res = base_str - if self.abs_val: - res = f"|{res}|" - if self.neg: - res = f"-{res}" - return res - - -@dataclasses.dataclass(frozen=True) -class InstructionModifiers: - """Output modifiers for VALU instructions (clamp).""" - clamp: bool = False - - def apply(self, bits: int) -> int: - return apply_f64_clamp(bits) if self.clamp else (bits & MASK64) - - def format_asm(self) -> str: - return " clamp" if self.clamp else "" - - -class Opcode(enum.Enum): - """VALU 64-bit floating-point opcodes.""" - V_MIN_F64 = "v_min_f64" - V_MAX_F64 = "v_max_f64" - - -class Encoding(enum.Enum): - """Instruction encoding format.""" - VOP2 = "e32" - VOP3 = "e64" - - -@dataclasses.dataclass(frozen=True) -class Instruction: - """Symbolic AST node representing a double-precision VALU instruction.""" - opcode: Opcode - dst: Register - src0: Register | Immediate - src1: Register | Immediate - src0_mods: OperandModifiers = dataclasses.field(default_factory=OperandModifiers) - src1_mods: OperandModifiers = dataclasses.field(default_factory=OperandModifiers) - inst_mods: InstructionModifiers = dataclasses.field(default_factory=InstructionModifiers) - encoding: Encoding = Encoding.VOP3 - - def __post_init__(self) -> None: - if not self.dst.is_vgpr: - raise ValueError(f"VALU instruction destination must be a VGPR: {self.dst}") - if self.dst.count != 2: - raise ValueError(f"VALU f64 instruction destination must be a 64-bit pair (count=2): {self.dst}") - # VOP2 (e32) encoding does not support input modifiers or clamp - has_mods = self.src0_mods.neg or self.src0_mods.abs_val or self.src1_mods.neg or self.src1_mods.abs_val or self.inst_mods.clamp - if self.encoding == Encoding.VOP2 and has_mods: - raise ValueError("VOP2 encoding does not support input modifiers or clamp (requires VOP3/e64)") - - def to_assembly(self) -> str: - s0_str = self.src0.format_asm() - s1_str = self.src1.format_asm() - s0_fmt = self.src0_mods.format_asm(s0_str) - s1_fmt = self.src1_mods.format_asm(s1_str) - dst_str = self.dst.format_asm() - clamp_str = self.inst_mods.format_asm() - enc_suffix = f"_{self.encoding.value}" if self.encoding == Encoding.VOP2 else "" - return f"{self.opcode.value}{enc_suffix} {dst_str}, {s0_fmt}, {s1_fmt}{clamp_str}" - - -@dataclasses.dataclass -class Program: - """Symbolic sequence of VALU instructions.""" - instructions: list[Instruction] = dataclasses.field(default_factory=list) - - def append(self, inst: Instruction) -> None: - self.instructions.append(inst) - - def to_assembly(self) -> str: - return "\n".join(inst.to_assembly() for inst in self.instructions) - - -# --------------------------------------------------------------------------- -# Condition Codes, Status Flags, and Carry/Borrow Isolation -# --------------------------------------------------------------------------- - -@dataclasses.dataclass(frozen=True) -class ConditionCodes: - """Architectural condition codes for double-precision float operations.""" - equal: bool - less: bool - greater: bool - unordered: bool - zero: bool - negative: bool - - -@dataclasses.dataclass(frozen=True) -class FPStatusFlags: - """IEEE 754 floating-point status flags.""" - invalid: bool # e.g., sNaN operand - denormal: bool # e.g., subnormal operand - inexact: bool = False - overflow: bool = False - underflow: bool = False - - -def compute_condition_codes(s0: int, s1: int, result: int) -> ConditionCodes: - """Computes condition codes evaluating relationship of s0 vs s1 and result attributes.""" - s0 &= MASK64 - s1 &= MASK64 - result &= MASK64 - nan0 = is_nan_f64(s0) - nan1 = is_nan_f64(s1) - - if nan0 or nan1: - unordered = True - equal = False - less = False - greater = False - else: - unordered = False - f0 = bits_to_f64(s0) - f1 = bits_to_f64(s1) - k0 = zero_ordered_key(f0) - k1 = zero_ordered_key(f1) - equal = (k0 == k1) - less = (k0 < k1) - greater = (k0 > k1) - - res_zero = (result in (POS_ZERO_F64, NEG_ZERO_F64)) - res_negative = bool(result & SIGN_MASK_F64) - return ConditionCodes( - equal=equal, - less=less, - greater=greater, - unordered=unordered, - zero=res_zero, - negative=res_negative, - ) - - -def compute_fp_status_flags(s0: int, s1: int, result: int) -> FPStatusFlags: - """Computes IEEE 754 status flags for double-precision operations.""" - invalid = is_snan_f64(s0) or is_snan_f64(s1) - denormal = is_subnormal_f64(s0) or is_subnormal_f64(s1) or is_subnormal_f64(result) - return FPStatusFlags( - invalid=invalid, - denormal=denormal, - inexact=False, - overflow=False, - underflow=False, - ) - - -# --------------------------------------------------------------------------- -# Deterministic Scalar Instruction Interpreter -# --------------------------------------------------------------------------- - -class ScalarVALUInterpreter: - """Deterministic scalar interpreter for GFX10/RDNA2 VALU f64 instructions.""" - - def __init__(self) -> None: - self.vgprs: list[int] = [0] * 256 - self.sgprs: list[int] = [0] * 106 - self.vcc: int = 0 - self.last_condition_codes: ConditionCodes | None = None - self.last_status_flags: FPStatusFlags | None = None - self.trace: list[str] = [] - - def read_reg_u32(self, kind: RegKind, idx: int) -> int: - if idx < 0 or (kind == RegKind.VGPR and idx >= 256) or (kind == RegKind.SGPR and idx >= 106): - raise IndexError(f"Register index out of bounds: {kind.value}{idx}") - return (self.vgprs[idx] if kind == RegKind.VGPR else self.sgprs[idx]) & MASK32 - - def write_reg_u32(self, kind: RegKind, idx: int, val: int) -> None: - if idx < 0 or (kind == RegKind.VGPR and idx >= 256) or (kind == RegKind.SGPR and idx >= 106): - raise IndexError(f"Register index out of bounds: {kind.value}{idx}") - val32 = val & MASK32 - if kind == RegKind.VGPR: - self.vgprs[idx] = val32 - else: - self.sgprs[idx] = val32 - - def read_reg_u64(self, kind: RegKind, idx: int) -> int: - lo = self.read_reg_u32(kind, idx) - hi = self.read_reg_u32(kind, idx + 1) - return join_dwords(lo, hi) - - def write_reg_u64(self, kind: RegKind, idx: int, val: int) -> None: - lo, hi = split_dwords(val) - self.write_reg_u32(kind, idx, lo) - self.write_reg_u32(kind, idx + 1, hi) - - def read_operand(self, op: Register | Immediate, mods: OperandModifiers) -> int: - if isinstance(op, Immediate): - raw = op.bits - elif isinstance(op, Register): - raw = self.read_reg_u64(op.kind, op.index) - else: - raise TypeError(f"Unsupported operand type: {type(op)}") - return mods.apply(raw) - - def step(self, inst: Instruction) -> int: - """Executes a single VALU instruction deterministically.""" - # Latch all input operands before writing to destination (read-before-write semantics) - s0_val = self.read_operand(inst.src0, inst.src0_mods) - s1_val = self.read_operand(inst.src1, inst.src1_mods) - - if inst.opcode == Opcode.V_MIN_F64: - res_raw = ref_min_f64(s0_val, s1_val) - elif inst.opcode == Opcode.V_MAX_F64: - res_raw = ref_max_f64(s0_val, s1_val) - else: - raise NotImplementedError(f"Unsupported opcode in scalar interpreter: {inst.opcode}") - - final_res = inst.inst_mods.apply(res_raw) - self.write_reg_u64(inst.dst.kind, inst.dst.index, final_res) - self.last_condition_codes = compute_condition_codes(s0_val, s1_val, final_res) - self.last_status_flags = compute_fp_status_flags(s0_val, s1_val, final_res) - # Note: In GFX10/RDNA2, VALU floating-point min/max instructions do NOT generate carry/borrow; - # VCC is preserved and never modified. - self.trace.append(f"{inst.to_assembly()} => {final_res:#018x}") - return final_res - - def run_program(self, prog: Program) -> list[int]: - """Executes all instructions in a program sequentially.""" - return [self.step(inst) for inst in prog.instructions] - - -# --------------------------------------------------------------------------- -# SIMD Wavefront Interpreter (Multi-Lane Divergence & 32/64-Bit EXEC Masking) -# --------------------------------------------------------------------------- - -class SIMDWavefrontInterpreter: - """Multi-lane SIMD interpreter modeling Wave32 and Wave64 execution on RDNA2.""" - - def __init__(self, wave_size: int = 64) -> None: - if wave_size not in (32, 64): - raise ValueError(f"Invalid wave_size: {wave_size} (must be 32 or 64)") - self.wave_size: int = wave_size - self.exec_mask: int = (1 << wave_size) - 1 - # Per-lane VGPR files: [wave_size][256] 32-bit registers - self.vgprs: list[list[int]] = [[0] * 256 for _ in range(wave_size)] - # Wavefront-shared SGPR file: [106] 32-bit registers - self.sgprs: list[int] = [0] * 106 - self.vcc: int = 0 - - def set_exec_mask(self, mask: int) -> None: - valid_mask = (1 << self.wave_size) - 1 - self.exec_mask = mask & valid_mask - - def read_lane_reg_u32(self, lane: int, kind: RegKind, idx: int) -> int: - if kind == RegKind.VGPR: - return self.vgprs[lane][idx] & MASK32 - return self.sgprs[idx] & MASK32 - - def write_lane_reg_u32(self, lane: int, kind: RegKind, idx: int, val: int) -> None: - val32 = val & MASK32 - if kind == RegKind.VGPR: - self.vgprs[lane][idx] = val32 - else: - self.sgprs[idx] = val32 - - def read_lane_reg_u64(self, lane: int, kind: RegKind, idx: int) -> int: - lo = self.read_lane_reg_u32(lane, kind, idx) - hi = self.read_lane_reg_u32(lane, kind, idx + 1) - return join_dwords(lo, hi) - - def write_lane_reg_u64(self, lane: int, kind: RegKind, idx: int, val: int) -> None: - lo, hi = split_dwords(val) - self.write_lane_reg_u32(lane, kind, idx, lo) - self.write_lane_reg_u32(lane, kind, idx + 1, hi) - - def read_lane_operand(self, lane: int, op: Register | Immediate, mods: OperandModifiers) -> int: - if isinstance(op, Immediate): - raw = op.bits - elif isinstance(op, Register): - raw = self.read_lane_reg_u64(lane, op.kind, op.index) - else: - raise TypeError(f"Unsupported operand type: {type(op)}") - return mods.apply(raw) - - def step(self, inst: Instruction) -> list[int | None]: - """Executes a VALU instruction across all lanes in the wavefront governed by EXEC mask.""" - # 1. Latch inputs for all lanes (read-before-write semantics across the wave) - latched_inputs: list[tuple[int, int]] = [] - for lane in range(self.wave_size): - s0_val = self.read_lane_operand(lane, inst.src0, inst.src0_mods) - s1_val = self.read_lane_operand(lane, inst.src1, inst.src1_mods) - latched_inputs.append((s0_val, s1_val)) - - # 2. Compute and write back strictly for active lanes - lane_results: list[int | None] = [] - for lane in range(self.wave_size): - is_active = bool((self.exec_mask >> lane) & 1) - if not is_active: - lane_results.append(None) - continue - - s0_val, s1_val = latched_inputs[lane] - if inst.opcode == Opcode.V_MIN_F64: - res_raw = ref_min_f64(s0_val, s1_val) - elif inst.opcode == Opcode.V_MAX_F64: - res_raw = ref_max_f64(s0_val, s1_val) - else: - raise NotImplementedError(f"Unsupported opcode in SIMD interpreter: {inst.opcode}") - - final_res = inst.inst_mods.apply(res_raw) - self.write_lane_reg_u64(lane, inst.dst.kind, inst.dst.index, final_res) - lane_results.append(final_res) - - return lane_results - - -class TestValuMinMaxF64Oracle(unittest.TestCase): - """Unit tests for the reference mathematical oracle and architectural model.""" - - def test_basic_float_min_max(self) -> None: - self.assertEqual(ref_min_f64(POS_ONE_F64, POS_TWO_F64), POS_ONE_F64) - self.assertEqual(ref_min_f64(POS_TWO_F64, POS_ONE_F64), POS_ONE_F64) - self.assertEqual(ref_max_f64(POS_ONE_F64, POS_TWO_F64), POS_TWO_F64) - self.assertEqual(ref_max_f64(POS_TWO_F64, POS_ONE_F64), POS_TWO_F64) - self.assertEqual(ref_min_f64(NEG_TWO_F64, NEG_ONE_F64), NEG_TWO_F64) - self.assertEqual(ref_max_f64(NEG_TWO_F64, NEG_ONE_F64), NEG_ONE_F64) - - def test_signed_zeros_ordering(self) -> None: - self.assertEqual(ref_min_f64(POS_ZERO_F64, NEG_ZERO_F64), NEG_ZERO_F64) - self.assertEqual(ref_min_f64(NEG_ZERO_F64, POS_ZERO_F64), NEG_ZERO_F64) - self.assertEqual(ref_max_f64(POS_ZERO_F64, NEG_ZERO_F64), POS_ZERO_F64) - self.assertEqual(ref_max_f64(NEG_ZERO_F64, POS_ZERO_F64), POS_ZERO_F64) - - def test_infinities_ordering(self) -> None: - self.assertEqual(ref_min_f64(NEG_INF_F64, POS_INF_F64), NEG_INF_F64) - self.assertEqual(ref_max_f64(NEG_INF_F64, POS_INF_F64), POS_INF_F64) - self.assertEqual(ref_min_f64(DBL_MAX, POS_INF_F64), DBL_MAX) - self.assertEqual(ref_max_f64(DBL_MAX, POS_INF_F64), POS_INF_F64) - self.assertEqual(ref_min_f64(NEG_DBL_MAX, NEG_INF_F64), NEG_INF_F64) - self.assertEqual(ref_max_f64(NEG_DBL_MAX, NEG_INF_F64), NEG_DBL_MAX) - - def test_subnormals_preservation(self) -> None: - self.assertTrue(is_subnormal_f64(SUBNORM_MIN_F64)) - self.assertTrue(is_subnormal_f64(SUBNORM_MAX_F64)) - self.assertEqual(ref_min_f64(SUBNORM_MIN_F64, SUBNORM_MAX_F64), SUBNORM_MIN_F64) - self.assertEqual(ref_max_f64(SUBNORM_MIN_F64, SUBNORM_MAX_F64), SUBNORM_MAX_F64) - self.assertEqual(ref_min_f64(POS_ZERO_F64, SUBNORM_MIN_F64), POS_ZERO_F64) - self.assertEqual(ref_max_f64(POS_ZERO_F64, SUBNORM_MIN_F64), SUBNORM_MIN_F64) - - def test_nan_suppression_and_propagation(self) -> None: - self.assertEqual(ref_min_f64(QNAN_F64, POS_ONE_F64), POS_ONE_F64) - self.assertEqual(ref_min_f64(POS_ONE_F64, QNAN_F64), POS_ONE_F64) - self.assertEqual(ref_max_f64(QNAN_F64, POS_ONE_F64), POS_ONE_F64) - self.assertEqual(ref_max_f64(POS_ONE_F64, QNAN_F64), POS_ONE_F64) - self.assertEqual(ref_min_f64(QNAN_PAYLOAD_A, QNAN_PAYLOAD_B), QNAN_F64) - self.assertEqual(ref_max_f64(QNAN_PAYLOAD_A, QNAN_PAYLOAD_B), QNAN_F64) - - def test_modifiers_abs_neg(self) -> None: - self.assertEqual(apply_f64_modifiers(NEG_ONE_F64, abs_val=True), POS_ONE_F64) - self.assertEqual(apply_f64_modifiers(POS_ONE_F64, neg=True), NEG_ONE_F64) - self.assertEqual(apply_f64_modifiers(POS_ONE_F64, neg=True, abs_val=True), NEG_ONE_F64) - self.assertEqual(ref_min_f64_ext(POS_TWO_F64, POS_ONE_F64, neg0=True), NEG_TWO_F64) - self.assertEqual(ref_max_f64_ext(NEG_TWO_F64, NEG_TEN_F64, abs0=True), POS_TWO_F64) - - def test_clamp_modifier(self) -> None: - self.assertEqual(apply_f64_clamp(NEG_TWO_F64), POS_ZERO_F64) - self.assertEqual(apply_f64_clamp(NEG_ZERO_F64), POS_ZERO_F64) - self.assertEqual(apply_f64_clamp(POS_TWO_F64), POS_ONE_F64) - self.assertEqual(apply_f64_clamp(HALF_F64), HALF_F64) - self.assertEqual(apply_f64_clamp(QNAN_F64), QNAN_F64) - - def test_split_join_dwords(self) -> None: - lo, hi = split_dwords(POS_ONE_F64) - self.assertEqual(lo, 0x00000000) - self.assertEqual(hi, 0x3FF00000) - self.assertEqual(join_dwords(lo, hi), POS_ONE_F64) - - -class TestValuMinMaxF64AST(unittest.TestCase): - """Unit tests for symbolic AST opcode definitions and typed expressions.""" - - def test_register_construction_and_formatting(self) -> None: - v0 = Register(RegKind.VGPR, 0, count=2) - v2 = Register(RegKind.VGPR, 2, count=2) - s4 = Register(RegKind.SGPR, 4, count=2) - self.assertTrue(v0.is_vgpr) - self.assertFalse(v0.is_sgpr) - self.assertTrue(s4.is_sgpr) - self.assertEqual(v0.format_asm(), "v[0:1]") - self.assertEqual(v2.format_asm(), "v[2:3]") - self.assertEqual(s4.format_asm(), "s[4:5]") - - def test_immediate_construction(self) -> None: - imm_f = Immediate(1.0) - imm_b = Immediate(0x7FF0000000000000) - self.assertEqual(imm_f.bits, POS_ONE_F64) - self.assertEqual(imm_f.as_float, 1.0) - self.assertEqual(imm_b.bits, POS_INF_F64) - - def test_operand_modifiers_formatting(self) -> None: - mods_none = OperandModifiers() - mods_abs = OperandModifiers(abs_val=True) - mods_neg = OperandModifiers(neg=True) - mods_both = OperandModifiers(neg=True, abs_val=True) - - self.assertEqual(mods_none.format_asm("v[0:1]"), "v[0:1]") - self.assertEqual(mods_abs.format_asm("v[0:1]"), "|v[0:1]|") - self.assertEqual(mods_neg.format_asm("v[0:1]"), "-v[0:1]") - self.assertEqual(mods_both.format_asm("v[0:1]"), "-|v[0:1]|") - - def test_instruction_formatting(self) -> None: - inst = Instruction( - opcode=Opcode.V_MIN_F64, - dst=Register(RegKind.VGPR, 0, count=2), - src0=Register(RegKind.VGPR, 2, count=2), - src1=Register(RegKind.VGPR, 4, count=2), - src0_mods=OperandModifiers(neg=True, abs_val=True), - inst_mods=InstructionModifiers(clamp=True), - ) - self.assertEqual(inst.to_assembly(), "v_min_f64 v[0:1], -|v[2:3]|, v[4:5] clamp") - - inst_e32 = Instruction( - opcode=Opcode.V_MAX_F64, - dst=Register(RegKind.VGPR, 0, count=2), - src0=Register(RegKind.VGPR, 2, count=2), - src1=Register(RegKind.VGPR, 4, count=2), - encoding=Encoding.VOP2, - ) - self.assertEqual(inst_e32.to_assembly(), "v_max_f64_e32 v[0:1], v[2:3], v[4:5]") - - def test_instruction_validation(self) -> None: - # Invalid destination kind (must be VGPR) - with self.assertRaises(ValueError): - Instruction( - opcode=Opcode.V_MIN_F64, - dst=Register(RegKind.SGPR, 0, count=2), - src0=Register(RegKind.VGPR, 2, count=2), - src1=Register(RegKind.VGPR, 4, count=2), - ) - - # Invalid destination count (must be 2 for 64-bit float) - with self.assertRaises(ValueError): - Instruction( - opcode=Opcode.V_MIN_F64, - dst=Register(RegKind.VGPR, 0, count=1), - src0=Register(RegKind.VGPR, 2, count=2), - src1=Register(RegKind.VGPR, 4, count=2), - ) - - # VOP2 cannot take modifiers - with self.assertRaises(ValueError): - Instruction( - opcode=Opcode.V_MIN_F64, - dst=Register(RegKind.VGPR, 0, count=2), - src0=Register(RegKind.VGPR, 2, count=2), - src1=Register(RegKind.VGPR, 4, count=2), - src0_mods=OperandModifiers(neg=True), - encoding=Encoding.VOP2, - ) - - def test_program_assembly(self) -> None: - prog = Program() - prog.append(Instruction( - opcode=Opcode.V_MIN_F64, - dst=Register(RegKind.VGPR, 0, count=2), - src0=Register(RegKind.VGPR, 2, count=2), - src1=Register(RegKind.VGPR, 4, count=2), - )) - prog.append(Instruction( - opcode=Opcode.V_MAX_F64, - dst=Register(RegKind.VGPR, 6, count=2), - src0=Register(RegKind.VGPR, 0, count=2), - src1=Immediate(1.0), - inst_mods=InstructionModifiers(clamp=True), - )) - expected = ( - "v_min_f64 v[0:1], v[2:3], v[4:5]\n" - f"v_max_f64 v[6:7], v[0:1], {POS_ONE_F64:#018x} clamp" - ) - self.assertEqual(prog.to_assembly(), expected) - - -class TestValuMinMaxF64ScalarInterpreter(unittest.TestCase): - """Unit tests for the deterministic scalar VALU instruction interpreter.""" - - def test_scalar_register_read_write(self) -> None: - interp = ScalarVALUInterpreter() - interp.write_reg_u64(RegKind.VGPR, 0, POS_ONE_F64) - interp.write_reg_u64(RegKind.SGPR, 4, NEG_TWO_F64) - - self.assertEqual(interp.read_reg_u64(RegKind.VGPR, 0), POS_ONE_F64) - self.assertEqual(interp.read_reg_u64(RegKind.SGPR, 4), NEG_TWO_F64) - self.assertEqual(interp.read_reg_u32(RegKind.VGPR, 0), 0x00000000) - self.assertEqual(interp.read_reg_u32(RegKind.VGPR, 1), 0x3FF00000) - - def test_scalar_min_execution_vgpr_sources(self) -> None: - interp = ScalarVALUInterpreter() - interp.write_reg_u64(RegKind.VGPR, 2, POS_TWO_F64) - interp.write_reg_u64(RegKind.VGPR, 4, POS_ONE_F64) - - inst = Instruction( - opcode=Opcode.V_MIN_F64, - dst=Register(RegKind.VGPR, 0, count=2), - src0=Register(RegKind.VGPR, 2, count=2), - src1=Register(RegKind.VGPR, 4, count=2), - ) - res = interp.step(inst) - self.assertEqual(res, POS_ONE_F64) - self.assertEqual(interp.read_reg_u64(RegKind.VGPR, 0), POS_ONE_F64) - - def test_scalar_max_execution_sgpr_sources(self) -> None: - interp = ScalarVALUInterpreter() - interp.write_reg_u64(RegKind.VGPR, 2, NEG_TWO_F64) - interp.write_reg_u64(RegKind.SGPR, 0, NEG_ONE_F64) - - inst = Instruction( - opcode=Opcode.V_MAX_F64, - dst=Register(RegKind.VGPR, 0, count=2), - src0=Register(RegKind.VGPR, 2, count=2), - src1=Register(RegKind.SGPR, 0, count=2), - ) - res = interp.step(inst) - self.assertEqual(res, NEG_ONE_F64) - self.assertEqual(interp.read_reg_u64(RegKind.VGPR, 0), NEG_ONE_F64) - - def test_scalar_immediate_operand(self) -> None: - interp = ScalarVALUInterpreter() - interp.write_reg_u64(RegKind.VGPR, 2, POS_TWO_F64) - - inst = Instruction( - opcode=Opcode.V_MIN_F64, - dst=Register(RegKind.VGPR, 0, count=2), - src0=Register(RegKind.VGPR, 2, count=2), - src1=Immediate(3.0), - ) - res = interp.step(inst) - self.assertEqual(res, POS_TWO_F64) - - def test_scalar_modifiers_abs_neg_clamp(self) -> None: - interp = ScalarVALUInterpreter() - interp.write_reg_u64(RegKind.VGPR, 2, NEG_TWO_F64) - interp.write_reg_u64(RegKind.VGPR, 4, POS_THREE_F64) - - # min(|-2.0|, 3.0) clamp -> min(2.0, 3.0) = 2.0 clamped to [0,1] = 1.0 - inst = Instruction( - opcode=Opcode.V_MIN_F64, - dst=Register(RegKind.VGPR, 0, count=2), - src0=Register(RegKind.VGPR, 2, count=2), - src1=Register(RegKind.VGPR, 4, count=2), - src0_mods=OperandModifiers(abs_val=True), - inst_mods=InstructionModifiers(clamp=True), - ) - res = interp.step(inst) - self.assertEqual(res, POS_ONE_F64) - - def test_scalar_program_execution_chain(self) -> None: - interp = ScalarVALUInterpreter() - interp.write_reg_u64(RegKind.VGPR, 2, POS_TEN_F64) # 10.0 - interp.write_reg_u64(RegKind.VGPR, 4, POS_TWO_F64) # 2.0 - interp.write_reg_u64(RegKind.VGPR, 6, HALF_F64) # 0.5 - - prog = Program() - # v[0:1] = min(v[2:3], v[4:5]) = min(10.0, 2.0) = 2.0 - prog.append(Instruction( - opcode=Opcode.V_MIN_F64, - dst=Register(RegKind.VGPR, 0, count=2), - src0=Register(RegKind.VGPR, 2, count=2), - src1=Register(RegKind.VGPR, 4, count=2), - )) - # v[8:9] = max(v[0:1], v[6:7]) = max(2.0, 0.5) = 2.0 - prog.append(Instruction( - opcode=Opcode.V_MAX_F64, - dst=Register(RegKind.VGPR, 8, count=2), - src0=Register(RegKind.VGPR, 0, count=2), - src1=Register(RegKind.VGPR, 6, count=2), - )) - - results = interp.run_program(prog) - self.assertEqual(results, [POS_TWO_F64, POS_TWO_F64]) - self.assertEqual(interp.read_reg_u64(RegKind.VGPR, 0), POS_TWO_F64) - self.assertEqual(interp.read_reg_u64(RegKind.VGPR, 8), POS_TWO_F64) - self.assertEqual(len(interp.trace), 2) - - -class TestValuMinMaxF64SIMD(unittest.TestCase): - """Unit tests for SIMD multi-lane divergence and 32/64-bit EXEC masking.""" - - def test_wave32_uniform_inputs(self) -> None: - simd = SIMDWavefrontInterpreter(wave_size=32) - inst = Instruction( - opcode=Opcode.V_MIN_F64, - dst=Register(RegKind.VGPR, 0, count=2), - src0=Register(RegKind.VGPR, 2, count=2), - src1=Register(RegKind.VGPR, 4, count=2), - ) - for lane in range(32): - simd.write_lane_reg_u64(lane, RegKind.VGPR, 2, POS_TWO_F64) - simd.write_lane_reg_u64(lane, RegKind.VGPR, 4, POS_ONE_F64) - - results = simd.step(inst) - self.assertEqual(len(results), 32) - for lane in range(32): - self.assertEqual(results[lane], POS_ONE_F64) - self.assertEqual(simd.read_lane_reg_u64(lane, RegKind.VGPR, 0), POS_ONE_F64) - - def test_wave64_multi_lane_divergence(self) -> None: - simd = SIMDWavefrontInterpreter(wave_size=64) - inst = Instruction( - opcode=Opcode.V_MAX_F64, - dst=Register(RegKind.VGPR, 0, count=2), - src0=Register(RegKind.VGPR, 2, count=2), - src1=Register(RegKind.VGPR, 4, count=2), - ) - expected: list[int] = [] - for lane in range(64): - v0 = f64_to_bits(float(lane)) - v1 = f64_to_bits(float(63 - lane)) - simd.write_lane_reg_u64(lane, RegKind.VGPR, 2, v0) - simd.write_lane_reg_u64(lane, RegKind.VGPR, 4, v1) - expected.append(ref_max_f64(v0, v1)) - - results = simd.step(inst) - for lane in range(64): - self.assertEqual(results[lane], expected[lane]) - self.assertEqual(simd.read_lane_reg_u64(lane, RegKind.VGPR, 0), expected[lane]) - - def test_wave32_exec_masking_partial(self) -> None: - simd = SIMDWavefrontInterpreter(wave_size=32) - # Checkerboard EXEC mask: even lanes active - exec_mask = 0x55555555 - simd.set_exec_mask(exec_mask) - - # Pre-populate dst v[0:1] with canary value - canary = 0xDEADBEEFCAFE0000 - for lane in range(32): - simd.write_lane_reg_u64(lane, RegKind.VGPR, 0, canary) - simd.write_lane_reg_u64(lane, RegKind.VGPR, 2, POS_TWO_F64) - simd.write_lane_reg_u64(lane, RegKind.VGPR, 4, POS_ONE_F64) - - inst = Instruction( - opcode=Opcode.V_MIN_F64, - dst=Register(RegKind.VGPR, 0, count=2), - src0=Register(RegKind.VGPR, 2, count=2), - src1=Register(RegKind.VGPR, 4, count=2), - ) - results = simd.step(inst) - - for lane in range(32): - if (exec_mask >> lane) & 1: - self.assertEqual(results[lane], POS_ONE_F64) - self.assertEqual(simd.read_lane_reg_u64(lane, RegKind.VGPR, 0), POS_ONE_F64) - else: - self.assertIsNone(results[lane]) - # Inactive lanes strictly retain prior register contents - self.assertEqual(simd.read_lane_reg_u64(lane, RegKind.VGPR, 0), canary) - - def test_wave64_exec_masking_all_inactive(self) -> None: - simd = SIMDWavefrontInterpreter(wave_size=64) - simd.set_exec_mask(0) - - canary = 0xBAADF00D12345678 - for lane in range(64): - simd.write_lane_reg_u64(lane, RegKind.VGPR, 0, canary) - simd.write_lane_reg_u64(lane, RegKind.VGPR, 2, POS_ONE_F64) - simd.write_lane_reg_u64(lane, RegKind.VGPR, 4, POS_TWO_F64) - - inst = Instruction( - opcode=Opcode.V_MIN_F64, - dst=Register(RegKind.VGPR, 0, count=2), - src0=Register(RegKind.VGPR, 2, count=2), - src1=Register(RegKind.VGPR, 4, count=2), - ) - results = simd.step(inst) - self.assertEqual(results, [None] * 64) - for lane in range(64): - self.assertEqual(simd.read_lane_reg_u64(lane, RegKind.VGPR, 0), canary) - - def test_simd_with_shared_sgpr_scalar_source(self) -> None: - simd = SIMDWavefrontInterpreter(wave_size=32) - # Write scalar value 5.0 to s[0:1] - simd.write_lane_reg_u64(0, RegKind.SGPR, 0, f64_to_bits(5.0)) - - # Each lane has divergent VGPR v[2:3] with value lane * 1.0 - for lane in range(32): - simd.write_lane_reg_u64(lane, RegKind.VGPR, 2, f64_to_bits(float(lane))) - - inst = Instruction( - opcode=Opcode.V_MIN_F64, - dst=Register(RegKind.VGPR, 0, count=2), - src0=Register(RegKind.VGPR, 2, count=2), - src1=Register(RegKind.SGPR, 0, count=2), - ) - results = simd.step(inst) - for lane in range(32): - expected = f64_to_bits(min(float(lane), 5.0)) - self.assertEqual(results[lane], expected) - self.assertEqual(simd.read_lane_reg_u64(lane, RegKind.VGPR, 0), expected) - - -class TestValuMinMaxF64RegisterAliasing(unittest.TestCase): - """Unit tests for register aliasing and in-place operand preservation.""" - - def test_aliasing_dst_equals_src0(self) -> None: - interp = ScalarVALUInterpreter() - # v[0:1] = 10.0, v[2:3] = 2.0 - interp.write_reg_u64(RegKind.VGPR, 0, POS_TEN_F64) - interp.write_reg_u64(RegKind.VGPR, 2, POS_TWO_F64) - - # v[0:1] = min(v[0:1], v[2:3]) - inst = Instruction( - opcode=Opcode.V_MIN_F64, - dst=Register(RegKind.VGPR, 0, count=2), - src0=Register(RegKind.VGPR, 0, count=2), - src1=Register(RegKind.VGPR, 2, count=2), - ) - res = interp.step(inst) - self.assertEqual(res, POS_TWO_F64) - self.assertEqual(interp.read_reg_u64(RegKind.VGPR, 0), POS_TWO_F64) - # v[2:3] preserved - self.assertEqual(interp.read_reg_u64(RegKind.VGPR, 2), POS_TWO_F64) - - def test_aliasing_dst_equals_src1(self) -> None: - interp = ScalarVALUInterpreter() - # v[0:1] = 10.0, v[2:3] = 2.0 - interp.write_reg_u64(RegKind.VGPR, 0, POS_TEN_F64) - interp.write_reg_u64(RegKind.VGPR, 2, POS_TWO_F64) - - # v[2:3] = max(v[0:1], v[2:3]) - inst = Instruction( - opcode=Opcode.V_MAX_F64, - dst=Register(RegKind.VGPR, 2, count=2), - src0=Register(RegKind.VGPR, 0, count=2), - src1=Register(RegKind.VGPR, 2, count=2), - ) - res = interp.step(inst) - self.assertEqual(res, POS_TEN_F64) - self.assertEqual(interp.read_reg_u64(RegKind.VGPR, 2), POS_TEN_F64) - # v[0:1] preserved - self.assertEqual(interp.read_reg_u64(RegKind.VGPR, 0), POS_TEN_F64) - - def test_aliasing_all_operands_same(self) -> None: - interp = ScalarVALUInterpreter() - interp.write_reg_u64(RegKind.VGPR, 0, NEG_TWO_F64) - - # v[0:1] = min(v[0:1], v[0:1]) with abs modifier on src0 - inst = Instruction( - opcode=Opcode.V_MIN_F64, - dst=Register(RegKind.VGPR, 0, count=2), - src0=Register(RegKind.VGPR, 0, count=2), - src1=Register(RegKind.VGPR, 0, count=2), - src0_mods=OperandModifiers(abs_val=True), - ) - # min(|-2.0|, -2.0) = min(2.0, -2.0) = -2.0 - res = interp.step(inst) - self.assertEqual(res, NEG_TWO_F64) - self.assertEqual(interp.read_reg_u64(RegKind.VGPR, 0), NEG_TWO_F64) - - def test_overlapping_unaligned_register_pairs(self) -> None: - # Test read-before-write safety across overlapping register allocations: - # dst = v[1:2], src0 = v[0:1], src1 = v[2:3] - interp = ScalarVALUInterpreter() - # Set up registers v0, v1, v2, v3 - # v[0:1] = 1.0 (lo=0, hi=0x3ff00000) -> v0=0, v1=0x3ff00000 - interp.write_reg_u64(RegKind.VGPR, 0, POS_ONE_F64) - # v[2:3] = 2.0 (lo=0, hi=0x40000000) -> v2=0, v3=0x40000000 - interp.write_reg_u64(RegKind.VGPR, 2, POS_TWO_F64) - - inst = Instruction( - opcode=Opcode.V_MAX_F64, - dst=Register(RegKind.VGPR, 1, count=2), - src0=Register(RegKind.VGPR, 0, count=2), - src1=Register(RegKind.VGPR, 2, count=2), - ) - res = interp.step(inst) - self.assertEqual(res, POS_TWO_F64) - # dst v[1:2] now holds POS_TWO_F64: v1=0, v2=0x40000000 - self.assertEqual(interp.read_reg_u64(RegKind.VGPR, 1), POS_TWO_F64) - # v0 and v3 remained undisturbed - self.assertEqual(interp.read_reg_u32(RegKind.VGPR, 0), 0) - self.assertEqual(interp.read_reg_u32(RegKind.VGPR, 3), 0x40000000) - - def test_unmodified_registers_preserved(self) -> None: - interp = ScalarVALUInterpreter() - for idx in range(10, 20): - interp.write_reg_u32(RegKind.VGPR, idx, 0x11110000 + idx) - - inst = Instruction( - opcode=Opcode.V_MIN_F64, - dst=Register(RegKind.VGPR, 0, count=2), - src0=Immediate(1.0), - src1=Immediate(2.0), - ) - interp.step(inst) - - for idx in range(10, 20): - self.assertEqual(interp.read_reg_u32(RegKind.VGPR, idx), 0x11110000 + idx) - - def test_simd_aliasing_with_divergent_exec_mask(self) -> None: - simd = SIMDWavefrontInterpreter(wave_size=32) - exec_mask = 0x0000000F # First 4 lanes active - simd.set_exec_mask(exec_mask) - - # In all lanes: v[0:1] = 10.0, v[2:3] = 1.0 - for lane in range(32): - simd.write_lane_reg_u64(lane, RegKind.VGPR, 0, POS_TEN_F64) - simd.write_lane_reg_u64(lane, RegKind.VGPR, 2, POS_ONE_F64) - - # v[0:1] = min(v[0:1], v[2:3]) - inst = Instruction( - opcode=Opcode.V_MIN_F64, - dst=Register(RegKind.VGPR, 0, count=2), - src0=Register(RegKind.VGPR, 0, count=2), - src1=Register(RegKind.VGPR, 2, count=2), - ) - simd.step(inst) - - for lane in range(32): - if lane < 4: - self.assertEqual(simd.read_lane_reg_u64(lane, RegKind.VGPR, 0), POS_ONE_F64) - else: - self.assertEqual(simd.read_lane_reg_u64(lane, RegKind.VGPR, 0), POS_TEN_F64) - - -class TestValuMinMaxF64ConditionCodes(unittest.TestCase): - """Unit tests for condition codes, status flags, and carry/borrow isolation.""" - - def test_condition_codes_ordering(self) -> None: - interp = ScalarVALUInterpreter() - inst_lt = Instruction( - opcode=Opcode.V_MIN_F64, - dst=Register(RegKind.VGPR, 0, count=2), - src0=Immediate(1.0), - src1=Immediate(2.0), - ) - interp.step(inst_lt) - cc = interp.last_condition_codes - self.assertIsNotNone(cc) - assert cc is not None - self.assertTrue(cc.less) - self.assertFalse(cc.equal) - self.assertFalse(cc.greater) - self.assertFalse(cc.unordered) - self.assertFalse(cc.zero) - self.assertFalse(cc.negative) - - inst_gt = Instruction( - opcode=Opcode.V_MAX_F64, - dst=Register(RegKind.VGPR, 0, count=2), - src0=Immediate(10.0), - src1=Immediate(2.0), - ) - interp.step(inst_gt) - cc_gt = interp.last_condition_codes - self.assertIsNotNone(cc_gt) - assert cc_gt is not None - self.assertTrue(cc_gt.greater) - self.assertFalse(cc_gt.less) - self.assertFalse(cc_gt.equal) - - inst_eq = Instruction( - opcode=Opcode.V_MIN_F64, - dst=Register(RegKind.VGPR, 0, count=2), - src0=Immediate(-2.0), - src1=Immediate(-2.0), - ) - interp.step(inst_eq) - cc_eq = interp.last_condition_codes - self.assertIsNotNone(cc_eq) - assert cc_eq is not None - self.assertTrue(cc_eq.equal) - self.assertTrue(cc_eq.negative) - - def test_condition_codes_unordered_nan(self) -> None: - interp = ScalarVALUInterpreter() - inst_nan = Instruction( - opcode=Opcode.V_MIN_F64, - dst=Register(RegKind.VGPR, 0, count=2), - src0=Immediate(0x7FF8000000000000), # QNAN - src1=Immediate(1.0), - ) - interp.step(inst_nan) - cc = interp.last_condition_codes - self.assertIsNotNone(cc) - assert cc is not None - self.assertTrue(cc.unordered) - self.assertFalse(cc.equal) - self.assertFalse(cc.less) - self.assertFalse(cc.greater) - - def test_condition_codes_signed_zeros(self) -> None: - # -0.0 < +0.0 ordered key - cc = compute_condition_codes(NEG_ZERO_F64, POS_ZERO_F64, NEG_ZERO_F64) - self.assertTrue(cc.less) - self.assertFalse(cc.equal) - self.assertTrue(cc.zero) - self.assertTrue(cc.negative) - - cc_rev = compute_condition_codes(POS_ZERO_F64, NEG_ZERO_F64, POS_ZERO_F64) - self.assertTrue(cc_rev.greater) - self.assertFalse(cc_rev.equal) - self.assertTrue(cc_rev.zero) - self.assertFalse(cc_rev.negative) - - def test_status_flags_snan_invalid(self) -> None: - flags_snan = compute_fp_status_flags(SNAN_F64, POS_ONE_F64, POS_ONE_F64) - self.assertTrue(flags_snan.invalid) - self.assertFalse(flags_snan.denormal) - - flags_qnan = compute_fp_status_flags(QNAN_F64, POS_ONE_F64, POS_ONE_F64) - self.assertFalse(flags_qnan.invalid) - - def test_status_flags_denormal(self) -> None: - flags_sub = compute_fp_status_flags(SUBNORM_MIN_F64, POS_ONE_F64, SUBNORM_MIN_F64) - self.assertTrue(flags_sub.denormal) - self.assertFalse(flags_sub.invalid) - - def test_carry_borrow_vcc_isolation(self) -> None: - interp = ScalarVALUInterpreter() - # Set VCC to arbitrary non-zero carry mask - canary_vcc = 0xFFFFFFFFFFFFFFFF - interp.vcc = canary_vcc - - inst = Instruction( - opcode=Opcode.V_MIN_F64, - dst=Register(RegKind.VGPR, 0, count=2), - src0=Immediate(1.0), - src1=Immediate(2.0), - ) - interp.step(inst) - # In RDNA2 ISA, floating-point min/max NEVER writes or disturbs VCC - self.assertEqual(interp.vcc, canary_vcc) - - simd = SIMDWavefrontInterpreter(wave_size=64) - simd.vcc = canary_vcc - simd.step(inst) - self.assertEqual(simd.vcc, canary_vcc) - - -class TestValuMinMaxF64IEEE754Boundaries(unittest.TestCase): - """Exhaustive unit tests for IEEE 754 boundary extremes, subnormals, and NaN handling.""" - - def test_signed_zero_matrix(self) -> None: - # min signed zero permutations - self.assertEqual(ref_min_f64(POS_ZERO_F64, POS_ZERO_F64), POS_ZERO_F64) - self.assertEqual(ref_min_f64(POS_ZERO_F64, NEG_ZERO_F64), NEG_ZERO_F64) - self.assertEqual(ref_min_f64(NEG_ZERO_F64, POS_ZERO_F64), NEG_ZERO_F64) - self.assertEqual(ref_min_f64(NEG_ZERO_F64, NEG_ZERO_F64), NEG_ZERO_F64) - - # max signed zero permutations - self.assertEqual(ref_max_f64(POS_ZERO_F64, POS_ZERO_F64), POS_ZERO_F64) - self.assertEqual(ref_max_f64(POS_ZERO_F64, NEG_ZERO_F64), POS_ZERO_F64) - self.assertEqual(ref_max_f64(NEG_ZERO_F64, POS_ZERO_F64), POS_ZERO_F64) - self.assertEqual(ref_max_f64(NEG_ZERO_F64, NEG_ZERO_F64), NEG_ZERO_F64) - - def test_subnormals_vs_zeros(self) -> None: - # Positive subnormal is strictly greater than both +0.0 and -0.0 - self.assertEqual(ref_min_f64(SUBNORM_MIN_F64, POS_ZERO_F64), POS_ZERO_F64) - self.assertEqual(ref_min_f64(SUBNORM_MIN_F64, NEG_ZERO_F64), NEG_ZERO_F64) - self.assertEqual(ref_max_f64(SUBNORM_MIN_F64, POS_ZERO_F64), SUBNORM_MIN_F64) - self.assertEqual(ref_max_f64(SUBNORM_MIN_F64, NEG_ZERO_F64), SUBNORM_MIN_F64) - - # Negative subnormal is strictly less than both +0.0 and -0.0 - self.assertEqual(ref_min_f64(NEG_SUBNORM_MIN_F64, POS_ZERO_F64), NEG_SUBNORM_MIN_F64) - self.assertEqual(ref_min_f64(NEG_SUBNORM_MIN_F64, NEG_ZERO_F64), NEG_SUBNORM_MIN_F64) - self.assertEqual(ref_max_f64(NEG_SUBNORM_MIN_F64, POS_ZERO_F64), POS_ZERO_F64) - self.assertEqual(ref_max_f64(NEG_SUBNORM_MIN_F64, NEG_ZERO_F64), NEG_ZERO_F64) - - def test_subnormals_vs_normal_min(self) -> None: - # SUBNORM_MAX is 2^-1022 - 2^-1074, which is strictly less than DBL_MIN (2^-1022) - self.assertEqual(ref_min_f64(SUBNORM_MAX_F64, DBL_MIN), SUBNORM_MAX_F64) - self.assertEqual(ref_max_f64(SUBNORM_MAX_F64, DBL_MIN), DBL_MIN) - self.assertEqual(ref_min_f64(NEG_SUBNORM_MAX_F64, NEG_DBL_MIN), NEG_DBL_MIN) - self.assertEqual(ref_max_f64(NEG_SUBNORM_MAX_F64, NEG_DBL_MIN), NEG_SUBNORM_MAX_F64) - - def test_infinities_vs_normal_max(self) -> None: - self.assertEqual(ref_min_f64(DBL_MAX, POS_INF_F64), DBL_MAX) - self.assertEqual(ref_max_f64(DBL_MAX, POS_INF_F64), POS_INF_F64) - self.assertEqual(ref_min_f64(NEG_DBL_MAX, NEG_INF_F64), NEG_INF_F64) - self.assertEqual(ref_max_f64(NEG_DBL_MAX, NEG_INF_F64), NEG_DBL_MAX) - self.assertEqual(ref_min_f64(NEG_INF_F64, POS_INF_F64), NEG_INF_F64) - self.assertEqual(ref_max_f64(NEG_INF_F64, POS_INF_F64), POS_INF_F64) - - def test_nan_suppression_comprehensive(self) -> None: - test_values = [ - POS_ZERO_F64, NEG_ZERO_F64, POS_ONE_F64, NEG_ONE_F64, - DBL_MIN, NEG_DBL_MIN, DBL_MAX, NEG_DBL_MAX, - SUBNORM_MIN_F64, SUBNORM_MAX_F64, NEG_SUBNORM_MIN_F64, NEG_SUBNORM_MAX_F64, - POS_INF_F64, NEG_INF_F64, - ] - nans = [QNAN_F64, NEG_QNAN_F64, QNAN_PAYLOAD_A, QNAN_PAYLOAD_B, SNAN_F64] - - for val in test_values: - for nan in nans: - with self.subTest(val=f"{val:#018x}", nan=f"{nan:#018x}"): - # Non-NaN operand is always returned intact - self.assertEqual(ref_min_f64(nan, val), val) - self.assertEqual(ref_min_f64(val, nan), val) - self.assertEqual(ref_max_f64(nan, val), val) - self.assertEqual(ref_max_f64(val, nan), val) - - def test_dual_nan_propagation(self) -> None: - nans = [QNAN_F64, NEG_QNAN_F64, QNAN_PAYLOAD_A, QNAN_PAYLOAD_B, SNAN_F64] - for nan0 in nans: - for nan1 in nans: - res_min = ref_min_f64(nan0, nan1) - res_max = ref_max_f64(nan0, nan1) - self.assertTrue(is_nan_f64(res_min)) - self.assertTrue(is_nan_f64(res_max)) - # Canonical quiet NaN bit is set - self.assertTrue(is_qnan_f64(res_min)) - self.assertTrue(is_qnan_f64(res_max)) - - def test_modifiers_on_boundary_extremes(self) -> None: - # abs on infinities and zeros - self.assertEqual(apply_f64_modifiers(NEG_INF_F64, abs_val=True), POS_INF_F64) - self.assertEqual(apply_f64_modifiers(NEG_ZERO_F64, abs_val=True), POS_ZERO_F64) - # neg on infinities and zeros - self.assertEqual(apply_f64_modifiers(POS_INF_F64, neg=True), NEG_INF_F64) - self.assertEqual(apply_f64_modifiers(POS_ZERO_F64, neg=True), NEG_ZERO_F64) - self.assertEqual(apply_f64_modifiers(NEG_ZERO_F64, neg=True), POS_ZERO_F64) - - # clamp on infinities and subnormals - self.assertEqual(apply_f64_clamp(POS_INF_F64), POS_ONE_F64) - self.assertEqual(apply_f64_clamp(NEG_INF_F64), POS_ZERO_F64) - self.assertEqual(apply_f64_clamp(SUBNORM_MIN_F64), SUBNORM_MIN_F64) - self.assertEqual(apply_f64_clamp(NEG_SUBNORM_MIN_F64), POS_ZERO_F64) - self.assertEqual(apply_f64_clamp(QNAN_F64), QNAN_F64) - - -class TestValuMinMaxF64NegativeControls(unittest.TestCase): - """Unit tests for negative controls, syntax rejection, and invalid AST inputs.""" - - def test_invalid_register_indices(self) -> None: - with self.assertRaises(ValueError): - Register(RegKind.VGPR, -1, count=2) - with self.assertRaises(ValueError): - Register(RegKind.VGPR, 256, count=2) - with self.assertRaises(ValueError): - # Index 255 with count 2 spills past 255 - Register(RegKind.VGPR, 255, count=2) - - def test_invalid_register_counts(self) -> None: - with self.assertRaises(ValueError): - Register(RegKind.VGPR, 0, count=0) - with self.assertRaises(ValueError): - Register(RegKind.VGPR, 0, count=3) - - def test_invalid_destination_kind(self) -> None: - # VALU destination cannot be SGPR - with self.assertRaises(ValueError): - Instruction( - opcode=Opcode.V_MIN_F64, - dst=Register(RegKind.SGPR, 0, count=2), - src0=Register(RegKind.VGPR, 2, count=2), - src1=Register(RegKind.VGPR, 4, count=2), - ) - - def test_invalid_destination_count(self) -> None: - # 64-bit float operation destination cannot be 32-bit single register - with self.assertRaises(ValueError): - Instruction( - opcode=Opcode.V_MIN_F64, - dst=Register(RegKind.VGPR, 0, count=1), - src0=Register(RegKind.VGPR, 2, count=2), - src1=Register(RegKind.VGPR, 4, count=2), - ) - - def test_invalid_vop2_modifiers(self) -> None: - # VOP2 encoding cannot have clamp - with self.assertRaises(ValueError): - Instruction( - opcode=Opcode.V_MIN_F64, - dst=Register(RegKind.VGPR, 0, count=2), - src0=Register(RegKind.VGPR, 2, count=2), - src1=Register(RegKind.VGPR, 4, count=2), - inst_mods=InstructionModifiers(clamp=True), - encoding=Encoding.VOP2, - ) - - def test_scalar_interpreter_out_of_bounds_access(self) -> None: - interp = ScalarVALUInterpreter() - with self.assertRaises(IndexError): - interp.read_reg_u32(RegKind.VGPR, 256) - with self.assertRaises(IndexError): - interp.write_reg_u32(RegKind.SGPR, 106, 0) - - def test_simd_interpreter_invalid_wave_size(self) -> None: - with self.assertRaises(ValueError): - SIMDWavefrontInterpreter(wave_size=16) - with self.assertRaises(ValueError): - SIMDWavefrontInterpreter(wave_size=128) - - -class TestValuMinMaxF64MutationDetection(unittest.TestCase): - """Mutation tests: verifies that intentional sabotages/mutations of the oracle are caught.""" - - def test_mutation_inverted_comparison(self) -> None: - # Sabotage: swap min and max - def mutated_min(s0: int, s1: int) -> int: - return ref_max_f64(s0, s1) - - # Standard check should detect failure - with self.assertRaises(AssertionError): - self.assertEqual(mutated_min(POS_ONE_F64, POS_TWO_F64), POS_ONE_F64) - - def test_mutation_signed_zero_blindness(self) -> None: - # Sabotage: ignoring signed zero ordering (-0.0 vs +0.0) - def mutated_min_zero_blind(s0: int, s1: int) -> int: - f0 = bits_to_f64(s0) - f1 = bits_to_f64(s1) - # Python standard min(0.0, -0.0) returns the first argument: min(+0.0, -0.0) == 0.0 - return s0 if f0 <= f1 else s1 - - # Must catch that min(+0.0, -0.0) should be -0.0, not +0.0 - with self.assertRaises(AssertionError): - self.assertEqual(mutated_min_zero_blind(POS_ZERO_F64, NEG_ZERO_F64), NEG_ZERO_F64) - - def test_mutation_nan_propagation_bug(self) -> None: - # Sabotage: propagate NaN instead of suppressing it - def mutated_min_nan_propagate(s0: int, s1: int) -> int: - if is_nan_f64(s0): - return s0 - if is_nan_f64(s1): - return s1 - return ref_min_f64(s0, s1) - - with self.assertRaises(AssertionError): - self.assertEqual(mutated_min_nan_propagate(QNAN_F64, POS_ONE_F64), POS_ONE_F64) - - def test_mutation_clamp_negative_zero_bug(self) -> None: - # Sabotage: clamping -0.0 retains -0.0 instead of flushing to +0.0 - def mutated_clamp_negative_zero(bits: int) -> int: - val = bits_to_f64(bits) - if val < 0.0: - return POS_ZERO_F64 - if val > 1.0: - return POS_ONE_F64 - return bits # returns -0.0 unchanged - - with self.assertRaises(AssertionError): - self.assertEqual(mutated_clamp_negative_zero(NEG_ZERO_F64), POS_ZERO_F64) - - def test_mutation_exec_mask_leak(self) -> None: - # Sabotage: inactive lanes write to destination VGPR - simd = SIMDWavefrontInterpreter(wave_size=32) - simd.set_exec_mask(0) # all inactive - canary = 0x1234567890ABCDEF - simd.write_lane_reg_u64(0, RegKind.VGPR, 0, canary) - - # Proper step preserves canary - inst = Instruction( - opcode=Opcode.V_MIN_F64, - dst=Register(RegKind.VGPR, 0, count=2), - src0=Immediate(1.0), - src1=Immediate(2.0), - ) - simd.step(inst) - self.assertEqual(simd.read_lane_reg_u64(0, RegKind.VGPR, 0), canary) - - # Mutated write unconditionally overwrites - simd.write_lane_reg_u64(0, RegKind.VGPR, 0, POS_ONE_F64) - with self.assertRaises(AssertionError): - self.assertEqual(simd.read_lane_reg_u64(0, RegKind.VGPR, 0), canary) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_valu_minmax_i32_u32.py b/tests/semantic/test_valu_minmax_i32_u32.py deleted file mode 100644 index 0fb47ab4d..000000000 --- a/tests/semantic/test_valu_minmax_i32_u32.py +++ /dev/null @@ -1,539 +0,0 @@ -"""Semantic interpreter unit tests for RDNA2 32-bit integer VALU min/max instructions. - -Covers all four ops end-to-end through tools/rdna2spirv.py and tests/semantic/spirv_mini_interp.py: - v_min_i32 D.i32 = min(S0.i32, S1.i32) (signed 32-bit two's complement) - v_max_i32 D.i32 = max(S0.i32, S1.i32) (signed 32-bit two's complement) - v_min_u32 D.u32 = min(S0.u32, S1.u32) (unsigned 32-bit) - v_max_u32 D.u32 = max(S0.u32, S1.u32) (unsigned 32-bit) - -Tests signed vs unsigned ordering on high-bit values (0x80000000 = INT32_MIN, 0x7FFFFFFF = INT32_MAX, -0xFFFFFFFF = -1 / UINT32_MAX, 0, 1), full boundary pair matrices, equal/negative/positive pairs, -inline constants, 32-bit literal constants, SGPR operands, VOP2 (_e32 / bare), VOP3 (_e64), and SDWA -(_sdwa) encodings, register aliasing, inactive EXEC lane preservation, chained min/max clamping, -and sabotaged-SPIR-V negative controls. -""" -import gc -import itertools -import os -import re -import struct -import sys -import tempfile -import unittest -import warnings - -HERE = os.path.dirname(os.path.abspath(__file__)) -ROOT = os.path.dirname(os.path.dirname(HERE)) -TOOLS_DIR = os.environ.get("LEONIDA_TOOLS_DIR") or os.path.join(ROOT, "tools") - -sys.dont_write_bytecode = True -if TOOLS_DIR not in sys.path: - sys.path.insert(0, TOOLS_DIR) -if HERE not in sys.path: - sys.path.insert(0, HERE) - -import rdna2spirv # noqa: E402 -import spirv_mini_interp as si # noqa: E402 - -MASK32 = 0xFFFFFFFF -STUB_DXBC = b"DXBC" + bytes(24) + struct.pack(" int: - return x & MASK32 - - -def s32(x: int) -> int: - v = x & MASK32 - return v - (1 << 32) if (v & 0x80000000) else v - - -def ref_op(op: str, x: int, y: int) -> int: - """Plain-Python RDNA2 ISA reference; operands and result are raw 32-bit words.""" - ux, uy = u32(x), u32(y) - if op == "v_min_i32": - return min(s32(ux), s32(uy)) & MASK32 - if op == "v_max_i32": - return max(s32(ux), s32(uy)) & MASK32 - if op == "v_min_u32": - return min(ux, uy) - if op == "v_max_u32": - return max(ux, uy) - raise ValueError(f"unknown op {op!r}") - - -def ref_clamp(signed: bool, x: int, lo: int, hi: int) -> int: - """Plain-Python clamp(x, lo, hi) = min(max(x, lo), hi) as raw 32-bit word.""" - if signed: - return min(max(s32(x), s32(lo)), s32(hi)) & MASK32 - return min(max(u32(x), u32(lo)), u32(hi)) - - -_TMP_DIR = None -_SRC_PATH = None - - -def setUpModule(): - global _TMP_DIR, _SRC_PATH - _TMP_DIR = tempfile.TemporaryDirectory() - disasm_dir = os.path.join(_TMP_DIR.name, "disasm") - os.mkdir(disasm_dir) - _SRC_PATH = os.path.join(disasm_dir, "ps_valu_minmax_i32_u32.s") - with open(os.path.join(_TMP_DIR.name, "ps_valu_minmax_i32_u32.dxbc"), "wb") as f: - f.write(STUB_DXBC) - - -def tearDownModule(): - global _TMP_DIR, _SRC_PATH - if _TMP_DIR is not None: - gc.collect() - _TMP_DIR.cleanup() - _TMP_DIR = None - _SRC_PATH = None - - -def translate_lines(lines) -> str: - if _TMP_DIR is None: - setUpModule() - asm = "; test_valu_minmax_i32_u32\n" + "".join(f"\t{ln}\n" for ln in lines) + "\ts_endpgm\n" - with open(_SRC_PATH, "w", encoding="utf-8", newline="\n") as f: - f.write(asm) - with warnings.catch_warnings(): - warnings.simplefilter("ignore", ResourceWarning) - return rdna2spirv.translate(_SRC_PATH) - - -def run_mrt0(lines, regs=("v0", "v0", "v0", "v0")) -> list[int]: - spv = translate_lines(list(lines) + [f"exp mrt0 {', '.join(regs)} done vm"]) - return list(si.run_fragment(spv)["%out_mrt0"]) - - -def run_pair(mnemonic: str, x: int, y: int) -> int: - return run_mrt0([ - f"v_mov_b32 v1, {u32(x):#x}", - f"v_mov_b32 v2, {u32(y):#x}", - f"{mnemonic} v0, v1, v2", - ])[0] - - -class ReferenceOracleTests(unittest.TestCase): - """Cross-check the plain-Python reference oracle against hand-worked values.""" - - def test_hand_worked_values(self): - cases = [ - # High-bit signed vs unsigned disagreements - ("v_min_i32", INT32_MIN, INT32_MAX, INT32_MIN), - ("v_max_i32", INT32_MIN, INT32_MAX, INT32_MAX), - ("v_min_u32", INT32_MIN, INT32_MAX, INT32_MAX), - ("v_max_u32", INT32_MIN, INT32_MAX, INT32_MIN), - ("v_min_i32", UINT32_MAX, 0, UINT32_MAX), # -1 < 0 - ("v_max_i32", UINT32_MAX, 0, 0), # max(-1, 0) = 0 - ("v_min_u32", UINT32_MAX, 0, 0), # min(2^32-1, 0) = 0 - ("v_max_u32", UINT32_MAX, 0, UINT32_MAX), # max(2^32-1, 0) = 2^32-1 - ("v_min_i32", UINT32_MAX, 1, UINT32_MAX), # -1 < 1 - ("v_max_i32", UINT32_MAX, 1, 1), - ("v_min_u32", UINT32_MAX, 1, 1), - ("v_max_u32", UINT32_MAX, 1, UINT32_MAX), - # Both negative (high bit set on both): signed and unsigned orders coincide - ("v_min_i32", INT32_MIN, UINT32_MAX, INT32_MIN), - ("v_max_i32", INT32_MIN, UINT32_MAX, UINT32_MAX), - ("v_min_u32", INT32_MIN, UINT32_MAX, INT32_MIN), - ("v_max_u32", INT32_MIN, UINT32_MAX, UINT32_MAX), - # Equal operands - ("v_min_i32", INT32_MIN, INT32_MIN, INT32_MIN), - ("v_max_u32", UINT32_MAX, UINT32_MAX, UINT32_MAX), - ] - for op, x, y, want in cases: - with self.subTest(op=op, x=hex(x), y=hex(y)): - self.assertEqual(ref_op(op, x, y), want) - - -class ValuMinMaxCoreTests(unittest.TestCase): - """Core semantic value tests across signed/unsigned disagreements, boundaries, and categories.""" - - def test_signed_vs_unsigned_high_bit_disagreements(self): - # Every pair has one high-bit value (negative as i32, >= 2^31 as u32) and one non-negative value, - # so signed and unsigned min/max must strictly disagree on both min and max. - pairs = [ - (INT32_MIN, INT32_MAX), - (INT32_MAX, INT32_MIN), - (UINT32_MAX, 0), - (0, UINT32_MAX), - (UINT32_MAX, 1), - (1, UINT32_MAX), - (INT32_MIN, 0), - (0, INT32_MIN), - (INT32_MIN, 1), - (0xFFFFFFF0, 0x00000040), - (0x80000001, 0x7FFFFFFE), - ] - for x, y in pairs: - with self.subTest(x=hex(x), y=hex(y)): - min_i, max_i, min_u, max_u = run_mrt0([ - f"v_mov_b32 v1, {x:#x}", - f"v_mov_b32 v2, {y:#x}", - "v_min_i32 v10, v1, v2", - "v_max_i32 v11, v1, v2", - "v_min_u32 v12, v1, v2", - "v_max_u32 v13, v1, v2", - ], ("v10", "v11", "v12", "v13")) - self.assertEqual(min_i, ref_op("v_min_i32", x, y)) - self.assertEqual(max_i, ref_op("v_max_i32", x, y)) - self.assertEqual(min_u, ref_op("v_min_u32", x, y)) - self.assertEqual(max_u, ref_op("v_max_u32", x, y)) - self.assertNotEqual(min_i, min_u) - self.assertNotEqual(max_i, max_u) - - def test_boundary_matrix_all_ops(self): - # All 81 ordered pairs of BOUNDARY_VALUES x 4 ops, batched 4 per shader in mrt0 xyzw. - pairs = list(itertools.product(BOUNDARY_VALUES, repeat=2)) - for op in OPS: - for start in range(0, len(pairs), 4): - chunk = pairs[start:start + 4] - lines = [] - expected = [] - for slot, (x, y) in enumerate(chunk): - dst = f"v{10 + slot}" - lines += [ - f"v_mov_b32 v1, {x:#x}", - f"v_mov_b32 v2, {y:#x}", - f"{op} {dst}, v1, v2", - ] - expected.append(ref_op(op, x, y)) - while len(expected) < 4: - lines.append(f"v_mov_b32 v{10 + len(expected)}, 0") - expected.append(0) - with self.subTest(op=op, batch=start // 4): - self.assertEqual(run_mrt0(lines, ("v10", "v11", "v12", "v13")), expected) - - def test_equal_operands(self): - values = (0, 1, 42, INT32_MAX, INT32_MIN, 0xDEADBEEF, UINT32_MAX) - for v in values: - with self.subTest(v=hex(v)): - words = run_mrt0([ - f"v_mov_b32 v1, {v:#x}", - f"v_mov_b32 v2, {v:#x}", - "v_min_i32 v10, v1, v2", - "v_max_i32 v11, v1, v2", - "v_min_u32 v12, v1, v2", - "v_max_u32 v13, v1, v2", - ], ("v10", "v11", "v12", "v13")) - self.assertEqual(words, [v, v, v, v]) - - def test_negative_vs_negative_and_positive_vs_positive(self): - # When both operands share sign bit (both negative or both non-negative), signed and unsigned agree. - same_sign_pairs = [ - # Negative vs negative - (INT32_MIN, UINT32_MAX), # -2147483648 vs -1 - (0xFFFFFFF0, 0xFFFFFFFC), # -16 vs -4 - (0x80000001, 0x80000000), # -2147483647 vs -2147483648 - (0xC0000000, 0xBFFFFFFF), # -1073741824 vs -1073741825 - # Positive vs positive - (0, 1), - (1, 64), - (0x12345678, 0x76543210), - (0x7FFFFFFE, INT32_MAX), - ] - for x, y in same_sign_pairs: - for a, b in ((x, y), (y, x)): - with self.subTest(a=hex(a), b=hex(b)): - min_i, max_i, min_u, max_u = run_mrt0([ - f"v_mov_b32 v1, {a:#x}", - f"v_mov_b32 v2, {b:#x}", - "v_min_i32 v10, v1, v2", - "v_max_i32 v11, v1, v2", - "v_min_u32 v12, v1, v2", - "v_max_u32 v13, v1, v2", - ], ("v10", "v11", "v12", "v13")) - self.assertEqual(min_i, ref_op("v_min_i32", a, b)) - self.assertEqual(max_i, ref_op("v_max_i32", a, b)) - self.assertEqual(min_u, ref_op("v_min_u32", a, b)) - self.assertEqual(max_u, ref_op("v_max_u32", a, b)) - self.assertEqual(min_i, min_u) - self.assertEqual(max_i, max_u) - - -class ValuMinMaxOperandsAndEncodingsTests(unittest.TestCase): - """Inline constants, 32-bit literals, SGPR sources, VOP2/VOP3/SDWA forms, aliasing, and EXEC masking.""" - - def test_inline_constants_src0_and_e64_src1(self): - # Inline constants (0, -1, 1, 64, -16) as src0 in VOP2, and as src1 in VOP3 (_e64). - v_val = 0x00000005 - v_neg = 0xFFFFFFFC # -4 - cases = [ - # (insn, x, y, op) - ("v_min_i32_e32 v0, 0, v1", 0, v_neg, "v_min_i32"), - ("v_max_i32_e32 v0, 0, v1", 0, v_neg, "v_max_i32"), - ("v_min_u32_e32 v0, 0, v1", 0, v_neg, "v_min_u32"), - ("v_max_u32_e32 v0, 0, v1", 0, v_neg, "v_max_u32"), - ("v_min_i32_e32 v0, -1, v2", UINT32_MAX, v_val, "v_min_i32"), - ("v_max_i32_e32 v0, -1, v2", UINT32_MAX, v_val, "v_max_i32"), - ("v_min_u32_e32 v0, -1, v2", UINT32_MAX, v_val, "v_min_u32"), - ("v_max_u32_e32 v0, -1, v2", UINT32_MAX, v_val, "v_max_u32"), - ("v_min_i32_e32 v0, 1, v1", 1, v_neg, "v_min_i32"), - ("v_max_i32_e32 v0, 1, v2", 1, v_val, "v_max_i32"), - ("v_min_i32_e32 v0, 64, v2", 64, v_val, "v_min_i32"), - ("v_max_u32_e32 v0, 64, v2", 64, v_val, "v_max_u32"), - # VOP3 (_e64) allows inline constants in src1 (or both src0 and src1). - ("v_min_i32_e64 v0, v2, -1", v_val, UINT32_MAX, "v_min_i32"), - ("v_max_i32_e64 v0, v1, 0", v_neg, 0, "v_max_i32"), - ("v_min_u32_e64 v0, v1, 64", v_neg, 64, "v_min_u32"), - ("v_max_u32_e64 v0, v2, -1", v_val, UINT32_MAX, "v_max_u32"), - ("v_min_i32_e64 v0, -16, 64", 0xFFFFFFF0, 64, "v_min_i32"), - ("v_min_u32_e64 v0, -16, 64", 0xFFFFFFF0, 64, "v_min_u32"), - ("v_max_i32_e64 v0, -16, 64", 0xFFFFFFF0, 64, "v_max_i32"), - ("v_max_u32_e64 v0, -16, 64", 0xFFFFFFF0, 64, "v_max_u32"), - ] - for insn, x, y, op in cases: - with self.subTest(insn=insn): - got = run_mrt0([ - f"v_mov_b32 v1, {v_neg:#x}", - f"v_mov_b32 v2, {v_val:#x}", - insn, - ])[0] - self.assertEqual(got, ref_op(op, x, y)) - - def test_literal_32bit_constants_src0(self): - # 32-bit literal constants (outside inline constant range) as src0 in VOP2/bare/e32. - v_val = 0x00001000 - literals = (INT32_MIN, INT32_MAX, 0xFFFFFF00, 0x12345678, 0xDEADBEEF) - for lit in literals: - with self.subTest(lit=hex(lit)): - words = run_mrt0([ - f"v_mov_b32 v2, {v_val:#x}", - f"v_min_i32_e32 v10, {lit:#x}, v2", - f"v_max_i32_e32 v11, {lit:#x}, v2", - f"v_min_u32 v12, {lit:#x}, v2", - f"v_max_u32 v13, {lit:#x}, v2", - ], ("v10", "v11", "v12", "v13")) - self.assertEqual(words, [ - ref_op("v_min_i32", lit, v_val), - ref_op("v_max_i32", lit, v_val), - ref_op("v_min_u32", lit, v_val), - ref_op("v_max_u32", lit, v_val), - ]) - - def test_sgpr_operands_vop2_and_e64(self): - # SGPR src0 in VOP2 (_e32 / bare) and SGPR src0/src1 in VOP3 (_e64). - s_val = INT32_MIN - v_val = INT32_MAX - s_other = UINT32_MAX - for suffix in ("", "_e32", "_e64"): - with self.subTest(form=f"sgpr_src0{suffix}"): - words = run_mrt0([ - f"s_mov_b32 s4, {s_val:#x}", - f"v_mov_b32 v2, {v_val:#x}", - f"v_min_i32{suffix} v10, s4, v2", - f"v_max_i32{suffix} v11, s4, v2", - f"v_min_u32{suffix} v12, s4, v2", - f"v_max_u32{suffix} v13, s4, v2", - ], ("v10", "v11", "v12", "v13")) - self.assertEqual(words, [ - ref_op("v_min_i32", s_val, v_val), - ref_op("v_max_i32", s_val, v_val), - ref_op("v_min_u32", s_val, v_val), - ref_op("v_max_u32", s_val, v_val), - ]) - - # VOP3 (_e64) also permits SGPR in src1 or in both src0 and src1 (same SGPR or distinct SGPRs). - words_e64 = run_mrt0([ - f"s_mov_b32 s4, {s_val:#x}", - f"s_mov_b32 s5, {s_other:#x}", - f"v_mov_b32 v2, {v_val:#x}", - "v_min_i32_e64 v10, v2, s4", - "v_max_u32_e64 v11, v2, s4", - "v_min_i32_e64 v12, s4, s5", - "v_max_u32_e64 v13, s4, s5", - ], ("v10", "v11", "v12", "v13")) - self.assertEqual(words_e64, [ - ref_op("v_min_i32", v_val, s_val), - ref_op("v_max_u32", v_val, s_val), - ref_op("v_min_i32", s_val, s_other), - ref_op("v_max_u32", s_val, s_other), - ]) - - def test_vop2_e32_and_vop3_e64_equivalence(self): - pairs = [ - (INT32_MIN, INT32_MAX), - (UINT32_MAX, 0), - (0xFFFFFF00, 0x00000100), - (0x80000001, 0x80000000), - ] - for op in OPS: - for x, y in pairs: - want = ref_op(op, x, y) - with self.subTest(op=op, x=hex(x), y=hex(y)): - bare = run_pair(op, x, y) - e32 = run_pair(f"{op}_e32", x, y) - e64 = run_pair(f"{op}_e64", x, y) - self.assertEqual(bare, want) - self.assertEqual(e32, want) - self.assertEqual(e64, want) - - def test_sdwa_source_and_destination_modifiers(self): - # v1 = 0x8001007F -> BYTE_0 = 0x7F (+127), BYTE_2 = 0x01, BYTE_3 = 0x80 (-128 sext / 128 uext), - # WORD_0 = 0x007F, WORD_1 = 0x8001 (-32767 sext / 32769 uext). - # v2 = 0x0002FFFE -> BYTE_0 = 0xFE (-2 sext / 254 uext), WORD_0 = 0xFFFE (-2 sext / 65534 uext). - v1, v2 = 0x8001007F, 0x0002FFFE - words = run_mrt0([ - f"v_mov_b32 v1, {v1:#x}", - f"v_mov_b32 v2, {v2:#x}", - f"v_mov_b32 v12, {OLD:#x}", - # sext(BYTE_3(v1)) = -128 (0xFFFFFF80) vs sext(BYTE_0(v2)) = -2 (0xFFFFFFFE) -> min_i32 = -128 - "v_min_i32_sdwa v10, sext(v1), sext(v2) dst_sel:DWORD dst_unused:UNUSED_PAD src0_sel:BYTE_3 src1_sel:BYTE_0", - # uext(BYTE_3(v1)) = 128 vs uext(BYTE_0(v2)) = 254 -> max_u32 = 254 - "v_max_u32_sdwa v11, v1, v2 dst_sel:DWORD dst_unused:UNUSED_PAD src0_sel:BYTE_3 src1_sel:BYTE_0", - # sext(WORD_1(v1)) = -32767 (0xFFFF8001) vs uext(WORD_0(v1)) = 0x7F -> min_i32 = 0xFFFF8001; - # placed into WORD_1 with UNUSED_PRESERVE keeps OLD[15:0] = 0xBABE -> 0x8001BABE. - "v_min_i32_sdwa v12, sext(v1), v1 dst_sel:WORD_1 dst_unused:UNUSED_PRESERVE src0_sel:WORD_1 src1_sel:WORD_0", - # sext(BYTE_3(v1)) = -128 vs sext(BYTE_0(v2)) = -2 -> max_i32 = -2 (0xFFFFFFFE); - # dst_sel:BYTE_0 with UNUSED_SEXT sign-extends low byte 0xFE back to 0xFFFFFFFE. - "v_max_i32_sdwa v13, sext(v1), sext(v2) dst_sel:BYTE_0 dst_unused:UNUSED_SEXT src0_sel:BYTE_3 src1_sel:BYTE_0", - ], ("v10", "v11", "v12", "v13")) - self.assertEqual(words, [ - 0xFFFFFF80, # min_i32(-128, -2) = -128 - 0x000000FE, # max_u32(128, 254) = 254 - 0x8001BABE, # low 16 bits of 0xFFFF8001 inserted at WORD_1, preserving 0xBABE - 0xFFFFFFFE, # max_i32(-128, -2) = -2 -> BYTE_0 = 0xFE, UNUSED_SEXT -> 0xFFFFFFFE - ]) - - def test_dst_aliases_sources(self): - a, b = INT32_MIN, 0x00000007 - for op in OPS: - for order, x, y in ( - ("v0, v0, v1", a, b), - ("v0, v1, v0", b, a), - ("v0, v0, v0", a, a), - ): - with self.subTest(op=op, order=order): - got = run_mrt0([ - f"v_mov_b32 v0, {a:#x}", - f"v_mov_b32 v1, {b:#x}", - f"{op} {order}", - ])[0] - self.assertEqual(got, ref_op(op, x, y)) - - def test_inactive_exec_lane_preserves_destination(self): - for op in OPS: - for suffix in ("", "_e32", "_e64"): - insn = f"{op}{suffix}" - with self.subTest(insn=insn): - got = run_mrt0([ - f"v_mov_b32 v0, {OLD:#x}", - f"v_mov_b32 v1, {INT32_MIN:#x}", - f"v_mov_b32 v2, {INT32_MAX:#x}", - "v_cmpx_eq_u32_e32 vcc_lo, 0, 1", - f"{insn} v0, v1, v2", - "s_mov_b32 exec_lo, -1", - ])[0] - self.assertEqual(got, OLD) - - -class ValuMinMaxClampingTests(unittest.TestCase): - """Chaining v_min/v_max as signed and unsigned clamp(x, lo, hi).""" - - def test_signed_clamp_chain(self): - # Signed range [-10, +10] across below-min, at-min, interior, at-max, above-max, and extremes. - lo = (-10) & MASK32 - hi = 10 - inputs = (INT32_MIN, (-11) & MASK32, lo, (-1) & MASK32, 0, 5, hi, 11, INT32_MAX) - for x in inputs: - want = ref_clamp(True, x, lo, hi) - with self.subTest(x=hex(x)): - # Test both min(max(x, lo), hi) and max(min(x, hi), lo), with VOP2 and _e64. - got_min_max, got_max_min, got_e64, _ = run_mrt0([ - f"v_mov_b32 v1, {x:#x}", - f"v_mov_b32 v2, {lo:#x}", - f"v_mov_b32 v3, {hi:#x}", - # Chain 1: min(max(x, lo), hi) - "v_max_i32 v4, v1, v2", - "v_min_i32 v10, v4, v3", - # Chain 2: max(min(x, hi), lo) - "v_min_i32 v5, v1, v3", - "v_max_i32 v11, v5, v2", - # Chain 3: inline-constant bounds in VOP3 _e64 - "v_max_i32_e64 v6, v1, -10", - "v_min_i32_e64 v12, v6, 10", - "v_mov_b32 v13, 0", - ], ("v10", "v11", "v12", "v13")) - self.assertEqual(got_min_max, want) - self.assertEqual(got_max_min, want) - self.assertEqual(got_e64, want) - - def test_unsigned_clamp_chain_straddling_sign_bit(self): - # Unsigned range [0x7FFFFFF0, 0x80000010] straddles the i32 sign boundary: - # signed clamping would invert lo > hi, so this proves unsigned ordering end-to-end. - lo = 0x7FFFFFF0 - hi = 0x80000010 - inputs = (0, 1, 0x7FFFFFEF, lo, INT32_MAX, INT32_MIN, hi, 0x80000011, UINT32_MAX) - for x in inputs: - want = ref_clamp(False, x, lo, hi) - with self.subTest(x=hex(x)): - got_min_max, got_max_min, _, _ = run_mrt0([ - f"v_mov_b32 v1, {x:#x}", - f"v_mov_b32 v2, {lo:#x}", - f"v_mov_b32 v3, {hi:#x}", - "v_max_u32 v4, v1, v2", - "v_min_u32 v10, v4, v3", - "v_min_u32_e64 v5, v1, v3", - "v_max_u32_e64 v11, v5, v2", - "v_mov_b32 v12, 0", - "v_mov_b32 v13, 0", - ], ("v10", "v11", "v12", "v13")) - self.assertEqual(got_min_max, want) - self.assertEqual(got_max_min, want) - - -class ValuMinMaxNegativeControlsTests(unittest.TestCase): - """Sabotage translated SPIR-V and confirm the tests detect signed/unsigned and min/max swaps.""" - - def test_sabotaged_spirv_is_detected(self): - controls = [ - ("v_min_i32 swapped to UMin", "v_min_i32 v0, v1, v2", INT32_MIN, INT32_MAX, - r"glsl SMin", "glsl UMin", ref_op("v_min_i32", INT32_MIN, INT32_MAX)), - ("v_max_i32 swapped to UMax", "v_max_i32 v0, v1, v2", INT32_MIN, INT32_MAX, - r"glsl SMax", "glsl UMax", ref_op("v_max_i32", INT32_MIN, INT32_MAX)), - ("v_min_u32 swapped to SMin", "v_min_u32 v0, v1, v2", UINT32_MAX, 0, - r"glsl UMin", "glsl SMin", ref_op("v_min_u32", UINT32_MAX, 0)), - ("v_max_u32 swapped to SMax", "v_max_u32 v0, v1, v2", UINT32_MAX, 0, - r"glsl UMax", "glsl SMax", ref_op("v_max_u32", UINT32_MAX, 0)), - ("v_min_i32 swapped to SMax", "v_min_i32 v0, v1, v2", 0xFFFFFFFE, 5, - r"glsl SMin", "glsl SMax", ref_op("v_min_i32", 0xFFFFFFFE, 5)), - ("v_max_u32 swapped to UMin", "v_max_u32 v0, v1, v2", 1, 64, - r"glsl UMax", "glsl UMin", ref_op("v_max_u32", 1, 64)), - ] - for label, insn, v1, v2, pattern, repl, want in controls: - with self.subTest(what=label): - good = translate_lines([ - f"v_mov_b32 v1, {v1:#x}", - f"v_mov_b32 v2, {v2:#x}", - insn, - "exp mrt0 v0, v0, v0, v0 done vm", - ]) - self.assertEqual(si.run_fragment(good)["%out_mrt0"][0], want) - bad, count = re.subn(pattern, repl, good) - self.assertEqual(count, 1, f"unexpected match count for {pattern}") - self.assertNotEqual(si.run_fragment(bad)["%out_mrt0"][0], want) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_valu_mul_f16.py b/tests/semantic/test_valu_mul_f16.py deleted file mode 100644 index a661a1416..000000000 --- a/tests/semantic/test_valu_mul_f16.py +++ /dev/null @@ -1,148 +0,0 @@ -"""v_mul_f16 (RDNA2 VOP2 / VOP3): D.f16 = S0.f16 * S1.f16, binary16 with round to nearest even. - -Every case is translated by tools/rdna2spirv.py and executed with tests/semantic/spirv_mini_interp.py; the expected -word is written down by hand (from the ISA) next to each case, rechecked against the plain-Python binary16 reference in -tests/semantic/f16_ref.py, and extended with seeded random operands. Covers the _e32 form (the high half of the -destination is kept), the _e64 form with op_sel, SGPR / literal / inline-constant sources, neg/abs, omod and clamp. -Standard library only: no GPU, no LLVM, no game data. -""" -import os -import random -import sys -import unittest - -HERE = os.path.dirname(os.path.abspath(__file__)) -sys.dont_write_bytecode = True -sys.path.insert(0, HERE) -import support # noqa: E402 -from f16_ref import OLD, ref_mul, same_f16, scale # noqa: E402 - -ONE, TWO, THREE, HALF, QUARTER = 0x3C00, 0x4000, 0x4200, 0x3800, 0x3400 -MAXH, INF, NINF, QNAN = 0x7BFF, 0x7C00, 0xFC00, 0x7E00 -MIN_NORMAL, MIN_SUB, MAX_SUB = 0x0400, 0x0001, 0x03FF - - -def run(line, seeds, old=OLD, hi=0x5A5A): - """Run one instruction on a one-lane pixel shader and return v0 as exported to mrt0. - - `seeds` maps a register ("v1", "s2", ...) to the word it starts with; a value that fits in 16 bits gets `hi` in its - upper half, so reading the wrong half of a source shows. v0 starts as `old`. - """ - prog = [f"v_mov_b32 v0, {old:#x}"] - for reg, w in seeds.items(): - w = w if w > 0xFFFF else (hi << 16) | w - prog.append(f"{'s' if reg[0] == 's' else 'v'}_mov_b32 {reg}, {w:#x}") - prog += [line, "exp mrt0 v0, v0, v0, v0 done vm", "s_endpgm"] - return support.mrt0_words(support.translate_lines("ps_mul_f16", prog))[0] - - -# (src0, src1, D), written by hand. -CASES = [ - (0x3E00, TWO, THREE), # 1.5 * 2 = 3 - (HALF, HALF, QUARTER), # 0.5 * 0.5 - (0xBC00, TWO, 0xC000), # -1 * 2 = -2 - (0x0000, 0xBC00, 0x8000), # +0 * -1 = -0 - (0x8000, 0xBC00, 0x0000), # -0 * -1 = +0 - (INF, 0x0000, QNAN), # inf * 0 = NaN - (INF, 0xC000, NINF), # inf * -2 = -inf - (MAXH, TWO, INF), # 131008 overflows - (MAXH, HALF, 0x77FF), # 32752, exact - (MIN_NORMAL, HALF, 0x0200), # 2^-15 is subnormal: 512 quanta of 2^-24 - (MIN_SUB, HALF, 0x0000), # half a quantum: tie to even is 0 - (MIN_SUB, 0x3A00, MIN_SUB), # 0.75 of a quantum rounds up to 1 - (0x3C01, 0x3C01, 0x3C02), # 1 + 2^-9 + 2^-20 rounds to 1 + 2^-9 - (0x5640, 0x5640, 0x70E2), # 100 * 100 = 10000 - (0x4900, 0xC100, 0xCE40), # 10 * -2.5 = -25 - (QNAN, ONE, QNAN), -] - -SPECIAL = [0x0000, 0x8000, ONE, 0xBC00, TWO, 0xC000, HALF, 0xB800, THREE, 0x3E00, MAXH, 0xFBFF, INF, NINF, QNAN, - MIN_NORMAL, MIN_SUB, 0x8001, MAX_SUB, 0x3C01, 0x3BFF, 0x1000, 0x6800, 0x6801, 0x4C00] - - -class MulF16(unittest.TestCase): - def test_hand_written_table_matches_reference(self): - for a, b, want in CASES: - self.assertTrue(same_f16(ref_mul(a, b), want), (hex(a), hex(b), hex(ref_mul(a, b)))) - - def test_e32_writes_low_half_and_keeps_high_half(self): - for a, b, want in CASES: - with self.subTest(a=hex(a), b=hex(b)): - got = run("v_mul_f16 v0, v1, v2", {"v1": a, "v2": b}) - self.assertEqual(got >> 16, OLD >> 16) - self.assertTrue(same_f16(got & 0xFFFF, want), hex(got)) - - def test_vop3_sgpr_and_literal_sources(self): - for a, b, want in CASES[:14]: - forms = [ - ("e64 vgpr", "v_mul_f16_e64 v0, v1, v2", {"v1": a, "v2": b}), - ("e64 sgpr", "v_mul_f16_e64 v0, s1, s2", {"s1": a, "s2": b}), - ("e32 sgpr src0", "v_mul_f16 v0, s1, v2", {"s1": a, "v2": b}), - ("e32 literal src0", f"v_mul_f16 v0, {a:#x}, v2", {"v2": b}), - ("e64 literal src1", f"v_mul_f16_e64 v0, v1, {b:#x}", {"v1": a}), - ] - for form, line, seeds in forms: - with self.subTest(a=hex(a), b=hex(b), form=form): - got = run(line, seeds) - self.assertEqual(got >> 16, OLD >> 16) - self.assertTrue(same_f16(got & 0xFFFF, want), hex(got)) - - def test_inline_constants(self): - # (inline constant as src0, its binary16 value, v1 low half, D), by hand - for text, c, b, want in (("2.0", TWO, 0x3E00, THREE), ("-1.0", 0xBC00, HALF, 0xB800), ("0.5", HALF, 0x4400, TWO), - ("4.0", 0x4400, 0xB800, 0xC000), ("1.0", ONE, 0x3A00, 0x3A00)): - with self.subTest(const=text): - self.assertEqual(run(f"v_mul_f16 v0, {text}, v1", {"v1": b}) & 0xFFFF, want) - self.assertEqual(ref_mul(c, b), want) - - def test_op_sel_selects_source_and_destination_halves(self): - # src0 = (lo 1.0, hi 3.0), src1 = (lo 0.5, hi -0.25); D by hand for each (src0 half, src1 half). - s0, s1 = (THREE << 16) | ONE, (0xB400 << 16) | HALF - expect_lo = {(0, 0): 0x3800, (1, 0): 0x3E00, (0, 1): 0xB400, (1, 1): 0xBA00} # 0.5, 1.5, -0.25, -0.75 - for h0 in (0, 1): - for h1 in (0, 1): - for dh in (0, 1): - want = expect_lo[(h0, h1)] - expect = ((want << 16) | (OLD & 0xFFFF)) if dh else ((OLD & 0xFFFF0000) | want) - with self.subTest(op_sel=(h0, h1, dh)): - got = run(f"v_mul_f16_e64 v0, v1, v2 op_sel:[{h0},{h1},{dh}]", {"v1": s0, "v2": s1}) - self.assertEqual(got, expect) - - def test_neg_and_abs_source_modifiers(self): - # v1 = 1.5, v2 = -2.0; (operand text, D) by hand - for ops, want in (("v1, v2", 0xC200), ("-v1, v2", 0x4200), ("v1, -v2", 0x4200), ("|v1|, |v2|", 0x4200), - ("-|v1|, v2", 0x4200), ("v1, -|v2|", 0xC200), ("|v1|, v2", 0xC200), ("v1, |v2|", 0x4200)): - with self.subTest(ops=ops): - got = run(f"v_mul_f16_e64 v0, {ops}", {"v1": 0x3E00, "v2": 0xC000}) - self.assertEqual(got & 0xFFFF, want) - - def test_output_modifiers_and_clamp(self): - # #4542, measured on gfx1036: an f16 destination ignores omod (mul:2/mul:4/div:2) under the game's MODE - # (IEEE=0, f16 denormals kept) and keeps clamp (docs/design.md, f16 output modifiers). - # unmodified result: 1.5 * 2 = 3.0; clamp limits it to [0, 1] (negatives and NaN become +0) - for suffix, want in ((" mul:2", 0x4200), (" mul:4", 0x4200), (" div:2", 0x4200), (" clamp", ONE)): - with self.subTest(mod=suffix): - got = run("v_mul_f16_e64 v0, v1, v2" + suffix, {"v1": 0x3E00, "v2": TWO}) - self.assertEqual(got & 0xFFFF, want) - for (a, b), suffix, want in (((HALF, HALF), " clamp", QUARTER), ((0xB800, HALF), " clamp", 0x0000), - ((ONE, 0x3E00), " div:2 clamp", ONE), ((0x3A00, ONE), " mul:2 clamp", 0x3A00)): - with self.subTest(a=hex(a), b=hex(b), mod=suffix): - self.assertEqual(run("v_mul_f16_e64 v0, v1, v2" + suffix, {"v1": a, "v2": b}) & 0xFFFF, want) - for suffix, f in ((" mul:2", 2.0), (" mul:4", 4.0), (" div:2", 0.5)): - got = run("v_mul_f16_e64 v0, v1, v2" + suffix, {"v1": 0x4900, "v2": 0xC100}) # 10 and -2.5 - self.assertEqual(got & 0xFFFF, ref_mul(0x4900, 0xC100)) - - def test_random_operands(self): - rng = random.Random(0x3C16) - pool = SPECIAL + [rng.getrandbits(16) for _ in range(40)] - for _ in range(120): - a = rng.choice(pool) if rng.random() < 0.5 else rng.getrandbits(16) - b = rng.choice(pool) if rng.random() < 0.5 else rng.getrandbits(16) - with self.subTest(a=hex(a), b=hex(b)): - got = run("v_mul_f16 v0, v1, v2", {"v1": a, "v2": b}) - self.assertEqual(got >> 16, OLD >> 16) - self.assertTrue(same_f16(got & 0xFFFF, ref_mul(a, b)), (hex(got), hex(ref_mul(a, b)))) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_valu_mul_f16_mode_round.py b/tests/semantic/test_valu_mul_f16_mode_round.py deleted file mode 100644 index 03886e821..000000000 --- a/tests/semantic/test_valu_mul_f16_mode_round.py +++ /dev/null @@ -1,142 +0,0 @@ -"""v_mul_f16 under MODE.FP_ROUND[3:2] toward zero (s_setreg_imm32_b32 hwreg(HW_REG_MODE, 2, 2), 3). - -Standard library only; no GPU, no LLVM, no game files. - -docs/design.md ("f16 rounding", SHADER-55/56): after a MODE.FP_ROUND toward-zero write, every f16 ALU result takes the -toward-zero form (`Gen.f16_res`). tests/test_mode_round.py checks that for v_cvt_f16_f32, v_add/sub/fma_f16 and the -packed ops, and that the f16 transcendentals ignore the mode; this file does the same for v_mul_f16, which had no test -under a MODE write. The f16 * f16 product is exact in f32 (11-bit significands), so the one rounding is the f16 one. - -Operands are picked so the two modes give different bits (hand-worked, checked by an exact Fraction oracle below): - 0x3e01 * 1.5 = 2305.5/1024 = 2 + 128.75 * 2^-9 -> RNE 0x4081, RTZ 0x4080 (and the same negated) - 65504 * 2.0 = 131008 -> RNE +-inf (0x7c00 / 0xfc00), RTZ +-65504 (0x7bff / 0xfbff) - 2^-24 * 1.5 = 1.5 * 2^-24 (f16 subnormal) -> RNE 0x0002, RTZ 0x0001 (and the same negated) - inf * 2.0 and 1.0 * 1.5 are the same in both modes. -v_mul_f16_e32 writes the low half and keeps the high half of the destination (docs/design.md "16-bit results"), -so each destination is seeded with 0xaaaa5555 and the expected word is 0xaaaa0000 | result. -""" -from fractions import Fraction -import os -import sys -import unittest - -HERE = os.path.dirname(os.path.abspath(__file__)) -sys.dont_write_bytecode = True -if HERE not in sys.path: - sys.path.insert(0, HERE) - -import support # noqa: E402 - -RTZ = "s_setreg_imm32_b32 hwreg(HW_REG_MODE, 2, 2), 3" -RNE = "s_setreg_imm32_b32 hwreg(HW_REG_MODE, 2, 2), 0" -SEED = 0xAAAA5555 - -# (a, b, RNE result, RTZ result), all f16 bits -CASES = [ - (0x3E01, 0x3E00, 0x4081, 0x4080), # 1.500977 * 1.5: 0.75 ulp above 0x4080 - (0xBE01, 0x3E00, 0xC081, 0xC080), # the same negated: toward zero is toward 0x4080's magnitude - (0x7BFF, 0x4000, 0x7C00, 0x7BFF), # 65504 * 2 overflows: inf to nearest, max finite toward zero - (0xFBFF, 0x4000, 0xFC00, 0xFBFF), - (0x0001, 0x3E00, 0x0002, 0x0001), # subnormal 1.5 * 2^-24: tie to even 2, truncated to 1 - (0x8001, 0x3E00, 0x8002, 0x8001), - (0x7C00, 0x4000, 0x7C00, 0x7C00), # a true inf stays inf toward zero - (0x3C00, 0x3E00, 0x3E00, 0x3E00), # exact product: no rounding in either mode -] - - -def f16_value(h): - """Exact value of finite f16 bits `h`, or +-inf as a float.""" - s = -1 if h & 0x8000 else 1 - e, m = (h >> 10) & 0x1F, h & 0x3FF - if e == 0x1F: - assert m == 0, "NaN is not used here" - return s * float("inf") - if e == 0: - return s * Fraction(m, 1 << 24) - return s * Fraction(1024 + m, 1024) * Fraction(2) ** (e - 25 + 10) - - -def ref_mul_f16(a, b, rtz): - """Plain-Python f16 product of bits `a` and `b`, rounded once to nearest even or toward zero.""" - x, y = f16_value(a), f16_value(b) - if isinstance(x, float) or isinstance(y, float): - p = float(x) * float(y) - return (0x8000 if p < 0 else 0) | 0x7C00 - p = x * y - sign = 0x8000 if p < 0 else 0 - p = abs(p) - if p == 0: - return sign - e = 14 # find the binade: 2^(e-15) <= p < 2^(e-14), clamped to subnormals - while e > 1 and p < Fraction(2) ** (e - 15): - e -= 1 - while p >= Fraction(2) ** (e - 14): - e += 1 - ulp = Fraction(2) ** (e - 25) # e here is the biased exponent of a normal (1 also covers e == 0) - q, r = divmod(p, ulp) - q = int(q) - if not rtz and (r * 2 > ulp or (r * 2 == ulp and q & 1)): - q += 1 - bits = q + ((e - 1) << 10) if q >= 1024 or e > 1 else q - if bits >= 0x7C00: - bits = 0x7BFF if rtz else 0x7C00 - return sign | bits - - -def run_quad(cases, prefix=()): - """Run four v_mul_f16_e32 on one fragment (v0..v3, seeded high halves); return the four mrt0 words.""" - lines = [] - for i, (a, b) in enumerate(cases): - lines += [f"v_mov_b32 v{10 + 2 * i}, {a:#x}", f"v_mov_b32 v{11 + 2 * i}, {b:#x}", f"v_mov_b32 v{i}, {SEED:#x}"] - lines += list(prefix) - lines += [f"v_mul_f16_e32 v{i}, v{10 + 2 * i}, v{11 + 2 * i}" for i in range(4)] - lines += ["exp mrt0 v0, v1, v2, v3 done vm", "s_endpgm"] - return support.mrt0_words(support.translate_lines("ps_mul_f16_mode", lines)) - - -def word(h): - return (SEED & 0xFFFF0000) | h - - -class OracleSelfTest(unittest.TestCase): - def test_hand_worked_table_matches_exact_oracle(self): - for a, b, rne, rtz in CASES: - with self.subTest(a=hex(a), b=hex(b)): - self.assertEqual(ref_mul_f16(a, b, rtz=False), rne) - self.assertEqual(ref_mul_f16(a, b, rtz=True), rtz) - - -class MulF16ModeRoundTests(unittest.TestCase): - def test_default_mode_rounds_to_nearest_even(self): - for lo in (0, 4): - quad = CASES[lo:lo + 4] - with self.subTest(cases=lo): - got = run_quad([(a, b) for a, b, _, _ in quad]) - self.assertEqual(got, [word(rne) for _, _, rne, _ in quad]) - - def test_toward_zero_after_mode_write(self): - for lo in (0, 4): - quad = CASES[lo:lo + 4] - with self.subTest(cases=lo): - got = run_quad([(a, b) for a, b, _, _ in quad], prefix=[RTZ]) - self.assertEqual(got, [word(rtz) for _, _, _, rtz in quad]) - - def test_mode_write_back_to_nearest_even(self): - # RTZ for v0/v1, then RNE again for v2/v3, on the same two inputs. - lines = [ - "v_mov_b32 v10, 0x3e01", "v_mov_b32 v11, 0x3e00", "v_mov_b32 v12, 0x7bff", "v_mov_b32 v13, 0x4000", - f"v_mov_b32 v0, {SEED:#x}", f"v_mov_b32 v1, {SEED:#x}", f"v_mov_b32 v2, {SEED:#x}", f"v_mov_b32 v3, {SEED:#x}", - RTZ, - "v_mul_f16_e32 v0, v10, v11", - "v_mul_f16_e32 v1, v12, v13", - RNE, - "v_mul_f16_e32 v2, v10, v11", - "v_mul_f16_e32 v3, v12, v13", - "exp mrt0 v0, v1, v2, v3 done vm", "s_endpgm", - ] - got = support.mrt0_words(support.translate_lines("ps_mul_f16_mode_back", lines)) - self.assertEqual(got, [word(0x4080), word(0x7BFF), word(0x4081), word(0x7C00)]) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_valu_mul_f64.py b/tests/semantic/test_valu_mul_f64.py deleted file mode 100644 index 0f8cf7eeb..000000000 --- a/tests/semantic/test_valu_mul_f64.py +++ /dev/null @@ -1,1493 +0,0 @@ -"""Semantic reference tests and mathematical oracle for AMD RDNA2 v_mul_f64. - -RDNA2 Vector Arithmetic Logic Unit (VALU) Architecture: - In AMD RDNA2 (GFX10/GFX1030) ISA, vector registers (VGPRs) are 32 bits wide. - Operations on 64-bit double-precision floating-point quantities (binary64, IEEE 754) - operate across aligned pairs of adjacent registers: v[d:d+1] from source operands - v[s0:s0+1] and v[s1:s1+1] (or scalar SGPR pairs s[k:k+1], literal 64-bit constants, - or inline constants). - - Instruction: - v_mul_f64 v[d:d+1], src0, src1 [clamp] [omod] - - IEEE-754 binary64 encoding: - - 1 sign bit (bit 63) - - 11 exponent bits with bias 1023 (bits 62:52) - - 52 mantissa / fraction bits (bits 51:0) - -Standard library only: Python 3.9+ compatible, zero game data, zero external dependencies. -""" -from __future__ import annotations - -import abc -from dataclasses import dataclass -import enum -import math -import struct -import unittest - -MASK32 = 0xFFFFFFFF -MASK64 = 0xFFFFFFFFFFFFFFFF - -# IEEE-754 binary64 bit constants -F64_POS_ZERO = 0x0000000000000000 -F64_NEG_ZERO = 0x8000000000000000 -F64_POS_INF = 0x7FF0000000000000 -F64_NEG_INF = 0xFFF0000000000000 -F64_CANONICAL_QNAN = 0x7FF8000000000000 -F64_QUIET_BIT = 0x0008000000000000 - -F64_EXP_MASK = 0x7FF0000000000000 -F64_MANT_MASK = 0x000FFFFFFFFFFFFF -F64_SIGN_MASK = 0x8000000000000000 - -F64_ONE = 0x3FF0000000000000 # 1.0 -F64_NEG_ONE = 0xBFF0000000000000 # -1.0 -F64_TWO = 0x4000000000000000 # 2.0 -F64_HALF = 0x3FE0000000000000 # 0.5 -F64_MIN_NORMAL = 0x0010000000000000 # 2^-1022 -F64_MAX_NORMAL = 0x7FEFFFFFFFFFFFFF # (2 - 2^-52) * 2^1023 -F64_MIN_SUBNORMAL = 0x0000000000000001 # 2^-1074 -F64_MAX_SUBNORMAL = 0x000FFFFFFFFFFFFF - -OLD_VGPR_SENTINEL = 0xDEADBEEF - - -def u32(val: int) -> int: - """Normalize integer to unsigned 32-bit range [0, 2^32 - 1].""" - return val & MASK32 - - -def u64(val: int) -> int: - """Normalize integer to unsigned 64-bit range [0, 2^64 - 1].""" - return val & MASK64 - - -def split_dwords(val64: int) -> tuple[int, int]: - """Split an unsigned 64-bit integer into (low_dword, high_dword).""" - val = val64 & MASK64 - return val & MASK32, (val >> 32) & MASK32 - - -def join_dwords(lo: int, hi: int) -> int: - """Join (low_dword, high_dword) into an unsigned 64-bit integer.""" - return ((hi & MASK32) << 32) | (lo & MASK32) - - -def f64_to_u64(val: float) -> int: - """Pack an IEEE-754 double precision float into an unsigned 64-bit integer.""" - try: - return struct.unpack(" float: - """Unpack an unsigned 64-bit integer into an IEEE-754 double precision float.""" - return struct.unpack(" bool: - """Return True if the 64-bit pattern represents an IEEE-754 NaN.""" - return ((bits & F64_EXP_MASK) == F64_EXP_MASK) and ((bits & F64_MANT_MASK) != 0) - - -def is_f64_snan(bits: int) -> bool: - """Return True if the 64-bit pattern represents a signaling NaN.""" - return is_f64_nan(bits) and ((bits & F64_QUIET_BIT) == 0) - - -def is_f64_qnan(bits: int) -> bool: - """Return True if the 64-bit pattern represents a quiet NaN.""" - return is_f64_nan(bits) and ((bits & F64_QUIET_BIT) != 0) - - -def is_f64_zero(bits: int) -> bool: - """Return True if the 64-bit pattern represents +0.0 or -0.0.""" - return (bits & (F64_EXP_MASK | F64_MANT_MASK)) == 0 - - -def is_f64_inf(bits: int) -> bool: - """Return True if the 64-bit pattern represents +inf or -inf.""" - return ((bits & F64_EXP_MASK) == F64_EXP_MASK) and ((bits & F64_MANT_MASK) == 0) - - -def is_f64_subnormal(bits: int) -> bool: - """Return True if the 64-bit pattern represents a subnormal/denormal float.""" - return ((bits & F64_EXP_MASK) == 0) and ((bits & F64_MANT_MASK) != 0) - - -def is_f64_normal(bits: int) -> bool: - """Return True if the 64-bit pattern represents a normalized finite float.""" - exp = (bits >> 52) & 0x7FF - return 0 < exp < 0x7FF - - -def f64_sign(bits: int) -> int: - """Return the sign bit (0 or 1).""" - return (bits >> 63) & 1 - - -def quiet_f64(bits: int) -> int: - """Force an IEEE-754 double NaN to quiet by setting the quiet bit.""" - return (bits & MASK64) | F64_QUIET_BIT - - -def apply_input_modifiers_f64(bits: int, *, neg: bool = False, abs_val: bool = False) -> int: - """Apply VOP3 input modifiers (abs, neg). - - In RDNA2 ISA: - When both abs and neg are set, abs is evaluated before neg: - i.e. neg(abs(x)) forces the sign bit to 1 (negative). - """ - res = bits & MASK64 - if abs_val: - res &= ~F64_SIGN_MASK - if neg: - res ^= F64_SIGN_MASK - return res - - -def ref_mul_f64( - src0_bits: int, - src1_bits: int, - *, - clamp: bool = False, - src0_neg: bool = False, - src0_abs: bool = False, - src1_neg: bool = False, - src1_abs: bool = False, -) -> int: - """Reference mathematical oracle for RDNA2 double-precision multiplication v_mul_f64. - - Evaluates: - D.f64 = src0 * src1 - accounting for IEEE-754 binary64 rules, input modifiers (neg, abs), and clamp [0.0, 1.0]. - """ - s0 = apply_input_modifiers_f64(src0_bits, neg=src0_neg, abs_val=src0_abs) - s1 = apply_input_modifiers_f64(src1_bits, neg=src1_neg, abs_val=src1_abs) - - sign_res = f64_sign(s0) ^ f64_sign(s1) - - # NaN propagation - if is_f64_nan(s0): - res = quiet_f64(s0) - elif is_f64_nan(s1): - res = quiet_f64(s1) - # 0 * Inf -> Canonical QNaN - elif (is_f64_zero(s0) and is_f64_inf(s1)) or (is_f64_inf(s0) and is_f64_zero(s1)): - res = F64_CANONICAL_QNAN - # Inf * anything non-zero -> Inf with expected sign - elif is_f64_inf(s0) or is_f64_inf(s1): - res = F64_NEG_INF if sign_res else F64_POS_INF - # Zero * anything finite -> Zero with expected sign - elif is_f64_zero(s0) or is_f64_zero(s1): - res = F64_NEG_ZERO if sign_res else F64_POS_ZERO - else: - # Standard finite multiplication - val0 = u64_to_f64(s0) - val1 = u64_to_f64(s1) - prod = val0 * val1 - res = f64_to_u64(prod) - if is_f64_zero(res): - res = F64_NEG_ZERO if sign_res else F64_POS_ZERO - elif is_f64_inf(res): - res = F64_NEG_INF if sign_res else F64_POS_INF - - # Clamp modifier: clamps result to [0.0, 1.0]. - # In RDNA2 VALU: if result is NaN, clamp produces +0.0. - if clamp: - if is_f64_nan(res): - res = F64_POS_ZERO - else: - val = u64_to_f64(res) - if val < 0.0 or is_f64_zero(res): - res = F64_POS_ZERO - elif val > 1.0: - res = F64_ONE - - return res & MASK64 - - -def ref_mul_f64_dwords( - s0_lo: int, - s0_hi: int, - s1_lo: int, - s1_hi: int, - *, - clamp: bool = False, - src0_neg: bool = False, - src0_abs: bool = False, - src1_neg: bool = False, - src1_abs: bool = False, -) -> tuple[int, int]: - """Decomposed dword interface for v_mul_f64.""" - s0 = join_dwords(s0_lo, s0_hi) - s1 = join_dwords(s1_lo, s1_hi) - res = ref_mul_f64( - s0, - s1, - clamp=clamp, - src0_neg=src0_neg, - src0_abs=src0_abs, - src1_neg=src1_neg, - src1_abs=src1_abs, - ) - return split_dwords(res) - - -class VALURegisterFile: - """Architectural model for RDNA2 VALU 32-bit vector register file.""" - - def __init__(self, num_vgprs: int = 256) -> None: - self.num_vgprs = num_vgprs - self.regs = [0] * num_vgprs - - def get_vgpr(self, idx: int) -> int: - if not (0 <= idx < self.num_vgprs): - raise IndexError(f"VGPR index out of range: {idx}") - return self.regs[idx] & MASK32 - - def set_vgpr(self, idx: int, val: int) -> None: - if not (0 <= idx < self.num_vgprs): - raise IndexError(f"VGPR index out of range: {idx}") - self.regs[idx] = val & MASK32 - - def get_vgpr_pair(self, idx: int) -> int: - if not (0 <= idx < self.num_vgprs - 1): - raise IndexError(f"VGPR pair index out of range: v[{idx}:{idx+1}]") - lo = self.get_vgpr(idx) - hi = self.get_vgpr(idx + 1) - return join_dwords(lo, hi) - - def set_vgpr_pair(self, idx: int, val64: int) -> None: - if not (0 <= idx < self.num_vgprs - 1): - raise IndexError(f"VGPR pair index out of range: v[{idx}:{idx+1}]") - lo, hi = split_dwords(val64) - self.set_vgpr(idx, lo) - self.set_vgpr(idx + 1, hi) - - -# ============================================================================== -# Symbolic AST Opcode Definitions and Typed Expressions for v_mul_f64 -# ============================================================================== - -class OperandKind(enum.Enum): - VGPR_PAIR = "vgpr_pair" - SGPR_PAIR = "sgpr_pair" - LITERAL_64 = "literal_64" - INLINE_IMM = "inline_imm" - - -@dataclass -class ASTOperand: - kind: OperandKind - reg_idx: int = 0 - imm_val: int = 0 - neg: bool = False - abs_val: bool = False - - def format_asm(self) -> str: - if self.kind == OperandKind.VGPR_PAIR: - s = f"v[{self.reg_idx}:{self.reg_idx + 1}]" - elif self.kind == OperandKind.SGPR_PAIR: - s = f"s[{self.reg_idx}:{self.reg_idx + 1}]" - elif self.kind == OperandKind.LITERAL_64: - s = f"0x{self.imm_val:016x}" - elif self.kind == OperandKind.INLINE_IMM: - s = f"{self.imm_val}" - else: - s = "unknown" - if self.abs_val: - s = f"|{s}|" - if self.neg: - s = f"-{s}" - return s - - -@dataclass -class ASTInstruction: - opcode: str - dst: ASTOperand - src0: ASTOperand - src1: ASTOperand - clamp: bool = False - omod: int = 0 - - def validate(self) -> None: - if self.opcode != "v_mul_f64": - raise ValueError(f"Invalid opcode for v_mul_f64 AST: {self.opcode}") - if self.dst.kind != OperandKind.VGPR_PAIR: - raise ValueError(f"Destination must be a VGPR pair, got {self.dst.kind}") - if not (0 <= self.dst.reg_idx <= 254): - raise ValueError(f"Destination VGPR pair index out of range: {self.dst.reg_idx}") - if self.dst.neg or self.dst.abs_val: - raise ValueError("Destination operand cannot have neg or abs modifiers") - for name, src in [("src0", self.src0), ("src1", self.src1)]: - if src.kind == OperandKind.VGPR_PAIR: - if not (0 <= src.reg_idx <= 254): - raise ValueError(f"{name} VGPR pair index out of range: {src.reg_idx}") - elif src.kind == OperandKind.SGPR_PAIR: - if not (0 <= src.reg_idx <= 104): - raise ValueError(f"{name} SGPR pair index out of range: {src.reg_idx}") - - def format_asm(self) -> str: - s = f"{self.opcode} {self.dst.format_asm()}, {self.src0.format_asm()}, {self.src1.format_asm()}" - if self.clamp: - s += " clamp" - return s - - -class F64Expression(abc.ABC): - @abc.abstractmethod - def evaluate(self, env: dict[str, int]) -> int: - pass - - -@dataclass -class F64Constant(F64Expression): - bits: int - - def evaluate(self, env: dict[str, int]) -> int: - return self.bits & MASK64 - - -@dataclass -class F64Variable(F64Expression): - name: str - - def evaluate(self, env: dict[str, int]) -> int: - if self.name not in env: - raise KeyError(f"Variable {self.name} not found in environment") - return env[self.name] & MASK64 - - -@dataclass -class F64UnaryOp(F64Expression): - op: str # "abs", "neg", "neg_abs" - operand: F64Expression - - def evaluate(self, env: dict[str, int]) -> int: - val = self.operand.evaluate(env) - if self.op == "abs": - return apply_input_modifiers_f64(val, abs_val=True) - elif self.op == "neg": - return apply_input_modifiers_f64(val, neg=True) - elif self.op == "neg_abs": - return apply_input_modifiers_f64(val, neg=True, abs_val=True) - raise ValueError(f"Unknown unary operator: {self.op}") - - -@dataclass -class F64Mul(F64Expression): - lhs: F64Expression - rhs: F64Expression - clamp: bool = False - - def evaluate(self, env: dict[str, int]) -> int: - v_lhs = self.lhs.evaluate(env) - v_rhs = self.rhs.evaluate(env) - return ref_mul_f64(v_lhs, v_rhs, clamp=self.clamp) - - -def instruction_to_expression(inst: ASTInstruction) -> F64Mul: - """Translate an ASTInstruction to a typed symbolic expression tree.""" - inst.validate() - - def build_operand_expr(op: ASTOperand, prefix: str) -> F64Expression: - if op.kind in (OperandKind.VGPR_PAIR, OperandKind.SGPR_PAIR): - expr: F64Expression = F64Variable(f"{prefix}_{op.reg_idx}") - elif op.kind in (OperandKind.LITERAL_64, OperandKind.INLINE_IMM): - expr = F64Constant(op.imm_val) - else: - raise ValueError(f"Unsupported operand kind: {op.kind}") - - if op.abs_val and op.neg: - expr = F64UnaryOp("neg_abs", expr) - elif op.abs_val: - expr = F64UnaryOp("abs", expr) - elif op.neg: - expr = F64UnaryOp("neg", expr) - return expr - - lhs = build_operand_expr(inst.src0, "src0") - rhs = build_operand_expr(inst.src1, "src1") - return F64Mul(lhs, rhs, clamp=inst.clamp) - - -# ============================================================================== -# Deterministic Scalar Instruction Interpreter for v_mul_f64 -# ============================================================================== - -def parse_asm_operand(tok: str) -> ASTOperand: - tok = tok.strip() - neg = False - abs_val = False - if tok.startswith("-"): - neg = True - tok = tok[1:].strip() - if tok.startswith("|") and tok.endswith("|"): - abs_val = True - tok = tok[1:-1].strip() - - if tok.startswith("v[") and tok.endswith("]"): - inner = tok[2:-1] - parts = inner.split(":") - reg_idx = int(parts[0]) - return ASTOperand(kind=OperandKind.VGPR_PAIR, reg_idx=reg_idx, neg=neg, abs_val=abs_val) - elif tok.startswith("s[") and tok.endswith("]"): - inner = tok[2:-1] - parts = inner.split(":") - reg_idx = int(parts[0]) - return ASTOperand(kind=OperandKind.SGPR_PAIR, reg_idx=reg_idx, neg=neg, abs_val=abs_val) - elif tok.startswith("0x") or tok.startswith("0X"): - imm = int(tok, 16) - return ASTOperand(kind=OperandKind.LITERAL_64, imm_val=imm, neg=neg, abs_val=abs_val) - else: - try: - if "." in tok or "e" in tok.lower(): - imm = f64_to_u64(float(tok)) - return ASTOperand(kind=OperandKind.LITERAL_64, imm_val=imm, neg=neg, abs_val=abs_val) - imm = int(tok) - return ASTOperand(kind=OperandKind.INLINE_IMM, imm_val=imm, neg=neg, abs_val=abs_val) - except ValueError: - raise ValueError(f"Unrecognized assembly operand token: {tok}") - - -def parse_asm_line(line: str) -> ASTInstruction: - clean = line.split(";")[0].split("//")[0].strip() - tokens = [t for t in clean.replace(",", " ").split() if t] - if not tokens: - raise ValueError("Empty assembly line") - opcode = tokens[0] - if opcode != "v_mul_f64": - raise ValueError(f"Expected opcode v_mul_f64, got {opcode}") - - clamp = False - raw_ops = [] - for tok in tokens[1:]: - if tok.lower() == "clamp": - clamp = True - else: - raw_ops.append(tok) - - if len(raw_ops) != 3: - raise ValueError(f"v_mul_f64 requires 3 operands (dst, src0, src1), got {len(raw_ops)}: {raw_ops}") - - dst = parse_asm_operand(raw_ops[0]) - src0 = parse_asm_operand(raw_ops[1]) - src1 = parse_asm_operand(raw_ops[2]) - inst = ASTInstruction(opcode=opcode, dst=dst, src0=src0, src1=src1, clamp=clamp) - inst.validate() - return inst - - -class ScalarInterpreter: - """Deterministic scalar instruction interpreter for RDNA2 VALU v_mul_f64.""" - - def __init__(self, num_vgprs: int = 256, num_sgprs: int = 106) -> None: - self.vgpr = VALURegisterFile(num_vgprs=num_vgprs) - self.num_sgprs = num_sgprs - self.sgprs = [0] * num_sgprs - self.vcc = 0 - self.scc = 0 - - def get_sgpr(self, idx: int) -> int: - if not (0 <= idx < self.num_sgprs): - raise IndexError(f"SGPR index out of range: {idx}") - return self.sgprs[idx] & MASK32 - - def set_sgpr(self, idx: int, val: int) -> None: - if not (0 <= idx < self.num_sgprs): - raise IndexError(f"SGPR index out of range: {idx}") - self.sgprs[idx] = val & MASK32 - - def get_sgpr_pair(self, idx: int) -> int: - if not (0 <= idx < self.num_sgprs - 1): - raise IndexError(f"SGPR pair index out of range: s[{idx}:{idx+1}]") - lo = self.get_sgpr(idx) - hi = self.get_sgpr(idx + 1) - return join_dwords(lo, hi) - - def set_sgpr_pair(self, idx: int, val64: int) -> None: - if not (0 <= idx < self.num_sgprs - 1): - raise IndexError(f"SGPR pair index out of range: s[{idx}:{idx+1}]") - lo, hi = split_dwords(val64) - self.set_sgpr(idx, lo) - self.set_sgpr(idx + 1, hi) - - def resolve_operand(self, op: ASTOperand) -> int: - if op.kind == OperandKind.VGPR_PAIR: - val = self.vgpr.get_vgpr_pair(op.reg_idx) - elif op.kind == OperandKind.SGPR_PAIR: - val = self.get_sgpr_pair(op.reg_idx) - elif op.kind == OperandKind.LITERAL_64: - val = op.imm_val - elif op.kind == OperandKind.INLINE_IMM: - val = op.imm_val - else: - raise ValueError(f"Unknown operand kind: {op.kind}") - return apply_input_modifiers_f64(val, neg=op.neg, abs_val=op.abs_val) - - def execute_ast(self, inst: ASTInstruction) -> int: - inst.validate() - s0 = self.resolve_operand(inst.src0) - s1 = self.resolve_operand(inst.src1) - res = ref_mul_f64(s0, s1, clamp=inst.clamp) - self.vgpr.set_vgpr_pair(inst.dst.reg_idx, res) - return res - - def execute_asm(self, line: str) -> int: - inst = parse_asm_line(line) - return self.execute_ast(inst) - - -# ============================================================================== -# SIMD Wavefront Execution Model (Wave32 / Wave64) for v_mul_f64 -# ============================================================================== - -def ref_simd_mul_f64( - src0_lanes: list[int], - src1_lanes: list[int], - wave_size: int = 64, - exec_mask: int | None = None, - prev_dst: list[int] | None = None, - *, - clamp: bool = False, - src0_neg: bool = False, - src0_abs: bool = False, - src1_neg: bool = False, - src1_abs: bool = False, -) -> list[int]: - """Reference SIMD execution oracle across wavefront lanes.""" - if wave_size not in (32, 64): - raise ValueError(f"Unsupported wave size: {wave_size}") - if len(src0_lanes) != wave_size or len(src1_lanes) != wave_size: - raise ValueError(f"Operand length must match wave_size ({wave_size})") - - active_mask = (1 << wave_size) - 1 if exec_mask is None else (exec_mask & ((1 << wave_size) - 1)) - fallback = [0] * wave_size if prev_dst is None else prev_dst - if len(fallback) != wave_size: - raise ValueError(f"prev_dst length must match wave_size ({wave_size})") - - output = list(fallback) - for lane in range(wave_size): - if (active_mask >> lane) & 1: - output[lane] = ref_mul_f64( - src0_lanes[lane], - src1_lanes[lane], - clamp=clamp, - src0_neg=src0_neg, - src0_abs=src0_abs, - src1_neg=src1_neg, - src1_abs=src1_abs, - ) - return output - - -class SIMDWavefront: - """SIMD wavefront simulator modeling multi-lane execution and EXEC masking.""" - - def __init__(self, wave_size: int = 64, num_vgprs: int = 256) -> None: - if wave_size not in (32, 64): - raise ValueError(f"Wave size must be 32 or 64, got {wave_size}") - self.wave_size = wave_size - self.num_vgprs = num_vgprs - self.lanes = [VALURegisterFile(num_vgprs=num_vgprs) for _ in range(wave_size)] - self.exec_mask = (1 << wave_size) - 1 - self.vcc = 0 - self.sgprs = [0] * 106 - - def store_vgpr_pair_wave(self, reg_idx: int, values: list[int]) -> None: - if len(values) != self.wave_size: - raise ValueError(f"Value count ({len(values)}) does not match wave_size ({self.wave_size})") - for lane in range(self.wave_size): - self.lanes[lane].set_vgpr_pair(reg_idx, values[lane]) - - def load_vgpr_pair_wave(self, reg_idx: int) -> list[int]: - return [self.lanes[lane].get_vgpr_pair(reg_idx) for lane in range(self.wave_size)] - - def step_v_mul_f64( - self, - dst_reg: int, - src0_reg: int, - src1_reg: int, - *, - clamp: bool = False, - src0_neg: bool = False, - src0_abs: bool = False, - src1_neg: bool = False, - src1_abs: bool = False, - ) -> list[int]: - active_mask = self.exec_mask & ((1 << self.wave_size) - 1) - for lane in range(self.wave_size): - if (active_mask >> lane) & 1: - s0 = self.lanes[lane].get_vgpr_pair(src0_reg) - s1 = self.lanes[lane].get_vgpr_pair(src1_reg) - res = ref_mul_f64( - s0, - s1, - clamp=clamp, - src0_neg=src0_neg, - src0_abs=src0_abs, - src1_neg=src1_neg, - src1_abs=src1_abs, - ) - self.lanes[lane].set_vgpr_pair(dst_reg, res) - return self.load_vgpr_pair_wave(dst_reg) - - -# ============================================================================== -# Condition Codes, Status Flags, and Carry/Borrow Isolation for v_mul_f64 -# ============================================================================== - -@dataclass -class StatusFlags: - invalid_op: bool = False - overflow: bool = False - underflow: bool = False - inexact: bool = False - zero: bool = False - negative: bool = False - nan: bool = False - - -def compute_mul_f64_status_flags(src0: int, src1: int, result: int) -> StatusFlags: - flags = StatusFlags() - s0 = src0 & MASK64 - s1 = src1 & MASK64 - res = result & MASK64 - - # Invalid operation: SNaN operand or 0 * Inf - if is_f64_snan(s0) or is_f64_snan(s1): - flags.invalid_op = True - elif (is_f64_zero(s0) and is_f64_inf(s1)) or (is_f64_inf(s0) and is_f64_zero(s1)): - flags.invalid_op = True - - if is_f64_nan(res): - flags.nan = True - else: - flags.negative = bool(f64_sign(res)) - if is_f64_zero(res): - flags.zero = True - if not is_f64_zero(s0) and not is_f64_zero(s1) and not is_f64_inf(s0) and not is_f64_inf(s1): - flags.underflow = True - else: - # Check overflow: finite * finite -> inf - if not is_f64_inf(s0) and not is_f64_inf(s1) and is_f64_inf(res): - flags.overflow = True - flags.inexact = True - # Check underflow: finite non-zero * finite non-zero -> subnormal - elif not is_f64_zero(s0) and not is_f64_zero(s1) and is_f64_subnormal(res): - flags.underflow = True - - return flags - - -def ref_cmp_f64(op: str, src0: int, src1: int) -> bool: - """Evaluate double-precision IEEE-754 comparison condition codes.""" - if op in ("u", "unordered"): - return is_f64_nan(src0) or is_f64_nan(src1) - - if is_f64_nan(src0) or is_f64_nan(src1): - return op in ("neq", "ne", "!=") - - v0 = u64_to_f64(src0) - v1 = u64_to_f64(src1) - if op in ("eq", "=="): - return v0 == v1 - elif op in ("ne", "neq", "!="): - return v0 != v1 - elif op in ("lt", "<"): - return v0 < v1 - elif op in ("le", "<="): - return v0 <= v1 - elif op in ("gt", ">"): - return v0 > v1 - elif op in ("ge", ">="): - return v0 >= v1 - raise ValueError(f"Unknown comparison operator: {op}") - - -def generate_condition_mask_f64(op: str, src0_lanes: list[int], src1_lanes: list[int]) -> int: - """Generate a 32-bit or 64-bit condition mask (VCC) from per-lane comparisons.""" - mask = 0 - for lane, (s0, s1) in enumerate(zip(src0_lanes, src1_lanes)): - if ref_cmp_f64(op, s0, s1): - mask |= (1 << lane) - return mask - - -class TestVMulF64ReferenceOracle(unittest.TestCase): - """Test suite for reference mathematical oracle and architectural model.""" - - def test_basic_multiplication(self) -> None: - # 2.0 * 3.5 = 7.0 - r = ref_mul_f64(f64_to_u64(2.0), f64_to_u64(3.5)) - self.assertEqual(u64_to_f64(r), 7.0) - - # -1.5 * 4.0 = -6.0 - r = ref_mul_f64(f64_to_u64(-1.5), f64_to_u64(4.0)) - self.assertEqual(u64_to_f64(r), -6.0) - - # -2.5 * -8.0 = 20.0 - r = ref_mul_f64(f64_to_u64(-2.5), f64_to_u64(-8.0)) - self.assertEqual(u64_to_f64(r), 20.0) - - def test_zero_rules(self) -> None: - # +0.0 * +0.0 = +0.0 - self.assertEqual(ref_mul_f64(F64_POS_ZERO, F64_POS_ZERO), F64_POS_ZERO) - # +0.0 * -0.0 = -0.0 - self.assertEqual(ref_mul_f64(F64_POS_ZERO, F64_NEG_ZERO), F64_NEG_ZERO) - # -0.0 * -0.0 = +0.0 - self.assertEqual(ref_mul_f64(F64_NEG_ZERO, F64_NEG_ZERO), F64_POS_ZERO) - # +0.0 * 5.0 = +0.0 - self.assertEqual(ref_mul_f64(F64_POS_ZERO, f64_to_u64(5.0)), F64_POS_ZERO) - # -0.0 * 5.0 = -0.0 - self.assertEqual(ref_mul_f64(F64_NEG_ZERO, f64_to_u64(5.0)), F64_NEG_ZERO) - - def test_inf_and_zero_rules(self) -> None: - # 0 * Inf -> Canonical QNaN - self.assertEqual(ref_mul_f64(F64_POS_ZERO, F64_POS_INF), F64_CANONICAL_QNAN) - self.assertEqual(ref_mul_f64(F64_NEG_ZERO, F64_POS_INF), F64_CANONICAL_QNAN) - self.assertEqual(ref_mul_f64(F64_POS_INF, F64_POS_ZERO), F64_CANONICAL_QNAN) - - # Inf * Inf -> Inf with XOR sign - self.assertEqual(ref_mul_f64(F64_POS_INF, F64_POS_INF), F64_POS_INF) - self.assertEqual(ref_mul_f64(F64_POS_INF, F64_NEG_INF), F64_NEG_INF) - self.assertEqual(ref_mul_f64(F64_NEG_INF, F64_NEG_INF), F64_POS_INF) - - # Inf * finite non-zero -> Inf with XOR sign - self.assertEqual(ref_mul_f64(F64_POS_INF, f64_to_u64(2.0)), F64_POS_INF) - self.assertEqual(ref_mul_f64(F64_POS_INF, f64_to_u64(-2.0)), F64_NEG_INF) - - def test_input_modifiers(self) -> None: - # neg: 2.0 * neg(3.0) = -6.0 - r = ref_mul_f64(f64_to_u64(2.0), f64_to_u64(3.0), src1_neg=True) - self.assertEqual(u64_to_f64(r), -6.0) - - # abs: -2.0 * abs(-3.0) = -6.0 - r = ref_mul_f64(f64_to_u64(-2.0), f64_to_u64(-3.0), src1_abs=True) - self.assertEqual(u64_to_f64(r), -6.0) - - # abs + neg on src0: neg(abs(-2.0)) = -2.0; * 3.0 = -6.0 - r = ref_mul_f64(f64_to_u64(-2.0), f64_to_u64(3.0), src0_abs=True, src0_neg=True) - self.assertEqual(u64_to_f64(r), -6.0) - - def test_clamp_modifier(self) -> None: - # In range [0.0, 1.0]: 0.5 * 1.5 = 0.75 - r = ref_mul_f64(f64_to_u64(0.5), f64_to_u64(1.5), clamp=True) - self.assertEqual(u64_to_f64(r), 0.75) - - # > 1.0 clamped to 1.0: 2.0 * 3.0 = 6.0 -> 1.0 - r = ref_mul_f64(f64_to_u64(2.0), f64_to_u64(3.0), clamp=True) - self.assertEqual(r, F64_ONE) - - # < 0.0 clamped to +0.0: -2.0 * 3.0 = -6.0 -> +0.0 - r = ref_mul_f64(f64_to_u64(-2.0), f64_to_u64(3.0), clamp=True) - self.assertEqual(r, F64_POS_ZERO) - - # NaN clamped to +0.0 - r = ref_mul_f64(F64_POS_ZERO, F64_POS_INF, clamp=True) - self.assertEqual(r, F64_POS_ZERO) - - def test_dword_decomposition(self) -> None: - s0 = f64_to_u64(12.345) - s1 = f64_to_u64(67.89) - s0_lo, s0_hi = split_dwords(s0) - s1_lo, s1_hi = split_dwords(s1) - - lo, hi = ref_mul_f64_dwords(s0_lo, s0_hi, s1_lo, s1_hi) - res64 = join_dwords(lo, hi) - expected = ref_mul_f64(s0, s1) - self.assertEqual(res64, expected) - - def test_register_file_pair_access(self) -> None: - rf = VALURegisterFile(num_vgprs=16) - val = 0x01234567_89ABCDEF - rf.set_vgpr_pair(4, val) - - self.assertEqual(rf.get_vgpr(4), 0x89ABCDEF) - self.assertEqual(rf.get_vgpr(5), 0x01234567) - self.assertEqual(rf.get_vgpr_pair(4), val) - - with self.assertRaises(IndexError): - rf.get_vgpr_pair(15) - - -class TestSymbolicAST(unittest.TestCase): - """Test suite for symbolic AST definitions and typed expressions.""" - - def test_ast_creation_and_formatting(self) -> None: - dst = ASTOperand(kind=OperandKind.VGPR_PAIR, reg_idx=0) - src0 = ASTOperand(kind=OperandKind.VGPR_PAIR, reg_idx=2) - src1 = ASTOperand(kind=OperandKind.SGPR_PAIR, reg_idx=4) - inst = ASTInstruction(opcode="v_mul_f64", dst=dst, src0=src0, src1=src1) - inst.validate() - self.assertEqual(inst.format_asm(), "v_mul_f64 v[0:1], v[2:3], s[4:5]") - - # With clamp and modifiers - src0_mod = ASTOperand(kind=OperandKind.VGPR_PAIR, reg_idx=2, neg=True, abs_val=True) - inst_clamp = ASTInstruction(opcode="v_mul_f64", dst=dst, src0=src0_mod, src1=src1, clamp=True) - inst_clamp.validate() - self.assertEqual(inst_clamp.format_asm(), "v_mul_f64 v[0:1], -|v[2:3]|, s[4:5] clamp") - - def test_typed_expression_evaluation(self) -> None: - c1 = F64Constant(f64_to_u64(2.5)) - c2 = F64Constant(f64_to_u64(4.0)) - mul_expr = F64Mul(lhs=c1, rhs=c2) - res = mul_expr.evaluate({}) - self.assertEqual(u64_to_f64(res), 10.0) - - # Unary operations - neg_c1 = F64UnaryOp("neg", c1) - res_neg = F64Mul(lhs=neg_c1, rhs=c2).evaluate({}) - self.assertEqual(u64_to_f64(res_neg), -10.0) - - def test_instruction_to_expression(self) -> None: - dst = ASTOperand(kind=OperandKind.VGPR_PAIR, reg_idx=0) - src0 = ASTOperand(kind=OperandKind.VGPR_PAIR, reg_idx=2, neg=True) - src1 = ASTOperand(kind=OperandKind.LITERAL_64, imm_val=f64_to_u64(3.0)) - inst = ASTInstruction(opcode="v_mul_f64", dst=dst, src0=src0, src1=src1, clamp=False) - - expr = instruction_to_expression(inst) - env = {"src0_2": f64_to_u64(4.0)} - res = expr.evaluate(env) - # -4.0 * 3.0 = -12.0 - self.assertEqual(u64_to_f64(res), -12.0) - - def test_ast_validation_errors(self) -> None: - # Invalid opcode - bad_op = ASTInstruction( - opcode="v_add_f64", - dst=ASTOperand(OperandKind.VGPR_PAIR, 0), - src0=ASTOperand(OperandKind.VGPR_PAIR, 2), - src1=ASTOperand(OperandKind.VGPR_PAIR, 4), - ) - with self.assertRaises(ValueError): - bad_op.validate() - - # Destination cannot be SGPR - bad_dst = ASTInstruction( - opcode="v_mul_f64", - dst=ASTOperand(OperandKind.SGPR_PAIR, 0), - src0=ASTOperand(OperandKind.VGPR_PAIR, 2), - src1=ASTOperand(OperandKind.VGPR_PAIR, 4), - ) - with self.assertRaises(ValueError): - bad_dst.validate() - - # Destination out of bounds - oob_dst = ASTInstruction( - opcode="v_mul_f64", - dst=ASTOperand(OperandKind.VGPR_PAIR, 256), - src0=ASTOperand(OperandKind.VGPR_PAIR, 2), - src1=ASTOperand(OperandKind.VGPR_PAIR, 4), - ) - with self.assertRaises(ValueError): - oob_dst.validate() - - -class TestScalarInterpreter(unittest.TestCase): - """Test suite for deterministic scalar instruction interpreter.""" - - def test_execute_vgpr_sources(self) -> None: - interp = ScalarInterpreter() - interp.vgpr.set_vgpr_pair(2, f64_to_u64(3.0)) - interp.vgpr.set_vgpr_pair(4, f64_to_u64(4.5)) - - dst = ASTOperand(kind=OperandKind.VGPR_PAIR, reg_idx=0) - src0 = ASTOperand(kind=OperandKind.VGPR_PAIR, reg_idx=2) - src1 = ASTOperand(kind=OperandKind.VGPR_PAIR, reg_idx=4) - inst = ASTInstruction(opcode="v_mul_f64", dst=dst, src0=src0, src1=src1) - - res = interp.execute_ast(inst) - self.assertEqual(u64_to_f64(res), 13.5) - self.assertEqual(interp.vgpr.get_vgpr_pair(0), res) - - def test_execute_sgpr_sources(self) -> None: - interp = ScalarInterpreter() - interp.set_sgpr_pair(0, f64_to_u64(-2.0)) - interp.vgpr.set_vgpr_pair(2, f64_to_u64(7.0)) - - dst = ASTOperand(kind=OperandKind.VGPR_PAIR, reg_idx=4) - src0 = ASTOperand(kind=OperandKind.SGPR_PAIR, reg_idx=0) - src1 = ASTOperand(kind=OperandKind.VGPR_PAIR, reg_idx=2) - inst = ASTInstruction(opcode="v_mul_f64", dst=dst, src0=src0, src1=src1) - - res = interp.execute_ast(inst) - self.assertEqual(u64_to_f64(res), -14.0) - self.assertEqual(interp.vgpr.get_vgpr_pair(4), res) - - def test_execute_literal_source(self) -> None: - interp = ScalarInterpreter() - interp.vgpr.set_vgpr_pair(2, f64_to_u64(5.0)) - - dst = ASTOperand(kind=OperandKind.VGPR_PAIR, reg_idx=0) - src0 = ASTOperand(kind=OperandKind.VGPR_PAIR, reg_idx=2) - src1 = ASTOperand(kind=OperandKind.LITERAL_64, imm_val=f64_to_u64(0.2)) - inst = ASTInstruction(opcode="v_mul_f64", dst=dst, src0=src0, src1=src1) - - res = interp.execute_ast(inst) - self.assertEqual(u64_to_f64(res), 1.0) - self.assertEqual(interp.vgpr.get_vgpr_pair(0), res) - - def test_execute_text_asm(self) -> None: - interp = ScalarInterpreter() - interp.vgpr.set_vgpr_pair(6, f64_to_u64(1.25)) - interp.set_sgpr_pair(8, f64_to_u64(8.0)) - - res = interp.execute_asm("v_mul_f64 v[0:1], v[6:7], s[8:9]") - self.assertEqual(u64_to_f64(res), 10.0) - self.assertEqual(interp.vgpr.get_vgpr_pair(0), f64_to_u64(10.0)) - - def test_execute_modifiers_and_clamp(self) -> None: - interp = ScalarInterpreter() - interp.vgpr.set_vgpr_pair(2, f64_to_u64(-1.5)) - interp.vgpr.set_vgpr_pair(4, f64_to_u64(-0.5)) - - # -|v[2:3]| is -1.5, multiplied by -0.5 is 0.75, within clamp [0, 1] - res = interp.execute_asm("v_mul_f64 v[0:1], -|v[2:3]|, v[4:5] clamp") - self.assertEqual(u64_to_f64(res), 0.75) - - # > 1.0 clamped - interp.vgpr.set_vgpr_pair(4, f64_to_u64(-2.0)) - # -1.5 * -2.0 = 3.0 -> clamped to 1.0 - res2 = interp.execute_asm("v_mul_f64 v[0:1], -|v[2:3]|, v[4:5] clamp") - self.assertEqual(res2, F64_ONE) - - -class TestSIMDMultiLaneDivergence(unittest.TestCase): - """Test suite for SIMD multi-lane divergence and 32/64-bit EXEC masking.""" - - def test_wave32_all_active(self) -> None: - sim = SIMDWavefront(wave_size=32) - s0_vals = [f64_to_u64(float(i + 1)) for i in range(32)] - s1_vals = [f64_to_u64(2.5) for _ in range(32)] - sim.store_vgpr_pair_wave(2, s0_vals) - sim.store_vgpr_pair_wave(4, s1_vals) - - res = sim.step_v_mul_f64(0, 2, 4) - for i in range(32): - self.assertEqual(u64_to_f64(res[i]), (i + 1) * 2.5) - - def test_wave64_all_active(self) -> None: - sim = SIMDWavefront(wave_size=64) - s0_vals = [f64_to_u64(float(i + 1)) for i in range(64)] - s1_vals = [f64_to_u64(0.125) for _ in range(64)] - sim.store_vgpr_pair_wave(2, s0_vals) - sim.store_vgpr_pair_wave(4, s1_vals) - - res = sim.step_v_mul_f64(0, 2, 4) - for i in range(64): - self.assertEqual(u64_to_f64(res[i]), (i + 1) * 0.125) - - def test_wave32_divergent_exec_mask(self) -> None: - sim = SIMDWavefront(wave_size=32) - sentinel_pair = join_dwords(OLD_VGPR_SENTINEL, OLD_VGPR_SENTINEL) - sim.store_vgpr_pair_wave(0, [sentinel_pair] * 32) - - s0_vals = [f64_to_u64(3.0)] * 32 - s1_vals = [f64_to_u64(4.0)] * 32 - sim.store_vgpr_pair_wave(2, s0_vals) - sim.store_vgpr_pair_wave(4, s1_vals) - - # Alternating lanes active: 0b0101... - sim.exec_mask = 0x55555555 - res = sim.step_v_mul_f64(0, 2, 4) - - for lane in range(32): - if lane % 2 == 0: - self.assertEqual(u64_to_f64(res[lane]), 12.0) - else: - self.assertEqual(res[lane], sentinel_pair) - - def test_wave64_divergent_exec_mask(self) -> None: - sim = SIMDWavefront(wave_size=64) - sentinel_pair = join_dwords(OLD_VGPR_SENTINEL, OLD_VGPR_SENTINEL) - sim.store_vgpr_pair_wave(0, [sentinel_pair] * 64) - - s0_vals = [f64_to_u64(2.0)] * 64 - s1_vals = [f64_to_u64(5.0)] * 64 - sim.store_vgpr_pair_wave(2, s0_vals) - sim.store_vgpr_pair_wave(4, s1_vals) - - # Lower 32 lanes active, upper 32 inactive - sim.exec_mask = 0x00000000_FFFFFFFF - res = sim.step_v_mul_f64(0, 2, 4) - - for lane in range(32): - self.assertEqual(u64_to_f64(res[lane]), 10.0) - for lane in range(32, 64): - self.assertEqual(res[lane], sentinel_pair) - - def test_wave32_upper_exec_bits_ignored(self) -> None: - sim = SIMDWavefront(wave_size=32) - sentinel_pair = join_dwords(OLD_VGPR_SENTINEL, OLD_VGPR_SENTINEL) - sim.store_vgpr_pair_wave(0, [sentinel_pair] * 32) - sim.store_vgpr_pair_wave(2, [f64_to_u64(2.0)] * 32) - sim.store_vgpr_pair_wave(4, [f64_to_u64(3.0)] * 32) - - # In Wave32, upper 32 bits of exec_mask must have no effect - sim.exec_mask = 0xDEADBEEF_FFFFFFFF - res = sim.step_v_mul_f64(0, 2, 4) - for lane in range(32): - self.assertEqual(u64_to_f64(res[lane]), 6.0) - - def test_simd_oracle_validation(self) -> None: - wave_size = 64 - s0_vals = [f64_to_u64(float(i + 1.5)) for i in range(wave_size)] - s1_vals = [f64_to_u64(float(i + 0.5)) for i in range(wave_size)] - exec_mask = 0xAAAAAAAAAAAAAAAA - - prev_dst = [join_dwords(0xCAFE, i) for i in range(wave_size)] - expected = ref_simd_mul_f64(s0_vals, s1_vals, wave_size=wave_size, exec_mask=exec_mask, prev_dst=prev_dst) - - sim = SIMDWavefront(wave_size=wave_size) - sim.store_vgpr_pair_wave(0, prev_dst) - sim.store_vgpr_pair_wave(2, s0_vals) - sim.store_vgpr_pair_wave(4, s1_vals) - sim.exec_mask = exec_mask - - actual = sim.step_v_mul_f64(0, 2, 4) - self.assertEqual(actual, expected) - - -class TestRegisterAliasing(unittest.TestCase): - """Test suite for register aliasing and in-place operand preservation.""" - - def test_inplace_dst_equals_src0(self) -> None: - interp = ScalarInterpreter() - interp.vgpr.set_vgpr_pair(4, f64_to_u64(3.0)) - interp.vgpr.set_vgpr_pair(6, f64_to_u64(5.0)) - - # v[4:5] = v[4:5] * v[6:7] - res = interp.execute_asm("v_mul_f64 v[4:5], v[4:5], v[6:7]") - self.assertEqual(u64_to_f64(res), 15.0) - self.assertEqual(interp.vgpr.get_vgpr_pair(4), f64_to_u64(15.0)) - # src1 v[6:7] must remain intact - self.assertEqual(u64_to_f64(interp.vgpr.get_vgpr_pair(6)), 5.0) - - def test_inplace_dst_equals_src1(self) -> None: - interp = ScalarInterpreter() - interp.vgpr.set_vgpr_pair(4, f64_to_u64(7.0)) - interp.vgpr.set_vgpr_pair(6, f64_to_u64(2.0)) - - # v[6:7] = v[4:5] * v[6:7] - res = interp.execute_asm("v_mul_f64 v[6:7], v[4:5], v[6:7]") - self.assertEqual(u64_to_f64(res), 14.0) - self.assertEqual(interp.vgpr.get_vgpr_pair(6), f64_to_u64(14.0)) - # src0 v[4:5] must remain intact - self.assertEqual(u64_to_f64(interp.vgpr.get_vgpr_pair(4)), 7.0) - - def test_inplace_self_squaring(self) -> None: - interp = ScalarInterpreter() - interp.vgpr.set_vgpr_pair(2, f64_to_u64(-4.0)) - - # v[2:3] = v[2:3] * v[2:3] -> 16.0 - res = interp.execute_asm("v_mul_f64 v[2:3], v[2:3], v[2:3]") - self.assertEqual(u64_to_f64(res), 16.0) - self.assertEqual(interp.vgpr.get_vgpr_pair(2), f64_to_u64(16.0)) - - def test_partially_overlapping_register_pairs(self) -> None: - interp = ScalarInterpreter() - # Setup: - # v0 = 0xAAAA0000, v1 = 0x0000BBBB -> src0 v[0:1] - # v2 = 0xCCCC0000, v3 = 0x0000DDDD -> src1 v[2:3] - s0_val = f64_to_u64(3.0) - s1_val = f64_to_u64(6.0) - interp.vgpr.set_vgpr_pair(0, s0_val) - interp.vgpr.set_vgpr_pair(2, s1_val) - - v0_before = interp.vgpr.get_vgpr(0) - v3_before = interp.vgpr.get_vgpr(3) - - # Execute with dst as unaligned v[1:2] overlapping both src0 (via v1) and src1 (via v2) - dst = ASTOperand(kind=OperandKind.VGPR_PAIR, reg_idx=1) - src0 = ASTOperand(kind=OperandKind.VGPR_PAIR, reg_idx=0) - src1 = ASTOperand(kind=OperandKind.VGPR_PAIR, reg_idx=2) - inst = ASTInstruction(opcode="v_mul_f64", dst=dst, src0=src0, src1=src1) - res = interp.execute_ast(inst) - - self.assertEqual(u64_to_f64(res), 18.0) - self.assertEqual(interp.vgpr.get_vgpr_pair(1), f64_to_u64(18.0)) - # Non-overlapping boundary dwords v[0] and v[3] must remain completely unchanged - self.assertEqual(interp.vgpr.get_vgpr(0), v0_before) - self.assertEqual(interp.vgpr.get_vgpr(3), v3_before) - - def test_simd_inplace_divergent_mask(self) -> None: - sim = SIMDWavefront(wave_size=32) - init_vals = [f64_to_u64(float(i + 1)) for i in range(32)] - scale_vals = [f64_to_u64(10.0) for _ in range(32)] - sim.store_vgpr_pair_wave(0, init_vals) - sim.store_vgpr_pair_wave(2, scale_vals) - - # Active on odd lanes only: 0xAAAAAAAA - sim.exec_mask = 0xAAAAAAAA - res = sim.step_v_mul_f64(0, 0, 2) - - for lane in range(32): - if lane % 2 == 1: - # Active lane: multiplied - self.assertEqual(u64_to_f64(res[lane]), (lane + 1) * 10.0) - else: - # Inactive lane: preserved original - self.assertEqual(res[lane], init_vals[lane]) - - def test_successive_inplace_chain(self) -> None: - interp = ScalarInterpreter() - interp.vgpr.set_vgpr_pair(0, f64_to_u64(1.0)) - interp.vgpr.set_vgpr_pair(2, f64_to_u64(2.0)) - - # Repeatedly double v[0:1] 5 times: 1.0 -> 2.0 -> 4.0 -> 8.0 -> 16.0 -> 32.0 - for _ in range(5): - interp.execute_asm("v_mul_f64 v[0:1], v[0:1], v[2:3]") - - self.assertEqual(u64_to_f64(interp.vgpr.get_vgpr_pair(0)), 32.0) - - -class TestConditionCodesAndStatusFlags(unittest.TestCase): - """Test suite for condition codes, status flags, and carry/borrow isolation.""" - - def test_status_flags_invalid_operation(self) -> None: - # 0.0 * Inf - res = ref_mul_f64(F64_POS_ZERO, F64_POS_INF) - flags = compute_mul_f64_status_flags(F64_POS_ZERO, F64_POS_INF, res) - self.assertTrue(flags.invalid_op) - self.assertTrue(flags.nan) - - # SNaN * 2.0 (SNaN has quiet bit = 0) - snan = (F64_POS_INF | 0x0001000000000000) & ~F64_QUIET_BIT - res_snan = ref_mul_f64(snan, F64_TWO) - flags_snan = compute_mul_f64_status_flags(snan, F64_TWO, res_snan) - self.assertTrue(flags_snan.invalid_op) - self.assertTrue(flags_snan.nan) - - def test_status_flags_overflow(self) -> None: - # (1e200) * (1e200) overflows binary64 - val = f64_to_u64(1e200) - res = ref_mul_f64(val, val) - flags = compute_mul_f64_status_flags(val, val, res) - self.assertTrue(flags.overflow) - self.assertTrue(flags.inexact) - self.assertEqual(res, F64_POS_INF) - - def test_status_flags_underflow(self) -> None: - # (1e-200) * (1e-200) underflows to 0.0 - val = f64_to_u64(1e-200) - res = ref_mul_f64(val, val) - flags = compute_mul_f64_status_flags(val, val, res) - self.assertTrue(flags.underflow) - self.assertTrue(flags.zero) - - def test_status_flags_zero_and_negative(self) -> None: - # -2.0 * 3.0 = -6.0 (negative, non-zero) - v0 = f64_to_u64(-2.0) - v1 = f64_to_u64(3.0) - r1 = ref_mul_f64(v0, v1) - flags1 = compute_mul_f64_status_flags(v0, v1, r1) - self.assertTrue(flags1.negative) - self.assertFalse(flags1.zero) - - # -0.0 * 3.0 = -0.0 (negative zero) - r2 = ref_mul_f64(F64_NEG_ZERO, v1) - flags2 = compute_mul_f64_status_flags(F64_NEG_ZERO, v1, r2) - self.assertTrue(flags2.negative) - self.assertTrue(flags2.zero) - - def test_vcc_and_scc_preserved(self) -> None: - # Floating point v_mul_f64 does not generate carry/borrow and never writes VCC or SCC - interp = ScalarInterpreter() - interp.vcc = 0x12345678_9ABCDEF0 - interp.scc = 1 - interp.vgpr.set_vgpr_pair(2, f64_to_u64(4.0)) - interp.vgpr.set_vgpr_pair(4, f64_to_u64(5.0)) - - interp.execute_asm("v_mul_f64 v[0:1], v[2:3], v[4:5]") - self.assertEqual(interp.vcc, 0x12345678_9ABCDEF0) - self.assertEqual(interp.scc, 1) - - sim = SIMDWavefront(wave_size=32) - sim.vcc = 0xCAFEBABE - sim.store_vgpr_pair_wave(2, [f64_to_u64(2.0)] * 32) - sim.store_vgpr_pair_wave(4, [f64_to_u64(3.0)] * 32) - sim.step_v_mul_f64(0, 2, 4) - self.assertEqual(sim.vcc, 0xCAFEBABE) - - def test_condition_code_generation(self) -> None: - # Generate condition codes from comparisons on multiplication results - v_zero = [F64_POS_ZERO] * 4 - # Four lanes: products will be [-4.0, 0.0, 4.0, NaN] - s0 = [f64_to_u64(-2.0), f64_to_u64(0.0), f64_to_u64(2.0), F64_POS_ZERO] - s1 = [f64_to_u64(2.0), f64_to_u64(5.0), f64_to_u64(2.0), F64_POS_INF] - prods = [ref_mul_f64(a, b) for a, b in zip(s0, s1)] - - # Compare < 0: only lane 0 (-4.0 < 0) -> bit 0 - mask_lt = generate_condition_mask_f64("<", prods, v_zero) - self.assertEqual(mask_lt, 0b0001) - - # Compare == 0: only lane 1 (0.0 == 0) -> bit 1 - mask_eq = generate_condition_mask_f64("==", prods, v_zero) - self.assertEqual(mask_eq, 0b0010) - - # Compare > 0: only lane 2 (4.0 > 0) -> bit 2 - mask_gt = generate_condition_mask_f64(">", prods, v_zero) - self.assertEqual(mask_gt, 0b0100) - - # Compare unordered: only lane 3 (NaN) -> bit 3 - mask_u = generate_condition_mask_f64("u", prods, v_zero) - self.assertEqual(mask_u, 0b1000) - - -class TestIEEE754BoundaryExtremes(unittest.TestCase): - """Test suite for IEEE-754 boundary extremes, subnormals, and NaN handling.""" - - def test_nan_snan_quieting(self) -> None: - # Positive signaling NaN - snan_pos = 0x7FF0000000000001 - self.assertTrue(is_f64_snan(snan_pos)) - res_pos = ref_mul_f64(snan_pos, F64_ONE) - self.assertTrue(is_f64_qnan(res_pos)) - self.assertEqual(res_pos, 0x7FF8000000000001) - - # Negative signaling NaN - snan_neg = 0xFFF0000012345678 - self.assertTrue(is_f64_snan(snan_neg)) - res_neg = ref_mul_f64(F64_TWO, snan_neg) - self.assertTrue(is_f64_qnan(res_neg)) - self.assertEqual(res_neg, 0xFFF8000012345678) - - def test_nan_payload_propagation(self) -> None: - # Quiet NaN payload from src0 - qnan_a = 0x7FF8AABBCCDDEEFF - res_a = ref_mul_f64(qnan_a, f64_to_u64(5.0)) - self.assertEqual(res_a, qnan_a) - - # Quiet NaN payload from src1 - qnan_b = 0xFFF8112233445566 - res_b = ref_mul_f64(f64_to_u64(-3.0), qnan_b) - self.assertEqual(res_b, qnan_b) - - def test_nan_dual_precedence(self) -> None: - # When both are NaN, src0 takes precedence - qnan0 = 0x7FF8AAAA00000000 - qnan1 = 0x7FF8BBBB00000000 - res = ref_mul_f64(qnan0, qnan1) - self.assertEqual(res, qnan0) - - def test_signed_zero_combinations(self) -> None: - self.assertEqual(ref_mul_f64(F64_POS_ZERO, F64_POS_ZERO), F64_POS_ZERO) - self.assertEqual(ref_mul_f64(F64_POS_ZERO, F64_NEG_ZERO), F64_NEG_ZERO) - self.assertEqual(ref_mul_f64(F64_NEG_ZERO, F64_POS_ZERO), F64_NEG_ZERO) - self.assertEqual(ref_mul_f64(F64_NEG_ZERO, F64_NEG_ZERO), F64_POS_ZERO) - - # With finite numbers - self.assertEqual(ref_mul_f64(F64_POS_ZERO, f64_to_u64(10.0)), F64_POS_ZERO) - self.assertEqual(ref_mul_f64(F64_POS_ZERO, f64_to_u64(-10.0)), F64_NEG_ZERO) - self.assertEqual(ref_mul_f64(F64_NEG_ZERO, f64_to_u64(10.0)), F64_NEG_ZERO) - self.assertEqual(ref_mul_f64(F64_NEG_ZERO, f64_to_u64(-10.0)), F64_POS_ZERO) - - def test_signed_infinity_combinations(self) -> None: - self.assertEqual(ref_mul_f64(F64_POS_INF, F64_POS_INF), F64_POS_INF) - self.assertEqual(ref_mul_f64(F64_POS_INF, F64_NEG_INF), F64_NEG_INF) - self.assertEqual(ref_mul_f64(F64_NEG_INF, F64_POS_INF), F64_NEG_INF) - self.assertEqual(ref_mul_f64(F64_NEG_INF, F64_NEG_INF), F64_POS_INF) - - # With finite numbers - self.assertEqual(ref_mul_f64(F64_POS_INF, f64_to_u64(2.0)), F64_POS_INF) - self.assertEqual(ref_mul_f64(F64_POS_INF, f64_to_u64(-2.0)), F64_NEG_INF) - self.assertEqual(ref_mul_f64(F64_NEG_INF, f64_to_u64(2.0)), F64_NEG_INF) - self.assertEqual(ref_mul_f64(F64_NEG_INF, f64_to_u64(-2.0)), F64_POS_INF) - - def test_max_normal_overflow(self) -> None: - # DBL_MAX * 1.0 = DBL_MAX - self.assertEqual(ref_mul_f64(F64_MAX_NORMAL, F64_ONE), F64_MAX_NORMAL) - # DBL_MAX * -1.0 = -DBL_MAX - self.assertEqual(ref_mul_f64(F64_MAX_NORMAL, F64_NEG_ONE), F64_MAX_NORMAL | F64_SIGN_MASK) - # DBL_MAX * 2.0 = +inf (overflow) - self.assertEqual(ref_mul_f64(F64_MAX_NORMAL, F64_TWO), F64_POS_INF) - # DBL_MAX * -2.0 = -inf (overflow) - self.assertEqual(ref_mul_f64(F64_MAX_NORMAL, f64_to_u64(-2.0)), F64_NEG_INF) - - def test_min_normal_underflow_to_subnormal(self) -> None: - # DBL_MIN * 1.0 = DBL_MIN - self.assertEqual(ref_mul_f64(F64_MIN_NORMAL, F64_ONE), F64_MIN_NORMAL) - # DBL_MIN * 0.5 = subnormal 2^-1023 - res = ref_mul_f64(F64_MIN_NORMAL, F64_HALF) - self.assertTrue(is_f64_subnormal(res)) - self.assertEqual(res, 0x0008000000000000) - - def test_subnormal_boundaries(self) -> None: - # Min subnormal (2^-1074) * 1.0 = min subnormal - self.assertEqual(ref_mul_f64(F64_MIN_SUBNORMAL, F64_ONE), F64_MIN_SUBNORMAL) - # Min subnormal * 2.0 = 2^-1073 (0x2) - self.assertEqual(ref_mul_f64(F64_MIN_SUBNORMAL, F64_TWO), 0x0000000000000002) - # Min subnormal * 0.5 = underflow to +0.0 - self.assertEqual(ref_mul_f64(F64_MIN_SUBNORMAL, F64_HALF), F64_POS_ZERO) - # -Min subnormal * 0.5 = underflow to -0.0 - self.assertEqual(ref_mul_f64(F64_MIN_SUBNORMAL | F64_SIGN_MASK, F64_HALF), F64_NEG_ZERO) - - def test_round_to_nearest_even(self) -> None: - v_base = 1.0 + 2.0**(-52) - bits_base = f64_to_u64(v_base) - res = ref_mul_f64(bits_base, F64_ONE) - self.assertEqual(res, bits_base) - - -# ============================================================================== -# Mutants for Mutation Detection -# ============================================================================== - -def mutant_mul_as_add(s0: int, s1: int, **kwargs) -> int: - """Mutant 1: Replaces multiplication with addition.""" - v0 = u64_to_f64(s0) - v1 = u64_to_f64(s1) - return f64_to_u64(v0 + v1) - - -def mutant_ignore_neg(s0: int, s1: int, *, src0_neg: bool = False, src1_neg: bool = False, **kwargs) -> int: - """Mutant 2: Ignores negative modifiers.""" - return ref_mul_f64(s0, s1, src0_neg=False, src1_neg=False, **kwargs) - - -def mutant_ignore_abs(s0: int, s1: int, *, src0_abs: bool = False, src1_abs: bool = False, **kwargs) -> int: - """Mutant 3: Ignores absolute value modifiers.""" - return ref_mul_f64(s0, s1, src0_abs=False, src1_abs=False, **kwargs) - - -def mutant_ignore_clamp(s0: int, s1: int, *, clamp: bool = False, **kwargs) -> int: - """Mutant 4: Ignores clamp.""" - return ref_mul_f64(s0, s1, clamp=False, **kwargs) - - -def mutant_clamp_nan_to_nan(s0: int, s1: int, *, clamp: bool = False, **kwargs) -> int: - """Mutant 5: Clamps numbers but fails to clamp NaN to +0.0.""" - res = ref_mul_f64(s0, s1, clamp=False, **kwargs) - if clamp and not is_f64_nan(res): - val = u64_to_f64(res) - if val < 0.0: - return F64_POS_ZERO - elif val > 1.0: - return F64_ONE - return res - - -def mutant_snan_not_quieted(s0: int, s1: int, **kwargs) -> int: - """Mutant 6: Returns SNaN without quieting.""" - if is_f64_snan(s0): - return s0 - if is_f64_snan(s1): - return s1 - return ref_mul_f64(s0, s1, **kwargs) - - -def mutant_zero_inf_returns_zero(s0: int, s1: int, **kwargs) -> int: - """Mutant 7: 0 * Inf returns 0 instead of canonical QNaN.""" - if (is_f64_zero(s0) and is_f64_inf(s1)) or (is_f64_inf(s0) and is_f64_zero(s1)): - return F64_POS_ZERO - return ref_mul_f64(s0, s1, **kwargs) - - -def mutant_f32_truncation(s0: int, s1: int, **kwargs) -> int: - """Mutant 8: Truncates operands to single-precision float.""" - f0 = struct.unpack(" None: - for bad_op in ("v_mul_f32", "v_add_f64", "s_mul_f64", "v_mul_i64", "foo"): - with self.assertRaises(ValueError): - parse_asm_line(f"{bad_op} v[0:1], v[2:3], v[4:5]") - - def test_syntax_rejection_bad_operands(self) -> None: - # Malformed register syntax - for bad_line in ( - "v_mul_f64 v0, v[2:3], v[4:5]", - "v_mul_f64 v[0:1], invalid_reg, v[4:5]", - "v_mul_f64 v[0:1], v[2:3], xyz", - ): - with self.assertRaises(ValueError): - parse_asm_line(bad_line) - - def test_syntax_rejection_operand_count(self) -> None: - # Too few operands - with self.assertRaises(ValueError): - parse_asm_line("v_mul_f64 v[0:1], v[2:3]") - # Too many operands - with self.assertRaises(ValueError): - parse_asm_line("v_mul_f64 v[0:1], v[2:3], v[4:5], v[6:7]") - - def test_syntax_rejection_destination_modifiers(self) -> None: - with self.assertRaises(ValueError): - parse_asm_line("v_mul_f64 -v[0:1], v[2:3], v[4:5]") - with self.assertRaises(ValueError): - parse_asm_line("v_mul_f64 |v[0:1]|, v[2:3], v[4:5]") - - def test_syntax_rejection_empty_lines(self) -> None: - with self.assertRaises(ValueError): - parse_asm_line("") - with self.assertRaises(ValueError): - parse_asm_line(" ; comment only") - - def test_negative_control_add_instead_of_mul(self) -> None: - # Multiplying 3.0 * 4.0 should be 12.0, not 7.0 - v0 = f64_to_u64(3.0) - v1 = f64_to_u64(4.0) - good = ref_mul_f64(v0, v1) - bad = mutant_mul_as_add(v0, v1) - self.assertNotEqual(good, bad) - self.assertEqual(u64_to_f64(good), 12.0) - self.assertEqual(u64_to_f64(bad), 7.0) - - def test_negative_control_single_precision_loss(self) -> None: - # A precision pattern that fits binary64 but loses bits in binary32: - # 1.0000000000001 * 1.0000000000001 - v = 1.0 + 1e-12 - v_bits = f64_to_u64(v) - good = ref_mul_f64(v_bits, v_bits) - bad = mutant_f32_truncation(v_bits, v_bits) - self.assertNotEqual(good, bad) - - def test_mutation_detection_all_mutants_caught(self) -> None: - # Verify that our test suite discriminator catches every mutant: - # Mutant 1: add instead of mul - self.assertNotEqual(ref_mul_f64(f64_to_u64(3.0), f64_to_u64(4.0)), - mutant_mul_as_add(f64_to_u64(3.0), f64_to_u64(4.0))) - - # Mutant 2: ignore neg - self.assertNotEqual(ref_mul_f64(f64_to_u64(3.0), f64_to_u64(4.0), src0_neg=True), - mutant_ignore_neg(f64_to_u64(3.0), f64_to_u64(4.0), src0_neg=True)) - - # Mutant 3: ignore abs - self.assertNotEqual(ref_mul_f64(f64_to_u64(-3.0), f64_to_u64(4.0), src0_abs=True), - mutant_ignore_abs(f64_to_u64(-3.0), f64_to_u64(4.0), src0_abs=True)) - - # Mutant 4: ignore clamp - self.assertNotEqual(ref_mul_f64(f64_to_u64(2.0), f64_to_u64(3.0), clamp=True), - mutant_ignore_clamp(f64_to_u64(2.0), f64_to_u64(3.0), clamp=True)) - - # Mutant 5: clamp NaN to NaN instead of +0.0 - self.assertNotEqual(ref_mul_f64(F64_POS_ZERO, F64_POS_INF, clamp=True), - mutant_clamp_nan_to_nan(F64_POS_ZERO, F64_POS_INF, clamp=True)) - - # Mutant 6: SNaN not quieted - snan = 0x7FF0000000000001 - self.assertNotEqual(ref_mul_f64(snan, F64_ONE), - mutant_snan_not_quieted(snan, F64_ONE)) - - # Mutant 7: 0 * Inf returns 0 instead of QNaN - self.assertNotEqual(ref_mul_f64(F64_POS_ZERO, F64_POS_INF), - mutant_zero_inf_returns_zero(F64_POS_ZERO, F64_POS_INF)) - - # Mutant 8: f32 truncation - v = f64_to_u64(1.0000000000001) - self.assertNotEqual(ref_mul_f64(v, v), - mutant_f32_truncation(v, v)) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_valu_mul_hi.py b/tests/semantic/test_valu_mul_hi.py deleted file mode 100644 index fb91c833b..000000000 --- a/tests/semantic/test_valu_mul_hi.py +++ /dev/null @@ -1,149 +0,0 @@ -"""v_mul_hi_u32 and v_mul_hi_i32 (RDNA2 VOP3): D = high 32 bits of the 64-bit product of two 32-bit sources. - -Every case is translated by tools/rdna2spirv.py and executed with tests/semantic/spirv_mini_interp.py; the expected -word is written down by hand next to each case and also recomputed by the plain-Python reference below. -Standard library only: no GPU, no LLVM, no game data. -""" -import os -import random -import sys -import unittest - -HERE = os.path.dirname(os.path.abspath(__file__)) -sys.dont_write_bytecode = True -sys.path.insert(0, HERE) - -import support # noqa: E402 - -MASK32 = 0xFFFFFFFF -INT32_MAX = 0x7FFFFFFF -INT32_MIN = 0x80000000 - - -def ref_u32(a, b): - return ((a & MASK32) * (b & MASK32) >> 32) & MASK32 - - -def ref_i32(a, b): - sa = a - (1 << 32) if a & 0x80000000 else a - sb = b - (1 << 32) if b & 0x80000000 else b - return (sa * sb >> 32) & MASK32 - - -def run(op, a, b, form="vgpr"): - """Translate and run `op v0, , ` on a one-lane pixel shader; return v0 as exported to mrt0.""" - if form == "vgpr": - setup = [f"v_mov_b32 v1, {a:#x}", f"v_mov_b32 v2, {b:#x}"] - srcs = "v1, v2" - elif form == "sgpr": - setup = [f"s_mov_b32 s1, {a:#x}", f"s_mov_b32 s2, {b:#x}"] - srcs = "s1, s2" - else: # inline constant or literal as the second source, v1 as the first - setup = [f"v_mov_b32 v1, {a:#x}"] - srcs = f"v1, {b:#x}" - lines = setup + [f"{op} v0, {srcs}", "exp mrt0 v0, v0, v0, v0 done vm", "s_endpgm"] - return support.mrt0_words(support.translate_lines("ps_mul_hi", lines))[0] - - -def run_alias(op, a, b, mode): - """Write the result over a source: mode "src0" (v1), "src1" (v2) or "square" (v1 = op v1, v1, with b ignored).""" - dst, srcs = {"src0": ("v1", "v1, v2"), "src1": ("v2", "v1, v2"), "square": ("v1", "v1, v1")}[mode] - lines = [f"v_mov_b32 v1, {a:#x}", f"v_mov_b32 v2, {b:#x}", f"{op} {dst}, {srcs}", - f"exp mrt0 {dst}, {dst}, {dst}, {dst} done vm", "s_endpgm"] - return support.mrt0_words(support.translate_lines("ps_mul_hi", lines))[0] - - -def run_mixed(op, vgpr, sgpr, scalar_first): - """One VGPR and one SGPR operand, in either order.""" - srcs = "s4, v2" if scalar_first else "v2, s4" - lines = [f"v_mov_b32 v2, {vgpr:#x}", f"s_mov_b32 s4, {sgpr:#x}", f"{op} v0, {srcs}", - "exp mrt0 v0, v0, v0, v0 done vm", "s_endpgm"] - return support.mrt0_words(support.translate_lines("ps_mul_hi", lines))[0] - - -# (a, b, v_mul_hi_u32 word, v_mul_hi_i32 word), written by hand. -CASES = [ - (0x80000000, 2, 0x00000001, 0xFFFFFFFF), # 2^31 * 2 = 2^32; (-2^31) * 2 = -2^32 - (0x10000, 0x10000, 0x00000001, 0x00000001), # 2^32 - (100, 200, 0x00000000, 0x00000000), - (0xFFFF, 0xFFFF, 0x00000000, 0x00000000), - (0, 0xFFFFFFFF, 0x00000000, 0x00000000), - (0xFFFFFFFF, 1, 0x00000000, 0xFFFFFFFF), # u: 2^32-1 fits; i: -1 * 1 = -1 - (0xFFFFFFFF, 2, 0x00000001, 0xFFFFFFFF), # u: 0x1_FFFFFFFE; i: -1 * 2 = -2 - (0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFE, 0x00000000), # u: 0xFFFFFFFE_00000001; i: (-1)*(-1) = 1 - (3, 4, 0x00000000, 0x00000000), - (10, 0xFFFFFFFB, 0x00000009, 0xFFFFFFFF), # i: 10 * -5 = -50 - (INT32_MIN, 0xFFFFFFFF, 0x7FFFFFFF, 0x00000000), # i: -2^31 * -1 = 2^31 - (INT32_MIN, INT32_MIN, 0x40000000, 0x40000000), # u: 2^62; i: (-2^31)^2 = 2^62 - (INT32_MAX, INT32_MAX, 0x3FFFFFFF, 0x3FFFFFFF), # (2^31-1)^2 = 0x3FFFFFFF_00000001 - (INT32_MIN, INT32_MAX, 0x3FFFFFFF, 0xC0000000), # i: -2^62 + 2^31 = 0xC0000000_80000000 - (0x12345678, 0x9ABCDEF0, 0x0B00EA4E, 0xF8CC93D6), # 0x12345678 * 0x9ABCDEF0 and its signed reading -] - - -class MulHi(unittest.TestCase): - def test_hand_written_table_matches_reference(self): - for a, b, u, i in CASES: - self.assertEqual(ref_u32(a, b), u, (hex(a), hex(b))) - self.assertEqual(ref_i32(a, b), i, (hex(a), hex(b))) - - def test_translated_cases(self): - for a, b, u, i in CASES: - with self.subTest(a=hex(a), b=hex(b)): - self.assertEqual(run("v_mul_hi_u32", a, b), u) - self.assertEqual(run("v_mul_hi_i32", a, b), i) - - def test_sgpr_and_literal_sources(self): - for a, b, u, i in CASES[:8]: - for form in ("sgpr", "literal"): - with self.subTest(a=hex(a), b=hex(b), form=form): - self.assertEqual(run("v_mul_hi_u32", a, b, form), u) - self.assertEqual(run("v_mul_hi_i32", a, b, form), i) - - def test_destination_overlaps_a_source(self): - # The high product differs from the overwritten source in these rows, so returning that source fails them. - for a, b, u, i in CASES: - for mode in ("src0", "src1"): - with self.subTest(a=hex(a), b=hex(b), mode=mode): - self.assertEqual(run_alias("v_mul_hi_u32", a, b, mode), u) - self.assertEqual(run_alias("v_mul_hi_i32", a, b, mode), i) - - def test_in_place_square(self): - # (a, high word of a*a unsigned, signed), by hand: 0x80000000^2 = 2^62, 0xFFFFFFFF^2 = 0xFFFFFFFE_00000001, - # 0x10000^2 = 2^32, 0x7FFFFFFF^2 = 0x3FFFFFFF_00000001, 0x12345678^2 = 0x14B66DC_1DF4D840. - for a, u, i in ((0x80000000, 0x40000000, 0x40000000), (0xFFFFFFFF, 0xFFFFFFFE, 0), - (0x10000, 1, 1), (0x7FFFFFFF, 0x3FFFFFFF, 0x3FFFFFFF), (0x12345678, 0x014B66DC, 0x014B66DC)): - self.assertEqual((ref_u32(a, a), ref_i32(a, a)), (u, i), hex(a)) - with self.subTest(a=hex(a)): - self.assertEqual(run_alias("v_mul_hi_u32", a, a, "square"), u) - self.assertEqual(run_alias("v_mul_hi_i32", a, a, "square"), i) - - def test_mixed_vector_and_scalar_sources(self): - # (vector operand, scalar operand, unsigned word, signed word), by hand. - for v, sc, u, i in ((0x20000, 0x10000, 2, 2), # 2^17 * 2^16 = 2^33 - (0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFE, 0), - (0x80000000, 2, 1, 0xFFFFFFFF), - (0xFFFFFFFB, 10, 9, 0xFFFFFFFF), # -5 * 10 = -50 - (INT32_MAX, INT32_MIN, 0x3FFFFFFF, 0xC0000000)): - self.assertEqual((ref_u32(v, sc), ref_i32(v, sc)), (u, i), (hex(v), hex(sc))) - for scalar_first in (False, True): - with self.subTest(v=hex(v), s=hex(sc), scalar_first=scalar_first): - self.assertEqual(run_mixed("v_mul_hi_u32", v, sc, scalar_first), u) - self.assertEqual(run_mixed("v_mul_hi_i32", v, sc, scalar_first), i) - - def test_random_operands(self): - rng = random.Random(0x6D756C68) - for _ in range(60): - a, b = rng.getrandbits(32), rng.getrandbits(32) - with self.subTest(a=hex(a), b=hex(b)): - self.assertEqual(run("v_mul_hi_u32", a, b), ref_u32(a, b)) - self.assertEqual(run("v_mul_hi_i32", a, b), ref_i32(a, b)) - - def test_signedness_is_not_confused(self): - # -1 * -1: the signed high word is 0, the unsigned one 0xFFFFFFFE. - self.assertEqual(run("v_mul_hi_i32", 0xFFFFFFFF, 0xFFFFFFFF), 0) - self.assertEqual(run("v_mul_hi_u32", 0xFFFFFFFF, 0xFFFFFFFF), 0xFFFFFFFE) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_valu_mul_legacy_denorm.py b/tests/semantic/test_valu_mul_legacy_denorm.py deleted file mode 100644 index 304880ebb..000000000 --- a/tests/semantic/test_valu_mul_legacy_denorm.py +++ /dev/null @@ -1,86 +0,0 @@ -"""Bit-level DX9 legacy multiply under the inferred RDNA2 f32 denorm mode 0. - -Synthetic-only tests: zero operands override infinity/NaN with positive zero, -including an input subnormal flushed to zero. A nonzero product that underflows -flushes to a zero with its sign. The product is flushed before VOP3 omod and -the scaled result is flushed again. -""" - -import os -import sys -import unittest - -# Allow this standalone test to run with python -I, as the other semantic tests do. -sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) - -import support - - -def run_mul(src0, src1, mods=""): - ins = "v_mul_legacy_f32_e64" if mods else "v_mul_legacy_f32" - lines = [ - f"v_mov_b32 v0, {src0:#x}", - f"v_mov_b32 v1, {src1:#x}", - f"{ins} v2, v0, v1{(' ' + mods) if mods else ''}", - "exp mrt0 v2, v2, v2, v2 done vm", - "s_endpgm", - ] - spv = support.translate_lines("ps_mul_legacy_denorm_semantic", lines) - words = support.mrt0_words(spv) - assert len(words) == 4 - return words[0], spv - - -class LegacyMulDenormalTests(unittest.TestCase): - def test_inputs_flush_before_legacy_zero_override(self): - # With mode0, 2^-149 is treated as zero, so the nonzero result 2^-125 - # of an IEEE multiply must not survive. Both signs of a zero input - # give +0 under the legacy DX9 zero-times-anything rule. - for src0, src1 in [ - (0x00000001, 0x4B800000), - (0x80000001, 0x4B800000), - (0x00000001, 0x7F800000), - (0x80000001, 0xFFC00000), - (0x00000000, 0x7F800000), - (0x80000000, 0xFF800000), - ]: - with self.subTest(src0=hex(src0), src1=hex(src1)): - got, _ = run_mul(src0, src1) - self.assertEqual(got, 0) - - def test_nonzero_products_flush_signed_underflow(self): - for src0, src1, expected in [ - (0x00800000, 0x3F000000, 0x00000000), - (0x80800000, 0x3F000000, 0x80000000), - (0x00800000, 0x3F800000, 0x00800000), - (0x80800000, 0x3F800000, 0x80800000), - (0x40000000, 0x40400000, 0x40C00000), - ]: - with self.subTest(src0=hex(src0), src1=hex(src1)): - got, _ = run_mul(src0, src1) - self.assertEqual(got, expected) - - def test_product_flush_precedes_modifiers(self): - for src0, src1, mods, expected in [ - (0x00800000, 0x3F000000, "mul:2", 0x00000000), - (0x80800000, 0x3F000000, "mul:4", 0x00000000), - (0x00800000, 0x3F800000, "div:2", 0x00000000), - (0x80800000, 0x3F800000, "div:2", 0x00000000), - (0x40000000, 0x40400000, "div:2", 0x40400000), - ]: - with self.subTest(src0=hex(src0), src1=hex(src1), mods=mods): - got, _ = run_mul(src0, src1, mods) - self.assertEqual(got, expected) - - def test_emits_explicit_f32_flushes_instead_of_a_driver_mode(self): - _, spv = run_mul(0x00800000, 0x3F000000, "mul:2") - # One check for each input, plus the product and final result. - self.assertGreaterEqual(spv.count("OpFOrdLessThan %bool"), 4) - self.assertIn("OpFMul %float", spv) - self.assertIn("OpSelect %float", spv) - # The software rule does not demand a vendor-specific float control. - self.assertNotIn("DenormFlushToZero 32", spv) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_valu_multi_frexp_bundle.py b/tests/semantic/test_valu_multi_frexp_bundle.py deleted file mode 100644 index 7c8f719e0..000000000 --- a/tests/semantic/test_valu_multi_frexp_bundle.py +++ /dev/null @@ -1,568 +0,0 @@ -"""Semantic reference tests and translator-backed validation for AMD RDNA2 VALU Multi-Precision Float Decomposition Suite. - -Subsystem Feature Bundle 48 covers 6 multi-precision floating-point frexp decomposition instructions (f16, f32, f64): - 1. v_frexp_exp_i16_f16 - Extracts 16-bit integer exponent from half-precision float (S0 = mant * 2^exp, |mant| in [0.5, 1)) - 2. v_frexp_mant_f16 - Extracts 16-bit half-precision mantissa in [0.5, 1) with sign preservation - 3. v_frexp_exp_i32_f32 - Extracts 32-bit signed integer exponent from single-precision float (biased exponent - 126) - 4. v_frexp_mant_f32 - Extracts 32-bit single-precision mantissa in [0.5, 1) with sign preservation - 5. v_frexp_exp_i32_f64 - Extracts 32-bit signed integer exponent from double-precision float (biased exponent - 1022) - 6. v_frexp_mant_f64 - Extracts 64-bit double-precision mantissa in [0.5, 1) with sign preservation - -RDNA2 Floating-Point Decomposition Architecture: - - Supports f16 (IEEE 754 half-precision binary16), f32 (binary32), and f64 (binary64). - - Unbiased exponent and normalized significand extraction. - - Zero, infinity, NaN, and denormal/subnormal edge-case handling adhering to GFX1030+ hardware semantics. - - End-to-end SPIR-V assembly translation through tools/rdna2spirv.py. - -Standard library only: Python 3.9+ compatible, zero game data, zero external dependencies. -""" -from __future__ import annotations - -from dataclasses import dataclass -import enum -import math -import os -import struct -import sys -import unittest - -HERE = os.path.dirname(os.path.abspath(__file__)) -TESTS_DIR = os.path.dirname(HERE) -for p in (HERE, TESTS_DIR): - if p not in sys.path: - sys.path.insert(0, p) - -from support import translate_lines, mrt0_words # noqa: E402 - -MASK16 = 0xFFFF -MASK32 = 0xFFFFFFFF -MASK64 = 0xFFFFFFFFFFFFFFFF - - -# --- Half-precision helpers --- -def h2f(h: int) -> float: - return struct.unpack(" int: - return struct.unpack(" bool: - return (h >> 10) & 0x1F != 31 and (h & 0x7FFF) != 0 - - -def oracle_frexp_exp_i16_f16(h: int) -> int: - """Reference mathematical oracle for v_frexp_exp_i16_f16.""" - if not is_f16_finite_nonzero(h): - return 0 - val = h2f(h) - _, exp = math.frexp(val) - return exp & MASK16 - - -def oracle_frexp_mant_f16(h: int) -> int: - """Reference mathematical oracle for v_frexp_mant_f16.""" - if not is_f16_finite_nonzero(h): - return h & MASK16 - val = h2f(h) - mant, _ = math.frexp(val) - return f2h(mant) - - -# --- Single-precision helpers --- -def f32_to_bits(f: float) -> int: - return struct.unpack(" float: - return struct.unpack(" bool: - e = (b >> 23) & 0xFF - return 0 < e < 255 - - -def oracle_frexp_exp_i32_f32(b: int) -> int: - """Reference mathematical oracle for v_frexp_exp_i32_f32.""" - b &= MASK32 - if not is_f32_normal(b): - return 0 - e = (b >> 23) & 0xFF - return (e - 126) & MASK32 - - -def oracle_frexp_mant_f32(b: int) -> int: - """Reference mathematical oracle for v_frexp_mant_f32.""" - b &= MASK32 - e = (b >> 23) & 0xFF - sgn = b & 0x80000000 - if e == 0: - return sgn - if e == 255: - return b - return sgn | 0x3F000000 | (b & 0x007FFFFF) - - -# --- Double-precision helpers --- -def d2u(x: float) -> int: - return struct.unpack(" float: - return struct.unpack(" bool: - exp_f = (u >> 52) & 0x7FF - frac = u & ((1 << 52) - 1) - return exp_f < 2047 and (exp_f > 0 or frac != 0) - - -def oracle_frexp_exp_i32_f64(u: int) -> int: - """Reference mathematical oracle for v_frexp_exp_i32_f64.""" - u &= MASK64 - if not is_f64_finite_nonzero(u): - return 0 - val = u2d(u) - _, exp = math.frexp(val) - return exp & MASK32 - - -def oracle_frexp_mant_f64(u: int) -> int: - """Reference mathematical oracle for v_frexp_mant_f64.""" - u &= MASK64 - if not is_f64_finite_nonzero(u): - return u - val = u2d(u) - mant, _ = math.frexp(val) - return d2u(mant) - -# ----------------------------------------------------------------------------- -# Opcode 1: v_frexp_exp_i16_f16 -# ----------------------------------------------------------------------------- -class VFrexpExpI16F16OracleTests(unittest.TestCase): - def test_frexp_exp_f16_powers_of_two(self): - # 1.0 (0x3C00) = 0.5 * 2^1 -> exp = 1 - self.assertEqual(oracle_frexp_exp_i16_f16(0x3C00), 1) - # 0.5 (0x3800) = 0.5 * 2^0 -> exp = 0 - self.assertEqual(oracle_frexp_exp_i16_f16(0x3800), 0) - # 2.0 (0x4000) = 0.5 * 2^2 -> exp = 2 - self.assertEqual(oracle_frexp_exp_i16_f16(0x4000), 2) - # -4.0 (0xC400) = -0.5 * 2^3 -> exp = 3 - self.assertEqual(oracle_frexp_exp_i16_f16(0xC400), 3) - - def test_frexp_exp_f16_special_values(self): - # +/-0.0 -> 0 - self.assertEqual(oracle_frexp_exp_i16_f16(0x0000), 0) - self.assertEqual(oracle_frexp_exp_i16_f16(0x8000), 0) - # +/-INF -> 0 - self.assertEqual(oracle_frexp_exp_i16_f16(0x7C00), 0) - self.assertEqual(oracle_frexp_exp_i16_f16(0xFC00), 0) - # NaN -> 0 - self.assertEqual(oracle_frexp_exp_i16_f16(0x7E00), 0) - -class RegKind(enum.Enum): - VGPR = "vgpr" - SGPR = "sgpr" - IMM = "imm" - - -@dataclass(frozen=True) -class Operand: - kind: RegKind - index: int = 0 - raw_val: int = 0 - - -@dataclass(frozen=True) -class ValuInstructionAST: - mnemonic: str - dst: Operand - src0: Operand - src1: Operand | None = None - src2: Operand | None = None - - -class WavefrontSimdState: - def __init__(self, lane_count: int = 32): - self.lane_count = lane_count - self.exec_mask: int = (1 << lane_count) - 1 - self.vgprs = [[0] * 64 for _ in range(lane_count)] - - def set_vgpr(self, lane: int, reg_idx: int, val: int): - self.vgprs[lane][reg_idx] = val & MASK32 - - def get_vgpr(self, lane: int, reg_idx: int) -> int: - return self.vgprs[lane][reg_idx] & MASK32 - -class VFrexpExpI16F16AstInterpreterTests(unittest.TestCase): - def test_frexp_exp_f16_ast_construction(self): - ast = ValuInstructionAST("v_frexp_exp_i16_f16", Operand(RegKind.VGPR, 0), Operand(RegKind.VGPR, 1)) - self.assertEqual(ast.mnemonic, "v_frexp_exp_i16_f16") - self.assertEqual(ast.dst.index, 0) - self.assertEqual(ast.src0.index, 1) - - def test_frexp_exp_f16_scalar_execution(self): - # -1.0 (0xBC00) -> exp = 1 - res = oracle_frexp_exp_i16_f16(0xBC00) - self.assertEqual(res, 1) - -class VFrexpExpI16F16SimdDivergenceTests(unittest.TestCase): - def test_frexp_exp_f16_simd_exec_masking(self): - wave = WavefrontSimdState(lane_count=32) - wave.exec_mask = 0x55555555 # Even lanes - for i in range(32): - wave.set_vgpr(i, 0, 0xDEADBEEF) - if (wave.exec_mask >> i) & 1: - wave.set_vgpr(i, 0, oracle_frexp_exp_i16_f16(0x3C00)) - for i in range(32): - if (0x55555555 >> i) & 1: - self.assertEqual(wave.get_vgpr(i, 0), 1) - else: - self.assertEqual(wave.get_vgpr(i, 0), 0xDEADBEEF) - - def test_frexp_exp_f16_subnormal_normalization(self): - # Subnormal 0x0001 (2^-24) -> exp = -23 (0xFFE9) - self.assertEqual(oracle_frexp_exp_i16_f16(0x0001), 0xFFE9) - -class VFrexpExpI16F16TranslatorTests(unittest.TestCase): - def test_frexp_exp_f16_translation_and_execution(self): - lines = [ - "v_mov_b32 v1, 0x3C00", - "v_frexp_exp_i16_f16 v0, v1", - "exp mrt0 v0, v0, v0, v0 done vm", - "s_endpgm", - ] - spv = translate_lines("ps_frexp_exp_f16_exec", lines) - val = mrt0_words(spv)[0] - self.assertEqual(val, 1) - - def test_frexp_exp_f16_syntax_rejection(self): - with self.assertRaises(Exception): - translate_lines("ps_bad_frexp_exp_f16", ["v_frexp_exp_i16_f16"]) - -# ----------------------------------------------------------------------------- -# Opcode 2: v_frexp_mant_f16 -# ----------------------------------------------------------------------------- -class VFrexpMantF16OracleTests(unittest.TestCase): - def test_frexp_mant_f16_basic(self): - # 1.0 (0x3C00) -> 0.5 (0x3800) - self.assertEqual(oracle_frexp_mant_f16(0x3C00), 0x3800) - # -1.0 (0xBC00) -> -0.5 (0xB800) - self.assertEqual(oracle_frexp_mant_f16(0xBC00), 0xB800) - - def test_frexp_mant_f16_special_values(self): - # +/-0.0 preserved - self.assertEqual(oracle_frexp_mant_f16(0x0000), 0x0000) - self.assertEqual(oracle_frexp_mant_f16(0x8000), 0x8000) - # +/-INF preserved - self.assertEqual(oracle_frexp_mant_f16(0x7C00), 0x7C00) - self.assertEqual(oracle_frexp_mant_f16(0xFC00), 0xFC00) - # NaN preserved - self.assertEqual(oracle_frexp_mant_f16(0x7E00), 0x7E00) - -class VFrexpMantF16AstInterpreterTests(unittest.TestCase): - def test_frexp_mant_f16_ast_construction(self): - ast = ValuInstructionAST("v_frexp_mant_f16", Operand(RegKind.VGPR, 0), Operand(RegKind.VGPR, 1)) - self.assertEqual(ast.mnemonic, "v_frexp_mant_f16") - - def test_frexp_mant_f16_scalar_execution(self): - # 2.0 (0x4000) -> 0.5 (0x3800) - res = oracle_frexp_mant_f16(0x4000) - self.assertEqual(res, 0x3800) - -class VFrexpMantF16SimdDivergenceTests(unittest.TestCase): - def test_frexp_mant_f16_simd_exec_masking(self): - wave = WavefrontSimdState(lane_count=32) - wave.exec_mask = 0x0000FFFF - for i in range(32): - wave.set_vgpr(i, 0, 0x12345678) - if (wave.exec_mask >> i) & 1: - inp = 0x3C00 if (i % 2 == 0) else 0xBC00 - wave.set_vgpr(i, 0, oracle_frexp_mant_f16(inp)) - for i in range(16): - expected = 0x3800 if (i % 2 == 0) else 0xB800 - self.assertEqual(wave.get_vgpr(i, 0), expected) - for i in range(16, 32): - self.assertEqual(wave.get_vgpr(i, 0), 0x12345678) - -class VFrexpMantF16TranslatorTests(unittest.TestCase): - def test_frexp_mant_f16_translation_and_execution(self): - lines = [ - "v_mov_b32 v1, 0x3C00", - "v_frexp_mant_f16 v0, v1", - "exp mrt0 v0, v0, v0, v0 done vm", - "s_endpgm", - ] - spv = translate_lines("ps_frexp_mant_f16_exec", lines) - val = mrt0_words(spv)[0] - self.assertEqual(val, 0x3800) - - def test_frexp_mant_f16_syntax_rejection(self): - with self.assertRaises(Exception): - translate_lines("ps_bad_frexp_mant_f16", ["v_frexp_mant_f16"]) - -# ----------------------------------------------------------------------------- -# Opcode 3: v_frexp_exp_i32_f32 -# ----------------------------------------------------------------------------- -class VFrexpExpI32F32OracleTests(unittest.TestCase): - def test_frexp_exp_f32_powers_of_two(self): - # 1.0f (0x3F800000) -> 1 - self.assertEqual(oracle_frexp_exp_i32_f32(0x3F800000), 1) - # 0.5f (0x3F000000) -> 0 - self.assertEqual(oracle_frexp_exp_i32_f32(0x3F000000), 0) - # 4.0f (0x40800000) -> 3 - self.assertEqual(oracle_frexp_exp_i32_f32(0x40800000), 3) - # -8.0f (0xC1000000) -> 4 - self.assertEqual(oracle_frexp_exp_i32_f32(0xC1000000), 4) - - def test_frexp_exp_f32_special_values(self): - # 0.0f -> 0 - self.assertEqual(oracle_frexp_exp_i32_f32(0), 0) - # INF / NaN -> 0 - self.assertEqual(oracle_frexp_exp_i32_f32(0x7F800000), 0) - self.assertEqual(oracle_frexp_exp_i32_f32(0x7FC00000), 0) - -class VFrexpExpI32F32AstInterpreterTests(unittest.TestCase): - def test_frexp_exp_f32_ast_construction(self): - ast = ValuInstructionAST("v_frexp_exp_i32_f32", Operand(RegKind.VGPR, 0), Operand(RegKind.VGPR, 1)) - self.assertEqual(ast.mnemonic, "v_frexp_exp_i32_f32") - - def test_frexp_exp_f32_scalar_execution(self): - # 16.0f (0x41800000) -> exp = 5 - res = oracle_frexp_exp_i32_f32(0x41800000) - self.assertEqual(res, 5) - -class VFrexpExpI32F32SimdDivergenceTests(unittest.TestCase): - def test_frexp_exp_f32_simd_exec_masking(self): - wave = WavefrontSimdState(lane_count=32) - wave.exec_mask = 0xAAAAAAAA - for i in range(32): - wave.set_vgpr(i, 0, 0x99999999) - if (wave.exec_mask >> i) & 1: - # 2.0^i in f32 - f_val = f32_to_bits(math.pow(2.0, i)) - wave.set_vgpr(i, 0, oracle_frexp_exp_i32_f32(f_val)) - for i in range(32): - if (0xAAAAAAAA >> i) & 1: - self.assertEqual(wave.get_vgpr(i, 0), i + 1) - else: - self.assertEqual(wave.get_vgpr(i, 0), 0x99999999) - -class VFrexpExpI32F32TranslatorTests(unittest.TestCase): - def test_frexp_exp_f32_translation_and_execution(self): - lines = [ - "v_mov_b32 v1, 0x3F800000", - "v_frexp_exp_i32_f32 v0, v1", - "exp mrt0 v0, v0, v0, v0 done vm", - "s_endpgm", - ] - spv = translate_lines("ps_frexp_exp_f32_exec", lines) - val = mrt0_words(spv)[0] - self.assertEqual(val, 1) - - def test_frexp_exp_f32_syntax_rejection(self): - with self.assertRaises(Exception): - translate_lines("ps_bad_frexp_exp_f32", ["v_frexp_exp_i32_f32"]) - -# ----------------------------------------------------------------------------- -# Opcode 4: v_frexp_mant_f32 -# ----------------------------------------------------------------------------- -class VFrexpMantF32OracleTests(unittest.TestCase): - def test_frexp_mant_f32_basic(self): - # 1.0f (0x3F800000) -> 0.5f (0x3F000000) - self.assertEqual(oracle_frexp_mant_f32(0x3F800000), 0x3F000000) - # -1.0f (0xBF800000) -> -0.5f (0xBF000000) - self.assertEqual(oracle_frexp_mant_f32(0xBF800000), 0xBF000000) - - def test_frexp_mant_f32_special_values(self): - # 0.0f -> 0.0f - self.assertEqual(oracle_frexp_mant_f32(0x00000000), 0x00000000) - self.assertEqual(oracle_frexp_mant_f32(0x80000000), 0x80000000) - # INF / NaN preserved - self.assertEqual(oracle_frexp_mant_f32(0x7F800000), 0x7F800000) - self.assertEqual(oracle_frexp_mant_f32(0x7FC00000), 0x7FC00000) - -class VFrexpMantF32AstInterpreterTests(unittest.TestCase): - def test_frexp_mant_f32_ast_construction(self): - ast = ValuInstructionAST("v_frexp_mant_f32", Operand(RegKind.VGPR, 0), Operand(RegKind.VGPR, 1)) - self.assertEqual(ast.mnemonic, "v_frexp_mant_f32") - - def test_frexp_mant_f32_scalar_execution(self): - # 4.0f (0x40800000) -> 0.5f (0x3F000000) - res = oracle_frexp_mant_f32(0x40800000) - self.assertEqual(res, 0x3F000000) - -class VFrexpMantF32SimdDivergenceTests(unittest.TestCase): - def test_frexp_mant_f32_simd_exec_masking(self): - wave = WavefrontSimdState(lane_count=32) - wave.exec_mask = 0xF0F0F0F0 - for i in range(32): - wave.set_vgpr(i, 0, 0x55555555) - if (wave.exec_mask >> i) & 1: - inp = f32_to_bits(1.5 * math.pow(2.0, i)) - wave.set_vgpr(i, 0, oracle_frexp_mant_f32(inp)) - for i in range(32): - if (0xF0F0F0F0 >> i) & 1: - # 1.5 * 2^i = 0.75 * 2^(i+1) -> mantissa is 0.75f (0x3F400000) - self.assertEqual(wave.get_vgpr(i, 0), 0x3F400000) - else: - self.assertEqual(wave.get_vgpr(i, 0), 0x55555555) - -class VFrexpMantF32TranslatorTests(unittest.TestCase): - def test_frexp_mant_f32_translation_and_execution(self): - lines = [ - "v_mov_b32 v1, 0x3F800000", - "v_frexp_mant_f32 v0, v1", - "exp mrt0 v0, v0, v0, v0 done vm", - "s_endpgm", - ] - spv = translate_lines("ps_frexp_mant_f32_exec", lines) - val = mrt0_words(spv)[0] - self.assertEqual(val, 0x3F000000) - - def test_frexp_mant_f32_syntax_rejection(self): - with self.assertRaises(Exception): - translate_lines("ps_bad_frexp_mant_f32", ["v_frexp_mant_f32"]) - -# ----------------------------------------------------------------------------- -# Opcode 5: v_frexp_exp_i32_f64 -# ----------------------------------------------------------------------------- -class VFrexpExpI32F64OracleTests(unittest.TestCase): - def test_frexp_exp_f64_powers_of_two(self): - # 1.0d (0x3FF0000000000000) -> 1 - self.assertEqual(oracle_frexp_exp_i32_f64(0x3FF0000000000000), 1) - # 0.5d (0x3FE0000000000000) -> 0 - self.assertEqual(oracle_frexp_exp_i32_f64(0x3FE0000000000000), 0) - # 2.0d (0x4000000000000000) -> 2 - self.assertEqual(oracle_frexp_exp_i32_f64(0x4000000000000000), 2) - # -4.0d (0xC010000000000000) -> 3 - self.assertEqual(oracle_frexp_exp_i32_f64(0xC010000000000000), 3) - - def test_frexp_exp_f64_special_values(self): - # 0.0d -> 0 - self.assertEqual(oracle_frexp_exp_i32_f64(0), 0) - # INF / NaN -> 0 - self.assertEqual(oracle_frexp_exp_i32_f64(0x7FF0000000000000), 0) - self.assertEqual(oracle_frexp_exp_i32_f64(0x7FF8000000000000), 0) - -class VFrexpExpI32F64AstInterpreterTests(unittest.TestCase): - def test_frexp_exp_f64_ast_construction(self): - ast = ValuInstructionAST("v_frexp_exp_i32_f64", Operand(RegKind.VGPR, 2), Operand(RegKind.VGPR, 0)) - self.assertEqual(ast.mnemonic, "v_frexp_exp_i32_f64") - - def test_frexp_exp_f64_scalar_execution(self): - # 8.0d (0x4020000000000000) -> 4 - res = oracle_frexp_exp_i32_f64(0x4020000000000000) - self.assertEqual(res, 4) - -class VFrexpExpI32F64SimdDivergenceTests(unittest.TestCase): - def test_frexp_exp_f64_simd_exec_masking(self): - wave = WavefrontSimdState(lane_count=32) - wave.exec_mask = 0x00FF00FF - for i in range(32): - wave.set_vgpr(i, 2, 0x77777777) - if (wave.exec_mask >> i) & 1: - val = d2u(math.pow(2.0, i)) - wave.set_vgpr(i, 2, oracle_frexp_exp_i32_f64(val)) - for i in range(32): - if (0x00FF00FF >> i) & 1: - self.assertEqual(wave.get_vgpr(i, 2), i + 1) - else: - self.assertEqual(wave.get_vgpr(i, 2), 0x77777777) - - def test_frexp_exp_f64_subnormal_normalization(self): - # Smallest subnormal 0x0000000000000001 (2^-1074) -> exp = -1073 (0xFFFFFBCF in u32) - self.assertEqual(oracle_frexp_exp_i32_f64(1), 0xFFFFFBCF) - -class VFrexpExpI32F64TranslatorTests(unittest.TestCase): - def test_frexp_exp_f64_translation_and_execution(self): - lines = [ - "v_mov_b32 v0, 0", - "v_mov_b32 v1, 0x3FF00000", - "v_frexp_exp_i32_f64 v2, v[0:1]", - "exp mrt0 v2, v2, v2, v2 done vm", - "s_endpgm", - ] - spv = translate_lines("ps_frexp_exp_f64_exec", lines) - val = mrt0_words(spv)[0] - self.assertEqual(val, 1) - - def test_frexp_exp_f64_syntax_rejection(self): - with self.assertRaises(Exception): - translate_lines("ps_bad_frexp_exp_f64", ["v_frexp_exp_i32_f64 v0, v[0:1] clamp"]) - -# ----------------------------------------------------------------------------- -# Opcode 6: v_frexp_mant_f64 -# ----------------------------------------------------------------------------- -class VFrexpMantF64OracleTests(unittest.TestCase): - def test_frexp_mant_f64_basic(self): - # 1.0d (0x3FF0000000000000) -> 0.5d (0x3FE0000000000000) - self.assertEqual(oracle_frexp_mant_f64(0x3FF0000000000000), 0x3FE0000000000000) - # -1.0d (0xBFF0000000000000) -> -0.5d (0xBFE0000000000000) - self.assertEqual(oracle_frexp_mant_f64(0xBFF0000000000000), 0xBFE0000000000000) - - def test_frexp_mant_f64_special_values(self): - # 0.0d -> 0.0d - self.assertEqual(oracle_frexp_mant_f64(0), 0) - # INF / NaN preserved - self.assertEqual(oracle_frexp_mant_f64(0x7FF0000000000000), 0x7FF0000000000000) - self.assertEqual(oracle_frexp_mant_f64(0x7FF8000000000000), 0x7FF8000000000000) - -class VFrexpMantF64AstInterpreterTests(unittest.TestCase): - def test_frexp_mant_f64_ast_construction(self): - ast = ValuInstructionAST("v_frexp_mant_f64", Operand(RegKind.VGPR, 2), Operand(RegKind.VGPR, 0)) - self.assertEqual(ast.mnemonic, "v_frexp_mant_f64") - - def test_frexp_mant_f64_scalar_execution(self): - # 2.0d (0x4000000000000000) -> 0.5d (0x3FE0000000000000) - res = oracle_frexp_mant_f64(0x4000000000000000) - self.assertEqual(res, 0x3FE0000000000000) - -class VFrexpMantF64SimdDivergenceTests(unittest.TestCase): - def test_frexp_mant_f64_simd_exec_masking(self): - wave = WavefrontSimdState(lane_count=32) - wave.exec_mask = 0x33333333 - for i in range(32): - wave.set_vgpr(i, 2, 0xAAAAAAAA) - wave.set_vgpr(i, 3, 0xBBBBBBBB) - if (wave.exec_mask >> i) & 1: - # 3.0 * 2^i - d_val = d2u(3.0 * math.pow(2.0, i)) - mant = oracle_frexp_mant_f64(d_val) - wave.set_vgpr(i, 2, mant & MASK32) - wave.set_vgpr(i, 3, (mant >> 32) & MASK32) - # 3.0 = 0.75 * 4 -> mantissa is 0.75d (0x3FE8000000000000) - expected_lo = 0x00000000 - expected_hi = 0x3FE80000 - for i in range(32): - if (0x33333333 >> i) & 1: - self.assertEqual(wave.get_vgpr(i, 2), expected_lo) - self.assertEqual(wave.get_vgpr(i, 3), expected_hi) - else: - self.assertEqual(wave.get_vgpr(i, 2), 0xAAAAAAAA) - self.assertEqual(wave.get_vgpr(i, 3), 0xBBBBBBBB) - -class VFrexpMantF64TranslatorTests(unittest.TestCase): - def test_frexp_mant_f64_translation_and_execution(self): - lines = [ - "v_mov_b32 v0, 0", - "v_mov_b32 v1, 0x3FF00000", - "v_frexp_mant_f64 v[2:3], v[0:1]", - "exp mrt0 v2, v3, v2, v3 done vm", - "s_endpgm", - ] - spv = translate_lines("ps_frexp_mant_f64_exec", lines) - res = mrt0_words(spv) - self.assertEqual(res[0], 0x00000000) - self.assertEqual(res[1], 0x3FE00000) - - def test_frexp_mant_f64_syntax_rejection(self): - with self.assertRaises(Exception): - translate_lines("ps_bad_frexp_mant_f64", ["v_frexp_mant_f64 v0, v[0:1]"]) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_valu_pack_b32_f16.py b/tests/semantic/test_valu_pack_b32_f16.py deleted file mode 100644 index 3f128b75a..000000000 --- a/tests/semantic/test_valu_pack_b32_f16.py +++ /dev/null @@ -1,159 +0,0 @@ -"""v_pack_b32_f16 (RDNA2 VOP3): D = (S1.half << 16) | S0.half, where op_sel[0] / op_sel[1] pick the low (0) or high (1) -16-bit half of S0 / S1. All 32 bits of the destination are written (nothing of the old value survives). The halves are -moved as bits: a VOP3 abs clears bit 15 of the half, neg flips it, abs first (docs/design.md, `v_pack_b32_f16` source -modifiers; measured on gfx1036 with IEEE mode 0, where a signalling NaN keeps its payload). - -Every case is translated by tools/rdna2spirv.py and executed with tests/semantic/spirv_mini_interp.py; the expected -word is written down by hand next to each case, then compared against a few lines of plain Python, with SGPR / literal / -inline-constant sources, op_sel and seeded random operands. Standard library only: no GPU, no LLVM, no game data. -""" -import os -import random -import sys -import unittest - -sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) -from f16_unary_cases import run as _run # noqa: E402 - -LINE = "v_pack_b32_f16 v0, v1, v2" - - -def run(line, seeds): - """The destination starts as 0xdeadbeef; seeds are whole 32-bit words (no filler in the high half).""" - return _run(line, seeds, hi=0) - - -def half(w, sel, ab=False, ng=False): - h = (w >> (16 * sel)) & 0xFFFF - if ab: - h &= 0x7FFF - if ng: - h ^= 0x8000 - return h - - -def ref(s0, s1, sel=(0, 0), mods=((False, False), (False, False))): - return half(s0, sel[0], *mods[0]) | (half(s1, sel[1], *mods[1]) << 16) - - -# (src0 dword, src1 dword, D with op_sel [0,0]), by hand: D = (S1[15:0] << 16) | S0[15:0] -CASES = [ - (0x00003C00, 0x00004000, 0x40003C00), # 1.0, 2.0 - (0xAAAA3C00, 0xBBBB4000, 0x40003C00), # the high halves of the sources are ignored - (0x00000000, 0x00008000, 0x80000000), # +0, -0 - (0x00008000, 0x00000000, 0x00008000), - (0x00007C00, 0x0000FC00, 0xFC007C00), # +inf, -inf - (0x00007E00, 0x00007E01, 0x7E017E00), # quiet NaNs keep their bits - (0x00007C01, 0x0000FC01, 0xFC017C01), # signalling NaNs are moved, not quieted (IEEE mode 0) - (0x00000001, 0x000003FF, 0x03FF0001), # subnormals - (0x00007BFF, 0x0000FBFF, 0xFBFF7BFF), # +-65504 - (0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF), - (0x12345678, 0x9ABCDEF0, 0xDEF05678), -] - -SPECIAL = [0x0000, 0x8000, 0x3C00, 0xBC00, 0x7C00, 0xFC00, 0x7E00, 0xFE00, 0x7C01, 0xFC01, 0x7DFF, 0x0001, 0x03FF, - 0x0400, 0x7BFF, 0xFBFF, 0xFFFF, 0x5A5A] -# Operand words whose halves differ, so op_sel and the modifiers show: low 1.5 / high -3.0, low sNaN / high -0, ... -MIXED = [0xC2003E00, 0x80007C01, 0x7E00FC01, 0x03FF8001, 0x3C000000] - - -class PackB32F16(unittest.TestCase): - def test_hand_written_table_matches_reference(self): - for a, b, want in CASES: - self.assertEqual(ref(a, b), want, (hex(a), hex(b))) - - def test_vgpr_pair_writes_the_whole_destination(self): - for a, b, want in CASES: - with self.subTest(a=hex(a), b=hex(b)): - self.assertEqual(run(LINE, {"v1": a, "v2": b}), want) # OLD = 0xdeadbeef leaves no trace - - def test_sgpr_and_literal_sources(self): - for a, b, want in CASES: - forms = [ - ("sgpr sgpr", "v_pack_b32_f16 v0, s1, s2", {"s1": a, "s2": b}), - ("sgpr vgpr", "v_pack_b32_f16 v0, s1, v2", {"s1": a, "v2": b}), - ("vgpr sgpr", "v_pack_b32_f16 v0, v1, s2", {"v1": a, "s2": b}), - ("literal src0", f"v_pack_b32_f16 v0, {a:#x}, v2", {"v2": b}), - ("literal src1", f"v_pack_b32_f16 v0, v1, {b:#x}", {"v1": a}), - ] - for form, line, seeds in forms: - with self.subTest(a=hex(a), b=hex(b), form=form): - self.assertEqual(run(line, seeds), want) - - def test_inline_constants_are_f16_in_the_low_half_over_a_zero_high_half(self): - # docs/design.md "f16 inline constants": 1.0 is 0x3c00, not the f32 pattern; its high half reads +0.0 - for text, c in (("1.0", 0x3C00), ("-1.0", 0xBC00), ("0.5", 0x3800), ("2.0", 0x4000), ("-4.0", 0xC400), - ("0", 0), ("1", 1), ("64", 64)): - with self.subTest(const=text): - self.assertEqual(run(f"v_pack_b32_f16 v0, {text}, v2", {"v2": 0x4400}), (0x4400 << 16) | c) - self.assertEqual(run(f"v_pack_b32_f16 v0, v1, {text}", {"v1": 0x4400}), (c << 16) | 0x4400) - self.assertEqual(run("v_pack_b32_f16 v0, 1.0, 2.0", {}), 0x40003C00) - - def test_op_sel_selects_each_source_half(self): - for a in MIXED: - for b in MIXED: - for s0 in (0, 1): - for s1 in (0, 1): - with self.subTest(a=hex(a), b=hex(b), op_sel=(s0, s1)): - got = run(f"v_pack_b32_f16 v0, v1, v2 op_sel:[{s0},{s1},0]", {"v1": a, "v2": b}) - self.assertEqual(got, ref(a, b, (s0, s1))) - - def test_op_sel_by_hand(self): - a, b = (0xC200 << 16) | 0x3E00, (0x8000 << 16) | 0x7C01 # a: 1.5 | -3.0, b: sNaN | -0 - for sel, want in (((0, 0), 0x7C013E00), ((1, 0), 0x7C01C200), ((0, 1), 0x80003E00), ((1, 1), 0x8000C200)): - with self.subTest(op_sel=sel): - self.assertEqual(run(f"v_pack_b32_f16 v0, v1, v2 op_sel:[{sel[0]},{sel[1]},0]", {"v1": a, "v2": b}), want) - - def test_source_modifiers_act_on_the_selected_half_as_bit_moves(self): - # a = low 1.5 (0x3e00) / high -3.0 (0xc200), b = low sNaN (0x7c01) / high -0 (0x8000); D by hand - a, b = 0xC2003E00, 0x80007C01 - cases = ( - ("-v1, v2", (0, 0), 0x7C01BE00), ("|v1|, v2", (0, 0), 0x7C013E00), ("-|v1|, v2", (0, 0), 0x7C01BE00), - ("v1, -v2", (0, 0), 0xFC013E00), ("v1, |v2|", (0, 0), 0x7C013E00), - ("|v1|, |v2|", (1, 1), 0x00004200), # |-3.0| = 0x4200 in the low half, |-0| = +0 in the high half - ("-v1, -v2", (1, 1), 0x0000_4200), # -(-3.0) = 0x4200, -(-0) = +0 - ("-v1, -v2", (0, 1), 0x0000000 | 0xBE00), # -(1.5) = 0xbe00, -(-0) = +0 - ("-|v1|, -|v2|", (1, 0), 0xFC01C200), # bit 15 set on both: 0xc200 and 0xfc01 - ) - for ops, sel, want in cases: - with self.subTest(ops=ops, op_sel=sel): - got = run(f"v_pack_b32_f16 v0, {ops} op_sel:[{sel[0]},{sel[1]},0]", {"v1": a, "v2": b}) - self.assertEqual(got, want) - - def test_modifier_grid_against_reference(self): - flags = [(False, False), (True, False), (False, True), (True, True)] - for w0 in (0x7C01FC01, 0xC2003E00, 0x03FF8001): - for w1 in (0x80007E00, 0x00007C01): - for m0 in flags: - for m1 in flags: - for sel in ((0, 0), (1, 1), (1, 0)): - ops = [] - for r, (ab, ng) in (("v1", m0), ("v2", m1)): - ops.append(("-" if ng else "") + (f"|{r}|" if ab else r)) - with self.subTest(w0=hex(w0), w1=hex(w1), ops=ops, op_sel=sel): - got = run(f"v_pack_b32_f16 v0, {ops[0]}, {ops[1]} op_sel:[{sel[0]},{sel[1]},0]", - {"v1": w0, "v2": w1}) - self.assertEqual(got, ref(w0, w1, sel, (m0, m1))) - - def test_same_register_twice_and_destination_aliasing_a_source(self): - self.assertEqual(run("v_pack_b32_f16 v0, v1, v1", {"v1": 0xC2003E00}), 0x3E003E00) - self.assertEqual(run("v_pack_b32_f16 v0, v1, v1 op_sel:[1,0,0]", {"v1": 0xC2003E00}), 0x3E00C200) - # v0 = (-3.0 | 1.5) read and written by the same instruction: the halves swap - self.assertEqual(run("v_pack_b32_f16 v0, v0, v0 op_sel:[1,0,0]", {"v0": 0xC2003E00}), 0x3E00C200) - - def test_random_operands(self): - rng = random.Random(0x9AC4B32) - pool = SPECIAL + [rng.getrandbits(16) for _ in range(30)] - for _ in range(120): - a = (rng.choice(pool) << 16 | rng.choice(pool)) if rng.random() < 0.5 else rng.getrandbits(32) - b = (rng.choice(pool) << 16 | rng.choice(pool)) if rng.random() < 0.5 else rng.getrandbits(32) - sel = (rng.getrandbits(1), rng.getrandbits(1)) - m = ((rng.getrandbits(1) == 1, rng.getrandbits(1) == 1), (rng.getrandbits(1) == 1, rng.getrandbits(1) == 1)) - ops = [("-" if ng else "") + (f"|{r}|" if ab else r) for r, (ab, ng) in (("v1", m[0]), ("v2", m[1]))] - with self.subTest(a=hex(a), b=hex(b), sel=sel, ops=ops): - got = run(f"v_pack_b32_f16 v0, {ops[0]}, {ops[1]} op_sel:[{sel[0]},{sel[1]},0]", {"v1": a, "v2": b}) - self.assertEqual(got, ref(a, b, sel, m)) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_valu_perm_b32.py b/tests/semantic/test_valu_perm_b32.py deleted file mode 100644 index 6a5a13207..000000000 --- a/tests/semantic/test_valu_perm_b32.py +++ /dev/null @@ -1,123 +0,0 @@ -"""v_perm_b32 (RDNA2 VOP3): result byte i is picked by selector byte i from the 8 bytes {S0, S1} (S1 is the low half). - - 0..3 byte 0..3 of S1 4..7 byte 0..3 of S0 - 8..11 0xFF or 0x00 from the sign bit of S1[15], S1[31], S0[15], S0[31] (bits 15, 31, 47, 63 of {S0, S1}) - 12 0x00 >=13 0xFF - -Each case is translated by tools/rdna2spirv.py and executed with tests/semantic/spirv_mini_interp.py; the expected -words are written by hand. (An earlier copy of this file checked a private model that picked other sign bits for -selectors 8..11 than the ISA and the translator do.) Standard library only: no GPU, no LLVM, no game data. -""" -import os -import random -import sys -import unittest - -HERE = os.path.dirname(os.path.abspath(__file__)) -sys.dont_write_bytecode = True -sys.path.insert(0, HERE) - -import support # noqa: E402 - -MASK32 = 0xFFFFFFFF - - -def sel(b0, b1, b2, b3): - return b0 | (b1 << 8) | (b2 << 16) | (b3 << 24) - - -def ref_perm(s0, s1, selector): - """Plain-Python reference of the table in the module docstring.""" - pool = [(s1 >> (8 * i)) & 0xFF for i in range(4)] + [(s0 >> (8 * i)) & 0xFF for i in range(4)] - out = 0 - for i in range(4): - c = (selector >> (8 * i)) & 0xFF - if c < 8: - v = pool[c] - elif c < 12: - w, b = [(s1, 15), (s1, 31), (s0, 15), (s0, 31)][c - 8] - v = 0xFF if (w >> b) & 1 else 0 - else: - v = 0 if c == 12 else 0xFF - out |= v << (8 * i) - return out - - -def run(s0, s1, selector, form="vgpr", dst=None): - """dst: None for a fresh v0, or 0/1/2 to write the result over S0/S1/the selector and export that register.""" - if dst is not None: - lines = [f"v_mov_b32 v1, {s0:#x}", f"v_mov_b32 v2, {s1:#x}", f"v_mov_b32 v3, {selector:#x}", - f"v_perm_b32 v{dst + 1}, v1, v2, v3", f"exp mrt0 v{dst + 1}, v{dst + 1}, v{dst + 1}, v{dst + 1} done vm", - "s_endpgm"] - return support.mrt0_words(support.translate_lines("ps_perm", lines))[0] - if form == "vgpr": - setup = [f"v_mov_b32 v1, {s0:#x}", f"v_mov_b32 v2, {s1:#x}", f"v_mov_b32 v3, {selector:#x}"] - srcs = "v1, v2, v3" - else: - setup = [f"s_mov_b32 s1, {s0:#x}", f"s_mov_b32 s2, {s1:#x}", f"s_mov_b32 s3, {selector:#x}"] - srcs = "s1, s2, s3" - lines = setup + [f"v_perm_b32 v0, {srcs}", "exp mrt0 v0, v0, v0, v0 done vm", "s_endpgm"] - return support.mrt0_words(support.translate_lines("ps_perm", lines))[0] - - -S0, S1 = 0xAABBCCDD, 0x11223344 - -# (name, S0, S1, selector, expected word), written by hand. -CASES = [ - ("identity S1", S0, S1, sel(0, 1, 2, 3), 0x11223344), - ("identity S0", S0, S1, sel(4, 5, 6, 7), 0xAABBCCDD), - ("interleave", S0, S1, sel(0, 4, 1, 5), 0xCC33DD44), - ("bswap S1", 0x9ABCDEF0, 0x12345678, sel(3, 2, 1, 0), 0x78563412), - ("bswap S0", 0x9ABCDEF0, 0x12345678, sel(7, 6, 5, 4), 0xF0DEBC9A), - ("broadcast S1 byte 0", 0, 0x01020304, sel(0, 0, 0, 0), 0x04040404), - ("broadcast S0 byte 3", 0x88776655, 0, sel(7, 7, 7, 7), 0x88888888), - ("zero fill", 0xFFFFFFFF, 0xFFFFFFFF, sel(12, 12, 12, 12), 0x00000000), - ("zero mixed", S0, S1, sel(0, 12, 4, 12), 0x00DD0044), - ("ones fill 13..255", 0, 0, sel(13, 14, 15, 255), 0xFFFFFFFF), - ("ones mixed", 0x12345678, 0x9ABCDEF0, sel(0, 13, 4, 255), 0xFF78FFF0), - # 8: S1 bit 15, 9: S1 bit 31, 10: S0 bit 15, 11: S0 bit 31 - ("sel 8 set", 0, 0x00008000, sel(8, 12, 12, 12), 0x000000FF), - ("sel 8 clear (S1 bit 31 does not count)", 0, 0x80000000, sel(8, 12, 12, 12), 0x00000000), - ("sel 9 set", 0, 0x80000000, sel(12, 9, 12, 12), 0x0000FF00), - ("sel 9 clear", 0, 0x7FFFFFFF, sel(12, 9, 12, 12), 0x00000000), - ("sel 10 set", 0x00008000, 0, sel(12, 12, 10, 12), 0x00FF0000), - ("sel 10 clear (S0 bit 31 does not count)", 0x80000000, 0, sel(12, 12, 10, 12), 0x00000000), - ("sel 11 set", 0x80000000, 0, sel(12, 12, 12, 11), 0xFF000000), - ("sel 11 clear (S1 bit 7 does not count)", 0, 0x00000080, sel(12, 12, 12, 11), 0x00000000), - ("all four sign bits set", 0x80008000, 0x80008000, sel(8, 9, 10, 11), 0xFFFFFFFF), - ("selector bytes use all 8 bits", S0, S1, sel(0x10, 0x7F, 0x80, 0xFF), 0xFFFFFFFF), -] - - -class PermB32(unittest.TestCase): - def test_hand_written_table_matches_reference(self): - for name, s0, s1, selector, want in CASES: - self.assertEqual(ref_perm(s0, s1, selector), want, name) - - def test_translated_cases(self): - for name, s0, s1, selector, want in CASES: - with self.subTest(name): - self.assertEqual(run(s0, s1, selector), want) - - def test_sgpr_sources(self): - for name, s0, s1, selector, want in CASES[:8]: - with self.subTest(name): - self.assertEqual(run(s0, s1, selector, "sgpr"), want) - - def test_destination_overlaps_each_source(self): - # The destination is S0, S1 or the selector: every source must be read before the destination is written. - for name, s0, s1, selector, want in CASES: - for dst, what in ((0, "S0"), (1, "S1"), (2, "selector")): - with self.subTest(name, dst=what): - self.assertEqual(run(s0, s1, selector, dst=dst), want) - - def test_random_operands(self): - rng = random.Random(0x7065726D) - for _ in range(60): - s0, s1, selector = (rng.getrandbits(32) for _ in range(3)) - with self.subTest(s0=hex(s0), s1=hex(s1), selector=hex(selector)): - self.assertEqual(run(s0, s1, selector), ref_perm(s0, s1, selector)) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_valu_permlane16.py b/tests/semantic/test_valu_permlane16.py deleted file mode 100644 index 413635ce7..000000000 --- a/tests/semantic/test_valu_permlane16.py +++ /dev/null @@ -1,834 +0,0 @@ -"""Semantic value and translation tests for RDNA2 cross-lane permutes: - v_permlane16_b32 D = vS[(l & ~15) | sel[l & 15]] - v_permlanex16_b32 D = vS[((l & ~15) ^ 16) | sel[l & 15]] - -where the 4-bit lane selector nibbles `sel[0..7]` come from `src1` (bits `[4*k+3 : 4*k]`) and -`sel[8..15]` come from `src2` (bits `[4*(k-8)+3 : 4*(k-8)]`), applied independently inside each -32-lane row (`[0..15]` and `[16..31]`, and in wave64 `[32..47]` and `[48..63]`). Only lanes active -in `EXEC` write `vD`; inactive destination lanes preserve their prior `vD`. - -Executed end-to-end through `tools/rdna2spirv.py` and `tests/semantic/spirv_mini_interp.py` -(`run_workgroup`) across 32 lanes (wave32) and 64 lanes (wave64 on both one 64-wide subgroup and -two 32-wide subgroups), as well as partial waves (20 and 40 lanes), and checked against -hand-computed constants and an independent plain-Python RDNA2 ISA reference model. Standard library -only; zero game data; hand-written RDNA2 disassembly listings only. - -Documented findings (observed in `tools/rdna2spirv.py`; no shared files modified): - 1. `op_sel:[fi, bound_ctrl]` and inactive source lanes (`tools/rdna2spirv.py` lines 4608-4632): - In RDNA2 ISA (measured on RDNA2 gfx1036 and RDNA3.5 gfx1150; see `docs/shader_validation.md` - and `tools/crosslane_fuzz.py`), when a source lane is inactive in `EXEC` (`EXEC[src] == 0`): - - `fi=1` (`op_sel:[1,0]`, `op_sel:[1,1]`): reads the inactive source lane's pre-existing `vS`. - - `fi=0, bound_ctrl=0` (`op_sel:[0,0]` or omitted): keeps the destination lane's prior `vD`. - - `fi=0, bound_ctrl=1` (`op_sel:[0,1]`): writes `0` to the destination lane. - `tools/rdna2spirv.py` lines 4608-4632 do not inspect `mods` (`op_sel:[fi, bound_ctrl]`) and emit - `self.g_shuffle(r, v, src)` unconditionally without checking the source lane's `%active` bit. - Therefore: - - When all accessed source lanes are active in `EXEC`, all four `op_sel` modes (`[0,0]`, - `[1,0]`, `[0,1]`, `[1,1]`) and omitted `op_sel` match the RDNA2 ISA. - - When a source lane is inactive in `EXEC` and `fi=1` (`op_sel:[1,0]`, `op_sel:[1,1]`), the - translation matches the RDNA2 ISA (reading the inactive source lane's pre-existing `vS`). - - When a source lane is inactive in `EXEC` and `fi=0` (`op_sel:[0,0]`/omitted, - `op_sel:[0,1]`), the translator currently reads `vS[src]` instead of keeping `vD` or - writing `0`. Those inactive-source `fi=0` cases are tested in the plain-Python ISA - reference tests (`OracleTests`) and excluded from passing end-to-end assertions rather - than relaxing expected values; structural SPIR-V translation is verified in - `EmulationAndFindingTests`. - 2. `--wave64-emulate` (`tools/rdna2spirv.py` lines 2671-2810, 2890-2895, 4608-4632): - With `WAVE64_EMULATE = True`, wave64 compute/mesh shaders lower `g_shuffle` and `sub_lane` - through `%x_buf` Workgroup-memory exchanges, `OpControlBarrier`, and a round loop (`OpLoopMerge` - with a backward branch). `tests/semantic/spirv_mini_interp.py` rejects `Workgroup` barriers and - non-forward branches (`UnsupportedConstruct`), so `--wave64-emulate` is covered by translation - and structural SPIR-V invariants here (and rejected cleanly by `run_workgroup`). - 3. Wave64 native on two 32-wide subgroups (`subgroup_size = 32`): - Because `v_permlane16_b32` and `v_permlanex16_b32` never cross the 32-lane row boundary - (`0..31` vs `32..63`), both instructions stay exact across all 64 lanes even on two 32-wide - subgroups without `--wave64-emulate`. -""" -import gc -import os -import re -import struct -import sys -import tempfile -import unittest -import warnings - -HERE = os.path.dirname(os.path.abspath(__file__)) -ROOT = os.path.dirname(os.path.dirname(HERE)) -TOOLS_DIR = os.environ.get("LEONIDA_TOOLS_DIR") or os.path.join(ROOT, "tools") - -sys.dont_write_bytecode = True -if TOOLS_DIR not in sys.path: - sys.path.insert(0, TOOLS_DIR) -if HERE not in sys.path: - sys.path.insert(0, HERE) - -import rdna2spirv # noqa: E402 -import spirv_mini_interp as si # noqa: E402 - -MASK32 = 0xFFFFFFFF -ALL32 = 0xFFFFFFFF -ALL64 = 0xFFFFFFFFFFFFFFFF -OLD_SENTINEL = 0xCAFE0000 -HEAP_FILL = 0xEEEEEEEE -# V# in s[0:3]: base 0, stride 0, num_records 0x10000 bytes (OOB_SELECT = 3). -VSHARP = [0, 0, 0x10000, 0x31016FAC] -INPUT_BASE = 0x8000 - -ID_S1 = 0x76543210 -ID_S2 = 0xFEDCBA98 -REV8_S1 = 0x01234567 -REV8_S2 = 0x89ABCDEF -REV16_S1 = 0x89ABCDEF -REV16_S2 = 0x01234567 -PAIR_SWAP_S1 = 0x10325476 -PAIR_SWAP_S2 = 0x98BADCFE -ASYM_S1 = 0x3A0F5C91 -ASYM_S2 = 0xE27B48D6 - - -def ref_permlane(x16: bool, src_vals: list[int], dst_old: list[int], s1: int, s2: int, - exec_mask: int, fi: int = 0, bound_ctrl: int = 0) -> list[int]: - """Independent RDNA2 ISA reference model for v_permlane16_b32 / v_permlanex16_b32.""" - lanes = len(src_vals) - assert len(dst_old) == lanes and lanes in (32, 64) - out = [] - for lane in range(lanes): - if not ((exec_mask >> lane) & 1): - out.append(dst_old[lane] & MASK32) - continue - within = lane & 15 - sel_word = s2 if within >= 8 else s1 - nib = (sel_word >> (4 * (lane & 7))) & 0xF - half = lane & ~15 - row = (half ^ 16) if x16 else half - src_lane = row | nib - if ((exec_mask >> src_lane) & 1) or fi: - out.append(src_vals[src_lane] & MASK32) - elif bound_ctrl: - out.append(0) - else: - out.append(dst_old[lane] & MASK32) - return out - - -class _Heap(dict): - def get(self, key, default=None): - return super().get(key, HEAP_FILL) - - -_TMP_DIR = None -_DISASM_DIR = None -_FSSM_DIR = None - - -def _make_fssm(threads: int, rsrc2: int = 0x8088) -> bytes: - header = bytearray(0x148) - struct.pack_into("<4I", header, 0x138, rsrc2, threads, 1, 1) - return bytes(header) - - -def setUpModule(): - global _TMP_DIR, _DISASM_DIR, _FSSM_DIR - _TMP_DIR = tempfile.TemporaryDirectory() - _DISASM_DIR = os.path.join(_TMP_DIR.name, "disasm") - _FSSM_DIR = os.path.join(_TMP_DIR.name, "fssm") - os.mkdir(_DISASM_DIR) - os.mkdir(_FSSM_DIR) - - -def tearDownModule(): - global _TMP_DIR, _DISASM_DIR, _FSSM_DIR - if _TMP_DIR is not None: - gc.collect() - _TMP_DIR.cleanup() - _TMP_DIR = None - _DISASM_DIR = None - _FSSM_DIR = None - - -def translate_cs(name: str, lines: list[str], threads: int, emulate: bool = False) -> tuple[str, object]: - assert name.startswith("cs_"), f"compute shader name must start with cs_: {name!r}" - if _TMP_DIR is None: - setUpModule() - with open(os.path.join(_FSSM_DIR, name + ".fssm"), "wb") as f: - f.write(_make_fssm(threads)) - src_path = os.path.join(_DISASM_DIR, name + ".s") - asm = f"; {name}\n" + "".join(f"\t{ln}\n" for ln in lines) + "\ts_endpgm\n" - with open(src_path, "w", encoding="utf-8", newline="") as f: - f.write(asm) - old_emu = rdna2spirv.WAVE64_EMULATE - rdna2spirv.WAVE64_EMULATE = emulate - try: - with warnings.catch_warnings(): - warnings.simplefilter("ignore", ResourceWarning) - spv = rdna2spirv.translate(src_path) - gen = rdna2spirv.translate.last_gen - gc.collect() - finally: - rdna2spirv.WAVE64_EMULATE = old_emu - return spv, gen - - -def run_cs(name: str, lines: list[str], threads: int, subgroup_size: int, - init_inputs: list[int] | None = None, out_slots: int = 1) -> list[int]: - """Translate and run a compute shader; return `threads * out_slots` 32-bit output words.""" - spv, _ = translate_cs(name, lines, threads, emulate=False) - mem = _Heap() - if init_inputs is not None: - for i, val in enumerate(init_inputs): - mem[INPUT_BASE + 4 * i] = val & MASK32 - si.run_workgroup( - spv, threads, subgroup_size, - inputs_for=lambda i: {"%wg_id": (0, 0, 0), "%local_id": (i, 0, 0), "%sg_lane": i % subgroup_size}, - push_constants=VSHARP + [0] * 28, - memory=mem, - ) - out_bytes = 4 * threads * out_slots - stray = sorted(a for a in mem if a < INPUT_BASE and (a % 4 != 0 or a >= out_bytes)) - if stray: - raise AssertionError(f"{name}: unexpected stores outside out[0..{threads * out_slots - 1}]: {stray}") - return [mem.get(4 * k) for k in range(threads * out_slots)] - - -def exec_mask_lines(mask: int, wave: int) -> list[str]: - lines = [f"s_mov_b32 exec_lo, {mask & MASK32:#x}"] - if wave == 64: - lines.append(f"s_mov_b32 exec_hi, {(mask >> 32) & MASK32:#x}") - return lines - - -def restore_exec_lines(wave: int) -> list[str]: - return ["s_mov_b64 exec, -1"] if wave == 64 else ["s_mov_b32 exec_lo, -1"] - - -def store_slots_lines(regs: list[str], threads: int) -> list[str]: - """Emit buffer_store_dword for each VGPR in `regs` at `4 * (slot * threads + v0)`.""" - lines = ["v_lshlrev_b32_e32 v21, 2, v0"] - for slot, reg in enumerate(regs): - if slot == 0: - lines.append(f"buffer_store_dword {reg}, v21, s[0:3], 0 offen") - else: - lines.append(f"buffer_store_dword {reg}, v21, s[0:3], 0 offen offset:{4 * slot * threads}") - return lines - - -class OracleTests(unittest.TestCase): - """Cross-check hand-worked constants and ISA semantics against ref_permlane.""" - - def test_hand_worked_identity_and_half_swap(self): - vals32 = [100 + l for l in range(32)] - old32 = [OLD_SENTINEL | l for l in range(32)] - # v_permlane16_b32 identity leaves all 32 lanes unchanged. - self.assertEqual(ref_permlane(False, vals32, old32, ID_S1, ID_S2, ALL32), vals32) - # v_permlanex16_b32 swaps [0..15] and [16..31]. - self.assertEqual( - ref_permlane(True, vals32, old32, ID_S1, ID_S2, ALL32), - [100 + (l ^ 16) for l in range(32)], - ) - - # Wave64 swaps within each 32-lane row: [0..15]<->[16..31] and [32..47]<->[48..63]. - vals64 = [500 + l for l in range(64)] - old64 = [OLD_SENTINEL | l for l in range(64)] - got64 = ref_permlane(True, vals64, old64, ID_S1, ID_S2, ALL64) - self.assertEqual((got64[0], got64[15], got64[16], got64[31]), (516, 531, 500, 515)) - self.assertEqual((got64[32], got64[47], got64[48], got64[63]), (548, 563, 532, 547)) - - def test_hand_worked_nibble_patterns_and_exec_opsel_rules(self): - vals32 = [1000 + l for l in range(32)] - old32 = [OLD_SENTINEL | l for l in range(32)] - - # Broadcast 0 from s1 (lanes 0..7) and 15 from s2 (lanes 8..15). - got_bcast = ref_permlane(False, vals32, old32, 0x00000000, 0xFFFFFFFF, ALL32) - self.assertEqual(got_bcast[0:8], [1000] * 8) - self.assertEqual(got_bcast[8:16], [1015] * 8) - self.assertEqual(got_bcast[16:24], [1016] * 8) - self.assertEqual(got_bcast[24:32], [1031] * 8) - - # Full 16-lane reversal: s1=0x89abcdef (lanes 0..7 -> 15..8), s2=0x01234567 (lanes 8..15 -> 7..0). - got_rev16 = ref_permlane(False, vals32, old32, REV16_S1, REV16_S2, ALL32) - self.assertEqual(got_rev16[0:16], [1000 + (15 - l) for l in range(16)]) - self.assertEqual(got_rev16[16:32], [1016 + (15 - l) for l in range(16)]) - - # Sub-half 8-lane reversal: s1=0x01234567 (0..7 -> 7..0), s2=0x89abcdef (8..15 -> 15..8). - got_rev8 = ref_permlane(True, vals32, old32, REV8_S1, REV8_S2, ALL32) - self.assertEqual(got_rev8[0:8], [1016 + (7 - l) for l in range(8)]) - self.assertEqual(got_rev8[8:16], [1016 + (15 - l) for l in range(8)]) - - # op_sel:[fi, bound_ctrl] when lane 0 is INACTIVE in EXEC (0xFFFFFFFE): - # lanes 1..15 broadcast local lane 0 (inactive in half 0!), lanes 16..31 broadcast local lane 16 (active!). - exec_no_0 = ALL32 ^ 1 - # fi=0, bound_ctrl=0 -> lanes 1..15 keep old32, lane 0 keeps old32[0], lanes 16..31 read 1016. - r00 = ref_permlane(False, vals32, old32, 0, 0, exec_no_0, fi=0, bound_ctrl=0) - self.assertEqual(r00[0], old32[0]) - self.assertEqual(r00[1:16], old32[1:16]) - self.assertEqual(r00[16:32], [1016] * 16) - - # fi=0, bound_ctrl=1 -> lanes 1..15 write 0, lane 0 keeps old32[0], lanes 16..31 read 1016. - r01 = ref_permlane(False, vals32, old32, 0, 0, exec_no_0, fi=0, bound_ctrl=1) - self.assertEqual(r01[0], old32[0]) - self.assertEqual(r01[1:16], [0] * 15) - self.assertEqual(r01[16:32], [1016] * 16) - - # fi=1, bound_ctrl=0 or 1 -> lanes 1..15 read inactive lane 0's vals32[0], lane 0 keeps old32[0]. - for bc in (0, 1): - r1x = ref_permlane(False, vals32, old32, 0, 0, exec_no_0, fi=1, bound_ctrl=bc) - self.assertEqual(r1x[0], old32[0]) - self.assertEqual(r1x[1:16], [1000] * 15) - self.assertEqual(r1x[16:32], [1016] * 16) - - -class Wave32ExecutionTests(unittest.TestCase): - """End-to-end 32-lane execution for v_permlane16_b32 and v_permlanex16_b32.""" - - def _run_batch(self, specs: list[tuple[bool, int, int, str, str]], init_vals: list[int], - old_vals: list[int], exec_mask: int = ALL32) -> list[list[int]]: - """Run a list of (x16, s1, s2, src_form, extra_mods) batched into one shader.""" - lines = [ - "v_lshlrev_b32_e32 v20, 2, v0", - f"v_add_nc_u32_e32 v20, {INPUT_BASE:#x}, v20", - "buffer_load_dword v1, v20, s[0:3], 0 offen", - ] - regs = [] - for idx, _ in enumerate(specs): - dst = f"v{2 + idx}" - regs.append(dst) - lines.append(f"v_or_b32_e32 {dst}, {OLD_SENTINEL:#x}, v0") - lines.extend(exec_mask_lines(exec_mask, 32)) - for idx, (x16, s1, s2, src_expr, extra) in enumerate(specs): - dst = f"v{2 + idx}" - op = "v_permlanex16_b32" if x16 else "v_permlane16_b32" - if src_expr == "sgpr": - lines += [f"s_mov_b32 s4, {s1:#x}", f"s_mov_b32 s5, {s2:#x}", - f"{op} {dst}, v1, s4, s5{extra}"] - elif src_expr == "lit_sgpr": - lines += [f"s_mov_b32 s5, {s2:#x}", f"{op} {dst}, v1, {s1:#x}, s5{extra}"] - elif src_expr == "sgpr_lit": - lines += [f"s_mov_b32 s4, {s1:#x}", f"{op} {dst}, v1, s4, {s2:#x}{extra}"] - elif src_expr == "inline": - lines.append(f"{op} {dst}, v1, {s1}, {s2}{extra}") - elif src_expr == "same_sgpr": - assert s1 == s2 - lines += [f"s_mov_b32 s4, {s1:#x}", f"{op} {dst}, v1, s4, s4{extra}"] - elif src_expr == "e64_sgpr": - lines += [f"s_mov_b32 s4, {s1:#x}", f"s_mov_b32 s5, {s2:#x}", - f"{op}_e64 {dst}, v1, s4, s5{extra}"] - else: - raise ValueError(src_expr) - lines.extend(restore_exec_lines(32)) - lines.extend(store_slots_lines(regs, 32)) - flat = run_cs("cs_w32_permlane_batch", lines, 32, 32, init_inputs=init_vals, out_slots=len(specs)) - return [flat[slot * 32:(slot + 1) * 32] for slot in range(len(specs))] - - def test_half_isolation_vs_cross_half_swap_and_nibble_selectors(self): - init_vals = [(0x10000000 + l * 0x010101) & MASK32 for l in range(32)] - old_vals = [OLD_SENTINEL | l for l in range(32)] - specs = [ - # Identity (SGPR+SGPR, literal+SGPR, SGPR+literal, _e64) - (False, ID_S1, ID_S2, "sgpr", ""), - (True, ID_S1, ID_S2, "sgpr", ""), - (False, ID_S1, ID_S2, "lit_sgpr", ""), - (True, ID_S1, ID_S2, "sgpr_lit", ""), - (True, ID_S1, ID_S2, "e64_sgpr", ""), - # Broadcasts with inline constants (0, -1, 15, -16) and same-SGPR - (False, 0, 0, "inline", ""), - (True, 0, 0, "inline", ""), - (False, -1, -1, "inline", ""), - (True, 0, -1, "inline", ""), - (False, -16, 15, "inline", ""), # -16 = 0xfffffff0, 15 = 0x0000000f - (True, 0x55555555, 0x55555555, "same_sgpr", ""), - # 8-lane reversal vs full 16-lane reversal - (False, REV8_S1, REV8_S2, "sgpr", ""), - (True, REV8_S1, REV8_S2, "sgpr", ""), - (False, REV16_S1, REV16_S2, "sgpr", ""), - (True, REV16_S1, REV16_S2, "sgpr", ""), - # Pairwise swap & asymmetric non-bijective permutation - (False, PAIR_SWAP_S1, PAIR_SWAP_S2, "sgpr", ""), - (True, ASYM_S1, ASYM_S2, "sgpr", ""), - ] - results = self._run_batch(specs, init_vals, old_vals) - for idx, (x16, s1, s2, form, _) in enumerate(specs): - s1_u = s1 & MASK32 - s2_u = s2 & MASK32 - want = ref_permlane(x16, init_vals, old_vals, s1_u, s2_u, ALL32) - with self.subTest(idx=idx, x16=x16, form=form, s1=hex(s1_u), s2=hex(s2_u)): - self.assertEqual(results[idx], want) - - # Spot-check half-staying vs half-swapping explicitly: - self.assertEqual(results[0], init_vals) - self.assertEqual(results[1], init_vals[16:32] + init_vals[0:16]) - - def test_all_16_nibble_broadcasts_for_both_ops(self): - init_vals = [0x9000 + l * 17 for l in range(32)] - old_vals = [OLD_SENTINEL | l for l in range(32)] - specs = [] - for nib in range(16): - sel = 0x11111111 * nib - specs.append((False, sel, sel, "same_sgpr", "")) - specs.append((True, sel, sel, "same_sgpr", "")) - # Batch 16 specs at a time to stay well within VGPR file (v2..v17). - for base in (0, 16): - chunk = specs[base:base + 16] - results = self._run_batch(chunk, init_vals, old_vals) - for idx, (x16, s1, s2, _, _) in enumerate(chunk): - want = ref_permlane(x16, init_vals, old_vals, s1, s2, ALL32) - with self.subTest(x16=x16, nib=s1 & 0xF): - self.assertEqual(results[idx], want) - - def test_butterfly_32lane_sum_reduction(self): - # Real compiler idiom: xor 1, 2, 4, 8 via v_permlane16_b32 then xor 16 via v_permlanex16_b32. - init_vals = [3 * l + 5 for l in range(32)] - expected_sum = sum(init_vals) - got = run_cs("cs_w32_permlane_butterfly", [ - "v_lshlrev_b32_e32 v20, 2, v0", - f"v_add_nc_u32_e32 v20, {INPUT_BASE:#x}, v20", - "buffer_load_dword v1, v20, s[0:3], 0 offen", - # xor 1: s1=0x67452301, s2=0xefcdab89 - "s_mov_b32 s5, 0xefcdab89", - "v_permlane16_b32 v2, v1, 0x67452301, s5", - "v_add_nc_u32_e32 v1, v1, v2", - # xor 2: s1=0x54761032, s2=0xdcfe98ba - "s_mov_b32 s5, 0xdcfe98ba", - "v_permlane16_b32 v2, v1, 0x54761032, s5", - "v_add_nc_u32_e32 v1, v1, v2", - # xor 4: s1=0x32107654, s2=0xba98fedc - "s_mov_b32 s5, 0xba98fedc", - "v_permlane16_b32 v2, v1, 0x32107654, s5", - "v_add_nc_u32_e32 v1, v1, v2", - # xor 8: s1=0xfedcba98, s2=0x76543210 - "s_mov_b32 s5, 0x76543210", - "v_permlane16_b32 v2, v1, 0xfedcba98, s5", - "v_add_nc_u32_e32 v1, v1, v2", - # xor 16: identity nibbles via v_permlanex16_b32 - "s_mov_b32 s4, 0x76543210", - "s_mov_b32 s5, 0xfedcba98", - "v_permlanex16_b32 v2, v1, s4, s5", - "v_add_nc_u32_e32 v1, v1, v2", - "v_lshlrev_b32_e32 v21, 2, v0", - "buffer_store_dword v1, v21, s[0:3], 0 offen", - ], 32, 32, init_inputs=init_vals) - self.assertEqual(got, [expected_sum] * 32) - - def test_exec_destination_masking_and_all_op_sel_with_active_sources(self): - # Active lanes in each 16-lane half are {0, 2, 4, 6, 8, 9, 10, 11}; - # selectors ONLY read from active lanes {0, 2, 4, 6, 8, 9, 10, 11}, so all 4 op_sel modes match ISA. - exec_mask = 0x0F550F55 - s1_sel = 0x64206420 # nibbles in {0, 2, 4, 6} (all active) - s2_sel = 0xBA98BA98 # nibbles in {8, 9, 10, 11} (all active) - init_vals = [0x100 + l for l in range(32)] - old_vals = [OLD_SENTINEL | l for l in range(32)] - specs = [] - for x16 in (False, True): - for mods in ("", " op_sel:[0,0]", " op_sel:[1,0]", " op_sel:[0,1]", " op_sel:[1,1]"): - specs.append((x16, s1_sel, s2_sel, "sgpr", mods)) - results = self._run_batch(specs, init_vals, old_vals, exec_mask=exec_mask) - for idx, (x16, s1, s2, _, mods) in enumerate(specs): - want = ref_permlane(x16, init_vals, old_vals, s1, s2, exec_mask) - with self.subTest(x16=x16, mods=mods or "default"): - self.assertEqual(results[idx], want) - - def test_op_sel_fi1_reads_inactive_source_lanes(self): - # Lanes 0, 16 are OFF in EXEC; active lanes modify v1 to 9999 AFTER pre-filling v1, - # then v_permlane16_b32 / v_permlanex16_b32 with op_sel:[1,0] and op_sel:[1,1] broadcast - # local lane 0 (inactive lane 0 / inactive lane 16!). Active lanes must see the inactive - # lanes' pre-existing values (2000 and 2016), while inactive lanes 0 and 16 keep OLD. - exec_mask = ALL32 ^ ((1 << 0) | (1 << 16)) - init_vals = [2000 + l for l in range(32)] - old_vals = [OLD_SENTINEL | l for l in range(32)] - updated_vals = [init_vals[l] if not ((exec_mask >> l) & 1) else 9999 for l in range(32)] - - lines = [ - "v_lshlrev_b32_e32 v20, 2, v0", - f"v_add_nc_u32_e32 v20, {INPUT_BASE:#x}, v20", - "buffer_load_dword v1, v20, s[0:3], 0 offen", - f"v_or_b32_e32 v2, {OLD_SENTINEL:#x}, v0", - f"v_or_b32_e32 v3, {OLD_SENTINEL:#x}, v0", - f"v_or_b32_e32 v4, {OLD_SENTINEL:#x}, v0", - f"v_or_b32_e32 v5, {OLD_SENTINEL:#x}, v0", - *exec_mask_lines(exec_mask, 32), - "v_mov_b32_e32 v1, 9999", # inactive lanes 0 & 16 keep 2000 & 2016 - "v_permlane16_b32 v2, v1, 0, 0 op_sel:[1,0]", - "v_permlane16_b32 v3, v1, 0, 0 op_sel:[1,1]", - "v_permlanex16_b32 v4, v1, 0, 0 op_sel:[1,0]", - "v_permlanex16_b32 v5, v1, 0, 0 op_sel:[1,1]", - *restore_exec_lines(32), - *store_slots_lines(["v2", "v3", "v4", "v5"], 32), - ] - flat = run_cs("cs_w32_permlane_fi1", lines, 32, 32, init_inputs=init_vals, out_slots=4) - for slot, x16 in enumerate((False, False, True, True)): - got = flat[slot * 32:(slot + 1) * 32] - want = ref_permlane(x16, updated_vals, old_vals, 0, 0, exec_mask, fi=1, bound_ctrl=slot & 1) - self.assertEqual(got, want) - self.assertEqual(flat[0], OLD_SENTINEL | 0) - self.assertEqual(flat[1], 2000) - self.assertEqual(flat[16], OLD_SENTINEL | 16) - self.assertEqual(flat[17], 2016) - # Slot 2 (permlanex16 op_sel:[1,0]): active lanes 1..15 read inactive lane 16 (2016). - self.assertEqual(flat[2 * 32 + 1], 2016) - self.assertEqual(flat[2 * 32 + 17], 2000) - - def test_destination_aliasing_v1_and_v0(self): - init_vals = [300 + l for l in range(32)] - # 1. Alias v1, v1 (with EXEC mask & fi=1 reading inactive lane 0 before overwrite) - exec_mask = ALL32 ^ (1 << 0) - got_v1 = run_cs("cs_w32_permlane_alias_v1", [ - "v_lshlrev_b32_e32 v20, 2, v0", - f"v_add_nc_u32_e32 v20, {INPUT_BASE:#x}, v20", - "buffer_load_dword v1, v20, s[0:3], 0 offen", - "v_mov_b32_e32 v2, v1", - *exec_mask_lines(exec_mask, 32), - "s_mov_b32 s4, 0x00000000", - "s_mov_b32 s5, 0x00000000", - "v_permlane16_b32 v1, v1, s4, s5 op_sel:[1,0]", - "v_permlanex16_b32 v2, v2, 0x76543210, 0xfedcba98 op_sel:[1,0]", - *restore_exec_lines(32), - *store_slots_lines(["v1", "v2"], 32), - ], 32, 32, init_inputs=init_vals, out_slots=2) - self.assertEqual(got_v1[:32], ref_permlane(False, init_vals, init_vals, 0, 0, exec_mask, fi=1)) - self.assertEqual(got_v1[32:], ref_permlane(True, init_vals, init_vals, ID_S1, ID_S2, exec_mask, fi=1)) - - # 2. Alias v0, v0 directly (save output byte offset 4 * v0 in v21 first) - got_v0_16 = run_cs("cs_w32_permlane16_alias_v0", [ - "v_lshlrev_b32_e32 v21, 2, v0", - f"s_mov_b32 s4, {REV16_S1:#x}", - f"s_mov_b32 s5, {REV16_S2:#x}", - "v_permlane16_b32 v0, v0, s4, s5", - "buffer_store_dword v0, v21, s[0:3], 0 offen", - ], 32, 32) - self.assertEqual(got_v0_16, ref_permlane(False, list(range(32)), list(range(32)), REV16_S1, REV16_S2, ALL32)) - - got_v0_x16 = run_cs("cs_w32_permlanex16_alias_v0", [ - "v_lshlrev_b32_e32 v21, 2, v0", - f"s_mov_b32 s4, {REV16_S1:#x}", - f"s_mov_b32 s5, {REV16_S2:#x}", - "v_permlanex16_b32 v0, v0, s4, s5", - "buffer_store_dword v0, v21, s[0:3], 0 offen", - ], 32, 32) - self.assertEqual(got_v0_x16, ref_permlane(True, list(range(32)), list(range(32)), REV16_S1, REV16_S2, ALL32)) - - def test_partial_wave_20_lanes_avoids_missing_lanes(self): - # 20 threads on a 32-wide subgroup: lanes 20..31 do not exist. - # 1. All 20 existing lanes active (0xFFFFF): selectors in {0..3} read existing active lanes 0..3 / 16..19. - exec_20 = 0xFFFFF - got_all20 = run_cs("cs_w32_partial20_all", [ - "v_add_nc_u32_e32 v1, 700, v0", - f"v_or_b32_e32 v2, {OLD_SENTINEL:#x}, v0", - f"v_or_b32_e32 v3, {OLD_SENTINEL:#x}, v0", - *exec_mask_lines(exec_20, 32), - "v_permlane16_b32 v2, v1, 0x32103210, 0x01230123", - "v_permlanex16_b32 v3, v1, 0x32103210, 0x01230123", - *restore_exec_lines(32), - *store_slots_lines(["v2", "v3"], 20), - ], 20, 32, out_slots=2) - vals_padded = [700 + l for l in range(20)] + [0] * 12 - old_padded = [OLD_SENTINEL | l for l in range(20)] + [0] * 12 - self.assertEqual(got_all20[:20], ref_permlane(False, vals_padded, old_padded, 0x32103210, 0x01230123, exec_20)[:20]) - self.assertEqual(got_all20[20:40], ref_permlane(True, vals_padded, old_padded, 0x32103210, 0x01230123, exec_20)[:20]) - - # 2. EXEC = 0xFFFF (lanes 16..19 inactive): permlane16 reads [0..15] and preserves OLD on 16..19; - # permlanex16 op_sel:[1,0] (fi=1) reads inactive lanes 16..19 while inactive lanes 16..19 discard UNDEF - # shuffles from missing lanes 20..31 and keep OLD. - exec_16 = 0xFFFF - got_masked = run_cs("cs_w32_partial20_masked", [ - "v_add_nc_u32_e32 v1, 700, v0", - f"v_or_b32_e32 v2, {OLD_SENTINEL:#x}, v0", - f"v_or_b32_e32 v3, {OLD_SENTINEL:#x}, v0", - *exec_mask_lines(exec_16, 32), - "v_permlane16_b32 v2, v1, 0x01234567, 0x89abcdef", - "v_permlanex16_b32 v3, v1, 0x32103210, 0x01230123 op_sel:[1,0]", - *restore_exec_lines(32), - *store_slots_lines(["v2", "v3"], 20), - ], 20, 32, out_slots=2) - self.assertEqual(got_masked[:20], ref_permlane(False, vals_padded, old_padded, REV8_S1, REV8_S2, exec_16)[:20]) - self.assertEqual(got_masked[20:40], ref_permlane(True, vals_padded, old_padded, 0x32103210, 0x01230123, exec_16, fi=1)[:20]) - - -class Wave64ExecutionTests(unittest.TestCase): - """End-to-end 64-lane execution across one 64-wide subgroup AND two 32-wide subgroups.""" - - def test_wave64_halves_selectors_exec_and_fi1_on_subgroup_64_and_32(self): - init_vals = [0x4000 + l * 31 for l in range(64)] - old_vals = [OLD_SENTINEL | l for l in range(64)] - # Asymmetric 64-bit EXEC: active lanes in each 16-lane quarter are {0, 2, 4, 6, 8, 9, 10, 11}. - exec_active_only = 0x0F550F550F550F55 - # Inactive source lane 0 and lane 32 (one in each 32-lane row) for fi=1 test. - exec_no_0_32 = ALL64 ^ ((1 << 0) | (1 << 32)) - updated_fi1 = [init_vals[l] if not ((exec_no_0_32 >> l) & 1) else (8800 + l) for l in range(64)] - - lines = [ - "s_mov_b64 exec, -1", - "v_lshlrev_b32_e32 v20, 2, v0", - f"v_add_nc_u32_e32 v20, {INPUT_BASE:#x}, v20", - "buffer_load_dword v1, v20, s[0:3], 0 offen", - "v_mov_b32_e32 v10, v1", - # Slot 0: v_permlane16_b32 identity (stays in [0..15], [16..31], [32..47], [48..63]) - f"s_mov_b32 s4, {ID_S1:#x}", - f"s_mov_b32 s5, {ID_S2:#x}", - "v_permlane16_b32 v2, v1, s4, s5", - # Slot 1: v_permlanex16_b32 identity (swaps [0..15]<->[16..31] and [32..47]<->[48..63]) - "v_permlanex16_b32 v3, v1, s4, s5", - # Slot 2: v_permlane16_b32 asymmetric non-bijective selectors - f"s_mov_b32 s6, {ASYM_S1:#x}", - f"s_mov_b32 s7, {ASYM_S2:#x}", - "v_permlane16_b32 v4, v1, s6, s7", - # Slot 3: v_permlanex16_b32_e64 full 16-lane reversal - f"s_mov_b32 s8, {REV16_S2:#x}", - f"v_permlanex16_b32_e64 v5, v1, {REV16_S1:#x}, s8", - # Slot 4: 64-bit EXEC destination masking with active sources (v6 pre-loaded with OLD) - f"v_or_b32_e32 v6, {OLD_SENTINEL:#x}, v0", - "s_mov_b32 s9, 0xba98ba98", - *exec_mask_lines(exec_active_only, 64), - "v_permlanex16_b32 v6, v1, 0x64206420, s9", - *restore_exec_lines(64), - # Slot 5: fi=1 reading inactive source lane 0 (in low 32) and lane 32 (in high 32) - f"v_or_b32_e32 v7, {OLD_SENTINEL:#x}, v0", - *exec_mask_lines(exec_no_0_32, 64), - "v_add_nc_u32_e32 v10, 8800, v0", - "v_permlane16_b32 v7, v10, 0, 0 op_sel:[1,0]", - # Slot 6: fi=1 permlanex16 reading inactive lane 32 from lanes 48..63 & lane 0 from 16..31 - *restore_exec_lines(64), - f"v_or_b32_e32 v8, {OLD_SENTINEL:#x}, v0", - *exec_mask_lines(exec_no_0_32, 64), - "v_permlanex16_b32 v8, v10, 0, 0 op_sel:[1,1]", - *restore_exec_lines(64), - *store_slots_lines(["v2", "v3", "v4", "v5", "v6", "v7", "v8"], 64), - ] - - expected_slots = [ - ref_permlane(False, init_vals, old_vals, ID_S1, ID_S2, ALL64), - ref_permlane(True, init_vals, old_vals, ID_S1, ID_S2, ALL64), - ref_permlane(False, init_vals, old_vals, ASYM_S1, ASYM_S2, ALL64), - ref_permlane(True, init_vals, old_vals, REV16_S1, REV16_S2, ALL64), - ref_permlane(True, init_vals, old_vals, 0x64206420, 0xBA98BA98, exec_active_only), - ref_permlane(False, updated_fi1, old_vals, 0, 0, exec_no_0_32, fi=1, bound_ctrl=0), - ref_permlane(True, updated_fi1, old_vals, 0, 0, exec_no_0_32, fi=1, bound_ctrl=1), - ] - - for subgroup_size in (64, 32): - with self.subTest(subgroup_size=subgroup_size): - flat = run_cs(f"cs_w64_permlane_sg{subgroup_size}", lines, 64, subgroup_size, - init_inputs=init_vals, out_slots=7) - for slot, want in enumerate(expected_slots): - got = flat[slot * 64:(slot + 1) * 64] - self.assertEqual(got, want, f"subgroup={subgroup_size}, slot={slot}") - - def test_wave64_destination_aliasing_v0_and_v1(self): - for subgroup_size in (64, 32): - with self.subTest(subgroup_size=subgroup_size): - got = run_cs(f"cs_w64_permlane_alias_sg{subgroup_size}", [ - "s_mov_b64 exec, -1", - "v_lshlrev_b32_e32 v21, 2, v0", - "v_add_nc_u32_e32 v1, 500, v0", - f"s_mov_b32 s4, {PAIR_SWAP_S1:#x}", - f"s_mov_b32 s5, {PAIR_SWAP_S2:#x}", - "v_permlane16_b32 v1, v1, s4, s5", - "v_permlanex16_b32 v0, v0, s4, s5", - "buffer_store_dword v1, v21, s[0:3], 0 offen", - f"buffer_store_dword v0, v21, s[0:3], 0 offen offset:{4 * 64}", - ], 64, subgroup_size, out_slots=2) - self.assertEqual( - got[:64], - ref_permlane(False, [500 + l for l in range(64)], [0] * 64, PAIR_SWAP_S1, PAIR_SWAP_S2, ALL64), - ) - self.assertEqual( - got[64:], - ref_permlane(True, list(range(64)), list(range(64)), PAIR_SWAP_S1, PAIR_SWAP_S2, ALL64), - ) - - def test_wave64_partial_wave_40_lanes(self): - # 40 threads in a 64-wide subgroup: lanes 32..39 exist in quarter [32..47]; lanes 40..63 do not. - # Active lanes 0..31 run v_permlanex16_b32 across [0..15] <-> [16..31], and lanes 32..39 run - # v_permlane16_b32 within [32..39]; inactive lanes 32..39 on permlanex16 discard UNDEF from [48..63]. - exec_low32 = 0x00000000FFFFFFFF - got = run_cs("cs_w64_partial40_permlane", [ - "s_mov_b64 exec, -1", - "v_add_nc_u32_e32 v1, 200, v0", - f"v_or_b32_e32 v2, {OLD_SENTINEL:#x}, v0", - f"v_or_b32_e32 v3, {OLD_SENTINEL:#x}, v0", - "v_permlane16_b32 v2, v1, 0x32107654, 0x32107654", - *exec_mask_lines(exec_low32, 64), - "v_permlanex16_b32 v3, v1, 0x01234567, 0x89abcdef", - *restore_exec_lines(64), - *store_slots_lines(["v2", "v3"], 40), - ], 40, 64, out_slots=2) - vals64 = [200 + l for l in range(40)] + [0] * 24 - old64 = [OLD_SENTINEL | l for l in range(40)] + [0] * 24 - self.assertEqual(got[:40], ref_permlane(False, vals64, old64, 0x32107654, 0x32107654, ALL64)[:40]) - self.assertEqual(got[40:], ref_permlane(True, vals64, old64, REV8_S1, REV8_S2, exec_low32)[:40]) - - -class EmulationAndFindingTests(unittest.TestCase): - """Translation / structural SPIR-V checks for --wave64-emulate and documented op_sel finding.""" - - def test_wave64_emulate_lowers_permlane_through_x_buf_without_subgroup_ops(self): - base = [ - "s_mov_b64 exec, -1", - "v_add_nc_u32_e32 v1, 100, v0", - f"s_mov_b32 s4, {ID_S1:#x}", - f"s_mov_b32 s5, {ID_S2:#x}", - ] - tail = [ - "v_lshlrev_b32_e32 v21, 2, v0", - "buffer_store_dword v2, v21, s[0:3], 0 offen", - ] - spv_16, gen_16 = translate_cs("cs_w64_emu_perm16", base + ["v_permlane16_b32 v2, v1, s4, s5"] + tail, - 64, emulate=True) - spv_x16, gen_x16 = translate_cs("cs_w64_emu_permx16", base + ["v_permlanex16_b32 v2, v1, s4, s5"] + tail, - 64, emulate=True) - for spv, gen in ((spv_16, gen_16), (spv_x16, gen_x16)): - self.assertTrue(gen.wave64 and gen.emulate) - self.assertNotIn("OpGroupNonUniform", spv) - self.assertNotIn("%sg_lane", spv) - self.assertIn("%x_buf = OpVariable", spv) - self.assertGreaterEqual(spv.count("OpControlBarrier"), 2) - # Nibble extraction (width = 4) and 16-lane half mask (0xFFFFFFF0) - self.assertRegex(spv, r"OpBitFieldUExtract %uint %\w+ %\w+ %c4\b") - self.assertIn("OpBitwiseAnd %uint %", spv) - self.assertIn("%cfffffff0", spv) - # spirv_mini_interp.py deliberately rejects the emulated Workgroup/loop scheduler. - with self.assertRaises(si.UnsupportedConstruct): - si.run_workgroup( - spv, 64, 32, - inputs_for=lambda i: {"%wg_id": (0, 0, 0), "%local_id": (i, 0, 0), "%sg_lane": i % 32}, - push_constants=VSHARP + [0] * 28, memory={}, - ) - - # v_permlanex16_b32 XORs the masked half base with 16 (%c10); v_permlane16_b32 does not. - xor16_pat = r"OpBitwiseAnd %uint %\w+ %cfffffff0\n\s*%\w+ = OpBitwiseXor %uint %\w+ %c10\b" - self.assertIsNone(re.search(xor16_pat, spv_16)) - self.assertIsNotNone(re.search(xor16_pat, spv_x16)) - - # Wave32 shaders are unaffected by WAVE64_EMULATE=True. - w32_lines = ["v_permlanex16_b32 v2, v0, 0x76543210, 0xfedcba98", - "v_lshlrev_b32_e32 v21, 2, v0", "buffer_store_dword v2, v21, s[0:3], 0 offen"] - spv_w32_plain, _ = translate_cs("cs_w32_emu_nop", w32_lines, 32, emulate=False) - spv_w32_emu, gen_w32_emu = translate_cs("cs_w32_emu_nop", w32_lines, 32, emulate=True) - self.assertFalse(gen_w32_emu.wave64 or gen_w32_emu.emulate) - self.assertEqual(spv_w32_plain, spv_w32_emu) - - def test_op_sel_fi0_translates_cleanly_while_inactive_src_handling_is_excluded(self): - # Documented finding (tools/rdna2spirv.py lines 4608-4632): op_sel:[0,0] and op_sel:[0,1] - # are accepted by shader_ir/rdna2spirv without raising Unsupported, and lower to - # OpGroupNonUniformShuffle without inspecting mods or source %active; inactive-source fi=0 - # value assertions stay excluded from Wave32ExecutionTests / Wave64ExecutionTests. - for op in ("v_permlane16_b32", "v_permlanex16_b32"): - for opsel in ("op_sel:[0,0]", "op_sel:[0,1]"): - with self.subTest(op=op, opsel=opsel): - spv, gen = translate_cs("cs_w32_opsel_fi0", [ - "v_mov_b32_e32 v1, v0", - "s_mov_b32 exec_lo, 0xfffffffe", - f"{op} v2, v1, 0, 0 {opsel}", - "s_mov_b32 exec_lo, -1", - "v_lshlrev_b32_e32 v21, 2, v0", - "buffer_store_dword v2, v21, s[0:3], 0 offen", - ], 32) - self.assertFalse(gen.wave64) - self.assertIn("OpGroupNonUniformShuffle %uint %c3", spv) - self.assertRegex(spv, r"OpBitFieldUExtract %uint %\w+ %\w+ %c4\b") - - -class NegativeControls(unittest.TestCase): - """Sabotage the translated SPIR-V like a translator regression; multi-lane execution must detect it.""" - - def _run(self, spv: str, threads: int, subgroup_size: int) -> list[int]: - mem = _Heap() - si.run_workgroup( - spv, threads, subgroup_size, - inputs_for=lambda i: {"%wg_id": (0, 0, 0), "%local_id": (i, 0, 0), "%sg_lane": i % subgroup_size}, - push_constants=VSHARP + [0] * 28, - memory=mem, - ) - return [mem.get(4 * k) for k in range(threads)] - - def test_sabotage_permlanex16_xor16_dropped(self): - spv, _ = translate_cs("cs_w64_neg_x16", [ - "s_mov_b64 exec, -1", - "v_add_nc_u32_e32 v1, 100, v0", - f"v_permlanex16_b32 v2, v1, {ID_S1:#x}, {ID_S2:#x}", - "v_lshlrev_b32_e32 v21, 2, v0", - "buffer_store_dword v2, v21, s[0:3], 0 offen", - ], 64) - want = ref_permlane(True, [100 + l for l in range(64)], [0] * 64, ID_S1, ID_S2, ALL64) - self.assertEqual(self._run(spv, 64, 64), want) - - bad, n = re.subn(r"(%\w+) = OpBitwiseXor %uint (%\w+) %c10\b", r"\1 = OpCopyObject %uint \2", spv) - self.assertEqual(n, 1) - got_bad = self._run(bad, 64, 64) - self.assertNotEqual(got_bad, want) - self.assertEqual(got_bad, [100 + l for l in range(64)]) # collapsed to permlane16 - - def test_sabotage_half_base_dropped_or_shuffle_removed(self): - spv, _ = translate_cs("cs_w32_neg_perm16", [ - "v_add_nc_u32_e32 v1, 200, v0", - f"v_or_b32_e32 v2, {OLD_SENTINEL:#x}, v0", - f"s_mov_b32 exec_lo, {0x0F550F55:#x}", - "s_mov_b32 s4, 0x64206420", - "s_mov_b32 s5, 0xba98ba98", - "v_permlane16_b32 v2, v1, s4, s5", - "s_mov_b32 exec_lo, -1", - "v_lshlrev_b32_e32 v21, 2, v0", - "buffer_store_dword v2, v21, s[0:3], 0 offen", - ], 32) - want = ref_permlane(False, [200 + l for l in range(32)], [OLD_SENTINEL | l for l in range(32)], - 0x64206420, 0xBA98BA98, 0x0F550F55) - self.assertEqual(self._run(spv, 32, 32), want) - - # 1. Dropping the 0xFFFFFFF0 half-base mask sends lanes 16..31 into [0..15]. - bad_half, n1 = re.subn(r"OpBitwiseAnd %uint (%\w+) %cfffffff0\b", r"OpBitwiseAnd %uint \1 %c0", spv) - self.assertEqual(n1, 1) - self.assertNotEqual(self._run(bad_half, 32, 32), want) - - # 2. Swapping the hi8 OpSelect arms swaps s1 (lanes 0..7) and s2 (lanes 8..15). - bad_sel, n2 = re.subn( - r"(%\w+ = OpUGreaterThanEqual %bool %\w+ %c8\n(?:.*\n){0,5}?\s*%\w+ = OpSelect %uint %\w+ )(%\w+) (%\w+)", - r"\1\3 \2", - spv, - ) - self.assertEqual(n2, 1) - self.assertNotEqual(self._run(bad_sel, 32, 32), want) - - # 3. Replacing OpGroupNonUniformShuffle with OpCopyObject turns permute into own-lane copy. - bad_shuf, n3 = re.subn( - r"(%\w+) = OpGroupNonUniformShuffle %uint %c3 (%\w+) %\w+", - r"\1 = OpCopyObject %uint \2", - spv, - ) - self.assertEqual(n3, 2) # the data shuffle and, with FI=0 (no op_sel), the source lane's activity shuffle (SHADER-74) - self.assertNotEqual(self._run(bad_shuf, 32, 32), want) - - # 4. The FI/BOUND_CTRL result is a bitwise merge, not a select (#5895): an active lane whose source is off in - # EXEC keeps the old value. Every even lane selects an odd (off) source, so the unsabotaged run keeps OLD - # everywhere; forcing the ok-mask on makes the active lanes take the off source's value instead — the - # MoltenVK symptom the masks exist to prevent. - spv_fi, _ = translate_cs("cs_w32_neg_perm_fi", [ - "v_add_nc_u32_e32 v1, 200, v0", - f"v_or_b32_e32 v2, {OLD_SENTINEL:#x}, v0", - f"s_mov_b32 exec_lo, {0x55555555:#x}", - "s_mov_b32 s4, 0x11111111", - "s_mov_b32 s5, 0x11111111", - "v_permlane16_b32 v2, v1, s4, s5", - "s_mov_b32 exec_lo, -1", - "v_lshlrev_b32_e32 v21, 2, v0", - "buffer_store_dword v2, v21, s[0:3], 0 offen", - ], 32) - want_fi = [OLD_SENTINEL | l for l in range(32)] # FI=0 with an off source keeps OLD; odd lanes are off in EXEC - self.assertEqual(self._run(spv_fi, 32, 32), want_fi) - ok_mask = re.search(r"(%\w+) = OpSelect %uint %\w+ (%cffffffff) %c0(\n(?:.*\n){0,2}?\s*%\w+ = OpAccessChain %_ptr_Function_uint %vgpr)", spv_fi) - self.assertIsNotNone(ok_mask) - bad_ok = spv_fi[:ok_mask.start()] + ok_mask.group(1) + " = OpCopyObject %uint " + ok_mask.group(2) + ok_mask.group(3) + spv_fi[ok_mask.end():] - got_bad_ok = self._run(bad_ok, 32, 32) - self.assertNotEqual(got_bad_ok, want_fi) - self.assertNotEqual(got_bad_ok[0], OLD_SENTINEL) # the active lane now takes the off source's value - - # 5. Forcing the destination EXEC mask on overwrites inactive destination lanes: dst() combines with the - # same masks, and its exec mask is the select that its own OpNot consumes on the next line. - exec_mask = re.search(r"(%\w+) = OpSelect %uint %\w+ (%cffffffff) %c0(?=\n\s*%\w+ = OpNot %uint \1\n)", spv) - self.assertIsNotNone(exec_mask) - bad_exec = spv[:exec_mask.start()] + exec_mask.group(1) + " = OpCopyObject %uint " + exec_mask.group(2) + spv[exec_mask.end():] - got_bad_exec = self._run(bad_exec, 32, 32) - self.assertNotEqual(got_bad_exec, want) - self.assertNotEqual(got_bad_exec[1], OLD_SENTINEL | 1) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_valu_pipeflush.py b/tests/semantic/test_valu_pipeflush.py deleted file mode 100644 index 02f35db7c..000000000 --- a/tests/semantic/test_valu_pipeflush.py +++ /dev/null @@ -1,77 +0,0 @@ -"""Semantic interpreter tests for RDNA2 v_pipeflush. - -v_pipeflush (GFX10 VOP1) flushes the VALU pipeline and has no architectural effect: no register, memory, VCC, SCC -or EXEC changes. It is translated as nothing, like v_nop. Each case translates a synthetic pixel shader with -tools/rdna2spirv.py, runs it in tests/semantic/spirv_mini_interp.py and checks that the values around the -instruction come out unchanged. -""" -import os -import struct -import sys -import tempfile -import unittest -import warnings - -HERE = os.path.dirname(os.path.abspath(__file__)) -ROOT = os.path.dirname(os.path.dirname(HERE)) -TOOLS_DIR = os.environ.get("LEONIDA_TOOLS_DIR") or os.path.join(ROOT, "tools") - -sys.dont_write_bytecode = True -sys.path.insert(0, TOOLS_DIR) -sys.path.insert(0, HERE) - -import rdna2spirv # noqa: E402 -import spirv_mini_interp as si # noqa: E402 - -STUB_DXBC = b"DXBC" + bytes(24) + struct.pack(" str: - if _TMP_DIR is None: - setUpModule() - asm = "; test_pipeflush\n" + "".join(f"\t{ln}\n" for ln in lines) + "\texp mrt0 v0, v1, v2, v3 done vm\n\ts_endpgm\n" - with open(_SRC_PATH, "w", encoding="utf-8") as f: - f.write(asm) - with warnings.catch_warnings(): - warnings.simplefilter("ignore", ResourceWarning) - return rdna2spirv.translate(_SRC_PATH) - - -class PipeflushTests(unittest.TestCase): - PROLOGUE = ["v_mov_b32 v0, 0x40000001", "v_mov_b32 v1, 0x40000002", "s_mov_b32 s2, 7", "s_cmp_eq_u32 s2, 7", - "v_cmp_eq_u32 vcc_lo, 0x40000001, v0"] - EPILOGUE = ["s_cselect_b32 s3, 0x40000003, 0x40000000", "v_mov_b32 v2, s3", - "v_cndmask_b32 v3, 0x40000000, 0x40000004, vcc_lo"] - - def test_values_survive(self): - spv = translate(self.PROLOGUE + ["v_pipeflush"] + self.EPILOGUE) - self.assertEqual(si.run_fragment(spv)["%out_mrt0"], (0x40000001, 0x40000002, 0x40000003, 0x40000004)) - - def test_same_program_as_without_it(self): - with_it = translate(self.PROLOGUE + ["v_pipeflush", "v_pipeflush_e64"] + self.EPILOGUE) - without = translate(self.PROLOGUE + self.EPILOGUE) - self.assertEqual(si.run_fragment(with_it), si.run_fragment(without)) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_valu_pk_add_f16.py b/tests/semantic/test_valu_pk_add_f16.py deleted file mode 100644 index a4f9e2145..000000000 --- a/tests/semantic/test_valu_pk_add_f16.py +++ /dev/null @@ -1,169 +0,0 @@ -"""v_pk_add_f16 (RDNA2 VOP3P): D.f16[i] = S0.f16[i] + S1.f16[i] for both halves, binary16 with round to nearest even. - -Every case is translated by tools/rdna2spirv.py and executed with tests/semantic/spirv_mini_interp.py. The expected -words are written down by hand (from the ISA) next to each case; the plain-Python binary16 reference in -tests/semantic/f16_ref.py rechecks them lane by lane and drives seeded random operands and modifier combinations. -Covers per-lane results, op_sel / op_sel_hi half selection, neg_lo / neg_hi, clamp and SGPR sources. -Standard library only: no GPU, no LLVM, no game data. -""" -import os -import random -import sys -import unittest - -HERE = os.path.dirname(os.path.abspath(__file__)) -sys.dont_write_bytecode = True -sys.path.insert(0, HERE) -import support # noqa: E402 -from f16_ref import clamp01, ref_add, same_f16 # noqa: E402 - -ONE, TWO, THREE, HALF, QUARTER = 0x3C00, 0x4000, 0x4200, 0x3800, 0x3400 -MAXH, INF, NINF, QNAN = 0x7BFF, 0x7C00, 0xFC00, 0x7E00 -MIN_NORMAL, MIN_SUB, MAX_SUB = 0x0400, 0x0001, 0x03FF - - -def P(lo, hi): - """A dword holding two binary16 values.""" - return (hi << 16) | lo - - -def run(line, seeds, old=0xDEADBEEF): - """Run one instruction on a one-lane pixel shader and return v0 as exported to mrt0 (seeds map reg -> dword).""" - prog = [f"v_mov_b32 v0, {old:#x}"] - for reg, w in seeds.items(): - prog.append(f"{'s' if reg[0] == 's' else 'v'}_mov_b32 {reg}, {w:#x}") - prog += [line, "exp mrt0 v0, v0, v0, v0 done vm", "s_endpgm"] - return support.mrt0_words(support.translate_lines("ps_pk_add_f16", prog))[0] - - -def half(w, i): - return (w >> (16 * i)) & 0xFFFF - - -def pk_ref(fn, srcs, op_sel=None, op_sel_hi=None, neg_lo=None, neg_hi=None, clamp=False): - """Reference for one packed op: the low result reads half op_sel[i] of source i (negated by neg_lo[i]), the high - result half op_sel_hi[i] (negated by neg_hi[i]); defaults are op_sel 0, op_sel_hi 1, no negation.""" - n = len(srcs) - op_sel, op_sel_hi = op_sel or [0] * n, op_sel_hi or [1] * n - neg_lo, neg_hi = neg_lo or [0] * n, neg_hi or [0] * n - out = [] - for sel, ng in ((op_sel, neg_lo), (op_sel_hi, neg_hi)): - r = fn(*[half(s, h) ^ (0x8000 if g else 0) for s, h, g in zip(srcs, sel, ng)]) - out.append(clamp01(r) if clamp else r) - return P(out[0], out[1]) - - -def same_pk(a, b): - return same_f16(a & 0xFFFF, b & 0xFFFF) and same_f16(a >> 16, b >> 16) - - -def mods_text(op_sel=None, op_sel_hi=None, neg_lo=None, neg_hi=None, clamp=False): - t = "" - for name, v in (("op_sel", op_sel), ("op_sel_hi", op_sel_hi), ("neg_lo", neg_lo), ("neg_hi", neg_hi)): - if v is not None: - t += f" {name}:[{','.join(map(str, v))}]" - return t + (" clamp" if clamp else "") - - -def regs(n): - return ", ".join(f"v{i}" for i in range(1, n + 1)) - - -# mnemonic -> (source count, reference for one lane) -OPS = {"v_pk_add_f16": (2, ref_add)} - -# mnemonic -> rows of (source dwords..., D), written by hand; lane 0 is the low half -CASES = { - 'v_pk_add_f16': [ - (P(ONE, TWO), P(TWO, THREE), P(THREE, 0x4500)), # (1 + 2, 2 + 3) = (3, 5) - (P(HALF, 0x8000), P(QUARTER, 0x8000), P(0x3A00, 0x8000)), # (0.5 + 0.25, -0 + -0) = (0.75, -0) - (P(MAXH, ONE), P(MAXH, MIN_SUB), P(INF, ONE)), # lanes are independent: overflow / 1 + 2^-24 = 1 - (P(0x3E00, INF), P(0xBE00, NINF), P(0x0000, QNAN)), # (1.5 - 1.5 = +0, inf + -inf = NaN) - (P(MIN_NORMAL, 0x6800), P(0x8001, ONE), P(MAX_SUB, 0x6800)), # (2^-14 - 2^-24 = largest subnormal, 2048 + 1 ties to even) - (P(ONE, 0x6801), P(0x1000, ONE), P(ONE, 0x6802)), # (1 + 2^-11 ties to 1, 2050 + 1 ties to 2052) - (P(0x8000, 0x0000), P(0x0000, 0x8000), P(0x0000, 0x0000)), # (-0 + +0, +0 + -0) = (+0, +0) - (P(MIN_SUB, 0xFBFF), P(MIN_SUB, 0xFBFF), P(0x0002, NINF)), # (2^-23, -65504 * 2 overflows) - ], - -} - -# mnemonic -> (sources, modifier text, D), by hand. S0 = (1.0, 3.0), S1 = (0.5, -0.25), S2 = (0.25, -1.0) as -# (low, high) halves. -S0, S1, S2 = P(ONE, THREE), P(HALF, 0xB400), P(QUARTER, 0xBC00) -MODS = { - 'v_pk_add_f16': [ - ((S0, S1), "", P(0x3E00, 0x4180)), # (1 + 0.5, 3 - 0.25) = (1.5, 2.75) - ((S0, S1), " op_sel:[1,0]", P(0x4300, 0x4180)), # low: S0.hi + S1.lo = 3.5 - ((S0, S1), " op_sel:[0,1] op_sel_hi:[0,0]", P(0x3A00, 0x3E00)), # low: 1 + -0.25 = 0.75; high: 1 + 0.5 - ((S0, S1), " op_sel:[1,1] op_sel_hi:[0,0]", P(0x4180, 0x3E00)), # low: 3 + -0.25 = 2.75; high: 1 + 0.5 - ((S0, S1), " neg_lo:[1,0]", P(0xB800, 0x4180)), # low: -1 + 0.5 - ((S0, S1), " neg_hi:[0,1]", P(0x3E00, 0x4280)), # high: 3 - -0.25 = 3.25 - ((S0, S1), " neg_lo:[1,1] neg_hi:[1,1]", P(0xBE00, 0xC180)), # both negated: (-1.5, -2.75) - ((P(0x3E00, 0xBC00), P(HALF, QUARTER)), " clamp", P(ONE, 0x0000)), # (2.0, -0.75) -> (1, 0) - ((P(HALF, QUARTER), P(QUARTER, QUARTER)), " clamp", P(0x3A00, HALF)), # inside [0, 1]: unchanged - ], - -} - - -class PkAddF16(unittest.TestCase): - def test_hand_written_table_matches_reference(self): - for op, rows in CASES.items(): - for *src, want in rows: - with self.subTest(op=op, src=[hex(s) for s in src]): - self.assertTrue(same_pk(pk_ref(OPS[op][1], src), want), hex(pk_ref(OPS[op][1], src))) - - def test_per_lane_results(self): - for op, rows in CASES.items(): - for *src, want in rows: - with self.subTest(op=op, src=[hex(s) for s in src]): - got = run(f"{op} v0, {regs(len(src))}", {f"v{i}": s for i, s in enumerate(src, 1)}) - self.assertTrue(same_pk(got, want), hex(got)) - - def test_sgpr_sources(self): - for op, rows in CASES.items(): - for *src, want in rows[:6]: - n = len(src) - forms = [("all sgpr", ", ".join(f"s{i}" for i in range(1, n + 1)), {f"s{i}": s for i, s in enumerate(src, 1)}), - ("sgpr src0", ", ".join(["s1"] + [f"v{i}" for i in range(2, n + 1)]), - {"s1": src[0], **{f"v{i}": s for i, s in enumerate(src[1:], 2)}})] - for form, text, seeds in forms: - with self.subTest(op=op, src=[hex(s) for s in src], form=form): - self.assertTrue(same_pk(run(f"{op} v0, {text}", seeds), want)) - - def test_hand_written_modifier_cases(self): - for op, rows in MODS.items(): - for srcs, mods, want in rows: - with self.subTest(op=op, mods=mods): - got = run(f"{op} v0, {regs(len(srcs))}{mods}", {f"v{i}": s for i, s in enumerate(srcs, 1)}) - self.assertTrue(same_pk(got, want), hex(got)) - - def test_every_op_sel_and_op_sel_hi_combination(self): - a, b, c = P(0x3E00, 0xC400), P(0x4900, 0x3A00), P(0xB800, 0x4D00) # distinct halves: 1.5/-4, 10/.75, -.5/20 - for op, (n, fn) in OPS.items(): - srcs = [a, b, c][:n] - for sel in range(1 << n): - for selhi in range(1 << n): - os_, oh = [(sel >> i) & 1 for i in range(n)], [(selhi >> i) & 1 for i in range(n)] - with self.subTest(op=op, op_sel=os_, op_sel_hi=oh): - got = run(f"{op} v0, {regs(n)}{mods_text(os_, oh)}", {f"v{i}": s for i, s in enumerate(srcs, 1)}) - self.assertTrue(same_pk(got, pk_ref(fn, srcs, os_, oh)), hex(got)) - - def test_random_operands_and_modifiers(self): - rng = random.Random(0xADD2) - pool = [0x0000, 0x8000, ONE, 0xBC00, TWO, HALF, THREE, MAXH, 0xFBFF, INF, NINF, QNAN, MIN_NORMAL, MIN_SUB, - 0x8001, MAX_SUB, 0x3C01, 0x6800, 0x6801, 0x4C00, 0x1000, 0x9000] - for _ in range(150): - op = rng.choice(sorted(OPS)) - n, fn = OPS[op] - srcs = [P(*[rng.choice(pool) if rng.random() < 0.5 else rng.getrandbits(16) for _ in range(2)]) - for _ in range(n)] - os_, oh = [rng.getrandbits(1) for _ in range(n)], [rng.getrandbits(1) for _ in range(n)] - nl, nh = [rng.getrandbits(1) for _ in range(n)], [rng.getrandbits(1) for _ in range(n)] - with self.subTest(op=op, src=[hex(s) for s in srcs], mods=(os_, oh, nl, nh)): - got = run(f"{op} v0, {regs(n)}{mods_text(os_, oh, nl, nh)}", {f"v{i}": s for i, s in enumerate(srcs, 1)}) - self.assertTrue(same_pk(got, pk_ref(fn, srcs, os_, oh, nl, nh)), hex(got)) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_valu_pk_fma_f16.py b/tests/semantic/test_valu_pk_fma_f16.py deleted file mode 100644 index c8d2f2617..000000000 --- a/tests/semantic/test_valu_pk_fma_f16.py +++ /dev/null @@ -1,165 +0,0 @@ -"""v_pk_fma_f16 (RDNA2 VOP3P): D.f16[i] = S0.f16[i] * S1.f16[i] + S2.f16[i] for both halves, one rounding per half. - -Every case is translated by tools/rdna2spirv.py and executed with tests/semantic/spirv_mini_interp.py. The expected -words are written down by hand (from the ISA) next to each case; the plain-Python binary16 reference in -tests/semantic/f16_ref.py rechecks them lane by lane and drives seeded random operands and modifier combinations. -Covers per-lane results, op_sel / op_sel_hi half selection, neg_lo / neg_hi, clamp and SGPR sources. -Standard library only: no GPU, no LLVM, no game data. -""" -import os -import random -import sys -import unittest - -HERE = os.path.dirname(os.path.abspath(__file__)) -sys.dont_write_bytecode = True -sys.path.insert(0, HERE) -import support # noqa: E402 -from f16_ref import clamp01, ref_fma, same_f16 # noqa: E402 - -ONE, TWO, THREE, HALF, QUARTER = 0x3C00, 0x4000, 0x4200, 0x3800, 0x3400 -MAXH, INF, NINF, QNAN = 0x7BFF, 0x7C00, 0xFC00, 0x7E00 -MIN_NORMAL, MIN_SUB, MAX_SUB = 0x0400, 0x0001, 0x03FF - - -def P(lo, hi): - """A dword holding two binary16 values.""" - return (hi << 16) | lo - - -def run(line, seeds, old=0xDEADBEEF): - """Run one instruction on a one-lane pixel shader and return v0 as exported to mrt0 (seeds map reg -> dword).""" - prog = [f"v_mov_b32 v0, {old:#x}"] - for reg, w in seeds.items(): - prog.append(f"{'s' if reg[0] == 's' else 'v'}_mov_b32 {reg}, {w:#x}") - prog += [line, "exp mrt0 v0, v0, v0, v0 done vm", "s_endpgm"] - return support.mrt0_words(support.translate_lines("ps_pk_fma_f16", prog))[0] - - -def half(w, i): - return (w >> (16 * i)) & 0xFFFF - - -def pk_ref(fn, srcs, op_sel=None, op_sel_hi=None, neg_lo=None, neg_hi=None, clamp=False): - """Reference for one packed op: the low result reads half op_sel[i] of source i (negated by neg_lo[i]), the high - result half op_sel_hi[i] (negated by neg_hi[i]); defaults are op_sel 0, op_sel_hi 1, no negation.""" - n = len(srcs) - op_sel, op_sel_hi = op_sel or [0] * n, op_sel_hi or [1] * n - neg_lo, neg_hi = neg_lo or [0] * n, neg_hi or [0] * n - out = [] - for sel, ng in ((op_sel, neg_lo), (op_sel_hi, neg_hi)): - r = fn(*[half(s, h) ^ (0x8000 if g else 0) for s, h, g in zip(srcs, sel, ng)]) - out.append(clamp01(r) if clamp else r) - return P(out[0], out[1]) - - -def same_pk(a, b): - return same_f16(a & 0xFFFF, b & 0xFFFF) and same_f16(a >> 16, b >> 16) - - -def mods_text(op_sel=None, op_sel_hi=None, neg_lo=None, neg_hi=None, clamp=False): - t = "" - for name, v in (("op_sel", op_sel), ("op_sel_hi", op_sel_hi), ("neg_lo", neg_lo), ("neg_hi", neg_hi)): - if v is not None: - t += f" {name}:[{','.join(map(str, v))}]" - return t + (" clamp" if clamp else "") - - -def regs(n): - return ", ".join(f"v{i}" for i in range(1, n + 1)) - - -# mnemonic -> (source count, reference for one lane) -OPS = {"v_pk_fma_f16": (3, ref_fma)} - -# mnemonic -> rows of (source dwords..., D), written by hand; lane 0 is the low half -CASES = { - 'v_pk_fma_f16': [ - (P(TWO, 0x3C01), P(THREE, 0x3C01), P(ONE, 0xBC02), P(0x4700, 0x0010)), # (2 * 3 + 1 = 7, (1+2^-10)^2 - (1+2^-9) = 2^-20 fused) - (P(MAXH, 0x8000), P(TWO, ONE), P(0xFBFF, 0x8000), P(MAXH, 0x8000)), # (131008 - 65504 fused, -0 * 1 + -0 = -0) - (P(HALF, MIN_SUB), P(HALF, HALF), P(QUARTER, MIN_SUB), P(HALF, 0x0002)), # (0.5, 1.5 quanta ties to even) - (P(INF, 0x3E00), P(0x0000, TWO), P(ONE, 0xC200), P(QNAN, 0x0000)), # (inf * 0 = NaN, 1.5 * 2 - 3 = +0) - (P(ONE, ONE), P(ONE, ONE), P(MIN_SUB, QNAN), P(ONE, QNAN)), # (1 + 2^-24 = 1, NaN addend) - ], - -} - -# mnemonic -> (sources, modifier text, D), by hand. S0 = (1.0, 3.0), S1 = (0.5, -0.25), S2 = (0.25, -1.0) as -# (low, high) halves. -S0, S1, S2 = P(ONE, THREE), P(HALF, 0xB400), P(QUARTER, 0xBC00) -MODS = { - 'v_pk_fma_f16': [ - ((S0, S1, S2), "", P(0x3A00, 0xBF00)), # (1 * 0.5 + 0.25, 3 * -0.25 + -1) = (0.75, -1.75) - ((S0, S1, S2), " op_sel:[1,0,0]", P(0x3F00, 0xBF00)), # low: 3 * 0.5 + 0.25 = 1.75 - ((S0, S1, S2), " op_sel:[0,1,1] op_sel_hi:[0,0,0]", P(0xBD00, 0x3A00)), # low: 1 * -0.25 + -1; high: 1 * 0.5 + 0.25 - ((S0, S1, S2), " neg_lo:[1,0,0]", P(0xB400, 0xBF00)), # low: -1 * 0.5 + 0.25 = -0.25 - ((S0, S1, S2), " neg_hi:[0,0,1]", P(0x3A00, 0x3400)), # high: -0.75 + 1 = 0.25 - ((S0, S1, S2), " neg_lo:[0,0,1] neg_hi:[1,0,0]", P(0x3400, 0xB400)), # (0.5 - 0.25, 0.75 - 1) - ((P(TWO, 0xC000), P(ONE, ONE), P(HALF, 0xBC00)), " clamp", P(ONE, 0x0000)), # (2.5, -3) -> (1, 0) - ((P(HALF, HALF), P(HALF, ONE), P(QUARTER, 0x0000)), " clamp", P(HALF, HALF)), # inside [0, 1]: unchanged - ], - -} - - -class PkFmaF16(unittest.TestCase): - def test_hand_written_table_matches_reference(self): - for op, rows in CASES.items(): - for *src, want in rows: - with self.subTest(op=op, src=[hex(s) for s in src]): - self.assertTrue(same_pk(pk_ref(OPS[op][1], src), want), hex(pk_ref(OPS[op][1], src))) - - def test_per_lane_results(self): - for op, rows in CASES.items(): - for *src, want in rows: - with self.subTest(op=op, src=[hex(s) for s in src]): - got = run(f"{op} v0, {regs(len(src))}", {f"v{i}": s for i, s in enumerate(src, 1)}) - self.assertTrue(same_pk(got, want), hex(got)) - - def test_sgpr_sources(self): - for op, rows in CASES.items(): - for *src, want in rows[:6]: - n = len(src) - forms = [("all sgpr", ", ".join(f"s{i}" for i in range(1, n + 1)), {f"s{i}": s for i, s in enumerate(src, 1)}), - ("sgpr src0", ", ".join(["s1"] + [f"v{i}" for i in range(2, n + 1)]), - {"s1": src[0], **{f"v{i}": s for i, s in enumerate(src[1:], 2)}})] - for form, text, seeds in forms: - with self.subTest(op=op, src=[hex(s) for s in src], form=form): - self.assertTrue(same_pk(run(f"{op} v0, {text}", seeds), want)) - - def test_hand_written_modifier_cases(self): - for op, rows in MODS.items(): - for srcs, mods, want in rows: - with self.subTest(op=op, mods=mods): - got = run(f"{op} v0, {regs(len(srcs))}{mods}", {f"v{i}": s for i, s in enumerate(srcs, 1)}) - self.assertTrue(same_pk(got, want), hex(got)) - - def test_every_op_sel_and_op_sel_hi_combination(self): - a, b, c = P(0x3E00, 0xC400), P(0x4900, 0x3A00), P(0xB800, 0x4D00) # distinct halves: 1.5/-4, 10/.75, -.5/20 - for op, (n, fn) in OPS.items(): - srcs = [a, b, c][:n] - for sel in range(1 << n): - for selhi in range(1 << n): - os_, oh = [(sel >> i) & 1 for i in range(n)], [(selhi >> i) & 1 for i in range(n)] - with self.subTest(op=op, op_sel=os_, op_sel_hi=oh): - got = run(f"{op} v0, {regs(n)}{mods_text(os_, oh)}", {f"v{i}": s for i, s in enumerate(srcs, 1)}) - self.assertTrue(same_pk(got, pk_ref(fn, srcs, os_, oh)), hex(got)) - - def test_random_operands_and_modifiers(self): - rng = random.Random(0xF3A2) - pool = [0x0000, 0x8000, ONE, 0xBC00, TWO, HALF, THREE, MAXH, 0xFBFF, INF, NINF, QNAN, MIN_NORMAL, MIN_SUB, - 0x8001, MAX_SUB, 0x3C01, 0x6800, 0x6801, 0x4C00, 0x1000, 0x9000] - for _ in range(150): - op = rng.choice(sorted(OPS)) - n, fn = OPS[op] - srcs = [P(*[rng.choice(pool) if rng.random() < 0.5 else rng.getrandbits(16) for _ in range(2)]) - for _ in range(n)] - os_, oh = [rng.getrandbits(1) for _ in range(n)], [rng.getrandbits(1) for _ in range(n)] - nl, nh = [rng.getrandbits(1) for _ in range(n)], [rng.getrandbits(1) for _ in range(n)] - with self.subTest(op=op, src=[hex(s) for s in srcs], mods=(os_, oh, nl, nh)): - got = run(f"{op} v0, {regs(n)}{mods_text(os_, oh, nl, nh)}", {f"v{i}": s for i, s in enumerate(srcs, 1)}) - self.assertTrue(same_pk(got, pk_ref(fn, srcs, os_, oh, nl, nh)), hex(got)) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_valu_pk_minmax_f16.py b/tests/semantic/test_valu_pk_minmax_f16.py deleted file mode 100644 index 2f05a31e6..000000000 --- a/tests/semantic/test_valu_pk_minmax_f16.py +++ /dev/null @@ -1,205 +0,0 @@ -"""v_pk_min_f16 and v_pk_max_f16 (RDNA2 VOP3P): D.f16[i] = min / max of S0.f16[i] and S1.f16[i] for both halves; a NaN operand loses to the other one. - -Every case is translated by tools/rdna2spirv.py and executed with tests/semantic/spirv_mini_interp.py. The expected -words are written down by hand (from the ISA) next to each case; the plain-Python binary16 reference in -tests/semantic/f16_ref.py rechecks them lane by lane and drives seeded random operands and modifier combinations. -Covers per-lane results, op_sel / op_sel_hi half selection, neg_lo / neg_hi, clamp and SGPR sources. -Standard library only: no GPU, no LLVM, no game data. -""" -import os -import random -import sys -import unittest - -HERE = os.path.dirname(os.path.abspath(__file__)) -sys.dont_write_bytecode = True -sys.path.insert(0, HERE) -import support # noqa: E402 -from f16_ref import clamp01, f16_value, is_nan, same_f16 # noqa: E402 - -ONE, TWO, THREE, HALF, QUARTER = 0x3C00, 0x4000, 0x4200, 0x3800, 0x3400 -MAXH, INF, NINF, QNAN = 0x7BFF, 0x7C00, 0xFC00, 0x7E00 -MIN_NORMAL, MIN_SUB, MAX_SUB = 0x0400, 0x0001, 0x03FF - - -def ref_min(a, b): - """v_min_f16: a NaN operand yields the other operand (both NaN: a NaN); -0 < +0.""" - if is_nan(a) or is_nan(b): - return QNAN if is_nan(a) and is_nan(b) else (b if is_nan(a) else a) - if (a | b) & 0x7FFF == 0: - return a | b # both zero: -0 wins - return a if f16_value(a) < f16_value(b) else b - - -def ref_max(a, b): - """v_max_f16: a NaN operand yields the other operand (both NaN: a NaN); +0 > -0.""" - if is_nan(a) or is_nan(b): - return QNAN if is_nan(a) and is_nan(b) else (b if is_nan(a) else a) - if (a | b) & 0x7FFF == 0: - return a & b - return a if f16_value(a) > f16_value(b) else b - - - -def P(lo, hi): - """A dword holding two binary16 values.""" - return (hi << 16) | lo - - -def run(line, seeds, old=0xDEADBEEF): - """Run one instruction on a one-lane pixel shader and return v0 as exported to mrt0 (seeds map reg -> dword).""" - prog = [f"v_mov_b32 v0, {old:#x}"] - for reg, w in seeds.items(): - prog.append(f"{'s' if reg[0] == 's' else 'v'}_mov_b32 {reg}, {w:#x}") - prog += [line, "exp mrt0 v0, v0, v0, v0 done vm", "s_endpgm"] - return support.mrt0_words(support.translate_lines("ps_pk_minmax_f16", prog))[0] - - -def half(w, i): - return (w >> (16 * i)) & 0xFFFF - - -def pk_ref(fn, srcs, op_sel=None, op_sel_hi=None, neg_lo=None, neg_hi=None, clamp=False): - """Reference for one packed op: the low result reads half op_sel[i] of source i (negated by neg_lo[i]), the high - result half op_sel_hi[i] (negated by neg_hi[i]); defaults are op_sel 0, op_sel_hi 1, no negation.""" - n = len(srcs) - op_sel, op_sel_hi = op_sel or [0] * n, op_sel_hi or [1] * n - neg_lo, neg_hi = neg_lo or [0] * n, neg_hi or [0] * n - out = [] - for sel, ng in ((op_sel, neg_lo), (op_sel_hi, neg_hi)): - r = fn(*[half(s, h) ^ (0x8000 if g else 0) for s, h, g in zip(srcs, sel, ng)]) - out.append(clamp01(r) if clamp else r) - return P(out[0], out[1]) - - -def same_pk(a, b): - return same_f16(a & 0xFFFF, b & 0xFFFF) and same_f16(a >> 16, b >> 16) - - -def mods_text(op_sel=None, op_sel_hi=None, neg_lo=None, neg_hi=None, clamp=False): - t = "" - for name, v in (("op_sel", op_sel), ("op_sel_hi", op_sel_hi), ("neg_lo", neg_lo), ("neg_hi", neg_hi)): - if v is not None: - t += f" {name}:[{','.join(map(str, v))}]" - return t + (" clamp" if clamp else "") - - -def regs(n): - return ", ".join(f"v{i}" for i in range(1, n + 1)) - - -# mnemonic -> (source count, reference for one lane) -OPS = {"v_pk_min_f16": (2, ref_min), "v_pk_max_f16": (2, ref_max)} - -# mnemonic -> rows of (source dwords..., D), written by hand; lane 0 is the low half -CASES = { - 'v_pk_min_f16': [ - (P(ONE, THREE), P(TWO, HALF), P(ONE, HALF)), # (min(1, 2), min(3, 0.5)) - (P(0xBC00, 0x0000), P(ONE, 0x8000), P(0xBC00, 0x8000)), # (min(-1, 1), min(+0, -0) = -0) - (P(0x8000, 0x8000), P(0x0000, 0x8000), P(0x8000, 0x8000)), # (min(-0, +0) = -0, min(-0, -0) = -0) - (P(QNAN, ONE), P(ONE, QNAN), P(ONE, ONE)), # a NaN operand yields the other one - (P(QNAN, INF), P(QNAN, MAXH), P(QNAN, MAXH)), # (both NaN: NaN, min(inf, 65504)) - (P(NINF, MIN_SUB), P(0xFBFF, 0x0000), P(NINF, 0x0000)), # (min(-inf, -65504), min(2^-24, 0)) - (P(0x8001, 0x3C01), P(MIN_SUB, ONE), P(0x8001, ONE)), # (min(-2^-24, 2^-24), min(1 + 2^-10, 1)) - ], - 'v_pk_max_f16': [ - (P(ONE, THREE), P(TWO, HALF), P(TWO, THREE)), # (max(1, 2), max(3, 0.5)) - (P(0xBC00, 0x0000), P(ONE, 0x8000), P(ONE, 0x0000)), # (max(-1, 1), max(+0, -0) = +0) - (P(0x8000, 0x8000), P(0x0000, 0x8000), P(0x0000, 0x8000)), # (max(-0, +0) = +0, max(-0, -0) = -0) - (P(QNAN, ONE), P(ONE, QNAN), P(ONE, ONE)), # a NaN operand yields the other one - (P(QNAN, INF), P(QNAN, MAXH), P(QNAN, INF)), # (both NaN: NaN, max(inf, 65504)) - (P(NINF, MIN_SUB), P(0xFBFF, 0x0000), P(0xFBFF, MIN_SUB)), # (max(-inf, -65504), max(2^-24, 0)) - (P(0x8001, 0x3C01), P(MIN_SUB, ONE), P(MIN_SUB, 0x3C01)), # (max(-2^-24, 2^-24), max(1 + 2^-10, 1)) - ], - -} - -# mnemonic -> (sources, modifier text, D), by hand. S0 = (1.0, 3.0), S1 = (0.5, -0.25), S2 = (0.25, -1.0) as -# (low, high) halves. -S0, S1, S2 = P(ONE, THREE), P(HALF, 0xB400), P(QUARTER, 0xBC00) -MODS = { - 'v_pk_min_f16': [ - ((S0, S1), "", P(0x3800, 0xB400)), # (min(1, 0.5), min(3, -0.25)) - ((S0, S1), " op_sel:[1,0]", P(0x3800, 0xB400)), # low: min(3, 0.5) - ((S0, S1), " op_sel:[0,1] op_sel_hi:[0,0]", P(0xB400, 0x3800)), # low: min(1, -0.25); high: min(1, 0.5) - ((S0, S1), " op_sel:[1,1] op_sel_hi:[0,0]", P(0xB400, 0x3800)), # low: min(3, -0.25); high: min(1, 0.5) - ((S0, S1), " neg_lo:[1,0]", P(0xBC00, 0xB400)), # low: min(-1, 0.5) - ((S0, S1), " neg_hi:[0,1]", P(0x3800, 0x3400)), # high: min(3, 0.25) - ((P(0x3E00, 0xB800), P(TWO, 0xBC00)), " clamp", P(ONE, 0x0000)), # (1.5, -1) -> (1, 0) - ((P(HALF, QUARTER), P(0x3A00, ONE)), " clamp", P(HALF, QUARTER)), # inside [0, 1]: unchanged - ], - 'v_pk_max_f16': [ - ((S0, S1), "", P(ONE, THREE)), # (max(1, 0.5), max(3, -0.25)) - ((S0, S1), " op_sel:[1,0]", P(THREE, THREE)), # low: max(3, 0.5) - ((S0, S1), " op_sel:[0,1] op_sel_hi:[0,0]", P(ONE, ONE)), # low: max(1, -0.25); high: max(1, 0.5) - ((S0, S1), " op_sel:[1,1] op_sel_hi:[0,0]", P(THREE, ONE)), # low: max(3, -0.25); high: max(1, 0.5) - ((S0, S1), " neg_lo:[1,0]", P(HALF, THREE)), # low: max(-1, 0.5) - ((S0, S1), " neg_hi:[0,1]", P(ONE, THREE)), # high: max(3, 0.25) - ((P(0x3E00, 0xB800), P(TWO, 0xBC00)), " clamp", P(ONE, 0x0000)), # (2, -0.5) -> (1, 0) - ((P(HALF, QUARTER), P(0x3A00, ONE)), " clamp", P(0x3A00, ONE)), # inside [0, 1]: unchanged - ], - -} - - -class PkMinMaxF16(unittest.TestCase): - def test_hand_written_table_matches_reference(self): - for op, rows in CASES.items(): - for *src, want in rows: - with self.subTest(op=op, src=[hex(s) for s in src]): - self.assertTrue(same_pk(pk_ref(OPS[op][1], src), want), hex(pk_ref(OPS[op][1], src))) - - def test_per_lane_results(self): - for op, rows in CASES.items(): - for *src, want in rows: - with self.subTest(op=op, src=[hex(s) for s in src]): - got = run(f"{op} v0, {regs(len(src))}", {f"v{i}": s for i, s in enumerate(src, 1)}) - self.assertTrue(same_pk(got, want), hex(got)) - - def test_sgpr_sources(self): - for op, rows in CASES.items(): - for *src, want in rows[:6]: - n = len(src) - forms = [("all sgpr", ", ".join(f"s{i}" for i in range(1, n + 1)), {f"s{i}": s for i, s in enumerate(src, 1)}), - ("sgpr src0", ", ".join(["s1"] + [f"v{i}" for i in range(2, n + 1)]), - {"s1": src[0], **{f"v{i}": s for i, s in enumerate(src[1:], 2)}})] - for form, text, seeds in forms: - with self.subTest(op=op, src=[hex(s) for s in src], form=form): - self.assertTrue(same_pk(run(f"{op} v0, {text}", seeds), want)) - - def test_hand_written_modifier_cases(self): - for op, rows in MODS.items(): - for srcs, mods, want in rows: - with self.subTest(op=op, mods=mods): - got = run(f"{op} v0, {regs(len(srcs))}{mods}", {f"v{i}": s for i, s in enumerate(srcs, 1)}) - self.assertTrue(same_pk(got, want), hex(got)) - - def test_every_op_sel_and_op_sel_hi_combination(self): - a, b, c = P(0x3E00, 0xC400), P(0x4900, 0x3A00), P(0xB800, 0x4D00) # distinct halves: 1.5/-4, 10/.75, -.5/20 - for op, (n, fn) in OPS.items(): - srcs = [a, b, c][:n] - for sel in range(1 << n): - for selhi in range(1 << n): - os_, oh = [(sel >> i) & 1 for i in range(n)], [(selhi >> i) & 1 for i in range(n)] - with self.subTest(op=op, op_sel=os_, op_sel_hi=oh): - got = run(f"{op} v0, {regs(n)}{mods_text(os_, oh)}", {f"v{i}": s for i, s in enumerate(srcs, 1)}) - self.assertTrue(same_pk(got, pk_ref(fn, srcs, os_, oh)), hex(got)) - - def test_random_operands_and_modifiers(self): - rng = random.Random(0x31A5) - pool = [0x0000, 0x8000, ONE, 0xBC00, TWO, HALF, THREE, MAXH, 0xFBFF, INF, NINF, QNAN, MIN_NORMAL, MIN_SUB, - 0x8001, MAX_SUB, 0x3C01, 0x6800, 0x6801, 0x4C00, 0x1000, 0x9000] - for _ in range(150): - op = rng.choice(sorted(OPS)) - n, fn = OPS[op] - srcs = [P(*[rng.choice(pool) if rng.random() < 0.5 else rng.getrandbits(16) for _ in range(2)]) - for _ in range(n)] - os_, oh = [rng.getrandbits(1) for _ in range(n)], [rng.getrandbits(1) for _ in range(n)] - nl, nh = [rng.getrandbits(1) for _ in range(n)], [rng.getrandbits(1) for _ in range(n)] - with self.subTest(op=op, src=[hex(s) for s in srcs], mods=(os_, oh, nl, nh)): - got = run(f"{op} v0, {regs(n)}{mods_text(os_, oh, nl, nh)}", {f"v{i}": s for i, s in enumerate(srcs, 1)}) - self.assertTrue(same_pk(got, pk_ref(fn, srcs, os_, oh, nl, nh)), hex(got)) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_valu_pk_mul_f16.py b/tests/semantic/test_valu_pk_mul_f16.py deleted file mode 100644 index 3c3f453f1..000000000 --- a/tests/semantic/test_valu_pk_mul_f16.py +++ /dev/null @@ -1,168 +0,0 @@ -"""v_pk_mul_f16 (RDNA2 VOP3P): D.f16[i] = S0.f16[i] * S1.f16[i] for both halves, binary16 with round to nearest even. - -Every case is translated by tools/rdna2spirv.py and executed with tests/semantic/spirv_mini_interp.py. The expected -words are written down by hand (from the ISA) next to each case; the plain-Python binary16 reference in -tests/semantic/f16_ref.py rechecks them lane by lane and drives seeded random operands and modifier combinations. -Covers per-lane results, op_sel / op_sel_hi half selection, neg_lo / neg_hi, clamp and SGPR sources. -Standard library only: no GPU, no LLVM, no game data. -""" -import os -import random -import sys -import unittest - -HERE = os.path.dirname(os.path.abspath(__file__)) -sys.dont_write_bytecode = True -sys.path.insert(0, HERE) -import support # noqa: E402 -from f16_ref import clamp01, ref_mul, same_f16 # noqa: E402 - -ONE, TWO, THREE, HALF, QUARTER = 0x3C00, 0x4000, 0x4200, 0x3800, 0x3400 -MAXH, INF, NINF, QNAN = 0x7BFF, 0x7C00, 0xFC00, 0x7E00 -MIN_NORMAL, MIN_SUB, MAX_SUB = 0x0400, 0x0001, 0x03FF - - -def P(lo, hi): - """A dword holding two binary16 values.""" - return (hi << 16) | lo - - -def run(line, seeds, old=0xDEADBEEF): - """Run one instruction on a one-lane pixel shader and return v0 as exported to mrt0 (seeds map reg -> dword).""" - prog = [f"v_mov_b32 v0, {old:#x}"] - for reg, w in seeds.items(): - prog.append(f"{'s' if reg[0] == 's' else 'v'}_mov_b32 {reg}, {w:#x}") - prog += [line, "exp mrt0 v0, v0, v0, v0 done vm", "s_endpgm"] - return support.mrt0_words(support.translate_lines("ps_pk_mul_f16", prog))[0] - - -def half(w, i): - return (w >> (16 * i)) & 0xFFFF - - -def pk_ref(fn, srcs, op_sel=None, op_sel_hi=None, neg_lo=None, neg_hi=None, clamp=False): - """Reference for one packed op: the low result reads half op_sel[i] of source i (negated by neg_lo[i]), the high - result half op_sel_hi[i] (negated by neg_hi[i]); defaults are op_sel 0, op_sel_hi 1, no negation.""" - n = len(srcs) - op_sel, op_sel_hi = op_sel or [0] * n, op_sel_hi or [1] * n - neg_lo, neg_hi = neg_lo or [0] * n, neg_hi or [0] * n - out = [] - for sel, ng in ((op_sel, neg_lo), (op_sel_hi, neg_hi)): - r = fn(*[half(s, h) ^ (0x8000 if g else 0) for s, h, g in zip(srcs, sel, ng)]) - out.append(clamp01(r) if clamp else r) - return P(out[0], out[1]) - - -def same_pk(a, b): - return same_f16(a & 0xFFFF, b & 0xFFFF) and same_f16(a >> 16, b >> 16) - - -def mods_text(op_sel=None, op_sel_hi=None, neg_lo=None, neg_hi=None, clamp=False): - t = "" - for name, v in (("op_sel", op_sel), ("op_sel_hi", op_sel_hi), ("neg_lo", neg_lo), ("neg_hi", neg_hi)): - if v is not None: - t += f" {name}:[{','.join(map(str, v))}]" - return t + (" clamp" if clamp else "") - - -def regs(n): - return ", ".join(f"v{i}" for i in range(1, n + 1)) - - -# mnemonic -> (source count, reference for one lane) -OPS = {"v_pk_mul_f16": (2, ref_mul)} - -# mnemonic -> rows of (source dwords..., D), written by hand; lane 0 is the low half -CASES = { - 'v_pk_mul_f16': [ - (P(0x3E00, TWO), P(TWO, 0xBC00), P(THREE, 0xC000)), # (1.5 * 2, 2 * -1) = (3, -2) - (P(HALF, MAXH), P(HALF, TWO), P(QUARTER, INF)), # (0.25, 65504 * 2 overflows) - (P(MIN_SUB, MIN_NORMAL), P(HALF, HALF), P(0x0000, 0x0200)), # (half a quantum ties to even = 0, 2^-15 subnormal) - (P(0x3C01, 0x5640), P(0x3C01, 0x5640), P(0x3C02, 0x70E2)), # (1 + 2^-9 + 2^-20 rounds down, 100 * 100) - (P(0x0000, 0x8000), P(0xBC00, 0xBC00), P(0x8000, 0x0000)), # (+0 * -1 = -0, -0 * -1 = +0) - (P(INF, QNAN), P(0x0000, ONE), P(QNAN, QNAN)), # (inf * 0 = NaN, NaN * 1 = NaN) - (P(MIN_SUB, 0x4900), P(0x3A00, 0xC100), P(MIN_SUB, 0xCE40)), # (0.75 quantum rounds up, 10 * -2.5 = -25) - ], - -} - -# mnemonic -> (sources, modifier text, D), by hand. S0 = (1.0, 3.0), S1 = (0.5, -0.25), S2 = (0.25, -1.0) as -# (low, high) halves. -S0, S1, S2 = P(ONE, THREE), P(HALF, 0xB400), P(QUARTER, 0xBC00) -MODS = { - 'v_pk_mul_f16': [ - ((S0, S1), "", P(0x3800, 0xBA00)), # (1 * 0.5, 3 * -0.25) - ((S0, S1), " op_sel:[1,0]", P(0x3E00, 0xBA00)), # low: 3 * 0.5 = 1.5 - ((S0, S1), " op_sel:[0,1] op_sel_hi:[0,0]", P(0xB400, 0x3800)), # low: 1 * -0.25; high: 1 * 0.5 - ((S0, S1), " op_sel:[1,1] op_sel_hi:[0,0]", P(0xBA00, 0x3800)), # low: 3 * -0.25; high: 1 * 0.5 - ((S0, S1), " neg_lo:[1,0]", P(0xB800, 0xBA00)), # low: -1 * 0.5 - ((S0, S1), " neg_hi:[0,1]", P(0x3800, 0x3A00)), # high: 3 * 0.25 - ((S0, S1), " neg_lo:[1,1] neg_hi:[1,1]", P(0x3800, 0xBA00)), # (-1 * -0.5, -3 * 0.25) - ((P(THREE, 0xB800), P(HALF, HALF)), " clamp", P(ONE, 0x0000)), # (1.5, -0.25) -> (1, 0) - ((P(HALF, QUARTER), P(HALF, ONE)), " clamp", P(QUARTER, QUARTER)), # inside [0, 1]: unchanged - ], - -} - - -class PkMulF16(unittest.TestCase): - def test_hand_written_table_matches_reference(self): - for op, rows in CASES.items(): - for *src, want in rows: - with self.subTest(op=op, src=[hex(s) for s in src]): - self.assertTrue(same_pk(pk_ref(OPS[op][1], src), want), hex(pk_ref(OPS[op][1], src))) - - def test_per_lane_results(self): - for op, rows in CASES.items(): - for *src, want in rows: - with self.subTest(op=op, src=[hex(s) for s in src]): - got = run(f"{op} v0, {regs(len(src))}", {f"v{i}": s for i, s in enumerate(src, 1)}) - self.assertTrue(same_pk(got, want), hex(got)) - - def test_sgpr_sources(self): - for op, rows in CASES.items(): - for *src, want in rows[:6]: - n = len(src) - forms = [("all sgpr", ", ".join(f"s{i}" for i in range(1, n + 1)), {f"s{i}": s for i, s in enumerate(src, 1)}), - ("sgpr src0", ", ".join(["s1"] + [f"v{i}" for i in range(2, n + 1)]), - {"s1": src[0], **{f"v{i}": s for i, s in enumerate(src[1:], 2)}})] - for form, text, seeds in forms: - with self.subTest(op=op, src=[hex(s) for s in src], form=form): - self.assertTrue(same_pk(run(f"{op} v0, {text}", seeds), want)) - - def test_hand_written_modifier_cases(self): - for op, rows in MODS.items(): - for srcs, mods, want in rows: - with self.subTest(op=op, mods=mods): - got = run(f"{op} v0, {regs(len(srcs))}{mods}", {f"v{i}": s for i, s in enumerate(srcs, 1)}) - self.assertTrue(same_pk(got, want), hex(got)) - - def test_every_op_sel_and_op_sel_hi_combination(self): - a, b, c = P(0x3E00, 0xC400), P(0x4900, 0x3A00), P(0xB800, 0x4D00) # distinct halves: 1.5/-4, 10/.75, -.5/20 - for op, (n, fn) in OPS.items(): - srcs = [a, b, c][:n] - for sel in range(1 << n): - for selhi in range(1 << n): - os_, oh = [(sel >> i) & 1 for i in range(n)], [(selhi >> i) & 1 for i in range(n)] - with self.subTest(op=op, op_sel=os_, op_sel_hi=oh): - got = run(f"{op} v0, {regs(n)}{mods_text(os_, oh)}", {f"v{i}": s for i, s in enumerate(srcs, 1)}) - self.assertTrue(same_pk(got, pk_ref(fn, srcs, os_, oh)), hex(got)) - - def test_random_operands_and_modifiers(self): - rng = random.Random(0x3D2) - pool = [0x0000, 0x8000, ONE, 0xBC00, TWO, HALF, THREE, MAXH, 0xFBFF, INF, NINF, QNAN, MIN_NORMAL, MIN_SUB, - 0x8001, MAX_SUB, 0x3C01, 0x6800, 0x6801, 0x4C00, 0x1000, 0x9000] - for _ in range(150): - op = rng.choice(sorted(OPS)) - n, fn = OPS[op] - srcs = [P(*[rng.choice(pool) if rng.random() < 0.5 else rng.getrandbits(16) for _ in range(2)]) - for _ in range(n)] - os_, oh = [rng.getrandbits(1) for _ in range(n)], [rng.getrandbits(1) for _ in range(n)] - nl, nh = [rng.getrandbits(1) for _ in range(n)], [rng.getrandbits(1) for _ in range(n)] - with self.subTest(op=op, src=[hex(s) for s in srcs], mods=(os_, oh, nl, nh)): - got = run(f"{op} v0, {regs(n)}{mods_text(os_, oh, nl, nh)}", {f"v{i}": s for i, s in enumerate(srcs, 1)}) - self.assertTrue(same_pk(got, pk_ref(fn, srcs, os_, oh, nl, nh)), hex(got)) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_valu_pk_shift_b16.py b/tests/semantic/test_valu_pk_shift_b16.py deleted file mode 100644 index 4ac7ea253..000000000 --- a/tests/semantic/test_valu_pk_shift_b16.py +++ /dev/null @@ -1,289 +0,0 @@ -"""Semantic interpreter tests for RDNA2 packed 16-bit integer shift ops (VOP3P). - -Covers v_pk_lshlrev_b16, v_pk_lshrrev_b16 and v_pk_ashrrev_i16: -- 4-bit shift count masking (& 15) and full 0..15 range on both halves independently. -- Half-word isolation (no carry/borrow or shift bleed between low and high 16-bit lanes). -- Unsigned zero-fill vs signed arithmetic sign-extension in v_pk_ashrrev_i16. -- op_sel / op_sel_hi operand half selection, SGPR/inline/literal sources, destination aliasing. -- Rejection of unsupported modifiers (clamp, neg_lo/neg_hi, mul/div, src neg/abs, malformed op_sel). - -Each test translates a hand-written pixel shader through tools/rdna2spirv.py and executes it in -tests/semantic/spirv_mini_interp.py. Standard library only; no GPU, no game files. -""" -import os -import random -import re -import sys -import unittest - -HERE = os.path.dirname(os.path.abspath(__file__)) -ROOT = os.path.dirname(os.path.dirname(HERE)) -sys.dont_write_bytecode = True -TOOLS_DIR = os.environ.get("LEONIDA_TOOLS_DIR") or os.path.join(ROOT, "tools") -if TOOLS_DIR not in sys.path: - sys.path.insert(0, TOOLS_DIR) -if HERE not in sys.path: - sys.path.insert(0, HERE) - -import rdna2spirv # noqa: E402 -import spirv_mini_interp as si # noqa: E402 -import support # noqa: E402 - -OPS = ("v_pk_lshlrev_b16", "v_pk_lshrrev_b16", "v_pk_ashrrev_i16") -WORDS = ( - 0x00000000, - 0x00010002, - 0x7FFF8000, - 0x80007FFF, - 0x8001FFFF, - 0x8004FFF0, - 0x00FF0100, - 0xFFFFFFFF, -) - - -def s16(x): - x &= 0xFFFF - return x - 0x10000 if x & 0x8000 else x - - -def ref_pk_shift(op, sh_word, val_word, sel=(0, 0), selhi=(1, 1)): - """Independent ISA model for v_pk_lshlrev_b16, v_pk_lshrrev_b16, v_pk_ashrrev_i16.""" - out = 0 - for h, sl in enumerate((sel, selhi)): - amt = (sh_word >> (16 * sl[0])) & 0xF - val = (val_word >> (16 * sl[1])) & 0xFFFF - if op == "v_pk_lshlrev_b16": - r = (val << amt) & 0xFFFF - elif op == "v_pk_lshrrev_b16": - r = val >> amt - elif op == "v_pk_ashrrev_i16": - r = (s16(val) >> amt) & 0xFFFF - else: - raise ValueError(f"unexpected op {op}") - out |= (r & 0xFFFF) << (16 * h) - return out - - -def mod_str(name, bits): - return f" {name}:[{','.join(map(str, bits))}]" - - -def translate_shift(lines): - return support.translate_lines("ps_pk_shift_b16", lines) - - -def run_shift(line, push=None): - prog = [ - "v_mov_b32 v1, s0", - "v_mov_b32 v2, s1", - "v_mov_b32 v0, 0xdeadbeef", - line, - "v_mov_b32 v3, 0", - "v_mov_b32 v4, 0", - "v_mov_b32 v5, 0", - "exp mrt0 v0, v3, v4, v5 done vm", - "s_endpgm", - ] - spv = translate_shift(prog) - return support.mrt0_words(spv, push_constants=push)[0] - - -class PkShiftB16Tests(unittest.TestCase): - def test_reference_sanity(self): - self.assertEqual(ref_pk_shift("v_pk_lshlrev_b16", 0x00130002, 0x8004FFF0), 0x0020FFC0) - self.assertEqual(ref_pk_shift("v_pk_lshrrev_b16", 0x00130002, 0x8004FFF0), 0x10003FFC) - self.assertEqual(ref_pk_shift("v_pk_ashrrev_i16", 0x00130002, 0x8004FFF0), 0xF000FFFC) - self.assertEqual( - ref_pk_shift("v_pk_ashrrev_i16", 0x00130002, 0x8004FFF0, sel=(1, 0), selhi=(0, 1)), - 0xE001FFFE, - ) - - def test_shift_amounts_and_4bit_masking(self): - val = 0x80017FFF - for amt_lo, amt_hi in ((0, 0), (1, 15), (4, 8), (15, 1), (16, 17), (31, 0xFFF3), (0xFFFF, 0x0020)): - sh = (amt_lo & 0xFFFF) | ((amt_hi & 0xFFFF) << 16) - for op in OPS: - with self.subTest(op=op, amt_lo=amt_lo, amt_hi=amt_hi): - got = run_shift(f"{op} v0, v1, v2", push=[sh, val]) - self.assertEqual(got, ref_pk_shift(op, sh, val)) - - def test_signed_vs_unsigned_and_half_isolation(self): - shifts = (0x00010001, 0x0004000F, 0x000F0000, 0x00170013) - for op in OPS: - for sh in shifts: - for val in WORDS: - with self.subTest(op=op, sh=hex(sh), val=hex(val)): - got = run_shift(f"{op} v0, v1, v2", push=[sh, val]) - self.assertEqual(got, ref_pk_shift(op, sh, val)) - - def test_op_sel_and_op_sel_hi_permutations(self): - sh = 0x00070003 - val = 0x81234567 - combos = ( - (None, None, ""), - ([1, 0], [0, 1], ""), - ([0, 1], [1, 0], ""), - ([0, 0], [0, 0], ""), - ([1, 1], [1, 1], ""), - ([1, 1], None, ""), - (None, [0, 0], ""), - ([1, 0], [0, 1], " neg_lo:[0,0] neg_hi:[0,0]"), - ) - for op in OPS: - for sel, selhi, extra in combos: - line = f"{op} v0, v1, v2" - if sel is not None: - line += mod_str("op_sel", sel) - if selhi is not None: - line += mod_str("op_sel_hi", selhi) - line += extra - with self.subTest(op=op, line=line): - got = run_shift(line, push=[sh, val]) - want = ref_pk_shift(op, sh, val, sel or (0, 0), selhi or (1, 1)) - self.assertEqual(got, want) - - def test_constants_sgpr_and_aliasing(self): - # Inline positive constants zero-extend; negative inline constants sign-extend to 32-bit dwords. - cases = ( - ("v_pk_lshlrev_b16 v0, 4, v2", None, [0, 0x12345678], ref_pk_shift("v_pk_lshlrev_b16", 4, 0x12345678)), - ("v_pk_lshlrev_b16 v0, 4, v2 op_sel_hi:[0,1]", None, [0, 0x12345678], - ref_pk_shift("v_pk_lshlrev_b16", 4, 0x12345678, selhi=(0, 1))), - ("v_pk_ashrrev_i16 v0, -1, v2", None, [0, 0x80040008], ref_pk_shift("v_pk_ashrrev_i16", 0xFFFFFFFF, 0x80040008)), - ("v_pk_lshrrev_b16 v0, -16, v2", None, [0, 0x8004FFF0], ref_pk_shift("v_pk_lshrrev_b16", 0xFFFFFFF0, 0x8004FFF0)), - ("v_pk_lshlrev_b16 v0, v1, -16", None, [0x00020001, 0], ref_pk_shift("v_pk_lshlrev_b16", 0x00020001, 0xFFFFFFF0)), - ("v_pk_ashrrev_i16 v0, 0x00040001, v2", None, [0, 0x8000FFF0], - ref_pk_shift("v_pk_ashrrev_i16", 0x00040001, 0x8000FFF0)), - ("v_pk_lshrrev_b16 v0, s0, v2", None, [0x00030005, 0x80F01234], - ref_pk_shift("v_pk_lshrrev_b16", 0x00030005, 0x80F01234)), - ("v_pk_ashrrev_i16 v0, v1, s1", None, [0x00030005, 0x80F01234], - ref_pk_shift("v_pk_ashrrev_i16", 0x00030005, 0x80F01234)), - ) - for line, _, push, want in cases: - with self.subTest(line=line): - self.assertEqual(run_shift(line, push=push), want) - - # Destination aliasing src0 or src1 must still read the original operands. - for op in OPS: - sh, val = 0x00050002, 0x8123F00F - prog_alias0 = [ - "v_mov_b32 v0, s0", - "v_mov_b32 v1, s1", - f"{op} v0, v0, v1", - "v_mov_b32 v2, 0", - "exp mrt0 v0, v2, v2, v2 done vm", - "s_endpgm", - ] - prog_alias1 = [ - "v_mov_b32 v0, s0", - "v_mov_b32 v1, s1", - f"{op} v1, v0, v1", - "v_mov_b32 v2, 0", - "exp mrt0 v1, v2, v2, v2 done vm", - "s_endpgm", - ] - with self.subTest(op=op, alias="dst==src0"): - self.assertEqual( - support.mrt0_words(translate_shift(prog_alias0), push_constants=[sh, val])[0], - ref_pk_shift(op, sh, val), - ) - with self.subTest(op=op, alias="dst==src1"): - self.assertEqual( - support.mrt0_words(translate_shift(prog_alias1), push_constants=[sh, val])[0], - ref_pk_shift(op, sh, val), - ) - - def test_seeded_random_cases(self): - rng = random.Random(0x504B5348) - for op in OPS: - for i in range(24): - sh = rng.getrandbits(32) - val = rng.getrandbits(32) - sel = [rng.randint(0, 1), rng.randint(0, 1)] - selhi = [rng.randint(0, 1), rng.randint(0, 1)] - line = f"{op} v0, v1, v2" + mod_str("op_sel", sel) + mod_str("op_sel_hi", selhi) - with self.subTest(op=op, case=i): - got = run_shift(line, push=[sh, val]) - self.assertEqual(got, ref_pk_shift(op, sh, val, tuple(sel), tuple(selhi))) - - def test_rejected_modifiers(self): - bad_lines = ( - "v_pk_lshlrev_b16 v0, v1, v2 clamp", - "v_pk_lshrrev_b16 v0, v1, v2 clamp", - "v_pk_ashrrev_i16 v0, v1, v2 clamp", - "v_pk_lshlrev_b16 v0, v1, v2 neg_lo:[1,0]", - "v_pk_lshrrev_b16 v0, v1, v2 neg_lo:[0,1]", - "v_pk_ashrrev_i16 v0, v1, v2 neg_hi:[1,0]", - "v_pk_lshlrev_b16 v0, v1, v2 neg_hi:[0,1]", - "v_pk_lshlrev_b16 v0, v1, v2 mul:2", - "v_pk_lshrrev_b16 v0, v1, v2 div:2", - "v_pk_lshlrev_b16 v0, v1, -v2", - "v_pk_ashrrev_i16 v0, |v1|, v2", - # a three-entry op_sel is llvm-mc gfx1013 syntax (runtime/test/shaders/ps_ops6.asm) and is accepted - "v_pk_lshlrev_b16 v0, v1, v2 op_sel:[0,0,0,0]", - "v_pk_lshrrev_b16 v0, v1, v2 op_sel_hi:[1]", - "v_pk_ashrrev_i16 v0, v1, v2 op_sel:[0,2]", - "v_pk_lshlrev_b16 v0, v1, v2 op_sel:bad", - ) - for line in bad_lines: - with self.subTest(line=line): - with self.assertRaises(rdna2spirv.Unsupported): - translate_shift([ - "v_mov_b32 v1, 1", - "v_mov_b32 v2, 2", - line, - "exp mrt0 v0, v0, v0, v0 done vm", - "s_endpgm", - ]) - - def test_negative_controls(self): - # 1. Sabotaging signed 16-bit extraction to unsigned must lose sign-extension on negative halves. - spv_ashr = translate_shift([ - "v_mov_b32 v1, s0", - "v_mov_b32 v2, s1", - "v_pk_ashrrev_i16 v0, v1, v2", - "v_mov_b32 v3, 0", - "exp mrt0 v0, v3, v3, v3 done vm", - "s_endpgm", - ]) - self.assertIn("OpBitFieldSExtract", spv_ashr) - sabotaged_ashr = spv_ashr.replace("OpBitFieldSExtract", "OpBitFieldUExtract") - push = [0x00020002, 0x8004FFF0] - self.assertEqual(support.mrt0_words(spv_ashr, push_constants=push)[0], 0xE001FFFC) - self.assertNotEqual(support.mrt0_words(sabotaged_ashr, push_constants=push)[0], 0xE001FFFC) - - # 2. Sabotaging the 4-bit shift count mask to 5 bits must fail when shift count == 16. - spv_lshl = translate_shift([ - "v_mov_b32 v1, s0", - "v_mov_b32 v2, s1", - "v_pk_lshlrev_b16 v0, v1, v2", - "v_mov_b32 v3, 0", - "exp mrt0 v0, v3, v3, v3 done vm", - "s_endpgm", - ]) - m = re.search(r"=\s*OpBitFieldUExtract\s+%uint\s+%\S+\s+%\S+\s+(%\S+)\n", spv_lshl) - self.assertIsNotNone(m) - const4 = m.group(1) - m5 = re.search(r"^(%\S+)\s*=\s*OpConstant\s+%uint\s+5\s*$", spv_lshl, re.M) - if m5: - const5 = m5.group(1) - sabotaged_mask = re.sub( - r"(OpBitFieldUExtract\s+%uint\s+%\S+\s+%\S+\s+)" + re.escape(const4) + r"\b", - r"\1" + const5, - spv_lshl, - ) - else: - sabotaged_mask = re.sub( - r"^" + re.escape(const4) + r"\s*=\s*OpConstant\s+%uint\s+4\s*$", - f"{const4} = OpConstant %uint 5", - spv_lshl, - flags=re.M, - ) - self.assertNotEqual(sabotaged_mask, spv_lshl) - push16 = [0x00100010, 0x12345678] - self.assertEqual(support.mrt0_words(spv_lshl, push_constants=push16)[0], 0x12345678) - self.assertNotEqual(support.mrt0_words(sabotaged_mask, push_constants=push16)[0], 0x12345678) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_valu_rcp_f16.py b/tests/semantic/test_valu_rcp_f16.py deleted file mode 100644 index a31bc2823..000000000 --- a/tests/semantic/test_valu_rcp_f16.py +++ /dev/null @@ -1,44 +0,0 @@ -"""v_rcp_f16 (RDNA2 VOP1 / VOP3): D.f16 = 1.0 / S0.f16, correctly rounded (0 ulp on every non-NaN input on hardware, -docs/design.md "f16 transcendentals"), with rcp(+-0) = +-inf and rcp(+-inf) = +-0. - -Every case is translated by tools/rdna2spirv.py and executed with tests/semantic/spirv_mini_interp.py; the expected -word is written down by hand (from the ISA) next to each case, rechecked against the plain-Python reference in -tests/semantic/f16_unary_cases.py, and extended with seeded random operands, neg/abs, omod/clamp, op_sel, and SGPR / -literal / inline-constant sources. A NaN result is compared by class, not payload. Standard library only. -""" -import os -import sys -import unittest - -sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) -from f16_unary_cases import (HALF, INF, MAXH, MAX_SUB, MIN_NORMAL, MIN_SUB, NINF, ONE, QNAN, QUARTER, TWO, # noqa: E402 - UnaryF16, ref_rcp, run, same_f16) - - -class RcpF16(UnaryF16, unittest.TestCase): - OP = "v_rcp_f16" - ref = staticmethod(ref_rcp) - CASES = [ - (ONE, ONE), (TWO, HALF), (HALF, TWO), (QUARTER, 0x4400), (0x4400, QUARTER), - (0xBC00, 0xBC00), (0xC000, 0xB800), # rcp(-1) = -1, rcp(-2) = -0.5 - (0x4200, 0x3555), # 1/3 = 0.33333 -> 0x3555 (0.333251953125) - (0x4500, 0x3266), # 1/5 = 0.2 -> 0x3266 (0.199951171875) - (0x0000, INF), (0x8000, NINF), # rcp(+-0) = +-inf - (INF, 0x0000), (NINF, 0x8000), # rcp(+-inf) = +-0 - (QNAN, QNAN), - (MAXH, 0x0100), # 1/65504 = 1.5267e-5 = 256.1 * 2^-24 -> the subnormal 0x0100 - (MIN_NORMAL, 0x7400), # 1/2^-14 = 2^14 = 16384 - (MAX_SUB, 0x7401), # 16777216 / 1023 = 16400.06, ulp 16 there -> 16400 - (0x0100, INF), # 1/2^-16 = 65536 overflows - (MIN_SUB, INF), # 1/2^-24 = 2^24 overflows - (0x8001, NINF), - ] - MOD_INPUTS = [0x4400, 0x4000, 0x4900, 0xC400] # 4, 2, 10, -4 - INLINE = [("2.0", TWO, HALF), ("4.0", 0x4400, QUARTER), ("0.5", HALF, TWO), ("-1.0", 0xBC00, 0xBC00), - ("1.0", ONE, ONE), ("-4.0", 0xC400, 0xB400)] - # low half 4.0 / high half 0.5: rcp = 0.25 / 2.0 - OP_SEL = [((HALF << 16) | 0x4400, QUARTER, TWO)] - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_valu_rcp_f64.py b/tests/semantic/test_valu_rcp_f64.py deleted file mode 100644 index eb6112698..000000000 --- a/tests/semantic/test_valu_rcp_f64.py +++ /dev/null @@ -1,1444 +0,0 @@ -"""Semantic reference tests and mathematical oracle for AMD RDNA2 v_rcp_f64. - -RDNA2 Vector Arithmetic Logic Unit (VALU) Architecture: - In AMD RDNA2 (GFX10/GFX1030) ISA, vector registers (VGPRs) are 32 bits wide. - Operations on 64-bit double-precision floating-point quantities (binary64, IEEE 754) - operate across aligned pairs of adjacent registers: v[d:d+1] from source operand - v[s0:s0+1] (or scalar SGPR pair s[k:k+1], literal 64-bit constant, or inline constant). - - Instruction: - v_rcp_f64 v[d:d+1], src0 [clamp] [omod] - - Reciprocal definition: - D.f64 = 1.0 / S0.f64 - - IEEE-754 binary64 encoding: - - 1 sign bit (bit 63) - - 11 exponent bits with bias 1023 (bits 62:52) - - 52 mantissa / fraction bits (bits 51:0) - -Standard library only: Python 3.9+ compatible, zero game data, zero external dependencies. -""" -from __future__ import annotations - -import abc -from dataclasses import dataclass -import enum -import math -import struct -import unittest - -MASK32 = 0xFFFFFFFF -MASK64 = 0xFFFFFFFFFFFFFFFF - -# IEEE-754 binary64 bit constants -F64_POS_ZERO = 0x0000000000000000 -F64_NEG_ZERO = 0x8000000000000000 -F64_POS_INF = 0x7FF0000000000000 -F64_NEG_INF = 0xFFF0000000000000 -F64_CANONICAL_QNAN = 0x7FF8000000000000 -F64_QUIET_BIT = 0x0008000000000000 - -F64_EXP_MASK = 0x7FF0000000000000 -F64_MANT_MASK = 0x000FFFFFFFFFFFFF -F64_SIGN_MASK = 0x8000000000000000 - -F64_ONE = 0x3FF0000000000000 # 1.0 -F64_NEG_ONE = 0xBFF0000000000000 # -1.0 -F64_TWO = 0x4000000000000000 # 2.0 -F64_HALF = 0x3FE0000000000000 # 0.5 -F64_FOUR = 0x4010000000000000 # 4.0 -F64_QUARTER = 0x3FD0000000000000 # 0.25 -F64_MIN_NORMAL = 0x0010000000000000 # 2^-1022 -F64_MAX_NORMAL = 0x7FEFFFFFFFFFFFFF # (2 - 2^-52) * 2^1023 -F64_MIN_SUBNORMAL = 0x0000000000000001 # 2^-1074 -F64_MAX_SUBNORMAL = 0x000FFFFFFFFFFFFF - -OLD_VGPR_SENTINEL = 0xDEADBEEF - - -def u32(val: int) -> int: - """Normalize integer to unsigned 32-bit range [0, 2^32 - 1].""" - return val & MASK32 - - -def u64(val: int) -> int: - """Normalize integer to unsigned 64-bit range [0, 2^64 - 1].""" - return val & MASK64 - - -def split_dwords(val64: int) -> tuple[int, int]: - """Split an unsigned 64-bit integer into (low_dword, high_dword).""" - val = val64 & MASK64 - return val & MASK32, (val >> 32) & MASK32 - - -def join_dwords(lo: int, hi: int) -> int: - """Join (low_dword, high_dword) into an unsigned 64-bit integer.""" - return ((hi & MASK32) << 32) | (lo & MASK32) - - -def f64_to_u64(val: float) -> int: - """Pack an IEEE-754 double precision float into an unsigned 64-bit integer.""" - try: - return struct.unpack(" float: - """Unpack an unsigned 64-bit integer into an IEEE-754 double precision float.""" - return struct.unpack(" bool: - """Return True if the 64-bit pattern represents an IEEE-754 NaN.""" - return ((bits & F64_EXP_MASK) == F64_EXP_MASK) and ((bits & F64_MANT_MASK) != 0) - - -def is_f64_snan(bits: int) -> bool: - """Return True if the 64-bit pattern represents a signaling NaN.""" - return is_f64_nan(bits) and ((bits & F64_QUIET_BIT) == 0) - - -def is_f64_qnan(bits: int) -> bool: - """Return True if the 64-bit pattern represents a quiet NaN.""" - return is_f64_nan(bits) and ((bits & F64_QUIET_BIT) != 0) - - -def is_f64_zero(bits: int) -> bool: - """Return True if the 64-bit pattern represents +0.0 or -0.0.""" - return (bits & (F64_EXP_MASK | F64_MANT_MASK)) == 0 - - -def is_f64_inf(bits: int) -> bool: - """Return True if the 64-bit pattern represents +inf or -inf.""" - return ((bits & F64_EXP_MASK) == F64_EXP_MASK) and ((bits & F64_MANT_MASK) == 0) - - -def is_f64_subnormal(bits: int) -> bool: - """Return True if the 64-bit pattern represents a subnormal/denormal float.""" - return ((bits & F64_EXP_MASK) == 0) and ((bits & F64_MANT_MASK) != 0) - - -def is_f64_normal(bits: int) -> bool: - """Return True if the 64-bit pattern represents a normalized finite float.""" - exp = (bits >> 52) & 0x7FF - return 0 < exp < 0x7FF - - -def f64_sign(bits: int) -> int: - """Return the sign bit (0 or 1).""" - return (bits >> 63) & 1 - - -def quiet_f64(bits: int) -> int: - """Force an IEEE-754 double NaN to quiet by setting the quiet bit.""" - return (bits & MASK64) | F64_QUIET_BIT - - -def apply_input_modifiers_f64(bits: int, *, neg: bool = False, abs_val: bool = False) -> int: - """Apply VOP3 input modifiers (abs, neg). - - In RDNA2 ISA: - When both abs and neg are set, abs is evaluated before neg: - i.e. neg(abs(x)) forces the sign bit to 1 (negative). - """ - res = bits & MASK64 - if abs_val: - res &= ~F64_SIGN_MASK - if neg: - res ^= F64_SIGN_MASK - return res - - -def apply_f64_clamp(bits: int) -> int: - """Clamp double precision value to [0.0, 1.0]. NaN clamps to +0.0.""" - if is_f64_nan(bits): - return F64_POS_ZERO - val = u64_to_f64(bits) - if val < 0.0 or is_f64_zero(bits): - return F64_POS_ZERO - elif val > 1.0 or is_f64_inf(bits): - return F64_ONE - return bits & MASK64 - - -def ref_rcp_f64( - src0_bits: int, - *, - clamp: bool = False, - src0_neg: bool = False, - src0_abs: bool = False, -) -> int: - """Reference mathematical oracle for RDNA2 double-precision reciprocal v_rcp_f64. - - Evaluates: - D.f64 = 1.0 / S0.f64 - accounting for IEEE-754 binary64 rules, input modifiers (neg, abs), and clamp [0.0, 1.0]. - """ - s0 = apply_input_modifiers_f64(src0_bits, neg=src0_neg, abs_val=src0_abs) - sign = f64_sign(s0) - - # NaN input yields quiet NaN - if is_f64_nan(s0): - res = quiet_f64(s0) - # 1.0 / +-0.0 = +-Inf - elif is_f64_zero(s0): - res = F64_NEG_INF if sign else F64_POS_INF - # 1.0 / +-Inf = +-0.0 - elif is_f64_inf(s0): - res = F64_NEG_ZERO if sign else F64_POS_ZERO - else: - val0 = u64_to_f64(s0) - try: - recip = 1.0 / val0 - res = f64_to_u64(recip) - if is_f64_zero(res): - res = F64_NEG_ZERO if sign else F64_POS_ZERO - elif is_f64_inf(res): - res = F64_NEG_INF if sign else F64_POS_INF - except OverflowError: - res = F64_NEG_INF if sign else F64_POS_INF - - if clamp: - res = apply_f64_clamp(res) - - return res & MASK64 - - -def ref_rcp_f64_dwords( - s0_lo: int, - s0_hi: int, - *, - clamp: bool = False, - src0_neg: bool = False, - src0_abs: bool = False, -) -> tuple[int, int]: - """Decomposed dword interface for v_rcp_f64.""" - s0 = join_dwords(s0_lo, s0_hi) - res = ref_rcp_f64(s0, clamp=clamp, src0_neg=src0_neg, src0_abs=src0_abs) - return split_dwords(res) - - -class VALURegisterFile: - """Architectural model for RDNA2 VALU 32-bit vector register file.""" - - def __init__(self, num_vgprs: int = 256) -> None: - self.num_vgprs = num_vgprs - self.regs = [0] * num_vgprs - - def get_vgpr(self, idx: int) -> int: - if not (0 <= idx < self.num_vgprs): - raise IndexError(f"VGPR index out of range: {idx}") - return self.regs[idx] & MASK32 - - def set_vgpr(self, idx: int, val: int) -> None: - if not (0 <= idx < self.num_vgprs): - raise IndexError(f"VGPR index out of range: {idx}") - self.regs[idx] = val & MASK32 - - def get_vgpr_pair(self, idx: int) -> int: - if not (0 <= idx < self.num_vgprs - 1): - raise IndexError(f"VGPR pair index out of range: v[{idx}:{idx+1}]") - lo = self.get_vgpr(idx) - hi = self.get_vgpr(idx + 1) - return join_dwords(lo, hi) - - def set_vgpr_pair(self, idx: int, val64: int) -> None: - if not (0 <= idx < self.num_vgprs - 1): - raise IndexError(f"VGPR pair index out of range: v[{idx}:{idx+1}]") - lo, hi = split_dwords(val64) - self.set_vgpr(idx, lo) - self.set_vgpr(idx + 1, hi) - - -# ============================================================================== -# Symbolic AST Opcode Definitions and Typed Expressions for v_rcp_f64 -# ============================================================================== - -class OperandKind(enum.Enum): - VGPR_PAIR = "vgpr_pair" - SGPR_PAIR = "sgpr_pair" - LITERAL_64 = "literal_64" - INLINE_IMM = "inline_imm" - - -@dataclass -class ASTOperand: - kind: OperandKind - reg_idx: int = 0 - imm_val: int = 0 - neg: bool = False - abs_val: bool = False - - def format_asm(self) -> str: - if self.kind == OperandKind.VGPR_PAIR: - s = f"v[{self.reg_idx}:{self.reg_idx + 1}]" - elif self.kind == OperandKind.SGPR_PAIR: - s = f"s[{self.reg_idx}:{self.reg_idx + 1}]" - elif self.kind == OperandKind.LITERAL_64: - s = f"0x{self.imm_val:016x}" - elif self.kind == OperandKind.INLINE_IMM: - s = f"{self.imm_val}" - else: - s = "unknown" - if self.abs_val: - s = f"|{s}|" - if self.neg: - s = f"-{s}" - return s - - -@dataclass -class ASTInstruction: - opcode: str - dst: ASTOperand - src0: ASTOperand - clamp: bool = False - omod: int = 0 - - def validate(self) -> None: - if self.opcode != "v_rcp_f64": - raise ValueError(f"Invalid opcode for v_rcp_f64 AST: {self.opcode}") - if self.dst.kind != OperandKind.VGPR_PAIR: - raise ValueError(f"Destination must be a VGPR pair, got {self.dst.kind}") - if not (0 <= self.dst.reg_idx <= 254): - raise ValueError(f"Destination VGPR pair index out of range: {self.dst.reg_idx}") - if self.dst.neg or self.dst.abs_val: - raise ValueError("Destination operand cannot have neg or abs modifiers") - if self.src0.kind == OperandKind.VGPR_PAIR: - if not (0 <= self.src0.reg_idx <= 254): - raise ValueError(f"src0 VGPR pair index out of range: {self.src0.reg_idx}") - elif self.src0.kind == OperandKind.SGPR_PAIR: - if not (0 <= self.src0.reg_idx <= 104): - raise ValueError(f"src0 SGPR pair index out of range: {self.src0.reg_idx}") - - def format_asm(self) -> str: - s = f"{self.opcode} {self.dst.format_asm()}, {self.src0.format_asm()}" - if self.clamp: - s += " clamp" - return s - - -class F64Expression(abc.ABC): - @abc.abstractmethod - def evaluate(self, env: dict[str, int]) -> int: - pass - - -@dataclass -class F64Constant(F64Expression): - bits: int - - def evaluate(self, env: dict[str, int]) -> int: - return self.bits & MASK64 - - -@dataclass -class F64Variable(F64Expression): - name: str - - def evaluate(self, env: dict[str, int]) -> int: - if self.name not in env: - raise KeyError(f"Variable {self.name} not found in environment") - return env[self.name] & MASK64 - - -@dataclass -class F64UnaryOp(F64Expression): - op: str # "abs", "neg", "neg_abs" - operand: F64Expression - - def evaluate(self, env: dict[str, int]) -> int: - val = self.operand.evaluate(env) - if self.op == "abs": - return apply_input_modifiers_f64(val, abs_val=True) - elif self.op == "neg": - return apply_input_modifiers_f64(val, neg=True) - elif self.op == "neg_abs": - return apply_input_modifiers_f64(val, neg=True, abs_val=True) - raise ValueError(f"Unknown unary operator: {self.op}") - - -@dataclass -class F64Rcp(F64Expression): - operand: F64Expression - clamp: bool = False - - def evaluate(self, env: dict[str, int]) -> int: - val = self.operand.evaluate(env) - return ref_rcp_f64(val, clamp=self.clamp) - - -def instruction_to_expression(inst: ASTInstruction) -> F64Rcp: - """Translate an ASTInstruction to a typed symbolic expression tree.""" - inst.validate() - - def build_operand_expr(op: ASTOperand, prefix: str) -> F64Expression: - if op.kind in (OperandKind.VGPR_PAIR, OperandKind.SGPR_PAIR): - expr: F64Expression = F64Variable(f"{prefix}_{op.reg_idx}") - elif op.kind in (OperandKind.LITERAL_64, OperandKind.INLINE_IMM): - expr = F64Constant(op.imm_val) - else: - raise ValueError(f"Unsupported operand kind: {op.kind}") - - if op.abs_val and op.neg: - expr = F64UnaryOp("neg_abs", expr) - elif op.abs_val: - expr = F64UnaryOp("abs", expr) - elif op.neg: - expr = F64UnaryOp("neg", expr) - return expr - - src_expr = build_operand_expr(inst.src0, "src0") - return F64Rcp(operand=src_expr, clamp=inst.clamp) - - -# ============================================================================== -# Deterministic Scalar Instruction Interpreter for v_rcp_f64 -# ============================================================================== - -def parse_asm_operand(tok: str) -> ASTOperand: - tok = tok.strip() - neg = False - abs_val = False - if tok.startswith("-"): - neg = True - tok = tok[1:].strip() - if tok.startswith("|") and tok.endswith("|"): - abs_val = True - tok = tok[1:-1].strip() - - if tok.startswith("v[") and tok.endswith("]"): - inner = tok[2:-1] - parts = inner.split(":") - reg_idx = int(parts[0]) - return ASTOperand(kind=OperandKind.VGPR_PAIR, reg_idx=reg_idx, neg=neg, abs_val=abs_val) - elif tok.startswith("s[") and tok.endswith("]"): - inner = tok[2:-1] - parts = inner.split(":") - reg_idx = int(parts[0]) - return ASTOperand(kind=OperandKind.SGPR_PAIR, reg_idx=reg_idx, neg=neg, abs_val=abs_val) - elif tok.startswith("0x") or tok.startswith("0X"): - imm = int(tok, 16) - return ASTOperand(kind=OperandKind.LITERAL_64, imm_val=imm, neg=neg, abs_val=abs_val) - else: - try: - if "." in tok or "e" in tok.lower(): - imm = f64_to_u64(float(tok)) - return ASTOperand(kind=OperandKind.LITERAL_64, imm_val=imm, neg=neg, abs_val=abs_val) - imm = int(tok) - return ASTOperand(kind=OperandKind.INLINE_IMM, imm_val=imm, neg=neg, abs_val=abs_val) - except ValueError: - raise ValueError(f"Unrecognized assembly operand token: {tok}") - - -def parse_asm_line(line: str) -> ASTInstruction: - clean = line.split(";")[0].split("//")[0].strip() - tokens = [t for t in clean.replace(",", " ").split() if t] - if not tokens: - raise ValueError("Empty assembly line") - opcode = tokens[0] - if opcode != "v_rcp_f64": - raise ValueError(f"Expected opcode v_rcp_f64, got {opcode}") - - clamp = False - raw_ops = [] - for tok in tokens[1:]: - if tok.lower() == "clamp": - clamp = True - else: - raw_ops.append(tok) - - if len(raw_ops) != 2: - raise ValueError(f"v_rcp_f64 requires 2 operands (dst, src0), got {len(raw_ops)}: {raw_ops}") - - dst = parse_asm_operand(raw_ops[0]) - src0 = parse_asm_operand(raw_ops[1]) - inst = ASTInstruction(opcode=opcode, dst=dst, src0=src0, clamp=clamp) - inst.validate() - return inst - - -class ScalarInterpreter: - """Deterministic scalar instruction interpreter for RDNA2 VALU v_rcp_f64.""" - - def __init__(self, num_vgprs: int = 256, num_sgprs: int = 106) -> None: - self.vgpr = VALURegisterFile(num_vgprs=num_vgprs) - self.num_sgprs = num_sgprs - self.sgprs = [0] * num_sgprs - self.vcc = 0 - self.scc = 0 - - def get_sgpr(self, idx: int) -> int: - if not (0 <= idx < self.num_sgprs): - raise IndexError(f"SGPR index out of range: {idx}") - return self.sgprs[idx] & MASK32 - - def set_sgpr(self, idx: int, val: int) -> None: - if not (0 <= idx < self.num_sgprs): - raise IndexError(f"SGPR index out of range: {idx}") - self.sgprs[idx] = val & MASK32 - - def get_sgpr_pair(self, idx: int) -> int: - if not (0 <= idx < self.num_sgprs - 1): - raise IndexError(f"SGPR pair index out of range: s[{idx}:{idx+1}]") - lo = self.get_sgpr(idx) - hi = self.get_sgpr(idx + 1) - return join_dwords(lo, hi) - - def set_sgpr_pair(self, idx: int, val64: int) -> None: - if not (0 <= idx < self.num_sgprs - 1): - raise IndexError(f"SGPR pair index out of range: s[{idx}:{idx+1}]") - lo, hi = split_dwords(val64) - self.set_sgpr(idx, lo) - self.set_sgpr(idx + 1, hi) - - def resolve_operand(self, op: ASTOperand) -> int: - if op.kind == OperandKind.VGPR_PAIR: - val = self.vgpr.get_vgpr_pair(op.reg_idx) - elif op.kind == OperandKind.SGPR_PAIR: - val = self.get_sgpr_pair(op.reg_idx) - elif op.kind == OperandKind.LITERAL_64: - val = op.imm_val - elif op.kind == OperandKind.INLINE_IMM: - val = op.imm_val - else: - raise ValueError(f"Unknown operand kind: {op.kind}") - return apply_input_modifiers_f64(val, neg=op.neg, abs_val=op.abs_val) - - def execute_ast(self, inst: ASTInstruction) -> int: - inst.validate() - s0 = self.resolve_operand(inst.src0) - res = ref_rcp_f64(s0, clamp=inst.clamp) - self.vgpr.set_vgpr_pair(inst.dst.reg_idx, res) - return res - - def execute_asm(self, line: str) -> int: - inst = parse_asm_line(line) - return self.execute_ast(inst) - - -# ============================================================================== -# SIMD Wavefront Execution Model (Wave32 / Wave64) for v_rcp_f64 -# ============================================================================== - -def ref_simd_rcp_f64( - src0_lanes: list[int], - wave_size: int = 64, - exec_mask: int | None = None, - prev_dst: list[int] | None = None, - *, - clamp: bool = False, - src0_neg: bool = False, - src0_abs: bool = False, -) -> list[int]: - """Reference SIMD execution oracle across wavefront lanes.""" - if wave_size not in (32, 64): - raise ValueError(f"Unsupported wave size: {wave_size}") - if len(src0_lanes) != wave_size: - raise ValueError(f"Operand length must match wave_size ({wave_size})") - - active_mask = (1 << wave_size) - 1 if exec_mask is None else (exec_mask & ((1 << wave_size) - 1)) - fallback = [0] * wave_size if prev_dst is None else prev_dst - if len(fallback) != wave_size: - raise ValueError(f"prev_dst length must match wave_size ({wave_size})") - - output = list(fallback) - for lane in range(wave_size): - if (active_mask >> lane) & 1: - output[lane] = ref_rcp_f64( - src0_lanes[lane], - clamp=clamp, - src0_neg=src0_neg, - src0_abs=src0_abs, - ) - return output - - -class SIMDWavefront: - """SIMD wavefront simulator modeling multi-lane execution and EXEC masking.""" - - def __init__(self, wave_size: int = 64, num_vgprs: int = 256) -> None: - if wave_size not in (32, 64): - raise ValueError(f"Wave size must be 32 or 64, got {wave_size}") - self.wave_size = wave_size - self.num_vgprs = num_vgprs - self.lanes = [VALURegisterFile(num_vgprs=num_vgprs) for _ in range(wave_size)] - self.exec_mask = (1 << wave_size) - 1 - self.vcc = 0 - self.sgprs = [0] * 106 - - def store_vgpr_pair_wave(self, reg_idx: int, values: list[int]) -> None: - if len(values) != self.wave_size: - raise ValueError(f"Value count ({len(values)}) does not match wave_size ({self.wave_size})") - for lane in range(self.wave_size): - self.lanes[lane].set_vgpr_pair(reg_idx, values[lane]) - - def load_vgpr_pair_wave(self, reg_idx: int) -> list[int]: - return [self.lanes[lane].get_vgpr_pair(reg_idx) for lane in range(self.wave_size)] - - def step_v_rcp_f64( - self, - dst_reg: int, - src0_reg: int, - *, - clamp: bool = False, - src0_neg: bool = False, - src0_abs: bool = False, - ) -> list[int]: - active_mask = self.exec_mask & ((1 << self.wave_size) - 1) - for lane in range(self.wave_size): - if (active_mask >> lane) & 1: - s0 = self.lanes[lane].get_vgpr_pair(src0_reg) - res = ref_rcp_f64( - s0, - clamp=clamp, - src0_neg=src0_neg, - src0_abs=src0_abs, - ) - self.lanes[lane].set_vgpr_pair(dst_reg, res) - return self.load_vgpr_pair_wave(dst_reg) - - -class TestSIMDMultiLaneDivergence(unittest.TestCase): - """Test suite for SIMD multi-lane divergence and 32/64-bit EXEC masking.""" - - def test_wave32_all_active(self) -> None: - sim = SIMDWavefront(wave_size=32) - s0_vals = [f64_to_u64(float(i + 1)) for i in range(32)] - sim.store_vgpr_pair_wave(2, s0_vals) - - res = sim.step_v_rcp_f64(0, 2) - for i in range(32): - self.assertEqual(u64_to_f64(res[i]), 1.0 / (i + 1)) - - def test_wave64_all_active(self) -> None: - sim = SIMDWavefront(wave_size=64) - s0_vals = [f64_to_u64(float(i + 1) * 2.0) for i in range(64)] - sim.store_vgpr_pair_wave(2, s0_vals) - - res = sim.step_v_rcp_f64(0, 2) - for i in range(64): - self.assertEqual(u64_to_f64(res[i]), 1.0 / ((i + 1) * 2.0)) - - def test_wave32_divergent_exec_mask(self) -> None: - sim = SIMDWavefront(wave_size=32) - sentinel_pair = join_dwords(OLD_VGPR_SENTINEL, OLD_VGPR_SENTINEL) - sim.store_vgpr_pair_wave(0, [sentinel_pair] * 32) - - s0_vals = [f64_to_u64(4.0)] * 32 - sim.store_vgpr_pair_wave(2, s0_vals) - - # Alternating lanes active: 0b0101... - sim.exec_mask = 0x55555555 - res = sim.step_v_rcp_f64(0, 2) - - for lane in range(32): - if lane % 2 == 0: - self.assertEqual(u64_to_f64(res[lane]), 0.25) - else: - self.assertEqual(res[lane], sentinel_pair) - - def test_wave64_divergent_exec_mask(self) -> None: - sim = SIMDWavefront(wave_size=64) - sentinel_pair = join_dwords(OLD_VGPR_SENTINEL, OLD_VGPR_SENTINEL) - sim.store_vgpr_pair_wave(0, [sentinel_pair] * 64) - - s0_vals = [f64_to_u64(2.0)] * 64 - sim.store_vgpr_pair_wave(2, s0_vals) - - # Lower 32 lanes active, upper 32 inactive - sim.exec_mask = 0x00000000_FFFFFFFF - res = sim.step_v_rcp_f64(0, 2) - - for lane in range(32): - self.assertEqual(u64_to_f64(res[lane]), 0.5) - for lane in range(32, 64): - self.assertEqual(res[lane], sentinel_pair) - - def test_wave32_upper_exec_bits_ignored(self) -> None: - sim = SIMDWavefront(wave_size=32) - sentinel_pair = join_dwords(OLD_VGPR_SENTINEL, OLD_VGPR_SENTINEL) - sim.store_vgpr_pair_wave(0, [sentinel_pair] * 32) - sim.store_vgpr_pair_wave(2, [f64_to_u64(2.0)] * 32) - - # In Wave32, upper 32 bits of exec_mask must have no effect - sim.exec_mask = 0xDEADBEEF_FFFFFFFF - res = sim.step_v_rcp_f64(0, 2) - for lane in range(32): - self.assertEqual(u64_to_f64(res[lane]), 0.5) - - def test_simd_oracle_validation(self) -> None: - wave_size = 64 - s0_vals = [f64_to_u64(float(i + 1.25)) for i in range(wave_size)] - exec_mask = 0xAAAAAAAAAAAAAAAA - - prev_dst = [join_dwords(0xCAFE, i) for i in range(wave_size)] - expected = ref_simd_rcp_f64(s0_vals, wave_size=wave_size, exec_mask=exec_mask, prev_dst=prev_dst) - - sim = SIMDWavefront(wave_size=wave_size) - sim.store_vgpr_pair_wave(0, prev_dst) - sim.store_vgpr_pair_wave(2, s0_vals) - sim.exec_mask = exec_mask - - actual = sim.step_v_rcp_f64(0, 2) - self.assertEqual(actual, expected) - - -# ============================================================================== -# Register Aliasing and In-Place Operand Preservation for v_rcp_f64 -# ============================================================================== - -class TestRegisterAliasing(unittest.TestCase): - """Test suite for register aliasing and in-place operand preservation.""" - - def test_inplace_dst_equals_src0(self) -> None: - interp = ScalarInterpreter() - interp.vgpr.set_vgpr_pair(4, F64_FOUR) - - # v[4:5] = 1.0 / v[4:5] -> 0.25 - res = interp.execute_asm("v_rcp_f64 v[4:5], v[4:5]") - self.assertEqual(u64_to_f64(res), 0.25) - self.assertEqual(interp.vgpr.get_vgpr_pair(4), f64_to_u64(0.25)) - - def test_inplace_self_inversion_cycle(self) -> None: - interp = ScalarInterpreter() - initial = f64_to_u64(16.0) - interp.vgpr.set_vgpr_pair(2, initial) - - # 1st reciprocal: 16.0 -> 0.0625 - res1 = interp.execute_asm("v_rcp_f64 v[2:3], v[2:3]") - self.assertEqual(u64_to_f64(res1), 0.0625) - self.assertEqual(interp.vgpr.get_vgpr_pair(2), res1) - - # 2nd reciprocal: 0.0625 -> 16.0 - res2 = interp.execute_asm("v_rcp_f64 v[2:3], v[2:3]") - self.assertEqual(u64_to_f64(res2), 16.0) - self.assertEqual(interp.vgpr.get_vgpr_pair(2), initial) - - def test_partially_overlapping_register_pairs(self) -> None: - interp = ScalarInterpreter() - s0_val = f64_to_u64(4.0) - interp.vgpr.set_vgpr_pair(0, s0_val) - interp.vgpr.set_vgpr(2, 0x11223344) - - v0_before = interp.vgpr.get_vgpr(0) - - # Execute with dst as unaligned v[1:2] overlapping src0 v[0:1] (via v1) - dst = ASTOperand(kind=OperandKind.VGPR_PAIR, reg_idx=1) - src0 = ASTOperand(kind=OperandKind.VGPR_PAIR, reg_idx=0) - inst = ASTInstruction(opcode="v_rcp_f64", dst=dst, src0=src0) - res = interp.execute_ast(inst) - - self.assertEqual(u64_to_f64(res), 0.25) - self.assertEqual(interp.vgpr.get_vgpr_pair(1), f64_to_u64(0.25)) - # Non-overlapping boundary dword v[0] must remain completely unchanged - self.assertEqual(interp.vgpr.get_vgpr(0), v0_before) - - def test_reverse_overlapping_register_pairs(self) -> None: - interp = ScalarInterpreter() - s0_val = f64_to_u64(8.0) - interp.vgpr.set_vgpr_pair(1, s0_val) - interp.vgpr.set_vgpr(3, 0x55667788) - - v3_before = interp.vgpr.get_vgpr(3) - - # Execute with dst v[0:1] overlapping src0 v[1:2] (via v1) - dst = ASTOperand(kind=OperandKind.VGPR_PAIR, reg_idx=0) - src0 = ASTOperand(kind=OperandKind.VGPR_PAIR, reg_idx=1) - inst = ASTInstruction(opcode="v_rcp_f64", dst=dst, src0=src0) - res = interp.execute_ast(inst) - - self.assertEqual(u64_to_f64(res), 0.125) - self.assertEqual(interp.vgpr.get_vgpr_pair(0), f64_to_u64(0.125)) - # Boundary dword v[3] remains completely intact - self.assertEqual(interp.vgpr.get_vgpr(3), v3_before) - - def test_simd_inplace_divergent_mask(self) -> None: - sim = SIMDWavefront(wave_size=32) - init_vals = [f64_to_u64(float(i + 1) * 2.0) for i in range(32)] - sim.store_vgpr_pair_wave(0, init_vals) - - # Active on odd lanes only: 0xAAAAAAAA - sim.exec_mask = 0xAAAAAAAA - res = sim.step_v_rcp_f64(0, 0) - - for lane in range(32): - if lane % 2 == 1: - # Active lane: inverted - self.assertEqual(u64_to_f64(res[lane]), 1.0 / ((lane + 1) * 2.0)) - else: - # Inactive lane: preserved original - self.assertEqual(res[lane], init_vals[lane]) - - def test_consecutive_chain_distinct_registers(self) -> None: - interp = ScalarInterpreter() - interp.vgpr.set_vgpr_pair(0, f64_to_u64(2.0)) - - # v[2:3] = 1 / v[0:1] = 0.5 - interp.execute_asm("v_rcp_f64 v[2:3], v[0:1]") - # v[4:5] = 1 / v[2:3] = 2.0 - interp.execute_asm("v_rcp_f64 v[4:5], v[2:3]") - # v[6:7] = 1 / v[4:5] = 0.5 - interp.execute_asm("v_rcp_f64 v[6:7], v[4:5]") - - self.assertEqual(u64_to_f64(interp.vgpr.get_vgpr_pair(0)), 2.0) - self.assertEqual(u64_to_f64(interp.vgpr.get_vgpr_pair(2)), 0.5) - self.assertEqual(u64_to_f64(interp.vgpr.get_vgpr_pair(4)), 2.0) - self.assertEqual(u64_to_f64(interp.vgpr.get_vgpr_pair(6)), 0.5) - - -# ============================================================================== -# Condition Codes, Status Flags, and Carry/Borrow Isolation for v_rcp_f64 -# ============================================================================== - -@dataclass -class StatusFlags: - invalid_op: bool = False - div_by_zero: bool = False - overflow: bool = False - underflow: bool = False - inexact: bool = False - zero: bool = False - negative: bool = False - nan: bool = False - - -def compute_rcp_f64_status_flags(src0: int, result: int) -> StatusFlags: - flags = StatusFlags() - s0 = src0 & MASK64 - res = result & MASK64 - - # Invalid operation: SNaN operand - if is_f64_snan(s0): - flags.invalid_op = True - - # Division by zero: 1.0 / +-0.0 - if is_f64_zero(s0): - flags.div_by_zero = True - - if is_f64_nan(res): - flags.nan = True - else: - flags.negative = bool(f64_sign(res)) - if is_f64_zero(res): - flags.zero = True - # Finite non-zero input producing zero is underflow - if not is_f64_inf(s0): - flags.underflow = True - flags.inexact = True - elif is_f64_inf(res): - # Finite non-zero input producing inf is overflow - if not is_f64_zero(s0): - flags.overflow = True - flags.inexact = True - else: - # Check inexact: test if val0 * res == 1.0 exactly - v0 = u64_to_f64(s0) - vr = u64_to_f64(res) - if v0 * vr != 1.0: - flags.inexact = True - - return flags - - -def ref_cmp_f64(op: str, src0: int, src1: int) -> bool: - """Evaluate double-precision IEEE-754 comparison condition codes.""" - if op in ("u", "unordered"): - return is_f64_nan(src0) or is_f64_nan(src1) - - if is_f64_nan(src0) or is_f64_nan(src1): - return op in ("neq", "ne", "!=") - - v0 = u64_to_f64(src0) - v1 = u64_to_f64(src1) - if op in ("eq", "=="): - return v0 == v1 - elif op in ("ne", "neq", "!="): - return v0 != v1 - elif op in ("lt", "<"): - return v0 < v1 - elif op in ("le", "<="): - return v0 <= v1 - elif op in ("gt", ">"): - return v0 > v1 - elif op in ("ge", ">="): - return v0 >= v1 - raise ValueError(f"Unknown comparison operator: {op}") - - -def generate_condition_mask_f64(op: str, src0_lanes: list[int], src1_lanes: list[int]) -> int: - """Generate a 32-bit or 64-bit condition mask (VCC) from per-lane comparisons.""" - mask = 0 - for lane, (s0, s1) in enumerate(zip(src0_lanes, src1_lanes)): - if ref_cmp_f64(op, s0, s1): - mask |= (1 << lane) - return mask - - -class TestConditionCodesAndStatusFlags(unittest.TestCase): - """Test suite for condition codes, status flags, and carry/borrow isolation.""" - - def test_status_flags_div_by_zero(self) -> None: - # 1.0 / +0.0 = +Inf - res = ref_rcp_f64(F64_POS_ZERO) - flags = compute_rcp_f64_status_flags(F64_POS_ZERO, res) - self.assertTrue(flags.div_by_zero) - self.assertFalse(flags.invalid_op) - self.assertFalse(flags.negative) - - # 1.0 / -0.0 = -Inf - res_neg = ref_rcp_f64(F64_NEG_ZERO) - flags_neg = compute_rcp_f64_status_flags(F64_NEG_ZERO, res_neg) - self.assertTrue(flags_neg.div_by_zero) - self.assertTrue(flags_neg.negative) - - def test_status_flags_invalid_operation(self) -> None: - # SNaN input - snan = (F64_POS_INF | 0x0001000000000000) & ~F64_QUIET_BIT - res_snan = ref_rcp_f64(snan) - flags_snan = compute_rcp_f64_status_flags(snan, res_snan) - self.assertTrue(flags_snan.invalid_op) - self.assertTrue(flags_snan.nan) - - def test_status_flags_overflow(self) -> None: - # Subnormal input reciprocal overflows to infinity - res = ref_rcp_f64(F64_MIN_SUBNORMAL) - flags = compute_rcp_f64_status_flags(F64_MIN_SUBNORMAL, res) - self.assertTrue(flags.overflow) - self.assertTrue(flags.inexact) - self.assertEqual(res, F64_POS_INF) - - def test_status_flags_zero_and_negative(self) -> None: - # 1.0 / -2.0 = -0.5 (negative, non-zero) - v0 = f64_to_u64(-2.0) - r1 = ref_rcp_f64(v0) - flags1 = compute_rcp_f64_status_flags(v0, r1) - self.assertTrue(flags1.negative) - self.assertFalse(flags1.zero) - - # 1.0 / -Inf = -0.0 (negative zero) - r2 = ref_rcp_f64(F64_NEG_INF) - flags2 = compute_rcp_f64_status_flags(F64_NEG_INF, r2) - self.assertTrue(flags2.negative) - self.assertTrue(flags2.zero) - - def test_vcc_and_scc_preserved(self) -> None: - # Floating point v_rcp_f64 does not generate carry/borrow and never modifies VCC or SCC - interp = ScalarInterpreter() - interp.vcc = 0x12345678_9ABCDEF0 - interp.scc = 1 - interp.vgpr.set_vgpr_pair(2, F64_FOUR) - - interp.execute_asm("v_rcp_f64 v[0:1], v[2:3]") - self.assertEqual(interp.vcc, 0x12345678_9ABCDEF0) - self.assertEqual(interp.scc, 1) - - sim = SIMDWavefront(wave_size=32) - sim.vcc = 0xCAFEBABE - sim.store_vgpr_pair_wave(2, [F64_TWO] * 32) - sim.step_v_rcp_f64(0, 2) - self.assertEqual(sim.vcc, 0xCAFEBABE) - - def test_condition_code_generation(self) -> None: - v_zero = [F64_POS_ZERO] * 4 - # Four inputs: [-2.0, +Inf, 2.0, NaN] - # Their reciprocals: [-0.5, +0.0, 0.5, NaN] - s0 = [f64_to_u64(-2.0), F64_POS_INF, f64_to_u64(2.0), F64_CANONICAL_QNAN] - rcps = [ref_rcp_f64(x) for x in s0] - - # Compare < 0: only lane 0 (-0.5 < 0) -> bit 0 - mask_lt = generate_condition_mask_f64("<", rcps, v_zero) - self.assertEqual(mask_lt, 0b0001) - - # Compare == 0: only lane 1 (+0.0 == 0) -> bit 1 - mask_eq = generate_condition_mask_f64("==", rcps, v_zero) - self.assertEqual(mask_eq, 0b0010) - - # Compare > 0: only lane 2 (0.5 > 0) -> bit 2 - mask_gt = generate_condition_mask_f64(">", rcps, v_zero) - self.assertEqual(mask_gt, 0b0100) - - # Compare unordered: only lane 3 (NaN) -> bit 3 - mask_u = generate_condition_mask_f64("u", rcps, v_zero) - self.assertEqual(mask_u, 0b1000) - - -# ============================================================================== -# IEEE 754 Boundary Extremes, Subnormals, and NaN Handling for v_rcp_f64 -# ============================================================================== - -DBL_MIN = 0x0010000000000000 # 2^-1022 -DBL_MAX = 0x7FEFFFFFFFFFFFFF # ~1.7976931348623157e+308 -NEG_DBL_MIN = 0x8010000000000000 -NEG_DBL_MAX = 0xFFEFFFFFFFFFFFFF - -SUBNORM_MIN = 0x0000000000000001 # 2^-1074 -SUBNORM_MAX = 0x000FFFFFFFFFFFFF -NEG_SUBNORM_MIN = 0x8000000000000001 -NEG_SUBNORM_MAX = 0x800FFFFFFFFFFFFF - -QNAN_PAYLOAD_A = 0x7FF8000000000001 -QNAN_PAYLOAD_B = 0x7FF8AAAAAAAAAAAA -SNAN_F64 = 0x7FF0000000000001 -NEG_SNAN_F64 = 0xFFF0000000000001 - - -class TestIEEE754Boundaries(unittest.TestCase): - """Exhaustive unit tests for IEEE 754 boundary extremes, subnormals, and NaN handling.""" - - def test_signed_zero_boundary(self) -> None: - self.assertEqual(ref_rcp_f64(F64_POS_ZERO), F64_POS_INF) - self.assertEqual(ref_rcp_f64(F64_NEG_ZERO), F64_NEG_INF) - - # Input modifiers on zeros - self.assertEqual(ref_rcp_f64(F64_NEG_ZERO, src0_abs=True), F64_POS_INF) - self.assertEqual(ref_rcp_f64(F64_POS_ZERO, src0_neg=True), F64_NEG_INF) - self.assertEqual(ref_rcp_f64(F64_NEG_ZERO, src0_neg=True), F64_POS_INF) - - def test_infinities_boundary(self) -> None: - self.assertEqual(ref_rcp_f64(F64_POS_INF), F64_POS_ZERO) - self.assertEqual(ref_rcp_f64(F64_NEG_INF), F64_NEG_ZERO) - - # Input modifiers on infinities - self.assertEqual(ref_rcp_f64(F64_NEG_INF, src0_abs=True), F64_POS_ZERO) - self.assertEqual(ref_rcp_f64(F64_POS_INF, src0_neg=True), F64_NEG_ZERO) - self.assertEqual(ref_rcp_f64(F64_NEG_INF, src0_neg=True), F64_POS_ZERO) - - def test_subnormals_overflow(self) -> None: - # Minimum subnormal (2^-1074) reciprocal overflows binary64 to signed infinity - self.assertEqual(ref_rcp_f64(SUBNORM_MIN), F64_POS_INF) - self.assertEqual(ref_rcp_f64(NEG_SUBNORM_MIN), F64_NEG_INF) - - # Maximum subnormal (2^-1022 * (1 - 2^-52)) reciprocal is a finite normal float (~4.49e307) - res_sub_max = ref_rcp_f64(SUBNORM_MAX) - self.assertTrue(is_f64_normal(res_sub_max)) - self.assertAlmostEqual(u64_to_f64(res_sub_max), 1.0 / u64_to_f64(SUBNORM_MAX)) - - def test_normal_extrema(self) -> None: - # 1.0 / DBL_MIN = 2^1022 - exp_val = 2.0 ** 1022 - self.assertEqual(ref_rcp_f64(DBL_MIN), f64_to_u64(exp_val)) - self.assertEqual(ref_rcp_f64(NEG_DBL_MIN), f64_to_u64(-exp_val)) - - # 1.0 / DBL_MAX produces a tiny positive subnormal (~5.56e-309 < 2^-1022) - res_max = ref_rcp_f64(DBL_MAX) - self.assertEqual(f64_sign(res_max), 0) - self.assertTrue(is_f64_subnormal(res_max)) - self.assertAlmostEqual(u64_to_f64(res_max), 1.0 / u64_to_f64(DBL_MAX)) - - # 1.0 / NEG_DBL_MAX produces a tiny negative subnormal - res_neg_max = ref_rcp_f64(NEG_DBL_MAX) - self.assertEqual(f64_sign(res_neg_max), 1) - self.assertTrue(is_f64_subnormal(res_neg_max)) - self.assertAlmostEqual(u64_to_f64(res_neg_max), 1.0 / u64_to_f64(NEG_DBL_MAX)) - - def test_nan_handling_and_quieting(self) -> None: - nans = [F64_CANONICAL_QNAN, QNAN_PAYLOAD_A, QNAN_PAYLOAD_B, SNAN_F64, NEG_SNAN_F64] - for n in nans: - with self.subTest(nan=f"{n:#018x}"): - res = ref_rcp_f64(n) - self.assertTrue(is_f64_nan(res)) - self.assertTrue(is_f64_qnan(res)) - - def test_boundary_extremes_with_clamp(self) -> None: - # +0.0 -> +Inf clamped to 1.0 - self.assertEqual(ref_rcp_f64(F64_POS_ZERO, clamp=True), F64_ONE) - # -0.0 -> -Inf clamped to +0.0 - self.assertEqual(ref_rcp_f64(F64_NEG_ZERO, clamp=True), F64_POS_ZERO) - # +Inf -> +0.0 clamped to +0.0 - self.assertEqual(ref_rcp_f64(F64_POS_INF, clamp=True), F64_POS_ZERO) - # -Inf -> -0.0 clamped to +0.0 - self.assertEqual(ref_rcp_f64(F64_NEG_INF, clamp=True), F64_POS_ZERO) - # Subnormals clamped - self.assertEqual(ref_rcp_f64(SUBNORM_MIN, clamp=True), F64_ONE) - self.assertEqual(ref_rcp_f64(NEG_SUBNORM_MIN, clamp=True), F64_POS_ZERO) - # NaNs clamped to +0.0 - self.assertEqual(ref_rcp_f64(F64_CANONICAL_QNAN, clamp=True), F64_POS_ZERO) - self.assertEqual(ref_rcp_f64(SNAN_F64, clamp=True), F64_POS_ZERO) - - -# ============================================================================== -# Negative Controls, Syntax Rejection, and Mutation Detection for v_rcp_f64 -# ============================================================================== - -class TestNegativeControlsAndMutations(unittest.TestCase): - """Test suite for negative controls, syntax rejection, and mutation detection.""" - - def test_syntax_rejection_empty_and_whitespace(self) -> None: - with self.assertRaises(ValueError): - parse_asm_line("") - with self.assertRaises(ValueError): - parse_asm_line(" ; comment only") - - def test_syntax_rejection_wrong_opcode(self) -> None: - with self.assertRaises(ValueError): - parse_asm_line("v_rcp_f32 v[0:1], v[2:3]") - with self.assertRaises(ValueError): - parse_asm_line("v_mul_f64 v[0:1], v[2:3]") - - def test_syntax_rejection_wrong_operand_count(self) -> None: - # Zero source operands - with self.assertRaises(ValueError): - parse_asm_line("v_rcp_f64 v[0:1]") - # Two source operands (v_rcp_f64 takes only one source operand!) - with self.assertRaises(ValueError): - parse_asm_line("v_rcp_f64 v[0:1], v[2:3], v[4:5]") - - def test_syntax_rejection_invalid_operand_tokens(self) -> None: - with self.assertRaises(ValueError): - parse_asm_operand("invalid_token") - with self.assertRaises(ValueError): - parse_asm_operand("m[0:1]") - - def test_syntax_rejection_out_of_bounds_registers(self) -> None: - # Destination VGPR > 254 - inst_bad_dst = ASTInstruction( - opcode="v_rcp_f64", - dst=ASTOperand(OperandKind.VGPR_PAIR, reg_idx=256), - src0=ASTOperand(OperandKind.VGPR_PAIR, reg_idx=0), - ) - with self.assertRaises(ValueError): - inst_bad_dst.validate() - - # Source SGPR > 104 - inst_bad_src = ASTInstruction( - opcode="v_rcp_f64", - dst=ASTOperand(OperandKind.VGPR_PAIR, reg_idx=0), - src0=ASTOperand(OperandKind.SGPR_PAIR, reg_idx=106), - ) - with self.assertRaises(ValueError): - inst_bad_src.validate() - - def test_syntax_rejection_illegal_dst_modifier(self) -> None: - inst_neg_dst = ASTInstruction( - opcode="v_rcp_f64", - dst=ASTOperand(OperandKind.VGPR_PAIR, reg_idx=0, neg=True), - src0=ASTOperand(OperandKind.VGPR_PAIR, reg_idx=2), - ) - with self.assertRaises(ValueError): - inst_neg_dst.validate() - - inst_abs_dst = ASTInstruction( - opcode="v_rcp_f64", - dst=ASTOperand(OperandKind.VGPR_PAIR, reg_idx=0, abs_val=True), - src0=ASTOperand(OperandKind.VGPR_PAIR, reg_idx=2), - ) - with self.assertRaises(ValueError): - inst_abs_dst.validate() - - def test_negative_simd_wave_sizes_and_lengths(self) -> None: - with self.assertRaises(ValueError): - SIMDWavefront(wave_size=16) - with self.assertRaises(ValueError): - SIMDWavefront(wave_size=128) - - # ref_simd_rcp_f64 with invalid wave size - with self.assertRaises(ValueError): - ref_simd_rcp_f64([0] * 16, wave_size=16) - - # ref_simd_rcp_f64 with length mismatch - with self.assertRaises(ValueError): - ref_simd_rcp_f64([0] * 32, wave_size=64) - - def test_negative_register_file_bounds(self) -> None: - rf = VALURegisterFile(num_vgprs=16) - with self.assertRaises(IndexError): - rf.get_vgpr(-1) - with self.assertRaises(IndexError): - rf.get_vgpr(16) - with self.assertRaises(IndexError): - rf.get_vgpr_pair(15) - with self.assertRaises(IndexError): - rf.set_vgpr_pair(15, 0) - - def test_mutation_zero_reciprocal_sign_detection(self) -> None: - # A buggy oracle that fails to propagate sign on 1.0 / -0.0 - def mutated_oracle(src: int) -> int: - if is_f64_zero(src): - return F64_POS_INF # Bug: always positive infinity - return ref_rcp_f64(src) - - correct = ref_rcp_f64(F64_NEG_ZERO) - buggy = mutated_oracle(F64_NEG_ZERO) - self.assertNotEqual(buggy, correct) - self.assertEqual(correct, F64_NEG_INF) - - def test_mutation_clamp_nan_to_zero_detection(self) -> None: - # A buggy clamp that leaves NaN intact instead of clamping to +0.0 - def mutated_clamp(src: int) -> int: - res = ref_rcp_f64(src) - return res # Bug: misses clamp on NaN - - correct = ref_rcp_f64(F64_CANONICAL_QNAN, clamp=True) - buggy = mutated_clamp(F64_CANONICAL_QNAN) - self.assertNotEqual(buggy, correct) - self.assertEqual(correct, F64_POS_ZERO) - - def test_mutation_clamp_negative_to_zero_detection(self) -> None: - # A buggy clamp that does not clamp negative values to 0.0 - def mutated_clamp(src: int) -> int: - res = ref_rcp_f64(src) - return res # Bug: misses lower clamp bound 0.0 - - val = f64_to_u64(-2.0) - correct = ref_rcp_f64(val, clamp=True) - buggy = mutated_clamp(val) - self.assertNotEqual(buggy, correct) - self.assertEqual(correct, F64_POS_ZERO) - - def test_mutation_inactive_lane_tampering_detection(self) -> None: - # Verify SIMD step strictly protects inactive lanes - sim = SIMDWavefront(wave_size=32) - sentinel = join_dwords(OLD_VGPR_SENTINEL, OLD_VGPR_SENTINEL) - sim.store_vgpr_pair_wave(0, [sentinel] * 32) - sim.store_vgpr_pair_wave(2, [f64_to_u64(2.0)] * 32) - sim.exec_mask = 0x00000001 # Only lane 0 active - - res = sim.step_v_rcp_f64(0, 2) - self.assertEqual(u64_to_f64(res[0]), 0.5) - for lane in range(1, 32): - self.assertEqual(res[lane], sentinel) - - def test_mutation_abs_neg_modifier_order(self) -> None: - # RDNA2 rule: neg(abs(x)) forces sign to 1. - # If an implementation mistakenly computed abs(neg(x)), sign would be 0 (+0.5). - # We verify that neg=True, abs_val=True forces negative result (-0.5). - res = ref_rcp_f64(f64_to_u64(-2.0), src0_neg=True, src0_abs=True) - self.assertEqual(u64_to_f64(res), -0.5) - self.assertEqual(f64_sign(res), 1) - - -class TestScalarInterpreter(unittest.TestCase): - """Test suite for deterministic scalar instruction interpreter.""" - - def test_execute_vgpr_source(self) -> None: - interp = ScalarInterpreter() - interp.vgpr.set_vgpr_pair(2, F64_FOUR) - - dst = ASTOperand(kind=OperandKind.VGPR_PAIR, reg_idx=0) - src0 = ASTOperand(kind=OperandKind.VGPR_PAIR, reg_idx=2) - inst = ASTInstruction(opcode="v_rcp_f64", dst=dst, src0=src0) - - res = interp.execute_ast(inst) - self.assertEqual(u64_to_f64(res), 0.25) - self.assertEqual(interp.vgpr.get_vgpr_pair(0), res) - - def test_execute_sgpr_source(self) -> None: - interp = ScalarInterpreter() - interp.set_sgpr_pair(4, f64_to_u64(-2.0)) - - dst = ASTOperand(kind=OperandKind.VGPR_PAIR, reg_idx=0) - src0 = ASTOperand(kind=OperandKind.SGPR_PAIR, reg_idx=4) - inst = ASTInstruction(opcode="v_rcp_f64", dst=dst, src0=src0) - - res = interp.execute_ast(inst) - self.assertEqual(u64_to_f64(res), -0.5) - self.assertEqual(interp.vgpr.get_vgpr_pair(0), res) - - def test_execute_literal_source(self) -> None: - interp = ScalarInterpreter() - - dst = ASTOperand(kind=OperandKind.VGPR_PAIR, reg_idx=0) - src0 = ASTOperand(kind=OperandKind.LITERAL_64, imm_val=f64_to_u64(0.125)) - inst = ASTInstruction(opcode="v_rcp_f64", dst=dst, src0=src0) - - res = interp.execute_ast(inst) - self.assertEqual(u64_to_f64(res), 8.0) - self.assertEqual(interp.vgpr.get_vgpr_pair(0), res) - - def test_execute_text_asm(self) -> None: - interp = ScalarInterpreter() - interp.vgpr.set_vgpr_pair(6, f64_to_u64(8.0)) - - res = interp.execute_asm("v_rcp_f64 v[0:1], v[6:7] ; take reciprocal") - self.assertEqual(u64_to_f64(res), 0.125) - self.assertEqual(interp.vgpr.get_vgpr_pair(0), f64_to_u64(0.125)) - - def test_execute_modifiers_and_clamp(self) -> None: - interp = ScalarInterpreter() - interp.vgpr.set_vgpr_pair(2, f64_to_u64(-2.0)) - - # -|v[2:3]| is -2.0, reciprocal is -0.5, clamp produces +0.0 - res = interp.execute_asm("v_rcp_f64 v[0:1], -|v[2:3]| clamp") - self.assertEqual(res, F64_POS_ZERO) - - # Reciprocal of 2.0 is 0.5, within clamp [0, 1] - interp.vgpr.set_vgpr_pair(2, F64_TWO) - res2 = interp.execute_asm("v_rcp_f64 v[0:1], v[2:3] clamp") - self.assertEqual(u64_to_f64(res2), 0.5) - - -class TestSymbolicAST(unittest.TestCase): - """Test suite for symbolic AST definitions and typed expressions.""" - - def test_ast_creation_and_formatting(self) -> None: - dst = ASTOperand(kind=OperandKind.VGPR_PAIR, reg_idx=0) - src0 = ASTOperand(kind=OperandKind.VGPR_PAIR, reg_idx=2) - inst = ASTInstruction(opcode="v_rcp_f64", dst=dst, src0=src0) - inst.validate() - self.assertEqual(inst.format_asm(), "v_rcp_f64 v[0:1], v[2:3]") - - # With clamp and modifiers - src0_mod = ASTOperand(kind=OperandKind.SGPR_PAIR, reg_idx=4, neg=True, abs_val=True) - inst_clamp = ASTInstruction(opcode="v_rcp_f64", dst=dst, src0=src0_mod, clamp=True) - inst_clamp.validate() - self.assertEqual(inst_clamp.format_asm(), "v_rcp_f64 v[0:1], -|s[4:5]| clamp") - - def test_typed_expression_evaluation(self) -> None: - c1 = F64Constant(F64_TWO) - rcp_expr = F64Rcp(operand=c1) - res = rcp_expr.evaluate({}) - self.assertEqual(u64_to_f64(res), 0.5) - - # Unary modifier - neg_c1 = F64UnaryOp("neg", c1) - res_neg = F64Rcp(operand=neg_c1).evaluate({}) - self.assertEqual(u64_to_f64(res_neg), -0.5) - - def test_instruction_to_expression(self) -> None: - dst = ASTOperand(kind=OperandKind.VGPR_PAIR, reg_idx=0) - src0 = ASTOperand(kind=OperandKind.VGPR_PAIR, reg_idx=2, neg=True) - inst = ASTInstruction(opcode="v_rcp_f64", dst=dst, src0=src0, clamp=False) - - expr = instruction_to_expression(inst) - env = {"src0_2": F64_FOUR} - res = expr.evaluate(env) - # 1.0 / (-4.0) = -0.25 - self.assertEqual(u64_to_f64(res), -0.25) - - def test_ast_validation_errors(self) -> None: - # Invalid opcode - bad_op = ASTInstruction( - opcode="v_mul_f64", - dst=ASTOperand(OperandKind.VGPR_PAIR, 0), - src0=ASTOperand(OperandKind.VGPR_PAIR, 2), - ) - with self.assertRaises(ValueError): - bad_op.validate() - - # Destination cannot be SGPR - bad_dst = ASTInstruction( - opcode="v_rcp_f64", - dst=ASTOperand(OperandKind.SGPR_PAIR, 0), - src0=ASTOperand(OperandKind.VGPR_PAIR, 2), - ) - with self.assertRaises(ValueError): - bad_dst.validate() - - # Destination out of bounds - oob_dst = ASTInstruction( - opcode="v_rcp_f64", - dst=ASTOperand(OperandKind.VGPR_PAIR, 256), - src0=ASTOperand(OperandKind.VGPR_PAIR, 2), - ) - with self.assertRaises(ValueError): - oob_dst.validate() - - -class TestVRcpF64ReferenceOracle(unittest.TestCase): - """Test suite for reference mathematical oracle and architectural model.""" - - def test_basic_reciprocal(self) -> None: - # 1.0 / 1.0 = 1.0 - r = ref_rcp_f64(F64_ONE) - self.assertEqual(u64_to_f64(r), 1.0) - - # 1.0 / 2.0 = 0.5 - r = ref_rcp_f64(F64_TWO) - self.assertEqual(u64_to_f64(r), 0.5) - - # 1.0 / 0.5 = 2.0 - r = ref_rcp_f64(F64_HALF) - self.assertEqual(u64_to_f64(r), 2.0) - - # 1.0 / 4.0 = 0.25 - r = ref_rcp_f64(F64_FOUR) - self.assertEqual(u64_to_f64(r), 0.25) - - # 1.0 / -4.0 = -0.25 - r = ref_rcp_f64(f64_to_u64(-4.0)) - self.assertEqual(u64_to_f64(r), -0.25) - - def test_zero_reciprocal_rules(self) -> None: - # 1.0 / +0.0 = +Inf - self.assertEqual(ref_rcp_f64(F64_POS_ZERO), F64_POS_INF) - # 1.0 / -0.0 = -Inf - self.assertEqual(ref_rcp_f64(F64_NEG_ZERO), F64_NEG_INF) - - def test_inf_reciprocal_rules(self) -> None: - # 1.0 / +Inf = +0.0 - self.assertEqual(ref_rcp_f64(F64_POS_INF), F64_POS_ZERO) - # 1.0 / -Inf = -0.0 - self.assertEqual(ref_rcp_f64(F64_NEG_INF), F64_NEG_ZERO) - - def test_nan_reciprocal_rules(self) -> None: - # QNaN propagated with quiet bit - qnan = F64_CANONICAL_QNAN - self.assertTrue(is_f64_nan(ref_rcp_f64(qnan))) - self.assertTrue(is_f64_qnan(ref_rcp_f64(qnan))) - - # SNaN quieted - snan = (F64_POS_INF | 0x0001000000000000) & ~F64_QUIET_BIT - r_snan = ref_rcp_f64(snan) - self.assertTrue(is_f64_nan(r_snan)) - self.assertTrue(is_f64_qnan(r_snan)) - - def test_input_modifiers(self) -> None: - # neg: 1.0 / neg(2.0) = -0.5 - r = ref_rcp_f64(F64_TWO, src0_neg=True) - self.assertEqual(u64_to_f64(r), -0.5) - - # abs: 1.0 / abs(-2.0) = 0.5 - r = ref_rcp_f64(f64_to_u64(-2.0), src0_abs=True) - self.assertEqual(u64_to_f64(r), 0.5) - - # neg + abs: neg(abs(-2.0)) = -2.0 -> 1.0 / -2.0 = -0.5 - r = ref_rcp_f64(f64_to_u64(-2.0), src0_neg=True, src0_abs=True) - self.assertEqual(u64_to_f64(r), -0.5) - - def test_clamp_modifier(self) -> None: - # In range [0.0, 1.0]: 1.0 / 2.0 = 0.5 -> 0.5 - r = ref_rcp_f64(F64_TWO, clamp=True) - self.assertEqual(u64_to_f64(r), 0.5) - - # > 1.0 clamped to 1.0: 1.0 / 0.5 = 2.0 -> 1.0 - r = ref_rcp_f64(F64_HALF, clamp=True) - self.assertEqual(r, F64_ONE) - - # +Inf clamped to 1.0: 1.0 / +0.0 = +Inf -> 1.0 - r = ref_rcp_f64(F64_POS_ZERO, clamp=True) - self.assertEqual(r, F64_ONE) - - # Negative clamped to +0.0: 1.0 / -2.0 = -0.5 -> +0.0 - r = ref_rcp_f64(f64_to_u64(-2.0), clamp=True) - self.assertEqual(r, F64_POS_ZERO) - - # NaN clamped to +0.0 - r = ref_rcp_f64(F64_CANONICAL_QNAN, clamp=True) - self.assertEqual(r, F64_POS_ZERO) - - def test_dword_decomposition(self) -> None: - s0 = f64_to_u64(12.5) - lo, hi = split_dwords(s0) - r_lo, r_hi = ref_rcp_f64_dwords(lo, hi) - res = join_dwords(r_lo, r_hi) - self.assertEqual(u64_to_f64(res), 0.08) - - def test_register_file_pair_access(self) -> None: - rf = VALURegisterFile(num_vgprs=16) - val = 0x01234567_89ABCDEF - rf.set_vgpr_pair(4, val) - - self.assertEqual(rf.get_vgpr(4), 0x89ABCDEF) - self.assertEqual(rf.get_vgpr(5), 0x01234567) - self.assertEqual(rf.get_vgpr_pair(4), val) - - with self.assertRaises(IndexError): - rf.get_vgpr_pair(15) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_valu_rcp_fdiv.py b/tests/semantic/test_valu_rcp_fdiv.py deleted file mode 100644 index 975ee8560..000000000 --- a/tests/semantic/test_valu_rcp_fdiv.py +++ /dev/null @@ -1,1234 +0,0 @@ -"""Semantic value tests for OpFDiv in spirv_mini_interp and RDNA2 reciprocal VALU ops: - - OpFDiv (scalar %float and vector %v2float) directly in tests/semantic/spirv_mini_interp.py - - v_rcp_f32: D.f32 = 1.0 / S0.f32 - - v_rcp_iflag_f32: D.f32 = 1.0 / S0.f32 (no FP flags) - - v_rcp_f16: D.f16 = 1.0 / S0.f16 (preserves the untouched 16-bit half of D) - - Newton-Raphson division iteration pipeline (v_rcp_f32 + v_fma_f32 + v_mul_f32) - - -Per the SPIR-V specification and tests/semantic/README.md, OpFDiv by zero (+-0.0) is undefined and raises -spirv_mini_interp.UnsupportedConstruct("OpFDiv by zero (undefined in SPIR-V)"). Accordingly, finite non-zero, -subnormal, +-inf, and NaN operands are value-checked against independent Fraction-based binary32/binary16 -oracles, while +-0.0 divisors/inputs of the f32 ops are verified to raise UnsupportedConstruct (v_rcp_f16 selects the -ISA's +-inf for +-0 itself). - -NaN payloads are not pinned because values passing through Python floats lose exact NaN payload bits; NaN -results are asserted as binary32/binary16 NaNs. Standard library only; hand-written RDNA2 listings only. -""" -from __future__ import annotations - -from fractions import Fraction -import gc -import itertools -import math -import os -import re -import struct -import sys -import tempfile -import unittest -import warnings - -HERE = os.path.dirname(os.path.abspath(__file__)) -ROOT = os.path.dirname(os.path.dirname(HERE)) -TOOLS_DIR = os.environ.get("LEONIDA_TOOLS_DIR") or os.path.join(ROOT, "tools") - -sys.dont_write_bytecode = True -if TOOLS_DIR not in sys.path: - sys.path.insert(0, TOOLS_DIR) -if HERE not in sys.path: - sys.path.insert(0, HERE) - -import rdna2spirv # noqa: E402 -import spirv_mini_interp as si # noqa: E402 - -MASK32 = 0xFFFFFFFF -STUB_DXBC = b"DXBC" + bytes(24) + struct.pack("= 65520 -> +inf) -H_SUB_2M15 = 0x0200 # 2^-15 (1/x = 32768 = 0x7800) -H_SUB_MAX = 0x03FF # 1023 * 2^-24 -H_NORM_MIN = 0x0400 # 2^-14 (1/x = 16384 = 0x7400) -H_0P25 = 0x3400 # 0.25 -H_NEG_0P25 = 0xB400 # -0.25 -H_0P5 = 0x3800 # 0.5 -H_NEG_0P5 = 0xB800 # -0.5 -H_0P75 = 0x3A00 # 0.75 -H_1P0 = 0x3C00 # 1.0 -H_NEG_1P0 = 0xBC00 # -1.0 -H_NEG_1P25 = 0xBD00 # -1.25 -H_1P5 = 0x3E00 # 1.5 -H_2P0 = 0x4000 # 2.0 -H_NEG_2P0 = 0xC000 # -2.0 -H_3P0 = 0x4200 # 3.0 -H_NEG_3P0 = 0xC200 # -3.0 -H_4P0 = 0x4400 # 4.0 -H_NEG_4P0 = 0xC400 # -4.0 -H_8P0 = 0x4800 # 8.0 -H_16P0 = 0x4C00 # 16.0 -H_1024 = 0x6400 # 1024.0 -H_MAX = 0x7BFF # 65504.0 -H_NEG_MAX = 0xFBFF # -65504.0 -H_POS_INF = 0x7C00 # +inf -H_NEG_INF = 0xFC00 # -inf -H_QNAN = 0x7E01 # +qNaN -H_NEG_QNAN = 0xFE01 # -qNaN -H_SNAN = 0x7C01 # +sNaN - - -def f32_bits(x: float) -> int: - try: - return struct.unpack(" 0 else 0xFF800000 - - -def is_f32_nan_bits(bits: int) -> bool: - return (bits & 0x7F800000) == 0x7F800000 and (bits & 0x007FFFFF) != 0 - - -def is_f16_nan(half: int) -> bool: - return (half & 0x7FFF) > 0x7C00 - - -def merge_half(old: int, half: int, dst_hi: int) -> int: - h = half & 0xFFFF - return ((h << 16) | (old & 0xFFFF)) if dst_hi else ((old & 0xFFFF0000) | h) - - -# ----------------------------------------------------------------------------- -# Independent Exact-Rational Binary32 / Binary16 Reference Oracles -# ----------------------------------------------------------------------------- - -def _rne_int(q: Fraction) -> int: - n = q.numerator // q.denominator - rem = q - n - if rem > Fraction(1, 2) or (rem == Fraction(1, 2) and (n & 1)): - n += 1 - return n - - -def f32_to_fraction(bits: int) -> Fraction: - bits &= MASK32 - sign = -1 if (bits >> 31) else 1 - exp = (bits >> 23) & 0xFF - man = bits & 0x7FFFFF - if exp == 0xFF: - raise ValueError(f"non-finite f32 bits {bits:#010x}") - if exp == 0: - return sign * Fraction(man, 1 << 23) * Fraction(2) ** -126 - return sign * Fraction((1 << 23) | man, 1 << 23) * Fraction(2) ** (exp - 127) - - -def round_fraction_to_f32(val: Fraction, neg_zero: bool = False) -> int: - if val == 0: - return 0x80000000 if neg_zero else 0x00000000 - sign = 0x80000000 if val < 0 else 0 - a = abs(val) - e = a.numerator.bit_length() - a.denominator.bit_length() - if Fraction(2) ** e > a: - e -= 1 - if e < -126: - n = _rne_int(a / Fraction(2) ** -149) - if n == 0: - return sign - if n < (1 << 23): - return sign | n - return sign | (1 << 23) - n = _rne_int(a / Fraction(2) ** (e - 23)) - if n == (1 << 24): - n >>= 1 - e += 1 - if e > 127: - return sign | 0x7F800000 - return sign | ((e + 127) << 23) | (n & 0x7FFFFF) - - -def f16_to_fraction(half: int) -> Fraction: - half &= 0xFFFF - sign = -1 if (half >> 15) else 1 - exp = (half >> 10) & 0x1F - man = half & 0x3FF - if exp == 0x1F: - raise ValueError(f"non-finite f16 bits {half:#06x}") - if exp == 0: - return sign * Fraction(man, 1 << 10) * Fraction(2) ** -14 - return sign * Fraction((1 << 10) | man, 1 << 10) * Fraction(2) ** (exp - 15) - - -def round_fraction_to_f16(val: Fraction, neg_zero: bool = False) -> int: - if val == 0: - return 0x8000 if neg_zero else 0x0000 - sign = 0x8000 if val < 0 else 0 - a = abs(val) - e = a.numerator.bit_length() - a.denominator.bit_length() - if Fraction(2) ** e > a: - e -= 1 - if e < -14: - n = _rne_int(a / Fraction(2) ** -24) - return sign | n - n = _rne_int(a / Fraction(2) ** (e - 10)) - if n == (1 << 11): - n >>= 1 - e += 1 - if e > 15: - return sign | 0x7C00 - return sign | ((e + 15) << 10) | (n & 0x3FF) - - -def ref_rcp_f32(x_bits: int, *, scale: Fraction = Fraction(1), clamp: bool = False) -> int: - """Reference oracle for non-zero f32 reciprocal (with optional output scale/clamp).""" - bits = x_bits & MASK32 - sign = bits & 0x80000000 - absu = bits & 0x7FFFFFFF - if absu == 0: - raise ValueError("division by zero is undefined in SPIR-V") - if absu > 0x7F800000: - if clamp: - raise ValueError("clamp of NaN is undefined in GLSL.std.450") - return 0x7FC00000 - if absu == 0x7F800000: - # 1 / (+-inf) = +-0.0; omod preserves sign of zero, clamp orders -0 below +0 -> +0. - return 0 if clamp else sign - # Match OpFDiv(1, x) rounded to binary32 before clamp_mods (scale, then FClamp [0, 1]). - r_bits = round_fraction_to_f32(Fraction(1) / f32_to_fraction(bits)) - if (r_bits & 0x7FFFFFFF) == 0x7F800000: - r_sign = r_bits & 0x80000000 - if clamp: - return 0 if r_sign else 0x3F800000 - return r_bits - val = f32_to_fraction(r_bits) * scale - if clamp: - if val <= 0: - return 0x00000000 - if val >= 1: - return 0x3F800000 - return round_fraction_to_f32(val) - - -def ref_rcp_f16(h_bits: int, *, scale: Fraction = Fraction(1), clamp: bool = False) -> int: - """Reference oracle for non-zero f16 reciprocal (f32 OpFDiv + clamp_mods + f16_bits).""" - h = h_bits & 0xFFFF - sign = (h & 0x8000) << 16 - absh = h & 0x7FFF - if absh == 0: - raise ValueError("division by zero is undefined in SPIR-V") - if absh > 0x7C00: - if clamp: - raise ValueError("clamp of NaN is undefined in GLSL.std.450") - return (h & 0x8000) | 0x7E00 - if absh == 0x7C00: - return 0 if clamp else (h & 0x8000) - # Widening f16 -> f32 is exact, then f32 OpFDiv + omod/clamp, then f16 nearest-even narrowing. - r_bits = round_fraction_to_f32(Fraction(1) / f16_to_fraction(h)) - r_sign = r_bits & 0x80000000 - if (r_bits & 0x7FFFFFFF) == 0x7F800000: - if clamp: - return 0 if r_sign else 0x3C00 - return (r_sign >> 16) | 0x7C00 - val = f32_to_fraction(r_bits) * scale - if clamp: - if val <= 0: - return 0x0000 - if val >= 1: - return 0x3C00 - r_f32 = round_fraction_to_f32(val, neg_zero=bool(sign)) - return round_fraction_to_f16(f32_to_fraction(r_f32), neg_zero=bool(r_f32 & 0x80000000)) - - -def f32_to_float(bits: int) -> float: - return struct.unpack(" int: - a_bits &= MASK32 - b_bits &= MASK32 - if a_bits == b_bits: - return 0 - if (a_bits & 0x7FFFFFFF) == 0 and (b_bits & 0x7FFFFFFF) == 0: - return 0 - if (a_bits >> 31) != (b_bits >> 31): - return (a_bits & 0x7FFFFFFF) + (b_bits & 0x7FFFFFFF) - return abs((a_bits & 0x7FFFFFFF) - (b_bits & 0x7FFFFFFF)) - - -def ref_exact_fdiv_f32(a_bits: int, b_bits: int) -> int: - """Exact-rational IEEE 754 float32 division reference oracle.""" - a_bits &= MASK32 - b_bits &= MASK32 - sign = (a_bits ^ b_bits) & 0x80000000 - absu_b = b_bits & 0x7FFFFFFF - absu_a = a_bits & 0x7FFFFFFF - if absu_b == 0: - raise ValueError("division by zero is undefined in SPIR-V") - if absu_a > 0x7F800000 or absu_b > 0x7F800000: - return 0x7FC00000 - if absu_a == 0x7F800000 and absu_b == 0x7F800000: - return 0x7FC00000 - if absu_b == 0x7F800000: - return sign - if absu_a == 0x7F800000: - return sign | 0x7F800000 - if absu_a == 0: - return sign - fa = f32_to_fraction(a_bits) - fb = f32_to_fraction(b_bits) - return round_fraction_to_f32(fa / fb, neg_zero=bool(sign)) - - -def ref_newton_raphson_steps_f32(a_bits: int, b_bits: int) -> tuple[int, int, int, int]: - """Simulate RDNA2 4-step Newton-Raphson division in software. - - Step 1: Initial reciprocal estimate y0 = rcp(b) - Step 2: Error term e = 1.0 - b * y0 via FMA (fma(-b, y0, 1.0)) - Step 3: Refined reciprocal y1 = y0 + y0 * e via FMA (fma(y0, e, y0)) - Step 4: Quotient q = a * y1 via FMul - """ - a_bits &= MASK32 - b_bits &= MASK32 - if (b_bits & 0x7FFFFFFF) == 0: - raise ValueError("division by zero is undefined in SPIR-V") - y0_bits = ref_rcp_f32(b_bits) - y0 = f32_to_float(y0_bits) - b = f32_to_float(b_bits) - a = f32_to_float(a_bits) - - e = si.fma_f32(-b, y0, 1.0) - e_bits = f32_bits(e) - - y1 = si.fma_f32(y0, e, y0) - y1_bits = f32_bits(y1) - - q = struct.unpack(" int: - return ref_newton_raphson_steps_f32(a_bits, b_bits)[3] - - -NR_FDIV_HAND_WORKED = ( - ("one_half", 0x3F800000, 0x40000000, (0x3F000000, 0x00000000, 0x3F000000, 0x3F000000)), - ("seven_thirds", 0x40E00000, 0x40400000, (0x3EAAAAAB, 0xB3000000, 0x3EAAAAAB, 0x40155556)), - ("ten_fourths", 0x41200000, 0x40800000, (0x3E800000, 0x00000000, 0x3E800000, 0x40200000)), - ("neg_fifteen_fifths", 0xC1700000, 0x40A00000, (0x3E4CCCCD, 0xB2800000, 0x3E4CCCCD, 0xC0400000)), - ("pos_neg_div", 0x42C90000, 0xC1A20000, (0xBD4A4588, 0xB2000000, 0xBD4A4588, 0xC09ED098)), - ("pos_zero", 0x00000000, 0x40800000, (0x3E800000, 0x00000000, 0x3E800000, 0x00000000)), - ("neg_zero", 0x80000000, 0x40800000, (0x3E800000, 0x00000000, 0x3E800000, 0x80000000)), -) - - - -RCP_F32_HAND_WORKED = ( - ("pos_one", 0x3F800000, 0x3F800000), - ("neg_one", 0xBF800000, 0xBF800000), - ("pos_two", 0x40000000, 0x3F000000), - ("neg_two", 0xC0000000, 0xBF000000), - ("pos_four", 0x40800000, 0x3E800000), - ("neg_quarter", 0xBE800000, 0xC0800000), - ("pos_2p20", 0x49800000, 0x35800000), - ("neg_2pm20", 0xB5800000, 0xC9800000), - ("pos_1p5", 0x3FC00000, 0x3F2AAAAB), - ("neg_3p0", 0xC0400000, 0xBEAAAAAB), - ("pos_0p3", 0x3E99999A, 0x40555555), - ("subnorm_2m128_to_inf", 0x00200000, 0x7F800000), - ("neg_subnorm_min_to_ninf", 0x80000001, 0xFF800000), - ("2p127_to_subnorm", 0x7F000000, 0x00400000), - ("pos_inf", 0x7F800000, 0x00000000), - ("neg_inf", 0xFF800000, 0x80000000), -) - -RCP_F16_HAND_WORKED = ( - ("pos_one", H_1P0, H_1P0), - ("neg_one", H_NEG_1P0, H_NEG_1P0), - ("pos_two", H_2P0, H_0P5), - ("neg_two", H_NEG_2P0, H_NEG_0P5), - ("pos_four", H_4P0, H_0P25), - ("neg_quarter", H_NEG_0P25, H_NEG_4P0), - ("pos_1p5", H_1P5, 0x3955), - ("pos_3p0", H_3P0, 0x3555), - ("neg_3p0", H_NEG_3P0, 0xB555), - ("sub_min_overflow", H_SUB_MIN, H_POS_INF), - ("neg_sub_min_overflow", H_NEG_SUB_MIN, H_NEG_INF), - ("sub_2m16_overflow", H_SUB_2M16, H_POS_INF), - ("sub_2m15", H_SUB_2M15, 0x7800), - ("sub_max", H_SUB_MAX, 0x7401), - ("norm_min", H_NORM_MIN, 0x7400), - ("f16_max", H_MAX, 0x0100), - ("neg_f16_max", H_NEG_MAX, 0x8100), - ("pos_inf", H_POS_INF, H_POS_ZERO), - ("neg_inf", H_NEG_INF, H_NEG_ZERO), -) - - -# ----------------------------------------------------------------------------- -# Translation & Execution Helpers -# ----------------------------------------------------------------------------- - -_TMP_DIR = None -_PS_PATH = None -_CS_PATH = None -_CS_FSSM = None - - -def _make_fssm(rsrc2: int, group: tuple[int, int, int]) -> bytes: - header = bytearray(0x148) - struct.pack_into("<4I", header, 0x138, rsrc2, *group) - return bytes(header) - - -def setUpModule(): - global _TMP_DIR, _PS_PATH, _CS_PATH, _CS_FSSM - _TMP_DIR = tempfile.TemporaryDirectory() - disasm_dir = os.path.join(_TMP_DIR.name, "disasm") - fssm_dir = os.path.join(_TMP_DIR.name, "fssm") - os.mkdir(disasm_dir) - os.mkdir(fssm_dir) - _PS_PATH = os.path.join(disasm_dir, "ps_valu_rcp_fdiv.s") - _CS_PATH = os.path.join(disasm_dir, "cs_valu_rcp_fdiv.s") - _CS_FSSM = os.path.join(fssm_dir, "cs_valu_rcp_fdiv.fssm") - with open(os.path.join(_TMP_DIR.name, "ps_valu_rcp_fdiv.dxbc"), "wb") as f: - f.write(STUB_DXBC) - - -def tearDownModule(): - global _TMP_DIR, _PS_PATH, _CS_PATH, _CS_FSSM - if _TMP_DIR is not None: - gc.collect() - _TMP_DIR.cleanup() - _TMP_DIR = None - _PS_PATH = None - _CS_PATH = None - _CS_FSSM = None - - -def translate_ps(lines: list[str]) -> str: - if _TMP_DIR is None: - setUpModule() - asm = ( - "; test_valu_rcp_fdiv\n" - + "".join(f"\t{ln}\n" for ln in lines) - + "\texp mrt0 v0, v0, v0, v0 done vm\n" - + "\ts_endpgm\n" - ) - with open(_PS_PATH, "w", encoding="utf-8", newline="") as f: - f.write(asm) - with warnings.catch_warnings(): - warnings.simplefilter("ignore", ResourceWarning) - spv = rdna2spirv.translate(_PS_PATH) - gc.collect() - return spv - - -def run_ps_v0(lines: list[str]) -> int: - return si.run_fragment(translate_ps(lines))["%out_mrt0"][0] - - -def run_op(line: str, v1: int, old: int = OLD, s4: int = 0) -> int: - return run_ps_v0([ - f"s_mov_b32 s4, {s4:#x}", - f"v_mov_b32 v1, {v1:#x}", - f"v_mov_b32 v0, {old:#x}", - line, - ]) - - -def run_cs(lines: list[str], group_size: int, subgroup_size: int, memory: dict[int, int]) -> dict[int, int]: - if _TMP_DIR is None: - setUpModule() - with open(_CS_FSSM, "wb") as f: - f.write(_make_fssm(0x0088, (group_size, 1, 1))) - asm = "; test_cs_valu_rcp_fdiv\n" + "".join(f"\t{ln}\n" for ln in lines) + "\ts_endpgm\n" - with open(_CS_PATH, "w", encoding="utf-8", newline="") as f: - f.write(asm) - with warnings.catch_warnings(): - warnings.simplefilter("ignore", ResourceWarning) - spv = rdna2spirv.translate(_CS_PATH) - gc.collect() - return si.run_workgroup( - spv, group_size, subgroup_size, - inputs_for=lambda i: {"%wg_id": (0, 0, 0), "%local_id": (i, 0, 0)}, - push_constants=VSHARP + [0] * 28, - memory=memory, - ) - - -# ----------------------------------------------------------------------------- -# 1. Reference Oracle Self-Tests -# ----------------------------------------------------------------------------- - -class OracleSelfTests(unittest.TestCase): - def test_hand_worked_rcp_f32_and_f16_match_fraction_oracles(self): - for name, x_bits, want in RCP_F32_HAND_WORKED: - with self.subTest(kind="f32", name=name): - self.assertEqual(ref_rcp_f32(x_bits), want) - for name, h_bits, want in RCP_F16_HAND_WORKED: - with self.subTest(kind="f16", name=name): - self.assertEqual(ref_rcp_f16(h_bits), want) - - -class NewtonRaphsonOracleTests(unittest.TestCase): - def test_hand_worked_newton_raphson_steps(self): - for name, a_bits, b_bits, want_steps in NR_FDIV_HAND_WORKED: - with self.subTest(case=name): - got_steps = ref_newton_raphson_steps_f32(a_bits, b_bits) - self.assertEqual(got_steps, want_steps) - - def test_exact_rational_division_oracle(self): - cases = ( - (f32_bits(1.0), f32_bits(2.0), f32_bits(0.5)), - (f32_bits(8.0), f32_bits(4.0), f32_bits(2.0)), - (f32_bits(-9.0), f32_bits(3.0), f32_bits(-3.0)), - (f32_bits(100.0), f32_bits(-25.0), f32_bits(-4.0)), - (0x00000000, f32_bits(5.0), 0x00000000), - (0x80000000, f32_bits(5.0), 0x80000000), - (f32_bits(1.0), 0x7F800000, 0x00000000), - (f32_bits(-1.0), 0x7F800000, 0x80000000), - ) - for a_bits, b_bits, want in cases: - with self.subTest(a=hex(a_bits), b=hex(b_bits)): - self.assertEqual(ref_exact_fdiv_f32(a_bits, b_bits), want) - - def test_zero_divisor_raises_in_oracles(self): - for z in (0x00000000, 0x80000000): - with self.subTest(zero=hex(z)): - with self.assertRaises(ValueError): - ref_newton_raphson_steps_f32(f32_bits(1.0), z) - with self.assertRaises(ValueError): - ref_exact_fdiv_f32(f32_bits(1.0), z) - - def test_newton_raphson_oracle_accuracy_within_one_ulp(self): - test_pairs = ( - (1.0, 3.0), - (7.0, 3.0), - (22.0, 7.0), - (355.0, 113.0), - (12345.67, 0.00123), - (-9876.54, 321.0), - (1e12, 3.0), - (1e-12, 7.0), - (0.15625, 1.25), - (1024.0, 10.0), - (-4096.0, 13.0), - ) - for a_f, b_f in test_pairs: - with self.subTest(a=a_f, b=b_f): - ab = f32_bits(a_f) - bb = f32_bits(b_f) - nr = ref_newton_raphson_fdiv_f32(ab, bb) - exact = ref_exact_fdiv_f32(ab, bb) - ulp = f32_ulp_diff(nr, exact) - self.assertLessEqual(ulp, 1, f"ULP diff {ulp} exceeds 1 for {a_f}/{b_f}: nr={nr:#010x} exact={exact:#010x}") - - -# ----------------------------------------------------------------------------- -# 2. Direct OpFDiv Unit Tests in spirv_mini_interp.py -# ----------------------------------------------------------------------------- - -FDIV_HEADER = """\ -OpCapability Shader -OpMemoryModel Logical GLSL450 -OpEntryPoint Fragment %main "main" %out -%void = OpTypeVoid -%fn = OpTypeFunction %void -%uint = OpTypeInt 32 0 -%float = OpTypeFloat 32 -%v2float = OpTypeVector %float 2 -%_ptr_Output_uint = OpTypePointer Output %uint -%out = OpVariable %_ptr_Output_uint Output -%_ptr_PC = OpTypePointer PushConstant %uint -%pc = OpVariable %_ptr_PC PushConstant -%c0 = OpConstant %uint 0 -%c1 = OpConstant %uint 1 -%c2 = OpConstant %uint 2 -%c3 = OpConstant %uint 3 -%f0 = OpConstant %float 0 -%f0p5 = OpConstant %float 0.5 -%f1 = OpConstant %float 1 -%f2 = OpConstant %float 2 -%f3 = OpConstant %float 3 -%f4 = OpConstant %float 4 -%f255 = OpConstant %float 255 -%u_neg0 = OpConstant %uint 2147483648 -%u_inf = OpConstant %uint 2139095040 -%u_ninf = OpConstant %uint 4286578688 -%u_qnan = OpConstant %uint 2143289344 -%u_snan = OpConstant %uint 2139095041 -%u_fltmax = OpConstant %uint 2139095039 -%u_nfltmax = OpConstant %uint 4286578687 -%main = OpFunction %void None %fn -%entry = OpLabel -%fm0 = OpBitcast %float %u_neg0 -%inf = OpBitcast %float %u_inf -%ninf = OpBitcast %float %u_ninf -%qnan = OpBitcast %float %u_qnan -%snan = OpBitcast %float %u_snan -%fltmax = OpBitcast %float %u_fltmax -%nfltmax = OpBitcast %float %u_nfltmax -%fm2 = OpFNegate %float %f2 -%fm3 = OpFNegate %float %f3 -%fm1 = OpFNegate %float %f1 -""" -FDIV_FOOTER = "OpReturn\nOpFunctionEnd\n" - - -def run_fdiv_scalar(num: str, den: str) -> int: - text = ( - FDIV_HEADER - + f"%r = OpFDiv %float {num} {den}\n" - + "%res = OpBitcast %uint %r\n" - + "OpStore %out %res\n" - + FDIV_FOOTER - ) - return si.run_fragment(text)["%out"][0] - - -def run_fdiv_vec2(n0: str, n1: str, d0: str, d1: str) -> tuple[int, int]: - hdr = FDIV_HEADER.replace( - 'OpEntryPoint Fragment %main "main" %out', - 'OpEntryPoint Fragment %main "main" %out %out1', - ).replace( - "%out = OpVariable %_ptr_Output_uint Output", - "%out = OpVariable %_ptr_Output_uint Output\n%out1 = OpVariable %_ptr_Output_uint Output", - ) - body = ( - f"%vn = OpCompositeConstruct %v2float {n0} {n1}\n" - + f"%vd = OpCompositeConstruct %v2float {d0} {d1}\n" - + "%vr = OpFDiv %v2float %vn %vd\n" - + "%r0 = OpCompositeExtract %float %vr 0\n" - + "%r1 = OpCompositeExtract %float %vr 1\n" - + "%b0 = OpBitcast %uint %r0\n" - + "%b1 = OpBitcast %uint %r1\n" - + "OpStore %out %b0\n" - + "OpStore %out1 %b1\n" - ) - res = si.run_fragment(hdr + body + FDIV_FOOTER) - return res["%out"][0], res["%out1"][0] - - -class OpFDivInterpreterTests(unittest.TestCase): - def test_scalar_finite_signed_zero_inf_and_overflow(self): - cases = ( - ("%f1", "%f4", f32_bits(0.25)), - ("%fm3", "%f2", f32_bits(-1.5)), - ("%f3", "%f255", 0x3C40C0C1), - # Signed zero dividends keep exact IEEE sign rules. - ("%f0", "%f2", 0x00000000), - ("%f0", "%fm2", 0x80000000), - ("%fm0", "%f2", 0x80000000), - ("%fm0", "%fm2", 0x00000000), - # Division by +-inf -> +-0.0. - ("%f1", "%inf", 0x00000000), - ("%fm1", "%inf", 0x80000000), - ("%f1", "%ninf", 0x80000000), - ("%fm1", "%ninf", 0x00000000), - ("%f0", "%ninf", 0x80000000), - ("%fm0", "%inf", 0x80000000), - ("%fm0", "%ninf", 0x00000000), - # +-inf divided by finite non-zero -> +-inf. - ("%inf", "%f2", 0x7F800000), - ("%inf", "%fm2", 0xFF800000), - ("%ninf", "%f2", 0xFF800000), - ("%ninf", "%fm2", 0x7F800000), - # Binary32 overflow -> +-inf. - ("%fltmax", "%f0p5", 0x7F800000), - ("%nfltmax", "%f0p5", 0xFF800000), - ) - for num, den, want in cases: - with self.subTest(num=num, den=den): - self.assertEqual(run_fdiv_scalar(num, den), want) - - def test_scalar_inf_over_inf_and_nan_propagation(self): - nan_cases = ( - ("%inf", "%inf"), - ("%inf", "%ninf"), - ("%ninf", "%inf"), - ("%ninf", "%ninf"), - ("%qnan", "%f2"), - ("%f2", "%qnan"), - ("%qnan", "%inf"), - ("%inf", "%qnan"), - ("%f0", "%qnan"), - ("%snan", "%f2"), - ("%f2", "%snan"), - ) - for num, den in nan_cases: - with self.subTest(num=num, den=den): - got = run_fdiv_scalar(num, den) - self.assertTrue(is_f32_nan_bits(got), f"expected NaN for {num}/{den}, got {got:#010x}") - - def test_vector_v2float_division(self): - self.assertEqual(run_fdiv_vec2("%f1", "%fm3", "%f4", "%fm2"), (f32_bits(0.25), f32_bits(1.5))) - self.assertEqual(run_fdiv_vec2("%f1", "%fm0", "%ninf", "%ninf"), (0x80000000, 0x00000000)) - g0, g1 = run_fdiv_vec2("%f1", "%inf", "%ninf", "%ninf") - self.assertEqual(g0, 0x80000000) - self.assertTrue(is_f32_nan_bits(g1), f"expected NaN in lane 1, got {g1:#010x}") - - def test_zero_divisor_and_non_float_are_rejected(self): - for num, den in ( - ("%f1", "%f0"), - ("%f1", "%fm0"), - ("%fm1", "%f0"), - ("%fm1", "%fm0"), - ("%f0", "%f0"), - ("%fm0", "%fm0"), - ("%inf", "%f0"), - ("%qnan", "%f0"), - ("%qnan", "%fm0"), - ): - with self.subTest(num=num, den=den): - with self.assertRaises(si.UnsupportedConstruct): - run_fdiv_scalar(num, den) - - for n0, n1, d0, d1 in ( - ("%f1", "%f2", "%f0", "%f2"), - ("%f1", "%f2", "%f2", "%fm0"), - ): - with self.subTest(vec=(n0, n1, d0, d1)): - with self.assertRaises(si.UnsupportedConstruct): - run_fdiv_vec2(n0, n1, d0, d1) - - with self.assertRaises(si.UnsupportedConstruct): - si.run_fragment( - FDIV_HEADER + "%res = OpFDiv %uint %c2 %c1\nOpStore %out %res\n" + FDIV_FOOTER - ) - - -# ----------------------------------------------------------------------------- -# 3. End-to-End v_rcp_f32 & v_rcp_iflag_f32 Value Tests -# ----------------------------------------------------------------------------- - -class RcpF32AndIflagExecutionTests(unittest.TestCase): - OPS = ("v_rcp_f32", "v_rcp_iflag_f32") - - def test_hand_worked_and_edge_values_across_encodings(self): - for op in self.OPS: - for suffix in ("_e32", "_e64", ""): - for name, x_bits, want in RCP_F32_HAND_WORKED: - with self.subTest(op=op + suffix, case=name): - got = run_op(f"{op}{suffix} v0, v1", x_bits) - self.assertEqual(got, want) - - def test_nan_inputs_preserve_nan(self): - for op in self.OPS: - for suffix in ("_e32", "_e64"): - for x_bits in (0x7FC00000, 0xFFC00001, 0x7F800001, 0xFF800001): - with self.subTest(op=op + suffix, x=hex(x_bits)): - got = run_op(f"{op}{suffix} v0, v1", x_bits) - self.assertTrue(is_f32_nan_bits(got), f"expected NaN, got {got:#010x}") - - def test_zero_inputs_raise_unsupported_construct(self): - for op in self.OPS: - for suffix in ("_e32", "_e64"): - for x_bits in (0x00000000, 0x80000000): - with self.subTest(op=op + suffix, x=hex(x_bits)): - with self.assertRaises(si.UnsupportedConstruct): - run_op(f"{op}{suffix} v0, v1", x_bits) - with self.subTest(op=op, mod="-|0|"): - with self.assertRaises(si.UnsupportedConstruct): - run_op(f"{op}_e64 v0, -|0|", 0) - - def test_vop3_output_and_source_modifiers(self): - cases = ( - # (insn_suffix_and_src, v1_bits, scale, clamp) - ("v1 clamp", f32_bits(0.5), Fraction(1), True), - ("v1 clamp", f32_bits(-0.5), Fraction(1), True), - ("v1 clamp", f32_bits(4.0), Fraction(1), True), - ("v1 mul:2", f32_bits(4.0), Fraction(2), False), - ("v1 mul:2", f32_bits(-0.5), Fraction(2), False), - ("v1 mul:4", f32_bits(4.0), Fraction(4), False), - ("v1 mul:4", f32_bits(-2.0), Fraction(4), False), - ("v1 div:2", f32_bits(2.0), Fraction(1, 2), False), - ("v1 div:2", f32_bits(-0.5), Fraction(1, 2), False), - # omod applies before clamp: 1/0.5 * 0.5 = 1.0; 1/4.0 * 2 = 0.5; 1/0.5 * 2 -> clamped 1.0 - ("v1 mul:2 clamp", f32_bits(0.5), Fraction(2), True), - ("v1 mul:2 clamp", f32_bits(4.0), Fraction(2), True), - ("v1 mul:2 clamp", f32_bits(-0.5), Fraction(2), True), - ("v1 clamp div:2", f32_bits(0.5), Fraction(1, 2), True), - ("v1 clamp div:2", f32_bits(-0.5), Fraction(1, 2), True), - ) - for op in self.OPS: - for args, x_bits, scale, clamp in cases: - with self.subTest(op=op, args=args, x=hex(x_bits)): - got = run_op(f"{op}_e64 v0, {args}", x_bits) - want = ref_rcp_f32(x_bits, scale=scale, clamp=clamp) - self.assertEqual(got, want) - - # Source modifiers (-v1, |v1|, -|v1|) alone and combined with output modifiers. - src_cases = ( - ("-v1", f32_bits(2.0), f32_bits(-0.5)), - ("|v1|", f32_bits(-4.0), f32_bits(0.25)), - ("-|v1|", f32_bits(-2.0), f32_bits(-0.5)), - ("-|v1|", f32_bits(2.0), f32_bits(-0.5)), - ("-v1 clamp", f32_bits(-0.5), f32_bits(1.0)), - ("|v1| mul:2", f32_bits(-0.5), f32_bits(4.0)), - ("-|v1| mul:2 clamp", f32_bits(0.5), f32_bits(0.0)), - ("-|v1| div:2", f32_bits(-0.5), f32_bits(-1.0)), - ) - for op in self.OPS: - for args, x_bits, want in src_cases: - with self.subTest(op=op, args=args, x=hex(x_bits)): - self.assertEqual(run_op(f"{op}_e64 v0, {args}", x_bits), want) - - def test_inline_constants_literals_sgprs_and_aliasing(self): - for op in self.OPS: - # Inline float constants, VOP3 constant modifiers, and 32-bit literal. - self.assertEqual(run_op(f"{op}_e32 v0, 0.5", 0), f32_bits(2.0)) - self.assertEqual(run_op(f"{op}_e32 v0, -0.5", 0), f32_bits(-2.0)) - self.assertEqual(run_op(f"{op}_e32 v0, 4.0", 0), f32_bits(0.25)) - self.assertEqual(run_op(f"{op}_e64 v0, -|2.0|", 0), f32_bits(-0.5)) - self.assertEqual(run_op(f"{op}_e64 v0, neg(0x3f800000)", 0), f32_bits(-1.0)) - self.assertEqual(run_op(f"{op}_e32 v0, 0x40400000", 0), 0x3EAAAAAB) - - # SGPR source and modified SGPR source. - self.assertEqual(run_op(f"{op}_e32 v0, s4", 0, s4=f32_bits(-4.0)), f32_bits(-0.25)) - self.assertEqual(run_op(f"{op}_e64 v0, |s4| mul:2", 0, s4=f32_bits(-4.0)), f32_bits(0.5)) - - # In-place aliasing: dst == src. - self.assertEqual(run_ps_v0(["v_mov_b32 v0, 0x40000000", f"{op}_e32 v0, v0"]), f32_bits(0.5)) - self.assertEqual(run_ps_v0(["v_mov_b32 v0, 0xc0800000", f"{op}_e64 v0, -v0 mul:4"]), f32_bits(1.0)) - - -# ----------------------------------------------------------------------------- -# 4. End-to-End v_rcp_f16 Value Tests -# ----------------------------------------------------------------------------- - -class RcpF16ExecutionTests(unittest.TestCase): - def test_hand_worked_values_across_e32_e64_and_bare(self): - for suffix in ("_e32", "_e64", ""): - for name, h_bits, want_half in RCP_F16_HAND_WORKED: - with self.subTest(suffix=suffix, case=name): - got = run_op(f"v_rcp_f16{suffix} v0, v1", 0xCAFE0000 | h_bits) - self.assertEqual(got, merge_half(OLD, want_half, 0)) - - def test_nan_preserves_nan_and_other_half(self): - for suffix in ("_e32", "_e64"): - for h in (H_QNAN, H_NEG_QNAN, H_SNAN): - with self.subTest(suffix=suffix, h=hex(h)): - got = run_op(f"v_rcp_f16{suffix} v0, v1", 0xCAFE0000 | h) - self.assertEqual(got & 0xFFFF0000, OLD & 0xFFFF0000) - self.assertTrue(is_f16_nan(got & 0xFFFF), f"expected NaN in low half, got {got:#010x}") - - def test_zero_inputs_give_signed_infinity(self): - # The ISA's rcp(+-0) = +-inf. The translator selects it itself rather than dividing by zero (undefined in - # SPIR-V, so the interpreter raises); the f32 forms above still leave it to the driver. - for line, v1, want, dst_hi in ( - ("v_rcp_f16_e32 v0, v1", (H_1P0 << 16) | H_POS_ZERO, 0x7C00, 0), - ("v_rcp_f16_e32 v0, v1", (H_1P0 << 16) | H_NEG_ZERO, 0xFC00, 0), - ("v_rcp_f16_e64 v0, v1 op_sel:[1,0]", (H_POS_ZERO << 16) | H_1P0, 0x7C00, 0), - ("v_rcp_f16_e64 v0, v1 op_sel:[1,1]", (H_NEG_ZERO << 16) | H_1P0, 0xFC00, 1), - ): - with self.subTest(line=line, v1=hex(v1)): - self.assertEqual(run_op(line, v1), merge_half(OLD, want, dst_hi)) - - def test_op_sel_all_combinations(self): - # v1 = (hi: -4.0, lo: 0.5) -> rcp(hi) = -0.25, rcp(lo) = 2.0. - v1 = (H_NEG_4P0 << 16) | H_0P5 - for src_hi, dst_hi in itertools.product((0, 1), repeat=2): - h_in = H_NEG_4P0 if src_hi else H_0P5 - line = f"v_rcp_f16_e64 v0, v1 op_sel:[{src_hi},{dst_hi}]" - with self.subTest(line=line): - self.assertEqual(run_op(line, v1), merge_half(OLD, ref_rcp_f16(h_in), dst_hi)) - - def test_vop3_source_and_output_modifiers(self): - v1 = (H_NEG_0P5 << 16) | H_4P0 - self.assertEqual(run_op("v_rcp_f16_e64 v0, -v1 op_sel:[0,0]", v1), merge_half(OLD, H_NEG_0P25, 0)) - self.assertEqual(run_op("v_rcp_f16_e64 v0, |v1| op_sel:[1,1]", v1), merge_half(OLD, H_2P0, 1)) - self.assertEqual(run_op("v_rcp_f16_e64 v0, -|v1| op_sel:[1,0]", v1), merge_half(OLD, H_NEG_2P0, 0)) - - # Output modifiers: on RDNA2 with denorms kept, omod is ignored on f16 results; clamp applies to [0.0, 1.0]. - self.assertEqual(run_op("v_rcp_f16_e64 v0, v1 mul:2", v1), merge_half(OLD, H_0P25, 0)) - self.assertEqual(run_op("v_rcp_f16_e64 v0, v1 mul:4", v1), merge_half(OLD, H_0P25, 0)) - self.assertEqual(run_op("v_rcp_f16_e64 v0, v1 div:2", v1), merge_half(OLD, H_0P25, 0)) - self.assertEqual(run_op("v_rcp_f16_e64 v0, v1 op_sel:[1,1] mul:2", v1), merge_half(OLD, H_NEG_2P0, 1)) - self.assertEqual(run_op("v_rcp_f16_e64 v0, v1 op_sel:[1,1] clamp", v1), merge_half(OLD, H_POS_ZERO, 1)) - self.assertEqual(run_op("v_rcp_f16_e64 v0, |v1| op_sel:[1,0] mul:2 clamp", v1), merge_half(OLD, H_1P0, 0)) - self.assertEqual(run_op("v_rcp_f16_e64 v0, |v1| op_sel:[1,1] clamp div:2", v1), merge_half(OLD, H_1P0, 1)) - - def test_inline_constants_sgpr_and_aliasing(self): - self.assertEqual(run_op("v_rcp_f16_e32 v0, 0.5", 0), merge_half(OLD, H_2P0, 0)) - self.assertEqual(run_op("v_rcp_f16_e32 v0, -0.5", 0), merge_half(OLD, H_NEG_2P0, 0)) - self.assertEqual(run_op("v_rcp_f16_e64 v0, -1.0", 0), merge_half(OLD, H_NEG_1P0, 0)) - self.assertEqual(run_op("v_rcp_f16_e64 v0, -|0x4000|", 0), merge_half(OLD, H_NEG_0P5, 0)) - - s4 = (H_NEG_4P0 << 16) | H_0P5 - self.assertEqual(run_op("v_rcp_f16_e32 v0, s4", 0, s4=s4), merge_half(OLD, H_2P0, 0)) - self.assertEqual(run_op("v_rcp_f16_e64 v0, s4 op_sel:[1,1]", 0, s4=s4), merge_half(OLD, H_NEG_0P25, 1)) - - # In-place aliasing: dst == src reading one half and writing the other keeps the original unread half. - v0_init = (H_0P5 << 16) | H_4P0 - self.assertEqual( - run_ps_v0([f"v_mov_b32 v0, {v0_init:#x}", "v_rcp_f16_e64 v0, v0 op_sel:[1,0]"]), - (H_0P5 << 16) | H_2P0, - ) - self.assertEqual( - run_ps_v0([f"v_mov_b32 v0, {v0_init:#x}", "v_rcp_f16_e32 v0, v0"]), - (H_0P5 << 16) | H_0P25, - ) - - -# ----------------------------------------------------------------------------- -# 5. EXEC Masking & Negative Control Tests -# ----------------------------------------------------------------------------- - -class RcpExecMaskingTests(unittest.TestCase): - def test_single_lane_exec_masking(self): - for line in ( - "v_rcp_f32_e32 v0, v1", - "v_rcp_iflag_f32_e32 v0, v1", - "v_rcp_f16_e32 v0, v1", - "v_rcp_f16_e64 v0, v1 op_sel:[1,1]", - ): - with self.subTest(line=line): - got = run_ps_v0([ - f"v_mov_b32 v1, {(H_2P0 << 16) | H_4P0:#x}", - f"v_mov_b32 v0, {OLD:#x}", - "s_mov_b32 exec_lo, 0", - line, - "s_mov_b32 exec_lo, 1", - ]) - self.assertEqual(got, OLD) - - # Disabled ops leave v0 unchanged; re-enabling EXEC executes the subsequent op. - got_toggled = run_ps_v0([ - f"v_mov_b32 v1, {(H_0P5 << 16) | H_4P0:#x}", - f"v_mov_b32 v0, {OLD:#x}", - "s_mov_b32 exec_lo, 0", - "v_rcp_f16_e64 v0, v1 op_sel:[0,0]", - "v_rcp_f16_e64 v0, v1 op_sel:[1,1]", - "s_mov_b32 exec_lo, 1", - "v_rcp_f16_e64 v0, v1 op_sel:[1,0]", - ]) - self.assertEqual(got_toggled, merge_half(OLD, H_2P0, 0)) - - def test_multilane_compute_exec_masking(self): - # 4 lanes in wave32: disable odd lanes (lane & 1 != 0) before executing v_rcp_*. - # Active even lanes (0, 2) compute the reciprocal; inactive odd lanes (1, 3) keep OLD. - cases = ( - ("v_rcp_f32_e32 v3, v2", f32_bits(4.0), f32_bits(0.25)), - ("v_rcp_iflag_f32_e64 v3, v2 mul:2", f32_bits(4.0), f32_bits(0.5)), - ("v_rcp_f16_e64 v3, v2 op_sel:[1,1]", (H_0P5 << 16) | H_4P0, merge_half(OLD, H_2P0, 1)), - ) - for insn, src_word, active_want in cases: - with self.subTest(insn=insn): - mem = {} - lines = [ - "v_lshlrev_b32 v4, 2, v0", # lane byte offset = lane * 4 - f"v_mov_b32 v2, {src_word:#x}", - f"v_mov_b32 v3, {OLD:#x}", - "v_and_b32 v5, v0, 1", - "v_cmpx_eq_u32 v5, 0", # keep even lanes active - insn, - "s_mov_b32 exec_lo, -1", - "buffer_store_dword v3, v4, s[0:3], 0 offen", - ] - run_cs(lines, group_size=4, subgroup_size=32, memory=mem) - self.assertEqual( - [mem[4 * i] for i in range(4)], - [active_want, OLD, active_want, OLD], - ) - - -# ----------------------------------------------------------------------------- -# 6. Newton-Raphson Multi-Step Division Emulation (v_rcp_f32 + v_fma_f32 + v_mul_f32) -# ----------------------------------------------------------------------------- - -def run_nr_fdiv_ps(a_bits: int, b_bits: int) -> int: - """Execute 4-step Newton-Raphson division in a pixel shader and return quotient bits.""" - return run_ps_v0([ - f"v_mov_b32 v0, {a_bits:#x}", - f"v_mov_b32 v1, {b_bits:#x}", - "v_rcp_f32_e32 v2, v1", - "v_fma_f32 v3, -v1, v2, 1.0", - "v_fma_f32 v4, v2, v3, v2", - "v_mul_f32_e32 v0, v0, v4", - ]) - - -def run_nr_fdiv_steps_cs(a_bits: int, b_bits: int) -> tuple[int, int, int, int]: - """Execute 4-step Newton-Raphson division in a compute shader and capture all intermediate registers.""" - mem: dict[int, int] = {} - lines = [ - f"v_mov_b32 v0, {a_bits:#x}", - f"v_mov_b32 v1, {b_bits:#x}", - "v_rcp_f32_e32 v2, v1", - "v_fma_f32 v3, -v1, v2, 1.0", - "v_fma_f32 v4, v2, v3, v2", - "v_mul_f32_e32 v5, v0, v4", - "v_mov_b32 v6, 0", - "buffer_store_dword v2, v6, s[0:3], 0 offen offset:0", - "buffer_store_dword v3, v6, s[0:3], 0 offen offset:4", - "buffer_store_dword v4, v6, s[0:3], 0 offen offset:8", - "buffer_store_dword v5, v6, s[0:3], 0 offen offset:12", - ] - run_cs(lines, group_size=1, subgroup_size=32, memory=mem) - return mem[0], mem[4], mem[8], mem[12] - - -class NewtonRaphsonMultiStepEmulationTests(unittest.TestCase): - def test_hand_worked_pipeline_steps_match_oracle(self): - for name, a_bits, b_bits, want_steps in NR_FDIV_HAND_WORKED: - with self.subTest(case=name): - got_steps = run_nr_fdiv_steps_cs(a_bits, b_bits) - self.assertEqual(got_steps, want_steps) - - def test_end_to_end_quotients_match_oracle(self): - cases = ( - (f32_bits(1.0), f32_bits(2.0)), - (f32_bits(3.5), f32_bits(1.75)), - (f32_bits(10.0), f32_bits(3.0)), - (f32_bits(-15.0), f32_bits(4.0)), - (f32_bits(100.5), f32_bits(-20.25)), - (f32_bits(1e6), f32_bits(3.0)), - (f32_bits(2.5e-5), f32_bits(4.0e5)), - (f32_bits(1.0), f32_bits(7.0)), - (f32_bits(22.0), f32_bits(7.0)), - (f32_bits(-0.125), f32_bits(8.0)), - (0x00000000, f32_bits(4.0)), - (0x80000000, f32_bits(4.0)), - (0x00000000, f32_bits(-4.0)), - (0x80000000, f32_bits(-4.0)), - ) - for a_bits, b_bits in cases: - with self.subTest(a=hex(a_bits), b=hex(b_bits)): - got = run_nr_fdiv_ps(a_bits, b_bits) - want = ref_newton_raphson_fdiv_f32(a_bits, b_bits) - self.assertEqual(got, want) - - def test_vop3_encodings_and_register_reuse(self): - # In-place register reuse: v0 = dividend, v1 = divisor, v2 = y0 -> y1, v0 = quotient - lines = [ - f"v_mov_b32 v0, {f32_bits(10.0):#x}", - f"v_mov_b32 v1, {f32_bits(2.0):#x}", - "v_rcp_f32_e64 v2, v1", - "v_fma_f32 v3, -v1, v2, 1.0", - "v_fma_f32 v2, v2, v3, v2", - "v_mul_f32_e64 v0, v0, v2", - ] - self.assertEqual(run_ps_v0(lines), f32_bits(5.0)) - - # Negative dividend and divisor with VOP3 - lines_neg = [ - f"v_mov_b32 v0, {f32_bits(-24.0):#x}", - f"v_mov_b32 v1, {f32_bits(-6.0):#x}", - "v_rcp_f32_e64 v2, v1", - "v_fma_f32 v3, -v1, v2, 1.0", - "v_fma_f32 v2, v2, v3, v2", - "v_mul_f32_e64 v0, v0, v2", - ] - self.assertEqual(run_ps_v0(lines_neg), f32_bits(4.0)) - - def test_sgpr_and_inline_constant_operands(self): - # SGPR divisor - lines_sgpr = [ - f"s_mov_b32 s4, {f32_bits(4.0):#x}", - f"v_mov_b32 v0, {f32_bits(2.0):#x}", - "v_rcp_f32_e32 v2, s4", - "v_fma_f32 v3, -s4, v2, 1.0", - "v_fma_f32 v4, v2, v3, v2", - "v_mul_f32_e32 v0, v0, v4", - ] - self.assertEqual(run_ps_v0(lines_sgpr), f32_bits(0.5)) - - # Inline float constants as divisor (2.0) - lines_imm = [ - f"v_mov_b32 v0, {f32_bits(12.0):#x}", - "v_rcp_f32_e32 v2, 2.0", - "v_fma_f32 v3, -2.0, v2, 1.0", - "v_fma_f32 v4, v2, v3, v2", - "v_mul_f32_e32 v0, v0, v4", - ] - self.assertEqual(run_ps_v0(lines_imm), f32_bits(6.0)) - - def test_multilane_simd_divergence_under_exec_mask(self): - mem: dict[int, int] = {} - lines = [ - "v_lshlrev_b32 v6, 2, v0", - f"v_mov_b32 v7, {f32_bits(10.0):#x}", - f"v_mov_b32 v8, {f32_bits(2.0):#x}", - "v_cmp_eq_u32 vcc, v0, 2", - f"v_cndmask_b32 v7, v7, {f32_bits(-15.0):#x}, vcc", - f"v_cndmask_b32 v8, v8, {f32_bits(5.0):#x}, vcc", - f"v_mov_b32 v5, {OLD:#x}", - "v_and_b32 v9, v0, 1", - "v_cmpx_eq_u32 v9, 0", - "v_rcp_f32_e32 v2, v8", - "v_fma_f32 v3, -v8, v2, 1.0", - "v_fma_f32 v4, v2, v3, v2", - "v_mul_f32_e32 v5, v7, v4", - "s_mov_b32 exec_lo, -1", - "buffer_store_dword v5, v6, s[0:3], 0 offen", - ] - run_cs(lines, group_size=4, subgroup_size=32, memory=mem) - self.assertEqual( - [mem[4 * i] for i in range(4)], - [f32_bits(5.0), OLD, f32_bits(-3.0), OLD], - ) - - -class NewtonRaphsonAccuracyAndEdgeCaseTests(unittest.TestCase): - def test_quotient_accuracy_within_one_ulp_wide_dynamic_range(self): - cases = ( - (1.0e-30, 2.0), - (3.14159265e-25, 1.41421356e-20), - (1.0e-15, 3.0), - (1.0e-5, 7.0), - (1.0, 3.0), - (7.0, 3.0), - (22.0, 7.0), - (355.0, 113.0), - (1.234567e5, 9.87654e-5), - (1.0e15, 3.0e5), - (1.0e25, 2.5e10), - (1.0e30, 4.0e15), - (-1.0e20, 3.0), - (1.0e20, -7.0), - (-5.5e15, -1.1e5), - ) - for a_f, b_f in cases: - with self.subTest(a=a_f, b=b_f): - ab = f32_bits(a_f) - bb = f32_bits(b_f) - got = run_nr_fdiv_ps(ab, bb) - exact = ref_exact_fdiv_f32(ab, bb) - ulp = f32_ulp_diff(got, exact) - self.assertLessEqual( - ulp, 1, - f"Accuracy exceeds 1 ULP for {a_f}/{b_f}: got {got:#010x}, exact {exact:#010x}, diff {ulp}" - ) - - def test_subnormal_quotients_and_inputs(self): - cases = ( - ("subnormal_div_2", 0x00000004, f32_bits(2.0), 0x00000002), - ("neg_subnormal_div_2", 0x80000004, f32_bits(2.0), 0x80000002), - ("subnormal_div_half", 0x00000002, f32_bits(0.5), 0x00000004), - ("normal_underflow_to_subnormal", 0x00400000, f32_bits(2.0), 0x00200000), - ("subnormal_divisor_to_normal", f32_bits(1.0), 0x00400000, 0x7F000000), - ) - for name, ab, bb, want in cases: - with self.subTest(case=name): - got = run_nr_fdiv_ps(ab, bb) - self.assertEqual(got, want) - - def test_sign_rule_preservation(self): - cases = ( - (f32_bits(6.0), f32_bits(2.0), f32_bits(3.0)), - (f32_bits(6.0), f32_bits(-2.0), f32_bits(-3.0)), - (f32_bits(-6.0), f32_bits(2.0), f32_bits(-3.0)), - (f32_bits(-6.0), f32_bits(-2.0), f32_bits(3.0)), - (0x00000000, f32_bits(2.0), 0x00000000), - (0x80000000, f32_bits(2.0), 0x80000000), - (0x00000000, f32_bits(-2.0), 0x80000000), - (0x80000000, f32_bits(-2.0), 0x00000000), - ) - for ab, bb, want in cases: - with self.subTest(a=hex(ab), b=hex(bb)): - self.assertEqual(run_nr_fdiv_ps(ab, bb), want) - - def test_zero_and_infinite_divisor_behavior(self): - # Division by +-0.0 is undefined in SPIR-V and raises UnsupportedConstruct - for z in (0x00000000, 0x80000000): - with self.subTest(zero=hex(z)): - with self.assertRaises(si.UnsupportedConstruct): - run_nr_fdiv_ps(f32_bits(1.0), z) - - # Infinite divisor: 1 / +-inf -> +-0.0, step 2 FMA calculates 1 - inf * 0 -> NaN - for inf_bits in (0x7F800000, 0xFF800000): - with self.subTest(inf=hex(inf_bits)): - got = run_nr_fdiv_ps(f32_bits(1.0), inf_bits) - self.assertTrue(is_f32_nan_bits(got), f"expected NaN from inf divisor, got {got:#010x}") - - def test_negative_controls_for_pipeline_sabotage(self): - a = f32_bits(7.0) - b = f32_bits(3.0) - lines = [ - f"v_mov_b32 v0, {a:#x}", - f"v_mov_b32 v1, {b:#x}", - "v_rcp_f32_e32 v2, v1", - "v_fma_f32 v3, -v1, v2, 1.0", - "v_fma_f32 v4, v2, v3, v2", - "v_mul_f32_e32 v0, v0, v4", - ] - spv = translate_ps(lines) - correct_res = si.run_fragment(spv)["%out_mrt0"][0] - want = ref_newton_raphson_fdiv_f32(a, b) - self.assertEqual(correct_res, want) - - # Sabotage 1: Corrupt error-term FMA to FMul - bad_fma, n1 = re.subn(r"OpExtInst %float %glsl Fma\b", "OpFMul %float", spv, count=1) - self.assertEqual(n1, 1) - bad_res1 = si.run_fragment(bad_fma)["%out_mrt0"][0] - self.assertNotEqual(bad_res1, want) - self.assertGreater(f32_ulp_diff(bad_res1, want), 1000) - - # Sabotage 2: Corrupt final FMul to FAdd - bad_mul, n2 = re.subn(r"OpFMul %float\b", "OpFAdd %float", spv, count=1) - self.assertEqual(n2, 1) - bad_res2 = si.run_fragment(bad_mul)["%out_mrt0"][0] - self.assertNotEqual(bad_res2, want) - self.assertGreater(f32_ulp_diff(bad_res2, want), 1000) - - # Sabotage 3: Inverting FMA sign (+b instead of -b in error term) - lines_bad_sign = [ - f"v_mov_b32 v0, {a:#x}", - f"v_mov_b32 v1, {b:#x}", - "v_rcp_f32_e32 v2, v1", - "v_fma_f32 v3, v1, v2, 1.0", - "v_fma_f32 v4, v2, v3, v2", - "v_mul_f32_e32 v0, v0, v4", - ] - bad_sign_res = run_ps_v0(lines_bad_sign) - self.assertNotEqual(bad_sign_res, want) - self.assertGreater(f32_ulp_diff(bad_sign_res, want), 1000) - - # Sabotage 4: Dropping base term in refinement (y0*e instead of y0 + y0*e) - lines_bad_refine = [ - f"v_mov_b32 v0, {a:#x}", - f"v_mov_b32 v1, {b:#x}", - "v_rcp_f32_e32 v2, v1", - "v_fma_f32 v3, -v1, v2, 1.0", - "v_fma_f32 v4, v2, v3, 0.0", - "v_mul_f32_e32 v0, v0, v4", - ] - bad_refine_res = run_ps_v0(lines_bad_refine) - self.assertNotEqual(bad_refine_res, want) - self.assertGreater(f32_ulp_diff(bad_refine_res, want), 1000) - - -class NegativeControlTests(unittest.TestCase): - def test_sabotaged_spirv_is_detected(self): - cases = ( - ("v_rcp_f32_e32 v0, v1", f32_bits(4.0), f32_bits(0.25)), - ("v_rcp_iflag_f32_e64 v0, v1 mul:2", f32_bits(4.0), f32_bits(0.5)), - ("v_rcp_f16_e64 v0, v1 op_sel:[0,1]", (H_1P0 << 16) | H_4P0, merge_half(OLD, H_0P25, 1)), - ) - for line, v1_bits, want in cases: - with self.subTest(line=line): - spv = translate_ps([f"v_mov_b32 v0, {OLD:#x}", f"v_mov_b32 v1, {v1_bits:#x}", line]) - self.assertEqual(si.run_fragment(spv)["%out_mrt0"][0], want) - bad, n = re.subn(r"OpFDiv %float %f1\b", "OpFMul %float %f1", spv, count=1) - self.assertEqual(n, 1) - self.assertNotEqual(si.run_fragment(bad)["%out_mrt0"][0], want) - - # Sabotaging FClamp on v_rcp_iflag_f32_e64 clamp changes clamped 1/0.5 = 2.0 -> 1.0. - spv_clamp = translate_ps([ - f"v_mov_b32 v0, {OLD:#x}", - f"v_mov_b32 v1, {f32_bits(0.5):#x}", - "v_rcp_iflag_f32_e64 v0, v1 clamp", - ]) - self.assertEqual(si.run_fragment(spv_clamp)["%out_mrt0"][0], f32_bits(1.0)) - bad_clamp, n = re.subn(r"OpExtInst %float %glsl FClamp (%\w+) %f0 %f1", r"OpCopyObject %float \1", spv_clamp) - self.assertEqual(n, 1) - self.assertEqual(si.run_fragment(bad_clamp)["%out_mrt0"][0], f32_bits(2.0)) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_valu_rsq_f16.py b/tests/semantic/test_valu_rsq_f16.py deleted file mode 100644 index bbc7f5573..000000000 --- a/tests/semantic/test_valu_rsq_f16.py +++ /dev/null @@ -1,46 +0,0 @@ -"""v_rsq_f16 (RDNA2 VOP1 / VOP3): D.f16 = 1.0 / sqrt(S0.f16), correctly rounded (0 ulp on every non-NaN input on hardware, -docs/design.md "f16 transcendentals"), with rsq(+0) = +inf, rsq(-0) = -inf, rsq(+inf) = +0, and a NaN for a negative -operand (-inf included). - -Every case is translated by tools/rdna2spirv.py and executed with tests/semantic/spirv_mini_interp.py; the expected -word is written down by hand (from the ISA, values checked independently with float64) next to each case, rechecked -against the plain-Python reference in tests/semantic/f16_unary_cases.py, and extended with seeded random operands, -neg/abs, omod/clamp, op_sel, and SGPR / literal / inline-constant sources. A NaN result is compared by class, not -payload. Standard library only: no GPU, no LLVM, no game data. -""" -import os -import sys -import unittest - -sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) -from f16_unary_cases import (HALF, INF, MAXH, MAX_SUB, MIN_NORMAL, MIN_SUB, NINF, ONE, QNAN, QUARTER, TWO, # noqa: E402,F401 - UnaryF16, ref_rsq, run, same_f16) # noqa: F401 - - -class RsqF16(UnaryF16, unittest.TestCase): - OP = "v_rsq_f16" - ref = staticmethod(ref_rsq) - CASES = [ - (ONE, ONE), (0x4400, HALF), (0x4C00, QUARTER), (QUARTER, TWO), - (TWO, 0x39A8), # 0.70710678 = 1.41421 * 2^-1, mantissa 424 - (0x4200, 0x389E), # 0.57735027 - (HALF, 0x3DA8), # 1.41421356 - (0x4900, 0x350F), # rsq(10) = 0.31622777 - (0x5640, 0x2E66), # rsq(100) = 0.1 - (MAXH, 0x1C00), # rsq(65504) = 0.0039070 -> 2^-8 = 0.00390625 - (MIN_NORMAL, 0x5800), # rsq(2^-14) = 2^7 = 128 - (MIN_SUB, 0x6C00), # rsq(2^-24) = 2^12 = 4096 - (MAX_SUB, 0x5801), - (0x0000, INF), (0x8000, NINF), # rsq(+-0) = +-inf - (INF, 0x0000), - (NINF, QNAN), (0xBC00, QNAN), (0x8001, QNAN), # a negative operand is a NaN (0xfe00 on hardware) - (QNAN, QNAN), - ] - MOD_INPUTS = [0x4400, 0x4900, QUARTER, 0xC400] - INLINE = [("4.0", 0x4400, HALF), ("1.0", ONE, ONE), ("0.5", HALF, 0x3DA8), ("2.0", TWO, 0x39A8), - ("-1.0", 0xBC00, QNAN)] - OP_SEL = [((0x4C00 << 16) | 0x4400, HALF, QUARTER)] # lo 4.0 / hi 16.0 - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_valu_rsq_f64.py b/tests/semantic/test_valu_rsq_f64.py deleted file mode 100644 index 6fe6efed8..000000000 --- a/tests/semantic/test_valu_rsq_f64.py +++ /dev/null @@ -1,1509 +0,0 @@ -"""Semantic interpreter tests and reference mathematical oracle for RDNA2 v_rsq_f64. - -Models IEEE 754-2008 / IEEE 754-2019 binary64 double-precision reciprocal square root -and AMD RDNA2 / GFX10 Vector Arithmetic Logic Unit (VALU) architectural semantics: - D.d = 1.0 / sqrt(S0.d) - -RDNA2 Double-Precision Floating-Point ISA Rules: - 1. Register Pair Allocation: - Double-precision 64-bit values occupy aligned pairs of 32-bit vector registers: - v[d:d+1] where low 32 bits reside in v[d] and high 32 bits in v[d+1]. - 2. Reciprocal Square Root Operation: - Computes the IEEE 754 reciprocal square root of S0. - - Positive finite numbers: 1.0 / sqrt(S0). Exact powers of 4 and 2 yield exact results: - rsq(1.0) = 1.0, rsq(4.0) = 0.5, rsq(16.0) = 0.25, rsq(0.25) = 2.0, rsq(0.0625) = 4.0. - - Zeros: rsq(+0.0) = +Infinity, rsq(-0.0) = +Infinity. - - Positive Infinity: rsq(+Infinity) = +0.0. - - Negative numbers & -Infinity: square root of negative is invalid, producing Quiet NaN. - - NaNs: Quiet NaN propagates; Signaling NaN is quieted. - 3. Modifiers (VOP3 encoding): - - Input modifiers: abs (|S0|) clears sign bit 63; neg (-S0) toggles sign bit 63. - - Output modifier: clamp saturates result to [0.0, 1.0]. Clamping negative/NaN yields +0.0. - 4. Subnormals & Flush-to-Zero: - Under IEEE mode, subnormal double values are computed with full precision. - Under flush-to-zero (FTZ), subnormal inputs flush to signed zero, yielding +Infinity. - -Standard library Python only; zero third-party dependencies; zero game data. -Python 3.9+ compatible (from __future__ import annotations). -""" -from __future__ import annotations - -from dataclasses import dataclass, field -from enum import Enum, auto -import math -import struct -import unittest -from typing import List, Optional, Tuple, Union - -MASK32: int = 0xFFFF_FFFF -MASK64: int = 0xFFFF_FFFF_FFFF_FFFF -SIGN_MASK: int = 0x8000_0000_0000_0000 -EXP_MASK: int = 0x7FF0_0000_0000_0000 -FRAC_MASK: int = 0x000F_FFFF_FFFF_FFFF -QNAN_BIT: int = 0x0008_0000_0000_0000 -CANONICAL_QNAN: int = 0x7FF8_0000_0000_0000 - -# Canonical IEEE 754 binary64 bit patterns -POS_ZERO: int = 0x0000_0000_0000_0000 -NEG_ZERO: int = 0x8000_0000_0000_0000 -POS_INF: int = 0x7FF0_0000_0000_0000 -NEG_INF: int = 0xFFF0_0000_0000_0000 - -ONE_F64: int = 0x3FF0_0000_0000_0000 # 1.0 -FOUR_F64: int = 0x4010_0000_0000_0000 # 4.0 -SIXTEEN_F64: int = 0x4030_0000_0000_0000 # 16.0 -SIXTY_FOUR_F64: int = 0x4050_0000_0000_0000 # 64.0 -QUARTER_F64: int = 0x3FD0_0000_0000_0000 # 0.25 -SIXTEENTH_F64: int = 0x3FB0_0000_0000_0000 # 0.0625 -HALF_F64: int = 0x3FE0_0000_0000_0000 # 0.5 -TWO_F64: int = 0x4000_0000_0000_0000 # 2.0 -THREE_F64: int = 0x4008_0000_0000_0000 # 3.0 -NINE_F64: int = 0x4022_0000_0000_0000 # 9.0 -HUNDRED_F64: int = 0x4059_0000_0000_0000 # 100.0 - -NEG_ONE_F64: int = 0xBFF0_0000_0000_0000 # -1.0 -NEG_FOUR_F64: int = 0xC010_0000_0000_0000 # -4.0 -NEG_QUARTER_F64: int = 0xBFD0_0000_0000_0000 # -0.25 - -DBL_MIN: int = 0x0010_0000_0000_0000 # Smallest positive normal: 2^-1022 -DBL_MAX: int = 0x7FEF_FFFF_FFFF_FFFF # Largest finite positive float -SUBNORM_MIN: int = 0x0000_0000_0000_0001 # Smallest positive subnormal: 2^-1074 -SUBNORM_MAX: int = 0x000F_FFFF_FFFF_FFFF # Largest positive subnormal - - -def f64_to_bits(val: float) -> int: - """Convert Python float (IEEE 754 double) to 64-bit unsigned integer bits.""" - return struct.unpack(" float: - """Convert 64-bit unsigned integer bits to Python float (IEEE 754 double).""" - return struct.unpack(" Tuple[int, int, int]: - """Unpack bits into (sign, exponent, fraction) components.""" - sign = (bits & SIGN_MASK) >> 63 - exponent = (bits & EXP_MASK) >> 52 - fraction = bits & FRAC_MASK - return sign, exponent, fraction - - -def words_to_f64_bits(lo: int, hi: int) -> int: - """Combine two 32-bit VGPR words (lo, hi) into a 64-bit integer representation.""" - return ((hi & MASK32) << 32) | (lo & MASK32) - - -def f64_bits_to_words(bits: int) -> Tuple[int, int]: - """Split a 64-bit integer into two 32-bit VGPR words (lo, hi).""" - lo = bits & MASK32 - hi = (bits >> 32) & MASK32 - return lo, hi - - -def is_nan(bits: int) -> bool: - """Return True if bits represent an IEEE 754 NaN.""" - return ((bits & EXP_MASK) == EXP_MASK) and ((bits & FRAC_MASK) != 0) - - -def is_qnan(bits: int) -> bool: - """Return True if bits represent an IEEE 754 Quiet NaN.""" - return is_nan(bits) and bool(bits & QNAN_BIT) - - -def is_snan(bits: int) -> bool: - """Return True if bits represent an IEEE 754 Signaling NaN.""" - return is_nan(bits) and not bool(bits & QNAN_BIT) - - -def is_inf(bits: int) -> bool: - """Return True if bits represent IEEE 754 positive or negative infinity.""" - return ((bits & EXP_MASK) == EXP_MASK) and ((bits & FRAC_MASK) == 0) - - -def is_subnormal(bits: int) -> bool: - """Return True if bits represent a subnormal (denormal) double-precision float.""" - return ((bits & EXP_MASK) == 0) and ((bits & FRAC_MASK) != 0) - - -def is_zero(bits: int) -> bool: - """Return True if bits represent positive or negative zero.""" - return (bits & ~SIGN_MASK) == 0 - - -def apply_f64_modifiers(bits: int, abs_mod: bool, neg_mod: bool) -> int: - """Apply VOP3 input modifiers: abs clears sign bit; neg toggles sign bit.""" - res = bits & MASK64 - if abs_mod: - res &= ~SIGN_MASK - if neg_mod: - res ^= SIGN_MASK - return res - - -def oracle_v_rsq_f64( - src_bits: int, - abs_src: bool = False, - neg_src: bool = False, - clamp: bool = False, - flush_subnormals: bool = False, -) -> int: - """Reference mathematical oracle for RDNA2 v_rsq_f64. - - Computes D = 1.0 / sqrt(src) according to IEEE 754-2008 / RDNA2 VALU rules: - - abs_src / neg_src input modifiers applied before root calculation. - - Flush-to-zero flushes subnormal input to signed zero. - - NaN input produces Quiet NaN (or +0.0 if clamp is enabled). - - Negative non-zero and -Infinity inputs produce Canonical Quiet NaN (or +0.0 if clamp is enabled). - - +0.0 and -0.0 produce +Infinity (clamped to 1.0 if clamp is enabled). - - +Infinity produces +0.0. - - Finite positive numbers produce 1.0 / sqrt(x), clamped to [0.0, 1.0] if clamp is enabled. - """ - s = apply_f64_modifiers(src_bits, abs_src, neg_src) - - # 1. Subnormal flush-to-zero mode - if flush_subnormals and is_subnormal(s): - s = NEG_ZERO if (s & SIGN_MASK) else POS_ZERO - - # 2. NaN inputs propagate quieted NaN - if is_nan(s): - if clamp: - return POS_ZERO - return s | QNAN_BIT - - # 3. Negative non-zero or negative infinity yields Quiet NaN - if (s & SIGN_MASK) and not is_zero(s): - if clamp: - return POS_ZERO - return CANONICAL_QNAN - - # 4. Zero inputs (+0.0, -0.0) produce +Infinity - if is_zero(s): - if clamp: - return ONE_F64 - return POS_INF - - # 5. Positive Infinity yields +0.0 - if s == POS_INF: - return POS_ZERO - - # 6. Finite positive calculation - val = bits_to_f64(s) - res_val = 1.0 / math.sqrt(val) - - if clamp: - if res_val < 0.0: - res_val = 0.0 - elif res_val > 1.0: - res_val = 1.0 - - return f64_to_bits(res_val) - - -class TestF64ModelAndOracle(unittest.TestCase): - """Unit tests for IEEE 754 binary64 bit functions and the reference v_rsq_f64 oracle.""" - - def test_exact_powers_of_four_and_two(self) -> None: - """Exact square roots and reciprocals must be bit-exact in binary64.""" - self.assertEqual(oracle_v_rsq_f64(ONE_F64), ONE_F64) - self.assertEqual(oracle_v_rsq_f64(FOUR_F64), HALF_F64) - self.assertEqual(oracle_v_rsq_f64(SIXTEEN_F64), QUARTER_F64) - self.assertEqual(oracle_v_rsq_f64(SIXTY_FOUR_F64), f64_to_bits(0.125)) - self.assertEqual(oracle_v_rsq_f64(QUARTER_F64), TWO_F64) - self.assertEqual(oracle_v_rsq_f64(SIXTEENTH_F64), FOUR_F64) - - def test_positive_finite_non_integers(self) -> None: - """Test reciprocal square root for general positive floating point values.""" - res_nine = bits_to_f64(oracle_v_rsq_f64(NINE_F64)) - self.assertAlmostEqual(res_nine, 1.0 / 3.0, places=15) - - res_hundred = bits_to_f64(oracle_v_rsq_f64(HUNDRED_F64)) - self.assertAlmostEqual(res_hundred, 0.1, places=15) - - res_two = bits_to_f64(oracle_v_rsq_f64(TWO_F64)) - self.assertAlmostEqual(res_two, 1.0 / math.sqrt(2.0), places=15) - - def test_zero_inputs_produce_positive_infinity(self) -> None: - """Both +0.0 and -0.0 yield +Infinity in AMD RDNA2 RSQ semantics.""" - self.assertEqual(oracle_v_rsq_f64(POS_ZERO), POS_INF) - self.assertEqual(oracle_v_rsq_f64(NEG_ZERO), POS_INF) - - def test_positive_infinity_yields_positive_zero(self) -> None: - """1.0 / sqrt(+Inf) yields +0.0.""" - self.assertEqual(oracle_v_rsq_f64(POS_INF), POS_ZERO) - - def test_negative_inputs_produce_canonical_qnan(self) -> None: - """Square root of negative real numbers produces Quiet NaN.""" - self.assertEqual(oracle_v_rsq_f64(NEG_ONE_F64), CANONICAL_QNAN) - self.assertEqual(oracle_v_rsq_f64(NEG_FOUR_F64), CANONICAL_QNAN) - self.assertEqual(oracle_v_rsq_f64(NEG_QUARTER_F64), CANONICAL_QNAN) - self.assertEqual(oracle_v_rsq_f64(NEG_INF), CANONICAL_QNAN) - - def test_nan_inputs_propagate_quieted(self) -> None: - """NaN operands propagate quieted NaN.""" - qnan_in = CANONICAL_QNAN | 0x1234 - snan_in = POS_INF | 0x0001_0000 # Signaling NaN - self.assertTrue(is_qnan(oracle_v_rsq_f64(qnan_in))) - self.assertTrue(is_qnan(oracle_v_rsq_f64(snan_in))) - - def test_input_modifiers_abs_and_neg(self) -> None: - """Input modifiers abs and neg transform operand before root calculation.""" - # abs(-4.0) -> +4.0 -> rsq gives 0.5 - self.assertEqual(oracle_v_rsq_f64(NEG_FOUR_F64, abs_src=True), HALF_F64) - # neg(4.0) -> -4.0 -> rsq gives NaN - self.assertEqual(oracle_v_rsq_f64(FOUR_F64, neg_src=True), CANONICAL_QNAN) - # neg(-4.0) -> +4.0 -> rsq gives 0.5 - self.assertEqual(oracle_v_rsq_f64(NEG_FOUR_F64, neg_src=True), HALF_F64) - # abs and neg together on positive: neg(abs(4.0)) -> -4.0 -> NaN - self.assertEqual(oracle_v_rsq_f64(FOUR_F64, abs_src=True, neg_src=True), CANONICAL_QNAN) - - def test_clamp_modifier(self) -> None: - """Clamp modifier saturates result to [0.0, 1.0].""" - # 0.25 -> 2.0 -> clamped to 1.0 - self.assertEqual(oracle_v_rsq_f64(QUARTER_F64, clamp=True), ONE_F64) - # 4.0 -> 0.5 -> within [0.0, 1.0] -> unchanged - self.assertEqual(oracle_v_rsq_f64(FOUR_F64, clamp=True), HALF_F64) - # +0.0 -> +inf -> clamped to 1.0 - self.assertEqual(oracle_v_rsq_f64(POS_ZERO, clamp=True), ONE_F64) - # Negative -> NaN -> clamped to +0.0 - self.assertEqual(oracle_v_rsq_f64(NEG_FOUR_F64, clamp=True), POS_ZERO) - # NaN -> clamped to +0.0 - self.assertEqual(oracle_v_rsq_f64(CANONICAL_QNAN, clamp=True), POS_ZERO) - - def test_subnormal_handling(self) -> None: - """Subnormal precision preservation in IEEE mode and flush in FTZ mode.""" - sub = SUBNORM_MAX - res_ieee = oracle_v_rsq_f64(sub, flush_subnormals=False) - self.assertFalse(is_nan(res_ieee)) - self.assertFalse(is_inf(res_ieee)) - self.assertGreater(bits_to_f64(res_ieee), 1.0) - - # In FTZ mode, subnormal flushes to +0.0, so rsq gives +Infinity - res_ftz = oracle_v_rsq_f64(sub, flush_subnormals=True) - self.assertEqual(res_ftz, POS_INF) - - def test_word_conversion_helpers(self) -> None: - """Splitting and joining 32-bit dwords must roundtrip 64-bit values accurately.""" - lo, hi = f64_bits_to_words(FOUR_F64) - rejoined = words_to_f64_bits(lo, hi) - self.assertEqual(rejoined, FOUR_F64) - - sign, exp, frac = split_f64_bits(FOUR_F64) - self.assertEqual(sign, 0) - self.assertEqual(exp, 1025) - self.assertEqual(frac, 0) - - -# ============================================================================ -# Section 2: Symbolic AST Opcode Definitions and Typed Expressions -# ============================================================================ - -class RegType(Enum): - """Architectural register file identifier.""" - VGPR = auto() - SGPR = auto() - LITERAL = auto() - - -@dataclass(frozen=True) -class RegPair: - """An aligned 64-bit pair of 32-bit registers (v[d:d+1] or s[s:s+1]).""" - index: int - reg_type: RegType = RegType.VGPR - - def __post_init__(self) -> None: - if self.reg_type == RegType.VGPR: - if not (0 <= self.index <= 254): - raise ValueError(f"VGPR index {self.index} out of valid range [0, 254] for a 64-bit pair") - elif self.reg_type == RegType.SGPR: - if not (0 <= self.index <= 104): - raise ValueError(f"SGPR index {self.index} out of valid range [0, 104] for a 64-bit pair") - else: - raise ValueError(f"Invalid register type for RegPair: {self.reg_type}") - - @property - def low(self) -> int: - """Low 32-bit dword register index.""" - return self.index - - @property - def high(self) -> int: - """High 32-bit dword register index.""" - return self.index + 1 - - def __str__(self) -> str: - prefix = "v" if self.reg_type == RegType.VGPR else "s" - return f"{prefix}[{self.index}:{self.index + 1}]" - - -@dataclass(frozen=True) -class Literal64: - """A 64-bit immediate constant bit pattern.""" - bits: int - - def __post_init__(self) -> None: - if not (0 <= self.bits <= MASK64): - raise ValueError(f"Literal64 bits {hex(self.bits)} out of range [0, 2^64-1]") - - @classmethod - def from_float(cls, val: float) -> Literal64: - return cls(f64_to_bits(val)) - - def to_float(self) -> float: - return bits_to_f64(self.bits) - - def __str__(self) -> str: - return f"0x{self.bits:016x}" - - -@dataclass(frozen=True) -class VOP3Operand: - """A VOP3 source operand with optional input modifiers (abs and neg).""" - reg_pair: Optional[RegPair] = None - literal: Optional[Literal64] = None - abs_mod: bool = False - neg_mod: bool = False - - def __post_init__(self) -> None: - if (self.reg_pair is None) == (self.literal is None): - raise ValueError("VOP3Operand must specify exactly one of reg_pair or literal") - - @classmethod - def from_vgpr(cls, index: int, abs_mod: bool = False, neg_mod: bool = False) -> VOP3Operand: - return cls(reg_pair=RegPair(index, RegType.VGPR), abs_mod=abs_mod, neg_mod=neg_mod) - - @classmethod - def from_sgpr(cls, index: int, abs_mod: bool = False, neg_mod: bool = False) -> VOP3Operand: - return cls(reg_pair=RegPair(index, RegType.SGPR), abs_mod=abs_mod, neg_mod=neg_mod) - - @classmethod - def from_lit(cls, bits: int, abs_mod: bool = False, neg_mod: bool = False) -> VOP3Operand: - return cls(literal=Literal64(bits), abs_mod=abs_mod, neg_mod=neg_mod) - - def __str__(self) -> str: - core = str(self.reg_pair) if self.reg_pair is not None else str(self.literal) - if self.abs_mod: - core = f"|{core}|" - if self.neg_mod: - core = f"-{core}" - return core - - -@dataclass(frozen=True) -class VRSQF64Instruction: - """Symbolic AST node for RDNA2 VALU v_rsq_f64 instruction.""" - dst: RegPair - src0: VOP3Operand - clamp: bool = False - flush_denorms: bool = False - - def __post_init__(self) -> None: - if self.dst.reg_type != RegType.VGPR: - raise ValueError(f"Destination must be a VGPR pair, got {self.dst.reg_type}") - - def disasm(self) -> str: - """Render GCN/RDNA assembly representation.""" - res = f"v_rsq_f64 {self.dst}, {self.src0}" - if self.clamp: - res += " clamp" - return res - - -class TestSymbolicAST(unittest.TestCase): - """Unit tests for symbolic AST opcode definitions and typed expressions.""" - - def test_reg_pair_creation_and_bounds(self) -> None: - """Test register pair construction, indexing, and boundary validation.""" - v = RegPair(0, RegType.VGPR) - self.assertEqual(v.low, 0) - self.assertEqual(v.high, 1) - self.assertEqual(str(v), "v[0:1]") - - s = RegPair(10, RegType.SGPR) - self.assertEqual(s.low, 10) - self.assertEqual(s.high, 11) - self.assertEqual(str(s), "s[10:11]") - - # Boundary checks - RegPair(254, RegType.VGPR) - RegPair(104, RegType.SGPR) - with self.assertRaises(ValueError): - RegPair(255, RegType.VGPR) - with self.assertRaises(ValueError): - RegPair(105, RegType.SGPR) - with self.assertRaises(ValueError): - RegPair(-1, RegType.VGPR) - - def test_literal64_creation(self) -> None: - """Test 64-bit immediate literal operand.""" - lit = Literal64(0x3FF0_0000_0000_0000) - self.assertEqual(lit.to_float(), 1.0) - self.assertEqual(str(lit), "0x3ff0000000000000") - - lit2 = Literal64.from_float(4.0) - self.assertEqual(lit2.bits, FOUR_F64) - - with self.assertRaises(ValueError): - Literal64(-1) - with self.assertRaises(ValueError): - Literal64(1 << 64) - - def test_vop3_operand_formatting(self) -> None: - """Test formatting of VOP3 operands with input modifiers.""" - op_plain = VOP3Operand.from_vgpr(4) - self.assertEqual(str(op_plain), "v[4:5]") - - op_abs = VOP3Operand.from_vgpr(4, abs_mod=True) - self.assertEqual(str(op_abs), "|v[4:5]|") - - op_neg = VOP3Operand.from_vgpr(4, neg_mod=True) - self.assertEqual(str(op_neg), "-v[4:5]") - - op_neg_abs = VOP3Operand.from_vgpr(4, abs_mod=True, neg_mod=True) - self.assertEqual(str(op_neg_abs), "-|v[4:5]|") - - op_sgpr = VOP3Operand.from_sgpr(0) - self.assertEqual(str(op_sgpr), "s[0:1]") - - op_lit = VOP3Operand.from_lit(ONE_F64) - self.assertEqual(str(op_lit), "0x3ff0000000000000") - - with self.assertRaises(ValueError): - VOP3Operand(reg_pair=None, literal=None) - - def test_instruction_disasm(self) -> None: - """Test disassembly output of VRSQF64Instruction.""" - instr_basic = VRSQF64Instruction( - dst=RegPair(0, RegType.VGPR), - src0=VOP3Operand.from_vgpr(2), - ) - self.assertEqual(instr_basic.disasm(), "v_rsq_f64 v[0:1], v[2:3]") - - instr_mod = VRSQF64Instruction( - dst=RegPair(4, RegType.VGPR), - src0=VOP3Operand.from_vgpr(6, abs_mod=True, neg_mod=True), - clamp=True, - ) - self.assertEqual(instr_mod.disasm(), "v_rsq_f64 v[4:5], -|v[6:7]| clamp") - - # Destination must be VGPR - with self.assertRaises(ValueError): - VRSQF64Instruction( - dst=RegPair(0, RegType.SGPR), - src0=VOP3Operand.from_vgpr(2), - ) - - -# ============================================================================ -# Section 3: Deterministic Scalar Instruction Interpreter -# ============================================================================ - -@dataclass -class ScalarMachineState: - """Architectural register state of an AMD RDNA2 compute unit single thread.""" - vgprs: List[int] = field(default_factory=lambda: [0] * 256) - sgprs: List[int] = field(default_factory=lambda: [0] * 106) - pc: int = 0 - cycle_count: int = 0 - - def read_vgpr(self, index: int) -> int: - return self.vgprs[index] & MASK32 - - def write_vgpr(self, index: int, val: int) -> None: - self.vgprs[index] = val & MASK32 - - def read_sgpr(self, index: int) -> int: - return self.sgprs[index] & MASK32 - - def write_sgpr(self, index: int, val: int) -> None: - self.sgprs[index] = val & MASK32 - - def read_vgpr_pair(self, index: int) -> int: - lo = self.read_vgpr(index) - hi = self.read_vgpr(index + 1) - return words_to_f64_bits(lo, hi) - - def write_vgpr_pair(self, index: int, val64: int) -> None: - lo, hi = f64_bits_to_words(val64) - self.write_vgpr(index, lo) - self.write_vgpr(index + 1, hi) - - def read_sgpr_pair(self, index: int) -> int: - lo = self.read_sgpr(index) - hi = self.read_sgpr(index + 1) - return words_to_f64_bits(lo, hi) - - def write_sgpr_pair(self, index: int, val64: int) -> None: - lo, hi = f64_bits_to_words(val64) - self.write_sgpr(index, lo) - self.write_sgpr(index + 1, hi) - - def read_operand_raw_bits(self, op: VOP3Operand) -> int: - if op.literal is not None: - return op.literal.bits - assert op.reg_pair is not None - if op.reg_pair.reg_type == RegType.VGPR: - return self.read_vgpr_pair(op.reg_pair.index) - elif op.reg_pair.reg_type == RegType.SGPR: - return self.read_sgpr_pair(op.reg_pair.index) - raise ValueError(f"Unknown register type {op.reg_pair.reg_type}") - - -class ScalarInterpreter: - """Deterministic scalar instruction interpreter for RDNA2 VALU instructions.""" - - def __init__(self, state: Optional[ScalarMachineState] = None) -> None: - self.state = state if state is not None else ScalarMachineState() - - def execute(self, instr: VRSQF64Instruction) -> int: - """Step a single VRSQF64Instruction against scalar state.""" - raw_bits = self.state.read_operand_raw_bits(instr.src0) - res_bits = oracle_v_rsq_f64( - raw_bits, - abs_src=instr.src0.abs_mod, - neg_src=instr.src0.neg_mod, - clamp=instr.clamp, - flush_subnormals=instr.flush_denorms, - ) - self.state.write_vgpr_pair(instr.dst.index, res_bits) - self.state.pc += 4 - self.state.cycle_count += 1 - return res_bits - - -class TestScalarInterpreter(unittest.TestCase): - """Unit tests for deterministic scalar instruction execution.""" - - def test_vgpr_to_vgpr_execution(self) -> None: - """Execute v_rsq_f64 reading from VGPR pair and writing to VGPR pair.""" - state = ScalarMachineState() - # Set v[2:3] = 4.0 - state.write_vgpr_pair(2, FOUR_F64) - - instr = VRSQF64Instruction( - dst=RegPair(0, RegType.VGPR), - src0=VOP3Operand.from_vgpr(2), - ) - interp = ScalarInterpreter(state) - res = interp.execute(instr) - - self.assertEqual(res, HALF_F64) - self.assertEqual(state.read_vgpr_pair(0), HALF_F64) - self.assertEqual(state.read_vgpr_pair(2), FOUR_F64) - self.assertEqual(state.pc, 4) - self.assertEqual(state.cycle_count, 1) - - def test_sgpr_source_execution(self) -> None: - """Execute v_rsq_f64 with SGPR pair as source operand.""" - state = ScalarMachineState() - # Set s[4:5] = 16.0 - state.write_sgpr_pair(4, SIXTEEN_F64) - - instr = VRSQF64Instruction( - dst=RegPair(0, RegType.VGPR), - src0=VOP3Operand.from_sgpr(4), - ) - interp = ScalarInterpreter(state) - res = interp.execute(instr) - - self.assertEqual(res, QUARTER_F64) - self.assertEqual(state.read_vgpr_pair(0), QUARTER_F64) - - def test_literal_source_execution(self) -> None: - """Execute v_rsq_f64 with immediate 64-bit constant literal.""" - state = ScalarMachineState() - instr = VRSQF64Instruction( - dst=RegPair(10, RegType.VGPR), - src0=VOP3Operand.from_lit(QUARTER_F64), - ) - interp = ScalarInterpreter(state) - res = interp.execute(instr) - - self.assertEqual(res, TWO_F64) - self.assertEqual(state.read_vgpr_pair(10), TWO_F64) - - def test_input_modifiers_in_interpreter(self) -> None: - """Execute v_rsq_f64 with abs and neg input modifiers via interpreter.""" - state = ScalarMachineState() - state.write_vgpr_pair(6, NEG_FOUR_F64) - - # abs(-4.0) -> +4.0 -> rsq gives 0.5 - instr = VRSQF64Instruction( - dst=RegPair(0, RegType.VGPR), - src0=VOP3Operand.from_vgpr(6, abs_mod=True), - ) - interp = ScalarInterpreter(state) - self.assertEqual(interp.execute(instr), HALF_F64) - self.assertEqual(state.read_vgpr_pair(0), HALF_F64) - - def test_clamp_modifier_in_interpreter(self) -> None: - """Execute v_rsq_f64 with clamp modifier via interpreter.""" - state = ScalarMachineState() - state.write_vgpr_pair(2, QUARTER_F64) # rsq(0.25) = 2.0 -> clamped to 1.0 - - instr = VRSQF64Instruction( - dst=RegPair(8, RegType.VGPR), - src0=VOP3Operand.from_vgpr(2), - clamp=True, - ) - interp = ScalarInterpreter(state) - self.assertEqual(interp.execute(instr), ONE_F64) - self.assertEqual(state.read_vgpr_pair(8), ONE_F64) - - def test_register_isolation(self) -> None: - """Verify that writing to destination does not modify unaddressed registers.""" - state = ScalarMachineState() - state.write_vgpr(0, 0x1111_1111) - state.write_vgpr(1, 0x2222_2222) - state.write_vgpr(2, 0x3333_3333) - state.write_vgpr(3, 0x4444_4444) - state.write_vgpr_pair(4, FOUR_F64) - - instr = VRSQF64Instruction( - dst=RegPair(2, RegType.VGPR), - src0=VOP3Operand.from_vgpr(4), - ) - interp = ScalarInterpreter(state) - interp.execute(instr) - - # v[0:1] must remain untouched - self.assertEqual(state.read_vgpr(0), 0x1111_1111) - self.assertEqual(state.read_vgpr(1), 0x2222_2222) - # v[2:3] has updated result - self.assertEqual(state.read_vgpr_pair(2), HALF_F64) - - -# ============================================================================ -# Section 4: SIMD Multi-Lane Divergence and 32/64-Bit EXEC Masking -# ============================================================================ - -@dataclass -class SIMDState: - """Architectural state for a wavefront (Wave32 or Wave64) with EXEC masking.""" - num_lanes: int = 64 - exec_mask: int = MASK64 - lanes: List[List[int]] = field(default_factory=list) - sgprs: List[int] = field(default_factory=lambda: [0] * 106) - - def __post_init__(self) -> None: - if self.num_lanes not in (32, 64): - raise ValueError(f"num_lanes must be 32 or 64, got {self.num_lanes}") - if not self.lanes: - self.lanes = [[0] * 256 for _ in range(self.num_lanes)] - if self.num_lanes == 32: - self.exec_mask &= MASK32 - - def is_lane_active(self, lane_idx: int) -> bool: - """True if the lane's bit is enabled in the wavefront EXEC mask.""" - return bool(self.exec_mask & (1 << lane_idx)) - - def read_lane_vgpr(self, lane_idx: int, reg_idx: int) -> int: - return self.lanes[lane_idx][reg_idx] & MASK32 - - def write_lane_vgpr(self, lane_idx: int, reg_idx: int, val: int) -> None: - self.lanes[lane_idx][reg_idx] = val & MASK32 - - def read_lane_vgpr_pair(self, lane_idx: int, reg_idx: int) -> int: - lo = self.read_lane_vgpr(lane_idx, reg_idx) - hi = self.read_lane_vgpr(lane_idx, reg_idx + 1) - return words_to_f64_bits(lo, hi) - - def write_lane_vgpr_pair(self, lane_idx: int, reg_idx: int, val64: int) -> None: - lo, hi = f64_bits_to_words(val64) - self.write_lane_vgpr(lane_idx, reg_idx, lo) - self.write_lane_vgpr(lane_idx, reg_idx + 1, hi) - - def read_sgpr_pair(self, reg_idx: int) -> int: - lo = self.sgprs[reg_idx] & MASK32 - hi = self.sgprs[reg_idx + 1] & MASK32 - return words_to_f64_bits(lo, hi) - - def write_sgpr_pair(self, reg_idx: int, val64: int) -> None: - lo, hi = f64_bits_to_words(val64) - self.sgprs[reg_idx] = lo - self.sgprs[reg_idx + 1] = hi - - def read_lane_operand_bits(self, lane_idx: int, op: VOP3Operand) -> int: - if op.literal is not None: - return op.literal.bits - assert op.reg_pair is not None - if op.reg_pair.reg_type == RegType.VGPR: - return self.read_lane_vgpr_pair(lane_idx, op.reg_pair.index) - elif op.reg_pair.reg_type == RegType.SGPR: - return self.read_sgpr_pair(op.reg_pair.index) - raise ValueError(f"Unknown register type {op.reg_pair.reg_type}") - - -class SIMDInterpreter: - """SIMD wavefront execution engine modeling divergent multi-lane execution.""" - - def __init__(self, state: Optional[SIMDState] = None) -> None: - self.state = state if state is not None else SIMDState() - - def execute(self, instr: VRSQF64Instruction) -> List[Optional[int]]: - """Execute VRSQF64Instruction across all active lanes conditioned on EXEC mask.""" - results: List[Optional[int]] = [] - for lane in range(self.state.num_lanes): - if not self.state.is_lane_active(lane): - results.append(None) - continue - raw_bits = self.state.read_lane_operand_bits(lane, instr.src0) - res = oracle_v_rsq_f64( - raw_bits, - abs_src=instr.src0.abs_mod, - neg_src=instr.src0.neg_mod, - clamp=instr.clamp, - flush_subnormals=instr.flush_denorms, - ) - self.state.write_lane_vgpr_pair(lane, instr.dst.index, res) - results.append(res) - return results - - -class TestSIMDMultiLaneDivergence(unittest.TestCase): - """Unit tests for SIMD multi-lane divergence and 32/64-bit EXEC masking.""" - - def test_wave32_full_execution(self) -> None: - """Wave32 wavefront executes across all 32 lanes with divergent per-lane inputs.""" - simd = SIMDState(num_lanes=32, exec_mask=MASK32) - # Populate each lane with a distinct power of 4 or known square - test_inputs = [ - ONE_F64, FOUR_F64, SIXTEEN_F64, SIXTY_FOUR_F64, - QUARTER_F64, SIXTEENTH_F64, POS_ZERO, POS_INF, - ] * 4 # 32 inputs - for lane, inp in enumerate(test_inputs): - simd.write_lane_vgpr_pair(lane, 2, inp) - - instr = VRSQF64Instruction( - dst=RegPair(0, RegType.VGPR), - src0=VOP3Operand.from_vgpr(2), - ) - interp = SIMDInterpreter(simd) - res = interp.execute(instr) - - self.assertEqual(len(res), 32) - for lane, inp in enumerate(test_inputs): - expected = oracle_v_rsq_f64(inp) - self.assertEqual(res[lane], expected) - self.assertEqual(simd.read_lane_vgpr_pair(lane, 0), expected) - - def test_wave64_full_execution(self) -> None: - """Wave64 wavefront executes across all 64 lanes.""" - simd = SIMDState(num_lanes=64, exec_mask=MASK64) - for lane in range(64): - simd.write_lane_vgpr_pair(lane, 4, FOUR_F64) - - instr = VRSQF64Instruction( - dst=RegPair(6, RegType.VGPR), - src0=VOP3Operand.from_vgpr(4), - ) - interp = SIMDInterpreter(simd) - res = interp.execute(instr) - - self.assertEqual(len(res), 64) - for lane in range(64): - self.assertEqual(res[lane], HALF_F64) - self.assertEqual(simd.read_lane_vgpr_pair(lane, 6), HALF_F64) - - def test_checkerboard_divergence_even_lanes(self) -> None: - """EXEC mask enables even lanes only; odd lanes must remain completely unmodified.""" - exec_even = 0x5555_5555_5555_5555 - simd = SIMDState(num_lanes=64, exec_mask=exec_even) - SENTINEL = 0xDEAD_BEEF_CAFE_BABE - - for lane in range(64): - simd.write_lane_vgpr_pair(lane, 0, SENTINEL) - simd.write_lane_vgpr_pair(lane, 2, FOUR_F64) - - instr = VRSQF64Instruction( - dst=RegPair(0, RegType.VGPR), - src0=VOP3Operand.from_vgpr(2), - ) - interp = SIMDInterpreter(simd) - res = interp.execute(instr) - - for lane in range(64): - if lane % 2 == 0: - self.assertEqual(res[lane], HALF_F64) - self.assertEqual(simd.read_lane_vgpr_pair(lane, 0), HALF_F64) - else: - self.assertIsNone(res[lane]) - self.assertEqual(simd.read_lane_vgpr_pair(lane, 0), SENTINEL) - - def test_wave_half_divergence(self) -> None: - """EXEC mask enables lower 32 lanes (half-wave) only.""" - exec_lo32 = 0x0000_0000_FFFF_FFFF - simd = SIMDState(num_lanes=64, exec_mask=exec_lo32) - SENTINEL = 0x1234_5678_9ABC_DEF0 - - for lane in range(64): - simd.write_lane_vgpr_pair(lane, 0, SENTINEL) - simd.write_lane_vgpr_pair(lane, 2, SIXTEEN_F64) - - instr = VRSQF64Instruction( - dst=RegPair(0, RegType.VGPR), - src0=VOP3Operand.from_vgpr(2), - ) - interp = SIMDInterpreter(simd) - res = interp.execute(instr) - - for lane in range(32): - self.assertEqual(res[lane], QUARTER_F64) - self.assertEqual(simd.read_lane_vgpr_pair(lane, 0), QUARTER_F64) - - for lane in range(32, 64): - self.assertIsNone(res[lane]) - self.assertEqual(simd.read_lane_vgpr_pair(lane, 0), SENTINEL) - - def test_single_lane_active(self) -> None: - """EXEC mask enables exactly one lane (lane 17).""" - target_lane = 17 - simd = SIMDState(num_lanes=64, exec_mask=(1 << target_lane)) - SENTINEL = 0xAAAA_BBBB_CCCC_DDDD - - for lane in range(64): - simd.write_lane_vgpr_pair(lane, 0, SENTINEL) - simd.write_lane_vgpr_pair(lane, 2, QUARTER_F64) - - instr = VRSQF64Instruction( - dst=RegPair(0, RegType.VGPR), - src0=VOP3Operand.from_vgpr(2), - ) - interp = SIMDInterpreter(simd) - res = interp.execute(instr) - - for lane in range(64): - if lane == target_lane: - self.assertEqual(res[lane], TWO_F64) - self.assertEqual(simd.read_lane_vgpr_pair(lane, 0), TWO_F64) - else: - self.assertIsNone(res[lane]) - self.assertEqual(simd.read_lane_vgpr_pair(lane, 0), SENTINEL) - - def test_zero_exec_mask_noop(self) -> None: - """An EXEC mask of 0 is a complete no-op across all registers and lanes.""" - simd = SIMDState(num_lanes=64, exec_mask=0) - SENTINEL = 0x5555_AAAA_5555_AAAA - - for lane in range(64): - simd.write_lane_vgpr_pair(lane, 0, SENTINEL) - simd.write_lane_vgpr_pair(lane, 2, FOUR_F64) - - instr = VRSQF64Instruction( - dst=RegPair(0, RegType.VGPR), - src0=VOP3Operand.from_vgpr(2), - ) - interp = SIMDInterpreter(simd) - res = interp.execute(instr) - - self.assertTrue(all(r is None for r in res)) - for lane in range(64): - self.assertEqual(simd.read_lane_vgpr_pair(lane, 0), SENTINEL) - - def test_scalar_broadcast_to_active_simd_lanes(self) -> None: - """Source operand from SGPR pair is broadcast identically across all active lanes.""" - simd = SIMDState(num_lanes=64, exec_mask=MASK64) - simd.write_sgpr_pair(10, SIXTEEN_F64) - - instr = VRSQF64Instruction( - dst=RegPair(4, RegType.VGPR), - src0=VOP3Operand.from_sgpr(10), - ) - interp = SIMDInterpreter(simd) - res = interp.execute(instr) - - for lane in range(64): - self.assertEqual(res[lane], QUARTER_F64) - self.assertEqual(simd.read_lane_vgpr_pair(lane, 4), QUARTER_F64) - - -# ============================================================================ -# Section 5: Register Aliasing and In-Place Operand Preservation -# ============================================================================ - -class TestRegisterAliasing(unittest.TestCase): - """Unit tests for register aliasing and in-place operand preservation.""" - - def test_complete_in_place_aliasing_scalar(self) -> None: - """In-place execution where destination and source are identical (v[0:1] = rsq(v[0:1])).""" - state = ScalarMachineState() - state.write_vgpr_pair(0, FOUR_F64) - - instr = VRSQF64Instruction( - dst=RegPair(0, RegType.VGPR), - src0=VOP3Operand.from_vgpr(0), - ) - interp = ScalarInterpreter(state) - res = interp.execute(instr) - - self.assertEqual(res, HALF_F64) - self.assertEqual(state.read_vgpr_pair(0), HALF_F64) - - def test_partial_overlap_dst_low_src_high(self) -> None: - """Partial overlap: dst=v[0:1], src=v[1:2] sharing register v[1].""" - state = ScalarMachineState() - # Set v[1:2] = 16.0 - state.write_vgpr_pair(1, SIXTEEN_F64) - - instr = VRSQF64Instruction( - dst=RegPair(0, RegType.VGPR), - src0=VOP3Operand.from_vgpr(1), - ) - interp = ScalarInterpreter(state) - res = interp.execute(instr) - - self.assertEqual(res, QUARTER_F64) - self.assertEqual(state.read_vgpr_pair(0), QUARTER_F64) - - def test_partial_overlap_dst_high_src_low(self) -> None: - """Partial overlap: dst=v[2:3], src=v[1:2] sharing register v[2].""" - state = ScalarMachineState() - # Set v[1:2] = 0.25 - state.write_vgpr_pair(1, QUARTER_F64) - - instr = VRSQF64Instruction( - dst=RegPair(2, RegType.VGPR), - src0=VOP3Operand.from_vgpr(1), - ) - interp = ScalarInterpreter(state) - res = interp.execute(instr) - - self.assertEqual(res, TWO_F64) - self.assertEqual(state.read_vgpr_pair(2), TWO_F64) - - def test_successive_in_place_evaluations(self) -> None: - """Two successive in-place rsq evaluations: rsq(rsq(16.0)) == rsq(0.25) == 2.0.""" - state = ScalarMachineState() - state.write_vgpr_pair(4, SIXTEEN_F64) - - instr = VRSQF64Instruction( - dst=RegPair(4, RegType.VGPR), - src0=VOP3Operand.from_vgpr(4), - ) - interp = ScalarInterpreter(state) - - # Step 1: rsq(16.0) -> 0.25 - r1 = interp.execute(instr) - self.assertEqual(r1, QUARTER_F64) - self.assertEqual(state.read_vgpr_pair(4), QUARTER_F64) - - # Step 2: rsq(0.25) -> 2.0 - r2 = interp.execute(instr) - self.assertEqual(r2, TWO_F64) - self.assertEqual(state.read_vgpr_pair(4), TWO_F64) - - def test_in_place_simd_multi_lane(self) -> None: - """Wavefront executing in-place v[0:1] = rsq(v[0:1]) with lane divergence.""" - simd = SIMDState(num_lanes=64, exec_mask=0x5555_5555_5555_5555) # even lanes - for lane in range(64): - simd.write_lane_vgpr_pair(lane, 0, FOUR_F64) - - instr = VRSQF64Instruction( - dst=RegPair(0, RegType.VGPR), - src0=VOP3Operand.from_vgpr(0), - ) - interp = SIMDInterpreter(simd) - res = interp.execute(instr) - - for lane in range(64): - if lane % 2 == 0: - self.assertEqual(res[lane], HALF_F64) - self.assertEqual(simd.read_lane_vgpr_pair(lane, 0), HALF_F64) - else: - self.assertIsNone(res[lane]) - self.assertEqual(simd.read_lane_vgpr_pair(lane, 0), FOUR_F64) - - def test_in_place_negative_to_nan(self) -> None: - """In-place replacement of negative float by Canonical QNaN.""" - state = ScalarMachineState() - state.write_vgpr_pair(6, NEG_FOUR_F64) - - instr = VRSQF64Instruction( - dst=RegPair(6, RegType.VGPR), - src0=VOP3Operand.from_vgpr(6), - ) - interp = ScalarInterpreter(state) - res = interp.execute(instr) - - self.assertEqual(res, CANONICAL_QNAN) - self.assertEqual(state.read_vgpr_pair(6), CANONICAL_QNAN) - - -# ============================================================================ -# Section 6: Condition Codes, Status Flags, and Carry/Borrow Generation -# ============================================================================ - -@dataclass -class FPStatusFlags: - """IEEE 754 / RDNA2 floating-point exception sticky flags.""" - invalid: bool = False # IOC: Invalid operation (negative operand, sNaN) - div_by_zero: bool = False # DZC: Division by zero (+0.0, -0.0 input) - overflow: bool = False # OFC: Overflow - underflow: bool = False # UFC: Underflow - inexact: bool = False # IXC: Inexact transcendental/rounding result - - def accumulate(self, other: FPStatusFlags) -> None: - """Accumulate (bitwise OR) flags into hardware sticky status register.""" - self.invalid |= other.invalid - self.div_by_zero |= other.div_by_zero - self.overflow |= other.overflow - self.underflow |= other.underflow - self.inexact |= other.inexact - - def to_bits(self) -> int: - """Encode flags into hardware status register bitmask.""" - bits = 0 - if self.invalid: - bits |= 1 << 0 - if self.div_by_zero: - bits |= 1 << 1 - if self.overflow: - bits |= 1 << 2 - if self.underflow: - bits |= 1 << 3 - if self.inexact: - bits |= 1 << 4 - return bits - - -def compute_v_rsq_f64_flags( - src_bits: int, - abs_src: bool = False, - neg_src: bool = False, - clamp: bool = False, - flush_subnormals: bool = False, -) -> Tuple[int, FPStatusFlags]: - """Compute v_rsq_f64 result along with its architectural FP exception flags.""" - flags = FPStatusFlags() - s = apply_f64_modifiers(src_bits, abs_src, neg_src) - - # Subnormal input under FTZ - if flush_subnormals and is_subnormal(s): - flags.underflow = True - s = NEG_ZERO if (s & SIGN_MASK) else POS_ZERO - - # Signaling NaN input raises Invalid - if is_snan(s): - flags.invalid = True - res = POS_ZERO if clamp else (s | QNAN_BIT) - return res, flags - - # Quiet NaN input propagates without Invalid - if is_nan(s): - res = POS_ZERO if clamp else (s | QNAN_BIT) - return res, flags - - # Negative non-zero and -Infinity input raises Invalid - if (s & SIGN_MASK) and not is_zero(s): - flags.invalid = True - res = POS_ZERO if clamp else CANONICAL_QNAN - return res, flags - - # Zero input raises Division-by-Zero - if is_zero(s): - flags.div_by_zero = True - res = ONE_F64 if clamp else POS_INF - return res, flags - - # Positive Infinity - if s == POS_INF: - return POS_ZERO, flags - - # Positive finite numbers - val = bits_to_f64(s) - res_val = 1.0 / math.sqrt(val) - - # Check exact powers of 2/4 - # An input is an exact power of 4 if log2(val) is an even integer - is_exact = False - if val > 0.0: - log2_val = math.log2(val) - if log2_val.is_integer() and (int(log2_val) % 2 == 0): - is_exact = True - - if not is_exact: - flags.inexact = True - - if clamp: - if res_val < 0.0: - res_val = 0.0 - elif res_val > 1.0: - res_val = 1.0 - - res_bits = f64_to_bits(res_val) - if is_subnormal(res_bits): - flags.underflow = True - - return res_bits, flags - - -class TestConditionCodesAndStatusFlags(unittest.TestCase): - """Unit tests for condition codes, IEEE 754 status flags, and VCC condition masks.""" - - def test_invalid_flag_negative_inputs(self) -> None: - """Negative operands raise the Invalid Operation (IOC) status flag.""" - _, flags_neg4 = compute_v_rsq_f64_flags(NEG_FOUR_F64) - self.assertTrue(flags_neg4.invalid) - self.assertFalse(flags_neg4.div_by_zero) - - _, flags_neginf = compute_v_rsq_f64_flags(NEG_INF) - self.assertTrue(flags_neginf.invalid) - - def test_invalid_flag_signaling_nan(self) -> None: - """Signaling NaN operand raises the Invalid Operation (IOC) status flag.""" - snan = POS_INF | 0x0001_0000 - _, flags = compute_v_rsq_f64_flags(snan) - self.assertTrue(flags.invalid) - - def test_quiet_nan_does_not_raise_invalid(self) -> None: - """Quiet NaN operand propagates without asserting Invalid Operation.""" - _, flags = compute_v_rsq_f64_flags(CANONICAL_QNAN) - self.assertFalse(flags.invalid) - - def test_div_by_zero_flag_zeros(self) -> None: - """Both +0.0 and -0.0 raise Division by Zero (DZC).""" - _, flags_pos0 = compute_v_rsq_f64_flags(POS_ZERO) - self.assertTrue(flags_pos0.div_by_zero) - self.assertFalse(flags_pos0.invalid) - - _, flags_neg0 = compute_v_rsq_f64_flags(NEG_ZERO) - self.assertTrue(flags_neg0.div_by_zero) - - def test_inexact_flag_non_perfect_squares(self) -> None: - """Non-exact reciprocal square roots (2.0, 3.0, 10.0) assert Inexact (IXC).""" - _, flags_two = compute_v_rsq_f64_flags(TWO_F64) - self.assertTrue(flags_two.inexact) - - _, flags_three = compute_v_rsq_f64_flags(THREE_F64) - self.assertTrue(flags_three.inexact) - - def test_exact_roots_do_not_raise_inexact(self) -> None: - """Exact roots of powers of 4 (1.0, 4.0, 16.0, 0.25, 0.0625) do not assert Inexact.""" - _, flags_1 = compute_v_rsq_f64_flags(ONE_F64) - self.assertFalse(flags_1.inexact) - - _, flags_4 = compute_v_rsq_f64_flags(FOUR_F64) - self.assertFalse(flags_4.inexact) - - _, flags_16 = compute_v_rsq_f64_flags(SIXTEEN_F64) - self.assertFalse(flags_16.inexact) - - _, flags_quarter = compute_v_rsq_f64_flags(QUARTER_F64) - self.assertFalse(flags_quarter.inexact) - - _, flags_sixteenth = compute_v_rsq_f64_flags(SIXTEENTH_F64) - self.assertFalse(flags_sixteenth.inexact) - - def test_cumulative_sticky_flags_accumulation(self) -> None: - """Verify that sticky status register correctly accumulates flags across instructions.""" - sticky = FPStatusFlags() - - # Step 1: exact operation -> no flags - _, f1 = compute_v_rsq_f64_flags(FOUR_F64) - sticky.accumulate(f1) - self.assertEqual(sticky.to_bits(), 0) - - # Step 2: division by zero -> div_by_zero flag (bit 1) - _, f2 = compute_v_rsq_f64_flags(POS_ZERO) - sticky.accumulate(f2) - self.assertEqual(sticky.to_bits(), 1 << 1) - - # Step 3: negative operand -> invalid flag (bit 0) - _, f3 = compute_v_rsq_f64_flags(NEG_FOUR_F64) - sticky.accumulate(f3) - self.assertEqual(sticky.to_bits(), (1 << 0) | (1 << 1)) - - # Step 4: inexact operation -> inexact flag (bit 4) - _, f4 = compute_v_rsq_f64_flags(TWO_F64) - sticky.accumulate(f4) - self.assertEqual(sticky.to_bits(), (1 << 0) | (1 << 1) | (1 << 4)) - - def test_vcc_condition_masks(self) -> None: - """Compute condition mask across SIMD wave lanes (emulating V_CMP / VCC).""" - simd = SIMDState(num_lanes=64, exec_mask=MASK64) - # Assign various values across lanes - for lane in range(64): - if lane % 4 == 0: - simd.write_lane_vgpr_pair(lane, 0, POS_ZERO) # -> +inf - elif lane % 4 == 1: - simd.write_lane_vgpr_pair(lane, 0, POS_INF) # -> +0.0 - elif lane % 4 == 2: - simd.write_lane_vgpr_pair(lane, 0, NEG_FOUR_F64) # -> NaN - else: - simd.write_lane_vgpr_pair(lane, 0, FOUR_F64) # -> 0.5 (positive finite) - - instr = VRSQF64Instruction( - dst=RegPair(2, RegType.VGPR), - src0=VOP3Operand.from_vgpr(0), - ) - interp = SIMDInterpreter(simd) - res = interp.execute(instr) - - # Build condition bitmasks - vcc_zero = 0 - vcc_inf = 0 - vcc_nan = 0 - vcc_finite_pos = 0 - - for lane, r in enumerate(res): - assert r is not None - if is_zero(r): - vcc_zero |= (1 << lane) - elif is_inf(r): - vcc_inf |= (1 << lane) - elif is_nan(r): - vcc_nan |= (1 << lane) - else: - vcc_finite_pos |= (1 << lane) - - # Verify orthogonal bitmasks partition the wave lanes - self.assertEqual(vcc_zero | vcc_inf | vcc_nan | vcc_finite_pos, MASK64) - self.assertEqual(vcc_zero & vcc_inf, 0) - self.assertEqual(vcc_zero & vcc_nan, 0) - self.assertEqual(vcc_inf & vcc_nan, 0) - - -# ============================================================================ -# Section 7: IEEE 754 Boundary Extremes, Subnormals, and NaN Handling -# ============================================================================ - -class TestIEEE754BoundaryExtremes(unittest.TestCase): - """Unit tests for IEEE 754 boundary extremes, subnormals, and NaN handling.""" - - def test_dbl_min_normal_boundary(self) -> None: - """rsq(2^-1022) = 2^511, exact power of 2 representation.""" - res_bits = oracle_v_rsq_f64(DBL_MIN) - self.assertFalse(is_nan(res_bits)) - self.assertFalse(is_inf(res_bits)) - expected_val = 2.0 ** 511 - self.assertAlmostEqual(bits_to_f64(res_bits), expected_val, delta=expected_val * 1e-15) - - def test_dbl_max_normal_boundary(self) -> None: - """rsq(DBL_MAX) produces small finite positive normal float.""" - res_bits = oracle_v_rsq_f64(DBL_MAX) - self.assertFalse(is_nan(res_bits)) - self.assertFalse(is_inf(res_bits)) - res_val = bits_to_f64(res_bits) - self.assertGreater(res_val, 0.0) - self.assertLess(res_val, 1e-150) - - def test_subnorm_min_gradual_underflow(self) -> None: - """rsq(2^-1074) evaluates to 2^537 under IEEE-754 gradual underflow.""" - res_bits = oracle_v_rsq_f64(SUBNORM_MIN, flush_subnormals=False) - self.assertFalse(is_nan(res_bits)) - self.assertFalse(is_inf(res_bits)) - expected_val = 2.0 ** 537 - self.assertAlmostEqual(bits_to_f64(res_bits), expected_val, delta=expected_val * 1e-15) - - def test_subnorm_max_gradual_underflow(self) -> None: - """Largest positive subnormal computes without NaN under IEEE mode.""" - res_bits = oracle_v_rsq_f64(SUBNORM_MAX, flush_subnormals=False) - self.assertFalse(is_nan(res_bits)) - self.assertFalse(is_inf(res_bits)) - self.assertGreater(bits_to_f64(res_bits), 2.0 ** 511) - - def test_subnormal_flush_to_zero_mode(self) -> None: - """Under FTZ mode, both smallest and largest subnormals flush to 0, producing +Inf.""" - res_min_ftz = oracle_v_rsq_f64(SUBNORM_MIN, flush_subnormals=True) - self.assertEqual(res_min_ftz, POS_INF) - - res_max_ftz = oracle_v_rsq_f64(SUBNORM_MAX, flush_subnormals=True) - self.assertEqual(res_max_ftz, POS_INF) - - def test_qnan_payload_preservation(self) -> None: - """Quiet NaN payloads are preserved and have the quiet bit asserted.""" - payload_a = 0x7FF8_0000_1234_5678 - res_a = oracle_v_rsq_f64(payload_a) - self.assertEqual(res_a, payload_a) - - payload_b = 0x7FF9_BEEF_CAFE_0001 - res_b = oracle_v_rsq_f64(payload_b) - self.assertEqual(res_b, payload_b) - - def test_snan_quieting(self) -> None: - """Signaling NaN is converted to a Quiet NaN with quiet bit set.""" - snan = 0x7FF0_0000_0000_0001 - res = oracle_v_rsq_f64(snan) - self.assertTrue(is_qnan(res)) - self.assertEqual(res, snan | QNAN_BIT) - - def test_negative_subnormals_yield_qnan(self) -> None: - """Negative subnormals represent negative numbers and yield Canonical QNaN.""" - neg_sub_min = SUBNORM_MIN | SIGN_MASK - neg_sub_max = SUBNORM_MAX | SIGN_MASK - self.assertEqual(oracle_v_rsq_f64(neg_sub_min), CANONICAL_QNAN) - self.assertEqual(oracle_v_rsq_f64(neg_sub_max), CANONICAL_QNAN) - - def test_monotonic_decrease_across_normals(self) -> None: - """Reciprocal square root is strictly monotonically decreasing for positive inputs.""" - inputs = [ - 0.0001, 0.01, 0.25, 0.5, 1.0, 2.0, 4.0, 16.0, 100.0, 10000.0, 1e8, 1e20, - ] - prev_res = math.inf - for inp in inputs: - curr_res = bits_to_f64(oracle_v_rsq_f64(f64_to_bits(inp))) - self.assertLess(curr_res, prev_res) - prev_res = curr_res - - def test_clamp_saturation_at_boundaries(self) -> None: - """Clamp modifier saturates extreme values to [0.0, 1.0].""" - # SUBNORM_MIN produces 2^537 >> 1.0 -> clamped to 1.0 - self.assertEqual(oracle_v_rsq_f64(SUBNORM_MIN, clamp=True), ONE_F64) - # DBL_MIN produces 2^511 >> 1.0 -> clamped to 1.0 - self.assertEqual(oracle_v_rsq_f64(DBL_MIN, clamp=True), ONE_F64) - # DBL_MAX produces ~7.4e-155 -> within [0.0, 1.0] -> unchanged - self.assertEqual(oracle_v_rsq_f64(DBL_MAX, clamp=True), oracle_v_rsq_f64(DBL_MAX, clamp=False)) - # +0.0 produces +inf -> clamped to 1.0 - self.assertEqual(oracle_v_rsq_f64(POS_ZERO, clamp=True), ONE_F64) - # -0.0 produces +inf -> clamped to 1.0 - self.assertEqual(oracle_v_rsq_f64(NEG_ZERO, clamp=True), ONE_F64) - - -# ============================================================================ -# Section 8: Negative Controls, Syntax Rejection, and Mutation Detection -# ============================================================================ - -def mutant_omit_sqrt(src_bits: int, **kwargs: bool) -> int: - """Mutant 1: computes 1.0 / x instead of 1.0 / sqrt(x).""" - val = bits_to_f64(src_bits) - if val <= 0.0: - return CANONICAL_QNAN - return f64_to_bits(1.0 / val) - - -def mutant_ignore_negative_nan(src_bits: int, **kwargs: bool) -> int: - """Mutant 2: calculates root of absolute value instead of NaN for negative inputs.""" - s = src_bits & MASK64 - val = abs(bits_to_f64(s)) - if val == 0.0: - return POS_INF - return f64_to_bits(1.0 / math.sqrt(val)) - - -def mutant_zero_to_zero(src_bits: int, **kwargs: bool) -> int: - """Mutant 3: returns +0.0 instead of +Infinity on zero inputs.""" - if is_zero(src_bits): - return POS_ZERO - return oracle_v_rsq_f64(src_bits, **kwargs) - - -def mutant_omit_clamp(src_bits: int, **kwargs: bool) -> int: - """Mutant 4: fails to clamp values > 1.0 to 1.0.""" - return oracle_v_rsq_f64(src_bits, clamp=False) - - -def mutant_invert_sign(src_bits: int, **kwargs: bool) -> int: - """Mutant 5: negates the output sign.""" - res = oracle_v_rsq_f64(src_bits, **kwargs) - return res ^ SIGN_MASK - - -class TestNegativeControlsAndMutations(unittest.TestCase): - """Unit tests for negative controls, syntax rejection, and mutation detection.""" - - def test_syntax_rejection_invalid_vgpr_index(self) -> None: - """Register pairs with indices > 254 must be rejected with ValueError.""" - with self.assertRaises(ValueError): - RegPair(255, RegType.VGPR) - with self.assertRaises(ValueError): - RegPair(300, RegType.VGPR) - with self.assertRaises(ValueError): - RegPair(-1, RegType.VGPR) - - def test_syntax_rejection_invalid_sgpr_index(self) -> None: - """SGPR pairs with indices > 104 must be rejected with ValueError.""" - with self.assertRaises(ValueError): - RegPair(105, RegType.SGPR) - with self.assertRaises(ValueError): - RegPair(-5, RegType.SGPR) - - def test_syntax_rejection_invalid_literal_range(self) -> None: - """Literal values outside 64-bit unsigned bounds must be rejected.""" - with self.assertRaises(ValueError): - Literal64(-1) - with self.assertRaises(ValueError): - Literal64(1 << 64) - - def test_syntax_rejection_invalid_destination_type(self) -> None: - """VALU instruction destination cannot be SGPR or literal.""" - with self.assertRaises(ValueError): - VRSQF64Instruction( - dst=RegPair(0, RegType.SGPR), - src0=VOP3Operand.from_vgpr(2), - ) - - def test_syntax_rejection_invalid_vop3_operand_spec(self) -> None: - """VOP3Operand must specify exactly one of reg_pair or literal.""" - with self.assertRaises(ValueError): - VOP3Operand(reg_pair=None, literal=None) - with self.assertRaises(ValueError): - VOP3Operand( - reg_pair=RegPair(0, RegType.VGPR), - literal=Literal64(0), - ) - - def test_syntax_rejection_invalid_simd_lane_count(self) -> None: - """SIMDState must only accept 32 or 64 lanes.""" - with self.assertRaises(ValueError): - SIMDState(num_lanes=16) - with self.assertRaises(ValueError): - SIMDState(num_lanes=48) - - def test_mutation_detection_omit_sqrt(self) -> None: - """Verify that omitting square root is detected.""" - golden = oracle_v_rsq_f64(FOUR_F64) # 0.5 - mutant = mutant_omit_sqrt(FOUR_F64) # 0.25 - self.assertNotEqual(golden, mutant) - - def test_mutation_detection_ignore_negative_nan(self) -> None: - """Verify that failing to produce NaN on negative input is detected.""" - golden = oracle_v_rsq_f64(NEG_FOUR_F64) - mutant = mutant_ignore_negative_nan(NEG_FOUR_F64) - self.assertEqual(golden, CANONICAL_QNAN) - self.assertNotEqual(mutant, CANONICAL_QNAN) - - def test_mutation_detection_zero_to_zero(self) -> None: - """Verify that zero returning 0 instead of Infinity is detected.""" - golden = oracle_v_rsq_f64(POS_ZERO) - mutant = mutant_zero_to_zero(POS_ZERO) - self.assertEqual(golden, POS_INF) - self.assertEqual(mutant, POS_ZERO) - self.assertNotEqual(golden, mutant) - - def test_mutation_detection_omit_clamp(self) -> None: - """Verify that omitting clamp saturation is detected.""" - golden = oracle_v_rsq_f64(QUARTER_F64, clamp=True) # 1.0 - mutant = mutant_omit_clamp(QUARTER_F64, clamp=True) # 2.0 - self.assertEqual(golden, ONE_F64) - self.assertEqual(mutant, TWO_F64) - self.assertNotEqual(golden, mutant) - - def test_mutation_detection_invert_sign(self) -> None: - """Verify that inverted output sign is detected.""" - golden = oracle_v_rsq_f64(FOUR_F64) - mutant = mutant_invert_sign(FOUR_F64) - self.assertEqual(golden, HALF_F64) - self.assertEqual(mutant, HALF_F64 | SIGN_MASK) - - def test_mathematical_property_rsq_squared_identity(self) -> None: - """Mathematical identity: (rsq(x))^2 == 1.0 / x for positive floats.""" - test_values = [0.1, 0.5, 1.0, 2.0, 3.5, 7.8, 10.0, 42.0, 100.0, 1024.0] - for val in test_values: - bits = f64_to_bits(val) - rsq_val = bits_to_f64(oracle_v_rsq_f64(bits)) - reconstructed_inv = rsq_val * rsq_val - expected_inv = 1.0 / val - rel_error = abs(reconstructed_inv - expected_inv) / expected_inv - self.assertLess(rel_error, 1e-14) - - def test_mathematical_scaling_property(self) -> None: - """Scaling identity: rsq(4 * x) == 0.5 * rsq(x).""" - test_values = [0.05, 0.25, 1.0, 4.0, 9.0, 25.0, 100.0] - for val in test_values: - rsq_x = bits_to_f64(oracle_v_rsq_f64(f64_to_bits(val))) - rsq_4x = bits_to_f64(oracle_v_rsq_f64(f64_to_bits(4.0 * val))) - self.assertAlmostEqual(rsq_4x, 0.5 * rsq_x, places=14) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_valu_sad_u32.py b/tests/semantic/test_valu_sad_u32.py deleted file mode 100644 index e8cca5b2a..000000000 --- a/tests/semantic/test_valu_sad_u32.py +++ /dev/null @@ -1,78 +0,0 @@ -"""v_sad_u32 (RDNA2 VOP3): D = |S0 - S1| + S2 on unsigned 32-bit operands, modulo 2^32. - -Each case is translated by tools/rdna2spirv.py (support.translate_lines) and executed with -tests/semantic/spirv_mini_interp.py; the expected words are written by hand from the ISA formula and also recomputed -by a plain-Python reference, with VGPR, SGPR and literal/inline-constant sources and seeded random operands. -Standard library only: no GPU, no LLVM, no game data. (The old file modelled the instruction in its own classes and -never ran the translator. The `clamp` modifier is the business of test_sad_clamp.py / test_alu_sad_u32.py.) -""" -import os -import random -import sys -import unittest - -sys.dont_write_bytecode = True -sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) -import support # noqa: E402 - -M32 = 0xFFFFFFFF - - -def ref(s0, s1, s2): - return (abs(s0 - s1) + s2) & M32 - - -def run(s0, s1, s2, form="vgpr"): - if form == "vgpr": - lines = [f"v_mov_b32 v1, {s0:#x}", f"v_mov_b32 v2, {s1:#x}", f"v_mov_b32 v3, {s2:#x}", "v_sad_u32 v0, v1, v2, v3"] - elif form == "sgpr": - lines = [f"s_mov_b32 s1, {s0:#x}", f"s_mov_b32 s2, {s1:#x}", f"s_mov_b32 s3, {s2:#x}", "v_sad_u32 v0, s1, s2, s3"] - elif form == "literal": # one literal (S1) between VGPRs: the VOP3 literal slot of GFX10 - lines = [f"v_mov_b32 v1, {s0:#x}", f"v_mov_b32 v3, {s2:#x}", f"v_sad_u32 v0, v1, {s1:#x}, v3"] - else: - raise ValueError(form) - lines += ["exp mrt0 v0, v0, v0, v0 done vm", "s_endpgm"] - return support.mrt0_words(support.translate_lines("ps_sad_u32", lines))[0] - - -# (S0, S1, S2, expected word), written by hand. -CASES = [ - (5, 3, 0, 2), (3, 5, 0, 2), (7, 7, 0, 0), (10, 4, 100, 106), (4, 10, 100, 106), - (0, 0xFFFFFFFF, 0, 0xFFFFFFFF), (0xFFFFFFFF, 0, 0, 0xFFFFFFFF), - (0x80000000, 0x7FFFFFFF, 0, 1), # unsigned: not a signed wrap - (0, 0x80000000, 0, 0x80000000), - (0xFFFFFFFF, 0, 1, 0), # 2^32 - 1 + 1 wraps - (0xFFFFFFFF, 0, 0xFFFFFFFF, 0xFFFFFFFE), - (0x12345678, 0x12345600, 0x10, 0x88), - (0x00000001, 0xFFFFFFFF, 0x00000003, 0x00000001), # 0xFFFFFFFE + 3 mod 2^32 -] - - -class SadU32(unittest.TestCase): - def test_hand_table_matches_reference(self): - for s0, s1, s2, want in CASES: - self.assertEqual(ref(s0, s1, s2), want, (hex(s0), hex(s1), hex(s2))) - - def test_translated_forms(self): - for form in ("vgpr", "sgpr", "literal"): - for s0, s1, s2, want in CASES: - with self.subTest(form=form, s0=hex(s0), s1=hex(s1), s2=hex(s2)): - self.assertEqual(run(s0, s1, s2, form), want) - - def test_symmetric_in_s0_s1(self): - rng = random.Random(0x5AD) - for _ in range(20): - a, b, c = (rng.getrandbits(32) for _ in range(3)) - self.assertEqual(run(a, b, c), run(b, a, c)) - - def test_random_operands(self): - rng = random.Random(0x5AD32) - for _ in range(60): - s0, s1, s2 = (rng.getrandbits(32) for _ in range(3)) - for form in ("vgpr", "sgpr", "literal"): - with self.subTest(form=form, s0=hex(s0), s1=hex(s1), s2=hex(s2)): - self.assertEqual(run(s0, s1, s2, form), ref(s0, s1, s2)) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_valu_sin_cos_turns.py b/tests/semantic/test_valu_sin_cos_turns.py deleted file mode 100644 index 5c4aad398..000000000 --- a/tests/semantic/test_valu_sin_cos_turns.py +++ /dev/null @@ -1,71 +0,0 @@ -"""v_sin_f32/v_cos_f32: range reduction in turns, not after scaling by 2*pi. - -The hardware takes the operand in turns and reduces to [0, 1) before evaluating. Scaling first loses bits for large -inputs and leaves Sin outside [-pi, pi], where Vulkan's precision is not guaranteed. The old translation is up to -1e-4 off near 255 turns; reducing first is within an f32 ulp of the double result. -""" -import math -import struct -import unittest - -import support - - -def _bits(x): - return struct.unpack(" int: - """Convert a Python float (IEEE 754 double) to 64-bit integer bits.""" - return struct.unpack(" float: - """Convert 64-bit integer bits to a Python float (IEEE 754 double).""" - return struct.unpack(" Tuple[int, int, int]: - """Unpack bits into (sign, exponent, fraction) components.""" - sign = (bits & SIGN_MASK) >> 63 - exponent = (bits & EXP_MASK) >> 52 - fraction = bits & FRAC_MASK - return sign, exponent, fraction - - -def words_to_f64_bits(lo: int, hi: int) -> int: - """Combine two 32-bit VGPR words (lo, hi) into a 64-bit integer representation.""" - return ((hi & 0xFFFF_FFFF) << 32) | (lo & 0xFFFF_FFFF) - - -def f64_bits_to_words(bits: int) -> Tuple[int, int]: - """Split a 64-bit integer into two 32-bit VGPR words (lo, hi).""" - lo = bits & 0xFFFF_FFFF - hi = (bits >> 32) & 0xFFFF_FFFF - return lo, hi - - -def is_nan(bits: int) -> bool: - """Return True if bits represent an IEEE 754 NaN.""" - return ((bits & EXP_MASK) == EXP_MASK) and ((bits & FRAC_MASK) != 0) - - -def is_qnan(bits: int) -> bool: - """Return True if bits represent an IEEE 754 Quiet NaN.""" - return is_nan(bits) and bool(bits & QNAN_BIT) - - -def is_snan(bits: int) -> bool: - """Return True if bits represent an IEEE 754 Signaling NaN.""" - return is_nan(bits) and not bool(bits & QNAN_BIT) - - -def is_inf(bits: int) -> bool: - """Return True if bits represent IEEE 754 positive or negative infinity.""" - return ((bits & EXP_MASK) == EXP_MASK) and ((bits & FRAC_MASK) == 0) - - -def is_subnormal(bits: int) -> bool: - """Return True if bits represent a subnormal (denormal) double-precision float.""" - return ((bits & EXP_MASK) == 0) and ((bits & FRAC_MASK) != 0) - - -def is_zero(bits: int) -> bool: - """Return True if bits represent positive or negative zero.""" - return (bits & ~SIGN_MASK) == 0 - - -def apply_f64_modifiers(bits: int, abs_mod: bool, neg_mod: bool) -> int: - """Apply VOP3 input modifiers: abs clears sign bit; neg toggles sign bit.""" - res = bits & 0xFFFF_FFFF_FFFF_FFFF - if abs_mod: - res &= ~SIGN_MASK - if neg_mod: - res ^= SIGN_MASK - return res - - -def oracle_v_sqrt_f64( - src_bits: int, - abs_mod: bool = False, - neg_mod: bool = False, - clamp: bool = False, -) -> int: - """Reference mathematical oracle for RDNA2 v_sqrt_f64 double-precision square root. - - Computes D = sqrt(src) conforming to IEEE 754-2008 double precision (binary64) - with Round-to-Nearest-Even (RNE), applying input modifiers and clamp. - """ - s = apply_f64_modifiers(src_bits, abs_mod, neg_mod) - - # 1. NaN handling - if is_nan(s): - if clamp: - return POS_ZERO - # Quiet signaling NaN or preserve quiet NaN - return s | QNAN_BIT - - # 2. Signed zero handling: sqrt(+0) = +0, sqrt(-0) = -0 - if is_zero(s): - if s == NEG_ZERO: - return POS_ZERO if clamp else NEG_ZERO - return POS_ZERO - - # 3. Negative values (< 0): Invalid operation -> Canonical Quiet NaN - if bool(s & SIGN_MASK): - return POS_ZERO if clamp else CANONICAL_QNAN - - # 4. Positive infinity: sqrt(+inf) = +inf - if s == POS_INF: - return ONE_F64 if clamp else POS_INF - - # 5. Finite positive values - f_val = bits_to_f64(s) - res_f = math.sqrt(f_val) - res = f64_to_bits(res_f) - - # 6. Clamp modifier ([0.0, 1.0]) - if clamp: - if res_f < 0.0 or res == NEG_ZERO: - res = POS_ZERO - elif res_f > 1.0 or res == POS_INF: - res = ONE_F64 - - return res - - -# ============================================================================== -# Symbolic AST Opcode Definitions and Typed Expressions -# ============================================================================== - -class RegType(Enum): - VGPR = auto() - SGPR = auto() - - -@dataclass(frozen=True) -class RegPair: - """Represents an architectural 64-bit register pair (e.g., v[0:1] or s[4:5]).""" - index: int - reg_type: RegType - - def __post_init__(self) -> None: - if not (0 <= self.index <= 254): - raise ValueError(f"Register pair base index {self.index} out of range [0, 254]") - - @property - def lo_reg(self) -> int: - return self.index - - @property - def hi_reg(self) -> int: - return self.index + 1 - - @property - def name(self) -> str: - prefix = "v" if self.reg_type == RegType.VGPR else "s" - return f"{prefix}[{self.index}:{self.index + 1}]" - - -@dataclass(frozen=True) -class Literal64: - """Represents a 64-bit literal or inline float constant.""" - bits: int - - @classmethod - def from_float(cls, val: float) -> Literal64: - return cls(f64_to_bits(val)) - - @property - def float_value(self) -> float: - return bits_to_f64(self.bits) - - @property - def name(self) -> str: - if self.bits == POS_ZERO: - return "0.0" - if self.bits == NEG_ZERO: - return "-0.0" - f = self.float_value - if math.isnan(f): - return "nan" - if math.isinf(f): - return "inf" if f > 0 else "-inf" - return f"{f:g}" - - -@dataclass(frozen=True) -class VOP3Operand: - """Typed expression operand with optional input modifiers (abs, neg).""" - source: Union[RegPair, Literal64] - abs_mod: bool = False - neg_mod: bool = False - - def disassemble(self) -> str: - s = self.source.name - if self.abs_mod: - s = f"|{s}|" - if self.neg_mod: - s = f"-{s}" - return s - - -@dataclass(frozen=True) -class VSqrtF64Instruction: - """Symbolic AST node representing a RDNA2 v_sqrt_f64 instruction.""" - dst: RegPair - src: VOP3Operand - clamp: bool = False - - def __post_init__(self) -> None: - if self.dst.reg_type != RegType.VGPR: - raise TypeError(f"Destination of VALU instruction must be VGPR, got {self.dst.reg_type}") - - def disassemble(self) -> str: - s = f"v_sqrt_f64 {self.dst.name}, {self.src.disassemble()}" - if self.clamp: - s += " clamp" - return s - - -# ============================================================================== -# Deterministic Scalar Instruction Interpreter -# ============================================================================== - -@dataclass -class ScalarMachineState: - """Architectural register file for a single wavefront lane.""" - vgprs: List[int] = field(default_factory=lambda: [0] * 256) - sgprs: List[int] = field(default_factory=lambda: [0] * 256) - - def get_vgpr64(self, index: int) -> int: - return words_to_f64_bits(self.vgprs[index], self.vgprs[index + 1]) - - def set_vgpr64(self, index: int, bits: int) -> None: - lo, hi = f64_bits_to_words(bits) - self.vgprs[index] = lo - self.vgprs[index + 1] = hi - - def get_sgpr64(self, index: int) -> int: - return words_to_f64_bits(self.sgprs[index], self.sgprs[index + 1]) - - def set_sgpr64(self, index: int, bits: int) -> None: - lo, hi = f64_bits_to_words(bits) - self.sgprs[index] = lo - self.sgprs[index + 1] = hi - - -class ScalarInterpreter: - """Deterministic scalar instruction interpreter for v_sqrt_f64.""" - - def resolve_operand(self, op: VOP3Operand, state: ScalarMachineState) -> int: - if isinstance(op.source, RegPair): - if op.source.reg_type == RegType.VGPR: - return state.get_vgpr64(op.source.index) - elif op.source.reg_type == RegType.SGPR: - return state.get_sgpr64(op.source.index) - else: - raise ValueError(f"Unknown register type: {op.source.reg_type}") - elif isinstance(op.source, Literal64): - return op.source.bits - else: - raise TypeError(f"Unsupported operand source type: {type(op.source)}") - - def step(self, instr: VSqrtF64Instruction, state: ScalarMachineState) -> int: - # Atomic read phase - s_raw = self.resolve_operand(instr.src, state) - - # Computation phase - result_bits = oracle_v_sqrt_f64( - src_bits=s_raw, - abs_mod=instr.src.abs_mod, - neg_mod=instr.src.neg_mod, - clamp=instr.clamp, - ) - - # Write-back phase - state.set_vgpr64(instr.dst.index, result_bits) - return result_bits - - -# ============================================================================== -# SIMD Multi-Lane Execution Engine and EXEC Masking -# ============================================================================== - -@dataclass -class SIMDState: - """Multi-lane SIMD machine state representing Wave32 or Wave64.""" - num_lanes: int - exec_mask: Optional[int] = None - vgprs: List[List[int]] = field(default_factory=list) - sgprs: List[int] = field(default_factory=lambda: [0] * 256) - - def __post_init__(self) -> None: - if self.num_lanes not in (32, 64): - raise ValueError(f"num_lanes must be 32 or 64, got {self.num_lanes}") - if not self.vgprs: - self.vgprs = [[0] * 256 for _ in range(self.num_lanes)] - if self.exec_mask is None: - self.exec_mask = (1 << self.num_lanes) - 1 - - def get_vgpr64(self, lane: int, index: int) -> int: - return words_to_f64_bits(self.vgprs[lane][index], self.vgprs[lane][index + 1]) - - def set_vgpr64(self, lane: int, index: int, bits: int) -> None: - lo, hi = f64_bits_to_words(bits) - self.vgprs[lane][index] = lo - self.vgprs[lane][index + 1] = hi - - def get_sgpr64(self, index: int) -> int: - return words_to_f64_bits(self.sgprs[index], self.sgprs[index + 1]) - - def set_sgpr64(self, index: int, bits: int) -> None: - lo, hi = f64_bits_to_words(bits) - self.sgprs[index] = lo - self.sgprs[index + 1] = hi - - -class SIMDInterpreter: - """SIMD instruction interpreter handling multi-lane divergence and EXEC masking.""" - - def resolve_lane_operand(self, op: VOP3Operand, state: SIMDState, lane: int) -> int: - if isinstance(op.source, RegPair): - if op.source.reg_type == RegType.VGPR: - return state.get_vgpr64(lane, op.source.index) - elif op.source.reg_type == RegType.SGPR: - return state.get_sgpr64(op.source.index) - else: - raise ValueError(f"Unknown register type: {op.source.reg_type}") - elif isinstance(op.source, Literal64): - return op.source.bits - else: - raise TypeError(f"Unsupported operand source type: {type(op.source)}") - - def step(self, instr: VSqrtF64Instruction, state: SIMDState) -> List[Optional[int]]: - results: List[Optional[int]] = [None] * state.num_lanes - # Atomic read phase across all lanes - s_vals = [ - self.resolve_lane_operand(instr.src, state, lane) - for lane in range(state.num_lanes) - ] - - # Execution phase - for lane in range(state.num_lanes): - if (state.exec_mask & (1 << lane)) != 0: - res = oracle_v_sqrt_f64( - src_bits=s_vals[lane], - abs_mod=instr.src.abs_mod, - neg_mod=instr.src.neg_mod, - clamp=instr.clamp, - ) - state.set_vgpr64(lane, instr.dst.index, res) - results[lane] = res - - return results - - -# ============================================================================== -# Condition Codes, Status Flags, and Carry/Borrow Generation -# ============================================================================== - -@dataclass(frozen=True) -class FPStatusFlags: - """Architectural floating-point condition codes and IEEE 754 status flags.""" - invalid: bool = False - overflow: bool = False - underflow: bool = False - inexact: bool = False - zero: bool = False - negative: bool = False - denormal: bool = False - infinite: bool = False - nan: bool = False - - -def evaluate_v_sqrt_f64_flags( - src_bits: int, - res_bits: int, - abs_mod: bool = False, - neg_mod: bool = False, - clamp: bool = False, -) -> FPStatusFlags: - """Evaluate IEEE 754 architectural flags and condition codes for v_sqrt_f64.""" - s = apply_f64_modifiers(src_bits, abs_mod, neg_mod) - - s_nan = is_nan(s) - s_snan = is_snan(s) - s_inf = is_inf(s) - s_neg = bool(s & SIGN_MASK) - s_zero = is_zero(s) - - invalid = False - if s_snan: - invalid = True - elif (s_neg and not s_zero) or (s_inf and s_neg): - invalid = True - - nan_flag = is_nan(res_bits) - inf_flag = is_inf(res_bits) - zero_flag = is_zero(res_bits) - neg_flag = bool(res_bits & SIGN_MASK) - denorm_flag = is_subnormal(res_bits) - - overflow = False - underflow = False - if denorm_flag: - underflow = True - - inexact = False - if not (s_nan or s_inf or nan_flag or inf_flag or invalid or s_zero): - f = bits_to_f64(s) - res_f = bits_to_f64(res_bits) - if not clamp: - if res_f * res_f != f: - inexact = True - else: - clamped_math = min(1.0, max(0.0, math.sqrt(f))) - if clamped_math != res_f or res_f * res_f != f: - inexact = True - - return FPStatusFlags( - invalid=invalid, - overflow=overflow, - underflow=underflow, - inexact=inexact, - zero=zero_flag, - negative=neg_flag, - denormal=denorm_flag, - infinite=inf_flag, - nan=nan_flag, - ) - - -def compute_f64_sqrt_borrow(src_bits: int, res_bits: int) -> Tuple[int, int]: - """Demonstrate non-restoring square root integer mantissa remainder and borrow generation.""" - _, exp, frac = split_f64_bits(src_bits) - _, res_exp, res_frac = split_f64_bits(res_bits) - m_src = (1 << 52) | frac if exp != 0 else frac - m_res = (1 << 52) | res_frac if res_exp != 0 else res_frac - radicand = m_src << 52 - squared = m_res * m_res - remainder = radicand - squared - borrow = 1 if remainder < 0 else 0 - return remainder, borrow - - -# ============================================================================== -# Unit Tests -# ============================================================================== - -class TestF64ModelAndOracle(unittest.TestCase): - """Unit tests for binary64 bit model, predicates, and reference oracle.""" - - def test_bit_representation_roundtrip(self) -> None: - values = [0.0, -0.0, 1.0, -1.0, 0.25, 4.0, 1e-100, 1e100, math.pi] - for val in values: - with self.subTest(val=val): - bits = f64_to_bits(val) - recovered = bits_to_f64(bits) - if math.isnan(val): - self.assertTrue(math.isnan(recovered)) - else: - self.assertEqual(val, recovered) - self.assertEqual(math.copysign(1.0, val), math.copysign(1.0, recovered)) - - def test_word_packing_vgpr_pair(self) -> None: - val = 9876543.21098765 - bits = f64_to_bits(val) - lo, hi = f64_bits_to_words(bits) - self.assertEqual(lo, bits & 0xFFFF_FFFF) - self.assertEqual(hi, (bits >> 32) & 0xFFFF_FFFF) - combined = words_to_f64_bits(lo, hi) - self.assertEqual(combined, bits) - self.assertEqual(bits_to_f64(combined), val) - - def test_classification_predicates(self) -> None: - self.assertTrue(f64_to_bits(0.0) == POS_ZERO) - self.assertTrue(f64_to_bits(-0.0) == NEG_ZERO) - self.assertTrue(is_zero(POS_ZERO)) - self.assertTrue(is_zero(NEG_ZERO)) - self.assertFalse(is_zero(f64_to_bits(1.0))) - - self.assertTrue(is_inf(POS_INF)) - self.assertTrue(is_inf(NEG_INF)) - self.assertFalse(is_inf(POS_ZERO)) - - snan_bits = 0x7FF0_0000_0000_0001 - qnan_bits = CANONICAL_QNAN - self.assertTrue(is_nan(snan_bits)) - self.assertTrue(is_snan(snan_bits)) - self.assertFalse(is_qnan(snan_bits)) - - self.assertTrue(is_nan(qnan_bits)) - self.assertTrue(is_qnan(qnan_bits)) - self.assertFalse(is_snan(qnan_bits)) - - subnorm_bits = 0x0000_0000_0000_0001 - self.assertTrue(is_subnormal(subnorm_bits)) - self.assertFalse(is_subnormal(POS_ZERO)) - self.assertFalse(is_subnormal(f64_to_bits(1.0))) - - def test_exact_finite_sqrt(self) -> None: - c4 = oracle_v_sqrt_f64(f64_to_bits(4.0)) - self.assertEqual(bits_to_f64(c4), 2.0) - - c9 = oracle_v_sqrt_f64(f64_to_bits(9.0)) - self.assertEqual(bits_to_f64(c9), 3.0) - - c025 = oracle_v_sqrt_f64(f64_to_bits(0.25)) - self.assertEqual(bits_to_f64(c025), 0.5) - - c100 = oracle_v_sqrt_f64(f64_to_bits(100.0)) - self.assertEqual(bits_to_f64(c100), 10.0) - - def test_signed_zero_rules(self) -> None: - # IEEE 754: sqrt(+0) = +0, sqrt(-0) = -0 - self.assertEqual(oracle_v_sqrt_f64(POS_ZERO), POS_ZERO) - self.assertEqual(oracle_v_sqrt_f64(NEG_ZERO), NEG_ZERO) - - def test_negative_values_produce_canonical_qnan(self) -> None: - # sqrt(-4.0) -> CANONICAL_QNAN - self.assertEqual(oracle_v_sqrt_f64(f64_to_bits(-4.0)), CANONICAL_QNAN) - self.assertEqual(oracle_v_sqrt_f64(NEG_INF), CANONICAL_QNAN) - - def test_input_modifiers_abs_neg(self) -> None: - val_neg = f64_to_bits(-16.0) - # abs on negative: |-16.0| = 16.0 -> sqrt(16.0) = 4.0 - res_abs = oracle_v_sqrt_f64(val_neg, abs_mod=True) - self.assertEqual(bits_to_f64(res_abs), 4.0) - - # neg on negative: -(-16.0) = 16.0 -> sqrt(16.0) = 4.0 - res_neg = oracle_v_sqrt_f64(val_neg, neg_mod=True) - self.assertEqual(bits_to_f64(res_neg), 4.0) - - # neg on positive: -(16.0) = -16.0 -> canonical qNaN - res_neg_pos = oracle_v_sqrt_f64(f64_to_bits(16.0), neg_mod=True) - self.assertEqual(res_neg_pos, CANONICAL_QNAN) - - # abs and neg together: -|16.0| = -16.0 -> canonical qNaN - res_both = oracle_v_sqrt_f64(val_neg, abs_mod=True, neg_mod=True) - self.assertEqual(res_both, CANONICAL_QNAN) - - def test_clamp_modifier(self) -> None: - # sqrt(4.0) = 2.0 -> clamped to 1.0 - res_hi = oracle_v_sqrt_f64(f64_to_bits(4.0), clamp=True) - self.assertEqual(res_hi, ONE_F64) - - # sqrt(0.25) = 0.5 -> within [0, 1], unchanged - res_mid = oracle_v_sqrt_f64(f64_to_bits(0.25), clamp=True) - self.assertEqual(bits_to_f64(res_mid), 0.5) - - # sqrt(-0.0) with clamp -> +0.0 - res_nz = oracle_v_sqrt_f64(NEG_ZERO, clamp=True) - self.assertEqual(res_nz, POS_ZERO) - - # sqrt(-4.0) with clamp -> +0.0 - res_neg = oracle_v_sqrt_f64(f64_to_bits(-4.0), clamp=True) - self.assertEqual(res_neg, POS_ZERO) - - def test_infinity_sqrt(self) -> None: - self.assertEqual(oracle_v_sqrt_f64(POS_INF), POS_INF) - self.assertEqual(oracle_v_sqrt_f64(POS_INF, clamp=True), ONE_F64) - self.assertEqual(oracle_v_sqrt_f64(NEG_INF), CANONICAL_QNAN) - self.assertEqual(oracle_v_sqrt_f64(NEG_INF, clamp=True), POS_ZERO) - - def test_nan_quietening_and_propagation(self) -> None: - snan = 0x7FF0_0000_1234_5678 - res = oracle_v_sqrt_f64(snan) - self.assertTrue(is_qnan(res)) - self.assertEqual(res, snan | QNAN_BIT) - - qnan = 0x7FF8_0000_8765_4321 - res_q = oracle_v_sqrt_f64(qnan) - self.assertEqual(res_q, qnan) - - -class TestSymbolicAST(unittest.TestCase): - """Unit tests for symbolic AST opcode definitions and typed expressions.""" - - def test_regpair_validation_and_naming(self) -> None: - v0 = RegPair(0, RegType.VGPR) - self.assertEqual(v0.name, "v[0:1]") - self.assertEqual(v0.lo_reg, 0) - self.assertEqual(v0.hi_reg, 1) - - s8 = RegPair(8, RegType.SGPR) - self.assertEqual(s8.name, "s[8:9]") - self.assertEqual(s8.lo_reg, 8) - self.assertEqual(s8.hi_reg, 9) - - with self.assertRaises(ValueError): - RegPair(255, RegType.VGPR) - with self.assertRaises(ValueError): - RegPair(-1, RegType.VGPR) - - def test_operand_disassembly(self) -> None: - v = RegPair(2, RegType.VGPR) - op_plain = VOP3Operand(v) - self.assertEqual(op_plain.disassemble(), "v[2:3]") - - op_abs = VOP3Operand(v, abs_mod=True) - self.assertEqual(op_abs.disassemble(), "|v[2:3]|") - - op_neg = VOP3Operand(v, neg_mod=True) - self.assertEqual(op_neg.disassemble(), "-v[2:3]") - - op_neg_abs = VOP3Operand(v, abs_mod=True, neg_mod=True) - self.assertEqual(op_neg_abs.disassemble(), "-|v[2:3]|") - - lit = Literal64.from_float(4.0) - op_lit = VOP3Operand(lit) - self.assertEqual(op_lit.disassemble(), "4") - - def test_v_sqrt_f64_ast_construction_and_validation(self) -> None: - dst = RegPair(0, RegType.VGPR) - src = VOP3Operand(RegPair(2, RegType.VGPR), neg_mod=True, abs_mod=True) - instr = VSqrtF64Instruction(dst=dst, src=src, clamp=True) - - self.assertEqual(instr.disassemble(), "v_sqrt_f64 v[0:1], -|v[2:3]| clamp") - - # Invalid destination type (SGPR) - with self.assertRaises(TypeError): - VSqrtF64Instruction(dst=RegPair(0, RegType.SGPR), src=src) - - def test_structural_equality(self) -> None: - i1 = VSqrtF64Instruction( - RegPair(0, RegType.VGPR), - VOP3Operand(RegPair(2, RegType.VGPR)), - ) - i2 = VSqrtF64Instruction( - RegPair(0, RegType.VGPR), - VOP3Operand(RegPair(2, RegType.VGPR)), - ) - self.assertEqual(i1, i2) - - -class TestScalarInterpreter(unittest.TestCase): - """Unit tests for the deterministic scalar interpreter.""" - - def setUp(self) -> None: - self.interp = ScalarInterpreter() - self.state = ScalarMachineState() - - def test_scalar_vgpr_source(self) -> None: - self.state.set_vgpr64(2, f64_to_bits(25.0)) - instr = VSqrtF64Instruction( - dst=RegPair(0, RegType.VGPR), - src=VOP3Operand(RegPair(2, RegType.VGPR)), - ) - res_bits = self.interp.step(instr, self.state) - self.assertEqual(bits_to_f64(res_bits), 5.0) - self.assertEqual(self.state.get_vgpr64(0), res_bits) - - def test_scalar_sgpr_source(self) -> None: - self.state.set_sgpr64(4, f64_to_bits(144.0)) - instr = VSqrtF64Instruction( - dst=RegPair(6, RegType.VGPR), - src=VOP3Operand(RegPair(4, RegType.SGPR)), - ) - res_bits = self.interp.step(instr, self.state) - self.assertEqual(bits_to_f64(res_bits), 12.0) - self.assertEqual(self.state.get_vgpr64(6), res_bits) - - def test_scalar_literal_source(self) -> None: - instr = VSqrtF64Instruction( - dst=RegPair(8, RegType.VGPR), - src=VOP3Operand(Literal64.from_float(0.0625)), - ) - res_bits = self.interp.step(instr, self.state) - self.assertEqual(bits_to_f64(res_bits), 0.25) - self.assertEqual(self.state.get_vgpr64(8), res_bits) - - def test_scalar_with_modifiers_and_clamp(self) -> None: - self.state.set_vgpr64(0, f64_to_bits(-16.0)) - # |-16.0| = 16.0 -> sqrt(16.0) = 4.0 -> clamp -> 1.0 - instr = VSqrtF64Instruction( - dst=RegPair(4, RegType.VGPR), - src=VOP3Operand(RegPair(0, RegType.VGPR), abs_mod=True), - clamp=True, - ) - res_bits = self.interp.step(instr, self.state) - self.assertEqual(res_bits, ONE_F64) - self.assertEqual(self.state.get_vgpr64(4), ONE_F64) - - def test_scalar_determinism(self) -> None: - runs = [] - for _ in range(50): - st = ScalarMachineState() - st.set_vgpr64(0, 0x400921FB54442D18) # pi - instr = VSqrtF64Instruction( - dst=RegPair(2, RegType.VGPR), - src=VOP3Operand(RegPair(0, RegType.VGPR)), - ) - runs.append(self.interp.step(instr, st)) - self.assertTrue(all(r == runs[0] for r in runs)) - - -class TestSIMDMultiLaneDivergence(unittest.TestCase): - """Unit tests for SIMD execution, lane divergence, and 32/64-bit EXEC masking.""" - - def setUp(self) -> None: - self.interp = SIMDInterpreter() - - def test_wave32_full_exec(self) -> None: - state = SIMDState(num_lanes=32, exec_mask=0xFFFF_FFFF) - for lane in range(32): - val = float(lane * lane) - state.set_vgpr64(lane, 0, f64_to_bits(val)) - instr = VSqrtF64Instruction( - dst=RegPair(2, RegType.VGPR), - src=VOP3Operand(RegPair(0, RegType.VGPR)), - ) - results = self.interp.step(instr, state) - for lane in range(32): - self.assertIsNotNone(results[lane]) - self.assertEqual(bits_to_f64(state.get_vgpr64(lane, 2)), float(lane)) - - def test_wave32_divergent_masking(self) -> None: - # Alternating mask: even lanes active (0x55555555) - sentinel = 0xDEAD_BEEF_CAFE_BABE - state = SIMDState(num_lanes=32, exec_mask=0x5555_5555) - for lane in range(32): - state.set_vgpr64(lane, 0, f64_to_bits(float(lane * lane))) - state.set_vgpr64(lane, 4, sentinel) - - instr = VSqrtF64Instruction( - dst=RegPair(4, RegType.VGPR), - src=VOP3Operand(RegPair(0, RegType.VGPR)), - ) - results = self.interp.step(instr, state) - for lane in range(32): - if lane % 2 == 0: - self.assertIsNotNone(results[lane]) - self.assertEqual(bits_to_f64(state.get_vgpr64(lane, 4)), float(lane)) - else: - self.assertIsNone(results[lane]) - self.assertEqual(state.get_vgpr64(lane, 4), sentinel) - - def test_wave64_full_exec(self) -> None: - state = SIMDState(num_lanes=64, exec_mask=0xFFFF_FFFF_FFFF_FFFF) - for lane in range(64): - state.set_vgpr64(lane, 0, f64_to_bits(float(lane * 4))) - instr = VSqrtF64Instruction( - dst=RegPair(2, RegType.VGPR), - src=VOP3Operand(RegPair(0, RegType.VGPR)), - ) - self.interp.step(instr, state) - for lane in range(64): - self.assertEqual(bits_to_f64(state.get_vgpr64(lane, 2)), math.sqrt(float(lane * 4))) - - def test_wave64_half_disabled(self) -> None: - # Lower 32 lanes active, upper 32 lanes inactive - sentinel = 0x1122_3344_5566_7788 - state = SIMDState(num_lanes=64, exec_mask=0x0000_0000_FFFF_FFFF) - for lane in range(64): - state.set_vgpr64(lane, 0, f64_to_bits(64.0)) - state.set_vgpr64(lane, 4, sentinel) - - instr = VSqrtF64Instruction( - dst=RegPair(4, RegType.VGPR), - src=VOP3Operand(RegPair(0, RegType.VGPR)), - ) - results = self.interp.step(instr, state) - for lane in range(64): - if lane < 32: - self.assertIsNotNone(results[lane]) - self.assertEqual(bits_to_f64(state.get_vgpr64(lane, 4)), 8.0) - else: - self.assertIsNone(results[lane]) - self.assertEqual(state.get_vgpr64(lane, 4), sentinel) - - def test_wave_exec_all_zero(self) -> None: - sentinel = 0xAA55_AA55_AA55_AA55 - state = SIMDState(num_lanes=32, exec_mask=0x0000_0000) - for lane in range(32): - state.set_vgpr64(lane, 0, sentinel) - instr = VSqrtF64Instruction( - dst=RegPair(0, RegType.VGPR), - src=VOP3Operand(Literal64.from_float(100.0)), - ) - results = self.interp.step(instr, state) - self.assertTrue(all(r is None for r in results)) - for lane in range(32): - self.assertEqual(state.get_vgpr64(lane, 0), sentinel) - - def test_simd_sgpr_uniform_broadcast(self) -> None: - state = SIMDState(num_lanes=32, exec_mask=0xFFFF_FFFF) - state.set_sgpr64(10, f64_to_bits(10000.0)) - - instr = VSqrtF64Instruction( - dst=RegPair(2, RegType.VGPR), - src=VOP3Operand(RegPair(10, RegType.SGPR)), - ) - self.interp.step(instr, state) - for lane in range(32): - self.assertEqual(bits_to_f64(state.get_vgpr64(lane, 2)), 100.0) - - -class TestRegisterAliasing(unittest.TestCase): - """Unit tests for register aliasing and in-place operand preservation.""" - - def setUp(self) -> None: - self.scalar_interp = ScalarInterpreter() - self.simd_interp = SIMDInterpreter() - - def test_dst_alias_src_inplace(self) -> None: - state = ScalarMachineState() - state.set_vgpr64(0, f64_to_bits(16.0)) - state.set_vgpr64(2, f64_to_bits(999.0)) - instr = VSqrtF64Instruction( - dst=RegPair(0, RegType.VGPR), - src=VOP3Operand(RegPair(0, RegType.VGPR)), - ) - self.scalar_interp.step(instr, state) - self.assertEqual(bits_to_f64(state.get_vgpr64(0)), 4.0) - # Unrelated register untouched - self.assertEqual(bits_to_f64(state.get_vgpr64(2)), 999.0) - - def test_inplace_iterative_convergence(self) -> None: - # Applying sqrt repeatedly converges towards 1.0 - state = ScalarMachineState() - state.set_vgpr64(0, f64_to_bits(65536.0)) - instr = VSqrtF64Instruction( - dst=RegPair(0, RegType.VGPR), - src=VOP3Operand(RegPair(0, RegType.VGPR)), - ) - # 65536 -> 256 -> 16 -> 4 -> 2 - for expected in [256.0, 16.0, 4.0, 2.0]: - self.scalar_interp.step(instr, state) - self.assertEqual(bits_to_f64(state.get_vgpr64(0)), expected) - - def test_partial_overlap_misaligned_alias(self) -> None: - # Destination v[1:2] partially overlaps source v[0:1] (shares v[1]) - state = ScalarMachineState() - bits_src = f64_to_bits(16.0) - state.set_vgpr64(0, bits_src) - lo0, hi0 = f64_bits_to_words(bits_src) - - instr = VSqrtF64Instruction( - dst=RegPair(1, RegType.VGPR), - src=VOP3Operand(RegPair(0, RegType.VGPR)), - ) - res_bits = self.scalar_interp.step(instr, state) - self.assertEqual(bits_to_f64(res_bits), 4.0) - self.assertEqual(state.get_vgpr64(1), res_bits) - # v[0] should remain unchanged lo0 - self.assertEqual(state.vgprs[0], lo0) - - def test_simd_multi_lane_aliasing(self) -> None: - state = SIMDState(num_lanes=32, exec_mask=0xFFFF_FFFF) - for lane in range(32): - state.set_vgpr64(lane, 0, f64_to_bits(float(lane * lane))) - - instr = VSqrtF64Instruction( - dst=RegPair(0, RegType.VGPR), - src=VOP3Operand(RegPair(0, RegType.VGPR)), - ) - self.simd_interp.step(instr, state) - for lane in range(32): - self.assertEqual(bits_to_f64(state.get_vgpr64(lane, 0)), float(lane)) - - -class TestConditionCodesAndStatusFlags(unittest.TestCase): - """Unit tests for status flags, condition codes, and carry/borrow generation.""" - - def test_exact_finite_flags(self) -> None: - s = f64_to_bits(4.0) - res = oracle_v_sqrt_f64(s) - flags = evaluate_v_sqrt_f64_flags(s, res) - self.assertFalse(flags.invalid) - self.assertFalse(flags.overflow) - self.assertFalse(flags.underflow) - self.assertFalse(flags.inexact) - self.assertFalse(flags.zero) - self.assertFalse(flags.negative) - self.assertFalse(flags.denormal) - self.assertFalse(flags.infinite) - self.assertFalse(flags.nan) - - def test_inexact_flag(self) -> None: - s = f64_to_bits(2.0) - res = oracle_v_sqrt_f64(s) - flags = evaluate_v_sqrt_f64_flags(s, res) - self.assertTrue(flags.inexact) - self.assertFalse(flags.invalid) - - def test_invalid_operation_flag(self) -> None: - # Negative radicand - s_neg = f64_to_bits(-1.0) - res = oracle_v_sqrt_f64(s_neg) - flags = evaluate_v_sqrt_f64_flags(s_neg, res) - self.assertTrue(flags.invalid) - self.assertTrue(flags.nan) - - # Signaling NaN operand - snan = 0x7FF0_0000_0000_0001 - res_snan = oracle_v_sqrt_f64(snan) - flags_snan = evaluate_v_sqrt_f64_flags(snan, res_snan) - self.assertTrue(flags_snan.invalid) - self.assertTrue(flags_snan.nan) - - # Negative infinity - res_ninf = oracle_v_sqrt_f64(NEG_INF) - flags_ninf = evaluate_v_sqrt_f64_flags(NEG_INF, res_ninf) - self.assertTrue(flags_ninf.invalid) - self.assertTrue(flags_ninf.nan) - - def test_zero_and_negative_flags(self) -> None: - # +0.0 - res_pz = oracle_v_sqrt_f64(POS_ZERO) - flags_pz = evaluate_v_sqrt_f64_flags(POS_ZERO, res_pz) - self.assertTrue(flags_pz.zero) - self.assertFalse(flags_pz.negative) - - # -0.0 - res_nz = oracle_v_sqrt_f64(NEG_ZERO) - flags_nz = evaluate_v_sqrt_f64_flags(NEG_ZERO, res_nz) - self.assertTrue(flags_nz.zero) - self.assertTrue(flags_nz.negative) - - def test_infinite_flag(self) -> None: - res = oracle_v_sqrt_f64(POS_INF) - flags = evaluate_v_sqrt_f64_flags(POS_INF, res) - self.assertTrue(flags.infinite) - self.assertFalse(flags.invalid) - - def test_sqrt_borrow_generation(self) -> None: - # Perfect square: 4.0 - s4 = f64_to_bits(4.0) - res2 = oracle_v_sqrt_f64(s4) - rem, borrow = compute_f64_sqrt_borrow(s4, res2) - self.assertEqual(borrow, 0) - - -class TestIEEE754BoundaryExtremes(unittest.TestCase): - """Unit tests for IEEE 754 boundary extremes, subnormals, and NaN handling.""" - - def test_subnormal_sqrt_transition_to_normal(self) -> None: - # Smallest positive subnormal: 2^-1074 (bits: 0x1) - # sqrt(2^-1074) = 2^-537, which is a normal double! - sub_min = 0x0000_0000_0000_0001 - res = oracle_v_sqrt_f64(sub_min) - self.assertFalse(is_subnormal(res)) - self.assertFalse(is_zero(res)) - # Exponent of 2^-537 in IEEE 754 (bias 1023): 1023 - 537 = 486 - sign, exp, frac = split_f64_bits(res) - self.assertEqual(sign, 0) - self.assertEqual(exp, 486) - self.assertEqual(frac, 0) - - def test_largest_subnormal_sqrt(self) -> None: - # Largest subnormal: 0x000F_FFFF_FFFF_FFFF = (1 - 2^-52) * 2^-1022 - max_sub = 0x000F_FFFF_FFFF_FFFF - res = oracle_v_sqrt_f64(max_sub) - self.assertFalse(is_subnormal(res)) - # Exponent is 511 (just below 2^-511) - sign, exp, _ = split_f64_bits(res) - self.assertEqual(sign, 0) - self.assertEqual(exp, 511) - - def test_nan_signaling_to_quiet_conversion(self) -> None: - snan = 0x7FF0_0000_0000_0005 # fraction non-zero, quiet bit 51 is 0 - self.assertTrue(is_snan(snan)) - res = oracle_v_sqrt_f64(snan) - self.assertTrue(is_qnan(res)) - self.assertEqual(res, snan | QNAN_BIT) - - def test_nan_payload_preservation(self) -> None: - payload = 0x0008_DEAD_BEEF_CAFE - qnan = EXP_MASK | payload - res = oracle_v_sqrt_f64(qnan) - self.assertEqual(res, qnan) - - def test_nan_with_modifiers(self) -> None: - qnan = 0x7FF8_0000_0000_0001 - # abs clears sign bit - res_abs = oracle_v_sqrt_f64(qnan | SIGN_MASK, abs_mod=True) - self.assertEqual(res_abs & SIGN_MASK, 0) - self.assertTrue(is_qnan(res_abs)) - - # neg toggles sign bit - res_neg = oracle_v_sqrt_f64(qnan, neg_mod=True) - self.assertEqual(res_neg & SIGN_MASK, SIGN_MASK) - - def test_nan_with_clamp(self) -> None: - qnan = CANONICAL_QNAN - res = oracle_v_sqrt_f64(qnan, clamp=True) - self.assertEqual(res, POS_ZERO) - - snan = 0x7FF0_0000_0000_0001 - res_snan = oracle_v_sqrt_f64(snan, clamp=True) - self.assertEqual(res_snan, POS_ZERO) - - def test_infinity_arithmetic_boundaries(self) -> None: - self.assertEqual(oracle_v_sqrt_f64(POS_INF), POS_INF) - self.assertEqual(oracle_v_sqrt_f64(NEG_INF), CANONICAL_QNAN) - self.assertEqual(oracle_v_sqrt_f64(POS_INF, clamp=True), ONE_F64) - self.assertEqual(oracle_v_sqrt_f64(NEG_INF, clamp=True), POS_ZERO) - - def test_maximum_finite_f64(self) -> None: - max_f64 = 0x7FEF_FFFF_FFFF_FFFF - res = oracle_v_sqrt_f64(max_f64) - f_res = bits_to_f64(res) - self.assertAlmostEqual(f_res, 1.3407807929942597e+154, delta=1e140) - - def test_smallest_normal_f64(self) -> None: - # 2^-1022 (0x0010_0000_0000_0000) -> sqrt is 2^-511 (0x2000_0000_0000_0000) - min_norm = 0x0010_0000_0000_0000 - res = oracle_v_sqrt_f64(min_norm) - expected = 0x2000_0000_0000_0000 - self.assertEqual(res, expected) - - -class TestNegativeControlsAndMutationDetection(unittest.TestCase): - """Unit tests for negative controls, syntax rejection, and mutation detection.""" - - def test_syntax_rejection_invalid_register_indices(self) -> None: - with self.assertRaises(ValueError): - RegPair(255, RegType.VGPR) - with self.assertRaises(ValueError): - RegPair(-1, RegType.VGPR) - with self.assertRaises(ValueError): - RegPair(300, RegType.SGPR) - - def test_syntax_rejection_invalid_destination(self) -> None: - with self.assertRaises(TypeError): - VSqrtF64Instruction( - dst=RegPair(0, RegType.SGPR), - src=VOP3Operand(RegPair(2, RegType.VGPR)), - ) - - def test_syntax_rejection_invalid_lane_count(self) -> None: - with self.assertRaises(ValueError): - SIMDState(num_lanes=16) - with self.assertRaises(ValueError): - SIMDState(num_lanes=48) - with self.assertRaises(ValueError): - SIMDState(num_lanes=128) - - def test_negative_control_divergence(self) -> None: - s = f64_to_bits(16.0) - res = oracle_v_sqrt_f64(s) - self.assertNotEqual(res, f64_to_bits(5.0)) - self.assertNotEqual(res, f64_to_bits(16.0)) - - def test_mutation_detection_identity_mutant(self) -> None: - def mutant_oracle(src: int) -> int: - return src - - s = f64_to_bits(16.0) - golden = oracle_v_sqrt_f64(s) - mutant = mutant_oracle(s) - self.assertNotEqual(golden, mutant) - - def test_mutation_detection_snan_unquieted(self) -> None: - def mutant_oracle(src: int) -> int: - return src - - snan = 0x7FF0_0000_0000_0001 - golden = oracle_v_sqrt_f64(snan) - mutant = mutant_oracle(snan) - self.assertTrue(is_qnan(golden)) - self.assertFalse(is_qnan(mutant)) - - def test_mutation_detection_neg_zero_to_pos_zero(self) -> None: - def mutant_oracle(src: int) -> int: - return POS_ZERO if is_zero(src) else oracle_v_sqrt_f64(src) - - golden = oracle_v_sqrt_f64(NEG_ZERO) - mutant = mutant_oracle(NEG_ZERO) - self.assertEqual(golden, NEG_ZERO) - self.assertNotEqual(golden, mutant) - - def test_mutation_detection_unclamped_mutant(self) -> None: - def mutant_oracle(src: int, clamp: bool = False) -> int: - return oracle_v_sqrt_f64(src, clamp=False) - - s = f64_to_bits(4.0) - golden = oracle_v_sqrt_f64(s, clamp=True) - mutant = mutant_oracle(s, clamp=True) - self.assertEqual(golden, ONE_F64) - self.assertNotEqual(golden, mutant) - - def test_mutation_detection_ignoring_abs_modifier(self) -> None: - def mutant_oracle(src: int, abs_mod: bool = False) -> int: - return oracle_v_sqrt_f64(src, abs_mod=False) - - val = f64_to_bits(-9.0) - golden = oracle_v_sqrt_f64(val, abs_mod=True) - mutant = mutant_oracle(val, abs_mod=True) - self.assertEqual(bits_to_f64(golden), 3.0) - self.assertEqual(mutant, CANONICAL_QNAN) - self.assertNotEqual(golden, mutant) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_valu_sub_f16.py b/tests/semantic/test_valu_sub_f16.py deleted file mode 100644 index d01c9d63a..000000000 --- a/tests/semantic/test_valu_sub_f16.py +++ /dev/null @@ -1,150 +0,0 @@ -"""v_sub_f16 (RDNA2 VOP2 / VOP3): D.f16 = S0.f16 - S1.f16, binary16 with round to nearest even. - -Every case is translated by tools/rdna2spirv.py and executed with tests/semantic/spirv_mini_interp.py; the expected -word is written down by hand (from the ISA) next to each case, rechecked against the plain-Python binary16 reference in -tests/semantic/f16_ref.py, and extended with seeded random operands. Covers the _e32 form (the high half of the -destination is kept), the _e64 form with op_sel, SGPR / literal / inline-constant sources, neg/abs, omod and clamp. -Standard library only: no GPU, no LLVM, no game data. -""" -import os -import random -import sys -import unittest - -HERE = os.path.dirname(os.path.abspath(__file__)) -sys.dont_write_bytecode = True -sys.path.insert(0, HERE) -import support # noqa: E402 -from f16_ref import OLD, ref_sub, same_f16, scale # noqa: E402 - -ONE, TWO, THREE, HALF, QUARTER = 0x3C00, 0x4000, 0x4200, 0x3800, 0x3400 -MAXH, INF, NINF, QNAN = 0x7BFF, 0x7C00, 0xFC00, 0x7E00 -MIN_NORMAL, MIN_SUB, MAX_SUB = 0x0400, 0x0001, 0x03FF - - -def run(line, seeds, old=OLD, hi=0x5A5A): - """Run one instruction on a one-lane pixel shader and return v0 as exported to mrt0. - - `seeds` maps a register ("v1", "s2", ...) to the word it starts with; a value that fits in 16 bits gets `hi` in its - upper half, so reading the wrong half of a source shows. v0 starts as `old`. - """ - prog = [f"v_mov_b32 v0, {old:#x}"] - for reg, w in seeds.items(): - w = w if w > 0xFFFF else (hi << 16) | w - prog.append(f"{'s' if reg[0] == 's' else 'v'}_mov_b32 {reg}, {w:#x}") - prog += [line, "exp mrt0 v0, v0, v0, v0 done vm", "s_endpgm"] - return support.mrt0_words(support.translate_lines("ps_sub_f16", prog))[0] - - -# (src0, src1, D), written by hand. -CASES = [ - (THREE, ONE, TWO), # 3 - 1 = 2 - (ONE, TWO, 0xBC00), # 1 - 2 = -1 - (HALF, QUARTER, QUARTER), # 0.5 - 0.25 - (0x3E00, 0x3E00, 0x0000), # x - x = +0 - (0x8000, 0x0000, 0x8000), # -0 - +0 = -0 - (0x0000, 0x0000, 0x0000), # +0 - +0 = +0 - (0x0000, 0x8000, 0x0000), # +0 - -0 = +0 - (0x8000, 0x8000, 0x0000), # -0 - -0 = -0 + +0 = +0 - (MAXH, 0xFBFF, INF), # 65504 - -65504 overflows - (MAXH, 0xCC00, INF), # 65504 - -16 = 65520: tie, even is the overflow - (MIN_NORMAL, MIN_SUB, MAX_SUB), # 2^-14 - 2^-24 = the largest subnormal - (MIN_SUB, 0x8001, 0x0002), # 2^-24 - -2^-24 - (ONE, 0x9000, ONE), # 1 - -2^-11: half an ulp, ties to even, stays 1 - (ONE, 0x9001, 0x3C01), # a little over half an ulp rounds up - (0x3C01, ONE, 0x1400), # (1 + 2^-10) - 1 = 2^-10, exact - (INF, INF, QNAN), # inf - inf = NaN - (INF, NINF, INF), - (ONE, QNAN, QNAN), -] - -SPECIAL = [0x0000, 0x8000, ONE, 0xBC00, TWO, 0xC000, HALF, 0xB800, THREE, 0x3E00, MAXH, 0xFBFF, INF, NINF, QNAN, - MIN_NORMAL, MIN_SUB, 0x8001, MAX_SUB, 0x3C01, 0x3BFF, 0x1000, 0x6800, 0x6801, 0x4C00] - - -class SubF16(unittest.TestCase): - def test_hand_written_table_matches_reference(self): - for a, b, want in CASES: - self.assertTrue(same_f16(ref_sub(a, b), want), (hex(a), hex(b), hex(ref_sub(a, b)))) - - def test_e32_writes_low_half_and_keeps_high_half(self): - for a, b, want in CASES: - with self.subTest(a=hex(a), b=hex(b)): - got = run("v_sub_f16 v0, v1, v2", {"v1": a, "v2": b}) - self.assertEqual(got >> 16, OLD >> 16) - self.assertTrue(same_f16(got & 0xFFFF, want), hex(got)) - - def test_vop3_sgpr_and_literal_sources(self): - for a, b, want in CASES[:14]: - forms = [ - ("e64 vgpr", "v_sub_f16_e64 v0, v1, v2", {"v1": a, "v2": b}), - ("e64 sgpr", "v_sub_f16_e64 v0, s1, s2", {"s1": a, "s2": b}), - ("e32 sgpr src0", "v_sub_f16 v0, s1, v2", {"s1": a, "v2": b}), - ("e32 literal src0", f"v_sub_f16 v0, {a:#x}, v2", {"v2": b}), - ("e64 literal src1", f"v_sub_f16_e64 v0, v1, {b:#x}", {"v1": a}), - ] - for form, line, seeds in forms: - with self.subTest(a=hex(a), b=hex(b), form=form): - got = run(line, seeds) - self.assertEqual(got >> 16, OLD >> 16) - self.assertTrue(same_f16(got & 0xFFFF, want), hex(got)) - - def test_inline_constants(self): - # (inline constant as src0, its binary16 value, v1 low half, D), by hand - for text, c, b, want in (("2.0", TWO, HALF, 0x3E00), ("-1.0", 0xBC00, HALF, 0xBE00), ("0.5", HALF, QUARTER, QUARTER), - ("4.0", 0x4400, 0xB800, 0x4480), ("1.0", ONE, ONE, 0x0000)): - with self.subTest(const=text): - self.assertEqual(run(f"v_sub_f16 v0, {text}, v1", {"v1": b}) & 0xFFFF, want) - self.assertEqual(ref_sub(c, b), want) - - def test_op_sel_selects_source_and_destination_halves(self): - # src0 = (lo 1.0, hi 3.0), src1 = (lo 0.5, hi -0.25); D by hand for each (src0 half, src1 half). - s0, s1 = (THREE << 16) | ONE, (0xB400 << 16) | HALF - expect_lo = {(0, 0): 0x3800, (1, 0): 0x4100, (0, 1): 0x3D00, (1, 1): 0x4280} # 0.5, 2.5, 1.25, 3.25 - for h0 in (0, 1): - for h1 in (0, 1): - for dh in (0, 1): - want = expect_lo[(h0, h1)] - expect = ((want << 16) | (OLD & 0xFFFF)) if dh else ((OLD & 0xFFFF0000) | want) - with self.subTest(op_sel=(h0, h1, dh)): - got = run(f"v_sub_f16_e64 v0, v1, v2 op_sel:[{h0},{h1},{dh}]", {"v1": s0, "v2": s1}) - self.assertEqual(got, expect) - - def test_neg_and_abs_source_modifiers(self): - # v1 = 1.0, v2 = -0.5; (operand text, D) by hand - for ops, want in (("v1, v2", 0x3E00), ("-v1, v2", 0xB800), ("v1, -v2", HALF), ("|v1|, |v2|", HALF), - ("-|v1|, v2", 0xB800), ("v1, -|v2|", 0x3E00)): - with self.subTest(ops=ops): - got = run(f"v_sub_f16_e64 v0, {ops}", {"v1": ONE, "v2": 0xB800}) - self.assertEqual(got & 0xFFFF, want) - - def test_output_modifiers_and_clamp(self): - # #4542, measured on gfx1036: an f16 destination ignores omod (mul:2/mul:4/div:2) under the game's MODE - # (IEEE=0, f16 denormals kept) and keeps clamp (docs/design.md, f16 output modifiers). - # unmodified result: 2.5 - 0.5 = 2.0; clamp limits it to [0, 1] (negatives and NaN become +0) - for suffix, want in ((" mul:2", 0x4000), (" mul:4", 0x4000), (" div:2", 0x4000), (" clamp", ONE)): - with self.subTest(mod=suffix): - got = run("v_sub_f16_e64 v0, v1, v2" + suffix, {"v1": 0x4100, "v2": HALF}) - self.assertEqual(got & 0xFFFF, want) - for (a, b), suffix, want in (((HALF, QUARTER), " clamp", QUARTER), ((HALF, ONE), " clamp", 0x0000), - ((ONE, 0xB800), " div:2 clamp", ONE), ((ONE, QUARTER), " mul:2 clamp", 0x3A00)): - with self.subTest(a=hex(a), b=hex(b), mod=suffix): - self.assertEqual(run("v_sub_f16_e64 v0, v1, v2" + suffix, {"v1": a, "v2": b}) & 0xFFFF, want) - for suffix, f in ((" mul:2", 2.0), (" mul:4", 4.0), (" div:2", 0.5)): - got = run("v_sub_f16_e64 v0, v1, v2" + suffix, {"v1": 0x4900, "v2": 0xC100}) # 10 and -2.5 - self.assertEqual(got & 0xFFFF, ref_sub(0x4900, 0xC100)) - - def test_random_operands(self): - rng = random.Random(0x50B16) - pool = SPECIAL + [rng.getrandbits(16) for _ in range(40)] - for _ in range(120): - a = rng.choice(pool) if rng.random() < 0.5 else rng.getrandbits(16) - b = rng.choice(pool) if rng.random() < 0.5 else rng.getrandbits(16) - with self.subTest(a=hex(a), b=hex(b)): - got = run("v_sub_f16 v0, v1, v2", {"v1": a, "v2": b}) - self.assertEqual(got >> 16, OLD >> 16) - self.assertTrue(same_f16(got & 0xFFFF, ref_sub(a, b)), (hex(got), hex(ref_sub(a, b)))) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_valu_subrev_f16.py b/tests/semantic/test_valu_subrev_f16.py deleted file mode 100644 index 3156e0062..000000000 --- a/tests/semantic/test_valu_subrev_f16.py +++ /dev/null @@ -1,154 +0,0 @@ -"""v_subrev_f16 (RDNA2 VOP2 / VOP3): D.f16 = S1.f16 - S0.f16 (v_sub_f16 with its operands swapped), binary16. - -Every case is translated by tools/rdna2spirv.py and executed with tests/semantic/spirv_mini_interp.py; the expected -word is written down by hand (from the ISA) next to each case, rechecked against the plain-Python binary16 reference in -tests/semantic/f16_ref.py, and extended with seeded random operands. Covers the _e32 form (the high half of the -destination is kept), the _e64 form with op_sel, SGPR / literal / inline-constant sources, neg/abs, omod and clamp. -Standard library only: no GPU, no LLVM, no game data. -""" -import os -import random -import sys -import unittest - -HERE = os.path.dirname(os.path.abspath(__file__)) -sys.dont_write_bytecode = True -sys.path.insert(0, HERE) -import support # noqa: E402 -from f16_ref import OLD, ref_sub, same_f16, scale # noqa: E402 - -ONE, TWO, THREE, HALF, QUARTER = 0x3C00, 0x4000, 0x4200, 0x3800, 0x3400 -MAXH, INF, NINF, QNAN = 0x7BFF, 0x7C00, 0xFC00, 0x7E00 -MIN_NORMAL, MIN_SUB, MAX_SUB = 0x0400, 0x0001, 0x03FF - - -def ref_subrev(a, b): - return ref_sub(b, a) - - -def run(line, seeds, old=OLD, hi=0x5A5A): - """Run one instruction on a one-lane pixel shader and return v0 as exported to mrt0. - - `seeds` maps a register ("v1", "s2", ...) to the word it starts with; a value that fits in 16 bits gets `hi` in its - upper half, so reading the wrong half of a source shows. v0 starts as `old`. - """ - prog = [f"v_mov_b32 v0, {old:#x}"] - for reg, w in seeds.items(): - w = w if w > 0xFFFF else (hi << 16) | w - prog.append(f"{'s' if reg[0] == 's' else 'v'}_mov_b32 {reg}, {w:#x}") - prog += [line, "exp mrt0 v0, v0, v0, v0 done vm", "s_endpgm"] - return support.mrt0_words(support.translate_lines("ps_subrev_f16", prog))[0] - - -# (src0, src1, D), written by hand. -CASES = [ - (ONE, THREE, TWO), # 3 - 1 = 2 - (TWO, ONE, 0xBC00), # 1 - 2 = -1 - (QUARTER, HALF, QUARTER), # 0.5 - 0.25 - (0x3E00, 0x3E00, 0x0000), # x - x = +0 - (0x0000, 0x8000, 0x8000), # -0 - +0 = -0 - (0x0000, 0x0000, 0x0000), # +0 - +0 = +0 - (0x8000, 0x0000, 0x0000), # +0 - -0 = +0 - (0x8000, 0x8000, 0x0000), # -0 - -0 = -0 + +0 = +0 - (0xFBFF, MAXH, INF), # 65504 - -65504 overflows - (0xCC00, MAXH, INF), # 65504 - -16 = 65520: tie, even is the overflow - (MIN_SUB, MIN_NORMAL, MAX_SUB), # 2^-14 - 2^-24 = the largest subnormal - (0x8001, MIN_SUB, 0x0002), # 2^-24 - -2^-24 - (0x9000, ONE, ONE), # 1 - -2^-11: half an ulp, ties to even, stays 1 - (0x9001, ONE, 0x3C01), # a little over half an ulp rounds up - (ONE, 0x3C01, 0x1400), # (1 + 2^-10) - 1 = 2^-10, exact - (INF, INF, QNAN), # inf - inf = NaN - (NINF, INF, INF), - (QNAN, ONE, QNAN), -] - -SPECIAL = [0x0000, 0x8000, ONE, 0xBC00, TWO, 0xC000, HALF, 0xB800, THREE, 0x3E00, MAXH, 0xFBFF, INF, NINF, QNAN, - MIN_NORMAL, MIN_SUB, 0x8001, MAX_SUB, 0x3C01, 0x3BFF, 0x1000, 0x6800, 0x6801, 0x4C00] - - -class SubrevF16(unittest.TestCase): - def test_hand_written_table_matches_reference(self): - for a, b, want in CASES: - self.assertTrue(same_f16(ref_subrev(a, b), want), (hex(a), hex(b), hex(ref_subrev(a, b)))) - - def test_e32_writes_low_half_and_keeps_high_half(self): - for a, b, want in CASES: - with self.subTest(a=hex(a), b=hex(b)): - got = run("v_subrev_f16 v0, v1, v2", {"v1": a, "v2": b}) - self.assertEqual(got >> 16, OLD >> 16) - self.assertTrue(same_f16(got & 0xFFFF, want), hex(got)) - - def test_vop3_sgpr_and_literal_sources(self): - for a, b, want in CASES[:14]: - forms = [ - ("e64 vgpr", "v_subrev_f16_e64 v0, v1, v2", {"v1": a, "v2": b}), - ("e64 sgpr", "v_subrev_f16_e64 v0, s1, s2", {"s1": a, "s2": b}), - ("e32 sgpr src0", "v_subrev_f16 v0, s1, v2", {"s1": a, "v2": b}), - ("e32 literal src0", f"v_subrev_f16 v0, {a:#x}, v2", {"v2": b}), - ("e64 literal src1", f"v_subrev_f16_e64 v0, v1, {b:#x}", {"v1": a}), - ] - for form, line, seeds in forms: - with self.subTest(a=hex(a), b=hex(b), form=form): - got = run(line, seeds) - self.assertEqual(got >> 16, OLD >> 16) - self.assertTrue(same_f16(got & 0xFFFF, want), hex(got)) - - def test_inline_constants(self): - # (inline constant as src0, its binary16 value, v1 low half, D), by hand - for text, c, b, want in (("2.0", TWO, HALF, 0xBE00), ("-1.0", 0xBC00, HALF, 0x3E00), ("0.5", HALF, QUARTER, 0xB400), - ("4.0", 0x4400, 0xB800, 0xC480), ("1.0", ONE, ONE, 0x0000)): - with self.subTest(const=text): - self.assertEqual(run(f"v_subrev_f16 v0, {text}, v1", {"v1": b}) & 0xFFFF, want) - self.assertEqual(ref_subrev(c, b), want) - - def test_op_sel_selects_source_and_destination_halves(self): - # src0 = (lo 1.0, hi 3.0), src1 = (lo 0.5, hi -0.25); D by hand for each (src0 half, src1 half). - s0, s1 = (THREE << 16) | ONE, (0xB400 << 16) | HALF - expect_lo = {(0, 0): 0xB800, (1, 0): 0xC100, (0, 1): 0xBD00, (1, 1): 0xC280} # -0.5, -2.5, -1.25, -3.25 - for h0 in (0, 1): - for h1 in (0, 1): - for dh in (0, 1): - want = expect_lo[(h0, h1)] - expect = ((want << 16) | (OLD & 0xFFFF)) if dh else ((OLD & 0xFFFF0000) | want) - with self.subTest(op_sel=(h0, h1, dh)): - got = run(f"v_subrev_f16_e64 v0, v1, v2 op_sel:[{h0},{h1},{dh}]", {"v1": s0, "v2": s1}) - self.assertEqual(got, expect) - - def test_neg_and_abs_source_modifiers(self): - # v1 = 1.0, v2 = -0.5; (operand text, D) by hand - for ops, want in (("v1, v2", 0xBE00), ("-v1, v2", HALF), ("v1, -v2", 0xB800), ("|v1|, |v2|", 0xB800), - ("-|v1|, v2", HALF), ("v1, -|v2|", 0xBE00)): - with self.subTest(ops=ops): - got = run(f"v_subrev_f16_e64 v0, {ops}", {"v1": ONE, "v2": 0xB800}) - self.assertEqual(got & 0xFFFF, want) - - def test_output_modifiers_and_clamp(self): - # #4542, measured on gfx1036: an f16 destination ignores omod (mul:2/mul:4/div:2) under the game's MODE - # (IEEE=0, f16 denormals kept) and keeps clamp (docs/design.md, f16 output modifiers). - # unmodified result: 2.5 - 0.5 = 2.0 (src1 - src0); clamp limits it to [0, 1] (negatives and NaN become +0) - for suffix, want in ((" mul:2", 0x4000), (" mul:4", 0x4000), (" div:2", 0x4000), (" clamp", ONE)): - with self.subTest(mod=suffix): - got = run("v_subrev_f16_e64 v0, v1, v2" + suffix, {"v1": HALF, "v2": 0x4100}) - self.assertEqual(got & 0xFFFF, want) - for (a, b), suffix, want in (((QUARTER, HALF), " clamp", QUARTER), ((ONE, HALF), " clamp", 0x0000), - ((0xB800, ONE), " div:2 clamp", ONE), ((QUARTER, ONE), " mul:2 clamp", 0x3A00)): - with self.subTest(a=hex(a), b=hex(b), mod=suffix): - self.assertEqual(run("v_subrev_f16_e64 v0, v1, v2" + suffix, {"v1": a, "v2": b}) & 0xFFFF, want) - for suffix, f in ((" mul:2", 2.0), (" mul:4", 4.0), (" div:2", 0.5)): - got = run("v_subrev_f16_e64 v0, v1, v2" + suffix, {"v1": 0x4900, "v2": 0xC100}) # 10 and -2.5 - self.assertEqual(got & 0xFFFF, ref_subrev(0x4900, 0xC100)) - - def test_random_operands(self): - rng = random.Random(0x5B2E5) - pool = SPECIAL + [rng.getrandbits(16) for _ in range(40)] - for _ in range(120): - a = rng.choice(pool) if rng.random() < 0.5 else rng.getrandbits(16) - b = rng.choice(pool) if rng.random() < 0.5 else rng.getrandbits(16) - with self.subTest(a=hex(a), b=hex(b)): - got = run("v_subrev_f16 v0, v1, v2", {"v1": a, "v2": b}) - self.assertEqual(got >> 16, OLD >> 16) - self.assertTrue(same_f16(got & 0xFFFF, ref_subrev(a, b)), (hex(got), hex(ref_subrev(a, b)))) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_valu_trig_f32.py b/tests/semantic/test_valu_trig_f32.py deleted file mode 100644 index 772488bd6..000000000 --- a/tests/semantic/test_valu_trig_f32.py +++ /dev/null @@ -1,720 +0,0 @@ -"""Semantic value tests for RDNA2 single-precision transcendental VALU operations: - - v_cos_f32: D.f32 = cos(S0.f32 * 2*pi) (operand in turns / revolutions) - - v_sin_f32: D.f32 = sin(S0.f32 * 2*pi) (operand in turns / revolutions) - - v_rcp_f32: D.f32 = 1.0 / S0.f32 (single-precision reciprocal) - - v_rsq_f32: D.f32 = 1.0 / sqrt(S0.f32) (single-precision inverse square root) - - v_sqrt_f32: D.f32 = sqrt(S0.f32) (single-precision square root) - -RDNA2 takes trigonometric inputs in units of revolutions (turns), reducing to [-0.5, 0.5] -before multiplying by 2*pi. Reciprocal and inverse square root provide 1-ULP approximations -satisfying core identities: - - Pythagorean: sin^2(x) + cos^2(x) ~= 1.0 - - Reciprocal: x * rcp(x) ~= 1.0 - - Inverse Sqrt: x * (rsq(x))^2 ~= 1.0 - - Sqrt / Rsq: rsq(x) * sqrt(x) ~= 1.0 - -This test suite verifies plain-Python IEEE-754 / RDNA2 reference oracles, mathematical -invariants, an in-test RDNA2 SIMD wave interpreter modeling multi-lane divergence under -EXEC masking, and end-to-end SPIR-V shader translation and execution via spirv_mini_interp. - -Standard library Python only; synthetic hand-written listings only (no game data). -""" -from __future__ import annotations - -import gc -import math -import os -import struct -import sys -import tempfile -import unittest -import warnings - -HERE = os.path.dirname(os.path.abspath(__file__)) -ROOT = os.path.dirname(os.path.dirname(HERE)) -TOOLS_DIR = os.environ.get("LEONIDA_TOOLS_DIR") or os.path.join(ROOT, "tools") - -sys.dont_write_bytecode = True -if TOOLS_DIR not in sys.path: - sys.path.insert(0, TOOLS_DIR) -if HERE not in sys.path: - sys.path.insert(0, HERE) - -import rdna2spirv # noqa: E402 -import spirv_mini_interp as si # noqa: E402 -import support # noqa: E402 - -MASK32 = 0xFFFFFFFF -MASK64 = 0xFFFFFFFFFFFFFFFF -TWO_PI = 6.283185307179586476925286766559 -SENTINEL_FILL = 0xDEADBEEF - -# Canonical binary32 IEEE-754 bit patterns. -POS_ZERO = 0x00000000 -NEG_ZERO = 0x80000000 -SUBNORM_MIN = 0x00000001 # 2^-149 (smallest positive subnormal) -NEG_SUBNORM_MIN = 0x80000001 # -2^-149 -SUBNORM_MAX = 0x007FFFFF # (1 - 2^-23) * 2^-126 -FLT_MIN = 0x00800000 # 2^-126 (smallest positive normal) -NEG_FLT_MIN = 0x80800000 # -2^-126 -HALF = 0x3F000000 # 0.5 -NEG_HALF = 0xBF000000 # -0.5 -ONE = 0x3F800000 # 1.0 -NEG_ONE = 0xBF800000 # -1.0 -TWO = 0x40000000 # 2.0 -NEG_TWO = 0xC0000000 # -2.0 -FOUR = 0x40800000 # 4.0 -SIXTEEN = 0x41800000 # 16.0 -POS_INF = 0x7F800000 # +inf -NEG_INF = 0xFF800000 # -inf -QNAN = 0x7FC00000 # canonical positive quiet NaN -NEG_QNAN = 0xFFC00000 # canonical negative quiet NaN -SNAN = 0x7F800001 # signaling NaN - - -def f32_to_bits(val: float) -> int: - """Pack Python float to 32-bit unsigned integer IEEE-754 representation.""" - try: - return struct.unpack(" 0 else NEG_INF - - -def bits_to_f32(bits: int) -> float: - """Unpack 32-bit unsigned integer to Python single-precision float.""" - return struct.unpack(" bool: - """Check if 32-bit word encodes an IEEE-754 NaN.""" - b = bits & MASK32 - return (b & 0x7F800000) == 0x7F800000 and (b & 0x007FFFFF) != 0 - - -def round_even(x: float) -> float: - """Round to nearest integer, breaking ties to even (IEEE-754 roundTiesToEven).""" - return float(round(x)) - - -def ref_turn_reduce(turns: float) -> float: - """Reduce turn count to [-0.5, 0.5] as performed by RDNA2 hardware and rdna2spirv. - - For finite inputs, turns - round_even(turns) reduces exactly in binary32. - Signed zeros (+0.0 and -0.0) are preserved. - """ - if math.isnan(turns) or math.isinf(turns): - return float("nan") - if turns == 0.0: - return turns - return turns - round_even(turns) - - -def ref_cos_f32(turns_bits: int) -> int: - """RDNA2 v_cos_f32 reference oracle: D.f32 = cos(turns * 2*pi).""" - if is_f32_nan_bits(turns_bits): - return QNAN - val = bits_to_f32(turns_bits) - if math.isinf(val): - return QNAN - if val == 0.0: - return ONE - t = ref_turn_reduce(val) - rad = t * TWO_PI - res = math.cos(rad) - return f32_to_bits(res) - - -def ref_sin_f32(turns_bits: int) -> int: - """RDNA2 v_sin_f32 reference oracle: D.f32 = sin(turns * 2*pi).""" - if is_f32_nan_bits(turns_bits): - return QNAN - val = bits_to_f32(turns_bits) - if math.isinf(val): - return QNAN - if turns_bits == NEG_ZERO: - return NEG_ZERO - if turns_bits == POS_ZERO: - return POS_ZERO - t = ref_turn_reduce(val) - rad = t * TWO_PI - res = math.sin(rad) - if res == 0.0 and math.copysign(1.0, val) < 0: - return NEG_ZERO - return f32_to_bits(res) - - -def ref_rcp_f32(x_bits: int) -> int: - """RDNA2 v_rcp_f32 reference oracle: D.f32 = 1.0 / S0.f32.""" - if is_f32_nan_bits(x_bits): - return QNAN - val = bits_to_f32(x_bits) - if val == 0.0: - return NEG_INF if (x_bits & 0x80000000) else POS_INF - if math.isinf(val): - return NEG_ZERO if val < 0 else POS_ZERO - res = 1.0 / val - return f32_to_bits(res) - - -def ref_rsq_f32(x_bits: int) -> int: - """RDNA2 v_rsq_f32 reference oracle: D.f32 = 1.0 / sqrt(S0.f32).""" - if is_f32_nan_bits(x_bits): - return QNAN - val = bits_to_f32(x_bits) - if val < 0.0: - return QNAN - if val == 0.0: - return POS_INF - if math.isinf(val): - return POS_ZERO - res = 1.0 / math.sqrt(val) - return f32_to_bits(res) - - -def ref_sqrt_f32(x_bits: int) -> int: - """RDNA2 v_sqrt_f32 reference oracle: D.f32 = sqrt(S0.f32).""" - if is_f32_nan_bits(x_bits): - return QNAN - val = bits_to_f32(x_bits) - if val < 0.0: - return QNAN - if val == 0.0: - return x_bits # preserves signed -0.0 - if math.isinf(val): - return POS_INF - res = math.sqrt(val) - return f32_to_bits(res) - - -class Rdna2ValuSimdInterpreter: - """Software model of RDNA2 Vector ALU SIMD execution with EXEC mask divergence. - - Simulates a wavefront (32 lanes for Wave32, 64 lanes for Wave64), tracking: - - Vector registers v0..v63 per lane - - Scalar registers s0..s15 - - 64-bit EXEC mask (exec_lo, exec_hi) - - Per-lane divergence: vector instructions execute only on active lanes where - ((exec >> lane) & 1) != 0. Inactive lanes strictly retain their previous register state. - """ - - def __init__(self, wave_size: int = 32): - if wave_size not in (32, 64): - raise ValueError(f"Unsupported wave_size {wave_size}; must be 32 or 64") - self.wave_size = wave_size - self.exec_mask = (1 << wave_size) - 1 - self.vgprs = [[SENTINEL_FILL] * 64 for _ in range(wave_size)] - self.sgprs = [0] * 16 - - def set_exec(self, mask: int): - self.exec_mask = mask & ((1 << self.wave_size) - 1) - - def parse_reg(self, token: str) -> tuple[str, int]: - token = token.strip().rstrip(",") - if token.startswith("v") and token[1:].isdigit(): - return ("v", int(token[1:])) - if token.startswith("s") and token[1:].isdigit(): - return ("s", int(token[1:])) - if token == "exec": - return ("exec", 0) - if token == "exec_lo": - return ("exec_lo", 0) - if token == "exec_hi": - return ("exec_hi", 0) - return ("imm", int(token, 0)) - - def get_src_lane(self, token: str, lane: int) -> int: - kind, idx = self.parse_reg(token) - if kind == "v": - return self.vgprs[lane][idx] - if kind == "s": - return self.sgprs[idx] - if kind == "imm": - return idx & MASK32 - raise ValueError(f"Unknown src token: {token}") - - def execute_line(self, line: str): - line = line.split(";")[0].strip() - if not line or line.startswith("//"): - return - parts = line.replace(",", " ").split() - op = parts[0] - args = parts[1:] - - if op == "s_mov_b32": - dst_kind, dst_idx = self.parse_reg(args[0]) - val = self.get_src_lane(args[1], 0) - if dst_kind == "s": - self.sgprs[dst_idx] = val & MASK32 - elif dst_kind == "exec_lo": - self.exec_mask = (self.exec_mask & 0xFFFFFFFF00000000) | (val & MASK32) - elif dst_kind == "exec_hi": - self.exec_mask = (self.exec_mask & 0x00000000FFFFFFFF) | ((val & MASK32) << 32) - elif op == "s_mov_b64": - dst_kind, dst_idx = self.parse_reg(args[0]) - src_kind, src_idx = self.parse_reg(args[1]) - if src_kind == "imm": - val = src_idx & MASK64 - elif src_kind == "s": - val = (self.sgprs[src_idx] & MASK32) | ((self.sgprs[src_idx + 1] & MASK32) << 32) - elif src_kind == "exec": - val = self.exec_mask - else: - val = 0 - if dst_kind == "exec": - self.set_exec(val) - elif dst_kind == "s": - self.sgprs[dst_idx] = val & MASK32 - self.sgprs[dst_idx + 1] = (val >> 32) & MASK32 - elif op == "s_not_b64": - dst_kind, dst_idx = self.parse_reg(args[0]) - src_kind, _ = self.parse_reg(args[1]) - val = ~self.exec_mask if src_kind == "exec" else ~0 - if dst_kind == "exec": - self.set_exec(val) - elif op == "s_and_b64": - dst_kind, _ = self.parse_reg(args[0]) - src0_kind, src0_val = self.parse_reg(args[1]) - src1_kind, src1_val = self.parse_reg(args[2]) - v0 = self.exec_mask if src0_kind == "exec" else src0_val - v1 = self.exec_mask if src1_kind == "exec" else src1_val - res = v0 & v1 - if dst_kind == "exec": - self.set_exec(res) - elif op in ("v_mov_b32", "v_cos_f32", "v_sin_f32", "v_rcp_f32", "v_rsq_f32", "v_sqrt_f32"): - dst_kind, dst_idx = self.parse_reg(args[0]) - if dst_kind != "v": - raise ValueError(f"Vector instruction destination must be a VGPR: {line}") - for lane in range(self.wave_size): - if not ((self.exec_mask >> lane) & 1): - continue - src_val = self.get_src_lane(args[1], lane) - if op == "v_mov_b32": - out_val = src_val - elif op == "v_cos_f32": - out_val = ref_cos_f32(src_val) - elif op == "v_sin_f32": - out_val = ref_sin_f32(src_val) - elif op == "v_rcp_f32": - out_val = ref_rcp_f32(src_val) - elif op == "v_rsq_f32": - out_val = ref_rsq_f32(src_val) - elif op == "v_sqrt_f32": - out_val = ref_sqrt_f32(src_val) - self.vgprs[lane][dst_idx] = out_val & MASK32 - - def run_program(self, lines: list[str]): - for line in lines: - self.execute_line(line) - - -class TestTranscendentalOracles(unittest.TestCase): - """Test suite validating the RDNA2 transcendental reference oracles.""" - - def test_cos_cardinal_angles(self): - # 0 turns = 0 rad -> cos = 1.0 - self.assertEqual(ref_cos_f32(POS_ZERO), ONE) - self.assertEqual(ref_cos_f32(NEG_ZERO), ONE) - # 0.25 turns = pi/2 rad -> cos = 0.0 - c025 = bits_to_f32(ref_cos_f32(f32_to_bits(0.25))) - self.assertAlmostEqual(c025, 0.0, places=6) - # 0.5 turns = pi rad -> cos = -1.0 - c05 = bits_to_f32(ref_cos_f32(f32_to_bits(0.5))) - self.assertAlmostEqual(c05, -1.0, places=6) - # 0.75 turns = 3pi/2 rad -> cos = 0.0 - c075 = bits_to_f32(ref_cos_f32(f32_to_bits(0.75))) - self.assertAlmostEqual(c075, 0.0, places=6) - # 1.0 turns = 2pi rad -> cos = 1.0 - c10 = bits_to_f32(ref_cos_f32(f32_to_bits(1.0))) - self.assertAlmostEqual(c10, 1.0, places=6) - - def test_sin_cardinal_angles(self): - # 0.0 turns -> sin = 0.0; -0.0 turns -> sin = -0.0 - self.assertEqual(ref_sin_f32(POS_ZERO), POS_ZERO) - self.assertEqual(ref_sin_f32(NEG_ZERO), NEG_ZERO) - # 0.25 turns = pi/2 rad -> sin = 1.0 - s025 = bits_to_f32(ref_sin_f32(f32_to_bits(0.25))) - self.assertAlmostEqual(s025, 1.0, places=6) - # 0.5 turns = pi rad -> sin = 0.0 - s05 = bits_to_f32(ref_sin_f32(f32_to_bits(0.5))) - self.assertAlmostEqual(s05, 0.0, places=6) - # 0.75 turns = 3pi/2 rad -> sin = -1.0 - s075 = bits_to_f32(ref_sin_f32(f32_to_bits(0.75))) - self.assertAlmostEqual(s075, -1.0, places=6) - # 1.0 turns = 2pi rad -> sin = 0.0 - s10 = bits_to_f32(ref_sin_f32(f32_to_bits(1.0))) - self.assertAlmostEqual(s10, 0.0, places=6) - - def test_pythagorean_identity(self): - # sin^2(x) + cos^2(x) == 1.0 across continuous spectrum of angles - for i in range(-50, 51): - turns = i * 0.125 + 0.03125 - t_bits = f32_to_bits(turns) - s = bits_to_f32(ref_sin_f32(t_bits)) - c = bits_to_f32(ref_cos_f32(t_bits)) - pyth = s * s + c * c - self.assertAlmostEqual(pyth, 1.0, delta=1e-5, msg=f"Pythagorean identity failed at turns={turns}") - - def test_turn_periodicity_and_symmetry(self): - # Invariance under whole integer turn offsets: f(x + k) == f(x) - dyadic_angles = [0.125, 0.25, 0.375, 0.625, 0.875] - for a in dyadic_angles: - for k in (1, 2, 5, 10, 50, 100): - base_c = bits_to_f32(ref_cos_f32(f32_to_bits(a))) - shift_c = bits_to_f32(ref_cos_f32(f32_to_bits(a + float(k)))) - self.assertAlmostEqual(base_c, shift_c, delta=1e-5) - - base_s = bits_to_f32(ref_sin_f32(f32_to_bits(a))) - shift_s = bits_to_f32(ref_sin_f32(f32_to_bits(a + float(k)))) - self.assertAlmostEqual(base_s, shift_s, delta=1e-5) - - # Symmetry: cos(-x) == cos(x), sin(-x) == -sin(x) - angles = [0.1, 0.23, 0.45, 0.67, 0.89] - for a in angles: - pos_bits = f32_to_bits(a) - neg_bits = f32_to_bits(-a) - self.assertAlmostEqual(bits_to_f32(ref_cos_f32(pos_bits)), bits_to_f32(ref_cos_f32(neg_bits)), delta=1e-6) - self.assertAlmostEqual(bits_to_f32(ref_sin_f32(pos_bits)), -bits_to_f32(ref_sin_f32(neg_bits)), delta=1e-6) - - -class TestReciprocalAndRsqOracles(unittest.TestCase): - """Test suite validating v_rcp_f32, v_rsq_f32, and v_sqrt_f32 reference oracles.""" - - def test_rcp_exact_powers_of_two(self): - cases = [ - (1.0, 1.0), - (2.0, 0.5), - (4.0, 0.25), - (8.0, 0.125), - (0.5, 2.0), - (0.25, 4.0), - (0.125, 8.0), - (-2.0, -0.5), - (-0.25, -4.0), - ] - for inp, expected in cases: - got_bits = ref_rcp_f32(f32_to_bits(inp)) - self.assertEqual(got_bits, f32_to_bits(expected)) - - def test_rsq_exact_values(self): - cases = [ - (1.0, 1.0), - (4.0, 0.5), - (16.0, 0.25), - (64.0, 0.125), - (0.25, 2.0), - (0.0625, 4.0), - ] - for inp, expected in cases: - got_bits = ref_rsq_f32(f32_to_bits(inp)) - self.assertEqual(got_bits, f32_to_bits(expected)) - - def test_sqrt_exact_values(self): - cases = [ - (1.0, 1.0), - (4.0, 2.0), - (9.0, 3.0), - (16.0, 4.0), - (0.25, 0.5), - (0.0, 0.0), - ] - for inp, expected in cases: - got_bits = ref_sqrt_f32(f32_to_bits(inp)) - self.assertEqual(got_bits, f32_to_bits(expected)) - - def test_reciprocal_identity(self): - # x * rcp(x) ~= 1.0 for positive normal floats - for i in range(1, 100): - val = i * 0.375 + 0.125 - r = bits_to_f32(ref_rcp_f32(f32_to_bits(val))) - product = val * r - self.assertAlmostEqual(product, 1.0, delta=1e-5, msg=f"Reciprocal identity failed at {val}") - - def test_inverse_sqrt_identity(self): - # x * (rsq(x))^2 ~= 1.0 for positive normal floats - for i in range(1, 100): - val = i * 0.5 + 0.25 - rsq = bits_to_f32(ref_rsq_f32(f32_to_bits(val))) - identity = val * (rsq * rsq) - self.assertAlmostEqual(identity, 1.0, delta=1e-5, msg=f"Inverse sqrt identity failed at {val}") - - def test_sqrt_rsq_duality(self): - # rsq(x) * sqrt(x) ~= 1.0 - for i in range(1, 100): - val = i * 1.25 + 0.5 - rsq = bits_to_f32(ref_rsq_f32(f32_to_bits(val))) - sq = bits_to_f32(ref_sqrt_f32(f32_to_bits(val))) - product = rsq * sq - self.assertAlmostEqual(product, 1.0, delta=1e-5, msg=f"Sqrt/Rsq duality failed at {val}") - - -class TestSimdWaveInterpreterDivergence(unittest.TestCase): - """Test suite validating multi-lane SIMD divergence under EXEC mask.""" - - def test_wave32_checkerboard_divergence_rcp_rsq(self): - # 32-lane Wave32 with checkerboard active masks - interp = Rdna2ValuSimdInterpreter(wave_size=32) - - # Initialize v0 per lane with distinct inputs: (lane + 1) * 2.0 - for lane in range(32): - val = float((lane + 1) * 2) - interp.vgprs[lane][0] = f32_to_bits(val) - interp.vgprs[lane][1] = SENTINEL_FILL - - # Phase 1: Activate even lanes only (0x55555555) and compute v_rcp_f32 - interp.run_program([ - "s_mov_b32 exec_lo, 0x55555555", - "v_rcp_f32 v1, v0", - ]) - - for lane in range(32): - if lane % 2 == 0: - expected = ref_rcp_f32(interp.vgprs[lane][0]) - self.assertEqual(interp.vgprs[lane][1], expected, f"Even lane {lane} failed rcp") - else: - self.assertEqual(interp.vgprs[lane][1], SENTINEL_FILL, f"Odd lane {lane} was improperly modified") - - # Phase 2: Invert mask to odd lanes only (0xAAAAAAAA) and compute v_rsq_f32 - interp.run_program([ - "s_mov_b32 exec_lo, 0xAAAAAAAA", - "v_rsq_f32 v1, v0", - ]) - - for lane in range(32): - if lane % 2 == 1: - expected = ref_rsq_f32(interp.vgprs[lane][0]) - self.assertEqual(interp.vgprs[lane][1], expected, f"Odd lane {lane} failed rsq") - else: - # Even lanes should still hold their previous rcp result! - expected = ref_rcp_f32(interp.vgprs[lane][0]) - self.assertEqual(interp.vgprs[lane][1], expected, f"Even lane {lane} lost previous value") - - def test_wave64_halves_divergence_rcp_sqrt(self): - # 64-lane Wave64 split into low half (0..31) and high half (32..63) - interp = Rdna2ValuSimdInterpreter(wave_size=64) - - for lane in range(64): - val = float(lane + 4) - interp.vgprs[lane][0] = f32_to_bits(val) - interp.vgprs[lane][2] = SENTINEL_FILL - - # Activate lower half (0x00000000FFFFFFFF): compute v_rcp_f32 into v2 - interp.run_program([ - "s_mov_b64 exec, 0x00000000FFFFFFFF", - "v_rcp_f32 v2, v0", - ]) - - for lane in range(32): - expected = ref_rcp_f32(interp.vgprs[lane][0]) - self.assertEqual(interp.vgprs[lane][2], expected, f"Lower lane {lane} failed rcp") - for lane in range(32, 64): - self.assertEqual(interp.vgprs[lane][2], SENTINEL_FILL, f"Upper lane {lane} was modified") - - # Activate upper half (0xFFFFFFFF00000000): compute v_sqrt_f32 into v2 - interp.run_program([ - "s_mov_b64 exec, 0xFFFFFFFF00000000", - "v_sqrt_f32 v2, v0", - ]) - - for lane in range(32): - expected = ref_rcp_f32(interp.vgprs[lane][0]) - self.assertEqual(interp.vgprs[lane][2], expected, f"Lower lane {lane} was overwritten") - for lane in range(32, 64): - expected = ref_sqrt_f32(interp.vgprs[lane][0]) - self.assertEqual(interp.vgprs[lane][2], expected, f"Upper lane {lane} failed sqrt") - - -class TestTrigTranslationAndExecution(unittest.TestCase): - """End-to-end translation and execution of v_cos_f32 and v_sin_f32.""" - - def test_v_cos_and_v_sin_pixel_shader_execution(self): - test_turns = [0.0, 0.25, 0.5, 0.75] - for t in test_turns: - tb = f32_to_bits(t) - lines = [ - f"v_mov_b32 v0, 0x{tb:08x}", - "v_cos_f32 v1, v0", - "v_sin_f32 v2, v0", - "exp mrt0 v1, v2, v0, v0 done vm", - "s_endpgm", - ] - spv = support.translate_lines(f"ps_trig_{tb:08x}", lines) - words = support.mrt0_words(spv) - got_cos = bits_to_f32(words[0]) - got_sin = bits_to_f32(words[1]) - expected_cos = bits_to_f32(ref_cos_f32(tb)) - expected_sin = bits_to_f32(ref_sin_f32(tb)) - self.assertAlmostEqual(got_cos, expected_cos, delta=1e-5) - self.assertAlmostEqual(got_sin, expected_sin, delta=1e-5) - - def test_large_turns_reduction_in_shader(self): - for large_turn in (100.3, 254.51): - tb = f32_to_bits(large_turn) - lines = [ - f"v_mov_b32 v0, 0x{tb:08x}", - "v_sin_f32 v1, v0", - "v_cos_f32 v2, v0", - "exp mrt0 v1, v2, v0, v0 done vm", - "s_endpgm", - ] - spv = support.translate_lines(f"ps_large_trig_{tb:08x}", lines) - words = support.mrt0_words(spv) - got_sin = bits_to_f32(words[0]) - got_cos = bits_to_f32(words[1]) - expected_sin = bits_to_f32(ref_sin_f32(tb)) - expected_cos = bits_to_f32(ref_cos_f32(tb)) - self.assertAlmostEqual(got_sin, expected_sin, delta=1e-5) - self.assertAlmostEqual(got_cos, expected_cos, delta=1e-5) - - -class TestRcpRsqShaderExecution(unittest.TestCase): - """End-to-end pixel shader execution for reciprocal and inverse square root.""" - - def test_rcp_and_rsq_powers_of_two_shader(self): - test_values = [1.0, 2.0, 4.0, 16.0, 0.25] - for val in test_values: - vb = f32_to_bits(val) - lines = [ - f"v_mov_b32 v0, 0x{vb:08x}", - "v_rcp_f32 v1, v0", - "v_rsq_f32 v2, v0", - "v_sqrt_f32 v3, v0", - "exp mrt0 v1, v2, v3, v0 done vm", - "s_endpgm", - ] - spv = support.translate_lines(f"ps_rcp_rsq_{vb:08x}", lines) - words = support.mrt0_words(spv) - self.assertEqual(words[0], ref_rcp_f32(vb)) - self.assertEqual(words[1], ref_rsq_f32(vb)) - self.assertEqual(words[2], ref_sqrt_f32(vb)) - - -class TestSpecialFloatBoundaries(unittest.TestCase): - """Test suite validating special float values: zeros, infinities, subnormals, and NaNs.""" - - def test_rcp_special_values(self): - # rcp(+-0.0) = +-inf - self.assertEqual(ref_rcp_f32(POS_ZERO), POS_INF) - self.assertEqual(ref_rcp_f32(NEG_ZERO), NEG_INF) - # rcp(+-inf) = +-0.0 - self.assertEqual(ref_rcp_f32(POS_INF), POS_ZERO) - self.assertEqual(ref_rcp_f32(NEG_INF), NEG_ZERO) - - def test_rsq_special_values(self): - # rsq(+0.0) = +inf - self.assertEqual(ref_rsq_f32(POS_ZERO), POS_INF) - # rsq(-x) = qNaN for x > 0 - self.assertTrue(is_f32_nan_bits(ref_rsq_f32(NEG_ONE))) - self.assertTrue(is_f32_nan_bits(ref_rsq_f32(NEG_TWO))) - # rsq(+inf) = +0.0 - self.assertEqual(ref_rsq_f32(POS_INF), POS_ZERO) - # rsq(-inf) = qNaN - self.assertTrue(is_f32_nan_bits(ref_rsq_f32(NEG_INF))) - - def test_sqrt_special_values(self): - # sqrt(+0.0) = +0.0, sqrt(-0.0) = -0.0 - self.assertEqual(ref_sqrt_f32(POS_ZERO), POS_ZERO) - self.assertEqual(ref_sqrt_f32(NEG_ZERO), NEG_ZERO) - # sqrt(-x) = qNaN for x > 0 - self.assertTrue(is_f32_nan_bits(ref_sqrt_f32(NEG_ONE))) - self.assertTrue(is_f32_nan_bits(ref_sqrt_f32(NEG_TWO))) - # sqrt(+inf) = +inf, sqrt(-inf) = qNaN - self.assertEqual(ref_sqrt_f32(POS_INF), POS_INF) - self.assertTrue(is_f32_nan_bits(ref_sqrt_f32(NEG_INF))) - - def test_trig_special_values(self): - # cos(+-0.0) = 1.0 - self.assertEqual(ref_cos_f32(POS_ZERO), ONE) - self.assertEqual(ref_cos_f32(NEG_ZERO), ONE) - # sin(+0.0) = +0.0, sin(-0.0) = -0.0 - self.assertEqual(ref_sin_f32(POS_ZERO), POS_ZERO) - self.assertEqual(ref_sin_f32(NEG_ZERO), NEG_ZERO) - # cos(+-inf) = qNaN, sin(+-inf) = qNaN - self.assertTrue(is_f32_nan_bits(ref_cos_f32(POS_INF))) - self.assertTrue(is_f32_nan_bits(ref_cos_f32(NEG_INF))) - self.assertTrue(is_f32_nan_bits(ref_sin_f32(POS_INF))) - self.assertTrue(is_f32_nan_bits(ref_sin_f32(NEG_INF))) - - def test_nan_propagation(self): - # Both qNaN and sNaN must produce a NaN result across all operations - for nan_input in (QNAN, NEG_QNAN, SNAN): - self.assertTrue(is_f32_nan_bits(ref_cos_f32(nan_input)), f"cos({nan_input:#x}) not NaN") - self.assertTrue(is_f32_nan_bits(ref_sin_f32(nan_input)), f"sin({nan_input:#x}) not NaN") - self.assertTrue(is_f32_nan_bits(ref_rcp_f32(nan_input)), f"rcp({nan_input:#x}) not NaN") - self.assertTrue(is_f32_nan_bits(ref_rsq_f32(nan_input)), f"rsq({nan_input:#x}) not NaN") - self.assertTrue(is_f32_nan_bits(ref_sqrt_f32(nan_input)), f"sqrt({nan_input:#x}) not NaN") - - def test_subnormal_boundaries(self): - # Reciprocal of tiny subnormals overflows to infinity (2^149 > 2^128) - self.assertEqual(ref_rcp_f32(SUBNORM_MIN), POS_INF) - self.assertEqual(ref_rcp_f32(NEG_SUBNORM_MIN), NEG_INF) - # Inverse sqrt of subnormal min: 1 / sqrt(2^-149) = 2^74.5 fits in f32 normal range - rsq_subnorm = ref_rsq_f32(SUBNORM_MIN) - self.assertFalse(is_f32_nan_bits(rsq_subnorm)) - self.assertNotEqual(rsq_subnorm, POS_INF) - self.assertAlmostEqual(bits_to_f32(rsq_subnorm), 1.0 / math.sqrt(bits_to_f32(SUBNORM_MIN)), delta=1e16) - # Smallest normal float: 1 / 2^-126 = 2^126 (fits in f32) - rcp_flt_min = ref_rcp_f32(FLT_MIN) - self.assertFalse(is_f32_nan_bits(rcp_flt_min)) - self.assertNotEqual(rcp_flt_min, POS_INF) - self.assertAlmostEqual(bits_to_f32(rcp_flt_min), 2.0 ** 126, delta=1e20) - - -class TestNegativeControlsAndFaults(unittest.TestCase): - """Test suite validating negative controls, fault handling, and unsupported constructs.""" - - def test_spirv_unsupported_rcp_zero(self): - # In SPIR-V / spirv_mini_interp, OpFDiv by zero raises UnsupportedConstruct - for zero_word in (POS_ZERO, NEG_ZERO): - lines = [ - f"v_mov_b32 v0, 0x{zero_word:08x}", - "v_rcp_f32 v1, v0", - "exp mrt0 v1, v0, v0, v0 done vm", - "s_endpgm", - ] - spv = support.translate_lines(f"ps_rcp_zero_{zero_word:08x}", lines) - with self.assertRaises(si.UnsupportedConstruct): - support.mrt0_words(spv) - - def test_spirv_unsupported_rsq_zero_or_negative(self): - # In GLSL.std.450 / spirv_mini_interp, InverseSqrt of <= 0 raises UnsupportedConstruct - for bad_val in (POS_ZERO, NEG_ZERO, NEG_ONE): - lines = [ - f"v_mov_b32 v0, 0x{bad_val:08x}", - "v_rsq_f32 v1, v0", - "exp mrt0 v1, v0, v0, v0 done vm", - "s_endpgm", - ] - spv = support.translate_lines(f"ps_rsq_bad_{bad_val:08x}", lines) - with self.assertRaises(si.UnsupportedConstruct): - support.mrt0_words(spv) - - def test_simd_interpreter_fault_rejection(self): - # Disallow unsupported wave sizes - with self.assertRaises(ValueError): - Rdna2ValuSimdInterpreter(wave_size=16) - with self.assertRaises(ValueError): - Rdna2ValuSimdInterpreter(wave_size=128) - - # Disallow vector destination to a scalar register - interp = Rdna2ValuSimdInterpreter(wave_size=32) - with self.assertRaises(ValueError): - interp.execute_line("v_rcp_f32 s0, v0") - - # Disallow unknown token syntax - with self.assertRaises(ValueError): - interp.execute_line("v_mov_b32 v0, invalid_token_xyz") - - def test_negative_control_oracle_assertions(self): - # Sanity check: assert that intentionally mutated values fail - with self.assertRaises(AssertionError): - self.assertEqual(ref_rcp_f32(f32_to_bits(2.0)), f32_to_bits(0.25)) - - with self.assertRaises(AssertionError): - self.assertEqual(ref_rsq_f32(f32_to_bits(4.0)), f32_to_bits(2.0)) - - with self.assertRaises(AssertionError): - self.assertEqual(ref_cos_f32(POS_ZERO), NEG_ONE) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_valu_trig_f64.py b/tests/semantic/test_valu_trig_f64.py deleted file mode 100644 index 0448eab04..000000000 --- a/tests/semantic/test_valu_trig_f64.py +++ /dev/null @@ -1,1507 +0,0 @@ -"""Semantic reference tests and mathematical oracle for AMD RDNA2 v_trig_f64. - -RDNA2 Vector Arithmetic Logic Unit (VALU) Architecture: - In AMD RDNA2 (GFX10/GFX1030) ISA, vector registers (VGPRs) are 32 bits wide. - Operations on 64-bit double-precision floating-point quantities (binary64, IEEE 754) - operate across aligned pairs of adjacent registers: v[d:d+1] from source operand - v[s0:s0+1] (or scalar SGPR pair s[k:k+1], literal 64-bit constants, or inline constants). - - Instruction: - v_trig_f64 v[d:d+1], src0 [clamp] - (with trigonometric function / argument evaluation in units of 2*pi revolutions / turns) - - Mathematical Specification: - 1. Angle Domain: - Input src0 is specified in cycles / revolutions (turns), where 1.0 turn = 2*pi radians. - The hardware reduces the input argument modulo 1.0 to the fundamental domain [-0.5, 0.5] - using IEEE roundTiesToEven: - reduced_turns = turns - round_even(turns) - This exact range reduction ensures zero transcendental error drift across multi-turn rotations. - 2. Primary Evaluation: - The primary trigonometric function evaluates: - radians = reduced_turns * 2*pi - D.f64 = sin(radians) (or cos(radians) in dual / cos-mode) - 3. IEEE 754 & RDNA2 Rules: - - Signed Zero: - sin(+0.0) = +0.0, sin(-0.0) = -0.0 - cos(+0.0) = 1.0, cos(-0.0) = 1.0 - - Infinities: - sin(+-inf) = Canonical QNaN - cos(+-inf) = Canonical QNaN - - NaNs: - NaN operands are quieted and propagated as Canonical Quiet NaNs. - - Subnormals: - Denormal / subnormal inputs are preserved without flushing in IEEE compliance mode. - - Cardinal Angles (in turns): - turns = 0.00 -> sin = 0.0, cos = 1.0 - turns = 0.25 -> sin = 1.0, cos = 0.0 (pi/2 rad) - turns = 0.50 -> sin = 0.0, cos = -1.0 (pi rad) - turns = 0.75 -> sin = -1.0, cos = 0.0 (3*pi/2 rad) - - VOP3 Input Modifiers: - abs (|x|) clears sign bit 63. - neg (-x) toggles sign bit 63. - neg(abs(x)) forces the sign bit to 1 (negative). - - Output Clamp: - clamp forces result into [0.0, 1.0]. Negative results or -0.0 clamp to +0.0. - In RDNA2 VALU, clamping NaN yields +0.0. - -Standard library only: Python 3.9+ compatible, zero game data, zero external dependencies. -""" -from __future__ import annotations - -import abc -from dataclasses import dataclass -import enum -import math -import struct -import unittest - -MASK32: int = 0xFFFFFFFF -MASK64: int = 0xFFFFFFFFFFFFFFFF -TWO_PI: float = 6.283185307179586476925286766559 - -# IEEE-754 binary64 bit constants -F64_POS_ZERO: int = 0x0000000000000000 -F64_NEG_ZERO: int = 0x8000000000000000 -F64_POS_INF: int = 0x7FF0000000000000 -F64_NEG_INF: int = 0xFFF0000000000000 -F64_CANONICAL_QNAN: int = 0x7FF8000000000000 -F64_QUIET_BIT: int = 0x0008000000000000 - -F64_EXP_MASK: int = 0x7FF0000000000000 -F64_MANT_MASK: int = 0x000FFFFFFFFFFFFF -F64_SIGN_MASK: int = 0x8000000000000000 - -F64_ONE: int = 0x3FF0000000000000 # 1.0 -F64_NEG_ONE: int = 0xBFF0000000000000 # -1.0 -F64_TWO: int = 0x4000000000000000 # 2.0 -F64_HALF: int = 0x3FE0000000000000 # 0.5 -F64_QUARTER: int = 0x3FD0000000000000 # 0.25 (1/4 turn = 90 deg = pi/2 rad) -F64_NEG_QUARTER: int = 0xBFD0000000000000 # -0.25 (-1/4 turn = -90 deg = -pi/2 rad) -F64_THREE_QUARTERS: int = 0x3FE8000000000000 # 0.75 (3/4 turn = 270 deg = 3*pi/2 rad) - -F64_MIN_NORMAL: int = 0x0010000000000000 # 2^-1022 -F64_MAX_NORMAL: int = 0x7FEFFFFFFFFFFFFF # (2 - 2^-52) * 2^1023 -F64_MIN_SUBNORMAL: int = 0x0000000000000001 # 2^-1074 -F64_MAX_SUBNORMAL: int = 0x000FFFFFFFFFFFFF - -OLD_VGPR_SENTINEL: int = 0xDEADBEEF - - -class TrigMode(enum.Enum): - SIN = 0 - COS = 1 - - -def u32(val: int) -> int: - """Normalize integer to unsigned 32-bit range [0, 2^32 - 1].""" - return val & MASK32 - - -def u64(val: int) -> int: - """Normalize integer to unsigned 64-bit range [0, 2^64 - 1].""" - return val & MASK64 - - -def split_dwords(val64: int) -> tuple[int, int]: - """Split an unsigned 64-bit integer into (low_dword, high_dword).""" - val = val64 & MASK64 - return val & MASK32, (val >> 32) & MASK32 - - -def join_dwords(lo: int, hi: int) -> int: - """Join (low_dword, high_dword) into an unsigned 64-bit integer.""" - return ((hi & MASK32) << 32) | (lo & MASK32) - - -def f64_to_u64(val: float) -> int: - """Pack an IEEE-754 double precision float into an unsigned 64-bit integer.""" - try: - return struct.unpack(" float: - """Unpack an unsigned 64-bit integer into an IEEE-754 double precision float.""" - return struct.unpack(" bool: - """Return True if the 64-bit pattern represents an IEEE-754 NaN.""" - return ((bits & F64_EXP_MASK) == F64_EXP_MASK) and ((bits & F64_MANT_MASK) != 0) - - -def is_f64_snan(bits: int) -> bool: - """Return True if the 64-bit pattern represents a signaling NaN.""" - return is_f64_nan(bits) and ((bits & F64_QUIET_BIT) == 0) - - -def is_f64_qnan(bits: int) -> bool: - """Return True if the 64-bit pattern represents a quiet NaN.""" - return is_f64_nan(bits) and ((bits & F64_QUIET_BIT) != 0) - - -def is_f64_zero(bits: int) -> bool: - """Return True if the 64-bit pattern represents +0.0 or -0.0.""" - return (bits & (F64_EXP_MASK | F64_MANT_MASK)) == 0 - - -def is_f64_inf(bits: int) -> bool: - """Return True if the 64-bit pattern represents +inf or -inf.""" - return ((bits & F64_EXP_MASK) == F64_EXP_MASK) and ((bits & F64_MANT_MASK) == 0) - - -def is_f64_subnormal(bits: int) -> bool: - """Return True if the 64-bit pattern represents a subnormal/denormal float.""" - return ((bits & F64_EXP_MASK) == 0) and ((bits & F64_MANT_MASK) != 0) - - -def is_f64_normal(bits: int) -> bool: - """Return True if the 64-bit pattern represents a normalized finite float.""" - exp = (bits >> 52) & 0x7FF - return 0 < exp < 0x7FF - - -def f64_sign(bits: int) -> int: - """Return the sign bit (0 or 1).""" - return (bits >> 63) & 1 - - -def quiet_f64(bits: int) -> int: - """Force an IEEE-754 double NaN to quiet by setting the quiet bit.""" - return (bits & MASK64) | F64_QUIET_BIT - - -def round_even(x: float) -> float: - """Round float to nearest integer, breaking ties to even.""" - return float(round(x)) - - -def ref_turn_reduce_f64(turns: float) -> float: - """Reduce turn count to [-0.5, 0.5] turns using roundTiesToEven.""" - if math.isnan(turns) or math.isinf(turns): - return float("nan") - if turns == 0.0: - return turns - return turns - round_even(turns) - - -def apply_input_modifiers_f64(bits: int, *, neg: bool = False, abs_val: bool = False) -> int: - """Apply VOP3 input modifiers (abs, neg). - - In RDNA2 ISA: - When both abs and neg are set, abs is evaluated before neg: - i.e. neg(abs(x)) forces the sign bit to 1 (negative). - """ - res = bits & MASK64 - if abs_val: - res &= ~F64_SIGN_MASK - if neg: - res ^= F64_SIGN_MASK - return res - - -def apply_f64_clamp(bits: int) -> int: - """Apply VOP3 clamp modifier [0.0, 1.0]. NaN or negatives clamp to +0.0.""" - if is_f64_nan(bits): - return F64_POS_ZERO - val = u64_to_f64(bits) - if val < 0.0 or is_f64_zero(bits): - return F64_POS_ZERO - elif val > 1.0: - return F64_ONE - return bits & MASK64 - - -def ref_trig_f64( - src0_bits: int, - *, - mode: TrigMode = TrigMode.SIN, - clamp: bool = False, - src0_neg: bool = False, - src0_abs: bool = False, -) -> int: - """Reference mathematical oracle for RDNA2 double-precision v_trig_f64. - - Evaluates: - D.f64 = trig(src0 * 2*pi) - in units of revolutions / turns with exact [-0.5, 0.5] range reduction. - """ - s0 = apply_input_modifiers_f64(src0_bits, neg=src0_neg, abs_val=src0_abs) - - # NaN input produces canonical quiet NaN - if is_f64_nan(s0): - res = quiet_f64(s0) - # Infinities produce canonical quiet NaN - elif is_f64_inf(s0): - res = F64_CANONICAL_QNAN - # Zero input rules - elif is_f64_zero(s0): - if mode == TrigMode.SIN: - res = F64_NEG_ZERO if f64_sign(s0) else F64_POS_ZERO - else: - res = F64_ONE - else: - turns = u64_to_f64(s0) - reduced = ref_turn_reduce_f64(turns) - - if mode == TrigMode.SIN: - if reduced == 0.0: - res = F64_NEG_ZERO if f64_sign(s0) else F64_POS_ZERO - elif reduced == 0.25: - res = F64_ONE - elif reduced == -0.25: - res = F64_NEG_ONE - elif abs(reduced) == 0.5: - res = F64_POS_ZERO - else: - rad = reduced * TWO_PI - res = f64_to_u64(math.sin(rad)) - if is_f64_zero(res): - res = F64_NEG_ZERO if reduced < 0 else F64_POS_ZERO - else: # COS - if reduced == 0.0: - res = F64_ONE - elif abs(reduced) == 0.25: - res = F64_POS_ZERO - elif abs(reduced) == 0.5: - res = F64_NEG_ONE - else: - rad = reduced * TWO_PI - res = f64_to_u64(math.cos(rad)) - - if clamp: - res = apply_f64_clamp(res) - - return res & MASK64 - - -def ref_trig_f64_dwords( - s0_lo: int, - s0_hi: int, - *, - mode: TrigMode = TrigMode.SIN, - clamp: bool = False, - src0_neg: bool = False, - src0_abs: bool = False, -) -> tuple[int, int]: - """Decomposed dword interface for v_trig_f64.""" - s0 = join_dwords(s0_lo, s0_hi) - res = ref_trig_f64( - s0, - mode=mode, - clamp=clamp, - src0_neg=src0_neg, - src0_abs=src0_abs, - ) - return split_dwords(res) - - -class VALURegisterFile: - """Architectural model for RDNA2 VALU 32-bit vector register file.""" - - def __init__(self, num_vgprs: int = 256) -> None: - self.num_vgprs = num_vgprs - self.regs = [0] * num_vgprs - - def get_vgpr(self, idx: int) -> int: - if not (0 <= idx < self.num_vgprs): - raise IndexError(f"VGPR index out of range: {idx}") - return self.regs[idx] & MASK32 - - def set_vgpr(self, idx: int, val: int) -> None: - if not (0 <= idx < self.num_vgprs): - raise IndexError(f"VGPR index out of range: {idx}") - self.regs[idx] = val & MASK32 - - def get_vgpr_pair(self, idx: int) -> int: - if not (0 <= idx < self.num_vgprs - 1): - raise IndexError(f"VGPR pair index out of range: v[{idx}:{idx+1}]") - lo = self.get_vgpr(idx) - hi = self.get_vgpr(idx + 1) - return join_dwords(lo, hi) - - def set_vgpr_pair(self, idx: int, val64: int) -> None: - if not (0 <= idx < self.num_vgprs - 1): - raise IndexError(f"VGPR pair index out of range: v[{idx}:{idx+1}]") - lo, hi = split_dwords(val64) - self.set_vgpr(idx, lo) - self.set_vgpr(idx + 1, hi) - - -class TestVTrigF64ReferenceOracle(unittest.TestCase): - """Test suite for reference mathematical oracle and architectural model.""" - - def test_cardinal_angles_sin(self) -> None: - # 0.0 turn -> sin(0) = 0.0 - self.assertEqual(ref_trig_f64(F64_POS_ZERO, mode=TrigMode.SIN), F64_POS_ZERO) - # 0.25 turn -> sin(pi/2) = 1.0 - self.assertEqual(ref_trig_f64(F64_QUARTER, mode=TrigMode.SIN), F64_ONE) - # 0.50 turn -> sin(pi) = 0.0 - self.assertEqual(ref_trig_f64(F64_HALF, mode=TrigMode.SIN), F64_POS_ZERO) - # 0.75 turn -> sin(3*pi/2) = -1.0 - self.assertEqual(ref_trig_f64(F64_THREE_QUARTERS, mode=TrigMode.SIN), F64_NEG_ONE) - # 1.00 turn -> sin(2*pi) = 0.0 - self.assertEqual(ref_trig_f64(F64_ONE, mode=TrigMode.SIN), F64_POS_ZERO) - - def test_cardinal_angles_cos(self) -> None: - # 0.0 turn -> cos(0) = 1.0 - self.assertEqual(ref_trig_f64(F64_POS_ZERO, mode=TrigMode.COS), F64_ONE) - # 0.25 turn -> cos(pi/2) = 0.0 - self.assertEqual(ref_trig_f64(F64_QUARTER, mode=TrigMode.COS), F64_POS_ZERO) - # 0.50 turn -> cos(pi) = -1.0 - self.assertEqual(ref_trig_f64(F64_HALF, mode=TrigMode.COS), F64_NEG_ONE) - # 0.75 turn -> cos(3*pi/2) = 0.0 - self.assertEqual(ref_trig_f64(F64_THREE_QUARTERS, mode=TrigMode.COS), F64_POS_ZERO) - # 1.00 turn -> cos(2*pi) = 1.0 - self.assertEqual(ref_trig_f64(F64_ONE, mode=TrigMode.COS), F64_ONE) - - def test_signed_zeros(self) -> None: - self.assertEqual(ref_trig_f64(F64_POS_ZERO, mode=TrigMode.SIN), F64_POS_ZERO) - self.assertEqual(ref_trig_f64(F64_NEG_ZERO, mode=TrigMode.SIN), F64_NEG_ZERO) - self.assertEqual(ref_trig_f64(F64_POS_ZERO, mode=TrigMode.COS), F64_ONE) - self.assertEqual(ref_trig_f64(F64_NEG_ZERO, mode=TrigMode.COS), F64_ONE) - - def test_infinities_produce_qnan(self) -> None: - self.assertEqual(ref_trig_f64(F64_POS_INF, mode=TrigMode.SIN), F64_CANONICAL_QNAN) - self.assertEqual(ref_trig_f64(F64_NEG_INF, mode=TrigMode.SIN), F64_CANONICAL_QNAN) - self.assertEqual(ref_trig_f64(F64_POS_INF, mode=TrigMode.COS), F64_CANONICAL_QNAN) - self.assertEqual(ref_trig_f64(F64_NEG_INF, mode=TrigMode.COS), F64_CANONICAL_QNAN) - - def test_nan_propagation(self) -> None: - snan = 0x7FF0000000000001 - res_sin = ref_trig_f64(snan, mode=TrigMode.SIN) - self.assertTrue(is_f64_qnan(res_sin)) - res_cos = ref_trig_f64(snan, mode=TrigMode.COS) - self.assertTrue(is_f64_qnan(res_cos)) - - def test_input_modifiers(self) -> None: - # neg: sin(-0.25 turn) = -1.0; with neg modifier: sin(-(-0.25)) = sin(0.25) = 1.0 - r = ref_trig_f64(F64_NEG_QUARTER, mode=TrigMode.SIN, src0_neg=True) - self.assertEqual(r, F64_ONE) - - # abs: sin(|-0.25|) = sin(0.25) = 1.0 - r = ref_trig_f64(F64_NEG_QUARTER, mode=TrigMode.SIN, src0_abs=True) - self.assertEqual(r, F64_ONE) - - # abs + neg: neg(abs(0.25)) = -0.25 -> sin(-0.25) = -1.0 - r = ref_trig_f64(F64_QUARTER, mode=TrigMode.SIN, src0_abs=True, src0_neg=True) - self.assertEqual(r, F64_NEG_ONE) - - def test_clamp_modifier(self) -> None: - # In range [0.0, 1.0]: sin(0.125 turn) = sin(pi/4) ~= 0.7071 - r = ref_trig_f64(f64_to_u64(0.125), mode=TrigMode.SIN, clamp=True) - self.assertAlmostEqual(u64_to_f64(r), math.sin(math.pi / 4), places=7) - - # Negative clamped to +0.0: sin(-0.25) = -1.0 -> clamped to +0.0 - r = ref_trig_f64(F64_NEG_QUARTER, mode=TrigMode.SIN, clamp=True) - self.assertEqual(r, F64_POS_ZERO) - - # NaN clamped to +0.0 - r = ref_trig_f64(F64_POS_INF, mode=TrigMode.SIN, clamp=True) - self.assertEqual(r, F64_POS_ZERO) - - def test_turn_periodicity(self) -> None: - # Any value x and x + 100.0 turns should yield the exact same result - base_turns = 0.1738294 - for k in (1.0, 10.0, 1000.0, -50.0): - t1 = f64_to_u64(base_turns) - t2 = f64_to_u64(base_turns + k) - self.assertAlmostEqual( - u64_to_f64(ref_trig_f64(t1, mode=TrigMode.SIN)), - u64_to_f64(ref_trig_f64(t2, mode=TrigMode.SIN)), - places=9, - ) - - def test_pythagorean_identity(self) -> None: - # sin^2(x) + cos^2(x) == 1.0 for arbitrary turn values - for angle in (0.05, 0.1337, 0.33333333, -0.42, 12.3456): - bits = f64_to_u64(angle) - s = u64_to_f64(ref_trig_f64(bits, mode=TrigMode.SIN)) - c = u64_to_f64(ref_trig_f64(bits, mode=TrigMode.COS)) - self.assertAlmostEqual(s * s + c * c, 1.0, places=12) - - def test_dword_decomposition(self) -> None: - s0 = f64_to_u64(0.25) - s0_lo, s0_hi = split_dwords(s0) - lo, hi = ref_trig_f64_dwords(s0_lo, s0_hi, mode=TrigMode.SIN) - res64 = join_dwords(lo, hi) - self.assertEqual(res64, F64_ONE) - - def test_register_file_pair_access(self) -> None: - rf = VALURegisterFile(num_vgprs=16) - val = 0x01234567_89ABCDEF - rf.set_vgpr_pair(4, val) - - self.assertEqual(rf.get_vgpr(4), 0x89ABCDEF) - self.assertEqual(rf.get_vgpr(5), 0x01234567) - self.assertEqual(rf.get_vgpr_pair(4), val) - - with self.assertRaises(IndexError): - rf.get_vgpr_pair(15) - - -# ============================================================================== -# Symbolic AST Opcode Definitions and Typed Expressions for v_trig_f64 -# ============================================================================== - -class OperandKind(enum.Enum): - VGPR_PAIR = "vgpr_pair" - SGPR_PAIR = "sgpr_pair" - LITERAL_64 = "literal_64" - INLINE_IMM = "inline_imm" - - -@dataclass -class ASTOperand: - kind: OperandKind - reg_idx: int = 0 - imm_val: int = 0 - neg: bool = False - abs_val: bool = False - - def format_asm(self) -> str: - if self.kind == OperandKind.VGPR_PAIR: - s = f"v[{self.reg_idx}:{self.reg_idx + 1}]" - elif self.kind == OperandKind.SGPR_PAIR: - s = f"s[{self.reg_idx}:{self.reg_idx + 1}]" - elif self.kind == OperandKind.LITERAL_64: - s = f"0x{self.imm_val:016x}" - elif self.kind == OperandKind.INLINE_IMM: - s = f"{self.imm_val}" - else: - s = "unknown" - if self.abs_val: - s = f"|{s}|" - if self.neg: - s = f"-{s}" - return s - - -@dataclass -class ASTInstruction: - opcode: str - dst: ASTOperand - src0: ASTOperand - mode: TrigMode = TrigMode.SIN - clamp: bool = False - omod: int = 0 - - def validate(self) -> None: - if self.opcode != "v_trig_f64": - raise ValueError(f"Invalid opcode for v_trig_f64 AST: {self.opcode}") - if self.dst.kind != OperandKind.VGPR_PAIR: - raise ValueError(f"Destination must be a VGPR pair, got {self.dst.kind}") - if not (0 <= self.dst.reg_idx <= 254): - raise ValueError(f"Destination VGPR pair index out of range: {self.dst.reg_idx}") - if self.dst.neg or self.dst.abs_val: - raise ValueError("Destination operand cannot have neg or abs modifiers") - if self.src0.kind == OperandKind.VGPR_PAIR: - if not (0 <= self.src0.reg_idx <= 254): - raise ValueError(f"src0 VGPR pair index out of range: {self.src0.reg_idx}") - elif self.src0.kind == OperandKind.SGPR_PAIR: - if not (0 <= self.src0.reg_idx <= 104): - raise ValueError(f"src0 SGPR pair index out of range: {self.src0.reg_idx}") - - def format_asm(self) -> str: - s = f"{self.opcode} {self.dst.format_asm()}, {self.src0.format_asm()}" - if self.clamp: - s += " clamp" - return s - - -class F64Expression(abc.ABC): - @abc.abstractmethod - def evaluate(self, env: dict[str, int]) -> int: - pass - - -@dataclass -class F64Constant(F64Expression): - bits: int - - def evaluate(self, env: dict[str, int]) -> int: - return self.bits & MASK64 - - -@dataclass -class F64Variable(F64Expression): - name: str - - def evaluate(self, env: dict[str, int]) -> int: - if self.name not in env: - raise KeyError(f"Variable {self.name} not found in environment") - return env[self.name] & MASK64 - - -@dataclass -class F64UnaryOp(F64Expression): - op: str # "abs", "neg", "neg_abs" - operand: F64Expression - - def evaluate(self, env: dict[str, int]) -> int: - val = self.operand.evaluate(env) - if self.op == "abs": - return apply_input_modifiers_f64(val, abs_val=True) - elif self.op == "neg": - return apply_input_modifiers_f64(val, neg=True) - elif self.op == "neg_abs": - return apply_input_modifiers_f64(val, neg=True, abs_val=True) - raise ValueError(f"Unknown unary operator: {self.op}") - - -@dataclass -class F64Trig(F64Expression): - operand: F64Expression - mode: TrigMode = TrigMode.SIN - clamp: bool = False - - def evaluate(self, env: dict[str, int]) -> int: - val = self.operand.evaluate(env) - return ref_trig_f64(val, mode=self.mode, clamp=self.clamp) - - -def instruction_to_expression(inst: ASTInstruction) -> F64Trig: - """Translate an ASTInstruction to a typed symbolic expression tree.""" - inst.validate() - - op = inst.src0 - if op.kind in (OperandKind.VGPR_PAIR, OperandKind.SGPR_PAIR): - expr: F64Expression = F64Variable(f"src0_{op.reg_idx}") - elif op.kind in (OperandKind.LITERAL_64, OperandKind.INLINE_IMM): - expr = F64Constant(op.imm_val) - else: - raise ValueError(f"Unsupported operand kind: {op.kind}") - - if op.abs_val and op.neg: - expr = F64UnaryOp("neg_abs", expr) - elif op.abs_val: - expr = F64UnaryOp("abs", expr) - elif op.neg: - expr = F64UnaryOp("neg", expr) - - return F64Trig(expr, mode=inst.mode, clamp=inst.clamp) - - -class TestSymbolicAST(unittest.TestCase): - """Test suite for symbolic AST definitions and typed expressions.""" - - def test_ast_creation_and_formatting(self) -> None: - dst = ASTOperand(kind=OperandKind.VGPR_PAIR, reg_idx=0) - src0 = ASTOperand(kind=OperandKind.VGPR_PAIR, reg_idx=2) - inst = ASTInstruction(opcode="v_trig_f64", dst=dst, src0=src0) - inst.validate() - self.assertEqual(inst.format_asm(), "v_trig_f64 v[0:1], v[2:3]") - - # With clamp and modifiers - src0_mod = ASTOperand(kind=OperandKind.VGPR_PAIR, reg_idx=2, neg=True, abs_val=True) - inst_clamp = ASTInstruction(opcode="v_trig_f64", dst=dst, src0=src0_mod, clamp=True) - inst_clamp.validate() - self.assertEqual(inst_clamp.format_asm(), "v_trig_f64 v[0:1], -|v[2:3]| clamp") - - def test_typed_expression_evaluation(self) -> None: - c1 = F64Constant(F64_QUARTER) - trig_expr = F64Trig(operand=c1, mode=TrigMode.SIN) - res = trig_expr.evaluate({}) - self.assertEqual(res, F64_ONE) - - # COS mode - trig_cos = F64Trig(operand=c1, mode=TrigMode.COS) - res_cos = trig_cos.evaluate({}) - self.assertEqual(res_cos, F64_POS_ZERO) - - # Unary operations: neg(0.25) -> sin(-0.25) = -1.0 - neg_c1 = F64UnaryOp("neg", c1) - res_neg = F64Trig(operand=neg_c1, mode=TrigMode.SIN).evaluate({}) - self.assertEqual(res_neg, F64_NEG_ONE) - - def test_instruction_to_expression(self) -> None: - dst = ASTOperand(kind=OperandKind.VGPR_PAIR, reg_idx=0) - src0 = ASTOperand(kind=OperandKind.VGPR_PAIR, reg_idx=2, neg=True) - inst = ASTInstruction(opcode="v_trig_f64", dst=dst, src0=src0, mode=TrigMode.SIN) - expr = instruction_to_expression(inst) - - env = {"src0_2": F64_QUARTER} - res = expr.evaluate(env) - self.assertEqual(res, F64_NEG_ONE) - - def test_ast_validation_errors(self) -> None: - # Bad opcode - bad_inst = ASTInstruction( - opcode="v_sin_f32", - dst=ASTOperand(kind=OperandKind.VGPR_PAIR, reg_idx=0), - src0=ASTOperand(kind=OperandKind.VGPR_PAIR, reg_idx=2), - ) - with self.assertRaises(ValueError): - bad_inst.validate() - - # Destination must be VGPR pair - bad_dst = ASTInstruction( - opcode="v_trig_f64", - dst=ASTOperand(kind=OperandKind.SGPR_PAIR, reg_idx=0), - src0=ASTOperand(kind=OperandKind.VGPR_PAIR, reg_idx=2), - ) - with self.assertRaises(ValueError): - bad_dst.validate() - - # Destination cannot have neg modifier - bad_mod = ASTInstruction( - opcode="v_trig_f64", - dst=ASTOperand(kind=OperandKind.VGPR_PAIR, reg_idx=0, neg=True), - src0=ASTOperand(kind=OperandKind.VGPR_PAIR, reg_idx=2), - ) - with self.assertRaises(ValueError): - bad_mod.validate() - - -# ============================================================================== -# Deterministic Scalar Instruction Interpreter for v_trig_f64 -# ============================================================================== - -def parse_asm_operand(tok: str) -> ASTOperand: - tok = tok.strip() - neg = False - abs_val = False - if tok.startswith("-"): - neg = True - tok = tok[1:].strip() - if tok.startswith("|") and tok.endswith("|"): - abs_val = True - tok = tok[1:-1].strip() - - if tok.startswith("v[") and tok.endswith("]"): - inner = tok[2:-1] - parts = inner.split(":") - reg_idx = int(parts[0]) - return ASTOperand(kind=OperandKind.VGPR_PAIR, reg_idx=reg_idx, neg=neg, abs_val=abs_val) - elif tok.startswith("s[") and tok.endswith("]"): - inner = tok[2:-1] - parts = inner.split(":") - reg_idx = int(parts[0]) - return ASTOperand(kind=OperandKind.SGPR_PAIR, reg_idx=reg_idx, neg=neg, abs_val=abs_val) - elif tok.startswith("0x") or tok.startswith("0X"): - imm = int(tok, 16) - return ASTOperand(kind=OperandKind.LITERAL_64, imm_val=imm, neg=neg, abs_val=abs_val) - else: - try: - if "." in tok or "e" in tok.lower(): - imm = f64_to_u64(float(tok)) - return ASTOperand(kind=OperandKind.LITERAL_64, imm_val=imm, neg=neg, abs_val=abs_val) - imm = int(tok) - return ASTOperand(kind=OperandKind.INLINE_IMM, imm_val=imm, neg=neg, abs_val=abs_val) - except ValueError: - raise ValueError(f"Unrecognized assembly operand token: {tok}") - - -def parse_asm_line(line: str) -> ASTInstruction: - clean = line.split(";")[0].split("//")[0].strip() - tokens = [t for t in clean.replace(",", " ").split() if t] - if not tokens: - raise ValueError("Empty assembly line") - opcode = tokens[0] - if opcode != "v_trig_f64": - raise ValueError(f"Expected opcode v_trig_f64, got {opcode}") - - clamp = False - mode = TrigMode.SIN - raw_ops = [] - for tok in tokens[1:]: - ltok = tok.lower() - if ltok == "clamp": - clamp = True - elif ltok == "cos": - mode = TrigMode.COS - elif ltok == "sin": - mode = TrigMode.SIN - else: - raw_ops.append(tok) - - if len(raw_ops) != 2: - raise ValueError(f"v_trig_f64 requires 2 operands (dst, src0), got {len(raw_ops)}: {raw_ops}") - - dst = parse_asm_operand(raw_ops[0]) - src0 = parse_asm_operand(raw_ops[1]) - inst = ASTInstruction(opcode=opcode, dst=dst, src0=src0, mode=mode, clamp=clamp) - inst.validate() - return inst - - -class ScalarInterpreter: - """Deterministic scalar instruction interpreter for RDNA2 VALU v_trig_f64.""" - - def __init__(self, num_vgprs: int = 256, num_sgprs: int = 106) -> None: - self.vgpr = VALURegisterFile(num_vgprs=num_vgprs) - self.num_sgprs = num_sgprs - self.sgprs = [0] * num_sgprs - self.vcc = 0 - self.scc = 0 - - def get_sgpr(self, idx: int) -> int: - if not (0 <= idx < self.num_sgprs): - raise IndexError(f"SGPR index out of range: {idx}") - return self.sgprs[idx] & MASK32 - - def set_sgpr(self, idx: int, val: int) -> None: - if not (0 <= idx < self.num_sgprs): - raise IndexError(f"SGPR index out of range: {idx}") - self.sgprs[idx] = val & MASK32 - - def get_sgpr_pair(self, idx: int) -> int: - if not (0 <= idx < self.num_sgprs - 1): - raise IndexError(f"SGPR pair index out of range: s[{idx}:{idx+1}]") - lo = self.get_sgpr(idx) - hi = self.get_sgpr(idx + 1) - return join_dwords(lo, hi) - - def set_sgpr_pair(self, idx: int, val64: int) -> None: - if not (0 <= idx < self.num_sgprs - 1): - raise IndexError(f"SGPR pair index out of range: s[{idx}:{idx+1}]") - lo, hi = split_dwords(val64) - self.set_sgpr(idx, lo) - self.set_sgpr(idx + 1, hi) - - def resolve_operand(self, op: ASTOperand) -> int: - if op.kind == OperandKind.VGPR_PAIR: - val = self.vgpr.get_vgpr_pair(op.reg_idx) - elif op.kind == OperandKind.SGPR_PAIR: - val = self.get_sgpr_pair(op.reg_idx) - elif op.kind == OperandKind.LITERAL_64: - val = op.imm_val - elif op.kind == OperandKind.INLINE_IMM: - val = op.imm_val - else: - raise ValueError(f"Unknown operand kind: {op.kind}") - return apply_input_modifiers_f64(val, neg=op.neg, abs_val=op.abs_val) - - def execute_ast(self, inst: ASTInstruction) -> int: - inst.validate() - s0 = self.resolve_operand(inst.src0) - res = ref_trig_f64(s0, mode=inst.mode, clamp=inst.clamp) - self.vgpr.set_vgpr_pair(inst.dst.reg_idx, res) - return res - - def execute_asm(self, line: str) -> int: - inst = parse_asm_line(line) - return self.execute_ast(inst) - - -class TestScalarInterpreter(unittest.TestCase): - """Test suite for deterministic scalar interpreter execution.""" - - def test_execute_vgpr_source(self) -> None: - interp = ScalarInterpreter() - interp.vgpr.set_vgpr_pair(2, F64_QUARTER) - res = interp.execute_asm("v_trig_f64 v[0:1], v[2:3]") - self.assertEqual(res, F64_ONE) - self.assertEqual(interp.vgpr.get_vgpr_pair(0), F64_ONE) - - def test_execute_sgpr_source(self) -> None: - interp = ScalarInterpreter() - interp.set_sgpr_pair(4, F64_QUARTER) - res = interp.execute_asm("v_trig_f64 v[6:7], s[4:5]") - self.assertEqual(res, F64_ONE) - self.assertEqual(interp.vgpr.get_vgpr_pair(6), F64_ONE) - - def test_execute_literal_source(self) -> None: - interp = ScalarInterpreter() - res = interp.execute_asm(f"v_trig_f64 v[0:1], 0x{F64_QUARTER:016x}") - self.assertEqual(res, F64_ONE) - self.assertEqual(interp.vgpr.get_vgpr_pair(0), F64_ONE) - - def test_execute_with_modifiers_and_clamp(self) -> None: - interp = ScalarInterpreter() - interp.vgpr.set_vgpr_pair(2, F64_QUARTER) - # neg modifier makes turns -0.25 -> sin(-0.25) = -1.0; clamp makes it +0.0 - res = interp.execute_asm("v_trig_f64 v[0:1], -v[2:3] clamp") - self.assertEqual(res, F64_POS_ZERO) - self.assertEqual(interp.vgpr.get_vgpr_pair(0), F64_POS_ZERO) - - def test_execute_cos_mode(self) -> None: - interp = ScalarInterpreter() - interp.vgpr.set_vgpr_pair(2, F64_POS_ZERO) - res = interp.execute_asm("v_trig_f64 v[0:1], v[2:3] cos") - self.assertEqual(res, F64_ONE) - self.assertEqual(interp.vgpr.get_vgpr_pair(0), F64_ONE) - - def test_sequential_program_execution(self) -> None: - interp = ScalarInterpreter() - # Step 1: v[0:1] = sin(0.25 turns) = 1.0 - interp.execute_asm(f"v_trig_f64 v[0:1], 0x{F64_QUARTER:016x}") - # Step 2: v[2:3] = cos(0.00 turns) = 1.0 - interp.execute_asm("v_trig_f64 v[2:3], 0x0 cos") - # Step 3: v[4:5] = sin(v[0:1]) where v[0:1] is 1.0 -> sin(1.0 turn) = 0.0 - interp.execute_asm("v_trig_f64 v[4:5], v[0:1]") - - self.assertEqual(interp.vgpr.get_vgpr_pair(0), F64_ONE) - self.assertEqual(interp.vgpr.get_vgpr_pair(2), F64_ONE) - self.assertEqual(interp.vgpr.get_vgpr_pair(4), F64_POS_ZERO) - - -# ============================================================================== -# SIMD Wavefront Execution Model (Wave32 / Wave64) for v_trig_f64 -# ============================================================================== - -def ref_simd_trig_f64( - src0_lanes: list[int], - wave_size: int = 64, - exec_mask: int | None = None, - prev_dst: list[int] | None = None, - *, - mode: TrigMode = TrigMode.SIN, - clamp: bool = False, - src0_neg: bool = False, - src0_abs: bool = False, -) -> list[int]: - """Reference SIMD execution oracle across wavefront lanes.""" - if wave_size not in (32, 64): - raise ValueError(f"Unsupported wave size: {wave_size}") - if len(src0_lanes) != wave_size: - raise ValueError(f"Operand length must match wave_size ({wave_size})") - - active_mask = (1 << wave_size) - 1 if exec_mask is None else (exec_mask & ((1 << wave_size) - 1)) - fallback = [0] * wave_size if prev_dst is None else prev_dst - if len(fallback) != wave_size: - raise ValueError(f"prev_dst length must match wave_size ({wave_size})") - - output = list(fallback) - for lane in range(wave_size): - if (active_mask >> lane) & 1: - output[lane] = ref_trig_f64( - src0_lanes[lane], - mode=mode, - clamp=clamp, - src0_neg=src0_neg, - src0_abs=src0_abs, - ) - return output - - -class SIMDWavefront: - """SIMD wavefront simulator modeling multi-lane execution and EXEC masking.""" - - def __init__(self, wave_size: int = 64, num_vgprs: int = 256) -> None: - if wave_size not in (32, 64): - raise ValueError(f"Wave size must be 32 or 64, got {wave_size}") - self.wave_size = wave_size - self.num_vgprs = num_vgprs - self.lanes = [VALURegisterFile(num_vgprs=num_vgprs) for _ in range(wave_size)] - self.exec_mask = (1 << wave_size) - 1 - self.vcc = 0 - self.sgprs = [0] * 106 - - def store_vgpr_pair_wave(self, reg_idx: int, values: list[int]) -> None: - if len(values) != self.wave_size: - raise ValueError(f"Value count ({len(values)}) does not match wave_size ({self.wave_size})") - for lane in range(self.wave_size): - self.lanes[lane].set_vgpr_pair(reg_idx, values[lane]) - - def load_vgpr_pair_wave(self, reg_idx: int) -> list[int]: - return [self.lanes[lane].get_vgpr_pair(reg_idx) for lane in range(self.wave_size)] - - def step_v_trig_f64( - self, - dst_reg: int, - src0_reg: int, - *, - mode: TrigMode = TrigMode.SIN, - clamp: bool = False, - src0_neg: bool = False, - src0_abs: bool = False, - ) -> list[int]: - active_mask = self.exec_mask & ((1 << self.wave_size) - 1) - for lane in range(self.wave_size): - if (active_mask >> lane) & 1: - s0 = self.lanes[lane].get_vgpr_pair(src0_reg) - res = ref_trig_f64( - s0, - mode=mode, - clamp=clamp, - src0_neg=src0_neg, - src0_abs=src0_abs, - ) - self.lanes[lane].set_vgpr_pair(dst_reg, res) - return self.load_vgpr_pair_wave(dst_reg) - - -class TestSIMDMultiLaneDivergence(unittest.TestCase): - """Test suite for SIMD multi-lane divergence and EXEC masking.""" - - def test_wave32_full_exec(self) -> None: - wave = SIMDWavefront(wave_size=32) - angles = [f64_to_u64(i / 32.0) for i in range(32)] - wave.store_vgpr_pair_wave(2, angles) - - res = wave.step_v_trig_f64(0, 2, mode=TrigMode.SIN) - expected = ref_simd_trig_f64(angles, wave_size=32, mode=TrigMode.SIN) - self.assertEqual(res, expected) - - def test_wave64_full_exec(self) -> None: - wave = SIMDWavefront(wave_size=64) - angles = [f64_to_u64(i / 64.0) for i in range(64)] - wave.store_vgpr_pair_wave(4, angles) - - res = wave.step_v_trig_f64(0, 4, mode=TrigMode.COS) - expected = ref_simd_trig_f64(angles, wave_size=64, mode=TrigMode.COS) - self.assertEqual(res, expected) - - def test_wave32_partial_exec_preservation(self) -> None: - wave = SIMDWavefront(wave_size=32) - sentinel = join_dwords(OLD_VGPR_SENTINEL, OLD_VGPR_SENTINEL) - wave.store_vgpr_pair_wave(0, [sentinel] * 32) - - angles = [F64_QUARTER] * 32 - wave.store_vgpr_pair_wave(2, angles) - - # Alternating mask: even lanes active - wave.exec_mask = 0x55555555 - res = wave.step_v_trig_f64(0, 2, mode=TrigMode.SIN) - - for lane in range(32): - if lane % 2 == 0: - self.assertEqual(res[lane], F64_ONE, f"Active lane {lane} failed to update") - else: - self.assertEqual(res[lane], sentinel, f"Inactive lane {lane} was mutated") - - def test_wave64_upper_half_exec(self) -> None: - wave = SIMDWavefront(wave_size=64) - sentinel = join_dwords(OLD_VGPR_SENTINEL, OLD_VGPR_SENTINEL) - wave.store_vgpr_pair_wave(0, [sentinel] * 64) - - angles = [F64_QUARTER] * 64 - wave.store_vgpr_pair_wave(2, angles) - - # Only upper 32 lanes active - wave.exec_mask = 0xFFFFFFFF00000000 - res = wave.step_v_trig_f64(0, 2, mode=TrigMode.SIN) - - for lane in range(64): - if lane >= 32: - self.assertEqual(res[lane], F64_ONE, f"Active upper lane {lane} failed to update") - else: - self.assertEqual(res[lane], sentinel, f"Inactive lower lane {lane} was overwritten") - - def test_wave_exec_all_zero(self) -> None: - wave = SIMDWavefront(wave_size=32) - sentinel = join_dwords(OLD_VGPR_SENTINEL, OLD_VGPR_SENTINEL) - wave.store_vgpr_pair_wave(0, [sentinel] * 32) - wave.store_vgpr_pair_wave(2, [F64_QUARTER] * 32) - - wave.exec_mask = 0x00000000 - res = wave.step_v_trig_f64(0, 2, mode=TrigMode.SIN) - self.assertEqual(res, [sentinel] * 32) - - def test_wave_single_active_lane(self) -> None: - wave = SIMDWavefront(wave_size=64) - sentinel = join_dwords(OLD_VGPR_SENTINEL, OLD_VGPR_SENTINEL) - wave.store_vgpr_pair_wave(0, [sentinel] * 64) - wave.store_vgpr_pair_wave(2, [F64_QUARTER] * 64) - - # Only lane 42 active - wave.exec_mask = 1 << 42 - res = wave.step_v_trig_f64(0, 2, mode=TrigMode.SIN) - - for lane in range(64): - if lane == 42: - self.assertEqual(res[lane], F64_ONE) - else: - self.assertEqual(res[lane], sentinel) - - def test_wave_size_validation(self) -> None: - with self.assertRaises(ValueError): - SIMDWavefront(wave_size=16) - with self.assertRaises(ValueError): - SIMDWavefront(wave_size=128) - with self.assertRaises(ValueError): - ref_simd_trig_f64([0] * 16, wave_size=16) - - -# ============================================================================== -# Register Aliasing and In-Place Operand Preservation for v_trig_f64 -# ============================================================================== - -class TestRegisterAliasing(unittest.TestCase): - """Test suite for register aliasing and in-place operand preservation.""" - - def test_inplace_dst_equals_src0(self) -> None: - interp = ScalarInterpreter() - interp.vgpr.set_vgpr_pair(4, F64_QUARTER) - - # v[4:5] = v_trig_f64(v[4:5]) -> sin(0.25 turns) = 1.0 - res = interp.execute_asm("v_trig_f64 v[4:5], v[4:5]") - self.assertEqual(res, F64_ONE) - self.assertEqual(interp.vgpr.get_vgpr_pair(4), F64_ONE) - - def test_partially_overlapping_register_pairs(self) -> None: - interp = ScalarInterpreter() - # Setup: src0 at v[0:1] - interp.vgpr.set_vgpr_pair(0, F64_QUARTER) - v0_before = interp.vgpr.get_vgpr(0) - - # Execute with dst as unaligned v[1:2] overlapping src0 via v[1] - dst = ASTOperand(kind=OperandKind.VGPR_PAIR, reg_idx=1) - src0 = ASTOperand(kind=OperandKind.VGPR_PAIR, reg_idx=0) - inst = ASTInstruction(opcode="v_trig_f64", dst=dst, src0=src0, mode=TrigMode.SIN) - res = interp.execute_ast(inst) - - self.assertEqual(res, F64_ONE) - self.assertEqual(interp.vgpr.get_vgpr_pair(1), F64_ONE) - # Non-overlapping boundary dword v[0] must remain completely unchanged - self.assertEqual(interp.vgpr.get_vgpr(0), v0_before) - - def test_adjacent_register_isolation(self) -> None: - interp = ScalarInterpreter() - sentinel_lo = 0x11112222 - sentinel_hi = 0x33334444 - sentinel = join_dwords(sentinel_lo, sentinel_hi) - - interp.vgpr.set_vgpr_pair(0, sentinel) - interp.vgpr.set_vgpr_pair(2, F64_QUARTER) - interp.vgpr.set_vgpr_pair(4, sentinel) - - # Execute v_trig_f64 writing only to v[2:3] - interp.execute_asm("v_trig_f64 v[2:3], v[2:3]") - - self.assertEqual(interp.vgpr.get_vgpr_pair(2), F64_ONE) - # Adjacent v[0:1] and v[4:5] must not be corrupted - self.assertEqual(interp.vgpr.get_vgpr_pair(0), sentinel) - self.assertEqual(interp.vgpr.get_vgpr_pair(4), sentinel) - - def test_simd_inplace_divergent_mask(self) -> None: - sim = SIMDWavefront(wave_size=32) - init_vals = [f64_to_u64(0.25) if i % 2 == 1 else f64_to_u64(0.12345) for i in range(32)] - sim.store_vgpr_pair_wave(0, init_vals) - - # Active on odd lanes only: 0xAAAAAAAA - sim.exec_mask = 0xAAAAAAAA - res = sim.step_v_trig_f64(0, 0, mode=TrigMode.SIN) - - for lane in range(32): - if lane % 2 == 1: - # Active lane: updated to sin(0.25) = 1.0 - self.assertEqual(res[lane], F64_ONE, f"Lane {lane} failed to update") - else: - # Inactive lane: preserved original - self.assertEqual(res[lane], init_vals[lane], f"Lane {lane} was mutated") - - def test_successive_inplace_trig_chain(self) -> None: - interp = ScalarInterpreter() - # Start with 0.25 -> sin(0.25) = 1.0 -> sin(1.0) = 0.0 -> sin(0.0) = 0.0 - interp.vgpr.set_vgpr_pair(0, F64_QUARTER) - interp.execute_asm("v_trig_f64 v[0:1], v[0:1]") - self.assertEqual(interp.vgpr.get_vgpr_pair(0), F64_ONE) - - interp.execute_asm("v_trig_f64 v[0:1], v[0:1]") - self.assertEqual(interp.vgpr.get_vgpr_pair(0), F64_POS_ZERO) - - interp.execute_asm("v_trig_f64 v[0:1], v[0:1]") - self.assertEqual(interp.vgpr.get_vgpr_pair(0), F64_POS_ZERO) - - -# ============================================================================== -# Condition Codes, Status Flags, and Carry/Borrow Isolation for v_trig_f64 -# ============================================================================== - -@dataclass -class StatusFlags: - invalid_op: bool = False - overflow: bool = False - underflow: bool = False - inexact: bool = False - zero: bool = False - negative: bool = False - nan: bool = False - - -def compute_trig_f64_status_flags(src0: int, result: int) -> StatusFlags: - flags = StatusFlags() - s0 = src0 & MASK64 - res = result & MASK64 - - # Invalid operation: SNaN operand or Infinite operand (sin/cos of Inf is invalid) - if is_f64_snan(s0) or is_f64_inf(s0): - flags.invalid_op = True - - if is_f64_nan(res): - flags.nan = True - else: - flags.negative = bool(f64_sign(res)) - if is_f64_zero(res): - flags.zero = True - else: - # Check inexact: transcendental results on non-cardinal inputs are inexact - val = u64_to_f64(s0) - red = ref_turn_reduce_f64(val) - if red not in (0.0, 0.25, -0.25, 0.5, -0.5): - flags.inexact = True - - return flags - - -def ref_cmp_f64(op: str, src0: int, src1: int) -> bool: - """Evaluate double-precision IEEE-754 comparison condition codes.""" - if op in ("u", "unordered"): - return is_f64_nan(src0) or is_f64_nan(src1) - - if is_f64_nan(src0) or is_f64_nan(src1): - return op in ("neq", "ne", "!=") - - v0 = u64_to_f64(src0) - v1 = u64_to_f64(src1) - if op in ("eq", "=="): - return v0 == v1 - elif op in ("ne", "neq", "!="): - return v0 != v1 - elif op in ("lt", "<"): - return v0 < v1 - elif op in ("le", "<="): - return v0 <= v1 - elif op in ("gt", ">"): - return v0 > v1 - elif op in ("ge", ">="): - return v0 >= v1 - raise ValueError(f"Unknown comparison operator: {op}") - - -def generate_condition_mask_f64(op: str, src0_lanes: list[int], src1_lanes: list[int]) -> int: - """Generate a 32-bit or 64-bit condition mask (VCC) from per-lane comparisons.""" - mask = 0 - for lane, (s0, s1) in enumerate(zip(src0_lanes, src1_lanes)): - if ref_cmp_f64(op, s0, s1): - mask |= (1 << lane) - return mask - - -class TestConditionCodesAndStatusFlags(unittest.TestCase): - """Test suite for condition codes, status flags, and carry/borrow isolation.""" - - def test_status_flags_invalid_operation(self) -> None: - # sin(Inf) -> Invalid operation exception and NaN - res_inf = ref_trig_f64(F64_POS_INF, mode=TrigMode.SIN) - flags_inf = compute_trig_f64_status_flags(F64_POS_INF, res_inf) - self.assertTrue(flags_inf.invalid_op) - self.assertTrue(flags_inf.nan) - - # SNaN -> Invalid operation exception - snan = (F64_POS_INF | 0x0001000000000000) & ~F64_QUIET_BIT - res_snan = ref_trig_f64(snan, mode=TrigMode.SIN) - flags_snan = compute_trig_f64_status_flags(snan, res_snan) - self.assertTrue(flags_snan.invalid_op) - self.assertTrue(flags_snan.nan) - - def test_status_flags_zero_and_negative(self) -> None: - # sin(-0.25 turns) = -1.0 (negative, non-zero) - res_neg = ref_trig_f64(F64_NEG_QUARTER, mode=TrigMode.SIN) - flags_neg = compute_trig_f64_status_flags(F64_NEG_QUARTER, res_neg) - self.assertTrue(flags_neg.negative) - self.assertFalse(flags_neg.zero) - - # sin(-0.0 turns) = -0.0 (negative zero) - res_nzero = ref_trig_f64(F64_NEG_ZERO, mode=TrigMode.SIN) - flags_nzero = compute_trig_f64_status_flags(F64_NEG_ZERO, res_nzero) - self.assertTrue(flags_nzero.negative) - self.assertTrue(flags_nzero.zero) - - def test_status_flags_inexact(self) -> None: - # 0.125 turn = 45 degrees -> sin(pi/4) is irrational and inexact - t = f64_to_u64(0.125) - res = ref_trig_f64(t, mode=TrigMode.SIN) - flags = compute_trig_f64_status_flags(t, res) - self.assertTrue(flags.inexact) - - def test_vcc_and_scc_preserved(self) -> None: - # Floating point v_trig_f64 does not generate carry/borrow and never writes VCC or SCC - interp = ScalarInterpreter() - interp.vcc = 0x12345678_9ABCDEF0 - interp.scc = 1 - interp.vgpr.set_vgpr_pair(2, F64_QUARTER) - - interp.execute_asm("v_trig_f64 v[0:1], v[2:3]") - self.assertEqual(interp.vcc, 0x12345678_9ABCDEF0) - self.assertEqual(interp.scc, 1) - - sim = SIMDWavefront(wave_size=32) - sim.vcc = 0xCAFEBABE - sim.store_vgpr_pair_wave(2, [F64_QUARTER] * 32) - sim.step_v_trig_f64(0, 2) - self.assertEqual(sim.vcc, 0xCAFEBABE) - - def test_condition_code_generation(self) -> None: - v_zero = [F64_POS_ZERO] * 4 - # Four angles in turns: [-0.25 (sin=-1), 0.0 (sin=0), 0.25 (sin=1), Inf (sin=NaN)] - srcs = [F64_NEG_QUARTER, F64_POS_ZERO, F64_QUARTER, F64_POS_INF] - sins = [ref_trig_f64(a, mode=TrigMode.SIN) for a in srcs] - - # Compare < 0: only lane 0 (-1.0 < 0) -> bit 0 - mask_lt = generate_condition_mask_f64("<", sins, v_zero) - self.assertEqual(mask_lt, 0b0001) - - # Compare == 0: only lane 1 (0.0 == 0) -> bit 1 - mask_eq = generate_condition_mask_f64("==", sins, v_zero) - self.assertEqual(mask_eq, 0b0010) - - # Compare > 0: only lane 2 (1.0 > 0) -> bit 2 - mask_gt = generate_condition_mask_f64(">", sins, v_zero) - self.assertEqual(mask_gt, 0b0100) - - # Compare unordered: only lane 3 (NaN) -> bit 3 - mask_u = generate_condition_mask_f64("u", sins, v_zero) - self.assertEqual(mask_u, 0b1000) - - -# ============================================================================== -# IEEE 754 Boundary Extremes, Subnormals, and NaN Handling for v_trig_f64 -# ============================================================================== - -class TestIEEE754BoundaryExtremes(unittest.TestCase): - """Test suite for IEEE-754 boundary extremes, subnormals, and NaN handling.""" - - def test_nan_snan_quieting(self) -> None: - # Positive signaling NaN - snan_pos = 0x7FF0000000000001 - self.assertTrue(is_f64_snan(snan_pos)) - res_pos = ref_trig_f64(snan_pos, mode=TrigMode.SIN) - self.assertTrue(is_f64_qnan(res_pos)) - - # Negative signaling NaN - snan_neg = 0xFFF0000000000001 - self.assertTrue(is_f64_snan(snan_neg)) - res_neg = ref_trig_f64(snan_neg, mode=TrigMode.COS) - self.assertTrue(is_f64_qnan(res_neg)) - - def test_qnan_propagation(self) -> None: - qnan_custom = 0x7FF8000000001234 - self.assertTrue(is_f64_qnan(qnan_custom)) - res_sin = ref_trig_f64(qnan_custom, mode=TrigMode.SIN) - self.assertTrue(is_f64_qnan(res_sin)) - res_cos = ref_trig_f64(qnan_custom, mode=TrigMode.COS) - self.assertTrue(is_f64_qnan(res_cos)) - - def test_infinities_return_canonical_qnan(self) -> None: - self.assertEqual(ref_trig_f64(F64_POS_INF, mode=TrigMode.SIN), F64_CANONICAL_QNAN) - self.assertEqual(ref_trig_f64(F64_NEG_INF, mode=TrigMode.SIN), F64_CANONICAL_QNAN) - self.assertEqual(ref_trig_f64(F64_POS_INF, mode=TrigMode.COS), F64_CANONICAL_QNAN) - self.assertEqual(ref_trig_f64(F64_NEG_INF, mode=TrigMode.COS), F64_CANONICAL_QNAN) - - def test_signed_zeros_preservation(self) -> None: - # sin(+0.0) = +0.0, sin(-0.0) = -0.0 - self.assertEqual(ref_trig_f64(F64_POS_ZERO, mode=TrigMode.SIN), F64_POS_ZERO) - self.assertEqual(ref_trig_f64(F64_NEG_ZERO, mode=TrigMode.SIN), F64_NEG_ZERO) - # cos(+0.0) = 1.0, cos(-0.0) = 1.0 - self.assertEqual(ref_trig_f64(F64_POS_ZERO, mode=TrigMode.COS), F64_ONE) - self.assertEqual(ref_trig_f64(F64_NEG_ZERO, mode=TrigMode.COS), F64_ONE) - - def test_subnormal_inputs(self) -> None: - # Smallest subnormal - sub_min = F64_MIN_SUBNORMAL - self.assertTrue(is_f64_subnormal(sub_min)) - res_min = ref_trig_f64(sub_min, mode=TrigMode.SIN) - # In IEEE mode, not flushed to zero: sin(2*pi*x) > 0 - self.assertFalse(is_f64_zero(res_min)) - self.assertEqual(f64_sign(res_min), 0) - - # Negative subnormal - neg_sub_min = F64_MIN_SUBNORMAL | F64_SIGN_MASK - res_neg = ref_trig_f64(neg_sub_min, mode=TrigMode.SIN) - self.assertFalse(is_f64_zero(res_neg)) - self.assertEqual(f64_sign(res_neg), 1) - - # Largest subnormal: cos(subnormal) == 1.0 - sub_max = F64_MAX_SUBNORMAL - res_cos = ref_trig_f64(sub_max, mode=TrigMode.COS) - self.assertEqual(res_cos, F64_ONE) - - def test_normal_boundary_extremes(self) -> None: - # Smallest normal float: 2^-1022 - min_norm = F64_MIN_NORMAL - self.assertTrue(is_f64_normal(min_norm)) - res_sin = ref_trig_f64(min_norm, mode=TrigMode.SIN) - self.assertFalse(is_f64_zero(res_sin)) - self.assertFalse(is_f64_nan(res_sin)) - - # Numbers >= 2^53 are exact integers with zero fractional part - int_power = f64_to_u64(2.0**53 + 4.0) - self.assertEqual(ref_trig_f64(int_power, mode=TrigMode.SIN), F64_POS_ZERO) - self.assertEqual(ref_trig_f64(int_power, mode=TrigMode.COS), F64_ONE) - - # Largest normal float: 1.7976931348623157e+308 - max_norm = F64_MAX_NORMAL - self.assertTrue(is_f64_normal(max_norm)) - res_max = ref_trig_f64(max_norm, mode=TrigMode.SIN) - # As max_norm is an integer with zero fractional turn, sin is zero - self.assertEqual(res_max, F64_POS_ZERO) - - -# ============================================================================== -# Mutants for Mutation Detection -# ============================================================================== - -def mutant_radians_not_turns(s0: int, *, mode: TrigMode = TrigMode.SIN, **kwargs) -> int: - """Mutant 1: Treats input directly as radians instead of turns (missing 2*pi scale).""" - val = u64_to_f64(s0) - if is_f64_nan(s0) or is_f64_inf(s0): - return F64_CANONICAL_QNAN - res = math.sin(val) if mode == TrigMode.SIN else math.cos(val) - return f64_to_u64(res) - - -def mutant_ignore_neg(s0: int, *, src0_neg: bool = False, **kwargs) -> int: - """Mutant 2: Ignores negative modifier.""" - return ref_trig_f64(s0, src0_neg=False, **kwargs) - - -def mutant_ignore_abs(s0: int, *, src0_abs: bool = False, **kwargs) -> int: - """Mutant 3: Ignores absolute value modifier.""" - return ref_trig_f64(s0, src0_abs=False, **kwargs) - - -def mutant_ignore_clamp(s0: int, *, clamp: bool = False, **kwargs) -> int: - """Mutant 4: Ignores clamp modifier.""" - return ref_trig_f64(s0, clamp=False, **kwargs) - - -def mutant_clamp_nan_to_nan(s0: int, *, clamp: bool = False, **kwargs) -> int: - """Mutant 5: Clamps numbers but fails to clamp NaN to +0.0.""" - res = ref_trig_f64(s0, clamp=False, **kwargs) - if clamp and not is_f64_nan(res): - val = u64_to_f64(res) - if val < 0.0: - return F64_POS_ZERO - elif val > 1.0: - return F64_ONE - return res - - -def mutant_snan_not_quieted(s0: int, **kwargs) -> int: - """Mutant 6: Returns SNaN without setting the quiet bit.""" - if is_f64_snan(s0): - return s0 - return ref_trig_f64(s0, **kwargs) - - -def mutant_inf_returns_zero(s0: int, **kwargs) -> int: - """Mutant 7: Returns 0.0 on infinite inputs instead of Canonical QNaN.""" - if is_f64_inf(s0): - return F64_POS_ZERO - return ref_trig_f64(s0, **kwargs) - - -def mutant_f32_truncation(s0: int, **kwargs) -> int: - """Mutant 8: Truncates intermediate calculation to 32-bit single precision float.""" - f0 = struct.unpack(" None: - for bad_op in ("v_trig_f32", "v_sin_f32", "s_trig_f64", "v_add_f64", "unknown_op"): - with self.assertRaises(ValueError): - parse_asm_line(f"{bad_op} v[0:1], v[2:3]") - - def test_syntax_rejection_bad_operands(self) -> None: - for bad_line in ( - "v_trig_f64 v0, v[2:3]", - "v_trig_f64 v[0:1], invalid_reg", - "v_trig_f64 v[0:1], v[300:301]", - ): - with self.assertRaises(ValueError): - parse_asm_line(bad_line) - - def test_syntax_rejection_operand_count(self) -> None: - # Too few operands - with self.assertRaises(ValueError): - parse_asm_line("v_trig_f64 v[0:1]") - # Too many operands - with self.assertRaises(ValueError): - parse_asm_line("v_trig_f64 v[0:1], v[2:3], v[4:5]") - - def test_syntax_rejection_destination_modifiers(self) -> None: - with self.assertRaises(ValueError): - parse_asm_line("v_trig_f64 -v[0:1], v[2:3]") - with self.assertRaises(ValueError): - parse_asm_line("v_trig_f64 |v[0:1]|, v[2:3]") - - def test_syntax_rejection_empty_lines(self) -> None: - with self.assertRaises(ValueError): - parse_asm_line("") - with self.assertRaises(ValueError): - parse_asm_line(" ; comment only") - - def test_negative_control_radians_instead_of_turns(self) -> None: - # sin(0.25 turns) = 1.0; sin(0.25 rad) ~= 0.2474 - s0 = F64_QUARTER - good = ref_trig_f64(s0, mode=TrigMode.SIN) - bad = mutant_radians_not_turns(s0, mode=TrigMode.SIN) - self.assertNotEqual(good, bad) - self.assertEqual(good, F64_ONE) - self.assertNotEqual(bad, F64_ONE) - - def test_negative_control_f32_truncation_detected(self) -> None: - # An angle whose low 29 mantissa bits matter in binary64 - angle = 0.125 + 2.0**(-30) - s0 = f64_to_u64(angle) - good = ref_trig_f64(s0) - bad = mutant_f32_truncation(s0) - self.assertNotEqual(good, bad, "Single precision truncation mutation must be detected") - - def test_mutation_detection_all_mutants_caught(self) -> None: - # Mutant 1: radians not turns - self.assertNotEqual(ref_trig_f64(F64_QUARTER), mutant_radians_not_turns(F64_QUARTER)) - - # Mutant 2: ignore neg - self.assertNotEqual( - ref_trig_f64(F64_QUARTER, src0_neg=True), - mutant_ignore_neg(F64_QUARTER, src0_neg=True), - ) - - # Mutant 3: ignore abs - self.assertNotEqual( - ref_trig_f64(F64_NEG_QUARTER, src0_abs=True), - mutant_ignore_abs(F64_NEG_QUARTER, src0_abs=True), - ) - - # Mutant 4: ignore clamp - self.assertNotEqual( - ref_trig_f64(F64_NEG_QUARTER, clamp=True), - mutant_ignore_clamp(F64_NEG_QUARTER, clamp=True), - ) - - # Mutant 5: clamp NaN to NaN instead of +0.0 - self.assertNotEqual( - ref_trig_f64(F64_POS_INF, clamp=True), - mutant_clamp_nan_to_nan(F64_POS_INF, clamp=True), - ) - - # Mutant 6: SNaN not quieted - snan = 0x7FF0000000000001 - self.assertNotEqual(ref_trig_f64(snan), mutant_snan_not_quieted(snan)) - - # Mutant 7: Inf returns 0 instead of QNaN - self.assertNotEqual(ref_trig_f64(F64_POS_INF), mutant_inf_returns_zero(F64_POS_INF)) - - def test_mutation_detects_exec_mask_leakage(self) -> None: - sim = SIMDWavefront(wave_size=32) - sentinel = join_dwords(OLD_VGPR_SENTINEL, OLD_VGPR_SENTINEL) - sim.store_vgpr_pair_wave(0, [sentinel] * 32) - sim.store_vgpr_pair_wave(2, [F64_QUARTER] * 32) - - # Only lane 0 active - sim.exec_mask = 0x00000001 - res = sim.step_v_trig_f64(0, 2) - - self.assertEqual(res[0], F64_ONE) - for lane in range(1, 32): - self.assertEqual(res[lane], sentinel, f"Lane {lane} leaked despite inactive EXEC mask") - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_valu_untested_ops.py b/tests/semantic/test_valu_untested_ops.py deleted file mode 100644 index 3659349a4..000000000 --- a/tests/semantic/test_valu_untested_ops.py +++ /dev/null @@ -1,105 +0,0 @@ -"""Semantic interpreter tests for VALU ops that had no translation test. - -RDNA2 ISA definitions: - v_cmp__u64 / _i64 per lane, S0 S1 over 64-bit values, unsigned or signed (the signed order differs only - when the high words differ in bit 63); - v_cvt_f32_ubyte D = float(S0[8k+7:8k]); - v_lshlrev_b16 / v_lshrrev_b16 / v_ashrrev_i16 D[15:0] = S1.16 shifted by S0[3:0] (the amount wraps at 16, so - 16 shifts by 0); only the low half of D is checked here; - v_bcnt_u32_b32 D = popcount(S0) + S1 (32-bit wrap). -Each case runs a one-lane pixel shader through tools/rdna2spirv.py and tests/semantic/spirv_mini_interp.py and compares -with plain-Python integer references written from the lines above. Compare results leave through v_cndmask_b32_e64. -""" -import os -import struct -import sys -import unittest - -HERE = os.path.dirname(os.path.abspath(__file__)) -sys.dont_write_bytecode = True -sys.path.insert(0, HERE) - -import spirv_mini_interp as si # noqa: E402 -import support # noqa: E402 - -M32 = 0xFFFFFFFF -M64 = (1 << 64) - 1 - - -def s64(x): - return x - (1 << 64) if x >> 63 else x - - -def s16(x): - x &= 0xFFFF - return x - 0x10000 if x & 0x8000 else x - - -def run(lines): - spv = support.translate_lines("ps_valu_untested", lines + ["exp mrt0 v10, v11, v12, v13 done vm", "s_endpgm"]) - return si.run_fragment(spv)["%out_mrt0"] - - -def regs(**kw): - out = [] - for name, val in kw.items(): - out += [f"s_mov_b32 s{name[1:]}, {val & M32:#x}", f"v_mov_b32 v{name[1:]}, s{name[1:]}"] - return out - - -class Cmp64(unittest.TestCase): - VALUES = [0, 1, M64, 1 << 63, (1 << 63) - 1, 1 << 32, 0xFFFFFFFF, 0x80000000, 0xFFFFFFFF00000000, - 0x00000001FFFFFFFF, 0x7FFFFFFF80000000, 0x123456789ABCDEF0] - CONDS = {"lt": lambda a, b: a < b, "le": lambda a, b: a <= b, "gt": lambda a, b: a > b, - "ge": lambda a, b: a >= b, "eq": lambda a, b: a == b, "ne": lambda a, b: a != b} - - def test_all(self): - for cond, fn in self.CONDS.items(): - for ty in ("u64", "i64"): - for x in self.VALUES: - for y in self.VALUES: - a, b = (x, y) if ty == "u64" else (s64(x), s64(y)) - lines = (regs(v2=x & M32, v3=x >> 32, v4=y & M32, v5=y >> 32) - + ["v_mov_b32 v10, 0", "v_mov_b32 v11, 0", "v_mov_b32 v12, 0", "v_mov_b32 v13, 0", - "v_mov_b32 v14, 1", f"v_cmp_{cond}_{ty}_e64 s20, v[2:3], v[4:5]", - "v_cndmask_b32_e64 v10, v10, v14, s20"]) - with self.subTest(cond=cond, ty=ty, x=hex(x), y=hex(y)): - self.assertEqual(run(lines)[0], int(fn(a, b))) - - -class Misc(unittest.TestCase): - def one(self, op, srcs, old=0, mods=""): - regs_ = [] - for i, v in enumerate(srcs): - regs_ += [f"s_mov_b32 s{2 + i}, {v & M32:#x}", f"v_mov_b32 v{2 + i}, s{2 + i}"] - lines = regs_ + [f"s_mov_b32 s9, {old:#x}", "v_mov_b32 v10, s9", "v_mov_b32 v11, 0", "v_mov_b32 v12, 0", - "v_mov_b32 v13, 0", f"{op} v10, " + ", ".join(f"v{2 + i}" for i in range(len(srcs))) + mods] - return run(lines)[0] - - def test_cvt_f32_ubyte(self): - for x in (0, M32, 0x80402010, 0x01FF7F80, 0x12345678): - for k in range(4): - e = struct.unpack("> (8 * k)) & 0xFF)))[0] - with self.subTest(k=k, x=hex(x)): - self.assertEqual(self.one(f"v_cvt_f32_ubyte{k}", [x]), e) - - def test_shifts_b16(self): - for x in (0, 1, 0x8000, 0xFFFF, 0x7FFF, 0xA5C3): - for s in (0, 1, 15, 16, 17, 31, 0xFFF0, 0x12340010): - old = 0xABCD0000 - x16 = x & 0xFFFF - cases = {"v_lshlrev_b16": (x16 << (s & 15)) & 0xFFFF, "v_lshrrev_b16": x16 >> (s & 15), - "v_ashrrev_i16": (s16(x16) >> (s & 15)) & 0xFFFF} - for op, lo in cases.items(): - with self.subTest(op=op, x=hex(x), s=hex(s)): - self.assertEqual(self.one(op, [s, x], old=old) & 0xFFFF, lo) - - def test_bcnt(self): - for x in (0, 1, M32, 0x80000000, 0x12345678): - for c in (0, 5, M32): - with self.subTest(x=hex(x), c=hex(c)): - self.assertEqual(self.one("v_bcnt_u32_b32", [x, c]), (bin(x).count("1") + c) & M32) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_value_semantics.py b/tests/semantic/test_value_semantics.py deleted file mode 100644 index 7159fb3d0..000000000 --- a/tests/semantic/test_value_semantics.py +++ /dev/null @@ -1,956 +0,0 @@ -"""Value-level regression tests for the recent RDNA2 -> SPIR-V semantic fixes. - -Each pixel shader ends with `exp mrt0 v.., v.., v.., v..`, so four 32-bit words are checked per shader. The -expectations are written down by hand as constants and recomputed by plain-Python reference functions (checked -against each other in OracleTests). Neither the constants nor the references use the translator or the SPIR-V -interpreter. - -ISA semantics used (AMD RDNA2 ISA reference, VALU/VOP3/VOP3P chapters): - v_mul_legacy_f32 0 * anything, inf/NaN included, is +0.0; otherwise a normal IEEE binary32 multiply. - v_lshlrev_b16 D.lo = (S1.lo << (S0.lo & 15)) & 0xffff; the VOP3 form keeps D's high half. - v_lshrrev_b16 same with >>; v_ashrrev_i16 sign-extends S1.lo before the arithmetic shift. - v_pk_lshrev_b16 / per half: D.h = (S1.half <> (S0.half & 15)) & 0xffff. op_sel picks the source half - v_pk_lshlrev_b16 / used for the low result half, op_sel_hi for the high result half. - v_pk_ashrrev_i16 - v_add_nc_u16 D.lo = (S0.lo + S1.lo) & 0xffff; the VOP3 form keeps D's high half (carry is dropped). - v_sin_f16/v_cos_f16 input is a number of turns: sin/cos(S * 2*pi), rounded to binary16; high half kept. - v_add/sub/mul_f16, low halves in, D.lo out, D's high half kept; neg/abs in the VOP3 form apply to the low - v_fmac_f16 half that is read. v_fmac_f16: D.lo = S0.lo * S1.lo + D.lo. The ps_f16_vop2 words were - measured on an RX 6800 (gfx1030), wave32 and wave64 (see its .asm header). - v_cvt_f16_f32 VOP3 omod and clamp apply to the f16, after the rounding: round, omod, clamp (an RX 6800, - see ps_outmods_f16.asm). With an omod a zero or denormal f16 gives +0. - s_buffer_load_dwordx2 with destination vcc: dword 0 -> vcc_lo, dword 1 -> vcc_hi. - v_interp_mov_f32 reads the flat (provoking-vertex) input attribute; the translator must declare it Flat. - v_perm_b32 byte i = BYTE_PERMUTE({S0, S1}, S2 byte i) over 8 bytes, S1 = bytes 0-3: selector 0-7 picks - that byte; 8/9/10/11 give 0xff if bit 7 of byte 1/3/5/7 is set, else 0; 12 gives 0; - 13 and above give 0xff. - v_alignbit_b32 D = ({S0, S1} >> (S2 & 31)) & 0xffffffff. - v_med3_i32/u32 the middle of three values, compared signed or unsigned. - v_mul_hi_u32/i32 bits 63:32 of the unsigned or signed 64-bit product. - v_bcnt_u32_b32 D = popcount(S0) + S1. - v_ffbl_b32/ffbh_u32 index of the lowest set bit / count of leading zeros; 0xffffffff when S0 = 0. - v_xad_u32/add3_u32 D = (S0 ^ S1) + S2 / D = S0 + S1 + S2, both mod 2^32. - s_min/max_i32/u32 D = S0 < S1 ? S0 : S1 (max: >), SCC = 1 when S0 is chosen, so a tie gives S1 and SCC 0. - v_fmamk_f32/madmk_f32 D = S0 * K + S1, K the literal (printed vdst, src0, K, vsrc1); fmamk is fused. - v_fmaak_f32/madak_f32 D = S0 * S1 + K (printed vdst, src0, vsrc1, K). - s_ff1_i32_b32 / index of the lowest set / clear bit of S0, -1 (0xffffffff) when there is none. An inline - s_ff0_i32_b32 constant or literal source is a 32-bit value, not a lane mask (SHADER-46). - v_mad_u32_u16 / D = S0.lo * S1.lo + S2 mod 2^32, the halves zero- (u16) or sign-extended (i16); op_sel bit - v_mad_i32_i16 0/1 reads the high half of S0/S1. D is a whole dword (nothing of the old value is kept). - Measured on gfx1036 (ps_valu16_mad_sel.asm): op_sel bit 2 adds S2[31:16] zero-extended - (i16 too), bit 3 writes the result << 16, clamp saturates to u32 / i32 before that shift. - v_subrev_f16 D.lo = S1.lo - S0.lo; the high half of D is kept in the VOP2 and the VOP3 form. - 16-bit SDWA ops with dst_sel:DWORD the 16-bit result is written zero-extended: the high half of D is - (v_add/mul_f16, cleared whatever dst_unused says (measured on gfx1036, ps_sdwa_dword_hi.asm). - v_cvt_u16_f16, - v_cvt_f16_u16) - s_*_saveexec_b32/b64, a constant used as a lane mask gives lane L its bit L: of the 32-bit value for a b32 op, - s_andn2_wrexec_*, of the 64-bit value for a b64 op (inline constants sign-extended, literals with a zero - s_mov/s_not/s_and_b64 high word). cs_w32_mask_imm / cs_w64_mask_imm run every lane of a wave (LaneMaskConstants). - into EXEC or VCC - v_add_lshl_u32 D = (S0 + S1) << (S2 & 31). v_and_or_b32 D = (S0 & S1) | S2. v_xor3_b32 D = S0 ^ S1 ^ S2. - v_bfi_b32 D = (S0 & S1) | (~S0 & S2). v_bfm_b32 D = ((1 << (S0 & 31)) - 1) << (S1 & 31). - v_bfrev_b32 D = S0 with its 32 bits in reverse order. - v_mad_i32_i24 D = sext24(S0) * sext24(S1) + S2 (low 32 bits); bits 24-31 of S0/S1 are ignored. - v_mul_hi_u32_u24 D = (zext24(S0) * zext24(S1)) >> 32. - v_min/max_i32/u32, the smallest / largest operand, compared signed (_i32) or unsigned (_u32). - v_min3/max3_i32/u32 - v_cmp(x)_*_f32 GE/LG/O and the other ordered compares are false when either source is NaN; the N forms - (NGE = !(S0 >= S1), NGT, NLE, NLT, NEQ) are their negations, so true on NaN; F = 0, TRU = 1. - v_cmp(x)_*_u64/_i64 the whole 64-bit values compared unsigned / signed (the low word is never signed). - s_andn2_saveexec_b32 D = EXEC; EXEC = S0 & ~EXEC; SCC = (EXEC != 0). - s_andn2_wrexec_b32 EXEC = S0 & ~EXEC; D = EXEC (the new one); SCC = (EXEC != 0). - -The appended cases for ps_ops5/ps_ops6 also pin the op_sel source-half selection for packed shifts, which the -GPU-checked ps_ops4 does not exercise. cs_bounds (compute) pins the buffer num_records bounds checks: an -out-of-bounds store must not modify memory and an out-of-bounds load must return 0. cs_fmt_1010102 (compute) pins -the channel order of the 10:10:10:2 typed-buffer formats: the names list the channel widths from the top bit, so -2_10_10_10 (50) is R10G10B10A2 and 10_10_10_2 (44) has a 2-bit x (Mesa gfx10_format_table.py, ac_formats.c). -""" -import math -import os -import struct -import sys -import unittest -from unittest import mock - -import support -import spirv_mini_interp as si - -# Independent constants, written down by hand (derivations are in the reference functions). -EXPECTED_LEGACY_MUL = [0x00000000, 0x00000000, 0x00000000, 0x40C00000] -EXPECTED_OPS4 = [0x34000010, 0x00120800, 0xBEEF0000, 0x12343C00] -EXPECTED_OPS5 = [0x12340010, 0xBEEF0800, 0xAAAAFFFF, 0xDEADBC00] -EXPECTED_OPS6 = [0xF800FFFF, 0x01000010, 0x00800800, 0x8000FFF0] -EXPECTED_OPS7 = [0x00FF8077, 0xFF0000FF, 0x89ABCDEF, 0x00070003] -EXPECTED_OPS8 = [0x80000000, 0xBFFFFFFF, 0x000F100E, 0x0F0F0F1F] -EXPECTED_VCC_X2 = [0x11223344, 0x55667788, 0x00000000, 0x00000000] -EXPECTED_F16_VOP2 = [0xAAAA4000, 0xAAAAC000, 0xAAAA3A00, 0x42003F00] # hardware-measured -EXPECTED_CVT_F16_OUT_MODS = [0xAAAA3C00, 0xAAAA3E00, 0x7C000000, 0x3C000000] -EXPECTED_SDWA_DWORD_HI = [0x00004000, 0x00000003, 0x00004700, 0x0000C000] # hardware-measured (gfx1036) -EXPECTED_FLAT = [0x00000101, 0x00000102, 0x3F000000, 0x3E800000] -EXPECTED_SCC_MINMAX = [0x00030205, 0x00030207, 0x00030209, 0x00030203] -EXPECTED_FMA_LITERAL = [0x41B80000, 0x41800000, 0x40E00000, 0x41A40000] -EXPECTED_BOUNDS = {0x00: 0x12345678, 0x04: 0x12345678, 0x08: 0x00000000, 0x0C: 0xEEEEEEEE} -EXPECTED_FMT_1010102 = {0x00: 0x00000000, 0x04: 0x3F800000, 0x08: 0x00000000, 0x0C: 0x3F800000, - 0x10: 0x3F800000, 0x14: 0x00000000, 0x18: 0x3F800000, 0x1C: 0x00000000, - 0x20: 0x00000000, 0x24: 0x3F800000, 0x28: 0x00000000, 0x2C: 0x3F800000, - 0x30: 0xC00FFC00, 0x34: 0x003FF003, 0x38: 0xE00003FF, 0x3C: 0xFFE00003} -EXPECTED_SFF_IMM = [0x00000002, 0x00000001, 0x00000014, 0x00000010] -EXPECTED_VALU16_MAD = [0x00000002, 0x00030002, 0x00008000, 0x00000004] -EXPECTED_VALU16_SUBREV = [0xAAAABC00, 0xAAAAC000, 0xAAAA3C00, 0x42003800] -EXPECTED_VALU16_MAD_SEL = [0x00008003, 0xDB880000, 0xFFFFFFFF, 0x80000000] # hardware-measured -# ps_sdwa_f16_const, measured on gfx1036 (the .asm header): f16 inline constant, then src_sel -EXPECTED_SDWA_F16_CONST = [0xAAAA3800, 0xAAAA1C00, 0xAAAA3E00, 0xAAAA73F0] -# ps_vint_*: 32-bit integer VALU ops on the heap VINT_HEAP (h0..h7, the words check.py's VINT_ENV seeds). -VINT_HEAP = (0xAB800000, 0x12FFFFFE, 0x00000021, 0x80000001, 0x7FFFFFFE, 0xF0F0F0F0, 0x12345678, 0xFFFFFFFF) -EXPECTED_VINT = {"ps_vint_logic3": [0xFFFFFFFE, 0xBBB05070, 0x1D3B5977, 0x123F5F7E], - "ps_vint_bits": [0xFFFFFFFE, 0x40000000, 0x1E6A2C48, 0x000001D5], - "ps_vint_mul24": [0x13345678, 0xFFFFFFFD, 0x00007FFF, 0x0000FFFF], - "ps_vint_minmax": [0x7FFFFFFE, 0x80000001, 0x80000001, 0x7FFFFFFE], - "ps_vint_minmax3": [0xF0F0F0F0, 0xAB800000, 0xF0F0F0F0, 0xAB800000]} -EXPECTED_VCMP_F32_NAN = [0x0000376C, 0x0000FD5B, 0x0000D36C, 0x00000FE7] # derivation in ps_vcmp_f32_nan.asm -EXPECTED_VCMP_64 = [0x0000B3C4, 0x000091E6, 0x00006787, 0x00007C93] # derivation in ps_vcmp_64.asm -EXPECTED_ANDN2_EXEC = [1, 8, 16, 2064, 2068, 3, 20, 1544] # derivation in cs_w32_andn2_exec.asm -VCMP_F32_HEAP = (0x7FC10001, 0x3F800000, 0x40000000) # NaN, 1.0, 2.0 -# Four (A, B) pairs as A.lo A.hi B.lo B.hi (ps_vcmp_64.asm header). -VCMP_64_HEAP = (0x80000000, 0, 1, 0, 0xFFFFFFFF, 0xFFFFFFFF, 1, 0, 1, 0, 0x80000000, 0, 7, 5, 7, 5) - - -def _f32_bits(x): - return struct.unpack("> (16 * n)) & 0xFFFF - - def one(shalf, vhalf): - amount = half(sh, shalf) & 15 - x = half(val, vhalf) - if kind == "ashr": - return (_s16(x) >> amount) & 0xFFFF - return ((x << amount) if kind == "lshl" else (x >> amount)) & 0xFFFF - - return one(sel[0], sel[1]) | (one(selhi[0], selhi[1]) << 16) - - -def reference_ops4(): - v0, shift = 0x12348001, 0x00080004 - sin = _half(math.sin(_unhalf(0x3400) * 2.0 * math.pi)) # 0.25 turns -> 1.0 - add = (0xBEEF0000 & 0xFFFF0000) | ((0x0001 + 0xFFFF) & 0xFFFF) # carry out of the low half is dropped - return [_pk_shift("lshl", shift, v0), _pk_shift("lshr", shift, v0), add, - 0x12340000 | sin] - - -def reference_ops5(): - lshl = 0x12340000 | ((0x8001 << 4) & 0xFFFF) - lshr = 0xBEEF0000 | ((0x8001 >> 4) & 0xFFFF) - ashr = 0xAAAA0000 | ((_s16(0xFFF0) >> 4) & 0xFFFF) - cos = 0xDEAD0000 | _half(math.cos(_unhalf(0x3800) * 2.0 * math.pi)) # 0.5 turns -> -1.0 - return [lshl, lshr, ashr, cos] - - -def reference_ops6(): - return [_pk_shift("ashr", 0x00040004, 0x8000FFF0), - # op_sel:[1,0,0] -> low result shifts by the high half of src0; op_sel_hi:[0,0,0] -> high result - # shifts by the low half. Both use the low half of the value. - _pk_shift("lshl", 0x00040008, 0x12348001, sel=(1, 0), selhi=(0, 0)), - _pk_shift("lshr", 0x00040008, 0xBEEF8001, sel=(1, 0), selhi=(0, 0)), - _pk_shift("ashr", 0, 0x8000FFF0)] - - -def _perm(s0, s1, sel): - data = list(s1.to_bytes(4, "little")) + list(s0.to_bytes(4, "little")) - out = 0 - for i in range(4): - k = (sel >> (8 * i)) & 0xFF - if k >= 13: - b = 0xFF - elif k == 12: - b = 0 - elif k >= 8: - b = 0xFF if data[2 * (k - 8) + 1] & 0x80 else 0 - else: - b = data[k] - out |= b << (8 * i) - return out - - -def _s(v): - return v - (1 << 32) if v & 0x80000000 else v - - -def reference_ops7(): - m = 0xFFFFFFFF - med_i = sorted([_s(0xFFFFFFFB), 7, 3])[1] & m - med_u = sorted([0xFFFFFFFB, 7, 3])[1] - return [_perm(0x80112233, 0x4455E677, 0x0C0D0700), - _perm(0x80112233, 0x4455E677, 0x0B0A0908), # sign of bytes 1, 3, 5, 7: E6, 44, 22, 80 - (((0x12345678 << 32) | 0x9ABCDEF0) >> (36 & 31)) & m, - ((med_u << 16) + med_i) & m] - - -def reference_ops8(): - m = 0xFFFFFFFF - bcnt = bin(0xF0F00001).count("1") + 5 - ffbl = (0x00010000 & -0x00010000).bit_length() - 1 - ffbh = 32 - 0x00010000.bit_length() - xad = ((0xF0F0F0F0 ^ m) + 1) & m - signed_high = ((_s(0xFFFFFFFE) * 0x40000000) >> 32) & m - return [(0x80000001 * 0xFFFFFFFF) >> 32, - signed_high ^ 0x40000000, - ((ffbh << 16) + (ffbl << 8) + bcnt) & m, - (xad + 16 + m) & m] # v_ffbh_u32(0) = 0xffffffff - - -def reference_scc_minmax(): - def minmax(op, x, y): - """(D, SCC) of s_min/s_max _i32/_u32 on 32-bit words: SCC = 1 only when S0 is the one chosen.""" - kx, ky = (_s(x), _s(y)) if op.endswith("i32") else (x, y) - pick = kx < ky if op.startswith("min") else kx > ky - return x if pick else y, int(pick) - - words = [] - m1 = 0xFFFFFFFF # the inline constant -1 as a register word - for op, tie, strict in (("min_i32", 5, (m1, 1)), ("max_i32", 7, (1, m1)), - ("min_u32", 9, (1, m1)), ("max_u32", 3, (m1, 1))): - d, scc_tie = minmax(op, tie, tie) - _, scc_strict = minmax(op, *strict) - words.append(d | ((1 if scc_tie else 2) << 8) | ((3 if scc_strict else 4) << 16)) - return words - - -def reference_fma_literal(): - # Every product and sum is exact in f32, so fused and unfused give the same bits. - k1, k2 = 10.0, 0.5 - return [_f32_bits(2.0 * k1 + 3.0), _f32_bits(2.0 * 3.0 + k1), # fmamk, fmaak - _f32_bits(4.0 * k2 + 5.0), _f32_bits(4.0 * 5.0 + k2)] # madmk, madak - - -def reference_f16_vop2(): - a, b, acc = _unhalf(0x3E00), _unhalf(0x3800), _unhalf(0x3C00) # low halves: 1.5, 0.5, accumulator 1.0 - return [0xAAAA0000 | _half(a + b), 0xAAAA0000 | _half(-a - abs(b)), 0xAAAA0000 | _half(a * b), - 0x42000000 | _half(a * b + acc)] - - -def reference_cvt_f16_out_mods(): - def f16(x): # round to nearest even; struct refuses what rounds past 65504, which is inf - try: - return _half(x) - except OverflowError: - return 0xFC00 if x < 0 else 0x7C00 - - def cvt(x, omod=None, clamp=False): - h = f16(x) - if omod is not None and h & 0x7C00 != 0x7C00: - v = _unhalf(h) * omod if h & 0x7C00 else 0.0 - h = f16(v) if abs(v) >= 2.0 ** -14 else 0 # zero and denormal: +0 - return _half(min(max(_unhalf(h), 0.0), 1.0)) if clamp else h - - return [0xAAAA0000 | cvt(1.5, clamp=True), 0xAAAA0000 | cvt(0.375, 4), - cvt(2.0 ** -15, 2) | cvt(65520.0, 0.5) << 16, cvt(-0.0, 2) | cvt(2.0, 2, clamp=True) << 16] - - -def reference_vcc_x2(): - return [0x11223344, 0x55667788, 0, 0] - - -def reference_flat(): - return [0x101, 0x101 + 1, _f32_bits(0.5), _f32_bits(0.25)] - - -def reference_bounds(): - # num_records = 16: store 0 and load 0 are in bounds, the store and load at offset 16 are not. The OOB load - # feeds a store of 0 into offset 8; the OOB store must leave offset 16 untouched (it is not in the map). - return {0x00: 0x12345678, 0x04: 0x12345678, 0x08: 0, 0x0C: 0xEEEEEEEE} - - -WIDTHS_1010102 = {50: (10, 10, 10, 2), # 2_10_10_10_UNORM, R10G10B10A2 - 44: (2, 10, 10, 10)} # 10_10_10_2_UNORM - - -def _unorm_unpack(word, widths): - out, bit = [], 0 - for w in widths: - out.append(_f32_bits(((word >> bit) & ((1 << w) - 1)) / ((1 << w) - 1))) - bit += w - return out - - -def _unorm_pack(values, widths): - word, bit = 0, 0 - for v, w in zip(values, widths): - word |= round(min(max(v, 0.0), 1.0) * ((1 << w) - 1)) << bit - bit += w - return word - - -def reference_fmt_1010102(): - # Every field is 0 or full scale, so the decoded floats are exact. - src50, src44, stored = 0xC00FFC00, 0x003FF003, (1.0, 0.0, 0.5, 1.0) - words = (_unorm_unpack(src50, WIDTHS_1010102[50]) + _unorm_unpack(src44, WIDTHS_1010102[44]) - + _unorm_unpack(src50, WIDTHS_1010102[50]) - + [src50, src44, _unorm_pack(stored, WIDTHS_1010102[50]), _unorm_pack(stored, WIDTHS_1010102[44])]) - return {4 * i: w for i, w in enumerate(words)} - - -def _ff1(x): - """Index of the lowest set bit of a 32-bit value, 0xffffffff if none.""" - x &= 0xFFFFFFFF - return (x & -x).bit_length() - 1 if x else 0xFFFFFFFF - - -def reference_sff_imm(): - # ps_sff_imm: s_ff1 of the inline constant 4 and of the literal 0x00100000; s_ff0 of the inline constant 61 - # (0b111101) and of the literal 0x0000ffff (the lowest clear bit is the lowest set bit of ~S0). - return [_ff1(4), _ff1(~61), _ff1(0x00100000), _ff1(~0x0000FFFF)] - - -def _mad_32_16(signed, s0, s1, s2, sel=(0, 0)): - """v_mad_u32_u16 / v_mad_i32_i16: the selected 16-bit halves, extended, multiplied, plus S2, mod 2^32.""" - a, b = (s0 >> (16 * sel[0])) & 0xFFFF, (s1 >> (16 * sel[1])) & 0xFFFF - if signed: - a, b = _s16(a), _s16(b) - return (a * b + s2) & 0xFFFFFFFF - - -def reference_valu16_mad(): - v0, v1, v3, v5, v6, v7 = 0x1234FFFF, 0x5678FFFE, 0x00030000, 0x00018000, 0xFFFF7FFF, 0x40000000 - return [_mad_32_16(False, v0, v1, v3), _mad_32_16(True, v0, v1, v3), _mad_32_16(True, v5, v6, v7), - _mad_32_16(True, v5, v6, 5, sel=(1, 1))] - - -def reference_valu16_mad_sel(): - # op_sel bit 2 adds S2[31:16] zero-extended; bit 3 shifts the result left by 16; clamp saturates the sum. - v0, v1, v3, v5, v6, v7 = 0x1234FFFF, 0x5678FFFE, 0x8001FFF0, 0x00018000, 0xFFFF7FFF, 0x80000000 - x = _mad_32_16(True, v0, v1, v3 >> 16) - y = (_mad_32_16(False, v0, v1, v3, sel=(1, 0)) << 16) & 0xFFFFFFFF - z = min((v0 & 0xFFFF) * (v0 & 0xFFFF) + v3, 0xFFFFFFFF) - w = max(-(1 << 31), min((1 << 31) - 1, -32768 * 32767 - (1 << 31))) & 0xFFFFFFFF # v5.lo * v6.lo + v7 - return [x, y, z, w] - - -def reference_sdwa_dword_hi(): - # Low/high halves of the sources: v2.lo 1.0, v4.lo 3.0, v4.hi -2.0, v6.hi 7. Each result is the 16-bit value - # alone; nothing of the destinations' 0xdeadbeef is left. - one, three, m_two = _unhalf(0x3C00), _unhalf(0x4200), _unhalf(0xC000) - return [_half(one + one), int(three) & 0xFFFF, _half(7.0), _half(one * m_two)] - - -def reference_valu16_subrev(): - a, b, d = _unhalf(0x3E00), _unhalf(0x3800), _unhalf(0x3C00) # low halves: v0 1.5, v1 0.5, v5 1.0 - return [0xAAAA0000 | _half(b - a), 0xAAAA0000 | _half(-b - a), 0xAAAA0000 | _half(min(1.0, b + a)), - 0x42000000 | _half(a - d)] - - -def reference_sdwa_f16_const(): - # An f16 float inline constant is its f16 bits over a zero high half; an integer op reads 1.0 as its f32 bits. - # src_sel then picks a zero-extended field of those 32 bits, like a register's. - def sel(word, off, width): - return (word >> off) & ((1 << width) - 1) - v1, s8 = 0x64003800, 0x3C000000 - x = _unhalf(sel(_half(1.0), 16, 16)) + _unhalf(sel(v1, 0, 16)) # +0.0 + 0.5 - y = _unhalf(sel(_half(2.0), 8, 8)) * _unhalf(sel(v1, 16, 16)) # 2^-18 * 1024.0 - z = _unhalf(sel(s8, 16, 16)) + _unhalf(sel(v1, 0, 16)) # 1.0 + 0.5 - w = float(sel(struct.unpack(" f16 - return [0xAAAA0000 | _half(v) for v in (x, y, z, w)] - - -def reference_vint(): - """The ps_vint_* words from the ISA definitions, on the operands each .asm passes (hN = VINT_HEAP[N]).""" - h = VINT_HEAP - m = 0xFFFFFFFF - def i32(x): - return x - (1 << 32) if x & 0x80000000 else x - def s24(x): - x &= 0xFFFFFF - return x - (1 << 24) if x & 0x800000 else x - def bfm(size, offset): - return (((1 << (size & 31)) - 1) << (offset & 31)) & m - def bfrev(x): - return int(f"{x:032b}"[::-1], 2) - return {"ps_vint_logic3": [((h[3] + h[4]) << (h[2] & 31)) & m, (h[6] & h[5]) | h[0], h[5] ^ h[6] ^ h[7], - (h[5] & h[6]) | (~h[5] & h[1] & m)], - "ps_vint_bits": [bfm(h[7], h[2]), bfm(h[2], h[1]), bfrev(h[6]), bfrev(h[0])], - "ps_vint_mul24": [(s24(h[0]) * s24(h[1]) + h[6]) & m, (s24(h[4]) * s24(h[3]) + h[7]) & m, - ((h[0] & 0xFFFFFF) * (h[1] & 0xFFFFFF)) >> 32, - ((h[7] & 0xFFFFFF) * (h[7] & 0xFFFFFF)) >> 32], - "ps_vint_minmax": [max(h[3], h[4], key=i32), min(h[3], h[4], key=i32), max(h[3], h[4]), min(h[3], h[4])], - "ps_vint_minmax3": [max(h[4], h[3], h[5]), max(h[0], h[6], h[3]), min(h[5], h[4], h[6], key=i32), - min(h[7], h[6], h[0], key=i32)]} -def _pack_nibbles(ops, pairs, test): - """Bit 4*k + i of the word: op k on pair i.""" - return sum(int(test(op, *pair)) << (4 * k + i) for k, op in enumerate(ops) for i, pair in enumerate(pairs)) -def reference_vcmp_f32_nan(): - nan = float("nan") - pairs = ((nan, 1.0), (1.0, 2.0), (2.0, 1.0), (1.0, 1.0)) - ordered = {"lt": lambda a, b: a < b, "le": lambda a, b: a <= b, "gt": lambda a, b: a > b, - "ge": lambda a, b: a >= b, "eq": lambda a, b: a == b, "lg": lambda a, b: a < b or a > b, - "o": lambda a, b: not (math.isnan(a) or math.isnan(b)), "f": lambda a, b: False} - def test(op, a, b): - if op == "tru": - return True - if op.startswith("n"): # nge/ngt/nle/nlt/neq: the negated ordered compare - return not ordered[op[1:]](a, b) - return ordered[op](a, b) - return [_pack_nibbles(ops, pairs, test) for ops in (("ge", "lg", "neq", "nge"), ("ngt", "nle", "nlt", "tru"), - ("ge", "lg", "nge", "nlt"), ("neq", "o", "tru", "f"))] -def reference_vcmp_64(): - w = VCMP_64_HEAP - pairs = [((w[4 * i + 1] << 32) | w[4 * i], (w[4 * i + 3] << 32) | w[4 * i + 2]) for i in range(4)] - def test(op, a, b): - cond, ty = op.split("_") - if ty == "i64": - a, b = (x - (1 << 64) if x >> 63 else x for x in (a, b)) - return {"lt": a < b, "le": a <= b, "gt": a > b, "ge": a >= b, "eq": a == b, "ne": a != b}[cond] - return [_pack_nibbles(ops, pairs, test) for ops in (("lt_u64", "le_u64", "gt_u64", "ge_u64"), - ("lt_i64", "le_i64", "gt_i64", "ge_i64"), - ("ne_u64", "eq_i64", "ne_i64", "lt_i64"), - ("gt_u64", "ge_i64", "le_u64", "ne_i64"))] -def reference_andn2_exec(): - def popcount(m): - return bin(m).count("1") - def ff1(m): - return (m & -m).bit_length() - 1 if m else -1 - lanes = range(32) - mask = lambda f: sum(1 << i for i in lanes if f(i)) # noqa: E731 - out = [] - # 1) saveexec, VCC = bit 3 clear, EXEC = 0xffff - vcc, exec_ = mask(lambda i: i & 8 == 0), 0x0000FFFF - d, exec_ = exec_, vcc & ~exec_ & 0xFFFFFFFF - out += [1 if exec_ else 2, popcount(exec_), popcount(d), popcount(exec_) << 8 | ff1(exec_)] - # 2) wrexec, VCC = lanes 16..31, EXEC = 0x0f0f0f0f - vcc, exec_ = mask(lambda i: i >= 16), 0x0F0F0F0F - exec_ = vcc & ~exec_ & 0xFFFFFFFF - d = exec_ - out += [popcount(exec_) << 8 | ff1(exec_), 3 if exec_ else 4, ff1(d)] - # 3) both with an S0 inside EXEC: EXEC and SCC become 0 - vcc = mask(lambda i: i < 8) - e1, e2 = vcc & ~0x0000FFFF & 0xFFFFFFFF, vcc & ~0xFFFFFFFF & 0xFFFFFFFF - out.append((5 if e1 else 6) << 8 | (7 if e2 else 8)) - return out -def _isg1_dxbc(elements): - """A DXBC container with one ISG1 input signature. elements: (register, mask, system value, component type).""" - payload = bytearray(struct.pack(" 1); v_cmpx forms too. - self.check("ps_vcmp_64", EXPECTED_VCMP_64, push_constants=[0x1000, 0, 64, 0] + [0] * 28, - memory={0x1000 + 4 * i: w for i, w in enumerate(VCMP_64_HEAP)}) - - def test_s_andn2_saveexec_and_wrexec_b32(self): - # A 32-thread wave32: saveexec returns the old EXEC, wrexec the new one; EXEC = S0 & ~EXEC and SCC is - # whether it is non-zero (cs_w32_andn2_exec.asm). - spv = support.translate_fixture("cs_w32_andn2_exec", fssm=_fssm(0x8088, (32, 1, 1))) - memory = si.run_workgroup( - spv, 32, 32, inputs_for=lambda i: {"%wg_id": (0, 0, 0), "%local_id": (i, 0, 0), "%sg_lane": i}, - push_constants=[0, 0, 0x1000, 0x31016FAC] + [0] * 28, memory={}) - self.assertEqual(sorted(memory), list(range(0, 32, 4)), "lane 0 stores out[0..7] only") - self.assertEqual([memory[4 * k] for k in range(8)], EXPECTED_ANDN2_EXEC) - - -class ReadLog(dict): - """A {byte_address: word} memory for run_fragment that records the address of every load.""" - - def __init__(self, *args): - super().__init__(*args) - self.reads = [] - - def get(self, key, default=None): - self.reads.append(key) - return super().get(key, default) - - -VEC_REGION = 0x1000 - - -def _pattern_word(offset): - # byte n of the region holds 0x40 + n (as in the measurement), so an unaligned dword is its four exact bytes - return int.from_bytes(bytes((0x40 + offset + k) & 0xFF for k in range(4)), "little") - - -class RawBufferTailBounds(unittest.TestCase): - """Raw MUBUF loads (V# stride 0) are bounded per dword, measured on an AMD Radeon RX 6800 (gfx1030), raw - compute kernel, wave32 and wave64, V# word3 0x31016fac (OOB_SELECT 3): - - O = inst_offset + soffset + (offen ? vaddr : 0) one byte offset, nothing truncated - dword i = data at base + O + 4*i (byte exact) if O + 4*i + 4 <= NUM_RECORDS, else 0 (and not read) - - Each case is a one-thread compute program written by hand around one buffer_load (row names of the oracle's - model in the comments; rule in docs/design.md, Buffer bounds checking). It runs in spirv_mini_interp with a - memory whose every byte address holds the dword starting there; the test asserts the words stored and the - exact addresses loaded. Since 2e8101b the interpreter raises on a PhysicalStorageBuffer access that is not - 4-byte aligned (undefined under the translator's Aligned 4), so a row that loads at an unaligned O sets - base_low to make base + O aligned: the bound sees only O, so the measured O / NUM_RECORDS pairs are kept, but - byte-exact data at an unaligned address is no longer checked here. The last tests pin paths the measurement did not cover and that keep their old check - of the first byte: structured buffers and idxen (OOB_SELECT 1). - """ - - def run_program(self, load_lines, n, *, nr, base_low=0, word1=0, word3=0x31016FAC, offset=0, extra=()): - lines = ["v_cmpx_eq_u32_e32 0, v0", - f"s_mov_b32 s4, {VEC_REGION + base_low:#x}", f"s_mov_b32 s5, {word1:#x}", - f"s_mov_b32 s6, {nr:#x}", f"s_mov_b32 s7, {word3:#x}", - f"v_mov_b32 v1, {offset:#x}", *extra, *load_lines, "s_waitcnt vmcnt(0)"] - lines += [f"buffer_store_dword v{2 + i}, off, s[0:3], 0 offset:{4 * i}" for i in range(n)] - lines.append("s_endpgm") - spv = support.translate_lines("cs_vec_tail", lines, fssm=CS_BOUNDS_FSSM) - memory = ReadLog({VEC_REGION + k: _pattern_word(k - base_low) for k in range(-4, 0x40)}) - support.run_fragment(spv, inputs={"%wg_id": (0, 0, 0), "%local_id": (0, 0, 0)}, - push_constants=[0, 0, 0x100, 0x31016FAC] + [0] * 28, memory=memory) - words = [dict.get(memory, 4 * i) for i in range(n)] - return words, [a - VEC_REGION - base_low for a in memory.reads] - - def check(self, line, n, want, **kw): - """want: per dword, the byte offset O + 4*i whose data it holds, or None for 0 (and no load).""" - words, reads = self.run_program([line], n, **kw) - self.assertEqual([f"{w:#010x}" for w in words], - [f"{0 if o is None else _pattern_word(o):#010x}" for o in want], line) - self.assertEqual([hex(r) for r in reads], [hex(o) for o in want if o is not None], line) - - def test_single_dword_needs_all_four_bytes(self): - # vx1-k0[1], lane 15: offset 0xf, NR 18 -> 0 (a start-only check, 0xf < 18, would read) - self.check("buffer_load_dword v2, v1, s[4:7], 0 offen", 1, [None], nr=18, offset=0xF) - # offset 0xe, NR 18: bytes 0xe..0x11 fit -> data (base_low 2: base + O aligned, see the class docstring) - self.check("buffer_load_dword v2, v1, s[4:7], 0 offen", 1, [0xE], nr=18, offset=0xE, base_low=2) - - def test_multi_dword_load_is_bounded_per_dword(self): - # vx4a-k0[4..7], lane 3: x4 at offset 3, NR 18 -> d0..d2 data, d3 (bytes 15..18) 0 - # (base_low here and below makes base + O aligned for the interpreter, see the class docstring) - self.check("buffer_load_dwordx4 v[2:5], v1, s[4:7], 0 offen", 4, [3, 7, 0xB, None], nr=18, offset=3, - base_low=1) - # lane 2: d3 = bytes 14..17 fits -> all four data - self.check("buffer_load_dwordx4 v[2:5], v1, s[4:7], 0 offen", 4, [2, 6, 0xA, 0xE], nr=18, offset=2, - base_low=2) - # vmix2-k0[4..7]: x4 off offset:13, NR 20 -> data, 0, 0, 0 - self.check("buffer_load_dwordx4 v[2:5], off, s[4:7], 0 offset:13", 4, [13, None, None, None], nr=20, - base_low=3) - # x2 at 8, NR 0xe: d0 data, d1 0 - self.check("buffer_load_dwordx2 v[2:3], v1, s[4:7], 0 offen", 2, [8, None], nr=0xE, offset=8) - - def test_offsets_are_summed_before_the_check(self): - # vx1-k*[7..13] style: soffset 3 + inst_offset 2 + vaddr 0xb = 0x10; NR 0x16 -> x2: data, 0 - self.check("buffer_load_dwordx2 v[2:3], v1, s[4:7], s8 offen offset:2", 2, [0x10, None], - nr=0x16, offset=0xB, extra=("s_mov_b32 s8, 3",)) - - def test_base_low_bits_kept_in_the_address_not_in_the_bound(self): - # vx4a-k3[4], [7] measured base & 3 = 3 with x4 at offset 3, NR 18 -> d0..d2 data at base + 3.., d3 0. - # Stand-in at offset 5 so that base + O is aligned for the interpreter (class docstring): d0..d2 data, - # d3 (bytes 0x11..0x14) 0; a bound that added base & 3 would also zero d2 (3 + 5 + 8 + 4 = 0x14 > 18). - self.check("buffer_load_dwordx4 v[2:5], v1, s[4:7], 0 offen", 4, [5, 9, 0xD, None], - nr=18, offset=5, base_low=3) - - def test_num_records_zero_reads_nothing(self): - self.check("buffer_load_dwordx4 v[2:5], v1, s[4:7], 0 offen", 4, [None] * 4, nr=0, offset=0) - - # Modes 1 and 2 (OOB_SELECT) check the index or NUM_RECORDS once for the whole load; modes 0 and 3 are per dword - # (docs/buffer_bounds.md; tests/semantic/test_buffer_oob_select.py has the full table). - def test_structured_buffer_keeps_its_first_byte_check(self): - # OOB_SELECT 1, stride 4, NR 2 records (8 bytes): no idxen, so index 0 < 2 and every dword is loaded - self.check("buffer_load_dwordx4 v[2:5], v1, s[4:7], 0 offen", 4, [4, 8, 0xC, 0x10], - nr=2, offset=4, word1=4 << 16, word3=0x11016FAC) - - def test_idxen_keeps_its_first_byte_check(self): - # OOB_SELECT 1, idxen with index 0 and offset:0xc, NR 0xe: index 0 < 0xe, so both dwords are loaded - self.check("buffer_load_dwordx2 v[2:3], v1, s[4:7], 0 idxen offset:12", 2, [0xC, 0x10], nr=0xE, offset=0, - word3=0x11016FAC) - - def test_store_is_per_dword(self): - # x2 at 0xc with NR 0x10: the first dword ends at 0x10 and lands, the second (ends at 0x14) is dropped - lines = ["v_cmpx_eq_u32_e32 0, v0", f"s_mov_b32 s4, {VEC_REGION:#x}", "s_mov_b32 s5, 0", - "s_mov_b32 s6, 0x10", "s_mov_b32 s7, 0x31016fac", "v_mov_b32 v1, 0xc", - "v_mov_b32 v2, 0x11111111", "v_mov_b32 v3, 0x22222222", - "buffer_store_dwordx2 v[2:3], v1, s[4:7], 0 offen", "s_endpgm"] - spv = support.translate_lines("cs_vec_store", lines, fssm=CS_BOUNDS_FSSM) - memory = {} - support.run_fragment(spv, inputs={"%wg_id": (0, 0, 0), "%local_id": (0, 0, 0)}, - push_constants=[0, 0, 0x100, 0x31016FAC] + [0] * 28, memory=memory) - self.assertEqual(memory, {VEC_REGION + 0xC: 0x11111111}) - - -class MeasuredBoundsShaders(unittest.TestCase): - """The four GPU tests of the measured SMEM / raw MUBUF rules (runtime/test/shaders/cs_smem_bounds.asm, - cs_smem_stride_align.asm, cs_smem_sload_neg.asm, cs_buf_tail.asm), run here in the interpreter on a 256-byte - heap filled with 0xee like vk_compute_test's. The words are the ones derived in each .asm header.""" - - WANT = { - "cs_smem_bounds": [0, 0x5EED0010, 0x5EED000C, 0, 0x5EED000C, 0x5EED0010, 0, 0], - "cs_smem_stride_align": [0x5EED0010, 0, 0, 0x5EED0000, 0x5EED0000, 0x5EED0000, 0x5EED0000, 0x5EED0004], - "cs_smem_sload_neg": [0x5EED0004, 0x5EED0000, 0x5EED0004, 0x5EED0004, 0x5EED0008, 0x5EED000C, - 0xEEEEEEEE, 0xEEEEEEEE], - # SHADER-328: constant and run-time SGPR offsets agree; out[4..7] are not written (heap fill) - "cs_smem_sconst_off": [0, 0x5EED0018, 0x5EED0018, 0x5EED0014, 0xEEEEEEEE, 0xEEEEEEEE, 0xEEEEEEEE, 0xEEEEEEEE], - "cs_buf_tail": [0, 0x5EED000C, 0x5EED0008, 0x5EED000C, 0, 0, 0x5EED0010, 0], - "cs_oob_select": [0x5EED000C, 0, 0x5EED0014, 0, 0x5EED0018, 0xEEEEEEEE, 0, 0], - "cs_oob_tail": [0, 0, 0x5EED0010, 0, 0xBEEF0000, 0xEEEEEEEE, 0, 0x5EED0010], - } - - def test_words(self): - for name, want in self.WANT.items(): - with self.subTest(shader=name): - spv = support.translate_fixture(name, fssm=CS_BOUNDS_FSSM) - memory = {a: 0xEEEEEEEE for a in range(0, 0x100, 4)} - support.run_fragment(spv, inputs={"%wg_id": (0, 0, 0), "%local_id": (0, 0, 0)}, - push_constants=[0, 0, 0xFFFFFFFF, 0x31016FAC] + [0] * 28, memory=memory) - self.assertEqual([f"{memory[4 * i]:#010x}" for i in range(8)], [f"{w:#010x}" for w in want]) - self.assertEqual(set(memory), set(range(0, 0x100, 4)), "nothing written outside the heap") - - -class LaneMaskConstants(unittest.TestCase): - """runtime/test/shaders/cs_w32_mask_imm.asm and cs_w64_mask_imm.asm: a constant read as a lane mask (saveexec, - wrexec, s_and_b64 / s_not_b64 / s_mov_b64 into EXEC or VCC) gives lane L its bit L, not bit 0 for every lane. - Run on all lanes of one wave (32 on a 32-wide subgroup, 64 on a 64-wide one, no --wave64-emulate) with a heap - of 0xee bytes; the words are the GPU check's (check.py CS_DUMPS), derived by hand in each .asm header.""" - - WANT = {"cs_w32_mask_imm": (32, [2056, 20, 2, 6152, 2050, 4112, 258, 32]), - "cs_w64_mask_imm": (64, [2056, 1084, 828, 2052, 319, 2104, 516, 2064])} - # Bit 0 of the constant for every lane, the translation before the fix (in the .asm headers). - OLD = {"cs_w32_mask_imm": [0xFFFFFF00, 32, 32, 0xFFFFFF00, 2072, 0xFFFFFF00, 0xFFFFFF00, 32], - "cs_w64_mask_imm": [0xFFFFFF00] * 7 + [2080]} - - def run_words(self, name, lanes): - sys.path.insert(0, os.path.join(support.ROOT, "runtime", "test", "shaders")) - from compute_fixture import compute_header - header = compute_header(os.path.join(support.ROOT, "runtime", "test", "shaders", name + ".asm")) - spv = support.translate_fixture(name, fssm=bytes(header)) - memory = {a: 0xEEEEEEEE for a in range(0, 0x100, 4)} - si.run_workgroup(spv, lanes, lanes, - inputs_for=lambda i: {"%wg_id": (0, 0, 0), "%local_id": (i, 0, 0), "%sg_lane": i}, - push_constants=[0, 0, 0xFFFFFFFF, 0x31016FAC] + [0] * 28, memory=memory) - self.assertEqual(set(memory), set(range(0, 0x100, 4)), "nothing written outside the heap") - return [memory[4 * i] for i in range(8)] - - def test_words(self): - for name, (lanes, want) in self.WANT.items(): - with self.subTest(shader=name): - got = self.run_words(name, lanes) - self.assertEqual([f"{w:#010x}" for w in got], [f"{w:#010x}" for w in want]) - self.assertNotEqual(got, self.OLD[name]) - - def test_words_follow_from_the_masks(self): - # Plain-Python reference: word = set lanes | lowest lane << 8 of each case's resulting mask. - def word(m): - return 0xFFFFFF00 if m == 0 else bin(m).count("1") | ((m & -m).bit_length() - 1) << 8 - m32, m64 = 0xFFFFFFFF, (1 << 64) - 1 - w32 = [word(0xFF00 & m32), word(0x55555555 | 0xFF), word(5 & m32), word(0xFF00FF00 & ~0xFFFF & m32), - word(0x3FF & ~0xFF), word(-16 & m32 & ~0xFFFF), word(0x80000002 | 0), word(-1 & m32)] - w64 = [word(0xFF00 & m64), word(-16 & m64), word(-8 & m64 & ~0x10), word(0xFF00 & ~0xF0F0 & m64), - word(-2 & m64), word(~0xFF & m64), word(0x3C), bin(0xFF00FF).count("1") | 8 << 8] - self.assertEqual(w32, self.WANT["cs_w32_mask_imm"][1]) - self.assertEqual(w64, self.WANT["cs_w64_mask_imm"][1]) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_vcmp16_opsel.py b/tests/semantic/test_vcmp16_opsel.py deleted file mode 100644 index 100ea7480..000000000 --- a/tests/semantic/test_vcmp16_opsel.py +++ /dev/null @@ -1,562 +0,0 @@ -"""Semantic interpreter tests for VOP3 op_sel on 16-bit vector compares: - - v_cmp_*_f16_e64 / v_cmpx_*_f16_e64 (lt, le, gt, ge, eq, lg, neq, o, u, plus neg/abs on high half) - - v_cmp_*_u16_e64 / v_cmpx_*_u16_e64 (eq, ne, lg, lt, le, gt, ge) - - v_cmp_*_i16_e64 / v_cmpx_*_i16_e64 (eq, ne, lg, lt, le, gt, ge, including signed negative high halves) - -VOP3 op_sel:[s0,s1] selects bit 15:0 (0) or bit 31:16 (1) of each 16-bit source operand before float -input modifiers (neg/abs) or integer zero/sign extension. VOPC writes a scalar lane mask (VCC/SGPR -or EXEC for v_cmpx), so there is no destination op_sel bit. - -Run directly: - python -I tests/semantic/test_vcmp16_opsel.py -v -""" -import gc -import math -import os -import shutil -import struct -import subprocess -import sys -import tempfile -import unittest -import warnings - -HERE = os.path.dirname(os.path.abspath(__file__)) -if HERE not in sys.path: - sys.path.insert(0, HERE) - -import spirv_mini_interp as si # noqa: E402 -import spirv_wave_interp as wi # noqa: E402 -from support import STUB_DXBC, mrt0_words, rdna2spirv # noqa: E402 - -VSHARP = [0, 0, 0xFFFFFFFF, 0x31016FAC] # OOB_SELECT 3 (raw) -SENTINEL = 0xDEADBEEF - -# Half-precision bit constants -H_ZERO = 0x0000 # +0.0 -H_NZERO = 0x8000 # -0.0 -H_HALF = 0x3800 # +0.5 -H_ONE = 0x3C00 # +1.0 -H_TWO = 0x4000 # +2.0 -H_THREE = 0x4200 # +3.0 -H_FOUR = 0x4400 # +4.0 -H_MONE = 0xBC00 # -1.0 -H_MTWO = 0xC000 # -2.0 -H_MFOUR = 0xC400 # -4.0 -H_INF = 0x7C00 # +inf -H_NINF = 0xFC00 # -inf -H_QNAN = 0x7E00 # qNaN - - -def pack16(lo: int, hi: int) -> int: - return ((hi & 0xFFFF) << 16) | (lo & 0xFFFF) - - -def f16_half(word: int, hi: int) -> float: - bits = (word >> 16) & 0xFFFF if hi else (word & 0xFFFF) - return struct.unpack(" int: - return (word >> 16) & 0xFFFF if hi else (word & 0xFFFF) - - -def i16_half(word: int, hi: int) -> int: - v = u16_half(word, hi) - return v - 0x10000 if v & 0x8000 else v - - -def f16_rel(cond: str, x: float, y: float) -> int: - nan = math.isnan(x) or math.isnan(y) - if cond == "o": - return int(not nan) - if cond == "u": - return int(nan) - if cond == "lt": - return int(x < y) - if cond == "le": - return int(x <= y) - if cond == "gt": - return int(x > y) - if cond == "ge": - return int(x >= y) - if cond == "eq": - return int(x == y) - if cond == "lg": - return int((not nan) and x != y) - if cond == "neq": - return int(nan or x != y) - raise ValueError(cond) - - -def int_rel(cond: str, x: int, y: int) -> int: - return int({ - "eq": x == y, - "ne": x != y, - "lg": x != y, - "lt": x < y, - "le": x <= y, - "gt": x > y, - "ge": x >= y, - }[cond]) - - -_TMP_DIR = None -_PS_PATH = None - - -def setUpModule(): - global _TMP_DIR, _PS_PATH - _TMP_DIR = tempfile.TemporaryDirectory() - dis = os.path.join(_TMP_DIR.name, "disasm") - os.mkdir(dis) - _PS_PATH = os.path.join(dis, "ps_vcmp16_opsel.s") - with open(os.path.join(_TMP_DIR.name, "ps_vcmp16_opsel.dxbc"), "wb") as f: - f.write(STUB_DXBC) - - -def tearDownModule(): - global _TMP_DIR - if _TMP_DIR is not None: - _TMP_DIR.cleanup() - _TMP_DIR = None - - -def translate_ps(lines): - if _TMP_DIR is None: - setUpModule() - asm = "; ps_vcmp16_opsel\n" + "".join(f"\t{ln}\n" for ln in lines) - with open(_PS_PATH, "w", encoding="utf-8", newline="") as f: - f.write(asm) - with warnings.catch_warnings(): - warnings.simplefilter("ignore", ResourceWarning) - return rdna2spirv.translate(_PS_PATH) - - -def run_ps_bit(x_word: int, y_word: int, cmp_line: str, mask: str = "s4") -> int: - lines = [ - f"v_mov_b32 v1, {x_word:#x}", - f"v_mov_b32 v2, {y_word:#x}", - cmp_line, - f"v_cndmask_b32_e64 v0, 0x40000000, 0x40000001, {mask}", - "exp mrt0 v0, v0, v0, v0 done vm", - "s_endpgm", - ] - w = mrt0_words(translate_ps(lines))[0] - assert (w >> 1) == 0x20000000, hex(w) - return w & 1 - - -def run_cs(name: str, body_lines, wave_size: int, user_sgprs=None): - """Translate a synthetic compute shader and run all lanes in spirv_mini_interp.run_workgroup.""" - with tempfile.TemporaryDirectory() as tmp: - os.mkdir(os.path.join(tmp, "disasm")) - os.mkdir(os.path.join(tmp, "fssm")) - s_path = os.path.join(tmp, "disasm", name + ".s") - with open(s_path, "w", encoding="utf-8", newline="") as f: - f.write(f"; {name}\n") - for ln in body_lines: - f.write(f"\t{ln}\n") - f.write("\ts_endpgm\n") - with open(os.path.join(tmp, name + ".dxbc"), "wb") as f: - f.write(STUB_DXBC) - rsrc2 = 0x8090 if user_sgprs else 0x8088 - with open(os.path.join(tmp, "fssm", name + ".fssm"), "wb") as f: - f.write(bytes(0x138) + struct.pack("<4I", rsrc2, wave_size, 1, 1)) - with warnings.catch_warnings(): - warnings.simplefilter("ignore", ResourceWarning) - spv = rdna2spirv.translate(s_path) - gc.collect() - assert rdna2spirv.translate.last_gen.wave64 == (wave_size == 64) - sgprs = list(user_sgprs) if user_sgprs else [] - pc = VSHARP + sgprs + [0] * (28 - len(sgprs)) - return si.run_workgroup( - spv, wave_size, wave_size, - inputs_for=lambda i: {"%wg_id": (0, 0, 0), "%local_id": (i, 0, 0), "%sg_lane": i}, - push_constants=pc, memory={}, - ) - - -class F16CompareOpSelTests(unittest.TestCase): - def test_f16_opsel_relations(self): - # Packed pairs chosen so each (s0, s1) combination tests distinct ordering & equality cases: - # Pair A: v1=(1.0, 4.0), v2=(2.0, 1.0) -> (lo,lo): 1<2; (hi,lo): 4>2; (lo,hi): 1==1; (hi,hi): 4>1 - # Pair B: v1=(3.0, 2.0), v2=(2.0, 2.0) -> (lo,lo): 3>2; (hi,lo): 2==2; (lo,hi): 3>2; (hi,hi): 2==2 - # Pair C: v1=(-2.0, 0.5), v2=(0.5, -1.0) -> signed negatives in both halves - pairs = [ - (pack16(H_ONE, H_FOUR), pack16(H_TWO, H_ONE)), - (pack16(H_THREE, H_TWO), pack16(H_TWO, H_TWO)), - (pack16(H_MTWO, H_HALF), pack16(H_HALF, H_MONE)), - ] - for cond in ("lt", "le", "gt", "ge", "eq", "lg", "neq"): - for xw, yw in pairs: - for s0, s1 in ((0, 0), (1, 0), (0, 1), (1, 1)): - want = f16_rel(cond, f16_half(xw, s0), f16_half(yw, s1)) - with self.subTest(cond=cond, x=hex(xw), y=hex(yw), opsel=(s0, s1)): - got = run_ps_bit( - xw, yw, - f"v_cmp_{cond}_f16_e64 s4, v1, v2 op_sel:[{s0},{s1}]", - mask="s4", - ) - self.assertEqual(got, want) - - def test_f16_opsel_ordered_unordered_nan(self): - # NaN in high half of v1, finite in low half; NaN in low half of v2, finite in high half: - # (0,0): finite vs NaN -> unordered; (1,0): NaN vs NaN -> unordered; - # (0,1): finite vs finite -> ordered; (1,1): NaN vs finite -> unordered. - xw = pack16(H_ONE, H_QNAN) - yw = pack16(H_QNAN, H_TWO) - # Also test finite-lo/NaN-hi vs finite-lo/finite-hi so [0,0] is ordered and [1,0] is unordered. - cases = [ - (xw, yw), - (pack16(H_ONE, H_QNAN), pack16(H_TWO, H_THREE)), - (pack16(H_QNAN, H_ONE), pack16(H_TWO, H_QNAN)), - ] - for cond in ("o", "u", "lt", "eq", "neq"): - for a, b in cases: - for s0, s1 in ((0, 0), (1, 0), (0, 1), (1, 1)): - want = f16_rel(cond, f16_half(a, s0), f16_half(b, s1)) - with self.subTest(cond=cond, a=hex(a), b=hex(b), opsel=(s0, s1)): - got = run_ps_bit( - a, b, - f"v_cmp_{cond}_f16_e64 vcc_lo, v1, v2 op_sel:[{s0},{s1}]", - mask="vcc_lo", - ) - self.assertEqual(got, want) - - def test_f16_opsel_neg_abs_modifiers(self): - # v1 = (lo=+1.0, hi=-4.0), v2 = (lo=+2.0, hi=+4.0) - # Selecting hi of v1 (-4.0): - # -v1 -> +4.0: eq v2.hi (+4.0) is 1, gt v2.lo (+2.0) is 1 - # |v1| -> +4.0: eq v2.hi (+4.0) is 1, lt v2.lo (+2.0) is 0 - # -|v1| -> -4.0: lt v2.lo (+2.0) is 1 - # Reading lo of v1 (+1.0) instead would flip every case below. - xw = pack16(H_ONE, H_MFOUR) - yw = pack16(H_TWO, H_FOUR) - cases = [ - ("v_cmp_eq_f16_e64 s4, -v1, v2 op_sel:[1,1]", 1), - ("v_cmp_gt_f16_e64 s4, -v1, v2 op_sel:[1,0]", 1), - ("v_cmp_eq_f16_e64 s4, |v1|, v2 op_sel:[1,1]", 1), - ("v_cmp_lt_f16_e64 s4, |v1|, v2 op_sel:[1,0]", 0), - ("v_cmp_lt_f16_e64 s4, v1, -v2 op_sel:[0,1]", 0), # +1.0 < -4.0 -> 0 (lo of v2 would give +1.0 < -2.0 -> 0, check gt below) - ("v_cmp_lt_f16_e64 s4, -|v1|, v2 op_sel:[1,0]", 1), # -4.0 < +2.0 -> 1 - ("v_cmp_gt_f16_e64 s4, -|v1|, -v2 op_sel:[1,0]", 0), # -4.0 > -2.0 -> 0 (lo would be -1.0 > -2.0 -> 1!) - ("v_cmp_eq_f16_e64 s4, v1, -v2 op_sel:[1,1]", 1), # -4.0 == -4.0 -> 1 - ] - for line, want in cases: - with self.subTest(line=line): - self.assertEqual(run_ps_bit(xw, yw, line, mask="s4"), want) - - -class Int16CompareOpSelTests(unittest.TestCase): - def test_u16_opsel_all_combos(self): - # Pair 1: v1=(lo=0x0001, hi=0xFFFF), v2=(lo=0x0002, hi=0x0001) - # (0,0): 1 < 2; (1,0): 65535 > 2; (0,1): 1 == 1; (1,1): 65535 > 1 - # Pair 2: v1=(lo=0x8000, hi=0x0005), v2=(lo=0x7FFF, hi=0x0005) - # (0,0): 32768 > 32767; (1,0): 5 < 32767; (0,1): 32768 > 5; (1,1): 5 == 5 - pairs = [ - (pack16(0x0001, 0xFFFF), pack16(0x0002, 0x0001)), - (pack16(0x8000, 0x0005), pack16(0x7FFF, 0x0005)), - ] - for cond in ("eq", "ne", "lg", "lt", "le", "gt", "ge"): - for xw, yw in pairs: - for s0, s1 in ((0, 0), (1, 0), (0, 1), (1, 1)): - want = int_rel(cond, u16_half(xw, s0), u16_half(yw, s1)) - with self.subTest(cond=cond, x=hex(xw), y=hex(yw), opsel=(s0, s1)): - got = run_ps_bit( - xw, yw, - f"v_cmp_{cond}_u16_e64 s4, v1, v2 op_sel:[{s0},{s1}]", - mask="s4", - ) - self.assertEqual(got, want) - - def test_i16_opsel_all_combos(self): - # Negative signed i16 in high half vs positive in low half: - # Pair 1: v1=(lo=+1, hi=-1=0xFFFF), v2=(lo=+2, hi=+1) - # (0,0): +1 < +2; (1,0): -1 < +2; (0,1): +1 == +1; (1,1): -1 < +1 (unsigned would say 0xFFFF > 1!) - # Pair 2: v1=(lo=+32767=0x7FFF, hi=-32768=0x8000), v2=(lo=-1=0xFFFF, hi=+0) - # (0,0): +32767 > -1; (1,0): -32768 < -1; (0,1): +32767 > 0; (1,1): -32768 < 0 - # Pair 3: v1=(lo=+5, hi=-2=0xFFFE), v2=(lo=-2=0xFFFE, hi=-2=0xFFFE) - # (0,0): +5 > -2; (1,0): -2 == -2; (0,1): +5 > -2; (1,1): -2 == -2 - pairs = [ - (pack16(0x0001, 0xFFFF), pack16(0x0002, 0x0001)), - (pack16(0x7FFF, 0x8000), pack16(0xFFFF, 0x0000)), - (pack16(0x0005, 0xFFFE), pack16(0xFFFE, 0xFFFE)), - ] - for cond in ("eq", "ne", "lg", "lt", "le", "gt", "ge"): - for xw, yw in pairs: - for s0, s1 in ((0, 0), (1, 0), (0, 1), (1, 1)): - want = int_rel(cond, i16_half(xw, s0), i16_half(yw, s1)) - with self.subTest(cond=cond, x=hex(xw), y=hex(yw), opsel=(s0, s1)): - got = run_ps_bit( - xw, yw, - f"v_cmp_{cond}_i16_e64 s4, v1, v2 op_sel:[{s0},{s1}]", - mask="s4", - ) - self.assertEqual(got, want) - - -class CmpxWaveExecOpSelTests(unittest.TestCase): - def test_cmpx_compute_wave32_and_wave64(self): - # For each type (f16, u16, i16) and wave size (32, 64), give even lanes a packed value whose - # high half PASSES the compare (low half FAILS), and odd lanes a packed value whose high half - # FAILS (low half PASSES). v_cmpx_*_e64 with op_sel:[1,0] must keep even lanes active and - # switch off odd lanes, writing lane|0x100 only for even lanes and leaving SENTINEL on odd lanes. - cases = [ - # (tag, cmp_line, even_v1, odd_v1, v2) - ("f16_lt_10", "v_cmpx_lt_f16_e64 v1, v2 op_sel:[1,0]", - pack16(H_FOUR, H_ONE), pack16(H_ONE, H_FOUR), pack16(H_TWO, H_TWO)), - ("f16_gt_01", "v_cmpx_gt_f16_e64 v1, v2 op_sel:[0,1]", - pack16(H_FOUR, H_ONE), pack16(H_ONE, H_FOUR), pack16(H_FOUR, H_TWO)), - ("u16_gt_10", "v_cmpx_gt_u16_e64 v1, v2 op_sel:[1,0]", - pack16(0x0001, 0xFFFF), pack16(0xFFFF, 0x0001), pack16(0x0010, 0x0010)), - ("i16_lt_10", "v_cmpx_lt_i16_e64 v1, v2 op_sel:[1,0]", - pack16(0x0005, 0xFFFF), pack16(0xFFFF, 0x0005), pack16(0x0001, 0x0001)), - ] - for wave in (32, 64): - vcc = "vcc" if wave == 64 else "vcc_lo" - save_exec = "s_mov_b64 s[8:9], exec" if wave == 64 else "s_mov_b32 s8, exec_lo" - for tag, cmp_line, even_v1, odd_v1, v2_word in cases: - with self.subTest(wave=wave, case=tag): - body = [ - save_exec, - # Pre-fill output[lane] = SENTINEL while all lanes are active. - "v_lshlrev_b32_e32 v4, 2, v0", - f"v_mov_b32 v5, {SENTINEL:#x}", - "buffer_store_dword v5, v4, s[0:3], 0 offen", - # v3 = lane & 1; even lanes get even_v1, odd lanes get odd_v1. - "v_and_b32_e32 v3, 1, v0", - f"v_cmp_eq_u32_e64 {vcc}, v3, 0", - f"v_mov_b32 v6, {even_v1:#x}", - f"v_mov_b32 v7, {odd_v1:#x}", - f"v_cndmask_b32_e64 v1, v7, v6, {vcc}", - f"v_mov_b32 v2, {v2_word:#x}", - cmp_line, - # Only lanes that survived v_cmpx execute this store. - "v_or_b32_e32 v5, 0x100, v0", - "buffer_store_dword v5, v4, s[0:3], 0 offen", - ] - mem = run_cs(f"cs_cmpx_{tag}_w{wave}", body, wave_size=wave) - for lane in range(wave): - want = (0x100 | lane) if (lane % 2 == 0) else SENTINEL - self.assertEqual(mem.get(lane * 4), want, f"lane {lane}") - - def test_cmpx_int16_spirv_wave_interp(self): - # Run v_cmpx_*_u16_e64 and v_cmpx_*_i16_e64 with op_sel directly through spirv_wave_interp - # across both wave32 and wave64, verifying lane-exact EXEC kill on pixel export. - cases = [ - # (tag, cmp_line, even_v1, odd_v1, v2) - ("u16_gt_10", "v_cmpx_gt_u16_e64 v1, v2 op_sel:[1,0]", - pack16(0x0001, 0xFFFF), pack16(0xFFFF, 0x0001), pack16(0x0010, 0x0010)), - ("u16_lt_01", "v_cmpx_lt_u16_e64 v1, v2 op_sel:[0,1]", - pack16(0x0002, 0x0100), pack16(0x0100, 0x0002), pack16(0x0001, 0x0050)), - ("i16_lt_10", "v_cmpx_lt_i16_e64 v1, v2 op_sel:[1,0]", - pack16(0x0005, 0xFFFF), pack16(0xFFFF, 0x0005), pack16(0x0001, 0x0001)), - ("i16_gt_01", "v_cmpx_gt_i16_e64 v1, v2 op_sel:[0,1]", - pack16(0x0001, 0xFFFE), pack16(0xFFFE, 0x0001), pack16(0x0005, 0xFFFF)), - ] - for wave in (32, 64): - vcc = "vcc" if wave == 64 else "vcc_lo" - lane_setup = [ - "v_mbcnt_lo_u32_b32 v3, -1, 0", - ] - if wave == 64: - lane_setup.append("v_mbcnt_hi_u32_b32 v3, -1, v3") - for tag, cmp_line, even_v1, odd_v1, v2_word in cases: - with self.subTest(wave=wave, case=tag): - lines = lane_setup + [ - "v_and_b32_e32 v4, 1, v3", - f"v_cmp_eq_u32_e64 {vcc}, v4, 0", - f"v_mov_b32 v6, {even_v1:#x}", - f"v_mov_b32 v7, {odd_v1:#x}", - f"v_cndmask_b32_e64 v1, v7, v6, {vcc}", - f"v_mov_b32 v2, {v2_word:#x}", - cmp_line, - "v_or_b32_e32 v0, 0x40000000, v3", - "exp mrt0 v0, v0, v0, v0 done vm", - "s_endpgm", - ] - spv = translate_ps(lines) - self.assertEqual(rdna2spirv.translate.last_gen.wave64, wave == 64) - outputs = wi.run_wave(spv, wave=wave)["outputs"] - for lane in range(wave): - if lane % 2 == 0: - self.assertIsNotNone(outputs[lane], f"lane {lane} should stay active") - self.assertEqual(outputs[lane]["%out_mrt0"][0], 0x40000000 | lane) - else: - self.assertIsNone(outputs[lane], f"lane {lane} should be killed by v_cmpx") - - -class VcmpInactiveLanesSdstTests(unittest.TestCase): - def test_vcmp_inactive_lanes_wave32(self): - body = [ - "v_mov_b32 v1, 0x1234", - "v_mov_b32 v2, 0x1234", - "s_mov_b32 exec_lo, 0x55555555", - "v_cmp_eq_u16_e64 s4, v1, v2 op_sel:[0,0]", - "s_mov_b32 exec_lo, -1", - "v_lshrrev_b32_e32 v3, v0, s4", - "v_and_b32_e32 v3, 1, v3", - "v_lshlrev_b32_e32 v6, 2, v0", - "buffer_store_dword v3, v6, s[0:3], 0 offen", - ] - mem = run_cs("cs_vcmp_inactive_w32", body, 32) - for lane in range(32): - self.assertEqual(mem.get(lane * 4), 1 if (lane % 2 == 0) else 0) - - def test_vcmp_inactive_lanes_wave64(self): - body = [ - "v_mov_b32 v1, 0x1234", - "v_mov_b32 v2, 0x1234", - "s_mov_b64 exec, 0x5555555555555555", - "v_cmp_eq_u16_e64 s[4:5], v1, v2 op_sel:[0,0]", - "s_mov_b64 exec, -1", - "v_cmp_ge_u32_e64 s6, v0, 32", - "v_cndmask_b32_e64 v4, s4, s5, s6", - "v_and_b32_e32 v5, 31, v0", - "v_lshrrev_b32_e32 v3, v5, v4", - "v_and_b32_e32 v3, 1, v3", - "v_lshlrev_b32_e32 v6, 2, v0", - "buffer_store_dword v3, v6, s[0:3], 0 offen", - ] - mem = run_cs("cs_vcmp_inactive_w64", body, 64) - for lane in range(64): - self.assertEqual(mem.get(lane * 4), 1 if (lane % 2 == 0) else 0) - - -class ConstantsAndLiteralsOpSelTests(unittest.TestCase): - def test_inline_float_constants_opsel(self): - # 1.0 has 0x3C00 in low half, +0.0 in high half - v1 = pack16(H_ONE, H_TWO) - self.assertEqual(run_ps_bit(v1, 0, "v_cmp_eq_f16_e64 s4, v1, 1.0 op_sel:[0,0]", mask="s4"), 1) - self.assertEqual(run_ps_bit(v1, 0, "v_cmp_eq_f16_e64 s4, v1, 1.0 op_sel:[1,0]", mask="s4"), 0) - self.assertEqual(run_ps_bit(pack16(H_ZERO, H_TWO), 0, "v_cmp_eq_f16_e64 s4, v1, 1.0 op_sel:[0,1]", mask="s4"), 1) - self.assertEqual(run_ps_bit(v1, 0, "v_cmp_eq_f16_e64 s4, v1, 1.0 op_sel:[0,1]", mask="s4"), 0) - self.assertEqual(run_ps_bit(pack16(H_MTWO, H_ONE), 0, "v_cmp_eq_f16_e64 s4, v1, -2.0 op_sel:[0,0]", mask="s4"), 1) - self.assertEqual(run_ps_bit(pack16(H_ZERO, H_ONE), 0, "v_cmp_eq_f16_e64 s4, v1, -2.0 op_sel:[0,1]", mask="s4"), 1) - - def test_inline_integer_constants_opsel(self): - # Inline integer constant 1: opsel=0 -> 1; opsel=1 -> 0 - self.assertEqual(run_ps_bit(pack16(1, 2), 0, "v_cmp_eq_u16_e64 s4, v1, 1 op_sel:[0,0]", mask="s4"), 1) - self.assertEqual(run_ps_bit(pack16(0, 2), 0, "v_cmp_eq_u16_e64 s4, v1, 1 op_sel:[0,1]", mask="s4"), 1) - # Inline integer constant -1: opsel=0 -> 0xFFFF; opsel=1 -> 0xFFFF - self.assertEqual(run_ps_bit(pack16(0xFFFF, 0), 0, "v_cmp_eq_u16_e64 s4, v1, -1 op_sel:[0,0]", mask="s4"), 1) - self.assertEqual(run_ps_bit(pack16(0xFFFF, 0), 0, "v_cmp_eq_u16_e64 s4, v1, -1 op_sel:[0,1]", mask="s4"), 1) - self.assertEqual(run_ps_bit(pack16(0xFFFF, 0), 0, "v_cmp_eq_i16_e64 s4, v1, -1 op_sel:[0,0]", mask="s4"), 1) - self.assertEqual(run_ps_bit(pack16(0xFFFF, 0), 0, "v_cmp_eq_i16_e64 s4, v1, -1 op_sel:[0,1]", mask="s4"), 1) - - def test_32bit_literals_opsel(self): - # Literal 0x80007FFF: lo=0x7FFF (+32767), hi=0x8000 (-32768 in i16, 32768 in u16) - self.assertEqual(run_ps_bit(pack16(0x7FFF, 0), 0, "v_cmp_eq_u16_e64 s4, v1, 0x80007FFF op_sel:[0,0]", mask="s4"), 1) - self.assertEqual(run_ps_bit(pack16(0x8000, 0), 0, "v_cmp_eq_u16_e64 s4, v1, 0x80007FFF op_sel:[0,1]", mask="s4"), 1) - self.assertEqual(run_ps_bit(pack16(0x7FFF, 0), 0, "v_cmp_eq_i16_e64 s4, v1, 0x80007FFF op_sel:[0,0]", mask="s4"), 1) - self.assertEqual(run_ps_bit(pack16(0, 0x8000), 0, "v_cmp_eq_i16_e64 s4, v1, 0x80007FFF op_sel:[1,1]", mask="s4"), 1) - self.assertEqual(run_ps_bit(pack16(0, 0), 0, "v_cmp_lt_i16_e64 s4, v1, 0x80007FFF op_sel:[0,1]", mask="s4"), 0) - - # f16 literal 0x40003C00 (lo = 1.0, hi = 2.0) - self.assertEqual(run_ps_bit(pack16(H_ONE, H_FOUR), 0, "v_cmp_eq_f16_e64 s4, v1, 0x40003C00 op_sel:[0,0]", mask="s4"), 1) - self.assertEqual(run_ps_bit(pack16(H_FOUR, H_TWO), 0, "v_cmp_eq_f16_e64 s4, v1, 0x40003C00 op_sel:[1,1]", mask="s4"), 1) - - @unittest.skipUnless(shutil.which("spirv-as") and shutil.which("spirv-val"), - "needs spirv-as and spirv-val on PATH") - def test_spirv_val_compliance(self): - cases = [ - ("f16_opsel_const", ["v_cmp_eq_f16_e64 s4, v1, 1.0 op_sel:[0,1]", "v_cndmask_b32_e64 v0, 0, 1, s4", "exp mrt0 v0, v0, v0, v0 done vm", "s_endpgm"]), - ("u16_opsel_lit", ["v_cmp_gt_u16_e64 s4, v1, 0x80007FFF op_sel:[1,0]", "v_cndmask_b32_e64 v0, 0, 1, s4", "exp mrt0 v0, v0, v0, v0 done vm", "s_endpgm"]), - ("i16_opsel_const", ["v_cmp_lt_i16_e64 s4, v1, -1 op_sel:[0,1]", "v_cndmask_b32_e64 v0, 0, 1, s4", "exp mrt0 v0, v0, v0, v0 done vm", "s_endpgm"]), - ("cmpx_f16_wave64", ["v_cmpx_lt_f16_e64 v1, v2 op_sel:[1,0]", "exp mrt0 v0, v0, v0, v0 done vm", "s_endpgm"]), - ] - with tempfile.TemporaryDirectory() as tmp: - for tag, lines in cases: - spv_text = translate_ps(lines) - spv_path = os.path.join(tmp, f"ps_{tag}.spv") - sa_path = os.path.join(tmp, f"ps_{tag}.spvasm") - with open(sa_path, "w", encoding="utf-8") as f: - f.write(spv_text) - rdna2spirv.assemble_spirv(sa_path, spv_path) - res = subprocess.run(["spirv-val", "--target-env", "vulkan1.2", spv_path], capture_output=True, text=True) - self.assertEqual(res.returncode, 0, f"spirv-val failed for {tag}: {res.stderr}") - - -class SgprHighHalvesOpSelTests(unittest.TestCase): - def test_sgpr_high_halves_f16(self): - user_s4 = pack16(H_ONE, H_FOUR) - # s4 as src1: opsel:[0, 0] reads lo(s4)=1.0 - lines = [ - f"v_mov_b32 v1, {pack16(H_ONE, 0):#x}", - "v_cmp_eq_f16_e64 s5, v1, s4 op_sel:[0,0]", - "v_and_b32_e32 v2, 1, s5", - "v_lshlrev_b32_e32 v3, 2, v0", - "buffer_store_dword v2, v3, s[0:3], 0 offen", - ] - mem = run_cs("cs_sgpr_f16_0", lines, 32, user_sgprs=[user_s4]) - self.assertEqual(mem.get(0), 1) - - # opsel:[0, 1] reads hi(s4)=4.0 - lines = [ - f"v_mov_b32 v1, {pack16(H_FOUR, 0):#x}", - "v_cmp_eq_f16_e64 s5, v1, s4 op_sel:[0,1]", - "v_and_b32_e32 v2, 1, s5", - "v_lshlrev_b32_e32 v3, 2, v0", - "buffer_store_dword v2, v3, s[0:3], 0 offen", - ] - mem = run_cs("cs_sgpr_f16_1", lines, 32, user_sgprs=[user_s4]) - self.assertEqual(mem.get(0), 1) - - # s4 as src0: - lines = [ - f"v_mov_b32 v1, {pack16(H_FOUR, 0):#x}", - "v_cmp_eq_f16_e64 s5, s4, v1 op_sel:[1,0]", - "v_and_b32_e32 v2, 1, s5", - "v_lshlrev_b32_e32 v3, 2, v0", - "buffer_store_dword v2, v3, s[0:3], 0 offen", - ] - mem = run_cs("cs_sgpr_f16_src0", lines, 32, user_sgprs=[user_s4]) - self.assertEqual(mem.get(0), 1) - - # s4 with neg / abs on high half: - lines = [ - f"v_mov_b32 v1, {pack16(H_MFOUR, 0):#x}", - "v_cmp_eq_f16_e64 s5, v1, -s4 op_sel:[0,1]", - "v_and_b32_e32 v2, 1, s5", - "v_lshlrev_b32_e32 v3, 2, v0", - "buffer_store_dword v2, v3, s[0:3], 0 offen", - ] - mem = run_cs("cs_sgpr_f16_neg", lines, 32, user_sgprs=[user_s4]) - self.assertEqual(mem.get(0), 1) - - def test_sgpr_high_halves_int16(self): - user_s4 = pack16(0x7FFF, 0xFFFF) - lines = [ - f"v_mov_b32 v1, {pack16(0xFFFF, 0):#x}", - "v_cmp_eq_u16_e64 s5, v1, s4 op_sel:[0,1]", - "v_and_b32_e32 v2, 1, s5", - "v_lshlrev_b32_e32 v3, 2, v0", - "buffer_store_dword v2, v3, s[0:3], 0 offen", - ] - mem = run_cs("cs_sgpr_u16_1", lines, 32, user_sgprs=[user_s4]) - self.assertEqual(mem.get(0), 1) - - lines = [ - "v_mov_b32 v1, 0", - "v_cmp_lt_i16_e64 s5, s4, v1 op_sel:[1,0]", - "v_and_b32_e32 v2, 1, s5", - "v_lshlrev_b32_e32 v3, 2, v0", - "buffer_store_dword v2, v3, s[0:3], 0 offen", - ] - mem = run_cs("cs_sgpr_i16_lt", lines, 32, user_sgprs=[user_s4]) - self.assertEqual(mem.get(0), 1) - - lines = [ - "v_mov_b32 v1, 0", - "v_cmp_lt_u16_e64 s5, s4, v1 op_sel:[1,0]", - "v_and_b32_e32 v2, 1, s5", - "v_lshlrev_b32_e32 v3, 2, v0", - "buffer_store_dword v2, v3, s[0:3], 0 offen", - ] - mem = run_cs("cs_sgpr_u16_lt", lines, 32, user_sgprs=[user_s4]) - self.assertEqual(mem.get(0), 0) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_vcmp64_null_src.py b/tests/semantic/test_vcmp64_null_src.py deleted file mode 100644 index c9ca51239..000000000 --- a/tests/semantic/test_vcmp64_null_src.py +++ /dev/null @@ -1,109 +0,0 @@ -"""RDNA2 null reads zero in either 64-bit integer VALU compare source.""" -import itertools -import struct -import unittest - -import support -import spirv_mini_interp as si - -CONDITIONS = ("eq", "ne", "lt", "le", "gt", "ge") -VALUES = (0, 1, 1 << 32, 1 << 63, (1 << 64) - 1) - - -def reference(cond, ty, x, y): - if ty == "i64": - x, y = (v - (1 << 64) if v >> 63 else v for v in (x, y)) - return {"eq": x == y, "ne": x != y, "lt": x < y, "le": x <= y, - "gt": x > y, "ge": x >= y}[cond] - - -def run_compare(cond, ty, form, cmpx, sources, value=0, inactive=False): - op = f"v_cmp{'x' if cmpx else ''}_{cond}_{ty}_{form}" - operands = ", ".join(sources) - if not cmpx: - operands = "vcc_lo, " + operands - lines = [f"v_mov_b32 v2, {value & 0xFFFFFFFF:#x}", f"v_mov_b32 v3, {value >> 32:#x}", - "s_mov_b32 vcc_lo, -1"] - if inactive: - lines.append("s_mov_b32 exec_lo, 0") - lines += [f"{op} {operands}", "v_cndmask_b32 v0, 0, 1, vcc_lo", - "exp mrt0 v0, v0, v0, v0 done vm", "s_endpgm"] - return si.run_fragment(support.translate_lines("ps_vcmp64_null", lines)).get("%out_mrt0") - - -class CompareNullSources(unittest.TestCase): - def check_sources(self, cmpx): - for cond, ty, (form, slot), value in itertools.product( - CONDITIONS, ("u64", "i64"), (("e32", 0), ("e64", 0), ("e64", 1)), VALUES): - with self.subTest(cond=cond, ty=ty, form=form, slot=slot, value=hex(value)): - sources = ["v[2:3]", "v[2:3]"] - sources[slot] = "null" - x, y = (0, value) if slot == 0 else (value, 0) - expected = reference(cond, ty, x, y) - result = run_compare(cond, ty, form, cmpx, sources, value) - if cmpx: - self.assertEqual(result, (1, 1, 1, 1) if expected else None) - else: - self.assertEqual(result, (int(expected),) * 4) - - def test_vcmp_sources(self): - self.check_sources(False) - - def test_vcmpx_sources(self): - self.check_sources(True) - - def test_vcmpx_mixed_lanes_preserve_vcc(self): - lanes = 32 - vcc = 0x96A53C69 - fssm = bytearray(0x148) - struct.pack_into("<4I", fssm, 0x138, 0x8088, lanes, 1, 1) - for ty, slot in itertools.product(("u64", "i64"), (0, 1)): - with self.subTest(ty=ty, slot=slot): - cond = ("lt" if slot == 0 else "gt") if ty == "u64" else ("gt" if slot == 0 else "lt") - sources = ["v[2:3]", "v[2:3]"] - sources[slot] = "null" - lines = ["v_and_b32 v2, 1, v0", - "v_mov_b32 v3, 0" if ty == "u64" else "v_lshlrev_b32 v3, 31, v2", - f"s_mov_b32 vcc_lo, {vcc:#x}", - f"v_cmpx_{cond}_{ty}_e64 {', '.join(sources)}", - "s_mov_b32 s8, exec_lo", "s_mov_b32 s9, vcc_lo", - "s_mov_b32 exec_lo, -1", - "v_cndmask_b32_e64 v4, 0, 1, s8", "v_cndmask_b32_e64 v5, 0, 1, s9", - "v_lshlrev_b32 v6, 3, v0", - "buffer_store_dword v4, v6, s[0:3], 0 offen", - "buffer_store_dword v5, v6, s[0:3], 4 offen", "s_endpgm"] - spv = support.translate_lines("cs_vcmp64_null_masks", lines, fssm=bytes(fssm)) - got = si.run_workgroup( - spv, lanes, 32, - inputs_for=lambda i: {"%wg_id": (0, 0, 0), "%local_id": (i, 0, 0), "%sg_lane": i}, - push_constants=[0, 0, 0x1000, 0x31016FAC] + [0] * 28, memory={}) - values = [(i & 1) if ty == "u64" else ((1 << 63) + 1 if i & 1 else 0) - for i in range(lanes)] - operands = [(0, value) if slot == 0 else (value, 0) for value in values] - mask = sum(1 << i for i, (x, y) in enumerate(operands) if reference(cond, ty, x, y)) - self.assertNotIn(mask, (0, (1 << lanes) - 1, vcc)) - expected = {8 * i + offset: value for i in range(lanes) - for offset, value in ((0, (mask >> i) & 1), (4, (vcc >> i) & 1))} - self.assertEqual(got, expected) - - def test_both_null(self): - for cond, ty, cmpx in itertools.product(CONDITIONS, ("u64", "i64"), (False, True)): - with self.subTest(cond=cond, ty=ty, cmpx=cmpx): - expected = reference(cond, ty, 0, 0) - result = run_compare(cond, ty, "e64", cmpx, ["null", "null"]) - self.assertEqual(result, ((1,) * 4 if expected else None) if cmpx else (int(expected),) * 4) - - def test_inactive_lane_stays_inactive(self): - for cond, ty, cmpx in itertools.product(CONDITIONS, ("u64", "i64"), (False, True)): - with self.subTest(cond=cond, ty=ty, cmpx=cmpx): - self.assertIsNone(run_compare(cond, ty, "e64", cmpx, ["null", "v[2:3]"], inactive=True)) - - def test_non_pair_register_stays_unsupported(self): - for cond, cmpx in itertools.product(CONDITIONS, (False, True)): - with self.subTest(cond=cond, cmpx=cmpx): - with self.assertRaises(support.rdna2spirv.Unsupported): - run_compare(cond, "u64", "e64", cmpx, ["null", "v2"]) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_vcmp_dst_wave32_vcchi.py b/tests/semantic/test_vcmp_dst_wave32_vcchi.py deleted file mode 100644 index 239b7a4b7..000000000 --- a/tests/semantic/test_vcmp_dst_wave32_vcchi.py +++ /dev/null @@ -1,490 +0,0 @@ -"""Semantic tests for v_cmp_* / v_cmp_class_f64 null/exec/wave32-vcc_hi SDSTs and wave32 vcc_hi masks. - -Covers: - - null destination on v_cmp_* (f32, f16, u16, i16, u32, i32, f64, f/tru_f64, u64 eq/lt, i64) and v_cmp_class_f64: - mask write is discarded without touching VCC or EXEC (wave32, wave64, and --wave64-emulate) - - exec_lo (wave32) and exec (wave64 / --wave64-emulate) destinations on the same compare / class families: - active lanes update EXEC and inactive lanes remain off (including constant tru/t compares), while VCC stays intact - - wave32 vcc_hi as an independent 32-bit mask/scalar register: - * v_cmp_*, v_cmp_class_f64, v_add_co_u32, v_mad_u64_u32, s_and_saveexec_b32, s_wqm_b32 writing vcc_hi - * v_cndmask_b32_e64, v_add_co_ci_u32_e64, s_bcnt1_i32_b32, s_ff1_i32_b32, s_flbit_i32_b32, - v_mbcnt_lo_u32_b32, s_cmp_eq/lt_u32, s_wqm_b32 reading vcc_hi (preserving vcc_lo) - * plain scalar data in vcc_hi (e.g. 0xA5000005, s_wqm_b32 vcc_hi, 1) read both as scalar and as a lane-bit - mask without corrupting or reading vcc_lo - - negative controls rejecting invalid destinations (VGPR everywhere; vcc_hi SDST in wave64) - - Vulkan 1.2 SPIR-V validation via spirv-as / spirv-val when present on PATH -""" -import gc -import os -import shutil -import struct -import subprocess -import sys -import tempfile -import unittest -import warnings - -HERE = os.path.dirname(os.path.abspath(__file__)) -ROOT = os.path.dirname(os.path.dirname(HERE)) -TOOLS_DIR = os.environ.get("LEONIDA_TOOLS_DIR") or os.path.join(ROOT, "tools") - -sys.dont_write_bytecode = True -if HERE not in sys.path: - sys.path.insert(0, HERE) -if TOOLS_DIR not in sys.path: - sys.path.insert(0, TOOLS_DIR) - -import rdna2spirv # noqa: E402 -import spirv_mini_interp as si # noqa: E402 -import spirv_wave_interp as wi # noqa: E402 - -STUB_DXBC = b"DXBC" + bytes(24) + struct.pack(" 0), - ("f64", [ - "v_cvt_f64_u32_e32 v[2:3], v0", - "v_mov_b32_e32 v4, 0", - "v_mov_b32_e32 v5, 0x40180000", # 6.0 - ], "v_cmp_lt_f64_e64 {dst}, v[2:3], v[4:5]", lambda i: i < 6), - ("f_f64", [ - "v_cvt_f64_u32_e32 v[2:3], v0", - ], "v_cmp_f_f64_e64 {dst}, v[2:3], v[2:3]", lambda i: False), - ("tru_f64", [ - "v_cvt_f64_u32_e32 v[2:3], v0", - ], "v_cmp_tru_f64_e64 {dst}, v[2:3], v[2:3]", lambda i: True), - ("u64_eq", [ - "v_mov_b32_e32 v2, v0", - "v_mov_b32_e32 v3, 0", - "v_mov_b32_e32 v4, 4", - "v_mov_b32_e32 v5, 0", - ], "v_cmp_eq_u64_e64 {dst}, v[2:3], v[4:5]", lambda i: i == 4), - ("u64_lt", [ - "v_mov_b32_e32 v2, v0", - "v_mov_b32_e32 v3, 0", - "v_mov_b32_e32 v4, 8", - "v_mov_b32_e32 v5, 0", - ], "v_cmp_lt_u64_e64 {dst}, v[2:3], v[4:5]", lambda i: i < 8), - ("class_f64", [ - "v_cvt_f64_u32_e32 v[2:3], v0", # lane 0 is +0.0 (bit 6 = 0x40); lanes >= 1 are +normal (bit 8 = 0x100) - ], "v_cmp_class_f64_e64 {dst}, v[2:3], 0x100", lambda i: i >= 1), -] - - -class VcmpDstWave32VccHiTests(unittest.TestCase): - def _native_modes(self): - return [(32, False), (64, False)] - - def test_null_destination_preserves_vcc_and_exec(self): - for wave_size, emulate in self._native_modes(): - vcc_reg = "vcc_lo" if wave_size == 32 else "vcc" - mov_exec = "s_mov_b32 exec_lo, -1" if wave_size == 32 else "s_mov_b64 exec, -1" - and_exec = "s_and_b32 exec_lo, exec_lo, vcc_lo" if wave_size == 32 else "s_and_b64 exec, exec, vcc" - for idx, (tag, setup, tmpl, _cond_fn) in enumerate(COMPARE_NULL_EXEC_CASES): - with self.subTest(wave=wave_size, emulate=emulate, case=tag): - # Initial active mask: even lanes (i & 1 == 0) via v_and_b32 + v_cmp_eq_u32. - lines = [ - "v_and_b32_e32 v10, 1, v0", - "v_mov_b32_e32 v11, 0x77777777", - "v_mov_b32_e32 v12, 0x88888888", - f"v_cmp_eq_u32_e64 {vcc_reg}, v10, 0", - *setup, - and_exec, - # VCC sentinel: lanes with (v0 & 3) == 2 (distinguished from active mask!) - "v_and_b32_e32 v13, 3, v0", - f"{mov_exec}", - f"v_cmp_eq_u32_e64 {vcc_reg}, v13, 2", - # Re-apply even-lane EXEC before v_cmp null, so both active and inactive lanes run null compare. - "v_cmp_eq_u32_e64 s4, v10, 0" if wave_size == 32 else "v_cmp_eq_u32_e64 s[4:5], v10, 0", - "s_mov_b32 exec_lo, s4" if wave_size == 32 else "s_mov_b64 exec, s[4:5]", - tmpl.format(dst="null"), - # Record which lanes stayed active in v11, and restore full EXEC to read VCC in v12. - "v_mov_b32_e32 v11, 0x11111111", - mov_exec, - f"v_cndmask_b32_e64 v12, 0x22222222, 0x33333333, {vcc_reg}", - "v_lshlrev_b32_e32 v14, 3, v0", - "v_add_nc_u32_e32 v15, 4, v14", - "buffer_store_dword v11, v14, s[0:3], 0 offen", - "buffer_store_dword v12, v15, s[0:3], 0 offen", - ] - mem = _run_cs(f"null_{tag}_w{wave_size}_{int(emulate)}", lines, - wave_size=wave_size, emulate=emulate, validate=(idx == 0)) - for i in range(wave_size): - got_exec = mem[i * 8] - got_vcc = mem[i * 8 + 4] - self.assertEqual(got_exec, 0x11111111 if (i & 1) == 0 else 0x77777777, f"lane {i} exec") - self.assertEqual(got_vcc, 0x33333333 if (i & 3) == 2 else 0x22222222, f"lane {i} vcc") - - def test_exec_destination_narrows_exec_without_clobbering_vcc(self): - for wave_size, emulate in self._native_modes(): - vcc_reg = "vcc_lo" if wave_size == 32 else "vcc" - exec_reg = "exec_lo" if wave_size == 32 else "exec" - mov_exec = "s_mov_b32 exec_lo, -1" if wave_size == 32 else "s_mov_b64 exec, -1" - and_exec = "s_and_b32 exec_lo, exec_lo, s4" if wave_size == 32 else "s_and_b64 exec, exec, s[4:5]" - sg_dst = "s4" if wave_size == 32 else "s[4:5]" - for idx, (tag, setup, tmpl, cond_fn) in enumerate(COMPARE_NULL_EXEC_CASES): - with self.subTest(wave=wave_size, emulate=emulate, case=tag): - lines = [ - "v_mov_b32_e32 v11, 0x55555555", - # Setup runs with all lanes on so inputs are defined everywhere. - *setup, - # Set distinct VCC pattern: (v0 & 3) == 1 - "v_and_b32_e32 v13, 3, v0", - f"v_cmp_eq_u32_e64 {vcc_reg}, v13, 1", - # Narrow initial EXEC to lanes with (v0 & 1) == 0. - "v_and_b32_e32 v10, 1, v0", - f"v_cmp_eq_u32_e64 {sg_dst}, v10, 0", - and_exec, - # Execute compare targeting EXEC directly. - tmpl.format(dst=exec_reg), - "v_mov_b32_e32 v11, 0xAAAAAAAA", - mov_exec, - f"v_cndmask_b32_e64 v12, 0x10101010, 0x20202020, {vcc_reg}", - "v_lshlrev_b32_e32 v14, 3, v0", - "v_add_nc_u32_e32 v15, 4, v14", - "buffer_store_dword v11, v14, s[0:3], 0 offen", - "buffer_store_dword v12, v15, s[0:3], 0 offen", - ] - mem = _run_cs(f"exec_{tag}_w{wave_size}_{int(emulate)}", lines, - wave_size=wave_size, emulate=emulate, validate=(idx in (0, 6, 8, 11))) - for i in range(wave_size): - want_active = ((i & 1) == 0) and cond_fn(i) - self.assertEqual(mem[i * 8], 0xAAAAAAAA if want_active else 0x55555555, f"lane {i} exec") - self.assertEqual(mem[i * 8 + 4], 0x20202020 if (i & 3) == 1 else 0x10101010, f"lane {i} vcc") - - def test_wave32_vcc_hi_mask_producers_and_consumers_isolate_vcc_lo(self): - # Producer matrix in wave32 targeting vcc_hi while vcc_lo holds lane 7 only (0x00000080). - producers = [ - ("cmp_f32", [ - "v_cvt_f32_u32_e32 v1, v0", - "v_cmp_lt_f32_e64 vcc_hi, v1, 5.0", - ], 0x0000001F), - ("cmp_f64", [ - "v_cvt_f64_u32_e32 v[2:3], v0", - "v_mov_b32_e32 v4, 0", - "v_mov_b32_e32 v5, 0x40080000", # 3.0 - "v_cmp_lt_f64_e64 vcc_hi, v[2:3], v[4:5]", - ], 0x00000007), - ("cmp_class_f64", [ - "v_cvt_f64_u32_e32 v[2:3], v0", - "v_cmp_class_f64_e64 vcc_hi, v[2:3], 0x40", # +0.0 -> lane 0 only - ], 0x00000001), - ("cmp_eq_u64", [ - "v_mov_b32_e32 v2, v0", - "v_mov_b32_e32 v3, 0", - "v_mov_b32_e32 v4, 19", - "v_mov_b32_e32 v5, 0", - "v_cmp_eq_u64_e64 vcc_hi, v[2:3], v[4:5]", - ], 1 << 19), - ("cmp_lt_u64", [ - "v_mov_b32_e32 v2, v0", - "v_mov_b32_e32 v3, 0", - "v_mov_b32_e32 v4, 6", - "v_mov_b32_e32 v5, 0", - "v_cmp_lt_u64_e64 vcc_hi, v[2:3], v[4:5]", - ], 0x0000003F), - ("add_co", [ - "v_mov_b32_e32 v1, 0xFFFFFFFF", - "v_cmp_lt_u32_e64 s6, v0, 4", - "v_cndmask_b32_e64 v2, 0, 1, s6", - "v_add_co_u32 v3, vcc_hi, v1, v2", - ], 0x0000000F), - ("mad_u64", [ - "v_cmp_lt_u32_e64 s6, v0, 3", - "v_cndmask_b32_e64 v2, 1, 0xFFFFFFFF, s6", - "v_mov_b32_e32 v4, 0", - "v_mov_b32_e32 v5, 0xFFFFFFFF", - "v_mad_u64_u32 v[6:7], vcc_hi, v2, 0x10000000, v[4:5]", - ], 0x00000007), - ("saveexec", [ - "v_cmp_lt_u32_e64 s6, v0, 2", - "s_and_saveexec_b32 vcc_hi, s6", - "s_mov_b32 exec_lo, -1", - ], 0xFFFFFFFF), - ] - - for tag, prod_lines, want_mask in producers: - with self.subTest(producer=tag): - lines = [ - "v_cmp_eq_u32_e64 vcc_lo, v0, 7", - *prod_lines, - # Consumers reading vcc_hi as a lane mask: - "v_cndmask_b32_e64 v10, 0, 1, vcc_hi", # per-lane bit of vcc_hi - "v_add_co_ci_u32_e64 v11, s8, 10, 0, vcc_hi", # 10 + carry_in(vcc_hi) - "s_bcnt1_i32_b32 s9, vcc_hi", # popcount of whole wave - "v_mov_b32_e32 v12, s9", - "v_mbcnt_lo_u32_b32 v13, vcc_hi, 0", # prefix count - "s_cmp_eq_u32 vcc_hi, 0", # 1 iff mask == 0 - "s_cselect_b32 s10, 1, 0", - "v_mov_b32_e32 v14, s10", - "v_cndmask_b32_e32 v15, 0, 1, vcc_lo", # verify vcc_lo still only lane 7 - "v_mul_i32_i24_e32 v16, 24, v0", - "buffer_store_dword v10, v16, s[0:3], 0 offen", - "v_add_nc_u32_e32 v16, 4, v16", - "buffer_store_dword v11, v16, s[0:3], 0 offen", - "v_add_nc_u32_e32 v16, 4, v16", - "buffer_store_dword v12, v16, s[0:3], 0 offen", - "v_add_nc_u32_e32 v16, 4, v16", - "buffer_store_dword v13, v16, s[0:3], 0 offen", - "v_add_nc_u32_e32 v16, 4, v16", - "buffer_store_dword v14, v16, s[0:3], 0 offen", - "v_add_nc_u32_e32 v16, 4, v16", - "buffer_store_dword v15, v16, s[0:3], 0 offen", - ] - mem = _run_cs(f"w32_vcchi_{tag}", lines, wave_size=32, emulate=False, validate=True) - pop = bin(want_mask).count("1") - for i in range(32): - bit = (want_mask >> i) & 1 - prefix = bin(want_mask & ((1 << i) - 1)).count("1") - base = i * 24 - self.assertEqual(mem[base], bit, f"{tag} lane {i} cndmask") - self.assertEqual(mem[base + 4], 10 + bit, f"{tag} lane {i} add_co_ci") - self.assertEqual(mem[base + 8], pop, f"{tag} lane {i} s_bcnt1") - self.assertEqual(mem[base + 12], prefix, f"{tag} lane {i} v_mbcnt") - self.assertEqual(mem[base + 16], 1 if want_mask == 0 else 0, f"{tag} lane {i} s_cmp_eq") - self.assertEqual(mem[base + 20], 1 if i == 7 else 0, f"{tag} lane {i} vcc_lo isolated") - - # s_wqm_b32 vcc_hi, s6: validate both CS (QuadSwap) and VS semantic execution (run_wave). - wqm_lines = [ - "v_cmp_eq_u32_e64 vcc_lo, v0, 7", - "v_cmp_eq_u32_e64 s6, v0, 5", - "s_wqm_b32 vcc_hi, s6", - "v_cndmask_b32_e64 v10, 0, 1, vcc_hi", - "v_add_co_ci_u32_e64 v11, s8, 10, 0, vcc_hi", - "s_bcnt1_i32_b32 s9, vcc_hi", - "v_mov_b32_e32 v12, s9", - "v_cndmask_b32_e32 v15, 0, 1, vcc_lo", - ] - _validate_spirv("w32_vcchi_wqm_cs", _translate_cs("w32_vcchi_wqm_cs", wqm_lines, wave_size=32)) - vs_out = _run_vs_w32("w32_vcchi_wqm_vs", wqm_lines) - for i in range(32): - bit = 1 if 4 <= i < 8 else 0 - self.assertEqual(vs_out[i], (bit, 10 + bit, 4, 1 if i == 7 else 0), f"wqm lane {i}") - - def test_wave32_vcc_hi_plain_data_scalar_and_mask_reads_preserve_vcc_lo(self): - # 0xA5000005 sets bits {0, 2, 24, 26, 29, 31}; 6 bits total. - data_word = 0xA5000005 - lines = [ - "v_cmp_eq_u32_e64 vcc_lo, v0, 7", - f"s_mov_b32 vcc_hi, {data_word:#x}", - "s_mov_b32 s4, vcc_hi", # scalar read -> 0xA5000005 - "v_mov_b32_e32 v10, s4", - "s_bcnt1_i32_b32 s5, vcc_hi", # popcount of scalar word -> 6 - "v_mov_b32_e32 v11, s5", - "v_cndmask_b32_e64 v12, 0x100, 0x200, vcc_hi", # per-lane bit of 0xA5000005! - "v_add_co_ci_u32_e64 v13, s6, 20, 0, vcc_hi", # 20 + bit(lane, 0xA5000005) - # Plain-data s_wqm_b32 into vcc_hi -> 0xF (scalar AND bitmask lanes 0..3) while preserving vcc_lo. - "s_wqm_b32 vcc_hi, 0x1", - "s_mov_b32 s7, vcc_hi", - "v_mov_b32_e32 v14, s7", - "v_cndmask_b32_e64 v15, 0, 1, vcc_hi", - "v_cndmask_b32_e32 v16, 0, 1, vcc_lo", - "v_mul_i32_i24_e32 v17, 28, v0", - "buffer_store_dword v10, v17, s[0:3], 0 offen", - "v_add_nc_u32_e32 v17, 4, v17", - "buffer_store_dword v11, v17, s[0:3], 0 offen", - "v_add_nc_u32_e32 v17, 4, v17", - "buffer_store_dword v12, v17, s[0:3], 0 offen", - "v_add_nc_u32_e32 v17, 4, v17", - "buffer_store_dword v13, v17, s[0:3], 0 offen", - "v_add_nc_u32_e32 v17, 4, v17", - "buffer_store_dword v14, v17, s[0:3], 0 offen", - "v_add_nc_u32_e32 v17, 4, v17", - "buffer_store_dword v15, v17, s[0:3], 0 offen", - "v_add_nc_u32_e32 v17, 4, v17", - "buffer_store_dword v16, v17, s[0:3], 0 offen", - ] - mem = _run_cs("w32_vcchi_data", lines, wave_size=32, emulate=False, validate=True) - for i in range(32): - bit = (data_word >> i) & 1 - base = i * 28 - self.assertEqual(mem[base], data_word, f"lane {i} scalar read") - self.assertEqual(mem[base + 4], 6, f"lane {i} bcnt1 data") - self.assertEqual(mem[base + 8], 0x200 if bit else 0x100, f"lane {i} cndmask data") - self.assertEqual(mem[base + 12], 20 + bit, f"lane {i} co_ci data") - self.assertEqual(mem[base + 16], 0xF, f"lane {i} s_wqm scalar") - self.assertEqual(mem[base + 20], 1 if i < 4 else 0, f"lane {i} s_wqm mask bit") - self.assertEqual(mem[base + 24], 1 if i == 7 else 0, f"lane {i} vcc_lo isolated") - - def test_wave32_vcc_hi_overwrite_data_and_cmp_with_vcc_lo(self): - # First hold a mask in vcc_hi, verify s_cmp_eq_u32 vcc_hi, vcc_lo; then overwrite vcc_hi with data - # and verify vcc_lo still behaves as a mask while vcc_hi behaves as data. - lines = [ - "v_cmp_lt_u32_e64 vcc_lo, v0, 4", - "v_cmp_lt_u32_e64 vcc_hi, v0, 4", - "s_cmp_eq_u32 vcc_hi, vcc_lo", - "s_cselect_b32 s4, 1, 0", - "v_mov_b32_e32 v10, s4", - "s_mov_b32 vcc_hi, 0x10", # lane 4 bit set -> only lane 4 when read by v_cndmask - "s_bcnt1_i32_b32 s5, vcc_lo", # still 4 - "v_mov_b32_e32 v11, s5", - "v_cndmask_b32_e64 v12, 0, 1, vcc_hi", - "v_cndmask_b32_e32 v13, 0, 1, vcc_lo", - "v_mul_i32_i24_e32 v14, 16, v0", - "buffer_store_dword v10, v14, s[0:3], 0 offen", - "v_add_nc_u32_e32 v14, 4, v14", - "buffer_store_dword v11, v14, s[0:3], 0 offen", - "v_add_nc_u32_e32 v14, 4, v14", - "buffer_store_dword v12, v14, s[0:3], 0 offen", - "v_add_nc_u32_e32 v14, 4, v14", - "buffer_store_dword v13, v14, s[0:3], 0 offen", - ] - mem = _run_cs("w32_vcchi_cmp_overwrite", lines, wave_size=32, emulate=False, validate=True) - for i in range(32): - base = i * 16 - self.assertEqual(mem[base], 1, f"lane {i} vcc_hi == vcc_lo") - self.assertEqual(mem[base + 4], 4, f"lane {i} bcnt1(vcc_lo)") - self.assertEqual(mem[base + 8], 1 if i == 4 else 0, f"lane {i} data vcc_hi") - self.assertEqual(mem[base + 12], 1 if i < 4 else 0, f"lane {i} mask vcc_lo") - - def test_wave64_emulate_null_and_exec_destinations_validate(self): - # Validate every compare/class family with null and exec destinations under --wave64-emulate, - # and confirm standalone null writes emit no %vcc / %active store while exec writes update %active. - for tag, setup, tmpl, _ in COMPARE_NULL_EXEC_CASES: - with self.subTest(case=tag, dst="null"): - spv = _translate_cs(f"emu_null_{tag}", [*setup, tmpl.format(dst="null")], wave_size=64, emulate=True) - _validate_spirv(f"emu_null_{tag}", spv) - self.assertNotIn("OpStore %vcc ", spv) - self.assertNotIn("OpStore %active ", spv) - with self.subTest(case=tag, dst="exec"): - spv = _translate_cs(f"emu_exec_{tag}", [*setup, tmpl.format(dst="exec")], wave_size=64, emulate=True) - _validate_spirv(f"emu_exec_{tag}", spv) - self.assertNotIn("OpStore %vcc ", spv) - self.assertIn("OpStore %active ", spv) - - def test_negative_controls_invalid_compare_destinations(self): - invalid = [ - (32, "v_cmp_lt_f32_e64 v2, v0, v1"), - (32, "v_cmp_lt_f64_e64 v2, v[0:1], v[2:3]"), - (32, "v_cmp_class_f64_e64 v2, v[0:1], 1"), - (32, "v_cmp_lt_f32_e64 1, v0, v1"), - (64, "v_cmp_lt_f32_e64 vcc_hi, v0, v1"), - (64, "v_cmp_lt_f64_e64 vcc_hi, v[0:1], v[2:3]"), - (64, "v_cmp_class_f64_e64 vcc_hi, v[0:1], 1"), - (64, "v_cmp_class_f64_e64 exec_hi, v[0:1], 1"), - ] - for wave_size, bad in invalid: - with self.subTest(wave=wave_size, insn=bad): - with self.assertRaises(rdna2spirv.Unsupported) as ctx: - _translate_cs("bad_vcmp_dst", [bad], wave_size=wave_size) - self.assertIn("destination", str(ctx.exception)) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_vcmp_f16.py b/tests/semantic/test_vcmp_f16.py deleted file mode 100644 index f3b20550b..000000000 --- a/tests/semantic/test_vcmp_f16.py +++ /dev/null @@ -1,59 +0,0 @@ -"""v_cmp_{f,lt,eq,le,gt,lg,ge,o,u,nge,nlg,ngt,nle,neq,nlt,tru}_f16, e32 (VCC) and e64 (SGPR pair, swapped operands). - -RDNA2 ISA (VOPC, _F16): the compare reads S0.f16 and S1.f16, bits 15:0 of the operands only, and the ordered forms -are false when either operand is NaN, so the N* forms are true for an unordered pair; +0 == -0. The shaders are -runtime/test/shaders/ps_vcmp_f16.asm and ps_vcmp_f16_e64.asm (also run on the GPU by check.py and run_gpu_tests.py); -their headers derive the eight words by hand. The reference here is plain Python on the same f16 bit patterns. -""" -import math -import struct -import unittest - -import support - -EXPECTED_E32 = [0x48A12080, 0x4CE9B1A2, 0x4BA72C98, 0x4FEFBDBA] # derivation in ps_vcmp_f16.asm -EXPECTED_E64 = [0x44C11100, 0x4CF171C1, 0x47C71D18, 0x4FF77DD9] # derivation in ps_vcmp_f16_e64.asm -# (A, B) as f16 bit patterns: 1<2, 2>1, +0 == -0, qNaN vs 1, 1 vs sNaN, +inf > -inf, denormal 1 < denormal 2 -PAIRS = ((0x3C00, 0x4000), (0x4000, 0x3C00), (0x0000, 0x8000), (0x7E00, 0x3C00), (0x3C00, 0x7C01), - (0x7C00, 0xFC00), (0x0001, 0x0002)) -OPS = (("f", lambda a, b: False), ("lt", lambda a, b: a < b), ("eq", lambda a, b: a == b), - ("le", lambda a, b: a <= b), ("gt", lambda a, b: a > b), ("lg", lambda a, b: a < b or a > b), - ("ge", lambda a, b: a >= b), ("o", lambda a, b: not (math.isnan(a) or math.isnan(b))), - ("u", lambda a, b: math.isnan(a) or math.isnan(b)), ("nge", lambda a, b: not a >= b), - ("nlg", lambda a, b: not (a < b or a > b)), ("ngt", lambda a, b: not a > b), ("nle", lambda a, b: not a <= b), - ("neq", lambda a, b: not a == b), ("nlt", lambda a, b: not a < b), ("tru", lambda a, b: True)) - - -def f16(bits): - return struct.unpack(" S1) are false when unordered, and -0 equals +0; - NGE, NLG, NGT, NLE, NEQ, NLT are the logical negations of GE, LG, GT, LE, EQ, LT, so they are TRUE when unordered. -v_cmp writes the result to VCC (e32) or an SGPR pair (e64) and v_cmpx writes EXEC; v_cmpx is checked by the lanes it -leaves active. VOP3 abs and neg act on the sources before the compare (so -|NaN| is still a NaN). -Expected values come from the Python predicates below, not from the translator. Each case translates a one-lane pixel -shader with tools/rdna2spirv.py and runs it in tests/semantic/spirv_mini_interp.py. -""" -import itertools -import math -import os -import struct -import sys -import unittest - -HERE = os.path.dirname(os.path.abspath(__file__)) -sys.dont_write_bytecode = True -sys.path.insert(0, HERE) - -import spirv_mini_interp as si # noqa: E402 -import support # noqa: E402 - -PREDS = { - "f": lambda a, b: False, - "tru": lambda a, b: True, - "o": lambda a, b: not (math.isnan(a) or math.isnan(b)), - "u": lambda a, b: math.isnan(a) or math.isnan(b), - "lt": lambda a, b: a < b, - "eq": lambda a, b: a == b, - "le": lambda a, b: a <= b, - "gt": lambda a, b: a > b, - "ge": lambda a, b: a >= b, - "lg": lambda a, b: a < b or a > b, - "nlt": lambda a, b: not a < b, - "neq": lambda a, b: not a == b, - "nle": lambda a, b: not a <= b, - "ngt": lambda a, b: not a > b, - "nge": lambda a, b: not a >= b, - "nlg": lambda a, b: not (a < b or a > b), -} -# Bit patterns: -inf, -1, -0, +0, +1, 1+ulp, +inf, quiet NaN (both signs), signaling NaN. -VALUES = [0xFF800000, 0xBF800000, 0x80000000, 0x00000000, 0x3F800000, 0x3F800001, 0x7F800000, - 0x7FC00000, 0xFFC00000, 0x7F800001] - - -def f32(bits): - return struct.unpack("> 31 else x - - -def reference_word(signed_compare, swapped): - """One mrt0 word: bit 5*k + i is op k on pair i, bit 31 is v_cmp_t, bit 30 is v_cmp_f (always 0).""" - word = 1 << 31 - for k, (_, rel) in enumerate(OPS): - for i, (a, b) in enumerate(PAIRS): - s0, s1 = (b, a) if swapped else (a, b) - if signed_compare: - s0, s1 = signed(s0), signed(s1) - if rel(s0, s1): - word |= 1 << (5 * k + i) - return word - - -class VcmpInt32(unittest.TestCase): - def test_reference_matches_the_header_words(self): - ref = [reference_word(False, False), reference_word(True, False), - reference_word(False, True), reference_word(True, True)] - self.assertEqual([f"{w:#010x}" for w in ref], [f"{w:#010x}" for w in EXPECTED]) - - def test_ps_vcmp_int32(self): - spv = support.translate_fixture("ps_vcmp_int32") - words = support.mrt0_words(spv, push_constants=[0x1000, 0, 32, 0] + [0] * 28, - memory={0x1000 + 4 * i: w for i, w in enumerate(HEAP)}) - self.assertEqual([f"{w:#010x}" for w in words], [f"{w:#010x}" for w in EXPECTED]) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_vcmpx_f16.py b/tests/semantic/test_vcmpx_f16.py deleted file mode 100644 index b7929e725..000000000 --- a/tests/semantic/test_vcmpx_f16.py +++ /dev/null @@ -1,35 +0,0 @@ -"""v_cmpx_{f,lt,eq,le,gt,lg,ge,o,u,nge,nlg,ngt,nle,neq,nlt,tru}_f16, e32 and e64 (swapped operands). - -RDNA2 ISA (VOPC, _F16): a v_cmpx compares like v_cmp (S0.f16 with S1.f16, ordered compares false for a NaN, +0 == -0) -but writes the result to EXEC (EXEC = EXEC & compare) and to nothing else, so VCC is kept. The shaders are -runtime/test/shaders/ps_vcmpx_f16.asm and ps_vcmpx_f16_e64.asm (also run on the GPU by check.py and -run_gpu_tests.py); their headers derive the eight words by hand. The reference reuses the one of test_vcmp_f16 and -adds bit 29 (VCC kept, 1) next to bit 30 (marker) and bit 28 (a v_cmpx cannot widen EXEC, 0). -""" -import unittest - -import support -from test_vcmp_f16 import reference_words - -EXPECTED_E32 = [0x68A12080, 0x6CE9B1A2, 0x6BA72C98, 0x6FEFBDBA] # derivation in ps_vcmpx_f16.asm -EXPECTED_E64 = [0x64C11100, 0x6CF171C1, 0x67C71D18, 0x6FF77DD9] # derivation in ps_vcmpx_f16_e64.asm - - -def hexes(words): - return [f"{w:#010x}" for w in words] - - -class VcmpxF16(unittest.TestCase): - def test_reference_matches_the_header_words(self): - self.assertEqual(hexes(w | 0x20000000 for w in reference_words(False)), hexes(EXPECTED_E32)) - self.assertEqual(hexes(w | 0x20000000 for w in reference_words(True)), hexes(EXPECTED_E64)) - - def test_ps_vcmpx_f16(self): - self.assertEqual(hexes(support.mrt0_words(support.translate_fixture("ps_vcmpx_f16"))), hexes(EXPECTED_E32)) - - def test_ps_vcmpx_f16_e64(self): - self.assertEqual(hexes(support.mrt0_words(support.translate_fixture("ps_vcmpx_f16_e64"))), hexes(EXPECTED_E64)) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_vcmpx_forms.py b/tests/semantic/test_vcmpx_forms.py deleted file mode 100644 index 0fffdcf19..000000000 --- a/tests/semantic/test_vcmpx_forms.py +++ /dev/null @@ -1,219 +0,0 @@ -"""The 14 v_cmpx forms that had no test: v_cmpx_{eq,gt,le,lt,ngt,nle}_f32, v_cmpx_f_i32, v_cmpx_t_u32, -v_cmpx_{eq,gt,le}_i64 and v_cmpx_{ge,lt,ne}_u64. - -RDNA2 ISA (VOPC): EXEC = EXEC & compare(S0, S1), per lane, and nothing else is written, so VCC is kept. - EQ = S0 == S1, GT = S0 > S1, LE = S0 <= S1, LT = S0 < S1: ordered, false when a source is NaN; -0 equals +0. - NGT = !(S0 > S1), NLE = !(S0 <= S1): the negations, so true when a source is NaN. - F = 0, T = 1, whatever the sources hold. - _I64 / _U64 compare the whole 64-bit values signed / unsigned (the low word is never signed). - -Three kinds of test, all through tools/rdna2spirv.py and tests/semantic/spirv_mini_interp.py: - * ps_vcmpx_forms (runtime/test/shaders, also run on the GPU by check.py and run_gpu_tests.py): the four words - its header derives by hand, compared with a reference written here from the definitions above. - * every form in both encodings (e32, e64) on a table of operands: the pixel survives exactly when Python's own - comparison of the operands holds. - * a wave of 16 lanes with different operands, one of them switched off beforehand: the lanes left running. -""" -import itertools -import struct -import unittest - -import support -import spirv_mini_interp as si - -EXPECTED = [0xF05B2A48, 0xF05E8A12, 0xB174BE18, 0x15550000] # derivation in ps_vcmpx_forms.asm -# NaN, 1.0, 2.0, -0.0, +0.0, -infinity, two unused words; then four pairs (A, B) as A.lo A.hi B.lo B.hi. -HEAP = (0x7FC10001, 0x3F800000, 0x40000000, 0x80000000, 0x00000000, 0xFF800000, 0, 0, - 0x80000000, 0x00000000, 0x00000001, 0x00000000, - 0x00000007, 0x80000000, 0x00000007, 0x00000000, - 0x00000001, 0x00000005, 0x80000000, 0x00000005, - 0x00000007, 0x00000005, 0x00000007, 0x00000005) - -F32_OPS = ("eq", "gt", "le", "lt", "ngt", "nle") -I64_OPS = ("eq_i64", "gt_i64", "le_i64", "ge_u64", "lt_u64", "ne_u64") -ALL_OPS = tuple(f"{c}_f32" for c in F32_OPS) + ("f_i32", "t_u32") + I64_OPS - - -def f32(bits): - return struct.unpack("> 63 else x - - -def relation(op, a, b): - """The ISA's compare for `op` (the mnemonic without v_cmpx_). a, b: the sources' bits (32 or 64 wide).""" - cond, ty = op.rsplit("_", 1) - if cond in ("f", "t"): - return cond == "t" - if ty == "f32": - x, y = f32(a), f32(b) # Python's float compares are IEEE: false on NaN, -0.0 == 0.0 - return {"eq": x == y, "gt": x > y, "le": x <= y, "lt": x < y, "ngt": not x > y, "nle": not x <= y}[cond] - if ty == "i64": - a, b = signed64(a), signed64(b) - return {"eq": a == b, "ne": a != b, "gt": a > b, "ge": a >= b, "lt": a < b, "le": a <= b}[cond] - - -def reference_words(): - """The four mrt0 words of ps_vcmpx_forms, from `relation` and the heap (layout in the .asm header).""" - nan, one, two, nzero, pzero, ninf = HEAP[:6] - q = [((HEAP[9 + 4 * i] << 32) | HEAP[8 + 4 * i], (HEAP[11 + 4 * i] << 32) | HEAP[10 + 4 * i]) for i in range(4)] - first8 = ALL_OPS[:8] - - def nibbles(ops, pairs): - return sum(int(relation(op, *p)) << (4 * k + i) for k, op in enumerate(ops) for i, p in enumerate(pairs)) - - word0 = nibbles(first8, ((nan, one), (one, two), (two, one), (one, one))) - word1 = nibbles(first8, ((two, one), (nzero, pzero), (nan, nan), (ninf, one))) - word2 = nibbles(I64_OPS + ("gt_i64", "ge_u64"), q) - # Operands that make op k true (bits 0..13 and the odd VCC bits) and false (the even VCC bits). - true = {"eq_f32": (one, one), "gt_f32": (two, one), "le_f32": (one, two), "lt_f32": (one, two), - "ngt_f32": (nan, one), "nle_f32": (nan, one), "f_i32": (one, one), "t_u32": (one, two), - "eq_i64": q[3], "gt_i64": q[0], "le_i64": q[1], "ge_u64": q[1], "lt_u64": q[2], "ne_u64": q[1]} - false = {"eq_f32": (nan, nan), "le_f32": (two, one), "ngt_f32": (two, one), "f_i32": (one, one), - "eq_i64": q[1], "le_i64": q[0], "lt_u64": q[1]} - word3 = 0 - for k, op in enumerate(ALL_OPS): - exec_ = False # emptied by v_cmpx_ne_u32 of equal values - exec_ = exec_ and relation(op, *true[op]) - word3 |= int(exec_) << k - vcc = k % 2 == 0 # even k: VCC = 1 and a false compare; odd: 0 and true - assert relation(op, *(false[op] if vcc else true[op])) != vcc, op - word3 |= int(vcc) << (16 + k) # v_cmpx leaves VCC alone - return [word0, word1, word2, word3] - - -F32_VALUES = {"0": 0x00000000, "-0": 0x80000000, "1": 0x3F800000, "-1": 0xBF800000, "2.5": 0x40200000, - "inf": 0x7F800000, "-inf": 0xFF800000, "nan": 0x7FC00000, "-nan": 0xFFC00001} -# 64-bit values that only the high word, only the low word, or the sign tell apart. -I64_VALUES = (0x0000000000000000, 0x0000000000000001, 0x0000000080000000, 0x00000000FFFFFFFF, - 0x0000000100000000, 0x0000000500000007, 0x7FFFFFFFFFFFFFFF, 0x8000000000000000, - 0x8000000000000007, 0xFFFFFFFF00000000, 0xFFFFFFFFFFFFFFFF) - - -def survives(op, form, a, b): - """Run `v_cmpx__
a, b` in a one-pixel shader; True when the pixel still exports afterwards.""" - if op.endswith("64"): - lines = [f"v_mov_b32 v2, {a & 0xFFFFFFFF:#x}", f"v_mov_b32 v3, {a >> 32:#x}", - f"v_mov_b32 v4, {b & 0xFFFFFFFF:#x}", f"v_mov_b32 v5, {b >> 32:#x}", - f"v_cmpx_{op}_{form} v[2:3], v[4:5]"] - else: - lines = [f"v_mov_b32 v2, {a:#x}", f"v_mov_b32 v3, {b:#x}", f"v_cmpx_{op}_{form} v2, v3"] - spv = support.translate_lines("ps_vcmpx_case", [*lines, "exp mrt0 v2, v2, v2, v2 done vm", "s_endpgm"]) - return "%out_mrt0" in si.run_fragment(spv) - - -class OracleTests(unittest.TestCase): - def test_reference_matches_the_hand_derived_words(self): - self.assertEqual([f"{w:#010x}" for w in reference_words()], [f"{w:#010x}" for w in EXPECTED]) - - def test_relation_on_the_cases_that_tell_the_forms_apart(self): - nan, one, two = HEAP[:3] - self.assertFalse(relation("eq_f32", nan, nan)) - self.assertTrue(relation("eq_f32", 0x80000000, 0)) - self.assertTrue(relation("ngt_f32", nan, one) and relation("nle_f32", nan, one)) - self.assertFalse(relation("le_f32", nan, one) or relation("gt_f32", nan, one)) - self.assertTrue(relation("ngt_f32", one, two) and not relation("nle_f32", one, two)) - self.assertTrue(relation("ge_u64", 1 << 63, 1) and relation("le_i64", 1 << 63, 1)) - self.assertTrue(relation("gt_i64", 0x80000000, 1) and relation("lt_u64", 1, 0x80000000)) - - -class FixtureTests(unittest.TestCase): - def test_ps_vcmpx_forms(self): - spv = support.translate_fixture("ps_vcmpx_forms") - words = support.mrt0_words(spv, push_constants=[0x1000, 0, 96, 0] + [0] * 28, - memory={0x1000 + 4 * i: w for i, w in enumerate(HEAP)}) - self.assertEqual([f"{w:#010x}" for w in words], [f"{w:#010x}" for w in EXPECTED]) - - -class EveryFormOnATable(unittest.TestCase): - def test_f32_forms(self): - for cond, form in itertools.product(F32_OPS, ("e32", "e64")): - op = f"{cond}_f32" - for (xn, xb), (yn, yb) in itertools.product(F32_VALUES.items(), repeat=2): - with self.subTest(op=op, form=form, x=xn, y=yn): - self.assertEqual(survives(op, form, xb, yb), relation(op, xb, yb)) - - def test_f_i32_and_t_u32_ignore_their_sources(self): - for op, form in itertools.product(("f_i32", "t_u32"), ("e32", "e64")): - for a, b in ((0, 0), (1, 2), (2, 1), (0xFFFFFFFF, 0), (0x80000000, 0x7FFFFFFF)): - with self.subTest(op=op, form=form, a=hex(a), b=hex(b)): - self.assertEqual(survives(op, form, a, b), op == "t_u32") - - def test_64_bit_forms(self): - for op, form in itertools.product(I64_OPS, ("e32", "e64")): - for a, b in itertools.product(I64_VALUES, repeat=2): - with self.subTest(op=op, form=form, a=hex(a), b=hex(b)): - self.assertEqual(survives(op, form, a, b), relation(op, a, b)) - - -class LanesOfAWave(unittest.TestCase): - """One 16-thread wave32: lane i compares operand X[i] with one shared operand; lane 5 is off beforehand. - Each lane left running stores its index, so the stored words are the EXEC the compare left.""" - LANES = 16 - OFF = 5 - F32_X = (0x7FC00000, 0x3F800000, 0x40000000, 0x80000000, 0x00000000, 0x3F800000, 0xFF800000, 0x7F800000, - 0xBF800000, 0x3F800001, 0x3F7FFFFF, 0xFFC00000, 0x00000001, 0x80000001, 0x40000000, 0x3F800000) - F32_Y = 0x3F800000 # 1.0 - I64_X = (0, 1, 0x80000000, 0xFFFFFFFF, 0x100000000, 0x500000007, 0x7FFFFFFFFFFFFFFF, 0x8000000000000000, - 0x8000000000000007, 0xFFFFFFFF00000000, 0xFFFFFFFFFFFFFFFF, 0x500000006, 0x500000008, - 0x400000007, 0x600000007, 0x8000000500000007) - I64_Y = 0x500000007 - - def run_wave(self, setup, compare): - fssm = bytearray(0x148) # COMPUTE_PGM_RSRC2 (4 user SGPRs), group size - struct.pack_into("<4I", fssm, 0x138, 0x8088, self.LANES, 1, 1) - lines = [*setup, - f"v_cmpx_ne_u32_e32 {self.OFF}, v0", # lane OFF leaves the wave - "v_cmp_gt_u32_e32 vcc_lo, 8, v0", # VCC = lanes 0..7: must survive the compare - compare, - "v_cndmask_b32_e64 v20, 0x100, 0x200, vcc_lo", - "v_or_b32_e32 v20, v20, v0", - "v_lshlrev_b32_e32 v21, 2, v0", - "buffer_store_dword v20, v21, s[0:3], 0 offen", - "s_endpgm"] - spv = support.translate_lines("cs_vcmpx_wave", lines, fssm=bytes(fssm)) - return si.run_workgroup( - spv, self.LANES, 32, inputs_for=lambda i: {"%wg_id": (0, 0, 0), "%local_id": (i, 0, 0), "%sg_lane": i}, - push_constants=[0, 0, 0x1000, 0x31016FAC] + [0] * 28, memory={}) - - def want(self, op, xs, y): - # lane i stores (0x200 if i < 8 else 0x100) | i at 4*i when it is still running - return {4 * i: (0x200 if i < 8 else 0x100) | i - for i in range(self.LANES) if i != self.OFF and relation(op, xs[i], y)} - - @staticmethod - def per_lane(reg, values): - """v = values[lane], built with one v_cndmask per lane from the lane index in v0.""" - lines = [f"v_mov_b32_e32 v{reg}, {values[0]:#x}"] - for i, v in enumerate(values[1:], 1): - lines += [f"v_mov_b32_e32 v19, {v:#x}", f"v_cmp_eq_u32_e32 vcc_lo, {i}, v0", - f"v_cndmask_b32_e32 v{reg}, v{reg}, v19, vcc_lo"] - return lines - - def test_f32_forms(self): - setup = self.per_lane(1, self.F32_X) + [f"v_mov_b32_e32 v2, {self.F32_Y:#x}"] - for cond, form in itertools.product(F32_OPS, ("e32", "e64")): - with self.subTest(op=cond, form=form): - got = self.run_wave(setup, f"v_cmpx_{cond}_f32_{form} v1, v2") - self.assertEqual(got, self.want(f"{cond}_f32", self.F32_X, self.F32_Y)) - - def test_f_i32_and_t_u32(self): - setup = self.per_lane(1, self.F32_X) + [f"v_mov_b32_e32 v2, {self.F32_Y:#x}"] - for op, form in itertools.product(("f_i32", "t_u32"), ("e32", "e64")): - with self.subTest(op=op, form=form): - got = self.run_wave(setup, f"v_cmpx_{op}_{form} v1, v2") - self.assertEqual(got, self.want(op, self.F32_X, self.F32_Y)) - - def test_64_bit_forms(self): - setup = (self.per_lane(1, [x & 0xFFFFFFFF for x in self.I64_X]) + self.per_lane(2, [x >> 32 for x in self.I64_X]) - + [f"v_mov_b32_e32 v3, {self.I64_Y & 0xFFFFFFFF:#x}", f"v_mov_b32_e32 v4, {self.I64_Y >> 32:#x}"]) - for op, form in itertools.product(I64_OPS, ("e32", "e64")): - with self.subTest(op=op, form=form): - got = self.run_wave(setup, f"v_cmpx_{op}_{form} v[1:2], v[3:4]") - self.assertEqual(got, self.want(op, self.I64_X, self.I64_Y)) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_vector_mem_mubuf.py b/tests/semantic/test_vector_mem_mubuf.py deleted file mode 100644 index 95316e468..000000000 --- a/tests/semantic/test_vector_mem_mubuf.py +++ /dev/null @@ -1,1137 +0,0 @@ -"""Semantic interpreter tests for untyped MUBUF buffer loads and stores. - -Covers AMD RDNA2 / GFX10 untyped buffer memory load/store ISA semantics and -tools/rdna2spirv.py translation: - * Buffer Resource Descriptor (V# 128-bit layout): - - Dword 0: Base address low 32 bits [31:0] - - Dword 1: Base address high 16 bits [15:0] in bits [15:0]; Stride in bytes - in bits [29:16] (14 bits); cache flags in bits [31:30] - - Dword 2: Number of records (num_records), representing capacity in bytes - (raw buffer, stride == 0) or element record count (structured buffer, stride > 0) - - Dword 3: Format and descriptor metadata (untyped loads/stores treat data raw) - - 64-bit base address pointer expansion: ((dword1 & 0xFFFF) << 32) | dword0. - Proper masking (dword1 & 0xFFFF) prevents stride and descriptor flags from - polluting the 64-bit physical storage buffer address. - * Effective Address Calculation: - - Raw buffer: total = soffset + inst_offset + (offen ? vaddr : 0) - - Structured buffer with idxen: total = soffset + inst_offset + vindex * stride + (offen ? voffset : 0) - - Structured buffer without idxen: total = soffset + inst_offset + (offen ? vaddr : 0) - - Effective 64-bit address: (base_64 + total) & 0xFFFFFFFFFFFFFFFF - - Support for immediate offset modifier (offset:N), SGPR soffset, and vaddr = off - * Bounds Checking & Out-of-Bounds Behavior: - - Raw buffer (stride == 0): in_bounds = total < num_records - - Structured buffer with idxen: in_bounds = vindex < num_records - - Structured buffer without idxen: in_bounds = total < (num_records * stride) - - Out-of-bounds loads: return 0 for all loaded dwords (via OpPhi / OpSelect) - - Out-of-bounds stores: suppressed (memory unchanged) - * Multi-dword Vector Memory Operations: - - buffer_load_dword, buffer_load_dwordx2, buffer_load_dwordx3, buffer_load_dwordx4 - - buffer_store_dword, buffer_store_dwordx2, buffer_store_dwordx3, buffer_store_dwordx4 - - Consecutive dwords accessed at byte offsets: +0, +4, +8, +12 - * Lane Activity & Wave Execution: - - Active lanes execute loads and stores. - - Inactive lanes return 0 for loads and never mutate memory for stores. - * Complete deterministic reference interpreter oracle and end-to-end SPIR-V - translation execution via spirv_mini_interp. -""" -from __future__ import annotations - -import gc -import os -import struct -import sys -import tempfile -import unittest -import warnings - -HERE = os.path.dirname(os.path.abspath(__file__)) -ROOT = os.path.dirname(os.path.dirname(HERE)) -TOOLS_DIR = os.environ.get("LEONIDA_TOOLS_DIR") or os.path.join(ROOT, "tools") - -sys.dont_write_bytecode = True -if TOOLS_DIR not in sys.path: - sys.path.insert(0, TOOLS_DIR) -if HERE not in sys.path: - sys.path.insert(0, HERE) - -import rdna2spirv # noqa: E402 -import spirv_mini_interp as si # noqa: E402 - -MASK14 = 0x3FFF -MASK16 = 0xFFFF -MASK32 = 0xFFFFFFFF -MASK64 = 0xFFFFFFFFFFFFFFFF - -STUB_DXBC = b"DXBC" + bytes(24) + struct.pack(" None: - self.d0 = d0 & MASK32 - self.d1 = d1 & MASK32 - self.d2 = d2 & MASK32 - self.d3 = d3 & MASK32 - - @classmethod - def from_fields( - cls, - base_address: int, - stride: int = 0, - num_records: int = 0, - format_code: int = 0, - flags: int = 0, - ) -> BufferResourceDescriptor: - d0 = base_address & MASK32 - base_hi = (base_address >> 32) & MASK16 - stride_field = (stride & MASK14) << 16 - d1 = base_hi | stride_field | ((flags & 3) << 30) - d2 = num_records & MASK32 - d3 = (format_code & 0x7F) << 12 - return cls(d0, d1, d2, d3) - - @property - def base_lo(self) -> int: - return self.d0 - - @property - def base_hi(self) -> int: - return self.d1 & MASK16 - - @property - def stride(self) -> int: - return (self.d1 >> 16) & MASK14 - - @property - def base_64(self) -> int: - return ((self.base_hi << 32) | self.base_lo) & MASK64 - - @property - def num_records(self) -> int: - return self.d2 - - @property - def format_code(self) -> int: - return (self.d3 >> 12) & 0x7F - - def as_words(self) -> tuple[int, int, int, int]: - return (self.d0, self.d1, self.d2, self.d3) - - -def compute_mubuf_address( - desc: BufferResourceDescriptor, - soffset: int = 0, - inst_offset: int = 0, - vaddr_off: int | None = None, - vaddr_idx: int | None = None, -) -> tuple[int, bool, int]: - """Calculates effective 64-bit address, bounds status, and total byte offset. - - Returns: - (effective_address, in_bounds, total_offset) - """ - total = (soffset + inst_offset) & MASK32 - if vaddr_idx is not None: - total = (total + (vaddr_idx & MASK32) * desc.stride) & MASK32 - if vaddr_off is not None: - total = (total + (vaddr_off & MASK32)) & MASK32 - - effective_addr = (desc.base_64 + total) & MASK64 - - is_raw = desc.stride == 0 - tot_ok = total < desc.num_records - if vaddr_idx is not None: - idx_ok = (vaddr_idx & MASK32) < desc.num_records - in_bounds = tot_ok if is_raw else idx_ok - else: - limit = desc.num_records * desc.stride - str_ok = total < limit - in_bounds = tot_ok if is_raw else str_ok - - return effective_addr, in_bounds, total - - -class MubufReferenceInterpreter: - """Semantic reference interpreter modeling untyped MUBUF loads and stores.""" - - def __init__(self, memory: dict[int, int] | None = None) -> None: - self.memory = {} if memory is None else dict(memory) - self.sgprs = [0] * 106 - self.vgprs = [0] * 256 - self.active_lane = True - - def set_sgpr_range(self, start: int, values: tuple[int, ...] | list[int]) -> None: - for i, val in enumerate(values): - self.sgprs[start + i] = val & MASK32 - - def set_vgpr(self, reg: int, val: int) -> None: - self.vgprs[reg] = val & MASK32 - - def get_vgpr(self, reg: int) -> int: - return self.vgprs[reg] & MASK32 - - def get_descriptor(self, start_sgpr: int) -> BufferResourceDescriptor: - return BufferResourceDescriptor( - self.sgprs[start_sgpr], - self.sgprs[start_sgpr + 1], - self.sgprs[start_sgpr + 2], - self.sgprs[start_sgpr + 3], - ) - - def read_dword(self, byte_addr: int) -> int: - return self.memory.get(byte_addr & MASK64, 0) & MASK32 - - def write_dword(self, byte_addr: int, val: int) -> None: - self.memory[byte_addr & MASK64] = val & MASK32 - - def buffer_load_dword( - self, - vdst: int, - srsrc: int, - soffset: int = 0, - inst_offset: int = 0, - vaddr_off: int | None = None, - vaddr_idx: int | None = None, - num_dwords: int = 1, - ) -> list[int]: - desc = self.get_descriptor(srsrc) - addr, in_bounds, _ = compute_mubuf_address( - desc, - soffset=soffset, - inst_offset=inst_offset, - vaddr_off=vaddr_off, - vaddr_idx=vaddr_idx, - ) - loaded = [] - for i in range(num_dwords): - if self.active_lane and in_bounds: - val = self.read_dword(addr + 4 * i) - else: - val = 0 - self.set_vgpr(vdst + i, val) - loaded.append(val) - return loaded - - def buffer_store_dword( - self, - vdata: int, - srsrc: int, - soffset: int = 0, - inst_offset: int = 0, - vaddr_off: int | None = None, - vaddr_idx: int | None = None, - num_dwords: int = 1, - ) -> bool: - desc = self.get_descriptor(srsrc) - addr, in_bounds, _ = compute_mubuf_address( - desc, - soffset=soffset, - inst_offset=inst_offset, - vaddr_off=vaddr_off, - vaddr_idx=vaddr_idx, - ) - if self.active_lane and in_bounds: - for i in range(num_dwords): - val = self.get_vgpr(vdata + i) - self.write_dword(addr + 4 * i, val) - return True - return False - - -class WaveMubufInterpreter: - """Multi-lane SIMD wave reference interpreter modeling RDNA2 Wave32/Wave64 MUBUF operations.""" - - def __init__(self, wave_size: int = 64, memory: dict[int, int] | None = None) -> None: - self.wave_size = wave_size - self.memory = {} if memory is None else dict(memory) - self.sgprs = [0] * 106 - self.vgprs = [[0] * 256 for _ in range(wave_size)] - self.exec_mask = (1 << wave_size) - 1 - - def set_sgpr_range(self, start: int, values: tuple[int, ...] | list[int]) -> None: - for i, val in enumerate(values): - self.sgprs[start + i] = val & MASK32 - - def set_lane_vgpr(self, lane: int, reg: int, val: int) -> None: - self.vgprs[lane][reg] = val & MASK32 - - def get_lane_vgpr(self, lane: int, reg: int) -> int: - return self.vgprs[lane][reg] & MASK32 - - def set_exec_mask(self, mask: int) -> None: - self.exec_mask = mask & ((1 << self.wave_size) - 1) - - def is_lane_active(self, lane: int) -> bool: - return bool((self.exec_mask >> lane) & 1) - - def get_descriptor(self, start_sgpr: int) -> BufferResourceDescriptor: - return BufferResourceDescriptor( - self.sgprs[start_sgpr], - self.sgprs[start_sgpr + 1], - self.sgprs[start_sgpr + 2], - self.sgprs[start_sgpr + 3], - ) - - def read_dword(self, byte_addr: int) -> int: - return self.memory.get(byte_addr & MASK64, 0) & MASK32 - - def write_dword(self, byte_addr: int, val: int) -> None: - self.memory[byte_addr & MASK64] = val & MASK32 - - def buffer_load_dword( - self, - vdst: int, - srsrc: int, - soffset: int = 0, - inst_offset: int = 0, - vaddr_off_reg: int | None = None, - vaddr_idx_reg: int | None = None, - num_dwords: int = 1, - ) -> list[list[int]]: - desc = self.get_descriptor(srsrc) - wave_results = [] - for lane in range(self.wave_size): - vaddr_off = self.get_lane_vgpr(lane, vaddr_off_reg) if vaddr_off_reg is not None else None - vaddr_idx = self.get_lane_vgpr(lane, vaddr_idx_reg) if vaddr_idx_reg is not None else None - addr, in_bounds, _ = compute_mubuf_address( - desc, - soffset=soffset, - inst_offset=inst_offset, - vaddr_off=vaddr_off, - vaddr_idx=vaddr_idx, - ) - lane_loaded = [] - for i in range(num_dwords): - if self.is_lane_active(lane) and in_bounds: - val = self.read_dword(addr + 4 * i) - else: - val = 0 - self.set_lane_vgpr(lane, vdst + i, val) - lane_loaded.append(val) - wave_results.append(lane_loaded) - return wave_results - - def buffer_store_dword( - self, - vdata: int, - srsrc: int, - soffset: int = 0, - inst_offset: int = 0, - vaddr_off_reg: int | None = None, - vaddr_idx_reg: int | None = None, - num_dwords: int = 1, - ) -> list[bool]: - desc = self.get_descriptor(srsrc) - stored_flags = [] - for lane in range(self.wave_size): - vaddr_off = self.get_lane_vgpr(lane, vaddr_off_reg) if vaddr_off_reg is not None else None - vaddr_idx = self.get_lane_vgpr(lane, vaddr_idx_reg) if vaddr_idx_reg is not None else None - addr, in_bounds, _ = compute_mubuf_address( - desc, - soffset=soffset, - inst_offset=inst_offset, - vaddr_off=vaddr_off, - vaddr_idx=vaddr_idx, - ) - if self.is_lane_active(lane) and in_bounds: - for i in range(num_dwords): - val = self.get_lane_vgpr(lane, vdata + i) - self.write_dword(addr + 4 * i, val) - stored_flags.append(True) - else: - stored_flags.append(False) - return stored_flags - - -class MubufSpirvHarness: - """Manages translation and fragment execution for MUBUF shaders.""" - - def __init__(self) -> None: - self.tmp_dir = tempfile.TemporaryDirectory() - self.disasm_dir = os.path.join(self.tmp_dir.name, "disasm") - os.mkdir(self.disasm_dir) - self.src_path = os.path.join(self.disasm_dir, "ps_mubuf.s") - self.dxbc_path = os.path.join(self.tmp_dir.name, "ps_mubuf.dxbc") - with open(self.dxbc_path, "wb") as f: - f.write(STUB_DXBC) - - def cleanup(self) -> None: - gc.collect() - self.tmp_dir.cleanup() - - def translate_and_run( - self, asm: str, memory: dict[int, int] | None = None - ) -> tuple[tuple[int, ...], dict[int, int]]: - with open(self.src_path, "w", encoding="utf-8") as f: - f.write(asm) - with warnings.catch_warnings(): - warnings.simplefilter("ignore", ResourceWarning) - spv = rdna2spirv.translate(self.src_path) - mem = {} if memory is None else dict(memory) - res = si.run_fragment(spv, memory=mem) - mrt0 = res.get("%out_mrt0", (0, 0, 0, 0)) - return tuple(mrt0), mem - - -class TestDescriptorExpansion(unittest.TestCase): - """Verifies V# descriptor field unpacking and 64-bit pointer expansion.""" - - def test_base_address_reconstruction(self): - desc = BufferResourceDescriptor.from_fields(base_address=0x00007FFF12345678) - self.assertEqual(desc.base_lo, 0x12345678) - self.assertEqual(desc.base_hi, 0x7FFF) - self.assertEqual(desc.base_64, 0x00007FFF12345678) - - def test_stride_and_flags_masked_from_base(self): - desc = BufferResourceDescriptor.from_fields( - base_address=0x00000004AABBCCDD, - stride=128, - num_records=1024, - flags=3, - ) - self.assertEqual(desc.base_hi, 0x0004) - self.assertEqual(desc.stride, 128) - self.assertEqual(desc.base_64, 0x00000004AABBCCDD) - self.assertNotEqual(desc.d1 & 0xFFFF0000, 0) - self.assertEqual(desc.d1 & 0xFFFF, 0x0004) - - def test_stride_bitfield_extraction(self): - for stride_val in (0, 4, 16, 64, 256, 1024, 16383): - with self.subTest(stride=stride_val): - desc = BufferResourceDescriptor.from_fields(base_address=0x1000, stride=stride_val) - self.assertEqual(desc.stride, stride_val) - - def test_num_records_raw_vs_structured(self): - raw_desc = BufferResourceDescriptor.from_fields(0x1000, stride=0, num_records=4096) - self.assertEqual(raw_desc.num_records, 4096) - self.assertEqual(raw_desc.stride, 0) - - struct_desc = BufferResourceDescriptor.from_fields(0x1000, stride=32, num_records=64) - self.assertEqual(struct_desc.num_records, 64) - self.assertEqual(struct_desc.stride, 32) - - def test_format_code_extraction(self): - for code in (0, 13, 20, 22, 60, 62, 75): - with self.subTest(code=code): - desc = BufferResourceDescriptor.from_fields(0x1000, format_code=code) - self.assertEqual(desc.format_code, code) - - def test_boundary_base_addresses(self): - zero_desc = BufferResourceDescriptor.from_fields(0) - self.assertEqual(zero_desc.base_64, 0) - - boundary_desc = BufferResourceDescriptor.from_fields(0x0000FFFFFFFFFFFF) - self.assertEqual(boundary_desc.base_lo, 0xFFFFFFFF) - self.assertEqual(boundary_desc.base_hi, 0xFFFF) - self.assertEqual(boundary_desc.base_64, 0x0000FFFFFFFFFFFF) - - -class TestOffsetArithmeticAndBounds(unittest.TestCase): - """Verifies effective address math and bounds checking for raw and structured buffers.""" - - def test_raw_buffer_in_bounds(self): - desc = BufferResourceDescriptor.from_fields(base_address=0x2000, stride=0, num_records=256) - addr, in_b, total = compute_mubuf_address(desc, soffset=16, inst_offset=32, vaddr_off=48) - self.assertEqual(total, 96) - self.assertEqual(addr, 0x2060) - self.assertTrue(in_b) - - def test_raw_buffer_exact_boundaries(self): - desc = BufferResourceDescriptor.from_fields(base_address=0x1000, stride=0, num_records=100) - _, in_b_96, _ = compute_mubuf_address(desc, inst_offset=96) - self.assertTrue(in_b_96) - - _, in_b_99, _ = compute_mubuf_address(desc, inst_offset=99) - self.assertTrue(in_b_99) - - _, in_b_100, _ = compute_mubuf_address(desc, inst_offset=100) - self.assertFalse(in_b_100) - - _, in_b_104, _ = compute_mubuf_address(desc, inst_offset=104) - self.assertFalse(in_b_104) - - def test_structured_buffer_idxen_in_bounds(self): - desc = BufferResourceDescriptor.from_fields(base_address=0x4000, stride=64, num_records=10) - addr, in_b, total = compute_mubuf_address(desc, inst_offset=8, vaddr_idx=3) - self.assertEqual(total, 3 * 64 + 8) - self.assertEqual(addr, 0x4000 + 200) - self.assertTrue(in_b) - - def test_structured_buffer_idxen_boundaries(self): - desc = BufferResourceDescriptor.from_fields(base_address=0x4000, stride=64, num_records=10) - _, in_b_last, _ = compute_mubuf_address(desc, vaddr_idx=9) - self.assertTrue(in_b_last) - - _, in_b_limit, _ = compute_mubuf_address(desc, vaddr_idx=10) - self.assertFalse(in_b_limit) - - _, in_b_beyond, _ = compute_mubuf_address(desc, vaddr_idx=15) - self.assertFalse(in_b_beyond) - - def test_structured_buffer_idxen_and_offen(self): - desc = BufferResourceDescriptor.from_fields(base_address=0x1000, stride=32, num_records=8) - addr, in_b, total = compute_mubuf_address( - desc, soffset=4, inst_offset=8, vaddr_idx=2, vaddr_off=12 - ) - expected_total = 4 + 8 + 2 * 32 + 12 - self.assertEqual(total, expected_total) - self.assertEqual(addr, 0x1000 + expected_total) - self.assertTrue(in_b) - - def test_structured_buffer_without_idxen(self): - desc = BufferResourceDescriptor.from_fields(base_address=0x1000, stride=16, num_records=4) - _, in_b_60, _ = compute_mubuf_address(desc, vaddr_off=60) - self.assertTrue(in_b_60) - - _, in_b_64, _ = compute_mubuf_address(desc, vaddr_off=64) - self.assertFalse(in_b_64) - - def test_address_addition_modulo_64(self): - desc = BufferResourceDescriptor.from_fields(base_address=0xFFFFFFFFFFFFFFF0, stride=0, num_records=0x1000) - addr, _, _ = compute_mubuf_address(desc, inst_offset=0x20) - self.assertEqual(addr, (1 << 48) | 0x10) - - -class TestReferenceInterpreterLoads(unittest.TestCase): - """Verifies reference interpreter execution of untyped buffer loads.""" - - def setUp(self): - self.mem = { - 0x1000: 0x11111111, - 0x1004: 0x22222222, - 0x1008: 0x33333333, - 0x100C: 0x44444444, - 0x1080: 0x55555555, - 0x1084: 0x66666666, - } - self.interp = MubufReferenceInterpreter(self.mem) - - def test_single_dword_load_in_bounds(self): - desc = BufferResourceDescriptor.from_fields(0x1000, stride=0, num_records=64) - self.interp.set_sgpr_range(0, desc.as_words()) - res = self.interp.buffer_load_dword(vdst=2, srsrc=0, vaddr_off=4, num_dwords=1) - self.assertEqual(res, [0x22222222]) - self.assertEqual(self.interp.get_vgpr(2), 0x22222222) - - def test_multi_dword_loads_in_bounds(self): - desc = BufferResourceDescriptor.from_fields(0x1000, stride=0, num_records=64) - self.interp.set_sgpr_range(0, desc.as_words()) - res_x2 = self.interp.buffer_load_dword(vdst=2, srsrc=0, vaddr_off=0, num_dwords=2) - self.assertEqual(res_x2, [0x11111111, 0x22222222]) - - res_x4 = self.interp.buffer_load_dword(vdst=4, srsrc=0, vaddr_off=0, num_dwords=4) - self.assertEqual(res_x4, [0x11111111, 0x22222222, 0x33333333, 0x44444444]) - self.assertEqual([self.interp.get_vgpr(4 + i) for i in range(4)], res_x4) - - def test_single_dword_load_oob_returns_zero(self): - desc = BufferResourceDescriptor.from_fields(0x1000, stride=0, num_records=16) - self.interp.set_sgpr_range(0, desc.as_words()) - res = self.interp.buffer_load_dword(vdst=2, srsrc=0, vaddr_off=64, num_dwords=1) - self.assertEqual(res, [0]) - self.assertEqual(self.interp.get_vgpr(2), 0) - - def test_multi_dword_load_oob_returns_zeros(self): - desc = BufferResourceDescriptor.from_fields(0x1000, stride=0, num_records=16) - self.interp.set_sgpr_range(0, desc.as_words()) - res = self.interp.buffer_load_dword(vdst=2, srsrc=0, vaddr_off=32, num_dwords=4) - self.assertEqual(res, [0, 0, 0, 0]) - - def test_inactive_lane_load_returns_zero(self): - desc = BufferResourceDescriptor.from_fields(0x1000, stride=0, num_records=64) - self.interp.set_sgpr_range(0, desc.as_words()) - self.interp.active_lane = False - res = self.interp.buffer_load_dword(vdst=2, srsrc=0, vaddr_off=0, num_dwords=1) - self.assertEqual(res, [0]) - self.assertEqual(self.interp.get_vgpr(2), 0) - - def test_structured_load_idxen(self): - desc = BufferResourceDescriptor.from_fields(0x1000, stride=64, num_records=4) - self.interp.set_sgpr_range(0, desc.as_words()) - res_idx2 = self.interp.buffer_load_dword(vdst=2, srsrc=0, vaddr_idx=2, num_dwords=1) - self.assertEqual(res_idx2, [0x55555555]) - - res_oob = self.interp.buffer_load_dword(vdst=2, srsrc=0, vaddr_idx=5, num_dwords=1) - self.assertEqual(res_oob, [0]) - - -class TestReferenceInterpreterStores(unittest.TestCase): - """Verifies reference interpreter execution of untyped buffer stores.""" - - def setUp(self): - self.interp = MubufReferenceInterpreter() - - def test_single_dword_store_in_bounds(self): - desc = BufferResourceDescriptor.from_fields(0x2000, stride=0, num_records=64) - self.interp.set_sgpr_range(0, desc.as_words()) - self.interp.set_vgpr(10, 0xCAFEBABE) - ok = self.interp.buffer_store_dword(vdata=10, srsrc=0, vaddr_off=16, num_dwords=1) - self.assertTrue(ok) - self.assertEqual(self.interp.read_dword(0x2010), 0xCAFEBABE) - - def test_multi_dword_stores_in_bounds(self): - desc = BufferResourceDescriptor.from_fields(0x2000, stride=0, num_records=64) - self.interp.set_sgpr_range(0, desc.as_words()) - for i, val in enumerate((0xAAAA0001, 0xAAAA0002, 0xAAAA0003, 0xAAAA0004)): - self.interp.set_vgpr(10 + i, val) - - ok = self.interp.buffer_store_dword(vdata=10, srsrc=0, vaddr_off=0, num_dwords=4) - self.assertTrue(ok) - self.assertEqual(self.interp.read_dword(0x2000), 0xAAAA0001) - self.assertEqual(self.interp.read_dword(0x2004), 0xAAAA0002) - self.assertEqual(self.interp.read_dword(0x2008), 0xAAAA0003) - self.assertEqual(self.interp.read_dword(0x200C), 0xAAAA0004) - - def test_single_dword_store_oob_suppressed(self): - desc = BufferResourceDescriptor.from_fields(0x2000, stride=0, num_records=32) - self.interp.set_sgpr_range(0, desc.as_words()) - self.interp.set_vgpr(10, 0xDEADBEEF) - ok = self.interp.buffer_store_dword(vdata=10, srsrc=0, vaddr_off=64, num_dwords=1) - self.assertFalse(ok) - self.assertEqual(self.interp.read_dword(0x2040), 0) - - def test_multi_dword_store_oob_suppressed(self): - desc = BufferResourceDescriptor.from_fields(0x2000, stride=0, num_records=16) - self.interp.set_sgpr_range(0, desc.as_words()) - self.interp.set_vgpr(10, 0x1111) - self.interp.set_vgpr(11, 0x2222) - ok = self.interp.buffer_store_dword(vdata=10, srsrc=0, vaddr_off=32, num_dwords=2) - self.assertFalse(ok) - self.assertEqual(len(self.interp.memory), 0) - - def test_inactive_lane_store_suppressed(self): - desc = BufferResourceDescriptor.from_fields(0x2000, stride=0, num_records=64) - self.interp.set_sgpr_range(0, desc.as_words()) - self.interp.set_vgpr(10, 0x12345678) - self.interp.active_lane = False - ok = self.interp.buffer_store_dword(vdata=10, srsrc=0, vaddr_off=0, num_dwords=1) - self.assertFalse(ok) - self.assertEqual(len(self.interp.memory), 0) - - def test_structured_store_idxen(self): - desc = BufferResourceDescriptor.from_fields(0x1000, stride=32, num_records=4) - self.interp.set_sgpr_range(0, desc.as_words()) - self.interp.set_vgpr(5, 0x77778888) - ok = self.interp.buffer_store_dword(vdata=5, srsrc=0, vaddr_idx=2, num_dwords=1) - self.assertTrue(ok) - self.assertEqual(self.interp.read_dword(0x1040), 0x77778888) - - ok_oob = self.interp.buffer_store_dword(vdata=5, srsrc=0, vaddr_idx=4, num_dwords=1) - self.assertFalse(ok_oob) - self.assertEqual(self.interp.read_dword(0x1080), 0) - - def test_adjacent_memory_preserved(self): - desc = BufferResourceDescriptor.from_fields(0x1000, stride=0, num_records=64) - self.interp.set_sgpr_range(0, desc.as_words()) - self.interp.write_dword(0x1000, 0xAAAAAAAA) - self.interp.write_dword(0x1008, 0xCCCCCCCC) - self.interp.set_vgpr(1, 0xBBBBBBBB) - self.interp.buffer_store_dword(vdata=1, srsrc=0, vaddr_off=4, num_dwords=1) - self.assertEqual(self.interp.read_dword(0x1000), 0xAAAAAAAA) - self.assertEqual(self.interp.read_dword(0x1004), 0xBBBBBBBB) - self.assertEqual(self.interp.read_dword(0x1008), 0xCCCCCCCC) - - -class TestWaveInterpreter(unittest.TestCase): - """Verifies multi-lane SIMD wave execution (Wave32 and Wave64) with divergence and lane masking.""" - - def test_wave64_divergent_loads_with_exec_mask(self): - wave = WaveMubufInterpreter(wave_size=64) - desc = BufferResourceDescriptor.from_fields(0x1000, stride=0, num_records=256) - wave.set_sgpr_range(0, desc.as_words()) - - # Populate memory with lane-specific words - for i in range(64): - wave.write_dword(0x1000 + i * 4, 0x10000000 | i) - - # Each lane has its own byte offset in v0 - for lane in range(64): - wave.set_lane_vgpr(lane, 0, lane * 4) - - # Active mask: lower half active (lanes 0..31), upper half disabled (lanes 32..63) - wave.set_exec_mask((1 << 32) - 1) - results = wave.buffer_load_dword(vdst=1, srsrc=0, vaddr_off_reg=0, num_dwords=1) - - for lane in range(32): - self.assertEqual(results[lane], [0x10000000 | lane]) - self.assertEqual(wave.get_lane_vgpr(lane, 1), 0x10000000 | lane) - for lane in range(32, 64): - self.assertEqual(results[lane], [0]) - self.assertEqual(wave.get_lane_vgpr(lane, 1), 0) - - def test_wave32_divergent_stores_with_checkerboard_mask(self): - wave = WaveMubufInterpreter(wave_size=32) - desc = BufferResourceDescriptor.from_fields(0x2000, stride=0, num_records=256) - wave.set_sgpr_range(0, desc.as_words()) - - for lane in range(32): - wave.set_lane_vgpr(lane, 0, lane * 4) # offset - wave.set_lane_vgpr(lane, 1, 0xCAFE0000 | lane) # data - - # Checkerboard mask: only odd lanes active (0xAAAAAAAA) - checkerboard = 0xAAAAAAAA - wave.set_exec_mask(checkerboard) - flags = wave.buffer_store_dword(vdata=1, srsrc=0, vaddr_off_reg=0, num_dwords=1) - - for lane in range(32): - addr = 0x2000 + lane * 4 - if lane % 2 == 1: - self.assertTrue(flags[lane]) - self.assertEqual(wave.read_dword(addr), 0xCAFE0000 | lane) - else: - self.assertFalse(flags[lane]) - self.assertEqual(wave.read_dword(addr), 0) - - def test_wave_boundary_oob_split(self): - wave = WaveMubufInterpreter(wave_size=64) - # Buffer holds 16 dwords (64 bytes) - desc = BufferResourceDescriptor.from_fields(0x4000, stride=0, num_records=64) - wave.set_sgpr_range(0, desc.as_words()) - - for i in range(16): - wave.write_dword(0x4000 + i * 4, 0xA000 | i) - - # All lanes active - wave.set_exec_mask((1 << 64) - 1) - for lane in range(64): - wave.set_lane_vgpr(lane, 0, lane * 4) - - results = wave.buffer_load_dword(vdst=5, srsrc=0, vaddr_off_reg=0, num_dwords=1) - - # Lanes 0..15 are within 64 bytes - for lane in range(16): - self.assertEqual(results[lane], [0xA000 | lane]) - self.assertEqual(wave.get_lane_vgpr(lane, 5), 0xA000 | lane) - # Lanes 16..63 are out of bounds -> return 0 - for lane in range(16, 64): - self.assertEqual(results[lane], [0]) - self.assertEqual(wave.get_lane_vgpr(lane, 5), 0) - - def test_wave_multi_dword_stores(self): - wave = WaveMubufInterpreter(wave_size=16) - desc = BufferResourceDescriptor.from_fields(0x8000, stride=0, num_records=512) - wave.set_sgpr_range(0, desc.as_words()) - - for lane in range(16): - wave.set_lane_vgpr(lane, 0, lane * 16) # 16-byte spacing - wave.set_lane_vgpr(lane, 2, 0x11110000 | lane) - wave.set_lane_vgpr(lane, 3, 0x22220000 | lane) - - wave.set_exec_mask(0xFFFF) - flags = wave.buffer_store_dword(vdata=2, srsrc=0, vaddr_off_reg=0, num_dwords=2) - - for lane in range(16): - self.assertTrue(flags[lane]) - base_addr = 0x8000 + lane * 16 - self.assertEqual(wave.read_dword(base_addr), 0x11110000 | lane) - self.assertEqual(wave.read_dword(base_addr + 4), 0x22220000 | lane) - self.assertEqual(wave.read_dword(base_addr + 8), 0) - - -class TestSpirvTranslationLoads(unittest.TestCase): - """End-to-end SPIR-V translation and execution for untyped buffer loads.""" - - def setUp(self): - self.harness = MubufSpirvHarness() - self.addCleanup(self.harness.cleanup) - - def test_spv_load_dword_raw_offen(self): - asm = ( - "; test_load_raw_offen\n" - "\ts_mov_b32 s0, 0x1000\n" - "\ts_mov_b32 s1, 0\n" - "\ts_mov_b32 s2, 0x100\n" - "\ts_mov_b32 s3, 0x30000000\n" - "\tv_mov_b32 v1, 0x10\n" - "\tbuffer_load_dword v2, v1, s[0:3], 0 offen\n" - "\ts_waitcnt vmcnt(0)\n" - "\texp mrt0 v2, v2, v2, v2 done vm\n" - "\ts_endpgm\n" - ) - mrt, _ = self.harness.translate_and_run(asm, memory={0x1010: 0x12345678}) - self.assertEqual(mrt[0], 0x12345678) - - def test_spv_load_dword_raw_offset_imm(self): - asm = ( - "; test_load_raw_offset_imm\n" - "\ts_mov_b32 s0, 0x1000\n" - "\ts_mov_b32 s1, 0\n" - "\ts_mov_b32 s2, 0x100\n" - "\ts_mov_b32 s3, 0x30000000\n" - "\tbuffer_load_dword v2, off, s[0:3], 0 offset:24\n" - "\ts_waitcnt vmcnt(0)\n" - "\texp mrt0 v2, v2, v2, v2 done vm\n" - "\ts_endpgm\n" - ) - mrt, _ = self.harness.translate_and_run(asm, memory={0x1018: 0x87654321}) - self.assertEqual(mrt[0], 0x87654321) - - def test_spv_load_dword_raw_soffset_sgpr(self): - asm = ( - "; test_load_raw_soffset_sgpr\n" - "\ts_mov_b32 s0, 0x1000\n" - "\ts_mov_b32 s1, 0\n" - "\ts_mov_b32 s2, 0x100\n" - "\ts_mov_b32 s3, 0x30000000\n" - "\ts_mov_b32 s4, 0x20\n" - "\tv_mov_b32 v1, 0x10\n" - "\tbuffer_load_dword v2, v1, s[0:3], s4 offen offset:8\n" - "\ts_waitcnt vmcnt(0)\n" - "\texp mrt0 v2, v2, v2, v2 done vm\n" - "\ts_endpgm\n" - ) - mrt, _ = self.harness.translate_and_run(asm, memory={0x1038: 0xABCDEF01}) - self.assertEqual(mrt[0], 0xABCDEF01) - - def test_spv_load_dword_raw_oob_returns_zero(self): - asm = ( - "; test_load_raw_oob\n" - "\ts_mov_b32 s0, 0x1000\n" - "\ts_mov_b32 s1, 0\n" - "\ts_mov_b32 s2, 0x80\n" - "\ts_mov_b32 s3, 0x30000000\n" - "\tv_mov_b32 v1, 0x100\n" - "\tbuffer_load_dword v2, v1, s[0:3], 0 offen\n" - "\ts_waitcnt vmcnt(0)\n" - "\texp mrt0 v2, v2, v2, v2 done vm\n" - "\ts_endpgm\n" - ) - mrt, _ = self.harness.translate_and_run(asm, memory={0x1100: 0x99999999}) - self.assertEqual(mrt[0], 0) - - def test_spv_load_dword_structured_idxen(self): - stride = 64 - s1_val = (stride << 16) | 0 - asm = ( - "; test_load_struct_idxen\n" - "\ts_mov_b32 s0, 0x1000\n" - f"\ts_mov_b32 s1, {s1_val:#x}\n" - "\ts_mov_b32 s2, 4\n" - "\ts_mov_b32 s3, 0\n" - "\tv_mov_b32 v0, 2\n" - "\tbuffer_load_dword v2, v0, s[0:3], 0 idxen\n" - "\ts_waitcnt vmcnt(0)\n" - "\texp mrt0 v2, v2, v2, v2 done vm\n" - "\ts_endpgm\n" - ) - mrt, _ = self.harness.translate_and_run(asm, memory={0x1080: 0x5555AAAA}) - self.assertEqual(mrt[0], 0x5555AAAA) - - def test_spv_load_dword_structured_idxen_oob_returns_zero(self): - stride = 64 - s1_val = (stride << 16) | 0 - asm = ( - "; test_load_struct_idxen_oob\n" - "\ts_mov_b32 s0, 0x1000\n" - f"\ts_mov_b32 s1, {s1_val:#x}\n" - "\ts_mov_b32 s2, 4\n" - "\ts_mov_b32 s3, 0\n" - "\tv_mov_b32 v0, 4\n" - "\tbuffer_load_dword v2, v0, s[0:3], 0 idxen\n" - "\ts_waitcnt vmcnt(0)\n" - "\texp mrt0 v2, v2, v2, v2 done vm\n" - "\ts_endpgm\n" - ) - mrt, _ = self.harness.translate_and_run(asm, memory={0x1100: 0x5555AAAA}) - self.assertEqual(mrt[0], 0) - - def test_spv_load_dword_structured_idxen_offen(self): - stride = 64 - s1_val = (stride << 16) | 0 - asm = ( - "; test_load_struct_idxen_offen\n" - "\ts_mov_b32 s0, 0x1000\n" - f"\ts_mov_b32 s1, {s1_val:#x}\n" - "\ts_mov_b32 s2, 4\n" - "\ts_mov_b32 s3, 0\n" - "\tv_mov_b32 v0, 1\n" - "\tv_mov_b32 v1, 12\n" - "\tbuffer_load_dword v2, v[0:1], s[0:3], 0 idxen offen offset:4\n" - "\ts_waitcnt vmcnt(0)\n" - "\texp mrt0 v2, v2, v2, v2 done vm\n" - "\ts_endpgm\n" - ) - mrt, _ = self.harness.translate_and_run(asm, memory={0x1050: 0x77778888}) - self.assertEqual(mrt[0], 0x77778888) - - def test_spv_load_dword_structured_raw_offset(self): - stride = 64 - s1_val = (stride << 16) | 0 - asm = ( - "; test_load_struct_raw_offset\n" - "\ts_mov_b32 s0, 0x1000\n" - f"\ts_mov_b32 s1, {s1_val:#x}\n" - "\ts_mov_b32 s2, 4\n" - "\ts_mov_b32 s3, 0\n" - "\tv_mov_b32 v1, 60\n" - "\tbuffer_load_dword v2, v1, s[0:3], 0 offen\n" - "\tv_mov_b32 v3, 64\n" - "\tbuffer_load_dword v4, v3, s[0:3], 0 offen\n" - "\ts_waitcnt vmcnt(0)\n" - "\texp mrt0 v2, v4, v2, v4 done vm\n" - "\ts_endpgm\n" - ) - mrt, _ = self.harness.translate_and_run(asm, memory={0x103C: 0xAAAA1111, 0x1040: 0xBBBB2222}) - self.assertEqual(mrt[0], 0xAAAA1111) - self.assertEqual(mrt[1], 0) - - def test_spv_load_dwordx2_x3_x4(self): - asm = ( - "; test_load_multi_dword\n" - "\ts_mov_b32 s0, 0x1000\n" - "\ts_mov_b32 s1, 0\n" - "\ts_mov_b32 s2, 0x100\n" - "\ts_mov_b32 s3, 0x30000000\n" - "\tv_mov_b32 v1, 0\n" - "\tbuffer_load_dwordx4 v[2:5], v1, s[0:3], 0 offen\n" - "\ts_waitcnt vmcnt(0)\n" - "\texp mrt0 v2, v3, v4, v5 done vm\n" - "\ts_endpgm\n" - ) - mem = {0x1000: 0x01, 0x1004: 0x02, 0x1008: 0x03, 0x100C: 0x04} - mrt, _ = self.harness.translate_and_run(asm, memory=mem) - self.assertEqual(mrt, (0x01, 0x02, 0x03, 0x04)) - - def test_spv_load_descriptor_masking(self): - s1_val = (128 << 16) | 0x0001 - asm = ( - "; test_load_descriptor_masking\n" - "\ts_mov_b32 s0, 0x1000\n" - f"\ts_mov_b32 s1, {s1_val:#x}\n" - "\ts_mov_b32 s2, 0x1000\n" - "\ts_mov_b32 s3, 0\n" - "\tv_mov_b32 v1, 0\n" - "\tbuffer_load_dword v2, v1, s[0:3], 0 offen\n" - "\ts_waitcnt vmcnt(0)\n" - "\texp mrt0 v2, v2, v2, v2 done vm\n" - "\ts_endpgm\n" - ) - mem = {0x000100001000: 0xFEDCBA98} - mrt, _ = self.harness.translate_and_run(asm, memory=mem) - self.assertEqual(mrt[0], 0xFEDCBA98) - - -class TestSpirvTranslationStores(unittest.TestCase): - """End-to-end SPIR-V translation and execution for untyped buffer stores.""" - - def setUp(self): - self.harness = MubufSpirvHarness() - self.addCleanup(self.harness.cleanup) - - def test_spv_store_dword_raw_offen(self): - asm = ( - "; test_store_raw_offen\n" - "\ts_mov_b32 s0, 0x2000\n" - "\ts_mov_b32 s1, 0\n" - "\ts_mov_b32 s2, 0x100\n" - "\ts_mov_b32 s3, 0x30000000\n" - "\tv_mov_b32 v1, 0x10\n" - "\tv_mov_b32 v2, 0xCAFEBABE\n" - "\tbuffer_store_dword v2, v1, s[0:3], 0 offen\n" - "\ts_waitcnt vmcnt(0)\n" - "\texp mrt0 v2, v2, v2, v2 done vm\n" - "\ts_endpgm\n" - ) - _, mem = self.harness.translate_and_run(asm) - self.assertEqual(mem.get(0x2010), 0xCAFEBABE) - - def test_spv_store_dword_raw_offset_imm(self): - asm = ( - "; test_store_raw_offset_imm\n" - "\ts_mov_b32 s0, 0x2000\n" - "\ts_mov_b32 s1, 0\n" - "\ts_mov_b32 s2, 0x100\n" - "\ts_mov_b32 s3, 0x30000000\n" - "\tv_mov_b32 v2, 0x99887766\n" - "\tbuffer_store_dword v2, off, s[0:3], 0 offset:32\n" - "\ts_waitcnt vmcnt(0)\n" - "\texp mrt0 v2, v2, v2, v2 done vm\n" - "\ts_endpgm\n" - ) - _, mem = self.harness.translate_and_run(asm) - self.assertEqual(mem.get(0x2020), 0x99887766) - - def test_spv_store_dword_raw_soffset_sgpr(self): - asm = ( - "; test_store_raw_soffset_sgpr\n" - "\ts_mov_b32 s0, 0x2000\n" - "\ts_mov_b32 s1, 0\n" - "\ts_mov_b32 s2, 0x100\n" - "\ts_mov_b32 s3, 0x30000000\n" - "\ts_mov_b32 s4, 0x30\n" - "\tv_mov_b32 v1, 0x08\n" - "\tv_mov_b32 v2, 0x11223344\n" - "\tbuffer_store_dword v2, v1, s[0:3], s4 offen offset:4\n" - "\ts_waitcnt vmcnt(0)\n" - "\texp mrt0 v2, v2, v2, v2 done vm\n" - "\ts_endpgm\n" - ) - _, mem = self.harness.translate_and_run(asm) - self.assertEqual(mem.get(0x203C), 0x11223344) - - def test_spv_store_dword_raw_oob_suppressed(self): - asm = ( - "; test_store_raw_oob\n" - "\ts_mov_b32 s0, 0x2000\n" - "\ts_mov_b32 s1, 0\n" - "\ts_mov_b32 s2, 0x80\n" - "\ts_mov_b32 s3, 0x30000000\n" - "\tv_mov_b32 v1, 0x80\n" - "\tv_mov_b32 v2, 0xDEADDEAD\n" - "\tbuffer_store_dword v2, v1, s[0:3], 0 offen\n" - "\ts_waitcnt vmcnt(0)\n" - "\texp mrt0 v2, v2, v2, v2 done vm\n" - "\ts_endpgm\n" - ) - _, mem = self.harness.translate_and_run(asm) - self.assertEqual(mem, {}) - - def test_spv_store_dword_structured_idxen(self): - stride = 32 - s1_val = (stride << 16) | 0 - asm = ( - "; test_store_struct_idxen\n" - "\ts_mov_b32 s0, 0x3000\n" - f"\ts_mov_b32 s1, {s1_val:#x}\n" - "\ts_mov_b32 s2, 4\n" - "\ts_mov_b32 s3, 0\n" - "\tv_mov_b32 v0, 3\n" - "\tv_mov_b32 v2, 0x55667788\n" - "\tbuffer_store_dword v2, v0, s[0:3], 0 idxen\n" - "\ts_waitcnt vmcnt(0)\n" - "\texp mrt0 v2, v2, v2, v2 done vm\n" - "\ts_endpgm\n" - ) - _, mem = self.harness.translate_and_run(asm) - self.assertEqual(mem.get(0x3000 + 3 * 32), 0x55667788) - - def test_spv_store_dword_structured_idxen_oob_suppressed(self): - stride = 32 - s1_val = (stride << 16) | 0 - asm = ( - "; test_store_struct_idxen_oob\n" - "\ts_mov_b32 s0, 0x3000\n" - f"\ts_mov_b32 s1, {s1_val:#x}\n" - "\ts_mov_b32 s2, 4\n" - "\ts_mov_b32 s3, 0\n" - "\tv_mov_b32 v0, 4\n" - "\tv_mov_b32 v2, 0xBAD00BAD\n" - "\tbuffer_store_dword v2, v0, s[0:3], 0 idxen\n" - "\ts_waitcnt vmcnt(0)\n" - "\texp mrt0 v2, v2, v2, v2 done vm\n" - "\ts_endpgm\n" - ) - _, mem = self.harness.translate_and_run(asm) - self.assertEqual(mem, {}) - - def test_spv_store_dword_structured_idxen_offen(self): - stride = 64 - s1_val = (stride << 16) | 0 - asm = ( - "; test_store_struct_idxen_offen\n" - "\ts_mov_b32 s0, 0x1000\n" - f"\ts_mov_b32 s1, {s1_val:#x}\n" - "\ts_mov_b32 s2, 4\n" - "\ts_mov_b32 s3, 0\n" - "\ts_mov_b32 s4, 4\n" - "\tv_mov_b32 v0, 1\n" - "\tv_mov_b32 v1, 8\n" - "\tv_mov_b32 v2, 0x33445566\n" - "\tbuffer_store_dword v2, v[0:1], s[0:3], s4 idxen offen offset:16\n" - "\ts_waitcnt vmcnt(0)\n" - "\texp mrt0 v2, v2, v2, v2 done vm\n" - "\ts_endpgm\n" - ) - _, mem = self.harness.translate_and_run(asm) - self.assertEqual(mem.get(0x105C), 0x33445566) - - def test_spv_store_dwordx2_x3_x4(self): - asm = ( - "; test_store_multi_dword\n" - "\ts_mov_b32 s0, 0x4000\n" - "\ts_mov_b32 s1, 0\n" - "\ts_mov_b32 s2, 0x100\n" - "\ts_mov_b32 s3, 0x30000000\n" - "\tv_mov_b32 v1, 0\n" - "\tv_mov_b32 v2, 0x10101010\n" - "\tv_mov_b32 v3, 0x20202020\n" - "\tv_mov_b32 v4, 0x30303030\n" - "\tv_mov_b32 v5, 0x40404040\n" - "\tbuffer_store_dwordx4 v[2:5], v1, s[0:3], 0 offen\n" - "\ts_waitcnt vmcnt(0)\n" - "\texp mrt0 v2, v3, v4, v5 done vm\n" - "\ts_endpgm\n" - ) - _, mem = self.harness.translate_and_run(asm) - self.assertEqual(mem.get(0x4000), 0x10101010) - self.assertEqual(mem.get(0x4004), 0x20202020) - self.assertEqual(mem.get(0x4008), 0x30303030) - self.assertEqual(mem.get(0x400C), 0x40404040) - - def test_spv_store_descriptor_masking(self): - s1_val = (64 << 16) | 0x0002 - asm = ( - "; test_store_descriptor_masking\n" - "\ts_mov_b32 s0, 0x2000\n" - f"\ts_mov_b32 s1, {s1_val:#x}\n" - "\ts_mov_b32 s2, 0x1000\n" - "\ts_mov_b32 s3, 0\n" - "\tv_mov_b32 v1, 0\n" - "\tv_mov_b32 v2, 0xABCD1234\n" - "\tbuffer_store_dword v2, v1, s[0:3], 0 offen\n" - "\ts_waitcnt vmcnt(0)\n" - "\texp mrt0 v2, v2, v2, v2 done vm\n" - "\ts_endpgm\n" - ) - _, mem = self.harness.translate_and_run(asm) - self.assertEqual(mem.get(0x000200002000), 0xABCD1234) - - -class TestNegativeControlsAndMutations(unittest.TestCase): - """Verifies that intentional descriptor/offset/boundary mutations fail semantic checks.""" - - def test_unmasked_descriptor_base_corrupts_address(self): - desc = BufferResourceDescriptor.from_fields(0x1000, stride=64, num_records=10) - correct_addr, _, _ = compute_mubuf_address(desc, inst_offset=16) - - corrupted_hi = desc.d1 - corrupted_base_64 = (corrupted_hi << 32) | desc.d0 - corrupted_addr = (corrupted_base_64 + 16) & MASK64 - self.assertNotEqual(correct_addr, corrupted_addr) - - def test_corrupted_stride_diverges(self): - desc = BufferResourceDescriptor.from_fields(0x1000, stride=32, num_records=10) - addr_correct, _, _ = compute_mubuf_address(desc, vaddr_idx=2) - - corrupted_desc = BufferResourceDescriptor.from_fields(0x1000, stride=64, num_records=10) - addr_corrupted, _, _ = compute_mubuf_address(corrupted_desc, vaddr_idx=2) - self.assertNotEqual(addr_correct, addr_corrupted) - - def test_corrupted_bounds_check_diverges(self): - desc = BufferResourceDescriptor.from_fields(0x1000, stride=0, num_records=100) - _, in_b_correct, _ = compute_mubuf_address(desc, inst_offset=100) - self.assertFalse(in_b_correct) - - in_b_corrupted = 100 <= desc.num_records - self.assertTrue(in_b_corrupted) - - def test_unsupported_modifiers_rejected(self): - harness = MubufSpirvHarness() - self.addCleanup(harness.cleanup) - for mod in ("lds", "tfe"): - with self.subTest(mod=mod): - asm = ( - f"; test_unsupported_{mod}\n" - "\ts_mov_b32 s0, 0x1000\n" - "\ts_mov_b32 s1, 0\n" - "\ts_mov_b32 s2, 0x100\n" - "\ts_mov_b32 s3, 0\n" - f"\tbuffer_load_dword v2, v1, s[0:3], 0 offen {mod}\n" - "\ts_endpgm\n" - ) - with self.assertRaises(rdna2spirv.Unsupported): - harness.translate_and_run(asm) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_vop3_const_mods.py b/tests/semantic/test_vop3_const_mods.py deleted file mode 100644 index 55839b5a3..000000000 --- a/tests/semantic/test_vop3_const_mods.py +++ /dev/null @@ -1,245 +0,0 @@ -"""Semantic interpreter tests for VOP3 FP input modifiers on numeric constants and literals. - -LLVM AMDGPUInstPrinter::printOperandAndFPInputMods prints VOP3 FP source modifiers on inline constants and 32-bit -literals as ``neg()``, ``||`` and ``-||`` (and the assembler also accepts ``abs()`` and -``neg(abs())``). In hardware, ``abs`` clears the sign bit first and ``neg`` flips the sign bit second: - - * ``-|1.0|``, ``-|-2.0|``, ``neg(|1.0|)`` -> ``-1.0`` / ``-2.0`` / ``-1.0`` (previously ``shader_ir`` folded the - outer ``-`` into ``v`` with ``abs=True`` and no ``neg``, so ``FAbs`` turned them positive). - * ``neg(0x3f800000)`` -> ``0xbf800000`` (``-1.0f``) and ``neg(0x3c00)`` -> ``0xbc00`` (``-1.0h``) (previously - ``shader_ir`` did two's-complement negation, producing ``-4.0f`` / ``-4.0h``). - * ``neg(1)`` -> ``0x80000001`` (negative f32 subnormal), NOT ``-1`` (``0xffffffff``, quiet NaN). - * ``|0xbf800000|``, ``-|0x3f800000|``, ``-|0|`` preserve ``abs`` and ``neg`` on integer/hex literals (previously - ``shader_ir`` dropped ``abs`` on ``imm`` operands). - -Each case translates a synthetic pixel shader with ``tools/rdna2spirv.py`` and executes it in -``tests/semantic/spirv_mini_interp.py`` (no llvm-mc, SPIRV-Tools, GPU or game data needed). -""" -import os -import re -import struct -import sys -import tempfile -import unittest -import warnings -from pathlib import Path - -HERE = os.path.dirname(os.path.abspath(__file__)) -ROOT = os.path.dirname(os.path.dirname(HERE)) -TOOLS_DIR = os.environ.get("LEONIDA_TOOLS_DIR") or os.path.join(ROOT, "tools") - -sys.dont_write_bytecode = True -sys.path.insert(0, TOOLS_DIR) -sys.path.insert(0, HERE) - -import rdna2spirv # noqa: E402 -import spirv_mini_interp as si # noqa: E402 - -STUB_DXBC = b"DXBC" + bytes(24) + struct.pack(" quiet NaN (class bit 1 = 0x002) - # neg(1) = 0x80000001 -> negative subnormal (class bit 4 = 0x010) - # neg(-1) = 0x7fffffff -> positive quiet NaN (class bit 1 = 0x002) - # -|0| = 0x80000000 -> negative zero (class bit 5 = 0x020) - got = run([ - "v_cmp_class_f32_e64 s4, neg(1), 0x10", - "v_cndmask_b32_e64 v0, 0, 1, s4", - "v_cmp_class_f32_e64 s5, -1, 0x10", - "v_cndmask_b32_e64 v1, 0, 1, s5", - "v_cmp_class_f32_e64 s6, neg(-1), 0x2", - "v_cndmask_b32_e64 v2, 0, 1, s6", - "v_cmp_class_f32_e64 s7, -|0|, 0x20", - "v_cndmask_b32_e64 v3, 0, 1, s7", - ]) - self.assertEqual(got, [1, 0, 1, 1]) - - def test_compare_with_modified_constants(self): - got = run([ - "v_mov_b32 v4, 0xbf800000", # -1.0f - "v_cmp_eq_f32_e64 s4, v4, -|1.0|", - "v_cndmask_b32_e64 v0, 0, 1, s4", - "v_cmp_eq_f32_e64 s5, v4, neg(0x3f800000)", - "v_cndmask_b32_e64 v1, 0, 1, s5", - "v_cmp_eq_f32_e64 s6, 1.0, |0xbf800000|", - "v_cndmask_b32_e64 v2, 0, 1, s6", - "v_cmp_u_f32_e64 s7, neg(1), 0.0", # neg(1) is a subnormal, NOT NaN - "v_cndmask_b32_e64 v3, 0, 1, s7", - ]) - self.assertEqual(got, [1, 1, 1, 0]) - - -class F16AndMixConstModifierTests(unittest.TestCase): - def test_f16_alu_and_compare_with_modified_constants(self): - # f16 inline and literal constants: 0x3c00 = +1.0h, 0xbc00 = -1.0h. - got = run([ - "v_add_f16_e64 v0, 0, -|1.0|", - "v_add_f16_e64 v1, 0, neg(0x3c00)", - "v_add_f16_e64 v2, 0, |0xbc00|", - "v_add_f16_e64 v3, 0, -|0x3c00|", - ]) - self.assertEqual([w & 0xFFFF for w in got], [0xBC00, 0xBC00, 0x3C00, 0xBC00]) - - def test_f16_cvt_compare_and_fma_mix(self): - got = run([ - "v_cvt_f32_f16_e64 v0, -|0.5|", - "v_cvt_f32_f16_e64 v1, neg(0x3c00)", - "v_fma_mix_f32 v2, -|0x3c00|, 2.0, 0.5 op_sel:[0,0,0] op_sel_hi:[1,0,0]", - "v_cmp_eq_f16_e64 s4, -1.0, -|1.0|", - "v_cndmask_b32_e64 v3, 0, 1, s4", - ]) - # -0.5f, -1.0f, -1.0h * 2.0f + 0.5f = -1.5f, compare true = 1 - self.assertEqual(got, [0xBF000000, 0xBF800000, 0xBFC00000, 1]) - - def test_v_pack_b32_f16_neg_flips_the_packed_half(self): - # SHADER-260, measured on gfx1036: `neg` on this instruction is a plain sign flip of the half it packs, - # before any quieting (0x7c01 -> 0xfc01 in IEEE mode 0 and -> 0xfe01 in mode 1), in either half and with - # op_sel. It used to be refused, together with every other modifier (and before that, neg(0x3c00) silently - # folded to -0x3c00 = 0xc400, -4.0h, bypassing the modifier check). - got = run([ - "v_mov_b32 v1, 0x7c01", - "v_pack_b32_f16 v0, neg(0x3c00), 0x4000", # -1.0h in the low half, 2.0h in the high one - "v_pack_b32_f16 v2, neg(v1), v1", # sign flip on the low half only; no quieting is modelled - ]) - self.assertEqual(got[:3], [0x4000BC00, 0x00007C01, 0x7C01FC01]) - - def test_v_pack_b32_f16_abs_clears_the_sign_of_the_packed_half(self): - # `abs` is the ISA's sign clear (|S|), applied before `neg`; it has no hardware run of this instruction yet. - got = run([ - "v_mov_b32 v1, 0xbc00", - "v_pack_b32_f16 v0, abs(0xbc00), 0x4000", # +1.0h in the low half, 2.0h in the high one - "v_pack_b32_f16 v2, -abs(v1), v1", # clear then flip the low half; src1 stays -1.0h - ]) - self.assertEqual(got[:3], [0x40003C00, 0x0000BC00, 0xBC00BC00]) - -class F64ConstModifierStructureTests(unittest.TestCase): - def test_unary_f64_literals_reach_the_operation_as_high_words(self) -> None: - fixture = Path(HERE) / "fixtures" / "unary_f64_literals.asm" - unary = [line for line in fixture.read_text(encoding="ascii").splitlines() if "_e32 " in line] - for line in unary[:3]: - with self.subTest(line=line): - spv = translate([line]) - literal = int(line.rsplit(" ", 1)[1], 16) - self.assertIn(f"OpCompositeConstruct %v2uint_d %c0 %c{literal:x}", spv) - - # frexp uses integer words alone. Execute the mantissa and exponent paths and read both destination words. - for spelling, expected in (("0x40180000", [0, 0x3fe80000, 3]), ("2.0", [0, 0x3fe00000, 2]), - ("1", [0, 0x3fe00000, (-1073) & 0xffffffff])): # 2^-1074 = 0.5 * 2^-1073 - with self.subTest(spelling=spelling): - lines = [op.replace("0x40180000", spelling) for op in unary[3:]] - got = run(lines, export="v8, v9, v7, v7") - self.assertEqual(got[:3], expected) - - def test_f64_literal_and_inline_source_words(self) -> None: - fixture = Path(HERE) / "fixtures" / "f64_literals.asm" - instructions = [line for line in fixture.read_text(encoding="utf-8").splitlines() - if line and not line.startswith(";")] - spv = translate(instructions) - words = {name: int(value) for name, value in - re.findall(r"(%\w+) = OpConstant %uint (\d+)", spv)} - pairs = {name: (words[high] << 32) | words[low] for name, low, high in - re.findall(r"(%\w+) = OpCompositeConstruct %v2uint_d (%\w+) (%\w+)", spv)} - doubles = {name: pairs[pair] for name, pair in - re.findall(r"(%\w+) = OpBitcast %double (%\w+)", spv)} - conversions = re.findall(r"OpFConvert %float (%\w+)", spv) - additions = re.findall(r"OpFAdd %double (%\w+) (%\w+)", spv) - self.assertEqual([doubles[source] for source in conversions], - [0x3FF8000000000000, 0xFFF0000000000000, 64, 0xFFFFFFFFFFFFFFFF]) - self.assertEqual([(doubles[left], doubles[right]) for left, right in additions], - [(0x0000000100000000, 1), (0x3FF0000000000000, 0xBFF8000000000000)]) - - def test_f64_emits_fabs_then_fnegate_for_neg_abs_const(self): - spv = translate([ - "v_cvt_f32_f64 v0, -|1.0|", - "v_cvt_f32_f64 v1, neg(0)", - "v_mov_b32 v2, 0", - "v_mov_b32 v3, 0", - ]) - # For -|1.0|: FAbs %double must precede OpFNegate %double feeding OpFConvert %float. - m_abs = re.search(r"(%\w+) = OpExtInst %double %glsl FAbs (%\w+)", spv) - self.assertIsNotNone(m_abs, "expected double FAbs for -|1.0|") - abs_id = m_abs.group(1) - m_neg = re.search(rf"(%\w+) = OpFNegate %double {re.escape(abs_id)}\b", spv) - self.assertIsNotNone(m_neg, "expected double OpFNegate after FAbs for -|1.0|") - # For neg(0): OpFNegate %double on bitcast of (0, 0). - self.assertGreaterEqual(len(re.findall(r"= OpFNegate %double ", spv)), 2) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_vopc_const_ordered.py b/tests/semantic/test_vopc_const_ordered.py deleted file mode 100644 index 5bde5de83..000000000 --- a/tests/semantic/test_vopc_const_ordered.py +++ /dev/null @@ -1,158 +0,0 @@ -"""Semantic interpreter tests for the constant and ordered/unordered RDNA2 VOPC compares. - - v_cmp_f_{i32,u32}, v_cmp_f_{f32,f16}: always false - v_cmp_t_{i32,u32}, v_cmp_tru_{f32,f16}: always true - v_cmp_o_{f32,f16}: ordered, true when neither source is NaN - v_cmp_u_{f32,f16}: unordered, true when either source is NaN -The result goes to VCC (VOPC), to an SGPR mask (VOP3) or, for v_cmpx, to EXEC. Each case translates a synthetic pixel -shader with tools/rdna2spirv.py, runs it in tests/semantic/spirv_mini_interp.py and compares lane 0's bit with a -plain-Python reference. The bit leaves through exp as 0x40000000 or 0x40000001 (always a normal float). -""" -import math -import os -import struct -import sys -import tempfile -import unittest -import warnings - -HERE = os.path.dirname(os.path.abspath(__file__)) -ROOT = os.path.dirname(os.path.dirname(HERE)) -TOOLS_DIR = os.environ.get("LEONIDA_TOOLS_DIR") or os.path.join(ROOT, "tools") - -sys.dont_write_bytecode = True -sys.path.insert(0, TOOLS_DIR) -sys.path.insert(0, HERE) - -import rdna2spirv # noqa: E402 -import spirv_mini_interp as si # noqa: E402 - -STUB_DXBC = b"DXBC" + bytes(24) + struct.pack(" bool: - return (u & 0x7F800000) == 0x7F800000 and (u & 0x7FFFFF) != 0 - - -def is_nan16(u: int) -> bool: - return (u & 0x7C00) == 0x7C00 and (u & 0x3FF) != 0 - - -def ref(cond: str, nan_x: bool, nan_y: bool) -> int: - return int({"f": False, "t": True, "tru": True, "o": not (nan_x or nan_y), "u": nan_x or nan_y}[cond]) - - -_TMP_DIR = None -_SRC_PATH = None - - -def setUpModule(): - global _TMP_DIR, _SRC_PATH - _TMP_DIR = tempfile.TemporaryDirectory() - disasm_dir = os.path.join(_TMP_DIR.name, "disasm") - os.mkdir(disasm_dir) - _SRC_PATH = os.path.join(disasm_dir, "ps_vopc_const.s") - with open(os.path.join(_TMP_DIR.name, "ps_vopc_const.dxbc"), "wb") as f: - f.write(STUB_DXBC) - - -def tearDownModule(): - global _TMP_DIR - if _TMP_DIR is not None: - _TMP_DIR.cleanup() - _TMP_DIR = None - - -def run_bit(x: int, y: int, line: str, mask: str = "vcc_lo", preset: int = 0, *, - active: bool = True, restore_exec: bool = False) -> int | None: - """v1 = x, v2 = y, the mask preset to all ones or zero, then ``line``; return lane 0's bit of ``mask``.""" - if _TMP_DIR is None: - setUpModule() - lines = [f"v_mov_b32 v1, {x:#x}", f"v_mov_b32 v2, {y:#x}", f"s_mov_b32 vcc_lo, {-1 if preset else 0}", - f"s_mov_b32 s10, {-1 if preset else 0}"] - if not active: - lines.append("s_mov_b32 exec_lo, 0") - lines.append(line) - if restore_exec: - lines.append("s_mov_b32 exec_lo, -1") - lines.append(f"v_cndmask_b32 v0, 0x40000000, 0x40000001, {mask}") - asm = "; test_vopc_const\n" + "".join(f"\t{ln}\n" for ln in lines) + "\texp mrt0 v0, v0, v0, v0 done vm\n\ts_endpgm\n" - with open(_SRC_PATH, "w", encoding="utf-8") as f: - f.write(asm) - with warnings.catch_warnings(): - warnings.simplefilter("ignore", ResourceWarning) - spv = rdna2spirv.translate(_SRC_PATH) - w = si.run_fragment(spv).get("%out_mrt0") - if w is None: - return None # the lane was switched off (v_cmpx with a false result) - assert w[0] >> 1 == 0x20000000, hex(w[0]) - return w[0] & 1 - - -class ConstOrderedCompareTests(unittest.TestCase): - def test_reference(self): - self.assertTrue(is_nan32(0x7F800001) and not is_nan32(0x7F800000)) - self.assertTrue(is_nan16(0x7C01) and not is_nan16(0x7C00)) - self.assertEqual(ref("o", False, True), 0) - self.assertEqual(ref("u", False, True), 1) - - def test_float_compares(self): - for ty, values, nan in (("f32", F32, is_nan32), ("f16", F16, is_nan16)): - for cond in ("f", "tru", "o", "u"): - for x in values: - for y in values[::3]: - with self.subTest(op=f"v_cmp_{cond}_{ty}", x=hex(x), y=hex(y)): - want = ref(cond, nan(x), nan(y)) - got = run_bit(x, y, f"v_cmp_{cond}_{ty} vcc_lo, v1, v2", preset=1 - want) - self.assertEqual(got, want) - - def test_integer_constant_compares(self): - for ty in ("u32", "i32"): - for cond in ("f", "t"): - for x, y in ((0, 0), (1, 2), (0xFFFFFFFF, 0)): - with self.subTest(op=f"v_cmp_{cond}_{ty}", x=x, y=y): - want = ref(cond, False, False) - self.assertEqual(run_bit(x, y, f"v_cmp_{cond}_{ty} vcc_lo, v1, v2", preset=1 - want), want) - - def test_64bit_constant_predicates(self) -> None: - with open(os.path.join(HERE, "fixtures", "vopc_constant_64.asm"), encoding="ascii") as fixture: - instructions = [line.strip() for line in fixture if line.startswith("v_cmp")] - self.assertEqual(len(instructions), 12) - for line in instructions: - cmpx = line.startswith("v_cmpx_") - want = "_f_" not in line - mask = "s10" if " s10," in line else "vcc_lo" - for active in (False, True): - with self.subTest(line=line, active=active): - # v1 is the high word of the first source: a NaN for f64 cases. - if cmpx: - self.assertEqual(run_bit(0x7ff80000, 1, line, preset=1, active=active), - 1 if active and want else None) - else: - self.assertEqual(run_bit(0x7ff80000, 1, line, mask=mask, preset=1 - int(active and want), - active=active, restore_exec=True), int(active and want)) - if cmpx or mask == "s10": - with self.subTest(line=line, destination="VCC unchanged"): - preset = int(not want) - self.assertEqual(run_bit(0x7ff80000, 1, line, preset=preset, restore_exec=True), preset) - - def test_vop3_form_writes_the_named_mask(self): - self.assertEqual(run_bit(0x7FC00000, 0x3F800000, "v_cmp_u_f32_e64 s10, v1, v2", mask="s10"), 1) - self.assertEqual(run_bit(0x7FC00000, 0x3F800000, "v_cmp_o_f32_e64 s10, v1, v2", mask="s10", preset=1), 0) - self.assertEqual(run_bit(5, 6, "v_cmp_t_u32_e64 s10, v1, v2", mask="s10"), 1) - # VCC is left alone when the VOP3 form names another mask. - self.assertEqual(run_bit(5, 6, "v_cmp_t_u32_e64 s10, v1, v2", mask="vcc_lo"), 0) - - def test_cmpx_writes_exec(self): - # v_cmpx: EXEC &= result. A true result keeps the lane (it exports); a false one switches it off. - self.assertEqual(run_bit(0x7FC00000, 0, "v_cmpx_u_f32 v1, v2", preset=1), 1) - self.assertIsNone(run_bit(0x3F800000, 0, "v_cmpx_u_f32 v1, v2", preset=1)) - self.assertEqual(run_bit(0, 0, "v_cmpx_t_i32 v1, v2", preset=1), 1) - self.assertIsNone(run_bit(0, 0, "v_cmpx_f_u32 v1, v2", preset=1)) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_vs_readfirstlane.py b/tests/semantic/test_vs_readfirstlane.py deleted file mode 100644 index ebf8db9f8..000000000 --- a/tests/semantic/test_vs_readfirstlane.py +++ /dev/null @@ -1,114 +0,0 @@ -"""v_readfirstlane_b32 handles first-active lanes without crossing wave32 pixel halves. - - python -I tests/semantic/test_vs_readfirstlane.py - -A native (not --wave64-emulate) readfirstlane is a ballot of the EXEC lanes, its lowest set bit and a shuffle from -that lane. A wave32 pixel shader selects the ballot word and physical lane for its own 32-lane half, since a -fragment subgroup may contain two logical waves. MoltenVK lowers OpGroupNonUniformBallotFindLSB, like the SubgroupSize built-in, to Metal's -`threads_per_simdgroup` input, which a vertex function can't declare ("invalid 'threads_per_simdgroup' attribute for -input declaration in a vertex function", Apple M4, MoltenVK 1.4.2), so every VS with a readfirstlane failed to -compile there. A vertex shader takes the lowest set bit with FindILsb over the ballot's four words, which Metal -accepts in a vertex function; wave32 pixel shaders use the same word-wise operation to isolate a logical wave. -Other stages keep BallotFindLSB. A ballot has no bits at or above the subgroup size, so the two give the same lane -(docs/design.md, the v_readfirstlane_b32 row). - -Hand-written listings run on the strict wave interpreter (spirv_wave_interp.py) with vertex index = lane, with the -first EXEC lane in each ballot word. No llvm-mc, GPU or game data. -""" -import os -import re -import sys -import unittest - -HERE = os.path.dirname(os.path.abspath(__file__)) -sys.path.insert(0, HERE) -import support # noqa: E402,F401 (sets the tools path) -from support import translate_listing # noqa: E402 -import spirv_wave_interp as wi # noqa: E402 - -LITERAL_OPS = ("exp", "buffer_", "global_", "ds_", "image_") - - -def size(text): - """Byte size for the fake encoding the translator places branch offsets with.""" - op = text.split()[0] - if op.startswith(LITERAL_OPS) or op.endswith("_e64") or "0x" in text: - return 8 - return 4 - - -def listing(name, lines): - out = f"; {name} synthetic\n" - for text in lines: - out += f"\t{text} ; encoding: [{','.join(['0x00'] * size(text))}]\n" - return out.encode() - - -def first_lane_vs(first, wave64): - """A VS whose lanes below `first` are off in EXEC around `v_readfirstlane_b32 s20, v4` (v4 = 3 * vertex + 1); - every lane then exports s20 in param0.x.""" - if wave64: - save, restore, andsave = (["s_mov_b64 s[10:11], exec"], ["s_mov_b64 exec, s[10:11]"], - ["s_and_saveexec_b64 s[12:13], vcc"]) - else: - save, restore, andsave = (["s_mov_b32 s10, exec_lo"], ["s_mov_b32 exec_lo, s10"], - ["s_and_saveexec_b32 s12, vcc_lo"]) - return (save + ["v_mul_u32_u24_e32 v4, 3, v0", "v_add_nc_u32_e32 v4, 1, v4", - f"v_cmp_lt_u32_e32 vcc, {first - 1}, v0"] + andsave + - ["v_readfirstlane_b32 s20, v4"] + restore + - ["v_mov_b32_e32 v5, 0", "v_mov_b32_e32 v6, s20", "exp pos0 v5, v5, v5, v5 done", - "exp param0 v6, v5, v5, v5", "s_endpgm"]) - - -def param0_x(asm, wave): - res = wi.run_wave(asm, wave=wave, builtins={"VertexIndex": lambda lane: lane, "InstanceIndex": lambda lane: 0}) - xs = [] - for out in res["outputs"]: - word = next(v for name, v in out.items() if name.endswith("param0")) - xs.append(word[0].bits if isinstance(word[0], wi.F) else word[0]) - return xs - - -class VertexReadFirstLane(unittest.TestCase): - def check(self, wave, first): - asm = translate_listing(f"vs_rfl_{wave}_{first}", listing("vs", first_lane_vs(first, wave > 32))) - self.assertEqual(param0_x(asm, wave), [3 * first + 1] * wave) - return asm - - def test_first_lane_in_word_0(self): - for first in (1, 6, 31): - with self.subTest(first=first): - self.check(32, first) - - def test_first_lane_in_word_1_of_a_64_lane_subgroup(self): - for first in (32, 40, 63): - with self.subTest(first=first): - self.check(64, first) - - def test_all_four_ballot_words_are_read(self): - # Vulkan allows subgroups of up to 128 invocations (the interpreter runs 32 and 64), so all four words count. - asm = self.check(32, 6) - bal = re.search(r"(%\w+) = OpGroupNonUniformBallot ", asm).group(1) - words = set(re.findall(rf"= OpCompositeExtract %uint {re.escape(bal)} (\d)\b", asm)) - self.assertEqual(words, {"0", "1", "2", "3"}) - - def test_no_ballot_find_lsb_or_subgroup_size_in_a_vertex_shader(self): - asm = self.check(32, 6) - self.assertNotIn("OpGroupNonUniformBallotFindLSB", asm) - self.assertIsNone(re.search(r"BuiltIn SubgroupSize\b", asm)) - self.assertIn("OpGroupNonUniformBallot ", asm) - self.assertIn("FindILsb", asm) - - def test_wave32_pixel_shader_selects_its_subgroup_half(self): - lines = ["s_mov_b32 s10, exec_lo", "v_cmp_lt_u32_e32 vcc, 5, v2", "s_and_saveexec_b32 s12, vcc_lo", - "v_readfirstlane_b32 s20, v2", "s_mov_b32 exec_lo, s10", "v_mov_b32_e32 v6, s20", - "exp mrt0 v6, v6, v6, v6 done vm", "s_endpgm"] - asm = translate_listing("ps_rfl", listing("ps", lines)) - self.assertNotIn("OpGroupNonUniformBallotFindLSB", asm) - self.assertIn("FindILsb", asm) - self.assertRegex(asm, r"OpBitwiseAnd %uint %\w+ %c20") - self.assertIn("OpGroupNonUniformShuffle", asm) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_w64x_scalar_load_order.py b/tests/semantic/test_w64x_scalar_load_order.py deleted file mode 100644 index 1621afaa7..000000000 --- a/tests/semantic/test_w64x_scalar_load_order.py +++ /dev/null @@ -1,133 +0,0 @@ -"""--wave64-emulate: a scalar load (s_load / s_buffer_load) is ordered with the wave's vector stores (#1587). - -On hardware a wave issues its instructions in order, so every lane's `buffer_store` is done (`s_waitcnt vmcnt(0)`) -before the wave's `s_load` of the same address. Under `--wave64-emulate` the two halves of a wave can run in two -32-wide subgroups, which order memory only at the barrier between rounds (docs/design.md, "Wave64 emulation"). Until -#1587 a scalar load was not one of the accesses `Gen.x_memory_order` cuts a round at, so a store and a later scalar -load of the same wave sat in one segment, and the other half could load before this half had stored: -`tools/valu_fuzz.py --family mem --emulate` found lanes 32-63 reading the buffer's fill pattern after an -`s_buffer_load` / `s_load` of the slot lane 0 had just written (the slot comes from `v_readfirstlane_b32`, which -the emulation already reads over the whole wave). - -The interpreters here don't run workgroup barriers, so this checks the rule on the emitted rounds: the SPIR-V of every -segment (a case of the round loop's `OpSwitch %pcv`) may not access buffer memory (the PhysicalStorageBuffer pointers -both the vector and the scalar memory ops go through) in a conflicting order: no access after a write, no write after -a read. The programs are written here; no game data. -""" -import os -import re -import struct -import sys -import unittest - -HERE = os.path.dirname(os.path.abspath(__file__)) -if HERE not in sys.path: - sys.path.insert(0, HERE) # python -I leaves the script's folder off sys.path - -import support # noqa: E402 (support puts tools/ on sys.path, honouring LEONIDA_TOOLS_DIR) - -rdna2spirv = support.rdna2spirv - -# s[0:3] is the output V# (4 user SGPRs); s[8:9] a 64-bit pointer to the same memory, s[12:15] a V# of it for -# s_buffer_load. Every access is one dword, so one instruction is one OpLoad or OpStore. -HEAD = ["s_mov_b64 exec, -1", "s_mov_b32 s8, 0", "s_mov_b32 s9, 0", - "s_mov_b32 s12, 0", "s_mov_b32 s13, 0", "s_mov_b32 s14, 0x1000", "s_mov_b32 s15, 0x31016FAC", - "v_lshlrev_b32_e32 v1, 2, v0", # v1 = the lane's byte offset - # as in the fuzz program, before any memory op: s16 = the byte offset of the wave's first lane - "v_readfirstlane_b32 s16, v1"] -STORE = ["buffer_store_dword v0, v1, s[0:3], 0 offen", "s_waitcnt vmcnt(0)"] -SLOAD = ["s_load_dword s10, s[8:9], 0x0", "s_waitcnt lgkmcnt(0)", "v_mov_b32_e32 v2, s10"] -# The fuzz program's shape: the slot of the wave's first lane, from v_readfirstlane_b32, as the soffset. -SBUF = ["s_buffer_load_dword s10, s[12:15], s16 offset:0x0", "s_waitcnt lgkmcnt(0)", - "v_mov_b32_e32 v2, s10"] -TAIL = ["buffer_store_dword v2, v1, s[0:3], 0 offen offset:256", "s_endpgm"] - - -def fssm(threads=64): - """Compute header: COMPUTE_PGM_RSRC2 0x8088 (4 user SGPRs, TGID_X), one wave of `threads`.""" - return bytes(0x138) + struct.pack("<4I", 0x8088, threads, 1, 1) - - -def translate(lines, emulate=True): - prev = rdna2spirv.WAVE64_EMULATE - rdna2spirv.WAVE64_EMULATE = emulate - try: - spv = support.translate_lines("cs_w64x_sload_order", lines, fssm=fssm()) - finally: - rdna2spirv.WAVE64_EMULATE = prev - assert rdna2spirv.translate.last_gen.wave64, "the test program must translate as wave64" - return spv - - -def segments(spv): - """{segment label: ["r"/"w", ...]}: the buffer accesses of each case of the round loop's switch, in order.""" - lines = spv.splitlines() - sw = next((ln.split() for ln in lines if ln.split()[:2] == ["OpSwitch", "%pcv"]), None) - assert sw is not None, "no round-loop switch: not an emulated translation" - labels = set(sw[4::2]) - psb = set() - out, cur = {}, None - for ln in lines: - t = ln.split() - if len(t) >= 3 and t[1] == "=" and t[2] == "OpLabel": - if t[0] in labels: - cur = out.setdefault(t[0], []) - elif t[0] == sw[3]: # the default label ends the cases - cur = None - continue - if cur is None: - continue - if len(t) >= 4 and t[2] == "OpAccessChain" and t[3] == "%_ptr_PSB_uint": - psb.add(t[0]) - elif len(t) >= 5 and t[2] == "OpLoad" and t[4] in psb: - cur.append("r") - elif len(t) >= 2 and t[0] == "OpStore" and t[1] in psb: - cur.append("w") - return out - - -def conflicts(segs): - """The segments where an access follows a write, or a write follows a read (x_memory_order's rule).""" - bad = [] - for lab, acc in segs.items(): - s = "".join(acc) - if re.search(r"w.", s) or re.search(r"r.*w", s): - bad.append((lab, s)) - return bad - - -class ScalarLoadOrderTests(unittest.TestCase): - def check_ordered(self, lines, accesses): - segs = segments(translate(lines)) - self.assertEqual(sum(len(a) for a in segs.values()), accesses, segs) # every access was found - self.assertEqual(conflicts(segs), [], segs) - return segs - - def test_store_then_s_load(self): - # read after write: the store's round ends before the load - self.check_ordered(HEAD + STORE + SLOAD + TAIL, 3) - - def test_store_then_s_buffer_load_at_the_first_lane_slot(self): - # the #1587 program shape: buffer_store, then v_readfirstlane_b32 + s_buffer_load - self.check_ordered(HEAD + STORE + SBUF + TAIL, 3) - - def test_s_load_then_store(self): - # write after read: the other half's store may not land before this half's scalar load - self.check_ordered(HEAD + SLOAD + STORE + ["s_endpgm"], 2) - - def test_reads_share_a_round(self): - # loads alone never conflict: two scalar loads and a vector load stay in one segment - lines = HEAD + SLOAD + ["s_load_dword s11, s[8:9], 0x4", "s_waitcnt lgkmcnt(0)", - "buffer_load_dword v3, v1, s[0:3], 0 offen", "s_waitcnt vmcnt(0)", "s_endpgm"] - segs = self.check_ordered(lines, 3) - self.assertIn(["r", "r", "r"], segs.values(), segs) - - def test_native_wave64_is_unchanged(self): - # without the flag there are no rounds: the store and the load are one straight run - spv = translate(HEAD + STORE + SLOAD + TAIL, emulate=False) - self.assertNotIn("%pcv", spv) - self.assertNotIn("OpControlBarrier", spv) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_wave32_bfm64_data.py b/tests/semantic/test_wave32_bfm64_data.py deleted file mode 100644 index e2f122849..000000000 --- a/tests/semantic/test_wave32_bfm64_data.py +++ /dev/null @@ -1,110 +0,0 @@ -"""s_bfm_b64 in wave32 code: 64-bit data, not a lane mask. - -Standard library only; no GPU, no LLVM, no game files. - -RDNA2 ISA SOP2 S_BFM_B64: D = ((1 << (S0 & 63)) - 1) << (S1 & 63), SCC not written. In a 64-lane wave the -translator reads D as a lane mask (each invocation holds its own lane's bit; test_salu_bfm64_add_i32.py). A 32-lane -wave has no 64-bit lane masks, so there it is plain 64-bit data. The pipeline library's wave32 compute programs -(docs/shader_library.md) use it that way: `s_bfm_b64 s[88:89], 2, 54` and `s_mov_b64 s[90:91], 0x18500000` build -an S# in place, which image_sample then reads. Their kind-0 dispatch state says wave32, and until this change the -translator refused all 958 of them ("FSPX wave32 dispatch state contradicts wave64 code"), counting s_bfm_b64 as a -wave64 marker. - -Each case writes fspx/.json with the wave size (the sidecar tools/shader_library.py writes), translates a -compute listing, runs every invocation with run_workgroup and has each store both words at its own slot. -""" -import json -import os -import struct -import sys -import tempfile -import unittest -import warnings - -HERE = os.path.dirname(os.path.abspath(__file__)) -ROOT = os.path.dirname(os.path.dirname(HERE)) -TOOLS_DIR = os.environ.get("LEONIDA_TOOLS_DIR") or os.path.join(ROOT, "tools") - -sys.dont_write_bytecode = True -sys.path.insert(0, TOOLS_DIR) -sys.path.insert(0, HERE) - -import lane_masks # noqa: E402 -import rdna2spirv # noqa: E402 -import spirv_mini_interp as si # noqa: E402 - -STUB_DXBC = b"DXBC" + bytes(24) + struct.pack("> 32)}) - - def test_sampler_words_are_known_constants(self): - # The S# built in place reaches the index's literal samplers, as one moved with s_mov_b64 does. - spv = translate(["s_bfm_b64 s[88:89], 2, 54", "s_mov_b64 s[90:91], 0x18500000", - "s_load_dwordx8 s[80:87], s[0:1], 0x0", "v_mov_b32 v1, 0", "v_mov_b32 v2, 0", - "s_waitcnt lgkmcnt(0)", - "image_sample_lz v5, v[1:2], s[80:87], s[88:91] dmask:0x1 dim:SQ_RSRC_IMG_2D", - "s_waitcnt vmcnt(0)", "buffer_store_dword v5, v0, s[0:3], 0 offen"], wave32=True) - self.assertIn("OpImageSample", spv) - self.assertIn("OpConstant %uint 12582912", spv) # word 1 = (3 << 54) >> 32, folded - - def test_fspx_wave32_with_bfm_is_not_refused(self): - translate(["s_bfm_b64 s[8:9], 2, 54", "s_and_saveexec_b32 s10, vcc_lo", "s_mov_b32 exec_lo, s10"], - wave32=True) - - def test_other_wave64_markers_still_refused(self): - with self.assertRaises(rdna2spirv.Unsupported): - translate(["s_bfm_b64 s[8:9], 2, 54", "s_and_saveexec_b64 s[10:11], vcc"], wave32=True) - - def test_run_time_operand_refused(self): - with self.assertRaises(rdna2spirv.Unsupported): - translate(["s_mov_b32 s5, 2", "v_readfirstlane_b32 s6, v0", "s_bfm_b64 s[8:9], s6, 54"], wave32=True) - - def test_lane_masks_leaves_wave32_result_data(self): - ins = {"op": "s_bfm_b64", "args": [{"k": "sgpr", "r": 8, "n": 2}, {"k": "imm", "v": 2}, - {"k": "imm", "v": 54}], "mods": []} - st64, st32 = {}, {} - lane_masks.step(st64, ins) - lane_masks.step(st32, ins, wave64=False) - self.assertEqual((st64.get(8), st64.get(9)), (lane_masks.MASK_LO, lane_masks.MASK_HI)) - self.assertEqual((st32.get(8), st32.get(9)), (None, None)) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_wave32_lane_select.py b/tests/semantic/test_wave32_lane_select.py deleted file mode 100644 index 5008e38f2..000000000 --- a/tests/semantic/test_wave32_lane_select.py +++ /dev/null @@ -1,70 +0,0 @@ -"""Wave32 lane select of v_readlane_b32 / v_writelane_b32 (SHADER-52), executed across the 32 lanes of the -translated SPIR-V. - -The lane is S1[4:0] in wave32 and S1[5:0] in wave64. Until #488 the translator masked with 63 in wave32 too, so -a lane select of 32 or more wrote no lane, and a read shuffled from a lane past the end of a 32-wide subgroup -(undefined in SPIR-V; NVIDIA happens to wrap it). Found by tools/crosslane_fuzz.py (FUZZ-7). - -tests/test_translate.py checks which masks appear in the SPIR-V text; this runs the result. The input is the GPU -test runtime/test/shaders/cs_w32_lane_wrap.asm (hand-written, no game data; fixture from regen_fixtures.py), -run by spirv_mini_interp.run_workgroup as one 32-thread workgroup on one 32-wide subgroup. A shuffle from lane -32 or more raises UndefinedResult there, so a translation that masks with 63 fails loudly instead of passing on -a driver's wrap. -""" -import re -import struct -import unittest - -import support -import spirv_mini_interp as si - -# 4 user SGPRs (the output V#), workgroup id in s4, 512 bytes of LDS, 32x1x1 threads (the .asm's "; group:"). -FSSM = bytearray(0x148) -struct.pack_into("<4I", FSSM, 0x138, 0x8088, 32, 1, 1) -FSSM = bytes(FSSM) -VSHARP = [0, 0, 0x1000, 0x31016FAC] -# The .asm header (and check.py): readlane(40) = lane 8 = 25, readlane(5) = 16, writelane(40) lands on lane 8, -# so readlane(8) and readlane(40) both give 777. Lane 0 stores the four words. -EXPECTED = [25, 16, 777, 777] - - -def translate(): - return support.translate_fixture("cs_w32_lane_wrap", fssm=FSSM) - - -def run(spv): - memory = si.run_workgroup( - spv, 32, 32, - inputs_for=lambda i: {"%wg_id": (0, 0, 0), "%local_id": (i, 0, 0), "%sg_lane": i}, - push_constants=VSHARP + [0] * 28, memory={}) - stray = sorted(a for a in memory if not 0 <= a < 16 or a % 4) - if stray: - raise AssertionError(f"stores outside out[0..3]: {stray}") - return [memory.get(4 * k) for k in range(4)] - - -class Wave32LaneSelect(unittest.TestCase): - def test_lane_select_uses_bits_4_0(self): - self.assertEqual(run(translate()), EXPECTED) - - def test_mask_63_is_undefined(self): - # Negative control: put the wave64 mask back on the lane selects; the read of lane 40 must then be - # out of range for the subgroup. - spv = translate() - c31 = re.search(r"^(%\S+) = OpConstant %uint 31$", spv, re.M).group(1) - lines = spv.splitlines() - sels = [i for i, ln in enumerate(lines) - if re.search(r"= OpBitwiseAnd %uint \S+ " + re.escape(c31) + "$", ln)] - # Four reads and one write select a lane, plus the wave lane (LocalInvocationIndex & 31), which a wider - # mask leaves unchanged in a 32-thread group. - self.assertGreaterEqual(len(sels), 5) - for i in sels: - lines[i] = lines[i][:-len(c31)] + "%neg_c63" - k = next(i for i, ln in enumerate(lines) if ln.startswith(c31 + " = OpConstant")) - lines.insert(k + 1, "%neg_c63 = OpConstant %uint 63") - with self.assertRaises(si.UndefinedResult): - run("\n".join(lines) + "\n") - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_wave32_pixel_subgroup64.py b/tests/semantic/test_wave32_pixel_subgroup64.py deleted file mode 100644 index 4648aa889..000000000 --- a/tests/semantic/test_wave32_pixel_subgroup64.py +++ /dev/null @@ -1,161 +0,0 @@ -"""Wave32 pixel shaders stay isolated when Vulkan runs them in a 64-lane subgroup. - -The inputs are deliberately different in the two physical halves. Each translated PS is run both as one 64-lane -subgroup and as two 32-lane subgroups; outputs must match the independent logical-wave32 expectations. -""" -import os -import struct -import sys -import unittest - -HERE = os.path.dirname(os.path.abspath(__file__)) -sys.dont_write_bytecode = True -sys.path.insert(0, HERE) - -import support -import spirv_mini_interp as si - - -def fbits(value): - return struct.unpack("= 4] - helpers = [i for i, lane in enumerate(lanes) if lane % 32 < 4] if first_quad == "helpers" else [] - inputs = [float(lane // 32) for lane in lanes] - judged = [i for i in range(len(lanes)) if i not in helpers] - expected = [tuple(fbits(c) for c in texels[1 + lanes[i] // 32]) for i in judged] - for subgroup_size in (32, 64): - with self.subTest(first_quad=first_quad, subgroup_size=subgroup_size): - got = run_ps(spv, subgroup_size, inputs, lanes, push_constants=[base, 0], memory=memory, - resources={"%desc_map": desc_map, "%images": images}, helpers=helpers) - self.assertEqual([got[i] for i in judged], expected) - - def test_readfirstlane_with_zero_exec_falls_back_to_first_running_lane(self): - # When EXEC == 0 across a wave32 fragment half and lane 0 of that half is absent (e.g. uncovered - # first quad), v_readfirstlane_b32 must fall back to wave32_first_running_lane() rather than - # shuffling from absent lane 0 (SPIR-V / Vulkan UB, SHADER-1016). - spv = support.translate_lines("ps_wave32_readfirstlane_zero_exec", [ - "v_interp_mov_f32_e32 v2, p0, attr0.x", - "s_mov_b32 exec_lo, 0", - "v_readfirstlane_b32 s20, v2", - "s_mov_b32 exec_lo, -1", - "v_mov_b32_e32 v6, s20", - "exp mrt0 v6, v6, v6, v6 done vm", - "s_endpgm", - ]) - lanes = [lane for lane in range(64) if lane % 32 >= 4] - inputs = [float(lane + 1) for lane in lanes] - # Lowest running lane is 4 (value 5.0) in half 0 and 36 (value 37.0) in half 1. - expected = [(fbits(5.0 if lane < 32 else 37.0),) * 4 for lane in lanes] - for subgroup_size in (32, 64): - with self.subTest(subgroup_size=subgroup_size): - self.assertEqual(run_ps(spv, subgroup_size, inputs, lanes), expected) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_wave64_cross_half.py b/tests/semantic/test_wave64_cross_half.py deleted file mode 100644 index 13a7f1538..000000000 --- a/tests/semantic/test_wave64_cross_half.py +++ /dev/null @@ -1,175 +0,0 @@ -"""Wave64 cross-half lane operations, executed across all 64 lanes of the translated SPIR-V. - -The inputs are the GPU tests runtime/test/shaders/cs_w64x_readlane, cs_w64x_writelane and cs_w64x_bpermute -(hand-written, no game data; fixtures from regen_fixtures.py). Each is translated without --wave64-emulate and run -by spirv_mini_interp.run_workgroup as one 64-thread workgroup, in two layouts: - -* one 64-wide subgroup (AMD with requiredSubgroupSize = 64). The eight output words must equal the values the - GPU check expects (runtime/test/shaders/check.py W64X_DUMPS, scripts/run_gpu_tests.py), derived in each .asm - header from the RDNA2 ISA: v_readlane/v_writelane select lane S1 % 64 and ignore EXEC; ds_bpermute_b32 works - on each 32-lane half as an independent wave32 (ISA 10.4.4) and reads 0 from a lane that is off in EXEC. -* two 32-wide subgroups, invocations 0-31 and 32-63 (NVIDIA, e.g. an RTX 4070 Super, without emulation). This is - the documented gap in docs/design.md ("Wave64 handling": cross-lane ops between the two halves stay approximate - on 32-wide subgroups). The tests pin which results stay exact there and which do not: - - ds_bpermute_b32 never crosses halves, so all eight words stay exact; - - v_writelane_b32 writes the right lane in both halves (the wave lane comes from LocalInvocationIndex); - - a v_readlane_b32 from the other half shuffles from lane >= 32 of a 32-wide subgroup, which SPIR-V leaves - undefined. Strictly that is UndefinedResult. Under the wrap model (lane Id mod 32, the symptom in issue - #94, an observation and not the specification) the expected words below are what a 32-wide GPU without - --wave64-emulate shows. Measured: NVIDIA GeForce RTX 4070 SUPER (subgroup 32), driver 610.88, Vulkan SDK - 1.4.363.0, `vk_compute_test .spv 1 dump` on the non-emulated build of run_gpu_tests.py: all 24 - words equal WRAP32_EXPECTED. That is one driver's behaviour, not a requirement. - -Limits: --wave64-emulate output uses Workgroup memory and a round loop, which the interpreter rejects, so the -emulated path is covered only by the GPU tests. The subgroup layout (invocation i in subgroup i // 32) is the -usual one for a 1-D workgroup but Vulkan does not guarantee it. -""" -import re -import struct -import unittest - -import support -import spirv_mini_interp as si - -# 4 user SGPRs (the output V#), workgroup id in s4, 512 bytes of LDS, 64x1x1 threads: build.py's default header. -FSSM = bytearray(0x148) -struct.pack_into("<4I", FSSM, 0x138, 0x8088, 64, 1, 1) -FSSM = bytes(FSSM) -# V# in s[0:3]: base 0, stride 0, num_records 0x1000 bytes. out[k] is the dword at byte 4k. -VSHARP = [0, 0, 0x1000, 0x31016FAC] - -# Expected on a 64-wide subgroup: the GPU check's values (check.py W64X_DUMPS). -GPU_EXPECTED = { - "cs_w64x_readlane": [121, 121, 16, 97, 16, 100, 100, 121], - "cs_w64x_writelane": [4660, 77, 99, 2748, 0, 0, 4660, 99], - "cs_w64x_bpermute": [36, 316, 253, 218, 435, 225, 0, 442], -} - -# Two 32-wide subgroups, wrap model. readlane: v2 = 3 * lane + 1 and each subgroup reads lane (S1 % 64) % 32 of -# its own half. The low half reads lane 8 for lane 40 (25), lane 0 for 32 (1) and lane 1 for 33 (4); the upper -# half reads lane 32 + 5 = 37 for lane 5 (112). Words stored by lanes of the half the source lane is in stay right: -# out[0] lane 0: s6 = v2[8] = 25 out[1] lane 33: s6 = v2[40] = 121 out[2] lane 63: s7 = v2[37] = 112 -# out[3] lane 0: s8 = v2[0] = 1 out[4] lane 45: s7 = v2[37] = 112 out[5] lane 7: s9 = v2[1] = 4 -# out[6] lane 60: s9 = v2[33] = 100 out[7] lane 63: v2[40] = 121 -# writelane: the writes are exact, the two readlanes from lanes 0 and 8 read lanes 8 and 31 of the low half, -# which nobody wrote (0). -WRAP32_EXPECTED = { - "cs_w64x_readlane": [25, 121, 112, 1, 112, 4, 100, 121], - "cs_w64x_writelane": [4660, 77, 99, 2748, 0, 0, 0, 0], - "cs_w64x_bpermute": GPU_EXPECTED["cs_w64x_bpermute"], -} - - -def translate(name): - return support.translate_fixture(name, fssm=FSSM) - - -def run(spv, subgroup_size, out_of_range="raise"): - """Run one 64-thread workgroup; return out[0..7] and check nothing was written past them.""" - memory = si.run_workgroup( - spv, 64, subgroup_size, - inputs_for=lambda i: {"%wg_id": (0, 0, 0), "%local_id": (i, 0, 0), "%sg_lane": i % subgroup_size}, - push_constants=VSHARP + [0] * 28, memory={}, out_of_range=out_of_range) - stray = sorted(a for a in memory if not 0 <= a < 32 or a % 4) - if stray: - raise AssertionError(f"stores outside out[0..7]: {stray}") - return [memory.get(4 * k) for k in range(8)] - - -class Wave64OnSubgroup64(unittest.TestCase): - """Exact on a 64-wide subgroup: the values the GPU check expects.""" - - def test_each_shader(self): - for name, want in GPU_EXPECTED.items(): - with self.subTest(shader=name): - self.assertEqual(run(translate(name), 64), want) - - -class Wave64OnTwoSubgroups32(unittest.TestCase): - """The same modules on two 32-wide subgroups, no --wave64-emulate.""" - - def test_bpermute_stays_exact(self): - spv = translate("cs_w64x_bpermute") - self.assertEqual(run(spv, 32), GPU_EXPECTED["cs_w64x_bpermute"]) - - def test_cross_half_readlane_is_undefined(self): - for name in ("cs_w64x_readlane", "cs_w64x_writelane"): - with self.subTest(shader=name): - with self.assertRaisesRegex(si.UndefinedResult, r"lane 40 of a 32-wide subgroup"): - run(translate(name), 32) - - def test_wrap_model_prediction(self): - for name, want in WRAP32_EXPECTED.items(): - with self.subTest(shader=name): - got = run(translate(name), 32, out_of_range="wrap") - self.assertEqual(got, want) - wrong = [k for k in range(8) if got[k] != GPU_EXPECTED[name][k]] - self.assertEqual(bool(wrong), name != "cs_w64x_bpermute", f"{name}: words {wrong} differ") - - def test_writelane_writes_are_exact(self): - # out[0..5] are the written lanes and their untouched neighbours; only the readlanes (out[6..7]) cross. - got = run(translate("cs_w64x_writelane"), 32, out_of_range="wrap") - self.assertEqual(got[:6], GPU_EXPECTED["cs_w64x_writelane"][:6]) - - -class NegativeControls(unittest.TestCase): - """Sabotage the translated SPIR-V the way a translator regression would; the 64-wide result must change.""" - - def sabotage(self, name, pattern, repl, count): - spv = translate(name) - bad, n = re.subn(pattern, repl, spv) - self.assertEqual(n, count, f"anchor {pattern!r} matched {n} times in {name}") - got = run(bad, 64) - self.assertNotEqual(got, GPU_EXPECTED[name]) - return got - - def test_readlane_lane_select_mod_32(self): - # v_readlane lane = S1 & 31 instead of & 63 (the issue #94 symptom, moved into the translator). - got = self.sabotage("cs_w64x_readlane", - r"(OpBitwiseAnd %uint \S+ )%c3f(\n\s*%\w+ = OpGroupNonUniformShuffle)", r"\1%c1f\2", 5) - self.assertEqual(got[0], 25) # lane 40 -> lane 8 - - def test_bpermute_upper_half_reads_low_half(self): - # The half base from the subgroup lane dropped (the bug fixed on 2026-11-21, see docs/design.md "LDS"). - got = self.sabotage("cs_w64x_bpermute", - r"(= OpLoad %uint %sg_lane\n\s*%\w+ = OpBitwiseAnd %uint %\w+ )%c20", r"\1%c0", 3) - self.assertEqual(got[1], 7 * 13 + 1) # lane 40 reads lane 13 of the low half instead of lane 45 - - -_SHIFT_MODULE = """ -%uint = OpTypeInt 32 0 -%bool = OpTypeBool -%c1 = OpConstant %uint 1 -%c7 = OpConstant %uint 7 -%c40 = OpConstant %uint 40 -%true = OpConstantTrue %bool -%false = OpConstantFalse %bool -%_ptr_Output_uint = OpTypePointer Output %uint -%out = OpVariable %_ptr_Output_uint Output -%main = OpFunction -%entry = OpLabel -%big = OpShiftLeftLogical %uint %c1 %c40 -%dec = OpISub %uint %big %c1 -%pick = OpSelect %uint {cond} %c7 %dec -OpStore %out %pick -OpReturn -OpFunctionEnd -""" - - -class InterpreterContract(unittest.TestCase): - def test_undefined_shift_only_fails_when_used(self): - # 1 << 40 on a 32-bit type is undefined; the translator's v_mbcnt computes it for lanes >= 32 and selects - # it away. The unselected side is fine, storing it is not. - self.assertEqual(si.run_fragment(_SHIFT_MODULE.format(cond="%true")), {"%out": (7,)}) - with self.assertRaisesRegex(si.UnsupportedConstruct, "undefined value"): - si.run_fragment(_SHIFT_MODULE.format(cond="%false")) - - def test_single_invocation_rejects_a_shuffle(self): - with self.assertRaisesRegex(si.UnsupportedConstruct, "run_workgroup"): - si.run_fragment(translate("cs_w64x_readlane"), - inputs={"%wg_id": (0, 0, 0), "%local_id": (0, 0, 0)}, push_constants=VSHARP) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_wave64_emulate_barriers.py b/tests/semantic/test_wave64_emulate_barriers.py deleted file mode 100644 index 7e8ba488f..000000000 --- a/tests/semantic/test_wave64_emulate_barriers.py +++ /dev/null @@ -1,598 +0,0 @@ -"""Regression and workgroup-execution tests for --wave64-emulate barrier alignment: - -1. `tools/wave64_emulate_opt.py` (`_classify_block_body`, `_insn_may_barrier`) recognizes - `s_flbit_i32_b32` and `s_flbit_i32` on lane masks (`exec_lo`, `exec_hi`, `vcc_lo`, mask SGPRs), - matching `Gen.lane_mask_word` -> `Gen.wave_mask` -> `Gen.x_round`. -2. `tools/wave64_emulate_opt.py` recognizes `s_cmp_eq_u64` and `s_cmp_lg_u64` on mixed - mask+data SGPR pairs (one word holds a lane mask, the other holds arbitrary scalar data), - matching `rdna2spirv.py` emitting `Gen.wave_mask` -> `Gen.x_round` per mask word. -3. `tools/rdna2spirv.py` (`Gen.x_memory_order`) skips `ds_nop`, matching `NOOPS` and - `wave64_emulate_opt._x_memory_order_access`. - -Run from the repository root: python -I tests/semantic/test_wave64_emulate_barriers.py -""" -import os -import sys -import unittest - -HERE = os.path.dirname(os.path.abspath(__file__)) -if HERE not in sys.path: - sys.path.insert(0, HERE) - -import test_wave64_emulate_opt as emulate_opt_tests # noqa: E402 -import spirv_asm # noqa: E402 - -rdna2spirv = emulate_opt_tests.rdna2spirv -wave64_emulate_opt = emulate_opt_tests.wave64_emulate_opt -run_emulated_workgroup = emulate_opt_tests.run_emulated_workgroup -_translate_encoded = emulate_opt_tests._translate_encoded -VSHARP = emulate_opt_tests.VSHARP -MASK32 = emulate_opt_tests.MASK32 - -# USER_SGPR = 5 (s0..s3 = VSHARP, s4 = extra runtime scalar; TGID_X = s5), 512 B LDS -RSRC2_USER5 = 0x808A -# USER_SGPR = 6 (s0..s3 = VSHARP, s4..s5 = extra runtime scalars; TGID_X = s6), 512 B LDS -RSRC2_USER6 = 0x808C - - -def _pre_vote_or_atomic_count(spv): - return spv.count("OpFunctionCall %uint %x_pre_vote_fn") + spv.count("OpAtomicOr") - - -class UnitBarrierPredictionTests(unittest.TestCase): - def _insn(self, op, args): - return {"op": op, "args": args, "mods": [], "enc": None, "pc": 0} - - def test_flbit_mask_vs_plain_data(self): - exec_lo = {"k": "special", "t": "exec_lo"} - exec_hi = {"k": "special", "t": "exec_hi"} - vcc_lo = {"k": "special", "t": "vcc_lo"} - dst = {"k": "sgpr", "r": 14, "n": 1} - sgpr8 = {"k": "sgpr", "r": 8, "n": 1} - - for op in ("s_flbit_i32_b32", "s_flbit_i32"): - for src, lm, want in ( - (exec_lo, {}, True), - (exec_hi, {}, True), - (vcc_lo, {"vcc": "M"}, True), - (vcc_lo, {}, False), - (sgpr8, {8: "M"}, True), - (sgpr8, {}, False), - ): - ins = self._insn(op, [dst, src]) - lm_map = {id(ins): lm} - self.assertEqual(wave64_emulate_opt._insn_may_barrier(ins, lm_map, set()), want, f"{op} {src} lm={lm}") - clean = wave64_emulate_opt._classify_block_body([ins], lm_map, set(), frozenset())[0] - self.assertEqual(clean, not want, f"{op} classify {src} lm={lm}") - - def test_mixed_cmp_u64_mask_and_data_pair(self): - pair_a = {"k": "sgpr", "r": 8, "n": 2} - pair_b = {"k": "sgpr", "r": 10, "n": 2} - imm0 = {"k": "imm", "v": 0} - - for op in ("s_cmp_eq_u64", "s_cmp_lg_u64"): - for args in ([pair_a, imm0], [imm0, pair_a], [pair_a, pair_b]): - ins = self._insn(op, args) - for lm, want in ( - ({8: "LO"}, True), - ({9: "HI"}, True), - ({8: "LO", 9: "HI"}, True), - ({}, False), - ({10: "LO"}, True if pair_b in args else False), - ): - lm_map = {id(ins): lm} - self.assertEqual( - wave64_emulate_opt._insn_may_barrier(ins, lm_map, set()), - want, - f"{op} {args} lm={lm}", - ) - clean = wave64_emulate_opt._classify_block_body([ins], lm_map, set(), frozenset())[0] - self.assertEqual(clean, not want, f"{op} classify {args} lm={lm}") - - def test_ds_nop_x_memory_order_matches_opt(self): - self.assertIsNone(wave64_emulate_opt._x_memory_order_access("ds_nop")) - # Verify Gen.x_memory_order("ds_nop") leaves x_dirty untouched and does not trigger x_order_barrier. - insns_with_nop = [ - ("s_mov_b64 s[20:21], exec", 4), - ("v_lshlrev_b32_e32 v2, 2, v0", 4), - ("ds_read_b32 v3, v2", 8), - ("ds_nop", 4), - ("ds_read_b32 v4, v2", 8), - ("v_add_nc_u32_e32 v5, v3, v4", 4), - ("buffer_store_dword v5, v2, s[0:3], 0 offen", 8), - ("s_endpgm", 4), - ] - insns_plain = [x for x in insns_with_nop if x[0] != "ds_nop"] - spv_nop, gen_nop = _translate_encoded("cs_ds_nop_sl_1", insns_with_nop, (64, 1, 1), emulate=True) - spv_ref, gen_ref = _translate_encoded("cs_ds_nop_sl_0", insns_plain, (64, 1, 1), emulate=True) - self.assertEqual(len(gen_nop.x_segs), 0) - self.assertEqual(len(gen_nop.x_segs), len(gen_ref.x_segs)) - self.assertEqual(spv_nop.count("OpControlBarrier"), spv_ref.count("OpControlBarrier")) - - -class FlbitEmulateBarrierTests(unittest.TestCase): - def test_flbit_b32_on_exec_and_vcc_inside_execz_region(self): - # 1) Lanes 10..19 active -> exec_lo bitmask 10..19 (highest bit 19 => 31 - 19 = 12), exec_hi empty (-1), - # vcc lanes 5..12 (highest bit 12 => 31 - 12 = 19). - insns_lo = [ - ("v_cmp_ge_u32_e64 vcc, v0, 10", 8), - ("v_cmp_lt_u32_e64 s[6:7], v0, 20", 8), - ("s_and_b64 s[6:7], vcc, s[6:7]", 4), - ("v_cmp_ge_u32_e64 s[18:19], v0, 5", 8), - ("v_cmp_le_u32_e64 s[20:21], v0, 12", 8), - ("s_and_b64 vcc, s[18:19], s[20:21]", 4), - ("v_mov_b32_e32 v4, 0", 4), - ("v_mov_b32_e32 v5, 0", 4), - ("v_mov_b32_e32 v6, 0", 4), - ("s_and_saveexec_b64 s[8:9], s[6:7]", 4), - ("s_cbranch_execz 6", 4), - ("s_flbit_i32_b32 s14, exec_lo", 4), - ("s_flbit_i32_b32 s15, exec_hi", 4), - ("s_flbit_i32_b32 s16, vcc_lo", 4), - ("v_mov_b32_e32 v4, s14", 4), - ("v_mov_b32_e32 v5, s15", 4), - ("v_mov_b32_e32 v6, s16", 4), - ("s_or_b64 exec, exec, s[8:9]", 4), - ("v_lshlrev_b32_e32 v10, 2, v0", 4), - ("buffer_store_dword v4, v10, s[0:3], 0 offen", 8), - ("buffer_store_dword v5, v10, s[0:3], 0 offen offset:256", 8), - ("buffer_store_dword v6, v10, s[0:3], 0 offen offset:512", 8), - ("s_endpgm", 4), - ] - spv, gen = _translate_encoded("cs_flbit_b32_execz_lo", insns_lo, (64, 1, 1), emulate=True) - self.assertEqual([b is not None for b in gen.blocks], [True, True, True]) - self.assertGreaterEqual(_pre_vote_or_atomic_count(spv), 1) - self.assertEqual(spirv_asm.assemble(spv, target_env="vulkan1.2")[:4], b"\x03\x02\x23\x07") - for rev in (False, True): - mem, _ = run_emulated_workgroup(spv, (64, 1, 1), push_constants=VSHARP + [0] * 28, reverse_order=rev) - for lane in range(10, 20): - self.assertEqual(mem[lane * 4], 12, f"lane {lane} exec_lo") - self.assertEqual(mem[256 + lane * 4], MASK32, f"lane {lane} exec_hi") - self.assertEqual(mem[512 + lane * 4], 19, f"lane {lane} vcc_lo") - for lane in list(range(0, 10)) + list(range(20, 64)): - self.assertEqual(mem[lane * 4], 0) - - # 2) Only upper-half lanes 40..49 active -> exec_hi bits 8..17 (31 - 17 = 14) and copied MASK_HI SGPR s17 - insns_hi = [ - ("v_cmp_ge_u32_e64 s[6:7], v0, 40", 8), - ("v_cmp_lt_u32_e64 s[18:19], v0, 50", 8), - ("s_and_b64 s[6:7], s[6:7], s[18:19]", 4), - ("v_mov_b32_e32 v4, 0", 4), - ("v_mov_b32_e32 v5, 0", 4), - ("v_mov_b32_e32 v6, 0", 4), - ("s_and_saveexec_b64 s[8:9], s[6:7]", 4), - ("s_cbranch_execz 7", 4), - ("s_mov_b32 s17, exec_hi", 4), - ("s_flbit_i32_b32 s14, exec_lo", 4), - ("s_flbit_i32_b32 s15, exec_hi", 4), - ("s_flbit_i32_b32 s16, s17", 4), - ("v_mov_b32_e32 v4, s14", 4), - ("v_mov_b32_e32 v5, s15", 4), - ("v_mov_b32_e32 v6, s16", 4), - ("s_or_b64 exec, exec, s[8:9]", 4), - ("v_lshlrev_b32_e32 v10, 2, v0", 4), - ("buffer_store_dword v4, v10, s[0:3], 0 offen", 8), - ("buffer_store_dword v5, v10, s[0:3], 0 offen offset:256", 8), - ("buffer_store_dword v6, v10, s[0:3], 0 offen offset:512", 8), - ("s_endpgm", 4), - ] - spv_hi, _ = _translate_encoded("cs_flbit_b32_execz_hi", insns_hi, (64, 1, 1), emulate=True) - self.assertGreaterEqual(_pre_vote_or_atomic_count(spv_hi), 1) - mem_hi, _ = run_emulated_workgroup(spv_hi, (64, 1, 1), push_constants=VSHARP + [0] * 28) - for lane in range(40, 50): - self.assertEqual(mem_hi[lane * 4], MASK32, f"lane {lane} exec_lo") - self.assertEqual(mem_hi[256 + lane * 4], 14, f"lane {lane} exec_hi") - self.assertEqual(mem_hi[512 + lane * 4], 14, f"lane {lane} s17") - - def test_flbit_b32_multiwave_divergent_guard(self): - # 128 threads: Wave 0 enters s_cbranch_scc0 guard and trims EXEC to lanes 10..19 -> s14 = 12; - # Wave 1 skips the guard -> s14 = 99. Guard block MUST NOT be in sync_free_blocks. - insns = [ - ("s_mov_b64 exec, -1", 4), - ("s_mov_b32 s14, 99", 4), - ("v_cmp_lt_u32_e64 s[6:7], v0, 20", 8), - ("v_cmp_ge_u32_e64 s[10:11], v0, 10", 8), - ("s_and_b64 s[6:7], s[6:7], s[10:11]", 4), - ("v_readfirstlane_b32 s19, v0", 4), - ("s_cmp_lt_u32 s19, 64", 4), - ("s_cbranch_scc0 4", 4), - ("s_and_saveexec_b64 s[8:9], s[6:7]", 4), - ("s_flbit_i32_b32 s14, exec_lo", 4), - ("s_or_b64 exec, exec, s[8:9]", 4), - ("s_nop 0", 4), - ("v_mov_b32_e32 v4, s14", 4), - ("v_lshlrev_b32_e32 v10, 2, v0", 4), - ("buffer_store_dword v4, v10, s[0:3], 0 offen", 8), - ("s_endpgm", 4), - ] - spv, gen = _translate_encoded("cs_flbit_b32_mw", insns, (128, 1, 1), emulate=True, rsrc2=0x20088) - self.assertEqual(gen.control_flow, "emulated wave64 structured") - self.assertEqual(gen.emulate_plan["mode"], "structured_hybrid") - self.assertNotIn(1, gen.emulate_plan["sync_free_blocks"]) - self.assertIn(1, gen.emulate_plan["mini_of_block"]) - for rev in (False, True): - mem, _ = run_emulated_workgroup(spv, (128, 1, 1), push_constants=VSHARP + [0] * 28, reverse_order=rev) - for l in range(64): - self.assertEqual(mem[l * 4], 12, f"wave0 lane {l} rev={rev}") - for l in range(64, 128): - self.assertEqual(mem[l * 4], 99, f"wave1 lane {l} rev={rev}") - - def test_flbit_i32_signed_exec_and_mask_sgpr(self): - # Covers FindSMsb on bit31=0 (0..5 -> 26), bit31=1 (24..31 -> 8), and all-ones (0..31 -> -1). - for lo_start, lo_end, want in ( - (0, 6, 26), - (24, 32, 8), - (0, 32, MASK32), - ): - with self.subTest(range=(lo_start, lo_end)): - insns = [ - (f"v_cmp_ge_u32_e64 s[6:7], v0, {lo_start}", 8), - (f"v_cmp_lt_u32_e64 s[18:19], v0, {lo_end}", 8), - ("s_and_b64 s[6:7], s[6:7], s[18:19]", 4), - ("v_mov_b32_e32 v4, 0", 4), - ("v_mov_b32_e32 v5, 0", 4), - ("v_mov_b32_e32 v6, 0", 4), - ("s_and_saveexec_b64 s[8:9], s[6:7]", 4), - ("s_cbranch_execz 7", 4), - ("s_mov_b32 s17, exec_lo", 4), - ("s_flbit_i32 s14, exec_lo", 4), - ("s_flbit_i32 s15, exec_hi", 4), - ("s_flbit_i32 s16, s17", 4), - ("v_mov_b32_e32 v4, s14", 4), - ("v_mov_b32_e32 v5, s15", 4), - ("v_mov_b32_e32 v6, s16", 4), - ("s_or_b64 exec, exec, s[8:9]", 4), - ("v_lshlrev_b32_e32 v10, 2, v0", 4), - ("buffer_store_dword v4, v10, s[0:3], 0 offen", 8), - ("buffer_store_dword v5, v10, s[0:3], 0 offen offset:256", 8), - ("buffer_store_dword v6, v10, s[0:3], 0 offen offset:512", 8), - ("s_endpgm", 4), - ] - spv, _ = _translate_encoded(f"cs_flbit_i32_{lo_start}_{lo_end}", insns, (64, 1, 1), emulate=True) - self.assertGreaterEqual(_pre_vote_or_atomic_count(spv), 1) - mem, _ = run_emulated_workgroup(spv, (64, 1, 1), push_constants=VSHARP + [0] * 28) - for l in range(lo_start, lo_end): - self.assertEqual(mem[l * 4], want, f"lane {l} exec_lo") - self.assertEqual(mem[256 + l * 4], MASK32, f"lane {l} exec_hi") - self.assertEqual(mem[512 + l * 4], want, f"lane {l} s17") - - # Multi-wave (128 threads) divergent s_cbranch_scc0 guard using s_flbit_i32 - insns_mw = [ - ("s_mov_b64 exec, -1", 4), - ("s_mov_b32 s14, 99", 4), - ("v_cmp_ge_u32_e64 s[6:7], v0, 24", 8), - ("v_cmp_lt_u32_e64 s[10:11], v0, 32", 8), - ("s_and_b64 s[6:7], s[6:7], s[10:11]", 4), - ("v_readfirstlane_b32 s19, v0", 4), - ("s_cmp_lt_u32 s19, 64", 4), - ("s_cbranch_scc0 4", 4), - ("s_and_saveexec_b64 s[8:9], s[6:7]", 4), - ("s_flbit_i32 s14, exec_lo", 4), - ("s_or_b64 exec, exec, s[8:9]", 4), - ("s_nop 0", 4), - ("v_mov_b32_e32 v4, s14", 4), - ("v_lshlrev_b32_e32 v10, 2, v0", 4), - ("buffer_store_dword v4, v10, s[0:3], 0 offen", 8), - ("s_endpgm", 4), - ] - spv_mw, gen_mw = _translate_encoded("cs_flbit_i32_mw", insns_mw, (128, 1, 1), emulate=True, rsrc2=0x20088) - self.assertEqual(gen_mw.emulate_plan["mode"], "structured_hybrid") - self.assertNotIn(1, gen_mw.emulate_plan["sync_free_blocks"]) - mem_mw, _ = run_emulated_workgroup(spv_mw, (128, 1, 1), push_constants=VSHARP + [0] * 28) - for l in range(64): - self.assertEqual(mem_mw[l * 4], 8, f"wave0 lane {l}") - for l in range(64, 128): - self.assertEqual(mem_mw[l * 4], 99, f"wave1 lane {l}") - - def test_flbit_plain_scalar_data_still_folds_and_stays_sync_free(self): - # Single-wave s_cbranch_execz with s_flbit_i32_b32 + s_flbit_i32 on runtime scalar s4 still folds. - insns_fold = [ - ("v_mov_b32_e32 v4, 0", 4), - ("v_mov_b32_e32 v5, 0", 4), - ("v_cmp_lt_u32_e64 s[6:7], v0, 16", 8), - ("s_and_saveexec_b64 s[8:9], s[6:7]", 4), - ("s_cbranch_execz 4", 4), - ("s_flbit_i32_b32 s14, s4", 4), - ("s_flbit_i32 s15, s4", 4), - ("v_mov_b32_e32 v4, s14", 4), - ("v_mov_b32_e32 v5, s15", 4), - ("s_or_b64 exec, exec, s[8:9]", 4), - ("v_lshlrev_b32_e32 v10, 2, v0", 4), - ("buffer_store_dword v4, v10, s[0:3], 0 offen", 8), - ("buffer_store_dword v5, v10, s[0:3], 0 offen offset:256", 8), - ("s_endpgm", 4), - ] - spv_f, gen_f = _translate_encoded("cs_flbit_data_fold", insns_fold, (64, 1, 1), emulate=True, rsrc2=RSRC2_USER5) - self.assertEqual([b is not None for b in gen_f.blocks], [True, False, False]) - self.assertEqual(_pre_vote_or_atomic_count(spv_f), 0) - # 0xFF000000: unsigned leading 0s = 0, signed leading 1s = 8 - mem_f, _ = run_emulated_workgroup(spv_f, (64, 1, 1), push_constants=VSHARP + [0xFF000000] + [0] * 27) - for l in range(16): - self.assertEqual(mem_f[l * 4], 0) - self.assertEqual(mem_f[256 + l * 4], 8) - - # Multi-wave s_cbranch_scc0 with plain-data s_flbit_* stays sync_free. - insns_mw = [ - ("s_mov_b64 exec, -1", 4), - ("s_mov_b32 s14, 99", 4), - ("s_mov_b32 s15, 99", 4), - ("v_readfirstlane_b32 s19, v0", 4), - ("s_cmp_lt_u32 s19, 64", 4), - ("s_cbranch_scc0 2", 4), - ("s_flbit_i32_b32 s14, s4", 4), - ("s_flbit_i32 s15, s4", 4), - ("s_nop 0", 4), - ("v_mov_b32_e32 v4, s14", 4), - ("v_mov_b32_e32 v5, s15", 4), - ("v_lshlrev_b32_e32 v10, 2, v0", 4), - ("buffer_store_dword v4, v10, s[0:3], 0 offen", 8), - ("buffer_store_dword v5, v10, s[0:3], 0 offen offset:512", 8), - ("s_endpgm", 4), - ] - spv_mw, gen_mw = _translate_encoded("cs_flbit_data_mw", insns_mw, (128, 1, 1), emulate=True, rsrc2=RSRC2_USER5) - self.assertIn(1, gen_mw.emulate_plan["sync_free_blocks"]) - mem_mw, _ = run_emulated_workgroup(spv_mw, (128, 1, 1), push_constants=VSHARP + [0xFF000000] + [0] * 27) - for l in range(64): - self.assertEqual(mem_mw[l * 4], 0) - self.assertEqual(mem_mw[512 + l * 4], 8) - for l in range(64, 128): - self.assertEqual(mem_mw[l * 4], 99) - self.assertEqual(mem_mw[512 + l * 4], 99) - - -class MixedCmpU64BarrierTests(unittest.TestCase): - def test_mixed_low_mask_high_data_pair_single_wave_execz(self): - # s8 = exec_lo (lane mask), s9 = s4 (runtime scalar data, NOT literal 0/-1 EITHER). - # Compare s[8:9] against 0 inside s_cbranch_execz. - def build(lo_start, lo_end): - return [ - (f"v_cmp_ge_u32_e64 s[6:7], v0, {lo_start}", 8), - (f"v_cmp_lt_u32_e64 s[18:19], v0, {lo_end}", 8), - ("s_and_b64 s[6:7], s[6:7], s[18:19]", 4), - ("v_mov_b32_e32 v4, 0", 4), - ("s_and_saveexec_b64 s[10:11], s[6:7]", 4), - ("s_cbranch_execz 5", 4), - ("s_mov_b32 s8, exec_lo", 4), - ("s_mov_b32 s9, s4", 4), - ("s_cmp_eq_u64 s[8:9], 0", 4), - ("s_cselect_b32 s14, 111, 222", 4), - ("v_mov_b32_e32 v4, s14", 4), - ("s_or_b64 exec, exec, s[10:11]", 4), - ("v_lshlrev_b32_e32 v10, 2, v0", 4), - ("buffer_store_dword v4, v10, s[0:3], 0 offen", 8), - ("s_endpgm", 4), - ] - - # Upper-half lanes 40..48 active -> exec_lo == 0 -> eq iff s4 == 0 - spv_hi, _ = _translate_encoded("cs_mixed_u64_hi", build(40, 48), (64, 1, 1), emulate=True, rsrc2=RSRC2_USER5) - self.assertGreaterEqual(_pre_vote_or_atomic_count(spv_hi), 1) - self.assertEqual(spirv_asm.assemble(spv_hi, target_env="vulkan1.2")[:4], b"\x03\x02\x23\x07") - for s4_val, want in ((0, 111), (0x12345678, 222)): - for rev in (False, True): - mem, _ = run_emulated_workgroup( - spv_hi, (64, 1, 1), push_constants=VSHARP + [s4_val] + [0] * 27, reverse_order=rev - ) - for l in range(40, 48): - self.assertEqual(mem[l * 4], want, f"s4={s4_val:#x} l={l} rev={rev}") - - # Lower-half lanes 5..10 active -> exec_lo != 0 -> never equal to 0 even when s4 == 0 - spv_lo, _ = _translate_encoded("cs_mixed_u64_lo", build(5, 10), (64, 1, 1), emulate=True, rsrc2=RSRC2_USER5) - self.assertGreaterEqual(_pre_vote_or_atomic_count(spv_lo), 1) - mem_lo, _ = run_emulated_workgroup(spv_lo, (64, 1, 1), push_constants=VSHARP + [0] + [0] * 27) - for l in range(5, 10): - self.assertEqual(mem_lo[l * 4], 222, f"lane {l}") - - def test_mixed_high_mask_low_data_pair_reversed_operand(self): - # s8 = s4 (runtime scalar data), s9 = exec_hi (MASK_HI), and s[8:9] is second arg of s_cmp_lg_u64. - def build(lo_start, lo_end): - return [ - (f"v_cmp_ge_u32_e64 s[6:7], v0, {lo_start}", 8), - (f"v_cmp_lt_u32_e64 s[18:19], v0, {lo_end}", 8), - ("s_and_b64 s[6:7], s[6:7], s[18:19]", 4), - ("v_mov_b32_e32 v4, 0", 4), - ("s_and_saveexec_b64 s[10:11], s[6:7]", 4), - ("s_cbranch_execz 5", 4), - ("s_mov_b32 s8, s4", 4), - ("s_mov_b32 s9, exec_hi", 4), - ("s_cmp_lg_u64 0, s[8:9]", 4), - ("s_cselect_b32 s14, 333, 444", 4), - ("v_mov_b32_e32 v4, s14", 4), - ("s_or_b64 exec, exec, s[10:11]", 4), - ("v_lshlrev_b32_e32 v10, 2, v0", 4), - ("buffer_store_dword v4, v10, s[0:3], 0 offen", 8), - ("s_endpgm", 4), - ] - - # Lower-half lanes 4..8 active -> exec_hi == 0 -> lg 0 iff s4 != 0 - spv_lo, _ = _translate_encoded("cs_mixed_u64_rev_lo", build(4, 8), (64, 1, 1), emulate=True, rsrc2=RSRC2_USER5) - self.assertGreaterEqual(_pre_vote_or_atomic_count(spv_lo), 1) - for s4_val, want in ((0, 444), (9, 333)): - mem, _ = run_emulated_workgroup(spv_lo, (64, 1, 1), push_constants=VSHARP + [s4_val] + [0] * 27) - for l in range(4, 8): - self.assertEqual(mem[l * 4], want, f"s4={s4_val} lane {l}") - - # Upper-half lanes 40..44 active -> exec_hi != 0 -> always lg 0 even when s4 == 0 - spv_hi, _ = _translate_encoded("cs_mixed_u64_rev_hi", build(40, 44), (64, 1, 1), emulate=True, rsrc2=RSRC2_USER5) - mem_hi, _ = run_emulated_workgroup(spv_hi, (64, 1, 1), push_constants=VSHARP + [0] + [0] * 27) - for l in range(40, 44): - self.assertEqual(mem_hi[l * 4], 333, f"lane {l}") - - def test_mixed_mask_data_pair_multiwave_divergent_guard(self): - # 128 threads: Wave 0 enters s_cbranch_scc0 guard (exec trimmed to 40..47, so exec_lo == 0), - # compares s[8:9] (s8=exec_lo, s9=s4) against 0; Wave 1 skips guard and keeps 999. - insns = [ - ("s_mov_b64 exec, -1", 4), - ("s_mov_b32 s14, 999", 4), - ("v_cmp_ge_u32_e64 s[6:7], v0, 40", 8), - ("v_cmp_lt_u32_e64 s[18:19], v0, 48", 8), - ("s_and_b64 s[6:7], s[6:7], s[18:19]", 4), - ("v_readfirstlane_b32 s19, v0", 4), - ("s_cmp_lt_u32 s19, 64", 4), - ("s_cbranch_scc0 6", 4), - ("s_and_saveexec_b64 s[10:11], s[6:7]", 4), - ("s_mov_b32 s8, exec_lo", 4), - ("s_mov_b32 s9, s4", 4), - ("s_cmp_lg_u64 s[8:9], 0", 4), - ("s_cselect_b32 s14, 555, 666", 4), - ("s_or_b64 exec, exec, s[10:11]", 4), - ("s_nop 0", 4), - ("v_mov_b32_e32 v4, s14", 4), - ("v_lshlrev_b32_e32 v10, 2, v0", 4), - ("buffer_store_dword v4, v10, s[0:3], 0 offen", 8), - ("s_endpgm", 4), - ] - spv, gen = _translate_encoded("cs_mixed_u64_mw", insns, (128, 1, 1), emulate=True, rsrc2=RSRC2_USER5) - self.assertEqual(gen.emulate_plan["mode"], "structured_hybrid") - self.assertNotIn(1, gen.emulate_plan["sync_free_blocks"]) - for s4_val, want_w0 in ((0, 666), (42, 555)): - for rev in (False, True): - mem, _ = run_emulated_workgroup( - spv, (128, 1, 1), push_constants=VSHARP + [s4_val] + [0] * 27, reverse_order=rev - ) - for l in range(64): - self.assertEqual(mem[l * 4], want_w0, f"wave0 l={l} s4={s4_val} rev={rev}") - for l in range(64, 128): - self.assertEqual(mem[l * 4], 999, f"wave1 l={l} s4={s4_val} rev={rev}") - - def test_plain_data_u64_pair_still_folds_and_stays_sync_free(self): - insns_fold = [ - ("v_mov_b32_e32 v4, 0", 4), - ("v_cmp_lt_u32_e64 s[6:7], v0, 16", 8), - ("s_and_saveexec_b64 s[10:11], s[6:7]", 4), - ("s_cbranch_execz 3", 4), - ("s_cmp_eq_u64 s[4:5], 0", 4), - ("s_cselect_b32 s14, 11, 22", 4), - ("v_mov_b32_e32 v4, s14", 4), - ("s_or_b64 exec, exec, s[10:11]", 4), - ("v_lshlrev_b32_e32 v10, 2, v0", 4), - ("buffer_store_dword v4, v10, s[0:3], 0 offen", 8), - ("s_endpgm", 4), - ] - spv_f, gen_f = _translate_encoded("cs_plain_u64_fold", insns_fold, (64, 1, 1), emulate=True, rsrc2=RSRC2_USER6) - self.assertEqual(emulate_opt_tests._switch_case_count(gen_f), 1) - self.assertEqual(_pre_vote_or_atomic_count(spv_f), 0) - for s4, s5, want in ((0, 0, 11), (0, 1, 22), (1, 0, 22)): - mem_f, _ = run_emulated_workgroup(spv_f, (64, 1, 1), push_constants=VSHARP + [s4, s5] + [0] * 26) - for l in range(16): - self.assertEqual(mem_f[l * 4], want) - - insns_mw = [ - ("s_mov_b64 exec, -1", 4), - ("s_mov_b32 s14, 99", 4), - ("v_readfirstlane_b32 s19, v0", 4), - ("s_cmp_lt_u32 s19, 64", 4), - ("s_cbranch_scc0 2", 4), - ("s_cmp_eq_u64 s[4:5], 0", 4), - ("s_cselect_b32 s14, 11, 22", 4), - ("s_nop 0", 4), - ("v_mov_b32_e32 v4, s14", 4), - ("v_lshlrev_b32_e32 v10, 2, v0", 4), - ("buffer_store_dword v4, v10, s[0:3], 0 offen", 8), - ("s_endpgm", 4), - ] - spv_mw, gen_mw = _translate_encoded("cs_plain_u64_mw", insns_mw, (128, 1, 1), emulate=True, rsrc2=RSRC2_USER6) - self.assertIn(1, gen_mw.emulate_plan["sync_free_blocks"]) - mem_mw, _ = run_emulated_workgroup(spv_mw, (128, 1, 1), push_constants=VSHARP + [0, 1] + [0] * 26) - for l in range(64): - self.assertEqual(mem_mw[l * 4], 22) - for l in range(64, 128): - self.assertEqual(mem_mw[l * 4], 99) - - -class DsNopOrderTests(unittest.TestCase): - def test_ds_nop_after_lds_read_or_write_folds_in_single_wave(self): - # Single-wave (64 threads): ds_read_b32 + ds_nop and ds_write_b32 + ds_nop inside s_cbranch_execz - # must both STILL fold (0 OpAtomicOr / %x_pre_vote_fn, 0 OpControlBarrier inside the folded region). - insns = [ - ("s_mov_b64 exec, -1", 4), - ("v_lshlrev_b32_e32 v10, 2, v0", 4), - ("v_add_nc_u32_e32 v11, 1000, v0", 4), - ("ds_write_b32 v10, v11", 8), - ("v_mov_b32_e32 v4, v0", 4), - # Fold 1: ds_read_b32 followed by ds_nop (uniform pre-barrier orders earlier ds_write -> ds_read). - ("v_cmp_lt_u32_e64 s[6:7], v0, 16", 8), - ("s_and_saveexec_b64 s[8:9], s[6:7]", 4), - ("s_cbranch_execz 3", 4), - ("ds_read_b32 v4, v10", 8), - ("ds_nop", 4), - ("s_or_b64 exec, exec, s[8:9]", 4), - # Fold 2: single ds_write_b32 followed by ds_nop (single LDS access in folded region). - ("v_cmp_ge_u32_e64 s[6:7], v0, 48", 8), - ("s_and_saveexec_b64 s[8:9], s[6:7]", 4), - ("s_cbranch_execz 4", 4), - ("ds_nop", 4), - ("v_add_nc_u32_e32 v12, 2000, v0", 4), - ("ds_write_b32 v10, v12", 8), - ("s_or_b64 exec, exec, s[8:9]", 4), - # Read back LDS into v5 and store both v4 and v5 to global buffer. - ("ds_read_b32 v5, v10", 8), - ("buffer_store_dword v4, v10, s[0:3], 0 offen", 8), - ("buffer_store_dword v5, v10, s[0:3], 0 offen offset:256", 8), - ("s_endpgm", 4), - ] - spv, gen = _translate_encoded("cs_ds_nop_fold", insns, (64, 1, 1), emulate=True) - insns_ref = [x for x in insns if x[0] != "ds_nop"] - # Adjust branch offsets without the two ds_nop instructions (-1 dword inside each region). - insns_ref = [ - ("s_cbranch_execz 2", 4) if x[0] == "s_cbranch_execz 3" else - ("s_cbranch_execz 3", 4) if x[0] == "s_cbranch_execz 4" else x - for x in insns_ref - ] - spv_ref, gen_ref = _translate_encoded("cs_ds_nop_fold_ref", insns_ref, (64, 1, 1), emulate=True) - self.assertEqual(_pre_vote_or_atomic_count(spv), 0) - self.assertEqual(sum(1 for b in gen.blocks if b is not None), 1) - self.assertEqual(len(gen.x_segs), len(gen_ref.x_segs)) - self.assertEqual(spv.count("OpControlBarrier"), spv_ref.count("OpControlBarrier")) - mem, _ = run_emulated_workgroup(spv, (64, 1, 1), push_constants=VSHARP + [0] * 28) - for l in range(64): - want_v4 = (1000 + l) if l < 16 else l - want_v5 = (2000 + l) if l >= 48 else (1000 + l) - self.assertEqual(mem[l * 4], want_v4, f"v4 lane {l}") - self.assertEqual(mem[256 + l * 4], want_v5, f"v5 lane {l}") - - def test_ds_nop_stays_sync_free_in_multiwave_guard(self): - # 128 threads: Wave 0 enters guard 1 (ds_read_b32 + ds_nop) and Wave 1 enters guard 2 (ds_write_b32 + ds_nop). - insns = [ - ("s_mov_b64 exec, -1", 4), - ("v_lshlrev_b32_e32 v10, 2, v0", 4), - ("v_add_nc_u32_e32 v11, 500, v0", 4), - ("ds_write_b32 v10, v11", 8), - ("s_nop 0", 4), - ("v_mov_b32_e32 v4, v0", 4), - ("v_readfirstlane_b32 s19, v0", 4), - ("s_cmp_lt_u32 s19, 64", 4), - ("s_cbranch_scc0 4", 4), - ("ds_read_b32 v4, v10", 8), - ("ds_nop", 4), - ("v_add_nc_u32_e32 v4, 10, v4", 4), - ("s_nop 0", 4), - ("v_readfirstlane_b32 s19, v0", 4), - ("s_cmp_ge_u32 s19, 64", 4), - ("s_cbranch_scc0 4", 4), - ("v_add_nc_u32_e32 v12, 900, v0", 4), - ("ds_write_b32 v10, v12", 8), - ("ds_nop", 4), - ("ds_read_b32 v5, v10", 8), - ("buffer_store_dword v4, v10, s[0:3], 0 offen", 8), - ("buffer_store_dword v5, v10, s[0:3], 0 offen offset:512", 8), - ("s_endpgm", 4), - ] - spv, gen = _translate_encoded("cs_ds_nop_mw", insns, (128, 1, 1), emulate=True, rsrc2=0x20088) - self.assertEqual(gen.control_flow, "emulated wave64 structured") - self.assertEqual(gen.emulate_plan["mode"], "structured_hybrid") - # Both divergent guards stay inline_sync_free! - self.assertEqual(len(gen.emulate_plan["sync_free_blocks"]), 2) - self.assertEqual(len(gen.emulate_plan["mini_blocks"]), 0) - self.assertEqual(spirv_asm.assemble(spv, target_env="vulkan1.2")[:4], b"\x03\x02\x23\x07") - for rev in (False, True): - mem, _ = run_emulated_workgroup(spv, (128, 1, 1), push_constants=VSHARP + [0] * 28, reverse_order=rev) - for l in range(64): - self.assertEqual(mem[l * 4], 510 + l, f"v4 w0 l={l} rev={rev}") - self.assertEqual(mem[512 + l * 4], 500 + l, f"v5 w0 l={l} rev={rev}") - for l in range(64, 128): - self.assertEqual(mem[l * 4], l, f"v4 w1 l={l} rev={rev}") - self.assertEqual(mem[512 + l * 4], 900 + l, f"v5 w1 l={l} rev={rev}") - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_wave64_emulate_opt.py b/tests/semantic/test_wave64_emulate_opt.py deleted file mode 100644 index da6400036..000000000 --- a/tests/semantic/test_wave64_emulate_opt.py +++ /dev/null @@ -1,1758 +0,0 @@ -"""Unit and 64/128-lane workgroup execution tests for tools/wave64_emulate_opt.py (--wave64-emulate). - -Verifies both exact optimizations introduced for Issue #884: - 1. Backward CFG SCC liveness: dead `scc_from_mask` / `scc_any_half` votes on lane-mask ops are elided - under --wave64-emulate, while live SCC writes (direct, cross-block, loop-carried, carry-in) stay exact. - 2. Safe lane-local `s_cbranch_execz` / `s_cbranch_execnz` region folding + continuation chaining: single-entry, - single-exit regions with no cross-lane ops, no barriers, no memory/LDS writes, no EXEC-widening, and no - live-out scalars fold inline behind `if (%active)` (and chain single-predecessor continuations), keeping - all 64 lanes of each wave in the same scheduler round. - -Includes a strict workgroup SPIR-V interpreter with real OpControlBarrier uniformity checks, shared Workgroup -memory (%x_buf and %lds), 32-bit Workgroup atomics, OpSwitch, loops, and PhysicalStorageBuffer loads/stores so -the translated --wave64-emulate SPIR-V is executed bit-for-bit across 64-thread (1-wave) and 128-thread -(2-wave) workgroups and compared against an independent RDNA2 ISA reference. - -Run from the repository root: python -I tests/semantic/test_wave64_emulate_opt.py -""" -import os -import re -import struct -import sys -import tempfile -import unittest - -HERE = os.path.dirname(os.path.abspath(__file__)) -if HERE not in sys.path: - sys.path.insert(0, HERE) - -import support # noqa: E402 - -rdna2spirv = support.rdna2spirv -wave64_emulate_opt = rdna2spirv.wave64_emulate_opt - -MASK32 = 0xFFFFFFFF -VSHARP = [0, 0, 0xFFFFFFFF, 0x31016FAC] # raw buffer covering all offsets - - -# ---- Strict SPIR-V workgroup + barrier interpreter (for --wave64-emulate modules) ---- -_SPV_LINE = re.compile(r"^(?:(%\w+)\s*=\s*)?(\w+)(?:\s+(.*))?$") -_SPV_IGNORED = frozenset({ - "OpCapability", "OpExtension", "OpExtInstImport", "OpMemoryModel", "OpEntryPoint", - "OpExecutionMode", "OpDecorate", "OpMemberDecorate", "OpTypeVoid", "OpTypeFunction", - "OpSelectionMerge", "OpLoopMerge", "OpFunctionEnd", -}) - - -def _strip_comments(text): - out = [] - for raw in text.splitlines(): - s = raw.split(";", 1)[0].strip() - if s: - out.append(s) - return out - - -def _s32(v): - v &= MASK32 - return v - 0x100000000 if v & 0x80000000 else v - - -def _parse_module(text): - types = {} - ptr_types = {} - consts = {} - id_type = {} - globals_ = [] - funcs = {} - cur_fn = None - cur_params = [] - cur_body = [] - - def zero_of(tid): - k = types[tid] - if k[0] == "int": - return 0 - if k[0] == "float": - return 0.0 - if k[0] == "bool": - return False - if k[0] == "vec": - return tuple(zero_of(k[1]) for _ in range(k[2])) - if k[0] == "arr": - return [zero_of(k[1]) for _ in range(k[2])] - if k[0] == "struct": - return [zero_of(m) for m in k[1]] - raise NotImplementedError(f"zero_of {k}") - - for line in _strip_comments(text): - m = _SPV_LINE.match(line) - if not m: - raise AssertionError(f"cannot parse SPIR-V line: {line!r}") - res, op, rest = m.groups() - a = rest.split() if rest else [] - if cur_fn is not None: - if op == "OpFunctionParameter": - cur_params.append(res) - elif op == "OpFunctionEnd": - funcs[cur_fn] = (cur_params, cur_body) - cur_fn = None - else: - cur_body.append((res, op, a, line)) - continue - if op == "OpFunction": - cur_fn = res - cur_params = [] - cur_body = [] - continue - if op in _SPV_IGNORED: - continue - if op == "OpTypeInt": - types[res] = ("int", int(a[0]), int(a[1])) - elif op == "OpTypeFloat": - types[res] = ("float", int(a[0])) - elif op == "OpTypeBool": - types[res] = ("bool",) - elif op == "OpTypeVector": - types[res] = ("vec", a[0], int(a[1])) - elif op == "OpTypeArray": - types[res] = ("arr", a[0], int(consts[a[1]])) - elif op == "OpTypeRuntimeArray": - types[res] = ("rarr", a[0]) - elif op == "OpTypeStruct": - types[res] = ("struct", a) - elif op == "OpTypePointer": - ptr_types[res] = (a[0], a[1]) - elif op == "OpConstant": - k = types[a[0]] - if k[0] == "int": - consts[res] = int(a[1]) & ((1 << k[1]) - 1) - id_type[res] = a[0] - elif k[0] == "float": - consts[res] = float(a[1]) - id_type[res] = a[0] - else: - raise NotImplementedError(f"OpConstant {k}") - elif op == "OpConstantTrue": - consts[res] = True - elif op == "OpConstantFalse": - consts[res] = False - elif op == "OpConstantNull": - consts[res] = zero_of(a[0]) - elif op == "OpVariable": - cls, pointee = ptr_types[a[0]] - assert a[1] == cls, f"storage class mismatch: {line}" - globals_.append((res, cls, pointee, a[2] if len(a) > 2 else None)) - else: - raise NotImplementedError(f"header op {op}: {line}") - - assert "%main" in funcs - # Expand single-block helper OpFunctionCalls inline into %main's instruction stream for lockstep interpretation. - body = [] - call_seq = 0 - for res, op, a, line in funcs["%main"][1]: - if op != "OpFunctionCall": - body.append((res, op, a, line)) - continue - call_seq += 1 - ret_t, fn_name = a[0], a[1] - call_args = a[2:] - fn_params, fn_insns = funcs[fn_name] - assert len(call_args) == len(fn_params) - id_map = dict(zip(fn_params, call_args)) - for fres, fop, fa, fline in fn_insns: - if fop == "OpLabel": - continue - mapped_a = [id_map.get(x, x) for x in fa] - if fop == "OpReturnValue": - body.append((res, "OpCopyObject", [ret_t, mapped_a[0]], f"{res} = OpCopyObject {ret_t} {mapped_a[0]}")) - break - new_res = f"%fc{call_seq}_{fres[1:]}" if fres else None - if fres: - id_map[fres] = new_res - body.append((new_res, fop, mapped_a, fline)) - - labels = {res: idx for idx, (res, op, _, _) in enumerate(body) if op == "OpLabel" and res} - return { - "types": types, "ptr_types": ptr_types, "consts": consts, "id_type": id_type, - "globals": globals_, "body": body, "labels": labels, "main_pc": 0, - "zero_of": zero_of, - } - - -def _check_spirv_structure(text): - """Static structural sanity checks on translated SPIR-V text (unique labels, valid targets, no subgroup ops).""" - lines = _strip_comments(text) - in_fn = False - seen_labels = set() - defined_ids = set() - referenced_labels = [] - prev_term = True - for line in lines: - m = _SPV_LINE.match(line) - assert m, f"unparseable SPIR-V line: {line!r}" - res, op, rest = m.groups() - a = rest.split() if rest else [] - if op == "OpFunction": - in_fn = True - prev_term = True - continue - if op == "OpFunctionParameter": - assert in_fn and prev_term, f"OpFunctionParameter outside function header: {line}" - continue - if op == "OpFunctionEnd": - assert prev_term, "function ended without block terminator" - in_fn = False - continue - if not in_fn: - if res: - defined_ids.add(res) - continue - if op == "OpLabel": - assert prev_term, f"OpLabel {res} reached without preceding terminator" - assert res not in seen_labels, f"duplicate OpLabel {res}" - seen_labels.add(res) - prev_term = False - continue - assert not prev_term, f"instruction after terminator before OpLabel: {line}" - if op == "OpBranch": - referenced_labels.append(a[0]) - prev_term = True - elif op == "OpBranchConditional": - referenced_labels.extend((a[1], a[2])) - prev_term = True - elif op == "OpSwitch": - referenced_labels.append(a[1]) - for i in range(3, len(a), 2): - referenced_labels.append(a[i]) - prev_term = True - elif op in ("OpReturn", "OpReturnValue", "OpKill", "OpUnreachable"): - prev_term = True - elif op == "OpSelectionMerge": - referenced_labels.append(a[0]) - elif op == "OpLoopMerge": - referenced_labels.extend((a[0], a[1])) - for lbl in referenced_labels: - assert lbl in seen_labels, f"branch/merge references undefined label {lbl}" - - -def run_emulated_workgroup(spvasm, local_size, push_constants=None, memory=None, max_steps=2_000_000, reverse_order=False): - """Execute a --wave64-emulate compute shader across all `lx * ly * lz` invocations with real shared - Workgroup memory and strict uniform OpControlBarrier checking. Returns `(memory, barrier_count)`.""" - _check_spirv_structure(spvasm) - mod = _parse_module(spvasm) - types = mod["types"] - ptr_types = mod["ptr_types"] - consts = mod["consts"] - body = mod["body"] - labels = mod["labels"] - zero_of = mod["zero_of"] - - push_constants = list(push_constants or []) - memory = {} if memory is None else memory - lx, ly, lz = local_size - coords = [(x, y, z) for z in range(lz) for y in range(ly) for x in range(lx)] - n_inv = len(coords) - - # Shared Workgroup variables across all invocations in the workgroup. - wg_boxes = {} - for res, cls, pointee, init_id in mod["globals"]: - if cls == "Workgroup": - wg_boxes[res] = [zero_of(pointee)] - - def walk_struct_offset(tid, idxs): - off = 0 - cur = tid - for idx in idxs: - k = types[cur] - if k[0] == "struct": - for m_t in k[1][:idx]: - off += _type_bytes(m_t) - cur = k[1][idx] - elif k[0] == "arr": - off += idx * _type_bytes(k[1]) - cur = k[1] - else: - raise NotImplementedError(f"walk {k}") - return off, cur - - def _type_bytes(tid): - k = types[tid] - if k[0] == "int": - return k[1] // 8 - if k[0] == "float": - return k[1] // 8 - if k[0] == "vec": - return k[2] * _type_bytes(k[1]) - if k[0] == "arr": - return k[2] * _type_bytes(k[1]) - if k[0] == "struct": - return sum(_type_bytes(m) for m in k[1]) - raise NotImplementedError(f"size {k}") - - def make_inv(idx, coord): - vals = dict(consts) - id_t = dict(mod["id_type"]) - ptrs = {} - pc_t = {} - for res, cls, pointee, init_id in mod["globals"]: - if cls == "PushConstant": - ptrs[res] = ("pc", 0) - pc_t[res] = pointee - elif cls == "Workgroup": - ptrs[res] = (wg_boxes[res], 0) - elif cls == "Input": - if res == "%local_id": - box = [coord] - elif res == "%wg_id": - box = [(0, 0, 0)] - elif res == "%local_index": - box = [idx] - else: - box = [zero_of(pointee)] - ptrs[res] = (box, 0) - else: - raise NotImplementedError(f"global storage class {cls}") - return { - "pc": mod["main_pc"], "vals": vals, "id_t": id_t, "ptrs": ptrs, "pc_t": pc_t, - "cur_lbl": None, "prev_lbl": None, "done": False, "barrier": None, - } - - def step_until_barrier(inv, step_budget): - vals, id_t, ptrs, pc_t = inv["vals"], inv["id_t"], inv["ptrs"], inv["pc_t"] - pc = inv["pc"] - steps = 0 - while pc < len(body): - steps += 1 - if steps > step_budget: - raise AssertionError(f"exceeded step budget {step_budget} (infinite loop?)") - res, op, a, line = body[pc] - pc += 1 - if res and a: - id_t[res] = a[0] - if op == "OpLabel": - inv["prev_lbl"], inv["cur_lbl"] = inv["cur_lbl"], res - continue - if op in _SPV_IGNORED: - continue - if op == "OpControlBarrier": - inv["pc"] = pc - inv["barrier"] = pc - 1 - return steps - if op == "OpReturn": - inv["pc"] = pc - inv["done"] = True - return steps - if op == "OpBranch": - pc = labels[a[0]] - continue - if op == "OpBranchConditional": - cond = vals[a[0]] - assert isinstance(cond, bool), f"non-bool branch cond: {line}" - pc = labels[a[1] if cond else a[2]] - continue - if op == "OpSwitch": - sel = vals[a[0]] - tgt = a[1] - for k in range(2, len(a), 2): - if int(a[k]) == sel: - tgt = a[k + 1] - break - pc = labels[tgt] - continue - if op == "OpPhi": - matched = [a[k] for k in range(1, len(a) - 1, 2) if a[k + 1] == inv["prev_lbl"]] - assert len(matched) == 1, f"OpPhi prev_lbl={inv['prev_lbl']!r} not in {line}" - vals[res] = vals[matched[0]] - continue - if op == "OpVariable": - cls, pointee = ptr_types[a[0]] - assert cls == "Function" - if len(a) > 2: - iv = vals[a[2]] - box = [list(iv) if isinstance(iv, list) else iv] - else: - box = [zero_of(pointee)] - ptrs[res] = (box, 0) - elif op == "OpAccessChain": - p = ptrs[a[1]] - if p[0] == "pc": - off, cur = walk_struct_offset(pc_t[a[1]], [vals[i] for i in a[2:]]) - ptrs[res] = ("pc", p[1] + off) - pc_t[res] = cur - elif p[0] == "psb": - elem = ptr_types[a[0]][1] - stride = _type_bytes(types[elem][1] if types[elem][0] == "rarr" else elem) - ptrs[res] = ("psb", p[1] + stride * vals[a[2]]) - else: - cur_p = p - for idx_id in a[2:]: - idx = vals[idx_id] - container = cur_p[0][cur_p[1]] - assert 0 <= idx < len(container), f"OOB index {idx} in {line}" - cur_p = (container, idx) - ptrs[res] = cur_p - elif op == "OpLoad": - p = ptrs[a[1]] - if p[0] == "pc": - w = p[1] // 4 - vals[res] = push_constants[w] if 0 <= w < len(push_constants) else 0 - elif p[0] == "psb": - assert p[1] % 4 == 0, f"unaligned PSB load {p[1]:#x}" - vals[res] = memory.get(p[1], 0) - else: - v = p[0][p[1]] - vals[res] = list(v) if isinstance(v, list) else v - elif op == "OpStore": - p = ptrs[a[0]] - v = vals[a[1]] - if p[0] == "psb": - assert p[1] % 4 == 0, f"unaligned PSB store {p[1]:#x}" - memory[p[1]] = v & MASK32 - else: - p[0][p[1]] = v - elif op in ("OpAtomicOr", "OpAtomicIAdd", "OpAtomicAnd", "OpAtomicXor", "OpAtomicExchange"): - p = ptrs[a[1]] - old = memory.get(p[1], 0) if p[0] == "psb" else p[0][p[1]] - v = vals[a[4]] & MASK32 - if op == "OpAtomicOr": - new = old | v - elif op == "OpAtomicIAdd": - new = (old + v) & MASK32 - elif op == "OpAtomicAnd": - new = old & v - elif op == "OpAtomicXor": - new = old ^ v - else: - new = v - if p[0] == "psb": - memory[p[1]] = new & MASK32 - else: - p[0][p[1]] = new & MASK32 - vals[res] = old - elif op == "OpSelect": - vals[res] = vals[a[2]] if vals[a[1]] else vals[a[3]] - elif op == "OpCopyObject": - vals[res] = vals[a[1]] - elif op == "OpCompositeExtract": - v = vals[a[1]] - for i in a[2:]: - v = v[int(i)] - vals[res] = v - elif op == "OpCompositeConstruct": - vals[res] = tuple(vals[x] for x in a[1:]) - elif op == "OpConvertUToPtr": - ptrs[res] = ("psb", vals[a[1]]) - vals[res] = ptrs[res] - elif op == "OpUConvert": - bits = types[a[0]][1] - vals[res] = vals[a[1]] & ((1 << bits) - 1) - elif op == "OpBitcast": - k = types[a[0]] - v = vals[a[1]] - if k[0] == "int": - vals[res] = v & ((1 << k[1]) - 1) if isinstance(v, int) else struct.unpack("> vals[a[2]] - elif op == "OpIAdd": - bits = types[a[0]][1] - vals[res] = (vals[a[1]] + vals[a[2]]) & ((1 << bits) - 1) - elif op == "OpISub": - bits = types[a[0]][1] - vals[res] = (vals[a[1]] - vals[a[2]]) & ((1 << bits) - 1) - elif op == "OpIMul": - bits = types[a[0]][1] - vals[res] = (vals[a[1]] * vals[a[2]]) & ((1 << bits) - 1) - elif op == "OpUMod": - vals[res] = vals[a[1]] % vals[a[2]] - elif op == "OpUDiv": - vals[res] = vals[a[1]] // vals[a[2]] - elif op == "OpIAddCarry": - s = (vals[a[1]] & MASK32) + (vals[a[2]] & MASK32) - vals[res] = (s & MASK32, 1 if s > MASK32 else 0) - elif op == "OpISubBorrow": - x, y = vals[a[1]] & MASK32, vals[a[2]] & MASK32 - vals[res] = ((x - y) & MASK32, 1 if x < y else 0) - elif op == "OpIEqual": - vals[res] = vals[a[1]] == vals[a[2]] - elif op == "OpINotEqual": - vals[res] = vals[a[1]] != vals[a[2]] - elif op == "OpULessThan": - vals[res] = vals[a[1]] < vals[a[2]] - elif op == "OpULessThanEqual": - vals[res] = vals[a[1]] <= vals[a[2]] - elif op == "OpUGreaterThan": - vals[res] = vals[a[1]] > vals[a[2]] - elif op == "OpUGreaterThanEqual": - vals[res] = vals[a[1]] >= vals[a[2]] - elif op == "OpSLessThan": - vals[res] = _s32(vals[a[1]]) < _s32(vals[a[2]]) - elif op == "OpSGreaterThan": - vals[res] = _s32(vals[a[1]]) > _s32(vals[a[2]]) - elif op == "OpLogicalNot": - vals[res] = not vals[a[1]] - elif op == "OpLogicalAnd": - vals[res] = vals[a[1]] and vals[a[2]] - elif op == "OpLogicalOr": - vals[res] = vals[a[1]] or vals[a[2]] - elif op == "OpBitCount": - vals[res] = (vals[a[1]] & MASK32).bit_count() - elif op == "OpBitFieldUExtract": - base, off, cnt = vals[a[1]], vals[a[2]], vals[a[3]] - vals[res] = (base >> off) & ((1 << cnt) - 1) if cnt else 0 - elif op == "OpExtInst": - ext_op = a[2] - if ext_op == "UMin": - vals[res] = min(vals[a[3]], vals[a[4]]) - elif ext_op == "UMax": - vals[res] = max(vals[a[3]], vals[a[4]]) - elif ext_op == "FindILsb": - v = vals[a[3]] & MASK32 - vals[res] = (v & -v).bit_length() - 1 if v else MASK32 - elif ext_op == "FindUMsb": - v = vals[a[3]] & MASK32 - vals[res] = v.bit_length() - 1 if v else MASK32 - elif ext_op == "FindSMsb": - v = _s32(vals[a[3]]) - if v in (0, -1): - vals[res] = MASK32 - elif v > 0: - vals[res] = v.bit_length() - 1 - else: - vals[res] = (~v).bit_length() - 1 - else: - raise NotImplementedError(f"OpExtInst {ext_op}: {line}") - else: - raise NotImplementedError(f"unsupported op {op}: {line}") - inv["pc"] = pc - inv["done"] = True - return steps - - invs = [make_inv(i, c) for i, c in enumerate(coords)] - step_order = list(reversed(invs)) if reverse_order else invs - total_steps = 0 - barriers = 0 - while True: - for inv in step_order: - if not inv["done"]: - inv["barrier"] = None - total_steps += step_until_barrier(inv, max_steps - total_steps) - if all(inv["done"] for inv in invs): - break - # Strict uniform barrier check: every invocation must stop at the exact same OpControlBarrier. - if any(inv["done"] for inv in invs): - raise AssertionError("non-uniform OpControlBarrier: some invocations returned while others waited") - sites = {inv["barrier"] for inv in invs} - if len(sites) != 1 or None in sites: - raise AssertionError(f"non-uniform OpControlBarrier sites: {sites}") - barriers += 1 - return memory, barriers - - -def _translate_encoded(name, insns, local_size=(64, 1, 1), emulate=True, rsrc2=0x8088): - """Translate a list of `(text, nbytes)` instructions with synthetic encoding placeholders.""" - lines = [f"; {name} synthetic", "; mattr: +wavefrontsize64,-wavefrontsize32"] - for txt, nb in insns: - enc = ",".join(["0x00"] * nb) - lines.append(f"\t{txt:52s} ; encoding: [{enc}]") - prev_emu = rdna2spirv.WAVE64_EMULATE - rdna2spirv.WAVE64_EMULATE = emulate - try: - with tempfile.TemporaryDirectory() as td: - os.mkdir(os.path.join(td, "disasm")) - os.mkdir(os.path.join(td, "fssm")) - s_path = os.path.join(td, "disasm", name + ".s") - f_path = os.path.join(td, "fssm", name + ".fssm") - with open(s_path, "w", encoding="utf-8") as f: - f.write("\n".join(lines) + "\n") - lx, ly, lz = local_size - with open(f_path, "wb") as f: - f.write(bytes(0x138) + struct.pack("<4I", rsrc2, lx, ly, lz)) - spv = rdna2spirv.translate(s_path) - gen = rdna2spirv.translate.last_gen - return spv, gen - finally: - rdna2spirv.WAVE64_EMULATE = prev_emu - - -def _switch_case_count(gen): - return sum(1 for b in gen.blocks if b is not None) + len(gen.x_segs) - - -def _screenprobes_insns(n_steps, with_loads=False): - insns = [("v_mov_b32_e32 v4, v0", 4)] - for _ in range(n_steps): - insns.append(("v_cmp_lt_u32_e64 s[10:11], 16, v4", 8)) - insns.append(("s_and_saveexec_b64 s[12:13], s[10:11]", 4)) - insns.append(("s_cbranch_execz 4" if with_loads else "s_cbranch_execz 2", 4)) - if with_loads: - insns.append(("v_lshlrev_b32_e32 v8, 2, v0", 4)) - insns.append(("buffer_load_dword v5, v8, s[0:3], 0 offen", 8)) - insns.append(("v_add_nc_u32_e32 v4, v5, v4", 4)) - else: - insns.append(("v_add_nc_u32_e32 v4, 1, v4", 4)) - insns.append(("v_xor_b32_e32 v4, 7, v4", 4)) - insns.append(("s_andn2_b64 exec, s[12:13], exec", 4)) - insns.append(("s_cbranch_execz 2", 4)) - insns.append(("v_add_nc_u32_e32 v4, 3, v4", 4)) - insns.append(("v_xor_b32_e32 v4, 5, v4", 4)) - insns.append(("s_or_b64 exec, exec, s[12:13]", 4)) - insns.append(("v_lshlrev_b32_e32 v9, 2, v0", 4)) - insns.append(("v_add_nc_u32_e32 v9, 1024, v9", 4)) - insns.append(("buffer_store_dword v4, v9, s[0:3], 0 offen", 8)) - insns.append(("s_endpgm", 4)) - return insns - - -class DeadSccLivenessTests(unittest.TestCase): - def test_dead_scc_mask_ops_elide_votes_while_live_scc_is_exact(self): - # First s_and_saveexec_b64 has DEAD SCC (immediately overwritten by second s_and_saveexec_b64); - # second s_and_saveexec_b64 has LIVE SCC (read by s_cselect_b32), and only lane 50 is active! - insns = [ - ("v_cmp_lt_u32_e64 s[6:7], 20, v0", 8), - ("s_and_saveexec_b64 s[8:9], s[6:7]", 4), # DEAD SCC -> no vote! - ("s_or_b64 exec, exec, s[8:9]", 4), # DEAD SCC -> no vote! - ("v_cmp_eq_u32_e64 s[10:11], 50, v0", 8), - ("s_and_saveexec_b64 s[12:13], s[10:11]", 4), # LIVE SCC -> must vote across all 64 lanes! - ("s_cselect_b32 s14, 111, 222", 4), - ("s_mov_b64 exec, -1", 4), - ("v_mov_b32_e32 v5, s14", 4), - ("v_lshlrev_b32_e32 v6, 2, v0", 4), - ("buffer_store_dword v5, v6, s[0:3], 0 offen", 8), - ("s_endpgm", 4), - ] - spv, gen = _translate_encoded("cs_scc_live_dead", insns, (64, 1, 1), emulate=True) - # Only ONE mask-op SCC vote remains (1 OpAtomicOr, not 3). - self.assertEqual(spv.count("OpAtomicOr"), 1) - self.assertEqual(len(gen.x_segs), 1) - mem, _ = run_emulated_workgroup(spv, (64, 1, 1), push_constants=VSHARP + [0] * 28) - for lane in range(64): - self.assertEqual(mem[lane * 4], 111, f"lane {lane} missed live wave64 SCC from lane 50") - - def test_cross_block_live_scc_preserved(self): - # SCC written in block 0 by s_and_saveexec_b64, read in block 1 by s_cbranch_scc0. - insns = [ - ("s_mov_b32 s14, 0", 4), - ("v_cmp_eq_u32_e64 s[6:7], 45, v0", 8), - ("s_and_saveexec_b64 s[8:9], s[6:7]", 4), # LIVE SCC across branch! - ("s_cbranch_scc0 1", 4), # not taken because lane 45 is active - ("s_mov_b32 s14, 77", 4), - ("s_mov_b64 exec, -1", 4), - ("v_mov_b32_e32 v5, s14", 4), - ("v_lshlrev_b32_e32 v6, 2, v0", 4), - ("buffer_store_dword v5, v6, s[0:3], 0 offen", 8), - ("s_endpgm", 4), - ] - spv, _ = _translate_encoded("cs_scc_xblock", insns, (64, 1, 1), emulate=True) - self.assertEqual(spv.count("OpAtomicOr"), 1) - mem, _ = run_emulated_workgroup(spv, (64, 1, 1), push_constants=VSHARP + [0] * 28) - for lane in range(64): - self.assertEqual(mem[lane * 4], 77, f"lane {lane}: expected 77 from cross-block live SCC") - - def test_src_scc_keeps_mask_vote_live(self): - for threads in (64, 128): - for consumer in ("scalar", "vector"): - with self.subTest(threads=threads, consumer=consumer): - insns = [ - ("v_and_b32_e32 v3, 63, v0", 4), - ("v_cmp_eq_u32_e64 s[6:7], 45, v3", 8), - ("s_and_saveexec_b64 s[8:9], s[6:7]", 4), - ] - if consumer == "scalar": - insns.append(("s_mov_b32 s14, src_scc", 4)) - insns.append(("s_mov_b64 exec, -1", 4)) - insns.append(("v_mov_b32_e32 v5, s14", 4) if consumer == "scalar" - else ("v_mov_b32_e32 v5, src_scc", 4)) - insns.extend([ - ("v_lshlrev_b32_e32 v6, 2, v0", 4), - ("buffer_store_dword v5, v6, s[0:3], 0 offen", 8), - ("s_endpgm", 4), - ]) - size = (threads, 1, 1) - spirv, _ = _translate_encoded("cs_scc_inline_source", insns, size) - mem, _ = run_emulated_workgroup(spirv, size, push_constants=VSHARP + [0] * 28) - # Lane 45 is active on every wave, so the scalar SCC reads as one in every lane. - actual = [mem[lane * 4] for lane in range(threads)] - self.assertEqual(actual, [1] * threads, - f"{actual.count(1)}/{threads} lanes observed the live SCC") - - def test_non_emulated_unchanged_keeps_wqm_scc_vote(self): - # Verify WAVE64_EMULATE=False keeps dead-SCC votes (required by test_translate.py WQM_MASK). - insns = [ - ("s_mov_b64 exec, -1", 4), - ("v_cmp_gt_u32_e32 vcc, 16, v0", 4), - ("s_wqm_b64 s[6:7], vcc", 4), - ("s_bcnt1_i32_b64 s8, s[6:7]", 4), - ("s_endpgm", 4), - ] - spv_native, _ = _translate_encoded("cs_wqm_native_keep", insns, (64, 1, 1), emulate=False) - self.assertIn("OpGroupNonUniformAny", spv_native) - spv_emu, _ = _translate_encoded("cs_wqm_emu_dead_scc", insns, (64, 1, 1), emulate=True) - self.assertNotIn("OpGroupNonUniform", spv_emu) - # Only s_bcnt1's wave_mask uses OpAtomicOr (2 words); s_wqm's dead SCC vote is elided. - self.assertEqual(spv_emu.count("OpAtomicOr"), 2) - - -class LocalExecFoldTests(unittest.TestCase): - def test_screenprobes_chain_64_and_128_threads_bit_exact(self): - # 16 sequential ScreenProbes-shaped if/else steps with buffer loads + final store. - insns = _screenprobes_insns(16, with_loads=True) - init_mem = {i * 4: ((i * 17 + 3) & 0xFF) for i in range(128)} - for wg in ((64, 1, 1), (128, 1, 1)): - with self.subTest(wg=wg): - spv, gen = _translate_encoded(f"cs_sp_{wg[0]}", insns, wg, emulate=True) - # All 16*4=64 blocks collapse into 1 block + 1 memory-order split before the final store! - self.assertEqual(_switch_case_count(gen), 2) - self.assertEqual(spv.count("OpAtomicOr"), 0) - self.assertNotIn("OpGroupNonUniform", spv) - mem, _ = run_emulated_workgroup(spv, wg, push_constants=VSHARP + [0] * 28, memory=dict(init_mem)) - for lane in range(wg[0]): - v = lane - ld = init_mem[lane * 4] - for _ in range(16): - if 16 < v: - v = ((v + ld) & MASK32) ^ 7 - else: - v = ((v + 3) & MASK32) ^ 5 - self.assertEqual(mem[1024 + lane * 4], v, f"wg={wg} lane={lane}") - - def test_nested_exec_and_inner_saveexec_fold_exact(self): - # Outer s_cbranch_execz contains a nested s_and_saveexec_b64 + s_cbranch_execz + s_or_b64 restore. - insns = [ - ("v_mov_b32_e32 v4, v0", 4), - ("v_cmp_lt_u32_e64 s[6:7], 15, v0", 8), # lanes 16..63 - ("s_and_saveexec_b64 s[8:9], s[6:7]", 4), - ("s_cbranch_execz 7", 4), # outer skip -> restore - ("v_add_nc_u32_e32 v4, 100, v4", 4), - ("v_cmp_lt_u32_e64 s[10:11], 40, v0", 8), # inner: lanes 41..63 - ("s_and_saveexec_b64 s[12:13], s[10:11]", 4), - ("s_cbranch_execz 1", 4), # inner skip -> inner restore - ("v_add_nc_u32_e32 v4, 1000, v4", 4), - ("s_or_b64 exec, exec, s[12:13]", 4), # inner restore (from zero_pair s[12:13]) - ("v_add_nc_u32_e32 v4, 10, v4", 4), - ("s_or_b64 exec, exec, s[8:9]", 4), # outer restore - ("v_lshlrev_b32_e32 v9, 2, v0", 4), - ("buffer_store_dword v4, v9, s[0:3], 0 offen", 8), - ("s_endpgm", 4), - ] - spv, gen = _translate_encoded("cs_nested_fold", insns, (64, 1, 1), emulate=True) - self.assertEqual(_switch_case_count(gen), 1) - self.assertEqual(spv.count("OpAtomicOr"), 0) - mem, _ = run_emulated_workgroup(spv, (64, 1, 1), push_constants=VSHARP + [0] * 28) - for lane in range(64): - want = lane - if lane > 15: - want += 100 - if lane > 40: - want += 1000 - want += 10 - self.assertEqual(mem[lane * 4], want, f"lane {lane}") - - def test_negative_live_out_scalar_not_folded(self): - # Like cs_w64x_branch: s9 is written inside s_cbranch_execz and read after join -> MUST NOT fold! - insns = [ - ("s_mov_b32 s9, 0", 4), - ("s_mov_b32 exec_lo, 0", 4), - ("s_mov_b32 exec_hi, 0xff", 4), # lanes 32..39 active; lane 0 inactive - ("s_cbranch_execz 1", 4), # must vote across all 64 lanes! - ("s_mov_b32 s9, 5", 4), - ("s_mov_b64 exec, -1", 4), - ("v_mov_b32_e32 v5, s9", 4), - ("v_lshlrev_b32_e32 v6, 2, v0", 4), - ("buffer_store_dword v5, v6, s[0:3], 0 offen", 8), - ("s_endpgm", 4), - ] - spv, _ = _translate_encoded("cs_neg_live_scalar", insns, (64, 1, 1), emulate=True) - self.assertEqual(spv.count("OpAtomicOr"), 1) - mem, _ = run_emulated_workgroup(spv, (64, 1, 1), push_constants=VSHARP + [0] * 28) - for lane in range(64): - self.assertEqual(mem[lane * 4], 5, f"lane {lane}: stale scalar s9 after s_cbranch_execz") - - def test_negative_store_and_crosslane_and_exec_widen_not_folded(self): - cases = [ - ("multi_store", [ - ("s_and_saveexec_b64 s[8:9], vcc", 4), - ("s_cbranch_execz 4", 4), - ("buffer_store_dword v0, v0, s[0:3], 0 offen", 8), - ("buffer_store_dword v0, v0, s[0:3], 0 offen offset:4", 8), - ("s_or_b64 exec, exec, s[8:9]", 4), - ("s_endpgm", 4), - ]), - ("load_and_store", [ - ("s_and_saveexec_b64 s[8:9], vcc", 4), - ("s_cbranch_execz 4", 4), - ("buffer_load_dword v4, v0, s[0:3], 0 offen", 8), - ("buffer_store_dword v4, v0, s[0:3], 0 offen", 8), - ("s_or_b64 exec, exec, s[8:9]", 4), - ("s_endpgm", 4), - ]), - ("crosslane", [ - ("s_and_saveexec_b64 s[8:9], vcc", 4), - ("s_cbranch_execz 1", 4), - ("v_readlane_b32 s10, v0, 40", 4), - ("s_or_b64 exec, exec, s[8:9]", 4), - ("s_endpgm", 4), - ]), - ("exec_widen", [ - ("s_and_saveexec_b64 s[8:9], vcc", 4), - ("s_cbranch_execz 2", 4), - ("s_mov_b64 exec, -1", 4), # widens EXEC! must not fold - ("v_add_nc_u32_e32 v4, 1, v4", 4), - ("s_or_b64 exec, exec, s[8:9]", 4), - ("s_endpgm", 4), - ]), - ] - for label, insns in cases: - with self.subTest(case=label): - spv, _ = _translate_encoded(f"cs_neg_{label}", insns, (64, 1, 1), emulate=True) - self.assertGreaterEqual(spv.count("OpAtomicOr"), 1, f"{label} should NOT fold s_cbranch_execz") - - def test_mask_flbit_keeps_wave_exchange_out_of_lane_local_execz_fold(self): - # Both waves have bit 3 set in VCC_LO. Only lane 32 of each wave writes its leading-zero count. - for lx in (64, 128): - for op, ext_inst in (("s_flbit_i32_b32", "FindUMsb"), ("s_flbit_i32", "FindSMsb")): - for source in ("vcc_lo", "s14"): - with self.subTest(threads=lx, op=op, source=source): - insns = [ - ("s_mov_b32 s14, 8", 4), - ("v_and_b32_e32 v1, 63, v0", 4), - ("v_cmp_eq_u32_e32 vcc, 3, v1", 4), - ("v_lshlrev_b32_e32 v6, 2, v0", 4), - ("s_mov_b32 exec_lo, 0", 4), - ("s_mov_b32 exec_hi, 1", 4), - ("s_cbranch_execz 4", 4), - (f"{op} s9, {source}", 4), - ("v_mov_b32_e32 v4, s9", 4), - ("buffer_store_dword v4, v6, s[0:3], 0 offen", 8), - ("s_mov_b64 exec, -1", 4), - ("s_endpgm", 4), - ] - spv, _ = _translate_encoded("cs_flbit_in_execz", insns, (lx, 1, 1), emulate=True) - self.assertIn(ext_inst, spv) - if source == "vcc_lo": - self.assertIn("OpAtomicOr", spv) - else: - self.assertNotIn("OpAtomicOr", spv) - if op == "s_flbit_i32_b32": - mem, _ = run_emulated_workgroup(spv, (lx, 1, 1), push_constants=VSHARP + [0] * 28) - self.assertEqual(mem, {lane * 4: 28 for lane in range(32, lx, 64)}) - - def test_write_before_folded_read_orders_across_halves(self): - # Every lane stores `100 + lane` at `lane * 4`; then ONLY lanes >= 32 enter a folded s_cbranch_execz - # and read partner lane `(lane ^ 32) * 4`. The uniform x_split before `if (%active)` must order the write! - insns = [ - ("v_lshlrev_b32_e32 v7, 2, v0", 4), - ("v_add_nc_u32_e32 v6, 100, v0", 4), - ("buffer_store_dword v6, v7, s[0:3], 0 offen", 8), - ("v_mov_b32_e32 v9, 0", 4), - ("v_cmp_le_u32_e64 s[6:7], 32, v0", 8), # lanes 32..63 only - ("s_and_saveexec_b64 s[8:9], s[6:7]", 4), - ("s_cbranch_execz 4", 4), - ("v_xor_b32_e32 v8, 32, v0", 4), - ("v_lshlrev_b32_e32 v8, 2, v8", 4), - ("buffer_load_dword v9, v8, s[0:3], 0 offen", 8), - ("s_or_b64 exec, exec, s[8:9]", 4), - ("v_add_nc_u32_e32 v10, 512, v7", 4), - ("buffer_store_dword v9, v10, s[0:3], 0 offen", 8), - ("s_endpgm", 4), - ] - spv, gen = _translate_encoded("cs_raw_before_fold", insns, (64, 1, 1), emulate=True) - # Folded (0 OpAtomicOr), with 2 uniform memory-order splits: write->read and read->write. - self.assertEqual(spv.count("OpAtomicOr"), 0) - self.assertEqual(len(gen.x_segs), 2) - mem, _ = run_emulated_workgroup(spv, (64, 1, 1), push_constants=VSHARP + [0] * 28) - for lane in range(64): - want = (100 + (lane ^ 32)) if lane >= 32 else 0 - self.assertEqual(mem[512 + lane * 4], want, f"lane {lane}") - - def test_multiwave_128_folded_exec_stays_synchronized_for_later_readlane_and_barrier(self): - # 128 threads (2 waves): every thread runs a folded s_cbranch_execz, followed by v_readlane(lane 40) - # and an s_barrier + LDS read from the other wave. Proves zero round desynchronization across waves! - insns = [ - ("v_mov_b32_e32 v4, v0", 4), - ("v_and_b32_e32 v2, 1, v0", 4), - ("v_cmp_eq_u32_e64 s[6:7], 1, v2", 8), # odd lanes only - ("s_and_saveexec_b64 s[8:9], s[6:7]", 4), - ("s_cbranch_execz 1", 4), # folded! - ("v_add_nc_u32_e32 v4, 1000, v4", 4), - ("s_or_b64 exec, exec, s[8:9]", 4), - ("v_readlane_b32 s10, v4, 41", 4), # cross-half readlane in each wave (odd lane -> +1000) - ("v_lshlrev_b32_e32 v5, 2, v0", 4), - ("ds_write_b32 v5, v4", 8), - ("s_barrier", 4), - ("v_xor_b32_e32 v6, 64, v0", 4), # read partner thread in the OTHER wave! - ("v_lshlrev_b32_e32 v6, 2, v6", 4), - ("ds_read_b32 v7, v6", 8), - ("v_add_nc_u32_e32 v8, s10, v7", 4), - ("buffer_store_dword v8, v5, s[0:3], 0 offen", 8), - ("s_endpgm", 4), - ] - spv, _ = _translate_encoded("cs_mw128_sync", insns, (128, 1, 1), emulate=True) - self.assertEqual(spv.count("OpAtomicOr"), 0) - mem, barriers = run_emulated_workgroup(spv, (128, 1, 1), push_constants=VSHARP + [0] * 28) - self.assertGreaterEqual(barriers, 3) - for tid in range(128): - wave_base = (tid // 64) * 64 - s10_want = wave_base + 41 + 1000 - partner = tid ^ 64 - v7_want = partner + (1000 if (partner & 1) else 0) - self.assertEqual(mem[tid * 4], s10_want + v7_want, f"tid {tid}") - - def test_folded_region_with_internal_loop_exact(self): - # Multi-block folded s_cbranch_execz containing an internal scalar-counted loop (`sub_tree` loop path). - # Lanes >= 32 add 5 four times (+20); lanes < 32 skip the entire loop. s15 is dead at the join. - insns = [ - ("v_mov_b32_e32 v4, v0", 4), - ("v_cmp_le_u32_e64 s[6:7], 32, v0", 8), # lanes 32..63 - ("s_and_saveexec_b64 s[8:9], s[6:7]", 4), - ("s_cbranch_execz 5", 4), # skip 5 dwords (5 x 4B insns) to restore - ("s_mov_b32 s15, 4", 4), - ("v_add_nc_u32_e32 v4, 5, v4", 4), # loop header (pc +4) - ("s_sub_u32 s15, s15, 1", 4), - ("s_cmp_gt_u32 s15, 0", 4), - ("s_cbranch_scc1 -4", 4), # back 4 dwords to v_add_nc_u32 - ("s_or_b64 exec, exec, s[8:9]", 4), - ("v_lshlrev_b32_e32 v9, 2, v0", 4), - ("buffer_store_dword v4, v9, s[0:3], 0 offen", 8), - ("s_endpgm", 4), - ] - spv, gen = _translate_encoded("cs_fold_loop", insns, (64, 1, 1), emulate=True) - self.assertEqual(_switch_case_count(gen), 1) - self.assertEqual(spv.count("OpAtomicOr"), 0) - self.assertGreaterEqual(spv.count("OpLoopMerge"), 2) # outer scheduler loop + inner folded loop - mem, _ = run_emulated_workgroup(spv, (64, 1, 1), push_constants=VSHARP + [0] * 28) - for lane in range(64): - want = lane + (20 if lane >= 32 else 0) - self.assertEqual(mem[lane * 4], want, f"lane {lane}") - - def test_folded_region_scalar_branch_to_join_skips_the_rest(self): - # An s_cbranch_scc inside a folded s_cbranch_execz region that jumps straight to the join: the region's - # sub-CFG must keep that exit edge, or the block after the branch runs on the exit path too. Lanes whose - # (5 * lane) & 15 > 12 enter the region; s11 decides the scalar branch. The add must run only when the - # branch falls through. - for cmp, s11, taken in (("s_cmp_ge_u32 s11, 33", 5, True), ("s_cmp_ge_u32 s11, 33", 40, False), - ("s_cmp_lt_u32 s11, 33", 5, True), ("s_cmp_lt_u32 s11, 33", 40, False)): - branch = "s_cbranch_scc0 2" if cmp.startswith("s_cmp_ge") else "s_cbranch_scc1 2" - insns = [ - ("v_mul_lo_u32 v3, v0, 5", 8), - ("v_and_b32_e32 v3, 15, v3", 4), - ("v_mov_b32_e32 v4, 1", 4), - (f"s_mov_b32 s11, {s11}", 4), - ("v_cmp_lt_u32_e32 vcc, 12, v3", 4), - ("s_and_saveexec_b64 s[8:9], vcc", 4), - ("s_cbranch_execz 4", 4), # to the join (4 dwords) - (cmp, 4), - (branch, 4), # to the join (2 dwords) - ("v_add_nc_u32_e32 v4, 21, v4", 4), - ("v_add_nc_u32_e32 v4, 100, v4", 4), - ("s_or_b64 exec, exec, s[8:9]", 4), - ("v_lshlrev_b32_e32 v9, 2, v0", 4), - ("buffer_store_dword v4, v9, s[0:3], 0 offen", 8), - ("s_endpgm", 4), - ] - for threads in (64, 128): - with self.subTest(cmp=cmp, s11=s11, threads=threads): - spv, gen = _translate_encoded("cs_fold_scc_exit", insns, (threads, 1, 1), emulate=True) - self.assertEqual(_switch_case_count(gen), 1) # the region is folded inline - mem, _ = run_emulated_workgroup(spv, (threads, 1, 1), push_constants=VSHARP + [0] * 28) - for lane in range(threads): - inside = ((lane % 64) * 5) & 15 > 12 - want = 1 + (121 if inside and not taken else 0) - self.assertEqual(mem[lane * 4], want, f"lane {lane}") - - def test_cs_w64x_saveexec_b64_fixture_emulated_exact(self): - # Run the repo's real cs_w64x_saveexec_b64.s fixture under --wave64-emulate on the 64-lane barrier interpreter. - fixture = os.path.join(HERE, "fixtures", "disasm", "cs_w64x_saveexec_b64.s") - if not os.path.isfile(fixture): - self.skipTest("cs_w64x_saveexec_b64.s fixture absent") - prev_emu = rdna2spirv.WAVE64_EMULATE - rdna2spirv.WAVE64_EMULATE = True - try: - with tempfile.TemporaryDirectory() as td: - os.mkdir(os.path.join(td, "disasm")) - os.mkdir(os.path.join(td, "fssm")) - s_path = os.path.join(td, "disasm", "cs_w64x_saveexec_b64.s") - f_path = os.path.join(td, "fssm", "cs_w64x_saveexec_b64.fssm") - with open(fixture, encoding="utf-8") as src, open(s_path, "w", encoding="utf-8") as dst: - dst.write(src.read()) - with open(f_path, "wb") as f: - f.write(bytes(0x138) + struct.pack("<4I", 0x8088, 64, 1, 1)) - spv = rdna2spirv.translate(s_path) - finally: - rdna2spirv.WAVE64_EMULATE = prev_emu - mem, _ = run_emulated_workgroup(spv, (64, 1, 1), push_constants=VSHARP + [0] * 28) - got = [mem.get(i * 4, 0) for i in range(8)] - self.assertEqual(got, [6160, 12304, 5120, 2088, 6168, 8192, 7176, 1837171]) - - def test_mask_pair_with_constant_half_is_not_folded(self): - # Old #4480: s[4:5] is a v_cmp mask whose high half was set to 0, s[12:13] a -1 whose high half became a - # mask. rdna2spirv reads both as lane masks (s_bcnt1 collects the wave), so the execz region they are - # counted in must not be folded as lane-local; it was, and translate() asserted on the x_split inside it. - fixture = os.path.join(HERE, "fixtures", "wave64_mask_const_half.asm") - with open(fixture, encoding="ascii") as f: - lines = f.read().splitlines() - prev_emu = rdna2spirv.WAVE64_EMULATE - for threads in (64, 128): - with self.subTest(threads=threads): - rdna2spirv.WAVE64_EMULATE = True - try: - with tempfile.TemporaryDirectory() as td: - os.mkdir(os.path.join(td, "disasm")) - os.mkdir(os.path.join(td, "fssm")) - s_path = os.path.join(td, "disasm", "cs_w64_mask_const_half.s") - with open(s_path, "w", encoding="utf-8") as dst: - dst.write("; cs_w64_mask_const_half hand-written\n; mattr: +wavefrontsize64,-wavefrontsize32\n") - dst.write("\n".join(ln for ln in lines if not ln.startswith(";")) + "\n") - with open(os.path.join(td, "fssm", "cs_w64_mask_const_half.fssm"), "wb") as f: - f.write(bytes(0x138) + struct.pack("<4I", 0x8088, threads, 1, 1)) - spv = rdna2spirv.translate(s_path) - finally: - rdna2spirv.WAVE64_EMULATE = prev_emu - mem, _ = run_emulated_workgroup(spv, (threads, 1, 1), push_constants=VSHARP + [0] * 28) - for t in range(threads): - want = (8, 40) if t >= 16 else (0, 0) - self.assertEqual((mem.get(8 * t, 0), mem.get(8 * t + 4, 0)), want, f"thread {t}") - - def test_write_before_folded_scalar_load_orders_cleanly(self): - # #1587 interaction: buffer_store before a folded s_cbranch_execz containing s_load_dword must emit - # a uniform x_split BEFORE `if (%active)`, never inside the divergent branch. - insns = [ - ("s_mov_b32 s8, 0", 4), - ("s_mov_b32 s9, 0", 4), - ("v_lshlrev_b32_e32 v7, 2, v0", 4), - ("v_add_nc_u32_e32 v6, 200, v0", 4), - ("buffer_store_dword v6, v7, s[0:3], 0 offen", 8), - ("v_mov_b32_e32 v9, 0", 4), - ("v_cmp_le_u32_e64 s[6:7], 32, v0", 8), - ("s_and_saveexec_b64 s[10:11], s[6:7]", 4), - ("s_cbranch_execz 3", 4), - ("s_load_dword s14, s[8:9], 0x0", 8), # s14 dead at join; reads mem written by lane 0! - ("v_mov_b32_e32 v9, s14", 4), - ("s_or_b64 exec, exec, s[10:11]", 4), - ("v_add_nc_u32_e32 v10, 512, v7", 4), - ("buffer_store_dword v9, v10, s[0:3], 0 offen", 8), - ("s_endpgm", 4), - ] - spv, gen = _translate_encoded("cs_raw_sload_fold", insns, (64, 1, 1), emulate=True) - self.assertEqual(spv.count("OpAtomicOr"), 0) - self.assertEqual(len(gen.x_segs), 2) # write->s_load split before fold + s_load->store after - mem, _ = run_emulated_workgroup(spv, (64, 1, 1), push_constants=VSHARP + [0] * 28) - for lane in range(64): - want = 200 if lane >= 32 else 0 - self.assertEqual(mem[512 + lane * 4], want, f"lane {lane}") - - def test_nested_reused_saveexec_and_xor_if_else_folds_cleanly(self): - # Outer `if (lane >= 16)` containing TWO sequential inner `if/else` diamonds that reuse the SAME - # s[10:11] saved-EXEC pair and use LLVM's `s_xor_b64` + `s_or_saveexec_b64` if/else lowering. - insns = [ - ("v_mov_b32_e32 v4, v0", 4), - ("v_cmp_le_u32_e64 s[6:7], 16, v0", 8), # outer: lane >= 16 - ("s_and_saveexec_b64 s[8:9], s[6:7]", 4), - ("s_cbranch_execz 17", 4), # outer skip (17 dwords) - # Inner 1: if (lane >= 32) v4 += 100 else v4 += 10 using s[10:11] + s_xor_b64 + s_or_saveexec_b64 - ("v_cmp_le_u32_e64 vcc, 32, v0", 8), - ("s_and_saveexec_b64 s[10:11], vcc", 4), - ("s_xor_b64 s[10:11], exec, s[10:11]", 4), # else mask in s[10:11] - ("s_cbranch_execz 1", 4), - ("v_add_nc_u32_e32 v4, 100, v4", 4), - ("s_or_saveexec_b64 s[12:13], s[10:11]", 4), # swap to else, save then-exec - ("s_andn2_b64 exec, exec, s[12:13]", 4), # keep else lanes only - ("s_cbranch_execz 1", 4), - ("v_add_nc_u32_e32 v4, 10, v4", 4), - ("s_or_b64 exec, exec, s[12:13]", 4), # restore outer exec - # Inner 2: REUSE s[10:11] for a second inner guard: if (lane >= 48) v4 += 1000 - ("v_cmp_le_u32_e64 vcc, 48, v0", 8), - ("s_and_saveexec_b64 s[10:11], vcc", 4), - ("s_cbranch_execz 1", 4), - ("v_add_nc_u32_e32 v4, 1000, v4", 4), - ("s_or_b64 exec, exec, s[10:11]", 4), - # Outer restore - ("s_or_b64 exec, exec, s[8:9]", 4), - ("v_lshlrev_b32_e32 v9, 2, v0", 4), - ("buffer_store_dword v4, v9, s[0:3], 0 offen", 8), - ("s_endpgm", 4), - ] - spv, gen = _translate_encoded("cs_reused_nested_fold", insns, (64, 1, 1), emulate=True) - self.assertEqual(_switch_case_count(gen), 1) - self.assertEqual(spv.count("OpAtomicOr"), 0) - mem, _ = run_emulated_workgroup(spv, (64, 1, 1), push_constants=VSHARP + [0] * 28) - for lane in range(64): - want = lane - if lane >= 16: - want += 100 if lane >= 32 else 10 - if lane >= 48: - want += 1000 - self.assertEqual(mem[lane * 4], want, f"lane {lane}") - - def test_negative_live_in_pair_and_unmasked_vcc_scc_not_folded(self): - # 1) s[10:11] initialized to -1 BEFORE the region and ORed with exec inside -> live-in at run -> MUST NOT fold! - insns_live_in = [ - ("v_mov_b32_e32 v4, v0", 4), - ("s_mov_b64 s[10:11], -1", 4), - ("v_cmp_le_u32_e64 s[6:7], 32, v0", 8), - ("s_and_saveexec_b64 s[8:9], s[6:7]", 4), - ("s_cbranch_execz 3", 4), - ("s_or_b64 s[10:11], s[10:11], exec", 4), # preserves entry -1, NOT guaranteed 0! - ("s_or_b64 exec, exec, s[10:11]", 4), # widens EXEC to all-ones! - ("v_add_nc_u32_e32 v4, 5, v4", 4), - ("s_or_b64 exec, exec, s[8:9]", 4), - ("v_lshlrev_b32_e32 v9, 2, v0", 4), - ("buffer_store_dword v4, v9, s[0:3], 0 offen", 8), - ("s_endpgm", 4), - ] - spv1, _ = _translate_encoded("cs_neg_livein_zero", insns_live_in, (64, 1, 1), emulate=True) - self.assertGreaterEqual(spv1.count("OpAtomicOr"), 1) - mem1, _ = run_emulated_workgroup(spv1, (64, 1, 1), push_constants=VSHARP + [0] * 28) - for lane in range(64): - self.assertEqual(mem1[lane * 4], lane + 5, f"lane {lane}: EXEC widen must run for all lanes") - - # 2) `s_and_b64 s[10:11], vcc, s[12:13]` where vcc is not tracked by lane_masks, with internal live SCC: - # Gen.is_mask_op treats vcc as a mask op and emits scc_from_mask -> MUST NOT fold or crash! - insns_vcc_scc = [ - ("s_mov_b32 s12, 1", 4), - ("s_mov_b32 s13, 0", 4), - ("s_mov_b64 vcc, s[12:13]", 4), # vcc written as plain data, NOT in lane_masks - ("v_cmp_le_u32_e64 s[6:7], 32, v0", 8), - ("s_and_saveexec_b64 s[8:9], s[6:7]", 4), - ("s_cbranch_execz 3", 4), - ("s_and_b64 s[10:11], vcc, s[12:13]", 4), # Gen.is_mask_op(vcc) -> scc_from_mask! - ("s_cselect_b32 s14, 7, 3", 4), # reads SCC inside region (s14 dead at join) - ("v_mov_b32_e32 v4, s14", 4), - ("s_or_b64 exec, exec, s[8:9]", 4), - ("v_lshlrev_b32_e32 v9, 2, v0", 4), - ("buffer_store_dword v4, v9, s[0:3], 0 offen", 8), - ("s_endpgm", 4), - ] - spv2, _ = _translate_encoded("cs_neg_vcc_scc", insns_vcc_scc, (64, 1, 1), emulate=True) - vote_calls = spv2.count("OpFunctionCall %uint %x_pre_vote_fn") or spv2.count("OpAtomicOr") - self.assertGreaterEqual(vote_calls, 2) # branch vote + scc_from_mask vote - - def test_s_cmovk_i32_keeps_scc_live_and_blocks_execz_fold(self): - # 1) s_cmovk_i32 implicitly reads SCC: s_and_saveexec_b64 must keep its cross-half SCC vote. - insns_vote = [ - ("s_mov_b32 s14, 222", 4), - ("v_cmp_eq_u32_e64 s[10:11], 50, v0", 8), - ("s_and_saveexec_b64 s[12:13], s[10:11]", 4), - ("s_cmovk_i32 s14, 111", 4), - ("s_mov_b64 exec, -1", 4), - ("v_mov_b32_e32 v5, s14", 4), - ("v_lshlrev_b32_e32 v9, 2, v0", 4), - ("buffer_store_dword v5, v9, s[0:3], 0 offen", 8), - ("s_endpgm", 4), - ] - spv1, _ = _translate_encoded("cs_cmovk_scc_live", insns_vote, (64, 1, 1), emulate=True) - self.assertGreaterEqual(spv1.count("OpAtomicOr"), 1) - mem1, _ = run_emulated_workgroup(spv1, (64, 1, 1), push_constants=VSHARP + [0] * 28) - for lane in range(64): - self.assertEqual(mem1[lane * 4], 111, f"lane {lane}") - - # 2) Region writing SCC when s_cmovk_i32 reads SCC after join MUST NOT fold (64 & 128 threads). - insns_fold = [ - ("s_mov_b32 s14, 222", 4), - ("s_cmp_eq_u32 s14, 222", 4), - ("v_cmp_lt_u32_e64 s[6:7], 40, v0", 8), - ("s_and_saveexec_b64 s[8:9], s[6:7]", 4), - ("s_cbranch_execz 2", 4), - ("s_cmp_eq_u32 s14, 0", 4), - ("v_add_nc_u32_e32 v4, 1, v0", 4), - ("s_mov_b64 exec, -1", 4), - ("s_cmovk_i32 s14, 111", 4), - ("v_mov_b32_e32 v5, s14", 4), - ("v_lshlrev_b32_e32 v9, 2, v0", 4), - ("buffer_store_dword v5, v9, s[0:3], 0 offen", 8), - ("s_endpgm", 4), - ] - for lx in (64, 128): - spv2, _ = _translate_encoded(f"cs_cmovk_no_fold_{lx}", insns_fold, (lx, 1, 1), emulate=True) - self.assertGreaterEqual(spv2.count("OpAtomicOr"), 1) - mem2, _ = run_emulated_workgroup(spv2, (lx, 1, 1), push_constants=VSHARP + [0] * 28) - for lane in range(lx): - self.assertEqual(mem2[lane * 4], 222, f"lx={lx} lane={lane}") - - # 3) Every opcode in tools/rdna2spirv.py that emits `OpLoad %uint %scc` must satisfy reads_scc(). - src_path = os.path.join(os.path.dirname(os.path.dirname(HERE)), "tools", "rdna2spirv.py") - with open(src_path, encoding="utf-8") as f: - lines = f.readlines() - scc_ops = set() - for i, line in enumerate(lines): - if "OpLoad %uint %scc" not in line: - continue - for j in range(i, max(-1, i - 25), -1): - m_ops = re.findall(r'"(s_[a-z0-9_]+)"', lines[j]) - if m_ops and ("elif op" in lines[j] or "if op" in lines[j]): - scc_ops.update(m_ops) - break - self.assertGreaterEqual(len(scc_ops), 8) - for op in sorted(scc_ops): - self.assertTrue( - wave64_emulate_opt.reads_scc({"op": op, "args": []}), - f"{op} loads %scc in rdna2spirv.py but reads_scc() returned False", - ) - - def test_m0_implicit_read_in_v_movrel_blocks_execz_fold(self): - # Region writes m0 and post-join v_movrels_b32 reads m0 implicitly -> MUST NOT fold. - insns = [ - ("v_mov_b32_e32 v4, 10", 4), - ("v_mov_b32_e32 v5, 77", 4), - ("s_mov_b32 m0, 0", 4), - ("v_cmp_lt_u32_e64 s[6:7], 40, v0", 8), - ("s_and_saveexec_b64 s[8:9], s[6:7]", 4), - ("s_cbranch_execz 1", 4), - ("s_mov_b32 m0, 1", 4), - ("s_mov_b64 exec, -1", 4), - ("v_movrels_b32_e32 v6, v4", 4), - ("v_lshlrev_b32_e32 v9, 2, v0", 4), - ("buffer_store_dword v6, v9, s[0:3], 0 offen", 8), - ("s_endpgm", 4), - ] - spv, _ = _translate_encoded("cs_m0_vmovrel_no_fold", insns, (64, 1, 1), emulate=True) - self.assertGreaterEqual(spv.count("OpAtomicOr"), 1) - mem, _ = run_emulated_workgroup(spv, (64, 1, 1), push_constants=VSHARP + [0] * 28) - for lane in range(64): - self.assertEqual(mem[lane * 4], 77, f"lane {lane}: wave ran region so m0=1 -> v5=77 everywhere") - - def test_single_store_acyclic_fold_orders_war_and_raw(self): - # Acyclic single-store s_cbranch_execz regions fold inline (0 OpAtomicOr), while uniform pre/post - # memory ordering protects both WAR (load before folded store) and RAW (folded store before load). - insns = [ - ("v_lshlrev_b32_e32 v7, 2, v0", 4), - ("v_add_nc_u32_e32 v6, 50, v0", 4), - ("buffer_store_dword v6, v7, s[0:3], 0 offen", 8), - ("v_xor_b32_e32 v8, 32, v0", 4), - ("v_lshlrev_b32_e32 v8, 2, v8", 4), - ("buffer_load_dword v9, v8, s[0:3], 0 offen", 8), # reads partner half before overwrite - ("v_cmp_le_u32_e64 s[6:7], 32, v0", 8), - ("s_and_saveexec_b64 s[10:11], s[6:7]", 4), - ("s_cbranch_execz 3", 4), - ("v_add_nc_u32_e32 v11, 500, v9", 4), - ("buffer_store_dword v11, v7, s[0:3], 0 offen", 8), # single store -> folded with WAR split before! - ("s_or_b64 exec, exec, s[10:11]", 4), - ("buffer_load_dword v12, v8, s[0:3], 0 offen", 8), # reads partner half after folded store -> RAW split! - ("v_add_nc_u32_e32 v13, 512, v7", 4), - ("buffer_store_dword v12, v13, s[0:3], 0 offen", 8), - ("s_endpgm", 4), - ] - for size in ((64, 1, 1), (128, 1, 1)): - with self.subTest(size=size): - spv, _ = _translate_encoded("cs_single_store_fold", insns, size, emulate=True) - self.assertEqual(spv.count("OpAtomicOr"), 0) - for rev in (False, True): - mem, _ = run_emulated_workgroup(spv, size, push_constants=VSHARP + [0] * 28, reverse_order=rev) - for tid in range(size[0]): - partner = tid ^ 32 - # lanes < 32 kept 50 + tid; lanes >= 32 overwrote their slot with 500 + (50 + (tid ^ 32)) - if partner >= 32: - want = 500 + 50 + (partner ^ 32) - else: - want = 50 + partner - self.assertEqual(mem[512 + tid * 4], want, f"tid {tid} rev={rev}") - - -class StructuredEmulationTests(unittest.TestCase): - """Structured --wave64-emulate (`inline_all` for <=64 threads, `structured_hybrid` for >64 threads).""" - - def test_single_wave_inline_all_zero_switch_and_loop_carried_war(self): - # 64-thread and partial 40-thread shaders with live-out scalars, loop-carried store->load->store WAR/RAW, - # and v_readfirstlane emit 0 OpSwitch cases and 0 x_spills while staying bit-exact. - insns = [ - ("s_mov_b64 exec, -1", 4), - ("s_mov_b32 s16, 10", 4), - ("v_mov_b32_e32 v4, v0", 4), - ("v_lshlrev_b32_e32 v10, 2, v0", 4), - ("buffer_store_dword v4, v10, s[0:3], 0 offen", 8), - # Un-foldable live-out scalar s_cbranch_execz - ("v_cmp_le_u32_e64 s[6:7], 20, v0", 8), - ("s_and_saveexec_b64 s[8:9], s[6:7]", 4), - ("s_cbranch_execz 2", 4), - ("s_add_u32 s16, s16, 5", 4), - ("v_add_nc_u32_e32 v4, s16, v4", 4), - ("s_or_b64 exec, exec, s[8:9]", 4), - ("v_add_nc_u32_e32 v4, s16, v4", 4), - # Loop with store -> cross-half load -> next iteration store (tests back-edge dirty_in!) - ("s_mov_b32 s20, 3", 4), - ("buffer_store_dword v4, v10, s[0:3], 0 offen", 8), - ("v_xor_b32_e32 v12, 32, v0", 4), - ("v_lshlrev_b32_e32 v12, 2, v12", 4), - ("buffer_load_dword v13, v12, s[0:3], 0 offen", 8), - ("v_add_nc_u32_e32 v4, v4, v13", 4), - ("s_sub_u32 s20, s20, 1", 4), - ("s_cmp_gt_u32 s20, 0", 4), - ("s_cbranch_scc1 -10", 4), - ("buffer_store_dword v4, v10, s[0:3], 0 offen offset:512", 8), - ("s_endpgm", 4), - ] - for threads in (64, 40): - with self.subTest(threads=threads): - spv, gen = _translate_encoded(f"cs_inline_{threads}", insns, (threads, 1, 1), emulate=True) - self.assertEqual(gen.control_flow, "emulated wave64 structured") - self.assertEqual(gen.emulate_plan["mode"], "inline_all") - self.assertNotIn("OpSwitch", spv) - self.assertEqual(len(gen.x_spills), 0) - self.assertNotIn("OpGroupNonUniform", spv) - for rev in (False, True): - mem, _ = run_emulated_workgroup(spv, (threads, 1, 1), push_constants=VSHARP + [0] * 28, reverse_order=rev) - # Reference simulation - arr = [0] * 64 - for l in range(threads): - arr[l] = l - v4 = [l + (15 if l >= 20 else 0) + 15 for l in range(threads)] - for _ in range(3): - for l in range(threads): - arr[l] = v4[l] - nxt = [v4[l] + arr[l ^ 32] for l in range(threads)] - v4 = nxt - for l in range(threads): - self.assertEqual(mem[512 + l * 4], v4[l] & 0xFFFFFFFF, f"lane {l} rev={rev}") - - def test_mask_flbit_is_synchronized_in_a_branch_taken_by_only_one_wave(self): - # One wave takes the SCC branch body. Its bit scan still needs a workgroup exchange. - for op, ext_inst in (("s_flbit_i32_b32", "FindUMsb"), ("s_flbit_i32", "FindSMsb")): - with self.subTest(op=op): - insns = [ - ("v_and_b32_e32 v1, 63, v0", 4), - ("v_cmp_eq_u32_e32 vcc, 3, v1", 4), - ("v_lshlrev_b32_e32 v6, 2, v0", 4), - ("v_readfirstlane_b32 s20, v0", 4), - ("s_cmp_eq_u32 s20, 0", 4), - ("s_cbranch_scc0 4", 4), - (f"{op} s9, vcc_lo", 4), - ("v_mov_b32_e32 v4, s9", 4), - ("buffer_store_dword v4, v6, s[0:3], 0 offen", 8), - ("s_mov_b64 exec, -1", 4), - ("s_endpgm", 4), - ] - spv, _ = _translate_encoded("cs_flbit_in_scc_branch", insns, (128, 1, 1), emulate=True) - self.assertIn(ext_inst, spv) - if op == "s_flbit_i32_b32": - mem, _ = run_emulated_workgroup(spv, (128, 1, 1), push_constants=VSHARP + [0] * 28) - self.assertEqual(mem, {lane * 4: 28 for lane in range(64)}) - - def test_multiwave_structured_hybrid_zero_switch_and_local_mini_scheduler(self): - # 128 threads (2 waves): top-level spine + sync-free guard (live-out scalar) + wave-divergent - # mini-scheduler (Wave 0 runs v_readlane + store + cross-half load while Wave 1 skips it) + top s_barrier. - insns = [ - ("s_mov_b64 exec, -1", 4), - ("s_mov_b32 s16, 7", 4), - ("v_mov_b32_e32 v4, v0", 4), - ("v_lshlrev_b32_e32 v10, 2, v0", 4), - ("buffer_store_dword v4, v10, s[0:3], 0 offen", 8), - # 1) Sync-free guard with live-out scalar (0 OpSwitch!) - ("v_cmp_le_u32_e64 s[6:7], 96, v0", 8), # Wave 0 skips, Wave 1 takes - ("s_and_saveexec_b64 s[8:9], s[6:7]", 4), - ("s_cbranch_execz 2", 4), - ("s_add_u32 s16, s16, 30", 4), - ("v_add_nc_u32_e32 v4, s16, v4", 4), - ("s_or_b64 exec, exec, s[8:9]", 4), - ("v_add_nc_u32_e32 v4, s16, v4", 4), - # 2) Wave-divergent guard with v_readlane + store + load -> isolated local mini_scheduler! - ("v_readfirstlane_b32 s19, v0", 4), - ("s_cmp_lt_u32 s19, 64", 4), - ("s_cbranch_scc0 9", 4), # Wave 0 enters, Wave 1 skips! - ("v_readlane_b32 s18, v4, 37", 4), - ("v_add_nc_u32_e32 v4, s18, v4", 4), - ("buffer_store_dword v4, v10, s[0:3], 0 offen", 8), - ("v_xor_b32_e32 v12, 32, v0", 4), - ("v_lshlrev_b32_e32 v12, 2, v12", 4), - ("buffer_load_dword v13, v12, s[0:3], 0 offen", 8), - ("v_add_nc_u32_e32 v4, v4, v13", 4), - # 3) Top-level inline s_barrier + cross-wave LDS exchange! - ("ds_write_b32 v10, v4", 8), - ("s_barrier", 4), - ("v_xor_b32_e32 v12, 64, v0", 4), - ("v_lshlrev_b32_e32 v12, 2, v12", 4), - ("ds_read_b32 v13, v12", 8), - ("v_add_nc_u32_e32 v4, v4, v13", 4), - ("buffer_store_dword v4, v10, s[0:3], 0 offen offset:1024", 8), - ("s_endpgm", 4), - ] - spv, gen = _translate_encoded("cs_hybrid_128", insns, (128, 1, 1), emulate=True, rsrc2=0x20088) - self.assertEqual(gen.control_flow, "emulated wave64 structured") - self.assertEqual(gen.emulate_plan["mode"], "structured_hybrid") - kinds = [st[0] for st in gen.emulate_plan["steps"]] - self.assertIn("inline_sync_free", kinds) - self.assertIn("mini_scheduler", kinds) - # Only the 1 isolated mini_scheduler has an OpSwitch (with <= 3 segments, NOT the whole shader!). - switches = re.findall(r"OpSwitch\s+%\w+\s+%\w+([^\n]*)", spv) - self.assertEqual(len(switches), 1) - self.assertLessEqual(len(switches[0].split()) // 2, 3) - - # Direct ISA-derived reference values for all 128 lanes: - # Wave 0 (0..63): skips guard 1 (s16=7, v4 = l + 7); enters guard 2 (s18 = 37 + 7 = 44, - # v4 = l + 51, then adds partner (l^32) + 51 -> v4_w0(l) = l + (l^32) + 102). - # Wave 1 (64..127): enters guard 1 (s16=37; l in 64..95 -> l + 37; l in 96..127 -> l + 74); skips guard 2. - # After s_barrier: each lane adds v4 of (l ^ 64). - def isa_v4_before_sbar(l): - if l < 64: - return l + (l ^ 32) + 102 - return l + (74 if l >= 96 else 37) - - orig_plan = wave64_emulate_opt.plan_structured_emulation - wave64_emulate_opt.plan_structured_emulation = lambda *a, **kw: None - try: - spv_base, _ = _translate_encoded("cs_hybrid_128_base", insns, (128, 1, 1), emulate=True, rsrc2=0x20088) - finally: - wave64_emulate_opt.plan_structured_emulation = orig_plan - mem_base, _ = run_emulated_workgroup(spv_base, (128, 1, 1), push_constants=VSHARP + [0] * 28) - for rev in (False, True): - mem_new, _ = run_emulated_workgroup(spv, (128, 1, 1), push_constants=VSHARP + [0] * 28, reverse_order=rev) - self.assertEqual(mem_new, mem_base) - for l in range(128): - want = isa_v4_before_sbar(l) + isa_v4_before_sbar(l ^ 64) - self.assertEqual(mem_new[1024 + l * 4], want, f"lane {l} rev={rev}") - - def test_multiwave_divergent_sbarrier_falls_back_to_rounds(self): - # Wave 0 hits s_barrier in one arm while Wave 1 hits s_barrier in another -> MUST keep global rounds. - insns = [ - ("s_mov_b64 exec, -1", 4), - ("v_lshlrev_b32_e32 v2, 2, v0", 4), - ("ds_write_b32 v2, v0", 8), - ("v_readfirstlane_b32 s5, v0", 4), - ("s_cmp_lt_u32 s5, 64", 4), - ("s_cbranch_scc0 8", 4), - ("s_barrier", 4), - ("v_xor_b32_e32 v3, 64, v0", 4), - ("v_lshlrev_b32_e32 v3, 2, v3", 4), - ("ds_read_b32 v4, v3", 8), - ("buffer_store_dword v4, v2, s[0:3], 0 offen", 8), - ("s_endpgm", 4), - ("s_barrier", 4), - ("s_endpgm", 4), - ] - spv, gen = _translate_encoded("cs_div_sbar_w64", insns, (128, 1, 1), emulate=True, rsrc2=0x20088) - self.assertEqual(gen.control_flow, "emulated wave64 rounds") - self.assertIsNone(gen.emulate_plan) - mem, _ = run_emulated_workgroup(spv, (128, 1, 1), push_constants=VSHARP + [0] * 28) - for lane in range(64): - self.assertEqual(mem[lane * 4], lane + 64, f"lane {lane}") - - def test_monotone_dirty_transfer_no_phantom_clear_after_x_round(self): - # Regression: an x_round (v_readlane_b32) clears g.x_dirty in codegen before a subsequent - # buffer_store + ds_read. A non-monotone transfer_superblock that cleared on phantom conflicts - # with an earlier block's ('lds','w') wiped ('mem','w') from dirty_in[blk3] and dropped the - # OpControlBarrier required before blk3's cross-half buffer_load. - insns = [ - ("s_or_b64 exec, exec, exec", 4), - ("s_mov_b32 s4, 0", 4), - ("s_cmp_eq_u32 s4, 0", 4), - ("v_lshlrev_b32_e32 v10, 2, v0", 4), - ("v_add_nc_u32_e32 v1, 7, v0", 4), - ("ds_write_b32 v10, v1", 8), - ("s_cbranch_scc0 1", 4), - ("s_nop 0", 4), - ("v_readlane_b32 s5, v0, 33", 4), - ("buffer_store_dword v1, v10, s[0:3], 0 offen", 8), - ("ds_read_b32 v2, v10", 8), - ("s_branch 0", 4), - # Read the opposite half of the wave (lane ^ 32) from global memory: requires a barrier! - ("v_xor_b32_e32 v11, 32, v0", 4), - ("v_lshlrev_b32_e32 v11, 2, v11", 4), - ("buffer_load_dword v3, v11, s[0:3], 0 offen", 8), - ("v_add_nc_u32_e32 v3, v3, v2", 4), - ("buffer_store_dword v3, v10, s[0:3], 0 offen offset:512", 8), - ("s_endpgm", 4), - ] - for lx, expected_mode in ((64, "inline_all"), (128, "structured_hybrid")): - spv, gen = _translate_encoded(f"cs_monotone_dirty_{lx}", insns, (lx, 1, 1), emulate=True, rsrc2=0x20088) - self.assertEqual(gen.control_flow, "emulated wave64 structured") - self.assertEqual(gen.emulate_plan["mode"], expected_mode) - self.assertIn(("mem", "w"), gen.emulate_plan["dirty_in"][3]) - lines = spv.splitlines() - i2 = next(i for i, l in enumerate(lines) if l.strip().startswith("%blk2 = OpLabel")) - i3 = next(i for i, l in enumerate(lines) if l.strip().startswith("%blk3 = OpLabel")) - blk2_to_end = lines[i2:] - store_idx = next(i for i, l in enumerate(blk2_to_end) - if "OpStore" in l and "OpConvertUToPtr" in "\n".join(blk2_to_end[max(0, i - 15):i])) - i3_rel = i3 - i2 - load_idx = next(i for i, l in enumerate(blk2_to_end[i3_rel:], i3_rel) - if "OpLoad %uint" in l and "OpConvertUToPtr" in "\n".join(blk2_to_end[max(0, i - 15):i])) - self.assertTrue(any("OpControlBarrier" in l for l in blk2_to_end[store_idx:load_idx]), - f"missing OpControlBarrier between blk2 buffer_store and blk3 buffer_load ({expected_mode})") - for rev in (False, True): - mem, _ = run_emulated_workgroup(spv, (lx, 1, 1), push_constants=VSHARP + [0] * 28, reverse_order=rev) - for lane in range(lx): - partner = lane ^ 32 - self.assertEqual(mem[512 + lane * 4], (partner + 7) + (lane + 7), f"lx={lx} lane={lane} rev={rev}") - - def test_known_pc_guard_unwrap_and_x_pre_helper_functions(self): - # 1) Sequential un-foldable diamonds (live-out scalar s16) in inline_all (64 threads) and inside a loop: - # _unwrap_known_pc_guards must unwrap every post-dominating spine join block (no `if (%pc == join)` - # guard around join blocks), and x_round must outline pre-barrier setup into %x_pre_vote_fn / %x_pre_data_fn. - insns = [ - ("s_mov_b64 exec, -1", 4), - ("s_mov_b32 s16, 1", 4), - ("v_mov_b32_e32 v4, v0", 4), - ("v_lshlrev_b32_e32 v10, 2, v0", 4), - # Diamond 1 (live-out s16 -> not folded by find_local_exec_folds; joins at Spine 1) - ("v_cmp_le_u32_e64 s[6:7], 16, v0", 8), - ("s_and_saveexec_b64 s[8:9], s[6:7]", 4), - ("s_cbranch_execz 2", 4), - ("s_add_u32 s16, s16, 10", 4), - ("v_add_nc_u32_e32 v4, s16, v4", 4), - # Spine 1 (block 2): must be unwrapped at top level in inline_all! - ("s_or_b64 exec, exec, s[8:9]", 4), - ("v_readfirstlane_b32 s17, v4", 4), - ("v_readlane_b32 s18, v4, 0", 4), - # Diamond 2 (live-out s16 -> joins at Spine 2) - ("v_cmp_le_u32_e64 s[6:7], 48, v0", 8), - ("s_and_saveexec_b64 s[8:9], s[6:7]", 4), - ("s_cbranch_execz 2", 4), - ("s_add_u32 s16, s16, 20", 4), - ("v_add_nc_u32_e32 v4, s16, v4", 4), - # Spine 2 (block 4): must ALSO be unwrapped at top level in inline_all! - ("s_or_b64 exec, exec, s[8:9]", 4), - ("v_add_nc_u32_e32 v4, s16, v4", 4), - ("v_add_nc_u32_e32 v4, s17, v4", 4), - ("v_add_nc_u32_e32 v4, s18, v4", 4), - ("buffer_store_dword v4, v10, s[0:3], 0 offen", 8), - ("s_endpgm", 4), - ] - spv, gen = _translate_encoded("cs_unwrap_spine", insns, (64, 1, 1), emulate=True) - self.assertEqual(gen.emulate_plan["mode"], "inline_all") - top_kinds = [(it[0], it[1]) for it in gen.emulate_plan["tree"]] - # Blocks 0, 2, 4 are all direct top-level ("block", b) items; only blocks 1 and 3 are guarded! - self.assertEqual(top_kinds, [("block", 0), ("guard", 1), ("block", 2), ("guard", 3), ("block", 4)]) - self.assertIn("%x_pre_vote_fn = OpFunction", spv) - self.assertIn("%x_pre_both_fn = OpFunction", spv) - self.assertIn("%x_pre_data_fn = OpFunction", spv) - self.assertGreaterEqual(spv.count("OpFunctionCall %uint %x_pre_vote_fn"), 2) - self.assertEqual(spv.count("OpFunctionCall %uint %x_pre_both_fn"), 1) - self.assertEqual(spv.count("OpFunctionCall %uint %x_pre_data_fn"), 1) - # Verify binary SPIR-V assembly with tools/spirv_asm.py - import spirv_asm - binary = spirv_asm.assemble(spv, target_env="vulkan1.2") - self.assertEqual(binary[:4], struct.pack("= 16 else l; s17 = s18 = v4[0] = 0 - v4 = l + (11 if l >= 16 else 0) - # After diamond 2: s16 = 31; v4 += 31 if l >= 48; then spine 2 adds s16 (31) + s17 (0) + s18 (0) - if l >= 48: - v4 += 31 - v4 += 31 - self.assertEqual(mem[l * 4], v4, f"lane {l}") - - # 2) Guard-spine coalescing after an early-exit branch (0 -> [1 (end), 2]) and inside a header-exit loop: - # cfg_structure.structure hoists spine guards into the enclosing list where skip_pc holds the early-exit - # target. _unwrap_known_pc_guards must coalesce and unwrap all hoisted post-dominating spine guards. - import cfg_structure - succ_early = [[1, 2], []] # block 0 -> early exit 1 or main body 2 - cur = 2 - for _ in range(10): - succ_early.append([cur + 1, cur + 2]) - succ_early.append([cur + 2]) - cur += 2 - succ_early.append([]) - raw_tree = cfg_structure.structure(succ_early) - out_pcs = {b: (frozenset(s) if s else frozenset({-1})) for b, s in enumerate(succ_early)} - unwrapped_tree = wave64_emulate_opt._unwrap_known_pc_guards(raw_tree, out_pcs, 0) - - def count_guards(t): - c = 0 - st = [t] - while st: - for item in st.pop(): - if item[0] == "guard": - c += 1 - st.append(item[2]) - elif item[0] == "loop": - st.append(item[2]) - return c - - # Raw tree has 22 guards (guard 1, guard 2, plus 10 arm guards and 10 hoisted spine guards); - # coalesced unwrap removes all 10 hoisted spine guards -> 12 guards. - self.assertEqual(count_guards(raw_tree), 22) - self.assertEqual(count_guards(unwrapped_tree), 12) - - def test_slist_and_src_scc_liveness_and_scalar_rw(self): - sgpr = lambda r, n=1: {"k": "sgpr", "r": r, "n": n} - vgpr = lambda r, n=1: {"k": "vgpr", "r": r, "n": n} - spec = lambda t: {"k": "special", "t": t} - slist = lambda *regs: {"k": "slist", "r": list(regs), "n": len(regs)} - - # reads_scc & scc_live_outs: explicit `src_scc` operand keeps the producer's SCC live. - prod = {"op": "s_and_saveexec_b64", "args": [sgpr(8, 2), spec("vcc")], "mods": ()} - cons = {"op": "s_mov_b32", "args": [sgpr(10), spec("src_scc")], "mods": ()} - end = {"op": "s_endpgm", "args": [], "mods": ()} - self.assertTrue(wave64_emulate_opt.reads_scc(cons)) - self.assertIn(id(prod), wave64_emulate_opt.scc_live_outs([[prod, cons, end]], [[]])) - rd_scc, _, _ = wave64_emulate_opt._scalar_rw(cons) - self.assertEqual(rd_scc, 1 << wave64_emulate_opt._BIT_SCC) - - # _scalar_rw on sgpr-pair slist copy/load. - load_pair = {"op": "s_buffer_load_dwordx2", "args": [slist(12, 13), slist(4, 5, 6, 7), {"k": "imm", "v": 0}], "mods": ()} - rd, mw, mk = wave64_emulate_opt._scalar_rw(load_pair) - self.assertEqual(rd, (1 << 4) | (1 << 5) | (1 << 6) | (1 << 7)) - self.assertEqual(mw, (1 << 12) | (1 << 13)) - self.assertEqual(mk, (1 << 12) | (1 << 13)) - - # Partial vcc_lo in an slist: may_w includes VCC, must_kill kills s105 only (vcc_hi is preserved). - load_half = {"op": "s_buffer_load_dwordx2", "args": [slist(105, "vcc_lo"), sgpr(0, 4), {"k": "imm", "v": 0}], "mods": ()} - rd, mw, mk = wave64_emulate_opt._scalar_rw(load_half) - self.assertEqual(rd, 0xF) - self.assertEqual(mw, (1 << 105) | (1 << wave64_emulate_opt._BIT_VCC)) - self.assertEqual(mk, 1 << 105) - - # Full [vcc_lo, vcc_hi] slist overwrites both halves -> must_kill includes VCC. - load_vcc = {"op": "s_buffer_load_dwordx4", "args": [slist(104, 105, "vcc_lo", "vcc_hi"), sgpr(0, 4), {"k": "imm", "v": 0}], "mods": ()} - rd, mw, mk = wave64_emulate_opt._scalar_rw(load_vcc) - self.assertEqual(mw, (1 << 104) | (1 << 105) | (1 << wave64_emulate_opt._BIT_VCC)) - self.assertEqual(mk, (1 << 104) | (1 << 105) | (1 << wave64_emulate_opt._BIT_VCC)) - - # VOP3b carry-out second destination as an slist. - add_co = {"op": "v_add_co_u32_e64", "args": [vgpr(0), slist(4, 5), vgpr(1), vgpr(2)], "mods": ()} - rd, mw, mk = wave64_emulate_opt._scalar_rw(add_co) - self.assertEqual(rd, 0) - self.assertEqual(mw, (1 << 4) | (1 << 5)) - self.assertEqual(mk, (1 << 4) | (1 << 5)) - - def test_slist_lane_mask_and_barrier_classification(self): - sgpr = lambda r, n=1: {"k": "sgpr", "r": r, "n": n} - slist = lambda *regs: {"k": "slist", "r": list(regs), "n": len(regs)} - - pair_45 = slist(4, 5) - pair_89 = slist(8, 9) - vcc_pair = slist("vcc_lo", "vcc_hi") - - bcnt = {"op": "s_bcnt1_i32_b64", "args": [sgpr(0), pair_45], "mods": ()} - lm_45 = {id(bcnt): {4: "mask", 5: "mask"}} - self.assertTrue(wave64_emulate_opt._holds_lane_mask(bcnt, pair_45, lm_45[id(bcnt)])) - self.assertFalse(wave64_emulate_opt._holds_lane_mask(bcnt, pair_89, lm_45[id(bcnt)])) - # One mask word and one constant word (absent from the map) is still a mask pair (old #4480). - self.assertTrue(wave64_emulate_opt._holds_lane_mask(bcnt, sgpr(4, 2), {4: "mask_lo"})) - self.assertTrue(wave64_emulate_opt._holds_lane_mask(bcnt, sgpr(4, 2), {5: "mask_hi"})) - self.assertFalse(wave64_emulate_opt._holds_lane_mask(bcnt, sgpr(4, 2), {6: "mask_lo"})) - self.assertFalse(wave64_emulate_opt._holds_lane_mask(bcnt, sgpr(5), {4: "mask_lo"})) - self.assertTrue(wave64_emulate_opt._is_mask_op(bcnt, vcc_pair, {})) - self.assertTrue(wave64_emulate_opt._insn_may_barrier(bcnt, lm_45, set())) - clean, _, _, _, _ = wave64_emulate_opt._classify_block_body([bcnt], lm_45, set(), frozenset()) - self.assertFalse(clean) - - # Live-SCC mask vote with [vcc_lo, vcc_hi] destination must be treated as a barrier / non-foldable. - and_vcc = {"op": "s_and_b64", "args": [vcc_pair, sgpr(6, 2), sgpr(8, 2)], "mods": ()} - self.assertTrue(wave64_emulate_opt._insn_may_barrier(and_vcc, {}, {id(and_vcc)})) - clean, _, _, _, _ = wave64_emulate_opt._classify_block_body([and_vcc], {}, {id(and_vcc)}, frozenset()) - self.assertFalse(clean) - - # _is_uniform_scc_safe rejects 32-bit logic with live SCC reading a masked slist. - and_mask32 = {"op": "s_and_b32", "args": [sgpr(8), pair_45, sgpr(6)], "mods": ()} - self.assertFalse(wave64_emulate_opt._is_uniform_scc_safe([[and_mask32]], {id(and_mask32): {4: "mask"}}, {id(and_mask32)})) - - def test_slist_live_out_scalar_and_src_scc_end_to_end(self): - # 1) Live-out scalar written via FSPX slist `[s105,vcc_lo]` inside s_cbranch_execz must NOT fold. - insns_live = [ - ("v_mov_b32_e32 v10, 42", 4), - ("v_mov_b32_e32 v11, 0", 4), - ("buffer_store_dword v10, v11, s[0:3], 0 offen", 8), - ("s_mov_b32 s105, 0", 4), - ("s_mov_b32 exec_lo, 0", 4), - ("s_mov_b32 exec_hi, 0xff", 4), # lanes 32..39 active; lanes 0..31 inactive - ("s_cbranch_execz 2", 4), # skip 2 dwords (8-byte SMEM load) - ("s_buffer_load_dwordx2 [s105,vcc_lo], s[0:3], 0", 8), - ("s_mov_b64 exec, -1", 4), - ("v_mov_b32_e32 v5, s105", 4), - ("v_lshlrev_b32_e32 v6, 2, v0", 4), - ("v_add_nc_u32_e32 v6, 256, v6", 4), - ("buffer_store_dword v5, v6, s[0:3], 0 offen", 8), - ("s_endpgm", 4), - ] - spv, _ = _translate_encoded("cs_slist_live_scalar", insns_live, (64, 1, 1), emulate=True) - self.assertGreaterEqual(spv.count("OpAtomicOr"), 1) - mem, _ = run_emulated_workgroup(spv, (64, 1, 1), push_constants=VSHARP + [0] * 28) - for lane in range(64): - self.assertEqual(mem[256 + lane * 4], 42, f"lane {lane}: stale s105 after slist load in s_cbranch_execz") - - # 2) Explicit `src_scc` read after s_and_saveexec_b64 must keep SCC live (vote across all 64 lanes). - insns_scc = [ - ("v_cmp_le_u32_e64 s[6:7], 32, v0", 8), # only lanes 32..63 active -> wave SCC = 1 - ("s_and_saveexec_b64 s[8:9], s[6:7]", 4), - ("s_mov_b32 s10, src_scc", 4), - ("s_or_b64 exec, exec, s[8:9]", 4), - ("v_mov_b32_e32 v5, s10", 4), - ("v_lshlrev_b32_e32 v6, 2, v0", 4), - ("buffer_store_dword v5, v6, s[0:3], 0 offen", 8), - ("s_endpgm", 4), - ] - spv, _ = _translate_encoded("cs_src_scc_live", insns_scc, (64, 1, 1), emulate=True) - self.assertGreaterEqual(spv.count("OpAtomicOr"), 1) - mem, _ = run_emulated_workgroup(spv, (64, 1, 1), push_constants=VSHARP + [0] * 28) - for lane in range(64): - self.assertEqual(mem[lane * 4], 1, f"lane {lane}: src_scc lost wave vote after s_and_saveexec_b64") - - def test_bounded_opcode_caches_and_superblock_dirty_transfer(self): - # 1) Bounded caches must stay within _OP_CACHE_MAX even with > _OP_CACHE_MAX synthetic opcodes. - limit = wave64_emulate_opt._OP_CACHE_MAX - wave64_emulate_opt._BASE_OP_CACHE.clear() - wave64_emulate_opt._OP_META_CACHE.clear() - for i in range(limit + 32): - op = f"v_synth_op_{i}_e32" - self.assertEqual(wave64_emulate_opt.base_op(op), f"v_synth_op_{i}") - meta = wave64_emulate_opt._get_op_meta(op) - self.assertEqual(meta[0], f"v_synth_op_{i}") - self.assertLessEqual(len(wave64_emulate_opt._BASE_OP_CACHE), limit) - self.assertLessEqual(len(wave64_emulate_opt._OP_META_CACHE), limit) - - # 2) Precomputed superblock dirty transfer: s_barrier clears earlier dirty state while a - # subsequent folded region's mem_reads still propagates to the successor block. - sgpr = lambda r, n=1: {"k": "sgpr", "r": r, "n": n} - vgpr = lambda r, n=1: {"k": "vgpr", "r": r, "n": n} - spec = lambda t: {"k": "special", "t": t} - imm = lambda v: {"k": "imm", "v": v} - ins_se = {"op": "s_and_saveexec_b64", "args": [sgpr(8, 2), spec("vcc")], "mods": ()} - blocks = [ - [ - {"op": "ds_write_b32", "args": [vgpr(0), vgpr(1)], "mods": ()}, - {"op": "s_barrier", "args": [], "mods": ()}, - ins_se, - {"op": "s_cbranch_execz", "args": [imm(2)], "mods": ()}, - ], - [ - {"op": "buffer_load_dword", "args": [vgpr(2), vgpr(0), sgpr(0, 4), imm(0)], "mods": ()}, - ], - [ - {"op": "s_or_b64", "args": [spec("exec"), spec("exec"), sgpr(8, 2)], "mods": ()}, - {"op": "s_cmp_eq_u32", "args": [sgpr(4), imm(0)], "mods": ()}, - {"op": "s_cbranch_scc0", "args": [imm(1)], "mods": ()}, - ], - [ - {"op": "buffer_store_dword", "args": [vgpr(2), vgpr(0), sgpr(0, 4), imm(0)], "mods": ()}, - {"op": "s_endpgm", "args": [], "mods": ()}, - ], - [ - {"op": "s_endpgm", "args": [], "mods": ()}, - ], - ] - raw_edges = [[2, 1], [2], [4, 3], [], []] - succ = [[2, 1], [2], [4, 3], [], []] - lm = {id(ins_se): {"vcc": True}} - scc_live = wave64_emulate_opt.scc_live_outs(blocks, succ) - folds, fold_chain, absorbed = wave64_emulate_opt.find_local_exec_folds(blocks, raw_edges, succ, lm, scc_live) - self.assertIn(0, folds) - self.assertEqual(fold_chain.get(0), 2) - plan = wave64_emulate_opt.plan_structured_emulation( - blocks, raw_edges, succ, folds, fold_chain, absorbed, lm, scc_live, 64 - ) - self.assertIsNotNone(plan) - self.assertEqual(plan["mode"], "inline_all") - # s_barrier cleared ("lds", "w"), and folded block 1 added ("mem", "r") after it. - self.assertEqual(plan["dirty_in"][3], frozenset({("mem", "r")})) - self.assertEqual(plan["dirty_in"][4], frozenset({("mem", "r")})) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_wave64_halves.py b/tests/semantic/test_wave64_halves.py deleted file mode 100644 index 83cb798c5..000000000 --- a/tests/semantic/test_wave64_halves.py +++ /dev/null @@ -1,1342 +0,0 @@ -"""SHADER-10: wave64 vertex/pixel shaders on 32-wide subgroups. Tier classification and partition invariance. - -tools/wave64_halves.py decides from the code whether a wave64 VS/PS/GS gives the same results when its wave is cut -into two 32-lane halves (the criterion of docs/design.md, "Wave64 graphics: partition invariance"). Two kinds of -check, both on hand-written listings (no llvm-mc, GPU or game data): - - * Classification: each program is translated, and the tier in its metadata (wave64_graphics) and the reasons - are asserted. The programs are the idioms of the research note (skip regions, quad masks, waterfall loops, - wave-aggregated atomics, readfirstlane/readlane, lane counts, lane ids, ...), including the near misses that - must be tier C. - * Execution: vertex shaders that use integer arithmetic only run on the strict wave interpreter - (spirv_wave_interp.py) as one wave of 64 lanes and as two waves of 32 lanes, with vertex index v for global lane - v (so a lane's data does not depend on how the wave is cut). Tier A and B programs must export the same words - both ways and the words the header derives; tier C programs must differ in the words the test names, which - shows the detector is right to refuse them. - -The GPU twin of the execution half is runtime/test/shaders/w64_graphics.py (pixel shaders, one subgroup size forced -to 64 and to 32 on the same GPU). -""" -import os -import sys -import unittest - -HERE = os.path.dirname(os.path.abspath(__file__)) -sys.path.insert(0, HERE) -import support # noqa: E402,F401 (sets the tools path) -from support import translate_lines, translate_listing # noqa: E402 -import rdna2spirv # noqa: E402 -import spirv_wave_interp as wi # noqa: E402 - -LITERAL_OPS = ("exp", "buffer_", "global_", "ds_", "image_") -VOP3_ONLY = ("v_mbcnt_lo_u32_b32", "v_mbcnt_hi_u32_b32", "v_readlane_b32", "v_writelane_b32", "v_lshl_add_u32", - "v_cmp_", "v_cndmask_b32_e64", "v_add_nc_u32_e64") - - -def size(text): - """Byte size of an instruction for the fake encoding the translator's branch offsets are placed with.""" - op = text.split()[0] - if op.startswith(LITERAL_OPS) or op.endswith("_e64") or op in VOP3_ONLY[:5] or "0x" in text: - return 8 - if op.startswith("v_cmp") and not op.endswith("_e32") and "vcc" not in text: - return 8 - return 4 - - -def listing(name, lines): - out = f"; {name} synthetic\n" - for text in lines: - out += f"\t{text} ; encoding: [{','.join(['0x00'] * size(text))}]\n" - return out.encode() - - -def meta_of(name, lines): - """(tier, reasons, idioms) of a translated wave64 program, from the metadata the translator writes.""" - asm = translate_listing(name, listing(name, lines)) - g = rdna2spirv.translate.last_gen - w = g.w64g - return (w["tier"], w["reasons"], w["idioms"]) if w else (None, [], []), asm - - -PRO = ["s_mov_b64 s[10:11], exec"] # the program is wave64 (a 64-bit op on EXEC) -LANE_ID = ["v_mbcnt_lo_u32_b32 v10, -1, 0", "v_mbcnt_hi_u32_b32 v10, -1, v10"] # the lane id, 0..63 in the wave -EPI_VS = ["v_mov_b32_e32 v5, 0", "exp pos0 v5, v5, v5, v5 done", "exp param0 v6, v7, v5, v5", "s_endpgm"] -EPI_PS = ["exp mrt0 v6, v7, v5, v5 done vm", "s_endpgm"] - - -def vs(body, prologue=PRO): - return prologue + ["v_mov_b32_e32 v6, 0", "v_mov_b32_e32 v7, 0"] + body + EPI_VS - - -def ps(body): - return PRO + ["v_mov_b32_e32 v6, 0", "v_mov_b32_e32 v7, 0", "v_mov_b32_e32 v5, 0"] + body + EPI_PS[:-1] + \ - ["s_endpgm"] - - -# ---- execution of vertex shaders: 64 lanes against two halves of 32 -------------------------------------------- -def run_cut(asm, wave, push=None): - """Outputs of every lane of a 64-lane program run as 64/wave waves of `wave` lanes (vertex index = global lane).""" - words = [] - for half in range(64 // wave): - res = wi.run_wave(asm, wave=wave, push_constants=push, - builtins={"VertexIndex": lambda lane, base=half * wave: base + lane, - "InstanceIndex": lambda lane: 0, "BaseVertex": lambda lane: 0, - "BaseInstance": lambda lane: 0}) - words += [o and tuple(sorted(o.items())) for o in res["outputs"]] - return words - - -def out_param(words, k=0): - """Per lane, the words of param `k`'s output as a tuple (None for a lane that wrote nothing).""" - result = [] - for w in words: - d = dict(w) if w else {} - result.append(next((v for name, v in d.items() if name.endswith(f"param{k}")), None)) - return result - - -# ---- the early exit of a pixel kill ------------------------------------------------------------------------------ -KILL = ["s_mov_b64 s[20:21], exec", "v_cmp_gt_u32_e32 vcc, 40, v0", "s_andn2_b64 s[20:21], s[20:21], vcc"] -RUN_WQM = ["s_wqm_b64 s[22:23], s[20:21]", "s_and_b64 exec, exec, s[22:23]"] -EXIT_PS = ["s_mov_b64 exec, s[20:21]", "exp null off, off, off, off done vm", "s_endpgm"] -EXIT_VS = ["s_mov_b64 exec, s[20:21]", "exp pos0 v5, v5, v5, v5 done", "s_endpgm"] - - -def kill(head, run, exit_, stage="ps", vote="s_cbranch_scc0"): - """head, a branch to the exit when the live mask is empty, the run side and the epilogue, then the exit.""" - epi = EPI_PS if stage == "ps" else EPI_VS - tail = run + epi - hop = sum(size(t) for t in tail) // 4 - return PRO + ["v_mov_b32_e32 v6, 0", "v_mov_b32_e32 v7, 0", "v_mov_b32_e32 v5, 0"] + head + \ - [f"{vote} {hop}"] + tail + exit_ - - -class Classification(unittest.TestCase): - def tier(self, name, lines, tier, reasons=None, idioms=None, contains=None): - (t, r, i), _ = meta_of(name, lines) - self.assertEqual(t, tier, f"{name}: tier {t}, reasons {r}, idioms {i}") - if reasons is not None: - self.assertEqual(sorted(r), sorted(reasons), name) - if contains is not None: - self.assertTrue(set(contains) <= set(r), f"{name}: reasons {r} lack {contains}") - if idioms is not None: - self.assertEqual(sorted(i), sorted(idioms), name) - - # -- tier A - def test_a_skip_wqm_quad(self): - self.tier("ps_a_skip", ps([ - "v_and_b32_e32 v4, 3, v0", "v_cmp_eq_u32_e32 vcc, 1, v4", - "s_and_saveexec_b64 s[12:13], vcc", "s_cbranch_execz 1", "v_mul_u32_u24_e32 v6, 7, v0", - "s_or_b64 exec, exec, s[12:13]", "v_cmp_eq_u32_e32 vcc, 1, v4", "s_wqm_b64 s[14:15], vcc", - "v_cndmask_b32_e64 v7, 0, 1, s[14:15]"]), "A", [], []) - - def test_a_vccz_narrowed(self): - self.tier("ps_a_vccz", ps([ - "v_cmp_eq_u32_e32 vcc, 2, v0", "s_cbranch_vccz 3", "s_and_saveexec_b64 s[16:17], vcc", - "v_add_nc_u32_e32 v6, 9, v6", "s_or_b64 exec, exec, s[16:17]"]), "A", [], []) - - def test_a_loop_execnz_no_scalar_state(self): - self.tier("ps_a_loop", ps([ - "v_and_b32_e32 v4, 3, v0", "v_add_nc_u32_e32 v10, 1, v4", "v_mov_b32_e32 v9, 0", - "v_add_nc_u32_e32 v9, 1, v9", "v_cmp_lt_u32_e32 vcc, v9, v10", "s_and_b64 exec, exec, vcc", - "s_cbranch_execnz -4", "s_mov_b64 exec, s[10:11]", "v_mov_b32_e32 v6, v9"]), "A", [], []) - - def test_a_bpermute_swizzle_in_half(self): - self.tier("ps_a_bperm", ps(["v_lshlrev_b32_e32 v4, 2, v0", "ds_bpermute_b32 v6, v4, v0"]), "A", [], []) - - def test_a_bpermute_lane_id_address(self): - # the lane id is 0..63 in the wave and 0..31 in a half: equal modulo 32 lanes, which is all a wave64 - # ds_bpermute uses (address bits 2..6, per half), so xor/and/or/add on it and a shift by 2 stay exact - self.tier("ps_a_bperm_id", ps([*LANE_ID, "v_xor_b32_e32 v11, 1, v10", "v_lshlrev_b32_e32 v11, 2, v11", - "ds_bpermute_b32 v6, v11, v0", "v_and_b32_e32 v12, -4, v10", - "v_or_b32_e32 v12, 2, v12", "v_lshl_add_u32 v12, v12, 2, 0", - "ds_bpermute_b32 v7, v12, v0", "s_waitcnt lgkmcnt(0)"]), "A", [], []) - - def test_a_permute_lane_id_address(self): - self.tier("ps_a_perm_id", ps([*LANE_ID, "v_add_nc_u32_e32 v11, 5, v10", "v_lshlrev_b32_e32 v11, 2, v11", - "ds_permute_b32 v6, v11, v0", "s_waitcnt lgkmcnt(0)"]), "A", [], []) - - # -- tier B - def test_b_waterfall(self): - self.tier("ps_b_wf", ps([ - "v_and_b32_e32 v4, 7, v0", "v_readfirstlane_b32 s20, v4", "v_cmp_eq_u32_e32 vcc, s20, v4", - "s_and_saveexec_b64 s[12:13], vcc", "s_mul_i32 s21, s20, 17", "v_add_nc_u32_e32 v6, s21, v0", - "s_xor_b64 exec, exec, s[12:13]", "s_cbranch_execnz -7", "s_mov_b64 exec, s[10:11]"]), "B", [], - ["waterfall"]) - - def test_b_readfirstlane_of_uniform(self): - self.tier("ps_b_rfl", ps(["v_mov_b32_e32 v5, s4", "v_readfirstlane_b32 s20, v5", - "v_add_nc_u32_e32 v6, s20, v0"]), "B", [], ["readfirstlane-uniform"]) - - def test_b_readlane_of_uniform_any_lane(self): - self.tier("ps_b_rl", ps(["v_mov_b32_e32 v5, s4", "v_readlane_b32 s20, v5, 40", - "v_add_nc_u32_e32 v6, s20, v0"]), "B", [], ["readlane-uniform"]) - - def test_b_aggregated_atomic(self): - self.tier("ps_b_atomic", ps([ - "v_and_b32_e32 v4, 3, v0", "v_cmp_eq_u32_e32 vcc, 1, v4", "s_and_saveexec_b64 s[12:13], vcc", - "s_bcnt1_i32_b64 s6, exec", "v_mbcnt_lo_u32_b32 v10, exec_lo, 0", "v_mbcnt_hi_u32_b32 v10, exec_hi, v10", - "v_cmp_eq_u32_e32 vcc, 0, v10", "s_and_saveexec_b64 s[14:15], vcc", "v_mov_b32_e32 v11, s6", - "v_mov_b32_e32 v12, 0", "buffer_atomic_add v11, v12, s[0:3], 0 offen glc", "s_or_b64 exec, exec, s[14:15]", - "v_readfirstlane_b32 s7, v11", "v_add_nc_u32_e32 v13, s7, v10", "v_lshlrev_b32_e32 v13, 2, v13", - "buffer_store_dword v0, v13, s[0:3], 0 offen offset:256", "s_mov_b64 exec, s[10:11]"]), "B", [], - ["aggregated-atomic", "elected-lane"]) - - def test_c_aggregated_atomic_at_a_per_lane_address(self): - # the elected lane runs the atomic at its own address; each half elects its own lane, so an address made from - # a per-lane value (here the pixel's y, untainted) bumps another counter there and the slots collide - base = _load_ps_w64_lines("ps_w64_b_ballot_atomic") - per_lane = [] - for line in base: - per_lane += (["v_lshrrev_b32_e32 v12, 2, v3", "v_lshlrev_b32_e32 v12, 2, v12"] - if line == "v_mov_b32_e32 v12, 0" else [line]) - self.assertNotEqual(per_lane, base) - push = [0, 0, 65536, 0x30000000] - for name, lines, tier, reasons in (("ps_b_atomic_uniform_addr", base, "B", []), - ("ps_c_atomic_per_lane_addr", per_lane, "C", ["elected-lane"])): - with self.subTest(name): - (t, r, _), asm = meta_of(name, lines) - self.assertEqual((t, r), (tier, reasons)) - whole, halves = {0: 0}, {0: 0} - _run_ps_cut(asm, 64, push=push, memory=whole) - _run_ps_cut(asm, 32, push=push, memory=halves) - self.assertEqual(whole == halves, tier == "B") - - def test_b_spill_and_reload_in_half(self): - self.tier("ps_b_spill", ps(["v_writelane_b32 v20, s4, 3", "v_readlane_b32 s21, v20, 3", - "v_add_nc_u32_e32 v6, s21, v0"]), "B", [], ["lane-spill"]) - - def test_b_spill_and_reload_upper_half_lane_40(self): - # Pure scalar spill into lanes 32..63 (v20 is never read as a vector operand): lowered to a parked scalar - # slot so SGPR spills past lane 31 are exact on 32-wide subgroups (tier B). - self.tier("ps_b_spill_hi", ps([ - "v_writelane_b32 v20, s4, 40", "v_writelane_b32 v20, s5, 63", - "v_readlane_b32 s21, v20, 40", "v_readlane_b32 s22, v20, 63", - "s_add_u32 s23, s21, s22", "v_add_nc_u32_e32 v6, s23, v0"]), "B", [], ["lane-spill"]) - - def test_c_spill_in_divergent_vote_branch_is_stale_scalar(self): - # Spilling to lane 40 behind a wave-wide vote and reading outside must stay tier C (stale-scalar). - # v_writelane_b32 is an 8-byte VOP3 instruction (2 dwords). - self.tier("ps_c_spill_stale", ps([ - "v_writelane_b32 v20, s4, 40", "v_cmp_eq_u32_e32 vcc, 0, v0", "s_cbranch_vccz 2", - "v_writelane_b32 v20, s5, 40", "v_readlane_b32 s21, v20, 40", - "v_mov_b32_e32 v6, s21"]), "C", contains=["stale-scalar"]) - - def test_c_spill_of_tainted_count_stays_tier_c(self): - # Spilling a tainted scalar (lane-count) into lane 40 and reloading must still report lane-count. - self.tier("ps_c_spill_cnt", ps([ - "v_cmp_eq_u32_e32 vcc, 1, v0", "s_bcnt1_i32_b64 s6, vcc", - "v_writelane_b32 v20, s6, 40", "v_readlane_b32 s21, v20, 40", - "v_mov_b32_e32 v6, s21"]), "C", ["lane-count"]) - - def test_b_readfirstlane_uniform_inside_narrowed_exec(self): - # v5 written from a scalar inside a narrowed EXEC block is uniform across all active lanes, - # so v_readfirstlane_b32 inside that block is exact (tier B). - self.tier("ps_b_rfl_narrow", ps([ - "v_and_b32_e32 v4, 3, v0", "v_cmp_eq_u32_e32 vcc, 1, v4", - "s_and_saveexec_b64 s[12:13], vcc", "v_mov_b32_e32 v5, s4", - "v_readfirstlane_b32 s20, v5", "v_add_nc_u32_e32 v6, s20, v0", - "s_or_b64 exec, exec, s[12:13]"]), "B", [], ["readfirstlane-uniform"]) - - def test_c_readfirstlane_after_exec_restore_not_uniform(self): - # Writing v5 from a scalar under narrowed EXEC and reading after EXEC restore is NOT uniform (tier C). - self.tier("ps_c_rfl_after_restore", ps([ - "v_mov_b32_e32 v5, v0", "v_and_b32_e32 v4, 3, v0", "v_cmp_eq_u32_e32 vcc, 1, v4", - "s_and_saveexec_b64 s[12:13], vcc", "v_mov_b32_e32 v5, s4", - "s_or_b64 exec, exec, s[12:13]", "v_readfirstlane_b32 s20, v5", - "v_mov_b32_e32 v6, s20"]), "C") - - def test_c_readfirstlane_active_uniform_scalar_escapes_after_restore(self): - # Reading v5 inside narrowed EXEC produces lane-0's old value in a half where EXEC == 0; - # using that scalar after EXEC restore escapes the mask and must stay tier C (PR #2469 review). - self.tier("ps_c_rfl_escape", ps([ - "v_mov_b32_e32 v5, 7", "v_cmp_eq_u32_e32 vcc, 33, v0", - "s_and_saveexec_b64 s[12:13], vcc", "v_mov_b32_e32 v5, 50", - "v_readfirstlane_b32 s20, v5", "s_mov_b64 exec, s[10:11]", - "v_mov_b32_e32 v6, s20"]), "C", contains=["cross-lane"]) - - def test_c_nonlinear_count_scaling_refused(self): - # Count as shift distance (1 << count) and 24-bit truncating multiply (v_mul_u32_u24) are nonlinear - # and must NOT qualify for wave-aggregated atomics (PR #2469 review). - self.tier("ps_c_atomic_shift_dist", ps([ - "v_and_b32_e32 v4, 3, v0", "v_cmp_eq_u32_e32 vcc, 1, v4", "s_and_saveexec_b64 s[12:13], vcc", - "s_bcnt1_i32_b64 s6, exec", "s_lshl_b32 s6, 1, s6", - "v_mbcnt_lo_u32_b32 v10, exec_lo, 0", "v_mbcnt_hi_u32_b32 v10, exec_hi, v10", - "v_cmp_eq_u32_e32 vcc, 0, v10", "s_and_saveexec_b64 s[14:15], vcc", "v_mov_b32_e32 v11, s6", - "v_mov_b32_e32 v12, 0", "buffer_atomic_add v11, v12, s[0:3], 0 offen glc", "s_or_b64 exec, exec, s[14:15]", - "v_readfirstlane_b32 s7, v11", "v_add_nc_u32_e32 v13, s7, v10", "v_lshlrev_b32_e32 v13, 2, v13", - "buffer_store_dword v0, v13, s[0:3], 0 offen offset:256", "s_mov_b64 exec, s[10:11]"]), "C", - contains=["lane-count"]) - self.tier("ps_c_atomic_mul_u24", ps([ - "v_and_b32_e32 v4, 3, v0", "v_cmp_eq_u32_e32 vcc, 1, v4", "s_and_saveexec_b64 s[12:13], vcc", - "s_bcnt1_i32_b64 s6, exec", "s_mul_i32 s6, s6, 0x100000", - "v_mbcnt_lo_u32_b32 v10, exec_lo, 0", "v_mbcnt_hi_u32_b32 v10, exec_hi, v10", - "v_cmp_eq_u32_e32 vcc, 0, v10", "s_and_saveexec_b64 s[14:15], vcc", "v_mov_b32_e32 v15, s6", - "v_mul_u32_u24_e32 v11, 1, v15", - "v_mov_b32_e32 v12, 0", "buffer_atomic_add v11, v12, s[0:3], 0 offen glc", "s_or_b64 exec, exec, s[14:15]", - "v_readfirstlane_b32 s7, v11", "v_add_nc_u32_e32 v13, s7, v10", "v_lshlrev_b32_e32 v13, 2, v13", - "buffer_store_dword v0, v13, s[0:3], 0 offen offset:256", "s_mov_b64 exec, s[10:11]"]), "C", - contains=["lane-count"]) - - def test_b_scaled_aggregated_atomic_and_global_atomic_add(self): - # Stride-scaled s_bcnt1 (s_lshl_b32 by 2 = 4 bytes/lane) in buffer_atomic_add and global_atomic_add. - self.tier("ps_b_atomic_scaled", ps([ - "v_and_b32_e32 v4, 3, v0", "v_cmp_eq_u32_e32 vcc, 1, v4", "s_and_saveexec_b64 s[12:13], vcc", - "s_bcnt1_i32_b64 s6, exec", "s_lshl_b32 s6, s6, 2", - "v_mbcnt_lo_u32_b32 v10, exec_lo, 0", "v_mbcnt_hi_u32_b32 v10, exec_hi, v10", - "v_cmp_eq_u32_e32 vcc, 0, v10", "s_and_saveexec_b64 s[14:15], vcc", "v_mov_b32_e32 v11, s6", - "v_mov_b32_e32 v12, 0", "buffer_atomic_add v11, v12, s[0:3], 0 offen glc", "s_or_b64 exec, exec, s[14:15]", - "v_readfirstlane_b32 s7, v11", "v_lshlrev_b32_e32 v13, 2, v10", "v_add_nc_u32_e32 v13, s7, v13", - "buffer_store_dword v0, v13, s[0:3], 0 offen offset:256", "s_mov_b64 exec, s[10:11]"]), "B", [], - ["aggregated-atomic", "elected-lane"]) - # global_atomic_add with glc has operand order (vdst, vaddr, vdata, saddr). - self.tier("ps_b_global_atomic", ps([ - "v_and_b32_e32 v4, 3, v0", "v_cmp_eq_u32_e32 vcc, 1, v4", "s_and_saveexec_b64 s[12:13], vcc", - "s_bcnt1_i32_b64 s6, exec", "v_mbcnt_lo_u32_b32 v10, exec_lo, 0", "v_mbcnt_hi_u32_b32 v10, exec_hi, v10", - "v_cmp_eq_u32_e32 vcc, 0, v10", "s_and_saveexec_b64 s[14:15], vcc", "v_mov_b32_e32 v11, s6", - "v_mov_b32_e32 v12, 0", "global_atomic_add v14, v12, v11, s[4:5] glc", "s_or_b64 exec, exec, s[14:15]", - "v_readfirstlane_b32 s7, v14", "v_add_nc_u32_e32 v13, s7, v10", "v_lshlrev_b32_e32 v13, 2, v13", - "global_store_dword v13, v0, s[4:5]", "s_mov_b64 exec, s[10:11]"]), "B", [], - ["aggregated-atomic", "elected-lane"]) - - # -- tier C: each near miss of the idioms above - def test_c_lane_count_exported(self): - self.tier("ps_c_cnt", ps(["v_cmp_eq_u32_e32 vcc, 1, v0", "s_bcnt1_i32_b64 s6, vcc", "v_mov_b32_e32 v6, s6"]), - "C", ["lane-count"]) - - def test_c_rank_exported(self): - self.tier("ps_c_rank", ps(["v_mbcnt_lo_u32_b32 v6, exec_lo, 0", "v_mbcnt_hi_u32_b32 v6, exec_hi, v6"]), "C", - ["lane-rank"]) - - def test_c_lane_id_exported(self): - self.tier("ps_c_id", ps(["v_mbcnt_lo_u32_b32 v6, -1, 0", "v_mbcnt_hi_u32_b32 v6, -1, v6"]), "C", ["lane-id"]) - - def test_c_bpermute_lane_id_address_near_misses(self): - # a shift by 1: address bit 7 is not reached, lane bit 5 lands in bit 6, which the permute uses - self.tier("ps_c_bperm_shl1", ps([*LANE_ID, "v_lshlrev_b32_e32 v11, 1, v10", "ds_bpermute_b32 v6, v11, v0", - "s_waitcnt lgkmcnt(0)"]), "C", ["lane-id"]) - # the low count alone is 32 for every upper-half lane of the wave - self.tier("ps_c_bperm_lo", ps(["v_mbcnt_lo_u32_b32 v10, -1, 0", "v_lshlrev_b32_e32 v11, 2, v10", - "ds_bpermute_b32 v6, v11, v0", "s_waitcnt lgkmcnt(0)"]), "C", ["lane-id"]) - # a right shift moves lane bit 5 down into the bits the permute uses - self.tier("ps_c_bperm_shr", ps([*LANE_ID, "v_lshrrev_b32_e32 v11, 1, v10", "v_lshlrev_b32_e32 v11, 3, v11", - "ds_bpermute_b32 v6, v11, v0", "s_waitcnt lgkmcnt(0)"]), "C", ["lane-id"]) - # combined with a lane mask: the mask is not the same in the wave and in a half - self.tier("ps_c_bperm_mask", ps([*LANE_ID, "v_and_b32_e32 v11, s10, v10", "v_lshlrev_b32_e32 v11, 2, v11", - "ds_bpermute_b32 v6, v11, v0", "s_waitcnt lgkmcnt(0)"]), "C") - # SDWA selects and integer clamp change the value: a byte of id << 7, a saturating id - 32 - self.tier("ps_c_bperm_sdwa", ps([*LANE_ID, "v_lshlrev_b32_e32 v11, 7, v10", - "v_mov_b32_sdwa v12, v11 dst_sel:DWORD dst_unused:UNUSED_PAD src0_sel:BYTE_1", - "v_lshlrev_b32_e32 v12, 2, v12", "ds_bpermute_b32 v6, v12, v0", - "s_waitcnt lgkmcnt(0)"]), "C", ["lane-id"]) - self.tier("ps_c_bperm_clamp", ps([*LANE_ID, "v_add_nc_u32_e64 v11, v10, -32 clamp", - "v_lshlrev_b32_e32 v11, 2, v11", "ds_bpermute_b32 v6, v11, v0", - "s_waitcnt lgkmcnt(0)"]), "C", ["lane-id"]) - # the lane id still taints the data it permutes, and the lane id itself - self.tier("ps_c_bperm_data", ps([*LANE_ID, "v_lshlrev_b32_e32 v11, 2, v10", "ds_bpermute_b32 v6, v11, v10", - "s_waitcnt lgkmcnt(0)"]), "C", ["lane-id"]) - - def test_c_first_lane_index(self): - self.tier("ps_c_ff1", ps(["v_cmp_eq_u32_e32 vcc, 1, v0", "s_ff1_i32_b64 s6, vcc", "v_mov_b32_e32 v6, s6"]), - "C", ["first-lane"]) - - def test_c_readlane_of_varying(self): - self.tier("ps_c_rl", ps(["v_readlane_b32 s6, v0, 40", "v_mov_b32_e32 v6, s6"]), "C", ["cross-lane"]) - self.tier("ps_c_rl7", ps(["v_readlane_b32 s6, v0, 7", "v_mov_b32_e32 v6, s6"]), "C", ["cross-lane"]) - - def test_c_writelane_of_varying_lane(self): - self.tier("ps_c_wl", ps(["v_writelane_b32 v6, s4, 40"]), "C", ["cross-lane"]) - - def test_c_readfirstlane_of_varying_exported(self): - self.tier("ps_c_rfl", ps(["v_readfirstlane_b32 s6, v0", "v_mov_b32_e32 v6, s6"]), "C") - - def test_c_waterfall_scalar_escapes(self): - self.tier("ps_c_wf_out", ps([ - "v_and_b32_e32 v4, 7, v0", "v_readfirstlane_b32 s20, v4", "v_cmp_eq_u32_e32 vcc, s20, v4", - "s_and_saveexec_b64 s[12:13], vcc", "v_add_nc_u32_e32 v6, s20, v0", - "s_xor_b64 exec, exec, s[12:13]", "s_cbranch_execnz -5", "s_mov_b64 exec, s[10:11]", - "v_mov_b32_e32 v7, s20"]), "C") - - def test_c_waterfall_trip_count(self): - self.tier("ps_c_wf_count", ps([ - "s_mov_b32 s22, 0", "v_and_b32_e32 v4, 7, v0", "v_readfirstlane_b32 s20, v4", - "v_cmp_eq_u32_e32 vcc, s20, v4", "s_and_saveexec_b64 s[12:13], vcc", "s_add_u32 s22, s22, 1", - "s_xor_b64 exec, exec, s[12:13]", "s_cbranch_execnz -6", "s_mov_b64 exec, s[10:11]", - "v_mov_b32_e32 v7, s22"]), "C", ["stale-scalar"]) - - def test_c_vote_defines_scalar_read_later(self): - self.tier("ps_c_stale", ps([ - "v_cmp_eq_u32_e32 vcc, 0, v0", "s_mov_b32 s5, 7", "s_cbranch_vccz 1", "s_add_u32 s5, s5, 1", - "v_mov_b32_e32 v6, s5"]), "C") - - def test_c_exec_skip_defines_scalar_read_later(self): - self.tier("ps_c_stale_exec", ps([ - "v_cmp_eq_u32_e32 vcc, 0, v0", "s_and_saveexec_b64 s[12:13], vcc", "s_mov_b32 s5, 7", - "s_cbranch_execz 1", "s_add_u32 s5, s5, 1", "s_or_b64 exec, exec, s[12:13]", "v_mov_b32_e32 v6, s5"]), - "C", ["stale-scalar"]) - - def test_slist_taint_and_stale_tracking(self): - # LLVM VCCTuple scalar lists (slist, e.g. [s104,s105,vcc_lo,vcc_hi]) must propagate taint and stale defs/uses. - self.tier("ps_a_slist_clean", ps([ - "buffer_store_dword v0, v1, [s104,s105,vcc_lo,vcc_hi], 0 offen"]), "A", [], []) - self.tier("ps_c_slist_src_taint", ps([ - "v_cmp_eq_u32_e32 vcc, 1, v0", "s_bcnt1_i32_b64 s104, vcc", - "buffer_store_dword v0, v1, [s104,s105,vcc_lo,vcc_hi], 0 offen"]), "C", ["lane-count"]) - self.tier("ps_c_slist_dst_taint", ps([ - "v_cmp_eq_u32_e32 vcc, 1, v0", "s_bcnt1_i32_b64 s4, vcc", - "s_load_dwordx4 [s104,s105,vcc_lo,vcc_hi], s[4:5], 0", "s_waitcnt lgkmcnt(0)", - "v_mov_b32_e32 v6, s104"]), "C", ["lane-count"]) - self.tier("ps_c_slist_stale_def", ps([ - "v_cmp_eq_u32_e32 vcc, 0, v0", "s_and_saveexec_b64 s[12:13], vcc", "s_mov_b32 s104, 7", - "s_cbranch_execz 1", "s_load_dwordx4 [s104,s105,vcc_lo,vcc_hi], s[0:1], 0", - "s_or_b64 exec, exec, s[12:13]", "v_mov_b32_e32 v6, s104"]), "C", ["stale-scalar"]) - self.tier("ps_c_slist_stale_use", ps([ - "v_cmp_eq_u32_e32 vcc, 0, v0", "s_and_saveexec_b64 s[12:13], vcc", "s_mov_b32 s104, 7", - "s_cbranch_execz 1", "s_add_u32 s104, s104, 1", "s_or_b64 exec, exec, s[12:13]", - "buffer_store_dword v0, v1, [s104,s105,vcc_lo,vcc_hi], 0 offen"]), "C", ["stale-scalar"]) - # VOP3b scalar carry-out destination written as an slist must be classified as a destination, not a source. - import wave64_halves - ins = {"op": "v_add_co_u32_e64", "args": [ - {"k": "vgpr", "r": 6, "n": 1}, - {"k": "slist", "r": [105, "vcc_lo"], "n": 2}, - {"k": "vgpr", "r": 0, "n": 1}, - {"k": "vgpr", "r": 1, "n": 1}, - ], "mods": []} - dests, srcs, _, _ = wave64_halves.operands(ins) - self.assertEqual([wave64_halves._regs(d) for d in dests], [[("v", 6)], [("s", 105), "vcc"]]) - self.assertEqual([wave64_halves._regs(s) for s in srcs], [[("v", 0)], [("v", 1)]]) - - def test_c_branch_on_count(self): - self.tier("ps_c_brcnt", ps([ - "v_cmp_eq_u32_e32 vcc, 1, v0", "s_bcnt1_i32_b64 s6, vcc", "s_cmp_eq_u32 s6, 5", "s_cbranch_scc1 1", - "v_mov_b32_e32 v6, 1"]), "C") - - def test_c_vccz_without_narrowing(self): - self.tier("ps_c_vccz", ps(["v_cmp_eq_u32_e32 vcc, 2, v0", "s_cbranch_vccz 1", "v_add_nc_u32_e32 v6, 9, v6"]), - "C", ["unsafe-vote-branch"]) - - def test_c_half_of_a_mask(self): - self.tier("ps_c_half", ps(["s_mov_b32 exec_hi, 0"]), "C", ["mask-half"]) - self.tier("ps_c_half2", ps(["v_cmp_eq_u32_e32 vcc, 1, v0", "s_mov_b32 s6, vcc_hi", "v_mov_b32_e32 v6, s6"]), - "C", contains=["mask-half"]) - - def test_c_vcmpx_on_the_lane_id(self): - # v_cmpx writes EXEC like v_cmp + s_and_b64 exec: on 32-wide waves lanes 32..63 see ids 0..31 and stay on. - for form in ("e32", "e64"): - self.tier(f"vs_c_vcmpx_{form}", vs([*LANE_ID, "v_mov_b32_e32 v6, 1", f"v_cmpx_gt_u32_{form} 32, v10", - "v_mov_b32_e32 v6, 2"]), "C", ["tainted-exec"]) - - def test_a_vcmpx_on_a_uniform_value(self): - self.tier("vs_a_vcmpx_uniform", vs(["s_mov_b32 s20, 5", "v_mov_b32_e32 v6, 1", "v_cmpx_gt_u32_e32 s20, 3", - "v_mov_b32_e32 v6, 2"]), "A", []) - - def test_c_mask_stored_as_data(self): - self.tier("ps_c_maskdata", ps(["v_cmp_eq_u32_e32 vcc, 1, v0", "s_mov_b64 s[6:7], vcc", - "v_mov_b32_e32 v6, s6"]), "C") - - def test_c_elected_lane_side_effect_not_a_count(self): - self.tier("ps_c_elect", ps([ - "v_and_b32_e32 v4, 3, v0", "v_cmp_eq_u32_e32 vcc, 1, v4", "s_and_saveexec_b64 s[12:13], vcc", - "v_mbcnt_lo_u32_b32 v10, exec_lo, 0", "v_mbcnt_hi_u32_b32 v10, exec_hi, v10", - "v_cmp_eq_u32_e32 vcc, 0, v10", "s_and_saveexec_b64 s[14:15], vcc", "v_mov_b32_e32 v11, 1", - "v_mov_b32_e32 v12, 0", "buffer_atomic_add v11, v12, s[0:3], 0 offen glc", - "s_or_b64 exec, exec, s[14:15]", "s_mov_b64 exec, s[10:11]"]), "C", ["elected-side-effect"]) - - def test_c_rank_into_export_even_with_base(self): - self.tier("ps_c_slot_exported", ps([ - "v_mbcnt_lo_u32_b32 v10, exec_lo, 0", "v_mbcnt_hi_u32_b32 v10, exec_hi, v10", "v_add_nc_u32_e32 v6, 1, v10"]), - "C", ["lane-rank"]) - - # -- non-wave64 and other stages are not analysed - def test_wave32_is_not_analysed(self): - asm = translate_listing("ps_w32", listing("ps_w32", ["v_mov_b32_e32 v6, 0", "exp mrt0 v6, v6, v6, v6 done vm", - "s_endpgm"])) - self.assertIsNone(rdna2spirv.translate.last_gen.w64g) - self.assertNotEqual(asm, "") - - -class Execution(unittest.TestCase): - """Vertex shaders: the words of lane k with all 64 lanes in one wave and with the lanes cut into two waves.""" - - def run_both(self, name, lines, push=None): - (tier, reasons, idioms), asm = meta_of(name, lines) - whole, halves = run_cut(asm, 64, push), run_cut(asm, 32, push) - return tier, out_param(whole), out_param(halves) - - def test_a_vertex_invariant(self): - tier, whole, halves = self.run_both("vs_a_skip", vs([ - "v_and_b32_e32 v4, 7, v0", "v_cmp_eq_u32_e32 vcc, 1, v4", "v_mov_b32_e32 v6, 0x3e8", - "s_and_saveexec_b64 s[12:13], vcc", "s_cbranch_execz 1", "v_mul_u32_u24_e32 v6, 7, v0", - "s_or_b64 exec, exec, s[12:13]", "v_cmp_eq_u32_e32 vcc, 1, v4", "s_wqm_b64 s[14:15], vcc", - "v_cndmask_b32_e64 v7, 0, 1, s[14:15]"])) - self.assertEqual(tier, "A") - self.assertEqual(whole, halves) - # lanes with k % 8 == 1 run the skip region; whole-quad mode lights the 4 consecutive lanes around them - want = [(7 * k if k % 8 == 1 else 1000, int(k % 8 < 4)) for k in range(64)] - self.assertEqual([w[:2] for w in whole], want) - - def test_b_waterfall_invariant(self): - tier, whole, halves = self.run_both("vs_b_wf", vs([ - "v_and_b32_e32 v4, 7, v0", "v_readfirstlane_b32 s20, v4", "v_cmp_eq_u32_e32 vcc, s20, v4", - "s_and_saveexec_b64 s[12:13], vcc", "s_mul_i32 s21, s20, 17", "v_add_nc_u32_e32 v6, s21, v0", - "s_xor_b64 exec, exec, s[12:13]", "s_cbranch_execnz -7", "s_mov_b64 exec, s[10:11]"])) - self.assertEqual(tier, "B") - self.assertEqual(whole, halves) - self.assertEqual([w[0] for w in whole], [17 * (k & 7) + k for k in range(64)]) - - def test_a_bpermute_lane_id_address_invariant(self): - tier, whole, halves = self.run_both("vs_a_bperm_id", vs([ - *LANE_ID, "v_xor_b32_e32 v11, 1, v10", "v_lshlrev_b32_e32 v11, 2, v11", "ds_bpermute_b32 v6, v11, v0", - "s_waitcnt lgkmcnt(0)"])) - self.assertEqual(tier, "A") - self.assertEqual(whole, halves) - self.assertEqual([w[0] for w in whole], [k ^ 1 for k in range(64)]) - - def test_a_permlane_swizzle_invariant(self): - # vertex k is lane k of the wave (and lane k % 32 of its half): every read stays in the lane's half - tier, whole, halves = self.run_both("vs_a_perm", vs([ - "s_mov_b32 s20, 0x67452301", "s_mov_b32 s21, 0xefcdab89", "v_permlane16_b32 v6, v0, s20, s21", - "s_mov_b32 s22, 0x76543210", "s_mov_b32 s23, 0xfedcba98", "v_permlanex16_b32 v7, v0, s22, s23"])) - self.assertEqual(tier, "A") - self.assertEqual(whole, halves) - self.assertEqual([w[:2] for w in whole], [(k ^ 1, k ^ 16) for k in range(64)]) - tier, whole, halves = self.run_both("vs_a_swz", vs([ - "ds_swizzle_b32 v6, v0 offset:swizzle(QUAD_PERM,3,2,1,0)", "ds_swizzle_b32 v7, v0 offset:swizzle(SWAP,16)", - "s_waitcnt lgkmcnt(0)"])) - self.assertEqual(tier, "A") - self.assertEqual(whole, halves) - self.assertEqual([w[:2] for w in whole], [(k ^ 3, k ^ 16) for k in range(64)]) - - def test_c_bpermute_shift_by_one_differs(self): - # the negative control of the rule: lane bit 5 reaches an address bit the permute uses - tier, whole, halves = self.run_both("vs_c_bperm_shl1", vs([ - *LANE_ID, "v_lshlrev_b32_e32 v11, 1, v10", "ds_bpermute_b32 v6, v11, v0", "s_waitcnt lgkmcnt(0)"])) - self.assertEqual(tier, "C") - self.assertNotEqual([w[0] for w in whole], [w[0] for w in halves]) - - def test_b_readlane_of_uniform_value_at_lane_40(self): - # lane 40 does not exist in a 32-lane wave: without the rewrite the shuffle reads a lane that is not running - tier, whole, halves = self.run_both("vs_b_rl", vs([ - "v_mov_b32_e32 v5, s4", "v_readlane_b32 s20, v5, 40", "v_add_nc_u32_e32 v6, s20, v0"]), - push=[0, 0, 0, 0, 77]) - self.assertEqual(tier, "B") - self.assertEqual(whole, halves) - self.assertEqual([w[0] for w in whole], [77 + k for k in range(64)]) - - def test_b_readfirstlane_of_uniform(self): - tier, whole, halves = self.run_both("vs_b_rfl", vs([ - "v_mov_b32_e32 v5, s4", "v_readfirstlane_b32 s20, v5", "v_add_nc_u32_e32 v6, s20, v0"]), - push=[0, 0, 0, 0, 9]) - self.assertEqual(tier, "B") - self.assertEqual(whole, halves) - self.assertEqual([w[0] for w in whole], [9 + k for k in range(64)]) - - def test_b_spill_upper_half_lane_40_and_63_invariant(self): - # Lanes 40 and 63 do not exist on a 32-lane subgroup: parked scalar slots keep 64-lane and 2x32-lane exact. - tier, whole, halves = self.run_both("vs_b_spill_hi", vs([ - "v_writelane_b32 v20, s4, 40", "v_writelane_b32 v20, s5, 63", - "v_readlane_b32 s21, v20, 40", "v_readlane_b32 s22, v20, 63", - "s_add_u32 s23, s21, s22", "v_add_nc_u32_e32 v6, s23, v0"]), - push=[0, 0, 0, 0, 100, 23]) - self.assertEqual(tier, "B") - self.assertEqual(whole, halves) - self.assertEqual([w[0] for w in whole], [123 + k for k in range(64)]) - - def test_b_readfirstlane_uniform_under_narrowed_exec_invariant(self): - # Also test with only lane 33 active (lower half has empty EXEC): using s20 ONLY inside the - # narrowed block keeps 64-lane and 2x32-lane outputs identical. - tier, whole, halves = self.run_both("vs_b_rfl_narrow", vs([ - "v_mov_b32_e32 v5, 7", "v_cmp_eq_u32_e32 vcc, 33, v0", - "s_and_saveexec_b64 s[12:13], vcc", "v_mov_b32_e32 v5, s4", - "v_readfirstlane_b32 s20, v5", "v_add_nc_u32_e32 v6, s20, v0", - "s_mov_b64 exec, s[10:11]"]), - push=[0, 0, 0, 0, 50]) - self.assertEqual(tier, "B") - self.assertEqual(whole, halves) - self.assertEqual([w[0] for w in whole], [83 if k == 33 else 0 for k in range(64)]) - - def test_c_readfirstlane_escape_after_restore_differs(self): - # Same narrowed-EXEC readfirstlane, but s20 escapes past EXEC restore: lower half gets lane-0 - # fallback (7) while upper half gets 50, so it MUST classify C. - tier, whole, halves = self.run_both("vs_c_rfl_escape", vs([ - "v_mov_b32_e32 v5, 7", "v_cmp_eq_u32_e32 vcc, 33, v0", - "s_and_saveexec_b64 s[12:13], vcc", "v_mov_b32_e32 v5, 50", - "v_readfirstlane_b32 s20, v5", "s_mov_b64 exec, s[10:11]", - "v_mov_b32_e32 v6, s20"])) - self.assertEqual(tier, "C") - self.assertNotEqual(whole, halves) - self.assertEqual([w[0] for w in whole], [50] * 64) - self.assertEqual([w[0] for w in halves], [7] * 32 + [50] * 32) - - def test_c_lane_count_differs(self): - tier, whole, halves = self.run_both("vs_c_cnt", vs([ - "v_and_b32_e32 v4, 3, v0", "v_cmp_eq_u32_e32 vcc, 1, v4", "s_bcnt1_i32_b64 s6, vcc", - "v_mov_b32_e32 v6, s6", "v_mov_b32_e32 v7, v4"])) - self.assertEqual(tier, "C") - self.assertEqual([w[1] for w in whole], [w[1] for w in halves]) # per-lane data is the same - self.assertEqual({w[0] for w in whole}, {16}) - self.assertEqual({w[0] for w in halves}, {8}) - - def test_c_lane_id_differs(self): - tier, whole, halves = self.run_both("vs_c_id", vs([ - "v_mbcnt_lo_u32_b32 v6, -1, 0", "v_mbcnt_hi_u32_b32 v6, -1, v6"])) - self.assertEqual(tier, "C") - self.assertEqual([w[0] for w in whole], list(range(64))) - self.assertEqual([w[0] for w in halves], list(range(32)) * 2) - - def test_c_stale_scalar_differs(self): - tier, whole, halves = self.run_both("vs_c_stale", vs([ - "v_cmp_eq_u32_e32 vcc, 0, v0", "s_mov_b32 s5, 7", "s_cbranch_vccz 1", "s_add_u32 s5, s5, 1", - "v_mov_b32_e32 v6, s5"])) - self.assertEqual(tier, "C") - self.assertEqual({w[0] for w in whole}, {8}) # vertex 0 is on, the whole wave adds - self.assertEqual({w[0] for w in halves[:32]}, {8}) - self.assertEqual({w[0] for w in halves[32:]}, {7}) # the other half voted no - - -AGG_HEAD = ["v_and_b32_e32 v4, 3, v0", "v_cmp_eq_u32_e32 vcc, 1, v4", "s_and_saveexec_b64 s[12:13], vcc"] -AGG_RANK = ["v_mbcnt_lo_u32_b32 v10, exec_lo, 0", "v_mbcnt_hi_u32_b32 v10, exec_hi, v10"] -AGG_ELECT = ["v_cmp_eq_u32_e32 vcc, 0, v10", "s_and_saveexec_b64 s[14:15], vcc", "v_mov_b32_e32 v11, s6", - "v_mov_b32_e32 v12, 0", "buffer_atomic_add v11, v12, s[0:3], 0 offen glc", "s_or_b64 exec, exec, s[14:15]", - "v_readfirstlane_b32 s7, v11"] - - -class ReviewRegressions(unittest.TestCase): - """Programs an independent review used to get a false tier A or B (silent wrong rendering). Each must be C, - or, as vertex shaders, the 64-lane and the two-half runs must agree.""" - tier = Classification.tier - - def test_scc_of_a_vote_into_data(self): - for name, body in ( - ("cselect", ["v_cmp_eq_u32_e32 vcc, 1, v0", "s_cmp_lg_u64 vcc, 0", "s_cselect_b32 s5, 1, 0", - "v_mov_b32_e32 v6, s5"]), - ("saveexec_cselect", ["v_cmp_eq_u32_e32 vcc, 1, v0", "s_and_saveexec_b64 s[12:13], vcc", - "s_cselect_b32 s5, 1, 0", "s_or_b64 exec, exec, s[12:13]", - "v_mov_b32_e32 v6, s5"]), - ("addc", ["v_cmp_eq_u32_e32 vcc, 1, v0", "s_cmp_lg_u64 vcc, 0", "s_addc_u32 s5, s5, 0", - "v_mov_b32_e32 v6, s5"]), - ("cmov", ["v_cmp_eq_u32_e32 vcc, 1, v0", "s_cmp_lg_u64 vcc, 0", "s_mov_b32 s5, 0", - "s_cmov_b32 s5, 9", "v_mov_b32_e32 v6, s5"]), - ("bcnt", ["s_bcnt1_i32_b64 s6, exec", "s_cselect_b32 s5, 1, 0", "v_mov_b32_e32 v6, s5"])): - self.tier("ps_scc_" + name, ps(body), "C", contains=["cross-lane"]) - - def test_scc_vote_still_branches(self): - # the one allowed consumer of a vote's SCC: s_cbranch_scc*, skipping lane-masked work - self.tier("ps_scc_branch", ps([ - "v_cmp_eq_u32_e32 vcc, 2, v0", "s_and_saveexec_b64 s[16:17], vcc", "s_cbranch_scc0 1", - "v_add_nc_u32_e32 v6, 9, v6", "s_or_b64 exec, exec, s[16:17]"]), "A", [], []) - - def test_rank_alone_is_not_a_slot(self): - self.tier("ps_rank_addr", ps([ - "v_mbcnt_lo_u32_b32 v10, exec_lo, 0", "v_mbcnt_hi_u32_b32 v10, exec_hi, v10", - "v_lshlrev_b32_e32 v13, 2, v10", "buffer_store_dword v0, v13, s[0:3], 0 offen offset:256"]), - "C", ["lane-rank"]) - - def test_base_alone_is_not_a_slot(self): - self.tier("ps_base_addr", ps(AGG_HEAD + ["s_bcnt1_i32_b64 s6, exec"] + AGG_RANK + AGG_ELECT + [ - "v_mov_b32_e32 v13, s7", "buffer_store_dword v0, v13, s[0:3], 0 offen offset:256", - "s_mov_b64 exec, s[10:11]"]), "C", ["allocation-order"]) - - def test_atomic_add_of_a_count_by_every_lane(self): - for name, mods in (("plain", ""), ("glc", " glc")): - self.tier("ps_allcount_" + name, ps([ - "s_bcnt1_i32_b64 s6, exec", "v_mov_b32_e32 v11, s6", "v_mov_b32_e32 v12, 0", - "buffer_atomic_add v11, v12, s[0:3], 0 offen" + mods]), "C", ["lane-count"]) - - def test_count_of_another_mask_in_the_elected_atomic(self): - self.tier("ps_cnt_other", ps([ - "v_and_b32_e32 v4, 3, v0", "v_cmp_eq_u32_e32 vcc, 1, v4", "s_bcnt1_i32_b64 s6, vcc", - "v_cmp_eq_u32_e32 vcc, 2, v4", "s_and_saveexec_b64 s[12:13], vcc"] + AGG_RANK + AGG_ELECT[:2] + [ - "v_mov_b32_e32 v11, s6", "v_mov_b32_e32 v12, 0", "buffer_atomic_add v11, v12, s[0:3], 0 offen glc", - "s_or_b64 exec, exec, s[14:15]", "s_mov_b64 exec, s[10:11]"]), "C", ["lane-count"]) - - def test_count_of_exec_before_it_narrowed(self): - self.tier("ps_cnt_wider", ps([ - "s_bcnt1_i32_b64 s6, exec", "v_and_b32_e32 v4, 3, v0", "v_cmp_eq_u32_e32 vcc, 1, v4", - "s_and_saveexec_b64 s[12:13], vcc"] + AGG_RANK + AGG_ELECT[:2] + [ - "v_mov_b32_e32 v11, s6", "v_mov_b32_e32 v12, 0", "buffer_atomic_add v11, v12, s[0:3], 0 offen glc", - "s_or_b64 exec, exec, s[14:15]", "s_mov_b64 exec, s[10:11]"]), "C", ["lane-count"]) - - def test_vote_whose_other_side_has_code(self): - self.tier("ps_vccnz_else", ps([ - "v_cmp_eq_u32_e32 vcc, 1, v0", "s_cbranch_vccnz 2", "v_mov_b32_e32 v6, 5", "s_branch 3", - "s_and_saveexec_b64 s[16:17], vcc", "v_mov_b32_e32 v6, 7", "s_or_b64 exec, exec, s[16:17]"]), - "C", contains=["unsafe-vote-branch"]) - self.tier("ps_vccnz_else2", ps([ - "v_cmp_eq_u32_e32 vcc, 1, v0", "s_cbranch_vccnz 2", "v_mov_b32_e32 v6, 5", "s_branch 3", - "s_and_saveexec_b64 s[16:17], vcc", "v_mov_b32_e32 v6, 7", "s_or_b64 exec, exec, s[16:17]", - "v_mov_b32_e32 v7, 1"]), "C", contains=["unsafe-vote-branch"]) - - def test_vccnz_with_a_jump_only_fall_through_is_a_skip(self): - self.tier("ps_vccnz_jump", ps([ - "v_cmp_eq_u32_e32 vcc, 1, v0", "s_cbranch_vccnz 1", "s_branch 3", "s_and_saveexec_b64 s[16:17], vcc", - "v_add_nc_u32_e32 v6, 13, v6", "s_or_b64 exec, exec, s[16:17]"]), "A", [], []) - - def test_exec_zero_side_with_code_of_its_own(self): - # execz: the taken side (no lane active in the wave) writes an SGPR that is exported afterwards - self.tier("ps_execz_sgpr", ps([ - "v_cmp_eq_u32_e32 vcc, 1, v0", "s_mov_b32 s5, 7", "s_and_saveexec_b64 s[12:13], vcc", - "s_cbranch_execz 2", "v_mov_b32_e32 v8, 100", "s_branch 1", "s_mov_b32 s5, 9", - "s_or_b64 exec, exec, s[12:13]", "v_mov_b32_e32 v6, s5"]), "C", contains=["unsafe-execz-branch"]) - # execnz: the fall-through is the exec-zero side - self.tier("ps_execnz_else", ps([ - "v_cmp_eq_u32_e32 vcc, 1, v0", "s_and_saveexec_b64 s[12:13], vcc", "s_cbranch_execnz 2", - "s_mov_b32 s5, 9", "s_branch 1", "v_mov_b32_e32 v8, 100", "s_or_b64 exec, exec, s[12:13]", - "v_mov_b32_e32 v6, s5"]), "C", contains=["unsafe-execz-branch"]) - # a VALU-only exec-zero side is refused too (kept simple: the side must be the join) - self.tier("ps_execz_valu", ps([ - "v_cmp_eq_u32_e32 vcc, 1, v0", "s_and_saveexec_b64 s[12:13], vcc", "s_cbranch_execz 2", - "v_mov_b32_e32 v6, 7", "s_branch 1", "v_mov_b32_e32 v6, 5", "s_or_b64 exec, exec, s[12:13]"]), - "C", contains=["unsafe-execz-branch"]) - - def test_exec_zero_side_that_is_the_join_or_a_loop_exit_is_a_skip(self): - self.tier("ps_execz_join", ps([ - "v_cmp_eq_u32_e32 vcc, 1, v0", "s_and_saveexec_b64 s[12:13], vcc", "s_cbranch_execz 1", - "v_mov_b32_e32 v6, 7", "s_or_b64 exec, exec, s[12:13]"]), "A", [], []) - self.tier("ps_execz_jump_join", ps([ - "v_cmp_eq_u32_e32 vcc, 1, v0", "s_and_saveexec_b64 s[12:13], vcc", "s_cbranch_execnz 1", - "s_branch 1", "v_mov_b32_e32 v6, 7", "s_or_b64 exec, exec, s[12:13]"]), "A", [], []) - - # ---- second review: a rank / count / mask that is not bound to the mask it belongs to - ATOMIC = ["v_mov_b32_e32 v11, s6", "v_mov_b32_e32 v12, 0", "buffer_atomic_add v11, v12, s[0:3], 0 offen glc", - "s_or_b64 exec, exec, s[14:15]"] - SLOT = ["v_readfirstlane_b32 s7, v11", "v_add_nc_u32_e32 v13, s7, {rank}", "v_lshlrev_b32_e32 v13, 2, v13", - "buffer_store_dword v0, v13, s[0:3], 0 offen offset:256"] - ELECT_NARROWED = ["v_cmp_eq_u32_e32 vcc, 0, v10", "s_and_saveexec_b64 s[14:15], vcc"] - ENTRY_RANK = ["v_mbcnt_lo_u32_b32 v14, exec_lo, 0", "v_mbcnt_hi_u32_b32 v14, exec_hi, v14"] - - def test_slot_rank_of_the_entry_exec_is_not_the_counted_mask(self): - body = (self.ENTRY_RANK + AGG_HEAD + ["s_bcnt1_i32_b64 s6, exec"] + AGG_RANK + self.ELECT_NARROWED - + self.ATOMIC + [x.format(rank="v14") for x in self.SLOT] + ["s_mov_b64 exec, s[10:11]"]) - self.tier("ps_rank_entry_exec", ps(body), "C", contains=["lane-rank"]) - - def test_slot_rank_from_the_saved_exec(self): - body = (AGG_HEAD + ["s_bcnt1_i32_b64 s6, exec"] + AGG_RANK + self.ELECT_NARROWED + self.ATOMIC + [ - "v_mbcnt_lo_u32_b32 v14, s12, 0", "v_mbcnt_hi_u32_b32 v14, s13, v14"] - + [x.format(rank="v14") for x in self.SLOT] + ["s_mov_b64 exec, s[10:11]"]) - self.tier("ps_rank_saved_exec", ps(body), "C", contains=["lane-rank"]) - - def test_slot_of_the_right_mask_is_still_b(self): - body = (AGG_HEAD + ["s_bcnt1_i32_b64 s6, exec"] + AGG_RANK + self.ELECT_NARROWED + self.ATOMIC - + [x.format(rank="v10") for x in self.SLOT] + ["s_mov_b64 exec, s[10:11]"]) - self.tier("ps_rank_right_mask", ps(body), "B", [], ["aggregated-atomic", "elected-lane"]) - - def test_lane_mask_combined_with_a_register_is_data(self): - for name, body in ( - ("and_user_bcnt", ["s_and_b64 s[14:15], exec, s[4:5]", "s_bcnt1_i32_b64 s6, s[14:15]", - "v_mov_b32_e32 v6, s6"]), - ("and_user_narrowed", ["v_cmp_lt_u32_e32 vcc, 40, v0", "s_and_b64 exec, exec, vcc", - "s_and_b64 s[14:15], exec, s[4:5]", "s_mov_b64 exec, s[10:11]", - "s_bcnt1_i32_b64 s6, s[14:15]", "v_mov_b32_e32 v6, s6"]), - ("vcc_and_user_cmp", ["v_cmp_lt_u32_e32 vcc, 40, v0", "s_and_b64 s[14:15], vcc, s[4:5]", - "s_cmp_eq_u64 s[14:15], 0", "s_cselect_b32 s6, 1, 2", "v_mov_b32_e32 v6, s6"]), - ("vcc_and_user_branch", ["v_cmp_lt_u32_e32 vcc, 40, v0", "s_and_b64 s[14:15], vcc, s[4:5]", - "s_cmp_eq_u64 s[14:15], 0", "s_cbranch_scc1 1", "v_mov_b32_e32 v6, 4"]), - ("or_user_ff1", ["v_cmp_lt_u32_e32 vcc, 40, v0", "s_or_b64 s[14:15], vcc, s[4:5]", - "s_ff1_i32_b64 s6, s[14:15]", "v_mov_b32_e32 v6, s6"]), - ("andn2_user_bcnt", ["v_cmp_lt_u32_e32 vcc, 40, v0", "s_andn2_b64 s[14:15], s[4:5], vcc", - "s_bcnt1_i32_b64 s6, s[14:15]", "v_mov_b32_e32 v6, s6"]), - ("and_user_bcnt0", ["v_cmp_lt_u32_e32 vcc, 40, v0", "s_and_b64 s[14:15], vcc, s[4:5]", - "s_bcnt0_i32_b64 s6, s[14:15]", "v_mov_b32_e32 v6, s6"])): - self.tier("ps_maskdata_" + name, ps(body), "C") - - def test_mask_and_constants_stay_masks(self): - self.tier("ps_mask_const", ps([ - "v_cmp_lt_u32_e32 vcc, 40, v0", "s_and_b64 s[14:15], vcc, -1", "s_and_saveexec_b64 s[12:13], s[14:15]", - "v_add_nc_u32_e32 v6, 9, v6", "s_or_b64 exec, exec, s[12:13]"]), "A", [], []) - - def test_waterfall_vgpr_rewritten_before_the_compare(self): - self.tier("ps_wf_rewritten", ps([ - "v_and_b32_e32 v4, 7, v0", "v_readfirstlane_b32 s20, v4", "v_add_nc_u32_e32 v4, 1, v4", - "v_cmp_eq_u32_e32 vcc, s20, v4", "s_and_saveexec_b64 s[12:13], vcc", "v_add_nc_u32_e32 v6, s20, v0", - "s_xor_b64 exec, exec, s[12:13]", "s_cbranch_execnz -7", "s_mov_b64 exec, s[10:11]"]), "C") - - def test_analysis_failure_is_tier_c_and_not_an_error(self): - import wave64_halves - old = wave64_halves.analyse - - def boom(*a, **k): - raise RuntimeError("boom") - wave64_halves.analyse = boom - try: - self.tier("ps_boom", ps(["v_mov_b32_e32 v6, 1"]), "C", ["analysis-error"]) - finally: - wave64_halves.analyse = old - - -class ReviewExecution(unittest.TestCase): - run_both = Execution.run_both - - def lanes(self, name, body): - tier, whole, halves = self.run_both(name, vs(body)) - return tier, sorted({w[0] if w else None for w in whole}), sorted({w[0] if w else None for w in halves}) - - def test_cselect_of_a_vote_differs_and_is_c(self): - tier, whole, halves = self.lanes("vs_cselect", [ - "v_cmp_eq_u32_e32 vcc, 1, v0", "s_cmp_lg_u64 vcc, 0", "s_cselect_b32 s5, 1, 0", "v_mov_b32_e32 v6, s5"]) - self.assertEqual((tier, whole, halves), ("C", [1], [0, 1])) # vertex 1 is in the first half only - - def test_vote_else_side_differs_and_is_c(self): - tier, whole, halves = self.lanes("vs_vccnz_else", [ - "v_cmp_eq_u32_e32 vcc, 1, v0", "s_cbranch_vccnz 2", "v_mov_b32_e32 v6, 5", "s_branch 3", - "s_and_saveexec_b64 s[16:17], vcc", "v_mov_b32_e32 v6, 7", "s_or_b64 exec, exec, s[16:17]"]) - self.assertEqual(tier, "C") - self.assertNotEqual(whole, halves) - - def test_vote_with_empty_other_side_is_invariant(self): - tier, whole, halves = self.lanes("vs_vccz_join", [ - "v_cmp_eq_u32_e32 vcc, 33, v0", "v_mov_b32_e32 v6, 4", "s_cbranch_vccz 3", - "s_and_saveexec_b64 s[16:17], vcc", "v_mov_b32_e32 v6, 7", "s_or_b64 exec, exec, s[16:17]"]) - self.assertEqual(tier, "A") - self.assertEqual(whole, halves) - self.assertEqual(whole, [4, 7]) # only vertex 33, in the second half - - -class SccVotePolarity(unittest.TestCase): - """`s_cmp_eq_u64 m, 0` sets SCC when the mask is empty, `s_cmp_lg_u64 m, 0` (and the 64-bit logic ops, s_bcnt1) - when it is not: the side a vote runs when some lane votes yes is the not-taken side of `s_cbranch_scc1` after - cmp_eq and the taken one after cmp_lg.""" - tier = Classification.tier - run_both = Execution.run_both - HEAD = ["v_cmp_gt_u32_e32 vcc, 20, v0", "s_and_b64 s[20:21], exec, vcc"] - - def test_cmp_eq_jump_to_narrowing_is_c(self): - # scc1 (mask empty) jumps to the narrowing, the "yes" side skips it: a half with no lane < 20 empties EXEC, - # the wave never does - tier, whole, halves = self.run_both("vs_cmp_eq_wrong", vs(self.HEAD + [ - "s_cmp_eq_u64 s[20:21], 0", "s_cbranch_scc1 1", "s_branch 1", "s_and_b64 exec, exec, s[20:21]", - "v_add_nc_u32_e32 v6, 3, v0"])) - self.assertEqual([w[0] for w in whole], [3 + k for k in range(64)]) - self.assertEqual([w[0] for w in halves], [3 + k for k in range(32)] + [0] * 32) - self.assertEqual(tier, "C") - - def test_cmp_eq_skip_when_empty_is_a(self): - # scc1 (mask empty) skips the narrowed region: the yes side narrows EXEC to the mask, the no side is the join - for name, cmp_, br in (("vs_cmp_eq_skip", "s_cmp_eq_u64 s[20:21], 0", "s_cbranch_scc1 2"), - ("vs_cmp_eq_skip0", "s_cmp_eq_u64 0, s[20:21]", "s_cbranch_scc1 2"), - ("vs_cmp_lg_skip", "s_cmp_lg_u64 s[20:21], 0", "s_cbranch_scc0 2")): - tier, whole, halves = self.run_both(name, vs(self.HEAD + [ - cmp_, br, "s_and_b64 exec, exec, s[20:21]", "v_add_nc_u32_e32 v6, 3, v0", - "s_mov_b64 exec, s[10:11]"])) - self.assertEqual(tier, "A", name) - self.assertEqual(whole, halves, name) - self.assertEqual([w[0] for w in whole], [3 + k if k < 20 else 0 for k in range(64)], name) - - def test_exec_restore_by_mov_is_not_an_exec_vote(self): - # s_mov_b64 writes no SCC: the branch after restoring EXEC reads the cmp_lg vote on the mask, not EXEC's - tier, whole, halves = self.run_both("vs_mov_exec_scc", vs(self.HEAD + [ - "s_cmp_lg_u64 s[20:21], 0", "s_mov_b64 exec, s[10:11]", "s_cbranch_scc0 1", - "v_add_nc_u32_e32 v6, 3, v0"])) - self.assertEqual([w[0] for w in whole], [3 + k for k in range(64)]) - self.assertEqual([w[0] for w in halves], [3 + k for k in range(32)] + [0] * 32) - self.assertEqual(tier, "C") - - def test_mov_of_the_mask_keeps_the_cmp_eq_vote(self): - # s_mov_b64 writes no SCC: scc0 after cmp_eq is "mask not empty", the wrong side to skip the narrowing. Tagged - # as a vote on the copy (non-empty polarity) the same skip looked like the exact one: a false tier A - tier, whole, halves = self.run_both("vs_mov_keeps_vote", vs(self.HEAD + [ - "s_cmp_eq_u64 s[20:21], 0", "s_mov_b64 s[22:23], vcc", "s_cbranch_scc0 2", - "s_and_b64 exec, exec, s[22:23]", "v_add_nc_u32_e32 v6, 3, v0", "s_mov_b64 exec, s[10:11]"])) - self.assertEqual(tier, "C") - self.assertEqual(whole, halves) # equal on this input; the tier is about the branch sense - - def test_cselect_result_is_no_vote_execution(self): - # s_cselect_b64 reads SCC and writes none: scc1 after cmp_eq skips when the mask is empty; the narrowing by the - # cselect result is the wrong thing to skip and the halves differ from the wave - tier, whole, halves = self.run_both("vs_cselect_keeps_vote", vs(self.HEAD + [ - "s_cmp_eq_u64 s[20:21], 0", "s_cselect_b64 s[22:23], s[20:21], exec", "s_cbranch_scc1 2", - "s_and_b64 exec, exec, s[22:23]", "v_add_nc_u32_e32 v6, 3, v0", "s_mov_b64 exec, s[10:11]"])) - self.assertEqual(tier, "C") - self.assertNotEqual(whole, halves) - - def test_cselect_and_mov_keep_the_scc_vote(self): - # neither s_cselect_b64 nor s_mov_b64 of a mask writes SCC: the vote stays on the compared mask - for name, mid in (("vs_keep_cselect", "s_cselect_b64 s[22:23], s[20:21], exec"), - ("vs_keep_mov_vcc", "s_mov_b64 s[22:23], vcc")): - self.tier(name, vs(self.HEAD + [ - "s_cmp_eq_u64 s[20:21], 0", mid, "s_cbranch_scc1 1", "s_branch 1", "s_and_b64 exec, exec, s[20:21]", - "v_add_nc_u32_e32 v6, 3, v0"]), "C", contains=["unsafe-vote-branch"]) - self.tier(name + "_a", vs(self.HEAD + [ - "s_cmp_eq_u64 s[20:21], 0", mid, "s_cbranch_scc1 2", "s_and_b64 exec, exec, s[20:21]", - "v_add_nc_u32_e32 v6, 3, v0", "s_mov_b64 exec, s[10:11]"]), "A") - - def test_cmp_eq_wrong_polarity_classification(self): - # the same skip with the branch sense flipped: scc0 after cmp_eq jumps over the narrowing when lanes vote yes - self.tier("vs_cmp_eq_scc0", vs(self.HEAD + [ - "s_cmp_eq_u64 s[20:21], 0", "s_cbranch_scc0 2", "s_and_b64 exec, exec, s[20:21]", - "v_add_nc_u32_e32 v6, 3, v0", "s_mov_b64 exec, s[10:11]"]), "C", contains=["unsafe-vote-branch"]) - - -UNIFORM = [[0, 0, 0, 0, 9], [0, 0, 0, 0, 1]] # s4 = 9: the compare 5 < s4 says yes; s4 = 1: no -VCCZ_SIDES = ["s_cbranch_vccz 3", "v_mov_b32_e32 v6, 7", "s_mov_b32 s20, 1", "s_branch 2", "v_mov_b32_e32 v6, 5", - "s_mov_b32 s20, 2", "v_add_nc_u32_e32 v7, s20, v0"] - - -class UniformVote(unittest.TestCase): - """A vote on a compare of a wave-uniform value made while EXEC is the launch mask is no lane vote: the mask is every - launch lane or none, so each half votes as the wave does, and both sides may have code (scalars included) of their - own. The near misses vote differently in the two halves and must stay tier C.""" - run_both = Execution.run_both - - def invariant(self, name, body, tier, idioms, want): - for push in UNIFORM: - t, whole, halves = self.run_both(name, vs(body), push) - (_, reasons, got_idioms), _ = meta_of(name, vs(body)) - self.assertEqual((t, reasons, got_idioms), (tier, [], idioms), name) - self.assertEqual(whole, halves, (name, push)) - self.assertEqual([w[:2] for w in whole], [want(push[4], k) for k in range(64)], (name, push)) - - def differs(self, name, body, reason, push=UNIFORM[0]): - t, whole, halves = self.run_both(name, vs(body), push) - (_, reasons, _), _ = meta_of(name, vs(body)) - self.assertEqual(t, "C", name) - self.assertIn(reason, reasons, name) - self.assertNotEqual(whole, halves, name) - return whole, halves - - def test_a_vccz_if_else_with_scalars_read_after_the_join(self): - self.invariant("vs_uv_vccz", ["v_mov_b32_e32 v1, s4", "v_cmp_lt_u32_e32 vcc, 5, v1"] + VCCZ_SIDES, "A", [], - lambda s4, k: (7, 1 + k) if s4 > 5 else (5, 2 + k)) - - def test_a_llvm_and_exec_vccnz(self): - self.invariant("vs_uv_and_exec", [ - "v_mov_b32_e32 v1, s4", "v_cmp_lt_u32_e64 s[14:15], 5, v1", "s_and_b64 vcc, exec, s[14:15]", - "s_cbranch_vccnz 3", "v_mov_b32_e32 v6, 5", "s_mov_b32 s20, 2", "s_branch 2", "v_mov_b32_e32 v6, 7", - "s_mov_b32 s20, 1", "v_add_nc_u32_e32 v7, s20, v0"], "A", [], - lambda s4, k: (7, 1 + k) if s4 > 5 else (5, 2 + k)) - - def test_a_uniform_loop_back_edge(self): - # s20 counts the trips in an SGPR across the back edge: every half runs s4 of them, as the wave does - self.invariant("vs_uv_loop", [ - "s_mov_b32 s20, 0", "s_add_u32 s20, s20, 1", "v_add_nc_u32_e32 v6, 3, v6", "v_mov_b32_e32 v1, s20", - "v_cmp_gt_u32_e32 vcc, s4, v1", "s_cbranch_vccnz -5", "v_add_nc_u32_e32 v7, s20, v0"], "A", [], - lambda s4, k: (3 * s4, s4 + k)) - - def test_b_readfirstlane_of_a_uniform_value_feeds_the_vote(self): - self.invariant("vs_uv_rfl", ["v_mov_b32_e32 v1, s4", "v_readfirstlane_b32 s21, v1", "v_mov_b32_e32 v2, s21", - "v_cmp_lt_u32_e32 vcc, 5, v2"] + VCCZ_SIDES, "B", ["readfirstlane-uniform"], - lambda s4, k: (7, 1 + k) if s4 > 5 else (5, 2 + k)) - - def test_c_compare_under_a_narrowed_exec(self): - # EXEC narrowed to lanes 0..31: the second half has no active lane, votes no and sets s20 = 2, which the lanes - # of that half read once EXEC is restored; the wave voted yes (s20 = 1) - whole, halves = self.differs("vs_uv_narrowed", [ - "v_mov_b32_e32 v1, s4", "v_cmp_gt_u32_e32 vcc, 32, v0", "s_and_saveexec_b64 s[12:13], vcc", - "v_cmp_lt_u32_e32 vcc, 5, v1", "s_cbranch_vccz 3", "v_mov_b32_e32 v6, 7", "s_mov_b32 s20, 1", - "s_branch 2", "v_mov_b32_e32 v6, 5", "s_mov_b32 s20, 2", "s_mov_b64 exec, s[12:13]", - "v_add_nc_u32_e32 v7, s20, v0"], "unsafe-vote-branch") - self.assertEqual([w[1] for w in whole[32:]], [1 + k for k in range(32, 64)]) - self.assertEqual([w[1] for w in halves[32:]], [2 + k for k in range(32, 64)]) - - def test_c_half_of_a_uniform_mask_rewritten(self): - # s15 (the high half of the uniform mask) is rewritten before the mask becomes VCC: the wave still sees the low - # half's bits and votes yes, the second half sees s15 = 0 and votes no - name = "vs_uv_half_rewritten" - body = vs(["v_mov_b32_e32 v1, s4", "v_cmp_lt_u32_e64 s[14:15], 5, v1", "s_mov_b32 s15, 0", - "s_mov_b64 vcc, s[14:15]"] + VCCZ_SIDES) - (t, reasons, _), _ = meta_of(name, body) - self.assertEqual(t, "C", name) - self.assertIn("unsafe-vote-branch", reasons, name) - - def test_c_readfirstlane_of_a_varying_value(self): - # the first lane is vertex 0 in the wave and vertex 32 in the second half - self.differs("vs_uv_rfl_varying", ["v_readfirstlane_b32 s21, v0", "v_mov_b32_e32 v1, s21", - "v_cmp_eq_u32_e32 vcc, 0, v1"] + VCCZ_SIDES, "tainted-branch") - - def test_c_compare_on_a_lane_count(self): - # 64 lanes in the wave, 32 in a half: 40 < count is yes for the wave, no for each half - self.differs("vs_uv_bcnt", ["s_bcnt1_i32_b64 s21, exec", "v_mov_b32_e32 v1, s21", - "v_cmp_lt_u32_e32 vcc, 40, v1"] + VCCZ_SIDES, "lane-count") - - def test_c_scc_of_a_lane_mask_with_a_uniform_vcc_written_after_it(self): - # SCC is the vote of the AND (vertex 1 on: the wave and the first half say yes); the uniform v_cmp after it - # writes VCC but not SCC, so the branch still votes on the lane mask; since SHADER-820 (#4620) the new VCC - # ends SCC's tag as a vote, so the branch is reported as a tainted one - self.differs("vs_uv_scc_stale", ["v_cmp_eq_u32_e64 s[16:17], 1, v0", "s_and_b64 vcc, exec, s[16:17]", - "v_mov_b32_e32 v1, s4", "v_cmp_lt_u32_e32 vcc, 5, v1", "s_cbranch_scc0 3"] - + VCCZ_SIDES[1:], "tainted-branch") - - def test_c_uniform_mask_anded_with_a_lane_mask(self): - # only vertex 1 survives the AND: the wave and the first half vote yes, the second half no - self.differs("vs_uv_and_lane", ["v_mov_b32_e32 v1, s4", "v_cmp_lt_u32_e32 vcc, 5, v1", - "v_cmp_eq_u32_e64 s[16:17], 1, v0", "s_and_b64 vcc, vcc, s[16:17]"] - + VCCZ_SIDES, "unsafe-vote-branch") - - def test_c_partial_write_keeps_varying_bits(self): - # v1 = lane << 8, then its low byte (SDWA, UNUSED_PRESERVE) or low half (16-bit add) from s4: the sources are - # uniform but bits the write keeps are not, so 0x2000 > v1 is yes for lanes 0..31 only (found by @shdann) - sides = ["s_cbranch_vccz 3", "v_mov_b32_e32 v6, 7", "s_mov_b32 s20, 1", "s_branch 2", "v_mov_b32_e32 v6, 5", - "s_mov_b32 s20, 2", "v_add_nc_u32_e32 v7, s20, v0"] - self.differs("vs_uv_sdwa_partial", [ - "v_lshlrev_b32_e32 v1, 8, v0", - "v_mov_b32_sdwa v1, s4 dst_sel:BYTE_0 dst_unused:UNUSED_PRESERVE src0_sel:DWORD", - "v_cmp_gt_u32_e32 vcc, 0x2000, v1"] + sides, "unsafe-vote-branch", push=[0, 0, 0, 0, 9]) - self.differs("vs_uv_u16_partial", [ - "v_lshlrev_b32_e32 v1, 16, v0", "v_add_u16_e64 v1, 1, s4", - "v_cmp_gt_u32_e32 vcc, 0x200000, v1"] + sides, "unsafe-vote-branch", push=[0, 0, 0, 0, 9]) - - def test_a_whole_register_16_bit_forms_stay_uniform(self): - # a packed convert, a SAD and a VOP2 16-bit integer op write the whole VGPR: uniform sources, uniform result - for name, op in (("vs_uv_pkrtz", "v_cvt_pkrtz_f16_f32_e32 v1, s4, v2"), ("vs_uv_sad", "v_sad_u16 v1, s4, 0, v2"), - ("vs_uv_add_u16_e32", "v_add_u16_e32 v1, s4, v2")): - (t, reasons, _), _ = meta_of(name, vs(["v_mov_b32_e32 v2, s4", op, "v_cmp_lt_u32_e32 vcc, 5, v1"] - + VCCZ_SIDES)) - self.assertEqual((t, reasons), ("A", []), name) - - def test_a_partial_write_over_a_uniform_register(self): - # the kept bits come from s4 too, so the register stays uniform - name = "vs_uv_sdwa_uniform" - (t, reasons, _), _ = meta_of(name, vs([ - "v_mov_b32_e32 v1, s4", "v_mov_b32_sdwa v1, s4 dst_sel:BYTE_0 dst_unused:UNUSED_PRESERVE src0_sel:DWORD", - "v_cmp_lt_u32_e32 vcc, 5, v1"] + VCCZ_SIDES)) - self.assertEqual((t, reasons), ("A", []), name) - -class KillExit(unittest.TestCase): - """The early exit of a pixel kill (`s_andn2_b64 live, live, exec/vcc`, `s_cbranch_scc0` to a block that only - empties EXEC from that mask, exports and ends): a half whose live mask is empty writes nothing there, and in the - wave its lanes stay off on the run side to the end. Tier A only when the exit is inert, the run side narrows EXEC - into the mask's quads before anything else and never widens it, and the vote is the mask's own.""" - tier = Classification.tier - run_both = Execution.run_both - - # -- tier A - def test_a_kill_wqm_and_exec(self): - self.tier("ps_kill_wqm", kill(KILL, RUN_WQM + ["v_add_nc_u32_e32 v6, 3, v0"], EXIT_PS), "A", [], []) - - def test_a_kill_cmpx_wqm_mov_exec(self): - self.tier("ps_kill_cmpx", kill( - ["s_mov_b64 s[20:21], exec", "v_cmpx_gt_u32_e32 40, v0", "s_andn2_b64 s[20:21], s[20:21], exec"], - ["s_wqm_b64 s[22:23], s[20:21]", "s_mov_b64 exec, s[22:23]", "v_add_nc_u32_e32 v6, 3, v0"], - EXIT_PS), "A", [], []) - - def test_a_kill_direct_narrowing(self): - for name, run in (("ps_kill_and", ["s_and_b64 exec, exec, s[20:21]"]), - ("ps_kill_mov", ["s_mov_b64 exec, s[20:21]"]), - ("ps_kill_wqm_exec", ["s_wqm_b64 exec, s[20:21]"])): - self.tier(name, kill(KILL, run + ["v_add_nc_u32_e32 v6, 3, v0"], EXIT_PS), "A", [], []) - self.tier("ps_kill_exit0", kill(KILL, RUN_WQM, ["s_mov_b64 exec, 0"] + EXIT_PS[1:]), "A", [], []) - - def test_a_kill_then_if_endif(self): - # a saveexec / restore pair after the narrowing restores a mask taken inside it: EXEC stays in the quads - self.tier("ps_kill_if", kill(KILL, RUN_WQM + [ - "v_cmp_eq_u32_e32 vcc, 1, v0", "s_and_saveexec_b64 s[12:13], vcc", "s_cbranch_execz 1", - "v_mov_b32_e32 v6, 7", "s_or_b64 exec, exec, s[12:13]"], EXIT_PS), "A", [], []) - - def test_a_kill_saveexec_first(self): - # the run side's first narrowing is a SAVEEXEC: EXEC = wqm mask & EXEC (inside), s[30:31] = the old EXEC - self.tier("ps_kill_saveexec", kill(KILL, ["s_wqm_b64 s[22:23], s[20:21]", "s_and_saveexec_b64 s[30:31], " - "s[22:23]", "v_add_nc_u32_e32 v6, 3, v0"], EXIT_PS), "A", [], []) - - # -- near misses: tier C unsafe-vote-branch - def test_c_exit_with_code_of_its_own(self): - for name, exit_ in ( - ("ps_kill_exit_vmov", ["v_mov_b32_e32 v6, 1"] + EXIT_PS), - ("ps_kill_exit_exp_first", ["exp mrt0 v6, v7, v5, v5 done vm", "s_mov_b64 exec, s[20:21]", - "s_endpgm"]), - ("ps_kill_exit_store", EXIT_PS[:1] + ["buffer_store_dword v6, v5, s[0:3], 0 offen"] + EXIT_PS[1:]), - ("ps_kill_exit_sgpr", EXIT_PS[:1] + ["s_mov_b32 s5, 1"] + EXIT_PS[1:]), - ("ps_kill_exit_other_mask", ["s_mov_b64 exec, s[10:11]"] + EXIT_PS[1:]), - ("ps_kill_exit_jumps_back", EXIT_PS[:2] + ["s_branch -8"])): # into the run side's s_and - self.tier(name, kill(KILL, RUN_WQM, exit_), "C", contains=["unsafe-vote-branch"]) - - def test_c_run_side_does_not_narrow(self): - self.tier("ps_kill_run_code", kill(KILL, ["v_mov_b32_e32 v6, 5"] + RUN_WQM, EXIT_PS), - "C", contains=["unsafe-vote-branch"]) - self.tier("ps_kill_run_other", kill(KILL, ["s_and_b64 exec, exec, s[10:11]"], EXIT_PS), - "C", contains=["unsafe-vote-branch"]) - - def test_c_saveexec_that_does_not_narrow(self): - # s_or_saveexec: EXEC = mask | EXEC, not inside; restoring the saved (old) EXEC widens again - self.tier("ps_kill_or_saveexec", kill(KILL, ["s_wqm_b64 s[22:23], s[20:21]", "s_or_saveexec_b64 s[30:31], " - "s[22:23]", "v_add_nc_u32_e32 v6, 3, v0"], EXIT_PS), - "C", contains=["unsafe-vote-branch"]) - self.tier("ps_kill_saveexec_restore", kill(KILL, ["s_wqm_b64 s[22:23], s[20:21]", "s_and_saveexec_b64 " - "s[30:31], s[22:23]", "s_mov_b64 exec, s[30:31]", - "v_add_nc_u32_e32 v6, 3, v0"], EXIT_PS), - "C", contains=["unsafe-vote-branch"]) - - def test_c_run_side_widens_again(self): - self.tier("ps_kill_widen", kill(KILL, RUN_WQM + ["s_mov_b64 exec, s[10:11]", "v_mov_b32_e32 v6, 9"], - EXIT_PS), "C", contains=["unsafe-vote-branch"]) - self.tier("ps_kill_or", kill(KILL, RUN_WQM + ["s_or_b64 exec, exec, s[10:11]"], EXIT_PS), - "C", contains=["unsafe-vote-branch"]) - - def test_c_mask_redefined_or_not_the_vote(self): - # the mask is rewritten after the vote (s_mov leaves SCC alone): the exit reads another value. Since - # SHADER-820 (#4620) the new value ends SCC's tag as a vote on that mask, so the branch is a tainted one. - self.tier("ps_kill_redef", kill(KILL + ["s_mov_b64 s[20:21], exec"], RUN_WQM, EXIT_PS), - "C", contains=["tainted-branch"]) - # SCC = (mask == 0): the branch to the "exit" is taken when the mask is not empty - self.tier("ps_kill_cmp_eq", kill(KILL + ["s_cmp_eq_u64 s[20:21], 0"], RUN_WQM, EXIT_PS), - "C", contains=["unsafe-vote-branch"]) - - def test_c_vm_export_before_the_vote(self): - self.tier("ps_kill_vm_first", kill(["exp mrt1 v6, v7, v5, v5 vm"] + KILL, RUN_WQM, EXIT_PS), - "C", contains=["unsafe-vote-branch"]) - - def test_shared_exit_of_two_kills_stays_c(self): - # conservative: the exit sets EXEC from a live mask the second kill redefined behind the first vote (stale) - second = ["v_cmp_gt_u32_e32 vcc, 50, v0", "s_andn2_b64 s[20:21], s[20:21], vcc"] - run = RUN_WQM + second + ["s_cbranch_scc0 5"] + RUN_WQM - self.tier("ps_kill_shared", kill(KILL, run, EXIT_PS), "C", contains=["tainted-exec"]) - - def test_mov_of_a_mask_is_not_a_vote(self): - # s_mov_b64 writes no SCC: the branch reads the lane-count compare before it, not a vote on the copy - self.tier("ps_mov_scc", ps([ - "v_cmp_eq_u32_e32 vcc, 1, v0", "s_bcnt1_i32_b64 s6, vcc", "s_cmp_eq_u32 s6, 5", - "s_mov_b64 s[24:25], vcc", "s_cbranch_scc0 3", "s_and_saveexec_b64 s[16:17], s[24:25]", - "v_mov_b32_e32 v6, 7", "s_or_b64 exec, exec, s[16:17]"]), "C", contains=["lane-count"]) - - # -- execution: vertex shaders, 64 lanes against two halves of 32 (vertices < 40 killed: all of the first half) - def test_kill_exit_invariant(self): - tier, whole, halves = self.run_both("vs_kill", kill(KILL, RUN_WQM + [ - "v_mul_u32_u24_e32 v6, 3, v0", "v_mov_b32_e32 v7, 1"], EXIT_VS, "vs")) - self.assertEqual(tier, "A") - self.assertEqual(whole, halves) - # a vertex that is off writes nothing: the interpreter's outputs start at zero - self.assertEqual([w[:2] for w in whole], [(0, 0)] * 40 + [(3 * k, 1) for k in range(40, 64)]) - - def test_kill_exit_saveexec_invariant(self): - tier, whole, halves = self.run_both("vs_kill_saveexec", kill(KILL, [ - "s_wqm_b64 s[22:23], s[20:21]", "s_and_saveexec_b64 s[30:31], s[22:23]", - "v_mul_u32_u24_e32 v6, 3, v0", "v_mov_b32_e32 v7, 1"], EXIT_VS, "vs")) - self.assertEqual(tier, "A") - self.assertEqual(whole, halves) - self.assertEqual([w[:2] for w in whole], [(0, 0)] * 40 + [(3 * k, 1) for k in range(40, 64)]) - - def test_kill_exit_that_widens_differs_and_is_c(self): - tier, whole, halves = self.run_both("vs_kill_widen", kill(KILL, RUN_WQM + [ - "s_mov_b64 exec, s[10:11]", "v_mul_u32_u24_e32 v6, 3, v0", "v_mov_b32_e32 v7, 1"], EXIT_VS, "vs")) - self.assertEqual(tier, "C") - self.assertEqual([w[:2] for w in whole], [(3 * k, 1) for k in range(64)]) - self.assertEqual([w[:2] for w in halves[:32]], [(0, 0)] * 32) # the first half took the exit - - -class AddTidBuffer(unittest.TestCase): - """A MUBUF/MTBUF access with no idxen through a literal V# whose word3 has ADD_TID_ENABLE (bit 23) takes the - wave lane as its index (idxen ignores the bit), so what it reads or writes depends on the lane id: tier C - `lane-id`. A literal with the bit clear and any access with idxen are tier A. (A run-time V# is assumed to - have the bit clear: docs/design.md, SHADER-10.)""" - TID, NO_TID = 0x31816fac, 0x31016fac - - def v_sharp(self, word3): - # SWIZZLE_ENABLE, stride 4, 8-index swizzle: with ADD_TID_ENABLE, lane i reads the dword at base + 4 * i - return ["s_mov_b32 s0, 0x1000", "s_mov_b32 s1, 0x80040000", "s_mov_b32 s2, 0x1000", - f"s_mov_b32 s3, {word3:#x}", "v_mov_b32_e32 v9, 0"] - - def program(self, word3, access): - return vs(self.v_sharp(word3) + [access, "s_waitcnt vmcnt(0)"]) - - def test_literal_add_tid_without_idxen_is_lane_dependent(self): - for load in ("buffer_load_dword v6, off, s[0:3], 0", "buffer_load_format_x v6, off, s[0:3], 0"): - lines = self.program(self.TID, load) - (tier, reasons, _), _ = meta_of("vs_add_tid", lines) - self.assertEqual((tier, "lane-id" in reasons), ("C", True), load) - - def test_literal_add_tid_clear_is_tier_a(self): - lines = self.program(self.NO_TID, "buffer_load_dword v6, off, s[0:3], 0") - (tier, reasons, _), _ = meta_of("vs_no_tid", lines) - self.assertEqual((tier, reasons), ("A", [])) - - def test_idxen_ignores_add_tid(self): - lines = self.program(self.TID, "buffer_load_dword v6, v9, s[0:3], 0 idxen") - (tier, reasons, _), _ = meta_of("vs_idxen_tid", lines) - self.assertEqual((tier, reasons), ("A", [])) - - def test_literal_copied_through_another_sgpr_still_counts(self): - lines = vs(self.v_sharp(self.NO_TID)[:3] + ["s_mov_b32 s20, 0x31816fac", "s_mov_b32 s3, s20", - "buffer_load_dword v6, off, s[0:3], 0"]) - self.assertEqual(meta_of("vs_tid_copy", lines)[0][0], "C") - - def test_word3_built_by_other_scalar_ops_counts(self): - # rdna2spirv folds these into the literal word3; the analysis must see the same bit - head = ["s_mov_b32 s0, 0x1000", "s_mov_b32 s1, 0x80040000", "s_mov_b32 s2, 0x1000"] - load = "buffer_load_dword v6, off, s[0:3], 0" - for name, build, tier in ( - ("mov64_set", ["s_mov_b64 s[2:3], 0x31816fac00001000"], "C"), - ("mov64_clear", ["s_mov_b64 s[2:3], 0x31016fac00001000"], "A"), - ("mov64_pair_copy", ["s_mov_b64 s[20:21], 0x31816fac00001000", "s_mov_b64 s[2:3], s[20:21]"], "C"), - ("pack_set", ["s_pack_ll_b32_b16 s3, 0x6fac, 0x3181"], "C"), - ("pack_clear", ["s_pack_ll_b32_b16 s3, 0x6fac, 0x3101"], "A"), - ("bfm_set", ["s_bfm_b32 s3, 9, 23"], "C"), - ("bfm_clear", ["s_bfm_b32 s3, 3, 12"], "A"), - ("movk_clear", ["s_movk_i32 s3, 0x1234"], "A")): - lines = vs(head + (["s_mov_b32 s3, 0"] if name.startswith("mov64") else []) + build - + ["v_mov_b32_e32 v9, 0", load, "s_waitcnt vmcnt(0)"]) - self.assertEqual(meta_of("vs_w3_" + name, lines)[0][0], tier, name) - - def test_offen_tbuffer_and_store_format_follow_the_bit(self): - for access in ("buffer_load_dword v6, v9, s[0:3], 0 offen", - "tbuffer_load_format_x v6, off, s[0:3], 0 format:[BUF_FMT_32_FLOAT]", - "buffer_store_format_x v6, off, s[0:3], 0"): - (tier, reasons, _), _ = meta_of("vs_tid_variant", self.program(self.TID, access)) - self.assertEqual((tier, "lane-id" in reasons), ("C", True), access) - (tier, reasons, _), _ = meta_of("vs_notid_variant", self.program(self.NO_TID, access)) - self.assertEqual((tier, reasons), ("A", []), access) - - def test_stores_and_atomics_by_lane_are_tier_c(self): - for access in ("buffer_store_dword v6, off, s[0:3], 0", "buffer_atomic_add v6, off, s[0:3], 0"): - (tier, reasons, _), _ = meta_of("vs_tid_write", self.program(self.TID, access)) - self.assertEqual((tier, "lane-id" in reasons), ("C", True), access) - (tier, _, _), _ = meta_of("vs_notid_write", self.program(self.NO_TID, access)) - self.assertEqual(tier, "A", access) - - def test_run_time_v_sharp_is_assumed_to_have_the_bit_clear(self): - # the word3 comes from user data: nothing in the code says the bit is set (design.md, SHADER-10) - lines = vs(["buffer_load_dword v6, off, s[4:7], 0", "s_waitcnt vmcnt(0)"]) - self.assertEqual(meta_of("vs_runtime_vsharp", lines)[0][0], "A") - - -class Refusal(unittest.TestCase): - def test_error_mode_refuses_tier_c(self): - old = rdna2spirv.WAVE64_GRAPHICS - rdna2spirv.WAVE64_GRAPHICS = "error" - try: - with self.assertRaises(rdna2spirv.Unsupported) as cm: - translate_listing("ps_c_cnt", listing("ps_c_cnt", ps(["v_cmp_eq_u32_e32 vcc, 1, v0", - "s_bcnt1_i32_b64 s6, vcc", - "v_mov_b32_e32 v6, s6"]))) - self.assertIn("lane-count", str(cm.exception)) - finally: - rdna2spirv.WAVE64_GRAPHICS = old - - def test_off_mode_has_no_tier(self): - old = rdna2spirv.WAVE64_GRAPHICS - rdna2spirv.WAVE64_GRAPHICS = "off" - try: - translate_listing("ps_c_cnt", listing("ps_c_cnt", ps(["v_cmp_eq_u32_e32 vcc, 1, v0", - "s_bcnt1_i32_b64 s6, vcc", "v_mov_b32_e32 v6, s6"]))) - self.assertIsNone(rdna2spirv.translate.last_gen.w64g) - finally: - rdna2spirv.WAVE64_GRAPHICS = old - - -class GeometryRing(unittest.TestCase): - """TEST-251: a legacy GS's LDS write is an output slot from its offset alone (rdna2spirv.gs_ds drops the VGPR - address, the lane's GSVS area), so a lane id that only forms that address is no partition dependence; the data - written, and a lane id in a memory store's address, still are. GPU twins: gs_w64_a_ring, gs_w64_c_lane_id.""" - PRO = ["s_bfe_i32 s0, s3, 0x80008", "s_bfm_b64 exec, s0, 0", "s_cmp_eq_u32 s0, 64", "s_cselect_b64 exec, -1, exec", - "v_mbcnt_lo_u32_b32 v13, -1, 0", "v_mbcnt_hi_u32_b32 v13, -1, v13"] - EPI = ["s_sendmsg sendmsg(MSG_GS, GS_OP_EMIT, 0)", "s_sendmsg sendmsg(MSG_GS, GS_OP_CUT, 0)", - "s_sendmsg sendmsg(MSG_GS_DONE, GS_OP_NOP)", "s_endpgm"] - - def tier(self, body): - sys.path.insert(0, os.path.join(HERE, "..", "..", "runtime", "test", "shaders")) - import build # gs_container: gs_tri's ISG1/OSG1 - name = "gs_w64_ring_test" - translate_listing(name, listing(name, self.PRO + body + self.EPI), build.gs_container()) - w = rdna2spirv.translate.last_gen.w64g - return w["tier"], w["reasons"] - - def test_lane_id_in_the_ring_address_is_tier_a(self): - self.assertEqual(self.tier(["v_mul_u32_u24_e32 v12, 0x60, v13", "v_mov_b32_e32 v14, 0", - "ds_write2_b32 v12, v14, v14 offset0:0 offset1:1"]), ("A", [])) - - def test_lane_id_written_to_the_ring_is_tier_c(self): - self.assertEqual(self.tier(["v_mov_b32_e32 v12, 0", "ds_write2_b32 v12, v13, v13 offset0:0 offset1:1"]), - ("C", ["lane-id"])) - - def test_lane_id_in_a_memory_store_address_is_tier_c(self): - self.assertEqual(self.tier(["v_mov_b32_e32 v14, 0", "v_lshlrev_b32_e32 v12, 2, v13", - "buffer_store_dword v14, v12, s[4:7], 0 offen", - "ds_write2_b32 v14, v14, v14 offset0:0 offset1:1"]), ("C", ["lane-id"])) - - - - -def _ps_xy(lane): - """8x8 2x2-quad pixel coordinates per lane: lane 4k+{0,1,2,3} is TL, TR, BL, BR.""" - q, c = divmod(lane, 4) - return 2 * (q % 4) + (c & 1), 2 * (q // 4) + (c >> 1) - - -_SWIZZLE_OFFSETS = { - "offset:0x801b": "offset:swizzle(QUAD_PERM,3,2,1,0)", - "offset:0x41f": "offset:swizzle(SWAP,1)", - "offset:0x401f": "offset:swizzle(SWAP,16)", - "offset:0x1c": "offset:swizzle(BROADCAST,4,0)", -} - - -def _load_ps_w64_lines(name): - asm_path = os.path.join(os.path.dirname(HERE), "..", "runtime", "test", "shaders", f"{name}.asm") - out = [] - with open(asm_path, encoding="utf-8") as f: - for raw in f: - line = raw.strip() - if not line or line.startswith(";"): - continue - for hex_off, sym_off in _SWIZZLE_OFFSETS.items(): - line = line.replace(hex_off, sym_off) - out.append(line) - return out - - -def _run_ps_cut(asm, wave, push=None, memory=None): - words = [] - for half in range(64 // wave): - base = half * wave - res = wi.run_wave( - asm, - wave=wave, - push_constants=push, - inputs={0: lambda lane, b=base: ((_ps_xy(b + lane)[0] + 0.5) / 64.0, - (_ps_xy(b + lane)[1] + 0.5) / 64.0, 0.0, 0.0)}, - memory=memory, - ) - for o in res["outputs"]: - if o is None: # a killed lane exports nothing; the attachment keeps its clear value - words.append(None) - continue - mrt = o["%out_mrt0"] - words.append(tuple(v.bits if isinstance(v, wi.F) else v for v in mrt)) - return words - - -class PixelShaders(unittest.TestCase): - """TEST-722: run every runtime/test/shaders/ps_w64_*.asm fixture on spirv_wave_interp (wave 64 vs 2x32).""" - - def test_ps_w64_fixtures(self): - sys.path.insert(0, os.path.join(HERE, "..", "..", "runtime", "test", "shaders")) - import w64_graphics as wg - - ps_names = sorted(n for n in wg.FIXTURES if n.startswith("ps_w64_")) - self.assertGreaterEqual(len(ps_names), 17) # 17 when TEST-722 landed; new fixtures run here too - for name in ps_names: - with self.subTest(fixture=name): - ref_tier, ref_fn, env = wg.FIXTURES[name] - (tier, _, _), asm = meta_of(name, _load_ps_w64_lines(name)) - self.assertEqual(tier, ref_tier) - push = [int(x, 0) for x in env["VKH_SGPRS"].split(",")] if "VKH_SGPRS" in env else None - mem64 = {0: 0} if "VKH_HEAP" in env else None - mem32 = {0: 0} if "VKH_HEAP" in env else None - w64 = _run_ps_cut(asm, 64, push=push, memory=mem64) - for lane in range(64): - x, y = _ps_xy(lane) - exp = ref_fn(y * 64 + x) - if w64[lane] is None: - self.assertEqual(exp, (wg.CLEAR,) * 4, f"{name} wave64 lane {lane} was killed") - continue - for c in range(4): - if exp[c] is not None: - self.assertEqual(w64[lane][c], exp[c], f"{name} wave64 lane {lane} c{c}") - if name == "ps_w64_c_readlane": - with self.assertRaises(wi.UnsupportedConstruct): - _run_ps_cut(asm, 32, push=push) - continue - w32 = _run_ps_cut(asm, 32, push=push, memory=mem32) - if tier in ("A", "B"): - self.assertEqual(w32, w64) - else: - self.assertNotEqual(w32, w64) - if "VKH_HEAP" in env: - self.assertEqual(mem64[0], 16) - self.assertEqual(mem32[0], 16) - slots64 = {mem64[0x100 + 4 * k] for k in range(16)} - slots32 = {mem32[0x100 + 4 * k] for k in range(16)} - self.assertEqual(len(slots64), 16) - self.assertEqual(slots64, slots32) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_wave64_halves_partial_dst.py b/tests/semantic/test_wave64_halves_partial_dst.py deleted file mode 100644 index 6f8260df2..000000000 --- a/tests/semantic/test_wave64_halves_partial_dst.py +++ /dev/null @@ -1,372 +0,0 @@ -"""Partial-destination and DPP mask soundness regression tests for tools/wave64_halves.py. - -Covers four classes of partial-destination / sub-wave writes where destinations keep prior -bits or lanes and must remain taint-preserving and non-uniform: - 1. SDWA dst_unused:UNUSED_PRESERVE with sub-dword dst_sel (BYTE_*, WORD_*) - 2. Single-half 16-bit VALU ops (integer VOP3/_nc_16/mad/min3 and float/cvt/mix f16 ops) - 3. DPP partial-lane writes (row_mask/bank_mask != 0xf, bound_ctrl:0) and half-asymmetric row_mask - 4. Partial d16 memory/image/LDS loads (global_*_d16*, buffer/tbuffer_*_d16_{x,xyz}, ds_read_*_d16*, d16 image_load) - -Including cases proving a divergent upper half plus a uniform partial write is never wrongly -proven uniform for the v_readlane_b32 rewrite in tools/rdna2spirv.py. - - python -I tests/semantic/test_wave64_halves_partial_dst.py -""" -import os -import sys -import unittest - -HERE = os.path.dirname(os.path.abspath(__file__)) -sys.path.insert(0, HERE) -import support # noqa: E402,F401 (sets the tools path) -import rdna2spirv # noqa: E402 -import wave64_halves # noqa: E402 -from test_wave64_halves import ( # noqa: E402 - meta_of, - out_param, - run_cut, - size, - vs, -) -from support import translate_listing # noqa: E402 - - -def _meta_of_vop3(name, lines): - """Like test_wave64_halves.meta_of, giving VOP3-only *_nc_*16 ops an 8-byte encoding.""" - raw = f"; {name} synthetic\n" - for text in lines: - nbytes = 8 if text.split()[0].startswith("v_add_nc_") else size(text) - raw += f"\t{text} ; encoding: [{','.join(['0x00'] * nbytes)}]\n" - asm = translate_listing(name, raw.encode()) - w = rdna2spirv.translate.last_gen.w64g - return (w["tier"], w["reasons"], w["idioms"]) if w else (None, [], []), asm - - -class PartialDestSoundnessTests(unittest.TestCase): - def assert_tier_c_and_diverges(self, name, body, contains=None, push=None, meta_fn=meta_of): - lines = vs(body) - (tier, reasons, _), asm = meta_fn(name, lines) - self.assertEqual(tier, "C", f"{name}: expected tier C, got {tier} (reasons={reasons})") - if contains is not None: - self.assertTrue(set(contains) <= set(reasons), f"{name}: reasons {reasons} lack {contains}") - whole = out_param(run_cut(asm, 64, push)) - halves = out_param(run_cut(asm, 32, push)) - self.assertNotEqual(whole, halves, f"{name}: expected 1x64 and 2x32 outputs to diverge") - - def assert_tier_a_and_agrees(self, name, body, push=None): - lines = vs(body) - (tier, reasons, _), asm = meta_of(name, lines) - self.assertEqual(tier, "A", f"{name}: expected tier A, got {tier} (reasons={reasons})") - self.assertEqual(out_param(run_cut(asm, 64, push)), out_param(run_cut(asm, 32, push)), name) - - def assert_readlane_not_uniform(self, name, body, idiom="readlane-uniform"): - lines = vs(body) - (tier, reasons, idioms), asm = meta_of(name, lines) - self.assertEqual(tier, "C", f"{name}: expected tier C, got {tier} (reasons={reasons}, idioms={idioms})") - self.assertIn("cross-lane", reasons, f"{name}: reasons={reasons}") - self.assertNotIn(idiom, idioms, f"{name}: idioms={idioms}") - whole = out_param(run_cut(asm, 64)) - halves = out_param(run_cut(asm, 32)) - self.assertTrue(all(w == whole[0] for w in whole), f"{name}: whole wave readlane not broadcast: {whole[:4]}") - self.assertNotEqual(whole, halves, f"{name}: expected 1x64 and 2x32 readlane outputs to diverge") - - # -- 1. SDWA dst_unused:UNUSED_PRESERVE - def test_sdwa_unused_preserve_keeps_prior_taint(self): - for tag, sel, sh in (("byte0", "BYTE_0", 8), ("word0", "WORD_0", 16), ("word1", "WORD_1", 0)): - setup = [ - "v_mbcnt_lo_u32_b32 v6, -1, 0", - "v_mbcnt_hi_u32_b32 v6, -1, v6", - ] - if sh: - setup.append(f"v_lshlrev_b32_e32 v6, {sh}, v6") - self.assert_tier_c_and_diverges(f"vs_sdwa_preserve_{tag}", setup + [ - f"v_mov_b32_sdwa v6, 7 dst_sel:{sel} dst_unused:UNUSED_PRESERVE src0_sel:DWORD", - ], contains=["lane-id"]) - - def test_sdwa_unused_preserve_blocks_uniform_readlane(self): - self.assert_readlane_not_uniform("vs_sdwa_preserve_readlane", [ - "v_lshlrev_b32_e32 v10, 8, v0", - "v_mov_b32_sdwa v10, s4 dst_sel:BYTE_0 dst_unused:UNUSED_PRESERVE src0_sel:DWORD", - "v_readlane_b32 s6, v10, 0", - "v_mov_b32_e32 v6, s6", - ], idiom="readlane-uniform") - self.assert_readlane_not_uniform("vs_sdwa_preserve_word_readlane", [ - "v_lshlrev_b32_e32 v10, 16, v0", - "v_mov_b32_sdwa v10, s4 dst_sel:WORD_0 dst_unused:UNUSED_PRESERVE src0_sel:DWORD", - "v_readlane_b32 s6, v10, 0", - "v_mov_b32_e32 v6, s6", - ], idiom="readlane-uniform") - self.assert_readlane_not_uniform("vs_sdwa_preserve_readfirstlane", [ - "v_lshlrev_b32_e32 v10, 8, v0", - "v_mov_b32_sdwa v10, s4 dst_sel:BYTE_0 dst_unused:UNUSED_PRESERVE src0_sel:DWORD", - "v_readfirstlane_b32 s6, v10", - "v_mov_b32_e32 v6, s6", - ], idiom="readfirstlane-uniform") - - def test_sdwa_clean_controls(self): - for tag, mod in ( - ("pad", "dst_sel:BYTE_0 dst_unused:UNUSED_PAD src0_sel:DWORD"), - ("sext", "dst_sel:BYTE_0 dst_unused:UNUSED_SEXT src0_sel:DWORD"), - ("dword", "dst_sel:DWORD dst_unused:UNUSED_PRESERVE src0_sel:DWORD"), - ): - self.assert_tier_a_and_agrees(f"vs_sdwa_clean_{tag}", [ - "v_mbcnt_lo_u32_b32 v6, -1, 0", - "v_mbcnt_hi_u32_b32 v6, -1, v6", - f"v_mov_b32_sdwa v6, 7 {mod}", - ]) - - (tier, reasons, idioms), asm = meta_of("vs_sdwa_preserve_already_uniform", vs([ - "v_mov_b32_e32 v10, s4", - "v_mov_b32_sdwa v10, 5 dst_sel:BYTE_0 dst_unused:UNUSED_PRESERVE src0_sel:DWORD", - "v_readlane_b32 s6, v10, 0", - "v_mov_b32_e32 v6, s6", - ])) - self.assertEqual(tier, "B", f"reasons={reasons}, idioms={idioms}") - self.assertIn("readlane-uniform", idioms) - self.assertEqual(out_param(run_cut(asm, 64, [0x12345678])), out_param(run_cut(asm, 32, [0x12345678]))) - - # -- 2. Single-half 16-bit VALU ops - def test_single_half_int16_ops_keep_high_half_taint(self): - for tag, inst, mfn in ( - ("add_u16_e64", "v_add_u16_e64 v6, 1, s4", meta_of), - ("add_nc_u16", "v_add_nc_u16 v6, 1, s4", _meta_of_vop3), - ("mad_u16", "v_mad_u16 v6, 1, 2, 3", meta_of), - ("min3_u16", "v_min3_u16 v6, 1, 2, 3", meta_of), - ): - self.assert_tier_c_and_diverges(f"vs_16_{tag}", [ - "v_mbcnt_lo_u32_b32 v6, -1, 0", - "v_mbcnt_hi_u32_b32 v6, -1, v6", - "v_lshlrev_b32_e32 v6, 16, v6", - inst, - ], contains=["lane-id"], meta_fn=mfn) - - def test_single_half_int16_blocks_uniform_readlane(self): - self.assert_readlane_not_uniform("vs_u16_e64_readlane", [ - "v_lshlrev_b32_e32 v10, 16, v0", - "v_add_u16_e64 v10, 1, s4", - "v_readlane_b32 s6, v10, 0", - "v_mov_b32_e32 v6, s6", - ], idiom="readlane-uniform") - self.assert_readlane_not_uniform("vs_u16_e64_readfirstlane", [ - "v_lshlrev_b32_e32 v10, 16, v0", - "v_add_u16_e64 v10, 1, s4", - "v_readfirstlane_b32 s6, v10", - "v_mov_b32_e32 v6, s6", - ], idiom="readfirstlane-uniform") - - def test_single_half_f16_ops_keep_taint_and_block_uniform_readlane(self): - for tag, inst in ( - ("add_f16", "v_add_f16_e32 v6, 1.0, s4"), - ("cvt_f16_f32", "v_cvt_f16_f32_e32 v6, s4"), - ("fma_mixlo_f16", "v_fma_mixlo_f16 v6, s4, s4, s4"), - ("frexp_mant_f16", "v_frexp_mant_f16 v6, s4"), - ): - (tier, reasons, _), _ = meta_of(f"vs_f16_{tag}", vs([ - "v_mbcnt_lo_u32_b32 v6, -1, 0", - "v_mbcnt_hi_u32_b32 v6, -1, v6", - "v_lshlrev_b32_e32 v6, 16, v6", - inst, - ])) - self.assertEqual(tier, "C", f"{tag}: expected tier C, got {tier} (reasons={reasons})") - self.assertIn("lane-id", reasons, f"{tag}: reasons={reasons}") - - (tier, reasons, idioms), _ = meta_of("vs_add_f16_readlane", vs([ - "v_lshlrev_b32_e32 v10, 16, v0", - "v_add_f16_e32 v10, 1.0, s4", - "v_readlane_b32 s6, v10, 0", - "v_mov_b32_e32 v6, s6", - ])) - self.assertEqual(tier, "C", f"expected tier C, got {tier} (reasons={reasons}, idioms={idioms})") - self.assertIn("cross-lane", reasons) - self.assertNotIn("readlane-uniform", idioms) - - def test_vop3_encoding_distinguishes_int16_partial_vs_vop2_e32(self): - v6 = {"k": "vgpr", "r": 6, "n": 1} - imm1 = {"k": "imm", "v": 1} - s4 = {"k": "sgpr", "r": 4, "n": 1} - _, srcs_vop3, _, _ = wave64_halves.operands({ - "op": "v_add_u16", "args": [v6, imm1, s4], "mods": [], "enc": "D703000600000881", - }) - _, srcs_vop2, _, _ = wave64_halves.operands({ - "op": "v_add_u16", "args": [v6, imm1, s4], "mods": [], "enc": "06000881", - }) - self.assertIs(srcs_vop3[0], v6) - self.assertNotIn(v6, srcs_vop2) - - def test_16bit_clean_controls(self): - self.assert_tier_a_and_agrees("vs_u16_e32_clean", [ - "v_mbcnt_lo_u32_b32 v6, -1, 0", - "v_mbcnt_hi_u32_b32 v6, -1, v6", - "v_lshlrev_b32_e32 v6, 16, v6", - "v_add_u16_e32 v6, 1, s4", - ]) - - for tag, inst in ( - ("pack_b32_f16", "v_pack_b32_f16 v6, s4, s4"), - ("cvt_pk_u16_u32", "v_cvt_pk_u16_u32 v6, s4, s4"), - ): - (tier, reasons, _), _ = meta_of(f"vs_16_clean_{tag}", vs([ - "v_mbcnt_lo_u32_b32 v6, -1, 0", - "v_mbcnt_hi_u32_b32 v6, -1, v6", - inst, - ])) - self.assertEqual(tier, "A", f"{tag}: expected tier A, got {tier} (reasons={reasons})") - - (tier, reasons, idioms), asm = meta_of("vs_u16_e64_already_uniform", vs([ - "v_mov_b32_e32 v10, s4", - "v_add_u16_e64 v10, 1, s4", - "v_readlane_b32 s6, v10, 0", - "v_mov_b32_e32 v6, s6", - ])) - self.assertEqual(tier, "B", f"reasons={reasons}, idioms={idioms}") - self.assertIn("readlane-uniform", idioms) - self.assertEqual(out_param(run_cut(asm, 64, [0x00010002])), out_param(run_cut(asm, 32, [0x00010002]))) - - # -- 3. DPP partial-lane preservation and asymmetric row_mask - def test_dpp_asymmetric_row_mask_is_tier_c(self): - for rmask in ("0x3", "0x1", "0xc"): - self.assert_tier_c_and_diverges(f"vs_dpp_asym_{rmask}", [ - "v_mov_b32_e32 v6, 10", - "v_mov_b32_e32 v1, 99", - f"v_mov_b32_dpp v6, v1 quad_perm:[0,1,2,3] row_mask:{rmask} bank_mask:0xf bound_ctrl:1", - ], contains=["cross-lane"]) - - def test_dpp_partial_preserves_prior_taint(self): - self.assert_tier_c_and_diverges("vs_dpp_sym_row_mask_taint", [ - "v_mbcnt_lo_u32_b32 v6, -1, 0", - "v_mbcnt_hi_u32_b32 v6, -1, v6", - "v_mov_b32_e32 v1, 99", - "v_mov_b32_dpp v6, v1 quad_perm:[0,1,2,3] row_mask:0x5 bank_mask:0xf bound_ctrl:1", - ], contains=["lane-id"]) - self.assert_tier_c_and_diverges("vs_dpp_bank_mask_taint", [ - "v_mbcnt_lo_u32_b32 v6, -1, 0", - "v_mbcnt_hi_u32_b32 v6, -1, v6", - "v_mov_b32_e32 v1, 99", - "v_mov_b32_dpp v6, v1 quad_perm:[0,1,2,3] row_mask:0xf bank_mask:0x5 bound_ctrl:1", - ], contains=["lane-id"]) - self.assert_tier_c_and_diverges("vs_dpp_bound_ctrl0_taint", [ - "v_mbcnt_lo_u32_b32 v6, -1, 0", - "v_mbcnt_hi_u32_b32 v6, -1, v6", - "v_mov_b32_e32 v1, 99", - "v_mov_b32_dpp v6, v1 row_shl:1 row_mask:0xf bank_mask:0xf", - ], contains=["lane-id"]) - - def test_dpp_clean_controls(self): - self.assert_tier_a_and_agrees("vs_dpp_clean_sym_row_bank_mask", [ - "v_mov_b32_e32 v6, 10", - "v_mov_b32_e32 v1, 99", - "v_mov_b32_dpp v6, v1 quad_perm:[0,1,2,3] row_mask:0x5 bank_mask:0x5 bound_ctrl:1", - ]) - self.assert_tier_a_and_agrees("vs_dpp_clean_full_quad", [ - "v_mbcnt_lo_u32_b32 v6, -1, 0", - "v_mbcnt_hi_u32_b32 v6, -1, v6", - "v_mov_b32_e32 v1, 99", - "v_mov_b32_dpp v6, v1 quad_perm:[0,1,2,3] row_mask:0xf bank_mask:0xf bound_ctrl:1", - ]) - self.assert_tier_a_and_agrees("vs_dpp_clean_full_row_shl", [ - "v_mbcnt_lo_u32_b32 v6, -1, 0", - "v_mbcnt_hi_u32_b32 v6, -1, v6", - "v_mov_b32_e32 v1, 99", - "v_mov_b32_dpp v6, v1 row_shl:1 row_mask:0xf bank_mask:0xf bound_ctrl:1", - ]) - - # -- 4. Partial d16 loads and operands() edge cases - def test_partial_d16_loads_preserve_prior_taint(self): - for tag, body in ( - ("global_short_d16", [ - "v_mbcnt_lo_u32_b32 v6, -1, 0", - "v_mbcnt_hi_u32_b32 v6, -1, v6", - "v_lshlrev_b32_e32 v6, 16, v6", - "v_mov_b32_e32 v2, 0", - "global_load_short_d16 v6, v2, s[0:1]", - ]), - ("global_ubyte_d16_hi", [ - "v_mbcnt_lo_u32_b32 v6, -1, 0", - "v_mbcnt_hi_u32_b32 v6, -1, v6", - "v_mov_b32_e32 v2, 0", - "global_load_ubyte_d16_hi v6, v2, s[0:1]", - ]), - ("buf_fmt_d16_x", [ - "v_mbcnt_lo_u32_b32 v6, -1, 0", - "v_mbcnt_hi_u32_b32 v6, -1, v6", - "v_lshlrev_b32_e32 v6, 16, v6", - "v_mov_b32_e32 v2, 0", - "buffer_load_format_d16_x v6, v2, s[0:3], 0 offen", - ]), - ("buf_fmt_d16_xyz", [ - "v_mbcnt_lo_u32_b32 v7, -1, 0", - "v_mbcnt_hi_u32_b32 v7, -1, v7", - "v_lshlrev_b32_e32 v7, 16, v7", - "v_mov_b32_e32 v2, 0", - "buffer_load_format_d16_xyz v[6:7], v2, s[0:3], 0 offen", - ]), - ): - (tier, reasons, _), _ = meta_of(f"vs_d16_{tag}", vs(body)) - self.assertEqual(tier, "C", f"{tag}: expected tier C, got {tier} (reasons={reasons})") - self.assertIn("lane-id", reasons, f"{tag}: reasons={reasons}") - - (tier, reasons, _), _ = meta_of("vs_d16_clean_xy", vs([ - "v_mbcnt_lo_u32_b32 v6, -1, 0", - "v_mbcnt_hi_u32_b32 v6, -1, v6", - "v_lshlrev_b32_e32 v6, 16, v6", - "v_mov_b32_e32 v2, 0", - "buffer_load_format_d16_xy v6, v2, s[0:3], 0 offen", - ])) - self.assertEqual(tier, "A", f"expected tier A, got {tier} (reasons={reasons})") - - def test_operands_unit_d16_ds_image_and_cndmask_sdwa(self): - v6 = {"k": "vgpr", "r": 6, "n": 1} - v2 = {"k": "vgpr", "r": 2, "n": 1} - v3 = {"k": "vgpr", "r": 3, "n": 1} - s_img = {"k": "sgpr", "r": 0, "n": 8} - s_samp = {"k": "sgpr", "r": 8, "n": 4} - - for op in ("ds_read_u16_d16", "ds_read_u8_d16_hi"): - _, srcs, _, _ = wave64_halves.operands({"op": op, "args": [v6, v2], "mods": []}) - self.assertIs(srcs[0], v6, op) - - _, srcs_img1, _, _ = wave64_halves.operands({ - "op": "image_load", "args": [v6, v2, s_img, s_samp], "mods": ["dmask:0x1", "d16"], - }) - self.assertIs(srcs_img1[0], v6) - - _, srcs_img2, _, _ = wave64_halves.operands({ - "op": "image_load", "args": [v6, v2, s_img, s_samp], "mods": ["dmask:0x3", "d16"], - }) - self.assertNotIn(v6, srcs_img2) - - _, srcs_cnd, _, uses_cnd = wave64_halves.operands({ - "op": "v_cndmask_b32_sdwa", - "args": [v6, v2, v3], - "mods": ["dst_sel:BYTE_0", "dst_unused:UNUSED_PRESERVE"], - }) - self.assertIs(srcs_cnd[0], v6) - self.assertIn("vcc", uses_cnd) - - _, srcs_f16_dpp, _, _ = wave64_halves.operands({ - "op": "v_add_f16_dpp", - "args": [v6, v2, v3], - "mods": ["quad_perm:[0,1,2,3]", "row_mask:0xf", "bank_mask:0xf", "bound_ctrl:1"], - }) - self.assertIs(srcs_f16_dpp[0], v6) - - attr0 = {"k": "attr", "a": 0, "c": 0} - _, srcs_p2, _, _ = wave64_halves.operands({ - "op": "v_interp_p2_f16", "args": [v6, v2, attr0, v3], "mods": [], - }) - self.assertIs(srcs_p2[0], v6) - _, srcs_p1, _, _ = wave64_halves.operands({ - "op": "v_interp_p1ll_f16", "args": [v6, v2, attr0], "mods": [], - }) - self.assertNotIn(v6, srcs_p1) - - _, srcs_f16_sdwa_dword, _, _ = wave64_halves.operands({ - "op": "v_add_f16_sdwa", - "args": [v6, v2, v3], - "mods": ["dst_sel:DWORD", "dst_unused:UNUSED_PRESERVE"], - }) - self.assertNotIn(v6, srcs_f16_sdwa_dword) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_wave64_halves_readlane_uniform.py b/tests/semantic/test_wave64_halves_readlane_uniform.py deleted file mode 100644 index 6f15ec678..000000000 --- a/tests/semantic/test_wave64_halves_readlane_uniform.py +++ /dev/null @@ -1,43 +0,0 @@ -"""Regression tests for SHADER-314: v_readlane_b32 of a uniform VGPR with a tainted lane selector.""" -import os -import sys -import unittest - -HERE = os.path.dirname(os.path.abspath(__file__)) -ROOT = os.path.dirname(os.path.dirname(HERE)) -sys.path.insert(0, os.path.join(ROOT, "tools")) -sys.path.insert(0, HERE) - -import rdna2spirv # noqa: E402 -from test_wave64_halves import listing, ps, translate_listing # noqa: E402 - - -class ReadlaneUniformTaintedLaneTests(unittest.TestCase): - def test_uniform_vgpr_with_tainted_lane_is_tier_b(self): - asm = listing("ps_readlane_uniform_tainted_lane", ps([ - "v_mov_b32_e32 v5, s4", - "s_ff1_i32_b64 s6, exec", - "v_readlane_b32 s5, v5, s6", - "v_mov_b32_e32 v6, s5", - ])) - translate_listing("ps_readlane_uniform_tainted_lane", asm) - w = rdna2spirv.translate.last_gen.w64g - self.assertEqual(w["tier"], "B") - self.assertEqual(w["reasons"], []) - self.assertIn("readlane-uniform", w["idioms"]) - - def test_varying_vgpr_with_tainted_lane_stays_tier_c(self): - asm = listing("ps_readlane_varying_tainted_lane", ps([ - "v_mbcnt_lo_u32_b32 v5, -1, 0", - "s_ff1_i32_b64 s6, exec", - "v_readlane_b32 s5, v5, s6", - "v_mov_b32_e32 v6, s5", - ])) - translate_listing("ps_readlane_varying_tainted_lane", asm) - w = rdna2spirv.translate.last_gen.w64g - self.assertEqual(w["tier"], "C") - self.assertEqual(w["reasons"], ["first-lane"]) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_wave64_halves_soundness.py b/tests/semantic/test_wave64_halves_soundness.py deleted file mode 100644 index 0e12731cd..000000000 --- a/tests/semantic/test_wave64_halves_soundness.py +++ /dev/null @@ -1,418 +0,0 @@ -"""Soundness regression tests for tools/wave64_halves.py. - -Each regression checks a bug where an unsafe wave64 VS/PS/GS program used to pass as Tier A or B -(or lose a genuine vote SCC), together with clean control cases that must remain Tier A or B. -Vertex-shader cases using integer arithmetic also execute on spirv_wave_interp.py as one 64-lane -wave vs two 32-lane waves to prove the two runs actually diverge (or agree for clean controls). - - python -I tests/semantic/test_wave64_halves_soundness.py -""" -import os -import sys -import unittest - -HERE = os.path.dirname(os.path.abspath(__file__)) -sys.path.insert(0, HERE) -import support # noqa: E402,F401 (sets the tools path) -import rdna2spirv # noqa: E402 -from test_wave64_halves import ( # noqa: E402 - AGG_HEAD, - AGG_RANK, - meta_of, - out_param, - ps, - run_cut, - vs, -) - -ATOMIC = ["v_mov_b32_e32 v11, s6", "v_mov_b32_e32 v12, 0", - "buffer_atomic_add v11, v12, s[0:3], 0 offen glc", - "s_or_b64 exec, exec, s[14:15]"] -SLOT = ["v_readfirstlane_b32 s7, v11", "v_add_nc_u32_e32 v13, s7, {rank}", - "v_lshlrev_b32_e32 v13, 2, v13", - "buffer_store_dword v0, v13, s[0:3], 0 offen offset:256"] -ELECT_NARROWED = ["v_cmp_eq_u32_e32 vcc, 0, v10", "s_and_saveexec_b64 s[14:15], vcc"] - - -class SoundnessRegressions(unittest.TestCase): - def assert_tier_c_and_diverges(self, name, body, contains=None, push=None): - lines = vs(body) - (tier, reasons, _), asm = meta_of(name, lines) - self.assertEqual(tier, "C", f"{name}: expected tier C, got {tier} (reasons={reasons})") - if contains is not None: - self.assertTrue(set(contains) <= set(reasons), f"{name}: reasons {reasons} lack {contains}") - whole = out_param(run_cut(asm, 64, push)) - halves = out_param(run_cut(asm, 32, push)) - self.assertNotEqual(whole, halves, f"{name}: expected 1x64 and 2x32 outputs to diverge") - - def assert_ps_tier(self, name, body, tier, reasons=None, contains=None, idioms=None): - (got_tier, got_reasons, got_idioms), _ = meta_of(name, ps(body)) - self.assertEqual(got_tier, tier, f"{name}: got tier {got_tier}, reasons={got_reasons}, idioms={got_idioms}") - if reasons is not None: - self.assertEqual(sorted(got_reasons), sorted(reasons), name) - if contains is not None: - self.assertTrue(set(contains) <= set(got_reasons), f"{name}: reasons {got_reasons} lack {contains}") - if idioms is not None: - self.assertEqual(sorted(got_idioms), sorted(idioms), name) - - # -- RMW destinations and s_pack - def test_s_addk_i32_preserves_lane_count_taint(self): - self.assert_tier_c_and_diverges("vs_rmw_addk", [ - "v_cmp_lt_u32_e32 vcc, 4, v0", - "s_bcnt1_i32_b64 s6, vcc", - "s_addk_i32 s6, 1", - "v_mov_b32_e32 v6, s6", - ], contains=["lane-count"]) - - def test_s_mulk_i32_preserves_lane_count_taint(self): - self.assert_tier_c_and_diverges("vs_rmw_mulk", [ - "v_cmp_lt_u32_e32 vcc, 4, v0", - "s_bcnt1_i32_b64 s6, vcc", - "s_mulk_i32 s6, 3", - "v_mov_b32_e32 v6, s6", - ], contains=["lane-count"]) - - def test_s_bitset_preserves_lane_count_taint(self): - self.assert_tier_c_and_diverges("vs_rmw_bitset1", [ - "v_cmp_lt_u32_e32 vcc, 4, v0", - "s_bcnt1_i32_b64 s6, vcc", - "s_bitset1_b32 s6, 7", - "v_mov_b32_e32 v6, s6", - ], contains=["lane-count"]) - self.assert_tier_c_and_diverges("vs_rmw_bitset0", [ - "v_cmp_lt_u32_e32 vcc, 4, v0", - "s_bcnt1_i32_b64 s6, vcc", - "s_bitset0_b32 s6, 0", - "v_mov_b32_e32 v6, s6", - ], contains=["lane-count"]) - - def test_s_cmovk_i32_reads_vote_scc(self): - self.assert_tier_c_and_diverges("vs_rmw_cmovk", [ - "v_cmp_eq_u32_e32 vcc, 1, v0", - "s_cmp_lg_u64 vcc, 0", - "s_mov_b32 s5, 0", - "s_cmovk_i32 s5, 9", - "v_mov_b32_e32 v6, s5", - ], contains=["cross-lane"]) - - def test_s_cmov_b32_keeps_tainted_dst_when_scc_false(self): - self.assert_tier_c_and_diverges("vs_rmw_cmov_dst", [ - "v_cmp_lt_u32_e32 vcc, 4, v0", - "s_bcnt1_i32_b64 s6, vcc", - "s_mov_b32 s4, 0", - "s_cmp_eq_u32 s4, 1", - "s_cmov_b32 s6, 9", - "v_mov_b32_e32 v6, s6", - ], contains=["lane-count"]) - - def test_s_pack_is_not_no_dest(self): - self.assert_tier_c_and_diverges("vs_spack", [ - "v_cmp_lt_u32_e32 vcc, 4, v0", - "s_bcnt1_i32_b64 s6, vcc", - "s_pack_ll_b32_b16 s5, s6, 1", - "v_mov_b32_e32 v6, s5", - ], contains=["lane-count"]) - - def test_s_pack_behind_vote_is_tracked_as_stale_scalar(self): - self.assert_tier_c_and_diverges("vs_spack_stale", [ - "v_cmp_eq_u32_e32 vcc, 1, v0", - "s_mov_b32 s5, 7", - "s_cbranch_vccz 1", - "s_pack_ll_b32_b16 s5, 9, 2", - "v_mov_b32_e32 v6, s5", - ], contains=["stale-scalar"]) - - def test_v_dot4c_i32_i8_preserves_lane_id_taint(self): - self.assert_tier_c_and_diverges("vs_rmw_dot4c", [ - "v_mbcnt_lo_u32_b32 v6, -1, 0", - "v_mbcnt_hi_u32_b32 v6, -1, v6", - "v_dot4c_i32_i8 v6, v5, v5", - ], contains=["lane-id"]) - - def test_v_fmac_f32_on_lane_id_does_not_become_uniform(self): - self.assert_ps_tier("ps_rmw_fmac_uniform", [ - "v_mbcnt_lo_u32_b32 v6, -1, 0", - "v_mbcnt_hi_u32_b32 v6, -1, v6", - "v_fmac_f32_e32 v6, 0, v5", - "v_readfirstlane_b32 s5, v6", - "v_mov_b32_e32 v6, s5", - ], "C", contains=["lane-id"]) - - def test_v_swap_b32_swaps_taint_into_exported_vgpr(self): - self.assert_tier_c_and_diverges("vs_vswap", [ - "v_mbcnt_lo_u32_b32 v7, -1, 0", - "v_mbcnt_hi_u32_b32 v7, -1, v7", - "v_swap_b32 v6, v7", - ], contains=["lane-id"]) - - # -- SCC-preserving scalar ops - def test_s_mul_i32_does_not_clear_vote_scc(self): - self.assert_tier_c_and_diverges("vs_scc_mul", [ - "v_cmp_eq_u32_e32 vcc, 1, v0", - "s_cmp_lg_u64 vcc, 0", - "s_mul_i32 s8, 3, 4", - "s_cselect_b32 s5, 1, 0", - "v_mov_b32_e32 v6, s5", - ], contains=["cross-lane"]) - - def test_s_ff1_i32_b64_does_not_turn_tainted_scc_into_exec_vote(self): - self.assert_tier_c_and_diverges("vs_ff1_preserves_scc", [ - "v_cmp_lt_u32_e32 vcc, 4, v0", - "s_bcnt1_i32_b64 s6, vcc", - "s_cmp_eq_u32 s6, 59", - "s_ff1_i32_b64 s7, exec", - "s_cbranch_scc0 1", - "v_mov_b32_e32 v6, 9", - ], contains=["lane-count"]) - - # -- s_bfm_b64 uses per-half wave_lane (0..31) - def test_s_bfm_b64_lane_mask_is_lane_id_tainted(self): - self.assert_tier_c_and_diverges("vs_sbfm64", [ - "s_bfm_b64 s[14:15], 4, 0", - "v_cndmask_b32_e64 v6, 0, 1, s[14:15]", - ], contains=["lane-id"]) - - # -- Dynamic register indexing (movrel) - def test_v_movrels_b32_with_tainted_m0(self): - self.assert_tier_c_and_diverges("vs_vmovrels_m0", [ - "v_and_b32_e32 v4, 15, v0", - "v_cmp_eq_u32_e32 vcc, 1, v4", - "s_bcnt1_i32_b64 s6, vcc", - "v_mov_b32_e32 v10, 10", - "v_mov_b32_e32 v12, 12", - "s_mov_b32 m0, s6", - "v_movrels_b32 v6, v8", - ], contains=["lane-count"]) - - def test_s_movrels_b32_reads_tainted_and_stale_sgpr(self): - self.assert_ps_tier("ps_smovrels_tainted", [ - "v_cmp_eq_u32_e32 vcc, 1, v0", - "s_bcnt1_i32_b64 s9, vcc", - "s_mov_b32 m0, 3", - "s_movrels_b32 s5, s6", - "v_mov_b32_e32 v6, s5", - ], "C", contains=["lane-count"]) - lines = [ - "s_wqm_b64 exec, exec", - "v_mov_b32_e32 v5, 0", - "v_mov_b32_e32 v6, 0", - "v_mov_b32_e32 v7, 0", - "v_cmp_eq_u32_e32 vcc, 1, v0", - "s_mov_b32 s9, 1", - "s_cbranch_vccz 1", - "s_mov_b32 s9, 2", - "s_mov_b32 m0, 3", - "s_movrels_b32 s5, s6", - "v_mov_b32_e32 v6, s5", - "exp mrt0 v6, v7, v5, v5 done vm", - "s_endpgm", - ] - (got_tier, got_reasons, _), _ = meta_of("ps_smovrels_stale", lines) - self.assertEqual(got_tier, "C", f"ps_smovrels_stale: got {got_tier}, reasons={got_reasons}") - self.assertIn("stale-scalar", got_reasons) - - def test_v_movreld_b32_with_tainted_m0_or_src(self): - self.assert_tier_c_and_diverges("vs_vmovreld_m0", [ - "v_and_b32_e32 v4, 15, v0", - "v_cmp_eq_u32_e32 vcc, 1, v4", - "s_bcnt1_i32_b64 s6, vcc", - "s_sub_i32 s6, s6, 2", - "s_mov_b32 m0, s6", - "v_mov_b32_e32 v5, 9", - "v_movreld_b32 v6, v5", - ], contains=["lane-count"]) - self.assert_tier_c_and_diverges("vs_vmovreld_src", [ - "v_mbcnt_lo_u32_b32 v5, -1, 0", - "v_mbcnt_hi_u32_b32 v5, -1, v5", - "s_mov_b32 m0, 0", - "v_movreld_b32 v6, v5", - ], contains=["lane-id"]) - - def test_v_movreld_b32_nonzero_offset_propagates_taint(self): - self.assert_tier_c_and_diverges("vs_vmovreld_src_off1", [ - "v_mbcnt_lo_u32_b32 v8, -1, 0", - "v_mbcnt_hi_u32_b32 v8, -1, v8", - "s_mov_b32 m0, 1", - "v_movreld_b32 v5, v8", - ], contains=["lane-id"]) - w64g = rdna2spirv.translate.last_gen.w64g - self.assertIn("exp", [op for _, _, op in w64g["sites"]], - f"expected downstream exp sink to observe propagated taint: {w64g['sites']}") - - def test_v_add_co_ci_u32_reads_implicit_vcc(self): - self.assert_tier_c_and_diverges("vs_add_co_ci_vcc", [ - "v_mbcnt_lo_u32_b32 v4, -1, 0", - "v_mbcnt_hi_u32_b32 v4, -1, v4", - "v_cmp_lt_u32_e32 vcc, 31, v4", - "v_add_co_ci_u32_e32 v6, vcc, 0, v6", - ], contains=["lane-id"]) - - def test_v_swap_b32_under_narrowed_exec_is_not_uniform(self): - self.assert_tier_c_and_diverges("vs_vswap_masked_uniform", [ - "v_mov_b32_e32 v5, v0", - "v_mov_b32_e32 v7, 11", - "v_cmp_eq_u32_e32 vcc, 0, v0", - "s_and_saveexec_b64 s[12:13], vcc", - "v_swap_b32 v5, v7", - "s_mov_b64 exec, s[10:11]", - "v_readfirstlane_b32 s20, v5", - "v_mov_b32_e32 v6, s20", - ], contains=["cross-lane"]) - - def test_s_movrels_b32_reads_mask_sgpr_as_data(self): - self.assert_tier_c_and_diverges("vs_smovrels_mask", [ - "s_mov_b32 m0, 5", - "s_movrels_b32 s5, s6", - "v_mov_b32_e32 v6, s5", - ], contains=["cross-lane"]) - - # -- saveexec / wrexec / s_andn2_b64 / _b32 mask-half - def test_s_andn1_saveexec_on_elected_mask_is_refused(self): - body = (AGG_HEAD + ["s_bcnt1_i32_b64 s6, exec"] + AGG_RANK - + ["v_cmp_eq_u32_e32 vcc, 0, v10", "s_andn1_saveexec_b64 s[14:15], vcc"] - + ATOMIC + [x.format(rank="v10") for x in SLOT] + ["s_mov_b64 exec, s[10:11]"]) - self.assert_ps_tier("ps_andn1_saveexec_elect", body, "C", contains=["tainted-exec"]) - - def test_s_andn2_saveexec_flips_out_of_elected_region(self): - body = (AGG_HEAD + ["s_bcnt1_i32_b64 s6, exec"] + AGG_RANK + ELECT_NARROWED - + ["s_andn2_saveexec_b64 s[16:17], s[14:15]"] - + ATOMIC + [x.format(rank="v10") for x in SLOT] + ["s_mov_b64 exec, s[10:11]"]) - self.assert_ps_tier("ps_andn2_saveexec_flip", body, "C", contains=["lane-count"]) - - def test_s_andn1_wrexec_on_elected_mask_is_refused(self): - body = (AGG_HEAD + ["s_bcnt1_i32_b64 s6, exec"] + AGG_RANK - + ["v_cmp_eq_u32_e32 vcc, 0, v10", "s_andn1_wrexec_b64 s[14:15], vcc"] - + ATOMIC + [x.format(rank="v10") for x in SLOT] + ["s_mov_b64 exec, s[10:11]"]) - self.assert_ps_tier("ps_andn1_wrexec_elect", body, "C", contains=["tainted-exec"]) - - def test_s_andn2_wrexec_writes_new_exec_not_old(self): - self.assert_tier_c_and_diverges("vs_andn2_wrexec_saved", [ - "v_mov_b32_e32 v5, v0", - "v_cmp_eq_u32_e32 vcc, 0, v0", - "s_andn2_wrexec_b64 s[12:13], vcc", - "s_mov_b64 exec, s[12:13]", - "v_mov_b32_e32 v5, 7", - "s_mov_b64 exec, s[10:11]", - "v_readfirstlane_b32 s20, v5", - "v_mov_b32_e32 v6, s20", - ], contains=["cross-lane"]) - - def test_s_andn1_wrexec_writes_new_exec_not_old(self): - self.assert_tier_c_and_diverges("vs_andn1_wrexec_saved", [ - "v_mov_b32_e32 v5, v0", - "v_cmp_eq_u32_e32 vcc, 0, v0", - "s_andn1_wrexec_b64 s[12:13], vcc", - "s_mov_b64 exec, s[12:13]", - "v_mov_b32_e32 v5, 7", - "s_mov_b64 exec, s[10:11]", - "v_readfirstlane_b32 s20, v5", - "v_mov_b32_e32 v6, s20", - ], contains=["cross-lane"]) - - def test_s_and_saveexec_b32_is_mask_half(self): - self.assert_ps_tier("ps_saveexec_b32", [ - "s_mov_b32 s14, 1", - "s_and_saveexec_b32 s12, s14", - ], "C", contains=["mask-half"]) - - def test_s_andn2_b64_exec_rules(self): - self.assert_ps_tier("ps_andn2_exec_elect", ( - AGG_HEAD + AGG_RANK + ["v_cmp_eq_u32_e32 vcc, 0, v10", "s_andn2_b64 exec, exec, vcc", - "s_mov_b64 exec, s[10:11]"] - ), "C", contains=["tainted-exec"]) - self.assert_ps_tier("ps_andn2_exec_flip", ( - AGG_HEAD + ["s_bcnt1_i32_b64 s6, exec"] + AGG_RANK + ELECT_NARROWED - + ["s_andn2_b64 exec, s[14:15], exec"] - + ATOMIC + [x.format(rank="v10") for x in SLOT] + ["s_mov_b64 exec, s[10:11]"] - ), "C", contains=["lane-count"]) - - def test_s_andn2_exec_in_vote_branch_is_unsafe(self): - for tag, op in (("saveexec", "s_andn2_saveexec_b64"), ("wrexec", "s_andn2_wrexec_b64")): - self.assert_tier_c_and_diverges(f"vs_vote_{tag}_andn2", [ - "v_cmp_eq_u32_e32 vcc, 1, v0", - "s_cbranch_vccz 1", - f"{op} s[14:15], vcc", - "v_mov_b32_e32 v6, 9", - "s_mov_b64 exec, s[10:11]", - ], contains=["unsafe-vote-branch"]) - - def test_s_andn1_exec_in_vote_branch_is_unsafe(self): - for tag, op in (("saveexec", "s_andn1_saveexec_b64"), ("wrexec", "s_andn1_wrexec_b64")): - self.assert_tier_c_and_diverges(f"vs_vote_{tag}_andn1", [ - "v_cmp_eq_u32_e32 vcc, 1, v0", - "s_cbranch_vccz 3", - f"{op} s[14:15], vcc", - "v_mov_b32_e32 v6, 9", - "s_mov_b64 exec, s[10:11]", - ], contains=["unsafe-vote-branch"]) - - # -- Clean controls (no false positives) - # SHADER-820 (@shdann): a vote's SCC tag survived a new value in the voted mask register. v_cmp into the pair - # or VCC and s_mov_b64 don't write SCC, so s_cbranch_scc0 votes on the old mask while the run side narrows - # EXEC to the new one: one 64-lane wave writes v6 in lanes 20..63, two 32-lane waves skip the upper half. - STALE_VOTE_HEAD = ["v_cmp_gt_u32_e32 vcc, 20, v0", "s_and_b64 s[20:21], exec, vcc", "s_cmp_lg_u64 s[20:21], 0"] - STALE_VOTE_TAIL = ["s_cbranch_scc0 3", "s_and_b64 exec, exec, s[20:21]", "v_add_nc_u32_e32 v6, 3, v0", - "s_mov_b64 exec, s[10:11]"] - - def test_vote_on_a_rewritten_pair_is_unsafe(self): - self.assert_tier_c_and_diverges("vs_stale_vote_vcmp", self.STALE_VOTE_HEAD + [ - "v_cmp_gt_u32_e64 s[20:21], 64, v0"] + self.STALE_VOTE_TAIL) - self.assert_tier_c_and_diverges("vs_stale_vote_mov", self.STALE_VOTE_HEAD + [ - "s_mov_b64 s[20:21], exec"] + self.STALE_VOTE_TAIL) - - def test_vote_on_a_rewritten_vcc_is_unsafe(self): - self.assert_tier_c_and_diverges("vs_stale_vote_vcc", [ - "v_cmp_gt_u32_e32 vcc, 20, v0", "s_and_b64 vcc, exec, vcc", "v_cmp_gt_u32_e32 vcc, 64, v0", - "s_cbranch_scc0 3", "s_and_saveexec_b64 s[18:19], vcc", "v_add_nc_u32_e32 v6, 3, v0", - "s_mov_b64 exec, s[18:19]"]) - - def test_vote_on_an_unchanged_or_revoted_mask_stays_a(self): - for name, body in ( - ("vs_vote_unchanged", self.STALE_VOTE_HEAD + self.STALE_VOTE_TAIL), - # the second s_and_b64 writes s[20:21] and votes on it (SCC = new mask != 0): its tag is the new one - ("vs_vote_revoted", self.STALE_VOTE_HEAD + ["v_cmp_gt_u32_e32 vcc, 40, v0", - "s_and_b64 s[20:21], exec, vcc"] + self.STALE_VOTE_TAIL)): - with self.subTest(name=name): - (tier, reasons, _), asm = meta_of(name, vs(body)) - self.assertEqual(tier, "A", f"{name}: got {tier}, reasons={reasons}") - self.assertEqual(out_param(run_cut(asm, 64)), out_param(run_cut(asm, 32)), name) - - def test_clean_controls_stay_invariant(self): - for name, body in ( - ("vs_clean_spack", ["s_pack_ll_b32_b16 s5, s4, 7", "v_mov_b32_e32 v6, s5"]), - ("vs_clean_rmw", ["s_mov_b32 s5, 3", "s_addk_i32 s5, 4", "s_mulk_i32 s5, 2", - "s_bitset1_b32 s5, 4", "s_cmp_eq_u32 s5, 14", "s_cmovk_i32 s5, 9", - "v_mov_b32_e32 v6, s5"]), - ("vs_clean_vswap", ["v_mbcnt_lo_u32_b32 v6, -1, 0", "v_mbcnt_hi_u32_b32 v6, -1, v6", - "v_mov_b32_e32 v8, 11", "v_swap_b32 v6, v8"]), - ("vs_clean_vmovrels", ["v_mov_b32_e32 v8, 5", "s_mov_b32 m0, 0", "v_movrels_b32 v6, v8"]), - ("vs_clean_vmovreld", ["v_mov_b32_e32 v5, 9", "s_mov_b32 m0, 0", "v_movreld_b32 v6, v5"]), - ("vs_clean_vmovreld_off1", ["v_mov_b32_e32 v8, 9", "s_mov_b32 m0, 1", "v_movreld_b32 v5, v8"]), - ("vs_clean_andn2_saveexec", ["v_cmp_eq_u32_e32 vcc, 1, v0", - "s_and_saveexec_b64 s[12:13], vcc", - "v_mov_b32_e32 v6, 5", - "s_andn2_saveexec_b64 s[12:13], s[12:13]", - "v_mov_b32_e32 v6, 7", - "s_mov_b64 exec, s[10:11]"]), - ): - lines = vs(body) - (tier, reasons, _), asm = meta_of(name, lines) - self.assertEqual(tier, "A", f"{name}: got {tier}, reasons={reasons}") - self.assertEqual(out_param(run_cut(asm, 64)), out_param(run_cut(asm, 32)), name) - - lines = vs(["s_mov_b32 s8, 5", "s_mov_b32 m0, 0", "s_movrels_b32 s5, s8", "v_mov_b32_e32 v6, s5"], - prologue=["s_wqm_b64 exec, exec"]) - (tier, reasons, _), asm = meta_of("vs_clean_smovrels", lines) - self.assertEqual(tier, "A", f"vs_clean_smovrels: got {tier}, reasons={reasons}") - self.assertEqual(out_param(run_cut(asm, 64)), out_param(run_cut(asm, 32)), "vs_clean_smovrels") - - self.assert_ps_tier("ps_clean_fmac_uniform", [ - "v_mov_b32_e32 v5, s4", - "v_fmac_f32_e32 v5, 0, v5", - "v_readfirstlane_b32 s5, v5", - "v_mov_b32_e32 v6, s5", - ], "B", reasons=[], idioms=["readfirstlane-uniform"]) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_wave64_mov_b32_cross_half.py b/tests/semantic/test_wave64_mov_b32_cross_half.py deleted file mode 100644 index 9bc48278d..000000000 --- a/tests/semantic/test_wave64_mov_b32_cross_half.py +++ /dev/null @@ -1,176 +0,0 @@ -"""Wave64: cross-half s_mov_b32 lane-mask moves (exec_lo/hi, vcc_lo/hi, half-mask SGPRs). - -In RDNA2 wave64, exec_lo / vcc_lo / s_lo hold bits for lanes 0..31 and exec_hi / vcc_hi / s_hi hold bits for -lanes 32..63. A cross-half move such as `s_mov_b32 exec_lo, exec_hi` or `s_mov_b32 vcc_hi, exec_lo` copies the -32-bit mask from one half into the other half while leaving the untouched half intact. - -Each case builds distinct 64-bit masks in VCC, EXEC, and s[12:13] from push constants, runs one cross-half -`s_mov_b32`, and observes all 64 lanes via EXEC-guarded stores or `v_cndmask_b32` + `s_cbranch_vccz` using -`spirv_mini_interp.run_workgroup`. Standard library only; no LLVM, GPU, or game data. - - python -I -m unittest discover -s tests/semantic -p "test_wave64_mov_b32_cross_half.py" -v -""" -import gc -import os -import struct -import sys -import tempfile -import unittest -import warnings - -HERE = os.path.dirname(os.path.abspath(__file__)) -ROOT = os.path.dirname(os.path.dirname(HERE)) -TOOLS_DIR = os.environ.get("LEONIDA_TOOLS_DIR") or os.path.join(ROOT, "tools") - -sys.dont_write_bytecode = True -for p in (HERE, TOOLS_DIR): - if p not in sys.path: - sys.path.insert(0, p) - -import rdna2spirv # noqa: E402 -import spirv_asm # noqa: E402 -import spirv_mini_interp as si # noqa: E402 - -M32 = 0xFFFFFFFF -STUB_DXBC = b"DXBC" + bytes(24) + struct.pack("> l) & 1 else 0 for l in range(64)] - - -class Wave64MovB32CrossHalf(unittest.TestCase): - # Distinct bit patterns for EXEC (lo/hi), VCC (lo/hi), and s[12:13] (lo/hi). - EXEC_LO, EXEC_HI = 0x0000000F, 0x00000003 - VCC_LO, VCC_HI = 0x00000055, 0x000000AA - S_LO, S_HI = 0x0000001F, 0x000000C0 - - def _setup(self): - # s[12:13] <- (s8, s9), EXEC <- (s4, s5) via vcc, then VCC <- (s6, s7) - # Note: build s[12:13] and VCC while EXEC is all-ones, then set EXEC last. - return ( - build_mask_into_vcc("s8", "s9") - + [("s_and_b64 s[12:13], vcc, exec", 4)] - + build_mask_into_vcc("s4", "s5") - + [("s_and_b64 s[14:15], vcc, exec", 4)] - + build_mask_into_vcc("s6", "s7") - + [("s_mov_b64 exec, s[14:15]", 4)] - ) - - def _run_exec_case(self, name, mov_insn): - lines = ( - self._setup() - + [(mov_insn, 4)] - + [ - ("v_mov_b32_e32 v6, 0", 4), - ("s_mov_b64 s[16:17], exec", 4), - ("s_mov_b64 exec, -1", 4), - ("v_mov_b32_e32 v6, 0", 4), - ("s_mov_b64 exec, s[16:17]", 4), - ("v_mov_b32_e32 v6, 1", 4), - ("s_mov_b64 exec, -1", 4), - ("v_lshlrev_b32_e32 v5, 2, v0", 4), - ("buffer_store_dword v6, v5, s[0:3], 0 offen", 8), - ("s_endpgm", 4), - ] - ) - spv = translate_cs(name, lines) - binary = spirv_asm.assemble(spv) - self.assertGreater(len(binary), 0) - return run_cs(spv, self.EXEC_LO, self.EXEC_HI, self.VCC_LO, self.VCC_HI, self.S_LO, self.S_HI) - - def _run_vcc_case(self, name, mov_insn): - lines = ( - self._setup() - + [(mov_insn, 4)] - + [ - ("s_mov_b64 exec, -1", 4), - ("v_cndmask_b32_e64 v6, 0, 1, vcc", 8), - ("v_lshlrev_b32_e32 v5, 2, v0", 4), - ("buffer_store_dword v6, v5, s[0:3], 0 offen", 8), - ("s_endpgm", 4), - ] - ) - spv = translate_cs(name, lines) - binary = spirv_asm.assemble(spv) - self.assertGreater(len(binary), 0) - return run_cs(spv, self.EXEC_LO, self.EXEC_HI, self.VCC_LO, self.VCC_HI, self.S_LO, self.S_HI) - - def test_cross_half_exec_moves(self): - cases = ( - ("exec_lo_from_exec_hi", "s_mov_b32 exec_lo, exec_hi", self.EXEC_HI | (self.EXEC_HI << 32)), - ("exec_hi_from_exec_lo", "s_mov_b32 exec_hi, exec_lo", self.EXEC_LO | (self.EXEC_LO << 32)), - ("exec_lo_from_vcc_hi", "s_mov_b32 exec_lo, vcc_hi", self.VCC_HI | (self.EXEC_HI << 32)), - ("exec_hi_from_vcc_lo", "s_mov_b32 exec_hi, vcc_lo", self.EXEC_LO | (self.VCC_LO << 32)), - ("exec_lo_from_s_hi", "s_mov_b32 exec_lo, s13", self.S_HI | (self.EXEC_HI << 32)), - ("exec_hi_from_s_lo", "s_mov_b32 exec_hi, s12", self.EXEC_LO | (self.S_LO << 32)), - ) - for name, insn, expected in cases: - with self.subTest(case=name, insn=insn): - self.assertEqual(self._run_exec_case("cs_" + name, insn), mask_bits(expected)) - - def test_cross_half_vcc_moves(self): - cases = ( - ("vcc_lo_from_vcc_hi", "s_mov_b32 vcc_lo, vcc_hi", self.VCC_HI | (self.VCC_HI << 32)), - ("vcc_hi_from_vcc_lo", "s_mov_b32 vcc_hi, vcc_lo", self.VCC_LO | (self.VCC_LO << 32)), - ("vcc_lo_from_exec_hi", "s_mov_b32 vcc_lo, exec_hi", self.EXEC_HI | (self.VCC_HI << 32)), - ("vcc_hi_from_exec_lo", "s_mov_b32 vcc_hi, exec_lo", self.VCC_LO | (self.EXEC_LO << 32)), - ("vcc_lo_from_s_hi", "s_mov_b32 vcc_lo, s13", self.S_HI | (self.VCC_HI << 32)), - ("vcc_hi_from_s_lo", "s_mov_b32 vcc_hi, s12", self.VCC_LO | (self.S_LO << 32)), - ) - for name, insn, expected in cases: - with self.subTest(case=name, insn=insn): - self.assertEqual(self._run_vcc_case("cs_" + name, insn), mask_bits(expected)) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_wave64_saveexec_b32.py b/tests/semantic/test_wave64_saveexec_b32.py deleted file mode 100644 index 3af99bc56..000000000 --- a/tests/semantic/test_wave64_saveexec_b32.py +++ /dev/null @@ -1,216 +0,0 @@ -"""Value tests for wave64 s_*_saveexec_b32 and s_andn{1,2}_wrexec_b32. - -On RDNA2 in wave64 mode, the 32-bit SOP1 forms operate strictly on EXEC_LO (lanes 0..31): - - s__saveexec_b32 D, S0: D = EXEC_LO; EXEC_LO = f(S0, EXEC_LO); SCC = (EXEC_LO != 0) - - s_andn{1,2}_wrexec_b32 D, S0: EXEC_LO = f(S0, EXEC_LO); D = EXEC_LO; SCC = (EXEC_LO != 0) - - EXEC_HI (lanes 32..63) is untouched. - - D receives a MASK_LO value (lanes 0..31 only), so whole-wave consumers like s_bcnt1_i32_b32 - count only the low half. - - Cross-half operands (exec_hi / vcc_hi / MASK_HI sources, or exec_hi / vcc_hi destinations) - transfer the 32-bit word across halves. - -Verified through rdna2spirv -> spirv_mini_interp.run_workgroup (64 lanes) and spirv-as/spirv-val -(native wave64 and --wave64-emulate). Standard library only; no GPU or game data. -""" -import os -import shutil -import struct -import subprocess -import sys -import tempfile -import unittest - -HERE = os.path.dirname(os.path.abspath(__file__)) -if HERE not in sys.path: - sys.path.insert(0, HERE) - -import support # noqa: E402 -import spirv_mini_interp as si # noqa: E402 -import lane_masks as lm # noqa: E402 - -rdna2spirv = support.rdna2spirv -SPIRV_AS = shutil.which("spirv-as") -SPIRV_VAL = shutil.which("spirv-val") - -FSSM_64 = bytes(0x138) + struct.pack("<4I", 0x88, 64, 1, 1) -VSHARP = [0, 0, 0x1000, 0x31016FAC] -M32 = 0xFFFFFFFF - -EXEC_FUNCS = { - "and": lambda s, e: (s & e) & M32, - "or": lambda s, e: (s | e) & M32, - "xor": lambda s, e: (s ^ e) & M32, - "andn1": lambda s, e: ((~s) & e) & M32, - "andn2": lambda s, e: (s & (~e)) & M32, - "orn1": lambda s, e: ((~s) | e) & M32, - "orn2": lambda s, e: (s | (~e)) & M32, - "nand": lambda s, e: (~(s & e)) & M32, - "nor": lambda s, e: (~(s | e)) & M32, - "xnor": lambda s, e: (~(s ^ e)) & M32, -} - - -def validate_spirv(spv): - if not (SPIRV_AS and SPIRV_VAL): - return - with tempfile.TemporaryDirectory() as tmp: - asm = os.path.join(tmp, "s.spvasm") - bin_ = os.path.join(tmp, "s.spv") - with open(asm, "w", encoding="utf-8", newline="\n") as f: - f.write(spv) - r1 = subprocess.run([SPIRV_AS, "--target-env", "vulkan1.3", asm, "-o", bin_], - capture_output=True, text=True) - if r1.returncode != 0: - raise AssertionError(f"spirv-as failed:\n{r1.stderr}") - r2 = subprocess.run([SPIRV_VAL, "--target-env", "vulkan1.3", bin_], - capture_output=True, text=True) - if r2.returncode != 0: - raise AssertionError(f"spirv-val failed:\n{r2.stderr}") - - -def run_w64(lines, *, validate_emulate=True): - """Translate as native wave64, validate with spirv-val (and optionally --wave64-emulate), - and run all 64 lanes in spirv_mini_interp.run_workgroup.""" - prev = rdna2spirv.WAVE64_EMULATE - try: - rdna2spirv.WAVE64_EMULATE = False - spv = support.translate_lines("cs_w64_saveexec_b32", lines + ["s_endpgm"], fssm=FSSM_64) - assert rdna2spirv.translate.last_gen.wave64 - validate_spirv(spv) - if validate_emulate: - rdna2spirv.WAVE64_EMULATE = True - spv_emu = support.translate_lines("cs_w64_saveexec_b32", lines + ["s_endpgm"], fssm=FSSM_64) - assert rdna2spirv.translate.last_gen.wave64 - validate_spirv(spv_emu) - finally: - rdna2spirv.WAVE64_EMULATE = prev - return si.run_workgroup( - spv, 64, 64, - inputs_for=lambda i: {"%wg_id": (0, 0, 0), "%local_id": (i, 0, 0), "%sg_lane": i}, - push_constants=VSHARP + [0] * 28, - memory={}, - ) - - -def read_exec_and_state(lines, init_lo, init_hi): - """Setup EXEC = (init_hi << 32) | init_lo, run `lines`, then record: - out[0] = resulting EXEC_LO, out[1] = resulting EXEC_HI, out[2] = SCC (0/1), - out[3] = popcount(s8) via s_bcnt1_i32_b32, out[4] = s8 restored to EXEC_LO popcount.""" - prog = [ - "s_mov_b64 exec, -1", # ensure wave64 classification - f"s_mov_b32 exec_lo, {init_lo:#x}", - f"s_mov_b32 exec_hi, {init_hi:#x}", - *lines, - # Capture SCC before touching EXEC - "s_cselect_b32 s10, 1, 0", - # Capture current 64-bit EXEC into per-lane flag, then ballot via s_bcnt1 / per-lane stores - "v_mov_b32_e32 v10, 0", - "s_mov_b64 s[12:13], exec", - "s_mov_b64 exec, -1", - "v_cndmask_b32_e64 v10, 0, 1, s[12:13]", - # Store each lane's exec bit at byte 64 + 4*lane - "v_lshlrev_b32_e32 v11, 2, v0", - "v_add_nc_u32_e32 v11, 64, v11", - "buffer_store_dword v10, v11, s[0:3], 0 offen", - # Compute s_bcnt1_i32_b32 on s8 (the saved/written destination) to check MASK_LO tagging - "s_bcnt1_i32_b32 s11, s8", - # Store SCC (s10) at byte 0, bcnt(s8) (s11) at byte 4 from lane 0 - "v_cmpx_eq_u32_e32 0, v0", - "v_mov_b32_e32 v1, s10", - "v_mov_b32_e32 v2, s11", - "v_mov_b32_e32 v12, 0", "buffer_store_dword v1, v12, s[0:3], 0 offen", - "v_mov_b32_e32 v12, 4", "buffer_store_dword v2, v12, s[0:3], 0 offen", - ] - mem = run_w64(prog) - exec_lo = sum(((mem.get(64 + 4 * i, 0) & 1) << i) for i in range(32)) - exec_hi = sum(((mem.get(64 + 4 * (32 + i), 0) & 1) << i) for i in range(32)) - return exec_lo, exec_hi, mem.get(0), mem.get(4) - - -class Wave64SaveexecB32Tests(unittest.TestCase): - def test_all_ten_saveexec_b32_preserve_exec_hi_and_scc_low_half(self): - # Crucially: init_lo = 0x0000000F, s0 = 0x000000F0, init_hi = 0x000000FF. - # For s_and_saveexec_b32: new EXEC_LO = 0 while EXEC_HI stays 0x000000FF (non-zero!) -> SCC MUST be 0! - # Previously on main, set_exec(r) clobbered EXEC_HI to 0xF0 and scc_from_mask voted 1 over all 64 lanes. - init_lo, init_hi, s0 = 0x0000000F, 0x000000FF, 0x000000F0 - for kind, fn in EXEC_FUNCS.items(): - op = f"s_{kind}_saveexec_b32" - with self.subTest(op=op): - got_lo, got_hi, got_scc, got_bcnt = read_exec_and_state( - [f"{op} s8, {s0:#x}"], init_lo, init_hi - ) - want_lo = fn(s0, init_lo) - self.assertEqual(got_lo, want_lo) - self.assertEqual(got_hi, init_hi) # EXEC_HI untouched - self.assertEqual(got_scc, 1 if want_lo != 0 else 0) # SCC = (EXEC_LO != 0) only - self.assertEqual(got_bcnt, bin(init_lo).count("1")) # s8 holds MASK_LO (4, not 4+8=12) - - def test_wrexec_b32_preserves_exec_hi_and_scc_low_half(self): - # Case where new EXEC_LO is 0 while EXEC_HI is non-zero, and case where new EXEC_LO is non-zero. - for op, kind in (("s_andn2_wrexec_b32", "andn2"), ("s_andn1_wrexec_b32", "andn1")): - for init_lo, init_hi, s0 in ( - (0x000000FF, 0xA5A50000, 0x0000000F), # andn2 -> 0 (while EXEC_HI != 0); andn1 -> 0xF0 - (0x0000000F, 0x000000FF, 0x000000FF), # andn2 -> 0xF0; andn1 -> 0 (while EXEC_HI != 0) - ): - with self.subTest(op=op, init_lo=hex(init_lo), s0=hex(s0)): - got_lo, got_hi, got_scc, got_bcnt = read_exec_and_state( - [f"{op} s8, {s0:#x}"], init_lo, init_hi - ) - want_lo = EXEC_FUNCS[kind](s0, init_lo) - self.assertEqual(got_lo, want_lo) - self.assertEqual(got_hi, init_hi) - self.assertEqual(got_scc, 1 if want_lo != 0 else 0) - self.assertEqual(got_bcnt, bin(want_lo).count("1")) - - def test_cross_half_hi_source_and_exec_hi_dest(self): - # 1) Source is exec_hi (lanes 32..63 = 0x000000F0) applied to EXEC_LO (0x000000FF): - # new EXEC_LO = 0xF0 & 0xFF = 0xF0, EXEC_HI stays 0x000000F0. - got_lo, got_hi, got_scc, got_bcnt = read_exec_and_state( - ["s_and_saveexec_b32 s8, exec_hi"], init_lo=0x000000FF, init_hi=0x000000F0 - ) - self.assertEqual((got_lo, got_hi, got_scc, got_bcnt), (0x000000F0, 0x000000F0, 1, 8)) - - # 2) Destination is exec_hi: old EXEC_LO (0x00000033) copied into EXEC_HI, - # while EXEC_LO becomes (0x0F & 0x33) = 0x03. - got_lo2, got_hi2, got_scc2, _ = read_exec_and_state( - ["s_mov_b32 s8, 0", "s_and_saveexec_b32 exec_hi, 0x0000000f"], - init_lo=0x00000033, init_hi=0xFFFF0000, - ) - self.assertEqual((got_lo2, got_hi2, got_scc2), (0x00000003, 0x00000033, 1)) - - def test_vcc_lo_dest_keeps_vcc_hi_intact(self): - # Initialize VCC as a lane mask with vcc_hi = 0x000000AA (distinct from later exec_hi = 0x000000F0). - # s_and_saveexec_b32 vcc_lo, 0x0f must update only vcc_lo (lanes 0..31) to old exec_lo (0x55) while - # keeping vcc_hi = 0xAA (old mask_dst overwrote lanes 32..63 of %vcc with exec_hi = 0xF0). - prog = [ - "s_mov_b64 exec, -1", - "s_mov_b32 exec_lo, 0", - "s_mov_b32 exec_hi, 0x000000aa", - "v_cmp_lt_u32_e32 vcc, v0, 64", # vcc_lo = 0, vcc_hi = 0xAA (real lane mask) - "s_mov_b32 exec_lo, 0x00000055", - "s_mov_b32 exec_hi, 0x000000f0", - "s_and_saveexec_b32 vcc_lo, 0x0000000f", - "s_mov_b64 exec, -1", - "v_cndmask_b32_e64 v10, 0, 1, vcc", - "v_lshlrev_b32_e32 v11, 2, v0", - "buffer_store_dword v10, v11, s[0:3], 0 offen", - ] - mem = run_w64(prog) - vcc_lo = sum(((mem.get(4 * i, 0) & 1) << i) for i in range(32)) - vcc_hi = sum(((mem.get(4 * (32 + i), 0) & 1) << i) for i in range(32)) - self.assertEqual(vcc_lo, 0x00000055) - self.assertEqual(vcc_hi, 0x000000AA) - - def test_lane_masks_tags_b32_saveexec_and_wrexec_as_mask_lo(self): - s = lambda r, n=1: {"k": "sgpr", "r": r, "n": n} - use = {"op": "s_nop", "args": []} - ins = lambda op, *a: {"op": op, "args": list(a)} - for op in ("s_and_saveexec_b32", "s_andn2_wrexec_b32"): - masks, _ = lm.analyse([[ins(op, s(4), {"k": "imm", "v": 0xF}), use]], [[]]) - self.assertEqual(masks[id(use)], {4: lm.MASK_LO}) - masks64, _ = lm.analyse([[ins("s_and_saveexec_b64", s(4, 2), {"k": "imm", "v": -1}), use]], [[]]) - self.assertEqual(masks64[id(use)], {4: lm.MASK_LO, 5: lm.MASK_HI}) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_wave64_scmp_masks.py b/tests/semantic/test_wave64_scmp_masks.py deleted file mode 100644 index a3f4a632b..000000000 --- a/tests/semantic/test_wave64_scmp_masks.py +++ /dev/null @@ -1,777 +0,0 @@ -"""Semantic tests for Wave64/Wave32 s_cmp_* on opposite mask halves and mask-vs-scalar operands. - -Translates synthetic .s listings (no llvm-mc or game data required) with tools/rdna2spirv.py and -executes all 64 (wave64) or 32 (wave32) lanes via tests/semantic/spirv_mini_interp.run_workgroup. - -Covers: - - Wave64 s_cmp_eq_u32 / s_cmp_lg_u32 on opposite halves: vcc_lo vs vcc_hi, exec_lo vs exec_hi, - and MASK_LO SGPR vs MASK_HI SGPR (equal halves, unequal halves matching on lane 0 with equal - popcount, and single-bit mismatches). - - Wave64 and Wave32 s_cmp_eq_u32 / s_cmp_lt_u32 / s_cmp_gt_i32 comparing a lane-mask half - against arbitrary 32-bit scalar SGPRs and immediates (e.g. 0x80000003). - - Wave64 s_cmp_eq_u64 / s_cmp_lg_u64 comparing a lane mask against an arbitrary 64-bit SGPR - pair or non-0/-1 immediate. - - Preservation of the fast wave_equal vote path for same-half and mask-vs-0/-1 equality compares. -""" -from __future__ import annotations - -import gc -import os -import struct -import sys -import tempfile -import unittest -import warnings - -HERE = os.path.dirname(os.path.abspath(__file__)) -ROOT = os.path.dirname(os.path.dirname(HERE)) -TOOLS_DIR = os.environ.get("LEONIDA_TOOLS_DIR") or os.path.join(ROOT, "tools") - -sys.dont_write_bytecode = True -if HERE not in sys.path: - sys.path.insert(0, HERE) -if TOOLS_DIR not in sys.path: - sys.path.insert(0, TOOLS_DIR) - -import rdna2spirv # noqa: E402 -import spirv_mini_interp as si # noqa: E402 - -STUB_DXBC = b"DXBC" + bytes(24) + struct.pack(" 8 user SGPRs (s[0:3]=V#, s4=lo, s5=hi, s6=cmp_lo, s7=cmp_hi), TGID_X. -VSHARP = [0, 0, 0xFFFFFFFF, 0x31016FAC] - - -def make_fssm(threads): - return bytes(0x138) + struct.pack("<4I", 0x8090, threads, 1, 1) - - -def translate_cs(name, asm, threads=64): - """Translate a synthetic compute .s listing into SPIR-V assembly.""" - with tempfile.TemporaryDirectory() as tmp: - os.mkdir(os.path.join(tmp, "disasm")) - os.mkdir(os.path.join(tmp, "fssm")) - s_path = os.path.join(tmp, "disasm", name + ".s") - with open(s_path, "w", encoding="utf-8") as f: - f.write(f"; {name} synthetic\n") - for ln in asm.splitlines(): - st = ln.strip() - if st and not st.startswith(";"): - f.write(f"\t{st}\n") - with open(os.path.join(tmp, name + ".dxbc"), "wb") as f: - f.write(STUB_DXBC) - with open(os.path.join(tmp, "fssm", name + ".fssm"), "wb") as f: - f.write(make_fssm(threads)) - with warnings.catch_warnings(): - warnings.simplefilter("ignore", ResourceWarning) - spv = rdna2spirv.translate(s_path) - gc.collect() - return spv - - -def run_cs(spv, threads, s4=0, s5=0, s6=0, s7=0): - pc = VSHARP + [s4 & 0xFFFFFFFF, s5 & 0xFFFFFFFF, s6 & 0xFFFFFFFF, s7 & 0xFFFFFFFF] + [0] * 24 - return si.run_workgroup( - spv, threads, threads, - inputs_for=lambda i: {"%wg_id": (0, 0, 0), "%local_id": (i, 0, 0), "%sg_lane": i}, - push_constants=pc, memory={}, - ) - - -def emit_store_scc(slot): - """Emit RDNA2 lines that store SCC (1 or 0) to buffer dword `slot`.""" - return ( - f"s_cselect_b32 s20, 1, 0\n" - f"v_mov_b32_e32 v4, s20\n" - f"v_mov_b32_e32 v5, {slot * 4}\n" - f"buffer_store_dword v4, v5, s[0:3], 0 offen\n" - ) - - -# Builds a wave64 lane mask in `vcc` whose bit i is ((s4 if i < 32 else s5) >> (i & 31)) & 1, -# and copies it into s[12:13] (MASK_LO=s12, MASK_HI=s13). -WAVE64_BUILD_VCC_AND_SGPR = """\ -v_mov_b32_e32 v11, s5 -v_cmp_lt_u32_e64 vcc, v0, 32 -v_cndmask_b32_e64 v1, v11, s4, vcc -v_and_b32_e32 v2, 31, v0 -v_lshrrev_b32_e32 v3, v2, v1 -v_and_b32_e32 v3, 1, v3 -v_cmp_ne_u32_e64 vcc, 0, v3 -s_and_b64 s[12:13], vcc, exec -""" - -# Same for wave32: builds `vcc` from s4 (lanes 0..31). -WAVE32_BUILD_VCC = """\ -v_mov_b32_e32 v1, s4 -v_and_b32_e32 v2, 31, v0 -v_lshrrev_b32_e32 v3, v2, v1 -v_and_b32_e32 v3, 1, v3 -v_cmp_ne_u32_e64 vcc_lo, 0, v3 -""" - - -def _s32(u): - u &= 0xFFFFFFFF - return u - 0x100000000 if u >= 0x80000000 else u - - -def pack_u64(lo: int, hi: int) -> int: - """Pack low and high 32-bit unsigned words into a 64-bit integer.""" - return ((hi & 0xFFFFFFFF) << 32) | (lo & 0xFFFFFFFF) - - -def ref_s_cmp_u64(op: str, src0: int, src1: int) -> int: - """Expected SCC (1 or 0) of a 64-bit scalar compare. - - GFX10 has only these two (llvm-mc rejects s_cmp_lt/le/gt/ge_u64 for gfx1013): - - s_cmp_eq_u64: SCC = (src0[63:0] == src1[63:0]) - - s_cmp_lg_u64: SCC = (src0[63:0] != src1[63:0]) - """ - s0 = src0 & 0xFFFFFFFFFFFFFFFF - s1 = src1 & 0xFFFFFFFFFFFFFFFF - if op == "s_cmp_eq_u64": - return int(s0 == s1) - if op == "s_cmp_lg_u64": - return int(s0 != s1) - raise ValueError(f"no 64-bit scalar compare {op} on GFX10") - - -class Wave64OppositeHalvesTests(unittest.TestCase): - @classmethod - def setUpClass(cls): - asm = ( - WAVE64_BUILD_VCC_AND_SGPR - # 0: vcc_lo == vcc_hi - + "s_cmp_eq_u32 vcc_lo, vcc_hi\n" + emit_store_scc(0) - # 1: vcc_lo != vcc_hi - + "s_cmp_lg_u32 vcc_lo, vcc_hi\n" + emit_store_scc(1) - # 2: MASK_LO (s12) == MASK_HI (s13) - + "s_cmp_eq_u32 s12, s13\n" + emit_store_scc(2) - # 3: MASK_LO (s12) != MASK_HI (s13) - + "s_cmp_lg_u32 s12, s13\n" + emit_store_scc(3) - # 4 & 5: exec_lo == exec_hi / exec_lo != exec_hi (save/restore exec so store runs) - + "s_mov_b64 s[14:15], exec\n" - + "s_and_b64 exec, exec, vcc\n" - + "s_cmp_eq_u32 exec_lo, exec_hi\n" - + "s_cselect_b32 s21, 1, 0\n" - + "s_cmp_lg_u32 exec_lo, exec_hi\n" - + "s_cselect_b32 s22, 1, 0\n" - + "s_mov_b64 exec, s[14:15]\n" - + "v_mov_b32_e32 v4, s21\nv_mov_b32_e32 v5, 16\nbuffer_store_dword v4, v5, s[0:3], 0 offen\n" - + "v_mov_b32_e32 v4, s22\nv_mov_b32_e32 v5, 20\nbuffer_store_dword v4, v5, s[0:3], 0 offen\n" - + "s_endpgm\n" - ) - cls.spv = translate_cs("cs_w64_opp_halves", asm, threads=64) - - def test_opposite_halves_equal_and_unequal(self): - cases = [ - # Equal halves - (0x80000003, 0x80000003), - (0x00000000, 0x00000000), - (0xFFFFFFFF, 0xFFFFFFFF), - # Unequal halves that match on lane 0 AND have identical popcount (2) - (0x00000003, 0x00000005), - # Unequal halves with lane 0 off in both and identical popcount (1) - (0x00000002, 0x80000000), - # Unequal halves where one is all-zero - (0x00000000, 0x80000000), - (0x00000001, 0x00000002), - ] - for lo, hi in cases: - with self.subTest(lo=hex(lo), hi=hex(hi)): - mem = run_cs(self.spv, 64, s4=lo, s5=hi) - eq = int(lo == hi) - ne = int(lo != hi) - got = [mem[4 * k] for k in range(6)] - self.assertEqual(got, [eq, ne, eq, ne, eq, ne]) - - -class MaskVsScalarAndOrderingTests(unittest.TestCase): - @classmethod - def setUpClass(cls): - asm_w64 = ( - WAVE64_BUILD_VCC_AND_SGPR - # 0: vcc_lo == 0x80000003 (arbitrary immediate) - + "s_cmp_eq_u32 vcc_lo, 0x80000003\n" + emit_store_scc(0) - # 1: vcc_hi == s6 (arbitrary scalar SGPR) - + "s_cmp_eq_u32 vcc_hi, s6\n" + emit_store_scc(1) - # 2: s6 == s12 (scalar on left, MASK_LO on right) - + "s_cmp_eq_u32 s6, s12\n" + emit_store_scc(2) - # 3: vcc_lo < s6 (unsigned ordering) - + "s_cmp_lt_u32 vcc_lo, s6\n" + emit_store_scc(3) - # 4: s13 < s7 (MASK_HI unsigned ordering) - + "s_cmp_lt_u32 s13, s7\n" + emit_store_scc(4) - # 5: vcc_lo > 0 (signed i32 ordering: 0x80000003 is negative!) - + "s_cmp_gt_i32 vcc_lo, 0\n" + emit_store_scc(5) - # 6: vcc_hi > s7 (signed i32 ordering) - + "s_cmp_gt_i32 vcc_hi, s7\n" + emit_store_scc(6) - # 7: exec_hi < s7 (exec_hi ordering against scalar) - + "s_mov_b64 s[14:15], exec\n" - + "s_and_b64 exec, exec, vcc\n" - + "s_cmp_lt_u32 exec_hi, s7\n" - + "s_cselect_b32 s21, 1, 0\n" - + "s_mov_b64 exec, s[14:15]\n" - + "v_mov_b32_e32 v4, s21\nv_mov_b32_e32 v5, 28\nbuffer_store_dword v4, v5, s[0:3], 0 offen\n" - + "s_endpgm\n" - ) - cls.spv_w64 = translate_cs("cs_w64_mask_scalar", asm_w64, threads=64) - - asm_w32 = ( - WAVE32_BUILD_VCC - # 0: vcc_lo == 0x80000003 - + "s_cmp_eq_u32 vcc_lo, 0x80000003\n" + emit_store_scc(0) - # 1: vcc_lo < s6 (u32) - + "s_cmp_lt_u32 vcc_lo, s6\n" + emit_store_scc(1) - # 2: vcc_lo > 0 (i32) - + "s_cmp_gt_i32 vcc_lo, 0\n" + emit_store_scc(2) - # 3: s6 == vcc_lo (scalar on left) - + "s_cmp_eq_u32 s6, vcc_lo\n" + emit_store_scc(3) - + "s_endpgm\n" - ) - cls.spv_w32 = translate_cs("cs_w32_mask_scalar", asm_w32, threads=32) - - def test_wave64_mask_vs_scalar_and_ordering(self): - cases = [ - # (lo, hi, cmp_lo=s6, cmp_hi=s7) - (0x80000003, 0x00000005, 0x80000003, 0x00000006), - (0x80000003, 0x80000001, 0x80000004, 0x00000000), - (0x00000005, 0x00000005, 0x00000005, 0x00000005), - (0x00000001, 0xFFFFFFFE, 0x00000000, 0xFFFFFFFF), - ] - for lo, hi, s6, s7 in cases: - with self.subTest(lo=hex(lo), hi=hex(hi), s6=hex(s6), s7=hex(s7)): - mem = run_cs(self.spv_w64, 64, s4=lo, s5=hi, s6=s6, s7=s7) - want = [ - int(lo == 0x80000003), - int(hi == s6), - int(s6 == lo), - int(lo < s6), - int(hi < s7), - int(_s32(lo) > 0), - int(_s32(hi) > _s32(s7)), - int(hi < s7), - ] - self.assertEqual([mem[4 * k] for k in range(8)], want) - - def test_wave32_mask_vs_scalar_and_ordering(self): - cases = [ - (0x80000003, 0x80000003), - (0x80000003, 0x80000004), - (0x00000005, 0x00000004), - (0x00000000, 0x00000001), - ] - for lo, s6 in cases: - with self.subTest(lo=hex(lo), s6=hex(s6)): - mem = run_cs(self.spv_w32, 32, s4=lo, s6=s6) - want = [ - int(lo == 0x80000003), - int(lo < s6), - int(_s32(lo) > 0), - int(s6 == lo), - ] - self.assertEqual([mem[4 * k] for k in range(4)], want) - - -class Wave64U64MaskCompareTests(unittest.TestCase): - @classmethod - def setUpClass(cls): - asm = ( - WAVE64_BUILD_VCC_AND_SGPR - # 0: s_cmp_eq_u64 vcc, s[6:7] (mask vs arbitrary 64-bit scalar pair) - + "s_cmp_eq_u64 vcc, s[6:7]\n" + emit_store_scc(0) - # 1: s_cmp_lg_u64 vcc, s[6:7] - + "s_cmp_lg_u64 vcc, s[6:7]\n" + emit_store_scc(1) - # 2: s_cmp_eq_u64 s[6:7], s[12:13] (scalar pair vs mask SGPR pair) - + "s_cmp_eq_u64 s[6:7], s[12:13]\n" + emit_store_scc(2) - # 3: s_cmp_eq_u64 vcc, 0x12345678 (mask vs non-0/-1 immediate) - + "s_cmp_eq_u64 vcc, 0x12345678\n" + emit_store_scc(3) - # 4: s_cmp_lg_u64 vcc, 0x12345678 - + "s_cmp_lg_u64 vcc, 0x12345678\n" + emit_store_scc(4) - + "s_endpgm\n" - ) - cls.spv = translate_cs("cs_w64_u64_mask", asm, threads=64) - - def test_u64_mask_vs_scalar_pair_and_imm(self): - cases = [ - # Exact match with scalar pair - (0x12345678, 0x9ABCDEF0, 0x12345678, 0x9ABCDEF0), - # lo matches, hi differs (same lane 0 bit) - (0x12345679, 0x00000001, 0x12345679, 0x00000002), - # hi matches, lo differs - (0x00000003, 0x80000001, 0x00000005, 0x80000001), - # Exact match with 0x00000000_12345678 immediate - (0x12345678, 0x00000000, 0x12345678, 0x00000000), - # lo matches 0x12345678, hi non-zero -> != 0x12345678 - (0x12345678, 0x00000001, 0x00000000, 0x00000000), - ] - for lo, hi, s6, s7 in cases: - with self.subTest(lo=hex(lo), hi=hex(hi), s6=hex(s6), s7=hex(s7)): - mem = run_cs(self.spv, 64, s4=lo, s5=hi, s6=s6, s7=s7) - eq_pair = int(lo == s6 and hi == s7) - eq_imm = int(lo == 0x12345678 and hi == 0) - want = [eq_pair, 1 - eq_pair, eq_pair, eq_imm, 1 - eq_imm] - self.assertEqual([mem[4 * k] for k in range(5)], want) - - -class PartialWaveAllOnesTests(unittest.TestCase): - """A group smaller than the wave: lanes that were never launched have 0 bits in VCC and EXEC but take no part - in a subgroup vote, so `s_cmp` of a mask against -1 must compare the mask word (GPU: cs_*_partial_scmp.asm).""" - - def _run(self, name, prologue, cases, threads, wave): - asm = prologue + "v_cmp_eq_u32_e32 {}, v1, v1\n".format("vcc" if wave == 64 else "vcc_lo") - for k, (cmp_op, _) in enumerate(cases): - asm += cmp_op + "\n" + emit_store_scc(k) - spv = translate_cs(name, asm + "s_endpgm\n", threads=threads) - mem = si.run_workgroup( - spv, threads, wave, - inputs_for=lambda i: {"%wg_id": (0, 0, 0), "%local_id": (i, 0, 0), "%sg_lane": i}, - push_constants=VSHARP + [0] * 28, memory={}, - ) - self.assertEqual([mem[4 * k] for k in range(len(cases))], [want for _, want in cases]) - - def test_wave64_40_threads(self): - # vcc = exec = 0x000000ff_ffffffff - self._run("cs_w64_partial_ones", "v_mbcnt_lo_u32_b32 v1, -1, 0\nv_mbcnt_hi_u32_b32 v1, -1, v1\n", [ - ("s_cmp_eq_u32 vcc_hi, -1", 0), - ("s_cmp_lg_u32 vcc_hi, -1", 1), - ("s_cmp_eq_u32 vcc_lo, -1", 1), - ("s_cmp_eq_u64 vcc, -1", 0), - ("s_cmp_lg_u64 vcc, -1", 1), - ("s_cmp_eq_u64 exec, -1", 0), - ("s_cmp_lg_u64 vcc, 0", 1), - ], threads=40, wave=64) - - def test_wave32_20_threads(self): - # vcc_lo = exec_lo = 0x000fffff - self._run("cs_w32_partial_ones", "v_mbcnt_lo_u32_b32 v1, -1, 0\n", [ - ("s_cmp_eq_u32 vcc_lo, -1", 0), - ("s_cmp_lg_u32 vcc_lo, -1", 1), - ("s_cmp_eq_u32 exec_lo, -1", 0), - ("s_cmp_lg_u32 vcc_lo, 0", 1), - ], threads=20, wave=32) - - -class FastPathPreservationTests(unittest.TestCase): - def test_same_half_and_zero_imm_keep_vote_fast_path(self): - asm = ( - WAVE64_BUILD_VCC_AND_SGPR - + "s_cmp_eq_u32 vcc_lo, 0\n" - + "s_cmp_eq_u32 vcc_lo, exec_lo\n" - + "s_cmp_lg_u32 vcc_hi, 0\n" - + "s_cmp_eq_u64 vcc, exec\n" - + "s_endpgm\n" - ) - spv = translate_cs("cs_w64_fast_vote", asm, threads=64) - self.assertIn("OpGroupNonUniformAll", spv) - self.assertIn("OpGroupNonUniformAny", spv) - self.assertNotIn("OpGroupNonUniformBitwiseOr", spv) - - def test_opposite_halves_and_scalar_use_wave_mask_not_vote(self): - prologue = WAVE64_BUILD_VCC_AND_SGPR.replace("s_and_b64 s[12:13], vcc, exec", "s_mov_b64 s[12:13], vcc") - for name, cmp_op in ( - ("opp", "s_cmp_eq_u32 vcc_lo, vcc_hi"), - ("imm", "s_cmp_eq_u32 vcc_lo, 0x80000003"), - ("ord", "s_cmp_lt_u32 vcc_lo, s6"), - ("u64", "s_cmp_eq_u64 vcc, s[6:7]"), - # -1 (all ones): a vote misses lanes that were never launched, whose bits are 0 in the mask - ("ones32", "s_cmp_lg_u32 vcc_hi, -1"), - ("ones64", "s_cmp_eq_u64 vcc, -1"), - ): - with self.subTest(case=name): - spv = translate_cs(f"cs_w64_wm_{name}", prologue + cmp_op + "\ns_endpgm\n", threads=64) - self.assertIn("OpGroupNonUniformBitwiseOr", spv) - self.assertNotIn("OpGroupNonUniformAll", spv) - self.assertNotIn("OpGroupNonUniformAny", spv) - - - -class Wave64ReferenceOracleTests(unittest.TestCase): - @classmethod - def setUpClass(cls): - asm = ( - WAVE64_BUILD_VCC_AND_SGPR - # 0: s_cmp_eq_u64 vcc, s[6:7] (mask vs scalar pair) - + "s_cmp_eq_u64 vcc, s[6:7]\n" + emit_store_scc(0) - # 1: s_cmp_lg_u64 vcc, s[6:7] - + "s_cmp_lg_u64 vcc, s[6:7]\n" + emit_store_scc(1) - # 2: s_cmp_eq_u64 s[6:7], vcc (scalar pair vs mask) - + "s_cmp_eq_u64 s[6:7], vcc\n" + emit_store_scc(2) - # 3: s_cmp_lg_u64 s[6:7], vcc - + "s_cmp_lg_u64 s[6:7], vcc\n" + emit_store_scc(3) - # 4: s_cmp_eq_u64 vcc, s[12:13] (mask vs mask SGPR copy) - + "s_cmp_eq_u64 vcc, s[12:13]\n" + emit_store_scc(4) - # 5: s_cmp_lg_u64 vcc, s[12:13] - + "s_cmp_lg_u64 vcc, s[12:13]\n" + emit_store_scc(5) - # 6: s_cmp_eq_u64 vcc, 0 (mask vs zero immediate) - + "s_cmp_eq_u64 vcc, 0\n" + emit_store_scc(6) - # 7: s_cmp_lg_u64 vcc, 0 - + "s_cmp_lg_u64 vcc, 0\n" + emit_store_scc(7) - # 8: s_cmp_eq_u64 vcc, 0x55555555 (mask vs 32-bit literal immediate) - + "s_cmp_eq_u64 vcc, 0x55555555\n" + emit_store_scc(8) - # 9: s_cmp_lg_u64 vcc, 0x55555555 - + "s_cmp_lg_u64 vcc, 0x55555555\n" + emit_store_scc(9) - + "s_endpgm\n" - ) - cls.spv = translate_cs("cs_w64_oracle_u64", asm, threads=64) - - def test_wave64_mask_vs_oracle(self): - """Cross-check simulated wave64 execution against reference oracle predictions.""" - cases = [ - # Exact matches - (0x12345678, 0x9ABCDEF0, 0x12345678, 0x9ABCDEF0), - (0x00000000, 0x00000000, 0x00000000, 0x00000000), - (0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF), - (0x55555555, 0x00000000, 0x55555555, 0x00000000), - # Low half equal, high half different - (0xCAFEBABE, 0x11111111, 0xCAFEBABE, 0x22222222), - # High half equal, low half different - (0x11111111, 0xCAFEBABE, 0x22222222, 0xCAFEBABE), - # Single-bit difference at boundaries - (0x00000001, 0x00000000, 0x00000000, 0x00000000), - (0x80000000, 0x00000000, 0x00000000, 0x00000000), - (0x00000000, 0x00000001, 0x00000000, 0x00000000), - (0x00000000, 0x80000000, 0x00000000, 0x00000000), - # Inverted patterns - (0xAAAAAAAA, 0x55555555, 0x55555555, 0xAAAAAAAA), - (0x0F0F0F0F, 0xF0F0F0F0, 0xF0F0F0F0, 0x0F0F0F0F), - ] - for lo, hi, s6, s7 in cases: - with self.subTest(lo=hex(lo), hi=hex(hi), s6=hex(s6), s7=hex(s7)): - mask64 = pack_u64(lo, hi) - scalar64 = pack_u64(s6, s7) - mem = run_cs(self.spv, 64, s4=lo, s5=hi, s6=s6, s7=s7) - - want = [ - ref_s_cmp_u64("s_cmp_eq_u64", mask64, scalar64), - ref_s_cmp_u64("s_cmp_lg_u64", mask64, scalar64), - ref_s_cmp_u64("s_cmp_eq_u64", scalar64, mask64), - ref_s_cmp_u64("s_cmp_lg_u64", scalar64, mask64), - ref_s_cmp_u64("s_cmp_eq_u64", mask64, mask64), - ref_s_cmp_u64("s_cmp_lg_u64", mask64, mask64), - ref_s_cmp_u64("s_cmp_eq_u64", mask64, 0), - ref_s_cmp_u64("s_cmp_lg_u64", mask64, 0), - ref_s_cmp_u64("s_cmp_eq_u64", mask64, 0x55555555), - ref_s_cmp_u64("s_cmp_lg_u64", mask64, 0x55555555), - ] - got = [mem[4 * k] for k in range(10)] - self.assertEqual(got, want) - - - -class Wave64SccConditionUpdateTests(unittest.TestCase): - @classmethod - def setUpClass(cls): - asm = ( - WAVE64_BUILD_VCC_AND_SGPR - # Step 1: Compare A (eq u64), preserve SCC across ALU movs - + "s_cmp_eq_u64 vcc, s[6:7]\n" - + "s_mov_b32 s16, 0x42\n" - + "v_mov_b32_e32 v6, s16\n" - + "s_cselect_b32 s21, 1, 0\n" - # Step 2: Compare B (lg u64), unconditionally updates SCC - + "s_cmp_lg_u64 vcc, s[6:7]\n" - + "s_mov_b32 s17, 0x43\n" - + "s_cselect_b32 s22, 1, 0\n" - # Step 3: Compare C (tautology scalar eq), sets SCC to 1 - + "s_cmp_eq_u64 s[6:7], s[6:7]\n" - + "s_cselect_b32 s23, 1, 0\n" - # Step 4: Compare D (contradiction scalar lg), sets SCC to 0 - + "s_cmp_lg_u64 s[6:7], s[6:7]\n" - + "s_cselect_b32 s24, 1, 0\n" - # Step 5: Compare E (32-bit low half eq) - + "s_cmp_eq_u32 vcc_lo, s6\n" - + "s_cselect_b32 s25, 1, 0\n" - # Step 6: Compare F (32-bit high half lg) - + "s_cmp_lg_u32 vcc_hi, s7\n" - + "s_cselect_b32 s26, 1, 0\n" - # Store s21..s26 to slots 0..5 - + "v_mov_b32_e32 v4, s21\nv_mov_b32_e32 v5, 0\nbuffer_store_dword v4, v5, s[0:3], 0 offen\n" - + "v_mov_b32_e32 v4, s22\nv_mov_b32_e32 v5, 4\nbuffer_store_dword v4, v5, s[0:3], 0 offen\n" - + "v_mov_b32_e32 v4, s23\nv_mov_b32_e32 v5, 8\nbuffer_store_dword v4, v5, s[0:3], 0 offen\n" - + "v_mov_b32_e32 v4, s24\nv_mov_b32_e32 v5, 12\nbuffer_store_dword v4, v5, s[0:3], 0 offen\n" - + "v_mov_b32_e32 v4, s25\nv_mov_b32_e32 v5, 16\nbuffer_store_dword v4, v5, s[0:3], 0 offen\n" - + "v_mov_b32_e32 v4, s26\nv_mov_b32_e32 v5, 20\nbuffer_store_dword v4, v5, s[0:3], 0 offen\n" - + "s_endpgm\n" - ) - cls.spv = translate_cs("cs_w64_scc_updates", asm, threads=64) - - def test_scc_sequential_updates_and_preservation(self): - cases = [ - # Equal mask & scalar - (0x12345678, 0x9ABCDEF0, 0x12345678, 0x9ABCDEF0), - # Low half equal, high half different - (0x12345678, 0x11111111, 0x12345678, 0x22222222), - # High half equal, low half different - (0x11111111, 0x9ABCDEF0, 0x22222222, 0x9ABCDEF0), - # Completely different - (0x00000000, 0x00000000, 0xFFFFFFFF, 0xFFFFFFFF), - ] - for lo, hi, s6, s7 in cases: - with self.subTest(lo=hex(lo), hi=hex(hi), s6=hex(s6), s7=hex(s7)): - mem = run_cs(self.spv, 64, s4=lo, s5=hi, s6=s6, s7=s7) - u64_eq = int(lo == s6 and hi == s7) - u64_lg = int(lo != s6 or hi != s7) - lo_eq = int(lo == s6) - hi_lg = int(hi != s7) - want = [u64_eq, u64_lg, 1, 0, lo_eq, hi_lg] - self.assertEqual([mem[4 * k] for k in range(6)], want) - - -class Wave64MaskDecompositionTests(unittest.TestCase): - @classmethod - def setUpClass(cls): - asm = ( - WAVE64_BUILD_VCC_AND_SGPR - # 0: direct s_cmp_eq_u64 vcc, s[6:7] - + "s_cmp_eq_u64 vcc, s[6:7]\n" - + "s_cselect_b32 s20, 1, 0\n" - # 1: decomposed eq: vcc_lo == s6 AND vcc_hi == s7 - + "s_cmp_eq_u32 vcc_lo, s6\n" - + "s_cselect_b32 s21, 1, 0\n" - + "s_cmp_eq_u32 vcc_hi, s7\n" - + "s_cselect_b32 s22, 1, 0\n" - + "s_and_b32 s23, s21, s22\n" - # 2: direct s_cmp_lg_u64 vcc, s[6:7] - + "s_cmp_lg_u64 vcc, s[6:7]\n" - + "s_cselect_b32 s24, 1, 0\n" - # 3: decomposed lg: vcc_lo != s6 OR vcc_hi != s7 - + "s_cmp_lg_u32 vcc_lo, s6\n" - + "s_cselect_b32 s25, 1, 0\n" - + "s_cmp_lg_u32 vcc_hi, s7\n" - + "s_cselect_b32 s26, 1, 0\n" - + "s_or_b32 s27, s25, s26\n" - # 4: De Morgan negation of decomposed equality: s23 ^ 1 - + "s_xor_b32 s28, s23, 1\n" - # 5: direct s_cmp_eq_u64 s[6:7], vcc (swapped) - + "s_cmp_eq_u64 s[6:7], vcc\n" - + "s_cselect_b32 s29, 1, 0\n" - # Store results to buffer: slots 0..5 - + "v_mov_b32_e32 v4, s20\nv_mov_b32_e32 v5, 0\nbuffer_store_dword v4, v5, s[0:3], 0 offen\n" - + "v_mov_b32_e32 v4, s23\nv_mov_b32_e32 v5, 4\nbuffer_store_dword v4, v5, s[0:3], 0 offen\n" - + "v_mov_b32_e32 v4, s24\nv_mov_b32_e32 v5, 8\nbuffer_store_dword v4, v5, s[0:3], 0 offen\n" - + "v_mov_b32_e32 v4, s27\nv_mov_b32_e32 v5, 12\nbuffer_store_dword v4, v5, s[0:3], 0 offen\n" - + "v_mov_b32_e32 v4, s28\nv_mov_b32_e32 v5, 16\nbuffer_store_dword v4, v5, s[0:3], 0 offen\n" - + "v_mov_b32_e32 v4, s29\nv_mov_b32_e32 v5, 20\nbuffer_store_dword v4, v5, s[0:3], 0 offen\n" - + "s_endpgm\n" - ) - cls.spv = translate_cs("cs_w64_decomp", asm, threads=64) - - def test_64bit_mask_decomposition_equivalence(self): - cases = [ - (0x12345678, 0x9ABCDEF0, 0x12345678, 0x9ABCDEF0), - (0x12345678, 0x00000000, 0x12345678, 0xFFFFFFFF), - (0x00000000, 0x9ABCDEF0, 0xFFFFFFFF, 0x9ABCDEF0), - (0xAAAAAAAA, 0x55555555, 0x55555555, 0xAAAAAAAA), - (0x00000001, 0x00000000, 0x00000000, 0x00000000), - (0x00000000, 0x80000000, 0x00000000, 0x00000000), - (0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF), - (0x00000000, 0x00000000, 0x00000000, 0x00000000), - ] - for lo, hi, s6, s7 in cases: - with self.subTest(lo=hex(lo), hi=hex(hi), s6=hex(s6), s7=hex(s7)): - mem = run_cs(self.spv, 64, s4=lo, s5=hi, s6=s6, s7=s7) - direct_eq = mem[0] - decomp_eq = mem[4] - direct_lg = mem[8] - decomp_lg = mem[12] - demorgan_lg = mem[16] - swapped_eq = mem[20] - - self.assertEqual(direct_eq, decomp_eq) - self.assertEqual(direct_lg, decomp_lg) - self.assertEqual(decomp_lg, demorgan_lg) - self.assertEqual(direct_eq, swapped_eq) - - -class Wave64BoundaryExtremesTests(unittest.TestCase): - @classmethod - def setUpClass(cls): - asm = ( - WAVE64_BUILD_VCC_AND_SGPR - # 0: vcc == s[6:7] - + "s_cmp_eq_u64 vcc, s[6:7]\n" + emit_store_scc(0) - # 1: vcc != s[6:7] - + "s_cmp_lg_u64 vcc, s[6:7]\n" + emit_store_scc(1) - # 2: vcc == 0 (zero boundary) - + "s_cmp_eq_u64 vcc, 0\n" + emit_store_scc(2) - # 3: vcc != 0 - + "s_cmp_lg_u64 vcc, 0\n" + emit_store_scc(3) - # 4: vcc == -1 (all ones boundary) - + "s_cmp_eq_u64 vcc, -1\n" + emit_store_scc(4) - # 5: vcc != -1 - + "s_cmp_lg_u64 vcc, -1\n" + emit_store_scc(5) - + "s_endpgm\n" - ) - cls.spv = translate_cs("cs_w64_boundary", asm, threads=64) - - def test_boundary_extremes(self): - cases = [ - # All zeros - (0x00000000, 0x00000000, 0x00000000, 0x00000000), - # All ones - (0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF), - # Half-word zeros and ones - (0x00000000, 0xFFFFFFFF, 0x00000000, 0xFFFFFFFF), - (0xFFFFFFFF, 0x00000000, 0xFFFFFFFF, 0x00000000), - # INT64_MAX: 0x7FFFFFFF_FFFFFFFF - (0xFFFFFFFF, 0x7FFFFFFF, 0xFFFFFFFF, 0x7FFFFFFF), - # INT64_MIN: 0x80000000_00000000 - (0x00000000, 0x80000000, 0x00000000, 0x80000000), - # Single bit at lane 0 - (0x00000001, 0x00000000, 0x00000001, 0x00000000), - # Single bit at lane 31 (MSB of lo) - (0x80000000, 0x00000000, 0x80000000, 0x00000000), - # Single bit at lane 32 (LSB of hi) - (0x00000000, 0x00000001, 0x00000000, 0x00000001), - # Single bit at lane 63 (MSB of hi) - (0x00000000, 0x80000000, 0x00000000, 0x80000000), - # Corner bits: lane 0 and lane 63 set - (0x00000001, 0x80000000, 0x00000001, 0x80000000), - ] - for lo, hi, s6, s7 in cases: - with self.subTest(lo=hex(lo), hi=hex(hi), s6=hex(s6), s7=hex(s7)): - mask64 = pack_u64(lo, hi) - scalar64 = pack_u64(s6, s7) - mem = run_cs(self.spv, 64, s4=lo, s5=hi, s6=s6, s7=s7) - - want = [ - int(mask64 == scalar64), - int(mask64 != scalar64), - int(mask64 == 0), - int(mask64 != 0), - int(mask64 == 0xFFFFFFFFFFFFFFFF), - int(mask64 != 0xFFFFFFFFFFFFFFFF), - ] - self.assertEqual([mem[4 * k] for k in range(6)], want) - - -class Wave64SignedVsUnsignedTests(unittest.TestCase): - @classmethod - def setUpClass(cls): - asm = ( - WAVE64_BUILD_VCC_AND_SGPR - # 0: unsigned lt: vcc_lo < s6 - + "s_cmp_lt_u32 vcc_lo, s6\n" + emit_store_scc(0) - # 1: signed lt: vcc_lo < s6 - + "s_cmp_lt_i32 vcc_lo, s6\n" + emit_store_scc(1) - # 2: unsigned gt: vcc_lo > s6 - + "s_cmp_gt_u32 vcc_lo, s6\n" + emit_store_scc(2) - # 3: signed gt: vcc_lo > s6 - + "s_cmp_gt_i32 vcc_lo, s6\n" + emit_store_scc(3) - # 4: unsigned lt: vcc_hi < s7 - + "s_cmp_lt_u32 vcc_hi, s7\n" + emit_store_scc(4) - # 5: signed lt: vcc_hi < s7 - + "s_cmp_lt_i32 vcc_hi, s7\n" + emit_store_scc(5) - # 6: 64-bit eq: vcc == s[6:7] - + "s_cmp_eq_u64 vcc, s[6:7]\n" + emit_store_scc(6) - # 7: 64-bit lg: vcc != s[6:7] - + "s_cmp_lg_u64 vcc, s[6:7]\n" + emit_store_scc(7) - + "s_endpgm\n" - ) - cls.spv = translate_cs("cs_w64_signed_unsigned", asm, threads=64) - - def test_signed_vs_unsigned_divergence_and_equality_invariance(self): - cases = [ - # MSB set in vcc_lo (negative signed, large unsigned) vs 0 - (0x80000000, 0x00000001, 0x00000000, 0x80000000), - # All ones in vcc_lo (-1 signed, 0xFFFFFFFF unsigned) vs 1 - (0xFFFFFFFF, 0x7FFFFFFF, 0x00000001, 0x00000000), - # 0x7FFFFFFF vs 0x80000000 (signed: pos > neg; unsigned: 0x7fffffff < 0x80000000) - (0x7FFFFFFF, 0x7FFFFFFF, 0x80000000, 0x80000000), - # Exact match - (0x80000001, 0x80000002, 0x80000001, 0x80000002), - ] - for lo, hi, s6, s7 in cases: - with self.subTest(lo=hex(lo), hi=hex(hi), s6=hex(s6), s7=hex(s7)): - mem = run_cs(self.spv, 64, s4=lo, s5=hi, s6=s6, s7=s7) - - u_lt_lo = int((lo & 0xFFFFFFFF) < (s6 & 0xFFFFFFFF)) - s_lt_lo = int(_s32(lo) < _s32(s6)) - u_gt_lo = int((lo & 0xFFFFFFFF) > (s6 & 0xFFFFFFFF)) - s_gt_lo = int(_s32(lo) > _s32(s6)) - - u_lt_hi = int((hi & 0xFFFFFFFF) < (s7 & 0xFFFFFFFF)) - s_lt_hi = int(_s32(hi) < _s32(s7)) - - eq_64 = int(lo == s6 and hi == s7) - lg_64 = int(lo != s6 or hi != s7) - - want = [u_lt_lo, s_lt_lo, u_gt_lo, s_gt_lo, u_lt_hi, s_lt_hi, eq_64, lg_64] - self.assertEqual([mem[4 * k] for k in range(8)], want) - - -class Wave64NegativeControlsTests(unittest.TestCase): - @classmethod - def setUpClass(cls): - asm = ( - WAVE64_BUILD_VCC_AND_SGPR - # 0: vcc == s[6:7] - + "s_cmp_eq_u64 vcc, s[6:7]\n" + emit_store_scc(0) - # 1: vcc != s[6:7] - + "s_cmp_lg_u64 vcc, s[6:7]\n" + emit_store_scc(1) - # 2: s[12:13] == s[6:7] (mask copied to SGPR pair vs scalar pair) - + "s_cmp_eq_u64 s[12:13], s[6:7]\n" + emit_store_scc(2) - # 3: s[12:13] != s[6:7] - + "s_cmp_lg_u64 s[12:13], s[6:7]\n" + emit_store_scc(3) - # 4: s[6:7] == s[6:7] (non-mask SGPR pair tautology) - + "s_cmp_eq_u64 s[6:7], s[6:7]\n" + emit_store_scc(4) - # 5: s[6:7] != s[6:7] (non-mask SGPR pair contradiction) - + "s_cmp_lg_u64 s[6:7], s[6:7]\n" + emit_store_scc(5) - + "s_endpgm\n" - ) - cls.spv = translate_cs("cs_w64_neg_ctrl", asm, threads=64) - - def test_single_bit_perturbations_break_equality(self): - """Starting from exact equality, perturbing any single bit must yield eq=0, lg=1.""" - base_lo = 0x12345678 - base_hi = 0x9ABCDEF0 - bit_positions = [0, 1, 15, 31, 32, 47, 63] - for bit in bit_positions: - with self.subTest(bit=bit): - if bit < 32: - p_s6 = base_lo ^ (1 << bit) - p_s7 = base_hi - else: - p_s6 = base_lo - p_s7 = base_hi ^ (1 << (bit - 32)) - - mem = run_cs(self.spv, 64, s4=base_lo, s5=base_hi, s6=p_s6, s7=p_s7) - self.assertEqual(mem[0], 0) - self.assertEqual(mem[4], 1) - self.assertEqual(mem[8], 0) - self.assertEqual(mem[12], 1) - self.assertEqual(mem[16], 1) - self.assertEqual(mem[20], 0) - - def test_mutual_exclusion_and_sgpr_orthogonality(self): - cases = [ - (0x12345678, 0x9ABCDEF0, 0x12345678, 0x9ABCDEF0), - (0x12345678, 0x9ABCDEF0, 0x00000000, 0x00000000), - (0xAAAAAAAA, 0x55555555, 0x55555555, 0xAAAAAAAA), - (0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF), - (0x00000000, 0x00000000, 0x00000000, 0x00000000), - ] - for lo, hi, s6, s7 in cases: - with self.subTest(lo=hex(lo), hi=hex(hi), s6=hex(s6), s7=hex(s7)): - mem = run_cs(self.spv, 64, s4=lo, s5=hi, s6=s6, s7=s7) - vcc_eq, vcc_lg = mem[0], mem[4] - sgpr_eq, sgpr_lg = mem[8], mem[12] - tautology, contradiction = mem[16], mem[20] - - # Negative control 1: strict mutual exclusion - self.assertEqual(vcc_eq ^ vcc_lg, 1) - self.assertEqual(vcc_eq + vcc_lg, 1) - self.assertEqual(sgpr_eq ^ sgpr_lg, 1) - self.assertEqual(sgpr_eq + sgpr_lg, 1) - - # Negative control 2: VCC mask vs SGPR mask representation consistency - self.assertEqual(vcc_eq, sgpr_eq) - self.assertEqual(vcc_lg, sgpr_lg) - - # Negative control 3: Baseline invariants - self.assertEqual(tautology, 1) - self.assertEqual(contradiction, 0) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_wave64_subgroup_ops.py b/tests/semantic/test_wave64_subgroup_ops.py deleted file mode 100644 index c1f86e3db..000000000 --- a/tests/semantic/test_wave64_subgroup_ops.py +++ /dev/null @@ -1,139 +0,0 @@ -"""Wave64 whole-wave mask and vote tests, run across every lane of the translated SPIR-V. - -Eight GPU tests from runtime/test/shaders (hand-written, no game data; fixtures from regen_fixtures.py), translated -without --wave64-emulate and run by spirv_mini_interp.run_workgroup the way vk_compute_test runs them: one group -of the size in the .asm header (64 threads, 40 for cs_w64x_partial), a heap filled with 0xEE bytes, s[0:3] = a V# -with base 0 and num_records 0xFFFFFFFF. - -* One 64-wide subgroup: every word equals the GPU check's value (check.py CS_DUMPS, W64X_DUMPS, W64X_PARTIAL; for - cs_wavemask the per-lane formula of vk_compute_test's "wavemask" mode). This covers ballots and s_bcnt1 / - s_ff1 of 64-bit masks, readfirstlane with only upper lanes on, the votes behind wave-uniform branches, and the - missing lanes of a partial wave (ds_bpermute uses the ballot to avoid shuffling from a missing lane). -* Two 32-wide subgroups (NVIDIA without emulation): the words differ, and WAVE32_EXPECTED pins them. Measured: - NVIDIA GeForce RTX 4070 SUPER (subgroup 32), driver 610.88, `vk_compute_test .spv 1 dump` on - run_gpu_tests.py's non-emulated build, three runs each: every word equals WAVE32_EXPECTED, and cs_wavemask - reports 64 mismatches with lane 0 = 0x00081021, as here. These follow from SPIR-V (each subgroup votes over its - own 32 lanes) except cs_w64x_load_ballot_load, whose loads read the other subgroup's stores: the order between - subgroups is not specified, and the interpreter's (subgroup 0's instruction, then subgroup 1's) is the order - that GPU showed. - -Not covered: the cs_w64x tests with branches (branch, sbarrier, wg128_branches, and cs_wm_half_ops / -cs_wm_scc_rfl), because the translator needs llvm-mc's encodings for branch targets and these fixtures are -unassembled; and the --wave64-emulate output (Workgroup memory and a round loop). -""" -import os -import re -import struct -import sys -import unittest - -import support -import spirv_mini_interp as si - -sys.path.insert(0, os.path.join(support.ROOT, "runtime", "test", "shaders")) -import check # noqa: E402 (the GPU check's expected words) -from compute_fixture import compute_header # noqa: E402 - -ASM_DIR = os.path.join(support.ROOT, "runtime", "test", "shaders") -GPU_DUMPS = dict(check.CS_DUMPS + check.W64X_DUMPS + check.W64X_PARTIAL) -DUMPS = ("cs_w64x_ballot", "cs_w64x_readfirstlane", "cs_w64x_load_ballot_load", "cs_w64x_partial", - "cs_wave64_ballot", "cs_wm_bfm64", "cs_wm_half_cmp") -HEAP_FILL = 0xEEEEEEEE -VSHARP = [0, 0, 0xFFFFFFFF, 0x31016FAC] - -# Two 32-wide subgroups: each half votes, counts and picks its first lane on its own. -WAVE32_EXPECTED = { - "cs_w64x_ballot": [1061, 1069, 1077, 1085] + [HEAP_FILL] * 4, - "cs_w64x_readfirstlane": [100, 140, 100, 132, 132, 133, 100, 48], - "cs_w64x_load_ballot_load": [43, 74, 43, 10, 42, 18, 41, 32], - "cs_w64x_partial": [32, 8, 528, 0, 0, 532, 539, 500], - "cs_wave64_ballot": [16, 16, 0, 0xFFFFFFFF, 0, 0xFFFFFFFF], - "cs_wm_bfm64": [16, 8, 0, 0xFFFFFFFF], - "cs_wm_half_cmp": [1, 0, 0, 1], -} - - -class Heap(dict): - """vk_compute_test's heap: every byte starts as 0xEE.""" - - def get(self, key, default=None): - return super().get(key, HEAP_FILL) - - -def wavemask_want(lane): - # vk_compute_test.cpp "wavemask": lanes 16-47 come back on after the parked mask (0x80) and the one through a - # VGPR (0x40), plus how many set lanes are below this one. - top = 0xC0 + lane - 16 if 16 <= lane < 48 else 0 - return 65 | 16 << 8 | 8 << 16 | top << 24 - - -def run(name, subgroup_size): - header = compute_header(os.path.join(ASM_DIR, name + ".asm")) - threads = struct.unpack_from("(?P%\w+) = OpGroupNonUniformBallotBitExtract[^\n]*\n\s*)" - r"(?P%\w+) = OpSelect %uint (?P=present) (?P%\w+) %\w+(?=\n)", - r"\g\g = OpCopyObject %uint \g", - spv, - ) - self.assertEqual(replaced, 2) - with self.assertRaisesRegex(si.UnsupportedConstruct, "undefined value"): - si.run_workgroup(bad, 40, 64, - inputs_for=lambda i: {"%wg_id": (0, 0, 0), "%local_id": (i, 0, 0), "%sg_lane": i}, - push_constants=VSHARP + [0] * 28, memory=Heap()) - - -class LockstepMemoryOrder(unittest.TestCase): - def test_a_load_after_a_store_sees_every_lane(self): - # cs_w64x_load_ballot_load: every lane stores out[lane], then lane 63 loads out[0]. In a SIMD wave all 64 - # stores happen first and the second load reads 10 + 0, so out[3] = 42; a run that let lane 0 finish its - # block before lane 63 started would read lane 0's later store instead. - self.assertEqual(words(run("cs_w64x_load_ballot_load", 64), 8)[3], 42) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_wave64_vcc_data_branch.py b/tests/semantic/test_wave64_vcc_data_branch.py deleted file mode 100644 index c088bf5fc..000000000 --- a/tests/semantic/test_wave64_vcc_data_branch.py +++ /dev/null @@ -1,142 +0,0 @@ -"""Wave64: s_cbranch_vccz/s_cbranch_vccnz must test all 64 bits of VCC when it holds data. - -RDNA2 ISA: VCCZ/VCCNZ test the whole 64-bit register. A shader that writes vcc_lo and -vcc_hi with s_mov_b32 is using VCC as ordinary scalar data, not as a lane mask: in the -translation each lane holds the same low word in %vcc and the same high word in %vcc_hi. -The old branch_condition() loaded only %vcc, so a high-only non-zero VCC looked zero. -Both SGPR-source and constant writes are covered: @ray3242's original reproducer uses -`s_mov_b32 vcc_lo, 0` / `s_mov_b32 vcc_hi, 0x8000000a`. A VCC that was a lane mask -earlier and is then overwritten with data is a separate -dataflow limitation of #2544 and is not covered here. - -Each case is a synthetic 64-thread compute shader translated by tools/rdna2spirv.py and -run with tests/semantic/spirv_mini_interp.run_workgroup; output word 0 is 7 when the -branch was taken and 9 when it fell through. No llvm-mc, GPU or game data is used. -""" -import gc -import os -import struct -import sys -import tempfile -import unittest -import warnings - -HERE = os.path.dirname(os.path.abspath(__file__)) -ROOT = os.path.dirname(os.path.dirname(HERE)) -TOOLS_DIR = os.environ.get("LEONIDA_TOOLS_DIR") or os.path.join(ROOT, "tools") - -sys.dont_write_bytecode = True -for p in (HERE, TOOLS_DIR): - if p not in sys.path: - sys.path.insert(0, p) - -import rdna2spirv # noqa: E402 -import spirv_mini_interp as si # noqa: E402 - -M32 = 0xFFFFFFFF -STUB_DXBC = b"DXBC" + bytes(24) + struct.pack("> l & 1 else 3 for l in range(64)], [7 if vcc == 0 else 9] * 64 - - -# The half write under test, and the new (lo, hi) halves of VCC as a function of the old ones. -CASES = { - "mov_vcc_lo_0": ([("s_mov_b32 vcc_lo, 0", 4)], lambda lo, hi: (0, hi)), - "mov_vcc_hi_0": ([("s_mov_b32 vcc_hi, 0", 4)], lambda lo, hi: (lo, 0)), - "mov_vcc_lo_all": ([("s_mov_b32 vcc_lo, -1", 4)], lambda lo, hi: (M32, hi)), - "mov_vcc_hi_all": ([("s_mov_b32 vcc_hi, -1", 4)], lambda lo, hi: (lo, M32)), - "and_vcc_lo_0": ([("s_and_b32 vcc_lo, vcc_lo, 0", 4)], lambda lo, hi: (0, hi)), - "or_vcc_hi_all": ([("s_or_b32 vcc_hi, vcc_hi, -1", 4)], lambda lo, hi: (lo, M32)), - "mov_sgpr_0_vcc_lo": ([("s_mov_b32 s6, 0", 4), ("s_mov_b32 vcc_lo, s6", 4)], lambda lo, hi: (0, hi)), - "mov_sgpr_all_vcc_hi": ([("s_mov_b32 s6, -1", 4), ("s_mov_b32 vcc_hi, s6", 4)], lambda lo, hi: (lo, M32)), -} -MASKS = [(0x0000FFFF, 0xFFFF0000), (0, 1), (1, 0), (0x80000006, 0x00010000), (0, 0), (M32, M32)] - - -class Wave64VccHalfWriteTests(unittest.TestCase): - @classmethod - def setUpClass(cls): - cls.spv = {k: translate_cs("cs_w64_vcc_" + k, BUILD_VCC + body + OBSERVE) - for k, (body, _) in CASES.items()} - cls.seq_spv = translate_cs("cs_w64_vcc_seq", BUILD_VCC + [ - ("s_mov_b32 vcc_hi, 0", 4), - ("s_bcnt1_i32_b64 s6, vcc", 4), - ("s_mov_b32 vcc_hi, -1", 4), - ("s_bcnt1_i32_b64 s7, vcc", 4), - ("s_mov_b32 vcc_lo, 0", 4), - ("s_bcnt1_i32_b64 s8, vcc", 4), - ("v_lshlrev_b32_e32 v5, 2, v0", 4), - ("v_mov_b32_e32 v6, s6", 4), - ("buffer_store_dword v6, v5, s[0:3], 0 offen offset:512", 8), - ("v_mov_b32_e32 v6, s7", 4), - ("buffer_store_dword v6, v5, s[0:3], 0 offen offset:768", 8), - ("v_mov_b32_e32 v6, s8", 4), - ("buffer_store_dword v6, v5, s[0:3], 0 offen offset:1024", 8), - ] + OBSERVE) - - def test_reference(self): - self.assertEqual(expect(0, 1)[1][0], 9) - self.assertEqual(expect(0, 0)[1][0], 7) - self.assertEqual(expect(0, 1)[0][32], 5) - - def test_half_write_keeps_other_half(self): - for name, (body, after) in CASES.items(): - for lo, hi in MASKS: - with self.subTest(case=name, lo=hex(lo), hi=hex(hi)): - got = run(self.spv[name], lo, hi) - self.assertEqual(got, expect(*after(lo, hi))) - - def test_back_to_back_half_mask_writes_preserve_whole_wave_vcc(self): - for lo, hi in MASKS: - with self.subTest(lo=hex(lo), hi=hex(hi)): - pc = VSHARP + [lo & M32, hi & M32, 0, 0] + [0] * 24 - mem = si.run_workgroup(self.seq_spv, 64, 64, - inputs_for=lambda i: {"%wg_id": (0, 0, 0), "%local_id": (i, 0, 0), - "%sg_lane": i}, - push_constants=pc, memory={}) - lo_cnt = (lo & M32).bit_count() - self.assertEqual([mem[512 + 4 * l] for l in range(64)], [lo_cnt] * 64) - self.assertEqual([mem[768 + 4 * l] for l in range(64)], [lo_cnt + 32] * 64) - self.assertEqual([mem[1024 + 4 * l] for l in range(64)], [32] * 64) - got = ([mem[4 * l] for l in range(64)], [mem[256 + 4 * l] for l in range(64)]) - self.assertEqual(got, expect(0, M32)) - - -class Wave64VccHalfDataWriteTests(unittest.TestCase): - """Plain-data writes to vcc_lo / vcc_hi after v_cmp in wave64 must write all 64 lanes as scalar data rather than - updating only one 32-lane mask half (which left 0xFFFFFFFF = -NaN in lanes 32..63 after v_cmp).""" - - LOAD_ADDR = 0x2000 - - @classmethod - def setUpClass(cls): - cls.ps_spv = translate_asm("ps_w64_vcc_lo_smem_sub", [ - ("s_mov_b64 s[12:13], exec", 4), - ("v_cmp_ne_u32_e64 vcc, 0, s4", 8), - ("s_buffer_load_dword vcc_lo, s[0:3], 0x10", 8), - ("v_mov_b32_e32 v1, s5", 4), - ("v_sub_f32_e64 v2, vcc_lo, v1", 8), - ("exp mrt0 v2, v2, v2, v2 done vm", 8), - ("s_endpgm", 4), - ], cs=False) - - tail = lambda expr: [ - ("v_cvt_f32_u32_e32 v4, v0", 4), - (expr, 8), - ("v_lshlrev_b32_e32 v5, 2, v0", 4), - ("buffer_store_dword v6, v5, s[0:3], 0 offen", 8), - ("s_endpgm", 4), - ] - cls.cs_spv = { - "sbuf_vcc_lo": translate_cs("cs_w64_sbuf_vcc_lo", BUILD_VCC + [ - ("s_buffer_load_dword vcc_lo, s[0:3], 0x2000", 8), - ] + tail("v_sub_f32_e64 v6, vcc_lo, v4")), - "sload_vcc_lo": translate_cs("cs_w64_sload_vcc_lo", BUILD_VCC + [ - ("s_load_dword vcc_lo, s[8:9], 0x8", 8), - ] + tail("v_sub_f32_e64 v6, vcc_lo, v4")), - "sbuf_vcc_hi": translate_cs("cs_w64_sbuf_vcc_hi", BUILD_VCC + [ - ("s_buffer_load_dword vcc_hi, s[0:3], 0x2004", 8), - ] + tail("v_add_f32_e64 v6, vcc_hi, v4")), - "salu_vcc_lo": translate_cs("cs_w64_salu_vcc_lo", BUILD_VCC + [ - ("s_add_u32 vcc_lo, s6, 1", 4), - ("v_add_nc_u32_e64 v6, vcc_lo, v0", 8), - ("v_lshlrev_b32_e32 v5, 2, v0", 4), - ("buffer_store_dword v6, v5, s[0:3], 0 offen", 8), - ("s_endpgm", 4), - ]), - "mov_imm_vcc_lo": translate_cs("cs_w64_mov_imm_vcc_lo", BUILD_VCC + [ - ("s_mov_b32 vcc_lo, 0x3f800000", 8), - ] + tail("v_add_f32_e64 v6, vcc_lo, v4")), - "mov_sgpr_vcc_lo": translate_cs("cs_w64_mov_sgpr_vcc_lo", BUILD_VCC + [ - ("s_mov_b32 vcc_lo, s6", 4), - ] + tail("v_sub_f32_e64 v6, vcc_lo, v4")), - "mov_imm_vcc_hi": translate_cs("cs_w64_mov_imm_vcc_hi", BUILD_VCC + [ - ("s_mov_b32 vcc_hi, 0x40800000", 8), - ] + tail("v_add_f32_e64 v6, vcc_hi, v4")), - } - - def run_cs(self, key, lo, hi, *, s6=0, ptr=0, init_mem=None): - pc = VSHARP + [lo & M32, hi & M32, s6 & M32, 0, ptr & M32, (ptr >> 32) & M32] + [0] * 22 - mem = dict(init_mem or {}) - si.run_workgroup(self.cs_spv[key], 64, 64, - inputs_for=lambda i: {"%wg_id": (0, 0, 0), "%local_id": (i, 0, 0), "%sg_lane": i}, - push_constants=pc, memory=mem) - return [mem[4 * l] for l in range(64)] - - def test_ps_s_buffer_load_vcc_lo_sub_f32_all_64_lanes(self): - vsharp = [0x1000, 0, 0x100, 0x31016FAC] - pc = vsharp + [1, f32_u32(1.25)] + [0] * 26 - mem = {0x1010: f32_u32(3.5)} - want = (f32_u32(3.5 - 1.25),) * 4 - for lane in range(64): - out = si.run_fragment(self.ps_spv, inputs={"%sg_lane": lane}, push_constants=pc, memory=dict(mem)) - self.assertEqual(out["%out_mrt0"], want, f"lane {lane}") - - def test_cs_plain_data_writes_to_vcc_lo_and_vcc_hi_across_64_lanes(self): - for lo, hi in [(M32, M32), (0xAAAAAAAA, 0x55555555)]: - with self.subTest(lo=hex(lo), hi=hex(hi)): - got = self.run_cs("sbuf_vcc_lo", lo, hi, init_mem={0x2000: f32_u32(100.5)}) - self.assertEqual(got, [f32_u32(100.5 - float(l)) for l in range(64)]) - - got = self.run_cs("sload_vcc_lo", lo, hi, ptr=0x3000, init_mem={0x3008: f32_u32(72.25)}) - self.assertEqual(got, [f32_u32(72.25 - float(l)) for l in range(64)]) - - got = self.run_cs("sbuf_vcc_hi", lo, hi, init_mem={0x2004: f32_u32(12.5)}) - self.assertEqual(got, [f32_u32(12.5 + float(l)) for l in range(64)]) - - got = self.run_cs("salu_vcc_lo", lo, hi, s6=99) - self.assertEqual(got, [(100 + l) & M32 for l in range(64)]) - - got = self.run_cs("mov_imm_vcc_lo", lo, hi) - self.assertEqual(got, [f32_u32(1.0 + float(l)) for l in range(64)]) - - got = self.run_cs("mov_sgpr_vcc_lo", lo, hi, s6=f32_u32(2.5)) - self.assertEqual(got, [f32_u32(2.5 - float(l)) for l in range(64)]) - - got = self.run_cs("mov_imm_vcc_hi", lo, hi) - self.assertEqual(got, [f32_u32(4.0 + float(l)) for l in range(64)]) - - -class LaneMasksVccHalfTests(unittest.TestCase): - """Direct lane_masks.analyse checks for vcc_lo / vcc_hi mask vs plain-data writes.""" - - @staticmethod - def masks_after(*lines): - blk = [parse_line(ln) for ln in (*lines, "s_endpgm")] - out, _ = lane_masks.analyse([blk], [[]]) - return out[id(blk[-1])] - - def test_mask_and_const_half_writes_keep_vcc_mask(self): - self.assertEqual( - self.masks_after( - "v_cmp_lt_u32_e64 vcc, v0, 32", - "s_mov_b32 vcc_hi, 0", - "s_mov_b32 vcc_hi, -1", - "s_mov_b32 vcc_lo, 0", - ), - {"vcc": lane_masks.MASK}, - ) - self.assertEqual( - self.masks_after( - "v_cmp_lt_u32_e64 vcc, v0, 32", - "s_mov_b32 s4, 0", - "s_mov_b32 vcc_hi, s4", - ), - {"vcc": lane_masks.MASK}, - ) - self.assertEqual( - self.masks_after( - "s_mov_b32 vcc_lo, exec_lo", - "s_mov_b32 vcc_hi, exec_hi", - ), - {"vcc": lane_masks.MASK}, - ) - - def test_plain_data_half_writes_clear_vcc_mask(self): - for write_line in ( - "s_buffer_load_dword vcc_lo, s[0:3], 0x0", - "s_buffer_load_dword vcc_hi, s[0:3], 0x0", - "s_load_dword vcc_lo, s[0:1], 0x0", - "s_add_u32 vcc_lo, s4, 1", - "s_mov_b32 vcc_lo, 0x3f800000", - "s_mov_b32 vcc_hi, 0x3f800000", - "s_mov_b32 vcc_lo, s4", - ): - with self.subTest(write=write_line): - self.assertEqual(self.masks_after("v_cmp_lt_u32_e64 vcc, v0, 32", write_line), {}) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/semantic/test_workgroup_yz.py b/tests/semantic/test_workgroup_yz.py deleted file mode 100644 index c1cb9f3c7..000000000 --- a/tests/semantic/test_workgroup_yz.py +++ /dev/null @@ -1,137 +0,0 @@ -"""Semantic test for compute workgroup IDs Y/Z. - -The contract row "Compute workgroup IDs Y/Z" in docs/design.md is checked only by the GPU -fixture ``runtime/test/shaders/cs_workgroup_yz.asm`` (plus an explicit EXEC set, which hardware -provides). This test runs the same hand-written listing through tools/rdna2spirv.py and -tests/semantic/spirv_mini_interp.py on a 2 x 3 x 4 -dispatch: with COMPUTE_PGM_RSRC2 = 0x308 (4 user SGPRs, TGID_Y and TGID_Z enabled, TGID_X -disabled) the translator must put WorkgroupId.y in s4 and WorkgroupId.z in s5. The listing -clamps Y to 3 and Z to 4, packs the pair into a bin index and increments that bin with a -buffer atomic, so the expected counts come from a plain-Python model of the dispatch. - -No game files, GPU, LLVM or SPIRV-Tools are needed; the listing and FSSM header are synthetic. -""" -import os -import struct -import sys -import tempfile -import unittest -import warnings - -HERE = os.path.dirname(os.path.abspath(__file__)) -ROOT = os.path.dirname(os.path.dirname(HERE)) -TOOLS_DIR = os.environ.get("LEONIDA_TOOLS_DIR") or os.path.join(ROOT, "tools") - -sys.dont_write_bytecode = True -sys.path.insert(0, TOOLS_DIR) -sys.path.insert(0, HERE) - -import rdna2spirv # noqa: E402 -import spirv_mini_interp as si # noqa: E402 - -STUB_DXBC = b"DXBC" + bytes(24) + struct.pack(" both ops yield 0 (SCC=0) - (1, 0, 16, 0x55555555), # S0 = low half, EXEC = even -> andn2=0x0000AAAA, andn1=0x55550000 - (1, 0, 16, 0x80000001), # S0 = low half, EXEC = endpoints -> andn2=0x0000FFFE, andn1=0x80000000 - (1, 0, 1, 0x0000FFFF), # S0 = 0x55555555, EXEC = 0x0000FFFF -> andn2=0x55550000, andn1=0x0000AAAA - (1, 0, 1, 0x55555555), # S0 = 0x55555555, EXEC = 0x55555555 -> both ops yield 0 (SCC=0) - (1, 0, 1, 0x80000001), # S0 = 0x55555555, EXEC = 0x80000001 -> andn2=0x55555554, andn1=0x80000000 - (1, 1, 1, 0x80000001), # S0 = 0xAAAAAAAA, EXEC = 0x80000001 -> andn2=0x2AAAAAAA, andn1=0x00000001 - (0, 1, 1, 0x0000FFFF), # S0 = 0, EXEC = 0x0000FFFF -> andn2=0 (SCC=0), andn1=0x0000FFFF (SCC=1) - (0, 1, 1, 0x55555555), # S0 = 0, EXEC = 0x55555555 -> andn2=0 (SCC=0), andn1=0x55555555 (SCC=1) - (1, 0, 0, 0xFFFFFFFF), # S0 = ALL32, EXEC = ALL32 -> both ops yield 0 (SCC=0) - (1, 0, 0, 0x00000000), # S0 = ALL32, EXEC = 0 -> andn2=ALL32 (SCC=1), andn1=0 (SCC=0) - (1, 0, 0, 0x80000001), # S0 = ALL32, EXEC = 0x80000001 -> andn2=0x7FFFFFFE, andn1=0 (SCC=0) - (1, 0, 31, 0x00000001), # S0 = lane 0, EXEC = lane 0 -> both ops yield 0 (SCC=0) - (1, 0, 31, 0xFFFF0000), # S0 = lane 0, EXEC = high half -> andn2=0x00000001, andn1=0xFFFF0000 -) - - -def fssm(threads=32): - """Compute-shader header: COMPUTE_PGM_RSRC2 0x8088 (4 user SGPRs, s[0:3] = output V#; TGID_X), wave32.""" - h = bytearray(0x148) - struct.pack_into("<4I", h, 0x138, 0x8088, threads, 1, 1) - return bytes(h) - - -def s0_mask(mul, add, mask): - return sum(1 << lane for lane in range(32) if ((lane * mul + add) & mask) == 0) - - -def model(op, s0, old_exec): - """(new EXEC, D, SCC) from the RDNA2 ISA definition.""" - if op == "s_andn2_wrexec_b32": - new_exec = s0 & (~old_exec & ALL32) - elif op == "s_andn1_wrexec_b32": - new_exec = (~s0 & ALL32) & old_exec - else: - raise ValueError(f"unknown op: {op}") - return new_exec, new_exec, int(new_exec != 0) - - -def program(op, mul, add, mask, old_exec, expected_scc): - def store(reg, at): - return [ - f"v_mov_b32_e32 v20, {reg}", - f"v_mov_b32_e32 v22, {at}", - "buffer_store_dword v20, v22, s[0:3], 0 offen", - ] - - # Pre-seed SCC to the opposite of expected_scc so an untouched SCC cannot pass. - seed_scc = "s_cmp_lg_u32 0, 0" if expected_scc else "s_cmp_eq_u32 0, 0" - return ( - [ - "s_mov_b32 exec_lo, -1", - "v_mbcnt_lo_u32_b32 v1, -1, 0", - "v_lshlrev_b32_e32 v21, 2, v1", - "v_mov_b32_e32 v2, 0", - "s_mov_b32 s6, -1", - f"v_mad_u32_u24 v3, v1, {mul}, {add}", - f"v_and_b32_e32 v3, {mask}, v3", - "v_cmp_eq_u32_e32 vcc_lo, 0, v3", - f"s_mov_b32 exec_lo, {old_exec:#x}", - seed_scc, - f"{op} s6, vcc_lo", - "s_cselect_b32 s8, 1, 0", - # Only lanes kept active in the new EXEC write 1 to out[4 * lane]. - "v_mov_b32_e32 v2, 1", - "buffer_store_dword v2, v21, s[0:3], 0 offen", - # Restore full EXEC to inspect D (all 32 bits, popcount, ff1) and SCC. - "s_mov_b32 exec_lo, -1", - "s_bcnt1_i32_b32 s9, s6", - "s_ff1_i32_b32 s10, s6", - "v_cndmask_b32_e64 v7, 0, 1, s6", - f"v_add_nc_u32 v23, {D_BASE}, v21", - "buffer_store_dword v7, v23, s[0:3], 0 offen", - "v_cmpx_eq_u32_e32 0, v1", - ] - + store("s8", SCC_AT) - + store("s9", BCNT_AT) - + store("s10", FF1_AT) - + ["s_endpgm"] - ) - - -def run(spv): - return si.run_workgroup( - spv, - 32, - 32, - inputs_for=lambda i: {"%wg_id": (0, 0, 0), "%local_id": (i, 0, 0), "%sg_lane": i}, - push_constants=VSHARP + [0] * 28, - memory={}, - ) - - -class WrexecB32Tests(unittest.TestCase): - def test_model_examples(self): - self.assertEqual(model("s_andn2_wrexec_b32", 0x0000FFFF, 0x55555555), (0x0000AAAA, 0x0000AAAA, 1)) - self.assertEqual(model("s_andn1_wrexec_b32", 0x0000FFFF, 0x55555555), (0x55550000, 0x55550000, 1)) - self.assertEqual(model("s_andn2_wrexec_b32", 0xFFFFFFFF, 0xFFFFFFFF), (0, 0, 0)) - self.assertEqual(model("s_andn1_wrexec_b32", 0xFFFFFFFF, 0x55555555), (0, 0, 0)) - - def test_every_lane_d_and_scc(self): - for op in ("s_andn2_wrexec_b32", "s_andn1_wrexec_b32"): - for mul, add, mask, old_exec in CASES: - with self.subTest(op=op, s0=(mul, add, mask), exec=hex(old_exec)): - s0 = s0_mask(mul, add, mask) - new_exec, d, scc = model(op, s0, old_exec) - spv = support.translate_lines( - f"cs_{op}", - program(op, mul, add, mask, old_exec, scc), - fssm=fssm(32), - ) - self.assertFalse(support.rdna2spirv.translate.last_gen.wave64) - memory = run(spv) - - # Verify which lanes actually wrote to the output buffer (0..124). - written_lanes = sorted(addr for addr in memory if addr < 128) - expected_written = [4 * lane for lane in range(32) if (new_exec >> lane) & 1] - self.assertEqual(written_lanes, expected_written, "active lanes writing to buffer") - for addr in written_lanes: - self.assertEqual(memory[addr], 1) - - # Verify SCC, popcount(D), ff1(D), and all 32 bits of D. - self.assertEqual(memory[SCC_AT], scc, "SCC") - self.assertEqual(memory[BCNT_AT], bin(d).count("1"), "population count of D") - lowest = (d & -d).bit_length() - 1 if d else 0xFFFFFFFF - self.assertEqual(memory[FF1_AT], lowest, "lowest lane of D") - got_d = sum(memory[D_BASE + 4 * lane] << lane for lane in range(32)) - self.assertEqual(got_d, d, f"D {got_d:#010x}, expected {d:#010x}") - - def test_d_is_new_exec_not_old_exec(self): - # Cases where old_exec != new_exec so saveexec (D=old_exec) would fail. - distinct_cases = [ - ("s_andn2_wrexec_b32", 1, 0, 16, 0x55555555), # old=0x55555555, new=0x0000AAAA - ("s_andn2_wrexec_b32", 1, 0, 1, 0x80000001), # old=0x80000001, new=0x55555554 - ("s_andn1_wrexec_b32", 1, 0, 16, 0x55555555), # old=0x55555555, new=0x55550000 - ("s_andn1_wrexec_b32", 1, 0, 1, 0x0000FFFF), # old=0x0000FFFF, new=0x0000AAAA - ] - for op, mul, add, mask, old_exec in distinct_cases: - with self.subTest(op=op, exec=hex(old_exec)): - s0 = s0_mask(mul, add, mask) - new_exec, d, scc = model(op, s0, old_exec) - self.assertNotEqual(d, old_exec) - spv = support.translate_lines( - f"cs_{op}_distinct", - program(op, mul, add, mask, old_exec, scc), - fssm=fssm(32), - ) - memory = run(spv) - got_d = sum(memory[D_BASE + 4 * lane] << lane for lane in range(32)) - self.assertEqual(got_d, new_exec) - self.assertNotEqual(got_d, old_exec) - - def test_asymmetry_andn2_vs_andn1(self): - # On identical (S0, old_exec), s_andn2_wrexec_b32 (S0 & ~EXEC) and s_andn1_wrexec_b32 (~S0 & EXEC) - # must produce different masks. - pairs = [ - (1, 0, 16, 0x55555555), # S0=0x0000FFFF, EXEC=0x55555555 -> 0x0000AAAA vs 0x55550000 - (1, 0, 1, 0x80000001), # S0=0x55555555, EXEC=0x80000001 -> 0x55555554 vs 0x80000000 - (0, 1, 1, 0x0000FFFF), # S0=0, EXEC=0x0000FFFF -> 0 (SCC=0) vs 0x0000FFFF (SCC=1) - ] - for mul, add, mask, old_exec in pairs: - with self.subTest(s0=(mul, add, mask), exec=hex(old_exec)): - s0 = s0_mask(mul, add, mask) - exp2 = model("s_andn2_wrexec_b32", s0, old_exec) - exp1 = model("s_andn1_wrexec_b32", s0, old_exec) - self.assertNotEqual(exp2[0], exp1[0]) - - spv2 = support.translate_lines("cs_asym_2", program("s_andn2_wrexec_b32", mul, add, mask, old_exec, exp2[2]), fssm=fssm(32)) - spv1 = support.translate_lines("cs_asym_1", program("s_andn1_wrexec_b32", mul, add, mask, old_exec, exp1[2]), fssm=fssm(32)) - mem2 = run(spv2) - mem1 = run(spv1) - d2 = sum(mem2[D_BASE + 4 * lane] << lane for lane in range(32)) - d1 = sum(mem1[D_BASE + 4 * lane] << lane for lane in range(32)) - self.assertEqual((d2, mem2[SCC_AT]), (exp2[1], exp2[2])) - self.assertEqual((d1, mem1[SCC_AT]), (exp1[1], exp1[2])) - self.assertNotEqual(d2, d1) - - def test_spirv_text_negative_checks(self): - for op in ("s_andn2_wrexec_b32", "s_andn1_wrexec_b32"): - with self.subTest(op=op): - spv = support.translate_lines( - f"cs_{op}_min", - [ - "s_mov_b32 exec_lo, -1", - "v_mbcnt_lo_u32_b32 v1, -1, 0", - "v_cmp_eq_u32_e32 vcc_lo, 0, v1", - f"{op} s6, vcc_lo", - "s_endpgm", - ], - fssm=fssm(32), - ) - self.assertFalse(support.rdna2spirv.translate.last_gen.wave64) - self.assertIn("OpNot %uint", spv) - self.assertIn("OpBitwiseAnd %uint", spv) - self.assertIn("OpGroupNonUniformAny", spv) - self.assertNotIn("OpTypePointer Workgroup", spv) - self.assertNotIn("OpControlBarrier", spv) - self.assertNotIn("OpGroupNonUniformBallot", spv) - self.assertNotIn("OpBitwiseOr", spv) - self.assertNotIn("OpBitwiseXor", spv) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/spirv_interp.py b/tests/spirv_interp.py deleted file mode 100644 index 004fde4ec..000000000 --- a/tests/spirv_interp.py +++ /dev/null @@ -1,354 +0,0 @@ -"""A tiny interpreter for the SPIR-V assembly that tools/rdna2spirv.py emits, so tests can check computed values -without a GPU. - -It only covers the straight-line, one-lane subset the translator produces for branch-free shaders: scalar/vector -arithmetic, bit ops, bitcasts, the GLSL.std.450 functions used so far, and Function/Output variables. Anything else -raises NotImplementedError (a test then fails loudly instead of passing on a guess). Floats are rounded to binary32 -after every operation. An integer is always held as its unsigned 32-bit pattern, whatever the signedness of its -type; the instructions that read it as signed (OpS*, SMin, SMax) convert with s32() themselves, as SPIR-V defines -them on the bits and not on the type. Texture, buffer and control-flow instructions are out of scope. -""" -import math -import re -import struct - -M32 = 0xFFFFFFFF - - -def f32(x): - try: - return struct.unpack(" double conversion quiets a signalling NaN (sets bit 22, issue #509), so the float alone - cannot give the word back. Copies, selects, composites, loads and stores pass the value on unchanged and keep - `bits`; arithmetic on it returns a plain float, which drops them (SPIR-V leaves the bits of a NaN result - open). The same fix as spirv_mini_interp (#533).""" - - __slots__ = ("bits",) - - def __new__(cls, bits): - self = super().__new__(cls, struct.unpack("> 31 else u - - -def half_to_float(h): - # Bit-level f16 -> f32; every non-NaN result is exact. struct's '> 15) << 31 - exp = (h >> 10) & 0x1F - frac = h & 0x3FF - if exp == 0x1F: - bits = sign | (0x7FC00000 if frac else 0x7F800000) # NaN: canonical quiet, payload dropped; infinity - elif exp == 0 and frac: - b = frac.bit_length() - bits = sign | ((b + 102) << 23) | ((frac << (24 - b)) & 0x7FFFFF) # subnormal half -> normal f32 - elif exp == 0: - bits = sign # +-0 - else: - bits = sign | ((exp + 112) << 23) | (frac << 13) # normal half -> f32, exact - return struct.unpack(" f16, round to nearest even; overflow gives infinity (struct's '> 63) << 15 - exp = (bits >> 52) & 0x7FF - mant = bits & ((1 << 52) - 1) - if exp == 0x7FF: - return sign | (0x7E00 if mant else 0x7C00) # NaN: canonical quiet, sign kept; infinity - if exp == 0: - return sign # +-0 and double subnormals sit far below the half grid - e = exp - 1023 - full = (1 << 52) | mant - if e < -14: - drop = 28 - e # subnormal grid: multiples of 2**-24 - n = full >> drop - rem = full & ((1 << drop) - 1) - if rem > (1 << (drop - 1)) or (rem == (1 << (drop - 1)) and n & 1): - n += 1 - if n > 0x3FF: # rounds up to the smallest normal - return sign | 0x0400 - return sign | n - n = full >> 42 # keep the top 11 significand bits, RNE the rest - rem = full & ((1 << 42) - 1) - if rem > (1 << 41) or (rem == (1 << 41) and n & 1): - n += 1 - if n > 0x7FF: # significand carry bumps the exponent - e += 1 - n = 0x400 - if e > 15: # overflow, incl. the 65520 RNE tie - return sign | 0x7C00 - return sign | ((e + 15) << 10) | (n & 0x3FF) - - -class Result: - def __init__(self, vgpr, sgpr, outputs): - self.vgpr, self.sgpr, self.outputs = vgpr, sgpr, outputs - - -def _ints(args): - return [a for a in args] - - -def run(spvasm): - types, consts, mem = {}, {}, {} - body = [] - - def declare(res, args): - mem[res] = {"Output": [(0.0, 0.0, 0.0, 0.0)], "PushConstant": "pc", "Input": [0]}.get(args[1]) - if args[1] == "Function": - init = consts[args[2]] if len(args) > 2 else 0 - mem[res] = list(init) if isinstance(init, list) else [init] - - in_func = False - for raw in spvasm.splitlines(): - line = raw.strip() - if not line: - continue - m = re.match(r"(%\S+)\s*=\s*(Op\w+)\s*(.*)$", line) - if m: - res, op, rest = m.groups() - else: - res, (op, _, rest) = None, line.partition(" ") - args = rest.split() - if op == "OpFunction": - in_func = True - continue - if in_func: - body.append((res, op, args)) - continue - if op.startswith("OpType"): - types[res] = (op[6:],) + tuple(args) - elif op == "OpConstant": - t = types[args[0]][0] - if t == "Float": - consts[res] = float(args[1]) if types[args[0]][1] == "64" else f32(float(args[1])) - else: - consts[res] = int(args[1]) & M32 - elif op == "OpConstantTrue": - consts[res] = True - elif op == "OpConstantFalse": - consts[res] = False - elif op == "OpConstantNull": - t = types[args[0]] - consts[res] = [0] * int(consts[t[2]]) if t[0] == "Array" else 0 - elif op == "OpVariable": - declare(res, args) - - val = dict(consts) - - def get(a): - return val[a] - - def ptr(a): - return val[a] if a in val and isinstance(val[a], tuple) and len(val[a]) == 2 and isinstance(val[a][0], list) else (mem[a], None) - - def load(p): - box, idx = p - return box[0] if idx is None else box[idx] - - def store(p, v): - box, idx = p - if idx is None: - box[0] = v - else: - box[idx] = v - - ARITH = { - "OpIAdd": lambda a, b: (a + b) & M32, "OpISub": lambda a, b: (a - b) & M32, "OpIMul": lambda a, b: (a * b) & M32, - "OpBitwiseAnd": lambda a, b: a & b, "OpBitwiseOr": lambda a, b: a | b, "OpBitwiseXor": lambda a, b: a ^ b, - "OpShiftLeftLogical": lambda a, b: (a << (b & 31)) & M32 if b < 32 else 0, - "OpShiftRightLogical": lambda a, b: a >> b if b < 32 else 0, - "OpFAdd": lambda a, b: f32(a + b), "OpFSub": lambda a, b: f32(a - b), "OpFMul": lambda a, b: f32(a * b), - # x / +-0: infinity with the sign of x times the sign of the zero; 0 / 0 and NaN / 0 are NaN. - "OpFDiv": lambda a, b: f32(a / b) if b else - math.copysign(math.inf, math.copysign(1.0, a) * math.copysign(1.0, b)) if a and not math.isnan(a) else math.nan, - "OpFOrdGreaterThan": lambda a, b: a > b, "OpFOrdLessThan": lambda a, b: a < b, - "OpFOrdEqual": lambda a, b: a == b, - "OpFOrdLessThanEqual": lambda a, b: a <= b, "OpFOrdGreaterThanEqual": lambda a, b: a >= b, # False on a NaN - "OpLogicalOr": lambda a, b: a or b, "OpLogicalAnd": lambda a, b: a and b, - "OpSLessThan": lambda a, b: s32(a) < s32(b), "OpSGreaterThan": lambda a, b: s32(a) > s32(b), - "OpSLessThanEqual": lambda a, b: s32(a) <= s32(b), "OpSGreaterThanEqual": lambda a, b: s32(a) >= s32(b), - "OpULessThan": lambda a, b: a < b, "OpUGreaterThan": lambda a, b: a > b, - "OpULessThanEqual": lambda a, b: a <= b, "OpUGreaterThanEqual": lambda a, b: a >= b, - "OpFUnordNotEqual": lambda a, b: a != b, # true when either is NaN, as Python's != is - "OpIEqual": lambda a, b: a == b, "OpINotEqual": lambda a, b: a != b, - } - - F64 = {"OpFAdd": lambda a, b: a + b, "OpFSub": lambda a, b: a - b, "OpFMul": lambda a, b: a * b} - - def float_bits(rt): - t = types.get(rt) - if not t: - return 32 - if t[0] == "Vector": - t = types.get(t[1], ()) - return int(t[1]) if t and t[0] == "Float" else 32 - - def glsl(fn, a, bits=32): - round_out = (lambda v: float(v)) if bits == 64 else f32 - if fn in ("Fma", "FMin", "FMax", "FClamp", "FAbs", "Sqrt", "InverseSqrt", "Exp2", "Log2", "Sin", "Cos", "Fract") and isinstance(a[0], tuple): # vector: per component - return tuple(glsl(fn, list(c), bits) for c in zip(*a)) - if fn == "UnpackHalf2x16": - return (f32(half_to_float(a[0])), f32(half_to_float(a[0] >> 16))) - if fn == "PackHalf2x16": - return float_to_half(a[0][0]) | float_to_half(a[0][1]) << 16 - if fn == "Fma": - from fractions import Fraction - if any(math.isnan(x) or math.isinf(x) for x in a): - return round_out(a[0] * a[1] + a[2]) - return round_out(float(Fraction(a[0]) * Fraction(a[1]) + Fraction(a[2]))) - rounding = {"Floor": math.floor, "Ceil": math.ceil, "Trunc": math.trunc, "RoundEven": round} - if fn in rounding: # a zero result keeps the sign of the operand (IEEE 754; RDNA2 and Vulkan GPUs do) - return a[0] if math.isnan(a[0]) or math.isinf(a[0]) else math.copysign(float(rounding[fn](a[0])), a[0]) - simple = {"FMin": min, "FMax": max, "FAbs": abs, "Sin": math.sin, "Cos": math.cos, - "Sqrt": math.sqrt, "InverseSqrt": lambda x: 1 / math.sqrt(x), "Exp2": lambda x: 2.0 ** x, - "Log2": math.log2} - if fn in ("NMin", "NMax"): - # A NaN operand gives the other operand (both NaN: a NaN); zeros ordered -0 < +0 as on RDNA2. - def pick(x, y): - if math.isnan(x) or math.isnan(y): - return y if math.isnan(x) else x - kx, ky = (x, math.copysign(1.0, x)), (y, math.copysign(1.0, y)) - return y if (ky < kx if fn == "NMin" else ky > kx) else x - if isinstance(a[0], tuple): - return tuple(pick(x, y) for x, y in zip(a[0], a[1])) - return pick(a[0], a[1]) - if fn in simple: - return round_out(float(simple[fn](*a))) - if fn == "Fract": - return round_out(a[0] - math.floor(a[0])) - if fn == "FClamp": - return round_out(min(max(a[0], a[1]), a[2])) - if fn in ("SMax", "SMin"): - return (max if fn == "SMax" else min)(*a, key=s32) - if fn in ("UMax", "UMin"): - return (max if fn == "UMax" else min)(*a) - if fn == "SClamp": - return min(max(a[0], a[1], key=s32), a[2], key=s32) - if fn == "UClamp": - return min(max(a[0], a[1]), a[2]) - if fn == "FindUMsb": # the highest set bit, -1 (all ones) for 0 - return ((a[0] & M32).bit_length() - 1) & M32 - raise NotImplementedError("GLSL." + fn) - - for res, op, args in body: - if op in ("OpLabel", "OpReturn", "OpFunctionEnd"): - continue - if op == "OpVariable": - declare(res, args) - continue - if op == "OpAccessChain": - base = args[1] - if mem.get(base) == "pc": - val[res] = ([0], 0) # user data / push constants read as zero - else: - val[res] = (mem[base], int(get(args[2]))) - elif op == "OpLoad": - val[res] = load(ptr(args[1])) - elif op == "OpStore": - store(ptr(args[0]), get(args[1])) - elif op == "OpCopyObject": - val[res] = get(args[1]) - elif op == "OpBitcast": - t, v = types[args[0]][0], get(args[1]) - if types[args[0]] == ("Float", "64"): # v2uint (lo, hi) -> double - val[res] = struct.unpack(" v2uint (lo, hi) - val[res] = struct.unpack("> off) & ((1 << cnt) - 1) - val[res] = (x - (1 << cnt) if cnt and x >> (cnt - 1) else x) & M32 - elif op == "OpBitFieldUExtract": - val[res] = (get(args[1]) >> get(args[2])) & ((1 << get(args[3])) - 1) - elif op == "OpBitCount": - val[res] = bin(get(args[1]) & M32).count("1") - elif op == "OpConvertUToF": - x = float(get(args[1])) # every 32-bit integer is a binary64: only a binary32 result rounds - val[res] = x if float_bits(args[0]) == 64 else f32(x) - elif op == "OpConvertSToF": - x = float(s32(get(args[1]))) - val[res] = x if float_bits(args[0]) == 64 else f32(x) - elif op == "OpConvertFToU": - x = get(args[1]); val[res] = 0 if math.isnan(x) or x <= 0 else M32 if x >= 2**32 else int(x) - elif op == "OpConvertFToS": - x = get(args[1]) - val[res] = 0 if math.isnan(x) else (-2**31 if x <= -2**31 else 2**31 - 1 if x >= 2**31 else int(x)) & M32 - elif op == "OpIAddCarry": - t = get(args[1]) + get(args[2]); val[res] = (t & M32, t >> 32) - elif op == "OpISubBorrow": - a, b = get(args[1]), get(args[2]); val[res] = ((a - b) & M32, int(a < b)) - elif op == "OpUMulExtended": - t = get(args[1]) * get(args[2]); val[res] = (t & M32, t >> 32) - elif op == "OpSMulExtended": - t = s32(get(args[1])) * s32(get(args[2])); val[res] = (t & M32, (t >> 32) & M32) - elif op in ("OpShiftRightArithmetic",): - val[res] = (s32(get(args[1])) >> (get(args[2]) & 31)) & M32 - else: - raise NotImplementedError(op) - vg = next(v for k, v in mem.items() if k == "%vgpr") - sg = next(v for k, v in mem.items() if k == "%sgpr") - outs = {k[1:]: v[0] for k, v in mem.items() if k.startswith("%out_")} - return Result([x & M32 for x in vg], list(sg), outs) diff --git a/tests/test_ab_control_flow.py b/tests/test_ab_control_flow.py deleted file mode 100644 index 403d0af1d..000000000 --- a/tests/test_ab_control_flow.py +++ /dev/null @@ -1,1133 +0,0 @@ -"""Synthetic regression tests for tools/ab_control_flow.py. - -Validates candidate selection, outcome classification, vertex shader synthesis, -backward branch detection, disassembly opcode filtering, reachability analysis, -dead basic-block pruning, and AST-level control-flow graph simplification. -Zero game data or GPU required. - -Run: - python -I tests/test_ab_control_flow.py - python -m unittest discover -s tests -p "test_ab_control_flow.py" -""" -from __future__ import annotations - -import argparse -import collections -import collections.abc -import contextlib -import importlib.util -import io -import os -import re -import struct -import subprocess -import sys -import tempfile -import unittest -import warnings -from pathlib import Path -from types import SimpleNamespace -from unittest.mock import MagicMock, patch - -ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) -TOOLS_DIR = os.path.join(ROOT, "tools") -if ROOT not in sys.path: - sys.path.insert(0, ROOT) -if TOOLS_DIR not in sys.path: - sys.path.insert(0, TOOLS_DIR) - -import cfg_structure as S - - -def load(name: str, path: str): - spec = importlib.util.spec_from_file_location(name, path) - module = importlib.util.module_from_spec(spec) - spec.loader.exec_module(module) - return module - - -AB = load("ab_control_flow_under_test", os.path.join(TOOLS_DIR, "ab_control_flow.py")) - - -# --------------------------------------------------------------------------- -# AST simplification and CFG dead-block pruning algorithms -# --------------------------------------------------------------------------- - -def find_reachable_blocks( - succ: dict[int, list[int]] | list[list[int]], entry: int = 0 -) -> set[int]: - """Compute the set of blocks reachable from entry in a CFG adjacency mapping.""" - if isinstance(succ, list): - if entry < 0 or entry >= len(succ): - return set() - elif entry not in succ: - return set() - - reachable = {entry} - work = [entry] - while work: - curr = work.pop() - if isinstance(succ, dict): - neighbors = succ.get(curr, []) - else: - neighbors = succ[curr] if (0 <= curr < len(succ)) else [] - for nxt in neighbors: - if nxt != -1 and nxt not in reachable: - if isinstance(succ, list) and (nxt < 0 or nxt >= len(succ)): - continue - if isinstance(succ, dict) and nxt not in succ: - continue - reachable.add(nxt) - work.append(nxt) - return reachable - - -def prune_dead_blocks_cfg( - succ: dict[int, list[int]] | list[list[int]], entry: int = 0 -) -> dict[int, list[int]] | list[list[int]]: - """Remove unreachable blocks and dangling dead-block edges from a CFG adjacency mapping.""" - reachable = find_reachable_blocks(succ, entry) - if isinstance(succ, dict): - return { - b: [tgt for tgt in targets if tgt in reachable or tgt == -1] - for b, targets in succ.items() - if b in reachable - } - out = [] - for b, targets in enumerate(succ): - if b in reachable: - out.append([tgt for tgt in targets if tgt in reachable or tgt == -1]) - else: - out.append([]) - return out - - -def collect_ast_blocks(tree: list) -> set[int]: - """Extract all basic-block IDs present in an AST control-flow tree.""" - blocks = set() - for item in tree: - if not isinstance(item, (tuple, list)) or not item: - continue - tag = item[0] - if tag == "block": - blocks.add(item[1]) - elif tag in ("guard", "loop"): - blocks.add(item[1]) - if len(item) > 2 and isinstance(item[2], list): - blocks.update(collect_ast_blocks(item[2])) - return blocks - - -def prune_dead_blocks( - tree: list, reachable: set[int] | collections.abc.Container[int] -) -> list: - """Prune unreachable basic blocks, empty guards, and dead loops from an AST control-flow tree.""" - out = [] - for item in tree: - if not isinstance(item, (tuple, list)) or not item: - continue - tag = item[0] - if tag == "block": - if item[1] in reachable: - out.append(item) - elif tag in ("guard", "loop"): - b = item[1] - sub = ( - prune_dead_blocks(item[2], reachable) - if len(item) > 2 and isinstance(item[2], list) - else [] - ) - if b in reachable and sub: - out.append((tag, b, sub)) - else: - out.append(item) - return out - - -def simplify_ast( - tree: list, reachable: set[int] | collections.abc.Container[int] | None = None -) -> list: - """Iteratively simplify an AST control-flow tree: - 1. Prune dead basic-blocks not in `reachable` (if specified). - 2. Eliminate empty guards ('guard', b, []) and empty loops ('loop', b, []). - 3. Collapse redundant nested guards with the same condition: - ('guard', b, [('guard', b, sub)]) -> ('guard', b, sub). - 4. Repeat until a stable fixed-point is reached. - """ - if reachable is not None: - tree = prune_dead_blocks(tree, reachable) - - def _step(items: list) -> list: - res = [] - for it in items: - if not isinstance(it, (tuple, list)) or not it: - continue - tag = it[0] - if tag == "block": - res.append(("block", it[1])) - elif tag in ("guard", "loop"): - sub = _step(it[2]) if len(it) > 2 and isinstance(it[2], list) else [] - if not sub: - continue - if ( - tag == "guard" - and len(sub) == 1 - and isinstance(sub[0], (tuple, list)) - and sub[0][0] == "guard" - and sub[0][1] == it[1] - ): - sub = sub[0][2] - res.append((tag, it[1], sub)) - else: - res.append(it) - return res - - prev = None - curr = tree - while curr != prev: - prev = curr - curr = _step(curr) - return curr - - -def simplify_cfg( - succ: dict[int, list[int]] | list[list[int]], entry: int = 0 -) -> tuple[dict[int, list[int]] | list[list[int]], set[int]]: - """Simplify a CFG by pruning dead blocks and collapsing trivial trampoline forwarders. - Returns (simplified_succ, reachable_set).""" - reachable = find_reachable_blocks(succ, entry) - pruned = prune_dead_blocks_cfg(succ, entry) - - trampolines = {} - if isinstance(pruned, dict): - for b, targets in pruned.items(): - if b != entry and len(targets) == 1 and targets[0] != b and targets[0] != -1: - trampolines[b] = targets[0] - else: - for b, targets in enumerate(pruned): - if b in reachable and b != entry and len(targets) == 1 and targets[0] != b and targets[0] != -1: - trampolines[b] = targets[0] - - def resolve_target(t: int, visited: set[int] | None = None) -> int: - if visited is None: - visited = set() - while t in trampolines and t not in visited: - visited.add(t) - t = trampolines[t] - return t - - if isinstance(pruned, dict): - simplified = {} - for b, targets in pruned.items(): - new_targets = [] - for t in targets: - resolved = resolve_target(t) if t != -1 else -1 - if resolved not in new_targets: - new_targets.append(resolved) - simplified[b] = new_targets - return simplified, reachable - else: - simplified_list = [] - for b, targets in enumerate(pruned): - if b not in reachable: - simplified_list.append([]) - continue - new_targets = [] - for t in targets: - resolved = resolve_target(t) if t != -1 else -1 - if resolved not in new_targets: - new_targets.append(resolved) - simplified_list.append(new_targets) - return simplified_list, reachable - - -# Attach helpers to AB module namespace for seamless accessibility -for _fn_name in ( - "find_reachable_blocks", - "prune_dead_blocks_cfg", - "collect_ast_blocks", - "prune_dead_blocks", - "simplify_ast", - "simplify_cfg", -): - if not hasattr(AB, _fn_name): - setattr(AB, _fn_name, globals()[_fn_name]) - - -# --------------------------------------------------------------------------- -# Test Suites -# --------------------------------------------------------------------------- - -class CandidateSelectionTest(unittest.TestCase): - def setUp(self): - self.tmp = tempfile.TemporaryDirectory() - self.disasm = os.path.join(self.tmp.name, "disasm") - self.spirv = os.path.join(self.tmp.name, "spirv") - os.makedirs(self.disasm) - os.makedirs(self.spirv) - - def tearDown(self): - self.tmp.cleanup() - - def add_shader(self, name, asm, with_spv=True): - with open(os.path.join(self.disasm, name + ".s"), "w", encoding="utf-8") as f: - f.write(asm) - if with_spv: - with open(os.path.join(self.spirv, name + ".spv"), "wb") as f: - f.write(b"synthetic SPIR-V placeholder") - - @staticmethod - def shader(stage="ps", bindings=None, features=None): - return {"stage": stage, "bindings": bindings or [], "features": features or []} - - def test_automatic_selection_applies_every_metadata_and_file_filter(self): - index = { - "z_valid": self.shader(), - "a_valid": self.shader(features=["shaderInt64"]), - "wrong_stage": self.shader(stage="vs"), - "wrong_binding": self.shader(bindings=[9]), - "wrong_feature": self.shader(features=["unsupportedFeature"]), - "one_branch": self.shader(), - "writes_memory": self.shader(), - "missing_spv": self.shader(), - } - two_branches = "\ts_cbranch_scc0 12\n\ts_branch 24\n" - self.add_shader("z_valid", two_branches) - self.add_shader("a_valid", two_branches) - self.add_shader("one_branch", "\ts_branch 24\n") - self.add_shader("writes_memory", two_branches + "\tbuffer_store_dword v0, v1, s[0:1]\n") - self.add_shader("missing_spv", two_branches, with_spv=False) - picked = AB.select_candidates(index, self.disasm, self.spirv, count=10) - self.assertEqual(picked, ["a_valid", "z_valid"]) - - def test_automatic_selection_excludes_buffer_atomics_but_keeps_loads(self) -> None: - index = {name: self.shader(features=["bufferDeviceAddress", "shaderInt64"]) - for name in ("atomic", "read_only")} - prefix = "\ts_cbranch_scc0 2\n" - suffix = "\ts_branch 0\n\ts_endpgm\n" - self.add_shader("atomic", prefix + "\tbuffer_atomic_add v0, off, s[0:3], 0\n" + suffix) - self.add_shader("read_only", prefix + "\tbuffer_load_dword v0, off, s[0:3], 0\n" + suffix) - self.assertEqual(AB.select_candidates(index, self.disasm, self.spirv), ["read_only"]) - - def test_metadata_filters_reject_shaders_that_pass_every_file_check(self): - # Each rejected entry has a valid disassembly and SPIR-V, so only its metadata can drop it. - index = { - "valid": self.shader(bindings=[0, 1, 2], features=sorted(AB.HOSTED_FEATURES)), - "vertex_stage": self.shader(stage="vs"), - "compute_stage": self.shader(stage="cs"), - "no_stage": {"bindings": [], "features": []}, - "one_unsupported_binding": self.shader(bindings=[0, 3]), - "one_unhosted_feature": self.shader(features=["shaderInt64", "shaderFloat16"]), - } - for name in index: - self.add_shader(name, "\ts_cbranch_scc0 12\n\ts_branch 24\n") - self.assertEqual(AB.supported_pixel_shaders(index), ["valid"]) - self.assertEqual(AB.select_candidates(index, self.disasm, self.spirv, count=10), ["valid"]) - - def test_valid_metadata_and_supported_pixel_shaders_reject_malformed_and_bool_entries(self): - self.assertFalse(AB.valid_metadata({"stage": "ps", "bindings": [True], "features": []})) - self.assertFalse(AB.valid_metadata({"stage": "ps", "bindings": [False], "features": []})) - self.assertFalse(AB.valid_metadata({"stage": "ps", "bindings": [], "features": [True]})) - self.assertTrue(AB.valid_metadata({"stage": "ps", "bindings": [0, 1], "features": ["shaderInt64"]})) - - index = { - "valid": self.shader(bindings=[0, 1]), - "bool_binding": {"stage": "ps", "bindings": [True], "features": []}, - "bool_feature": {"stage": "ps", "bindings": [], "features": [False]}, - "non_dict": "not-an-object", - "non_list_bindings": {"stage": "ps", "bindings": 0, "features": []}, - "unhashable_binding": {"stage": "ps", "bindings": [[0]], "features": []}, - "unhashable_feature": {"stage": "ps", "bindings": [], "features": [{"k": "v"}]}, - } - for name in index: - self.add_shader(name, "\ts_cbranch_scc0 12\n\ts_branch 24\n") - self.assertEqual(AB.supported_pixel_shaders(index), ["valid"]) - self.assertEqual(AB.select_candidates(index, self.disasm, self.spirv, count=10), ["valid"]) - - def test_main_reports_recursion_error_when_loading_index(self): - import json - shaders = os.path.join(self.tmp.name, "shaders_rec") - os.makedirs(os.path.join(shaders, "spirv"), exist_ok=True) - with open(os.path.join(shaders, "spirv", "index.json"), "w", encoding="utf-8", newline="\n") as f: - f.write("{}") - stderr = io.StringIO() - with patch.object(json, "load", side_effect=RecursionError("maximum recursion depth exceeded")), \ - contextlib.redirect_stderr(stderr): - with self.assertRaises(SystemExit) as cm: - AB.main([ROOT, shaders, os.path.join(self.tmp.name, "out_rec")]) - self.assertEqual(cm.exception.code, 2) - self.assertIn("cannot read", stderr.getvalue()) - - def test_backward_branch_detection_and_loops_filter(self): - self.assertFalse(AB.is_backward_branch("\ts_cbranch_scc0 12\n\ts_branch 40\n")) - self.assertTrue(AB.is_backward_branch("\ts_cbranch_scc0 32768\n\ts_branch 40\n")) - index = {"forward": self.shader(), "backward": self.shader()} - self.add_shader("forward", "\ts_cbranch_scc0 12\n\ts_branch 40\n") - self.add_shader("backward", "\ts_cbranch_scc0 32768\n\ts_branch 40\n") - self.assertEqual(AB.select_candidates(index, self.disasm, self.spirv, loops="none"), ["forward"]) - self.assertEqual(AB.select_candidates(index, self.disasm, self.spirv, loops="only"), ["backward"]) - - def test_names_file_overrides_automatic_selection(self): - names = os.path.join(self.tmp.name, "names.txt") - with open(names, "w", encoding="utf-8") as f: - f.write("not_in_index\nfiltered_out\n") - # Both names have synthetic disassemblies but no index entries or prebuilt SPIR-V: --names bypasses - # automatic metadata and file selection, while preserving files the later translation stage needs. - self.add_shader("not_in_index", "\ts_branch 12\n\ts_branch 24\n", with_spv=False) - self.add_shader("filtered_out", "\tbuffer_store_dword v0, v1, s[0:1]\n", with_spv=False) - self.assertEqual(AB.select_candidates({}, self.disasm, self.spirv, loops="only", names_file=names), - ["not_in_index", "filtered_out"]) - - def test_count_limits_the_automatic_selection(self): - index = {name: self.shader() for name in ("c", "b", "a")} - for name in index: - self.add_shader(name, "\ts_cbranch_scc0 12\n\ts_branch 40\n") - self.assertEqual(AB.select_candidates(index, self.disasm, self.spirv, count=2), ["a", "b"]) - - def test_count_below_one_is_refused(self): - index = {"a": self.shader()} - self.add_shader("a", "\ts_cbranch_scc0 12\n\ts_branch 40\n") - for count in (0, -3): - with self.subTest(count=count), self.assertRaises(ValueError): - AB.select_candidates(index, self.disasm, self.spirv, count=count) - - def test_invalid_loops_parameter_raises(self): - with self.assertRaises(ValueError): - AB.select_candidates({}, self.disasm, self.spirv, loops="invalid") - - -class CountArgumentTest(unittest.TestCase): - def test_positive_int(self): - self.assertEqual(AB.positive_int("150"), 150) - self.assertEqual(AB.positive_int("1"), 1) - for text in ("0", "-1", "-100", "x", "12.5", ""): - with self.subTest(text=text), self.assertRaises(argparse.ArgumentTypeError): - AB.positive_int(text) - - def test_cli_refuses_counts_below_one_before_making_out(self): - with tempfile.TemporaryDirectory() as tmp: - out = os.path.join(tmp, "out") - for flag in ("--count", "--runs", "--timeout"): - with self.subTest(flag=flag), self.assertRaises(SystemExit) as ctx, \ - contextlib.redirect_stderr(io.StringIO()) as err: - AB.main([tmp, tmp, out, flag, "0"]) - self.assertEqual(ctx.exception.code, 2) - self.assertIn(flag, err.getvalue()) - self.assertFalse(os.path.exists(out)) - - - def test_cli_rejects_empty_selection_before_preparing_the_harness(self): - with tempfile.TemporaryDirectory() as tmp: - spirv = os.path.join(tmp, "spirv") - os.mkdir(spirv) - with open(os.path.join(spirv, "index.json"), "w", encoding="utf-8", newline="\n") as f: - f.write("{}") - out = os.path.join(tmp, "out") - with patch.object(AB, "test_vertex_shader") as harness, \ - contextlib.redirect_stdout(io.StringIO()), contextlib.redirect_stderr(io.StringIO()) as err: - self.assertEqual(AB.main([tmp, tmp, out]), 1) - harness.assert_not_called() - self.assertIn("no shader candidates", err.getvalue()) - self.assertFalse(os.path.exists(out)) - - -class CliBadInputTest(unittest.TestCase): - """Bad paths end in one stderr line and exit 2, and a mistyped input leaves no output tree behind.""" - - def run_cli(self, *args, path=None): - env = dict(os.environ) - if path is not None: - env["PATH"] = path - return subprocess.run([sys.executable, "-I", os.path.join(TOOLS_DIR, "ab_control_flow.py"), *args], - capture_output=True, text=True, env=env) - - def check_one_line(self, res, needle): - self.assertEqual(res.returncode, 2, res.stderr) - self.assertIn(needle, res.stderr) - self.assertNotIn("Traceback", res.stderr) - - def test_bad_paths(self): - with tempfile.TemporaryDirectory() as tmp: - shaders = os.path.join(tmp, "shaders") - os.makedirs(os.path.join(shaders, "spirv")) - blocker = os.path.join(tmp, "blocker") - with open(blocker, "w", encoding="utf-8") as f: - f.write("x") - out = os.path.join(tmp, "out") - # No shaders folder at all. - self.check_one_line(self.run_cli(tmp, os.path.join(tmp, "nope"), out), "index.json") - self.assertFalse(os.path.exists(out)) - # An index that is not JSON. - with open(os.path.join(shaders, "spirv", "index.json"), "wb") as f: - f.write(b"\xff\xfe not json") - self.check_one_line(self.run_cli(tmp, shaders, out), "index.json") - self.assertFalse(os.path.exists(out)) - with open(os.path.join(shaders, "spirv", "index.json"), "w", encoding="utf-8") as f: - f.write("{}") - # A names file that does not exist. - self.check_one_line(self.run_cli(tmp, shaders, out, "--names", os.path.join(tmp, "nope.txt")), "--names") - self.assertFalse(os.path.exists(out)) - # Past the selection (an explicit names file selects without reading the disassembly): - names = os.path.join(tmp, "names.txt") - with open(names, "w", encoding="utf-8") as f: - f.write("one\n") - disasm = os.path.join(shaders, "dxbc", "disasm") - os.makedirs(disasm) - with open(os.path.join(disasm, "one.s"), "w", encoding="utf-8", newline="\n") as f: - f.write("s_endpgm\n") - # an output path under a regular file, - self.check_one_line(self.run_cli(tmp, shaders, os.path.join(blocker, "out"), "--names", names), - "cannot create") - # and no SPIR-V tools on PATH. - self.check_one_line(self.run_cli(tmp, shaders, out, "--names", names, - path=os.path.join(tmp, "empty-path")), "spirv-as") - self.assertFalse(os.path.exists(out)) # the output folder this run made is removed again - # An output folder that already existed stays, with what this run put in it removed. - os.makedirs(out) - self.check_one_line(self.run_cli(tmp, shaders, out, "--names", names, - path=os.path.join(tmp, "empty-path")), "spirv-as") - self.assertEqual(os.listdir(out), []) - - def test_assembler_failure_preserves_concurrent_output(self): - with tempfile.TemporaryDirectory() as tmp: - root = Path(tmp) - (root / "spirv").mkdir() - (root / "spirv/index.json").write_text("{}", encoding="utf-8") - disasm = root / "dxbc/disasm" - disasm.mkdir(parents=True) - (disasm / "one.s").write_text("s_endpgm\n", encoding="utf-8") - names = root / "names.txt" - names.write_text("one\n", encoding="utf-8") - - for preexisting in (True, False): - with self.subTest(preexisting=preexisting): - out = root / ("existing" if preexisting else "fresh") - if preexisting: - out.mkdir() - sibling = out / "other-job.txt" - - def fail_assembler(command, **kwargs): - self.assertEqual(command[0], "spirv-as") - out.mkdir(exist_ok=True) - sibling.write_bytes(b"other job") - raise subprocess.CalledProcessError(1, command) - - with patch.object(AB.subprocess, "run", side_effect=fail_assembler), \ - contextlib.redirect_stderr(io.StringIO()), contextlib.redirect_stdout(io.StringIO()), \ - self.assertRaises(SystemExit) as raised: - AB.main([tmp, tmp, str(out), "--names", str(names)]) - self.assertEqual(raised.exception.code, 2) - self.assertTrue(sibling.is_file(), "cleanup deleted concurrent output") - self.assertEqual(sibling.read_bytes(), b"other job") - - def test_bad_index_shape_and_stale_names_leave_no_output(self): - with tempfile.TemporaryDirectory() as tmp: - shaders = os.path.join(tmp, "shaders") - os.makedirs(os.path.join(shaders, "spirv")) - index = os.path.join(shaders, "spirv", "index.json") - out = os.path.join(tmp, "out") - for payload in ("[]", '{"one": []}', '{"one": {"bindings": 5}}', '{"one": {"features": "x"}}', - '{"one": {"bindings": [[0]]}}', '{"one": {"features": {"a": 1}}}'): - with open(index, "w", encoding="utf-8", newline="\n") as f: - f.write(payload) - self.check_one_line(self.run_cli(tmp, shaders, out), "metadata") - self.assertFalse(os.path.exists(out)) - with open(index, "w", encoding="utf-8", newline="\n") as f: - f.write("{}") - names = os.path.join(tmp, "names.txt") - for payload in (b"missing\n", b"\xff"): - with open(names, "wb") as f: - f.write(payload) - self.check_one_line(self.run_cli(tmp, shaders, out, "--names", names), "cannot read selected") - self.assertFalse(os.path.exists(out)) - - def test_unreadable_output_folder(self): - with tempfile.TemporaryDirectory() as tmp: - shaders = os.path.join(tmp, "shaders") - os.makedirs(os.path.join(shaders, "spirv")) - os.makedirs(os.path.join(shaders, "dxbc", "disasm")) - with open(os.path.join(shaders, "spirv", "index.json"), "w", encoding="utf-8", newline="\n") as f: - f.write("{}") - names = os.path.join(tmp, "names.txt") - with open(names, "w", encoding="utf-8", newline="\n") as f: - f.write("one\n") - with open(os.path.join(shaders, "dxbc", "disasm", "one.s"), "w", encoding="utf-8", newline="\n") as f: - f.write("s_endpgm\n") - out = os.path.join(tmp, "out") - os.makedirs(out) - # Listing the folder fails (what a mode 000 folder does to a non-root user, injected so that it also - # runs as root and on Windows). - real_listdir = os.listdir - - def listdir(path="."): - if os.fspath(path) == out: - raise PermissionError(13, "Permission denied", out) - return real_listdir(path) - stderr = io.StringIO() - with patch("os.listdir", listdir), contextlib.redirect_stderr(stderr), \ - contextlib.redirect_stdout(io.StringIO()), self.assertRaises(SystemExit) as raised: - AB.main([tmp, shaders, out, "--names", names]) - self.assertEqual(raised.exception.code, 2) - self.assertIn("cannot create", stderr.getvalue()) - - @unittest.skipIf(os.name == "nt" or not hasattr(os, "geteuid") or os.geteuid() == 0, - "mode 000 does not stop root or Windows") - def test_mode_000_output_folder(self): - with tempfile.TemporaryDirectory() as tmp: - shaders = os.path.join(tmp, "shaders") - os.makedirs(os.path.join(shaders, "spirv")) - os.makedirs(os.path.join(shaders, "dxbc", "disasm")) - with open(os.path.join(shaders, "spirv", "index.json"), "w", encoding="utf-8", newline="\n") as f: - f.write("{}") - names = os.path.join(tmp, "names.txt") - with open(names, "w", encoding="utf-8", newline="\n") as f: - f.write("one\n") - with open(os.path.join(shaders, "dxbc", "disasm", "one.s"), "w", encoding="utf-8", newline="\n") as f: - f.write("s_endpgm\n") - out = os.path.join(tmp, "out") - os.makedirs(out) - os.chmod(out, 0) - try: - self.check_one_line(self.run_cli(tmp, shaders, out, "--names", names), "cannot create") - finally: - os.chmod(out, 0o700) - - -class ResultClassificationTest(unittest.TestCase): - def test_translation_failure(self): - self.assertEqual(AB.classify_result(False, [b"same"], [b"same"]), "a translation is invalid") - - def test_dispatch_harness_failure(self): - self.assertEqual(AB.classify_result(True, [None], [b"image"]), "dispatch form failed to run") - - def test_structured_harness_failure(self): - self.assertEqual(AB.classify_result(True, [b"image"], [None]), "structured form failed to run") - - def test_both_forms_timeout(self): - self.assertEqual(AB.classify_result(True, ["timeout"], ["timeout"]), "neither terminates") - - def test_only_one_form_times_out(self): - self.assertEqual(AB.classify_result(True, ["timeout"], [b"image"]), "ONLY ONE FORM TERMINATES") - self.assertEqual(AB.classify_result(True, [b"image"], ["timeout"]), "ONLY ONE FORM TERMINATES") - - def test_harness_failure_is_not_mislabeled_as_the_other_form_terminating(self): - self.assertEqual(AB.classify_result(True, ["timeout"], [None]), "structured form failed to run") - self.assertEqual(AB.classify_result(True, [None], ["timeout"]), "dispatch form failed to run") - - def test_inconsistent_repeated_runs_are_unstable(self): - self.assertEqual(AB.classify_result(True, [b"first", b"second"], [b"image"]), - "unstable from run to run") - - def test_inconsistent_structured_runs_are_unstable(self): - self.assertEqual(AB.classify_result(True, [b"image", b"image"], [b"first", b"second"]), - "unstable from run to run") - # A form that times out on one run and not the next is unstable, not "ONLY ONE FORM TERMINATES". - self.assertEqual(AB.classify_result(True, [b"image", b"image"], [b"image", "timeout"]), - "unstable from run to run") - - def test_identical_images(self): - self.assertEqual(AB.classify_result(True, [b"same", b"same"], [b"same", b"same"]), "identical") - - def test_different_images(self): - self.assertEqual(AB.classify_result(True, [b"dispatch"], [b"structured"]), "DIFFERENT") - - -class OutputAndVertexShaderTest(unittest.TestCase): - def test_outcomes_tsv_contents(self): - with tempfile.TemporaryDirectory() as tmp: - path = AB.write_outcomes(tmp, [("shader_a", "identical"), ("shader_b", "DIFFERENT")]) - with open(path, encoding="utf-8") as f: - self.assertEqual(f.read(), "shader_a\tidentical\nshader_b\tDIFFERENT\n") - - def test_vertex_shader_generation_assembles_and_validates_all_locations(self): - with tempfile.TemporaryDirectory() as tmp: - calls = [] - - def fake_run(args, check): - calls.append((args, check)) - if args[0] == "spirv-as": - with open(args[-1], "wb") as f: - f.write(b"synthetic assembled SPIR-V") - return SimpleNamespace(returncode=0) - - result = AB.test_vertex_shader(tmp, runner=fake_run) - self.assertTrue(os.path.isfile(result)) - self.assertEqual(len(calls), 2) - self.assertEqual([call[0][0] for call in calls], ["spirv-as", "spirv-val"]) - self.assertTrue(all(check for _, check in calls)) - source = os.path.join(tmp, "test_vs.spvasm") - with open(source, encoding="utf-8") as f: - asm = f.read() - self.assertIn("OpDecorate %o31 Location 31", asm) - self.assertIn("%o31 = OpVariable %po Output", asm) - self.assertIn("OpStore %o31 %zero", asm) - self.assertIn("OpStore %o0 %t", asm) - self.assertIn("OpDecorate %pos BuiltIn Position", asm) - self.assertIn("OpDecorate %vid BuiltIn VertexIndex", asm) - - -class BackwardBranchAndDisasmTest(unittest.TestCase): - """Test branch displacement classification and opcode filter patterns.""" - - def test_is_backward_branch_boundary_cases(self): - # Displacements >= 32768 (0x8000) represent backward branches in RDNA2 - self.assertFalse(AB.is_backward_branch("\ts_branch 0\n")) - self.assertFalse(AB.is_backward_branch("\ts_cbranch_scc0 32767\n")) - self.assertTrue(AB.is_backward_branch("\ts_cbranch_scc0 32768\n")) - self.assertTrue(AB.is_backward_branch("\ts_branch 65535\n")) - self.assertTrue(AB.is_backward_branch("\ts_cbranch_execz 32768\n")) - self.assertFalse(AB.is_backward_branch("\ts_cbranch_execnz 100\n")) - - def test_unsupported_opcodes_detected_by_needs_regex(self): - unsupported = [ - "image_store", - "image_atomic", - "buffer_store", - "tbuffer_store_format_xyzw", - "global_store", - "global_atomic", - "ds_read_b32", - "ds_write_b32", - "s_swappc", - "s_getpc", - "s_sendmsg", - "s_sleep", - ] - for op in unsupported: - with self.subTest(op=op): - disasm = f"\tv_mov_b32 v0, 0\n\t{op} v0\n\ts_branch 10\n" - self.assertIsNotNone(AB.NEEDS.search(disasm)) - - def test_supported_instructions_pass_needs_filter(self): - supported = [ - "\ts_branch 10\n", - "\ts_cbranch_scc0 20\n", - "\ts_cbranch_execnz 30\n", - "\tv_add_f32 v0, v1, v2\n", - "\tv_mul_f32 v0, v0, v3\n", - "\ts_mov_b32 s0, 42\n", - ] - for ins in supported: - with self.subTest(instruction=ins): - self.assertIsNone(AB.NEEDS.search(ins)) - - def test_constants_and_clear_colour(self): - self.assertEqual(AB.LOCATIONS, 32) - self.assertEqual(AB.CLEAR, struct.pack("<4f", -1.0, -1.0, -1.0, -1.0)) - self.assertEqual(AB.SUPPORTED_BINDINGS, {0, 1, 2}) - self.assertEqual( - AB.HOSTED_FEATURES, - {"bufferDeviceAddress", "runtimeDescriptorArray", "shaderInt64", "shaderSampledImageArrayDynamicIndexing"}, - ) - - -class ReachabilityAnalysisTest(unittest.TestCase): - """Test CFG reachability analysis.""" - - def test_linear_flow(self): - succ = [[1], [2], [3], []] - self.assertEqual(find_reachable_blocks(succ, entry=0), {0, 1, 2, 3}) - - def test_diamond_graph(self): - succ = { - 0: [1, 2], - 1: [3], - 2: [3], - 3: [-1], - } - self.assertEqual(find_reachable_blocks(succ, entry=0), {0, 1, 2, 3}) - - def test_unreachable_islands_and_dead_cycles(self): - succ = { - 0: [1], - 1: [-1], - 2: [3], - 3: [2], - 4: [0], - } - reachable = find_reachable_blocks(succ, entry=0) - self.assertEqual(reachable, {0, 1}) - self.assertNotIn(2, reachable) - self.assertNotIn(3, reachable) - self.assertNotIn(4, reachable) - - def test_empty_or_invalid_entry(self): - self.assertEqual(find_reachable_blocks([], entry=0), set()) - self.assertEqual(find_reachable_blocks([[1]], entry=99), set()) - self.assertEqual(find_reachable_blocks({}, entry=0), set()) - - -class DeadBlockPruningCFGTest(unittest.TestCase): - """Test pruning unreachable basic blocks and dead edges from CFGs.""" - - def test_prune_list_representation(self): - # 0 -> 1; blocks 2 and 3 are isolated dead blocks - succ = [[1], [], [3], [2]] - pruned = prune_dead_blocks_cfg(succ, entry=0) - self.assertEqual(pruned, [[1], [], [], []]) - - def test_prune_dict_representation(self): - succ = { - 0: [1], - 1: [-1], - 2: [3], - 3: [0], - } - pruned = prune_dead_blocks_cfg(succ, entry=0) - self.assertEqual(pruned, {0: [1], 1: [-1]}) - - def test_prune_edges_pointing_to_unreachable_nodes(self): - succ = { - 0: [1, 99], - 1: [-1], - } - pruned = prune_dead_blocks_cfg(succ, entry=0) - self.assertEqual(pruned, {0: [1], 1: [-1]}) - - -class ASTBlockCollectionTest(unittest.TestCase): - """Test basic-block collection from AST trees.""" - - def test_flat_blocks(self): - tree = [("block", 0), ("block", 1), ("block", 2)] - self.assertEqual(collect_ast_blocks(tree), {0, 1, 2}) - - def test_nested_guards_and_loops(self): - tree = [ - ("block", 0), - ("guard", 1, [("block", 1), ("guard", 2, [("block", 2)])]), - ("loop", 3, [("block", 3), ("guard", 4, [("block", 4)])]), - ] - self.assertEqual(collect_ast_blocks(tree), {0, 1, 2, 3, 4}) - - def test_empty_and_malformed_tree(self): - self.assertEqual(collect_ast_blocks([]), set()) - self.assertEqual(collect_ast_blocks([(), None, "invalid", 123]), set()) - - -class ASTDeadBlockPruningTest(unittest.TestCase): - """Test AST-level dead basic-block pruning.""" - - def test_prune_unreachable_block_nodes(self): - tree = [("block", 0), ("block", 1), ("block", 2)] - reachable = {0, 2} - pruned = prune_dead_blocks(tree, reachable) - self.assertEqual(pruned, [("block", 0), ("block", 2)]) - - def test_prune_guard_with_dead_condition(self): - tree = [ - ("block", 0), - ("guard", 1, [("block", 1)]), - ("guard", 3, [("block", 3)]), - ] - reachable = {0, 1} - pruned = prune_dead_blocks(tree, reachable) - self.assertEqual(pruned, [("block", 0), ("guard", 1, [("block", 1)])]) - - def test_prune_guard_whose_body_becomes_empty(self): - tree = [ - ("block", 0), - ("guard", 1, [("block", 2)]), - ] - reachable = {0, 1} - pruned = prune_dead_blocks(tree, reachable) - self.assertEqual(pruned, [("block", 0)]) - - def test_prune_nested_dead_constructs(self): - tree = [ - ("loop", 0, [ - ("block", 0), - ("guard", 1, [ - ("block", 1), - ("guard", 99, [("block", 99)]), - ]), - ]), - ("guard", 88, [("loop", 88, [("block", 88)])]), - ] - reachable = {0, 1} - pruned = prune_dead_blocks(tree, reachable) - self.assertEqual( - pruned, - [("loop", 0, [("block", 0), ("guard", 1, [("block", 1)])])], - ) - - -class ASTSimplificationTest(unittest.TestCase): - """Test iterative simplification rules on AST control-flow trees.""" - - def test_eliminate_empty_guards_and_loops(self): - tree = [ - ("block", 0), - ("guard", 1, []), - ("loop", 2, []), - ("block", 3), - ] - simplified = simplify_ast(tree) - self.assertEqual(simplified, [("block", 0), ("block", 3)]) - - def test_collapse_redundant_nested_guards(self): - tree = [ - ("guard", 1, [ - ("guard", 1, [ - ("block", 1), - ]) - ]) - ] - simplified = simplify_ast(tree) - self.assertEqual(simplified, [("guard", 1, [("block", 1)])]) - - def test_multi_pass_fixed_point_simplification(self): - tree = [ - ("block", 0), - ("guard", 1, [ - ("guard", 2, [ - ("block", 2), - ]) - ]), - ] - simplified = simplify_ast(tree, reachable={0}) - self.assertEqual(simplified, [("block", 0)]) - - def test_idempotence(self): - tree = [ - ("block", 0), - ("guard", 1, [("block", 1)]), - ("loop", 2, [("block", 2), ("guard", 3, [("block", 3)])]), - ] - pass1 = simplify_ast(tree) - pass2 = simplify_ast(pass1) - self.assertEqual(pass1, pass2) - - -class CFGSimplificationTest(unittest.TestCase): - """Test CFG trampoline forwarder collapsing.""" - - def test_single_trampoline_collapse(self): - # 0 -> 1 -> 2 - succ = { - 0: [1], - 1: [2], - 2: [-1], - } - simplified, reachable = simplify_cfg(succ, entry=0) - self.assertEqual(reachable, {0, 1, 2}) - self.assertEqual(simplified[0], [2]) - self.assertEqual(simplified[2], [-1]) - - def test_trampoline_chain_collapse(self): - # 0 -> 1 -> 2 -> 3 - succ = { - 0: [1], - 1: [2], - 2: [3], - 3: [-1], - } - simplified, reachable = simplify_cfg(succ, entry=0) - self.assertEqual(simplified[0], [3]) - - def test_entry_block_never_collapsed_as_trampoline(self): - succ = { - 0: [1], - 1: [-1], - } - simplified, reachable = simplify_cfg(succ, entry=0) - self.assertEqual(simplified[0], [1]) - - def test_trampoline_cycle_avoidance(self): - succ = { - 0: [1], - 1: [2], - 2: [1], - } - simplified, reachable = simplify_cfg(succ, entry=0) - self.assertIn(simplified[0][0], (1, 2)) - - -class EndToEndSemanticEquivalenceTest(unittest.TestCase): - """Verify that simplifying an AST preserves exact execution paths for all reachable blocks.""" - - def test_diamond_cfg_ast_execution(self): - # Reducible diamond graph: 0 -> [1, 2], 1 -> [3], 2 -> [3], 3 -> [] - succ = [[1, 2], [3], [3], []] - tree = S.structure(succ) - self.assertIsNotNone(tree) - - simplified = simplify_ast(tree, reachable={0, 1, 2, 3}) - - def choose_left(b): - return 1 if b == 0 else (3 if b in (1, 2) else S.END) - - def choose_right(b): - return 2 if b == 0 else (3 if b in (1, 2) else S.END) - - trace_left_orig = S.run(tree, choose_left, 100) - trace_left_simp = S.run(simplified, choose_left, 100) - self.assertEqual(trace_left_orig, trace_left_simp) - self.assertEqual(trace_left_simp, [0, 1, 3]) - - trace_right_orig = S.run(tree, choose_right, 100) - trace_right_simp = S.run(simplified, choose_right, 100) - self.assertEqual(trace_right_orig, trace_right_simp) - self.assertEqual(trace_right_simp, [0, 2, 3]) - - def test_dead_branch_pruned_ast_execution(self): - succ = [[1, 2], [3], [3], []] - tree = S.structure(succ) - self.assertIsNotNone(tree) - - simplified = simplify_ast(tree, reachable={0, 1, 3}) - blocks = collect_ast_blocks(simplified) - self.assertNotIn(2, blocks) - self.assertEqual(blocks, {0, 1, 3}) - - def choose_path(b): - return 1 if b == 0 else (3 if b == 1 else S.END) - - trace = S.run(simplified, choose_path, 100) - self.assertEqual(trace, [0, 1, 3]) - - -class PipelineExecutionTest(unittest.TestCase): - """Test full CLI pipeline execution with synthetic shaders and mocks.""" - - def setUp(self): - self.tmp = tempfile.TemporaryDirectory() - self.repo = os.path.join(self.tmp.name, "repo") - self.shaders = os.path.join(self.tmp.name, "shaders") - self.out = os.path.join(self.tmp.name, "out") - os.makedirs(self.repo) - os.makedirs(os.path.join(self.shaders, "dxbc", "disasm")) - os.makedirs(os.path.join(self.shaders, "spirv")) - os.makedirs(os.path.join(self.repo, "runtime", "build")) - - def tearDown(self): - self.tmp.cleanup() - - @patch("subprocess.run") - def test_main_cli_pipeline_success(self, mock_run) -> None: - self.assert_pipeline_outcome(mock_run, 64 * 64 * 16, "identical MRT0: non-clear") - - @patch("subprocess.run") - def test_main_rejects_identical_truncated_images(self, mock_run) -> None: - self.assert_pipeline_outcome(mock_run, 16, "dispatch form failed to run") - - @patch("subprocess.run") - def test_clear_mrt0_with_unobserved_export(self, mock_run): - self.assert_pipeline_outcome(mock_run, AB.READBACK_BYTES, "identical MRT0: clear-only; unobserved MRT2", - targets=(0, 2), pixel=AB.CLEAR) - - @patch("subprocess.run") - def test_only_unbound_target(self, mock_run): - self.assert_pipeline_outcome(mock_run, AB.READBACK_BYTES, - "identical MRT0 clear-difference mask: empty; unobserved MRT1", - targets=(1,), pixel=AB.CLEAR) - - @patch("subprocess.run") - def test_all_attachments_detects_mrt1_difference(self, mock_run): - self.assert_pipeline_outcome(mock_run, 2 * AB.READBACK_BYTES, "identical MRT0: non-clear; MRT1: DIFFERENT", - targets=(0, 1), all_attachments=True, divergent=True) - - @patch("subprocess.run") - def test_sparse_outputs_preserve_mask_and_ignore_gap(self, mock_run): - self.assert_pipeline_outcome(mock_run, 3 * AB.READBACK_BYTES, - "identical MRT0 clear-difference mask: empty; identical MRT2: clear-only", - targets=(2,), all_attachments=True, pixel=AB.CLEAR, divergent=True) - - @patch("subprocess.run") - def test_missing_plane(self, mock_run): - self.assert_pipeline_outcome(mock_run, AB.READBACK_BYTES, - "MRT0: dispatch form failed to run; MRT1: dispatch form failed to run", - targets=(0, 1), all_attachments=True) - - @patch("subprocess.run") - def test_duplicate_or_missing_cached_target(self, mock_run): - for cached in ([0, 1, 1], [0]): - self.assert_pipeline_outcome(mock_run, AB.READBACK_BYTES, - "cached outputs disagree with translated colour targets", - targets=(0, 1), all_attachments=True, cached=cached) - - def assert_pipeline_outcome(self, mock_run, image_size: int, expected: str, targets=(0,), pixel=bytes(16), - all_attachments=False, divergent=False, cached=None) -> None: - import json - - # Prepare synthetic index - index = { - "ps_test": { - "stage": "ps", - "bindings": [0, 1], - "features": ["bufferDeviceAddress"], - } - } - index["ps_test"]["outputs"] = list(targets) if cached is None else cached - with open(os.path.join(self.shaders, "spirv", "index.json"), "w", encoding="utf-8") as f: - json.dump(index, f) - - # Prepare disassembly and placeholder spirv - disasm_path = os.path.join(self.shaders, "dxbc", "disasm", "ps_test.s") - with open(disasm_path, "w", encoding="utf-8") as f: - f.write("\ts_cbranch_scc0 10\n\ts_branch 20\n\ts_endpgm\n") - - with open(os.path.join(self.shaders, "spirv", "ps_test.spv"), "wb") as f: - f.write(b"placeholder") - - # Mock runner behavior: - # 1. spirv-as -> returns 0 - # 2. spirv-val -> returns 0 - # 3. rdna2spirv new -> returns "1 pass spirv-val" - # 4. rdna2spirv dispatch -> returns "1 pass spirv-val" - # 5. vk_texture_test harness run 1 -> creates raw image - # 6. vk_texture_test harness run 2 -> creates raw image - def side_effect(args, **kwargs): - cmd = args[0] - if "spirv-as" in cmd: - with open(args[-1], "wb") as f: - f.write(b"fake_vs_spv") - return SimpleNamespace(returncode=0, stdout="pass") - elif "spirv-val" in cmd: - return SimpleNamespace(returncode=0, stdout="pass") - elif "rdna2spirv.py" in str(args): - # Write the synthetic output declarations. - out_dir = args[args.index("--out") + 1] - os.makedirs(out_dir, exist_ok=True) - with open(os.path.join(out_dir, "ps_test.spvasm"), "w", encoding="utf-8") as f: - for target in targets: - f.write(f"%out_mrt{target} = OpVariable %po Output\n") - with open(os.path.join(out_dir, "ps_test.spv"), "wb") as f: - f.write(b"fake_spv") - return SimpleNamespace(returncode=0, stdout="1 pass spirv-val\n") - else: - # Harness call - raw_path = args[3] - with open(raw_path, "wb") as f: - data = bytearray(pixel * (image_size // len(pixel))) - if all_attachments: - self.assertEqual(args[4:], ["64", "64", str(max(targets) + 1)]) - if divergent and "dispatch" in args[2]: - data[AB.READBACK_BYTES] ^= 1 - f.write(data) - return SimpleNamespace(returncode=0, stdout="OK") - - mock_run.side_effect = side_effect - - with warnings.catch_warnings(): - warnings.simplefilter("ignore", ResourceWarning) - with contextlib.redirect_stdout(io.StringIO()): - ret = AB.main([ - self.repo, - self.shaders, - self.out, - "--count", "1", - "--runs", "1", - "--harness", "dummy_harness.exe", - *(["--all-attachments"] if all_attachments else []), - ]) - self.assertEqual(ret, 0) - outcomes_file = os.path.join(self.out, "outcomes.tsv") - self.assertTrue(os.path.isfile(outcomes_file)) - with open(outcomes_file, "r", encoding="utf-8") as f: - content = f.read() - self.assertEqual(content, f"ps_test\t{expected}\n") - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/test_acphal_abi.py b/tests/test_acphal_abi.py deleted file mode 100644 index 822df4e04..000000000 --- a/tests/test_acphal_abi.py +++ /dev/null @@ -1,108 +0,0 @@ -"""Synthetic tests for acphal.dll / APU heap management & SHAPE contexts (no game data).""" -import os -import re -import struct -import subprocess -import sys -import tempfile -import unittest - -ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) -sys.path.insert(0, os.path.join(ROOT, "tests")) -import runtime_cmake # noqa: E402 - - -class TestAcpHalAbi(unittest.TestCase): - def setUp(self): - self.acphal_cpp = os.path.join(ROOT, "runtime", "shims", "acphal.cpp") - self.acphal_test = os.path.join(ROOT, "runtime", "test", "acphal_test.cpp") - self.registry_cpp = os.path.join(ROOT, "runtime", "shims", "registry.cpp") - self.cmakelists = os.path.join(ROOT, "runtime", "CMakeLists.txt") - self.build_ps1 = os.path.join(ROOT, "scripts", "build_runtime.ps1") - - def test_all_nine_acphal_exports_defined(self): - """acphal.dll must export all 9 functions imported by the retail binary (PR #6885, docs/retail_boot_frame_loop.md).""" - with open(self.acphal_cpp, "r", encoding="utf-8") as f: - content = f.read() - - expected_exports = [ - "AcpHalAllocateShapeContexts", - "AcpHalCreate", - "AcpHalReleaseShapeContexts", - "ApuAlloc", - "ApuCreateHeap", - "ApuFree", - "ApuIsVirtualAddressValid", - "ApuMapApuAddress", - "ApuMapVirtualAddress", - ] - for exp in expected_exports: - self.assertIn(f'"{exp}"', content, f"acphal.dll SHIM_TABLE must register export {exp}") - - def test_shape_contexts_layout_matches_gdk_and_retail_offset(self): - """SHAPE_CONTEXTS layout: 6 dwords, then 6 pointers, with xmaContextArray at +0x38 (retail measurement).""" - # SHAPE_CONTEXTS: - # uint32_t numSrcContexts; // offset 0 - # uint32_t numEqCompContexts; // offset 4 - # uint32_t numFiltVolContexts; // offset 8 - # uint32_t numDmaContexts; // offset 12 - # uint32_t numXmaContexts; // offset 16 - # uint32_t numPcmContexts; // offset 20 - # void* srcContextArray; // offset 24 (0x18) - # void* eqCompContextArray; // offset 32 (0x20) - # void* filtVolContextArray; // offset 40 (0x28) - # void* dmaContextArray; // offset 48 (0x30) - # void* xmaContextArray; // offset 56 (0x38) - 5th pointer, checked at +0x38! - # void* pcmContextArray; // offset 64 (0x40) - # APU_ADDRESS apuSrcContextArray; // offset 72 (0x48) - # APU_ADDRESS apuEqComp... // offset 80 (0x50) - # APU_ADDRESS apuFiltVol... // offset 88 (0x58) - # APU_ADDRESS apuDma... // offset 96 (0x60) - # APU_ADDRESS apuXma... // offset 104 (0x68) - # APU_ADDRESS apuPcm... // offset 112 (0x70) - # Total size: 120 bytes (0x78) - layout_format = "<6I6Q6Q" - self.assertEqual(struct.calcsize(layout_format), 120) - - # Offset of 5th pointer (xmaContextArray): 6 * 4 + 4 * 8 = 24 + 32 = 56 = 0x38 - xma_ptr_offset = 6 * 4 + 4 * 8 - self.assertEqual(xma_ptr_offset, 0x38) - - # Verify static_asserts in acphal.cpp - with open(self.acphal_cpp, "r", encoding="utf-8") as f: - content = f.read() - - self.assertIn("static_assert(sizeof(SHAPE_CONTEXTS) == 120", content) - self.assertIn("static_assert(offsetof(SHAPE_CONTEXTS, xmaContextArray) == 0x38", content) - self.assertIn("static_assert(sizeof(SHAPE_XMA_CONTEXT) == 64", content) - self.assertIn("static_assert(sizeof(SHAPE_SRC_CONTEXT) == 32", content) - self.assertIn("static_assert(sizeof(SHAPE_EQCOMP_CONTEXT) == 352", content) - self.assertIn("static_assert(sizeof(SHAPE_FILTVOL_CONTEXT) == 32", content) - self.assertIn("static_assert(sizeof(SHAPE_DMA_CONTEXT) == 16", content) - self.assertIn("static_assert(sizeof(SHAPE_PCM_CONTEXT) == 32", content) - - def test_registry_classifies_acphal_hresult(self): - """registry.cpp must classify acphal.dll HRESULT-returning functions.""" - with open(self.registry_cpp, "r", encoding="utf-8") as f: - content = f.read() - - self.assertIn('dll == "acphal.dll"', content) - self.assertIn("AcpHalAllocateShapeContexts", content) - self.assertIn("AcpHalCreate", content) - self.assertIn("ApuAlloc", content) - self.assertIn("ApuCreateHeap", content) - - def test_cmakelists_and_fallback_register_acphal(self): - """CMakeLists.txt and build_runtime.ps1 must both register acphal.cpp in gta6rt.""" - cmake = runtime_cmake.read(self.cmakelists) - self.assertIn("shims/acphal.cpp", cmake) - self.assertIn("add_executable(acphal_test", cmake) - self.assertIn("add_test(NAME acphal COMMAND acphal_test)", cmake) - - with open(self.build_ps1, "r", encoding="utf-8") as f: - ps1 = f.read() - self.assertIn("shims\\acphal.cpp", ps1) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/test_amd_swizzle.py b/tests/test_amd_swizzle.py deleted file mode 100644 index 6e30a3e9f..000000000 --- a/tests/test_amd_swizzle.py +++ /dev/null @@ -1,368 +0,0 @@ -"""amd_swizzle.load: parses addrlib's pattern tables without evaluating them as Python. - - python -m pytest tests/test_amd_swizzle.py -""" -import io -import os -import pathlib -import sys -import tempfile -import types -import unittest -from pathlib import Path -from unittest import mock - -try: - import pytest # noqa: E402 (keeps the CI bash loop from running this file) -except ImportError: - pytest = None - -TOOLS_DIR = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "tools") -if TOOLS_DIR not in sys.path: - sys.path.insert(0, TOOLS_DIR) - -try: - import amd_swizzle as A # noqa: E402 - HAVE_NUMPY = True -except ModuleNotFoundError as e: - if e.name != "numpy": - raise - A = None - HAVE_NUMPY = False - -# tools/amd_swizzle.py needs numpy (tests/requirements.txt). Without it the module-level tests below are skipped, -# as the __main__ block skips them; the CLI guard tests fake numpy and still run. -if pytest is not None: - needs_numpy = pytest.mark.skipif(not HAVE_NUMPY, reason="numpy is not installed") -else: - def needs_numpy(fn): - return fn - - -def table(name, rows): - body = "\n".join(" {" + ", ".join(r) + ", }, // " + str(i) for i, r in enumerate(rows)) - return f"const UINT_64 GFX10_SW_PATTERN_{name}[][{len(rows[0])}] =\n{{\n{body}\n}};\n" - - -def header(nibble01_row): - return (table("NIBBLE01", [nibble01_row]) + table("NIBBLE2", [["0"] * 4]) + - table("NIBBLE3", [["0"] * 4]) + table("NIBBLE4", [["0"] * 4]) + - "const ADDR_SW_PATINFO GFX10_SW_64K_D_X_PATINFO[] =\n{\n" - " { 0, 0, 0, 0, 0, } , // 1 pipes 1 bpe\n};\n") - - -def load(text): - with tempfile.TemporaryDirectory() as d: - path = os.path.join(d, "gfx10SwizzlePattern.h") - with open(path, "w", encoding="utf-8") as f: - f.write(text) - return A.load(path) - - -@needs_numpy -def test_symbols_and_xor(): - nibbles, tables = load(header(["X0", "0", "Y1", "X3 ^ Y3", "Z0", "S2 ^ Y4 ^ X5", "7", "Y0"])) - assert nibbles["NIBBLE01"] == [[1, 0, 1 << 17, (1 << 3) ^ (1 << 19), 1 << 32, - (1 << 50) ^ (1 << 20) ^ (1 << 5), 7, 1 << 16]] - assert nibbles["NIBBLE2"] == [[0, 0, 0, 0]] - assert tables["GFX10_SW_64K_D_X_PATINFO"] == [(0, 0, 0, 0, 0, "1 pipes 1 bpe")] - - -@needs_numpy -def test_rejects_code(): - for cell in ("__import__('os').getcwd()", "X0 | Y0", "X16", "-1"): - try: - load(header([cell] + ["0"] * 7)) - except ValueError: - continue - raise AssertionError(f"accepted {cell!r}") - - -def _load_amd_swizzle_for_cli(): - if A is not None: - return A - fake_np = types.ModuleType("numpy") - fake_np.uint8 = int - fake_np.float32 = float - fake_np.int64 = int - fake_np.ndarray = object - with mock.patch.dict(sys.modules, {"numpy": fake_np}): - import amd_swizzle - return amd_swizzle - - -class AmdSwizzleCliGuardTests(unittest.TestCase): - def setUp(self): - if not HAVE_NUMPY: - fake_np = types.ModuleType("numpy") - fake_np.uint8 = int - fake_np.float32 = float - fake_np.int64 = int - fake_np.ndarray = object - p = mock.patch.dict(sys.modules, {"numpy": fake_np}) - p.start() - self.addCleanup(p.stop) - self.mod = _load_amd_swizzle_for_cli() - - def test_missing_input_returns_2_without_traceback(self): - with tempfile.TemporaryDirectory() as tmp: - missing = os.path.join(tmp, "does_not_exist.bin") - stderr = io.StringIO() - with mock.patch.object(sys, "stderr", stderr): - rc = self.mod.main([missing, "--width", "64", "--height", "64"]) - self.assertEqual(rc, 2) - self.assertIn("ERROR:", stderr.getvalue()) - self.assertNotIn("Traceback", stderr.getvalue()) - - def test_bad_out_paths_rejected_before_reading_or_searching(self): - with tempfile.TemporaryDirectory() as tmp: - blob = os.path.join(tmp, "blob.bin") - with open(blob, "wb") as f: - f.write(b"\x01\x02\x03\x04" * 64) - existing_dir = os.path.join(tmp, "out_dir") - os.mkdir(existing_dir) - file_ancestor = os.path.join(tmp, "file_ancestor") - with open(file_ancestor, "w", encoding="utf-8") as f: - f.write("x") - - bad_outs = [ - "", - " ", - "bad\x00out.png", - existing_dir, - os.path.join(tmp, "trailing") + os.sep, - os.path.join(file_ancestor, "sub", "out.png"), - blob, - os.path.join(tmp, ".", "blob.bin"), - ] - for bad in bad_outs: - with self.subTest(out=bad): - stderr = io.StringIO() - with mock.patch.object(self.mod, "load") as load_mock, \ - mock.patch.object(sys, "stderr", stderr): - rc = self.mod.main([blob, "--width", "64", "--height", "64", "--out", bad]) - self.assertEqual(rc, 2) - self.assertIn("ERROR:", stderr.getvalue()) - self.assertNotIn("Traceback", stderr.getvalue()) - load_mock.assert_not_called() - - def _run_with_save_side_effect(self, tmp, out_name, side_effect): - blob = os.path.join(tmp, "blob.bin") - with open(blob, "wb") as f: - f.write(b"\x00" * 64) - out_path = os.path.join(tmp, "nested", out_name) - - fake_lin = mock.MagicMock() - fake_lin.size = 64 - fake_lin.tobytes.return_value = b"\x00" * 64 - fake_img = mock.MagicMock() - fake_img.reshape.return_value = fake_img - - fake_pil = types.ModuleType("PIL") - fake_pil_image = types.ModuleType("PIL.Image") - fake_opened = mock.MagicMock() - fake_opened.convert.return_value.save.side_effect = side_effect - fake_pil_image.open = mock.Mock(return_value=fake_opened) - fake_pil.Image = fake_pil_image - - fake_tables = {"GFX10_SW_64K_S_PATINFO": [(0, 0, 0, 0, 0, "1 pipes 8 bpe")]} - with mock.patch.dict(sys.modules, {"PIL": fake_pil, "PIL.Image": fake_pil_image}), \ - mock.patch.object(self.mod, "load", return_value=({}, fake_tables)), \ - mock.patch.object(self.mod, "equation", return_value=[]), \ - mock.patch.object(self.mod, "detile", return_value=fake_lin), \ - mock.patch.object(self.mod, "feature", return_value=fake_img), \ - mock.patch("tile_probe.score", return_value=1.0): - stdout, stderr = io.StringIO(), io.StringIO() - with mock.patch.object(sys, "stdout", stdout), mock.patch.object(sys, "stderr", stderr): - rc = self.mod.main([blob, "--width", "8", "--height", "8", "--out", out_path]) - return rc, stderr.getvalue() - - def test_write_oserror_returns_2_without_traceback(self): - with tempfile.TemporaryDirectory() as tmp: - rc, err = self._run_with_save_side_effect(tmp, "best.png", PermissionError("denied")) - self.assertEqual(rc, 2) - self.assertIn("ERROR:", err) - self.assertNotIn("Traceback", err) - - def test_write_value_error_returns_2_without_traceback(self): - with tempfile.TemporaryDirectory() as tmp: - rc, err = self._run_with_save_side_effect( - tmp, "best.unknown", ValueError("unknown file extension: .unknown") - ) - self.assertEqual(rc, 2) - self.assertIn("ERROR:", err) - self.assertIn("unknown file extension: .unknown", err) - self.assertNotIn("Traceback", err) - - -if __name__ == "__main__": - if HAVE_NUMPY: - for name, fn in list(globals().items()): - if name.startswith("test_") and callable(fn): - fn() - print("ok", name) - unittest.main() - - -@needs_numpy -def test_64k_block_extent_comes_from_the_element_count(): - # XOR modes have no x/y bit that appears alone, so the old solo-bit guess returned 1x1 or too small. - for bpe, bw, bh in ((1, 256, 256), (2, 256, 128), (4, 128, 128), (8, 128, 64), (16, 64, 64)): - _, meta = A.offsets([(1, 0), (0, 1)], bpe, 1, 1) - assert meta[:2] == (bw, bh), (bpe, meta) - assert bw * bh * bpe == 65536 - - -def cli(tmp_path, *args): - import subprocess - tool = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "tools", "amd_swizzle.py") - return subprocess.run([sys.executable, "-I", tool, str(tmp_path / "blob.bin"), *args], - capture_output=True, text=True, timeout=120, check=False) - - -@needs_numpy -def test_out_cannot_overwrite_the_input(tmp_path): - # Before: --out naming the blob rendered the preview over the sample it had just detiled. - blob = tmp_path / "blob.bin" - blob.write_bytes(bytes(range(256)) * 64) - before = blob.read_bytes() - p = cli(tmp_path, "--width", "256", "--height", "256", "--out", str(blob)) - assert p.returncode == 2, p.stderr - assert "overwrite" in p.stderr - assert "Traceback" not in p.stderr - assert blob.read_bytes() == before - - -@needs_numpy -def test_out_directory_is_a_message_not_a_traceback(tmp_path): - (tmp_path / "blob.bin").write_bytes(bytes(range(256)) * 64) - p = cli(tmp_path, "--width", "256", "--height", "256", "--out", str(tmp_path)) - assert p.returncode == 2, p.stderr - assert "is a directory" in p.stderr - assert "Traceback" not in p.stderr - - -@needs_numpy -def test_uncompressed_feature_uses_raw_rgb_bytes(): - import numpy as np - raw = np.arange(8, dtype=np.uint8).reshape(-1, 4) - got = A.feature(raw, 4) - assert got.shape == (2, 3) - assert got.tolist() == [[0, 1, 2], [4, 5, 6]] - - -@pytest.mark.parametrize(("bpe", "texels", "pixels"), [ - (1, bytes((17, 63, 129, 245)), [(17, 17, 17), (63, 63, 63), (129, 129, 129), (245, 245, 245)]), - (2, bytes((17, 33, 63, 94, 129, 159, 245, 200)), [(17, 33, 0), (63, 94, 0), (129, 159, 0), (245, 200, 0)]), -], ids=["r8", "rg8"]) -@needs_numpy -def test_cli_previews_uncompressed_r8_and_rg8( - tmp_path: pathlib.Path, monkeypatch: pytest.MonkeyPatch, bpe: int, texels: bytes, pixels: list[tuple[int, int, int]], -) -> None: - image = pytest.importorskip("PIL.Image") - # A synthetic 4 KiB row-major tile, 64 elements per row in both formats. - bits = ["0"] * (bpe - 1) + [f"X{i}" for i in range(6)] + [f"Y{i}" for i in range(7 - bpe)] - rows = {"NIBBLE01": bits[:8], "NIBBLE2": bits[8:], "NIBBLE3": ["0"] * 4, "NIBBLE4": ["0"] * 4} - header_path = tmp_path / "swizzle.h" - header_path.write_text( - "".join(table(name, [row]) for name, row in rows.items()) - + "const ADDR_SW_PATINFO GFX10_SW_4K_S_PATINFO[] =\n{\n" - + f" {{ 0, 0, 0, 0, 0, }} , // synthetic {bpe} bpe\n}};\n", - encoding="utf-8", - newline="\n", - ) - monkeypatch.setenv("AMD_SWIZZLE_HEADER", str(header_path)) - tile = bytearray(4096) - tile[:2 * bpe] = texels[:2 * bpe] - tile[64 * bpe:66 * bpe] = texels[2 * bpe:] - (tmp_path / "blob.bin").write_bytes(tile) - output = tmp_path / "preview.png" - - result = cli(tmp_path, "--bpe", str(bpe), "--width", "2", "--height", "2", "--modes", "4K", "--out", str(output)) - - assert result.returncode == 0, result.stderr - with image.open(output) as png: - assert png.size == (2, 2) - assert png.tobytes() == bytes(channel for pixel in pixels for channel in pixel) - - -@needs_numpy -def test_cli_detiles_4k_tables_with_4k_blocks(): - # A 128x128 RGBA gradient tiled in 4 KB blocks (32x32 elements, row-major). The same pattern entry under - # a 64K table name must not be picked by --modes 4K, and the 4K table must detile with 12-bit, 4 KB blocks. - import subprocess - import numpy as np - sys.path.insert(0, os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "tools")) - from tile_probe import score - rows = {"NIBBLE01": ["0", "0", "X0", "Y0", "X1", "Y1", "X2", "Y2"], "NIBBLE2": ["X3", "Y3", "X4", "Y4"], - "NIBBLE3": ["X5", "Y5", "X6", "Y6"], "NIBBLE4": ["0", "0", "0", "0"]} - text = "".join(table(name, [row]) for name, row in rows.items()) - for name in ("GFX10_SW_4K_S_PATINFO", "GFX10_SW_64K_S_PATINFO"): - text += (f"const ADDR_SW_PATINFO {name}[] =\n{{\n" - " { 0, 0, 0, 0, 0, } , // 1 pipes 4 bpe\n};\n") - y, x = np.mgrid[0:128, 0:128] - linear = np.stack([x * 2, y * 2, (x + y) // 2, np.full_like(x, 255)], axis=-1).astype(np.uint8) - with tempfile.TemporaryDirectory() as d: - hdr = os.path.join(d, "gfx10SwizzlePattern.h") - with open(hdr, "w", encoding="utf-8") as f: - f.write(text) - nibbles, tables = A.load(hdr) - eq = A.equation(nibbles, tables["GFX10_SW_4K_S_PATINFO"][0], 12) - off, meta = A.offsets(eq, 4, 128, 128, 4096) - assert meta[:2] == (32, 32) - tiled = np.zeros(128 * 128 * 4, np.uint8) - for c in range(4): - tiled[off.reshape(-1) + c] = linear[..., c].reshape(-1) - blob = os.path.join(d, "blob.bin") - tiled.tofile(blob) - p = subprocess.run([sys.executable, "-I", A.__file__, blob, "--bpe", "4", "--width", "128", - "--height", "128", "--modes", "4K"], capture_output=True, text=True, - env=dict(os.environ, AMD_SWIZZLE_HEADER=hdr)) - assert p.returncode == 0, p.stderr - lines = p.stdout.splitlines() - assert [ln.split()[1] for ln in lines] == ["GFX10_SW_4K_S_PATINFO"], p.stdout - assert float(lines[0].split()[0]) == round(score(linear[..., :3].astype(np.float32)), 2), p.stdout - - -@needs_numpy -def test_preview_keeps_partial_bc_blocks(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None: - import struct - - image = pytest.importorskip("PIL.Image") - preview = tmp_path / "preview.png" - tile = bytearray(4096) - colors = ( - (0xF800, 0xF800, 0x07E0), - (0xF800, 0xF800, 0x07E0), - (0x001F, 0x001F, 0xFFFF), - ) - for y, row in enumerate(colors): - for x, color in enumerate(row): - struct.pack_into("= len(raw): - return None - return raw[idx.reshape(-1)] - - -def make_equation(mode, bpe, bits): - """One (x mask, y mask) per address bit; the bits below the element size address bytes inside an element.""" - low = bpe.bit_length() - 1 - eq, xi, yi = [], 0, 0 - for bit in range(bits): - if bit < low: - eq.append((0, 0)) - elif (bit - low) % 2 == 0: - eq.append((1 << xi, 0)) - xi += 1 - else: - eq.append((0, 1 << yi)) - yi += 1 - if mode == "D_X": - for bit in range(low, min(bits, low + 6)): - mx, my = eq[bit] - eq[bit] = (mx ^ (1 << (xi + bit % 3)), my ^ (1 << (yi + bit % 2))) - elif mode == "R_X": - for bit in range(low, bits): - mx, my = eq[bit] - eq[bit] = (mx ^ (1 << (xi + bit % 4)) ^ (1 << (xi + 1 + bit % 3)), my ^ (1 << (yi + bit % 5)) ^ (1 << (yi + 2))) - return eq - - -def random_data(n, seed): - return np.random.default_rng(seed).integers(0, 256, n, dtype=np.uint8).tobytes() - - -# Narrow, tall, single-row/column, and sizes that are not multiples of any block extent. -SIZES = [(1, 1), (1, 70), (70, 1), (3, 5), (37, 5), (5, 37), (64, 64), (100, 37), (129, 65), (130, 3), (257, 513)] -BLOCKS = {256: 8, 4096: 12, 65536: 16} - - -@unittest.skipIf(np is None, "numpy is not installed") -class DetileMatchesReference(unittest.TestCase): - def check(self, eq, bpe, wb, hb, block_bytes, data=None): - label = (bpe, wb, hb, block_bytes) - want_off, want_meta = reference_offsets(eq, bpe, wb, hb, block_bytes) - got_off, got_meta = A.offsets(eq, bpe, wb, hb, block_bytes) - self.assertEqual(got_meta, want_meta, label) - self.assertEqual(got_off.shape, (hb, wb), label) - self.assertEqual(got_off.dtype, np.int64, label) - np.testing.assert_array_equal(got_off, want_off, str(label)) - if data is None: - data = random_data(int(want_off.max()) + bpe + 3, wb * 7 + hb) - want = reference_detile(data, eq, bpe, wb, hb, block_bytes) - got = A.detile(data, eq, bpe, wb, hb, block_bytes) - if want is None: - self.assertIsNone(got, label) - else: - self.assertEqual(got.shape, want.shape, label) - self.assertEqual(got.dtype, np.uint8, label) - np.testing.assert_array_equal(got, want, str(label)) - return want - - def test_modes_bpe_sizes_and_block_sizes(self): - for block_bytes, bits in BLOCKS.items(): - for bpe in (1, 2, 4, 8, 16): - if bpe > block_bytes: - continue - for mode in ("S", "D_X", "R_X"): - eq = make_equation(mode, bpe, bits) - for wb, hb in SIZES: - with self.subTest(block=block_bytes, bpe=bpe, mode=mode, size=(wb, hb)): - self.check(eq, bpe, wb, hb, block_bytes) - - def test_realistic_texture_sizes(self): - # BC1 / BC7 are 4x4-pixel elements; RGBA8 is one pixel per element. - for bpe, pixels_per_element in ((8, 4), (16, 4), (4, 1)): - for px in (512, 1024): - n = px // pixels_per_element - for mode in ("S", "D_X", "R_X"): - with self.subTest(bpe=bpe, px=px, mode=mode): - self.check(make_equation(mode, bpe, 16), bpe, n, n, 65536) - - def test_random_equations(self): - rng = random.Random(20260807) - for _ in range(60): - bpe = rng.choice((1, 2, 4, 8, 16)) - bits = rng.choice((8, 12, 16)) - block_bytes = 1 << bits - if bpe > block_bytes: - continue - eq = [(rng.getrandbits(16) if rng.random() < 0.8 else 0, rng.getrandbits(16) if rng.random() < 0.8 else 0) - for _ in range(bits)] - wb, hb = rng.randint(1, 200), rng.randint(1, 200) - with self.subTest(bpe=bpe, bits=bits, size=(wb, hb)): - self.check(eq, bpe, wb, hb, block_bytes) - - def test_too_short_data_returns_none(self): - eq = make_equation("R_X", 4, 16) - off, _ = A.offsets(eq, 4, 100, 37) - need = int(off.max()) // 4 * 4 + 4 - for size in (0, 3, need - 4, need - 1): - with self.subTest(size=size): - self.assertIsNone(self.check(eq, 4, 100, 37, 65536, data=bytes(size))) - self.assertIsNotNone(self.check(eq, 4, 100, 37, 65536, data=bytes(need))) - - def test_trailing_partial_element_is_ignored(self): - eq = make_equation("D_X", 8, 16) - off, _ = A.offsets(eq, 8, 9, 9) - data = random_data(int(off.max()) + 8 + 5, 5) - for cut in range(0, 8): - self.check(eq, 8, 9, 9, 65536, data=data[: len(data) - cut]) - - def test_accepts_bytearray_and_memoryview(self): - eq = make_equation("R_X", 16, 16) - data = random_data(65536 * 3, 9) - want = A.detile(data, eq, 16, 70, 33) - for wrapper in (bytearray, memoryview): - np.testing.assert_array_equal(A.detile(wrapper(data), eq, 16, 70, 33), want) - - def test_element_size_not_a_power_of_two_or_not_dividing_the_block(self): - eq = make_equation("S", 4, 12) - for bpe, block_bytes in ((3, 4096), (3, 65536), (6, 4096), (12, 65536), (5, 256)): - for wb, hb in ((1, 1), (7, 9), (40, 33)): - with self.subTest(bpe=bpe, block=block_bytes, size=(wb, hb)): - self.check(eq, bpe, wb, hb, block_bytes, data=random_data(1 << 21, bpe)) - - def test_round_trip_tiles_then_detiles(self): - for block_bytes, bits in ((4096, 12), (65536, 16)): - for bpe in (1, 2, 4, 8, 16): - eq = make_equation("S", bpe, bits) # an S layout is a bijection within each block - wb, hb = 97, 53 - linear = np.random.default_rng(bpe).integers(0, 256, (hb * wb, bpe), dtype=np.uint8) - off, _ = A.offsets(eq, bpe, wb, hb, block_bytes) - self.assertEqual(len(np.unique(off)), off.size) - tiled = np.zeros((int(off.max()) // bpe + 1, bpe), np.uint8) - tiled[off.reshape(-1) // bpe] = linear - got = A.detile(tiled.tobytes(), eq, bpe, wb, hb, block_bytes) - np.testing.assert_array_equal(got, linear) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/test_analyze_4240_full.py b/tests/test_analyze_4240_full.py deleted file mode 100644 index 75f822a39..000000000 --- a/tests/test_analyze_4240_full.py +++ /dev/null @@ -1,256 +0,0 @@ -"""analyze_4240_full: a rejected 42 40 00 00 block is counted and stepped over, not parsed for ever. - - python -I tests/test_analyze_4240_full.py - -Everything is synthetic: an RPF9-like header, zlib streams and hand-built block headers. No game data is used. -""" -import contextlib -import io -import json -import os -import struct -import subprocess -import sys -import tempfile -import unittest -import zlib -from unittest import mock - -ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) -TOOL = os.path.join(ROOT, "tools", "analyze_4240_full.py") -sys.path.insert(0, os.path.join(ROOT, "tools")) - -import analyze_4240_full as A # noqa: E402 - -BLOCK_6330 = struct.pack(" None: - path = os.path.join(self.root, "direct-4240.rpf") - # Four 8-byte positions from 0x80, then four 4-byte colors from 0xA0. - slots = [0x4042, (0x50 << 8) | 0x26] + [0] * 22 - page = block_4240(slots) + bytes(0xA0 - 0x60) + bytes((10, 20, 30, 255)) * 4 - make_archive(path, page) - - stats = A.process_archive(path) - - self.assertEqual((stats["streams"], stats["blocks_4240"], stats["blocks_6330"]), (1, 1, 0)) - self.assertEqual(stats["slot_tag_counts"], {(0, 0x42): 1, (1, 0x26): 1}) - self.assertEqual(stats["strides"], {(0, 0x42, 1, 0x26, 32): 1}) - self.assertEqual(stats["errors"], 0) - - def test_missing_input_is_one_error_line(self): - missing = os.path.join(self.root, "missing.rpf") - p = self.run_tool(missing) - self.assertEqual(p.returncode, 2, p.stderr) - self.assertIn("does not exist", p.stderr) - self.assertIn("missing.rpf", p.stderr) - self.assertNotIn("Traceback", p.stderr) - self.assertNotIn("Processing", p.stdout) - - def test_a_folder_input_is_one_line_and_the_run_continues(self): - # Before: exists() let a folder through, open() raised PermissionError, and the archives after it were lost. - folder = os.path.join(self.root, "carve") - os.makedirs(folder) - good = self.truncated_archive() - p = self.run_tool(folder, good) - self.assertEqual(p.returncode, 1, p.stderr) - self.assertIn("is not a file", p.stderr) - self.assertIn("carve", p.stderr) - self.assertNotIn("Traceback", p.stderr) - self.assertIn("Processing " + good, p.stdout, "the next archive is still read") - - def test_unreadable_archive_is_reported_and_later_archives_are_measured(self): - blocked = os.path.join(self.root, "locked.rpf") - make_archive(blocked, BLOCK_6330) - good = self.truncated_archive() - out = os.path.join(self.root, "stats.json") - stderr = io.StringIO() - - def open_archive(path, *args, **kwargs): - if path == blocked: - raise PermissionError(13, "input is locked", path) - return open(path, *args, **kwargs) - - with (mock.patch.object(A, "open", create=True, side_effect=open_archive), - mock.patch.object(sys, "argv", [TOOL, blocked, good, "--json", out]), - contextlib.redirect_stdout(io.StringIO()), - contextlib.redirect_stderr(stderr)): - self.assertEqual(A.main(), 1) - self.assertEqual(stderr.getvalue().splitlines(), - [f"ERROR: cannot read {blocked}: input is locked"]) - with open(out, encoding="utf-8") as fh: - doc = json.load(fh) - self.assertEqual(len(doc), 1) - self.assertEqual(doc[0]["errors"], 1) - - def test_limit_below_one_is_refused(self): - path = self.truncated_archive() - for bad in ("0", "-1"): - with self.subTest(limit=bad): - p = self.run_tool(path, "--limit", bad) - self.assertEqual(p.returncode, 2, p.stderr) - self.assertIn("at least 1", p.stderr) - self.assertNotIn("Traceback", p.stderr) - - def test_json_in_a_missing_folder_is_created(self): - path = self.truncated_archive() - out = os.path.join(self.root, "no", "such", "stats.json") - p = self.run_tool(path, "--json", out) - self.assertEqual(p.returncode, 0, p.stderr) - with open(out, encoding="utf-8") as f: - doc = json.load(f) - self.assertEqual(len(doc), 1) - self.assertEqual(doc[0]["errors"], 1) - - def test_json_naming_an_input_archive_is_refused_and_the_archive_kept(self): - # Before: the archive was read, then replaced with the JSON report. - path = self.truncated_archive() - with open(path, "rb") as f: - before = f.read() - for spelling in (path, os.path.join(self.root, ".", os.path.basename(path))): - with self.subTest(json=spelling): - p = self.run_tool(path, "--json", spelling) - self.assertEqual(p.returncode, 2, p.stderr) - self.assertIn("would overwrite the input archive", p.stderr) - self.assertNotIn("Traceback", p.stderr) - self.assertNotIn("Processing", p.stdout, "refused before the scan") - with open(path, "rb") as f: - self.assertEqual(f.read(), before) - - def test_json_naming_a_later_input_is_refused(self): - first, second = self.truncated_archive(), os.path.join(self.root, "second.rpf") - make_archive(second, BLOCK_6330) - p = self.run_tool(first, second, "--json", second) - self.assertEqual(p.returncode, 2, p.stderr) - self.assertIn("second.rpf", p.stderr) - self.assertTrue(open(second, "rb").read().startswith(b"9FPR")) - - def test_json_through_a_link_to_an_input_is_refused(self): - path = self.truncated_archive() - link = os.path.join(self.root, "link.json") - try: - os.link(path, link) # a hard link: another name for the archive itself - except OSError as e: - self.skipTest(f"hard links unavailable: {e}") - p = self.run_tool(path, "--json", link) - self.assertEqual(p.returncode, 2, p.stderr) - self.assertIn("would overwrite the input archive", p.stderr) - self.assertTrue(open(path, "rb").read().startswith(b"9FPR")) - - def test_json_folder_is_refused_before_the_scan(self): - path = self.truncated_archive() - p = self.run_tool(path, "--json", self.root) - self.assertEqual(p.returncode, 2, p.stderr) - self.assertIn("is a folder", p.stderr) - self.assertNotIn("Traceback", p.stderr) - self.assertNotIn("Processing", p.stdout) - - def test_a_failed_json_write_is_one_error_line(self): - path = self.truncated_archive() - blocker = os.path.join(self.root, "plain-file") - with open(blocker, "w", encoding="utf-8") as f: - f.write("x") - out = os.path.join(blocker, "stats.json") # its parent is a file, so the folder can't be made - p = self.run_tool(path, "--json", out) - self.assertEqual(p.returncode, 2, p.stderr) - self.assertIn("cannot write", p.stderr) - self.assertNotIn("Traceback", p.stderr) - - def bad_offset_archive(self): - path = os.path.join(self.root, "bad-offset.rpf") - header = bytearray(0x780) - header[0:4] = b"9FPR" - struct.pack_into("= 0 else -2 * v - 1 - - -def encode_delta2(ints, quantum, offset): - """Type-10 channel for non-negative integers `ints` (value = int * quantum + offset).""" - nf = len(ints) - nc = (nf + 63) // 64 - starts = [ints[64 * c] for c in range(nc)] - raw = [] - for c in range(nc): - v = 0 - for j in range(64): - f = 64 * c + j + 1 - if f >= nf: - break - step = ints[f] - ints[f - 1] - raw.append(zz(step - v)) - v = step - assert len(raw) == nf - 1 - raw += [0] * ((-len(raw)) % 8) - widths = [max(x.bit_length() for x in raw[g:g + 8]) for g in range(0, len(raw), 8)] - total = sum(widths) - c3 = (total + 31) // 32 - positions, acc = [], 0 - for c in range(nc): - positions.append(acc) - acc += sum(widths[8 * c:8 * c + 8]) - c1 = max(1, max(positions).bit_length()) - c2 = max(1, max(starts).bit_length()) - front = Bits() - for p in positions: - front.put(p, c1) - for s in starts: - front.put(s, c2) - for k in widths: - front.put(0, k) - front.put(1, 1) - lanes = [Bits() for _ in range(8)] - for g, k in enumerate(widths): - for j in range(8): - lanes[j].put(raw[8 * g + j], k) - front_bytes = front.bytes(((front.n + 31) // 32) * 4) - words = [] - lane_words = [lanes[j].value.to_bytes(4 * c3, "little") for j in range(8)] - for w in range(c3): - for j in range(8): - words.append(lane_words[j][4 * w:4 * w + 4]) - blob = front_bytes + b"".join(words) - head = struct.pack("> 7) & 1, control h & 0x7F - return obj - - -def motion_matcher(p, name, refs=True, pose_rows=True): - """A `.motionmatcher` with two records: record 0 is the dictionary's own `.clip` (hash 1), record 1 a clip that - is not in the archive. Its own key is (3, joaat32(name)).""" - m = p.alloc(bytes(0x190)) - p.ptr(m + 0x20, features(p, pose_rows)) # the feature object - p.b[m + 0x28:m + 0x38] = bytes(range(0x80, 0x90)) # 16-byte id; +0x30 is not a pointer - p.string(m + 0x38, "pack:/one.motionmatcher") - records = struct.pack(" child k - motion = self.motion(children=[(1, 2), (3, 4)], axis=([joaat32("speed")], [(0, 0.0), (1, 1.0)], 0.0, 1.0), - sample_lists=[[(0, 1.0, 1.0), (1, 1.0, 1.0)], [(1, 1.0, 1.0)]]) - stats = anim_clips.new_stats() - anim_clips.count_motion_blend(motion, stats) - self.assertEqual((stats["motion_samples:3:sample_k_is_child_k"], stats["motion_samples:3:every_list_one_item"], - stats["motion_samples:3:every_child_sampled"]), (0, 0, 1)) - - def test_malformed_node_keeps_the_time_table(self): - times = [(1.5, 1.5, [(0.0, 0.0), (1.5, 1.5)])] - motion = self.motion(children=[(1, 2)], times=times, node=(8, [(1, 0, 0)], 1), node_axis_count=0xFFFF) - self.assertIsNone(motion["node"]) # the axis array runs past the page - self.assertEqual(len(motion["times"]), 1) - - def test_child_out_of_range_is_counted(self): - motion = self.motion(children=[(1, 2)], axis=([joaat32("speed")], [(0, 0.0)], 0.0, 0.0), - sample_lists=[[(5, 1.0, 1.0)]]) - stats = anim_clips.new_stats() - anim_clips.count_motion_blend(motion, stats) - self.assertEqual((stats["motion_samples:3:children_in_range"], stats["motion_samples:3:every_child_sampled"]), - (0, 0)) - - def test_multi_axis_nodes(self): - for kind, n_axes in ((4, 2), (5, 3), (6, 4), (8, 5)): - axes = [(joaat32("speed") if i == 0 else 0xABC0 + i, i, 1) for i in range(n_axes)] - lists = [[(i % 2, 1.0, 1.0)] for i in range(4)] - motion = self.motion(children=[(1, 2), (3, 4)], node=(kind, axes, 4), sample_lists=lists) - k, axis = motion["node"] - self.assertEqual((k, axis["names"], axis["slots"], axis["sample_count"]), - (kind, [a[0] for a in axes], [(i, 1) for i in range(n_axes)], 4)) - self.assertNotIn("samples", axis) - stats = anim_clips.new_stats() - anim_clips.count_motion_blend(motion, stats) - self.assertEqual((stats[f"motion_node_axes:{kind}:{n_axes}"], - stats[f"motion_node_axis_name:{kind}:speed"], - stats[f"motion_node_axis_name:{kind}:unresolved"], - stats[f"motion_samples:{kind}:lists_equal_node_samples"], - stats[f"motion_samples:{kind}:every_child_sampled"], stats["motion_axes"]), - (1, 1, n_axes - 1, 1, 1, 0)) - - def test_multi_axis_pairs(self): - motion = self.motion(children=[(1, 2)], node=(6, [(1, 0, 0)] * 4, 1), node_pairs=[(0xAA, 0xBB), (0xCC, 0xDD)]) - self.assertEqual(motion["node"][1]["pairs"], [(0xAA, 0xBB), (0xCC, 0xDD)]) - stats = anim_clips.new_stats() - anim_clips.count_motion_blend(motion, stats) - self.assertEqual(stats["motion_node_pairs:6:2"], 1) - motion = self.motion(children=[(1, 2)], node=(4, [(1, 0, 0)] * 2, 1)) # null +0x20 - self.assertIsNone(motion["node"][1]["pairs"]) - stats = anim_clips.new_stats() - anim_clips.count_motion_blend(motion, stats) - self.assertEqual(stats["motion_node_pairs:4:null"], 1) - - def test_type1_node(self): - motion = self.motion(children=[(1, 2)], node=(1, [], 1), sample_lists=[[(0, 1.0, 1.0)]]) - self.assertEqual(motion["node"], (1, {"names": [], "slots": [], "sample_count": 1})) - stats = anim_clips.new_stats() - anim_clips.count_motion_blend(motion, stats) - self.assertEqual((stats["motion_node_type:1"], stats["motion_node_axes:1:0"], - stats["motion_samples:1:sample_k_is_child_k"]), (1, 1, 1)) - - def test_sample_lists_of_a_two_node_motion_are_not_counted(self): - motion = self.motion(children=[(1, 2)], parameters=2, node=(1, [], 1), sample_lists=[[(0, 1.0, 1.0)]] * 3) - self.assertEqual(len(motion["samples"]), 3) - stats = anim_clips.new_stats() - anim_clips.count_motion_blend(motion, stats) - self.assertFalse([k for k in stats if k.startswith("motion_samples:")]) - - def test_delta2_round_trip(self): - for n in (1, 2, 8, 9, 63, 64, 65, 129, 200): - ints = [(7 * f * f) % 1000 + 20 * (f % 3) for f in range(n)] - blob = encode_delta2(ints, 0.5, -3.0) + bytes(8) - stats = anim_clips.new_stats() - values, size = anim_clips.decode_delta2(blob, 0, n, stats) - self.assertEqual(size, len(blob) - 8) - self.assertEqual(values, [x * 0.5 - 3.0 for x in ints], n) - self.assertEqual(stats["delta2_boundaries"], (n - 1) // 64) - self.assertEqual(stats["delta2_boundaries_closed"], stats["delta2_boundaries"]) - - def test_tracks(self): - anim = self.d["packs"][0]["animations"][0] - stats = anim_clips.new_stats() - tracks, total = anim_clips.decode_animation(self.s, anim, stats) - self.assertEqual(total, NF) - self.assertEqual(stats["frames_sum_matches"], 1) - for f in (0, 39, 40, 41, NF - 1): - x, y, z = X_INTS[f] * 0.002 - 0.05, 0.25, Z_INTS[f] * 0.002 - 0.1 - w = math.sqrt(1 - x * x - y * y - z * z) - for got, want in zip(tracks[0][f], (x, y, z, w)): - self.assertAlmostEqual(got, want, places=5) - self.assertEqual(len(tracks[1][f]), 4) - for got in tracks[1][f]: - self.assertAlmostEqual(got, 0.5, places=6) - self.assertEqual(tracks[2][f], (1.0, 2.0, 3.0)) - self.assertAlmostEqual(tracks[3][f][0], TABLE[f % 4] * 0.1 + 1.0, places=5) - self.assertEqual(tracks[4][f][0], f * 1.5) - self.assertEqual(stats["boundary_quaternions"], stats["boundary_quaternions_same_rotation"]) - self.assertEqual(stats["boundary_values"], stats["boundary_values_within_1e-3"]) - self.assertEqual(stats["channel:10_delta2_float"], 2) - self.assertEqual(stats["channel:03_raw_float"], 2) - - def test_rebuilt_component_goes_to_the_type7_position(self): - seq = encode_sequence(1, [(2, 0, 0, 0.1), (2, 0, 1, 0.2), (2, 0, 2, 0.3), (7, 0, 1, None)]) - s = anim_clips.System(dictionary("p", [seq], 1, TRACKS[:1])) - anim = anim_clips.parse_dictionary(s)["packs"][0]["animations"][0] - tracks, _ = anim_clips.decode_animation(s, anim) - w = math.sqrt(1 - 0.01 - 0.04 - 0.09) - for got, want in zip(tracks[0][0], (0.1, w, 0.2, 0.3)): - self.assertAlmostEqual(got, want, places=6) - - def test_definitions_must_end_at_the_frame_data(self): - seq = bytearray(encode_sequence(3, [(2, 0, 0, 1.0), (2, 0, 1, 2.0)])) - struct.pack_into("= 16) at the very end of the page so u64(+0x30) fits while d[+0x3F] is OOB. - p = Page() - pm = p.alloc(bytes(16)) - p.b[pm + 8], p.b[pm + 9] = 1, 0 - p.ptr(8, pm) - p.string(0x38, "trunc@clip") - struct.pack_into(" (32 * words) // 1 = 8.5B - with self.assertRaisesRegex(anim_clips.DecodeError, "type-5"): - anim_clips.decode_sequence(anim_clips.System(bytes(seq)), 0) - # Smaller type-5 word count that still overruns frame_offset into frame bits. - seq2 = bytearray(encode_sequence(2, [(5, 0, 0, (2, 4, TABLE, 0.1, 1.0, [0, 1]))])) - struct.pack_into(" 1 word allocated before frame_offset - with self.assertRaisesRegex(anim_clips.DecodeError, "type-5"): - anim_clips.decode_sequence(anim_clips.System(bytes(seq2)), 0) - # Type-10 word count overrunning frame_offset into frame bits / counts. - seq3 = bytearray(encode_sequence(4, [(10, 0, 0, (0.5, 0.0, [1, 2, 3, 4]))])) - words = struct.unpack_from(" None: - data = bytearray(two_sequence_dictionary("six-pages@dict")) - page_map = struct.unpack_from("= 64 for page in pages)) - path = os.path.join(self.tmp.name, "six-pages.rpf") - root, *_ = write_rpf(path, pages) - _, summary = anim_clips.scan(path) - self.assertEqual(summary["pages"], {"6": 1}) - self.assertEqual(summary["counts"]["animations_decoded"], 1) - - result = subprocess.run( - [sys.executable, "-I", TOOL, path, "--decode", str(root), "--frames", "3"], - capture_output=True, text=True, errors="replace", check=False, - ) - self.assertEqual(result.returncode, 0, result.stderr) - animation = json.loads(result.stdout)["packs"][0]["animations"][0] - self.assertEqual(animation["decoded_frames"], NF) - self.assertEqual(animation["decoded"]["2"], [[1.0, 2.0, 3.0]] * 3) - self.assertEqual(animation["decoded"]["4"], [[0.0], [1.5], [3.0]]) - - def test_decode_page_counts_on_or_across_sixth_page(self): - data = bytearray(two_sequence_dictionary()) - pm = len(data) - data.extend(bytes(96)) - struct.pack_into(" animated GLB). - - python -I tests/test_anim_glb.py - -Every byte is built here: a synthetic skeleton drawable, a synthetic skinned part drawable (system and graphics -pages) and a synthetic anim.rpf from test_anim_clips' encoders. No game file, value or name is used. -""" -import json -import math -import os -import struct -import subprocess -import sys -import tempfile -import unittest -import zlib -from unittest.mock import patch - -ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) -TOOL = os.path.join(ROOT, "tools", "anim_glb.py") -sys.path.insert(0, os.path.join(ROOT, "tools")) -sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) - -import anim_clips # noqa: E402 -import anim_glb # noqa: E402 -from anim_index import joaat32 # noqa: E402 -import test_anim_clips as clips_fixture # noqa: E402 - -SYSTEM, GRAPHICS = 0x50000000, 0x60000000 -# Three joints: the clip fixture animates skel_a and skel_b (rotation) and skel_c (translation). -NAMES = ("SKEL_A", "SKEL_B", "SKEL_C") -PARENTS = (None, 0, 1) -ROTATIONS = ((0.0, 0.0, math.sqrt(0.5), math.sqrt(0.5)), (0.0, 0.0, 0.0, 1.0), (0.5, 0.5, 0.5, 0.5)) -TRANSLATIONS = ((0.0, 0.0, 1.0), (0.5, 0.0, 0.0), (0.0, 0.25, 0.0)) - - -class Page: - """System or graphics page builder; `base` is 0x50000000 or 0x60000000.""" - - def __init__(self, base=SYSTEM, head=0x100): - self.b = bytearray(head) - self.base = base - - def alloc(self, data, align=16): - self.b += bytes((-len(self.b)) % align) - at = len(self.b) - self.b += data - return at - - def ptr(self, at, target, base=None): - struct.pack_into(" 4 else 1 # 8 influences use slots 16/17 and 20/21 - for k in range(sets): - weights, bones = bytearray(), bytearray() - for pairs in skin: - pairs = (pairs + [(0, 0)] * 8)[4 * k:4 * k + 4] - weights += bytes(w for _b, w in pairs) - bones += bytes(b for b, _w in pairs) if layout == "u8x4" else \ - b"".join(struct.pack(" offsets.""" - out, offsets = bytearray(0x1000), [] - for pages in resources: - offsets.append(len(out) + 16) - for k, page in enumerate(pages): - if k == 0: - out += bytes(16) - out += zlib.compress(page) - out += bytes((-len(out)) % 16) - out += bytes((-len(out)) % 0x1000) - with open(path, "wb") as f: - f.write(out) - return offsets - - -def read_glb(path): - with open(path, "rb") as f: - data = f.read() - magic, version, total = struct.unpack_from("<4sII", data, 0) - assert magic == b"glTF" and version == 2 and total == len(data) - jlen, _ = struct.unpack_from(" a for a, b in zip(times, times[1:]))) - - def test_bone_hash_zero_drives_the_mover(self): - out, _ = self.channels(0.0, 4 / 30, 1.0) - self.assertIn(("mover", "translation"), out) - out, tally = self.channels(0.0, 4 / 30, 1.0, root_motion=False) - self.assertNotIn(("mover", "translation"), out) - self.assertEqual(tally["tracks_mover_skipped"], 1) - - def test_single_frame_pose_window_keeps_only_that_frame(self): - anim_clips.decode_animation = lambda _s, _anim: ( - {0: [(float(k), 0.0, 0.0, 1.0) for k in range(5)], - 1: [(float(k * 10), 0.0, 0.0) for k in range(5)]}, - 5, - ) - out, _ = self.channels(2 / 30, 2 / 30, 1.0) - self.assertEqual(out[("mover", "translation")], [(0.0, (20.0, 0.0, 0.0))]) - # Off-grid start == end windows pick the nearest frame instead of falling back to frame 0. - out_mid, _ = self.channels(0.075, 0.075, 1.0) - self.assertEqual(out_mid[("mover", "translation")], [(0.0, (20.0, 0.0, 0.0))]) - out_hi, _ = self.channels(0.095, 0.095, 1.0) - self.assertEqual(out_hi[("mover", "translation")], [(0.0, (30.0, 0.0, 0.0))]) - # Even when start == end sits slightly before a frame within 1e-4, timestamp stays 0.0. - self.anim["duration"] = 4 / 32 - t = 2 / 32 - 2**-14 - out_tol, _ = self.channels(t, t, 1 / 1024) - self.assertEqual(out_tol[("mover", "translation")], [(0.0, (20.0, 0.0, 0.0))]) - - def test_select_clips_handles_non_hex_0x_names_and_bad_selectors(self): - d = { - "clips": [ - {"kind": "clip", "name": "other.clip", "hash": 0x11111111}, - {"kind": "clip", "name": "0x_intro.clip", "hash": 0x22222222}, - ] - } - self.assertEqual([c["hash"] for c in anim_glb.select_clips(d, ["0x_intro"])], [0x22222222]) - with self.assertRaisesRegex(anim_glb.ExportError, "0xbad"): - anim_glb.select_clips(d, ["0xbad"]) - - -class SamplerTimeTest(unittest.TestCase): - def test_fractional_time_bounds_match_the_binary_accessor(self) -> None: - skeleton = skeleton_resource() - joints, _ = anim_glb.read_skeleton(skeleton, anim_glb.drawable_at(skeleton, None)) - keys = [(1 / 30, (0.0, 0.0, 0.0)), (2 / 30, (1.0, 0.0, 0.0))] - glb, _ = anim_glb.build(joints, [], [("sample", {(0, "translation"): keys})]) - with tempfile.TemporaryDirectory() as tmp: - path = os.path.join(tmp, "sampler.glb") - with open(path, "wb") as out: - out.write(glb) - gltf, binary = read_glb(path) - - sampler = gltf["animations"][0]["samplers"][0] - index = sampler["input"] - min_time, max_time = accessor_values(gltf, binary, index) - self.assertEqual(gltf["accessors"][index]["min"], list(min_time)) - self.assertEqual(gltf["accessors"][index]["max"], list(max_time)) - - def test_keys_that_collapse_to_one_stored_time_are_refused(self) -> None: - skeleton = skeleton_resource() - joints, _ = anim_glb.read_skeleton(skeleton, anim_glb.drawable_at(skeleton, None)) - keys = [(1.0, (0.0, 0.0, 0.0)), (1.0 + 2 ** -25, (1.0, 0.0, 0.0))] - with self.assertRaisesRegex(ValueError, "key times are not increasing"): - anim_glb.build(joints, [], [("sample", {(0, "translation"): keys})]) - - -class ExportTest(unittest.TestCase): - def setUp(self): - self.tmp = tempfile.TemporaryDirectory() - self.packs = os.path.join(self.tmp.name, "packs.rpf") - self.anim = os.path.join(self.tmp.name, "anim.rpf") - palette = [joaat32("skel_c"), joaat32("skel_a")] - skin = [[(0, 200), (1, 55)], [(1, 255)], [(0, 128), (1, 127)], [(1, 255)]] - self.offsets = write_archive(self.packs, [[skeleton_resource()], list(part_resource(palette, "u8x4", skin))]) - self.dict_offset = clips_fixture.write_rpf(self.anim, [clips_fixture.two_sequence_dictionary("first@dict")])[0] - - def tearDown(self): - self.tmp.cleanup() - - def run_tool(self, *args): - return subprocess.run([sys.executable, "-I", TOOL, *args], capture_output=True, text=True) - - def export(self, *extra): - out = os.path.join(self.tmp.name, "out.glb") - report = os.path.join(self.tmp.name, "report.json") - r = self.run_tool(self.packs, out, "--skeleton", hex(self.offsets[0]), "--part", hex(self.offsets[1]), - "--anim", self.anim, "--dictionary", hex(self.dict_offset), "--report", report, *extra) - self.assertEqual(r.returncode, 0, r.stderr) - with open(report, encoding="utf-8") as f: - return read_glb(out), json.load(f) - - def test_export_writes_skin_joints_and_clip(self): - (gltf, binary), report = self.export() - self.assertEqual(gltf["nodes"][0]["rotation"], anim_glb.Z_UP_TO_Y_UP) - skin = gltf["skins"][0] - self.assertEqual([gltf["nodes"][i]["name"] for i in skin["joints"]], list(NAMES)) - ibm = accessor_values(gltf, binary, skin["inverseBindMatrices"]) - world = world_transforms() - for got, (q, t) in zip(ibm, world): - for a, b in zip(got, inverse_bind(q, t)): - self.assertAlmostEqual(a, b, places=5) - prim = gltf["meshes"][0]["primitives"][0] - joints = accessor_values(gltf, binary, prim["attributes"]["JOINTS_0"]) - weights = accessor_values(gltf, binary, prim["attributes"]["WEIGHTS_0"]) - self.assertEqual(joints[0][:2], (2, 0)) - for row in weights: - self.assertAlmostEqual(sum(row), 1.0, places=5) - # skinned mesh nodes sit at the scene root, outside the turned skeleton - mesh_node = next(n for n in gltf["nodes"] if "mesh" in n) - self.assertNotIn("rotation", mesh_node) - self.assertEqual(mesh_node["skin"], 0) - # the fixture clip: rotation on skel_a and skel_b, translation on skel_c, two control tracks left out - (animation,) = gltf["animations"] - targets = sorted((gltf["nodes"][c["target"]["node"]]["name"], c["target"]["path"]) - for c in animation["channels"]) - self.assertEqual(targets, [("SKEL_A", "rotation"), ("SKEL_B", "rotation"), ("SKEL_C", "translation")]) - self.assertEqual(report["clips"][0]["tracks_other_type"], 2) - # the sampled values are the decoded ones - s, d = anim_glb.load_dictionary(self.anim, self.dict_offset) - tracks, frames = anim_clips.decode_animation(s, d["packs"][0]["animations"][0]) - channel = next(c for c in animation["channels"] if gltf["nodes"][c["target"]["node"]]["name"] == "SKEL_A") - sampler = animation["samplers"][channel["sampler"]] - times = accessor_values(gltf, binary, sampler["input"]) - values = accessor_values(gltf, binary, sampler["output"]) - self.assertEqual(len(times), frames) - self.assertAlmostEqual(times[-1][0], (frames - 1) / 30.0, places=5) - for got, want in zip(values, tracks[0]): - for a, b in zip(got, want): - self.assertAlmostEqual(a, b, places=5) - - def test_dictionary_lookup_stops_before_adjacent_resource(self): - data = clips_fixture.two_sequence_dictionary() - _, selected, _ = clips_fixture.write_rpf(self.anim, [data] * 3) - with patch.object(anim_glb.anim_index, "classify", wraps=anim_glb.anim_index.classify) as classify: - system, _dictionary = anim_glb.load_dictionary(self.anim, selected) - self.assertEqual(system.d, data) - self.assertEqual([call.args[1] for call in classify.call_args_list], [selected]) - - def test_export_reads_page_map_on_sixth_page(self): - data = bytearray(clips_fixture.two_sequence_dictionary()) - page_map = len(data) - data.extend(bytes(96)) - struct.pack_into("" * 4 - return data + bytes(max(0, 64 - len(data))) - - -def bink(): - data = bytearray(0x40) - data[:4] = b"KB2n" - struct.pack_into("/index.json is the carve manifest's name even before a carve has written it. - carve = os.path.join(self.root, "carved_no_manifest") - os.makedirs(carve) - manifest = os.path.join(carve, "index.json") - out_csv = os.path.join(self.root, "no_manifest.csv") - for args, flag in (([manifest], "output"), ([out_csv, "--rigs", manifest], "--rigs")): - with self.subTest(flag=flag): - p = subprocess.run([sys.executable, "-I", TOOL, carve, *args, "--quiet"], - capture_output=True, text=True, encoding="utf-8", errors="replace") - self.assertEqual(p.returncode, 2, p.stdout + p.stderr) - self.assertIn(f"{flag} would overwrite the carve manifest", p.stderr) - self.assertFalse(os.path.exists(manifest)) - - def test_cli_carve_dir_protects_manifest_and_input_files(self): - carve = os.path.join(self.root, "carved_manifest_test") - os.makedirs(carve) - manifest = os.path.join(carve, "index.json") - with open(manifest, "w", encoding="utf-8") as f: - f.write('{"manifest": true}') - bin_file = os.path.join(carve, "000000001000.bin") - with open(bin_file, "wb") as f: - f.write(b"A" * 64) - out_csv = os.path.join(self.root, "valid.csv") - - # Refuse to overwrite carve manifest via out - p = subprocess.run([sys.executable, "-I", TOOL, carve, manifest, "--quiet"], - capture_output=True, text=True, errors="replace") - self.assertEqual(p.returncode, 2, p.stdout + p.stderr) - self.assertIn("output would overwrite the carve manifest", p.stderr) - - # Refuse to overwrite carve manifest via --rigs - p = subprocess.run([sys.executable, "-I", TOOL, carve, out_csv, "--rigs", manifest, "--quiet"], - capture_output=True, text=True, errors="replace") - self.assertEqual(p.returncode, 2, p.stdout + p.stderr) - self.assertIn("--rigs would overwrite the carve manifest", p.stderr) - - # Refuse to overwrite carved input file via out - p = subprocess.run([sys.executable, "-I", TOOL, carve, bin_file, "--quiet"], - capture_output=True, text=True, errors="replace") - self.assertEqual(p.returncode, 2, p.stdout + p.stderr) - self.assertIn("output would overwrite an input file", p.stderr) - - # Refuse to overwrite carved input file via --rigs - p = subprocess.run([sys.executable, "-I", TOOL, carve, out_csv, "--rigs", bin_file, "--quiet"], - capture_output=True, text=True, errors="replace") - self.assertEqual(p.returncode, 2, p.stdout + p.stderr) - self.assertIn("--rigs would overwrite an input file", p.stderr) - - def test_directory(self): - folder = os.path.join(self.root, "carved") - os.makedirs(folder) - for i, payload in enumerate((move(), page(), names())): - with open(os.path.join(folder, f"{0x1000 + i * 0x100:012x}.bin"), "wb") as f: - f.write(payload) - rows, summary = anim_index.scan_dir(folder) - self.assertEqual([r["offset"] for r in rows], [0x1000, 0x1100, 0x1200]) - self.assertEqual([r["signature"] for r in rows], ["move", "page-directory", "name-table"]) - self.assertEqual(summary["mode"], "directory") - - def test_directory_classifies_each_payload_before_opening_the_next(self): - folder = os.path.join(self.root, "streamed") - os.mkdir(folder) - payloads = (move(), page(), names()) - for name, payload in zip(("00001000.bin", "a.bin", "b.bin"), payloads): - with open(os.path.join(folder, name), "wb") as f: - f.write(payload) - - classify = mock.Mock(wraps=anim_index.classify) - reads = [] - - def tracked_open(path, mode): - self.assertEqual(classify.call_count, len(reads)) - reads.append(os.path.basename(path)) - return open(path, mode) - - with mock.patch.object(anim_index, "classify", classify), \ - mock.patch.object(anim_index, "open", tracked_open, create=True): - rows, summary = anim_index.scan_dir(folder) - self.assertEqual(reads, ["00001000.bin", "a.bin", "b.bin"]) - self.assertEqual([row["offset"] for row in rows], [0x1000, 1, 2]) - self.assertEqual(summary["span"], sum(map(len, payloads))) - - def test_directory_rejects_start_and_limit(self): - folder = os.path.join(self.root, "carved") - os.makedirs(folder) - for offset in (0x100, 0x200): - with open(os.path.join(folder, f"{offset:012x}.bin"), "wb") as f: - f.write(b"A" * 64) - cases = [("--start", "0"), ("--limit", "1"), ("--limit", "1", "--start", "0x200")] - for i, flags in enumerate(cases): - with self.subTest(flags=flags): - out = os.path.join(self.root, f"bad{i}.json") - p = subprocess.run([sys.executable, "-I", TOOL, folder, out, "--quiet", *flags], - capture_output=True, text=True, errors="replace") - self.assertEqual(p.returncode, 2, p.stdout + p.stderr) - self.assertEqual(len(p.stderr.splitlines()), 1, p.stderr) - for flag in flags[::2]: - self.assertIn(flag, p.stderr) - self.assertFalse(os.path.exists(out)) - - def test_directory_skips_the_carvers_index_and_reports(self): - """rpf9_carve.py writes index.json next to the streams; it and a report are not payloads.""" - folder = os.path.join(self.root, "carved") - os.makedirs(folder) - for i, payload in enumerate((move(), page(), names())): - with open(os.path.join(folder, f"{0x1000 + i * 0x100:012x}.bin"), "wb") as f: - f.write(payload) - with open(os.path.join(folder, "index.json"), "w", encoding="utf-8") as f: - f.write('[{"off": 4096, "stored": 16}]') - with open(os.path.join(folder, "report.csv"), "w", encoding="utf-8") as f: - f.write("offset,size\n") - rows, summary = anim_index.scan_dir(folder) - self.assertEqual([r["offset"] for r in rows], [0x1000, 0x1100, 0x1200]) - - def test_scan_rpf_closes_mmap_on_invalid_start(self): - with tracked_mmaps() as created: - with self.assertRaisesRegex(ValueError, "outside the archive"): - anim_index.scan_rpf(self.rpf, start=os.path.getsize(self.rpf) + 1) - self.assertEqual(len(created), 1) - self.assertTrue(created[0].closed) - os.remove(self.rpf) - self.assertFalse(os.path.exists(self.rpf)) - - -class RigArchiveTest(unittest.TestCase): - def setUp(self): - self.tmp = tempfile.TemporaryDirectory() - self.root = self.tmp.name - self.rpf = os.path.join(self.root, "rigs.rpf") - # A real continuation follows a full 64 KiB stream: pad the rig table (parse_rbf0 ignores the tail) - # and cut it there. - blob = rbf0_blob() - blob += bytes(CHUNK + 4096 - len(blob)) - self.parts = [blob[:CHUNK], blob[CHUNK:]] - self.skel = b"SKEL_Synthetic\x00SKEL_Second\x00" - self.skel += bytes(64 - len(self.skel)) - self.front = b"\x0f\x00\xe0\x00\x0c\x00\x16\x00SKEL_Front\x00" - self.front += struct.pack(" None: - source = "src@one" - first, second = RIGS[source].items() - shared = {"anim/rig/x/shared": [(KIND_A, [10])]} - write_rpf(self.rpf, [ - rig_dictionary(source, dict([first]) | shared), - rig_dictionary(source, dict([second]) | shared), - rig_dictionary("src@two", RIGS["src@two"]), - ]) - dicts, _ = anim_rigs.scan(self.rpf) - self.assertEqual([d["name"] for d in dicts], [source, source, "src@two"]) - - for dictionaries in (dicts, dicts[::-1]): - joined = anim_rigs.join_rbf0(dictionaries, RIGSETS) - self.assertEqual(joined["resolved"], 3) - self.assertEqual(joined["keys_named_by_an_entry"], 3) - self.assertEqual(joined["key_missing"], 1) - self.assertEqual(joined["keys"], 5) - - def test_bad_block_is_reported_not_raised(self): - page = bytearray(rig_dictionary("src@bad", {"anim/rig/b": [(KIND_A, [1])]})) - at = page.rfind(b"RIG\x02") - page[at:at + 3] = b"XYZ" - rpf = os.path.join(self.tmp.name, "bad.rpf") - write_rpf(rpf, [bytes(page)]) - dicts, summary = anim_rigs.scan(rpf) - self.assertEqual(summary["counts"]["rig_dictionaries_unparsed"], 1) - self.assertIn("no RIG block", dicts[0]["error"]) - - def test_truncated_rig_header_is_reported_not_raised(self): - p = Page() - pm = p.alloc(bytes(16)) - p.b[pm + 8], p.b[pm + 9] = 1, 0 - p.ptr(8, pm) - p.string(0x38, "src@trunc") - struct.pack_into("") - second.write_bytes(b"") - ready, done = threading.Event(), threading.Event() - got = {} - - def fake_names(argv): - mount = Path(argv[argv.index("--mount") + 1]) - Path(argv[argv.index("--out") + 1]).write_text( - "source,offset,size,path,confidence,width,height,frames\n" - f"movies.rpf,4096,10,Stinger/{mount.stem}.bk2,anchored,3840,2160,450\n", - encoding="utf-8", newline="\n") - if mount == first: # hold the first lookup between writing its report and reading it - ready.set() - done.wait(10) - return 0 - - def look_up(mount): - try: - got[mount.stem] = bink_play.load_names(archive, mount)[0][0] - except SystemExit as e: - got[mount.stem] = str(e) - - with mock.patch.object(bink_play, "cache_path", return_value=d / "cache" / "bink_names.csv"), \ - mock.patch.object(bink_play.bink_names, "main", side_effect=fake_names): - worker = threading.Thread(target=look_up, args=(first,)) - worker.start() - self.assertTrue(ready.wait(10)) - try: - look_up(second) - finally: - done.set() - worker.join() - self.assertEqual(got, {"first": "Stinger/first.bk2", "second": "Stinger/second.bk2"}) - self.assertEqual(sorted(p.name for p in (d / "cache").iterdir()), ["bink_names.csv"]) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/test_boot_trace.py b/tests/test_boot_trace.py deleted file mode 100644 index e68f162f8..000000000 --- a/tests/test_boot_trace.py +++ /dev/null @@ -1,596 +0,0 @@ -"""Unit tests for tools/boot_trace.py on synthetic traces (no game data, no Windows, no GPU).""" - -import contextlib -import io -import json -import os -import sys -import tempfile -import unittest - -HERE = os.path.dirname(os.path.abspath(__file__)) -ROOT = os.path.dirname(HERE) -sys.path.insert(0, os.path.join(ROOT, "tools")) - -import boot_trace as bt - -STARTUP = [ - {"seq": 1, "t": 0.0, "kind": "trace_open", "pid": 123}, - { - "seq": 2, - "kind": "map", - "module": "game.exe", - "base": "0x140000000", - "size": "0x1000", - "relocated": False, - }, - { - "seq": 3, - "kind": "map", - "module": "x.dll", - "base": "0x180000000", - "size": "0x2000", - "relocated": True, - }, - { - "seq": 4, - "kind": "tls_callback", - "module": "x.dll", - "at": "x.dll+0x10", - "reason": 1, - }, - {"seq": 5, "kind": "dllmain", "module": "x.dll", "result": 1}, - {"seq": 6, "kind": "dllmain", "module": "y.dll", "result": 0}, - { - "seq": 7, - "kind": "unimplemented_call", - "import": "x.dll!Foo", - "caller": "game.exe+0x10", - }, - { - "seq": 8, - "kind": "unimplemented_call", - "import": "x.dll!Foo", - "caller": "game.exe+0x20", - }, - { - "seq": 9, - "kind": "unimplemented_call", - "import": "y.dll!Bar", - "caller": "game.exe+0x30", - }, - {"seq": 10, "kind": "debug_string", "text": "secret game text"}, - { - "seq": 11, - "kind": "exception", - "code": "0xc0000005", - "at": "game.exe+0x40", - "access": "read", - "address": "0x0", - "stack": ["game.exe+0x40", "game.exe+0x120"], - }, - { - "seq": 12, - "kind": "exception", - "code": "0xe06d7363", - "at": "game.exe+0x30", - "cpp": True, - }, - {"seq": 13, "kind": "future_event", "detail": "a kind this version does not know"}, - {"seq": 14, "kind": "exit", "code": 0}, -] - -D3D12 = [ - "[rt] ordinary diagnostic", - "[d3d12-trace] #1 D3D12XboxCreateDevice ok", - "[d3d12-trace] #2 CreateCommandQueue failed", - "[d3d12-trace] #3 Foo unsupported", - "[d3d12-trace] #4 D3D12XboxCreateDevice ok", - "[d3d12-trace] #5 SetMarker/BeginEvent with unknown metadata unsupported", - "[d3d12-trace] #6 MapTiles refused", - "[d3d12-trace] #7 CreateRootSignature called", - "[d3d12-trace] #8 SetMarker ignored", - "d3d12_test.exe : [d3d12-trace] #9 ID3D12CommandQueue::ExecuteCommandLists called", -] - - -class BootTraceTests(unittest.TestCase): - def setUp(self): - self.tmp = tempfile.TemporaryDirectory() - self.startup = os.path.join(self.tmp.name, "boot.jsonl") - self.d3d12 = os.path.join(self.tmp.name, "d3d12.log") - - def tearDown(self): - self.tmp.cleanup() - - def write(self, path, events, newline="\n"): - with open(path, "w", encoding="utf-8", newline="") as f: - f.writelines(json.dumps(event) + newline for event in events) - - def write_lines(self, path, lines): - with open(path, "w", encoding="utf-8") as f: - f.write("\n".join(lines) + "\n") - - def test_startup_summary(self): - self.write(self.startup, STARTUP) - trace = bt.parse_startup(self.startup) - self.assertEqual(trace["pid"], 123) - self.assertEqual(trace["events"], len(STARTUP)) - self.assertEqual(trace["bad_lines"], 0) - self.assertEqual(trace["kinds"]["map"], 2) - self.assertEqual(trace["kinds"]["future_event"], 1) - self.assertEqual([m["module"] for m in trace["modules"]], ["game.exe", "x.dll"]) - self.assertEqual(trace["tls_callbacks"], 1) - self.assertEqual( - trace["dllmain"], {"ok": 1, "failed": 1, "failed_modules": ["y.dll"]} - ) - self.assertEqual( - [u["import"] for u in trace["unimplemented"]], ["x.dll!Foo", "y.dll!Bar"] - ) - self.assertEqual(trace["unimplemented"][0]["caller"], "game.exe+0x10") - self.assertEqual(trace["unimplemented_by_dll"], {"x.dll": 1, "y.dll": 1}) - self.assertEqual(trace["debug_strings"], 1) - self.assertEqual(trace["exception_count"], 2) - self.assertEqual( - trace["exceptions"][0]["stack"], ["game.exe+0x40", "game.exe+0x120"] - ) - self.assertIs(trace["exceptions"][1]["cpp"], True) - self.assertEqual(trace["exit"], 0) - - def test_unimplemented_calls_rank_by_frequency_and_preserve_first_caller(self): - names = ("x.dll!Foo", "y.dll!Bar", "y.dll!Bar", "y.dll!Bar") - self.write(self.startup, [ - {"kind": "unimplemented_call", "import": name, "caller": f"synthetic+{i}"} - for i, name in enumerate(names) - ]) - trace = bt.parse_startup(self.startup, limit=1) - self.assertEqual(trace["unimplemented_call_counts"], {"x.dll!Foo": 1, "y.dll!Bar": 3}) - self.assertEqual(trace["unimplemented_by_dll"], {"x.dll": 1, "y.dll": 1}) - report = bt.format_text(bt.summarize(trace, None), 1) - self.assertIn("unimplemented: 2 unique, 4 calls", report) - self.assertIn("y.dll!Bar from synthetic+1 (3 calls)", report) - self.assertNotIn("x.dll!Foo from", report) - - def test_exception_limit_keeps_final_observation(self): - early = [ - {"kind": "exception", "code": "0xe06d7363", "at": f"synthetic.exe+0x{0x1100 + i:x}", "cpp": True} - for i in range(10) - ] - final = { - "kind": "exception", - "code": "0xc0000005", - "at": "synthetic.exe+0x2010", - "access": "read", - "address": "0x0", - "stack": ["synthetic.exe+0x2010", "synthetic.exe+0x1000"], - } - for limit, preceding in ((1, early), (10, early), (10, early[:-1])): - with self.subTest(limit=limit, count=len(preceding) + 1): - self.write(self.startup, [STARTUP[0], *preceding, final]) - output = io.StringIO() - with contextlib.redirect_stdout(output): - self.assertEqual(bt.main([self.startup, "--limit", str(limit), "--json"]), 0) - summary = json.loads(output.getvalue()) - startup = summary["startup"] - self.assertEqual(startup["exception_count"], len(preceding) + 1) - self.assertEqual( - [exc["at"] for exc in startup["exceptions"]], - [exc["at"] for exc in preceding[:limit - 1]] + [final["at"]], - ) - self.assertEqual(startup["exceptions"][-1]["stack"], final["stack"]) - self.assertIn("synthetic.exe+0x2010 (read 0x0)", bt.format_text(summary, limit)) - - def test_debug_text_is_not_printed(self): - self.write(self.startup, STARTUP) - text = bt.format_text(bt.summarize(bt.parse_startup(self.startup), None), 10) - self.assertIn("debug strings: 1", text) - self.assertNotIn("secret game text", text) - - def test_truncated_line_is_counted_not_fatal(self): - self.write(self.startup, STARTUP) - with open(self.startup, "a", encoding="utf-8") as f: - f.write('{"seq": 15, "kind":') - trace = bt.parse_startup(self.startup) - self.assertEqual(trace["events"], len(STARTUP)) - self.assertEqual(trace["bad_lines"], 1) - self.assertEqual(trace["bad_line_numbers"], [len(STARTUP) + 1]) - - def test_crlf_and_non_object_lines_are_counted(self): - self.write( - self.startup, - [ - {"seq": 1, "kind": "trace_open", "pid": 7}, - {"seq": 2, "kind": "exit", "code": 0}, - ], - newline="\r\n", - ) - with open(self.startup, "a", encoding="utf-8") as f: - f.write("null\n") - trace = bt.parse_startup(self.startup) - self.assertEqual(trace["events"], 2) - self.assertEqual(trace["bad_lines"], 1) - - def test_malformed_exit_records_preserve_the_last_valid_code(self): - for code in (0, -7): - with self.subTest(code=code): - self.write(self.startup, [ - {"kind": "trace_open", "pid": 123}, - {"kind": "exit", "code": code}, - {"kind": "exit"}, - {"kind": "exit", "code": "0"}, - {"kind": "exit", "code": True}, - {"kind": "exit", "code": None}, - {"kind": "exit", "code": 0.0}, - {"kind": "debug_string", "text": "synthetic"}, - ]) - trace = bt.parse_startup(self.startup) - self.assertEqual(trace["bad_lines"], 5) - self.assertEqual(trace["bad_line_numbers"], [3, 4, 5, 6, 7]) - self.assertEqual(trace["events"], 3) - self.assertEqual(trace["kinds"]["exit"], 1) - self.assertIs(type(trace["exit"]), int) - self.assertEqual(trace["exit"], code) - self.assertEqual(trace["debug_strings"], 1) - - def test_d3d12_summary(self): - self.write_lines(self.d3d12, D3D12) - trace = bt.parse_d3d12(self.d3d12) - self.assertEqual(trace["calls"], 9) - self.assertEqual(trace["ignored_lines"], 1) - self.assertEqual( - trace["outcomes"], - { - "ok": 2, - "failed": 1, - "unsupported": 2, - "refused": 1, - "called": 2, - "ignored": 1, - }, - ) - self.assertEqual( - trace["methods"], - [ - "D3D12XboxCreateDevice", - "CreateCommandQueue", - "Foo", - "SetMarker/BeginEvent with unknown metadata", - "MapTiles", - "CreateRootSignature", - "SetMarker", - "ID3D12CommandQueue::ExecuteCommandLists", - ], - ) - self.assertEqual( - trace["first"]["D3D12XboxCreateDevice"], {"seq": 1, "outcome": "ok"} - ) - self.assertEqual( - trace["first"]["ID3D12CommandQueue::ExecuteCommandLists"], - {"seq": 9, "outcome": "called"}, - ) - self.assertEqual(trace["failed"], [{"seq": 2, "method": "CreateCommandQueue"}]) - self.assertEqual( - trace["unsupported"], - [ - {"seq": 3, "method": "Foo"}, - {"seq": 5, "method": "SetMarker/BeginEvent with unknown metadata"}, - ], - ) - self.assertEqual(trace["refused"], [{"seq": 6, "method": "MapTiles"}]) - self.assertEqual(trace["last_seq"], 9) - self.assertEqual(trace["sequence_break_count"], 0) - self.assertEqual(trace["sequence_breaks"], []) - - def test_repeated_method_failures_are_counted_beyond_the_sample_limit(self): - self.write_lines(self.d3d12, [ - "[d3d12-trace] #1 CreatePipelineState ok", - "[d3d12-trace] #2 CreatePipelineState failed", - "[d3d12-trace] #3 CreatePipelineState failed", - "[d3d12-trace] #4 ExecuteCommandLists partial", - ]) - trace = bt.parse_d3d12(self.d3d12, limit=1) - self.assertEqual(trace["method_outcomes"], { - "CreatePipelineState": {"ok": 1, "failed": 2}, - "ExecuteCommandLists": {"partial": 1}, - }) - self.assertEqual(len(trace["failed"]), 1) - self.assertIn("CreatePipelineState: failed 2", bt.format_text({"startup": None, "d3d12": trace}, 1)) - - def test_sequence_breaks_count_boundaries_and_limit_examples(self): - self.write_lines(self.d3d12, [ - "[d3d12-trace] #4 Foo called", - "[rt] ordinary diagnostic", - "[d3d12-trace] #5 Foo called", - "[d3d12-trace] #12 Foo called", - "[d3d12-trace] #1 Foo called", - "[d3d12-trace] #1 Foo failed", - "[d3d12-trace] #2 Foo called", - ]) - examples = [ - {"expected": 1, "observed": 4}, - {"expected": 6, "observed": 12}, - {"expected": 13, "observed": 1}, - {"expected": 2, "observed": 1}, - ] - for limit in (2, 4): - with self.subTest(limit=limit): - output = io.StringIO() - with contextlib.redirect_stdout(output): - self.assertEqual(bt.main(["--d3d12", self.d3d12, "--json", "--limit", str(limit)]), 0) - summary = json.loads(output.getvalue()) - trace = summary["d3d12"] - self.assertEqual(trace["sequence_break_count"], 4) - self.assertEqual(trace["sequence_breaks"], examples[:limit]) - self.assertEqual(trace["calls"], 6) - self.assertEqual(trace["outcomes"], {"called": 5, "failed": 1}) - self.assertEqual(trace["last_seq"], 2) - self.assertEqual(trace["ignored_lines"], 1) - text = bt.format_text(summary, limit) - self.assertIn("sequence breaks: 4", text) - self.assertIn("expected #6, observed #12", text) - self.assertEqual(text.count("observed #"), limit) - - def test_powershell_error_record_prefix_keeps_the_first_call(self): - self.write_lines( - self.d3d12, - [ - "d3d12_test.exe : [d3d12-trace] #1 ID3D12GraphicsCommandList::SetPipelineState called", - "At line:1 char:1", - "+ & '.\\d3d12_test.exe' --trace-d3d12 2> log", - ], - ) - trace = bt.parse_d3d12(self.d3d12) - self.assertEqual(trace["calls"], 1) - self.assertEqual( - trace["first"]["ID3D12GraphicsCommandList::SetPipelineState"], - {"seq": 1, "outcome": "called"}, - ) - - def test_d3d12_text_report_names_refused_and_spaced_methods(self): - self.write_lines(self.d3d12, D3D12) - text = bt.format_text(bt.summarize(None, bt.parse_d3d12(self.d3d12)), 10) - self.assertIn("refused: #6 MapTiles", text) - self.assertIn("#5 SetMarker/BeginEvent with unknown metadata", text) - self.assertIn("ID3D12CommandQueue::ExecuteCommandLists", text) - self.assertIn("[rt] diagnostics are not summarized", text) - self.assertNotIn("sequence breaks", text) - - def test_partial_submissions_are_named_in_text_and_json(self): - method = "ID3D12CommandQueue::ExecuteCommandLists" - self.write_lines(self.d3d12, [ - f"[d3d12-trace] #1 {method} ok", - f"[d3d12-trace] #2 {method} partial", - f"[d3d12-trace] #3 {method} partial", - ]) - trace = bt.parse_d3d12(self.d3d12, limit=1) - self.assertEqual(trace["first"][method], {"seq": 1, "outcome": "ok"}) - self.assertEqual(trace["outcomes"]["partial"], 2) - text = bt.format_text(bt.summarize(None, trace), 1) - self.assertIn(f" partial: #2 {method}", text.splitlines()) - self.assertNotIn(f" partial: #3 {method}", text.splitlines()) - - stdout = io.StringIO() - with contextlib.redirect_stdout(stdout): - self.assertEqual(bt.main(["--d3d12", self.d3d12, "--limit", "1", "--json"]), 0) - parsed = json.loads(stdout.getvalue())["d3d12"] - self.assertEqual(parsed["partial"], [{"seq": 2, "method": method}]) - self.assertEqual(parsed["outcomes"]["partial"], 2) - - def test_json_cli(self): - self.write(self.startup, STARTUP) - self.write_lines(self.d3d12, D3D12) - out = io.StringIO() - with contextlib.redirect_stdout(out): - self.assertEqual( - bt.main([self.startup, "--d3d12", self.d3d12, "--json"]), 0 - ) - data = json.loads(out.getvalue()) - self.assertEqual(data["startup"]["pid"], 123) - self.assertEqual(data["d3d12"]["calls"], 9) - - def test_counts_only_json_omits_raw_trace_fields(self): - self.write(self.startup, [ - {"kind": "exception", "code": "private-code", "address": "private-address", - "stack": ["private-stack"]}, - {"kind": "file_open_failed", "path": "private-file", "caller": "private-caller"}, - {"kind": "error", "what": "private-message"}, - {"kind": "private-kind"}, - ]) - self.write_lines(self.d3d12, [ - "[d3d12-trace] #1 private-method failed", - "[d3d12-trace] #2 private-method private-outcome", - ]) - out = io.StringIO() - with contextlib.redirect_stdout(out): - self.assertEqual(bt.main([self.startup, "--d3d12", self.d3d12, "--counts-only"]), 0) - text = out.getvalue() - self.assertNotIn("private-", text) - self.assertNotIn("boot.jsonl", text) - self.assertNotIn("d3d12.log", text) - data = json.loads(text) - self.assertEqual(data["startup"]["exception_count"], 1) - self.assertEqual(data["startup"]["events"], 4) - self.assertEqual(data["d3d12"]["outcomes"], {"failed": 1, "other": 1}) - self.assertEqual(data["d3d12"]["calls"], 2) - - def test_counts_only_redacts_missing_input_paths_from_stderr(self): - err = io.StringIO() - with contextlib.redirect_stderr(err): - self.assertEqual(bt.main([self.startup, "--counts-only"]), 2) - self.assertIn("startup trace unavailable", err.getvalue()) - self.assertNotIn("boot.jsonl", err.getvalue()) - - def test_missing_and_empty_files_are_errors(self): - err = io.StringIO() - with contextlib.redirect_stderr(err): - self.assertEqual(bt.main([os.path.join(self.tmp.name, "missing.jsonl")]), 2) - open(self.startup, "w").close() - self.assertEqual(bt.main([self.startup]), 2) - self.assertEqual(bt.main(["--limit", "0", self.startup]), 2) - self.assertIn("cannot read", err.getvalue()) - - def test_attach_failure_is_reported_before_any_d3d12_call(self): - self.write(self.startup, [{"kind": "error", "what": "guest.dll: DllMain returned FALSE"}]) - self.write_lines(self.d3d12, ["error: guest.dll: DllMain returned FALSE"]) - out, err = io.StringIO(), io.StringIO() - with contextlib.redirect_stdout(out), contextlib.redirect_stderr(err): - self.assertEqual(bt.main([self.startup, "--d3d12", self.d3d12]), 2) - self.assertIn("error: guest.dll: DllMain returned FALSE", out.getvalue()) - self.assertIn("no [d3d12-trace] line", err.getvalue()) - - def test_missing_startup_preserves_d3d12_json(self): - self.write_lines(self.d3d12, ["[d3d12-trace] #1 CreateCommandQueue failed"]) - out, err = io.StringIO(), io.StringIO() - with contextlib.redirect_stdout(out), contextlib.redirect_stderr(err): - self.assertEqual(bt.main([self.startup, "--d3d12", self.d3d12, "--json"]), 2) - self.assertIn("cannot read", err.getvalue()) - self.assertEqual(json.loads(out.getvalue()), bt.summarize(None, bt.parse_d3d12(self.d3d12))) - - def test_no_report_when_neither_input_can_be_read(self): - out, err = io.StringIO(), io.StringIO() - with contextlib.redirect_stdout(out), contextlib.redirect_stderr(err): - self.assertEqual(bt.main([self.startup, "--d3d12", self.d3d12, "--json"]), 2) - self.assertEqual(out.getvalue(), "") - self.assertIn(self.startup, err.getvalue()) - self.assertIn(self.d3d12, err.getvalue()) - - def test_last_recorded_d3d12_call_can_repeat_an_earlier_method(self): - self.write_lines(self.d3d12, [ - "[d3d12-trace] #1 CreateCommandAllocator ok", - "[d3d12-trace] #2 CreateCommittedResource failed", - "[d3d12-trace] #3 CreateCommandAllocator ok", - "[rt] a runtime diagnostic after the last call", - "[d3d12-trace] #4", - ]) - trace = bt.parse_d3d12(self.d3d12, limit=1) - self.assertEqual(trace["ignored_lines"], 2) - self.assertEqual(trace["first"]["CreateCommandAllocator"], {"seq": 1, "outcome": "ok"}) - self.assertEqual(trace["failed"], [{"seq": 2, "method": "CreateCommittedResource"}]) - - output = io.StringIO() - with contextlib.redirect_stdout(output): - self.assertEqual(bt.main(["--d3d12", self.d3d12, "--limit", "1", "--json"]), 0) - parsed = json.loads(output.getvalue())["d3d12"] - self.assertEqual(parsed["last_seq"], 3) - self.assertEqual(parsed["last_call"], {"seq": 3, "method": "CreateCommandAllocator", "outcome": "ok"}) - text = bt.format_text(bt.summarize(None, trace), 1) - self.assertIn(" last recorded call: #3 CreateCommandAllocator ok", text.splitlines()) - - def test_unterminated_d3d12_outcome_must_be_complete(self): - first = b"[d3d12-trace] #1 CreateCommandAllocator ok\n" - second = b"[d3d12-trace] #2 CreateCommittedResource " - for ending, seq, ignored, outcomes in ( - (b"fai", 1, 1, {"ok": 1}), - (b"failed", 2, 0, {"ok": 1, "failed": 1}), - (b"ignored", 2, 0, {"ok": 1, "ignored": 1}), - (b"future-result\n", 2, 0, {"ok": 1, "future-result": 1}), - ): - with self.subTest(ending=ending): - with open(self.d3d12, "wb") as fh: - fh.write(first + second + ending) - trace = bt.parse_d3d12(self.d3d12) - self.assertEqual(trace["last_call"]["seq"], seq) - self.assertEqual(trace["last_call"]["outcome"], next(reversed(outcomes))) - self.assertEqual(trace["last_seq"], seq) - self.assertEqual(trace["calls"], seq) - self.assertEqual(trace["outcomes"], outcomes) - self.assertEqual(trace["ignored_lines"], ignored) - self.assertEqual(trace["sequence_break_count"], 0) - - def test_d3d12_log_without_trace_lines_is_an_error(self): - self.write_lines(self.d3d12, ["[rt] one", "[rt] two"]) - err = io.StringIO() - with contextlib.redirect_stderr(err): - self.assertEqual(bt.main(["--d3d12", self.d3d12]), 2) - self.assertIn("no [d3d12-trace] line", err.getvalue()) - - def test_utf16_logs_keep_both_wrapped_and_unwrapped_calls(self): - lines = ("synthetic.exe : [d3d12-trace] #1 First called\r\n" - "[d3d12-trace] #2 Second ok\r\n") - for encoding, bom in (("utf-16-le", b"\xff\xfe"), ("utf-16-be", b"\xfe\xff")): - with self.subTest(encoding=encoding): - with open(self.d3d12, "wb") as f: - f.write(bom + lines.encode(encoding)) - output = io.StringIO() - errors = io.StringIO() - with contextlib.redirect_stdout(output), contextlib.redirect_stderr(errors): - result = bt.main(["--d3d12", self.d3d12, "--json"]) - self.assertEqual(result, 0, errors.getvalue()) - trace = json.loads(output.getvalue())["d3d12"] - self.assertEqual(trace["calls"], 2) - self.assertEqual(trace["methods"], ["First", "Second"]) - - def test_utf8_bom_is_stripped(self): - with open(self.d3d12, "wb") as f: - f.write(b"\xef\xbb\xbf" + b"[d3d12-trace] #1 Foo ok\n") - trace = bt.parse_d3d12(self.d3d12) - self.assertEqual(trace["calls"], 1) - self.assertEqual(trace["methods"], ["Foo"]) - - def test_text_report_has_the_triage_units(self): - self.write(self.startup, STARTUP) - text = bt.format_text(bt.summarize(bt.parse_startup(self.startup), None), 10) - for needle in ( - "pid 123", - "modules (2)", - "dllmain: 1 ok, 1 failed", - "unimplemented: 2 unique", - "x.dll!Foo from game.exe+0x10", - "by dll (unique imports): x.dll 1, y.dll 1", - "exceptions: 2", - "code 0xc0000005 at game.exe+0x40 (read 0x0)", - "code 0xe06d7363 at game.exe+0x30 (C++ throw)", - "stack: game.exe+0x40, game.exe+0x120", - "exit: 0", - ): - self.assertIn(needle, text) - - def test_failed_file_opens_and_skipped_int3_are_listed(self): - self.write( - self.startup, - [ - {"seq": 1, "kind": "trace_open", "pid": 1}, - {"seq": 2, "kind": "file_open_failed", "api": "CreateFileW", "path": "GAME:/probe/missing.bin", "error": 2, "caller": "game.exe+0x20"}, - {"seq": 3, "kind": "int3_skipped", "at": "game.exe+0x1330"}, - ], - ) - trace = bt.parse_startup(self.startup) - self.assertEqual(trace["file_open_failed"], [{"path": "GAME:/probe/missing.bin", "error": 2, "caller": "game.exe+0x20"}]) - self.assertEqual(trace["int3_skipped"], ["game.exe+0x1330"]) - text = bt.format_text(bt.summarize(trace, None), 10) - self.assertIn("failed file opens: 1", text) - self.assertIn("GAME:/probe/missing.bin error 2 from game.exe+0x20", text) - self.assertIn("game.exe+0x1330", text) - - def test_last_observed_tls_callback_in_incomplete_startup(self): - first = {"kind": "tls_callback", "module": "first.dll", "at": "first.dll+0x1100", "reason": 1} - for fields, reason, phase in ( - ({"reason": 1}, 1, "process attach"), - ({"reason": 0}, 0, "process detach"), - ({}, None, "phase unknown"), - ): - with self.subTest(phase=phase): - last = {"kind": "tls_callback", "module": "fixture.exe", "at": "fixture.exe+0x2200", **fields} - self.write(self.startup, [STARTUP[0], first, last]) - with open(self.startup, "a", encoding="utf-8", newline="\n") as f: - f.write('{"kind":"tls_callback","at":"truncated') - - output = io.StringIO() - with contextlib.redirect_stdout(output): - self.assertEqual(bt.main([self.startup, "--json"]), 0) - summary = json.loads(output.getvalue()) - startup = summary["startup"] - self.assertEqual(startup["tls_callbacks"], 2) - self.assertEqual(startup["bad_lines"], 1) - self.assertIsNone(startup["exit"]) - self.assertEqual( - startup["last_tls_callback"], - {"module": "fixture.exe", "at": "fixture.exe+0x2200", "reason": reason}, - ) - text = bt.format_text(summary, 10) - self.assertIn("tls callbacks: 2", text) - self.assertIn(f"last observed TLS callback: fixture.exe+0x2200 ({phase})", text) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/test_buffer_bounds_probe.py b/tests/test_buffer_bounds_probe.py deleted file mode 100644 index 2da9db0c2..000000000 --- a/tests/test_buffer_bounds_probe.py +++ /dev/null @@ -1,63 +0,0 @@ -"""CPU-only unit tests for tools/buffer_bounds_probe.py (SHADER-341).""" -import os -import subprocess -import sys -import tempfile -import unittest - -REPO = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) -PROBE = os.path.join(REPO, "tools", "buffer_bounds_probe.py") - - -class BufferBoundsProbeTests(unittest.TestCase): - def test_self_test(self): - proc = subprocess.run([sys.executable, "-I", PROBE, "--self-test"], - capture_output=True, text=True, check=False) - self.assertEqual(proc.returncode, 0, proc.stderr or proc.stdout) - self.assertIn("self-test OK", proc.stdout) - - def test_non_gfx10_or_missing_oracle_exits_77(self): - env = {k: v for k, v in os.environ.items() - if not k.startswith("LEONIDA_HW_") and k != "LEONIDA_AMD_CLANG"} - env["LEONIDA_AMD_CLANG"] = os.path.join(REPO, "does_not_exist_clang") - proc = subprocess.run([sys.executable, "-I", PROBE], env=env, - capture_output=True, text=True, check=False) - self.assertEqual(proc.returncode, 77, proc.stderr or proc.stdout) - - def test_bad_waves(self): - proc = subprocess.run([sys.executable, "-I", PROBE, "--waves", "16"], - capture_output=True, text=True, check=False) - self.assertEqual(proc.returncode, 2, proc.stderr or proc.stdout) - - def test_json_folder_is_refused_before_the_gpu_run(self): - with tempfile.TemporaryDirectory() as folder: - proc = subprocess.run([sys.executable, "-I", PROBE, "--json", folder], - env=self.no_oracle_env(), capture_output=True, text=True, - check=False) - self.assertEqual(proc.returncode, 2, proc.stderr or proc.stdout) - self.assertIn("ERROR: --json", proc.stderr) - self.assertIn("is a directory", proc.stderr) - self.assertNotIn("Traceback", proc.stderr) - - def test_json_in_a_missing_folder_is_refused_before_the_gpu_run(self): - with tempfile.TemporaryDirectory() as folder: - target = os.path.join(folder, "missing", "report.json") - proc = subprocess.run([sys.executable, "-I", PROBE, "--json", target], - env=self.no_oracle_env(), capture_output=True, text=True, - check=False) - self.assertEqual(proc.returncode, 2, proc.stderr or proc.stdout) - self.assertIn("ERROR: --json", proc.stderr) - self.assertIn("does not exist", proc.stderr) - self.assertNotIn("Traceback", proc.stderr) - self.assertFalse(os.path.exists(target)) - - def no_oracle_env(self): - """An env with no hardware oracle, so a missing guard shows up as the 77 skip rather than a sweep.""" - env = {k: v for k, v in os.environ.items() - if not k.startswith("LEONIDA_HW_") and k != "LEONIDA_AMD_CLANG"} - env["LEONIDA_AMD_CLANG"] = os.path.join(REPO, "does_not_exist_clang") - return env - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/test_buffer_format_fuzz_cli.py b/tests/test_buffer_format_fuzz_cli.py deleted file mode 100644 index 3c92181b3..000000000 --- a/tests/test_buffer_format_fuzz_cli.py +++ /dev/null @@ -1,50 +0,0 @@ -"""CPU-only tests for tools/buffer_format_fuzz.py's command line: an explicit --formats is checked before the GPU. - - python -I tests/test_buffer_format_fuzz_cli.py - -A typo in --formats used to be found only after runner.open_oracle(), so a machine without the oracle answered -"hardware oracle unavailable" (77) and one with it raised SystemExit (1). It is a usage error (2) before the oracle. -""" -import importlib.util -import os -import subprocess -import sys -import unittest - -REPO = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) -TOOL = os.path.join(REPO, "tools", "buffer_format_fuzz.py") - - -def run(*args): - return subprocess.run([sys.executable, "-I", TOOL, *args], capture_output=True, text=True, check=False) - - -def load_tool(): - spec = importlib.util.spec_from_file_location("buffer_format_fuzz", TOOL) - module = importlib.util.module_from_spec(spec) - spec.loader.exec_module(module) - return module - - -class BufferFormatFuzzFormatsTests(unittest.TestCase): - def test_unknown_format_is_a_usage_error_before_the_oracle(self): - proc = run("--oracle", "hw", "--formats", "8_8_8_8_UNORM_typo") - self.assertEqual(proc.returncode, 2, proc.stdout + proc.stderr) - self.assertIn("unknown format '8_8_8_8_UNORM_typo'", proc.stderr) - self.assertNotIn("hardware oracle", proc.stdout + proc.stderr) - - def test_a_code_outside_the_table_is_refused_too(self): - proc = run("--oracle", "hw", "--formats", "0,8_8_8_8_UNORM") - self.assertEqual(proc.returncode, 2, proc.stdout + proc.stderr) - self.assertIn("unknown format '0'", proc.stderr) - - def test_known_names_and_codes_map_to_the_table(self): - tool = load_tool() - pairs = tool.select_formats("8_8_8_8_UNORM,56") - self.assertEqual([n for _, n in pairs], ["8_8_8_8_UNORM", tool.GFX10_NAMES[56]]) - with self.assertRaises(ValueError): - tool.select_formats("not_a_format") - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/test_buffer_format_fuzz_gfx11_skip.py b/tests/test_buffer_format_fuzz_gfx11_skip.py deleted file mode 100644 index c5cbdbda6..000000000 --- a/tests/test_buffer_format_fuzz_gfx11_skip.py +++ /dev/null @@ -1,130 +0,0 @@ -"""Tests for tools/buffer_format_fuzz.py GFX11-empty selection and oracle cleanup. - - python -I tests/test_buffer_format_fuzz_gfx11_skip.py - -Standard library only; stubs hw_oracle so no GPU or game files are required. -""" -import contextlib -import io -import os -import sys -import types -import unittest -from unittest.mock import patch - -REPO = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) -TOOLS = os.path.join(REPO, "tools") -sys.path.insert(0, TOOLS) - -import buffer_format_fuzz as bff # noqa: E402 - - -class FakeOracle: - def __init__(self, arch="gfx1150", device="Fake Radeon 880M", run_fn=None): - self.arch = arch - self.device = device - self.closed = 0 - self.run_calls = 0 - self._run_fn = run_fn - - def run(self, kernels, words=0): - self.run_calls += 1 - if self._run_fn is not None: - return self._run_fn(kernels, words) - return [] - - def close(self): - self.closed += 1 - - -def make_hw_oracle_pkg(oracle, family_fn): - pkg = types.ModuleType("hw_oracle") - runner_mod = types.ModuleType("hw_oracle.runner") - asm_mod = types.ModuleType("hw_oracle.asm") - - class Unavailable(Exception): - pass - - runner_mod.Unavailable = Unavailable - runner_mod.open_oracle = lambda arch=None: oracle - asm_mod.family = family_fn - pkg.runner = runner_mod - pkg.asm = asm_mod - return { - "hw_oracle": pkg, - "hw_oracle.runner": runner_mod, - "hw_oracle.asm": asm_mod, - } - - -def run_main(argv, oracle, family_fn): - mods = make_hw_oracle_pkg(oracle, family_fn) - buf = io.StringIO() - with patch.dict(sys.modules, mods): - with patch.object(sys, "argv", ["buffer_format_fuzz.py", *argv]): - with contextlib.redirect_stdout(buf): - rc = bff.main() - return rc, buf.getvalue() - - -class BufferFormatFuzzGfx11SkipTests(unittest.TestCase): - def test_gfx10_only_formats_on_gfx11_exit_77_and_close_oracle(self): - oracle = FakeOracle(arch="gfx1150") - rc, out = run_main(["--oracle", "hw", "--formats", "30,31"], oracle, lambda a: "gfx11") - self.assertEqual(rc, 77, out) - self.assertIn("GFX10-only", out) - self.assertEqual(oracle.run_calls, 0) - self.assertEqual(oracle.closed, 1) - - def test_mixed_formats_on_gfx11_run_supported_format_only(self): - oracle = FakeOracle(arch="gfx1150") - - def fake_run_loads(_oracle, _family, fmts, _path, _rng, _budget): - return {code: (1, [], 0) for code, _ in fmts} - - with patch.object(bff, "run_loads", side_effect=fake_run_loads) as mock_loads: - rc, out = run_main( - ["--oracle", "hw", "--formats", "30,8_8_8_8_UNORM", "--mode", "load", "--path", "mubuf", "--budget", "1"], - oracle, - lambda a: "gfx11", - ) - self.assertEqual(rc, 0, out) - self.assertEqual(mock_loads.call_count, 1) - passed_fmts = mock_loads.call_args[0][2] - self.assertEqual([n for _, n in passed_fmts], ["8_8_8_8_UNORM"]) - self.assertEqual(oracle.closed, 1) - - def test_negative_control_runs_even_with_gfx10_only_formats(self): - oracle = FakeOracle(arch="gfx1150") - with patch.object(bff, "negative_control", return_value=0) as mock_neg: - rc, out = run_main( - ["--oracle", "hw", "--formats", "30", "--negative-control"], - oracle, - lambda a: "gfx11", - ) - self.assertEqual(rc, 0, out) - self.assertEqual(mock_neg.call_count, 1) - self.assertEqual(oracle.closed, 1) - - def test_oracle_closed_when_family_lookup_raises(self): - oracle = FakeOracle(arch="unknown") - - def boom(_arch): - raise ValueError("unknown arch") - - mods = make_hw_oracle_pkg(oracle, boom) - with patch.dict(sys.modules, mods): - with patch.object(sys, "argv", ["buffer_format_fuzz.py", "--oracle", "hw", "--formats", "8_8_8_8_UNORM"]): - with self.assertRaises(ValueError): - bff.main() - self.assertEqual(oracle.closed, 1) - - def test_gfx12_exits_77_and_closes_oracle_once(self): - oracle = FakeOracle(arch="gfx1200") - rc, out = run_main(["--oracle", "hw", "--formats", "8_8_8_8_UNORM"], oracle, lambda a: "gfx12") - self.assertEqual(rc, 77, out) - self.assertEqual(oracle.closed, 1) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/test_buffer_store_probe.py b/tests/test_buffer_store_probe.py deleted file mode 100644 index b33195d24..000000000 --- a/tests/test_buffer_store_probe.py +++ /dev/null @@ -1,166 +0,0 @@ -"""CPU-only unit tests for tools/buffer_store_probe.py (SHADER-364).""" -import io -import json -import os -import subprocess -import sys -import tempfile -import unittest -import unittest.mock -from contextlib import redirect_stderr, redirect_stdout - -REPO = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) -TOOLS = os.path.join(REPO, "tools") -PROBE = os.path.join(TOOLS, "buffer_store_probe.py") - -sys.dont_write_bytecode = True -if TOOLS not in sys.path: - sys.path.insert(0, TOOLS) - -import buffer_store_probe as probe # noqa: E402 -from hw_oracle import asm as hw_asm, runner as hw_runner # noqa: E402 - - -class BufferStoreProbeTests(unittest.TestCase): - def test_self_test(self): - proc = subprocess.run([sys.executable, "-I", PROBE, "--self-test"], - capture_output=True, text=True, check=False) - self.assertEqual(proc.returncode, 0, proc.stderr or proc.stdout) - self.assertIn("self-test OK", proc.stdout) - - def test_non_gfx10_or_missing_oracle_exits_77(self): - env = {k: v for k, v in os.environ.items() - if not k.startswith("LEONIDA_HW_") and k != "LEONIDA_AMD_CLANG"} - env["LEONIDA_AMD_CLANG"] = os.path.join(REPO, "does_not_exist_clang") - proc = subprocess.run([sys.executable, "-I", PROBE], env=env, - capture_output=True, text=True, check=False) - self.assertEqual(proc.returncode, 77, proc.stderr or proc.stdout) - - def test_invalid_waves_rejected_before_open_oracle(self): - for bad in ("", " ", "abc", "32,foo", "16", "32,128"): - with self.subTest(waves=bad): - err = io.StringIO() - with unittest.mock.patch.object(hw_runner, "open_oracle", - side_effect=AssertionError("open_oracle called")), \ - redirect_stderr(err): - rc = probe.main(["--waves", bad]) - self.assertEqual(rc, 2) - self.assertIn("error:", err.getvalue()) - - def test_invalid_json_rejected_before_open_oracle(self): - with tempfile.TemporaryDirectory() as tmp: - file_ancestor = os.path.join(tmp, "not_a_dir") - with open(file_ancestor, "w", encoding="utf-8") as f: - f.write("x") - bad_paths = [ - "", - " ", - "bad\x00.json", - tmp, - os.path.join(tmp, "sub") + os.sep, - os.path.join(file_ancestor, "out.json"), - os.path.join(file_ancestor, "nested", "out.json"), - ] - for bad in bad_paths: - with self.subTest(json_path=bad): - err = io.StringIO() - with unittest.mock.patch.object(hw_runner, "open_oracle", - side_effect=AssertionError("open_oracle called")), \ - redirect_stderr(err): - rc = probe.main(["--json", bad]) - self.assertEqual(rc, 2) - self.assertIn("error:", err.getvalue()) - - def test_valid_nested_json_does_not_create_dirs_on_unavailable(self): - with tempfile.TemporaryDirectory() as tmp: - nested = os.path.join(tmp, "a", "b", "out.json") - err = io.StringIO() - with unittest.mock.patch.object(hw_runner, "open_oracle", - side_effect=hw_runner.Unavailable("no GPU")), \ - redirect_stderr(err): - rc = probe.main(["--json", nested]) - self.assertEqual(rc, 77) - self.assertFalse(os.path.exists(os.path.join(tmp, "a"))) - - def test_write_json_report_creates_dirs_and_uses_lf(self): - with tempfile.TemporaryDirectory() as tmp: - nested = os.path.join(tmp, "sub", "dir", "report.json") - err = probe.write_json_report(nested, {"arch": "gfx1035", "waves": {"32": {}}}) - self.assertIsNone(err) - with open(nested, "rb") as f: - raw = f.read() - self.assertNotIn(b"\r\n", raw) - self.assertEqual(json.loads(raw.decode("utf-8"))["arch"], "gfx1035") - - def test_write_json_oserror_returns_1_without_traceback(self): - fake_oracle = unittest.mock.MagicMock(arch="gfx1035") - fake_norm = {name: {"inst": {"exact": [0], "inputs": [0]}} for name, *_ in probe.NORM_FORMATS} - fake_norm["snorm2_ties"] = {"exact": [0], "inputs": [0]} - fake_two = {"formats_ok": 12, "formats_total": 12, "triples_ok": 216, "triples_total": 216} - with tempfile.TemporaryDirectory() as tmp: - out_path = os.path.join(tmp, "report.json") - out, err = io.StringIO(), io.StringIO() - with unittest.mock.patch.object(hw_runner, "open_oracle", return_value=fake_oracle), \ - unittest.mock.patch.object(hw_asm, "family", return_value="gfx10"), \ - unittest.mock.patch.object(probe, "probe_norm", return_value=fake_norm), \ - unittest.mock.patch.object(probe, "probe_two_comp", return_value=fake_two), \ - unittest.mock.patch("builtins.open", side_effect=OSError("disk full")), \ - redirect_stdout(out), redirect_stderr(err): - rc = probe.main(["--waves", "32", "--json", out_path]) - self.assertEqual(rc, 1) - self.assertIn("error:", err.getvalue()) - self.assertIn("disk full", err.getvalue()) - self.assertNotIn("Traceback", err.getvalue()) - - -class FakeNormOracle: - """Answers probe_norm's store kernels like a GFX10 GPU that follows the probe's exact model (model_norm), - except that the formats in `double_round` follow the double-rounding model (model_norm_double).""" - arch = "gfx1030" - - def __init__(self, double_round=()): - self.double_round = set(double_round) - - def run(self, programs, words=4): - out = [] - for k in programs: - code = (int(k.lines[4].split()[-1], 16) >> 12) & 0x7F - u = int(k.lines[5].split()[-1], 16) - if code == 45: - out.append([probe.model_norm(u, "snorm", 2), 0]) - continue - name, _code, kind, bits = next(f for f in probe.NORM_FORMATS if f[1] == code) - model = probe.model_norm_double if name in self.double_round else probe.model_norm - out.append([model(u, kind, bits), 0]) - return out - - -class SummaryLineTests(unittest.TestCase): - """The per-wave summary line reports the measured UNORM/SNORM results, not a fixed 'norm exact'.""" - TWO_OK = {"formats_total": 12, "formats_ok": 12, "format_mismatches": [], - "triples_total": 216, "triples_ok": 216, "triple_mismatches": []} - - def run_main(self, oracle): - out, err = io.StringIO(), io.StringIO() - with unittest.mock.patch.object(hw_runner, "open_oracle", return_value=oracle), unittest.mock.patch.object(hw_asm, "family", return_value="gfx10"), unittest.mock.patch.object(probe, "probe_two_comp", return_value=self.TWO_OK), redirect_stdout(out), redirect_stderr(err): - rc = probe.main(["--waves", "32"]) - return rc, out.getvalue(), err.getvalue() - - def test_exact_hardware_reports_every_sweep(self): - rc, out, err = self.run_main(FakeNormOracle()) - self.assertEqual(rc, 0, err) - self.assertIn("norm 10/10 sweeps exact across 5 formats, snorm2 ties 4/4", out) - - def test_double_rounding_format_is_reported(self): - rc, out, err = self.run_main(FakeNormOracle(double_round=("unorm16",))) - self.assertEqual(rc, 1, err) - self.assertNotIn("norm exact", out) - self.assertIn("norm 8/10 sweeps exact across 5 formats, snorm2 ties 4/4", out) - self.assertIn("unorm16 buffer_store_format_x:", out) - self.assertIn("exact, first mismatch f32 0x", out) - self.assertIn("unorm16 tbuffer_store_format_x:", out) - self.assertNotIn("unorm8 buffer_store_format_x:", out) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/test_buffer_swizzle_probe.py b/tests/test_buffer_swizzle_probe.py deleted file mode 100644 index e1c4a0e35..000000000 --- a/tests/test_buffer_swizzle_probe.py +++ /dev/null @@ -1,142 +0,0 @@ -"""Unit tests for tools/buffer_swizzle_probe.py (SHADER-343). Standard library only; no GPU or game files needed.""" -import io -import json -import os -import sys -import tempfile -import unittest -import unittest.mock -from contextlib import redirect_stderr, redirect_stdout -from pathlib import Path - -ROOT = Path(__file__).resolve().parents[1] -TOOLS = ROOT / "tools" -sys.dont_write_bytecode = True -if str(TOOLS) not in sys.path: - sys.path.insert(0, str(TOOLS)) - -import buffer_swizzle_probe as probe # noqa: E402 -from hw_oracle import runner as hw_runner # noqa: E402 - - -class BufferSwizzleProbeTests(unittest.TestCase): - def test_cases_unique_and_nonempty(self): - cases = probe.build_cases() - self.assertGreaterEqual(len(cases), 20) - names = [c.name for c in cases] - self.assertEqual(len(names), len(set(names))) - groups = {c.group for c in cases} - self.assertEqual(groups, { - "swizzle_basic", "idxen_ignores_tid", "swizzle_activation", - "multi_dword_stepping", "typed_and_atomic_x2", "oob_mode3_soffset", - "offset_wrap", "add_tid_wave_lane", - }) - for key in probe.KNOWN_DIVERGENCES: - self.assertIn(key, names) - - def test_hw_kernel_lines_wave32_and_wave64(self): - by_name = {c.name: c for c in probe.build_cases()} - c = by_name["tid_wave32_vs_wave64"] - w32 = "\n".join(probe._hw_kernel_lines(c, 0, wave=32)) - w64 = "\n".join(probe._hw_kernel_lines(c, 1, wave=64)) - self.assertIn("s_mov_b32 s28, exec_lo", w32) - self.assertIn("s_mov_b64 s[28:29], exec", w64) - self.assertIn("s_barrier", w32) - self.assertIn(".Lseed_0:", w32) - self.assertIn(".Lseed_1:", w64) - - def test_self_test_and_translator_groups(self): - buf = io.StringIO() - with redirect_stdout(buf): - rc = probe.main(["--self-test"]) - self.assertEqual(rc, 0) - self.assertIn("self-test:", buf.getvalue()) - - def test_list_groups_and_unknown_group(self): - out, err = io.StringIO(), io.StringIO() - with redirect_stdout(out): - rc = probe.main(["--list-groups"]) - self.assertEqual(rc, 0) - self.assertIn("oob_mode3_soffset", out.getvalue()) - - with redirect_stderr(err): - rc = probe.main(["--group", "does_not_exist"]) - self.assertEqual(rc, 2) - self.assertIn("unknown group", err.getvalue()) - - def test_hw_unavailable_returns_77(self): - err = io.StringIO() - with unittest.mock.patch.object(hw_runner, "open_oracle", side_effect=hw_runner.Unavailable("no GPU")): - with redirect_stderr(err): - rc = probe.main(["--oracle", "hw", "--group", "offset_wrap"]) - self.assertEqual(rc, 77) - self.assertIn("no GPU", err.getvalue()) - - def test_both_match_known_divergence_strict_and_json(self): - cases = [c for c in probe.build_cases() if c.group == "oob_mode3_soffset"] - tr = probe.run_translator(cases, waves=(32, 64)) - fake_hw = ("device=mock arch=gfx1036", {32: dict(tr[32]), 64: dict(tr[64])}) - with tempfile.TemporaryDirectory() as tmp: - jpath = os.path.join(tmp, "out.json") - out = io.StringIO() - with unittest.mock.patch.object(probe, "run_hw", return_value=fake_hw): - with redirect_stdout(out): - rc = probe.main(["--oracle", "both", "--group", "oob_mode3_soffset", "--json", jpath]) - self.assertEqual(rc, 0) - self.assertIn("2 match, 0 known divergence, 0 unexpected mismatch, 0 wave32/64 diff", out.getvalue()) - data = json.loads(Path(jpath).read_text(encoding="utf-8")) - self.assertEqual(data["device"], "device=mock arch=gfx1036") - self.assertEqual(len(data["cases"]), 2) - - # Synthetic known divergence vs --strict - fake_hw[1][32]["indexed_mode3_soff_edge"] = fake_hw[1][64]["indexed_mode3_soff_edge"] = [1, 2, 3, 4] - known = {"indexed_mode3_soff_edge": ("synthetic", [1, 2, 3, 4], "test-only divergence")} - with unittest.mock.patch.dict(probe.KNOWN_DIVERGENCES, known): - out2 = io.StringIO() - with unittest.mock.patch.object(probe, "run_hw", return_value=fake_hw): - with redirect_stdout(out2): - rc_ok = probe.main(["--oracle", "both", "--group", "oob_mode3_soffset"]) - self.assertEqual(rc_ok, 0) - self.assertIn("1 match, 1 known divergence, 0 unexpected mismatch", out2.getvalue()) - - out3 = io.StringIO() - with unittest.mock.patch.object(probe, "run_hw", return_value=fake_hw): - with redirect_stdout(out3): - rc_strict = probe.main(["--oracle", "both", "--group", "oob_mode3_soffset", "--strict"]) - self.assertEqual(rc_strict, 1) - - err = io.StringIO() - with unittest.mock.patch.object(probe, "run_hw", return_value=fake_hw): - with redirect_stdout(io.StringIO()), redirect_stderr(err): - rc_dir = probe.main(["--oracle", "both", "--group", "oob_mode3_soffset", "--json", tmp]) - self.assertEqual(rc_dir, 2) - - def test_report_failure_names_the_output(self): - group = "offset_wrap" - result = {32: {case.name: [1, 2, 3, 4] for case in probe.build_cases() if case.group == group}} - with tempfile.TemporaryDirectory() as tmp: - blocker = Path(tmp) / "blocker" - blocker.write_bytes(b"keep") - report = str(blocker / "report.json") - with unittest.mock.patch.object(probe, "run_translator", return_value=result), \ - redirect_stdout(io.StringIO()), redirect_stderr(io.StringIO()) as err: - rc = probe.main(["--group", group, "--wave", "32", "--json", report]) - self.assertEqual(rc, 2) - self.assertIn(f"cannot write {report}", err.getvalue()) - self.assertEqual(blocker.read_bytes(), b"keep") - - def test_unexpected_mismatch_and_wave_diff_fail(self): - bad_hw = ("device=mock arch=gfx1036", { - 32: {"voff_inst_wrap_and_soff_nowrap": [1, 2, 3, 4]}, - 64: {"voff_inst_wrap_and_soff_nowrap": [1, 2, 3, 5]}, - }) - out = io.StringIO() - with unittest.mock.patch.object(probe, "run_hw", return_value=bad_hw): - with redirect_stdout(out): - rc = probe.main(["--oracle", "both", "--group", "offset_wrap"]) - self.assertEqual(rc, 1) - self.assertIn("WAVE_DIFF", out.getvalue()) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/test_build_batch_launch.py b/tests/test_build_batch_launch.py deleted file mode 100644 index a19ba1cb8..000000000 --- a/tests/test_build_batch_launch.py +++ /dev/null @@ -1,86 +0,0 @@ -"""The Windows build scripts start their generated batch file from any folder name, `&` and `^` included. - - python -I tests/test_build_batch_launch.py - -`scripts/build_runtime.ps1` and `scripts/build_llvm_mc.ps1` write `_build.cmd` into the build folder and start it -with `Start-Process cmd.exe -ArgumentList ...`. With `/c "path"`, cmd.exe drops the quotes when the path holds a -special character such as `&` or `^` and then runs only the part before it. This test takes each script's launch -line as written and runs it on a stub batch in such folders: the stub must run, and its exit code must come back. -Windows only (PowerShell and cmd.exe); no compiler, no game files. -""" -import base64 -import os -from pathlib import Path -import re -import subprocess -import sys -import tempfile -import unittest - -ROOT = Path(__file__).resolve().parents[1] -SCRIPTS = ("build_runtime.ps1", "build_llvm_mc.ps1") -# build_llvm_mc.ps1 keeps the one-line form; build_runtime.ps1 writes `-FilePath cmd.exe` and ends the line with a -# backtick, continuing with -WindowStyle and the log redirects. Both pass the same -ArgumentList expression. -LAUNCH = re.compile(r"^\$p = Start-Process (?:-FilePath )?cmd\.exe -ArgumentList (.+?)" - r" (?:-NoNewWindow )?-PassThru(?: `)?\s*$", re.M) -FOLDERS = ("plain", "a & b", "a&b", "x^y", "sp (x)", "東京 & co") - - -def launch_arguments(script): - """The -ArgumentList expression of the script's one `$p = Start-Process cmd.exe` line.""" - found = LAUNCH.findall((ROOT / "scripts" / script).read_text(encoding="utf-8-sig")) - if len(found) != 1: - raise AssertionError(f"{script}: expected one `$p = Start-Process cmd.exe -ArgumentList ...` line, found " - f"{len(found)}; update tests/test_build_batch_launch.py together with the script") - return found[0] - - -def start(arguments, bat): - """Run `$p = Start-Process cmd.exe -ArgumentList ` with $bat set, as the script does; its exit code.""" - command = ("$ErrorActionPreference = 'Stop'\n" - "$bat = $env:LEONIDA_LAUNCH_BAT\n" - f"$p = Start-Process cmd.exe -ArgumentList {arguments} -NoNewWindow -PassThru\n" - "$null = $p.Handle\n" - "$p.WaitForExit()\n" - "exit $p.ExitCode\n") - encoded = base64.b64encode(command.encode("utf-16-le")).decode("ascii") - return subprocess.run(["powershell.exe", "-NoProfile", "-NonInteractive", "-EncodedCommand", encoded], - env=dict(os.environ, LEONIDA_LAUNCH_BAT=str(bat)), capture_output=True, timeout=60) - - -@unittest.skipUnless(sys.platform == "win32", "requires Windows PowerShell and cmd.exe") -class BatchLaunchTest(unittest.TestCase): - def check(self, arguments): - """Folders the launch line fails in, as `name/exit code` strings.""" - broken = [] - with tempfile.TemporaryDirectory() as directory: - for name in FOLDERS: - folder = Path(directory) / name - folder.mkdir() - bat = folder / "_build.cmd" - ran = folder / "ran.txt" - for code in (0, 7): - bat.write_bytes(f'@echo off\r\necho ran> "%~dp0ran.txt"\r\nexit /b {code}\r\n'.encode("ascii")) - if ran.exists(): - ran.unlink() - result = start(arguments, bat) - if not ran.exists() or result.returncode != code: - broken.append(f"{name}/{code}->{result.returncode}") - return broken - - def test_each_script_starts_its_batch_in_any_folder(self): - for script in SCRIPTS: - with self.subTest(script=script): - self.assertEqual(self.check(launch_arguments(script)), [], - f"{script}'s launch line does not run the batch in these folders") - - def test_the_check_catches_a_launch_line_that_drops_the_quotes(self): - # The form both scripts used before: cmd.exe /c "path" loses the quotes around a path holding & or ^. - broken = self.check('"/c", "`"$bat`""') - self.assertIn("a & b/0->1", broken) - self.assertIn("x^y/7->1", broken) - self.assertFalse([b for b in broken if b.startswith(("plain/", "sp (x)/"))], broken) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/test_build_llvm_mc_batch.py b/tests/test_build_llvm_mc_batch.py deleted file mode 100644 index 648a60efa..000000000 --- a/tests/test_build_llvm_mc_batch.py +++ /dev/null @@ -1,63 +0,0 @@ -"""Exercise the native LLVM builder's batch writer without compiling LLVM.""" -import os -from pathlib import Path -import subprocess -import tempfile -import unittest - - -SCRIPT = Path(__file__).resolve().parents[1] / "scripts" / "build_llvm_mc.ps1" - - -@unittest.skipUnless(os.name == "nt", "requires Windows PowerShell and cmd.exe") -class BuildBatchTest(unittest.TestCase): - def test_unicode_paths_exit_status_and_console_code_page(self): - text = SCRIPT.read_text(encoding="utf-8-sig") - start = text.index('$bat = Join-Path $Temp "_build.cmd"') - writer = text[start:text.index("$p = Start-Process", start)] - - with tempfile.TemporaryDirectory(prefix="leonida & llvm ") as directory: - work = Path(directory) / "LLVM 東京" - work.mkdir() - (work / "vcvars64.bat").write_bytes(b"@exit /b 0\r\n") - driver = Path(directory) / "write-build.ps1" - driver.write_text( - "param([string]$Temp, [int]$Code)\n" - "$ErrorActionPreference = 'Stop'\n" - "$installer = $Temp\n" - "$vcvars = Join-Path $Temp 'vcvars64.bat'\n" - "$body = 'cd /d \"' + $Temp + '\" || exit /b 1' + \"`r`nexit /b $Code\"\n" - + writer, - encoding="utf-8", newline="\n", - ) - console_check = work / "check-console.cmd" - console_check.write_bytes( - b"@echo off\r\nchcp 437 >nul || exit /b 99\r\nchcp >before.txt\r\n" - b'call "%~dp0_build.cmd"\r\nset "build_exit=%errorlevel%"\r\nchcp >after.txt\r\nexit /b %build_exit%\r\n' - ) - startup = subprocess.STARTUPINFO() - startup.dwFlags |= subprocess.STARTF_USESHOWWINDOW - startup.wShowWindow = subprocess.SW_HIDE - for code in (0, 17): - with self.subTest(exit_code=code): - subprocess.run( - ["powershell.exe", "-NoProfile", "-NonInteractive", "-ExecutionPolicy", "Bypass", - "-File", str(driver), "-Temp", str(work), "-Code", str(code)], - check=True, timeout=30, - ) - batch = (work / "_build.cmd").read_bytes() - self.assertTrue(batch.startswith(b"@echo off\r\n")) - self.assertIn(str(work).encode("utf-8"), batch) - result = subprocess.run( - ["cmd.exe", "/d", "/c", r".\check-console.cmd"], cwd=work, timeout=30, - env={**os.environ, "NoDefaultCurrentDirectoryInExePath": "1"}, - creationflags=subprocess.CREATE_NEW_CONSOLE, startupinfo=startup, capture_output=True, - ) - self.assertEqual(result.returncode, code, result.stdout + result.stderr) - before = (work / "before.txt").read_bytes() - self.assertIn(b"437", before) - self.assertEqual((work / "after.txt").read_bytes(), before) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/test_build_llvm_mc_cleanup.py b/tests/test_build_llvm_mc_cleanup.py deleted file mode 100644 index 4ad7a7b5a..000000000 --- a/tests/test_build_llvm_mc_cleanup.py +++ /dev/null @@ -1,48 +0,0 @@ -"""Exercise the native LLVM builder's robust directory cleanup handling read-only attributes.""" -import os -from pathlib import Path -import stat -import subprocess -import tempfile -import unittest - - -SCRIPT = Path(__file__).resolve().parents[1] / "scripts" / "build_llvm_mc.ps1" - - -@unittest.skipUnless(os.name == "nt", "requires Windows PowerShell") -class BuildCleanupTest(unittest.TestCase): - def test_cleanup_removes_readonly_nested_files_and_directories(self): - text = SCRIPT.read_text(encoding="utf-8-sig") - start = text.index("function Remove-DirectoryRobust") - func_def = text[start:text.index("if (-not (Test-Path (Join-Path $src", start)].strip() - - with tempfile.TemporaryDirectory() as directory: - target = Path(directory) / "test_temp_cleanup" - target.mkdir() - sub = target / ".git" / "objects" / "pack" - sub.mkdir(parents=True) - ro_file = sub / "sample_pack.idx" - ro_file.write_bytes(b"DATA") - # Mark file and directory read-only on Windows - os.chmod(ro_file, stat.S_IREAD) - os.chmod(sub, stat.S_IREAD) - - driver = Path(directory) / "test-clean.ps1" - driver.write_text( - "param([string]$Path)\n" - "$ErrorActionPreference = 'Stop'\n" - + func_def + "\n" - "Remove-DirectoryRobust $Path\n", - encoding="utf-8", newline="\n", - ) - res = subprocess.run( - ["powershell.exe", "-NoProfile", "-NonInteractive", "-ExecutionPolicy", "Bypass", - "-File", str(driver), "-Path", str(target)], - capture_output=True, text=True, check=True, timeout=30, - ) - self.assertFalse(target.exists(), f"Target directory should have been removed: {res.stderr}") - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/test_build_runtime_batch.py b/tests/test_build_runtime_batch.py deleted file mode 100644 index 5cb7d5ff5..000000000 --- a/tests/test_build_runtime_batch.py +++ /dev/null @@ -1,48 +0,0 @@ -"""Check the runtime build wrapper's batch encoding without compiling the runtime.""" -import os -from pathlib import Path -import subprocess -import tempfile -import unittest - - -SCRIPT = Path(__file__).resolve().parents[1] / "scripts" / "build_runtime.ps1" - - -@unittest.skipUnless(os.name == "nt", "requires Windows PowerShell and cmd.exe") -class BuildRuntimeBatchTest(unittest.TestCase): - def test_build_cmd_preserves_unicode_paths(self): - text = SCRIPT.read_text(encoding="utf-8-sig") - start = text.index('$bat = Join-Path $out "_build.cmd"') - writer = text[start:text.index("$p = Start-Process", start)] - - with tempfile.TemporaryDirectory(prefix="leonida & batch ") as directory: - checkout = Path(directory) / "Leonida 東京" - checkout.mkdir() - (checkout / "vcvars64.bat").write_bytes(b"@exit /b 0\r\n") - driver = Path(directory) / "write-build.ps1" - driver.write_text( - "param([string]$out, [string]$installer)\n" - "$ErrorActionPreference = 'Stop'\n" - "$vcvars = Join-Path $installer 'vcvars64.bat'\n" - "$body = 'cd /d \"' + $installer + '\" || exit /b 1'\n" - + writer, - encoding="utf-8", newline="\n", - ) - subprocess.run( - ["powershell.exe", "-NoProfile", "-NonInteractive", "-ExecutionPolicy", "Bypass", - "-File", str(driver), "-out", directory, "-installer", str(checkout)], - check=True, timeout=30, - ) - batch_path = Path(directory) / "_build.cmd" - batch = batch_path.read_bytes() - self.assertTrue(batch.startswith(b"@echo off\r\n")) - self.assertIn(str(checkout).encode("utf-8"), batch) - subprocess.run( - ["cmd.exe", "/d", "/c", r".\_build.cmd"], cwd=directory, - env={**os.environ, "NoDefaultCurrentDirectoryInExePath": "1"}, check=True, timeout=30, - ) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/test_build_runtime_cmake.py b/tests/test_build_runtime_cmake.py deleted file mode 100644 index c7685a521..000000000 --- a/tests/test_build_runtime_cmake.py +++ /dev/null @@ -1,118 +0,0 @@ -"""Run the runtime wrapper's real CMake batch branch with a native argument recorder. - -Windows only; needs the .NET Framework C# compiler, not MSVC, CMake, a GPU or game files. -The recorder validates configure paths and lets either stage fail independently. -""" -import base64 -import os -from pathlib import Path -import shutil -import subprocess -import tempfile -import unittest - -SCRIPT = Path(__file__).resolve().parents[1] / "scripts" / "build_runtime.ps1" -CSC = Path(os.environ.get("WINDIR", r"C:\Windows")) / "Microsoft.NET/Framework64/v4.0.30319/csc.exe" -RECORDER = r''' -using System; -using System.IO; -class Recorder { - static int Main(string[] args) { - bool build = args.Length > 0 && args[0] == "--build"; - string stage = build ? "build" : "configure"; - File.WriteAllLines(Path.Combine(Environment.GetEnvironmentVariable("LEONIDA_CMAKE_LOG"), stage + ".txt"), args); - if (!build) { - for (int i = 0; i + 1 < args.Length; ++i) - if (args[i] == "-S" && !Directory.Exists(args[i + 1])) return 9; - } - return Environment.GetEnvironmentVariable("LEONIDA_CMAKE_FAIL") == stage ? 7 : 0; - } -} -''' - - -@unittest.skipUnless(os.name == "nt" and CSC.is_file(), "requires Windows PowerShell and .NET Framework csc") -class CMakeBatchTest(unittest.TestCase): - @classmethod - def setUpClass(cls): - cls.temp = tempfile.TemporaryDirectory(prefix="leonida_cmake_") - cls.addClassCleanup(cls.temp.cleanup) - cls.base = Path(cls.temp.name) - source = cls.base / "recorder.cs" - source.write_text(RECORDER, encoding="utf-8", newline="\n") - cls.recorder = cls.base / "recorder.exe" - subprocess.run([str(CSC), "/nologo", "/target:exe", "/out:" + str(cls.recorder), str(source)], - check=True, capture_output=True, timeout=30) - - def run_build(self, folder, extension, fail=""): - text = SCRIPT.read_text(encoding="utf-8-sig") - start = text.index('$cfg = if ($Debug)') - end = text.index('} else {', text.index('if ($cmake -and $ninja)', start)) - branch = text[start:end] + "}\n" - writer = text[text.index('$bat = Join-Path $out "_build.cmd"'):] - root = folder / "checkout" - src, out = root / "runtime", root / "runtime/build" - out.mkdir(parents=True) - tools = folder / "tools ^ & 東京" - tools.mkdir() - backend = tools / "recorder.exe" - shutil.copyfile(self.recorder, backend) - cmake = tools / ("cmake" + extension) - if extension == ".exe": - shutil.copyfile(self.recorder, cmake) - else: - cmake.write_text('@echo off\nchcp 65001 >nul\n"' + str(backend) + '" %*\nexit /b %errorlevel%\n', - encoding="utf-8", newline="\r\n") - # The real vcvars lives in the VS installation, outside the checkout. - vcvars = self.base / "vcvars64.bat" - vcvars.write_text('@exit /b 0\n', encoding="ascii", newline="\r\n") - ninja = tools / "ninja.exe" - command = ("$ErrorActionPreference = 'Stop'\n" - "$root = $env:LEONIDA_CMAKE_ROOT\n" - "$src = Join-Path $root 'runtime'\n" - "$out = Join-Path $src 'build'\n" - "$installer = $env:LEONIDA_CMAKE_INSTALLER\n" - "$vcvars = Join-Path $installer 'vcvars64.bat'\n" - "$cmake = $env:LEONIDA_CMAKE_EXE\n" - "$ninja = $env:LEONIDA_CMAKE_NINJA\n" - "$Debug = $false\n$FetchSdl3 = $true\n$jobs = 3\n" - + branch + writer) - encoded = base64.b64encode(command.encode("utf-16-le")).decode("ascii") - result = subprocess.run( - ["powershell.exe", "-NoProfile", "-NonInteractive", "-EncodedCommand", encoded], - env=dict(os.environ, LEONIDA_CMAKE_ROOT=str(root), LEONIDA_CMAKE_LOG=str(folder), - LEONIDA_CMAKE_INSTALLER=str(self.base), - LEONIDA_CMAKE_EXE=str(cmake), LEONIDA_CMAKE_NINJA=str(ninja), - LEONIDA_CMAKE_FAIL=fail, VULKAN_SDK=str(folder / "vulkan")), - capture_output=True, timeout=45, - ) - return result, src, out, ninja - - def test_native_and_batch_cmake_paths_and_exit_codes(self): - for name in ("plain", "caret^dir", "пробел ^ & 東京"): - for extension in (".exe", ".cmd", ".bat"): - for fail in ("", "configure", "build"): - with self.subTest(folder=name, extension=extension, fail=fail): - with tempfile.TemporaryDirectory(dir=self.base) as tmp: - folder = Path(tmp) / name - folder.mkdir() - result, src, out, ninja = self.run_build(folder, extension, fail) - batch = (out / "_build.cmd").read_bytes() - self.assertNotIn(b"\n", batch.replace(b"\r\n", b"")) - self.assertEqual(result.returncode, 1 if fail else 0, - (result.stdout + result.stderr).decode(errors="replace")) - configure = (folder / "configure.txt").read_text(encoding="utf-8-sig").splitlines() - self.assertEqual(configure, ["-S", str(src), "-B", str(out), "-G", "Ninja", - "-DCMAKE_MAKE_PROGRAM=" + str(ninja), - "-DCMAKE_BUILD_TYPE=RelWithDebInfo", - "-DLEONIDA_SDL3_FETCH=ON", "-DLEONIDA_REQUIRE_VULKAN=ON"]) - built = folder / "build.txt" - if fail == "configure": - self.assertFalse(built.exists(), "configure failure must stop before build") - else: - self.assertEqual(built.read_text(encoding="utf-8-sig").splitlines(), - ["--build", str(out), "-j", "3"]) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/test_build_runtime_fallback.py b/tests/test_build_runtime_fallback.py deleted file mode 100644 index 9ea2b4099..000000000 --- a/tests/test_build_runtime_fallback.py +++ /dev/null @@ -1,211 +0,0 @@ -"""scripts/build_runtime.ps1's cl.exe fallback builds every GPU test harness the Python tools need (no build run). - -The fallback is what runs when Visual Studio has no "C++ CMake tools" component. Without these programs, -check.py / run_gpu_tests.py stop with "missing vk_compute_test", and so do the fuzzers. - - python -I tests/test_build_runtime_fallback.py -""" -import os -from pathlib import Path -import re -import subprocess -import sys -import tempfile -import unittest - -ROOT = Path(__file__).resolve().parents[1] -sys.path[:0] = [str(ROOT / "scripts"), str(ROOT / "runtime" / "test" / "shaders"), str(ROOT / "tools"), - str(ROOT / "tests")] -import check # noqa: E402 -import image_fuzz # noqa: E402 -import run_gpu_tests # noqa: E402 -import runtime_cmake # noqa: E402 - -SCRIPT = ROOT / "scripts" / "build_runtime.ps1" - - -def fallback_body(text: str) -> str: - """The cl.exe branch: from the line-starting `} else {` after the CMake test to the end of its here-string.""" - start = re.search(r"^\} else \{", text, re.M).start() - return text[start:text.index('"@', text.index('$body = @"', start))] - - -class FallbackBuildsTheHarnesses(unittest.TestCase): - def setUp(self): - self.body = fallback_body(SCRIPT.read_text(encoding="utf-8")) - self.programs = set(re.findall(r"/Fe:([A-Za-z0-9_]+)\.exe", self.body)) - - def test_the_harnesses_the_gpu_tools_require_are_built(self): - needed = set(run_gpu_tests.REQUIRED_TEST_PROGRAMS) | set(check.TEST_PROGRAMS) | {image_fuzz.HARNESS} - self.assertEqual(needed - self.programs, set(), "missing from build_runtime.ps1's cl.exe fallback") - - def test_every_harness_the_gpu_suite_starts_is_built(self): - """A harness run_gpu_tests.py or check.py starts by name, but the fallback did not build, fails its test - with "could not start" (ps_ssharp: vk_sampler_test.exe, WinError 2).""" - named = set() - for path in (ROOT / "scripts" / "run_gpu_tests.py", ROOT / "runtime" / "test" / "shaders" / "check.py"): - named |= set(re.findall(r'"(vk_[a-z0-9_]+)"', path.read_text(encoding="utf-8"))) - harnesses = {n for n in named if (ROOT / "runtime" / "test" / f"{n}.cpp").is_file()} - self.assertIn("vk_sampler_test", harnesses) - self.assertEqual(harnesses - self.programs, set(), "missing from build_runtime.ps1's cl.exe fallback") - - def test_the_fallback_builds_every_harness_a_tool_starts(self): - """EGEN-FALLBACK-SANDBOX-SWEEP: tools/sandbox.py starts runtime/build/vk_sandbox(.exe) and ends at - "unsupported: vk_sandbox is not built" without it; tools/ps_sweep.py --exe and - tools/ab_control_flow.py --all-attachments start runtime/build/vk_ps_sweep.exe. CMake builds both, the cl.exe - fallback built neither, so neither pixel check of translated shaders could run from a fallback build.""" - named = set() - for folder in ("tools", "scripts", "runtime/test/shaders"): - for path in (ROOT / folder).rglob("*.py"): - named |= set(re.findall(r'"(vk_[a-z0-9_]+)"', path.read_text(encoding="utf-8"))) - harnesses = {n for n in named if (ROOT / "runtime" / "test" / f"{n}.cpp").is_file()} - self.assertTrue({"vk_sandbox", "vk_ps_sweep"} <= harnesses) - self.assertEqual(harnesses - self.programs, set(), "missing from build_runtime.ps1's cl.exe fallback") - - def test_the_launcher_compiles_every_source_cmake_gives_gta6rt(self): - """BUILD-680: main.cpp calls rt::fs::configure, but the fallback left out shims/file_system.cpp (LNK2019). - Every source of CMake's add_executable(gta6rt ...) must be in the fallback's launcher list ($files).""" - cmake = runtime_cmake.read() - block = re.search(r"add_executable\(gta6rt\s+(.*?)\)", cmake, re.S).group(1) - wanted = {item.replace("/", "\\") for item in block.split() if item.endswith(".cpp")} - files = re.search(r"\$files = (.*?) \| ForEach-Object", self.body).group(1) - listed = set(re.findall(r'"([^"]+\.cpp)"', files)) - self.assertTrue(wanted) - self.assertEqual(wanted - listed, set(), "in CMake's gta6rt sources but not in the cl.exe fallback") - - def test_every_test_source_it_compiles_exists(self): - sources = re.findall(r'"\$src\\test\\([A-Za-z0-9_]+\.cpp)"', self.body) - self.assertTrue(sources) - for name in sources: - with self.subTest(source=name): - self.assertTrue((ROOT / "runtime" / "test" / name).is_file()) - - def test_the_pipeline_checker_gets_the_stack_reserve_cmake_gives_it(self): - """BUILD-1457: a driver compiles on vk_pipeline_check's threads, and AMD's Windows compiler overflows the - 1 MB PE default. CMake links the checker with /STACK:; the fallback has to pass - the same number on the checker's own cl line (a /link option applies to that one program).""" - cmake = runtime_cmake.read() - reserve = re.search(r"set\(LEONIDA_PIPELINE_CHECK_STACK (\d+)\)", cmake).group(1) - self.assertGreaterEqual(int(reserve), 8 * 1024 * 1024) - self.assertIn("target_link_options(vk_pipeline_check PRIVATE /STACK:${LEONIDA_PIPELINE_CHECK_STACK})", cmake) - lines = [line for line in self.body.splitlines() if "/Fe:vk_pipeline_check.exe" in line] - self.assertEqual(len(lines), 1) - self.assertRegex(lines[0], rf"/Fe:vk_pipeline_check\.exe /link (\S+ )*/STACK:{reserve}( |$)") - - def test_the_loader_gets_the_stack_reserve_cmake_gives_it(self): - """BUILD-1457, the loader's side: a game thread with the default stack size gets the reserve in gta6rt.exe's - header, and the driver compiles a pipeline's shaders on the thread that creates it. CMake links gta6rt with - /STACK:; the fallback has to pass the same number, and it is the number run_entry gives the - entry thread, so every game thread that asks for no size has the same room.""" - cmake = runtime_cmake.read() - reserve = re.search(r"set\(GTA6RT_STACK (\d+)\)", cmake).group(1) - self.assertGreaterEqual(int(reserve), 8 * 1024 * 1024) - self.assertRegex(cmake, r"target_link_options\(gta6rt PRIVATE [^)]*/STACK:\$\{GTA6RT_STACK\}\)") - lines = [line for line in self.body.splitlines() if "/Fe:gta6rt.exe" in line] - self.assertEqual(len(lines), 1) - self.assertRegex(lines[0], rf"/Fe:gta6rt\.exe /link (\S+ )*/STACK:{reserve}( |$)") - shim = (ROOT / "runtime" / "shims" / "process_shim.h").read_text(encoding="utf-8") - megabytes = re.search(r"run_entry\(void\* entry, std::size_t stack_bytes = (\d+)u << 20\);", shim).group(1) - self.assertEqual(int(megabytes) << 20, int(reserve)) - - def test_the_loader_gets_the_host_base_cmake_gives_it(self): - cmake = runtime_cmake.read() - base = re.search(r"set\(GTA6RT_HOST_BASE (/BASE:0x[0-9A-Fa-f]+)\)", cmake).group(1) - self.assertRegex(cmake, r"target_link_options\(gta6rt PRIVATE [^)]*\$\{GTA6RT_HOST_BASE\}") - lines = [line for line in self.body.splitlines() if "/Fe:gta6rt.exe" in line] - self.assertEqual(len(lines), 1) - def has_exactly_the_cmake_base(line): - before, separator, after = line.partition(" /link ") - if not separator or "/Fe:gta6rt.exe" not in before: - return False - return [option for option in after.split() if option.upper().startswith("/BASE:")] == [base] - - self.assertFalse(has_exactly_the_cmake_base(lines[0].replace(base, ""))) - self.assertFalse(has_exactly_the_cmake_base(lines[0] + " /BASE:0x140000000")) - self.assertTrue(has_exactly_the_cmake_base(lines[0])) - - def test_build_cmd_sets_utf8_codepage_for_ninja_showincludes(self): - text = SCRIPT.read_text(encoding="utf-8") - self.assertIn("chcp 65001 >nul", text) - self.assertLess(text.index("chcp 65001 >nul"), text.index('call `"$vcvars`"')) - - @unittest.skipUnless(sys.platform == "win32", "requires Windows PowerShell") - def test_path_fallback_prefers_vs_and_skips_msys_cmake(self): - text = SCRIPT.read_text(encoding="utf-8") - # Extract the helper functions and the two Find-BuildTool assignments directly from scripts/build_runtime.ps1. - helpers_start = text.index("function Invoke-ToolProbe") - helpers_end = text.index("$root = Split-Path") - lookup_start = text.index("$cmakeDir = Join-Path") - lookup_end = text.index("$cfg = if") - snippet = text[helpers_start:helpers_end] + "\n" + text[lookup_start:lookup_end] - - def run_probe(vs_dir: Path, path_dirs: list[Path]) -> tuple[str, str]: - ps = ( - "$ErrorActionPreference = 'Stop'\n" - "$vs = $env:LEONIDA_VS_DIR\n" - + snippet - + "\nWrite-Output \"CMAKE=$cmake\"\nWrite-Output \"NINJA=$ninja\"\n" - ) - env = dict(os.environ, PATH=";".join(str(p) for p in path_dirs), LEONIDA_VS_DIR=str(vs_dir)) - res = subprocess.run( - ["powershell.exe", "-NoProfile", "-NonInteractive", "-Command", ps], - env=env, capture_output=True, text=True, check=True, timeout=30, - ) - found = {} - for line in res.stdout.splitlines(): - if "=" in line: - k, v = line.split("=", 1) - found[k.strip()] = v.strip() - return found.get("CMAKE", ""), found.get("NINJA", "") - - with tempfile.TemporaryDirectory() as tmp: - root = Path(tmp) - vs_empty = root / "vs_empty" - msys_dir = root / "msys_bin" - native_cmake_dir = root / "native_cmake_bin" - native_ninja_dir = root / "native_ninja_bin" - for d in (vs_empty, msys_dir, native_cmake_dir, native_ninja_dir): - d.mkdir() - - # MSYS/devkitPro-like cmake: lacks Visual Studio generators in --help. - msys_cmake = msys_dir / "cmake.cmd" - msys_cmake.write_text("@echo off\r\necho * Ninja\r\necho Unix Makefiles\r\nexit /b 0\r\n", encoding="ascii") - - # Native Windows cmake: lists both Visual Studio and Ninja generators. - native_cmake = native_cmake_dir / "cmake.cmd" - native_cmake.write_text( - "@echo off\r\necho Visual Studio 18 2026\r\necho * Ninja\r\nexit /b 0\r\n", - encoding="ascii", - ) - native_ninja = native_ninja_dir / "ninja.cmd" - native_ninja.write_text("@echo off\r\necho 1.12.1\r\nexit /b 0\r\n", encoding="ascii") - - # 1) No VS CMake tools, MSYS cmake comes first on PATH -> must skip MSYS and pick native PATH cmake + ninja. - cmake, ninja = run_probe(vs_empty, [msys_dir, native_cmake_dir, native_ninja_dir]) - self.assertEqual(Path(cmake).resolve(), native_cmake.resolve()) - self.assertEqual(Path(ninja).resolve(), native_ninja.resolve()) - - # 2) Only MSYS cmake on PATH -> must reject it so build_runtime.ps1 falls back to cl.exe. - cmake, ninja = run_probe(vs_empty, [msys_dir]) - self.assertEqual(cmake, "") - self.assertEqual(ninja, "") - - # 3) Native cmake on PATH without ninja -> ninja stays empty so CMake branch does not run. - cmake, ninja = run_probe(vs_empty, [native_cmake_dir]) - self.assertEqual(Path(cmake).resolve(), native_cmake.resolve()) - self.assertEqual(ninja, "") - - # 4) VS bundled CMake + Ninja present -> must prefer VS over PATH. - vs_full = root / "vs_full" - vs_cmake = vs_full / "Common7" / "IDE" / "CommonExtensions" / "Microsoft" / "CMake" / "CMake" / "bin" / "cmake.exe" - vs_ninja = vs_full / "Common7" / "IDE" / "CommonExtensions" / "Microsoft" / "CMake" / "Ninja" / "ninja.exe" - vs_cmake.parent.mkdir(parents=True) - vs_ninja.parent.mkdir(parents=True) - vs_cmake.write_bytes(b"") - vs_ninja.write_bytes(b"") - cmake, ninja = run_probe(vs_full, [native_cmake_dir, native_ninja_dir]) - self.assertEqual(Path(cmake).resolve(), vs_cmake.resolve()) - self.assertEqual(Path(ninja).resolve(), vs_ninja.resolve()) - -if __name__ == "__main__": - unittest.main() diff --git a/tests/test_bvh_geometry_check.py b/tests/test_bvh_geometry_check.py deleted file mode 100644 index 17371b711..000000000 --- a/tests/test_bvh_geometry_check.py +++ /dev/null @@ -1,113 +0,0 @@ -"""Synthetic checks for tools/bvh_geometry_check.py: the right geometry passes, a shifted, smaller or re-indexed one -fails the check that should catch it. No game data is read. - - python -I tests/test_bvh_geometry_check.py -""" -import contextlib -import io -import os -import struct -import sys -import tempfile -import unittest - -ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) -sys.path.insert(0, os.path.join(ROOT, "tools")) -sys.path.insert(0, os.path.join(ROOT, "tests")) - -import bvh_geometry_check as C # noqa: E402 -import bvh_rehydrate as R # noqa: E402 -from test_bvh_rehydrate import build # noqa: E402 - -# Two triangles sharing the edge (1, 2); bounds x 0..1, y 0..1, z 0 -VB = struct.pack("<12f", 0, 0, 0, 1, 0, 0, 0, 1, 0, 1, 1, 0) -IB = struct.pack("<6I", 0, 1, 2, 2, 1, 3) -TRUE = R.Geometry(VB, indices=IB) -LEAVES = [(0, 0x81, 0, 1, 0x09)] # one leaf holding both triangles -BOUNDS = (0, 0, 0, 1, 1, 0) - - -class TestChecks(unittest.TestCase): - def test_true_geometry_is_consistent(self): - src, _, _ = build(LEAVES, bounds=BOUNDS) - r = C.check(src, [TRUE]) - self.assertTrue(r["consistent"], r) - self.assertEqual((r["leaves_outside"], r["bounds_gap"], r["pairs"]), (0, 0.0, {"0": [1, 1]})) - self.assertGreater(r["internal_area"], 0.0) - - def test_shifted_geometry_fails_bounds(self): - shifted = R.Geometry(VB, indices=IB, transform=((1, 0, 0, 0.5), (0, 1, 0, 0), (0, 0, 1, 0))) - src, _, _ = build(LEAVES, bounds=BOUNDS) - r = C.check(src, [shifted]) - self.assertFalse(r["consistent"]) - self.assertEqual(r["leaves_outside"], 1) - self.assertAlmostEqual(r["bounds_gap"], 0.5, places=6) - - def test_smaller_geometry_inside_the_bounds_still_fails(self): - src, _, _ = build(LEAVES, bounds=(0, 0, 0, 2, 1, 0)) - r = C.check(src, [TRUE]) - self.assertEqual(r["leaves_outside"], 0) - self.assertFalse(r["consistent"]) - - def test_reindexed_geometry_fails_pairs_without_positions(self): - # same triangles count, but the second one no longer shares an edge with the first - src, _, _ = build(LEAVES, bounds=BOUNDS) - loose = R.Geometry(VB + struct.pack("<6f", 1, 1, 0, 1, 1, 0), indices=struct.pack("<6I", 0, 1, 2, 3, 4, 5)) - r = C.check(src, [loose]) - self.assertEqual(r["pairs"], {"0": [0, 1]}) - self.assertFalse(r["consistent"]) - - def test_overrides(self): - tight = build([(0, 0x01, 0, None, 0x09), (0, 0x01, 1, None, 0x09)], overrides={6: 0.25}, bounds=BOUNDS)[0] - self.assertEqual(C.check(tight, [TRUE])["overrides_consistent"], 1) - one_ulp = struct.unpack(" 0) - with contextlib.redirect_stdout(io.StringIO()): - self.assertEqual(C.main([paths[0], "--geom", paths[1] + "," + paths[2], "--transform", "1,0,0,9,0,1,0,0,0,0,1,0"]), 1) - with contextlib.redirect_stderr(io.StringIO()): - self.assertEqual(C.main([paths[0]]), 2) - - def test_json_must_not_overwrite_input_or_buffers(self): - src, _, _ = build(LEAVES, bounds=BOUNDS) - with tempfile.TemporaryDirectory() as d: - paths = [os.path.join(d, n) for n in ("in.bin", "vb.bin", "ib.bin", "r.json")] - for p, data in zip(paths, (src, VB, IB)): - with open(p, "wb") as f: - f.write(data) - # --json names the dehydrated input itself - for target in (paths[0], paths[1], paths[2]): - with contextlib.redirect_stderr(io.StringIO()) as err: - rc = C.main([paths[0], "--geom", paths[1] + "," + paths[2], "--json", target]) - self.assertEqual(rc, 2) - self.assertIn("must not overwrite", err.getvalue()) - # a hard link to the input also counts - link = os.path.join(d, "link.json") - try: - os.link(paths[0], link) - except (OSError, NotImplementedError, AttributeError) as e: - self.skipTest(f"hard links unavailable: {e}") - with contextlib.redirect_stderr(io.StringIO()) as err: - rc = C.main([paths[0], "--geom", paths[1] + "," + paths[2], "--json", link]) - self.assertEqual(rc, 2) - self.assertIn("must not overwrite", err.getvalue()) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/test_bvh_gpu_smoke.py b/tests/test_bvh_gpu_smoke.py deleted file mode 100644 index fc7919fca..000000000 --- a/tests/test_bvh_gpu_smoke.py +++ /dev/null @@ -1,206 +0,0 @@ -"""tools/bvh_gpu_smoke.py without a GPU or game files: the heap image, the word count and the judging of runs, with -a fake vk_compute_test in place of the real one.""" -import struct -import sys -import tempfile -import unittest -from pathlib import Path - -ROOT = Path(__file__).resolve().parents[1] -sys.path.insert(0, str(ROOT / "tools")) - -import bvh_gpu_smoke as smoke # noqa: E402 - - -def fake_runner(behaviour): - """A runner that writes the heap image plus per-program changes to the dump, as vk_compute_test's VKC_DUMP does. - behaviour: name -> ("ok", writes) | ("exit 1",) | ("validation",) | ("timeout",) | ("flaky", writes).""" - calls = {} - - def run(vkc, spv, init, dump, heap_words, validation, timeout): - name = Path(spv).stem - calls[name] = calls.get(name, 0) + 1 - kind = behaviour.get(name, ("ok", {})) - if kind[0] not in ("ok", "flaky"): - return kind[0], "boom" - heap = bytearray(Path(init).read_bytes()) - assert len(heap) == heap_words * 4 - for offset, word in kind[1].items(): - if kind[0] == "flaky" and calls[name] == 2: - word ^= 1 - struct.pack_into("x" - - -def make_rpf(payloads): - """An RPF9-shaped buffer: 4-byte magic, u32 data start at 4, then zlib streams separated by zeros.""" - body = b"" - for p in payloads: - body += zlib.compress(p, 9) + b"\0" * 16 - head = bytearray(0x40) - head[0:4] = b"9FPR" - struct.pack_into("\nx' - row_enc = bvh_index.classify(with_enc, len(with_enc)) - self.assertEqual(row_enc["kind"], "xml") - self.assertFalse(row_enc["fragment"]) - self.assertEqual(row_enc["root_element"], "CMapData") - - def test_xml_fragment(self): - text = b"/americas/map/x_bvh.rpf" + b" " * 40 - row = bvh_index.classify(text, len(text)) - self.assertEqual(row["kind"], "xml") - self.assertTrue(row["fragment"]) - - -class ScanTest(unittest.TestCase): - def setUp(self): - self.tmp = tempfile.TemporaryDirectory() - self.dir = self.tmp.name - - def tearDown(self): - self.tmp.cleanup() - - def test_two_streams_are_both_found(self): - # The old carver advanced by the 1 MiB read size, so a small first stream hid the second one. - payloads = [b"a" * 5000, bvh_payload(5)] - path = os.path.join(self.dir, "two.rpf") - with open(path, "wb") as f: - f.write(make_rpf(payloads)) - rows, summary = bvh_index.scan_rpf(path) - self.assertEqual(summary[0]["streams"], 2) - self.assertEqual([r["kind"] for r in rows], ["raw", "bvh4"]) - self.assertEqual(rows[1]["node_count"], 5) - self.assertEqual(summary[0]["inflated"], 5000 + 0x140 + 5 * 64) - - def test_fill_requires_all_bvh4_node_bytes(self): - path = os.path.join(self.dir, "one.rpf") - with open(path, "wb") as f: - f.write(make_rpf([bvh_payload(1)])) - rows, _ = bvh_index.scan_rpf(path, max_inflate=384) - self.assertEqual(rows[0]["fill"], {"81": 64, "total": 64}) - for cap in (320, 352): - with self.subTest(cap=cap): - rows, _ = bvh_index.scan_rpf(path, max_inflate=cap) - self.assertEqual(rows[0]["kind"], "bvh4") - self.assertEqual(rows[0]["node_bytes"], 64) - self.assertNotIn("fill", rows[0]) - - def test_directory_with_an_unreadable_archive_keeps_the_others_but_exits_nonzero(self): - good = os.path.join(self.dir, "good.rpf") - with open(good, "wb") as f: - f.write(make_rpf([bvh_payload(3)])) - bad = bytearray(make_rpf([bvh_payload(2)])) - struct.pack_into(" None: - n = 1200 - complete = bvh_payload(n) - chunk = complete[:65536] - for name, payload in (("complete.bin", complete), ("chunk.bin", chunk)): - with open(os.path.join(self.dir, name), "wb") as f: - f.write(payload) - - rows, _ = bvh_index.scan_dir(self.dir) - by_kind = {row["kind"]: row for row in rows} - self.assertEqual(by_kind["bvh4"]["fill"]["total"], n * 64) - self.assertEqual(by_kind["bvh4-chunk"]["node_count"], n) - self.assertNotIn("fill", by_kind["bvh4-chunk"]) - - archive = os.path.join(self.dir, "chunks.rpf") - with open(archive, "wb") as f: - f.write(make_rpf([chunk])) - (archived,), _ = bvh_index.scan_rpf(archive) - self.assertEqual(archived["kind"], "bvh4-chunk") - self.assertNotIn("fill", archived) - - def test_folder_name_with_glob_characters_is_a_path(self): - # glob read "[v1]" as a character class, so a folder named like this indexed nothing and exited 0. - folder = os.path.join(self.dir, "carve [v1]") - os.makedirs(folder) - with open(os.path.join(folder, "a.bin"), "wb") as f: - f.write(bvh_payload(4)) - rows, summary = bvh_index.scan_dir(folder) - self.assertEqual([r["kind"] for r in rows], ["bvh4"]) - archives = os.path.join(self.dir, "pack [1]") - os.makedirs(archives) - with open(os.path.join(archives, "a.rpf"), "wb") as f: - f.write(make_rpf([bvh_payload(2)])) - rows, summary = bvh_index.scan_dir(archives) - self.assertEqual([r["kind"] for r in rows], ["bvh4"]) - - def test_empty_and_short_archives_have_no_streams(self): - for name, data in (("empty.rpf", b""), ("short.rpf", b"9FPR")): - path = os.path.join(self.dir, name) - with open(path, "wb") as f: - f.write(data) - rows, summary = bvh_index.scan_rpf(path) - self.assertEqual(rows, []) - self.assertEqual((summary[0]["streams"], summary[0]["span"]), (0, 0)) - - def test_start_outside_the_archive_is_refused(self): - path = os.path.join(self.dir, "one.rpf") - with open(path, "wb") as f: - f.write(make_rpf([bvh_payload(2)])) - with self.assertRaises(ValueError): - bvh_index.scan_rpf(path, start=1 << 20) - - def test_directory_keeps_good_archives_next_to_a_bad_one(self): - with open(os.path.join(self.dir, "a_good.rpf"), "wb") as f: - f.write(make_rpf([bvh_payload(2)])) - with open(os.path.join(self.dir, "b_bad.rpf"), "wb") as f: - f.write(b"9FPR" + struct.pack(" one `o` group each, in the shape CreateObj writes.""" - lines, first = [], 1 - for index, (positions, faces) in enumerate(groups): - lines.append("o model_0_geometry_%d" % index) - lines += ["v %.9g %.9g %.9g" % p for p in positions] - lines += ["f %d//%d %d//%d %d//%d" % (first + a, first + a, first + b, first + b, first + c, first + c) - for a, b, c in faces] - first += len(positions) - with open(path, "w", encoding="utf-8", newline="\n") as f: - f.write("\n".join(lines) + "\n") - - -def item(offset, file, triangles, hashes=None, buckets=None): - """One manifest row, as tools/rpf9dump writes it: per geometry triangles and shader index, and with `buckets` - one render bucket per material (None leaves the field out, as an older export does).""" - materials = [{"ShaderIndex": i, "Shader": "%08X" % h} for i, h in enumerate(hashes or [])] - for material, bucket in zip(materials, buckets or []): - if bucket is not None: - material["RenderBucket"] = bucket - return {"Offset": offset, "File": file, "Name": "drawable_at_%X" % offset, "Meshes": len(triangles), - "Verts": 0, "Tris": sum(triangles), "MeshTris": list(triangles), - "MeshModels": [0] * len(triangles), "MeshGeoms": list(range(len(triangles))), - "MeshShaders": list(range(len(triangles))) if hashes else [None] * len(triangles), - "Materials": materials} - - -class TestMatching(unittest.TestCase): - def setUp(self): - directory = tempfile.TemporaryDirectory() - self.addCleanup(directory.cleanup) - self.dir = directory.name - - def guide(self, blas, items, obj_groups, argv=()): - """Write the export this run reads, call the matcher, return (status, stdout, stderr).""" - manifest = os.path.join(self.dir, "manifest.json") - with open(manifest, "w", encoding="utf-8") as f: - json.dump({"Count": len(items), "Items": items}, f) - for name, groups in obj_groups.items(): - write_obj(os.path.join(self.dir, name), groups) - path = os.path.join(self.dir, "blas.bin") - with open(path, "wb") as f: - f.write(blas) - out, err = io.StringIO(), io.StringIO() - with contextlib.redirect_stdout(out), contextlib.redirect_stderr(err): - status = M.main([path, manifest, *argv]) - return status, out.getvalue(), err.getvalue() - - def test_a_manifest_that_is_not_an_object_is_one_error_line(self): - path = os.path.join(self.dir, "blas.bin") - with open(path, "wb") as f: - f.write(build(LEAVES, bounds=BOUNDS)[0]) - for doc in ([1], [], "x", 3, None): - manifest = os.path.join(self.dir, "manifest.json") - with open(manifest, "w", encoding="utf-8") as f: - json.dump(doc, f) - out, err = io.StringIO(), io.StringIO() - with contextlib.redirect_stdout(out), contextlib.redirect_stderr(err): - status = M.main([path, manifest]) - self.assertEqual(status, 2, doc) - lines = err.getvalue().splitlines() - self.assertEqual(len(lines), 1, err.getvalue()) - self.assertTrue(lines[0].startswith("error: "), lines[0]) - self.assertNotIn("Traceback", err.getvalue()) - - def test_the_right_geometry_is_found_and_consistent(self): - src, _, _ = build(LEAVES, bounds=BOUNDS) - status, out, _ = self.guide(src, [item(0x1000, "a.obj", [5, 2, 3])], - {"a.obj": [group(5), group(2), group(3)]}) - self.assertEqual(status, 0, out) - self.assertIn("triangles per geometry index: [2]", out) - self.assertIn("1 of 1 scored candidates are consistent", out) - self.assertIn("model 0 geometry [1] (bucket rule not applied: a geometry has no render bucket) | outside 0 of 1", - out) - - def test_a_geometry_with_other_triangle_counts_is_not_a_candidate(self): - src, _, _ = build(LEAVES, bounds=BOUNDS) - status, out, _ = self.guide(src, [item(0x1000, "a.obj", [5, 3])], {"a.obj": [group(5), group(3)]}) - self.assertEqual(status, 1, out) - self.assertIn("0 candidates", out) - self.assertIn("0 of 0 scored candidates are consistent", out) - # An empty run says why: the drawable is outside the exported window, or the rule does not fit. - self.assertIn("outside the exported window", out) - - def test_a_wrong_geometry_is_rejected(self): - src, _, _ = build(LEAVES, bounds=BOUNDS) - # The same two triangles, half a unit away from what the BLAS stores: the leaves fall outside sceneBounds. - moved = [(x + 0.5, y, z) for x, y, z in QUAD] - status, out, _ = self.guide(src, [item(0x1000, "a.obj", [2])], {"a.obj": [(moved, QUAD_FACES)]}) - self.assertEqual(status, 1, out) - self.assertIn("rejected", out) - self.assertIn("outside 1 of 1", out) - - def test_the_shader_rule_leaves_a_geometry_out(self): - src, _, _ = build(LEAVES, bounds=BOUNDS) - hashes = [0xAAAA1111, 0xBBBB2222] - files = {"a.obj": [group(4), group(2)]} - # Geometry 0 has the excluded shader, so the two triangles belong to geometry 1. - status, out, _ = self.guide(src, [item(0x1000, "a.obj", [4, 2], hashes)], files, - ["--skip-shaders", "%08X" % hashes[0]]) - self.assertEqual(status, 0, out) - self.assertIn("model 0 geometry [1]", out) - # Excluding the other shader instead leaves a four-triangle geometry, which the signature does not fit. - status, out, _ = self.guide(src, [item(0x1000, "a.obj", [4, 2], hashes)], files, - ["--skip-shaders", "%08X" % hashes[1]]) - self.assertEqual(status, 1, out) - - def test_the_bucket_rule_leaves_buckets_1_and_2_out(self): - src, _, _ = build(LEAVES, bounds=BOUNDS) - hashes = [0x11110000, 0x22220000, 0x33330000, 0x44440000] - # Buckets 1 and 2 are left out, so geometry 3 (bucket 3) is index 1 and geometry 0 (bucket 0) index 0; the - # BLAS's one leaf uses index 0 with two triangles, which only the bucket-0 geometry has once 1 and 2 are out. - files = {"a.obj": [group(2), group(2), group(2), group(9)]} - rows = [item(0x1000, "a.obj", [2, 2, 2, 9], hashes, [0, 1, 2, 3])] - self.assertEqual([mesh[5] for mesh in M.model_geometries(rows[0])], [0, 1, 2, 3]) - candidates = M.match_candidates(rows, [2, 9], frozenset(), 8) - self.assertEqual([[c["kept"][k][0] for k in c["used"]] for c in candidates], [[0, 3]]) - # Without the rule, [2, 9] also embeds through geometries 1 and 2. - loose = M.match_candidates(rows, [2, 9], frozenset(), 8, buckets=False) - self.assertEqual(sorted([c["kept"][k][0] for k in c["used"]] for c in loose), [[0, 3], [1, 3], [2, 3]]) - status, out, _ = self.guide(src, rows, files) - self.assertEqual(status, 0, out) - self.assertIn("1 candidates", out) - self.assertIn("model 0 geometry [0] | outside 0 of 1", out) - - def test_the_bucket_rule_finds_what_the_signature_alone_cannot(self): - # Signature [2, 5]: geometries 0 and 2 (bucket 0 and 3); geometry 1 (bucket 2, 5 triangles) is a decal the - # BVH leaves out. Without the rule the ordered match would also take geometry 1 for the 5. - rows = [item(0x1000, "a.obj", [2, 5, 5], [1, 2, 3], [0, 2, 3])] - self.assertEqual([[c["kept"][k][0] for k in c["used"]] for c in M.match_candidates(rows, [2, 5], frozenset(), 8)], - [[0, 2]]) - self.assertEqual(len(M.match_candidates(rows, [2, 5], frozenset(), 8, buckets=False)), 2) - # A model all of whose geometries are left out has no candidate. - self.assertEqual(M.match_candidates([item(0x2000, "b.obj", [2], [1], [1])], [2], frozenset(), 8), []) - - def test_the_bucket_rule_ignores_bit_7(self): - # 0x83 is bucket 3 with bit 7 set (kept); 0x82 is bucket 2 with bit 7 set (left out); 6 is left out. - rows = [item(0x1000, "a.obj", [4, 3, 3, 8], [1, 2, 3, 4], [0x83, 0x82, 6, 0x80])] - self.assertEqual([[c["kept"][k][0] for k in c["used"]] for c in M.match_candidates(rows, [4, 8], frozenset(), 8)], - [[0, 3]]) - self.assertEqual(M.match_candidates(rows, [4, 3], frozenset(), 8), []) - - def test_the_bucket_rule_is_not_applied_without_every_bucket(self): - src, _, _ = build(LEAVES, bounds=BOUNDS) - # Geometry 1 has no bucket: the rule cannot be applied, so the bucket-1 geometry stays a candidate. - rows = [item(0x1000, "a.obj", [2, 7], [1, 2], [1, None])] - status, out, _ = self.guide(src, rows, {"a.obj": [group(2), group(7)]}) - self.assertEqual(status, 0, out) - self.assertIn("model 0 geometry [0] (bucket rule not applied", out) - - def test_no_bucket_rule_keeps_every_geometry(self): - src, _, _ = build(LEAVES, bounds=BOUNDS) - rows = [item(0x1000, "a.obj", [2], [1], [2])] - status, out, _ = self.guide(src, rows, {"a.obj": [group(2)]}) - self.assertEqual(status, 1, out) - self.assertIn("0 candidates", out) - status, out, _ = self.guide(src, rows, {"a.obj": [group(2)]}, ["--no-bucket-rule"]) - self.assertEqual(status, 0, out) - self.assertIn("model 0 geometry [0] | outside 0 of 1", out) - - def test_bucket_kept(self): - self.assertEqual([M.bucket_kept(b) for b in (0, 1, 2, 3, 4, 5, 6, None)], - [True, False, False, True, False, False, False, None]) - # Bit 7 does not change the choice. - self.assertEqual([M.bucket_kept(b) for b in (0x80, 0x81, 0x82, 0x83)], [True, False, False, True]) - - def test_skip_shaders_still_applies_on_top_of_the_bucket_rule(self): - rows = [item(0x1000, "a.obj", [2, 2], [0xAAAA1111, 0xBBBB2222], [0, 0])] - candidates = M.match_candidates(rows, [2], frozenset([0xAAAA1111]), 8) - self.assertEqual([[c["kept"][k][0] for k in c["used"]] for c in candidates], [[1]]) - - def test_the_instance_transform_decides(self): - src, _, _ = build(LEAVES, bounds=(0.5, 0.0, 0.0, 1.5, 1.0, 0.0)) - descriptor = os.path.join(self.dir, "instance208.bin") - with open(descriptor, "wb") as f: - f.write(bytes(0x50) + struct.pack("<12f", *[v for row in SHIFTED for v in row]) + bytes(60)) - status, out, _ = self.guide(src, [item(0x1000, "a.obj", [2])], {"a.obj": [group(2)]}, - ["--descriptor", descriptor]) - self.assertEqual(status, 0, out) - status, out, err = self.guide(src, [item(0x1000, "a.obj", [2])], {"a.obj": [group(2)]}) - self.assertEqual(status, 1, out) - self.assertIn("rejected", out) - self.assertIn("without the instance transform", err) - - def test_geometries_are_matched_inside_one_model(self): - src, _, _ = build(LEAVES, bounds=BOUNDS) - row = item(0x1000, "a.obj", [5, 2]) - row["MeshModels"] = [0, 1] # two models in the primary LOD, one geometry each - row["MeshGeoms"] = [0, 0] - status, out, _ = self.guide(src, [row], {"a.obj": [group(5), group(2)]}) - self.assertEqual(status, 0, out) - self.assertIn("model 1 geometry [0]", out) - - def test_a_manifest_without_per_geometry_counts_is_an_input_error(self): - src, _, _ = build(LEAVES, bounds=BOUNDS) - row = item(0x1000, "a.obj", [2]) - del row["MeshTris"] - status, _, err = self.guide(src, [row], {"a.obj": [group(2)]}) - self.assertEqual(status, 2) - self.assertIn("MeshTris", err) - - def test_a_manifest_that_lists_more_geometries_than_its_obj_holds_is_an_error_not_a_traceback(self): - src, _, _ = build(LEAVES, bounds=BOUNDS) - row = item(0x1000, "a.obj", [5, 2]) # the signature fits the second geometry only - row["MeshTris"] = [5, 2] - status, out, _ = self.guide(src, [row], {"a.obj": [group(5)]}) # ... but the OBJ has one group - self.assertEqual(status, 1, out) - self.assertIn("the manifest lists", out) - self.assertIn("scored candidates are consistent", out) - - def test_a_manifest_with_no_models_says_what_is_wrong(self): - src, _, _ = build(LEAVES, bounds=BOUNDS) - status, _, err = self.guide(src, [], {"a.obj": [group(2)]}) - self.assertEqual(status, 2) - self.assertIn("found no model in its window", err) - - def test_json_over_the_dehydrated_input_is_refused_before_it_is_read(self): - src, _, _ = build(LEAVES, bounds=BOUNDS) - blas = os.path.join(self.dir, "blas.bin") - status, _, err = self.guide(src, [item(0x1000, "a.obj", [2])], {"a.obj": [group(2)]}, - ["--json", blas]) - self.assertEqual(status, 2) - self.assertIn("--json would overwrite", err) - with open(blas, "rb") as f: - self.assertEqual(f.read(), src) - - def test_json_over_the_manifest_is_refused(self): - src, _, _ = build(LEAVES, bounds=BOUNDS) - manifest = os.path.join(self.dir, "manifest.json") - status, _, err = self.guide(src, [item(0x1000, "a.obj", [2])], {"a.obj": [group(2)]}, - ["--json", manifest]) - self.assertEqual(status, 2) - self.assertIn("--json would overwrite", err) - with open(manifest, encoding="utf-8") as f: - self.assertEqual(len(json.load(f)["Items"]), 1) - - def test_json_over_the_descriptor_is_refused(self): - src, _, _ = build(LEAVES, bounds=BOUNDS) - descriptor = os.path.join(self.dir, "instance208.bin") - data = bytes(0x50) + struct.pack("<12f", *[v for row in SHIFTED for v in row]) + bytes(60) - with open(descriptor, "wb") as f: - f.write(data) - status, _, err = self.guide(src, [item(0x1000, "a.obj", [2])], {"a.obj": [group(2)]}, - ["--descriptor", descriptor, "--json", descriptor]) - self.assertEqual(status, 2) - self.assertIn("--json would overwrite", err) - with open(descriptor, "rb") as f: - self.assertEqual(f.read(), data) - - def test_json_over_the_write_export_is_refused(self): - src, _, _ = build(LEAVES, bounds=BOUNDS) - out_dir = os.path.join(self.dir, "out") - os.makedirs(out_dir) - status, _, err = self.guide(src, [item(0x1000, "a.obj", [2])], {"a.obj": [group(2)]}, - ["--write", out_dir, "--json", os.path.join(out_dir, "export.json")]) - self.assertEqual(status, 2) - self.assertIn("--write's export.json", err) - - def test_json_over_a_write_vertex_buffer_is_refused(self): - src, _, _ = build(LEAVES, bounds=BOUNDS) - out_dir = os.path.join(self.dir, "out") - status, _, err = self.guide(src, [item(0x1000, "a.obj", [2])], {"a.obj": [group(2)]}, - ["--write", out_dir, "--json", os.path.join(out_dir, "g0_f3.bin")]) - self.assertEqual(status, 2) - self.assertIn("--write's g0_f3.bin", err) - # Refused before the export runs: no buffer and no export.json were written. - self.assertFalse(os.path.exists(os.path.join(out_dir, "export.json"))) - - def test_json_over_a_write_index_buffer_is_refused(self): - src, _, _ = build(LEAVES, bounds=BOUNDS) - out_dir = os.path.join(self.dir, "out") - status, _, err = self.guide(src, [item(0x1000, "a.obj", [2])], {"a.obj": [group(2)]}, - ["--write", out_dir, "--json", os.path.join(out_dir, "g0_tri.bin")]) - self.assertEqual(status, 2) - self.assertIn("--write's g0_tri.bin", err) - self.assertFalse(os.path.exists(os.path.join(out_dir, "export.json"))) - - def test_json_over_a_later_geometry_buffer_is_refused(self): - # Two matched geometries: the report must not land on the second one's buffers either. - src, _, _ = build([(0, 0x81, 0, 1, 0x09), (1, 0x81, 0, 1, 0x09)], bounds=BOUNDS) - out_dir = os.path.join(self.dir, "out") - status, _, err = self.guide(src, [item(0x1000, "a.obj", [2, 2])], {"a.obj": [group(2), group(2)]}, - ["--write", out_dir, "--json", os.path.join(out_dir, "g1_tri.bin")]) - self.assertEqual(status, 2) - self.assertIn("--write's g1_tri.bin", err) - self.assertFalse(os.path.exists(os.path.join(out_dir, "export.json"))) - - def test_json_beside_the_write_buffers_still_works(self): - src, _, _ = build(LEAVES, bounds=BOUNDS) - out_dir = os.path.join(self.dir, "out") - report = os.path.join(self.dir, "report.json") - status, out, _ = self.guide(src, [item(0x1000, "a.obj", [2])], {"a.obj": [group(2)]}, - ["--write", out_dir, "--json", report]) - self.assertEqual(status, 0, out) - with open(os.path.join(out_dir, "g0_f3.bin"), "rb") as f: - self.assertEqual(len(f.read()), 4 * 12) - with open(report, encoding="utf-8") as f: - self.assertTrue(json.load(f)["consistent"]) - - def test_json_over_an_unwritable_target_is_one_error_line(self): - src, _, _ = build(LEAVES, bounds=BOUNDS) - nested = os.path.join(self.dir, "missing_dir", "report.json") - status, _, err = self.guide(src, [item(0x1000, "a.obj", [5, 2, 3])], - {"a.obj": [group(5), group(2), group(3)]}, ["--json", nested]) - self.assertEqual(status, 2) - self.assertIn("cannot write", err) - self.assertNotIn("Traceback", err) - - def test_json_to_its_own_path_still_writes_the_report(self): - src, _, _ = build(LEAVES, bounds=BOUNDS) - report = os.path.join(self.dir, "report.json") - status, out, _ = self.guide(src, [item(0x1000, "a.obj", [5, 2, 3])], - {"a.obj": [group(5), group(2), group(3)]}, ["--json", report]) - self.assertEqual(status, 0, out) - with open(report, encoding="utf-8") as f: - body = json.load(f) - self.assertTrue(body["consistent"]) - self.assertEqual(body["matched"]["geometry"], [1]) - - def test_write_produces_the_buffers_bvh_rehydrate_reads(self): - src, _, _ = build(LEAVES, bounds=BOUNDS) - out = os.path.join(self.dir, "written") - status, text, _ = self.guide(src, [item(0x1000, "a.obj", [5, 2, 3])], - {"a.obj": [group(5), group(2), group(3)]}, ["--write", out]) - self.assertEqual(status, 0, text) - with open(os.path.join(out, "export.json"), encoding="utf-8") as f: - rows = json.load(f) - self.assertEqual(len(rows), 1) # only the geometry the BLAS uses is written - row = rows[0] - self.assertEqual((row["drawable_geometry"], row["vertices"], row["triangles"]), (1, 4, 2)) - self.assertIsNone(row["transform"]) - with open(os.path.join(out, row["vb"]), "rb") as f: - vb = f.read() - with open(os.path.join(out, row["ib"]), "rb") as f: - ib = f.read() - self.assertEqual((len(vb), len(ib)), (4 * 12, 2 * 12)) - geometry = R.Geometry(vb, row["stride"], ib, False) - self.assertEqual([geometry.triangle(0), geometry.triangle(1)], list(QUAD_FACES)) - - def test_write_stores_nothing_when_no_candidate_is_consistent(self): - src, _, _ = build(LEAVES, bounds=BOUNDS) - moved = [(x + 0.5, y, z) for x, y, z in QUAD] - out = os.path.join(self.dir, "nothing") - status, text, _ = self.guide(src, [item(0x1000, "a.obj", [2])], {"a.obj": [(moved, QUAD_FACES)]}, - ["--write", out]) - self.assertEqual(status, 1, text) - self.assertIn("nothing written", text) - self.assertFalse(os.path.exists(out)) - - def test_the_shader_rule_is_not_applied_without_every_hash(self): - src, _, _ = build(LEAVES, bounds=BOUNDS) - status, out, _ = self.guide(src, [item(0x1000, "a.obj", [2, 7])], {"a.obj": [group(2), group(7)]}, - ["--skip-shaders", "12345678"]) - self.assertEqual(status, 0, out) - self.assertIn("shader rule not applied", out) - - def test_json_in_a_missing_directory_is_one_error_line(self): - src, _, _ = build(LEAVES, bounds=BOUNDS) - nested = os.path.join(self.dir, "nodir", "r.json") - status, _, err = self.guide(src, [item(0x1000, "a.obj", [2])], {"a.obj": [group(2)]}, - ["--json", nested]) - self.assertEqual(status, 2, err) - self.assertIn("cannot write", err) - self.assertNotIn("Traceback", err) - self.assertFalse(os.path.exists(nested)) - - def test_readonly_json_is_one_error_line(self): - src, _, _ = build(LEAVES, bounds=BOUNDS) - ro = os.path.join(self.dir, "ro.json") - with open(ro, "w", encoding="utf-8") as f: - f.write("{}") - os.chmod(ro, 0o444) - try: - try: - with open(ro, "a", encoding="utf-8"): - pass - self.skipTest("the file is still writable (running as root, or Windows)") - except OSError: - pass - status, _, err = self.guide(src, [item(0x1000, "a.obj", [2])], {"a.obj": [group(2)]}, - ["--json", ro]) - self.assertEqual(status, 2, err) - self.assertIn("cannot write", err) - self.assertNotIn("Traceback", err) - finally: - os.chmod(ro, 0o644) - - -class TestPieces(unittest.TestCase): - def test_leaf_signature_counts_a_paired_leaf_twice(self): - self.assertEqual(M.leaf_signature(build([(0, 0x81, 0, 1, 0x09)], bounds=BOUNDS)[0]), [2]) - self.assertEqual(M.leaf_signature(build([(0, 0x01, 0, None, 0x09)], bounds=BOUNDS)[0]), [1]) - self.assertEqual(M.leaf_signature(build([(0, 0x01, 0, None, 0x09), (1, 0x01, 0, None, 0x09)], bounds=BOUNDS)[0]), - [1, 1]) - - def test_leaf_signature_applies_the_header_offset(self): - src, _, _ = build(LEAVES, bounds=BOUNDS) - self.assertEqual(M.leaf_signature(bytes(0x100) + src, 0x100), [2]) - - def test_embeddings_are_ordered_by_default(self): - self.assertEqual(M.embeddings([2, 3], [2, 3, 3], 8), [[0, 1], [0, 2]]) - self.assertEqual(M.embeddings([3, 2], [2, 3, 3], 8), []) - self.assertEqual(M.embeddings([3, 2], [2, 3, 3], 8, ordered=False), [[1, 0], [2, 0]]) - self.assertEqual(len(M.embeddings([1], [1] * 20, 5)), 5) # the cap holds - - def test_embeddings_prune_impossible_suffixes(self): - # Count triangle-count comparisons so the regression doesn't depend on machine speed. - class Count(int): - __hash__ = int.__hash__ - - def __eq__(self, other): - nonlocal comparisons - comparisons += 1 - return int.__eq__(self, other) - - def __ne__(self, other): - return not self == other - - cases = [ - (True, [1] * 8 + [2], [2] + [1] * 16, []), # the only 2 comes too early - (False, [1] * 6 + [2, 2], [2] + [1] * 8, []), # two distinct 2s are needed - (True, [1] * 8 + [2], [1] * 8 + [2] + [1] * 8, [list(range(9))]), - ] - for ordered, signature, counts, expected in cases: - with self.subTest(ordered=ordered, counts=counts): - comparisons = 0 - self.assertEqual(M.embeddings(signature, list(map(Count, counts)), 2, ordered), expected) - self.assertLess(comparisons, 4096) - - def test_embeddings_keep_first_matches_in_index_order(self): - counts = [7] * 8 + [1, 2, 1, 2, 1] - signature = [1, 2, 1] - for ordered in (True, False): - choices = itertools.combinations if ordered else itertools.permutations - expected = [list(indices) for indices in choices(range(len(counts)), len(signature)) - if [counts[i] for i in indices] == signature] - for cap in (0, 1, 3, len(expected) + 1): - with self.subTest(ordered=ordered, cap=cap): - self.assertEqual(M.embeddings(signature, counts, cap, ordered), expected[:cap]) - self.assertEqual(M.embeddings([], counts, 1, ordered), [[]]) - self.assertEqual(M.embeddings([], counts, 0, ordered), []) - - def test_read_groups_rebases_faces_per_group(self): - with tempfile.TemporaryDirectory() as directory: - path = os.path.join(directory, "a.obj") - write_obj(path, [(QUAD, QUAD_FACES), (QUAD, [(0, 1, 2)])]) - groups = M.read_groups(path) - self.assertEqual([len(positions) for positions, _ in groups], [4, 4]) - self.assertEqual(groups[0][1], QUAD_FACES) - self.assertEqual(groups[1][1], [(0, 1, 2)]) # second group's faces start at its own first vertex - self.assertEqual(groups[1][0], QUAD) - - def test_read_transform_reads_the_matrix_at_0x50(self): - with tempfile.TemporaryDirectory() as directory: - path = os.path.join(directory, "instance208.bin") - with open(path, "wb") as f: - f.write(bytes(0x50) + struct.pack("<12f", *[v for row in SHIFTED for v in row]) + bytes(60)) - self.assertEqual(M.read_transform(path), SHIFTED) - - def test_shader_hashes_parse_from_a_list(self): - self.assertEqual(M.parse_shader_hashes("0xAA, bb"), frozenset({0xAA, 0xBB})) - self.assertEqual(M.parse_shader_hashes(""), frozenset()) - self.assertEqual(M.parse_shader_hashes(None), frozenset()) - - def test_json_directory_is_refused_before_reading_inputs(self): - with tempfile.TemporaryDirectory() as directory: - err = io.StringIO() - with contextlib.redirect_stderr(err): - rc = M.main([os.path.join(directory, "missing.bvh"), - os.path.join(directory, "missing.json"), "--json", directory]) - self.assertEqual(rc, 2) - self.assertIn("is a directory", err.getvalue()) - - def test_json_write_failure_preserves_previous_report(self): - with tempfile.TemporaryDirectory() as directory: - previous = '{"previous": true}' - path = os.path.join(directory, "report.json") - with open(path, "w", encoding="utf-8", newline="\n") as f: - f.write(previous) - with mock.patch.object(M, "replace_retry", side_effect=OSError(13, "Permission denied")): - with self.assertRaises(OSError): - M.write_json_report(path, {"signature": [], "consistent": False}) - with open(path, encoding="utf-8") as f: - self.assertEqual(f.read(), previous) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/test_bvh_packing_check.py b/tests/test_bvh_packing_check.py deleted file mode 100644 index a79d9f54e..000000000 --- a/tests/test_bvh_packing_check.py +++ /dev/null @@ -1,300 +0,0 @@ -"""Synthetic dehydrated BLASes for tools/bvh_packing_check.py: a clean two-level tree passes, and each broken -invariant is reported under its own reason. Also scans a small fake archive with a split stream. No game data. - - python -I tests/test_bvh_packing_check.py -""" -import contextlib -import io -import json -import os -import struct -import sys -import tempfile -import unittest -import zlib - -ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) -sys.path.insert(0, os.path.join(ROOT, "tools")) - -import bvh_packing_check as C # noqa: E402 -import bvh_rehydrate as R # noqa: E402 - -FLAGS = 0x80000000 | R.FLAG_DEHYDRATED | 0x00020006 -ELEMENTS, NODES = 0x100, 0x200 -BOUNDS = (0.0, 0.0, 0.0, 4.0, 2.0, 1.0) -GOOD_ORDER = 0x09 - - -def ptr(offset, kind): - return (offset >> 6) << 3 | kind - - -def leaf(i): - return ptr(ELEMENTS + 64 * i, R.TRI0) - - -def group(nodes, wide=False): - """nodes: [(children, {bit: value})] -> group bytes (node words, child pointers, stored values).""" - words, kids, values = [], [], [] - for children, overrides in nodes: - mask = 0 - for bit in sorted(overrides): - mask |= 1 << bit - values.append(overrides[bit]) - words.append(len(children) << 24 | mask) - kids += children - body = struct.pack("<%dI" % len(words), *words) + struct.pack("<%dI" % len(kids), *kids) - if wide: - return body + struct.pack("<%df" % len(values), *values) - return body + struct.pack("<%dH" % len(values), *(R.float_to_half(v) for v in values)) - - -def build(level0=None, level1=None, orders=None, n_leaves=4, flags=FLAGS, root=None, total=0x300, table=None): - """Four leaves; level 0: two BOX16 nodes over leaves (0, 1) and (2, 3); level 1: the BOX16 root over both.""" - a, b = ptr(NODES, R.BOX16), ptr(NODES + 64, R.BOX16) - root = ptr(NODES + 128, R.BOX16) if root is None else root - level0 = [([leaf(0), leaf(1)], {}), ([leaf(2), leaf(3)], {})] if level0 is None else level0 - level1 = [([a, b], {})] if level1 is None else level1 - src = bytearray(total) - src[0:64] = struct.pack("<4I6f6I", flags, total // 64 - 1, 0, n_leaves, *BOUNDS, NODES, 0, root, ELEMENTS, - 0x40, R.NO_TRANSFORM) - orders = [GOOD_ORDER] * n_leaves if orders is None else orders - chunk = bytes(3 * n_leaves) + bytes([1] * n_leaves) + bytes(3 * n_leaves) + b"\xff" * (3 * n_leaves) + bytes(orders) - src[ELEMENTS:ELEMENTS + len(chunk)] = chunk - g0, g1 = group(level0), group(level1) - src[NODES:NODES + len(g0)] = g0 - src[NODES + 128:NODES + 128 + len(g1)] = g1 - table = [(0, 128), (128, 192)] if table is None else table - lv = b"".join(struct.pack("<2I", x, y) for x, y in table) + struct.pack(" two vertices in one slot - self.assertEqual(fails(build(orders=[GOOD_ORDER, 0x05, GOOD_ORDER, 0x05])), {"leaf_vertex_order": 2}) - - def test_level_table_out_of_order(self): - self.assertEqual(fails(build(table=[(0, 100), (128, 192)])), {"level_table": 1}) - - def test_levels_past_table(self): - self.assertEqual(fails(build(table=[(0, 128), (128, 0x300)])), {"levels_past_table": 1}) - - def test_group_overflow(self): - # a single BOX16 node (64 bytes) cannot hold a word, four children and 24 halves (4 + 16 + 48 bytes) - many = {bit: 0.5 for bit in range(24)} - level0 = [([leaf(0), leaf(1), leaf(2), leaf(3)], many)] - src = build(level0=level0, level1=[([ptr(NODES, R.BOX16)], {})], table=[(0, 64), (64, 128)], - root=ptr(NODES + 64, R.BOX16)) - self.assertIn("group_overflow", fails(src)) - - def test_root_not_a_node(self): - self.assertEqual(fails(build(root=ptr(NODES + 192, R.BOX16))), {"root_not_a_node": 1}) - - def test_root_leaf(self): - src = build(n_leaves=1, root=leaf(0), level0=[], level1=[], table=[]) - res = C.check_stream(src) - self.assertEqual(dict(res.fails), {}) - self.assertEqual(res.stats["root_leaf"], 1) - - -def payload(structure): - """A whole bvh4 payload: the 0x100 prefix with the wrapper words, then the structure.""" - end = 0x100 + len(structure) - prefix = bytearray(0x100) - struct.pack_into("" + bytes(64), bad, big[:0x10000], big[0x10000:]]) - for workers, window in ((1, 1 << 20), (2, 64)): - tally, _ = C.scan_archive(path, workers, window, progress=False) - rep = tally.report() - self.assertEqual((rep["checked"], rep["passed"]), (3, 2), (workers, window)) - self.assertEqual(rep["fail_streams"], {"leaf_vertex_order": 1}) - self.assertEqual(rep["kinds"].get("bvh4-chunk-joined"), 1) - self.assertEqual(rep["kinds"].get("continuation"), 1) - self.assertNotIn("raw", rep["kinds"]) - - def test_stream_starting_at_window_boundary_is_not_dropped(self): - good_z = zlib.compress(payload(build())) - bad_z = zlib.compress(payload(build(orders=[GOOD_ORDER, 0x05, GOOD_ORDER, GOOD_ORDER]))) - # Header has data_start = 16; with window = 64, window 0 is [16, 80). - # Place good_z at offset 79 (end - 1) so its 2-byte zlib header straddles 79..80, - # and place bad_z on an exact later window boundary to verify no double-counting. - window = 64 - pad_before_good = (16 + window - 1) - 16 - after_good = 16 + pad_before_good + len(good_z) - next_boundary = 16 + ((after_good - 16 + window - 1) // window) * window - if next_boundary == after_good: - next_boundary += window - pad_before_bad = next_boundary - after_good - raw = b"RPF9" + struct.pack(" the five per-chunk arrays.""" - out = bytearray() - for g, *_ in leaves: - out += g.to_bytes(3, "little") - for _, fl, *_ in leaves: - out.append(fl) - for _, _, p0, *_ in leaves: - out += p0.to_bytes(3, "little") - for _, _, _, p1, _ in leaves: - out += (0xFFFFFF if p1 is None else p1).to_bytes(3, "little") - for *_, order in leaves: - out.append(order) - return bytes(out) - - -def box_group(nodes, wide): - """nodes: [(child pointers, {bit: stored value})] -> one compressed group.""" - words, kids, values = [], [], [] - for children, overrides in nodes: - mask = 0 - for bit in sorted(overrides): - mask |= 1 << bit - values.append(overrides[bit]) - words.append(len(children) << 24 | mask) - kids += children - body = struct.pack("<%dI" % len(words), *words) + struct.pack("<%dI" % len(kids), *kids) - return body + (struct.pack("<%df" % len(values), *values) if wide else struct.pack("<%dH" % len(values), *values)) - - -def level_table(pairs): - return b"".join(struct.pack("<2I", a, b) for a, b in pairs) + struct.pack("> 6) << 3 | kind - - -def build(leaves, root_wide=True, overrides=None, compression=R.NO_TRANSFORM, bounds=(0, 0, 0, 1, 1, 1), - flags=BLAS_DEHYDRATED): - """One box node over up to four leaves. Layout: header, parent table at 0x40, leaves at 0x100, node at 0x200.""" - total, elements, parents, nodes = 0x300, 0x100, 0x40, 0x200 - src = bytearray(total) - leaf_ptrs = [ptr(elements + 64 * i, R.TRI0) for i in range(len(leaves))] - root = ptr(nodes, R.BOX32 if root_wide else R.BOX16) - src[0:64] = header(total, len(leaves), bounds, nodes, root, elements, parents, compression, flags) - chunk = leaf_chunk(leaves) - src[elements:elements + len(chunk)] = chunk - grp = box_group([(leaf_ptrs, overrides or {})], root_wide) - src[nodes:nodes + len(grp)] = grp - lv = level_table([(128, 128)] if root_wide else [(0, 64)]) - src[total - len(lv):] = lv - return bytes(src), root, leaf_ptrs - - -def floats(buf, at, n): - return struct.unpack_from("<%df" % n, buf, at) - - -QUADS = R.Geometry(struct.pack("<12f", 0, 0, 0, 1, 0, 0, 0, 1, 0, 1, 1, 0), indices=struct.pack("<6I", 0, 1, 2, 2, 1, 3)) - - -class TestLeaves(unittest.TestCase): - def test_single_and_paired_leaf(self): - # leaf 0: triangle 0 alone, vertex order 0x09 = (1, 2) -> slots (0, 1, 2); leaf 1: triangles 0 and 1 paired - src, _, _ = build([(0, 0x01, 0, None, 0x09), (0, 0x81, 0, 1, 0x09)]) - out = R.rehydrate(src, [QUADS]) - self.assertEqual(floats(out, 0x100, 9), (0, 0, 0, 1, 0, 0, 0, 1, 0)) - self.assertTrue(all(math.isnan(x) for x in floats(out, 0x100 + 36, 3))) - self.assertEqual(struct.unpack_from("<4I", out, 0x100 + 48), (0x0001, 0, R.INVALID, 0x009)) - # the paired leaf's fourth vertex is triangle 1's third index (neither 0x20 nor 0x80 in the order byte) - self.assertEqual(floats(out, 0x140 + 36, 3), (1, 1, 0)) - self.assertEqual(struct.unpack_from("<4I", out, 0x140 + 48), (0x0081, 0, 1, 0x009)) - - def test_vertex_order_moves_slots(self): - # order 0x06: first = 2, second = 1, third = (2 ^ 3) - 1 = 0 -> vertices land in slots 1, 0, 2 - src, _, _ = build([(0, 0x01, 0, None, 0x06)]) - out = R.rehydrate(src, [QUADS]) - self.assertEqual(floats(out, 0x100, 9), (1, 0, 0, 0, 0, 0, 0, 1, 0)) - self.assertEqual(struct.unpack_from(" 0x40 + 16 - self.assertEqual(struct.unpack_from(" 2, 4, 1; translation on: x bounds [10, 12] -> centre 11, y and z straddle 0 - word = 0x80000000 | 0x40000000 | 0x7F << 16 | 0x81 << 8 | 0x80 - g = R.Geometry(struct.pack("<9f", 11, 1, 2, 12, 0, 0, 10, 0, 0)) - src, _, _ = build([(0, 0x01, 0, None, 0x09)], compression=word, bounds=(10, -1, -1, 12, 1, 3)) - self.assertEqual(floats(R.rehydrate(src, [g]), 0x100, 3), (0, 4, 2)) - - def test_rotation_table(self): - self.assertEqual(R.rotation(0), ((1, 0, 0), (0, 1, 0), (0, 0, 1))) - r = R.rotation(16) # index 16: x and y step 0, z step 1 (pi/8) - self.assertAlmostEqual(r[0][0], math.cos(math.pi / 8), places=6) - - -class TestErrorsAndCli(unittest.TestCase): - def test_errors(self): - src, _, _ = build([(0, 0x01, 0, None, 0x09)]) - with self.assertRaisesRegex(ValueError, "geometry index 0"): - R.rehydrate(src, []) - plain = bytearray(src) - struct.pack_into(" bytes: - """A made-up FSSM blob shader_disasm.py accepts: the code section offset at 0xC0, code 0x28 bytes into it, a - few filler words that differ per seed and the closing s_endpgm.""" - head = bytearray(b"FSSM" + b"\x01\x01" + bytes(0xF0 - 6)) - struct.pack_into(" bytes: - """DXBC { SFI0, ILDN = the module's PDB path, DXIL = program header + XDAT { 0x12, 0x0D = XBCH + zlib(blob), - 0x07 = bitcode } }: the parts of the builder's containers the tools read (docs/embedded_shaders.md section 2).""" - packed = zlib.compress(blob) - xbch = b"XBCH" + struct.pack(" bytes: - """Containers between unrelated bytes, as a DLL holds them.""" - return b"MZ" + b"\0" * 126 + b"".join(c + b"\xcc" * 12 for c in containers) - - -def tool(name: str, *args: str) -> subprocess.CompletedProcess: - return subprocess.run([sys.executable, "-I", os.path.join(ROOT, "tools", name), *args], - capture_output=True, text=True) - - -class IndexKey(unittest.TestCase): - """fssm_sha256 is the SHA-256 of the FSSM blob fssm_unpack.py inflates from the container's XBCH record: the - bytes runtime/src/shader_library.h's fssm_program() inflates from the container the DLL passes to slot 62.""" - - def test_the_extracted_layout_gives_the_translator_the_key_and_the_stage(self): - blobs = {"SortKeys": fssm_blob(1), "WriteNodes": fssm_blob(2)} - with tempfile.TemporaryDirectory() as t: - dll = os.path.join(t, "builder.dll") - with open(dll, "wb") as f: - f.write(dll_like(*(builder_container(name, blob) for name, blob in blobs.items()))) - out = os.path.join(t, "bvh") - r = tool("pe_shader_containers.py", dll, "--extract", out) - self.assertEqual(r.returncode, 0, r.stdout + r.stderr) - r = tool("fssm_unpack.py", out, "--carve-index", os.path.join(out, "index.json")) - self.assertEqual(r.returncode, 0, r.stdout + r.stderr) - os.makedirs(os.path.join(out, "disasm")) - rdna2spirv._STAGES = None # stage_of() reads /index.json once per process - self.addCleanup(setattr, rdna2spirv, "_STAGES", None) - for name, blob in blobs.items(): - with open(os.path.join(out, "fssm", name + ".fssm"), "rb") as f: - self.assertEqual(f.read(), blob) - listing = os.path.join(out, "disasm", name + ".s") - meta = shader_meta.collect(listing, name, [[]], [[]]) - self.assertEqual(meta.get("fssm_sha256"), hashlib.sha256(blob).hexdigest()) - self.assertNotIn("fspx_code_sha256", meta) - self.assertEqual(rdna2spirv.stage_of(name, listing), "cs") - - def test_a_container_without_an_xbch_record_gets_no_program(self): - """Such a container is extracted and then counted by the step as not translated, never dropped.""" - bare = container([(b"SFI0", bytes(8)), (b"ILDN", ildn("NoProgram")), (b"DXIL", b"\0" * 24)]) - with tempfile.TemporaryDirectory() as t: - dll = os.path.join(t, "builder.dll") - with open(dll, "wb") as f: - f.write(dll_like(bare, builder_container("SortKeys", fssm_blob(1)))) - out = os.path.join(t, "bvh") - self.assertEqual(tool("pe_shader_containers.py", dll, "--extract", out).returncode, 0) - r = tool("fssm_unpack.py", out, "--carve-index", os.path.join(out, "index.json")) - self.assertEqual(r.returncode, 0, r.stdout + r.stderr) - self.assertEqual(sorted(os.listdir(os.path.join(out, "fssm"))), ["SortKeys.fssm"]) - self.assertTrue(os.path.isfile(os.path.join(out, "NoProgram.dxbc"))) - - -class BvhStage(unittest.TestCase): - """Which tools bvh_shaders() runs and what it reports. Each stand-in writes what the real tool writes last.""" - - def setUp(self): - self.tmp = tempfile.TemporaryDirectory() - self.addCleanup(self.tmp.cleanup) - self.work = os.path.join(self.tmp.name, "work") - self.game = os.path.join(self.tmp.name, "game") - os.makedirs(self.game) - self.dll = os.path.join(self.game, make_game.BVH_DLL) - self.programs = {"SortKeys": fssm_blob(1), "WriteNodes": fssm_blob(2), "CopyNodes": fssm_blob(3)} - self.untranslated = set() # the programs the stand-in translator has no rule for - self.write_dll() - self.unpacked = os.path.join(self.work, "shaders", "bvh") - self.spirv = os.path.join(self.work, "shaders", "spirv", "bvh") - self.calls, self.logs = [], [] - - def write_dll(self): - with open(self.dll, "wb") as f: - f.write(dll_like(*(builder_container(name, blob) for name, blob in self.programs.items()))) - - def fake_translate(self, *args): - """rdna2spirv.py: a module and an index entry for every listing it has a rule for.""" - out = args[args.index("--out") + 1] - os.makedirs(out, exist_ok=True) - index = {} - for listing in sorted(os.listdir(args[0])): - name = listing[:-2] - if not listing.endswith(".s") or name in self.untranslated: - continue - with open(os.path.join(os.path.dirname(args[0]), "fssm", name + ".fssm"), "rb") as f: - index[name] = {"stage": "cs", "fssm_sha256": hashlib.sha256(f.read()).hexdigest()} - with open(os.path.join(out, name + ".spv"), "wb") as f: - f.write(b"module of " + name.encode()) - with open(os.path.join(out, "index.json"), "w", encoding="utf-8", newline="\n") as f: - json.dump(index, f) - - def fake_py(self, tool_name, *args): - self.calls.append((tool_name, args)) - if tool_name == "pe_shader_containers.py": - os.makedirs(self.unpacked, exist_ok=True) - for name in self.programs: - open(os.path.join(self.unpacked, name + ".dxbc"), "wb").close() - with open(os.path.join(self.unpacked, "index.json"), "w", encoding="utf-8", newline="\n") as f: - json.dump([{"name": n, "file": n + ".dxbc", "stage": "cs"} for n in self.programs], f) - elif tool_name == "fssm_unpack.py": - os.makedirs(os.path.join(self.unpacked, "fssm"), exist_ok=True) - for name, blob in self.programs.items(): - with open(os.path.join(self.unpacked, "fssm", name + ".fssm"), "wb") as f: - f.write(blob) - with open(os.path.join(self.unpacked, "fssm_index.json"), "w", encoding="utf-8", newline="\n") as f: - json.dump([{"name": n} for n in self.programs], f) - elif tool_name == "shader_disasm.py": - os.makedirs(os.path.join(self.unpacked, "disasm"), exist_ok=True) - for name in self.programs: - with open(os.path.join(self.unpacked, "disasm", name + ".s"), "w", encoding="utf-8", - newline="\n") as f: - f.write("s_endpgm\n") - elif tool_name == "rdna2spirv.py": - self.fake_translate(*args) - - def run_step(self, signature="llvm-mc 23", emulate=False, fallbacks=(), py=None): - self.calls, self.logs = [], [] - with mock.patch.object(make_game, "py", py or self.fake_py), \ - mock.patch.object(make_game, "log", self.logs.append): - make_game.bvh_shaders(self.game, self.work, signature, 3, emulate=emulate, fallbacks=fallbacks) - return [name for name, _ in self.calls] - - def test_runs_once_then_only_reports(self): - self.assertEqual(self.run_step(), TOOLS) - (_, extract), (_, unpack), (_, disasm), (_, translate) = self.calls - self.assertEqual(extract, (self.dll, "--extract", self.unpacked)) - self.assertEqual(unpack, (self.unpacked, "--carve-index", os.path.join(self.unpacked, "index.json"))) - self.assertEqual(disasm, (os.path.join(self.unpacked, "fssm"), "--unpack-index", - os.path.join(self.unpacked, "fssm_index.json"), "--out", - os.path.join(self.unpacked, "disasm"), "--mcpu", "gfx1013", "--jobs", 3)) - # The listings sit beside index.json and fssm/, where rdna2spirv.py looks for the stage and the FSSM blob. - self.assertEqual(translate, (os.path.join(self.unpacked, "disasm"), "--out", self.spirv, "--no-asm", - "--max-shared-memory", 32768)) - self.assertTrue(os.path.isfile(os.path.join(self.spirv, "bvh_build.json"))) - self.assertIn(f"shaders: 3 of 3 {make_game.BVH_DLL} programs translated", self.logs) - self.assertEqual(self.run_step(), []) - self.assertEqual(self.logs, [f"shaders: 3 of 3 {make_game.BVH_DLL} programs translated"]) - - def test_the_real_tools_fill_the_folder_and_a_second_run_leaves_no_duplicates(self): - """Extraction, unpacking and disassembly by the repository's tools (llvm-mc stood in for), twice: the - second run must replace the first one's containers, where pe_shader_containers.py alone would add - _NN.dxbc beside them and those would be translated as more programs.""" - mc = os.path.join(self.tmp.name, "fake_mc.py") - with open(mc, "w", encoding="utf-8", newline="\n") as f: - f.write("print('\\ts_endpgm')\n") - - def run_tool(tool_name, *args): - self.calls.append((tool_name, args)) - if tool_name == "rdna2spirv.py": - return self.fake_translate(*args) - make_game.run([sys.executable, "-I", os.path.join(make_game.TOOLS, tool_name), *args], - stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) - - with mock.patch.dict(os.environ, {"LLVM_MC": f'"{sys.executable}" "{mc}"'}): - for signature in ("llvm-mc 23", "llvm-mc 24"): - self.assertEqual(self.run_step(signature=signature, py=run_tool), TOOLS) - names = sorted(self.programs) - self.assertEqual(sorted(f for f in os.listdir(self.unpacked) if f.endswith(".dxbc")), - [n + ".dxbc" for n in names]) - self.assertEqual(sorted(os.listdir(os.path.join(self.unpacked, "fssm"))), - [n + ".fssm" for n in names]) - self.assertEqual(sorted(os.listdir(os.path.join(self.unpacked, "disasm"))), - [n + ".s" for n in names]) - with open(os.path.join(self.spirv, "index.json"), encoding="utf-8") as f: - index = json.load(f) - self.assertEqual({n: index[n]["fssm_sha256"] for n in index}, - {n: hashlib.sha256(blob).hexdigest() for n, blob in self.programs.items()}) - self.assertIn(f"shaders: 3 of 3 {make_game.BVH_DLL} programs translated", self.logs) - self.assertEqual(self.run_step(signature="llvm-mc 24", py=run_tool), []) - - def test_no_dll_no_step(self): - os.remove(self.dll) - self.assertEqual(self.run_step(), []) - self.assertFalse(os.path.exists(self.spirv)) - self.assertFalse(os.path.exists(self.unpacked)) - - def test_a_dll_that_is_gone_takes_the_old_index_with_it(self): - """A work folder reused for a package without the DLL: the runtime loads /bvh/index.json whenever - it exists, so the index of the earlier run must not stay, and the DLL coming back runs the step again.""" - self.assertEqual(self.run_step(), TOOLS) - index, settings = os.path.join(self.spirv, "index.json"), os.path.join(self.spirv, "bvh_build.json") - self.assertTrue(os.path.isfile(index) and os.path.isfile(settings)) - os.remove(self.dll) - self.assertEqual(self.run_step(), []) - self.assertFalse(os.path.exists(index)) - self.assertFalse(os.path.exists(settings)) - self.assertEqual(self.logs, [f"shaders: no {make_game.BVH_DLL} in the game folder, so no BVH builder " - "programs to translate"]) - self.assertEqual(self.run_step(), []) # and again, with nothing left to remove - self.write_dll() - self.assertEqual(self.run_step(), TOOLS) - self.assertTrue(os.path.isfile(index) and os.path.isfile(settings)) - - def test_each_input_change_runs_it_again(self): - self.run_step() - self.assertEqual(self.run_step(signature="llvm-mc 24"), TOOLS) - self.assertEqual(self.run_step(signature="llvm-mc 24", emulate=True), TOOLS) - self.assertIn("--wave64-emulate", self.calls[3][1]) - flags = ("--no-float-controls",) - self.assertEqual(self.run_step(signature="llvm-mc 24", emulate=True, fallbacks=flags), TOOLS) - self.assertIn("--no-float-controls", self.calls[3][1]) - self.programs["CopyNodes"] = fssm_blob(4) - self.write_dll() - self.assertEqual(self.run_step(signature="llvm-mc 24", emulate=True, fallbacks=flags), TOOLS) - self.assertEqual(self.run_step(signature="llvm-mc 24", emulate=True, fallbacks=flags), []) - with mock.patch.object(make_game, "translation_sources_digest", return_value="another translator"): - self.assertEqual(self.run_step(signature="llvm-mc 24", emulate=True, fallbacks=flags), TOOLS) - with mock.patch.object(make_game, "BVH_MAX_SHARED_MEMORY", 65536): - self.assertEqual(self.run_step(signature="llvm-mc 24", emulate=True, fallbacks=flags), TOOLS) - self.assertEqual(self.calls[3][1][4:6], ("--max-shared-memory", 65536)) - - def test_an_untranslated_program_is_named_on_every_run_and_the_step_still_finishes(self): - """The translator has no rule for one program: its name and the counts are logged by the run that - translates and by every run that reuses the result. The others are published; nothing is skipped quietly.""" - self.untranslated = {"WriteNodes"} - for expected in (TOOLS, [], []): - self.assertEqual(self.run_step(), expected) - self.assertIn(f"shaders: 2 of 3 {make_game.BVH_DLL} programs translated", self.logs) - named = [line for line in self.logs if "NOT translated: WriteNodes." in line] - self.assertEqual(len(named), 1, self.logs) - self.assertIn("E_INVALIDARG", named[0]) - self.assertNotIn("SortKeys", named[0]) - with open(os.path.join(self.spirv, "index.json"), encoding="utf-8") as f: - self.assertEqual(sorted(json.load(f)), ["CopyNodes", "SortKeys"]) - self.assertFalse(os.path.exists(os.path.join(self.spirv, "WriteNodes.spv"))) - # Once the translator has the rule, the changed translator runs the step again and the line is gone. - self.untranslated = set() - with mock.patch.object(make_game, "translation_sources_digest", return_value="a translator with the rule"): - self.assertEqual(self.run_step(), TOOLS) - self.assertEqual([line for line in self.logs if "NOT translated" in line], []) - self.assertIn(f"shaders: 3 of 3 {make_game.BVH_DLL} programs translated", self.logs) - - def test_an_entry_the_runtime_cannot_find_counts_as_not_translated(self): - """rdna2spirv.py keeps an entry whose metadata failed as {"error": ...}: it has no fssm_sha256, so the - runtime skips it, and the step reports the program instead of counting its module.""" - real = self.fake_translate - - def no_key(*args): - real(*args) - path = os.path.join(self.spirv, "index.json") - with open(path, encoding="utf-8") as f: - index = json.load(f) - index["SortKeys"] = {"error": "ValueError: synthetic"} - with open(path, "w", encoding="utf-8", newline="\n") as f: - json.dump(index, f) - self.fake_translate = no_key - self.assertEqual(self.run_step(), TOOLS) - self.assertIn(f"shaders: 2 of 3 {make_game.BVH_DLL} programs translated", self.logs) - self.assertEqual(len([line for line in self.logs if "NOT translated: SortKeys." in line]), 1) - - def test_nothing_translated_fails_and_keeps_no_index(self): - self.untranslated = set(self.programs) - with self.assertRaises(SystemExit), mock.patch("sys.stderr", new_callable=io.StringIO) as err: - self.run_step() - self.assertIn(f"none of the {make_game.BVH_DLL} programs translated", err.getvalue()) - self.assertFalse(os.path.exists(os.path.join(self.spirv, "index.json"))) # nothing for the runtime to load - self.assertFalse(os.path.exists(os.path.join(self.spirv, "bvh_build.json"))) - self.untranslated = set() - self.assertEqual(self.run_step(), TOOLS) - - def test_missing_cached_module_or_index_is_rebuilt(self): - self.assertEqual(self.run_step(), TOOLS) - module = os.path.join(self.spirv, "SortKeys.spv") - os.remove(module) - self.assertEqual(self.run_step(), TOOLS) - with open(module, "rb") as f: - self.assertEqual(f.read(), b"module of SortKeys") - self.assertEqual(self.run_step(), []) - os.remove(os.path.join(self.unpacked, "index.json")) # the list of programs the report counts against - self.assertEqual(self.run_step(), TOOLS) - self.assertEqual(self.run_step(), []) - - def test_a_stopped_translation_leaves_no_marker_and_no_old_modules(self): - self.run_step() - open(os.path.join(self.spirv, "notes.txt"), "w").close() - - def stop(tool_name, *args): - if tool_name == "rdna2spirv.py": - raise KeyboardInterrupt - self.fake_py(tool_name, *args) - with self.assertRaises(KeyboardInterrupt): - self.run_step(signature="llvm-mc 24", py=stop) - self.assertFalse(os.path.exists(os.path.join(self.spirv, "index.json"))) - self.assertFalse(os.path.exists(os.path.join(self.spirv, "bvh_build.json"))) - self.assertFalse(os.path.exists(os.path.join(self.spirv, "SortKeys.spv"))) # from the run before - self.assertTrue(os.path.isfile(os.path.join(self.spirv, "notes.txt"))) - self.assertEqual(self.run_step(signature="llvm-mc 24"), TOOLS) - self.assertEqual(self.run_step(signature="llvm-mc 24"), []) - - -class ShadersStageWithTheDlls(unittest.TestCase): - """The whole shaders() stage with both DLLs in the game folder: the builder's step comes last, and neither it - nor the FSPX step makes the other or the game's shaders run again.""" - - def test_the_builder_runs_after_fspx_and_alone_when_only_its_dll_changes(self): - from test_fspx_shaders_stage import container as fspx_container, dll_like as fspx_dll, program - with tempfile.TemporaryDirectory() as t: - work, game = os.path.join(t, "work"), os.path.join(t, "game") - os.makedirs(game) - with open(os.path.join(game, make_game.FSPX_DLL), "wb") as f: - f.write(fspx_dll(fspx_container(program()))) - dll = os.path.join(game, make_game.BVH_DLL) - with open(dll, "wb") as f: - f.write(dll_like(builder_container("SortKeys", fssm_blob(1)))) - ran = [] - dxbc = os.path.join(work, "shaders", "dxbc") - bvh = os.path.join(work, "shaders", "bvh") - - def write(text, *parts): - os.makedirs(os.path.dirname(os.path.join(*parts)), exist_ok=True) - with open(os.path.join(*parts), "w", encoding="utf-8", newline="\n") as f: - f.write(text) - - def fake_py(tool_name, *args): - ran.append(tool_name) - builder = args[0].startswith(bvh) - if tool_name == "shader_carve.py": - write('[{"file": "shader.dxbc"}]', dxbc, "index.json") - elif tool_name == "pe_shader_containers.py": - write('[{"name": "SortKeys", "file": "SortKeys.dxbc", "stage": "cs"}]', bvh, "index.json") - elif tool_name == "fssm_unpack.py": - write('[{"name": "%s"}]' % ("SortKeys" if builder else "shader"), bvh if builder else dxbc, - "fssm_index.json") - elif tool_name == "shader_disasm.py": - # make_game checks that every unpacked shader of the corpus got a non-empty listing - write("s_endpgm\n", bvh if builder else dxbc, "disasm", - ("SortKeys" if builder else "shader") + ".s") - elif tool_name == "rdna2spirv.py": - out = args[args.index("--out") + 1] - # the FSPX step keeps its output only when the index names a compute program whose module is - # there, keyed by fspx_code_sha256 (make_game.fspx_cache_complete, tests/test_fspx_shaders_stage) - name = "SortKeys" if builder else "Upscale" - write('{"%s": {"stage": "cs", "fssm_sha256": "%s"}}' % (name, "a" * 64) if builder else - '{"%s": {"stage": "cs", "fspx_code_sha256": "%s"}}' % (name, "b" * 64), - out, "index.json") - write("", out, name + ".spv") - - def fake_translate(disasm, spirv, jobs, emulate=False, fallbacks=()): - ran.append("translate") - write("", spirv, "index.json") - - def stage(): - ran.clear() - with mock.patch.object(make_game, "py", fake_py), \ - mock.patch.object(make_game, "need", lambda *a: None), \ - mock.patch.object(make_game, "translate", fake_translate), \ - mock.patch.object(make_game, "llvm_mc_signature", return_value="llvm-mc 23"), \ - mock.patch.object(make_game, "log", lambda *a: None): - make_game.shaders(game, work, 2) - return list(ran) - - self.assertEqual(stage(), ["shader_carve.py", "fssm_unpack.py", "shader_disasm.py", "translate", - "fspx_unpack.py", "rdna2spirv.py", *TOOLS]) - self.assertEqual(stage(), []) - with open(dll, "wb") as f: - f.write(dll_like(builder_container("SortKeys", fssm_blob(2)))) - self.assertEqual(stage(), TOOLS) - with open(os.path.join(game, make_game.FSPX_DLL), "wb") as f: - f.write(fspx_dll(fspx_container(program() + b"\0\0\x80\xbf"))) - self.assertEqual(stage(), ["fspx_unpack.py", "rdna2spirv.py"]) - for sub in ((), ("fspx",), ("bvh",)): - self.assertTrue(os.path.isfile(os.path.join(work, "shaders", "spirv", *sub, "index.json"))) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/test_bvh_slot_check.py b/tests/test_bvh_slot_check.py deleted file mode 100644 index d712a1639..000000000 --- a/tests/test_bvh_slot_check.py +++ /dev/null @@ -1,209 +0,0 @@ -"""Synthetic controls for multi-slot BVH geometry checks.""" -import json -import os -import shutil -import struct -import subprocess -import sys -import tempfile -import unittest -import zlib -from collections import Counter -from pathlib import Path - -ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) -sys.path[:0] = [os.path.join(ROOT, "tools"), os.path.join(ROOT, "tests")] - -import bvh_slot_check as S -from test_bvh_geometry_check import BOUNDS, LEAVES, TRUE, build -from test_bvh_rehydrate import box_group, header, leaf_chunk, level_table, ptr - - -def translation(dx): - return ((1, 0, 0, dx), (0, 1, 0, 0), (0, 0, 1, 0)) - - -def tiled_block(dx): - """32 pairs of triangles, eight boxes of leaves, two boxes of boxes, then the root.""" - elements, nodes = 0x400, 0x1000 - body = bytearray(0x1800) - leaves = [(0, 0x81, 2 * i, 2 * i + 1, 0x09) for i in range(32)] - packed = leaf_chunk(leaves) - body[elements:elements + len(packed)] = packed - children = [ptr(elements + 64 * i, S.R.TRI0) for i in range(32)] - end = 0 - levels = [] - while len(children) > 1: - boxes = [(children[i:i + 4], {}) for i in range(0, len(children), 4)] - packed = box_group(boxes, True) - base = nodes + end - body[base:base + len(packed)] = packed - children = [ptr(base + 128 * i, S.R.BOX32) for i in range(len(boxes))] - end += 128 * len(boxes) - levels.append((end, end)) - body[:64] = header(len(body), 32, (dx, 0, 0, dx + 32, 1, 0), nodes, children[0], elements, 64) - table = level_table(levels) - body[-len(table):] = table - wrapper = bytearray(256) - struct.pack_into("> 4) << high) for q in bcpack_tables.BC1_QUADRANT] - for low, high in shifts - ] - return {"version": 1, "bc1": {"endpoints": [[0] * 6 for _ in range(256)], "selectors": selectors}} - - -@unittest.skipUnless(importlib.util.find_spec("numpy"), "install NumPy for calibrated export") -class CalibratedExport(unittest.TestCase): - def test_mode1_array_dds_writes_slice_major_subresources(self) -> None: - import calibrated_texture as ct - import tex_headers - - tile = 65536 - # A two-slice BC5 array with a standalone top mip and one packed-tail mip. - # Each source tile has one distinct constant block, in mip-major order. - tail0, tail1 = bytes([51, 0] + [0] * 14), bytes([102, 0] + [0] * 14) - top0, top1 = bytes([153, 0] + [0] * 14), bytes([204, 0] + [0] * 14) - source = b"".join(block * (tile // 16) for block in (tail0, tail1, top0, top1)) - expected_top = (top0 * (64 * 64), top1 * (64 * 64)) - expected_full = (expected_top[0] + tail0 * (32 * 32) - + expected_top[1] + tail1 * (32 * 32)) - with tempfile.TemporaryDirectory() as directory: - path = Path(directory) / "array.ttpf" - desc = fixtures.pack_etpf_record(256, 256, 2, 0, 83, 2, 1, 1, 4096) - fixtures.write_rds5_pool(path, [desc], [source]) - with closing(ct.ttpf.Pool(path)) as pool: - decoder = ct.LocalDecoder(pool, {"version": 1}) - dds = decoder.dds(0) - header = tex_headers.parse_dds_header(dds) - self.assertEqual((header["array_size"], header["mips"]), (2, 2)) - self.assertEqual(dds[148:], expected_full) - self.assertEqual(decoder.dds(0, mips=1)[148:], b"".join(expected_top)) - - def test_bc1_export_and_existing_output(self): - import calibrated_texture - try: - calibrated_texture.native() - except OSError as exc: - self.skipTest(f"build tools/bcpack_calibration first: {exc}") - with tempfile.TemporaryDirectory() as directory: - root = Path(directory) - pool = root / "pool.ttpf" - output = root / "result.dds" - profile = root / "profile.json" - _, linear, _ = fixtures.build_bc1_bcpack_pool(pool) - profile.write_text(json.dumps(synthetic_profile()), encoding="utf-8") - command = [sys.executable, "-IB", str(ROOT / "tools/ttpf_mips.py"), - "export", str(pool), "0", str(output), "--calibration", str(profile)] - run = subprocess.run(command, capture_output=True, text=True) - self.assertEqual(run.returncode, 0, run.stderr) - data = output.read_bytes() - self.assertEqual(data[:4], b"DDS ") - self.assertEqual(data[148:], b"".join(linear[i] for i in sorted(linear))) - self.assertEqual(subprocess.run(command, capture_output=True).returncode, 2) - self.assertEqual(output.read_bytes(), data) - profile.write_text('{"version": 99}', encoding="utf-8") - self.assertEqual(subprocess.run(command + ["--force"], capture_output=True).returncode, 2) - self.assertEqual(output.read_bytes(), data) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/test_calibrated_texture_extra.py b/tests/test_calibrated_texture_extra.py deleted file mode 100644 index 3367895e8..000000000 --- a/tests/test_calibrated_texture_extra.py +++ /dev/null @@ -1,2214 +0,0 @@ -"""Expanded stdlib-only unit tests for tools/calibrated_texture.py. - -Covers native loader wiring, array validation, zig/distance/accumulate helpers, -tile address mapping, BC1/BC3/BC4/BC5/BC7 block rebuilders, LocalDecoder chunk -decoding/caching/surface/DDS export paths, error handling, and CLI integration -using synthetic pools/profiles and unittest.mock (no game data). - - python -I tests/test_calibrated_texture_extra.py -v -""" -from __future__ import annotations - -import bisect -from contextlib import contextmanager, redirect_stderr, redirect_stdout -import ctypes -import hashlib -import importlib.util -import io -import json -import math -import os -from pathlib import Path -import struct -import sys -import tempfile -import unittest -from unittest import mock -import zlib - -ROOT = Path(__file__).resolve().parents[1] -TOOLS_DIR = ROOT / "tools" -TESTS_DIR = ROOT / "tests" -for _p in (str(TESTS_DIR), str(TOOLS_DIR)): - if _p not in sys.path: - sys.path.insert(0, _p) - -import bcpack # noqa: E402 -import bcpack_tables # noqa: E402 -import bcpack_tables_bptc as _bptc # noqa: E402 -import test_bcpack as tb # noqa: E402 -import test_ttpf_mips as ttm # noqa: E402 -import tex_headers # noqa: E402 -import ttpf_mips as ttpf # noqa: E402 -from test_calibrated_texture import synthetic_profile # noqa: E402 - - -# --------------------------------------------------------------------------- -# Minimal pure-stdlib NumPy shim for environments without NumPy installed. -# Only used when importlib.util.find_spec("numpy") is None. -# --------------------------------------------------------------------------- - -class _FakeDType: - """Minimal NumPy-like dtype descriptor supporting integers, bool, float, str, and Vn.""" - - _SPEC = { - "bool": ("b", 1, "?", False, False), - "b1": ("b", 1, "?", False, False), - "int8": ("i", 1, "b", True, False), - "i1": ("i", 1, "b", True, False), - "uint8": ("u", 1, "B", False, False), - "u1": ("u", 1, "B", False, False), - "int16": ("i", 2, "= db.itemsize else db - u_dt, i_dt = (da, db) if da.kind == "u" else (db, da) - if u_dt.itemsize >= i_dt.itemsize: - if u_dt.itemsize == 8: - return _FakeDType("uint64") - return _FakeDType(f"int{max(i_dt.itemsize, u_dt.itemsize * 2) * 8}") - return i_dt - - -def _infer_dtype(flat_vals): - if not flat_vals: - return _FakeDType("int64") - kinds = set() - for v in flat_vals: - if isinstance(v, (bytes, bytearray)): - kinds.add(("V", len(v))) - elif isinstance(v, bool): - kinds.add("b") - elif isinstance(v, int): - kinds.add("i") - elif isinstance(v, float): - kinds.add("f") - elif isinstance(v, str): - kinds.add("U") - else: - kinds.add("O") - if len(kinds) == 1: - k = next(iter(kinds)) - if isinstance(k, tuple) and k[0] == "V": - return _FakeDType(f"V{k[1]}") - if k == "b": - return _FakeDType("bool") - if k == "i": - lo = min(flat_vals) - hi = max(flat_vals) - if -0x8000000000000000 <= lo and hi <= 0x7FFFFFFFFFFFFFFF: - return _FakeDType("int64") - return _FakeDType("uint64") - if k == "f": - return _FakeDType("float64") - if k == "U": - return _FakeDType("str") - if kinds <= {"b", "i"}: - return _FakeDType("int64") - if kinds <= {"b", "i", "f"}: - return _FakeDType("float64") - return _FakeDType("object") - - -def _flatten_nested(obj): - if isinstance(obj, _FakeArray): - return obj.shape, obj._flat_list(), obj.dtype - if isinstance(obj, (list, tuple)): - if not obj: - return (0,), [], None - sub_shapes = [] - items = [] - sub_dtypes = [] - for elem in obj: - if isinstance(elem, (list, tuple, _FakeArray)): - sh, fl, dt = _flatten_nested(elem) - sub_shapes.append(sh) - items.extend(fl) - if dt is not None: - sub_dtypes.append(dt) - else: - sub_shapes.append(()) - items.append(elem) - if len(set(sub_shapes)) != 1: - raise ValueError("inhomogeneous shape") - shape = (len(obj),) + sub_shapes[0] - dt = sub_dtypes[0] if sub_dtypes and all(d == sub_dtypes[0] for d in sub_dtypes) else None - return shape, items, dt - return (), [obj], None - - -def _shape_strides(shape): - strides = [1] * len(shape) - for i in range(len(shape) - 2, -1, -1): - strides[i] = strides[i + 1] * shape[i + 1] - return tuple(strides) - - -def _broadcast_shapes(s1, s2): - n = max(len(s1), len(s2)) - p1 = (1,) * (n - len(s1)) + s1 - p2 = (1,) * (n - len(s2)) + s2 - out = [] - for a, b in zip(p1, p2): - if a == b: - out.append(a) - elif a == 1: - out.append(b) - elif b == 1: - out.append(a) - else: - raise ValueError(f"operands could not be broadcast together with shapes {s1} {s2}") - return tuple(out) - - -def _broadcast_index(out_coord, target_shape): - pad = len(out_coord) - len(target_shape) - res = [] - for c, dim in zip(out_coord[pad:], target_shape): - res.append(0 if dim == 1 else c) - return tuple(res) - - -def _unravel(flat_idx, shape): - if not shape: - return () - coords = [0] * len(shape) - rem = flat_idx - for ax in range(len(shape) - 1, -1, -1): - dim = shape[ax] - coords[ax] = rem % dim - rem //= dim - return tuple(coords) - - -def _ravel_coord(coord, strides): - return sum(c * s for c, s in zip(coord, strides)) - - -class _FakeCtypesView: - def __init__(self, arr): - self._arr = arr - - @property - def data(self): - return ctypes.addressof(self._arr._buf) - - -class _FakeFlat: - def __init__(self, arr): - self._arr = arr - - def __getitem__(self, idx): - return self._arr.ravel()[idx] - - def __setitem__(self, idx, value): - indices = idx._flat_list() if isinstance(idx, _FakeArray) else list(idx) - vals = value._flat_list() if isinstance(value, _FakeArray) else ( - list(value) if isinstance(value, (list, tuple)) else [value] * len(indices) - ) - if len(vals) == 1 and len(indices) != 1: - vals = vals * len(indices) - for pos, val in zip(indices, vals): - self._arr._set_flat(int(pos), val) - - -class _FakeArray: - """Pure-Python contiguous ndarray subset backed by a live ctypes byte buffer.""" - - def __init__(self, shape, dtype, flat_vals=None, raw_bytes=None): - self.shape = tuple(shape) - self.dtype = _normalize_dtype(dtype) - self.size = math.prod(self.shape) if self.shape else 1 - self.ndim = len(self.shape) - self._strides = _shape_strides(self.shape) - total_bytes = self.size * self.dtype.itemsize - if self.dtype.kind in "UO": - self._buf = None - self._obj_data = list(flat_vals) if flat_vals is not None else [None] * self.size - return - self._obj_data = None - self._buf = (ctypes.c_ubyte * max(1, total_bytes))() - if raw_bytes is not None: - if len(raw_bytes) != total_bytes: - raise ValueError(f"Expected {total_bytes} raw bytes, got {len(raw_bytes)}") - if total_bytes: - ctypes.memmove(self._buf, raw_bytes, total_bytes) - elif flat_vals is not None: - for i, val in enumerate(flat_vals): - self._set_flat(i, val) - - def _get_flat(self, i): - if i < 0: - i += self.size - if not 0 <= i < self.size: - raise IndexError(i) - if self._obj_data is not None: - return self._obj_data[i] - sz = self.dtype.itemsize - if self.dtype.kind == "V": - return bytes(self._buf[i * sz : (i + 1) * sz]) - return self.dtype._struct.unpack_from(self._buf, i * sz)[0] - - def _set_flat(self, i, val): - if i < 0: - i += self.size - if not 0 <= i < self.size: - raise IndexError(i) - if self._obj_data is not None: - self._obj_data[i] = val - return - coerced = self.dtype.cast_val(val) - sz = self.dtype.itemsize - if self.dtype.kind == "V": - for b_i, byte in enumerate(coerced): - self._buf[i * sz + b_i] = byte - else: - self.dtype._struct.pack_into(self._buf, i * sz, coerced) - - def _flat_list(self): - return [self._get_flat(i) for i in range(self.size)] - - def _get_coord(self, coord): - return self._get_flat(_ravel_coord(coord, self._strides)) - - def _set_coord(self, coord, val): - self._set_flat(_ravel_coord(coord, self._strides), val) - - @property - def ctypes(self): - return _FakeCtypesView(self) - - @property - def flat(self): - return _FakeFlat(self) - - @property - def T(self): - return self.transpose(*reversed(range(self.ndim))) - - def __len__(self): - if self.ndim == 0: - raise TypeError("len() of unsized object") - return self.shape[0] - - def __iter__(self): - if self.ndim == 0: - raise TypeError("iteration over a 0-d array") - for i in range(self.shape[0]): - yield self[i] - - def __int__(self): - if self.size != 1: - raise TypeError("only length-1 arrays can be converted to Python scalars") - return int(self._get_flat(0)) - - def __index__(self): - if self.size != 1 or self.dtype.kind not in "iu": - raise TypeError("only integer scalar arrays can be converted to a scalar index") - return int(self._get_flat(0)) - - def __bool__(self): - if self.size != 1: - raise ValueError("The truth value of an array with more than one element is ambiguous") - return bool(self._get_flat(0)) - - def copy(self): - if self._obj_data is not None: - return _FakeArray(self.shape, self.dtype, flat_vals=list(self._obj_data)) - return _FakeArray(self.shape, self.dtype, raw_bytes=self.tobytes()) - - def tobytes(self): - if self._obj_data is not None: - raise TypeError("cannot convert object/str array to bytes") - n = self.size * self.dtype.itemsize - return bytes(memoryview(self._buf)[:n]) - - def tolist(self): - def _build(offset, shape): - if not shape: - return self._get_flat(offset) - step = math.prod(shape[1:]) if len(shape) > 1 else 1 - return [_build(offset + i * step, shape[1:]) for i in range(shape[0])] - return _build(0, self.shape) - - def astype(self, dtype): - dt = _normalize_dtype(dtype) - return _FakeArray(self.shape, dt, flat_vals=self._flat_list()) - - def ravel(self): - return _FakeArray((self.size,), self.dtype, raw_bytes=self.tobytes()) if self._buf is not None else _FakeArray((self.size,), self.dtype, flat_vals=self._flat_list()) - - def reshape(self, *newshape): - if len(newshape) == 1 and isinstance(newshape[0], (tuple, list)): - newshape = tuple(newshape[0]) - shape = list(newshape) - if -1 in shape: - neg_idx = shape.index(-1) - known = math.prod(d for d in shape if d != -1) - shape[neg_idx] = self.size // known - shape = tuple(shape) - if math.prod(shape) != self.size: - raise ValueError(f"cannot reshape array of size {self.size} into shape {shape}") - if self._buf is not None: - return _FakeArray(shape, self.dtype, raw_bytes=self.tobytes()) - return _FakeArray(shape, self.dtype, flat_vals=self._flat_list()) - - def transpose(self, *axes): - if len(axes) == 1 and isinstance(axes[0], (tuple, list)): - axes = tuple(axes[0]) - if not axes: - axes = tuple(reversed(range(self.ndim))) - new_shape = tuple(self.shape[a] for a in axes) - vals = [] - for idx in range(self.size): - coord = _unravel(idx, new_shape) - src = [0] * self.ndim - for new_ax, old_ax in enumerate(axes): - src[old_ax] = coord[new_ax] - vals.append(self._get_coord(tuple(src))) - return _FakeArray(new_shape, self.dtype, flat_vals=vals) - - def any(self): - return any(bool(v) for v in self._flat_list()) - - def all(self): - return all(bool(v) for v in self._flat_list()) - - def max(self): - vals = self._flat_list() - if not vals: - raise ValueError("zero-size array to reduction operation maximum which has no identity") - return max(vals) - - def min(self): - vals = self._flat_list() - if not vals: - raise ValueError("zero-size array to reduction operation minimum which has no identity") - return min(vals) - - # --- Indexing --- - def _parse_key(self, key): - if not isinstance(key, tuple): - key = (key,) - # Fast path: single boolean mask matching array shape or leading axis - if len(key) == 1 and isinstance(key[0], _FakeArray) and key[0].dtype.kind == "b": - return ("bool_mask", key[0]) - if len(key) == 1 and isinstance(key[0], (list, tuple)) and key[0] and all(isinstance(v, bool) for v in key[0]): - return ("bool_mask", _fake_asarray(key[0], dtype="bool")) - - # General multi-axis key supporting int, slice, None, and integer fancy indexers - items = list(key) - non_none = [x for x in items if x is not None] - while len(non_none) < self.ndim: - items.append(slice(None)) - non_none.append(slice(None)) - return ("axes", items) - - def __getitem__(self, key): - kind, parsed = self._parse_key(key) - if kind == "bool_mask": - mask = parsed - if mask.shape == self.shape: - vals = [v for v, m in zip(self._flat_list(), mask._flat_list()) if m] - return _FakeArray((len(vals),), self.dtype, flat_vals=vals) - if mask.ndim == 1 and len(mask) == self.shape[0]: - tail_shape = self.shape[1:] - tail_size = math.prod(tail_shape) if tail_shape else 1 - vals = [] - rows = 0 - for r, keep in enumerate(mask._flat_list()): - if keep: - rows += 1 - base = r * tail_size - for off in range(tail_size): - vals.append(self._get_flat(base + off)) - return _FakeArray((rows,) + tail_shape, self.dtype, flat_vals=vals) - raise IndexError("boolean index did not match indexed array") - - # Separate axes into newaxis, slice, int, or fancy integer array - fancy_positions = [] - axis = 0 - axis_specs = [] - for item in parsed: - if item is None: - axis_specs.append(("newaxis", None)) - continue - dim = self.shape[axis] - if isinstance(item, slice): - axis_specs.append(("slice", range(*item.indices(dim)))) - elif isinstance(item, int) or (isinstance(item, _FakeArray) and item.ndim == 0 and item.dtype.kind in "iu"): - idx = int(item) - if idx < 0: - idx += dim - if not 0 <= idx < dim: - raise IndexError(idx) - axis_specs.append(("int", idx)) - else: - arr = item if isinstance(item, _FakeArray) else _fake_asarray(item) - if arr.dtype.kind not in "iu": - raise IndexError("arrays used as indices must be of integer type") - fancy_positions.append((len(axis_specs), dim, arr)) - axis_specs.append(("fancy", arr)) - axis += 1 - - if not fancy_positions: - out_shape = [] - ranges = [] - for sp_kind, sp_val in axis_specs: - if sp_kind == "newaxis": - out_shape.append(1) - ranges.append([0]) - elif sp_kind == "slice": - out_shape.append(len(sp_val)) - ranges.append(list(sp_val)) - else: - ranges.append([sp_val]) - if not out_shape: - coord = tuple(r[0] for r in ranges) - return self._get_coord(coord) - vals = [] - total = math.prod(out_shape) - for idx in range(total): - oc = _unravel(idx, tuple(out_shape)) - src = [] - oi = 0 - for sp_kind, sp_val in axis_specs: - if sp_kind == "newaxis": - oi += 1 - elif sp_kind == "slice": - src.append(sp_val[oc[oi]]) - oi += 1 - else: - src.append(sp_val) - vals.append(self._get_coord(tuple(src))) - return _FakeArray(tuple(out_shape), self.dtype, flat_vals=vals) - - # Broadcast all fancy arrays together - bshape = () - for _, _, arr in fancy_positions: - bshape = _broadcast_shapes(bshape, arr.shape) - contiguous_fancy = [p for p, _, _ in fancy_positions] == list( - range(fancy_positions[0][0], fancy_positions[0][0] + len(fancy_positions)) - ) - # Build output shape - out_shape = [] - fancy_inserted = False - slice_ranges = {} - for pos, (sp_kind, sp_val) in enumerate(axis_specs): - if sp_kind == "newaxis": - out_shape.append(1) - elif sp_kind == "slice": - out_shape.append(len(sp_val)) - slice_ranges[pos] = list(sp_val) - elif sp_kind == "fancy": - if contiguous_fancy: - if not fancy_inserted: - out_shape.extend(bshape) - fancy_inserted = True - else: - if not fancy_inserted: - out_shape = list(bshape) + out_shape - fancy_inserted = True - - # Map each output coordinate to source coordinate - total = math.prod(out_shape) if out_shape else 1 - vals = [] - b_start = 0 if not contiguous_fancy else sum( - 1 for p, (k, _) in enumerate(axis_specs[: fancy_positions[0][0]]) if k in ("newaxis", "slice") - ) - b_len = len(bshape) - for flat_i in range(total): - oc = _unravel(flat_i, tuple(out_shape)) - b_coord = oc[b_start : b_start + b_len] - src = [] - oi = 0 if contiguous_fancy else b_len - for pos, (sp_kind, sp_val) in enumerate(axis_specs): - if sp_kind == "newaxis": - oi += 1 - elif sp_kind == "slice": - src.append(slice_ranges[pos][oc[oi]]) - oi += 1 - elif sp_kind == "int": - src.append(sp_val) - elif sp_kind == "fancy": - if pos == fancy_positions[0][0] and contiguous_fancy: - oi += b_len - dim = self.shape[len(src)] - fc = _broadcast_index(b_coord, sp_val.shape) - idx_v = int(sp_val._get_coord(fc)) if sp_val.ndim else int(sp_val._get_flat(0)) - if idx_v < 0: - idx_v += dim - if not 0 <= idx_v < dim: - raise IndexError(idx_v) - src.append(idx_v) - vals.append(self._get_coord(tuple(src))) - if not out_shape: - return vals[0] - return _FakeArray(tuple(out_shape), self.dtype, flat_vals=vals) - - def __setitem__(self, key, value): - kind, parsed = self._parse_key(key) - if kind == "bool_mask": - mask = parsed - rhs = value if isinstance(value, _FakeArray) else _fake_asarray(value, dtype=self.dtype) - if mask.shape == self.shape: - k = 0 - for i, m in enumerate(mask._flat_list()): - if m: - v = rhs._get_flat(0) if rhs.size == 1 else rhs._get_flat(k) - self._set_flat(i, v) - k += 1 - return - if mask.ndim == 1 and len(mask) == self.shape[0]: - tail_shape = self.shape[1:] - tail_size = math.prod(tail_shape) if tail_shape else 1 - n_true = sum(1 for m in mask._flat_list() if m) - target_shape = (n_true,) + tail_shape - b_shape = _broadcast_shapes(target_shape, rhs.shape) - if b_shape != target_shape: - raise ValueError(f"cannot broadcast {rhs.shape} to {target_shape}") - t_idx = 0 - for r, keep in enumerate(mask._flat_list()): - if keep: - base = r * tail_size - for off in range(tail_size): - tc = (t_idx,) + _unravel(off, tail_shape) - rc = _broadcast_index(tc, rhs.shape) - self._set_flat(base + off, rhs._get_coord(rc) if rhs.ndim else rhs._get_flat(0)) - t_idx += 1 - return - raise IndexError("boolean index did not match indexed array") - - # Concrete axis assignment (ints and slices) - slices = [] - sub_shape = [] - axis = 0 - for item in parsed: - if item is None: - continue - dim = self.shape[axis] - if isinstance(item, slice): - rng = list(range(*item.indices(dim))) - slices.append(rng) - sub_shape.append(len(rng)) - else: - idx = int(item) - if idx < 0: - idx += dim - if not 0 <= idx < dim: - raise IndexError(idx) - slices.append([idx]) - axis += 1 - rhs = value if isinstance(value, _FakeArray) else _fake_asarray(value, dtype=self.dtype) - sub_shape = tuple(sub_shape) - if not sub_shape: - coord = tuple(r[0] for r in slices) - self._set_coord(coord, rhs._get_flat(0) if rhs.size == 1 else rhs) - return - total = math.prod(sub_shape) - for fi in range(total): - sc = _unravel(fi, sub_shape) - dst = [] - si = 0 - for rng in slices: - if len(rng) == 1 and len(sub_shape) < len(slices): - dst.append(rng[0]) - else: - dst.append(rng[sc[si]]) - si += 1 - # Re-derive dst accurately: - dst = [] - si = 0 - for ax_i, item in enumerate(parsed): - if item is None: - continue - if isinstance(item, slice): - dst.append(slices[ax_i][sc[si]]) - si += 1 - else: - dst.append(slices[ax_i][0]) - rc = _broadcast_index(sc, rhs.shape) - self._set_coord(tuple(dst), rhs._get_coord(rc) if rhs.ndim else rhs._get_flat(0)) - - # --- Operators --- - def _binop(self, other, fn, out_dtype=None): - rhs = other if isinstance(other, _FakeArray) else _fake_asarray(other) - bshape = _broadcast_shapes(self.shape, rhs.shape) - dt = _normalize_dtype(out_dtype) if out_dtype is not None else _promote_dtype(self.dtype, rhs.dtype) - total = math.prod(bshape) if bshape else 1 - vals = [] - for i in range(total): - oc = _unravel(i, bshape) - a_val = self._get_coord(_broadcast_index(oc, self.shape)) if self.ndim else self._get_flat(0) - b_val = rhs._get_coord(_broadcast_index(oc, rhs.shape)) if rhs.ndim else rhs._get_flat(0) - vals.append(fn(a_val, b_val)) - return _FakeArray(bshape, dt, flat_vals=vals) - - def _rbinop(self, other, fn, out_dtype=None): - lhs = other if isinstance(other, _FakeArray) else _fake_asarray(other) - return lhs._binop(self, fn, out_dtype=out_dtype) - - def _ibop(self, other, fn): - res = self._binop(other, fn, out_dtype=self.dtype) - for i, v in enumerate(res._flat_list()): - self._set_flat(i, v) - return self - - def __add__(self, o): return self._binop(o, lambda a, b: a + b) - def __radd__(self, o): return self._rbinop(o, lambda a, b: a + b) - def __iadd__(self, o): return self._ibop(o, lambda a, b: a + b) - def __sub__(self, o): return self._binop(o, lambda a, b: a - b) - def __rsub__(self, o): return self._rbinop(o, lambda a, b: a - b) - def __mul__(self, o): return self._binop(o, lambda a, b: a * b) - def __rmul__(self, o): return self._rbinop(o, lambda a, b: a * b) - def __floordiv__(self, o): return self._binop(o, lambda a, b: a // b) - def __mod__(self, o): return self._binop(o, lambda a, b: a % b) - def __imod__(self, o): return self._ibop(o, lambda a, b: a % b) - def __lshift__(self, o): return self._binop(o, lambda a, b: a << b) - def __rlshift__(self, o): - # Preserve self's integer dtype when shifting a scalar 1 << uint64_arr - rhs_arr = o if isinstance(o, _FakeArray) else _fake_asarray(o, dtype=self.dtype) - return rhs_arr._binop(self, lambda a, b: a << b, out_dtype=self.dtype) - def __rshift__(self, o): return self._binop(o, lambda a, b: a >> b) - def __and__(self, o): return self._binop(o, lambda a, b: a & b) - def __or__(self, o): return self._binop(o, lambda a, b: a | b) - def __ior__(self, o): return self._ibop(o, lambda a, b: a | b) - def __xor__(self, o): return self._binop(o, lambda a, b: a ^ b) - def __lt__(self, o): return self._binop(o, lambda a, b: a < b, out_dtype="bool") - def __le__(self, o): return self._binop(o, lambda a, b: a <= b, out_dtype="bool") - def __gt__(self, o): return self._binop(o, lambda a, b: a > b, out_dtype="bool") - def __ge__(self, o): return self._binop(o, lambda a, b: a >= b, out_dtype="bool") - def __eq__(self, o): return self._binop(o, lambda a, b: a == b, out_dtype="bool") - def __ne__(self, o): return self._binop(o, lambda a, b: a != b, out_dtype="bool") - - def __neg__(self): - return _FakeArray(self.shape, self.dtype, flat_vals=[-v for v in self._flat_list()]) - - def __invert__(self): - if self.dtype.kind == "b": - return _FakeArray(self.shape, self.dtype, flat_vals=[not v for v in self._flat_list()]) - return _FakeArray(self.shape, self.dtype, flat_vals=[~v for v in self._flat_list()]) - - def __matmul__(self, other): - rhs = other if isinstance(other, _FakeArray) else _fake_asarray(other) - dt = _promote_dtype(self.dtype, rhs.dtype) - if self.ndim == 2 and rhs.ndim == 1 and self.shape[1] == rhs.shape[0]: - m, k = self.shape - r_vals = rhs._flat_list() - s_vals = self._flat_list() - out = [sum(s_vals[i * k + j] * r_vals[j] for j in range(k)) for i in range(m)] - return _FakeArray((m,), dt, flat_vals=out) - raise ValueError(f"Unsupported matmul shapes {self.shape} @ {rhs.shape}") - - -def _fake_asarray(values, dtype=None): - if isinstance(values, _FakeArray): - if dtype is None or values.dtype == _normalize_dtype(dtype): - return values - return values.astype(dtype) - shape, flat, sub_dt = _flatten_nested(values) - dt = _normalize_dtype(dtype) if dtype is not None else (sub_dt or _infer_dtype(flat)) - return _FakeArray(shape, dt, flat_vals=flat) - - -def _fake_array(values, dtype=None): - arr = _fake_asarray(values, dtype=dtype) - return arr.copy() - - -def _fake_ascontiguousarray(values, dtype=None): - return _fake_asarray(values, dtype=dtype).copy() - - -def _fake_zeros(shape, dtype="float64"): - sh = (int(shape),) if isinstance(shape, int) else tuple(shape) - dt = _normalize_dtype(dtype) - n = math.prod(sh) if sh else 1 - if dt.kind == "V": - return _FakeArray(sh, dt, flat_vals=[b"\x00" * dt.itemsize] * n) - return _FakeArray(sh, dt, flat_vals=[0] * n) - - -def _fake_empty(shape, dtype="float64"): - return _fake_zeros(shape, dtype=dtype) - - -def _fake_frombuffer(buf, dtype="uint8"): - raw = bytes(buf) - dt = _normalize_dtype(dtype) - if len(raw) % dt.itemsize != 0: - raise ValueError("buffer size must be a multiple of element size") - return _FakeArray((len(raw) // dt.itemsize,), dt, raw_bytes=raw) - - -def _fake_arange(start, stop=None, step=1, dtype=None): - if stop is None: - start, stop = 0, start - vals = list(range(int(start), int(stop), int(step))) - return _FakeArray((len(vals),), dtype or "int64", flat_vals=vals) - - -def _fake_any(arr): - return _fake_asarray(arr).any() - - -def _fake_all(arr): - return _fake_asarray(arr).all() - - -def _fake_unique(arr): - vals = sorted(set(_fake_asarray(arr)._flat_list())) - dt = arr.dtype if isinstance(arr, _FakeArray) else _infer_dtype(vals) - return _FakeArray((len(vals),), dt, flat_vals=vals) - - -def _fake_searchsorted(a, v, side="left"): - edges = _fake_asarray(a)._flat_list() - queries = _fake_asarray(v) - fn = bisect.bisect_right if side == "right" else bisect.bisect_left - res = [fn(edges, x) for x in queries._flat_list()] - return _FakeArray(queries.shape, "int64", flat_vals=res) - - -def _fake_roll(a, shift): - arr = _fake_asarray(a) - vals = arr._flat_list() - n = len(vals) - if n == 0: - return arr.copy() - s = shift % n - rolled = vals[-s:] + vals[:-s] if s else list(vals) - return _FakeArray(arr.shape, arr.dtype, flat_vals=rolled) - - -def _fake_column_stack(tup): - cols = [_fake_asarray(c) for c in tup] - n = cols[0].shape[0] - dt = cols[0].dtype - for c in cols[1:]: - dt = _promote_dtype(dt, c.dtype) - flat = [] - for r in range(n): - for c in cols: - flat.append(c._get_flat(r)) - return _FakeArray((n, len(cols)), dt, flat_vals=flat) - - -class _FakeBitwiseOr: - @staticmethod - def reduce(arr, axis=0): - a = _fake_asarray(arr) - if axis < 0: - axis += a.ndim - out_shape = tuple(d for i, d in enumerate(a.shape) if i != axis) - dim = a.shape[axis] - total = math.prod(out_shape) if out_shape else 1 - vals = [] - for idx in range(total): - oc = _unravel(idx, out_shape) - acc = 0 - for k in range(dim): - src = list(oc) - src.insert(axis, k) - acc |= a._get_coord(tuple(src)) - vals.append(acc) - return _FakeArray(out_shape, a.dtype, flat_vals=vals) - - -def _make_fake_numpy(): - import types - mod = types.ModuleType("numpy") - mod.array = _fake_array - mod.asarray = _fake_asarray - mod.ascontiguousarray = _fake_ascontiguousarray - mod.zeros = _fake_zeros - mod.empty = _fake_empty - mod.frombuffer = _fake_frombuffer - mod.arange = _fake_arange - mod.any = _fake_any - mod.all = _fake_all - mod.unique = _fake_unique - mod.searchsorted = _fake_searchsorted - mod.roll = _fake_roll - mod.column_stack = _fake_column_stack - mod.bitwise_or = _FakeBitwiseOr() - mod.ndarray = _FakeArray - return mod - - -def _load_calibrated_texture(): - """Load tools/calibrated_texture.py using real NumPy if present, else the stdlib shim.""" - if importlib.util.find_spec("numpy") is not None: - import calibrated_texture - return calibrated_texture, False - fake_np = _make_fake_numpy() - spec = importlib.util.spec_from_file_location( - "calibrated_texture", str(TOOLS_DIR / "calibrated_texture.py") - ) - mod = importlib.util.module_from_spec(spec) - with mock.patch.dict(sys.modules, {"numpy": fake_np}): - spec.loader.exec_module(mod) - return mod, True - - -ct, _USING_FAKE_NP = _load_calibrated_texture() -np = ct.np - - -# --------------------------------------------------------------------------- -# Synthetic RDS5 / ETPF pool and BCPack stream builders (no game data) -# --------------------------------------------------------------------------- - -def write_custom_pool(path, records, chunks): - """Write a synthetic RDS5/ETPF pool with arbitrary `(codec, payload, virt_size)` chunks.""" - count = len(chunks) + 2 - table_end = 24 + (count - 1) * 8 - etpf = ttpf.align(table_end, 256) - area = len(records) * 24 - metadata = 16 + area + len(records) * 32 - padded = ttpf.align(metadata, 4096) - - source = etpf + padded - virt = padded - entries = [] - packed_chunks = [] - for codec, payload, vsize_chunk in chunks: - assert vsize_chunk > 0 and vsize_chunk % 4096 == 0 - if codec == 0: - assert len(payload) == vsize_chunk - pad = 0 - else: - pad = (-len(payload)) % 256 - entries.append((source // 256) | (codec << 26) | ((virt // 4096) << 30) | (pad << 52)) - packed_chunks.append((source, payload)) - source += len(payload) + pad - virt += vsize_chunk - - vsize = virt - entries.append((source // 256) | ((vsize // 4096) << 30)) - - header = bytearray(24) - header[0:4] = b"RDS5" - struct.pack_into("0->-512; Block 2->1->0; Block 3->2->1->0 (depth 3); - # Block 4: d=10 (external -> root = 4 - 10 = -6); Block 5->4 (root = -6). - distances = np.array([0, 1, 1, 1, 10, 1, 2, 0], dtype="int32") - residuals = np.array( - [[10, 1], [2, 3], [4, 5], [6, 7], [100, 200], [5, -10], [7, 8], [9, 10]], - dtype="int32", - ) - roots = ct.accumulate(distances, residuals) - self.assertEqual(roots.tolist(), [-512, -512, -512, -512, -6, -6, -6, -512]) - self.assertEqual( - residuals.tolist(), - [[10, 1], [12, 4], [16, 9], [22, 16], [100, 200], [105, 190], [107, 208], [9, 10]], - ) - - def test_addresses_matches_detile_across_4k_and_64k_tiles(self): - ct.addresses.cache_clear() - for tile in (4096, 65536): - for fmt, bs in ((71, 8), (98, 16)): - with self.subTest(tile=tile, bs=bs): - lay = ttpf.surface_layout(256, 192, fmt, 8, tile) - bw, bh = lay["block_w"], lay["block_h"] - for mip in (lay["mips"][0], lay["mips"][-1]): - w, h = mip["blocks_w"], mip["blocks_h"] - x0, y0 = mip["tile_x"], mip["tile_y"] - got = ct.addresses(tile, bs, bw, bh, w, h, x0, y0).tolist() - # Compare against ttpf.detile by placing unique byte markers at each offset. - # Note detile checks offset within mip["region"]; fill a synthetic region with - # 8-byte / 16-byte tagged offsets. - region = bytearray(mip["region"]) - for off in range(0, len(region), bs): - struct.pack_into(" 256+0-255=1 -> age=255) - # Block 1: d=1 -> chains onto Block 0 (external root) - # Block 2: d=0 -> self-contained with negative endpoint wrap - # Block 3: d=1 -> chains onto Block 2 - lanes = [ - [tb._zig(-1), tb._zig(1), 0, tb._zig(1)], # l0: -1 mod 256 = 255 - [0, 0, 0, 0], - [tb._zig(2), tb._zig(-3), tb._zig(-1), tb._zig(4)], - [tb._zig(-4), tb._zig(5), tb._zig(-2), tb._zig(10)], - [tb._zig(1), tb._zig(2), tb._zig(-3), tb._zig(7)], - [tb._zig(-1), tb._zig(3), tb._zig(-5), tb._zig(2)], - [tb._zig(6), tb._zig(-2), tb._zig(-1), tb._zig(8)], - [tb._zig(0), tb._zig(1), tb._zig(-2), tb._zig(3)], - [0, 17, 128, 255], - [1, 33, 64, 200], - [2, 99, 150, 10], - [3, 210, 44, 77], - ] - sy = np.ascontiguousarray(np.asarray(lanes, dtype="uint8").T) - got = ct.bc1_blocks(sy, (seeds, selectors)) - expected = bcpack._bc1_blocks(lanes, 4, None) - self.assertEqual(got, expected) - - # Missing external history (provisional entry 6 -> age 250 has -1 in seeds) raises ValueError. - bad_seeds = ct.array([[-1] * 6 for _ in range(256)], (256, 6), "int32", -1, 63) - lanes_ext = [[tb._zig(-6)] if k == 0 else [0] for k in range(12)] - sy_ext = np.ascontiguousarray(np.asarray(lanes_ext, dtype="uint8").T) - with self.assertRaisesRegex(ValueError, "Missing BC1 endpoint history"): - ct.bc1_blocks(sy_ext, (bad_seeds, selectors)) - - # Self-contained stream (d=0) succeeds even with -1 in all external seeds. - lanes_self = [[k * 3 % 32] for k in range(12)] - lanes_self[0] = [0] - lanes_self[1] = [0] - sy_self = np.ascontiguousarray(np.asarray(lanes_self, dtype="uint8").T) - self.assertEqual(ct.bc1_blocks(sy_self, (bad_seeds, selectors)), bcpack._bc1_blocks(lanes_self, 1, None)) - - def test_bc7_blocks_invokes_native_rebuild(self): - sy = np.array([[i for i in range(16)] for _ in range(4)], dtype="uint8") # 2 blocks - labels = ct.array([[1, 2, 0, 0] for _ in range(1024)], (1024, 4), "int16", -1, 255) - anchors = ct.array([7] * 128, (128,), "uint16", 0, 65535) - seed = ct.array([[[0, 8] for _ in range(56)] for _ in range(256)], (256, 56, 2), "uint8", 0, 255) - - b0 = bytes(range(16)) - b1 = bytes(range(16, 32)) - seen = {} - - def fake_rebuild(s_ptr, count, lab_ptr, seed_ptr, anc_ptr, out_ptr, ok_ptr): - seen["args"] = (s_ptr, count, lab_ptr, seed_ptr, anc_ptr, out_ptr, ok_ptr) - seen["s_bytes"] = _read_u8_buf(s_ptr, count * 32) - _write_u8_buf(out_ptr, b0 + b1) - _write_u8_buf(ok_ptr, bytes([1, 0])) - - with _fake_native_context(rebuild_fn=fake_rebuild) as lib: - out, ok = ct.bc7_blocks(sy, (labels, anchors), seed) - self.assertEqual(lib.rebuild.call_count, 1) - self.assertEqual(seen["args"][1], 2) - self.assertEqual(seen["args"][2], labels.ctypes.data) - self.assertEqual(seen["args"][3], seed.ctypes.data) - self.assertEqual(seen["args"][4], anchors.ctypes.data) - self.assertEqual(seen["s_bytes"], sy.tobytes()) - self.assertEqual(out.tobytes(), b0 + b1) - self.assertEqual(ok.tolist(), [True, False]) - - # Zero blocks - empty_sy = np.zeros((0, 16), dtype="uint8") - with _fake_native_context() as lib: - out0, ok0 = ct.bc7_blocks(empty_sy, (labels, anchors), seed) - self.assertEqual(out0.shape, (0,)) - self.assertEqual(ok0.shape, (0,)) - self.assertEqual(lib.rebuild.call_args[0][1], 0) - - def test_scalar_bc4_parity_and_missing_slot(self): - table = dict(bcpack_tables.BC4_HISTORY_PROVISIONAL) - # Block 0: d=0; Block 1: d=1; Block 2: external slot 25 (d=256+2-25=233 -> unzig(-23)) - d2 = tb._zig(-23) - lanes = [ - [0, tb._zig(1), d2], - [0, 0, 0], - [tb._zig(30), tb._zig(-50), tb._zig(-100)], - [tb._zig(-120), tb._zig(45), tb._zig(20)], - [0, 12, 33], [1, 15, 44], [2, 20, 55], [3, 25, 63], - [4, 30, 7], [5, 35, 8], [6, 40, 9], [7, 45, 10], - ] - sy = np.ascontiguousarray(np.asarray(lanes, dtype="uint8").T) - got = ct.scalar_bc4(sy, table) - expected = bcpack._bc4_blocks(lanes, 3, set()) - self.assertEqual(got, expected) - - with self.assertRaises(KeyError): - ct.scalar_bc4(sy, {}) - - def test_local_bc5_parity_and_missing_slot(self): - # Block 0: confirmed entry 182 (d=256+0-182=74) - # Block 1: d=1 (chains onto Block 0) - # Block 2: provisional entry 3 (d=256+2-3=255 -> -1 mod 256) - # Block 3: distance=0 (seed 128) - # local_bc5 uses compatibility endpoint ordering where s[:, 0, 2:4] holds - # (r0, r1) and s[:, 1, 2:4] holds (g0, g1), while selector lanes 4..11 - # match bcpack._bc5_blocks identically. - d0a, d0b = tb._deint4(tb._zig(74) & 255) - d1a, d1b = tb._deint4(tb._zig(1) & 255) - d2a, d2b = tb._deint4(tb._zig(-1) & 255) - lanes = [[] for _ in range(12)] - lanes[0] = [d0a, d0b, d1a, d1b, d2a, d2b, 0, 0] - lanes[1] = [0] * 8 - lanes[2] = [tb._zig(10), tb._zig(-20), tb._zig(5), tb._zig(-15), tb._zig(30), tb._zig(40), tb._zig(-60), tb._zig(70)] - lanes[3] = [tb._zig(-5), tb._zig(25), tb._zig(-10), tb._zig(35), tb._zig(-40), tb._zig(12), tb._zig(80), tb._zig(-90)] - for ln in range(4, 12): - lanes[ln] = [(ln * 7 + k * 5) & 63 for k in range(8)] - sy = np.ascontiguousarray(np.asarray(lanes, dtype="uint8").T) - got = ct.local_bc5(sy) - - # Verify selector bytes (bytes 2..7 and 10..15 of each 16-byte block) match bcpack._bc5_blocks, - # and endpoint bytes match the compatibility ordering against BC5_HISTORY_* tables. - ref = bcpack._bc5_blocks(lanes, 4, set()) - self.assertEqual(len(got), 64) - h182 = bcpack_tables.BC5_HISTORY_CONFIRMED[182] - h3 = bcpack_tables.BC5_HISTORY_PROVISIONAL[3] - # Block 0: base h182 reshaped (2, 2) -> [[h182[0], h182[1]], [h182[2], h182[3]]] - b0_ep = ( - (h182[0] + 10) % 256, - (h182[1] - 5) % 256, - (h182[2] - 20) % 256, - (h182[3] + 25) % 256, - ) - # Block 1: chains onto Block 0 - b1_ep = ( - (b0_ep[0] + 5) % 256, - (b0_ep[1] - 10) % 256, - (b0_ep[2] - 15) % 256, - (b0_ep[3] + 35) % 256, - ) - # Block 2: base h3 - b2_ep = ( - (h3[0] + 30) % 256, - (h3[1] - 40) % 256, - (h3[2] + 40) % 256, - (h3[3] + 12) % 256, - ) - # Block 3: d=0 -> seed (128, 128, 128, 128) - b3_ep = ((128 - 60) % 256, (128 + 80) % 256, (128 + 70) % 256, (128 - 90) % 256) - for bi, ep in enumerate((b0_ep, b1_ep, b2_ep, b3_ep)): - off = bi * 16 - self.assertEqual((got[off], got[off + 1], got[off + 8], got[off + 9]), ep) - self.assertEqual(got[off + 2 : off + 8], ref[off + 2 : off + 8]) - self.assertEqual(got[off + 10 : off + 16], ref[off + 10 : off + 16]) - - # Unknown history entry 1 (neither confirmed nor provisional) raises KeyError. - u0a, u0b = tb._deint4(tb._zig(-1) & 255) - bad_lanes = [[u0a, u0b] if k == 0 else [0, 0] for k in range(12)] - bad_sy = np.ascontiguousarray(np.asarray(bad_lanes, dtype="uint8").T) - with self.assertRaises(KeyError): - ct.local_bc5(bad_sy) - - def test_local_bc3_parity_and_missing_slot(self): - profile = _bc3_profile_from_tables() - # Block 0: d=0 (slot -512) - # Block 1: d=1 (chains onto Block 0) - # Block 2: provisional entry 26 (d=256+2-26=232 -> unzig(-24) & 255) - d0a, d0b = 0, 0 - d1a, d1b = tb._deint4(tb._zig(1) & 255) - d2a, d2b = tb._deint4(tb._zig(-24) & 255) - lanes = [[] for _ in range(12)] - lanes[0] = [d0a, d0b, d1a, d1b, d2a, d2b] - lanes[1] = [0] * 6 - lanes[2] = [tb._zig(20), tb._zig(-30), tb._zig(5), tb._zig(-10), tb._zig(40), tb._zig(-50)] - for ln in range(3, 7): - lanes[ln] = [(ln * 11 + k * 7) & 63 for k in range(6)] - lanes[7] = [tb._zig(7), tb._zig(-3), tb._zig(4), tb._zig(-2), tb._zig(12), tb._zig(-8)] - lanes[8] = [tb._zig(-15), tb._zig(22), tb._zig(3), tb._zig(-9), tb._zig(18), tb._zig(25)] - lanes[9] = [tb._zig(9), tb._zig(-12), tb._zig(-1), tb._zig(6), tb._zig(-14), tb._zig(11)] - lanes[10] = [12, 45, 78, 123, 200, 251] - lanes[11] = [33, 67, 101, 144, 188, 229] - - sy = np.ascontiguousarray(np.asarray(lanes, dtype="uint8").T) - got = ct.local_bc3(sy, profile) - expected = bcpack._bc3_blocks(lanes, 3, set()) - self.assertEqual(got, expected) - - with self.assertRaises(KeyError): - ct.local_bc3(sy, {"endpoints": {}, "color": profile["color"], "alpha": profile["alpha"]}) - - -class TestLocalDecoder(unittest.TestCase): - def setUp(self): - tmp = tempfile.TemporaryDirectory() - self.addCleanup(tmp.cleanup) - self.root = Path(tmp.name) - - def _open_pool(self, name, records, chunks): - path = self.root / name - base = write_custom_pool(path, records, chunks) - pool = ttpf.Pool(str(path)) - self.addCleanup(pool.close) - return pool, base - - def test_init_rejects_bad_calibration_versions_and_isolates_cache(self): - pool, base = self._open_pool( - "raw.ttpf", - [ttm.pack_etpf_record(64, 64, 1, 0, 71, 1, 1, 4, 4096)], - [(0, b"\xAA" * 4096, 4096)], - ) - for bad in (None, [], "v1", 1, {}, {"version": 0}, {"version": 2}, {"version": "1"}): - with self.subTest(bad=bad): - with self.assertRaisesRegex(ValueError, "Unsupported calibration version"): - ct.LocalDecoder(pool, bad) - - dec1 = ct.LocalDecoder(pool, {"version": 1}) - dec2 = ct.LocalDecoder(pool, {"version": 1}) - self.assertEqual(dec1.edges.tolist(), [base, base + 4096]) - b1, m1 = dec1.read_chunk(0, 8, "base") - self.assertIsNone(m1) - self.assertEqual(len(b1), 512) - self.assertEqual(dec1.read_chunk.cache_info().currsize, 1) - self.assertEqual(dec2.read_chunk.cache_info().currsize, 0) - - def test_seed_validation_precision_and_caching(self): - pool, _ = self._open_pool( - "dummy.ttpf", - [ttm.pack_etpf_record(64, 64, 1, 0, 98, 1, 1, 4, 4096)], - [(0, b"\x00" * 4096, 4096)], - ) - cal = {"version": 1, "bc7": _empty_bc7_section()} - dec = ct.LocalDecoder(pool, cal) - s1 = dec.seed("base") - s2 = dec.seed("base") - self.assertIs(s1, s2) - with self.assertRaises(KeyError): - dec.seed("nonexistent") - - cal["bc7"]["seeds"]["bad_prec"] = [[[0, 9] for _ in range(56)] for _ in range(256)] - with self.assertRaisesRegex(ValueError, "Invalid history precision"): - dec.seed("bad_prec") - - def test_symbols_native_fallback_compatibility_and_errors(self): - # Build a valid 64x64 1-mip BC1 BCPack chunk (512 blocks = 4096 bytes) - layout = ttpf.surface_layout(64, 64, 71, 1, 4096) - linear = ttm.solid_chain(layout, 71)[0] - tiled = bytearray(layout["size"]) - ttm.retile_to(layout, layout["mips"][0], linear, tiled) - packed_bc1 = tb.encode_bc1_blocks(bytes(tiled)) - chunk_sha = hashlib.sha256(packed_bc1).hexdigest() - - # Chunk 0: valid BC1 BCPack - # Chunk 1: valid BC1 BCPack with an extra trailing 0x00 byte so decode_lanes consumes < packed - # Chunk 2: valid BC4 BCPack (unused compatibility branch when codec != 1) - bc4_lanes = [[0] * 512 for _ in range(12)] - packed_bc4 = _encode_bc4_from_lanes(bc4_lanes) - pool, _ = self._open_pool( - "syms.ttpf", - [ttm.pack_etpf_record(64, 64, 1, 0, 71, 1, 1, 4, 4096)], - [ - (1, packed_bc1, 4096), - (1, packed_bc1 + b"\x00", 4096), - (4, packed_bc4, 4096), - ], - ) - - # 1. Native unpack succeeds (returns packed) -> bcpack.decode_lanes is NOT called. - dec_nat = ct.LocalDecoder(pool, {"version": 1}) - expected_lanes, _ = bcpack.decode_lanes(packed_bc1, 1, 4096) - expected_sy = np.ascontiguousarray(np.asarray(expected_lanes, dtype="uint8").T) - - def fake_unpack(raw, packed, widths_bytes, nlanes, nsym, sy_ptr): - self.assertEqual(raw, packed_bc1) - self.assertEqual(packed, len(packed_bc1)) - self.assertEqual(widths_bytes, bytes(w - 1 for w in bcpack.LANE_WIDTHS[1])) - self.assertEqual(nlanes, 12) - self.assertEqual(nsym, 512) - _write_u8_buf(sy_ptr, expected_sy.tobytes()) - return packed - - with _fake_native_context(unpack_fn=fake_unpack), \ - mock.patch.object(bcpack, "decode_lanes", side_effect=AssertionError("unexpected fallback")): - got_sy = dec_nat.symbols(0) - self.assertEqual(got_sy.tobytes(), expected_sy.tobytes()) - - # 2. Native unpack returns -1 -> falls back to bcpack.decode_lanes. - with _fake_native_context(): - got_fallback = dec_nat.symbols(0) - self.assertEqual(got_fallback.tobytes(), expected_sy.tobytes()) - - # 3. Trailing unstripped zero byte makes consumed != packed -> ValueError. - with _fake_native_context(): - with self.assertRaisesRegex(ValueError, "Entropy decode failed for chunk 1"): - dec_nat.symbols(1) - - # 4. Compatibility rotation on codec 1 rotates selected flat positions left by 1. - cycle = [1, 5, 13] - dec_rot = ct.LocalDecoder(pool, {"version": 1, "compatibility": {chunk_sha: cycle}}) - with _fake_native_context(): - rotated = dec_rot.symbols(0) - flat_orig = expected_sy.ravel().tolist() - flat_rot = rotated.ravel().tolist() - self.assertEqual(flat_rot[1], flat_orig[5]) - self.assertEqual(flat_rot[5], flat_orig[13]) - self.assertEqual(flat_rot[13], flat_orig[1]) - for idx in range(len(flat_orig)): - if idx not in cycle: - self.assertEqual(flat_rot[idx], flat_orig[idx]) - - # 5. Compatibility rotation errors (duplicate, out-of-range, negative, non-int including bool). - for bad_cycle in ([0, 0], [-1], [expected_sy.size], [True], [1.0], ["0"]): - with self.subTest(bad_cycle=bad_cycle): - dec_bad = ct.LocalDecoder( - pool, {"version": 1, "compatibility": {chunk_sha: bad_cycle}} - ) - with _fake_native_context(): - with self.assertRaisesRegex(ValueError, "Invalid symbol rotation"): - dec_bad.symbols(0) - - # 6. Compatibility does NOT run for non-BC1 codecs, empty cycle, or unknown sha. - bc4_sha = hashlib.sha256(packed_bc4).hexdigest() - dec_bc4 = ct.LocalDecoder(pool, {"version": 1, "compatibility": {bc4_sha: [0, 0]}}) - with _fake_native_context(): - sy4 = dec_bc4.symbols(2) - self.assertEqual(sy4.shape, (512, 12)) - - dec_noop = ct.LocalDecoder( - pool, - {"version": 1, "compatibility": {chunk_sha: [], "0" * 64: [0, 1]}}, - ) - with _fake_native_context(): - self.assertEqual(dec_noop.symbols(0).tobytes(), expected_sy.tobytes()) - - def test_read_chunk_errors_and_all_codecs(self): - # Raw (codec 0), zlib (codec 8), and bad-length zlib chunk - raw_bytes = bytes((i & 0xFF) for i in range(4096)) - zlib_bytes = zlib.compress(raw_bytes) - bad_zlib = zlib.compress(raw_bytes[:2048]) - - # Codec 6 (BC6H) and Codec 7 (BC7) - packed_bc6h = _encode_bc6h_solid(256) - packed_bc7 = _encode_bc7_mode6_solid(256) - - pool, _ = self._open_pool( - "codecs.ttpf", - [ttm.pack_etpf_record(64, 64, 1, 0, 71, 1, 1, 4, 4096)], - [ - (0, raw_bytes, 4096), - (8, zlib_bytes, 4096), - (8, bad_zlib, 4096), - (6, packed_bc6h, 4096), - (7, packed_bc7, 4096), - ], - ) - cal = { - "version": 1, - "bc6h": {}, - "bc7": _empty_bc7_section(), - } - dec = ct.LocalDecoder(pool, cal) - - # Size/block-size/codec mismatches (including unknown codec 99) - with self.assertRaisesRegex(ValueError, "Block size and codec disagree"): - dec.read_chunk(0, 7, "base") # 4096 % 7 != 0 - with self.assertRaisesRegex(ValueError, "Block size and codec disagree"): - dec.read_chunk(3, 8, "base") # codec 6 is 16-byte blocks, not 8 - orig_chunks = list(pool.chunks) - try: - pool.chunks = orig_chunks + [(0, 4096, 0, 4096, 99, 0)] - with self.assertRaisesRegex(ValueError, "Block size and codec disagree"): - dec.read_chunk(len(orig_chunks), 16, "base") - finally: - pool.chunks = orig_chunks - - # Raw & zlib - b_raw, m_raw = dec.read_chunk(0, 8, "base") - self.assertIsNone(m_raw) - self.assertEqual(b_raw.tobytes(), raw_bytes) - b_z, m_z = dec.read_chunk(1, 16, "base") - self.assertIsNone(m_z) - self.assertEqual(b_z.tobytes(), raw_bytes) - with self.assertRaisesRegex(ValueError, "Invalid raw chunk length"): - dec.read_chunk(2, 8, "base") - - # BC6H delegates to bcpack._bc6h_blocks - with _fake_native_context(): - b6, m6 = dec.read_chunk(3, 16, "base") - self.assertIsNone(m6) - self.assertEqual(b6.tobytes(), bcpack.decode(packed_bc6h, 6, 4096)) - - # BC7 profile cascades: early (1 call), base (early stop if all valid), base->secondary, refined->3 - call_seeds = [] - - def rebuild_early_stop(s_ptr, count, lab_ptr, seed_ptr, anc_ptr, out_ptr, ok_ptr): - call_seeds.append(_read_u8_buf(seed_ptr, 8)) - _write_u8_buf(out_ptr, b"\x11" * (count * 16)) - _write_u8_buf(ok_ptr, b"\x01" * count) - - with _fake_native_context(rebuild_fn=rebuild_early_stop): - b7_base, m7_base = dec.read_chunk(4, 16, "base") - self.assertEqual(len(call_seeds), 1) - self.assertTrue(m7_base.all()) - self.assertEqual(b7_base.tobytes(), b"\x11" * 4096) - - call_seeds.clear() - dec.read_chunk(4, 16, "early") - self.assertEqual(len(call_seeds), 1) - - # Partial fill across base -> secondary -> refined - cal2 = {"version": 1, "bc7": _empty_bc7_section()} - # Mark first byte of each seed so mocked rebuild distinguishes them - cal2["bc7"]["seeds"]["base"][0][0] = [1, 8] - cal2["bc7"]["seeds"]["secondary"][0][0] = [2, 8] - cal2["bc7"]["seeds"]["refined"][0][0] = [3, 8] - dec2 = ct.LocalDecoder(pool, cal2) - seen_tags = [] - - def rebuild_cascading(s_ptr, count, lab_ptr, seed_ptr, anc_ptr, out_ptr, ok_ptr): - tag = _read_u8_buf(seed_ptr, 1)[0] - seen_tags.append(tag) - out_buf = bytearray(count * 16) - ok_buf = bytearray(count) - for idx in range(count): - if (tag == 1 and idx % 3 == 0) or (tag == 2 and idx % 3 == 1): - out_buf[idx * 16 : (idx + 1) * 16] = bytes([tag]) * 16 - ok_buf[idx] = 1 - elif tag == 3 and idx == 2: - out_buf[idx * 16 : (idx + 1) * 16] = bytes([3]) * 16 - ok_buf[idx] = 1 - _write_u8_buf(out_ptr, bytes(out_buf)) - _write_u8_buf(ok_ptr, bytes(ok_buf)) - - with _fake_native_context(rebuild_fn=rebuild_cascading): - blocks, valid = dec2.read_chunk(4, 16, "refined") - self.assertEqual(seen_tags, [1, 2, 3]) - self.assertTrue(bool(valid[0]) and bool(valid[1]) and bool(valid[2])) - self.assertFalse(bool(valid[5])) # 5 % 3 == 2, != 2 - self.assertEqual(blocks.tobytes()[:48], b"\x01" * 16 + b"\x02" * 16 + b"\x03" * 16) - - def test_surface_bounds_multichunk_and_bc7_adjustments(self): - # Chunk 0: 4096 bytes raw (bs=16, 256 blocks) - # Chunk 1: 4096 bytes BC7 (bs=16, 256 blocks) - c0 = b"".join(bytes([i & 0xFF]) * 16 for i in range(256)) - c1 = _encode_bc7_mode6_solid(256) - pool, base = self._open_pool( - "surface.ttpf", - [ttm.pack_etpf_record(64, 64, 1, 0, 98, 1, 1, 4, 4096)], - [(0, c0, 4096), (7, c1, 4096)], - ) - cal = {"version": 1, "bc7": _empty_bc7_section()} - dec = ct.LocalDecoder(pool, cal) - - # Empty address array returns empty bytes cleanly - self.assertEqual(dec.surface(np.array([], dtype="int64"), 16, "base"), b"") - - # Out of bounds - for bad_at in ([base - 16], [base + 8192], [base, base + 10000]): - with self.subTest(bad_at=bad_at): - with self.assertRaisesRegex(ValueError, "Texture exceeds virtual pool"): - dec.surface(np.array(bad_at, dtype="int64"), 16, "base") - - # Non-monotonic multi-chunk lookup where unreferenced blocks in chunk 1 remain unresolved - def rebuild_partial(s_ptr, count, lab_ptr, seed_ptr, anc_ptr, out_ptr, ok_ptr): - seed_bytes = _read_u8_buf(seed_ptr, 256 * 56 * 2) - # Check if adjustment patched seed[7, 3] = (99, 8) - patched = seed_bytes[(7 * 56 + 3) * 2 : (7 * 56 + 3) * 2 + 2] == bytes([99, 8]) - out_buf = bytearray(count * 16) - ok_buf = bytearray(count) - for idx in range(count): - if idx == 10: - out_buf[idx * 16 : (idx + 1) * 16] = b"\xAA" * 16 - ok_buf[idx] = 1 - elif idx == 20 and patched: - out_buf[idx * 16 : (idx + 1) * 16] = b"\xBB" * 16 - ok_buf[idx] = 1 - _write_u8_buf(out_ptr, bytes(out_buf)) - _write_u8_buf(ok_ptr, bytes(ok_buf)) - - with _fake_native_context(rebuild_fn=rebuild_partial): - # Request block 10 of chunk 1 (resolved), block 5 of chunk 0, block 0 of chunk 0 - at_ok = np.array([base + 4096 + 10 * 16, base + 5 * 16, base], dtype="int64") - got_ok = dec.surface(at_ok, 16, "base") - self.assertEqual(got_ok, b"\xAA" * 16 + bytes([5]) * 16 + bytes([0]) * 16) - - # Request unresolved block 20 with profile != "refined" -> Missing calibrated blocks - at_miss = np.array([base + 4096 + 10 * 16, base + 4096 + 20 * 16], dtype="int64") - with self.assertRaisesRegex(ValueError, "Missing calibrated blocks"): - dec.surface(at_miss, 16, "base") - - # Refined profile: compute exact sha256 key expected by LocalDecoder.surface - sy1 = dec.symbols(1) - miss_ix = np.array([20], dtype=" Incomplete calibrated endpoints - cal["bc7"]["adjustments"][adj_key] = [(7, 3, 42)] - with self.assertRaisesRegex(ValueError, "Incomplete calibrated endpoints"): - dec.surface(at_miss, 16, "refined") - - # Valid adjustment resolves block 20 without mutating cached refined seed! - cal["bc7"]["adjustments"][adj_key] = [(7, 3, 99)] - got_ref = dec.surface(at_miss, 16, "refined") - self.assertEqual(got_ref, b"\xAA" * 16 + b"\xBB" * 16) - self.assertEqual(dec.seed("refined").tobytes()[(7 * 56 + 3) * 2 : (7 * 56 + 3) * 2 + 2], b"\x00\x08") - - def test_dds_end_to_end_codecs_and_layouts(self): - # 1. BC3 (fmt 77, codec 3), BC4 (fmt 80, codec 4), BC5 (fmt 83, codec 5), - # BC6H (fmt 95, codec 6), BC7 (fmt 98, codec 7) across 4K/64K, partial mips, - # non-square, all-tail, single-mip, and multi-chunk spans. - for fmt, codec, w, h, mips, mode in ( - (77, 3, 64, 32, 6, 4), # BC3, 4K tile, non-square - (80, 4, 16, 16, 5, 4), # BC4, 4K tile, all-tail (first_tail == 0) - (83, 5, 64, 64, 1, 4), # BC5, 4K tile, single-mip - (95, 6, 64, 64, 5, 4), # BC6H, 4K tile - (98, 7, 16, 16, 1, 0), # BC7, 64K tile, small single-mip - ): - with self.subTest(fmt=fmt, codec=codec, dims=(w, h, mips)): - tile = ttpf.tile_bytes(mode) - lay = ttpf.surface_layout(w, h, fmt, mips, tile) - linear = ttm.solid_chain(lay, fmt) - tiled = bytearray(lay["size"]) - for m in lay["mips"]: - ttm.retile_to(lay, m, linear[m["index"]], tiled) - - eb = lay["element_bytes"] - nblocks = lay["size"] // eb - if codec == 3: - inv_pair = {p: i for i, p in enumerate(bcpack_tables.BC3_ALPHA_PAIR)} - inv_quad = {v: i for i, v in enumerate(bcpack_tables.BC3_COLOUR_QUADRANT)} - lanes = [[] for _ in range(12)] - prev = (128, 128, 0, 0, 0, 0, 0, 0) - for i in range(nblocks): - blk = tiled[i * 16 : (i + 1) * 16] - a0, a1 = blk[0], blk[1] - abits = int.from_bytes(blk[2:8], "little") - c0, c1, r0, r1, r2, r3 = struct.unpack_from("> 11) & 31, (c0 >> 5) & 63, c0 & 31, - (c1 >> 11) & 31, (c1 >> 5) & 63, c1 & 31, - ) - mods = bcpack._BC3_MODS - deltas = [((ep[k] - prev[k] + mods[k] // 2) % mods[k]) - mods[k] // 2 for k in range(8)] - # Use d=0 on block 0, d=1 afterwards - if i == 0: - lanes[0].extend([0, 0]) - else: - d1a, d1b = tb._deint4(tb._zig(1) & 255) - lanes[0].extend([d1a, d1b]) - lanes[1].extend([0, 0]) - lanes[2].extend([tb._zig(deltas[0]), tb._zig(deltas[1])]) - for r in range(4): - row = (abits >> (12 * r)) & 0xFFF - lanes[3 + r].extend([ - inv_pair[(row & 7, (row >> 3) & 7)], - inv_pair[((row >> 6) & 7, (row >> 9) & 7)], - ]) - lanes[7].extend([tb._zig(deltas[2]), tb._zig(deltas[5])]) - lanes[8].extend([tb._zig(deltas[3]), tb._zig(deltas[6])]) - lanes[9].extend([tb._zig(deltas[4]), tb._zig(deltas[7])]) - qa = (r0 & 15) | ((r1 & 15) << 4) - qb = (r0 >> 4) | ((r1 >> 4) << 4) - qc = (r2 & 15) | ((r3 & 15) << 4) - qd = (r2 >> 4) | ((r3 >> 4) << 4) - lanes[10].extend([inv_quad[qa], inv_quad[qb]]) - lanes[11].extend([inv_quad[qc], inv_quad[qd]]) - prev = ep - packed_chunk = _encode_bc3_from_lanes(lanes) - elif codec == 4: - inv_pair = {p: i for i, p in enumerate(bcpack_tables.BC4_PAIR)} - lanes = [[] for _ in range(12)] - for i in range(nblocks): - blk = tiled[i * 8 : (i + 1) * 8] - a0, a1 = blk[0], blk[1] - bits = int.from_bytes(blk[2:8], "little") - lanes[0].append(0) - lanes[1].append(0) - lanes[2].append(tb._zig(((a0 - 128 + 128) % 256) - 128)) - lanes[3].append(tb._zig(((a1 - 128 + 128) % 256) - 128)) - for r in range(4): - row = (bits >> (12 * r)) & 0xFFF - lanes[4 + 2 * r].append(inv_pair[(row & 7, (row >> 3) & 7)]) - lanes[4 + 2 * r + 1].append(inv_pair[((row >> 6) & 7, (row >> 9) & 7)]) - packed_chunk = _encode_bc4_from_lanes(lanes) - elif codec == 5: - inv_pair = {p: i for i, p in enumerate(bcpack_tables.BC5_PAIR)} - lanes = [[] for _ in range(12)] - for i in range(nblocks): - blk = tiled[i * 16 : (i + 1) * 16] - r0, r1 = blk[0], blk[1] - br = int.from_bytes(blk[2:8], "little") - g0, g1 = blk[8], blk[9] - bg = int.from_bytes(blk[10:16], "little") - lanes[0].extend([0, 0]) - lanes[1].extend([0, 0]) - # Compatibility endpoint ordering: half 0 -> (r0, r1), half 1 -> (g0, g1) - lanes[2].extend([tb._zig(((r0 - 128 + 128) % 256) - 128), tb._zig(((g0 - 128 + 128) % 256) - 128)]) - lanes[3].extend([tb._zig(((r1 - 128 + 128) % 256) - 128), tb._zig(((g1 - 128 + 128) % 256) - 128)]) - for ch, bval in enumerate((br, bg)): - for r in range(4): - row = (bval >> (12 * r)) & 0xFFF - lanes[4 + 4 * ch + r].extend([ - inv_pair[(row & 7, (row >> 3) & 7)], - inv_pair[((row >> 6) & 7, (row >> 9) & 7)], - ]) - packed_chunk = _encode_bc5_from_lanes(lanes) - elif codec == 6: - # Use raw solid BC6H blocks with mode 0x0F? Simpler: encode mode-11 blocks and - # verify decoded DDS payload matches bcpack.decode(packed_chunk, 6, ...). - packed_chunk = _encode_bc6h_solid(nblocks) - decoded_bc6 = bcpack.decode(packed_chunk, 6, lay["size"]) - linear = {m["index"]: ttpf.detile(lay, m, decoded_bc6[m["offset"] : m["offset"] + m["region"]]) for m in lay["mips"]} - elif codec == 7: - # Ensure padding blocks are valid mode-6 for encoder - pad_blk = (1 << 6).to_bytes(16, "little") - for off in range(0, len(tiled), 16): - if tiled[off : off + 16] == b"\x00" * 16: - tiled[off : off + 16] = pad_blk - packed_chunk = tb.encode_bc7_mode6_blocks(bytes(tiled)) - - pool, base = self._open_pool( - f"pool_{fmt}.ttpf", - [ttm.pack_etpf_record(w, h, mips, 0, fmt, 1, 1, mode, 4096)], - [(codec, packed_chunk, lay["size"])], - ) - cal = { - "version": 1, - "bc3": _bc3_profile_from_tables(), - "bc4": {"custom": {str(k): list(v) for k, v in bcpack_tables.BC4_HISTORY_PROVISIONAL.items()}}, - "bc6h": {}, - "bc7": _empty_bc7_section(), - "entries": {Path(pool.path).name: {"0": "custom"}}, - } - - def rebuild_from_tiled(s_ptr, count, lab_ptr, seed_ptr, anc_ptr, out_ptr, ok_ptr, _t=bytes(tiled)): - _write_u8_buf(out_ptr, _t[: count * 16]) - _write_u8_buf(ok_ptr, b"\x01" * count) - - dec = ct.LocalDecoder(pool, cal) - with _fake_native_context(rebuild_fn=rebuild_from_tiled): - dds = dec.dds(0) - # Partial mips when mips > 1 - if mips > 1: - dds_part = dec.dds(0, mips=2) - hdr_p = tex_headers.parse_dds_header(dds_part) - self.assertEqual(hdr_p["mips"], 2) - self.assertEqual(dds_part[148:], linear[0] + linear[1]) - - hdr = tex_headers.parse_dds_header(dds) - self.assertEqual(hdr["width"], w) - self.assertEqual(hdr["height"], h) - self.assertEqual(hdr["mips"], mips) - self.assertEqual(hdr["dxgi_format"], fmt) - self.assertEqual(hdr["array_size"], 1) - self.assertEqual(dds[148:], b"".join(linear[i] for i in range(mips))) - - def test_dds_multichunk_and_2d_array_and_validation_errors(self): - # 2D texture spanning 2 chunks (raw + zlib) plus 2D array and invalid descriptors - lay = ttpf.surface_layout(64, 64, 71, 5, 4096) # size = 8192 = 2 * 4096 pages - lin = ttm.solid_chain(lay, 71) - tiled = bytearray(lay["size"]) - for m in lay["mips"]: - ttm.retile_to(lay, m, lin[m["index"]], tiled) - - # 2-slice 2D array using slice-major layout expected by LocalDecoder.dds - arr_lay = ttpf.surface_layout(32, 32, 71, 4, 4096) # 4096 bytes per slice - s0 = bytearray(4096) - s1 = bytearray(4096) - lin0 = ttm.solid_chain(arr_lay, 71, color_fn=lambda x, y, bw, bh: (255, 0, 0)) - lin1 = ttm.solid_chain(arr_lay, 71, color_fn=lambda x, y, bw, bh: (0, 255, 0)) - for m in arr_lay["mips"]: - ttm.retile_to(arr_lay, m, lin0[m["index"]], s0) - ttm.retile_to(arr_lay, m, lin1[m["index"]], s1) - - p_dummy = self.root / "multi.ttpf" - chunk0 = bytes(tiled[:4096]) - chunk1 = zlib.compress(bytes(tiled[4096:])) - chunk2 = bytes(s0 + s1) - base0 = ttpf.align(16 + 7 * 24 + 7 * 32, 4096) - # Keep records in non-decreasing base order so Pool.span() maps rec0 and rec1 accurately. - rec_unmapped = ttm.pack_etpf_record(32, 32, 1, 0, 71, 1, 1, 4, 0) - rec0 = ttm.pack_etpf_record(64, 64, 5, 0, 71, 1, 1, 4, base0) - rec_bad_fmt = ttm.pack_etpf_record(32, 32, 1, 0, 28, 1, 1, 4, base0) - rec_bad_dim = ttm.pack_etpf_record(32, 32, 1, 0, 71, 6, 2, 18, base0) - rec_huge = ttm.pack_etpf_record(16384, 16384, 1, 0, 98, 2, 1, 4, base0) - rec1 = ttm.pack_etpf_record(32, 32, 4, 0, 71, 2, 1, 4, base0 + 8192) - rec_cross = ttm.pack_etpf_record(256, 256, 7, 1, 71, 1, 1, 4, base0 + 8192) - - write_custom_pool( - p_dummy, - [rec_unmapped, rec0, rec_bad_fmt, rec_bad_dim, rec_huge, rec1, rec_cross], - [(0, chunk0, 4096), (8, chunk1, 4096), (0, chunk2, 8192)], - ) - pool = ttpf.Pool(str(p_dummy)) - self.addCleanup(pool.close) - dec = ct.LocalDecoder(pool, {"version": 1}) - - # Multi-chunk 2D texture (index 1) - dds0 = dec.dds(1) - self.assertEqual(dds0[148:], b"".join(lin[i] for i in range(5))) - - # 2D array (depth=2, index 5) - dds1 = dec.dds(5) - hdr1 = tex_headers.parse_dds_header(dds1) - self.assertEqual((hdr1["array_size"], hdr1["mips"]), (2, 4)) - expected_arr = b"".join(lin0[i] for i in range(4)) + b"".join(lin1[i] for i in range(4)) - self.assertEqual(dds1[148:], expected_arr) - - # Error paths - with self.assertRaisesRegex(ValueError, "supported BCn 2D texture or array"): - dec.dds(2) - with self.assertRaisesRegex(ValueError, "supported BCn 2D texture or array"): - dec.dds(3) - for bad_mips in (0, -1, 6): - with self.assertRaisesRegex(ValueError, "Mip count outside descriptor range"): - dec.dds(1, mips=bad_mips) - with self.assertRaisesRegex(ValueError, "Texture has no mapped allocation"): - dec.dds(0) - with self.assertRaisesRegex(ValueError, "Texture crosses its allocation boundary"): - dec.dds(6) - with self.assertRaisesRegex(ValueError, "DDS exceeds output limit"): - dec.dds(4) - - def test_dds_no_tail_64k_tile_layout(self): - # 512x256 BC7 (fmt 98, bs=16, 64K tile -> bw=64, bh=64) with 2 mips: - # mip 0 is 128x64 blocks (2 tiles), mip 1 is 64x32 blocks (> bw//2=32 -> 1 tile), so tail == 2 == levels. - lay = ttpf.surface_layout(512, 256, 98, 2, 65536) - self.assertEqual(lay["first_tail"], 2) - lin0 = bytes([0xAA] * (128 * 64 * 16)) - lin1 = bytes([0xBB] * (64 * 32 * 16)) - tiled = bytearray(lay["size"]) - ttm.retile_to(lay, lay["mips"][0], lin0, tiled) - ttm.retile_to(lay, lay["mips"][1], lin1, tiled) - pool, _ = self._open_pool( - "notail.ttpf", - [ttm.pack_etpf_record(512, 256, 2, 0, 98, 1, 1, 0, 4096)], - [(8, zlib.compress(bytes(tiled)), lay["size"])], - ) - dec = ct.LocalDecoder(pool, {"version": 1}) - dds = dec.dds(0) - self.assertEqual(dds[148:], lin0 + lin1) - - def test_compact_dds_layout_uses_tex_headers_tail_and_mips(self): - # ASSET-568: NPOT chains and a single-mip sub-tile must use the measured compact - # layout's first_tail/mips, not locally re-derived grids (the latter packed a - # lone mip into the tail and misplaced the NPOT standalone subresources). - for width, height, fmt, levels, tile in ((65, 65, 98, 7, 4096), (32, 32, 71, 1, 4096)): - with self.subTest(size=(width, height, fmt, levels, tile)): - lay = ttpf.surface_layout(width, height, fmt, levels, tile) - bw, bh, grids, offsets = ct.compact_dds_layout(width, height, fmt, levels, tile) - self.assertEqual((bw, bh), (lay["block_w"], lay["block_h"])) - self.assertEqual(grids, [(m["blocks_w"], m["blocks_h"]) for m in lay["mips"]]) - stride = tile if lay["first_tail"] < levels else 0 - for m in lay["mips"]: - i = m["index"] - if i < lay["first_tail"]: - want = (m["offset"], 0, 0, stride) - else: - want = (0, m["tile_x"], m["tile_y"], stride) - self.assertEqual(offsets[i], want) - if levels == 1: - self.assertEqual(lay["first_tail"], 1) - self.assertEqual(offsets[0], (0, 0, 0, 0)) - - def test_all_supported_formats_and_entries_fallback(self): - self.assertEqual(ct.LocalDecoder.formats, frozenset((71, 72, 77, 78, 80, 83, 95, 96, 98, 99))) - base0 = ttpf.align(16 + 10 * 24 + 10 * 32, 4096) - records = [ - ttm.pack_etpf_record(16, 16, 1, 0, fmt, 1, 1, 4, base0) - for fmt in sorted(ct.LocalDecoder.formats) - ] - pool, _ = self._open_pool("all_fmts.ttpf", records, [(0, b"\x5A" * 4096, 4096)]) - dec = ct.LocalDecoder( - pool, - {"version": 1, "entries": {"other.ttpf": {"0": "early"}, "all_fmts.ttpf": {"9": "custom"}}}, - ) - seen_profiles = [] - orig_surface = dec.surface - - def spy_surface(at, bs, profile): - seen_profiles.append(profile) - return orig_surface(at, bs, profile) - - with mock.patch.object(dec, "surface", side_effect=spy_surface): - for idx, fmt in enumerate(sorted(ct.LocalDecoder.formats)): - dds = dec.dds(idx) - hdr = tex_headers.parse_dds_header(dds) - bs = 8 if fmt in (71, 72, 80) else 16 - self.assertEqual(hdr["dxgi_format"], fmt) - self.assertEqual(hdr["pitch_linear"], 4 * 4 * bs) - self.assertEqual(dds[148:], b"\x5A" * (16 * bs)) - self.assertEqual(seen_profiles, ["base"] * 9 + ["custom"]) - - def test_invalid_bc1_and_bc7_config_shapes(self): - bc1_packed = tb.encode_bc1_blocks(b"\x00" * 4096) - bc7_packed = _encode_bc7_mode6_solid(256) - pool, _ = self._open_pool( - "bad_cfg.ttpf", - [ttm.pack_etpf_record(64, 64, 1, 0, 71, 1, 1, 4, 4096)], - [(1, bc1_packed, 4096), (7, bc7_packed, 4096)], - ) - bad_bc1 = ct.LocalDecoder( - pool, {"version": 1, "bc1": {"endpoints": [[0] * 6], "selectors": [[0] * 256] * 4}} - ) - with _fake_native_context(), self.assertRaisesRegex(ValueError, "Invalid calibration field"): - bad_bc1.read_chunk(0, 8, "base") - - bad_bc7 = ct.LocalDecoder( - pool, {"version": 1, "bc7": {"labels": [[0, 0, 0, 0]], "anchors": [0] * 128}} - ) - with _fake_native_context(), self.assertRaisesRegex(ValueError, "Invalid calibration field"): - bad_bc7.read_chunk(1, 16, "base") - - -class TestExportFileAndCli(unittest.TestCase): - def setUp(self): - tmp = tempfile.TemporaryDirectory() - self.addCleanup(tmp.cleanup) - self.root = Path(tmp.name) - self.pool_path = self.root / "pool.ttpf" - self.lay, self.linear, _ = ttm.build_bc1_bcpack_pool(self.pool_path) - self.profile = self.root / "profile.json" - self.profile.write_text(json.dumps(synthetic_profile()), encoding="utf-8") - - def test_export_file_atomic_link_replace_and_cleanup(self): - pool = ttpf.Pool(str(self.pool_path)) - self.addCleanup(pool.close) - out = self.root / "out.dds" - - # 1. Create new file (force=False) - with _fake_native_context(): - rc = ct.export_file(pool, 0, out, None, False, self.profile) - self.assertEqual(rc, 0) - data = out.read_bytes() - self.assertEqual(data[:4], b"DDS ") - self.assertEqual(data[148:], b"".join(self.linear[i] for i in sorted(self.linear))) - # No leftover temporary files - self.assertEqual(sorted(p.name for p in self.root.iterdir()), ["out.dds", "pool.ttpf", "profile.json"]) - - # 2. Existing target with force=False raises FileExistsError, keeps target intact, cleans tmp - out.write_bytes(b"SENTINEL") - with _fake_native_context(): - with self.assertRaises(FileExistsError): - ct.export_file(pool, 0, out, None, False, self.profile) - self.assertEqual(out.read_bytes(), b"SENTINEL") - self.assertEqual(sorted(p.name for p in self.root.iterdir()), ["out.dds", "pool.ttpf", "profile.json"]) - - # 3. Existing target with force=True replaces target atomically and cleans tmp - with _fake_native_context(): - rc_force = ct.export_file(pool, 0, out, 2, True, self.profile) - self.assertEqual(rc_force, 0) - replaced = out.read_bytes() - self.assertEqual(tex_headers.parse_dds_header(replaced)["mips"], 2) - self.assertEqual(replaced[148:], self.linear[0] + self.linear[1]) - self.assertEqual(sorted(p.name for p in self.root.iterdir()), ["out.dds", "pool.ttpf", "profile.json"]) - - # 4. Cache is cleared even if dds() fails - clear_calls = [] - - with _fake_native_context(), \ - mock.patch.object(ct.LocalDecoder, "dds", side_effect=ValueError("boom")): - orig_init = ct.LocalDecoder.__init__ - - def tracked_init(self_dec, p, c): - orig_init(self_dec, p, c) - orig_cc = self_dec.read_chunk.cache_clear - self_dec.read_chunk.cache_clear = lambda: (clear_calls.append(1), orig_cc())[1] - - with mock.patch.object(ct.LocalDecoder, "__init__", tracked_init): - with self.assertRaisesRegex(ValueError, "boom"): - ct.export_file(pool, 0, self.root / "unused.dds", None, False, self.profile) - self.assertEqual(len(clear_calls), 1) - - # 5. Missing or invalid profile JSON - with self.assertRaises(FileNotFoundError): - ct.export_file(pool, 0, self.root / "u.dds", None, False, self.root / "missing.json") - bad_json = self.root / "bad.json" - bad_json.write_text("{not json", encoding="utf-8") - with self.assertRaises(json.JSONDecodeError): - ct.export_file(pool, 0, self.root / "u.dds", None, False, bad_json) - - def test_ttpf_mips_cli_calibration_paths(self): - out = self.root / "cli.dds" - - def run_cli(*argv): - out_buf, err_buf = io.StringIO(), io.StringIO() - with mock.patch.dict(sys.modules, {"calibrated_texture": ct}), \ - _fake_native_context(), \ - redirect_stdout(out_buf), redirect_stderr(err_buf): - rc = ttpf.main(list(argv)) - return rc, out_buf.getvalue(), err_buf.getvalue() - - # Success - rc, _, err = run_cli("export", str(self.pool_path), "0", str(out), "--calibration", str(self.profile)) - self.assertEqual(rc, 0, err) - dds = out.read_bytes() - self.assertEqual(dds[:4], b"DDS ") - self.assertEqual(dds[148:], b"".join(self.linear[i] for i in sorted(self.linear))) - - # Refuses overwrite without --force - out.write_bytes(b"KEEP_ME") - rc2, _, err2 = run_cli("export", str(self.pool_path), "0", str(out), "--calibration", str(self.profile)) - self.assertEqual(rc2, 2) - self.assertIn("calibrated export failed", err2) - self.assertNotIn("Traceback", err2) - self.assertEqual(out.read_bytes(), b"KEEP_ME") - - # Overwrites with --force and --mips - rc3, _, err3 = run_cli( - "export", str(self.pool_path), "0", str(out), - "--calibration", str(self.profile), "--mips", "1", "--force", - ) - self.assertEqual(rc3, 0, err3) - self.assertEqual(tex_headers.parse_dds_header(out.read_bytes())["mips"], 1) - - # Rejects --calibration + --history together - rc4, _, err4 = run_cli( - "export", str(self.pool_path), "0", str(out), - "--calibration", str(self.profile), "--history", str(self.profile), "--force", - ) - self.assertEqual(rc4, 2) - self.assertIn("choose either --calibration or --history", err4) - - # Bad profile version returns exit code 2 cleanly - self.profile.write_text('{"version": 99}', encoding="utf-8") - rc5, _, err5 = run_cli( - "export", str(self.pool_path), "0", str(out), - "--calibration", str(self.profile), "--force", - ) - self.assertEqual(rc5, 2) - self.assertIn("Unsupported calibration version", err5) - self.assertNotIn("Traceback", err5) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/test_carve_all_brackets.py b/tests/test_carve_all_brackets.py deleted file mode 100644 index bbb9e5746..000000000 --- a/tests/test_carve_all_brackets.py +++ /dev/null @@ -1,34 +0,0 @@ -"""carve_all.ps1 with a game folder whose name holds [ ] (PowerShell wildcard characters).""" -import json -import os -from pathlib import Path -import subprocess -import tempfile -import unittest - -SCRIPT = Path(__file__).resolve().parents[1] / "scripts" / "carve_all.ps1" -INDEX = {"summary": {"files": 1, "bink2_files": 0, "span": 10, "compressed_bytes": 5, "unread_bytes": 5, - "inflated_bytes": 5}, "files": []} - - -@unittest.skipUnless(os.name == "nt", "PowerShell research script") -class CarveAllBracketPathTest(unittest.TestCase): - def test_bracketed_game_folder_finds_its_archives(self): - with tempfile.TemporaryDirectory() as tmp: - game, out = Path(tmp, "GTA VI [1.0.2.1]"), Path(tmp, "carves [1]") - game.mkdir() - (game / "common.rpf").write_bytes(b"x") - (out / "common").mkdir(parents=True) - (out / "common" / "index.json").write_text(json.dumps(INDEX), encoding="utf-8") - result = subprocess.run( - ["powershell.exe", "-NoProfile", "-ExecutionPolicy", "Bypass", "-File", str(SCRIPT), - "-Game", str(game), "-Out", str(out)], cwd=tmp, capture_output=True, text=True) - self.assertEqual(result.returncode, 0, result.stdout + result.stderr) - text = (out / "coverage.json").read_text(encoding="utf-8-sig").strip() - rows = json.loads(text) if text else [] - rows = rows if isinstance(rows, list) else [rows] - self.assertEqual([r["archive"] for r in rows], ["common.rpf"]) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/test_carve_all_paths.py b/tests/test_carve_all_paths.py deleted file mode 100644 index 70dc2cfab..000000000 --- a/tests/test_carve_all_paths.py +++ /dev/null @@ -1,233 +0,0 @@ -import ctypes -import json -import os -from pathlib import Path -import subprocess -import tempfile -import unittest - - -SCRIPT = Path(__file__).resolve().parents[1] / "scripts" / "carve_all.ps1" -INDEX = {"summary": {"files": 1, "bink2_files": 0, "span": 10, "compressed_bytes": 5, "unread_bytes": 5, - "inflated_bytes": 5}, "files": []} - - -@unittest.skipUnless(os.name == "nt", "PowerShell research script") -class CarveAllGamePathTest(unittest.TestCase): - def test_invalid_cached_summary_does_not_replace_coverage(self): - with tempfile.TemporaryDirectory() as tmp: - game, out = Path(tmp, "game"), Path(tmp, "out") - game.mkdir() - (game / "sample.rpf").write_bytes(b"x") - cached = out / "sample" - cached.mkdir(parents=True) - index = cached / "index.json" - coverage = out / "coverage.json" - summary = INDEX["summary"] - invalid_indexes = { - "invalid JSON": "{", - "missing summary": "{}", - "negative span": json.dumps({"summary": {**summary, "span": -1}}), - "bytes in empty span": json.dumps({"summary": {**summary, "span": 0}}), - "non-numeric span": json.dumps({"summary": {**summary, "span": "ten"}}), - "missing count": json.dumps({"summary": {k: v for k, v in summary.items() if k != "files"}}), - } - for case, contents in invalid_indexes.items(): - with self.subTest(case=case): - index.write_text(contents, encoding="utf-8") - coverage.write_bytes(b"[]\n") - result = subprocess.run( - ["powershell.exe", "-NoProfile", "-ExecutionPolicy", "Bypass", "-File", str(SCRIPT), - "-Game", str(game), "-Out", str(out)], capture_output=True, text=True, timeout=30, - ) - self.assertNotEqual(result.returncode, 0, result.stdout + result.stderr) - self.assertIn("Invalid carve index", result.stderr) - self.assertIn("index.json", result.stderr) - self.assertEqual(coverage.read_bytes(), b"[]\n") - - def test_empty_cached_data_area_reports_zero_coverage(self): - with tempfile.TemporaryDirectory() as tmp: - game, out = Path(tmp, "game"), Path(tmp, "out") - game.mkdir() - (game / "empty.rpf").write_bytes(b"x") - cached = out / "empty" - cached.mkdir(parents=True) - summary = {key: 0 for key in INDEX["summary"]} - (cached / "index.json").write_text(json.dumps({"summary": summary, "files": []}), encoding="utf-8") - result = subprocess.run( - ["powershell.exe", "-NoProfile", "-ExecutionPolicy", "Bypass", "-File", str(SCRIPT), - "-Game", str(game), "-Out", str(out)], capture_output=True, text=True, timeout=30, - ) - self.assertEqual(result.returncode, 0, result.stdout + result.stderr) - row = json.loads((out / "coverage.json").read_text(encoding="utf-8-sig")) - self.assertEqual(row, {"archive": "empty.rpf", "files": 0, "bink2": 0, "span": 0, - "readable": 0, "unread": 0, "inflated": 0}) - - def test_inconsistent_cached_summary_does_not_replace_coverage(self): - summary = INDEX["summary"] - cases = { - "compressed past span": ({"compressed_bytes": 11, "unread_bytes": 0}, "compressed_bytes"), - "unread past span": ({"compressed_bytes": 0, "unread_bytes": 11}, "unread_bytes"), - "combined bytes past span": ({"compressed_bytes": 7, "unread_bytes": 4}, "unread_bytes"), - "bink past file count": ({"bink2_files": 2}, "bink2_files"), - "int64 byte sum past span by one": ( - {"span": 2**63 - 1, "compressed_bytes": 2**62, "unread_bytes": 2**62}, "unread_bytes"), - "int64 bink past file count by one": ( - {"files": 2**62, "bink2_files": 2**62 + 1}, "bink2_files"), - } - with tempfile.TemporaryDirectory() as tmp: - game, out = Path(tmp, "game"), Path(tmp, "out") - game.mkdir() - (game / "sample.rpf").write_bytes(b"x") - cache = out / "sample" - cache.mkdir(parents=True) - index, coverage = cache / "index.json", out / "coverage.json" - previous = b"previous complete coverage\x00\xff" - for label, (changes, field) in cases.items(): - with self.subTest(case=label): - index.write_text(json.dumps({"summary": {**summary, **changes}, "files": []}), - encoding="utf-8", newline="\n") - coverage.write_bytes(previous) - result = subprocess.run( - ["powershell.exe", "-NoProfile", "-ExecutionPolicy", "Bypass", "-File", str(SCRIPT), - "-Game", str(game), "-Out", str(out)], capture_output=True, text=True, timeout=30, - ) - self.assertNotEqual(result.returncode, 0, result.stdout + result.stderr) - self.assertIn("Invalid carve index", result.stderr) - self.assertIn(field, result.stderr) - self.assertEqual(coverage.read_bytes(), previous) - - def test_consistent_summary_boundaries_keep_the_expected_counts(self): - cases = { - "exact span": {**INDEX["summary"], "bink2_files": 1}, - "int64 exact span": {**INDEX["summary"], "span": 2**63 - 1, - "compressed_bytes": 2**62, "unread_bytes": 2**62 - 1}, - "only padding": {"files": 0, "bink2_files": 0, "span": 10, "compressed_bytes": 0, - "unread_bytes": 0, "inflated_bytes": 0}, - } - with tempfile.TemporaryDirectory() as tmp: - game, out = Path(tmp, "game"), Path(tmp, "out") - game.mkdir() - (game / "sample.rpf").write_bytes(b"x") - cache = out / "sample" - cache.mkdir(parents=True) - for label, summary in cases.items(): - with self.subTest(case=label): - (cache / "index.json").write_text(json.dumps({"summary": summary, "files": []}), - encoding="utf-8", newline="\n") - result = subprocess.run( - ["powershell.exe", "-NoProfile", "-ExecutionPolicy", "Bypass", "-File", str(SCRIPT), - "-Game", str(game), "-Out", str(out)], capture_output=True, text=True, timeout=30, - ) - self.assertEqual(result.returncode, 0, result.stdout + result.stderr) - self.assertEqual(result.stderr, "") - row = json.loads((out / "coverage.json").read_text(encoding="utf-8-sig")) - self.assertEqual((row["files"], row["bink2"], row["span"], row["inflated"]), - tuple(summary[key] for key in ("files", "bink2_files", "span", "inflated_bytes"))) - self.assertEqual(row["readable"], round(summary["compressed_bytes"] / summary["span"], 4)) - self.assertEqual(row["unread"], round(summary["unread_bytes"] / summary["span"], 4)) - - def test_failed_carver_stops_without_replacing_coverage(self): - with tempfile.TemporaryDirectory() as tmp: - root = Path(tmp) - game, out, tools = root / "game", root / "out", root / "tools" - for folder in (game, out, tools): - folder.mkdir() - (game / "first.rpf").write_bytes(b"x") - (game / "second.rpf").write_bytes(b"xx") - (tools / "python.cmd").write_bytes(b"@exit /b 7\r\n") - coverage = out / "coverage.json" - coverage.write_bytes(b"[]\n") - result = subprocess.run( - ["powershell.exe", "-NoProfile", "-ExecutionPolicy", "Bypass", "-File", str(SCRIPT), - "-Game", str(game), "-Out", str(out)], - env={**os.environ, "PATH": str(tools) + os.pathsep + os.environ["PATH"]}, - capture_output=True, text=True, timeout=30, - ) - self.assertNotEqual(result.returncode, 0, result.stdout + result.stderr) - self.assertIn("Carving first.rpf failed (exit 7)", result.stderr) - self.assertNotIn("second.rpf", result.stdout + result.stderr) - self.assertEqual(coverage.read_bytes(), b"[]\n") - - def test_relative_and_trailing_separator_game_paths_find_existing_carves(self): - with tempfile.TemporaryDirectory() as tmp: - game, out = Path(tmp, "game"), Path(tmp, "out") - (game / "pack" / "p1").mkdir(parents=True) - (game / "common.rpf").write_bytes(b"x") - (game / "pack" / "p1" / "p1.rpf").write_bytes(b"xy") - # Both archives are already carved, so no carve should start. - for name in ("common", "pack_p1_p1"): - (out / name).mkdir(parents=True) - (out / name / "index.json").write_text(json.dumps(INDEX), encoding="utf-8") - args = ["game", ".\\game", str(game) + "\\"] - short_game = ctypes.create_unicode_buffer(32768) - short_path_length = ctypes.windll.kernel32.GetShortPathNameW(str(game), short_game, len(short_game)) - if short_path_length and short_game.value.casefold() != str(game).casefold(): - args.append(short_game.value + "\\") - for arg in args: - with self.subTest(game=arg): - result = subprocess.run( - ["powershell.exe", "-NoProfile", "-ExecutionPolicy", "Bypass", "-File", str(SCRIPT), - "-Game", arg, "-Out", str(out)], cwd=tmp, capture_output=True, text=True) - self.assertEqual(result.returncode, 0, result.stdout + result.stderr) - self.assertNotIn("carving", result.stdout) - rows = json.loads((out / "coverage.json").read_text(encoding="utf-8-sig")) - self.assertEqual([r["archive"] for r in rows], ["common.rpf", "pack\\p1\\p1.rpf"]) - self.assertEqual(sorted(p.name for p in out.iterdir()), - ["common", "coverage.json", "pack_p1_p1"]) - - def test_game_path_with_83_short_name_component_finds_existing_carves(self): - # Resolve-Path keeps an 8.3 component (e.g. RUNNER~1) but Get-ChildItem emits canonical - # FullNames. A trailing separator plus such a component used to cut the rel path at the - # wrong offset, re-carving archives that were already present. - with tempfile.TemporaryDirectory() as tmp: - base = Path(tmp, "LongDirectoryNameForCarveAllShortPath") - game, out = base / "game", base / "out" - (game / "pack" / "p1").mkdir(parents=True) - (game / "common.rpf").write_bytes(b"x") - (game / "pack" / "p1" / "p1.rpf").write_bytes(b"xy") - for name in ("common", "pack_p1_p1"): - (out / name).mkdir(parents=True) - (out / name / "index.json").write_text(json.dumps(INDEX), encoding="utf-8") - buf = ctypes.create_unicode_buffer(1024) - get_short = ctypes.windll.kernel32.GetShortPathNameW - get_short.argtypes = [ctypes.c_wchar_p, ctypes.c_wchar_p, ctypes.c_uint] - get_short.restype = ctypes.c_uint - if not get_short(str(game), buf, len(buf)): - self.skipTest("GetShortPathNameW failed") - short_game = buf.value + "\\" - if short_game == str(game) + "\\": - self.skipTest("8.3 short names are unavailable on this volume") - result = subprocess.run( - ["powershell.exe", "-NoProfile", "-ExecutionPolicy", "Bypass", "-File", str(SCRIPT), - "-Game", short_game, "-Out", str(out)], cwd=tmp, capture_output=True, text=True) - self.assertEqual(result.returncode, 0, result.stdout + result.stderr) - self.assertNotIn("carving", result.stdout) - rows = json.loads((out / "coverage.json").read_text(encoding="utf-8-sig")) - self.assertEqual([r["archive"] for r in rows], ["common.rpf", "pack\\p1\\p1.rpf"]) - - def test_colliding_archive_names_do_not_share_a_cached_index(self): - with tempfile.TemporaryDirectory() as tmp: - game, out = Path(tmp, "game"), Path(tmp, "out") - (game / "pack").mkdir(parents=True) - (game / "pack" / "scene.rpf").write_bytes(b"x") - (game / "PACK_scene.rpf").write_bytes(b"xx") - cached = out / "pack_scene" - cached.mkdir(parents=True) - (cached / "index.json").write_text(json.dumps(INDEX), encoding="utf-8") - coverage = out / "coverage.json" - coverage.write_bytes(b"[]\n") - - result = subprocess.run( - ["powershell.exe", "-NoProfile", "-ExecutionPolicy", "Bypass", "-File", str(SCRIPT), - "-Game", str(game), "-Out", str(out)], capture_output=True, text=True, timeout=30, - ) - self.assertNotEqual(result.returncode, 0, result.stdout + result.stderr) - self.assertIn("pack\\scene.rpf", result.stderr) - self.assertIn("PACK_scene.rpf", result.stderr) - self.assertNotIn("carving", result.stdout) - self.assertEqual(coverage.read_bytes(), b"[]\n") - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/test_carve_short_system_pages.py b/tests/test_carve_short_system_pages.py deleted file mode 100644 index 6186fe520..000000000 --- a/tests/test_carve_short_system_pages.py +++ /dev/null @@ -1,281 +0,0 @@ -"""Declared short model pages survive the real carver and folder joiner. Synthetic bytes only.""" -import json -import os -from pathlib import Path -import struct -import subprocess -import sys -import tempfile -import unittest -import zlib - -ROOT = Path(__file__).resolve().parents[1] -sys.path[:0] = [str(ROOT / "tests"), str(ROOT / "tools")] -import test_restofworld_model_join as fixture # noqa: E402 -import restofworld_model_join as joiner # noqa: E402 - - -def model_pages(final_size=48, middle_pages=0, first_size=65536): - system, graphics = fixture.make_standalone_drawable_1x1() - first = bytearray(system[0].ljust(first_size, b"\0")) - fixture._write_page_map(first, first_size - 64, middle_pages + 2, 1) - if final_size >= 22: - struct.pack_into("= 64 for row in index["files"])) - self.assertEqual(joiner.scan_rpf(str(source))[1]["joined_resources"], 0) - self.assertEqual(joiner.scan_dir(str(folder))[1]["joined_resources"], 0) - - def test_archive_framing_breaks_do_not_admit_the_short_page(self): - for kind in ("wide gap", "nonzero padding", "unaligned root", "nonzero root prefix", "bad checksum", "Bink"): - with self.subTest(kind=kind): - pages = model_pages() - data, recorded = fixture.pack_synthetic_rpf([pages]) - offsets = recorded[0][0] - data = bytearray(data) - if kind == "wide gap": - data[offsets[1]:offsets[1]] = b"\0" * 16 - elif kind == "nonzero padding": - self.assertLess(offsets[0] + len(zlib.compress(pages[0])), offsets[1]) - data[offsets[1] - 1] = 1 - elif kind == "unaligned root": - data[offsets[0]:offsets[0]] = b"\0" * 16 - elif kind == "nonzero root prefix": - data[offsets[0] - 1] = 1 - elif kind == "bad checksum": - data[offsets[1] + len(zlib.compress(pages[1])) - 1] ^= 1 - else: - data[offsets[1]:offsets[1]] = fixture.make_bink2() - source, folder, index = self.carve(bytes(data)) - self.assertTrue(all(row["size"] >= 64 for row in index["files"])) - self.assertEqual(joiner.scan_rpf(str(source))[1]["joined_resources"], 0) - self.assertEqual(joiner.scan_dir(str(folder))[1]["joined_resources"], 0) - - def test_scan_windows_still_bound_the_complete_continuation(self): - pages = model_pages() - data, recorded = fixture.pack_synthetic_rpf([pages]) - offsets = recorded[0][0] - end = offsets[1] + len(zlib.compress(pages[1])) - for delta, expected in ((-1, [65536]), (0, [65536, 48])): - with self.subTest(checksum_end_delta=delta): - _, _, index = self.carve(data, "--limit", end + delta - offsets[0]) - self.assertEqual([row["size"] for row in index["files"]], expected) - _, _, index = self.carve(data, "--start", offsets[1]) - self.assertEqual([row["size"] for row in index["files"]], [len(pages[-1])]) - - def test_folder_mode_keeps_its_framing_policy_and_inflate_limit(self): - folder = self.root / "bare" - folder.mkdir() - for i, page in enumerate(model_pages()): - (folder / f"{i + 1:012x}.bin").write_bytes(page) - resources, summary = joiner.scan_dir(str(folder)) - self.assertEqual(summary["joined_resources"], 1) - self.assertEqual(resources[0]["system_bytes"], 65536 + 48) - _, capped = joiner.scan_dir(str(folder), max_inflate=32768) - self.assertEqual(capped["skipped_candidates"], 1) - self.assertEqual(capped["zlib_streams"], 1) - self.assertEqual(capped["joined_resources"], 0) - # All read-only mappings must be closed before returning, including on Windows. - os.replace(folder / "000000000001.bin", folder / "renamed.bin") - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/test_cf_diff.py b/tests/test_cf_diff.py deleted file mode 100644 index 03f191347..000000000 --- a/tests/test_cf_diff.py +++ /dev/null @@ -1,171 +0,0 @@ -"""Tests for tools/cf_diff.py and tools/cf_ref.py, the FUZZ-8 control-flow fuzzer (no game data, no GPU, no -llvm-mc). - - python -m pytest tests/test_cf_diff.py -v -""" -import os -import random -import subprocess -import sys -import tempfile - -import pytest - -ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) -TOOL = os.path.join(ROOT, "tools", "cf_diff.py") -sys.path.insert(0, os.path.join(ROOT, "tools")) - -import cf_diff # noqa: E402 -import cf_ref # noqa: E402 -import rdna2spirv # noqa: E402 - -# Condition true for lanes 4 and 20 only (v3 = lane * 5 & 15), so a lane's own bit and the wave's mask disagree. -FEW_LANES = ("eq", "u32", 4, 3) - -# Wave32 shapes whose SCC comes from a 32-bit logic op on lane masks. Until 2026-11-22 the translator set that SCC -# from the lane's own bit instead of the whole mask, and every one of these mismatched. -SCC_MASK_CASES = { - "s_and_b32 + s_cbranch_scc0": [("sccmask", FEW_LANES, "and", "s_cbranch_scc0", [("probe", 11)])], - "s_xor_b32 + s_cbranch_scc1": [("sccmask", FEW_LANES, "xor", "s_cbranch_scc1", [("probe", 11)])], - "s_xor_b32 + s_cselect_b32": [("csel", FEW_LANES, "xor", 11)], - "loop closed by s_andn2_b32 exec + s_cbranch_scc1": [ - ("vloop", (0, 3, True), None, [("probe", 9), ("op", "s_add_u32 s10, s10, 1")])], -} - - -@pytest.mark.parametrize("count", ["0", "-1"]) -def test_empty_program_batch_is_a_usage_error(count, capsys, monkeypatch): - def unexpected_suite(*args, **kwargs): - pytest.fail("started a suite with no programs") - - monkeypatch.setattr(cf_diff, "run_suite", unexpected_suite) - with pytest.raises(SystemExit) as exc: - cf_diff.main(["--programs", count]) - assert exc.value.code == 2 - captured = capsys.readouterr() - assert "--programs must be at least 1" in captured.err - assert captured.out == "" - - -def test_a_run_where_every_program_was_skipped_is_not_a_success(capsys, monkeypatch): - monkeypatch.setattr(cf_diff, "run_case", lambda *args, **kwargs: ("skip", "unsupported form")) - assert cf_diff.main(["--programs", "2", "--seed", "1"]) == 2 - assert "no program ran: every one was skipped" in capsys.readouterr().out - - -@pytest.mark.parametrize("statuses, code", [ - (["skip", "skip"], 2), # nothing was compared - (["skip", "mismatch"], 1), # a mismatch outranks "nothing else ran" - (["match", "skip"], 0), # one wave compared and matched -]) -def test_a_single_program_run_exits_like_the_suite(statuses, code, capsys, monkeypatch): - results = iter(statuses) - monkeypatch.setattr(cf_diff, "run_case", lambda *args, **kwargs: (next(results), "detail")) - assert cf_diff.main(["--program", "3", "--seed", "1", "--wave", "both"]) == code - assert ("no program ran: every one was skipped" in capsys.readouterr().out) == (code == 2) - - -def test_generation_is_deterministic(): - assert cf_diff.program_for(5, 3, 32, 3) == cf_diff.program_for(5, 3, 32, 3) - assert cf_diff.program_for(5, 3, 32, 3) != cf_diff.program_for(5, 4, 32, 3) - - -def test_branch_offsets_land_on_their_labels(): - e = cf_diff.Emitter(32) - e.program([("if", FEW_LANES, True, [("probe", 3)]), ("sloop", 2, [("probe", 4)])]) - lines = e.assemble() - pcs, pc = [], 0 - for _, size in lines: - pcs.append(pc) - pc += size - for (text, size), at in zip(lines, pcs): - if text.startswith(("s_branch", "s_cbranch")): - target = at + 4 + 4 * int(text.split()[1]) - assert target in pcs, text - - -def test_reference_needs_encodings(): - with tempfile.TemporaryDirectory() as tmp: - p = os.path.join(tmp, "x.s") - with open(p, "w", encoding="utf-8") as f: - f.write("; x code 0x0..0x8\n\ts_branch 0\n\ts_endpgm\n") - with pytest.raises(cf_ref.ProgramError): - cf_ref.run(p) - - -def test_reference_wave32_saveexec_and_restore(): - body = [("if", FEW_LANES, True, [("op", "v_add_nc_u32 v9, 1, v9")])] - with tempfile.TemporaryDirectory() as tmp: - p = os.path.join(tmp, "x.s") - with open(p, "w", encoding="utf-8") as f: - f.write(cf_diff.listing_text(cf_diff.build(body, 32), "ps_x")) - r = cf_ref.run(p, wave=32) - assert sorted(r["exports"]) == list(range(32)) - assert [lane for lane in range(32) if r["exports"][lane][1] == 1] == [4, 20] - assert r["exec"] == 0xFFFFFFFF - - -@pytest.mark.parametrize("wave", (32, 64)) -@pytest.mark.parametrize("structured", (True, False), ids=("structured", "dispatch-loop")) -def test_small_fixed_seed_run_is_clean(wave, structured): - counts, failures = cf_diff.run_suite(6, seed=20261122, waves=(wave,), structured=structured) - assert counts["harness-error"] == 0, failures - assert counts["mismatch"] == 0, failures - assert counts["pass"] == 6, counts - - -@pytest.mark.parametrize("case", sorted(SCC_MASK_CASES)) -@pytest.mark.parametrize("structured", (True, False), ids=("structured", "dispatch-loop")) -def test_scc_of_wave32_mask_ops_is_wave_wide(case, structured): - status, detail = cf_diff.run_case("ps_scc_mask", SCC_MASK_CASES[case], 32, structured) - assert status == "match", detail - - -@pytest.mark.parametrize("case", sorted(SCC_MASK_CASES)) -def test_scc_mask_cases_catch_a_per_lane_scc(case, monkeypatch): - """The cases above are sensitive: with the old per-lane SCC they mismatch.""" - monkeypatch.setattr(rdna2spirv.Gen, "scc_logic", lambda self, a, r: self.scc_nonzero(r)) - status, _ = cf_diff.run_case("ps_scc_mask", SCC_MASK_CASES[case], 32) - assert status == "mismatch" - - -def test_minimize_keeps_the_mismatch(monkeypatch): - monkeypatch.setattr(rdna2spirv.Gen, "scc_logic", lambda self, a, r: self.scc_nonzero(r)) - body = [("probe", 1), ("op", "v_add_nc_u32 v8, 3, v8")] + SCC_MASK_CASES["s_and_b32 + s_cbranch_scc0"] - small = cf_diff.minimize(body, 32) - assert len(small) < len(body) - assert cf_diff.run_case("ps_scc_mask", small, 32)[0] == "mismatch" - - -def test_self_test_passes(): - assert cf_diff.self_test() is True - - -def test_no_arguments_prints_usage(): - proc = subprocess.run([sys.executable, "-I", TOOL], capture_output=True, text=True, timeout=5) - assert proc.returncode == 2 - assert "usage:" in proc.stderr - assert "Traceback" not in proc.stderr - - -def test_generator_covers_every_shape(): - kinds = set() - - def walk(nodes): - for n in nodes: - kinds.add(n[0]) - for x in n[1:]: - if isinstance(x, list): - walk(x) - for i in range(200): - walk(cf_diff.generate(random.Random(i), 32)) - assert {"if", "ifelse", "cmpx", "saveexec", "vccz", "sif", "sloop", "vloop", - "irr", "sccmask", "csel", "probe"} <= kinds - - -@pytest.mark.parametrize("op_name", ("andn2", "orn2", "xor", "nand", "nor", "xnor")) -@pytest.mark.parametrize("wave", (32, 64)) -def test_saveexec_variants_match(op_name, wave): - body = [("saveexec", FEW_LANES, op_name, "s_cbranch_scc0", [("probe", 13), ("op", "v_add_nc_u32 v9, 1, v9")])] - status, detail = cf_diff.run_case(f"ps_saveexec_{op_name}", body, wave, structured=True) - assert status == "match", detail diff --git a/tests/test_cf_ref.py b/tests/test_cf_ref.py deleted file mode 100644 index 0b747e16b..000000000 --- a/tests/test_cf_ref.py +++ /dev/null @@ -1,892 +0,0 @@ -"""Unit tests for tools/cf_ref.py (standard library only; no game data, GPU, or llvm-mc). - -Run from the repository root: - python -I tests/test_cf_ref.py -v -""" -import os -import sys -import tempfile -import unittest - -ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) -sys.path.insert(0, os.path.join(ROOT, "tools")) - -import cf_ref # noqa: E402 -import cpu_ref # noqa: E402 -from shader_ir import parse_file # noqa: E402 - -MASK32 = 0xFFFFFFFF -MASK64 = 0xFFFFFFFFFFFFFFFF -_VOP3_NO_E64 = {"v_mul_lo_u32", "v_mbcnt_lo_u32_b32", "v_mbcnt_hi_u32_b32"} - - -def _enc_bytes(size): - return "; encoding: [" + ",".join(["0x00"] * size) + "]" - - -def _guess_size(text): - op = text.split()[0] - if op == "exp" or op.endswith("_e64") or op in _VOP3_NO_E64: - return 8 - for tok in text.replace(",", " ").split()[1:]: - if tok.startswith("0x") or (tok.lstrip("-").isdigit() and not (-16 <= int(tok) <= 64)): - return 8 - return 4 - - -def assemble(items, name="test", code_start=0): - """Expand instructions, ('lbl', name) markers, and ('br', op, label) branches into a .s listing.""" - pc = code_start - labels = {} - sized = [] - for item in items: - if isinstance(item, tuple) and item[0] == "lbl": - labels[item[1]] = pc - continue - if isinstance(item, tuple) and item[0] == "br": - size = 4 - sized.append((item, pc, size)) - else: - text, size = item if isinstance(item, tuple) else (item, _guess_size(item)) - sized.append((text, pc, size)) - pc += size - - lines = [f"; {name} code 0x{code_start:x}..0x{pc:x}"] - for item, at, size in sized: - if isinstance(item, tuple) and item[0] == "br": - _, op, target = item - delta = labels[target] - (at + 4) - if delta % 4 != 0: - raise ValueError(f"branch target {target} is not 4-byte aligned") - text = f"{op} {delta // 4}" - else: - text = item - lines.append(f"\t{text} {_enc_bytes(size)}") - return "\n".join(lines) + "\n" - - -def lane_id_prologue(wave): - """Instructions that populate v0 with each lane's hardware ID (0..wave-1).""" - insns = ["v_mbcnt_lo_u32_b32 v0, -1, 0"] - if wave == 64: - insns.append("v_mbcnt_hi_u32_b32 v0, -1, v0") - return insns - - -def load_u64(lo_reg, hi_reg, value): - """Emit s_mov_b32 pairs to load a 64-bit constant into s[lo_reg:hi_reg].""" - return [ - f"s_mov_b32 s{lo_reg}, 0x{value & MASK32:08x}", - f"s_mov_b32 s{hi_reg}, 0x{(value >> 32) & MASK32:08x}", - ] - - -class CfRefTestCase(unittest.TestCase): - def setUp(self): - self.tmp = tempfile.TemporaryDirectory(prefix="cf-ref-") - self.addCleanup(self.tmp.cleanup) - self.n = 0 - - def write_text(self, text): - self.n += 1 - path = os.path.join(self.tmp.name, f"t{self.n}.s") - with open(path, "w", encoding="utf-8", newline="\n") as f: - f.write(text) - return path - - def run_items(self, items, wave=32, max_steps=200000, code_start=0): - path = self.write_text(assemble(items, name=f"t{self.n + 1}", code_start=code_start)) - return cf_ref.run(path, wave=wave, max_steps=max_steps) - - def run_raw(self, raw_lines, wave=32, max_steps=200000, header="; raw code 0x0..0x100"): - body = "\n".join(raw_lines) + "\n" - text = f"{header}\n{body}" if header is not None else body - return cf_ref.run(self.write_text(text), wave=wave, max_steps=max_steps) - - -class WaveModeAndMaskWidthTests(CfRefTestCase): - def test_wave32_exec_upper_half_is_zero_and_only_low_32_lanes_run(self): - items = lane_id_prologue(32) + [ - "v_mov_b32 v1, 0x1234", - "v_mov_b32 v2, 0", - "v_mov_b32 v3, 0", - "exp mrt0 v0, v1, v2, v3 done vm", - "s_endpgm", - ] - path = self.write_text(assemble(items)) - machine = cf_ref.WaveMachine(parse_file(path), wave=32) - self.assertEqual(machine.exec, MASK32) - self.assertEqual(machine.exec >> 32, 0) - res = machine.run() - self.assertEqual(res["wave"], 32) - self.assertEqual(res["exec"], MASK32) - self.assertEqual(res["vcc"], 0) - self.assertEqual(sorted(res["exports"]), list(range(32))) - for lane in range(32): - self.assertEqual(res["exports"][lane], (lane, 0x1234, 0, 0)) - - def test_wave64_all_lanes_active_and_64bit_masks(self): - items = lane_id_prologue(64) + [ - "v_cmp_le_u32_e32 vcc, 40, v0", - "v_mov_b32 v1, 1", - "v_mov_b32 v2, 2", - "v_mov_b32 v3, 3", - "exp mrt0 v0, v1, v2, v3 done vm", - "s_endpgm", - ] - path = self.write_text(assemble(items)) - machine = cf_ref.WaveMachine(parse_file(path), wave=64) - self.assertEqual(machine.exec, MASK64) - res = machine.run() - self.assertEqual(res["wave"], 64) - self.assertEqual(res["exec"], MASK64) - self.assertEqual(res["vcc"], sum(1 << lane for lane in range(40, 64))) - self.assertEqual(sorted(res["exports"]), list(range(64))) - for lane in range(64): - self.assertEqual(res["exports"][lane], (lane, 1, 2, 3)) - - def test_mbcnt_lo_and_hi_partial_mask_and_accumulator(self): - # Mask 0x55555555 has bits set at even positions 0, 2, 4, ... - items = [ - "v_mbcnt_lo_u32_b32 v0, 0x55555555, 10", - "v_mbcnt_hi_u32_b32 v1, 0x55555555, v0", - "v_mov_b32 v2, 0", - "v_mov_b32 v3, 0", - "exp mrt0 v0, v1, v2, v3 done vm", - "s_endpgm", - ] - res = self.run_items(items, wave=64) - for lane in range(64): - lo_expected = 10 + ((min(lane, 32) + 1) // 2) - hi_delta = (max(lane - 32, 0) + 1) // 2 - self.assertEqual(res["exports"][lane][:2], (lo_expected, lo_expected + hi_delta)) - - def test_s_mov_mask_operations_and_scc_preservation(self): - # Wave32: moving between vcc_lo/vcc, exec_lo/exec, SGPR, inline imm, and null must leave SCC alone. - res32 = self.run_items([ - "s_cmp_eq_u32 1, 1", # SCC = 1 - "s_mov_b32 vcc_lo, 0x0f0f0f0f", - "s_mov_b32 s0, vcc", - "s_mov_b32 s1, exec_lo", - "s_mov_b32 null, vcc_lo", - "s_mov_b32 s2, scc", - "s_cmp_eq_u32 1, 2", # SCC = 0 - "s_mov_b32 vcc, -1", - "s_mov_b32 exec_lo, 0x00ff00ff", - "s_mov_b32 s3, scc", - "s_endpgm", - ], wave=32) - self.assertEqual(res32["sgpr"][0], 0x0F0F0F0F) - self.assertEqual(res32["sgpr"][1], MASK32) - self.assertEqual(res32["sgpr"][2], 1) - self.assertEqual(res32["sgpr"][3], 0) - self.assertEqual(res32["vcc"], MASK32) - self.assertEqual(res32["exec"], 0x00FF00FF) - self.assertEqual(res32["scc"], 0) - - # Wave64: s_mov_b64 handles 64-bit masks without altering SCC, and *_lo writes preserve upper 32 bits. - res64 = self.run_items( - load_u64(0, 1, 0x123456789ABCDEF0) + [ - "s_cmp_eq_u32 5, 5", # SCC = 1 - "s_mov_b64 vcc, s[0:1]", - "s_mov_b64 s[2:3], vcc", - "s_mov_b64 null, exec", - "s_mov_b32 vcc_lo, 0x11223344", - "s_mov_b32 s4, scc", - "s_mov_b64 s[6:7], -1", - "s_mov_b64 exec, 0", - "s_endpgm", - ], - wave=64, - ) - self.assertEqual(res64["sgpr"][2], 0x9ABCDEF0) - self.assertEqual(res64["sgpr"][3], 0x12345678) - self.assertEqual(res64["sgpr"][4], 1) - self.assertEqual(res64["sgpr"][6], MASK32) - self.assertEqual(res64["sgpr"][7], MASK32) - self.assertEqual(res64["vcc"], 0x1234567811223344) - self.assertEqual(res64["exec"], 0) - - res64_exec_lo = self.run_items([ - "s_mov_b32 exec_lo, 0x5", - "s_endpgm", - ], wave=64) - self.assertEqual(res64_exec_lo["exec"], 0xFFFFFFFF00000005) - - def test_v_cndmask_b32_implicit_and_explicit_conditions(self): - # Wave32: VOP2 3-arg and 4-arg forms use low 32 bits of VCC; _e64 uses SGPR. - res32 = self.run_items(lane_id_prologue(32) + [ - "s_mov_b32 vcc_lo, 0x0000000a", - "s_mov_b32 s0, 0x00000005", - "v_mov_b32 v1, 100", - "v_mov_b32 v2, 200", - "v_cndmask_b32 v3, v1, v2", - "v_cndmask_b32 v4, v1, v2, vcc_lo", - "v_cndmask_b32_e64 v5, v1, v2, s0", - "v_mov_b32 v6, 0", - "exp mrt0 v3, v4, v5, v6 done vm", - "s_endpgm", - ], wave=32) - for lane in range(32): - vcc_sel = 200 if lane in (1, 3) else 100 - sgpr_sel = 200 if lane in (0, 2) else 100 - self.assertEqual(res32["exports"][lane][:3], (vcc_sel, vcc_sel, sgpr_sel)) - - # Wave64: VOP2 implicit VCC reads full 64-bit VCC including lanes >= 32. - res64 = self.run_items( - lane_id_prologue(64) + load_u64(0, 1, (1 << 2) | (1 << 45)) + [ - "s_mov_b64 vcc, s[0:1]", - "v_mov_b32 v1, 10", - "v_mov_b32 v2, 20", - "v_cndmask_b32 v3, v1, v2", - "v_cndmask_b32_e64 v4, v1, v2, s[0:1]", - "v_mov_b32 v5, 0", - "v_mov_b32 v6, 0", - "exp mrt0 v3, v4, v5, v6 done vm", - "s_endpgm", - ], - wave=64, - ) - for lane in range(64): - want = 20 if lane in (2, 45) else 10 - self.assertEqual(res64["exports"][lane][:2], (want, want)) - - def test_mask_width_mismatches_and_invalid_wave_raise(self): - cases = [ - (32, ["s_and_b64 vcc, vcc, exec", "s_endpgm"]), - (32, ["s_and_saveexec_b64 s[0:1], vcc", "s_endpgm"]), - (32, ["s_mov_b64 exec, -1", "s_endpgm"]), - (64, ["s_and_b32 vcc, vcc, exec", "s_endpgm"]), - (64, ["s_and_saveexec_b32 s0, vcc_lo", "s_endpgm"]), - (64, ["v_cmp_eq_u32_e64 s0, v0, 0", "s_endpgm"]), - ] - for wave, insns in cases: - with self.subTest(wave=wave, insn=insns[0]): - with self.assertRaises(cpu_ref.Unsupported): - self.run_items(insns, wave=wave) - - path = self.write_text(assemble(["s_endpgm"])) - with self.assertRaises(ValueError): - cf_ref.run(path, wave=16) - - -class BranchTests(CfRefTestCase): - def test_pc_relative_forward_zero_and_mixed_instruction_sizes(self): - # code_start=0x100 exercises non-zero base PCs; mix 4-byte and 8-byte encodings. - res = self.run_raw([ - f"\ts_mov_b32 s0, 1 {_enc_bytes(4)}", # 0x100..0x104 - f"\ts_branch 0 {_enc_bytes(4)}", # 0x104..0x108 -> next_pc 0x108 - f"\ts_mov_b32 s1, 2 {_enc_bytes(4)}", # 0x108..0x10c (executed) - f"\ts_branch 2 {_enc_bytes(4)}", # 0x10c..0x110 -> 0x110 + 8 = 0x118 - f"\ts_mov_b32 s2, 99 {_enc_bytes(4)}", # 0x110..0x114 (skipped) - f"\ts_mov_b32 s3, 99 {_enc_bytes(4)}", # 0x114..0x118 (skipped) - f"\ts_branch 2 {_enc_bytes(4)}", # 0x118..0x11c -> 0x11c + 8 = 0x124 - f"\tv_mul_lo_u32 v0, v1, 3 {_enc_bytes(8)}", # 0x11c..0x124 (one 8-byte insn skipped) - f"\ts_mov_b32 s4, 7 {_enc_bytes(4)}", # 0x124..0x128 - f"\ts_endpgm {_enc_bytes(4)}", # 0x128..0x12c - ], header="; forward code 0x100..0x12c") - self.assertEqual(res["sgpr"], {0: 1, 1: 2, 4: 7}) - self.assertEqual(res["steps"], 7) - - def test_backward_branch_negative_simm16_representations(self): - # All three encodings of -3 (decimal -3, hex 0xfffd, unsigned 65533) must sign-extend identically. - for off_text in ("-3", "0xfffd", "65533"): - with self.subTest(off=off_text): - res = self.run_raw([ - f"\ts_mov_b32 s0, 0 {_enc_bytes(4)}", # 0x00 - f"\ts_add_u32 s0, s0, 1 {_enc_bytes(4)}", # 0x04 (loop head) - f"\ts_cmp_lt_u32 s0, 3 {_enc_bytes(4)}", # 0x08 - f"\ts_cbranch_scc1 {off_text} {_enc_bytes(4)}", # 0x0c -> 0x10 + 4*(-3) = 0x04 - f"\ts_endpgm {_enc_bytes(4)}", # 0x10 - ]) - self.assertEqual(res["sgpr"], {0: 3}) - self.assertEqual(res["steps"], 1 + 3 * 3 + 1) - - # 0xffff (-1) jumps to the branch instruction itself (next_pc - 4 == pc). - with self.assertRaises(cf_ref.ProgramError) as cm: - self.run_raw([ - f"\ts_cmp_eq_u32 1, 1 {_enc_bytes(4)}", # 0x00 - f"\ts_cbranch_scc1 0xffff {_enc_bytes(4)}", # 0x04 -> 0x08 - 4 = 0x04 - f"\ts_endpgm {_enc_bytes(4)}", - ], max_steps=3) - self.assertIn("at pc 0x4", str(cm.exception)) - - def test_backward_branch_with_8byte_body_instruction(self): - # 8-byte v_mul_lo_u32 + two 4-byte scalar insns + 4-byte branch = 20 bytes -> simm16 = -5. - res = self.run_items([ - "s_mov_b32 s0, 0", - "v_mov_b32 v0, 1", - ("lbl", "loop"), - "v_mul_lo_u32 v0, v0, 3", - "s_add_u32 s0, s0, 1", - "s_cmp_lt_u32 s0, 4", - ("br", "s_cbranch_scc1", "loop"), - "v_mov_b32 v1, 0", - "v_mov_b32 v2, 0", - "v_mov_b32 v3, 0", - "exp mrt0 v0, v1, v2, v3 done vm", - "s_endpgm", - ], wave=32) - self.assertEqual(res["sgpr"][0], 4) - self.assertEqual(res["exports"][0][0], 81) - - def test_conditional_branches_taken_and_fallthrough(self): - # Exercise every conditional branch opcode in both taken and fallthrough states. - res = self.run_items([ - "s_mov_b32 s0, 0", - "s_cmp_eq_u32 1, 1", # SCC = 1 - ("br", "s_cbranch_scc0", "bad"), # not taken - ("br", "s_cbranch_scc1", "k1"), # taken - ("lbl", "k1"), - "s_add_u32 s0, s0, 1", - "s_cmp_eq_u32 1, 2", # SCC = 0 - ("br", "s_cbranch_scc1", "bad"), # not taken - ("br", "s_cbranch_scc0", "k2"), # taken - ("lbl", "k2"), - "s_add_u32 s0, s0, 2", - "s_mov_b32 vcc_lo, 0", # VCCZ = 1 - ("br", "s_cbranch_vccnz", "bad"), # not taken - ("br", "s_cbranch_vccz", "k3"), # taken - ("lbl", "k3"), - "s_add_u32 s0, s0, 4", - "s_mov_b32 vcc_lo, 8", # VCCZ = 0 - ("br", "s_cbranch_vccz", "bad"), # not taken - ("br", "s_cbranch_vccnz", "k4"), # taken - ("lbl", "k4"), - "s_add_u32 s0, s0, 8", - ("br", "s_cbranch_execz", "bad"), # EXEC != 0 -> not taken - ("br", "s_cbranch_execnz", "k5"), # taken - ("lbl", "k5"), - "s_add_u32 s0, s0, 16", - "s_mov_b32 exec_lo, 0", # EXECZ = 1 - ("br", "s_cbranch_execnz", "bad"), # not taken - ("br", "s_cbranch_execz", "done"), # taken - ("lbl", "bad"), - "s_mov_b32 s0, 999", - ("lbl", "done"), - "s_add_u32 s0, s0, 32", - "s_endpgm", - ], wave=32) - self.assertEqual(res["sgpr"][0], 1 + 2 + 4 + 8 + 16 + 32) - - def test_vccz_and_execz_check_only_low_32_bits_in_wave32_and_all_64_in_wave64(self): - # Wave64: bit 40 set in VCC or EXEC must make *z false and *nz true. - res64 = self.run_items(load_u64(0, 1, 1 << 40) + [ - "s_mov_b32 s2, 0", - "s_mov_b64 vcc, s[0:1]", - ("br", "s_cbranch_vccz", "skip1"), - "s_add_u32 s2, s2, 1", - ("lbl", "skip1"), - ("br", "s_cbranch_vccnz", "skip2"), - "s_add_u32 s2, s2, 100", - ("lbl", "skip2"), - "s_mov_b64 exec, s[0:1]", - ("br", "s_cbranch_execz", "skip3"), - "s_add_u32 s2, s2, 2", - ("lbl", "skip3"), - ("br", "s_cbranch_execnz", "done"), - "s_add_u32 s2, s2, 100", - ("lbl", "done"), - "s_endpgm", - ], wave=64) - self.assertEqual(res64["sgpr"][2], 3) - - # Wave32: even if upper 32 bits of machine.vcc/exec are non-zero, *z/*nz inspect only bits [31:0]. - vcc_path = self.write_text(assemble([ - "s_mov_b32 s0, 0", - ("br", "s_cbranch_vccnz", "fail"), - "s_add_u32 s0, s0, 1", - ("br", "s_cbranch_vccz", "ok"), - ("lbl", "fail"), - "s_mov_b32 s0, 999", - ("lbl", "ok"), - "s_endpgm", - ])) - m_vcc = cf_ref.WaveMachine(parse_file(vcc_path), wave=32) - m_vcc.vcc = 1 << 40 - r_vcc = m_vcc.run() - self.assertEqual(r_vcc["sgpr"][0], 1) - self.assertEqual(r_vcc["vcc"], 0) - - exec_path = self.write_text(assemble([ - "s_mov_b32 s0, 0", - ("br", "s_cbranch_execnz", "fail"), - "s_add_u32 s0, s0, 2", - ("br", "s_cbranch_execz", "ok"), - ("lbl", "fail"), - "s_mov_b32 s0, 999", - ("lbl", "ok"), - "s_endpgm", - ])) - m_exec = cf_ref.WaveMachine(parse_file(exec_path), wave=32) - m_exec.exec = 1 << 40 - r_exec = m_exec.run() - self.assertEqual(r_exec["sgpr"][0], 2) - self.assertEqual(r_exec["exec"], 0) - - def test_wave32_vcc_mask_writes_preserve_vcc_hi_and_scalar_ops_ignore_exec_hi(self): - res_vcc = self.run_items([ - "s_mov_b32 vcc_hi, 0xdeadbeef", - "s_mov_b32 vcc, 5", - "s_mov_b32 s0, vcc_hi", - "s_and_b32 vcc, vcc, 1", - "s_mov_b32 s1, vcc_hi", - "s_and_saveexec_b32 vcc, 3", - "s_mov_b32 s2, vcc_hi", - "s_mov_b32 s3, vcc_lo", - "s_endpgm", - ], wave=32) - self.assertEqual(res_vcc["sgpr"][0], 0xDEADBEEF) - self.assertEqual(res_vcc["sgpr"][1], 0xDEADBEEF) - self.assertEqual(res_vcc["sgpr"][2], 0xDEADBEEF) - self.assertEqual(res_vcc["sgpr"][3], 0xFFFFFFFF) - - res_exec = self.run_items([ - "s_add_u32 exec_hi, 1, 0", - "s_lshl_b32 exec_hi, 1, 2", - "s_cselect_b32 exec_hi, 7, 9", - "s_mov_b32 s0, exec_hi", - "s_add_u32 s1, exec_hi, 5", - "v_mov_b32 v0, 1", - "exp mrt0 v0, v0, v0, v0 done vm", - "s_endpgm", - ], wave=32) - self.assertEqual(res_exec["sgpr"][0], 0) - self.assertEqual(res_exec["sgpr"][1], 5) - self.assertEqual(sorted(res_exec["exports"]), list(range(32))) - - -class CompareAndFlagTests(CfRefTestCase): - def test_v_cmp_predicates_u32_and_i32_and_inactive_lanes_write_zero(self): - # Pre-seed VCC with all 1s and restrict EXEC to lanes 0..3 so inactive lanes 4..31 must clear to 0. - # Lanes 0..3 get [0, 1, 0xffffffff, 0x80000000] compared against 0/1/-1 to test u32 vs i32. - items = lane_id_prologue(32) + [ - "s_mov_b32 vcc_lo, -1", - "v_mov_b32 v1, 0", - "v_cmp_eq_u32_e32 vcc_lo, 1, v0", - "v_cndmask_b32 v1, v1, 1, vcc_lo", - "v_cmp_eq_u32_e32 vcc_lo, 2, v0", - "v_cndmask_b32 v1, v1, -1, vcc_lo", - "v_cmp_eq_u32_e32 vcc_lo, 3, v0", - "v_cndmask_b32 v1, v1, 0x80000000, vcc_lo", - "s_mov_b32 exec_lo, 0x0f", - "s_mov_b32 vcc_lo, -1", - "v_cmp_eq_u32_e32 vcc, v1, 0", # lane 0 only (wave32 maps vcc -> vcc_lo) - "v_cmp_ne_u32_e64 s0, v1, 0", # lanes 1, 2, 3 - "v_cmp_lg_u32_e64 s1, v1, 0", # lanes 1, 2, 3 - "v_cmp_lt_u32_e64 s2, v1, 1", # lane 0 - "v_cmp_le_u32_e64 s3, v1, 1", # lanes 0, 1 - "v_cmp_gt_u32_e64 s4, v1, 1", # lanes 2, 3 - "v_cmp_ge_u32_e64 s5, v1, 1", # lanes 1, 2, 3 - "v_cmp_lt_i32_e64 s6, v1, 0", # lanes 2, 3 (-1 and INT_MIN) - "v_cmp_le_i32_e64 s7, v1, 0", # lanes 0, 2, 3 - "v_cmp_gt_i32_e64 s8, v1, -1", # lanes 0, 1 - "v_cmp_ge_i32_e64 s9, v1, -1", # lanes 0, 1, 2 - "v_cmp_eq_i32_e64 null, v1, 0", # discarded cleanly - "s_endpgm", - ] - res = self.run_items(items, wave=32) - self.assertEqual(res["vcc"], 0b0001) - self.assertEqual(res["sgpr"], { - 0: 0b1110, - 1: 0b1110, - 2: 0b0001, - 3: 0b0011, - 4: 0b1100, - 5: 0b1110, - 6: 0b1100, - 7: 0b1101, - 8: 0b0011, - 9: 0b0111, - }) - - def test_v_cmp_wave64_sgpr_pair_and_inactive_lanes(self): - items = lane_id_prologue(64) + load_u64(0, 1, (1 << 5) | (1 << 40)) + [ - "s_mov_b64 exec, s[0:1]", - "v_cmp_ge_u32_e64 s[2:3], v0, 0", # true for every lane, but only lanes 5 and 40 are active - "s_endpgm", - ] - res = self.run_items(items, wave=64) - self.assertEqual(res["sgpr"][2], 1 << 5) - self.assertEqual(res["sgpr"][3], 1 << (40 - 32)) - - def test_v_cmpx_updates_exec_without_touching_vcc(self): - # Wave32: pre-active mask 0x0f0f, v_cmpx keeps lanes where 10 > v0 -> lanes 0..3 and 8..9. - res32 = self.run_items(lane_id_prologue(32) + [ - "s_mov_b32 vcc_lo, 0xdeadbeef", - "s_mov_b32 exec_lo, 0x0f0f", - "v_cmpx_gt_u32_e32 10, v0", - "v_mov_b32 v1, 0", - "v_mov_b32 v2, 0", - "v_mov_b32 v3, 0", - "exp mrt0 v0, v1, v2, v3 done vm", - "s_endpgm", - ], wave=32) - self.assertEqual(res32["vcc"], 0xDEADBEEF) - self.assertEqual(res32["exec"], 0x030F) - self.assertEqual(sorted(res32["exports"]), [0, 1, 2, 3, 8, 9]) - - # Wave64: signed compare with negative values; VCC remains untouched. - res64 = self.run_items( - lane_id_prologue(64) + load_u64(0, 1, 0x123456789ABCDEF0) + load_u64(2, 3, (1 << 1) | (1 << 40) | (1 << 41)) + [ - "s_mov_b64 vcc, s[0:1]", - "s_mov_b64 exec, s[2:3]", - "v_sub_nc_u32 v0, v0, 41", # lane 1 -> -40, lane 40 -> -1, lane 41 -> 0 - "v_cmpx_ge_i32_e32 -1, v0", # -1 >= signed(v0) -> lanes 1 and 40 survive, lane 41 drops - "v_mov_b32 v1, 0", - "v_mov_b32 v2, 0", - "v_mov_b32 v3, 0", - "exp mrt0 v0, v1, v2, v3 done vm", - "s_endpgm", - ], - wave=64, - ) - self.assertEqual(res64["vcc"], 0x123456789ABCDEF0) - self.assertEqual(res64["exec"], (1 << 1) | (1 << 40)) - self.assertEqual(sorted(res64["exports"]), [1, 40]) - - def test_s_cmp_predicates_u32_and_i32(self): - cases = [ - ("s_cmp_eq_u32", "5", "5", 1), - ("s_cmp_eq_u32", "5", "6", 0), - ("s_cmp_ne_u32", "5", "6", 1), - ("s_cmp_lg_u32", "5", "5", 0), - ("s_cmp_lt_u32", "1", "0xffffffff", 1), - ("s_cmp_lt_i32", "1", "0xffffffff", 0), - ("s_cmp_le_u32", "0x80000000", "0x7fffffff", 0), - ("s_cmp_le_i32", "0x80000000", "0x7fffffff", 1), - ("s_cmp_gt_u32", "0xffffffff", "0", 1), - ("s_cmp_gt_i32", "0xffffffff", "0", 0), - ("s_cmp_ge_i32", "-5", "-5", 1), - ("s_cmp_ge_i32", "-6", "-5", 0), - ] - insns = [] - for idx, (op, a, b, _) in enumerate(cases): - insns.append(f"{op} {a}, {b}") - insns.append(f"s_mov_b32 s{idx + 1}, scc") - insns.append("s_endpgm") - res = self.run_items(insns, wave=32) - for idx, (_, _, _, want) in enumerate(cases): - self.assertEqual(res["sgpr"][idx + 1], want, cases[idx]) - - def test_scalar_bitwise_ops_and_scc_wave32_and_wave64(self): - # All 8 SOP2 bitwise ops on SGPRs and masks in wave32. - a32, b32 = 0xF0F00F0F, 0xFF00FF00 - ops32 = [ - ("and", a32 & b32), - ("or", a32 | b32), - ("xor", a32 ^ b32), - ("andn2", a32 & ~b32 & MASK32), - ("orn2", (a32 | ~b32) & MASK32), - ("nand", ~(a32 & b32) & MASK32), - ("nor", ~(a32 | b32) & MASK32), - ("xnor", ~(a32 ^ b32) & MASK32), - ] - insns32 = [f"s_mov_b32 s0, 0x{a32:08x}", f"s_mov_b32 s1, 0x{b32:08x}"] - for idx, (name, _) in enumerate(ops32): - dst = 10 + idx * 2 - insns32.append(f"s_{name}_b32 s{dst}, s0, s1") - insns32.append(f"s_mov_b32 s{dst + 1}, scc") - insns32 += [ - "s_nand_b32 s2, -1, -1", # result 0 -> SCC transitions 1 -> 0 - "s_mov_b32 s3, scc", - "s_mov_b32 vcc_lo, 0x00ff00ff", - "s_and_b32 null, vcc_lo, exec_lo", # mask-touching op -> SCC = 1 - "s_mov_b32 s4, scc", - "s_and_b32 vcc, 0, exec_lo", # zero mask -> VCC = 0, SCC = 0 - "s_mov_b32 s5, scc", - "s_endpgm", - ] - res32 = self.run_items(insns32, wave=32) - for idx, (name, want) in enumerate(ops32): - dst = 10 + idx * 2 - self.assertEqual(res32["sgpr"][dst], want, name) - self.assertEqual(res32["sgpr"][dst + 1], 1 if want else 0, name) - self.assertEqual(res32["sgpr"][2], 0) - self.assertEqual(res32["sgpr"][3], 0) - self.assertEqual(res32["sgpr"][4], 1) - self.assertEqual(res32["sgpr"][5], 0) - self.assertEqual(res32["vcc"], 0) - - # Wave64: all 8 _b64 mask ops + _b32 SGPR-only logic + high-half-only non-zero SCC check. - a64, b64 = 0x0000000100000000, 0x0000000300000000 - ops64 = [ - ("and", a64 & b64), - ("or", a64 | b64), - ("xor", a64 ^ b64), - ("andn2", a64 & ~b64 & MASK64), - ("orn2", (a64 | ~b64) & MASK64), - ("nand", ~(a64 & b64) & MASK64), - ("nor", ~(a64 | b64) & MASK64), - ("xnor", ~(a64 ^ b64) & MASK64), - ] - insns64 = load_u64(0, 1, a64) + load_u64(2, 3, b64) + [ - "s_and_b32 s4, 0xf0, 0x33", - "s_mov_b32 s5, scc", - ] - for idx, (name, _) in enumerate(ops64): - pair_lo = 10 + idx * 2 - scc_reg = 30 + idx - insns64.append(f"s_{name}_b64 s[{pair_lo}:{pair_lo + 1}], s[0:1], s[2:3]") - insns64.append(f"s_mov_b32 s{scc_reg}, scc") - insns64 += ["s_xor_b64 vcc, s[0:1], s[0:1]", "s_endpgm"] - res64 = self.run_items(insns64, wave=64) - self.assertEqual(res64["sgpr"][4], 0x30) - self.assertEqual(res64["sgpr"][5], 1) - for idx, (name, want) in enumerate(ops64): - pair_lo = 10 + idx * 2 - got = (res64["sgpr"][pair_lo + 1] << 32) | res64["sgpr"][pair_lo] - self.assertEqual(got, want, name) - self.assertEqual(res64["sgpr"][30 + idx], 1 if want else 0, name) - self.assertEqual(res64["vcc"], 0) - self.assertEqual(res64["scc"], 0) - - def test_saveexec_all_variants_wave32_and_wave64(self): - # All 10 saveexec variants in wave32 and wave64, checking saved old EXEC, new EXEC, and SCC. - s0_32, e0_32 = 0x0F0F0F0F, 0x00FF00FF - s0_64, e0_64 = 0x123456789ABCDEF0, 0x00FF00FF0F0F0F0F - variants = { - "and": lambda s, e, m: s & e, - "or": lambda s, e, m: s | e, - "xor": lambda s, e, m: s ^ e, - "andn2": lambda s, e, m: s & ~e & m, - "orn2": lambda s, e, m: (s | ~e) & m, - "nand": lambda s, e, m: ~(s & e) & m, - "nor": lambda s, e, m: ~(s | e) & m, - "xnor": lambda s, e, m: ~(s ^ e) & m, - "andn1": lambda s, e, m: ~s & e & m, - "orn1": lambda s, e, m: (~s | e) & m, - } - for name, fn in variants.items(): - with self.subTest(wave=32, variant=name): - res = self.run_items([ - f"s_mov_b32 exec_lo, 0x{e0_32:08x}", - f"s_mov_b32 s0, 0x{s0_32:08x}", - f"s_{name}_saveexec_b32 s0, s0", # alias dst and src: must read old s0 and save old EXEC - "s_endpgm", - ], wave=32) - want = fn(s0_32, e0_32, MASK32) & MASK32 - self.assertEqual(res["sgpr"][0], e0_32) - self.assertEqual(res["exec"], want) - self.assertEqual(res["scc"], 1 if want else 0) - - with self.subTest(wave=64, variant=name): - res = self.run_items( - load_u64(0, 1, e0_64) + load_u64(2, 3, s0_64) + [ - "s_mov_b64 exec, s[0:1]", - f"s_{name}_saveexec_b64 s[4:5], s[2:3]", - "s_endpgm", - ], - wave=64, - ) - want = fn(s0_64, e0_64, MASK64) & MASK64 - self.assertEqual((res["sgpr"][5] << 32) | res["sgpr"][4], e0_64) - self.assertEqual(res["exec"], want) - self.assertEqual(res["scc"], 1 if want else 0) - - # Explicitly verify SCC transitions to 0 when new EXEC becomes 0 (while old EXEC was non-zero). - res_zero = self.run_items([ - "s_cmp_eq_u32 1, 1", - "s_mov_b32 exec_lo, 0x0f0f", - "s_and_saveexec_b32 s0, 0x00f0", - "s_endpgm", - ], wave=32) - self.assertEqual(res_zero["sgpr"][0], 0x0F0F) - self.assertEqual(res_zero["exec"], 0) - self.assertEqual(res_zero["scc"], 0) - - def test_scalar_add_sub_u32_and_i32_scc_carry_borrow_overflow(self): - cases = [ - ("s_add_u32", "0xffffffff", "1", 0, 1), - ("s_add_u32", "0x7fffffff", "1", 0x80000000, 0), - ("s_sub_u32", "0", "1", 0xFFFFFFFF, 1), - ("s_sub_u32", "1", "2", 0xFFFFFFFF, 1), - ("s_sub_u32", "2", "2", 0, 0), - ("s_sub_u32", "5", "2", 3, 0), - ("s_add_i32", "0x7fffffff", "1", 0x80000000, 1), # +max + +1 -> signed overflow - ("s_add_i32", "0x80000000", "-1", 0x7FFFFFFF, 1), # -min + -1 -> signed overflow - ("s_add_i32", "-1", "1", 0, 0), # opposite signs -> no signed overflow - ("s_add_i32", "-2", "-3", 0xFFFFFFFB, 0), # negative without overflow - ("s_sub_i32", "0x80000000", "1", 0x7FFFFFFF, 1), # INT_MIN - 1 -> signed overflow - ("s_sub_i32", "0x7fffffff", "-1", 0x80000000, 1), # INT_MAX - (-1) -> signed overflow - ("s_sub_i32", "0", "1", 0xFFFFFFFF, 0), # same sign -> no signed overflow - ("s_sub_i32", "-1", "-2", 1, 0), # same sign -> no signed overflow - ] - for op, a, b, want_val, want_scc in cases: - with self.subTest(op=op, a=a, b=b): - res = self.run_items([ - f"s_mov_b32 s0, {a}", - f"s_mov_b32 s1, {b}", - f"{op} s2, s0, s1", - "s_endpgm", - ], wave=32) - self.assertEqual(res["sgpr"][2], want_val) - self.assertEqual(res["scc"], want_scc) - - def test_s_cselect_b32_selects_and_preserves_scc(self): - res = self.run_items([ - "s_cmp_eq_u32 3, 3", # SCC = 1 - "s_cselect_b32 s0, 11, 22", # picks 11, SCC stays 1 - "s_cselect_b32 s1, 33, 44", # still sees SCC = 1 -> picks 33 - "s_mov_b32 s2, scc", - "s_cmp_eq_u32 3, 4", # SCC = 0 - "s_cselect_b32 s3, 11, 22", # picks 22, SCC stays 0 - "s_cselect_b32 s4, 33, 44", # still sees SCC = 0 -> picks 44 - "s_mov_b32 s5, scc", - "s_endpgm", - ], wave=32) - self.assertEqual(res["sgpr"], {0: 11, 1: 33, 2: 1, 3: 22, 4: 44, 5: 0}) - self.assertEqual(res["scc"], 0) - - def test_vector_alu_and_cpu_ref_fallback_respect_exec(self): - # Active only on lane 1 (mask 0x2); lane 0 must retain its pre-mask sentinel values. - res = self.run_items([ - "v_mov_b32 v0, 10", - "v_mov_b32 v1, 3", - "v_mov_b32 v2, 77", - "v_mov_b32 v3, 77", - "v_mov_b32 v4, 77", - "v_mov_b32 v5, 77", - "s_mov_b32 exec_lo, 0x2", - "v_add_nc_u32 v2, v0, v1", - "v_sub_nc_u32 v3, v0, v1", - "v_subrev_nc_u32 v4, v0, v1", - "v_mul_lo_u32 v5, v0, v1", - "v_xor_b32 v2, 1, v2", # falls through to cpu_ref.Machine.step - "s_mov_b32 exec_lo, 0x3", - "exp mrt0 v2, v3, v4, v5 done vm", - "s_endpgm", - ], wave=32) - self.assertEqual(res["exports"][0], (77, 77, 77, 77)) - self.assertEqual(res["exports"][1], (12, 7, 0xFFFFFFF9, 30)) - - -class ExportHaltStepAndErrorTests(CfRefTestCase): - def test_exp_records_only_active_lanes_across_divergent_exports(self): - # Lanes 0..7 take the then-branch and export (lane, 100, 0, 0); lanes 8..15 take else and export (lane, 200, 0, 0); - # lanes 16..31 stay inactive during both exports and must not appear in res["exports"]. - res = self.run_items(lane_id_prologue(32) + [ - "s_mov_b32 exec_lo, 0x0000ffff", - "v_cmp_lt_u32_e32 vcc_lo, v0, 8", - "s_and_saveexec_b32 s0, vcc_lo", - "v_mov_b32 v1, 100", - "v_mov_b32 v2, 0", - "v_mov_b32 v3, 0", - "exp mrt0 v0, v1, v2, v3 done vm", - "s_xor_b32 exec_lo, exec_lo, s0", - "v_mov_b32 v1, 200", - "exp mrt0 v0, v1, v2, v3 done vm", - "s_or_b32 exec_lo, exec_lo, s0", - "s_endpgm", - ], wave=32) - self.assertEqual(sorted(res["exports"]), list(range(16))) - for lane in range(8): - self.assertEqual(res["exports"][lane], (lane, 100, 0, 0)) - for lane in range(8, 16): - self.assertEqual(res["exports"][lane], (lane, 200, 0, 0)) - - # Exporting with EXEC == 0 records nothing. - res_empty = self.run_items([ - "s_mov_b32 exec_lo, 0", - "exp mrt0 v0, v1, v2, v3 done vm", - "s_endpgm", - ], wave=32) - self.assertEqual(res_empty["exports"], {}) - - def test_s_endpgm_halts_before_trailing_instructions(self): - res = self.run_items([ - "s_mov_b32 s0, 42", - "s_endpgm", - "s_mov_b32 s0, 99", - "v_pk_fma_f16 v0, v1, v2, v3", - "exp mrt0 v0, v1, v2, v3 done vm", - ], wave=32) - self.assertEqual(res["sgpr"], {0: 42}) - self.assertEqual(res["exports"], {}) - self.assertEqual(res["steps"], 2) - - def test_max_steps_boundary_and_exceeded(self): - # Exactly 5 dynamic instructions: s_mov, s_add, s_cmp, s_cbranch (not taken), s_endpgm. - items = [ - "s_mov_b32 s0, 0", - ("lbl", "loop"), - "s_add_u32 s0, s0, 1", - "s_cmp_lt_u32 s0, 1", - ("br", "s_cbranch_scc1", "loop"), - "s_endpgm", - ] - ok = self.run_items(items, max_steps=5) - self.assertEqual(ok["steps"], 5) - self.assertEqual(ok["sgpr"], {0: 1}) - - with self.assertRaises(cf_ref.ProgramError) as cm: - self.run_items(items, max_steps=4) - self.assertIn("step limit 4", str(cm.exception)) - - # Tight infinite loop also stops cleanly with ProgramError at max_steps. - with self.assertRaises(cf_ref.ProgramError): - self.run_raw([f"\ts_branch -1 {_enc_bytes(4)}", f"\ts_endpgm {_enc_bytes(4)}"], max_steps=10) - - with self.assertRaises(ValueError): - self.run_items(["s_endpgm"], max_steps=0) - - def test_unsupported_instructions_and_operands_raise_cpu_ref_unsupported(self): - self.assertIs(cf_ref.Unsupported, cpu_ref.Unsupported) - self.assertIs(cf_ref.ProgramError, cpu_ref.ProgramError) - unsupported_programs = [ - (["v_pk_fma_f16 v0, v1, v2, v3", "s_endpgm"], 32), - (["ds_read_b32 v0, v1", "s_endpgm"], 32), - (["s_waitcnt vmcnt(0)", "s_endpgm"], 32), - (["s_andn1_wrexec_b32 s0, vcc_lo", "s_endpgm"], 32), - (["s_cmp_eq_u64 s[0:1], s[2:3]", "s_endpgm"], 64), - (["s_cmp_eq_u32 v0, 0", "s_endpgm"], 32), - (["v_cmp_eq_f32_e32 vcc, v0, v1", "s_endpgm"], 32), - (["v_cmpx_eq_u32_e64 s[0:1], v0, v1", "s_endpgm"], 64), - (["exp pos0 v0, v1, v2, v3 done", "s_endpgm"], 32), - (["exp mrt0 off, off, off, off done vm", "s_endpgm"], 32), - (["s_branch L_missing", "s_endpgm"], 32), - (["s_branch s0", "s_endpgm"], 32), - (["s_mov_saveexec_b32 s0, vcc_lo", "s_endpgm"], 32), - (["s_and_b32 vcc_lo, vcc_lo, scc", "s_endpgm"], 32), - (["v_cmp_eq_u32_e64 v0, v0, 0", "s_endpgm"], 32), - (["v_cmp_eq_u32_e32 vcc, v0", "s_endpgm"], 32), - (["v_add_nc_u32_e64 v2, v1, 1 clamp", "s_endpgm"], 32), - (["exp mrt0 v0, v0, v1, v1 done compr vm", "s_endpgm"], 32), - (["v_cmp_eq_u32_e32 vcc_lo, v0, v1 quad_perm:[1,0,3,2] row_mask:0xf bank_mask:0xf", "s_endpgm"], 32), - (["s_mov_b32 vcc, 1", "s_endpgm"], 64), - (["s_mov_b32 exec, 1", "s_endpgm"], 64), - ] - for insns, wave in unsupported_programs: - with self.subTest(insn=insns[0], wave=wave): - with self.assertRaises(cpu_ref.Unsupported): - self.run_items(insns, wave=wave) - - def test_program_errors_for_missing_encodings_header_endpgm_and_bad_branch_targets(self): - # Missing ; encoding: comment or empty ; encoding: [] - with self.assertRaises(cf_ref.ProgramError): - self.run_raw(["\ts_endpgm"]) - with self.assertRaises(cf_ref.ProgramError): - self.run_raw(["\ts_endpgm ; encoding: []"]) - # Missing header line - with self.assertRaises(cf_ref.ProgramError): - self.run_raw([f"\ts_endpgm {_enc_bytes(4)}"], header=None) - # Empty listing (no instructions) - with self.assertRaises(cf_ref.ProgramError): - self.run_raw([]) - # Missing s_endpgm - with self.assertRaises(cf_ref.ProgramError): - self.run_raw([f"\ts_mov_b32 s0, 1 {_enc_bytes(4)}"]) - # Branch out of bounds - with self.assertRaises(cf_ref.ProgramError): - self.run_raw([f"\ts_branch 10 {_enc_bytes(4)}", f"\ts_endpgm {_enc_bytes(4)}"]) - # Branch into the middle of an 8-byte instruction - with self.assertRaises(cf_ref.ProgramError): - self.run_raw([ - f"\ts_branch 1 {_enc_bytes(4)}", - f"\tv_mul_lo_u32 v0, v0, 2 {_enc_bytes(8)}", - f"\ts_endpgm {_enc_bytes(4)}", - ]) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/test_cf_ref_edge_fixes.py b/tests/test_cf_ref_edge_fixes.py deleted file mode 100644 index 2ea11772f..000000000 --- a/tests/test_cf_ref_edge_fixes.py +++ /dev/null @@ -1,294 +0,0 @@ -"""Regression tests for tools/cf_ref.py s_cmp_* validation and exec_hi/vcc_hi mask ops. - -Standard library only; uses hand-written synthetic .s listings (no game data, GPU, or llvm-mc). - -Run from the repository root: - python -I tests/test_cf_ref_edge_fixes.py -v -""" -import os -import sys -import tempfile -import unittest - -ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) -sys.path.insert(0, os.path.join(ROOT, "tools")) - -import cf_ref # noqa: E402 -import cpu_ref # noqa: E402 -from shader_ir import parse_file # noqa: E402 - -MASK32 = 0xFFFFFFFF -MASK64 = 0xFFFFFFFFFFFFFFFF -_VOP3_NO_E64 = {"v_mul_lo_u32", "v_mbcnt_lo_u32_b32", "v_mbcnt_hi_u32_b32"} - - -def _enc_bytes(size): - return "; encoding: [" + ",".join(["0x00"] * size) + "]" - - -def _guess_size(text): - op = text.split()[0] - if op == "exp" or op.endswith("_e64") or op in _VOP3_NO_E64: - return 8 - for tok in text.replace(",", " ").split()[1:]: - if tok.startswith("0x") or (tok.lstrip("-").isdigit() and not (-16 <= int(tok) <= 64)): - return 8 - return 4 - - -def assemble(items, name="test"): - pc = 0 - labels = {} - sized = [] - for item in items: - if isinstance(item, tuple) and item[0] == "lbl": - labels[item[1]] = pc - continue - if isinstance(item, tuple) and item[0] == "br": - sized.append((item, pc, 4)) - pc += 4 - else: - text, size = item if isinstance(item, tuple) else (item, _guess_size(item)) - sized.append((text, pc, size)) - pc += size - - lines = [f"; {name} code 0x0..0x{pc:x}"] - for item, at, size in sized: - if isinstance(item, tuple) and item[0] == "br": - _, op, target = item - delta = labels[target] - (at + 4) - if delta % 4 != 0: - raise ValueError(f"branch target {target} is not 4-byte aligned") - text = f"{op} {delta // 4}" - else: - text = item - lines.append(f"\t{text} {_enc_bytes(size)}") - return "\n".join(lines) + "\n" - - -def lane_id_prologue(wave): - insns = ["v_mbcnt_lo_u32_b32 v0, -1, 0"] - if wave == 64: - insns.append("v_mbcnt_hi_u32_b32 v0, -1, v0") - return insns - - -class CfRefEdgeFixesTests(unittest.TestCase): - def setUp(self): - self.tmp = tempfile.TemporaryDirectory(prefix="cf-ref-edge-") - self.addCleanup(self.tmp.cleanup) - self.n = 0 - - def write_items(self, items): - self.n += 1 - path = os.path.join(self.tmp.name, f"t{self.n}.s") - with open(path, "w", encoding="utf-8", newline="\n") as f: - f.write(assemble(items, name=f"t{self.n}")) - return path - - def run_items(self, items, wave=32): - return cf_ref.run(self.write_items(items), wave=wave) - - def test_s_cmp_unknown_condition_raises_unsupported(self): - bad_ops = [ - "s_cmp_bad_u32 s0, s1", - "s_cmp_bad_i32 s0, s1", - "s_cmp_tru_u32 s0, s1", - "s_cmp_f_i32 s0, s1", - "s_cmp_foo s0, s1", - "s_cmp_eq_u64 s[0:1], s[2:3]", - "s_cmp_lt_f32 s0, s1", - ] - for insn in bad_ops: - mnemonic = insn.split()[0] - with self.subTest(insn=insn): - with self.assertRaises(cpu_ref.Unsupported) as cm: - self.run_items([insn, "s_endpgm"], wave=32) - self.assertIn(mnemonic, str(cm.exception)) - - def test_wave64_exec_hi_mov_preserves_lo_and_controls_upper_lanes(self): - # Set exec_lo to lanes {0, 1} and exec_hi to lanes {32, 34}, preserving exec_lo. - # Then verify active lanes 32..63 run, inactive ones do not, and exec_hi clears cleanly. - res = self.run_items(lane_id_prologue(64) + [ - "v_mov_b32 v1, 0", - "v_mov_b32 v2, 0", - "v_mov_b32 v3, 0", - "s_cmp_eq_u32 1, 1", # SCC = 1; s_mov_b32 exec_hi must preserve SCC - "s_mov_b32 exec_lo, 0x00000003", - "s_mov_b32 exec_hi, 0x00000005", - "s_mov_b32 s0, scc", - "v_mov_b32 v1, 77", - "exp mrt0 v0, v1, v2, v3 done vm", - "s_mov_b32 exec_hi, 0", - "s_endpgm", - ], wave=64) - self.assertEqual(res["sgpr"][0], 1) - self.assertEqual(sorted(res["exports"]), [0, 1, 32, 34]) - for lane in (0, 1, 32, 34): - self.assertEqual(res["exports"][lane], (lane, 77, 0, 0)) - self.assertEqual(res["exec"], 0x0000000000000003) - - # exec_lo == 0 and exec_hi != 0 must keep EXECZ == 0 (s_cbranch_execnz taken). - res_nz = self.run_items([ - "s_mov_b32 s0, 0", - "s_mov_b32 exec_lo, 0", - "s_mov_b32 exec_hi, 0x00010000", - ("br", "s_cbranch_execz", "bad"), - ("br", "s_cbranch_execnz", "ok"), - ("lbl", "bad"), - "s_mov_b32 s0, 999", - ("lbl", "ok"), - "s_add_u32 s0, s0, 1", - "s_mov_b32 exec_hi, 0", - ("br", "s_cbranch_execnz", "bad2"), - "s_add_u32 s0, s0, 2", - ("lbl", "bad2"), - "s_endpgm", - ], wave=64) - self.assertEqual(res_nz["sgpr"][0], 3) - self.assertEqual(res_nz["exec"], 0) - - def test_wave64_vcc_hi_mov_preserves_lo_and_drives_upper_lanes(self): - # Write vcc_lo (lanes 1, 3) then vcc_hi (lanes 33, 63); low 32 bits must stay intact - # and VOP2 v_cndmask_b32 must see vcc[63:32] on lanes 32..63. - res = self.run_items(lane_id_prologue(64) + [ - "s_cmp_eq_u32 1, 1", # SCC = 1; s_mov_b32 vcc_hi must preserve SCC - "s_mov_b32 vcc_lo, 0x0000000a", - "s_mov_b32 vcc_hi, 0x80000002", - "s_mov_b32 s0, scc", - "v_mov_b32 v1, 10", - "v_mov_b32 v2, 20", - "v_cndmask_b32 v3, v1, v2", - "v_mov_b32 v4, 0", - "exp mrt0 v0, v3, v4, v4 done vm", - "s_endpgm", - ], wave=64) - self.assertEqual(res["sgpr"][0], 1) - self.assertEqual(res["vcc"], (0x80000002 << 32) | 0x0000000A) - for lane in range(64): - want = 20 if lane in (1, 3, 33, 63) else 10 - self.assertEqual(res["exports"][lane][1], want) - - # vcc_lo == 0 and vcc_hi != 0 must keep VCCZ == 0 in wave64; clearing vcc_hi sets VCCZ == 1. - res_vccz = self.run_items([ - "s_mov_b32 s0, 0", - "s_mov_b32 vcc_lo, 0", - "s_mov_b32 vcc_hi, 0x10", - ("br", "s_cbranch_vccz", "bad"), - "s_add_u32 s0, s0, 1", - "s_mov_b32 vcc_hi, 0", - ("br", "s_cbranch_vccnz", "bad"), - "s_add_u32 s0, s0, 2", - ("br", "s_cbranch_vccz", "done"), - ("lbl", "bad"), - "s_mov_b32 s0, 999", - ("lbl", "done"), - "s_endpgm", - ], wave=64) - self.assertEqual(res_vccz["sgpr"][0], 3) - self.assertEqual(res_vccz["vcc"], 0) - - def test_read_exec_hi_and_vcc_hi_in_scalar_ops_wave64(self): - res = self.run_items([ - "s_mov_b32 exec_lo, 0x11223344", - "s_mov_b32 exec_hi, 0x55667788", - "s_mov_b32 vcc_lo, 0xaabbccdd", - "s_mov_b32 vcc_hi, 0x0f0f0f0f", - "s_cmp_eq_u32 1, 2", # SCC = 0; s_mov_b32 must preserve SCC - "s_mov_b32 s4, vcc_hi", - "s_mov_b32 s5, exec_hi", - "s_mov_b32 s6, scc", - "s_and_b32 s7, exec_hi, 0x00ff00ff", - "s_mov_b32 s8, scc", - "s_or_b32 vcc_hi, vcc_hi, 0xf0000000", - "s_mov_b32 s9, scc", - "s_xnor_b32 s10, exec_hi, 0x55667788", # 32-bit exact complement of XOR -> 0xffffffff -> SCC=1 - "s_mov_b32 s11, scc", - "s_xor_b32 s12, exec_hi, 0x55667788", # 0 -> SCC=0 - "s_mov_b32 s13, scc", - "s_xnor_b32 s14, exec_hi, 0xaa998877", # 0 -> SCC=0 (verifies 32-bit mask, not 64-bit) - "s_mov_b32 s15, scc", - "s_cmp_eq_u32 vcc_hi, 0xff0f0f0f", - "s_mov_b32 s16, scc", - "s_cmp_lg_u32 exec_hi, 0x55667788", - "s_mov_b32 s17, scc", - "s_mov_b32 exec_lo, -1", - "s_mov_b32 exec_hi, 0", - "s_xnor_b32 s18, exec_hi, -1", # 32-bit -1 -> ~(0 ^ 0xffffffff) = 0, SCC=0 - "s_mov_b32 s19, scc", - "s_mov_b32 exec_hi, -1", - "s_xor_b32 s20, exec_hi, -1", # 32-bit -1 -> 0xffffffff ^ 0xffffffff = 0, SCC=0 - "s_mov_b32 s21, scc", - "s_endpgm", - ], wave=64) - self.assertEqual(res["sgpr"][4], 0x0F0F0F0F) - self.assertEqual(res["sgpr"][5], 0x55667788) - self.assertEqual(res["sgpr"][6], 0) - self.assertEqual(res["sgpr"][7], 0x00660088) - self.assertEqual(res["sgpr"][8], 1) - self.assertEqual(res["sgpr"][9], 1) - self.assertEqual(res["sgpr"][10], 0xFFFFFFFF) - self.assertEqual(res["sgpr"][11], 1) - self.assertEqual(res["sgpr"][12], 0) - self.assertEqual(res["sgpr"][13], 0) - self.assertEqual(res["sgpr"][14], 0) - self.assertEqual(res["sgpr"][15], 0) - self.assertEqual(res["sgpr"][16], 1) - self.assertEqual(res["sgpr"][17], 0) - self.assertEqual(res["sgpr"][18], 0) - self.assertEqual(res["sgpr"][19], 0) - self.assertEqual(res["sgpr"][20], 0) - self.assertEqual(res["sgpr"][21], 0) - self.assertEqual(res["vcc"], (0xFF0F0F0F << 32) | 0xAABBCCDD) - self.assertEqual(res["exec"], MASK64) - - # Full-wave 64-bit register names in _b32 SOP2 ops remain rejected in wave64. - with self.assertRaises(cpu_ref.Unsupported): - self.run_items(["s_and_b32 vcc, vcc, exec", "s_endpgm"], wave=64) - - def test_wave32_exec_hi_keeps_upper_half_zero_and_vcc_hi_is_scalar(self): - # Wave32 runs with EXEC[63:32] == 0 so lanes 32-63 never execute even if exec_hi is written. - # vcc_hi holds its own 32-bit value independently of wave32 VCC[31:0] / VCCZ. - items = lane_id_prologue(32) + [ - "s_mov_b32 exec_lo, 0x0000000f", - "s_mov_b32 exec_hi, 0xffffffff", - "s_or_b32 exec_hi, exec_hi, 0x1", - "s_mov_b32 s0, exec_hi", - "s_and_b32 s1, exec_hi, 1", - "s_mov_b32 s2, scc", - "s_mov_b32 vcc_lo, 0x00000005", - "s_mov_b32 vcc_hi, 0xdeadbeef", - "s_mov_b32 s3, vcc_hi", - "s_and_b32 s4, vcc_hi, 0x0000ffff", - "s_mov_b32 vcc_lo, 0", - ("br", "s_cbranch_vccnz", "bad"), - "s_and_saveexec_b32 vcc_hi, 0x00000003", - "s_mov_b32 s5, vcc_hi", - "s_mov_b32 exec_lo, vcc_hi", - "v_mov_b32 v1, 1", - "v_mov_b32 v2, 2", - "v_mov_b32 v3, 3", - "exp mrt0 v0, v1, v2, v3 done vm", - ("br", "s_branch", "done"), - ("lbl", "bad"), - "s_mov_b32 s3, 0", - ("lbl", "done"), - "s_endpgm", - ] - path = self.write_items(items) - machine = cf_ref.WaveMachine(parse_file(path), wave=32) - res = machine.run() - self.assertEqual(machine.exec >> 32, 0) - self.assertEqual(res["exec"], 0x0000000F) - self.assertEqual(res["vcc"], 0) - self.assertEqual(res["sgpr"][0], 0) - self.assertEqual(res["sgpr"][1], 0) - self.assertEqual(res["sgpr"][2], 0) - self.assertEqual(res["sgpr"][3], 0xDEADBEEF) - self.assertEqual(res["sgpr"][4], 0x0000BEEF) - self.assertEqual(res["sgpr"][5], 0x0000000F) - self.assertEqual(sorted(res["exports"]), [0, 1, 2, 3]) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/test_cfg_run_limit.py b/tests/test_cfg_run_limit.py deleted file mode 100644 index cd0f632ac..000000000 --- a/tests/test_cfg_run_limit.py +++ /dev/null @@ -1,41 +0,0 @@ -"""tools/cfg_structure.run stops after `limit` blocks, and a limit of zero or less runs none (standard library only). - - python -I tests/test_cfg_run_limit.py -""" -import os -import sys -import unittest - -ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) -sys.path.insert(0, os.path.join(ROOT, "tools")) - -import cfg_structure # noqa: E402 - - -def straight_line(n): - """A tree of n blocks, 0..n-1, where each block goes to the next one.""" - return [("block", i) for i in range(n)], lambda b: b + 1 - - -class RunLimitTest(unittest.TestCase): - def test_runs_everything_under_the_limit(self): - tree, choose = straight_line(3) - self.assertEqual(cfg_structure.run(tree, choose, 10), [0, 1, 2]) - - def test_stops_after_limit_blocks(self): - tree, choose = straight_line(5) - self.assertEqual(cfg_structure.run(tree, choose, 2), [0, 1]) - self.assertEqual(cfg_structure.run(tree, choose, 1), [0]) - - def test_limit_equal_to_the_length_runs_everything(self): - tree, choose = straight_line(3) - self.assertEqual(cfg_structure.run(tree, choose, 3), [0, 1, 2]) - - def test_zero_or_negative_limit_runs_nothing(self): - tree, choose = straight_line(3) - self.assertEqual(cfg_structure.run(tree, choose, 0), []) - self.assertEqual(cfg_structure.run(tree, choose, -4), []) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/test_cfg_structure.py b/tests/test_cfg_structure.py deleted file mode 100644 index d4fa49058..000000000 --- a/tests/test_cfg_structure.py +++ /dev/null @@ -1,256 +0,0 @@ -"""cfg_structure.structure: the tree runs exactly the blocks the graph does, in the same order. - - python -I tests/test_cfg_structure.py - -Random graphs, random branch outcomes. For each graph the tree is interpreted and compared with a plain walk of -the graph that makes the same choices. Irreducible graphs must be refused (None), reducible ones must not be. -""" -from functools import cache -import os -import random -import sys - -sys.path.insert(0, os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "tools")) -import cfg_structure as S # noqa: E402 - - -@cache -def branch_index(seed, block, visit, count): - # The choice depends only on these numbers, so different graphs can reuse it. - return random.Random(f"{seed}/{block}/{visit}").randrange(count) - - -def chooser(succ, seed): - """Branch outcomes that depend only on the block and how often it has run, so two runs that execute the - same blocks make the same choices.""" - visits = {} - - def choose(b): - options = succ[b] - if len(options) < 2: - return options[0] if options else S.END - k = visits[b] = visits.get(b, 0) + 1 - return options[branch_index(seed, b, k, len(options))] - return choose - - -def walk(succ, choose, limit): - trace, b = [], 0 - while b != S.END and len(trace) < limit: - trace.append(b) - b = choose(b) - return trace - - -def reducible(succ): - """Independent test (T1/T2): repeatedly delete self-loops and merge a block into its only predecessor.""" - g = {v: set(s) for v, s in enumerate(succ)} - seen, work = {0}, [0] - while work: - for w in g[work.pop()]: - if w not in seen: - seen.add(w) - work.append(w) - g = {v: {w for w in s if w in seen} for v, s in g.items() if v in seen} - changed = True - while changed and len(g) > 1: - changed = False - for v in list(g): - g[v].discard(v) - preds = [p for p in g if v in g[p]] - if v != 0 and len(preds) == 1: - p = preds[0] - g[p] |= g.pop(v) - g[p].discard(v) - changed = True - break - return len(g) == 1 - - -def random_graph(rng): - n = rng.randint(1, 14) - kind = rng.random() - succ = [] - for v in range(n): - k = rng.choice((0, 1, 1, 2, 2, 2)) - if kind < 0.5: # anything goes: many of these are irreducible - succ.append([rng.randrange(n) for _ in range(k)]) - else: # mostly forward, with jumps back: loops, breaks, early exits - succ.append([rng.randrange(v + 1, n) if v + 1 < n and rng.random() < 0.75 else rng.randrange(v + 1) - for _ in range(k)]) - return succ - - -def blocks_in(tree): - out = [] - stack = [tree] - while stack: - for it in reversed(stack.pop()): - if it[0] == "block": - out.append(it[1]) - else: - stack.append(it[2]) - out.reverse() - return out - - -def max_depth(tree): - best = 0 - stack = [(tree, 0)] - while stack: - items, depth = stack.pop() - if depth > best: - best = depth - for it in items: - if it[0] in ("guard", "loop"): - stack.append((it[2], depth + 1)) - return best - - -def _check_random_graphs(): - rng = random.Random(20261121) - structured = refused = loops = split_ok = split_cap = 0 - for case in range(20000): - succ = random_graph(rng) - tree = S.structure(succ) - assert (tree is not None) == reducible(succ), f"reducibility disagrees for {succ}" - if tree is None: - refused += 1 - res = S.split_irreducible(succ) - if res is not None: - new_succ, orig = res - assert len(new_succ) <= min(2 * len(succ), len(succ) + 64) - stree = S.structure(new_succ) - assert stree is not None, f"split_irreducible returned irreducible graph for {succ}" - splaced = blocks_in(stree) - assert len(splaced) == len(set(splaced)), f"a split block is placed twice: {succ}" - for seed in range(6): - want = walk(succ, chooser(succ, seed), 200) - visits = {} - - def split_choose(b, _orig=orig, _ns=new_succ, _seed=seed, _v=visits): - ob = _orig[b] - k = _v[ob] = _v.get(ob, 0) + 1 - opts = _ns[b] - if not opts: - return S.END - return opts[branch_index(_seed, ob, k, len(opts))] - - got = [orig[b] for b in S.run(stree, split_choose, 200)] - assert got == want, f"split graph {succ} seed {seed}: tree ran {got}, graph runs {want}" - split_ok += 1 - else: - split_cap += 1 - continue - structured += 1 - loops += '"loop"' in repr(tree).replace("'", '"') - placed = blocks_in(tree) - assert len(placed) == len(set(placed)), f"a block is placed twice: {succ}" - for seed in range(6): - want = walk(succ, chooser(succ, seed), 200) - got = S.run(tree, chooser(succ, seed), 200) - assert got == want, f"graph {succ} seed {seed}: tree ran {got}, graph runs {want}" - assert structured > 5000 and refused > 1000 and loops > 2000, (structured, refused, loops) - assert split_ok > 1000 and split_ok + split_cap == refused, (split_ok, split_cap, refused) - return structured, refused, loops, split_ok, split_cap - - -def test_random_graphs(): - _check_random_graphs() - - -def test_depth(): - assert S.depth([("block", 0)]) == 0 - assert S.depth([("block", 0), ("loop", 1, [("block", 1), ("guard", 2, [("block", 2)])])]) == 2 - assert S.depth([]) == 0 - assert S.depth(S.structure([[1, 2], [3], [3], []])) == 1 # a diamond is one guard deep - - -def test_shapes(): - assert S.structure([[]]) == [("block", 0)] - assert S.structure([[1], [2], []]) == [("block", 0), ("block", 1), ("block", 2)] # no tests needed - # A diamond: the two arms in either order (here 2 first), then the join, which must come last. - assert S.structure([[1, 2], [3], [3], []]) == [("block", 0), ("guard", 2, [("block", 2)]), - ("guard", 1, [("block", 1)]), ("guard", 3, [("block", 3)])] - assert S.structure([[0, 1], []]) == [("loop", 0, [("block", 0)]), ("guard", 1, [("block", 1)])] - assert S.structure([[1, 2], [2], [1]]) is None # two-entry loop - ns, orig = S.split_irreducible([[1, 2], [2], [1]]) - assert S.structure(ns) is not None and len(ns) == 4 and orig == [0, 1, 2, 2] - # Nested irreducible cycle {2, 3} inside an outer reducible loop headed by 1. - nested = [[1], [2, 3], [3, 4], [2, 4], [1, 5], []] - assert S.structure(nested) is None - ns2, orig2 = S.split_irreducible(nested) - assert S.structure(ns2) is not None and len(ns2) == 7 - # Regression for single-node infinite unrolling: SCC {1, 2, 3} with entries 1 (h) and 2 (e), plus an - # internal subcycle 2 <-> 3 that does not pass through 1. Single-node cloning bounces 2' -> 3 -> 3' -> 2 -> ... - # until hitting the cap; closed-region cloning duplicates R = {2, 3} once (+2 blocks, 5 -> 7). - subcycle = [[1, 2], [3, 4], [3], [1, 2], []] - assert S.structure(subcycle) is None - ns3, orig3 = S.split_irreducible(subcycle) - assert S.structure(ns3) is not None and len(ns3) == 7 - for seed in range(6): - want = walk(subcycle, chooser(subcycle, seed), 200) - visits = {} - - def sc_choose(b, _o=orig3, _ns=ns3, _s=seed, _v=visits): - ob = _o[b] - k = _v[ob] = _v.get(ob, 0) + 1 - opts = _ns[b] - return S.END if not opts else opts[random.Random(f"{_s}/{ob}/{k}").randrange(len(opts))] - - assert [orig3[b] for b in S.run(S.structure(ns3), sc_choose, 200)] == want - # Cap enforcement: max_splits=0 must refuse an irreducible graph cleanly. - assert S.split_irreducible([[1, 2], [2], [1]], max_splits=0) is None - - -def test_deep_sequential_chains_stay_flat_and_iterative(): - """Long chains of sequential if/else diamonds, sequential loops, and early-exit chains must structure without - hitting Python's recursion limit and keep bounded OpSelectionMerge nesting depth.""" - # 1. 2,000 sequential if/else diamonds (6,001 blocks): previously nested 2,000 levels deep and raised RecursionError. - n_diamonds = 2000 - diamonds = [] - for k in range(n_diamonds): - b = 3 * k - diamonds.extend([[b + 1, b + 2], [b + 3], [b + 3]]) - diamonds.append([]) - tree = S.structure(diamonds) - assert tree is not None - assert len(blocks_in(tree)) == len(diamonds) - assert max_depth(tree) <= 2, f"expected O(1) depth on sequential diamonds, got {max_depth(tree)}" - for seed in range(3): - want = walk(diamonds, chooser(diamonds, seed), len(diamonds) + 5) - got = S.run(tree, chooser(diamonds, seed), len(diamonds) + 5) - assert got == want - - # 2. 1,200 sequential single-block loops: previously nested 1,200 levels deep. - n_loops = 1200 - loops = [[k, k + 1] for k in range(n_loops)] + [[]] - ltree = S.structure(loops) - assert ltree is not None - assert len(blocks_in(ltree)) == len(loops) - assert max_depth(ltree) <= 2, f"expected O(1) depth on sequential loops, got {max_depth(ltree)}" - for seed in range(3): - want = walk(loops, chooser(loops, seed), 5000) - got = S.run(ltree, chooser(loops, seed), 5000) - assert got == want - - # 3. 1,500 sequential early-exit guards (b -> {b+1, END}): stays bounded by max_guard_depth without recursion. - n_exits = 1500 - exits = [[k + 1, n_exits] for k in range(n_exits)] + [[]] - etree = S.structure(exits) - assert etree is not None - assert len(blocks_in(etree)) == len(exits) - assert max_depth(etree) <= 17, f"expected bounded depth on early-exit chain, got {max_depth(etree)}" - for seed in range(3): - want = walk(exits, chooser(exits, seed), len(exits) + 5) - got = S.run(etree, chooser(exits, seed), len(exits) + 5) - assert got == want - - -if __name__ == "__main__": - test_depth() - test_shapes() - test_deep_sequential_chains_stay_flat_and_iterative() - structured, refused, loops, split_ok, split_cap = _check_random_graphs() - print(f"ok: {structured} graphs structured and run, {refused} irreducible " - f"({split_ok} split-structured, {split_cap} capped), {loops} with loops") diff --git a/tests/test_character_census.py b/tests/test_character_census.py deleted file mode 100644 index d55c33243..000000000 --- a/tests/test_character_census.py +++ /dev/null @@ -1,548 +0,0 @@ -"""character_census: synthetic decoded models, manifest rows and the report-path guard. - - python -I tests/test_character_census.py - -All model.json files, manifests, shaders, textures and counts here are built by the test. No game -data is read or written. -""" -import contextlib -import csv -import importlib.util -import io -import json -import os -import pathlib -import subprocess -import sys -import tempfile -import unittest -from unittest import mock - -ROOT = pathlib.Path(__file__).resolve().parent.parent -TOOL = ROOT / "tools" / "character_census.py" - - -def load_tool(): - spec = importlib.util.spec_from_file_location("character_census_under_test", TOOL) - module = importlib.util.module_from_spec(spec) - spec.loader.exec_module(module) - return module - - -CC = load_tool() - - -def write_json(path, value): - path.parent.mkdir(parents=True, exist_ok=True) - path.write_text(json.dumps(value, indent=2), encoding="utf-8") - - -def skinned_model(): - return { - "name": "synthetic_skinned", - "type": "dr", - "vertex_count": 12, - "triangle_count": 4, - "drawable": { - "name": "synthetic_skinned", - "skeleton": [ - {"name": "SKEL_ROOT"}, - {"name": "SKEL_Pelvis"}, - {"name": "SKEL_Head"}, - ], - "models": [{"bone_palette": [1, 2, 3]}], - "shaders": [{"name_hash": "210FBC6A", - "textures": [{"hash64": "AABBCCDDEEFF0011"}]}], - }, - "materials": [ - {"shader_name_hash": "210FBC6A", - "textures": [{"param_hash": "C8E8C282", "hash64": "AABBCCDDEEFF0011"}]}, - {"shader_name_hash": "DEADBEEF", - "textures": [{"hash64": "0011223344556677"}]}, - ], - "meshes": [ - {"name": "mesh0", "vertex_count": 8, "triangle_count": 2, "skinned": True, - "skin_influences": 8, "bones": ["SKEL_ROOT", "SKEL_Pelvis", "SKEL_Head"]}, - {"name": "mesh1", "vertex_count": 4, "triangle_count": 2, "skinned": True, - "skin_influences": 4}, - ], - } - - -def static_model(): - return { - "name": "synthetic_static", - "type": "dr", - "vertex_count": 6, - "triangle_count": 2, - "materials": [ - {"shader_name_hash": "12345678", "textures": [{"hash32": "89ABCDEF"}]}, - ], - "meshes": [ - {"name": "static", "vertex_count": 6, "triangle_count": 2, "skinned": False}, - ], - } - - -def fragment_model(): - return { - "name": "synthetic_fragment", - "type": "ft", - "vertex_count": 25, - "triangle_count": 32, - "drawable": { - "skeleton": [{"name": "SKEL_ROOT"}, {"name": "SKEL_Pelvis"}], - }, - "materials": [{"shader_name_hash": "B5D47C70", "textures": []}], - "meshes": [ - {"name": "bounds", "vertex_count": 25, "triangle_count": 32, "skinned": True, - "skin_influences": 1}, - ], - } - - -def partial_model(): - return { - "name": "synthetic_partial", - "type": "ft", - "vertex_count": "many", - "triangle_count": -1, - "meshes": "not-a-list", - "materials": {}, - } - - -class CharacterCensusTest(unittest.TestCase): - def setUp(self): - self.temp = tempfile.TemporaryDirectory() - self.root = pathlib.Path(self.temp.name) / "models" - self.root.mkdir() - write_json(self.root / "skinned" / "model.json", skinned_model()) - write_json(self.root / "static" / "model.json", static_model()) - write_json(self.root / "fragment" / "model.json", fragment_model()) - write_json(self.root / "partial" / "model.json", partial_model()) - broken = self.root / "broken" / "model.json" - broken.parent.mkdir() - broken.write_text('{"name": "synthetic_broken",', encoding="utf-8") - - def tearDown(self): - self.temp.cleanup() - - def run_tool(self, *args): - return subprocess.run([sys.executable, "-I", str(TOOL), *map(str, args)], - cwd=ROOT, capture_output=True, text=True, timeout=120) - - def report(self, *args): - path = pathlib.Path(self.temp.name) / "report.json" - result = self.run_tool(self.root, "--json", path, *args) - self.assertEqual(result.returncode, 0, result.stderr) - return json.loads(path.read_text(encoding="utf-8")) - - def by_name(self, data): - return {row["name"]: row for row in data["models"]} - - def test_table_prints_counts_kinds_and_skins(self): - result = self.run_tool(self.root) - self.assertEqual(result.returncode, 0, result.stderr) - self.assertNotIn("Traceback", result.stderr) - self.assertIn("character census: 5 models", result.stdout) - self.assertIn("43 vertices (2 without)", result.stdout) - self.assertIn("38 triangles (2 without)", result.stdout) - self.assertIn("? indices", result.stdout) - self.assertIn("8-influence skin: 1 yes, 3 no, 1 unknown", result.stdout) - self.assertIn("by kind:", result.stdout) - self.assertIn("by shader (a model with several materials counts under each):", result.stdout) - self.assertIn("0x210FBC6A", result.stdout) - self.assertIn("0xB5D47C70", result.stdout) - self.assertIn("synthetic_skinned", result.stdout) - self.assertIn("synthetic_fragment", result.stdout) - self.assertIn("problems:", result.stdout) - self.assertIn("cannot read model.json", result.stdout) - - def test_json_summary_and_rows_are_reproducible(self): - data = self.report() - summary = data["summary"] - self.assertEqual(summary["models"], 5) - self.assertEqual(summary["vertices"], 43) - self.assertEqual(summary["triangles"], 38) - self.assertEqual(summary["indices"], 0) - self.assertEqual(summary["unknown_vertices"], 2) - self.assertEqual(summary["unknown_triangles"], 2) - self.assertEqual(summary["unknown_indices"], 5) - self.assertEqual(summary["skin_8"], 1) - self.assertEqual(summary["skin_unknown"], 1) - self.assertEqual(summary["malformed"], 2) - self.assertEqual(summary["shader_hashes"], 4) - self.assertEqual(summary["texture_keys"], 3) - self.assertEqual(list(summary["by_kind"]), ["drawable", "fragment", "unknown"]) - self.assertEqual(summary["by_kind"]["drawable"]["models"], 2) - self.assertEqual(summary["by_kind"]["drawable"]["vertices"], 18) - self.assertEqual(summary["by_kind"]["drawable"]["triangles"], 6) - self.assertEqual(summary["by_kind"]["fragment"]["models"], 2) - self.assertEqual(summary["by_kind"]["fragment"]["vertices"], 25) - self.assertEqual(summary["by_kind"]["fragment"]["triangles"], 32) - self.assertEqual(summary["by_shader"]["0x210FBC6A"], - {"models": 1, "vertices": 12, "triangles": 4}) - self.assertEqual(summary["by_shader"]["0xDEADBEEF"], - {"models": 1, "vertices": 12, "triangles": 4}) - self.assertEqual(summary["by_shader"]["0x12345678"], - {"models": 1, "vertices": 6, "triangles": 2}) - self.assertEqual(summary["by_shader"]["0xB5D47C70"], - {"models": 1, "vertices": 25, "triangles": 32}) - - rows = self.by_name(data) - self.assertEqual(sorted(rows), ["broken", "synthetic_fragment", "synthetic_partial", - "synthetic_skinned", "synthetic_static"]) - skinned = rows["synthetic_skinned"] - self.assertEqual(skinned["kind"], "drawable") - self.assertEqual(skinned["vertices"], 12) - self.assertEqual(skinned["triangles"], 4) - self.assertIsNone(skinned["indices"]) - self.assertEqual(skinned["bones"], 3) - self.assertIs(skinned["skin_8"], True) - self.assertEqual(skinned["shaders"], ["0x210FBC6A", "0xDEADBEEF"]) - self.assertEqual(skinned["textures"], ["0x0011223344556677", "0xAABBCCDDEEFF0011"]) - self.assertEqual(skinned["issues"], []) - - static = rows["synthetic_static"] - self.assertEqual(static["bones"], 0) - self.assertIs(static["skin_8"], False) - self.assertEqual(static["textures"], ["0x89ABCDEF"]) - - fragment = rows["synthetic_fragment"] - self.assertEqual(fragment["kind"], "fragment") - self.assertEqual(fragment["bones"], 2) - self.assertIs(fragment["skin_8"], False) - - broken = rows["broken"] - self.assertEqual(broken["kind"], "unknown") - self.assertIsNone(broken["vertices"]) - self.assertTrue(any("cannot read model.json" in issue for issue in broken["issues"])) - - partial = rows["synthetic_partial"] - self.assertEqual(partial["kind"], "fragment") - self.assertEqual(partial["bones"], 0) - self.assertIs(partial["skin_8"], False) - for text in ("meshes is not a list", "materials is not a list", - "vertex count is not a non-negative integer", "missing vertex count", - "triangle count is not a non-negative integer", "missing triangle count"): - self.assertTrue(any(text in issue for issue in partial["issues"]), text) - - def test_mesh_totals_require_all_contributions_and_derive_triangles_per_mesh(self): - root = pathlib.Path(self.temp.name) / "mesh_counts" - write_json(root / "model.json", {"name": "mixed", "meshes": [ - {"vertex_count": 5, "triangle_count": 2}, {"indices": [0, 1, 2]}, - ]}) - out = pathlib.Path(self.temp.name) / "counts.json" - result = self.run_tool(root, "--json", out) - self.assertEqual(result.returncode, 0, result.stderr) - report = json.loads(out.read_text(encoding="utf-8")) - row, = report["models"] - self.assertIsNone(row["vertices"]) - self.assertIsNone(row["indices"]) - self.assertEqual(row["triangles"], 3) - self.assertEqual(report["summary"]["unknown_vertices"], 1) - self.assertEqual(report["summary"]["unknown_indices"], 1) - self.assertEqual(report["summary"]["by_kind"]["component"]["triangles"], 3) - - def test_indices_from_separate_meshes_do_not_form_a_triangle(self): - row = CC.model_row({"meshes": [{"index_count": 2}, {"index_count": 2}]}, "model.json") - self.assertEqual(row["indices"], 4) - self.assertEqual(row["triangles"], 0) - - def test_optional_index_count_is_counted_when_an_input_supplies_it(self): - with tempfile.TemporaryDirectory() as td: - root = pathlib.Path(td) / "one" - write_json(root / "model.json", { - "name": "synthetic_indexed", - "type": "dr", - "vertex_count": 4, - "triangle_count": 1, - "index_count": 12, - "materials": [], - "meshes": [{"name": "m", "vertex_count": 4, "triangle_count": 1}], - }) - out = pathlib.Path(td) / "report.json" - result = self.run_tool(root, "--json", out) - self.assertEqual(result.returncode, 0, result.stderr) - data = json.loads(out.read_text(encoding="utf-8")) - self.assertEqual(data["summary"]["indices"], 12) - self.assertEqual(data["summary"]["unknown_indices"], 0) - self.assertEqual(data["models"][0]["indices"], 12) - - def test_csv_has_one_row_per_model(self): - path = pathlib.Path(self.temp.name) / "report.csv" - result = self.run_tool(self.root, "--csv", path) - self.assertEqual(result.returncode, 0, result.stderr) - with path.open(newline="", encoding="utf-8") as handle: - rows = {row["name"]: row for row in csv.DictReader(handle)} - self.assertEqual(len(rows), 5) - self.assertEqual(rows["synthetic_skinned"]["skin_8"], "true") - self.assertEqual(rows["synthetic_static"]["skin_8"], "false") - self.assertEqual(rows["broken"]["skin_8"], "") - self.assertEqual(rows["synthetic_skinned"]["shaders"], "0x210FBC6A;0xDEADBEEF") - self.assertEqual(rows["synthetic_skinned"]["textures"], - "0x0011223344556677;0xAABBCCDDEEFF0011") - self.assertEqual(rows["synthetic_static"]["vertices"], "6") - self.assertEqual(rows["broken"]["vertices"], "") - - def test_json_and_csv_must_differ(self): - out = pathlib.Path(self.temp.name) / "report.bin" - result = self.run_tool(self.root, "--json", out, "--csv", out) - self.assertEqual(result.returncode, 2, result.stderr) - self.assertIn("must use different paths", result.stderr) - - def test_report_path_cannot_overwrite_a_nested_model(self): - target = self.root / "skinned" / "model.json" - before = target.read_text(encoding="utf-8") - result = self.run_tool(self.root, "--json", target) - self.assertEqual(result.returncode, 2, result.stderr) - self.assertIn("would overwrite the input", result.stderr) - self.assertEqual(target.read_text(encoding="utf-8"), before) - - def test_report_path_alias_is_refused(self): - target = self.root / "skinned" / "model.json" - before = target.read_text(encoding="utf-8") - alias = self.root / "sub" / ".." / "skinned" / "model.json" - result = self.run_tool(self.root, "--csv", alias) - self.assertEqual(result.returncode, 2, result.stderr) - self.assertIn("would overwrite the input", result.stderr) - self.assertEqual(target.read_text(encoding="utf-8"), before) - - def test_report_path_cannot_be_a_directory(self): - result = self.run_tool(self.root, "--json", self.root) - self.assertEqual(result.returncode, 2, result.stderr) - self.assertIn("is a directory", result.stderr) - - def test_report_write_failure_names_the_destination(self): - blocker = pathlib.Path(self.temp.name) / "file" - blocker.write_bytes(b"keep") - for flag in ("--json", "--csv"): - with self.subTest(flag=flag): - target = blocker / ("report." + flag[2:]) - result = self.run_tool(self.root, flag, target) - self.assertEqual(result.returncode, 2, result.stderr) - self.assertEqual(result.stdout, "") - self.assertIn(f"cannot write {target}", result.stderr) - self.assertNotIn("Traceback", result.stderr) - self.assertEqual(blocker.read_bytes(), b"keep") - - def test_report_inside_the_tree_but_not_an_input_is_allowed(self): - out = self.root / "report.json" - result = self.run_tool(self.root, "--json", out) - self.assertEqual(result.returncode, 0, result.stderr) - self.assertTrue(out.is_file()) - self.assertTrue((self.root / "skinned" / "model.json").is_file()) - - def test_manifest_items_are_counted_without_guessing_bones(self): - manifest = pathlib.Path(self.temp.name) / "manifest.json" - write_json(manifest, { - "src": "synthetic", - "Count": 2, - "Items": [ - {"Name": "manifest_fragment.#ft", "File": "fragment.obj", "Verts": 25, - "Tris": 32, "IsFragment": True, "HasBoneBindings": True, - "Materials": [{"Shader": "B5D47C70", "Textures": []}]}, - {"Name": "manifest_drawable.#dr", "File": "drawable.obj", "Verts": 10, - "Tris": 4, "IsFragment": False, "HasBoneBindings": False, - "Materials": [{"Shader": "210FBC6A", - "Textures": [{"Id64": "AABBCCDDEEFF0011"}]}]}, - ], - }) - out = pathlib.Path(self.temp.name) / "manifest-report.json" - result = self.run_tool(manifest, "--json", out) - self.assertEqual(result.returncode, 0, result.stderr) - data = json.loads(out.read_text(encoding="utf-8")) - summary = data["summary"] - self.assertEqual(summary["models"], 2) - self.assertEqual(summary["vertices"], 35) - self.assertEqual(summary["triangles"], 36) - self.assertEqual(summary["malformed"], 0) - self.assertEqual(summary["skin_8"], 0) - self.assertEqual(summary["skin_unknown"], 1) - self.assertEqual(summary["by_kind"]["fragment"]["models"], 1) - self.assertEqual(summary["by_kind"]["drawable"]["models"], 1) - self.assertEqual(summary["by_shader"]["0xB5D47C70"]["vertices"], 25) - self.assertEqual(summary["by_shader"]["0x210FBC6A"]["vertices"], 10) - rows = self.by_name(data) - fragment = rows["manifest_fragment.#ft"] - self.assertEqual(fragment["kind"], "fragment") - self.assertIsNone(fragment["bones"]) - self.assertIsNone(fragment["skin_8"]) - drawable = rows["manifest_drawable.#dr"] - self.assertEqual(drawable["kind"], "drawable") - self.assertEqual(drawable["bones"], 0) - self.assertIs(drawable["skin_8"], False) - self.assertEqual(drawable["textures"], ["0xAABBCCDDEEFF0011"]) - - def test_manifest_models_list_resolves_paths(self): - manifest = self.root / "models.json" - write_json(manifest, {"models": ["skinned/model.json", {"path": "static/model.json"}]}) - out = pathlib.Path(self.temp.name) / "models-report.json" - result = self.run_tool(manifest, "--json", out) - self.assertEqual(result.returncode, 0, result.stderr) - data = json.loads(out.read_text(encoding="utf-8")) - self.assertEqual(data["summary"]["models"], 2) - self.assertEqual(data["summary"]["vertices"], 18) - self.assertEqual(data["summary"]["triangles"], 6) - self.assertEqual({row["name"] for row in data["models"]}, - {"synthetic_skinned", "synthetic_static"}) - self.assertTrue(all("models.json#" in row["source"] for row in data["models"])) - - def test_manifest_report_path_cannot_overwrite_a_referenced_model(self): - manifest = self.root / "models.json" - write_json(manifest, {"models": ["skinned/model.json", "static/model.json"]}) - target = self.root / "skinned" / "model.json" - before = target.read_text(encoding="utf-8") - result = self.run_tool(manifest, "--json", target) - self.assertEqual(result.returncode, 2, result.stderr) - self.assertIn("would overwrite the input", result.stderr) - self.assertEqual(target.read_text(encoding="utf-8"), before) - - def test_manifest_without_bone_binding_flag_reports_unknown(self): - with tempfile.TemporaryDirectory() as td: - manifest = pathlib.Path(td) / "manifest.json" - write_json(manifest, {"Items": [ - {"Name": "old_row.#dr", "Verts": 4, "Tris": 2, "IsFragment": False, - "Materials": [{"Shader": "12345678", "Textures": []}]}, - ]}) - out = pathlib.Path(td) / "report.json" - result = self.run_tool(manifest, "--json", out) - self.assertEqual(result.returncode, 0, result.stderr) - data = json.loads(out.read_text(encoding="utf-8")) - row = data["models"][0] - self.assertIsNone(row["bones"]) - self.assertIsNone(row["skin_8"]) - self.assertIn("HasBoneBindings is missing", row["issues"]) - self.assertEqual(data["summary"]["skin_unknown"], 1) - - def test_section_table_marks_eight_influence_without_mesh_field(self): - with tempfile.TemporaryDirectory() as td: - root = pathlib.Path(td) / "one" - write_json(root / "model.json", { - "name": "synthetic_sections", - "type": "dr", - "vertex_count": 3, - "triangle_count": 1, - "drawable": { - "models": [{"bone_palette": [1, 2]}], - "buffers": [{"mesh_blob": {"sections": [ - [6, 0x100, 0x26], [7, 0x110, 0x26], - [8, 0x120, 0x25], [9, 0x130, 0x25], - ]}}], - }, - "meshes": [{"name": "m", "vertex_count": 3, "triangle_count": 1, - "skinned": True}], - }) - out = pathlib.Path(td) / "report.json" - result = self.run_tool(root, "--json", out) - self.assertEqual(result.returncode, 0, result.stderr) - row = json.loads(out.read_text(encoding="utf-8"))["models"][0] - self.assertIs(row["skin_8"], True) - self.assertEqual(row["bones"], 2) - - def test_single_model_file_is_a_census(self): - target = self.root / "static" / "model.json" - out = pathlib.Path(self.temp.name) / "single.json" - result = self.run_tool(target, "--json", out) - self.assertEqual(result.returncode, 0, result.stderr) - data = json.loads(out.read_text(encoding="utf-8")) - self.assertEqual(data["summary"]["models"], 1) - self.assertEqual(data["models"][0]["name"], "synthetic_static") - - def test_model_json_saved_with_a_utf8_bom_is_read(self): - # A model.json saved by a Windows editor starts with a UTF-8 BOM. Read as plain utf-8, json.load refuses it - # ("Unexpected UTF-8 BOM"), and the census counted the model as unknown with an issue instead of reading it. - with tempfile.TemporaryDirectory() as tmp: - root = pathlib.Path(tmp) / "models" - model = root / "bom" / "model.json" - model.parent.mkdir(parents=True) - model.write_bytes(b"\xef\xbb\xbf" + json.dumps(static_model()).encode("utf-8")) - out = pathlib.Path(tmp) / "report.json" - result = self.run_tool(root, "--json", out) - self.assertEqual(result.returncode, 0, result.stderr) - data = json.loads(out.read_text(encoding="utf-8")) - self.assertEqual(data["summary"]["models"], 1) - row = data["models"][0] - self.assertEqual(row["name"], "synthetic_static") - self.assertEqual(row["issues"], []) - - def test_signed_and_underscore_hashes_are_not_hashes(self): - # Python's int(text, 16) accepts a sign and underscores; the documented grammar is hex digits only. - with tempfile.TemporaryDirectory() as tmp: - root = pathlib.Path(tmp) / "models" - model = { - "name": "synthetic_bad_hashes", - "type": "dr", - "vertex_count": 0, - "triangle_count": 0, - "materials": [ - {"shader_name_hash": "-1", "textures": [{"hash32": "+1"}]}, - {"shader_name_hash": "+1", "textures": [{"hash32": "12_34"}]}, - {"shader_name_hash": "12_34", "textures": [{"hash32": "-1"}]}, - ], - } - write_json(root / "bad" / "model.json", model) - out = pathlib.Path(tmp) / "report.json" - result = self.run_tool(root, "--json", out) - self.assertEqual(result.returncode, 0, result.stderr) - data = json.loads(out.read_text(encoding="utf-8")) - row = self.by_name(data)["synthetic_bad_hashes"] - self.assertEqual(row["shaders"], []) - self.assertEqual(row["textures"], []) - shader_issues = [i for i in row["issues"] if "is not an 8-digit shader hash" in i] - texture_issues = [i for i in row["issues"] if "is not a hexadecimal texture key" in i] - self.assertEqual(len(shader_issues), 3, row["issues"]) - self.assertEqual(len(texture_issues), 3, row["issues"]) - - def test_missing_target_is_a_clean_error(self): - result = self.run_tool(pathlib.Path(self.temp.name) / "absent") - self.assertEqual(result.returncode, 2) - self.assertIn("not found", result.stderr) - self.assertNotIn("Traceback", result.stderr) - - def test_unlistable_subfolder_is_a_clean_error_not_a_silent_undercount(self): - # os.walk skips a directory it cannot list unless onerror raises; the census used to report - # the remaining models and exit 0, hiding the incomplete scan. - sub = self.root / "static" - os.chmod(sub, 0o000) - try: - try: - os.listdir(sub) - self.skipTest("the sub-folder is still listable (running as root, or Windows)") - except OSError: - pass - result = self.run_tool(self.root) - self.assertEqual(result.returncode, 2, result.stderr) - self.assertIn("ERROR", result.stderr) - self.assertNotIn("Traceback", result.stderr) - finally: - os.chmod(sub, 0o755) - - def test_unlistable_subfolder_is_a_clean_error_when_chmod_is_not_enough(self): - # The chmod case above self-skips on Windows and as root, and CI only runs this file on - # windows-latest, so the guard went unexercised there. Forcing os.scandir to raise for one - # folder gives the same PermissionError os.walk hits for real, on every platform. - sub = self.root / "static" - real_scandir = os.scandir - locked = os.path.normcase(os.path.abspath(str(sub))) - - def scandir(path, *args, **kwargs): - if os.path.normcase(os.path.abspath(str(path))) == locked: - raise PermissionError(13, "Access is denied", str(path)) - return real_scandir(path, *args, **kwargs) - - err = io.StringIO() - out = io.StringIO() - with mock.patch.object(CC.os, "scandir", scandir): - with contextlib.redirect_stderr(err), contextlib.redirect_stdout(out): - code = CC.main([str(self.root)]) - self.assertEqual(code, 2, err.getvalue()) - self.assertIn("ERROR", err.getvalue()) - self.assertIn("cannot read", err.getvalue()) - self.assertIn(str(sub), err.getvalue()) - self.assertNotIn("Traceback", err.getvalue()) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/test_character_textures.py b/tests/test_character_textures.py deleted file mode 100644 index a5dccd6c0..000000000 --- a/tests/test_character_textures.py +++ /dev/null @@ -1,293 +0,0 @@ -"""character_textures.py on synthetic decoded model JSON. - -Run with ``python -I tests/test_character_textures.py``. Covers a head material (diffusetex + -bumptex), a garment material (speculartex only, must flag missing albedo), an unknown slot, the -JSON/CSV reports and the report-path guard. Every fixture is hand-written; no game data is used. -""" -import csv -import json -import pathlib -import subprocess -import sys -import tempfile -import unittest - -ROOT = pathlib.Path(__file__).resolve().parent.parent -TOOL = ROOT / "tools" / "character_textures.py" - - -def model(materials, name="synthetic_model"): - return {"Name": name, "Materials": materials} - - -def write_model(folder, document, name="model.json"): - folder = pathlib.Path(folder) - folder.mkdir(parents=True, exist_ok=True) - path = folder / name - path.write_text(json.dumps(document), encoding="utf-8") - return path - - -def run_tool(*args): - return subprocess.run([sys.executable, "-I", str(TOOL), *map(str, args)], - cwd=ROOT, capture_output=True, text=True, encoding="utf-8", - errors="replace", timeout=60) - - -HEADER = "model\tmaterial\tslot\trole\ttexture\tasset_key" - - -def table(output): - """The data rows of the tab-separated table (header and FLAG lines excluded).""" - return [line.split("\t") for line in output.splitlines() - if line.count("\t") == 5 and line != HEADER] - - -class CharacterTextureTests(unittest.TestCase): - def test_manifest_file_names_are_independent_of_the_export_host(self): - entries = [ - {"File": r"C:\exports\models\cap.v2.mesh", "Materials": [{}]}, - {"file": "models/shoes.mesh", "materials": [{}]}, - {"File": r"models\unused.mesh", "Name": "named", "Materials": [{}]}, - ] - with tempfile.TemporaryDirectory() as td: - path = write_model(td, {"Items": entries}) - report_path = pathlib.Path(td) / "report.json" - result = run_tool(path, "--json", report_path) - self.assertEqual(result.returncode, 0, result.stderr) - expected = ["cap.v2", "shoes", "named"] - self.assertEqual([row[0] for row in table(result.stdout)], expected) - report = json.loads(report_path.read_text(encoding="utf-8")) - self.assertEqual([m["name"] for m in report["models"]], expected) - - def test_head_material_reports_diffusetex_and_bumptex(self): - with tempfile.TemporaryDirectory() as td: - path = write_model(td, model([{ - "Name": "head", - "Shader": "a1b2c3d4", - "Textures": [ - {"Param": "0xC8E8C282", "Name": "face_diffusetex"}, - {"Param": "0x1E77BF4C", "Name": "face_bumptex"}, - ], - }])) - result = run_tool(path) - self.assertEqual(result.returncode, 0, result.stderr) - rows = {row[3]: row for row in table(result.stdout)} - self.assertEqual(rows["diffusetex"], [ - "synthetic_model", "head", "0xC8E8C282", "diffusetex", "face_diffusetex", "-"]) - self.assertEqual(rows["bumptex"], [ - "synthetic_model", "head", "0x1E77BF4C", "bumptex", "face_bumptex", "-"]) - self.assertNotIn("FLAG", result.stdout) - - def test_garment_without_albedo_is_flagged(self): - with tempfile.TemporaryDirectory() as td: - path = write_model(td, model([{ - "Name": "jacket", - "Shader": "D5ED50F4", - "Textures": [{"Param": "0xC6F46E79", "Name": "jacket_speculartex"}], - }])) - result = run_tool(path) - self.assertEqual(result.returncode, 0, result.stderr) - rows = table(result.stdout) - self.assertEqual(len(rows), 1, result.stdout) - self.assertEqual(rows[0][2:], ["0xC6F46E79", "speculartex", "jacket_speculartex", "-"]) - self.assertIn("FLAG garment-no-albedo", result.stdout) - self.assertIn("d5ed50f4", result.stdout) - self.assertIn("speculartex is not colour", result.stdout) - self.assertNotIn("diffusetex", result.stdout) - - def test_unknown_slot_is_not_guessed_from_its_name(self): - with tempfile.TemporaryDirectory() as td: - path = write_model(td, model([{ - "Name": "mystery", - "Shader": "a1b2c3d4", - "Textures": [{"Param": 0xDEADBEEF, "Name": "diffusetex"}], - }])) - result = run_tool(path) - self.assertEqual(result.returncode, 0, result.stderr) - rows = table(result.stdout) - self.assertEqual(rows[0][2], "0xDEADBEEF") - self.assertEqual(rows[0][3], "unknown 0xDEADBEEF") - self.assertEqual(rows[0][4], "diffusetex") - self.assertIn("unknown slots", result.stdout) - - def test_every_verified_slot_maps_to_its_name(self): - slots = { - "0xC8E8C282": "diffusetex", - "0xC6F46E79": "speculartex", - "0x1E77BF4C": "bumptex", - "0x739E3D0D": "speculartex2", - "0x8ADB8480": "materialid", - } - with tempfile.TemporaryDirectory() as td: - path = write_model(td, model([{ - "Name": "slots", - "Shader": "a1b2c3d4", - "Textures": [{"Param": slot, "Name": role} for slot, role in slots.items()], - }])) - result = run_tool(path) - self.assertEqual(result.returncode, 0, result.stderr) - self.assertEqual({row[2]: row[3] for row in table(result.stdout)}, slots) - self.assertFalse([row for row in table(result.stdout) if row[3].startswith("unknown")]) - - def test_missing_albedo_outside_a_garment_shader_is_not_flagged(self): - with tempfile.TemporaryDirectory() as td: - path = write_model(td, model([{ - "Name": "trim", - "Shader": "a1b2c3d4", - "Textures": [{"Param": "0x1E77BF4C", "Name": "trim_normal"}], - }]), name="model.json") - result = run_tool(path, "--json", pathlib.Path(td) / "report.json") - self.assertEqual(result.returncode, 0, result.stderr) - self.assertNotIn("garment-no-albedo", result.stdout) - report = json.loads((pathlib.Path(td) / "report.json").read_text(encoding="utf-8")) - material = report["models"][0]["materials"][0] - self.assertTrue(material["missing_albedo"]) - self.assertEqual(material["flags"], []) - - def test_json_and_csv_reports(self): - with tempfile.TemporaryDirectory() as td: - path = write_model(td, model([ - {"Name": "head", "Shader": "a1b2c3d4", "Textures": [ - {"Param": "C8E8C282", "Name": "face_diffusetex"}]}, - {"Name": "jacket", "Shader": "ea8d09d0", "Textures": [ - {"Param": "C6F46E79", "Name": "jacket_speculartex"}]}, - ])) - report_path = pathlib.Path(td) / "out" / "report.json" - csv_path = pathlib.Path(td) / "out" / "report.csv" - result = run_tool(path, "--json", report_path, "--csv", csv_path) - self.assertEqual(result.returncode, 0, result.stderr) - - report = json.loads(report_path.read_text(encoding="utf-8")) - self.assertEqual(report["summary"]["materials"], 2) - self.assertEqual(report["summary"]["bindings"], 2) - self.assertEqual(report["summary"]["garment_without_albedo"], 1) - head, jacket = report["models"][0]["materials"] - self.assertEqual(head["bindings"][0]["role"], "diffusetex") - self.assertTrue(jacket["garment"]) - self.assertTrue(jacket["missing_albedo"]) - self.assertEqual(jacket["flags"], ["garment-no-albedo"]) - self.assertTrue(report["warnings"][0].startswith("garment-no-albedo")) - - data = csv_path.read_bytes() - self.assertNotIn(b"\r", data) - lines = data.decode("utf-8").splitlines() - self.assertEqual(lines[0], "source,model,material,shader,slot,role,texture,flags,asset_key") - self.assertIn(",head,a1b2c3d4,0xC8E8C282,diffusetex,face_diffusetex,", lines[1]) - self.assertIn(",jacket,ea8d09d0,0xC6F46E79,speculartex,jacket_speculartex,garment-no-albedo", - lines[2]) - - def test_shared_name_hash_preserves_distinct_asset_keys_in_each_report(self): - name_hash = "12345678" - keys = ["0000000112345678", "FEDCBA9812345678"] - refs = [{"Param": "C8E8C282", "TextureIndex": i, "Name": name_hash, "Id64": key} - for i, key in enumerate(keys)] - refs.append({"Param": "C8E8C282", "Name": name_hash}) - with tempfile.TemporaryDirectory() as td: - path = write_model(td, {"Items": [model([{"Textures": refs}, {"Textures": []}])]}) - report_path, csv_path = pathlib.Path(td) / "report.json", pathlib.Path(td) / "report.csv" - result = run_tool(path, "--json", report_path, "--csv", csv_path) - self.assertEqual(result.returncode, 0, result.stderr) - - self.assertEqual(result.stdout.splitlines()[0], HEADER) - self.assertEqual([row[4:] for row in table(result.stdout)], - [[name_hash, key] for key in [*keys, "-"]] + [["-", "-"]]) - report = json.loads(report_path.read_text(encoding="utf-8")) - bindings = report["models"][0]["materials"][0]["bindings"] - expected = [(name_hash, key) for key in [*keys, None]] - self.assertEqual([(b["texture"], b["asset_key"]) for b in bindings], expected) - self.assertEqual([(r["texture"], r["asset_key"]) for r in report["rows"]], expected + [("-", None)]) - with csv_path.open(encoding="utf-8", newline="") as f: - self.assertEqual([(r["texture"], r["asset_key"]) for r in csv.DictReader(f)], - [(name_hash, key) for key in [*keys, ""]] + [("-", "")]) - - def test_asset_key_requires_an_explicit_64_bit_identity(self): - refs = [{"id64": "0xfedcba9876543210"}, {"AssetKey": 0}, {"asset_key": 2**64 - 1}, - {"Id64": "12345678"}, {"Id64": 2**64}, {"Id64": True}, - {"Key": "1234567800000001"}, "1234567800000002"] - with tempfile.TemporaryDirectory() as td: - path = write_model(td, model([{"Textures": refs}])) - report_path = pathlib.Path(td) / "report.json" - result = run_tool(path, "--json", report_path) - self.assertEqual(result.returncode, 0, result.stderr) - rows = json.loads(report_path.read_text(encoding="utf-8"))["rows"] - self.assertEqual([r["asset_key"] for r in rows], - ["FEDCBA9876543210", "0000000000000000", "FFFFFFFFFFFFFFFF"] + [None] * 5) - - def test_directory_is_searched_recursively(self): - with tempfile.TemporaryDirectory() as td: - write_model(pathlib.Path(td) / "a" / "b", model([{ - "Name": "head", "Shader": "a1b2c3d4", - "Textures": [{"Param": "0xC8E8C282", "Name": "face"}]}], name="first")) - write_model(pathlib.Path(td) / "c", model([{ - "Name": "jacket", "Shader": "39ddb9ca", - "Textures": [{"Param": "0xC6F46E79", "Name": "spec"}]}], name="second")) - result = run_tool(td) - self.assertEqual(result.returncode, 0, result.stderr) - self.assertIn("first", result.stdout) - self.assertIn("second", result.stdout) - self.assertEqual(result.stdout.count("FLAG garment-no-albedo"), 1) - - def test_json_cannot_overwrite_an_input(self): - with tempfile.TemporaryDirectory() as td: - path = write_model(td, model([{"Name": "head", "Shader": "a1b2c3d4", "Textures": []}])) - before = path.read_bytes() - result = run_tool(path, "--json", path) - self.assertEqual(result.returncode, 2, result.stderr) - self.assertIn("would overwrite the input", result.stderr) - self.assertEqual(path.read_bytes(), before) - - def test_csv_cannot_overwrite_an_input(self): - with tempfile.TemporaryDirectory() as td: - path = write_model(td, model([{"Name": "head", "Shader": "a1b2c3d4", "Textures": []}])) - before = path.read_bytes() - result = run_tool(path, "--csv", path) - self.assertEqual(result.returncode, 2, result.stderr) - self.assertIn("would overwrite the input", result.stderr) - self.assertEqual(path.read_bytes(), before) - - def test_json_and_csv_must_use_different_paths(self): - with tempfile.TemporaryDirectory() as td: - path = write_model(td, model([{"Name": "head", "Shader": "a1b2c3d4", "Textures": []}])) - out = pathlib.Path(td) / "report.bin" - result = run_tool(path, "--json", out, "--csv", out) - self.assertEqual(result.returncode, 2, result.stderr) - self.assertIn("must use different paths", result.stderr) - - def test_unlistable_subfolder_is_an_error_not_a_silent_skip(self): - import io - from unittest import mock - import importlib.util - spec = importlib.util.spec_from_file_location("ct_under_test", TOOL) - mod = importlib.util.module_from_spec(spec) - spec.loader.exec_module(mod) - with tempfile.TemporaryDirectory() as td: - write_model(pathlib.Path(td) / "a", model([{"Name": "m", "Materials": []}])) - orig_walk = mod.os.walk - def fail_walk(top, *args, **kwargs): - if "onerror" in kwargs and kwargs["onerror"]: - kwargs["onerror"](PermissionError(13, "Permission denied")) - return orig_walk(top, *args, **kwargs) - with mock.patch.object(mod.os, "walk", side_effect=fail_walk): - with mock.patch.object(sys, "argv", ["character_textures.py", td]): - with mock.patch("sys.stderr", new_callable=io.StringIO) as err: - code = mod.main() - self.assertEqual(code, 2) - self.assertIn("ERROR:", err.getvalue()) - self.assertIn("Permission denied", err.getvalue()) - - def test_unwritable_report_path_exits_2_without_traceback(self): - with tempfile.TemporaryDirectory() as td: - write_model(pathlib.Path(td) / "a", model([{"Name": "m", "Materials": []}])) - blocker = pathlib.Path(td) / "file_parent" - blocker.write_text("x", encoding="utf-8") - bad_json = blocker / "out.json" - proc = subprocess.run([sys.executable, "-I", TOOL, td, "--json", str(bad_json)], - capture_output=True, text=True) - self.assertEqual(proc.returncode, 2, proc.stderr) - self.assertNotIn("Traceback", proc.stderr) - self.assertIn("ERROR: cannot write", proc.stderr) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/test_check_apt_key.py b/tests/test_check_apt_key.py deleted file mode 100644 index 3b25a9d33..000000000 --- a/tests/test_check_apt_key.py +++ /dev/null @@ -1,148 +0,0 @@ -"""scripts/check_apt_key.py accepts only the pinned key, and the workflows check every apt key they fetch. - - python -I tests/test_check_apt_key.py - -GnuPG is stood in for by a small Python program that prints the `--with-colons` listing written in each test's "key -file", so the tests run anywhere without a real key or gpg: the one key, another key, two primary keys, a primary key -with subkeys, a file gpg can't read. The workflows are read as text: every `.key`/`.gpg`/`.asc` URL they fetch must go -to a temporary file that `scripts/check_apt_key.py` checks before anything installs it. Standard library only. -""" -import os -import re -import shutil -import subprocess -import sys -import tempfile -import unittest - -ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) -sys.path.insert(0, os.path.join(ROOT, "scripts")) -import check_apt_key # noqa: E402 - -SCRIPT = os.path.join(ROOT, "scripts", "check_apt_key.py") -WINEHQ = "D43F640145369C51D786DDEA76F1A20FF987672F" -LLVM = "6084F3CF814B57C1CF12EFD515CF4D18AF4F7421" - -# A stand-in for `gpg --batch --show-keys --with-colons FILE`: prints FILE, or fails like gpg on a file starting "junk". -FAKE_GPG = """import sys -data = open(sys.argv[-1], encoding="utf-8").read() -if data.startswith("junk"): - sys.stderr.write("gpg: no valid OpenPGP data found.\\n") - sys.exit(2) -sys.stdout.write(data) -""" - - -def listing(*keys): - """`--with-colons` text for primary keys, each (fingerprint, [subkey fingerprints]).""" - lines = [] - for primary, subkeys in keys: - lines += [f"pub:-:3072:1:{primary[-16:]}:1544460984:::-:::scESC::::::23::0:", - f"fpr:::::::::{primary}:", - "uid:-::::1544461093::0000::Example ::::::::::0:"] - for sub in subkeys: - lines += [f"sub:-:3072:1:{sub[-16:]}:1544460984::::::e::::::23:", f"fpr:::::::::{sub}:"] - return "\n".join(lines) + "\n" - - -class PrimaryFingerprints(unittest.TestCase): - def test_one_key_with_subkeys(self): - sub = "9CDD4BB7ED8C37C95FFF34F1DDB25B3BE89767D6" - self.assertEqual(check_apt_key.primary_fingerprints(listing((WINEHQ, [sub]))), [WINEHQ]) - - def test_two_primary_keys(self): - self.assertEqual(check_apt_key.primary_fingerprints(listing((WINEHQ, []), (LLVM, []))), [WINEHQ, LLVM]) - - def test_nothing(self): - self.assertEqual(check_apt_key.primary_fingerprints(""), []) - - def test_normalize(self): - self.assertEqual(check_apt_key.normalize("d43f 6401 4536 9c51 d786 ddea 76f1 a20f f987 672f"), WINEHQ) - for bad in ("", "D43F", WINEHQ + "00", "G" * 40): - self.assertIsNone(check_apt_key.normalize(bad), bad) - - -class CheckWithStandInGpg(unittest.TestCase): - def setUp(self): - self.dir = tempfile.mkdtemp() - self.addCleanup(shutil.rmtree, self.dir) - fake = os.path.join(self.dir, "fake_gpg.py") - with open(fake, "w", encoding="utf-8", newline="\n") as f: - f.write(FAKE_GPG) - self.gpg = (sys.executable, "-I", fake) - - def key(self, text): - path = os.path.join(self.dir, f"key{len(os.listdir(self.dir))}.asc") - with open(path, "w", encoding="utf-8", newline="\n") as f: - f.write(text) - return path - - def test_the_pinned_key_passes(self): - self.assertIsNone(check_apt_key.check(self.key(listing((WINEHQ, ["9CDD4BB7ED8C37C95FFF34F1DDB25B3BE89767D6"]))), - WINEHQ, self.gpg)) - - def test_another_key_fails(self): - problem = check_apt_key.check(self.key(listing((LLVM, []))), WINEHQ, self.gpg) - self.assertIn(f"is key {LLVM}, expected {WINEHQ}", problem) - - def test_a_second_primary_key_fails(self): - problem = check_apt_key.check(self.key(listing((WINEHQ, []), (LLVM, []))), WINEHQ, self.gpg) - self.assertIn("holds 2 primary keys", problem) - - def test_no_key_fails(self): - self.assertIn("holds no public key", check_apt_key.check(self.key(""), WINEHQ, self.gpg)) - - def test_unreadable_file_fails(self): - problem = check_apt_key.check(self.key("junk"), WINEHQ, self.gpg) - self.assertIn("could not read", problem) - self.assertIn("no valid OpenPGP data", problem) - - def test_missing_gpg_fails(self): - problem = check_apt_key.check(self.key(listing((WINEHQ, []))), WINEHQ, - (os.path.join(self.dir, "no-such-gpg"),)) - self.assertIsNotNone(problem) - - -class CommandLine(unittest.TestCase): - def run_script(self, *args): - return subprocess.run([sys.executable, "-I", SCRIPT, *args], capture_output=True, text=True) - - def test_usage_errors(self): - self.assertEqual(self.run_script().returncode, 2) - self.assertEqual(self.run_script(__file__, "not-a-fingerprint").returncode, 2) - - def test_missing_file(self): - result = self.run_script(os.path.join(ROOT, "no-such.key"), WINEHQ) - self.assertEqual(result.returncode, 1) - self.assertIn("no such key file", result.stderr) - - -class Workflows(unittest.TestCase): - """Every apt key a workflow downloads is checked by check_apt_key.py before it is installed.""" - - KEY_URL = re.compile(r"https://\S+?\.(?:key|gpg|asc)\b") - - def test_every_fetched_key_is_checked_first(self): - folder = os.path.join(ROOT, ".github", "workflows") - fetched = 0 - for name in sorted(os.listdir(folder)): - if not name.endswith((".yml", ".yaml")): - continue - with open(os.path.join(folder, name), encoding="utf-8") as f: - lines = f.read().splitlines() - for n, line in enumerate(lines): - if not self.KEY_URL.search(line) or not re.search(r"\b(curl|wget)\b", line): - continue - fetched += 1 - where = f"{name}:{n + 1}" - with self.subTest(where=where): - self.assertNotIn("|", line.split("#")[0], f"{where} pipes a key straight into a command") - self.assertNotRegex(line, r"/etc/apt|/usr/share/keyrings", f"{where} downloads into apt's keyrings") - following = "\n".join(lines[n + 1:n + 4]) - self.assertRegex(following, r"scripts/check_apt_key\.py \"?\$\w+\"? [0-9A-F]{40}\b", - f"{where}: the key isn't checked by scripts/check_apt_key.py right after") - self.assertGreaterEqual(fetched, 2, "expected the WineHQ and apt.llvm.org key downloads") - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/test_check_d3d12_trace.py b/tests/test_check_d3d12_trace.py deleted file mode 100644 index 0fcc951ea..000000000 --- a/tests/test_check_d3d12_trace.py +++ /dev/null @@ -1,97 +0,0 @@ -"""Run runtime/test/check_d3d12_trace.py through a fake runner, without a Windows build.""" -import os -from pathlib import Path -import subprocess -import sys -import tempfile -import time -import unittest - - -ROOT = Path(__file__).resolve().parents[1] -CHECK = ROOT / "runtime" / "test" / "check_d3d12_trace.py" - -COMMAND_LIST_TRACE = [ - "ID3D12GraphicsCommandList::SetPipelineState called", - "ID3D12GraphicsCommandList::SetGraphicsRootSignature called", - "ID3D12GraphicsCommandList::SetMarker called", - "ID3D12GraphicsCommandList3::SetProtectedResourceSession unsupported", - "ID3D12GraphicsCommandList3::SetProtectedResourceSession unsupported", - "ID3D12GraphicsCommandList::Close ok", - "ID3D12GraphicsCommandList::Close failed", - "ID3D12GraphicsCommandList::Reset ok", - "ID3D12GraphicsCommandList::SetDescriptorHeaps called", - "ID3D12GraphicsCommandList::SetGraphicsRootDescriptorTable called", - "ID3D12GraphicsCommandList::SetComputeRootSignature called", - "ID3D12GraphicsCommandList::Dispatch called", - "ID3D12GraphicsCommandList::DrawInstanced called", - "ID3D12GraphicsCommandList::DrawIndexedInstanced called", - "ID3D12GraphicsCommandList::Close failed", -] - - -class CheckD3D12TraceRunnerTests(unittest.TestCase): - def setUp(self): - directory = tempfile.TemporaryDirectory() - self.addCleanup(directory.cleanup) - self.cwd = Path(directory.name) - - def check(self, runner_source: str, runner_timeout: int = 20) -> subprocess.CompletedProcess: - (self.cwd / "runner.py").write_text(runner_source, encoding="utf-8", newline="\n") - # Shorten the runner limit without touching the script: run its main() with RUNNER_TIMEOUT replaced. - launch = ("import runpy, sys; timeout = int(sys.argv.pop(1)); script = sys.argv.pop(1); sys.argv[0] = script; " - "main = runpy.run_path(script)['main']; main.__globals__['RUNNER_TIMEOUT'] = timeout; main()") - return subprocess.run( - [sys.executable, "-I", "-B", "-c", launch, str(runner_timeout), str(CHECK), "fixture.exe", - f"--runner={sys.executable}", "--runner=-I", "--runner=runner.py"], - cwd=self.cwd, capture_output=True, text=True, timeout=60, - ) - - def test_trace_through_runner(self): - lines = "".join(f"[d3d12-trace] #{n} {entry}\\n" for n, entry in enumerate(COMMAND_LIST_TRACE, 1)) - result = self.check( - "import sys\n" - "assert sys.argv[1] == 'fixture.exe', sys.argv\n" - f"if '--trace-d3d12' in sys.argv[2:]:\n sys.stderr.write('{lines}')\n" - ) - self.assertEqual(result.returncode, 0, result.stderr) - self.assertIn(f"D3D12 trace verified with {len(COMMAND_LIST_TRACE)} ordered entries", result.stdout) - - def test_failing_fixture_reports_its_output(self): - result = self.check("import sys\nprint('fixture output')\nsys.exit(3)\n") - self.assertEqual(result.returncode, 1) - self.assertIn("fixture.exe exited with 3", result.stderr) - self.assertIn("fixture output", result.stderr) - - @unittest.skipUnless(os.name == "posix", "requires POSIX process groups and flock") - def test_runner_timeout_stops_the_fixture_it_started(self): - import fcntl - - # Like a Wine launcher: the fixture runs in a child that holds the output pipes and outlives the limit. - result = self.check( - "import subprocess, sys, time\n" - "child = subprocess.Popen([sys.executable, '-c', " - "'import fcntl, sys, time; lock = open(\"fixture.lock\", \"w\"); fcntl.flock(lock, fcntl.LOCK_EX); " - "print(\"fixture ready\", flush=True); time.sleep(60)'], stdout=subprocess.PIPE)\n" - "child.stdout.readline()\n" - "time.sleep(60)\n", - runner_timeout=2, - ) - self.assertEqual(result.returncode, 1, result.stderr) - self.assertIn("fixture.exe: no exit within 2s", result.stderr) - self.assertNotIn("Traceback", result.stderr) - # The lock is released once the fixture exits, even while its PID is still a zombie. - with (self.cwd / "fixture.lock").open("r+") as lock: - deadline = time.monotonic() + 2 - while True: - try: - fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB) - break - except BlockingIOError: - if time.monotonic() >= deadline: - self.fail("the fixture outlived the runner timeout") - time.sleep(0.02) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/test_check_no_game_data.py b/tests/test_check_no_game_data.py deleted file mode 100644 index de35ccdea..000000000 --- a/tests/test_check_no_game_data.py +++ /dev/null @@ -1,326 +0,0 @@ -"""scripts/check_no_game_data.py catches game-data magics under any file name. - - python -I tests/test_check_no_game_data.py - -Every input is a few hand-written header bytes in a temporary directory (no game files): each format under a harmless -name, files that must pass (text, PNG, a lone "MZ", magics past the start), and the default mode over a throwaway git -repository. The script runs as itself, through its own command line. -""" -import bz2 -import contextlib -import errno -import gzip -import importlib.util -import io -import lzma -import os -import shutil -import stat -import subprocess -import sys -import tempfile -import tarfile -import unittest -import zipfile -from unittest import mock - -ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) -SCRIPT = os.path.join(ROOT, "scripts", "check_no_game_data.py") - - -def pe_header(e_lfanew=0x80): - head = bytearray(e_lfanew + 4) - head[0:2] = b"MZ" - head[0x3C:0x40] = e_lfanew.to_bytes(4, "little") - head[e_lfanew:e_lfanew + 4] = b"PE\0\0" - return bytes(head) - - -# file name (deliberately not the format's extension), contents, format the script must report -CAUGHT = [ - ("archive.bin", b"9FPR" + bytes(12), "RPF9 archive"), - ("pool.dat", b"TTPF" + bytes(12), "TTPF texture pool"), - ("resource.dat", b"RSC8" + bytes(12), "RAGE resource"), - ("page.dat", b"0DRP" + bytes(12), "RAGE page directory"), - ("tree.dat", b"RBF0" + bytes(12), "RBF0 tree"), - ("shader.txt", b"XBCH" + (3).to_bytes(4, "little") + bytes(8), "XBCH shader container"), - ("shader2.txt", b"FSSM" + bytes(12), "FSSM shader"), - ("container.txt", b"DXBC" + bytes(12), "DXBC container"), - ("module.txt", bytes.fromhex("03022307") + bytes(12), "SPIR-V module"), - ("module_be.txt", bytes.fromhex("07230203") + bytes(12), "SPIR-V module"), - ("texture.png.txt", b"DDS " + (124).to_bytes(4, "little") + bytes(8), "DDS texture"), - ("bank.json", b"ADAT" + bytes(12), "AWC audio bank"), - ("music.md", b"OggS\0\x02" + bytes(10), "Ogg stream"), - ("sound.csv", b"RIFF" + bytes(4) + b"WAVEfmt ", "RIFF WAVE audio"), - ("movie.txt", b"KB2j" + bytes(12), "Bink 2 video"), - ("model.json", b"glTF" + (2).to_bytes(4, "little") + bytes(8), "glTF binary"), - ("game.txt", pe_header(), "PE executable"), - ("far_pe.txt", pe_header(0x400), "PE executable"), - # e_lfanew around the end of the first bytes read (0x208): before, straddling and after it - *((f"pe_{n}.txt", pe_header(n), "PE executable") for n in range(0x204, 0x20A)), - ("pe_1mib.txt", pe_header(1 << 20), "PE executable"), - ("pe_1mib_plus.txt", pe_header((1 << 20) + 4), "PE executable"), - ("image.bin", bytes(0x200) + b"msft-xvd" + bytes(8), "XVD image"), - ("container2.dat", b"PSIN" + bytes(12), "PSIN metadata container"), - ("heightmap.dat", b"PAMH" + bytes(12), "PAMH heightmap"), - ("heightmap2.dat", b"MHIU" + bytes(12), "MHIU heightmap"), - ("presets.dat", b"SPS1" + bytes(12), "SPS1 shader-preset table"), - ("effects.dat", b"SGD5" + bytes(12), "SGD5 effects database"), - ("texcontainer.dat", b"RDS5" + bytes(12), "RDS5 texture container"), - ("bank2.json", b"AWC\x00" + bytes(12), "AWC audio bank"), - ("script.lol", b"YSC\x00" + bytes(12), "YSC compiled script"), - ("anim.bin", b"MoVE" + (19).to_bytes(4, "little") + bytes(8), "MoVE animation container"), - ("bones.dat", b"SKEL_" + b"SKEL_Head\x00" + bytes(8), "SKEL_ bone table"), - ("script2.lol", b"SCRP" + bytes(12), "SCRP compiled script"), - ("story_save.txt", b"JSAV" + (3).to_bytes(4, "little") + bytes(8), "JSAV story save"), - ("profile.json", b"ASAV" + (1).to_bytes(4, "little") + bytes(8), "ASAV save record"), - ("chives.txt", b"SLAYER1\0" + bytes(8), "SLAYER1 packed save"), - ("chunk.json", b"LPK1" + (2).to_bytes(4, "little") + b"[]", "LPK1 world staging pack"), -] - -PASSED = [ - ("README.md", b"# Notes\n\nThe RPF9 magic is stored as 9FPR; DDS files start with 'DDS '.\n"), - ("logo.png", b"\x89PNG\r\n\x1a\n" + bytes(16)), - ("mz.txt", b"MZ is not enough on its own\n"), - ("metadata.txt", b"METADATA ADAT later in the line\n"), - ("bones.md", b"# SKEL_HEAD, MoVE and SCRP name formats; none of them starts this file\n"), - ("riff.bin", b"RIFF" + bytes(4) + b"AVI LIST"), - ("saves.md", b"# Saves\n\nA story save starts with JSAV, a profile with ASAV, its packed copy with SLAYER1.\n"), - ("slayer.txt", b"SLAYER1 without the zero byte after it is just a word\n"), - ("empty.txt", b""), - ("mz_past_end.txt", pe_header(0x80)[:0x40]), # e_lfanew points past the end of the file - ("mz_cut_signature.txt", pe_header(0x300)[:-2]), # only "PE" of the signature is there - ("mz_not_pe.txt", pe_header(0x80)[:-4] + b"NE\0\0"), -] - - -def rmtree(path): - """shutil.rmtree that also removes read-only files (Git's objects on Windows).""" - def retry(func, p, _): - os.chmod(p, stat.S_IWRITE) - func(p) - if sys.version_info >= (3, 12): - shutil.rmtree(path, onexc=retry) - else: - shutil.rmtree(path, onerror=retry) - - -def zipped(members): - """A zip archive (bytes) holding `members`, {name: bytes}.""" - buf = io.BytesIO() - with zipfile.ZipFile(buf, "w", zipfile.ZIP_DEFLATED) as z: - for name, data in members.items(): - z.writestr(name, data) - return buf.getvalue() - - -def tarred(members): - """A tar archive (bytes) holding `members`, {name: bytes}.""" - buf = io.BytesIO() - with tarfile.open(fileobj=buf, mode="w") as t: - for name, data in members.items(): - info = tarfile.TarInfo(name) - info.size = len(data) - t.addfile(info, io.BytesIO(data)) - return buf.getvalue() - - -def corrupt_deflate(archive): - """`archive` (one deflated zip member) with the first byte of its deflate data made an invalid block type.""" - data = bytearray(archive) - name_len, extra_len = int.from_bytes(data[26:28], "little"), int.from_bytes(data[28:30], "little") - data[30 + name_len + extra_len] = 0xFF # BTYPE 11: zlib.error "invalid block type" - return bytes(data) - - -DDS = b"DDS " + (124).to_bytes(4, "little") + bytes(8) -FSSM = b"FSSM" + bytes(12) -RPF = b"9FPR" + bytes(12) - -# file name, contents, the line the script must print after ": " -CAUGHT_IN_ARCHIVES = [ - ("notes.zip.txt", zipped({"readme.txt": b"text\n", "tex/a.png": DDS}), "DDS texture in zip archive (tex/a.png)"), - ("data.bin", gzip.compress(FSSM), "FSSM shader in gzip stream"), - ("tool.bin", bz2.compress(pe_header()), "PE executable in bzip2 stream"), - ("pack.bin", lzma.compress(RPF), "RPF9 archive in xz stream"), - ("far.bin", gzip.compress(pe_header(0x400)), "PE executable in gzip stream"), - ("nested.bin", gzip.compress(zipped({"inner/x.bin": RPF})), "RPF9 archive in zip archive (inner/x.bin) in gzip stream"), - ("a.bin", b"7z\xbc\xaf\x27\x1c" + bytes(26), "7-Zip archive (contents can't be checked)"), - ("b.bin", b"\x28\xb5\x2f\xfd" + bytes(12), "Zstandard stream (contents can't be checked)"), - ("c.bin", b"Rar!\x1a\x07\x01\x00" + bytes(8), "RAR archive (contents can't be checked)"), - ("broken.bin", b"PK\x03\x04" + bytes(40), "zip archive that can't be opened (contents can't be checked)"), - ("broken.gz", b"\x1f\x8b\x09\x00" + bytes(12), "gzip stream that can't be opened (contents can't be checked)"), - # broken.gz names compression method 9, which isn't deflate; deep.bin is a DDS under four gzip layers - ("corrupt.gz", gzip.compress(DDS)[:12] + b"\xff" * 12, - "gzip stream that can't be opened (contents can't be checked)"), - ("deep.bin", gzip.compress(gzip.compress(gzip.compress(gzip.compress(DDS)))), - "gzip stream nested more than 3 deep (contents can't be checked) in gzip stream in gzip stream in gzip stream"), - # Review of #4040: tar archives, zips with bytes in front, a corrupt deflate stream, a newline in a member name. - ("x.tar", tarred({"x.dds": DDS}), "DDS texture in tar archive (x.dds)"), - ("x.tar.gz", gzip.compress(tarred({"a.txt": b"text\n", "y.bin": FSSM})), - "FSSM shader in tar archive (y.bin) in gzip stream"), - ("x.tar.xz", lzma.compress(tarred({"z.bin": RPF})), "RPF9 archive in tar archive (z.bin) in xz stream"), - ("prefixed.txt", b"JUNK" + zipped({"a.png": DDS}), "DDS texture in zip archive (a.png)"), - ("sfx.exe.txt", b"#!/bin/sh\nexit 0\n" + zipped({"b.bin": RPF}), "RPF9 archive in zip archive (b.bin)"), - ("nested_prefixed.zip", zipped({"inner.bin": bytes(8) + zipped({"x.bin": RPF})}), - "RPF9 archive in zip archive (x.bin) in zip archive (inner.bin)"), - ("bad_deflate.zip", corrupt_deflate(zipped({"a.bin": DDS * 64})), - "zip archive that can't be opened (contents can't be checked)"), - ("newline.zip", zipped({"a\nb.png": DDS}), "DDS texture in zip archive (a?b.png)"), -] - -PASSED_ARCHIVES = [ - ("docs.zip", zipped({"a.txt": b"plain text\n", "dir/b.md": b"# notes\n", "empty.txt": b""})), - ("docs.tar", tarred({"a.txt": b"plain text\n"})), - ("docs.tar.bz2", bz2.compress(tarred({"a.txt": b"plain text\n"}))), - ("prefixed_clean.bin", b"JUNK" + zipped({"a.txt": b"text\n"})), - ("notes.gz", gzip.compress(b"The RPF9 magic is stored as 9FPR.\n")), - ("notes.bz2", bz2.compress(b"plain text\n")), - ("notes.xz", lzma.compress(b"plain text\n")), - ("nested_clean.gz", gzip.compress(zipped({"a.txt": b"text\n"}))), -] - - -def run(args, cwd=None): - return subprocess.run([sys.executable, "-I", SCRIPT, *args], cwd=cwd, capture_output=True, text=True) - - -class CheckNoGameData(unittest.TestCase): - def setUp(self): - self.dir = tempfile.mkdtemp() - self.addCleanup(rmtree, self.dir) - - def write(self, name, data): - path = os.path.join(self.dir, name) - with open(path, "wb") as f: - f.write(data) - return path - - def test_each_format_is_caught_under_another_name(self): - for name, data, fmt in CAUGHT: - with self.subTest(name=name): - result = run([self.write(name, data)]) - self.assertEqual(result.returncode, 1, result.stdout + result.stderr) - self.assertIn(f"{name}: {fmt}", result.stdout) - - def test_game_data_inside_archives_is_caught(self): - for name, data, line in CAUGHT_IN_ARCHIVES: - with self.subTest(name=name): - result = run([self.write(name, data)]) - self.assertEqual(result.returncode, 1, result.stdout + result.stderr) - self.assertIn(f"{name}: {line}", result.stdout) - - def test_decompression_is_bounded(self): - # A gzip of 65 MiB of zeros (about 64 KiB on disk) holding a zip: past the 64 MiB budget, reported, not read - # to the end; and a zip with more members than the budget lists. - bomb = io.BytesIO() - with gzip.GzipFile(fileobj=bomb, mode="wb") as g: - g.write(b"PK\x03\x04") - chunk = bytes(1 << 20) - for _ in range(65): - g.write(chunk) - many = io.BytesIO() - with zipfile.ZipFile(many, "w", zipfile.ZIP_STORED) as z: - for i in range(10001): - z.writestr(f"{i}.txt", b"") - for name, data, kind in [("bomb.gz", bomb.getvalue(), "gzip stream"), ("many.zip", many.getvalue(), "zip archive")]: - with self.subTest(name=name): - result = run([self.write(name, data)]) - self.assertEqual(result.returncode, 1, result.stdout + result.stderr) - self.assertIn(f"{name}: {kind} too large to check", result.stdout) - - def test_archives_of_ordinary_files_pass(self): - paths = [self.write(name, data) for name, data in PASSED_ARCHIVES] - result = run(paths) - self.assertEqual(result.returncode, 0, result.stdout + result.stderr) - self.assertEqual(result.stdout, "") - - def test_ordinary_files_pass(self): - paths = [self.write(name, data) for name, data in PASSED] - result = run(paths) - self.assertEqual(result.returncode, 0, result.stdout + result.stderr) - self.assertEqual(result.stdout, "") - - def test_reports_every_match_among_clean_files(self): - clean = self.write("README.md", b"# fine\n") - bad1 = self.write("a.bin", b"DDS " + bytes(12)) - bad2 = self.write("b.bin", b"OggS" + bytes(12)) - result = run([clean, bad1, bad2]) - self.assertEqual(result.returncode, 1) - self.assertEqual(len(result.stdout.splitlines()), 2, result.stdout) - self.assertIn("2 file(s)", result.stderr) - - def test_directories_and_missing_paths_are_skipped(self): - os.mkdir(os.path.join(self.dir, "sub")) - result = run([os.path.join(self.dir, "sub"), os.path.join(self.dir, "missing.bin")]) - self.assertEqual(result.returncode, 0, result.stdout + result.stderr) - - def run_with_unreadable(self, locked, paths): - """main() in this process with open() refusing `locked`; (exit status, stdout, stderr).""" - spec = importlib.util.spec_from_file_location("check_no_game_data_under_test", SCRIPT) - module = importlib.util.module_from_spec(spec) - spec.loader.exec_module(module) - real_open = open - - def refusing_open(file, *args, **kwargs): - if os.fspath(file) == locked: - raise PermissionError(errno.EACCES, "Permission denied", locked) - return real_open(file, *args, **kwargs) - - out, err = io.StringIO(), io.StringIO() - with mock.patch("builtins.open", refusing_open), \ - contextlib.redirect_stdout(out), contextlib.redirect_stderr(err): - rc = module.main(paths) - return rc, out.getvalue(), err.getvalue() - - def test_unreadable_file_is_one_stderr_line_and_exit_2(self): - locked = self.write("locked.bin", b"plain text\n") - sibling = self.write("sibling.bin", b"DDS " + bytes(12)) - clean = self.write("README.md", b"# fine\n") - rc, out, err = self.run_with_unreadable(locked, [locked, clean]) - self.assertEqual(rc, 2, out + err) - self.assertEqual(out, "") - self.assertEqual(len(err.splitlines()), 1, err) - self.assertTrue(err.startswith("check_no_game_data: cannot read "), err) - self.assertIn("locked.bin: Permission denied", err) - self.assertNotIn("Traceback", err) - - # the other files are still scanned; a real match wins over the unreadable one - rc, out, err = self.run_with_unreadable(locked, [locked, sibling, clean]) - self.assertEqual(rc, 1, out + err) - # display() reports the path relative to the working directory and keeps the absolute path when the two are - # on different drives: a Windows temp file is on C: while the checkout is on D:. - try: - expected = os.path.relpath(sibling) - except ValueError: - expected = sibling - self.assertEqual(out.splitlines(), [f"{expected}: DDS texture"], out) - self.assertIn("cannot read", err) - self.assertIn("1 file(s) start like game data", err) - self.assertNotIn("Traceback", err) - - pe = self.write("pe.bin", pe_header()) - rc, out, err = self.run_with_unreadable(locked, [locked, pe]) - self.assertEqual(rc, 1, out + err) - self.assertIn("PE executable", out) - - @unittest.skipUnless(shutil.which("git"), "git not installed") - def test_default_mode_reads_tracked_files_only(self): - git = ["git", "-c", "init.defaultBranch=main"] - subprocess.run([*git, "init", "-q", self.dir], check=True) - self.write("notes.txt", b"plain text\n") - self.write("untracked.bin", b"DDS " + bytes(12)) - subprocess.run(["git", "add", "notes.txt"], cwd=self.dir, check=True) - result = run([], cwd=self.dir) - self.assertEqual(result.returncode, 0, result.stdout + result.stderr) - - self.write("renamed.txt", b"FSSM" + bytes(12)) - subprocess.run(["git", "add", "renamed.txt"], cwd=self.dir, check=True) - result = run([], cwd=self.dir) - self.assertEqual(result.returncode, 1, result.stdout + result.stderr) - self.assertIn("renamed.txt: FSSM shader", result.stdout) - self.assertNotIn("untracked.bin", result.stdout) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/test_check_sparse_queue_family.py b/tests/test_check_sparse_queue_family.py deleted file mode 100644 index 98ae4f87f..000000000 --- a/tests/test_check_sparse_queue_family.py +++ /dev/null @@ -1,229 +0,0 @@ -"""Synthetic tests for runtime/test/check_sparse_queue_family.py (TEST-1089). - -The contract checker runs the GPU test twice, once under VK_LAYER_LUNARG_api_dump and once under -VK_LAYER_KHRONOS_validation, because api_dump's vkDestroyDevice can crash on the AMD Windows driver. These -tests check that each run loads exactly one of the two layers, that only that crash is allowed and only in -the api_dump run, and that any other crash, a skip or a missing case is still reported. No GPU or game data: the "GPU test" is a stub script. - -Run: - python -I tests/test_check_sparse_queue_family.py -""" -from __future__ import annotations - -import contextlib -import importlib.util -import io -import re -import sys -import tempfile -import unittest -from pathlib import Path -from unittest import mock - -ROOT = Path(__file__).resolve().parents[1] -sys.path.insert(0, str(ROOT / "tests")) -import runtime_cmake # noqa: E402 - -SPEC = importlib.util.spec_from_file_location("check_sparse_queue_family", - ROOT / "runtime" / "test" / "check_sparse_queue_family.py") -checker = importlib.util.module_from_spec(SPEC) -SPEC.loader.exec_module(checker) - -PASS_OUT = "".join(f"RESULT LAYER_MAP_{kind}_COPY_COMPUTE PASS mapped_mismatch=0/65536 unmapped_nonzero=0/65536\n" - for kind in ("DIRECT", "COPY", "COMPUTE")) + "LAYER_FINAL PASS\n" - - -DESTROY_TRACE = ("vkDestroyPipelineLayout(device, pipelineLayout, pAllocator) returns void:\n" - " device: VkDevice = 0000000000000000\n" - "vkDestroyDevice(device, pAllocator) returns void\n") - - -class Completed: - def __init__(self, returncode: int, stdout: str = "", stderr: str = "") -> None: - self.returncode, self.stdout, self.stderr = returncode, stdout, stderr - - -class PassEnvsTest(unittest.TestCase): - def test_each_run_loads_one_layer(self) -> None: - base = {"PATH": "x", "VK_INSTANCE_LAYERS": "VK_LAYER_LUNARG_api_dump", "LEONIDA_VK_VALIDATION": "1"} - dump, validation = checker.pass_envs(base, Path("settings")) - self.assertEqual(dump["VK_INSTANCE_LAYERS"], "VK_LAYER_LUNARG_api_dump") - self.assertEqual(dump["LEONIDA_VK_VALIDATION"], "0") - self.assertEqual(dump["VK_LAYER_SETTINGS_PATH"], "settings") - self.assertNotIn("VK_INSTANCE_LAYERS", validation) - self.assertEqual(validation["LEONIDA_VK_VALIDATION"], "1") - self.assertEqual(dump["PATH"], "x") - self.assertEqual(validation["PATH"], "x") - - def test_base_environment_is_not_changed(self) -> None: - base = {"LEONIDA_VK_VALIDATION": "1"} - checker.pass_envs(base, Path("s")) - self.assertEqual(base, {"LEONIDA_VK_VALIDATION": "1"}) - - -class RunPassTest(unittest.TestCase): - def run_with(self, result: Completed) -> tuple[str, int]: - with mock.patch.object(checker.subprocess, "run", return_value=result): - return checker.run_pass(Path("t.exe"), {}, Path(".")) - - def test_all_cases_pass(self) -> None: - self.assertEqual(self.run_with(Completed(0, PASS_OUT))[1], 0) - - def test_skip_code_is_a_skip(self) -> None: - self.assertEqual(self.run_with(Completed(77))[1], 77) - - def test_missing_layer_is_a_skip(self) -> None: - self.assertEqual(self.run_with(Completed(1, stderr="[rt] d3d12: vkCreateInstance (Vulkan 1.3) failed"))[1], 77) - - def test_access_violation_fails(self) -> None: - with self.assertRaises(AssertionError), contextlib.redirect_stderr(io.StringIO()): - self.run_with(Completed(0xC0000005, PASS_OUT)) - - def run_dump_with(self, result: Completed, *traces: str) -> int: - with tempfile.TemporaryDirectory() as td: - for i, trace in enumerate(traces): - (Path(td) / f"sparse_create_info.log{i or ''}").write_text(trace, encoding="utf-8") - with mock.patch.object(checker.subprocess, "run", return_value=result), \ - contextlib.redirect_stdout(io.StringIO()), contextlib.redirect_stderr(io.StringIO()): - return checker.run_pass(Path("t.exe"), {}, Path("."), trace_dir=Path(td))[1] - - def test_api_dump_crash_in_destroy_device_after_the_results_is_allowed(self) -> None: - self.assertEqual(self.run_dump_with(Completed(0xC0000005, PASS_OUT), DESTROY_TRACE), 0) - - def test_api_dump_crash_in_another_call_fails(self) -> None: - for trace in (DESTROY_TRACE + "vkDestroyInstance(instance, pAllocator) returns void:\n", - "vkQueueSubmit2(queue, submitCount, pSubmits, fence) returns VkResult:\n", ""): - with self.subTest(trace=trace), self.assertRaises(AssertionError): - self.run_dump_with(Completed(0xC0000005, PASS_OUT), trace) - - def test_api_dump_crash_without_exactly_one_trace_fails(self) -> None: - for traces in ((), (DESTROY_TRACE, DESTROY_TRACE)): - with self.subTest(traces=len(traces)), self.assertRaises(AssertionError): - self.run_dump_with(Completed(0xC0000005, PASS_OUT), *traces) - - def test_api_dump_crash_before_every_result_fails(self) -> None: - for out in (PASS_OUT.replace("LAYER_FINAL PASS", ""), PASS_OUT.replace("LAYER_MAP_COPY", "LAYER_MAP_OTHER")): - with self.subTest(out=out), self.assertRaises(AssertionError): - self.run_dump_with(Completed(0xC0000005, out), DESTROY_TRACE) - - def test_each_case_and_the_final_line_must_be_there_exactly_once(self) -> None: - # Review on #4900: a repeated case stood in for a missing one, and any line starting with the final line passed. - copy_row = next(ln for ln in PASS_OUT.splitlines(True) if "LAYER_MAP_COPY_" in ln) - direct_row = next(ln for ln in PASS_OUT.splitlines(True) if "LAYER_MAP_DIRECT_" in ln) - outputs = {"repeated case for a missing one": PASS_OUT.replace(copy_row, direct_row), - "extra case": PASS_OUT + direct_row, - "longer final line": PASS_OUT.replace("LAYER_FINAL PASS", "LAYER_FINAL PASSING"), - "prefixed final line": PASS_OUT.replace("LAYER_FINAL PASS", "X LAYER_FINAL PASS"), - "two final lines": PASS_OUT + "LAYER_FINAL PASS\n"} - for name, out in outputs.items(): - with self.subTest(name), self.assertRaises(AssertionError): - self.run_with(Completed(0, out)) - with self.subTest(name + ", allowed crash"), self.assertRaises(AssertionError): - self.run_dump_with(Completed(0xC0000005, out), DESTROY_TRACE) - - def test_api_dump_other_exit_codes_fail(self) -> None: - for code in (1, 2, 0xC0000374, 0xC0000409): - with self.subTest(code=hex(code)), self.assertRaises(AssertionError): - self.run_dump_with(Completed(code, PASS_OUT), DESTROY_TRACE) - - def test_missing_case_fails(self) -> None: - with self.assertRaises(AssertionError): - self.run_with(Completed(0, PASS_OUT.replace("LAYER_MAP_COPY", "LAYER_MAP_OTHER"))) - - -EXCLUSIVE_TRACE = (checker.SPARSE_FLAGS + ")\n" - " sharingMode: VkSharingMode = VK_SHARING_MODE_EXCLUSIVE (0)\n" - " queueFamilyIndexCount: uint32_t = 0\n") * 6 -CONCURRENT_TRACE = (checker.SPARSE_FLAGS + ")\n" - " sharingMode: VkSharingMode = VK_SHARING_MODE_CONCURRENT (1)\n" - " queueFamilyIndexCount: uint32_t = 2\n" - " pQueueFamilyIndices[0]: const uint32_t = 0\n" - " pQueueFamilyIndices[1]: const uint32_t = 1\n") * 6 - - -class TraceTest(unittest.TestCase): - def check(self, text): - with tempfile.TemporaryDirectory() as td: - path = Path(td) / "sparse.log" - path.write_text(text, encoding="utf-8", newline="\n") - return checker.check_trace(path, expect_exclusive=False) - - def test_large_family_list_is_not_truncated(self): - record = (f"{checker.SPARSE_FLAGS})\nsharingMode: VkSharingMode = VK_SHARING_MODE_CONCURRENT\n" - "queueFamilyIndexCount: uint32_t = 12\n") - record += "".join(f"pQueueFamilyIndices[{i}]: const uint32_t = {2*i}\n" for i in range(12)) - self.assertEqual(self.check(record * 6), (3, 6)) - - def test_each_sparse_buffer_must_supply_its_own_complete_array(self): - for invalid in (CONCURRENT_TRACE.replace("Indices[1]", "Indices[0]", 1), - CONCURRENT_TRACE.replace("Indices[1]", "Indices[2]", 1), - CONCURRENT_TRACE.replace(" pQueueFamilyIndices[1]: const uint32_t = 1\n", "", 1), - CONCURRENT_TRACE.replace(" pQueueFamilyIndices[1]", "vkOtherCall()\n pQueueFamilyIndices[1]", 1)): - with self.subTest(trace=invalid[:300]), self.assertRaises(AssertionError): - self.check(invalid) - - -class MainTest(unittest.TestCase): - def run_main(self, fake_run) -> int: - with tempfile.TemporaryDirectory() as td: - exe = Path(td) / "t.exe" - exe.write_bytes(b"") - with mock.patch.object(checker.subprocess, "run", side_effect=fake_run), \ - mock.patch.object(sys, "argv", ["check", str(exe)]), \ - contextlib.redirect_stdout(io.StringIO()): - return checker.main() - - def test_broken_trace_fails_even_when_validation_skips(self) -> None: - # Review on #4900: a skip from the validation run must not hide EXCLUSIVE sparse buffers from the first run. - def fake_run(argv, cwd, env, **kwargs): - if env.get("VK_INSTANCE_LAYERS") == "VK_LAYER_LUNARG_api_dump": - (Path(cwd) / "sparse_create_info.log").write_text(EXCLUSIVE_TRACE, encoding="utf-8") - return Completed(0, PASS_OUT) - return Completed(77) - - with self.assertRaises(AssertionError): - self.run_main(fake_run) - - def test_a_crash_in_the_validation_run_fails(self) -> None: - # The api_dump trace on disk ends in vkDestroyDevice, but only the api_dump run may crash there. - def fake_run(argv, cwd, env, **kwargs): - if env.get("VK_INSTANCE_LAYERS") == "VK_LAYER_LUNARG_api_dump": - (Path(cwd) / "sparse_create_info.log").write_text(CONCURRENT_TRACE + DESTROY_TRACE, encoding="utf-8") - return Completed(0xC0000005, PASS_OUT) - - with self.assertRaises(AssertionError), contextlib.redirect_stderr(io.StringIO()): - self.run_main(fake_run) - - def test_an_allowed_crash_still_passes_the_whole_check(self) -> None: - def fake_run(argv, cwd, env, **kwargs): - if env.get("VK_INSTANCE_LAYERS") == "VK_LAYER_LUNARG_api_dump": - (Path(cwd) / "sparse_create_info.log").write_text(CONCURRENT_TRACE + DESTROY_TRACE, encoding="utf-8") - return Completed(0xC0000005, PASS_OUT) - return Completed(0, PASS_OUT) - - self.assertEqual(self.run_main(fake_run), 0) - - def test_both_runs_fit_the_ctest_timeout(self) -> None: - cmake = runtime_cmake.read() - limit = re.search(r"d3d12_sparse_queue_family_contract PROPERTIES[^)]*TIMEOUT (\d+)", cmake) - self.assertIsNotNone(limit) - self.assertLess(2 * checker.RUN_TIMEOUT, int(limit.group(1))) - - def test_validation_errors_fail_the_check(self) -> None: - calls = [] - - def fake_run(argv, cwd, env, **kwargs): - calls.append(dict(env)) - if env.get("LEONIDA_VK_VALIDATION") == "1": - return Completed(0, PASS_OUT + "Validation Error: [ VUID-vkCmdDraw-None-02699 ] synthetic\n") - (Path(cwd) / "sparse_create_info.log").write_text(CONCURRENT_TRACE, encoding="utf-8") - return Completed(0, PASS_OUT) - - with self.assertRaises(AssertionError): - self.run_main(fake_run) - self.assertEqual(len(calls), 2) - self.assertEqual([c.get("VK_INSTANCE_LAYERS") for c in calls], ["VK_LAYER_LUNARG_api_dump", None]) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/test_check_tiny_frame.py b/tests/test_check_tiny_frame.py deleted file mode 100644 index 8c5da0091..000000000 --- a/tests/test_check_tiny_frame.py +++ /dev/null @@ -1,81 +0,0 @@ -"""The verdict logic of runtime/test/check_tiny_frame.py on synthetic output: no loader, GPU or game files.""" -import importlib.util -import unittest -from pathlib import Path - -ROOT = Path(__file__).resolve().parent.parent -SPEC = importlib.util.spec_from_file_location("check_tiny_frame", ROOT / "runtime" / "test" / "check_tiny_frame.py") -check = importlib.util.module_from_spec(SPEC) -SPEC.loader.exec_module(check) - - -def good_output(extra_trace=(), drop=None, binding="shim"): - """What a passing run prints: the binding report, the numbered trace and the guest's verdict.""" - calls = [call for call in list(check.EXPECTED) if call != drop] - calls[10:10] = extra_trace # between the views and the list's commands - lines = ["tiny_frame.exe base=0000000140000000 size=61440 entry=+0x1000 shim=7 host=40 module=0 unimplemented=0", - f" {binding:<13} d3d12_xs.dll!D3D12XboxCreateDevice", - "running tiny_frame.exe"] - lines += [f"[d3d12-trace] #{number} {call}" for number, call in enumerate(calls, 1)] - lines += ["tiny_frame: PASS all 32 pixels are the clear colour (64, 128, 191, 255)", "tiny_frame: OK", - "game exited with code 0", ""] - return "\n".join(lines) - - -class CheckOutputTest(unittest.TestCase): - def test_a_passing_run_has_no_problems(self): - self.assertEqual(check.check_output(0, good_output()), []) - - def test_crlf_output_and_calls_between_the_expected_ones_are_accepted(self): - output = good_output(extra_trace=["XboxID3D12CommandQueue::GetDesc called"]).replace("\n", "\r\n") - self.assertEqual(check.check_output(0, output), []) - - def test_nonzero_exit_code(self): - self.assertIn("exit code 3", check.check_output(3, good_output())) - - def test_missing_verdict_and_failed_check(self): - output = good_output().replace("tiny_frame: OK", "tiny_frame: FAIL Signal\ntiny_frame: FAILED") - problems = check.check_output(0, output) - self.assertIn("the guest did not print `tiny_frame: OK`", problems) - self.assertIn("the guest reported a failed check", problems) - - def test_missing_loader_exit_line(self): - output = good_output().replace("game exited with code 0", "game exited with code 1") - self.assertIn("gta6rt did not report `game exited with code 0`", check.check_output(0, output)) - - def test_host_binding_is_reported(self): - problems = check.check_output(0, good_output(binding="host")) - self.assertEqual(problems, ["d3d12_xs.dll!D3D12XboxCreateDevice was not bound to the shim"]) - - def test_missing_call_names_the_first_one_out_of_order(self): - problems = check.check_output(0, good_output(drop="ID3D12CommandQueue::Signal ok")) - self.assertEqual(problems, ["the trace has no `ID3D12CommandQueue::Signal ok` at its place in the " - "first-frame order"]) - - def test_a_call_that_did_not_succeed_is_reported(self): - problems = check.check_output(0, good_output(extra_trace=["ID3D12Device::CreateHeap unsupported"])) - self.assertEqual(problems, ["traced calls that did not succeed: ID3D12Device::CreateHeap unsupported"]) - - def test_a_gap_in_the_numbering_is_an_invalid_trace(self): - output = good_output().replace("[d3d12-trace] #3 ", "[d3d12-trace] #4 ") - problems = check.check_output(0, output) - self.assertEqual(len(problems), 1) - self.assertTrue(problems[0].startswith("invalid trace sequence at entry 3")) - - def test_no_trace_at_all(self): - output = "\n".join(line for line in good_output().split("\n") if not line.startswith("[d3d12-trace]")) - self.assertEqual(check.check_output(0, output), ["the trace has no `D3D12XboxCreateDevice ok` at its place " - "in the first-frame order"]) - - -class SubsequenceTest(unittest.TestCase): - def test_repeated_entries_need_as_many_occurrences(self): - self.assertIsNone(check.ordered_subsequence(["a", "a", "b"], ["a", "x", "a", "b"])) - self.assertEqual(check.ordered_subsequence(["a", "a", "b"], ["a", "b"]), "a") - - def test_order_matters(self): - self.assertEqual(check.ordered_subsequence(["a", "b"], ["b", "a"]), "b") - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/test_ci_expected_failures.py b/tests/test_ci_expected_failures.py deleted file mode 100644 index 9603545e6..000000000 --- a/tests/test_ci_expected_failures.py +++ /dev/null @@ -1,103 +0,0 @@ -"""Tests for scripts/ci_expected_failures.py, which judges the macOS CI job's test runs. - - python -I tests/test_ci_expected_failures.py -""" -from __future__ import annotations - -import contextlib -import io -from pathlib import Path -import sys -import tempfile -import unittest - -ROOT = Path(__file__).resolve().parents[1] -SCRIPTS = ROOT / "scripts" -if str(SCRIPTS) not in sys.path: - sys.path.insert(0, str(SCRIPTS)) - -import ci_expected_failures as cef # noqa: E402 - - -class Judge(unittest.TestCase): - def test_clean_run_passes(self): - self.assertEqual(cef.judge([], 0, []), (0, [])) - - def test_only_expected_failures_pass_with_a_warning(self): - code, lines = cef.judge(["ps_ssharp"], 1, ["ps_ssharp"]) - self.assertEqual(code, 0) - self.assertEqual(lines, ["::warning::ps_ssharp failed, as expected until its fix is merged"]) - - def test_unexpected_failure_fails(self): - code, lines = cef.judge(["ps_ssharp", "cs_lds"], 1, ["ps_ssharp"]) - self.assertEqual(code, 1) - self.assertIn("::error::cs_lds failed", lines) - - def test_runner_failure_without_names_fails(self): - code, lines = cef.judge([], 2, ["ps_ssharp"]) - self.assertEqual(code, 1) - self.assertIn("::error::the test runner exited with 2 without naming a failed test", lines) - - def test_interrupted_run_cannot_pass_on_a_partial_failure_list(self): - for status in (-15, 143): - with self.subTest(status=status): - code, lines = cef.judge(["known"], status, ["known", "not_run"]) - self.assertEqual(code, 1) - self.assertTrue(any(str(status) in line and line.startswith("::error::") for line in lines)) - self.assertFalse(any("not_run passed" in line for line in lines)) - - def test_expected_failure_that_passes_gets_a_notice(self): - code, lines = cef.judge([], 0, ["xdxr_build_check"]) - self.assertEqual(code, 0) - self.assertEqual(lines, ["::notice::xdxr_build_check passed: drop it from the expected failures"]) - - -class Main(unittest.TestCase): - def run_main(self, failed: str, *args: str) -> int: - with tempfile.TemporaryDirectory() as tmp: - path = Path(tmp) / "failed.txt" - path.write_text(failed, encoding="utf-8") - # Swallowed: a "::error::" line in a CI log would become a real annotation. - with contextlib.redirect_stdout(io.StringIO()): - return cef.main([str(path), *args]) - - def test_reads_names_one_per_line_and_ignores_blank_lines(self): - self.assertEqual(self.run_main("\nxdxr_build_check\n\n", "8", "xdxr_build_check"), 0) - self.assertEqual(self.run_main("a\nb\n", "8", "a"), 1) - - def test_an_expected_argument_can_hold_several_names(self): - self.assertEqual(self.run_main("a\nb\n", "8", " a b\n"), 0) - self.assertEqual(self.run_main("a\nb\n", "8", ""), 1) - - def test_missing_arguments_is_a_usage_error(self): - with contextlib.redirect_stderr(io.StringIO()): - self.assertEqual(cef.main([]), 2) - - def test_help_prints_the_usage_and_succeeds(self): - out = io.StringIO() - with contextlib.redirect_stdout(out): - self.assertEqual(cef.main(["--help"]), 0) - self.assertIn("FAILED_LIST EXIT_STATUS", out.getvalue()) - - def test_a_list_that_cannot_be_read_is_one_error_line(self): - with tempfile.TemporaryDirectory() as tmp: - missing = Path(tmp) / "absent.txt" - err = io.StringIO() - with contextlib.redirect_stderr(err): - self.assertEqual(cef.main([str(missing), "8"]), 2) - self.assertEqual(err.getvalue().count("\n"), 1) - self.assertIn(str(missing), err.getvalue()) - - def test_a_non_integer_status_is_one_error_line(self): - with tempfile.TemporaryDirectory() as tmp: - path = Path(tmp) / "failed.txt" - path.write_text("a\n", encoding="utf-8") - err = io.StringIO() - with contextlib.redirect_stderr(err): - self.assertEqual(cef.main([str(path), "x"]), 2) - self.assertEqual(err.getvalue().count("\n"), 1) - self.assertIn("'x'", err.getvalue()) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/test_ci_registration.py b/tests/test_ci_registration.py deleted file mode 100644 index 6dd23e93e..000000000 --- a/tests/test_ci_registration.py +++ /dev/null @@ -1,631 +0,0 @@ -"""Every test file under tests/ is selected by a CI job -- and that job can actually run its tests. - - python -I tests/test_ci_registration.py - -``.github/workflows/ci.yml`` splits ``tests/test_*.py`` between two jobs with a single predicate -(``PYTEST_FILE_MARKERS``, or no ``__main__``): the standard-library loop in ``check`` runs the rest with -``python -I``, and ``translator-tests`` hands the matched files to pytest. ``tests/semantic/`` goes to -``unittest discover`` and ``tests/*.cjs`` to ``node --test``. This is the test-file counterpart of -``tests/test_ctest_registration.py``: it reads the patterns from the workflow (not from a copy, so it cannot -drift) and fails on the three ways a test goes missing without CI turning red -- - -* a file no job selects, because no glob matches its name: ``tests/thing_test.py`` matches neither - ``test_*.py`` nor ``test*.py``; -* a file a job selects but whose tests that job cannot collect, e.g. a standard-library script that trips - ``PYTEST_FILE_MARKERS`` and keeps its checks under ``if __name__ == "__main__":`` -- the loop skips it and - pytest imports it, collects nothing, and the job stays green because the other files supply items; and -* a file the loop runs with ``python -I`` that only *mentions* ``__main__`` (the loop decides with - ``grep -q '__main__'``, which a comment satisfies), or whose guard is inverted - (``if __name__ != "__main__":``) and runs nothing; -* a semantic file with only module-level ``test*`` functions: ``unittest discover`` collects nothing - there, even though pytest would; and -* a nested ``tests/*/test_*.cjs`` file that ``fnmatch`` matches across ``/`` but the non-recursive - ``node --test tests/test_*.cjs`` command never runs. - -It also runs the ``check`` loop itself, taken from the workflow, under bash on a synthetic tree: the loop has -to run every file and then fail, since stopping at the first failure hides the files sorted after it. - -Only the tracked test files and the workflow are read; no game files, no build tools, no pytest. The loop check -needs bash (Git for Windows' on Windows) and skips without it, except on a GitHub runner. -""" -import ast -import fnmatch -import os -import re -import shutil -import subprocess -import sys -import tempfile -import unittest -from unittest import mock - -ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) -WORKFLOW = os.path.join(".github", "workflows", "ci.yml") - -# What a file has to be called to claim it is a test. Any of these that no job selects is a bug, which is why -# the suffix form (tests/thing_test.py) counts even though no job's glob matches it today. -TEST_FILE = re.compile(r"^(?:test.*\.py|.*_test\.py|test.*\.cjs)$") - - -def read(root, rel): - with open(os.path.join(root, rel), encoding="utf-8", errors="replace") as f: - return f.read() - - -def ci_rules(root): - """(markers, pruned, loop_glob, semantic_dir, viewer_glob), exactly as the workflow spells them.""" - text = read(root, WORKFLOW) - - def find(pattern, what): - match = re.search(pattern, text, re.M) - if not match: - raise AssertionError( - f"ci.yml no longer spells {what} the way tests/test_ci_registration.py expects it to; " - "update this test together with the workflow") - return match.groups() - - (markers,) = find(r"^\s*PYTEST_FILE_MARKERS:\s*'([^']+)'", "PYTEST_FILE_MARKERS") - # The check loop and the translator list share this one find expression. - pruned, loop_glob = find(r"-path\s+'([^']+)'\s+-prune\s+-o\s+-type\s+f\s+-name\s+'([^']+)'", - "the tests/test_*.py scan") - # scripts/run_semantic_tests.py runs the files unittest discover would find, one process each - (semantic,) = find(r"(?:python\s+-m\s+unittest\s+discover\s+-s|python\s+-I\s+scripts/run_semantic_tests\.py)\s+(\S+)", - "the semantic suite's folder") - (viewer,) = find(r"node\s+--test\s+(\S+)", "node --test") - if re.search(r"unittest\s+discover[^\n]*-p\s", text): - raise AssertionError("unittest discover now passes -p; this test assumes its default 'test*.py' pattern") - return markers, pruned.rstrip("/"), loop_glob, semantic.rstrip("/"), viewer - - -STDLIB_STEP = "Tests (standard library only, no game data)" - - -def step_script(root, step_name): - """The ``run: |`` block of the workflow step called ``step_name``, dedented, exactly as CI runs it.""" - lines = read(root, WORKFLOW).splitlines() - for i, line in enumerate(lines): - if line.strip() == f"- name: {step_name}": - step_indent = len(line) - len(line.lstrip()) + 2 - for j in range(i + 1, len(lines)): - text = lines[j] - if text.strip() and len(text) - len(text.lstrip()) < step_indent: - break # the next step: this one has no run block - if text.strip() == "run: |": - body = [] - for k in range(j + 1, len(lines)): - if lines[k].strip() and len(lines[k]) - len(lines[k].lstrip()) <= step_indent: - break - body.append(lines[k]) - indent = min(len(b) - len(b.lstrip()) for b in body if b.strip()) - return "\n".join(b[indent:] for b in body).strip("\n") + "\n" - raise AssertionError(f"ci.yml has no step named {step_name!r} with a `run: |` block; update " - "tests/test_ci_registration.py together with the workflow") - - -def git_bash(): - """The bash GitHub's `shell: bash` uses: Git for Windows' on Windows (not WSL's), PATH's elsewhere.""" - if os.name != "nt": - return shutil.which("bash") - git = shutil.which("git") - if git: - folder = os.path.dirname(os.path.realpath(git)) - for _ in range(3): - folder = os.path.dirname(folder) - for candidate in (os.path.join(folder, "bin", "bash.exe"), os.path.join(folder, "usr", "bin", "bash.exe")): - if os.path.isfile(candidate): - return candidate - return None - - -def tracked_under_tests(root): - try: - result = subprocess.run(["git", "ls-files", "-z", "--", "tests"], cwd=root, capture_output=True, text=True) - if result.returncode == 0: - return [n for n in result.stdout.split("\0") if n] - except OSError: - pass - names = [] # no git: walk, as tests/test_docs_links.py does - for base, dirs, files in os.walk(os.path.join(root, "tests")): - dirs[:] = [d for d in dirs if d not in (".git", "third_party", "__pycache__")] - for name in files: - names.append(os.path.relpath(os.path.join(base, name), root).replace(os.sep, "/")) - return names - - -def claimed_test_files(root): - """Tracked files under tests/ that claim to be tests: by name, or because they define one.""" - found = [] - for rel in tracked_under_tests(root): - name = rel.rsplit("/", 1)[-1] - if TEST_FILE.match(name): - found.append(rel) - elif name.endswith(".py"): - try: - if defines_a_test(read(root, rel)): - found.append(rel) # a test under a name no job's glob matches - except SyntaxError: - pass - return sorted(found) - - -def matches_nonrecursive_glob(rel, pattern): - """Match the way the shell and ``node --test`` do: ``*`` does not cross ``/``. - - ``fnmatch`` lets ``tests/test_*.cjs`` match ``tests/sub/test_x.cjs``, but the workflow command - only expands the top level, so those files would be selected by this test and never run. - """ - directory, _, name = rel.rpartition("/") - pattern_dir, _, pattern_name = pattern.rpartition("/") - return directory == pattern_dir and fnmatch.fnmatchcase(name, pattern_name) - - -def job_of(root: str, rel: str, rules: tuple[str, str, str, str, str]) -> str | None: - """Which job runs ``rel``: 'stdlib', 'pytest', 'semantic', 'viewer', or None for no job at all.""" - markers, pruned, loop_glob, semantic, viewer = rules - if rel.startswith(semantic + "/"): - directory, _, name = rel.rpartition("/") - # unittest discovery only descends into packages beneath its start directory. - while directory != semantic: - if not os.path.isfile(os.path.join(root, directory, "__init__.py")): - return None - directory = directory.rpartition("/")[0] - return "semantic" if fnmatch.fnmatchcase(name, "test*.py") else None - if matches_nonrecursive_glob(rel, viewer): - return "viewer" - if rel.startswith(pruned + "/"): - return None # the Python scans prune this whole tree - if fnmatch.fnmatchcase(rel.rsplit("/", 1)[-1], loop_glob): - source = read(root, rel) - if re.search(markers, source, re.M) or "__main__" not in source: - return "pytest" - return "stdlib" - return None - - -DOCS_ONLY_STEP = "Check documentation when only documentation changed" -# The tests that read only the documents. `check` is skipped for a docs-only pull request, so the docs-only step -# of `change-scope` is the one place they run for it. -DOCUMENT_TESTS = ("tests/test_docs_*.py", "tests/test_i18n_index.py") - - -def docs_only_patterns(root): - """The test files or globs the docs-only step runs, exactly as the workflow spells them.""" - text = read(root, WORKFLOW) - start = text.find("- name: " + DOCS_ONLY_STEP) - if start < 0: - raise AssertionError( - f"ci.yml no longer has the step '{DOCS_ONLY_STEP}'; update tests/test_ci_registration.py together " - "with the workflow") - # The step ends at the next line indented no deeper than its own "- name:": another step, or another job. - end = re.compile(r"^ {0,6}\S", re.M).search(text, text.index("\n", start)) - # A commented-out command is the usual way a test stops running: shell comments don't count. (`#` starts one - # at the beginning of a line or after a space, as in bash.) - lines = [re.sub(r"(^|\s)#.*", "", line) for line in text[start:end.start() if end else len(text)].splitlines()] - return re.findall(r"tests/[\w*./-]+\.py", "\n".join(lines)) - - -def document_tests_not_run_for_docs_only(root, files): - """Document tests the docs-only step does not run, and names in the step that match no tracked file.""" - patterns = docs_only_patterns(root) - wanted = [f for f in files if any(matches_nonrecursive_glob(f, p) for p in DOCUMENT_TESTS)] - missing = [f for f in wanted if not any(matches_nonrecursive_glob(f, p) for p in patterns)] - stale = [p for p in patterns if not any(matches_nonrecursive_glob(f, p) for f in files)] - return missing, stale - - -def defines_a_test(source, require_test_case=False): - """Would the runner find a test here? TestCase subclasses (through local bases) and test* functions. - - ``unittest discover`` only collects TestCase subclasses, so the semantic job passes - ``require_test_case=True``: a module with only ``def test_x(): ...`` runs zero cases there even - though pytest would collect it. - """ - tree = ast.parse(source) - bases, case_aliases = {}, set() - # Recognize bare aliases introduced by a direct import; this is not a general name resolver. - for node in tree.body: - if isinstance(node, ast.ClassDef): - bases[node.name] = [ - "TestCase" if isinstance(b, ast.Name) and b.id in case_aliases else ast.unparse(b).rsplit(".", 1)[-1] - for b in node.bases - ] - case_aliases.discard(node.name) - elif isinstance(node, (ast.Import, ast.ImportFrom)): - for item in node.names: - name = item.asname or item.name.split(".", 1)[0] - if (isinstance(node, ast.ImportFrom) and node.level == 0 and node.module == "unittest" - and item.name == "TestCase" and item.asname): - case_aliases.add(name) - else: - case_aliases.discard(name) - elif isinstance(node, ast.Assign): - case_aliases.difference_update(t.id for t in node.targets if isinstance(t, ast.Name)) - elif isinstance(node, ast.AnnAssign) and node.value is not None and isinstance(node.target, ast.Name): - # A bare annotation does not change the imported binding. - case_aliases.discard(node.target.id) - elif isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)): - case_aliases.discard(node.name) - - def is_test_case(name): - seen, stack = set(), [name] - while stack: - for base in bases.get(stack.pop(), []): - if base in seen: - continue - seen.add(base) - if base == "TestCase": - return True - stack.append(base) - return False - - for node in tree.body: - if isinstance(node, ast.ClassDef) and is_test_case(node.name): - if any(isinstance(item, (ast.FunctionDef, ast.AsyncFunctionDef)) and item.name.startswith("test") - for item in node.body): - return True - # a mixin imported from another module (tests/semantic/f16_unary_cases.py's UnaryF16) brings its tests - if any(b not in bases and b not in ("TestCase", "object") for b in bases[node.name]): - return True - if not require_test_case and isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)) \ - and node.name.startswith("test"): - return True - return False - - -def semantic_job_text(workflow): - """The `semantic-tests:` job of the workflow, up to the next job.""" - match = re.search(r"^ semantic-tests:\n(.*?)(?=^ [A-Za-z0-9_-]+:\n|\Z)", workflow, re.M | re.S) - if not match: - raise AssertionError("ci.yml no longer has a `semantic-tests:` job; update tests/test_ci_registration.py") - return match.group(1) - - -def spirv_gated_semantic_files(root, files): - """tests/semantic files that skip when spirv-as / spirv-val are not installed.""" - gated = [] - for rel in files: - if not rel.startswith("tests/semantic/") or not rel.endswith(".py"): - continue - source = read(root, rel) - if re.search(r"which\(\s*[\"']spirv-(?:as|val)[\"']", source) and re.search(r"skip(?:Unless|Test|If)\b", source): - gated.append(rel) - return gated - - -def spirv_tools_problem(workflow, gated): - """Why the semantic job cannot run `gated` tests, or None: it needs an apt install of spirv-tools and the - LEONIDA_REQUIRE_SPIRV_TOOLS=1 switch that makes a missing tool fail.""" - if not gated: - return None - job = semantic_job_text(workflow) - problems = [] - if not re.search(r"apt-get\s+install[^\n]*\bspirv-tools\b", job): - problems.append("it does not `apt-get install` spirv-tools") - if not re.search(r"LEONIDA_REQUIRE_SPIRV_TOOLS:[^\n]*['\"]1['\"]", job): - problems.append("it never sets LEONIDA_REQUIRE_SPIRV_TOOLS to 1") - return "; ".join(problems) or None - - -def spirv_using_stdlib_files(root, files, rules): - """Files the standard-library loop runs that call spirv-as / spirv-val only when they are installed.""" - return [rel for rel in files if job_of(root, rel, rules) == "stdlib" - and re.search(r"which\(\s*[\"']spirv-(?:as|val)[\"']", read(root, rel))] - - -def stdlib_loop_jobs_with_spirv_tools(workflow): - """Jobs that `apt-get install` spirv-tools and run the standard-library loop (`python -I "$t"`).""" - jobs = re.findall(r"^ ([A-Za-z0-9_-]+):\n(.*?)(?=^ [A-Za-z0-9_-]+:\n|\Z)", workflow, re.M | re.S) - return [name for name, job in jobs if re.search(r'python\s+-I\s+"\$t"', job) - and re.search(r"apt-get\s+install[^\n]*\bspirv-tools\b", job)] - - -def has_main_guard(source): - """A real ``if __name__ == "__main__":`` block that runs something. - - A comment or docstring mentioning ``__main__`` is not enough, and neither is an inverted guard - such as ``if __name__ != "__main__": unittest.main()``: ``python -I`` imports the file, the - comparison is true, ``unittest.main()`` is skipped, and the process still exits 0. - """ - def is_name(node): - return isinstance(node, ast.Name) and node.id == "__name__" - - def is_main(node): - return isinstance(node, ast.Constant) and node.value == "__main__" - - for node in ast.walk(ast.parse(source)): - if not isinstance(node, ast.If): - continue - test = node.test - if not isinstance(test, ast.Compare) or len(test.ops) != 1 or not isinstance(test.ops[0], ast.Eq): - continue - left, right = test.left, test.comparators[0] - if not ((is_name(left) and is_main(right)) or (is_main(left) and is_name(right))): - continue - if any(isinstance(item, ast.Call) for item in ast.walk(node)): - return True - return False - - -class RepositoryRegistrationTest(unittest.TestCase): - @classmethod - def setUpClass(cls): - cls.rules = ci_rules(ROOT) - cls.files = claimed_test_files(ROOT) - - def test_the_scan_sees_the_repository(self): - # A glob that stops matching, or a git call that fails, must not turn the checks below into no-ops. - self.assertGreaterEqual(len(self.files), 300, f"only {len(self.files)} test files found: {self.files[:5]}") - self.assertTrue(any(f.startswith("tests/semantic/") for f in self.files)) - - def test_the_scan_falls_back_when_git_is_missing(self): - with mock.patch("subprocess.run", side_effect=FileNotFoundError("git")): - files = tracked_under_tests(ROOT) - self.assertGreaterEqual(len(files), 300) - self.assertTrue(any(f.startswith("tests/semantic/") for f in files)) - - def test_every_test_file_is_selected_by_a_job(self): - unselected = [f for f in self.files if job_of(ROOT, f, self.rules) is None] - self.assertEqual(unselected, [], - "no CI job runs these test files: " + ", ".join(unselected) + "\n" - "Rename them to tests/test_*.py (or tests/test_*.cjs), put them under tests/semantic/ " - "as test*.py with an __init__.py in each nested directory, or add the pattern to ci.yml.") - - def test_direct_testcase_import_alias(self): - import_alias = "from unittest import TestCase as Parent\n" - test_class = "class Example({base}):\n def test_one(self): pass\n" - direct = test_class.format(base="Parent") - cases = ( - ("direct", import_alias + direct, True), - ("local subclass", import_alias + "class Middle(Parent): pass\n" - + test_class.format(base="Middle"), True), - ("empty", import_alias + "class Example(Parent): pass\n", False), - ("unrelated import", "from types import SimpleNamespace as Parent\n" + direct, False), - ("relative import", "from .unittest import TestCase as Parent\n" + direct, False), - ("qualified name", import_alias + test_class.format(base="other.Parent"), False), - ("reassigned", import_alias + "Parent = object\n" + direct, False), - ("annotated assignment before class", import_alias + "Parent: type = object\n" + direct, False), - ("annotation only", import_alias + "Parent: type\n" + direct, True), - ("annotated assignment after class", import_alias + direct + "Parent: type = object\n", True), - ("local shadow", import_alias + "class Parent: pass\n" + direct, False), - ("reimported", import_alias + "from types import SimpleNamespace as Parent\n" + direct, False), - ) - for kind, source, expected in cases: - with self.subTest(kind=kind): - self.assertEqual(defines_a_test(source, require_test_case=True), expected) - - def test_every_selected_file_exposes_a_test_to_its_runner(self): - # Selection is not execution: pytest imports a file it is handed and reports zero items without - # failing, and unittest discover ignores a module with no TestCase. - silent = [] - for rel in self.files: - job = job_of(ROOT, rel, self.rules) - if job not in ("pytest", "semantic") or not rel.endswith(".py"): - continue - if not defines_a_test(read(ROOT, rel), require_test_case=(job == "semantic")): - silent.append((job, rel)) - self.assertEqual(silent, [], "selected by CI, but the runner would collect no test:\n" + "\n".join( - f" {rel}: {job} imports it and collects nothing, so the job stays green. Give it a unittest.TestCase " - f"or a module-level test* function, or take it out of that job's list in ci.yml." - for job, rel in silent)) - - def test_every_file_the_loop_runs_has_a_main_guard(self): - # The loop decides with `grep -q '__main__'`, which a comment satisfies; python -I would then import - # the file and run nothing. - guardless = [f for f in self.files - if job_of(ROOT, f, self.rules) == "stdlib" and not has_main_guard(read(ROOT, f))] - self.assertEqual(guardless, [], "the check loop runs these with python -I, which executes no test:\n" + - "\n".join(f" {f}: no `if __name__ == \"__main__\":` block" for f in guardless)) - - def test_the_semantic_job_installs_what_its_spirv_gated_tests_need(self): - # A test that skips without spirv-as / spirv-val runs only where something installed them. The runner images - # have neither, so a job that skips instead of installing reports green for tests that never ran. - gated = spirv_gated_semantic_files(ROOT, self.files) - self.assertGreaterEqual(len(gated), 3, f"the scan found only {gated}") - for expected in ("tests/semantic/test_fma_khr.py", "tests/semantic/test_bary_fallback.py", - "tests/semantic/test_image_coherent.py"): - self.assertIn(expected, gated) - problem = spirv_tools_problem(read(ROOT, WORKFLOW), gated) - self.assertIsNone(problem, "the `semantic-tests` job in ci.yml runs tests that skip without SPIRV-Tools, but " + - str(problem) + ".\nInstall spirv-tools on the Linux leg and set LEONIDA_REQUIRE_SPIRV_TOOLS " - "to '1' there (see tests/semantic/test_spirv_tools_required.py).") - - def test_a_job_runs_the_spirv_using_stdlib_files_with_spirv_tools(self): - # The check job's Windows runner has no SPIRV-Tools, so these files skip their spirv-val checks there. - used = spirv_using_stdlib_files(ROOT, self.files, self.rules) - self.assertIn("tests/test_split_big_switch.py", used) - workflow = read(ROOT, WORKFLOW) - self.assertEqual(stdlib_loop_jobs_with_spirv_tools(workflow.replace("spirv-tools", "curl")), []) - self.assertTrue(stdlib_loop_jobs_with_spirv_tools(workflow), "no job in ci.yml installs SPIRV-Tools and " - "runs the standard-library loop, so the spirv-val checks of these files never run:\n " + - "\n ".join(used)) - - def test_the_spirv_tools_check_flags_a_job_that_installs_nothing(self): - workflow = read(ROOT, WORKFLOW) - gated = ["tests/semantic/test_fma_khr.py"] - self.assertIsNone(spirv_tools_problem(workflow, gated)) - self.assertIsNone(spirv_tools_problem(workflow, [])) - no_install = workflow.replace("sudo apt-get install -y --no-install-recommends spirv-tools\n", - "sudo apt-get install -y --no-install-recommends curl\n", 1) - self.assertNotEqual(no_install, workflow) - self.assertIn("apt-get", no_install) - # the translator-tests job above installs spirv-tools too; only the semantic job's own text may count - self.assertIn("does not `apt-get install` spirv-tools", spirv_tools_problem(no_install, gated) or "") - no_switch = workflow.replace("LEONIDA_REQUIRE_SPIRV_TOOLS: ${{ runner.os == 'Linux' && '1' || '0' }}", - "LEONIDA_REQUIRE_SPIRV_TOOLS: ${{ runner.os == 'Linux' && 'yes' || 'no' }}") - self.assertNotEqual(no_switch, workflow) - self.assertIn("never sets LEONIDA_REQUIRE_SPIRV_TOOLS", spirv_tools_problem(no_switch, gated) or "") - - def test_a_docs_only_pull_request_runs_every_document_test(self): - # `check` is skipped when only documents changed, so a document test left out of the docs-only step never - # sees the pull request that breaks it: the pull request is green and `main` fails after the merge. - missing, stale = document_tests_not_run_for_docs_only(ROOT, self.files) - self.assertEqual(missing, [], f"the '{DOCS_ONLY_STEP}' step in ci.yml does not run: " + ", ".join(missing)) - self.assertEqual(stale, [], "that step names test files that do not exist: " + ", ".join(stale)) - # The step runs them with `python3 -I`: each has to be a standard-library script with a main guard. - ran = [f for f in self.files if any(matches_nonrecursive_glob(f, p) for p in docs_only_patterns(ROOT))] - self.assertGreaterEqual(len(ran), 5, ran) - for rel in ran: - with self.subTest(file=rel): - self.assertEqual(job_of(ROOT, rel, self.rules), "stdlib") - self.assertTrue(has_main_guard(read(ROOT, rel))) - - def test_the_scan_flags_a_document_test_the_docs_only_step_leaves_out(self): - with tempfile.TemporaryDirectory() as tmp: - os.makedirs(os.path.join(tmp, ".github", "workflows")) - files = ["tests/test_docs_links.py", "tests/test_docs_design_rows.py", "tests/test_i18n_index.py", - "tests/test_other.py"] - - def workflow(run_lines): - with open(os.path.join(tmp, WORKFLOW), "w", encoding="utf-8") as f: - f.write("jobs:\n change-scope:\n steps:\n" - f" - name: {DOCS_ONLY_STEP}\n run: |\n" - + "".join(f" {line}\n" for line in run_lines) - + " check:\n steps:\n - run: python -I tests/test_other.py\n") - - # The step as it was: two files by name. The design-rows test is a document test it never ran. - workflow(["python3 -I tests/test_docs_links.py", "python3 -I tests/test_i18n_index.py"]) - self.assertEqual(document_tests_not_run_for_docs_only(tmp, files), - (["tests/test_docs_design_rows.py"], [])) - workflow(["for t in tests/test_docs_*.py tests/test_i18n_index.py; do", " python3 -I \"$t\" || exit 1", - "done"]) - self.assertEqual(document_tests_not_run_for_docs_only(tmp, files), ([], [])) - # A name that matches nothing: bash would hand the literal pattern to python3 and the step would fail. - workflow(["python3 -I tests/test_docs_links.py", "python3 -I tests/test_docs_gone.py"]) - self.assertEqual(document_tests_not_run_for_docs_only(tmp, files), - (["tests/test_docs_design_rows.py", "tests/test_i18n_index.py"], - ["tests/test_docs_gone.py"])) - # The step is read up to the next step or job, not to the end of the file. - self.assertNotIn("tests/test_other.py", docs_only_patterns(tmp)) - # A commented-out command does not run: neither a whole line nor the rest of a line after ` #`. - workflow(["# for t in tests/test_docs_*.py tests/test_i18n_index.py; do", "echo skipped", - "python3 -I tests/test_docs_links.py # python3 -I tests/test_i18n_index.py"]) - self.assertEqual(docs_only_patterns(tmp), ["tests/test_docs_links.py"]) - self.assertEqual(document_tests_not_run_for_docs_only(tmp, files), - (["tests/test_docs_design_rows.py", "tests/test_i18n_index.py"], [])) - - def test_the_scan_flags_an_unlisted_file_and_a_file_pytest_cannot_collect(self): - with tempfile.TemporaryDirectory() as tmp: - os.makedirs(os.path.join(tmp, ".github", "workflows")) - os.makedirs(os.path.join(tmp, "tests", "semantic")) - os.makedirs(os.path.join(tmp, "tests", "test_nested_dir")) - with open(os.path.join(tmp, WORKFLOW), "w", encoding="utf-8") as f: - f.write(read(ROOT, WORKFLOW)) - def write(name, text): - with open(os.path.join(tmp, name), "w", encoding="utf-8") as f: - f.write(text) - write("tests/test_plain.py", "import unittest\n" - "class T(unittest.TestCase):\n def test_ok(self):\n pass\n" - "if __name__ == \"__main__\":\n unittest.main()\n") - # Trips PYTEST_FILE_MARKERS, so the loop skips it; its only check is under __main__, so pytest - # collects nothing: the file no job executes. - write("tests/test_numpy_probe.py", "HAVE_NUMPY = False\n" - "def check():\n assert 1 + 1 == 2\n" - "if __name__ == \"__main__\":\n check()\n") - write("tests/left_out_test.py", "import unittest\n" - "class T(unittest.TestCase):\n def test_ok(self):\n pass\n") - write("tests/semantic/test_case.py", "import unittest\n" - "class T(unittest.TestCase):\n def test_ok(self):\n pass\n") - write("tests/semantic/pytest_style.py", "def test_looks_like_a_test():\n pass\n") - # unittest discover ignores module-level test functions, so the semantic job would run zero. - write("tests/semantic/test_function_only.py", "def test_passes():\n pass\n") - # The inverted guard passes a substring test but runs nothing under python -I. - write("tests/test_inequality_guard.py", "import unittest\n" - "class T(unittest.TestCase):\n def test_ok(self):\n pass\n" - "if __name__ != \"__main__\":\n unittest.main()\n") - # fnmatch would match this against tests/test_*.cjs, but node --test does not recurse. - write("tests/test_nested_dir/test_nested.cjs", "const test = require('node:test');\n") - - rules = ci_rules(tmp) - found = claimed_test_files(tmp) - selected = {rel: job_of(tmp, rel, rules) for rel in found} - - self.assertEqual(selected["tests/left_out_test.py"], None) - self.assertEqual(selected["tests/semantic/pytest_style.py"], None) - self.assertEqual(selected["tests/test_numpy_probe.py"], "pytest") - self.assertFalse(defines_a_test(read(tmp, "tests/test_numpy_probe.py"))) - self.assertTrue(defines_a_test(read(tmp, "tests/test_plain.py"))) - self.assertTrue(has_main_guard(read(tmp, "tests/test_plain.py"))) - self.assertEqual(selected["tests/semantic/test_case.py"], "semantic") - self.assertEqual(selected["tests/semantic/test_function_only.py"], "semantic") - self.assertFalse(defines_a_test(read(tmp, "tests/semantic/test_function_only.py"), - require_test_case=True)) - self.assertFalse(has_main_guard(read(tmp, "tests/test_inequality_guard.py"))) - self.assertEqual(selected["tests/test_nested_dir/test_nested.cjs"], None) - - def test_semantic_selection_matches_discovery_through_packages(self) -> None: - with tempfile.TemporaryDirectory() as tmp: - rules = ci_rules(ROOT) - semantic = rules[3] - cases = ("test_root.py", "packaged/test_packaged.py", "bare/test_bare.py", - "bare/leaf/test_bare_ancestor.py") - for case in cases: - path = os.path.join(tmp, semantic, case) - os.makedirs(os.path.dirname(path), exist_ok=True) - with open(path, "w", encoding="utf-8", newline="\n") as f: - f.write("import unittest\nclass Case(unittest.TestCase):\n def test_ok(self):\n pass\n") - for package in ("packaged", "bare/leaf"): - with open(os.path.join(tmp, semantic, package, "__init__.py"), "w", encoding="utf-8", newline="\n") as f: - f.write("# Package for unittest discovery.\n") - - result = subprocess.run([sys.executable, "-m", "unittest", "discover", "-s", semantic, "-v"], - cwd=tmp, capture_output=True, text=True, timeout=15, check=True) - for case in cases: - with self.subTest(case=case): - module = case.removesuffix(".py").replace("/", ".") - discovered = f"({module}.Case.test_ok)" in result.stderr - self.assertEqual(job_of(tmp, f"{semantic}/{case}", rules) == "semantic", discovered, result.stderr) - self.assertIn("Ran 2 tests", result.stderr) - - -class StdlibLoopTest(unittest.TestCase): - """The check job's loop runs every file and then fails, so one failure cannot hide the files after it.""" - - def test_loop_runs_past_a_failure_and_names_every_failed_file(self): - if not git_bash(): - # On a runner a missing bash would turn this check into a silent skip. - self.assertFalse(os.environ.get("GITHUB_ACTIONS"), "no bash found on the CI runner") - self.skipTest("needs bash (Git for Windows on Windows)") - script = step_script(ROOT, STDLIB_STEP) - markers = ci_rules(ROOT)[0] - failing = "import sys\nif __name__ == \"__main__\":\n sys.exit(1)\n" - passing = "import sys\nif __name__ == \"__main__\":\n sys.exit(0)\n" - with tempfile.TemporaryDirectory() as tmp: - os.makedirs(os.path.join(tmp, "tests", "semantic")) - files = { - "tests/test_a_fails.py": failing, - "tests/test_b_passes.py": passing, - "tests/test_c_fails.py": failing, - "tests/test_d_pytest.py": "import pytest\n" + failing, # the loop leaves it to pytest - "tests/semantic/test_e.py": failing, # pruned: unittest discover runs it - } - for rel, text in files.items(): - with open(os.path.join(tmp, rel), "w", encoding="utf-8", newline="\n") as f: - f.write(text) - with open(os.path.join(tmp, "step.sh"), "w", encoding="utf-8", newline="\n") as f: - f.write(script) - # The step calls `python`: a shim on PATH runs this interpreter (a POSIX box may only have `python3`). - bindir = os.path.join(tmp, "bin") - os.makedirs(bindir) - shim = os.path.join(bindir, "python") - with open(shim, "w", encoding="utf-8", newline="\n") as f: - f.write("#!/bin/sh\nexec '%s' \"$@\"\n" % sys.executable.replace("'", "'\\''")) - os.chmod(shim, 0o755) - env = dict(os.environ, PYTEST_FILE_MARKERS=markers, PATH=bindir + os.pathsep + os.environ.get("PATH", "")) - # GitHub runs `shell: bash` as `bash --noprofile --norc -eo pipefail {0}`. - result = subprocess.run([git_bash(), "--noprofile", "--norc", "-eo", "pipefail", "step.sh"], cwd=tmp, - env=env, capture_output=True, text=True, timeout=120) - out = result.stdout + result.stderr - self.assertNotEqual(result.returncode, 0, out) - ran = re.findall(r"^== (\S+)$", out, re.M) - self.assertEqual(ran, ["tests/test_a_fails.py", "tests/test_b_passes.py", "tests/test_c_fails.py"], out) - errors = re.findall(r"^::error file=(\S+)::", out, re.M) - self.assertEqual(errors, ["tests/test_a_fails.py", "tests/test_c_fails.py"], out) - - def test_step_script_reads_the_check_loop(self): - script = step_script(ROOT, STDLIB_STEP) - self.assertIn('python -I "$t"', script) - self.assertIn("-name 'test_*.py'", script) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/test_classify_carve.py b/tests/test_classify_carve.py deleted file mode 100644 index 774525218..000000000 --- a/tests/test_classify_carve.py +++ /dev/null @@ -1,365 +0,0 @@ -"""Tests for tools/classify_carve.py, built from synthetic carve indexes (no game data). - - python -I tests/test_classify_carve.py -""" -import contextlib -import importlib.util -import io -import json -import os -import subprocess -import sys -import tempfile -import unittest -from unittest import mock - -ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) - -ZERO_HEAD = "00" * 16 -RBF0_HEAD = "5242463000000000" -RESPAGE_HEAD = "42400000deadbeef" - - -def load_module(): - path = os.path.join(ROOT, "tools", "classify_carve.py") - spec = importlib.util.spec_from_file_location("classify_carve_under_test", path) - module = importlib.util.module_from_spec(spec) - spec.loader.exec_module(module) - return module - - -carve = load_module() - - -def counts(entry): - return {k: entry[k] for k in ("files", "bytes")} - - -class ClassifyTests(unittest.TestCase): - def test_bink2_rows_do_not_need_a_head(self): - # rpf9_carve writes bink2 rows with dimensions and no head field. - self.assertEqual(carve.classify({"type": "bink2", "size": 12}), "bink2") - - def test_bink2_wins_over_a_signature(self): - self.assertEqual(carve.classify({"type": "bink2", "head": RBF0_HEAD, "size": 1}), "bink2") - - def test_rbf0_metadata(self): - self.assertEqual(carve.classify({"head": RBF0_HEAD, "size": 1}), "rbf0") - - def test_resource_page(self): - self.assertEqual(carve.classify({"head": RESPAGE_HEAD, "size": 1}), "respage") - - def test_gpu_zero_header_needs_sixteen_zero_bytes(self): - self.assertEqual(carve.classify({"head": ZERO_HEAD, "size": 1}), "gpu-zerohdr") - # Fifteen zero bytes are not enough, and the fallback names four bytes. - self.assertEqual(carve.classify({"head": "00" * 15, "size": 1}), "other:00000000") - - def test_other_is_keyed_by_the_first_four_bytes(self): - self.assertEqual(carve.classify({"head": "deadbeefcafebabe", "size": 1}), "other:deadbeef") - - def test_short_head_is_used_as_is(self): - self.assertEqual(carve.classify({"head": "abcd", "size": 1}), "other:abcd") - - def test_signature_must_be_at_the_start(self): - self.assertEqual(carve.classify({"head": "ff" + RBF0_HEAD, "size": 1}), "other:ff524246") - - -class BomIndexTests(unittest.TestCase): - def test_utf8_bom_index_is_accepted(self): - rows = [{"head": RBF0_HEAD, "size": 1}] - with tempfile.TemporaryDirectory() as root: - index = os.path.join(root, "index.json") - with open(index, "w", encoding="utf-8-sig") as f: - json.dump({"files": rows}, f) - self.assertEqual(list(carve.index_rows(index)), rows) - - -class SizeStatsTests(unittest.TestCase): - def setUp(self): - tmp = tempfile.TemporaryDirectory() - self.addCleanup(tmp.cleanup) - self.root = tmp.name - # Archive a: rbf0 sizes 40, 10, 30 (odd), gpu-zerohdr 5 (single). - # Archive b: rbf0 sizes 20 (single), gpu-zerohdr 8, 2, 6, 100 (even). - self.archive("a", [ - {"head": RBF0_HEAD, "size": 40}, {"head": RBF0_HEAD, "size": 10}, - {"head": RBF0_HEAD, "size": 30}, {"head": ZERO_HEAD, "size": 5}, - ]) - self.archive("b", [ - {"head": RBF0_HEAD, "size": 20}, {"head": ZERO_HEAD, "size": 8}, - {"head": ZERO_HEAD, "size": 2}, {"head": ZERO_HEAD, "size": 6}, - {"head": ZERO_HEAD, "size": 100}, - ]) - with mock.patch("sys.argv", ["classify_carve.py", self.root]), contextlib.redirect_stdout(io.StringIO()): - carve.main() - with open(os.path.join(self.root, "types.json"), encoding="utf-8") as f: - self.types = json.load(f) - - def archive(self, name, rows): - path = os.path.join(self.root, name) - os.makedirs(path) - with open(os.path.join(path, "index.json"), "w", encoding="utf-8") as f: - json.dump({"files": rows}, f) - - def test_per_archive_stats(self): - per = self.types["per_archive"] - self.assertEqual(per["a"]["rbf0"], {"files": 3, "bytes": 80, "min": 10, "max": 40, "median": 30}) - self.assertEqual(per["a"]["gpu-zerohdr"], {"files": 1, "bytes": 5, "min": 5, "max": 5, "median": 5}) - self.assertEqual(per["b"]["rbf0"], {"files": 1, "bytes": 20, "min": 20, "max": 20, "median": 20}) - # Even count: sizes 2, 6, 8, 100 -> lower middle value 6, an integer. - self.assertEqual(per["b"]["gpu-zerohdr"], {"files": 4, "bytes": 116, "min": 2, "max": 100, "median": 6}) - - def test_overall_stats_span_archives(self): - overall = self.types["overall"] - # rbf0: 10, 20, 30, 40 -> even, lower middle 20. - self.assertEqual(overall["rbf0"], {"files": 4, "bytes": 100, "min": 10, "max": 40, "median": 20}) - # gpu-zerohdr: 2, 5, 6, 8, 100 -> odd, middle 6. - self.assertEqual(overall["gpu-zerohdr"], {"files": 5, "bytes": 121, "min": 2, "max": 100, "median": 6}) - - def test_existing_keys_keep_their_values_and_order(self): - for scope in (self.types["overall"], *self.types["per_archive"].values()): - for stats in scope.values(): - self.assertEqual(list(stats), ["files", "bytes", "min", "max", "median"]) - self.assertTrue(all(type(v) is int for v in stats.values())) - self.assertEqual(self.types["overall"]["rbf0"]["files"], 4) - self.assertEqual(self.types["overall"]["rbf0"]["bytes"], 100) - self.assertEqual(list(self.types["overall"]), ["gpu-zerohdr", "rbf0"]) - - def test_size_beyond_64_bits_is_accepted(self): - big = 2 ** 64 - with tempfile.TemporaryDirectory() as root: - os.makedirs(os.path.join(root, "a")) - with open(os.path.join(root, "a", "index.json"), "w", encoding="utf-8") as f: - json.dump({"files": [{"head": ZERO_HEAD, "size": big}]}, f) - with mock.patch("sys.argv", ["classify_carve.py", root]), contextlib.redirect_stdout(io.StringIO()): - self.assertEqual(carve.main(), 0) - with open(os.path.join(root, "types.json"), encoding="utf-8") as f: - types = json.load(f) - want = {"files": 1, "bytes": big, "min": big, "max": big, "median": big} - self.assertEqual(types["overall"]["gpu-zerohdr"], want) - self.assertEqual(types["per_archive"]["a"]["gpu-zerohdr"], want) - - def test_empty_report_has_no_entries_to_carry_stats(self): - with tempfile.TemporaryDirectory() as empty: - with mock.patch("sys.argv", ["classify_carve.py", empty]), contextlib.redirect_stdout(io.StringIO()): - carve.main() - with open(os.path.join(empty, "types.json"), encoding="utf-8") as f: - self.assertEqual(json.load(f), {"overall": {}, "per_archive": {}}) - - -class MainTests(unittest.TestCase): - def setUp(self): - tmp = tempfile.TemporaryDirectory() - self.addCleanup(tmp.cleanup) - self.root = tmp.name - - def archive(self, name, rows): - path = os.path.join(self.root, name) - os.makedirs(path, exist_ok=True) - with open(os.path.join(path, "index.json"), "w", encoding="utf-8") as f: - json.dump({"files": rows}, f) - return path - - def run_main(self): - out = io.StringIO() - with mock.patch("sys.argv", ["classify_carve.py", self.root]), contextlib.redirect_stdout(out): - carve.main() - return out.getvalue() - - def types(self): - with open(os.path.join(self.root, "types.json"), encoding="utf-8") as f: - return json.load(f) - - def test_counts_and_bytes_are_aggregated_per_class(self): - self.archive("a", [ - {"head": RBF0_HEAD, "size": 10}, - {"head": "5242463000000001", "size": 30}, - {"head": ZERO_HEAD, "size": 5}, - {"head": "deadbeefcafebabe", "size": 7}, - {"type": "bink2", "size": 3}, - ]) - self.run_main() - types = self.types() - a = types["per_archive"]["a"] - self.assertEqual(counts(a["rbf0"]), {"files": 2, "bytes": 40}) - self.assertEqual(counts(a["gpu-zerohdr"]), {"files": 1, "bytes": 5}) - self.assertEqual(counts(a["other:deadbeef"]), {"files": 1, "bytes": 7}) - self.assertEqual(counts(a["bink2"]), {"files": 1, "bytes": 3}) - self.assertEqual(counts(types["overall"]["rbf0"]), {"files": 2, "bytes": 40}) - - def test_overall_sums_across_archives(self): - self.archive("a", [{"head": RBF0_HEAD, "size": 10}]) - self.archive("b", [{"head": RBF0_HEAD, "size": 25}]) - self.run_main() - types = self.types() - self.assertEqual(counts(types["overall"]["rbf0"]), {"files": 2, "bytes": 35}) - self.assertEqual(counts(types["per_archive"]["a"]["rbf0"]), {"files": 1, "bytes": 10}) - - def test_archives_are_listed_in_name_order(self): - self.archive("b", [{"head": RBF0_HEAD, "size": 1}]) - self.archive("a", [{"head": RBF0_HEAD, "size": 1}]) - self.run_main() - self.assertEqual(list(self.types()["per_archive"]), ["a", "b"]) - - def test_classes_are_ordered_by_bytes_descending(self): - self.archive("a", [ - {"head": RBF0_HEAD, "size": 50}, - {"head": ZERO_HEAD, "size": 500}, - ]) - self.run_main() - types = self.types() - self.assertEqual(list(types["per_archive"]["a"]), ["gpu-zerohdr", "rbf0"]) - self.assertEqual(list(types["overall"]), ["gpu-zerohdr", "rbf0"]) - - def test_directory_without_an_index_is_skipped(self): - self.archive("a", [{"head": RBF0_HEAD, "size": 1}]) - os.makedirs(os.path.join(self.root, "empty"), exist_ok=True) - self.run_main() - self.assertEqual(list(self.types()["per_archive"]), ["a"]) - - def test_stdout_summary(self): - self.archive("a", [{"head": RBF0_HEAD, "size": 1}, {"head": ZERO_HEAD, "size": 2}]) - out = self.run_main() - self.assertIn("GiB", out) - self.assertIn("rbf0", out) - self.assertIn("2 classes in total", out) - - def test_empty_root(self): - out = self.run_main() - self.assertEqual(self.types(), {"overall": {}, "per_archive": {}}) - self.assertIn("0 classes in total", out) - - def test_types_json_uses_one_space_indent(self): - self.archive("a", [{"head": RBF0_HEAD, "size": 1}]) - self.run_main() - with open(os.path.join(self.root, "types.json"), encoding="utf-8") as f: - text = f.read() - self.assertTrue(text.startswith('{\n "overall": {')) - - def test_invalid_index_names_its_path_and_preserves_previous_report(self): - self.archive("a", [{"head": RBF0_HEAD, "size": 1}]) - self.run_main() - before = self.types() - index = os.path.join(self.archive("b", []), "index.json") - for data, message in ( - ("{", "invalid JSON"), - ('{"files": {}}', '"files" list'), - ('{"files": [{"head": "00"}]}', "row 1"), - ('{"files": [{"size": 12, "head": 42}]}', "row 1"), - ): - with self.subTest(data=data): - with open(index, "w", encoding="utf-8") as f: - f.write(data) - proc = subprocess.run( - [sys.executable, "-I", os.path.join(ROOT, "tools", "classify_carve.py"), self.root], - capture_output=True, text=True, - ) - self.assertEqual(proc.returncode, 2) - self.assertIn(index, proc.stderr) - self.assertIn(message, proc.stderr) - self.assertNotIn("Traceback", proc.stderr) - self.assertEqual(self.types(), before) - - def test_bad_arguments_and_roots_are_one_line(self): - tool = os.path.join(ROOT, "tools", "classify_carve.py") - a_file = os.path.join(self.root, "index.json") - with open(a_file, "w", encoding="utf-8") as f: - f.write("{}") - for args, message in (([], "usage"), ([self.root, "extra"], "usage"), - ([os.path.join(self.root, "missing")], "does not exist"), - ([a_file], "is not a folder")): - with self.subTest(args=[os.path.basename(a) for a in args]): - proc = subprocess.run([sys.executable, "-I", tool, *args], capture_output=True, text=True) - self.assertEqual(proc.returncode, 2) - self.assertIn(message, proc.stderr) - self.assertNotIn("Traceback", proc.stderr) - self.assertEqual(proc.stdout, "") - self.assertEqual(sorted(os.listdir(self.root)), ["index.json"]) # no types.json was written - - def test_types_json_directory_is_one_error_line(self): - self.archive("a", [{"head": RBF0_HEAD, "size": 1}]) - report = os.path.join(self.root, "types.json") - os.mkdir(report) - proc = subprocess.run( - [sys.executable, "-I", os.path.join(ROOT, "tools", "classify_carve.py"), self.root], - capture_output=True, text=True, - ) - self.assertEqual(proc.returncode, 2) - self.assertIn("types.json", proc.stderr) - self.assertIn("is a directory", proc.stderr) - self.assertIn("remove or rename", proc.stderr) - self.assertIn("before rerun", proc.stderr) - self.assertNotIn("Traceback", proc.stderr) - self.assertEqual(proc.stdout, "") - self.assertEqual(os.listdir(report), []) - self.assertEqual([n for n in os.listdir(self.root) if n.startswith(".types-")], []) - - def test_help_prints_usage_and_writes_nothing(self): - tool = os.path.join(ROOT, "tools", "classify_carve.py") - for flag in ("-h", "--help"): - with self.subTest(flag=flag): - proc = subprocess.run([sys.executable, "-I", tool, flag], capture_output=True, text=True, - cwd=self.root) - self.assertEqual(proc.returncode, 0) - self.assertIn("usage", proc.stdout) - # The printed line is meant to be copied from the repository root, so it names the tool's folder. - self.assertIn("python -I tools/classify_carve.py", proc.stdout) - self.assertEqual(proc.stderr, "") - self.assertEqual(os.listdir(self.root), []) # nothing read or written - - def test_failed_write_preserves_previous_report(self): - self.archive("a", [{"head": RBF0_HEAD, "size": 1}]) - self.run_main() - before = self.types() - files = sorted(os.listdir(self.root)) - - def fail_dump(_data, handle, **_kwargs): - handle.write("{") - raise OSError("synthetic write failure") - - with mock.patch.object(carve.json, "dump", side_effect=fail_dump): - with self.assertRaisesRegex(OSError, "write failure"): - self.run_main() - self.assertEqual(self.types(), before) - self.assertEqual(sorted(os.listdir(self.root)), files) - - def test_recursion_error_in_index_is_one_error_line(self): - index = os.path.join(self.archive("a", []), "index.json") - err = io.StringIO() - with mock.patch.object(carve.json, "load", side_effect=RecursionError("maximum recursion depth exceeded")): - with mock.patch.object(sys, "argv", ["classify_carve.py", self.root]): - with contextlib.redirect_stderr(err): - rc = carve.main() - self.assertEqual(rc, 2) - self.assertIn(index, err.getvalue()) - self.assertIn("invalid JSON", err.getvalue()) - - def test_unreadable_root_is_one_error_line(self): - err = io.StringIO() - with mock.patch.object(carve.os, "listdir", side_effect=PermissionError("denied")): - with mock.patch.object(sys, "argv", ["classify_carve.py", self.root]): - with contextlib.redirect_stderr(err): - rc = carve.main() - self.assertEqual(rc, 2) - self.assertIn(self.root, err.getvalue()) - - def test_symlinked_types_json_updates_target_in_place(self): - self.archive("a", [{"head": RBF0_HEAD, "size": 42}]) - with tempfile.TemporaryDirectory() as other: - target = os.path.join(other, "real_types.json") - with open(target, "w", encoding="utf-8") as f: - f.write("{}") - link = os.path.join(self.root, "types.json") - try: - os.symlink(target, link) - except OSError as exc: - self.skipTest(f"symlink unavailable: {exc}") - self.run_main() - self.assertTrue(os.path.islink(link)) - with open(target, encoding="utf-8") as f: - data = json.load(f) - self.assertEqual(counts(data["overall"]["rbf0"]), {"files": 1, "bytes": 42}) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/test_cmake_translator_deps.py b/tests/test_cmake_translator_deps.py deleted file mode 100644 index 00efc84d0..000000000 --- a/tests/test_cmake_translator_deps.py +++ /dev/null @@ -1,102 +0,0 @@ -"""The CMake rules that run runtime/test/shaders/build.py rebuild when any translator source changes. - -They used to list only build.py, compute_fixture.py, rdna2spirv.py and their .asm files, so an edit to a module the -translator imports (tools/spirv_asm.py, spirv_asm_tables.py, shader_ir.py, ...) left the last build's SPIR-V in place -(old #3752, BUILD-1064). The rules now depend on LEONIDA_TRANSLATOR_DEPS (runtime/cmake/translator_deps.cmake); this -checks that list against what build.py reaches. No compiler needed; the cmake -P case is skipped without cmake. -""" -import ast -import os -import re -import shutil -import subprocess -import sys -import tempfile -import unittest -from pathlib import Path - -ROOT = Path(__file__).resolve().parent.parent -sys.path[:0] = [str(ROOT), str(ROOT / "tests")] -import make_game # noqa: E402 -import runtime_cmake # noqa: E402 - -TOOLS = ROOT / "tools" -SHADERS = ROOT / "runtime" / "test" / "shaders" -BUILD_PY = SHADERS / "build.py" -MODULE = ROOT / "runtime" / "cmake" / "translator_deps.cmake" -CMAKE_LISTS = ROOT / "runtime" / "CMakeLists.txt" -CMAKE = shutil.which("cmake") - - -def listed(): - """The files LEONIDA_TRANSLATOR_DEPS names, relative to the repository.""" - return re.findall(r"\$\{_leonida_repo\}/(\S+?)\)?$", MODULE.read_text(encoding="utf-8"), re.M) - - -def reached(): - """build.py, the tools scripts it runs (named by a string literal) and every local module they import.""" - tree = ast.parse(BUILD_PY.read_text(encoding="utf-8")) - todo = [BUILD_PY] + [TOOLS / n.value for n in ast.walk(tree) - if isinstance(n, ast.Constant) and isinstance(n.value, str) - and n.value.endswith(".py") and (TOOLS / n.value).is_file()] - seen = set() - while todo: - path = todo.pop() - if path in seen: - continue - seen.add(path) - for node in ast.walk(ast.parse(path.read_text(encoding="utf-8"))): # function-level imports too - if isinstance(node, ast.Import): - mods = [a.name for a in node.names] - elif isinstance(node, ast.ImportFrom) and node.module and not node.level: - mods = [node.module] - else: - continue - for m in mods: - for folder in (path.parent, TOOLS): - if (folder / (m.split(".")[0] + ".py")).is_file(): - todo.append(folder / (m.split(".")[0] + ".py")) - break - return {p.relative_to(ROOT).as_posix() for p in seen} - - -class TranslatorDepsTest(unittest.TestCase): - def test_the_list_covers_every_local_module_build_py_reaches(self): - self.assertEqual({p for p in listed() if p.endswith(".py")}, reached()) - - def test_the_list_has_the_data_files_the_translator_reads(self): - data = {"tools/" + n for n in make_game.TRANSLATION_SOURCES if not n.endswith(".py")} - self.assertTrue(data) - self.assertEqual({p for p in listed() if not p.endswith(".py")}, data) - - def test_the_helpers_that_went_stale_are_listed(self): - for name in ("tools/spirv_asm.py", "tools/spirv_asm_tables.py", "tools/shader_ir.py", "tools/mc_command.py"): - self.assertIn(name, listed()) - - def test_every_build_py_rule_depends_on_the_list(self): - text = runtime_cmake.read(CMAKE_LISTS) - rules = [m.group(0) for m in re.finditer(r"add_custom_command\((?:[^()]|\$<[^>]*>|\([^()]*\))*\)", text) - if "test/shaders/build.py" in m.group(0)] - self.assertGreaterEqual(len(rules), 8) - for rule in rules: - self.assertIn("DEPENDS ${LEONIDA_TRANSLATOR_DEPS}", rule) - self.assertLess(text.index("cmake/translator_deps.cmake"), text.index("-I ${CMAKE_CURRENT_SOURCE_DIR}/test/shaders/build.py")) - - @unittest.skipUnless(CMAKE, "cmake not on PATH") - def test_cmake_resolves_the_list_to_existing_files(self): - with tempfile.TemporaryDirectory() as tmp: - script = Path(tmp) / "driver.cmake" - script.write_text(f'include("{MODULE.as_posix()}")\n' - 'foreach(f ${LEONIDA_TRANSLATOR_DEPS})\n message(STATUS "dep ${f}")\nendforeach()\n', - encoding="utf-8") - r = subprocess.run([CMAKE, "-P", str(script)], capture_output=True, text=True, timeout=60) - self.assertEqual(r.returncode, 0, r.stderr) - deps = re.findall(r"^-- dep (.+)$", r.stdout, re.M) - self.assertEqual(len(deps), len(listed())) - for d in deps: - self.assertTrue(os.path.isfile(d), d) - self.assertIn((TOOLS / "spirv_asm.py").as_posix(), [Path(d).as_posix() for d in deps]) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/test_cmake_vulkan_missing.py b/tests/test_cmake_vulkan_missing.py deleted file mode 100644 index 633c6112c..000000000 --- a/tests/test_cmake_vulkan_missing.py +++ /dev/null @@ -1,76 +0,0 @@ -"""A runtime configure without Vulkan headers must say so loudly, or fail when asked to. - -Everything under ``if(TARGET Vulkan::Headers)`` in runtime/CMakeLists.txt (the D3D12 COM objects, the Vulkan D3D12 -device in gta6rt and most of ctest) is left out without Vulkan headers. It used to be one STATUS line, so a build -whose VULKAN_SDK never reached CMake ran 45 of 125 tests and reported "100% tests passed". - -Runs runtime/cmake/vulkan_headers_missing.cmake with ``cmake -P`` (no compiler needed); skipped without cmake. -""" -import os -import re -import shutil -import subprocess -import tempfile -import unittest -from pathlib import Path - -ROOT = Path(__file__).resolve().parent.parent -MODULE = ROOT / "runtime" / "cmake" / "vulkan_headers_missing.cmake" -CMAKE_LISTS = ROOT / "runtime" / "CMakeLists.txt" -CMAKE = shutil.which("cmake") - - -def run_module(require): - with tempfile.TemporaryDirectory() as tmp: - script = Path(tmp) / "driver.cmake" - script.write_text(f'include("{MODULE.as_posix()}")\nleonida_vulkan_headers_missing()\n', encoding="utf-8") - args = [CMAKE] - if require is not None: - args.append(f"-DLEONIDA_REQUIRE_VULKAN={require}") - args += ["-P", str(script)] - return subprocess.run(args, capture_output=True, text=True, timeout=60) - - -@unittest.skipUnless(CMAKE, "cmake not on PATH") -class VulkanMissingMessageTest(unittest.TestCase): - def test_default_warns_and_names_what_is_left_out(self): - r = run_module(None) - self.assertEqual(r.returncode, 0, r.stderr) - self.assertIn("CMake Warning", r.stderr) - text = " ".join(r.stderr.split()) - for part in ("Vulkan D3D12 device in gta6rt", "LEONIDA_D3D12=vulkan", "D3D12 layer and GPU tests", - "CMakeCache.txt", "LEONIDA_VULKAN_HEADERS_FETCH=ON", "LEONIDA_REQUIRE_VULKAN=ON"): - self.assertIn(part, text) - - def test_off_still_warns(self): - r = run_module("OFF") - self.assertEqual(r.returncode, 0, r.stderr) - self.assertIn("CMake Warning", r.stderr) - - def test_require_fails_the_configure(self): - r = run_module("ON") - self.assertNotEqual(r.returncode, 0) - self.assertIn("CMake Error", r.stderr) - self.assertIn("Vulkan headers not found", r.stderr) - - -class CMakeListsUsesTheModuleTest(unittest.TestCase): - def test_no_headers_branch_calls_the_module(self): - text = CMAKE_LISTS.read_text(encoding="utf-8") - self.assertIn('option(LEONIDA_REQUIRE_VULKAN ', text) - # The else() of if(TARGET Vulkan::Headers) is the last top-level else before its endif. - m = re.search(r"^if\(TARGET Vulkan::Headers\)\n.*?^else\(\)\n(.*?)^endif\(\)", text, re.S | re.M) - self.assertIsNotNone(m, "if(TARGET Vulkan::Headers) ... else() ... endif() not found at top level") - self.assertIn("leonida_vulkan_headers_missing()", m.group(1)) - self.assertNotIn("message(STATUS", m.group(1)) - - def test_ci_requires_vulkan(self): - ci = (ROOT / ".github" / "workflows" / "runtime.yml").read_text(encoding="utf-8") - configures = re.findall(r"cmake -S runtime -B runtime/build.*?(?=\n\s*- name:)", ci, re.S) - self.assertGreaterEqual(len(configures), 2) - for c in configures: - self.assertIn("-DLEONIDA_REQUIRE_VULKAN=ON", c) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/test_compute_fixture.py b/tests/test_compute_fixture.py deleted file mode 100644 index d82e3ceb6..000000000 --- a/tests/test_compute_fixture.py +++ /dev/null @@ -1,37 +0,0 @@ -"""The synthetic compute shader metadata reaches the translator's workgroup declaration.""" - -from pathlib import Path -import sys -import tempfile -import unittest - -ROOT = Path(__file__).resolve().parents[1] -sys.path.insert(0, str(ROOT / "runtime" / "test" / "shaders")) -sys.path.insert(0, str(ROOT / "tools")) - -from compute_fixture import compute_header # noqa: E402 -from rdna2spirv import translate # noqa: E402 - - -class ComputeFixtureTests(unittest.TestCase): - def test_group_tuple_whitespace_reaches_spirv(self) -> None: - with tempfile.TemporaryDirectory() as tmp: - root = Path(tmp) - disasm = root / "disasm" - fssm = root / "fssm" - disasm.mkdir() - fssm.mkdir() - for index, group in enumerate(("4,2,1", "4, 2, 1", "4 , 2,\t1")): - with self.subTest(group=group): - shader = f"cs_group_{index}" - listing = disasm / f"{shader}.s" - listing.write_text(f"; group: {group}\n\ts_endpgm\n", encoding="utf-8", newline="\n") - (fssm / f"{shader}.fssm").write_bytes(compute_header(listing)) - assembly = translate(str(listing)) - local_size = next(line.strip() for line in assembly.splitlines() - if line.lstrip().startswith("OpExecutionMode %main LocalSize ")) - self.assertEqual(local_size, "OpExecutionMode %main LocalSize 4 2 1") - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/test_compute_fixture_shift.py b/tests/test_compute_fixture_shift.py deleted file mode 100644 index 95251feaa..000000000 --- a/tests/test_compute_fixture_shift.py +++ /dev/null @@ -1,91 +0,0 @@ -"""runtime/test/shaders/compute_fixture.py: the user-data shift for D3D12 compute fixtures (D3D-448). - - python -I tests/test_compute_fixture_shift.py - -Hand-written asm text only; no game files, no llvm-mc, no GPU. -""" -import os -import struct -import sys -import tempfile -import unittest -from unittest import mock - -ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) -sys.path.insert(0, os.path.join(ROOT, "runtime", "test", "shaders")) - -import compute_fixture as cf # noqa: E402 - -ASM = """; rsrc2: 0x808c -; s0 = seed, s[4:5] = table (comments keep their register names) -s_load_dwordx4 s[8:11], s[4:5], 0x0 -s_lshl_b32 s7, s6, 6 -v_add_nc_u32_e32 v4, s0, v3 ; s0 again -s_mov_b64 exec, vcc -s_and_b32 s105, s0, m0 -""" - - -class ShiftTest(unittest.TestCase): - def test_every_sgpr_moves_and_comments_stay(self): - got = cf.shift_user_data(ASM.replace("s105", "s100"), 4).splitlines() - self.assertEqual(got[0], "; rsrc2: 0x808c") - self.assertEqual(got[1], "; s0 = seed, s[4:5] = table (comments keep their register names)") - self.assertEqual(got[2], "s_load_dwordx4 s[12:15], s[8:9], 0x0") - self.assertEqual(got[3], "s_lshl_b32 s11, s10, 6") - self.assertEqual(got[4], "v_add_nc_u32_e32 v4, s4, v3 ; s0 again") - self.assertEqual(got[5], "s_mov_b64 exec, vcc") # named registers stay - self.assertEqual(got[6], "s_and_b32 s104, s4, m0") - - def test_zero_shift_is_identity(self): - self.assertEqual(cf.shift_user_data(ASM, 0), ASM) - - def test_past_s105_is_refused(self): - with self.assertRaises(ValueError): - cf.shift_user_data(ASM, 4) # s105 + 4 - with self.assertRaises(ValueError): - cf.shift_user_data("s_load_dwordx4 s[100:103], s[0:1], 0x0\n", 4) - - def test_mnemonics_and_vgprs_untouched(self): - line = "s_buffer_load_dword s1, s[4:7], 0x10 v_mov_b32 v1, v2\n" - self.assertEqual(cf.shift_user_data(line, 4), "s_buffer_load_dword s5, s[8:11], 0x10 v_mov_b32 v1, v2\n") - - -class Rsrc2Test(unittest.TestCase): - def test_user_count_moves_other_fields_stay(self): - # 0x808c: USER_SGPR 6, TGID_X, LDS 1 unit. +4 -> USER_SGPR 10, the rest unchanged. - got = cf.shifted_rsrc2(0x808c, 4) - self.assertEqual((got >> 1) & 31, 10) - self.assertEqual(got & ~(31 << 1), 0x808c & ~(31 << 1)) - self.assertEqual(cf.shifted_rsrc2(0x8088, 4), 0x8090) # the default header: 4 -> 8 user SGPRs - self.assertEqual(cf.shifted_rsrc2(0x8088, 0), 0x8088) - - def test_user_count_overflow_refused(self): - with self.assertRaises(ValueError): - cf.shifted_rsrc2(31 << 1, 1) - - def test_header_uses_the_shift(self): - with tempfile.TemporaryDirectory() as tmp: - path = os.path.join(tmp, "cs_x.asm") - with open(path, "w", encoding="utf-8") as f: - f.write("; rsrc2: 0x808c\n; group: 32,2,1\ns_endpgm\n") - plain = struct.unpack_from("<4I", cf.compute_header(path), 0x138) - shifted = struct.unpack_from("<4I", cf.compute_header(path, 4), 0x138) - self.assertEqual(plain, (0x808c, 32, 2, 1)) - self.assertEqual(shifted, (cf.shifted_rsrc2(0x808c, 4), 32, 2, 1)) - - -class EnvTest(unittest.TestCase): - def test_env_values(self): - for value, want in ((None, 0), ("", 0), ("4", 4), (" 4 ", 4)): - env = {} if value is None else {"LEONIDA_USER_DATA_SHIFT": value} - with mock.patch.dict(os.environ, env, clear=True): - self.assertEqual(cf.user_data_shift(), want) - for bad in ("four", "-1", "28"): - with mock.patch.dict(os.environ, {"LEONIDA_USER_DATA_SHIFT": bad}, clear=True): - with self.assertRaises(ValueError): - cf.user_data_shift() - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/test_conformance_native_paths.py b/tests/test_conformance_native_paths.py deleted file mode 100644 index 1e491c7f9..000000000 --- a/tests/test_conformance_native_paths.py +++ /dev/null @@ -1,96 +0,0 @@ -"""conform_native takes and prints paths outside the ANSI code page. - -main() receives a command line converted to the ANSI code page, and std::filesystem::path::string() throws for a -character that page does not have. The source checks run everywhere. The run checks need Windows, a built -conform_native.exe (tools/conformance/native/README.md) and a D3D12 adapter, and are skipped without them. No game -files. -""" -import os -from pathlib import Path -import re -import shutil -import subprocess -import sys -import tempfile -import unittest - -NATIVE = Path(__file__).resolve().parents[1] / "tools" / "conformance" / "native" -EXES = [NATIVE / "build" / "Release" / "conform_native.exe", NATIVE / "build" / "conform_native.exe"] -# No ANSI code page has all of these scripts, so the name is outside the active one on every Windows but UTF-8 ones. -NAME = "日本हिไท" - - -def code(path): - """The source without its comments.""" - text = path.read_text(encoding="utf-8") - return re.sub(r"//[^\n]*|/\*.*?\*/", "", text, flags=re.S) - - -class SourceTest(unittest.TestCase): - def test_the_command_line_is_read_as_utf16(self): - text = code(NATIVE / "src" / "main.cpp") - self.assertRegex(text, r"\bint wmain\(int \w+, wchar_t\*\* \w+\)") - self.assertNotRegex(text, r"\bint main\(") - - def test_no_path_is_converted_to_the_ansi_code_page(self): - sources = sorted((NATIVE / "src").glob("*.cpp")) - self.assertTrue(sources) - for path in sources: - with self.subTest(path=path.name): - self.assertNotRegex(code(path), r"\.(?:generic_)?string\(\)") - - -class RunTest(unittest.TestCase): - def setUp(self): - if sys.platform != "win32": - self.skipTest("conform_native is a Windows program") - self.exe = next((exe for exe in EXES if exe.is_file()), None) - if self.exe is None: - self.skipTest("conform_native.exe is not built") - temp = tempfile.TemporaryDirectory() - self.addCleanup(temp.cleanup) - self.root = Path(temp.name) - if self.run_exe(self.exe, self.root / "plain")[0] != 0: - self.skipTest("conform_native does not pass with ASCII paths on this machine") - - def run_exe(self, exe, out, *extra): - r = subprocess.run([str(exe), str(out), *map(str, extra)], capture_output=True, timeout=120) - return r.returncode, r.stdout.decode("utf-8"), r.stderr.decode("utf-8", "replace") - - def check_run(self, exe, out, *extra): - status, stdout, stderr = self.run_exe(exe, out, *extra) - self.assertEqual(status, 0, stdout + stderr) - self.assertEqual(sorted(os.listdir(out)), sorted(os.listdir(self.root / "plain"))) - return stdout - - def test_output_directory(self): - out = self.root / NAME - self.assertIn(f"output: {out}", self.check_run(self.exe, out)) - - def test_executable_directory(self): - folder = self.root / f"exe {NAME}" - folder.mkdir() - exe = Path(shutil.copy(self.exe, folder)) - shutil.copytree(self.exe.parent / "shaders", folder / "shaders") - self.assertIn(f"shaders: {folder / 'shaders'}", self.check_run(exe, self.root / "out")) - - def test_shader_directory_option(self): - shaders = self.root / f"shaders {NAME}" - shutil.copytree(self.exe.parent / "shaders", shaders) - self.assertIn(f"shaders: {shaders}", self.check_run(self.exe, self.root / "out", "--shaders", shaders)) - - def test_a_failure_names_the_path(self): - shaders = self.root / f"empty {NAME}" - shaders.mkdir() - status, _, stderr = self.run_exe(self.exe, self.root / "out", "--shaders", shaders) - self.assertEqual(status, 1, stderr) - self.assertIn(str(shaders / "fullscreen_color.vs.cso"), stderr) - - def test_an_unpaired_surrogate_in_the_output_directory(self): - out = self.root / "lone \ud800" - stdout = self.check_run(self.exe, out) - self.assertIn("lone �", stdout) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/test_conformance_png_transparency.py b/tests/test_conformance_png_transparency.py deleted file mode 100644 index 5611fbfa9..000000000 --- a/tests/test_conformance_png_transparency.py +++ /dev/null @@ -1,78 +0,0 @@ -"""Synthetic PNG transparency regressions; no renderer, GPU or game files.""" -import contextlib -import importlib.util -import io -from pathlib import Path -import sys -import tempfile -import unittest - - -SCRIPT = Path(__file__).resolve().parents[1] / "tools" / "conformance" / "compare.py" -SPEC = importlib.util.spec_from_file_location("conformance_compare_transparency", SCRIPT) -C = importlib.util.module_from_spec(SPEC) -sys.modules[SPEC.name] = C -SPEC.loader.exec_module(C) - - -class TransparencyTest(unittest.TestCase): - def setUp(self): - self.temp = tempfile.TemporaryDirectory() - self.addCleanup(self.temp.cleanup) - self.root = Path(self.temp.name) - - def png(self, name, rgba=False, transparent=False): - path = self.root / name - colour = (10, 20, 30, 0) if rgba else (10, 20, 30) - C.write_png(str(path), C.make_solid_raster(1, 1, 6 if rgba else 2, colour, name)) - if transparent: - chunks = C.split_png_chunks(path.read_bytes(), str(path)) - # Truecolor tRNS is three big-endian 16-bit samples (PNG 11.3.1.1). - key = b"\x00\x0a\x00\x14\x00\x1e" - path.write_bytes(C.PNG_SIGNATURE + b"".join( - C.make_chunk(kind, data) + (C.make_chunk(b"tRNS", key) if kind == b"IHDR" else b"") - for kind, data in chunks)) - return path - - def test_rgb_transparency_is_not_silently_decoded_as_opaque(self): - path = self.png("transparent.png", transparent=True) - with self.assertRaisesRegex(C.ToolError, "tRNS.*RGBA"): - C.read_png(str(path)) - - def test_trns_on_rgba_is_also_rejected(self): - # tRNS is forbidden on RGBA, which already stores alpha. - path = self.png("invalid.png", rgba=True, transparent=True) - with self.assertRaisesRegex(C.ToolError, "tRNS is forbidden.*RGBA"): - C.read_png(str(path)) - - def test_opaque_rgb_and_explicit_rgba_remain_supported(self): - rgb = C.read_png(str(self.png("rgb.png"))) - rgba = C.read_png(str(self.png("rgba.png", rgba=True))) - self.assertEqual(rgb.pixel_rgba(0, 0), (10, 20, 30, 255)) - self.assertEqual(rgba.pixel_rgba(0, 0), (10, 20, 30, 0)) - self.assertEqual(C.compare_rasters(rgb, rgba).differing_pixels, 1) - - def test_diff_refuses_transparency_in_either_input_without_a_heatmap(self): - for transparent_side in ("reference", "candidate"): - with self.subTest(side=transparent_side): - manifests = [] - for side in ("reference", "candidate"): - image = self.png(side + ".png", transparent=side == transparent_side) - manifest = self.root / (side + ".json") - C.write_selftest_manifest(str(manifest), side, "synthetic", [{ - "name": "scene", "png": image.name, - "checks": [{"x": 0, "y": 0, "r": 10, "g": 20, "b": 30, "a": 255}], - }]) - manifests.append(str(manifest)) - before = {p.name: p.read_bytes() for p in self.root.iterdir()} - errors = io.StringIO() - with contextlib.redirect_stdout(io.StringIO()), contextlib.redirect_stderr(errors): - rc = C.main(["diff", "--reference", manifests[0], "--candidate", manifests[1]]) - self.assertEqual(rc, C.EXIT_ERROR) - self.assertIn("tRNS", errors.getvalue()) - self.assertIn("RGBA", errors.getvalue()) - self.assertEqual(before, {p.name: p.read_bytes() for p in self.root.iterdir()}) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/test_conformance_run_script.py b/tests/test_conformance_run_script.py deleted file mode 100644 index e0dcd6880..000000000 --- a/tests/test_conformance_run_script.py +++ /dev/null @@ -1,115 +0,0 @@ -"""tools/conformance/native/scripts/run.ps1 deletes only what a run wrote: it checks the renderer is built before -touching -Output, and refuses (exit 2) an -Output that is a file, a link or junction, or a folder holding anything -but .png and manifest.json. Before, `Remove-Item $Output -Recurse -Force` ran first on whatever was passed. - -The script runs from a copy of tools/conformance/native in a temporary folder, with where.exe standing in for -conform_native.exe: it exits at once and writes nothing, which is all these checks need. Windows only.""" -import os -from pathlib import Path -import shutil -import subprocess -import tempfile -import unittest - - -SCRIPT = Path(__file__).resolve().parents[1] / "tools" / "conformance" / "native" / "scripts" / "run.ps1" -STAND_IN = Path(os.environ.get("SystemRoot", r"C:\Windows")) / "System32" / "where.exe" - - -@unittest.skipUnless(os.name == "nt" and shutil.which("powershell.exe") and STAND_IN.is_file(), - "requires Windows PowerShell") -class RunScriptTest(unittest.TestCase): - def setUp(self): - self.tmp = tempfile.TemporaryDirectory() - self.addCleanup(self.tmp.cleanup) - self.base = Path(self.tmp.name) - native = self.base / "tools" / "conformance" / "native" - (native / "scripts").mkdir(parents=True) - shutil.copy(SCRIPT, native / "scripts" / "run.ps1") - self.script = native / "scripts" / "run.ps1" - self.exe = native / "build" / "Release" / "conform_native.exe" - - def build(self): - self.exe.parent.mkdir(parents=True) - shutil.copy(STAND_IN, self.exe) - - def run_script(self, output): - result = subprocess.run( - ["powershell.exe", "-NoProfile", "-NonInteractive", "-ExecutionPolicy", "Bypass", - "-File", str(self.script), "-Output", str(output)], - capture_output=True, text=True, timeout=60) - return result.returncode, result.stdout + result.stderr - - def folder(self, name, files): - path = self.base / name - path.mkdir() - for file_name in files: - (path / file_name).write_bytes(b"x") - return path - - def test_unbuilt_renderer_touches_nothing(self): - output = self.folder("work", ["notes.txt", "old.png"]) - code, text = self.run_script(output) - self.assertEqual(code, 1, text) - self.assertIn("build first", text) - self.assertEqual(sorted(os.listdir(output)), ["notes.txt", "old.png"]) - - def test_previous_run_output_is_emptied(self): - self.build() - output = self.folder("run1", ["old_scene.png", "manifest.json"]) - code, text = self.run_script(output) - self.assertIn("EXITCODE", text) - self.assertNotEqual(code, 2, text) - self.assertFalse((output / "old_scene.png").exists(), text) - self.assertFalse((output / "manifest.json").exists(), text) - - def test_folder_with_other_files_is_refused(self): - self.build() - for name, files in (("mixed", ["scene.png", "keep.txt"]), ("hidden", [".git"])): - with self.subTest(name): - output = self.folder(name, files) - code, text = self.run_script(output) - self.assertEqual(code, 2, text) - self.assertIn("holds files a run does not write", text) - self.assertEqual(sorted(os.listdir(output)), sorted(files)) - - def test_subfolder_is_refused(self): - self.build() - output = self.folder("nested", ["scene.png"]) - (output / "sub").mkdir() - (output / "sub" / "keep.png").write_bytes(b"x") - code, text = self.run_script(output) - self.assertEqual(code, 2, text) - self.assertTrue((output / "sub" / "keep.png").exists()) - - def test_file_is_refused(self): - self.build() - output = self.base / "report.png" - output.write_bytes(b"x") - code, text = self.run_script(output) - self.assertEqual(code, 2, text) - self.assertIn("is a file", text) - self.assertTrue(output.exists()) - - def test_junction_is_refused_and_its_target_kept(self): - # A recursive Remove-Item on a junction can empty the folder it points to; mklink /J needs no privilege. - self.build() - target = self.folder("elsewhere", ["scene.png"]) - link = self.base / "link" - made = subprocess.run(["cmd", "/c", "mklink", "/J", str(link), str(target)], capture_output=True, text=True) - if made.returncode != 0: - self.skipTest(f"cannot make a junction here: {made.stdout}{made.stderr}") - code, text = self.run_script(link) - self.assertEqual(code, 2, text) - self.assertIn("link or junction", text) - self.assertTrue((target / "scene.png").exists()) - - def test_missing_output_folder_runs(self): - self.build() - code, text = self.run_script(self.base / "fresh") - self.assertNotEqual(code, 2, text) - self.assertIn("EXITCODE", text) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/test_console_paths.py b/tests/test_console_paths.py deleted file mode 100644 index 44921c916..000000000 --- a/tests/test_console_paths.py +++ /dev/null @@ -1,43 +0,0 @@ -"""Exercise the Unicode console paths CMake check with a synthetic loader.""" - -from pathlib import Path -import shutil -import subprocess -import sys -import tempfile -import unittest - -CHECK = Path(__file__).resolve().parents[1] / "runtime/test/check_console_paths.cmake" -CMAKE = shutil.which("cmake") - - -@unittest.skipUnless(CMAKE, "CMake is required to exercise the console paths check") -class ConsolePathsTests(unittest.TestCase): - def test_requires_the_guest_to_finish_successfully(self): - cases = ( - ("successful guest", "tiny_game: OK\ngame exited with code 0\n", 0), - ("paths only", "", 1), - ("guest failure", "tiny_game: FAILED\ngame exited with code 1\n", 1), - ("guest OK without loader exit", "tiny_game: OK\n", 1), - ("loader exit without guest OK", "game exited with code 0\n", 1), - ) - with tempfile.TemporaryDirectory() as tmp: - loader = Path(tmp) / "loader.py" - for name, verdict, expected in cases: - with self.subTest(name=name): - output = "console paths: GAME: -> game-Игра, writes -> overlay-保存\n" + verdict - loader.write_text( - f"import sys\nsys.stdout.buffer.write({output.encode('utf-8')!r})\n", - encoding="utf-8", newline="\n", - ) - result = subprocess.run( - [CMAKE, f"-DRUNNER={sys.executable}", f"-DLOADER={loader}", - "-DGUEST=synthetic.exe", "-P", str(CHECK)], - cwd=tmp, capture_output=True, encoding="utf-8", errors="replace", - timeout=10, check=False, - ) - self.assertEqual(result.returncode, expected, result.stdout + result.stderr) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/test_content_definitions.py b/tests/test_content_definitions.py deleted file mode 100644 index 534e64be0..000000000 --- a/tests/test_content_definitions.py +++ /dev/null @@ -1,158 +0,0 @@ -"""ASSET-149: hand-written content XML and carve indexes only.""" -import json -import os -import subprocess -import sys -import tempfile -import unittest - -ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) -sys.path.insert(0, os.path.join(ROOT, "tools")) -from content_definitions import ContentError, carve_documents, parse_content - -CHANGE = (b'fixture' - b'$(fixture)/alpha.rpfSYNTHETIC' - b'unchangedFLAG_A FLAG_B' - b'platform:/beta.rpf' - b'' - b'') -CONTENT = (b'' - b'$(fixture)/change.xmlKEEP' - b'' - b'') -SETUP = (b'fixture' - b'symbolic' - b'fixture_onefixture_two' - b'tail') - - -class ContentTests(unittest.TestCase): - def test_change_set_fields_and_unknown_records(self): - doc = parse_content([CHANGE]) - self.assertEqual(doc.kind, "change_set") - self.assertEqual([e.filename for e in doc.files], ["$(fixture)/alpha.rpf", "platform:/beta.rpf"]) - self.assertEqual([e.file_type for e in doc.files], ["SYNTHETIC", ""]) - self.assertEqual(doc.root.scalar("mapAddAtPhase"), "001") - unknown = doc.files[0].record.select("contents", "Unknown")[0] - self.assertEqual((unknown.text, unknown.attributes), ("unchanged", (("a", "01"),))) - self.assertEqual(len(doc.root.select("executionConditions", "genericConditions", "Item")), 1) - - def test_content_keeps_references_without_opening_them(self): - doc = parse_content([CONTENT]) - self.assertEqual(doc.kind, "content") - self.assertEqual(doc.included_changesets[0].scalar("loadPath"), "$(fixture)/change.xml") - self.assertEqual(doc.included_sets[0].attributes, (("ref", "fixture"),)) - self.assertEqual(doc.files, ()) - - def test_setup_groups_order_and_tail(self): - doc = parse_content([SETUP]) - self.assertEqual(doc.root.scalar("order"), "0x10") - self.assertEqual([x.text for x in doc.change_set_groups[0].select("ContentChangeSets", "Item")], - ["fixture_one", "fixture_two"]) - self.assertEqual(doc.root.select("future", "x")[0].tail, "tail") - self.assertEqual(doc.root.scalar("absent"), None) - - def test_chunk_boundaries_and_utf16(self): - expected = parse_content([CHANGE]) - for size in (1, 7, 63): - self.assertEqual(parse_content(CHANGE[i:i+size] for i in range(0, len(CHANGE), size)), expected) - raw = ''.encode('utf-16') - self.assertEqual(parse_content(raw[i:i+1] for i in range(len(raw))).root.scalar("label"), "café") - - def test_ambiguous_known_fields_are_rejected(self): - for fields in (b'ab', - b'', b'b'): - with self.assertRaises(ContentError): - parse_content([b'' + fields + - b'']) - - def test_missing_optional_file_fields_stay_missing(self): - doc = parse_content([b'' - b'']) - self.assertIsNone(doc.files[0].filename) - self.assertIsNone(doc.files[0].file_type) - - def test_invalid_unsupported_and_dtd_inputs(self): - for raw in (b'', b'', b'', b'', - b'', b'\xff', - b'', - b']>&x;', - b''): - with self.subTest(raw=raw), self.assertRaises(ContentError) as caught: - parse_content([raw]) - self.assertNotIn("private", str(caught.exception)) - - def test_byte_and_depth_limits(self): - with self.assertRaisesRegex(ContentError, 'byte limit'): - parse_content([SETUP], max_bytes=10) - with self.assertRaisesRegex(ContentError, 'nesting'): - parse_content([b'' + b'' * 128 + b'' * 128 + b'']) - - def make_carve(self, directory, blocks): - rows = [] - for i, data in enumerate(blocks): - offset = 4096 + i * 1000 - with open(os.path.join(directory, f'{offset:012x}.bin'), 'wb') as f: - f.write(data) - rows.append(dict(off=offset, size=len(data), stored=100, head=data[:16].hex())) - with open(os.path.join(directory, 'index.json'), 'w', encoding='utf-8', newline='\n') as f: - json.dump(dict(files=rows), f) - return rows - - def test_carve_groups_split_xml_and_keeps_spans(self): - with tempfile.TemporaryDirectory() as directory: - self.make_carve(directory, [CHANGE[:180], CHANGE[180:], CONTENT, SETUP, - b'']) - docs = list(carve_documents(directory)) - self.assertEqual(len(docs), 4) - self.assertEqual(docs[0][:2], (4096, 200)) - self.assertEqual([d.kind if d else None for _, _, d in docs], - ['change_set', 'content', 'setup', None]) - self.assertEqual(docs[0][2], parse_content([CHANGE])) - - def test_carve_missing_block_is_not_replaced_with_header(self): - with tempfile.TemporaryDirectory() as directory: - rows = self.make_carve(directory, [CHANGE]) - os.remove(os.path.join(directory, f'{rows[0]["off"]:012x}.bin')) - with self.assertRaises(OSError): - list(carve_documents(directory)) - - def test_cli_counts_unrelated_standalone_xml_separately(self): - with tempfile.TemporaryDirectory() as directory: - paths = [os.path.join(directory, name) for name in ("setup.xml", "other.xml", "broken.xml")] - for path, payload in zip(paths, (SETUP, b"", b"")): - with open(path, "wb") as f: - f.write(payload) - cmd = [sys.executable, "-I", os.path.join(ROOT, "tools", "content_definitions.py")] - for inputs, expected in ((paths[:2], 0), (paths, 1)): - with self.subTest(inputs=len(inputs)): - result = subprocess.run(cmd + inputs, capture_output=True, text=True) - self.assertEqual(result.returncode, expected, result.stderr) - counts = json.loads(result.stdout) - self.assertEqual((counts["setups"], counts["other_xml"], counts["failed_inputs"]), - (1, 1, expected)) - - def test_cli_reports_counts_only_and_failure_status(self): - with tempfile.TemporaryDirectory() as directory: - self.make_carve(directory, [CHANGE, CONTENT, SETUP]) - cmd = [sys.executable, '-I', os.path.join(ROOT, 'tools', 'content_definitions.py'), directory] - result = subprocess.run(cmd, capture_output=True, text=True) - self.assertEqual(result.returncode, 0, result.stderr) - self.assertEqual(json.loads(result.stdout), dict(documents=3, change_sets=1, contents=1, - setups=1, files=2, included_changesets=1, included_sets=1, groups=1, - other_xml=0, failed_inputs=0)) - self.assertEqual(result.stderr, '') - self.assertNotIn('fixture', result.stdout) - self.assertNotIn(directory, result.stdout) - - missing = os.path.join(directory, 'private.xml') - result = subprocess.run(cmd + [missing], capture_output=True, text=True) - self.assertEqual(result.returncode, 2, result.stderr) - self.assertEqual(json.loads(result.stdout), dict(documents=3, change_sets=1, contents=1, - setups=1, files=2, included_changesets=1, included_sets=1, groups=1, - other_xml=0, failed_inputs=1)) - self.assertEqual(result.stderr.strip().splitlines(), [f'ERROR: {missing}: does not exist']) - - -if __name__ == '__main__': - unittest.main() diff --git a/tests/test_cpu_feature_scan.py b/tests/test_cpu_feature_scan.py deleted file mode 100644 index 0a2941e1e..000000000 --- a/tests/test_cpu_feature_scan.py +++ /dev/null @@ -1,267 +0,0 @@ -"""Unit tests for tools/cpu_feature_scan.py on hand-written dumpbin-style listings and a small synthetic PE. - -The listings are written here line by line and the PE carries only headers and a .pdata table, so the test needs -no game files, no dumpbin and no third-party packages. - - python -I tests/test_cpu_feature_scan.py -""" -import io -import json -import os -import struct -import sys -import tempfile -import unittest -from contextlib import redirect_stderr, redirect_stdout - -ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) -TOOLS_DIR = os.path.join(ROOT, "tools") -if TOOLS_DIR not in sys.path: - sys.path.insert(0, TOOLS_DIR) - -import cpu_feature_scan as scan # noqa: E402 - -BASE = 0x140000000 - - -def listing(*rows): - """Rows are (rva, 'mnemonic operands'); written as `dumpbin /disasm:nobytes` prints them.""" - out = ["Dump of file synthetic.exe\n", "\n", "File Type: EXECUTABLE IMAGE\n", "\n"] - for rva, text in rows: - mnem, _, ops = text.partition(" ") - out.append(f" {BASE + rva:016X}: {mnem:<11} {ops}".rstrip() + "\n") - return out - - -def pe_with_pdata(ranges, image_base=BASE, size_override=None): - """An x64 PE whose only content is a .pdata section holding `ranges` as RUNTIME_FUNCTION entries.""" - pdata = b"".join(struct.pack("> 8 - self.assertEqual(self.vgpr(r, 4), 0x223344AA) # {v0, v1} >> 24 - self.assertEqual(self.vgpr(r, 5), 0xAABBCCDD) # a zero shift keeps src1 - self.assertEqual(self.vgpr(r, 6), 0x000044DD) # bytes 0, 4; sign 0; zero - self.assertEqual(self.vgpr(r, 7), 0xFFFFDDDD) # byte 0, sign of src1 half, 0xff - - def test_perm_sign_bit_selectors(self): - r = self.execute(""" - v_mov_b32 v0, 0x80000000 - v_mov_b32 v1, 0x80000000 - v_mov_b32 v2, 0x0b0a0908 - v_perm_b32 v3, v0, v1, v2 - v_mov_b32 v0, 0x00008000 - v_mov_b32 v1, 0x00008000 - v_perm_b32 v4, v0, v1, v2 - s_endpgm - """) - # Selectors 8/9 read bit 7 of src1 bytes 1/3 (bits 15/31), 10/11 the same of src0. - self.assertEqual(self.vgpr(r, 3), 0xFF00FF00) - self.assertEqual(self.vgpr(r, 4), 0x00FF00FF) - - def test_mul_hi_and_mad(self): - r = self.execute(""" - v_mul_hi_u32 v0, 0xffffffff, 0xffffffff - v_mul_hi_i32 v1, 0xffffffff, 1 - v_mul_hi_i32 v2, 0x40000000, 0x40000000 - v_mul_hi_i32 v3, 0x80000000, 0x40000000 - v_mad_u32_u24 v4, 0xffffff, 0xffffff, 5 - v_mad_i32_i24 v5, 0xffffff, 0xffffff, 5 - v_mad_i32_i24 v6, 0x800000, 0x800000, 1 - s_endpgm - """) - self.assertEqual(self.vgpr(r, 0), 0xFFFFFFFE) - self.assertEqual(self.vgpr(r, 1), 0xFFFFFFFF) - self.assertEqual(self.vgpr(r, 2), 0x10000000) - self.assertEqual(self.vgpr(r, 3), 0xE0000000) - self.assertEqual(self.vgpr(r, 4), 0xFE000006) # 0xffffff**2 + 5, low 32 bits - self.assertEqual(self.vgpr(r, 5), 6) - self.assertEqual(self.vgpr(r, 6), 1) # 2**46 + 1, low 32 bits - - def test_mov_inline_constants_and_literals(self): - r = self.execute(""" - v_mov_b32 v0, 1.0 - v_mov_b32 v1, 1 - v_mov_b32 v2, 0x3f800000 - v_mov_b32 v3, -1 - s_mov_b32 s0, 1.0 - s_mov_b32 s1, -1 - s_endpgm - """) - self.assertEqual(self.vgpr(r, 0), fbits(1.0)) - self.assertEqual(self.vgpr(r, 1), 1) # inline integer constant 1, not 1.0 - self.assertEqual(self.vgpr(r, 2), fbits(1.0)) - self.assertEqual(self.vgpr(r, 3), 0xFFFFFFFF) - self.assertEqual(self.sgpr(r, 0), fbits(1.0)) - self.assertEqual(self.sgpr(r, 1), 0xFFFFFFFF) - - def test_float_add_sub_mul(self): - r = self.execute(""" - v_mov_b32 v0, 1.0 - v_mov_b32 v1, 2.0 - v_add_f32 v2, v0, v1 - v_sub_f32 v3, v0, v1 - v_mul_f32 v4, v0, v1 - v_add_f32 v5, v1, 2 - s_endpgm - """) - self.assertEqual(self.vgpr(r, 2), fbits(3.0)) - self.assertEqual(self.vgpr(r, 3), fbits(-1.0)) - self.assertEqual(self.vgpr(r, 4), fbits(2.0)) - self.assertEqual(self.vgpr(r, 5), fbits(2.0)) # integer inline 2 is the bits 0x2, a denormal - - def test_integer_inline_constant_in_float_op_is_raw_bits(self): - # llvm-mc prints float inline constants with a point (2.0, -1.0); a bare integer is its bit pattern, - # as in LLVM's AMDGPU operand syntax example "v_add_f32 v0, -1, 0 // src0 = 0xFFFFFFFF (NaN)". - r = self.execute(""" - v_mov_b32 v0, 2.0 - v_mul_f32 v1, -1, v0 - v_add_f32 v2, 1, 0 - s_endpgm - """) - self.assertEqual(self.vgpr(r, 1), 0x7FC00000) # 0xffffffff is a NaN, canonicalised - self.assertEqual(self.vgpr(r, 2), 1) # the denormal 0x1, unflushed - - def test_nan_and_signed_zero(self): - r = self.execute(""" - v_mov_b32 v0, 0x7f800000 - v_mov_b32 v1, 0xff800000 - v_add_f32 v2, v0, v1 - v_mov_b32 v3, 0 - v_mul_f32 v4, v0, v3 - v_mov_b32 v5, 0x80000000 - v_add_f32 v6, v5, v3 - v_add_f32 v7, v5, v5 - v_mul_f32 v8, v5, 1.0 - v_sub_f32 v9, v5, v3 - v_sub_f32 v10, v3, v3 - v_mov_b32 v11, 0x7fc00001 - v_add_f32 v12, v11, 1.0 - s_endpgm - """) - self.assertEqual(self.vgpr(r, 2), QNAN) # inf + -inf - self.assertEqual(self.vgpr(r, 4), QNAN) # inf * 0 - self.assertEqual(self.vgpr(r, 6), 0) # -0 + +0 = +0 - self.assertEqual(self.vgpr(r, 7), SIGN) # -0 + -0 = -0 - self.assertEqual(self.vgpr(r, 8), SIGN) # -0 * 1 = -0 - self.assertEqual(self.vgpr(r, 9), SIGN) # -0 - +0 = -0 - self.assertEqual(self.vgpr(r, 10), 0) # +0 - +0 = +0 - self.assertEqual(self.vgpr(r, 12), QNAN) # NaN payload is canonicalized - - def test_denormals_are_preserved(self): - r = self.execute(""" - v_mov_b32 v0, 0x00000001 - v_add_f32 v1, v0, v0 - v_mul_f32 v2, v0, 0.5 - v_mul_f32 v3, v0, 1.5 - v_mov_b32 v4, 0x007fffff - v_add_f32 v5, v4, v0 - s_endpgm - """) - self.assertEqual(self.vgpr(r, 1), 0x00000002) # min subnormal + itself - self.assertEqual(self.vgpr(r, 2), 0x00000000) # half of min subnormal, tie to even - self.assertEqual(self.vgpr(r, 3), 0x00000002) # 1.5 * min subnormal, tie to even - self.assertEqual(self.vgpr(r, 5), 0x00800000) # max subnormal + min subnormal = min normal - - def test_fma_is_fused_not_double_rounded(self): - # 97/64 * 172961/262144 = 1 + 2**-24 exactly, a binary32 midpoint. Adding 2**-60 - # decides the direction; a host double fma would lose it and round to 1.0. - r = self.execute(""" - v_mov_b32 v0, 0x3fc20000 - v_mov_b32 v1, 0x3f28e840 - v_mov_b32 v2, 0x21800000 - v_fma_f32 v3, v0, v1, v2 - v_mov_b32 v4, 2.0 - v_mov_b32 v5, 3.0 - v_mov_b32 v6, 4.0 - v_fma_f32 v7, v4, v5, v6 - s_endpgm - """) - self.assertEqual(self.vgpr(r, 3), fbits(1.0 + 2.0 ** -23)) - self.assertEqual(self.vgpr(r, 7), fbits(10.0)) - - def test_fma_special_values(self): - r = self.execute(""" - v_mov_b32 v0, 0x7f800000 - v_mov_b32 v1, 0 - v_fma_f32 v2, v0, v1, 1.0 - v_mov_b32 v3, 0x80000000 - v_fma_f32 v4, v3, 0, v3 - v_fma_f32 v5, 1.0, 1.0, -1.0 - s_endpgm - """) - self.assertEqual(self.vgpr(r, 2), QNAN) # inf * 0 + 1 - self.assertEqual(self.vgpr(r, 4), SIGN) # -0 * +0 + -0 = -0 - self.assertEqual(self.vgpr(r, 5), 0) # exact cancellation, +0 - - def test_cndmask_wave64(self): - r = self.execute(""" - v_mov_b32 v0, 0x11111111 - v_mov_b32 v1, 0x22222222 - v_cndmask_b32 v2, v0, v1, vcc_lo - s_endpgm - """, lanes=64, vcc=(1 << 1) | (1 << 3) | (1 << 40)) - # Lane 40 checks that VOP2's implicit condition uses the full 64-bit VCC, not only vcc_lo. - expected = [0x22222222 if lane in (1, 3, 40) else 0x11111111 for lane in range(64)] - self.assertEqual(self.vgpr(r, 2), expected) - - def test_cndmask_implicit_vcc_one_lane(self): - body = """ - v_mov_b32 v0, 0x11111111 - v_mov_b32 v1, 0x22222222 - v_cndmask_b32 v2, v0, v1 - s_endpgm - """ - set_bit = self.execute(body, lane=1, vcc=1 << 1) - clear_bit = self.execute(body, lane=2, vcc=1 << 1) - self.assertEqual(self.vgpr(set_bit, 2), 0x22222222) - self.assertEqual(self.vgpr(clear_bit, 2), 0x11111111) - - def test_cndmask_sgpr_pair_wave64(self): - r = self.execute(""" - v_mov_b32 v0, 0x11111111 - v_mov_b32 v1, 0x22222222 - v_cndmask_b32_e64 v2, v0, v1, s[2:3] - s_endpgm - """, lanes=64, sgpr={2: 0x00000002, 3: 0x00000001}) - # Low half selects lane 1; high half selects lane 32. - self.assertEqual(self.vgpr(r, 2), [0x11111111] + [0x22222222] + - [0x11111111] * 30 + [0x22222222] + [0x11111111] * 31) - - def test_cndmask_sgpr_wave32(self): - r = self.execute(""" - v_mov_b32 v0, 0x11111111 - v_mov_b32 v1, 0x22222222 - v_cndmask_b32_e64 v2, v0, v1, s2 - s_endpgm - """, lane=1, sgpr={2: 0x00000002}) - self.assertEqual(self.vgpr(r, 2), 0x22222222) - - def test_cndmask_e64_abs_and_neg_modify_bit31(self): - # FUZZ-20, measured natively on RDNA2 (gfx1035): VOP3 abs/neg on v_cndmask_b32_e64 clear/flip bit 31 - # (float sign-bit moves, abs first then neg), not two's-complement integer abs/negate. - r = self.execute(""" - v_mov_b32 v0, 0x80000005 - v_mov_b32 v1, 0x00000005 - v_mov_b32 v2, 0x12345678 - s_mov_b32 s2, -1 - v_cndmask_b32_e64 v3, v2, -v0, s2 - v_cndmask_b32_e64 v4, v2, |v0|, s2 - v_cndmask_b32_e64 v5, v2, -|v0|, s2 - v_cndmask_b32_e64 v6, v2, -v1, s2 - v_cndmask_b32_e64 v7, -v0, v2, 0 - s_endpgm - """) - self.assertEqual(self.vgpr(r, 3), 0x00000005) - self.assertEqual(self.vgpr(r, 4), 0x00000005) - self.assertEqual(self.vgpr(r, 5), 0x80000005) - self.assertEqual(self.vgpr(r, 6), 0x80000005) - self.assertEqual(self.vgpr(r, 7), 0x00000005) - - def test_cndmask_respects_exec(self): - r = self.execute(""" - v_mov_b32 v0, 0x11111111 - v_mov_b32 v1, 0x22222222 - s_mov_b32 exec_lo, 0x00000002 - s_mov_b32 exec_hi, 0 - v_cndmask_b32 v2, v0, v1, vcc_lo - s_endpgm - """, lanes=64, vcc=0xFFFFFFFFFFFFFFFF) - # Only lane 1 is active, and it selects src1. - self.assertEqual(self.vgpr(r, 2), [0] + [0x22222222] + [0] * 62) - - def test_exec_lo_does_not_touch_the_high_half(self): - r = self.execute(""" - v_mov_b32 v0, 0x11111111 - s_mov_b32 exec_lo, 0x00000000 - v_mov_b32 v0, 0x22222222 - s_endpgm - """, lanes=64) - # Writing exec_lo leaves exec_hi as it was, so lanes 32-63 still run the second write. - self.assertEqual(self.vgpr(r, 0), [0x11111111] * 32 + [0x22222222] * 32) - - def test_shifts(self): - r = self.execute(""" - v_mov_b32 v0, 7 - v_lshlrev_b32 v1, 2, v0 - v_mov_b32 v2, 33 - v_lshlrev_b32 v3, v2, v0 - v_mov_b32 v4, 0x80000000 - v_lshrrev_b32 v5, 31, v4 - v_ashrrev_i32 v6, 31, v4 - v_mov_b32 v7, 0xfffffffe - v_ashrrev_i32 v8, 1, v7 - s_endpgm - """) - self.assertEqual(self.vgpr(r, 1), 28) - self.assertEqual(self.vgpr(r, 3), 14) # amount 33 is masked to 1 - self.assertEqual(self.vgpr(r, 5), 1) - self.assertEqual(self.vgpr(r, 6), 0xFFFFFFFF) - self.assertEqual(self.vgpr(r, 8), 0xFFFFFFFF) - - def test_scalar_add_carry_and_shifts(self): - r = self.execute(""" - s_mov_b32 s0, 0xffffffff - s_add_u32 s1, s0, 1 - s_mov_b32 s2, scc - s_mov_b32 s3, 0x80000000 - s_lshr_b32 s4, s3, 31 - s_mov_b32 s5, scc - s_mov_b32 s6, 0 - s_lshl_b32 s7, s6, 1 - s_mov_b32 s8, scc - s_endpgm - """) - self.assertEqual(self.sgpr(r, 1), 0) - self.assertEqual(self.sgpr(r, 2), 1) # carry out of s_add_u32 - self.assertEqual(self.sgpr(r, 4), 1) - self.assertEqual(self.sgpr(r, 5), 1) # s_lshr_b32: SCC = result != 0 - self.assertEqual(self.sgpr(r, 7), 0) - self.assertEqual(self.sgpr(r, 8), 0) # s_lshl_b32: zero result clears SCC - - def test_exec_mask_keeps_inactive_lanes(self): - r = self.execute(""" - v_mov_b32 v0, 0x11111111 - s_mov_b32 exec_lo, 0xffff0000 - s_mov_b32 exec_hi, 0 - v_mov_b32 v0, 0x22222222 - s_endpgm - """, lanes=64) - expected = [0x11111111] * 16 + [0x22222222] * 16 + [0x11111111] * 32 - self.assertEqual(self.vgpr(r, 0), expected) - - def test_exec_mask_one_lane(self): - body = """ - v_mov_b32 v0, 0x11111111 - s_mov_b32 exec_lo, 0xffff0000 - v_mov_b32 v0, 0x22222222 - s_endpgm - """ - active = self.execute(body, lane=20) - inactive = self.execute(body, lane=4) - self.assertEqual(self.vgpr(active, 0), 0x22222222) - self.assertEqual(self.vgpr(inactive, 0), 0x11111111) - self.assertTrue(active["active"]) - self.assertFalse(inactive["active"]) # "active" is the lane's final EXEC bit - - def test_16_bit_literals_and_packed_halves(self): - r = self.execute(""" - v_mov_b32 v0, 0x3c003c00 - v_and_b32 v1, v0, 0xffff - v_lshrrev_b32 v2, 16, v0 - v_or_b32 v3, v1, v2 - s_endpgm - """) - self.assertEqual(self.vgpr(r, 0), 0x3C003C00) - self.assertEqual(self.vgpr(r, 1), 0x3C00) - self.assertEqual(self.vgpr(r, 2), 0x3C00) - self.assertEqual(self.vgpr(r, 3), 0x3C00) - - def test_64_lane_per_lane_inputs(self): - values = [fbits(float(i)) for i in range(64)] - r = self.execute(""" - v_add_f32 v1, v0, 1.0 - s_endpgm - """, lanes=64, vgpr={0: values}) - self.assertEqual(self.vgpr(r, 1), [fbits(float(i) + 1.0) for i in range(64)]) - - def test_clamp(self): - r = self.execute(""" - v_add_f32 v0, 2.0, 2.0 clamp - v_add_f32 v1, -1.0, -1.0 clamp - s_endpgm - """) - self.assertEqual(self.vgpr(r, 0), fbits(1.0)) - self.assertEqual(self.vgpr(r, 1), 0) - - def test_unsupported_instruction_is_reported(self): - path = self.write(""" - v_pk_fma_f16 v0, v1, v2, v3 - s_endpgm - """) - with self.assertRaises(cpu_ref.Unsupported) as cm: - cpu_ref.run(path) - self.assertIn("v_pk_fma_f16", str(cm.exception)) - - def test_missing_endpgm_is_reported(self): - path = self.write(""" - v_mov_b32 v0, 1 - """) - with self.assertRaises(cpu_ref.ProgramError): - cpu_ref.run(path) - - def test_missing_header_is_reported(self): - path = os.path.join(self.tmp.name, "raw.s") - with open(path, "w", encoding="utf-8") as f: - f.write("\tv_mov_b32 v0, 1\n\ts_endpgm\n") - with self.assertRaises(cpu_ref.ProgramError): - cpu_ref.run(path) - - def test_unknown_input_is_rejected(self): - path = self.write(""" - s_endpgm - """) - with self.assertRaises(ValueError): - cpu_ref.run(path, {"sgprs": {0: 1}}) - - def test_bit_and_vop3_integer_ops(self): - r = self.execute(""" - v_mov_b32 v0, 0x00ff0001 - v_not_b32 v1, v0 - v_bfrev_b32 v2, 0x12345678 - v_ffbl_b32 v3, 0x00010100 - v_ffbh_u32 v4, 0x00010000 - v_ffbh_i32 v5, 0xfffffff0 - v_mov_b32 v15, 0x00ff00ff - v_xnor_b32 v6, 0x0f0f0f0f, v15 - v_bcnt_u32_b32 v7, 0xf0f0f0f0, 3 - v_add3_u32 v8, 10, 20, 30 - v_lshl_add_u32 v9, 3, 2, 5 - v_add_lshl_u32 v10, 3, 5, 2 - v_lshl_or_b32 v11, 3, 4, 1 - v_and_or_b32 v12, 0xf0, 0x3c, 1 - v_or3_b32 v13, 1, 2, 4 - v_xad_u32 v14, 0x5, 0x3, 10 - ; Edge cases: zero/all-ones, positive ffbh_i32, shift > 31, 32-bit overflow, overlapping or3/lshl_or - v_ffbl_b32 v16, 0 - v_ffbh_u32 v17, 0 - v_ffbh_i32 v18, 0 - v_ffbh_i32 v19, -1 - v_ffbh_i32 v20, 0x00100000 - v_lshl_add_u32 v21, 3, 33, 5 - v_add_lshl_u32 v22, 3, 5, 34 - v_lshl_or_b32 v23, 3, 33, 2 - v_add3_u32 v24, 0xffffffff, 2, 3 - v_bcnt_u32_b32 v25, 0xffffffff, 0xfffffffe - v_or3_b32 v26, 3, 6, 12 - s_endpgm - """) - self.assertEqual(self.vgpr(r, 1), 0xFF00FFFE) - self.assertEqual(self.vgpr(r, 2), 0x1E6A2C48) - self.assertEqual(self.vgpr(r, 3), 8) - self.assertEqual(self.vgpr(r, 4), 15) - self.assertEqual(self.vgpr(r, 5), 28) - self.assertEqual(self.vgpr(r, 6), 0xF00FF00F) - self.assertEqual(self.vgpr(r, 7), 19) - self.assertEqual(self.vgpr(r, 8), 60) - self.assertEqual(self.vgpr(r, 9), 17) - self.assertEqual(self.vgpr(r, 10), 32) - self.assertEqual(self.vgpr(r, 11), 49) - self.assertEqual(self.vgpr(r, 12), 0x31) - self.assertEqual(self.vgpr(r, 13), 7) - self.assertEqual(self.vgpr(r, 14), 16) - self.assertEqual(self.vgpr(r, 16), 0xFFFFFFFF) - self.assertEqual(self.vgpr(r, 17), 0xFFFFFFFF) - self.assertEqual(self.vgpr(r, 18), 0xFFFFFFFF) - self.assertEqual(self.vgpr(r, 19), 0xFFFFFFFF) - self.assertEqual(self.vgpr(r, 20), 11) - self.assertEqual(self.vgpr(r, 21), 11) # (3 << (33 & 31)) + 5 - self.assertEqual(self.vgpr(r, 22), 32) # 8 << (34 & 31) - self.assertEqual(self.vgpr(r, 23), 6) # (3 << 1) | 2 (overlapping bit 1, differs from +) - self.assertEqual(self.vgpr(r, 24), 4) # wrapped 32-bit sum - self.assertEqual(self.vgpr(r, 25), 30) # 32 + 0xfffffffe mod 2^32 (differs from 32 ^ 0xfffffffe) - self.assertEqual(self.vgpr(r, 26), 15) # overlapping 3 | 6 | 12 (differs from 3 ^ 6 ^ 12) - - def test_malformed_register_assignments_are_cli_errors(self): - path = self.write("s_endpgm") - for option, assignment, flags in ( - ("--sgpr", "3", []), - ("--vgpr", "3", []), - ("--sgpr", "x=0", []), - ("--sgpr", "3=bad", []), - ("--vgpr", "3=0,1", []), - ("--sgpr", "3", ["--parse-only"]), - ): - with self.subTest(option=option, assignment=assignment, flags=flags): - result = subprocess.run([sys.executable, "-I", cpu_ref.__file__, path, option, assignment, *flags], - capture_output=True, text=True) - self.assertEqual(result.returncode, 2, result.stderr) - self.assertEqual(result.stdout, "") - self.assertEqual(len(result.stderr.splitlines()), 1) - self.assertIn(option, result.stderr) - self.assertIn("N=VALUE", result.stderr) - - def test_out_of_range_lane_is_a_cli_error(self): - path = self.write("s_endpgm") - for lane in ("100", "-1", "64"): - with self.subTest(lane=lane): - result = subprocess.run([sys.executable, "-I", cpu_ref.__file__, path, "--lane", lane], - capture_output=True, text=True) - self.assertEqual(result.returncode, 2, result.stderr) - self.assertIn("--lane", result.stderr) - self.assertIn("0..63", result.stderr) - self.assertNotIn("Traceback", result.stderr) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/test_crosslane_fuzz.py b/tests/test_crosslane_fuzz.py deleted file mode 100644 index e82e05bc3..000000000 --- a/tests/test_crosslane_fuzz.py +++ /dev/null @@ -1,949 +0,0 @@ -"""tools/crosslane_fuzz.py: the reference model of the cross-lane ops, checked against values worked out by hand -from the RDNA ISA rules in its docstring. No GPU, no llvm-mc, no game files. - - python -I tests/test_crosslane_fuzz.py -""" -import argparse -import contextlib -import io -import os -import random -import re -import subprocess -import sys -import tempfile -import unittest -from unittest import mock - -TOOLS = os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "tools") -TOOL = os.path.join(TOOLS, "crosslane_fuzz.py") -sys.path.insert(0, TOOLS) -import crosslane_fuzz as X # noqa: E402 - - -def wave(size=64): - w = X.Wave(size, (1 << size) - 1) - w.v[2] = [3 * l + 1 for l in range(size)] - return w - - -def draw(gen, method, pred, tries=4000): - for _ in range(tries): - o = getattr(gen, method)() - if o is not None and pred(o): - return o - raise AssertionError(f"{method}: no op matched") - - -def operands(insn): - """Register numbers / literals of one instruction line, in order (modifiers after the operands dropped).""" - head = insn.split(" row_")[0].split(" quad_perm")[0].split(" dpp8")[0] - return [t.strip() for t in head.split(" ", 1)[1].split(",")] - - -class Model(unittest.TestCase): - def test_readlane_ignores_exec(self): - g = X.Gen(random.Random(1), 64, 64) - o = draw(g, "op_readlane", lambda o: "s_mov_b32" not in o.text) - dst, src, lane = operands(o.text) - w = wave() - w.v[int(src[1:])] = [5 * l for l in range(64)] - w.exec = 1 << 63 - o.apply([w]) - self.assertEqual(w.s[int(dst[1:])], 5 * int(lane)) - - def test_readfirstlane(self): - g = X.Gen(random.Random(0), 64, 64) - o = g.op_readfirstlane() - dst, src = (int(t[1:]) for t in operands(o.text)) - w = wave() - w.v[src] = [7 + l for l in range(64)] - w.exec = 0 # EXEC 0: lane 0 - o.apply([w]) - self.assertEqual(w.s[dst], 7) - w.exec = (1 << 40) | (1 << 50) # lowest active lane - o.apply([w]) - self.assertEqual(w.s[dst], 47) - - def test_cmp_writes_zero_for_inactive_lanes(self): - g = X.Gen(random.Random(2), 64, 64) - o = draw(g, "op_cmp", lambda o: "_ne_u32_e64 s[" in o.text and len(set(operands(o.text)[1:])) == 2) - dst, a, b = operands(o.text) - w = wave() - w.v[int(a[1:])] = list(range(64)) - w.v[int(b[1:])] = [64] * 64 # a != b in every lane - w.exec = 0xFFFF0000FFFF0000 - o.apply([w]) - self.assertEqual(w.mask(int(dst[2:].split(":")[0])), 0xFFFF0000FFFF0000) - - def test_mbcnt_lo_hi(self): - g = X.Gen(random.Random(4), 64, 64) - g.masks = [16] - o = draw(g, "op_mbcnt", lambda o: "s16" in o.text) - d = int(o.text.split()[1].strip(",")[1:]) - acc = int(operands(o.text.split("\n")[0])[2][1:]) - w = wave() - w.v[acc] = [0] * 64 - w.set_mask(16, 0xF0F0F0F0F0F0F0F0) - o.apply([w]) - self.assertEqual([w.vr(d)[l] for l in (0, 8, 40, 63)], [0, 4, 20, 31]) - - def test_saveexec_and_restore(self): - g = X.Gen(random.Random(3), 64, 64) - g.masks = [16] - save, restore = g.op_saveexec(), g.op_restore() - w = wave() - w.exec = 0x00000000FFFFFFFF - w.set_mask(16, 0x0F0F0F0F0F0F0F0F) - save.apply([w]) - self.assertEqual(w.exec, 0x0F0F0F0F) - restore.apply([w]) - self.assertEqual(w.exec, 0x00000000FFFFFFFF) - - def test_writelane_wave32_uses_bits_4_0(self): - g = X.Gen(random.Random(0), 32, 32) - o = draw(g, "op_writelane", lambda o: o.tag == "writelane_w32hi") - m = re.search(r"s_mov_b32 s28, (\d+)", o.text) - d, src, sel = operands(o.text.split("\n")[-1].strip()) - enc = int(m.group(1)) if m else int(sel) - self.assertGreaterEqual(enc, 32) - w = wave(32) - if src.startswith("s"): - w.s[int(src[1:])] = 0xABCD - val = 0xABCD if src.startswith("s") else int(src) & X.M32 - w.v[int(d[1:])] = [0x5555] * 32 - o.apply([w]) - self.assertEqual(w.v[int(d[1:])], [val if l == enc & 31 else 0x5555 for l in range(32)]) - - def test_permlanex16_mapping(self): - g = X.Gen(random.Random(6), 64, 64) - o = draw(g, "op_permlane", lambda o: "v_permlanex16_b32" in o.text) - insn = o.text.split("\n")[-1].strip() - d, v = (int(t[1:]) for t in operands(insn)[:2]) - s2 = int(re.search(r"s_mov_b32 s29, 0x([0-9a-f]+)", o.text).group(1), 16) - lit = re.search(r"s_mov_b32 s28, 0x([0-9a-f]+)", o.text) or re.search(r"0x([0-9a-f]+)", insn) - s1 = int(lit.group(1), 16) # from s28, or the instruction's literal - w = wave() - w.v[v] = [500 + l for l in range(64)] - o.apply([w]) - nib = (s1 | s2 << 32) - for l in (0, 5, 20, 40, 63): - src = (l & ~31) | ((l & 16) ^ 16) | (nib >> (4 * (l & 15)) & 15) - self.assertEqual(w.vr(d)[l], 500 + src) - - def test_dpp_invalid_source_and_disabled_bank_are_not_written(self): - g = X.Gen(random.Random(5), 64, 64, dpp=True) - ops = [o for o in (g.op_dpp() for _ in range(6000)) if o.text.startswith("v_add_nc_u32_dpp")] - shr = next(o for o in ops if " row_shr:1 " in o.text and "row_mask:0xf bank_mask:0xf" in o.text - and "bound_ctrl" not in o.text and "fi:1" not in o.text) - bank = next(o for o in ops if "row_mask:0xf bank_mask:0x1" in o.text and not o.text.endswith("0x1f")) - for o, unwritten, written in ((shr, (0, 16, 32, 48), (1, 17)), (bank, (4, 15, 20), (0, 3, 16))): - d, a, b = (int(t[1:]) for t in operands(o.text)) - w = wave() - w.v[a] = [100 + l for l in range(64)] - w.v[b] = [1000 + l for l in range(64)] - if d not in (a, b): - w.v[d] = [7] * 64 - before = list(w.vr(d)) - o.apply([w]) - for l in unwritten: - self.assertEqual(w.vr(d)[l], before[l], (o.text, l)) - for l in written: - self.assertNotEqual(w.vr(d)[l], before[l], (o.text, l)) - - def test_branch_skips_body_per_wave(self): - g = X.Gen(random.Random(9), 64, 128) - o = draw(g, "op_branch", lambda o: "s_cbranch_execz" in o.text and "v_readfirstlane" in o.text) - w0, w1 = wave(), wave() - w0.exec, w1.exec = 0, 1 << 33 - dst = int(re.search(r"v_readfirstlane_b32 s(\d+)", o.text).group(1)) - w0.s[dst] = w1.s[dst] = 0xDEAD - o.apply([w0, w1]) - self.assertEqual(w0.s[dst], 0xDEAD) # EXEC 0: this wave skips the body - - def test_programs_are_reproducible(self): - a = X.make_program(42, 64, 20, allow_maskdata=False) - b = X.make_program(42, 64, 20, allow_maskdata=False) - self.assertEqual(a.source(), b.source()) - self.assertEqual(a.expected()[0], b.expected()[0]) - - def test_self_test(self): - self.assertEqual(X.self_test(), 0) - - def test_dpp_seeds_are_unchanged(self): - # dpp_op was split out of Gen.op_dpp keeping the draw order; this program (5 DPP ops) is the one main - # generated before the split, so a seed someone reported still means the same program. - import hashlib - p = X.make_program(77, 64, 28, dpp=True) - self.assertEqual(sum("_dpp " in o.text for o in p.ops), 5) - self.assertEqual(hashlib.sha1(p.source().encode()).hexdigest(), "7174158b8d064cbddca318d3d7f433afac072691") - - -def run_dpp(op, exec_mask, size=64, old=7): - """Apply one DPP op to a wave whose src0 (v3, or v2 in place) is 100 + lane, src1 (v4) 1000 + lane and vD (v2) - `old`; returns (vD, hypothesis flag).""" - w = X.Wave(size, (1 << size) - 1) - w.v[3] = [100 + l for l in range(size)] - w.v[4] = [1000 + l for l in range(size)] - if op.text.split()[2].rstrip(",") == "v2": # in place: vD is src0 - w.v[2] = [100 + l for l in range(size)] - else: - w.v[2] = [old] * size - w.exec = exec_mask - hyp = op.fn(w) - return w.vr(2), hyp - - -class DppSweep(unittest.TestCase): - """dpp_op against values worked out by hand from the RDNA2 DPP rules, and what --dpp-sweep generates.""" - ODD = 0x5555555555555555 - - def test_row_shr_invalid_source_is_unwritten_or_zero(self): - v, _ = run_dpp(X.dpp_op(2, 3, 4, "mov", control=("row_shr", 1)), X.M64) - self.assertEqual((v[0], v[1], v[15], v[16], v[17]), (7, 100, 114, 7, 116)) - v, _ = run_dpp(X.dpp_op(2, 3, 4, "mov", control=("row_shr", 1), bound=True), X.M64) - self.assertEqual((v[0], v[16], v[17]), (0, 0, 116)) - - def test_inactive_source_fi_and_bound_ctrl(self): - # EXEC odd lanes off: lane 2 reads lane 1 (off). fi 0: bound_ctrl decides; fi 1: the inactive value is read. - shr = lambda **kw: run_dpp(X.dpp_op(2, 3, 4, "mov", control=("row_shr", 1), **kw), self.ODD)[0] - self.assertEqual(shr()[2], 7) - self.assertEqual(shr(bound=True)[2], 0) - self.assertEqual(shr(fi=True)[2], 101) - self.assertEqual(shr(fi=True, bound=True)[2], 101) - self.assertEqual(shr(fi=True)[1], 7) # lane 1 itself is off: never written - - def test_non_mov_unwritten_lane_keeps_old_vd(self): - # #238: an invalid source without bound_ctrl leaves the lane alone, not op(old vD, src1). - v, _ = run_dpp(X.dpp_op(2, 3, 4, "add", control=("row_shl", 2)), X.M64) - self.assertEqual((v[0], v[13], v[14], v[15]), (102 + 1000, 115 + 1013, 7, 7)) - - def test_row_and_bank_masks(self): - v, _ = run_dpp(X.dpp_op(2, 3, 4, "mov", control=("quad_perm", (0, 0, 0, 0)), row_mask=0x2, bank_mask=0x5), - X.M64) - written = [l for l in range(64) if v[l] != 7] - self.assertEqual(written, [16, 17, 18, 19, 24, 25, 26, 27]) - self.assertEqual(v[18], 116) - - def test_in_place_reads_every_source_first(self): - v, _ = run_dpp(X.dpp_op(2, 2, 4, "mov", control=("row_ror", 1)), X.M64) - self.assertEqual((v[0], v[1], v[16]), (115, 100, 131)) - - def test_dpp8_inactive_source(self): - bcast7 = (7,) * 8 - v, hyp = run_dpp(X.dpp_op(2, 3, 4, "mov", dpp8=bcast7), self.ODD) - self.assertEqual((v[0], v[8], v[1]), (0, 0, 7)) # lane 7 is off: 0 (the #238 hypothesis) - self.assertTrue(hyp) - v, hyp = run_dpp(X.dpp_op(2, 3, 4, "mov", dpp8=bcast7, fi=True), self.ODD) - self.assertEqual((v[0], v[8]), (107, 115)) - self.assertFalse(hyp) - - def test_row_share_and_xmask_wave32(self): - v, _ = run_dpp(X.dpp_op(2, 3, 4, "mov", control=("row_share", 5)), X.M32, size=32) - self.assertEqual((v[0], v[15], v[16], v[31]), (105, 105, 121, 121)) - v, _ = run_dpp(X.dpp_op(2, 3, 4, "xor", control=("row_xmask", 3)), X.M32, size=32) - self.assertEqual(v[5], (100 + 6) ^ 1005) - - def test_sweep_covers_every_control(self): - controls = X.dpp16_sweep_controls() - self.assertEqual(len(controls), 335) - self.assertEqual(len(set(controls)), 335) - for wave in (32, 64): - progs = X.dpp_sweep_programs(wave) - self.assertEqual(len(progs), 7206) - self.assertEqual(len({p.name for p in progs}), len(progs)) - self.assertEqual({p.family for p in progs}, set(X.DPP16_CONTROLS) | {"masks", "dpp8"}) - texts = [p.ops[1].text for p in progs] - for c, arg in controls: - text = X.dpp16_select(c, arg)[0] - self.assertTrue(any(f" {text} " in t for t in texts), text) - for kind in X.DPP_OPS.values(): - self.assertTrue(any(t.startswith(kind + "_dpp v2, v2,") or t.startswith(kind + "_dpp v2, v2 ") - for t in texts), kind) - masks = {re.search(r"row_mask:(0x\w+) bank_mask:(0x\w+)", t).groups() for t in texts if "row_mask" in t} - self.assertEqual(len(masks), 256) - for p in progs: - self.assertEqual(p.group, wave) - self.assertEqual([o.tag for o in p.ops], ["exec", "dpp"]) - p.expected() # the model runs every case - - def test_sweep_cli_needs_the_oracle_tools(self): - env = dict(os.environ, LEONIDA_AMD_CLANG=os.path.join(TOOLS, "no-such-clang.exe")) - r = subprocess.run([sys.executable, "-I", TOOL, "--oracle", "hw", "--dpp-sweep"], - capture_output=True, text=True, env=env) - self.assertEqual(r.returncode, 77, r.stdout + r.stderr) - - def test_sweep_on_hardware(self): - from hw_oracle import runner - try: - oracle = runner.open_oracle() - except runner.Unavailable as e: - self.skipTest(f"hardware oracle unavailable: {e}") - try: - stats, fails = {}, [] - progs = [p for wave in (32, 64) for p in X.dpp_sweep_programs(wave)[::97]] - X.run_hw(oracle, progs, stats, fails) - finally: - oracle.close() - self.assertEqual([(p.name, p.label, w) for p, _, w, _ in fails], []) - self.assertEqual(sum(st["match"] for st in stats.values()), len(progs)) - - -class Modes(unittest.TestCase): - """--modes takes native, emulate or both. Anything else used to run every program natively, wave64 included.""" - - def test_both_is_native_and_emulate(self): - self.assertEqual(X.parse_modes("both"), ["native", "emulate"]) - self.assertEqual(X.parse_modes("native,both"), ["native", "emulate"]) - - def test_list_keeps_order_and_drops_repeats(self): - self.assertEqual(X.parse_modes(" emulate, native ,emulate,"), ["emulate", "native"]) - - def test_unknown_or_empty_mode_is_rejected(self): - for text in ("emulat", "native,wave64", "", " , "): - with self.subTest(text=text), self.assertRaises(argparse.ArgumentTypeError): - X.parse_modes(text) - - def test_cli_rejects_an_unknown_mode_before_running(self): - r = subprocess.run([sys.executable, "-I", TOOL, "--modes", "emulat", "--self-test"], - capture_output=True, text=True) - self.assertEqual(r.returncode, 2, r.stdout + r.stderr) - self.assertIn("unknown mode 'emulat'", r.stderr) - - def test_emulate_with_wave32_is_a_usage_error(self): - # emulate runs a wave64 program as two 32-lane halves, so --wave 32 selects nothing to run: it used to print - # a bare `summary:` and exit 0. The refusal comes before the missing-harness check, so no build is needed. - r = subprocess.run([sys.executable, "-I", TOOL, "--wave", "32", "--modes", "emulate", "--programs", "1", - "--exe", os.path.join(TOOLS, "no-such-build", "vk_compute_test")], - capture_output=True, text=True) - self.assertEqual(r.returncode, 2, r.stdout + r.stderr) - self.assertIn("--modes emulate needs wave64 programs", r.stderr) - self.assertNotIn("vk_compute_test not found", r.stderr) - self.assertEqual(r.stdout, "") - - def test_wave64_native_without_w64_native_is_a_usage_error(self): - # A wave64 program runs natively only when --w64-native asks for the cross-half approximation; without it the - # selection was empty and the run ended after a bare `summary:` with exit 0. - r = subprocess.run([sys.executable, "-I", TOOL, "--wave", "64", "--modes", "native", "--programs", "1", - "--exe", os.path.join(TOOLS, "no-such-build", "vk_compute_test")], - capture_output=True, text=True) - self.assertEqual(r.returncode, 2, r.stdout + r.stderr) - self.assertIn("--w64-native", r.stderr) - self.assertNotIn("vk_compute_test not found", r.stderr) - self.assertEqual(r.stdout, "") - - def test_wave64_native_with_w64_native_reaches_the_harness_check(self): - # Not a usage error any more: the run gets as far as looking for vk_compute_test. - r = subprocess.run([sys.executable, "-I", TOOL, "--wave", "64", "--modes", "native", "--programs", "1", - "--w64-native", "--exe", os.path.join(TOOLS, "no-such-build", "vk_compute_test")], - capture_output=True, text=True) - self.assertEqual(r.returncode, 1, r.stdout + r.stderr) - self.assertIn("vk_compute_test not found", r.stderr) - - def test_one_wave_with_the_default_modes_reaches_the_harness_check(self): - # The default --modes is native,emulate: native runs every wave32 program and emulate every wave64 one, so - # neither --wave 32 nor --wave 64 is empty. Both used to be refused by the guards above, which fired when any - # selected mode had nothing to run instead of when all of them had. - for wave in ("32", "64"): - with self.subTest(wave=wave): - r = subprocess.run([sys.executable, "-I", TOOL, "--wave", wave, "--programs", "1", - "--exe", os.path.join(TOOLS, "no-such-build", "vk_compute_test")], - capture_output=True, text=True) - self.assertEqual(r.returncode, 1, r.stdout + r.stderr) - self.assertIn("vk_compute_test not found", r.stderr) - self.assertNotIn("nothing", r.stderr) - - def test_wave64_and_both_still_accept_emulate(self): - for wave in ("64", "both"): - with self.subTest(wave=wave): - r = subprocess.run([sys.executable, "-I", TOOL, "--wave", wave, "--modes", "emulate", "--self-test"], - capture_output=True, text=True) - self.assertEqual(r.returncode, 0, r.stdout + r.stderr) - self.assertIn("self-test OK", r.stdout) - - -class Counts(unittest.TestCase): - """--programs and --ops cannot be below 1: a run of no programs ended in a bare `summary:` with no lines and exit - 0, which reads as every program passing, and --ops 0 built a program with no ops. The other fuzzers refuse both.""" - - def run_tool(self, *args): - return subprocess.run([sys.executable, "-I", TOOL, *args], capture_output=True, text=True, timeout=300) - - def test_zero_or_negative_programs_is_a_usage_error(self): - for value in ("0", "-1", "-5"): - with self.subTest(programs=value): - r = self.run_tool("--programs", value, "--self-test") - self.assertEqual(r.returncode, 2, r.stdout + r.stderr) - self.assertIn(f"--programs: must be at least 1 (got {value})", r.stderr) - self.assertEqual(r.stdout, "") - - def test_zero_ops_is_a_usage_error(self): - r = self.run_tool("--ops", "0", "--self-test") - self.assertEqual(r.returncode, 2, r.stdout + r.stderr) - self.assertIn("--ops: must be at least 1 (got 0)", r.stderr) - self.assertEqual(r.stdout, "") - - def test_the_count_is_checked_before_the_harness_is_looked_for(self): - # Both are wrong here: a count below 1 is a usage error whatever the state of the build is. - r = self.run_tool("--exe", os.path.join(TOOLS, "no-such-build", "vk_compute_test"), "--programs", "0") - self.assertEqual(r.returncode, 2, r.stdout + r.stderr) - self.assertNotIn("vk_compute_test not found", r.stderr) - - def test_a_count_of_one_still_runs(self): - r = self.run_tool("--programs", "1", "--ops", "1", "--self-test") - self.assertEqual(r.returncode, 0, r.stdout + r.stderr) - self.assertIn("self-test OK", r.stdout) - - -class MissingHarness(unittest.TestCase): - """Without vk_compute_test the translator oracle stops with one line before any program is generated. It used to - translate for a while and then end in a FileNotFoundError traceback from the first GPU run.""" - - def run_tool(self, *extra, env=None): - with tempfile.TemporaryDirectory() as tmp: - exe = os.path.join(tmp, "no-such-build", "vk_compute_test.exe") - # LLVM_MC points nowhere too: the check has to come before anything that would need llvm-mc. - env = dict(os.environ, LLVM_MC=os.path.join(tmp, "no-such-llvm-mc"), **(env or {})) - r = subprocess.run([sys.executable, "-I", TOOL, "--exe", exe, "--programs", "2", *extra], - capture_output=True, text=True, env=env, timeout=300) - return exe, r - - def test_missing_exe_is_one_line_before_anything_runs(self): - exe, r = self.run_tool() - self.assertEqual(r.returncode, 1, r.stdout + r.stderr) - self.assertNotIn("Traceback", r.stderr) - self.assertIn(f"vk_compute_test not found at {exe}", r.stderr) - self.assertIn("--target vk_compute_test", r.stderr) - self.assertEqual(r.stdout, "") - - def test_hardware_oracle_alone_does_not_need_it(self): - _, r = self.run_tool("--oracle", "hw", env={"LEONIDA_AMD_CLANG": os.path.join(TOOLS, "no-such-clang.exe")}) - self.assertEqual(r.returncode, 77, r.stdout + r.stderr) - self.assertNotIn("vk_compute_test not found", r.stderr) - - def test_self_test_does_not_need_it(self): - _, r = self.run_tool("--self-test") - self.assertNotIn("vk_compute_test not found", r.stderr) - self.assertNotIn("Traceback", r.stderr) - - -class RelativeHarness(unittest.TestCase): - """A relative --exe written with "/" (runtime/build/RelWithDebInfo/vk_compute_test.exe) passes os.path.isfile, - but Windows' CreateProcess doesn't resolve it, so the first GPU run ended in a FileNotFoundError traceback. The - GPU runs now get an absolute path, also when the configuration subfolder is found for the path given.""" - - def test_a_relative_exe_reaches_the_gpu_runs_as_an_absolute_path(self): - seen = [] - with tempfile.TemporaryDirectory() as tmp: - os.makedirs(os.path.join(tmp, "build", "RelWithDebInfo")) - exe = os.path.join(tmp, "build", "RelWithDebInfo", "vk_compute_test.exe") - open(exe, "wb").close() - cwd = os.getcwd() - os.chdir(tmp) - try: - for given in ("build/RelWithDebInfo/vk_compute_test.exe", "build/vk_compute_test.exe"): - with self.subTest(exe=given), \ - mock.patch.object(X, "run_translator", lambda args, *rest: seen.append(args.exe)), \ - mock.patch.object(sys, "argv", ["crosslane_fuzz.py", "--exe", given, "--programs", "1"]), \ - contextlib.redirect_stdout(io.StringIO()): - X.main() - self.assertTrue(os.path.isabs(seen[-1]), seen[-1]) - self.assertTrue(os.path.samefile(seen[-1], exe), seen[-1]) - finally: - os.chdir(cwd) - self.assertEqual(len(seen), 2) - - -class GpuEnv(unittest.TestCase): - """FUZZ-13: vk_compute_test is asked for 32-wide subgroups for wave32 and emulated wave64 programs, as lds_fuzz.py - and valu_fuzz.py do. On AMD the compute default is 64, and a wave32 group over 32 lanes ran as one subgroup.""" - - def program(self, wave, group): - return X.Program("p", wave, group, [], {}, []) - - def test_wave32_asks_for_32(self): - env = X.gpu_env(self.program(32, 64), False, "d.bin", base={}) - self.assertEqual(env["VKC_SUBGROUP_SIZE"], "32") - - def test_emulated_wave64_asks_for_32(self): - env = X.gpu_env(self.program(64, 64), True, "d.bin", base={}) - self.assertEqual(env["VKC_SUBGROUP_SIZE"], "32") - - def test_native_wave64_keeps_the_device_default(self): - env = X.gpu_env(self.program(64, 64), False, "d.bin", base={"VKC_SUBGROUP_SIZE": "16"}) - self.assertEqual(env["VKC_SUBGROUP_SIZE"], "16") # whatever the caller had, untouched - self.assertNotIn("VKC_SUBGROUP_SIZE", X.gpu_env(self.program(64, 64), False, "d.bin", base={})) - - def test_buffer_size_and_dump(self): - env = X.gpu_env(self.program(32, 96), False, "out/d.bin", base={"KEEP": "1"}) - self.assertEqual(env["VKC_OUT_WORDS"], str(max(96 * len(X.OUT_REGS), 64))) - self.assertEqual(env["VKC_DUMP"], "out/d.bin") - self.assertEqual(env["KEEP"], "1") - self.assertEqual(X.gpu_env(self.program(32, 1), False, "d", base={})["VKC_OUT_WORDS"], - str(max(len(X.OUT_REGS), 64))) - - -class UnpinnedSubgroup(unittest.TestCase): - """A wave32 run vk_compute_test couldn't pin to 32 lanes is a skip; an emulated wave64 one is still compared.""" - - UNPINNED = "device: llvmpipe (LLVM 20.1.2, 256 bits) (subgroup 8..8)\ncompute subgroup size: 32 not available\n" - - def _run_gpu(self, prog, emulate, stdout): - def fake(cmd, **kw): - with open(kw["env"]["VKC_DUMP"], "wb") as f: - f.write(bytes(4 * prog.group * len(X.OUT_REGS))) - return subprocess.CompletedProcess(cmd, 0, stdout=stdout, stderr="") - with tempfile.TemporaryDirectory() as work, mock.patch.object(X.subprocess, "run", side_effect=fake): - return X.run_gpu("vk_compute_test", "p.spv", prog, work, emulate) - - def test_unpinned_wave32_raises(self): - with self.assertRaises(X.Unpinned) as ctx: - self._run_gpu(X.make_program(1, 32, 4), False, self.UNPINNED) - self.assertIn("can't run it at 32 lanes", str(ctx.exception)) - - def test_pinned_wave32_gives_its_words(self): - prog = X.make_program(1, 32, 4) - words = self._run_gpu(prog, False, "compute subgroup size: 32\n") - self.assertEqual(len(words), prog.group * len(X.OUT_REGS)) - - def test_emulated_wave64_gives_its_words(self): - prog = X.make_program(1, 64, 4) - words = self._run_gpu(prog, True, self.UNPINNED) - self.assertEqual(len(words), prog.group * len(X.OUT_REGS)) - - -class HardwareOracle(unittest.TestCase): - """--oracle hw: the native kernel text (no GPU needed) and the exit-77 contract.""" - - def test_hw_lines_resolve_branches_and_store_through_the_output_pointer(self): - for seed in range(40): - prog = X.make_program(seed, 64 if seed % 2 else 32, 24) - lines = prog.hw_lines(guard=False) - text = "\n".join(lines) - self.assertNotIn("@", text) - self.assertNotIn("buffer_store", text) - self.assertEqual(sum(ln.startswith("global_store_b32 v22, v20, s[2:3] offset:") for ln in lines), - len(X.OUT_REGS)) - self.assertEqual(lines[-1], "s_endpgm") - targets = re.findall(r"s_cbranch_\w+ (\.L\S+)", text) - for t in targets: - self.assertIn(t + ":", lines) - self.assertEqual(len(targets), len(set(targets))) - - def test_guard_follows_every_instruction_but_the_end(self): - prog = X.make_program(3, 32, 10) - plain, guarded = prog.hw_lines(guard=False), prog.hw_lines(guard=True) - labels = [ln for ln in plain if ln.endswith(":")] - self.assertEqual(len(guarded), 2 * (len(plain) - len(labels)) - 1 + len(labels)) - self.assertEqual([ln for ln in guarded if ln != "s_nop 7"], plain) - - def test_native_kernel_geometry(self): - from hw_oracle import asm - prog = X.make_program(5, 64, 8) - k = asm.Kernel(prog.hw_lines(), prog.wave, prog.group, prog.group * len(X.OUT_REGS), raw=True) - text, names, _ = asm.module_text([k], "gfx1150", wave=64) - self.assertIn(".amdhsa_wavefront_size32 0", text) - self.assertIn(".wavefront_size: 64", text) - text32, _, _ = asm.module_text([asm.Kernel(["s_endpgm"], 32, 32, 1, raw=True)], "gfx1150") - self.assertIn(".amdhsa_wavefront_size32 1", text32) - - def test_tool_exits_77_without_the_oracle_tools(self): - env = dict(os.environ, LEONIDA_AMD_CLANG=os.path.join(TOOLS, "no-such-clang.exe")) - r = subprocess.run([sys.executable, "-I", TOOL, "--oracle", "hw", "--programs", "2"], - capture_output=True, text=True, env=env) - self.assertEqual(r.returncode, 77, r.stdout + r.stderr) - self.assertIn("unavailable", r.stdout) - - def test_unknown_oracle_is_a_usage_error(self): - r = subprocess.run([sys.executable, "-I", TOOL, "--oracle", "gpu"], capture_output=True, text=True) - self.assertEqual(r.returncode, 2) - - def test_on_hardware(self): - from hw_oracle import runner - try: - oracle = runner.open_oracle() - except runner.Unavailable as e: - self.skipTest(f"hardware oracle unavailable: {e}") - try: - stats, fails = {}, [] - progs = [X.make_program(900 + i, (32, 64)[i % 2], 16, dpp=True) for i in range(12)] - X.run_hw(oracle, progs, stats, fails) - finally: - oracle.close() - self.assertEqual([(p.name, w) for p, _, w, _ in fails], []) - self.assertEqual(sum(st["programs"] for st in stats.values()), 12) - self.assertEqual(sum(st["match"] for st in stats.values()), 12) - for st in stats.values(): - self.assertEqual((st["mismatch"], st["hyp_only"], st["rejected"]), (0, 0, 0)) - -class HarnessErrors(unittest.TestCase): - """A program the GPU harness hangs or crashes on is one reported failure, not the end of the run.""" - - def test_timeout_is_a_harness_error(self): - prog = X.make_program(1, 32, 4) - with tempfile.TemporaryDirectory() as work, \ - mock.patch.object(X.subprocess, "run", side_effect=subprocess.TimeoutExpired(["x"], 60)): - with self.assertRaises(X.HarnessError) as ctx: - X.run_gpu("vk_compute_test", "p.spv", prog, work, False) - self.assertIn("timed out after 60 s", str(ctx.exception)) - - def test_missing_dump_is_a_harness_error_with_the_exit_code(self): - prog = X.make_program(1, 32, 4) - done = subprocess.CompletedProcess(["x"], 3, stdout="", stderr="device lost\n") - with tempfile.TemporaryDirectory() as work, mock.patch.object(X.subprocess, "run", return_value=done): - with self.assertRaises(X.HarnessError) as ctx: - X.run_gpu("vk_compute_test", "p.spv", prog, work, False) - self.assertIn("no dump (exit 3): device lost", str(ctx.exception)) - - def _main(self, run_gpu, argv): - """main() with the assembler, translator and GPU replaced: every program 'translates'.""" - def translate(work, emulate): - spdir = os.path.join(work, "spirv_emu" if emulate else "spirv_nat") - os.makedirs(spdir, exist_ok=True) - for name in names: - open(os.path.join(spdir, name + ".spv"), "wb").close() - return spdir, "" - - names = [] - out = io.StringIO() - with tempfile.TemporaryDirectory() as build: - exe = os.path.join(build, "vk_compute_test.exe") # only has to exist: run_gpu is replaced - open(exe, "wb").close() - with mock.patch.object(X, "assemble", side_effect=lambda mc, p, *a: names.append(p.name)), \ - mock.patch.object(X, "translate", side_effect=translate), \ - mock.patch.object(X, "run_gpu", side_effect=run_gpu), \ - mock.patch.object(sys, "argv", ["crosslane_fuzz.py", "--exe", exe] + argv), \ - contextlib.redirect_stdout(out): - code = X.main() - return code, out.getvalue() - - @staticmethod - def _expected_words(prog): - exp, _ = prog.expected() - words = [0] * (prog.group * len(X.OUT_REGS)) - for (tid, j), v in exp.items(): - words[tid * len(X.OUT_REGS) + j] = v - return words - - def test_run_goes_on_after_a_hang_and_exits_2(self): - calls = [] - - def run_gpu(exe, spv, prog, work, emulate): - calls.append(prog.name) - if len(calls) == 2: - raise X.HarnessError("vk_compute_test timed out after 60 s") - return self._expected_words(prog) - - with tempfile.TemporaryDirectory() as keep: - code, out = self._main(run_gpu, ["--programs", "4", "--wave", "32", "--modes", "native", - "--no-maskdata", "--keep", keep]) - kept = os.listdir(keep) - self.assertEqual(len(calls), 4) - self.assertEqual(code, 2) - self.assertIn(f"{calls[1]} [native] harness error: vk_compute_test timed out after 60 s", out) - self.assertIn("programs 4, match 3, mismatch 0, hyp_only 0, rejected 0, harness_errors 1", out) - self.assertEqual(kept, [f"{calls[1]}_native.asm"]) - - def test_every_program_skipped_exits_2(self): - def run_gpu(exe, spv, prog, work, emulate): - raise X.Unpinned("the device can't run it at 32 lanes") - - code, out = self._main(run_gpu, ["--programs", "4", "--wave", "32", "--modes", "native"]) - self.assertEqual(code, 2) - self.assertIn("harness_errors 0, skipped 4", out) - self.assertIn("no program ran", out) - self.assertNotIn("mismatch;", out) - - def test_skips_beside_matches_exit_0(self): - def run_gpu(exe, spv, prog, work, emulate): - if prog.wave == 32: - raise X.Unpinned("the device can't run it at 32 lanes") - return self._expected_words(prog) - - code, out = self._main(run_gpu, ["--programs", "4", "--wave", "both", "--no-maskdata"]) - self.assertEqual(code, 0, out) - self.assertIn("wave32 native: programs 2, match 0, mismatch 0, hyp_only 0, rejected 0, harness_errors 0, " - "skipped 2", out) - self.assertIn("wave64 emulate: programs 2, match 2", out) - - def test_clean_run_still_exits_0(self): - code, out = self._main(lambda exe, spv, prog, work, emulate: self._expected_words(prog), - ["--programs", "3", "--wave", "32", "--modes", "native", "--no-maskdata"]) - self.assertEqual(code, 0) - self.assertIn("match 3, mismatch 0, hyp_only 0, rejected 0, harness_errors 0", out) - - -def mask_name(text): - """'vcc' / 'exec' / the first SGPR of 's[16:17]', as Wave.mask takes it.""" - m = re.fullmatch(r"s\[(\d+):\d+\]", text) - return int(m.group(1)) if m else text - - -def ext_gen(seed=1, group=64): - g = X.Gen(random.Random(seed), 64, group, ext=True) - g.masks += ["vcc", 16, 18, 20] - return g - - -class Ext(unittest.TestCase): - """--ext: the wave64 extension ops, each against values worked out by hand from the rule in the docstring.""" - - def test_only_wave64_programs_change(self): - self.assertEqual(X.make_program(5, 32, 24, ext=True).source(), X.make_program(5, 32, 24).source()) - a, b = X.make_program(5, 64, 24, ext=True), X.make_program(5, 64, 24, ext=True) - self.assertEqual(a.source(), b.source()) - self.assertEqual(a.expected()[0], b.expected()[0]) - self.assertNotEqual(a.source(), X.make_program(5, 64, 24).source()) - g32 = X.Gen(random.Random(1), 32, 32, ext=True) - for name, _ in X.Gen.EXT_WEIGHTS: - self.assertIsNone(getattr(g32, name)(), name) - - def test_every_ext_op_is_generated(self): - seen = set() - for seed in range(60): - p = X.make_program(seed, 64, 24, ext=True) - p.expected() # the model runs every op - seen |= {t for o in p.ops for t in getattr(o, "tags", {o.tag})} - self.assertLessEqual({"scan64", "mask_scc", "cselect64", "mask_test", "bfm", "wqm", "carry", "bpermute", - "permute", "swizzle", "lane_wrap", "loop"}, seen) - - def test_carry_in_and_out(self): - # 0xffffffff + 0 + carry-in: the sum wraps to 0 and carries exactly where the carry-in is set. Lanes 48-63 - # are off: they keep vD and their carry-out bit is 0. - o = draw(ext_gen(), "op_carry", lambda o: o.text.startswith("v_add_co_ci_u32_e64") and - len(set(operands(o.text)[i] for i in (0, 2, 3))) == 3) - d, mo, a, b, mi = operands(o.text) - d, a, b = int(d[1:]), int(a[1:]), int(b[1:]) - w = wave() - w.exec = (1 << 48) - 1 - w.v[a], w.v[b], w.v[d] = [0xFFFFFFFF] * 64, [0] * 64, [7] * 64 - w.set_mask(mask_name(mi), 0xFFFF0000FFFF00F0) - o.apply([w]) - self.assertEqual(w.mask(mask_name(mo)), 0x00000000FFFF00F0) - self.assertEqual([w.vr(d)[l] for l in (0, 4, 15, 16, 31, 47, 48, 63)], - [0xFFFFFFFF, 0, 0xFFFFFFFF, 0, 0, 0xFFFFFFFF, 7, 7]) - - def test_subrev_borrow(self): - # v_subrev_co: D = S1 - S0; 5 - 9 borrows, 9 - 5 does not. - o = draw(ext_gen(2), "op_carry", lambda o: o.text.startswith("v_subrev_co_u32_e64") and - len(set(operands(o.text)[i] for i in (0, 2, 3))) == 3) - d, mo, a, b = operands(o.text) - d, a, b = int(d[1:]), int(a[1:]), int(b[1:]) - w = wave() - w.v[a] = [9 if l < 40 else 5 for l in range(64)] - w.v[b] = [5 if l < 40 else 9 for l in range(64)] - o.apply([w]) - self.assertEqual(w.mask(mask_name(mo)), (1 << 40) - 1) - self.assertEqual((w.vr(d)[0], w.vr(d)[63]), (0xFFFFFFFC, 4)) - - def test_bpermute_stays_in_its_half_and_reads_0_from_an_inactive_lane(self): - o = draw(ext_gen(3), "op_bpermute", lambda o: "offset" not in o.text and - len(set(operands(o.text.split("\n")[0]))) == 3) - d, ad, dat = (int(t[1:]) for t in operands(o.text.split("\n")[0])) - self.assertEqual(o.text.split("\n")[1].strip(), "s_waitcnt lgkmcnt(0)") - w = wave() - w.exec = X.M64 & ~(1 << 5) & ~(1 << 40) - w.v[ad] = [4 * (l + 1) for l in range(64)] # lane l reads lane (l + 1) & 31 of its half - w.v[dat] = [100 + l for l in range(64)] - w.v[d] = [7] * 64 - o.apply([w]) - got = w.vr(d) - self.assertEqual([got[l] for l in (0, 4, 5, 6, 31, 32, 39, 40, 63)], [101, 0, 7, 107, 100, 133, 0, 7, 132]) - - def test_permute_scatters_and_the_highest_sender_wins(self): - g = ext_gen(4) - o = draw(g, "op_permute", lambda o: o.text.startswith("ds_permute_b32") and "offset" not in o.text and - len(set(operands(o.text.split("\n")[0]))) == 3) - d, ad, dat = (int(t[1:]) for t in operands(o.text.split("\n")[0])) - w = wave() - w.v[dat] = [100 + l for l in range(64)] - w.v[ad] = [0] * 64 # every lane sends to lane 0 of its half - o.apply([w]) - self.assertEqual([w.vr(d)[l] for l in (0, 1, 31, 32, 33)], [131, 0, 0, 163, 0]) - w.v[ad] = [4 * (l ^ 1) for l in range(64)] # a permutation: lane l sends to lane l ^ 1 - w.v[d] = [7] * 64 - w.exec = X.M64 & ~(1 << 2) # lane 2 neither sends nor is written - o.apply([w]) - self.assertEqual([w.vr(d)[l] for l in (0, 1, 2, 3, 62)], [101, 100, 7, 0, 163]) - - def test_permute_with_generated_addresses_is_a_permutation(self): - o = draw(ext_gen(5), "op_permute", lambda o: o.text.startswith("v_mad_u32_u24") and - len(set(operands(o.text.split("\n")[2].split(" offset")[0]))) == 3) - d, ad, dat = (int(t[1:]) for t in operands(o.text.split("\n")[2].split(" offset")[0])) - self.assertEqual(ad, X.PERM_V) - w = wave() - w.v[1] = list(range(64)) - w.v[dat] = [100 + l for l in range(64)] - o.apply([w]) - self.assertEqual(sorted(w.vr(d)[:32]), [100 + l for l in range(32)]) # each half is permuted in itself - self.assertEqual(sorted(w.vr(d)[32:]), [132 + l for l in range(32)]) - - def test_swizzle_modes(self): - g = ext_gen(6) - rev = draw(g, "op_swizzle", lambda o: "swizzle(REVERSE,8)" in o.text and - len(set(operands(o.text.split(" offset")[0]))) == 2) - d, v = (int(t[1:]) for t in operands(rev.text.split(" offset")[0])) - w = wave() - w.v[v] = [100 + l for l in range(64)] - self.assertFalse(rev.apply([w])) - self.assertEqual([w.vr(d)[l] for l in (0, 7, 8, 33)], [107, 100, 115, 138]) - w.exec = X.M64 & ~(1 << 7) # lane 0's source is off: it reads 0, reported apart - self.assertTrue(rev.apply([w])) - self.assertEqual((w.vr(d)[0], w.vr(d)[1]), (0, 106)) - quad = draw(g, "op_swizzle", lambda o: "QUAD_PERM" in o.text and - len(set(operands(o.text.split(" offset")[0]))) == 2) - d, v = (int(t[1:]) for t in operands(quad.text.split(" offset")[0])) - q = [int(x) for x in re.search(r"QUAD_PERM, (\d), (\d), (\d), (\d)", quad.text).groups()] - w = wave() - w.v[v] = [100 + l for l in range(64)] - quad.apply([w]) - self.assertEqual([w.vr(d)[l] for l in (0, 5, 62)], [100 + q[0], 104 + q[1], 160 + q[2]]) - bits = draw(g, "op_swizzle", lambda o: "BITMASK_PERM" in o.text and - len(set(operands(o.text.split(" offset")[0]))) == 2) - pat = re.search(r'BITMASK_PERM, "([01pi]{5})"', bits.text).group(1) - d, v = (int(t[1:]) for t in operands(bits.text.split(" offset")[0])) - w = wave() - w.v[v] = [100 + l for l in range(64)] - bits.apply([w]) - lane = 37 # lane 5 of the upper half - src = 0 - for i, ch in enumerate(pat): # bit 4 first - bit = 1 << (4 - i) - own = (lane & 31) & bit - src |= bit if ch == "1" else 0 if ch == "0" else own if ch == "p" else own ^ bit - self.assertEqual(w.vr(d)[lane], 100 + (32 | src), pat) - - def test_lane_select_wraps_at_64(self): - o = draw(ext_gen(7), "op_lane_wrap", lambda o: "v_readlane_b32" in o.text) - enc = int(re.search(r"s_mov_b32 s28, (\d+)", o.text).group(1)) - d, v = re.search(r"v_readlane_b32 s(\d+), v(\d+), s28", o.text).groups() - self.assertGreaterEqual(enc, 64) - w = wave() - w.v[int(v)] = [100 + l for l in range(64)] - o.apply([w]) - self.assertEqual(w.s[int(d)], 100 + (enc & 63)) - - def probe(self, text): - d, a, b = (int(x) for x in re.search(r"s_cselect_b32 s(\d+), s(\d+), s(\d+)", text).groups()) - return d, a, b - - def test_wrexec_and_saveexec_forms(self): - g = ext_gen(8) - wr = draw(g, "op_exec_logic", lambda o: o.text.startswith("s_andn2_wrexec_b64")) - dst, src = (mask_name(t) for t in operands(wr.text.split("\n")[0])) - w = wave() - w.exec = 0x00FF - w.set_mask(src, 0x0FF0) - wr.apply([w]) # EXEC = S0 & ~EXEC; D = EXEC - self.assertEqual((w.exec, w.mask(dst)), (0x0F00, 0x0F00)) - nor = draw(g, "op_exec_logic", lambda o: o.text.startswith("s_nor_saveexec_b64")) - dst, src = (mask_name(t) for t in operands(nor.text.split("\n")[0])) - w = wave() - w.exec = X.M64 & ~0xFF - w.set_mask(src, 0xF0) - nor.apply([w]) # D = EXEC; EXEC = ~(S0 | EXEC) = lanes 0-3 - self.assertEqual((w.exec, w.mask(dst)), (0x0F, X.M64 & ~0xFF)) - partial = X.Gen(random.Random(8), 64, 40, ext=True) - partial.masks += [16] - for _ in range(300): # a partial wave never gets a form that complements a mask - self.assertNotRegex(partial.op_exec_logic().text, r"s_(orn1|orn2|nand|nor|xnor)_") - - def test_bfm_and_wqm(self): - g = ext_gen(9) - bfm = draw(g, "op_bfm", lambda o: re.fullmatch(r"s_bfm_b64 s\[\d+:\d+\], s(\d+), s(\d+)", o.text) and - len(set(operands(o.text)[1:])) == 2) - dst, sa, sb = operands(bfm.text) - w = wave() - w.s[int(sa[1:])], w.s[int(sb[1:])] = 64 + 5, 128 + 40 # size 5 at offset 40: the counts are taken mod 64 - bfm.apply([w]) - self.assertEqual(w.mask(mask_name(dst)), 0x1F << 40) - wqm = draw(g, "op_wqm", lambda o: len(set(operands(o.text.split("\n")[0]))) == 2) - dst, src = (mask_name(t) for t in operands(wqm.text.split("\n")[0])) - w = wave() - if src == "exec": - w.exec = 0x0000000100000100 - else: - w.set_mask(src, 0x0000000100000100) - wqm.apply([w]) - self.assertEqual(w.mask(dst), 0x0000000F00000F00) - self.assertIsNone(X.Gen(random.Random(1), 64, 40, ext=True).op_bfm()) # full waves only - - def test_mask_scan_and_tests(self): - g = ext_gen(10) - ff0 = draw(g, "op_scan64", lambda o: o.text.startswith("s_ff0_i32_b64") and "exec" not in o.text) - d, m = operands(ff0.text) - w = wave() - w.set_mask(mask_name(m), (1 << 37) - 1) - ff0.apply([w]) - self.assertEqual(w.s[int(d[1:])], 37) - w.set_mask(mask_name(m), X.M64) - ff0.apply([w]) - self.assertEqual(w.s[int(d[1:])], 0xFFFFFFFF) - bit = draw(g, "op_mask_test", lambda o: o.text.startswith("s_bitcmp1_b64") and "exec" not in o.text and - len(set(self.probe(o.text))) == 3) - m, lane = operands(bit.text.split("\n")[0]) - d, a, b = self.probe(bit.text) # s_cselect_b32 sD, sA, sB: D = SCC ? A : B - w = wave() - w.s[a], w.s[b] = 111, 222 - w.set_mask(mask_name(m), 1 << int(lane)) - bit.apply([w]) - self.assertEqual(w.s[d], 111) - w.set_mask(mask_name(m), X.M64 & ~(1 << int(lane))) - bit.apply([w]) - self.assertEqual(w.s[d], 222) - - def test_loop_runs_each_lane_its_own_trip_count(self): - # Trip limit = lane & 3, all 64 lanes on: 64, 48, 32 and 16 lanes run iterations 1 to 4, and each lane adds - # the count of every iteration it runs: 64, 112, 144 or 160. - g = ext_gen(11) - g.LOOP_BODY = ("op_salu",) - loop = draw(g, "op_loop", lambda o: o.text.startswith("v_and_b32_e32 v24, 3, v") and - re.search(r"v_and_b32_e32 v24, 3, v(\d+)", o.text).group(1) != - re.search(r"v_add_nc_u32_e32 v(\d+), s\d+, v\d+", o.text).group(1)) - src = int(re.search(r"v_and_b32_e32 v24, 3, v(\d+)", loop.text).group(1)) - vx = int(re.search(r"v_add_nc_u32_e32 v(\d+), s\d+, v\d+", loop.text).group(1)) - k = re.search(r";@LOOP(\d+)", loop.text).group(1) - self.assertIn(f"s_cbranch_execnz @-{k}", loop.text) - w = wave() - w.v[src] = list(range(64)) - w.v[vx] = [1000] * 64 - loop.apply([w]) - self.assertEqual(w.exec, X.M64) # EXEC comes back from the break mask - self.assertEqual(w.mask(X.LOOP_S[0]), X.M64) - self.assertEqual([w.vr(vx)[l] for l in (0, 1, 2, 3, 60, 63)], [1064, 1112, 1144, 1160, 1064, 1160]) - w = wave() # a wave that enters with EXEC 0 runs the body once - w.exec = 0 - w.v[vx] = [1000] * 64 - loop.apply([w]) - self.assertEqual((w.exec, w.vr(vx)[0]), (0, 1000)) - - def test_branch_offsets_forward_and_back(self): - lines = ["a", ";@LOOP0", "b", "c", "s_cbranch_execnz @-0", "s_cbranch_execz @1", "d", ";@END1", "e"] - sizes = {0: 1, 2: 1, 3: 2, 4: 1, 5: 1, 6: 3, 8: 1} - out = X.branch_offsets(lines, sizes) - self.assertEqual(out[4], "s_cbranch_execnz -4") # back over b, c and the branch itself - self.assertEqual(out[5], "s_cbranch_execz 3") # forward over d - self.assertEqual([out[i] for i in (0, 1, 2, 3, 6, 7, 8)], [lines[i] for i in (0, 1, 2, 3, 6, 7, 8)]) - - def test_native_kernel_has_a_label_for_every_loop(self): - loops = 0 - for seed in range(40): - prog = X.make_program(seed, 64, 24, ext=True) - plain, guarded = prog.hw_lines(guard=False), prog.hw_lines(guard=True) - text = "\n".join(plain) - self.assertNotIn("@", text) - targets = re.findall(r"s_cbranch_\w+ (\.L\S+)", text) - for t in targets: - self.assertIn(t + ":", plain) - self.assertEqual(len(targets), len(set(targets))) - back = [t for t in targets if re.search(r"_B\d+$", t)] - loops += len(back) - for t in back: # a loop's label is above its branch - self.assertLess(plain.index(t + ":"), plain.index(f"s_cbranch_execnz {t}")) - labels = [ln for ln in plain if ln.endswith(":")] - self.assertEqual(len(guarded), 2 * (len(plain) - len(labels)) - 1 + len(labels)) - self.assertGreater(loops, 10) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/test_cs_wave_probe_spv.py b/tests/test_cs_wave_probe_spv.py deleted file mode 100644 index 4ed930ac7..000000000 --- a/tests/test_cs_wave_probe_spv.py +++ /dev/null @@ -1,47 +0,0 @@ -"""runtime/test/cs_wave_probe_spv.h is the SPIR-V of runtime/test/glsl/cs_wave_probe.comp (vk_compute_test's -subgroup probe). Run: python -I tests/test_cs_wave_probe_spv.py""" -import os -import re -import shutil -import struct -import subprocess -import tempfile -import unittest - -ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) -HEADER = os.path.join(ROOT, "runtime", "test", "cs_wave_probe_spv.h") -SOURCE = os.path.join(ROOT, "runtime", "test", "glsl", "cs_wave_probe.comp") - - -def header_words(): - with open(HEADER, encoding="utf-8") as f: - return [int(x, 16) for x in re.findall(r"0x([0-9a-f]{8})u", f.read())] - - -class WaveProbeSpirv(unittest.TestCase): - def test_header_is_spirv_1_5(self): - # Below 1.6, so varying subgroup sizes are not allowed in the probe either (as in the translator's output). - w = header_words() - self.assertEqual(w[0], 0x07230203) - self.assertEqual(w[1], 0x00010500) - - def test_header_matches_the_glsl(self): - glslang = shutil.which("glslangValidator") - if not glslang: - self.skipTest("glslangValidator is not on PATH") - version = subprocess.run([glslang, "--version"], capture_output=True, text=True).stdout - if "16.6.0" not in version: # another glslang may emit other (equally valid) code - self.skipTest("the header was generated with glslang 16.6.0") - with tempfile.TemporaryDirectory() as tmp: - out = os.path.join(tmp, "cs_wave_probe.spv") - subprocess.run([glslang, "-V", "--target-env", "vulkan1.2", "-Os", "-o", out, SOURCE], check=True, - stdout=subprocess.DEVNULL) - with open(out, "rb") as f: - data = f.read() - words = list(struct.unpack(f"<{len(data) // 4}I", data)) - # Word 2 is the generator (glslang's version); the rest must be what the header holds. - self.assertEqual(words[:2] + words[3:], header_words()[:2] + header_words()[3:]) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/test_csv_line_endings.py b/tests/test_csv_line_endings.py deleted file mode 100644 index 8b883349d..000000000 --- a/tests/test_csv_line_endings.py +++ /dev/null @@ -1,70 +0,0 @@ -"""CSV reports must have the same bytes on every platform. - -`csv.writer` defaults to `lineterminator="\\r\\n"`, so a tool that leaves it at the default writes CRLF on Windows and -LF everywhere else, and the same archive gives different report bytes depending on the machine that exported it. -`tools/awc_manifest.py` and `tools/awc_shorts.py` pass `lineterminator="\\n"` and `tools/bink_index.py` documents why -its stdout writer needs it; this test keeps every other writer on the same convention. No game files are read. -""" -import os -import re -import subprocess -import sys -import tempfile -import unittest - -ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) -TOOLS = os.path.join(ROOT, "tools") - -# Every csv writer call in tools/, with the two lines that may continue it. -WRITER = re.compile(r"\bcsv\.(?:Dict)?[Ww]riter\(") - - -def writer_calls(): - """Yield (file, line number, the call's source text) for every csv writer constructed in tools/.""" - for name in sorted(os.listdir(TOOLS)): - if not name.endswith(".py"): - continue - path = os.path.join(TOOLS, name) - with open(path, encoding="utf-8") as f: - lines = f.read().splitlines() - for index, line in enumerate(lines): - if WRITER.search(line): - yield name, index + 1, "\n".join(lines[index:index + 3]) - - -class CsvTerminatorTest(unittest.TestCase): - def test_every_csv_writer_sets_an_lf_terminator(self): - missing = [f"{name}:{line}" for name, line, source in writer_calls() - if 'lineterminator="\\n"' not in source] - self.assertEqual(missing, [], "csv writers without lineterminator='\\n' (CRLF on Windows)") - - def run_tool(self, tool, source): - out = os.path.join(self.work, os.path.splitext(tool)[0] + ".csv") - result = subprocess.run([sys.executable, "-I", os.path.join(TOOLS, tool), source, out], - capture_output=True, text=True, check=False) - self.assertEqual(result.returncode, 0, result.stderr) - self.assertTrue(os.path.isfile(out), result.stdout) - with open(out, "rb") as f: - return f.read() - - def setUp(self): - self.temp = tempfile.TemporaryDirectory() - self.work = self.temp.name - self.source = os.path.join(self.work, "empty") - os.makedirs(self.source) - - def tearDown(self): - self.temp.cleanup() - - def test_csv_reports_have_no_carriage_return(self): - # These three scan a folder and write a header even when it holds nothing, so they need no archive. - for tool in ("page_index.py", "rbf0_index.py", "restofworld_index.py"): - with self.subTest(tool=tool): - data = self.run_tool(tool, self.source) - self.assertNotIn(b"\r", data, f"{tool} wrote a carriage return") - self.assertTrue(data.endswith(b"\n"), f"{tool} did not end its last row with a newline") - self.assertTrue(data.count(b"\n") >= 1) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/test_ctest_registration.py b/tests/test_ctest_registration.py deleted file mode 100644 index 583703baa..000000000 --- a/tests/test_ctest_registration.py +++ /dev/null @@ -1,105 +0,0 @@ -"""Every test executable the runtime builds must be registered with ctest. - -``add_executable(foo_test ...)`` without an ``add_test(... COMMAND foo_test)`` builds -the test but never runs it -- in ``ctest``, in the Windows runtime job or under Wine. -This happened to ``d3d12_indirect_rt_test``; the only intentional exception is -``d3d12_clear_test`` (see the comment next to its target in runtime/cmake/d3d12_vulkan.cmake). -""" -import os -import re -import sys -import unittest -from pathlib import Path - -ROOT = Path(__file__).resolve().parent.parent -sys.path.insert(0, str(ROOT / "tests")) -import runtime_cmake # noqa: E402 - -CMAKE = Path(os.environ.get("LEONIDA_RUNTIME_CMAKE", str(ROOT / "runtime" / "CMakeLists.txt"))) -SOURCE = Path(os.environ.get("LEONIDA_RUNTIME_TEST_SOURCE", - str(ROOT / "runtime" / "test" / "d3d12_indirect_rt_test.cpp"))) - -# d3d12_clear_test is deliberately run by hand until #521's tie rounding lands. -NOT_IN_CTEST = {"d3d12_clear_test"} - - -def built_test_executables(text): - return {name for name in re.findall(r"add_executable\(\s*([A-Za-z0-9_]+)", text) - if name.endswith("_test")} - - -def registered_commands(text): - # add_test may span lines, e.g. add_test(NAME x\n COMMAND foo_test ...). - return set(re.findall(r"add_test\([^)]*?\bCOMMAND\s+\"?([A-Za-z0-9_]+)", text, re.S)) - - -class CTestRegistrationTest(unittest.TestCase): - @classmethod - def setUpClass(cls): - cls.cmake = runtime_cmake.read(CMAKE) - - def test_all_test_executables_have_an_add_test(self): - missing = built_test_executables(self.cmake) - registered_commands(self.cmake) - NOT_IN_CTEST - self.assertEqual(missing, set(), f"built but never run by ctest: {sorted(missing)}") - - def test_the_exception_is_still_the_only_one(self): - # An allowlist that grows unnoticed is how this bug happens again. - self.assertEqual(NOT_IN_CTEST & built_test_executables(self.cmake), {"d3d12_clear_test"}) - - def test_indirect_rt_skips_with_the_ctest_skip_code(self): - self.assertTrue( - "add_test(NAME d3d12_indirect_rt COMMAND d3d12_indirect_rt_test)" in self.cmake, - "d3d12_indirect_rt_test is built but not registered with ctest", - ) - self.assertTrue( - "set_tests_properties(d3d12_indirect_rt PROPERTIES SKIP_RETURN_CODE 77)" in self.cmake, - "d3d12_indirect_rt must skip with 77 on a machine without a Vulkan GPU", - ) - - lines = SOURCE.read_text(encoding="utf-8").splitlines() - skips = [] - for i, line in enumerate(lines): - if 'std::printf("SKIP:' in line: - # The path's own return, not a conditional one inside it (a LEONIDA_VK_DEVICE filter that matches - # nothing fails with `if (!filter.empty()) return 1;` just before the skip's `return 77;`). - codes = [int(m) for l in lines[i:i + 7] if "if (" not in l for m in re.findall(r"return (\d+);", l)] - skips.append(codes[0] if codes else None) - # no loader, no ICD, no Vulkan 1.3 GPU -- all three are a ctest SKIP, not a failure. - self.assertEqual(len(skips), 3, f"expected three whole-test SKIP paths, got {len(skips)}") - self.assertEqual(skips, [77, 77, 77], "SKIP paths must return 77 for SKIP_RETURN_CODE 77") - - def test_whole_test_skips_return_the_skip_code(self): - # A test registered with SKIP_RETURN_CODE 77 that prints SKIP and returns 0 is counted as passed although it - # checked nothing: bink_audio_test did that for a movie without audio tracks after #1580. - wrong = whole_test_skips_not_77(self.cmake, ROOT / "runtime") - self.assertEqual(wrong, [], f"SKIP followed by a return code other than 77: {wrong}") - - -def whole_test_skips_not_77(cmake_text, runtime_dir): - """[(source:line, code)] for a SKIP print directly followed by `return N;` (N != 77) in the sources of a test - registered with SKIP_RETURN_CODE 77. A SKIP print with no return right after it skips one section, not the test.""" - skip_tests = set(re.findall(r"set_tests_properties\(\s*([A-Za-z0-9_]+)\s+PROPERTIES[^)]*SKIP_RETURN_CODE\s+77", - cmake_text)) - commands = dict(re.findall(r"add_test\(\s*NAME\s+([A-Za-z0-9_]+)\s+COMMAND\s+\"?([A-Za-z0-9_]+)", cmake_text)) - wrong = [] - for test in sorted(skip_tests): - exe = commands.get(test) - m = exe and re.search(r"add_executable\(\s*" + re.escape(exe) + r"\b([^)]*)\)", cmake_text) - if not m: - continue - for src in re.findall(r"(test/[A-Za-z0-9_./]+\.cpp)", m.group(1)): - path = runtime_dir / src - if not path.is_file(): - continue - lines = path.read_text(encoding="utf-8", errors="replace").splitlines() - for i, line in enumerate(lines): - if not re.search(r'(printf|puts)\(\s*"SKIP', line): - continue - after = re.match(r"\s*return\s+(\w+)\s*;", lines[i + 1]) if i + 1 < len(lines) else None - if after and after.group(1) != "77": - wrong.append((f"{src}:{i + 2}", after.group(1))) - return wrong - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/test_cube_sample.py b/tests/test_cube_sample.py deleted file mode 100644 index 7dee329c8..000000000 --- a/tests/test_cube_sample.py +++ /dev/null @@ -1,94 +0,0 @@ -"""Cube samples in tools/rdna2spirv.py. - -The hardware takes a cube sample's s and t in [1, 2] (sc / |cubema| + 1.5) and its third coordinate as 8 * slice + face -(Mesa ac_nir_lower_tex_coords.c, AMD LLPC ImageBuilder.cpp). The translator samples a 6-layer 2D-array view instead, -so it passes s - 1, t - 1 and layer 6 * slice + face. These tests evaluate the coordinate the SPIR-V hands to the -sample; runtime/test/shaders/ps_cube_sample.asm checks the result on a GPU. -""" -import math -import re -import struct - -import pytest - -from listing import translate_listing - - -def f32(x): - return struct.unpack(" even - self.assertEqual(run("v_cvt_flr_i32_f32_e32 v8, -2.0")[0], 0xFFFFFFFE) - self.assertEqual(run("v_cvt_flr_i32_f32_e64 v8, -3")[0], 0x80000000) # 0xfffffffd is a negative NaN - self.assertEqual(run("v_cvt_flr_i32_f32_e64 v8, 23")[0], 0) # a denormal word - self.assertEqual(run("v_cvt_norm_u16_f16_e32 v8, 0x3c00")[0], 0xFFFF) - self.assertEqual(run("v_cvt_pknorm_u16_f16 v8, 1.0, 0.5")[0], 0x8000FFFF) - - def test_line_parsing(self): - self.assertEqual(c.split_line("v_cvt_pknorm_i16_f16 v8, -|v9|, s4 op_sel:[1,0,0]"), - ("v_cvt_pknorm_i16_f16", "v_cvt_pknorm_i16_f16", ["v8", "-|v9|", "s4"], ["op_sel:[1,0,0]"])) - self.assertEqual(c.split_line("v_cvt_norm_u16_f16_e64 v9, |v10| clamp mul:2"), - ("v_cvt_norm_u16_f16", "v_cvt_norm_u16_f16_e64", ["v9", "|v10|"], ["clamp", "mul:2"])) - - def test_unmodelled_forms_raise(self): - for bad in ("v_cvt_pknorm_i16_f32 v8, v9, v10 op_sel:[1,0,0]", - "v_cvt_pknorm_i16_f32 v8, v9, v10 op_sel:[0,0,1]", - "v_cvt_pknorm_u16_f16 v8, 1.0, v10 op_sel:[1,0,0]", - "v_cvt_flr_i32_f32_e64 v8, -|v9", - "v_cvt_rpi_i32_f32_e64 s8, v9", - "v_cvt_f32_i32 v8, v9"): - with self.subTest(line=bad), self.assertRaises(c.HarnessError): - run(bad) - - -class Generator(unittest.TestCase): - def test_generation_is_deterministic(self): - self.assertEqual(c.program(random.Random(5), 6), c.program(random.Random(5), 6)) - self.assertNotEqual(c.program(random.Random(5), 6), c.program(random.Random(6), 6)) - - def test_ops_subset_is_respected(self): - rng = random.Random(1) - ops = ["v_cvt_rpi_i32_f32", "v_cvt_pknorm_u16_f16"] - for _ in range(30): - _, used = c.program(rng, 4, ops) - self.assertTrue(set(used) <= set(ops)) - self.assertEqual({op for op, *_ in c.sweep_ops(ops)}, set(ops)) - - def test_sweep_size(self): - # flr/rpi: 5 _e32 kinds + 11 _e64 (4 modifiers on the 2 register kinds, 3 constant kinds); - # norm adds the 6 output modifier settings per kind (30); pk32: 120 encodable kind/modifier pairs + clamp on - # 24 kind pairs; pk16: ((2 register kinds x 4 modifiers x 2 halves + 3)^2 - 1 (two literals)) x 2 destination - # halves, + clamp on the 24 kind pairs with each destination half - self.assertEqual(len(c.sweep_ops()), 2 * 16 + 2 * 46 + 2 * 144 + 2 * (2 * 360 + 2 * 24)) - - def test_edge_grid(self): - self.assertEqual(len(c.F32_TIES), 2 * 24 * 3) - for h in (0x3801, 0x3802, 0x3803, 0x3804, 0xB801, 0xB802): # the f16 double-rounding traps - self.assertIn(h, c.F16_TIES) - cases = c.grid_cases() - self.assertEqual(len(cases), - 4 * (len(c.F32_EDGES) + len(c.F32_TIES)) + 4 * (len(c.F16_EDGES) + len(c.F16_TIES))) - rng = random.Random(0) - by_op = {} - for case in cases: - by_op.setdefault(case[0], []).append(case) - for op, op_cases in by_op.items(): - kind, snorm = c.FAMILY[op] - chunk = op_cases[:4] - words = run(*c.grid_program(chunk, rng)) - for i, ((_, a, b), got) in enumerate(zip(chunk, words)): - if kind in ("flr", "rpi"): - want = c.to_i32(a, kind == "rpi") - elif kind == "norm": - want = 0xA5A50000 | c.normalize(c.f16_value(a), snorm) - elif kind == "pk32": - want = c.normalize(c.f32_value(a), snorm) | c.normalize(c.f32_value(b), snorm) << 16 - else: - want = c.normalize(c.f16_value(a), snorm) | c.normalize(c.f16_value(b), snorm) << 16 - self.assertEqual(got, want, f"{op} {a:#x} {b:#x}") - - def test_exhaustive_programs_cover_every_half(self): - seen = {} - for op, lines in c.exhaustive_programs(): - seen.setdefault(op, []).append(lines) - self.assertEqual({op: len(p) for op, p in seen.items()}, - {"v_cvt_norm_i16_f16": 16384, "v_cvt_norm_u16_f16": 16384, - "v_cvt_pknorm_i16_f16": 8192, "v_cvt_pknorm_u16_f16": 8192}) - halves = set() - for lines in seen["v_cvt_pknorm_u16_f16"]: - for line in lines: - if line.startswith("v_mov_b32_e32 v1"): - w = int(line.split()[-1], 16) - halves |= {w & 0xFFFF, w >> 16} - self.assertEqual(len(halves), 1 << 16) - - def test_programs_are_encodable(self): - rng = random.Random(2) - for _ in range(300): - lines, _ = c.program(rng, 6) - for line in lines: - op, raw, args, mods = c.split_line(line) - if op not in c.FAMILY: - continue - kind = c.FAMILY[op][0] - self.assertTrue(8 <= c._dst_index(args[0]) <= 11, line) - srcs = args[1:] - lits = [s for s in srcs if s.startswith("0x")] - consts = [s for s in srcs if not re.fullmatch(r"-?\|?[sv]\d+\|?", s)] - for s in consts: # no modifiers on constants - self.assertNotIn("|", s, line) - if raw.endswith("_e32"): - self.assertIn(op, c.VOP1_OPS, line) - self.assertEqual(mods, [], line) - self.assertNotRegex(srcs[0], r"[-|]v|[-|]s", line) - continue - self.assertLessEqual(len(lits), 1, line) - self.assertLessEqual(len(lits) + sum("s" in s and not s.startswith("0x") for s in srcs), 2, line) - for m in mods: - if m.startswith("op_sel"): - self.assertEqual(kind, "pk16", line) - self.assertRegex(m, r"^op_sel:\[[01],[01],[01]\]$", line) - sel = c._opsel(mods) - for s, bit in zip(srcs, sel): - self.assertTrue(not bit or s not in consts, line) - elif m == "clamp": - self.assertIn(op, c.CLAMP_OPS, line) - else: - self.assertIn(op, c.OMOD_OPS, line) - if lits: - self.assertGreater(int(lits[0], 16), 64, line) # never an inline constant - - -class Translated(unittest.TestCase): - def test_harness_canaries(self): - self.assertTrue(c.self_test()) - - def test_short_seeded_run_matches(self): - counts, failure = c.run_suite(20, 3, 5) - self.assertEqual(failure, None) - self.assertEqual(counts["skip"], {}) - self.assertEqual(counts["pass"], 20) - - def test_sweep_matches_for_rpi_and_pknorm_i16_f32(self): - counts, failure = c.run_sweep(4, ["v_cvt_rpi_i32_f32", "v_cvt_pknorm_i16_f32"]) - self.assertEqual((failure, counts["skip"]), (None, {})) - self.assertEqual(counts["pass"], 16 + 144) - - def test_edge_grid_matches_for_rpi(self): - counts, failure = c.run_grid(["v_cvt_rpi_i32_f32"]) - self.assertEqual((failure, counts["skip"]), (None, {})) - self.assertEqual(counts["pass"], -(-(len(c.F32_EDGES) + len(c.F32_TIES)) // c.GRID_PER_PROGRAM)) - for event in ("nan", "inf", "saturated", "tie"): - self.assertGreater(counts["events"][("v_cvt_rpi_i32_f32", event)], 0, event) - - def test_every_half_around_one_half_matches_for_pknorm_u16_f16(self): - # 0x3780..0x387f through the exhaustive stage's programs: the double-rounding traps and the 0.5 tie - progs = [lines for op, lines in c.exhaustive_programs(["v_cvt_pknorm_u16_f16"])] - for lines in progs[0x3780 // 8:0x3880 // 8]: - self.assertIsNone(c.check(lines), lines[0]) - - def test_a_wrong_translation_is_caught(self): - lines = ["v_mov_b32 v9, 0x3803", "v_cvt_pknorm_u16_f16 v8, v9, v9"] - self.assertIsNone(c.check(lines)) - real = c.translate_listing - try: - # 0.5 + 3 * 2^-11 times 65535 rounded in binary32 is 32863.5, which a second rounding takes to 32864 - c.translate_listing = lambda l, n, t: [0x80608060] + real(l, n, t)[1:] - self.assertIn("expected 0x805f805f, actual 0x80608060", c.check(lines)) - finally: - c.translate_listing = real - - def test_a_short_export_is_caught(self): - # zip alone compared only the words both oracles have, so a translator exporting two of the four passed - lines = ["v_mov_b32 v9, 0x3803", "v_cvt_pknorm_u16_f16 v8, v9, v9"] - real = c.translate_listing - try: - c.translate_listing = lambda l, n, t: real(l, n, t)[:2] - self.assertEqual(c.check(lines), "exported 2 words, want 4") - with tempfile.TemporaryDirectory() as tmp: - self.assertEqual(c.run_one(lines, "ps_cvt_short", tmp), ("mismatch", "exported 2 words, want 4")) - finally: - c.translate_listing = real - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/test_cvt_f16_omod_probe.py b/tests/test_cvt_f16_omod_probe.py deleted file mode 100644 index 7430597a3..000000000 --- a/tests/test_cvt_f16_omod_probe.py +++ /dev/null @@ -1,276 +0,0 @@ -"""Unit tests for tools/cvt_f16_omod_probe.py (reference model, kernel assembly, FakeOracle verdicts, CLI). - -Standard library only; no GPU, no LLVM required (the clang assembly test skips when AMD clang is unavailable), -and no game files. -""" -import io -import json -import os -import re -import subprocess -import sys -import tempfile -import unittest -from contextlib import redirect_stderr, redirect_stdout -from pathlib import Path -from unittest import mock - -TOOLS = Path(__file__).resolve().parents[1] / "tools" -sys.dont_write_bytecode = True -if str(TOOLS) not in sys.path: - sys.path.insert(0, str(TOOLS)) - -import cvt_f16_omod_probe as pr # noqa: E402 -from hw_oracle import asm, runner # noqa: E402 - - -class FakeOracle: - """Simulated hw_oracle backend that parses kernel_lines() and answers from expected_cvt_f16_omod.""" - - arch = "gfx1036" - device = "fake gfx1036" - - def __init__( - self, - *, - bad_lo: bool = False, - bad_hi: bool = False, - wave64_diff: bool = False, - error_msg: str | None = None, - ): - self.bad_lo = bad_lo - self.bad_hi = bad_hi - self.wave64_diff = wave64_diff - self.error_msg = error_msg - self.closed = False - - def run(self, kernels): - out = [] - for k in kernels: - if self.error_msg is not None: - out.append(self.error_msg) - continue - mdict = k.mode or {} - setreg_rtz = any("hwreg(HW_REG_MODE, 2, 2), 3" in ln for ln in k.lines) - rtz = (mdict.get("round16_64", 0) == 3) or setreg_rtz - denorm_keep = mdict.get("denorm16_64", 0) == 3 - ieee = mdict.get("ieee", 0) == 1 - dx10_clamp = mdict.get("dx10_clamp", 1) == 1 - words = [] - for ln in k.lines: - m_src = re.match(r"v_mov_b32_e32 v1, (0x[0-9a-fA-F]+)", ln) - if m_src: - cur_src = int(m_src.group(1), 16) - continue - m_cvt = re.match(r"v_cvt_f16_f32_e64 v2, v1(?:\s+(.*))?$", ln) - if m_cvt: - mod = (m_cvt.group(1) or "").strip() - w = pr.expected_cvt_f16_omod( - cur_src, - mod, - rtz=rtz, - denorm_keep=denorm_keep, - ieee=ieee, - dx10_clamp=dx10_clamp, - ) - if self.bad_lo and len(words) == 0: - w ^= 1 - if self.bad_hi and len(words) == 0: - w = (w & 0xFFFF) | (0x1234 << 16) - if self.wave64_diff and k.wave == 64 and len(words) == 0: - w ^= 1 - words.append(w) - out.append(words) - return out - - def close(self): - self.closed = True - - -def _run_main(oracle, *args): - buf = io.StringIO() - err = io.StringIO() - with mock.patch.object(runner, "open_oracle", return_value=oracle), redirect_stdout(buf), redirect_stderr(err): - rc = pr.main(list(args)) - return rc, buf.getvalue(), err.getvalue() - - -class ReferenceModelTests(unittest.TestCase): - def test_self_test(self): - with redirect_stdout(io.StringIO()): - self.assertEqual(pr.self_test(), 0) - - def test_critical_edge_cases(self): - f32 = pr._f32_bits - # RNE vs RTZ overflow - self.assertEqual( - pr.expected_cvt_f16_omod(f32(32768.0), "mul:2", rtz=False, denorm_keep=False, ieee=False), - 0xAAAA7C00, - ) - self.assertEqual( - pr.expected_cvt_f16_omod(f32(32768.0), "mul:2", rtz=True, denorm_keep=False, ieee=False), - 0xAAAA7BFF, - ) - self.assertEqual( - pr.expected_cvt_f16_omod(f32(-32768.0), "mul:2", rtz=True, denorm_keep=False, ieee=False), - 0xAAAAFBFF, - ) - # +-65520 div:2 rounds to f16 first (+-inf RNE, +-65504 RTZ), then divides - self.assertEqual( - pr.expected_cvt_f16_omod(f32(65520.0), "div:2", rtz=False, denorm_keep=False, ieee=False), - 0xAAAA7C00, - ) - self.assertEqual( - pr.expected_cvt_f16_omod(f32(65520.0), "div:2", rtz=True, denorm_keep=False, ieee=False), - 0xAAAA77FF, - ) - self.assertEqual( - pr.expected_cvt_f16_omod(f32(-65520.0), "div:2", rtz=True, denorm_keep=False, ieee=False), - 0xAAAAF7FF, - ) - # True +-inf stays +-inf even under RTZ + mul:2/mul:4 - self.assertEqual( - pr.expected_cvt_f16_omod(0x7F800000, "mul:2", rtz=True, denorm_keep=False, ieee=False), - 0xAAAA7C00, - ) - self.assertEqual( - pr.expected_cvt_f16_omod(0xFF800000, "mul:4", rtz=True, denorm_keep=False, ieee=False), - 0xAAAAFC00, - ) - # div:2 underflow from exponent 1 preserves sign (-0.0 = 0x8000); exponent 0 gives +0.0 (0x0000) - for neg_exp1 in (f32(-(2.0 ** -14)), f32(-1.5 * (2.0 ** -14)), 0xB8FFE000): - self.assertEqual( - pr.expected_cvt_f16_omod(neg_exp1, "div:2", rtz=False, denorm_keep=False, ieee=False), - 0xAAAA8000, - ) - self.assertEqual( - pr.expected_cvt_f16_omod(0x80000000, "div:2", rtz=False, denorm_keep=False, ieee=False), - 0xAAAA0000, - ) - self.assertEqual( - pr.expected_cvt_f16_omod(f32(-(2.0 ** -15)), "div:2", rtz=False, denorm_keep=False, ieee=False), - 0xAAAA0000, - ) - # clamp still produces +0.0 from -0.0 and acts in every mode - self.assertEqual( - pr.expected_cvt_f16_omod(f32(-(2.0 ** -14)), "clamp div:2", rtz=False, denorm_keep=False, ieee=False), - 0xAAAA0000, - ) - self.assertEqual( - pr.expected_cvt_f16_omod(f32(0.75), "clamp mul:2", rtz=True, denorm_keep=False, ieee=False), - 0xAAAA3C00, - ) - self.assertEqual( - pr.expected_cvt_f16_omod(f32(0.75), "clamp mul:2", rtz=True, denorm_keep=True, ieee=False), - 0xAAAA3A00, - ) - self.assertEqual( - pr.expected_cvt_f16_omod(f32(0.75), "clamp mul:2", rtz=True, denorm_keep=False, ieee=True), - 0xAAAA3A00, - ) - - -class KernelTests(unittest.TestCase): - def test_kernel_structure(self): - for mode_name in pr.MODES: - for mod in pr.MODS: - lines = pr.kernel_lines(mode_name, mod) - self.assertEqual(lines[-2:], ["s_waitcnt vmcnt(0)", "s_endpgm"]) - if mode_name == "dyn_rtz_d0_i0": - self.assertEqual(lines[0], "s_setreg_imm32_b32 hwreg(HW_REG_MODE, 2, 2), 3") - else: - self.assertTrue(lines[0].startswith("v_mov_b32_e32 v1, ")) - cvt_lines = [ln for ln in lines if ln.startswith("v_cvt_f16_f32_e64")] - self.assertEqual(len(cvt_lines), len(pr.INPUTS)) - - def test_kernels_assemble_when_amd_clang_available(self): - try: - clang = runner.find_clang() - except runner.Unavailable as e: - self.skipTest(str(e)) - for wave in (32, 64): - kernels, _ = pr.build_jobs(list(pr.MODES), [wave]) - text, _, _ = asm.module_text(kernels[:8], "gfx1036", wave=wave) - with tempfile.TemporaryDirectory() as d: - s_path = Path(d) / "k.s" - o_path = Path(d) / "k.o" - s_path.write_text(text, encoding="utf-8") - flags = ["-mwavefrontsize64"] if wave == 64 else [] - res = subprocess.run( - [clang, "--target=amdgcn-amd-amdhsa", "-mcpu=gfx1036", *flags, "-c", str(s_path), "-o", str(o_path)], - capture_output=True, - text=True, - ) - self.assertEqual(res.returncode, 0, res.stderr[:800]) - - -class ProbeCliTests(unittest.TestCase): - def test_fake_oracle_pass_and_json_lf(self): - oracle = FakeOracle() - with tempfile.TemporaryDirectory() as d: - report = os.path.join(d, "nested", "report.json") - rc, out, err = _run_main(oracle, "--json", report) - self.assertEqual(rc, 0, out + err) - self.assertTrue(oracle.closed) - self.assertIn("lo_mismatches=0, hi_mismatches=0, wave_diffs=0, dyn_rtz_diffs=0", out) - with open(report, "rb") as f: - raw = f.read() - self.assertNotIn(b"\r\n", raw) - doc = json.loads(raw.decode("utf-8")) - self.assertEqual(doc["arch"], "gfx1036") - self.assertEqual(doc["waves"], [32, 64]) - self.assertEqual(doc["inputs"], len(pr.INPUTS)) - self.assertEqual(doc["total_cases"], 2 * len(pr.MODES) * len(pr.MODS) * len(pr.INPUTS)) - self.assertEqual(doc["lo_mismatches"], 0) - self.assertEqual(doc["hi_mismatches"], 0) - self.assertEqual(doc["wave_diffs"], 0) - - def test_fake_oracle_lo_mismatch_exits_1(self): - rc, out, _ = _run_main(FakeOracle(bad_lo=True), "--modes", "rne_d0_i0", "--waves", "32") - self.assertEqual(rc, 1, out) - self.assertIn("MISMATCH", out) - - def test_fake_oracle_hi_clobber_exits_1(self): - rc, out, _ = _run_main(FakeOracle(bad_hi=True), "--modes", "rne_d0_i0", "--waves", "32") - self.assertEqual(rc, 1, out) - self.assertIn("hi_mismatches=8", out) - - def test_fake_oracle_wave_diff_exits_1(self): - rc, out, _ = _run_main(FakeOracle(wave64_diff=True), "--modes", "rne_d0_i0", "--waves", "32,64") - self.assertEqual(rc, 1, out) - self.assertIn("WAVE DIFF", out) - - def test_fake_oracle_harness_error_exits_2(self): - rc, out, _ = _run_main(FakeOracle(error_msg="assembler rejected: test"), "--modes", "rne_d0_i0", "--waves", "32") - self.assertEqual(rc, 2, out) - self.assertIn("harness error", out) - - def test_json_directory_refused_and_unwritable_path_exits_2(self): - with tempfile.TemporaryDirectory() as d: - with self.assertRaises(SystemExit): - _run_main(FakeOracle(), "--json", d) - blocker = os.path.join(d, "file_not_dir") - with open(blocker, "wb") as f: - f.write(b"keep") - rc, _, err = _run_main(FakeOracle(), "--modes", "rne_d0_i0", "--waves", "32", "--json", os.path.join(blocker, "r.json")) - self.assertEqual(rc, 2) - self.assertIn("ERROR: cannot write", err) - self.assertNotIn("Traceback", err) - - def test_non_gfx10_arch_exits_77(self): - oracle = FakeOracle() - oracle.arch = "gfx1100" - rc, out, _ = _run_main(oracle) - self.assertEqual(rc, 77, out) - self.assertTrue(oracle.closed) - - def test_unavailable_oracle_exits_77(self): - buf = io.StringIO() - with mock.patch.object(runner, "open_oracle", side_effect=runner.Unavailable("missing")), redirect_stdout(buf): - rc = pr.main(["--modes", "rne_d0_i0", "--waves", "32"]) - self.assertEqual(rc, 77) - self.assertIn("unavailable", buf.getvalue()) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/test_cvt_norm_mods_probe.py b/tests/test_cvt_norm_mods_probe.py deleted file mode 100644 index d6caea1a3..000000000 --- a/tests/test_cvt_norm_mods_probe.py +++ /dev/null @@ -1,303 +0,0 @@ -"""Unit tests for tools/cvt_norm_mods_probe.py (reference model, kernel assembly, FakeOracle verdicts, CLI). - -Standard library only; no GPU, no LLVM required (live assembly tests skip when unavailable), and no game files. -""" -import io -import json -import os -import re -import shutil -import subprocess -import sys -import tempfile -import unittest -from contextlib import redirect_stderr, redirect_stdout -from pathlib import Path -from unittest import mock - -TOOLS = Path(__file__).resolve().parents[1] / "tools" -sys.dont_write_bytecode = True -if str(TOOLS) not in sys.path: - sys.path.insert(0, str(TOOLS)) - -import cvt_norm_mods_probe as pr # noqa: E402 -from hw_oracle import asm, runner # noqa: E402 - - -def _eval_f32_src_mod(bits: int, expr: str) -> int: - if "|" in expr: - bits &= 0x7FFFFFFF - if expr.startswith("-"): - bits ^= 0x80000000 - return bits & pr.M32 - - -def _eval_f16_src_mod(bits16: int, expr: str) -> int: - bits16 &= pr.M16 - if "|" in expr: - bits16 &= 0x7FFF - if expr.startswith("-"): - bits16 ^= 0x8000 - return bits16 - - -class FakeOracle: - """Simulated hw_oracle backend parsing probe kernels and computing reference outputs.""" - - arch = "gfx1036" - device = "fake gfx1036" - - def __init__(self, *, bad_word: bool = False, wave64_diff: bool = False, error_msg: str | None = None): - self.bad_word = bad_word - self.wave64_diff = wave64_diff - self.error_msg = error_msg - self.closed = False - - def run(self, kernels, words=4): - del words - out = [] - for k in kernels: - if self.error_msg is not None: - out.append(self.error_msg) - continue - lines = k.lines - joined = "\n".join(lines) - m_sweep = re.search(r"v_add_nc_u32_e32 v11, (\d+), v10", joined) - if m_sweep: - base_word = int(m_sweep.group(1)) - m_op = re.search(r"(v_cvt_norm_[iu]16_f16)_e64", joined) - assert m_op is not None, joined - res = pr.expected_sweep_words(m_op.group(1))[base_word : base_word + 16384] - if self.bad_word: - res[0] ^= 1 - if self.wave64_diff and k.wave == 64: - res[0] ^= 1 - out.append(res) - continue - - regs: dict[str, int] = {} - res = [] - for ln in lines: - m_mov = re.match(r"v_mov_b32_e32 (v\d+), (0x[0-9a-fA-F]+|\d+)$", ln) - if m_mov: - regs[m_mov.group(1)] = int(m_mov.group(2), 0) & pr.M32 - continue - m_sdwa = re.match(r"(v_cvt_norm_[iu]16_f16)_sdwa v0, ([^ ]+)(.*)", ln) - if m_sdwa: - op, src_expr, tail = m_sdwa.groups() - snorm = op == "v_cvt_norm_i16_f16" - src = regs["v1"] - h = (src >> 16) & pr.M16 if "src0_sel:WORD_1" in tail else (src & pr.M16) - h = _eval_f16_src_mod(h, src_expr) - val16 = pr.expected_norm_f16(h, snorm) - seed = regs["v0"] - if "dst_sel:WORD_1" in tail: - w = (val16 << 16) | (seed & pr.M16) - elif "UNUSED_PRESERVE" in tail: - w = (seed & 0xFFFF0000) | val16 - elif "UNUSED_SEXT" in tail: - w = (0xFFFF0000 | val16) if (val16 & 0x8000) else val16 - else: - w = val16 - res.append(w & pr.M32) - continue - m_e64 = re.match(r"(v_cvt_norm_[iu]16_f16)_e64 v0, ([^ ]+)", ln) - if m_e64: - op, src_expr = m_e64.groups() - snorm = op == "v_cvt_norm_i16_f16" - h = _eval_f16_src_mod(regs["v1"] & pr.M16, src_expr) - val16 = pr.expected_norm_f16(h, snorm) - res.append((regs["v0"] & 0xFFFF0000) | val16) - continue - m_pk = re.match(r"(v_cvt_pknorm_[iu]16_f32) v0, ([^,]+), ([^ ]+)(?: clamp)?$", ln) - if m_pk: - op, s0_expr, s1_expr = m_pk.groups() - s0 = _eval_f32_src_mod(regs["v1"], s0_expr) - s1 = _eval_f32_src_mod(regs["v2"], s1_expr) - res.append(pr.expected_pknorm_f32(op, s0, s1)) - continue - - if res: - if self.bad_word: - res[0] ^= 1 - if self.wave64_diff and k.wave == 64: - res[0] ^= 1 - out.append(res) - return out - - def close(self): - self.closed = True - - -def _run_main(oracle, *args): - buf = io.StringIO() - err = io.StringIO() - with mock.patch.object(runner, "open_oracle", return_value=oracle), redirect_stdout(buf), redirect_stderr(err): - rc = pr.main(list(args)) - return rc, buf.getvalue(), err.getvalue() - - -class ReferenceModelTests(unittest.TestCase): - def test_self_test(self): - with redirect_stdout(io.StringIO()): - self.assertEqual(pr.self_test(), 0) - - def test_norm_f16_single_rounding_ties_and_edges(self): - # Single-rounding near +-0.5 vs f32 double-rounding - self.assertEqual(pr.expected_norm_f16(0x3800, True), 16384) - self.assertEqual(pr.expected_norm_f16(0x3801, True), 16399) - self.assertEqual(pr.expected_norm_f16(0xB801, True), (-16399) & 0xFFFF) - self.assertEqual(pr.expected_norm_f16(0x37FF, True), 16376) - self.assertEqual(pr.expected_norm_f16(0xB7FF, True), (-16376) & 0xFFFF) - self.assertEqual(pr.expected_norm_f16(0x3800, False), 32768) - self.assertEqual(pr.expected_norm_f16(0x3801, False), 32799) - self.assertEqual(pr.expected_norm_f16(0x37FF, False), 32752) - # Out-of-range, infinities, NaNs, subnormals - self.assertEqual(pr.expected_norm_f16(0x4000, True), 0x7FFF) - self.assertEqual(pr.expected_norm_f16(0xC000, True), 0x8001) - self.assertEqual(pr.expected_norm_f16(0xC000, False), 0) - self.assertEqual(pr.expected_norm_f16(0x7C00, False), 0xFFFF) - self.assertEqual(pr.expected_norm_f16(0xFC00, True), 0x8001) - self.assertEqual(pr.expected_norm_f16(0x7C01, True), 0) - self.assertEqual(pr.expected_norm_f16(0xFE00, False), 0) - self.assertEqual(pr.expected_norm_f16(0x0001, True), 0) - self.assertEqual(pr.expected_norm_f16(0x03FF, False), 4) - - def test_pknorm_f32_edges_and_near_ties(self): - self.assertEqual(pr.expected_pknorm_f32("v_cvt_pknorm_i16_f32", 0x38400180, 0x00000000), 0x00000001) - self.assertEqual(pr.expected_pknorm_f32("v_cvt_pknorm_i16_f32", 0x3C004101, 0xBF800000), 0x80010101) - self.assertEqual(pr.expected_pknorm_f32("v_cvt_pknorm_u16_f32", 0x37C000C0, 0x40000000), 0xFFFF0001) - self.assertEqual(pr.expected_pknorm_f32("v_cvt_pknorm_u16_f32", 0x3B008081, 0xBF800000), 0x00000081) - self.assertEqual(pr.expected_pknorm_f32("v_cvt_pknorm_i16_f32", 0x7F800001, 0xFF800000), 0x80010000) - - def test_kernel_builders_have_unique_labels_and_endpgm(self): - kernels, meta = pr.build_jobs(list(pr.OPS), [32, 64]) - self.assertEqual(len(kernels), len(meta)) - labels = [] - for k in kernels: - self.assertEqual(k.lines[-2:], ["s_waitcnt vmcnt(0)", "s_endpgm"]) - for ln in k.lines: - if ln.endswith(":"): - labels.append(ln[:-1]) - self.assertEqual(len(labels), len(set(labels)), "duplicate loop labels across kernels") - - def test_kernels_assemble_when_amd_clang_available(self): - try: - clang = runner.find_clang() - except runner.Unavailable as e: - self.skipTest(str(e)) - for wave in (32, 64): - kernels, _ = pr.build_jobs(list(pr.OPS), [wave]) - text, _, _ = asm.module_text(kernels, "gfx1036", wave=wave) - with tempfile.TemporaryDirectory() as d: - s_path = Path(d) / "k.s" - o_path = Path(d) / "k.o" - with open(s_path, "w", encoding="utf-8", newline="\n") as f: - f.write(text) - flags = ["-mwavefrontsize64"] if wave == 64 else [] - res = subprocess.run( - [clang, "--target=amdgcn-amd-amdhsa", "-mcpu=gfx1036", *flags, "-c", str(s_path), "-o", str(o_path)], - capture_output=True, - text=True, - ) - self.assertEqual(res.returncode, 0, res.stderr[:800]) - - def test_kernels_assemble_when_llvm_mc_available(self): - llvm_mc = os.environ.get("LLVM_MC") or shutil.which("llvm-mc") - if not llvm_mc or not os.path.isfile(llvm_mc): - self.skipTest("llvm-mc not found") - for wave in (32, 64): - kernels, _ = pr.build_jobs(list(pr.OPS), [wave]) - text, _, _ = asm.module_text(kernels, "gfx1036", wave=wave) - flags = ["-mattr=+wavefrontsize64"] if wave == 64 else [] - res = subprocess.run( - [llvm_mc, "-triple=amdgcn-amd-amdhsa", "-mcpu=gfx1036", *flags, "-filetype=obj", "-o", os.devnull], - input=text, - capture_output=True, - text=True, - ) - self.assertEqual(res.returncode, 0, res.stderr[:800]) - - -class ProbeCliTests(unittest.TestCase): - def test_fake_oracle_pass_and_json_lf(self): - oracle = FakeOracle() - with tempfile.TemporaryDirectory() as d: - report = os.path.join(d, "nested", "report.json") - rc, out, err = _run_main(oracle, "--json", report) - self.assertEqual(rc, 0, out + err) - self.assertTrue(oracle.closed) - self.assertIn("mismatches=0, wave_diffs=0", out) - with open(report, "rb") as f: - raw = f.read() - self.assertNotIn(b"\r\n", raw) - doc = json.loads(raw.decode("utf-8")) - self.assertEqual(doc["arch"], "gfx1036") - self.assertEqual(doc["waves"], [32, 64]) - self.assertEqual(doc["ops"], list(pr.OPS)) - self.assertEqual(doc["mismatches"], 0) - self.assertEqual(doc["wave_diffs"], 0) - self.assertEqual(doc["total_words"], 1050708) - - def test_fake_oracle_word_mismatch_exits_1(self): - rc, out, _ = _run_main(FakeOracle(bad_word=True), "--ops", "v_cvt_pknorm_i16_f32", "--waves", "32") - self.assertEqual(rc, 1, out) - self.assertIn("MISMATCH", out) - - def test_fake_oracle_wave_diff_exits_1(self): - rc, out, _ = _run_main(FakeOracle(wave64_diff=True), "--ops", "v_cvt_pknorm_u16_f32", "--waves", "32,64") - self.assertEqual(rc, 1, out) - self.assertIn("WAVE DIFF", out) - - def test_fake_oracle_harness_error_exits_2(self): - rc, out, _ = _run_main( - FakeOracle(error_msg="assembler rejected: test"), "--ops", "v_cvt_pknorm_i16_f32", "--waves", "32" - ) - self.assertEqual(rc, 2, out) - self.assertIn("harness error", out) - - def test_bad_cli_args_exit_2(self): - for bad_waves in ("", "16", "32,", "32,,64", "abc"): - with self.subTest(waves=bad_waves): - rc, _, err = _run_main(FakeOracle(), "--waves", bad_waves) - self.assertEqual(rc, 2) - self.assertIn("--waves", err) - for bad_ops in ("", "v_not_an_op", "v_cvt_norm_i16_f16,"): - with self.subTest(ops=bad_ops): - rc, _, err = _run_main(FakeOracle(), "--ops", bad_ops) - self.assertEqual(rc, 2) - self.assertIn("--ops", err) - - def test_json_directory_refused_and_unwritable_path_exits_2(self): - with tempfile.TemporaryDirectory() as d: - rc, _, err = _run_main(FakeOracle(), "--ops", "v_cvt_pknorm_i16_f32", "--waves", "32", "--json", d) - self.assertEqual(rc, 2) - self.assertIn("ERROR:", err) - self.assertNotIn("Traceback", err) - blocker = os.path.join(d, "file_not_dir") - with open(blocker, "wb") as f: - f.write(b"keep") - rc, _, err = _run_main( - FakeOracle(), "--ops", "v_cvt_pknorm_i16_f32", "--waves", "32", "--json", os.path.join(blocker, "r.json") - ) - self.assertEqual(rc, 2) - self.assertIn("ERROR: cannot write", err) - self.assertNotIn("Traceback", err) - - def test_non_gfx10_arch_exits_77(self): - oracle = FakeOracle() - oracle.arch = "gfx1100" - rc, out, _ = _run_main(oracle) - self.assertEqual(rc, 77, out) - self.assertTrue(oracle.closed) - - def test_unavailable_oracle_exits_77(self): - buf = io.StringIO() - with mock.patch.object(runner, "open_oracle", side_effect=runner.Unavailable("missing")), redirect_stdout(buf): - rc = pr.main(["--ops", "v_cvt_pknorm_i16_f32", "--waves", "32"]) - self.assertEqual(rc, 77) - self.assertIn("unavailable", buf.getvalue()) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/test_cvt_pknorm_f16_probe.py b/tests/test_cvt_pknorm_f16_probe.py deleted file mode 100644 index 268ff6ba9..000000000 --- a/tests/test_cvt_pknorm_f16_probe.py +++ /dev/null @@ -1,304 +0,0 @@ -"""Unit tests for tools/cvt_pknorm_f16_probe.py (reference model, kernels, evaluator, CLI, live gfx1036). - -Standard library only; no game files. Live hardware check runs on gfx1036 when available and skips otherwise. -""" -import io -import json -import os -import re -import sys -import tempfile -import unittest -from contextlib import redirect_stderr, redirect_stdout -from pathlib import Path -from unittest import mock - -TOOLS = Path(__file__).resolve().parents[1] / "tools" -sys.dont_write_bytecode = True -if str(TOOLS) not in sys.path: - sys.path.insert(0, str(TOOLS)) - -import cvt_pknorm_f16_probe as pr # noqa: E402 -from hw_oracle import asm, runner # noqa: E402 - -_INLINE_VALS = { - "0.5": 0x00003800, - "-0.5": 0x0000B800, - "1.0": 0x00003C00, - "1": 0x00000001, - "-1": 0xFFFFFFFF, - "0x3800": 0x00003800, -} - - -def _parse_src(tok: str, regs: dict[str, int]) -> tuple[int, bool, bool]: - is_neg = tok.startswith("-") - if is_neg: - tok = tok[1:] - is_abs = tok.startswith("|") and tok.endswith("|") - if is_abs: - tok = tok[1:-1] - if tok in regs: - val = regs[tok] - elif tok in _INLINE_VALS: - val = _INLINE_VALS[tok] - elif tok.startswith("0x"): - val = int(tok, 16) - else: - val = int(tok, 0) - return val, is_abs, is_neg - - -class FakeOracle: - """Simulated hw_oracle backend executing sweep and case kernels against pr.expected_pknorm_f16.""" - - def __init__( - self, - *, - arch: str = "gfx1036", - device: str = "fake gfx1036", - mismatch_sweep: bool = False, - mismatch_case: bool = False, - wave_diff: bool = False, - clamp_diff: bool = False, - raw_omod_diff: bool = False, - error_msg: str | None = None, - ): - self.arch = arch - self.device = device - self.mismatch_sweep = mismatch_sweep - self.mismatch_case = mismatch_case - self.wave_diff = wave_diff - self.clamp_diff = clamp_diff - self.raw_omod_diff = raw_omod_diff - self.error_msg = error_msg - self.closed = False - - def _run_sweep(self, k) -> list[int]: - ins = next(ln for ln in k.lines if ln.startswith("v_cvt_pknorm_")) - op = ins.split()[0] - dhi = "op_sel:[0,0,1]" in ins - clamp = "clamp" in ins - half = 1 if any("0x8000" in ln for ln in k.lines) else 0 - base = half * 32768 - tab = pr._REF_TABLES[op == "v_cvt_pknorm_i16_f16"] - words = [] - for idx in range(k.words): - lo = tab[base + 2 * idx] - hi = tab[base + 2 * idx + 1] - w = ((lo << 16) if dhi else (lo | (hi << 16))) & 0xFFFFFFFF - words.append(w) - if self.mismatch_sweep and half == 0: - words[0] ^= 1 - if self.wave_diff and k.wave == 64 and half == 0: - words[1] ^= 1 - if self.clamp_diff and clamp and half == 0: - words[2] ^= 1 - return words - - def _run_cases(self, k) -> list[int]: - regs: dict[str, int] = {} - words: list[int] = [] - for ln in k.lines: - m_mov = re.match(r"^(?:v_mov_b32_e32|s_mov_b32)\s+([vs]\d+),\s+(0x[0-9a-fA-F]+)$", ln) - if m_mov: - regs[m_mov.group(1)] = int(m_mov.group(2), 16) - continue - m_long = re.match(r"^\.long\s+(0x[0-9a-fA-F]+),\s+(0x[0-9a-fA-F]+)$", ln) - if m_long: - dw0 = int(m_long.group(1), 16) - dw1 = int(m_long.group(2), 16) - opc = (dw0 >> 16) & 0xFF - clamp = bool((dw0 >> 15) & 1) - omod = (dw1 >> 27) & 3 - op = "v_cvt_pknorm_i16_f16" if opc == 0x12 else "v_cvt_pknorm_u16_f16" - w = pr.expected_pknorm_f16(op, regs["v1"], regs["v2"], clamp=clamp) - if self.raw_omod_diff and omod == 2: - w ^= 0x100 - if self.clamp_diff and clamp: - w ^= 1 - words.append(w) - continue - m_op = re.match(r"^(v_cvt_pknorm_[iu]16_f16)\s+v8,\s+([^,]+),\s+([^\s]+)(?:\s+(.*))?$", ln) - if m_op: - op, s0_tok, s1_tok, tail = m_op.groups() - tail = tail or "" - s0_val, s0_abs, s0_neg = _parse_src(s0_tok, regs) - s1_val, s1_abs, s1_neg = _parse_src(s1_tok, regs) - sel = (0, 0) - dhi = False - m_sel = re.search(r"op_sel:\[(\d),(\d),(\d)\]", tail) - if m_sel: - sel = (int(m_sel.group(1)), int(m_sel.group(2))) - dhi = bool(int(m_sel.group(3))) - clamp = "clamp" in tail.split() - w = pr.expected_pknorm_f16( - op, s0_val, s1_val, sel=sel, dhi=dhi, clamp=clamp, - src0_abs=s0_abs, src0_neg=s0_neg, src1_abs=s1_abs, src1_neg=s1_neg, - ) - if self.mismatch_case and not words: - w ^= 1 - if self.wave_diff and k.wave == 64 and not words: - w ^= 2 - if self.clamp_diff and clamp and not words: - w ^= 4 - words.append(w) - return words - - def run(self, kernels): - out = [] - for k in kernels: - if self.error_msg is not None: - out.append(self.error_msg) - elif k.words == pr.SWEEP_WORDS_PER_HALF: - out.append(self._run_sweep(k)) - else: - out.append(self._run_cases(k)) - return out - - def close(self): - self.closed = True - - -def _run_main(oracle, *args): - buf = io.StringIO() - err = io.StringIO() - with mock.patch.object(runner, "open_oracle", return_value=oracle), redirect_stdout(buf), redirect_stderr(err): - rc = pr.main(list(args)) - return rc, buf.getvalue(), err.getvalue() - - -class ReferenceModelTests(unittest.TestCase): - def test_self_test(self): - with redirect_stdout(io.StringIO()): - self.assertEqual(pr.self_test(), 0) - - def test_double_rounding_nans_infs_and_modifiers(self): - # Single-rounded traps near +-0.5 ulp - self.assertEqual(pr.ref_norm16_f16(0x3801, True), 16399) - self.assertEqual(pr.ref_norm16_f16(0xB801, True), (-16399) & 0xFFFF) - self.assertEqual(pr.ref_norm16_f16(0x3801, False), 32799) - self.assertEqual(pr.ref_norm16_f16(0x37FF, True), 16376) - self.assertEqual(pr.ref_norm16_f16(0x37FF, False), 32752) - # NaNs, +-inf, +-0, denormals - for nan in (0x7E00, 0xFE00, 0x7C01, 0xFC01): - self.assertEqual(pr.ref_norm16_f16(nan, True), 0) - self.assertEqual(pr.ref_norm16_f16(nan, False), 0) - self.assertEqual(pr.ref_norm16_f16(0x7C00, True), 32767) - self.assertEqual(pr.ref_norm16_f16(0xFC00, True), (-32767) & 0xFFFF) - self.assertEqual(pr.ref_norm16_f16(0x7C00, False), 65535) - self.assertEqual(pr.ref_norm16_f16(0xFC00, False), 0) - self.assertEqual(pr.ref_norm16_f16(0x8000, True), 0) - self.assertEqual(pr.ref_norm16_f16(0x0001, False), 0) - # All 8 op_sel permutations + clamp no-op + abs/neg - s0, s1 = 0x3C003400, 0xBC003801 - want_opsel = { - (0, 0, 0): 0x400F2000, - (0, 0, 1): 0x20000000, - (0, 1, 0): 0x80012000, - (0, 1, 1): 0x20000000, - (1, 0, 0): 0x400F7FFF, - (1, 0, 1): 0x7FFF0000, - (1, 1, 0): 0x80017FFF, - (1, 1, 1): 0x7FFF0000, - } - for (a, b, d), want in want_opsel.items(): - for clamp in (False, True): - self.assertEqual( - pr.expected_pknorm_f16("v_cvt_pknorm_i16_f16", s0, s1, sel=(a, b), dhi=d, clamp=clamp), - want, - ) - self.assertEqual( - pr.expected_pknorm_f16( - "v_cvt_pknorm_i16_f16", s0, s1, sel=(1, 1), dhi=True, src0_abs=True, src1_neg=True - ), - 0x7FFF0000, - ) - - -class BuildJobsTests(unittest.TestCase): - def test_job_counts_labels_and_word_bounds(self): - kernels, meta = pr.build_jobs(list(pr.OPS), [32, 64], exhaustive=True) - # 2 waves * 2 ops * (4 sweep modes * 2 halves + 2 case kernels) = 40 kernels - self.assertEqual(len(kernels), 40) - self.assertEqual(len(meta), 40) - labels = [] - for k, entry in zip(kernels, meta): - self.assertTrue(k.raw) - self.assertLessEqual(k.words, 16384) - self.assertEqual(k.wave, entry[1]) - for ln in k.lines: - if ln.startswith(".L_pknorm_sweep_") and ln.endswith(":"): - labels.append(ln) - self.assertEqual(len(labels), 32) - self.assertEqual(len(set(labels)), 32) - - def test_no_exhaustive_jobs(self): - kernels, meta = pr.build_jobs(["v_cvt_pknorm_i16_f16"], [32], exhaustive=False) - self.assertEqual(len(kernels), 2) - self.assertTrue(all(m[0] == "cases" for m in meta)) - - -class MockedCLITests(unittest.TestCase): - def test_pass_and_json_lf_endings(self): - oracle = FakeOracle() - with tempfile.TemporaryDirectory() as tmp: - rep = Path(tmp) / "sub" / "report.json" - rc, out, err = _run_main(oracle, "--json", str(rep)) - self.assertEqual(rc, 0, out + err) - self.assertTrue(oracle.closed) - self.assertIn("mismatches=0, wave_diffs=0, clamp_diffs=0, raw_omod_diffs=0", out) - raw = rep.read_bytes() - self.assertNotIn(b"\r\n", raw) - doc = json.loads(raw.decode("utf-8")) - self.assertEqual(doc["sweep_halves"], 1048576) - self.assertEqual(doc["sweep_words"], 524288) - self.assertEqual(doc["case_words"], 8 * len(pr.CASES)) - self.assertEqual(doc["mismatches"], 0) - self.assertEqual(doc["wave_diffs"], 0) - self.assertEqual(doc["clamp_diffs"], 0) - self.assertEqual(doc["raw_omod_diffs"], 0) - - def test_failure_modes_and_exit_codes(self): - self.assertEqual(_run_main(FakeOracle(mismatch_sweep=True))[0], 1) - self.assertEqual(_run_main(FakeOracle(mismatch_case=True), "--no-exhaustive")[0], 1) - self.assertEqual(_run_main(FakeOracle(wave_diff=True))[0], 1) - self.assertEqual(_run_main(FakeOracle(clamp_diff=True), "--no-exhaustive")[0], 1) - self.assertEqual(_run_main(FakeOracle(raw_omod_diff=True), "--no-exhaustive")[0], 1) - - oracle_err = FakeOracle(error_msg="assemble failed") - rc, out, _ = _run_main(oracle_err, "--no-exhaustive") - self.assertEqual(rc, 2) - self.assertIn("harness error:", out) - self.assertTrue(oracle_err.closed) - - non_gfx10 = FakeOracle(arch="gfx1100", device="fake gfx1100") - rc, out, _ = _run_main(non_gfx10) - self.assertEqual(rc, 77) - self.assertIn("not GFX10", out) - - buf = io.StringIO() - with mock.patch.object(runner, "open_oracle", side_effect=runner.Unavailable("missing clang")), redirect_stdout(buf): - rc = pr.main([]) - self.assertEqual(rc, 77) - - with tempfile.TemporaryDirectory() as tmp, redirect_stderr(io.StringIO()): - with self.assertRaises(SystemExit) as cm: - pr.main(["--json", tmp]) - self.assertEqual(cm.exception.code, 2) - - -class LiveHardwareTests(unittest.TestCase): - def test_live_gfx1036_oracle(self): - buf = io.StringIO() - err = io.StringIO() - with redirect_stdout(buf), redirect_stderr(err): - rc = pr.main(["--hw-arch", "gfx1036"]) - if rc == 77: - self.skipTest(buf.getvalue().strip() or "gfx1036 hardware oracle unavailable") - self.assertEqual(rc, 0, buf.getvalue() + err.getvalue()) - self.assertIn("mismatches=0, wave_diffs=0, clamp_diffs=0, raw_omod_diffs=0", buf.getvalue()) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/test_d16_format_probe.py b/tests/test_d16_format_probe.py deleted file mode 100644 index c5c55d0a9..000000000 --- a/tests/test_d16_format_probe.py +++ /dev/null @@ -1,308 +0,0 @@ -"""tools/d16_format_probe.py: the candidate rules, the GFX10 descriptor, what each kernel stages and loads, the -comparison and its exit codes (through a fake oracle that plays the GPU), and the exit-77 contract. The last class -runs on the hardware when the oracle tools are present and the GPU is GFX10, and is skipped otherwise. Standard -library only.""" -import io -import json -import os -from contextlib import redirect_stderr, redirect_stdout -from fractions import Fraction -from pathlib import Path -import random -import re -import subprocess -import sys -import tempfile -import unittest -from unittest import mock - -TOOLS = Path(__file__).resolve().parents[1] / "tools" -sys.path.insert(0, str(TOOLS)) -import d16_format_probe as pr # noqa: E402 -from hw_oracle import asm, runner # noqa: E402 - - -class Rules(unittest.TestCase): - def test_self_test(self): - with redirect_stdout(io.StringIO()): - self.assertEqual(pr.self_test(), 0) - - def test_the_489_counts_in_docs_design(self): - # docs/design.md ("d16 and f16 format narrowing"): with RTZ narrowing 123 of 256 UNORM8, 31,742 of 65,536 - # UNORM16 and 110 of 256 SNORM8 values came out 1 ulp low - self.assertEqual(pr.rte_rtz_disagreements("unorm", 8), 123) - self.assertEqual(pr.rte_rtz_disagreements("snorm", 8), 110) - self.assertEqual(pr.rte_rtz_disagreements("unorm", 16), 31742) - - def test_only_four_16_bit_values_separate_one_rounding_from_two(self): - split = {(k, v) for k in ("unorm", "snorm") for v in range(65536) - if pr.models16(k, 16, v)["rte"] != pr.models16(k, 16, v)["f32_rte"]} - self.assertEqual(split, {("unorm", 0xFFAF), ("unorm", 0xFFEF), ("snorm", 0x7FF7), ("snorm", 0x8009)}) - - def test_8_and_10_bit_formats_only_tell_rte_from_rtz(self): - for kind, n in (("unorm", 8), ("snorm", 8), ("unorm", 10)): - for v in range(1 << n): - m = pr.models16(kind, n, v) - self.assertEqual(len({m["f32_rte"], m["rte"], m["mul_rte"], m["f32_rte_flush"]}), 1, (kind, v)) - - def test_snorm_minimum_is_minus_one_and_f32_decode_is_exact(self): - self.assertEqual(pr.models16("snorm", 8, 0x80)["f32_rte"], 0xBC00) - self.assertEqual(pr.models16("snorm", 8, 0x81)["f32_rte"], 0xBC00) - self.assertEqual(pr.models32("unorm", 16, 0xFFFF)["f32_rte"], 0x3F800000) - self.assertEqual(pr.models32("unorm", 8, 0x80)["f32_rte"], 0x3F008081) # 128 / 255 - - def test_round_frac_matches_the_fraction_form(self): - """round_frac works in integers; the Fraction form it replaced is the reference here, for f16 and f32 and - both modes: 16-bit format quotients, the first and last significands of a binade exact, at a tie and just - under one (a tie at the last one carries into the next binade), the same for denormals, powers of two down - past the smallest denormal, random fractions in [-1, 1], and all of them negated.""" - def reference(x, prec, emin, rtz=False): - if x == 0: - return Fraction(0) - sign, a = (-1 if x < 0 else 1), abs(x) - e = a.numerator.bit_length() - a.denominator.bit_length() - if Fraction(2) ** e > a: - e -= 1 - if Fraction(2) ** (e + 1) <= a: - e += 1 - ulp = Fraction(2) ** (max(e, emin) - prec + 1) - q = a / ulp - return sign * (q.numerator // q.denominator if rtz else round(q)) * ulp - - rng = random.Random(161) - for prec, emin in ((11, -14), (24, -126)): - cases = {Fraction(v, 65535) for v in range(0, 65536, 97)} - cases |= {Fraction(v, 32767) for v in range(0, 32768, 89)} - for e in (-1, -2, -7, emin): # the binade [2^e, 2^(e+1)), ulp 2^(e - prec + 1) - ulp = Fraction(2) ** (e - prec + 1) - for m in (2 ** (prec - 1), 2 ** (prec - 1) + 1, 2 ** prec - 2, 2 ** prec - 1): # first and last - cases |= {m * ulp, (m + Fraction(1, 2)) * ulp, (m + Fraction(1, 3)) * ulp} # exact, tie, below - ulp = Fraction(2) ** (emin - prec + 1) # denormals: 0 < x < 2^emin, the same ulp - for m in (0, 1, 2, 3, 2 ** (prec - 1) - 1): - cases |= {m * ulp, (m + Fraction(1, 2)) * ulp, (m + Fraction(1, 4)) * ulp} - cases |= {Fraction(1, 2 ** j) for j in range(prec - emin + 3)} # down to under the smallest denormal - cases |= {Fraction(rng.randrange(-(1 << 40), 1 << 40), rng.randrange(1 << 40, 1 << 41)) - for _ in range(400)} - cases |= {-c for c in cases} - for x in sorted(cases): - for rtz in (False, True): - self.assertEqual(pr.round_frac(x, prec, emin, rtz), reference(x, prec, emin, rtz), - (x, prec, emin, rtz)) - - -class Kernels(unittest.TestCase): - def test_descriptor_word3(self): - w = pr.descriptor_word3(8) - self.assertEqual([w & 7, w >> 3 & 7, w >> 6 & 7, w >> 9 & 7], [4, 5, 6, 7]) - self.assertEqual((w >> 12 & 0x7F, w >> 24 & 1, w >> 28 & 3, w >> 30), (8, 1, 3, 0)) - - def test_every_value_is_staged_once(self): - for fmt, (_, _, n) in pr.FORMATS.items(): - seen = [] - for inst, base in pr.jobs(fmt): - if inst != "buffer_d16": - continue - self.assertEqual(pr.kernel_lines(inst, fmt, base)[0], f"v_add_nc_u32 v1, 0x{base:x}, v0") - seen += [(base + t) & ((1 << n) - 1) for t in range(min(pr.THREADS, (1 << n) - base))] - self.assertEqual(seen, list(range(1 << n)), fmt) - - def test_mtbuf_names_the_format_and_mubuf_takes_it_from_the_descriptor(self): - lines = pr.kernel_lines("tbuffer_d16", "snorm16", 0) - self.assertIn("format:8 offen glc dlc", lines[10]) - self.assertTrue(pr.kernel_lines("buffer_d16", "snorm16", 0)[10].startswith("buffer_load_format_d16_x")) - self.assertIn(f"s_mov_b32 s11, 0x{pr.descriptor_word3(8):x}", lines) - - def test_kernels_assemble_for_rdna2(self): - try: - clang = runner.find_clang() - except runner.Unavailable as e: - self.skipTest(str(e)) - kernels = [asm.Kernel(pr.kernel_lines(inst, fmt, 0), 32, pr.THREADS, pr.WORDS, raw=True, vgprs=8, sgprs=16) - for fmt in pr.FORMATS for inst in pr.INSTS] - text, names, _ = asm.module_text(kernels, "gfx1031", wave=32) - with tempfile.TemporaryDirectory() as d: - s = Path(d) / "k.s" - s.write_text(text, encoding="utf-8") - r = subprocess.run([clang, "--target=amdgcn-amd-amdhsa", "-mcpu=gfx1031", "-c", str(s), "-o", - str(Path(d) / "k.o")], capture_output=True, text=True) - self.assertEqual(r.returncode, 0, r.stderr[:800]) - self.assertIn("global_store_dword v4, v3, s[2:3]", text) - self.assertIn("s_waitcnt_vscnt null, 0x0", text) - - -class FakeOracle: - """Plays the GPU: reads each kernel's base, format code and load, and answers with a rule's bits.""" - arch = "gfx1031" - device = "fake gfx1031" - - def __init__(self, rule="rte", clobber_hi=False, wave64_off=None, drop=0, none_at=None): - self.rule, self.clobber_hi, self.wave64_off = rule, clobber_hi, wave64_off - self.drop, self.none_at = drop, none_at # answer `drop` fewer kernels; no result for kernel `none_at` - - def run(self, kernels, words=4): - code_of = {c: (f, k, n) for f, (c, k, n) in pr.FORMATS.items()} - out = [] - for k in kernels: - base = int(re.search(r"0x([0-9a-f]+)", k.lines[0]).group(1), 16) - w3 = int(next(ln for ln in k.lines if ln.startswith("s_mov_b32 s11")).split("0x")[1], 16) - fmt, kind, n = code_of[w3 >> 12 & 0x7F] - load = k.lines[10] - staged = [(base + t) & ((1 << n) - 1) for t in range(pr.THREADS)] - res = [] - for v in staged: - if kind == "f16": - bits = v - elif load.startswith("buffer_load_format_x"): - res.append(pr.models32(kind, n, v)["f32_rte"]) - continue - else: - bits = pr.models16(kind, n, v)[self.rule] - if self.wave64_off is not None and k.wave == 64 and v == self.wave64_off: - bits ^= 1 - hi = 0 if self.clobber_hi else pr.HI_SEED - res.append(hi | bits) - out.append(staged + res) - if self.none_at is not None: - out[self.none_at] = None - return out[:len(out) - self.drop] if self.drop else out - - def close(self): - pass - - -def run_main(oracle, *args): - buf = io.StringIO() - with mock.patch.object(runner, "open_oracle", return_value=oracle), redirect_stdout(buf): - rc = pr.main(["--formats", "unorm8,float16", *args]) - return rc, buf.getvalue() - - -class Compare(unittest.TestCase): - def test_the_translators_rule_matches_everywhere(self): - rc, out = run_main(FakeOracle()) - self.assertEqual(rc, 0, out) - self.assertIn("off the rule 0", out) - self.assertIn("own bits 65536/65536", out) - - def test_double_rounding_hardware_shows_the_four_halfway_values(self): - buf = io.StringIO() - with mock.patch.object(runner, "open_oracle", return_value=FakeOracle("f32_rte")), redirect_stdout(buf): - rc = pr.main(["--formats", "unorm16,snorm16", "--waves", "32"]) - self.assertEqual(rc, 0, buf.getvalue()) - self.assertEqual(buf.getvalue().count("off the rule 2"), 4) # MUBUF and MTBUF, two formats - self.assertIn("value 0xffef: hw 0x3c00, rule 0x3bff", buf.getvalue()) - - def test_rtz_hardware_is_a_finding_not_a_failure(self): - with tempfile.TemporaryDirectory() as d: - j = os.path.join(d, "r.json") - rc, out = run_main(FakeOracle("f32_rtz"), "--json", j) - with open(j, encoding="utf-8") as f: - rep = json.load(f) - self.assertEqual(rc, 0, out) - d16 = rep["formats"]["unorm8"]["insts"]["buffer_d16"] - self.assertEqual(d16["off_rule"], 123) - self.assertEqual(d16["match"]["f32_rtz"], 256) - self.assertIn("f32_rtz", d16["first_off"][0]["fits"]) - - def test_a_wave_difference_exits_1(self): - rc, out = run_main(FakeOracle(wave64_off=9)) - self.assertEqual(rc, 1, out) - - def test_a_short_result_list_is_a_harness_error(self): - # BUILD-733: fewer results than kernels used to be zipped away, leaving values unchecked and exit 0. - for drop in (1, 10_000): # one kernel missing, then every result (an empty list) - with self.subTest(drop=drop): - rc, out = run_main(FakeOracle(drop=drop)) - self.assertEqual(rc, 2) - self.assertRegex(out, r"harness error: \w+ wave32: the oracle returned \d+ results for \d+ kernels") - - def test_a_missing_result_is_a_harness_error(self): - rc, out = run_main(FakeOracle(none_at=0)) - self.assertEqual(rc, 2) - self.assertIn("base 0: no result", out) - - def test_a_clobbered_high_half_is_a_harness_error(self): - rc, out = run_main(FakeOracle(clobber_hi=True)) - self.assertEqual(rc, 2, out) - self.assertIn("high half", out) - - def test_not_gfx10_exits_77(self): - o = FakeOracle() - o.arch = "gfx1150" - rc, out = run_main(o) - self.assertEqual(rc, 77, out) - - -class Cli(unittest.TestCase): - def test_exits_77_without_the_tools(self): - env = dict(os.environ, LEONIDA_AMD_CLANG=str(TOOLS / "no-such-clang.exe"), LEONIDA_HW_DRM_NODE="") - r = subprocess.run([sys.executable, "-I", str(TOOLS / "d16_format_probe.py"), "--formats", "unorm8"], - capture_output=True, text=True, env=env) - self.assertEqual(r.returncode, 77, r.stdout + r.stderr) - self.assertIn("unavailable", r.stdout) - - def test_unknown_format_is_a_usage_error(self): - r = subprocess.run([sys.executable, "-I", str(TOOLS / "d16_format_probe.py"), "--formats", "unorm12"], - capture_output=True, text=True) - self.assertEqual(r.returncode, 2) - self.assertIn("unorm12", r.stderr) - - -class OnHardware(unittest.TestCase): - @classmethod - def setUpClass(cls): - try: - cls.oracle = runner.open_oracle() - except runner.Unavailable as e: - raise unittest.SkipTest(f"hardware oracle unavailable: {e}") from None - if asm.family(cls.oracle.arch) != "gfx10": - cls.oracle.close() - raise unittest.SkipTest(f"{cls.oracle.arch} is not GFX10") - - @classmethod - def tearDownClass(cls): - cls.oracle.close() - - def test_unorm8_controls_hold_and_both_wave_sizes_agree(self): - w32 = pr.sweep(self.oracle, "unorm8", 32) - w64 = pr.sweep(self.oracle, "unorm8", 64) - self.assertEqual(w32, w64) - res = pr.classify("unorm8", w32) - self.assertEqual(res["control"], []) - self.assertEqual(w32["buffer_d16"][255] & 0xFFFF, 0x3C00) - self.assertEqual(w32["buffer_d16"][0] & 0xFFFF, 0) - self.assertEqual(w32["buffer_f32"][255], 0x3F800000) - - -class ReportPathTests(unittest.TestCase): - """--json names a file; its folder is created and a write failure is one line, not a traceback.""" - - def test_json_creates_a_missing_folder(self): - with tempfile.TemporaryDirectory() as d: - report = os.path.join(d, "reports", "deeper", "r.json") - rc, out = run_main(FakeOracle(), "--json", report) - self.assertEqual(rc, 0, out) - self.assertTrue(os.path.isfile(report)) - - def test_json_folder_is_refused(self): - with tempfile.TemporaryDirectory() as d: - with self.assertRaises(SystemExit): - run_main(FakeOracle(), "--json", d) - - def test_a_failed_write_is_one_line(self): - with tempfile.TemporaryDirectory() as d: - blocker = os.path.join(d, "not_a_folder") - with open(blocker, "wb") as f: - f.write(b"keep me") - err = io.StringIO() - with redirect_stderr(err): - rc, _ = run_main(FakeOracle(), "--json", os.path.join(blocker, "r.json")) - self.assertEqual(rc, 2) - self.assertIn("ERROR: cannot write", err.getvalue()) - self.assertNotIn("Traceback", err.getvalue()) - with open(blocker, "rb") as f: - self.assertEqual(f.read(), b"keep me") - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/test_d16_image_probe.py b/tests/test_d16_image_probe.py deleted file mode 100644 index e109d27ed..000000000 --- a/tests/test_d16_image_probe.py +++ /dev/null @@ -1,228 +0,0 @@ -"""tools/d16_image_probe.py: the textures and samplers, the kernels (they assemble for gfx1031), the comparison and its -exit codes through a fake oracle that plays the GPU, and the exit-77 contract. The last class runs on the hardware -when the oracle tools are present and the GPU is GFX10, and is skipped otherwise. Standard library only.""" -import io -import json -import os -from contextlib import redirect_stdout -from pathlib import Path -import re -import struct -import subprocess -import sys -import tempfile -import unittest -from unittest import mock - -TOOLS = Path(__file__).resolve().parents[1] / "tools" -sys.path.insert(0, str(TOOLS)) -import d16_format_probe as fp # noqa: E402 -import d16_image_probe as ip # noqa: E402 -from hw_oracle import asm, runner # noqa: E402 - - -class Textures(unittest.TestCase): - def test_self_test(self): - with redirect_stdout(io.StringIO()): - self.assertEqual(ip.self_test(), 0) - - def test_every_value_of_a_16_bit_format_is_one_texel(self): - seen = [v for b in range(ip.blocks("unorm16")) for v in ip.block_values("unorm16", b)] - self.assertEqual(seen, list(range(65536))) - - def test_the_float32_set_starts_with_the_two_unorm_halfway_quotients(self): - v, ties = ip.float32_texels() - self.assertEqual([fp.f32_bits(fp.to_f32(fp.Fraction(65519, 65535))), - fp.f32_bits(fp.to_f32(fp.Fraction(65455, 65535)))], [v[0], v[2]]) - self.assertTrue(all((b & 0x1FFF) == 0x1000 for b in v[:ties]), "the ties come first") - self.assertEqual(len(v), ip.TEXELS) - - def test_t_sharp_carries_the_format(self): - for fmt, (code, _, _, width) in ip.FORMATS.items(): - w = ip.t_words("gfx1031", fmt) - self.assertEqual((w[1] >> 20) & 0x1FF, code, fmt) - self.assertEqual(w[2] >> 31, 1) # RESOURCE_LEVEL on GFX10 - self.assertEqual(((w[2] & 0xFFF) << 2 | w[1] >> 30) + 1, width) - - -class Kernels(unittest.TestCase): - def test_kernels_assemble_for_rdna2(self): - try: - clang = runner.find_clang() - except runner.Unavailable as e: - self.skipTest(str(e)) - for wave in (32, 64): - kernels = [asm.Kernel(ip.kernel_lines("gfx1031", f"{f}_0", f, ip.block_values(f, 0), 0.5), wave, - ip.TEXELS, ip.TEXELS * ip.WORDS_PER_LANE, raw=True, vgprs=24, sgprs=32) - for f in ip.FORMATS] - text, _, _ = asm.module_text(kernels, "gfx1031", wave=wave) - with tempfile.TemporaryDirectory() as d: - s = Path(d) / "k.s" - s.write_text(text, encoding="utf-8") - r = subprocess.run([clang, "--target=amdgcn-amd-amdhsa", "-mcpu=gfx1031", - *(["-mwavefrontsize64"] if wave == 64 else []), "-c", str(s), "-o", - str(Path(d) / "k.o")], capture_output=True, text=True) - self.assertEqual(r.returncode, 0, r.stderr[:800]) - self.assertIn("image_sample_lz v13, v[16:17], s[8:15], s[20:23] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm d16", - text) - - -def _val(kind, n, v, rule): - return fp.models16(kind, n, v)[rule] - - -class FakeOracle: - """Plays the GPU from each kernel's label (.Lpc_) and its texture: d16 results by `rule`, f32 loads - correctly rounded, bilinear f32 the rounded exact mix and its d16 rounded from that f32 to nearest even.""" - arch = "gfx1031" - device = "fake gfx1031" - - def __init__(self, rule="rte", f32_off=False, wave64_flip=False, tie="even"): - self.rule, self.f32_off, self.wave64_flip, self.tie = rule, f32_off, wave64_flip, tie - - def run(self, kernels, words=4): - out = [] - for k in kernels: - fmt, block = re.match(r"\.Lpc(\w+?)_(\d+):", k.lines[1]).groups() - _, kind, n, width = ip.FORMATS[fmt] - vals = ip.block_values(fmt, int(block)) - frac = struct.unpack("f16 (RTE) reference, and a check that the d16 pair packer in -tools/rdna2spirv.py (pack_f16_pair_int, through Gen.f16_bits) is integer ops only. - -Runs with the standard library only (no GPU, LLVM, or SPIRV-Tools required): - python -I tests/test_d16_pack.py -""" -import math -import os -import random -import struct -import sys -import unittest - -ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) -sys.path.insert(0, os.path.join(ROOT, "tools")) -import rdna2spirv # noqa: E402 - - -def f32_to_f16_int_sim(u): - """Python mirror of the integer RTE narrowing #489 added as Gen.f32_to_f16_int (IEEE-754 binary16 RTE). Since - 2026-11-22 Gen.f16_bits does it for the d16 results too: the two gave the same bits on 30,648 inputs.""" - u &= 0xFFFFFFFF - sign = (u >> 16) & 0x8000 - exp = (u >> 23) & 0xFF - mant = u & 0x7FFFFF - - # Special: exp == 255 - is_nan = mant != 0 - spec_res = (sign | 0x7E00 | (mant >> 13)) if is_nan else (sign | 0x7C00) - - # Normal: exp >= 113 - n_exp = (exp - 112) & 0xFFFFFFFF - lsb = (mant >> 13) & 1 - rounded = (mant + (0xFFF + lsb)) & 0xFFFFFFFF - raw_norm = ((n_exp << 10) + (rounded >> 13)) & 0xFFFFFFFF - ovf = (exp > 142) or (raw_norm >= 0x7C00) - norm_res = sign | (0x7C00 if ovf else raw_norm) - - # Subnormal / underflow: 102 <= exp <= 112 (shift strictly in [14, 24] for all exp) - full_m = mant | 0x800000 - in_sub = (exp >= 102) and (exp <= 112) - s = (126 - exp) if in_sub else 24 - assert 14 <= s <= 24 - q = full_m >> s - half_bit = 1 << (s - 1) - rem_mask = (1 << s) - 1 - rem = full_m & rem_mask - round_up = (rem > half_bit) or ((rem == half_bit) and ((q & 1) != 0)) - sub_mag = (q + (1 if round_up else 0)) & 0xFFFFFFFF - sub_res = sign | (sub_mag if in_sub else 0) - - fin_res = norm_res if (exp >= 113) else sub_res - return spec_res if (exp == 255) else fin_res - - -def ref_f16(u): - f = struct.unpack(" rounds to even (0x0000) - (0x33000001, 0x0001), # > 2^-25 -> rounds up to smallest subnormal - (0x33800000, 0x0001), # 2^-24 = smallest f16 subnormal - (0x387FC000, 0x03FF), # exact largest f16 subnormal (1023 * 2^-24) - (0x387FDFFF, 0x03FF), # just below subnormal/normal tie -> 0x03FF - (0x387FE000, 0x0400), # exact tie (1023.5 * 2^-24) -> rounds to even (0x0400) - (0x38800000, 0x0400), # smallest f16 normal (2^-14) - (0x477FE000, 0x7BFF), # max finite f16 (65504.0) - (0x477FF000, 0x7C00), # 65520.0 (tie above 65504) -> rounds to even (+Inf) - (0xC77FF000, 0xFC00), # -65520.0 -> -Inf - (0x7F800000, 0x7C00), # +Inf - (0xFF800000, 0xFC00), # -Inf - ] - for u, want in cases: - self.assertEqual(f32_to_f16_int_sim(u), want, f"u=0x{u:08x}") - - # Quiet and signaling NaNs (both signs) produce quiet NaNs preserving sign. - for u in (0x7F800001, 0x7FC00000, 0x7FFFFFFF, 0xFF800001, 0xFFC00000, 0xFFFFFFFF): - got = f32_to_f16_int_sim(u) - self.assertGreater(got & 0x7FFF, 0x7C00, f"not NaN for u=0x{u:08x}") - self.assertNotEqual(got & 0x0200, 0, f"not quiet NaN for u=0x{u:08x}") - self.assertEqual(got & 0x8000, (u >> 16) & 0x8000, f"sign mismatch for u=0x{u:08x}") - - def test_all_exponents_and_random_mantissas_sweep(self): - rng = random.Random(2026) - boundary_mants = (0, 1, 2, 0xFFF, 0x1000, 0x1001, 0x1FFF, 0x2000, 0x2001, - 0x3FFF, 0x4000, 0x4001, 0x7FFFFE, 0x7FFFFF) - for sign_bit in (0, 0x80000000): - for exp in range(256): - mants = list(boundary_mants) + [rng.randrange(0, 1 << 23) for _ in range(100)] - for m in mants: - u = sign_bit | (exp << 23) | m - got = f32_to_f16_int_sim(u) - want = ref_f16(u) - if want is None: - self.assertGreater(got & 0x7FFF, 0x7C00) - self.assertNotEqual(got & 0x0200, 0) - self.assertEqual(got & 0x8000, (u >> 16) & 0x8000) - else: - self.assertEqual(got, want, f"u=0x{u:08x}") - - def test_gen_helper_emits_only_integer_ops_and_no_packhalf2x16(self): - g = rdna2spirv.Gen("ps") - g.pack_f16_pair_int("%f0", "%f1") - body = "\n".join(g.body) - self.assertNotIn("PackHalf2x16", body) - self.assertNotIn("OpExtInst", body) - self.assertIn("OpBitcast %uint", body) - self.assertIn("OpSelect %uint", body) - self.assertIn("OpBitwiseOr %uint", body) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/test_d3d12_guid_sites.py b/tests/test_d3d12_guid_sites.py deleted file mode 100644 index f44e6d523..000000000 --- a/tests/test_d3d12_guid_sites.py +++ /dev/null @@ -1,251 +0,0 @@ -"""tools/d3d12_guid_sites.py on hand-built PE32+ images (no game files, no SDK needed).""" -import json -import os -import struct -import subprocess -import sys -import tempfile -import unittest -import uuid - -ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) -sys.path.insert(0, os.path.join(ROOT, "tools")) - -import d3d12_guid_sites as sites # noqa: E402 - -QUEUE = uuid.UUID("0ec870a6-5d7e-4c22-8cfc-5baae07616ed") -RESOURCE = uuid.UUID("696442be-a72e-4059-bc79-5b5c98040fad") -UNKNOWN = uuid.UUID("12345678-4242-4343-8444-555555555555") -KNOWN = {"ID3D12CommandQueue": QUEUE, "ID3D12Resource": RESOURCE} - - -def build_rdata(rdata: bytes, imports=None): - """The .rdata body, its import directory RVA and its IAT slot RVAs; pe32plus places it at 0x2000. - - imports: {dll_name: [function names, ...]} placed inside the body after `rdata`. - """ - body = bytearray(rdata) - imports = imports or {} - rdata_rva = 0x2000 - iat_slots = [] - - def put(blob, align=8): - while len(body) % align: - body.append(0) - at = len(body) - body.extend(blob) - return rdata_rva + at - - imp = 0 - descriptors = [] - for dll, funcs in imports.items(): - thunks = [put(struct.pack(" SizeOfRawData; an import descriptor's Name RVA - # falls in the unbacked virtual tail (va + rsize), which must not alias section 2's raw bytes. - sect1_rva, sect1_raw, sect1_rsize, sect1_vsize = 0x1000, 0x200, 0x200, 0x1000 - sect2_rva, sect2_raw = 0x2000, 0x400 - # Place one import descriptor at sect1_rva pointing Name RVA into sect1's virtual tail (0x1200) - # and Lookup/IAT at 0x1040 (single ordinal #80 + null terminator). - sect1 = bytearray(sect1_rsize) - struct.pack_into(" str: - """Build a synthetic MIDL_INTERFACE string from method specifications. - - methods: list of (return_type, method_name, params, const_qualifier) - directives: optional list of (insert_index, directive_line) - """ - lines = [ - f'MIDL_INTERFACE("{guid}")', - f"{name} : public {base}", - "{", - "public:", - ] - - directive_map: dict[int, list[str]] = {} - if directives: - for idx, d in directives: - directive_map.setdefault(idx, []).append(d) - - for i, (ret, m_name, params, const_q) in enumerate(methods): - if i in directive_map: - lines.extend(directive_map[i]) - const_suffix = f" {const_q}" if const_q else "" - lines.append(f" virtual {ret} STDMETHODCALLTYPE {m_name}({params}){const_suffix} = 0;") - - end_idx = len(methods) - if end_idx in directive_map: - lines.extend(directive_map[end_idx]) - - lines.append("};") - lines.append("") - return "\n".join(lines) - - -class SyntheticStubGenerationTests(unittest.TestCase): - """Test suite covering synthetic COM interface stub generation.""" - - def test_stub_class_structure_and_signature(self): - methods = [ - ("void", "SyntheticExecute", "UINT count", ""), - ("HRESULT", "SyntheticQuery", "REFIID riid, void **ppv", ""), - ("UINT64", "SyntheticGetSize", "void", "const"), - ] - hdr = make_midl_interface("ISyntheticObject", "IUnknown", methods) - ifaces = gen.parse_interfaces(hdr) - - emitted = gen.emit_class(ifaces, "ISyntheticObject") - self.assertTrue(emitted.startswith("class ISyntheticObjectStubs : public ISyntheticObject {\npublic:")) - self.assertTrue(emitted.endswith("};")) - self.assertIn("// ISyntheticObject", emitted) - - # Check exact method overrides - self.assertIn( - ' void STDMETHODCALLTYPE SyntheticExecute(UINT count) override ' - '{ ::rt::d3d12::stub("ISyntheticObject::SyntheticExecute"); }', - emitted, - ) - self.assertIn( - ' HRESULT STDMETHODCALLTYPE SyntheticQuery(REFIID riid, void **ppv) override ' - '{ ::rt::d3d12::stub("ISyntheticObject::SyntheticQuery"); return E_NOTIMPL; }', - emitted, - ) - self.assertIn( - ' UINT64 STDMETHODCALLTYPE SyntheticGetSize(void) const override ' - '{ ::rt::d3d12::stub("ISyntheticObject::SyntheticGetSize"); return {}; }', - emitted, - ) - - def test_return_type_conventions(self): - """Verify return conventions: void -> nothing, HRESULT -> E_NOTIMPL, other -> {}.""" - methods = [ - ("void", "DoVoid", "void", ""), - ("HRESULT", "DoHresult", "void", ""), - ("BOOL", "DoBool", "void", ""), - ("UINT", "DoUint", "void", ""), - ("float", "DoFloat", "void", ""), - ("void*", "DoPointer", "void", ""), - ("ID3D12Resource*", "DoInterfacePtr", "void", ""), - ("D3D12_CPU_DESCRIPTOR_HANDLE", "DoDescriptor", "void", ""), - ] - hdr = make_midl_interface("ITypeCheck", "IUnknown", methods) - ifaces = gen.parse_interfaces(hdr) - emitted = gen.emit_class(ifaces, "ITypeCheck") - - self.assertIn('{ ::rt::d3d12::stub("ITypeCheck::DoVoid"); }', emitted) - self.assertIn('{ ::rt::d3d12::stub("ITypeCheck::DoHresult"); return E_NOTIMPL; }', emitted) - self.assertIn('{ ::rt::d3d12::stub("ITypeCheck::DoBool"); return {}; }', emitted) - self.assertIn('{ ::rt::d3d12::stub("ITypeCheck::DoUint"); return {}; }', emitted) - self.assertIn('{ ::rt::d3d12::stub("ITypeCheck::DoFloat"); return {}; }', emitted) - self.assertIn('{ ::rt::d3d12::stub("ITypeCheck::DoPointer"); return {}; }', emitted) - self.assertIn('{ ::rt::d3d12::stub("ITypeCheck::DoInterfacePtr"); return {}; }', emitted) - self.assertIn('{ ::rt::d3d12::stub("ITypeCheck::DoDescriptor"); return {}; }', emitted) - - def test_preprocessor_directives_in_stub(self): - methods = [ - ("void", "StepBefore", "void", ""), - ("void", "StepConditional", "void", ""), - ("void", "StepAfter", "void", ""), - ] - directives = [ - (1, "#if defined(SYNTHETIC_FEATURE_A)"), - (2, "#endif"), - ] - hdr = make_midl_interface("IConditional", "IUnknown", methods, directives=directives) - ifaces = gen.parse_interfaces(hdr) - emitted = gen.emit_class(ifaces, "IConditional") - - self.assertIn("#if defined(SYNTHETIC_FEATURE_A)", emitted) - self.assertIn("#endif", emitted) - lines = emitted.splitlines() - idx_if = lines.index("#if defined(SYNTHETIC_FEATURE_A)") - idx_cond = next(i for i, l in enumerate(lines) if "StepConditional" in l) - idx_endif = lines.index("#endif") - self.assertLess(idx_if, idx_cond) - self.assertLess(idx_cond, idx_endif) - - def test_comment_stripping(self): - """Block comments must be removed without leaving orphaned tokens.""" - raw = """\ -MIDL_INTERFACE("11111111-0000-0000-0000-000000000001") -IWithComments : public IUnknown -{ -public: - /* Block comment before method */ - virtual void STDMETHODCALLTYPE ActiveOne(void) = 0; - /* - virtual void STDMETHODCALLTYPE CommentedOutMethod(int x) = 0; - */ - virtual HRESULT STDMETHODCALLTYPE ActiveTwo(void) = 0; /* Trailing block comment */ -}; -""" - ifaces = gen.parse_interfaces(raw) - items = ifaces["IWithComments"][1] - method_names = [item[2] for item in items if item[0] == "m"] - self.assertEqual(method_names, ["ActiveOne", "ActiveTwo"]) - self.assertNotIn("CommentedOutMethod", method_names) - - -class EntryPointEnumerationTests(unittest.TestCase): - """Test suite covering entry point enumeration from synthetic export name lists.""" - - def test_entry_point_enumeration_order(self): - synthetic_export_names = [ - "CreateSyntheticCommandQueue", - "CreateSyntheticCommandAllocator", - "CreateSyntheticGraphicsPipeline", - "CreateSyntheticComputePipeline", - "CreateSyntheticDescriptorHeap", - "CreateSyntheticRootSignature", - ] - methods = [("HRESULT", name, "void", "") for name in synthetic_export_names] - hdr = make_midl_interface("ISyntheticDevice", "IUnknown", methods) - ifaces = gen.parse_interfaces(hdr) - - self.assertIn("ISyntheticDevice", ifaces) - base, items = ifaces["ISyntheticDevice"] - self.assertEqual(base, "IUnknown") - - enumerated_names = [item[2] for item in items if item[0] == "m"] - self.assertEqual(enumerated_names, synthetic_export_names) - - def test_multiline_entry_point_parameters(self): - raw = """\ -MIDL_INTERFACE("22222222-0000-0000-0000-000000000002") -ISyntheticComplex : public IUnknown -{ -public: - virtual HRESULT STDMETHODCALLTYPE DispatchComplexOperation( - _In_ const void *pInputBuffer, - _In_ UINT inputBufferSize, - _Out_writes_bytes_(outputBufferSize) void *pOutputBuffer, - UINT outputBufferSize, - _Out_opt_ UINT *pBytesWritten - ) = 0; -}; -""" - ifaces = gen.parse_interfaces(raw) - items = ifaces["ISyntheticComplex"][1] - self.assertEqual(len(items), 1) - tag, ret, name, params, const_q = items[0] - self.assertEqual(tag, "m") - self.assertEqual(ret, "HRESULT") - self.assertEqual(name, "DispatchComplexOperation") - self.assertIn("pInputBuffer", params) - self.assertIn("pBytesWritten", params) - self.assertEqual(const_q, "") - - def test_entry_point_metadata_extraction(self): - methods = [ - ("void", "GetDeviceName", "char *pOut, size_t maxLen", "const"), - ("HRESULT", "SetShaderState", "UINT slot, void *pBytecode", ""), - ("UINT", "GetDescriptorIncrementSize", "UINT heapType", "const"), - ] - hdr = make_midl_interface("ISyntheticInfo", "IUnknown", methods) - ifaces = gen.parse_interfaces(hdr) - items = ifaces["ISyntheticInfo"][1] - - self.assertEqual(len(items), 3) - self.assertEqual(items[0], ("m", "void", "GetDeviceName", "char *pOut, size_t maxLen", "const")) - self.assertEqual(items[1], ("m", "HRESULT", "SetShaderState", "UINT slot, void *pBytecode", "")) - self.assertEqual(items[2], ("m", "UINT", "GetDescriptorIncrementSize", "UINT heapType", "const")) - - -class OrdinalMappingTests(unittest.TestCase): - """Test suite covering ordinal mapping across COM interface vtable hierarchies.""" - - def test_single_interface_ordinal_sequence(self): - export_names = ["EntryAlpha", "EntryBeta", "EntryGamma", "EntryDelta"] - methods = [("void", name, "void", "") for name in export_names] - hdr = make_midl_interface("ISingleHierarchy", "IUnknown", methods) - ifaces = gen.parse_interfaces(hdr) - - emitted = gen.emit_class(ifaces, "ISingleHierarchy") - method_lines = [l.strip() for l in emitted.splitlines() if "::rt::d3d12::stub" in l] - - # In COM vtable ordering, methods are laid out in exact declaration order (ordinals 0..N-1) - self.assertEqual(len(method_lines), len(export_names)) - for ordinal, name in enumerate(export_names): - expected_stub_call = f'::rt::d3d12::stub("ISingleHierarchy::{name}");' - self.assertIn(expected_stub_call, method_lines[ordinal]) - - def test_multi_tier_inheritance_ordinal_mapping(self): - """In COM inheritance, base interface entry points occupy lower ordinals - - than derived interface entry points in the virtual table. - """ - root_methods = [ - ("void", "RootEntry1", "void", ""), - ("void", "RootEntry2", "void", ""), - ] - child_methods = [ - ("HRESULT", "ChildEntry1", "void", ""), - ("HRESULT", "ChildEntry2", "void", ""), - ] - grandchild_methods = [ - ("UINT", "GrandchildEntry1", "void", ""), - ] - - hdr_root = make_midl_interface("ISyntheticRoot", "IUnknown", root_methods, guid="33333333-0000-0000-0000-000000000001") - hdr_child = make_midl_interface("ISyntheticChild", "ISyntheticRoot", child_methods, guid="33333333-0000-0000-0000-000000000002") - hdr_grandchild = make_midl_interface("ISyntheticGrandchild", "ISyntheticChild", grandchild_methods, guid="33333333-0000-0000-0000-000000000003") - - combined = f"{hdr_root}\n{hdr_child}\n{hdr_grandchild}" - ifaces = gen.parse_interfaces(combined) - - # Chain must be in topological order: Root -> Child -> Grandchild - chain_order = gen.chain(ifaces, "ISyntheticGrandchild") - self.assertEqual(chain_order, ["ISyntheticRoot", "ISyntheticChild", "ISyntheticGrandchild"]) - - emitted = gen.emit_class(ifaces, "ISyntheticGrandchild") - stub_calls = re.findall(r'::rt::d3d12::stub\("([^"]+)"\);', emitted) - - expected_ordinal_map = [ - (0, "ISyntheticRoot::RootEntry1"), - (1, "ISyntheticRoot::RootEntry2"), - (2, "ISyntheticChild::ChildEntry1"), - (3, "ISyntheticChild::ChildEntry2"), - (4, "ISyntheticGrandchild::GrandchildEntry1"), - ] - - self.assertEqual(len(stub_calls), len(expected_ordinal_map)) - for expected_ordinal, expected_symbol in expected_ordinal_map: - self.assertEqual(stub_calls[expected_ordinal], expected_symbol) - - def test_synthetic_export_name_list_ordinal_stability(self): - """Ensures that changing or extending the synthetic export list preserves ordinal stability.""" - export_list = [f"SyntheticExport_{i:03d}" for i in range(25)] - methods = [("void", name, f"int param_{i}", "") for i, name in enumerate(export_list)] - hdr = make_midl_interface("IBigExportTable", "IUnknown", methods) - ifaces = gen.parse_interfaces(hdr) - - emitted = gen.emit_class(ifaces, "IBigExportTable") - stub_calls = re.findall(r'::rt::d3d12::stub\("([^"]+)"\);', emitted) - - self.assertEqual(len(stub_calls), 25) - for ordinal, name in enumerate(export_list): - self.assertEqual(stub_calls[ordinal], f"IBigExportTable::{name}") - - -class InheritanceChainValidationTests(unittest.TestCase): - """Test suite covering inheritance chain traversal and cycle detection.""" - - def test_single_leaf_chain(self): - methods = [("void", "DoRoot", "void", "")] - hdr = make_midl_interface("IRootOnly", "IUnknown", methods) - ifaces = gen.parse_interfaces(hdr) - self.assertEqual(gen.chain(ifaces, "IRootOnly"), ["IRootOnly"]) - - def test_deep_linear_chain(self): - headers = [ - make_midl_interface("INodeA", "IUnknown", [("void", "OpA", "void", "")]), - make_midl_interface("INodeB", "INodeA", [("void", "OpB", "void", "")]), - make_midl_interface("INodeC", "INodeB", [("void", "OpC", "void", "")]), - make_midl_interface("INodeD", "INodeC", [("void", "OpD", "void", "")]), - ] - ifaces = gen.parse_interfaces("\n".join(headers)) - self.assertEqual(gen.chain(ifaces, "INodeD"), ["INodeA", "INodeB", "INodeC", "INodeD"]) - - def test_missing_base_interface_raises_system_exit(self): - hdr = make_midl_interface("IOrphanInterface", "INonExistentBase", [("void", "Op", "void", "")]) - ifaces = gen.parse_interfaces(hdr) - with self.assertRaises(SystemExit) as cm: - gen.chain(ifaces, "IOrphanInterface") - self.assertIn("INonExistentBase not found", str(cm.exception)) - - def test_direct_self_cycle_raises_system_exit(self): - hdr = make_midl_interface("ISelfCyclic", "ISelfCyclic", [("void", "Op", "void", "")]) - ifaces = gen.parse_interfaces(hdr) - with self.assertRaises(SystemExit) as cm: - gen.chain(ifaces, "ISelfCyclic") - self.assertIn("circular inheritance", str(cm.exception)) - - def test_indirect_cycle_raises_system_exit(self): - headers = [ - make_midl_interface("ICycleA", "ICycleC", [("void", "OpA", "void", "")]), - make_midl_interface("ICycleB", "ICycleA", [("void", "OpB", "void", "")]), - make_midl_interface("ICycleC", "ICycleB", [("void", "OpC", "void", "")]), - ] - ifaces = gen.parse_interfaces("\n".join(headers)) - with self.assertRaises(SystemExit) as cm: - gen.chain(ifaces, "ICycleC") - self.assertIn("circular inheritance", str(cm.exception)) - - -class ParserSyntaxValidationTests(unittest.TestCase): - """Test suite covering edge cases and syntax rejections in parse_interfaces.""" - - def test_empty_string_returns_empty_dict(self): - self.assertEqual(gen.parse_interfaces(""), {}) - self.assertEqual(gen.parse_interfaces("// empty comment\n/* nothing */"), {}) - - def test_unterminated_method_declaration_raises(self): - broken = """\ -MIDL_INTERFACE("44444444-0000-0000-0000-000000000001") -IUnterminated : public IUnknown -{ -public: - virtual void STDMETHODCALLTYPE BadMethod(int a); -}; -""" - with self.assertRaises(SystemExit) as cm: - gen.parse_interfaces(broken) - self.assertIn("unterminated declaration", str(cm.exception)) - - def test_unparseable_method_syntax_raises(self): - malformed = """\ -MIDL_INTERFACE("44444444-0000-0000-0000-000000000002") -IMalformed : public IUnknown -{ -public: - virtual InvalidSyntaxWithoutCallingConvention() = 0; -}; -""" - with self.assertRaises(SystemExit) as cm: - gen.parse_interfaces(malformed) - self.assertIn("cannot parse", str(cm.exception)) - - -class StubGenerationCliAndIoTests(unittest.TestCase): - """Test suite covering CLI argument parsing, environment resolution, and file generation.""" - - def setUp(self): - tmp = tempfile.TemporaryDirectory() - self.addCleanup(tmp.cleanup) - self.tmp_dir = tmp.name - - self.synth_header = os.path.join(self.tmp_dir, "synthetic_d3d12.h") - methods_a = [("void", "StubA1", "void", ""), ("HRESULT", "StubA2", "void", "")] - methods_b = [("UINT", "StubB1", "void", "")] - content = f"{make_midl_interface('ISynthA', 'IUnknown', methods_a)}\n{make_midl_interface('ISynthB', 'ISynthA', methods_b)}" - with open(self.synth_header, "w", encoding="utf-8") as f: - f.write(content) - - self.out_file = os.path.join(self.tmp_dir, "gen_sub", "out_stubs.h") - - def test_find_header_in_include_path(self): - # Empty env - with mock.patch.dict(os.environ, {"INCLUDE": ""}, clear=False): - self.assertIsNone(gen.find_header()) - - # Target file named d3d12.h in a search directory - d3d12_dir = os.path.join(self.tmp_dir, "sdk_include") - os.makedirs(d3d12_dir, exist_ok=True) - d3d12_path = os.path.join(d3d12_dir, "d3d12.h") - with open(d3d12_path, "w", encoding="utf-8") as f: - f.write("// synthetic d3d12.h\n") - - # INCLUDE is os.pathsep-separated, as find_header reads it (";" on Windows, ":" elsewhere). - empty_dir = os.path.join(self.tmp_dir, "empty") - os.makedirs(empty_dir, exist_ok=True) - with mock.patch.dict(os.environ, {"INCLUDE": os.pathsep.join([empty_dir, d3d12_dir])}, clear=False): - self.assertEqual(gen.find_header(), d3d12_path) - - def test_cli_output_generation_and_boilerplate(self): - argv = [ - "gen_d3d12_stubs.py", - "--out", - self.out_file, - "--header", - self.synth_header, - "ISynthA", - "ISynthB", - ] - with mock.patch("sys.argv", argv): - res = gen.main() - self.assertEqual(res, 0) - self.assertTrue(os.path.isfile(self.out_file)) - - with open(self.out_file, encoding="utf-8") as f: - generated = f.read() - - # Check required boilerplate - self.assertTrue(generated.startswith("// Generated by tools/gen_d3d12_stubs.py")) - self.assertIn("#pragma once", generated) - self.assertIn("#include ", generated) - self.assertIn("namespace rt::d3d12 { void stub(const char* method); }", generated) - self.assertIn("#pragma warning(push)", generated) - self.assertIn("#pragma warning(disable : 4100)", generated) - self.assertIn("#pragma warning(pop)", generated) - - # Check classes exist in order - self.assertIn("class ISynthAStubs : public ISynthA", generated) - self.assertIn("class ISynthBStubs : public ISynthB", generated) - self.assertLess(generated.index("class ISynthAStubs"), generated.index("class ISynthBStubs")) - - def test_idempotent_file_writing(self): - argv = [ - "gen_d3d12_stubs.py", - "--out", - self.out_file, - "--header", - self.synth_header, - "ISynthA", - ] - with mock.patch("sys.argv", argv): - gen.main() - self.assertTrue(os.path.isfile(self.out_file)) - mtime_initial = os.stat(self.out_file).st_mtime_ns - - # Second execution with exact same arguments should not modify mtime - with mock.patch("sys.argv", argv): - gen.main() - mtime_second = os.stat(self.out_file).st_mtime_ns - self.assertEqual(mtime_initial, mtime_second) - - def test_missing_header_raises_system_exit(self): - argv = [ - "gen_d3d12_stubs.py", - "--out", - self.out_file, - "ISynthA", - ] - with mock.patch.dict(os.environ, {"INCLUDE": ""}, clear=False): - with mock.patch("sys.argv", argv): - with self.assertRaises(SystemExit) as cm: - gen.main() - self.assertIn("d3d12.h not found", str(cm.exception)) - - - -class MethodCoverageAndReportTests(unittest.TestCase): - """Test suite covering method coverage reporting and CLI report mode.""" - - def setUp(self): - tmp = tempfile.TemporaryDirectory() - self.addCleanup(tmp.cleanup) - self.tmp_dir = tmp.name - - self.synth_header = os.path.join(self.tmp_dir, "synthetic_coverage_d3d12.h") - methods_base = [ - ("void", "BaseMethodOne", "void", ""), - ("HRESULT", "BaseMethodTwo", "int arg", ""), - ] - methods_derived = [ - ("UINT", "DerivedMethodOne", "float f", "const"), - ("void*", "DerivedMethodTwo", "void", ""), - ] - content = ( - f"{make_midl_interface('ICovBase', 'IUnknown', methods_base)}\n" - f"{make_midl_interface('ICovDerived', 'ICovBase', methods_derived)}" - ) - with open(self.synth_header, "w", encoding="utf-8") as f: - f.write(content) - - def test_implemented_names_parsing(self): - src1 = os.path.join(self.tmp_dir, "impl1.cpp") - src2 = os.path.join(self.tmp_dir, "impl2.cpp") - - with open(src1, "w", encoding="utf-8") as f: - f.write("""\ -// Synthetic implementation file 1 -HRESULT STDMETHODCALLTYPE BaseMethodOne(void) override { return S_OK; } -void STDMETHODCALLTYPE DerivedMethodTwo(void) override {} -""") - - with open(src2, "w", encoding="utf-8") as f: - f.write("""\ -// Synthetic implementation file 2 -UINT STDMETHODCALLTYPE NonInterfaceMethod(int x) { return 0; } -""") - - names = gen.implemented_names([src1, src2]) - self.assertEqual(names, {"BaseMethodOne", "DerivedMethodTwo", "NonInterfaceMethod"}) - - def test_coverage_calculation_metrics(self): - src = os.path.join(self.tmp_dir, "impl.cpp") - with open(src, "w", encoding="utf-8") as f: - f.write("""\ -void STDMETHODCALLTYPE BaseMethodOne(void) override {} -UINT STDMETHODCALLTYPE DerivedMethodOne(float f) const override { return 1; } -""") - - with open(self.synth_header, encoding="utf-8") as f: - ifaces = gen.parse_interfaces(f.read()) - - rep = gen.coverage(ifaces, ["ICovDerived"], [src]) - self.assertEqual(len(rep), 1) - item = rep[0] - self.assertEqual(item["interface"], "ICovDerived") - self.assertEqual(item["methods"], 4) - self.assertEqual(item["implemented"], 2) - self.assertEqual(item["open"], ["ICovBase::BaseMethodTwo", "ICovDerived::DerivedMethodTwo"]) - - def test_coverage_multiple_leaves(self): - src = os.path.join(self.tmp_dir, "impl.cpp") - with open(src, "w", encoding="utf-8") as f: - f.write("void STDMETHODCALLTYPE BaseMethodOne(void) override {}\n") - - with open(self.synth_header, encoding="utf-8") as f: - ifaces = gen.parse_interfaces(f.read()) - - rep = gen.coverage(ifaces, ["ICovBase", "ICovDerived"], [src]) - self.assertEqual(len(rep), 2) - self.assertEqual(rep[0]["interface"], "ICovBase") - self.assertEqual(rep[0]["methods"], 2) - self.assertEqual(rep[0]["implemented"], 1) - self.assertEqual(rep[0]["open"], ["ICovBase::BaseMethodTwo"]) - - self.assertEqual(rep[1]["interface"], "ICovDerived") - self.assertEqual(rep[1]["methods"], 4) - self.assertEqual(rep[1]["implemented"], 1) - self.assertEqual(rep[1]["open"], [ - "ICovBase::BaseMethodTwo", - "ICovDerived::DerivedMethodOne", - "ICovDerived::DerivedMethodTwo", - ]) - - def test_cli_report_mode_generates_json_file(self): - src = os.path.join(self.tmp_dir, "impl.cpp") - with open(src, "w", encoding="utf-8") as f: - f.write("void STDMETHODCALLTYPE BaseMethodOne(void) override {}\n") - - rep_file = os.path.join(self.tmp_dir, "coverage.json") - argv = [ - "gen_d3d12_stubs.py", - "--report", - rep_file, - "--source", - src, - "--header", - self.synth_header, - "ICovDerived", - ] - with mock.patch("sys.argv", argv): - res = gen.main() - self.assertEqual(res, 0) - self.assertTrue(os.path.isfile(rep_file)) - - with open(rep_file, encoding="utf-8") as f: - data = json.load(f) - self.assertEqual(len(data), 1) - self.assertEqual(data[0]["interface"], "ICovDerived") - self.assertEqual(data[0]["methods"], 4) - self.assertEqual(data[0]["implemented"], 1) - - def test_cli_missing_out_and_report_raises_error(self): - argv = [ - "gen_d3d12_stubs.py", - "--header", - self.synth_header, - "ICovDerived", - ] - with mock.patch("sys.argv", argv), contextlib.redirect_stderr(io.StringIO()): - with self.assertRaises(SystemExit): - gen.main() - - def test_cli_report_missing_source_raises_error(self): - argv = [ - "gen_d3d12_stubs.py", - "--report", - os.path.join(self.tmp_dir, "rep.json"), - "--header", - self.synth_header, - "ICovDerived", - ] - with mock.patch("sys.argv", argv), contextlib.redirect_stderr(io.StringIO()): - with self.assertRaises(SystemExit): - gen.main() - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/test_d3d12_xs_surface.py b/tests/test_d3d12_xs_surface.py deleted file mode 100644 index 274dab600..000000000 --- a/tests/test_d3d12_xs_surface.py +++ /dev/null @@ -1,119 +0,0 @@ -"""d3d12_xs_surface: the 116-slot export table and the 83 standard GUIDs. - - python -m pytest tests/test_d3d12_xs_surface.py -q - python -I tests/test_d3d12_xs_surface.py - -The SCARAB cross-check runs only when SCARAB_REF points at a checkout; it is not needed for CI. -""" -import os -import sys -import tempfile -import unittest -from unittest import mock - -sys.path.insert(0, os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "tools")) -import d3d12_xs_surface as S # noqa: E402 - - -def test_slots_are_116(): - assert S.check_slots() == [] - - -def test_data_classes(): - assert S.check_data_classes() == [] - - -def test_guid_values(): - assert S.check_guid_values() == [] - - -def test_iid_block_is_alphabetical(): - assert S.check_iid_order() == [] - - -def test_unrecovered_console_iids_stay_outside_the_table(): - # SCARAB's provenance says the runtime does not export these; they must not acquire a - # guessed ordinal or GUID value from ordering. - assert len(S.UNRECOVERED_CONSOLE_IIDS) == 4 - assert S.check_unrecovered_console_iids() == [] - - -def test_standard_iids_match_sdk(): - um, _shared = S.find_sdk_include() - if not um: - raise unittest.SkipTest("Windows SDK headers not found") - errors, checked, _um = S.check_sdk() - assert errors == [] - assert checked == 83 - - -def test_sdk_include_override_accepts_a_trailing_separator(): - # WINDOWS_SDK_INCLUDE may name the version folder or its um folder, with or without a - # trailing separator; all four spellings must find the same um/shared pair. - with tempfile.TemporaryDirectory() as tmp: - version = os.path.join(tmp, "10.0.99999.0") - um = os.path.join(version, "um") - os.makedirs(um) - os.makedirs(os.path.join(version, "shared")) - saved = os.environ.get("WINDOWS_SDK_INCLUDE") - try: - for value in (um, um + os.sep, version, version + os.sep): - os.environ["WINDOWS_SDK_INCLUDE"] = value - got_um, got_shared = S.find_sdk_include() - assert got_um is not None, value - assert os.path.normcase(got_um) == os.path.normcase(um), (value, got_um) - assert os.path.normcase(got_shared) == os.path.normcase( - os.path.join(version, "shared")), (value, got_shared) - finally: - if saved is None: - os.environ.pop("WINDOWS_SDK_INCLUDE", None) - else: - os.environ["WINDOWS_SDK_INCLUDE"] = saved - - -def test_sdk_discovery_sorts_versions_numerically(): - # A lexicographic sort puts 10.0.99999.0 above 10.0.100000.0, but numerically 100000 is the - # newer build; automatic discovery must compare the version by number, not by string. - with tempfile.TemporaryDirectory() as tmp: - include = os.path.join(tmp, "Windows Kits", "10", "Include") - os.makedirs(include) - for ver in ("10.0.99999.0", "10.0.100000.0"): - vdir = os.path.join(include, ver) - os.makedirs(os.path.join(vdir, "um")) - os.makedirs(os.path.join(vdir, "shared")) - with mock.patch.dict(os.environ, {"ProgramFiles(x86)": tmp, "ProgramFiles": tmp}, - clear=False): - os.environ.pop("WINDOWS_SDK_INCLUDE", None) - os.environ.pop("SDK_INCLUDE", None) - got_um, got_shared = S.find_sdk_include() - assert got_um is not None - assert os.path.normcase(got_um) == os.path.normcase( - os.path.join(include, "10.0.100000.0", "um")), got_um - assert os.path.normcase(got_shared) == os.path.normcase( - os.path.join(include, "10.0.100000.0", "shared")), got_shared - - -def test_scarab_cross_check(): - root = os.environ.get("SCARAB_REF") - if not root: - raise unittest.SkipTest("SCARAB_REF is not set") - errors, _notes = S.check_scarab(root) - assert errors == [] - - -if __name__ == "__main__": - test_slots_are_116() - test_data_classes() - test_guid_values() - test_iid_block_is_alphabetical() - test_unrecovered_console_iids_stay_outside_the_table() - test_sdk_include_override_accepts_a_trailing_separator() - test_sdk_discovery_sorts_versions_numerically() - # Call the two optional checks through their real definitions so this runner cannot drift from them; both - # raise unittest.SkipTest when their inputs (SDK headers, SCARAB_REF) are absent. - for optional in (test_standard_iids_match_sdk, test_scarab_cross_check): - try: - optional() - except unittest.SkipTest as skip: - print(f"skipped: {skip}") - print("ok") diff --git a/tests/test_dds_png.py b/tests/test_dds_png.py deleted file mode 100644 index 4d800b25b..000000000 --- a/tests/test_dds_png.py +++ /dev/null @@ -1,1273 +0,0 @@ -"""Tests for tools/dds_png.py, built from synthetic DDS buffers (no game data). - - python -I tests/test_dds_png.py -""" -import contextlib -import importlib.util -import io -import os -import struct -import tempfile -import unittest -from unittest import mock -import zlib - -ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) - - -def load_module(): - path = os.path.join(ROOT, "tools", "dds_png.py") - spec = importlib.util.spec_from_file_location("dds_png_under_test", path) - module = importlib.util.module_from_spec(spec) - spec.loader.exec_module(module) - return module - - -dds = load_module() - -DDPF_ALPHAPIXELS = 0x1 -DDPF_FOURCC = 0x4 -DDPF_RGB = 0x40 - - -def dds_buffer(width, height, payload=b"", *, flags=0, fourcc=b"\x00\x00\x00\x00", - bit_count=0, masks=(0, 0, 0, 0), mips=0, dxgi=None, pitch=None, alpha_mode=0): - """A 128-byte DDS header, a DX10 header when dxgi is set, then the payload.""" - header = bytearray(128) - header[0:4] = b"DDS " - struct.pack_into(">6); the -# 0-to-255 ramps below are those interpolations for each weight table. -RAMP2 = (0, 84, 171, 255) -RAMP3 = (0, 36, 72, 108, 147, 183, 219, 255) -RAMP4 = (0, 16, 36, 52, 68, 84, 104, 120, 135, 151, 171, 187, 203, 219, 239, 255) - - -def bc7_block(*fields): - """Pack (value, bit_width) fields LSB-first into one 128-bit BC7 block.""" - packed = 0 - pos = 0 - for value, width in fields: - assert 0 <= value < (1 << width), (value, width) - packed |= value << pos - pos += width - assert pos == 128, pos - return packed.to_bytes(16, "little") - - -def bc7_mode(mode): - """The mode field: `mode` zero bits, then a one bit.""" - return (1 << mode, mode + 1) - - -def bc7_values(values, width): - return [(v, width) for v in values] - - -def bc7_indices(indices, width, anchors): - """Per-pixel index fields; anchor pixels drop their implicit zero MSB.""" - return [(v, width - 1 if p in anchors else width) for p, v in enumerate(indices)] - - -def gray(v, a=255): - return (v, v, v, a) - - -# Mode 0, partition 0 (subsets 0011/0011/0221/2222, anchors 0, 3, 15), 4-bit RGB -# endpoints plus one p-bit each. Subset 0 is a black-to-white ramp; subsets 1 and -# 2 are flat (8, 4, 2) with p-bit 1 -> 5-bit (17, 9, 5) and p-bit 0 -> (16, 8, 4). -BC7_MODE0 = bc7_block( - bc7_mode(0), (0, 4), - *bc7_values([0, 15, 8, 8, 8, 8], 4), - *bc7_values([0, 15, 4, 4, 4, 4], 4), - *bc7_values([0, 15, 2, 2, 2, 2], 4), - *bc7_values([0, 1, 1, 1, 0, 0], 1), - *bc7_indices([3, 7, 5, 3, 1, 4, 5, 5, 6, 5, 5, 5, 5, 5, 5, 3], 3, (0, 3, 15)), -) -BC7_MODE0_PIXELS = [ - gray(108), gray(255), (140, 74, 41, 255), (140, 74, 41, 255), - gray(36), gray(147), (140, 74, 41, 255), (140, 74, 41, 255), - gray(219), (132, 66, 33, 255), (132, 66, 33, 255), (140, 74, 41, 255), - (132, 66, 33, 255), (132, 66, 33, 255), (132, 66, 33, 255), (132, 66, 33, 255), -] - -# Mode 1, partition 17 (subset 1 = pixels 1, 2, 3, 7; anchors 0, 2), 6-bit RGB and -# one shared p-bit per subset. Subset 0 is flat (32, 16, 8) + p 1 -> 7-bit -# (65, 33, 17) -> (131, 66, 34). Subset 1 runs red -> green with p 0: 63 -> 126 -> 253. -BC7_MODE1 = bc7_block( - bc7_mode(1), (17, 6), - *bc7_values([32, 32, 63, 0], 6), - *bc7_values([16, 16, 0, 63], 6), - *bc7_values([8, 8, 0, 0], 6), - *bc7_values([1, 0], 1), - *bc7_indices([2, 0, 3, 4, 6, 6, 6, 7, 6, 6, 6, 6, 6, 6, 6, 6], 3, (0, 2)), -) -BC7_MODE1_PIXELS = [ - (131, 66, 34, 255), (253, 0, 0, 255), (146, 107, 0, 255), (107, 146, 0, 255), - (131, 66, 34, 255), (131, 66, 34, 255), (131, 66, 34, 255), (0, 253, 0, 255), -] + [(131, 66, 34, 255)] * 8 - -# Mode 2, partition 11 (columns 0, 0, 1, 2; anchors 0, 6, 15), 5-bit RGB, no -# p-bits. Subset 0 is a gray ramp, subset 1 flat (16, 8, 4) -> (132, 66, 33), -# subset 2 runs red -> blue. -BC7_MODE2 = bc7_block( - bc7_mode(2), (11, 6), - *bc7_values([0, 31, 16, 16, 31, 0], 5), - *bc7_values([0, 31, 8, 8, 0, 0], 5), - *bc7_values([0, 31, 4, 4, 0, 31], 5), - *bc7_indices([1, 2, 3, 0, 3, 0, 1, 1, 0, 0, 2, 2, 0, 0, 3, 1], 2, (0, 6, 15)), -) -BC7_MODE2_PIXELS = [ - gray(84), gray(171), (132, 66, 33, 255), (255, 0, 0, 255), - gray(255), gray(0), (132, 66, 33, 255), (171, 0, 84, 255), - gray(0), gray(0), (132, 66, 33, 255), (84, 0, 171, 255), - gray(0), gray(0), (132, 66, 33, 255), (171, 0, 84, 255), -] - -# Mode 3, partition 18 (subset 1 = pixels 8, 12, 13, 14; anchors 0, 8), 7-bit RGB -# plus one p-bit per endpoint: subset 1 endpoints (64, 32, 16) become -# (128, 64, 32) with p 0 and (129, 65, 33) with p 1. -BC7_MODE3 = bc7_block( - bc7_mode(3), (18, 6), - *bc7_values([0, 127, 64, 64], 7), - *bc7_values([0, 127, 32, 32], 7), - *bc7_values([0, 127, 16, 16], 7), - *bc7_values([0, 1, 0, 1], 1), - *bc7_indices([1, 2, 3, 0, 0, 0, 0, 0, 1, 0, 0, 0, 3, 0, 2, 3], 2, (0, 8)), -) -BC7_MODE3_PIXELS = [ - gray(84), gray(171), gray(255), gray(0), - gray(0), gray(0), gray(0), gray(0), - (128, 64, 32, 255), gray(0), gray(0), gray(0), - (129, 65, 33, 255), (128, 64, 32, 255), (129, 65, 33, 255), gray(255), -] - - -def bc7_mode4(rotation, selector): - """Mode 4: gray 5-bit colour ramp, 6-bit alpha 255 -> 0, 2-bit then 3-bit indices.""" - return bc7_block( - bc7_mode(4), (rotation, 2), (selector, 1), - *bc7_values([0, 31], 5), *bc7_values([0, 31], 5), *bc7_values([0, 31], 5), - *bc7_values([63, 0], 6), - *bc7_indices([p % 4 for p in range(16)], 2, (0,)), - *bc7_indices([p % 8 for p in range(16)], 3, (0,)), - ) - - -# Mode 5, rotation 2 (swap G and A): 7-bit colour (127, 0..127, 64) -> (255, ramp, -# 129), 8-bit alpha 10 -> 250, colour indices by column, alpha indices by row. -BC7_MODE5 = bc7_block( - bc7_mode(5), (2, 2), - *bc7_values([127, 127], 7), *bc7_values([0, 127], 7), *bc7_values([64, 64], 7), - *bc7_values([10, 250], 8), - *bc7_indices([p % 4 for p in range(16)], 2, (0,)), - *bc7_indices([p // 4 for p in range(16)], 2, (0,)), -) -BC7_MODE5_PIXELS = [ - (255, (10, 89, 171, 250)[p // 4], 129, RAMP2[p % 4]) for p in range(16) -] - -# Mode 6: 7-bit RGBA plus p-bits 0 / 1, so endpoints are R 0 / 255, G 254 / 1, -# B 128 / 129, A 254 / 255. Pixel p uses 4-bit index p. -BC7_MODE6 = bc7_block( - bc7_mode(6), - *bc7_values([0, 127], 7), *bc7_values([127, 0], 7), - *bc7_values([64, 64], 7), *bc7_values([127, 127], 7), - *bc7_values([0, 1], 1), - *bc7_indices(list(range(16)), 4, (0,)), -) - -# Mode 7, partition 0 (columns 0, 0, 1, 1; anchors 0, 15), 5-bit RGBA plus p-bits. -# Subset 0 ramps every channel 0 -> 255; subset 1 is flat (16, 8, 4, 2) + p 1 -> -# 6-bit (33, 17, 9, 5) -> (134, 69, 36, 20), so the p-bit reaches alpha too. -BC7_MODE7 = bc7_block( - bc7_mode(7), (0, 6), - *bc7_values([0, 31, 16, 16], 5), *bc7_values([0, 31, 8, 8], 5), - *bc7_values([0, 31, 4, 4], 5), *bc7_values([0, 31, 2, 2], 5), - *bc7_values([0, 1, 1, 1], 1), - *bc7_indices([1, 2, 3, 3, 3, 0, 2, 1, 0, 0, 1, 1, 0, 0, 2, 0], 2, (0, 15)), -) -BC7_MODE7_PIXELS = [ - gray(84, 84), gray(171, 171), (134, 69, 36, 20), (134, 69, 36, 20), - gray(255, 255), gray(0, 0), (134, 69, 36, 20), (134, 69, 36, 20), - gray(0, 0), gray(0, 0), (134, 69, 36, 20), (134, 69, 36, 20), - gray(0, 0), gray(0, 0), (134, 69, 36, 20), (134, 69, 36, 20), -] - - -def bc7_dds(width, height, payload, dxgi=98): - return dds_buffer(width, height, payload, flags=DDPF_FOURCC, fourcc=b"DX10", dxgi=dxgi) - - -def pixel(rgba, width, x, y): - start = (y * width + x) * 4 - return tuple(rgba[start:start + 4]) - - -def pixels(rgba): - return [tuple(rgba[i:i + 4]) for i in range(0, len(rgba), 4)] - - -def png_chunks(png): - """Split a PNG into (type, payload, stored_crc) tuples without trusting it.""" - assert png[:8] == dds.PNG_SIGNATURE, "missing PNG signature" - pos = 8 - chunks = [] - while pos < len(png): - length = struct.unpack_from(">I", png, pos)[0] - ctype = png[pos + 4:pos + 8] - payload = png[pos + 8:pos + 8 + length] - crc = struct.unpack_from(">I", png, pos + 8 + length)[0] - chunks.append((ctype, payload, crc)) - pos += 12 + length - return chunks - - -class HeaderTests(unittest.TestCase): - def test_legacy_dxt1_header(self): - info = dds.parse_dds_header(dds_buffer(8, 4, flags=DDPF_FOURCC, fourcc=b"DXT1")) - self.assertEqual(info["width"], 8) - self.assertEqual(info["height"], 4) - self.assertEqual(info["format"], "BC1") - self.assertIsNone(info["dxgi_format"]) - self.assertEqual(info["mip_count"], 1) - self.assertEqual(info["data_offset"], 128) - - def test_mip_count_defaults_to_one_when_zero(self): - self.assertEqual( - dds.parse_dds_header(dds_buffer(4, 4, flags=DDPF_FOURCC, fourcc=b"DXT5", mips=0))["mip_count"], - 1, - ) - - def test_mip_count_is_reported(self): - self.assertEqual( - dds.parse_dds_header(dds_buffer(4, 4, flags=DDPF_FOURCC, fourcc=b"DXT5", mips=3))["mip_count"], - 3, - ) - - def test_dx10_header_moves_the_payload(self): - info = dds.parse_dds_header(dds_buffer(16, 16, flags=DDPF_FOURCC, fourcc=b"DX10", dxgi=71)) - self.assertEqual(info["format"], "BC1") - self.assertEqual(info["dxgi_format"], 71) - self.assertEqual(info["data_offset"], 148) - - def test_fourcc_aliases(self): - cases = { - b"DXT1": "BC1", b"DXT3": "BC2", b"DXT5": "BC3", - b"ATI1": "BC4", b"BC4U": "BC4", b"BC4S": "BC4_SNORM", - b"ATI2": "BC5", b"BC5U": "BC5", b"BC5S": "BC5_SNORM", - } - for fourcc, expected in cases.items(): - with self.subTest(fourcc=fourcc): - info = dds.parse_dds_header(dds_buffer(4, 4, flags=DDPF_FOURCC, fourcc=fourcc)) - self.assertEqual(info["format"], expected) - - def test_canonical_uncompressed_masks(self): - cases = { - (0x00FF0000, 0x0000FF00, 0x000000FF, 0xFF000000): "BGRA8", - (0x00FF0000, 0x0000FF00, 0x000000FF, 0x00000000): "BGRX8", - (0x000000FF, 0x0000FF00, 0x00FF0000, 0xFF000000): "RGBA8", - (0x000000FF, 0x0000FF00, 0x00FF0000, 0x00000000): "RGBX8", - } - for masks, expected in cases.items(): - with self.subTest(masks=masks): - info = dds.parse_dds_header( - dds_buffer( - 2, 2, flags=DDPF_RGB | DDPF_ALPHAPIXELS, bit_count=32, masks=masks, - ) - ) - self.assertEqual(info["format"], expected) - - def test_alpha_flag_removes_the_alpha_mask(self): - info = dds.parse_dds_header( - dds_buffer( - 2, 2, flags=DDPF_RGB, bit_count=32, - masks=(0x00FF0000, 0x0000FF00, 0x000000FF, 0xFF000000), - ) - ) - self.assertEqual(info["format"], "BGRX8") - - def test_custom_bitmask_falls_back_to_rgba8(self): - info = dds.parse_dds_header( - dds_buffer( - 1, 1, flags=DDPF_RGB | DDPF_ALPHAPIXELS, bit_count=32, - masks=(0x3FF00000, 0x000FFC00, 0x000003FF, 0xC0000000), - ) - ) - self.assertEqual(info["format"], "RGBA8") - - def test_rejects_short_buffer(self): - with self.assertRaises(dds.DdsError): - dds.parse_dds_header(b"DDS " + b"\x00" * 60) - - def test_rejects_bad_magic(self): - with self.assertRaises(dds.DdsError) as ctx: - dds.parse_dds_header(b"NOPE" + b"\x00" * 124) - self.assertIn("magic", str(ctx.exception)) - - def test_rejects_zero_dimensions(self): - with self.assertRaises(dds.DdsError): - dds.parse_dds_header(dds_buffer(0, 4, flags=DDPF_FOURCC, fourcc=b"DXT1")) - - def test_rejects_unknown_fourcc(self): - with self.assertRaises(dds.DdsError) as ctx: - dds.parse_dds_header(dds_buffer(4, 4, flags=DDPF_FOURCC, fourcc=b"XXXX")) - self.assertIn("FourCC", str(ctx.exception)) - - def test_rejects_non_24_or_32_bit_rgb(self): - for bit_count in (8, 16): - with self.subTest(bit_count=bit_count): - with self.assertRaises(dds.DdsError) as ctx: - dds.parse_dds_header( - dds_buffer(4, 4, flags=DDPF_RGB, bit_count=bit_count, - masks=(0x00FF0000, 0x0000FF00, 0x000000FF, 0)) - ) - self.assertIn("bit count", str(ctx.exception)) - - def test_rejects_zero_rgb_masks(self): - with self.assertRaises(dds.DdsError): - dds.parse_dds_header( - dds_buffer(4, 4, flags=DDPF_RGB, bit_count=32, masks=(0, 0, 0, 0)) - ) - - def test_rejects_truncated_dx10(self): - with self.assertRaises(dds.DdsError) as ctx: - dds.parse_dds_header( - dds_buffer(4, 4, flags=DDPF_FOURCC, fourcc=b"DX10") - ) - self.assertIn("DX10", str(ctx.exception)) - - def test_rejects_unknown_dxgi_format(self): - # 94-96 are BC6H typeless/UF16/SF16, which this decoder deliberately does not claim. - for dxgi in (94, 95, 96): - with self.subTest(dxgi=dxgi): - with self.assertRaises(dds.DdsError) as ctx: - dds.parse_dds_header(dds_buffer(4, 4, flags=DDPF_FOURCC, fourcc=b"DX10", dxgi=dxgi)) - self.assertIn(str(dxgi), str(ctx.exception)) - - def test_bc7_dxgi_aliases(self): - for dxgi in (97, 98, 99): - with self.subTest(dxgi=dxgi): - info = dds.parse_dds_header(dds_buffer(4, 4, flags=DDPF_FOURCC, fourcc=b"DX10", dxgi=dxgi)) - self.assertEqual(info["format"], "BC7") - self.assertEqual(info["dxgi_format"], dxgi) - self.assertEqual(info["data_offset"], 148) - - def test_rejects_non_contiguous_mask(self): - with self.assertRaises(dds.DdsError) as ctx: - dds.parse_dds_header( - dds_buffer(2, 2, flags=DDPF_RGB, bit_count=32, - masks=(0x00FF00FF, 0x0000FF00, 0x000000FF, 0)) - ) - self.assertIn("Non-contiguous", str(ctx.exception)) - - -class UncompressedTests(unittest.TestCase): - def test_dx10_typeless_byte_layouts(self): - payload = bytes((0x10, 0x20, 0x30, 0x40)) - for dxgi, fmt, expected in ( - (27, "RGBA8", (0x10, 0x20, 0x30, 0x40)), - (90, "BGRA8", (0x30, 0x20, 0x10, 0x40)), - (92, "BGRX8", (0x30, 0x20, 0x10, 0xFF)), - ): - with self.subTest(dxgi=dxgi): - data = dds_buffer(1, 1, payload, flags=DDPF_FOURCC, fourcc=b"DX10", dxgi=dxgi) - info = dds.parse_dds_header(data) - self.assertEqual(info["format"], fmt) - self.assertEqual(info["dxgi_format"], dxgi) - self.assertEqual(dds.decode_dds(data), (1, 1, bytes(expected))) - - def test_padded_rows_are_removed_before_channel_conversion(self): - first_row = bytes((1, 2, 3, 4)) - second_row = bytes((5, 6, 7, 8)) - payload = first_row + b"\x99" * 4 + second_row - legacy = dict(flags=DDPF_RGB | DDPF_ALPHAPIXELS, bit_count=32, - masks=(0x000000FF, 0x0000FF00, 0x00FF0000, 0xFF000000)) - dx10 = dict(flags=DDPF_FOURCC, fourcc=b"DX10", dxgi=87) - for header, expected in ((legacy, [(1, 2, 3, 4), (5, 6, 7, 8)]), - (dx10, [(3, 2, 1, 4), (7, 6, 5, 8)])): - with self.subTest(header=header): - width, height, rgba = dds.decode_dds(dds_buffer(1, 2, payload, pitch=8, **header)) - self.assertEqual((width, height), (1, 2)) - self.assertEqual(pixels(rgba), expected) - - def test_pitch_with_custom_byte_masks(self): - payload = bytes((1, 2, 3, 4)) + b"\xcc" * 4 + bytes((5, 6, 7, 8)) - data = dds_buffer( - 1, 2, payload, flags=DDPF_RGB | DDPF_ALPHAPIXELS, bit_count=32, pitch=8, - masks=(0x0000FF00, 0x00FF0000, 0xFF000000, 0x000000FF), - ) - self.assertEqual(dds.decode_dds(data), (1, 2, bytes((2, 3, 4, 1, 6, 7, 8, 5)))) - - def test_pitch_with_r10g10b10a2_masks(self): - first = (1023 << 20) | (512 << 10) | 255 | (3 << 30) - second = (512 << 10) | 1023 | (1 << 30) - payload = struct.pack(" 6 data bytes per row, padded to the 8-byte pitch some writers emit. - payload = bytes((1, 2, 3, 4, 5, 6)) + b"\x99" * 2 + bytes((7, 8, 9, 10, 11, 12)) + b"\x99" * 2 - data = dds_buffer( - 2, 2, payload, flags=DDPF_RGB, bit_count=24, pitch=8, - masks=(0x00FF0000, 0x0000FF00, 0x000000FF, 0x00000000), - ) - self.assertEqual(pixels(dds.decode_dds(data)[2]), - [(3, 2, 1, 255), (6, 5, 4, 255), (9, 8, 7, 255), (12, 11, 10, 255)]) - - def test_alpha_flag_with_zero_mask_still_decodes(self): - # Some writers set DDPF_ALPHAPIXELS on 24-bit headers with a zero alpha mask. - payload = bytes((1, 2, 3)) - data = dds_buffer( - 1, 1, payload, flags=DDPF_RGB | DDPF_ALPHAPIXELS, bit_count=24, - masks=(0x00FF0000, 0x0000FF00, 0x000000FF, 0x00000000), - ) - self.assertEqual(dds.decode_dds(data), (1, 1, bytes((3, 2, 1, 255)))) - - def test_pitch_and_truncation_errors_are_reported(self): - header = dict(flags=DDPF_RGB, bit_count=24, - masks=(0x00FF0000, 0x0000FF00, 0x000000FF, 0x00000000)) - with self.assertRaisesRegex(dds.DdsError, "pitch"): - dds.decode_dds(dds_buffer(2, 2, b"\x00" * 6, pitch=5, **header)) - with self.assertRaisesRegex(dds.DdsError, "Truncated"): - dds.decode_dds(dds_buffer(2, 2, b"\x00" * 9, pitch=6, **header)) - - def test_unsupported_24_bit_mask_layouts_are_rejected(self): - for masks in ((0x000000FF, 0x00000000, 0x00000000, 0x00000000), - (0x000000FF, 0x000000FF, 0x000000FF, 0x00000000), - (0x00000FFF, 0x000FF000, 0x0FF00000, 0x00000000)): - with self.subTest(masks=masks): - data = dds_buffer(1, 1, flags=DDPF_RGB, bit_count=24, masks=masks) - with self.assertRaisesRegex(dds.DdsError, "24-bit RGB bitmask layout"): - dds.decode_dds(data) - - def test_png_preview_round_trip(self): - payload = bytes((0x10, 0x20, 0x30, 0x40, 0x50, 0x60)) - data = dds_buffer( - 2, 1, payload, flags=DDPF_RGB, bit_count=24, - masks=(0x00FF0000, 0x0000FF00, 0x000000FF, 0x00000000), - ) - png = dds.dds_to_png_bytes(data) - self.assertEqual(png[:8], dds.PNG_SIGNATURE) - self.assertEqual(struct.unpack(">II", png[16:24]), (2, 1)) - - -class AlphaModeTests(unittest.TestCase): - def test_premultiplied_rgba_and_bgra_decode_to_straight_alpha(self): - for dxgi, rgba in ((28, (64, 32, 16, 128)), (87, (16, 32, 64, 128))): - with self.subTest(dxgi=dxgi): - data = dds_buffer(1, 1, bytes(rgba), flags=DDPF_FOURCC, fourcc=b"DX10", - dxgi=dxgi, alpha_mode=2) - self.assertEqual(dds.decode_dds(data), (1, 1, bytes((128, 64, 32, 128)))) - - def test_premultiplied_alpha_rounding_clamping_and_endpoints(self): - stored = bytes((1, 1, 1, 2, 9, 3, 1, 2, 4, 5, 6, 0, 7, 8, 9, 255)) - expected = bytes((128, 128, 128, 2, 255, 255, 128, 2, 0, 0, 0, 0, 7, 8, 9, 255)) - data = dds_buffer(4, 1, stored, flags=DDPF_FOURCC, fourcc=b"DX10", dxgi=28, alpha_mode=2) - self.assertEqual(dds.decode_dds(data), (4, 1, expected)) - - def test_premultiplied_srgb_is_unmultiplied_in_linear_light(self): - # Decode sRGB, divide linear RGB by 128/255, encode sRGB, then round to 8 bits. - # Direct division of the encoded bytes would produce (255, 197, 141), which is wrong. - for dxgi, rgba in ((29, (137, 99, 71, 128)), (91, (71, 99, 137, 128))): - with self.subTest(dxgi=dxgi): - data = dds_buffer(1, 1, bytes(rgba), flags=DDPF_FOURCC, fourcc=b"DX10", - dxgi=dxgi, alpha_mode=2) - self.assertEqual(dds.decode_dds(data), (1, 1, bytes((187, 137, 99, 128)))) - - def test_premultiplied_bc3_is_converted_after_block_decoding(self): - block = bc3_block(128, 0, 0, c0=0x4000, c1=0) - data = dds_buffer(4, 4, block, flags=DDPF_FOURCC, fourcc=b"DX10", dxgi=77, alpha_mode=2) - self.assertEqual(dds.decode_dds(data), (4, 4, bytes((131, 0, 0, 128)) * 16)) - - def test_legacy_premultiplied_fourcc_png_pixels(self): - # The two FourCCs in each pair share their block layout and differ in alpha interpretation. - bc2 = bytes([0x88] * 8) + struct.pack(" c1 mode, indices 0,1,2,3 across the row. - payload = bc1_block(0xFFFF, 0x0000, [0b11100100, 0, 0, 0]) - _, _, rgba = dds.decode_dds(dds_buffer( - 4, 1, payload, flags=DDPF_FOURCC, fourcc=b"DXT1", - )) - self.assertEqual(pixels(rgba), [ - (255, 255, 255, 255), - (0, 0, 0, 255), - (170, 170, 170, 255), - (85, 85, 85, 255), - ]) - - def test_three_color_mode_row(self): - # c0 <= c1 switches to the three-color palette with a transparent slot. - payload = bc1_block(0x0000, 0xFFFF, [0b11100100, 0, 0, 0]) - _, _, rgba = dds.decode_dds(dds_buffer( - 4, 1, payload, flags=DDPF_FOURCC, fourcc=b"DXT1", - )) - self.assertEqual(pixels(rgba), [ - (0, 0, 0, 255), - (255, 255, 255, 255), - (127, 127, 127, 255), - (0, 0, 0, 0), - ]) - - def test_second_block_lands_at_column_four(self): - payload = ( - bc1_block(0xFFFF, 0x0000, [0, 0, 0, 0]) - + bc1_block(0xF800, 0x001F, [0, 0, 0, 0]) - ) - width, height, rgba = dds.decode_dds(dds_buffer( - 8, 4, payload, flags=DDPF_FOURCC, fourcc=b"DXT1", - )) - self.assertEqual((width, height), (8, 4)) - self.assertEqual(pixel(rgba, 8, 0, 0), (255, 255, 255, 255)) - self.assertEqual(pixel(rgba, 8, 3, 3), (255, 255, 255, 255)) - self.assertEqual(pixel(rgba, 8, 4, 0), (255, 0, 0, 255)) - self.assertEqual(pixel(rgba, 8, 7, 3), (255, 0, 0, 255)) - - -class Bc2Tests(unittest.TestCase): - def test_alpha_nibbles_scale_to_bytes(self): - alpha_q = 0x3210 # nibbles 0, 1, 2, 3 from left pixel to right - payload = struct.pack(" 0 selects the eight-value alpha ramp. - indices = 0 | (1 << 3) | (2 << 6) | (7 << 9) - payload = bc3_block(255, 0, indices) - _, _, rgba = dds.decode_dds(dds_buffer( - 4, 1, payload, flags=DDPF_FOURCC, fourcc=b"DXT5", - )) - self.assertEqual([p[3] for p in pixels(rgba)], [255, 0, 219, 36]) - self.assertEqual([p[:3] for p in pixels(rgba)], [(255, 255, 255)] * 4) - - -class Bc4Tests(unittest.TestCase): - def test_unsigned_gradient(self): - indices = 0 | (1 << 3) | (2 << 6) | (7 << 9) - payload = bc4_block(200, 100, indices) - _, _, rgba = dds.decode_dds(dds_buffer( - 4, 1, payload, flags=DDPF_FOURCC, fourcc=b"ATI1", - )) - self.assertEqual(pixels(rgba), [ - (200, 200, 200, 255), - (100, 100, 100, 255), - (186, 186, 186, 255), - (114, 114, 114, 255), - ]) - - def test_snorm_negative_endpoint_maps_to_zero(self): - payload = bc4_block(129, 64, 0 | (1 << 3)) - _, _, rgba = dds.decode_dds(dds_buffer( - 2, 1, payload, flags=DDPF_FOURCC, fourcc=b"BC4S", - )) - # 129 as int8 is -127, which maps to 0; 64 maps to round(191.75) = 192. - self.assertEqual(pixels(rgba), [(0, 0, 0, 255), (192, 192, 192, 255)]) - - -class Bc5Tests(unittest.TestCase): - def test_two_channel_z_reconstruction(self): - red = bc4_block(128, 0, 0) - green = bc4_block(128, 0, 0) - payload = red + green - _, _, rgba = dds.decode_dds(dds_buffer( - 1, 1, payload, flags=DDPF_FOURCC, fourcc=b"ATI2", - )) - # r = g = 128 is almost exactly normal (0, 0), so z rounds to 255. - self.assertEqual(pixels(rgba), [(128, 128, 255, 255)]) - - def test_z_lut_matches_the_direct_formula(self): - lut = dds._get_bc5_z_lut() - self.assertEqual(len(lut), 65536) - for r in (0, 1, 64, 127, 128, 200, 254, 255): - for g in (0, 1, 64, 127, 128, 200, 254, 255): - with self.subTest(r=r, g=g): - self.assertEqual(lut[(r << 8) | g], dds._bc5_z_direct(r, g)) - - def test_large_image_uses_the_cached_lut(self): - # 64x64 is 4096 pixels, where the decoder switches to the precomputed table. - red = bc4_block(200, 100, 0 | (1 << 3) | (2 << 6) | (3 << 9)) - green = bc4_block(100, 200, 0 | (1 << 3) | (2 << 6) | (3 << 9)) - payload = (red + green) * (16 * 16) - width, height, rgba = dds.decode_dds(dds_buffer( - 64, 64, payload, flags=DDPF_FOURCC, fourcc=b"BC5U", - )) - self.assertEqual((width, height), (64, 64)) - self.assertIsNotNone(dds._BC5_Z_LUT) - lut = dds._get_bc5_z_lut() - # Red uses the 200 > 100 eight-value ramp, green the 100 <= 200 six-value one. - for x, expected in enumerate([(200, 100), (100, 200), (186, 120), (171, 140)]): - r, g = expected - self.assertEqual(pixel(rgba, 64, x, 0), (r, g, lut[(r << 8) | g], 255)) - - def test_snorm_channels(self): - payload = bc4_block(127, 0, 0 | (1 << 3)) * 2 - _, _, rgba = dds.decode_dds(dds_buffer( - 2, 1, payload, flags=DDPF_FOURCC, fourcc=b"BC5S", - )) - self.assertEqual([p[:2] for p in pixels(rgba)], [(255, 255), (128, 128)]) - self.assertEqual([p[3] for p in pixels(rgba)], [255, 255]) - - -class Bc7Tests(unittest.TestCase): - def decode(self, payload, width=4, height=4, dxgi=98): - w, h, rgba = dds.decode_dds(bc7_dds(width, height, payload, dxgi)) - self.assertEqual((w, h), (width, height)) - self.assertEqual(len(rgba), width * height * 4) - return pixels(rgba) - - def test_partitioned_modes(self): - cases = { - 0: (BC7_MODE0, BC7_MODE0_PIXELS), - 1: (BC7_MODE1, BC7_MODE1_PIXELS), - 2: (BC7_MODE2, BC7_MODE2_PIXELS), - 3: (BC7_MODE3, BC7_MODE3_PIXELS), - 7: (BC7_MODE7, BC7_MODE7_PIXELS), - } - for mode, (block, expected) in cases.items(): - with self.subTest(mode=mode): - self.assertEqual(self.decode(block), expected) - - def test_mode4_index_selector_and_rotation(self): - # Selector 0: colour takes the 2-bit indices, alpha (255 -> 0) the 3-bit ones. - self.assertEqual( - self.decode(bc7_mode4(rotation=0, selector=0)), - [gray(RAMP2[p % 4], RAMP3[7 - p % 8]) for p in range(16)], - ) - # Selector 1 swaps the index sets; rotation 1 then swaps R and A. - self.assertEqual( - self.decode(bc7_mode4(rotation=1, selector=1)), - [(RAMP2[3 - p % 4], RAMP3[p % 8], RAMP3[p % 8], RAMP3[p % 8]) for p in range(16)], - ) - - def test_mode5_separate_alpha_indices_and_rotation(self): - self.assertEqual(self.decode(BC7_MODE5), BC7_MODE5_PIXELS) - - def test_mode6_four_bit_indices_and_pbits(self): - decoded = self.decode(BC7_MODE6) - self.assertEqual([p[0] for p in decoded], list(RAMP4)) - self.assertEqual(decoded[0], (0, 254, 128, 254)) - self.assertEqual(decoded[8], (135, 120, 129, 255)) - self.assertEqual(decoded[15], (255, 1, 129, 255)) - - def test_reserved_mode_is_transparent_black(self): - for block in (bytes(16), b"\x00" + b"\xff" * 15): - with self.subTest(block=block.hex()): - self.assertEqual(self.decode(block), [(0, 0, 0, 0)] * 16) - - def test_srgb_and_typeless_keep_stored_bytes(self): - payload = BC7_MODE6 + BC7_MODE7 - unorm = self.decode(payload, 8, 4, dxgi=98) - # Mode 6 pixel 8 is at row 2, column 0 of the 8-wide image. - self.assertEqual(unorm[16], (135, 120, 129, 255)) - for dxgi in (97, 99): - with self.subTest(dxgi=dxgi): - self.assertEqual(self.decode(payload, 8, 4, dxgi=dxgi), unorm) - - def test_blocks_are_placed_and_clipped(self): - blocks = [BC7_MODE6, BC7_MODE7, BC7_MODE2, BC7_MODE6] - expected_blocks = [self.decode(block) for block in blocks] - for width, height in ((5, 7), (8, 8)): - with self.subTest(size=(width, height)): - decoded = self.decode(b"".join(blocks), width, height) - for y in range(height): - for x in range(width): - block = expected_blocks[(y // 4) * 2 + x // 4] - self.assertEqual(decoded[y * width + x], block[(y % 4) * 4 + x % 4], (x, y)) - # A 3x5 image is a 1x2 grid of blocks; 1x1 keeps only the first pixel. - decoded = self.decode(BC7_MODE0 + BC7_MODE6, 3, 5) - self.assertEqual(decoded[:3], BC7_MODE0_PIXELS[:3]) - self.assertEqual(decoded[3:6], BC7_MODE0_PIXELS[4:7]) - self.assertEqual(decoded[12:15], [(0, 254, 128, 254), (16, 238, 128, 254), (36, 218, 128, 254)]) - self.assertEqual(self.decode(BC7_MODE6, 1, 1), [(0, 254, 128, 254)]) - - def test_truncated_payload(self): - for width, height, size in ((4, 4, 15), (5, 7, 63)): - with self.subTest(size=(width, height)): - with self.assertRaisesRegex(dds.DdsError, "Truncated BC7"): - dds.decode_dds(bc7_dds(width, height, b"\x00" * size)) - - -class TruncationTests(unittest.TestCase): - def test_truncated_block_payloads(self): - cases = { - b"DXT1": 8, b"DXT3": 16, b"DXT5": 16, b"ATI1": 8, b"ATI2": 16, - } - for fourcc, block in cases.items(): - with self.subTest(fourcc=fourcc): - with self.assertRaises(dds.DdsError) as ctx: - dds.decode_dds(dds_buffer( - 4, 4, b"\x00" * (block - 1), flags=DDPF_FOURCC, fourcc=fourcc, - )) - self.assertIn("Truncated", str(ctx.exception)) - - -class DownscaleTests(unittest.TestCase): - def rgba_grid(self, width, height): - buf = bytearray(width * height * 4) - for i in range(width * height): - buf[i * 4] = i - buf[i * 4 + 3] = 255 - return bytes(buf) - - def test_box_filter_4x4(self): - w, h, out = dds.downscale_rgba(4, 4, self.rgba_grid(4, 4), 2) - self.assertEqual((w, h), (2, 2)) - # Each output pixel averages a 2x2 block with round-half-up. - self.assertEqual([p[0] for p in pixels(out)], [3, 5, 11, 13]) - self.assertEqual([p[3] for p in pixels(out)], [255, 255, 255, 255]) - - def test_single_column_averages_pairs(self): - buf = bytearray() - for value in (0, 10, 20, 30): - buf += bytes((value, value, value, 255)) - w, h, out = dds.downscale_rgba(1, 4, bytes(buf), 2) - self.assertEqual((w, h), (1, 2)) - self.assertEqual([p[0] for p in pixels(out)], [5, 25]) - - def test_odd_extents_are_averaged_without_cropping(self): - line = b"".join(bytes((v, v, v, 255)) for v in (0, 0, 100, 200, 200)) - for width, height in ((5, 1), (1, 5)): - with self.subTest(width=width, height=height): - w, h, out = dds.downscale_rgba(width, height, line, 2) - self.assertEqual((w, h), (max(1, width // 2), max(1, height // 2))) - self.assertEqual(pixels(out), [(20, 20, 20, 255), (180, 180, 180, 255)]) - - rgba = bytes((0, 0, 0, 255)) * 8 + bytes((90, 180, 0, 255)) - self.assertEqual(dds.downscale_rgba(3, 3, rgba, 1), (1, 1, bytes((10, 20, 0, 255)))) - - def test_repeated_halving(self): - w, h, out = dds.downscale_rgba(8, 8, self.rgba_grid(8, 8), 2) - self.assertEqual((w, h), (2, 2)) - self.assertEqual(len(out), 2 * 2 * 4) - - def test_no_change_needed(self): - buf = self.rgba_grid(4, 4) - self.assertEqual(dds.downscale_rgba(4, 4, buf, 4), (4, 4, buf)) - self.assertEqual(dds.downscale_rgba(4, 4, buf, 0), (4, 4, buf)) - - def test_invalid_buffer_length(self): - with self.assertRaises(dds.DdsError): - dds.downscale_rgba(4, 4, b"\x00" * 8, 2) - - def test_invalid_dimensions(self): - with self.assertRaises(dds.DdsError): - dds.downscale_rgba(0, 4, b"", 2) - - def test_negative_max_size_rejected(self): - buf = self.rgba_grid(4, 4) - with self.assertRaisesRegex(dds.DdsError, "Invalid max_size: -1"): - dds.downscale_rgba(4, 4, buf, -1) - self.assertEqual(dds.downscale_rgba(4, 4, buf, 0), (4, 4, buf)) - - -class PngTests(unittest.TestCase): - def test_png_structure_and_crcs(self): - rgba = bytes((1, 2, 3, 4, 5, 6, 7, 8)) - png = dds.encode_png(2, 1, rgba) - chunks = png_chunks(png) - self.assertEqual([c[0] for c in chunks], [b"IHDR", b"IDAT", b"IEND"]) - for ctype, payload, crc in chunks: - expected = zlib.crc32(payload, zlib.crc32(ctype)) & 0xFFFFFFFF - self.assertEqual(crc, expected, ctype) - self.assertEqual(chunks[0][1], struct.pack(">IIBBBBB", 2, 1, 8, 6, 0, 0, 0)) - self.assertEqual(chunks[2][1], b"") - # One filter byte (0 = None) per row, then the RGBA row itself. - self.assertEqual(zlib.decompress(chunks[1][1]), b"\x00" + rgba) - - def test_rejects_bad_input(self): - with self.assertRaises(ValueError): - dds.encode_png(0, 1, b"") - with self.assertRaises(ValueError): - dds.encode_png(2, 1, b"\x00" * 7) - - def test_packed_r11g11b10_preview_respects_row_pitch_and_channel_bits(self) -> None: - def packed(red: int, green: int, blue: int) -> int: - return red | (green << 11) | (blue << 22) - - bright = packed(15 << 6, 14 << 6, 13 << 5) # 1.0, 0.5, 0.25 - fractions = packed((14 << 6) | 32, (13 << 6) | 32, (14 << 5) | 8) # 0.75, 0.375, 0.625 - edge = packed(0, 1, 31 << 5) # zero, subnormal, infinity - nan_hdr = packed((31 << 6) | 1, 16 << 6, 31) # NaN, 2.0, subnormal - payload = struct.pack("II", chunks[0][1][:8]), (2, 2)) - self.assertEqual(zlib.decompress(chunks[1][1]), bytes(( - 0, 255, 128, 64, 255, 191, 96, 159, 255, - 0, 0, 0, 255, 255, 0, 255, 0, 255, - ))) - - def test_dds_to_png_roundtrip(self): - payload = bc1_block(0xFFFF, 0x0000, [0, 0, 0, 0]) * 4 - png = dds.dds_to_png_bytes(dds_buffer( - 8, 8, payload, flags=DDPF_FOURCC, fourcc=b"DXT1", - )) - chunks = png_chunks(png) - self.assertEqual(struct.unpack(">II", chunks[0][1][:8]), (8, 8)) - raw = zlib.decompress(chunks[1][1]) - stride = 8 * 4 + 1 - self.assertEqual(len(raw), stride * 8) - for row in range(8): - self.assertEqual(raw[row * stride], 0) - row_bytes = raw[row * stride + 1:(row + 1) * stride] - self.assertEqual(row_bytes, b"\xff" * (8 * 4)) - - def test_downscaled_dds_to_png(self): - payload = bc1_block(0xFFFF, 0x0000, [0, 0, 0, 0]) * 16 - png = dds.dds_to_png_bytes(dds_buffer( - 16, 16, payload, flags=DDPF_FOURCC, fourcc=b"DXT1", - ), max_size=4) - self.assertEqual(struct.unpack(">II", png_chunks(png)[0][1][:8]), (4, 4)) - - def test_downscaled_png_weights_color_by_alpha(self) -> None: - red = bytes((255, 0, 0, 255)) - translucent_green = bytes((0, 255, 0, 128)) - transparent_blue = bytes((0, 0, 255, 0)) - cases = ( - (2, red + transparent_blue, (255, 0, 0, 128)), - (3, red + translucent_green + transparent_blue, (170, 85, 0, 128)), - ) - for width, rgba, expected in cases: - with self.subTest(width=width): - data = dds_buffer(width, 1, rgba, flags=DDPF_FOURCC, fourcc=b"DX10", dxgi=28) - chunks = png_chunks(dds.dds_to_png_bytes(data, max_size=1)) - self.assertEqual(struct.unpack(">II", chunks[0][1][:8]), (1, 1)) - self.assertEqual(zlib.decompress(chunks[1][1]), bytes((0, *expected))) - - def test_png_downscale_filters_tagged_srgb_in_linear_light(self): - rgba = bytes((0, 32, 0, 255, 255, 160, 10, 255)) - # BC1 indices 1 and 0 select black and white in the first two texels. - bc1 = bc1_block(0xFFFF, 0, [1, 0, 0, 0]) - for dxgi, payload, expected in ( - (29, rgba, (188, 119, 5, 255)), - (28, rgba, (128, 96, 5, 255)), - (72, bc1, (188, 188, 188, 255)), - (71, bc1, (128, 128, 128, 255)), - ): - with self.subTest(dxgi=dxgi): - data = dds_buffer(2, 1, payload, flags=DDPF_FOURCC, fourcc=b"DX10", dxgi=dxgi) - chunks = png_chunks(dds.dds_to_png_bytes(data, max_size=1)) - self.assertEqual(zlib.decompress(chunks[1][1]), bytes((0, *expected))) - - data = dds_buffer(2, 1, rgba, flags=DDPF_FOURCC, fourcc=b"DX10", dxgi=29) - for max_size in (0, 2): - chunks = png_chunks(dds.dds_to_png_bytes(data, max_size=max_size)) - self.assertEqual(zlib.decompress(chunks[1][1]), b"\0" + rgba) - - def test_srgb_downscale_weights_linear_color_by_alpha(self): - # Opaque red, half-covered green and invisible blue. Alpha is linear. - rgba = bytes((255, 0, 0, 255, 0, 255, 0, 128, 0, 0, 255, 0)) - data = dds_buffer(3, 1, rgba, flags=DDPF_FOURCC, fourcc=b"DX10", dxgi=29) - chunks = png_chunks(dds.dds_to_png_bytes(data, max_size=1)) - self.assertEqual(zlib.decompress(chunks[1][1]), bytes((0, 213, 156, 0, 128))) - - def test_srgb_linear_segment_rounds_half_bytes_up(self): - # All channels lie on the linear segment. Their means are 5.5, 5.5 and 3.5. - for alpha in (128, 255): - left = bytes((2, 5, 6, alpha)) - right = bytes((9, 6, 1, alpha)) - for rgba in (left + right, right + left): - with self.subTest(rgba=rgba): - data = dds_buffer(2, 1, rgba, flags=DDPF_FOURCC, fourcc=b"DX10", dxgi=29) - chunks = png_chunks(dds.dds_to_png_bytes(data, max_size=1)) - self.assertEqual(zlib.decompress(chunks[1][1]), bytes((0, 6, 6, 4, alpha))) - - def test_srgb_downscale_across_two_levels(self): - # An opaque white first row and three black rows give 25% linear light. - for width in (1, 4): - with self.subTest(width=width): - rgba = b"\xff" * (4 * width) + bytes((0, 0, 0, 255)) * (3 * width) - data = dds_buffer(width, 4, rgba, flags=DDPF_FOURCC, fourcc=b"DX10", dxgi=29) - chunks = png_chunks(dds.dds_to_png_bytes(data, max_size=1)) - self.assertEqual(zlib.decompress(chunks[1][1]), bytes((0, 137, 137, 137, 255))) - - def test_dds_to_png_rejects_negative_max_size(self): - payload = bc1_block(0xFFFF, 0x0000, [0, 0, 0, 0]) * 4 - data = dds_buffer(8, 8, payload, flags=DDPF_FOURCC, fourcc=b"DXT1") - with self.assertRaisesRegex(dds.DdsError, "Invalid max_size: -1"): - dds.dds_to_png_bytes(data, max_size=-1) - png = dds.dds_to_png_bytes(data, max_size=0) - self.assertEqual(struct.unpack(">II", png_chunks(png)[0][1][:8]), (8, 8)) - - -class CliTests(unittest.TestCase): - def test_cli_writes_png(self): - payload = bc1_block(0xFFFF, 0x0000, [0, 0, 0, 0]) * 4 - with tempfile.TemporaryDirectory() as tmp: - src = os.path.join(tmp, "in.dds") - dst = os.path.join(tmp, "nested", "out.png") - with open(src, "wb") as f: - f.write(dds_buffer(8, 8, payload, flags=DDPF_FOURCC, fourcc=b"DXT1")) - self.assertEqual(dds.main([src, dst]), 0) - with open(dst, "rb") as f: - self.assertEqual(f.read(8), dds.PNG_SIGNATURE) - - def test_cli_rejects_output_aliasing_input(self): - original = dds_buffer(4, 4, bc1_block(0xFFFF, 0, [0, 0, 0, 0]), - flags=DDPF_FOURCC, fourcc=b"DXT1") - with tempfile.TemporaryDirectory() as tmp: - src = os.path.join(tmp, "in.dds") - alias = os.path.join(tmp, ".", "in.dds") - with open(src, "wb") as f: - f.write(original) - stderr = io.StringIO() - with contextlib.redirect_stderr(stderr): - result = dds.main([src, alias]) - with open(src, "rb") as f: - self.assertEqual(f.read(), original) - self.assertEqual(result, 1) - self.assertIn("output must not overwrite the input DDS", stderr.getvalue()) - - def test_cli_publishes_only_after_a_complete_write(self): - original = dds_buffer(4, 4, bc1_block(0xFFFF, 0, [0, 0, 0, 0]), - flags=DDPF_FOURCC, fourcc=b"DXT1") - previous = dds.encode_png(1, 1, b"\x10\x20\x30\xff") - replacement = dds.dds_to_png_bytes(original) - for existing in (False, True): - with self.subTest(existing=existing), tempfile.TemporaryDirectory() as tmp: - src = os.path.join(tmp, "in.dds") - dst = os.path.join(tmp, "out.png") - with open(src, "wb") as f: - f.write(original) - if existing: - with open(dst, "wb") as f: - f.write(previous) - - @contextlib.contextmanager - def fail_partial_write(path, mode): - with open(path, mode) as f: - def write(data): - f.write(data[:4]) - raise OSError("synthetic disk-full write") - - yield mock.Mock(write=write) if mode == "wb" else f - - err = io.StringIO() - with mock.patch.object(dds, "open", side_effect=fail_partial_write, create=True), \ - contextlib.redirect_stderr(err): - self.assertEqual(dds.main([src, dst]), 1) - self.assertIn("synthetic disk-full write", err.getvalue()) - self.assertCountEqual(os.listdir(tmp), ["in.dds", "out.png"] if existing else ["in.dds"]) - if existing: - with open(dst, "rb") as f: - self.assertEqual(f.read(), previous) - self.assertEqual(dds.main([src, dst]), 0) - with open(dst, "rb") as f: - self.assertEqual(f.read(), replacement) - - def test_cli_reports_unsupported_input(self): - with tempfile.TemporaryDirectory() as tmp: - src = os.path.join(tmp, "in.dds") - dst = os.path.join(tmp, "out.png") - with open(src, "wb") as f: - f.write(dds_buffer(4, 4, flags=DDPF_FOURCC, fourcc=b"XXXX")) - err = io.StringIO() - with contextlib.redirect_stderr(err): - self.assertEqual(dds.main([src, dst]), 1) - self.assertIn("FourCC", err.getvalue()) - self.assertFalse(os.path.exists(dst)) - - def test_cli_rejects_negative_max_size(self): - payload = bc1_block(0xFFFF, 0x0000, [0, 0, 0, 0]) * 4 - with tempfile.TemporaryDirectory() as tmp: - src = os.path.join(tmp, "in.dds") - dst = os.path.join(tmp, "out.png") - with open(src, "wb") as f: - f.write(dds_buffer(8, 8, payload, flags=DDPF_FOURCC, fourcc=b"DXT1")) - err = io.StringIO() - with contextlib.redirect_stderr(err), self.assertRaises(SystemExit) as cm: - dds.main([src, dst, "--max-size", "-1"]) - self.assertEqual(cm.exception.code, 2) - self.assertIn("--max-size must be 0 or more", err.getvalue()) - self.assertFalse(os.path.exists(dst)) - - def test_cli_allows_zero_max_size(self): - payload = bc1_block(0xFFFF, 0x0000, [0, 0, 0, 0]) * 4 - with tempfile.TemporaryDirectory() as tmp: - src = os.path.join(tmp, "in.dds") - dst = os.path.join(tmp, "out.png") - with open(src, "wb") as f: - f.write(dds_buffer(8, 8, payload, flags=DDPF_FOURCC, fourcc=b"DXT1")) - self.assertEqual(dds.main([src, dst, "--max-size", "0"]), 0) - with open(dst, "rb") as f: - self.assertEqual(f.read(8), dds.PNG_SIGNATURE) - - -def halves(*codes): - return struct.pack(f"<{len(codes)}H", *codes) - - -HALF_FLOAT = dict(flags=DDPF_FOURCC, fourcc=b"DX10") - - -class HalfFloatTests(unittest.TestCase): - """DXGI 54 (R16_FLOAT) and 10 (R16G16B16A16_FLOAT): clamp to [0, 1], round(v * 255) half up.""" - - def test_header_names_the_half_float_formats(self): - for dxgi, name in ((54, "R16_FLOAT"), (10, "RGBA16_FLOAT")): - with self.subTest(dxgi=dxgi): - info = dds.parse_dds_header(dds_buffer(1, 1, dxgi=dxgi, **HALF_FLOAT)) - self.assertEqual((info["format"], info["dxgi_format"]), (name, dxgi)) - - def test_r16_float_fills_red_and_skips_row_padding(self): - # 1.0, 0.5 | 2^-8, 2.0 with four padding bytes after each 4-byte row. - payload = halves(0x3C00, 0x3800) + b"\xcc" * 4 + halves(0x1C00, 0x4000) - width, height, rgba = dds.decode_dds(dds_buffer(2, 2, payload, pitch=8, dxgi=54, **HALF_FLOAT)) - self.assertEqual((width, height), (2, 2)) - self.assertEqual(pixels(rgba), [(255, 0, 0, 255), (128, 0, 0, 255), (1, 0, 0, 255), (255, 0, 0, 255)]) - - def test_rgba16_float_keeps_alpha_and_skips_row_padding(self): - payload = (halves(0x3C00, 0x3800, 0x0000, 0x3C00) + b"\xcc" * 4 - + halves(0x3555, 0x1C00, 0x3BFF, 0x3800)) - width, height, rgba = dds.decode_dds(dds_buffer(1, 2, payload, pitch=12, dxgi=10, **HALF_FLOAT)) - self.assertEqual((width, height), (1, 2)) - # 0x3555 = 0.333252 -> 85; 0x3BFF = 0.999512 -> 255. - self.assertEqual(pixels(rgba), [(255, 128, 0, 255), (85, 1, 255, 128)]) - - def test_tightly_packed_rows_without_a_pitch(self): - payload = halves(0x3800, 0x3C00, 0x0000, 0x3400) # 0.5, 1, 0, 0.25 - for pitch in (None, 0): - with self.subTest(pitch=pitch): - self.assertEqual(dds.decode_dds(dds_buffer(2, 2, payload, pitch=pitch, dxgi=54, **HALF_FLOAT)), - (2, 2, bytes((128, 0, 0, 255, 255, 0, 0, 255, 0, 0, 0, 255, 64, 0, 0, 255)))) - - def test_nonfinite_negative_and_subnormal_values(self): - cases = ( - (0x7C00, 255), # +inf - (0xFC00, 0), # -inf - (0x7E00, 0), # quiet NaN - (0x7C01, 0), # signalling NaN - (0xFFFF, 0), # negative NaN - (0x8000, 0), # -0 - (0xBC00, 0), # -1 - (0x7BFF, 255), # 65504, largest finite - (0x0001, 0), # smallest subnormal - (0x0000, 0), - ) - payload = halves(*(code for code, _ in cases)) - _, _, r16 = dds.decode_dds(dds_buffer(len(cases), 1, payload, dxgi=54, **HALF_FLOAT)) - self.assertEqual(list(r16[0::4]), [v for _, v in cases]) - self.assertEqual(set(r16[3::4]), {255}) - # Same codes in every RGBA16_FLOAT channel, alpha included. - rgba_payload = b"".join(halves(code, code, code, code) for code, _ in cases) - _, _, rgba = dds.decode_dds(dds_buffer(len(cases), 1, rgba_payload, dxgi=10, **HALF_FLOAT)) - self.assertEqual(pixels(rgba), [(v, v, v, v) for _, v in cases]) - - def test_every_half_code_maps_deterministically(self): - payload = struct.pack("<65536H", *range(65536)) - data = dds_buffer(256, 256, payload, dxgi=54, **HALF_FLOAT) - _, _, rgba = dds.decode_dds(data) - red = rgba[0::4] - self.assertEqual(dds.decode_dds(data)[2], rgba) - positive = red[:0x7C00] # +0 up to 65504, in increasing order - self.assertTrue(all(a <= b for a, b in zip(positive, positive[1:]))) - self.assertEqual((red[0x3C00], red[0x7C00]), (255, 255)) - self.assertFalse(any(red[0x7C01:0x8000]), "NaN must be 0") - self.assertFalse(any(red[0x8000:]), "the sign bit must give 0") - - def test_pitch_and_truncation_errors(self): - with self.assertRaisesRegex(dds.DdsError, "RGBA16_FLOAT row pitch"): - dds.decode_dds(dds_buffer(1, 2, bytes(16), pitch=4, dxgi=10, **HALF_FLOAT)) - with self.assertRaisesRegex(dds.DdsError, "Truncated R16_FLOAT"): - dds.decode_dds(dds_buffer(2, 2, bytes(11), pitch=8, dxgi=54, **HALF_FLOAT)) - # The last row needs only its own bytes, not a full pitch. - self.assertEqual(dds.decode_dds(dds_buffer(2, 2, bytes(12), pitch=8, dxgi=54, **HALF_FLOAT))[0:2], (2, 2)) - - def test_cli_writes_the_png(self): - payload = halves(0x3C00, 0x0000, 0x3800, 0x3C00, 0x7E00, 0x7C00, 0x3400, 0x3800) - with tempfile.TemporaryDirectory() as tmp: - src = os.path.join(tmp, "in.dds") - dst = os.path.join(tmp, "out.png") - with open(src, "wb") as f: - f.write(dds_buffer(2, 1, payload, pitch=16, dxgi=10, **HALF_FLOAT)) - self.assertEqual(dds.main([src, dst]), 0) - with open(dst, "rb") as f: - chunks = png_chunks(f.read()) - ihdr = next(p for t, p, _ in chunks if t == b"IHDR") - self.assertEqual(struct.unpack(">II", ihdr[:8]), (2, 1)) - raw = zlib.decompress(b"".join(p for t, p, _ in chunks if t == b"IDAT")) - self.assertEqual(raw[1:], bytes((255, 0, 128, 255, 0, 255, 64, 128))) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/test_dds_png_dx10.py b/tests/test_dds_png_dx10.py deleted file mode 100644 index a0d55d324..000000000 --- a/tests/test_dds_png_dx10.py +++ /dev/null @@ -1,84 +0,0 @@ -"""Tests for DX10 alpha modes using synthetic DDS buffers (no game data). - - python3 -I tests/test_dds_png_dx10.py -""" -import importlib.util -import os -import struct -import unittest -import zlib - -ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) - - -def load_module(): - path = os.path.join(ROOT, "tools", "dds_png.py") - spec = importlib.util.spec_from_file_location("dds_png_under_test", path) - module = importlib.util.module_from_spec(spec) - spec.loader.exec_module(module) - return module - - -dds = load_module() - - -class Dx10AlphaTests(unittest.TestCase): - def test_rgba8_alpha_mode_in_png(self): - header = bytearray(148) - header[:4] = b"DDS " - struct.pack_into("I4s", png, pos) - self.assertEqual(kind, b"IDAT") - row = zlib.decompress(png[pos + 8:pos + 8 + size]) - self.assertEqual(row, bytes((0, 255, 0, 0, alpha))) - - -def _dx10(width, height, dxgi, payload, pitch=0): - header = bytearray(148) - header[:4] = b"DDS " - struct.pack_into(" 1 else 0) - struct.pack_into(" 1 else 0) - struct.pack_into(" 1 or dimension == 4 else 0)) - struct.pack_into(" normal export path (3D detile) -> preview its last slice. - w, h, depth = 8, 8, 8 - with tempfile.TemporaryDirectory() as tmp: - for fmt, last_pixel, expected in ( - (54, (0.5,), bytes((128, 0, 0, 255))), - (10, (-1.0, 0.25, 2.0, 0.5), bytes((0, 64, 255, 128))), - ): - with self.subTest(fmt=fmt): - sample = struct.pack("<" + "e" * len(last_pixel), *last_pixel) - linear = bytes((depth - 1) * w * h * len(sample)) + sample * (w * h) - layout = ttpf.volume_surface_layout(w, h, depth, 1, len(sample)) - tiled = pool_fixtures.retile_volume(layout, linear) - rec = pool_fixtures.pack_etpf_record(w, h, 1, 0, fmt, depth, 3, 2, 4096) - pool_path = Path(tmp, f"vol{fmt}.ttpf") - dds_path = pool_path.with_suffix(".dds") - pool_fixtures.write_rds5_pool(pool_path, [rec], [tiled]) - with contextlib.closing(ttpf.Pool(pool_path)) as pool, contextlib.redirect_stdout(io.StringIO()): - self.assertEqual(ttpf.export(pool, 0, str(dds_path)), 0) - self.assertEqual(dds.dds_file_to_png_bytes(dds_path, z=7), - dds.encode_png(w, h, expected * (w * h))) - if fmt == 54: - dst = Path(tmp, "slice.png") - self.assertEqual(dds.main([str(dds_path), str(dst), "--z", "7"]), 0) - self.assertEqual(dst.read_bytes(), dds.encode_png(w, h, expected * (w * h))) - - def test_cli_header_only_info_and_selected_pixels(self): - data = dx10(2, 2, b"", mips=2, layers=2, cube=True) - with tempfile.TemporaryDirectory() as tmp: - src, dst = Path(tmp, "cube.dds"), Path(tmp, "out.png") - src.write_bytes(data) - output = io.StringIO() - with contextlib.redirect_stdout(output): - self.assertEqual(dds.main([str(src), "--info"]), 0) - info = json.loads(output.getvalue()) - self.assertEqual((info["width"], info["height"], info["mip_count"]), (2, 2, 2)) - self.assertEqual((info["dimension"], info["array_size"], info["faces"]), ("2d", 2, list(FACES))) - self.assertEqual(list(Path(tmp).iterdir()), [src]) - last_pixel = bytes((12, 34, 56, 78)) - src.write_bytes(data + bytes(236) + last_pixel) - self.assertEqual(dds.main([str(src), str(dst), "--mip", "1", "--layer", "1", - "--face", "nz"]), 0) - self.assertEqual(dst.read_bytes(), dds.encode_png(1, 1, last_pixel)) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/test_desc_cache.py b/tests/test_desc_cache.py deleted file mode 100644 index a8443efd0..000000000 --- a/tests/test_desc_cache.py +++ /dev/null @@ -1,238 +0,0 @@ -"""The per-basic-block descriptor lookup cache of tools/rdna2spirv.py (standard library only: no GPU, LLVM or SPIRV-Tools). - - python -I tests/test_desc_cache.py - -Every image instruction needs the bindless index of its T# (8 SGPRs) and S# (4 SGPRs): a call of %desc_lookup_fn. A -second instruction on the same descriptors in the same basic block reuses the first one's result as long as no SGPR -of the descriptor was written in between. These tests translate small pixel shaders (the .s text is made here, with -encodings of the right length so that branch targets work out) and count the calls in the SPIR-V. -""" -import gc -import os -import shutil -import struct -import subprocess -import sys -import tempfile -import warnings - -ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) -sys.dont_write_bytecode = True -sys.path.insert(0, os.path.join(ROOT, "tools")) -import rdna2spirv # noqa: E402 - -CALL = "OpFunctionCall %uint %desc_lookup_fn" -STUB_DXBC = b"DXBC" + bytes(24) + struct.pack(" 1}) - seen.clear() - - for number, line in enumerate(text.splitlines(), 1): - if not line.startswith("|"): - close_table() - continue - name = line.split("|")[1].strip() - if name and set(name) - set("-: "): - seen[name].append(number) - close_table() - return repeated - - -class RepeatedRowNames(unittest.TestCase): - def test_a_row_given_twice_is_reported_with_both_lines(self): - text = "| Rule | Text |\n|---|---|\n| LDS | old |\n| Other | x |\n| LDS | new |\n" - self.assertEqual(repeated_row_names(text), {"LDS": [3, 5]}) - - def test_the_same_name_in_two_tables_is_fine(self): - text = "| Rule | Text |\n|---|---|\n| LDS | a |\n\nProse.\n\n| Rule | Text |\n|---|---|\n| LDS | b |\n" - self.assertEqual(repeated_row_names(text), {}) - - def test_separator_rows_and_empty_first_cells_do_not_count(self): - text = "| A | B |\n|:--|--:|\n| | x |\n| | y |\n| - | z |\n" - self.assertEqual(repeated_row_names(text), {}) - - -class DesignTable(unittest.TestCase): - def test_design_md_has_no_row_twice(self): - with open(DESIGN, encoding="utf-8") as f: - repeated = repeated_row_names(f.read()) - self.assertEqual(repeated, {}, "docs/design.md has these rows more than once (first cell: lines); " - "keep the newer text of each and delete the other") - - def test_deduplicating_the_image_query_row_keeps_its_measurements(self): - """Removing the older resinfo/get-lod wording must not cut out the newer row's measured facts.""" - with open(DESIGN, encoding="utf-8") as f: - row = next(line for line in f.read().splitlines() - if line.startswith("| Image atomics, size and LOD queries |")) - for fact in ("GPU-checked (TEST-184)", "Measured natively on RDNA2", "raw LOD includes", - "Unverified:", "on other dimensions is", "A host quirk", "OpImageQuerySizeLod", - "OpImageQueryLevels", "Gen.resinfo_words"): - with self.subTest(fact=fact): - self.assertIn(fact, row) - self.assertEqual(row.count("(ISA: {num_mip_levels"), 1) # one ISA parenthetical, not a splice - self.assertNotIn("depth (1) and the level count", row) # the superseded wording - self.assertNotIn("still differs in the first three", row) # contradicts Gen.resinfo_words - self.assertNotIn("`; the clamped LOD", row) # join artifact from a mid-sentence cut - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/test_dev_boot_trace.py b/tests/test_dev_boot_trace.py deleted file mode 100644 index 38fad27d9..000000000 --- a/tests/test_dev_boot_trace.py +++ /dev/null @@ -1,86 +0,0 @@ -"""Check the boot-trace entry point against the standalone producer.""" -import json -from pathlib import Path -import shutil -import subprocess -import sys -import tempfile -import unittest - - -ROOT = Path(__file__).resolve().parents[1] -CLI = ROOT / "scripts" / "dev.py" -PRODUCER = ROOT / "tools" / "boot_trace.py" - - -class BootTraceTests(unittest.TestCase): - def setUp(self): - directory = tempfile.TemporaryDirectory() - self.addCleanup(directory.cleanup) - self.cwd = Path(directory.name) - self.startup = "sess\u00e3o sint\u00e9tica.jsonl" - (self.cwd / self.startup).write_text( - '{"kind":"trace_open","pid":17}\n{"kind":"exit","code":7}\n', - encoding="utf-8", newline="\n", - ) - self.d3d = "render calls.log" - (self.cwd / self.d3d).write_text( - "[d3d12-trace] #2 Example call unsupported\n", encoding="utf-8", newline="\n", - ) - - def invoke(self, *args): - return subprocess.run( - [sys.executable, "-I", "-B", *args], - cwd=self.cwd, capture_output=True, timeout=10, - ) - - def compare(self, expected_code, *args): - direct = self.invoke(PRODUCER, *args) - result = self.invoke(CLI, "boot-trace", *args) - self.assertEqual(direct.returncode, expected_code, direct.stderr) - self.assertEqual(result.returncode, expected_code, result.stderr) - self.assertEqual(result.stdout, direct.stdout) - self.assertEqual(result.stderr, direct.stderr) - return result - - def test_help_and_text(self): - self.assertIn(b"--d3d12", self.compare(0, "--help").stdout) - self.assertTrue(self.compare(0, self.startup).stdout.strip()) - - def test_combined_json(self): - result = self.compare(0, self.startup, "--d3d12", self.d3d, "--json", "--limit", "1") - report = json.loads(result.stdout) - self.assertEqual(report["startup"]["exit"], 7) - self.assertEqual(report["d3d12"]["calls"], 1) - self.assertEqual(result.stderr, b"") - - def test_partial_json(self): - for startup, d3d, missing in ( - (self.startup, "absent.log", "d3d12"), - ("absent.jsonl", self.d3d, "startup"), - ): - with self.subTest(missing=missing): - result = self.compare(2, startup, "--d3d12", d3d, "--json") - report = json.loads(result.stdout) - self.assertIsNone(report[missing]) - self.assertTrue(any(report.values())) - self.assertIn(b"absent", result.stderr) - - def test_total_failure(self): - result = self.compare(2, "absent.jsonl", "--d3d12", "absent.log", "--json") - self.assertEqual(result.stdout, b"") - self.assertIn(b"absent.jsonl", result.stderr) - self.assertIn(b"absent.log", result.stderr) - - def test_missing_producer(self): - isolated_cli = self.cwd / "empty checkout" / "scripts" / "dev.py" - isolated_cli.parent.mkdir(parents=True) - shutil.copyfile(CLI, isolated_cli) - result = self.invoke(isolated_cli, "boot-trace", self.startup, "--json") - self.assertEqual(result.returncode, 2) - self.assertEqual(result.stdout, b"") - self.assertIn(b"boot_trace.py", result.stderr) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/test_dev_discovery.py b/tests/test_dev_discovery.py deleted file mode 100644 index 3becf5bc8..000000000 --- a/tests/test_dev_discovery.py +++ /dev/null @@ -1,97 +0,0 @@ -"""Exercise developer tool discovery through its public command line.""" -from contextlib import ExitStack -import json -import os -from pathlib import Path -import shutil -import subprocess -import sys -import tempfile -import unittest - - -ENTRY = Path(__file__).resolve().parents[1] / "scripts" / "dev.py" -PRODUCERS = ("tools/boot_trace.py", "scripts/run_guest_scene.py") - - -class DiscoveryTests(unittest.TestCase): - def setUp(self): - scratch = tempfile.TemporaryDirectory() - self.addCleanup(scratch.cleanup) - self.cwd = Path(scratch.name) - self.checkout = self.cwd / "checkout d\u00e9mo" - self.entry = self.checkout / "scripts" / "dev.py" - self.entry.parent.mkdir(parents=True) - shutil.copyfile(ENTRY, self.entry) - - def invoke(self, *args): - return subprocess.run( - [sys.executable, "-I", "-B", str(self.entry), *args], - cwd=self.cwd, capture_output=True, timeout=10, - ) - - def test_help_lists_discovery(self): - result = self.invoke("--help") - self.assertEqual(result.returncode, 0, result.stderr) - self.assertIn(b"discover", result.stdout) - - def test_discovery_leaves_producers_unexecuted(self): - for relative in PRODUCERS: - producer = self.checkout / relative - producer.parent.mkdir(exist_ok=True) - producer.write_text( - "from pathlib import Path\nPath(__file__).with_suffix('.ran').touch()\n", - encoding="utf-8", newline="\n", - ) - result = self.invoke("discover", "--json") - self.assertEqual(result.returncode, 0, result.stderr) - self.assertIsInstance(json.loads(result.stdout), dict) - for relative in PRODUCERS: - self.assertFalse((self.checkout / relative).with_suffix(".ran").exists()) - - def test_inventory_reflects_this_checkout(self): - for tool_id, present_path, missing_id, missing_path in ( - ("boot-trace", PRODUCERS[0], "guest-scene", PRODUCERS[1]), - ("guest-scene", PRODUCERS[1], "boot-trace", PRODUCERS[0]), - ): - with self.subTest(tool=tool_id), ExitStack() as cleanup: - producer = self.checkout / present_path - producer.parent.mkdir(exist_ok=True) - producer.write_text( - "import sys\nprint(sys.argv[1:])\n", encoding="utf-8", newline="\n", - ) - cleanup.callback(producer.unlink) - # A namesake file in the caller's directory must not count. - decoy = self.cwd / missing_path - decoy.parent.mkdir(exist_ok=True) - decoy.touch() - result = self.invoke("discover", "--json") - self.assertEqual(result.returncode, 0, result.stderr) - self.assertEqual(result.stderr, b"") - inventory = json.loads(result.stdout) - self.assertEqual(inventory["schema_version"], 1) - tools = {entry["id"]: entry for entry in inventory["tools"]} - self.assertEqual(len(tools), len(inventory["tools"])) - found, missing = tools[tool_id], tools[missing_id] - self.assertIs(found["present"], True) - self.assertEqual(found["path"], present_path) - self.assertTrue(found["requirements"]) - self.assertIs(missing["present"], False) - self.assertEqual(missing["path"], missing_path) - self.assertIsNone(missing["help_argv"]) - self.assertIs(inventory["live_controls"]["available"], False) - self.assertTrue(inventory["live_controls"]["reason"].strip()) - self.assertEqual(found["help_argv"][0], sys.executable) - help_result = subprocess.run(found["help_argv"], cwd=self.checkout, capture_output=True, - env={**os.environ, "PATH": ""}, timeout=10) - self.assertEqual(help_result.returncode, 0, help_result.stderr) - self.assertEqual(help_result.stdout.strip(), b"['--help']") - - def test_invalid_option_is_an_error(self): - result = self.invoke("discover", "--no-such-option") - self.assertEqual(result.returncode, 2) - self.assertTrue(result.stderr) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/test_dev_guest_scene.py b/tests/test_dev_guest_scene.py deleted file mode 100644 index cae851577..000000000 --- a/tests/test_dev_guest_scene.py +++ /dev/null @@ -1,104 +0,0 @@ -"""Exercise guest-scene forwarding and persisted results without a native GPU run.""" -import hashlib -import json -from pathlib import Path -import shutil -import subprocess -import sys -import tempfile -import unittest - - -SCRIPTS = Path(__file__).resolve().parents[1] / "scripts" - - -class GuestSceneTests(unittest.TestCase): - def setUp(self): - scratch = tempfile.TemporaryDirectory() - self.addCleanup(scratch.cleanup) - self.cwd = Path(scratch.name) - self.cli = SCRIPTS / "dev.py" - self.producer = SCRIPTS / "run_guest_scene.py" - - def invoke(self, *argv): - return subprocess.run( - [sys.executable, "-I", "-B", *argv], - cwd=self.cwd, capture_output=True, timeout=15, - ) - - def scene_args(self): - # Python stands in for Wine and interprets our plain-text loader on all hosts. - (self.cwd / "loader.txt").write_text( - "import sys\nprint('synthetic failure', file=sys.stderr)\nsys.exit(23)\n", - encoding="utf-8", newline="\n", - ) - (self.cwd / "guest.txt").touch() - (self.cwd / "shaders" / "spirv").mkdir(parents=True) - return ["--wine", sys.executable, "--loader", "loader.txt", "--guest", "guest.txt", - "--shaders", "shaders"] - - def test_help_without_output_directory(self): - direct = self.invoke(self.producer, "--help") - result = self.invoke(self.cli, "guest-scene", "--help") - self.assertEqual(result.returncode, 0, result.stderr) - self.assertIn(b"--negative-controls", result.stdout) - self.assertEqual(result.stdout, direct.stdout) - self.assertEqual(result.stderr, direct.stderr) - - def test_forwarding_and_required_output(self): - scripts = self.cwd / "checkout with spaces" / "scripts" - scripts.mkdir(parents=True) - cli = scripts / "dev.py" - shutil.copyfile(self.cli, cli) - (scripts / "run_guest_scene.py").write_text( - "import json, os, sys\n" - "print(json.dumps([sys.argv[1:], os.getcwd(), sys.flags.isolated]))\n" - "print('runner diagnostic', file=sys.stderr)\nsys.exit(19)\n", - encoding="utf-8", newline="\n", - ) - missing = self.invoke(cli, "guest-scene", "--loader", "loader with spaces") - self.assertEqual(missing.returncode, 2) - self.assertEqual(missing.stdout, b"") - self.assertIn(b"--out", missing.stderr) - argv = ["--loader", "loader with spaces", "--out", "r\u00e9sultat", "--negative-controls"] - forwarded = self.invoke(cli, "guest-scene", *argv) - self.assertEqual(forwarded.returncode, 19) - args, cwd, isolated = json.loads(forwarded.stdout) - self.assertEqual(args, argv) - self.assertEqual(Path(cwd).resolve(), self.cwd.resolve()) - self.assertEqual(isolated, 1) - self.assertEqual(forwarded.stderr.strip(), b"runner diagnostic") - - def test_failed_run_and_occupied_retry(self): - args = self.scene_args() - out = self.cwd / "r\u00e9sultat de test" - out.mkdir() - cmd = [self.cli, "guest-scene", *args, f"--out={out.name}"] - failed = self.invoke(*cmd) - self.assertEqual(failed.returncode, 1, failed.stderr) - self.assertIn(b"FAIL:", failed.stdout) - report = out / "report.json" - contents = report.read_bytes() - result = json.loads(contents) - self.assertEqual(result["status"], "fail") - self.assertEqual(result["runs"]["full"]["returncode"], 23) - self.assertEqual((out / "logs/full.stderr.log").read_bytes().strip(), b"synthetic failure") - retry = self.invoke(*cmd) - self.assertEqual(retry.returncode, 2) - self.assertEqual(retry.stdout, b"") - self.assertIn(b"empty", retry.stderr) - self.assertEqual(hashlib.sha256(report.read_bytes()).digest(), hashlib.sha256(contents).digest()) - - def test_output_creation_failure(self): - args = self.scene_args() - (self.cwd / "occupied").touch() - output = Path("occupied") / "run" - result = self.invoke(self.cli, "guest-scene", *args, "--out", str(output)) - self.assertEqual(result.returncode, 1) - self.assertEqual(result.stdout, b"") - self.assertTrue(result.stderr) - self.assertFalse((self.cwd / output / "report.json").exists()) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/test_div_fixup_diff.py b/tests/test_div_fixup_diff.py deleted file mode 100644 index 09c2a31b5..000000000 --- a/tests/test_div_fixup_diff.py +++ /dev/null @@ -1,377 +0,0 @@ -"""tools/div_fixup_diff.py: the reference against the words measured on RDNA2 hardware (gfx1036), the generator's -encoding rules, the sweep and edge grid, and short seeded differential runs. Standard library only; no GPU, no game -files. - -The f32 rows are tests/semantic/test_alu_div_fixup_f32.py's MEASURED list, imported as is. The f16 and f64 rows below -are the ones tests/semantic/test_alu_div_fixup.py marks as gfx1036 measurements, plus the cases of its -test_all_special_and_normal_cases, copied by value (they live inside a test method there). -""" -import io -import os -import random -import re -import sys -import unittest -from collections import Counter -from contextlib import redirect_stdout - -ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) -sys.path.insert(0, os.path.join(ROOT, "tools")) -import div_fixup_diff as d # noqa: E402 (puts tests/semantic on sys.path) -import test_alu_div_fixup_f32 as mf # noqa: E402 (the gfx1036-measured v_div_fixup_f32 words) - -F16, F32, F64 = (d.FMT[op] for op in d.OPS) -H_ONE, H_NEG2, H_HALF, H_INF, H_NINF = 0x3C00, 0xC000, 0x3800, 0x7C00, 0xFC00 -D_ONE, D_NEG2, D_THREE = 0x3FF0000000000000, 0xC000000000000000, 0x4008000000000000 -D_INF, D_NINF = 0x7FF0000000000000, 0xFFF0000000000000 -# (S0, S1, S2, result) from tests/semantic/test_alu_div_fixup.py -F16_ROWS = ( - (H_HALF, H_ONE, H_ONE, H_HALF), (H_HALF, H_NEG2, H_ONE, H_HALF | 0x8000), (H_ONE, 0x7C01, 0x7E01, 0x7E01), - (H_ONE, 0x7C01, H_ONE, 0x7C01), (H_ONE, H_ONE, 0x7C01, 0x7C01), (H_ONE, 0, 0x8000, 0xFE00), - (H_ONE, H_INF, H_NINF, 0xFE00), (H_ONE, H_NINF, H_ONE, 0x8000), (H_ONE, H_NEG2, 0x8000, 0), - (H_ONE, 0x8000, H_ONE, H_NINF), (H_ONE, H_NEG2, H_NINF, H_INF), (0x7E35, H_ONE, H_ONE, H_INF), - (0x7E35, H_NEG2, H_ONE, H_NINF), - (H_ONE, 0x7800, 0x0400, H_ONE), # gfx1036: e2 - e1 = -29 keeps S0 (no f16 cutoff) - (H_ONE, 0x0400, 0x7800, H_ONE), # gfx1036: e2 - e1 = +29 keeps S0 -) -F64_ROWS = ( - (D_THREE, D_ONE, D_ONE, D_THREE), (D_THREE, D_NEG2, D_ONE, D_THREE | 1 << 63), - (D_ONE, 0x7FF0000000000001, 0x7FF8000000000002, 0x7FF8000000000002), - (D_ONE, 0x7FF0000000000001, D_ONE, 0x7FF0000000000001), (D_ONE, D_ONE, 0x7FF0000000000001, 0x7FF0000000000001), - (D_ONE, 0, 1 << 63, 0xFFF8000000000000), (D_ONE, D_INF, D_NINF, 0xFFF8000000000000), - (D_ONE, D_NINF, D_ONE, 1 << 63), (D_ONE, D_NEG2, 1 << 63, 0), (D_ONE, 1 << 63, D_ONE, D_NINF), - (D_ONE, D_NEG2, D_NINF, D_INF), (0xFFF8123456789ABC, 0x4000000000000000, D_ONE, D_INF), - (0x7FF8123456789ABC, D_NEG2, D_ONE, D_NINF), - (D_ONE, 2046 << 52, 971 << 52, D_ONE), # gfx1036: e2 - e1 = -1075 keeps S0 - (D_ONE, 2046 << 52, 970 << 52, 0), # gfx1036: e2 - e1 = -1076 gives +0 - (D_ONE, 1123 << 52, 1 << 52, 0), # gfx1036: 2^-1022 / 2^100 gives +0 - (D_ONE, 1 << 52, 1025 << 52, D_ONE), # gfx1036: e2 - e1 = +1024 keeps S0 (no overflow cutoff) -) -NONE = [None, None] - - -def run(line, **regs): - """(the Machine, its v8 word) after the given v/s words and ``line``.""" - mc = d.Machine() - mc.write_word(8, 0x5A5A5A5A) - for name, w in regs.items(): - if name[0] == "s": - mc.s[int(name[1:])] = w - else: - mc.write_word(int(name[1:]), w) - d.step(line, mc) - return mc, mc.v[8] - - -def pair(n, x): - return {f"v{n}": x & 0xFFFFFFFF, f"v{n + 1}": x >> 32} - - -class Reference(unittest.TestCase): - def test_f32_matches_every_measured_gfx1036_row(self): - self.assertEqual(len(mf.MEASURED), 73) - for insn, v1, v2, v3, want in mf.MEASURED: - with self.subTest(insn=insn, s=(hex(v1), hex(v2), hex(v3))): - mc = d.Machine() - for r, w in ((1, v1), (2, v2), (3, v3), (4, 0xDEADBEEF)): - mc.write_word(r, w) - d.step(insn, mc) - self.assertIsNone(d.compare([mc.v[4], 0, 0, 0], [mc.state(4), NONE, NONE, NONE], [want, 0, 0, 0])) - - def test_f16_and_f64_semantic_rows(self): - for s0, s1, s2, want in F16_ROWS: - with self.subTest(f16=(hex(s0), hex(s1), hex(s2))): - self.assertEqual(d.fixup(F16, s0, s1, s2)[1], want) - _, v8 = run("v_div_fixup_f16 v8, v12, v13, v14", v12=0xBEEF0000 | s0, v13=0xCAFE0000 | s1, - v14=0xDEAD0000 | s2) - self.assertEqual(v8, 0x5A5A0000 | want) - for s0, s1, s2, want in F64_ROWS: - with self.subTest(f64=(hex(s0), hex(s1), hex(s2))): - mc, lo = run("v_div_fixup_f64 v[8:9], v[10:11], v[12:13], v[14:15]", - **pair(10, s0), **pair(12, s1), **pair(14, s2)) - self.assertEqual(lo | mc.v[9] << 32, want) - - def test_rule_order_and_cutoffs(self): - # f32: e2 - e1 = -151 gives a zero even against a NaN or inf S0; -150 does not - self.assertEqual(d.fixup(F32, 0x7FC00055, 0x64000000, 0x00800000), (5, 0)) - self.assertEqual(d.fixup(F32, 0x7F800000, 0xE4000000, 0x00800000), (5, 0x80000000)) - self.assertEqual(d.fixup(F32, 0x7FC00055, 0x4B800000, 0x00800000), (6, 0x7F800000)) - # f64 likewise at -1076 / -1075, and the NaN S0 rule comes after the cutoff - self.assertEqual(d.fixup(F64, 0x7FF8000000000001, 2046 << 52, 970 << 52), (5, 0)) - self.assertEqual(d.fixup(F64, 0x7FF8000000000001, 2046 << 52, 971 << 52), (6, D_INF)) - # f16: no cutoff at all - self.assertEqual(d.fixup(F16, 0x7E00, 0x7BFF, 0x0001), (6, H_INF)) - # f32 S1/S2 denormals are zeros (rules 3 to 5), an S0 denormal is kept; f16/f64 denormals are not zeros - self.assertEqual(d.fixup(F32, 0x00000003, 0x80000001, 0x3F800000), (4, 0xFF800000)) - self.assertEqual(d.fixup(F16, 0x0003, 0x8001, H_ONE), (7, 0x8003)) - self.assertEqual(d.fixup(F64, 3, (1 << 63) | 1, D_ONE)[0], 7) - - def test_f64_denormal_exponent_is_not_judged_inside_the_band(self): - # S2 = 2^-1074: its field 0, 1, or normalized -51; the readings agree below e1 = 1025 and above 1076 - self.assertEqual(d.fixup(F64, D_ONE, 1000 << 52, 1), (7, D_ONE)) - self.assertEqual(d.fixup(F64, D_ONE, 1100 << 52, 1), (5, 0)) - for e1 in (1025, 1050, 1076): # 1 - e1 > -1076 >= -51 - e1 here - with self.assertRaises(d.NotJudged, msg=e1): - d.fixup(F64, D_ONE, e1 << 52, 1) - - def test_f16_op_sel_and_inline_constants(self): - # op_sel:[1,0,1,1]: S0 and S2 from the high halves, the result to the high half, the low half kept - _, v8 = run("v_div_fixup_f16 v8, v12, -v13, v14 op_sel:[1,0,1,1]", v12=H_HALF << 16, v13=H_NEG2, - v14=H_ONE << 16) - self.assertEqual(v8, H_HALF << 16 | 0x5A5A) - # a float inline constant is its f16 value; an integer one is the low half of its word (-1: a NaN) - self.assertEqual(run("v_div_fixup_f16 v8, 0.5, 1.0, -2.0")[1], 0x5A5A0000 | 0xB800) - self.assertEqual(run("v_div_fixup_f16 v8, 0.5, 1.0, -1")[1], 0x5A5AFFFF) - self.assertEqual(run("v_div_fixup_f16 v8, 0x12343c00, 1.0, 1.0")[1], 0x5A5A3C00) - _, v8 = run("v_div_fixup_f16 v8, v12, v13, v14 clamp", v12=0x4000, v13=H_ONE, v14=H_ONE) - self.assertEqual(v8, 0x5A5A3C00) - - def test_f64_sources(self): - # an integer inline constant is sign-extended (-1 is a NaN), 1/(2 pi) is the binary64 value - mc, lo = run("v_div_fixup_f64 v[8:9], 1.0, 1.0, -1") - self.assertEqual(lo | mc.v[9] << 32, (1 << 64) - 1) - mc, lo = run("v_div_fixup_f64 v[8:9], 0.15915494309189532, -2.0, 1.0") - self.assertEqual(lo | mc.v[9] << 32, 0xBFC45F306DC9C882) - # abs and neg act on bit 63 only; SGPR pairs and odd VGPR pairs - mc, lo = run("v_div_fixup_f64 v[9:10], -|v[11:12]|, s[4:5], v[13:14]", **pair(11, D_THREE), - **pair(13, D_ONE), s4=0, s5=0x40000000) - self.assertEqual((lo, mc.v[9], mc.v[10]), (0x5A5A5A5A, 0, 0x40080000)) - - def test_f32_output_modifiers(self): - self.assertEqual(d.out_f32(0x7F7FFFFF, ["mul:2"]), (0x7F800000, None)) - self.assertEqual(d.out_f32(0x3F800000, ["div:2"]), (0x3F000000, None)) - self.assertEqual(d.out_f32(0xFF800000, ["mul:4"]), (0xFF800000, None)) - self.assertEqual(d.out_f32(0x3E800000, ["clamp", "mul:4"]), (0x3F800000, None)) - self.assertEqual(d.out_f32(0x80000000, ["clamp", "mul:2"]), (0, None)) # -0 under clamp: +0 - self.assertEqual(d.out_f32(0x80000000, ["clamp"]), (0, None)) - self.assertEqual(d.out_f32(0x807FFFFF, ["clamp"]), (0, None)) - self.assertEqual(d.out_f32(0x7F800001, ["clamp", "div:2"]), (0, None)) - self.assertEqual(d.out_f32(0x7F800001, ["mul:2"]), (0x7FC00000, "w32")) - for w, mods in ((0x80000000, ["mul:2"]), (0x00000001, ["mul:2"]), (0x00800000, ["div:2"]), - (0x00000001, ["clamp"])): - with self.assertRaises(d.NotJudged, msg=(hex(w), mods)): - d.out_f32(w, mods) - - def test_unmodelled_nan_payloads(self): - mc, _ = run("v_div_fixup_f32 v8, v12, v13, v14 mul:2", v12=H_ONE, v13=0x3F800000, v14=0xFFC00005) - self.assertEqual(mc.state(8), ["w32", "w32"]) - d.step("v_div_fixup_f32 v9, 1.0, 1.0, -|v8|", mc) # an unmodelled NaN passes through as one - self.assertEqual(mc.state(9), ["w32", "w32"]) - d.step("v_div_fixup_f32 v10, v8, 1.0, 1.0", mc) # as S0 it gives +inf whatever its payload - self.assertEqual((mc.v[10], mc.state(10)), (0x7F800000, NONE)) - d.step("v_div_fixup_f32 v11, 1.0, 1.0, v8 clamp", mc) # clamp gives +0 - self.assertEqual((mc.v[11], mc.state(11)), (0, NONE)) - for line in ("v_div_fixup_f16 v10, v8, 1.0, 1.0", "v_div_fixup_f64 v[10:11], v[8:9], 1.0, 1.0"): - with self.assertRaises(d.NotJudged, msg=line): - d.step(line, mc) - - def test_compare(self): - self.assertIsNone(d.compare([0, 0, 0, 0], [["w32", "w32"], NONE, NONE, NONE], [0xFFC00001, 0, 0, 0])) - self.assertIn("f32 NaN", d.compare([0, 0, 0, 0], [["w32", "w32"], NONE, NONE, NONE], [0x7F800000, 0, 0, 0])) - self.assertIsNone(d.compare([0x12345678, 0, 0, 0], [["w32", None], NONE, NONE, NONE], [0x1234ABCD, 0, 0, 0])) - self.assertIn("expected 0x00000000, actual 0x80000000", - d.compare([0, 0, 0, 0], [NONE] * 4, [0, 0x80000000, 0, 0])) - - def test_harness_errors(self): - for line in ("v_div_fixup_f32 v8, v9, v10, v11 op_sel:[1,0,0,0]", "v_div_fixup_f16 v8, v9, v10, v11 mul:2 div:2", - "v_div_fixup_f64 v[8:9], v[10:11], v[10:11], v[10:11] clamp", - "v_div_fixup_f64 v[8:9], 0x3ff00000, v[10:11], v[10:11]", "v_div_fixup_f64 v8, 1.0, 1.0, 1.0", - "v_div_fixup_f16 v8, 1.0, v9, v9 op_sel:[1,0,0,0]", "v_div_fixup_f32 v8, 65, v9, v9", - "v_div_scale_f32 v8, vcc_lo, v9, v9, v9"): - with self.assertRaises(d.HarnessError, msg=line): - run(line, v9=0x3F800000, v10=0x3F800000, v11=0x3FF00000) - - -class OutputMultipliers(unittest.TestCase): - """#6314 measured on gfx1036: under denorm_mode_16_64 = 3 an f16 or binary64 result ignores mul:2/mul:4/div:2, - and an f16 clamp still applies.""" - - def test_f16_result_is_not_scaled(self): - for s0, s1, s2 in ((0x3E00, 0x3C00, 0x3C00), (0x7BFF, 0x3C00, 0x3C00), (0x0001, 0x3C00, 0x3C00), - (0x3C00, 0x0000, 0x3C00), (0x3C00, 0x7C01, 0x3C00), (0x3800, 0xBC00, 0x3C00)): - regs = {"v12": s0 | 0xABCD0000, "v13": s1, "v14": s2} - for sel in ("", " op_sel:[0,0,0,1]"): - plain = run(f"v_div_fixup_f16 v8, v12, v13, v14{sel}", **regs)[1] - clamped = run(f"v_div_fixup_f16 v8, v12, v13, v14{sel} clamp", **regs)[1] if s1 != 0x7C01 else None - for om in ("mul:2", "mul:4", "div:2"): - with self.subTest(s0=hex(s0), s1=hex(s1), sel=sel, om=om): - self.assertEqual(run(f"v_div_fixup_f16 v8, v12, v13, v14{sel} {om}", **regs)[1], plain) - if clamped is not None: - self.assertEqual(run(f"v_div_fixup_f16 v8, v12, v13, v14{sel} clamp {om}", **regs)[1], - clamped) - # 1.5 under clamp div:2: 1.0 (clamped, not halved to 0.75) - self.assertEqual(run("v_div_fixup_f16 v8, v12, v13, v14 clamp div:2", v12=0x3E00, v13=0x3C00, v14=0x3C00)[1] - & 0xFFFF, 0x3C00) - - def test_f64_result_is_not_scaled(self): - for s0 in (0x3FF8000000000000, 0x7FEFFFFFFFFFFFFF, 0x0010000000000000, 3, 1 << 63): - regs = {"v12": s0 & d.M32, "v13": s0 >> 32, "v14": 0, "v15": 0x3FF00000} - mc, _ = run("v_div_fixup_f64 v[8:9], v[12:13], v[14:15], v[14:15]", **regs) - plain = (mc.v[8], mc.v[9]) - self.assertEqual(plain, (s0 & d.M32, (s0 >> 32) & 0x7FFFFFFF)) # |S0| with sign(S1) ^ sign(S2) = + - for om in ("mul:2", "mul:4", "div:2"): - with self.subTest(s0=hex(s0), om=om): - mc, _ = run(f"v_div_fixup_f64 v[8:9], v[12:13], v[14:15], v[14:15] {om}", **regs) - self.assertEqual((mc.v[8], mc.v[9]), plain) - - -class Generator(unittest.TestCase): - def test_generation_is_deterministic(self): - self.assertEqual(d.program(random.Random(5), 6), d.program(random.Random(5), 6)) - self.assertEqual(d.grid_cases(), d.grid_cases()) - - def test_ops_subset_is_respected(self): - lines, used = d.program(random.Random(2), 20, ["v_div_fixup_f64"]) - self.assertEqual(set(used), {"v_div_fixup_f64"}) - self.assertTrue(all(line.split()[0] in ("v_mov_b32", "s_mov_b32", "v_div_fixup_f64") for line in lines)) - - def test_sweep_covers_every_encodable_kind_combination(self): - by_op = Counter(c[0] for c in d.sweep_cases()) - # 5^3 kind triples, less 13 with two or three literals and 4 with three constant-bus reads - self.assertEqual(by_op, {"v_div_fixup_f16": 108, "v_div_fixup_f32": 108, "v_div_fixup_f64": 63}) - for op in d.OPS: - kinds = {k for c in d.sweep_cases([op]) for k in c[1]} - self.assertEqual(kinds, set(d.KINDS64 if op.endswith("f64") else d.KINDS), op) - - def test_programs_are_encodable(self): - rng = random.Random(9) - seen = Counter() - for _ in range(500): - lines, _ = d.program(rng, 6) - for line in lines: - op, args, mods = d.split_line(line) - if op in ("v_mov_b32", "s_mov_b32"): - continue - srcs = [a.strip("-|") for a in args[1:]] - lits = [a for a in srcs if a.startswith("0x")] - bus = [a for a in srcs if a.startswith("s")] - self.assertLessEqual(len(lits), 1, line) - self.assertLessEqual(len(lits) + len(bus), 2, line) - sel = d._opsel(mods) - for i, a in enumerate(srcs): - if sel[i]: - self.assertRegex(a, r"^[sv]\d+$", line) - if op == "v_div_fixup_f64": - self.assertFalse(lits, line) - self.assertLessEqual(set(mods), {"mul:2", "mul:4", "div:2"}, line) - seen[op + " " + " ".join(mods)] += 1 - self.assertRegex(args[0], r"^v\[(8:9|9:10|10:11)\]$", line) - seen["f64 odd pair"] += any(re.match(r"v\[(9|11|13):", a) for a in srcs) - seen["f64 sgpr pair"] += any(a.startswith("s[") for a in srcs) - else: - self.assertIn(args[0], ("v8", "v9", "v10", "v11"), line) - seen[op + " " + " ".join(mods)] += 1 - for want in ("f64 odd pair", "f64 sgpr pair", "v_div_fixup_f32 clamp mul:4", "v_div_fixup_f32 div:2", - "v_div_fixup_f64 mul:2", "v_div_fixup_f64 mul:4", "v_div_fixup_f64 div:2"): - self.assertGreater(seen[want], 0, want) - self.assertTrue(any(k.startswith("v_div_fixup_f16 ") and k.endswith(" clamp mul:4") for k in seen)) - self.assertTrue(any(k.startswith("v_div_fixup_f16 op_sel:") and k.endswith("clamp") for k in seen)) - - def test_edge_grid_reaches_every_rule(self): - cases = d.grid_cases() - self.assertEqual(Counter(c[0] for c in cases), - {"v_div_fixup_f16": 1450, "v_div_fixup_f32": 1397, "v_div_fixup_f64": 1179}) - for op in d.OPS: - f, rules, unjudged = d.FMT[op], Counter(), 0 - for _, words, mods, _, _ in (c for c in cases if c[0] == op): - bits = [(x & f.mag if "|" in m else x) ^ (f.sign if m.startswith("-") else 0) - for x, m in zip(words, mods)] - try: - rules[d.fixup(f, *bits)[0]] += 1 - except d.NotJudged: - unjudged += 1 - want = set(range(8)) - ({5} if op == "v_div_fixup_f16" else set()) - self.assertEqual(set(rules), want, op) - self.assertEqual(unjudged, 8 if op == "v_div_fixup_f64" else 0, op) - every = {"", "clamp", "mul:2", "mul:4", "div:2", "clamp mul:2", "clamp mul:4", "clamp div:2"} - omods = {op: {c[4] for c in cases if c[0] == op} for op in d.OPS} - self.assertEqual(omods, {"v_div_fixup_f16": every, "v_div_fixup_f32": every, - "v_div_fixup_f64": {"", "mul:2", "mul:4", "div:2"}}) - self.assertTrue(any(c[3][3] for c in cases if c[0] == "v_div_fixup_f16")) - # the f16 multipliers reach both destination halves - self.assertEqual({c[3][3] for c in cases if c[0] == "v_div_fixup_f16" and "mul:4" in c[4]}, {0, 1}) - - -class Translated(unittest.TestCase): - def test_harness_canaries(self): - with redirect_stdout(io.StringIO()) as out: - ok = d.self_test() - self.assertTrue(ok, out.getvalue()) - - def test_short_seeded_run_matches(self): - counts, failure = d.run_suite(20, 3, 5) - self.assertEqual((failure, counts["skip"]), (None, {})) - self.assertEqual(counts["pass"] + sum(counts["unjudged"].values()), 20) - self.assertGreater(counts["pass"], 12) - - def test_sweep_matches_for_f64(self): - counts, failure = d.run_sweep(4, ["v_div_fixup_f64"]) - self.assertEqual((failure, counts["skip"]), (None, {})) - self.assertGreater(counts["pass"], 110) - - def test_edge_grid_matches_for_f32(self): - counts, failure = d.run_grid(["v_div_fixup_f32"]) - self.assertEqual((failure, counts["skip"], counts["mismatch"]), (None, {}, 0)) - self.assertGreater(counts["events"]["v_div_fixup_f32"]["exponent cutoff"], 30) - - def test_each_program_is_checked_before_the_next_is_made(self): - # a run holds one program's text at a time, not the whole --programs list - made, seen = [], [] - real = d.program, d.sweep_program, d.grid_program, d.run_one - - def count(f): - return lambda *a: made.append(1) or f(*a) - try: - d.program, d.sweep_program, d.grid_program = (count(f) for f in real[:3]) - d.run_one = lambda lines, name, tmp, events: seen.append(len(made)) or ("match", None) - d.run_suite(5, 1) - d.run_sweep(1, ["v_div_fixup_f16"]) - d.run_grid(["v_div_fixup_f64"]) - finally: - d.program, d.sweep_program, d.grid_program, d.run_one = real - self.assertGreater(len(seen), 5 + 2 * 36) - self.assertEqual(seen, list(range(1, len(seen) + 1))) - - def test_measured_rows_through_the_translator(self): - for insn, v1, v2, v3, want in mf.MEASURED[::6]: - line = insn.replace("v4,", "v8,").replace("v1", "v12").replace("v2", "v13").replace("v3", "v14") - lines = [f"v_mov_b32 v{r}, 0x5a5a5a5a" for r in d.VGPRS] + [f"s_mov_b32 s{r}, 0" for r in d.SGPRS] - lines += [f"v_mov_b32 v12, 0x{v1:08x}", f"v_mov_b32 v13, 0x{v2:08x}", f"v_mov_b32 v14, 0x{v3:08x}", line] - with self.subTest(line=line): - self.assertEqual(d.reference(lines)[0][0], want) - self.assertIsNone(d.check(lines)) - - def test_output_multipliers_through_the_translator(self): - lines = [f"v_mov_b32 v{r}, 0x5a5a5a5a" for r in d.VGPRS] + [f"s_mov_b32 s{r}, 0" for r in d.SGPRS] - lines += ["v_mov_b32 v12, 0x3e00", "v_mov_b32 v13, 0x3c00", "v_mov_b32 v14, 0x3c00", "v_mov_b32 v15, 0x3ff80000", - "v_div_fixup_f16 v8, v12, v13, v14 mul:2", - "v_div_fixup_f16 v9, v12, v13, v14 op_sel:[0,0,0,1] clamp div:2", - "v_div_fixup_f64 v[10:11], v[14:15], v[12:13], v[12:13] mul:4"] - want = d.reference(lines)[0] - self.assertEqual(want, [0x5A5A3E00, 0x3C005A5A, 0x3C00, 0x3FF80000]) - self.assertIsNone(d.check(lines)) - real = d.translate_listing - try: # a translator that applied mul:2 to the f16 result: 3.0, not 1.5 - d.translate_listing = lambda l, n, t: [0x5A5A4200] + real(l, n, t)[1:] - self.assertIn("expected 0x5a5a3e00, actual 0x5a5a4200", d.check(lines)) - # ... or mul:4 to the f64 one: 6.0, not 1.5 - d.translate_listing = lambda l, n, t: real(l, n, t)[:3] + [0x40180000] - self.assertIn("expected 0x3ff80000, actual 0x40180000", d.check(lines)) - finally: - d.translate_listing = real - - def test_a_wrong_translation_is_caught(self): - lines = [f"v_mov_b32 v{r}, 0x5a5a5a5a" for r in d.VGPRS] + [f"s_mov_b32 s{r}, 0" for r in d.SGPRS] - lines += ["v_mov_b32 v12, 0x3f800000", "v_mov_b32 v13, 0x4c000000", "v_mov_b32 v14, 0x00800000", - "v_div_fixup_f32 v8, v12, v13, v14"] - self.assertIsNone(d.check(lines)) - real = d.translate_listing - try: # the result a cutoff of -150 would give: S0, not +0 - d.translate_listing = lambda l, n, t: [0x3F800000] + real(l, n, t)[1:] - self.assertIn("expected 0x00000000, actual 0x3f800000", d.check(lines)) - finally: - d.translate_listing = real - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/test_docs_cli_flags.py b/tests/test_docs_cli_flags.py deleted file mode 100644 index c88e4b85a..000000000 --- a/tests/test_docs_cli_flags.py +++ /dev/null @@ -1,269 +0,0 @@ -"""Every `--flag` the docs name exists in the code, and a command line that runs one tool uses that tool's flags. - - python -I tests/test_docs_cli_flags.py - -`tests/test_docs_repo_paths.py` checks the paths the docs name; this checks the options. A renamed or removed -argparse option leaves `python -I tools/x.py --old` in a README or guide that no longer runs. Three checks: - -1. a `--flag` anywhere in a Markdown page appears as a string in some tracked non-Markdown source file; -2. in a fenced command that starts `python [-I] tools/x.py` (or `scripts/`, or `make_game.py`), every flag appears in - that script (a script that builds flags as `"--" + name` is skipped; `--help` is argparse's own); -3. in a fenced command running a PowerShell script (`scripts/` or `tools/`), every flag appears in that script's - `param()` block. - -Reads tracked files only; no game files. -""" -import os -import re -import subprocess -import unittest - -ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) -FLAG = re.compile(r"(?) and line comments (# ...) outside strings.""" - src = re.sub(r"<#.*?#>", "", src, flags=re.DOTALL) - lines = [] - for line in src.splitlines(): - in_sgl = in_dbl = False - res = [] - for ch in line: - if ch == "'" and not in_dbl: - in_sgl = not in_sgl - elif ch == '"' and not in_sgl: - in_dbl = not in_dbl - elif ch == "#" and not in_sgl and not in_dbl: - break - res.append(ch) - lines.append("".join(res)) - return "\n".join(lines) - - -def extract_ps1_params(content): - """Set of lowercase parameter names from the first param(...) block in a PowerShell script.""" - cleaned = strip_ps_comments(content) - m = re.search(r"\bparam\s*\(", cleaned, re.IGNORECASE) - if not m: - return set() - start = m.end() - depth = 1 - i = start - n = len(cleaned) - in_sgl = in_dbl = False - while i < n and depth > 0: - ch = cleaned[i] - if ch == "'" and not in_dbl: - in_sgl = not in_sgl - elif ch == '"' and not in_sgl: - in_dbl = not in_dbl - elif not in_sgl and not in_dbl: - if ch == "(": - depth += 1 - elif ch == ")": - depth -= 1 - i += 1 - param_body = cleaned[start:i - 1 if depth == 0 else i] - - parts, cur, nest = [], [], 0 - in_sgl = in_dbl = False - for ch in param_body: - if ch == "'" and not in_dbl: - in_sgl = not in_sgl - elif ch == '"' and not in_sgl: - in_dbl = not in_dbl - elif not in_sgl and not in_dbl: - if ch in "([{": - nest += 1 - elif ch in ")]}": - if nest > 0: - nest -= 1 - elif ch == "," and nest == 0: - parts.append("".join(cur).strip()) - cur = [] - continue - cur.append(ch) - if cur: - parts.append("".join(cur).strip()) - - params = set() - for part in parts: - decl = part.split("=", 1)[0] - vars_found = re.findall(r"\$([a-zA-Z_][a-zA-Z0-9_]*)", decl) - if vars_found: - params.add(vars_found[-1].lower()) - return params - - -def unknown_flags(pages, code): - """[(page:line, flag)] for flags in `pages` ({name: text}) that do not occur in `code` (one string).""" - out = [] - for page, text in sorted(pages.items()): - for n, line in enumerate(text.split("\n"), 1): - for flag in sorted(set(FLAG.findall(line))): - if flag not in FOREIGN and flag not in code: - out.append((f"{page}:{n}", flag)) - return out - - -def fenced_commands(text): - """[(line number, one command)] for the fenced code lines, with backslash/backtick continuations joined.""" - out, fence, buf, start = [], False, "", 0 - for n, line in enumerate(text.split("\n"), 1): - if line.lstrip().startswith("```"): - fence, buf = not fence, "" - continue - if not fence: - continue - if not buf: - start = n - stripped = line.rstrip() - if stripped.endswith(("\\", "`")) and not stripped.endswith("``"): - buf += " " + stripped[:-1] - continue - out.append((start, buf + " " + stripped)) - buf = "" - return out - - -# These dev.py subcommands pass their arguments through to the producer. -DEV_PRODUCERS = { - "boot-trace": "tools/boot_trace.py", - "guest-scene": "scripts/run_guest_scene.py", -} - - -def tool_flag_mismatches(pages, sources): - """[(page:line, tool, flag)] for fenced commands running one tool with a flag its source lacks. - `sources` maps a tool path to its text.""" - out = [] - for page, text in sorted(pages.items()): - for n, cmd in fenced_commands(text): - m = COMMAND.search(cmd) - if not m or m.group(1) not in sources: - continue - tool = m.group(1) - args = cmd[m.end():].split(maxsplit=1) - if tool == "scripts/dev.py" and args: - tool = DEV_PRODUCERS.get(args[0], tool) - source = sources.get(tool, "") - if '"--" +' in source or "'--' +" in source: - continue - for flag in sorted(set(FLAG.findall(cmd))): - if flag not in FOREIGN and flag not in source: - out.append((f"{page}:{n}", tool, flag)) - return out - - -def ps1_flag_mismatches(pages, sources): - """[(page:line, tool, flag)] for fenced commands running a .ps1 script with a flag its param() lacks. - `sources` maps a script path to its text or parameter set.""" - param_cache = {} - for path, src in sources.items(): - norm = path.replace("\\", "/") - param_cache[norm] = src if isinstance(src, set) else extract_ps1_params(src) - out = [] - for page, text in sorted(pages.items()): - for n, cmd in fenced_commands(text): - for m in PS1_COMMAND.finditer(cmd): - tool = m.group(1).replace("\\", "/") - if tool not in param_cache: - continue - tail = cmd[m.end():].split("#", 1)[0] - allowed = param_cache[tool] - for flag in sorted(set(PS1_FLAG.findall(tail))): - flag_name = flag.lstrip("-").lower() - if flag_name not in allowed: - out.append((f"{page}:{n}", tool, flag)) - return out - - -class DocsCliFlags(unittest.TestCase): - def test_dev_inherits_only_the_selected_producer_flags(self): - pages = {"docs/dev.md": ("```\n" - "python -I scripts/dev.py boot-trace --d3d12 --negative-controls\n" - "python -I scripts/dev.py guest-scene --negative-controls --d3d12\n" - "python -I scripts/dev.py discover --json --d3d12\n" - "```\n")} - sources = { - "scripts/dev.py": "--json", - "tools/boot_trace.py": "--d3d12", - "scripts/run_guest_scene.py": "--negative-controls", - } - self.assertEqual(tool_flag_mismatches(pages, sources), [ - ("docs/dev.md:2", "tools/boot_trace.py", "--negative-controls"), - ("docs/dev.md:3", "scripts/run_guest_scene.py", "--d3d12"), - ("docs/dev.md:4", "scripts/dev.py", "--d3d12"), - ]) - - def test_checkers_report_only_the_missing_flag(self): - pages = {"docs/a.md": "Use `--real` or `--gone`, and `gh --search`.\n" - "```\npython -I tools/x.py --real --old \\\n --more\npython -I tools/y.py --old\n```\n"} - self.assertEqual(unknown_flags(pages, '"--real" "--more" "--old"'), [("docs/a.md:1", "--gone")]) - sources = {"tools/x.py": 'add("--real") add("--more")', "tools/y.py": 'add("--old")'} - self.assertEqual(tool_flag_mismatches(pages, sources), [("docs/a.md:3", "tools/x.py", "--old")]) - sources["tools/x.py"] += ' "--" + name' - self.assertEqual(tool_flag_mismatches(pages, sources), []) - - ps1_pages = {"docs/b.md": "```\n.\\scripts\\test.ps1 -ValidParam -BadParam\n```\n"} - ps1_sources = {"scripts/test.ps1": "param([string]$ValidParam)"} - self.assertEqual(ps1_flag_mismatches(ps1_pages, ps1_sources), [("docs/b.md:2", "scripts/test.ps1", "-BadParam")]) - - def test_docs_name_existing_flags(self): - files = tracked_files() - code = "\n".join(read(p) for p in files if p.endswith(SOURCE_SUFFIXES) and not p.startswith("docs/")) - pages = {p: read(p) for p in files if p.endswith(".md") and p not in OTHER_PROJECTS} - self.assertTrue(code and pages) - missing = unknown_flags(pages, code) - self.assertEqual(missing, [], "flags in the docs that no source file mentions: " + - "; ".join(f"{where} {flag}" for where, flag in missing)) - - def test_fenced_commands_use_the_flags_of_their_tool(self): - files = tracked_files() - sources = {p: read(p) for p in files if p.endswith(".py") and (p.startswith(("tools/", "scripts/")) or p == "make_game.py")} - pages = {p: read(p) for p in files if p.endswith(".md") and p not in OTHER_PROJECTS} - bad = tool_flag_mismatches(pages, sources) - self.assertEqual(bad, [], "fenced commands using a flag their script lacks: " + - "; ".join(f"{where} {tool} {flag}" for where, tool, flag in bad)) - - ps1_sources = {p: read(p) for p in files if p.endswith(".ps1") and p.startswith(("tools/", "scripts/"))} - ps1_bad = ps1_flag_mismatches(pages, ps1_sources) - self.assertEqual(ps1_bad, [], "fenced commands using a flag their PowerShell script lacks: " + - "; ".join(f"{where} {tool} {flag}" for where, tool, flag in ps1_bad)) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/test_docs_design_rows.py b/tests/test_docs_design_rows.py deleted file mode 100644 index 57761b1a0..000000000 --- a/tests/test_docs_design_rows.py +++ /dev/null @@ -1,141 +0,0 @@ -"""Each table in docs/design.md, docs/README.md and docs/testing.md names a topic once, and every row has the -same number of cells as its header. - - python -I tests/test_docs_design_rows.py - -The translator contract table is where every new rule is recorded (CONTRIBUTING.md, AGENTS.md). When two branches -edit the same row and a merge keeps both sides, the table ends up with two rows for one topic, each holding facts the -other lacks, and a reader who stops at the first one misses the rest. On 2026-11-22 twenty topics appeared two to six -times; the docs index and the testing guide's "Known problems" had the same pattern. This test fails on a repeated -first cell within one table of those pages, where the first cell is the topic (other pages repeat it on purpose, e.g. -one row per benchmark size). No game files or build tools. - -The second check is the table's shape: a rule that writes a literal pipe (`|v|` in a list of source modifiers) -has to escape it as `\\|`, or GitHub reads it as a separator, renders the row into columns the header does not -have and drops the tail of the rule — text lost in a page nobody re-reads. On 2026-11-22 eighteen rows of the -contract table had that shape (four to thirteen cells against a three-cell header). -""" -import os -import unittest - -ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) -PAGES = ("design.md", "README.md", "testing.md") - - -def unescaped_pipes(line): - """How many table separators a row really has: a cell that needs a literal pipe writes it ``\\|``.""" - count, i = 0, 0 - while i < len(line): - if line[i] == "\\": # the next character is literal, pipe or not - i += 2 - continue - if line[i] == "|": - count += 1 - i += 1 - return count - - -def mis_shaped_rows(lines): - """[(line, cells, header cells)] for rows whose cell count differs from their table's header. - - A rule that lists modifiers (`|v|`, `-|v|`) has to escape those pipes as `\\|`. Left raw, GitHub reads each one - as a separator and renders the row into columns the header does not have, dropping the tail of the rule, so the - table silently loses text instead of failing. - """ - found = [] - header, in_fence = None, False - for n, line in enumerate(lines, 1): - if line.lstrip().startswith("```"): - in_fence = not in_fence - if in_fence or not line.startswith("|"): - header = None - continue - cells = unescaped_pipes(line) - if set(line.strip()) <= set("|-: "): # the |---| rule carries the header's shape - header = cells - continue - if header is None: - header = cells - continue - if cells != header: - found.append((n, cells, header)) - return found - - -def repeated_topics(lines): - """[(topic, [1-based line numbers])] for first cells that appear more than once in one table.""" - found = [] - table, in_fence = [], False - - def close(): - seen = {} - for n in table[2:]: # skip the header and the |---| rule - cells = lines[n - 1].split("|") - if len(cells) > 2 and cells[1].strip(): - seen.setdefault(cells[1].strip(), []).append(n) - found.extend((k, v) for k, v in seen.items() if len(v) > 1) - - for n, line in enumerate(lines, 1): - if line.lstrip().startswith("```"): - in_fence = not in_fence - if not in_fence and line.startswith("|"): - table.append(n) - continue - if table: - close() - table = [] - if table: - close() - return found - - -class DesignTableRows(unittest.TestCase): - def test_checker_finds_a_repeated_topic_within_one_table_only(self): - lines = ["| Topic | Rule |", "|---|---|", "| EXEC | old |", "| LDS | x |", "| EXEC | new |", "", - "| Topic | Rule |", "|---|---|", "| LDS | other table |", "```", "| EXEC | in a code block |", - "| EXEC | in a code block |", "```"] - self.assertEqual(repeated_topics(lines), [("EXEC", [3, 5])]) - - def test_checker_finds_a_stray_pipe_but_not_an_escaped_one(self): - lines = ["| Topic | Rule |", "|---|---|", "| EXEC | writes |v| |", "| LDS | fine |", "", - "| Topic | Rule |", "|---|---|", "| EXEC | writes \\|v\\| |", "```", "| x | a | b |", "```"] - self.assertEqual(mis_shaped_rows(lines), [(3, 5, 3)]) - - def test_each_page_has_rows_its_header_can_hold(self): - for page in PAGES: - with self.subTest(page=page): - with open(os.path.join(ROOT, "docs", page), encoding="utf-8") as f: - lines = f.read().split("\n") - wrong = mis_shaped_rows(lines) - self.assertEqual(wrong, [], f"rows to fix in docs/{page} (line, cells, header cells): {wrong}") - - def test_each_page_names_each_topic_once_per_table(self): - for page in PAGES: - with self.subTest(page=page): - with open(os.path.join(ROOT, "docs", page), encoding="utf-8") as f: - lines = f.read().split("\n") - repeated = repeated_topics(lines) - self.assertEqual(repeated, [], f"rows to merge into one in docs/{page} (topic, lines): " + - "; ".join(f"{k[:60]!r} at {v}" for k, v in repeated)) - - def test_deduplicating_a_row_keeps_its_unique_border_mode_facts(self): - """Removing a duplicated sentence must not take unique measured facts with it. - - The "Other additions" row once held two copies of the border-mode and GPU-check paragraphs. A cleanup that - removed the whole block instead of the duplicates lost the BORDER_COLOR_TYPE / SHADER-348 description while - the tests above stayed green, and left a ``". ."`` artifact where the join had been. - """ - with open(os.path.join(ROOT, "docs", "design.md"), encoding="utf-8") as f: - rows = [line for line in f.read().split("\n") if line.startswith("| Other additions |")] - self.assertEqual(len(rows), 1) - row = rows[0] - for fact in ("BORDER_COLOR_TYPE", "SHADER-348", "FORCE_UNNORMALIZED", - "Modes 6 (clamp border) and 7 (mirror once border)", "remaining approximations", - "ps_gather_wrap.asm"): - with self.subTest(fact=fact): - self.assertIn(fact, row) - self.assertNotIn(". .", row) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/test_docs_encoding.py b/tests/test_docs_encoding.py deleted file mode 100644 index d1e56754b..000000000 --- a/tests/test_docs_encoding.py +++ /dev/null @@ -1,43 +0,0 @@ -"""Documentation must be UTF-8, not UTF-8 that was read as cp1252 and written back. - -A file that went through that round trip contains sequences such as ``×`` for ``×`` or -``–`` for ``–``; they make the measured tables in docs/ unreadable. This checks every Markdown -file in docs/ and the root README with the standard library only, no game data. - - python -I tests/test_docs_encoding.py -""" -import os -import unittest - -ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) - -# A UTF-8 byte sequence decoded as Windows-1252 and re-encoded as UTF-8 produces these pairs/triples. -MOJIBAKE = ( - ("\u00c3\u2014", "×"), # C3 97 -> à + EM DASH - ("\u00e2\u02c6\u02c6", "∈"), # E2 88 88 -> â + ˆ + ˆ - ("\u00e2\u20ac\u201c", "–"), # E2 80 93 -> â + € + LEFT DOUBLE QUOTATION MARK - ("\u00e2\u20ac\u201d", "—"), # E2 80 94 -> â + € + RIGHT DOUBLE QUOTATION MARK - ("\u00c2\u00b3", "³"), # C2 B3 ->  + ³ -) - - -class DocsEncoding(unittest.TestCase): - def test_no_cp1252_mojibake_in_docs(self): - paths = [os.path.join(ROOT, "README.md")] - docs = os.path.join(ROOT, "docs") - for dirpath, dirnames, filenames in os.walk(docs): - dirnames.sort() - for name in sorted(filenames): - if name.endswith(".md"): - paths.append(os.path.join(dirpath, name)) - self.assertGreater(len(paths), 1) - for path in paths: - with self.subTest(path=os.path.basename(path)): - with open(path, encoding="utf-8") as handle: - text = handle.read() - for bad, good in MOJIBAKE: - self.assertNotIn(bad, text, f"{os.path.basename(path)}: {bad!r} should be {good!r}") - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/test_docs_env_vars.py b/tests/test_docs_env_vars.py deleted file mode 100644 index 7217d0b1f..000000000 --- a/tests/test_docs_env_vars.py +++ /dev/null @@ -1,97 +0,0 @@ -"""Every LEONIDA_* / GTA6RT_* environment variable the runtime and make_game.py read is named in a document. - - python -I tests/test_docs_env_vars.py - -`runtime/README.md` documents the runtime's variables one by one, but five that the `xgameruntime` shim reads -(`LEONIDA_DEVICE_TYPE` and four more) were in no document at all. This collects the variable names that appear as -string literals in `runtime/core`, `runtime/src`, `runtime/shims` and `make_game.py` and checks that each is written -in some tracked Markdown file. Sources and Markdown only: no build, no GPU, no game files. -""" -import os -import re -import subprocess -import unittest - -ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) -# A variable name as a string literal: "LEONIDA_X", L"LEONIDA_X" or 'LEONIDA_X'. -LITERAL = re.compile(r"""["']((?:LEONIDA|GTA6RT)_[A-Z0-9_]+)["']""") -CODE = ("runtime/core/", "runtime/src/", "runtime/shims/", "make_game.py") -# Set by the runtime for itself, not by a person: gta6rt passes the first to the copy of itself it starts with the -# image base reserved (runtime/src/base_reservation.h), and the second is a name that is only looked up to make -# the CRT build its environment table (runtime/shims/process.cpp). -INTERNAL = {"LEONIDA_BASE_RESERVED", "LEONIDA_RT_ENV_INIT"} - - -def tracked_files(): - try: - out = subprocess.run(["git", "ls-files"], cwd=ROOT, capture_output=True, text=True, check=True).stdout - return [p for p in out.splitlines() if p] - except (OSError, subprocess.CalledProcessError): - found = [] - for root, dirs, files in os.walk(ROOT): - dirs[:] = [d for d in dirs if d not in (".git", "build", "__pycache__", "third_party", ".pytest_cache")] - found += [os.path.relpath(os.path.join(root, f), ROOT).replace(os.sep, "/") for f in files] - return found - - -def read(rel): - with open(os.path.join(ROOT, rel), encoding="utf-8", errors="replace") as f: - return f.read() - - -def variables_read(sources): - """{variable: first "file:line" that names it} over `sources` ({name: text}).""" - found = {} - for name in sorted(sources): - for number, line in enumerate(sources[name].splitlines(), 1): - for variable in LITERAL.findall(line): - found.setdefault(variable, f"{name}:{number}") - return found - - -def undocumented(sources, pages): - """[(variable, where it is read)] for variables no page of `pages` ({name: text}) names as a whole word.""" - text = "\n".join(pages.values()) - return [(variable, where) for variable, where in sorted(variables_read(sources).items()) - if variable not in INTERNAL and not re.search(rf"(?]+)>|([^)\s]+))(?:\s+\"[^\"]*\")?\)") -HTML = re.compile(r'(?:href|src)\s*=\s*"([^"]+)"') -HEADING = re.compile(r"^(#{1,6})\s+(.*?)\s*#*\s*$", re.M) -EXTERNAL = ("http://", "https://", "mailto:", "tel:", "data:") - - -def strip_fences(text): - """Drop fenced code blocks: headings and links inside them are not rendered. - - Line based, as CommonMark reads them: a fence opens on a line indented at most three spaces past the content of - its list item, with three or more backticks (and no backtick in the info string) or tildes, and closes on a line - of the same character, at least as long, with nothing after it. An unclosed fence runs to the end of the page. - A ``` inside a paragraph is inline code, so it never pairs with an unrelated fence further down. - """ - kept = [] - columns = [] # content column of each open list item, innermost last - fence = None # (character, length) of the open fence - for line in text.splitlines(keepends=True): - body = line.rstrip("\r\n").expandtabs(4) - stripped = body.lstrip(" ") - indent = len(body) - len(stripped) - if fence: - char, length = fence - run = len(stripped) - len(stripped.lstrip(char)) - if run >= length and not stripped[run:].strip(" ") and indent - (columns[-1] if columns else 0) <= 3: - fence = None - continue - if not stripped: - kept.append(line) - continue - while columns and indent < columns[-1]: - columns.pop() - item = LIST_ITEM.match(body) - if item and indent - (columns[-1] if columns else 0) <= 3: - rest = body[item.end():] - columns.append(item.end() if rest.strip() else indent + len(item.group(2)) + 1) - indent, stripped = columns[-1], rest.lstrip(" ") - opening = FENCE.match(stripped) - if opening and indent - (columns[-1] if columns else 0) <= 3: - run = opening.group(1) or opening.group(2) - fence = (run[0], len(run)) - continue - kept.append(line) - return "".join(kept) - - -def slug(heading): - """GitHub's heading anchor: lower case, punctuation dropped, spaces become hyphens.""" - text = heading.strip().lower().replace("`", "") - text = re.sub(r"[^\w\- ]", "", text, flags=re.UNICODE) - return text.replace(" ", "-") - - -def anchors(path): - """Every anchor a heading on the page generates, including the -N suffix of a duplicate.""" - seen = {} - found = set() - with open(path, encoding="utf-8", errors="replace") as f: - text = strip_fences(f.read()) - for match in HEADING.finditer(text): - base = slug(match.group(2)) - count = seen.get(base, 0) - seen[base] = count + 1 - found.add(base if count == 0 else f"{base}-{count}") - return found - - -def links(text): - """Markdown link/image targets and HTML href/src values, fenced code excluded.""" - text = strip_fences(text) - found = [m.group(1) or m.group(2) for m in LINK.finditer(text)] - found.extend(HTML.findall(text)) - return found - - -def markdown_files(root): - try: - result = subprocess.run(["git", "ls-files", "-z", "--", "*.md"], cwd=root, capture_output=True) - except FileNotFoundError: - pass # Git is optional when scanning a source archive. - else: - if result.returncode == 0: - return [os.path.join(root, os.fsdecode(name)) for name in result.stdout.split(b"\0") if name] - found = [] - for base, dirs, names in os.walk(root): - dirs[:] = [d for d in dirs if d not in (".git", "third_party", "node_modules", "__pycache__", ".pytest_cache")] - found.extend(os.path.join(base, name) for name in names if name.endswith(".md")) - return found - - -def broken_links(root, files): - """(page, link, reason) for every relative link whose file or anchor does not resolve.""" - cache = {} - - def anchors_of(path): - if path not in cache: - try: - cache[path] = anchors(path) - except OSError: - cache[path] = set() - return cache[path] - - problems = [] - for path in files: - try: - with open(path, encoding="utf-8", errors="replace") as f: - text = f.read() - except OSError: - continue - for link in links(text): - link = link.strip() - if not link or link.startswith(EXTERNAL): - continue - if link.startswith("#"): - anchor = unquote(link[1:]) - if anchor and anchor not in anchors_of(path): - problems.append((os.path.relpath(path, root), link, "same-page anchor not found")) - continue - target, _, anchor = link.partition("#") - if not target: - continue - target = unquote(target.split("?", 1)[0]) - destination = os.path.normpath(os.path.join(os.path.dirname(path), target)) - if not os.path.exists(destination): - problems.append((os.path.relpath(path, root), link, "missing file")) - elif anchor and os.path.isfile(destination) and anchor not in anchors_of(destination): - problems.append((os.path.relpath(path, root), link, "anchor not found")) - return problems - - -class SlugTest(unittest.TestCase): - def test_inline_code_keeps_its_text(self): - self.assertEqual(slug("Rejected candidates at `917e9b9`"), "rejected-candidates-at-917e9b9") - self.assertEqual(slug("`63 30 00 00` mesh pages"), "63-30-00-00-mesh-pages") - - def test_punctuation_is_dropped(self): - self.assertEqual(slug("The Windows runtime on Linux, under Wine or Proton"), - "the-windows-runtime-on-linux-under-wine-or-proton") - - def test_duplicate_headings_get_a_suffix(self): - with tempfile.TemporaryDirectory() as tmp: - page = os.path.join(tmp, "page.md") - with open(page, "w", encoding="utf-8") as f: - f.write("# Same\n\n# Same\n") - self.assertEqual(anchors(page), {"same", "same-1"}) - - -class StripFencesTest(unittest.TestCase): - def test_inline_triple_backticks_do_not_pair_with_a_fence(self): - text = "Write ```x``` inline.\n\n# Kept\n\n```sh\n# dropped\n```\n" - self.assertEqual(strip_fences(text), "Write ```x``` inline.\n\n# Kept\n\n") - - def test_a_longer_fence_holds_a_shorter_one(self): - self.assertEqual(strip_fences("````md\n```\n# dropped\n```\n````\n# Kept\n"), "# Kept\n") - - def test_tilde_fences_close_only_on_tildes(self): - text = "~~~\n```\n# dropped\n~~~\n# Kept\n```\n# dropped\n~~~\n```\n# Also kept\n" - self.assertEqual(strip_fences(text), "# Kept\n# Also kept\n") - - def test_a_closing_fence_takes_no_info_string(self): - self.assertEqual(strip_fences("```\n```sh\n# dropped\n```\n# Kept\n"), "# Kept\n") - - def test_fences_indented_inside_list_items(self): - text = ("- item\n - nested:\n\n ```powershell\n # dropped\n ```\n\n# Kept\n" - "1. ```\n # dropped\n ```\n# Also kept\n") - self.assertEqual(strip_fences(text), "- item\n - nested:\n\n\n# Kept\n# Also kept\n") - - def test_four_spaces_outside_a_list_is_not_a_fence(self): - self.assertEqual(strip_fences(" ```\n# Kept\n"), " ```\n# Kept\n") - - def test_an_unclosed_fence_runs_to_the_end(self): - self.assertEqual(strip_fences("# Kept\n```\n# dropped\n"), "# Kept\n") - - def test_crlf_line_endings(self): - self.assertEqual(strip_fences("```\r\n# dropped\r\n```\r\n# Kept\r\n"), "# Kept\r\n") - - def test_heading_after_inline_backticks_is_an_anchor(self): - with tempfile.TemporaryDirectory() as tmp: - page = os.path.join(tmp, "page.md") - with open(page, "w", encoding="utf-8") as f: - f.write("Use ```code``` inline.\n\n## Real heading\n\n```\n## Not a heading\n```\n") - self.assertEqual(anchors(page), {"real-heading"}) - - -class RepositoryLinksTest(unittest.TestCase): - @unittest.skipUnless(shutil.which("git"), "requires Git") - def test_flags_broken_link_in_tracked_unicode_filename(self): - with tempfile.TemporaryDirectory() as tmp: - subprocess.run(["git", "init", "-q"], cwd=tmp, check=True) - subprocess.run(["git", "config", "core.quotePath", "true"], cwd=tmp, check=True) - page = "café notes.md" - with open(os.path.join(tmp, page), "w", encoding="utf-8", newline="\n") as f: - f.write("[missing](missing.md)\n") - subprocess.run(["git", "add", "--", page], cwd=tmp, check=True) - self.assertEqual(broken_links(tmp, markdown_files(tmp)), [(page, "missing.md", "missing file")]) - - def test_markdown_files_walks_the_tree_when_git_is_missing(self): - with tempfile.TemporaryDirectory() as tmp: - page = os.path.join(tmp, "README.md") - with open(page, "w", encoding="utf-8", newline="\n") as f: - f.write("# README\n") - with patch.object(subprocess, "run", side_effect=FileNotFoundError): - self.assertEqual(markdown_files(tmp), [page]) - - def test_every_relative_link_resolves(self): - files = markdown_files(ROOT) - self.assertGreaterEqual(len(files), 30, "expected the tracked Markdown files to be found") - problems = broken_links(ROOT, files) - self.assertEqual(problems, [], - "\n".join(f"{page}: {link} ({why})" for page, link, why in problems)) - - def test_the_checker_flags_a_missing_file_and_a_bad_anchor(self): - with tempfile.TemporaryDirectory() as tmp: - def write(name, text): - with open(os.path.join(tmp, name), "w", encoding="utf-8") as f: - f.write(text) - write("good.md", "# Intro\n\n[other](other.md)\n[section](other.md#heading-one)\n[here](#intro)\n") - write("other.md", "## Heading one\n") - write("bad.md", "[missing](nope.md)\n[bad anchor](other.md#nope)\n") - files = [os.path.join(tmp, name) for name in ("bad.md", "good.md", "other.md")] - problems = sorted(broken_links(tmp, files)) - self.assertEqual(problems, [ - ("bad.md", "nope.md", "missing file"), - ("bad.md", "other.md#nope", "anchor not found"), - ]) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/test_docs_list_items.py b/tests/test_docs_list_items.py deleted file mode 100644 index 8a750320d..000000000 --- a/tests/test_docs_list_items.py +++ /dev/null @@ -1,88 +0,0 @@ -"""No list item in the Markdown docs is repeated a few lines later. - - python -I tests/test_docs_list_items.py - -When two branches rewrite the same bullet and a merge keeps both sides, the page shows the bullet twice: the current -text and the one it replaced, often next to each other (docs/d3d12_vulkan.md had its RTV/DSV bullet twice and its -"Hash-table cost" / "Wave64" risks twice each; docs/character_models.md kept the first line of a rewritten bullet). -A reader cannot tell which copy is current. This test flags two list items within WINDOW lines of each other whose -openings match. Reads tracked Markdown only; no game files. -""" -import os -import re -import shutil -import subprocess -import tempfile -import unittest -from unittest.mock import patch - -ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) -ITEM = re.compile(r"^(\s*)(?:[-*+]|\d+[.)])\s+(\S.*)$") -WINDOW = 8 # lines between the two items -OPENING = 60 # characters of the item's text that must match (after the list marker) - - -def repeated_items(text): - """[(line a, line b)] for list items within WINDOW lines whose first OPENING characters are equal.""" - items, in_fence = [], False - for n, line in enumerate(text.split("\n"), 1): - if line.lstrip().startswith("```"): - in_fence = not in_fence - continue - m = None if in_fence else ITEM.match(line) - if m and len(m.group(2)) >= OPENING: - items.append((n, len(m.group(1)), m.group(2)[:OPENING])) - found = [] - for i, (n, indent, head) in enumerate(items): - for n2, indent2, head2 in items[i + 1:]: - if n2 - n > WINDOW: - break - if indent2 == indent and head2 == head: - found.append((n, n2)) - return found - - -def markdown_files(): - try: - out = subprocess.run(["git", "ls-files", "-z", "--", "*.md"], cwd=ROOT, capture_output=True, check=True).stdout - files = [os.fsdecode(name) for name in out.split(b"\0") if name] - except (OSError, subprocess.CalledProcessError): - files = [os.path.relpath(os.path.join(r, f), ROOT).replace(os.sep, "/") - for r, d, fs in os.walk(ROOT) if ".git" not in r for f in fs if f.endswith(".md")] - return [f for f in files if not f.startswith("third_party/")] - - -class RepeatedListItems(unittest.TestCase): - @unittest.skipUnless(shutil.which("git"), "requires Git") - def test_reads_tracked_markdown_with_spaces(self): - with tempfile.TemporaryDirectory() as tmp: - subprocess.run(["git", "init", "-q"], cwd=tmp, check=True) - subprocess.run(["git", "config", "core.quotePath", "true"], cwd=tmp, check=True) - page = "space name.md" - with open(os.path.join(tmp, page), "w", encoding="utf-8", newline="\n") as f: - f.write("# Example\n") - subprocess.run(["git", "add", "--", page], cwd=tmp, check=True) - with patch(__name__ + ".ROOT", tmp): - self.test_docs_have_no_repeated_list_items() - self.assertEqual(markdown_files(), [page]) - - def test_checker_flags_a_repeated_item_only(self): - current = "- **Wave64.** A native wave64 shader needs a 64-wide subgroup in its stage: AMD can require it" - old = "- **Wave64.** A native wave64 shader needs a 64-wide subgroup in its stage: AMD (old wording)" - text = "\n".join([current, " continued", "- **Other.** " + "x" * 70, old, "", - "- **19 two-slice 2D arrays** (`depth = 2`, `depth - 1 = 1`) appeared as `depth = 1`", - "- **99 three-slice 2D arrays** (`depth = 3`, `depth - 1 = 2`) appeared as `depth = 2`", - "```", current, current, "```"]) - self.assertEqual(repeated_items(text), [(1, 4)]) - - def test_docs_have_no_repeated_list_items(self): - found = [] - for path in markdown_files(): - with open(os.path.join(ROOT, path), encoding="utf-8") as f: - found += [f"{path}:{a} and :{b}" for a, b in repeated_items(f.read())] - self.assertEqual(found, [], "a list item repeated a few lines later (keep the current copy): " + - "; ".join(found)) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/test_docs_pr_template.py b/tests/test_docs_pr_template.py deleted file mode 100644 index b76037d6d..000000000 --- a/tests/test_docs_pr_template.py +++ /dev/null @@ -1,38 +0,0 @@ -"""The pull request template prompts for `Depends on:`, `Fixes:`, `GPUs tested:` and whether it was AI-assisted. - - python -I tests/test_docs_pr_template.py - -The coordination issue builds its merge chains from `Depends on: #N` lines, AGENTS.md asks a pull request to say -that it was AI-assisted, `Fixes: #N` closes the issue on merge and `GPUs tested:` is what a reviewer checks a GPU -change against. Without a prompt in `.github/pull_request_template.md` those are the lines authors leave out. This -reads the template only, so rewording AGENTS.md or CONTRIBUTING.md cannot fail it. No game files. -""" -import os -import re -import unittest - -ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) -TEMPLATE = os.path.join(".github", "pull_request_template.md") -# A prompt is a line of its own that starts with the words an author fills in. -PROMPTS = ("Depends on:", "Fixes:", "GPUs tested:", "AI-assisted:") - - -def missing_prompts(template): - """The prompts of PROMPTS that no line of `template` starts with.""" - return [p for p in PROMPTS if not re.search("^" + re.escape(p), template, re.M)] - - -class PullRequestTemplateTest(unittest.TestCase): - def test_template_has_every_prompt(self): - with open(os.path.join(ROOT, TEMPLATE), encoding="utf-8") as f: - self.assertEqual(missing_prompts(f.read()), []) - - def test_a_template_without_a_prompt_is_reported(self): - self.assertEqual(missing_prompts("### Tested\n"), list(PROMPTS)) - # A mention inside another sentence is not a prompt: the line has to start with it. - self.assertEqual(missing_prompts("no Depends on: here\nFixes: none\nGPUs tested: n/a\nAI-assisted: no\n"), - ["Depends on:"]) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/test_docs_python_deps.py b/tests/test_docs_python_deps.py deleted file mode 100644 index 94c32b804..000000000 --- a/tests/test_docs_python_deps.py +++ /dev/null @@ -1,81 +0,0 @@ -"""AGENTS.md names every tool that needs numpy or Pillow, and CONTRIBUTING.md says how pytest-based tests run. - - python -I tests/test_docs_python_deps.py - -Both documents promise that Python tools use only the standard library "unless a file says otherwise" and that -`python -I tests/test_.py` runs a unit test. The exceptions drift: `calibrated_texture.py` and `skinned_glb.py` -took numpy without joining the list, and 24 test files are pytest-based and fail (or run nothing) under `python -I`. -Reads tracked files only; no game files. -""" -import ast -import os -import re -import subprocess -import unittest - -ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) -THIRD_PARTY = {"numpy", "PIL"} - - -def tracked_files(): - try: - out = subprocess.run(["git", "ls-files"], cwd=ROOT, capture_output=True, text=True, check=True).stdout - return [p for p in out.splitlines() if p] - except (OSError, subprocess.CalledProcessError): - found = [] - for root, dirs, files in os.walk(ROOT): - dirs[:] = [d for d in dirs if d not in (".git", "build", "__pycache__", ".pytest_cache")] - found += [os.path.relpath(os.path.join(root, f), ROOT).replace(os.sep, "/") for f in files] - return found - - -def imports_third_party(source): - """True if the module imports numpy or PIL anywhere (top level, in a try block or inside a function).""" - for node in ast.walk(ast.parse(source)): - if isinstance(node, ast.Import) and any(a.name.split(".")[0] in THIRD_PARTY for a in node.names): - return True - if isinstance(node, ast.ImportFrom) and node.level == 0 and (node.module or "").split(".")[0] in THIRD_PARTY: - return True - return False - - -def listed_tools(agents_text): - """Basenames of the `*.py` tools in the AGENTS.md convention bullet that names the numpy/Pillow exceptions.""" - bullet = re.search(r"^- Python tools run with `python -I`.*?(?=^- |^\Z)", agents_text, re.S | re.M) - return set(re.findall(r"`([\w]+\.py)`", bullet.group(0))) if bullet else set() - - -def read(path): - with open(os.path.join(ROOT, path), encoding="utf-8") as f: - return f.read() - - -class DocsPythonDeps(unittest.TestCase): - def test_listing_checker_sees_a_missing_and_a_stale_name(self): - text = "- Python tools run with `python -I`; the exceptions are `a.py` and `gone.py`.\n- Next bullet `b.py`.\n" - self.assertEqual(listed_tools(text), {"a.py", "gone.py"}) - self.assertTrue(imports_third_party("try:\n import numpy as np\nexcept ImportError:\n np = None\n")) - self.assertTrue(imports_third_party("def f():\n from PIL import Image\n")) - self.assertFalse(imports_third_party("import json\nfrom os import path\n")) - - def test_agents_lists_the_tools_that_need_numpy_or_pillow(self): - files = tracked_files() - needing = {os.path.basename(p) for p in files - if p.endswith(".py") and (p.startswith(("tools/", "scripts/")) or p == "make_game.py") - and imports_third_party(read(p))} - listed = listed_tools(read("AGENTS.md")) - self.assertTrue(needing and listed) - self.assertEqual(sorted(needing - listed), [], "tools that import numpy/Pillow but are not in AGENTS.md") - self.assertEqual(sorted(listed - needing), [], "tools named in AGENTS.md that no longer import numpy/Pillow") - - def test_contributing_says_pytest_files_do_not_run_under_python_i(self): - pytest_only = [p for p in tracked_files() - if re.fullmatch(r"tests/test_[\w]+\.py", p) and "__main__" not in read(p)] - if pytest_only: - self.assertIn("pytest", read("CONTRIBUTING.md"), - f"{len(pytest_only)} test files have no __main__ block (e.g. {pytest_only[0]}) but " - "CONTRIBUTING.md never mentions pytest") - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/test_docs_repeated_lines.py b/tests/test_docs_repeated_lines.py deleted file mode 100644 index 62720f830..000000000 --- a/tests/test_docs_repeated_lines.py +++ /dev/null @@ -1,74 +0,0 @@ -"""No two neighbouring prose lines in the Markdown docs start the same way. - - python -I tests/test_docs_repeated_lines.py - -When two branches rewrite the same sentence and a merge keeps both sides, the page shows the sentence twice on -consecutive lines: the current text and the one it replaced, usually with a different number in it (docs/d3d12_vulkan.md -had "the one left needs `buffer_store_short`" twice, docs/animation.md gave both 350,251 and 382,781 for the same -export, docs/models.md said its test file runs 10 and 15 tests). A reader cannot tell which line is current. -`tests/test_docs_list_items.py` does this for list items and `tests/test_docs_table_rows.py` for table rows; this -flags two prose lines (neither a list item, table row, heading or code) within WINDOW lines of each other whose first -OPENING characters are equal. Reads tracked Markdown only; no game files. -""" -import os -import re -import subprocess -import unittest - -ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) -WINDOW = 3 # lines between the two (1 = neighbours) -OPENING = 40 # characters, after the indentation, that must match -LIST_ITEM = re.compile(r"^(?:[-*+]|\d+[.)])\s") - - -def repeated_lines(text): - """[(line a, line b)] for prose lines within WINDOW lines whose first OPENING characters are equal.""" - found, in_fence, seen = [], False, {} - for n, line in enumerate(text.split("\n"), 1): - if line.lstrip().startswith("```"): - in_fence = not in_fence - continue - s = line.strip() - if in_fence or len(s) < OPENING or s[0] in "|#>" or LIST_ITEM.match(s): - continue - key = s[:OPENING] - if key in seen and n - seen[key] <= WINDOW: - found.append((seen[key], n)) - seen[key] = n - return found - - -def markdown_files(): - try: - out = subprocess.run(["git", "ls-files", "*.md"], cwd=ROOT, capture_output=True, text=True, check=True).stdout - files = out.split() - except (OSError, subprocess.CalledProcessError): - files = [os.path.relpath(os.path.join(r, f), ROOT).replace(os.sep, "/") - for r, d, fs in os.walk(ROOT) if ".git" not in r.split(os.sep) for f in fs if f.endswith(".md")] - return [f for f in files if not f.startswith("third_party/")] - - -class RepeatedLines(unittest.TestCase): - def test_checker_flags_neighbouring_repeats_only(self): - a = "The disassembly count is unchanged: the same 42 programs have no invalid word, and" - text = "\n".join([ - a + " 10 do.", a + " ten do.", # 1-2: repeated neighbours - "x", "y", "z", "w", - a + " later.", # 7: four lines on, not flagged - "- " + a, "- " + a, # list items are tests/test_docs_list_items.py's - "| " + a, "| " + a, # table rows are tests/test_docs_table_rows.py's - "```", a, a, "```", # inside a code fence - "short", "short", # shorter than OPENING - ]) - self.assertEqual(repeated_lines(text), [(1, 2)]) - - def test_docs_have_no_repeated_neighbouring_lines(self): - found = [] - for path in markdown_files(): - with open(os.path.join(ROOT, path), encoding="utf-8") as f: - found += [f"{path}:{a} and :{b}" for a, b in repeated_lines(f.read())] - self.assertEqual(found, [], "a line repeated just below itself (keep the current one): " + "; ".join(found)) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/test_docs_repo_paths.py b/tests/test_docs_repo_paths.py deleted file mode 100644 index fac5d4c4f..000000000 --- a/tests/test_docs_repo_paths.py +++ /dev/null @@ -1,90 +0,0 @@ -"""Repository paths the docs name in backticks exist. - - python -I tests/test_docs_repo_paths.py - -`tests/test_docs_links.py` checks Markdown links; this checks the other way the docs point at the tree, a backticked -`tools/...`, `runtime/...`, `tests/...`, `scripts/...`, `docs/...`, `viewer/...` or `game/...` path (TEST-871: until -the last three were added, `docs/audio_config.md` named a `docs/music.md` that was never in the repository). -`third_party/` is left out: its files are a submodule's, which `git ls-files` doesn't list. -A rename, or a page written against an unmerged pull request, leaves such a path pointing at nothing -(docs/saves.md described #279's `xgameruntime_services.cpp` as the runtime's save store while #279 was still -open). Reads tracked files only (`git ls-files`, with a directory walk when git is not available); no game files. -""" -import os -import re -import subprocess -import unittest - -ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) -PATH = re.compile(r"`((?:tools|runtime|tests|scripts|docs|viewer|game)/[A-Za-z0-9_./\-]+)`") -# Pages that quote another project's tree (SCARAB, americas-recomp): their paths are not this repository's. -OTHER_PROJECTS = {"docs/fssm_crosscheck.md", "docs/d3d12_xs_surface.md"} -# Build output, not tracked. -BUILD_OUTPUT = ("runtime/build",) - - -def tracked_files(): - try: - out = subprocess.run(["git", "ls-files"], cwd=ROOT, capture_output=True, text=True, check=True).stdout - return [p for p in out.splitlines() if p] - except (OSError, subprocess.CalledProcessError): - found = [] - for root, dirs, files in os.walk(ROOT): - dirs[:] = [d for d in dirs if d not in (".git", "build", "__pycache__", ".pytest_cache")] - found += [os.path.relpath(os.path.join(root, f), ROOT).replace(os.sep, "/") for f in files] - return found - - -def missing_paths(pages, files): - """[(page:line, path)] for backticked repository paths in `pages` ({name: text}) that `files` lacks.""" - known = set(files) - for f in files: - parts = f.split("/") - known.update("/".join(parts[:i]) for i in range(1, len(parts))) - out = [] - for page, text in sorted(pages.items()): - in_fence = False - for n, line in enumerate(text.split("\n"), 1): - if line.lstrip().startswith("```"): - in_fence = not in_fence - continue - if in_fence or "://" in line: # a link into another repository names its paths - continue - for m in PATH.finditer(line): - path = m.group(1).rstrip("/.") - if "*" in path or path.startswith(BUILD_OUTPUT) or path in known: - continue - out.append((f"{page}:{n}", path)) - return out - - -class DocsRepoPaths(unittest.TestCase): - def test_checker_reports_only_the_missing_path(self): - pages = {"docs/a.md": "Run `tools/real.py`, then `tools/gone.py`.\n```\n`tools/in_fence.py`\n```\n" - "`runtime/build/x.exe` and `tests/` and [`tools/x.py`](https://example.org/tools/x.py)"} - self.assertEqual(missing_paths(pages, ["tools/real.py", "tests/t.py"]), [("docs/a.md:1", "tools/gone.py")]) - - def test_docs_viewer_and_game_paths_are_checked(self): - # TEST-871: a missing page, viewer file or package manifest is reported like a missing tool. - pages = {"docs/b.md": "See `docs/real.md`, `docs/gone.md`, `viewer/index.html`, `viewer/gone.js`, " - "`game/xbox-1.0.2.1.json` and `game/gone.json`."} - files = ["docs/real.md", "viewer/index.html", "game/xbox-1.0.2.1.json"] - self.assertEqual(missing_paths(pages, files), - [("docs/b.md:1", "docs/gone.md"), ("docs/b.md:1", "viewer/gone.js"), - ("docs/b.md:1", "game/gone.json")]) - - def test_docs_name_existing_paths(self): - files = tracked_files() - pages = {} - for p in files: - if p.startswith("docs/") and p.endswith(".md") and p not in OTHER_PROJECTS: - with open(os.path.join(ROOT, p), encoding="utf-8") as f: - pages[p] = f.read() - self.assertTrue(pages) - missing = missing_paths(pages, files) - self.assertEqual(missing, [], "backticked paths that name no tracked file: " + - "; ".join(f"{where} {path}" for where, path in missing)) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/test_docs_table_ids.py b/tests/test_docs_table_ids.py deleted file mode 100644 index 86a753108..000000000 --- a/tests/test_docs_table_ids.py +++ /dev/null @@ -1,79 +0,0 @@ -"""No Markdown table names the same bold ID in two of its rows. - - python -I tests/test_docs_table_ids.py - -Tables whose rows are keyed by a bold ID in the first cell (`| **M2** | ...`, the milestones in -docs/d3d12_vulkan.md section 6) are edited one row at a time. When two branches rewrite the same row and a merge -keeps both sides, the table has the row twice, the older text under or near the newer one: section 6 had M2, M3, M6 -and M7 twice each, and its two M6 rows disagreed on how many FSSM programs pass. A reader cannot tell which copy is -current. Tables keyed by plain values (sizes, counts, names) repeat them on purpose and are not checked. Reads -tracked Markdown only; no game files. -""" -import os -import re -import subprocess -import unittest - -ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) -BOLD_ID = re.compile(r"^\*\*[^*]+\*\*$") # the whole first cell is bold -SEPARATOR = re.compile(r"^\|\s*:?-{3}") - - -def repeated_ids(text): - """[(line a, line b, id)] for two rows of one table whose first cells are the same bold ID.""" - found, in_fence, seen, in_table = [], False, {}, False - for n, line in enumerate(text.split("\n"), 1): - if line.lstrip().startswith("```"): - in_fence = not in_fence - in_table = False - continue - row = not in_fence and line.startswith("|") and not SEPARATOR.match(line) - if row and not in_table: - seen = {} - in_table = row or (not in_fence and SEPARATOR.match(line) is not None) - if not row: - continue - cells = line.split("|") - first = cells[1].strip() if len(cells) > 2 else "" - if not BOLD_ID.match(first): - continue - if first in seen: - found.append((seen[first], n, first)) - else: - seen[first] = n - return found - - -def markdown_files(): - try: - out = subprocess.run(["git", "ls-files", "*.md"], cwd=ROOT, capture_output=True, text=True, check=True).stdout - files = out.split() - except (OSError, subprocess.CalledProcessError): - files = [os.path.relpath(os.path.join(r, f), ROOT).replace(os.sep, "/") - for r, d, fs in os.walk(ROOT) if ".git" not in r for f in fs if f.endswith(".md")] - return [f for f in files if not f.startswith("third_party/")] - - -class RepeatedTableIds(unittest.TestCase): - def test_checker_flags_a_repeated_bold_id_only(self): - text = "\n".join([ - "| # | Scope |", "|---|---|", - "| **M2** | new text |", "| **M3** | x |", "| **M2** | old text |", # repeated: flagged - "| 1k | a |", "| 1k | b |", # plain values: not checked - "", - "| # | Scope |", "|---|---|", "| **M2** | another table |", # a new table starts over - "```", "| **M3** | in a fence |", "| **M3** | in a fence |", "```", - ]) - self.assertEqual(repeated_ids(text), [(3, 5, "**M2**")]) - - def test_docs_have_no_repeated_table_ids(self): - found = [] - for path in markdown_files(): - with open(os.path.join(ROOT, path), encoding="utf-8") as f: - found += [f"{path}:{a} and :{b} ({name})" for a, b, name in repeated_ids(f.read())] - self.assertEqual(found, [], "a table row repeated under the same bold ID (keep the current one): " + - "; ".join(found)) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/test_docs_table_rows.py b/tests/test_docs_table_rows.py deleted file mode 100644 index 3cba0d7d6..000000000 --- a/tests/test_docs_table_rows.py +++ /dev/null @@ -1,50 +0,0 @@ -"""Docs tables must not carry rows detached from a header (append-only drift).""" - -import unittest -from pathlib import Path - -ROOT = Path(__file__).resolve().parents[1] -DOCS = [ROOT / "README.md", *sorted((ROOT / "docs").rglob("*.md"))] - - -class DocsTableRowsTest(unittest.TestCase): - def test_no_orphan_table_rows(self): - for path in DOCS: - lines = path.read_text(encoding="utf-8").splitlines() - for i, line in enumerate(lines): - if not line.startswith("|"): - continue - prev = next((x for x in reversed(lines[:i]) if x.strip()), "") - if prev.startswith("|"): - continue - nxt = next((x for x in lines[i + 1:i + 3] if x.strip()), "") - if set(nxt.replace("|", "").replace(" ", "")) <= set("-:"): - continue # this is a table header followed by its separator - self.fail(f"{path.relative_to(ROOT)}:{i + 1}: table row without a table header") - - def test_no_duplicate_rows_in_one_table(self): - for path in DOCS: - lines = path.read_text(encoding="utf-8").splitlines() - block = [] - - def check(rows): - seen = {} - for lineno, row in rows: - if row in seen: - self.fail( - f"{path.relative_to(ROOT)}:{seen[row]} and {lineno}: " - "duplicate row in the same table" - ) - seen[row] = lineno - - for i, line in enumerate(lines, 1): - if line.startswith("|"): - block.append((i, line)) - elif block: - check(block) - block = [] - check(block) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/test_dot_diff.py b/tests/test_dot_diff.py deleted file mode 100644 index 0d6692c36..000000000 --- a/tests/test_dot_diff.py +++ /dev/null @@ -1,184 +0,0 @@ -"""tools/dot_diff.py: the packed integer dot reference against the words measured on RDNA2 hardware and hand-pinned -ISA words, the generator's encoding rules, the source-kind sweep, and a short seeded differential run. Standard -library only; no GPU, no game files. - -The family is v_dot2_i32_i16, v_dot2_u32_u16, v_dot4_i32_i8, v_dot4_u32_u8, v_dot8_i32_i4, v_dot8_u32_u4 (VOP3P) and -the accumulating v_dot4c_i32_i8, v_dot2c_i32_i16, v_dot2c_u32_u16, v_dot4c_u32_u8, v_dot8c_i32_i4, v_dot8c_u32_u4. -""" -import os -import random -import re -import sys -import unittest - -ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) -sys.path.insert(0, os.path.join(ROOT, "tools")) -import dot_diff as d # noqa: E402 (puts tests/semantic on sys.path) -import test_alu_dot4_i8 as hw # noqa: E402 (the gfx1036-measured v_dot4_i32_i8 / v_dot4c_i32_i8 words) - - -def run(*body): - """The reference's four exported words for a program.""" - return d.reference(list(body)) - - -class Reference(unittest.TestCase): - def test_measured_gfx1036_words(self): - # tests/semantic/test_alu_dot4_i8.py: v_dot4_i32_i8 v8, v1, v2, v3 and v_dot4c_i32_i8 on gfx1036 - for a, b, acc, want in hw.MEASURED: - with self.subTest(a=hex(a), b=hex(b), acc=hex(acc)): - self.assertEqual(d.dot("v_dot4_i32_i8", a, b, acc), want) - self.assertEqual(run(f"v_mov_b32 v9, {a:#x}", f"v_mov_b32 v10, {b:#x}", f"v_mov_b32 v11, {acc:#x}", - "v_dot4_i32_i8 v8, v9, v10, v11")[0], want) - self.assertEqual(run(f"v_mov_b32 v9, {a:#x}", f"v_mov_b32 v10, {b:#x}", f"v_mov_b32 v8, {acc:#x}", - "v_dot4c_i32_i8_e32 v8, v9, v10")[0], want) - self.assertEqual(run(f"v_mov_b32 v9, {a:#x}", f"v_mov_b32 v10, {b:#x}", f"v_mov_b32 v8, {acc:#x}", - "v_dot4c_i32_i8_e32 v8, v10, v9")[0], want) - - def test_measured_gfx1036_op_sel_words(self): - # the same hardware with op_sel 2 / op_sel_hi 5: S1's 16-bit halves exchanged - for a, b, acc, want in hw.MEASURED_OP_SEL: - with self.subTest(a=hex(a), b=hex(b), acc=hex(acc)): - self.assertEqual(run(f"v_mov_b32 v9, {a:#x}", f"v_mov_b32 v10, {b:#x}", f"v_mov_b32 v11, {acc:#x}", - "v_dot4_i32_i8 v8, v9, v10, v11 op_sel:[0,1,0] op_sel_hi:[1,0,1]")[0], want) - - def test_clamp_saturates_the_exact_sum(self): - M = d.M32 - # (-32768)^2 + (-32768)^2 = 2^31: wraps, saturates, and cancels against INT32_MIN without early saturation - self.assertEqual(d.dot("v_dot2_i32_i16", 0x80008000, 0x80008000, 0), 0x80000000) - self.assertEqual(d.dot("v_dot2_i32_i16", 0x80008000, 0x80008000, 0, clamp=True), 0x7FFFFFFF) - self.assertEqual(d.dot("v_dot2_i32_i16", 0x80008000, 0x80008000, 0x80000000, clamp=True), 0) - self.assertEqual(d.dot("v_dot2_i32_i16", 0x80008000, 0x80008000, 0x80000000), 0) - # the signed accumulator: -1 + 2^31 is in range, INT32_MIN - 448 is not - self.assertEqual(d.dot("v_dot2_i32_i16", 0x80008000, 0x80008000, M, clamp=True), 0x7FFFFFFF) - self.assertEqual(d.dot("v_dot8_i32_i4", 0x77777777, 0x88888888, 0x80000000, clamp=True), 0x80000000) - self.assertEqual(d.dot("v_dot8_i32_i4", 0x77777777, 0x88888888, 0x80000000), 0x7FFFFE40) - # unsigned: 2 * 65535^2 wraps to 0xfffc0002, saturates to UINT32_MAX; an unsigned accumulator never goes below 0 - self.assertEqual(d.dot("v_dot2_u32_u16", M, M, 0), 0xFFFC0002) - self.assertEqual(d.dot("v_dot2_u32_u16", M, M, 0, clamp=True), M) - self.assertEqual(d.dot("v_dot4_u32_u8", 0, 0, 0x80000000, clamp=True), 0x80000000) - self.assertEqual(d.dot("v_dot8_u32_u4", M, M, M - 1799, clamp=True), M) - self.assertEqual(d.dot("v_dot8_u32_u4", M, M, M - 1800, clamp=True), M) - self.assertEqual(d.dot("v_dot8_u32_u4", M, M, M - 1801, clamp=True), M - 1) - - def test_element_widths_and_signedness(self): - self.assertEqual(d.elements(0x80017FFF, 16, True), [32767, -32767]) - self.assertEqual(d.elements(0x80017FFF, 16, False), [32767, 32769]) - self.assertEqual(d.elements(0x807F01FF, 8, True), [-1, 1, 127, -128]) - self.assertEqual(d.elements(0x89ABCDEF, 4, True), [-1, -2, -3, -4, -5, -6, -7, -8]) - self.assertEqual(d.elements(0x89ABCDEF, 4, False), [15, 14, 13, 12, 11, 10, 9, 8]) - - def test_constants_read_as_32_bit_dwords(self): - # an inline constant is the sign-extended dword, a literal the whole dword - self.assertEqual(run("v_mov_b32 v9, 0x00010001", "v_dot2_i32_i16 v8, v9, -2, 0")[0], 0xFFFFFFFD) # (-2) + (-1) - self.assertEqual(run("v_mov_b32 v9, 0x00010001", "v_dot2_i32_i16 v8, v9, 64, 0")[0], 64) # 64 + 0 - self.assertEqual(run("v_mov_b32 v9, 0x00010001", "v_dot2_i32_i16 v8, v9, 0x00030004, 0")[0], 7) - - def test_line_parsing(self): - self.assertEqual(d.split_line("v_dot4_i32_i8 v8, v9, s4, 0x10 op_sel:[1,0,0] op_sel_hi:[1,1,1] clamp"), - ("v_dot4_i32_i8", ["v8", "v9", "s4", "0x10"], - {"clamp": True, "op_sel": (1, 0, 0), "op_sel_hi": (1, 1, 1)})) - self.assertEqual(d.split_line("v_dot8c_i32_i4_e64 v8, -3, v9 clamp"), - ("v_dot8c_i32_i4", ["v8", "-3", "v9"], {"clamp": True})) - with self.assertRaises(d.HarnessError): - run("v_dot2_i32_i16 v8, v9, v10, v11 op_sel:[1,0,0] op_sel_hi:[1,1,1]") # not a modelled form - - -class Generator(unittest.TestCase): - def test_generation_is_deterministic(self): - self.assertEqual(d.program(random.Random(5), 6), d.program(random.Random(5), 6)) - self.assertNotEqual(d.program(random.Random(5), 6), d.program(random.Random(6), 6)) - - def test_ops_subset_is_respected(self): - rng = random.Random(1) - ops = ["v_dot2_u32_u16", "v_dot4c_i32_i8"] - for _ in range(30): - _, used = d.program(rng, 4, ops) - self.assertTrue(set(used) <= set(ops)) - cases = d.sweep_ops(ops) - self.assertEqual({op for op, *_ in cases}, set(ops)) - self.assertEqual(len(cases), 100 + 4) - - def test_sweep_size(self): - # VOP3P: 50 encodable kind triples x clamp on/off; v_dot4_i32_i8 adds 16 op_sel settings x clamp on/off; - # v_dot4c_i32_i8: 4 S0 kinds; each gfx908 accumulating op: 4 S0 kinds plus 3 (no literal) with clamp - self.assertEqual(len(d.sweep_ops()), 6 * 100 + 32 + 4 + 5 * 7) - - def test_edge_grid(self): - self.assertEqual(d.lane_edges(16), (0x80008000, 0x7FFF7FFF, 0xFFFFFFFF, 0x7FFF8000)) - self.assertEqual(d.lane_edges(8), (0x80808080, 0x7F7F7F7F, 0xFFFFFFFF, 0x7F807F80)) - self.assertEqual(d.lane_edges(4), (0x88888888, 0x77777777, 0xFFFFFFFF, 0x78787878)) - # 16 S0/S1 pairs x 8 accumulators, x2 where clamp is taken: 6 VOP3P + 5 gfx908 forms, v_dot4c_i32_i8 once - cases = d.grid_cases() - self.assertEqual(len(cases), 11 * 256 + 128) - self.assertIn(("v_dot2_i32_i16", 0x80008000, 0x80008000, 0, True), cases) # the product-only overflow - for chunk in (cases[:4], cases[-3:]): - words = run(*d.grid_program(chunk)) - for (op, x, y, acc, clamp), got in zip(chunk, words): - self.assertEqual(got, d.dot(op, x, y, acc, clamp)) - - def test_programs_are_encodable(self): - rng = random.Random(2) - for _ in range(200): - lines, _ = d.program(rng, 6) - for line in lines: - op, args, mods = d.split_line(line) - if op not in d.FAMILY: - continue - self.assertTrue(8 <= d._dst_index(args[0]) <= 11, line) # results land in exported regs - srcs = args[1:] - lits = [s for s in srcs if s.startswith("0x")] - if op in d.VOP3P_OPS: - self.assertLessEqual(len(lits), 1, line) - self.assertLessEqual(len(lits) + sum(s.startswith("s") for s in srcs), 2, line) - if op not in d.OPSEL_OPS: - self.assertEqual((mods.get("op_sel", (0, 0, 0)), mods.get("op_sel_hi", (1, 1, 1))), - ((0, 0, 0), (1, 1, 1)), line) - else: - self.assertRegex(srcs[1], r"^v\d+$", line) # VOP2 S1 - self.assertTrue(line.split()[0].endswith("_e64") == ("clamp" in mods), line) - if "clamp" in mods: - self.assertIn(op, d.CLAMP_ACC_OPS) - self.assertFalse(lits, line) # gfx908 VOP3: no literal - - def test_accumulating_op_reads_the_old_destination(self): - self.assertEqual(run("v_mov_b32 v8, 0xFFFFFFF0", "v_mov_b32 v9, 0x01010101", - "v_dot4c_u32_u8_e32 v8, v9, v9")[0], 0xFFFFFFF4) - self.assertEqual(run("v_mov_b32 v8, 0xFFFFFFF0", "v_mov_b32 v9, 0x01010101", - "v_dot4c_u32_u8_e64 v8, 16, v9 clamp")[0], 0xFFFFFFFF) - - -class Translated(unittest.TestCase): - def test_harness_canaries(self): - self.assertTrue(d.self_test()) - - def test_short_seeded_run_matches(self): - counts, failure = d.run_suite(20, 3, 5) - self.assertEqual(failure, None) - self.assertEqual(counts["skip"], {}) - self.assertEqual(counts["pass"], 20) - - def test_sweep_matches_for_the_signed_vop3p_ops(self): - counts, failure = d.run_sweep(4, ["v_dot2_i32_i16", "v_dot4_i32_i8"]) - self.assertEqual((failure, counts["skip"]), (None, {})) - self.assertEqual(counts["pass"], 100 + 132) - - def test_edge_grid_matches_for_v_dot2_i32_i16(self): - counts, failure = d.run_grid(["v_dot2_i32_i16"]) - self.assertEqual((failure, counts["skip"], counts["pass"]), (None, {}, 64)) - self.assertGreater(counts["events"][("v_dot2_i32_i16", "saturated")], 0) - - def test_a_wrong_translation_is_caught(self): - lines = ["v_mov_b32 v8, 0x80008000", "v_mov_b32 v9, 0x80008000", "v_mov_b32 v10, 0", - "v_dot2_i32_i16 v11, v8, v9, v10 clamp"] - self.assertIsNone(d.check(lines)) - real = d.translate_listing - try: - d.translate_listing = lambda l, n, t: real(l, n, t)[:3] + [0x80000000] # wrapped instead of clamped - self.assertIn("expected 0x7fffffff, actual 0x80000000", d.check(lines)) - finally: - d.translate_listing = real - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/test_dotnet_rollforward.py b/tests/test_dotnet_rollforward.py deleted file mode 100644 index ac7fd8005..000000000 --- a/tests/test_dotnet_rollforward.py +++ /dev/null @@ -1,56 +0,0 @@ -"""Every .NET program in the repository may run on a newer runtime than the one it targets. - -The projects target net8.0, but a machine with only a newer .NET (the 10 SDK and runtime that current distributions -ship, for instance) builds them and then cannot start them: the host stops with "You must install or update .NET -to run this application ... Framework 'Microsoft.NETCore.App', version '8.0.0'" (exit code 150). make_game.py's -preflight and global.json already accept a newer SDK, so the built program has to accept a newer runtime too: an -`Exe` project sets to Major or LatestMajor, which goes into its runtimeconfig.json. A machine that has -the 8 runtime keeps using it. Standard library only; no .NET needed. -""" - -import os -import unittest -import xml.etree.ElementTree as ET - -ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) -SKIP_DIRS = {".git", "bin", "obj", "node_modules", "third_party", "build"} -POLICIES = {"Major", "LatestMajor"} - - -def project_files(): - for folder, dirs, files in os.walk(ROOT): - dirs[:] = [d for d in dirs if d not in SKIP_DIRS and not d.startswith("build")] - for name in files: - if name.endswith((".csproj", ".fsproj", ".vbproj")): - yield os.path.join(folder, name) - - -def property_values(path, name): - """The values of in every PropertyGroup of an SDK-style project file.""" - root = ET.parse(path).getroot() - return [(el.text or "").strip() for group in root.iter("PropertyGroup") for el in group.findall(name)] - - -class RollForwardTest(unittest.TestCase): - def test_the_projects_are_found(self): - names = {os.path.basename(p) for p in project_files()} - self.assertIn("rpf9dump.csproj", names) - self.assertIn("Rpf9DumpDiagnostics.csproj", names) - - def test_every_executable_project_rolls_forward(self): - checked = 0 - for path in project_files(): - if "Exe" not in property_values(path, "OutputType"): - continue - checked += 1 - rel = os.path.relpath(path, ROOT) - with self.subTest(project=rel): - self.assertTrue( - set(property_values(path, "RollForward")) & POLICIES, - f"{rel} is an Exe without Major: with only a newer .NET runtime " - "installed it builds but does not start (host exit 150)") - self.assertGreaterEqual(checked, 2) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/test_draw_ownership.py b/tests/test_draw_ownership.py deleted file mode 100644 index e649e86c3..000000000 --- a/tests/test_draw_ownership.py +++ /dev/null @@ -1,280 +0,0 @@ -"""Synthetic-data tests for tools/draw_ownership.py. - - python -I tests/test_draw_ownership.py - -Builds a ~64 KiB system segment with five drawable scenarios, then walks it and -reverses it: - - A1, A2 - regular chains: the walk MUST find the geometries, and classify_parent - answers "model-compatible" for the walked entries tables. - B - the LOD+8 used/capacity pair has used != capacity (H3): the walk rejects it. - C - the LOD pointer sits at +72, not at the +80 the schema reads (H1 - simulation): the walk cannot find it, only the reverse scan shows the - parent offset. - D - an orphan geometry-entries table that no drawable/model points at, only a - foreign structure: classify_parent answers "unknown parent", with a - 32-byte hex dump. - -Every byte here is built by the test. No game file, value or name is used. -""" -import os -import struct -import sys -import unittest - -ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) -sys.path.insert(0, os.path.join(ROOT, "tools")) - -import draw_ownership as dwo # noqa: E402 - -SIZE = 64 * 1024 - - -class Builder: - """8-byte-aligned bump allocator and field writers for the synthetic segment. - - Every system-pointer write is recorded as a (source position, target offset) edge, - so the tests can check the reverse index against exactly the edges that were built. - """ - - def __init__(self, size=SIZE): - self.buf = bytearray(size) - self.pos = 0 - self.edges = [] - - def alloc(self, nbytes): - self.pos = (self.pos + 7) & ~7 - at = self.pos - self.pos += nbytes - if self.pos > len(self.buf): - raise OverflowError("out of space in the synthetic segment") - return at - - def u16(self, at, value): - struct.pack_into(">10, lsb=1 - b.ptr(desc, ib) - b.u16(desc + 8, 2) # meshlets u16 - b.u16(desc + 10, 8) # triangles u16 - b.u32(desc + 12, 16 << 8) # binding u32: refs=(binding>>8)&0x7FFFFF - b.u32(ib + 8, 64) # index word count - b.u16(ib + 12, 4) # stride u16 = 4 - b.graphics_ptr(ib + 24, 0x2000) - b.ptr(geo + 8, vb) - b.ptr(geo + 64, desc) - return geo - - -def build_model(b, geometry_offsets): - """A 56B model record plus a geometry-entries table of 8B slots (used == capacity).""" - model = b.alloc(56) - entries = b.alloc(8 * len(geometry_offsets)) - for j, geo in enumerate(geometry_offsets): - b.ptr(entries + 8 * j, geo) - b.ptr(model + 8, entries) - b.u16(model + 16, len(geometry_offsets)) - b.u16(model + 18, len(geometry_offsets)) - b.u16(model + 54, len(geometry_offsets)) - return model, entries - - -def build_lod(b, model_offsets, used=None, capacity=None): - """A 16B LOD record plus a model-pointer table of 8B slots. used/capacity can be - overridden for the H3 case; the table holds `capacity` slots and the first - len(model_offsets) are live.""" - n_slots = capacity if capacity is not None else len(model_offsets) - lod = b.alloc(16) - table = b.alloc(8 * n_slots) - for i, model in enumerate(model_offsets): - b.ptr(table + 8 * i, model) - b.ptr(lod, table) - b.u16(lod + 8, used if used is not None else len(model_offsets)) - b.u16(lod + 10, n_slots) - return lod, table - - -def build_drawable(b, lod, link=80): - """A 176B drawable record; the LOD pointer goes to the `link` offset (+80 is the - schema, +72 the H1 simulation).""" - drawable = b.alloc(176) - b.ptr(drawable + link, lod) - return drawable - - -def build_segment(): - """Build the whole synthetic segment. Returns (system bytes, recorded edges, - dict of the offsets the tests assert on).""" - b = Builder() - - # --- A1: two models (3 + 1 geometries) --- - a1_geos = [build_geometry(b) for _ in range(3)] + [build_geometry(b)] - a1_m1, a1_e1 = build_model(b, a1_geos[:3]) - a1_m2, a1_e2 = build_model(b, a1_geos[3:]) - a1_lod, _ = build_lod(b, [a1_m1, a1_m2]) - a1 = build_drawable(b, a1_lod) - - # --- A2: one model (2 geometries) --- - a2_geos = [build_geometry(b, vertices=128) for _ in range(2)] - a2_m, a2_e = build_model(b, a2_geos) - a2_lod, _ = build_lod(b, [a2_m]) - a2 = build_drawable(b, a2_lod) - - # --- B: used != capacity at LOD+8 (H3) --- - b_geos = [build_geometry(b) for _ in range(2)] - b_m, _ = build_model(b, b_geos) - b_lod, _ = build_lod(b, [b_m], used=2, capacity=5) - b_drawable = build_drawable(b, b_lod) - - # --- C: the LOD pointer sits at drawable+72, the schema's +80 stays zero (H1 simulation) --- - c_geos = [build_geometry(b) for _ in range(2)] - c_m, _ = build_model(b, c_geos) - c_lod, _ = build_lod(b, [c_m]) - c_drawable = build_drawable(b, c_lod, link=72) - - # --- D: an orphan entries table (no model or drawable above it); its parent is a - # foreign, non-model-shaped 64B record whose +16 field points at it --- - d_geos = [build_geometry(b) for _ in range(2)] - d_entries = b.alloc(8 * len(d_geos)) - for j, geo in enumerate(d_geos): - b.ptr(d_entries + 8 * j, geo) - d_x = b.alloc(64) - d_scratch = b.alloc(32) - b.ptr(d_x, d_scratch) # another pointer field of the foreign structure - b.ptr(d_x + 16, d_entries) # the single edge to the orphan table - b.u32(d_x + 40, 0x7F3A00C1) # foreign type tag / count-like fields - - system = bytes(b.buf) - offsets = {"a1": a1, "a1_geos": a1_geos, "a1_m1": a1_m1, "a1_e1": a1_e1, - "a1_m2": a1_m2, "a1_e2": a1_e2, "a1_lod": a1_lod, - "a2": a2, "a2_lod": a2_lod, "a2_geos": a2_geos, "a2_m": a2_m, "a2_e": a2_e, - "b_drawable": b_drawable, "c_drawable": c_drawable, "c_lod": c_lod, - "d_geos": d_geos, "d_entries": d_entries, "d_x": d_x} - return system, b.edges, offsets - - -class WalkTests(unittest.TestCase): - @classmethod - def setUpClass(cls): - cls.system, _, cls.off = build_segment() - - def test_a1_two_model_chain(self): - found = list(dwo.walk_drawable(self.system, self.off["a1"])) - self.assertEqual(found, self.off["a1_geos"]) - chain = dwo.walk_chain(self.system, self.off["a1"]) - self.assertEqual(chain["drawable"], self.off["a1"]) - self.assertEqual(chain["lod"], self.off["a1_lod"]) - self.assertEqual([m["model"] for m in chain["models"]], [self.off["a1_m1"], self.off["a1_m2"]]) - self.assertEqual([m["entries"] for m in chain["models"]], [self.off["a1_e1"], self.off["a1_e2"]]) - self.assertEqual([m["geometries"] for m in chain["models"]], - [self.off["a1_geos"][:3], self.off["a1_geos"][3:]]) - - def test_a2_single_model_chain(self): - found = list(dwo.walk_drawable(self.system, self.off["a2"])) - self.assertEqual(found, self.off["a2_geos"]) - chain = dwo.walk_chain(self.system, self.off["a2"]) - self.assertEqual(chain["lod"], self.off["a2_lod"]) - self.assertEqual([m["model"] for m in chain["models"]], [self.off["a2_m"]]) - self.assertEqual([m["entries"] for m in chain["models"]], [self.off["a2_e"]]) - - def test_b_used_capacity_mismatch_is_rejected(self): - # H3: the walk must reject used != capacity, with the exact pair in the message - with self.assertRaises(dwo.CountError) as ctx: - list(dwo.walk_drawable(self.system, self.off["b_drawable"])) - message = str(ctx.exception) - self.assertIn("used=2", message) - self.assertIn("capacity=5", message) - - def test_drawable_outside_segment_is_rejected(self): - with self.assertRaises(dwo.OutOfSegmentError): - list(dwo.walk_drawable(self.system, len(self.system))) - - -class ReverseScanTests(unittest.TestCase): - @classmethod - def setUpClass(cls): - cls.system, cls.edges, cls.off = build_segment() - cls.index = dwo.reverse_pointers(cls.system) - - def test_c_walk_misses_the_lod_pointer_at_72(self): - with self.assertRaises(dwo.OutOfSegmentError): - list(dwo.walk_drawable(self.system, self.off["c_drawable"])) - - def test_c_reverse_scan_finds_the_parent(self): - # H1 simulation: the only incoming edge of the LOD record is the +72 field - sources = self.index.get(self.off["c_lod"], []) - self.assertEqual(sources, [self.off["c_drawable"] + 72]) - - def test_reverse_index_has_no_false_positives(self): - # The reverse index is exactly the set of pointers the builder wrote: every edge - # in it is a real pointer field, and no count/stride/tag value became an edge. - expected = {} - for at, target in self.edges: - expected.setdefault(target, []).append(at) - for sources in expected.values(): - sources.sort() - self.assertEqual(self.index, expected) - - def test_walked_geometries_have_their_entries_edge(self): - for drawable in (self.off["a1"], self.off["a2"]): - chain = dwo.walk_chain(self.system, drawable) - for model in chain["models"]: - for j, geo in enumerate(model["geometries"]): - self.assertIn(model["entries"] + 8 * j, self.index.get(geo, [])) - - def test_walked_entries_tables_classify_model_compatible(self): - for entries_key, model_key, geo_n in (("a1_e1", "a1_m1", 3), ("a1_e2", "a1_m2", 1), - ("a2_e", "a2_m", 2)): - with self.subTest(entries=hex(self.off[entries_key])): - parents = dwo.classify_parent(self.system, self.off[entries_key], self.index) - self.assertEqual(len(parents), 1) - self.assertEqual(parents[0]["classification"], "model-compatible") - self.assertEqual(parents[0]["model"], self.off[model_key]) - self.assertEqual(parents[0]["geometry_count"], geo_n) - self.assertTrue(parents[0]["model_referenced"]) - - def test_orphan_entries_table_classifies_unknown_parent(self): - parents = dwo.classify_parent(self.system, self.off["d_entries"], self.index) - self.assertEqual(len(parents), 1) - parent = parents[0] - self.assertEqual(parent["source"], self.off["d_x"] + 16) - self.assertEqual(parent["classification"], "unknown parent") - self.assertEqual(parent["model_candidate"], self.off["d_x"] + 8) - self.assertEqual(len(parent["context_dump"].splitlines()), 2) - - def test_orphan_geometries_pass_the_shape_check(self): - # The D table's geometry records are geometry-shaped on the system side; - # only their parent is unknown. - for geo in self.off["d_geos"]: - dwo.geometry_shape_check(self.system, geo) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/test_ds_permute_probe.py b/tests/test_ds_permute_probe.py deleted file mode 100644 index 32e8d5250..000000000 --- a/tests/test_ds_permute_probe.py +++ /dev/null @@ -1,137 +0,0 @@ -"""CPU-only unit tests for tools/ds_permute_probe.py (SHADER-133).""" -import io -import json -import os -import subprocess -import sys -import tempfile -import types -import unittest -from unittest import mock - -REPO = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) -TOOLS = os.path.join(REPO, "tools") -PROBE = os.path.join(TOOLS, "ds_permute_probe.py") -if TOOLS not in sys.path: - sys.path.insert(0, TOOLS) - -import ds_permute_probe # noqa: E402 - - -class _FakeUnavailable(Exception): - pass - - -def _fake_hw_oracle(open_side_effect=None): - asm_mod = types.SimpleNamespace(family=lambda arch: "gfx10") - open_oracle = mock.Mock(side_effect=open_side_effect or _FakeUnavailable("no gpu")) - runner_mod = types.SimpleNamespace(Unavailable=_FakeUnavailable, open_oracle=open_oracle) - pkg = types.SimpleNamespace(asm=asm_mod, runner=runner_mod) - return pkg, asm_mod, runner_mod, open_oracle - - -class DsPermuteProbeTests(unittest.TestCase): - def test_self_test(self): - proc = subprocess.run([sys.executable, "-I", PROBE, "--self-test"], - capture_output=True, text=True, check=False) - self.assertEqual(proc.returncode, 0, proc.stderr or proc.stdout) - self.assertIn("self-test OK", proc.stdout) - - def test_missing_oracle_exits_77(self): - env = {k: v for k, v in os.environ.items() - if not k.startswith("LEONIDA_HW_") and k != "LEONIDA_AMD_CLANG"} - env["LEONIDA_AMD_CLANG"] = os.path.join(REPO, "does_not_exist_clang") - proc = subprocess.run([sys.executable, "-I", PROBE], env=env, - capture_output=True, text=True, check=False) - self.assertEqual(proc.returncode, 77, proc.stderr or proc.stdout) - - def test_invalid_waves_rejected_before_open_oracle(self): - pkg, asm_mod, runner_mod, open_oracle = _fake_hw_oracle() - with mock.patch.dict(sys.modules, {"hw_oracle": pkg, "hw_oracle.asm": asm_mod, "hw_oracle.runner": runner_mod}): - for bad in ("", " , ", "abc", "32,abc", "16", "128"): - with self.subTest(waves=bad): - stderr = io.StringIO() - with mock.patch.object(sys, "stderr", stderr): - rc = ds_permute_probe.main(["--waves", bad]) - self.assertEqual(rc, 2) - self.assertIn("error:", stderr.getvalue()) - open_oracle.assert_not_called() - - def test_invalid_json_paths_rejected_before_open_oracle(self): - pkg, asm_mod, runner_mod, open_oracle = _fake_hw_oracle() - with tempfile.TemporaryDirectory() as tmp: - existing_dir = os.path.join(tmp, "dir") - os.mkdir(existing_dir) - file_ancestor = os.path.join(tmp, "not_a_dir") - with open(file_ancestor, "w", encoding="utf-8") as f: - f.write("x") - - bad_paths = [ - "", - " ", - "bad\x00out.json", - existing_dir, - os.path.join(tmp, "trailing") + os.sep, - os.path.join(file_ancestor, "sub", "out.json"), - ] - with mock.patch.dict(sys.modules, {"hw_oracle": pkg, "hw_oracle.asm": asm_mod, - "hw_oracle.runner": runner_mod}): - for bad in bad_paths: - with self.subTest(json_out=bad): - stderr = io.StringIO() - with mock.patch.object(sys, "stderr", stderr): - rc = ds_permute_probe.main(["--json", bad]) - self.assertEqual(rc, 2) - self.assertIn("error:", stderr.getvalue()) - open_oracle.assert_not_called() - - def test_valid_nested_json_does_not_create_dirs_when_oracle_unavailable(self): - pkg, asm_mod, runner_mod, open_oracle = _fake_hw_oracle() - with tempfile.TemporaryDirectory() as tmp: - nested_parent = os.path.join(tmp, "a", "b") - json_out = os.path.join(nested_parent, "report.json") - with mock.patch.dict(sys.modules, {"hw_oracle": pkg, "hw_oracle.asm": asm_mod, - "hw_oracle.runner": runner_mod}): - stderr = io.StringIO() - with mock.patch.object(sys, "stderr", stderr): - rc = ds_permute_probe.main(["--json", json_out]) - self.assertEqual(rc, 77) - open_oracle.assert_called_once() - self.assertFalse(os.path.exists(os.path.join(tmp, "a"))) - - def test_write_json_report_creates_parents_and_writes_lf_json(self): - with tempfile.TemporaryDirectory() as tmp: - out_path = os.path.join(tmp, "nested", "dir", "out.json") - payload = {"arch": "gfx1030", "waves": {"32": {"cases_total": 1, "cases_ok": 1}}} - err = ds_permute_probe.write_json_report(out_path, payload) - self.assertIsNone(err) - with open(out_path, "rb") as f: - raw = f.read() - self.assertNotIn(b"\r\n", raw) - self.assertEqual(json.loads(raw.decode("utf-8")), payload) - - def test_write_json_report_and_main_catch_oserror_cleanly(self): - with tempfile.TemporaryDirectory() as tmp: - out_path = os.path.join(tmp, "out.json") - with mock.patch("builtins.open", side_effect=PermissionError("denied")): - err = ds_permute_probe.write_json_report(out_path, {"ok": True}) - self.assertIsNotNone(err) - self.assertIn("cannot write --json", err) - - oracle = types.SimpleNamespace(arch="gfx1030") - pkg, asm_mod, runner_mod, _ = _fake_hw_oracle(open_side_effect=lambda: oracle) - fake_probe = {"cases_total": 1, "cases_ok": 1, "cases": {}} - with mock.patch.dict(sys.modules, {"hw_oracle": pkg, "hw_oracle.asm": asm_mod, - "hw_oracle.runner": runner_mod}), \ - mock.patch.object(ds_permute_probe, "probe_wave", return_value=fake_probe), \ - mock.patch("builtins.open", side_effect=OSError("disk full")): - stdout, stderr = io.StringIO(), io.StringIO() - with mock.patch.object(sys, "stdout", stdout), mock.patch.object(sys, "stderr", stderr): - rc = ds_permute_probe.main(["--waves", "32", "--json", out_path]) - self.assertEqual(rc, 1) - self.assertIn("error:", stderr.getvalue()) - self.assertNotIn("Traceback", stderr.getvalue()) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/test_exe_checklist.py b/tests/test_exe_checklist.py deleted file mode 100644 index 48e58c888..000000000 --- a/tests/test_exe_checklist.py +++ /dev/null @@ -1,219 +0,0 @@ -"""tools/exe_checklist.py: the ASSUMPTION / UNVERIFIED / VERIFY notes, gathered for the executable's first look. - -The repository here is a small tree built in a temporary folder (one shim, one doc), so the counts are exact; the -last test runs the tool on this repository to make sure every note it finds has a file, a line and some text. -Standard library only; no game files. -""" -import contextlib -import io -import json -import os -from pathlib import Path -import sys -import tempfile -import unittest - -ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) -sys.path.insert(0, os.path.join(ROOT, "tools")) -import exe_checklist as ec # noqa: E402 - -SHIM = """// demo: a shim with two notes. -// -// ASSUMPTION: the quota is 1 GiB until the executable -// shows its own. -#include -constexpr GUID kDemoClass = {0x704c3f58, 0xe629, 0x4cc2, {0xb1, 0x97, 0x30, 0x51, 0x1b, 0x99, 0x6f, 0xe2}}; -constexpr size_t kSize = 18; // UNVERIFIED, see the header -// The SKU. UNVERIFIED: nothing -// compares it. -int f(); -""" -OTHER = """// no class here -// ASSUMPTION: a note in a file that serves no runtime class. -""" -DOC = """# Demo - -Some text. - -- **Names:** fine. -- **VERIFY:** the container names, from the - executable's calls. - -**ASSUMPTION:** a paragraph note -that spans two lines. - -- **Unverified:** the same note in the docs' prose spelling. -- **Assumption** — the term's definition, not a note. -- **Assumptions to confirm:** the plural spelling is a note too. -""" -SAVE_CLASS = "704c3f58-e629-4cc2-b197-30511b996fe2" - - -class ExeChecklist(unittest.TestCase): - def setUp(self): - self.tmp = tempfile.TemporaryDirectory() - self.root = self.tmp.name - os.makedirs(os.path.join(self.root, "runtime", "shims")) - os.makedirs(os.path.join(self.root, "docs")) - for rel, text in (("runtime/shims/demo.cpp", SHIM), ("runtime/shims/other.cpp", OTHER), ("docs/demo.md", DOC)): - with open(os.path.join(self.root, rel), "w", encoding="utf-8", newline="\n") as f: - f.write(text) - - def tearDown(self): - self.tmp.cleanup() - - def test_notes_start_at_their_marker_and_skip_trailing_comments(self): - notes = ec.collect(self.root) - demo = [n for n in notes if n["file"] == "runtime/shims/demo.cpp"] - self.assertEqual([(n["line"], n["kind"]) for n in demo], [(3, "ASSUMPTION"), (8, "UNVERIFIED")]) - self.assertEqual(demo[0]["text"], "the quota is 1 GiB until the executable shows its own.") - self.assertEqual(demo[1]["text"], "nothing compares it.") - self.assertEqual(demo[0]["classes"], [SAVE_CLASS]) - - def test_one_class_scan_per_file_with_several_notes(self): - many = "".join(f"// ASSUMPTION: note {i}\nint value;\n" for i in range(4)) - with open(os.path.join(self.root, "runtime/shims/many.cpp"), "w", encoding="utf-8", newline="\n") as f: - f.write(SHIM + many) - seen, real = [], ec.served_classes - - def counting(source): - seen.append(source) - return real(source) - - ec.served_classes = counting - try: - notes = [n for n in ec.collect(self.root) if n["file"] == "runtime/shims/many.cpp"] - finally: - ec.served_classes = real - self.assertEqual(len(seen), 3) # one scan per file with notes (demo.cpp, other.cpp, many.cpp) - self.assertEqual(sum(1 for s in seen if "note 0" in s), 1) # not once per note - self.assertEqual(len(notes), 6) # two in the header, four added - self.assertEqual({tuple(n["classes"]) for n in notes}, {(SAVE_CLASS,)}) - - def test_doc_notes_are_the_list_item_or_paragraph(self): - docs = [n for n in ec.collect(self.root) if n["file"] == "docs/demo.md"] - self.assertEqual([(n["line"], n["kind"]) for n in docs], - [(6, "VERIFY"), (9, "ASSUMPTION"), (12, "UNVERIFIED"), (14, "ASSUMPTION")]) - self.assertEqual(docs[0]["text"], "the container names, from the executable's calls.") - self.assertEqual(docs[1]["text"], "a paragraph note that spans two lines.") - self.assertEqual(docs[2]["text"], "the same note in the docs' prose spelling.") - self.assertEqual(docs[3]["text"], "the plural spelling is a note too.") - - def test_a_marker_inside_a_sentence_or_a_table_row_is_prose(self): - with open(os.path.join(self.root, "docs", "demo.md"), "a", encoding="utf-8", newline="\n") as f: - f.write("| `v_demo` | written without the console (**Assumption**: not a note) |\n" - "| **Unverified:** nothing | `v_other` |\n" - "\n" - "A sentence that carries an **Assumption:** after its start is not a note either.\n" - "\n" - "- **A list item** whose next sentence says **Unverified:** this is not a note of its own.\n") - docs = [n for n in ec.collect(self.root) if n["file"] == "docs/demo.md"] - self.assertEqual([(n["line"], n["kind"]) for n in docs], - [(6, "VERIFY"), (9, "ASSUMPTION"), (12, "UNVERIFIED"), (14, "ASSUMPTION")]) - - def test_called_notes_come_first(self): - report = os.path.join(self.root, "x.gdk_calls.json") - with open(report, "w", encoding="utf-8") as f: - json.dump({"images": [{"classes": [{"class_id": SAVE_CLASS.upper()}]}]}, f) - out = os.path.join(self.root, "checklist.md") - with contextlib.redirect_stdout(io.StringIO()): - self.assertEqual(ec.main(["--root", self.root, "--gdk-calls", report, "--out", out]), 0) - with open(out, "rb") as f: - raw = f.read() - self.assertNotIn(b"\r\n", raw) - lines = [l for l in raw.decode("utf-8").split("\n") if l.startswith("- [ ]")] - self.assertIn("demo.cpp:3` ASSUMPTION **called**", lines[0]) - self.assertIn("demo.cpp:8` UNVERIFIED **called**", lines[1]) - self.assertIn("other.cpp:2` ASSUMPTION:", lines[2]) # serves no class: no tag, after the called ones - self.assertEqual(len(lines), 7) - - def test_a_class_the_executable_does_not_call(self): - report = os.path.join(self.root, "y.json") - with open(report, "w", encoding="utf-8") as f: - json.dump({"classes": [{"class_id": "00000000-0000-0000-0000-000000000001"}]}, f) # one image, no "images" - text = ec.render(ec.collect(self.root), ec.called_classes([report])) - self.assertIn("demo.cpp:3` ASSUMPTION (not called)", text) - - def test_verify_notes_in_code_are_collected(self): - verify = "// pad demo.\n//\n// The pads (VERIFY: against the game).\n// VERIFY: the timeout is not honoured.\n" - with open(os.path.join(self.root, "runtime", "shims", "verify.cpp"), "w", encoding="utf-8", newline="\n") as f: - f.write(verify) - notes = [n for n in ec.collect(self.root) if n["file"] == "runtime/shims/verify.cpp"] - self.assertEqual([(n["line"], n["kind"]) for n in notes], [(3, "VERIFY"), (4, "VERIFY")]) - self.assertEqual(notes[0]["text"], "against the game).") - self.assertEqual(notes[1]["text"], "the timeout is not honoured.") - - def test_a_root_that_is_not_a_directory_is_exit_2(self): - stderr = io.StringIO() - with contextlib.redirect_stderr(stderr), contextlib.redirect_stdout(io.StringIO()): - self.assertEqual(ec.main(["--root", os.path.join(self.root, "no_such")]), 2) - self.assertIn("not a directory", stderr.getvalue()) - - def test_an_out_that_is_a_directory_is_exit_2(self): - stderr = io.StringIO() - with contextlib.redirect_stderr(stderr), contextlib.redirect_stdout(io.StringIO()): - self.assertEqual(ec.main(["--root", self.root, "--out", os.path.join(self.root, "docs")]), 2) - self.assertIn("is a directory", stderr.getvalue()) - - def test_an_unreadable_report_is_exit_1(self): - stderr = io.StringIO() - with contextlib.redirect_stderr(stderr): - self.assertEqual(ec.main(["--root", self.root, "--gdk-calls", os.path.join(self.root, "missing.json")]), 1) - self.assertIn("cannot read", stderr.getvalue()) - - def assert_report_output_rejected(self, reports, output): - original = [report.read_bytes() for report in reports] - args = ["--root", self.root, "--out", str(output)] - for report in reports: - args.extend(["--gdk-calls", str(report)]) - stderr = io.StringIO() - with contextlib.redirect_stderr(stderr), contextlib.redirect_stdout(io.StringIO()): - with self.assertRaises(SystemExit) as raised: - ec.main(args) - self.assertEqual(raised.exception.code, 2) - self.assertIn("would overwrite", stderr.getvalue()) - self.assertEqual([report.read_bytes() for report in reports], original) - - def test_an_out_that_cannot_be_written_is_exit_1(self): - # --out under a folder that does not exist was a FileNotFoundError traceback. - out = os.path.join(self.root, "missing_dir", "notes.md") - stderr = io.StringIO() - with contextlib.redirect_stderr(stderr), contextlib.redirect_stdout(io.StringIO()): - self.assertEqual(ec.main(["--root", self.root, "--out", out]), 1) - self.assertIn("cannot write the checklist", stderr.getvalue()) - - def test_out_cannot_overwrite_any_input_report(self): - first = Path(self.root, "first.json") - second = Path(self.root, "second.json") - first.write_bytes(b'{"classes": []}') - second.write_bytes(b'{"images": []}') - self.assert_report_output_rejected([first, second], second) - - def test_out_cannot_overwrite_a_hard_link_to_an_input_report(self): - report = Path(self.root, "report.json") - alias = Path(self.root, "output.md") - report.write_bytes(b'{"classes": []}') - try: - os.link(report, alias) - except (OSError, NotImplementedError) as err: - self.skipTest(f"hard links unavailable: {err}") - self.assert_report_output_rejected([report], alias) - - def test_this_repository(self): - notes = ec.collect(ROOT) - self.assertTrue(notes) - for n in notes: - self.assertTrue(n["text"].strip(), n) - self.assertGreater(n["line"], 0) - # the store shim's remaining unverified sizes (SKU_ID_SIZE, trial-id bound) are on the list - self.assertTrue(any(n["file"] == "runtime/shims/xgameruntime_store.cpp" and "SKU_ID_SIZE" in n["text"] - for n in notes)) - self.assertTrue(any(n["file"] == "docs/runtime_imports.md" and n["kind"] == "UNVERIFIED" for n in notes)) - # d3d12_vulkan.md's console assumptions carry the page-wide uppercase marker, so the first look lists them - self.assertTrue(any(n["file"] == "docs/d3d12_vulkan.md" and n["kind"] == "ASSUMPTION" for n in notes)) - # so does modding.md's note on the three settings only the executable can confirm - self.assertTrue(any(n["file"] == "docs/modding.md" and n["kind"] == "ASSUMPTION" for n in notes)) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/test_f16_hw_words.py b/tests/test_f16_hw_words.py deleted file mode 100644 index 59cfb6b0e..000000000 --- a/tests/test_f16_hw_words.py +++ /dev/null @@ -1,209 +0,0 @@ -"""The ps_f16_* GPU test shaders: expected words measured on RDNA2 hardware, checked here without a GPU. - -HARDWARE holds, per shader, the four mrt0 words an AMD RX 6800 (gfx1030) returned when the shader's instructions -ran as a raw compute kernel (registers renamed, nothing else changed), in wave32 and in wave64, with IEEE mode off, -DX10 clamp on, denormals preserved and round to nearest even. They are not derived from the translator. - -Three things are checked for every shader: - * the words in the .asm header, in check.py and in scripts/run_gpu_tests.py are those hardware words; - * a plain-Python reference written from the rule in docs/design.md ("16-bit results") gives the same words; - * the translator's SPIR-V, run by tests/spirv_interp.py, gives the same words. -""" -import os -import re -import struct -import sys - -import pytest - -import rdna2spirv -import spirv_interp as si -from listing import EMPTY_DXBC, translate_listing - -ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) -SHADER_DIR = os.path.join(ROOT, "runtime", "test", "shaders") -sys.path.insert(0, SHADER_DIR) -import check # noqa: E402 (path set above) - -HARDWARE = { - "ps_f16_med3_opsel": (0xAAAA4100, 0xAAAA4200, 0xAAAA3E00, 0x40005555), - "ps_f16_med3_mods": (0x41005555, 0x3C005555, 0x41003800, 0xAAAABA00), - "ps_f16_vop2": (0xAAAA4000, 0xAAAAC000, 0xAAAA3A00, 0x42003F00), - "ps_f16_vop2b": (0xAAAA3E00, 0xAAAAB800, 0xAAAA3C00, 0x42003400), - "ps_f16_vop1": (0xAAAA4000, 0xAAAABC00, 0xAAAAC000, 0xAAAA8000), - "ps_f16_vop1b": (0xAAAA3400, 0xAAAA4000, 0xAAAAB400, 0xAAAA3800), - "ps_f16_const": (0xAAAA3D00, 0x38005555, 0xAAAA3800, 0x3F000000), - "ps_f16_const2": (0x42003D00, 0x3D004200, 0xAAAABC00, 3), - "ps_f16_pack": (0x34003C00, 0x38003400, 0x34000000, 0x44004200), - # neg/abs on the selected half: a sign flip / clear before packing (SHADER-260; the rule was measured on - # gfx1036 and these words follow it, they are not a direct readback of this shader) - "ps_f16_pack_mods": (0x4400B400, 0xC4003400, 0x4400C200, 0xB400B400), -} -OLD = 0xAAAA5555 - - -def h(x): - """f16 bits of x; every value used here is exact in f16.""" - b = struct.unpack("> 16) - - -def to_lo(old, x): - """Partial write: x into the low half, the high half of the destination kept.""" - return old & 0xFFFF0000 | h(x) - - -def to_hi(old, x): - """op_sel destination bit: x into the high half, the low half kept.""" - return h(x) << 16 | old & 0xFFFF - - -def med(a, b, c): - return sorted((a, b, c))[1] - - -def clamp(x): - return min(max(x, 0.0), 1.0) - - -def ref_med3_opsel(): - v0, v1, v2 = 0x41003C00, 0x48004000, 0x3E004200 - return (to_lo(OLD, med(hi(v0), lo(v1), lo(v2))), to_lo(OLD, med(lo(v0), hi(v1), lo(v2))), - to_lo(OLD, med(lo(v0), lo(v1), hi(v2))), to_hi(OLD, med(lo(v0), lo(v1), lo(v2)))) - - -def ref_med3_mods(): - v0, v1, v2 = 0xC1003800, 0xC8004000, 0x3A003C00 - return (to_hi(OLD, med(-hi(v0), abs(hi(v1)), lo(v2))), - to_hi(OLD, clamp(med(abs(hi(v0)), abs(hi(v1)), hi(v2)))), - to_hi(v0, med(-hi(v0), lo(v1), abs(hi(v1)))), # the destination is a copy of v0 - to_lo(OLD, med(lo(v0), hi(v1), -abs(hi(v2))))) - - -def ref_vop2(): - v0, v1, acc = 0x44003E00, 0x40003800, 0x42003C00 - return (to_lo(OLD, lo(v0) + lo(v1)), to_lo(OLD, -lo(v0) - abs(lo(v1))), to_lo(OLD, lo(v0) * lo(v1)), - to_lo(acc, lo(v0) * lo(v1) + lo(acc))) - - -def ref_vop2b(): - v0, v1, acc = 0x44003E00, 0x40003800, 0x42003C00 - return (to_lo(OLD, max(lo(v0), lo(v1))), to_lo(OLD, min(lo(v0), -lo(v1))), to_lo(OLD, clamp(lo(v0) + lo(v1))), - to_lo(acc, -lo(v0) * abs(lo(v1)) + lo(acc))) - - -def ref_vop1(): - v0, v1 = 0xBE004100, 0x4300BA00 - assert (lo(v0), lo(v1)) == (2.5, -0.75) - # 2.5 -> 2 (even) floor(-0.75) ceil(-2.5) trunc(-0.75) = -0.0 - return to_lo(OLD, 2.0), to_lo(OLD, -1.0), to_lo(OLD, -2.0), OLD & 0xFFFF0000 | 0x8000 - - -def ref_vop1b(): - v0, v1 = 0x34004400, 0x3E00C180 - assert (lo(v0), lo(v1)) == (4.0, -2.75) - return to_lo(OLD, lo(v1) - (-3.0)), to_lo(OLD, lo(v0) ** 0.5), to_lo(OLD, 1 / -lo(v0)), to_lo(OLD, lo(v0) ** -0.5) - - -def const(x): - """An inline float constant in an f16 op: the f16 value in the low half, zero in the high half.""" - return h(x) - - -def ref_const(): - v0 = 0x42003400 - return (to_lo(OLD, lo(const(1.0)) + lo(v0)), to_hi(OLD, med(hi(v0), lo(const(-4.0)), lo(const(0.5)))), - to_lo(OLD, lo(v0) * lo(const(2.0)) + hi(const(0.5))), - struct.unpack("> 16, (v1 & w) << 16 | v0 >> 16) - - -def ref_pack_mods(): - # -v / |v| on the selected half: NEG flips bit 15, ABS clears it, ABS first. - v0, v1, w = 0x42003400, 0x34004400, 0xFFFF - lo0, hi0, lo1, hi1 = v0 & w, v0 >> 16, v1 & w, v1 >> 16 - return (lo0 ^ 0x8000 | (lo1 & 0x7FFF) << 16, lo0 | (lo1 ^ 0x8000) << 16, - hi0 ^ 0x8000 | lo1 << 16, lo0 ^ 0x8000 | (hi1 ^ 0x8000) << 16) - - -REFERENCE = {"ps_f16_med3_opsel": ref_med3_opsel, "ps_f16_med3_mods": ref_med3_mods, "ps_f16_vop2": ref_vop2, - "ps_f16_vop2b": ref_vop2b, "ps_f16_vop1": ref_vop1, "ps_f16_vop1b": ref_vop1b, - "ps_f16_const": ref_const, "ps_f16_const2": ref_const2, "ps_f16_pack": ref_pack, - "ps_f16_pack_mods": ref_pack_mods} -NAMES = sorted(HARDWARE) - - -def source(name): - with open(os.path.join(SHADER_DIR, name + ".asm"), encoding="utf-8") as f: - return f.read() - - -def translated_words(tmp_path, name): - """The four words the translated shader writes to mrt0, per tests/spirv_interp.py.""" - insns = [ln.strip() for ln in source(name).splitlines() if ln.strip() and not ln.startswith(";")] - (tmp_path / "disasm").mkdir(exist_ok=True) - (tmp_path / f"{name}.dxbc").write_bytes(EMPTY_DXBC) - path = tmp_path / "disasm" / f"{name}.s" - path.write_text(f"; {name} code 0x0..0x100\n" + "".join("\t" + ln + "\n" for ln in insns)) - out = si.run(rdna2spirv.translate(str(path))).outputs["out_mrt0"] - return tuple(si.f2u(x) for x in out) - - -def test_every_f16_shader_is_listed(): - # ps_f16_fnan_* are the NaN-operand med3 shaders, with their own words and test (tests/semantic/test_float_nan_fract.py) - on_disk = sorted(f[:-4] for f in os.listdir(SHADER_DIR) - if f.startswith("ps_f16_") and f.endswith(".asm") and not f.startswith("ps_f16_fnan_")) - assert on_disk == NAMES == sorted(REFERENCE) - - -@pytest.mark.parametrize("name", NAMES) -def test_header_and_checkers_hold_the_hardware_words(name): - header = re.search(r"^; Expected mrt0 bits: (.*)$", source(name), re.M).group(1) - assert tuple(int(x, 0) for x in header.split(",")) == HARDWARE[name] - assert check.PIXEL_BITS[name] == HARDWARE[name] - with open(os.path.join(ROOT, "scripts", "run_gpu_tests.py"), encoding="utf-8") as f: - m = re.search(rf'"{name}": \(([^)]*)\)', f.read()) - assert m and tuple(int(x, 0) for x in m.group(1).split(",")) == HARDWARE[name] - - -@pytest.mark.parametrize("name", NAMES) -def test_rule_reference_gives_the_hardware_words(name): - assert tuple(f"{w:#010x}" for w in REFERENCE[name]()) == tuple(f"{w:#010x}" for w in HARDWARE[name]) - - -@pytest.mark.parametrize("name", NAMES) -def test_translator_gives_the_hardware_words(name, tmp_path): - got = translated_words(tmp_path, name) - assert tuple(f"{w:#010x}" for w in got) == tuple(f"{w:#010x}" for w in HARDWARE[name]) - - -# 0x3118 for 0.15915494 (1 / 2pi) is also what the hardware gave for v_max_f16 d, 0.15915494, v with v.lo = -4.0. -@pytest.mark.parametrize("text,bits", [("0.5", 0x3800), ("1.0", 0x3C00), ("2.0", 0x4000), ("4.0", 0x4400), - ("-0.5", 0xB800), ("-1.0", 0xBC00), ("-2.0", 0xC000), ("-4.0", 0xC400), - ("0.15915494", 0x3118)]) -def test_inline_float_constant_is_an_f16_value(text, bits, tmp_path): - """Every float constant the assembler prints for an f16 operand, read through a v_max_f16 that keeps it.""" - asm = f"v_mov_b32 v1, 0xfc00fc00\nv_mov_b32 v3, {OLD:#x}\nv_max_f16 v3, {text}, v1" # max(c, -inf) = c - assert si.run(translate_listing(tmp_path, asm)).vgpr[3] == OLD & 0xFFFF0000 | bits diff --git a/tests/test_f16_op_sel.py b/tests/test_f16_op_sel.py deleted file mode 100644 index 64041e7e7..000000000 --- a/tests/test_f16_op_sel.py +++ /dev/null @@ -1,101 +0,0 @@ -"""op_sel on f16 VOP3 ops in tools/rdna2spirv.py. - -These tests feed the translator hand-written ``.s`` listings, so they need neither llvm-mc nor spirv-tools and run -everywhere. They check the shape of the generated SPIR-V (which half is read, where the result goes), not computed -values; values are covered on a GPU by runtime/test/vk_harness. - -Semantics (Mesa ACO ``can_use_opsel`` / AMD RDNA2 ISA, VOP3 ``op_sel``): bit i < nsrc selects the high half of source i, -bit nsrc selects the high half of the destination. The half of the destination that is not written is kept. -""" -import re - -import pytest - -import rdna2spirv -from listing import translate_listing - -# Result register v3 is initialised first: an f16 write keeps the other half, so it reads the old value, and the -# translator rejects pixel shaders that read v0/v1 before writing them. -PROLOGUE = "v_mov_b32 v3, 0x12345678\nv_mov_b32 v1, 0x3c004000" - - -def translate(tmp_path, instruction): - return translate_listing(tmp_path, PROLOGUE + "\n" + instruction) - - -def high_extracts(spv): - """Number of UnpackHalf2x16 results read at component 1 (the high half).""" - return len(re.findall(r"OpCompositeExtract %float %\w+ 1$", spv, re.M)) - - -def low_extracts(spv): - return len(re.findall(r"OpCompositeExtract %float %\w+ 0$", spv, re.M)) - - -def left_shifts(spv): - return spv.count("OpShiftLeftLogical %uint") - - -# (id, instruction without modifiers, number of sources) -OPS = [ - ("v_fma_f16", "v_fma_f16 v3, v1, v1, v1", 3), - ("v_med3_f16", "v_med3_f16 v3, v1, v1, v1", 3), - ("v_min3_f16", "v_min3_f16 v3, v1, v1, v1", 3), - ("v_max3_f16", "v_max3_f16 v3, v1, v1, v1", 3), - ("v_add_f16", "v_add_f16_e64 v3, v1, v1", 2), - ("v_sub_f16", "v_sub_f16_e64 v3, v1, v1", 2), - ("v_subrev_f16", "v_subrev_f16_e64 v3, v1, v1", 2), - ("v_mul_f16", "v_mul_f16_e64 v3, v1, v1", 2), - ("v_max_f16", "v_max_f16_e64 v3, v1, v1", 2), - ("v_min_f16", "v_min_f16_e64 v3, v1, v1", 2), - ("v_sqrt_f16", "v_sqrt_f16_e64 v3, v1", 1), - ("v_rcp_f16", "v_rcp_f16_e64 v3, v1", 1), -] - - -@pytest.mark.parametrize("name,asm,nsrc", OPS, ids=[o[0] for o in OPS]) -def test_default_reads_low_halves_and_writes_low_half(name, asm, nsrc, tmp_path): - spv = translate(tmp_path, asm) - assert high_extracts(spv) == 0 - assert low_extracts(spv) == nsrc - - -@pytest.mark.parametrize("name,asm,nsrc", OPS, ids=[o[0] for o in OPS]) -def test_source_select_reads_high_half(name, asm, nsrc, tmp_path): - base = translate(tmp_path, asm) - for i in range(nsrc): - bits = [1 if j == i else 0 for j in range(nsrc + 1)] - spv = translate(tmp_path, f"{asm} op_sel:[{','.join(map(str, bits))}]") - assert high_extracts(spv) == 1, f"source {i}" - assert low_extracts(spv) == nsrc - 1, f"source {i}" - assert left_shifts(spv) == left_shifts(base) # destination is still the low half - - -@pytest.mark.parametrize("name,asm,nsrc", OPS, ids=[o[0] for o in OPS]) -def test_destination_select_writes_high_half(name, asm, nsrc, tmp_path): - base = translate(tmp_path, asm) - bits = [0] * nsrc + [1] - spv = translate(tmp_path, f"{asm} op_sel:[{','.join(map(str, bits))}]") - assert high_extracts(spv) == 0 - assert left_shifts(spv) == left_shifts(base) + 1 # result << 16, low half of the old value kept - - -def test_all_bits_set(tmp_path): - spv = translate(tmp_path, "v_fma_f16 v3, v1, v1, v1 op_sel:[1,1,1,1]") - assert high_extracts(spv) == 3 - assert low_extracts(spv) == 0 - - -def test_op_sel_with_neg_and_clamp_still_translates(tmp_path): - spv = translate(tmp_path, "v_fma_f16 v3, -v1, |v1|, v1 op_sel:[1,0,1,1] clamp") - assert high_extracts(spv) == 2 - - -def test_translation_is_deterministic(tmp_path): - asm = "v_med3_f16 v3, v1, v1, v1 op_sel:[1,0,1,1]" - assert translate(tmp_path, asm) == translate(tmp_path, asm) - - -def test_other_unsupported_instructions_are_still_rejected(tmp_path): - with pytest.raises(rdna2spirv.Unsupported): - translate(tmp_path, "v_sat_pk_u8_i16 v3, v1") diff --git a/tests/test_f16_op_sel_values.py b/tests/test_f16_op_sel_values.py deleted file mode 100644 index d1ae359db..000000000 --- a/tests/test_f16_op_sel_values.py +++ /dev/null @@ -1,84 +0,0 @@ -"""Computed values for op_sel on f16 VOP3 ops, checked with the SPIR-V interpreter in tests/spirv_interp.py. - -The reference is plain Python: pick the selected half of each source, compute in double precision, round to f16 -(round to nearest even), and merge into the destination keeping the half that is not written. Inputs are chosen so -every intermediate is exact, which makes the translator's f32 detour and the reference's single rounding agree. -""" -import itertools - -import pytest - -import spirv_interp as si -from listing import translate_listing - -SRC = {1: 0x44003E00, 2: 0x40003800, 4: 0x3400BC00} # v1: 1.5|4.0 v2: 0.5|2.0 v4: -1.0|0.25 (lo|hi) -OLD = 0xAAAA5555 - - -def median(a, b, c): - return sorted((a, b, c))[1] - - -# name -> (asm with {s} operand slots, number of sources, reference on floats) -OPS = { - "v_add_f16": ("v_add_f16_e64 v3, {0}, {1}", 2, lambda a, b: a + b), - "v_sub_f16": ("v_sub_f16_e64 v3, {0}, {1}", 2, lambda a, b: a - b), - "v_subrev_f16": ("v_subrev_f16_e64 v3, {0}, {1}", 2, lambda a, b: b - a), - "v_mul_f16": ("v_mul_f16_e64 v3, {0}, {1}", 2, lambda a, b: a * b), - "v_max_f16": ("v_max_f16_e64 v3, {0}, {1}", 2, max), - "v_min_f16": ("v_min_f16_e64 v3, {0}, {1}", 2, min), - "v_fma_f16": ("v_fma_f16 v3, {0}, {1}, {2}", 3, lambda a, b, c: a * b + c), - "v_med3_f16": ("v_med3_f16 v3, {0}, {1}, {2}", 3, median), - "v_min3_f16": ("v_min3_f16 v3, {0}, {1}, {2}", 3, min), - "v_max3_f16": ("v_max3_f16 v3, {0}, {1}, {2}", 3, max), - "v_sqrt_f16": ("v_sqrt_f16_e64 v3, {0}", 1, lambda a: a ** 0.5), - "v_rcp_f16": ("v_rcp_f16_e64 v3, {0}", 1, lambda a: 1 / a), -} -REGS = ["v1", "v2", "v4"] - - -def half(reg_value, hi): - return si.half_to_float(reg_value >> 16 if hi else reg_value) - - -def expected(fn, nsrc, sel, dst_hi, regs=(1, 2, 4)): - vals = [half(SRC[regs[i]], sel[i]) for i in range(nsrc)] - h = si.float_to_half(fn(*vals)) - return (h << 16 | OLD & 0xFFFF) if dst_hi else (OLD & 0xFFFF0000 | h) - - -def execute(tmp_path, asm): - prologue = "".join(f"v_mov_b32 v{r}, {v:#x}\n" for r, v in SRC.items()) + f"v_mov_b32 v3, {OLD:#x}\n" - return si.run(translate_listing(tmp_path, prologue + asm)).vgpr[3] - - -CASES = [(name, bits) for name, (_, n, _) in OPS.items() for bits in itertools.product((0, 1), repeat=n + 1)] - - -@pytest.mark.parametrize("name,bits", CASES, ids=[f"{n}-{''.join(map(str, b))}" for n, b in CASES]) -def test_op_sel_value(name, bits, tmp_path): - template, nsrc, fn = OPS[name] - asm = template.format(*REGS) + f" op_sel:[{','.join(map(str, bits))}]" - assert execute(tmp_path, asm) == expected(fn, nsrc, bits[:nsrc], bits[nsrc]), asm - - -def test_neg_applies_to_the_selected_half(tmp_path): - got = execute(tmp_path, "v_add_f16_e64 v3, -v1, v2 op_sel:[1,0,0]") - assert got == OLD & 0xFFFF0000 | si.float_to_half(-4.0 + 0.5) - - -def test_abs_applies_to_the_selected_half(tmp_path): - got = execute(tmp_path, "v_add_f16_e64 v3, |v4|, v2 op_sel:[0,1,0]") - assert got == OLD & 0xFFFF0000 | si.float_to_half(1.0 + 2.0) - - -def test_clamp_with_destination_high(tmp_path): - got = execute(tmp_path, "v_add_f16_e64 v3, v1, v2 op_sel:[0,0,1] clamp") # 1.5 + 0.5 = 2.0 -> clamped to 1.0 - assert got == si.float_to_half(1.0) << 16 | OLD & 0xFFFF - - -def test_fmac_destination_is_the_accumulator(tmp_path): - # v_fmac_f16 v3, v1, v2: v3.lo = v1.lo * v2.lo + v3.lo, high half kept - prologue = f"v_mov_b32 v1, {SRC[1]:#x}\nv_mov_b32 v2, {SRC[2]:#x}\nv_mov_b32 v3, 0xaaaa3c00\n" # accumulator 1.0 - got = si.run(translate_listing(tmp_path, prologue + "v_fmac_f16_e32 v3, v1, v2")).vgpr[3] - assert got == 0xAAAA0000 | si.float_to_half(1.5 * 0.5 + 1.0) diff --git a/tests/test_f16_trans_sweep.py b/tests/test_f16_trans_sweep.py deleted file mode 100644 index 8c8db6ee9..000000000 --- a/tests/test_f16_trans_sweep.py +++ /dev/null @@ -1,273 +0,0 @@ -"""tools/f16_trans_sweep.py: the f16 reference and its rounding, which input each kernel thread computes and where it -stores it, the classification, and the exit-77 contract. The last test runs on the hardware when the oracle tools -are present and is skipped otherwise. Standard library only.""" -import io -import json -import os -from contextlib import redirect_stderr, redirect_stdout -from decimal import Decimal -from pathlib import Path -import shutil -import subprocess -import sys -import tempfile -import unittest -from unittest import mock - -TOOLS = Path(__file__).resolve().parents[1] / "tools" -sys.path.insert(0, str(TOOLS)) -import f16_trans_sweep as sw # noqa: E402 -from hw_oracle import asm, runner # noqa: E402 - - -class Reference(unittest.TestCase): - def test_self_test(self): - self.assertEqual(sw.self_test(), 0) - - def test_rounding_to_f16(self): - self.assertEqual(sw.from_dec(Decimal(1) + Decimal(2) ** -11), 0x3C00) # tie: to even - self.assertEqual(sw.from_dec(Decimal(1) + Decimal(2) ** -11 * 3), 0x3C02) # tie: to even - self.assertEqual(sw.from_dec(Decimal(1) + Decimal(2) ** -11 + Decimal(2) ** -40), 0x3C01) - self.assertEqual(sw.from_dec(-(Decimal(1) + Decimal(2) ** -10 * Decimal("0.99")), rtz=True), 0xBC00) - self.assertEqual(sw.from_dec(Decimal(2) ** -14 - Decimal(2) ** -25), 0x0400) # rounds up to normal - self.assertEqual(sw.from_dec(Decimal(-70000)), 0xFC00) - self.assertEqual(sw.from_dec(Decimal(-70000), rtz=True), 0xFBFF) - - def test_undefined_inputs_are_the_ones_spirv_leaves_undefined(self): - undef = {op: [h for h, r in enumerate(sw.reference(op)) if r is None] for op in ("v_rcp_f16", "v_sqrt_f16")} - self.assertEqual(undef["v_rcp_f16"], [0x0000, 0x8000]) - self.assertEqual(len(undef["v_sqrt_f16"]), 31744) # every negative but -0, -inf included - self.assertNotIn(0x8000, undef["v_sqrt_f16"]) - self.assertIn(0xFC00, undef["v_sqrt_f16"]) - self.assertEqual(sw.exact("v_log_f16", 0x8000), "undef") - self.assertEqual(sw.exact("v_rsq_f16", 0x0000), "undef") - self.assertEqual(sw.exact("v_exp_f16", 0x7E00), "nan") - - def test_the_sine_reduces_in_turns_and_the_f32_product_does_not(self): - # x = 1000.5: sin(2 pi x) = sin(pi) = 0, but 6.2831855 * x in f32 is 6286.3726, about 1.6e-3 rad off - h = 0x63D1 - self.assertEqual(float(sw.to_dec(h)), 1000.5) - self.assertEqual(sw.to_bits(sw.exact("v_sin_f16", h)), 0) - self.assertNotEqual(sw.to_bits(sw.product_turns("v_sin_f16", h)), 0) - - -class Kernels(unittest.TestCase): - def test_every_input_is_computed_once_and_stored_at_its_own_half(self): - seen = {} - for j in range(65536 // sw.PER_KERNEL): - base = j * sw.PER_KERNEL - lines = sw.kernel_lines("v_exp_f16", base) - self.assertEqual(lines[1], f"v_add_nc_u32 v1, 0x{base:x}, v1") - for t in range(sw.THREADS): - for k in range(sw.PER_THREAD): - word = base // 2 + 4 * t + k // 2 # global_store_b128 at 16 * t, v8 + k // 2 - seen[word * 2 + k % 2] = base + 8 * t + k - self.assertEqual(sorted(seen), list(range(65536))) - self.assertTrue(all(seen[i] == i for i in seen)) - - def test_kernels_assemble_for_rdna2(self): - try: - clang = runner.find_clang() - except runner.Unavailable as e: - self.skipTest(str(e)) - kernels = [asm.Kernel(sw.kernel_lines(op, 0, "gfx1030"), w, sw.THREADS, sw.PER_KERNEL // 2, raw=True, - mode=sw.MODES["keep16"]) for op in sw.OPS for w in (32,)] - text, names, _ = asm.module_text(kernels, "gfx1030", wave=32) - with tempfile.TemporaryDirectory() as d: - s = Path(d) / "k.s" - s.write_text(text, encoding="utf-8") - r = subprocess.run([clang, "--target=amdgcn-amd-amdhsa", "-mcpu=gfx1030", "-c", str(s), "-o", - str(Path(d) / "k.o")], capture_output=True, text=True) - self.assertEqual(r.returncode, 0, r.stderr[:800]) - self.assertEqual(len(names), len(sw.OPS)) - self.assertIn(".amdhsa_float_denorm_mode_16_64 3", text) - self.assertIn("global_store_dwordx4 v24, v[8:11], s[2:3]", text) - - -class Classify(unittest.TestCase): - def setUp(self): - self.ref = sw.reference("v_rcp_f16") - - def test_the_rule_itself_is_all_exact(self): - hw = [r if r is not None else 0x7E00 for r in self.ref] - c, worst = sw.classify("v_rcp_f16", hw, self.ref) - self.assertEqual(c["exact"] + c["nan_ok"] + c["undefined"], 65536) - self.assertEqual(c["undefined"], 2) - self.assertEqual(worst, []) - - def test_each_kind_of_difference_is_counted_apart(self): - hw = [r if r is not None else 0 for r in self.ref] - hw[0x0000], hw[0x8000] = 0x7C00, 0xFC00 # undefined in the rule: the hardware's +-inf - hw[0x3C00] = 0x3C01 # rcp(1) off by 1 ulp - hw[0x4000] = 0x3802 # rcp(2) off by 2 ulp - hw[0x03FF] = 0x7C00 # rcp(largest denormal) as the hardware's rcp(+0) - hw[0x7BFF] = 0x0000 # rcp(65504) = 2^-16 * (1 + ...) is a denormal, flushed - hw[0x7E00] = 0x3C00 # NaN in, a number out - hw[0x7D00] = 0x7F00 # a signalling NaN quieted - hw[0x7C01] = 0x7C01 # a signalling NaN passed through - c, worst = sw.classify("v_rcp_f16", hw, self.ref) - self.assertTrue(sw.is_denorm(self.ref[0x7BFF])) - self.assertEqual((c["ulp1"], c["ulp_more"], c["max_ulp"]), (1, 1, 2)) - self.assertEqual((c["denorm_in_as_zero"], c["denorm_out_flushed"], c["other"]), (1, 1, 1)) - self.assertEqual((c["snan_quieted"], c["snan_kept"], c["snan_other"]), (1, 1, 1020)) - self.assertEqual({w[0] for w in worst}, {0x4000, 0x7E00}) - - -class Cli(unittest.TestCase): - def test_exits_77_without_the_tools(self): - env = dict(os.environ, LEONIDA_AMD_CLANG=str(TOOLS / "no-such-clang.exe"), LEONIDA_HW_DRM_NODE="") - r = subprocess.run([sys.executable, "-I", str(TOOLS / "f16_trans_sweep.py"), "--ops", "v_exp_f16"], - capture_output=True, text=True, env=env) - self.assertEqual(r.returncode, 77, r.stdout + r.stderr) - self.assertIn("unavailable", r.stdout) - - def test_unknown_names_are_a_usage_error(self): - r = subprocess.run([sys.executable, "-I", str(TOOLS / "f16_trans_sweep.py"), "--ops", "v_exp_f32"], - capture_output=True, text=True) - self.assertEqual(r.returncode, 2) - self.assertIn("v_exp_f32", r.stderr) - - def test_empty_and_malformed_selections_fail_before_opening_oracle(self): - cases = [ - (["--ops", ""], "--ops"), - (["--modes", ","], "--modes"), - (["--waves", ""], "--waves"), - (["--waves", "32,nope"], "--waves"), - (["--waves", "16"], "16"), - ] - for argv, message in cases: - with self.subTest(argv=argv), mock.patch.object(runner, "open_oracle") as open_oracle: - error = io.StringIO() - with self.assertRaises(SystemExit) as raised, redirect_stderr(error): - sw.main(argv) - self.assertEqual(raised.exception.code, 2) - self.assertIn(message, error.getvalue()) - open_oracle.assert_not_called() - - def test_json_empty_string_exits_1_before_opening_oracle(self): - err = io.StringIO() - with mock.patch.object(runner, "open_oracle") as open_oracle, redirect_stderr(err): - rc = sw.main(["--ops", "v_exp_f16", "--modes", "keep16", "--waves", "32", "--json", ""]) - self.assertEqual(rc, 1) - self.assertIn("error:", err.getvalue()) - open_oracle.assert_not_called() - - def test_json_existing_directory_exits_1_before_sweep_or_probe(self): - with tempfile.TemporaryDirectory() as d: - err = io.StringIO() - with mock.patch.object(runner, "open_oracle") as open_oracle, redirect_stderr(err): - rc = sw.main(["--ops", "v_exp_f16", "--modes", "keep16", "--waves", "32", "--json", d]) - self.assertEqual(rc, 1) - self.assertIn("error:", err.getvalue()) - open_oracle.assert_not_called() - - env = dict(os.environ, LEONIDA_AMD_CLANG=str(TOOLS / "no-such-clang.exe"), LEONIDA_HW_DRM_NODE="") - r = subprocess.run([sys.executable, "-I", str(TOOLS / "f16_trans_sweep.py"), - "--ops", "v_exp_f16", "--json", d], - capture_output=True, text=True, env=env) - self.assertEqual(r.returncode, 1, r.stdout + r.stderr) - self.assertIn("error:", r.stderr) - - def test_json_creates_nested_parent_and_writes_lf_endings(self): - ref = [0] * 65536 - fake_oracle = mock.MagicMock(device="fake-gpu", arch="gfx1030") - with tempfile.TemporaryDirectory() as d: - out_path = Path(d) / "nested" / "deep" / "report.json" - self.assertFalse(out_path.parent.exists()) - out = io.StringIO() - err = io.StringIO() - with mock.patch.object(runner, "open_oracle", return_value=fake_oracle), \ - mock.patch.object(sw, "check_modes"), \ - mock.patch.object(sw, "reference", return_value=ref), \ - mock.patch.object(sw, "sweep", return_value=list(ref)), \ - redirect_stdout(out), redirect_stderr(err): - rc = sw.main(["--ops", "v_exp_f16", "--modes", "keep16", "--waves", "32", "--json", str(out_path)]) - self.assertEqual(rc, 0, err.getvalue()) - self.assertEqual(err.getvalue(), "") - self.assertTrue(out_path.is_file()) - raw = out_path.read_bytes() - self.assertIn(b"\n", raw) - self.assertNotIn(b"\r\n", raw) - data = json.loads(raw.decode("utf-8")) - self.assertEqual(data["device"], "fake-gpu") - self.assertEqual(data["arch"], "gfx1030") - self.assertIn("keep16", data["ops"]["v_exp_f16"]) - fake_oracle.close.assert_called_once() - - def test_json_blocked_by_regular_file_parent_exits_1(self): - with tempfile.TemporaryDirectory() as d: - blocker = Path(d) / "blocker" - blocker.write_text("not a dir\n", encoding="utf-8", newline="\n") - for target in (blocker / "report.json", blocker / "sub" / "report.json"): - err = io.StringIO() - with mock.patch.object(runner, "open_oracle") as open_oracle, redirect_stderr(err): - rc = sw.main(["--ops", "v_exp_f16", "--modes", "keep16", "--waves", "32", "--json", str(target)]) - self.assertEqual(rc, 1) - self.assertIn("error:", err.getvalue()) - open_oracle.assert_not_called() - - env = dict(os.environ, LEONIDA_AMD_CLANG=str(TOOLS / "no-such-clang.exe"), LEONIDA_HW_DRM_NODE="") - r = subprocess.run([sys.executable, "-I", str(TOOLS / "f16_trans_sweep.py"), - "--ops", "v_exp_f16", "--json", str(blocker / "sub" / "report.json")], - capture_output=True, text=True, env=env) - self.assertEqual(r.returncode, 1, r.stdout + r.stderr) - self.assertIn("error:", r.stderr) - - def test_json_write_oserror_reports_cleanly_and_exits_1(self): - ref = [0] * 65536 - fake_oracle = mock.MagicMock(device="fake-gpu", arch="gfx1030") - with tempfile.TemporaryDirectory() as d: - out_path = Path(d) / "nested" / "report.json" - with mock.patch.object(runner, "open_oracle", return_value=fake_oracle), \ - mock.patch.object(sw, "check_modes"), \ - mock.patch.object(sw, "reference", return_value=ref), \ - mock.patch.object(sw, "sweep", return_value=list(ref)), \ - mock.patch.object(sw.os, "makedirs", side_effect=PermissionError(13, "Permission denied")): - out, err = io.StringIO(), io.StringIO() - with redirect_stdout(out), redirect_stderr(err): - rc = sw.main(["--ops", "v_exp_f16", "--modes", "keep16", "--waves", "32", "--json", str(out_path)]) - self.assertEqual(rc, 1) - self.assertIn("error:", err.getvalue()) - self.assertIn("Permission denied", err.getvalue()) - - with mock.patch.object(runner, "open_oracle", return_value=fake_oracle), \ - mock.patch.object(sw, "check_modes"), \ - mock.patch.object(sw, "reference", return_value=ref), \ - mock.patch.object(sw, "sweep", return_value=list(ref)), \ - mock.patch("builtins.open", side_effect=OSError(28, "No space left on device")): - out, err = io.StringIO(), io.StringIO() - with redirect_stdout(out), redirect_stderr(err): - rc = sw.main(["--ops", "v_exp_f16", "--modes", "keep16", "--waves", "32", "--json", str(out_path)]) - self.assertEqual(rc, 1) - self.assertIn("error:", err.getvalue()) - self.assertIn("No space left on device", err.getvalue()) - - -class OnHardware(unittest.TestCase): - @classmethod - def setUpClass(cls): - try: - cls.oracle = runner.open_oracle() - except runner.Unavailable as e: - raise unittest.SkipTest(f"hardware oracle unavailable: {e}") from None - why = asm.rdna23_skip_reason(cls.oracle.arch) - if why: - cls.oracle.close() - raise unittest.SkipTest(why) - - @classmethod - def tearDownClass(cls): - cls.oracle.close() - - def test_exp_sweep_is_the_same_in_both_wave_sizes_and_exact_on_integers(self): - sw.check_modes(self.oracle, ["keep16"]) - w32 = sw.sweep(self.oracle, "v_exp_f16", "keep16", 32) - w64 = sw.sweep(self.oracle, "v_exp_f16", "keep16", 64) - self.assertEqual(w32, w64) - for x, want in ((0x0000, 0x3C00), (0x3C00, 0x4000), (0x4000, 0x4400), (0xBC00, 0x3800), (0x7C00, 0x7C00), - (0xFC00, 0x0000)): - self.assertEqual(w32[x], want, f"exp2(0x{x:04x})") - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/test_f16_widen_probe.py b/tests/test_f16_widen_probe.py deleted file mode 100644 index 422e64e45..000000000 --- a/tests/test_f16_widen_probe.py +++ /dev/null @@ -1,232 +0,0 @@ -"""CPU-only unit tests for tools/f16_widen_probe.py: the models, the sweep through a fake oracle, and the CLI contracts.""" - -import io -import json -import os -import re -import subprocess -import sys -import tempfile -import unittest -import unittest.mock -from contextlib import redirect_stderr, redirect_stdout - -REPO = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) -TOOLS = os.path.join(REPO, "tools") -PROBE = os.path.join(TOOLS, "f16_widen_probe.py") - -sys.dont_write_bytecode = True -if TOOLS not in sys.path: - sys.path.insert(0, TOOLS) - -import f16_widen_probe as probe # noqa: E402 -from hw_oracle import asm as hw_asm, runner as hw_runner # noqa: E402 - - -class FakeOracle: - """Plays the GPU: returns the payload-preserving widening for every staged half, lane count from the load.""" - - arch = "gfx1036" - device = "fake gfx1036" - - def __init__(self, rule=None): - self.rule = rule or probe.h2f_payload - - def run(self, kernels, words=4): - out = [] - for k in kernels: - half = int( - [ln for ln in k.lines if ln.startswith("v_mov_b32 v4, 0x")][-1].split( - "0x" - )[1], - 16, - ) - lanes = [self.rule(half)] * words - out.append(lanes) - return out - - def close(self): - pass - - -def run_main(oracle, *args): - buf = io.StringIO() - with ( - unittest.mock.patch.object(hw_runner, "open_oracle", return_value=oracle), - redirect_stdout(buf), - ): - rc = probe.main(list(args)) - return rc, buf.getvalue() - - -class Models(unittest.TestCase): - def test_self_test(self): - proc = subprocess.run( - [sys.executable, "-I", PROBE, "--self-test"], - capture_output=True, - text=True, - check=False, - ) - self.assertEqual(proc.returncode, 0, proc.stderr or proc.stdout) - self.assertIn("self-test OK", proc.stdout) - - def test_the_three_rules_are_distinct(self): - self.assertEqual(probe.h2f_payload(0x7DDB), 0x7FBB6000) - self.assertEqual(probe.h2f_canonical(0x7DDB), 0x7FC00000) - self.assertEqual(probe.h2f_quiet(0x7DDB), 0x7FFB6000) - for h in (0x3C00, 0xC000): - self.assertEqual(probe.h2f_payload(h), probe.h2f_canonical(h)) - self.assertEqual(probe.h2f_payload(h), probe.h2f_quiet(h)) - - -class Sweep(unittest.TestCase): - def test_every_case_is_payload_on_the_measured_rule(self): - rc, out = run_main(FakeOracle(), "--waves", "32") - self.assertEqual(rc, 0, out) - oracle = FakeOracle() - report = probe.sweep(oracle, hw_asm, 32) - self.assertEqual( - len(report), 19 - ) # three formats x two forms x three widths, plus the ALU case - self.assertIn("alu/v_cvt_f32_f16", report) - for case, halves in report.items(): - for label, entry in halves.items(): - with self.subTest(case=case, half=label): - self.assertTrue( - all(c == "payload" for c in entry["classes"]), entry - ) - - def test_a_canonicalising_gpu_is_reported_as_such(self): - report = probe.sweep(FakeOracle(probe.h2f_canonical), hw_asm, 32) - entry = report["fmt13/16_FLOAT/buffer_x"] - self.assertEqual(entry["snan_7ddb"]["classes"], ["canonical"]) - self.assertEqual(entry["qnan_7fe6"]["classes"], ["canonical"]) - self.assertEqual( - entry["one_3c00"]["classes"], ["payload"] - ) # a finite half is the same either way - - def test_json_report_has_the_measured_table(self): - with tempfile.TemporaryDirectory() as tmp: - path = os.path.join(tmp, "sub", "report.json") - rc, out = run_main(FakeOracle(), "--waves", "32", "--json", path) - self.assertEqual(rc, 0, out) - with open(path, encoding="utf-8") as f: - data = json.load(f) - self.assertEqual(data["arch"], "gfx1036") - entry = data["waves"]["32"]["fmt13/16_FLOAT/buffer_x"]["snan_7ddb"] - self.assertEqual(entry["half"], "0x7ddb") - self.assertEqual(entry["words"], ["0x7fbb6000"]) - self.assertEqual(entry["classes"], ["payload"]) - - -class Contracts(unittest.TestCase): - def test_non_gfx10_or_missing_oracle_exits_77(self): - env = { - k: v - for k, v in os.environ.items() - if not k.startswith("LEONIDA_HW_") and k != "LEONIDA_AMD_CLANG" - } - env["LEONIDA_AMD_CLANG"] = os.path.join(REPO, "does_not_exist_clang") - proc = subprocess.run( - [sys.executable, "-I", PROBE], - env=env, - capture_output=True, - text=True, - check=False, - ) - self.assertEqual(proc.returncode, 77, proc.stderr or proc.stdout) - - def test_invalid_waves_rejected_before_open_oracle(self): - for bad in ("", " ", "abc", "32,foo", "16", "32,128"): - with self.subTest(waves=bad): - err = io.StringIO() - with ( - unittest.mock.patch.object( - hw_runner, - "open_oracle", - side_effect=AssertionError("open_oracle called"), - ), - redirect_stderr(err), - ): - rc = probe.main(["--waves", bad]) - self.assertEqual(rc, 2) - self.assertIn("error:", err.getvalue()) - - def test_invalid_json_rejected_before_open_oracle(self): - with tempfile.TemporaryDirectory() as tmp: - file_ancestor = os.path.join(tmp, "not_a_dir") - with open(file_ancestor, "w", encoding="utf-8") as f: - f.write("x") - for bad in ( - "", - " ", - "bad\x00.json", - tmp, - os.path.join(file_ancestor, "out.json"), - ): - with self.subTest(json_path=bad): - err = io.StringIO() - with ( - unittest.mock.patch.object( - hw_runner, - "open_oracle", - side_effect=AssertionError("open_oracle called"), - ), - redirect_stderr(err), - ): - rc = probe.main(["--json", bad]) - self.assertEqual(rc, 2) - self.assertIn("error:", err.getvalue()) - - def test_write_json_report_uses_lf(self): - with tempfile.TemporaryDirectory() as tmp: - nested = os.path.join(tmp, "sub", "dir", "report.json") - err = probe.write_json_report( - nested, {"arch": "gfx1036", "waves": {"32": {}}} - ) - self.assertIsNone(err) - with open(nested, "rb") as f: - raw = f.read() - self.assertNotIn(b"\r\n", raw) - self.assertEqual(json.loads(raw.decode("utf-8"))["arch"], "gfx1036") - - def test_write_json_oserror_returns_1_without_traceback(self): - with tempfile.TemporaryDirectory() as tmp: - out_path = os.path.join(tmp, "report.json") - out, err = io.StringIO(), io.StringIO() - with ( - unittest.mock.patch.object( - hw_runner, "open_oracle", return_value=FakeOracle() - ), - unittest.mock.patch.object(hw_asm, "family", return_value="gfx10"), - unittest.mock.patch("builtins.open", side_effect=OSError("disk full")), - redirect_stdout(out), - redirect_stderr(err), - ): - rc = probe.main(["--waves", "32", "--json", out_path]) - self.assertEqual(rc, 1) - self.assertIn("disk full", err.getvalue()) - self.assertNotIn("Traceback", err.getvalue()) - - def test_kernels_stage_then_load_the_same_half(self): - k = probe._kernel(hw_asm, "buffer_load_format_xy", 29, 0x7FE6, 64) - self.assertEqual(k.wave, 64) - self.assertIn("buffer_store_dword v4, off, s[8:11], 0 offset:32 glc", k.lines) - self.assertIn("s_waitcnt_vscnt null, 0x0", k.lines) - self.assertIn( - "buffer_load_format_xy v[4:5], off, s[8:11], 0 offset:32", k.lines - ) - self.assertIn("buffer_store_dword v5, off, s[8:11], 0 offset:4", k.lines) - self.assertEqual(k.lines[-1], "s_endpgm") - t = probe._kernel(hw_asm, "tbuffer_load_format_x", 13, 0x7DDB, 32) - self.assertTrue( - any( - ln.startswith("tbuffer_load_format_x v4,") and "format:13" in ln - for ln in t.lines - ) - ) - self.assertIn("v_mov_b32 v4, 0x7ddb", t.lines) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/test_f16misc_diff.py b/tests/test_f16misc_diff.py deleted file mode 100644 index c3c9d5c86..000000000 --- a/tests/test_f16misc_diff.py +++ /dev/null @@ -1,354 +0,0 @@ -"""tools/f16misc_diff.py: the f16 reference against the words measured on RDNA2 hardware and the semantic tests' -references, the generator's encoding rules, the sweep and edge grid, and short seeded differential runs. Standard -library only; no GPU, no game files. - -The family is v_min3_f16, v_max3_f16, v_frexp_mant_f16, v_frexp_exp_i16_f16, v_ldexp_f16, v_fmamk_f16, v_fmaak_f16, -v_pk_fmac_f16, v_fma_mix_f32, v_fma_mixlo_f16 and v_fma_mixhi_f16. - -The two single-rounding cases below are worked out by hand (f16: ulp 2^-10 on [1, 2), ties at the odd multiples of -2^-11; f32: ulp 2^-23 on [1, 2)). x * y is 2^-11 (1 + d / 2^21), so x * y + z is off an f16 tie by |d| 2^-32, less -than half an f32 ulp: - - P 0x2816 * 0x23d5 = 2^-11 (1 + 78 / 2^21); + 1.0 (0x3c00): once -> above the tie -> 0x3c01; f32 lands on the tie, - even is 0x3c00 - M 0x2817 * 0x23d3 = 2^-11 (1 - 11 / 2^21); + (1 + 2^-10) (0x3c01): once -> below the tie -> 0x3c01; f32 lands on - the tie 1 + 3 * 2^-11, even is 0x3c02 -""" -import inspect -import io -import os -import random -import re -import sys -import unittest -from collections import Counter -from contextlib import redirect_stdout - -ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) -sys.path.insert(0, os.path.join(ROOT, "tools")) -import f16misc_diff as f # noqa: E402 (puts tests/semantic on sys.path) -import test_alu_frexp_ldexp_f16 as fl # noqa: E402 -import test_alu_min3_max3_med3_16_hw as mm # noqa: E402 (the gfx1036-measured min3/max3/med3 words) -import test_alu_vop3_mods_hw as vm # noqa: E402 (the gfx1036-measured v_fma_mix_* words, among others) - -M16 = 0xFFFF -BY_HAND = ( # (x, y, z, single rounding, double rounding) - (0x2816, 0x23D5, 0x3C00, 0x3C01, 0x3C00), - (0x2817, 0x23D3, 0x3C01, 0x3C01, 0x3C02), -) - - -def base_op(line): - return re.sub(r"_e(32|64)$", "", line.split()[0]) - - -def measured(rows): - """Run the hardware-oracle rows (text, v1, v2, v3, word in v4) of the family through the reference. - Returns (Counter of ok / unjudged reasons, the mismatching rows).""" - res, bad = Counter(), [] - for text, v1, v2, v3, want in rows: - lines = text.split("\n") - if base_op(lines[-1]) not in f.FAMILY: - continue - mc = f.Machine() - for r, w in ((1, v1), (2, v2), (3, v3), (4, 0xDEADBEEF)): - mc.write_word(r, w) - try: - for line in lines: - op, args, _ = f.split_line(line) - if op == "s_mov_b32": - mc.s[int(args[0][1:])] = int(args[1], 16) - elif op == "v_mov_b32": - mc.write_word(mc.dst(args[0]), mc.v[int(args[1][1:])]) - else: - f.step(line, mc) - except f.NotJudged as e: - res[str(e)] += 1 - continue - none = [None, None] - if f.compare([mc.v[4], 0, 0, 0], [mc.state(4), none, none, none], [want, 0, 0, 0]): - bad.append((text, hex(v1), hex(v2), hex(v3), hex(want), hex(mc.v[4]))) - else: - res["ok " + base_op(lines[-1])] += 1 - return res, bad - - -def one(line, **regs): - """The word left in v8 by ``line`` after the given v words.""" - mc = f.Machine() - mc.write_word(8, 0x5A5A5A5A) - for name, w in regs.items(): - mc.write_word(int(name[1:]), w) - f.step(line, mc) - return mc.v[8], mc.state(8) - - -class Reference(unittest.TestCase): - def test_min3_max3_match_every_measured_gfx1036_row(self): - res, bad = measured(mm.MEASURED) - self.assertEqual(bad, []) - want = sum(base_op(r[0]) in ("v_min3_f16", "v_max3_f16") for r in mm.MEASURED) - self.assertEqual(res["ok v_min3_f16"] + res["ok v_max3_f16"], want) - self.assertGreaterEqual(want, 100) - - def test_fma_mix_matches_the_measured_gfx1036_rows(self): - res, bad = measured(vm.MEASURED) - self.assertEqual(bad, []) - self.assertGreaterEqual(res["ok v_fma_mix_f32"], 600) - self.assertGreaterEqual(res["ok v_fma_mixlo_f16"], 40) - self.assertGreaterEqual(res["ok v_fma_mixhi_f16"], 5) - self.assertEqual({k for k in res if not k.startswith("ok ")} - {"clamp of -0"}, set()) - - def test_frexp_ldexp_measured_rows(self): - for h, mant, ex in fl.MEASURED_FREXP: - self.assertEqual(one("v_frexp_mant_f16_e32 v8, v9", v9=h)[0] & M16, mant, hex(h)) - self.assertEqual(one("v_frexp_exp_i16_f16_e32 v8, v9", v9=h)[0] & M16, ex, hex(h)) - for h, n, word in fl.MEASURED_LDEXP: - got = one("v_ldexp_f16_e64 v8, v9, v9 op_sel:[0,1,0]", v9=h | ((n & M16) << 16))[0] & M16 - self.assertEqual(got, word, (hex(h), n)) - - def test_frexp_ldexp_match_the_semantic_reference_for_every_half(self): - mc = f.Machine() - bad = [] - for h in range(1 << 16): - mc.write_word(9, h) - f.step("v_frexp_mant_f16_e32 v8, v9", mc) - f.step("v_frexp_exp_i16_f16_e32 v10, v9", mc) - if (mc.v[8] & M16, mc.v[10] & M16) != (fl.ref_mant(h), fl.ref_exp(h)): - bad.append(("frexp", hex(h))) - n = (-64, -25, -15, 1, 30, 100)[h % 6] - mc.write_word(9, h | ((n & M16) << 16)) - f.step("v_ldexp_f16_e64 v8, v9, v9 op_sel:[0,1,0]", mc) - if mc.v[8] & M16 != fl.ref_ldexp(h, n): - bad.append(("ldexp", hex(h), n)) - self.assertEqual(bad[:5], []) - - def test_fma_rounds_once(self): - for x, y, z, single, double in BY_HAND: - exact = f.fma(f.decode16(x), f.decode16(y), f.decode16(z)) - self.assertEqual(f.encode16(f.round_to(exact, f.F16)), single) - self.assertEqual(f.encode16(f.round_to(f.round_to(exact, f.F32), f.F16)), double) - w, _ = one(f"v_fmamk_f16 v8, v9, 0x{y:04x}, v10", v9=x, v10=0xABCD0000 | z) - self.assertEqual(w, 0x5A5A0000 | single) - # lane 1 negates y and the accumulator: -(x * y + z) - w, _ = one("v_pk_fmac_f16 v8, v9, v10", v8=z | ((z ^ 0x8000) << 16), v9=x | (x << 16), - v10=y | ((y ^ 0x8000) << 16)) - self.assertEqual(w, single | ((single ^ 0x8000) << 16)) - w, _ = one("v_fma_mixhi_f16 v8, v9, v10, v11 op_sel:[0,0,0] op_sel_hi:[1,1,1]", v9=x, v10=y, v11=z) - self.assertEqual(w, (single << 16) | 0x5A5A) - - def test_near_one_pairs(self): - self.assertGreaterEqual(len(f.NEAR_ONE), 20) - for a, c, d in f.NEAR_ONE: - self.assertEqual((1024 + a) * (2048 - c), (1 << 21) + d) - self.assertTrue(0 < abs(d) < 256 and 1 <= c <= 1023, (a, c, d)) - self.assertTrue(any(d > 0 for _, _, d in f.NEAR_ONE) and any(d < 0 for _, _, d in f.NEAR_ONE)) - - def test_the_edge_grid_tells_single_from_double_rounding(self): - witnesses = Counter() - for op, words, *_ in f.grid_cases(): - if f.FAMILY[op] not in ("fmamk", "fmaak", "pkfmac", "mixlo", "mixhi"): - continue - vals = [f.decode16(w) if w <= M16 else f.decode32(w) for w in words] - exact = f.fma(*vals) - if exact[0] == "num" and f.round_to(exact, f.F16) != f.round_to(f.round_to(exact, f.F32), f.F16): - witnesses[op] += 1 - for op in ("v_fmamk_f16", "v_fmaak_f16", "v_pk_fmac_f16", "v_fma_mixlo_f16", "v_fma_mixhi_f16"): - self.assertGreaterEqual(witnesses[op], 4, op) - - def test_min3_max3_nan_and_signed_zero(self): - cases = (("v_min3_f16", (0x7E00, 0x3C00, 0x4000), 0x3C00), ("v_max3_f16", (0x7E00, 0x3C00, 0xFE00), 0x3C00), - ("v_min3_f16", (0x0000, 0x8000, 0x0000), 0x8000), ("v_max3_f16", (0x8000, 0x0000, 0x8000), 0x0000), - ("v_min3_f16", (0xFC00, 0x7E00, 0x0001), 0xFC00), ("v_max3_f16", (0x7C01, 0x0001, 0x8001), 0x0001)) - for op, (a, b, c), want in cases: - w, st = one(f"{op} v8, v9, v10, v11", v9=a, v10=b, v11=c) - self.assertEqual((w, st), (0x5A5A0000 | want, [None, None]), (op, a, b, c)) - w, st = one("v_min3_f16 v8, v9, v10, v11 op_sel:[0,0,0,1]", v9=0x7E00, v10=0x7D00, v11=0xFE00) - self.assertEqual((w & M16, st), (0x5A5A, [None, "nan"])) # every operand NaN: any NaN - - def test_output_modifiers(self): - # mul:2/mul:4/div:2 leave an f16 result as it is and clamp still acts; frexp_exp ignores both. The words - # main's translator gives, as measured on gfx1036 (docs/design.md). - for line, want in (("v_min3_f16 v8, v9, v10, v11 mul:2", 0xB800), - ("v_max3_f16 v8, v9, v10, v11 clamp div:2", 0x3C00), - ("v_frexp_mant_f16_e64 v8, v11 mul:4", 0x3900), - ("v_frexp_exp_i16_f16_e64 v8, v11 clamp mul:2", 0x0002), - ("v_ldexp_f16_e64 v8, v9, v12 div:2", 0x4600), - ("v_ldexp_f16_e64 v8, v11, v12 clamp mul:2", 0x3C00)): - w, st = one(line, v9=0x12343A00, v10=0x5678B800, v11=0x9ABC4100, v12=3) - self.assertEqual((w, st), (0x5A5A0000 | want, [None, None]), line) - - def test_clamp(self): - for line, v9, want in (("v_frexp_mant_f16_e64 v8, v9 clamp", 0x7E00, 0x0000), - ("v_frexp_mant_f16_e64 v8, v9 clamp", 0xC400, 0x0000), - ("v_ldexp_f16_e64 v8, v9, v9 op_sel:[0,1,0] clamp", 0x0003_4200, 0x3C00), - ("v_ldexp_f16_e64 v8, v9, v9 op_sel:[0,1,0] clamp", 0x0001_7E00, 0x0000), - ("v_min3_f16 v8, v9, v9, v9 clamp", 0x0000_4000, 0x3C00)): - self.assertEqual(one(line, v9=v9)[0] & M16, want, line) - with self.assertRaises(f.NotJudged): - one("v_max3_f16 v8, v9, v9, v9 clamp", v9=0x7E00) # FClamp of a NaN is undefined in SPIR-V - - def test_f32_operands_of_fma_mix_flush_denormals(self): - # 1 * (+denormal) + -0: the denormal reads as +0, so +0 + -0 = +0 (unflushed it would be the denormal) - w, _ = one("v_fma_mix_f32 v8, v9, v10, v11 op_sel_hi:[0,0,0]", v9=0x3F800000, v10=0x007FFFFF, v11=0x80000000) - self.assertEqual(w, 0x00000000) - # 1 * (-denormal) + -0 = -0 + -0 = -0 - w, _ = one("v_fma_mix_f32 v8, v9, v10, v11 op_sel_hi:[0,0,0]", v9=0x3F800000, v10=0x80000001, v11=0x80000000) - self.assertEqual(w, 0x80000000) - - def test_unjudged(self): - with self.assertRaises(f.NotJudged): # an f32 denormal result - one("v_fma_mix_f32 v8, v9, v10, v11 op_sel_hi:[0,0,0]", v9=0x00800000, v10=0x3F000000, v11=0) - mc = f.Machine() - mc.write_word(9, 0x7FC00000, "w32") - with self.assertRaises(f.NotJudged): # half of an f32 NaN read as an f16 - f.step("v_frexp_mant_f16_e32 v8, v9", mc) - - def test_compare(self): - none = [None, None] - self.assertIsNone(f.compare([0x12340000, 0, 0, 0], [[None, "nan"], none, none, none], [0x7FFF0000, 0, 0, 0])) - self.assertIn("f16 NaN", f.compare([0x12340000, 0, 0, 0], [[None, "nan"], none, none, none], - [0x7C000000, 0, 0, 0])) - self.assertIn("expected 0x12340000", f.compare([0x12340000, 0, 0, 0], [[None, "nan"], none, none, none], - [0x7E000001, 0, 0, 0])) - self.assertIsNone(f.compare([0, 0, 0, 0], [["w32", "w32"], none, none, none], [0xFFC00001, 0, 0, 0])) - self.assertIn("f32 NaN", f.compare([0, 0, 0, 0], [["w32", "w32"], none, none, none], [0x7F800000, 0, 0, 0])) - - def test_harness_errors(self): - for line in ("v_add_f16 v8, v9, v10", "v_fmamk_f16 v8, v9, 0x3c00, v10 mul:2", - "v_frexp_mant_f16_e32 v8, v9 div:2", "v_ldexp_f16_e64 v8, v9, -v9"): - with self.assertRaises(f.HarnessError, msg=line): - one(line, v9=0x3C00, v10=0x3C00) - - -class Generator(unittest.TestCase): - def test_generation_is_deterministic(self): - self.assertEqual(f.program(random.Random(5), 6), f.program(random.Random(5), 6)) - self.assertEqual(f.grid_cases(), f.grid_cases()) - - def test_ops_subset_is_respected(self): - lines, used = f.program(random.Random(2), 20, ["v_ldexp_f16", "v_fma_mixhi_f16"]) - self.assertEqual(set(used), {"v_ldexp_f16", "v_fma_mixhi_f16"}) - self.assertTrue(all(base_op(line) in ("v_mov_b32", "s_mov_b32") + tuple(used) for line in lines)) - - def test_sweep_covers_every_op_and_kind(self): - cases = f.sweep_cases() - self.assertEqual({c[0] for c in cases}, set(f.FAMILY)) - for op in f.FAMILY: - kinds = {k for c in cases if c[0] == op for k in c[2][:1]} - want = {"vgpr", "sgpr", "int", "float"} if f.FAMILY[op] in ("fmamk", "fmaak") else set(f.KINDS) - self.assertEqual(kinds, want, op) - # ldexp: 5 _e32 forms (src1 a VGPR) and 5 x 4 _e64 kind pairs but literal with literal - self.assertEqual(sum(c[0] == "v_ldexp_f16" for c in cases), 5 + 19) - - def test_programs_are_encodable(self): - rng = random.Random(9) - for _ in range(400): - lines, _ = f.program(rng, 6) - for line in lines: - op, args, mods = f.split_line(line) - if op in ("v_mov_b32", "s_mov_b32"): - continue - srcs = args[1:] - lits = [a for a in srcs if a.startswith("0x")] - sgprs = [a for a in srcs if a.lstrip("-|").startswith("s")] - self.assertLessEqual(len(lits), 1, line) - if op.endswith("_e32") or op in ("v_fmamk_f16", "v_fmaak_f16", "v_pk_fmac_f16"): - vsrc = [a for i, a in enumerate(srcs) if i > 0 and not (op in ("v_fmamk_f16", "v_fmaak_f16") - and a.startswith("0x"))] - self.assertTrue(all(a.startswith("v") for a in vsrc), line) - else: - self.assertLessEqual(len(lits) + len(sgprs), 2, line) - if base_op(line) in f.MIX: - self.assertIn("op_sel_hi:", line) - - def test_edge_grid(self): - cases = f.grid_cases() - by_op = Counter(c[0] for c in cases) - for op in ("v_fmamk_f16", "v_fmaak_f16", "v_pk_fmac_f16", "v_fma_mix_f32", "v_fma_mixlo_f16", - "v_fma_mixhi_f16"): - self.assertEqual(by_op[op], 240, op) - self.assertEqual(by_op["v_frexp_mant_f16"], 2 * len(f.F16_EDGES)) # plain and clamped - self.assertEqual(by_op["v_frexp_exp_i16_f16"], len(f.F16_EDGES)) - self.assertEqual(by_op["v_ldexp_f16"], (12 + 3) * len(f.F16_EDGES)) - clamped = {c[0] for c in cases if c[2:] == ("clamp",)} - self.assertEqual(clamped, {"v_frexp_mant_f16", "v_ldexp_f16"}) - nans = (0x7E00, 0x7D00) - triples = [c[1] for c in cases if c[0] == "v_min3_f16"] - self.assertEqual(len(triples), 10 ** 3 - 8) - self.assertFalse(any(all(v in nans for v in w) for w in triples)) - - def test_exhaustive_programs_cover_every_half(self): - progs = list(f.exhaustive_programs(["v_frexp_exp_i16_f16"])) - self.assertEqual(len(progs), (1 << 16) // f.GRID_PER_PROGRAM) - seen = {int(line.split("0x")[1], 16) & M16 for _, lines in progs for line in lines - if re.match(r"v_mov_b32 v1[2-5], ", line)} - self.assertEqual(len(seen), 1 << 16) - - -class Translated(unittest.TestCase): - def test_harness_canaries(self): - with redirect_stdout(io.StringIO()) as out: - ok = f.self_test() - self.assertTrue(ok, out.getvalue()) - - def test_short_seeded_run_matches(self): - counts, failure = f.run_suite(20, 3, 5) - self.assertEqual((failure, counts["skip"]), (None, {})) - self.assertEqual(counts["pass"] + sum(counts["unjudged"].values()), 20) - - def test_sweep_matches_for_ldexp_and_mixhi(self): - counts, failure = f.run_sweep(4, ["v_ldexp_f16", "v_fma_mixhi_f16"]) - self.assertEqual((failure, counts["skip"]), (None, {})) - self.assertGreater(counts["pass"], 100) - - def test_edge_grid_matches_for_fmamk_and_min3(self): - counts, failure = f.run_grid(["v_fmamk_f16", "v_min3_f16"]) - self.assertEqual((failure, counts["skip"]), (None, {})) - self.assertGreater(counts["events"]["v_fmamk_f16"]["tie"], 10) - self.assertGreater(counts["events"]["v_min3_f16"]["NaN"], 100) - - def test_each_program_is_checked_before_the_next_is_made(self): - # a run holds one program's text at a time, not the whole --programs list - made, seen = [], [] - real = f.program, f.sweep_program, f.grid_program, f.run_one - - def count(fn): - return lambda *a: made.append(1) or fn(*a) - try: - f.program, f.sweep_program, f.grid_program = (count(fn) for fn in real[:3]) - f.run_one = lambda lines, name, tmp, events=None: seen.append(len(made)) or ("match", None) - f.run_suite(5, 1) - f.run_sweep(1, ["v_ldexp_f16"]) - f.run_grid(["v_min3_f16"]) - finally: - f.program, f.sweep_program, f.grid_program, f.run_one = real - self.assertGreater(len(seen), 10) - self.assertEqual(seen, list(range(1, len(seen) + 1))) - self.assertTrue(inspect.isgenerator(f.exhaustive_programs())) - - def test_fma_rounds_once_through_the_translator(self): - for x, y, z, single, _ in BY_HAND: - for line in (f"v_fmamk_f16 v8, v12, 0x{y:04x}, v8", f"v_fmaak_f16 v8, v12, v13, 0x{z:04x}", - "v_fma_mixlo_f16 v8, v12, v13, v14 op_sel:[0,0,0] op_sel_hi:[1,1,1]"): - lines = [f"v_mov_b32 v{r}, 0x5a5a5a5a" for r in f.VGPRS] - lines += ["v_mov_b32 v8, 0x%08x" % (0xABCD0000 | z), "v_mov_b32 v12, 0x%08x" % x, - "v_mov_b32 v13, 0x%08x" % y, "v_mov_b32 v14, 0x%08x" % z, line] - self.assertEqual(f.reference(lines)[0][0] & M16, single, line) - self.assertIsNone(f.check(lines), line) - - def test_a_wrong_translation_is_caught(self): - x, y, z, single, double = BY_HAND[0] - lines = [f"v_mov_b32 v{r}, 0x5a5a5a5a" for r in f.VGPRS] - lines += [f"v_mov_b32 v8, 0x{z:08x}", f"v_mov_b32 v12, 0x{x:08x}", f"v_fmamk_f16 v8, v12, 0x{y:04x}, v8"] - self.assertIsNone(f.check(lines)) - real = f.translate_listing - try: - f.translate_listing = lambda l, n, t: [(real(l, n, t)[0] & ~M16) | double] + real(l, n, t)[1:] - self.assertIn(f"expected 0x0000{single:04x}, actual 0x0000{double:04x}", f.check(lines)) - finally: - f.translate_listing = real - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/test_f32_fuzz.py b/tests/test_f32_fuzz.py deleted file mode 100644 index 627936938..000000000 --- a/tests/test_f32_fuzz.py +++ /dev/null @@ -1,250 +0,0 @@ -"""Tests for tools/f32_fuzz.py, the FUZZ-3 float VALU differential fuzzer (no game data, no GPU, no llvm-mc). - - python -I tests/test_f32_fuzz.py -""" -import os -import random -import subprocess -import sys -import unittest - -ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) -sys.path.insert(0, os.path.join(ROOT, "tools")) -sys.dont_write_bytecode = True - -import f32_fuzz as ff # noqa: E402 - - -class ModelTests(unittest.TestCase): - def test_round_f32_ties_to_even_and_overflow(self): - from fractions import Fraction - self.assertEqual(ff.round_f32(Fraction(1) + Fraction(1, 1 << 24)), ff.bits(1.0)) # tie -> even - self.assertEqual(ff.round_f32(Fraction(1) + Fraction(3, 1 << 24)), ff.bits(1.0) + 2) - self.assertEqual(ff.round_f32(Fraction(2) ** 128), ff.PINF) - self.assertEqual(ff.round_f32(Fraction(-1, 3)), 0xBEAAAAAB) - - def test_mad_and_fma_differ_where_rounding_matters(self): - x, y, z = 0xBC500C59, 0x435A2099, 0x3E3DB015 - self.assertEqual(ff.add(ff.mul(x, y), z), 0xC0256A01) - self.assertEqual(ff.fma(x, y, z), 0xC0256A00) - - def test_signed_zeros(self): - self.assertEqual(ff.add(0x80000000, 0x80000000), 0x80000000) - self.assertEqual(ff.add(ff.bits(1.0), ff.bits(-1.0)), 0) - self.assertEqual(ff.legacy_mul(0x80000000, ff.NINF), 0) - self.assertEqual(ff.rounding(ff.bits(-0.25), "ceil"), 0x80000000) - - def test_rtz_f16(self): - self.assertEqual(ff.round_rtz_f16(ff.bits(65519.0)), 0x7BFF) - self.assertEqual(ff.round_rtz_f16(ff.NINF), 0xFC00) - self.assertEqual(ff.round_rtz_f16(ff.bits(2.0 ** -24 * 1.5)), 0x0001) - - def test_cube_major_axis(self): - # |z| largest and negative: face 5, sc = -x, tc = -y, ma = 2z. - x, y, z = ff.bits(0.5), ff.bits(0.25), ff.bits(-2.0) - self.assertEqual(ff.cube("v_cubeid_f32", x, y, z), ff.bits(5.0)) - self.assertEqual(ff.cube("v_cubesc_f32", x, y, z), ff.bits(-0.5)) - self.assertEqual(ff.cube("v_cubetc_f32", x, y, z), ff.bits(-0.25)) - self.assertEqual(ff.cube("v_cubema_f32", x, y, z), ff.bits(-4.0)) - # Measured on RDNA2 (gfx1036): v_cubema_f32 returns +0.0 (never -0.0) when all axes are ±0.0. - self.assertEqual(ff.cube("v_cubema_f32", 0, 0, 0x80000000), 0) - self.assertEqual(ff.cube("v_cubema_f32", 0x80000000, 0x80000000, 0x80000000), 0) - - -class HarnessTests(unittest.TestCase): - def test_self_test(self): - self.assertTrue(ff.self_test()) - - def test_generation_is_deterministic(self): - a = ff.gen(random.Random(5), "v_fma_f32") - b = ff.gen(random.Random(5), "v_fma_f32") - self.assertEqual(a, b) - - def test_seeded_run_has_no_mismatch(self): - # A short seeded sweep over every op: the translator rules found by FUZZ-3 stay fixed. Undefined-in-SPIR-V - # inputs and denormals are counted, never compared. - counts, by_op, _ = ff.run_suite(400, 3, tuple(ff.OPS), quiet=True) - self.assertEqual(by_op, {}) - self.assertEqual(counts["mismatch"], 0) - self.assertGreater(counts["match"], 300) - - def test_v_mac_f32_is_not_fused(self): - vals = [0xBC500C59, 0x435A2099] + [0] * 6 + [0x3E3DB015] - status, detail = ff.check("v_mac_f32", vals, [(0, {}), (1, {})], False, []) - self.assertEqual(status, "match", detail) - - def test_output_modifiers_on_conversions(self): - vals = [0x00007800] + [0] * 8 - for op, mods in (("v_cvt_f32_ubyte1", ["clamp"]), ("v_cvt_f32_u32", ["mul:4"]), - ("v_cvt_f32_i32", ["div:2"])): - with self.subTest(op=op, mods=mods): - status, detail = ff.check(op, vals, [(0, {})], True, mods) - self.assertEqual(status, "match", detail) - - def test_undefined_spirv_is_its_own_class(self): - vals = [0] + [0] * 8 # v_rcp_f32 of +0: hardware +inf, OpFDiv by zero - status, _ = ff.check("v_rcp_f32", vals, [(0, {})], False, []) - self.assertEqual(status, "undefined") - - def test_denormal_operand_is_skipped(self): - vals = [0x00000001, ff.bits(1.0)] + [0] * 7 - status, detail = ff.check("v_add_f32", vals, [(0, {}), (1, {})], False, []) - self.assertEqual(status, "skip") - self.assertIn("denormal", detail) - - def test_fmamk_madmk_operand_order_and_translator(self): - # S0 * K + S2 = 2.0 * 3.0 + 4.0 = 10.0 (whereas S0 * S2 + K would be 11.0). - vals = [0] * len(ff.SEED_REGS) - vals[0], vals[1] = ff.bits(2.0), ff.bits(4.0) - srcs = [(0, {}), ("k", ff.bits(3.0)), (1, {})] - for op in ("v_fmamk_f32", "v_madmk_f32"): - with self.subTest(op=op): - got_model = ff.model(op, vals, srcs, []) - self.assertEqual(got_model, [ff.bits(10.0), 0]) - self.assertEqual(ff.line(op, vals, srcs, False, []), - f"{op} v8, v0, 0x{ff.bits(3.0):x}, v1") - status, words = ff.run_translated(ff.listing(op, vals, srcs, False, [])[0]) - self.assertEqual((status, words[:2]), ("ok", got_model)) - - -class CliTests(unittest.TestCase): - TOOL = os.path.join(ROOT, "tools", "f32_fuzz.py") - - def test_no_arguments_prints_usage(self): - r = subprocess.run([sys.executable, "-I", self.TOOL], capture_output=True, text=True, timeout=5) - self.assertEqual(r.returncode, 2, r.stderr) - self.assertIn("usage:", r.stderr) - self.assertNotIn("Traceback", r.stderr) - - -class HardwareOracle(unittest.TestCase): - """--oracle hw: kernel text, verdicts, GFX11 skips and the exit-77 contract (no GPU needed), plus a run on the - GPU when the oracle tools are present.""" - TOOL = os.path.join(ROOT, "tools", "f32_fuzz.py") - - def case(self, op, vals, srcs, mods=(), e64=False): - return ff.Case(op, list(vals) + [0] * (9 - len(vals)), srcs, e64, list(mods)) - - def test_kernel_body(self): - c = self.case("v_add_f32", [ff.bits(1.0), ff.bits(2.0)], [(0, {}), (1, {})], ["mul:2", "clamp"], True) - lines = ff.hw_lines(c, "gfx1150") - self.assertIn("v_add_f32_e64 v8, v0, v1 clamp mul:2", lines) # GFX11 wants clamp before omod - self.assertEqual(lines[-3:], ["v_mov_b32 v20, 0", "global_store_b64 v20, v[8:9], s[2:3]", "s_endpgm"]) - self.assertEqual(ff.hw_lines(c, "gfx1030")[-2], "global_store_dwordx2 v20, v[8:9], s[2:3]") - self.assertEqual(len(ff.hw_lines(c, "gfx1150", guard=False)), len(lines) - 1) - - def test_packed_u8_hardware_verdict_compares_raw_bytes(self) -> None: - case = self.case("v_cvt_pk_u8_f32", [0x43000000, 0, 0x7FC00000], - [(0, {}), (1, {}), (2, {})], e64=True) - self.assertEqual(ff.hw_verdict(case, [0x7FC00080, 0]), ("match", [0x7FC00080, 0])) - self.assertEqual(ff.hw_verdict(case, [0x7FC00081, 0]), ("mismatch", [0x7FC00080, 0])) - - def test_removed_opcodes_are_skipped_not_substituted(self): - from hw_oracle import asm - for op in ("v_mad_f32", "v_mac_f32", "v_madak_f32", "v_madmk_f32", "v_mad_legacy_f32"): - self.assertIn(op, asm.valu_skip_reason(op, "gfx1150")) - self.assertIn(op, asm.valu_skip_reason(op, "gfx1030")) - self.assertIsNone(asm.valu_skip_reason(op, "gfx1013")) - self.assertIsNone(asm.valu_skip_reason("v_mul_legacy_f32", "gfx1150")) - - def test_mode_words(self): - self.assertEqual(ff.mode_word(ff.HW_MODES["flush"]), 0x1C0) - self.assertEqual(ff.mode_word(ff.HW_MODES["keep"]), 0x1F0) - self.assertEqual(ff.mode_word(ff.HW_MODES["ieee"]), 0x3C0) - self.assertFalse(ff.omod_active("keep", "v_add_f32")) - self.assertTrue(ff.omod_active("keep", "v_rcp_f32")) - - def test_verdicts(self): - a = self.case("v_add_f32", [ff.bits(1.0), ff.bits(2.0)], [(0, {}), (1, {})]) - self.assertEqual(ff.hw_verdict(a, [ff.bits(3.0), 0])[0], "match") - self.assertEqual(ff.hw_verdict(a, [ff.bits(3.0) ^ 1, 0])[0], "mismatch") - d = self.case("v_ceil_f32", [ff.bits(-0.75)], [(0, {})], ["mul:2"], True) - self.assertEqual(ff.hw_verdict(d, [0, 0])[0], "deviation:omod_neg_zero") # omod: -0 becomes +0 - self.assertEqual(ff.hw_verdict(d, [0x80000000, 0])[0], "match") - self.assertEqual(ff.hw_verdict(d, [ff.bits(1.0), 0])[0], "mismatch") - dn = self.case("v_add_f32", [1, ff.bits(1.0)], [(0, {}), (1, {})]) - self.assertEqual(ff.hw_verdict(dn, [ff.bits(1.0), 0])[0], "skip") - - def test_omod_deviation_needs_an_active_omod(self): - d = self.case("v_ceil_f32", [ff.bits(-0.75)], [(0, {})], ["mul:2"], True) - want = [0x80000000, 0] - self.assertEqual(ff.dev_omod_neg_zero(d, want), [0, 0]) - self.assertIsNone(ff.dev_omod_neg_zero(d, want, "ieee")) - self.assertIsNone(ff.dev_omod_neg_zero(d, want, "keep")) - self.assertIsNone(ff.dev_omod_neg_zero(self.case("v_ceil_f32", [0], [(0, {})], [], True), want)) - - def test_omod_label_does_not_count_a_kept_minus_zero_as_applied(self): - # ceil(-0.75) = -0: with and without the omod the model says -0, so a -0 from the hardware shows neither - # that the omod was applied nor that it was ignored (SHADER-353: 65 such programs under MODE.IEEE = 1 on - # gfx1031 were counted as "applied" while every unambiguous one was ignored). - d = self.case("v_ceil_f32", [ff.bits(-0.75)], [(0, {})], ["mul:2"], True) - self.assertEqual(ff.omod_label(d, [0x80000000, 0]), "-0 result kept (applied or ignored, same word)") - self.assertEqual(ff.omod_label(d, [0, 0]), "applied, but a -0 result becomes +0") - a = self.case("v_ceil_f32", [ff.bits(1.5)], [(0, {})], ["mul:2"], True) - self.assertEqual(ff.omod_label(a, [ff.bits(4.0), 0]), "applied") - self.assertEqual(ff.omod_label(a, [ff.bits(2.0), 0]), "ignored") - self.assertEqual(ff.omod_label(a, [ff.bits(3.0), 0]), "other") - - def test_zero_inf_probes_catch_a_plain_multiply(self): - import random - cases = [ff.gen_probe(random.Random(i), "v_mul_legacy_f32", "zero_inf") for i in range(8)] - self.assertTrue(all(c is not None for c in cases)) - with ff.perturbed("legacy_is_ieee"): - bad = sum(ff.hw_verdict(c, [0, 0])[0] == "match" for c in cases) - self.assertLess(bad, len(cases)) - - def test_f16_nan_halves_compare_as_nan(self): - self.assertTrue(ff.hw_same([0x7E00, 0], [0x7E06, 0], "v_cvt_f16_f32")) - self.assertFalse(ff.hw_same([0x7E00, 0], [0x3C00, 0], "v_cvt_f16_f32")) - self.assertFalse(ff.hw_same([0x00007E00, 0], [0x00017E00, 0], "v_cvt_f16_f32")) # high half is kept exactly - - def test_negative_control_detects_each_perturbation(self): - self.assertTrue(ff.hw_self_test()) - - def test_denormal_variants_distinguish_flush_from_keep(self): - m = self.case("v_mul_f32", [1, ff.bits(1048576.0)], [(0, {}), (1, {})]) - self.assertEqual(ff.denorm_label(m, [0, 0]), ("operand", "ftz|ftz_in|ftz_out")) - self.assertEqual(ff.denorm_label(m, [ff.bits(2.0 ** -129), 0]), ("operand", "keep")) - - def test_hardware_only_ops_stay_out_of_the_translator_run(self): - self.assertTrue(set(ff.HW_ONLY_OPS).isdisjoint(ff.OPS)) - r = subprocess.run([sys.executable, "-I", self.TOOL, "--ops", "v_min_f32"], capture_output=True, text=True) - self.assertEqual(r.returncode, 2) - - def test_exit_77_without_the_oracle_tools(self): - env = dict(os.environ, LEONIDA_AMD_CLANG=os.path.join(ROOT, "tools", "no-such-clang.exe")) - r = subprocess.run([sys.executable, "-I", self.TOOL, "--oracle", "hw", "--programs", "2"], - capture_output=True, text=True, env=env) - self.assertEqual(r.returncode, 77, r.stdout + r.stderr) - self.assertIn("unavailable", r.stdout) - - def test_unknown_oracle_is_a_usage_error(self): - r = subprocess.run([sys.executable, "-I", self.TOOL, "--oracle", "gpu"], capture_output=True, text=True) - self.assertEqual(r.returncode, 2) - - def test_on_hardware(self): - from hw_oracle import runner - try: - oracle = runner.open_oracle() - except runner.Unavailable as e: - self.skipTest(f"hardware oracle unavailable: {e}") - from hw_oracle import asm - why = asm.rdna23_skip_reason(oracle.arch) - if why: - oracle.close() - self.skipTest(why) - try: - ff.hw_probe_modes(oracle) - cases = ff.gen_cases(300, 21, tuple(ff.ALL_OPS)) + ff.gen_probes(2, 21, tuple(ff.ALL_OPS)) - rep = ff.hw_suite(oracle, cases, info_modes=("keep",)) - finally: - oracle.close() - self.assertEqual([(c.op, c.index) for c, _, _ in rep.mismatches], []) - self.assertGreater(sum(r["match"] for r in rep.per_op.values()), 150) - for name, (n, bad) in ff.negative_control(rep).items(): - if n >= 20 and name in ("add_lsb", "mul_rtz", "rndne_floor", "min_ieee_nan"): - self.assertGreater(bad, 0, name) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/test_f64_conversion.py b/tests/test_f64_conversion.py deleted file mode 100644 index 514ef2398..000000000 --- a/tests/test_f64_conversion.py +++ /dev/null @@ -1,57 +0,0 @@ -"""Check the SPIR-V data flow for output modifiers on v_cvt_f32_f64.""" - -import re -import sys -import tempfile -import unittest -from pathlib import Path - -TEST_DIR = Path(__file__).resolve().parent -sys.path[:0] = [str(TEST_DIR.parent / "tools"), str(TEST_DIR)] - -from listing import translate_listing - -FIXTURE = TEST_DIR / "fixtures" / "f64_conversion.asm" - - -class F64ConversionTest(unittest.TestCase): - def test_output_modifiers(self): - body = "\n".join( - line for line in FIXTURE.read_text(encoding="utf-8").splitlines() - if not line.startswith(";") - ) - cases = ( - ("", None, False), - ("mul:2", 0x40000000, False), - ("mul:4", 0x40800000, False), - ("div:2", 0x3F000000, False), - ("clamp", None, True), - ("clamp div:2", 0x3F000000, True), - ) - with tempfile.TemporaryDirectory() as directory: - for modifiers, scale_bits, clamp in cases: - with self.subTest(modifiers=modifiers): - spv = translate_listing(Path(directory), f"{body} {modifiers}".rstrip()) - self.check_conversion(spv, scale_bits, clamp) - - def check_conversion(self, spv, scale_bits, clamp): - def result(instruction): - match = re.search(rf"^ *(%\w+) = {instruction}$", spv, re.M) - self.assertIsNotNone(match, f"Missing SPIR-V instruction: {instruction}") - return match.group(1) - - value = result(r"OpFConvert %float %\w+") - if scale_bits is not None: - constant = result(rf"OpConstant %uint {scale_bits}") - scale = result(rf"OpBitcast %float {constant}") - value = result(rf"OpFMul %float {value} {scale}") - if clamp: - value = result(rf"OpExtInst %float %glsl FClamp {value} %f0 %f1") - word = result(rf"OpBitcast %uint {value}") - dest = result(r"OpAccessChain %_ptr_Function_uint %vgpr %c3") - # This straight-line fixture keeps EXEC full, so the result is stored directly. - self.assertRegex(spv, rf"(?m)^ *OpStore {dest} {word}$") - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/test_f64_diff.py b/tests/test_f64_diff.py deleted file mode 100644 index ca53426b2..000000000 --- a/tests/test_f64_diff.py +++ /dev/null @@ -1,417 +0,0 @@ -"""CLI and reference checks for tools/f64_diff.py; standard library only.""" -import contextlib -import io -import os -import random -import subprocess -import sys -import tempfile -import unittest -from unittest import mock -from fractions import Fraction - -ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) -TOOL = os.path.join(ROOT, "tools", "f64_diff.py") -sys.path.insert(0, os.path.join(ROOT, "tools")) -import f64_diff as fd - - -class F64DiffTests(unittest.TestCase): - def command(self, *args): - return subprocess.run([sys.executable, "-I", TOOL, *args], cwd=ROOT, - capture_output=True, text=True, timeout=60) - - def test_cli_self_test(self): - self.assertEqual(self.command("--self-test").returncode, 0) - - def test_lists_47_supported_forms_and_exclusions(self): - result = self.command("--list-ops") - listed = [line for line in result.stdout.splitlines() if line.startswith("v_")] - self.assertEqual(result.returncode, 0) - self.assertEqual(len(listed), 47) - self.assertIn("v_div_scale_f64", result.stdout) - - def test_exit_2_for_invalid_cli(self): - self.assertEqual(self.command("--ops", "v_not_real_f64").returncode, 2) - self.assertEqual(self.command("--programs", "-1").returncode, 2) - - def test_reference_reads_a_literal_by_its_printed_width(self): - # The translator's rule, mirrored: a spelling of more than 8 hex digits is the whole word, - # so a padded value that fits 32 bits is not shifted into the high half. - self.assertEqual(fd.read_source("0x12345678", {}, {}), 0x12345678_00000000) - self.assertEqual(fd.read_source("0x0000000012345678", {}, {}), 0x0000000012345678) - self.assertEqual(fd.read_source("0x3ff80000", {}, {}), 0x3FF80000_00000000) - self.assertEqual(fd.read_source("1", {}, {}), 1) - - def test_reference_rounds_all_four_binary64_modes(self): - half_ulp = Fraction(1, 1 << 53) - self.assertEqual(fd.round_fraction(Fraction(1) + half_ulp, 0), 0x3FF0000000000000) - self.assertEqual(fd.round_fraction(Fraction(1) + half_ulp, 1), 0x3FF0000000000001) - self.assertEqual(fd.round_fraction(Fraction(1) + half_ulp, 2), 0x3FF0000000000000) - self.assertEqual(fd.round_fraction(Fraction(1) + half_ulp, 3), 0x3FF0000000000000) - self.assertEqual(fd.round_fraction(-(Fraction(1) + half_ulp), 1), 0xBFF0000000000000) - self.assertEqual(fd.round_fraction(-(Fraction(1) + half_ulp), 2), 0xBFF0000000000001) - - def test_nan_tolerance_preserves_integer_low_word_after_partial_write(self): - expected = [0, 0x7FF80000, 0, 0] - actual = [0, 0xFFFFFFFF, 0, 0] - self.assertTrue(fd.equivalent(expected, actual, ("int", "f64"))) - self.assertFalse(fd.equivalent([1, *expected[1:]], actual, ("int", "f64"))) - self.assertFalse(fd.equivalent(expected, actual, ("int", "int"))) - - def test_exit_77_when_requested_oracle_is_unavailable(self): - env = dict(os.environ, LEONIDA_AMD_CLANG=os.path.join(ROOT, "tools", "no-such-clang.exe")) - hw = subprocess.run([sys.executable, "-I", TOOL, "--oracle", "hw", "--programs", "3"], cwd=ROOT, - capture_output=True, text=True, timeout=120, env=env) - self.assertEqual(hw.returncode, 77, hw.stdout + hw.stderr) - self.assertIn("hardware oracle unavailable", hw.stderr) - self.assertEqual(self.command("--oracle", "gpu", "--exe", "missing.exe").returncode, 77) - self.assertEqual(self.command("--oracle", "gpu", "--exe", "missing.exe", "--ops", "not_f64").returncode, 2) - - def test_skips_are_counted_with_reason(self): - result = self.command("--ops", "v_cvt_f32_f64", "--programs", "0") - self.assertEqual(result.returncode, 0) - self.assertIn("1 total", result.stdout) - self.assertIn("OpFConvert", result.stdout) - - def test_sqrt_preserves_negative_zero(self): - self.assertEqual(fd.ref_program(["v_sqrt_f64 v[8:9], -0.0"]), [0, 0x80000000, 0, 0]) - - def test_rsq_subnormal_is_an_explicit_skip(self): - lines = ["v_mov_b32 v12, 0x00000001", "v_mov_b32 v13, 0x00000000", - "v_rsq_f64 v[8:9], v[12:13]"] - with tempfile.TemporaryDirectory() as tmp: - status, reason, _, _ = fd.run_one(lines, "ps_f64_subnormal", tmp) - self.assertEqual(status, "skip") - self.assertIn("subnormal", reason) - self.assertIn("FTZ", reason) - - def test_gpu_rsq_precision_is_counted_as_unjudged(self): - with tempfile.TemporaryDirectory() as tmp: - status, reason, _, actual = fd.run_one(["v_rsq_f64 v[8:9], 3.25"], - "ps_f64_gpu_rsq_precision", tmp, "gpu", {"exe": "unused"}) - self.assertEqual(status, "skip") - self.assertIn("implementation-defined", reason) - self.assertIsNone(actual) - - def test_div_fixup_nan_s0_is_skipped_by_default_and_runs_with_known(self): - setup, body, _, _ = fd.make_case(random.Random(1), "v_div_fixup_f64", known_case="div-fixup-nan-s0") - lines = setup + body - with tempfile.TemporaryDirectory() as tmp: - skipped = fd.run_one(lines, "ps_f64_fixup_default", tmp) - self.assertEqual(skipped[0], "skip") - self.assertIn("div-fixup-nan-s0", skipped[1]) - known = fd.run_one(lines, "ps_f64_fixup_known", tmp, include_known=True) - # the translator now gives the ISA's signed infinity for NaN(S0) too (#4536 was written when it kept the NaN) - self.assertEqual(known[0], "match") - - def test_compare_reference_does_not_write_v8_without_cndmask(self): - for op in ("v_cmp_eq_f64_e64 s20, v[12:13], 0.0", - "v_cmp_class_f64_e64 s20, v[12:13], 0x3ff"): - result = fd.ref_program(["v_mov_b32 v8, 0x12345678", "v_mov_b32 v12, 0x00000000", - "v_mov_b32 v13, 0x3ff00000", op]) - self.assertEqual(result[0], 0x12345678) - - def test_hw_oracle_reference_starts_with_one_lane_in_exec(self): - # The hardware kernel is one lane, so a v_cmpx that hits leaves EXEC = 1 and `s_mov_b32 s22, exec_lo` reads 1; - # the all-lanes reference said 0xffffffff, so every v_cmpx case was a false mismatch on --oracle hw. The - # words are what gfx1036 returned for this program (RDNA2 iGPU, Windows driver 32.0.21045.16010). - lines = ["s_mov_b32 s6, 0x66466f79", "s_mov_b32 s7, 0x2df96874", - "v_mov_b32 v8, 0x1081490d", "v_mov_b32 v9, 0xfdeb0203", - "v_mov_b32 v10, 0xa1ef942f", "v_mov_b32 v11, 0xfedbc06e", - "s_mov_b32 s10, exec_lo", "v_cmpx_lt_f64_e64 0xc83d5d11, |s[6:7]|", - "s_mov_b32 s22, exec_lo", "s_mov_b32 exec_lo, s10", "v_mov_b32 v9, s22", - "v_cmp_lt_f64_e64 s20, 0xc83d5d11, |s[6:7]|", "v_cndmask_b32_e64 v8, 0, 1, s20"] - hardware = [0x00000001, 0x00000001, 0xA1EF942F, 0xFEDBC06E] - with tempfile.TemporaryDirectory() as tmp: - status, _, _, _ = fd.run_one(lines, "ps_f64_hw_exec", tmp, "hw", hw_words=hardware) - self.assertEqual(status, "match") - self.assertEqual(fd.ref_program(lines)[1], 0xFFFFFFFF) # the translator's all-lanes view is unchanged - self.assertEqual(fd.ref_program(lines, exec_lo=1)[1], 1) - - def test_shrink_reuses_prepared_gpu_context(self): - context = {"exe": "fake"} - observed = [] - def fake_run_one(lines, name, tmp, oracle, gpu_ctx, include_known=False): - observed.append(gpu_ctx) - return ("mismatch" if len(lines) > 1 else "match", "", [], []) - with tempfile.TemporaryDirectory() as tmp, \ - mock.patch.object(fd, "prepare_gpu", side_effect=AssertionError("GPU setup repeated")), \ - mock.patch.object(fd, "run_one", side_effect=fake_run_one): - reduced = fd.shrink(["first", "second"], [], "gpu", "fake.exe", context, tmp) - self.assertEqual(reduced, ["first", "second"]) - self.assertTrue(observed) - self.assertTrue(all(item is context for item in observed)) - - def test_known_divergences_only_reinserted_with_known(self): - normal = self.command("--ops", "v_add_f64", "--programs", "0") - known = self.command("--ops", "v_add_f64", "--programs", "0", "--no-sweep", "--known", "--all-failures") - self.assertNotIn("KNOWN_DIVERGENCE", normal.stdout) - # the known NaN(S0) case runs and, since the translator follows the ISA there, matches - self.assertEqual(known.returncode, 0, known.stdout) - self.assertNotIn("MISMATCH:", known.stdout) - - def test_sabotaged_translator_mismatch_and_shrinking(self): - lines = ["v_mov_b32 v12, 0x00000000", "v_mov_b32 v13, 0x3ff80000", - "v_trunc_f64 v[8:9], v[12:13]"] - original = fd.translate - def planted_bug(listing, name, temp): - out = original(listing, name, temp) - if any(line.startswith("v_trunc_f64 ") for line in listing): out[0] ^= 1 - return out - try: - fd.translate = planted_bug - with tempfile.TemporaryDirectory() as tmp: - status, _, expected, actual = fd.run_one(lines, "ps_f64_negative_control", tmp) - self.assertEqual(status, "mismatch") - self.assertNotEqual(expected, actual) - reduced = fd.shrink(lines, expected) - self.assertEqual(len(reduced), 1) - self.assertTrue(reduced[0].startswith("v_trunc_f64 ")) - finally: - fd.translate = original - - # ---- the reference functions, checked against hand-written tables (no shared code with the reference) ---- - - ONE, TWO, THREE = 0x3FF0000000000000, 0x4000000000000000, 0x4008000000000000 - NEG1, NEG2, NEG3 = 0xBFF0000000000000, 0xC000000000000000, 0xC008000000000000 - PZ, NZ = 0, 0x8000000000000000 - PINF, NINF = 0x7FF0000000000000, 0xFFF0000000000000 - QNAN, SNAN = 0x7FF8000000000000, 0x7FF0000000000001 - - def test_compare_table_all_16_conditions(self): - # Which of the four relations (lt, eq, gt, un) make each condition true: the ISA's definitions, written out. - true_for = { - "f": set(), "lt": {"lt"}, "eq": {"eq"}, "le": {"lt", "eq"}, "gt": {"gt"}, "lg": {"lt", "gt"}, - "ge": {"gt", "eq"}, "o": {"lt", "eq", "gt"}, "u": {"un"}, "nge": {"lt", "un"}, "nlg": {"eq", "un"}, - "ngt": {"lt", "eq", "un"}, "nle": {"gt", "un"}, "neq": {"lt", "gt", "un"}, "nlt": {"gt", "eq", "un"}, - "tru": {"lt", "eq", "gt", "un"}, - } - self.assertEqual(set(true_for), set(fd.CONDS)) - self.assertEqual(len(fd.CONDS), 16) - pairs = [(self.ONE, self.TWO, "lt"), (self.TWO, self.ONE, "gt"), (self.ONE, self.ONE, "eq"), - (self.NEG1, self.ONE, "lt"), (self.ONE, self.NEG1, "gt"), (self.NEG2, self.NEG2, "eq"), - (self.PZ, self.NZ, "eq"), (self.NZ, self.PZ, "eq"), (self.PZ, self.PZ, "eq"), (self.NZ, self.NZ, "eq"), - (0x8000000000000001, self.PZ, "lt"), (self.PZ, 1, "lt"), (1, 0x8000000000000001, "gt"), - (self.PINF, self.PINF, "eq"), (self.NINF, self.NINF, "eq"), (self.NINF, self.PINF, "lt"), - (self.PINF, self.NINF, "gt"), (self.PINF, self.ONE, "gt"), (self.NINF, self.ONE, "lt"), - (self.ONE, self.PINF, "lt"), (self.QNAN, self.ONE, "un"), (self.ONE, self.QNAN, "un"), - (self.QNAN, self.QNAN, "un"), (self.SNAN, self.ONE, "un"), (self.ONE, self.SNAN, "un"), - (self.QNAN, self.PINF, "un"), (self.NINF, self.QNAN, "un"), (self.QNAN, self.PZ, "un")] - for cond, relations in true_for.items(): - for a, b, relation in pairs: - with self.subTest(cond=cond, a=hex(a), b=hex(b)): - self.assertEqual(fd.compare(cond, a, b), int(relation in relations)) - - def test_class_table_all_ten_classes_and_boundaries(self): - table = [ - (0x7FF0000000000001, 0), (0xFFF0000000000001, 0), (0x7FF7FFFFFFFFFFFF, 0), # signalling NaN, any sign - (0x7FF8000000000000, 1), (0xFFF8000000000000, 1), (0xFFFFFFFFFFFFFFFF, 1), # quiet NaN, any payload - (self.NINF, 2), (self.NEG1, 3), (0xFFEFFFFFFFFFFFFF, 3), (0x8010000000000000, 3), - (0x800FFFFFFFFFFFFF, 4), (0x8000000000000001, 4), (self.NZ, 5), (self.PZ, 6), - (1, 7), (0x000FFFFFFFFFFFFF, 7), (0x0010000000000000, 8), (self.ONE, 8), - (0x7FEFFFFFFFFFFFFF, 8), (self.PINF, 9), - ] - for bits, want in table: - with self.subTest(bits=hex(bits)): - self.assertEqual(fd.class_index(bits), want) - self.assertEqual({want for _, want in table}, set(range(10))) - - def test_div_fixup_table(self): - one, two, three = self.ONE, self.TWO, self.THREE - e = lambda exp: exp << 52 # a biased exponent field with a zero fraction - qn2 = 0x7FF8000000000012 - table = [ - ("normal", three, one, one, three), - ("sign_out_negative_from_s1", three, self.NEG2, one, three | self.NZ), - ("sign_out_positive_both_negative", self.NEG3, self.NEG2, self.NEG1, three), - ("sign_out_clears_s0_sign", self.NEG3, one, one, three), - ("nan_s2_quiets_s2", one, one, self.SNAN, 0x7FF8000000000001), - ("nan_s2_beats_nan_s1", one, self.SNAN, qn2, qn2), - ("nan_s1_quiets_s1", one, self.SNAN, one, 0x7FF8000000000001), - ("nan_s2_beats_zero_over_zero", one, self.PZ, qn2, qn2), - ("zero_over_zero", one, self.PZ, self.NZ, 0xFFF8000000000000), - ("inf_over_inf", one, self.PINF, self.NINF, 0xFFF8000000000000), - ("x_over_inf_negative_zero", one, self.NINF, one, self.NZ), - ("x_over_inf_positive_zero", one, self.PINF, one, self.PZ), - ("zero_over_y", one, self.NEG2, self.NZ, self.PZ), - ("x_over_zero", one, self.NZ, one, self.NINF), - ("inf_over_y", one, self.NEG2, self.NINF, self.PINF), - ("nan_s0_to_signed_inf_isa_rule", self.QNAN, one, one, self.PINF), - ("nan_s0_to_signed_inf_negative", self.QNAN, self.NEG2, one, self.NINF), - ("underflow_edge_still_passes_s0", three, e(1075), e(1), three), - ("underflow_to_zero", three, e(1076), e(1), self.PZ), - ("underflow_beats_nan_s0", self.QNAN, e(1076), e(1), self.PZ), - ("overflow_edge_still_passes_s0", three, e(1), e(1024), three), - ("overflow_to_inf", three, e(1), e(1025), self.PINF), - ] - for name, s0, s1, s2, want in table: - with self.subTest(case=name): - self.assertEqual(fd.fixup(s0, s1, s2), want) - - def test_frexp_table(self): - half = 0x3FE0000000000000 - table = [ - (self.ONE, half, 1), (half, half, 0), (self.THREE, 0x3FE8000000000000, 2), (self.NEG2, self.NZ | half, 2), - (0xC020000000000000, self.NZ | half, 4), # -8 = -0.5 * 2**4 - (1, half, -1073), (3, 0x3FE8000000000000, -1072), # smallest subnormals - (0x000FFFFFFFFFFFFF, 0x3FEFFFFFFFFFFFFE, -1022), - (0x0010000000000000, half, -1021), (0x7FEFFFFFFFFFFFFF, 0x3FEFFFFFFFFFFFFF, 1024), - (self.PZ, self.PZ, 0), (self.NZ, self.NZ, 0), (self.PINF, self.PINF, 0), (self.NINF, self.NINF, 0), - (self.QNAN, self.QNAN, 0), (self.SNAN, self.SNAN, 0), - ] - for bits, mant, exp in table: - with self.subTest(bits=hex(bits)): - self.assertEqual(fd.frexp(bits), (mant, exp)) - - def test_add_bits_nan_inf_and_zero_table(self): - for a, b in ((self.QNAN, self.ONE), (self.ONE, self.QNAN), (self.SNAN, self.ONE), (self.QNAN, self.QNAN), - (self.PINF, self.NINF), (self.NINF, self.PINF), (self.QNAN, self.PINF)): - for mode in range(4): - with self.subTest(a=hex(a), b=hex(b), mode=mode): - self.assertTrue(fd.is_nan(fd.add_bits(a, b, mode))) - for a, b, want in ((self.PINF, self.ONE, self.PINF), (self.ONE, self.NINF, self.NINF), - (self.PINF, self.PINF, self.PINF), (self.NINF, self.NINF, self.NINF)): - for mode in range(4): - with self.subTest(a=hex(a), b=hex(b), mode=mode): - self.assertEqual(fd.add_bits(a, b, mode), want) - - def test_add_bits_exact_zero_sign_in_all_four_modes(self): - # IEEE 754-2019 6.3. Modes: 0 nearest even, 1 toward +inf, 2 toward -inf, 3 toward zero. - tiny = 1 # the smallest subnormal, so x + (-x) is an exact non-zero cancellation - cases = [ - ("+0 + +0", self.PZ, self.PZ, (self.PZ, self.PZ, self.PZ, self.PZ)), - ("-0 + -0", self.NZ, self.NZ, (self.NZ, self.NZ, self.NZ, self.NZ)), - ("+0 + -0", self.PZ, self.NZ, (self.PZ, self.PZ, self.NZ, self.PZ)), - ("-0 + +0", self.NZ, self.PZ, (self.PZ, self.PZ, self.NZ, self.PZ)), - ("1 + -1", self.ONE, self.NEG1, (self.PZ, self.PZ, self.NZ, self.PZ)), - ("-1 + 1", self.NEG1, self.ONE, (self.PZ, self.PZ, self.NZ, self.PZ)), - ("tiny + -tiny", tiny, tiny | self.NZ, (self.PZ, self.PZ, self.NZ, self.PZ)), - ] - for name, a, b, wants in cases: - for mode, want in enumerate(wants): - with self.subTest(case=name, mode=mode): - self.assertEqual(fd.add_bits(a, b, mode), want) - # A non-zero result keeps its own sign whatever the mode. - self.assertEqual(fd.add_bits(self.ONE, self.ONE, 2), self.TWO) - self.assertEqual(fd.add_bits(self.PZ, self.NEG1, 2), self.NEG1) - - # ---- --oracle hw: routed through tools/hw_oracle, compared with the reference (a fake stands in for the GPU) ---- - - class FakeHW: - """Answers each raw kernel with the reference's own result, as a hardware stand-in; flip corrupts v_trunc_f64.""" - device = "fake gfx1036" - - def __init__(self, flip=False, reason=None): - self.flip, self.reason, self.calls, self.closed = flip, reason, [], False - - def run(self, kernels): - self.calls.append(list(kernels)) - out = [] - for kernel in kernels: - if self.reason: - out.append(self.reason) - continue - try: - words = fd.ref_program(kernel.lines[:-3], True, exec_lo=1) # drop the store epilogue; one lane, EXEC = 1 - except (fd.SkipCase, ArithmeticError, IndexError, KeyError, ValueError): - out.append("assembler rejected: fake") - continue - broken = self.flip and any(line.startswith("v_trunc_f64 ") for line in kernel.lines) # a planted hardware bug - out.append([words[0] ^ 1] + list(words[1:]) if broken else list(words)) - return out - - def close(self): - self.closed = True - - def run_main(self, fake, *args): - stdout, stderr = io.StringIO(), io.StringIO() - with mock.patch.object(fd, "open_hw_oracle", return_value=fake) as opener, \ - mock.patch.object(fd, "translate", side_effect=AssertionError("the translator must not run")), \ - contextlib.redirect_stdout(stdout), contextlib.redirect_stderr(stderr): - code = fd.main(["--oracle", "hw", *args]) - return code, stdout.getvalue(), stderr.getvalue(), opener - - def test_hw_oracle_routes_programs_through_hw_oracle_and_uses_hw_arch(self): - fake = self.FakeHW() - code, out, _, opener = self.run_main(fake, "--hw-arch", "gfx1036", "--programs", "40", "--seed", "1") - self.assertEqual(code, 0, out) - opener.assert_called_once_with("gfx1036") - self.assertIn("hw: ", out) - self.assertIn(" 0 mismatch", out) - self.assertIn("fake gfx1036", out) - self.assertTrue(fake.closed) - self.assertEqual(len(fake.calls), 1) # one launch for the whole campaign - kernel = fake.calls[0][0] - self.assertEqual(kernel.lines[-1], "s_endpgm") - self.assertTrue(kernel.raw and kernel.threads == 1 and kernel.words == 4) - self.assertEqual(kernel.mode, fd.HW_MODE) - self.assertGreater(len(fake.calls[0]), 40) # sweep + programs - matches = int(out.split("hw: ")[1].split(" match")[0]) - self.assertGreater(matches, 60) - - def test_hw_oracle_with_known_runs_known_cases_against_the_reference(self): - fake = self.FakeHW() - code, out, _, _ = self.run_main(fake, "--known", "--programs", "20", "--seed", "2") - self.assertEqual(code, 0, out) - self.assertNotIn("KNOWN_DIVERGENCE", out) # translator-only exclusions do not apply to hardware - texts = [line for kernel in fake.calls[0] for line in kernel.lines] - self.assertTrue(any(" mul:2" in line for line in texts)) - self.assertTrue(any(" clamp" in line for line in texts)) - - def test_hw_oracle_mismatch_exits_1_and_shrinks_with_single_runs(self): - fake = self.FakeHW(flip=True) - code, out, _, _ = self.run_main(fake, "--ops", "v_trunc_f64", "--programs", "0") - self.assertEqual(code, 1, out) - self.assertIn("MISMATCH", out) - self.assertIn("minimal program:", out) - self.assertIn("v_trunc_f64", out) - self.assertGreater(len(fake.calls), 1) # the shrinker re-ran trial programs - self.assertTrue(all(len(batch) == 1 for batch in fake.calls[1:])) - self.assertTrue(fake.closed) - - def test_hw_oracle_skip_reason_from_runner_is_counted(self): - fake = self.FakeHW(reason="MODE dx10_clamp, ieee cannot be set on gfx1170") - code, out, _, _ = self.run_main(fake, "--ops", "v_trunc_f64", "--programs", "3") - self.assertEqual(code, 0, out) - self.assertIn("hardware: MODE dx10_clamp", out) - self.assertIn("0 match, 0 mismatch", out) - - def test_hw_oracle_unavailable_exits_77_without_running(self): - stderr = io.StringIO() - with mock.patch.object(fd, "open_hw_oracle", side_effect=fd.HWUnavailable("no AMD clang")), \ - contextlib.redirect_stderr(stderr): - code = fd.main(["--oracle", "hw", "--programs", "3"]) - self.assertEqual(code, 77) - self.assertIn("hardware oracle unavailable: no AMD clang", stderr.getvalue()) - - def test_hw_oracle_does_not_judge_approximate_transcendentals(self): - fake = self.FakeHW() - with tempfile.TemporaryDirectory() as tmp: - for op in ("v_rcp_f64", "v_rsq_f64", "v_sqrt_f64"): - status, reason, _, actual = fd.run_one([f"{op} v[8:9], 3.25"], "ps_f64_hw_approx", tmp, "hw", fake) - self.assertEqual(status, "skip") - self.assertIn("PROC-216", reason) - self.assertIsNone(actual) - self.assertEqual(fake.calls, []) - - def test_hw_oracle_open_failure_without_tools_is_hwunavailable(self): - env = dict(os.environ, LEONIDA_AMD_CLANG=os.path.join(ROOT, "tools", "no-such-clang.exe")) - with mock.patch.dict(os.environ, env), self.assertRaises(fd.HWUnavailable): - fd.open_hw_oracle("gfx1036") - - def test_cli_exit_1_on_plantable_mismatch(self): - original = fd.translate - stdout = io.StringIO() - try: - fd.translate = lambda listing, name, temp: [0xDEADBEEF, 0, 0, 0] - with contextlib.redirect_stdout(stdout): - code = fd.main(["--ops", "v_trunc_f64", "--programs", "0"]) - finally: - fd.translate = original - self.assertEqual(code, 1) - self.assertIn("minimal program:", stdout.getvalue()) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/test_f64_float_controls.py b/tests/test_f64_float_controls.py deleted file mode 100644 index 0b14dfaa7..000000000 --- a/tests/test_f64_float_controls.py +++ /dev/null @@ -1,75 +0,0 @@ -"""SHADER-597: a module that uses Float64 also declares SignedZeroInfNanPreserve 64. - -Without it Vulkan lets the driver assume no -0, NaN or inf in 64-bit float ops (shaderSignedZeroInfNanPreserveFloat64), -so f64 results such as -0 + -0 = -0 would rest on driver defaults. The 32-bit mode (SHADER-99, #664) is declared in -every module; the 64-bit one only where Float64 is, under the same --no-float-controls opt-out, and the index entry -names both properties so vk_pipeline_check skips the shader on a device that reports either one false. -""" - -import sys -import tempfile -import unittest -from pathlib import Path - -TEST_DIR = Path(__file__).resolve().parent -sys.path[:0] = [str(TEST_DIR.parent / "tools"), str(TEST_DIR)] - -import rdna2spirv -from listing import translate_listing - -# -0 + -0 in doubles: v[0:1] = v[6:7] = -0.0 (low word first); the sum goes to v[4:5]. -F64_BODY = """v_mov_b32 v0, 0 -v_mov_b32 v1, 0x80000000 -v_mov_b32 v6, 0 -v_mov_b32 v7, 0x80000000 -v_add_f64 v[4:5], v[0:1], v[6:7]""" -F32_BODY = """v_mov_b32 v2, 0x80000000 -v_add_f32 v3, v2, v2""" - -MODE_32 = "OpExecutionMode %main SignedZeroInfNanPreserve 32" -MODE_64 = "OpExecutionMode %main SignedZeroInfNanPreserve 64" - - -class F64FloatControlsTest(unittest.TestCase): - def translate(self, body, name): - with tempfile.TemporaryDirectory() as directory: - spv = translate_listing(Path(directory), body, name=name) - return spv, rdna2spirv.shader_meta(rdna2spirv.translate.last_gen, spv) - - def test_f64_module_declares_the_64_bit_mode(self): - spv, meta = self.translate(F64_BODY, "ps_f64_float_controls") - self.assertIn("OpCapability Float64", spv) - self.assertEqual(spv.count("OpCapability SignedZeroInfNanPreserve\n"), 1) - self.assertIn(MODE_32, spv) - self.assertIn(MODE_64, spv) - # Core since SPIR-V 1.4, as for the 32-bit mode: no SPV_KHR_float_controls at vulkan1.2. - self.assertNotIn("SPV_KHR_float_controls", spv) - # DenormPreserve 16 (SHADER-526) is declared in every module and its property comes after the two widths. - self.assertEqual(meta["float_controls"], - ["shaderSignedZeroInfNanPreserveFloat32", "shaderSignedZeroInfNanPreserveFloat64", - "shaderDenormPreserveFloat16"]) - self.assertIn("shaderFloat64", meta["features"]) - - def test_module_without_float64_keeps_only_the_32_bit_mode(self): - spv, meta = self.translate(F32_BODY, "ps_f32_float_controls") - self.assertNotIn("OpCapability Float64", spv) - self.assertIn(MODE_32, spv) - self.assertNotIn(MODE_64, spv) - self.assertEqual(meta["float_controls"], - ["shaderSignedZeroInfNanPreserveFloat32", "shaderDenormPreserveFloat16"]) - - def test_no_float_controls_leaves_out_both_widths(self): - saved = rdna2spirv.FLOAT_CONTROLS - rdna2spirv.FLOAT_CONTROLS = False - try: - spv, meta = self.translate(F64_BODY, "ps_f64_no_float_controls") - finally: - rdna2spirv.FLOAT_CONTROLS = saved - self.assertIn("OpCapability Float64", spv) - self.assertNotIn("SignedZeroInfNanPreserve", spv) - self.assertNotIn("DenormPreserve", spv) - self.assertNotIn("float_controls", meta) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/test_f64_omod_probe.py b/tests/test_f64_omod_probe.py deleted file mode 100644 index a1f63fb4c..000000000 --- a/tests/test_f64_omod_probe.py +++ /dev/null @@ -1,189 +0,0 @@ -"""Unit tests for tools/f64_omod_probe.py (gate model, simulated oracle verdicts, CLI). - -Standard library only; no GPU and no game files. The simulated oracle follows the gate the probe measures, and the -broken variants exist so the probe has to prove it reports a device that disagrees. -""" -import io -import json -import math -import os -import struct -import sys -import tempfile -import unittest -from contextlib import redirect_stderr, redirect_stdout -from pathlib import Path -from unittest import mock - -TOOLS = Path(__file__).resolve().parents[1] / "tools" -sys.dont_write_bytecode = True -if str(TOOLS) not in sys.path: - sys.path.insert(0, str(TOOLS)) - -import f64_omod_probe as pr # noqa: E402 -from hw_oracle import runner # noqa: E402 - -OP_KINDS = {op: kind for op, _form, kind, _cases in pr.OPS} - - -def f32(value): - return struct.unpack(" 1: - mod = parts[-1] - kind, value = plain_of(op, regs, mode) - scaling_on = True if self.apply_scaling_everywhere else pr.scaling_applies(kind, mode) - if mod in pr.SCALE and scaling_on and math.isfinite(value): - value = value * pr.SCALE[mod] - elif mod == "clamp" and math.isfinite(value): - value = min(max(value, 0.0), 1.0) - words.extend(pr.scalar_bits(value, kind)[:pr.word_count(kind)]) - if self.wave64_differs and kernel.wave == 64 and words: - words[0] ^= 1 - out.append(words) - return out - - def close(self): - self.closed = True - - -def run_main(argv, oracle): - out, err = io.StringIO(), io.StringIO() - with mock.patch.object(runner, "open_oracle", return_value=oracle): - with redirect_stdout(out), redirect_stderr(err): - code = pr.main(argv) - return code, out.getvalue(), err.getvalue() - - -class GateModelTests(unittest.TestCase): - def test_gate_is_per_result_precision(self): - game, flush = pr.MODES["game_i0_d3"], pr.MODES["i0_d0"] - keep32, ieee = pr.MODES["i0_d3_f32keep"], pr.MODES["i1_d0"] - for kind in ("f64", "f16"): - self.assertFalse(pr.scaling_applies(kind, game)) - self.assertTrue(pr.scaling_applies(kind, flush)) - self.assertFalse(pr.scaling_applies(kind, keep32)) - self.assertFalse(pr.scaling_applies(kind, ieee)) - # An f32 destination is flushed by denorm32, so it scales in the game mode too. - self.assertTrue(pr.scaling_applies("f32", game)) - self.assertTrue(pr.scaling_applies("f32", flush)) - self.assertFalse(pr.scaling_applies("f32", keep32)) - self.assertFalse(pr.scaling_applies("f32", ieee)) - - def test_clamp_and_non_finite_results(self): - game = pr.MODES["game_i0_d3"] - self.assertEqual(pr.expected_words(pr.scalar_bits(-0.875, "f64"), "clamp", "f64", game), - pr.scalar_bits(0.0, "f64")[:2]) - self.assertEqual(pr.expected_words(pr.scalar_bits(2.0, "f16"), "clamp", "f16", game)[:1], - pr.scalar_bits(1.0, "f16")[:1]) - inf = pr.scalar_bits(float("inf"), "f64")[:2] - self.assertEqual(pr.expected_words(inf, "mul:2", "f64", pr.MODES["i0_d0"]), inf) - self.assertEqual(pr.expected_words(inf, "clamp", "f64", game), inf) - - def test_self_test_reports_the_case_counts(self): - out = io.StringIO() - with redirect_stdout(out): - self.assertEqual(pr.main(["--self-test"]), 0) - self.assertIn("self-test ok", out.getvalue()) - - -class ProbeCliTests(unittest.TestCase): - def test_device_following_the_gate_is_accepted(self): - with tempfile.TemporaryDirectory() as work: - report = os.path.join(work, "probe.json") - code, out, err = run_main(["--waves", "32,64", "--json", report], FakeOracle()) - self.assertEqual((code, err), (0, "")) - self.assertIn("mismatches=0, wave_diffs=0", out) - with open(report, encoding="utf-8") as fh: - data = json.load(fh) - self.assertEqual(data["arch"], "gfx1036") - self.assertEqual(data["modes"], list(pr.MODES)) - self.assertEqual(data["mismatches"], 0) - self.assertEqual(data["wave_diffs"], 0) - # The 16/64-bit results keep the scaling only in the flushing mode; the f32 result keeps it in two. - scaled_modes = {mode for mode in pr.MODES if pr.scaling_applies("f64", pr.MODES[mode])} - self.assertEqual(scaled_modes, {"i0_d0"}) - self.assertEqual({mode for mode in pr.MODES if pr.scaling_applies("f32", pr.MODES[mode])}, - {"i0_d0", "game_i0_d3"}) - self.assertGreater(data["scaling_gated_on"], 0) - self.assertGreater(data["scaling_gated_off"], data["scaling_gated_on"]) - - def test_device_that_ignores_the_mode_gate_is_reported(self): - code, out, err = run_main(["--waves", "32"], FakeOracle(apply_scaling_everywhere=True)) - self.assertEqual(code, 1) - self.assertIn("MISMATCH game_i0_d3", out) - self.assertIn("v_cvt_f64_i32", out) - - def test_wave32_wave64_difference_is_reported(self): - code, out, _err = run_main(["--waves", "32,64"], FakeOracle(wave64_differs=True)) - self.assertEqual(code, 1) - self.assertIn("WAVE DIFF", out) - - def test_unavailable_or_non_gfx10_oracle_exits_77(self): - with mock.patch.object(runner, "open_oracle", side_effect=runner.Unavailable("no device")): - out = io.StringIO() - with redirect_stdout(out): - self.assertEqual(pr.main([]), 77) - self.assertIn("hardware oracle unavailable", out.getvalue()) - code, out, _err = run_main([], FakeOracle(arch="gfx1100")) - self.assertEqual((code, out.strip()), (77, "hardware oracle unavailable: gfx1100 is not GFX10")) - - def test_unknown_mode_is_a_cli_error(self): - with self.assertRaises(SystemExit) as caught: - with redirect_stderr(io.StringIO()): - pr.main(["--modes", "game_i0_d3,not_a_mode"]) - self.assertEqual(caught.exception.code, 2) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/test_f64_output_modifiers.py b/tests/test_f64_output_modifiers.py deleted file mode 100644 index badde3613..000000000 --- a/tests/test_f64_output_modifiers.py +++ /dev/null @@ -1,96 +0,0 @@ -"""Check the SPIR-V data flow for output modifiers (omod, then clamp) on v_add_f64. - -LLVM defines v_add_f64 as VOP3Inst<"v_add_f64", VOP3_Profile>; VOPProfile gives it HasClamp -(f64 is a modifier type) and HasOMod (its destination is floating point). runtime/test/shaders/ps_f64_mods.asm is -the matching GPU test. -""" - -import re -import struct -import sys -import tempfile -import unittest -from pathlib import Path - -TEST_DIR = Path(__file__).resolve().parent -sys.path[:0] = [str(TEST_DIR.parent / "tools"), str(TEST_DIR)] - -from listing import translate_listing - -# a = 0.75 in v[0:1], b = 0.5 in v[6:7] (low word first); the sum goes to v[4:5]. -BODY = """v_mov_b32 v0, 0 -v_mov_b32 v1, 0x3fe80000 -v_mov_b32 v6, 0 -v_mov_b32 v7, 0x3fe00000 -v_add_f64 v[4:5], v[0:1], v[6:7]""" - - -def words(x): - bits = struct.unpack("> 32 - - -class F64OutputModifiersTest(unittest.TestCase): - def test_add_f64_output_modifiers(self): - cases = ( - ("", None, False), - ("mul:2", 2.0, False), - ("mul:4", 4.0, False), - ("div:2", 0.5, False), - ("clamp", None, True), - ("clamp div:2", 0.5, True), - ("mul:4 clamp", 4.0, True), - ) - with tempfile.TemporaryDirectory() as directory: - for modifiers, scale, clamp in cases: - with self.subTest(modifiers=modifiers): - spv = translate_listing(Path(directory), f"{BODY} {modifiers}".rstrip()) - self.check_add(spv, scale, clamp) - - def check_add(self, spv, scale, clamp): - def result(instruction): - match = re.search(rf"^ *(%\w+) = {instruction}$", spv, re.M) - self.assertIsNotNone(match, f"Missing SPIR-V instruction: {instruction}") - return match.group(1) - - def double(x): - lo, hi = words(x) - pair = result(rf"OpCompositeConstruct %v2uint_d {result(f'OpConstant %uint {lo}')} " - rf"{result(f'OpConstant %uint {hi}')}") - return result(rf"OpBitcast %double {pair}") - - value = result(r"OpFAdd %double %\w+ %\w+") - if scale is not None: - value = result(rf"OpFMul %double {value} {double(scale)}") - else: - self.assertNotRegex(spv, r"OpFMul %double") - if clamp: - value = result(rf"OpExtInst %double %glsl FClamp {value} {double(0.0)} {double(1.0)}") - else: - self.assertNotIn("FClamp", spv) - pair = result(rf"OpBitcast %v2uint_d {value}") - for index, register in ((0, "%c4"), (1, "%c5")): - word = result(rf"OpCompositeExtract %uint {pair} {index}") - dest = result(rf"OpAccessChain %_ptr_Function_uint %vgpr {register}") - # This straight-line fixture keeps EXEC full, so each word is stored directly. - self.assertRegex(spv, rf"(?m)^ *OpStore {dest} {word}$") - # Every f64 add and scale keeps its own rounding (no_contraction decorates all float arithmetic). - for op in re.findall(r"(?m)^ *(%\w+) = Op(?:FAdd|FMul) %double ", spv): - self.assertRegex(spv, rf"(?m)^ *OpDecorate {op} NoContraction$") - - def test_gpu_fixture_expectation(self): - """The words written in ps_f64_mods.asm follow from the ISA rule (omod, then clamp), computed in Python.""" - def mods(x, scale=1.0, clamp=False): - x *= scale - return min(max(x, 0.0), 1.0) if clamp else x - - a, b = 0.75, 0.5 - want = tuple(words(v)[1] for v in (mods(a + b, 2.0), mods(a + b, clamp=True), - mods(a + b, 0.5, True), mods(a - b, 4.0))) - asm = (TEST_DIR.parent / "runtime" / "test" / "shaders" / "ps_f64_mods.asm").read_text(encoding="utf-8") - line = re.search(r"Expected mrt0 bits: (.*)", asm).group(1) - self.assertEqual(tuple(int(w, 16) for w in line.split(", ")), want) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/test_f64_transcendentals.py b/tests/test_f64_transcendentals.py deleted file mode 100644 index 9bd1dd19a..000000000 --- a/tests/test_f64_transcendentals.py +++ /dev/null @@ -1,138 +0,0 @@ -"""Check SPIR-V lowering and output modifiers for v_rcp_f64, v_rsq_f64 and v_sqrt_f64. - -LLVM defines all three as VOP1Inst<..., VOP_F64_F64>, whose VOP3 (_e64) form carries input modifiers -(abs, neg) and output modifiers (mul:2, mul:4, div:2, then clamp to [0, 1]). -""" - -import re -import shutil -import struct -import subprocess -import sys -import tempfile -import unittest -from pathlib import Path - -TEST_DIR = Path(__file__).resolve().parent -sys.path[:0] = [str(TEST_DIR.parent / "tools"), str(TEST_DIR)] - -from listing import translate_listing - - -def words(x): - bits = struct.unpack("> 32 - - -def load_double(lo_reg, hi_reg, value): - lo, hi = words(value) - return f"v_mov_b32 v{lo_reg}, {lo:#x}\nv_mov_b32 v{hi_reg}, {hi:#x}" - - -class F64TranscendentalsTest(unittest.TestCase): - def _check_store_pair(self, spv, value_id, dst_lo, dst_hi): - def result(instruction): - match = re.search(rf"^ *(%\w+) = {instruction}$", spv, re.M) - self.assertIsNotNone(match, f"Missing SPIR-V instruction: {instruction}") - return match.group(1) - - pair = result(rf"OpBitcast %v2uint_d {value_id}") - for index, reg in ((0, f"%c{dst_lo}"), (1, f"%c{dst_hi}")): - word = result(rf"OpCompositeExtract %uint {pair} {index}") - dest = result(rf"OpAccessChain %_ptr_Function_uint %vgpr {reg}") - if re.search(rf"(?m)^ *OpStore {re.escape(dest)} {re.escape(word)}$", spv): - continue - old_word = result(rf"OpLoad %uint {dest}") - masked = result(rf"OpSelect %uint %\w+ {word} {old_word}") - self.assertRegex(spv, rf"(?m)^ *OpStore {dest} {masked}$") - - def _double_const_id(self, spv, value): - def result(instruction): - match = re.search(rf"^ *(%\w+) = {instruction}$", spv, re.M) - self.assertIsNotNone(match, f"Missing SPIR-V instruction: {instruction}") - return match.group(1) - - lo, hi = words(value) - pair = result( - rf"OpCompositeConstruct %v2uint_d {result(f'OpConstant %uint {lo}')} " - rf"{result(f'OpConstant %uint {hi}')}" - ) - return result(rf"OpBitcast %double {pair}") - - def test_v_rcp_rsq_sqrt_f64_lowering_and_modifiers(self): - ops = ( - ("v_rcp_f64_e32", "", r"OpFDiv %double %\w+ %\w+", None, False), - ("v_rsq_f64_e32", "", r"OpExtInst %double %glsl InverseSqrt %\w+", None, False), - ("v_sqrt_f64_e32", "", r"OpExtInst %double %glsl Sqrt %\w+", None, False), - ("v_rcp_f64_e64", "mul:2", r"OpFDiv %double %\w+ %\w+", 2.0, False), - ("v_rsq_f64_e64", "clamp div:2", r"OpExtInst %double %glsl InverseSqrt %\w+", 0.5, True), - ("v_sqrt_f64_e64", "clamp mul:4", r"OpExtInst %double %glsl Sqrt %\w+", 4.0, True), - ) - prefix = load_double(0, 1, 4.0) - with tempfile.TemporaryDirectory() as directory: - for op, mods, pattern, scale, clamp in ops: - with self.subTest(op=op, mods=mods): - line = f"{op} v[4:5], v[0:1] {mods}".rstrip() - spv = translate_listing(Path(directory), f"{prefix}\n{line}") - self.assertIn("OpCapability Float64", spv) - m = re.search(rf"^ *(%\w+) = {pattern}$", spv, re.M) - self.assertIsNotNone(m, f"Missing {pattern} in:\n{spv}") - val = m.group(1) - if scale is not None: - scale_id = self._double_const_id(spv, scale) - m_mul = re.search(rf"^ *(%\w+) = OpFMul %double {val} {scale_id}$", spv, re.M) - self.assertIsNotNone(m_mul, f"Missing OpFMul by {scale} ({scale_id})") - val = m_mul.group(1) - else: - self.assertNotRegex(spv, r"OpFMul %double") - if clamp: - zero_id = self._double_const_id(spv, 0.0) - one_id = self._double_const_id(spv, 1.0) - m_cl = re.search( - rf"^ *(%\w+) = OpExtInst %double %glsl FClamp {val} {zero_id} {one_id}$", spv, re.M - ) - self.assertIsNotNone(m_cl) - val = m_cl.group(1) - else: - self.assertNotIn("FClamp", spv) - self._check_store_pair(spv, val, 4, 5) - if shutil.which("spirv-as") and shutil.which("spirv-val"): - spv_bin = Path(directory) / f"{op}.spv" - p_as = subprocess.run( - ["spirv-as", "--target-env", "vulkan1.2", "-o", str(spv_bin), "-"], - input=spv, text=True, capture_output=True, - ) - self.assertEqual(p_as.returncode, 0, p_as.stderr) - p_val = subprocess.run(["spirv-val", "--target-env", "vulkan1.2", str(spv_bin)], - text=True, capture_output=True) - self.assertEqual(p_val.returncode, 0, p_val.stderr) - - def test_input_modifiers_abs_neg_and_inline_constant(self): - prefix = load_double(0, 1, -4.0) - body = "\n".join(( - prefix, - "v_sqrt_f64_e64 v[2:3], |v[0:1]|", - "v_rcp_f64_e64 v[4:5], -v[2:3]", - "v_rsq_f64_e64 v[6:7], 4.0", - )) - with tempfile.TemporaryDirectory() as directory: - spv = translate_listing(Path(directory), body) - self.assertIn("OpExtInst %double %glsl FAbs", spv) - self.assertIn("OpFNegate %double", spv) - self.assertIn("OpExtInst %double %glsl Sqrt", spv) - self.assertIn("OpFDiv %double", spv) - self.assertIn("OpExtInst %double %glsl InverseSqrt", spv) - if shutil.which("spirv-as") and shutil.which("spirv-val"): - spv_bin = Path(directory) / "mods.spv" - p_as = subprocess.run( - ["spirv-as", "--target-env", "vulkan1.2", "-o", str(spv_bin), "-"], - input=spv, text=True, capture_output=True, - ) - self.assertEqual(p_as.returncode, 0, p_as.stderr) - p_val = subprocess.run(["spirv-val", "--target-env", "vulkan1.2", str(spv_bin)], - text=True, capture_output=True) - self.assertEqual(p_val.returncode, 0, p_val.stderr) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/test_feature_scan.py b/tests/test_feature_scan.py deleted file mode 100644 index fde494f53..000000000 --- a/tests/test_feature_scan.py +++ /dev/null @@ -1,538 +0,0 @@ -"""feature_scan: stage census, SFI0 flags, output streams, MMA/GDS opcodes and code-base counts on a synthetic work folder. - - python -I tests/test_feature_scan.py - -Every input is built here: tiny DXBC containers with only the parts the scanner reads, three hand-written .s -listings and a two-entry spirv/index.json. No game data. -""" -import json -import os -import struct -import subprocess -import sys -import tempfile - -TOOLS = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "tools") -sys.path.insert(0, TOOLS) -import feature_scan as F # noqa: E402 - -failures = 0 - - -def check(cond, what): - global failures - print(("PASS " if cond else "FAIL ") + what) - failures += not cond - - -def signature(streams): - """ISG1/OSG1 payload: count, first-element offset, 32-byte elements with the stream index first.""" - body = struct.pack(" bytes 0, 6, 5 (three 0..7) and 12 (one 12) - ("perm_imm_ps", "ps", - "\tv_perm_b32 v0, v1, v2, 0x0c050600\n" - "\ts_endpgm\n"), - # Constant SGPR selector 0x0b0a0908 -> bytes 8, 9, 10, 11 (four 8..11 sign-extend) - ("perm_sreg_cs", "cs", - "\ts_mov_b32 s4, 0x0b0a0908\n" - "\tv_perm_b32 v3, v1, v2, s4\n" - "\ts_endpgm\n"), - # Constant VGPR selector 0x0d0e0f08 -> bytes 8 (one 8..11) and 15, 14, 13 (three >= 13) - ("perm_vreg_vs", "vs", - "\tv_mov_b32_e32 v6, 0x0d0e0f08\n" - "\tv_perm_b32 v7, v1, v2, v6\n" - "\ts_endpgm\n"), - # Clobbered SGPR and VGPR before v_perm_b32 -> both unresolved - ("perm_clobber_ps", "ps", - "\ts_mov_b32 s5, 0x0c050600\n" - "\ts_add_u32 s5, s5, 1\n" - "\tv_perm_b32 v4, v1, v2, s5\n" - "\tv_mov_b32 v8, 0x0c050600\n" - "\tv_add_nc_u32 v8, v8, v1\n" - "\tv_perm_b32 v9, v1, v2, v8\n" - "\ts_endpgm\n"), - # The scalar carry is the second destination; wave64 writes both halves of its pair. - ("perm_carry_w32", "cs", - "\ts_mov_b32 s4, 0x08080808\n" - "\tv_add_co_u32 v8, s4, v1, v2\n" - "\tv_perm_b32 v9, v1, v2, s4\n" - "\ts_endpgm\n"), - ("perm_carry_w64", "vs", - "\ts_mov_b32 s5, 0x08080808\n" - "\tv_add_co_u32 v8, s[4:5], v1, v2\n" - "\tv_perm_b32 v9, v1, v2, s5\n" - "\ts_endpgm\n"), - ] - index = [] - for name, stage, listing in synthetic: - with open(os.path.join(dx, name + ".dxbc"), "wb") as f: - f.write(dxbc([("SFI0", struct.pack("= 24 else b"") - body += rec + bytes(size - len(rec)) - return body[:-4] if truncate else body - - -def listing(lines): - """A .s listing with `; encoding:` comments of the right length, so pcs and branch targets are real.""" - return "".join(f"\t{code} ; encoding: [{','.join(['0x00'] * n)}]\n" for code, n in lines) - - -def test_typed_buffers_and_psv0(): - """§8.2 #16: PSV0 counter/typed-buffer bindings, MTBUF formats and where each MUBUF V# word 3 comes from.""" - with tempfile.TemporaryDirectory() as tmp: - sh = os.path.join(tmp, "shaders") - dx = os.path.join(sh, "dxbc") - dis = os.path.join(dx, "disasm") - os.makedirs(dis) - cs = listing([ - ("s_load_dwordx4 s[8:11], s[0:1], 0x0", 8), # pc 0 - ("s_mov_b32 s15, 0x38000", 8), # 8: format 56, 8_8_8_8_UNORM - ("s_mov_b32 s19, 0x24000", 8), # 16: format 36, 10_11_11_FLOAT - ("s_or_b32 s23, s23, 0x1000", 8), # 24: computed - ("s_cmp_eq_u32 s11, 0", 4), # 32: reads s11, writes nothing - ("buffer_load_format_xyzw v[0:3], v4, s[8:11], 0 idxen", 8), # 36: memory - ("buffer_load_format_x v5, v4, s[12:15], 0 idxen", 8), # 44: literal - ("buffer_store_format_x v5, v4, s[16:19], 0 idxen", 8), # 52: literal, not in the table - ("buffer_load_format_x v6, v4, s[20:23], 0 idxen", 8), # 60: computed - ("buffer_load_format_x v7, v4, s[24:27], 0 idxen", 8), # 68: never written: shader input - ("s_cbranch_scc0 1", 4), # 76: to 84; 80 and 84 lead blocks - ("s_nop 0", 4), # 80 - ("buffer_load_format_x v8, v4, s[8:11], 0 idxen", 8), # 84: loaded in an earlier block - ("buffer_load_format_x v9, v4, s[12:15], 0 idxen", 8), # 92: literal from an earlier block - ("tbuffer_load_format_xy v[0:1], v4, s[8:11], 0 format:[BUF_FMT_16_16_SNORM] idxen", 8), - ("tbuffer_load_format_x v2, v4, s[8:11], 0 idxen", 8), # no format: GFX10 default 8_UNORM - ("tbuffer_store_format_x v2, v4, s[8:11], 0 format:[BUF_FMT_10_11_11_FLOAT] idxen", 8), - ("s_endpgm", 4)]) - ps = listing([("s_mov_b32 s11, 0", 4), # word 3 0: FORMAT INVALID - ("buffer_load_format_x v0, v1, s[0:3], 0 idxen", 8), - ("buffer_load_format_x v2, v1, s[8:11], 0 idxen", 8), ("s_endpgm", 4)]) - vs = listing([("v_mov_b32_e32 v0, v1", 4), ("s_endpgm", 4)]) - synthetic = [ - ("tb_cs", "cs", cs, psv0([(9, 12), (3, 10), (6, 2)])), # counter UAV, typed buffer SRV, typed 2D UAV - ("tb_ps", "ps", ps, psv0([(6, 10), (6, 10)])), # two typed buffer UAVs - ("tb_vs", "vs", vs, psv0([(3, 10)], size=16)), # v0 records carry no kind - ("tb_gs", "gs", None, psv0([(9, 12)], truncate=True)), # records past the end of the part - ] - index = [] - for name, stage, text, psv in synthetic: - with open(os.path.join(dx, name + ".dxbc"), "wb") as f: - f.write(dxbc([("SFI0", struct.pack("` followed by calls, with a -"lookup" called from many places and a decoy called once. -""" -import json -import os -import struct -import subprocess -import sys -import tempfile -import unittest - -ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) -TOOL = os.path.join(ROOT, "tools", "find_hash_lookup.py") -sys.path.insert(0, os.path.join(ROOT, "tools")) - -import find_hash_lookup as fhl # noqa: E402 - -TEXT_RVA, TEXT_RAW = 0x1000, 0x400 - - -def pe(code): - """A minimal PE32+ file whose only section, .text (executable), holds `code`.""" - header = bytearray(TEXT_RAW) - header[0:2] = b"MZ" - struct.pack_into(" str | None: - exe = ".exe" if os.name == "nt" else "" - for path in ( - os.environ.get("LEONIDA_VK_HARNESS"), - os.path.join(ROOT, "runtime", "build", "linux", f"vk_harness{exe}"), - os.path.join(ROOT, "runtime", "build", "windows", f"vk_harness{exe}"), - os.path.join(ROOT, "runtime", "build", f"vk_harness{exe}"), - ): - if path and os.path.isfile(path): - return path - return None - - -class MeshOutputTests(unittest.TestCase): - def test_fit_keeps_relative_depth_for_an_offset_mesh(self) -> None: - import tempfile - - vertices = [(-2.0, -1.0, 900.0, 0.0, 0.0), - (2.0, -1.0, 901.0, 1.0, 0.0), - (0.0, 1.0, 902.0, 0.5, 1.0)] - fitted = fl.fit(vertices, 128, 128, True, False) - with tempfile.TemporaryDirectory() as directory: - mesh = os.path.join(directory, "mesh.bin") - fl.write_mesh(mesh, fitted, [0, 1, 2]) - with open(mesh, "rb") as handle: - encoded = handle.read() - - records = encoded[fl.MESH_HEADER.size:fl.MESH_HEADER.size + 3 * 20] - depth = b"".join(records[offset + 8:offset + 12] for offset in (0, 20, 40)) - self.assertEqual(depth, struct.pack("<3f", 0.05, 0.5, 0.95)) - self.assertEqual(encoded[-12:], struct.pack("<3I", 0, 1, 2)) - - -class ProbeDepthTests(unittest.TestCase): - @staticmethod - def triangle(depths, uv): - return [(x, y, z, *uv) for (x, y), z in zip(((-1, -1), (1, -1), (-1, 1)), depths)] - - def test_only_visible_fragments_replace_an_earlier_triangle(self): - first, last = (0.125, 0.75), (0.75, 0.125) - back = self.triangle((0.25,) * 3, first) - for depths, left, right in ( - ((-1, -1, -1), first, first), - ((2, 2, 2), first, first), - ((-1, 1, -1), first, last), - ((2, 0, 2), first, last), - ((0, 0, 0), last, last), - ((1, 1, 1), last, last), - ((1 + 2**-25,) * 3, last, last), # Stored as exactly 1 in mesh.bin. - ): - with self.subTest(depths=depths): - vertices = back + self.triangle(depths, last) - self.assertEqual(fl.uv_at(vertices, range(6), 0, 0, 8, 8), left) - self.assertEqual(fl.uv_at(vertices, range(6), 5, 0, 8, 8), right) - - def test_clipped_region_can_be_clear_and_supplies_no_uv_probes(self): - vertices = self.triangle((-1, 1, -1), (0.75, 0.125)) - self.assertEqual(fl.clear_pixel(vertices, range(3), 8, 8), [0, 0]) - probes = fl.uv_probes(vertices, range(3), 8, 8) - self.assertTrue(probes) - self.assertTrue(all(p["pixel"][0] >= 4 for p in probes), probes) - - -class FirstLightTests(unittest.TestCase): - def setUp(self): - self.out = os.environ.get("LEONIDA_FIRST_LIGHT_DIR") - if not self.out: - self.skipTest( - "LEONIDA_FIRST_LIGHT_DIR is not set (run tools/first_light.py first)" - ) - self.out = os.path.abspath(os.path.expanduser(self.out)) - self.harness = harness() - if not self.harness: - self.skipTest( - "vk_harness is not built (runtime/build/linux or runtime/build/windows, target " - "vk_harness); set LEONIDA_VK_HARNESS" - ) - with open(os.path.join(self.out, "manifest.json"), encoding="utf-8") as f: - self.manifest = json.load(f) - - def test_draw_matches_the_manifest(self): - raw = os.path.join(self.out, "image_first_light.raw") - if os.path.exists(raw): - os.unlink( - raw - ) # a fresh run: a harness that writes nothing cannot pass on a stale file - env = fl.harness_env(self.manifest, self.out) # a --camera folder also passes its constants - subprocess.run( - [ - self.harness, - os.path.join(self.out, "vs.spv"), - os.path.join(self.out, "ps.spv"), - raw, - str(self.manifest["width"]), - str(self.manifest["height"]), - ], - check=True, - env=env, - ) - self.assertTrue(os.path.isfile(raw), "the harness did not write a fresh image") - with open(raw, "rb") as f: - data = f.read() - stats = check_image(data, self.manifest) - write_ppm( - os.path.join(self.out, "image_first_light.ppm"), - stats["pixels"], - self.manifest["width"], - self.manifest["height"], - ) - self.assertGreater(stats["covered"], 0) - - def test_check_cli_matches_the_oracle(self): - """The tool's --check must accept and reject the same images the test does.""" - subprocess.run( - [ - sys.executable, - "-I", - os.path.join(ROOT, "tools", "first_light.py"), - "--check", - "--out", - self.out, - "--harness", - self.harness, - ], - check=True, - ) - - def test_manifest_names_the_assets(self): - self.assertGreater(self.manifest["vertex_count"], 0) - self.assertGreater(self.manifest["triangle_count"], 0) - for key in ("vs", "ps"): - self.assertTrue( - self.manifest[key].get("fssm_sha256"), f"{key} has no FSSM hash" - ) - self.assertTrue( - os.path.isfile(os.path.join(self.out, self.manifest["files"][key])) - ) - - -class DrawOutputTests(unittest.TestCase): - def test_failed_recheck_clears_previous_preview_and_result(self) -> None: - manifest = { - "width": 2, - "height": 1, - "min_coverage": 0.5, - "max_coverage": 0.99, - "files": {"mesh": "mesh.bin"}, - } - first = struct.pack("<8f", 1, 0, 0, 1, 0, 0, 0, 0) - blank = bytes(32) - retry = struct.pack("<8f", 0, 1, 0, 1, 0, 0, 0, 0) - frames = iter((first, blank, retry)) - - def write_readback(cmd: list[str], *, check: bool, env: dict[str, str]) -> None: - Path(cmd[3]).write_bytes(next(frames)) - - with tempfile.TemporaryDirectory() as tmp: - out = Path(tmp) - manifest_path = out / "manifest.json" - manifest_path.write_text(json.dumps(manifest), encoding="utf-8", newline="\n") - ppm = out / "image.ppm" - argv = ["--out", tmp, "--check"] - with ( - patch.object(fl, "find_harness", return_value="stub.exe"), - patch.object(fl.subprocess, "run", side_effect=write_readback), - redirect_stdout(io.StringIO()), - ): - self.assertEqual(fl.main(argv), 0) - self.assertEqual(ppm.read_bytes(), b"P6\n2 1\n255\n\xff\0\0\0\0\0") - saved = json.loads(manifest_path.read_text(encoding="utf-8")) - self.assertEqual(saved["result"]["ratio"], 0.5) - - with self.assertRaisesRegex(SystemExit, "coverage 0.0000 outside"): - fl.main(argv) - self.assertEqual((out / "image.raw").read_bytes(), blank) - self.assertFalse(ppm.exists()) - self.assertEqual(json.loads(manifest_path.read_text(encoding="utf-8")), manifest) - - self.assertEqual(fl.main(argv), 0) - self.assertEqual((out / "image.raw").read_bytes(), retry) - self.assertEqual(ppm.read_bytes(), b"P6\n2 1\n255\n\0\xff\0\0\0\0") - saved = json.loads(manifest_path.read_text(encoding="utf-8")) - self.assertEqual(saved["result"]["ratio"], 0.5) - - -class PpmTests(unittest.TestCase): - def test_nonfinite_readback_channels_write_complete_ppm(self) -> None: - from pathlib import Path - from tempfile import TemporaryDirectory - - pixels = (float("nan"), float("inf"), float("-inf"), 1.0, - -0.25, 0.5, 1.25, 1.0) - with TemporaryDirectory() as temp: - path = Path(temp) / "preview.ppm" - write_ppm(str(path), pixels, 2, 1) - self.assertEqual(path.read_bytes(), b"P6\n2 1\n255\n" + bytes((0, 255, 0, 0, 128, 255))) - - -class ShaderPreparationTests(unittest.TestCase): - def test_same_display_name_keeps_both_stage_files(self) -> None: - modules = {"vs": build_vs_stub([0]), "ps": build_ps_stub([0])} - entries = [ - {"name": "shared", "file": "shared.dxbc", "stage": "vs"}, - {"name": "shared", "file": "shared~1.dxbc", "stage": "ps"}, - ] - with tempfile.TemporaryDirectory() as tmp: - work = Path(tmp) - dxbc = work / "shaders" / "dxbc" - dxbc.mkdir(parents=True) - (dxbc / "index.json").write_text(json.dumps(entries), encoding="utf-8", newline="\n") - for entry in entries: - (dxbc / entry["file"]).write_bytes(entry["stage"].encode("ascii")) - - def write_translation(argv: list[str]) -> None: - if Path(argv[0]).name != "rdna2spirv.py": - return - staged = work / "first_light" / "dxbc" - picked = json.loads((staged / "index.json").read_text(encoding="utf-8")) - self.assertEqual(picked, entries) - spirv = Path(argv[argv.index("--out") + 1]) - spirv.mkdir() - index = {} - for entry in picked: - stage = entry["stage"] - self.assertEqual((staged / entry["file"]).read_bytes(), stage.encode("ascii")) - stem = Path(entry["file"]).stem - (spirv / f"{stem}.spv").write_bytes(modules[stage]) - index[stem] = {"stage": stage, "fssm_sha256": stage + "-fixture"} - (spirv / "index.json").write_text(json.dumps(index), encoding="utf-8", newline="\n") - - with patch.object(fl, "run", side_effect=write_translation), redirect_stdout(io.StringIO()): - self.assertEqual(fl.main(["--game", tmp, "--work", tmp, "--no-fit", - "--vs", "shared", "--ps", "shared"]), 0) - out = work / "first_light" / "out" - manifest = json.loads((out / "manifest.json").read_text(encoding="utf-8")) - runtime_index = json.loads((out / "index.json").read_text(encoding="utf-8")) - for stage, module in modules.items(): - self.assertEqual((out / manifest["files"][stage]).read_bytes(), module) - self.assertEqual((out / f"{stage}.dxbc").read_bytes(), stage.encode("ascii")) - self.assertEqual(runtime_index[stage]["fssm_sha256"], stage + "-fixture") - self.assertEqual(manifest[stage]["fssm_sha256"], stage + "-fixture") - - -LINK_KINDS = ("symlink", "junction") if os.name == "nt" else ("symlink",) - - -def link_folder(kind: str, link: Path, target: Path) -> bool: - """Make a directory symlink or a Windows junction; False where this machine does not allow it.""" - if kind == "junction": - made = subprocess.run(["cmd", "/c", "mklink", "/J", str(link), str(target)], capture_output=True) - return made.returncode == 0 - try: - os.symlink(target, link, target_is_directory=True) - except (OSError, NotImplementedError): - return False - return True - - -class RunFolderTests(unittest.TestCase): - """first_light/dxbc and first_light/spirv hold one run's pair, whatever an earlier run left there. - - Fully synthetic: the containers are a few hand-written bytes, and the unpacker, the disassembler and the - translator are replaced by stand-ins that, like the real tools, take every file in the folder they are given. - """ - - def setUp(self) -> None: - tmp = tempfile.TemporaryDirectory(prefix="first-light-run-folders-") - self.addCleanup(tmp.cleanup) - self.tmp = Path(tmp.name) - self.work = self.tmp / "work" - self.staged = self.work / "first_light" / "dxbc" - self.spirv = self.work / "first_light" / "spirv" - carved = self.work / "shaders" / "dxbc" - carved.mkdir(parents=True) - entries = [ - {"name": "vertex", "file": "vertex.dxbc", "stage": "vs"}, - {"name": "first", "file": "first.dxbc", "stage": "ps"}, - {"name": "second", "file": "second.dxbc", "stage": "ps"}, - ] - (carved / "index.json").write_text(json.dumps(entries), encoding="utf-8", newline="\n") - for entry in entries: - (carved / entry["file"]).write_bytes(entry["name"].encode("ascii")) - self.handed = [] # per translator run: the listings it was given - - def tools(self, argv: list[str]) -> None: - tool = Path(argv[0]).name - src = Path(argv[1]) - if tool == "fssm_unpack.py": - (src / "fssm").mkdir(exist_ok=True) - for container in sorted(src.glob("*.dxbc")): - (src / "fssm" / f"{container.stem}.fssm").write_bytes(container.read_bytes()) - return - out = Path(argv[argv.index("--out") + 1]) - out.mkdir(exist_ok=True) - if tool == "shader_disasm.py": - for blob in sorted(src.glob("*.fssm")): - (out / f"{blob.stem}.s").write_bytes(blob.read_bytes()) - return - self.assertEqual(tool, "rdna2spirv.py") - stages = {Path(e["file"]).stem: e["stage"] - for e in json.loads((src.parent / "index.json").read_text(encoding="utf-8"))} - index_path = out / "index.json" # the translator merges a small run into an index it finds - index = json.loads(index_path.read_text(encoding="utf-8")) if index_path.is_file() else {} - listings = sorted(src.glob("*.s")) - for listing in listings: - (out / f"{listing.stem}.spv").write_bytes(b"spv " + listing.read_bytes()) - index[listing.stem] = {"stage": stages.get(listing.stem, "?"), "fssm_sha256": listing.stem} - index_path.write_text(json.dumps(index), encoding="utf-8", newline="\n") - self.handed.append([listing.stem for listing in listings]) - - def prepare(self, ps: str, *extra: str) -> None: - with patch.object(fl, "run", side_effect=self.tools), redirect_stdout(io.StringIO()): - self.assertEqual(fl.main(["--game", str(self.tmp), "--work", str(self.work), "--no-fit", - "--vs", "vertex", "--ps", ps, *extra]), 0) - - def files(self, folder: Path) -> list[str]: - return sorted(p.relative_to(folder).as_posix() for p in folder.rglob("*") if p.is_file()) - - def test_a_second_run_holds_only_its_own_pair(self) -> None: - other_out = self.work / "first_light" / "out_first" - self.prepare("first", "--out", str(other_out)) - self.assertEqual(self.handed, [["first", "vertex"]]) - (self.staged / "leftover.dxbc").write_bytes(b"leftover") # a container no run selected - (self.spirv / "leftover.spvasm").write_bytes(b"leftover") - carved_before = {name: (self.work / "shaders" / "dxbc" / name).read_bytes() - for name in self.files(self.work / "shaders" / "dxbc")} - other_out_before = {name: (other_out / name).read_bytes() for name in self.files(other_out)} - - self.prepare("second") - - self.assertEqual(self.handed[1], ["second", "vertex"]) - self.assertEqual(self.files(self.staged), - ["disasm/second.s", "disasm/vertex.s", "fssm/second.fssm", "fssm/vertex.fssm", - "index.json", "second.dxbc", "vertex.dxbc"]) - self.assertEqual(self.files(self.spirv), ["index.json", "second.spv", "vertex.spv"]) - translated = json.loads((self.spirv / "index.json").read_text(encoding="utf-8")) - self.assertEqual({stem: meta["stage"] for stem, meta in translated.items()}, - {"second": "ps", "vertex": "vs"}) - out = self.work / "first_light" / "out" - self.assertEqual((out / "ps.dxbc").read_bytes(), b"second") - self.assertEqual((out / "ps.spv").read_bytes(), b"spv second") - # Only the two run folders are emptied: the carve and the other run's --out are as they were. - self.assertEqual({name: (self.work / "shaders" / "dxbc" / name).read_bytes() - for name in self.files(self.work / "shaders" / "dxbc")}, carved_before) - self.assertEqual({name: (other_out / name).read_bytes() for name in self.files(other_out)}, - other_out_before) - self.assertEqual((other_out / "ps.dxbc").read_bytes(), b"first") - - def linked(self, kind: str, where: str) -> tuple[Path, Path]: - """A work folder whose first_light/ is a link of this kind to a folder outside it.""" - work, outside = self.tmp / kind / "work", self.tmp / kind / "outside" - (outside / "dxbc").mkdir(parents=True) - for keep in (outside / "keep.dxbc", outside / "dxbc" / "keep.dxbc"): - keep.write_bytes(b"keep") - link = work / "first_light" / where - link.parent.mkdir(parents=True) - if not link_folder(kind, link, outside): - self.skipTest(f"cannot create a {kind} here") - return work, outside - - def test_a_link_inside_a_run_folder_is_removed_not_followed(self) -> None: - for kind in LINK_KINDS: - with self.subTest(kind=kind): - work, outside = self.linked(kind, os.path.join("dxbc", "link")) - staged = work / "first_light" / "dxbc" - self.assertEqual(fl.reset_run_folders(str(work)), str(staged)) - self.assertEqual(os.listdir(staged), []) - self.assertEqual(self.files(outside), ["dxbc/keep.dxbc", "keep.dxbc"]) - - def test_a_run_folder_that_is_a_link_is_refused(self) -> None: - for kind in LINK_KINDS: - with self.subTest(kind=kind): - work, outside = self.linked(kind, "spirv") - staged = work / "first_light" / "dxbc" - staged.mkdir() - (staged / "earlier.dxbc").write_bytes(b"earlier") - with self.assertRaises(SystemExit) as refused: - fl.reset_run_folders(str(work)) - self.assertIn(str(work / "first_light" / "spirv"), str(refused.exception)) - self.assertNotIn("\n", str(refused.exception)) - self.assertEqual(self.files(outside), ["dxbc/keep.dxbc", "keep.dxbc"]) - self.assertEqual(os.listdir(staged), ["earlier.dxbc"]) # refused before anything is removed - - def test_a_first_light_folder_that_is_a_link_is_refused(self) -> None: - for kind in LINK_KINDS: - with self.subTest(kind=kind): - work, outside = self.linked(kind, "") - with self.assertRaises(SystemExit) as refused: - fl.reset_run_folders(str(work)) - self.assertIn(str(work / "first_light"), str(refused.exception)) - self.assertNotIn("\n", str(refused.exception)) - self.assertEqual(self.files(outside), ["dxbc/keep.dxbc", "keep.dxbc"]) - - def test_a_linked_first_light_with_no_run_folders_is_refused_too(self) -> None: - # Nothing stale lies behind the link, so only the check of first_light itself can refuse it; without that - # check the new dxbc was created in the folder the link points to, outside the work folder. - for kind in LINK_KINDS: - with self.subTest(kind=kind): - work, outside = self.tmp / kind / "work", self.tmp / kind / "outside" - outside.mkdir(parents=True) - work.mkdir() - if not link_folder(kind, work / "first_light", outside): - self.skipTest(f"cannot create a {kind} here") - with self.assertRaises(SystemExit) as refused: - fl.reset_run_folders(str(work)) - self.assertIn(str(work / "first_light"), str(refused.exception)) - self.assertNotIn("\n", str(refused.exception)) - self.assertEqual(os.listdir(outside), []) - - def test_a_file_that_cannot_be_removed_stops_the_run(self) -> None: - self.prepare("first") - held = self.staged / "first.dxbc" - denied = PermissionError(13, "Permission denied", str(held)) - with patch.object(fl.shutil, "rmtree", side_effect=denied), self.assertRaises(SystemExit) as stopped: - self.prepare("second") - self.assertIn(str(held), str(stopped.exception)) - self.assertIn("Permission denied", str(stopped.exception)) - self.assertNotIn("\n", str(stopped.exception)) - self.assertEqual(self.handed, [["first", "vertex"]]) # nothing was translated from the stale folder - - -class OracleTests(unittest.TestCase): - """The readback oracle on synthetic images: the controls run without a GPU or a game package.""" - - def setUp(self): - self.manifest = { - "width": 4, - "height": 4, - "min_coverage": 0.2, - "max_coverage": 0.5, - "centre_pixel": [2, 2], - "centre_uv": [0.25, 0.75], - "uv_probes": [{"pixel": [2, 2], "uv": [0.25, 0.75]}], - "clear_pixel": [0, 0], - "clear": CLEAR, - } - - def image(self, centre=(0.25, 0.75), fill=None) -> bytes: - pixels = [[CLEAR] * 4 for _ in range(16)] - if fill is not None: - pixels = [[fill, fill, fill, 1.0] for _ in range(16)] - else: - for x, y in ((1, 1), (2, 1), (1, 2), (2, 2)): - pixels[y * 4 + x] = [centre[0], centre[1], 0.0, 1.0] - return struct.pack("<64f", *(v for pixel in pixels for v in pixel)) - - def test_accepts_the_expected_image(self): - check_image(self.image(), self.manifest) - - def test_rejects_an_all_opaque_image(self): - with self.assertRaises(AssertionError): - check_image(self.image(fill=0.5), self.manifest) - - def test_rejects_a_swapped_uv(self): - with self.assertRaises(AssertionError): - check_image(self.image(centre=(0.75, 0.25)), self.manifest) - - def test_rejects_a_short_image(self): - with self.assertRaises(AssertionError): - check_image(b"", self.manifest) - - -class ProbeCoordinateTests(unittest.TestCase): - rgba = (0.25, 0.75, 0.0, 1.0) - image = struct.pack("<16f", *([CLEAR] * 8 + list(rgba) * 2)) - - def setUp(self): - self.manifest = {"width": 2, "height": 2, "min_coverage": 0.5, "max_coverage": 0.5} - - def test_rejects_invalid_coordinates_in_every_probe_path(self): - for point in ([-1, 1], [-1, 0], [2, 0], [0, 2], [0, -1], {}, [0], [True, 1], [0, 1.0]): - probes = ( - ("clear_pixel", {"clear_pixel": point}), - ("centre_pixel", {"centre_pixel": point, "centre_uv": self.rgba[:2]}), - ("centre_pixel", {"centre_pixel": point, "centre_rgba": self.rgba}), - ("uv_probes", {"uv_probes": [{"pixel": point, "uv": self.rgba[:2]}]}), - ("rgba_probes", {"rgba_probes": [{"pixel": point, "rgba": self.rgba}]}), - ) - for field, probe in probes: - with self.subTest(point=point, probe=probe): - with self.assertRaisesRegex(AssertionError, f"invalid {field}.*coordinates"): - check_image(self.image, self.manifest | probe) - - def test_accepts_edges_and_optional_probes(self): - for probe in ( - {}, - {"clear_pixel": None, "centre_pixel": None, "centre_uv": self.rgba[:2]}, - {"centre_uv": self.rgba[:2]}, - { - "clear_pixel": [1, 0], - "centre_pixel": [0, 1], - "centre_uv": self.rgba[:2], - "uv_probes": [{"pixel": [1, 1], "uv": self.rgba[:2]}], - }, - { - "centre_pixel": [1, 1], - "centre_rgba": self.rgba, - "centre_uv": [0.0, 0.0], - "rgba_probes": [{"pixel": [0, 1], "rgba": self.rgba}], - "uv_probes": [{"pixel": [1, 1], "uv": [0.0, 0.0]}], - }, - ): - with self.subTest(probe=probe): - self.assertEqual(check_image(self.image, self.manifest | probe)["covered"], 2) - - def test_empty_centre_pixel_uses_the_image_centre(self): - for key, expected in (("centre_uv", self.rgba[:2]), ("centre_rgba", self.rgba)): - with self.subTest(key=key): - manifest = self.manifest | {"centre_pixel": [], key: expected} - self.assertEqual(check_image(self.image, manifest)["covered"], 2) - - def test_rgba_probes_still_reject_invalid_uv_coordinates(self): - manifest = self.manifest | { - "rgba_probes": [{"pixel": [0, 1], "rgba": self.rgba}], - "uv_probes": [{"pixel": [99, -5]}], - } - with self.assertRaisesRegex(AssertionError, r"invalid uv_probes pixel coordinates \[99, -5\]"): - check_image(self.image, manifest) - - def test_null_uv_probes_are_optional_with_rgba(self): - manifest = self.manifest | { - "rgba_probes": [{"pixel": [0, 1], "rgba": self.rgba}], - "uv_probes": None, - } - self.assertEqual(check_image(self.image, manifest)["covered"], 2) - with self.assertRaises(TypeError): - check_image(self.image, manifest | {"uv_probes": False}) - - def test_check_reports_invalid_coordinates(self): - def draw(command, **kwargs): - Path(command[3]).write_bytes(self.image) - - with tempfile.TemporaryDirectory() as tmp: - out = Path(tmp) - manifest = self.manifest | { - "files": {"mesh": "mesh.bin"}, - "centre_uv": self.rgba[:2], - "centre_pixel": [2, 0], - } - (out / "manifest.json").write_text(json.dumps(manifest), encoding="utf-8", newline="\n") - with (patch.object(fl, "find_harness", return_value="vk_harness"), - patch.object(fl.subprocess, "run", side_effect=draw), - self.assertRaisesRegex(SystemExit, r"invalid centre_pixel coordinates \[2, 0\] for 2x2 image")): - fl.main(["--check", "--out", tmp]) - self.assertFalse((out / "image.ppm").exists()) - - -class ReadObjTests(unittest.TestCase): - """Wavefront OBJ parsing in tools/first_light.py without a GPU or game package.""" - - def _write_obj(self, text: str) -> str: - tmp = tempfile.TemporaryDirectory() - self.addCleanup(tmp.cleanup) - path = os.path.join(tmp.name, "mesh.obj") - with open(path, "w", encoding="utf-8", newline="\n") as f: - f.write(text) - return path - - def test_requires_finite_vertex_positions(self): - for coordinates in ("nan 0 0", "0 inf 0", "0 0 -inf", "0 1e999 0"): - with self.subTest(coordinates=coordinates): - path = self._write_obj(f"v {coordinates}\nv 1 0 0\nv 0 1 0\nf 1 2 3\n") - with self.assertRaises(SystemExit) as caught: - fl.read_obj(path) - self.assertIn(path, str(caught.exception)) - self.assertIn("non-finite vertex coordinates", str(caught.exception)) - - def test_requires_finite_texture_coordinates(self): - def triangle(u, v): - return self._write_obj( - "v 0 0 0\nv 1 0 0\nv 0 1 0\n" - f"vt {u} {v}\n" - "f 1/1 2/1 3/1\n" - ) - - vertices, indices = fl.read_obj(triangle("-0.25", "1.5")) - self.assertEqual(indices, [0, 1, 2]) - self.assertEqual([vertex[3:] for vertex in vertices], [(-0.25, 1.5)] * 3) - for u, v in (("nan", "0.75"), ("0.25", "inf"), ("-inf", "0.75"), ("0.25", "1e999")): - with self.subTest(u=u, v=v): - with self.assertRaisesRegex(SystemExit, "non-finite texture coordinates"): - fl.read_obj(triangle(u, v)) - - large_finite = triangle("1e38", "-1e38") - mesh = Path(large_finite).with_suffix(".bin") - fl.write_mesh(str(mesh), *fl.read_obj(large_finite)) - previous = mesh.read_bytes() - self.assertEqual(len(previous), 80) - for u, v in (("1e39", "0.75"), ("0.25", "-1e39")): - with self.subTest(u=u, v=v): - with self.assertRaisesRegex(SystemExit, "texture coordinates exceed the binary32 range"): - fl.write_mesh(str(mesh), *fl.read_obj(triangle(u, v))) - self.assertEqual(mesh.read_bytes(), previous) - - def test_negative_relative_indices_inline_comments_and_continuations(self): - positive = self._write_obj( - "v 0 0 0\nv 1 0 0\nv 0 1 0\n" - "vt 0.1 0.2\nvt 0.3 0.4\nvt 0.5 0.6\n" - "f 1/1 2/2 3/3\n" - ) - relative = self._write_obj( - "v 0 0 0 # origin\n" - "v 1 0 0\n" - "v 0 1 0\n" - "vt 0.1 0.2 # uv0\n" - "vt 0.3 0.4\n" - "vt 0.5 0.6\n" - "f -3/-3 \\\n" - " -2/-2 -1/-1 # trailing comment\n" - ) - self.assertEqual(fl.read_obj(relative), fl.read_obj(positive)) - - def test_rejects_zero_and_out_of_range_vertex_indices(self): - for bad in ( - "v 0 0 0\nv 1 0 0\nv 0 1 0\nf 0 1 2\n", - "v 0 0 0\nv 1 0 0\nv 0 1 0\nf 1 2 4\n", - "v 0 0 0\nv 1 0 0\nv 0 1 0\nf -4 -2 -1\n", - "v 0 0\nf 1 1 1\n", - ): - with self.subTest(bad=bad), self.assertRaises(SystemExit): - fl.read_obj(self._write_obj(bad)) - - -class TexturedOracleTests(unittest.TestCase): - """Synthetic tests for the textured first-light path (TEST-524): no GPU or game files.""" - - def setUp(self): - self.manifest = { - "width": 4, - "height": 4, - "min_coverage": 0.2, - "max_coverage": 0.5, - "centre_pixel": [2, 2], - "centre_rgba": [0.2, 0.4, 0.6, 1.0], - "rgba_probes": [{"pixel": [1, 1], "uv": [0.25, 0.75], "rgba": [0.8, 0.2, 0.1, 1.0]}], - "rgba_tolerance": 0.02, - "clear_pixel": [0, 0], - "clear": CLEAR, - "files": {"mesh": "mesh.bin", "texture": "texture.rgba"}, - "ps": {"subgroup_size": 32}, - "texture": { - "width": 2, - "height": 2, - "ptr_sgpr": 9, - "tsharp_va": 0x100, - "ssharp": [0x92, 0xC00000, 0x14500000, 0], - }, - } - - def image(self, centre=(0.2, 0.4, 0.6, 1.0), probe=(0.8, 0.2, 0.1, 1.0)) -> bytes: - pixels = [[CLEAR] * 4 for _ in range(16)] - for x, y in ((1, 1), (2, 1), (1, 2), (2, 2)): - pixels[y * 4 + x] = list(centre) - pixels[1 * 4 + 1] = list(probe) - return struct.pack("<64f", *(v for pixel in pixels for v in pixel)) - - @staticmethod - def _make_raw(width: int, height: int, overrides: dict[tuple[int, int], tuple[float, float, float, float]]) -> bytes: - pixels = [[CLEAR] * 4 for _ in range(width * height)] - for (x, y), rgba in overrides.items(): - pixels[y * width + x] = list(rgba) - return struct.pack(f"<{width * height * 4}f", *(v for pixel in pixels for v in pixel)) - - def test_accepts_expected_textured_image(self): - check_image(self.image(), self.manifest) - - def test_rejects_magenta_fallback_texture(self): - with self.assertRaises(AssertionError): - check_image(self.image(centre=(1.0, 0.0, 1.0, 1.0)), self.manifest) - - def test_rejects_wrong_textured_probe(self): - with self.assertRaises(AssertionError): - check_image(self.image(probe=(0.1, 0.2, 0.8, 1.0)), self.manifest) - - def test_rejects_expected_rgba_with_wrong_channel_count(self): - for field, colour, next_red in ( - ("centre_rgba", self.manifest["centre_rgba"], CLEAR), - ("rgba_probes", self.manifest["rgba_probes"][0]["rgba"], 0.2), - ): - for values in ([], colour[:3], [*colour, next_red]): - with self.subTest(field=field, values=values): - manifest = self.manifest.copy() - if field == "centre_rgba": - manifest[field] = values - else: - manifest[field] = [{**self.manifest[field][0], "rgba": values}] - with self.assertRaisesRegex(AssertionError, f"{field}.*exactly four"): - check_image(self.image(), manifest) - - def test_compares_alpha_for_four_channel_expectations(self): - for probe, readback in ( - ("centre", self.image(centre=(0.2, 0.4, 0.6, 0.75))), - ("offset", self.image(probe=(0.8, 0.2, 0.1, 0.75))), - ): - with self.subTest(probe=probe): - with self.assertRaises(AssertionError): - check_image(readback, self.manifest) - - def test_sample_rgba_bilinear(self): - rgba = bytes( - [ - 255, 0, 0, 255, 0, 255, 0, 255, - 0, 0, 255, 255, 255, 255, 0, 255, - ] - ) - # Centre (0.5, 0.5) averages all 4 texels equally -> (0.5, 0.5, 0.25, 1.0). - mid = fl.sample_rgba_bilinear(2, 2, rgba, 0.5, 0.5) - for got, want in zip(mid, (0.5, 0.5, 0.25, 1.0)): - self.assertAlmostEqual(got, want, places=4) - # Clamped corner (0.0, 0.0) hits texel (0, 0) -> red. - tl = fl.sample_rgba_bilinear(2, 2, rgba, -0.5, -0.5) - for got, want in zip(tl, (1.0, 0.0, 0.0, 1.0)): - self.assertAlmostEqual(got, want, places=4) - - def test_harness_env_sets_texture_vars(self): - env = fl.harness_env(self.manifest, "/tmp/fl_out", base_env={}) - self.assertEqual(env["VKH_TSHARP_VA"], "0x100") - self.assertEqual(env["VKH_SSHARP"], "0x92,0xc00000,0x14500000,0x0") - sgprs = env["VKH_SGPRS"].split(",") - self.assertEqual(len(sgprs), 10) - self.assertEqual(sgprs[9], "0x100") - self.assertEqual(env["VKH_SUBGROUP_SIZE"], "32") - self.assertTrue(env["VKH_TEX_RGBA"].endswith("texture.rgba")) - - def test_harness_rejects_wrapped_tsharp_va_overflow(self): - h = harness() - if not h: - self.skipTest("vk_harness is not built") - import tempfile - - with tempfile.TemporaryDirectory() as td: - rgba_path = os.path.join(td, "tex.rgba") - fl.write_texture_rgba(rgba_path, 1, 1, bytes([255, 0, 0, 255])) - env = dict( - os.environ, - VKH_TEX_RGBA=rgba_path, - VKH_TSHARP_VA="0xFFFFFFE0", - ) - proc = subprocess.run( - [h, "unused_vs.spv", "unused_ps.spv", os.path.join(td, "out.raw"), "4", "4"], - env=env, - capture_output=True, - text=True, - ) - self.assertEqual(proc.returncode, 2) - self.assertIn("VKH_TSHARP_VA", proc.stderr) - - def test_decode_synthetic_dds_and_write_rgba(self): - import tempfile - - # Minimal valid 2x2 uncompressed R8G8B8A8 DDS (128-byte header + 16 bytes pixels). - dds = bytearray(128) - dds[0:4] = b"DDS " - struct.pack_into("= 1) - manifest = { - "width": 32, - "height": 32, - "min_coverage": 0.01, - "max_coverage": 0.99, - "clear_pixel": [31, 31], - "clear": -1.0, - "texture": {"width": 1, "height": 1}, - "rgba_tolerance": 0.02, - "rgba_probes": probes, - } - # Build synthetic image: covered pixels in the triangle set to red vs magenta fallback. - covered_pixels = { - (px, py) - for py in range(32) - for px in range(32) - if fl.uv_at(verts, indices, px, py, 32, 32) is not None - } - self.assertTrue(len(covered_pixels) > 0) - red_img = self._make_raw( - 32, 32, - {pos: (1.0, 0.0, 0.0, 1.0) for pos in covered_pixels}, - ) - res = fl.check_image(red_img, manifest) - self.assertEqual(res["covered"], len(covered_pixels)) - magenta_img = self._make_raw( - 32, 32, - {pos: (1.0, 0.0, 1.0, 1.0) for pos in covered_pixels}, - ) - with self.assertRaises(AssertionError): - fl.check_image(magenta_img, manifest) - # Empty-probe textured manifest and fallback-indistinguishable expected colour are both rejected. - empty_manifest = dict(manifest, rgba_probes=[]) - with self.assertRaises(AssertionError): - fl.check_image(magenta_img, empty_manifest) - magenta_manifest = dict( - manifest, - rgba_probes=[{"pixel": probes[0]["pixel"], "uv": [0.0, 0.0], "rgba": [1.0, 0.0, 1.0, 1.0]}], - ) - with self.assertRaises(AssertionError): - fl.check_image(magenta_img, magenta_manifest) - - def test_nan_channels_rejected(self): - nan = float("nan") - # NaN in centre_rgba must fail (abs(NaN) > tol is False without an explicit finiteness check). - with self.assertRaises(AssertionError): - fl.check_image(self.image(centre=(nan, 0.4, 0.6, 1.0)), self.manifest) - # NaN in rgba_probes must fail. - with self.assertRaises(AssertionError): - fl.check_image(self.image(probe=(0.8, nan, 0.1, 1.0)), self.manifest) - # NaN in clear_pixel must fail. - raw_clear_nan = self._make_raw( - 4, 4, - { - (0, 0): (nan, -1.0, -1.0, -1.0), - (1, 1): (0.8, 0.2, 0.1, 1.0), - (2, 1): (0.2, 0.4, 0.6, 1.0), - (1, 2): (0.2, 0.4, 0.6, 1.0), - (2, 2): (0.2, 0.4, 0.6, 1.0), - }, - ) - with self.assertRaises(AssertionError): - fl.check_image(raw_clear_nan, self.manifest) - - def test_transparent_unorm_fragments_counted_as_covered(self): - # Valid transparent-red UNORM fragments (alpha == 0.0) must be counted as covered by - # distinguishing them from the -1.0 clear sentinel rather than requiring alpha > 0.5. - manifest = { - "width": 4, - "height": 4, - "min_coverage": 0.2, - "max_coverage": 0.9, - "centre_pixel": [2, 2], - "centre_rgba": [1.0, 0.0, 0.0, 0.0], - "clear_pixel": [0, 0], - "clear": -1.0, - "texture": {"width": 1, "height": 1}, - "rgba_tolerance": 0.02, - "rgba_probes": [{"pixel": [1, 1], "uv": [0.0, 0.0], "rgba": [1.0, 0.0, 0.0, 0.0]}], - } - overrides = {(x, y): (1.0, 0.0, 0.0, 0.0) for x in (1, 2) for y in (1, 2)} - raw = self._make_raw(4, 4, overrides) - res = fl.check_image(raw, manifest) - self.assertEqual(res["covered"], 4) - self.assertAlmostEqual(res["ratio"], 0.25) - - -def vs_on_cpu(sgprs: str, heap: str, x: float, y: float, z: float): - """CAMERA_VS's arithmetic, reading its constants the way its scalar loads do: the table address from s9, a V# - at table + 0x20 (world rows at 0x00..0x30) and one at table + 0x60 (view-projection rows at 0x160..0x19f).""" - s = [int(w, 0) for w in sgprs.split(",")] - words = {} - for item in heap.split(","): - addr, word = item.split("=") - words[int(addr, 0)] = int(word, 0) - - def dword(addr): - return words.get(addr, 0) - - def f(addr): - return struct.unpack(" None: - self.root = Path(self.enterContext(tempfile.TemporaryDirectory())) - self.enterContext(patch.object(first_light, "ROOT", str(self.root))) - self.enterContext(patch.dict(os.environ)) - os.environ.pop("LEONIDA_VK_HARNESS", None) - self.executable = "vk_harness.exe" if os.name == "nt" else "vk_harness" - - def put_harness(self, *parts: str) -> Path: - path = self.root.joinpath(*parts, self.executable) - path.parent.mkdir(parents=True, exist_ok=True) - path.touch() - return path - - def test_finds_windows_release_configuration(self) -> None: - release = self.put_harness("runtime", "build", "windows", "Release") - self.assertEqual(first_light.find_harness(None), str(release)) - - def test_finds_relwithdebinfo_in_the_standard_build_tree(self) -> None: - self.put_harness("runtime", "build", "Release") - optimized = self.put_harness("runtime", "build", "RelWithDebInfo") - self.assertEqual(first_light.find_harness(None), str(optimized)) - - def test_standalone_harness_keeps_priority_over_configured_harness(self) -> None: - self.put_harness("runtime", "build", "windows", "Release") - standalone = self.put_harness("runtime", "build") - self.assertEqual(first_light.find_harness(None), str(standalone)) - - def test_explicit_and_environment_paths_keep_priority(self) -> None: - configured = self.put_harness("runtime", "build", "windows", "Release") - explicit = self.put_harness("explicit") - environment = self.put_harness("environment") - os.environ["LEONIDA_VK_HARNESS"] = str(environment) - self.assertEqual(first_light.find_harness(str(explicit)), str(explicit)) - self.assertEqual(first_light.find_harness(str(explicit) + ".missing"), str(environment)) - environment.unlink() - self.assertEqual(first_light.find_harness(None), str(configured)) - - def put_sources(self) -> Path: - test = self.root / "runtime" / "test" - test.mkdir(parents=True, exist_ok=True) - (test / "vk_harness.cpp").write_text('#include "../src/table.h"\n', encoding="utf-8") - (self.root / "runtime" / "src").mkdir(exist_ok=True) - (self.root / "runtime" / "src" / "table.h").write_text("", encoding="utf-8") - return test - - def find_with_stderr(self) -> tuple[str, str]: - err = io.StringIO() - with contextlib.redirect_stderr(err): - found = first_light.find_harness(None) - return found, err.getvalue() - - def test_a_harness_older_than_its_sources_is_reported(self) -> None: - # Old #7148: a harness built before a pull drew with the old program and said nothing. - harness = self.put_harness("runtime", "build", "linux") - self.put_sources() - os.utime(harness, (1_000_000, 1_000_000)) - found, err = self.find_with_stderr() - self.assertEqual(found, str(harness)) - self.assertIn("WARNING", err) - self.assertIn("runtime/test/vk_harness.cpp", err) - self.assertIn("runtime/src/table.h", err) - self.assertIn("--target vk_harness", err) - - def test_a_current_harness_is_used_quietly(self) -> None: - self.put_sources() - harness = self.put_harness("runtime", "build", "linux") - future = os.path.getmtime(self.root / "runtime" / "src" / "table.h") + 60 - os.utime(harness, (future, future)) - found, err = self.find_with_stderr() - self.assertEqual(found, str(harness)) - self.assertEqual(err, "") - - def test_a_harness_outside_the_build_folder_is_not_compared(self) -> None: - self.put_sources() - explicit = self.put_harness("explicit") - os.utime(explicit, (1_000_000, 1_000_000)) - err = io.StringIO() - with contextlib.redirect_stderr(err): - self.assertEqual(first_light.find_harness(str(explicit)), str(explicit)) - self.assertEqual(err.getvalue(), "") - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/test_first_light_mesh_draw.py b/tests/test_first_light_mesh_draw.py deleted file mode 100644 index 96be1f207..000000000 --- a/tests/test_first_light_mesh_draw.py +++ /dev/null @@ -1,81 +0,0 @@ -"""First Light must not render geometry left by an earlier preparation run.""" - -import json -from pathlib import Path -import struct -import sys -import tempfile -import unittest -from unittest.mock import patch - -sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "tools")) -import first_light - - -class FirstLightMeshDrawTests(unittest.TestCase): - def setUp(self) -> None: - self.work = Path(self.enterContext(tempfile.TemporaryDirectory())) - self.out = self.work / "out" - self.out.mkdir() - self.mesh = self.out / "mesh.bin" - self.mesh.write_bytes(b"previous mesh placeholder") - dxbc = self.work / "shaders" / "dxbc" - spirv = self.work / "first_light" / "spirv" - dxbc.mkdir(parents=True) - spirv.mkdir(parents=True) - picks = [] - for stage in ("vs", "ps"): - (dxbc / f"{stage}.dxbc").touch() - (spirv / f"{stage}.spv").touch() - picks.append({"stage": stage, "name": stage, "file": f"{stage}.dxbc"}) - self.enterContext(patch.multiple( - first_light, - ensure_carve=lambda *args: "stub-index", - choose=lambda *args: picks, - translate=lambda *args: {"vs": {}, "ps": {}}, - find_harness=lambda *args: "stub-harness", - )) - self.draw = self.enterContext(patch.object(first_light.subprocess, "run", side_effect=self.write_readback)) - - @staticmethod - def write_readback(arguments: list[str], *, env: dict[str, str], check: bool) -> None: - if not Path(env["VKH_DRAW_MESH"]).is_file(): - raise AssertionError("the harness received no mesh") - pixels = (0.0, 0.0, 0.0, 1.0) * 2 + (-1.0,) * 8 - Path(arguments[3]).write_bytes(struct.pack("<16f", *pixels)) - - def prepare(self, *args: str) -> int: - return first_light.main([ - "--game", str(self.work), "--work", str(self.work), "--out", str(self.out), - "--no-fit", "--width", "2", "--height", "2", *args, - ]) - - def test_run_without_obj_never_draws_the_previous_mesh(self) -> None: - with self.assertRaisesRegex(SystemExit, "requires an OBJ with faces"): - self.prepare("--run") - self.draw.assert_not_called() - self.assertFalse((self.out / "image.raw").exists()) - - def test_prepare_without_obj_is_allowed_but_cannot_be_replayed(self) -> None: - self.assertEqual(self.prepare(), 0) - self.draw.assert_not_called() - manifest = json.loads((self.out / "manifest.json").read_text(encoding="utf-8")) - self.assertEqual((manifest["vertex_count"], manifest["index_count"]), (0, 0)) - self.assertFalse(self.mesh.is_file()) # a run without an OBJ removes the previous run's mesh.bin (95ebfb8e9) - with self.assertRaisesRegex(SystemExit, "requires an OBJ with faces"): - first_light.main(["--check", "--out", str(self.out)]) - self.draw.assert_not_called() - - def test_check_can_replay_a_manifest_for_prepared_geometry(self) -> None: - vertices = [(0.0, 0.0, 0.5, 0.0, 0.0), (1.0, 0.0, 0.5, 1.0, 0.0), (0.0, 1.0, 0.5, 0.0, 1.0)] - first_light.write_mesh(self.mesh, vertices, [0, 1, 2]) - (self.out / "manifest.json").write_text( - '{"width": 2, "height": 2, "vertex_count": 3, "index_count": 3, "files": {"mesh": "mesh.bin"}}', - encoding="utf-8", newline="\n", - ) - self.assertEqual(first_light.main(["--check", "--out", str(self.out)]), 0) - self.draw.assert_called_once() - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/test_first_light_stale_mesh.py b/tests/test_first_light_stale_mesh.py deleted file mode 100644 index b87da4b04..000000000 --- a/tests/test_first_light_stale_mesh.py +++ /dev/null @@ -1,47 +0,0 @@ -"""first_light: a preparation run without an OBJ must not leave (and then draw) the mesh.bin of an earlier run. - -The carve, translation and draw are stubbed; the folders hold placeholder bytes only. No game data, no GPU. -""" -import os -import sys -import tempfile -import unittest - -HERE = os.path.dirname(os.path.abspath(__file__)) -sys.path.insert(0, os.path.join(os.path.dirname(HERE), "tools")) -import first_light # noqa: E402 - - -class StaleMesh(unittest.TestCase): - def test_run_without_obj_drops_old_mesh(self): - with tempfile.TemporaryDirectory() as tmp: - work, out, game = (os.path.join(tmp, n) for n in ("work", "out", "game")) - os.makedirs(os.path.join(work, "first_light", "spirv")) - os.makedirs(os.path.join(work, "shaders", "dxbc")) - os.makedirs(out) - os.makedirs(game) - picked = [{"stage": "vs", "file": "a.dxbc", "name": "a"}, {"stage": "ps", "file": "b.dxbc", "name": "b"}] - for e in picked: - stem = os.path.splitext(e["file"])[0] - for path in (os.path.join(work, "first_light", "spirv", stem + ".spv"), - os.path.join(work, "shaders", "dxbc", e["file"])): - with open(path, "wb") as f: - f.write(b"x") - mesh = os.path.join(out, "mesh.bin") - with open(mesh, "wb") as f: - f.write(b"old mesh") - seen = [] - saved = (first_light.ensure_carve, first_light.choose, first_light.translate, first_light.run_draw) - first_light.ensure_carve = lambda g, w: "index" - first_light.choose = lambda i, v, p: picked - first_light.translate = lambda w, p: {"vs": {}, "ps": {}} - first_light.run_draw = lambda a, m, o: seen.append(os.path.exists(mesh)) - try: - first_light.main(["--game", game, "--work", work, "--out", out, "--no-fit", "--run"]) - finally: - (first_light.ensure_carve, first_light.choose, first_light.translate, first_light.run_draw) = saved - self.assertEqual(seen, [False]) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/test_first_look_exit.py b/tests/test_first_look_exit.py deleted file mode 100644 index 3c6725713..000000000 --- a/tests/test_first_look_exit.py +++ /dev/null @@ -1,122 +0,0 @@ -"""Exercise the Windows diagnostics script with a synthetic inspector and loader.""" -import os -from pathlib import Path -import shutil -import subprocess -import sys -import tempfile -import unittest - - -SCRIPT = Path(__file__).resolve().parents[1] / "scripts" / "first_look.ps1" -POWERSHELL = ["powershell.exe", "-NoProfile", "-NonInteractive", "-ExecutionPolicy", "Bypass"] - - -@unittest.skipUnless(os.name == "nt", "Windows PowerShell diagnostics script") -class FirstLookExitTest(unittest.TestCase): - def test_reports_are_written_and_dry_run_exit_status_is_returned(self): - with tempfile.TemporaryDirectory() as directory: - root = Path(directory) - scripts = root / "scripts" - tools = root / "tools" - build = root / "runtime" / "build" - for folder in (scripts, tools, build): - folder.mkdir(parents=True) - wrapper = Path(shutil.copyfile(SCRIPT, scripts / SCRIPT.name)) - (tools / "pe_inspect.py").write_text( - "from pathlib import Path\n" - "import sys\n" - "report = Path(sys.argv[-1]) / (Path(sys.argv[1]).name + '.json')\n" - "report.write_text('{\"imports\":[{\"where\":\"shim\",\"dll\":\"stub.dll\"," - "\"functions\":[\"Example\"]}],\"sections\":[]}', encoding='utf-8', newline='\\n')\n", - encoding="utf-8", newline="\n", - ) - compile_loader = ( - "$ErrorActionPreference = 'Stop'; " - "Add-Type -OutputAssembly gta6rt.exe -OutputType ConsoleApplication -TypeDefinition @'\n" - "public class Loader { public static int Main() {\n" - " int code = int.Parse(System.Environment.GetEnvironmentVariable(\"LEONIDA_TEST_LOADER_EXIT\"));\n" - " var dir = new System.IO.DirectoryInfo(System.AppDomain.CurrentDomain.BaseDirectory);\n" - " (code == 0 ? System.Console.Out : System.Console.Error).WriteLine(\"synthetic dry run from \" + dir.Name);\n" - " return code;\n" - "} }\n'@" - ) - env = {**os.environ, "PATH": str(Path(sys.executable).parent) + os.pathsep + os.environ["PATH"]} - # Keep Core's modules out of Windows PowerShell's search path when Python was started from pwsh. - env["PSModulePath"] = str(Path(os.environ["SystemRoot"]) / "System32/WindowsPowerShell/v1.0/Modules") - subprocess.run([*POWERSHELL, "-Command", compile_loader], cwd=scripts, env=env, check=True, timeout=30) - fixture = scripts / "gta6rt.exe" - (scripts / "build_runtime.ps1").write_text( - 'Copy-Item "$PSScriptRoot/gta6rt.exe" "$PSScriptRoot/../runtime/build/gta6rt.exe"\n' - 'New-Item -ItemType File -Force "$PSScriptRoot/../runtime/build/gta6rt_tls_host.dll" | Out-Null\n' - 'Set-Content "$PSScriptRoot/built.txt" built\n', encoding="utf-8", newline="\n", - ) - source = root / "runtime" / "src" / "loader.cpp" - source.parent.mkdir() - source.touch() - marker = scripts / "built.txt" - cmake = scripts / "cmake.cmd" - cmake.write_text( - '@echo off\nset "cfg=%~6"\nif not defined cfg set "cfg=Debug"\n' - 'if not exist "%~2\\%cfg%" mkdir "%~2\\%cfg%"\n' - 'copy /y "%~dp0gta6rt.exe" "%~2\\%cfg%\\gta6rt.exe" >nul\n' - 'type nul > "%~2\\%cfg%\\gta6rt_tls_host.dll"\n' - 'echo %cfg% > "%~dp0built.txt"\n', encoding="ascii", - ) - vs_configs = { - "vs-missing-dll": "Debug;Release;RelWithDebInfo", - "vs-first": "Debug;Release;MinSizeRel;RelWithDebInfo", - "vs-release-only": "Release", - "vs-stale-Release": "Debug;Release;RelWithDebInfo", - } - cases = ( - ("Debug", ["Debug"], "Debug", False, 0), - ("MinSizeRel", ["MinSizeRel", "Debug"], "MinSizeRel", False, 0), - ("Release", ["Release", "MinSizeRel"], "Release", False, 0), - ("RelWithDebInfo", ["RelWithDebInfo", "Release"], "RelWithDebInfo", False, 0), - ("flat", ["", "RelWithDebInfo"], "build", False, 17), - ("stale-Release", ["Release"], "build", True, 0), - ("missing", [], "build", True, 0), - ("vs-missing-dll", ["Release"], "Release", True, 0), - ("vs-first", [], "RelWithDebInfo", True, 0), - ("vs-release-only", [], "Release", True, 0), - ("vs-stale-Release", ["Release"], "Release", True, 0), - ) - for layout, folders, expected_dir, should_build, code in cases: - with self.subTest(layout=layout): - shutil.rmtree(build) - build.mkdir() - marker.unlink(missing_ok=True) - if layout in vs_configs: - (build / "CMakeCache.txt").write_text( - "CMAKE_GENERATOR:INTERNAL=Visual Studio 17 2022\n" - f"CMAKE_COMMAND:INTERNAL={cmake}\n" - f"CMAKE_CONFIGURATION_TYPES:STRING={vs_configs[layout]}\n", encoding="utf-8", - ) - for folder in folders: - loader = build / folder / "gta6rt.exe" - loader.parent.mkdir(exist_ok=True) - shutil.copyfile(fixture, loader) - if layout != "vs-missing-dll": - loader.with_name("gta6rt_tls_host.dll").touch() - if layout in ("stale-Release", "vs-stale-Release"): - older = source.stat().st_mtime - 3600 - os.utime(loader, (older, older)) - image = root / f"fixture-{layout}.exe" - image.write_bytes(b"MZ") - result = subprocess.run( - [*POWERSHELL, "-File", str(wrapper), "-Exe", str(image)], - env={**env, "LEONIDA_TEST_LOADER_EXIT": str(code)}, capture_output=True, text=True, timeout=30, - ) - report = root / "reports" / "exe" / image.stem - self.assertEqual(marker.exists(), should_build, result.stdout + result.stderr) - if layout in vs_configs: - self.assertEqual(marker.read_text(encoding="ascii").strip(), expected_dir) - self.assertTrue((report / "shim-todo.txt").is_file(), result.stdout + result.stderr) - self.assertIn("synthetic dry run from " + expected_dir, - (report / "dryrun.txt").read_text(encoding="utf-16")) - self.assertEqual(result.returncode, code, result.stdout + result.stderr) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/test_first_look_paths.py b/tests/test_first_look_paths.py deleted file mode 100644 index 3e198f02d..000000000 --- a/tests/test_first_look_paths.py +++ /dev/null @@ -1,91 +0,0 @@ -"""Exercise the day-one report from a PowerShell location different from the process working directory.""" -import hashlib -import json -import os -from pathlib import Path -import shutil -import subprocess -import sys -import tempfile -import unittest - -sys.path.insert(0, str(Path(__file__).resolve().parent)) -from test_pe_inspect import build_image - - -@unittest.skipUnless(os.name == "nt", "Windows PowerShell first-look diagnostics") -class FirstLookPathTests(unittest.TestCase): - def test_literal_image_loader_and_report_paths(self): - source = Path(__file__).resolve().parents[1] - with tempfile.TemporaryDirectory() as tmp: - repo = Path(tmp, "checkout [1]") - for folder in ("scripts", "tools", "runtime/build/Release"): - (repo / folder).mkdir(parents=True) - for relative in ("scripts/first_look.ps1", "tools/pe_inspect.py", "tools/gdk_runtime_calls.py", - "tools/gdk_runtime_classes.json", "tools/find_hash_lookup.py", "tools/exe_checklist.py", - "tools/report_paths.py"): - shutil.copyfile(source / relative, repo / relative) - game = Path(tmp, "package [1]") - game.mkdir() - image = game / "fixture[1].exe" - # Keep a bundled import and a missing import so both reports have evidence. - image.write_bytes(build_image().replace(b"kernel32.dll", b"fake_lib.dll")) - (game / "fixture1.exe").write_bytes(b"wrong file") - (game / "xmem.dll").touch() - env = { - **os.environ, - "PATH": str(Path(sys.executable).parent) + os.pathsep + os.environ["PATH"], - "PSModulePath": str(Path(os.environ["SystemRoot"], "System32/WindowsPowerShell/v1.0/Modules")), - "FIRST_LOOK_SCRIPT": str(repo / "scripts/first_look.ps1"), - "FIRST_LOOK_PACKAGE": str(game), - } - ps = ["powershell.exe", "-NoProfile", "-NonInteractive", "-ExecutionPolicy", "Bypass", "-Command"] - # Stand-in for gta6rt: record the actual arguments in the normal dry-run report. - subprocess.run([*ps, """$ErrorActionPreference = 'Stop' -Add-Type -OutputAssembly gta6rt.exe -OutputType ConsoleApplication -TypeDefinition ' -public class Loader { public static void Main(string[] args) { System.Console.WriteLine(string.Join("\\n", args)); } }' -"""], cwd=tmp, env=env, check=True, timeout=30) - loader = repo / "runtime/build/Release/gta6rt.exe" - shutil.move(Path(tmp, "gta6rt.exe"), loader) - loader.with_name("gta6rt_tls_host.dll").touch() - command = [*ps, "Set-Location -LiteralPath $env:FIRST_LOOK_PACKAGE; " - "& $env:FIRST_LOOK_SCRIPT -Exe 'fixture[1].exe'"] - result = subprocess.run(command, cwd=tmp, env=env, capture_output=True, timeout=30) - self.assertEqual(result.returncode, 0, result.stdout + result.stderr) - out = repo / "reports/exe" / image.stem - self.assertIn(hashlib.sha256(image.read_bytes()).hexdigest(), (out / "hash.txt").read_text("utf-16")) - # PowerShell's Resolve-Path hands the loader the canonical path: on Windows tempfile gives the 8.3 - # name (RUNNER~1) and resolve() expands it to the long one. - self.assertEqual((out / "dryrun.txt").read_text("utf-16").splitlines(), - ["--dry-run", str(image.resolve()), "--game-dir", str(game.resolve())]) - imports = json.loads((out / (image.name + ".json")).read_text("utf-8"))["imports"] - self.assertTrue(any(d["dll"].lower() == "xmem.dll" and d["where"] == "bundled" for d in imports)) - self.assertIn("fake_lib.dll", (out / "shim-todo.txt").read_text()) - self.assertIn("the called ones come first", (out / "checklist.md").read_text("utf-8")) - - # A source update in the bracketed checkout must still trigger the rebuild. - source_dir = repo / "runtime/src" - source_dir.mkdir() - (source_dir / "main.cpp").touch() - older = (source_dir / "main.cpp").stat().st_mtime - 3600 - os.utime(loader, (older, older)) - (repo / "scripts/build_runtime.ps1").write_text( - 'Copy-Item -LiteralPath "$PSScriptRoot/../runtime/build/Release/gta6rt.exe" ' - '-Destination "$PSScriptRoot/../runtime/build/gta6rt.exe"\n' - 'Copy-Item -LiteralPath "$PSScriptRoot/../runtime/build/Release/gta6rt_tls_host.dll" ' - '-Destination "$PSScriptRoot/../runtime/build/gta6rt_tls_host.dll"\n' - 'Set-Content -LiteralPath (Join-Path $PSScriptRoot "built.txt") -Value built\n', - encoding="utf-8", newline="\n", - ) - rebuilt = subprocess.run(command, cwd=tmp, env=env, capture_output=True, timeout=30) - self.assertEqual(rebuilt.returncode, 0, rebuilt.stdout + rebuilt.stderr) - self.assertTrue((repo / "scripts/built.txt").is_file()) - - image.unlink() # fixture1.exe still exists and would match the wildcard. - missing = subprocess.run(command, cwd=tmp, env=env, capture_output=True, timeout=30) - self.assertNotEqual(missing.returncode, 0) - self.assertIn(b"fixture[1].exe not found", missing.stderr) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/test_first_look_rebuild.py b/tests/test_first_look_rebuild.py deleted file mode 100644 index d2fc31f98..000000000 --- a/tests/test_first_look_rebuild.py +++ /dev/null @@ -1,137 +0,0 @@ -"""scripts/first_look.ps1 checks for a current and complete runtime before a dry run. - - python -I tests/test_first_look_rebuild.py - -A gta6rt.exe from before a pull still runs, but its dry run reports the old shim table: the day-one import to-do list -would be wrong without any error. The script used to build the loader only when it was missing. No game files. -""" -import os -import shutil -import subprocess -import sys -import tempfile -import time -import unittest -from pathlib import Path - -ROOT = Path(__file__).resolve().parents[1] -SCRIPT = ROOT / "scripts" / "first_look.ps1" -PE_INSPECT_STUB = ( - "from pathlib import Path\n" - "import sys\n" - "report = Path(sys.argv[-1]) / (Path(sys.argv[1]).name + '.json')\n" - "report.write_text('{\"imports\":[],\"sections\":[]}', encoding='utf-8', newline='\\n')\n" -) -# Stubs for the three tools first_look.ps1 runs after pe_inspect. Each one -# accepts its real arguments (argparse would reject unknown flags) but does -# nothing. A missing stub makes python exit 2 ("can't open file"), which -# becomes $LASTEXITCODE and propagates through the script's `exit -# $dryRunExitCode` path, failing the test on assertEqual(code, 0). -GDK_RUNTIME_CALLS_STUB = "import sys\n" -FIND_HASH_LOOKUP_STUB = ( - "from pathlib import Path\n" - "import sys\n" - "for a in sys.argv:\n" - " if a.endswith('.json'):\n" - " Path(a).parent.mkdir(parents=True, exist_ok=True)\n" - " Path(a).write_text('{}', encoding='utf-8', newline='\\n')\n" -) -EXE_CHECKLIST_STUB = "import sys\n" -# The build script leaves a marker; the loader is replaced by an alias that echoes its arguments. -BUILD_STUB = r""" -Set-Content -LiteralPath (Join-Path $PSScriptRoot 'built.txt') -Value 'built' -if ($env:LEONIDA_TEST_INCOMPLETE_RUNTIME -ne '1') { - $build = Join-Path (Split-Path $PSScriptRoot -Parent) 'runtime\build' - foreach ($name in 'gta6rt.exe', 'gta6rt_tls_host.dll') { - New-Item -ItemType File -Path (Join-Path $build $name) -Force | Out-Null - } -} -""" -RUN = r""" -$ErrorActionPreference = 'Stop' -Set-Alias -Name (Join-Path $PWD 'runtime\build\gta6rt.exe') -Value (Join-Path $PWD 'loader.cmd') -& .\scripts\first_look.ps1 -Exe (Join-Path $PWD 'fixture.exe') -""" - - -@unittest.skipUnless(os.name == "nt", "Windows PowerShell diagnostics script") -class FirstLookRebuildTest(unittest.TestCase): - def run_case(self, source_newer=False, missing=(), incomplete_build=False, cache=None): - with tempfile.TemporaryDirectory() as tmp: - root = Path(tmp) - for folder in ("scripts", "tools", "runtime/build", "runtime/src"): - (root / folder).mkdir(parents=True) - shutil.copyfile(SCRIPT, root / "scripts" / SCRIPT.name) - (root / "scripts" / "build_runtime.ps1").write_text(BUILD_STUB, encoding="utf-8") - (root / "tools" / "pe_inspect.py").write_text(PE_INSPECT_STUB, encoding="utf-8", newline="\n") - (root / "tools" / "gdk_runtime_calls.py").write_text(GDK_RUNTIME_CALLS_STUB, encoding="utf-8", newline="\n") - (root / "tools" / "find_hash_lookup.py").write_text(FIND_HASH_LOOKUP_STUB, encoding="utf-8", newline="\n") - (root / "tools" / "exe_checklist.py").write_text(EXE_CHECKLIST_STUB, encoding="utf-8", newline="\n") - (root / "fixture.exe").write_bytes(b"MZ") - (root / "loader.cmd").write_text("@echo off\necho %*\nexit /b 0\n", encoding="ascii") - loader = root / "runtime" / "build" / "gta6rt.exe" - if cache is not None: - (loader.parent / "CMakeCache.txt").write_text(cache, encoding="utf-8") - source = root / "runtime" / "src" / "pe_loader.cpp" - tls = loader.with_name("gta6rt_tls_host.dll") - loader.write_bytes(b"") - tls.touch() - source.write_text("// source\n", encoding="utf-8") - now = time.time() - older, newer = now - 3600, now - os.utime(loader, (newer, newer) if not source_newer else (older, older)) - os.utime(source, (newer, newer) if source_newer else (older, older)) - for name in missing: - loader.with_name(name).unlink() - env = {k: v for k, v in os.environ.items() if k.upper() != "PSMODULEPATH"} - env["PATH"] = str(Path(sys.executable).parent) + os.pathsep + env["PATH"] - env["LEONIDA_TEST_INCOMPLETE_RUNTIME"] = "1" if incomplete_build else "0" - run = subprocess.run(["powershell.exe", "-NoProfile", "-NonInteractive", "-ExecutionPolicy", "Bypass", - "-Command", RUN], cwd=root, env=env, capture_output=True, text=True, timeout=60) - dry_run = (root / "reports" / "exe" / "fixture" / "dryrun.txt").is_file() - return (root / "scripts" / "built.txt").is_file(), dry_run, run.returncode, run.stdout + run.stderr - - def test_a_loader_older_than_the_sources_is_rebuilt(self): - built, dry_run, code, out = self.run_case(source_newer=True) - self.assertTrue(built, out) - self.assertTrue(dry_run, out) - self.assertEqual(code, 0, out) - self.assertIn("rebuilding it first", out) - - def test_an_up_to_date_loader_is_used_as_it_is(self): - built, dry_run, code, out = self.run_case() - self.assertFalse(built, out) - self.assertTrue(dry_run, out) - self.assertEqual(code, 0, out) - - def test_a_missing_runtime_file_is_rebuilt(self): - for name in ("gta6rt.exe", "gta6rt_tls_host.dll"): - with self.subTest(name=name): - built, dry_run, code, out = self.run_case(missing=(name,)) - self.assertTrue(built, out) - self.assertTrue(dry_run, out) - self.assertEqual(code, 0, out) - - def test_an_incomplete_build_stops_before_the_dry_run(self): - built, dry_run, code, out = self.run_case(missing=("gta6rt_tls_host.dll",), incomplete_build=True) - self.assertTrue(built, out) - self.assertFalse(dry_run, out) - self.assertNotEqual(code, 0, out) - self.assertIn("runtime build did not produce", out) - self.assertIn("gta6rt_tls_host.dll", out) - - def test_incomplete_visual_studio_cache_names_the_missing_command(self): - generator = "CMAKE_GENERATOR:INTERNAL=Visual Studio 17 2022\n" - for command in ("", "CMAKE_COMMAND:INTERNAL=\n"): - with self.subTest(command=command): - built, dry_run, code, out = self.run_case(source_newer=True, cache=generator + command) - self.assertNotEqual(code, 0, out) - self.assertFalse(built, out) - self.assertIn("CMakeCache.txt", out) - self.assertIn("Reconfigure", out) - self.assertIn("CMAKE_COMMAND", out) - self.assertFalse(dry_run, out) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/test_first_look_shim_report.py b/tests/test_first_look_shim_report.py deleted file mode 100644 index 57c9a3809..000000000 --- a/tests/test_first_look_shim_report.py +++ /dev/null @@ -1,72 +0,0 @@ -"""Exercise the on-disk first-look report while a missing dependency is supplied.""" -import json -import os -from pathlib import Path -import shutil -import subprocess -import sys -import tempfile -import unittest - -sys.path.insert(0, str(Path(__file__).resolve().parent)) -from test_pe_inspect import build_image - - -@unittest.skipUnless(os.name == "nt", "Windows PowerShell diagnostics") -class FirstLookShimReportTest(unittest.TestCase): - def test_retry_with_last_missing_dll_supplied(self): - source = Path(__file__).resolve().parents[1] - with tempfile.TemporaryDirectory() as tmp: - root = Path(tmp) - # Every tool first_look.ps1 runs: a missing one fails its step, and the test's stand-in loader (an alias) - # leaves that exit code in $LASTEXITCODE for the script's exit. (gdk_runtime_calls since round 43, - # find_hash_lookup for mods, exe_checklist for the notes to confirm.) gdk_runtime_calls, find_hash_lookup - # and exe_checklist import tools/report_paths.py for the shared output-overwrite guard, so the copy needs - # it too or each tool stops at import with ModuleNotFoundError. - for name in ("scripts/first_look.ps1", "tools/pe_inspect.py", "tools/gdk_runtime_calls.py", - "tools/gdk_runtime_classes.json", "tools/find_hash_lookup.py", "tools/exe_checklist.py", - "tools/report_paths.py"): - (root / name).parent.mkdir(exist_ok=True) - shutil.copyfile(source / name, root / name) - loader = root / "runtime/build/gta6rt.exe" - loader.parent.mkdir(parents=True) - loader.touch() - loader.with_name("gta6rt_tls_host.dll").touch() - (root / "fixture.exe").write_bytes(build_image().replace(b"xmem.dll", b"demo.dll")) - # The report depends on the real PE inspection. Echo the dry-run arguments - # in place of a native loader so the test needs no runtime build. - script = r""" -$ErrorActionPreference = 'Stop' -Set-Alias -Name (Join-Path $PWD 'runtime\build\gta6rt.exe') -Value Write-Output -& .\scripts\first_look.ps1 -Exe (Join-Path $PWD 'fixture.exe') -""" - env = {k: v for k, v in os.environ.items() if k.upper() != "PSMODULEPATH"} - env["PATH"] = str(Path(sys.executable).parent) + os.pathsep + env["PATH"] - reports = root / "reports/exe/fixture" - todo = reports / "shim-todo.txt" - - def run_first_look(): - run = subprocess.run( - ["powershell.exe", "-NoProfile", "-NonInteractive", "-ExecutionPolicy", "Bypass", - "-Command", script], cwd=root, env=env, capture_output=True, timeout=30, - ) - self.assertEqual(run.returncode, 0, run.stderr) - # A failed find_hash_lookup step is only a warning in the script and later steps reset - # $LASTEXITCODE, so the exit status doesn't show it: check that each step wrote its report. - for report in ("fixture.exe.gdk_calls.json", "hash_lookup.json"): - self.assertTrue((reports / report).is_file(), (report, run.stdout, run.stderr)) - imports = json.loads((reports / "fixture.exe.json").read_text("utf-8"))["imports"] - return {entry["dll"].lower() for entry in imports if entry["where"] == "shim"} - - self.assertEqual(run_first_look(), {"demo.dll"}) - self.assertIn("demo.dll", todo.read_text().lower()) - (root / "demo.dll").touch() - self.assertEqual(run_first_look(), set()) - self.assertEqual(todo.read_bytes(), b"") - todo.unlink() - self.assertEqual(run_first_look(), set()) - self.assertEqual(todo.read_bytes(), b"") - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/test_fma_mix_literal_probe.py b/tests/test_fma_mix_literal_probe.py deleted file mode 100644 index 7b87a0e2a..000000000 --- a/tests/test_fma_mix_literal_probe.py +++ /dev/null @@ -1,102 +0,0 @@ -"""tools/fma_mix_literal_probe.py: the cases tell the two readings of a split v_fma_mix literal apart, the encodings -are the ones described, the translator side follows the halves reading, and a missing GPU is exit 77. Standard -library only; no GPU, no LLVM, no game files. - -The expected values are worked out by hand (src1 is v2 = 2.0; f16 0x4000 = 2.0, 0x4200 = 3.0, 0xbc00 = -1.0; f32 -0x40400000 = 3.0). No low half is an inline f16 constant, so llvm-mc prints each literal as the plain hex the listing -uses (an inline one, such as 0x3c00, prints as lit(0x...)): - - A fma(lo 3.0, 2.0, hi 2.0) = 8.0 low reading: fma(3.0, 2.0, 0.0) = 6.0 - B fma(hi 3.0, 2.0, hi 3.0) = 9.0 low reading: fma(0.0, 2.0, 0.0) = 0.0 - E fma(2.0, 2.0, hi -1.0) = 3.0 low reading: fma(2.0, 2.0, 0.0) = 4.0 - C fma(3.0, 2.0, 3.0) = 9.0 either way - D fma(3.0, 2.0, 2.0) = 8.0 either way -""" -import contextlib -import io -import os -import struct -import sys -import unittest -from unittest import mock - -ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) -sys.dont_write_bytecode = True -sys.path.insert(0, os.path.join(ROOT, "tools")) -sys.path.insert(0, os.path.join(ROOT, "tests", "semantic")) - -import fma_mix_literal_probe as probe # noqa: E402 - -BY_HAND = {"A": (8.0, 6.0), "B": (9.0, 0.0), "E": (3.0, 4.0), "C": (9.0, 9.0), "D": (8.0, 8.0)} - - -def f(word): - return struct.unpack("> 26, 0b110011) # VOP3P - self.assertEqual((w0 >> 16) & 0x7F, 0x20) # v_fma_mix_f32 - self.assertEqual(w0 & 0xFF, 8) # vdst v8 - self.assertEqual([(w0 >> b) & 1 for b in (11, 12, 13)], [0, 0, 1]) # op_sel - self.assertEqual([(w1 >> 27) & 1, (w1 >> 28) & 1, (w0 >> 14) & 1], [1, 0, 1]) # op_sel_hi - self.assertEqual([(w1 >> (9 * i)) & 0x1FF for i in range(3)], [0xFF, 0x102, 0xFF]) - self.assertEqual(lit, 0x40004200) - - def test_hw_kernel_carries_the_exact_words(self): - a = next(c for c in probe.CASES if c.name == "A") - w0, w1, lit = a.words(8, 2, a.literal) - self.assertIn(f".long 0x{w0:08x}, 0x{w1:08x}, 0x{lit:08x}", probe.hw_lines(a)) - - def test_listing_prints_llvm_mc_text_and_the_blob_holds_the_literal(self): - a = next(c for c in probe.CASES if c.name == "A") - text, blob = probe.ps_program(a) - self.assertIn("v_fma_mix_f32 v0, 0x4200, v2, 0x4200 op_sel:[0,0,1] op_sel_hi:[1,0,1]", text) - self.assertIn(struct.pack(" above the tie -> 0x3c01; f32 drops 2^-40 (< 2^-24), the tie goes to even 0x3c00 - B exact 1 + 3 * 2^-11 - 2^-40: once -> below the tie -> 0x3c01; f32 lands on the tie, even is 0x3c02 - C A negated: 0xbc01 / 0xbc00 - D exact 2^-25 + 2^-60: once -> above half the smallest subnormal -> 0x0001; f32 keeps 2^-25 exactly, the tie - between 0 and 2^-24 goes to even 0x0000 - E exact 65520 - 2^-20: once -> below the overflow tie -> 65504 0x7bff; f32 (ulp 2^-8) gives 65520, which rounds to - inf 0x7c00 - F (1 + 2^-12)^2 = 1 + 2^-11 + 2^-24: once -> 0x3c01; f32 ties (2^-24 is half its ulp) to even 1 + 2^-11 -> 0x3c00 - G (1 + 2^-7)(1 - 2^-7) 2^-11 + (1 + 2^-10) = 1 + 3 * 2^-11 - 2^-25: once 0x3c01; f32 ties onto 1 + 3 * 2^-11 -> 0x3c02 - H 2.5 = 0x4100 either way -""" -import os -import sys -import tempfile -import unittest - -ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) -sys.dont_write_bytecode = True -sys.path.insert(0, os.path.join(ROOT, "tools")) -sys.path.insert(0, os.path.join(ROOT, "tests", "semantic")) - -import fma_mix_probe as probe # noqa: E402 -import spirv_mini_interp # noqa: E402 - -BY_HAND = { # name: (single, double) - "A": (0x3C01, 0x3C00), "B": (0x3C01, 0x3C02), "C": (0xBC01, 0xBC00), "D": (0x0001, 0x0000), - "E": (0x7BFF, 0x7C00), "F": (0x3C01, 0x3C00), "G": (0x3C01, 0x3C02), "H": (0x4100, 0x4100), -} -VSHARP = [0, 0, 0x1000, 0x31016FAC] # s[0:3]: base 0, 4 KiB, as in tests/semantic/test_lds_atomics_values.py - - -def word(case, f16): - """The destination word a correct op leaves: the f16 in its half, the sentinel in the other.""" - s = probe.SENTINEL - return (s & 0xFFFF) | f16 << 16 if case.hi else (s & 0xFFFF0000) | f16 - - -class Inputs(unittest.TestCase): - def test_model_matches_hand_derivation(self): - self.assertEqual(sorted(c.name for c in probe.CASES), sorted(BY_HAND)) - for case in probe.CASES: - with self.subTest(case=case.name): - want = probe.expected(case) - self.assertEqual((want[probe.SINGLE], want[probe.DOUBLE]), BY_HAND[case.name]) - - def test_every_case_but_the_control_discriminates(self): - for case in probe.CASES: - single, double = BY_HAND[case.name] - self.assertEqual(single == double, case.what.startswith("control"), case.name) - - def test_both_ops_and_both_operand_kinds_are_covered(self): - self.assertEqual({c.op for c in probe.CASES}, {"v_fma_mixlo_f16", "v_fma_mixhi_f16"}) - self.assertTrue(any(c.f16 for c in probe.CASES) and any(not c.f16 for c in probe.CASES)) - - def test_operand_refuses_what_the_model_does_not_cover(self): - for w, f16 in ((0x7F800000, False), (0x00000001, False), (0x7C00, True)): - with self.assertRaises(ValueError): - probe.operand(w, f16) - - -class Translator(unittest.TestCase): - def test_translator_rounds_once(self): - # docs/design.md, Known approximations: v_fma_mix* rounds once straight to f16 (measured on RDNA2 hardware). - got = probe.run_translator() - rule, _ = probe.verdict(list(zip(probe.CASES, got))) - self.assertEqual(rule, probe.SINGLE) - for case, w in zip(probe.CASES, got): - self.assertEqual(w, word(case, BY_HAND[case.name][0]), case.name) - - def test_compute_listing_gives_the_pixel_shader_words(self): - # The Vulkan side's shader (operands from user SGPRs, one store per case) on the CPU interpreter, with the - # V# and the operand words as push constants the way vk_compute_test passes s0..s31. - with tempfile.TemporaryDirectory() as work: - spv = probe.translate_cs(work) - pc = VSHARP + probe.sgpr_words() - mem = spirv_mini_interp.run_workgroup( - spv, 1, 32, inputs_for=lambda i: {"%wg_id": (0, 0, 0), "%local_id": (i, 0, 0), "%sg_lane": i}, - push_constants=pc + [0] * (32 - len(pc)), memory={}) - self.assertEqual([mem.get(4 * k) for k in range(len(probe.CASES))], probe.run_translator()) - - def test_compute_header_declares_every_operand_sgpr(self): - rsrc2 = probe.cs_rsrc2(probe.CASES) - self.assertEqual((rsrc2 >> 1) & 31, 4 + 3 * len(probe.CASES)) - self.assertLessEqual(len(probe.sgpr_words()), 28) # VKC_SGPRS takes s4..s31 - - -class Verdict(unittest.TestCase): - def results(self, rule, **override): - out = [] - for case in probe.CASES: - single, double = BY_HAND[case.name] - f16 = single if rule == probe.SINGLE else double - out.append((case, override.get(case.name, word(case, f16)))) - return out - - def test_each_rule_is_recognised(self): - for rule in (probe.SINGLE, probe.DOUBLE): - self.assertEqual(probe.verdict(self.results(rule))[0], rule) - - def test_a_mix_of_rules_is_neither(self): - a = probe.CASES[0] - self.assertIsNone(probe.verdict(self.results(probe.DOUBLE, A=word(a, BY_HAND["A"][0])))[0]) - - def test_a_third_value_is_neither(self): - self.assertIsNone(probe.verdict(self.results(probe.SINGLE, E=word(probe.CASES[4], 0x7BFE)))[0]) - - def test_a_wrong_control_is_neither(self): - self.assertIsNone(probe.verdict(self.results(probe.SINGLE, H=word(probe.CASES[7], 0x4101)))[0]) - - def test_the_other_half_must_be_kept(self): - b = probe.CASES[1] # mixhi: the low half keeps the sentinel's - self.assertIsNone(probe.verdict(self.results(probe.DOUBLE, B=BY_HAND["B"][1] << 16))[0]) - self.assertEqual(probe.half(b, word(b, 0x3C02)), 0x3C02) - - def test_a_missing_result_is_neither(self): - rule, lines = probe.verdict(self.results(probe.SINGLE, D=None)) - self.assertIsNone(rule) - self.assertIn("missing", lines[3]) - - -class HardwareKernel(unittest.TestCase): - def test_kernel_body(self): - g = next(c for c in probe.CASES if c.f16) - lines = probe.hw_lines(g) - self.assertIn(f"{g.op} v8, v1, v2, v3 op_sel_hi:[1,1,1]", lines) - self.assertEqual(lines[-2:], ["global_store_b32 v20, v8, s[2:3]", "s_endpgm"]) - - def test_gfx10_kernel_text_sets_the_float_mode(self): - from hw_oracle import asm - text = asm.raw_kernel_text("k0", probe.hw_lines(probe.CASES[0]), "gfx1030", mode=probe.HW_MODE) - self.assertIn("global_store_dword v20, v8, s[2:3]", text) # GFX10 spelling - for directive in (".amdhsa_float_denorm_mode_16_64 3", ".amdhsa_float_round_mode_16_64 0", - ".amdhsa_ieee_mode 0"): - self.assertIn(directive, text) - - -class Command(unittest.TestCase): - def test_translator_only_run_exits_0(self): - import contextlib - import io - buf = io.StringIO() - with contextlib.redirect_stdout(buf): - rc = probe.main([]) - self.assertEqual(rc, 0) - self.assertIn("translator: follows single rounding", buf.getvalue()) - - def test_unknown_side_and_missing_build_are_usage_errors(self): - import contextlib - import io - for argv in (["--oracle", "gpu"], ["--oracle", "vulkan"]): - with self.subTest(argv=argv), contextlib.redirect_stderr(io.StringIO()): - with self.assertRaises(SystemExit) as cm: - probe.main(argv) - self.assertEqual(cm.exception.code, 2) - - def test_vulkan_side_without_a_build_is_unavailable(self): - import contextlib - import io - with tempfile.TemporaryDirectory() as empty, contextlib.redirect_stdout(io.StringIO()) as buf: - rc = probe.main(["--oracle", "vulkan", "--build", empty]) - self.assertEqual(rc, 77) - self.assertIn("vk_compute_test is not built", buf.getvalue()) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/test_fmisc_diff.py b/tests/test_fmisc_diff.py deleted file mode 100644 index e5d67ab8a..000000000 --- a/tests/test_fmisc_diff.py +++ /dev/null @@ -1,450 +0,0 @@ -"""tools/fmisc_diff.py: the f32 misc-op and float-compare reference against hand-worked values, a short seeded fuzz -run, and canaries. Standard library only; no GPU.""" -import contextlib -import io -import os -from pathlib import Path -import re -import subprocess -import sys -import unittest -import unittest.mock - -TOOL = Path(__file__).resolve().parents[1] / "tools" / "fmisc_diff.py" -sys.path.insert(0, str(TOOL.parent)) -import fmisc_diff as d # noqa: E402 - -M = d.M32 -SNAN, QNAN = 0x7F800001, 0x7FC00000 - - -def prefix(v=None, s=None): - return ([f"v_mov_b32_e32 v{r}, 0x{(v or {}).get(r, 0):x}" for r in d.VREGS] - + [f"s_mov_b32 s{r}, 0x{(s or {}).get(r, 0):x}" for r in d.SREGS]) - - -def run(*body, v=None, s=None, regs=(1, 2, 3, 4)): - """The reference's four exported words; v / s map register -> seed value (others are 0).""" - return d.reference(prefix(v, s) + list(body) + d.observe(list(regs))) - - -def one(line, **kw): - return run(line, **kw)[0] - - -def cmp(line, **kw): - return run(line, "v_cndmask_b32_e64 v1, 0, 1.0, " + line.split()[1].rstrip(","), **kw)[0] == 0x3F800000 - - -class Reference(unittest.TestCase): - def test_fract(self): - self.assertEqual(one("v_fract_f32_e32 v1, v2", v={2: 0xBFC00000}), 0x3F000000) # -1.5 -> 0.5 - self.assertEqual(one("v_fract_f32_e32 v1, v2", v={2: 0xB3800000}), 0x3F7FFFFF) # -2^-24 -> below 1.0 - self.assertEqual(one("v_fract_f32_e32 v1, v2", v={2: 0x80000000}), 0) # -0 -> +0 - self.assertEqual(one("v_fract_f32_e32 v1, v2", v={2: 0x4B7FFFFF}), 0) # an integer - self.assertEqual(one("v_fract_f32_e32 v1, v2", v={2: d.NINF}), 0xFFC00000) # gfx1036: exactly this - self.assertEqual(one("v_fract_f32_e32 v1, v2", v={2: d.PINF}), 0xFFC00000) - self.assertEqual(one("v_fract_f32_e32 v1, v2", v={2: 0x7F800001}), 0x7F800001) # a signalling NaN stays - self.assertEqual(one("v_fract_f32_e32 v1, v2", v={2: 0xFFC00123}), 0xFFC00123) # a NaN comes back as is - self.assertEqual(one("v_fract_f32_e64 v1, -v2 mul:2", v={2: 0x3F000000}), 0x3F800000) # 0.5 * 2 - - def test_frexp(self): - self.assertEqual(one("v_frexp_mant_f32_e32 v1, v2", v={2: 0xC1200000}), 0xBF200000) # -10 = -0.625 * 2^4 - self.assertEqual(one("v_frexp_exp_i32_f32_e32 v1, v2", v={2: 0xC1200000}), 4) - self.assertEqual(one("v_frexp_exp_i32_f32_e32 v1, v2", v={2: 0x3E800000}), M) # 0.25 = 0.5 * 2^-1 - self.assertEqual(one("v_frexp_mant_f32_e32 v1, v2", v={2: d.NINF}), d.NINF) - self.assertEqual(one("v_frexp_exp_i32_f32_e32 v1, v2", v={2: d.PINF}), 0) - self.assertEqual(one("v_frexp_mant_f32_e32 v1, v2", v={2: 0x80000000}), 0x80000000) - - def test_ldexp(self): - self.assertEqual(one("v_ldexp_f32 v1, v2, -3", v={2: 0x41000000}), 0x3F800000) # 8 * 2^-3 - self.assertEqual(one("v_ldexp_f32 v1, -v2, v3", v={2: 0x3F800000, 3: 128}), d.NINF) - self.assertEqual(one("v_ldexp_f32 v1, v2, v3", v={2: 0x3F800000, 3: 0x80000000}), 0) - self.assertEqual(one("v_ldexp_f32 v1, v2, v3", v={2: 0xBF800000, 3: 0x80000000}), 0x80000000) - self.assertEqual(one("v_ldexp_f32 v1, v2, 64", v={2: d.NINF}), d.NINF) - with self.assertRaises(d.Uncertain): - one("v_ldexp_f32 v1, v2, -127", v={2: 0x3F800000}) # a denormal result - - def test_conversions(self): - self.assertEqual(one("v_cvt_u32_f32_e32 v1, v2", v={2: 0x4F800000}), M) # 2^32 saturates - self.assertEqual(one("v_cvt_u32_f32_e32 v1, v2", v={2: 0xBFC00000}), 0) - self.assertEqual(one("v_cvt_i32_f32_e32 v1, v2", v={2: 0xCF000001}), 0x80000000) - self.assertEqual(one("v_cvt_i32_f32_e32 v1, v2", v={2: 0xC0200000}), M - 1) # -2.5 -> -2 - self.assertEqual(one("v_cvt_i32_f32_e64 v1, -v2", v={2: QNAN}), 0) - self.assertEqual(one("v_cvt_off_f32_i4_e32 v1, v2", v={2: 0x18}), 0xBF000000) # -8 / 16 - self.assertEqual(one("v_cvt_off_f32_i4_e64 v1, 7 mul:4", v={}), 0x3FE00000) # 7/16 * 4 - - def test_fmamk_rounds_once(self): - # (1 + 2^-23) * (1 - 2^-24) - 1 is 2^-24 - 2^-47, exact in f32 (0x337ffffe); a rounded product would give - # 1 + 2^-24 -> 1.0 (ties to even) and then 0 - self.assertEqual(one("v_fmamk_f32 v1, v2, 0x3f7fffff, v3", v={2: 0x3F800001, 3: 0xBF800000}), 0x337FFFFE) - self.assertEqual(one("v_fmamk_f32 v1, v2, 0x0, v3", v={2: d.PINF, 3: 0}), QNAN) - self.assertEqual(one("v_fmamk_f32 v1, -v2, 0x3f800000, v3", v={2: 0, 3: 0x80000000}), 0x80000000) - - def test_output_modifiers(self): - self.assertEqual(one("v_ldexp_f32 v1, v2, 1 clamp", v={2: 0x3F400000}), 0x3F800000) # 1.5 -> 1.0 - self.assertEqual(one("v_frexp_mant_f32_e64 v1, v2 clamp div:2", v={2: 0xC1200000}), 0) - with self.assertRaises(d.Uncertain): - one("v_fract_f32_e64 v1, v2 mul:2", v={2: 0x40000000}) # omod on a zero - with self.assertRaises(d.Uncertain): - one("v_fract_f32_e64 v1, v2 clamp", v={2: d.PINF}) # clamp of a NaN - with self.assertRaises(d.Uncertain): # omod on an sNaN - one("v_ldexp_f32 v1, v2, v3 mul:2", v={2: SNAN, 3: 0x7FFFFFFF}) - self.assertEqual(one("v_ldexp_f32 v1, v2, v3", v={2: SNAN, 3: 0x7FFFFFFF}), SNAN) # no omod: kept - self.assertTrue(d.is_nan(one("v_ldexp_f32 v1, v2, v3 div:2", v={2: QNAN, 3: 1}))) # a quiet NaN is fine - - def test_compares(self): - v = {2: 0x3F800000, 3: QNAN, 4: 0xBF800000} - self.assertTrue(cmp("v_cmp_lt_f32_e64 s20, v4, v2", v=v)) - self.assertFalse(cmp("v_cmp_lt_f32_e64 s20, -v4, v2", v=v)) # 1 < 1 - self.assertTrue(cmp("v_cmp_le_f32_e64 s21, -v4, |v2|", v=v)) - self.assertTrue(cmp("v_cmp_eq_f32_e64 vcc_lo, |v4|, v2", v=v)) - self.assertTrue(cmp("v_cmp_eq_f32_e32 vcc_lo, 0, v5", v={5: 0x80000000})) # +0 == -0 - for c, want in (("lt", False), ("nge", True), ("u", True), ("o", False), ("lg", False), ("neq", True), - ("tru", True), ("f", False)): - self.assertEqual(cmp(f"v_cmp_{c}_f32_e64 s20, v3, v2", v=v), want, c) - - def test_class(self): - v = {2: SNAN, 3: QNAN, 4: 0xBF800000, 5: 0x80000000, 6: d.PINF} - for reg, bit in ((2, 0), (3, 1), (4, 3), (5, 5), (6, 9)): - self.assertTrue(cmp(f"v_cmp_class_f32_e64 s20, v{reg}, 0x{1 << bit:x}", v=v), reg) - self.assertFalse(cmp(f"v_cmp_class_f32_e64 s20, v{reg}, 0x{0x3FF ^ (1 << bit):x}", v=v), reg) - # measured on gfx1036: neg / abs move the sign of a signalling NaN and keep it signalling - self.assertTrue(cmp("v_cmp_class_f32_e64 vcc_lo, -|v2|, 1", v=v)) - self.assertTrue(cmp("v_cmp_class_f32_e64 vcc_lo, |v4|, 0x100", v=v)) # |-1| is +normal - - def test_what_is_not_judged(self): - with self.assertRaises(d.Uncertain): - one("v_fract_f32_e32 v1, v2", v={2: 1}) # denormal operand - with self.assertRaises(d.Uncertain): # a NaN's payload - run("v_fract_f32_e32 v1, v2", "v_cvt_off_f32_i4_e32 v3, v1", v={2: QNAN}) - # a computed NaN read as a float, or copied, is fine; any NaN matches any NaN - self.assertTrue(d.is_nan(run("v_fract_f32_e32 v1, v2", "v_fract_f32_e32 v3, v1", v={2: QNAN})[2])) - self.assertIsNone(d._diff(["", "", "", "v_mov_b32_e32 v8, v1"] * 1, [QNAN] + [0] * 3, - [0xFFC00001] + [0] * 3, "x")) - - -class Generator(unittest.TestCase): - def lines(self, known=False, literals=True, n=3000, seed=1): - real = d.KNOWN, d.LITERALS - d.KNOWN, d.LITERALS = known, literals - try: - gen = d.Gen(d.random.Random(seed)) - return [line for _ in range(n) for line in gen.op(d.ALL_OPS)] - finally: - d.KNOWN, d.LITERALS = real - - def test_every_op_is_generated_in_every_form(self): - lines = self.lines() - forms = {line.split()[0] for line in lines} - for name, (form, _, fout, _) in d.OPS.items(): - if form == "vop1": - self.assertTrue({name + "_e32", name + "_e64"} <= forms, name) - else: - self.assertIn(name, forms) - for c in d.FCMP: - self.assertTrue({f"v_cmp_{c}_f32_e32", f"v_cmp_{c}_f32_e64"} <= forms, c) - self.assertIn("v_cmp_class_f32_e64", forms) - for word in (" mul:2", " mul:4", " div:2", " clamp", "|", "-v", "-s"): - self.assertTrue(any(word in line for line in lines), word) - - def test_sources_respect_the_encoding_rules(self): - for line in self.lines(): - op, _, rest = line.partition(" ") - srcs, mods = d.parse(rest) - srcs = srcs[1:] - if op == "v_cndmask_b32_e64": - continue - bare = [re.sub(r"^-?\|?([vs]\d+)\|?$", r"\1", x) for x in srcs] - lits = [x for x in bare if x.startswith("0x")] - scalars = set(x for x in bare if x.startswith("s")) | set(lits) - self.assertLessEqual(len(lits), 1, line) - self.assertLessEqual(len(scalars), 2, line) - if op.endswith("_e32") or op == "v_fmamk_f32": - self.assertFalse(any(x != y for x, y in zip(srcs, bare)), line) # no modifiers - self.assertTrue(all(x.startswith("v") for x in bare[1:]) or op == "v_fmamk_f32", line) - if " clamp" in line and any(m in line for m in d._OMOD): - self.assertLess(line.index(" clamp"), max(line.find(m) for m in d._OMOD), line) - self.assertFalse(any("0x" in line for line in self.lines(literals=False) - if not line.startswith("v_fmamk_f32"))) - - def test_known_divergences_are_left_out_by_default(self): - def class_mods(lines): - return any(line.startswith("v_cmp_class") and re.match(r"\s*(-|\|)[vs|]", line.split(",")[1]) - for line in lines) - self.assertFalse(class_mods(self.lines())) - self.assertTrue(class_mods(self.lines(known=True))) - - -class Translated(unittest.TestCase): - def test_harness_canaries(self): - with contextlib.redirect_stdout(io.StringIO()): - self.assertTrue(d.self_test()) - - def test_short_seeded_run_matches(self): - counts, failures = d.run_suite(80, 5, 4, d.ALL_OPS) - self.assertEqual(failures, [], failures[:1]) - self.assertTrue(all(k.startswith("uncertain: ") for k in counts["skip"]), counts["skip"]) - self.assertGreaterEqual(counts["pass"], 60) - - def test_hand_cases_match_the_translator(self): - seeds = {2: 0xBFC00000, 3: 0xB3800000, 4: 0xC1200000, 5: 0x4F800000, 6: QNAN, 7: 0x3F800001, 12: 0x18, - 13: 0xBF800000} - cases = ["v_fract_f32_e32 v1, v2", "v_fract_f32_e64 v1, -v3", "v_frexp_mant_f32_e64 v1, |v4| mul:2", - "v_frexp_exp_i32_f32_e32 v1, v4", "v_ldexp_f32 v1, -v4, s4 clamp", "v_ldexp_f32 v1, v13, 0x80", - "v_cvt_u32_f32_e32 v1, v5", "v_cvt_i32_f32_e64 v1, -|v4|", "v_cvt_off_f32_i4_e64 v1, v12 mul:4", - "v_fmamk_f32 v1, v7, 0x3f7fffff, v13", "v_fmamk_f32 v1, s5, 0x7f800000, v2"] - for case in cases: - with self.subTest(case=case): - self.assertIsNone(d.check(prefix(seeds, {4: 3, 5: 0x3F000000}) + [case] + d.observe([1, 2, 3, 4]))) - for c in d.FCMP: - for case in (f"v_cmp_{c}_f32_e64 s20, -v2, |v13|", f"v_cmp_{c}_f32_e32 vcc_lo, 1.0, v6"): - with self.subTest(case=case): - m = case.split()[1].rstrip(",") - self.assertIsNone(d.check(prefix(seeds) + [case, f"v_cndmask_b32_e64 v1, 0, 1.0, {m}"] - + d.observe([1, 2, 3, 4]))) - - def test_a_wrong_translation_is_caught(self): - lines = prefix({2: 0xBFC00000}) + ["v_fract_f32_e32 v1, v2"] + d.observe([1, 2, 3, 4]) - self.assertIsNone(d.check(lines)) - want = d.reference(lines) - real = d.translated - try: - d.translated = lambda _lines: [want[0] ^ 1] + want[1:] - self.assertIn("word 0 (v1)", d.check(lines)) - d.translated = lambda _lines: [QNAN ^ 0x1234] + want[1:] # a NaN where a number is wanted - self.assertIn("word 0 (v1)", d.check(lines)) - finally: - d.translated = real - - def test_shrinking_keeps_the_instruction_that_matters(self): - lines = d.generate(d.random.Random(2), 5, ["v_frexp_mant_f32", "v_cvt_off_f32_i4", "cmp"]) - body = lines[d.N_SEED:-d.N_OBS] - target = body[len(body) // 2] - if target.startswith("v_cmp"): - target = body[len(body) // 2 + 1] - real = d.translated - try: - d.translated = lambda l: [w ^ (1 if target in l else 0) for w in d.reference(l)] - small = d.shrink(lines) - finally: - d.translated = real - kept = [line for line in small if not line.startswith(("v_mov_b32_e32", "s_mov_b32"))] - self.assertIn(target, kept) - self.assertLessEqual(len(kept), 2) # the target (and its compare, for a v_cndmask) - - -class Cli(unittest.TestCase): - def main(self, *argv): - out = io.StringIO() - with contextlib.redirect_stdout(out), contextlib.redirect_stderr(io.StringIO()): - try: - rc = d.main(list(argv)) - except SystemExit as e: - rc = e.code - return rc, out.getvalue() - - def test_exit_codes(self): - rc, out = self.main("--list-ops") - self.assertEqual(rc, 0) - self.assertIn("v_ldexp_f32", out) - self.assertEqual(self.main("--ops", "v_nope")[0], 2) - self.assertEqual(self.main("--oracle", "gpu")[0], 2) - rc, out = self.main("--programs", "5", "--seed", "1") - self.assertEqual(rc, 0, out) - real = d.translated - try: - d.translated = lambda l: [w ^ 1 for w in d.reference(l)] - rc, out = self.main("--programs", "5", "--seed", "1", "--ops", "v_cvt_u32_f32") - finally: - d.translated = real - self.assertEqual(rc, 1) - self.assertIn("MISMATCH", out) - - def test_a_run_where_every_program_was_skipped_is_not_a_success(self): - def refuse(lines, *args): - raise d.Skip("unsupported form") - real = d.translated - try: - d.translated = refuse - rc, out = self.main("--programs", "3", "--seed", "1", "--ops", "v_cvt_u32_f32") - finally: - d.translated = real - self.assertEqual(rc, 2, out) - self.assertIn("no program ran: every one was skipped", out) - - def test_hardware_oracle_without_the_tools_exits_77(self): - env = dict(os.environ, LEONIDA_AMD_CLANG=str(TOOL.parent / "no-such-clang.exe")) - r = subprocess.run([sys.executable, "-I", str(TOOL), "--oracle", "hw", "--programs", "3"], - capture_output=True, text=True, env=env) - self.assertEqual(r.returncode, 77, r.stdout + r.stderr) - self.assertIn("unavailable", r.stdout) - - -class VulkanOracle(unittest.TestCase): - """--oracle hw,vk: the compute program the GPU runs, its wave64 spelling, and the verdict against the hardware.""" - - def setUp(self): - import vk_fuzz_run - self.vk = vk_fuzz_run - - def test_program_text_wave32(self): - lines = ["v_mov_b32_e32 v1, 0x3f800000", "v_cmp_lt_f32_e64 s20, v1, v2", "v_cndmask_b32_e64 v8, 0, 1, s20"] - text = self.vk.program_text("cs_x", lines, 4, 32).splitlines() - self.assertIn("; group: 32,1,1", text) - self.assertEqual(text[3:5], ["s_mov_b32 exec_lo, -1", "v_mov_b32 v20, v0"]) - self.assertIn("v_lshlrev_b32 v21, 4, v20", text) - self.assertIn("buffer_store_dword v8, v21, s[0:3], 0 offen", text) - self.assertIn("buffer_store_dword v11, v21, s[0:3], 0 offen offset:12", text) - self.assertEqual(text[-1], "s_endpgm") - self.assertIn("v_cmp_lt_f32_e64 s20, v1, v2", text) - - def test_wave64_spells_lane_masks_as_pairs(self): - w = self.vk.wave64_text - self.assertEqual(w("v_cmp_lt_f32_e64 s20, v1, v2"), "v_cmp_lt_f32_e64 s[20:21], v1, v2") - self.assertEqual(w("v_cndmask_b32_e64 v8, 0, 1, s21"), "v_cndmask_b32_e64 v8, 0, 1, s[22:23]") - self.assertEqual(w("v_cmp_lt_f32_e32 vcc_lo, v1, v2"), "v_cmp_lt_f32_e32 vcc, v1, v2") - self.assertEqual(w("s_mov_b32 s4, 0x20"), "s_mov_b32 s4, 0x20") # data SGPRs stay - self.assertEqual(w("s_mov_b32 s2, 0x20"), "s_mov_b32 s2, 0x20") - text = self.vk.program_text("cs_x", ["v_cmp_lt_f32_e64 s21, v1, v2"], 4, 64).splitlines() - self.assertIn("; mattr: +wavefrontsize64,-wavefrontsize32", text) - self.assertIn("s_mov_b64 exec, -1", text) - self.assertIn("v_cmp_lt_f32_e64 s[22:23], v1, v2", text) - - def test_kernel_for_wave64(self): - k = d.hw_kernel(["v_cmp_lt_f32_e64 s20, v1, v2"], 64) - self.assertEqual(k.wave, 64) - self.assertIn("v_cmp_lt_f32_e64 s[20:21], v1, v2", k.lines) - - def test_verdict_classes(self): - lines = prefix() + ["v_fract_f32 v1, v2"] + d.observe([1, 2, 3, 4]) - same = [0x3F800000, 0, 0, 0] - self.assertEqual(d.vk_verdict(lines, same, list(same))[0], "match") - nan = [QNAN, 0, 0, 0] - self.assertEqual(d.vk_verdict(lines, nan, [0xFFC00001, 0, 0, 0])[0], "match") # any NaN - klass, why = d.vk_verdict(lines, same, [0x3F800001, 0, 0, 0]) - self.assertEqual(klass, "mismatch") - self.assertIn("word 0", why) - # a denormal seed makes the reference decline: a difference there is the denormal gap, not a mismatch - den = prefix(v={2: 0x00000001}) + ["v_fract_f32 v1, v2"] + d.observe([1, 2, 3, 4]) - self.assertEqual(d.vk_verdict(den, [0, 1, 0, 0], [0x3F800000, 1, 0, 0])[0], "denormal") - - def test_vk_needs_the_hardware(self): - r = subprocess.run([sys.executable, "-I", str(TOOL), "--oracle", "vk", "--programs", "1"], - capture_output=True, text=True) - self.assertEqual(r.returncode, 2, r.stdout + r.stderr) - self.assertIn("--oracle hw,vk", r.stderr) - - -class OracleGuards(unittest.TestCase): - def test_run_suite_refuses_short_oracle_results(self): - mock_oracle = unittest.mock.MagicMock() - mock_oracle.run.return_value = [[1, 2, 3, 4]] * 2 - with self.assertRaises(RuntimeError) as ctx: - d.run_suite(programs=3, seed=1, max_ops=2, ops=d.ALL_OPS, backends=("hw",), oracle=mock_oracle) - self.assertIn("the hardware runner returned 2 results for 3 programs", str(ctx.exception)) - - def test_run_suite_refuses_a_none_batch_result(self): - mock_oracle = unittest.mock.MagicMock() - mock_oracle.run.return_value = None - with self.assertRaises(RuntimeError) as ctx: - d.run_suite(programs=2, seed=1, max_ops=2, ops=d.ALL_OPS, backends=("hw",), oracle=mock_oracle) - self.assertIn("no result from the hardware runner", str(ctx.exception)) - - def test_run_suite_refuses_bad_rows_before_the_vulkan_path(self): - # With --oracle hw,vk the rows reach vk_verdict before check(): a None, empty or short row must stop first. - for row, message in ((None, "no result from the hardware runner for program 0"), - ([], "the hardware runner returned 0 words for program 0 (expected 4)"), - ([1, 2], "the hardware runner returned 2 words for program 0 (expected 4)")): - with self.subTest(row=row): - mock_oracle = unittest.mock.MagicMock() - mock_oracle.run.return_value = [row] - vk = unittest.mock.MagicMock() - vk.run_programs.return_value = [[0, 0, 0, 0]] - with unittest.mock.patch.dict(sys.modules, {"vk_fuzz_run": vk}), \ - unittest.mock.patch.object(d, "vk_verdict") as verdict: - with self.assertRaises(RuntimeError) as ctx: - d.run_suite(programs=1, seed=1, max_ops=2, ops=d.ALL_OPS, backends=("hw", "vk"), - oracle=mock_oracle) - self.assertIn(message, str(ctx.exception)) - verdict.assert_not_called() - - def test_run_suite_keeps_skip_reasons(self): - mock_oracle = unittest.mock.MagicMock() - mock_oracle.run.return_value = ["unsupported on this GPU"] - counts, failures = d.run_suite(programs=1, seed=1, max_ops=2, ops=d.ALL_OPS, backends=("hw",), - oracle=mock_oracle) - self.assertEqual(failures, []) - self.assertEqual(counts["mismatch"], 0) - - def test_main_hw_vk_exits_2_on_bad_rows(self): - # The reviewer's case: --oracle hw,vk, one program, a malformed hardware row and a good Vulkan row. - for row in (None, [], [1, 2]): - with self.subTest(row=row): - mock_oracle = unittest.mock.MagicMock() - mock_oracle.arch = "gfx1030" - mock_oracle.device = "mock device" - mock_oracle.run.return_value = [row] - vk = unittest.mock.MagicMock() - vk.run_programs.return_value = [[0, 0, 0, 0]] - out, err = io.StringIO(), io.StringIO() - with unittest.mock.patch("hw_oracle.runner.open_oracle", return_value=mock_oracle), \ - unittest.mock.patch.dict(sys.modules, {"vk_fuzz_run": vk}), \ - unittest.mock.patch.multiple(d, VK_CONSTANTS=d.VK_CONSTANTS, KNOWN=d.KNOWN): - with contextlib.redirect_stdout(out), contextlib.redirect_stderr(err): - rc = d.main(["--oracle", "hw,vk", "--programs", "1", "--seed", "1"]) - self.assertEqual(rc, 2, out.getvalue() + err.getvalue()) - self.assertIn("harness error:", out.getvalue()) - mock_oracle.close.assert_called_once() - - def test_main_exits_2_on_a_none_batch_result(self): - mock_oracle = unittest.mock.MagicMock() - mock_oracle.arch = "gfx1030" - mock_oracle.device = "mock device" - mock_oracle.run.return_value = None - out, err = io.StringIO(), io.StringIO() - with unittest.mock.patch("hw_oracle.runner.open_oracle", return_value=mock_oracle), \ - unittest.mock.patch.multiple(d, VK_CONSTANTS=d.VK_CONSTANTS, KNOWN=d.KNOWN): - with contextlib.redirect_stdout(out), contextlib.redirect_stderr(err): - rc = d.main(["--oracle", "hw", "--programs", "2", "--seed", "1"]) - self.assertEqual(rc, 2) - self.assertIn("harness error: no result from the hardware runner", out.getvalue()) - mock_oracle.close.assert_called_once() - - def test_check_refuses_none_or_short_hw_results(self): - lines = prefix() + ["v_fract_f32 v1, v2"] + d.observe([1, 2, 3, 4]) - with self.assertRaises(RuntimeError) as ctx: - d.check(lines, backends=("hw",), hw=None) - self.assertIn("no result from the hardware runner", str(ctx.exception)) - - with self.assertRaises(RuntimeError) as ctx: - d.check(lines, backends=("hw",), hw=[1, 2]) - self.assertIn("the hardware runner returned 2 words (expected 4)", str(ctx.exception)) - - def test_main_exits_2_on_oracle_count_mismatch(self): - mock_oracle = unittest.mock.MagicMock() - mock_oracle.device = "mock device" - mock_oracle.run.return_value = [[1, 2, 3, 4]] * 2 - out, err = io.StringIO(), io.StringIO() - with unittest.mock.patch("hw_oracle.runner.open_oracle", return_value=mock_oracle): - with contextlib.redirect_stdout(out), contextlib.redirect_stderr(err): - rc = d.main(["--oracle", "hw", "--programs", "3", "--seed", "1"]) - self.assertEqual(rc, 2) - self.assertIn("harness error: the hardware runner returned 2 results for 3 programs", out.getvalue()) - mock_oracle.close.assert_called_once() - - def test_main_shrink_refuses_empty_oracle_result(self): - mock_oracle = unittest.mock.MagicMock() - mock_oracle.device = "mock device" - mock_oracle.run.side_effect = [[[0x11111111, 0x22222222, 0x33333333, 0x44444444]], []] - out, err = io.StringIO(), io.StringIO() - with unittest.mock.patch("hw_oracle.runner.open_oracle", return_value=mock_oracle): - with contextlib.redirect_stdout(out), contextlib.redirect_stderr(err): - rc = d.main(["--oracle", "hw", "--programs", "1", "--seed", "1"]) - self.assertEqual(rc, 2) - self.assertIn("harness error: the hardware runner returned no result for shrunk program", out.getvalue()) - mock_oracle.close.assert_called_once() - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/test_fog_volumes.py b/tests/test_fog_volumes.py deleted file mode 100644 index 73bad9a58..000000000 --- a/tests/test_fog_volumes.py +++ /dev/null @@ -1,336 +0,0 @@ -"""Synthetic unit tests for tools/fog_volumes.py (ASSET-308). No game files.""" -import concurrent.futures -import json -import os -import struct -import sys -import tempfile -import unittest -import unittest.mock -import zlib -from unittest import mock - -TESTS_DIR = os.path.dirname(os.path.abspath(__file__)) -TOOLS_DIR = os.path.join(os.path.dirname(TESTS_DIR), "tools") -if TOOLS_DIR not in sys.path: - sys.path.insert(0, TOOLS_DIR) - -import fog_volumes as fv # noqa: E402 -import pool_workers # noqa: E402 - -SYS = 0x50000000 - - -def build_synthetic_fog_0x7a(volumes: list[dict]) -> bytes: - """Build a minimal valid 0x7a resource with CScatteringTransmittance__FogVolumeListData and FogVolume.""" - vsz = 512 - # Layout: - # 0x000..0x050: 0x7a header - # 0x050..0x090: 2 struct descriptors (32 bytes each) - # 0x090..0x0b0: 2 block descriptors (16 bytes each) - # 0x0b0..0x1a0: 15 member descriptors for FogVolume (16 bytes each = 240 bytes) - # 0x1a0..0x1b0: 1 FogVolumeListData instance (16 bytes) - # 0x1b0.. : len(volumes) * 512 FogVolume instances - st_off = 0x50 - it_off = 0x90 - mem_off = 0xB0 - list_off = 0x1A0 - vol_off = 0x1B0 - total = vol_off + len(volumes) * vsz - buf = bytearray(total) - - # Header - buf[0x10:0x14] = b"0DRP" - buf[0x14] = 0x7A - struct.pack_into(" 256 KiB): exercises uncapped 0x7a inflation and distinct record counting. - base_vols = [ - {"IsBox": 1, "PositionOffset": (float(i), -1.0, 0.5), "ProfileIndex": 12} - for i in range(260) - ] - raw = build_synthetic_fog_0x7a(base_vols + base_vols) - self.assertGreater(len(raw), 262144) - comp = zlib.compress(raw) - with tempfile.TemporaryDirectory() as td: - rpf = os.path.join(td, "large.rpf") - with open(rpf, "wb") as f: - f.write(b"9FPR" + b"\x00" * 12 + comp + b"\x00" * 64) - doc = fv.summarize(rpf, jobs=1) - self.assertEqual(doc["resources"], 1) - self.assertEqual(doc["volumes"], 520) - self.assertEqual(doc["distinct_serialized_volumes"], 260) - self.assertEqual(doc["resources_by_volume_count"], {"520": 1}) - self.assertEqual(doc["scanned_0x7a_complete"], 1) - self.assertEqual(doc["scanned_0x7a_incomplete"], 0) - - def test_corrupt_and_truncated_compressed_stream(self): - # Build a valid 0x7a FogVolume payload large enough that its compressed body has - # room for a corrupt byte past the 24-byte header probe, plus a truncated copy. - raw_valid = build_synthetic_fog_0x7a([ - {"IsBox": 1, "PositionOffset": (float(i), 2.0, -0.5), "ProfileIndex": 12} - for i in range(16) - ]) - comp_valid = zlib.compress(raw_valid) - self.assertGreater(len(comp_valid), 64) - - corrupt = bytearray(comp_valid) - corrupt[-10] ^= 0xFF - truncated = comp_valid[:-12] - - with tempfile.TemporaryDirectory() as td: - # 1. Corrupt stream followed by a valid stream: must not raise zlib.error and must still find the valid one. - rpf_corrupt = os.path.join(td, "corrupt_then_valid.rpf") - with open(rpf_corrupt, "wb") as f: - f.write(b"9FPR" + b"\x00" * 12 + bytes(corrupt) + b"\x00" * 32 + comp_valid + b"\x00" * 32) - doc = fv.summarize(rpf_corrupt, jobs=1) - self.assertEqual(doc["resources"], 1) - self.assertEqual(doc["volumes"], 16) - self.assertGreaterEqual(doc["scanned_0x7a_incomplete"], 1) - self.assertEqual(doc["scanned_0x7a_complete"], 1) - - # 2. Truncated stream at EOF (missing last 12 bytes): must return 0 resources without crashing. - rpf_trunc = os.path.join(td, "truncated.rpf") - with open(rpf_trunc, "wb") as f: - f.write(b"9FPR" + b"\x00" * 12 + truncated) - doc_t = fv.summarize(rpf_trunc, jobs=1) - self.assertEqual(doc_t["resources"], 0) - self.assertEqual(doc_t["volumes"], 0) - self.assertEqual(doc_t["scanned_0x7a_incomplete"], 1) - self.assertEqual(doc_t["scanned_0x7a_complete"], 0) - - def test_cli_validation_guards(self): - with tempfile.TemporaryDirectory() as td: - fp = os.path.join(td, "in.bin") - with open(fp, "wb") as f: - f.write(b"\x00" * 64) - # Refuses overwriting input file - with self.assertRaises(SystemExit) as cm: - fv.main([fp, "--out", fp]) - self.assertEqual(cm.exception.code, 2) - # Refuses directory as --out - with self.assertRaises(SystemExit) as cm: - fv.main([fp, "--out", td]) - self.assertEqual(cm.exception.code, 2) - # Refuses missing input - with self.assertRaises(SystemExit) as cm: - fv.main([os.path.join(td, "missing.rpf")]) - self.assertEqual(cm.exception.code, 2) - - def test_jobs_below_one_is_a_usage_error(self): - # A --jobs of 0 used to run with max(1, 0) = one worker and exit 0, so a caller that meant to ask for - # an impossible worker count got a silent sequential run instead of an error. - with tempfile.TemporaryDirectory() as td: - for bad in ("0", "-3"): - with self.assertRaises(SystemExit) as cm: - fv.main([td, "--jobs", bad]) - self.assertEqual(cm.exception.code, 2) - @unittest.skipIf(pool_workers.MAX_PROCESS_WORKERS is None, "this platform has no process-pool worker cap") - def test_jobs_above_the_pool_cap_ask_for_the_cap(self): - # ProcessPoolExecutor takes at most 61 workers on Windows (WaitForMultipleObjects' handle limit), so a - # --jobs of 1000 used to reach it unchanged and the run died with ValueError before the first chunk. - with tempfile.TemporaryDirectory() as td: - path = os.path.join(td, "big.rpf") - with open(path, "wb") as f: - f.truncate(16 * 1024 * 1024) # four chunks of the 4 MiB floor, so the pool path is taken - asked = [] - - class RecordingPool: - def __init__(self, max_workers=None, **_kwargs): - asked.append(max_workers) - - def __enter__(self): - return self - - def __exit__(self, *_exc): - return False - - def map(self, fn, items): - return [fn(item) for item in items] - - with unittest.mock.patch.object(concurrent.futures, "ProcessPoolExecutor", RecordingPool): - result = fv._scan_rpf_offsets(path, jobs=1000) - self.assertEqual(asked, [pool_workers.MAX_PROCESS_WORKERS]) - self.assertEqual(result, ([], 0, 0)) - - def test_one_chunk_input_is_scanned_without_a_pool(self): - # A file that fits in one chunk is scanned in the calling process, whatever --jobs says. - with tempfile.TemporaryDirectory() as td: - path = os.path.join(td, "small.rpf") - with open(path, "wb") as f: - f.write(b"\x00" * 1024) - - def no_pool(*_args, **_kwargs): - raise AssertionError("a one-chunk input must not start a pool") - - with unittest.mock.patch.object(concurrent.futures, "ProcessPoolExecutor", no_pool): - self.assertEqual(fv._scan_rpf_offsets(path, jobs=1000), ([], 0, 0)) - - - def test_pool_is_capped_at_the_platform_limit(self): - # A --jobs above the worker-process limit used to reach ProcessPoolExecutor unchanged; on Windows the - # constructor then raises ValueError(max_workers must be <= 61). The other pool tools lower it with - # pool_workers.process_workers. 61 is forced here so the check does not depend on the host OS. - seen = [] - - class RecordingPool: - def __init__(self, max_workers=None): - seen.append(max_workers) - - def __enter__(self): - return self - - def __exit__(self, *exc): - return False - - def map(self, fn, iterable): - return [([], 0, 0) for _ in iterable] - - with tempfile.TemporaryDirectory() as td: - rpf = os.path.join(td, "big.rpf") - with open(rpf, "wb") as f: - f.write(b"\x00" * (9 * 1024 * 1024)) # three 4 MiB chunks, so the pool branch is taken - with mock.patch.object(pool_workers, "MAX_PROCESS_WORKERS", 61), \ - mock.patch.object(fv.concurrent.futures, "ProcessPoolExecutor", RecordingPool): - offs, complete, incomplete = fv._scan_rpf_offsets(rpf, jobs=200) - self.assertEqual((offs, complete, incomplete), ([], 0, 0)) - self.assertEqual(seen, [61]) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/test_fragment_children.py b/tests/test_fragment_children.py deleted file mode 100644 index a792433cb..000000000 --- a/tests/test_fragment_children.py +++ /dev/null @@ -1,264 +0,0 @@ -"""Synthetic-data tests for tools/fragment_children.py (ASSET-261, the fragment child-drawable census). - - python -I tests/test_fragment_children.py - -Every byte here is built by the test: synthetic fragment system pages inside a synthetic RPF9-style archive -made of page-aligned zlib streams. No game file, value or name is used. -""" -import json -import os -import struct -import subprocess -import sys -import tempfile -import unittest -import zlib -from unittest import mock - -ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) -TOOL = os.path.join(ROOT, "tools", "fragment_children.py") -sys.path.insert(0, os.path.join(ROOT, "tools")) - -import fragment_children as fc # noqa: E402 - -S = 0x50000000 - - -def drawable(b, at, shader=S + 0x10, lod=True): - """A minimal drawable record at `at` that passes the tool's body test (and the decoder's header test).""" - struct.pack_into(" None: - self.translations = {"upscaler_00": ("c" * 64, "s" * 64, b"synthetic module")} - self.assertEqual(self.run_step(), ["fspx_unpack.py", "rdna2spirv.py"]) - self.assertEqual(self.run_step(), []) - module = os.path.join(self.spirv, "upscaler_00.spv") - os.remove(module) - - self.assertEqual(self.run_step(), ["fspx_unpack.py", "rdna2spirv.py"]) - with open(module, "rb") as f: - self.assertEqual(f.read(), b"synthetic module") - self.assertEqual(self.run_step(), []) - - def test_no_dll_no_step(self): - os.remove(self.dll) - self.assertEqual(self.run_step(), []) - self.assertFalse(os.path.exists(self.spirv)) - - def test_each_input_change_runs_it_again(self): - self.run_step() - self.assertEqual(self.run_step(signature="llvm-mc 24"), ["fspx_unpack.py", "rdna2spirv.py"]) - self.assertEqual(self.run_step(signature="llvm-mc 24", emulate=True), ["fspx_unpack.py", "rdna2spirv.py"]) - self.assertIn("--wave64-emulate", self.calls[1][1]) - flags = ("--no-float-controls",) - self.assertEqual(self.run_step(signature="llvm-mc 24", emulate=True, fallbacks=flags), - ["fspx_unpack.py", "rdna2spirv.py"]) - self.assertIn("--no-float-controls", self.calls[1][1]) - self.write_dll(program() + b"\0\0\x80\xbf") - self.assertEqual(self.run_step(signature="llvm-mc 24", emulate=True, fallbacks=flags), - ["fspx_unpack.py", "rdna2spirv.py"]) - self.assertEqual(self.run_step(signature="llvm-mc 24", emulate=True, fallbacks=flags), []) - with mock.patch.object(make_game, "translation_sources_digest", return_value="another translator"): - self.assertEqual(self.run_step(signature="llvm-mc 24", emulate=True, fallbacks=flags), - ["fspx_unpack.py", "rdna2spirv.py"]) - - def test_same_keys_with_different_modules_fail_the_step(self): - """Same kind 6 and same kind 0 must translate to one module; otherwise the runtime could not choose.""" - self.translations = {"upscaler_00": ("c" * 64, "s" * 64, b"module A"), - "upscaler_01": ("c" * 64, "s" * 64, b"module B")} - with self.assertRaises(SystemExit), mock.patch("sys.stderr", new_callable=io.StringIO) as err: - self.run_step() - self.assertIn("upscaler_00", err.getvalue()) - self.assertIn("upscaler_01", err.getvalue()) - self.assertFalse(os.path.exists(os.path.join(self.spirv, "index.json"))) # nothing for the runtime to load - self.assertFalse(os.path.exists(os.path.join(self.spirv, "fspx_build.json"))) - - def test_same_code_key_is_allowed_with_other_state_or_the_same_module(self): - self.translations = {"upscaler_00": ("c" * 64, "s" * 64, b"module A"), - "upscaler_01": ("c" * 64, "t" * 64, b"module B"), # Vonsek's case: other kind 0 - "upscaler_02": ("c" * 64, "s" * 64, b"module A")} # a duplicate of 00 - self.assertEqual(self.run_step(), ["fspx_unpack.py", "rdna2spirv.py"]) - self.assertTrue(os.path.isfile(os.path.join(self.spirv, "fspx_build.json"))) - - def test_malformed_or_missing_output_index_fails_cleanly(self): - for raw in (False, "{broken", "[]"): - with self.subTest(raw=raw): - def bad_py(tool, *args): - self.calls.append((tool, args)) - if tool == "fspx_unpack.py": - os.makedirs(os.path.join(self.unpacked, "disasm"), exist_ok=True) - open(os.path.join(self.unpacked, "disasm", "upscaler.s"), "w").close() - elif tool == "rdna2spirv.py": - os.makedirs(self.spirv, exist_ok=True) - if raw is not False: - with open(os.path.join(self.spirv, "index.json"), "w", encoding="utf-8", - newline="\n") as f: - f.write(raw) - - with self.assertRaises(SystemExit), mock.patch("sys.stderr", new_callable=io.StringIO) as err: - self.calls = [] - with mock.patch.object(make_game, "py", bad_py), mock.patch.object(make_game, "log", lambda *a: None): - make_game.fspx_shaders(self.game, self.work, "llvm-mc 23") - self.assertIn("unreadable index", err.getvalue()) - self.assertFalse(os.path.exists(os.path.join(self.spirv, "index.json"))) - self.assertFalse(os.path.exists(os.path.join(self.spirv, "fspx_build.json"))) - - def test_a_stopped_translation_leaves_no_marker_and_no_old_modules(self): - self.run_step() - open(os.path.join(self.spirv, "notes.txt"), "w").close() - - def stop(tool, *args): - if tool == "rdna2spirv.py": - raise KeyboardInterrupt - self.fake_py(tool, *args) - with mock.patch.object(make_game, "py", stop), mock.patch.object(make_game, "log", lambda *a: None): - with self.assertRaises(KeyboardInterrupt): - make_game.fspx_shaders(self.game, self.work, "llvm-mc 24") - self.assertFalse(os.path.exists(os.path.join(self.spirv, "index.json"))) - self.assertFalse(os.path.exists(os.path.join(self.spirv, "fspx_build.json"))) - self.assertFalse(os.path.exists(os.path.join(self.spirv, "upscaler.spv"))) # from the run before - self.assertTrue(os.path.isfile(os.path.join(self.spirv, "notes.txt"))) - self.assertEqual(self.run_step(signature="llvm-mc 24"), ["fspx_unpack.py", "rdna2spirv.py"]) - self.assertEqual(self.run_step(signature="llvm-mc 24"), []) - - -class ShadersStageWithTheDll(unittest.TestCase): - """The whole shaders() stage with the DLL in the game folder: the FSPX step comes after the game's shaders and - never makes them run again.""" - - def test_fspx_runs_after_the_corpus_and_alone_when_only_its_inputs_change(self): - with tempfile.TemporaryDirectory() as t: - work, game = os.path.join(t, "work"), os.path.join(t, "game") - os.makedirs(game) - dll = os.path.join(game, make_game.FSPX_DLL) - with open(dll, "wb") as f: - f.write(dll_like(container(program()))) - ran = [] - dxbc = os.path.join(work, "shaders", "dxbc") - - def touch(*parts): - os.makedirs(os.path.dirname(os.path.join(*parts)), exist_ok=True) - open(os.path.join(*parts), "w").close() - - def fake_py(tool, *args): - ran.append(tool) - if tool == "shader_carve.py": - touch(dxbc, "index.json") - with open(os.path.join(dxbc, "index.json"), "w") as f: - f.write('[{"file": "shader.dxbc"}]') - elif tool == "fssm_unpack.py": - touch(dxbc, "fssm_index.json") - with open(os.path.join(dxbc, "fssm_index.json"), "w") as f: - f.write('[{"name": "shader"}]') - elif tool == "shader_disasm.py": - os.makedirs(os.path.join(dxbc, "disasm"), exist_ok=True) - # make_game checks that every unpacked shader got a non-empty listing - with open(os.path.join(dxbc, "disasm", "shader.s"), "w") as f: - f.write("s_endpgm\n") - elif tool == "rdna2spirv.py": - out = args[args.index("--out") + 1] - touch(out, "index.json") - # Publish a runtime-addressable module for the cache reuse check. - with open(os.path.join(out, "index.json"), "w", encoding="utf-8", newline="\n") as f: - json.dump({"upscaler_00": {"stage": "cs", "fspx_code_sha256": "e" * 64}}, f) - with open(os.path.join(out, "upscaler_00.spv"), "wb") as f: - f.write(b"synthetic module") - - def fake_translate(disasm, spirv, jobs, emulate=False, fallbacks=()): - ran.append("translate") - touch(spirv, "index.json") - - def stage(): - ran.clear() - with mock.patch.object(make_game, "py", fake_py), \ - mock.patch.object(make_game, "need", lambda *a: None), \ - mock.patch.object(make_game, "translate", fake_translate), \ - mock.patch.object(make_game, "llvm_mc_signature", return_value="llvm-mc 23"), \ - mock.patch.object(make_game, "log", lambda *a: None): - make_game.shaders(game, work, 2) - return list(ran) - - self.assertEqual(stage(), ["shader_carve.py", "fssm_unpack.py", "shader_disasm.py", "translate", - "fspx_unpack.py", "rdna2spirv.py"]) - self.assertEqual(stage(), []) - with open(dll, "wb") as f: - f.write(dll_like(container(program() + b"\0\0\x80\xbf"))) - self.assertEqual(stage(), ["fspx_unpack.py", "rdna2spirv.py"]) - self.assertTrue(os.path.isfile(os.path.join(work, "shaders", "spirv", "index.json"))) - self.assertTrue(os.path.isfile(os.path.join(work, "shaders", "spirv", "fspx", "index.json"))) - - -class FspxCacheComplete(unittest.TestCase): - """Pin fspx_cache_complete(), the predicate that decides whether the FSPX outputs can be reused.""" - - def setUp(self): - self.tmp = tempfile.TemporaryDirectory() - self.addCleanup(self.tmp.cleanup) - self.spirv = os.path.join(self.tmp.name, "shaders", "spirv", "fspx") - os.makedirs(self.spirv) - - def write_index(self, text): - with open(os.path.join(self.spirv, "index.json"), "w", encoding="utf-8", newline="\n") as f: - f.write(text) - - def test_empty_index_is_not_complete(self): - self.write_index("{}") - self.assertFalse(make_game.fspx_cache_complete(self.spirv)) - - def test_missing_index_is_not_complete(self): - self.assertFalse(make_game.fspx_cache_complete(self.spirv)) - - def test_malformed_index_is_not_complete(self): - self.write_index("{not json") - self.assertFalse(make_game.fspx_cache_complete(self.spirv)) - - def test_non_mapping_indexes_are_not_complete(self): - for text in ("[]", "null"): - with self.subTest(text=text): - self.write_index(text) - self.assertFalse(make_game.fspx_cache_complete(self.spirv)) - - def test_one_entry_with_its_module_is_complete(self): - self.write_index(json.dumps({"upscaler_00": {"stage": "cs", "fspx_code_sha256": "e" * 64}})) - with open(os.path.join(self.spirv, "upscaler_00.spv"), "wb") as f: - f.write(b"synthetic module") - self.assertTrue(make_game.fspx_cache_complete(self.spirv)) - - def test_one_entry_without_its_module_is_not_complete(self): - self.write_index(json.dumps({"upscaler_00": {"stage": "cs", "fspx_code_sha256": "e" * 64}})) - self.assertFalse(make_game.fspx_cache_complete(self.spirv)) - - def test_existing_module_without_runtime_lookup_metadata_is_not_complete(self): - with open(os.path.join(self.spirv, "upscaler_00.spv"), "wb") as f: - f.write(b"synthetic module") - for metadata in ({"error": "synthetic metadata failure"}, - {"stage": "cs", "fspx_code_sha256": "abbreviated"}, - {"stage": "ps", "fspx_code_sha256": "e" * 64}): - with self.subTest(metadata=metadata): - self.write_index(json.dumps({"upscaler_00": metadata})) - self.assertFalse(make_game.fspx_cache_complete(self.spirv)) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/test_fspx_unpack.py b/tests/test_fspx_unpack.py deleted file mode 100644 index 946da380c..000000000 --- a/tests/test_fspx_unpack.py +++ /dev/null @@ -1,486 +0,0 @@ -"""Unit tests for tools/fspx_unpack.py (the FSPX payloads of the FidelityFX DLL's shader containers) and for the -translator's FSPX sidecar reads (rdna2spirv.native_blob / cs_dispatch_state). - - python -I tests/test_fspx_unpack.py - -Zero game data: every payload and container is built here from synthetic bytes. -""" -import contextlib -import io -import json -import os -import struct -import subprocess -import sys -import tempfile -import unittest - -ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) -TOOL = os.path.join(ROOT, "tools", "fspx_unpack.py") -sys.path.insert(0, os.path.join(ROOT, "tools")) - -import fspx_unpack # noqa: E402 - -ENDPGM = struct.pack(" bytes: - """A minimal FSSM record with the measured 0x28-byte prologue and one s_endpgm.""" - blob = bytearray(CODE_END) - blob[0:4] = b"FSSM" - struct.pack_into(" bytes: - compressed = zlib.compress(payload) - return (b"XBCH" + struct.pack("<5I", 3, len(compressed), 0, len(payload), 0) - + compressed) - - -def dxbc_with(entries, hdr: int = 0x24) -> bytes: - """A DXBC-shaped container with the given XDAT entries. - - The 195 duplicate containers use four entries and keep the header word at 0x24; the fourth - entry therefore sits beyond the declared header size, as it does in the corpus. - """ - n = len(entries) - xdat = 0x18 - table = xdat + 12 - data = table + 12 * n - payloads = [(tag, p if tag != 0x0D else xbch(p)) for tag, p in entries] - dxil = bytearray(data + sum(len(p) for _, p in payloads)) - struct.pack_into(" bytes: - return dxbc_with([(0x12, b"hash"), (0x0D, first), (0x0D, second), (0x07, b"stub")]) - - def dxil(self, first: bytes, second: bytes) -> bytes: - return fssm_unpack.parts(self.container(first, second))[b"DXIL"] - - def test_xdat_entries_all_preserves_both_payloads_in_order(self): - first, second = fssm(0x11), fssm(0x22) - self.assertNotEqual(first, second) - entries = fssm_unpack.xdat_entries_all(self.dxil(first, second)) - self.assertEqual([tag for tag, _ in entries], [0x12, 0x0D, 0x0D, 0x07]) - # Entries hold the compressed XBCH payload: both must decompress to their own FSSM blob. - blobs = [zlib.decompress(payload[24:]) for tag, payload in entries if tag == 0x0D] - self.assertEqual(blobs, [first, second]) - - def test_xdat_entries_keeps_the_last_payload_per_tag(self): - first, second = fssm(0x11), fssm(0x22) - entries = fssm_unpack.xdat_entries(self.dxil(first, second)) - self.assertEqual(sorted(entries), [0x07, 0x0D, 0x12]) - # The single-value view is kept for old callers: last entry wins, as before the fix. - self.assertEqual(zlib.decompress(entries[0x0D][24:]), second) - - def test_unpack_selects_first_or_last_payload(self): - first, second = fssm(0x11), fssm(0x22) - container = self.container(first, second) - self.assertEqual(fssm_unpack.unpack(container)[0], second) # default: last - self.assertEqual(fssm_unpack.unpack(container, payload="last")[0], second) - self.assertEqual(fssm_unpack.unpack(container, payload="first")[0], first) - - def test_unpack_rejects_an_unknown_payload_choice(self): - with self.assertRaises(ValueError): - fssm_unpack.unpack(self.container(fssm(0x11), fssm(0x22)), payload="middle") - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/test_fssm_header.py b/tests/test_fssm_header.py deleted file mode 100644 index 4ee910894..000000000 --- a/tests/test_fssm_header.py +++ /dev/null @@ -1,425 +0,0 @@ -"""The FSSM pixel-input decoder reads documented record fields, the directory identity and the fp16 mask. - -All blobs here are built by hand; no shader from the game is used. - - python -I tests/test_fssm_header.py -""" -import json -import os -import struct -import subprocess -import sys -import tempfile -import unittest -from unittest import mock - -ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) -TOOLS = os.path.join(ROOT, "tools") -TOOL = os.path.join(TOOLS, "fssm_header.py") -sys.path.insert(0, TOOLS) - -import fssm_header # noqa: E402 - - -def blob(records=(), directory=(0x100, 0x20, 0x120), size=0x200, first=None, wave_flags=0): - """Build a synthetic FSSM header. records are complete 8-byte input records.""" - data = bytearray(size) - data[0:4] = b"FSSM" - if size >= 0xD8: - struct.pack_into(".fssm blob via fssm_header.wave_size(), cross-checks against code markers, -and falls back to the code-marker heuristic when no FSSM sidecar is present. - -All blobs, DXBC containers and disassembly listings here are built by hand; nothing needs -llvm-mc, spirv-as/val or a GPU. - - python -I tests/test_fssm_wave_size.py -""" -import gc -import os -import struct -import sys -import tempfile -import unittest -import warnings - -ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) -sys.path.insert(0, os.path.join(ROOT, "tools")) - -import fssm_header # noqa: E402 -import rdna2spirv # noqa: E402 - - -def make_dxbc(chunks=()): - head = 32 + 4 * len(chunks) - offsets, body = [], b"" - for fourcc, payload in chunks: - offsets.append(head + len(body)) - body += fourcc + struct.pack(".s + .dxbc + optional fssm/.fssm and translate.""" - prev_emulate = rdna2spirv.WAVE64_EMULATE - rdna2spirv.WAVE64_EMULATE = emulate - try: - with tempfile.TemporaryDirectory() as tmp: - disasm = os.path.join(tmp, "disasm") - os.mkdir(disasm) - s_path = os.path.join(disasm, name + ".s") - with open(s_path, "w", encoding="utf-8") as f: - f.write(f"; {name} code 0x100..0x200 (synthetic)\n") - for ln in lines: - f.write("\t" + ln + "\n") - with open(os.path.join(tmp, name + ".dxbc"), "wb") as f: - f.write(make_dxbc() if dxbc is None else dxbc) - if fssm is not None: - fdir = os.path.join(tmp, "fssm") - os.mkdir(fdir) - with open(os.path.join(fdir, name + ".fssm"), "wb") as f: - f.write(fssm) - with warnings.catch_warnings(): - warnings.simplefilter("ignore", ResourceWarning) - spv = rdna2spirv.translate(s_path) - gen = rdna2spirv.translate.last_gen - meta = rdna2spirv.shader_meta(gen, spv) - gc.collect() - return spv, gen, meta - finally: - rdna2spirv.WAVE64_EMULATE = prev_emulate - - -CS_HEADER_64 = (0x8088, (64, 1, 1)) -CS_HEADER_32 = (0x8088, (32, 1, 1)) - -STRAIGHT_CS = [ - "v_mov_b32_e32 v1, 1 ; encoding: [0x81,0x02,0x02,0x7e]", - "s_endpgm ; encoding: [0x00,0x00,0x81,0xbf]", -] - -READLANE_CS = [ - "v_mov_b32_e32 v1, 40 ; encoding: [0xa8,0x02,0x02,0x7e]", - "v_readlane_b32 s4, v1, 40 ; encoding: [0x04,0x00,0x60,0xd7,0x01,0x51,0x01,0x00]", - "s_endpgm ; encoding: [0x00,0x00,0x81,0xbf]", -] - -STRAIGHT_PS = [ - "v_mov_b32_e32 v2, 1.0 ; encoding: [0xf2,0x02,0x04,0x7e]", - "exp mrt0 v2, v2, v2, v2 done vm ; encoding: [0x0f,0x18,0x00,0xf8,0x02,0x02,0x02,0x02]", - "s_endpgm ; encoding: [0x00,0x00,0x81,0xbf]", -] - -STRAIGHT_VS = [ - "v_mov_b32_e32 v1, 1.0 ; encoding: [0xf2,0x02,0x02,0x7e]", - "exp pos0 v1, v1, v1, v1 done ; encoding: [0xcf,0x08,0x00,0xf8,0x01,0x01,0x01,0x01]", - "s_endpgm ; encoding: [0x00,0x00,0x81,0xbf]", -] - -STRAIGHT_GS = [ - "s_mov_b32 m0, 0 ; encoding: [0x80,0x03,0xfc,0xbe]", - "s_sendmsg sendmsg(MSG_GS, GS_OP_EMIT, 0) ; encoding: [0x22,0x00,0x90,0xbf]", - "s_sendmsg sendmsg(MSG_GS_DONE, GS_OP_NOP) ; encoding: [0x03,0x00,0x90,0xbf]", - "s_endpgm ; encoding: [0x00,0x00,0x81,0xbf]", -] - -GS_DXBC = make_dxbc([ - sig1_chunk(b"ISG1", [("SV_Position", 0, 0, 0xF, 0xF, 1, 3)]), - sig1_chunk(b"OSG1", [("SV_Position", 0, 0, 0xF, 0xF, 1, 3)]), -]) - - -class FssmWaveSizeTest(unittest.TestCase): - def test_straight_line_cs_wave64_from_fssm(self): - _, gen, meta = translate_case("cs_w64", STRAIGHT_CS, fssm=make_fssm(64, CS_HEADER_64)) - self.assertTrue(gen.wave64) - self.assertTrue(meta["wave64"]) - self.assertEqual(meta["subgroup_size"], 64) - - def test_straight_line_cs_readlane_uses_64_lane_mask(self): - # 11 markerless wave64 CS in the corpus use v_readlane_b32; wave64 must mask with 63 (%c3f), not 31 (%c1f). - spv64, gen64, meta64 = translate_case("cs_rl64", READLANE_CS, fssm=make_fssm(64, CS_HEADER_64)) - self.assertTrue(gen64.wave64) - self.assertEqual(meta64["subgroup_size"], 64) - self.assertIn("%c3f = OpConstant %uint 63", spv64) - self.assertIn("OpBitwiseAnd %uint %c28 %c3f", spv64) - - spv32, gen32, meta32 = translate_case("cs_rl32", READLANE_CS, fssm=make_fssm(32, CS_HEADER_32)) - self.assertFalse(gen32.wave64) - self.assertEqual(meta32["subgroup_size"], 32) - self.assertIn("%c1f = OpConstant %uint 31", spv32) - self.assertIn("OpBitwiseAnd %uint %c28 %c1f", spv32) - self.assertNotIn("%c3f = OpConstant %uint 63", spv32) - - def test_straight_line_ps_vs_gs_wave64_from_fssm(self): - for name, lines, dxbc in ( - ("ps_w64", STRAIGHT_PS, None), - ("vs_w64", STRAIGHT_VS, None), - ("gs_w64", STRAIGHT_GS, GS_DXBC), - ): - with self.subTest(stage=name[:2]): - _, gen, meta = translate_case(name, lines, fssm=make_fssm(64), dxbc=dxbc) - self.assertTrue(gen.wave64) - self.assertTrue(meta["wave64"]) - self.assertEqual(meta["subgroup_size"], 64) - self.assertTrue(meta["wave64_emulated"]) - self.assertEqual(meta["wave64_graphics"], "A") - - def test_wave32_from_fssm_for_cs_and_ps(self): - _, gen_cs, meta_cs = translate_case("cs_w32", STRAIGHT_CS, fssm=make_fssm(32, CS_HEADER_32)) - self.assertFalse(gen_cs.wave64) - self.assertFalse(meta_cs["wave64"]) - self.assertEqual(meta_cs["subgroup_size"], 32) - - _, gen_ps, meta_ps = translate_case("ps_w32", STRAIGHT_PS, fssm=make_fssm(32)) - self.assertFalse(gen_ps.wave64) - self.assertFalse(meta_ps["wave64"]) - self.assertEqual(meta_ps["subgroup_size"], 32) - self.assertNotIn("wave64_graphics", meta_ps) - - def test_missing_or_non_fssm_sidecar_falls_back_to_wave64_re(self): - # PS with no sidecar: straight-line falls back to wave32; WAVE64_RE falls back to wave64. - _, gen_ps32, meta_ps32 = translate_case("ps_nosidecar", STRAIGHT_PS, fssm=None) - self.assertFalse(gen_ps32.wave64) - self.assertEqual(meta_ps32["subgroup_size"], 32) - - w64_ps = ["s_mov_b64 exec, -1 ; encoding: [0xc1,0x04,0xfe,0xbe]"] + STRAIGHT_PS - _, gen_ps64, meta_ps64 = translate_case("ps_nosidecar64", w64_ps, fssm=None) - self.assertTrue(gen_ps64.wave64) - self.assertEqual(meta_ps64["subgroup_size"], 64) - - # CS with zero-prefixed synthetic header (no FSSM magic, as tests/conftest.py writes): - # wave_size() returns None, so translation falls back to WAVE64_RE. - zero_cs = make_fssm(64, CS_HEADER_64, magic=b"\x00\x00\x00\x00") - _, gen_cs32, _ = translate_case("cs_zero_hdr", STRAIGHT_CS, fssm=zero_cs) - self.assertFalse(gen_cs32.wave64) - - w64_cs = ["s_mov_b64 exec, -1 ; encoding: [0xc1,0x04,0xfe,0xbe]"] + STRAIGHT_CS - _, gen_cs64, _ = translate_case("cs_zero_hdr64", w64_cs, fssm=zero_cs) - self.assertTrue(gen_cs64.wave64) - - def test_contradicting_fssm_and_code_is_refused(self): - w64_code = ["s_and_saveexec_b64 s[0:1], vcc ; encoding: [0x6a,0x24,0x80,0xbe]"] + STRAIGHT_PS - with self.assertRaisesRegex(rdna2spirv.Unsupported, "FSSM wave32 header contradicts wave64 code"): - translate_case("ps_bad32", w64_code, fssm=make_fssm(32)) - - w32_code = ["s_and_saveexec_b32 s0, vcc_lo ; encoding: [0x6a,0x3c,0x80,0xbe]"] + STRAIGHT_PS - with self.assertRaisesRegex(rdna2spirv.Unsupported, "FSSM wave64 header contradicts wave32 code"): - translate_case("ps_bad64", w32_code, fssm=make_fssm(64)) - - def test_wave64_emulate_runs_on_straight_line_wave64_cs_from_fssm(self): - spv, gen, meta = translate_case("cs_emul64", READLANE_CS, - fssm=make_fssm(64, CS_HEADER_64), emulate=True) - self.assertTrue(gen.wave64) - self.assertTrue(gen.emulate) - self.assertTrue(meta["wave64"]) - self.assertTrue(meta["wave64_emulated"]) - self.assertEqual(meta["wave64_exchange"], "workgroup") - self.assertIsNone(meta["subgroup_size"]) - self.assertEqual(meta["control_flow"], "emulated wave64 rounds") - self.assertIn("%x_buf", spv) - self.assertNotIn("OpGroupNonUniform", spv) - - # Wave32 CS with --wave64-emulate must stay native wave32. - spv32, gen32, meta32 = translate_case("cs_emul32", READLANE_CS, - fssm=make_fssm(32, CS_HEADER_32), emulate=True) - self.assertFalse(gen32.wave64) - self.assertFalse(gen32.emulate) - self.assertEqual(meta32["subgroup_size"], 32) - self.assertNotIn("%x_buf", spv32) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/test_fuzz_find_harness.py b/tests/test_fuzz_find_harness.py deleted file mode 100644 index 84d8dfa3c..000000000 --- a/tests/test_fuzz_find_harness.py +++ /dev/null @@ -1,46 +0,0 @@ -"""The fuzzers find vk_compute_test in a Visual Studio build, and say so in one line when it isn't built.""" -import os -from pathlib import Path -import sys -import tempfile -import unittest - -ROOT = Path(__file__).resolve().parents[1] -sys.path.insert(0, str(ROOT / "runtime" / "test" / "shaders")) -from compute_fixture import find_test_program # noqa: E402 - -EXE = "vk_compute_test" + (".exe" if os.name == "nt" else "") - - -class FindTestProgram(unittest.TestCase): - def test_single_config_build(self): - with tempfile.TemporaryDirectory() as build: - (Path(build) / EXE).touch() - self.assertEqual(find_test_program(build, "vk_compute_test"), build) - - def test_visual_studio_config_folders(self): - for config in ("RelWithDebInfo", "Release"): - with self.subTest(config=config), tempfile.TemporaryDirectory() as build: - (Path(build) / config).mkdir() - (Path(build) / config / EXE).touch() - self.assertEqual(find_test_program(build, "vk_compute_test"), os.path.join(build, config)) - - def test_not_built(self): - with tempfile.TemporaryDirectory() as build: - self.assertIsNone(find_test_program(build, "vk_compute_test")) - - -class FuzzerWithoutHarness(unittest.TestCase): - def test_one_line_instead_of_a_traceback(self): - sys.path.insert(0, str(ROOT / "tools")) - import lds_fuzz - import valu_fuzz - for module in (valu_fuzz, lds_fuzz): - with self.subTest(tool=module.__name__), tempfile.TemporaryDirectory() as build: - with self.assertRaises(SystemExit) as stop: - module.run_gpu(None, "unused.spv", build, {}, False, "unused.bin") - self.assertIn("vk_compute_test not found", str(stop.exception.code)) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/test_fuzzer_work_isolation.py b/tests/test_fuzzer_work_isolation.py deleted file mode 100644 index b1c86ac5b..000000000 --- a/tests/test_fuzzer_work_isolation.py +++ /dev/null @@ -1,164 +0,0 @@ -"""The translator fuzzers must not remove or overwrite files in a caller's --work folder.""" -import contextlib -import io -import json -import subprocess -import sys -import tempfile -import unittest -from pathlib import Path -from unittest.mock import patch - -sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "tools")) -import lds_fuzz -import valu_fuzz - - -class FuzzerWorkIsolation(unittest.TestCase): - def test_existing_files_and_other_runs_survive(self): - cases = ( - (lds_fuzz, [], lds_fuzz.programs(1, 1, (32,))[0]), - (valu_fuzz, ["--family", "f16"], valu_fuzz.programs("f16", 1, 1, (32,))[0]), - ) - for module, extra, program in cases: - with self.subTest(fuzzer=module.__name__), tempfile.TemporaryDirectory() as tmp: - root = Path(tmp) - sentinels = {} - for subdir in ("disasm", "fssm", "spirv"): - path = root / subdir / "keep.txt" - path.parent.mkdir() - path.write_bytes(b"caller data") - sentinels[path] = b"caller data" - for suffix in (".asm", ".bin"): - path = root / (program.name + suffix) - path.write_bytes(b"caller artifact") - sentinels[path] = b"caller artifact" - - def assemble(cmd, **kwargs): - return subprocess.CompletedProcess(cmd, 0, "s_endpgm\n", "") - - def translate(cmd, **kwargs): - listing_dir = Path(cmd[3]) - out = Path(cmd[cmd.index("--out") + 1]) - out.mkdir(parents=True, exist_ok=True) - index = {} - for listing in listing_dir.glob("*.s"): - index[listing.stem] = {} - (out / (listing.stem + ".spv")).write_bytes(b"synthetic") - (out / "index.json").write_text(json.dumps(index), encoding="utf-8", newline="\n") - return subprocess.CompletedProcess(cmd, 0, "", "") - - outputs = [] - for _ in range(2): - output = io.StringIO() - argv = [module.__name__ + ".py", "--programs", "1", "--wave", "32", "--work", str(root), *extra] - with (patch.object(sys, "argv", argv), - patch.object(module.mc_command, "run", side_effect=assemble), - patch.object(module.subprocess, "run", side_effect=translate), - patch.object(module, "run_gpu", return_value=(77, "synthetic skip")), - contextlib.redirect_stdout(output)): - self.assertEqual(module.main(), 2) # no GPU programs ran - outputs.append(output.getvalue()) - for path, content in sentinels.items(): - self.assertTrue(path.exists(), f"{module.__name__} removed {path}") - self.assertEqual(path.read_bytes(), content, f"{module.__name__} overwrote {path}") - - runs = sorted(p for p in root.iterdir() if p.is_dir() and p.name not in {"disasm", "fssm", "spirv"}) - self.assertEqual(len(runs), 2, "each invocation needs its own retained output folder") - for run in runs: - self.assertTrue((run / (program.name + ".asm")).is_file()) - self.assertTrue((run / "spirv" / "index.json").is_file()) - self.assertNotEqual(runs[0], runs[1]) - # The fuzzer resolves --work before it makes the run folder, so the printed path is the canonical - # one: on Windows tempfile hands out the 8.3 name (RUNNER~1) and resolve() expands it. - self.assertTrue(any(str(runs[0].resolve()) in out for out in outputs)) - self.assertTrue(any(str(runs[1].resolve()) in out for out in outputs)) - - def test_failed_translation_reports_retained_output_and_creates_parent(self): - for module, extra in ((lds_fuzz, []), (valu_fuzz, ["--family", "f16"])): - with self.subTest(fuzzer=module.__name__), tempfile.TemporaryDirectory() as tmp: - parent = Path(tmp) / "new" / "work" - output = io.StringIO() - argv = [module.__name__ + ".py", "--programs", "1", "--wave", "32", "--work", str(parent), *extra] - with (patch.object(sys, "argv", argv), - patch.object(module, "translate", side_effect=RuntimeError("synthetic failure")), - contextlib.redirect_stdout(output)): - self.assertEqual(module.main(), 2) - runs = list(parent.iterdir()) - self.assertEqual(len(runs), 1) - self.assertTrue(runs[0].is_dir()) - self.assertIn(str(runs[0].resolve()), output.getvalue()) - self.assertIn("synthetic failure", output.getvalue()) - - def test_existing_file_as_work_reports_one_error(self): - for module, extra in ((lds_fuzz, []), (valu_fuzz, ["--family", "f16"])): - with self.subTest(fuzzer=module.__name__), tempfile.TemporaryDirectory() as tmp: - parent = Path(tmp) / "not-a-directory" - parent.write_bytes(b"caller data") - script = Path(__file__).resolve().parents[1] / "tools" / (module.__name__ + ".py") - cmd = [sys.executable, "-I", str(script), "--programs", "1", "--wave", "32", "--work", str(parent), *extra] - result = subprocess.run(cmd, stdin=subprocess.DEVNULL, capture_output=True, text=True, timeout=20) - self.assertEqual(result.returncode, 2, result.stderr) - self.assertIn("ERROR: cannot create work directory", result.stderr) - self.assertEqual(len(result.stderr.splitlines()), 1, result.stderr) - self.assertNotIn("Traceback", result.stderr) - self.assertEqual(parent.read_bytes(), b"caller data") - - def test_work_error_closes_an_open_hardware_oracle(self): - from hw_oracle import runner - - class Oracle: - device = "synthetic device" - arch = "gfx1030" - closed = False - - def close(self): - self.closed = True - - for module, extra in ((lds_fuzz, []), (valu_fuzz, ["--family", "f16"])): - with self.subTest(fuzzer=module.__name__), tempfile.TemporaryDirectory() as tmp: - parent = Path(tmp) / "not-a-directory" - parent.write_bytes(b"caller data") - oracle = Oracle() - argv = [module.__name__ + ".py", "--programs", "1", "--wave", "32", "--work", str(parent), - "--oracle", "translator,hw", *extra] - stderr = io.StringIO() - stats = ({32: {"match": 1, "mismatch": 0, "rejected": 0}}, []) - with (patch.object(sys, "argv", argv), patch.object(runner, "open_oracle", return_value=oracle), - patch.object(module, "run_hw", return_value=stats), contextlib.redirect_stdout(io.StringIO()), - contextlib.redirect_stderr(stderr)): - self.assertEqual(module.main(), 2) - self.assertTrue(oracle.closed) - self.assertIn("ERROR: cannot create work directory", stderr.getvalue()) - self.assertEqual(parent.read_bytes(), b"caller data") - - def test_child_creation_error_preserves_existing_files(self): - for module, extra in ((lds_fuzz, []), (valu_fuzz, ["--family", "f16"])): - with self.subTest(fuzzer=module.__name__), tempfile.TemporaryDirectory() as tmp: - parent = Path(tmp) / "work" - parent.mkdir() - sentinel = parent / "keep.txt" - sentinel.write_bytes(b"caller data") - argv = [module.__name__ + ".py", "--programs", "1", "--wave", "32", "--work", str(parent), *extra] - stderr = io.StringIO() - with (patch.object(sys, "argv", argv), - patch.object(module.tempfile, "mkdtemp", side_effect=PermissionError("synthetic deny")), - contextlib.redirect_stdout(io.StringIO()), contextlib.redirect_stderr(stderr)): - self.assertEqual(module.main(), 2) - self.assertIn("ERROR: cannot create work directory", stderr.getvalue()) - self.assertIn("synthetic deny", stderr.getvalue()) - self.assertEqual(sentinel.read_bytes(), b"caller data") - - def test_model_only_does_not_create_a_work_folder(self): - for module, extra in ((lds_fuzz, []), (valu_fuzz, ["--family", "f16"])): - with self.subTest(fuzzer=module.__name__), tempfile.TemporaryDirectory() as tmp: - parent = Path(tmp) / "not-created" - argv = [module.__name__ + ".py", "--programs", "1", "--wave", "32", "--model-only", - "--work", str(parent), *extra] - with patch.object(sys, "argv", argv), contextlib.redirect_stdout(io.StringIO()): - self.assertEqual(module.main(), 0) - self.assertFalse(parent.exists()) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/test_gallery.py b/tests/test_gallery.py deleted file mode 100644 index 708982290..000000000 --- a/tests/test_gallery.py +++ /dev/null @@ -1,653 +0,0 @@ -"""Unit tests for tools/gallery.py standalone 3D Studio & Asset Gallery server.""" -import functools -import json -import io -import os -import socket -import struct -import sys -import tempfile -import threading -import time -import unittest -from unittest import mock -import urllib.parse -import urllib.request -from unittest import mock - -HERE = os.path.dirname(os.path.abspath(__file__)) -ROOT = os.path.dirname(HERE) -TOOLS_DIR = os.path.join(ROOT, "tools") -if TOOLS_DIR not in sys.path: - sys.path.insert(0, TOOLS_DIR) - -import gallery - - -def _make_1x1_rgba_dds() -> bytes: - """Build a minimal 1x1 uncompressed RGBA DDS image for synthetic .dds -> .png preview tests.""" - hdr = bytearray(128) - hdr[0:4] = b"DDS " - struct.pack_into(" bytes: - lines = [f"GET {target} HTTP/1.1"] - if host is not None: - lines.append(f"Host: {host}") - lines.extend(extra_headers) - lines.extend(["Connection: close", "", ""]) - return "\r\n".join(lines).encode("latin-1") - - -def _split_response(raw: bytes): - head, _, body = raw.partition(b"\r\n\r\n") - status = int(head.split(b"\r\n", 1)[0].split()[1]) - return status, head.decode("latin-1"), body - - -def _raw_get(port: int, target: str, host: str | None = "127.0.0.1", extra_headers: tuple[str, ...] = ()): - """Send a raw HTTP/1.1 GET without client-side path normalization or header merging.""" - with socket.create_connection(("127.0.0.1", port), timeout=5) as sock: - sock.sendall(_get_request_bytes(target, host, extra_headers)) - chunks = [] - while data := sock.recv(65536): - chunks.append(data) - return _split_response(b"".join(chunks)) - - -class _MemoryConnection: - """Stands in for the accepted socket, so the handler reads exactly the bytes a test wrote: no loopback TCP, and so - nothing between the two ends that could rewrite the request (see _loopback_keeps_a_repeated_host).""" - - def __init__(self, request: bytes): - self._request = io.BytesIO(request) - self.response = bytearray() - - def makefile(self, mode, bufsize=-1): - return self._request - - def sendall(self, data): - self.response += data - - -def _memory_get(target: str, host: str | None = "127.0.0.1", extra_headers: tuple[str, ...] = ()): - """_raw_get without a socket: gallery.StudioHandler answers the same request bytes in this thread.""" - connection = _MemoryConnection(_get_request_bytes(target, host, extra_headers)) - gallery.StudioHandler(connection, ("127.0.0.1", 0), None) - return _split_response(bytes(connection.response)) - - -@functools.lru_cache(maxsize=1) -def _loopback_keeps_a_repeated_host() -> bool: - """False when a request sent over loopback TCP arrives without its second Host field. - - Security software that filters HTTP does this on some machines, on 127.0.0.1 too (measured with ESET Security on - Windows 11: `Host: a`, `Host: b` arrives as `Host: a`). The server then never sees the request the test wrote, so a - test of the duplicate-Host rule over a socket measures the filter, not gallery.py. Same probe as #4985 adds to - tests/test_viewer_serve.py.""" - request = b"GET / HTTP/1.1\r\nHost: 127.0.0.1\r\nHost: evil.example\r\nConnection: close\r\n\r\n" - received = bytearray() - with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as listener: - listener.bind(("127.0.0.1", 0)) - listener.listen(1) - listener.settimeout(10) - - def accept(): - try: - peer, _ = listener.accept() - except OSError: - return - with peer: - peer.settimeout(10) - try: - while not received.endswith(b"\r\n\r\n"): - data = peer.recv(65536) - if not data: - break - received.extend(data) - except OSError: - pass - - thread = threading.Thread(target=accept, daemon=True) - thread.start() - try: - with socket.create_connection(listener.getsockname(), timeout=10) as sock: - sock.sendall(request) - thread.join(10) - except OSError: - return True # no answer about a filter: let the socket test run and report what it sees - return bytes(received) == request or not received - - -class TestGalleryCategorization(unittest.TestCase): - def test_categories(self) -> None: - self.assertEqual(gallery.categorize_model("ped_lucia_body.glb"), "Персонажи (Characters)") - self.assertEqual(gallery.categorize_model("veh_infernus.glb"), "Транспорт (Vehicles)") - self.assertEqual(gallery.categorize_model("w_rifle_m4.glb"), "Оружие (Weapons)") - self.assertEqual(gallery.categorize_model("build_wall_01.glb"), "Карта и Здания (World)") - self.assertEqual(gallery.categorize_model("prop_chair_office.glb"), "Объекты и Пропы (Props)") - self.assertEqual(gallery.categorize_model("tree_palm_02.glb"), "Растительность (Nature)") - self.assertEqual(gallery.categorize_model("misc_something.glb"), "Прочее (Miscellaneous)") - - def test_folder_inference(self) -> None: - self.assertEqual(gallery.categorize_model("asset_01.glb", "clean_vehicles"), "Транспорт (Vehicles)") - self.assertEqual(gallery.categorize_model("model.glb", "unpacked_peds"), "Персонажи (Characters)") - - -class TestHostAllowed(unittest.TestCase): - def test_loopback_and_missing_hosts_are_allowed(self) -> None: - for host in (None, "127.0.0.1", "127.0.0.1:8080", "localhost", "LOCALHOST:8080", - "localhost.", "localhost.:8080", "[::1]", "[::1]:8080", " localhost "): - with self.subTest(host=host): - self.assertTrue(gallery.host_allowed(host)) - - def test_foreign_and_malformed_hosts_are_refused(self) -> None: - for host in ("", "evil.example", "evil.example:8080", "127.0.0.1.evil.example", - "localhost.evil.example:8080", "0.0.0.0:8080", "::1", - "localhost:", "localhost:abc", "localhost:65536", "localhost:" + "9" * 5000, - "[::1]junk", "[::1].", "[::1]:abc", "[::1]:8080:1", "127.0.0.1:80:80"): - with self.subTest(host=host[:40]): - self.assertFalse(gallery.host_allowed(host)) - - -class TestSafeSubpath(unittest.TestCase): - def setUp(self) -> None: - self.tmp = tempfile.TemporaryDirectory() - self.base = os.path.join(self.tmp.name, "assets") - self.sibling = os.path.join(self.tmp.name, "assets_secret") - os.makedirs(os.path.join(self.base, "sub"), exist_ok=True) - os.makedirs(self.sibling, exist_ok=True) - with open(os.path.join(self.base, "ok.glb"), "wb") as f: - f.write(b"ok") - with open(os.path.join(self.base, "sub", "nested.glb"), "wb") as f: - f.write(b"nested") - with open(os.path.join(self.sibling, "loot.glb"), "wb") as f: - f.write(b"loot") - - def tearDown(self) -> None: - self.tmp.cleanup() - - def test_valid_paths_resolve_inside_base(self) -> None: - for rel in ("ok.glb", "sub/nested.glb", "COM10.glb", "my.CON"): - with self.subTest(rel=rel): - resolved = gallery.safe_subpath(self.base, rel) - self.assertIsNotNone(resolved) - self.assertEqual( - os.path.normcase(os.path.commonpath([os.path.realpath(self.base), resolved])), - os.path.normcase(os.path.realpath(self.base)), - ) - - def test_traversal_and_invalid_segments_are_refused(self) -> None: - for rel in ("", "/", "\\", ".", "..", "sub", "sub/", "/ok.glb", "ok.glb/", - "../assets_secret/loot.glb", "..\\assets_secret\\loot.glb", - "sub/../../assets_secret/loot.glb", "sub//nested.glb", "./ok.glb", - "ok\x00.glb", "C:ok.glb", "ok.glb:stream"): - with self.subTest(rel=rel): - self.assertIsNone(gallery.safe_subpath(self.base, rel)) - - def test_windows_device_names_refused_before_realpath(self) -> None: - names = ("CON", "con.glb", "NUL", "NUL .glb", "COM1", "COM\u00b9.glb", "LPT\u00b2.png", "CONIN$", "conout$.bin") - with mock.patch.object(gallery.os.path, "isreserved", None, create=True): - with mock.patch.object(gallery.os.path, "realpath", - side_effect=AssertionError("device path reached realpath")) as rp: - for name in names: - with self.subTest(name=name): - self.assertIsNone(gallery.safe_subpath(self.base, name)) - self.assertIsNone(gallery.safe_subpath(self.base, f"sub/{name}")) - rp.assert_not_called() - - def test_symlink_escape_is_refused(self) -> None: - link = os.path.join(self.base, "escape.glb") - try: - os.symlink(os.path.join(self.sibling, "loot.glb"), link) - except (OSError, NotImplementedError) as exc: - self.skipTest(f"cannot create symlink here: {exc}") - self.assertIsNone(gallery.safe_subpath(self.base, "escape.glb")) - - def test_realpath_escape_is_refused(self) -> None: - outside = os.path.realpath(os.path.join(self.sibling, "loot.glb")) - real_base = os.path.realpath(self.base) - with mock.patch.object(gallery.os.path, "realpath", - side_effect=lambda p: real_base if p == self.base else outside): - self.assertIsNone(gallery.safe_subpath(self.base, "escape.glb")) - - -class TestGalleryServer(unittest.TestCase): - def setUp(self) -> None: - self.tmp = tempfile.TemporaryDirectory() - self.models_dir = os.path.join(self.tmp.name, "models") - self.models_secret = os.path.join(self.tmp.name, "models_secret") - self.textures_dir = os.path.join(self.tmp.name, "textures") - self.textures_secret = os.path.join(self.tmp.name, "textures_secret") - self.viewer_dir = os.path.join(self.tmp.name, "viewer") - self.viewer_secret = os.path.join(self.tmp.name, "viewer_secret") - self.vendor_dir = os.path.join(self.viewer_dir, "vendor") - for d in (self.models_dir, self.models_secret, self.textures_dir, - self.textures_secret, self.viewer_dir, self.viewer_secret, self.vendor_dir): - os.makedirs(d, exist_ok=True) - - # Create dummy assets - with open(os.path.join(self.models_dir, "test_car.glb"), "wb") as f: - f.write(b"glTF\x02\x00\x00\x00\x0c\x00\x00\x00") - - with open(os.path.join(self.textures_dir, "test_tex.png"), "wb") as f: - f.write(b"\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR") - - with open(os.path.join(self.textures_dir, "inside.dds"), "wb") as f: - f.write(_make_1x1_rgba_dds()) - - with open(os.path.join(self.viewer_dir, "studio.html"), "w", encoding="utf-8", newline="\n") as f: - f.write("

Studio

") - - with open(os.path.join(self.viewer_dir, "app.js"), "w", encoding="utf-8", newline="\n") as f: - f.write("console.log('ok');\n") - - with open(os.path.join(self.vendor_dir, "three.min.js"), "w", encoding="utf-8", newline="\n") as f: - f.write("// three\n") - - # Files outside the served roots that must never be served - with open(os.path.join(self.tmp.name, "secret.txt"), "wb") as f: - f.write(b"TOP_SECRET") - with open(os.path.join(self.tmp.name, "outside.dds"), "wb") as f: - f.write(_make_1x1_rgba_dds()) - with open(os.path.join(self.models_secret, "loot.glb"), "wb") as f: - f.write(b"LOOT_GLB") - with open(os.path.join(self.textures_secret, "loot.png"), "wb") as f: - f.write(b"LOOT_PNG") - with open(os.path.join(self.viewer_secret, "loot.txt"), "wb") as f: - f.write(b"LOOT_VIEWER") - - # Configure handler - gallery.StudioHandler.models_dir = self.models_dir - gallery.StudioHandler.textures_dir = self.textures_dir - gallery.StudioHandler.viewer_dir = self.viewer_dir - - # Start server on an open port - addr = ("127.0.0.1", 0) - self.httpd = gallery.socketserver.TCPServer(addr, gallery.StudioHandler) - self.port = self.httpd.server_address[1] - self.thread = threading.Thread(target=self.httpd.serve_forever, daemon=True) - self.thread.start() - time.sleep(0.1) - - def tearDown(self) -> None: - self.httpd.shutdown() - self.httpd.server_close() - self.tmp.cleanup() - - def test_texture_catalog_labels_jpeg_and_webp(self) -> None: - files = {"sky.JPG": "JPEG Image", "road.jpeg": "JPEG Image", "tree.webp": "WebP Image"} - for name in files: - with open(os.path.join(self.textures_dir, name), "wb") as f: - f.write(b"synthetic") - with urllib.request.urlopen(f"http://127.0.0.1:{self.port}/api/textures", timeout=3) as r: - textures = {row["name"]: row for row in json.load(r)["textures"]} - for name, expected in files.items(): - with self.subTest(name=name): - self.assertIn(name, textures) - self.assertEqual(textures[name]["format"], expected) - self.assertEqual(textures[name]["preview"], textures[name]["url"]) - - def test_dds_selection_by_catalog_url(self) -> None: - # Two RGBA8 layers with a 2x2 and 1x1 mip each. - hdr = bytearray(_make_1x1_rgba_dds()[:128]) - struct.pack_into("> mip - rgba = bytes([1 + layer * 2 + mip]) * (size * size * 4) - expected = gallery.dds_png.encode_png(size, size, rgba) - self.assertEqual(get(f"{url}?mip={mip}&layer={layer}"), expected) - if mip == layer == 0: - self.assertEqual(get(url), expected) - for query in ("layer=2", "mip=2", "mip=-1", "layer=1.5", "mip=", "mip=0&mip=1", "other=0"): - with self.subTest(query=query), self.assertRaises(urllib.error.HTTPError) as caught: - get(url + "?" + query) - self.assertEqual(caught.exception.code, 400) - - def test_volume_z_selection(self) -> None: - # Tight R16_FLOAT rows. Each 3x2 plane has a different pixel pattern. - hdr = bytearray(_make_1x1_rgba_dds()[:128]) - struct.pack_into(" None: - hdr = bytearray(_make_1x1_rgba_dds()[:128]) - struct.pack_into(" None: - base = f"http://127.0.0.1:{self.port}" - - # 1. Studio HTML root - with urllib.request.urlopen(f"{base}/", timeout=3) as r: - self.assertEqual(r.status, 200) - body = r.read().decode("utf-8") - self.assertIn("

Studio

", body) - - # 2. Models API - with urllib.request.urlopen(f"{base}/api/models", timeout=3) as r: - self.assertEqual(r.status, 200) - data = json.loads(r.read()) - self.assertEqual(data["count"], 1) - self.assertEqual(data["models"][0]["name"], "test_car.glb") - self.assertEqual(data["models"][0]["category"], "Транспорт (Vehicles)") - - # 3. Textures API - with urllib.request.urlopen(f"{base}/api/textures", timeout=3) as r: - self.assertEqual(r.status, 200) - tdata = json.loads(r.read()) - self.assertEqual(tdata["count"], 2) - self.assertEqual([t["name"] for t in tdata["textures"]], ["inside.dds", "test_tex.png"]) - - # 4. Binary serving & DDS preview fallback inside textures_dir - with urllib.request.urlopen(f"{base}/models/test_car.glb", timeout=3) as r: - self.assertEqual(r.status, 200) - self.assertTrue(r.read().startswith(b"glTF")) - - with urllib.request.urlopen(f"{base}/textures/test_tex.png", timeout=3) as r: - self.assertEqual(r.status, 200) - self.assertTrue(r.read().startswith(b"\x89PNG")) - - with urllib.request.urlopen(f"{base}/textures/inside.png", timeout=3) as r: - self.assertEqual(r.status, 200) - self.assertTrue(r.read().startswith(b"\x89PNG")) - - # 5. Viewer static & vendor assets - with urllib.request.urlopen(f"{base}/vendor/three.min.js", timeout=3) as r: - self.assertEqual(r.status, 200) - self.assertIn(b"// three", r.read()) - - with urllib.request.urlopen(f"{base}/app.js", timeout=3) as r: - self.assertEqual(r.status, 200) - self.assertIn(b"console.log", r.read()) - - def _raw_get(self, path: str) -> bytes: - """The whole response, status line and headers included, as the socket delivered it.""" - with socket.create_connection(("127.0.0.1", self.port), timeout=3) as sock: - sock.sendall(f"GET {path} HTTP/1.0\r\nHost: 127.0.0.1\r\n\r\n".encode()) - data = b"" - while chunk := sock.recv(65536): - data += chunk - return data - - def test_a_file_that_cannot_be_opened_is_one_500_response(self) -> None: - # _send_file used to send 200 and Content-Length before opening the file, then wrote a second status line - # (send_error's 500) into the body of the first. - def refuse(path, *args, **kwargs): - raise PermissionError(13, "Permission denied", path) - - gallery.open = refuse - self.addCleanup(delattr, gallery, "open") - response = self._raw_get("/textures/test_tex.png") - self.assertEqual(response.count(b"HTTP/1."), 1, response) - self.assertTrue(response.startswith(b"HTTP/1.0 500 "), response) - self.assertNotIn(b"LOOT", response) - - def test_a_read_error_after_the_headers_ends_the_response_short(self) -> None: - # Once 200 is out the status can't change: the body stops short and the connection closes, with no error - # page appended to it. - real_open = open - - class FailingRead(io.BufferedReader): - def read(self, *args): - raise OSError(5, "Input/output error") - - def failing(path, *args, **kwargs): - return FailingRead(real_open(path, "rb", buffering=0)) - - gallery.open = failing - self.addCleanup(delattr, gallery, "open") - response = self._raw_get("/textures/test_tex.png") - head, _, body = response.partition(b"\r\n\r\n") - self.assertEqual(response.count(b"HTTP/1."), 1, response) - self.assertTrue(head.startswith(b"HTTP/1.0 200 "), head) - size = os.path.getsize(os.path.join(self.textures_dir, "test_tex.png")) - self.assertIn(f"Content-Length: {size}".encode(), head) - self.assertEqual(body, b"") - - def test_a_read_error_after_the_headers_closes_a_keep_alive_connection(self) -> None: - # The gallery answers HTTP/1.0, which closes after every response anyway. Under HTTP/1.1 the connection - # would stay open, so a short body must close it, or the client would wait for the missing bytes. - real_open = open - - class FailingRead(io.BufferedReader): - def read(self, *args): - raise OSError(5, "Input/output error") - - gallery.open = lambda path, *a, **k: FailingRead(real_open(path, "rb", buffering=0)) - self.addCleanup(delattr, gallery, "open") - self.addCleanup(setattr, gallery.StudioHandler, "protocol_version", gallery.StudioHandler.protocol_version) - gallery.StudioHandler.protocol_version = "HTTP/1.1" - with socket.create_connection(("127.0.0.1", self.port), timeout=3) as sock: - sock.sendall(b"GET /textures/test_tex.png HTTP/1.1\r\nHost: 127.0.0.1\r\nConnection: keep-alive\r\n\r\n") - data = b"" - while chunk := sock.recv(65536): # a socket.timeout here means the connection was left open - data += chunk - head, _, body = data.partition(b"\r\n\r\n") - self.assertTrue(head.startswith(b"HTTP/1.1 200 "), head) - self.assertEqual(data.count(b"HTTP/1."), 1, data) - self.assertEqual(body, b"") - - def test_traversal_and_sibling_prefix_escapes_are_forbidden(self) -> None: - host = f"127.0.0.1:{self.port}" - cases = ( - ("/vendor/../../secret.txt", b"TOP_SECRET"), - ("/vendor/%2e%2e/%2e%2e/secret.txt", b"TOP_SECRET"), - ("/models/../models_secret/loot.glb", b"LOOT_GLB"), - ("/models/..%5cmodels_secret%5cloot.glb", b"LOOT_GLB"), - ("/textures/../textures_secret/loot.png", b"LOOT_PNG"), - ("/textures/../outside.png", b"\x89PNG"), - ("/textures/%2e%2e/outside.png", b"\x89PNG"), - ("/../viewer_secret/loot.txt", b"LOOT_VIEWER"), - ("/%2e%2e/viewer_secret/loot.txt", b"LOOT_VIEWER"), - ("/%2fviewer_secret/loot.txt", b"LOOT_VIEWER"), - ("/models//test_car.glb", b"glTF"), - ) - for target, secret in cases: - with self.subTest(target=target): - status, _, body = _raw_get(self.port, target, host=host) - self.assertEqual(status, 403) - self.assertNotIn(secret, body) - - def test_dds_symlink_escape_is_forbidden(self) -> None: - link = os.path.join(self.textures_dir, "escaped.dds") - try: - os.symlink(os.path.join(self.tmp.name, "outside.dds"), link) - except (OSError, NotImplementedError) as exc: - self.skipTest(f"cannot create symlink here: {exc}") - status, _, body = _raw_get(self.port, "/textures/escaped.png", host=f"127.0.0.1:{self.port}") - self.assertEqual(status, 403) - self.assertNotIn(b"\x89PNG", body) - - _GUARDED_TARGETS = ("/", "/api/models", "/api/textures", "/models/test_car.glb", "/textures/test_tex.png") - - def test_host_header_guards(self) -> None: - for target in self._GUARDED_TARGETS: - with self.subTest(case="foreign", target=target): - status, _, body = _raw_get(self.port, target, host="evil.example:8080") - self.assertEqual(status, 403) - self.assertNotIn(b"test_car.glb", body) - self.assertNotIn(b"glTF", body) - - status, _, body = _raw_get(self.port, "/models/test_car.glb", host=None) - self.assertEqual(status, 200) - self.assertTrue(body.startswith(b"glTF")) - - def _check_duplicate_host_gets_400(self, get) -> None: - loopback = f"127.0.0.1:{self.port}" - for target in self._GUARDED_TARGETS: - with self.subTest(target=target): - status, _, body = get(target, host=loopback, extra_headers=("Host: evil.example",)) - self.assertEqual(status, 400) - self.assertNotIn(b"test_car.glb", body) - self.assertNotIn(b"glTF", body) - - def test_duplicate_host_gets_400(self) -> None: - # The handler reads the request from memory, so the rule is checked on every machine. - self._check_duplicate_host_gets_400(_memory_get) - - def test_duplicate_host_gets_400_over_a_socket(self) -> None: - if not _loopback_keeps_a_repeated_host(): - self.skipTest("something on this machine removes a repeated Host field from loopback HTTP requests " - "(security software that filters HTTP)") - self._check_duplicate_host_gets_400(functools.partial(_raw_get, self.port)) - - def test_a_request_from_memory_is_answered_like_one_over_a_socket(self) -> None: - # _memory_get must reach the same guards and files as _raw_get, or test_duplicate_host_gets_400 checks nothing. - loopback = f"127.0.0.1:{self.port}" - for target, host in (("/models/test_car.glb", loopback), ("/textures/test_tex.png", loopback), - ("/api/models", loopback), ("/models/test_car.glb", "evil.example"), - ("/models/../secret.txt", loopback), ("/models/test_car.glb", None)): - with self.subTest(target=target, host=host): - over_socket = _raw_get(self.port, target, host=host) - from_memory = _memory_get(target, host=host) - self.assertEqual(from_memory[0], over_socket[0]) - self.assertEqual(from_memory[2], over_socket[2]) - - def test_windows_device_names_get_403_without_opening(self) -> None: - host = f"127.0.0.1:{self.port}" - targets = ("/models/COM%C2%B9.glb", "/textures/NUL%20.png", "/vendor/CONIN%24", "/AUX.js") - with mock.patch.object(gallery.os.path, "isreserved", None, create=True): - with mock.patch("builtins.open", side_effect=AssertionError("device path reached open")) as opened: - for target in targets: - with self.subTest(target=target): - status, _, _ = _raw_get(self.port, target, host=host) - self.assertEqual(status, 403) - opened.assert_not_called() - - def test_missing_valid_paths_return_404(self) -> None: - host = f"127.0.0.1:{self.port}" - for target in ("/vendor/missing.js", "/models/missing.glb", "/textures/missing.png", "/missing.js"): - with self.subTest(target=target): - status, _, _ = _raw_get(self.port, target, host=host) - self.assertEqual(status, 404) - - -class TestGalleryCommandLine(unittest.TestCase): - def test_rejects_out_of_range_ports_before_starting_server(self) -> None: - for port in (-1, 65536): - with ( - self.subTest(port=port), - mock.patch.object(gallery, "start_server") as start_server, - mock.patch.object(sys, "stderr", new_callable=io.StringIO) as stderr, - ): - with self.assertRaises(SystemExit) as raised: - gallery.main(["--port", str(port), "--no-browser"]) - - self.assertEqual(raised.exception.code, 2) - self.assertIn("--port must be between 0 and 65535", stderr.getvalue()) - start_server.assert_not_called() - - def test_passes_default_and_boundary_ports_to_server(self) -> None: - for args, port in (([], 8080), (["--port", "0"], 0), (["--port", "65535"], 65535)): - with self.subTest(port=port), mock.patch.object(gallery, "start_server") as start_server: - self.assertEqual(gallery.main([*args, "--no-browser"]), 0) - start_server.assert_called_once_with( - port=port, models_dir=None, textures_dir=None, open_browser=False, - retry_next_port=not args, - ) - - def test_reports_unavailable_listen_ports(self) -> None: - cases = ((["--port", "65535"], [65535]), (["--port", "8080"], [8080]), ([], [8080, 8081])) - for args, ports in cases: - with ( - self.subTest(ports=ports), - tempfile.TemporaryDirectory() as assets, - mock.patch.object(gallery.http.server.HTTPServer, "__init__", side_effect=OSError("address in use")) as bind, - mock.patch.object(sys, "stderr", new_callable=io.StringIO) as stderr, - ): - with self.assertRaises(SystemExit) as raised: - gallery.main([*args, "--models-dir", assets, "--textures-dir", assets, "--no-browser"]) - - self.assertEqual(raised.exception.code, 2) - self.assertIn(f"can't listen on port {ports[-1]}", stderr.getvalue()) - self.assertEqual([attempt.args[0] for attempt in bind.call_args_list], - [("127.0.0.1", port) for port in ports]) - - def test_implicit_port_can_use_the_next_port(self) -> None: - with ( - tempfile.TemporaryDirectory() as assets, - mock.patch.object(gallery.http.server.HTTPServer, "__init__", - side_effect=[OSError("address in use"), None]) as bind, - mock.patch.object(gallery.http.server.HTTPServer, "server_port", 8081, create=True), - mock.patch.object(gallery.http.server.HTTPServer, "serve_forever") as serve, - mock.patch.object(sys, "stdout", new_callable=io.StringIO) as stdout, - ): - self.assertEqual(gallery.main(["--models-dir", assets, "--textures-dir", assets, "--no-browser"]), 0) - self.assertEqual([attempt.args[0] for attempt in bind.call_args_list], - [("127.0.0.1", 8080), ("127.0.0.1", 8081)]) - self.assertIn("http://localhost:8081", stdout.getvalue()) - serve.assert_called_once_with() - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/test_gamedata_blobs.py b/tests/test_gamedata_blobs.py deleted file mode 100644 index fafd7dea0..000000000 --- a/tests/test_gamedata_blobs.py +++ /dev/null @@ -1,309 +0,0 @@ -"""gamedata_blobs.py must decode the remaining text and binary common.rpf payloads without game data. - - python -I tests/test_gamedata_blobs.py - -Every fixture is synthetic: preload lists, visual-settings lines, fixed-stride 1,296-byte records, a compact -3-region spatial grid blob, and minimal SGD5 databases. - -Set ``LEONIDA_GAMEDATA_BLOBS`` to another copy of the tool to use as a negative control; main's version fails -the bad-index cases with a bare KeyError or a raw index.json path. -""" -import json -import os -import shutil -import struct -import subprocess -import sys -import tempfile -import unittest -from unittest import mock - -ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) -TOOLS = os.path.join(ROOT, "tools") -TOOL = os.environ.get("LEONIDA_GAMEDATA_BLOBS", os.path.join(TOOLS, "gamedata_blobs.py")) -sys.path.insert(0, TOOLS) - -import gamedata_blobs # noqa: E402 -import sgd5_effects # noqa: E402 - - -def fixed_table_1296_blob(records: int) -> bytes: - """Build a synthetic 4 + N * 1296 fixed-stride table.""" - buf = bytearray(struct.pack(" bytes: - """Build a minimal valid 3-region grid (cells -> Region 3 ptrs -> Region 2 records of sizes 3, 6, 11).""" - r2_offset = cells * 4 - rec_word_sizes = (3, 6, 11) - r2_bytes = bytearray() - r2_rec_offsets = [] - pos = r2_offset - for idx, sz in enumerate(rec_word_sizes): - r2_rec_offsets.append(pos) - for w_i in range(sz): - # Keep Region 2 words >= len(blob) (high bit set) so they are distinct from trailing pointers. - r2_bytes += struct.pack(" 5 u32 words - r3_lists = ( - [r2_rec_offsets[0]], - [r2_rec_offsets[1], r2_rec_offsets[2]], - [r2_rec_offsets[0], r2_rec_offsets[2]], - ) - r3_bytes = bytearray() - r3_cell_offs = [] - cur = r3_offset - for lst in r3_lists: - r3_cell_offs.append(cur) - for ptr in lst: - r3_bytes += struct.pack(" bytes: - nbytes = name.encode("ascii") + b"\x00" - return ( - bytes([len(nbytes)]) + nbytes + bytes(4 + 24 + 80 + 16 + 12) - + struct.pack(" 0.95 distinguishes text from binary in small fixtures - preload0 = ("fx_one.fx\nfx_unused.fx\nfx_two.fx\n" + "\n" * 10).encode("ascii") - preload1 = ("fx_db1_only.fx\n" * 1).encode("ascii") + b" \n" - vfx_dat = ("# vfx\nfx_one.scale 0.5\nother.gamma 2.2\n" * 40).encode("ascii") - # Include enough lines for printable() and make binary chunk distinguishable - tbl = fixed_table_1296_blob(2) - grid = spatial_grid_blob(cells=8) - - self.add(tbl) - self.add(grid) - self.add(vfx_dat) - self.add(preload0) - self.add(preload1) - self.finish() - - archive_bytes, layouts = synthetic_sgd5_archive(["fx_one", "fx_two"], ["fx_db1_only"]) - shaders_path = os.path.join(self.root, "synthetic_shaders.rpf") - with open(shaders_path, "wb") as f: - f.write(archive_bytes) - - with mock.patch.object(sgd5_effects, "DATABASES", layouts): - payloads = gamedata_blobs.read_payloads(self.carve) - self.assertEqual([p["kind"] for p in payloads], - ["fixed_table_1296", "spatial_grid_table", "vfx_settings_dat", "fx_preload_list", "fx_preload_list"]) - xref = gamedata_blobs.cross_reference_sgd5(payloads, shaders_path) - self.assertEqual(xref["preload_lists"][0]["in_db0"], 2) - self.assertEqual(xref["preload_lists"][0]["unshipped"], 1) - self.assertTrue(xref["preload_lists"][0]["exact_order_db0"]) - self.assertTrue(xref["preload_lists"][1]["exact_order_db1"]) - self.assertEqual(xref["vfx_settings"][0]["prefixes_in_db0"], 1) - self.assertEqual(xref["vfx_settings"][0]["data_lines"], 80) - self.assertEqual(xref["vfx_settings"][0]["data_lines_in_db0"], 40) - - out_json = os.path.join(self.root, "reports", "blobs.json") - p = subprocess.run([sys.executable, "-I", TOOL, self.carve, "--json", out_json], - cwd=self.root, capture_output=True, text=True, encoding="utf-8", errors="replace") - self.assertEqual(p.returncode, 0, p.stdout + p.stderr) - with open(out_json, "rb") as f: - raw = f.read() - self.assertIn(b"\n", raw) - self.assertNotIn(b"\r\n", raw) - for secret in ("fx_one", "fx_unused", "fx_two", "fx_db1_only", "other.gamma"): - self.assertNotIn(secret, p.stdout) - self.assertNotIn(secret.encode("ascii"), raw) - - # Collisions against carve index, bin, shaders.rpf, or existing directory fail cleanly - for bad_out, extra in ( - (os.path.join(self.carve, "index.json"), []), - (os.path.join(self.carve, f"{self.rows[0]['off']:012x}.bin"), []), - (shaders_path, ["--shaders", shaders_path]), - ): - r = subprocess.run([sys.executable, "-I", TOOL, self.carve, *extra, "--json", bad_out], - cwd=self.root, capture_output=True, text=True, encoding="utf-8", errors="replace") - self.assertEqual(r.returncode, 1) - self.assertIn("error:", r.stderr) - self.assertNotIn("Traceback", r.stderr) - - -class BadCarveIndexTest(unittest.TestCase): - """A folder that is not an rpf9_carve.py carve is one error line naming the index and the bad row.""" - - def run_tool(self, target): - return subprocess.run([sys.executable, "-I", TOOL, target], - cwd=ROOT, capture_output=True, text=True, encoding="utf-8", errors="replace") - - def assert_one_error(self, result, *needles, code=1, prefix="error:"): - self.assertEqual(result.returncode, code, result.stdout + result.stderr) - self.assertNotIn("Traceback", result.stderr) - lines = result.stderr.strip().splitlines() - self.assertEqual(len(lines), 1, result.stderr) - self.assertTrue(lines[0].startswith(prefix), lines[0]) - for needle in needles: - self.assertIn(needle, lines[0]) - - def make_folder(self, index_json=None): - folder = tempfile.mkdtemp() - self.addCleanup(shutil.rmtree, folder, True) - if index_json is not None: - with open(os.path.join(folder, "index.json"), "w", encoding="utf-8") as f: - f.write(index_json) - return folder - - def test_no_index_json_names_the_folder(self): - folder = self.make_folder() - self.assert_one_error(self.run_tool(folder), folder, "no index.json") - - def test_malformed_json_names_the_index(self): - folder = self.make_folder("{oops") - self.assert_one_error(self.run_tool(folder), "index.json", "is not valid JSON") - - def test_index_without_files_names_the_key(self): - folder = self.make_folder("{}") - self.assert_one_error(self.run_tool(folder), "index.json", "no 'files' list") - - def test_row_without_stored_names_the_row(self): - folder = self.make_folder(json.dumps({"files": [{"off": 0}]})) - self.assert_one_error(self.run_tool(folder), "index.json", "row 0", "'off'", "'stored'") - - def test_missing_file_names_what_is_wrong(self): - # A missing input is "ERROR: ..." and exit 2 (#6701, tests/test_missing_input_exit_codes.py). - folder = self.make_folder() - self.assert_one_error(self.run_tool(os.path.join(folder, "nope.rpf")), "nope.rpf", "no such file or folder", - code=2, prefix="ERROR:") - - def test_reads_carve_index_with_utf8_bom(self): - folder = tempfile.mkdtemp() - self.addCleanup(shutil.rmtree, folder, True) - payload = fixed_table_1296_blob(1) - with open(os.path.join(folder, f"{0x1000:012x}.bin"), "wb") as f: - f.write(payload) - doc = {"files": [{"off": 0x1000, "stored": len(payload), "size": len(payload), "head": payload[:16].hex(), "pre": ""}]} - with open(os.path.join(folder, "index.json"), "wb") as f: - f.write(b"\xef\xbb\xbf" + json.dumps(doc).encode("utf-8")) - r = self.run_tool(folder) - self.assertEqual(r.returncode, 0, r.stdout + r.stderr) - self.assertIn("fixed_table_1296", r.stdout) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/test_gamedata_graph.py b/tests/test_gamedata_graph.py deleted file mode 100644 index 688dd6077..000000000 --- a/tests/test_gamedata_graph.py +++ /dev/null @@ -1,477 +0,0 @@ -"""gamedata_graph.py must measure a synthetic content-set graph without game data. - - python -I tests/test_gamedata_graph.py - -The fixtures are hand-written manifests: two change-set documents that include each other, one -content definition that includes the first, a missing set id, all four documented prefix rules, an -unknown ``common:/`` scheme, two parent locators, a tail-only document and a malformed document. -No game data is used. -""" -import json -import os -import subprocess -import sys -import tempfile -import unittest - -ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) -TOOL = os.path.join(ROOT, "tools", "gamedata_graph.py") -TOOLS = os.path.join(ROOT, "tools") -if TOOLS not in sys.path: - sys.path.insert(0, TOOLS) -import gamedata_graph as gg # noqa: E402 - -ALPHA = ( - b'\n' - b'\n' - b' set.alpha\n' - b' \n' - b' $(common)/fixture/a.bk2\n' - b' platform:/levels/fixture/a.rpf\n' - b' $(target)/fixture/a\n' - b' common:/FIXTURE/A.XML\n' - b' \n' - b' set.betamissing.set\n' - b'' -) -BETA = ( - b'\n' - b' set.beta\n' - b' platform:/data/fixture\n' - b' set.alpha\n' - b'' -) -GAMMA = ( - b'\n' - b'\n' - b' \n' - b' set.gamma' - b'$(common)/fixture/g.xml' - b'\n' - b' \n' - b' set.alpha\n' - b' $(root)/fixture/g.meta' - b'\n' - b'' -) -DELTA = ( - b'' -) -PLAIN = b'' -TAIL = b'\n' -BAD = b'' - - -class GamedataGraphTest(unittest.TestCase): - def setUp(self): - self.tmp = tempfile.TemporaryDirectory() - self.root = self.tmp.name - self.carve = os.path.join(self.root, "carve") - os.makedirs(self.carve) - self.rows = [] - self.next_off = 0x1000 - - def tearDown(self): - self.tmp.cleanup() - - def add(self, payload, parts=None): - parts = parts if parts is not None else [payload] - for part in parts: - offset = self.next_off - self.next_off += 0x1000 - with open(os.path.join(self.carve, f"{offset:012x}.bin"), "wb") as f: - f.write(part) - self.rows.append({ - "off": offset, - "stored": len(part), - "size": len(part), - "head": part[:16].hex(), - "pre": "", - }) - - def finish(self): - with open(os.path.join(self.carve, "index.json"), "w", encoding="utf-8") as f: - json.dump({"summary": {"archive": "synthetic", "files": len(self.rows)}, "files": self.rows}, f) - - def run_tool(self, *args): - return subprocess.run([sys.executable, "-I", TOOL, *args], cwd=self.root, - capture_output=True, text=True, errors="replace") - - def test_unknown_encoding_counts_as_unparsed_beside_valid_document(self): - unsupported = os.path.join(self.root, "unsupported.xml") - valid = os.path.join(self.root, "valid.xml") - out = os.path.join(self.root, "graph.json") - with open(unsupported, "wb") as f: - f.write(b'') - with open(valid, "wb") as f: - f.write(ALPHA) - result = self.run_tool(unsupported, valid, "--json", out) - self.assertEqual(result.returncode, 0, result.stderr) - with open(out, encoding="utf-8") as f: - summary = json.load(f)["summary"] - self.assertEqual(summary["payloads"], 2) - self.assertEqual(summary["parsed"], 1) - self.assertEqual(summary["unparsed"], 1) - self.assertEqual(summary["rootless"], 0) - self.assertEqual(summary["include_sites"], 2) - - def test_cli_reports_unwritable_graph_report(self): - self.finish() - out = os.path.join(self.root, "missing", "graph.json") - - result = self.run_tool(self.carve, "--json", out) - - self.assertEqual(result.returncode, 2, result.stderr) - self.assertIn(f"cannot write {out}", result.stderr) - self.assertNotIn("Traceback", result.stderr) - - def test_json_that_is_a_directory_is_refused(self): - self.finish() - r = self.run_tool(self.carve, "--json", self.root) - self.assertEqual(r.returncode, 2, r.stderr) - self.assertIn("is a directory", r.stderr) - self.assertNotIn("Traceback", r.stderr) - - def test_json_over_input_xml_file_is_refused(self): - xml_path = os.path.join(self.root, "input.xml") - with open(xml_path, "wb") as f: - f.write(ALPHA) - alias = os.path.join(self.root, ".", "input.xml") - r = self.run_tool(xml_path, "--json", alias) - self.assertEqual(r.returncode, 2, r.stderr) - self.assertIn("would overwrite the input", r.stderr) - self.assertNotIn("Traceback", r.stderr) - with open(xml_path, "rb") as f: - self.assertEqual(f.read(), ALPHA) - - def test_json_over_carve_dir_manifest_is_refused(self): - self.add(ALPHA) - self.finish() - manifest = os.path.join(self.carve, "index.json") - with open(manifest, "rb") as f: - content = f.read() - r = self.run_tool(self.carve, "--json", manifest) - self.assertEqual(r.returncode, 2, r.stderr) - self.assertIn("would overwrite the input", r.stderr) - self.assertNotIn("Traceback", r.stderr) - with open(manifest, "rb") as f: - self.assertEqual(f.read(), content) - - def test_json_over_carve_dir_bin_payload_is_refused(self): - self.add(ALPHA) - self.finish() - bin_path = os.path.join(self.carve, f"{self.rows[0]['off']:012x}.bin") - with open(bin_path, "rb") as f: - content = f.read() - r = self.run_tool(self.carve, "--json", bin_path) - self.assertEqual(r.returncode, 2, r.stderr) - self.assertIn("would overwrite an input file", r.stderr) - self.assertNotIn("Traceback", r.stderr) - with open(bin_path, "rb") as f: - self.assertEqual(f.read(), content) - - def test_json_cannot_replace_a_carved_payload_via_external_hard_link(self): - self.add(ALPHA) - self.finish() - payload = os.path.join(self.carve, f"{self.rows[0]['off']:012x}.bin") - report = os.path.join(self.root, "alias.json") - try: - os.link(payload, report) - except (OSError, NotImplementedError) as e: - self.skipTest(f"hard links unavailable: {e}") - r = self.run_tool(self.carve, "--json", report) - self.assertEqual(r.returncode, 2, r.stderr) - self.assertIn("would overwrite the input", r.stderr) - with open(payload, "rb") as f: - self.assertEqual(f.read(), ALPHA) - - def test_fresh_json_inside_carve_dir_is_allowed(self): - self.add(ALPHA) - self.finish() - out = os.path.join(self.carve, "graph.json") - r = self.run_tool(self.carve, "--json", out) - self.assertEqual(r.returncode, 0, r.stderr) - self.assertTrue(os.path.isfile(out)) - with open(out, "r", encoding="utf-8") as f: - data = json.load(f) - self.assertEqual(data["summary"]["mode"], "carve") - - def test_json_over_directory_mode_nested_xml_is_refused(self): - # Directory mode (no index.json) reads every nested *.xml; --json into one of them must not - # truncate it. - directory = os.path.join(self.root, "dir") - nested_dir = os.path.join(directory, "nested") - os.makedirs(nested_dir) - xml_path = os.path.join(nested_dir, "a.xml") - with open(xml_path, "wb") as f: - f.write(ALPHA) - - r = self.run_tool(directory, "--json", xml_path) - self.assertEqual(r.returncode, 2, r.stderr) - self.assertIn("would overwrite the input", r.stderr) - self.assertNotIn("Traceback", r.stderr) - with open(xml_path, "rb") as f: - self.assertEqual(f.read(), ALPHA) - - def test_json_over_directory_mode_xml_hardlink_is_refused(self): - directory = os.path.join(self.root, "dir") - os.makedirs(directory) - xml_path = os.path.join(directory, "a.xml") - with open(xml_path, "wb") as f: - f.write(ALPHA) - alias = os.path.join(self.root, "alias.xml") - try: - os.link(xml_path, alias) - except (OSError, NotImplementedError) as e: - self.skipTest(f"hard links unavailable: {e}") - - r = self.run_tool(directory, "--json", alias) - self.assertEqual(r.returncode, 2, r.stderr) - self.assertIn("would overwrite the input", r.stderr) - self.assertNotIn("Traceback", r.stderr) - with open(xml_path, "rb") as f: - self.assertEqual(f.read(), ALPHA) - - def test_cycle_at_end_of_a_deep_include_chain(self): - size = sys.getrecursionlimit() + 50 - adjacency = {node: [node + 1] for node in range(size - 1)} - adjacency[size - 1] = [size - 2] - components = gg._strongly_connected(list(range(size)), adjacency) - self.assertEqual(len(components), size - 1) - self.assertEqual([set(c) for c in components if len(c) > 1], [{size - 2, size - 1}]) - - def test_carve_graph_counts_cycles_reachability_and_no_leak(self): - self.add(ALPHA) - self.add(BETA) - split = GAMMA.index(b"") - self.add(GAMMA, [GAMMA[:split], GAMMA[split:]]) - self.add(DELTA) - self.add(PLAIN) - self.add(TAIL) - self.add(BAD) - self.finish() - - out = os.path.join(self.root, "graph.json") - p = self.run_tool(self.carve, "--json", out) - self.assertEqual(p.returncode, 0, p.stdout + p.stderr) - with open(out, encoding="utf-8") as f: - data = json.load(f) - s = data["summary"] - - self.assertEqual(s["mode"], "carve") - self.assertEqual(s["payloads"], 7) - self.assertEqual(s["documents"], 6) - self.assertEqual(s["parsed"], 5) - self.assertEqual(s["unparsed"], 2) - self.assertEqual(s["root_count"], 6) - self.assertEqual(s["rootless"], 0) - self.assertEqual(s["manifest_documents"], 3) - self.assertEqual(s["content_sets"], 4) - self.assertEqual(s["defined_content_sets"], 3) - self.assertEqual(s["dangling_content_sets"], 1) - self.assertEqual(s["duplicate_set_ids"], 0) - self.assertEqual(s["reference_sites"], 13) - self.assertEqual(s["target_sites"], 9) - self.assertEqual(s["include_sites"], 4) - self.assertEqual(s["references"], { - "filename": 6, "includedSets": 4, "loadPath": 1, "parentFile": 1, "parentPath": 1, - }) - self.assertEqual(s["prefixes"], { - "$(common)": 2, "$(root)": 1, "$(target)": 1, "common:/": 1, - "platform:/levels": 1, "platform:/other": 1, "relative/locator": 2, - }) - self.assertEqual(s["resolution"], { - "document": 3, "document_unmapped": 6, "include_id_missing": 1, - "relative_locator": 2, "unrecognized_prefix": 1, - }) - self.assertEqual(s["unique"], { - "targets": 9, - "targets_by_namespace": { - "$(common)": 2, "$(root)": 1, "$(target)": 1, "common:/": 1, - "platform:/levels": 1, "platform:/other": 1, "relative/locator": 2, - }, - "document_unmapped": 6, - "unknown_macro": 0, - "unrecognized_prefix": 1, - "relative_locator": 2, - "content_set_ids": 4, - "include_ids": 3, - }) - self.assertEqual(s["nodes"], {"documents": 7, "content_sets": 4, "targets": 9, "total": 20}) - self.assertEqual(s["edges"], { - "total": 16, "defines": 3, "includes": 4, "contains_file": 6, - "loads_changeset": 1, "parent_path": 1, "parent_file": 1, - "document_edges": 7, "target_edges": 9, - }) - self.assertEqual(s["content_graph"], { - "include_edges": 3, - "documents_with_incoming_includes": 2, - "documents_with_outgoing_includes": 3, - "root_documents": 1, - "root_fallback": False, - "reachable_documents": 3, - "max_depth": 2, - "cycles": 1, - "cycle_nodes": 2, - }) - self.assertEqual(s["reachable"], { - "documents": 3, "content_sets": 4, "targets": 7, "target_sites": 7, - }) - - mount = s["categories"]["mount / content manifests"] - self.assertEqual(mount["documents"], 3) - self.assertEqual(mount["manifest_documents"], 3) - self.assertEqual(mount["content_sets"], 3) - self.assertEqual(mount["include_references"], 4) - self.assertEqual(mount["target_references"], 7) - self.assertEqual(mount["references"], 11) - self.assertEqual(mount["roots"], 2) - unknown = s["categories"]["uncatalogued"] - self.assertEqual(unknown["documents"], 4) - self.assertEqual(unknown["target_references"], 2) - self.assertEqual(unknown["references"], 2) - self.assertEqual(unknown["roots"], 4) - - change_set = s["roots"]["CDataFileMgr__ContentChangeSetDef"] - self.assertEqual(change_set["documents"], 2) - self.assertEqual(change_set["content_sets"], 2) - self.assertEqual(change_set["include_references"], 3) - self.assertEqual(change_set["target_references"], 5) - self.assertEqual(change_set["references"], 8) - self.assertEqual(change_set["manifest_documents"], 2) - content_def = s["roots"]["CDataFileMgr__ContentDef"] - self.assertEqual(content_def["documents"], 1) - self.assertEqual(content_def["content_sets"], 1) - self.assertEqual(content_def["include_references"], 1) - self.assertEqual(content_def["target_references"], 2) - self.assertEqual(content_def["references"], 3) - - self.assertEqual(data["unresolved"], { - "document_unmapped": { - "$(common)": 2, "$(root)": 1, "$(target)": 1, - "platform:/levels": 1, "platform:/other": 1, - }, - "unknown_macro": {}, - "unrecognized_prefix": {"common:/": 1}, - "relative_locator": 2, - "include_id_missing": 1, - "total_sites": 10, - }) - - # Values, ids, locators and per-file names must not leak into the aggregate output. - with open(out, encoding="utf-8") as f: - blob = f.read() - for value in ("a.bk2", "fixture/a.rpf", "FIXTURE/A.XML", "set.alpha", "set.beta", - "missing.set", "../Item", "parent.dat", "fixture/g.meta", - "alpha.xml", "g.xml"): - self.assertNotIn(value, blob) - - def test_file_mode_keeps_manifest_documents_and_missing_ids(self): - alpha = os.path.join(self.root, "alpha.xml") - gamma = os.path.join(self.root, "gamma.xml") - delta = os.path.join(self.root, "delta.xml") - for path, payload in ((alpha, ALPHA), (gamma, GAMMA), (delta, DELTA)): - with open(path, "wb") as f: - f.write(payload) - - out = os.path.join(self.root, "files.json") - p = self.run_tool(alpha, gamma, delta, "--json", out) - self.assertEqual(p.returncode, 0, p.stdout + p.stderr) - with open(out, encoding="utf-8") as f: - data = json.load(f) - s = data["summary"] - self.assertEqual(s["mode"], "files") - self.assertEqual(s["payloads"], 3) - self.assertEqual(s["parsed"], 3) - self.assertEqual(s["manifest_documents"], 2) - self.assertEqual(s["content_sets"], 4) # alpha, beta, gamma and the second missing id - self.assertEqual(s["defined_content_sets"], 2) - self.assertEqual(s["dangling_content_sets"], 2) - self.assertEqual(s["resolution"]["document"], 1) - self.assertEqual(s["resolution"]["include_id_missing"], 2) - self.assertEqual(s["content_graph"]["include_edges"], 1) - self.assertEqual(s["content_graph"]["reachable_documents"], 2) - self.assertEqual(s["content_graph"]["cycles"], 0) - - def test_file_mode_counts_filenames_outside_file_lists(self): - with open(os.path.join(self.root, "sample.xml"), "wb") as f: - f.write(b"platform:/levels/a" - b"platform:/levels/b") - - p = self.run_tool("sample.xml", "--json", "graph.json") - self.assertEqual(p.returncode, 0, p.stdout + p.stderr) - with open(os.path.join(self.root, "graph.json"), encoding="utf-8") as f: - s = json.load(f)["summary"] - self.assertEqual(s["references"], {"filename": 1}) - self.assertEqual(s["nodes"]["targets"], 1) - self.assertEqual(s["edges"]["contains_file"], 1) - - def test_prefix_classification_keeps_unknown_schemes_unresolved(self): - self.assertEqual(gg.classify_target("$(common)/fixture/a.bk2"), - ("$(common)", "fixture/a.bk2", "document_unmapped")) - self.assertEqual(gg.classify_target("$(root)/fixture/x.meta"), - ("$(root)", "fixture/x.meta", "document_unmapped")) - self.assertEqual(gg.classify_target("platform:/levels/fixture/a.rpf"), - ("platform:/levels", "levels/fixture/a.rpf", "document_unmapped")) - self.assertEqual(gg.classify_target("platform:/data/fixture"), - ("platform:/other", "data/fixture", "document_unmapped")) - self.assertEqual(gg.classify_target("common:/FIXTURE/A.XML"), - ("common:/", "FIXTURE/A.XML", "unrecognized_prefix")) - self.assertEqual(gg.classify_target("$(future)/a"), - ("$(future)", "a", "unknown_macro")) - self.assertEqual(gg.classify_target("../Item[@key='X']"), - ("relative/locator", "../Item[@key='X']", "relative_locator")) - - -INHERIT = ( - b'' - b'' - b'' - b'' - b'' - b'' - b'' - b'' - b'' - b'' - b'' - b'' - b'' - b'' -) - - -class ParentPathInheritanceTest(unittest.TestCase): - def graph(self, *payloads): - return gg.build_graph([{"data": p, "complete": True} for p in payloads]) - - def test_sibling_locators_resolve_inside_the_document(self): - s = self.graph(INHERIT)["summary"]["parent_path_inheritance"] - self.assertEqual(s["documents"], 1) - self.assertEqual(s["sites"], 9) - self.assertEqual(s["xpath_sibling_form"], 8) # "Item/base" is not the ../Tag[@a='v'] form - # mid, leaf, dq, loopa, loopb; "case" is exact-match only; "far" has no sibling "base" in - self.assertEqual(s["resolved_in_document"], 5) - self.assertEqual(s["ambiguous"], 1) # two siblings share the key "twin" - self.assertEqual(s["unresolved"], 3) - self.assertEqual(s["chain_depths"], {"1": 2, "2": 1}) # mid and dq -> base, leaf -> mid -> base - self.assertEqual(s["cycles"], 2) # loopa and loopb each walk back to themselves - - def test_existing_counts_are_unchanged(self): - s = self.graph(INHERIT)["summary"] - self.assertEqual(s["references"], {"parentPath": 9}) - self.assertEqual(s["edges"]["parent_path"], 9) - self.assertEqual(s["resolution"], {"relative_locator": 9}) - - def test_no_locator_documents(self): - s = self.graph(PLAIN, BAD)["summary"]["parent_path_inheritance"] - self.assertEqual((s["documents"], s["sites"], s["cycles"], s["chain_depths"]), (0, 0, 0, {})) - - def test_summary_keeps_no_key_strings(self): - text = json.dumps(self.graph(INHERIT)) - for word in ("base", "leaf", "twin", "loopa", "far"): - self.assertNotIn(word, text) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/test_gamedata_graph_bad_index.py b/tests/test_gamedata_graph_bad_index.py deleted file mode 100644 index 083c842e8..000000000 --- a/tests/test_gamedata_graph_bad_index.py +++ /dev/null @@ -1,71 +0,0 @@ -"""Bad carve indexes must give one ERROR line in gamedata_graph.py, never a traceback. - -Run with ``python -I tests/test_gamedata_graph_bad_index.py``. Set ``LEONIDA_GAMEDATA_GRAPH`` to another copy -of the tool to use as a negative control (main's version fails every malformed-index case). All inputs are -hand-built; no game data is used. -""" -import json -import os -import pathlib -import subprocess -import sys -import tempfile -import unittest - -ROOT = pathlib.Path(__file__).resolve().parent.parent -TOOL = pathlib.Path(os.environ.get("LEONIDA_GAMEDATA_GRAPH", str(ROOT / "tools" / "gamedata_graph.py"))) -XML = (b'\n' - b'fixture') - - -class BadGamedataGraphIndexTest(unittest.TestCase): - def run_tool(self, carve): - return subprocess.run([sys.executable, "-I", str(TOOL), str(carve)], - cwd=ROOT, capture_output=True, text=True, timeout=60) - - def make_carve(self, folder, doc=None, text=None, payload=None): - carve = pathlib.Path(folder) / "x.rpf" - carve.mkdir() - index = carve / "index.json" - if text is not None: - index.write_text(text, encoding="utf-8") - else: - index.write_text(json.dumps(doc), encoding="utf-8") - if payload is not None: - (carve / "000000000000.bin").write_bytes(payload) - return carve - - def assert_one_error(self, result): - self.assertNotIn("Traceback", result.stderr, result.stderr) - self.assertEqual(result.returncode, 2, result.stderr) - self.assertEqual(len(result.stderr.strip().splitlines()), 1, result.stderr) - self.assertTrue(result.stderr.startswith("ERROR: cannot read "), result.stderr) - - def test_missing_files_key(self): - with tempfile.TemporaryDirectory() as td: - self.assert_one_error(self.run_tool(self.make_carve(td, {}))) - - def test_files_is_a_string(self): - with tempfile.TemporaryDirectory() as td: - self.assert_one_error(self.run_tool(self.make_carve(td, {"files": "oops"}))) - - def test_malformed_json(self): - with tempfile.TemporaryDirectory() as td: - self.assert_one_error(self.run_tool(self.make_carve(td, text="{oops"))) - - def test_row_without_off(self): - with tempfile.TemporaryDirectory() as td: - self.assert_one_error(self.run_tool(self.make_carve(td, {"files": [{"size": 4}]}))) - - def test_valid_carve_still_reports(self): - with tempfile.TemporaryDirectory() as td: - doc = {"files": [{"off": 0, "stored": len(XML), "size": len(XML), "head": XML[:16].hex()}]} - carve = self.make_carve(td, doc, payload=XML) - result = self.run_tool(carve) - self.assertEqual(result.returncode, 0, result.stderr) - self.assertNotIn("Traceback", result.stderr) - self.assertIn("payloads", result.stdout) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/test_gamedata_index.py b/tests/test_gamedata_index.py deleted file mode 100644 index 9c5599181..000000000 --- a/tests/test_gamedata_index.py +++ /dev/null @@ -1,497 +0,0 @@ -"""gamedata_index.py must group RPF9 zlib blocks into payloads without game data. - - python -I tests/test_gamedata_index.py - -Every fixture here is synthetic: small XML documents, a text list, a binary blob and two archive -magics. The archive test builds a minimal RPF9-shaped file with a zlib stream and zero padding. -""" -import csv -import importlib.util -import json -import os -import struct -import subprocess -import sys -import tempfile -import unittest -import zlib -from unittest import mock - -ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) -TOOL = os.path.join(ROOT, "tools", "gamedata_index.py") - - -def load_tool(): - spec = importlib.util.spec_from_file_location("gamedata_index_under_test", TOOL) - module = importlib.util.module_from_spec(spec) - spec.loader.exec_module(module) - return module - - -def chunked(data: bytes, first: int = 65536): - """Split a payload into a 64 KiB block and the remainder, the way RPF9 stores large files.""" - return [data[:first], data[first:]] if len(data) > first else [data] - - -T = load_tool() - - -class GamedataIndexTest(unittest.TestCase): - def setUp(self): - self.tmp = tempfile.TemporaryDirectory() - self.root = self.tmp.name - self.carve = os.path.join(self.root, "carve") - os.makedirs(self.carve) - self.rows = [] - self.next_off = 0x1000 - - def tearDown(self): - self.tmp.cleanup() - - def add(self, payload, chunks=None): - parts = chunks if chunks is not None else [payload] - for part in parts: - off = self.next_off - self.next_off += 0x1000 - with open(os.path.join(self.carve, f"{off:012x}.bin"), "wb") as f: - f.write(part) - self.rows.append({ - "off": off, - "stored": len(part), - "size": len(part), - "head": part[:16].hex(), - "pre": "", - }) - - def finish(self): - with open(os.path.join(self.carve, "index.json"), "w", encoding="utf-8") as f: - json.dump({"summary": {"archive": "synthetic", "files": len(self.rows)}, "files": self.rows}, f) - - def run_tool(self, target, *args): - return subprocess.run([sys.executable, "-I", TOOL, target, *args], cwd=self.root, - capture_output=True, text=True, encoding="utf-8", errors="replace") - - def test_a_resource_continues_after_any_whole_number_of_64k_blocks(self): - # A 0DRP resource whose first stream is 128 KiB continues in the next stream (docs/page_directory.md); - # a binary run of the same shape has no header proving that, so it keeps the exact 64 KiB rule. - page = bytes(T.PAGE_MARKER_AT) + T.PAGE_MARKER - resource = page + b"\x11" * (2 * 65536 - len(page)) - self.add(resource, [resource, b"\x22" * 1000]) - binary = bytes(range(256)) * 512 # 128 KiB with no header - self.add(binary, [binary, bytes(range(255, -1, -1)) * 4]) - self.finish() - out = os.path.join(self.root, "index.json") - p = self.run_tool(self.carve, "--json", out) - self.assertEqual(p.returncode, 0, p.stdout + p.stderr) - with open(out, encoding="utf-8") as f: - data = json.load(f) - self.assertEqual([(r["type"], r["chunks"]) for r in data["rows"]], - [("other", 2), ("binary", 1), ("binary", 1)]) - - def test_rejects_a_shared_csv_and_json_destination(self): - self.finish() - out = os.path.join(self.root, "index.json") - with open(out, "w", encoding="utf-8") as f: - f.write("existing report") - alias = os.path.join(self.root, ".", "index.json") - - result = self.run_tool(self.carve, "--csv", out, "--json", alias) - - with open(out, encoding="utf-8") as f: - self.assertEqual(f.read(), "existing report") - self.assertEqual(result.returncode, 2, result.stderr) - self.assertIn("--csv and --json must use different paths", result.stderr) - - def test_a_report_cannot_land_on_a_carved_stream(self): - # A carve folder holds one .bin/.bk2 per stream; a report written over one would eat the input. - self.add(b"
") - self.finish() - stream = os.path.join(self.carve, f"{self.rows[0]['off']:012x}.bin") - with open(stream, "rb") as f: - before = f.read() - for flag in ("--json", "--csv"): - with self.subTest(flag=flag): - p = self.run_tool(self.carve, flag, stream) - self.assertEqual(p.returncode, 2, p.stdout + p.stderr) - self.assertIn("would overwrite the carved stream", p.stderr) - self.assertNotIn("Traceback", p.stderr) - with open(stream, "rb") as f: - self.assertEqual(f.read(), before) - - def test_bad_targets_are_one_line(self): - empty = os.path.join(self.root, "empty.rpf") - open(empty, "wb").close() - no_index = os.path.join(self.root, "no_index") - os.mkdir(no_index) - bad_index = os.path.join(self.root, "bad_index") - os.mkdir(bad_index) - with open(os.path.join(bad_index, "index.json"), "w", encoding="utf-8") as f: - f.write('{"summary": {}}') # no "files" list - cases = ((os.path.join(self.root, "missing.rpf"), "does not exist"), (empty, "empty.rpf"), - (no_index, "index.json is missing"), (bad_index, "cannot read")) - for target, message in cases: - with self.subTest(target=os.path.basename(target)): - p = self.run_tool(target, "--json", os.path.join(self.root, "out.json")) - self.assertEqual(p.returncode, 2, p.stderr) - self.assertIn(message, p.stderr) - self.assertNotIn("Traceback", p.stderr) - self.assertEqual(p.stdout, "") - self.assertFalse(os.path.exists(os.path.join(self.root, "out.json"))) - - def test_directory_groups_chunks_and_roots(self): - self.add(b'\n') - second = b'\n' + b"x" * (65536 - len(b'\n')) - self.add(second, chunked(second + b"")) - text = b"line of text\n" * 6000 - self.add(text, chunked(text)) - self.add(b"RBF0" + bytes(60)) - self.add(b"PSIN" + bytes(60)) - self.add(bytes(range(256)) * 2) - self.add(b"MHIU" + b"\x17" * 100, [b"MHIU" + b"\x17" * 65532, b"\x17" * 100]) - self.add(b"\n") # no declaration, root inferred from the close tag - self.add(b"mid") # continuation whose start block was not carved - self.finish() - - out = os.path.join(self.root, "index.json") - p = self.run_tool(self.carve, "--csv", os.path.join(self.root, "index.csv"), "--json", out) - self.assertEqual(p.returncode, 0, p.stdout + p.stderr) - with open(out, encoding="utf-8") as f: - data = json.load(f) - s = data["summary"] - self.assertEqual(s["types"]["xml"]["files"], 4) # RootA, RootB, TailRoot, fragment - self.assertEqual(s["types"]["text"]["files"], 1) - self.assertEqual(s["types"]["rbf0"]["files"], 1) - self.assertEqual(s["types"]["psin"]["files"], 1) - self.assertEqual(s["types"]["binary"]["files"], 1) - self.assertEqual(s["types"]["other"]["files"], 1) - self.assertEqual(s["xml_documents"], 3) - self.assertEqual(s["xml_with_header"], 2) - self.assertEqual(s["xml_tail_only"], 1) - self.assertEqual(s["xml_incomplete"], 1) - self.assertEqual(set(s["roots"]), {"RootA", "RootB", "TailRoot"}) - self.assertEqual(len(data["rows"]), 9) - self.assertEqual([r["root"] for r in data["rows"] if r["type"] == "xml" and r["complete"]], - ["RootA", "RootB", "TailRoot"]) - self.assertEqual(data["rows"][1]["chunks"], 2) - self.assertEqual(data["rows"][2]["chunks"], 2) - self.assertEqual(data["rows"][6]["detail"], "MHIU") - self.assertEqual(data["rows"][7]["type"], "xml") - self.assertTrue(data["rows"][7]["complete"]) - self.assertFalse(data["rows"][7]["header"]) - self.assertFalse(data["rows"][8]["complete"]) - - with open(os.path.join(self.root, "index.csv"), newline="", encoding="utf-8") as f: - rows = list(csv.DictReader(f)) - self.assertEqual(len(rows), 9) - self.assertEqual(rows[0]["root"], "RootA") - self.assertEqual(rows[0]["type"], "xml") - - def test_sps1_magic_is_classified_as_other_sps1(self): - # +0x04 is u32 entry_count; 90 (0x5a = 'Z') reproduces the 5th byte that used to read "SPS1Z". - sps = bytearray(b"SPS1" + struct.pack("" * 80)[:4096 - len(head)] - page += bytes(512) - tool = load_tool() - self.assertGreater(tool.printable(page), 0.95) # the heuristic alone would call it text - self.add(page) - self.finish() - out = os.path.join(self.root, "index.json") - p = self.run_tool(self.carve, "--json", out) - self.assertEqual(p.returncode, 0, p.stdout + p.stderr) - with open(out, encoding="utf-8") as f: - data = json.load(f) - self.assertNotIn("xml", data["summary"]["types"]) - self.assertEqual(data["summary"]["xml_incomplete"], 0) - self.assertEqual([(r["type"], r["detail"]) for r in data["rows"]], [("other", "0DRP")]) - - def test_archive_runs_the_carver_and_reads_roots(self): - xml = b'\n' - blob = b"\x00\x01\x02binary\xff" * 32 - start = 16 - body = struct.pack("') - self.finish() - blocker = os.path.join(self.root, "blocker") - with open(blocker, "wb") as f: - f.write(b"x") - for flag, name in (("--csv", "out.csv"), ("--json", "out.json")): - with self.subTest(flag=flag): - out = os.path.join(blocker, name) - p = self.run_tool(self.carve, flag, out) - self.assertEqual(p.returncode, 2, p.stdout + p.stderr) - self.assertIn("ERROR: cannot write", p.stderr) - self.assertNotIn("Traceback", p.stderr) - - def test_reads_carve_index_with_utf8_bom(self): - self.add(b'') - index_path = os.path.join(self.carve, "index.json") - doc = {"summary": {"archive": "synthetic", "files": len(self.rows)}, "files": self.rows} - with open(index_path, "wb") as f: - f.write(b"\xef\xbb\xbf" + json.dumps(doc).encode("utf-8")) - out = os.path.join(self.root, "bom_out.json") - p = self.run_tool(self.carve, "--json", out) - self.assertEqual(p.returncode, 0, p.stdout + p.stderr) - with open(out, encoding="utf-8") as f: - data = json.load(f) - self.assertEqual(data["summary"]["xml_documents"], 1) - - -class XmlClassificationTest(unittest.TestCase): - """Synthetic XML classification cases; no game data, no files written.""" - - def setUp(self): - self.tool = load_tool() - self.bom = b"\xef\xbb\xbf" - self.decl = b'' - - def test_declaration_after_bom_and_whitespace_is_detected(self): - for space in (b"", b"\n", b" ", b"\r\n\t"): - with self.subTest(space=space): - data = self.bom + space + self.decl + b"\n" - self.assertTrue(self.tool.has_xml_decl(data)) - self.assertEqual(self.tool.stream_kind(data, {}), "decl") - self.assertEqual(self.tool.xml_root(data), "Root") - self.assertTrue(self.tool.standalone_xml(data)) - - def test_bom_only_empty_and_mid_document_declaration_have_no_leading_declaration(self): - for data in (b"", self.bom, self.bom + b" ", b"" + self.decl + b""): - with self.subTest(data=data): - self.assertFalse(self.tool.has_xml_decl(data)) - self.assertEqual(self.tool.xml_root(data), "Root" if b"" in data else "") - - def test_nested_same_name_root_is_not_a_closed_document(self): - for data in (b"", b"\n", b"x"): - with self.subTest(data=data): - self.assertFalse(self.tool.xml_complete("Foo", data)) - self.assertFalse(self.tool.standalone_xml(self.decl + data)) - - def test_root_name_requires_a_delimiter_after_the_whole_name(self): - for suffix in ("\u00e9", "\u6f22", "\u0301", "\u00b7", "\u00a0", "!", "=", "\x0b", "\x0c"): - with self.subTest(suffix=suffix): - data = ("").encode("utf-8") - self.assertEqual(self.tool.xml_root(data), "") - self.assertEqual(self.tool.xml_root(self.bom + self.decl + data), "") - self.assertEqual(self.tool.xml_root(b"", b"/>", b' attr="v">', b"\tattr='v'>", b"\rattr='v'>", b"\nattr='v'>"): - with self.subTest(name=name, ending=ending): - self.assertEqual(self.tool.xml_root(b"<" + name + ending), name.decode("ascii")) - - def test_balanced_and_self_closing_roots_remain_complete(self): - for data in (b"", b"textinner", - b"", b" \n", b"\n"): - with self.subTest(data=data): - self.assertTrue(self.tool.xml_complete("Foo", data)) - self.assertFalse(self.tool.xml_complete("", b"")) - - def test_quoted_greater_than_in_attributes_does_not_end_a_tag(self): - for data in (b'', b"", - b'text', b''): - with self.subTest(data=data): - self.assertTrue(self.tool.xml_complete("Foo", data)) - # A real second open element still leaves the document incomplete. - self.assertFalse(self.tool.xml_complete("Foo", b'')) - - def test_tags_inside_comments_and_cdata_do_not_count(self): - self.assertTrue(self.tool.xml_complete("Foo", b"]]>")) - for data in (b"", b"]]>"): - with self.subTest(data=data): - self.assertFalse(self.tool.xml_complete("Foo", data)) - - def test_self_closing_root_is_standalone_xml(self): - for data in (b"", b' \n', - self.bom + self.decl + b"\n"): - with self.subTest(data=data): - self.assertTrue(self.tool.standalone_xml(data)) - for bad in (b"", b"", b" trailing"): - with self.subTest(bad=bad): - self.assertFalse(self.tool.standalone_xml(bad)) - - -class XmlGroupingRegressionTest(GamedataIndexTest): - """The classification bugs must also show up in the index the tool writes.""" - - def test_declared_root_name_can_end_at_a_stream_boundary(self): - self.add(b"", [b'"]) - self.finish() - rows = T.build_rows(self.rows, T.DirectorySource(self.carve)) - self.assertEqual([(r["root"], r["complete"], r["chunks"]) for r in rows], [("Root", True, 2)]) - - def test_split_non_ascii_root_is_not_reported_as_its_ascii_prefix(self): - tail = ("\u00e9>" + "x" * 100 + "").encode("utf-8") - self.add(b"", [b'" + b"x" * (65536 - len(b">")) + b"" - self.add(b"", [first, second]) - self.add(b"unrelated text") - self.finish() - rows = T.build_rows(self.rows, T.DirectorySource(self.carve)) - self.assertEqual([(r["type"], r["chunks"]) for r in rows], [("xml", 2), ("text", 1)]) - self.assertEqual((rows[0]["root"], rows[0]["complete"]), ("Root", True)) - - def test_bom_with_whitespace_is_grouped_as_an_xml_document(self): - doc = b"\xef\xbb\xbf\n" + b'' + b"\n" - self.add(doc) - self.finish() - out = os.path.join(self.root, "index.json") - p = self.run_tool(self.carve, "--json", out) - self.assertEqual(p.returncode, 0, p.stderr) - with open(out, encoding="utf-8") as f: - rows = json.load(f)["rows"] - self.assertEqual(len(rows), 1) - self.assertEqual(rows[0]["type"], "xml") - self.assertEqual(rows[0]["root"], "RootBom") - self.assertTrue(rows[0]["header"]) - self.assertTrue(rows[0]["complete"]) - - def test_nested_open_root_stays_incomplete_after_continuation(self): - head = b"\xef\xbb\xbf" + b'' + b"\n" - head += b"x" * (65536 - len(head)) # a full 64 KiB stream, so the next one is absorbed - tail = b"" # closes only the nested Foo - self.add(head + tail, chunked(head + tail)) - self.finish() - out = os.path.join(self.root, "index.json") - p = self.run_tool(self.carve, "--json", out) - self.assertEqual(p.returncode, 0, p.stderr) - with open(out, encoding="utf-8") as f: - doc = json.load(f) - self.assertEqual(doc["summary"]["types"]["xml"]["files"], 1) - row = doc["rows"][0] - self.assertEqual(row["chunks"], 2) - self.assertTrue(row["header"]) - self.assertFalse(row["complete"]) - - def test_self_closing_and_exact_64k_declarationless_xml_boundaries(self): - # 1) A 64 KiB binary stream followed by a self-closing XML document must not swallow the XML. - bin64 = bytes(range(256)) * 256 - self.add(bin64) - self.add(b'\n') - # 2) An exact 64 KiB complete declarationless XML document must not swallow the next text stream. - prefix, suffix = b"", b"" - exact64 = prefix + b"a" * (65536 - len(prefix) - len(suffix)) + suffix - self.add(exact64) - self.add(b"plain text after xml\n") - # 3) An incomplete 64 KiB declarationless XML stream must not swallow a following binary stream. - unclosed64 = b"" + b"b" * (65536 - len(b"")) - self.add(unclosed64) - self.add(bytes(range(256)) * 2) - self.finish() - out = os.path.join(self.root, "index.json") - p = self.run_tool(self.carve, "--json", out) - self.assertEqual(p.returncode, 0, p.stderr) - with open(out, encoding="utf-8") as f: - rows = json.load(f)["rows"] - self.assertEqual( - [(r["type"], r["root"], r["complete"], r["chunks"]) for r in rows], - [ - ("binary", "", True, 1), - ("xml", "EmptyDoc", True, 1), - ("xml", "Exact64", True, 1), - ("text", "", True, 1), - ("xml", "", False, 1), - ("binary", "", True, 1), - ], - ) - - def test_declarationless_xml_keeps_utf8_continuation_stream(self): - # A 64 KiB continuation of non-ASCII UTF-8 text falls below printable()'s ASCII ratio - # and classifies as "binary", yet must stay part of the open declarationless XML document. - accent = "é".encode("utf-8") - # Split an "é" (0xC3 0xA9) across the 64 KiB chunk boundary as well. - head = b"" + b" " * (65536 - len(b"") - 1) + accent[:1] - middle = accent[1:] + b"" + accent * 32766 - self.assertEqual(len(head), 65536) - self.assertEqual(len(middle), 65536) - tail = b"" - self.add(head) - self.add(middle) - self.add(tail) - self.finish() - out = os.path.join(self.root, "index.json") - p = self.run_tool(self.carve, "--json", out) - self.assertEqual(p.returncode, 0, p.stderr) - with open(out, encoding="utf-8") as f: - rows = json.load(f)["rows"] - self.assertEqual( - [(r["type"], r["root"], r["complete"], r["chunks"]) for r in rows], - [("xml", "Doc", True, 3)], - ) - - -class BuildRowsReadCountTest(unittest.TestCase): - """The XML-shaped text branch must join the chunks it already read, not reinflate the group twice.""" - - def test_text_group_with_late_close_reads_each_member_once(self): - tool = load_tool() - head = b"" + b" " * (65536 - len(b"")) - tail = b"" - rows = [ - {"off": 0x1000, "stored": len(head), "size": 65536, "head": head[:16].hex(), "type": ""}, - {"off": 0x2000, "stored": len(tail), "size": len(tail), "head": tail[:16].hex(), "type": ""}, - ] - chunks_by_offset = {0x1000: head, 0x2000: tail} - source = mock.Mock() - source.read.side_effect = lambda row: chunks_by_offset[row["off"]] - - out = tool.build_rows(rows, source) - - self.assertEqual(len(out), 1) - row = out[0] - self.assertEqual(row["type"], "xml") - self.assertEqual(row["root"], "SyntheticRoot") - self.assertTrue(row["complete"]) - self.assertFalse(row["header"]) - self.assertEqual(row["chunks"], 2) - self.assertEqual(row["size"], 65536 + len(tail)) - self.assertEqual(row["stored"], len(head) + len(tail)) - self.assertEqual(source.read.call_count, 2) - self.assertEqual([call.args[0]["off"] for call in source.read.call_args_list], - [0x1000, 0x2000]) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/test_gamedata_index_report_paths.py b/tests/test_gamedata_index_report_paths.py deleted file mode 100644 index 17e041736..000000000 --- a/tests/test_gamedata_index_report_paths.py +++ /dev/null @@ -1,105 +0,0 @@ -"""gamedata_index.py report paths: create the parent folder and never overwrite the input index. - -Run with ``python -I tests/test_gamedata_index_report_paths.py``. Set ``LEONIDA_GAMEDATA_INDEX`` to -another copy of the tool to use as a negative control (main's version overwrites the input index and -tracebacks on a missing report folder). All inputs are hand-built; no game data is used. -""" -import json -import os -import pathlib -import subprocess -import sys -import tempfile -import unittest - -ROOT = pathlib.Path(__file__).resolve().parent.parent -TOOL = pathlib.Path(os.environ.get("LEONIDA_GAMEDATA_INDEX", str(ROOT / "tools" / "gamedata_index.py"))) - - -class ReportPathTest(unittest.TestCase): - def make_carve(self, folder): - carve = pathlib.Path(folder) / "x.rpf" - carve.mkdir() - (carve / "index.json").write_text(json.dumps({"files": []}), encoding="utf-8") - return carve - - def run_tool(self, carve, *extra): - return subprocess.run([sys.executable, "-I", str(TOOL), str(carve), *extra], - cwd=ROOT, capture_output=True, text=True, timeout=60) - - def test_missing_json_folder_is_created(self): - with tempfile.TemporaryDirectory() as td: - carve = self.make_carve(td) - out = pathlib.Path(td) / "missing" / "sub" / "gamedata.json" - result = self.run_tool(carve, "--json", str(out)) - self.assertEqual(result.returncode, 0, result.stderr) - self.assertTrue(out.is_file(), result.stderr) - self.assertIn("summary", json.loads(out.read_text(encoding="utf-8"))) - - def test_missing_csv_folder_is_created(self): - with tempfile.TemporaryDirectory() as td: - carve = self.make_carve(td) - out = pathlib.Path(td) / "missing" / "sub" / "gamedata.csv" - result = self.run_tool(carve, "--csv", str(out)) - self.assertEqual(result.returncode, 0, result.stderr) - self.assertTrue(out.is_file(), result.stderr) - self.assertIn("offset", out.read_text(encoding="utf-8").splitlines()[0]) - - def test_json_cannot_overwrite_the_input_index(self): - with tempfile.TemporaryDirectory() as td: - carve = self.make_carve(td) - index = carve / "index.json" - before = index.read_text(encoding="utf-8") - result = self.run_tool(carve, "--json", str(index)) - self.assertEqual(result.returncode, 2, result.stderr) - self.assertIn("would overwrite the input", result.stderr) - self.assertEqual(index.read_text(encoding="utf-8"), before) - - def test_csv_cannot_overwrite_the_input_index(self): - with tempfile.TemporaryDirectory() as td: - carve = self.make_carve(td) - index = carve / "index.json" - before = index.read_text(encoding="utf-8") - result = self.run_tool(carve, "--csv", str(index)) - self.assertEqual(result.returncode, 2, result.stderr) - self.assertIn("would overwrite the input", result.stderr) - self.assertEqual(index.read_text(encoding="utf-8"), before) - - def test_json_cannot_be_a_directory(self): - with tempfile.TemporaryDirectory() as td: - carve = self.make_carve(td) - outdir = pathlib.Path(td) / "outdir" - outdir.mkdir() - result = self.run_tool(carve, "--json", str(outdir)) - self.assertEqual(result.returncode, 2, result.stderr) - self.assertIn("is a directory", result.stderr) - - def test_csv_cannot_be_a_directory(self): - with tempfile.TemporaryDirectory() as td: - carve = self.make_carve(td) - outdir = pathlib.Path(td) / "outdir" - outdir.mkdir() - result = self.run_tool(carve, "--csv", str(outdir)) - self.assertEqual(result.returncode, 2, result.stderr) - self.assertIn("is a directory", result.stderr) - - def test_json_and_csv_must_differ(self): - with tempfile.TemporaryDirectory() as td: - carve = self.make_carve(td) - out = pathlib.Path(td) / "report.bin" - result = self.run_tool(carve, "--json", str(out), "--csv", str(out)) - self.assertEqual(result.returncode, 2, result.stderr) - self.assertIn("must use different paths", result.stderr) - - def test_reports_in_a_writable_folder_still_work(self): - with tempfile.TemporaryDirectory() as td: - carve = self.make_carve(td) - js = pathlib.Path(td) / "report.json" - csv_path = pathlib.Path(td) / "report.csv" - result = self.run_tool(carve, "--json", str(js), "--csv", str(csv_path)) - self.assertEqual(result.returncode, 0, result.stderr) - self.assertTrue(js.is_file() and csv_path.is_file(), result.stderr) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/test_gamedata_maps.py b/tests/test_gamedata_maps.py deleted file mode 100644 index 7f6edb19d..000000000 --- a/tests/test_gamedata_maps.py +++ /dev/null @@ -1,495 +0,0 @@ -"""gamedata_maps.py must decode the measured MHIU and PAMH (HMAP) layouts. - - python -I tests/test_gamedata_maps.py - -Every fixture is synthetic. MHIU is a 44-byte header, a row table and packed -u8 heights with a default fill. PAMH is HMAP v1.2: a row table, a max u8 array -and a min u8 array. The archive tests build a carve-shaped directory and check -the CLI, including a MHIU split across two 64 KiB streams. -""" -import json -import os -import struct -import subprocess -import sys -import tempfile -import unittest -from unittest import mock - -ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) -TOOLS = os.path.join(ROOT, "tools") -TOOL = os.path.join(TOOLS, "gamedata_maps.py") -sys.path.insert(0, TOOLS) - -import gamedata_maps # noqa: E402 - - -def mhiu_payload(width: int, height: int, rows, pixels: bytes, - default: int = 23) -> bytes: - """`rows` is a list of (start, count, values); offsets are assigned in order.""" - table = bytearray() - packed = bytearray() - for start, count, values in rows: - assert len(values) == count - offset = len(packed) - start - table += struct.pack(" bytes: - rows = b"".join(struct.pack("max", p.stdout) - - def test_groups_mhiu_continuation_stream(self): - payload = mhiu_payload(300, 1, [(0, 300, [i % 256 for i in range(300)])], pixels=b"\x07" * 90000) - self.assertGreater(len(payload), 65536) - self.add(payload, [payload[:65536], payload[65536:]]) - self.finish() - - p, data = self.run_tool() - self.assertEqual(p.returncode, 0, p.stdout + p.stderr) - mhiu = data["payloads"][0] - self.assertEqual(mhiu["chunks"], 2) - self.assertEqual(mhiu["grid"]["width"], 300) - self.assertEqual(mhiu["grid"]["height"], 1) - - def test_groups_a_continuation_after_a_128k_first_stream(self): - # The header's size bounds the join, so a first stream of any whole number of 64 KiB blocks continues. - payload = mhiu_payload(300, 1, [(0, 300, [i % 256 for i in range(300)])], pixels=b"\x07" * 150000) - self.assertGreater(len(payload), 2 * 65536) - self.add(payload, [payload[:2 * 65536], payload[2 * 65536:]]) - self.finish() - - p, data = self.run_tool() - self.assertEqual(p.returncode, 0, p.stdout + p.stderr) - mhiu = data["payloads"][0] - self.assertEqual(mhiu["chunks"], 2) - self.assertEqual(mhiu["grid"]["width"], 300) - - def test_reports_an_unwritable_json_destination(self): - self.finish() - blocker = os.path.join(self.root, "blocker") - with open(blocker, "wb") as f: - f.write(b"not a directory") - out = os.path.join(blocker, "maps.json") - result = subprocess.run( - [sys.executable, "-I", TOOL, self.carve, "--json", out], - capture_output=True, text=True, errors="replace", - ) - self.assertEqual(result.returncode, 1) - self.assertIn(f"cannot write {out}", result.stderr) - self.assertNotIn("Traceback", result.stderr) - self.assertNotIn("wrote", result.stdout) - - def test_creates_missing_parent_directories_for_json_with_lf_endings(self): - self.add(pamh_payload(3, 2, [1, 2, 3, 4, 5, 6], [0, 1, 2, 3, 4, 5])) - self.finish() - out = os.path.join(self.root, "missing", "nested", "maps.json") - result = subprocess.run( - [sys.executable, "-I", TOOL, self.carve, "--json", out], - cwd=self.root, capture_output=True, text=True, - encoding="utf-8", errors="replace", - ) - self.assertEqual(result.returncode, 0, result.stdout + result.stderr) - self.assertTrue(os.path.isfile(out)) - with open(out, "rb") as f: - raw = f.read() - self.assertIn(b"\n", raw) - self.assertNotIn(b"\r\n", raw) - data = json.loads(raw.decode("utf-8")) - self.assertEqual(len(data["payloads"]), 1) - self.assertEqual(data["payloads"][0]["type"], "PAMH") - - def test_refuses_json_colliding_with_index_json_and_case_variants(self): - self.add(pamh_payload(2, 2, [1, 2, 3, 4], [0, 1, 2, 3])) - self.finish() - index_path = os.path.join(self.carve, "index.json") - with open(index_path, "rb") as f: - original = f.read() - - targets = [index_path, os.path.join(self.carve, ".", "index.json")] - cased_index = os.path.join(self.carve, "INDEX.JSON") - if os.path.exists(cased_index): - targets.append(cased_index) - targets.append(os.path.join(self.root, "CARVE", "INDEX.JSON")) - - for out in targets: - with self.subTest(out=out): - result = subprocess.run( - [sys.executable, "-I", TOOL, self.carve, "--json", out], - cwd=self.root, capture_output=True, text=True, - encoding="utf-8", errors="replace", - ) - self.assertEqual(result.returncode, 1, result.stdout + result.stderr) - self.assertIn("error:", result.stderr) - self.assertIn("would overwrite", result.stderr) - self.assertNotIn("Traceback", result.stderr) - self.assertNotIn("wrote", result.stdout) - with open(index_path, "rb") as f: - self.assertEqual(f.read(), original) - - def test_refuses_json_colliding_with_carved_bin_file(self): - self.add(pamh_payload(2, 2, [1, 2, 3, 4], [0, 1, 2, 3])) - self.finish() - carved = os.path.join(self.carve, "000000001000.bin") - with open(carved, "rb") as f: - original = f.read() - - targets = [carved] - cased_bin = os.path.join(self.carve, "000000001000.BIN") - if os.path.exists(cased_bin): - targets.append(cased_bin) - - hardlink = os.path.join(self.root, "hardlink.json") - try: - os.link(carved, hardlink) - except (OSError, NotImplementedError): - hardlink = None - if hardlink is not None: - targets.append(hardlink) - - symlink = os.path.join(self.root, "symlink.json") - try: - os.symlink(carved, symlink) - except (OSError, NotImplementedError): - symlink = None - if symlink is not None: - targets.append(symlink) - - for out in targets: - with self.subTest(out=out): - result = subprocess.run( - [sys.executable, "-I", TOOL, self.carve, "--json", out], - cwd=self.root, capture_output=True, text=True, - encoding="utf-8", errors="replace", - ) - self.assertEqual(result.returncode, 1, result.stdout + result.stderr) - self.assertIn("error:", result.stderr) - self.assertIn("would overwrite", result.stderr) - self.assertNotIn("Traceback", result.stderr) - self.assertNotIn("wrote", result.stdout) - with open(carved, "rb") as f: - self.assertEqual(f.read(), original) - - def test_refuses_json_colliding_with_index_only_carved_stream(self): - self.add(pamh_payload(2, 2, [1, 2, 3, 4], [0, 1, 2, 3])) - self.finish() - carved = os.path.join(self.carve, "000000001000.bin") - os.remove(carved) - - result = subprocess.run( - [sys.executable, "-I", TOOL, self.carve, "--json", carved], - cwd=self.root, capture_output=True, text=True, - encoding="utf-8", errors="replace", - ) - self.assertEqual(result.returncode, 1, result.stdout + result.stderr) - self.assertIn("error:", result.stderr) - self.assertIn("would overwrite", result.stderr) - self.assertFalse(os.path.exists(carved)) - - def test_refuses_json_pointing_to_existing_directory_or_carve_dir(self): - self.finish() - existing_dir = os.path.join(self.root, "reports_dir") - os.makedirs(existing_dir) - - for out, expected in ((existing_dir, "directory"), (self.carve, "would overwrite")): - with self.subTest(out=out): - result = subprocess.run( - [sys.executable, "-I", TOOL, self.carve, "--json", out], - cwd=self.root, capture_output=True, text=True, - encoding="utf-8", errors="replace", - ) - self.assertEqual(result.returncode, 1, result.stdout + result.stderr) - self.assertIn("error:", result.stderr) - self.assertIn(expected, result.stderr) - self.assertNotIn("Traceback", result.stderr) - self.assertNotIn("wrote", result.stdout) - - def test_validates_json_before_scanning_carve_dir(self): - # Leave index.json corrupt so a scan would fail with a JSON error instead of the path guard. - carved = os.path.join(self.carve, "000000001000.bin") - with open(carved, "wb") as f: - f.write(b"raw carved stream") - index_path = os.path.join(self.carve, "index.json") - with open(index_path, "wb") as f: - f.write(b"{corrupt json") - out_dir = os.path.join(self.root, "existing_dir") - os.makedirs(out_dir) - - for out, expected in ((out_dir, "directory"), - (index_path, "would overwrite"), - (carved, "would overwrite")): - with self.subTest(out=out): - result = subprocess.run( - [sys.executable, "-I", TOOL, self.carve, "--json", out], - cwd=self.root, capture_output=True, text=True, - encoding="utf-8", errors="replace", - ) - self.assertEqual(result.returncode, 1, result.stdout + result.stderr) - self.assertIn(expected, result.stderr) - self.assertEqual(result.stdout, "") - - def test_allows_non_input_json_report_inside_carve_dir(self): - self.add(pamh_payload(2, 2, [1, 2, 3, 4], [0, 1, 2, 3])) - self.finish() - out = os.path.join(self.carve, "maps.json") - for _ in range(2): - result = subprocess.run( - [sys.executable, "-I", TOOL, self.carve, "--json", out], - cwd=self.root, capture_output=True, text=True, - encoding="utf-8", errors="replace", - ) - self.assertEqual(result.returncode, 0, result.stdout + result.stderr) - with open(out, encoding="utf-8") as f: - data = json.load(f) - self.assertEqual(len(data["payloads"]), 1) - - def test_macos_case_insensitive_volume_folds_case_and_nfd(self): - with mock.patch.object(gamedata_maps.os, "name", "posix"), \ - mock.patch.object(gamedata_maps.sys, "platform", "darwin"), \ - mock.patch.object(gamedata_maps.os, "pathconf", return_value=0, create=True): - self.assertTrue(gamedata_maps.same_report_path( - os.path.join(self.carve, "INDEX.JSON"), - os.path.join(self.carve, "index.json"), - )) - self.assertTrue(gamedata_maps.same_report_path( - os.path.join(self.carve, "caf\u00e9.json"), - os.path.join(self.carve, "CAFE\u0301.json"), - )) - - def test_complete_64k_map_leaves_the_next_stream_alone(self): - payload = mhiu_payload(255, 1, [(0, 255, [7] * 255)], pixels=b"\x00" * 65229) - self.assertEqual(len(payload), 65536) - self.add(payload) - self.add(b"unrelated resource") - self.finish() - - p, data = self.run_tool() - self.assertEqual(p.returncode, 0, p.stderr) - row, = data["payloads"] - self.assertEqual((row["size"], row["chunks"]), (65536, 1)) - self.assertEqual(row["grid"]["width"], 255) - - -class MalformedCarveIndex(unittest.TestCase): - """A carve index that parses but has no usable files list names the index, not a bare KeyError.""" - - def run_tool(self, index): - with tempfile.TemporaryDirectory() as root: - with open(os.path.join(root, "index.json"), "w", encoding="utf-8") as f: - json.dump(index, f) - result = subprocess.run([sys.executable, "-I", TOOL, root], - capture_output=True, text=True, errors="replace") - return result - - def test_empty_index_names_the_file_and_the_missing_key(self): - result = self.run_tool({}) - self.assertEqual(result.returncode, 1) - self.assertIn("index.json has no 'files' list", result.stderr) - self.assertNotIn("error: 'files'", result.stderr) - self.assertNotIn("Traceback", result.stderr) - - def test_row_without_an_offset_is_named(self): - result = self.run_tool({"files": [{"stored": 12}]}) - self.assertEqual(result.returncode, 1) - self.assertIn("row 0 needs an 'off'", result.stderr) - self.assertNotIn("Traceback", result.stderr) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/test_gamedata_maps_bad_index.py b/tests/test_gamedata_maps_bad_index.py deleted file mode 100644 index f1b4605bc..000000000 --- a/tests/test_gamedata_maps_bad_index.py +++ /dev/null @@ -1,90 +0,0 @@ -"""Bad carve indexes must give one error line in gamedata_maps.py, never a traceback. - -Run with ``python -I tests/test_gamedata_maps_bad_index.py``. Set ``LEONIDA_GAMEDATA_MAPS`` to another copy -of the tool to use as a negative control (main's version fails the two TypeError cases). All inputs are -hand-built; no game data is used. -""" -import json -import os -import pathlib -import subprocess -import sys -import tempfile -import unittest - -ROOT = pathlib.Path(__file__).resolve().parent.parent -TOOL = pathlib.Path(os.environ.get("LEONIDA_GAMEDATA_MAPS", str(ROOT / "tools" / "gamedata_maps.py"))) - - -class BadGamedataMapsIndexTest(unittest.TestCase): - def run_tool(self, carve): - return subprocess.run([sys.executable, "-I", str(TOOL), str(carve)], - cwd=ROOT, capture_output=True, text=True, timeout=60) - - def make_carve(self, folder, doc=None, text=None): - carve = pathlib.Path(folder) / "x.rpf" - carve.mkdir() - index = carve / "index.json" - if text is not None: - index.write_text(text, encoding="utf-8") - else: - index.write_text(json.dumps(doc), encoding="utf-8") - return carve - - def assert_one_error(self, result): - self.assertNotIn("Traceback", result.stderr, result.stderr) - self.assertEqual(result.returncode, 1, result.stderr) - self.assertEqual(len(result.stderr.strip().splitlines()), 1, result.stderr) - self.assertTrue(result.stderr.startswith("error:"), result.stderr) - - def assert_missing_source(self, result, target): - self.assertNotIn("Traceback", result.stderr, result.stderr) - self.assertEqual(result.returncode, 2, result.stderr) - self.assertEqual(len(result.stderr.strip().splitlines()), 1, result.stderr) - self.assertTrue(result.stderr.startswith(f"ERROR: {target}:"), result.stderr) - - def test_source_is_a_file(self): - # main's version names the index it could not open ('\index.json') and exits 1. - with tempfile.TemporaryDirectory() as td: - source = pathlib.Path(td) / "not-a-carve.txt" - source.write_text("junk", encoding="utf-8") - self.assert_missing_source(self.run_tool(source), source) - - def test_folder_without_index(self): - # A folder of carved .bin files whose index.json is missing, as main also fails on. - with tempfile.TemporaryDirectory() as td: - carve = pathlib.Path(td) - (carve / "000000000001.bin").write_bytes(b"MHIU" + bytes(40)) - self.assert_missing_source(self.run_tool(carve), carve) - - def test_missing_files_key(self): - with tempfile.TemporaryDirectory() as td: - self.assert_one_error(self.run_tool(self.make_carve(td, {}))) - - def test_files_is_a_string(self): - # TypeError in read_payloads: the one shape main's except tuple did not catch. - with tempfile.TemporaryDirectory() as td: - self.assert_one_error(self.run_tool(self.make_carve(td, {"files": "oops"}))) - - def test_files_is_null(self): - with tempfile.TemporaryDirectory() as td: - self.assert_one_error(self.run_tool(self.make_carve(td, {"files": None}))) - - def test_malformed_json(self): - with tempfile.TemporaryDirectory() as td: - self.assert_one_error(self.run_tool(self.make_carve(td, text="{oops"))) - - def test_row_without_off(self): - with tempfile.TemporaryDirectory() as td: - self.assert_one_error(self.run_tool(self.make_carve(td, {"files": [{"size": 4}]}))) - - def test_empty_carve_still_reports(self): - with tempfile.TemporaryDirectory() as td: - result = self.run_tool(self.make_carve(td, {"files": []})) - self.assertEqual(result.returncode, 0, result.stderr) - self.assertNotIn("Traceback", result.stderr) - self.assertIn("no MHIU or PAMH payloads", result.stdout) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/test_gamedata_reader.py b/tests/test_gamedata_reader.py deleted file mode 100644 index 1d8d9e081..000000000 --- a/tests/test_gamedata_reader.py +++ /dev/null @@ -1,402 +0,0 @@ -"""gamedata_reader: the generic conversion of RAGE parser XML, root/type dispatch, streaming and the CLI (no game files). - - python -I tests/test_gamedata_reader.py - -Every document is written here by hand, in the conventions docs/gamedata.md describes for common.rpf. -""" -import io -import json -import os -import subprocess -import sys -import tempfile -import unittest -from unittest import mock -import xml.etree.ElementTree as ET - -TOOLS = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "tools") -sys.path.insert(0, TOOLS) -import gamedata_reader as R # noqa: E402 - -DOC = b"""\xef\xbb\xbf - - - - - - - - - - - - - 1 2 3 - 4 5 - - 0.5 1.0 2.0 - 0 1 2 3 - - 1 0 0 - 0 1 0 - 0 0 1 - 4 5 6 - - - - - - - - - - - - - - -""" - -WANT = { - "@version": 3, "enabled": True, "count": 12, "mask": 31, "scale": 1.5, "bias": -2.5, "limit": float("inf"), - "label": "synthetic_name", "empty": "", "offset": (1.0, 2.5, -3.0), "tint": (0.5, 0.25, 0.0, 1.0), - "ids": [1, 2, 3, 4, 5], "weights": [0.5, 1, 2.0], "uvs": [(0, 1), (2, 3)], - "basis": [(1, 0, 0), (0, 1, 0), (0, 0, 1), (4, 5, 6)], - "items": [{"$type": "CThing", "size": 2}, None, {"size": 3}], - "lookup": {"alpha": {"v": 1}, "beta": {"v": 2}}, - "target": {"$ref": "other_entry"}, - "entry": [{"v": 1, "@name": "first", "@userFlags": 3}, {"v": 2, "@name": "second", "@userFlags": 0}], -} - - -class Conventions(unittest.TestCase): - def test_every_convention(self): - reader = R.Reader(root_handlers={}, type_handlers={}) - tag, typ, value = reader.read(DOC) - self.assertEqual((tag, typ), ("CSyntheticRoot", None)) - self.assertEqual(value, WANT) - self.assertEqual(reader.types, {"CThing": 1}) - for kind in ("scalar", "vector", "array", "list", "map", "null", "object", "reference", "struct", "text", - "extra attributes"): - self.assertGreater(reader.stats[kind], 0, kind) - - def test_streaming_equals_whole_tree(self): - # read() converts each top-level field as it ends and clears it; the result is the whole-tree conversion - reader = R.Reader(root_handlers={}, type_handlers={}) - whole = reader.convert(ET.fromstring(DOC[3:])) - self.assertEqual(reader.read(DOC)[2], whole) - - def test_scalars(self): - for text, want in (("true", True), ("false", False), ("7", 7), ("-7", -7), ("0xff", 255), ("1e3", 1000.0), - ("2.0f", 2.0), ("-inf", float("-inf")), ("abc", "abc"), ("1.2.3", "1.2.3")): - self.assertEqual(R.parse_scalar(text), want, text) - self.assertIs(type(R.parse_scalar(text)), type(want), text) - - def test_vector_array_must_be_whole(self): - with self.assertRaises(ValueError): - R.parse_content("vec3v_array", "1 2 3 4") - - def test_polymorphic_root_and_list_root(self): - reader = R.Reader(root_handlers={}, type_handlers={}) - self.assertEqual(reader.read(b''), ("R", "CRootType", - {"$type": "CRootType", "a": 1})) - self.assertEqual(reader.read(b'')[2], [1, 2]) - self.assertEqual(reader.read(b'leaf')[2], "leaf") - - def test_vector_with_extra_attributes_and_non_vector_xyzw(self): - reader = R.Reader(root_handlers={}, type_handlers={}) - self.assertEqual( - reader.read(b'')[2], - {"offset": {"$value": (1.0, 2.5, -3.0), "@name": "head", "@userFlags": 3}}, - ) - self.assertEqual(reader.stats["vector"], 1) - self.assertEqual(reader.stats["extra attributes"], 1) - - self.assertEqual( - reader.read(b'')[2], - {"node": {"@x": "label", "@y": 1.0}}, - ) - self.assertEqual( - reader.read(b'')[2], - {"node": {"@y": 2.0, "@z": 3.0}}, - ) - self.assertEqual( - reader.read(b'')[2], - {"s": {"$value": 10, "@x": 2}}, - ) - - def test_streaming_drops_top_level_children_from_root(self): - orig_iterparse = ET.iterparse - roots_seen = [] - max_children = 0 - - def spy_iterparse(*args, **kwargs): - nonlocal max_children - for event, el in orig_iterparse(*args, **kwargs): - if event == "start" and not roots_seen: - roots_seen.append(el) - elif roots_seen: - max_children = max(max_children, len(roots_seen[0])) - yield event, el - - with mock.patch.object(ET, "iterparse", side_effect=spy_iterparse): - R.Reader(root_handlers={}, type_handlers={}).read(DOC) - self.assertEqual(len(roots_seen), 1) - self.assertEqual(len(roots_seen[0]), 0) - - roots_seen.clear() - max_children = 0 - count = 1000 - large_xml = ( - b"" - + b"".join(f''.encode("ascii") - for i in range(count)) - + b"" - ) - reader = R.Reader(root_handlers={}, type_handlers={}) - with mock.patch.object(ET, "iterparse", side_effect=spy_iterparse): - tag, _, items = reader.read(large_xml) - self.assertEqual(tag, "CLargeRoot") - self.assertEqual(len(items), count) - self.assertEqual([item["idx"] for item in items], list(range(count))) - self.assertEqual(reader.stats["list"], 1) - self.assertEqual(len(roots_seen[0]), 0) - self.assertLess(max_children, count) - - -class Dispatch(unittest.TestCase): - def test_type_handler(self): - calls = [] - - def thing(el, reader): - calls.append(el.tag) - generic = reader.convert(el, use_type_handler=False) - return ("thing", generic["size"]) - - reader = R.Reader(root_handlers={}, type_handlers={"CThing": thing}) - value = reader.read(DOC)[2] - self.assertEqual(value["items"], [("thing", 2), None, {"size": 3}]) - self.assertEqual(calls, ["Item"]) - self.assertEqual(reader.stats["type handler"], 1) - - def test_type_handler_does_not_double_count_types_or_extra_attributes(self): - def thing(el, reader): - generic = reader.convert(el, use_type_handler=False) - return ("thing", generic["size"]) - - reader = R.Reader(root_handlers={}, type_handlers={"CThing": thing}) - _, _, value = reader.read(b'') - self.assertEqual(value, [{"$value": ("thing", 2), "@name": "first"}]) - self.assertEqual(reader.types, {"CThing": 1}) - self.assertEqual(reader.stats["type handler"], 1) - self.assertEqual(reader.stats["extra attributes"], 1) - self.assertEqual(reader.stats["object"], 1) - - direct_reader = R.Reader(root_handlers={}, type_handlers={"CThing": thing}) - direct_val = direct_reader.convert( - ET.fromstring(b''), - use_type_handler=False, - ) - self.assertEqual(direct_val, {"$type": "CThing", "size": 5, "@name": "direct"}) - self.assertEqual(direct_reader.types, {"CThing": 1}) - self.assertEqual(direct_reader.stats["type handler"], 0) - self.assertEqual(direct_reader.stats["extra attributes"], 1) - self.assertEqual(direct_reader.stats["object"], 1) - - def test_streaming_parity_on_typed_null_and_attribute_roots(self): - def thing(el, reader): - generic = reader.convert(el, use_type_handler=False) - return ("thing", generic["size"]) - - cases = ( - (b'', {}), - (b'', {}), - (b'', {}), - (b'', {"CThing": thing}), - (b'', {}), - (b'1 2', {}), - (b'', {}), - (b'', {}), - (b'', {"CThing": lambda el, r: ("vec", r.convert(el, use_type_handler=False))}), - ) - for raw, handlers in cases: - with self.subTest(raw=raw): - whole_reader = R.Reader(root_handlers={}, type_handlers=handlers) - stream_reader = R.Reader(root_handlers={}, type_handlers=handlers) - whole_val = whole_reader.convert(ET.fromstring(raw)) - _, _, stream_val = stream_reader.read(raw) - self.assertEqual(stream_val, whole_val) - self.assertEqual(stream_reader.stats, whole_reader.stats) - self.assertEqual(stream_reader.types, whole_reader.types) - - def test_root_handler_gets_the_whole_root(self): - def root(el, reader): - return sorted({child.tag for child in el}) - - reader = R.Reader(root_handlers={"CSyntheticRoot": root}, type_handlers={}) - tag, _, value = reader.read(DOC) - self.assertEqual(tag, "CSyntheticRoot") - self.assertIn("lookup", value) - self.assertEqual(reader.stats["root handler"], 1) - - def test_decorators_register(self): - saved_r, saved_t = dict(R.ROOT_HANDLERS), dict(R.TYPE_HANDLERS) - try: - @R.register_root("CSyntheticRoot") - def _root(el, reader): - return "root" - - @R.register_type("CThing") - def _thing(el, reader): - return "thing" - - self.assertEqual(R.Reader().read(DOC)[2], "root") - self.assertEqual(R.Reader().read(b'')[2], ["thing"]) - finally: - R.ROOT_HANDLERS.clear(); R.ROOT_HANDLERS.update(saved_r) - R.TYPE_HANDLERS.clear(); R.TYPE_HANDLERS.update(saved_t) - - -class Run(unittest.TestCase): - BAD_DOCUMENTS = ( - ("truncated array", b'1 2 3 4'), - ("unknown encoding", b''), - ("unsupported encoding", b''), - ) - - def setUp(self): - self.tmp = tempfile.TemporaryDirectory() - self.addCleanup(self.tmp.cleanup) - self.dir = os.path.join(self.tmp.name, "xml") - os.makedirs(self.dir) - with open(os.path.join(self.dir, "a.xml"), "wb") as f: - f.write(DOC) - with open(os.path.join(self.dir, "b.xml"), "wb") as f: - f.write(b'') # truncated, as a tail-cut carve can be - with open(os.path.join(self.dir, "c.xml"), "wb") as f: - f.write(b'') - - def test_summary_counts(self): - s = R.run([self.dir], reader=R.Reader(root_handlers={}, type_handlers={})) - self.assertEqual((s["documents"], s["roots"], s["not_well_formed"]), (2, 2, 1)) - self.assertEqual(s["per_root_documents"], {"CSyntheticRoot": 1, "COther": 1}) - self.assertEqual(s["type_classes"], 1) - - def test_root_filter(self): - s = R.run([self.dir], root_filter="COther", reader=R.Reader(root_handlers={}, type_handlers={})) - self.assertEqual(s["documents"], 1) - - def test_conversion_and_encoding_errors_do_not_abort_batch(self): - bad = os.path.join(self.tmp.name, "bad.xml") - good = os.path.join(self.dir, "c.xml") - for name, data in self.BAD_DOCUMENTS: - with self.subTest(name=name): - with open(bad, "wb") as f: - f.write(data) - s = R.run([bad, good], reader=R.Reader(root_handlers={}, type_handlers={})) - self.assertEqual((s["documents"], s["roots"], s["not_well_formed"]), (1, 1, 1)) - self.assertEqual(s["per_root_documents"], {"COther": 1}) - self.assertEqual(sum(s["parse_errors"].values()), 1) - - def test_cli_continues_after_conversion_and_encoding_errors(self): - bad = os.path.join(self.tmp.name, "bad.xml") - good = os.path.join(self.dir, "c.xml") - for name, data in self.BAD_DOCUMENTS: - with self.subTest(name=name): - with open(bad, "wb") as f: - f.write(data) - out = os.path.join(self.tmp.name, name) - r = subprocess.run([sys.executable, "-I", os.path.join(TOOLS, "gamedata_reader.py"), - bad, good, "--out", out], capture_output=True, text=True, timeout=10) - self.assertEqual(r.returncode, 0, r.stderr) - self.assertIn("1 documents read, 1 roots, 1 not well-formed", r.stdout) - self.assertNotIn("Traceback", r.stderr) - files = os.listdir(out) - self.assertEqual(len(files), 1) - self.assertTrue(files[0].startswith("COther_")) - with open(os.path.join(out, files[0]), encoding="utf-8") as f: - self.assertEqual(json.load(f), {"x": 2}) - - def test_cli_prints_counts_and_writes_json(self): - out = os.path.join(self.tmp.name, "json", "nested") - r = subprocess.run([sys.executable, "-I", os.path.join(TOOLS, "gamedata_reader.py"), self.dir, "--out", out], - capture_output=True, text=True) - self.assertEqual(r.returncode, 0, r.stderr) - self.assertIn("2 documents read, 2 roots, 1 not well-formed", r.stdout) - self.assertNotIn("synthetic_name", r.stdout) # counts only, no values - files = sorted(os.listdir(out)) - self.assertEqual(len(files), 2) - with open(os.path.join(out, next(f for f in files if f.startswith("CSyntheticRoot"))), encoding="utf-8") as f: - self.assertEqual(json.load(f)["label"], "synthetic_name") - - def test_exports_all_documents_with_the_same_basename(self): - targets = [] - for index in range(1, 4): - folder = os.path.join(self.tmp.name, str(index)) - os.mkdir(folder) - path = os.path.join(folder, "same.xml") - with open(path, "wb") as f: - f.write(f''.encode("ascii")) - targets.append(path) - out = os.path.join(self.tmp.name, "json") - for _ in range(2): - summary = R.run(targets, out_dir=out) - self.assertEqual(summary["documents"], 3) - files = sorted(os.listdir(out)) - self.assertEqual(len(files), 3) - values = [] - for name in files: - with open(os.path.join(out, name), encoding="utf-8") as f: - values.append(json.load(f)["x"]) - self.assertEqual(sorted(values), [1, 2, 3]) - def test_cli_fails_when_no_document_can_be_read(self): - # A corpus with a truncated tail still reads its other documents and exits 0 (the test above); a run that - # read nothing because every document was broken must not look like an empty read. - with tempfile.TemporaryDirectory() as d: - bad = os.path.join(d, "bad.xml") - with open(bad, "wb") as f: - f.write(b'') # truncated, and the only document - r = subprocess.run([sys.executable, "-I", os.path.join(TOOLS, "gamedata_reader.py"), bad], - capture_output=True, text=True) - self.assertEqual(r.returncode, 1, r.stderr) - self.assertIn("no document could be read", r.stderr) - self.assertNotIn("Traceback", r.stderr) - - def test_cli_missing_target(self): - r = subprocess.run([sys.executable, "-I", os.path.join(TOOLS, "gamedata_reader.py"), - os.path.join(self.tmp.name, "nope")], capture_output=True, text=True) - self.assertEqual(r.returncode, 2) - self.assertIn("does not exist", r.stderr) - self.assertNotIn("Traceback", r.stderr) - - def _cli(self, *args): - return subprocess.run([sys.executable, "-I", os.path.join(TOOLS, "gamedata_reader.py"), *args], - capture_output=True, text=True) - - def test_cli_bad_index_json_is_one_error_line(self): - for name, text in (("notjson", "{bad"), ("wrongshape", "[]"), ("nofiles", "{}")): - with self.subTest(name): - d = os.path.join(self.tmp.name, name) - os.makedirs(d) - with open(os.path.join(d, "index.json"), "w", encoding="utf-8", newline="\n") as f: - f.write(text) - r = self._cli(d) - self.assertEqual(r.returncode, 2, r.stderr) - self.assertNotIn("Traceback", r.stderr) - self.assertIn("ERROR: cannot read", r.stderr) - self.assertEqual(len(r.stderr.strip().splitlines()), 1, r.stderr) - - def test_cli_out_that_is_a_file_is_refused(self): - xml = os.path.join(self.tmp.name, "a.xml") - out = os.path.join(self.tmp.name, "afile") - for path, data in ((xml, b""), (out, b"x")): - with open(path, "wb") as f: - f.write(data) - r = self._cli(xml, "--out", out) - self.assertEqual(r.returncode, 2, r.stderr) - self.assertNotIn("Traceback", r.stderr) - self.assertIn("not a directory", r.stderr) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/test_gamedata_sps1.py b/tests/test_gamedata_sps1.py deleted file mode 100644 index 09b515793..000000000 --- a/tests/test_gamedata_sps1.py +++ /dev/null @@ -1,307 +0,0 @@ -"""gamedata_sps1.py must decode the SPS1 shader-preset table without game data. - - python -I tests/test_gamedata_sps1.py - -Every fixture is synthetic: SPS1 blobs with length-prefixed NUL-terminated preset/effect pairs and render buckets, -multi-stream 64 KiB carve directories, and minimal SGD5 databases for cross-reference and hash-lookup checks. -""" -import json -import os -import struct -import subprocess -import sys -import tempfile -import unittest -from unittest import mock - -ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) -TOOLS = os.path.join(ROOT, "tools") -TOOL = os.path.join(TOOLS, "gamedata_sps1.py") -sys.path.insert(0, TOOLS) - -import gamedata_sps1 # noqa: E402 -from hashdict import joaat # noqa: E402 -import sgd5_effects # noqa: E402 - - -def sps1_payload(entries: list[tuple[str, str, int]], count: int | None = None) -> bytes: - """Build a synthetic SPS1 payload from (preset, effect, render_bucket) tuples.""" - n = len(entries) if count is None else count - buf = bytearray(b"SPS1" + struct.pack(" bytes: - """Minimal valid SGD5 effect record (0 lists/passes, 2-byte NUL string pool).""" - nbytes = name.encode("ascii") + b"\x00" - out = bytearray([len(nbytes)]) + nbytes - out += bytes(4) # opaque u32 - out += bytes(6 * 4) # 6 empty stage ordinal lists - out += bytes(80) # fixed block - out += bytes(4 * 4) # 4 empty subtables (16/24/68/36 stride) - out += bytes(4) # 0 technique rows - out += bytes(4) # 0 pass rows - out += bytes(4) # 0 post-pass u32s - out += struct.pack("') - self.add(blob, [blob[:65536], blob[65536:]]) - self.add(b"MHIU" + bytes(40)) - self.finish() - - raw_bin = os.path.join(self.root, "only_sps1.bin") - with open(raw_bin, "wb") as f: - f.write(blob) - - for target in (self.carve, raw_bin): - loaded = gamedata_sps1.read_payloads(target) - self.assertEqual(len(loaded), 1) - self.assertEqual(loaded[0]["table"]["records"], 400) - self.assertEqual(loaded[0]["size"], len(blob)) - self.assertEqual(gamedata_sps1.read_payloads(self.carve)[0]["chunks"], 2) - - def test_exact_64k_sps1_does_not_absorb_following_opaque_row(self): - # 8B header + 327 * 200B + 128B == 65,536B exact, followed by an opaque binary row. - entries_64k = [(f"p{i:03d}_" + ("x" * 180) + ".sps", "fx_std", i % 7) for i in range(327)] - entries_64k.append(("p_end_" + ("y" * 107) + ".sps", "fx_std", 0)) - exact_64k = sps1_payload(entries_64k) - self.assertEqual(len(exact_64k), 65536) - - self.add(exact_64k) - self.add(b"\x01\x02\x03\x04" * 16) - self.finish() - loaded = gamedata_sps1.read_payloads(self.carve) - self.assertEqual(len(loaded), 1) - self.assertEqual(loaded[0]["size"], 65536) - self.assertEqual(loaded[0]["chunks"], 1) - self.assertEqual(loaded[0]["table"]["records"], 328) - - # Also verify an exact 131,072B two-chunk table stops after 2 chunks instead of absorbing a 3rd opaque row. - self.rows.clear() - entries_128k = [(f"p{i:03d}_" + ("x" * 180) + ".sps", "fx_std", i % 7) for i in range(655)] - entries_128k.append(("p_end_" + ("z" * 43) + ".sps", "fx_std", 0)) - exact_128k = sps1_payload(entries_128k) - self.assertEqual(len(exact_128k), 131072) - self.add(exact_128k, [exact_128k[:65536], exact_128k[65536:]]) - self.add(b"\x05\x06\x07\x08" * 16) - self.finish() - loaded2 = gamedata_sps1.read_payloads(self.carve) - self.assertEqual(len(loaded2), 1) - self.assertEqual(loaded2[0]["size"], 131072) - self.assertEqual(loaded2[0]["chunks"], 2) - self.assertEqual(loaded2[0]["table"]["records"], 656) - - def test_cross_references_sgd5_and_matches_hashes_without_leaking_names(self): - entries = [ - ("alpha_fx.sps", "alpha_fx", 0), - ("alias_to_alpha.sps", "alpha_fx", 1), - ("beta_only_alias.sps", "beta_fx", 4), - ("gamma_missing.sps", "missing_fx", 2), - ] - blob = sps1_payload(entries) - self.add(blob) - self.finish() - - archive_bytes, layouts = synthetic_sgd5_archive(["alpha_fx", "beta_fx"], ["gamma_missing"]) - shaders_path = os.path.join(self.root, "synthetic_shaders.rpf") - with open(shaders_path, "wb") as f: - f.write(archive_bytes) - - with mock.patch.object(sgd5_effects, "DATABASES", layouts): - payloads = gamedata_sps1.read_payloads(self.carve) - xref = gamedata_sps1.cross_reference_sgd5(payloads, shaders_path) - self.assertEqual(xref["sgd5_db0_effects"], 2) - self.assertEqual(xref["sgd5_db1_effects"], 1) - self.assertEqual(xref["records_resolved_db0"], 3) - self.assertEqual(xref["records_resolved_db1"], 0) - self.assertEqual(xref["records_unresolved"], 1) - self.assertEqual(xref["distinct_effects_resolved_db0"], 2) - self.assertEqual(xref["preset_stems_in_sgd5"], 2) # alpha_fx, gamma_missing - self.assertEqual(xref["sps1_only_preset_stems"], 2) # alias_to_alpha, beta_only_alias - - out_json = os.path.join(self.root, "reports", "sps1.json") - # Query beta_only_alias via CLI? Use in-process main after patching DATABASES via test directly; - # also run subprocess CLI without --shaders for --preset-hash + --json. - beta_hash = f"{joaat('beta_only_alias'):08x}" - proc = subprocess.run( - [sys.executable, "-I", TOOL, self.carve, "--preset-hash", beta_hash, "--json", out_json], - cwd=self.root, capture_output=True, text=True, encoding="utf-8", errors="replace", - ) - self.assertEqual(proc.returncode, 0, proc.stdout + proc.stderr) - with open(out_json, "rb") as f: - raw = f.read() - self.assertIn(b"\n", raw) - self.assertNotIn(b"\r\n", raw) - # No raw preset or effect string appears anywhere in JSON or stdout. - for secret in ("alpha_fx", "alias_to_alpha", "beta_only_alias", "beta_fx", "gamma_missing"): - self.assertNotIn(secret, proc.stdout) - self.assertNotIn(secret.encode("ascii"), raw) - report = json.loads(raw.decode("utf-8")) - self.assertEqual(len(report["hash_matches"]), 1) - m = report["hash_matches"][0] - self.assertEqual((m["record_index"], m["render_bucket"], m["aliased"]), (2, 4, True)) - self.assertEqual(m["preset_stem_hash"], f"{joaat('beta_only_alias'):08X}") - self.assertEqual(m["effect_hash"], f"{joaat('beta_fx'):08X}") - - def test_missing_input_path_is_a_usage_error_naming_it(self): - """BUILD-1046: a path that does not exist is exit 2 and one ERROR line, not a failed run.""" - missing = os.path.join(self.root, "no-such-input") - self.assertFalse(os.path.exists(missing)) - for cmd in ([sys.executable, "-I", TOOL, missing], - [sys.executable, "-I", TOOL, self.carve, "--shaders", missing]): - with self.subTest(cmd=cmd[3:]): - p = subprocess.run(cmd, cwd=self.root, capture_output=True, text=True, - encoding="utf-8", errors="replace") - self.assertEqual(p.returncode, 2, p.stdout + p.stderr) - self.assertNotIn("Traceback", p.stderr) - lines = p.stderr.strip().splitlines() - self.assertEqual(len(lines), 1, p.stderr) - self.assertTrue(lines[0].startswith("ERROR:"), p.stderr) - self.assertIn(missing, lines[0]) - - def test_refuses_json_colliding_with_inputs_and_rejects_bad_archive(self): - self.add(sps1_payload([("a.sps", "a", 0)])) - self.finish() - shaders_file = os.path.join(self.root, "shaders.rpf") - with open(shaders_file, "wb") as f: - f.write(b"dummy") - out_dir = os.path.join(self.root, "existing_dir") - os.makedirs(out_dir) - - for target, shaders, out in ( - (self.carve, None, os.path.join(self.carve, "index.json")), - (self.carve, None, os.path.join(self.carve, f"{self.rows[0]['off']:012x}.bin")), - (self.carve, shaders_file, shaders_file), - (self.carve, None, out_dir), - ): - cmd = [sys.executable, "-I", TOOL, target, "--json", out] - if shaders: - cmd += ["--shaders", shaders] - p = subprocess.run(cmd, cwd=self.root, capture_output=True, text=True, encoding="utf-8", errors="replace") - self.assertEqual(p.returncode, 1, p.stdout + p.stderr) - self.assertIn("error:", p.stderr) - self.assertNotIn("Traceback", p.stderr) - - bad_file = os.path.join(self.root, "not_rpf.bin") - with open(bad_file, "wb") as f: - f.write(b"NOPE1234") - p = subprocess.run([sys.executable, "-I", TOOL, bad_file], cwd=self.root, - capture_output=True, text=True, encoding="utf-8", errors="replace") - self.assertEqual(p.returncode, 1) - self.assertIn("neither an SPS1 payload nor an RPF9 archive", p.stderr) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/test_gamedata_xml.py b/tests/test_gamedata_xml.py deleted file mode 100644 index 3f850260a..000000000 --- a/tests/test_gamedata_xml.py +++ /dev/null @@ -1,403 +0,0 @@ -"""gamedata_xml.py must catalog synthetic XML without reading any game file. - - python -I tests/test_gamedata_xml.py - -Fixtures are hand-written documents: nested elements, attributes, macro and platform references, -an include-like manifest, a tail-only fragment and a malformed document. No game data is used. -""" -import contextlib -import csv -import io -import json -import os -import subprocess -import sys -import tempfile -import unittest -from unittest import mock - -ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) -TOOL = os.path.join(ROOT, "tools", "gamedata_xml.py") -sys.path.insert(0, os.path.join(ROOT, "tools")) -import gamedata_xml as g # noqa: E402 - -ALPHA = ( - b'\xef\xbb\xbf\n' - b'\n' - b' fixture\n' - b' \n' - b' $(common)/movies/fixture.bk2' - b'bk2\n' - b' platform:/levels/fixture.xml' - b'xml\n' - b' $(target)/data/fixture.xml' - b'xml\n' - b' platform:/data/fixture.xml' - b'xml\n' - b' \n' - b' $(root)/fixture' - b'\n' - b' \n' - b'' -) -BETA = ( - b'' - b'0 1' -) -TAIL = b'\n' -BAD = b'' -ROOTLESS = b'plain text, not an XML document\n' - - -class GamedataXmlTest(unittest.TestCase): - def setUp(self): - self.tmp = tempfile.TemporaryDirectory() - self.root = self.tmp.name - - def tearDown(self): - self.tmp.cleanup() - - def write(self, name, data): - path = os.path.join(self.root, name) - with open(path, "wb") as f: - f.write(data) - return path - - def run_tool(self, *args): - return subprocess.run([sys.executable, "-I", TOOL, *args], cwd=self.root, - capture_output=True, text=True, encoding="utf-8", errors="replace") - - def test_files_catalog_roots_elements_references_and_values(self): - alpha = self.write("alpha.xml", ALPHA) - beta = self.write("beta.xml", BETA) - out = os.path.join(self.root, "catalog.json") - csv_path = os.path.join(self.root, "catalog.csv") - p = self.run_tool(alpha, beta, "--json", out, "--csv", csv_path, "--check") - self.assertEqual(p.returncode, 0, p.stdout + p.stderr) - - with open(out, encoding="utf-8") as f: - data = json.load(f) - s = data["summary"] - self.assertEqual(s["documents"], 2) - self.assertEqual(s["well_formed"], 2) - self.assertEqual(s["fragments"], 0) - self.assertEqual(s["truncated"], 0) - self.assertEqual(s["malformed"], 0) - self.assertEqual(s["root_count"], 2) - self.assertEqual(s["elements"], 21) - self.assertEqual(s["max_depth"], 4) - self.assertEqual(s["comments"], 1) - self.assertEqual(s["comments_header"], 1) - self.assertEqual(s["references"], {"$(common)": 1, "$(root)": 1, "$(target)": 1}) - self.assertEqual(s["platform"], {"levels": 1, "other": 1}) - self.assertEqual(s["platform_total"], 2) - self.assertEqual(s["filename"], 4) - self.assertEqual(s["include_like"]["fileList"], 1) - self.assertEqual(s["include_like"]["includedSets"], 1) - self.assertEqual(s["include_like"]["loadPath"], 1) - self.assertEqual(s["xi_include"], 0) - - rows = {row["source"]: row for row in data["rows"]} - first = rows["alpha.xml"] - self.assertEqual(first["root"], "CDataFileMgr__ContentChangeSetDef") - self.assertEqual(first["category"], "mount / content manifests") - self.assertEqual(first["element_count"], 18) - self.assertEqual(first["max_depth"], 4) - self.assertEqual(first["attributes"], ["ref", "type", "version"]) - self.assertEqual(first["refs"], {"$(common)": 1, "$(root)": 1, "$(target)": 1}) - self.assertEqual(first["platform"], {"levels": 1, "other": 1}) - self.assertEqual(first["filename"], 4) - self.assertTrue(first["header"]) - self.assertTrue(first["well_formed"]) - self.assertFalse(first["fragment"]) - - second = rows["beta.xml"] - self.assertEqual(second["root"], "timecycle_modifier_data") - self.assertEqual(second["category"], "time, weather, sky, water") - self.assertEqual(second["element_count"], 3) - self.assertEqual(second["max_depth"], 3) - self.assertEqual(second["attributes"], ["name", "version"]) - self.assertFalse(second["header"]) - - root = data["roots"]["CDataFileMgr__ContentChangeSetDef"] - self.assertEqual(root["files"], 1) - self.assertEqual(root["category"], "mount / content manifests") - self.assertEqual(root["elements"], 18) - self.assertEqual(root["element_names"]["filename"], 4) - self.assertEqual(root["element_names"]["Item"], 5) - self.assertEqual(root["attributes"]["type"], 4) - self.assertEqual(root["attributes"]["ref"], 1) - self.assertEqual(root["refs"], {"$(common)": 1, "$(root)": 1, "$(target)": 1}) - self.assertEqual(root["platform"], {"levels": 1, "other": 1}) - self.assertEqual(root["filename"], 4) - - with open(csv_path, newline="", encoding="utf-8") as f: - csv_rows = list(csv.DictReader(f)) - self.assertEqual(len(csv_rows), 2) - self.assertEqual(csv_rows[0]["root"], "CDataFileMgr__ContentChangeSetDef") - self.assertEqual(csv_rows[0]["refs"], "$(common)=1;$(root)=1;$(target)=1") - self.assertEqual(csv_rows[0]["well_formed"], "true") - - # Values, text and comments must not leak into the catalog; names and counts are fine. - with open(out, encoding="utf-8") as f: - blob = f.read() - for value in ("fixture.bk2", "synthetic note", "synthetic_set", "0 1", "fixture.xml"): - self.assertNotIn(value, blob) - - def test_well_formed_roots_group_by_namespace_not_prefix(self): - bare = self.write("bare.xml", b"") - default = self.write("default.xml", b'') - prefix = self.write("prefix.xml", b'') - out = os.path.join(self.root, "catalog.json") - p = self.run_tool(bare, default, prefix, "--json", out, "--check") - self.assertEqual(p.returncode, 0, p.stdout + p.stderr) - with open(out, encoding="utf-8") as f: - report = json.load(f) - qualified = "{urn:example}CTuningFile" - self.assertEqual(set(report["roots"]), {"CTuningFile", qualified}) - self.assertEqual(report["roots"][qualified]["files"], 2) - self.assertEqual(report["roots"][qualified]["element_names"], {qualified: 2}) - self.assertEqual(report["roots"][qualified]["category"], "uncatalogued") - self.assertEqual(report["roots"]["CTuningFile"]["files"], 1) - self.assertEqual(report["summary"]["catalog_roots"], 1) - - def test_counts_tail_references_across_parser_buffer_boundary(self): - start = b"" - close = b"" - tail = b"$(common)/x" - short = self.write("short.xml", start + b"x" + close + tail) - padding = b"x" * (16384 - len(start) - len(close)) - long = self.write("long.xml", start + padding + close + tail) - out = os.path.join(self.root, "catalog.json") - p = self.run_tool(short, long, "--check", "--json", out) - self.assertEqual(p.returncode, 0, p.stdout + p.stderr) - - with open(out, encoding="utf-8") as f: - data = json.load(f) - rows = {row["source"]: row for row in data["rows"]} - self.assertEqual(rows["short.xml"]["refs"], {"$(common)": 1}) - self.assertEqual(rows["long.xml"]["refs"], {"$(common)": 1}) - - def test_check_reports_tail_only_fragment_and_malformed(self): - tail = self.write("tail.xml", TAIL) - p = self.run_tool(tail, "--check") - self.assertEqual(p.returncode, 0, p.stdout + p.stderr) - self.assertIn("1 truncated at the start", p.stdout) - self.assertIn("0 rootless fragments", p.stdout) - self.assertIn("0 malformed", p.stdout) - self.assertIn("TailRoot", p.stdout) - - rootless = self.write("rootless.xml", ROOTLESS) - p = self.run_tool(rootless, "--check") - self.assertEqual(p.returncode, 0, p.stdout + p.stderr) - self.assertIn("1 rootless fragment", p.stdout) - - bad = self.write("bad.xml", BAD) - p = self.run_tool(bad, "--check") - self.assertEqual(p.returncode, 1, p.stdout + p.stderr) - self.assertIn("1 malformed", p.stdout) - self.assertIn("line 1", p.stdout) - - # An end-truncated file that starts at and cuts off right after a closed child - # must keep root "COther" and report malformed (not tail_only under bogus root "x"). - cut = self.write("cut.xml", b"1") - out = os.path.join(self.root, "cut.json") - p = self.run_tool(cut, "--check", "--json", out) - self.assertEqual(p.returncode, 1, p.stdout + p.stderr) - with open(out, encoding="utf-8") as f: - row = json.load(f)["rows"][0] - self.assertEqual(row["root"], "COther") - self.assertFalse(row["tail_only"]) - self.assertFalse(row["truncated"]) - self.assertTrue(row["malformed"]) - - def test_check_crossed_tags(self): - cases = ( - (b"", "R"), - (b'', "R"), - (b']]>', "n:R"), - ) - for payload, root in cases: - with self.subTest(payload=payload): - doc = self.write("crossed.xml", payload) - p = self.run_tool(doc, "--check") - self.assertEqual(p.returncode, 1, p.stdout + p.stderr) - self.assertIn("malformed " + root + " @", p.stdout) - self.assertIn("0 truncated at the start", p.stdout) - - def test_check_crossed_text_in_missing_comment_or_cdata_prefix(self): - for opener, suffix in ((b""), (b"")): - payload = b"" + suffix + b"" - with self.subTest(opener=opener): - # Establish that these are tails of a well-formed document. - import xml.etree.ElementTree as ET - ET.fromstring(b"" + opener + payload) - doc = self.write("lexical_tail.xml", payload) - p = self.run_tool(doc, "--check") - self.assertEqual(p.returncode, 0, p.stdout + p.stderr) - self.assertIn("1 truncated at the start", p.stdout) - self.assertIn("truncated R @", p.stdout) - # A stray terminator must not hide malformed text after it. - broken = self.write("lexical_broken.xml", payload[:-4] + b"") - p = self.run_tool(broken, "--check") - self.assertEqual(p.returncode, 1, p.stdout + p.stderr) - - def test_check_reports_unknown_encoding_as_malformed(self): - unknown = self.write("unknown.xml", b'') - valid = self.write("valid.xml", b"") - p = self.run_tool(unknown, valid, "--check") - self.assertEqual(p.returncode, 1, p.stdout + p.stderr) - self.assertNotIn("Traceback", p.stderr) - self.assertIn("1 well-formed", p.stdout) - self.assertIn("1 malformed", p.stdout) - self.assertIn("not-a-charset", p.stdout) - - def test_comments_in_a_document_that_does_not_parse_are_counted(self): - # The fallback must respect the context of each delimiter after the parser stops. - cases = {"open.xml": (b"", 2), - "tail.xml": (b"
", 2), - "cdata.xml": (b"]]>", 2), - "comment-in-pi.xml": (b"
", 1), - "unfinished-comment.xml": (b"]]>") - out = os.path.join(self.root, "catalog.json") - p = self.run_tool(doc, "--json", out) - self.assertEqual(p.returncode, 0, p.stderr) - with open(out, encoding="utf-8") as f: - report = json.load(f) - self.assertTrue(report["rows"][0]["well_formed"]) - self.assertEqual(report["rows"][0]["comments"], 2) - self.assertEqual(report["summary"]["comments"], 2) - - def test_carve_directory_joins_chunks_and_marks_fragment(self): - carve = os.path.join(self.root, "carve") - os.makedirs(carve) - doc = b'\n' + b"" * 20 + b"" - split = doc.index(b" None: - carve = os.path.join(self.root, "headerless") - os.makedirs(carve) - rows = [] - for off, data in ((0x1000, b""), (0x2000, b"")): - with open(os.path.join(carve, f"{off:012x}.bin"), "wb") as f: - f.write(data) - rows.append({"off": off, "stored": len(data), "size": len(data), - "head": data[:16].hex(), "pre": ""}) - with open(os.path.join(carve, "index.json"), "w", encoding="utf-8", newline="\n") as f: - json.dump({"files": rows}, f) - - out = os.path.join(self.root, "headerless.json") - result = self.run_tool(carve, "--json", out, "--check") - self.assertEqual(result.returncode, 0, result.stdout + result.stderr) - with open(out, encoding="utf-8") as f: - report = json.load(f) - self.assertEqual([row["root"] for row in report["rows"]], ["Plain", "Empty"]) - for row in report["rows"]: - with self.subTest(root=row["root"]): - self.assertTrue(row["well_formed"]) - self.assertTrue(row["complete"]) - self.assertFalse(row["header"]) - self.assertFalse(row["tail_only"]) - self.assertFalse(row["fragment"]) - self.assertEqual(report["summary"]["tail_only"], 0) - self.assertEqual(report["summary"]["fragments"], 0) - - def test_a_folder_that_cannot_be_listed_fails_the_scan(self): - def fake_walk(root, onerror=None): - self.assertIsNotNone(onerror, "os.walk needs onerror, or an unlistable folder is skipped") - onerror(PermissionError(13, "permission denied", os.path.join(root, "blocked"))) - return iter(()) - - err = io.StringIO() - with mock.patch.object(g.os, "walk", side_effect=fake_walk), \ - mock.patch.object(sys, "argv", ["gamedata_xml.py", self.root]), \ - contextlib.redirect_stderr(err), contextlib.redirect_stdout(io.StringIO()): - rc = g.main() - self.assertEqual(rc, 2) - self.assertIn("permission denied", err.getvalue()) - - @unittest.skipUnless(os.name == "posix" and getattr(os, "geteuid", lambda: 0)() != 0, - "needs a POSIX filesystem and a non-root user to make a folder unlistable") - def test_a_real_unlistable_folder_fails_the_scan(self): - blocked = os.path.join(self.root, "blocked") - os.makedirs(blocked) - os.chmod(blocked, 0) - err = io.StringIO() - try: - with mock.patch.object(sys, "argv", ["gamedata_xml.py", self.root]), \ - contextlib.redirect_stderr(err), contextlib.redirect_stdout(io.StringIO()): - rc = g.main() - finally: - os.chmod(blocked, 0o755) - self.assertEqual(rc, 2) - self.assertIn("blocked", err.getvalue()) - - def test_unwritable_csv_or_json_is_one_error_line(self): - doc = self.write("alpha.xml", ALPHA) - blocker = self.write("blocker", b"x") - for flag, name in (("--csv", "out.csv"), ("--json", "out.json")): - with self.subTest(flag=flag): - out = os.path.join(blocker, name) - p = self.run_tool(doc, flag, out) - self.assertEqual(p.returncode, 2, p.stdout + p.stderr) - self.assertIn("ERROR: cannot write", p.stderr) - self.assertNotIn("Traceback", p.stderr) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/test_gamedata_xml_bad_index.py b/tests/test_gamedata_xml_bad_index.py deleted file mode 100644 index b10707632..000000000 --- a/tests/test_gamedata_xml_bad_index.py +++ /dev/null @@ -1,74 +0,0 @@ -"""Bad carve indexes must give one ERROR line in gamedata_xml.py, never a traceback. - -Run with ``python -I tests/test_gamedata_xml_bad_index.py``. Set ``LEONIDA_GAMEDATA_XML`` -to another copy of the tool to use as a negative control (main's version fails these -tests). All inputs are hand-built; no game data is used. -""" -import json -import os -import pathlib -import subprocess -import sys -import tempfile -import unittest - -ROOT = pathlib.Path(__file__).resolve().parent.parent -TOOL = pathlib.Path(os.environ.get("LEONIDA_GAMEDATA_XML", str(ROOT / "tools" / "gamedata_xml.py"))) -XML = (b'\n' - b'fixture') - - -class BadGamedataXmlIndexTest(unittest.TestCase): - def run_tool(self, carve, extra=None): - argv = [sys.executable, "-I", str(TOOL), str(carve)] - if extra: - argv += extra - return subprocess.run(argv, cwd=ROOT, capture_output=True, text=True, timeout=60) - - def make_carve(self, folder, doc=None, text=None, payload=None): - carve = pathlib.Path(folder) / "x.rpf" - carve.mkdir() - index = carve / "index.json" - if text is not None: - index.write_text(text, encoding="utf-8") - else: - index.write_text(json.dumps(doc), encoding="utf-8") - if payload is not None: - (carve / "000000000000.bin").write_bytes(payload) - return carve - - def assert_one_error(self, result): - self.assertNotIn("Traceback", result.stderr, result.stderr) - self.assertEqual(result.returncode, 2, result.stderr) - self.assertEqual(len(result.stderr.strip().splitlines()), 1, result.stderr) - self.assertTrue(result.stderr.startswith("ERROR: cannot read "), result.stderr) - - def test_missing_files_key(self): - with tempfile.TemporaryDirectory() as td: - self.assert_one_error(self.run_tool(self.make_carve(td, {}))) - - def test_row_missing_stored(self): - with tempfile.TemporaryDirectory() as td: - doc = {"files": [{"off": 0, "size": 4}]} - self.assert_one_error(self.run_tool(self.make_carve(td, doc))) - - def test_files_is_a_string(self): - with tempfile.TemporaryDirectory() as td: - self.assert_one_error(self.run_tool(self.make_carve(td, {"files": "oops"}))) - - def test_malformed_json(self): - with tempfile.TemporaryDirectory() as td: - self.assert_one_error(self.run_tool(self.make_carve(td, text="{oops"))) - - def test_valid_carve_still_reports(self): - with tempfile.TemporaryDirectory() as td: - doc = {"files": [{"off": 0, "stored": len(XML), "size": len(XML), "head": XML[:16].hex()}]} - carve = self.make_carve(td, doc, payload=XML) - result = self.run_tool(carve) - self.assertEqual(result.returncode, 0, result.stderr) - self.assertNotIn("Traceback", result.stderr) - self.assertIn("CDataFileMgr__ContentChangeSetDef", result.stdout) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/test_gamedata_xml_report_paths.py b/tests/test_gamedata_xml_report_paths.py deleted file mode 100644 index 3b048d9aa..000000000 --- a/tests/test_gamedata_xml_report_paths.py +++ /dev/null @@ -1,252 +0,0 @@ -"""gamedata_xml.py report paths: create the parent, never overwrite an input, reject a directory. - -Run with ``python -I tests/test_gamedata_xml_report_paths.py``. Set ``LEONIDA_GAMEDATA_XML`` to another -copy of the tool to use as a negative control (main's version tracebacks on a missing folder and a -directory, and overwrites inputs). All inputs are hand-built; no game data is used. -""" -import contextlib -import io -import json -import os -import pathlib -import subprocess -import sys -import tempfile -import unittest -from unittest import mock - -ROOT = pathlib.Path(__file__).resolve().parent.parent -TOOL = pathlib.Path(os.environ.get("LEONIDA_GAMEDATA_XML", str(ROOT / "tools" / "gamedata_xml.py"))) -for folder in (str(ROOT), str(ROOT / "tools")): - if folder not in sys.path: - sys.path.insert(0, folder) -import gamedata_xml - -XML = (b'\n' - b'fixture') - - -class ReportPathTest(unittest.TestCase): - def make_carve(self, folder): - carve = pathlib.Path(folder) / "x.rpf" - carve.mkdir() - (carve / "index.json").write_text(json.dumps({"files": []}), encoding="utf-8") - return carve - - def run_tool(self, *args): - return subprocess.run([sys.executable, "-I", str(TOOL), *map(str, args)], - cwd=ROOT, capture_output=True, text=True, timeout=60) - - def test_missing_json_folder_is_created(self): - with tempfile.TemporaryDirectory() as td: - carve = self.make_carve(td) - out = pathlib.Path(td) / "missing" / "sub" / "gamedata.json" - result = self.run_tool(carve, "--json", out) - self.assertEqual(result.returncode, 0, result.stderr) - self.assertTrue(out.is_file(), result.stderr) - self.assertIn("summary", json.loads(out.read_text(encoding="utf-8"))) - - def test_missing_csv_folder_is_created(self): - with tempfile.TemporaryDirectory() as td: - carve = self.make_carve(td) - out = pathlib.Path(td) / "missing" / "sub" / "gamedata.csv" - result = self.run_tool(carve, "--csv", out) - self.assertEqual(result.returncode, 0, result.stderr) - self.assertTrue(out.is_file(), result.stderr) - self.assertTrue(out.read_text(encoding="utf-8").startswith("source,")) - - def test_json_cannot_overwrite_the_carve_index(self): - with tempfile.TemporaryDirectory() as td: - carve = self.make_carve(td) - index = carve / "index.json" - before = index.read_text(encoding="utf-8") - result = self.run_tool(carve, "--json", index) - self.assertEqual(result.returncode, 2, result.stderr) - self.assertIn("would overwrite the input", result.stderr) - self.assertEqual(index.read_text(encoding="utf-8"), before) - - def test_csv_cannot_overwrite_the_carve_index(self): - with tempfile.TemporaryDirectory() as td: - carve = self.make_carve(td) - index = carve / "index.json" - before = index.read_text(encoding="utf-8") - result = self.run_tool(carve, "--csv", index) - self.assertEqual(result.returncode, 2, result.stderr) - self.assertIn("would overwrite the input", result.stderr) - self.assertEqual(index.read_text(encoding="utf-8"), before) - - def test_json_cannot_overwrite_an_xml_target(self): - with tempfile.TemporaryDirectory() as td: - doc = pathlib.Path(td) / "document.xml" - doc.write_bytes(XML) - before = doc.read_bytes() - result = self.run_tool(doc, "--json", doc) - self.assertEqual(result.returncode, 2, result.stderr) - self.assertIn("would overwrite the input", result.stderr) - self.assertEqual(doc.read_bytes(), before) - - def test_json_cannot_overwrite_a_nested_xml(self): - with tempfile.TemporaryDirectory() as td: - folder = pathlib.Path(td) / "tree" - folder.mkdir() - doc = folder / "nested.xml" - doc.write_bytes(XML) - before = doc.read_bytes() - result = self.run_tool(folder, "--json", doc) - self.assertEqual(result.returncode, 2, result.stderr) - self.assertIn("would overwrite the input", result.stderr) - self.assertEqual(doc.read_bytes(), before) - - def test_csv_cannot_overwrite_a_nested_xml(self): - with tempfile.TemporaryDirectory() as td: - folder = pathlib.Path(td) / "tree" - folder.mkdir() - doc = folder / "nested.xml" - doc.write_bytes(XML) - before = doc.read_bytes() - result = self.run_tool(folder, "--csv", doc) - self.assertEqual(result.returncode, 2, result.stderr) - self.assertIn("would overwrite the input", result.stderr) - self.assertEqual(doc.read_bytes(), before) - - def test_nested_xml_alias_is_refused(self): - with tempfile.TemporaryDirectory() as td: - folder = pathlib.Path(td) / "tree" - folder.mkdir() - (folder / "sub").mkdir() - doc = folder / "nested.xml" - doc.write_bytes(XML) - before = doc.read_bytes() - result = self.run_tool(folder, "--json", folder / "sub" / ".." / "nested.xml") - self.assertEqual(result.returncode, 2, result.stderr) - self.assertIn("would overwrite the input", result.stderr) - self.assertEqual(doc.read_bytes(), before) - - def test_json_cannot_overwrite_a_carve_stream(self): - with tempfile.TemporaryDirectory() as td: - carve = pathlib.Path(td) / "x.rpf" - carve.mkdir() - stream = carve / "000000000010.bin" - stream.write_bytes(b"not really xml") - before = stream.read_bytes() - (carve / "index.json").write_text(json.dumps({"files": [ - {"off": 0x10, "stored": 14, "size": 14, "type": "xml", "head": ""} - ]}), encoding="utf-8") - result = self.run_tool(carve, "--json", stream) - self.assertEqual(result.returncode, 2, result.stderr) - self.assertIn("would overwrite the input", result.stderr) - self.assertEqual(stream.read_bytes(), before) - - def test_report_inside_the_scanned_folder_still_works(self): - with tempfile.TemporaryDirectory() as td: - folder = pathlib.Path(td) / "tree" - folder.mkdir() - (folder / "a.xml").write_bytes(XML) - out = folder / "report.json" - result = self.run_tool(folder, "--json", out) - self.assertEqual(result.returncode, 0, result.stderr) - self.assertTrue(out.is_file(), result.stderr) - - def test_report_path_cannot_be_a_directory(self): - with tempfile.TemporaryDirectory() as td: - carve = self.make_carve(td) - outdir = pathlib.Path(td) / "outdir" - outdir.mkdir() - result = self.run_tool(carve, "--json", outdir) - self.assertEqual(result.returncode, 2, result.stderr) - self.assertIn("is a directory", result.stderr) - - def test_json_and_csv_must_differ(self): - with tempfile.TemporaryDirectory() as td: - carve = self.make_carve(td) - out = pathlib.Path(td) / "report.bin" - result = self.run_tool(carve, "--json", out, "--csv", out) - self.assertEqual(result.returncode, 2, result.stderr) - self.assertIn("must use different paths", result.stderr) - - def test_reports_in_a_writable_folder_still_work(self): - with tempfile.TemporaryDirectory() as td: - carve = self.make_carve(td) - js = pathlib.Path(td) / "report.json" - csv_path = pathlib.Path(td) / "report.csv" - result = self.run_tool(carve, "--json", js, "--csv", csv_path) - self.assertEqual(result.returncode, 0, result.stderr) - self.assertTrue(js.is_file() and csv_path.is_file(), result.stderr) - - -class PrefilterTest(unittest.TestCase): - def make_carve(self, folder): - carve = pathlib.Path(folder) / "x.rpf" - carve.mkdir() - (carve / "index.json").write_text(json.dumps({"files": []}), encoding="utf-8") - return carve - - def run_main(self, *args): - calls = [] - real = gamedata_xml.same_report_path - - def counting(first, second): - calls.append((first, second)) - return real(first, second) - - with mock.patch.object(gamedata_xml, "same_report_path", counting), \ - mock.patch.object(sys, "argv", ["gamedata_xml.py", *map(str, args)]), \ - contextlib.redirect_stdout(io.StringIO()), \ - contextlib.redirect_stderr(io.StringIO()): - try: - code = gamedata_xml.main() - except SystemExit as exc: - return calls, exc.code - return calls, code - - def test_existing_reports_skip_the_per_file_guard(self): - for flag, name in (("--json", "report.json"), ("--csv", "report.csv")): - with self.subTest(flag=flag), tempfile.TemporaryDirectory() as td: - carve = self.make_carve(td) - out = pathlib.Path(td) / name - out.write_text("old report", encoding="utf-8") - calls, code = self.run_main(carve, flag, out) - self.assertEqual(code, 0) - self.assertEqual(calls, []) - self.assertTrue(out.is_file()) - - def test_hard_link_report_still_calls_the_guard(self): - with tempfile.TemporaryDirectory() as td: - carve = self.make_carve(td) - alias = pathlib.Path(td) / "report.json" - os.link(carve / "index.json", alias) - calls, code = self.run_main(carve, "--json", alias) - self.assertEqual(code, 2) - self.assertGreater(len(calls), 0) - - def test_input_named_report_still_calls_the_guard(self): - with tempfile.TemporaryDirectory() as td: - folder = pathlib.Path(td) / "tree" - folder.mkdir() - doc = folder / "nested.xml" - doc.write_bytes(XML) - before = doc.read_bytes() - calls, code = self.run_main(folder, "--json", doc) - self.assertEqual(code, 2) - self.assertGreater(len(calls), 0) - self.assertEqual(doc.read_bytes(), before) - - def test_symlinked_xml_report_still_calls_the_guard(self): - with tempfile.TemporaryDirectory() as td: - folder = pathlib.Path(td) / "tree" - folder.mkdir() - report = pathlib.Path(td) / "report.json" - report.write_text("old report", encoding="utf-8") - alias = folder / "alias.xml" - try: - alias.symlink_to(report) - except OSError: - self.skipTest("symbolic links unavailable") - calls, code = self.run_main(folder, "--json", report) - self.assertEqual(code, 2) - self.assertGreater(len(calls), 0) - self.assertEqual(report.read_text(encoding="utf-8"), "old report") - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/test_gbuffer_census.py b/tests/test_gbuffer_census.py deleted file mode 100644 index 04eddb8c9..000000000 --- a/tests/test_gbuffer_census.py +++ /dev/null @@ -1,71 +0,0 @@ -"""Hand-built census inputs exercise both denominator and export coverage.""" -import json -from pathlib import Path -import struct -import sys -import tempfile -import unittest - -sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "tools")) -from gbuffer_census import census - -sys.path.insert(0, str(Path(__file__).resolve().parent)) -from test_fssm_unpack import make_dxbc, make_xbch, make_xdat_list - - -class CensusTests(unittest.TestCase): - def test_whole_payload_multiplicity_with_independent_coverage(self): - a = make_xbch(b"FSSM01a") - b = make_xbch(b"FSSM01b") - with tempfile.TemporaryDirectory() as temp: - root = Path(temp) - rows = [] - for i, slots in enumerate(([a], [a, a], [b], [a, b], [], [b"bad"], None)): - name = f"shader{i}.dxbc" - rows.append({"file": name, "stage": "ps", "name": "deferred" if i else "ordinary"}) - if slots is not None: - dxil = make_xdat_list([(13, slot) for slot in slots]) - (root / name).write_bytes(make_dxbc([(b"DXIL", dxil)], digest=bytes([i]) * 16)) - (root / "index.json").write_text(json.dumps(rows), encoding="utf-8", newline="\n") - report = census(root, root, payload_coverage=True) - default = census(root, root) - self.assertEqual(report["all indexed ps"]["payload_coverage"], - {"identified": 3, "distinct_payloads": 2, "ambiguous": 1, - "unavailable": 3, "payloads_by_indexed_entry_count": {1: 1, 2: 1}}) - deferred = report["entry contains deferred (casefold)"]["payload_coverage"] - self.assertEqual(deferred["payloads_by_indexed_entry_count"], {1: 2}) - for key, group in report.items(): - group.pop("payload_coverage") - self.assertEqual(group, default[key]) - - def test_cohorts_and_independent_coverage(self): - with tempfile.TemporaryDirectory() as temp: - root = Path(temp) - rows = [{"file": "PS_DeferredTextured.dxbc", "name": "ordinary", "stage": "ps"}, - {"file": "unavailable.dxbc", "name": "deFerRed", "stage": "ps"}, - {"file": "ignored.dxbc", "name": "Deferred", "stage": "vs"}] - (root / "index.json").write_text(json.dumps(rows), encoding="utf-8", newline="\n") - sig = struct.pack(" int: - return self.base + len(self.buf) - - def label(self, name: str) -> None: - self.labels[name] = self.here() - - def raw(self, text: str) -> None: - self.buf += bytes.fromhex(text) - - def rel(self, text: str, target, size: int = 4) -> None: - """An instruction ending in a displacement to `target` (a label or an RVA), counted from its end.""" - self.raw(text) - self.fixups.append((len(self.buf), size, target)) - self.buf += bytes(size) - - def finish(self) -> bytes: - for pos, size, target in self.fixups: - t = self.labels[target] if isinstance(target, str) else target - self.buf[pos:pos + size] = struct.pack(" None: - """lea r8,[rsp+out]; the id leas; call helper; test eax,eax; js done. iface_id None: mov rdx,rcx.""" - a.raw(f"4C8D4424{out_disp:02X}") # lea r8,[rsp+out] - if iface_id: - a.rel("488D15", GUIDS[iface_id]) # lea rdx,[iid] - a.rel("488D0D", GUIDS[class_id]) # lea rcx,[clsid] - if not iface_id: - a.raw("488BD1") # mov rdx,rcx - a.rel("E8", "helper") - a.raw("85C0") # test eax,eax - a.rel("78", done, 1) # js done - - -def build_code(a: Asm) -> list[tuple[int, int]]: - """The functions; returns their (begin, end) for .pdata.""" - funcs = [] - - def begin(name): - a.label(name) - return a.here() - - def end(start): - funcs.append((start, a.here())) - a.raw("CC" * (-len(a.buf) % 16)) - - s = begin("entry") - a.raw("4883EC28") # sub rsp,28h - a.rel("E8", "thunk1") - a.rel("E8", "thunk2") - a.rel("E8", "stub3") # through an incremental-link style jmp stub - a.raw("4883C428C3") # add rsp,28h; ret - end(s) - - s = begin("helper") - a.raw("33C0C3") # xor eax,eax; ret - end(s) - s = begin("dispatch") - a.raw("FFE0") # jmp rax (the CFG dispatch routine) - end(s) - - # thunk1, CFG form: XThreadingImpl (class id as interface id), slot 12 = XTaskQueueCreate(mode, mode, &queue) - s = begin("thunk1") - a.raw("4883EC38") - query(a, 0x28, THREADING, None, "done1") - a.raw("488B4C2428" "488B01") # mov rcx,[rsp+28h]; mov rax,[rcx] - a.raw("BA01000000" "41B802000000" "4C8D4C2430") # mov edx,1; mov r8d,2; lea r9,[rsp+30h] - a.raw("488B4060") # mov rax,[rax+60h] - a.rel("E8", "dispatch") - a.raw("488B4C2428" "488B01" "488B4010") # Release: slot 2 - a.rel("E8", "dispatch") - a.label("done1") - a.raw("4883C438C3") - end(s) - - # thunk2, call [rax+disp8]: XNetworkingImpl as IXNetworkingImpl2, slot 15 = XNetworkingGetConnectivityHint(&hint) - s = begin("thunk2") - a.raw("53" "4883EC30" "488BD9") # push rbx; sub rsp,30h; mov rbx,rcx - query(a, 0x28, NETWORKING, NETWORKING2, "done2") - a.raw("488B4C2428" "488B01" "488BD3") # mov rcx,[rsp+28h]; mov rax,[rcx]; mov rdx,rbx - a.raw("FF5078") # call [rax+78h] - a.raw("488B4C2428" "488B01" "FF5010") # Release - a.label("done2") - a.raw("4883C4305BC3") - end(s) - - # thunk3, call [r10+disp32] and a stack argument: XPackageImpl as IXPackageImpl3, slot 40 = - # XPackageRegisterPackageInstalled(queue, context, callback, &token) - s = begin("thunk3") - a.raw("4883EC48") - query(a, 0x38, PACKAGE, PACKAGE3, "done3") - a.raw("488B4C2438" "4C8B11") # mov rcx,[rsp+38h]; mov r10,[rcx] - a.raw("33D2" "4533C0" "4533C9") # xor edx,edx; xor r8d,r8d; xor r9d,r9d - a.raw("48C744242000000000") # mov qword ptr [rsp+20h],0 - a.raw("41FF9240010000") # call [r10+140h] - a.raw("488B4C2438" "4C8B11" "41FF5210") # Release through r10 - a.label("done3") - a.raw("4883C448C3") - end(s) - - # thunk4: ids the table doesn't know, slot 5, no arguments; nothing calls it. It calls thunkA first, as the - # library's thunks call the XThreadAssertNotTimeSensitive thunk. - s = begin("thunk4") - a.raw("4883EC38") - a.rel("E8", "thunkA") - query(a, 0x28, UNKNOWN_CLASS, UNKNOWN_IFACE, "done4") - a.raw("488B4C2428" "488B01" "488B4028") # mov rax,[rax+28h] - a.rel("E8", "dispatch") - a.raw("488B4C2428" "488B01" "488B4010") - a.rel("E8", "dispatch") - a.label("done4") - a.raw("4883C438C3") - end(s) - - # thunkA: XThreadingImpl slot 29 = XThreadAssertNotTimeSensitive, the slot load as disp32; only thunk4 calls it. - s = begin("thunkA") - a.raw("4883EC38") - query(a, 0x28, THREADING, THREADING, "doneA") - a.raw("488B4C2428" "488B01" "488B80E8000000") # mov rax,[rax+0E8h] - a.rel("E8", "dispatch") - a.raw("488B4C2428" "488B01" "488B4010") - a.rel("E8", "dispatch") - a.label("doneA") - a.raw("4883C438C3") - end(s) - - # thunkB: XThreadingImpl slot 16 = XTaskQueueDispatch(queue, port, timeout). rdx holds no id, r8 a global (the - # object's cache), and the method pointer reaches rax through r11. - s = begin("thunkB") - a.raw("4883EC38") - a.rel("4C8D05", CACHE_RVA) # lea r8,[cache] - a.rel("488D0D", GUIDS[THREADING]) # lea rcx,[clsid] - a.raw("33D2") # xor edx,edx - a.rel("E8", "helper") - a.raw("85C0") - a.rel("78", "doneB", 1) - a.rel("488B0D", CACHE_RVA) # mov rcx,[cache] - a.raw("488B01" "4C8B9880000000") # mov rax,[rcx]; mov r11,[rax+80h] - a.raw("33D2" "41B801000000" "4183C9FF") # xor edx,edx; mov r8d,1; or r9d,-1 - a.raw("498BC3") # mov rax,r11 - a.rel("E8", "dispatch") - a.rel("488B0D", CACHE_RVA) - a.raw("488B01" "488B4010") # Release - a.rel("E8", "dispatch") - a.label("doneB") - a.raw("4883C438C3") - end(s) - - # thunkC: a helper call whose ids come from a register, not a RIP-relative lea: listed, not followed. - s = begin("thunkC") - a.raw("4883EC38" "4C8D442428" "488BCB" "488BD3") # lea r8,[rsp+28h]; mov rcx,rbx; mov rdx,rbx - a.label("callC") - a.rel("E8", "helper") - a.raw("85C0") - a.rel("78", "doneC", 1) - a.raw("488B4C2428" "488B01" "488B4018") # slot 3 - a.rel("E8", "dispatch") - a.raw("488B4C2428" "488B01" "488B4010") - a.rel("E8", "dispatch") - a.label("doneC") - a.raw("4883C438C3") - end(s) - - a.label("stub3") # outside every function, like an ILT entry - a.rel("E9", "thunk3") - return funcs - - -def build_image(with_pdata: bool = True) -> bytes: - opt_size = 240 - buf = bytearray(RDATA_RAW + RDATA_SIZE) - buf[0:2] = b"MZ" - struct.pack_into(" dict: - return {c["class"] or c["class_id"]: c for c in report["classes"]} - - -def slots_of(cls: dict) -> dict: - return {(i["interface"], s["slot"]): s for i in cls["interfaces"] for s in i["slots"]} - - -class ImageTest(unittest.TestCase): - @classmethod - def setUpClass(cls): - cls.tmp = tempfile.mkdtemp() - cls.table = grc.RuntimeTable.load(grc.DEFAULT_TABLE) - cls.path = cls.write("thunks.dll", build_image()) - cls.served = grc.served_classes(SERVED_SOURCE) - cls.report = grc.report(cls.path, cls.table, cls.served) - - @classmethod - def tearDownClass(cls): - shutil.rmtree(cls.tmp, ignore_errors=True) - - @classmethod - def write(cls, name: str, data: bytes) -> str: - path = os.path.join(cls.tmp, name) - with open(path, "wb") as f: - f.write(data) - return path - - def test_helper_and_thunk_count(self): - self.assertEqual(self.report["helpers"], [f"rel {LABELS['helper']:#x}"]) - self.assertEqual(self.report["thunks"], 6) - # thunkC passes its ids in registers: listed, with no class read. - self.assertEqual(self.report["helper_calls_without_slot_call"], - [{"call": f"{LABELS['callC']:#x}", "class": None, "class_id": None, - "interface_id": None}]) - - def test_classes_slots_and_names(self): - classes = by_class(self.report) - self.assertEqual(set(classes), {"XThreadingImpl", "XNetworkingImpl", "XPackageImpl", UNKNOWN_CLASS}) - threading = slots_of(classes["XThreadingImpl"]) - self.assertEqual(threading[("XThreadingImpl/IXThreadingImpl", 12)]["method"], "XTaskQueueCreate") - self.assertEqual(threading[("XThreadingImpl/IXThreadingImpl", 12)]["args_estimate"], [3]) - self.assertEqual(threading[("XThreadingImpl/IXThreadingImpl", 29)]["method"], "XThreadAssertNotTimeSensitive") - self.assertEqual(threading[("XThreadingImpl/IXThreadingImpl", 29)]["args_estimate"], [0]) - # thunkB: no id in rdx, so the interface is the class id (not the global r8 points at); slot through r11. - self.assertEqual([i["interface_id"] for i in classes["XThreadingImpl"]["interfaces"]], [THREADING]) - dispatch = threading[("XThreadingImpl/IXThreadingImpl", 16)] - self.assertEqual((dispatch["method"], dispatch["args_estimate"]), ("XTaskQueueDispatch", [3])) - - networking = classes["XNetworkingImpl"] - self.assertEqual([i["interface_id"] for i in networking["interfaces"]], [NETWORKING2]) - hint = slots_of(networking)[("IXNetworkingImpl2", 15)] - self.assertEqual((hint["method"], hint["args_estimate"]), ("XNetworkingGetConnectivityHint", [1])) - - package = slots_of(classes["XPackageImpl"])[("IXPackageImpl3", 40)] - self.assertEqual((package["method"], package["args_estimate"]), ("XPackageRegisterPackageInstalled", [4])) - - def test_unknown_ids_are_reported(self): - unknown = by_class(self.report)[UNKNOWN_CLASS] - self.assertIsNone(unknown["class"]) - self.assertEqual(unknown["interfaces"][0]["interface"], "unknown") - self.assertEqual(unknown["interfaces"][0]["interface_id"], UNKNOWN_IFACE) - slot = unknown["interfaces"][0]["slots"][0] - self.assertEqual((slot["slot"], slot["method"], slot["args_estimate"]), (5, None, [0])) - - def test_served_flag(self): - classes = by_class(self.report) - self.assertIs(classes["XThreadingImpl"]["served"], True) - self.assertIs(classes["XPackageImpl"]["served"], False) - unserved = grc.report(self.path, self.table, None) - self.assertIsNone(by_class(unserved)["XThreadingImpl"]["served"]) - - def test_references(self): - classes = by_class(self.report) - threading = slots_of(classes["XThreadingImpl"]) - self.assertEqual(threading[("XThreadingImpl/IXThreadingImpl", 12)]["referenced"], 1) - # thunkA is called only by thunk4, which nothing calls. - self.assertEqual(threading[("XThreadingImpl/IXThreadingImpl", 29)]["referenced"], 0) - self.assertEqual(threading[("XThreadingImpl/IXThreadingImpl", 16)]["referenced"], 0) - self.assertEqual(classes["XPackageImpl"]["referenced_thunks"], 1) # through the jmp stub - self.assertEqual(classes[UNKNOWN_CLASS]["referenced_thunks"], 0) - self.assertEqual(self.report["referenced_thunks"], 3) - - def test_unreached_known_ids(self): - unreached = {u["class"]: u for u in self.report["unreached_classes"]} - self.assertEqual(set(unreached), {"XStoreImpl"}) - self.assertEqual(unreached["XStoreImpl"]["ids"][0]["id"], STORE) - - def test_without_pdata_the_byte_window_finds_the_same_slots(self): - path = self.write("no_pdata.dll", build_image(with_pdata=False)) - r = grc.report(path, self.table, self.served) - self.assertEqual(r["pdata_functions"], 0) - self.assertEqual({(c["class"], s["slot"]) for c in r["classes"] for i in c["interfaces"] for s in i["slots"]}, - {(c["class"], s["slot"]) for c in self.report["classes"] for i in c["interfaces"] - for s in i["slots"]}) - self.assertIsNone(r["referenced_thunks"]) - - def test_main_writes_text_and_json_with_lf(self): - out = os.path.join(self.tmp, "out") - source = self.write("xgameruntime.cpp", SERVED_SOURCE.encode()) - stdout = io.StringIO() - with contextlib.redirect_stdout(stdout): - rc = grc.main([self.path, "--out", out, "--runtime-source", source]) - self.assertEqual(rc, 0) - self.assertIn("not-served-referenced=XNetworkingImpl,XPackageImpl\n", stdout.getvalue()) - with open(os.path.join(out, "thunks.dll.gdk_calls.json"), "rb") as f: - raw = f.read() - self.assertNotIn(b"\r\n", raw) - self.assertEqual(json.loads(raw)["thunks"], 6) - with open(os.path.join(out, "thunks.dll.gdk_calls.txt"), "rb") as f: - text = f.read().decode("utf-8") - self.assertNotIn("\r\n", text) - self.assertIn("slot 12 XTaskQueueCreate", text) - self.assertIn("XPackageImpl as IXPackageImpl3: 40; referenced: 40", text) - self.assertIn("class id not read; interface not read", text) - - def test_main_names_repeated_inputs_and_refuses_a_file_as_out(self): - out = os.path.join(self.tmp, "out-twice") - stdout, stderr = io.StringIO(), io.StringIO() - with contextlib.redirect_stdout(stdout), contextlib.redirect_stderr(stderr): - self.assertEqual(grc.main([self.path, self.path, "--out", out]), 0) - self.assertEqual(grc.main([self.path, "--out", self.path]), 1) - self.assertTrue(os.path.isfile(os.path.join(out, "thunks.dll-2.gdk_calls.json"))) - self.assertIn("report written as thunks.dll-2.gdk_calls.txt/.json", stderr.getvalue()) - self.assertIn("path is a file, not a directory", stderr.getvalue()) - - def test_main_refuses_out_that_overwrites_input(self): - aliased_dir = os.path.join(self.tmp, "alias-out") - os.makedirs(aliased_dir, exist_ok=True) - aliased = os.path.join(aliased_dir, "thunks.dll.gdk_calls.json") - shutil.copyfile(grc.DEFAULT_TABLE, aliased) - with open(aliased, "rb") as f: - original = f.read() - stdout, stderr = io.StringIO(), io.StringIO() - with contextlib.redirect_stdout(stdout), contextlib.redirect_stderr(stderr): - rc = grc.main([self.path, "--table", aliased, "--out", aliased_dir]) - self.assertEqual(rc, 1) - self.assertIn("would overwrite input file", stderr.getvalue()) - with open(aliased, "rb") as f: - self.assertEqual(f.read(), original) - self.assertFalse(os.path.exists(os.path.join(aliased_dir, "thunks.dll.gdk_calls.txt"))) - - def test_the_default_source_is_every_runtime_shim(self): - # The classes xgameruntime.cpp hands on to its sibling files count as served: XUserImpl, XGameSaveImpl and - # XStoreImpl live in xgameruntime_user.cpp, _gamesave.cpp and _store.cpp. - served = grc.served_classes(grc.read_runtime_source(grc.DEFAULT_RUNTIME_SOURCE)) - names = set(served.values()) - for name in ("kThreadingClass", "kUserClass", "kSaveClass", "kStoreClass"): - self.assertIn(name, names) - self.assertEqual(served.get("704c3f58-e629-4cc2-b197-30511b996fe2"), "kSaveClass") - # xgameruntime.cpp serves XGameRuntimeFeatureImpl; the ids its feature table only names (k...ClassId) don't count. - self.assertEqual(served.get("8836fe87-edb9-4fe3-8dad-05f0d2cd5b40"), "kGameRuntimeFeatureClass") - self.assertEqual(served.get("1b339674-328d-4283-a200-3171f18d3639"), "kLauncherClass") # XLauncherImpl, xgameruntime_offline.cpp - self.assertNotIn("a4f1aee2-4bf1-4485-b008-a7c26d52ac27", served) # XAppCaptureImpl - empty = os.path.join(self.tmp, "no-shims") - os.makedirs(empty, exist_ok=True) - with self.assertRaises(OSError): - grc.read_runtime_source(empty) - - def test_main_json_to_stdout(self): - stdout, stderr = io.StringIO(), io.StringIO() - with contextlib.redirect_stdout(stdout), contextlib.redirect_stderr(stderr): - rc = grc.main([self.path, "--json", "--runtime-source", os.path.join(self.tmp, "missing.cpp")]) - self.assertEqual(rc, 0) - self.assertIn("'served' is unknown", stderr.getvalue()) - doc = json.loads(stdout.getvalue()) - self.assertEqual(doc["images"][0]["file"], "thunks.dll") - self.assertIsNone(by_class(doc["images"][0])["XThreadingImpl"]["served"]) - - def test_truncated_image(self): - data = build_image() - cut = self.write("cut.dll", data[:TEXT_RAW + 0x100]) - r = grc.report(cut, self.table, self.served) - self.assertEqual(r["cut_off_sections"], [".text", ".rdata"]) - self.assertEqual(r["thunks"], 0) # the ids are gone with .rdata - stderr, stdout = io.StringIO(), io.StringIO() - with contextlib.redirect_stderr(stderr), contextlib.redirect_stdout(stdout): - self.assertEqual(grc.main([cut]), 1) - self.assertEqual(grc.main([self.write("head.dll", data[:0x100])]), 1) - self.assertEqual(grc.main([self.write("text.txt", b"not a PE image")]), 1) - self.assertIn("incomplete", stderr.getvalue()) - self.assertIn("not a readable PE image", stderr.getvalue()) - - -class DecoderTest(unittest.TestCase): - def test_lengths(self): - cases = { - "488D0D00000000": 7, # lea rcx,[rip+0] - "41FF9240010000": 7, # call [r10+140h] - "48C744242000000000": 9, # mov qword ptr [rsp+20h],0 - "E800000000": 5, # call rel32 - "660F1F440000": 6, # nop word ptr [rax+rax] - "C5F877": 3, # vzeroupper - "48B80000000000000000": 10, # mov rax,imm64 - "F6C101": 3, # test cl,1 - "F7C100000000": 6, # test ecx,imm32 - "66F7C10000": 5, # test cx,imm16 - "6648F7C100000000": 8, # test rcx,imm32 (REX.W overrides 66h) - "66C7C10000": 5, # mov cx,imm16 - "6648C7C100000000": 8, # mov rcx,imm32 (REX.W overrides 66h) - "4C8B11": 3, # mov r10,[rcx] - "0F8400000000": 6, # je rel32 - } - for text, size in cases.items(): - with self.subTest(text=text): - insn = grc.decode(bytes.fromhex(text), 0, 0x1000) - self.assertIsNotNone(insn) - self.assertEqual(insn.size, size) - - def test_operands(self): - lea = grc.decode(bytes.fromhex("488D1510000000"), 0, 0x1000) - self.assertEqual((lea.reg, lea.base, lea.target), (grc.RDX, grc.RIP, 0x1017)) - call = grc.decode(bytes.fromhex("41FF9240010000"), 0, 0) - self.assertEqual((call.base, call.disp, call.is_call()), (10, 0x140, True)) - self.assertIsNone(grc.decode(bytes.fromhex("48"), 0, 0)) # cut off after a REX prefix - - -class TableTest(unittest.TestCase): - @classmethod - def setUpClass(cls): - cls.table = grc.RuntimeTable.load(grc.DEFAULT_TABLE) - - def test_second_interface_starts_at_slot_3(self): - self.assertEqual(self.table.method("IXUserGamertagImpl", 3), ("XUserGetGamertag", None)) - self.assertEqual(self.table.interface_for("cef4fac0-7676-4a94-a119-4c43f9eb5b74"), "IXUserGamertagImpl") - - def test_unknown_entries_keep_their_slot(self): - self.assertEqual(self.table.method("IXPackageImpl3", 20), (None, None)) - self.assertEqual(self.table.method("IXPackageImpl3", 22), ("XPackageUnregisterPackageInstalled", None)) - self.assertEqual(self.table.method("IXPackageImpl3", 40), ("XPackageRegisterPackageInstalled", None)) - - def test_interfaces_without_layout(self): - names, no_layout = self.table.slot_table("IXSystemImpl5") - self.assertEqual(no_layout, ["IXSystemImpl2", "IXSystemImpl5"]) - self.assertEqual(self.table.method("IXSystemImpl5", 8), ("XSystemAllowFullDownloadBandwidth", None)) - self.assertEqual(self.table.method("IXSystemImpl5", 9), (None, None)) - self.assertIsNone(self.table.interfaces["IXSystemImpl5"]["methods"]) - - def test_class_id_used_as_interface_id(self): - self.assertEqual(self.table.interface_for("03f0fe74-fdd9-4e5c-b630-f9339c47acc5"), "IXDisplayImpl") - # XSystemImpl's class id is also IXSystemImpl's; a slot past it is named from the class's interface. - self.assertEqual(self.table.interface_for("e349bd1a-fc20-4e40-b99c-4178cc6b409f"), "IXSystemImpl") - self.assertEqual(self.table.method("IXSystemImpl", 6), ("XSystemHandleTrack", "IXSystemImpl5")) - - def test_served_classes(self): - other = ("constexpr GUID kOther = {0x1, 0x2, 0x3, {0, 0, 0, 0, 0, 0, 0, 0}};\n" # not a k...Class - "constexpr GUID kBadClass = {0x1, 0x2, 0x3, {0x100, 0, 0, 0, 0, 0, 0, 0}};\n") # not a GUID - self.assertEqual(grc.served_classes(SERVED_SOURCE + other), {THREADING: "kThreadingClass"}) - - def test_ranges(self): - self.assertEqual(grc.ranges([3, 4, 5, 9, 12, 13]), "3-5, 9, 12-13") - - -class GeneratorTest(unittest.TestCase): - PAGES = { - "README.md": "# XFooImpl\n\nClass Id: `aaaaaaaa-0000-0000-0000-000000000001`\n\n" - "Implements: [IXFooImpl3](IXFooImpl3.md), [IXFooExtraImpl](IXFooExtraImpl.md)\n", - "IXFooImpl.md": "# IXFooImpl\n\nInterface Id: `aaaaaaaa-0000-0000-0000-000000000001`\n\nInherits: IUnknown\n\n" - "Layout:\n- [XFooFirst](https://example.invalid/first)\n- *unknown*\n" - "- XFooPrivate (no docs)\n- *unknown* (perhaps an older [XFooFirst](https://example.invalid))\n" - "\nA closing paragraph.\n", - "IXFooImpl2.md": "# IXFooImpl2\n\nInterface Id: `aaaaaaaa-0000-0000-0000-000000000002`\n\n" - "Inherits: [IXFooImpl](IXFooImpl.md)\n\nNo layout is known for this one.\n", - "IXFooImpl3.md": "# IXFooImpl3\n\nInterface Id: `AAAAAAAA-0000-0000-0000-000000000003`\n\n" - "Inherits: [IXFooImpl2](IXFooImpl2.md)\n\nLayout:\n- [XFooThird](https://example.invalid)\n", - "IXFooExtraImpl.md": "# IXFooExtraImpl\n\nInterface Id: `aaaaaaaa-0000-0000-0000-0000000000ee`\n\n" - "Inherits: IUnknown\n\nLayout:\n- [XFooExtra](https://example.invalid)\n", - } - - def setUp(self): - self.root = tempfile.mkdtemp() - folder = os.path.join(self.root, "COM", "XFooImpl") - os.makedirs(folder) - for name, text in self.PAGES.items(): - with open(os.path.join(folder, name), "w", encoding="utf-8", newline="\n") as f: - f.write(text) - - def tearDown(self): - shutil.rmtree(self.root, ignore_errors=True) - - def test_parse(self): - doc = gen.build(self.root) - self.assertEqual(doc["classes"]["XFooImpl"], - {"id": "aaaaaaaa-0000-0000-0000-000000000001", "implements": ["IXFooImpl3", "IXFooExtraImpl"]}) - ifaces = doc["interfaces"] - self.assertEqual(ifaces["IXFooImpl"]["methods"], ["XFooFirst", None, "XFooPrivate", None]) - self.assertIsNone(ifaces["IXFooImpl2"]["methods"]) - self.assertEqual(ifaces["IXFooImpl3"]["id"], "aaaaaaaa-0000-0000-0000-000000000003") - self.assertEqual(ifaces["IXFooImpl3"]["inherits"], "IXFooImpl2") - self.assertIsNone(ifaces["IXFooExtraImpl"]["inherits"]) - self.assertEqual(gen.check(doc["classes"], ifaces), []) - table = grc.RuntimeTable(doc) - self.assertEqual(table.method("IXFooImpl3", 7), ("XFooThird", None)) - self.assertEqual(table.method("IXFooExtraImpl", 3), ("XFooExtra", None)) - self.assertEqual(table.slot_table("IXFooImpl3")[1], ["IXFooImpl2"]) - - def test_main_writes_lf_json_and_reports_broken_links(self): - os.remove(os.path.join(self.root, "COM", "XFooImpl", "IXFooExtraImpl.md")) - out = os.path.join(self.root, "table.json") - stderr = io.StringIO() - with contextlib.redirect_stderr(stderr), contextlib.redirect_stdout(io.StringIO()): - self.assertEqual(gen.main([self.root, "--out", out]), 0) - self.assertIn("IXFooExtraImpl, which has no page", stderr.getvalue()) - with open(out, "rb") as f: - raw = f.read() - self.assertNotIn(b"\r\n", raw) - self.assertIn("GPL-3.0", json.loads(raw)["licence"]) - with contextlib.redirect_stderr(io.StringIO()): - self.assertEqual(gen.main([os.path.join(self.root, "missing"), "--out", out]), 1) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/test_gen_d3d12_stubs.py b/tests/test_gen_d3d12_stubs.py deleted file mode 100644 index 9f2616681..000000000 --- a/tests/test_gen_d3d12_stubs.py +++ /dev/null @@ -1,522 +0,0 @@ -"""Tests for tools/gen_d3d12_stubs.py, driven by a synthetic d3d12.h (no Windows SDK). - - python -I tests/test_gen_d3d12_stubs.py -""" -import contextlib -import importlib.util -import io -import json -import os -import subprocess -import sys -import tempfile -import unittest -from unittest import mock - -ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) - - -def load_module(): - path = os.path.join(ROOT, "tools", "gen_d3d12_stubs.py") - spec = importlib.util.spec_from_file_location("gen_d3d12_stubs_under_test", path) - module = importlib.util.module_from_spec(spec) - spec.loader.exec_module(module) - return module - - -gen = load_module() - -GOOD_HEADER = """\ -MIDL_INTERFACE("11111111-2222-3333-4444-555555555555") -IBase : public IUnknown -{ -public: - virtual void STDMETHODCALLTYPE DoThing(UINT a, UINT b) = 0; - virtual HRESULT STDMETHODCALLTYPE Multi( - UINT first, - UINT second) = 0; - /* virtual void STDMETHODCALLTYPE Removed() = 0; */ - virtual HRESULT STDMETHODCALLTYPE AfterComment(void) = 0; /* trailing note */ -}; - -MIDL_INTERFACE("66666666-7777-8888-9999-AAAAAAAAAAAA") -IChild : public IBase -{ -public: - virtual HRESULT STDMETHODCALLTYPE GetThing(UINT index, _Out_ ID3D12Thing **ppThing) const = 0; - virtual UINT64 STDMETHODCALLTYPE Size(void) = 0; -}; -""" - -GUARDED_HEADER = """\ -MIDL_INTERFACE("22222222-2222-2222-2222-222222222222") -IGuarded : public IUnknown -{ -public: -#if 0 - virtual void STDMETHODCALLTYPE Gone(void) = 0; -#endif - virtual void STDMETHODCALLTYPE Kept(void) = 0; -}; -""" - -BRANCHED_HEADER = """\ -MIDL_INTERFACE("77777777-7777-7777-7777-777777777777") -IBranched : public IUnknown -{ -public: -#if defined(_MSC_VER) || !defined(_WIN32) - virtual THING_DESC STDMETHODCALLTYPE GetDesc(void) = 0; -#else - virtual THING_DESC *STDMETHODCALLTYPE GetDesc( - THING_DESC * RetVal) = 0; -#endif - virtual UINT STDMETHODCALLTYPE GetCount(void) = 0; -}; -""" - -ORPHAN_HEADER = """\ -MIDL_INTERFACE("33333333-3333-3333-3333-333333333333") -IOrphan : public IMissing -{ -public: - virtual void STDMETHODCALLTYPE Nothing(void) = 0; -}; -""" - -BROKEN_HEADER = """\ -MIDL_INTERFACE("44444444-4444-4444-4444-444444444444") -IBroken : public IUnknown -{ -public: - virtual void STDMETHODCALLTYPE NotAMethod = 0; -}; -""" - -UNTERMINATED_HEADER = """\ -MIDL_INTERFACE("55555555-5555-5555-5555-555555555555") -IHalf : public IUnknown -{ -public: - virtual void STDMETHODCALLTYPE Missing(void); -}; -""" - -IFACES = gen.parse_interfaces(GOOD_HEADER) - - -class ParseInterfacesTests(unittest.TestCase): - def test_names_bases_and_methods(self): - self.assertEqual(sorted(IFACES), ["IBase", "IChild"]) - self.assertEqual(IFACES["IBase"][0], "IUnknown") - self.assertEqual(IFACES["IChild"][0], "IBase") - methods = [item for item in IFACES["IBase"][1] if item[0] == "m"] - self.assertEqual([m[2] for m in methods], ["DoThing", "Multi", "AfterComment"]) - self.assertEqual(methods[0], ("m", "void", "DoThing", "UINT a, UINT b", "")) - - def test_multiline_declaration_is_joined(self): - methods = [item for item in IFACES["IBase"][1] if item[0] == "m"] - self.assertEqual(methods[1][3], "UINT first, UINT second") - - def test_const_method_is_marked(self): - methods = [item for item in IFACES["IChild"][1] if item[0] == "m"] - self.assertEqual(methods[0][4], "const") - self.assertEqual(methods[0][2], "GetThing") - - def test_commented_out_method_is_dropped(self): - names = [item[2] for item in IFACES["IBase"][1] if item[0] == "m"] - self.assertNotIn("Removed", names) - - def test_inline_comment_after_a_declaration_keeps_it(self): - names = [item[2] for item in IFACES["IBase"][1] if item[0] == "m"] - self.assertIn("AfterComment", names) - - def test_cpp_line_comments_do_not_change_the_method_list(self): - header = GOOD_HEADER.replace( - " virtual void STDMETHODCALLTYPE DoThing(UINT a, UINT b) = 0;", - " // virtual void STDMETHODCALLTYPE Omitted() = 0; };\n" - " virtual void STDMETHODCALLTYPE DoThing(UINT a, // parameter note\n" - " UINT b) = 0; // trailing comment") - self.assertEqual(gen.parse_interfaces(header), IFACES) - - def test_preprocessor_lines_pass_through(self): - items = gen.parse_interfaces(GUARDED_HEADER)["IGuarded"][1] - self.assertEqual(items[0], ("#", "#if 0")) - self.assertEqual(items[1][0], "m") - self.assertEqual(items[1][2], "Gone") - self.assertEqual(items[2], ("#", "#endif")) - self.assertEqual(items[3][2], "Kept") - - def test_text_without_interfaces(self): - self.assertEqual(gen.parse_interfaces("// nothing here\n"), {}) - - def test_unterminated_declaration_raises(self): - with self.assertRaises(SystemExit): - gen.parse_interfaces(UNTERMINATED_HEADER) - - def test_unparseable_declaration_raises(self): - with self.assertRaises(SystemExit): - gen.parse_interfaces(BROKEN_HEADER) - - -class ChainTests(unittest.TestCase): - def test_leaf_comes_last(self): - self.assertEqual(gen.chain(IFACES, "IChild"), ["IBase", "IChild"]) - - def test_root_interface(self): - self.assertEqual(gen.chain(IFACES, "IBase"), ["IBase"]) - - def test_unknown_base_raises(self): - orphan = gen.parse_interfaces(ORPHAN_HEADER) - with self.assertRaises(SystemExit): - gen.chain(orphan, "IOrphan") - - -class EmitClassTests(unittest.TestCase): - def test_class_skeleton_and_method_order(self): - text = gen.emit_class(IFACES, "IChild") - self.assertTrue(text.startswith("class IChildStubs : public IChild {\npublic:")) - self.assertTrue(text.endswith("};")) - self.assertLess(text.index("// IBase"), text.index("// IChild")) - self.assertLess(text.index("DoThing"), text.index("GetThing")) - self.assertNotIn("Removed", text) - - def test_return_conventions_and_stub_names(self): - text = gen.emit_class(IFACES, "IChild") - self.assertIn( - ' void STDMETHODCALLTYPE DoThing(UINT a, UINT b) override ' - '{ ::rt::d3d12::stub("IBase::DoThing"); }', - text, - ) - self.assertIn( - ' HRESULT STDMETHODCALLTYPE Multi(UINT first, UINT second) override ' - '{ ::rt::d3d12::stub("IBase::Multi"); return E_NOTIMPL; }', - text, - ) - self.assertIn( - ' HRESULT STDMETHODCALLTYPE GetThing(UINT index, _Out_ ID3D12Thing **ppThing) const override ' - '{ ::rt::d3d12::stub("IChild::GetThing"); return E_NOTIMPL; }', - text, - ) - self.assertIn( - ' UINT64 STDMETHODCALLTYPE Size(void) override ' - '{ ::rt::d3d12::stub("IChild::Size"); return {}; }', - text, - ) - - def test_directives_are_emitted_verbatim(self): - text = gen.emit_class(gen.parse_interfaces(GUARDED_HEADER), "IGuarded") - self.assertIn("\n#if 0\n", text) - self.assertIn("\n#endif\n", text) - self.assertIn('stub("IGuarded::Gone")', text) - - -class CoverageTests(unittest.TestCase): - def setUp(self): - tmp = tempfile.TemporaryDirectory() - self.addCleanup(tmp.cleanup) - self.dir = tmp.name - self.source = os.path.join(self.dir, "impl.cpp") - with open(self.source, "w", encoding="utf-8") as f: - f.write( - "HRESULT STDMETHODCALLTYPE DoThing(UINT a);\n" - "HRESULT STDMETHODCALLTYPE GetThing(UINT i) const;\n" - "void NotAnOverride();\n" - ) - - def test_reports_open_methods_in_vtable_order(self): - report = gen.coverage(IFACES, ["IChild"], [self.source]) - self.assertEqual(report, [{ - "interface": "IChild", - "methods": 5, - "implemented": 2, - "open": ["IBase::Multi", "IBase::AfterComment", "IChild::Size"], - }]) - - def test_coverage_ignores_comments_and_quoted_examples(self) -> None: - with open(self.source, "w", encoding="utf-8") as f: - f.write( - "void STDMETHODCALLTYPE DoThing(UINT a, UINT b);\n" - "// HRESULT STDMETHODCALLTYPE Multi(UINT first, UINT second);\n" - "/* HRESULT STDMETHODCALLTYPE GetThing(UINT index) const; */\n" - 'const char* example = "HRESULT STDMETHODCALLTYPE AfterComment(void);";\n' - ) - report = gen.coverage(IFACES, ["IChild"], [self.source]) - self.assertEqual(report[0]["implemented"], 1) - self.assertEqual(report[0]["open"], - ["IBase::Multi", "IBase::AfterComment", "IChild::GetThing", "IChild::Size"]) - - def test_no_sources_means_every_method_is_open(self): - report = gen.coverage(IFACES, ["IBase"], []) - self.assertEqual(report[0]["implemented"], 0) - self.assertEqual(report[0]["open"], ["IBase::DoThing", "IBase::Multi", "IBase::AfterComment"]) - - def test_repeated_interface_is_reported_once(self): - report = gen.coverage(IFACES, ["IChild", "IChild"], [self.source]) - self.assertEqual([row["interface"] for row in report], ["IChild"]) - - def test_method_declared_in_both_preprocessor_branches_counts_once(self): - # d3d12.h declares struct-returning methods in both branches of #if/#else; that is one method. - interfaces = gen.parse_interfaces(BRANCHED_HEADER) - self.assertEqual(gen.coverage(interfaces, ["IBranched"], []), [{ - "interface": "IBranched", - "methods": 2, - "implemented": 0, - "open": ["IBranched::GetDesc", "IBranched::GetCount"], - }]) - with open(self.source, "w", encoding="utf-8", newline="\n") as f: - f.write("THING_DESC STDMETHODCALLTYPE GetDesc() { return {}; }\n") - report = gen.coverage(interfaces, ["IBranched"], [self.source]) - self.assertEqual((report[0]["methods"], report[0]["implemented"], report[0]["open"]), - (2, 1, ["IBranched::GetCount"])) - # The stub class keeps both branches, so it compiles under either side of the condition. - text = gen.emit_class(interfaces, "IBranched") - self.assertEqual(text.count('stub("IBranched::GetDesc")'), 2) - self.assertIn("\n#else\n", text) - - -class MainTests(unittest.TestCase): - def setUp(self): - tmp = tempfile.TemporaryDirectory() - self.addCleanup(tmp.cleanup) - self.dir = tmp.name - self.header = os.path.join(self.dir, "d3d12.h") - with open(self.header, "w", encoding="utf-8") as f: - f.write(GOOD_HEADER) - self.out = os.path.join(self.dir, "generated", "d3d12_stubs.h") - - def run_main(self, *interfaces, include_header=True): - args = ["gen_d3d12_stubs.py", "--out", self.out] - if include_header: - args += ["--header", self.header] - with mock.patch("sys.argv", args + list(interfaces)): - return gen.main() - - def test_writes_header_and_class(self): - self.assertEqual(self.run_main("IChild"), 0) - self.assertTrue(os.path.isdir(os.path.dirname(self.out))) - with open(self.out, encoding="utf-8") as f: - text = f.read() - self.assertTrue( - text.startswith( - "// Generated by tools/gen_d3d12_stubs.py from d3d12.h. Do not edit.\n" - ) - ) - for line in ( - "#pragma once", - "#include ", - "namespace rt::d3d12 { void stub(const char* method); }", - "#pragma warning(push)", - "#pragma warning(disable : 4100) // unreferenced parameters", - "class IChildStubs : public IChild {", - "#pragma warning(pop)", - ): - self.assertIn(line, text) - self.assertTrue(text.endswith("\n")) - self.assertNotIn("\r\n", text) - - def test_second_run_does_not_rewrite(self): - self.assertEqual(self.run_main("IChild"), 0) - before = os.stat(self.out).st_mtime_ns - self.assertEqual(self.run_main("IChild"), 0) - self.assertEqual(os.stat(self.out).st_mtime_ns, before) - - def test_two_interfaces_keep_their_order(self): - self.assertEqual(self.run_main("IBase", "IChild"), 0) - with open(self.out, encoding="utf-8") as f: - text = f.read() - self.assertLess(text.index("class IBaseStubs"), text.index("class IChildStubs")) - - def test_repeated_interface_is_emitted_once(self): - self.assertEqual(self.run_main("IChild", "IBase"), 0) - with open(self.out, encoding="utf-8") as f: - expected = f.read() - - self.assertEqual(self.run_main("IChild", "IBase", "IChild"), 0) - with open(self.out, encoding="utf-8") as f: - self.assertEqual(f.read(), expected) - - def test_unknown_interface_raises(self): - with self.assertRaises(SystemExit): - self.run_main("IWho") - - def test_circular_inheritance_reports_an_error(self): - with open(self.header, "w", encoding="utf-8") as f: - f.write(GOOD_HEADER.replace("IBase : public IUnknown", "IBase : public IChild")) - tool = os.path.join(ROOT, "tools", "gen_d3d12_stubs.py") - result = subprocess.run([sys.executable, "-I", tool, "--header", self.header, - "--out", self.out, "IChild"], capture_output=True, text=True, timeout=5) - self.assertNotEqual(result.returncode, 0) - self.assertIn("IChild -> IBase -> IChild", result.stderr) - self.assertFalse(os.path.exists(self.out)) - - def test_report_without_out(self): - source = os.path.join(self.dir, "impl.cpp") - with open(source, "w", encoding="utf-8") as f: - f.write("HRESULT STDMETHODCALLTYPE DoThing(UINT a);\n") - report = os.path.join(self.dir, "coverage.json") - args = ["gen_d3d12_stubs.py", "--header", self.header, "--report", report, - "--source", source, "IChild"] - with mock.patch("sys.argv", args): - self.assertEqual(gen.main(), 0) - with open(report, encoding="utf-8") as f: - data = json.load(f) - self.assertEqual(data[0]["interface"], "IChild") - self.assertEqual(data[0]["open"], - ["IBase::Multi", "IBase::AfterComment", "IChild::GetThing", "IChild::Size"]) - self.assertFalse(os.path.exists(self.out)) - - def test_out_or_report_is_required(self): - with mock.patch("sys.argv", ["gen_d3d12_stubs.py", "--header", self.header, "IChild"]): - with self.assertRaises(SystemExit): - gen.main() - - def test_report_requires_a_source(self): - report = os.path.join(self.dir, "coverage.json") - with mock.patch("sys.argv", ["gen_d3d12_stubs.py", "--header", self.header, - "--report", report, "IChild"]): - with self.assertRaises(SystemExit): - gen.main() - - def run_args(self, *args): - with mock.patch("sys.argv", ["gen_d3d12_stubs.py", *args]): - return gen.main() - - def make_source(self): - source = os.path.join(self.dir, "impl.cpp") - with open(source, "w", encoding="utf-8") as f: - f.write("HRESULT STDMETHODCALLTYPE DoThing(UINT a);\n") - return source - - def test_report_must_not_overwrite_a_source(self): - source = self.make_source() - with open(source, "rb") as f: - before = f.read() - with self.assertRaises(SystemExit): - self.run_args("--header", self.header, "--report", source, "--source", source, "IChild") - with open(source, "rb") as f: - self.assertEqual(f.read(), before) - - def test_out_must_not_overwrite_the_header(self): - with open(self.header, "rb") as f: - before = f.read() - with self.assertRaises(SystemExit): - self.run_args("--header", self.header, "--out", self.header, "IChild") - with open(self.header, "rb") as f: - self.assertEqual(f.read(), before) - - def test_out_and_report_must_differ(self): - source = self.make_source() - same = os.path.join(self.dir, "report.json") - with self.assertRaises(SystemExit): - self.run_args("--header", self.header, "--out", same, "--report", same, - "--source", source, "IChild") - self.assertFalse(os.path.exists(same)) - - def test_out_must_be_a_file(self): - folder = os.path.join(self.dir, "out_folder") - os.makedirs(folder) - with self.assertRaises(SystemExit): - self.run_args("--header", self.header, "--out", folder, "IChild") - - def test_a_source_folder_is_refused(self): - source = os.path.join(self.dir, "src_folder") - os.makedirs(source) - with self.assertRaises(SystemExit): - self.run_args("--header", self.header, "--report", os.path.join(self.dir, "r.json"), - "--source", source, "IChild") - - def test_a_missing_header_is_refused_before_writing(self): - with self.assertRaises(SystemExit): - self.run_args("--header", os.path.join(self.dir, "missing.h"), "--out", self.out, "IChild") - self.assertFalse(os.path.exists(self.out)) - - def test_a_failed_write_is_one_line(self): - blocker = os.path.join(self.dir, "not_a_folder") - with open(blocker, "wb") as f: - f.write(b"keep me") - err = io.StringIO() - with contextlib.redirect_stderr(err): - code = self.run_args("--header", self.header, "--out", os.path.join(blocker, "stubs.h"), "IChild") - self.assertEqual(code, 2) - self.assertIn("ERROR: cannot write", err.getvalue()) - self.assertNotIn("Traceback", err.getvalue()) - with open(blocker, "rb") as f: - self.assertEqual(f.read(), b"keep me") - - def test_find_header_uses_the_include_environment(self): - with mock.patch.dict(os.environ, {"INCLUDE": self.dir}, clear=False): - self.assertEqual(gen.find_header(), self.header) - self.assertEqual(self.run_main("IChild", include_header=False), 0) - self.assertTrue(os.path.isfile(self.out)) - - def test_find_header_without_include_returns_none(self): - with mock.patch.dict(os.environ, {"INCLUDE": ""}, clear=False): - self.assertIsNone(gen.find_header()) - - -class ReportPathCollisions(unittest.TestCase): - """`--out` and `--report` are two artifacts; naming one file for both lost the report silently (#2716).""" - - def setUp(self): - tmp = tempfile.TemporaryDirectory() - self.addCleanup(tmp.cleanup) - self.dir = tmp.name - self.header = os.path.join(self.dir, "d3d12.h") - with open(self.header, "w", encoding="utf-8") as f: - f.write(GOOD_HEADER) - self.source = os.path.join(self.dir, "impl.cpp") - with open(self.source, "w", encoding="utf-8") as f: - f.write("HRESULT STDMETHODCALLTYPE DoThing(UINT a);\n") - - def run_main(self, *args): - err = io.StringIO() - with mock.patch("sys.argv", ["gen_d3d12_stubs.py", "--header", self.header, *args, "IChild"]), \ - contextlib.redirect_stderr(err): - with self.assertRaises(SystemExit) as raised: - gen.main() - self.assertEqual(raised.exception.code, 2) - return err.getvalue() - - def test_out_and_report_must_differ(self): - one = os.path.join(self.dir, "both.txt") - err = self.run_main("--out", one, "--report", one, "--source", self.source) - self.assertIn("--out and --report must use different paths", err) - - def test_the_same_file_spelled_differently_is_still_the_same_file(self): - one = os.path.join(self.dir, "both.txt") - spelled = os.path.join(self.dir, ".", "sub", "..", "both.txt") - os.makedirs(os.path.join(self.dir, "sub")) - err = self.run_main("--out", one, "--report", spelled, "--source", self.source) - self.assertIn("must use different paths", err) - - def test_out_cannot_overwrite_a_source(self): - err = self.run_main("--out", self.source, "--report", os.path.join(self.dir, "r.json"), - "--source", self.source) - self.assertIn(f"--out {self.source} would overwrite the input {self.source}", err) - - def test_report_cannot_overwrite_a_source(self): - err = self.run_main("--out", os.path.join(self.dir, "out.h"), "--report", self.source, - "--source", self.source) - self.assertIn(f"--report {self.source} would overwrite the input {self.source}", err) - - @unittest.skipUnless(os.name == "nt", "letter case only folds on Windows and case-insensitive volumes") - def test_a_case_different_spelling_is_one_file(self): - err = self.run_main("--out", os.path.join(self.dir, "Out.H"), "--report", - os.path.join(self.dir, "out.h"), "--source", self.source) - self.assertIn("must use different paths", err) - - def test_distinct_paths_still_write_both_artifacts(self): - out = os.path.join(self.dir, "out.h") - report = os.path.join(self.dir, "r.json") - with mock.patch("sys.argv", ["gen_d3d12_stubs.py", "--header", self.header, "--out", out, - "--report", report, "--source", self.source, "IChild"]): - self.assertEqual(gen.main(), 0) - with open(out, encoding="utf-8") as f: - self.assertTrue(f.read().startswith("// Generated by tools/gen_d3d12_stubs.py")) - with open(report, encoding="utf-8") as f: - self.assertEqual(json.load(f)[0]["implemented"], 1) # still a report, not a header - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/test_gfx10_descriptors.py b/tests/test_gfx10_descriptors.py deleted file mode 100644 index 6060af557..000000000 --- a/tests/test_gfx10_descriptors.py +++ /dev/null @@ -1,98 +0,0 @@ -"""The format table of runtime/src/gfx10_descriptors.h against tools/gfx10_formats.json. - -The C++ header keeps its own copy of the GFX10_FORMAT codes it maps to Vulkan (the runtime does not read JSON for -this). This test reads the table out of the header and checks every row: the code has the name its comment says, -in the list the translator uses, and the Vulkan format beside it has that name's channel sizes and numeric type. -A GFX10 format names its channel sizes from the top bit down; a Vulkan format does so only when it is packed. - - python -I tests/test_gfx10_descriptors.py - python -m pytest tests/test_gfx10_descriptors.py -q -""" -import json -import os -import re -import unittest - -ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) -HEADER = os.path.join(ROOT, "runtime", "src", "gfx10_descriptors.h") -FORMATS = os.path.join(ROOT, "tools", "gfx10_formats.json") - -ROW = re.compile(r"^\s*\{(\d+), VK_FORMAT_(\w+), channels_(\w+)\},\s*// GFX10_FORMAT_(\w+)\s*$") -ANY_ROW = re.compile(r"^\s*\{\d+, VK_FORMAT_") - -# Depth-stencil formats, which Mesa's table maps by hand (src/amd/common/gfx10_format_table.py, HARDCODED). -BY_HAND = {"D24_UNORM_S8_UINT": "8_24_UNORM", "D32_SFLOAT_S8_UINT": "X24_8_32_FLOAT"} - - -def table(): - """[(code, Vulkan name without VK_FORMAT_, channel order, GFX10 name without GFX10_FORMAT_)], in file order.""" - rows, loose = [], 0 - with open(HEADER, encoding="utf-8") as f: - for line in f: - loose += bool(ANY_ROW.match(line)) - m = ROW.match(line) - if m: - rows.append((int(m.group(1)), m.group(2), m.group(3), m.group(4))) - return rows, loose - - -def gfx10_name(vulkan): - """The GFX10 format name a Vulkan format name implies. An extension's suffix (A8_UNORM_KHR) is not part of the - layout.""" - vulkan = re.sub(r"_(KHR|EXT)$", "", vulkan) - if vulkan in BY_HAND: - return BY_HAND[vulkan] - m = re.fullmatch(r"BC(\d)H?(?:_RGBA?)?_(\w+)_BLOCK", vulkan) - if m: - return f"BC{m.group(1)}_{m.group(2)}" - packed = re.search(r"_PACK\d+$", vulkan) - layout, numeric = (vulkan[:packed.start()] if packed else vulkan).rsplit("_", 1) - sizes = re.findall(r"[RGBAEXDS](\d+)", layout) - if not packed: - sizes.reverse() # memory order, lowest byte first -> from the top bit down - return "_".join(sizes + ["FLOAT" if numeric in ("SFLOAT", "UFLOAT") else numeric]) - - -class FormatTable(unittest.TestCase): - @classmethod - def setUpClass(cls): - cls.rows, cls.loose = table() - with open(FORMATS, encoding="utf-8") as f: - cls.names = {int(k): v[len("GFX10_FORMAT_"):] for k, v in json.load(f).items()} - - def test_every_row_is_read(self): - self.assertGreater(len(self.rows), 80) - self.assertEqual(len(self.rows), self.loose, "a table row does not have the form this test parses") - - def test_codes_have_the_names_in_the_comments(self): - for code, vulkan, _order, name in self.rows: - self.assertEqual(self.names.get(code), name, f"{{{code}, VK_FORMAT_{vulkan}}}") - - def test_vulkan_formats_have_the_layout_of_their_code(self): - for code, vulkan, _order, name in self.rows: - self.assertEqual(gfx10_name(vulkan), name, f"{{{code}, VK_FORMAT_{vulkan}}}") - - def test_rows_are_sorted_and_each_vulkan_format_appears_once(self): - codes = [r[0] for r in self.rows] - self.assertEqual(codes, sorted(codes)) - formats = [r[1] for r in self.rows] - self.assertEqual(len(formats), len(set(formats))) - - def test_what_the_translator_and_its_tests_rely_on(self): - by_vulkan = {r[1]: r[0] for r in self.rows} - # cs_imgstore.asm: word 1 = FORMAT << 20 with 0x38, 0x14 and 0x15. - self.assertEqual(by_vulkan["R8G8B8A8_UNORM"], 0x38) - self.assertEqual(by_vulkan["R32_UINT"], 0x14) - self.assertEqual(by_vulkan["R32_SINT"], 0x15) - # The translator picks the uint or sint view from the code's name (rdna2spirv.py, int_format_masks). A - # depth-stencil format is in the table as its depth plane, whatever its stencil plane's type. - for code, vulkan, _order, name in self.rows: - if vulkan in BY_HAND: - continue - for suffix in ("_UINT", "_SINT"): - self.assertEqual(name.endswith(suffix), vulkan.endswith(suffix) or f"{suffix}_PACK" in vulkan, - f"{{{code}, VK_FORMAT_{vulkan}}}") - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/test_glb_atomic.py b/tests/test_glb_atomic.py deleted file mode 100644 index 06c6554cd..000000000 --- a/tests/test_glb_atomic.py +++ /dev/null @@ -1,233 +0,0 @@ -"""GLB export file ownership and overlapping-write regressions; no game data. - - python -I tests/test_glb_atomic.py -v -""" -import os -from pathlib import Path -import sys -import tempfile -import threading -import unittest -from unittest import mock - -sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "tools")) -import glb_writer - - -class GlbAtomicTests(unittest.TestCase): - @staticmethod - def primitives(size=1): - return glb_writer.parse_obj( - f"v 0 0 0\nv {size} 0 0\nv 0 {size} 0\nf 1 2 3\n", - is_path=False, - ) - - def test_success_preserves_existing_sibling_and_output_bytes(self): - prims = self.primitives() - expected = glb_writer.build_glb(prims) - with tempfile.TemporaryDirectory() as directory: - target = Path(directory) / "mesh.glb" - sibling = Path(str(target) + ".tmp") - sibling.write_bytes(b"unrelated file") - target.write_bytes(b"previous export") - - stats = glb_writer.write_glb(target, prims) - - self.assertEqual(target.read_bytes(), expected) - self.assertEqual(sibling.read_bytes(), b"unrelated file") - self.assertEqual(stats["bytes"], len(expected)) - self.assertEqual(set(os.listdir(directory)), {target.name, sibling.name}) - - def test_failed_replace_preserves_destination_and_sibling(self): - with tempfile.TemporaryDirectory() as directory: - target = Path(directory) / "mesh.glb" - sibling = Path(str(target) + ".tmp") - target.write_bytes(b"previous export") - sibling.write_bytes(b"unrelated file") - with mock.patch.object(glb_writer.os, "replace", side_effect=PermissionError("busy")): - with self.assertRaisesRegex(PermissionError, "busy"): - glb_writer.write_glb(target, self.primitives()) - - self.assertEqual(target.read_bytes(), b"previous export") - self.assertEqual(sibling.read_bytes(), b"unrelated file") - self.assertEqual(set(os.listdir(directory)), {target.name, sibling.name}) - - def test_overlapping_writes_each_publish_their_own_complete_bytes(self): - first, second = self.primitives(1), self.primitives(2) - first_bytes, second_bytes = map(glb_writer.build_glb, (first, second)) - replace = os.replace - staging_paths = [] - with tempfile.TemporaryDirectory() as directory: - target = Path(directory) / "mesh.glb" - - def interleave(source, destination): - staging_paths.append(os.fspath(source)) - self.assertEqual(Path(source).parent.resolve(), target.parent.resolve()) - if len(staging_paths) == 1: - # The first writer has closed its file but has not published it. - glb_writer.write_glb(target, second) - self.assertEqual(target.read_bytes(), second_bytes) - replace(source, destination) - - with mock.patch.object(glb_writer.os, "replace", side_effect=interleave): - glb_writer.write_glb(target, first) - - self.assertEqual(target.read_bytes(), first_bytes) - self.assertEqual(len(set(staging_paths)), 2) - self.assertEqual(os.listdir(directory), [target.name]) - - def test_partial_write_failure_cleans_only_its_own_staging_file(self): - create_temp = tempfile.NamedTemporaryFile - - def failing_temp(*args, **kwargs): - handle = create_temp(*args, **kwargs) - write = handle.write - - def fail_write(payload): - write(payload[:12]) - raise OSError("simulated full disk") - - handle.write = fail_write - return handle - - with tempfile.TemporaryDirectory() as directory: - target = Path(directory) / "mesh.glb" - sibling = Path(str(target) + ".tmp") - target.write_bytes(b"previous export") - sibling.write_bytes(b"unrelated file") - with mock.patch.object(glb_writer.tempfile, "NamedTemporaryFile", side_effect=failing_temp): - with self.assertRaisesRegex(OSError, "simulated full disk"): - glb_writer.write_glb(target, self.primitives()) - - self.assertEqual(target.read_bytes(), b"previous export") - self.assertEqual(sibling.read_bytes(), b"unrelated file") - self.assertEqual(set(os.listdir(directory)), {target.name, sibling.name}) - - def test_transient_sharing_violation_is_retried(self): - prims = self.primitives() - replace = os.replace - calls = [] - - def busy_twice(source, destination): - calls.append(source) - if len(calls) <= 2: - raise PermissionError(13, "sharing violation") - replace(source, destination) - - with tempfile.TemporaryDirectory() as directory: - target = Path(directory) / "mesh.glb" - target.write_bytes(b"previous export") - with mock.patch.object(glb_writer, "_REPLACE_RETRY", True), \ - mock.patch.object(glb_writer.time, "sleep") as sleep, \ - mock.patch.object(glb_writer.os, "replace", side_effect=busy_twice): - glb_writer.write_glb(target, prims) - - self.assertEqual(target.read_bytes(), glb_writer.build_glb(prims)) - self.assertEqual(len(calls), 3) - self.assertEqual(sleep.call_count, 2) - self.assertEqual(os.listdir(directory), [target.name]) - - def test_lasting_sharing_violation_still_raises_after_retries(self): - with tempfile.TemporaryDirectory() as directory: - target = Path(directory) / "mesh.glb" - target.write_bytes(b"previous export") - replace = mock.Mock(side_effect=PermissionError("busy")) - with mock.patch.object(glb_writer, "_REPLACE_RETRY", True), \ - mock.patch.object(glb_writer.time, "sleep"), \ - mock.patch.object(glb_writer.os, "replace", replace): - with self.assertRaisesRegex(PermissionError, "busy"): - glb_writer.write_glb(target, self.primitives()) - - self.assertEqual(replace.call_count, len(glb_writer._REPLACE_DELAYS) + 1) - self.assertEqual(target.read_bytes(), b"previous export") - self.assertEqual(os.listdir(directory), [target.name]) - - def test_other_errors_are_not_retried(self): - with tempfile.TemporaryDirectory() as directory: - target = Path(directory) / "mesh.glb" - replace = mock.Mock(side_effect=FileNotFoundError("gone")) - with mock.patch.object(glb_writer, "_REPLACE_RETRY", True), \ - mock.patch.object(glb_writer.time, "sleep") as sleep, \ - mock.patch.object(glb_writer.os, "replace", replace): - with self.assertRaises(FileNotFoundError): - glb_writer.write_glb(target, self.primitives()) - self.assertEqual(replace.call_count, 1) - sleep.assert_not_called() - - @unittest.skipUnless(os.name == "nt", "sharing violations on replace are Windows-only") - def test_threads_writing_one_file_all_publish(self): - # Before the retry, 8 threads x 40 writes to one path failed 43-152 of 320 - # calls with PermissionError on Windows 11 (#425 review). - payloads = [self.primitives(size) for size in range(1, 9)] - allowed = {glb_writer.build_glb(p) for p in payloads} - errors = [] - with tempfile.TemporaryDirectory() as directory: - target = Path(directory) / "mesh.glb" - - def worker(prims): - for _ in range(40): - try: - glb_writer.write_glb(target, prims) - except OSError as exc: - errors.append(exc) - - threads = [threading.Thread(target=worker, args=(p,)) for p in payloads] - for t in threads: - t.start() - for t in threads: - t.join() - - self.assertEqual(errors, []) - self.assertIn(target.read_bytes(), allowed) - self.assertEqual(os.listdir(directory), [target.name]) - - @unittest.skipUnless(os.name == "posix", "POSIX permission bits") - def test_published_glb_keeps_permission_bits(self): - # The staging file is created 0600; the published GLB must not lose group/other read. - with tempfile.TemporaryDirectory() as directory: - target = Path(directory) / "mesh.glb" - old = os.umask(0o022) - try: - glb_writer.write_glb(target, self.primitives()) - self.assertEqual(target.stat().st_mode & 0o777, 0o644) - os.chmod(target, 0o640) - glb_writer.write_glb(target, self.primitives(2)) - self.assertEqual(target.stat().st_mode & 0o777, 0o640) - finally: - os.umask(old) - - def test_concurrent_new_files_leave_the_umask_alone(self): - # A new file's mode comes from a probe file (file_mode.published_mode), never from setting the umask to 0 - # and back, which could leave a threaded process at umask 0. - import file_mode - modes = [] - with tempfile.TemporaryDirectory() as directory, mock.patch.object(file_mode.os, "umask", side_effect=AssertionError("umask touched")) as umask: - threads = [threading.Thread(target=lambda i=i: modes.append( - file_mode.published_mode(os.path.join(directory, f"new{i}.glb")))) for i in range(2)] - for t in threads: - t.start() - for t in threads: - t.join() - umask.assert_not_called() - self.assertEqual(len(modes), 2) - self.assertEqual(modes[0], modes[1]) - - def test_published_glb_is_writable(self): - with tempfile.TemporaryDirectory() as directory: - target = Path(directory) / "mesh.glb" - glb_writer.write_glb(target, self.primitives()) - self.assertTrue(os.access(target, os.W_OK)) - glb_writer.write_glb(target, self.primitives(2)) - self.assertEqual(target.read_bytes(), glb_writer.build_glb(self.primitives(2))) - - def test_creates_missing_parent_directory(self): - with tempfile.TemporaryDirectory() as directory: - target = Path(directory) / "nested" / "mesh.glb" - prims = self.primitives() - glb_writer.write_glb(target, prims) - self.assertEqual(target.read_bytes(), glb_writer.build_glb(prims)) - self.assertEqual(os.listdir(target.parent), [target.name]) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/test_glb_inspect.py b/tests/test_glb_inspect.py deleted file mode 100644 index 533a2949e..000000000 --- a/tests/test_glb_inspect.py +++ /dev/null @@ -1,929 +0,0 @@ -"""Tests for tools/glb_inspect.py. - -Every GLB here is built by hand from JSON and BIN chunks; no game data, exporter -or third-party library is involved. - - python -I tests/test_glb_inspect.py -""" -import contextlib -import io -import json -import os -import stat -import struct -import subprocess -import sys -import tempfile -import unittest -from unittest import mock - -ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) -TOOL = os.path.join(ROOT, "tools", "glb_inspect.py") -sys.path.insert(0, os.path.dirname(TOOL)) -import glb_inspect # noqa: E402 - -JSON_CHUNK = 0x4E4F534A -BIN_CHUNK = 0x004E4942 -EXT_CHUNK = 0x54534554 - - -def json_bytes(gltf): - raw = json.dumps(gltf, separators=(",", ":"), ensure_ascii=False).encode("utf-8") - return raw + b" " * ((-len(raw)) % 4) - - -def raw_glb(chunks): - """A GLB from (type, payload) chunks; the caller pads each payload to 4 bytes.""" - body = b"".join(struct.pack(" json_end): - raise AssertionError("copied payload outside the JSON chunk") - return super().__getitem__(key) - - data = MetadataOnlyBytes(raw_glb([ - (JSON_CHUNK, metadata), (BIN_CHUNK, b"abc\x00"), (EXT_CHUNK, b"TEST"), - ])) - chunks = glb_inspect.parse_glb(data)["chunks"] - self.assertEqual(chunks[1]["padding"], 1) - self.assertEqual(chunks[2]["byte_length"], 4) - - def test_chunk_and_header_lengths_must_be_4_byte_aligned(self): - payload = b'{"asset":{"version":"2.0"}}' - self.assertEqual(len(payload) % 4, 3) - - header = struct.pack("<4sII", b"glTF", 2, 48) - body = struct.pack(" bytes: - """Generate a minimal valid RGBA PNG entirely via standard library struct/zlib.""" - if rgba_bytes is None: - rgba_bytes = bytes([255, 0, 0, 255] * (width * height)) - assert len(rgba_bytes) == width * height * 4 - - sig = b"\x89PNG\r\n\x1a\n" - # IHDR: width, height, bit_depth=8, color_type=6 (RGBA), comp=0, filter=0, interlace=0 - ihdr_data = struct.pack(">IIBBBBB", width, height, 8, 6, 0, 0, 0) - ihdr_crc = zlib.crc32(b"IHDR" + ihdr_data) & 0xFFFFFFFF - ihdr = struct.pack(">I4s", len(ihdr_data), b"IHDR") + ihdr_data + struct.pack(">I", ihdr_crc) - - # Raw scanlines: 1 filter byte (0 = None) per row + width * 4 RGBA bytes - raw_lines = bytearray() - row_bytes = width * 4 - for y in range(height): - raw_lines.append(0) - raw_lines.extend(rgba_bytes[y * row_bytes:(y + 1) * row_bytes]) - - idat_data = zlib.compress(bytes(raw_lines)) - idat_crc = zlib.crc32(b"IDAT" + idat_data) & 0xFFFFFFFF - idat = struct.pack(">I4s", len(idat_data), b"IDAT") + idat_data + struct.pack(">I", idat_crc) - - iend_crc = zlib.crc32(b"IEND") & 0xFFFFFFFF - iend = struct.pack(">I4s", 0, b"IEND") + struct.pack(">I", iend_crc) - return sig + ihdr + idat + iend - - -def _simple_triangle_primitive( - *, - has_normals: bool = True, - has_uvs: bool = True, - offset: float = 0.0, -) -> dict: - """Return a single synthetic triangle primitive.""" - positions = [ - (0.0 + offset, 0.0, 0.0), - (1.0 + offset, 0.0, 0.0), - (0.0 + offset, 1.0, 0.0), - ] - indices = [0, 1, 2] - prim: dict = { - "positions": positions, - "indices": indices, - } - if has_normals: - prim["normals"] = [(0.0, 0.0, 1.0), (0.0, 0.0, 1.0), (0.0, 0.0, 1.0)] - if has_uvs: - prim["uvs"] = [(0.0, 0.0), (1.0, 0.0), (0.0, 1.0)] - return prim - - -class TestGlbContainerHeaderAndChunkPadding(unittest.TestCase): - """Tests glTF 2.0 binary (.glb) 12-byte header and 8-byte chunk headers with padding.""" - - def test_glb_header_12_bytes_structure(self): - prim = _simple_triangle_primitive() - glb_bytes = glb_writer.build_glb([prim]) - - self.assertGreaterEqual(len(glb_bytes), 20) - magic, version, total_length = struct.unpack_from("<4sII", glb_bytes, 0) - self.assertEqual(magic, glb_writer.GLB_MAGIC) - self.assertEqual(magic, b"glTF") - self.assertEqual(version, glb_writer.GLB_VERSION) - self.assertEqual(version, 2) - self.assertEqual(total_length, len(glb_bytes)) - self.assertEqual(total_length % 4, 0) - - def test_json_chunk_header_and_space_padding(self): - prim = _simple_triangle_primitive() - glb_bytes = glb_writer.build_glb([prim]) - - json_len, json_type = struct.unpack_from(" 0: - self.assertEqual(json_raw[-pad_len:], b" " * pad_len) - - def test_bin_chunk_header_and_null_padding(self): - prim = _simple_triangle_primitive() - glb_bytes = glb_writer.build_glb([prim]) - - json_len, _ = struct.unpack_from(" COMPONENT_UNSIGNED_SHORT (5123) - small_prim = _simple_triangle_primitive() - glb_bytes = glb_writer.build_glb([small_prim]) - summary = glb_writer.read_glb_summary(glb_bytes) - idx_acc = summary["json"]["accessors"][summary["json"]["meshes"][0]["primitives"][0]["indices"]] - self.assertEqual(idx_acc["componentType"], glb_writer.COMPONENT_UNSIGNED_SHORT) - self.assertEqual(idx_acc["componentType"], 5123) - self.assertEqual(idx_acc["type"], "SCALAR") - self.assertEqual(idx_acc["count"], 3) - - # Large primitive: 65536 vertices -> COMPONENT_UNSIGNED_INT (5125) - vert_count = 65536 - large_positions = [(float(i % 10), float(i // 10), 0.0) for i in range(vert_count)] - # Triangle referencing index 0, 1, and 65535 - large_indices = [0, 1, 65535] - large_prim = { - "positions": large_positions, - "indices": large_indices, - } - glb_bytes_large = glb_writer.build_glb([large_prim]) - summary_large = glb_writer.read_glb_summary(glb_bytes_large) - idx_acc_large = summary_large["json"]["accessors"][ - summary_large["json"]["meshes"][0]["primitives"][0]["indices"] - ] - self.assertEqual(idx_acc_large["componentType"], glb_writer.COMPONENT_UNSIGNED_INT) - self.assertEqual(idx_acc_large["componentType"], 5125) - self.assertEqual(idx_acc_large["count"], 3) - - # Unpack uint32 from BIN payload - json_len, _ = struct.unpack_from(" alpha 1.0 - "double_sided": True, - } - } - glb_bytes = glb_writer.build_glb([prim], materials=materials) - summary = glb_writer.read_glb_summary(glb_bytes) - mat = summary["json"]["materials"][0] - self.assertTrue(mat.get("doubleSided")) - self.assertEqual(mat["pbrMetallicRoughness"]["baseColorFactor"], [0.2, 0.4, 0.6, 1.0]) - - def _alpha_materials(self, materials: dict, *, has_uvs: bool = False) -> list[dict]: - prims = [ - dict(_simple_triangle_primitive(has_uvs=has_uvs, offset=5.0 * i), material=key) - for i, key in enumerate(materials) - ] - return glb_writer.read_glb_summary(glb_writer.build_glb(prims, materials=materials))["json"]["materials"] - - def test_alpha_mode_inferred_and_explicit(self): - red = (1.0, 0.0, 0.0) - mats = self._alpha_materials({ - "plain": {"base_color_factor": red}, - "half": {"base_color_factor": red + (0.5,)}, - "opaque": {"base_color_factor": red + (0.5,), "alpha_mode": "OPAQUE"}, - "blend": {"base_color_factor": red, "alpha_mode": "BLEND"}, - "mask_default": {"alpha_mode": "MASK"}, - "mask_low": {"base_color_factor": red + (0.4,), "alpha_mode": "MASK", "alpha_cutoff": 0.5}, - }) - modes = {m["name"]: (m.get("alphaMode"), m.get("alphaCutoff")) for m in mats} - self.assertEqual(modes, { - "plain": (None, None), - "half": ("BLEND", None), - "opaque": (None, None), - "blend": ("BLEND", None), - "mask_default": ("MASK", None), - "mask_low": ("MASK", 0.5), - }) - alphas = [m["pbrMetallicRoughness"]["baseColorFactor"][3] for m in mats] - self.assertEqual(alphas, [1.0, 0.5, 0.5, 1.0, 1.0, 0.4]) - - def test_opaque_materials_stay_byte_identical(self): - prim = dict(_simple_triangle_primitive(), material="m1") - plain = glb_writer.build_glb([prim], {"m1": {"base_color_factor": (1.0, 0.0, 0.0)}}) - explicit = glb_writer.build_glb( - [prim], {"m1": {"base_color_factor": (1.0, 0.0, 0.0, 1.0), "alpha_mode": "OPAQUE"}}, - ) - self.assertEqual(plain, explicit) - self.assertNotIn(b"alphaMode", plain) - self.assertNotIn(b"alphaMode", glb_writer.build_glb([prim])) - - def test_alpha_mode_on_deduplicated_textured_material(self): - png = _make_synthetic_png(1, 1, bytes([0, 255, 0, 0])) - materials = { - "leaf": {"png_bytes": png, "alpha_mode": "MASK", "alpha_cutoff": 0.25}, - "no_mode": {"png_bytes": png}, # transparent texel alone never selects a mode - } - prims = [ - dict(_simple_triangle_primitive(offset=o), material=key) - for o, key in ((0.0, "leaf"), (5.0, "leaf"), (10.0, "no_mode")) - ] - gltf = glb_writer.read_glb_summary(glb_writer.build_glb(prims, materials=materials))["json"] - leaf, no_mode = gltf["materials"] - self.assertEqual((leaf["alphaMode"], leaf["alphaCutoff"]), ("MASK", 0.25)) - self.assertNotIn("alphaMode", no_mode) - self.assertEqual([p["material"] for p in gltf["meshes"][0]["primitives"]], [0, 0, 1]) - self.assertEqual(len(gltf["textures"]), 1) - - def test_invalid_alpha_specs_raise_error(self): - prim = dict(_simple_triangle_primitive(has_uvs=False), material="m1") - for spec in ( - {"alpha_mode": "blend"}, - {"alpha_mode": "TRANSPARENT"}, - {"alpha_mode": 1}, - {"alpha_cutoff": 0.5}, - {"alpha_mode": "BLEND", "alpha_cutoff": 0.5}, - {"alpha_mode": "MASK", "alpha_cutoff": float("nan")}, - {"alpha_mode": "MASK", "alpha_cutoff": -0.1}, - {"alpha_mode": "MASK", "alpha_cutoff": True}, - {"alpha_mode": "MASK", "alpha_cutoff": "0.5"}, - ): - with self.subTest(spec=spec), self.assertRaises(glb_writer.GlbError): - glb_writer.build_glb([prim], {"m1": spec}) - - -class TestGlbWriterValidationAndErrors(unittest.TestCase): - """Tests error cases and validation in build_glb and helper functions.""" - - def test_each_position_has_three_components_before_normals_are_generated(self): - # The total is nine floats, but flattening these rows moves 9 into the next vertex's X. - positions = [(0.0, 0.0, 0.0, 9.0), (1.0, 0.0), (0.0, 1.0, 0.0)] - for code in (glb_writer._FLOAT32_CODE, None): - for has_normals in (False, True): - with self.subTest(packing=code, has_normals=has_normals): - prim = _simple_triangle_primitive(has_normals=has_normals) - prim["positions"] = positions - with mock.patch.object(glb_writer, "_FLOAT32_CODE", code): - with self.assertRaisesRegex(glb_writer.GlbError, "expected 3 floats per vertex"): - glb_writer.build_glb([prim]) - - def test_invalid_indices_without_normals_raise_glb_error(self): - for invalid in (3, -4): - with self.subTest(index=invalid): - prim = _simple_triangle_primitive(has_normals=False) - prim["indices"] = [0, 1, invalid] - with self.assertRaisesRegex(glb_writer.GlbError, "index out of range"): - glb_writer.build_glb([prim]) - - def test_valid_triangle_packing_with_generated_and_explicit_normals(self): - positions = struct.pack("<9f", 0, 0, 0, 1, 0, 0, 0, 1, 0) - normals = struct.pack("<9f", 0, 0, 1, 0, 0, 1, 0, 0, 1) - indices = struct.pack("<3H", 0, 1, 2) - for code in (glb_writer._FLOAT32_CODE, None): - for has_normals in (False, True): - with self.subTest(packing=code, has_normals=has_normals): - prim = _simple_triangle_primitive(has_normals=has_normals) - with mock.patch.object(glb_writer, "_FLOAT32_CODE", code): - packed = glb_writer.pack_primitive(prim) - self.assertEqual(packed["positions"], positions) - self.assertEqual(packed["normals"], normals) - self.assertEqual(packed["indices"], indices) - self.assertEqual(packed["min"], [0.0, 0.0, 0.0]) - self.assertEqual(packed["max"], [1.0, 1.0, 0.0]) - - def test_malformed_positions_do_not_replace_an_existing_glb(self): - prim = _simple_triangle_primitive() - prim["positions"] = [(0.0, 0.0, 0.0, 9.0), (1.0, 0.0), (0.0, 1.0, 0.0)] - with tempfile.TemporaryDirectory() as folder: - path = os.path.join(folder, "model.glb") - previous = glb_writer.build_glb([_simple_triangle_primitive()]) - with open(path, "wb") as f: - f.write(previous) - with self.assertRaisesRegex(glb_writer.GlbError, "expected 3 floats per vertex"): - glb_writer.write_glb(path, [prim]) - with open(path, "rb") as f: - self.assertEqual(f.read(), previous) - self.assertEqual(os.listdir(folder), ["model.glb"]) - - def test_empty_primitives_raises_error(self): - with self.assertRaises(glb_writer.GlbError): - glb_writer.build_glb([]) - - with self.assertRaises(glb_writer.GlbError): - glb_writer.build_glb([{"positions": [], "indices": []}]) - - def test_non_multiple_of_3_indices_raises_error(self): - prim = { - "positions": [(0.0, 0.0, 0.0), (1.0, 0.0, 0.0)], - "indices": [0, 1], # 2 indices - } - with self.assertRaises(glb_writer.GlbError): - glb_writer.build_glb([prim]) - - def test_out_of_bounds_indices_raise_error(self): - prim_negative = { - "positions": [(0.0, 0.0, 0.0), (1.0, 0.0, 0.0), (0.0, 1.0, 0.0)], - "normals": [(0.0, 0.0, 1.0)] * 3, - "indices": [-1, 0, 1], - } - with self.assertRaises(glb_writer.GlbError): - glb_writer.build_glb([prim_negative]) - - prim_exceed = { - "positions": [(0.0, 0.0, 0.0), (1.0, 0.0, 0.0), (0.0, 1.0, 0.0)], - "normals": [(0.0, 0.0, 1.0)] * 3, - "indices": [0, 1, 3], # 3 >= len(positions) - } - with self.assertRaises(glb_writer.GlbError): - glb_writer.build_glb([prim_exceed]) - - def test_mismatched_attribute_lengths_raise_error(self): - prim_bad_normals = { - "positions": [(0.0, 0.0, 0.0), (1.0, 0.0, 0.0), (0.0, 1.0, 0.0)], - "normals": [(0.0, 1.0, 0.0)], # 1 != 3 - "indices": [0, 1, 2], - } - with self.assertRaises(glb_writer.GlbError): - glb_writer.build_glb([prim_bad_normals]) - - prim_bad_uvs = { - "positions": [(0.0, 0.0, 0.0), (1.0, 0.0, 0.0), (0.0, 1.0, 0.0)], - "uvs": [(0.0, 0.0)], # 1 != 3 - "indices": [0, 1, 2], - } - with self.assertRaises(glb_writer.GlbError): - glb_writer.build_glb([prim_bad_uvs]) - - def test_non_finite_floats_raise_error(self): - prim_nan = { - "positions": [(float("nan"), 0.0, 0.0), (1.0, 0.0, 0.0), (0.0, 1.0, 0.0)], - "indices": [0, 1, 2], - } - with self.assertRaises(glb_writer.GlbError): - glb_writer.build_glb([prim_nan]) - - prim_inf = { - "positions": [(float("inf"), 0.0, 0.0), (1.0, 0.0, 0.0), (0.0, 1.0, 0.0)], - "indices": [0, 1, 2], - } - with self.assertRaises(glb_writer.GlbError): - glb_writer.build_glb([prim_inf]) - - def test_invalid_base_color_factors_raise_error(self): - prim = _simple_triangle_primitive() - bad_factors = [ - "red", - [1.0, 0.0], # only 2 elements - [1.0, 0.0, 0.0, 0.0, 1.0], # 5 elements - [-0.1, 0.5, 0.5, 1.0], # negative - [1.1, 0.5, 0.5, 1.0], # > 1.0 - [float("nan"), 0.5, 0.5, 1.0], - ] - for bad in bad_factors: - with self.subTest(bad=bad): - with self.assertRaises(glb_writer.GlbError): - glb_writer.build_glb([prim], materials={"": {"base_color_factor": bad}}) - - -class TestReadGlbSummaryValidation(unittest.TestCase): - """Tests container framing and validation in read_glb_summary.""" - - @staticmethod - def _container(doc, *chunks): - json_bytes = json.dumps(doc).encode("utf-8") - json_bytes += b" " * ((-len(json_bytes)) % 4) - body = b"".join( - struct.pack(" 4 - } - jb = json.dumps(doc).encode("utf-8") - jb += b" " * ((-len(jb)) % 4) - bb = b"\x00\x00\x00\x00" - total = 12 + 8 + len(jb) + 8 + len(bb) - raw = ( - b"glTF" - + struct.pack(" None: - text = "v 0 0 0\nv 1 0 0\nv 0 1 0\nf 1 2 3\n" - expected = glb_writer.parse_obj(text, is_path=False) - self.assertEqual(expected[0]["indices"], [0, 1, 2]) - - with tempfile.TemporaryDirectory() as folder: - source = os.path.join(folder, "triangle.obj") - with open(source, "w", encoding="utf-8-sig", newline="\n") as f: - f.write(text) - with self.subTest(source="file"): - self.assertEqual(glb_writer.parse_obj(source), expected) - - with self.subTest(source="in-memory text"): - self.assertEqual(glb_writer.parse_obj("\ufeff" + text, is_path=False), expected) - - def test_parse_obj_zup_to_yup(self): - # OBJ coordinate (1, 2, 3) in Z-up becomes (1, 3, -2) in glTF Y-up - obj_text = "\n".join([ - "v 1 2 3", - "v 2 2 3", - "v 1 3 3", - "f 1 2 3", - ]) - prims = glb_writer.parse_obj(obj_text, is_path=False, up_axis="z") - self.assertEqual(len(prims), 1) - positions = prims[0]["positions"] - self.assertIn((1.0, 3.0, -2.0), positions) - self.assertIn((2.0, 3.0, -2.0), positions) - self.assertIn((1.0, 3.0, -3.0), positions) - - def test_parse_obj_yup_identity(self): - obj_text = "\n".join([ - "v 1 2 3", - "v 2 2 3", - "v 1 3 3", - "f 1 2 3", - ]) - prims = glb_writer.parse_obj(obj_text, is_path=False, up_axis="y") - self.assertEqual(len(prims), 1) - positions = prims[0]["positions"] - self.assertEqual(positions, [(1.0, 2.0, 3.0), (2.0, 2.0, 3.0), (1.0, 3.0, 3.0)]) - - def test_parse_obj_uv_v_flip(self): - # Wavefront UV (u, v) -> glTF UV (u, 1.0 - v) - obj_text = "\n".join([ - "v 0 0 0", - "v 1 0 0", - "v 0 1 0", - "vt 0.25 0.75", - "vt 0.5 0.2", - "vt 0.0 1.0", - "f 1/1 2/2 3/3", - ]) - prims = glb_writer.parse_obj(obj_text, is_path=False, up_axis="y") - uvs = prims[0]["uvs"] - self.assertAlmostEqual(uvs[0][0], 0.25) - self.assertAlmostEqual(uvs[0][1], 0.25) # 1.0 - 0.75 - self.assertAlmostEqual(uvs[1][0], 0.5) - self.assertAlmostEqual(uvs[1][1], 0.8) # 1.0 - 0.2 - self.assertAlmostEqual(uvs[2][0], 0.0) - self.assertAlmostEqual(uvs[2][1], 0.0) # 1.0 - 1.0 - - def test_glb_generated_normals_split_at_explicit_obj_smoothing_boundaries(self) -> None: - vertices = ["v 0 0 0", "v 1 0 0", "v 0 1 0", "v 0 0 1"] - for directives in (("s off", "s off"), ("s 0", "s 0"), ("s 1", "s 2")): - with self.subTest(directives=directives): - obj = "\n".join([*vertices, directives[0], "f 1 2 3", directives[1], "f 2 1 4"]) - prims = glb_writer.parse_obj(obj, is_path=False, up_axis="y") - data = glb_writer.build_glb(prims) - gltf = glb_writer.read_glb_summary(data)["json"] - mesh = gltf["meshes"][0]["primitives"][0] - accessor = gltf["accessors"][mesh["attributes"]["NORMAL"]] - view = gltf["bufferViews"][accessor["bufferView"]] - json_length = struct.unpack_from(" None: - obj = """\ -v 0 0 0 -v 1 0 0 -v 0 1 0 -vn 1e-200 0 0 -vn 1.7e308 0 1.7e308 -vn 5e-324 0 5e-324 -f 1//1 2//2 3//3 -""" - primitives = glb_writer.parse_obj(obj, is_path=False, up_axis="y") - data = glb_writer.build_glb(primitives) - gltf = glb_writer.read_glb_summary(data)["json"] - normal_idx = gltf["meshes"][0]["primitives"][0]["attributes"]["NORMAL"] - normals = gltf["accessors"][normal_idx] - view = gltf["bufferViews"][normals["bufferView"]] - json_len, = struct.unpack_from(" None: - text = ( - "v 0 0 0\nv 1 0 0\nv 2 0 0\nv 2 1 0\nv 0 1 0\n" - "vt 0 0.25\nvt 0.75 0.25\nf 1/1 2/2 3/1 4/1 5/1\n" - ) - primitive, = glb_writer.parse_obj(text, is_path=False, up_axis="y") - packed = glb_writer.pack_primitive(primitive) - positions = list(struct.iter_unpack("<3f", packed["positions"])) - uvs = list(struct.iter_unpack("<2f", packed["uvs"])) - self.assertEqual(uvs[positions.index((1, 0, 0))], (0.75, 0.75)) - - areas = [] - for triangle in struct.iter_unpack("<3H", packed["indices"]): - a, b, c = (positions[i] for i in triangle) - areas.append((b[0] - a[0]) * (c[1] - a[1]) - (b[1] - a[1]) * (c[0] - a[0])) - self.assertEqual(len(areas), 3) - self.assertTrue(all(area > 0 for area in areas), areas) - self.assertEqual(sum(areas), 4.0) - - def test_notched_face_preserves_its_surface_and_corner_attributes(self): - # A square with a 2 x 3 notch, including a collinear point on its base. - # Embed the outline in YZ so the down-axis projection matters. - outline = [(0, 0), (2, 0), (4, 0), (4, 4), (3, 4), (3, 1), (1, 1), (1, 4), (0, 4)] - vertices = [f"v 10 {20 + u} {30 + v}" for u, v in outline] - uvs = [f"vt {i / 16} 0.25" for i in range(len(outline))] - for reverse in (False, True): - for scale in (1, -1): - with self.subTest(reverse=reverse, scale=scale): - order = list(range(len(outline))) - if reverse: - order.reverse() - text = "\n".join(vertices + uvs + ["f " + " ".join(f"{i + 1}/{i + 1}" for i in order)]) - prim, = glb_writer.parse_obj(text, is_path=False, up_axis="y", scale=scale) - positions = prim["positions"] - expected_uvs = { - (10 * scale, (20 + u) * scale, (30 + v) * scale): (i / 16, 0.75) - for i, (u, v) in enumerate(outline) - } - self.assertEqual(dict(zip(positions, prim["uvs"])), expected_uvs) - sign = (-1 if reverse else 1) * scale - self.assertEqual(set(prim["normals"]), {(sign, 0, 0)}) - idx = prim["indices"] - self.assertEqual(len(idx), (len(outline) - 2) * 3) - total = 0 - for i in range(0, len(idx), 3): - a, b, c = (positions[j] for j in idx[i:i + 3]) - area2 = (b[1] - a[1]) * (c[2] - a[2]) - (b[2] - a[2]) * (c[1] - a[1]) - self.assertGreater(area2 * sign, 0) - total += abs(area2) - self.assertEqual(total, 2 * (4 * 4 - 2 * 3)) - - def test_valid_first_corner_fan_keeps_its_index_order(self): - for shape in ([(0, 0), (2, 0), (3, 2), (1, 3), (-1, 2)], - [(2, 1), (4, 0), (2, 4), (0, 0)]): - with self.subTest(shape=shape): - lines = [f"v {x} {y} 0" for x, y in shape] - lines.append("f " + " ".join(str(i + 1) for i in range(len(shape)))) - prim, = glb_writer.parse_obj("\n".join(lines), is_path=False, up_axis="y") - self.assertEqual(prim["positions"], [(x, y, 0) for x, y in shape]) - self.assertEqual(prim["indices"], [j for i in range(1, len(shape) - 1) for j in (0, i, i + 1)]) - - -class TestGlbWriterMainCli(unittest.TestCase): - """Tests the command-line entrypoint of tools/glb_writer.py.""" - - def test_main_cli_execution(self): - with tempfile.TemporaryDirectory() as tmp_dir: - obj_path = os.path.join(tmp_dir, "input.obj") - glb_path = os.path.join(tmp_dir, "output.glb") - with open(obj_path, "w", encoding="utf-8") as f: - f.write("v 0 0 0\nv 1 0 0\nv 0 1 0\nf 1 2 3\n") - - with contextlib.redirect_stdout(io.StringIO()), contextlib.redirect_stderr(io.StringIO()): - ret = glb_writer.main([obj_path, glb_path, "--up", "y"]) - self.assertEqual(ret, 0) - self.assertTrue(os.path.isfile(glb_path)) - - def test_main_cli_error_handling(self): - with tempfile.TemporaryDirectory() as tmp_dir: - bad_obj = os.path.join(tmp_dir, "non_existent.obj") - glb_path = os.path.join(tmp_dir, "output.glb") - with contextlib.redirect_stdout(io.StringIO()), contextlib.redirect_stderr(io.StringIO()): - ret = glb_writer.main([bad_obj, glb_path]) - self.assertEqual(ret, 1) - - def test_main_cli_refuses_to_overwrite_the_input(self): - with tempfile.TemporaryDirectory() as tmp_dir: - obj_path = os.path.join(tmp_dir, "input.obj") - text = "v 0 0 0\nv 1 0 0\nv 0 1 0\nf 1 2 3\n" - with open(obj_path, "w", encoding="utf-8", newline="") as f: - f.write(text) - links = [obj_path] - try: - link = os.path.join(tmp_dir, "alias.obj") - os.link(obj_path, link) - links.append(link) - except (OSError, NotImplementedError): - pass - for out in links: - err = io.StringIO() - with contextlib.redirect_stdout(io.StringIO()), contextlib.redirect_stderr(err): - ret = glb_writer.main([obj_path, out]) - self.assertEqual(ret, 1) - self.assertIn("overwrite the input", err.getvalue()) - self.assertNotIn("Traceback", err.getvalue()) - with open(obj_path, encoding="utf-8", newline="") as f: - self.assertEqual(f.read(), text) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/test_glb_writer_buffers.py b/tests/test_glb_writer_buffers.py deleted file mode 100644 index 322cd3438..000000000 --- a/tests/test_glb_writer_buffers.py +++ /dev/null @@ -1,45 +0,0 @@ -"""Test external buffers in synthetic binary glTF containers.""" -from __future__ import annotations - -import json -import os -import struct -import sys -import unittest - -ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) -TOOLS = os.path.join(ROOT, "tools") -if TOOLS not in sys.path: - sys.path.insert(0, TOOLS) - -import glb_writer - - -def _external_buffer_glb(view_length: int) -> bytes: - doc = { - "asset": {"version": "2.0"}, - "buffers": [{"uri": "sample.bin", "byteLength": 4}], - "bufferViews": [{"buffer": 0, "byteLength": view_length}], - } - json_bytes = json.dumps(doc).encode("utf-8") - json_bytes += b" " * ((-len(json_bytes)) % 4) - return ( - struct.pack("<4sII", b"glTF", 2, 20 + len(json_bytes)) - + struct.pack(" 4\)"): - glb_writer.read_glb_summary(_external_buffer_glb(view_length=5)) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/test_gpu_blocked_program.py b/tests/test_gpu_blocked_program.py deleted file mode 100644 index 8e957f3d3..000000000 --- a/tests/test_gpu_blocked_program.py +++ /dev/null @@ -1,83 +0,0 @@ -"""A test program Windows refuses to start (Smart App Control blocks fresh unsigned builds: WinError 4551) is one -failed test with the reason, not a traceback that ends the run. The error is faked, so this runs on any OS.""" -from pathlib import Path -import sys -import tempfile -import unittest -from unittest.mock import patch - -ROOT = Path(__file__).resolve().parents[1] -sys.path.insert(0, str(ROOT / "runtime" / "test" / "shaders")) -sys.path.insert(0, str(ROOT / "scripts")) -import check -import run_gpu_tests - - -def blocked(winerror=4551): - """The OSError Python raises on Windows when Application Control refuses to start a program.""" - e = PermissionError(13, "An Application Control policy has blocked this file") - e.winerror = winerror - return e - - -class CheckPy(unittest.TestCase): - def test_blocked_program_is_a_failed_test(self): - with patch.object(check.subprocess, "run", side_effect=blocked()): - code, out = check.run("/build/vk_compute_test.exe", "cs_lds.spv", "4", "mirror64") - self.assertNotEqual(code, 0) - self.assertNotEqual(code, check.UNSUPPORTED) # a blocked program is not a device limit: no SKIP - self.assertIn("could not start vk_compute_test.exe", out) - self.assertIn("Application Control", out) - - def test_blocked_mesh_harness_is_a_failed_test(self): - with tempfile.TemporaryDirectory() as tmp: - for name in ("ms_w64x_ballot", "fs_passthru"): - (Path(tmp) / f"{name}.spv").touch() - with patch.object(check.subprocess, "run", side_effect=blocked()): - problem = check.mesh_w64x_test(tmp, tmp, "ms_w64x_ballot") - self.assertNotIsInstance(problem, check.Skip) - self.assertIn("could not start vk_harness", problem) - self.assertIn("Application Control", problem) - - def test_blocked_pixel_harness_gives_the_reason(self): - with tempfile.TemporaryDirectory() as tmp: - (Path(tmp) / "ps_ops.spv").touch() - with patch.object(check.subprocess, "run", side_effect=blocked()): - problem = check.pixel_test(tmp, tmp, "ps_ops") - self.assertNotIsInstance(problem, check.Skip) - self.assertIn("could not start vk_harness", problem) - self.assertIn("Application Control", problem) - - def test_other_start_errors_quote_the_error(self): - with patch.object(check.subprocess, "run", side_effect=OSError(8, "Exec format error")): - code, out = check.run("/build/vk_harness", "a.spv") - self.assertNotEqual(code, 0) - self.assertIn("could not start vk_harness: [Errno 8] Exec format error", out) - self.assertNotIn("Application Control", out) - - def test_missing_programs_still_say_how_to_build_them(self): - with tempfile.TemporaryDirectory() as tmp: - with patch.object(check.subprocess, "run", side_effect=FileNotFoundError(2, "not found")): - with self.assertRaises(SystemExit) as stop: - check.run(str(Path(tmp) / "vk_compute_test"), "cs_lds.spv") - self.assertIn("Test programs not found", str(stop.exception)) - - def test_each_windows_refusal_names_who_refused(self): - for code, who in ((4551, "Application Control"), (1260, "software restriction policy"), - (225, "Microsoft Defender")): - self.assertIn(who, check.start_failure("vk_store_test.exe", blocked(code))) - - -class RunGpuTestsPy(unittest.TestCase): - def test_blocked_program_is_a_failed_test(self): - with patch.object(run_gpu_tests.subprocess, "run", side_effect=blocked()): - code, msg = run_gpu_tests.run_cmd(["C:/build/vk_compute_test.exe", "cs_bvh.spv", "1", "bvh"]) - self.assertNotEqual(code, 0) - self.assertNotEqual(code, run_gpu_tests.UNSUPPORTED) - self.assertIn("could not start vk_compute_test.exe", msg) - self.assertIn("Application Control", msg) - self.assertEqual(len(msg.splitlines()), 1) # one result line in the summary table - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/test_gpu_build_dir.py b/tests/test_gpu_build_dir.py deleted file mode 100644 index fcfaf40a7..000000000 --- a/tests/test_gpu_build_dir.py +++ /dev/null @@ -1,186 +0,0 @@ -"""run_gpu_tests.py and check.py find the test programs where the CMake generator put them: in the build folder -(Makefiles, Ninja) or in build/ (Visual Studio generator, TEST-38), and say which folder they picked. Fake -files only, so this runs on any OS.""" -from contextlib import redirect_stdout -from pathlib import Path -from unittest.mock import patch -import io -import os -import sys -import tempfile -import unittest - -ROOT = Path(__file__).resolve().parents[1] -sys.path.insert(0, str(ROOT / "runtime" / "test" / "shaders")) -sys.path.insert(0, str(ROOT / "scripts")) -import check -import run_gpu_tests - -PROGRAMS = tuple(t + check.EXE for t in check.TEST_PROGRAMS) - - -def touch(folder: Path, names=PROGRAMS, mtime=None): - folder.mkdir(parents=True, exist_ok=True) - for n in names: - f = folder / n - f.write_bytes(b"") - if mtime is not None: - os.utime(f, (mtime, mtime)) - - -class ResolveBuildDir(unittest.TestCase): - def setUp(self): - tmp = tempfile.TemporaryDirectory() - self.addCleanup(tmp.cleanup) - self.build = Path(tmp.name) / "build" - self.build.mkdir() - - def resolve(self): - return check.resolve_build_dir(str(self.build), PROGRAMS) - - def test_programs_directly_in_the_build_folder(self): - touch(self.build) - self.assertEqual(self.resolve(), str(self.build)) - - def test_visual_studio_generator_subfolder(self): - touch(self.build / "RelWithDebInfo") - self.assertEqual(self.resolve(), str(self.build / "RelWithDebInfo")) - - def test_release_subfolder(self): - touch(self.build / "Release") - self.assertEqual(self.resolve(), str(self.build / "Release")) - - def test_build_folder_wins_over_a_subfolder(self): - touch(self.build) - touch(self.build / "Release") - self.assertEqual(self.resolve(), str(self.build)) - - def test_most_recently_built_configuration_wins(self): - touch(self.build / "Debug", mtime=1_000_000) - touch(self.build / "Release", mtime=3_000_000) - touch(self.build / "RelWithDebInfo", mtime=2_000_000) - self.assertEqual(self.resolve(), str(self.build / "Release")) - - def test_a_configuration_missing_a_program_is_skipped(self): - touch(self.build / "Release", names=PROGRAMS[:2], mtime=9_000_000) # newer but incomplete - touch(self.build / "Debug", mtime=1_000_000) - self.assertEqual(self.resolve(), str(self.build / "Debug")) - - def test_nothing_found_returns_the_folder_given(self): - # so the "Test programs not found in " message names what the user passed - self.assertEqual(self.resolve(), str(self.build)) - touch(self.build / "Release", names=PROGRAMS[:1]) - self.assertEqual(self.resolve(), str(self.build)) - - def test_unknown_configuration_folder_is_not_searched(self): - touch(self.build / "Custom") - self.assertEqual(self.resolve(), str(self.build)) - - -class PickBuildDir(unittest.TestCase): - """The line that tells which folder was used (a #166 report names the build it ran).""" - - def setUp(self): - tmp = tempfile.TemporaryDirectory() - self.addCleanup(tmp.cleanup) - self.build = Path(tmp.name) / "build" - self.build.mkdir() - - def pick(self): - out = io.StringIO() - with redirect_stdout(out): - chosen = check.pick_build_dir(str(self.build), PROGRAMS) - return chosen, out.getvalue() - - def test_a_configuration_subfolder_is_named(self): - touch(self.build / "Release") - chosen, out = self.pick() - self.assertEqual(chosen, str(self.build / "Release")) - self.assertEqual(out, f"test programs: {self.build / 'Release'}\n") - - def test_several_configurations_name_the_candidates_and_the_newest_wins(self): - touch(self.build / "Debug", mtime=1_000_000) - touch(self.build / "RelWithDebInfo", mtime=2_000_000) - chosen, out = self.pick() - self.assertEqual(chosen, str(self.build / "RelWithDebInfo")) - self.assertEqual(out, f"test programs: {self.build / 'RelWithDebInfo'} (newest of RelWithDebInfo, Debug)\n") - - def test_the_build_folder_itself_prints_nothing(self): - touch(self.build) - touch(self.build / "Release") - self.assertEqual(self.pick(), (str(self.build), "")) - - def test_nothing_found_prints_nothing(self): - self.assertEqual(self.pick(), (str(self.build), "")) - - def test_not_found_message_names_the_searched_subfolders(self): - msg = check.not_found_message(str(self.build), ["vk_harness"]) - self.assertIn(f"Test programs not found in {self.build}: vk_harness", msg) - for c in check.CONFIG_DIRS: - self.assertIn(c, msg) - - -class MainUsesTheResolvedFolder(unittest.TestCase): - """The wiring: what resolve_build_dir finds is what the scripts hand to the code that runs the programs.""" - - def setUp(self): - tmp = tempfile.TemporaryDirectory() - self.addCleanup(tmp.cleanup) - self.tmp = Path(tmp.name) - self.build = self.tmp / "build" - touch(self.build / "Release", names=PROGRAMS) - - def test_run_gpu_tests_hands_the_configuration_folder_to_run_suite(self): - seen = [] - argv = ["run_gpu_tests.py", "--build", str(self.build)] - with (patch.object(sys, "argv", argv), - patch.object(run_gpu_tests, "run_suite", side_effect=lambda a, work: seen.append(a.build) or 0), - redirect_stdout(io.StringIO()) as out): - self.assertEqual(run_gpu_tests.main(), 0) - self.assertEqual([Path(p).resolve() for p in seen], [(self.build / "Release").resolve()]) - self.assertIn("test programs:", out.getvalue()) - - def test_run_gpu_tests_not_found_exits_with_the_searched_subfolders(self): - argv = ["run_gpu_tests.py", "--build", str(self.tmp / "empty")] - with patch.object(sys, "argv", argv), self.assertRaises(SystemExit) as e: - run_gpu_tests.main() - self.assertIn("RelWithDebInfo", str(e.exception)) - self.assertIn("Test programs not found in", str(e.exception)) - - def test_check_hands_the_configuration_folder_to_the_first_test(self): - class Stop(Exception): - pass - - def first_test(tools, *args, **kwargs): - raise Stop(tools) - - argv = ["check.py", str(self.tmp / "out"), str(self.build)] - with patch.object(sys, "argv", argv), patch.object(check, "compute_test", side_effect=first_test), \ - redirect_stdout(io.StringIO()) as out, self.assertRaises(Stop) as e: - check.main() - self.assertEqual(Path(e.exception.args[0]).resolve(), (self.build / "Release").resolve()) - self.assertIn("test programs:", out.getvalue()) - - -class MissingTestProgram(unittest.TestCase): - def test_missing_texture_executable_is_a_test_failure(self): - with tempfile.TemporaryDirectory() as tmp: - build = Path(tmp) - touch(build) - program = "vk_texture_test" + check.EXE - code, message = check.run(str(build / program)) - self.assertNotEqual(code, 0) - self.assertIn(program, message) - - def test_missing_core_executable_preserves_build_diagnostic(self): - with tempfile.TemporaryDirectory() as tmp: - build = Path(tmp) - touch(build, names=PROGRAMS[:-1]) - with self.assertRaises(SystemExit) as caught: - check.run(str(build / PROGRAMS[-1])) - self.assertIn(PROGRAMS[-1], str(caught.exception)) - self.assertIn("subfolders were searched", str(caught.exception)) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/test_gpu_test_timeout.py b/tests/test_gpu_test_timeout.py deleted file mode 100644 index d290862ee..000000000 --- a/tests/test_gpu_test_timeout.py +++ /dev/null @@ -1,122 +0,0 @@ -"""A GPU test program that hangs fails its own test instead of stalling the suite: run_gpu_tests.run_cmd and -check.run give each program LEONIDA_GPU_TEST_TIMEOUT seconds (default 120, 0 = no limit), then kill it. The hang -is a sleeping Python child, so no GPU is needed.""" -from contextlib import redirect_stdout -import io -import os -from pathlib import Path -import subprocess -import sys -import tempfile -import time -from types import SimpleNamespace -import unittest -from unittest.mock import patch - -ROOT = Path(__file__).resolve().parents[1] -sys.path.insert(0, str(ROOT / "scripts")) -sys.path.insert(0, str(ROOT / "runtime" / "test" / "shaders")) -import check -import run_gpu_tests - -HANG = [sys.executable, "-c", "import time; time.sleep(60)"] -QUICK = [sys.executable, "-c", "print('ok')"] - - -class Limit(unittest.TestCase): - def limit(self, value): - env = {k: v for k, v in os.environ.items() if k != "LEONIDA_GPU_TEST_TIMEOUT"} - if value is not None: - env["LEONIDA_GPU_TEST_TIMEOUT"] = value - with patch.dict(os.environ, env, clear=True): - return check.gpu_test_timeout() - - def test_default_and_override(self): - self.assertEqual(self.limit(None), check.DEFAULT_GPU_TEST_TIMEOUT) - self.assertEqual(self.limit(""), check.DEFAULT_GPU_TEST_TIMEOUT) - self.assertEqual(self.limit(" 2.5 "), 2.5) - - def test_zero_or_negative_means_no_limit(self): - self.assertIsNone(self.limit("0")) - self.assertIsNone(self.limit("-1")) - - def test_non_numeric_or_non_finite_limit_is_an_error(self): - for bad in ("soon", "nan", "inf", "-inf", "1e9999"): - with self.subTest(bad=bad): - with self.assertRaises(SystemExit) as ctx: - self.limit(bad) - message = str(ctx.exception.code) - self.assertIn("LEONIDA_GPU_TEST_TIMEOUT", message) - self.assertIn(repr(bad), message) - - -class HungProgram(unittest.TestCase): - def setUp(self): - patcher = patch.dict(os.environ, {"LEONIDA_GPU_TEST_TIMEOUT": "0.5"}) - patcher.start() - self.addCleanup(patcher.stop) - - def assert_killed(self, call): - start = time.monotonic() - rc, msg = call() - self.assertLess(time.monotonic() - start, 30) - self.assertNotEqual(rc, 0) - self.assertIn("timed out after 0.5 s", msg) - self.assertIn(os.path.basename(sys.executable), msg) - - def test_run_gpu_tests_run_cmd(self): - self.assert_killed(lambda: run_gpu_tests.run_cmd(HANG)) - - def test_check_run(self): - self.assert_killed(lambda: check.run(*HANG)) - - def test_texture_cases_use_the_timeout_from_the_shader_directory(self) -> None: - for name in ("ps_texture_sample", "ps_gather_wrap"): - with self.subTest(name=name), tempfile.TemporaryDirectory() as work: - args = SimpleNamespace(filter=f"{name}.asm", llvm_mc="llvm-mc", build=work) - spirv = Path(work, "spirv") - out = io.StringIO() - - def fake_run(cmd: list[str], **kwargs: object) -> subprocess.CompletedProcess[str]: - if cmd[0] == sys.executable: - (spirv / f"{name}.spv").touch() - return subprocess.CompletedProcess(cmd, 0, "", "") - self.assertEqual(Path(cmd[0]).stem, "vk_texture_test") - self.assertEqual(kwargs.get("cwd"), str(spirv)) - self.assertEqual(kwargs.get("timeout"), 0.5) - raise subprocess.TimeoutExpired(cmd, 0.5) - - with (patch.object(run_gpu_tests, "assemble_to_s", - side_effect=lambda _mc, _src, dst, _name: Path(dst).touch()), - patch.object(run_gpu_tests, "spirv_as"), - patch.object(run_gpu_tests, "bary_fallback", return_value=False), - patch.object(run_gpu_tests, "f16_interp_fallback", return_value=False), - patch.object(run_gpu_tests, "MESH_COMPUTE", False), - patch.object(run_gpu_tests.subprocess, "run", side_effect=fake_run), - redirect_stdout(out)): - self.assertEqual(run_gpu_tests.run_suite(args, work), 1) - self.assertRegex(out.getvalue(), rf"FAIL\s+{name}\s+.*timed out after 0\.5 s") - self.assertIn("0/1 passed", out.getvalue()) - - def test_quick_program_is_unaffected(self): - self.assertEqual(run_gpu_tests.run_cmd(QUICK), (0, "ok")) - rc, out = check.run(*QUICK) - self.assertEqual((rc, out.strip()), (0, "ok")) - - def test_translator_step_has_no_limit(self): - seen = {} - - def fake_run(cmd, **kw): - seen.update(kw) - raise OSError("stop here") - - with patch.object(run_gpu_tests.subprocess, "run", side_effect=fake_run): - run_gpu_tests.run_cmd(QUICK, gpu=False) - self.assertIsNone(seen["timeout"]) - with patch.object(run_gpu_tests.subprocess, "run", side_effect=fake_run): - run_gpu_tests.run_cmd(QUICK) - self.assertEqual(seen["timeout"], 0.5) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/test_gpu_unsupported_stage.py b/tests/test_gpu_unsupported_stage.py deleted file mode 100644 index 6c4bc0404..000000000 --- a/tests/test_gpu_unsupported_stage.py +++ /dev/null @@ -1,85 +0,0 @@ -"""TEST-18: a device without geometry or mesh shaders (MoltenVK, older GPUs) makes vk_harness exit 77; the -runners report that as SKIP, not as a failure.""" -import contextlib -import io -from pathlib import Path -import subprocess -import sys -import tempfile -from types import SimpleNamespace -import unittest -from unittest.mock import patch - -ROOT = Path(__file__).resolve().parents[1] -sys.path.insert(0, str(ROOT / "runtime" / "test" / "shaders")) -sys.path.insert(0, str(ROOT / "scripts")) -import check -import run_gpu_tests - - -class MeshCheckOnDeviceWithoutMeshShaders(unittest.TestCase): - """check.py's ms_w64x_ballot with a fake vk_harness.""" - - def run_mesh(self, code, stderr): - def harness(cmd, **_kw): - return subprocess.CompletedProcess(cmd, code, "", stderr) - - with tempfile.TemporaryDirectory() as tmp: - for name in ("ms_w64x_ballot", "fs_passthru"): - (Path(tmp) / f"{name}.spv").touch() - with patch.object(check.subprocess, "run", side_effect=harness): - return check.mesh_w64x_test(tmp, tmp, "ms_w64x_ballot") - - def test_missing_mesh_extension_skips(self): - problem = self.run_mesh(77, "device: fake (subgroup 32..32)\nunsupported: no VK_EXT_mesh_shader\n") - self.assertIsInstance(problem, check.Skip) - self.assertIn("no VK_EXT_mesh_shader", problem) - - def test_other_harness_errors_still_fail(self): - problem = self.run_mesh(1, "FAILED vkCreateDevice -> -8\n") - self.assertNotIsInstance(problem, check.Skip) - self.assertTrue(problem) - - -class RunGpuTestsUnsupportedDetail(unittest.TestCase): - def test_quotes_the_harness_reason(self): - msg = "device: MoltenVK (subgroup 32..32)\nunsupported: no geometryShader" - self.assertEqual(run_gpu_tests.unsupported_skip(msg), "SKIP (unsupported: no geometryShader)") - - def test_without_a_reason(self): - self.assertEqual(run_gpu_tests.unsupported_skip(""), "SKIP (unsupported device)") - - def test_harness_and_runners_agree_on_the_exit_code(self): - self.assertEqual(run_gpu_tests.UNSUPPORTED, check.UNSUPPORTED) - harness = (ROOT / "runtime" / "test" / "vk_harness.cpp").read_text() - for reason in ("unsupported: no VK_EXT_mesh_shader", "unsupported: no geometryShader"): - self.assertIn(reason, harness) - - - -class PixelTestOnDeviceWithoutAFeature(unittest.TestCase): - """run_gpu_tests.py's pixel branch with a fake vk_harness that exits 77 (no assembler or GPU needed).""" - - def test_the_skip_is_reported_once(self): - def fake_run_cmd(cmd, env=None, gpu=True): - if cmd[0] == sys.executable: # the translator: leave the .spv it would write - Path(cmd[cmd.index("--out") + 1], "ps_bary.spv").touch() - return 0, "" - return 77, "device: fake (subgroup 32..32)\nunsupported: no fragmentShaderBarycentric\n" - - out = io.StringIO() - with tempfile.TemporaryDirectory() as tmp: - args = SimpleNamespace(filter="ps_bary", llvm_mc="llvm-mc", build=tmp) - # the fake assembler still writes its .s: the runner copies this run's inputs before translating - fake_assemble = lambda _mc, _src, dst, _name: Path(dst).touch() - with (patch.object(run_gpu_tests, "assemble_to_s", side_effect=fake_assemble), - patch.object(run_gpu_tests, "spirv_as"), - patch.object(run_gpu_tests, "run_cmd", side_effect=fake_run_cmd), contextlib.redirect_stdout(out)): - self.assertEqual(run_gpu_tests.run_suite(args, tmp), 0) - rows = [line for line in out.getvalue().splitlines() if "ps_bary" in line] - self.assertEqual(len(rows), 1, out.getvalue()) - self.assertIn("SKIP (unsupported: no fragmentShaderBarycentric)", rows[0]) - self.assertIn("0/1 passed, 1 skipped", out.getvalue()) - -if __name__ == "__main__": - unittest.main() diff --git a/tests/test_gs_primitive_readback.py b/tests/test_gs_primitive_readback.py deleted file mode 100644 index f189e60ca..000000000 --- a/tests/test_gs_primitive_readback.py +++ /dev/null @@ -1,57 +0,0 @@ -"""GPU regression for translated GS strip cuts. Set LEONIDA_VK_HARNESS to the built vk_harness.""" -import os -from pathlib import Path -import struct -import subprocess - -import pytest - -from conftest import GS_TRI_DXBC, Shader, requires_tools - - -@requires_tools -def test_offscreen_geometry_strip_cuts(tmp_path): - harness = os.environ.get("LEONIDA_VK_HARNESS") - if not harness: - pytest.skip("set LEONIDA_VK_HARNESS to the built vk_harness") - - # Form a nondegenerate triangle with z=-1, w=1, entirely behind Vulkan's near clip plane. - vs = Shader(tmp_path, "vs_clipped", """ -v_lshlrev_b32_e32 v1, 1, v0 -v_and_b32_e32 v1, 2, v1 -v_and_b32_e32 v2, 2, v0 -v_cvt_f32_u32_e32 v1, v1 -v_cvt_f32_u32_e32 v2, v2 -v_mov_b32_e32 v3, -1.0 -v_mov_b32_e32 v4, 1.0 -exp pos0 v1, v2, v3, v4 done -exp param1 v1, v2, v3, v4 -s_endpgm -""") - ps = Shader(tmp_path, "ps_white", """ -v_mov_b32_e32 v0, 1.0 -exp mrt0 v0, v0, v0, v0 done -s_endpgm -""") - for shader in (vs, ps): - shader.validate(shader.translate()) - - fixture = Path(__file__).resolve().parents[1] / "runtime/test/shaders/gs_tri.asm" - triangle = fixture.read_text(encoding="utf-8") - # Three single-vertex strips produce zero triangles. One three-vertex strip produces one. - singles = triangle.replace("GS_OP_EMIT,", "GS_OP_EMIT_CUT,") - env = {key: value for key, value in os.environ.items() if not key.startswith("VKH_")} - for expected, asm in [(0, singles), (1, triangle)]: - gs = Shader(tmp_path, f"gs_strip_{expected}", asm, dxbc=GS_TRI_DXBC) - gs.validate(gs.translate()) - raw = tmp_path / f"{gs.name}.raw" - result = subprocess.run( - [harness, tmp_path / "vs_clipped.spv", tmp_path / "ps_white.spv", raw, "8", "8"], - env=dict(env, VKH_GS=str(tmp_path / f"{gs.name}.spv"), VKH_GS_PRIMITIVES="1"), - capture_output=True, text=True, timeout=30, - ) - if result.returncode == 77: - pytest.skip(result.stderr) - assert result.returncode == 0, result.stderr - assert f"gs_primitives={expected}" in result.stderr.splitlines(), result.stderr - assert raw.read_bytes() == struct.pack("<4f", -1, -1, -1, -1) * 64 diff --git a/tests/test_guest_scene_reference.py b/tests/test_guest_scene_reference.py deleted file mode 100644 index 3c0ed16dd..000000000 --- a/tests/test_guest_scene_reference.py +++ /dev/null @@ -1,149 +0,0 @@ -"""Fixed reference points for the synthetic guest's renderer and input trace (no GPU).""" -import argparse -import importlib.util -import json -from pathlib import Path -import struct -import subprocess -import sys -import tempfile -import unittest -from unittest import mock - - -path = Path(__file__).resolve().parents[1] / "scripts" / "run_guest_scene.py" -spec = importlib.util.spec_from_file_location("run_guest_scene", path) -runner = importlib.util.module_from_spec(spec) -spec.loader.exec_module(runner) - - -class GuestSceneReferenceTest(unittest.TestCase): - def test_trace_and_pixel_digest_at_scene_boundaries(self): - # These records were read back independently on the RTX 5090 and Apple M3 Max. - anchors = [ - (0, 512, 9, 8, 18, 1, 376597285, 314582078), - (137, 132, 44, 32, 153, 3, 3593765925, 2667449936), - (299, 320, 8, 58, 169, 2, 1840220197, 1732923390), - (300, 64, 8, 57, 177, 2, 1840220197, 1732923390), - (422, 4, 58, 8, 228, 1, 1662446373, 2331208379), - (599, 576, 58, 8, 30, 1, 1662446373, 2331208379), - ] - steps = runner.trace() - for frame, buttons, x, y, scene_byte, bias, low, high in anchors: - with self.subTest(frame=frame): - self.assertEqual(steps[frame], (buttons, x, y, scene_byte, bias)) - digest, _ = runner.predicted_image(x % 8, bias) - self.assertEqual(digest, (high << 32) | low) - - def test_pcm_envelope_and_period(self): - samples = struct.unpack("<11025h", runner.expected_pcm(9000)) - self.assertEqual(samples[0], 0) - self.assertEqual(samples[500:550], (9000,) * 50) - self.assertEqual(samples[550:600], (-9000,) * 50) - self.assertEqual(samples[-1], 0) - - - def test_redirected_cli_preserves_unicode_paths_and_guest_diagnostic(self): - # Force strict redirected text streams even on UTF-8 hosts. Invoke the real CLI with a - # small stand-in loader that produces a diagnostic and exits before rendering. - entry = ( - "import runpy, sys; " - "encoding, script = sys.argv[1:3]; del sys.argv[1:3]; " - "sys.stdout.reconfigure(encoding=encoding, errors='strict'); " - "sys.stderr.reconfigure(encoding=encoding, errors='strict'); " - "runpy.run_path(script, run_name='__main__')" - ) - with tempfile.TemporaryDirectory() as temp: - root = Path(temp) - (root / "spirv").mkdir() - loader = root / "loader.py" - diagnostic = "guest diagnostic: 測試" - loader.write_text(f"import os\nos.write(2, {diagnostic.encode()!r})\nraise SystemExit(7)\n", - encoding="ascii") - for encoding in ("cp1252", "utf-8"): - with self.subTest(encoding=encoding): - out = root / f"測試 café {encoding}" - result = subprocess.run( - [sys.executable, "-I", "-c", entry, encoding, str(path), "--wine", sys.executable, - "--loader", str(loader), "--guest", str(loader), "--shaders", str(root), "--out", str(out)], - capture_output=True, - ) - self.assertEqual(result.returncode, 1) - report = out / "report.json" - summary = json.loads(report.read_text(encoding="utf-8")) - self.assertEqual(summary["error"], "full: exit code 7") - self.assertEqual(summary["runs"]["full"]["outcome"], "exited") - self.assertEqual(summary["runs"]["full"]["returncode"], 7) - # The runner resolves --out before it writes (run_guest_scene.py:355), so the report path it - # prints is the physical one: on Windows the 8.3 name (RUNNER~1) is expanded, and on macOS the - # unresolved /var prefix only matched as a suffix of /private/var. - self.assertIn(str(report.resolve()).encode(encoding, "backslashreplace"), result.stdout) - self.assertIn(diagnostic.encode(encoding, "backslashreplace"), result.stderr) - self.assertNotIn(b"UnicodeEncodeError", result.stderr) - - def test_uncreatable_output_reports_clean_error(self): - with tempfile.TemporaryDirectory() as temp: - root = Path(temp) - (root / "spirv").mkdir() - placeholder = root / "placeholder.txt" - placeholder.write_bytes(b"synthetic input") - out = placeholder / "output" - result = subprocess.run( - [sys.executable, "-I", str(path), "--wine", sys.executable, - "--loader", str(placeholder), "--guest", str(placeholder), - "--shaders", str(root), "--out", str(out)], - capture_output=True, encoding="utf-8", errors="replace", timeout=20, - ) - self.assertEqual(result.returncode, 1, result.stdout + result.stderr) - self.assertIn(f"could not create output directory {out.resolve()}", result.stderr) - self.assertNotIn("Traceback", result.stderr) - self.assertEqual(result.stdout, "") - self.assertEqual(placeholder.read_bytes(), b"synthetic input") - - def test_launch_failure_preserves_run_record_and_logs(self): - with tempfile.TemporaryDirectory() as temp: - root = Path(temp) - (root / "spirv").mkdir() - bad_loader = root / "invalid.exe" - bad_loader.write_bytes(b"synthetic input that is not an executable") - bad_loader.chmod(0o700) - out = root / "output" - cmd = [sys.executable, "-I", str(path), "--loader", str(bad_loader), "--guest", str(bad_loader), - "--shaders", str(root), "--out", str(out)] - if sys.platform != "win32": - cmd += ["--wine", str(bad_loader), "--wine-arg=-a", "--wine-arg=path with spaces/wine"] - result = subprocess.run(cmd, capture_output=True, encoding="utf-8", timeout=20) - self.assertEqual(result.returncode, 1, result.stdout + result.stderr) - report = json.loads((out / "report.json").read_text(encoding="utf-8")) - self.assertIn("could not launch", report["error"]) - record = json.loads((out / "logs" / "full.json").read_text(encoding="utf-8")) - self.assertEqual(record, report["runs"]["full"]) - self.assertEqual(record["outcome"], "launch_failed") - self.assertIsNone(record["returncode"]) - # The runner resolves --loader, --guest and --shaders before it runs (scripts/run_guest_scene.py:348), - # so the record holds the physical path: on macOS /var/folders is a symlink to /private/var/folders. - self.assertEqual(record["cmd"][0], str(bad_loader.resolve())) - if sys.platform != "win32": - self.assertEqual(record["cmd"][1:3], ["-a", "path with spaces/wine"]) - self.assertTrue(record["launch_error"]) - for stream in ("stdout", "stderr"): - contents = (out / "logs" / f"full.{stream}.log").read_bytes() - self.assertEqual(record[f"{stream}_sha256"], runner.sha256(contents)) - - def test_timeout_has_its_own_run_outcome(self): - with tempfile.TemporaryDirectory() as temp: - root = Path(temp) - args = argparse.Namespace(wine=None, loader=root / "loader.exe", guest=root / "guest.exe", - shaders=root, play_audio=False) - session = runner.Session(args, root) - session.logs.mkdir() - with mock.patch.object(runner.subprocess, "run", side_effect=subprocess.TimeoutExpired("loader", 10)), \ - self.assertRaisesRegex(runner.Fail, "timed out"): - session.run("full", "full", root, root) - self.assertEqual(session.runs["full"]["outcome"], "timed_out") - self.assertIsNone(session.runs["full"]["returncode"]) - self.assertNotIn("launch_error", session.runs["full"]) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/test_hashdict.py b/tests/test_hashdict.py deleted file mode 100644 index ab5a8af7d..000000000 --- a/tests/test_hashdict.py +++ /dev/null @@ -1,723 +0,0 @@ -"""Unit tests for tools/hashdict.py: Jenkins one-at-a-time (joaat) hashing, string harvesting, -lookup CLI, case-insensitivity, and collision handling. - - python -I tests/test_hashdict.py -""" -import errno -import io -import json -import os -import subprocess -import sys -import tempfile -import unittest -from unittest import mock - -ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) -TOOL = os.path.join(ROOT, "tools", "hashdict.py") - -if ROOT not in sys.path: - sys.path.insert(0, ROOT) -if os.path.join(ROOT, "tools") not in sys.path: - sys.path.insert(0, os.path.join(ROOT, "tools")) - -import hashdict - - -class JenkinsHashTest(unittest.TestCase): - def test_empty_string(self): - self.assertEqual(hashdict.joaat(""), 0x00000000) - - def test_known_reference_vectors(self): - # Known Jenkins one-at-a-time reference vectors - self.assertEqual(hashdict.joaat("a"), 0xCA2E9442) - self.assertEqual(hashdict.joaat("apple"), 0x88F08EF3) - self.assertEqual(hashdict.joaat("the quick brown fox jumps over the lazy dog"), 0x2D1643CE) - # Canonical vehicle name hash documented in docs/design.md - self.assertEqual(hashdict.joaat("adder"), 0xB779A091) - - def test_case_insensitivity(self): - # joaat normalizes strings by lowercasing prior to hashing - self.assertEqual(hashdict.joaat("ADDER"), 0xB779A091) - self.assertEqual(hashdict.joaat("Adder"), 0xB779A091) - self.assertEqual(hashdict.joaat("aDdEr"), 0xB779A091) - self.assertEqual( - hashdict.joaat("vehicle_model/car01.wft"), - hashdict.joaat("VEHICLE_MODEL/CAR01.WFT"), - ) - self.assertEqual( - hashdict.joaat("Shader_Disasm:CodeBlock"), - hashdict.joaat("shader_disasm:codeblock"), - ) - - def test_unsigned_32bit_range(self): - test_strings = [ - "", - "x", - "test_token_123", - "very_long_string_identifier_" * 10, - "path/to/asset.bin", - ] - for s in test_strings: - h = hashdict.joaat(s) - self.assertIsInstance(h, int) - self.assertGreaterEqual(h, 0) - self.assertLessEqual(h, 0xFFFFFFFF) - self.assertEqual(h & 0xFFFFFFFF, h) - - def test_latin1_encoding_and_replacement(self): - # Latin-1 character in range 0-255: é hashes as the one byte 0xE9. "café" and "caf\xe9" are the same - # Python string, so the value is pinned (Latin-1 joaat, computed independently) instead of compared. - self.assertEqual(hashdict.joaat("caf\xe9"), 0xEEFBF723) - # Character outside Latin-1 range is replaced with '?' - self.assertEqual(hashdict.joaat("caf\u20ac"), hashdict.joaat("caf?")) - - -class StringHarvestTest(unittest.TestCase): - def test_harvest_basic_identifiers(self): - data = b"\x00\x01first_identifier\x00second_identifier\xff" - found = set() - hashdict.harvest(data, found, minlen=3) - self.assertIn("first_identifier", found) - self.assertIn("second_identifier", found) - - def test_harvest_delimiters_split(self): - # Strings are split by [./:\\] to extract nested token pieces - data = b"\x00folder/sub_dir\\file_item.ext:asset_name\x00" - found = set() - hashdict.harvest(data, found, minlen=3) - self.assertIn("folder/sub_dir\\file_item.ext:asset_name", found) - self.assertIn("folder", found) - self.assertIn("sub_dir", found) - self.assertIn("file_item", found) - self.assertIn("ext", found) - self.assertIn("asset_name", found) - - def test_harvest_minlen_threshold(self): - # Subparts shorter than minlen are filtered out - data = b"\x00ab.cde.f.ghij\x00" - found3 = set() - hashdict.harvest(data, found3, minlen=3) - self.assertNotIn("ab", found3) - self.assertNotIn("f", found3) - self.assertIn("cde", found3) - self.assertIn("ghij", found3) - - found4 = set() - hashdict.harvest(data, found4, minlen=4) - self.assertNotIn("cde", found4) - self.assertIn("ghij", found4) - - def test_harvest_short_standalone_identifiers(self): - # The default run pattern needs three bytes, so --min 1/2 must use a shorter matcher to - # keep one- and two-letter identifiers that stand alone (and still keep the longer ones). - data = b"\x00a\x00\x00ab\x00\x00abc\x00" - - found1 = set() - hashdict.harvest(data, found1, minlen=1) - self.assertIn("a", found1) - self.assertIn("ab", found1) - self.assertIn("abc", found1) - - found2 = set() - hashdict.harvest(data, found2, minlen=2) - self.assertNotIn("a", found2) - self.assertIn("ab", found2) - self.assertIn("abc", found2) - - found3 = set() - hashdict.harvest(data, found3, minlen=3) - self.assertNotIn("a", found3) - self.assertNotIn("ab", found3) - self.assertIn("abc", found3) - - -class LongRunHarvestTest(unittest.TestCase): - """A printable run longer than hashdict.MAX_NAME_LEN used to be cut at 201 characters, and the next match - started mid-run, so the component straddling the cut was lost and two fragments were added instead.""" - - def harvest(self, text): - found = set() - hashdict.harvest(b"\x00" + text.encode("ascii") + b"\x00", found, minlen=3) - return found - - def test_long_path_keeps_the_component_that_straddles_the_old_cut(self): - dirs = [f"dir_{i:02d}_abc" for i in range(15)] - dirs[-1] += "x" * (181 - len("/".join(dirs))) - path = "platform:/levels/" + "/".join(dirs) + "/props_lev_des_building_name.ytd" - self.assertEqual(len(path), 230) - self.assertTrue(path[:201].endswith("/pr")) # the old pattern cut inside "props_..." - found = self.harvest(path) - for part in ["platform", "levels", "props_lev_des_building_name", "ytd"] + dirs: - self.assertIn(part, found) - # no truncated prefix, no fragment of the straddling component, and the 230-character run is not a name - self.assertNotIn(path, found) - self.assertNotIn(path[:201], found) - self.assertNotIn("ops_lev_des_building_name", found) - self.assertNotIn("ops_lev_des_building_name.ytd", found) - - def test_delimiter_free_token_over_the_cap_adds_nothing(self): - token = "a" * (hashdict.MAX_NAME_LEN + 1) - self.assertEqual(self.harvest(token), set()) - - def test_run_of_exactly_the_cap_is_added_whole(self): - token = "n" * hashdict.MAX_NAME_LEN - self.assertEqual(self.harvest(token), {token}) - # with a delimiter: the whole run and its one piece of at least minlen ("d" is too short) - path = "d/" + "n" * (hashdict.MAX_NAME_LEN - 2) - self.assertEqual(len(path), hashdict.MAX_NAME_LEN) - self.assertEqual(self.harvest(path), {path, "n" * (hashdict.MAX_NAME_LEN - 2)}) - - -class LookupCLITest(unittest.TestCase): - def setUp(self): - self.tmp = tempfile.TemporaryDirectory() - self.hashes_file = os.path.join(self.tmp.name, "hashes.json") - self.mapping = { - "b779a091": "adder", - "88f08ef3": "apple", - "18c8836d": "str_85_83667", - } - with open(self.hashes_file, "w", encoding="utf-8") as f: - json.dump(self.mapping, f) - - def tearDown(self): - self.tmp.cleanup() - - def run_tool(self, *args): - return subprocess.run( - [sys.executable, "-I", TOOL, *args], - capture_output=True, - text=True, - ) - - def test_lookup_rejects_a_dictionary_that_is_not_an_object(self): - # #1034: a JSON array is one error line naming the file, not an AttributeError traceback - bad = os.path.join(self.tmp.name, "list.json") - with open(bad, "w", encoding="utf-8") as f: - f.write("[]") - p = self.run_tool("--lookup", bad, "0x1") - self.assertEqual(p.returncode, 2) - self.assertIn("list.json", p.stderr) - self.assertNotIn("Traceback", p.stderr) - - def test_build_rejects_a_malformed_archive_index(self): - # #1043: a bad //index.json is one ERROR line and exit 2, not a JSONDecodeError traceback - for body in ("not json", "[]", '{"files": 3}', '{"other": []}'): - with self.subTest(body=body), tempfile.TemporaryDirectory() as carve: - os.makedirs(os.path.join(carve, "arch")) - with open(os.path.join(carve, "arch", "index.json"), "w", encoding="utf-8") as f: - f.write(body) - p = self.run_tool(carve, "--out", os.path.join(carve, "out.json")) - self.assertEqual(p.returncode, 2, p.stderr) - self.assertIn("ERROR: cannot read", p.stderr) - self.assertNotIn("Traceback", p.stderr) - - def test_lookup_known_hashes(self): - p = self.run_tool("--lookup", self.hashes_file, "0xb779a091", "88f08ef3") - self.assertEqual(p.returncode, 0, p.stderr) - lines = [line.strip() for line in p.stdout.strip().splitlines() if line.strip()] - self.assertEqual(lines, [ - "0xb779a091 adder", - "88f08ef3 apple", - ]) - - def test_lookup_unknown_hash_prints_question_mark(self): - p = self.run_tool("--lookup", self.hashes_file, "0xdeadbeef") - self.assertEqual(p.returncode, 0, p.stderr) - self.assertIn("0xdeadbeef ?", p.stdout) - - def test_lookup_requires_at_least_one_hash(self): - result = self.run_tool("--lookup", self.hashes_file) - self.assertEqual(result.returncode, 2) - self.assertIn("hash", result.stderr.lower()) - - def test_lookup_hex_formatting_variants(self): - # Supports 0x prefix, uppercase, lowercase, and raw hex - p = self.run_tool("--lookup", self.hashes_file, "0XB779A091", "0x18c8836d", "88F08EF3") - self.assertEqual(p.returncode, 0, p.stderr) - lines = [line.strip() for line in p.stdout.strip().splitlines() if line.strip()] - self.assertEqual(lines, [ - "0XB779A091 adder", - "0x18c8836d str_85_83667", - "88F08EF3 apple", - ]) - - -class LookupBadInputTest(unittest.TestCase): - def setUp(self): - self.tmp = tempfile.TemporaryDirectory() - self.hashes_file = os.path.join(self.tmp.name, "hashes.json") - with open(self.hashes_file, "w", encoding="utf-8") as f: - json.dump({"88f08ef3": "apple"}, f) - - def tearDown(self): - self.tmp.cleanup() - - def run_tool(self, *args): - return subprocess.run([sys.executable, "-I", TOOL, *args], capture_output=True, text=True) - - def test_non_hex_value_is_a_usage_error_before_any_output(self): - p = self.run_tool("--lookup", self.hashes_file, "88f08ef3", "apple") - self.assertEqual(p.returncode, 2) - self.assertIn("'apple' is not a hexadecimal hash", p.stderr) - self.assertNotIn("Traceback", p.stderr) - self.assertEqual(p.stdout, "") # nothing printed for the valid value before the bad one - - def test_unreadable_dictionary_is_one_line(self): - bad = os.path.join(self.tmp.name, "bad.json") - with open(bad, "w", encoding="utf-8") as f: - f.write("{not json") - for path in (os.path.join(self.tmp.name, "missing.json"), bad): - with self.subTest(path=os.path.basename(path)): - p = self.run_tool("--lookup", path, "88f08ef3") - self.assertEqual(p.returncode, 2) - self.assertIn(path, p.stderr) - self.assertNotIn("Traceback", p.stderr) - - -class CarveAndExtraCLITest(unittest.TestCase): - def setUp(self): - self.tmp = tempfile.TemporaryDirectory() - self.dir = self.tmp.name - self.carve_dir = os.path.join(self.dir, "carve") - os.makedirs(self.carve_dir) - - # 1. Archive in default --archives list ('common') - common_dir = os.path.join(self.carve_dir, "common") - os.makedirs(common_dir) - common_index = { - "files": [ - {"off": 0, "head": "00000000", "type": "bin"}, - {"off": 16, "head": "00000000", "type": "bink2"}, - ] - } - with open(os.path.join(common_dir, "index.json"), "w", encoding="utf-8") as f: - json.dump(common_index, f) - with open(os.path.join(common_dir, f"{0:012x}.bin"), "wb") as f: - f.write(b"\x00\x00common_archive_asset\x00\x00") - with open(os.path.join(common_dir, f"{16:012x}.bin"), "wb") as f: - f.write(b"\x00\x00bink2_skipped_asset\x00\x00") - - # 2. Archive not in default list, but with metadata head (PSIN: 5053494e) - meta_dir = os.path.join(self.carve_dir, "custom_pack") - os.makedirs(meta_dir) - meta_index = { - "files": [ - {"off": 32, "head": "5053494e1234", "type": "bin"}, - {"off": 48, "head": "00000000", "type": "bin"}, - ] - } - with open(os.path.join(meta_dir, "index.json"), "w", encoding="utf-8") as f: - json.dump(meta_index, f) - with open(os.path.join(meta_dir, f"{32:012x}.bin"), "wb") as f: - f.write(b"\x00\x00pso_metadata_token\x00\x00") - with open(os.path.join(meta_dir, f"{48:012x}.bin"), "wb") as f: - f.write(b"\x00custom_archive_asset\x00") - - # 3. Extra directory with filenames - self.extra_dir = os.path.join(self.dir, "extra_files") - os.makedirs(self.extra_dir) - with open(os.path.join(self.extra_dir, "model_prop.mesh"), "w") as f: - f.write("") - - # 4. Extra standalone file - self.extra_file = os.path.join(self.dir, "standalone.txt") - with open(self.extra_file, "wb") as f: - f.write(b"\x00standalone_symbol_name\x00") - - self.out_json = os.path.join(self.dir, "out_hashes.json") - - def tearDown(self): - self.tmp.cleanup() - - def run_tool(self, *args): - return subprocess.run( - [sys.executable, "-I", TOOL, *args], - capture_output=True, - text=True, - ) - - def test_missing_extra_input_leaves_existing_dictionary_untouched(self): - missing = os.path.join(self.dir, "missing.txt") - previous = {"00000001": "previous_name"} - with open(self.out_json, "w", encoding="utf-8", newline="\n") as output: - json.dump(previous, output) - - result = self.run_tool(self.carve_dir, "--extra", self.extra_file, missing, "--out", self.out_json) - - self.assertEqual(result.returncode, 2, result.stderr) - self.assertIn("--extra", result.stderr) - self.assertIn(missing, result.stderr) - with open(self.out_json, encoding="utf-8") as output: - self.assertEqual(json.load(output), previous) - - def test_build_dictionary_and_roundtrip_lookup(self): - p = self.run_tool( - self.carve_dir, - "--out", self.out_json, - "--extra", self.extra_dir, self.extra_file, - ) - self.assertEqual(p.returncode, 0, p.stderr) - self.assertTrue(os.path.isfile(self.out_json)) - - with open(self.out_json, "r", encoding="utf-8") as f: - d = json.load(f) - - # Confirm harvested strings are in dictionary under their joaat hex - self.assertEqual(d.get(f"{hashdict.joaat('common_archive_asset'):08x}"), "common_archive_asset") - self.assertEqual(d.get(f"{hashdict.joaat('pso_metadata_token'):08x}"), "pso_metadata_token") - self.assertEqual(d.get(f"{hashdict.joaat('model_prop'):08x}"), "model_prop") - self.assertEqual(d.get(f"{hashdict.joaat('standalone_symbol_name'):08x}"), "standalone_symbol_name") - - # Bink2 entries should be skipped - self.assertNotIn(f"{hashdict.joaat('bink2_skipped_asset'):08x}", d) - - # Round-trip lookup via CLI - lookup_hash = f"0x{hashdict.joaat('model_prop'):08x}" - p_lookup = self.run_tool("--lookup", self.out_json, lookup_hash) - self.assertEqual(p_lookup.returncode, 0, p_lookup.stderr) - self.assertIn(f"{lookup_hash} model_prop", p_lookup.stdout) - - def test_unreadable_extra_subdirectory_preserves_existing_dictionary(self): - blocked = os.path.join(self.extra_dir, "blocked") - os.mkdir(blocked) - previous = {"12345678": "keep"} - with open(self.out_json, "w", encoding="utf-8", newline="\n") as f: - json.dump(previous, f) - scandir = os.scandir - - def scan(path): - if path == blocked: - raise PermissionError(errno.EACCES, "synthetic access denied", path) - return scandir(path) - - command = [TOOL, self.carve_dir, "--extra", self.extra_dir, "--out", self.out_json] - with (mock.patch.object(os, "scandir", side_effect=scan), - mock.patch.object(sys, "argv", command), - mock.patch.object(sys, "stdout", new_callable=io.StringIO), - mock.patch.object(sys, "stderr", new_callable=io.StringIO) as stderr): - result = hashdict.main() - - self.assertEqual(result, 2, stderr.getvalue()) - self.assertIn("--extra", stderr.getvalue()) - self.assertIn(blocked, stderr.getvalue()) - with open(self.out_json, encoding="utf-8") as f: - self.assertEqual(json.load(f), previous) - - def test_one_archive_folder_is_harvested_as_that_archive(self): - # /carve/common (its own index.json, as the gamedata_* tools take it) used to give an empty - # dictionary with exit 0: only //index.json was looked for. - p = self.run_tool(os.path.join(self.carve_dir, "common"), "--out", self.out_json) - self.assertEqual(p.returncode, 0, p.stderr) - self.assertIn("common: ", p.stdout) - with open(self.out_json, encoding="utf-8") as f: - d = json.load(f) - self.assertEqual(d.get(f"{hashdict.joaat('common_archive_asset'):08x}"), "common_archive_asset") - self.assertNotIn(f"{hashdict.joaat('bink2_skipped_asset'):08x}", d) - # An archive outside --archives still contributes only its PSIN/RBF0 blobs. - p = self.run_tool(os.path.join(self.carve_dir, "custom_pack"), "--out", self.out_json) - self.assertEqual(p.returncode, 0, p.stderr) - with open(self.out_json, encoding="utf-8") as f: - self.assertEqual(json.load(f), {f"{hashdict.joaat('pso_metadata_token'):08x}": "pso_metadata_token"}) - - def archive_names(self, *args): - p = self.run_tool(self.carve_dir, "--out", self.out_json, *args) - self.assertEqual(p.returncode, 0, p.stderr) - with open(self.out_json, encoding="utf-8") as f: - return set(json.load(f).values()) - - def test_archives_list_ignores_spaces_and_empty_entries(self): - # "common, custom_pack" used to select only common: " custom_pack" matched no archive, silently - names = self.archive_names("--archives", " common, custom_pack ,,") - self.assertIn("common_archive_asset", names) - self.assertIn("custom_archive_asset", names) - self.assertIn("pso_metadata_token", names) - # an empty list harvests only the PSIN/RBF0 blobs - names = self.archive_names("--archives", "") - self.assertNotIn("common_archive_asset", names) - self.assertNotIn("custom_archive_asset", names) - self.assertIn("pso_metadata_token", names) - - def test_archive_named_but_not_carved_is_a_usage_error(self): - previous = {"00000001": "previous_name"} - with open(self.out_json, "w", encoding="utf-8") as f: - json.dump(previous, f) - common = os.path.join(self.carve_dir, "common") - for carve, archives, message in ( - (self.carve_dir, "comon,custom_pack", "--archives: comon not found"), - (self.carve_dir, "common, data", "--archives: data not found"), - # a one-archive folder holds that archive only - (common, "custom_pack", "(archives there: common)")): - p = self.run_tool(carve, "--out", self.out_json, "--archives", archives) - self.assertEqual(p.returncode, 2, p.stderr) - self.assertIn("usage:", p.stderr) - self.assertIn(message, p.stderr) - self.assertNotIn("Traceback", p.stderr) - self.assertEqual(p.stdout, "") - with open(self.out_json, encoding="utf-8") as f: - self.assertEqual(json.load(f), previous) - - def test_default_archives_absent_from_a_partial_carve_are_not_an_error(self): - # the default list names data, script, ... which this carve lacks - names = self.archive_names() - self.assertIn("common_archive_asset", names) - self.assertIn("pso_metadata_token", names) - - def test_out_naming_a_one_archive_index_is_refused(self): - index = os.path.join(self.carve_dir, "common", "index.json") - with open(index, "rb") as f: - before = f.read() - p = self.run_tool(os.path.join(self.carve_dir, "common"), "--out", index) - self.assertEqual(p.returncode, 2, p.stderr) - self.assertIn("is one of the inputs", p.stderr) - with open(index, "rb") as f: - self.assertEqual(f.read(), before) - - def assert_carved_blob_preserved(self, output, blob): - with open(blob, "rb") as f: - original = f.read() - p = self.run_tool(self.carve_dir, "--out", output) - self.assertEqual(p.returncode, 2, p.stderr) - self.assertIn("is one of the inputs", p.stderr) - self.assertNotIn("Traceback", p.stderr) - with open(blob, "rb") as f: - self.assertEqual(f.read(), original) - - def test_out_cannot_replace_a_harvested_blob(self): - # The existing --out check protects index.json and --extra, but the - # .bin files read during harvesting are inputs as well. - for archive, offset in (("common", 0), ("custom_pack", 32)): - with self.subTest(archive=archive): - blob = os.path.join(self.carve_dir, archive, f"{offset:012x}.bin") - self.assert_carved_blob_preserved(blob, blob) - - def test_out_cannot_replace_a_hard_link_to_a_harvested_blob(self): - blob = os.path.join(self.carve_dir, "common", f"{0:012x}.bin") - alias = os.path.join(self.dir, "harvest_alias.json") - try: - os.link(blob, alias) - except (OSError, NotImplementedError) as error: - self.skipTest(f"hard links unavailable: {error}") - self.assert_carved_blob_preserved(alias, blob) - self.assertTrue(os.path.samefile(blob, alias)) - - def test_out_cannot_replace_a_symlink_to_a_harvested_blob(self): - blob = os.path.join(self.carve_dir, "common", f"{0:012x}.bin") - alias = os.path.join(self.dir, "harvest_link.json") - try: - os.symlink(blob, alias) - except (OSError, NotImplementedError) as error: - self.skipTest(f"symlinks unavailable: {error}") - self.assert_carved_blob_preserved(alias, blob) - self.assertTrue(os.path.islink(alias)) - - def test_build_requires_an_explicit_carve_directory(self): - empty = os.path.join(self.dir, "empty") - os.mkdir(empty) - with open(self.out_json, "w", encoding="utf-8") as f: - f.write('{"12345678": "keep"}') - result = subprocess.run([sys.executable, "-I", TOOL, "--out", self.out_json], - cwd=empty, capture_output=True, text=True) - self.assertEqual(result.returncode, 2) - self.assertIn("carve", result.stderr.lower()) - with open(self.out_json, encoding="utf-8") as f: - self.assertEqual(json.load(f), {"12345678": "keep"}) - - def test_missing_or_file_carve_is_one_line(self): - with open(self.out_json, "w", encoding="utf-8") as f: - f.write('{"12345678": "keep"}') - for carve, what in ((os.path.join(self.dir, "no_such_carve"), "does not exist"), - (self.extra_file, "is not a folder")): - with self.subTest(what=what): - p = self.run_tool(carve, "--out", self.out_json) - self.assertEqual(p.returncode, 2) - self.assertIn(carve, p.stderr) - self.assertIn(what, p.stderr) - self.assertNotIn("Traceback", p.stderr) - with open(self.out_json, encoding="utf-8") as f: - self.assertEqual(json.load(f), {"12345678": "keep"}) - - def test_non_bink_row_head_and_offset_are_validated_before_writing(self): - # Missing/nonstring head and invalid (missing, negative, float, bool) offsets must be one ERROR - # line naming the file and row, exit 2, and never overwrite --out. - cases = [ - {"off": 0, "type": "bin"}, # missing head - {"off": 0, "head": 123, "type": "bin"}, # non-string head - {"head": "00000000", "type": "bin"}, # missing offset - {"off": -1, "head": "00000000", "type": "bin"}, # negative offset - {"off": 1.5, "head": "00000000", "type": "bin"}, # non-integer offset - {"off": True, "head": "00000000", "type": "bin"},# bool offset (True == 1) - ] - for row in cases: - with self.subTest(row=row), tempfile.TemporaryDirectory() as carve: - os.makedirs(os.path.join(carve, "arch")) - with open(os.path.join(carve, "arch", "index.json"), "w", encoding="utf-8") as f: - json.dump({"files": [row]}, f) - out = os.path.join(carve, "out.json") - p = self.run_tool(carve, "--out", out) - self.assertEqual(p.returncode, 2, p.stderr) - self.assertIn("index.json", p.stderr) - self.assertIn("row 0", p.stderr) - self.assertNotIn("Traceback", p.stderr) - self.assertFalse(os.path.exists(out), "no report may be written on bad input") - - def test_listed_blob_missing_from_disk_is_skipped_and_reported(self): - # The PSIN blob is listed in custom_pack/index.json but gone: the run keeps every other string. - os.remove(os.path.join(self.carve_dir, "custom_pack", f"{32:012x}.bin")) - p = self.run_tool(self.carve_dir, "--out", self.out_json) - self.assertEqual(p.returncode, 0, p.stderr) - self.assertNotIn("Traceback", p.stderr) - self.assertIn("1 carved blobs", p.stderr) - self.assertIn(f"{32:012x}.bin", p.stderr) - with open(self.out_json, encoding="utf-8") as f: - d = json.load(f) - self.assertEqual(d.get(f"{hashdict.joaat('common_archive_asset'):08x}"), "common_archive_asset") - self.assertNotIn(f"{hashdict.joaat('pso_metadata_token'):08x}", d) - - def test_archive_index_saved_with_a_utf8_bom_is_read(self): - # Windows PowerShell 5.1 (Set-Content, Out-File) and old Notepad write JSON with a UTF-8 BOM; the - # names in that index must still be harvested, not end the build with "Expecting value". - index = os.path.join(self.carve_dir, "common", "index.json") - with open(index, "rb") as f: - raw = f.read() - with open(index, "wb") as f: - f.write(b"\xef\xbb\xbf" + raw) - - p = self.run_tool(self.carve_dir, "--out", self.out_json) - - self.assertEqual(p.returncode, 0, p.stderr) - self.assertNotIn("Traceback", p.stderr) - self.assertNotIn("Expecting value", p.stderr) - with open(self.out_json, encoding="utf-8") as f: - d = json.load(f) - self.assertEqual(d.get(f"{hashdict.joaat('common_archive_asset'):08x}"), "common_archive_asset") - - def test_build_is_reproducible_with_collisions(self): - with open(self.extra_file, "wb") as f: - f.write(b"widget Widget str_85_83667 str_63346_847129") - - flags = ["-P"] if sys.version_info >= (3, 11) else [] - results = [] - for seed in ("1", "2"): - # Unlike -I, -P keeps PYTHONHASHSEED while leaving the script directory off sys.path. - result = subprocess.run( - [sys.executable, *flags, TOOL, self.carve_dir, "--out", self.out_json, "--extra", self.extra_file], - env=dict(os.environ, PYTHONHASHSEED=seed), capture_output=True, text=True, - ) - self.assertEqual(result.returncode, 0, result.stderr) - with open(self.out_json, "rb") as f: - results.append(f.read()) - - self.assertEqual(results[0], results[1]) - mapping = json.loads(results[0]) - self.assertEqual(mapping[f"{hashdict.joaat('widget'):08x}"], "Widget") - # The two synthetic identifiers share a 32-bit hash. - self.assertEqual(mapping["18c8836d"], "str_63346_847129") - - -class ContinuationStreamTest(unittest.TestCase): - """A carved stream that fills whole 64 KiB blocks continues in the next one (docs/page_directory.md): the - blob is harvested with its continuation, so a name across the boundary is kept whole.""" - - NAME = b"synthetic_rig_name" - CUT = 8 # the boundary falls after "syntheti" - - def setUp(self): - self.tmp = tempfile.TemporaryDirectory() - self.addCleanup(self.tmp.cleanup) - self.carve = os.path.join(self.tmp.name, "carve") - self.out = os.path.join(self.tmp.name, "hashes.json") - - def write_archive(self, arch, streams): - """One archive folder of carved streams laid out back to back, as rpf9_carve.py writes them.""" - folder = os.path.join(self.carve, arch) - os.makedirs(folder) - rows, off = [], 0 - for data in streams: - with open(os.path.join(folder, f"{off:012x}.bin"), "wb") as f: - f.write(data) - rows.append({"off": off, "stored": len(data), "size": len(data), "head": data[:16].hex()}) - off += 0x10000 * ((len(data) + 0xFFFF) // 0x10000) - with open(os.path.join(folder, "index.json"), "w", encoding="utf-8", newline="\n") as f: - json.dump({"files": rows}, f) - - def first_stream(self, magic, size=65536): - """`size` bytes starting with `magic` and ending in the first CUT bytes of NAME.""" - tail = b"\x00" + self.NAME[:self.CUT] - return magic + b"\x01" * (size - len(magic) - len(tail)) + tail - - def names(self, *args): - p = subprocess.run([sys.executable, "-I", TOOL, self.carve, "--out", self.out, *args], - capture_output=True, text=True) - self.assertEqual(p.returncode, 0, p.stderr) - with open(self.out, encoding="utf-8") as f: - return set(json.load(f).values()) - - def test_pso_blob_is_read_past_its_first_stream(self): - # levels is not in the default --archives: only PSIN/RBF0 blobs are read there, now with their continuation - self.write_archive("levels", [self.first_stream(b"PSIN" + bytes(12)), - self.NAME[self.CUT:] + b"\x00continuation_only_name\x00"]) - names = self.names() - self.assertIn(self.NAME.decode(), names) - self.assertIn("continuation_only_name", names) - self.assertNotIn(self.NAME[:self.CUT].decode(), names) - - def test_name_across_the_boundary_of_a_fully_harvested_archive(self): - # a first stream of 128 KiB continues as well (docs/page_directory.md) - self.write_archive("common", [self.first_stream(b"\x00" * 16, 2 * 65536), self.NAME[self.CUT:] + b"\x00"]) - names = self.names() - self.assertIn(self.NAME.decode(), names) - self.assertNotIn(self.NAME[:self.CUT].decode(), names) - self.assertNotIn(self.NAME[self.CUT:].decode(), names) - - def test_streams_that_do_not_continue_are_harvested_apart(self): - # a stream short of a whole block ends its blob, and a new PSIN stream never continues the one before - self.write_archive("common", [self.first_stream(b"\x00" * 16, 65535), self.NAME[self.CUT:] + b"\x00", - self.first_stream(b"\x00" * 16), b"PSIN" + self.NAME[self.CUT:] + b"\x00"]) - names = self.names() - self.assertNotIn(self.NAME.decode(), names) - self.assertIn(self.NAME[:self.CUT].decode(), names) - self.assertIn(self.NAME[self.CUT:].decode(), names) - - -class OutputPathTest(unittest.TestCase): - def test_out_creates_its_parent_directory(self): - with tempfile.TemporaryDirectory() as tmp: - carve = os.path.join(tmp, "carve") - os.makedirs(carve) - with open(os.path.join(carve, "index.json"), "w", encoding="utf-8") as f: - json.dump({"files": []}, f) - out = os.path.join(tmp, "nested", "deeper", "hashes.json") - p = subprocess.run([sys.executable, "-I", TOOL, carve, "--out", out], - capture_output=True, text=True) - self.assertEqual(p.returncode, 0, p.stderr) - self.assertNotIn("Traceback", p.stderr) - self.assertTrue(os.path.isfile(out)) - with open(out, encoding="utf-8") as f: - self.assertEqual(json.load(f), {}) - - def test_out_naming_an_input_is_refused_and_left_alone(self): - with tempfile.TemporaryDirectory() as tmp: - carve = os.path.join(tmp, "carve") - os.makedirs(os.path.join(carve, "common")) - index = os.path.join(carve, "common", "index.json") - with open(index, "w", encoding="utf-8") as f: - json.dump({"files": []}, f) - extra = os.path.join(tmp, "names.txt") - with open(extra, "wb") as f: - f.write(b"adder\n") - for out in (extra, index): - with open(out, "rb") as f: - before = f.read() - p = subprocess.run([sys.executable, "-I", TOOL, carve, "--extra", extra, "--out", out], - capture_output=True, text=True) - self.assertEqual(p.returncode, 2, p.stderr) - self.assertIn("is one of the inputs", p.stderr) - self.assertNotIn("Traceback", p.stderr) - with open(out, "rb") as f: - self.assertEqual(f.read(), before) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/test_heap_index_census.py b/tests/test_heap_index_census.py deleted file mode 100644 index cf1cccd33..000000000 --- a/tests/test_heap_index_census.py +++ /dev/null @@ -1,255 +0,0 @@ -"""tools/heap_index_census.py on hand-written listings and containers (no game files, no GPU).""" -import json -import os -import struct -import subprocess -import sys -import tempfile -import unittest - -ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) -sys.path.insert(0, os.path.join(ROOT, "tools")) - -import heap_index_census as hic # noqa: E402 - -SFI0_RES = 1 << 25 -SFI0_SMP = 1 << 26 - - -def enc(n): - """A placeholder `; encoding:` of n bytes: the census only needs the length (for code offsets).""" - return "; encoding: [" + ",".join(["0x00"] * n) + "]" - - -def listing(name, lines): - """lines: (text, bytes) pairs -> a tab-indented listing as tools/shader_disasm.py writes it.""" - end = 0x100 + sum(n for _, n in lines) - body = "".join(f"\t{text:<40}{enc(n)}\n" for text, n in lines) - return f"; {name}.fssm code 0x100..0x{end:x}\n{body}" - - -def dxbc(flags): - """A DXBC container holding only an SFI0 part with the given feature flags.""" - sfi0 = b"SFI0" + struct.pack("/shaders/dxbc folder: carve index, containers, FSSM headers and disasm listings.""" - - def __init__(self): - self.tmp = tempfile.TemporaryDirectory() - self.root = self.tmp.name - self.disasm = os.path.join(self.root, "disasm") - os.makedirs(self.disasm) - os.makedirs(os.path.join(self.root, "fssm")) - self.index = [] - - def add(self, name, stage, flags, lines, rsrc2=None): - self.index.append({"file": name + ".dxbc", "stage": stage}) - with open(os.path.join(self.root, name + ".dxbc"), "wb") as f: - f.write(dxbc(flags)) - with open(os.path.join(self.disasm, name + ".s"), "w", encoding="utf-8", newline="\n") as f: - f.write(listing(name, lines)) - if rsrc2 is not None: - with open(os.path.join(self.root, "fssm", name + ".fssm"), "wb") as f: - f.write(fssm(rsrc2)) - with open(os.path.join(self.root, "index.json"), "w", encoding="utf-8", newline="\n") as f: - json.dump(self.index, f) - - def close(self): - self.tmp.cleanup() - - -# A heap-indexing PS: the resource heap is a 32-bit pointer in s8 (s9 forced to 0), a T# at a static offset; -# the sampler heap is a 32-bit pointer in s11 indexed by s5 (dynamic offset). -PS_HEAP = [ - ("s_mov_b32 s9, 0", 4), - ("s_load_dwordx8 s[20:27], s[8:9], 0x1660", 8), - ("s_mov_b32 s12, 0", 4), - ("s_load_dwordx4 s[28:31], s[11:12], s5", 8), - ("s_waitcnt lgkmcnt(0)", 4), - ("image_sample v[0:3], v[4:5], s[20:27], s[28:31] dmask:0xf dim:SQ_RSRC_IMG_2D", 8), - ("s_endpgm", 4), -] - - -class HeapIndexCensus(unittest.TestCase): - def setUp(self): - self.work = Work() - - def tearDown(self): - self.work.close() - - def test_user_ptr32_heap_bases_and_roles(self): - self.work.add("ps_heap", "ps", SFI0_RES | SFI0_SMP, PS_HEAP) - out = hic.census(self.work.disasm) - g = out["groups"]["ps sfi0=res+smp"] - self.assertEqual(g["shaders"], 1) - self.assertEqual(g["shaders_per_base"], {"user s8": 1, "user s11": 1}) - rows = {(r["base"], r["ptr"], r["role"], r["offset"]): r["count"] for r in g["loads"]} - self.assertEqual(rows, {("user s8", "ptr32", "T#", "static"): 1, - ("user s11", "ptr32", "S#", "dynamic"): 1}) - self.assertEqual(g["static_offsets"]["T#"], {"aligned32": 1, "max": 0x1660}) - - def test_compute_sgpr_past_user_count_is_system(self): - # COMPUTE_PGM_RSRC2 USER_SGPR = 2: s0..s1 are user data, s2 is the first system SGPR. - self.work.add("cs_sys", "cs", SFI0_RES, [ - ("s_load_dwordx8 s[20:27], s[2:3], 0x40", 8), - ("s_load_dwordx4 s[28:31], s[0:1], 0x0", 8), - ("s_endpgm", 4), - ], rsrc2=2 << 1) - g = hic.census(self.work.disasm)["groups"]["cs sfi0=res"] - bases = {(r["base"], r["ptr"]) for r in g["loads"]} - self.assertEqual(bases, {("system s[2:3]", "ptr64"), ("user s[0:1]", "ptr64")}) - - def test_pointer_loaded_from_memory(self): - self.work.add("ps_ld", "ps", 0, [ - ("s_mov_b32 s9, 0", 4), - ("s_load_dwordx2 s[0:1], s[8:9], 0x10", 8), - ("s_waitcnt lgkmcnt(0)", 4), - ("s_load_dwordx8 s[20:27], s[0:1], 0x0", 8), - ("s_endpgm", 4), - ]) - g = hic.census(self.work.disasm)["groups"]["ps sfi0=none"] - self.assertEqual(g["shaders_per_base"], {"loaded pointer": 1}) - self.assertEqual(g["loads"][0]["role"], "unused") - - def test_paths_that_disagree_drop_the_high_word(self): - # pc 0x100 cmp, 0x104 cbranch to 0x110; 0x108 s9 = 0, 0x10c branch to 0x114; 0x110 s9 = s10; 0x114 load. - self.work.add("ps_merge", "ps", SFI0_RES, [ - ("s_cmp_eq_u32 s5, 0", 4), - ("s_cbranch_scc0 2", 4), - ("s_mov_b32 s9, 0", 4), - ("s_branch 1", 4), - ("s_mov_b32 s9, s10", 4), - ("s_load_dwordx8 s[20:27], s[8:9], 0x20", 8), - ("s_endpgm", 4), - ]) - g = hic.census(self.work.disasm)["groups"]["ps sfi0=res"] - self.assertEqual([(r["base"], r["ptr"]) for r in g["loads"]], [("user s8", "ptr64_lo_only")]) - - def test_same_paths_keep_the_ptr32(self): - self.work.add("ps_same", "ps", SFI0_RES, [ - ("s_cmp_eq_u32 s5, 0", 4), - ("s_cbranch_scc0 2", 4), - ("s_mov_b32 s9, 0", 4), - ("s_branch 1", 4), - ("s_mov_b32 s9, 0", 4), - ("s_load_dwordx8 s[20:27], s[8:9], 0x20", 8), - ("s_endpgm", 4), - ]) - g = hic.census(self.work.disasm)["groups"]["ps sfi0=res"] - self.assertEqual([(r["base"], r["ptr"]) for r in g["loads"]], [("user s8", "ptr32")]) - - def test_branch_past_the_last_instruction_is_skipped(self): - # 0x104 s_cbranch_scc0 0 targets 0x108 = the end of the code: counted, not a KeyError. - self.work.add("ps_end", "ps", SFI0_RES, [ - ("s_cmp_eq_u32 s5, 0", 4), - ("s_cbranch_scc0 0", 4), - ]) - out = hic.census(self.work.disasm) - self.assertEqual(out["skipped"], {"branch target outside code": 1}) - - def test_embedded_data_is_counted_as_skipped(self): - self.work.add("ps_heap", "ps", SFI0_RES, PS_HEAP) - path = os.path.join(self.work.disasm, "ps_heap.s") - with open(path, "a", encoding="utf-8", newline="\n") as f: - f.write("\t; invalid instruction encoding\n") - out = hic.census(self.work.disasm) - self.assertEqual(out["skipped"], {"embedded data words": 1}) - self.assertEqual(out["groups"], {}) - - def test_cli_json_and_missing_folder(self): - self.work.add("ps_heap", "ps", SFI0_RES | SFI0_SMP, PS_HEAP) - js = os.path.join(self.work.root, "out", "census.json") - p = subprocess.run([sys.executable, "-I", os.path.join(ROOT, "tools", "heap_index_census.py"), - self.work.disasm, "--json", js], capture_output=True, text=True) - self.assertEqual(p.returncode, 0, p.stderr) - self.assertIn("ps sfi0=res+smp: 1 shaders", p.stdout) - with open(js, encoding="utf-8") as f: - self.assertEqual(json.load(f)["shaders_read"], 1) - p = subprocess.run([sys.executable, "-I", os.path.join(ROOT, "tools", "heap_index_census.py"), - os.path.join(self.work.root, "nope")], capture_output=True, text=True) - self.assertEqual(p.returncode, 2) - self.assertTrue(p.stderr.startswith("ERROR:"), p.stderr) - - def test_cli_json_over_the_carve_index_is_refused(self): - self.work.add("ps_heap", "ps", SFI0_RES | SFI0_SMP, PS_HEAP) - index = os.path.join(self.work.root, "index.json") - with open(index, "rb") as f: - before = f.read() - p = subprocess.run([sys.executable, "-I", os.path.join(ROOT, "tools", "heap_index_census.py"), - self.work.disasm, "--json", index], capture_output=True, text=True) - self.assertEqual(p.returncode, 2) - self.assertIn("--json would overwrite the carve index", p.stderr) - with open(index, "rb") as f: - self.assertEqual(f.read(), before) - - def test_cli_json_inside_the_disasm_folder_is_refused(self): - self.work.add("ps_heap", "ps", SFI0_RES | SFI0_SMP, PS_HEAP) - listing_path = os.path.join(self.work.disasm, "ps_heap.s") - with open(listing_path, "rb") as f: - before = f.read() - tool = os.path.join(ROOT, "tools", "heap_index_census.py") - p = subprocess.run([sys.executable, "-I", tool, self.work.disasm, "--json", listing_path], - capture_output=True, text=True) - self.assertEqual(p.returncode, 2) - self.assertIn("must not write inside the disasm folder", p.stderr) - with open(listing_path, "rb") as f: - self.assertEqual(f.read(), before) - # A name that does not exist yet is refused too: the folder itself is the input. - p = subprocess.run([sys.executable, "-I", tool, self.work.disasm, "--json", - os.path.join(self.work.disasm, "report.json")], capture_output=True, text=True) - self.assertEqual(p.returncode, 2) - self.assertFalse(os.path.exists(os.path.join(self.work.disasm, "report.json"))) - - def test_cli_json_over_a_dxbc_container_is_refused(self): - self.work.add("ps_heap", "ps", SFI0_RES | SFI0_SMP, PS_HEAP) - container = os.path.join(self.work.root, "ps_heap.dxbc") - with open(container, "rb") as f: - before = f.read() - p = subprocess.run([sys.executable, "-I", os.path.join(ROOT, "tools", "heap_index_census.py"), - self.work.disasm, "--json", container], capture_output=True, text=True) - self.assertEqual(p.returncode, 2) - self.assertIn("--json would overwrite an input the census reads", p.stderr) - with open(container, "rb") as f: - self.assertEqual(f.read(), before) - - def test_cli_json_over_an_fssm_header_is_refused(self): - self.work.add("cs_sys", "cs", SFI0_RES, [ - ("s_load_dwordx8 s[20:27], s[2:3], 0x40", 8), - ("s_endpgm", 4), - ], rsrc2=2 << 1) - header = os.path.join(self.work.root, "fssm", "cs_sys.fssm") - with open(header, "rb") as f: - before = f.read() - p = subprocess.run([sys.executable, "-I", os.path.join(ROOT, "tools", "heap_index_census.py"), - self.work.disasm, "--json", header], capture_output=True, text=True) - self.assertEqual(p.returncode, 2) - self.assertIn("--json would overwrite an input the census reads", p.stderr) - with open(header, "rb") as f: - self.assertEqual(f.read(), before) - - def test_cli_json_over_a_hard_link_to_a_container_is_refused(self): - self.work.add("ps_heap", "ps", SFI0_RES | SFI0_SMP, PS_HEAP) - container = os.path.join(self.work.root, "ps_heap.dxbc") - link = os.path.join(self.work.root, "report.json") - os.link(container, link) - with open(container, "rb") as f: - before = f.read() - p = subprocess.run([sys.executable, "-I", os.path.join(ROOT, "tools", "heap_index_census.py"), - self.work.disasm, "--json", link], capture_output=True, text=True) - self.assertEqual(p.returncode, 2) - self.assertIn("--json would overwrite an input the census reads", p.stderr) - with open(container, "rb") as f: - self.assertEqual(f.read(), before) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/test_hw_oracle.py b/tests/test_hw_oracle.py deleted file mode 100644 index 036877048..000000000 --- a/tests/test_hw_oracle.py +++ /dev/null @@ -1,926 +0,0 @@ -"""tools/hw_oracle: kernel text, literal and opcode filters, error mapping, the exit-77 contract, and the parts of -the Linux backend that need no GPU (reading the assembled object, the launcher's tokens, the display check). The -last tests run on the hardware when the oracle tools are present and are skipped otherwise. -Standard library only.""" -import os -from pathlib import Path -import struct -import subprocess -import sys -import tempfile -import unittest -import unittest.mock -from unittest import mock - -TOOLS = Path(__file__).resolve().parents[1] / "tools" -sys.path.insert(0, str(TOOLS)) -from hw_oracle import asm, drm, runner # noqa: E402 - -PROG = ["s_mov_b32 s4, 0x12345678", "s_mov_b32 s5, 7", "s_add_u32 s6, s4, s5", "s_cselect_b32 s30, 1, 0", - "v_mov_b32 v8, s4", "v_mov_b32 v9, s5", "v_mov_b32 v10, s6", "v_mov_b32 v11, s30"] - - -class Text(unittest.TestCase): - def test_families(self): - self.assertEqual(asm.family("gfx1150"), "gfx11") - self.assertEqual(asm.family("gfx1030"), "gfx10") - self.assertEqual(asm.family("gfx1013"), "gfx10") - self.assertEqual(asm.family("gfx1201"), "gfx12") - with self.assertRaises(ValueError): - asm.family("gfx90a") - - def test_kernel_uses_the_mnemonics_of_its_family(self): - k11, k10 = asm.kernel_text("k0", PROG, "gfx1150"), asm.kernel_text("k0", PROG, "gfx1030") - k12 = asm.kernel_text("k0", PROG, "gfx1201") - for k in (k11, k12): - self.assertIn("s_load_b64 s[2:3], s[0:1], 0x0", k) - self.assertIn("global_store_b128 v0, v[8:11], s[2:3]", k) - self.assertIn("s_load_dwordx2", k10) - self.assertIn("global_store_dwordx4", k10) - for k in (k11, k12, k10): - self.assertIn(" s_add_u32 s6, s4, s5\n", k) - self.assertIn(".amdhsa_wavefront_size32 1", k) - # the program runs between the output-pointer load and the store - self.assertLess(k.index("s_waitcnt lgkmcnt(0)"), k.index("s_add_u32")) - self.assertLess(k.index("s_add_u32"), k.index("v[8:11]")) - - def test_raw_kernels_get_the_memory_mnemonics_of_their_family(self): - body = ["v_mov_b32 v20, 7", "global_store_b32 v22, v20, s[2:3] offset:4", "s_endpgm"] - k10, k11 = asm.raw_kernel_text("k0", body, "gfx1036"), asm.raw_kernel_text("k0", body, "gfx1150") - self.assertIn(" global_store_dword v22, v20, s[2:3] offset:4\n", k10) # GFX10 has no global_store_b32 - self.assertNotIn("global_store_b32", k10) - self.assertIn(" global_store_b32 v22, v20, s[2:3] offset:4\n", k11) - self.assertEqual(asm.gfx10_spelling("global_load_b128 v[4:7], v0, s[2:3]"), "global_load_dwordx4 v[4:7], v0, s[2:3]") - self.assertEqual(asm.gfx10_spelling("v_mov_b32 v20, 7"), "v_mov_b32 v20, 7") - - def test_gfx1170_and_later_reject_the_ieee_and_dx10_clamp_mode_fields(self): - body = ["s_endpgm"] - for arch in ("gfx1170", "gfx1200", "gfx1201"): - for field in ("ieee", "dx10_clamp"): - with self.assertRaisesRegex(asm.ModeUnavailable, field, msg=f"{arch} {field}"): - asm.raw_kernel_text("k0", body, arch, mode={field: 0}) - - def test_denormal_and_rounding_mode_fields_still_work_on_gfx12(self): - text = asm.raw_kernel_text("k0", ["s_endpgm"], "gfx1201", - mode={"denorm32": 0, "denorm16_64": 3, "round16_64": 3}) - self.assertIn(".amdhsa_float_denorm_mode_32 0", text) - self.assertIn(".amdhsa_float_denorm_mode_16_64 3", text) - self.assertIn(".amdhsa_float_round_mode_16_64 3", text) - self.assertNotIn(".amdhsa_ieee_mode", text) - self.assertNotIn(".amdhsa_dx10_clamp", text) - - def test_gfx1150_still_emits_the_ieee_and_dx10_clamp_mode_fields(self): - text = asm.raw_kernel_text("k0", ["s_endpgm"], "gfx1150", mode={"ieee": 0, "dx10_clamp": 1}) - self.assertIn(".amdhsa_ieee_mode 0", text) - self.assertIn(".amdhsa_dx10_clamp 1", text) - - def test_the_runner_reports_an_unavailable_mode_as_a_skip(self): - o = object.__new__(runner.Oracle) # no tools, no GPU - o.arch, o.chunk = "gfx1201", 500 - # The kernel is not assembled; it comes back as the reason (#1620), and the rest of the run goes on. - result, = o.run([asm.Kernel(["s_endpgm"], raw=True, mode={"ieee": 0})]) - self.assertIsInstance(result, str) - self.assertIn("ieee", result) - - def test_metadata_is_required_and_lists_every_kernel(self): - text, names, starts = asm.module_text([PROG, PROG, PROG], "gfx1150") - self.assertEqual(names, ["k0", "k1", "k2"]) - self.assertIn('.amdgcn_target "amdgcn-amd-amdhsa--gfx1150"', text) - self.assertEqual(text.count(".symbol: k"), 3) - self.assertIn(".end_amdgpu_metadata", text) - self.assertEqual(text.count("global_store_b128"), 3) - - def test_error_lines_map_back_to_kernels(self): - text, names, starts = asm.module_text([PROG, PROG, PROG], "gfx1150") - lines = text.split("\n") - for k, start in enumerate(starts): - self.assertTrue(lines[start - 1].startswith(".globl k"), (k, lines[start - 1])) - err = f"k.s:{starts[1] + 7}:3: error: invalid operand\n s_foo\n" - self.assertEqual(asm.failing_kernels(err, starts), {1}) - err2 = err + f"k.s:{starts[2]}:1: error: x\n" - self.assertEqual(asm.failing_kernels(err2, starts), {1, 2}) - - -class DetectArch(unittest.TestCase): - def test_amdgpu_arch_target_features_are_dropped(self): - for printed, want in (("gfx1010:xnack-\n", "gfx1010"), ("gfx1150\n", "gfx1150"), - ("gfx1030:sramecc+:xnack-\ngfx1150\n", "gfx1030")): - with self.subTest(printed=printed): - done = subprocess.CompletedProcess([], 0, stdout=printed) - with mock.patch.dict(os.environ, {}, clear=False), \ - mock.patch.object(os.path, "isfile", return_value=True), \ - mock.patch.object(subprocess, "run", return_value=done): - os.environ.pop("LEONIDA_HW_ARCH", None) - arch = runner.detect_arch(os.path.join("opt", "clang")) - self.assertEqual(arch, want) - asm.family(arch) # what Oracle() does next must accept it - - -class True16(unittest.TestCase): - def test_the_low_half_is_named_only_on_the_f16_operand(self): - for old, new in ( - ("v_cvt_f16_f32_e32 v8, v4", "v_cvt_f16_f32_e32 v8.l, v4"), - (" v_cvt_f16_f32_e64 v8, -|v4|", " v_cvt_f16_f32_e64 v8.l, -|v4|"), - ("v_cvt_f16_f32 v8, 0x3f800000", "v_cvt_f16_f32 v8.l, 0x3f800000"), - ("v_cvt_f32_f16_e32 v8, v4", "v_cvt_f32_f16_e32 v8, v4.l"), - ("v_cvt_f32_f16_e64 v8, -|v14| clamp mul:2", "v_cvt_f32_f16_e64 v8, -|v14.l| clamp mul:2"), - ("v_cvt_f32_f16 v8, abs(v4)", "v_cvt_f32_f16 v8, abs(v4.l)"), - ("v_exp_f16 v12, v2", "v_exp_f16 v12.l, v2.l"), # both operands are f16 - ("v_sqrt_f16_e64 v12, -|v2|", "v_sqrt_f16_e64 v12.l, -|v2.l|"), - ("v_rcp_f16 v12, 0x3c00", "v_rcp_f16 v12.l, 0x3c00")): - self.assertEqual(asm.true16_spelling(old), new) - self.assertEqual(asm.true16_spelling(new), new) # already spelled that way - for same in ("v_cvt_pkrtz_f16_f32 v8, v4, v5", "v_cvt_f32_f16 v8, s4", "v_cvt_f32_f16 v8, 0x3c00", - "v_cvt_f32_f16 v8, v4.h", "v_mov_b32 v8, v4"): - self.assertEqual(asm.true16_spelling(same), same) - - def test_op_sel_of_the_16_bit_integer_vop3_ops_is_named_on_their_vgprs(self): - """Bit i of op_sel picks source i's half, the last bit the destination's. GFX11+ assemblers reject the bare - form of these eight ops (gfx1100, gfx1150 and gfx1201 checked with AMD LLVM 23); SGPRs and constants keep - taking their half from the op_sel list, so it stays as written.""" - for old, new in ( - ("v_max_u16_e64 v14, s12, v5 op_sel:[1,0,0]", "v_max_u16_e64 v14.l, s12, v5.l op_sel:[1,0,0]"), - ("v_mul_lo_u16_e64 v12, s16, v14 op_sel:[0,1,0]", - "v_mul_lo_u16_e64 v12.l, s16, v14.h op_sel:[0,1,0]"), - ("v_max_u16_e64 v18, v18, s9 op_sel:[1,1,0]", "v_max_u16_e64 v18.l, v18.h, s9 op_sel:[1,1,0]"), - ("v_mul_lo_u16_e64 v16, s19, 0x100 op_sel:[1,1,1]", - "v_mul_lo_u16_e64 v16.h, s19, 0x100 op_sel:[1,1,1]"), - (" v_lshlrev_b16_e64 v2, v19, 32 op_sel:[0,1,1]", - " v_lshlrev_b16_e64 v2.h, v19.l, 32 op_sel:[0,1,1]"), - ("v_ashrrev_i16 v0, s13, v18 op_sel:[0,1,0]", "v_ashrrev_i16 v0.l, s13, v18.h op_sel:[0,1,0]")): - self.assertEqual(asm.opsel16_spelling(old), new) - self.assertEqual(asm.opsel16_spelling(new), new) # already spelled that way - for same in ("v_max_u16_e64 v5, v1, v3", # no op_sel: the bare form still assembles - "v_add_nc_u16 v1, v2, v3 op_sel:[1,0,0]", # these ops take the bare form on GFX11+ - "v_mad_u16 v1, v2, v3, v4 op_sel:[1,0,0,0]", - "v_max_u16_e64 v1, v2 op_sel:[1,0,0]"): # not a destination and two sources - self.assertEqual(asm.opsel16_spelling(same), same) - - def test_the_non_returning_compare_and_store_is_respelled_and_swapped_on_gfx11(self): - """GFX11 has no ds_cmpst_b32, and ds_cmpstore_b32 takes the store value before the compare value.""" - self.assertEqual(asm.ds_line("ds_cmpst_b32 v0, v1, v2", "gfx1150"), - "ds_cmpstore_b32 v0, v2, v1") - self.assertEqual(asm.ds_line("ds_cmpst_b32 v0, v1, v2 offset:8", "gfx1100"), - "ds_cmpstore_b32 v0, v2, v1 offset:8") - self.assertEqual(asm.ds_line("ds_cmpst_b32 v0, v1, v2", "gfx1030"), - "ds_cmpst_b32 v0, v1, v2") - # Both changes are needed together: the rename alone would compare v2 and store v1. - with self.assertRaises(ValueError): - asm.ds_line("ds_cmpst_b32 v0, v1", "gfx1150") - - def test_error_lines_still_map_back(self): - text = "v_mov_b32 v1, 0\nv_cvt_f32_f16 v8, 0x3c00\nv_cvt_f16_f32 v8, v1\nv_mov_b32 v9, 0\n" - out = asm.true16_spelling(text) - self.assertEqual(out, text.replace("v_cvt_f16_f32 v8,", "v_cvt_f16_f32 v8.l,")) - - def test_true16_binary_keeps_explicit_halves_and_other_instruction_forms(self): - for old, new in ( - ("v_mul_f16_e32 v0, v1, v2", "v_mul_f16_e32 v0.l, v1.l, v2.l"), - (" v_max_f16_e64 v8.h, -|v4|, s1 // v9", " v_max_f16_e64 v8.h, -|v4.l|, s1 // v9"), - ("v_lshlrev_b16 v0, 3, v2", "v_lshlrev_b16 v0.l, 3, v2.l")): - self.assertEqual(asm.true16_spelling(old), new) - self.assertEqual(asm.true16_spelling(new), new) - for text in ("v_mul_lo_u16_e64 v1, v2, v3 op_sel:[0,1,0]", - "v_fma_f16_e64 v0, v1, v2, v3 op_sel:[1,0,1,1]", - "v_pk_add_f16 v0, v1, v2 op_sel:[1,0] op_sel_hi:[1,1]", - ".long 0xd7050014 // v_mul_lo_u16 v20, v21, v22"): - self.assertEqual(asm.true16_spelling(text), text) - - -class ToolchainFallbacks(unittest.TestCase): - """The two probes, with a stand-in for the assembler and the launcher.""" - - def oracle(self, arch="gfx1103"): - o = object.__new__(runner.Oracle) # no tools, no GPU - o.arch, o.chunk = arch, 500 - return o - - def probe(self, loads, error="hipModuleLoadData(&mod, img) -> hip error 209"): - o = self.oracle() - seen = [] - - def launch(co, names, words=4): - seen.append(o.code_object) - if o.code_object in loads: - return 0, "# device=test arch=gfx1103\n", "" - return 3, "", error - o._assemble = lambda text, wave=32: ("k.co", "") - o._launch = launch - return o, seen - - def test_a_runtime_that_takes_the_default_keeps_it(self): - o, seen = self.probe(loads={None, 5}) - o._probe() - self.assertEqual(seen, [None]) - self.assertIsNone(o.code_object) - - def test_error_209_retries_as_v5_and_keeps_it(self): - o, seen = self.probe(loads={5}) - self.assertEqual(o._probe(), "device=test arch=gfx1103") - self.assertEqual((seen, o.code_object), ([None, 5], 5)) - - def test_error_303_retries_as_v5_and_keeps_it(self): - o, seen = self.probe(loads={5}, error="hipModuleLoadData(&mod, img) -> hip error 303") - self.assertEqual(o._probe(), "device=test arch=gfx1103") - self.assertEqual((seen, o.code_object), ([None, 5], 5)) - - def test_a_209_that_stays_and_other_errors_are_unavailable(self): - o, seen = self.probe(loads=set()) - with self.assertRaisesRegex(runner.Unavailable, "209"): - o._probe() - self.assertEqual(seen, [None, 5]) - o, seen = self.probe(loads=set(), error="hipModuleLoadData(&mod, img) -> hip error 303") - with self.assertRaisesRegex(runner.Unavailable, "303"): - o._probe() - self.assertEqual(seen, [None, 5]) - o, seen = self.probe(loads={5}, error="hipMalloc -> hip error 2") - with self.assertRaisesRegex(runner.Unavailable, "error 2"): - o._probe() - self.assertEqual(seen, [None]) - - def test_a_launcher_quarantined_by_defender_is_unavailable(self): - o = self.oracle() - o.exe, o.dll = "leonida_hw_oracle_0123456789.exe", "amdhip64_7.dll" - blocked = OSError("Operation did not complete successfully because the file contains a virus") - blocked.winerror = 225 # only set by Python on Windows - with unittest.mock.patch.object(runner.subprocess, "run", side_effect=blocked): - with self.assertRaisesRegex(runner.Unavailable, "Defender.*exclusion"): - o._launch("k.co", ["k0"]) - with unittest.mock.patch.object(runner.subprocess, "run", side_effect=PermissionError("denied")): - with self.assertRaises(PermissionError): - o._launch("k.co", ["k0"]) - - def test_v5_that_does_not_assemble_is_unavailable(self): - o, _ = self.probe(loads={5}) - o._assemble = lambda text, wave=32: (None, "unknown argument") if o.code_object else ("k.co", "") - with self.assertRaisesRegex(runner.Unavailable, "unknown argument"): - o._probe() - - def test_the_chosen_version_reaches_the_assembler(self): - o = self.oracle() - o.clang, o.lld = "clang", "ld.lld" - ok = subprocess.CompletedProcess([], 0, "", "") - with tempfile.TemporaryDirectory() as tmp, \ - unittest.mock.patch.object(runner.subprocess, "run", return_value=ok) as run: - o.workdir = tmp - o._assemble("", 64) - self.assertFalse([a for a in run.call_args_list[0].args[0] if "code-object" in a]) - o.code_object = 5 - o._assemble("", 64) - args = run.call_args_list[2].args[0] - self.assertIn("-mcode-object-version=5", args) - self.assertIn("-mwavefrontsize64", args) - - def test_the_hip_linker_uses_amdgpu_elf_emulation(self): - o = self.oracle() - o.clang, o.lld = "clang", "ld.lld" - ok = subprocess.CompletedProcess([], 0, "", "") - with tempfile.TemporaryDirectory() as tmp, \ - mock.patch.object(runner.subprocess, "run", return_value=ok) as run: - o.workdir = tmp - code, error = o._assemble("") - self.assertEqual(error, "") - run.assert_called_with( - [o.lld, "-m", "elf64_amdgpu", "-shared", os.path.join(tmp, "k.o"), "-o", code], - capture_output=True, text=True, - ) - - def test_true16_is_used_only_where_the_assembler_needs_it(self): - bare_only = lambda text, wave=32: (None, "error") if ".l" in text else ("k.co", "") - half_only = lambda text, wave=32: ("k.co", "") if ".l" in text else (None, "error") - neither = lambda text, wave=32: (None, "error") - for arch, assemble, want in (("gfx1150", bare_only, False), ("gfx1103", half_only, True), - ("gfx1103", neither, False), ("gfx1036", half_only, False)): - o = self.oracle(arch) - o._assemble = assemble - self.assertEqual(o._needs_true16(), want, arch) - - def test_a_chunk_is_assembled_with_that_spelling(self): - for true16 in (False, True): - o = self.oracle() - o.true16, texts = true16, [] - o._assemble = lambda text, wave=32: (texts.append(text) or "k.co", "") - o._launch = lambda co, names, words=4: (0, "k0 00003c00\n", "") - kernel = asm.Kernel(["v_cvt_f16_f32 v8, v1", "s_endpgm"], words=1, raw=True) - self.assertEqual(o.run([kernel], words=1), [[0x3C00]]) - self.assertEqual("v8.l" in texts[0], true16) - - def test_op_sel_halves_are_named_on_gfx11_and_later_even_without_true16(self): - # The assembler that takes a bare v_cvt_f16_f32 (true16 probe: no) still needs v14.l / v5.l on these lines. - line = "v_max_u16_e64 v14, s12, v5 op_sel:[1,0,0]" - for arch, want in (("gfx1036", line), ("gfx1100", "v_max_u16_e64 v14.l, s12, v5.l op_sel:[1,0,0]"), - ("gfx1201", "v_max_u16_e64 v14.l, s12, v5.l op_sel:[1,0,0]")): - o = self.oracle(arch) - o.true16, texts = False, [] - o._assemble = lambda text, wave=32: (texts.append(text) or "k.co", "") - o._launch = lambda co, names, words=4: (0, "k0 00000001\n", "") - kernel = asm.Kernel([line, "s_endpgm"], words=1, raw=True) - self.assertEqual(o.run([kernel], words=1), [[1]]) - self.assertIn(want, texts[0], arch) - - def test_a_mode_the_architecture_cannot_set_is_never_assembled(self): - # FUZZ-43: gfx1170+ rejects .amdhsa_ieee_mode / .amdhsa_dx10_clamp. Those kernels come back as a reason; the - # others in the same run are still assembled and launched. - o = self.oracle("gfx1201") - o.true16, texts = False, [] - o._assemble = lambda text, wave=32: (texts.append(text) or "k.co", "") - o._launch = lambda co, names, words=4: (0, "".join(f"{n.split(':')[0]} 0000002a\n" for n in names), "") - body = ["s_endpgm"] - kernels = [asm.Kernel(body, words=1, raw=True, mode={"ieee": 0}), - asm.Kernel(body, words=1, raw=True, mode={"denorm32": 3}), - asm.Kernel(body, words=1, raw=True, mode={"dx10_clamp": 1, "round32": 1})] - got = o.run(kernels, words=1) - self.assertIn("MODE ieee cannot be set on gfx1201", got[0]) - self.assertEqual(got[1], [0x2A]) - self.assertIn("MODE dx10_clamp cannot be set on gfx1201", got[2]) - self.assertEqual(len(texts), 1) - self.assertNotIn(".amdhsa_ieee_mode", texts[0]) - self.assertNotIn(".amdhsa_dx10_clamp", texts[0]) - - def test_every_kernel_skipped_is_not_a_broken_chunk(self): - o = self.oracle("gfx1201") - o.true16 = False - o._assemble = lambda text, wave=32: self.fail("nothing should be assembled") - got = o.run([asm.Kernel(["s_endpgm"], words=1, raw=True, mode={"ieee": 1}) for _ in range(3)], words=1) - self.assertTrue(all(isinstance(g, str) and "unsupported on gfx1170+" in g for g in got)) - - -class Filters(unittest.TestCase): - def test_literals(self): - self.assertEqual(asm.literals("s_add_u32 s4, 0x100, s5"), {0x100}) - self.assertEqual(asm.literals("s_add_u32 s4, 64, -16"), set()) - self.assertEqual(asm.literals("s_and_b32 s4, 0x100, 0x100"), {0x100}) - self.assertEqual(len(asm.literals("s_and_b32 s4, 0x100, 0x200")), 2) - self.assertEqual(asm.literals("s_and_b32 s4, -1000, 0xfffffc18"), {0xFFFFFC18}) # one 32-bit value - self.assertEqual(asm.literals("s_cmpk_lt_u32 s4, 0x8000"), set()) # SIMM16, not a literal - self.assertEqual(asm.literals("s_movk_i32 s4, 0xffff"), set()) - - def test_mode_skip_reasons(self): - for arch in ("gfx1013", "gfx1030", "gfx1100", "gfx1150", "gfx1151"): - self.assertIsNone(asm.mode_skip_reason({"ieee": 0, "dx10_clamp": 0}, arch), arch) - for arch in ("gfx1170", "gfx1200", "gfx1201"): - self.assertIn("ieee", asm.mode_skip_reason({"ieee": 0}, arch)) - self.assertIn(".amdhsa_dx10_clamp", asm.mode_skip_reason({"dx10_clamp": 1, "denorm32": 3}, arch)) - # the denormal and rounding fields still assemble there - self.assertIsNone(asm.mode_skip_reason({"denorm32": 3, "denorm16_64": 0, "round32": 1, - "round16_64": 2}, arch), arch) - self.assertIsNone(asm.mode_skip_reason(None, arch)) - - def test_rdna23_skip_reason(self): - for arch in ("gfx1013", "gfx1030", "gfx1100", "gfx1150", "gfx1151"): - self.assertIsNone(asm.rdna23_skip_reason(arch), arch) - for arch in ("gfx1170", "gfx1200", "gfx1201"): - self.assertIn(arch, asm.rdna23_skip_reason(arch)) - - def test_skip_reasons(self): - self.assertIsNone(asm.skip_reason(PROG, "gfx1150")) - self.assertIn("s_ff0", asm.skip_reason(PROG + ["s_ff0_i32_b32 s4, s5"], "gfx1150")) - self.assertIsNone(asm.skip_reason(PROG + ["s_ff0_i32_b32 s4, s5"], "gfx1030")) # GFX10 still has it - self.assertIn("two different literals", asm.skip_reason(["s_and_b32 s4, 0x100, 0x200"], "gfx1030")) - # GFX12 keeps GFX11's removals and drops the SOPK compares, which GFX11 still has. - cmpk = PROG + ["s_cmpk_lt_i32 s4, 0x12"] - self.assertIsNone(asm.skip_reason(PROG, "gfx1201")) - self.assertIsNone(asm.skip_reason(cmpk, "gfx1150")) - self.assertIn("GFX12", asm.skip_reason(cmpk, "gfx1201")) - self.assertIn("s_ff0", asm.skip_reason(PROG + ["s_ff0_i32_b64 s[4:5], s[6:7]"], "gfx1201")) - self.assertEqual(len([op for op in asm.GFX12_REMOVED if op.startswith("s_cmpk_")]), 12) - - -class VcvarsScript(unittest.TestCase): - """The .cmd that calls vcvars64.bat and cl holds the checkout, %TEMP% and Visual Studio paths. A character - outside ASCII in any of them (a user name, the Turkish default folder name) used to end in UnicodeEncodeError, - which is not the Unavailable that callers turn into a skip.""" - NAME = "Ayşe Ğİı klasör" # Turkish letters: none of them is ASCII - - def build(self, tmp): - work = os.path.join(tmp, self.NAME) - os.makedirs(work) - src = os.path.join(work, "hw_oracle.c") - out = os.path.join(work, "hw_oracle.exe") - vcvars = os.path.join(work, "vcvars64.bat") - argv = runner.build_command("vcvars", vcvars, src, out, work) - with open(os.path.join(work, argv[-1]), "rb") as f: # the script runs with cwd=work - return argv, f.read(), (src, out, vcvars) - - def test_paths_outside_ascii_are_written_as_utf8(self): - with tempfile.TemporaryDirectory() as tmp: - argv, raw, paths = self.build(tmp) - self.assertEqual(argv[:3], ["cmd.exe", "/d", "/c"]) - text = raw.decode("utf-8") # strict: every byte is UTF-8 - for path in paths: - self.assertIn(path, text) - self.assertFalse(raw.startswith(b"\xef\xbb\xbf")) # cmd.exe would read a BOM as part of the first command - - def test_the_code_page_is_set_before_any_path_is_used(self): - with tempfile.TemporaryDirectory() as tmp: - _argv, raw, _paths = self.build(tmp) - lines = raw.decode("utf-8").split("\r\n") - self.assertEqual(lines[0], "@echo off") - self.assertEqual(lines[1], "chcp 65001 >nul") - self.assertTrue(all(line.isascii() for line in lines[:2])) - self.assertTrue(lines[2].startswith('set "PATH=')) - self.assertTrue(lines[3].startswith('call "')) - - def test_ascii_paths_give_the_same_commands_as_before(self): - with tempfile.TemporaryDirectory() as tmp: - for name in ("work", "a b", "a & b"): - with self.subTest(name=name): - work = os.path.join(tmp, name) - os.makedirs(work) - argv = runner.build_command("vcvars", "vcvars64.bat", "hw_oracle.c", "hw_oracle.exe", work) - with open(os.path.join(work, argv[-1]), "rb") as f: - # UTF-8, not ASCII: the /Fo folder sits in %TEMP%, which can hold a non-ASCII user name. - lines = f.read().decode("utf-8").split("\r\n") - self.assertEqual(lines[3], 'call "vcvars64.bat" >nul || exit /b 1') - self.assertTrue(lines[4].startswith("cl /nologo /O1 hw_oracle.c /Fehw_oracle.exe ")) - # list2cmdline quotes /Fo when the work folder holds a space or a cmd metacharacter such as &. - self.assertIn(f"/Fo{work}{os.sep}", lines[4].replace('"', "")) - - def test_the_direct_compilers_write_no_script(self): - with tempfile.TemporaryDirectory() as tmp: - work = os.path.join(tmp, self.NAME) - os.makedirs(work) - self.assertEqual(runner.build_command("gcc", "gcc", "a.c", "a.exe", work), - ["gcc", "-O1", "a.c", "-o", "a.exe"]) - self.assertEqual(runner.build_command("msvc", "cl.exe", "a.c", "a.exe", work)[0], "cl.exe") - self.assertEqual(os.listdir(work), []) - - @unittest.skipUnless(sys.platform == "win32", "runs the script through cmd.exe") - def test_the_script_runs_from_any_work_folder(self): - # A full path through `cmd.exe /c` loses its quotes when the folder holds & or ^, and a bare name is not - # found with NoDefaultCurrentDirectoryInExePath set. A stub vcvars shows the script got that far. - broken = [] - with tempfile.TemporaryDirectory() as tmp: - stub = os.path.join(tmp, "stub_vcvars.bat") - with open(stub, "wb") as f: - f.write(b'@echo off\r\necho reached> "%LEONIDA_TEST_MARKER%"\r\nexit /b 0\r\n') - for name in ("plain", "sp (x)", "a & b", "a&b", "x^y", self.NAME): - work = os.path.join(tmp, name) - os.makedirs(work) - marker = os.path.join(work, "reached.txt") - argv = runner.build_command("vcvars", stub, "hw_oracle.c", "hw_oracle.exe", work) - env = dict(os.environ, LEONIDA_TEST_MARKER=marker, NoDefaultCurrentDirectoryInExePath="1") - subprocess.run(argv, cwd=work, env=env, capture_output=True, timeout=60) # cl itself is absent - if not os.path.exists(marker): - broken.append(name) - self.assertEqual(broken, [], "build_hw_oracle.cmd did not run from these work folders") - - -class Unavailable(unittest.TestCase): - def test_missing_tools_are_reported_not_raised_as_crashes(self): - with unittest.mock.patch.dict(os.environ, {"LEONIDA_AMD_CLANG": str(TOOLS / "no-such-clang.exe")}): - with self.assertRaises(runner.Unavailable): - runner.find_clang() - with unittest.mock.patch.dict(os.environ, {"LEONIDA_HIP_DLL": str(TOOLS / "no-such.dll")}): - with self.assertRaises(runner.Unavailable): - runner.find_hip_dll() - - def test_host_compiler_choice(self): - here = str(Path(__file__)) # any file that exists stands in for a compiler - cl = str(Path(here).with_name("cl.exe")) - which = {"gcc": None, "cl": None} - real_isfile = os.path.isfile - no_msys = lambda p: False if "msys64" in p else real_isfile(p) # noqa: E731 (hide an installed MSYS2) - with unittest.mock.patch.object(runner.shutil, "which", side_effect=lambda n: which.get(n)), \ - unittest.mock.patch.object(runner.os.path, "isfile", side_effect=no_msys), \ - unittest.mock.patch.object(runner, "find_vcvars", return_value=None), \ - unittest.mock.patch.dict(os.environ, {"LEONIDA_HOST_CC": ""}): - with self.assertRaises(runner.Unavailable) as cm: - runner.find_cc() - self.assertIn("Visual Studio", str(cm.exception)) - which["gcc"] = here - self.assertEqual(runner.find_cc(), ("gcc", here)) # gcc stays first - if os.name == "nt": - which["gcc"], which["cl"] = None, here - self.assertEqual(runner.find_cc(), ("msvc", here)) # a Developer shell's cl - which["cl"] = None - with unittest.mock.patch.object(runner, "find_vcvars", return_value=here): - self.assertEqual(runner.find_cc(), ("vcvars", here)) # VS found through vswhere - with unittest.mock.patch.dict(os.environ, {"LEONIDA_HOST_CC": here}): - self.assertEqual(runner.find_cc(), ("gcc", here)) - with unittest.mock.patch.object(runner.os.path, "isfile", return_value=True), \ - unittest.mock.patch.dict(os.environ, {"LEONIDA_HOST_CC": cl}): - self.assertEqual(runner.find_cc(), ("msvc", cl)) # the override may be cl.exe - - def test_host_compiler_commands(self): - work = os.path.join(os.sep, "w") - self.assertEqual(runner.build_command("gcc", "gcc", "a.c", "o.exe", work), ["gcc", "-O1", "a.c", "-o", "o.exe"]) - cl = runner.build_command("msvc", "cl.exe", "a.c", "o.exe", work) - self.assertEqual(cl[:4], ["cl.exe", "/nologo", "/O1", "a.c"]) - self.assertIn("/Feo.exe", cl) - self.assertIn("/Fo" + os.path.join(work, ""), cl) # objects stay out of the cwd - import tempfile - with tempfile.TemporaryDirectory() as tmp: - argv = runner.build_command("vcvars", r"C:\VS 2022\vcvars64.bat", "a.c", "o.exe", tmp) - self.assertEqual(argv[:3], ["cmd.exe", "/d", "/c"]) - script = (Path(tmp) / argv[3]).read_text(encoding="utf-8") # UTF-8; tmp may be non-ASCII - self.assertIn('call "C:\\VS 2022\\vcvars64.bat"', script) # quoted: the path has a space - self.assertIn("cl /nologo /O1 a.c /Feo.exe", script) - self.assertIn("Installer", script) # vcvars needs vswhere on PATH - - def test_salu_diff_exits_77_without_the_tools(self): - env = dict(os.environ, LEONIDA_AMD_CLANG=str(TOOLS / "no-such-clang.exe")) - r = subprocess.run([sys.executable, "-I", str(TOOLS / "salu_diff.py"), "--oracle", "hw", "--programs", "3"], - capture_output=True, text=True, env=env) - self.assertEqual(r.returncode, 77, r.stdout + r.stderr) - self.assertIn("unavailable", r.stdout) - - def test_an_unsupported_architecture_is_unavailable_not_a_traceback(self): - # Oracle() checks the architecture right after finding the tools; stub those so this runs anywhere. - with unittest.mock.patch.object(runner, "find_clang", return_value="clang"), \ - unittest.mock.patch.object(runner, "_find_lld", return_value="ld.lld"), \ - unittest.mock.patch.object(runner, "find_hip_dll", return_value="amdhip64_7.dll"): - with self.assertRaises(runner.Unavailable) as cm: - runner.Oracle(arch="gfx90a") - self.assertIn("gfx90a", str(cm.exception)) - - def test_unknown_oracle_is_a_usage_error(self): - r = subprocess.run([sys.executable, "-I", str(TOOLS / "salu_diff.py"), "--oracle", "gpu"], - capture_output=True, text=True) - self.assertEqual(r.returncode, 2) - - -class ClangOnPath(unittest.TestCase): - """find_clang when the compiler comes from PATH: real files in a folder, and a stand-in for what each compiler - prints for `--print-targets` and `--version`.""" - EXT = ".exe" if os.name == "nt" else "" - - def setUp(self): - tmp = tempfile.TemporaryDirectory() - self.addCleanup(tmp.cleanup) - self.root = Path(tmp.name) - - def tool(self, *parts): - p = self.root.joinpath(*parts[:-1], parts[-1] + self.EXT) - p.parent.mkdir(parents=True, exist_ok=True) - p.write_bytes(b"") - return str(p) - - def tools(self, on_path, installed): - """PATH holds on_path ({name: file}); the compiler `c` reports installed[c] as its InstalledDir.""" - def run(cmd, **kw): - out = "amdgcn" if "--print-targets" in cmd else f"clang version 23.0.0\nInstalledDir: {installed[cmd[0]]}\n" - return subprocess.CompletedProcess(cmd, 0, out, "") - patches = [unittest.mock.patch.object(runner.shutil, "which", side_effect=lambda n: on_path.get(n)), - unittest.mock.patch.object(runner.subprocess, "run", side_effect=run), - unittest.mock.patch.dict(os.environ, {"LEONIDA_AMD_CLANG": "", "HIP_PATH": "", "ROCM_PATH": ""})] - for p in patches: - p.start() - self.addCleanup(p.stop) - - def test_a_launcher_on_path_stands_for_the_clang_it_is_installed_as(self): - # The rocm-sdk wheels in a Python outside the checkout: `amdclang` in Scripts has the amdgcn target, while - # clang, ld.lld and amdgpu-arch sit in the folder it names as InstalledDir. - launcher = self.tool("Scripts", "amdclang") - clang, lld = self.tool("llvm", "bin", "clang"), self.tool("llvm", "bin", "ld.lld") - self.tools({"amdclang": launcher}, {launcher: str(self.root / "llvm" / "bin")}) - found = runner.find_clang() - self.assertEqual(found, clang) - self.assertEqual(runner._find_lld(found), lld) - - def test_a_clang_with_its_linker_beside_it_is_used_where_it_was_found(self): - clang = self.tool("bin", "clang") - self.tool("bin", "ld.lld") - self.tool("other", "clang") - self.tools({"clang": clang}, {clang: str(self.root / "other")}) - self.assertEqual(runner.find_clang(), clang) - - def test_a_launcher_that_names_a_folder_without_a_clang_is_kept(self): - launcher = self.tool("Scripts", "amdclang") - self.tools({"amdclang": launcher}, {launcher: str(self.root / "nothing-here")}) - found = runner.find_clang() - self.assertEqual(found, launcher) - with self.assertRaises(runner.Unavailable): - runner._find_lld(found) - - -def relocatable(sections, symbols): - """A little-endian ELF64 relocatable object: sections is [(name, bytes, address)], symbols [(name, section - number from 1, value)]. Only what drm.text_section reads is filled in.""" - names = [""] + [s[0] for s in sections] + [".symtab", ".strtab", ".shstrtab"] - shstr, name_at = b"", [] - for n in names: - name_at.append(len(shstr)) - shstr += n.encode() + b"\0" - strtab, symtab = b"\0", bytes(24) - for name, shndx, value in symbols: - symtab += struct.pack("[^|]+?)\s*\|\s*(?P[^|]+?)\s*\|\s*" - r"(?P[^|]+?)\s*\|\s*(?P[^|]+?)\s*\|$") -LINK = re.compile(r"\[[^\]]*\]\(([^)]+)\)") -CODE = re.compile(r"`([A-Za-z][A-Za-z0-9-]*)`") -COMMIT = re.compile(r"^[0-9a-f]{7,40}$") -SYNC_MARKER = re.compile(r"`([0-9a-f]{7,40})`") - - -def sync_marker_matches(index_commit, quickstart_text): - """Whether the opening note has exactly the commit recorded in the index.""" - lines = quickstart_text.splitlines() - heading = next((i for i, line in enumerate(lines) if line.startswith("# ")), None) - start = heading + 1 if heading is not None else 0 - while start < len(lines) and not lines[start].strip(): - start += 1 - if start == len(lines): - return False - - opening_note = [] - for line in lines[start:]: - if not line.strip() or line.lstrip().startswith("#"): - break - opening_note.append(line[1:].lstrip() if line.startswith(">") else line) - - markers = SYNC_MARKER.findall("\n".join(opening_note)) - return len(markers) == 1 and markers[0] == index_commit - - -def parse(text): - """Rows of the language table. Raises ValueError for a row the table format does not parse.""" - rows = [] - for line in text.splitlines(): - line = line.strip() - if not line.startswith("|"): - continue - if set(line.replace("|", "").replace(" ", "")) <= set("-:"): - continue # the header separator - match = ROW.match(line) - if not match: - raise ValueError(f"malformed table row: {line}") - if match.group("language").strip() == "Language": - continue # the header - link = LINK.search(match.group("file")) - code = CODE.search(match.group("language")) - if not link or not code: - raise ValueError(f"row without a file link or a language code: {line}") - rows.append({"code": code.group(1), "file": link.group(1), - "commit": match.group("commit").strip().strip("`"), - "maintainer": match.group("maintainer").strip().strip("`")}) - return rows - - -def duplicate_codes(rows): - seen = set() - duplicates = [] - for row in rows: - if row["code"] in seen: - duplicates.append(row["code"]) - seen.add(row["code"]) - return duplicates - - -class IndexTest(unittest.TestCase): - def read_rows(self): - with open(INDEX, encoding="utf-8") as f: - return parse(f.read()) - - def test_one_row_per_language(self): - rows = self.read_rows() - self.assertGreaterEqual(len(rows), 3) - self.assertEqual(duplicate_codes(rows), []) - - def test_every_row_points_at_an_existing_quickstart(self): - base = os.path.dirname(INDEX) - for row in self.read_rows(): - with self.subTest(language=row["code"]): - path = os.path.normpath(os.path.join(base, row["file"])) - self.assertTrue(os.path.isfile(path), path) - self.assertTrue(row["maintainer"].startswith("@"), row) - self.assertRegex(row["commit"], COMMIT.pattern, row) - - def test_every_synced_commit_matches_its_quickstart_marker(self): - base = os.path.realpath(os.path.dirname(INDEX)) - for row in self.read_rows(): - path = os.path.realpath(os.path.join(base, row["file"])) - with self.subTest(language=row["code"]): - try: - within_i18n = os.path.commonpath((base, path)) == base - except ValueError: - within_i18n = False - self.assertTrue(within_i18n, f"{path} escapes the i18n directory") - with open(path, encoding="utf-8") as f: - quickstart = f.read() - self.assertTrue(sync_marker_matches(row["commit"], quickstart), - f"{path} sync marker does not match {row['commit']}") - - def test_docs_readme_names_every_language_once(self): - codes = [row["code"] for row in self.read_rows()] - with open(DOCS_README, encoding="utf-8") as f: - lines = [line for line in f.read().splitlines() - if line.startswith("Community quickstarts (stable onboarding text only")] - self.assertEqual(len(lines), 1, f"docs/README.md has {len(lines)} 'Other languages' lines") - line = lines[0] - for code in codes: - self.assertEqual(line.count(f"`{code}`"), 1, f"{code} is not named exactly once: {line}") - listed = set(re.findall(r"`([A-Za-z]{2,3}(?:-[A-Za-z]+)?)`", line)) - self.assertEqual(listed - set(codes), set(), - f"docs/README.md names languages without an i18n row: {listed - set(codes)}") - - def test_a_duplicate_language_is_reported(self): - table = ("| Language | File | Synced commit | Maintainer |\n" - "|---|---|---|---|\n" - "| 简体中文 (`zh-CN`) | [`zh-CN/quickstart.md`](zh-CN/quickstart.md) | `e7584c5` | `@a` |\n" - "| 简体中文 (`zh-CN`) | [`zh-CN/quickstart.md`](zh-CN/quickstart.md) | `0d61c357` | `@a` |\n") - rows = parse(table) - self.assertEqual(duplicate_codes(rows), ["zh-CN"]) - - def test_a_malformed_row_is_rejected(self): - table = ("| Language | File | Synced commit | Maintainer |\n" - "|---|---|---|---|\n" - "| 简体中文 | `zh-CN/quickstart.md` | `e7584c5` | `@a` |\n") - with self.assertRaises(ValueError): - parse(table) - - def test_synced_commit_matches_quickstart_marker(self): - page = "> This guide is synced with commit `01234567`.\n" - self.assertTrue(sync_marker_matches("01234567", page)) - - def test_synced_commit_mismatch_is_detected(self): - page = "> This guide is synced with commit `01234567`.\n" - self.assertFalse(sync_marker_matches("89abcdef", page)) - - def test_hash_outside_opening_note_does_not_count_as_sync_marker(self): - page = ("> [!NOTE]\n" - "> This guide has no sync marker.\n" - "\n" - "Example output: `01234567`.\n" - "\n" - "## First section\n") - self.assertFalse(sync_marker_matches("01234567", page)) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/test_image_bvh_census.py b/tests/test_image_bvh_census.py deleted file mode 100644 index c4f931fb5..000000000 --- a/tests/test_image_bvh_census.py +++ /dev/null @@ -1,287 +0,0 @@ -"""tools/image_bvh_census.py on hand-written listings: forms, descriptor fields, word-read categories, lane rule. - - python -I tests/test_image_bvh_census.py -v - -Every listing here is invented (registers and values included); no game data, no GPU. -""" -import contextlib -import io -import json -import os -from pathlib import Path -import sys -import tempfile -import unittest - -sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "tools")) -import image_bvh_census as census # noqa: E402 - -ENC = " ; encoding: [0x00,0x00,0x00,0x00]" # only the length matters: every instruction is 4 bytes here - - -def listing(*lines): - """A listing in shader_disasm's layout. `name:` lines are labels; `@name` in a branch is its target.""" - body, labels, pc = [], {}, 0 - for ln in lines: - if ln.endswith(":"): - labels[ln[:-1]] = pc - else: - body.append((pc, ln)) - pc += 4 - out = [] - for at, ln in body: - if "@" in ln: - op, target = ln.split("@") - ln = f"{op}{(labels[target] - at - 4) // 4}" - out.append("\t" + ln + ENC) - return "; cs_probe code 0x0..0x%x (header), gfx1013, 0 invalid words\n" % pc + "\n".join(out) + "\n" - - -def analyse(*lines): - with tempfile.TemporaryDirectory() as tmp: - path = os.path.join(tmp, "cs_probe.s") - with open(path, "w", encoding="utf-8", newline="\n") as f: - f.write(listing(*lines)) - _, insns = census.load_program(path) - return census.analyse(insns) - - -def reads(site, reach=None): - """{(word, category)} of a site's reads (optionally only those with the given reach).""" - return {(e[1], e[2]) for e in site["reads"] if reach is None or e[3] == reach} - - -DESC_LITERALS = [ # an invented descriptor; s8 is copied from the user SGPR s2 - "s_mov_b32 s8, s2", - "s_brev_b32 s9, 0x1fe", # 0x7f800000: box_grow 0xff, box_sort_en 0 - "s_movk_i32 s10, -2", # 0xfffffffe (sign-extended) - "s_mov_b32 s11, 0x52000123", # size bits 0x123, triangle_return_mode 0, llc_noalloc 1, type 5 -] -CALL32 = "image_bvh_intersect_ray v[4:7], v[0:10], s[8:11]" -TRIANGLE = [ # the words divided by word 1, and word 1's high half - "v_rcp_f32_e32 v20, v5", - "v_mul_f32_e32 v21, v4, v20", - "v_mul_legacy_f32_e32 v22, v20, v6", - "v_mov_b32_e32 v12, v7", # a plain copy is followed - "v_mul_f32_e32 v23, v12, v20", - "v_mul_i32_i24_sdwa v24, sext(v5), v30 dst_sel:DWORD dst_unused:UNUSED_PAD src0_sel:WORD_1 src1_sel:DWORD", - "v_cmp_gt_i32_e32 vcc_lo, 0, v24", -] - - -class CategoryTests(unittest.TestCase): - def test_triangle_words_and_literal_descriptor(self): - (site,) = analyse(*DESC_LITERALS, CALL32, *TRIANGLE, "s_endpgm") - self.assertEqual(site["form"], "image_bvh_intersect_ray") - self.assertEqual(reads(site), {(0, "ratio"), (1, "ratio"), (2, "ratio"), (3, "ratio"), (1, "high_half")}) - self.assertEqual(reads(site, "some"), set()) - self.assertEqual([p[1:] for p in site["product_reads"]], [("v_cmp_gt_i32 with 0", "all")]) - self.assertIsNone(site["desc"][0]) - fields = census.decode_descriptor(site["desc"]) - self.assertEqual(fields, {"box_grow": 0xFF, "box_sort_en": 0, "size": 0x123FFFFFFFE, - "triangle_return_mode": 0, "llc_noalloc": 1, "big_page": 0, "type": 5}) - - def test_box_words_64bit_form_and_unknown_descriptor_words(self): - (site,) = analyse( - "s_mov_b32 s12, 0", # word 0 literal - "s_load_dwordx2 s[13:14], s[0:1], 0x0", # words 1 and 2 from memory: not literals - "s_mov_b32 s15, 0x30000000", - "image_bvh64_intersect_ray v[4:7], v[0:11], s[12:15]", - "v_lshlrev_b32_e32 v10, 3, v4", # integer pack / compare - "v_and_or_b32 v11, v5, 7, v10", - "v_cmp_eq_u32_e32 vcc_lo, v31, v6", - "v_add_f32_e32 v9, v7, v8", # float, not divided - "global_store_dword v[30:31], v6, off", # memory - "s_endpgm") - self.assertEqual(site["form"], "image_bvh64_intersect_ray") - self.assertEqual(reads(site), {(0, "raw_integer"), (1, "raw_integer"), (2, "raw_integer"), - (3, "raw_float"), (2, "raw_other")}) - self.assertEqual(site["desc"][0], 0) - f = census.decode_descriptor(site["desc"]) - self.assertIsNone(f["box_sort_en"]) - self.assertIsNone(f["size"]) - self.assertEqual((f["type"], f["big_page"]), (3, 0)) - - def test_select_modifier_and_next_call_operand(self): - (first, second) = analyse( - CALL32, - "v_cndmask_b32_e32 v9, v4, v5, vcc_lo", # a select is not followed - "v_rcp_f32_e32 v20, v5", - "v_mul_f32_e64 v21, |v6|, v20", # an abs modifier: not the ratio - "v_mov_b32_e32 v0, v4", # word 0 becomes the next call's node id - "image_bvh_intersect_ray v[4:7], [v0, v12, v13, v14, v15, v16, v17, v18, v19, v24, v25], s[8:11]", - "s_endpgm") - self.assertEqual(reads(first), {(0, "select"), (1, "select"), (1, "ratio"), (2, "raw_float"), - (0, "raw_other")}) - self.assertEqual(reads(second), set()) - - def test_next_call_and_overwrite_kill_the_words(self): - (first, second) = analyse( - CALL32, - "v_mov_b32_e32 v6, 0", # word 2 overwritten - "v_add_f32_e32 v9, v6, v8", - "image_bvh_intersect_ray v[4:7], v[12:22], s[8:11]", - "v_add_f32_e32 v9, v4, v8", # the second call's word 0 - "s_endpgm") - self.assertEqual(reads(first), set()) - self.assertEqual(reads(second), {(0, "raw_float")}) - - -class PathTests(unittest.TestCase): - def test_overwrite_on_one_path_is_some_paths(self): - (site,) = analyse( - CALL32, - "s_cbranch_scc1 @join", - "v_mov_b32_e32 v5, 1.0", - "join:", - "v_rcp_f32_e32 v20, v5", - "s_endpgm") - self.assertEqual([e[1:4] for e in site["reads"]], [(1, "ratio", "some")]) - - def test_else_half_of_a_saved_mask_keeps_the_word(self): - (site,) = analyse( - CALL32, - "v_cmp_ne_u32_e32 vcc_lo, 4, v31", - "s_and_saveexec_b32 s40, vcc_lo", # then-half - "v_min3_u32 v5, v1, v2, v3", # overwrites word 1 in the then-lanes only - "s_andn2_b32 exec_lo, s40, exec_lo", # else-half: saved & ~then - "v_rcp_f32_e32 v20, v5", # these lanes never ran the overwrite - "s_mov_b32 exec_lo, s40", - "v_add_f32_e32 v21, v5, v8", # all lanes again: both values - "s_endpgm") - self.assertEqual([e[1:4] for e in site["reads"]], [(1, "ratio", "all"), (1, "raw_float", "some")]) - - def test_wrexec_else_half_and_restore(self): - (site,) = analyse( - CALL32, - "s_mov_b32 s41, exec_lo", - "v_cmpx_lt_u32_e32 2, v31", - "v_mov_b32_e32 v6, 0", - "s_andn2_wrexec_b32 s42, s41", # EXEC = s41 & ~EXEC - "v_cmp_eq_u32_e32 vcc_lo, v32, v6", - "s_mov_b32 exec_lo, s41", - "s_endpgm") - self.assertEqual([e[1:4] for e in site["reads"]], [(2, "raw_integer", "all")]) - - def test_unknown_exec_writer_gives_no_proof(self): - (site,) = analyse( - "s_load_dword s43, s[0:1], 0x0", - CALL32, - "v_cmp_ne_u32_e32 vcc_lo, 4, v31", - "s_and_saveexec_b32 s40, vcc_lo", - "v_min3_u32 v5, v1, v2, v3", - "s_mov_b32 exec_lo, s43", # a mask the walk cannot place - "v_rcp_f32_e32 v20, v5", - "s_endpgm") - self.assertEqual([e[1:4] for e in site["reads"]], [(1, "ratio", "some")]) - - def test_write_after_a_join_covers_reads_under_the_same_exec(self): - (site,) = analyse( - CALL32, - "s_mov_b32 s41, exec_lo", - "s_cbranch_scc1 @narrow", - "s_branch @join", - "narrow:", - "v_cmpx_lt_u32_e32 2, v31", # one path narrows, the other does not - "join:", - "v_mov_b32_e32 v6, 0", # every lane the join runs overwrites word 2 - "v_cmp_eq_u32_e32 vcc_lo, v32, v6", # so this reads no word - "s_mov_b32 exec_lo, s41", # the call's lanes again - "v_cmp_eq_u32_e32 vcc_lo, v33, v6", # lanes the narrowed path left out still hold word 2 - "s_endpgm") - self.assertEqual([e[1:4] for e in site["reads"]], [(2, "raw_integer", "some")]) - - def test_narrowing_in_a_loop_gives_no_proof(self): - (site,) = analyse( - CALL32, - "s_mov_b32 s50, exec_lo", - "loop:", - "v_readfirstlane_b32 s4, v9", - "v_cmpx_eq_u32_e32 s4, v9", # a different lane on every pass - "v_rcp_f32_e32 v20, v5", - "v_mov_b32_e32 v5, 0", # word 1 replaced in this pass's lanes - "s_xor_b32 s50, s50, exec_lo", - "s_mov_b32 exec_lo, s50", - "s_cbranch_execnz @loop", - "s_endpgm") - self.assertEqual([e[1:4] for e in site["reads"]], [(1, "ratio", "some")]) - - def test_inner_back_edge_drops_guards_and_saved_masks(self): - node = ("n", 8, census.ROOT) - st = census.SiteState({5: frozenset({(("w", 1), frozenset({("out", node)})), - (census.OTHER, frozenset({("in", node)}))})}, {40: node}, node) - out = census.strip(st) - self.assertEqual(out.masks, {}) - self.assertEqual(out.vg[5], frozenset({(("w", 1), frozenset()), (census.OTHER, frozenset())})) - self.assertEqual(st.masks, {40: node}) # the state on the other edges is untouched - - def test_loop_around_the_call_is_cut_and_counted(self): - (site,) = analyse( - "top:", - CALL32, - "v_rcp_f32_e32 v20, v5", - "s_cbranch_scc1 @top", - "s_endpgm") - self.assertEqual([e[1:4] for e in site["reads"]], [(1, "ratio", "all")]) - self.assertTrue(site["loop_carried"]) - - -class SummaryTests(unittest.TestCase): - def directory(self, tmp, listings): - for name, text in listings.items(): - with open(os.path.join(tmp, name + ".s"), "w", encoding="utf-8", newline="\n") as f: - f.write(text) - - def test_summary_partition_and_privacy(self): - listings = { - "cs_tri": listing(*DESC_LITERALS, CALL32, *TRIANGLE, "s_endpgm"), - "cs_box": listing("image_bvh64_intersect_ray v[4:7], v[0:11], s[12:15]", - "v_lshlrev_b32_e32 v10, 3, v4", "s_cbranch_scc1 @end", "v_mov_b32_e32 v4, 0", - "end:", "v_cmp_eq_u32_e32 vcc_lo, v31, v4", "s_endpgm"), - "cs_none": listing("v_mov_b32_e32 v0, 0", "s_endpgm"), - "cs_bad": listing(CALL32, "s_branch 0x40", "s_endpgm"), # a branch out of the code - } - with tempfile.TemporaryDirectory() as src, tempfile.TemporaryDirectory() as outdir: - self.directory(src, listings) - out = os.path.join(outdir, "census.json") - with contextlib.redirect_stdout(io.StringIO()) as printed: - self.assertEqual(census.main([src, "--out", out]), 0) - with open(out, "rb") as f: - blob = f.read() - self.assertNotIn(b"\r\n", blob) - s = json.loads(blob) - self.assertEqual(s["sites"], {"total": 2, "image_bvh_intersect_ray": 1, "image_bvh64_intersect_ray": 1}) - self.assertEqual(s["shaders"], {"cs": 2}) - self.assertEqual(s["not_analysed"], {"branch target outside code": 1}) - self.assertEqual(sum(v for v, _ in s["site_partition"].values()), s["sites"]["total"]) - # cs_box reads word 0 as an integer on every path (the shift) and on some paths (the compare): the - # category counts as read on every path, the compare as one read on some paths only - self.assertEqual(s["site_partition"], {"ratio+high_half": [1, 1], "raw_integer": [1, 1]}) - self.assertEqual(s["word_reads"]["sites"]["ratio"], [1, 0]) - self.assertEqual(s["word_reads"]["reads_some_paths"]["raw_integer"], 1) - self.assertEqual(s["some_paths_position"]["raw_integer"], [1, 0]) # before any later call - self.assertEqual(s["word_reads"]["per_word_sites"]["0"]["raw_integer"], [1, 0]) - self.assertEqual(s["descriptor"]["fields"]["type"], {"5": 1, "not a literal": 1}) - self.assertEqual(s["descriptor"]["word0"], {"not a literal": 2}) - self.assertEqual(s["high_half_product_readers"], {"v_cmp_gt_i32 with 0": [1, 0]}) - self.assertEqual(s["limits"]["sites with a category read on some paths only"], 0) - for text in (blob.decode("utf-8"), printed.getvalue()): - for name in listings: - self.assertNotIn(name, text) - - def test_missing_source_is_an_error(self): - with self.assertRaises(SystemExit) as cm, contextlib.redirect_stderr(io.StringIO()): - census.main([os.path.join(tempfile.gettempdir(), "no_such_shaders_dir_xyz")]) - self.assertNotEqual(cm.exception.code, 0) - - def test_output_must_not_overwrite_a_listing(self): - with tempfile.TemporaryDirectory() as src: - self.directory(src, {"cs_tri": listing(CALL32, "s_endpgm")}) - with self.assertRaises(SystemExit), contextlib.redirect_stderr(io.StringIO()): - census.main([src, "--out", os.path.join(src, "cs_tri.s")]) - with open(os.path.join(src, "cs_tri.s"), encoding="utf-8") as f: - self.assertIn("image_bvh", f.read()) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/test_image_d16_probe.py b/tests/test_image_d16_probe.py deleted file mode 100644 index 0c0f61b1b..000000000 --- a/tests/test_image_d16_probe.py +++ /dev/null @@ -1,257 +0,0 @@ -"""tools/image_d16_probe.py: the rules, the T# words and kernels per dimension, the comparison and its exit codes -(through a fake oracle that plays the GPU), and the exit-77 contract. The last class runs on the hardware when the -oracle tools are present and the GPU is GFX10, and is skipped otherwise. Standard library only.""" -import io -import json -import os -from contextlib import redirect_stdout -from pathlib import Path -import subprocess -import sys -import tempfile -import unittest -from unittest import mock - -TOOLS = Path(__file__).resolve().parents[1] / "tools" -sys.path.insert(0, str(TOOLS)) -import image_d16_probe as pr # noqa: E402 -from hw_oracle import asm, runner # noqa: E402 - - -class Rules(unittest.TestCase): - def test_self_test(self): - with redirect_stdout(io.StringIO()): - self.assertEqual(pr.self_test(), 0) - - def test_the_edges_separate_saturation_from_truncation(self): - self.assertEqual(pr.rules(0x00010000), {"trunc": 0x0000, "sat_u": 0xFFFF, "sat_s": 0x7FFF}) - self.assertEqual(pr.rules(0xFFFF7FFF), {"trunc": 0x7FFF, "sat_u": 0xFFFF, "sat_s": 0x8000}) - self.assertEqual(pr.rules(0x0000FFFF), {"trunc": 0xFFFF, "sat_u": 0xFFFF, "sat_s": 0x7FFF}) - self.assertEqual(pr.rules(0xFFFFFFFF), {"trunc": 0xFFFF, "sat_u": 0xFFFF, "sat_s": 0xFFFF}) - - -class Descriptors(unittest.TestCase): - def test_type_and_depth_word_per_dimension(self): - for dim, kind, word4 in (("1d", 8, 63), ("2d", 9, 63), ("2d_array", 13, 2), ("3d", 10, 2)): - t = pr.image_words(dim, "r32_uint") - self.assertEqual(t[3] >> 28, kind, dim) - self.assertEqual(t[4], word4, dim) # pitch - 1 for 1D/2D, last layer or depth - 1 - self.assertEqual(t[2] >> 31, 1, dim) # RESOURCE_LEVEL - - def test_two_channel_formats_keep_256_byte_rows(self): - self.assertEqual(pr.geometry("2d", "r32g32_sint"), (32, 2, 1, 64)) - self.assertEqual(pr.geometry("3d", "r32_sint"), (64, 2, 3, 384)) - - def test_each_kernel_reads_with_its_own_dimension(self): - lines = pr.kernel_lines("2d_array", "r32g32_uint") - loads = [ln for ln in lines if ln.startswith("image_load")] - self.assertEqual(loads, [ - "image_load v8, v[2:4], s[8:15] dmask:0x1 dim:SQ_RSRC_IMG_2D_ARRAY unorm", - "image_load v9, v[2:4], s[8:15] dmask:0x3 dim:SQ_RSRC_IMG_2D_ARRAY unorm d16", - "image_load_mip v10, v[2:5], s[8:15] dmask:0x3 dim:SQ_RSRC_IMG_2D_ARRAY unorm d16", - "image_load v11, v[2:4], s[8:15] dmask:0x2 dim:SQ_RSRC_IMG_2D_ARRAY unorm"]) - self.assertIn("image_load v8, v2, s[8:15] dmask:0x1 dim:SQ_RSRC_IMG_1D unorm", pr.kernel_lines("1d", "r32_sint")) - - def test_kernels_assemble_for_gfx1036(self): - try: - clang = runner.find_clang() - except runner.Unavailable as e: - self.skipTest(str(e)) - kernels = [] - for uid, (d, f) in enumerate((d, f) for d in pr.DIMS for f in pr.FORMATS): - n = pr.geometry(d, f)[3] - kernels.append(asm.Kernel(pr.kernel_lines(d, f, uid), 32, n, n * 4, raw=True)) - text, _, _ = asm.module_text(kernels, "gfx1036", wave=32) - with tempfile.TemporaryDirectory() as tmp: - s = Path(tmp) / "k.s" - s.write_text(text, encoding="utf-8") - r = subprocess.run([clang, "--target=amdgcn-amd-amdhsa", "-mcpu=gfx1036", "-c", str(s), "-o", - str(Path(tmp) / "k.o")], capture_output=True, text=True) - self.assertEqual(r.returncode, 0, r.stderr[:800]) - self.assertIn("global_store_dwordx4 v6, v[8:11], s[2:3]", text) - - -class FakeOracle: - """Plays the GPU: finds each kernel's dimension and format and answers with a rule's halves.""" - arch = "gfx1036" - device = "fake gfx1036" - - def __init__(self, rule="sat", bad_control=False, mip_off=False): - self.rule, self.bad_control, self.mip_off = rule, bad_control, mip_off - - def run(self, kernels, words=4): - by_code = {code: f for f, (code, _, _) in pr.FORMATS.items()} - by_dim = {name: d for d, (_, name, _, _) in pr.DIMS.items()} - out = [] - for k in kernels: - word1 = int(next(ln for ln in k.lines if ln.startswith("s_or_b32 s9")).split("0x")[1], 16) - fmt = by_code[(word1 >> 20) & 0x1FF] - dim = by_dim[next(ln for ln in k.lines if ln.startswith("image_load")).split("dim:")[1].split()[0]] - signed = pr.FORMATS[fmt][2] - rule = ("sat_s" if signed else "sat_u") if self.rule == "sat" else self.rule - res = [] - for i, texel in enumerate(pr.texel_values(fmt, pr.geometry(dim, fmt)[3])): - h = [pr.rules(v)[rule] for v in texel] - d16 = h[0] | ((h[1] << 16) if len(h) == 2 else pr.SEED & 0xFFFF0000) - mip = d16 ^ 1 if self.mip_off and i == 5 else d16 - x = texel[0] ^ 0x100 if self.bad_control and i == 3 else texel[0] - res += [x, d16, mip, texel[1] if len(texel) == 2 else pr.SEED] - out.append(res) - return out - - def close(self): - pass - - -def run_main(oracle, *args): - buf = io.StringIO() - with mock.patch.object(runner, "open_oracle", return_value=oracle), redirect_stdout(buf): - rc = pr.main(list(args)) - return rc, buf.getvalue() - - -class Compare(unittest.TestCase): - def test_saturating_hardware_matches_its_rule_on_every_case(self): - with tempfile.TemporaryDirectory() as d: - j = os.path.join(d, "r.json") - rc, out = run_main(FakeOracle(), "--json", j) - with open(j, encoding="utf-8") as f: - rep = json.load(f) - self.assertEqual(rc, 0, out) - self.assertEqual(len(rep["cases"]), 16) - e = rep["cases"]["3d r32_sint"] - self.assertEqual(e["forms"]["image_load"]["match"]["sat_s"], 384) - self.assertLess(e["forms"]["image_load"]["match"]["trunc"], 384) - self.assertEqual(e["forms"]["image_load_mip"]["high_half"], {"kept": 384}) - - def test_truncating_hardware_is_a_finding_not_a_failure(self): - rc, out = run_main(FakeOracle("trunc"), "--dims", "1d", "--formats", "r32_uint") - self.assertEqual(rc, 0, out) - self.assertIn("trunc 64/64", out) - - def test_a_wrong_control_word_is_a_harness_error(self): - rc, out = run_main(FakeOracle(bad_control=True), "--dims", "2d_array", "--formats", "r32_uint") - self.assertEqual(rc, 2, out) - self.assertIn("texel 3: x read back", out) - - def test_load_and_load_mip_disagreeing_exits_1(self): - rc, out = run_main(FakeOracle(mip_off=True), "--dims", "3d", "--formats", "r32g32_sint") - self.assertEqual(rc, 1, out) - - def test_not_gfx10_exits_77(self): - o = FakeOracle() - o.arch = "gfx1150" - rc, out = run_main(o) - self.assertEqual(rc, 77, out) - - -class Cli(unittest.TestCase): - def test_exits_77_without_the_tools(self): - env = dict(os.environ, LEONIDA_AMD_CLANG=str(TOOLS / "no-such-clang.exe"), LEONIDA_HW_DRM_NODE="") - r = subprocess.run([sys.executable, "-I", str(TOOLS / "image_d16_probe.py"), "--dims", "1d"], - capture_output=True, text=True, env=env) - self.assertEqual(r.returncode, 77, r.stdout + r.stderr) - self.assertIn("unavailable", r.stdout) - - def test_unknown_dimension_is_a_usage_error(self): - r = subprocess.run([sys.executable, "-I", str(TOOLS / "image_d16_probe.py"), "--dims", "cube"], - capture_output=True, text=True) - self.assertEqual(r.returncode, 2) - self.assertIn("cube", r.stderr) - - def test_bad_json_paths_rejected_before_open_oracle(self): - with tempfile.TemporaryDirectory() as tmp: - existing_dir = os.path.join(tmp, "dir") - os.mkdir(existing_dir) - file_ancestor = os.path.join(tmp, "file_ancestor") - with open(file_ancestor, "w", encoding="utf-8") as f: - f.write("x") - - bad_paths = [ - "", - " ", - "bad\x00out.json", - existing_dir, - os.path.join(tmp, "trailing") + os.sep, - os.path.join(file_ancestor, "sub", "out.json"), - ] - for bad in bad_paths: - with self.subTest(json_path=bad): - stderr = io.StringIO() - with mock.patch.object(runner, "open_oracle") as open_mock, \ - mock.patch.object(sys, "stderr", stderr): - rc = pr.main(["--json", bad]) - self.assertEqual(rc, 2) - self.assertIn("error:", stderr.getvalue()) - self.assertNotIn("Traceback", stderr.getvalue()) - open_mock.assert_not_called() - - def test_valid_nested_json_does_not_create_dirs_when_oracle_unavailable(self): - with tempfile.TemporaryDirectory() as tmp: - nested_dir = os.path.join(tmp, "a", "b") - json_path = os.path.join(nested_dir, "report.json") - stdout = io.StringIO() - with mock.patch.object(runner, "open_oracle", side_effect=runner.Unavailable("no gpu")), \ - mock.patch.object(sys, "stdout", stdout): - rc = pr.main(["--json", json_path]) - self.assertEqual(rc, 77) - self.assertFalse(os.path.exists(os.path.join(tmp, "a"))) - - def test_write_json_report_creates_parents_and_writes_lf_json(self): - with tempfile.TemporaryDirectory() as tmp: - out_path = os.path.join(tmp, "nested", "dir", "report.json") - payload = {"device": "fake", "arch": "gfx1036", "cases": {}} - err = pr.write_json_report(out_path, payload) - self.assertIsNone(err) - with open(out_path, "rb") as f: - raw = f.read() - self.assertNotIn(b"\r\n", raw) - self.assertEqual(json.loads(raw.decode("utf-8")), payload) - - def test_write_json_oserror_returns_2_without_traceback(self): - with tempfile.TemporaryDirectory() as tmp: - out_path = os.path.join(tmp, "report.json") - with mock.patch("builtins.open", side_effect=PermissionError("denied")): - err = pr.write_json_report(out_path, {"ok": True}) - self.assertIsNotNone(err) - self.assertIn("cannot write --json", err) - - stderr = io.StringIO() - with mock.patch("builtins.open", side_effect=OSError("disk full")), \ - mock.patch.object(sys, "stderr", stderr): - rc, _ = run_main(FakeOracle(), "--dims", "1d", "--formats", "r32_uint", "--json", out_path) - self.assertEqual(rc, 2) - self.assertIn("error:", stderr.getvalue()) - self.assertNotIn("Traceback", stderr.getvalue()) - - -class OnHardware(unittest.TestCase): - @classmethod - def setUpClass(cls): - try: - cls.oracle = runner.open_oracle() - except runner.Unavailable as e: - raise unittest.SkipTest(f"hardware oracle unavailable: {e}") from None - if asm.family(cls.oracle.arch) != "gfx10": - cls.oracle.close() - raise unittest.SkipTest(f"{cls.oracle.arch} is not GFX10") - - @classmethod - def tearDownClass(cls): - cls.oracle.close() - - def test_controls_hold_on_every_dimension(self): - cases = [(d, "r32_sint") for d in pr.DIMS] - kernels = [] - for uid, (d, f) in enumerate(cases): - n = pr.geometry(d, f)[3] - kernels.append(asm.Kernel(pr.kernel_lines(d, f, uid), 32, n, n * 4, raw=True)) - for (d, f), got in zip(cases, self.oracle.run(kernels)): - self.assertIsInstance(got, list, got) - e = pr.classify(d, f, got) - self.assertEqual(e["control"], [], d) - self.assertEqual(e["forms_differ"], 0, d) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/test_image_fuzz.py b/tests/test_image_fuzz.py deleted file mode 100644 index c7b2b72a7..000000000 --- a/tests/test_image_fuzz.py +++ /dev/null @@ -1,453 +0,0 @@ -"""CPU checks for tools/image_fuzz.py: the oracle, the texel mapping and the generated shader, no GPU. - -The GPU side (vk_image_fuzz, rdna2spirv.py) is what the fuzzer compares against; these tests make sure the -oracle it compares with is right, so a mismatch is the translator's and not the fuzzer's. -""" -import json -import os -from pathlib import Path -import random -import signal -import struct -import subprocess -import sys - -import pytest - -HERE = os.path.dirname(os.path.abspath(__file__)) -ROOT = os.path.dirname(HERE) -sys.path.insert(0, os.path.join(ROOT, "tools")) -import image_fuzz as imf # noqa: E402 - - -def test_empty_format_selection_is_a_usage_error(tmp_path): - work = tmp_path / "work" - result = subprocess.run([sys.executable, "-I", imf.__file__, "--formats", " , ", "--work", str(work)], - capture_output=True, text=True, timeout=60) - assert result.returncode == 2, result.stderr - assert "--formats must select at least one format" in result.stderr - assert "Traceback" not in result.stderr - assert not work.exists() - - -def test_work_that_is_a_file_is_a_usage_error(tmp_path): - work = tmp_path / "work.txt" - work.write_text("keep me", encoding="utf-8") - result = subprocess.run([sys.executable, "-I", imf.__file__, "--formats", "R8G8B8A8_UNORM", "--programs", "1", - "--work", str(work)], capture_output=True, text=True, timeout=60) - assert result.returncode == 2, result.stderr - assert "ERROR: --work is not a folder" in result.stderr - assert "Traceback" not in result.stderr - assert work.read_text(encoding="utf-8") == "keep me" - - -def test_work_under_a_file_is_a_usage_error(tmp_path): - blocker = tmp_path / "blocker.txt" - blocker.write_text("x", encoding="utf-8") - result = subprocess.run([sys.executable, "-I", imf.__file__, "--formats", "R8G8B8A8_UNORM", "--programs", "1", - "--work", str(blocker / "work")], capture_output=True, text=True, timeout=60) - assert result.returncode == 2, result.stderr - assert "ERROR: --work is not a folder" in result.stderr - assert "Traceback" not in result.stderr - assert blocker.read_text(encoding="utf-8") == "x" - - -def test_work_that_is_a_dangling_symlink_is_a_usage_error(tmp_path): - link = tmp_path / "link" - try: - os.symlink(tmp_path / "missing", link, target_is_directory=True) - except (OSError, NotImplementedError): - pytest.skip("cannot create a symlink here") - result = subprocess.run([sys.executable, "-I", imf.__file__, "--formats", "R8G8B8A8_UNORM", "--programs", "1", - "--work", str(link)], capture_output=True, text=True, timeout=60) - assert result.returncode == 2, result.stderr - assert "ERROR: --work is not a folder" in result.stderr - assert "Traceback" not in result.stderr - - -def test_format_codes_match_the_translator_table(): - with open(os.path.join(imf.TOOLS, "gfx10_formats.json"), encoding="utf-8") as f: - by_name = {name: int(code) for code, name in json.load(f).items()} - gfx10_names = { - "R8G8B8A8_UNORM": "GFX10_FORMAT_8_8_8_8_UNORM", - "R16G16B16A16_SFLOAT": "GFX10_FORMAT_16_16_16_16_FLOAT", - "R32G32B32A32_SFLOAT": "GFX10_FORMAT_32_32_32_32_FLOAT", - "R32_SFLOAT": "GFX10_FORMAT_32_FLOAT", - "R8G8B8A8_UINT": "GFX10_FORMAT_8_8_8_8_UINT", - "R8G8B8A8_SINT": "GFX10_FORMAT_8_8_8_8_SINT", - } - assert set(gfx10_names) == set(imf.FORMATS) - for name, (_, code, bpp, model) in imf.FORMATS.items(): - assert by_name[gfx10_names[name]] == code, name - assert bpp in (4, 8, 16) and model in ("unorm8", "half4", "float4", "float1", "uint8", "sint8"), name - - -def test_unorm_oracle_divides_by_255(): - texels = bytes([0, 1, 127, 255, 10, 20, 30, 40]) - got = imf.oracle("R8G8B8A8_UNORM", texels, 2, 1) - assert got[0] == [0.0, imf.f32(1 / 255.0), imf.f32(127 / 255.0), 1.0] - assert got[1] == [imf.f32(v / 255.0) for v in (10, 20, 30, 40)] - - -def test_half_oracle_reads_four_binary16(): - wanted = [-2.0, -0.0, 0.5, 65504.0] - texels = b"".join(struct.pack(" None: - work = tmp_path / "work" - work.mkdir() - build = tmp_path / "build" - build.mkdir() - harness = build / (imf.HARNESS + (".exe" if os.name == "nt" else "")) - harness.touch() - monkeypatch.setattr(imf, "assemble", lambda *_args: None) - - def run(cmd: list[str], **_kwargs: object) -> subprocess.CompletedProcess[str]: - if cmd[0] == str(harness): - return subprocess.CompletedProcess(cmd, 77, "unsupported: no Vulkan 1.2 device", "") - out = work / "spirv" - out.mkdir() - (out / "vs_ids.spv").touch() - return subprocess.CompletedProcess(cmd, 0, "2 shaders: 1 translated, 1 pass spirv-val\n 1 s_trap", "") - - monkeypatch.setattr(imf.subprocess, "run", run) - with pytest.raises(SystemExit, match=r"(?s)ps_image_load\.spv.*s_trap"): - imf.run_case("R8G8B8A8_UNORM", 4, 4, random.Random(1), str(work), str(build), False, False) - - -def test_unsupported_without_a_reason_line_still_skips(monkeypatch, tmp_path, capsys): - assert run_case_with_harness_result(monkeypatch, tmp_path, 77, "device: X\n") is None - assert "SKIP (the device does not support the set)" in capsys.readouterr().out - - -def test_a_harness_error_is_a_failure_not_a_skip(monkeypatch, tmp_path, capsys): - assert run_case_with_harness_result(monkeypatch, tmp_path, 1, "device: X\nvkCreateDevice failed\n") is False - out = capsys.readouterr().out - assert "FAIL (vk_image_fuzz exit 1: vkCreateDevice failed)" in out and "SKIP" not in out - assert " device: X" in out # the earlier lines are printed too - - -def test_a_crash_names_the_signal_and_prints_stderr(monkeypatch, tmp_path, capsys): - # #1429: ANV segfaulted in vkCreateGraphicsPipelines and the fuzzer printed only "FAIL (harness error)". - stderr = "validation: pipeline layout ok\ncreating graphics pipeline\n" - assert run_case_with_harness_result(monkeypatch, tmp_path, -signal.SIGSEGV, "device: X\n", stderr) is False - out = capsys.readouterr().out - assert "FAIL (vk_image_fuzz killed by SIGSEGV: creating graphics pipeline)" in out - assert " vk_image_fuzz stderr:\n validation: pipeline layout ok\n creating graphics pipeline\n" in out - assert "harness error" not in out - - -def test_a_silent_crash_still_says_how_the_harness_ended(monkeypatch, tmp_path, capsys): - assert run_case_with_harness_result(monkeypatch, tmp_path, 0xC0000005, "") is False - out = capsys.readouterr().out - assert "FAIL (vk_image_fuzz exit 0xc0000005 (access violation), no output)" in out - - -def test_a_long_stderr_prints_only_its_tail(monkeypatch, tmp_path, capsys): - stderr = "".join(f"line {i}\n" for i in range(50)) - assert run_case_with_harness_result(monkeypatch, tmp_path, 3, "", stderr) is False - out = capsys.readouterr().out - assert f"stderr (last {imf.STDERR_TAIL} of 50 lines):" in out - assert " line 49" in out and f" line {50 - imf.STDERR_TAIL}\n" in out - assert f" line {49 - imf.STDERR_TAIL}\n" not in out - - -@pytest.mark.parametrize("returncode,want", [ - (1, "exit 1"), - (2, "exit 2"), - (-signal.SIGABRT, "killed by SIGABRT"), - (-99, "killed by signal 99"), - (0xC0000409, "exit 0xc0000409 (stack buffer overrun)"), - (0xC0001234, "exit 0xc0001234"), -]) -def test_exit_status(returncode, want): - assert imf.exit_status(returncode) == want - - -def test_self_test_runs(): - r = subprocess.run([sys.executable, "-I", os.path.join(ROOT, "tools", "image_fuzz.py"), "--self-test"], - capture_output=True, text=True) - assert r.returncode == 0, r.stderr - assert "self-test: ok" in r.stdout - - -def build_dir_main_uses(monkeypatch, argv): - """The build folder main() hands run_case for `argv`, with run_case stubbed to a pass.""" - seen = [] - monkeypatch.setattr(imf, "run_case", lambda *args, **_kw: seen.append(args[5]) or True) - monkeypatch.setattr(sys, "argv", ["image_fuzz.py", "--programs", "1"] + argv) - assert imf.main() == 0 - return seen[0] - - -def test_default_build_is_runtime_build_on_every_platform(monkeypatch, tmp_path): - # It was runtime/build/linux, which only a Linux build following docs/testing.md has: on Windows (and on Linux - # following docs/shader_validation.md) every run stopped with "vk_image_fuzz not found" unless --build was given. - monkeypatch.setattr(imf, "find_test_program", lambda build, name: None) - assert build_dir_main_uses(monkeypatch, ["--work", str(tmp_path)]) == os.path.join(imf.ROOT, "runtime", "build") - - -def test_visual_studio_config_subfolder_is_found(monkeypatch, tmp_path): - build = tmp_path / "build" - (build / "RelWithDebInfo").mkdir(parents=True) - (build / "RelWithDebInfo" / (imf.HARNESS + (".exe" if os.name == "nt" else ""))).touch() - got = build_dir_main_uses(monkeypatch, ["--build", str(build), "--work", str(tmp_path / "w")]) - assert got == str(build / "RelWithDebInfo") - - -def test_translate_forwards_pc_tail_ubo(monkeypatch, tmp_path): - cmds = [] - - def fake_run(cmd, **_kw): - cmds.append(list(cmd)) - out = cmd[cmd.index("--out") + 1] # translate() now checks the two programs were emitted - os.makedirs(out, exist_ok=True) - for name in ("vs_ids.spv", "ps_image_load.spv"): - open(os.path.join(out, name), "wb").close() - return subprocess.CompletedProcess(cmd, 0, "", "") - - monkeypatch.setattr(imf.subprocess, "run", fake_run) - imf.translate(str(tmp_path)) - imf.translate(str(tmp_path), pc_tail=True) - assert "--pc-tail-ubo" not in cmds[0] - assert "--pc-tail-ubo" in cmds[1] - - -def test_run_case_passes_pc_tail_to_translator_and_harness(monkeypatch, tmp_path): - build = tmp_path / "build" - build.mkdir() - (build / (imf.HARNESS + (".exe" if os.name == "nt" else ""))).touch() - seen_translate = [] - seen_env = [] - monkeypatch.setattr(imf, "assemble", lambda *_args: None) - monkeypatch.setattr(imf, "translate", lambda work, pc_tail=False: seen_translate.append(pc_tail) or str(tmp_path / "spirv")) - - def fake_run(cmd, **kw): - seen_env.append(kw.get("env")) - return subprocess.CompletedProcess(cmd, 77, "unsupported: test\n", "") - - monkeypatch.setattr(imf.subprocess, "run", fake_run) - imf.run_case("R8G8B8A8_UNORM", 4, 4, random.Random(1), str(tmp_path), str(build), False, False, pc_tail=True) - assert seen_translate == [True] - assert seen_env[0]["LEONIDA_PC_TAIL_UBO"] == "1" - - -def test_main_enables_pc_tail_ubo_from_flag_or_env(monkeypatch, tmp_path): - for argv, env_val, want in ( - ([], "", False), - (["--pc-tail-ubo"], "", True), - ([], "1", True), - ([], "true", True), - ([], "0", False), - ): - seen = [] - monkeypatch.setenv("LEONIDA_PC_TAIL_UBO", env_val) - monkeypatch.setattr(imf, "run_case", lambda *args, **kw: seen.append(kw.get("pc_tail", False)) or True) - monkeypatch.setattr(sys, "argv", ["image_fuzz.py", "--programs", "1", "--work", str(tmp_path)] + argv) - assert imf.main() == 0 - assert seen == [want], (argv, env_val) diff --git a/tests/test_image_fuzz_hw.py b/tests/test_image_fuzz_hw.py deleted file mode 100644 index 1786c583b..000000000 --- a/tests/test_image_fuzz_hw.py +++ /dev/null @@ -1,304 +0,0 @@ -"""tools/image_fuzz.py --oracle hw without a GPU: the T# words per GPU family (exact dwords), the texture layout, the -native kernel text, the model's dwords, the negative control and the exit-77 contract. The last test runs on the -hardware when the oracle tools are present and is skipped otherwise. -""" -import json -import os -import random -import struct -import sys - -import pytest - -HERE = os.path.dirname(os.path.abspath(__file__)) -ROOT = os.path.dirname(HERE) -sys.path.insert(0, os.path.join(ROOT, "tools")) -import image_fuzz as imf # noqa: E402 -from hw_oracle import asm, runner, tsharp # noqa: E402 - -GFX11, GFX10, GFX101 = "gfx1150", "gfx1030", "gfx1010" - - -def test_t_sharp_gfx11_exact_words(): - # 16x8 R8G8B8A8_UNORM, linear: FORMAT 42 at [27:20], WIDTH_LO = 15 & 3 at [31:30], WIDTH_HI = 15 >> 2, - # HEIGHT = 7 at [27:14], DST_SEL 4 5 6 7, TYPE 9 (2D) at [31:28], pitch 64 texels (256 bytes) - 1 in DEPTH. - assert tsharp.image_words(GFX11, "R8G8B8A8_UNORM", 16, 8, 4) == [ - 0, 0xC2A00000, 0x0001C003, 0x90000FAC, 0x3F, 0x00400000, 0, 0] - - -def test_t_sharp_gfx10_exact_words(): - # The same texture on GFX10.3: FORMAT 56 at [28:20], RESOURCE_LEVEL (bit 31 of word 2) set, same pitch field. - assert tsharp.image_words(GFX10, "R8G8B8A8_UNORM", 16, 8, 4) == [ - 0, 0xC3800000, 0x8001C003, 0x90000FAC, 0x3F, 0x00400000, 0, 0] - - -def test_t_sharp_gfx101_has_no_pitch_field(): - assert tsharp.image_words(GFX101, "R8G8B8A8_UNORM", 16, 8, 4)[4] == 0 - assert not tsharp.has_custom_pitch(GFX101) and tsharp.has_custom_pitch(GFX10) and tsharp.has_custom_pitch(GFX11) - - -def test_t_sharp_wide_texture_and_one_channel_swizzle(): - words = tsharp.image_words(GFX11, "R32_SFLOAT", 64, 32, 4, (4, 0, 0, 1)) - assert words[1] == (22 << 20) | (3 << 30) # width 64: WIDTH_LO = 63 & 3 - assert words[2] == 15 | (31 << 14) # WIDTH_HI = 63 >> 2 - assert words[3] == 0x90000204 # DST_SEL x,0,0,1 and the 2D type - assert words[4] == 63 # 64 texels * 4 bytes = 256 bytes: pitch 64 - words = tsharp.image_words(GFX11, "R32G32B32A32_SFLOAT", 8, 8, 16) - assert words[1] == (63 << 20) | (3 << 30) and words[4] == 15 # 8 * 16 = 128 bytes pads to 256: pitch 16 - - -def test_t_sharp_rejects_what_it_cannot_describe(): - with pytest.raises(ValueError): - tsharp.image_words("gfx1201", "R8G8B8A8_UNORM", 8, 8, 4) # GFX12 is another layout - with pytest.raises(ValueError): - tsharp.image_words(GFX11, "R8G8B8A8_UNORM", 0, 8, 4) - with pytest.raises(KeyError): - tsharp.image_words(GFX11, "D32_SFLOAT", 8, 8, 4) - - -def test_format_tables_agree_with_the_translator_table_and_each_other(): - with open(os.path.join(imf.TOOLS, "gfx10_formats.json"), encoding="utf-8") as f: - by_name = {name: int(code) for code, name in json.load(f).items()} - names = {"R8G8B8A8_UNORM": "8_8_8_8_UNORM", "R16G16B16A16_SFLOAT": "16_16_16_16_FLOAT", - "R32G32B32A32_SFLOAT": "32_32_32_32_FLOAT", "R32_SFLOAT": "32_FLOAT", - "R8G8B8A8_UINT": "8_8_8_8_UINT", "R8G8B8A8_SINT": "8_8_8_8_SINT"} - assert set(tsharp.IMG_FORMATS["gfx10"]) == set(tsharp.IMG_FORMATS["gfx11"]) == set(imf.FORMATS) == set(names) - for fmt, short in names.items(): - assert tsharp.IMG_FORMATS["gfx10"][fmt] == by_name["GFX10_FORMAT_" + short] == imf.FORMATS[fmt][1] - # GFX11 numbers the formats in LLVM's UfmtGFX11 order: no 10_10_10_2-style gaps filled differently from GFX10 - assert len(set(tsharp.IMG_FORMATS["gfx11"].values())) == len(imf.FORMATS) - - -def test_pitch_and_layout(): - assert [tsharp.pitch_texels(w, 4) for w in (8, 16, 32, 64)] == [64, 64, 64, 64] - assert [tsharp.pitch_texels(w, 16) for w in (8, 16, 32, 64)] == [16, 16, 32, 64] - assert tsharp.pitch_texels(64, 8) == 64 - tight = bytes(range(32)) # 8 x 1 RGBA8 texels - laid = tsharp.lay_out(tight, 8, 1, 4) - assert laid == tight + b"\xcd" * 224 - assert len(tsharp.lay_out(bytes(8 * 4 * 3), 8, 3, 4)) == 3 * 256 - - -def test_lanes(): - assert tsharp.lanes(8, 8) == (64, 1) - assert tsharp.lanes(32, 32) == (1024, 1) - assert tsharp.lanes(64, 64) == (1024, 4) - - -def case(fmt="R8G8B8A8_UNORM", width=8, height=8, dmask=0xf, wave=32, index=0, seed=5): - data = imf.make_texels(fmt, width, height, random.Random(seed)) - return imf.Case(index, fmt, width, height, dmask, data, wave) - - -def test_kernel_text_per_family(): - c = case(width=64, height=64, dmask=0x5) - for arch in (GFX11, GFX10): - k = imf.hw_kernel(arch, c) - text = "\n".join(k.lines) - assert k.threads == 1024 and k.words == 64 * 64 * 4 and k.raw and k.wave == 32 - assert "image_load v[8:9], v[2:3], s[8:15] dmask:0x5 dim:SQ_RSRC_IMG_2D unorm" in text - assert text.count("image_load") == 4 # 4096 texels over 1024 lanes - assert "s_getpc_b64 s[4:5]" in text and ".p2align 8" in text and ".Ltex0:" in text - assert text.index("s_endpgm") < text.index(".Ltex0:") # the texture sits behind the code - full = asm.raw_kernel_text("k0", k.lines, arch) - assert ("global_store_b128 v4, v[8:11], s[2:3]" in full) == (arch == GFX11) - assert ("global_store_dwordx4 v4, v[8:11], s[2:3]" in full) == (arch == GFX10) - one = imf.hw_kernel(GFX11, case(dmask=0x2)) - assert "image_load v8, v[2:3]" in "\n".join(one.lines) - - -def test_kernel_data_is_the_laid_out_texture(): - c = case(width=8, height=2) - lines = imf.hw_kernel(GFX11, c).lines - start = lines.index(".Ltex0:") + 1 - data = b"".join(int(x, 16).to_bytes(4, "little") for ln in lines[start:] for x in ln.split(".long")[1].split(",")) - assert data == tsharp.lay_out(c.data[0], 8, 2, 4) - - -def test_kernel_loads_the_t_sharp_the_builder_made(): - c = case(fmt="R16G16B16A16_SFLOAT", width=16, height=8) - text = "\n".join(imf.hw_kernel(GFX11, c).lines) - words = tsharp.image_words(GFX11, c.fmt, 16, 8, 8) - assert f"s_or_b32 s9, s9, 0x{words[1]:08x}" in text - for i in range(2, 8): - assert f"s_mov_b32 s{8 + i}, 0x{words[i]:08x}" in text - - -def test_expected_words_pack_dmask_and_keep_sentinels(): - c = case(fmt="R32G32B32A32_SFLOAT", width=8, height=8, dmask=0x5) - want = imf.expected_words(c.fmt, c.data[0], 8, 8, 0x5) - assert len(want) == 8 * 8 * 4 - texel = struct.unpack_from("<4f", c.data[0], 0) - first = [struct.unpack(" Load came back as garbage. -""" -import re -from collections.abc import Callable -from pathlib import Path - -import pytest - -from conftest import Shader, requires_tools -from test_image_load_typed import Module - -pytestmark = requires_tools - - -def test_cube_load_d16_selects_the_format_at_the_array_binding(make_shader: Callable[[str], Shader]) -> None: - fixture = Path(__file__).parent / "semantic" / "fixtures" / "cube_load_d16.asm" - shader = make_shader(fixture.read_text(encoding="utf-8")) - mod = Module(shader.translate()) - shader.validate(mod.text) - assert {image[0] for _, _, image in mod.fetches()} == {"%uint", "%int", "%float"} - for _, var, image in mod.fetches(): - assert (mod.binding[var], image[1:4]) == (3, ["2D", "0", "1"]) - for fmt, kind in ((20, "uint"), (21, "sint"), (22, "float")): # GFX10 32_UINT/SINT/FLOAT - assert mod.branch(fmt << 20, 5) == kind - assert mod.branch(fmt << 20, 0) == "float" - - -@pytest.mark.parametrize("mask,dst", [("0x1", "v3"), ("0x3", "v3"), ("0x7", "v[3:4]")]) -def test_d16_image_load_reads_integer_views(make_shader, mask, dst): - sh = make_shader("v_mov_b32 v1, 0\nv_mov_b32 v2, 0\n" - f"image_load {dst}, v[1:2], s[8:15] dmask:{mask} dim:SQ_RSRC_IMG_2D unorm d16\n" - "s_waitcnt vmcnt(0)\nexp mrt0 v3, v4, v3, v4 done vm\ns_endpgm\n", name="ps_d16_load") - spv = sh.translate() - fetches = re.findall(r"OpImageFetch %(\w+) ", spv) - assert "v4uint_st" in fetches and "v4int_st" in fetches, "d16 image_load never reads the uint/sint views" - assert "OpImageRead" not in spv and "StorageImageReadWithoutFormat" not in spv # sampled aliases, not storage - assert "PackHalf2x16" not in spv # the float branch keeps the integer RTE f16 pack (#489) - sh.validate(spv) - - -@pytest.mark.parametrize("load,addr,dim", [("image_load", "v[1:2]", "2D"), ("image_load_mip", "v[4:7]", "3D")]) -def test_d16_integer_fetch_saturates_before_packing(make_shader, load, addr, dim): - shader = make_shader(f"{load} v3, {addr}, s[8:15] dmask:0x9 dim:SQ_RSRC_IMG_{dim} d16\n" - "s_waitcnt vmcnt(0)\nexp mrt0 v3, v3, v3, v3 done vm\ns_endpgm\n", name="ps_d16_sat") - text = shader.translate() - # R and A are both narrowed on each integer path. Full-width and float paths have different conversions. - for op, bounds in (("UMin", [65535]), ("SClamp", [0xffff8000, 32767])): - clamps = re.findall(rf"OpExtInst %\w+ %glsl {op} (%\w+(?: %\w+)+)", text) - assert len(clamps) == 2 - for args in clamps: - bound_ids = args.split()[1:] - assert len(bound_ids) == len(bounds) - for bound, expected in zip(bound_ids, bounds): - cast = re.search(rf"{bound} = OpBitcast %int (%\w+)", text) - const = cast[1] if cast else bound - assert re.search(rf"{const} = OpConstant %uint {expected}\b", text) - shader.validate(text) diff --git a/tests/test_image_load_typed.py b/tests/test_image_load_typed.py deleted file mode 100644 index 77f54fcb7..000000000 --- a/tests/test_image_load_typed.py +++ /dev/null @@ -1,646 +0,0 @@ -"""Typed image_load in tools/rdna2spirv.py reads every format from the sampled array (SHADER-151; standard library only: -no GPU, LLVM or game files; SPIRV-Tools only for the optional validation test). - - python -I tests/test_image_load_typed.py - -The image's numeric type lives in the T# (word 1 FORMAT [28:20]), so the translator branches on it at run time. -UINT and SINT formats are fetched through uint and sint aliases of the dimension's sampled array (same set and -binding), everything else and a lookup miss (index 0, the RGBA8_UNORM fallback) through the float array. Nothing -reads a storage image, so a shader that only loads declares no StorageImageReadWithoutFormat (which Intel Xe-LP -lacks, #619) and no StorageImageWriteWithoutFormat. These tests translate small pixel shaders and check the SPIR-V: -the capabilities, which binding and component type each fetch reads, and, with a small evaluator of the code that -picks the branch, the branch taken for all 512 FORMAT values with a hit and with a miss. -runtime/test/shaders/cs_imgload.asm checks the result on a GPU (vk_store_test load). -""" -import itertools -import os -import re -import shutil -import struct -import sys -import tempfile -import unittest -from pathlib import Path - -ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) -sys.dont_write_bytecode = True -sys.path.insert(0, os.path.join(ROOT, "tools")) -import rdna2spirv # noqa: E402 - -EMPTY_DXBC = b"DXBC" + bytes(16) + struct.pack(" (address registers, sampled binding, SPIR-V Dim, arrayed) -DIMS = {"2D": ("v[4:5]", 0, "2D", "0"), "2D_ARRAY": ("v[4:6]", 3, "2D", "1"), - "3D": ("v[4:6]", 6, "3D", "0"), "1D": ("v4", 5, "1D", "0"), - "CUBE": ("v[4:6]", 3, "2D", "1")} -STORAGE_IMAGE_CAPS = {"StorageImageReadWithoutFormat", "StorageImageWriteWithoutFormat", "Image1D"} - - -def translate(lines): - """SPIR-V assembly text of a pixel shader made of these instruction lines (and an export of v3).""" - with tempfile.TemporaryDirectory() as tmp: - os.mkdir(os.path.join(tmp, "disasm")) - with open(os.path.join(tmp, "ps_load.dxbc"), "wb") as f: - f.write(EMPTY_DXBC) - path = os.path.join(tmp, "disasm", "ps_load.s") - with open(path, "w", encoding="utf-8") as f: - f.write("; ps_load code 0x0..0x100\n" + "".join("\t" + ln + "\n" for ln in lines + EPILOGUE)) - return rdna2spirv.translate(path) - - -def load_shader(dim, dmask=0xF): - addr = DIMS[dim][0] - return translate(["v_mov_b32 v4, 1", "v_mov_b32 v5, 2", "v_mov_b32 v6, 0", - f"image_load v[0:3], {addr}, s[0:7] dmask:0x{dmask:x} dim:SQ_RSRC_IMG_{dim} unorm", - "s_waitcnt vmcnt(0)"]) - - -def vgpr_stores(m): - """VGPR index -> stored value id, from the OpStore lines (they carry no result id, so they are not in - m.order; the hoisted %reg_vN pointers are OpAccessChains into %vgpr, so they are).""" - reg_to_vgpr = {} - for rid, (op, args) in m.defs.items(): - if op == "OpAccessChain" and len(args) >= 3 and args[1] == "%vgpr": - reg_to_vgpr[rid] = m.value(args[2], 0, 0) - stores = {} - for line in m.text.splitlines(): - mm = re.match(r"\s*OpStore (%\w+) (%\w+)", line) - if mm and mm.group(1) in reg_to_vgpr: - stores[reg_to_vgpr[mm.group(1)]] = mm.group(2) - return stores - - -class Module: - """The instructions of a SPIR-V assembly text by result id, its decorations and capabilities.""" - - def __init__(self, text: str, vgprs: dict[int, int] | None = None): - self.vgprs = vgprs - self.text = text - self.defs, self.binding, self.order = {}, {}, [] - self.caps = set(re.findall(r"^\s*OpCapability (\w+)", text, re.M)) - for line in text.splitlines(): - m = re.match(r"\s*(%\w+) = (Op\w+)\s*(.*)$", line) - if m: - self.defs[m.group(1)] = (m.group(2), m.group(3).split()) - self.order.append((m.group(1), m.group(2), m.group(3).split())) - continue - m = re.match(r"\s*OpDecorate (%\w+) Binding (\d+)$", line) - if m: - self.binding[m.group(1)] = int(m.group(2)) - m = re.match(r"\s*(OpBranchConditional) (.*)$", line) - if m: - self.order.append((None, m.group(1), m.group(2).split())) - - def fetches(self): - """(result id, image variable, OpTypeImage operands) of every OpImageFetch.""" - out = [] - for rid, op, args in self.order: - if op != "OpImageFetch": - continue - load_op, load = self.defs[args[1]] - assert load_op == "OpLoad", load_op - chain_op, chain = self.defs[load[1]] - assert chain_op == "OpAccessChain", chain_op - out.append((rid, chain[1], self.defs[load[0]][1])) - return out - - def integer_coord_vgpr(self, operand): - op, cast = self.defs[operand] - assert op == "OpBitcast", op - op, load = self.defs[cast[1]] - assert op == "OpLoad", op - op, ptr = self.defs[load[1]] - assert (op, ptr[1]) == ("OpAccessChain", "%vgpr"), (op, ptr) - return self.value(ptr[2], 0, 0) - - def value(self, x, word1, index): - """Evaluate the uint/bool id x given the T#'s word 1 and the bindless index of the lookup.""" - if x in ("%true", "%false"): - return x == "%true" - op, a = self.defs[x] - if op == "OpConstant": - return int(a[1], 0) - if op == "OpConstantTrue": - return True - if op == "OpFunctionCall" and a[1] == "%desc_lookup_fn": - return index - if op == "OpLoad": - ptr_op, p = self.defs[a[1]] - assert ptr_op == "OpAccessChain", ptr_op - if p[1] == "%vgpr" and self.vgprs is not None: - return self.vgprs[self.value(p[2], word1, index)] - if p[1] == "%sgpr": - assert self.value(p[2], word1, index) == 1, "only T# word 1 is read" - return word1 - var_op, v = self.defs[p[1]] - assert var_op == "OpVariable" and v[1] == "Private", (var_op, v) - words = self.defs[v[2]][1][1:] # OpConstantComposite %fmt_mask_arr - return self.value(words[self.value(p[2], word1, index)], word1, index) - if op == "OpGroupNonUniformBroadcastFirst": # desc_lookup makes the descriptor word uniform: one invocation - return self.value(a[2], word1, index) # here, so the value itself (a[1] is the Subgroup scope) - if op == "OpGroupNonUniformShuffle": # the same for a wave32 pixel shader's half (SHADER-731, #4225) - return self.value(a[2], word1, index) - u = [self.value(y, word1, index) for y in a[1:]] - if op == "OpBitcast": - return u[0] - if op == "OpBitFieldUExtract": - return (u[0] >> u[1]) & ((1 << u[2]) - 1) - if op == "OpShiftRightLogical": - return u[0] >> u[1] - if op == "OpBitwiseAnd": - return u[0] & u[1] - if op == "OpINotEqual": - return u[0] != u[1] - if op == "OpLogicalAnd": - return u[0] and u[1] - raise AssertionError(f"unexpected {op} in the branch condition") - - def branch(self, word1, index): - """'sint', 'uint' or 'float': which fetch the typed load's two selections lead to.""" - conds, last = {}, None - for rid, op, args in self.order: - if op == "OpBranchConditional": - last = args[0] - elif op == "OpAccessChain" and re.fullmatch(r"%itx[12]_\d", args[1]): - conds["sint" if args[1].startswith("%itx2") else "uint"] = last - assert set(conds) == {"sint", "uint"}, conds - for kind in ("sint", "uint"): # the sint selection encloses the uint one - if self.value(conds[kind], word1, index): - return kind - return "float" - - -def format_class(fmt): - name = rdna2spirv.GFX10_FORMATS.get(fmt, "") - return "uint" if name.endswith("_UINT") else "sint" if name.endswith("_SINT") else "float" - - -class LoadOnlyShaders(unittest.TestCase): - def test_volume_mip_fetch_uses_xyz_level_and_descriptor_type(self): - for dst, modifier in (("v[0:1]", ""), ("v0", " d16")): - with self.subTest(modifier=modifier): - m = Module(translate([f"image_load_mip {dst}, v[4:7], s[0:7] " - f"dmask:0x9 dim:SQ_RSRC_IMG_3D unorm{modifier}"])) - fetches = m.fetches() - self.assertEqual({image[0] for _, _, image in fetches}, {"%float", "%uint", "%int"}) - for rid, var, image in fetches: - self.assertEqual((m.binding[var], image[1]), (6, "3D")) - _, _, xyz, mask, lod = m.defs[rid][1] - self.assertEqual(mask, "Lod") - op, coords = m.defs[xyz] - self.assertEqual((op, coords[0]), ("OpCompositeConstruct", "%v3int")) - self.assertEqual([m.integer_coord_vgpr(v) for v in [*coords[1:], lod]], [4, 5, 6, 7]) - for fmt, kind in ((75, "uint"), (76, "sint"), (77, "float")): # RGBA32 formats - self.assertEqual(m.branch(fmt << 20, 1), kind) - self.assertEqual(m.branch(fmt << 20, 0), "float") - - def test_2d_explicit_mip_reaches_every_typed_fetch(self): - m = Module(translate(["image_load_mip v[0:3], v[4:6], s[0:7] dmask:0xf dim:SQ_RSRC_IMG_2D", - "s_waitcnt vmcnt(0)"])) - fetches = m.fetches() - self.assertEqual({image[0] for _, _, image in fetches}, {"%float", "%uint", "%int"}) - for rid, var, _ in fetches: - self.assertEqual(m.binding[var], 0) - operands = m.defs[rid][1] - self.assertEqual(operands[-2], "Lod") - self.assertEqual(m.integer_coord_vgpr(operands[-1]), 6) - - def test_a16_2d_mip_address(self) -> None: - with open(os.path.join(ROOT, "tests", "semantic", "fixtures", "packed_mip_load_2d.asm"), - encoding="ascii") as fixture: - forms = [line.strip() for line in fixture if line.startswith("image_load_mip")] - regs = {8: 0xFFFF8001, 9: 0xDEAD0003, 18: 0x8000FFFE, 5: 0xCAFE0007} - expected = ((0x8001, 0xFFFF, 3), (0xFFFE, 0x8000, 7)) - self.assertEqual(len(forms), len(expected)) - for line, address in zip(forms, expected): - with self.subTest(line=line): - m = Module(translate([line]), vgprs=regs) - fetches = m.fetches() - self.assertEqual({image[0] for _, _, image in fetches}, {"%float", "%uint", "%int"}) - for rid, _, _ in fetches: - _, _, coord, mode, lod = m.defs[rid][1] - op, (ty, x, y) = m.defs[coord] - self.assertEqual((op, ty, mode), ("OpCompositeConstruct", "%v2int", "Lod")) - self.assertEqual(tuple(m.value(v, 0, 0) for v in (x, y, lod)), address) - - def test_a16_2d_mip_status_is_unsupported(self) -> None: - for destination, status in (("v[0:1]", "tfe"), ("v0", "lwe")): - with self.subTest(status=status), self.assertRaises(rdna2spirv.Unsupported): - translate([f"image_load_mip {destination}, v[8:9], s[0:7] dmask:0x1 dim:SQ_RSRC_IMG_2D a16 {status}"]) - - def test_2d_explicit_mip_d16_packs_only_selected_components(self): - listing = ["image_load_mip v0, v[4:6], s[0:7] dmask:0x9 dim:SQ_RSRC_IMG_2D d16", - "s_waitcnt vmcnt(0)"] - m = Module(translate(listing)) - self.assertEqual({image[0] for _, _, image in m.fetches()}, {"%float", "%uint", "%int"}) - for rid, _, _ in m.fetches(): - bits, = (r for r, op, args in m.order if op == "OpBitcast" and args[1] == rid) - components = [int(args[2]) for _, op, args in m.order if op == "OpCompositeExtract" and args[1] == bits] - self.assertEqual(components, [0, 3]) - # All three branches write just v0: R in the low half and A in the high half. - writes = [m.defs[ptr][1] for ptr in re.findall(r"^\s*OpStore (%\w+) ", m.text, re.MULTILINE)] - vgprs = [m.value(pointer[2], 0, 0) for pointer in writes if len(pointer) > 2 and pointer[1] == "%vgpr"] - self.assertEqual(vgprs.count(0), 3) - self.assertNotIn(1, vgprs) - - def test_no_storage_image_capability_and_no_storage_binding(self): - for dim in DIMS: - with self.subTest(dim=dim): - m = Module(load_shader(dim)) - self.assertFalse(m.caps & STORAGE_IMAGE_CAPS, sorted(m.caps)) - self.assertNotIn("OpImageRead", m.text) - # Set 0 bindings 4 and 7-19 are storage images (runtime/src/vulkan_bindless.h). - self.assertEqual(set(m.binding.values()), {0, 1, 2, DIMS[dim][1]}) - - def test_each_component_type_is_fetched_from_the_sampled_binding_of_its_dimension(self): - for dim, (_, binding, sdim, arrayed) in DIMS.items(): - with self.subTest(dim=dim): - m = Module(load_shader(dim)) - seen = {} - for _, var, image in m.fetches(): - # OpTypeImage - self.assertEqual(image[1:], [sdim, "0", arrayed, "0", "1", "Unknown"]) - self.assertEqual(m.binding[var], binding) - seen[image[0]] = var - self.assertEqual(set(seen), {"%int", "%uint", "%float"}) - self.assertEqual(len(set(seen.values())), 3, "one variable per component type") - - def test_the_tsharp_format_picks_the_fetch_and_a_miss_takes_the_float_one(self): - """All 512 FORMAT values: the 30 UINT and 15 SINT GFX10 formats read as uint and sint when the T# was found - (index 5), everything reads float on a miss (index 0). Bits outside FORMAT [28:20] don't matter.""" - m = Module(load_shader("2D")) - counts = {"uint": 0, "sint": 0, "float": 0} - for fmt in range(512): - want = format_class(fmt) - counts[want] += 1 - for other in (0, 0xE00FFFFF): - word1 = (fmt << 20) | other - self.assertEqual(m.branch(word1, 5), want, f"FORMAT {fmt} word1 {word1:#x}") - self.assertEqual(m.branch(word1, 0), "float", f"FORMAT {fmt} miss") - self.assertEqual(counts, {"uint": 30, "sint": 15, "float": 512 - 45}) - - def test_only_the_dmask_components_are_written(self): - m = Module(load_shader("2D", dmask=0x9)) - for rid, _, _ in m.fetches(): - uses = [args for _, op, args in m.order if op == "OpBitcast" and rid in args] - self.assertEqual(len(uses), 1) - bits = next(r for r, op, args in m.order if op == "OpBitcast" and args[1] == rid) - comps = sorted(int(args[2]) for _, op, args in m.order if op == "OpCompositeExtract" and args[1] == bits) - self.assertEqual(comps, [0, 3], "dmask 0x9: R into v0, A into v1") - - def test_d16_odd_dmask_preserves_trailing_vgpr_high_half(self): - # Odd component counts (1 or 3) must keep the trailing destination VGPR's high 16 bits via write_lo16 - # in all three typed branches (sint, uint, float), while even counts overwrite the whole register. - cases = ((0x1, 0, True), (0x7, 1, True), (0x3, 0, False), (0xF, 1, False)) - for dim, (dmask, dest_reg, expect_preserve) in itertools.product(("2D", "CUBE"), cases): - with self.subTest(dim=dim, dmask=hex(dmask)): - reg = "v0" if dest_reg == 0 else "v[0:1]" - m = Module(translate([ - "v_mov_b32 v0, 0x5a5a0000", - "v_mov_b32 v1, 0x5a5a0000", - "v_mov_b32 v4, 1", - "v_mov_b32 v5, 2", - f"image_load {reg}, {DIMS[dim][0]}, s[0:7] dmask:0x{dmask:x} dim:SQ_RSRC_IMG_{dim} unorm d16", - "s_waitcnt vmcnt(0)", - ])) - # write_lo16 emits: OpBitwiseAnd %uint %uint_0xFFFF0000. - hi_masks = 0 - for _, op, args in m.order: - if op != "OpBitwiseAnd": - continue - rhs = m.defs.get(args[2]) - if not rhs or rhs[0] != "OpConstant" or int(rhs[1][1], 0) != 0xFFFF0000: - continue - copy = m.defs.get(args[1]) - if not copy or copy[0] != "OpCopyObject": - continue - load = m.defs.get(copy[1][1]) - if not load or load[0] != "OpLoad": - continue - ptr = m.defs.get(load[1][1]) - if ptr and ptr[0] == "OpAccessChain" and ptr[1][1] == "%vgpr" and m.value(ptr[1][2], 0, 0) == dest_reg: - hi_masks += 1 - self.assertEqual(hi_masks, 3 if expect_preserve else 0) - - def test_tfe_status_vgpr_is_written_zero(self): - # MIMG tfe: the fetch status follows the data at vdata[data_count], for every image read and query. A - # Vulkan image is always resident, so the translator stores 0 there (SHADER-1266). llvm-mc 18.1.8 sizes - # vdata from dmask, d16 and tfe (it rejects `image_load v[16:17] ... dmask:0x1 lwe`), so lwe alone adds no - # register: the VGPR after the data is left untouched, as it is without either modifier. - t, s = "s[0:7]", "s[8:11]" - cases = ( # instruction without its data operand, data VGPR count - (f"image_load {{}}, v[4:5], {t} dmask:0x1 dim:SQ_RSRC_IMG_2D unorm", 1), - (f"image_load {{}}, v[4:5], {t} dmask:0x5 dim:SQ_RSRC_IMG_2D unorm", 2), - (f"image_load {{}}, v[4:5], {t} dmask:0x7 dim:SQ_RSRC_IMG_2D unorm d16", 2), - (f"image_load {{}}, v[4:5], {t} dmask:0x1 dim:SQ_RSRC_IMG_2D unorm glc", 1), - (f"image_load_mip {{}}, v[4:6], {t} dmask:0x1 dim:SQ_RSRC_IMG_2D unorm", 1), - (f"image_sample {{}}, v[4:5], {t}, {s} dmask:0xf dim:SQ_RSRC_IMG_2D", 4), - (f"image_sample_lz {{}}, v[4:5], {t}, {s} dmask:0x3 dim:SQ_RSRC_IMG_2D d16", 1), - (f"image_sample_c_lz {{}}, v[4:6], {t}, {s} dmask:0x1 dim:SQ_RSRC_IMG_2D", 1), - (f"image_gather4_lz {{}}, v[4:5], {t}, {s} dmask:0x1 dim:SQ_RSRC_IMG_2D", 4), - (f"image_get_resinfo {{}}, v4, {t} dmask:0x3 dim:SQ_RSRC_IMG_2D", 2), - (f"image_get_lod {{}}, v[4:5], {t}, {s} dmask:0x3 dim:SQ_RSRC_IMG_2D", 2), - ) - for asm, count in cases: - for mods, has_status in (("tfe", True), ("tfe lwe", True), ("lwe", False), ("", False)): - with self.subTest(asm=asm, mods=mods): - last = 16 + count - 1 + has_status - data = "v16" if last == 16 else f"v[16:{last}]" - m = Module(translate(["v_mov_b32 v4, 1", "v_mov_b32 v5, 2", "v_mov_b32 v6, 0", - f"{asm.format(data)} {mods}".rstrip(), "s_waitcnt vmcnt(0)"])) - stores = vgpr_stores(m) - for r in range(16, 16 + count): - self.assertIn(r, stores, f"the data VGPR v{r} is not written") - if has_status: - self.assertIn(16 + count, stores, "the fetch status VGPR is not written") - self.assertEqual(m.value(stores[16 + count], 0, 0), 0, "the fetch status must be 0") - else: - self.assertNotIn(16 + count, stores, "the VGPR after the data must be left untouched") - - -class LodQueryCoordinates(unittest.TestCase): - def test_a16_queries_with_status_are_unsupported(self) -> None: - for status, dest in (("tfe", "v[6:7]"), ("lwe", "v6")): - with self.subTest(status=status), self.assertRaises(rdna2spirv.Unsupported): - translate([f"image_get_lod {dest}, v10, s[8:15], s[16:19] " - f"dmask:0x1 dim:SQ_RSRC_IMG_2D a16 {status}"]) - - def test_a16_queries_unpack_uv_and_keep_f32_results(self) -> None: - fixture = Path(ROOT) / "tests/semantic/fixtures/get_lod_a16.asm" - lines = [line for line in fixture.read_text(encoding="utf-8").splitlines() - if line and not line.startswith(";")] - module = Module(translate(lines)) - queries = [(rid, args) for rid, op, args in module.order if op == "OpImageQueryLod"] - self.assertEqual(len(queries), 2) - for (rid, (ty, image, coord)), (register, image_type, components) in zip( - queries, [(10, "%simg2d", [0, 1]), (12, "%simg2da", [1])]): - self.assertEqual(ty, "%v2float") - self.assertEqual(module.defs[image][1][0], image_type) - op, unpack = module.defs[coord] - self.assertEqual((op, unpack[:3]), ("OpExtInst", ["%v2float", "%glsl", "UnpackHalf2x16"])) - op, load = module.defs[unpack[3]] - self.assertEqual(op, "OpLoad") - op, ptr = module.defs[load[1]] - self.assertEqual((op, ptr[1], module.value(ptr[2], 0, 0)), ("OpAccessChain", "%vgpr", register)) - self.assertEqual([int(args[2]) for _, op, args in module.order - if op == "OpCompositeExtract" and args[:2] == ["%float", rid]], components) - - -class TypedGatherShaders(unittest.TestCase): - def test_a16_offset_gathers_preserve_offset_and_unpack_uv_lod(self) -> None: - fixture = Path(ROOT) / "tests/semantic/fixtures/gather_offset_a16.asm" - lines = [line for line in fixture.read_text(encoding="ascii").splitlines() - if line and not line.startswith(";")] - end = lines.index("s_waitcnt vmcnt(0)") - for explicit in (True, False): - with self.subTest(explicit_lod=explicit): - body = lines[:end] - if not explicit: - body[-1] = body[-1].replace("gather4_l_o", "gather4_lz_o").replace("v[4:6]", "v[4:5]") - m = Module(translate(body)) - - def source_register(value: str) -> int: - op, load = m.defs[value] - self.assertEqual(op, "OpLoad") - op, ptr = m.defs[load[1]] - self.assertEqual((op, ptr[1]), ("OpAccessChain", "%vgpr")) - return m.value(ptr[2], 0, 0) - - fields = [(source_register(a[1]), m.value(a[2], 0, 0), m.value(a[3], 0, 0)) - for _, op, a in m.order if op == "OpBitFieldSExtract"] - self.assertEqual(fields, [(4, 0, 6), (4, 8, 6)]) - - def source_half(value: str) -> tuple[int, int]: - while m.defs[value][0] == "OpBitcast": - value = m.defs[value][1][1] - extract_op, (_, pair, half) = m.defs[value] - self.assertEqual(extract_op, "OpCompositeExtract") - op, unpack = m.defs[pair] - self.assertEqual((op, unpack[2]), ("OpExtInst", "UnpackHalf2x16")) - return source_register(unpack[3]), int(half) - - if explicit: - uv, = [a[1] for _, op, a in m.order if op == "OpFMul" and a[0] == "%v2float"] - lod, = [a[3] for _, op, a in m.order if op == "OpExtInst" and a[2] == "FClamp"] - self.assertEqual(source_half(lod), (6, 0)) - else: - uv, = {a[2] for _, op, a in m.order if op == "OpImageGather"} - op, coord = m.defs[uv] - self.assertEqual(op, "OpCompositeConstruct") - self.assertEqual([source_half(c) for c in coord[1:]], [(5, 0), (5, 1)]) - - def test_a16_offset_gathers_with_status_stay_unsupported(self) -> None: - for op in ("image_gather4_l_o", "image_gather4_lz_o"): - addr = "v[4:6]" if op == "image_gather4_l_o" else "v[4:5]" - for status in ("tfe", "lwe"): - with self.subTest(op=op, status=status), self.assertRaises(rdna2spirv.Unsupported): - dest = "v[10:14]" if status == "tfe" else "v[10:13]" - translate([f"{op} {dest}, {addr}, s[0:7], s[8:11] dmask:0x2 dim:SQ_RSRC_IMG_2D a16 {status}"]) - - def test_2d_lod_samples_use_matching_typed_views(self): - instructions = (("image_sample_lz", "v[4:5]"), ("image_sample_l", "v[4:6]")) - destinations = (("v[0:3]", ""), ("v[0:1]", " d16")) - for (name, addr), (dst, modifier) in itertools.product(instructions, destinations): - with self.subTest(name=name, modifier=modifier): - m = Module(translate([f"{name} {dst}, {addr}, s[0:7], s[8:11] " - f"dmask:0xf dim:SQ_RSRC_IMG_2D{modifier}"])) - samples = [args for _, op, args in m.order if op == "OpImageSampleExplicitLod"] - self.assertEqual({args[0] for args in samples}, {"%v4float", "%v4uint_st", "%v4int_st"}) - # T# word 1 for R32_UINT, R32_SINT and R32_FLOAT, respectively. - for fmt, expected in ((20, "uint"), (21, "sint"), (22, "float")): - self.assertEqual(m.branch(fmt << 20, 5), expected) - self.assertEqual(m.branch(fmt << 20, 0), "float") - for ty, sampled, _, mask, lod in samples: - self.assertEqual(mask, "Lod") - if name == "image_sample_lz": - self.assertEqual(lod, "%f0") - else: - op, cast = m.defs[lod] - self.assertEqual(op, "OpBitcast") - op, load = m.defs[cast[1]] - self.assertEqual(op, "OpLoad") - op, ptr = m.defs[load[1]] - self.assertEqual((op, ptr[1], m.value(ptr[2], 0, 0)), ("OpAccessChain", "%vgpr", 6)) - op, pair = m.defs[sampled] - self.assertEqual(op, "OpSampledImage") - _, image = m.defs[pair[1]] - _, chain = m.defs[image[1]] - self.assertEqual(m.binding[chain[1]], 0) - self.assertEqual(m.defs[ty][1][0], m.defs[image[0]][1][0]) - - def test_explicit_lod_gather_fetches_four_taps_from_each_typed_view(self): - for suffix, coords in (("", "v[4:6]"), ("_o", "v[4:7]")): - with self.subTest(suffix=suffix): - instruction = f"image_gather4_l{suffix} v[0:3], {coords}, s[0:7], s[8:11] dmask:0x2 dim:SQ_RSRC_IMG_2D" - m = Module(translate([instruction, "s_waitcnt vmcnt(0)"])) - fetches = m.fetches() - footprints = [] - for scalar in ("%float", "%uint", "%int"): - group = [(rid, var) for rid, var, image in fetches if image[0] == scalar] - self.assertEqual(len(group), 4) - footprints.append([m.defs[rid][1][2:] for rid, _ in group]) - for rid, var in group: - self.assertEqual(m.binding[var], 0) - self.assertEqual(m.defs[rid][1][-2], "Lod") - taps = [a for _, op, a in m.order if op == "OpCompositeExtract" and a[1] == rid] - self.assertEqual([a[2] for a in taps], ["1"]) - self.assertEqual(footprints[0], footprints[1]) - self.assertEqual(footprints[0], footprints[2]) - - def test_implicit_2d_sample_takes_gradients_before_typed_dispatch(self): - m = Module(translate(["image_sample v[0:1], v[4:5], s[0:7], s[8:11] " - "dmask:0xf dim:SQ_RSRC_IMG_2D d16"])) - samples = [args for _, op, args in m.order if op == "OpImageSampleExplicitLod"] - self.assertEqual({args[0] for args in samples}, {"%v4float", "%v4uint_st", "%v4int_st"}) - dispatch = re.search(r"OpBranchConditional %\w+ %\w+_s %\w+_rest", m.text) - self.assertIsNotNone(dispatch) - for _, _, coords, mode, dx, dy in samples: - self.assertEqual(mode, "Grad") - self.assertEqual(m.defs[dx], ("OpDPdx", ["%v2float", coords])) - self.assertEqual(m.defs[dy], ("OpDPdy", ["%v2float", coords])) - # The gradients must exist before the image-class selection can diverge. - self.assertLess(m.text.index(f"{dy} = OpDPdy"), dispatch.start()) - - def test_2d_gather_picks_the_sampled_type_and_selected_component(self): - for dst, modifier in (("v[0:3]", ""), ("v[0:1]", " d16")): - with self.subTest(modifier=modifier): - m = Module(translate([f"image_gather4_lz {dst}, v[4:5], s[0:7], s[8:11] " - f"dmask:0x2 dim:SQ_RSRC_IMG_2D{modifier}", "s_waitcnt vmcnt(0)"])) - types = set() - for rid, op, args in m.order: - if op != "OpImageGather": - continue - types.add(args[0]) - self.assertEqual(m.value(args[3], 0, 0), 1) # green - sampled_op, sampled = m.defs[args[1]] - self.assertEqual(sampled_op, "OpSampledImage") - image_load, image = m.defs[sampled[1]] - self.assertEqual(image_load, "OpLoad") - _, chain = m.defs[image[1]] - self.assertEqual(m.binding[chain[1]], 0) - if modifier and args[0] != "%v4float": - def uses(opcode, operand): - return [(r, a) for r, op, a in m.order if op == opcode and operand in a[1:]] - ((raw, _),) = uses("OpBitcast", rid) - taps = {int(a[2]): r for r, a in uses("OpCompositeExtract", raw)} - self.assertEqual(set(taps), {0, 1, 2, 3}) - halves = [] - for tap in range(4): - if args[0] == "%v4int_st": - ((signed, _),) = uses("OpBitcast", taps[tap]) - ((sat, clamp),) = uses("OpExtInst", signed) - self.assertEqual(clamp[2], "SClamp") - ((bits, _),) = uses("OpBitcast", sat) - ((half, mask),) = uses("OpBitwiseAnd", bits) - self.assertEqual(m.value(mask[2], 0, 0), 0xffff) - else: - ((half, clamp),) = uses("OpExtInst", taps[tap]) - self.assertEqual(clamp[2], "UMin") - self.assertEqual(m.value(clamp[4], 0, 0), 0xffff) - halves.append(half) - for tap in (0, 2): - lo = halves[tap] - ((hi, shift),) = uses("OpShiftLeftLogical", halves[tap + 1]) - self.assertEqual(m.value(shift[2], 0, 0), 16) - self.assertTrue(any(hi in a for _, a in uses("OpBitwiseOr", lo))) - - self.assertEqual(types, {"%v4uint_st", "%v4int_st", "%v4float"}) - - -class StoreAndLoad(unittest.TestCase): - def test_a_shader_that_also_stores_needs_write_without_format_and_both_indexing_capabilities(self): - m = Module(translate(["v_mov_b32 v4, 1", "v_mov_b32 v5, 2", - "image_store v[0:3], v[4:5], s[0:7] dmask:0xf dim:SQ_RSRC_IMG_2D unorm", - "image_load v[0:3], v[4:5], s[8:15] dmask:0xf dim:SQ_RSRC_IMG_2D unorm", - "s_waitcnt vmcnt(0)"])) - self.assertIn("StorageImageWriteWithoutFormat", m.caps) - self.assertIn("StorageImageArrayDynamicIndexing", m.caps) - self.assertIn("SampledImageArrayDynamicIndexing", m.caps) - self.assertNotIn("StorageImageReadWithoutFormat", m.caps) - self.assertNotIn("OpImageRead", m.text) - self.assertEqual(set(m.binding.values()), {0, 1, 2, 8, 9, 10}) - - -@unittest.skipUnless(shutil.which("spirv-as") and shutil.which("spirv-val"), "needs spirv-as and spirv-val") -class Validation(unittest.TestCase): - def test_spirv_val_accepts_every_dimension(self): - with tempfile.TemporaryDirectory() as tmp: - for dim in DIMS: - with self.subTest(dim=dim): - sa, sv = os.path.join(tmp, f"{dim}.spvasm"), os.path.join(tmp, f"{dim}.spv") - with open(sa, "w", encoding="utf-8") as f: - f.write(load_shader(dim)) - result = rdna2spirv.assemble_spirv(sa, sv) - self.assertEqual(result.returncode, 0, result.stderr + result.stdout) - - def test_spirv_val_accepts_d16_odd_dmask(self): - with tempfile.TemporaryDirectory() as tmp: - for dmask, reg in ((0x1, "v0"), (0x7, "v[0:1]")): - with self.subTest(dmask=hex(dmask)): - sa = os.path.join(tmp, f"d16_{dmask:x}.spvasm") - sv = os.path.join(tmp, f"d16_{dmask:x}.spv") - with open(sa, "w", encoding="utf-8") as f: - f.write(translate([ - "v_mov_b32 v0, 0x5a5a0000", - "v_mov_b32 v1, 0x5a5a0000", - "v_mov_b32 v4, 1", - "v_mov_b32 v5, 2", - f"image_load {reg}, v[4:5], s[0:7] dmask:0x{dmask:x} dim:SQ_RSRC_IMG_2D unorm d16", - "s_waitcnt vmcnt(0)", - ])) - result = rdna2spirv.assemble_spirv(sa, sv) - self.assertEqual(result.returncode, 0, result.stderr + result.stdout) - - -class VolumeGradientSamples(unittest.TestCase): - def test_volume_gradient_status_is_unsupported(self) -> None: - for dest, status in (("v[2:3]", "tfe"), ("v3", "lwe")): - with self.subTest(status=status), self.assertRaises(rdna2spirv.Unsupported): - translate([f"image_sample_d {dest}, v[10:18], s[0:7], s[8:11] " - f"dmask:0x1 dim:SQ_RSRC_IMG_3D {status}"]) - - def test_volume_address_operands(self) -> None: - fixture = Path(ROOT) / "tests/semantic/fixtures/volume_gradients.asm" - for line in fixture.read_text(encoding="utf-8").splitlines(): - if not line.startswith("image_sample_"): - continue - with self.subTest(line=line): - module = Module(translate([line])) - sample, = [args for _, op, args in module.order if op == "OpImageSampleExplicitLod"] - _, _, coords, mask, dx, dy, *clamp = sample - self.assertEqual(mask, "Grad|MinLod" if "_cl " in line else "Grad") - self.assertEqual(len(clamp), int("_cl " in line)) - - def source(value: str) -> tuple[int, int | None]: - # Through the bitcasts between a VGPR word and a float (a round trip is the original id). - op, args = module.defs[value] - while op == "OpBitcast": - op, args = module.defs[args[1]] - half = None - if op == "OpCompositeExtract": # f16 coord converted to f32 - _, unpacked, selector = args - unpack, (_, _, name, packed) = module.defs[unpacked] - self.assertEqual((unpack, name), ("OpExtInst", "UnpackHalf2x16")) - half = int(selector) - op, args = module.defs[packed] - self.assertEqual(op, "OpLoad") - access, (_, bank, index) = module.defs[args[1]] - self.assertEqual((access, bank), ("OpAccessChain", "%vgpr")) - return module.value(index, 0, 0), half - - for vector, registers in ((dx, (10, 11, 12)), (dy, (13, 14, 15))): - op, (ty, *components) = module.defs[vector] - self.assertEqual((op, ty), ("OpCompositeConstruct", "%v3float")) - self.assertEqual([source(c) for c in components], [(reg, None) for reg in registers]) - op, (ty, *xyz) = module.defs[coords] - self.assertEqual((op, ty), ("OpCompositeConstruct", "%v3float")) - packed = " a16" in line - self.assertEqual([source(c) for c in xyz], [(16, 0), (16, 1), (17, 0)] if packed - else [(16, None), (17, None), (18, None)]) - if clamp: - self.assertEqual(source(clamp[0]), (17, 1) if packed else (19, None)) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/test_image_query_probe.py b/tests/test_image_query_probe.py deleted file mode 100644 index c0edbd889..000000000 --- a/tests/test_image_query_probe.py +++ /dev/null @@ -1,247 +0,0 @@ -"""tools/image_query_probe.py: the resinfo and get_lod rules against the values measured on gfx1036, the descriptor -bits, the kernels, and the comparison and its exit codes (through a fake oracle that plays the GPU with the rules). -The last class runs on the hardware when the oracle tools are present and the GPU is GFX10, and is skipped otherwise. -Standard library only.""" -import io -import json -import math -import os -import sys -import tempfile -import unittest -from contextlib import redirect_stderr, redirect_stdout -from pathlib import Path -from unittest import mock - -TOOLS = Path(__file__).resolve().parents[1] / "tools" -sys.path.insert(0, str(TOOLS)) -import image_query_probe as pr # noqa: E402 -from hw_oracle import runner # noqa: E402 - - -class Rules(unittest.TestCase): - def test_self_test(self): - with redirect_stdout(io.StringIO()): - self.assertEqual(pr.self_test(), 0) - - def test_a_2d_depth_word_is_zero_whatever_word4_holds(self): - for depth in (0, 5, 0x3F, 0x1FFF): - self.assertEqual(pr.resinfo_model(16, 4, pr.TYPE_2D, depth, 0, 4, 0)[2], 0) - - def test_the_layer_count_is_minified_from_the_base_level(self): - got = [pr.resinfo_model(256, 256, pr.TYPE_2D_ARRAY, 99, base, 8, level)[2] - for base, level in ((0, 0), (0, 1), (0, 3), (1, 0), (1, 5))] - self.assertEqual(got, [100, 50, 12, 50, 1]) - - def test_past_the_last_level_the_size_is_zero_and_the_level_count_stays(self): - self.assertEqual(pr.resinfo_model(16, 4, pr.TYPE_2D, 0, 1, 4, 4), [0, 0, 0, 4]) - self.assertEqual(pr.resinfo_model(16, 4, pr.TYPE_2D_ARRAY, 5, 0, 2, 9), [0, 0, 0, 3]) - - def test_clamped_lod_per_mip_filter(self): - # computed LOD 2.75 + bias 0, MIN_LOD 0.5, MAX_LOD 2.25, five levels - self.assertEqual(pr.lod_model(2.75, pr.MIP_NONE, 0.5, 2.25, 0, 5), (0.0, 2.75)) - self.assertEqual(pr.lod_model(2.75, pr.MIP_POINT, 0.5, 2.25, 0, 5), (2.0, 2.75)) - self.assertEqual(pr.lod_model(2.75, pr.MIP_LINEAR, 0.5, 2.25, 0, 5), (2.25, 2.75)) - - def test_point_rounds_ties_up_and_min_lod_wins_over_max_lod(self): - self.assertEqual(pr.lod_model(0.5, pr.MIP_POINT, 0, 15, 0, 5)[0], 1) - self.assertEqual(pr.lod_model(7.0, pr.MIP_LINEAR, 3, 2, 0, 5)[0], 3) - self.assertEqual(pr.lod_model(0.0, pr.MIP_LINEAR, 5.5, 15, 0, 5)[0], 4) # capped by the level count - - -class Descriptors(unittest.TestCase): - def test_tsharp_type_levels_and_depth(self): - t = pr.tsharp_words("gfx1036", 16, 4, pr.TYPE_2D_ARRAY, depth_field=5, base=1, last=4) - self.assertEqual(t[3] >> 28, pr.TYPE_2D_ARRAY) - self.assertEqual((t[3] >> 12) & 0xF, 1) - self.assertEqual((t[3] >> 16) & 0xF, 4) - self.assertEqual(t[4] & 0x1FFF, 5) - self.assertEqual(t[2] >> 31, 1) # GFX10 RESOURCE_LEVEL - - def test_ssharp_fields(self): - s = pr.ssharp_words(pr.MIP_LINEAR, 0.5, 2.25, -0.5) - self.assertEqual(s[1] & 0xFFF, 128) - self.assertEqual(s[1] >> 12 & 0xFFF, 576) - self.assertEqual(s[2] & 0x3FFF, 0x3FFF & -128) - self.assertEqual(s[2] >> 26 & 3, pr.MIP_LINEAR) - - def test_kernels_use_the_instruction_and_dim(self): - k = pr.resinfo_kernel(pr.tsharp_words("gfx1036", 16, 4, pr.TYPE_2D_ARRAY, 5), 2, pr.TYPE_2D_ARRAY, 64) - self.assertIn("image_get_resinfo v[8:11], v2, s[8:15] dmask:0xf dim:SQ_RSRC_IMG_2D_ARRAY", k.lines) - self.assertIn("v_mov_b32 v2, 2", k.lines) - self.assertEqual((k.wave, k.threads, k.words), (64, 1, 4)) - k = pr.lod_kernel(pr.tsharp_words("gfx1036", 16, 16), pr.ssharp_words(pr.MIP_POINT, 0, 15), 0.25, 0.25, 32) - self.assertIn("image_get_lod v[8:9], v[2:3], s[8:15], s[16:19] dmask:0x3 dim:SQ_RSRC_IMG_2D", k.lines) - self.assertEqual((k.threads, k.words), (4, 16)) - - def test_every_lod_case_is_exact_in_binary(self): - # the probe compares raw LODs exactly, so each step must be a power of two times a quarter-step LOD - for name, w, h, last, du, dv, samp, lod in pr.lod_cases(): - self.assertEqual(lod * 4, int(lod * 4), name) - - -class FakeOracle: - """Plays the GPU with the probe's own rules, optionally wrong in one place.""" - arch = "gfx1036" - - def __init__(self, depth_2d=0): - self.depth_2d = depth_2d - - def run(self, kernels, words=4): - out = [] - for k in kernels: - text = "\n".join(k.lines) - sgprs = [int(ln.split(", ")[1], 16) for ln in k.lines if ln.startswith("s_mov_b32 s")] - t, s = sgprs[:8], sgprs[8:12] - typ, base, last = t[3] >> 28, (t[3] >> 12) & 0xF, (t[3] >> 16) & 0xF - width = (t[1] >> 30 | (t[2] & 0xFFF) << 2) + 1 - height = (t[2] >> 14 & 0xFFFF) + 1 - if "image_get_resinfo" in text: - level = int(next(ln for ln in k.lines if ln.startswith("v_mov_b32 v2,")).split(", ")[1]) - r = pr.resinfo_model(width, height, typ, t[4] & 0x1FFF, base, last, level) - if typ == pr.TYPE_2D and r[0]: - r[2] = self.depth_2d - out.append(r) - else: - du = pr.u2f(int(next(ln for ln in k.lines if ln.startswith("v_mul_f32 v2")).split()[2][:-1], 16)) - dv = pr.u2f(int(next(ln for ln in k.lines if ln.startswith("v_mul_f32 v3")).split()[2][:-1], 16)) - lod = round(math.log2(max(du * width, dv * height)) * 256) / 256 # the LOD has 8 fraction bits - bias = ((s[2] & 0x3FFF) ^ 0x2000) - 0x2000 - c, raw = pr.lod_model(lod, s[2] >> 26 & 3, (s[1] & 0xFFF) / 256, (s[1] >> 12 & 0xFFF) / 256, - bias / 256, last - base + 1) - out.append([pr.f2u(c), pr.f2u(raw), 0, 0] * 4) - return out - - def close(self): - pass - - -class Comparison(unittest.TestCase): - def test_rules_played_back_match(self): - with redirect_stdout(io.StringIO()): - bad, report = pr.run(FakeOracle(), [32]) - self.assertEqual(bad, 0) - self.assertEqual(len(report["resinfo"]), len(pr.resinfo_cases())) - - def test_a_gpu_that_writes_1_for_the_2d_depth_is_caught(self): - with redirect_stdout(io.StringIO()) as out: - bad, _ = pr.run(FakeOracle(depth_2d=1), [32]) - self.assertGreater(bad, 0) - self.assertIn("MISMATCH resinfo", out.getvalue()) - - def test_main_exit_codes(self): - with redirect_stdout(io.StringIO()): - with mock.patch.object(runner, "open_oracle", return_value=FakeOracle()): - self.assertEqual(pr.main(["--waves", "32"]), 0) - with mock.patch.object(runner, "open_oracle", return_value=FakeOracle(depth_2d=1)): - self.assertEqual(pr.main(["--waves", "32"]), 1) - with mock.patch.object(runner, "open_oracle", side_effect=runner.Unavailable("no GPU")): - self.assertEqual(pr.main([]), 77) - other = FakeOracle() - other.arch = "gfx1150" - with mock.patch.object(runner, "open_oracle", return_value=other): - self.assertEqual(pr.main([]), 77) - - def test_json_output_creates_its_parent_and_reports_write_errors(self): - with tempfile.TemporaryDirectory() as tmp, \ - mock.patch.object(runner, "open_oracle", return_value=FakeOracle()): - report = Path(tmp) / "new" / "report.json" - with redirect_stdout(io.StringIO()): - self.assertEqual(pr.main(["--waves", "32", "--json", str(report)]), 0) - self.assertTrue(report.is_file()) - - def test_a_report_that_cannot_be_written_still_shows_the_result_and_exits_2(self): - # Exit 1 means a result off the rules; an unwritable --json must not look like one, nor hide the summary. - for oracle, summary in ((FakeOracle(), r"follow the rules, 0 do not"), - (FakeOracle(depth_2d=1), r"follow the rules, [1-9]\d* do not")): - with self.subTest(summary=summary), tempfile.TemporaryDirectory() as tmp, \ - mock.patch.object(runner, "open_oracle", return_value=oracle): - report = Path(tmp) / "directory" - report.mkdir() - out, error = io.StringIO(), io.StringIO() - with redirect_stdout(out), redirect_stderr(error): - self.assertEqual(pr.main(["--waves", "32", "--json", str(report)]), 2) - self.assertRegex(out.getvalue(), summary) - self.assertIn(str(report), error.getvalue()) - self.assertIn("cannot write", error.getvalue()) - - def test_json_write_uses_lf_line_endings_and_cleans_temp(self): - with tempfile.TemporaryDirectory() as tmp, \ - mock.patch.object(runner, "open_oracle", return_value=FakeOracle()): - report = Path(tmp) / "report.json" - with redirect_stdout(io.StringIO()): - self.assertEqual(pr.main(["--waves", "32", "--json", str(report)]), 0) - raw = report.read_bytes() - self.assertIn(b"\n", raw) - self.assertNotIn(b"\r", raw) - doc = json.loads(raw.decode("utf-8")) - self.assertEqual(len(doc["resinfo"]), len(pr.resinfo_cases())) - self.assertEqual(len(doc["lod"]), len(pr.lod_cases())) - self.assertEqual([p.name for p in Path(tmp).glob(".image_query_probe-*")], []) - - def test_json_write_failure_preserves_previous_report_and_cleans_temp(self): - previous = '{"previous": true}' - real_named_temp = tempfile.NamedTemporaryFile - - def failing_temp(*args, **kwargs): - handle = real_named_temp(*args, **kwargs) - - def fail_write(data): - handle.file.write(data[:8]) - raise OSError(28, "No space left on device") - - handle.write = fail_write - return handle - - for label, patch in ( - ("write", mock.patch.object(pr.tempfile, "NamedTemporaryFile", side_effect=failing_temp)), - ("replace", mock.patch.object(pr, "replace_retry", side_effect=PermissionError(13, "Permission denied"))), - ): - with self.subTest(label=label), tempfile.TemporaryDirectory() as tmp, \ - mock.patch.object(runner, "open_oracle", return_value=FakeOracle()), patch: - report = Path(tmp) / "keep.json" - report.write_text(previous, encoding="utf-8", newline="\n") - out, error = io.StringIO(), io.StringIO() - with redirect_stdout(out), redirect_stderr(error): - self.assertEqual(pr.main(["--waves", "32", "--json", str(report)]), 2) - self.assertRegex(out.getvalue(), r"follow the rules, 0 do not") - self.assertIn(str(report), error.getvalue()) - self.assertIn("cannot write", error.getvalue()) - self.assertEqual(report.read_text(encoding="utf-8"), previous) - self.assertEqual([p.name for p in Path(tmp).glob(".image_query_probe-*")], []) - - def test_readonly_existing_report_is_preserved_without_temp_files(self): - if os.name != "nt" and os.geteuid() == 0: - self.skipTest("root bypasses read-only file mode") - previous = '{"readonly": true}' - with tempfile.TemporaryDirectory() as tmp: - report = Path(tmp) / "readonly.json" - report.write_text(previous, encoding="utf-8", newline="\n") - os.chmod(report, 0o444) - try: - with self.assertRaises(OSError): - pr.write_report(str(report), {"new": True}) - self.assertEqual(report.read_text(encoding="utf-8"), previous) - self.assertEqual([p.name for p in Path(tmp).glob(".image_query_probe-*")], []) - finally: - os.chmod(report, 0o600) - - -class Hardware(unittest.TestCase): - def test_on_the_gpu(self): - try: - oracle = runner.open_oracle() - except runner.Unavailable as e: - self.skipTest(f"hardware oracle unavailable: {e}") - try: - if not oracle.arch.startswith("gfx10"): - self.skipTest(f"{oracle.arch} is not GFX10") - with redirect_stdout(io.StringIO()): - bad, _ = pr.run(oracle, [32, 64]) - self.assertEqual(bad, 0) - finally: - oracle.close() - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/test_image_query_translate.py b/tests/test_image_query_translate.py deleted file mode 100644 index c314730cc..000000000 --- a/tests/test_image_query_translate.py +++ /dev/null @@ -1,325 +0,0 @@ -"""Translation and SPIR-V structure tests for image_get_resinfo and image_get_lod in tools/rdna2spirv.py. - -spirv_mini_interp.py does not yet implement OpImageQuerySizeLod, OpImageQueryLevels, or OpImageQueryLod, -so this suite characterizes current translator output (capabilities, image/sampler types, query opcodes, -dmask VGPR compaction, and negative/mutation controls) rather than pinning hardware-measured rules -(such as 2D resinfo depth=0 in docs/shader_validation.md), using the Python standard library only: - python -I tests/test_image_query_translate.py -v -""" -import gc -import os -import re -import struct -import sys -import tempfile -import unittest -import warnings - -ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) -sys.dont_write_bytecode = True -sys.path.insert(0, os.path.join(ROOT, "tools")) -import rdna2spirv # noqa: E402 - -# Minimal valid DXBC container with zero parts (no declared PS inputs). -STUB_DXBC = b"DXBC" + bytes(24) + struct.pack(" (opcode, operands_list) for SSA instructions in SPIR-V assembly.""" - defs = {} - for line in spvasm.splitlines(): - m = re.match(r"\s*(%\w+) = (Op\w+)(?: (.*))?$", line) - if m: - rest = m.group(3).split() if m.group(3) else [] - defs[m.group(1)] = (m.group(2), rest) - return defs - - -def unwrap_dst_value(defs, sid): - """Unwrap EXEC-masked OpSelect %uint emitted by Gen.dst().""" - op, args = defs[sid] - if op == "OpSelect": - return args[2] - return sid - - -def through_select(defs, vid): - """Past the OpSelects SHADER-388 puts on each size word (0 past the view's last level), to the queried value.""" - while defs[vid][0] == "OpSelect": - vid = defs[vid][1][2] # [type, condition, in-range value, 0] - return vid - - -def reaches(defs, vid, pred, seen=None): - """True when some definition feeding `vid` satisfies pred(op, args).""" - seen = set() if seen is None else seen - if vid in seen or vid not in defs: - return False - seen.add(vid) - op, args = defs[vid] - return pred(op, args) or any(reaches(defs, a, pred, seen) for a in args if a.startswith("%")) - - -class ImageGetResinfoTranslateTests(unittest.TestCase): - def test_2d_full_dmask_emits_image_query_and_all_four_channels(self): - spv = translate_lines("ps_resinfo_2d", [ - "v_mov_b32 v0, 0", - "image_get_resinfo v[4:7], v0, s[8:15] dmask:0xf dim:SQ_RSRC_IMG_2D", - "exp mrt0 v4, v5, v6, v7 done vm", - "s_endpgm", - ]) - self.assertIn("OpCapability ImageQuery", spv) - self.assertIn("OpAccessChain %_ptr_UC_img %images ", spv) - self.assertIn("OpLoad %img2d ", spv) - self.assertRegex(spv, r"%\w+ = OpImageQuerySizeLod %v2int %\w+ %\w+") - self.assertRegex(spv, r"%\w+ = OpImageQueryLevels %int %\w+") - self.assertNotIn("%images_arr", spv) - - defs = parse_defs(spv) - stores = [(idx, unwrap_dst_value(defs, sid)) for idx, sid in vgpr_stores(spv) if idx in (4, 5, 6, 7)] - self.assertEqual([idx for idx, _ in stores], [4, 5, 6, 7]) - # v4 <- width (extract 0 of SizeLod), v5 <- height (extract 1 of SizeLod), - # v6 <- constant 1 (current translator output; note: measured RDNA2 hardware rule is 0 per - # docs/shader_validation.md and tests/test_image_query_probe.py — this test characterizes - # current translator output and does not pin the hardware depth rule), - # v7 <- levels (OpImageQueryLevels). - src_ops = [defs[through_select(defs, defs[sid][1][1])][0] for _, sid in stores] - self.assertEqual(src_ops[0], "OpCompositeExtract") - self.assertEqual(src_ops[1], "OpCompositeExtract") - self.assertEqual(src_ops[2], "OpBitcast") # as_int(cu(1)) -> Bitcast %uint - # a 2D image's depth word is 0 on RDNA2 (SHADER-388, measured with tools/image_query_probe.py) - self.assertEqual(defs[defs[stores[2][1]][1][1]][1][1], "%c0") - self.assertEqual(src_ops[3], "OpImageQueryLevels") - - def test_2d_array_uses_v3int_and_images_arr(self): - spv = translate_lines("ps_resinfo_2da", [ - "v_mov_b32 v0, 1", - "image_get_resinfo v[4:7], v0, s[8:15] dmask:0xf dim:SQ_RSRC_IMG_2D_ARRAY", - "exp mrt0 v4, v5, v6, v7 done vm", - "s_endpgm", - ]) - self.assertIn("OpCapability ImageQuery", spv) - self.assertIn("OpAccessChain %_ptr_UC_imga %images_arr ", spv) - self.assertIn("OpLoad %img2da ", spv) - self.assertRegex(spv, r"%\w+ = OpImageQuerySizeLod %v3int %\w+ %\w+") - self.assertRegex(spv, r"%\w+ = OpImageQueryLevels %int %\w+") - - defs = parse_defs(spv) - stores = [(idx, unwrap_dst_value(defs, sid)) for idx, sid in vgpr_stores(spv) if idx in (4, 5, 6, 7)] - self.assertEqual([idx for idx, _ in stores], [4, 5, 6, 7]) - # For 2D_ARRAY, channel 2 (v6) comes from SizeLod %v3int axis 2 (the layer count, minified since SHADER-388). - c2 = defs[stores[2][1]][1][1] - self.assertTrue(reaches(defs, c2, lambda op, a: op == "OpCompositeExtract" and a[2] == "2")) - - def test_partial_dmask_compacts_written_vgprs(self): - # dmask:0x8 (bit 3 only -> mip levels) must write ONLY v4 (v[4:4]), not v5..v7. - spv_levels_only = translate_lines("ps_resinfo_dmask8", [ - "v_mov_b32 v0, 0", - "image_get_resinfo v4, v0, s[8:15] dmask:0x8 dim:SQ_RSRC_IMG_2D", - "exp mrt0 v4, v4, v4, v4 done vm", - "s_endpgm", - ]) - defs = parse_defs(spv_levels_only) - written = [(idx, unwrap_dst_value(defs, sid)) for idx, sid in vgpr_stores(spv_levels_only) if idx >= 4] - self.assertEqual([idx for idx, _ in written], [4]) - self.assertEqual(defs[defs[written[0][1]][1][1]][0], "OpImageQueryLevels") - - # dmask:0x9 (bits 0 and 3 -> width and mip levels) must compact into v4 and v5 only. - spv_w_lv = translate_lines("ps_resinfo_dmask9", [ - "v_mov_b32 v0, 0", - "image_get_resinfo v[4:5], v0, s[8:15] dmask:0x9 dim:SQ_RSRC_IMG_2D", - "exp mrt0 v4, v5, v4, v5 done vm", - "s_endpgm", - ]) - defs_w_lv = parse_defs(spv_w_lv) - written_w_lv = [(idx, unwrap_dst_value(defs_w_lv, sid)) for idx, sid in vgpr_stores(spv_w_lv) if idx >= 4] - self.assertEqual([idx for idx, _ in written_w_lv], [4, 5]) - self.assertEqual(defs_w_lv[through_select(defs_w_lv, defs_w_lv[written_w_lv[0][1]][1][1])][0], - "OpCompositeExtract") - self.assertEqual(defs_w_lv[defs_w_lv[written_w_lv[1][1]][1][1]][0], "OpImageQueryLevels") - - def test_non_ps_stage_supports_resinfo(self): - spv = translate_lines("vs_resinfo", [ - "v_mov_b32 v0, 0", - "image_get_resinfo v[4:7], v0, s[8:15] dmask:0xf dim:SQ_RSRC_IMG_2D", - "s_endpgm", - ]) - self.assertIn("OpCapability ImageQuery", spv) - self.assertIn("OpImageQuerySizeLod %v2int", spv) - self.assertIn("OpImageQueryLevels %int", spv) - - def test_unsupported_dims_and_mods_raise(self): - for dim in ("SQ_RSRC_IMG_1D", "SQ_RSRC_IMG_3D", "SQ_RSRC_IMG_CUBE", "SQ_RSRC_IMG_1D_ARRAY"): - with self.subTest(dim=dim): - with self.assertRaises(rdna2spirv.Unsupported): - translate_lines("ps_resinfo_bad_dim", [ - "v_mov_b32 v0, 0", - f"image_get_resinfo v[4:7], v0, s[8:15] dmask:0xf dim:{dim}", - "exp mrt0 v4, v5, v6, v7 done vm", - "s_endpgm", - ]) - for mod in ("a16", "d16"): - with self.subTest(mod=mod): - with self.assertRaises(rdna2spirv.Unsupported): - translate_lines("ps_resinfo_bad_mod", [ - "v_mov_b32 v0, 0", - f"image_get_resinfo v[4:7], v0, s[8:15] dmask:0xf dim:SQ_RSRC_IMG_2D {mod}", - "exp mrt0 v4, v5, v6, v7 done vm", - "s_endpgm", - ]) - - -class ImageGetLodTranslateTests(unittest.TestCase): - def test_2d_and_2d_array_emit_image_query_lod(self): - for dim, img_ty, arr_name, ptr_ty, simg_ty in ( - ("SQ_RSRC_IMG_2D", "%img2d", "%images", "%_ptr_UC_img", "%simg2d"), - ("SQ_RSRC_IMG_2D_ARRAY", "%img2da", "%images_arr", "%_ptr_UC_imga", "%simg2da"), - ): - with self.subTest(dim=dim): - spv = translate_lines("ps_get_lod", [ - "v_mov_b32 v0, 0.25", - "v_mov_b32 v1, 0.5", - "image_get_lod v[4:5], v[0:1], s[8:15], s[16:19] dmask:0x3 dim:" + dim, - "exp mrt0 v4, v5, v4, v5 done vm", - "s_endpgm", - ]) - self.assertIn("OpCapability ImageQuery", spv) - self.assertIn(f"OpAccessChain {ptr_ty} {arr_name} ", spv) - self.assertIn(f"OpLoad {img_ty} ", spv) - self.assertIn("OpAccessChain %_ptr_UC_smp %samplers ", spv) - self.assertIn("OpLoad %smp ", spv) - self.assertIn(f"OpSampledImage {simg_ty} ", spv) - self.assertRegex(spv, r"%\w+ = OpImageQueryLod %v2float %\w+ %\w+") - - defs = parse_defs(spv) - written = [(idx, unwrap_dst_value(defs, sid)) for idx, sid in vgpr_stores(spv) if idx in (4, 5)] - self.assertEqual([idx for idx, _ in written], [4, 5]) - # Both outputs are OpBitcast %uint of OpCompositeExtract %float from OpImageQueryLod. - for comp_idx, (_, sid) in enumerate(written): - self.assertEqual(defs[sid][0], "OpBitcast") - ext_id = defs[sid][1][1] - self.assertEqual(defs[ext_id][0], "OpCompositeExtract") - self.assertEqual(defs[defs[ext_id][1][1]][0], "OpImageQueryLod") - self.assertEqual(defs[ext_id][1][2], str(comp_idx)) - - def test_dmask_selects_clamped_or_unclamped_lod(self): - # dmask:0x1 -> channel 0 (mipmap/clamped lod) written to v4 only. - spv_c0 = translate_lines("ps_get_lod_d1", [ - "v_mov_b32 v0, 0.25", - "v_mov_b32 v1, 0.5", - "image_get_lod v4, v[0:1], s[8:15], s[16:19] dmask:0x1 dim:SQ_RSRC_IMG_2D", - "exp mrt0 v4, v4, v4, v4 done vm", - "s_endpgm", - ]) - defs0 = parse_defs(spv_c0) - w0 = [(idx, unwrap_dst_value(defs0, sid)) for idx, sid in vgpr_stores(spv_c0) if idx >= 4] - self.assertEqual([idx for idx, _ in w0], [4]) - self.assertEqual(defs0[defs0[w0[0][1]][1][1]][1][2], "0") - - # dmask:0x2 -> channel 1 (relative/unclamped lod) compacted into v4 only. - spv_c1 = translate_lines("ps_get_lod_d2", [ - "v_mov_b32 v0, 0.25", - "v_mov_b32 v1, 0.5", - "image_get_lod v4, v[0:1], s[8:15], s[16:19] dmask:0x2 dim:SQ_RSRC_IMG_2D", - "exp mrt0 v4, v4, v4, v4 done vm", - "s_endpgm", - ]) - defs1 = parse_defs(spv_c1) - w1 = [(idx, unwrap_dst_value(defs1, sid)) for idx, sid in vgpr_stores(spv_c1) if idx >= 4] - self.assertEqual([idx for idx, _ in w1], [4]) - self.assertEqual(defs1[defs1[w1[0][1]][1][1]][1][2], "1") - - def test_a16_unpacks_half2x16_coordinates(self): - spv = translate_lines("ps_get_lod_a16", [ - "v_mov_b32 v0, 0x38003400", - "image_get_lod v[4:5], v0, s[8:15], s[16:19] dmask:0x3 dim:SQ_RSRC_IMG_2D a16", - "exp mrt0 v4, v5, v4, v5 done vm", - "s_endpgm", - ]) - self.assertIn("OpExtInst %v2float %glsl UnpackHalf2x16", spv) - self.assertRegex(spv, r"%\w+ = OpImageQueryLod %v2float %\w+ %\w+") - - def test_unsupported_stages_dims_and_a16_flags_raise(self): - with self.assertRaises(rdna2spirv.Unsupported): - translate_lines("vs_get_lod", [ - "v_mov_b32 v0, 0.25", - "v_mov_b32 v1, 0.5", - "image_get_lod v[4:5], v[0:1], s[8:15], s[16:19] dmask:0x3 dim:SQ_RSRC_IMG_2D", - "s_endpgm", - ]) - for dim in ("SQ_RSRC_IMG_1D", "SQ_RSRC_IMG_3D", "SQ_RSRC_IMG_CUBE", "SQ_RSRC_IMG_1D_ARRAY"): - with self.subTest(dim=dim): - with self.assertRaises(rdna2spirv.Unsupported): - translate_lines("ps_get_lod_bad_dim", [ - "v_mov_b32 v0, 0.25", - "v_mov_b32 v1, 0.5", - f"image_get_lod v[4:5], v[0:1], s[8:15], s[16:19] dmask:0x3 dim:{dim}", - "exp mrt0 v4, v5, v4, v5 done vm", - "s_endpgm", - ]) - for flag in ("tfe", "lwe"): - with self.subTest(flag=flag): - with self.assertRaises(rdna2spirv.Unsupported): - translate_lines("ps_get_lod_a16_flag", [ - "v_mov_b32 v0, 0x38003400", - f"image_get_lod v[4:5], v0, s[8:15], s[16:19] dmask:0x3 dim:SQ_RSRC_IMG_2D a16 {flag}", - "exp mrt0 v4, v5, v4, v5 done vm", - "s_endpgm", - ]) - - -class ImageQueryNegativeControlTests(unittest.TestCase): - def test_shader_without_image_query_omits_capability_and_opcodes(self): - spv = translate_lines("ps_no_query", [ - "v_mov_b32 v4, 1", - "v_mov_b32 v5, 2", - "v_mov_b32 v6, 3", - "v_mov_b32 v7, 4", - "exp mrt0 v4, v5, v6, v7 done vm", - "s_endpgm", - ]) - self.assertNotIn("OpCapability ImageQuery", spv) - self.assertNotIn("OpImageQuerySizeLod", spv) - self.assertNotIn("OpImageQueryLevels", spv) - self.assertNotIn("OpImageQueryLod", spv) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/test_imhex_patterns.py b/tests/test_imhex_patterns.py deleted file mode 100644 index 9d7d38497..000000000 --- a/tests/test_imhex_patterns.py +++ /dev/null @@ -1,256 +0,0 @@ -"""Tests for the ImHex patterns in tools/imhex. - - python -I tests/test_imhex_patterns.py - -Every byte here is built by the test: no game file, name or path is used. The RBF0 inputs are first checked with -tools/rbf0_index.py and the PSIN inputs with tools/psin_index.py and tools/psin_data.py, the repository's own -parsers (the PSIN schema reuses the invented names of tests/test_psin_index.py). When ImHex is installed, each pattern -then runs on the same bytes -through ImHex's pattern-language CLI (`imhex --pl format ... -f json`) and the decoded fields are compared with the -parser's result. ImHex is found through LEONIDA_IMHEX, then PATH, then its default Windows install folder; without it -the ImHex half is skipped and the rest still runs. -""" -import json -import os -import shutil -import struct -import subprocess -import sys -import tempfile -import unittest - -ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) -PATTERNS = os.path.join(ROOT, "tools", "imhex") -sys.path.insert(0, os.path.join(ROOT, "tools")) -sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) - -import psin_data # noqa: E402 -import psin_index # noqa: E402 -import rbf0_index # noqa: E402 -from test_psin_index import SCHEMA as PSIN_SCHEMA, joaat, make_lenm, make_lsch, make_section # noqa: E402 - - -def find_imhex(): - candidates = [os.environ.get("LEONIDA_IMHEX"), shutil.which("imhex")] - if os.name == "nt": - candidates.append(os.path.join(os.environ.get("ProgramFiles", r"C:\Program Files"), "ImHex", "imhex.exe")) - for c in candidates: - if c and os.path.isfile(c): - return c - return None - - -IMHEX = find_imhex() - - -# ---- synthetic inputs ------------------------------------------------------------------------------------------ - -def _name(name): - return struct.pack("I", first + len(sections) + 16) + b"\x12\x34\x56\x78") - return b"PSIN" + struct.pack(">I", first) + rows + data + sections - - -def pragma_magic(pattern): - """The bytes of `#pragma magic [ .. ] @ 0x00` in a pattern file.""" - with open(os.path.join(PATTERNS, pattern), encoding="utf-8") as f: - for line in f: - if line.startswith("#pragma magic"): - inside = line[line.index("[") + 1:line.index("]")] - return bytes(int(b, 16) for b in inside.split()) - return None - - -# ---- tests ----------------------------------------------------------------------------------------------------- - -class InputsAndMagic(unittest.TestCase): - """Runs everywhere: the synthetic inputs are valid RBF0 by the repository's parser, and the magics agree.""" - - def test_synthetic_streams_parse(self): - for wide in (True, False): - r = rbf0_index.parse_rbf0(rbf0_stream(wide)[:-4]) - self.assertEqual(r["status"], "ok", r["error"]) - self.assertEqual(r["layout"], "wide-64" if wide else "narrow-32") - self.assertEqual(r["elements"], 2) - self.assertEqual(r["descriptors"], 7) - - def test_synthetic_psin_parses(self): - blob = psin_container() - r = psin_index.parse(blob, schema=True) - self.assertTrue(r["complete"], r["error"]) - self.assertEqual(r["schema"]["reason"], "") - self.assertEqual(r["lsns_blocks"], len(LSNS_BLOCKS)) - blocks, exact = psin_data.block_table(blob, r["first_section"]) - self.assertTrue(exact) - self.assertEqual([(t, n) for t, _at, n in blocks], [(t, len(d)) for t, d in PSIN_BLOCKS]) - - def test_pattern_magics(self): - self.assertEqual(pragma_magic("rbf0.hexpat"), rbf0_index.MAGIC) - self.assertEqual(pragma_magic("rpf9.hexpat"), b"9FPR") # RPF9 stored little-endian (docs/rpf.md) - self.assertEqual(pragma_magic("psin.hexpat"), psin_index.MAGIC) - - -@unittest.skipUnless(IMHEX, "ImHex is not installed (set LEONIDA_IMHEX to imhex.exe)") -class PatternsInImHex(unittest.TestCase): - def setUp(self): - self.tmp = tempfile.TemporaryDirectory() - self.addCleanup(self.tmp.cleanup) - - def run_pattern(self, pattern, data): - """Returns (decoded JSON or None, combined output).""" - src = os.path.join(self.tmp.name, "input.bin") - out = os.path.join(self.tmp.name, "out.json") - if os.path.exists(out): - os.remove(out) - with open(src, "wb") as f: - f.write(data) - cmd = [IMHEX, "--pl", "format", "-i", src, "-p", os.path.join(PATTERNS, pattern), "-o", out, "-f", "json"] - includes = os.path.join(os.path.dirname(IMHEX), "includes") - if os.path.isdir(includes): - cmd += ["-I", includes] - p = subprocess.run(cmd, capture_output=True, text=True, timeout=120) - log = p.stdout + p.stderr - if not os.path.exists(out): - return None, log - with open(out, encoding="utf-8") as f: - return json.load(f), log - - def check_rbf0(self, wide): - data = rbf0_stream(wide) - ref = rbf0_index.parse_rbf0(data[:-4]) - got, log = self.run_pattern("rbf0.hexpat", data) - self.assertIsNotNone(got, log) - self.assertEqual("prologue" in got["header"], wide) - records = got["records"] - - names = [r["name"] for r in records if "name" in r] - self.assertEqual(names, ref["descriptor_names"]) - self.assertEqual(sum(1 for r in records if r["index"] < 0xFD and r["type"] == 0x00), ref["elements"]) - ints = [r["value_int"] for r in records if "value_int" in r] - self.assertEqual(ints, ref["ints"]) - floats = [] - for r in records: - floats += [r["value_float"]] if "value_float" in r else r.get("value_vec3", []) - self.assertEqual(floats, ref["floats"]) - strings = [r.get("value_string", r.get("text", "")) for r in records if "value_string" in r or "text" in r] - self.assertEqual([s.split("%00")[0] for s in strings], ref["strings"]) - self.assertEqual([r["attribute_count"] for r in records if "attribute_count" in r], [1, 0]) - # The pattern stops where the root closes, as parse_rbf0 does: the 4 trailing bytes are not records. - self.assertEqual(records[-1]["index"], 0xFF) - self.assertEqual(sum(1 for r in records if r["index"] == 0xFF), 2) - - def test_rbf0_wide(self): - self.check_rbf0(wide=True) - - def test_rbf0_narrow(self): - self.check_rbf0(wide=False) - - def test_rpf9_header_and_opaque_toc(self): - got, log = self.run_pattern("rpf9.hexpat", rpf9_archive(data_offset=0x100)) - self.assertIsNotNone(got, log) - self.assertEqual(got["header"]["magic"], "9FPR") - self.assertEqual(got["header"]["data_offset"], 0x100) - self.assertEqual((got["header"]["u32_08"], got["header"]["trailer_size"]), (0x11, 0x22)) - self.assertEqual(len(got["header_rest_and_toc"]), 0x100 - 0x10) - - def test_psin_matches_psin_index_and_psin_data(self): - blob = psin_container() - ref = psin_index.parse(blob, schema=True) - table, _exact = psin_data.block_table(blob, ref["first_section"]) - got, log = self.run_pattern("psin.hexpat", blob) - self.assertIsNotNone(got, log) - self.assertEqual(got["header"]["first_section"], ref["first_section"]) - - # Block table: rows, the "pppppppp" end, and each block's data where psin_data places it. - self.assertEqual([(r["type"], r["size"]) for r in got["rows"]], [(t, n) for t, _at, n in table]) - self.assertEqual(got["table_end"], "pppppppp") - self.assertEqual([bytes(b["data"]) for b in got["blocks"]], [blob[at:at + n] for _t, at, n in table]) - - sections = {s["tag"]: s for s in got["sections"]} - self.assertEqual([(s["tag"], s["size"]) for s in got["sections"]], - [(s["tag"], s["size"]) for s in ref["sections"]]) - schema = ref["schema"] - self.assertEqual([s["name_hash"] for s in sections["LSCH"]["structs"]], - [int(s["hash"], 16) for s in schema["structs"]]) - self.assertEqual([(m["name_hash"], m["offset"], m["type"], m["index"], m["ref_hash"]) - for m in sections["LSCH"]["members"]], - [(int(m["hash"], 16), m["offset"], m["type"], m["index"], int(m["ref"], 16)) - for s in schema["structs"] for m in s["members"]]) - self.assertEqual([e["value_count"] for e in sections["LENM"]["enums"]], - [len(e["values"]) for e in schema["enums"]]) - self.assertEqual([v["value"] for v in sections["LENM"]["values"]], - [v["value"] for e in schema["enums"] for v in e["values"]]) - lsns = next(s for s in ref["sections"] if s["tag"] == "LSNS") - self.assertEqual([(d["kind"], d["bytes"]) for d in sections["LSNS"]["descs"]], - [(int(b["kind"], 16), b["bytes"]) for b in lsns["blocks"]]) - self.assertEqual([len(b["records"]) for b in sections["LSNS"]["lsns_blocks"]], [n // 16 for _k, n in LSNS_BLOCKS]) - self.assertEqual(sections["LRSC"]["rsc_version"], ref["rsc_version"]) - self.assertEqual(sections["LRSC"]["root_block"], 1) - self.assertEqual(sections["CHKS"]["checksum_size"], ref["checksum_size"]) - - def test_psin_truncated_keeps_the_whole_sections(self): - blob = psin_container(lsns=False) - first = struct.unpack_from(">I", blob, 4)[0] - lsch_size = struct.unpack_from(">I", blob, first + 4)[0] - cut = blob[:first + lsch_size + 20] # inside LENM - self.assertFalse(psin_index.parse(cut)["complete"]) - got, log = self.run_pattern("psin.hexpat", cut) - self.assertIsNotNone(got, log) - tags = [s["tag"] for s in got["sections"]] - self.assertEqual(tags, ["LSCH", "LENM"]) - self.assertIn("structs", got["sections"][0]) - self.assertEqual(len(got["sections"][1]["truncated"]), 12) # what is left after LENM's 8-byte header - - def test_rpf9_rejects_a_data_offset_past_the_end(self): - got, log = self.run_pattern("rpf9.hexpat", rpf9_archive(data_offset=0x100, size=0x140)[:0x20]) - self.assertIsNone(got) - self.assertIn("data offset is outside the file", log) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/test_import_call_sites.py b/tests/test_import_call_sites.py deleted file mode 100644 index 82c6d4e75..000000000 --- a/tests/test_import_call_sites.py +++ /dev/null @@ -1,215 +0,0 @@ -"""Unit tests for tools/import_call_sites.py: thunks and the direct calls to them, on an image built here byte by byte. - -The image has two executable-code layouts the tool must tell apart: calls (E8) and tail jumps (E9) to the thunk of an -import, and an import nothing calls. It needs no game files and no third-party packages. - - python -I tests/test_import_call_sites.py -""" -import contextlib -import io -import json -import os -import struct -import sys -import tempfile -import unittest - -ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) -TOOLS_DIR = os.path.join(ROOT, "tools") -if TOOLS_DIR not in sys.path: - sys.path.insert(0, TOOLS_DIR) - -import import_call_sites # noqa: E402 -import pe_inspect # noqa: E402 - -IMAGE_BASE = 0x140000000 -TEXT_RVA = 0x1000 -IDATA_RVA = 0x2000 - -# .text layout (RVAs): three thunks, then the callers. -THUNK_FOO = TEXT_RVA + 0x00 -THUNK_BAR = TEXT_RVA + 0x10 -THUNK_ORD = TEXT_RVA + 0x20 -# .idata layout: descriptor table, lookup table, address table, hint/name entries, module name. -IAT_FOO = IDATA_RVA + 0x60 -IAT_BAR = IAT_FOO + 8 -IAT_ORD = IAT_FOO + 16 -OTHER_IAT_RVA = IDATA_RVA + 0xE0 - - -def rel32(from_end, target): - return struct.pack(" tuple[bytes, bytes]: - """Virtual buffer (header, schema, lists) and physical buffer (instances) of one 0x7a resource.""" - V = bytearray(0x1000) - V[0x10:0x15] = b"0DRPz" - names = list(SCHEMA) - struct.pack_into(" None: - virtual, physical = resource(rotation_first=True) - summary: dict = {} - self.assertTrue(il.measure(virtual, physical, summary)) - self.assertEqual(summary["grass"]["rotation_idx_max"], 72) - self.assertEqual(summary["grass"], self.T["grass"]) - - def test_empty_list_is_counted(self): - V = bytearray(self.V) - struct.pack_into("= 48, but < 0x20 + 48 (80), so InstMat at +0x20 is truncated - inst = b"\0" * 56 - blocks = [(il.PROP_INST, len(inst), 0x60000000)] - R = {} - il.prop_list(bytes(pl), inst, blocks, structs, bytes(pl), 0, R) - self.assertEqual(R.get("instances_truncated"), 1) - - -class ArchiveTests(unittest.TestCase): - def test_end_to_end(self): - V, P = resource() - with tempfile.TemporaryDirectory() as tmp: - path = os.path.join(tmp, "fake.rpf") - first = zlib.compress(V) - first += b"\0" * (-len(first) % 16) - with open(path, "wb") as fh: - fh.write(b"RPF9" + struct.pack("", r.stderr) - self.assertNotIn("Traceback", r.stderr) - self.assertEqual(r.stdout, "") - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/test_instance_lists_schema_gap.py b/tests/test_instance_lists_schema_gap.py deleted file mode 100644 index e3d374d58..000000000 --- a/tests/test_instance_lists_schema_gap.py +++ /dev/null @@ -1,58 +0,0 @@ -"""tools/instance_lists.py: a list block whose struct the schema doesn't describe is counted, not a crash. - - python -I tests/test_instance_lists_schema_gap.py - -Synthetic bytes only (the resource builder of tests/test_instance_lists.py). -""" -import os -import struct -import sys -import tempfile -import unittest -import zlib - -HERE = os.path.dirname(os.path.abspath(__file__)) -sys.path.insert(0, HERE) -sys.path.insert(0, os.path.join(os.path.dirname(HERE), "tools")) - -import instance_lists as il # noqa: E402 -from test_instance_lists import resource # noqa: E402 - - -def without_prop_struct(): - """The fixture with the prop-list struct renamed in the schema; its block still names PROP_LIST.""" - V, P = resource() - V = bytearray(V) - st = 0x100 + 32 * list(il.STRUCT_SIZE).index(il.PROP_LIST) - assert struct.unpack_from("field_10 == 0) int3 -FIELD_STOP = 0x1B10 -GLOBAL_PTR = IDATA_RVA + 0x810 -INIT = 0x1C00 # GLOBAL_PTR = XMemFoo() -RESET = 0x1C20 # GLOBAL_PTR = 0 -USE = 0x1D00 # if (GLOBAL_PTR == 0) int3 -USE_STOP = 0x1D0C -BOOL = 0x1E00 # ok = 0; if (XMemFoo() >= 0) ok = 1; return ok - - -def call(at, target): - return b"\xe8" + rel32(at + 5, target) - - -def rip(at, length, target): - """disp32 of a RIP-relative operand in an instruction of `length` bytes at `at` (the disp ends at length-tail).""" - return rel32(at + length, target) - - -def functions(): - """{start: (code bytes, end)}: the functions the image holds, each with its .pdata entry.""" - f = {} - a = IMPORT_CHECK - f[a] = (b"\x48\x83\xec\x28" + call(a + 4, THUNK_FOO) + b"\x85\xc0" # sub rsp; call; test eax, eax - + b"\x0f\x88" + rel32(a + 0x11, a + 0x16) # js fail - + b"\x48\x83\xc4\x28\xc3" # add rsp; ret - + b"\x48\x8d\x0d" + rip(a + 0x16, 7, GLOBAL_FLAG) # fail: lea rcx, [rip+x] - + call(a + 0x1D, THUNK_BAR) + b"\xcc") # call XMemBar; int3 - a = SLOT_CHECK - f[a] = (b"\x53\x48\x83\xec\x20" # push rbx; sub rsp, 0x20 - + b"\x48\x8b\x0d" + rip(a + 5, 7, GLOBAL_DEVICE) # mov rcx, [rip+device] - + b"\x48\x8b\x01" # mov rax, [rcx] - + b"\xff\x90\x80\x01\x00\x00" # call [rax+0x180] - + b"\x8b\xd8\x33\xc9\x85\xdb" # mov ebx, eax; xor; test - + b"\x79\x01\xcc" # jns ok; int3 - + b"\x48\x83\xc4\x20\x5b\xc3") # ok: add rsp; pop rbx; ret - a = HOT - f[a] = (b"\x48\x83\xec\x28" + call(a + 4, STATUS) + b"\x83\xf8\x02" # call STATUS; cmp eax, 2 - + b"\x0f\x85" + rel32(a + 0x12, COLD) # jne cold - + b"\x48\x83\xc4\x28\xc3") - a = COLD - f[a] = b"\xb9\x05\x00\x00\x00" + call(a + 5, THUNK_BAR) + b"\xcc" - a = HANDLER - f[a] = (b"\x48\x83\xec\x28" + b"\x80\x3d" + rip(a + 4, 7, GLOBAL_FLAG) + b"\x01" # cmp byte [flag], 1 - + b"\x75\x05" + call(a + 0xD, THUNK_BAR) + b"\xcc") # jne stop; call; stop: int3 - f[STATUS] = b"\x33\xc0\xc3" - a = CALLER - f[a] = (b"\x48\x83\xec\x28" + call(a + 4, STATUS) + b"\x84\xc0" # call STATUS; test al, al - + b"\x74\x05" + call(a + 0xD, HANDLER) # je skip; call HANDLER - + b"\x48\x83\xc4\x28\xc3") # skip: add rsp; ret - a = CHECK - f[a] = (b"\x56\x48\x83\xec\x20\x8b\xf1" # push rsi; sub rsp; mov esi, ecx - + b"\x85\xc9\x78\x08" # test ecx, ecx; js high - + b"\x8b\xc6\x48\x83\xc4\x20\x5e\xc3" # out: mov eax, esi; ...; ret - + b"\x8d\x46\x10\x83\xf8\x03\x77\xf0" # high: lea eax, [rsi+0x10]; cmp; ja out - + b"\xb9\x05\x00\x00\x00\x0f\xa3\xc1\x73\xe6" # mov ecx, 5; bt ecx, eax; jae out - + call(a + 0x25, HANDLER2) + b"\xeb\xdf") # call HANDLER2; jmp out - f[HANDLER2] = call(HANDLER2, THUNK_BAR) + b"\xcc" - a = USER - f[a] = (b"\x48\x83\xec\x28" + b"\x48\x8b\x0d" + rip(a + 4, 7, GLOBAL_DEVICE) # mov rcx, [rip+device] - + b"\x48\x8b\x01\xff\x50\x40\x8b\xc8" # mov rax, [rcx]; call [rax+0x40] - + call(a + 0x13, CHECK) # mov ecx, eax; call CHECK - + call(a + 0x18, THUNK_FOO) + b"\x8b\xc8" + call(a + 0x1F, CHECK) # call XMemFoo; mov; call - + b"\x48\x83\xc4\x28\xc3") - a = FIELD - f[a] = (b"\x48\x83\xec\x28" + call(a + 4, THUNK_FOO) # call XMemFoo - + b"\x8b\x48\x10\x85\xc9\x75\x01\xcc" # mov ecx, [rax+0x10]; test; jne; int3 - + b"\x48\x83\xc4\x28\xc3") - a = INIT - f[a] = (b"\x48\x83\xec\x28" + call(a + 4, THUNK_FOO) - + b"\x48\x89\x05" + rip(a + 9, 7, GLOBAL_PTR) + b"\x48\x83\xc4\x28\xc3") # mov [rip+ptr], rax - f[RESET] = b"\x48\xc7\x05" + rip(RESET, 11, GLOBAL_PTR) + b"\x00\x00\x00\x00\xc3" # mov qword [rip+ptr], 0 - a = USE - f[a] = (b"\x48\x8b\x05" + rip(a, 7, GLOBAL_PTR) # mov rax, [rip+ptr] - + b"\x48\x85\xc0\x75\x01\xcc\xc3") # test rax, rax; jne; int3; ret - a = BOOL - f[a] = (b"\x53\x48\x83\xec\x20\x33\xdb" + call(a + 7, THUNK_FOO) # push; sub; xor ebx, ebx; call - + b"\x85\xc0\x78\x02\xb3\x01" # test eax, eax; js done; mov bl, 1 - + b"\x8b\xc3\x48\x83\xc4\x20\x5b\xc3") # done: mov eax, ebx; ...; ret - return {start: (code, start + len(code)) for start, code in f.items()} - - -def build(): - buf = bytearray(build_image([])) - entries = sorted(functions().items()) - for start, (code, end) in entries: - buf[start:end] = code - for i, (start, (_, end)) in enumerate(entries): - struct.pack_into(" len(data): - continue - to = base + m.end() + 4 + {0xC6: 1, 0xC7: 4}.get(op, 0) + struct.unpack_from("= 0")) - self.assertEqual(g["registers"][0]["import"], "xmem.dll!XMemFoo") - self.assertEqual((ok["stop"], ok["never_returns"], ok["reached_from_start"], ok["callers"]), - ("instruction", False, False, [])) - start = out[hex(IMPORT_CHECK)] # the function's first instruction - self.assertEqual((start["guards"], start["reached_from_start"]), ([], True)) - self.assertIn("no guard: every path from the function start reaches it", - int3_cause.to_text({"x": start})) - - def test_returns_lists_each_value_with_the_branches_that_set_it(self): - out = int3_cause.cause(self.data, [hex(BOOL + 0x13)], returned=True)[hex(BOOL + 0x13)] - self.assertEqual((out["stop"], out["function"][0], out["rets"], out["complete"]), ("returns", BOOL, 1, True)) - by_value = {x["constant"]: x for x in out["returns"]} - self.assertEqual(sorted(by_value), [0, 1]) - one, zero = by_value[1], by_value[0] - self.assertEqual((one["at"], one["copied"], zero["at"]), (BOOL + 0x10, True, BOOL + 5)) - [g] = one["guards"] - self.assertEqual((g["jump"], g["condition"]), ("js", "eax >= 0")) - self.assertEqual(g["registers"][0]["import"], "xmem.dll!XMemFoo") - self.assertTrue(zero["reached_from_start"]) - text = int3_cause.to_text({"x": out}) - self.assertIn(f"a copy of a constant (1) at {BOOL + 0x10:#x}:", text) - self.assertIn(f"js at {BOOL + 0xE:#x}, fall-through side: runs when eax >= 0", text) - self.assertIn("on every path from the function start", text) - - def test_wine_reports_the_address_after_the_int3(self): - r = self.one(f"exe+{IMPORT_STOP + 1:#x}") - self.assertEqual((r["rva"], r["at"]), (IMPORT_STOP + 1, IMPORT_STOP)) - self.assertEqual(r["guards"][0]["condition"], "eax < 0") - - def test_comparisons_read_as_conditions(self): - def cond(code, jcc_cc): - insn = decode(code, 0, 0) - self.assertEqual(insn.size, len(code)) - return int3_cause.condition(int3_cause.read_test(insn, code), jcc_cc) - self.assertEqual(cond(b"\x83\xf8\xff", 0x2), "eax > 16) & 0xFFFF - self.assertNotEqual(lo & 0x7C00, 0x7C00, hex(word)) - self.assertNotEqual(hi & 0x7C00, 0x7C00, hex(word)) - - def test_random_kernel_is_deterministic_per_seed(self): - a = ihp.random_kernel(Random(7), {"denorm32": 3})[0].lines - b = ihp.random_kernel(Random(7), {"denorm32": 3})[0].lines - self.assertEqual(a, b) # the instruction listing - - def test_random_kernel_layout(self): - kern, info = ihp.random_kernel(Random(3), {"denorm32": 3}) - stores = [l for l in kern.lines if l.startswith("global_store_dword")] - writes = [l for l in kern.lines if l.startswith("ds_write_b32")] - self.assertEqual(len(stores), 224) # 8 attrs x 4 channels x 7 outputs - self.assertEqual(len(writes), 160) # 3 attribute words each + I/J per lane - self.assertIn("s_mov_b32 m0, 0", kern.lines) - self.assertIn("v_interp_p1_f32 v2, v20, attr0.x", kern.lines) - self.assertEqual(len(info), 4) # params, kinds, ij, per-channel tags - - def test_tie_kernel_layout_is_two_stores_per_form(self): - kern, (groups, lanes, nout) = ihp.tie_kernel({"denorm32": 3}) - stores = [l for l in kern.lines if "global_store_dword" in l] - p1ll = [l for l in kern.lines if "v_interp_p1ll_f16" in l] - p2 = [l for l in kern.lines if "v_interp_p2_f16" in l] - self.assertEqual(nout, 4 * len(groups)) - self.assertEqual(len(stores), nout) # p1ll and p2 stored per form per group - self.assertEqual(len(p1ll), 2 * len(groups)) # normal and ` high` - self.assertEqual(len(p2), 2 * len(groups)) - - -class TieCheckTest(unittest.TestCase): - def test_a_value_that_rounds_differently_once_versus_twice_is_tallied(self): - # q = 1 + 2**-11 + 2**-24: f16 directly rounds it UP off the tie, while the f32 step ties - # to even and the f16 re-round then ties DOWN to 1.0. - h20 = F(2) ** -14 - j = F(8) + F(1, 8192) # h20 * j = 2**-11 + 2**-24 - groups = [((1.0, 1.0, 2.0 ** -14), [(1.0, float(j))])] - lanes = [(0, 1.0, float(j))] - nout = 4 - q = F(1) + h20 * j - got = 0x3C01 # the direct-once f16 result - res = [ihp.f32w(1.0), got, 0, 0] - tally, bad = {}, [] - ihp.check_ties(res, (groups, lanes, nout), tally, bad) - key = ("tie", "p2_f16 rounds once (not f32, then f16)") - self.assertIn(key, tally) - self.assertEqual(tally[key][0], 1) - self.assertEqual(tally[key][1], 0) - self.assertEqual(bad, []) - # and the sanity of the case itself: direct f16 differs from the via-f32 double round - self.assertNotEqual(ihp.f16w(ihp.r16(q)), ihp.f16w(ihp.r16(F(ihp.r32(q))))) - - def test_an_equal_result_is_not_tallied(self): - h20 = F(1) - groups = [((1.0, 1.0, 1.0), [(1.0, 0.5)])] - lanes = [(0, 1.0, 0.5)] - res = [ihp.f32w(1.0), 0x3C00, 0, 0] # got == both roundings == 1.0's f16 - tally, bad = {}, [] - ihp.check_ties(res, (groups, lanes, 4), tally, bad) - self.assertNotIn(("tie", "p2_f16 rounds once (not f32, then f16)"), tally) - self.assertEqual(bad, []) - - def test_a_word_that_matches_the_twice_rounded_result_is_reported_bad(self): - # Same q as the case above, but the stored word is the via-f32 one (1.0, 0x3C00) instead of - # the direct f16 (0x3C01). The model expects the direct rounding, so this has to land in the - # differ column and in bad, not in the ok column the previous test asserts. - h20 = F(2) ** -14 - j = F(8) + F(1, 8192) - groups = [((1.0, 1.0, 2.0 ** -14), [(1.0, float(j))])] - lanes = [(0, 1.0, float(j))] - q = F(1) + h20 * j - once, twice = ihp.f16w(ihp.r16(q)), ihp.f16w(ihp.r16(F(ihp.r32(q)))) - self.assertEqual((once, twice), (0x3C01, 0x3C00)) # the two really do disagree here - res = [ihp.f32w(1.0), twice, 0, 0] - tally, bad = {}, [] - ihp.check_ties(res, (groups, lanes, 4), tally, bad) - key = ("tie", "p2_f16 rounds once (not f32, then f16)") - self.assertEqual(tally[key], [0, 1]) - self.assertEqual(len(bad), 1) - self.assertIn("tie: lane 0", bad[0]) - self.assertIn(f"once {once:#06x} twice {twice:#06x}", bad[0]) - - -class RandomCheckTest(unittest.TestCase): - """check_random against hand-computed words: one (attr, component) pair, I = J = 1.0. - - p0 = p10 = p20 = the f32 1.0 (0x3F800000), and I = J = the f32 1.0 too, so every fma is exact. - The halves of that word are f16 0.0000 (low) and f16 0x3F80 = 1.875 (high): the f32 exponent - bits land in the f16 mantissa, which is exactly the kind of junk the split halves see. - o[0] p1_f32 = 1*1 + 1 = 2.0 -> 0x40000000 - o[1] p2_f32 = 1*1 + 2 = 3.0 -> 0x40400000 - o[2] p1ll low = 0*1 + 0 = 0.0 -> 0x00000000 - o[3] p2_f16 low = 0*1 + 0 = 0.0, canary on top -> 0xDEAD0000 - o[4] p1ll high = 1.875*1 + 1.875 = 3.75 -> 0x40700000 - o[5] p2_f16 high = 1.875*1 + 3.75 = 5.625 (f16 0x45A0) -> 0xDEAD45A0 - o[6] mov p0 -> 0x3F800000 - """ - - WORDS = [0x40000000, 0x40400000, 0x00000000, 0xDEAD0000, 0x40700000, 0xDEAD45A0, 0x3F800000] - - def run_check(self, words): - params = {(0, 0): (0x3F800000, 0x3F800000, 0x3F800000)} - kinds = {(0, 0): "f32"} - ij = [(ihp.f32w(1.0), ihp.f32w(1.0))] - info = (params, kinds, ij, 4 * ihp.NOUT_PER) - tally, bad = {}, [] - ihp.check_random(list(words), info, False, tally, bad) - return tally, bad - - def test_hand_computed_words_all_match(self): - tally, bad = self.run_check(self.WORDS) - self.assertEqual(bad, []) - self.assertEqual(len(tally), 9) # mov, both fma pairs, both half pairs, both canaries - for name, counts in tally.items(): - self.assertEqual(counts, [1, 0], name) - - def test_a_wrong_p1_f32_word_is_a_mismatch(self): - words = list(self.WORDS) - words[0] = 0x3FFFFFFF # one f32 ulp below 2.0 - tally, bad = self.run_check(words) - self.assertEqual(tally[("f32", "p1_f32 = fma(P10, I, P0)")], [0, 1]) - self.assertEqual(len(bad), 1) - self.assertIn("p1_f32 = fma(P10, I, P0)", bad[0]) - self.assertIn("lane 0 attr0.x", bad[0]) - - def test_a_p2_f16_that_keeps_its_dead_high_half_is_a_mismatch(self): - words = list(self.WORDS) - words[5] = 0x000045A0 # right low half, canary gone - tally, bad = self.run_check(words) - self.assertEqual(tally[("f32", "p2_f16 high keeps vdst[31:16]")], [0, 1]) - self.assertEqual(tally[("f32", "p2_f16 high = fma(h20, J, p1ll) in f16")], [1, 0]) - self.assertTrue(any("keeps vdst[31:16]" in b for b in bad)) - - -class CliTest(unittest.TestCase): - def run_tool(self, *argv): - with mock.patch("builtins.print"): - try: - return ihp.main(list(argv)) - except SystemExit as e: - return e.code - - def test_bad_seeds_are_a_usage_error(self): - with self.assertRaises(SystemExit) as ctx: - ihp.main(["--seeds", "1,x,3"]) - self.assertEqual(ctx.exception.code, 2) - - def test_denorm32_choice_is_enforced(self): - with self.assertRaises(SystemExit) as ctx: - ihp.main(["--denorm32", "1"]) - self.assertEqual(ctx.exception.code, 2) - - def test_no_oracle_is_77(self): - # Patch the oracle open instead of hoping this machine has no AMD GPU: on a box with a - # working gfx1036 target the unpatched call would run the real probe and return 0. - err = io.StringIO() - with mock.patch.object(ihp.runner, "open_oracle", - side_effect=ihp.runner.Unavailable("no AMD GPU on this box")): - with contextlib.redirect_stderr(err): - rc = ihp.main(["--arch", "gfx1036"]) - self.assertEqual(rc, 77) - self.assertIn("no AMD GPU on this box", err.getvalue()) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/test_isa_coverage.py b/tests/test_isa_coverage.py deleted file mode 100644 index ad653dca4..000000000 --- a/tests/test_isa_coverage.py +++ /dev/null @@ -1,344 +0,0 @@ -"""Unit tests for tools/isa_coverage.py (RDNA2 ISA coverage of the translator). - -The fixtures are our own text: a few made-up instruction entries in the schema of AMD's machine-readable ISA XML and -a few lines of translator-shaped source. No game data and no AMD file is needed. One test reads the real -amdgpu_isa_rdna2.xml when LEONIDA_RDNA2_ISA_XML points at it (download line in docs/isa_coverage.md) and skips -otherwise. - - python -I tests/test_isa_coverage.py -""" -from __future__ import annotations - -import contextlib -import io -import json -import os -import subprocess -import sys -import tempfile -import unittest -from unittest.mock import patch - -ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) -TOOLS_DIR = os.path.join(ROOT, "tools") -if TOOLS_DIR not in sys.path: - sys.path.insert(0, TOOLS_DIR) - -import isa_coverage as ic # noqa: E402 - -TRANSLATOR = os.path.join(TOOLS_DIR, "rdna2spirv.py") -REAL_XML = os.environ.get(ic.ENV_XML) - - -def _ins(name, *encodings): - encs = "".join(f"{e}" for e in encodings) - return (f"{name}" - f"{encs}") - - -FIXTURE_XML = ( - "MIT1.1.1" - "AMD RDNA 2" - + _ins("V_ADD_F32", "ENC_VOP2", "VOP3_INST_LITERAL", "VOP2_VOP_SDWA", "VOP2_VOP_DPP16") - + _ins("V_FANCY_F32", "ENC_VOP1") - + _ins("S_MOV_B32", "ENC_SOP1", "SOP1_INST_LITERAL") - + _ins("S_DENORM_MODE", "ENC_SOPP") - + _ins("V_CMP_LT_F32", "ENC_VOPC", "VOP3_SDST_ENC") - + _ins("S_NOP", "ENC_SOPP") - + _ins("GLOBAL_LOAD_DWORD", "ENC_FLAT_GLBL") - + _ins("SCRATCH_LOAD_DWORD", "ENC_FLAT_SCRATCH") - + _ins("IMAGE_LOAD", "ENC_MIMG", "MIMG_NSA1") - + _ins("S_ENDPGM", "ENC_SOPP") - + _ins("EXP", "ENC_EXP") - + _ins("S_AND_SAVEEXEC_B64", "ENC_SOP1") - + _ins("S_XOR_SAVEEXEC_B64", "ENC_SOP1") - + _ins("V_SHR_HI", "ENC_VOP1") - + _ins("V_SHR_LO", "ENC_VOP1") - + "") - -FIXTURE_SRC = ''' -NOOPS = {"s_nop", "s_endpgm"} -TABLE = {"v_add_f32": "OpFAdd", "v_made_up_f32": "OpFAdd"} - - -def base_op(op): - return op - - -class Gen: - LOGIC = {"and": 1, "or": 2} - - def _insn(self, ins): - op = base_op(ins["op"]) - if op in ("s_denorm_mode",): - raise Unsupported(op) - if op != "s_gone_b32": - pass - if op == "s_mov_b32": - pass - elif op.startswith("v_cmp_"): - pass - elif op in ("image_load", "v_add_u32_e64"): - if bad: - raise Unsupported(op + " form") - elif op == "exp": - pass - elif op.endswith("_saveexec_b64") and op[2:].split("_saveexec")[0] in self.LOGIC: - pass - elif op.endswith("_hi") and flag: - pass - elif op.endswith("_lo"): - raise Unsupported(op) - else: - raise Unsupported(op) - - def analysis(self, op): - return op.startswith("global_") -''' - - -def _fixture(text, suffix): - f = tempfile.NamedTemporaryFile("w", suffix=suffix, delete=False, encoding="utf-8") - f.write(text) - f.close() - return f.name - - -class LlvmProbeTests(unittest.TestCase): - def test_backend_failure_is_not_instruction_support(self) -> None: - diagnostic = "llvm-mc: error: unable to get target for 'amdgcn'" - failure = subprocess.CompletedProcess(["llvm-mc"], 1, "", diagnostic) - with patch.object(ic.subprocess, "run", return_value=failure): - outcome = ic.probe_llvm_mc("llvm-mc", ["s_endpgm"])["s_endpgm"] - self.assertEqual(outcome, f"LLVM probe failed (exit 1): {diagnostic}") - - def test_reports_success_and_known_instruction_diagnostics(self) -> None: - probes = ( - ("s_endpgm", 0, "", "LLVM: valid on gfx1013"), - ("v_add_f32", 1, ":1:1: error: too few operands for instruction", "LLVM: valid on gfx1013"), - ("v_bogus", 1, ":1:1: error: invalid instruction", "unknown to LLVM"), - ("v_wmma_f32", 1, ":1:1: error: instruction not supported on this GPU", - "LLVM: other GPU only (not gfx1013)"), - ) - for name, code, diagnostic, expected in probes: - with self.subTest(name=name): - outcome = subprocess.CompletedProcess(["llvm-mc"], code, "", diagnostic) - with patch.object(ic.subprocess, "run", return_value=outcome): - self.assertEqual(ic.probe_llvm_mc("llvm-mc", [name]), {name: expected}) - - -class LlvmStallTests(unittest.TestCase): - def test_stalled_llvm_mc_is_one_error_not_a_traceback(self) -> None: - stalled = subprocess.TimeoutExpired(["llvm-mc"], 30) - with patch.object(ic.subprocess, "run", side_effect=stalled) as run: - probe = ic.probe_llvm_mc("llvm-mc", ["s_endpgm", "v_add_f32"]) - self.assertEqual(list(probe), ["error"]) - self.assertIn("did not answer", probe["error"]) - self.assertEqual(run.call_count, 1) # the remaining names are not each given the full timeout again - - def test_main_reports_the_stall_next_to_each_name(self) -> None: - xml, src = _fixture(FIXTURE_XML, ".xml"), _fixture(FIXTURE_SRC, ".py") - self.addCleanup(os.unlink, xml) - self.addCleanup(os.unlink, src) - stalled = subprocess.TimeoutExpired(["llvm-mc"], 30) - out = io.StringIO() - with patch.object(ic.subprocess, "run", side_effect=stalled), contextlib.redirect_stdout(out): - code = ic.main(["--isa", xml, "--translator", src, "--llvm-mc", "llvm-mc"]) - self.assertEqual(code, 0) - self.assertIn("did not answer", out.getvalue()) - - -class FixtureTests(unittest.TestCase): - @classmethod - def setUpClass(cls): - cls.xml = _fixture(FIXTURE_XML, ".xml") - cls.src = _fixture(FIXTURE_SRC, ".py") - cls.isa = ic.read_isa(cls.xml) - cls.scan = ic.scan_translator(cls.src) - cls.rep = ic.build_report(cls.isa, cls.scan, ic.accepted_names(cls.src)) - - @classmethod - def tearDownClass(cls): - os.unlink(cls.xml) - os.unlink(cls.src) - - def test_reads_metadata_and_encoding_groups(self): - self.assertEqual(self.isa["architecture"], "AMD RDNA 2") - self.assertEqual(self.isa["license"], "MIT") - ins = self.isa["instructions"] - self.assertEqual(ins["v_add_f32"], ["VOP2", "VOP3", "DPP/SDWA"]) - self.assertEqual(ins["v_cmp_lt_f32"], ["VOPC", "VOP3"]) - self.assertEqual(ins["global_load_dword"], ["GLOBAL"]) - self.assertEqual(ins["scratch_load_dword"], ["SCRATCH"]) - self.assertEqual(ins["image_load"], ["MIMG"]) - - def test_classes(self): - c = self.rep["class"] - self.assertEqual(c["v_add_f32"], "handled-exact") # a table key - self.assertEqual(c["s_mov_b32"], "handled-exact") # an == test - self.assertEqual(c["s_nop"], "handled-exact") # a set - self.assertEqual(c["v_cmp_lt_f32"], "handled-family") # op.startswith in _insn - self.assertEqual(c["s_denorm_mode"], "refused") # a test whose whole body raises Unsupported - self.assertEqual(c["v_fancy_f32"], "unknown") - # op.startswith("global_") sits in a helper that is not the dispatch, so it must not count. - self.assertEqual(c["global_load_dword"], "unknown") - self.assertEqual(self.rep["totals"], {"handled-exact": 6, "handled-family": 2, "refused": 1, "unknown": 6}) - - def test_suffix_families(self): - c = self.rep["class"] - self.assertEqual(c["s_and_saveexec_b64"], "handled-family") - self.assertEqual(c["s_xor_saveexec_b64"], "unknown") - self.assertEqual(c["v_shr_hi"], "unknown") - self.assertEqual(c["v_shr_lo"], "unknown") - self.assertEqual(self.rep["suffixes"], {"_saveexec_b64": 1}) - self.assertIn("Suffix families the dispatch tests with op.endswith", ic.markdown(self.rep)) - - def test_partial_refusal_is_flagged_but_handled(self): - self.assertEqual(self.rep["class"]["image_load"], "handled-exact") - self.assertIn("image_load", self.rep["partial"]) - - def test_names_that_are_not_rdna2(self): - names = {e["name"]: e for e in self.rep["not_in_rdna2"]} - self.assertEqual(sorted(names), ["s_gone_b32", "v_add_u32_e64", "v_made_up_f32"]) - self.assertTrue(names["v_add_u32_e64"]["never_matches_after_base_op"]) - self.assertEqual(names["v_add_u32_e64"]["stem"], "v_add_u32") - self.assertFalse(names["v_made_up_f32"]["never_matches_after_base_op"]) - - def test_not_equal_is_not_a_refusal(self): - # `if op != "x": raise Unsupported` guards x, it does not refuse it. - src = _fixture('def f(op):\n if op != "s_setreg_imm32_b32":\n raise Unsupported(op)\n', ".py") - try: - self.assertEqual(ic.scan_translator(src)["refused"], []) - finally: - os.unlink(src) - - def test_accepted_names_keeps_tuple_comparators_when_refusal_uses_tuple(self): - # Python shares the ast.Load() singleton across every tuple/list comparator in the AST, so putting - # non-expr nodes into accepted_names()'s skip set used to drop every other `op in (...)` tuple in the file. - accepted = ic.accepted_names(self.src) - self.assertIn("image_load", accepted) - self.assertIn("v_add_u32_e64", accepted) - self.assertNotIn("s_denorm_mode", accepted) - src = _fixture( - 'def f(op):\n' - ' if op in ("v_fancy_f32",):\n' - ' raise Unsupported(op)\n' - ' elif op in ("v_fancy_f32", "s_mov_b32"):\n' - ' return 1\n', - ".py", - ) - try: - rep = ic.build_report(self.isa, ic.scan_translator(src), ic.accepted_names(src)) - self.assertEqual(rep["class"]["v_fancy_f32"], "handled-exact") - self.assertNotIn("v_fancy_f32", rep["refused"]) - finally: - os.unlink(src) - - def test_negated_and_guarded_comparisons_are_not_refusals(self): - src = _fixture( - 'def f(op, bad):\n' - ' if not (op == "s_setreg_imm32_b32"):\n' - ' raise Unsupported(op)\n' - ' if op in ("v_qsad_pk_u16_u8", "v_mqsad_pk_u16_u8") and bad:\n' - ' raise Unsupported(op)\n', - ".py", - ) - try: - scan = ic.scan_translator(src) - self.assertEqual(scan["refused"], []) - self.assertEqual(scan["partial"], ["v_mqsad_pk_u16_u8", "v_qsad_pk_u16_u8"]) - self.assertTrue({"v_qsad_pk_u16_u8", "v_mqsad_pk_u16_u8"} <= ic.accepted_names(src)) - finally: - os.unlink(src) - - def test_groups_count_each_encoding(self): - g = self.rep["groups"] - self.assertEqual(g["VOP2"]["handled-exact"], 1) - self.assertEqual(g["VOP3"]["total"], 2) # v_add_f32 literal form + v_cmp_lt_f32 sdst form - self.assertEqual(g["DPP/SDWA"]["total"], 1) - self.assertEqual(g["GLOBAL"]["unknown"], 1) - - def test_outputs(self): - text = ic.markdown(self.rep, list_unknown=True) - self.assertIn("| VOP2 | 1 | 1 | 0 | 0 | 0 |", text) - self.assertIn("`v_made_up_f32`", text) - self.assertIn("`v_fancy_f32`", text) - self.assertEqual(json.loads(json.dumps(self.rep))["totals"], self.rep["totals"]) - - def test_cli(self): - import contextlib - import io - out = io.StringIO() - with contextlib.redirect_stdout(out): - self.assertEqual(ic.main(["--isa", self.xml, "--translator", self.src, "--json"]), 0) - self.assertEqual(json.loads(out.getvalue())["instructions"], 15) - - -class TranslatorScanTests(unittest.TestCase): - """The real translator: facts that must keep holding for the scan to mean anything. No XML needed.""" - - @classmethod - def setUpClass(cls): - cls.scan = ic.scan_translator(TRANSLATOR) - - def test_finds_well_known_rules(self): - for name in ("v_mov_b32", "s_mov_b32", "v_cndmask_b32", "v_add_f32", "s_endpgm", "exp"): - self.assertIn(name, self.scan["exact"], name) - self.assertIn("v_cmp_", self.scan["prefixes"]) - self.assertIn("s_denorm_mode", self.scan["refused"]) - - def test_dispatch_size_sanity(self): - # A scan that silently stops seeing the if/elif chain would report almost everything unknown. - self.assertGreater(len(self.scan["exact"]), 300) - - def test_accepted_names_matches_non_refused_exact(self): - accepted = ic.accepted_names(TRANSLATOR) - self.assertEqual(set(self.scan["exact"]) - accepted, set(self.scan["refused"])) - - -@unittest.skipUnless(REAL_XML and os.path.isfile(REAL_XML), f"set {ic.ENV_XML} to amdgpu_isa_rdna2.xml") -class RealIsaTests(unittest.TestCase): - # Names the translator matches that AMD's RDNA2 XML does not list. Each one was looked at (docs/isa_coverage.md); - # a name that is not here and not in the XML is a typo or a wrong-generation name and fails the test. - KNOWN_NOT_IN_XML = { - "s_delay_alu": "RDNA3 instruction, kept in NOOPS so RDNA3 text does not trip the translator", - "s_get_waveid_in_workgroup": "gfx1013 per llvm-mc, missing from the XML", - "v_mac_f32": "gfx1013 per llvm-mc, missing from the XML", - "v_mad_f32": "gfx1013 per llvm-mc, missing from the XML", - "v_mad_legacy_f32": "gfx1013 per llvm-mc, missing from the XML", - "v_madak_f32": "gfx1013 per llvm-mc, missing from the XML", - "v_madmk_f32": "gfx1013 per llvm-mc, missing from the XML", - "v_mac_legacy_f32": "gfx1013 per llvm-mc (VOP2 v_mac_legacy_f32_e32), missing from the XML", - "v_add_u16": "internal: v_add_nc_u16 is re-dispatched under this GFX9 spelling", - "v_sub_u16": "internal: v_sub_nc_u16 is re-dispatched under this GFX9 spelling", - "v_add_i16": "internal: v_add_nc_i16 is re-dispatched under this name", - "v_sub_i16": "internal: v_sub_nc_i16 is re-dispatched under this name", - "s_atc_probe": "gfx1013 per llvm-mc, missing from the XML (a no-op in NOOPS)", - "s_atc_probe_buffer": "gfx1013 per llvm-mc, missing from the XML (a no-op in NOOPS)", - } - - @classmethod - def setUpClass(cls): - cls.rep = ic.build_report(ic.read_isa(REAL_XML), ic.scan_translator(TRANSLATOR), - ic.accepted_names(TRANSLATOR)) - - def test_translator_names_exist_in_rdna2(self): - stray = sorted(e["name"] for e in self.rep["not_in_rdna2"] if e["name"] not in self.KNOWN_NOT_IN_XML) - self.assertEqual(stray, [], "translator matches names that are not RDNA2 instructions") - - def test_no_name_ends_in_a_stripped_suffix(self): - dead = [e["name"] for e in self.rep["not_in_rdna2"] if e["never_matches_after_base_op"]] - self.assertEqual(dead, []) - - def test_every_prefix_matches_something(self): - self.assertEqual(self.rep["prefixes_without_rdna2_match"], []) - - def test_saveexec_family_is_handled(self): - stems = ("and", "andn1", "andn2", "nand", "nor", "or", "orn1", "orn2", "xnor", "xor") - for w in ("b32", "b64"): - for k in stems: - self.assertEqual(self.rep["class"][f"s_{k}_saveexec_{w}"], "handled-family", (k, w)) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/test_joaat_agreement.py b/tests/test_joaat_agreement.py deleted file mode 100644 index 478ab0c4c..000000000 --- a/tests/test_joaat_agreement.py +++ /dev/null @@ -1,83 +0,0 @@ -"""One joaat rule across tools: every lowercased copy hashes a name as tools/hashdict.py does. - - python -I tests/test_joaat_agreement.py - -Each tool carries its own copy of Jenkins one-at-a-time, so nothing stopped one of them from encoding -the name differently. Two did: audio_config hashed the lowercased UTF-8 bytes, and world_names encoded -to UTF-8 first and then lower-cased the bytes (bytes.lower() only folds ASCII). Both gave a different -32-bit hash for any non-ASCII character, which surfaces as a stream id no bank stores or a name hash -that never resolves, with no error anywhere. This test imports every copy in tools/ and compares it -with the dictionary the rest of the pipeline is pinned to. - -Synthetic names only; no game data. -""" -import os -import re -import sys -import unittest - -ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) -TOOLS = os.path.join(ROOT, "tools") -for path in (ROOT, TOOLS): - if path not in sys.path: - sys.path.insert(0, path) - -import hashdict # noqa: E402 - -# ASCII names, then names with a non-ASCII character: "é" is one Latin-1 byte (0xE9) and two UTF-8 -# bytes (0xC3 0xA9), and "ÉLÉGIE" also tells text.lower() apart from lower-casing the encoded bytes. -NAMES = [ - "adder", "plain_name", "burn", "boardwalk", - "café", "Café", "Señor", "Crème Brûlée", "ÉLÉGIE", "Radio_LosSantos_Café", -] - -# The modules whose name a reviewer would expect here: a rename must not turn the loop below into a -# test of nothing. -EXPECTED = ("anim_index", "audio_config", "awc_names", "hashdict", "mission_tables", "world_names") - - -def string_hash_copies(): - """{module name: function} for every ``def joaat(``/``def joaat32(`` that takes a string. - - ``tools/save_keys.py`` defines ``joaat(data, seed=0)`` over bytes with a seed for the composition - probe; it is a different hash and is covered by tests/test_save_keys.py. - """ - copies = {} - for filename in sorted(os.listdir(TOOLS)): - if not filename.endswith(".py"): - continue - with open(os.path.join(TOOLS, filename), encoding="utf-8") as handle: - source = handle.read() - for match in re.finditer(r"^def (joaat32|joaat)\(\s*([A-Za-z_]\w*)", source, re.M): - if match.group(2) == "data": - continue - module = __import__(filename[:-3]) - copies[filename[:-3]] = getattr(module, match.group(1)) - return copies - - -class JoaatAgreementTest(unittest.TestCase): - def test_every_copy_matches_the_pinned_dictionary(self): - copies = string_hash_copies() - for module in EXPECTED: - self.assertIn(module, copies) - for module, function in sorted(copies.items()): - for name in NAMES: - with self.subTest(copy=module, name=name): - self.assertEqual(function(name), hashdict.joaat(name), - f"{module} hashes {name!r} differently from hashdict.joaat") - - def test_a_stream_id_is_the_name_hash_of_the_same_name(self): - # The consequence of the bug: audio_config's id and the id awc_names recovers from a bank were - # computed with two different encodings, so they could never match for an accented title. - import audio_config - import awc_names - - for title in ("Café", "Crème Brûlée", "Radio Los Santos", "plain_song"): - with self.subTest(title=title): - self.assertEqual(audio_config.title_stream_id(title), - awc_names.joaat(audio_config.normalized_name(title)) & 0x1FFFFFFF) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/test_json_bom_inputs.py b/tests/test_json_bom_inputs.py deleted file mode 100644 index b0b9dc6ef..000000000 --- a/tests/test_json_bom_inputs.py +++ /dev/null @@ -1,192 +0,0 @@ -import contextlib -import io -import json -from pathlib import Path -import subprocess -import sys -import tempfile -import unittest -from unittest import mock - -__author__ = "it_komarov" - -ROOT = Path(__file__).resolve().parents[1] -sys.path.insert(0, str(ROOT / "tools")) - -import bcpack_history_calib as calibration -import bcpack_tables_bptc as history -import character_textures -import feature_scan -import gdk_runtime_calls -import ped_assemble -import shader_profile -import skinned_glb -import wave64_halves -import wave64_pipeline_audit as audit - - -class JsonBomInputTests(unittest.TestCase): - def setUp(self): - folder = tempfile.TemporaryDirectory() - self.addCleanup(folder.cleanup) - self.folder = Path(folder.name) - - def variants(self, document, name="input.json"): - for encoding in ("utf-8", "utf-8-sig"): - path = self.folder / name - path.parent.mkdir(parents=True, exist_ok=True) - path.write_bytes(json.dumps(document, ensure_ascii=False).encode(encoding)) - yield path - - def malformed(self, name="invalid.json"): - path = self.folder / name - path.parent.mkdir(parents=True, exist_ok=True) - path.write_bytes(b'\xef\xbb\xbf{"value":"\xff"}') - return path - - def call_main(self, main, arguments): - out, err = io.StringIO(), io.StringIO() - with contextlib.redirect_stdout(out), contextlib.redirect_stderr(err): - result = main(arguments) - return result, out.getvalue(), err.getvalue() - - def test_character_textures_material_bindings(self): - document = {"Name": "synthetic_model", "Materials": [{ - "Name": "head", "Shader": "a1b2c3d4", - "Textures": [{"Param": "0xC8E8C282", "Name": "synthetic_diffuse"}], - }]} - with self.assertRaises(ValueError): - character_textures.classify_file(str(self.malformed())) - for path in self.variants(document): - result = character_textures.classify_file(str(path))["models"] - self.assertEqual(result[0]["name"], "synthetic_model") - binding = result[0]["materials"][0]["bindings"][0] - self.assertEqual(binding["role"], "diffusetex") - self.assertEqual(binding["texture"], "synthetic_diffuse") - - def test_skinned_glb_model_json(self): - document = {"Name": "synthetic_\u00e9", "Materials": [{"Name": "material"}]} - with self.assertRaises(skinned_glb.SkinError): - skinned_glb._load_json(str(self.malformed())) - for path in self.variants(document, "model.json"): - self.assertEqual(skinned_glb._load_json(str(path)), document) - - def test_gdk_runtime_class_and_interface_lookup(self): - class_id = "00000000-0000-0000-0000-000000000001" - interface_id = "00000000-0000-0000-0000-000000000002" - document = { - "source": "synthetic_\u00e9", - "classes": {"Example": {"id": class_id, "implements": ["IExample"]}}, - "interfaces": {"IExample": {"id": interface_id, "class": "Example"}}, - } - with self.assertRaises(ValueError): - gdk_runtime_calls.RuntimeTable.load(str(self.malformed())) - for path in self.variants(document): - table = gdk_runtime_calls.RuntimeTable.load(str(path)) - self.assertEqual(table.source, "synthetic_\u00e9") - self.assertEqual(table.ids(), {class_id, interface_id}) - self.assertEqual(table.label(interface_id), "IExample") - self.assertEqual(table.class_of(interface_id), "Example") - - def test_shader_profile_preserves_stage_map(self): - disasm = self.folder / "dxbc" / "disasm" - disasm.mkdir(parents=True) - document = [{"file": "opaque.code.dxbc", "stage": "ps"}] - self.malformed("dxbc/index.json") - self.assertEqual(shader_profile.stage_map(disasm), {}) - for _ in self.variants(document, "dxbc/index.json"): - self.assertEqual(shader_profile.stage_map(disasm), {"opaque.code": "ps"}) - - def test_wave64_pipeline_audit_index_and_saved_caps(self): - document = {"synthetic": {"stage": "ps", "wave64": True, "wave64_graphics": "A"}} - caps = { - "subgroup_size": 32, "min_subgroup_size": 32, "max_subgroup_size": 32, - "supported_subgroup_stages": 63, "required_subgroup_size_stages": 32, - "subgroup_size_control": True, "max_compute_workgroup_subgroups": 32, - } - with self.assertRaises(ValueError): - audit.load_json(self.malformed()) - for index in self.variants(document, "index.json"): - for device in self.variants(caps, "caps.json"): - result, out, err = self.call_main(audit.main, [ - str(index), "--device-info", str(device), "--strict", - ]) - self.assertEqual(result, 0, err) - self.assertIn("shaders (1): partition-invariant=1", out) - - def test_bcpack_history_tables(self): - bc6h = {"endpointHistory": {"7": [[1, 2, 3, 4]] * 3}, "endpointClass": {"7": 3}} - bc7 = {"historyEndpoints": {"9": list(range(24))}} - bc4 = {"codec": "bc4", "confirmed": {"11": [17, 23]}, "replace": True} - for load in (history.load_bc6h, history.load_bc7, - lambda path: history.load_bc_history(4, path)): - with self.assertRaises(ValueError): - load(self.malformed()) - for path in self.variants({"bc6h": bc6h}, "bc6h.json"): - loaded = history.load_bc6h(path) - self.assertEqual(loaded[0][7], ((1, 2, 3, 4),) * 3) - self.assertEqual(loaded[2][7], 3) - for _ in self.variants(bc7, "bc7/bc7.json"): - loaded = history.load_bc7(self.folder / "bc7") - self.assertEqual(loaded["history_endpoints"][9], tuple(range(24))) - for _ in self.variants(bc4, "bc4/bc4.json"): - loaded = history.load_bc_history(4, self.folder / "bc4") - self.assertEqual(loaded, ({11: (17, 23)}, {}, True)) - - def test_wave64_halves_census_counts(self): - result, _, err = self.call_main(wave64_halves.main, ["--census", str(self.malformed())]) - self.assertEqual(result, 2) - self.assertIn("ERROR:", err) - document = {"synthetic": {"stage": "vs", "wave64": True, "wave64_graphics": "B"}} - for path in self.variants(document): - result, out, err = self.call_main(wave64_halves.main, ["--census", str(path)]) - self.assertEqual(result, 0, err) - self.assertIn("vs: B=1", out) - self.assertNotIn("synthetic", out) - - def test_ped_assemble_recursive_mesh_manifest(self): - mesh = {"name": "triangle", "positions": [[0, 0, 0], [1, 0, 0], [0, 1, 0]], - "triangles": [[0, 1, 2]]} - with self.assertRaises(ValueError): - ped_assemble.load_parts_from_path(str(self.malformed())) - for path in self.variants(mesh, "mesh.json"): - for manifest in self.variants({"parts": [path.name]}, "manifest.json"): - parts, skeleton = ped_assemble.load_parts_from_path(str(manifest)) - self.assertIsNone(skeleton) - self.assertEqual(len(parts), 1) - self.assertEqual(parts[0].name, "triangle") - self.assertEqual(parts[0].positions[1], (1.0, 0.0, 0.0)) - self.assertEqual(parts[0].triangles, [(0, 1, 2)]) - - def test_feature_scan_carve_and_translation_indices(self): - with self.assertRaises(ValueError): - feature_scan.scan_spirv(str(self.malformed())) - translated = {"synthetic": {"stage": "ps", "uses_code_base": True}} - for path in self.variants(translated, "shaders/spirv/index.json"): - self.assertEqual(feature_scan.scan_spirv(str(path)), { - "translated": {"ps": 1}, "uses_code_base": {"ps": 1}, - }) - for carve in self.variants([], "shaders/dxbc/index.json"): - result = subprocess.run([ - sys.executable, "-B", "-I", str(ROOT / "tools" / "feature_scan.py"), - str(carve.parent.parent), - ], capture_output=True, text=True, encoding="utf-8", timeout=30) - self.assertEqual(result.returncode, 0, result.stderr) - self.assertIn("uses_code_base by stage: {'ps': 1} of {'ps': 1}", result.stdout) - - def test_bcpack_reference_pairs_dispatch(self): - with self.assertRaises(ValueError): - calibration.apply_ref_pairs_file(str(self.malformed()), {}) - document = {"pairs": [{"pool": "pool.ttpf", "dds": "reference.dds", "index": 2}]} - calibrators = {4: object()} - for path in self.variants(document): - with mock.patch.object(calibration, "apply_ref_dds") as apply: - calibration.apply_ref_pairs_file(str(path), calibrators) - apply.assert_called_once_with( - str(self.folder / "pool.ttpf"), 2, - str(self.folder / "reference.dds"), calibrators, - ) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/test_lane_masks.py b/tests/test_lane_masks.py deleted file mode 100644 index d83c1544f..000000000 --- a/tests/test_lane_masks.py +++ /dev/null @@ -1,390 +0,0 @@ -"""lane_masks.analyse: which registers hold a lane mask when an instruction runs. - - python -I tests/test_lane_masks.py -""" -import os -import sys - -sys.path.insert(0, os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "tools")) -import lane_masks as L # noqa: E402 - - -def s(r, n=1): - return {"k": "sgpr", "r": r, "n": n} - - -def sp(t): - return {"k": "special", "t": t} - - -def imm(v): - return {"k": "imm", "v": v} - - -def v(r): - return {"k": "vgpr", "r": r, "n": 1} - - -def ins(op, *args): - return {"op": op, "args": list(args), "mods": []} - - -def masks_at_last(blocks, succ, block=-1): - return set(L.analyse(blocks, succ)[0][id(blocks[block][-1])]) - - -def test_straight_line(): - use = ins("s_bcnt1_i32_b64", s(8), s(6, 2)) - # A saved EXEC is a mask, in both registers of the pair. - assert masks_at_last([[ins("s_mov_b64", s(6, 2), sp("exec")), use]], [[]]) == {6, 7} - # A compare result is a mask, whether it lands in VCC or in a register pair. - assert masks_at_last([[ins("v_cmp_gt_f32_e32", sp("vcc_lo"), imm(0), v(1)), use]], [[]]) == {"vcc"} - assert masks_at_last([[ins("v_cmp_gt_f32_e64", s(6, 2), imm(0), v(1)), use]], [[]]) == {6, 7} - # Masks combined with masks stay masks; saveexec leaves the old EXEC in its destination. - assert masks_at_last([[ins("v_cmp_eq_u32_e64", s(2, 2), v(0), v(1)), ins("s_and_b64", s(6, 2), s(2, 2), sp("exec")), - ins("s_and_saveexec_b64", s(10, 2), s(6, 2)), use]], [[]]) == {2, 3, 6, 7, 10, 11} - # A light mask built from loaded dwords is data, and so is a mask once data is mixed in or it is overwritten. - assert masks_at_last([[ins("s_buffer_load_dword", s(6), s(0, 4), imm(8)), ins("s_lshr_b32", s(7), s(6), imm(3)), - use]], [[]]) == set() - assert masks_at_last([[ins("s_mov_b64", s(6, 2), sp("exec")), ins("s_and_b64", s(6, 2), s(6, 2), s(20, 2)), - use]], [[]]) == set() - assert masks_at_last([[ins("s_mov_b64", s(6, 2), sp("exec")), ins("s_load_dwordx4", s(4, 4), s(0, 2), imm(0)), - use]], [[]]) == set() - # Compares that only set SCC, and v_cmpx, read their first operand: the mask in it survives. - assert masks_at_last([[ins("s_mov_b64", s(6, 2), sp("exec")), ins("s_cmp_eq_u64", s(6, 2), imm(0)), - ins("v_cmpx_eq_u32_e32", s(6), v(1)), use]], [[]]) == {6, 7} - # Carry out of a 64-bit add, and the carry/sign sdst of 64-bit MAD, are lane masks. - assert masks_at_last([[ins("v_add_co_u32_e64", v(0), s(6, 2), v(1), v(2)), use]], [[]]) == {6, 7} - assert masks_at_last([[ins("v_mad_u64_u32", {"k": "vgpr", "r": 0, "n": 2}, s(6, 2), v(2), v(3), - {"k": "vgpr", "r": 4, "n": 2}), use]], [[]]) == {6, 7} - assert masks_at_last([[ins("v_mad_i64_i32", {"k": "vgpr", "r": 0, "n": 2}, sp("vcc"), v(2), v(3), - {"k": "vgpr", "r": 4, "n": 2}), use]], [[]]) == {"vcc"} - assert masks_at_last([[ins("v_mad_u64_u32", {"k": "vgpr", "r": 0, "n": 2}, sp("null"), v(2), v(3), - {"k": "vgpr", "r": 4, "n": 2}), use]], [[]]) == set() - - -def test_joins(): - use = ins("s_ff1_i32_b64", s(8), s(6, 2)) - mask = ins("s_mov_b64", s(6, 2), sp("exec")) - zero = ins("s_mov_b64", s(6, 2), imm(0)) - data = ins("s_load_dwordx2", s(6, 2), s(0, 2), imm(0)) - diamond = [[1, 2], [3], [3], []] - # A mask on one path and a constant 0 on the other: a mask. A mask on one and data on the other: not. - assert masks_at_last([[ins("s_nop")], [mask], [zero], [use]], diamond) == {6, 7} - assert masks_at_last([[ins("s_nop")], [mask], [data], [use]], diamond) == set() - # Constant on every path: plain data (the bits are the same either way). - assert masks_at_last([[ins("s_nop")], [zero], [dict(zero)], [use]], diamond) == set() - # A mask accumulated around a loop stays a mask; the loop body is seen with the entry state merged in. - acc = ins("s_or_b64", s(6, 2), s(6, 2), sp("vcc")) - cmp_ = ins("v_cmp_lt_u32_e32", sp("vcc_lo"), v(0), v(1)) - assert masks_at_last([[zero], [cmp_, acc], [use]], [[1], [1, 2], []]) == {6, 7, "vcc"} - # Unreachable blocks get an answer too (nothing is a mask there). - assert masks_at_last([[mask], [use]], [[], []]) == set() - - -def test_parked_masks(): - save = ins("s_mov_b64", s(0, 2), sp("exec")) - park = [ins("v_writelane_b32", v(128), s(0), imm(0)), ins("v_writelane_b32", v(128), s(1), imm(1))] - clobber = ins("s_load_dwordx2", s(0, 2), s(8, 2), imm(0)) - fetch = [ins("v_readlane_b32", s(0), v(128), imm(0)), ins("v_readlane_b32", s(1), v(128), imm(1))] - use = ins("s_mov_b64", sp("exec"), s(0, 2)) - slots = {("lane", 128, 0), ("lane", 128, 1)} - # A saved EXEC parked in two lanes of v128 and fetched back is a mask again; the slots stay known. - assert masks_at_last([[save] + park + [clobber] + fetch + [use]], [[]]) == {0, 1} | slots - # Data parked the same way stays data, and so does a mask fetched from a lane it was not parked in. - assert masks_at_last([[clobber] + park + fetch + [use]], [[]]) == set() - other_lane = ins("v_readlane_b32", s(0), v(128), imm(5)) - assert masks_at_last([[save, park[0], clobber, other_lane, use]], [[]]) == {("lane", 128, 0)} - # Writing the VGPR any other way ends what was parked there. - assert masks_at_last([[save] + park + [clobber, ins("v_mov_b32_e32", v(128), imm(0))] + fetch + [use]], [[]]) == set() - # Parked on one path only: not a mask. - assert masks_at_last([[save], park, [ins("s_nop")], [clobber] + fetch + [use]], [[1, 2], [3], [3], []]) == set() - # The slots the translator has to keep per lane: those some v_readlane fetches a mask from. - blocks = [[save] + park + [clobber] + fetch + [use]] - assert L.parked(blocks, L.analyse(blocks, [[]])[0]) == [(128, 0), (128, 1)] - blocks = [[clobber] + park + fetch + [use]] - assert L.parked(blocks, L.analyse(blocks, [[]])[0]) == [] - - -def test_masks_through_a_vgpr(): - use = ins("s_mov_b32", sp("exec_lo"), s(3)) - masks = [ins("s_mov_b32", s(3), sp("exec_lo")), ins("v_cmp_eq_u32_e64", s(47), v(1), v(2))] - # An OR of two masks done in the vector unit and read back: still a mask, through v51. - via = [ins("v_mov_b32_e32", v(51), s(3)), ins("v_or3_b32", v(51), s(3), s(47), v(51)), - ins("v_readfirstlane_b32", s(3), v(51))] - blocks = [masks + via + [use]] - got, writes = L.analyse(blocks, [[]]) - assert set(got[id(use)]) == {3, 47, ("v", 51)} - # Only the v_or3 is a mask write: the v_mov copy is an ordinary VALU write (SHADER-21 part 2). - assert writes == {id(via[1])} - # Mixed with data, or with the VGPR written by anything else in between, it is data. - data = ins("s_buffer_load_dword", s(47), s(0, 4), imm(0)) - assert masks_at_last([[masks[0], data] + via + [use]], [[]]) == set() - assert masks_at_last([masks + [via[0], ins("v_add_nc_u32_e32", v(51), v(51), v(2)), via[2], use]], [[]]) == {47} - # A constant alone does not make a VGPR a mask (v_mov_b32 v, 0 is everywhere). - blocks = [[ins("v_mov_b32_e32", v(51), imm(0)), ins("v_readfirstlane_b32", s(3), v(51)), use]] - assert L.analyse(blocks, [[]]) == ({id(i): {} for i in blocks[0]}, set()) - - -def test_vmov_mask_copy_is_exec_gated(): - # SHADER-21 part 2: a mask copied into a VGPR with v_mov_b32 is an ordinary - # VALU write, so inactive lanes keep the old VGPR; only per-lane mask - # computations (v_or3_b32 etc.) take the all-lanes store. - cmp_ = ins("v_cmp_lt_u32_e64", sp("vcc_lo"), v(5), v(6)) - copy = ins("v_mov_b32_e32", v(2), sp("vcc_lo")) - calc = ins("v_or3_b32", v(3), sp("vcc_lo"), sp("vcc_lo"), sp("vcc_lo")) - use = ins("s_bcnt1_i32_b64", s(8), s(6, 2)) - blocks = [[cmp_, copy, calc, use]] - got, writes = L.analyse(blocks, [[]]) - assert ("v", 2) in got[id(use)] and ("v", 3) in got[id(use)] - assert writes == {id(calc)} - - -def test_bfm64_and_half_kinds(): - # s_bfm_b64 produces a 64-bit lane mask (low half in s6, high half in s7). - use = ins("s_bcnt1_i32_b64", s(8), s(6, 2)) - got = L.analyse([[ins("s_bfm_b64", s(6, 2), imm(16), imm(8)), use]], [[]])[0][id(use)] - assert got == {6: L.MASK_LO, 7: L.MASK_HI} - # exec_lo / exec_hi preserve half identity on 32-bit copies. - got2 = L.analyse([[ins("s_mov_b32", s(6), sp("exec_lo")), ins("s_mov_b32", s(7), sp("exec_hi")), use]], [[]])[0][id(use)] - assert got2 == {6: L.MASK_LO, 7: L.MASK_HI} - # vcc_lo / vcc_hi map to MASK_LO / MASK_HI when vcc holds a lane mask, and None when vcc is data. - vcmp = ins("v_cmp_gt_u32_e32", sp("vcc_lo"), imm(16), v(0)) - got_vcc = L.analyse([[vcmp, ins("s_mov_b32", s(6), sp("vcc_lo")), ins("s_mov_b32", s(7), sp("vcc_hi")), use]], [[]])[0][id(use)] - assert got_vcc == {"vcc": L.MASK, 6: L.MASK_LO, 7: L.MASK_HI} - got_vcc_data = L.analyse([[ins("s_buffer_load_dword", sp("vcc_lo"), s(0, 4), imm(0)), - ins("s_mov_b32", s(6), sp("vcc_lo")), ins("s_mov_b32", s(7), sp("vcc_hi")), use]], [[]])[0][id(use)] - assert got_vcc_data == {} - # A separate write to vcc_hi ends vcc's life as a lane mask, so vcc_hi reads back as data. - got_vcc_hi = L.analyse([[vcmp, ins("s_mov_b32", sp("vcc_hi"), imm(0x1234)), - ins("s_mov_b32", s(7), sp("vcc_hi")), use]], [[]])[0][id(use)] - assert got_vcc_hi == {} - # Merging low half and high half yields generic MASK (unknown half -> keep both halves). - got3 = L.analyse([[ins("s_nop")], [ins("s_mov_b32", s(6), sp("exec_lo"))], - [ins("s_mov_b32", s(6), sp("exec_hi"))], [use]], [[1, 2], [3], [3], []])[0][id(use)] - assert got3 == {6: L.MASK} - - -def test_b64_mask_imm_and_include_either(): - use64 = ins("s_bcnt1_i32_b64", s(8), s(6, 2)) - use32 = ins("s_bcnt1_i32_b32", s(8), s(6)) - vcmp = ins("v_cmp_eq_u32_e32", sp("vcc"), imm(0), v(0)) - # 64-bit bitwise op of a lane mask with a non-0/-1 immediate stores a per-lane mask via mask_src/mask_dst. - got_and64 = L.analyse([[vcmp, ins("s_and_b64", s(6, 2), sp("vcc"), imm(0xFF)), use64]], [[]])[0][id(use64)] - assert got_and64 == {"vcc": L.MASK, 6: L.MASK_LO, 7: L.MASK_HI} - # 64-bit copy of a constant into vcc stores mask_src(imm) per lane into %vcc. - got_mov_vcc = L.analyse([[ins("s_mov_b64", sp("vcc"), imm(0x3F)), use64]], [[]])[0][id(use64)] - assert got_mov_vcc == {"vcc": L.MASK} - # Plain 64-bit data combined with an immediate stays data; 32-bit mask + non-0/-1 immediate into an SGPR stays data. - assert L.analyse([[ins("s_and_b64", s(6, 2), s(20, 2), imm(0xFF)), use64]], [[]])[0][id(use64)] == {} - assert L.analyse([[ins("s_and_b32", s(6), sp("exec_lo"), imm(1)), use32]], [[]])[0][id(use32)] == {} - # include_either=True exposes registers holding constant 0 / -1 (EITHER) alongside cur_masks. - blocks = [[ins("s_mov_b32", s(6), sp("exec_lo")), ins("s_mov_b32", s(7), imm(0)), use64]] - out, writes, either = L.analyse(blocks, [[]], include_either=True) - assert out[id(use64)] == {6: L.MASK_LO} - assert writes == set() - assert either[id(use64)] == {7} - - -def test_writelane_sdwa_dpp_swaps_stores_and_div_scale(): - use_s = ins("s_bcnt1_i32_b32", s(8), s(6)) - use_v = ins("v_readfirstlane_b32", s(8), v(5)) - mk = ins("v_cmp_eq_u32_e64", s(6), v(0), v(1)) - - # v_writelane_b32 writes one lane of v5, so v5 no longer holds a whole-VGPR mask ("v", 5), - # while the parked slot ("lane", 5, 0) reflects the written scalar operand. - wl_data = ins("v_writelane_b32", v(5), s(9), imm(0)) - got_wl = L.analyse([[mk, ins("v_or_b32_e32", v(5), s(6), s(6)), wl_data, use_v]], [[]])[0][id(use_v)] - assert ("v", 5) not in got_wl - wl_mask = ins("v_writelane_b32", v(5), s(6), imm(0)) - got_wl2 = L.analyse([[mk, ins("v_or_b32_e32", v(5), s(6), s(6)), wl_mask, use_v]], [[]])[0][id(use_v)] - assert ("v", 5) not in got_wl2 and ("lane", 5, 0) in got_wl2 - - # SDWA and DPP variants of VECTOR_BITWISE are not whole-dword per-lane mask computations: - # they must neither mark ("v", dst) nor enter mask_writes. - dpp_or = {"op": "v_or_b32_dpp", "args": [v(5), v(4), v(4)], "mods": ["row_shr:1", "row_mask:0x0"]} - sdwa_or = {"op": "v_or_b32_sdwa", "args": [v(5), s(6), s(6)], - "mods": ["dst_sel:BYTE_0", "dst_unused:UNUSED_PRESERVE", "src0_sel:BYTE_0", "src1_sel:BYTE_0"]} - dpp_mov = {"op": "v_mov_b32_dpp", "args": [v(5), v(4)], "mods": ["row_shr:1"]} - for op_ins in (dpp_or, sdwa_or, dpp_mov): - blk = [mk, ins("v_mov_b32_e32", v(4), s(6)), op_ins, use_v] - got, writes = L.analyse([blk], [[]]) - assert ("v", 5) not in got[id(use_v)], op_ins["op"] - assert id(op_ins) not in writes, op_ins["op"] - - # v_swap_b32 writes both operands, invalidating parked/VGPR masks in a[1] as well as a[0]. - got_swap = L.analyse([[mk, ins("v_writelane_b32", v(5), s(6), imm(0)), - ins("v_swap_b32_e32", v(4), v(5)), use_v]], [[]])[0][id(use_v)] - assert ("lane", 5, 0) not in got_swap and ("v", 5) not in got_swap - - # Relative-destination writes invalidate all registers at or above the base register. - for rel_op in ("v_movreld_b32_e32", "v_movrelsd_b32_e32", "v_movrelsd_2_b32_e32"): - got_rel = L.analyse([[mk, ins("v_writelane_b32", v(6), s(6), imm(0)), - ins("v_writelane_b32", v(3), s(6), imm(0)), - ins(rel_op, v(4), v(7)), use_v]], [[]])[0][id(use_v)] - assert ("lane", 6, 0) not in got_rel and ("lane", 3, 0) in got_rel, rel_op - got_swaprel = L.analyse([[mk, ins("v_writelane_b32", v(6), s(6), imm(0)), - ins("v_writelane_b32", v(2), s(6), imm(0)), - ins("v_swaprel_b32_e32", v(5), v(3)), use_v]], [[]])[0][id(use_v)] - assert ("lane", 6, 0) not in got_swaprel and ("lane", 2, 0) in got_swaprel - for srel_op in ("s_movreld_b32", "s_movreld_b64", "s_movrelsd_2_b32"): - got_srel = L.analyse([[ins("s_mov_b32", s(2), sp("exec_lo")), - ins("s_mov_b32", s(6), sp("exec_lo")), - ins(srel_op, s(4), s(8)), use_s]], [[]])[0][id(use_s)] - assert 6 not in got_srel and 2 in got_srel, srel_op - - # Store instructions, LDS-targeted buffer loads, and non-returning atomics do not write a[0]. - got_sstore = L.analyse([[mk, ins("s_store_dword", s(6), s(0, 2), imm(0)), - ins("s_buffer_store_dword", s(6), s(0, 4), imm(0)), use_s]], [[]])[0][id(use_s)] - assert 6 in got_sstore - for non_dst in ( - ins("global_store_dword", v(5), v(6), sp("off")), - ins("buffer_store_dword", v(5), v(6), s(0, 4), imm(0)), - ins("tbuffer_store_format_x", v(5), v(6), s(0, 4), imm(0)), - ins("flat_store_dword", v(5), v(6)), - ins("image_store", v(5), v(6), s(0, 8)), - ins("ds_write_b32", v(5), v(6)), - {"op": "buffer_load_dword", "args": [v(5), s(0, 4), imm(0)], "mods": ["offen", "lds"]}, - ins("global_atomic_add", v(5), v(6), sp("off")), - ins("buffer_atomic_add", v(5), v(6), s(0, 4), imm(0)), - ins("image_atomic_add", v(5), v(6), s(0, 8)), - ins("ds_add_u32", v(5), v(6)), - ): - got_keep = L.analyse([[mk, ins("v_writelane_b32", v(5), s(6), imm(0)), - non_dst, use_v]], [[]])[0][id(use_v)] - assert ("lane", 5, 0) in got_keep, non_dst["op"] - # Returning atomics (glc / _rtn) DO write a[0] and must still invalidate it. - for rtn_op in ( - {"op": "global_atomic_add", "args": [v(5), v(6), v(7), sp("off")], "mods": ["glc"]}, - {"op": "buffer_atomic_add", "args": [v(5), v(6), s(0, 4), imm(0)], "mods": ["glc"]}, - ins("ds_add_rtn_u32", v(5), v(6), v(7)), - ): - got_kill = L.analyse([[mk, ins("v_writelane_b32", v(5), s(6), imm(0)), - rtn_op, use_v]], [[]])[0][id(use_v)] - assert ("lane", 5, 0) not in got_kill, rtn_op["op"] - - # v_div_scale_f32 / v_div_scale_f64 write a per-lane scale mask to a[1]. - for ds_op in ("v_div_scale_f32", "v_div_scale_f64"): - got_ds = L.analyse([[ins(ds_op, v(0), s(6, 2), v(1), v(2), v(1)), use_s]], [[]])[0][id(use_s)] - assert got_ds == {6: L.MASK_LO, 7: L.MASK_HI}, ds_op - - - -def test_v_and_or_xnor_bfi_track_vector_masks(): - use = ins("s_and_b32", s(12), s(7), s(8)) - and_or = ins("v_and_or_b32", v(2), sp("vcc_lo"), sp("exec_lo"), imm(0)) - xnor = ins("v_xnor_b32", v(3), sp("vcc_lo"), sp("exec_lo")) - bfi = ins("v_bfi_b32", v(4), sp("vcc_lo"), sp("exec_lo"), imm(-1)) - mixed = ins("v_bfi_b32", v(5), sp("exec_lo"), sp("exec_hi"), imm(0)) - blocks = [[ - ins("v_cmp_eq_u32_e32", sp("vcc_lo"), v(0), v(1)), - and_or, - xnor, - bfi, - mixed, - ins("v_readfirstlane_b32", s(7), v(2)), - ins("v_readfirstlane_b32", s(8), v(3)), - ins("v_readfirstlane_b32", s(9), v(4)), - ins("v_readfirstlane_b32", s(10), v(5)), - use, - ]] - out, writes = L.analyse(blocks, [[]]) - for w in (and_or, xnor, bfi, mixed): - assert id(w) in writes, w["op"] - masks = out[id(use)] - assert masks.get(("v", 2)) == L.MASK_LO - assert masks.get(("v", 3)) == L.MASK_LO - assert masks.get(("v", 4)) == L.MASK_LO - assert masks.get(("v", 5)) == L.MASK - assert masks.get(7) == L.MASK_LO - assert masks.get(8) == L.MASK_LO - assert masks.get(9) == L.MASK_LO - assert masks.get(10) == L.MASK - # Negative controls: any non-mask or non-0/-1 constant operand keeps dst as plain data. - for bad in ( - ins("v_and_or_b32", v(6), sp("vcc_lo"), v(9), imm(0)), - ins("v_and_or_b32", v(6), sp("vcc_lo"), sp("exec_lo"), imm(5)), - ins("v_xnor_b32", v(6), sp("vcc_lo"), v(9)), - ins("v_bfi_b32", v(6), v(9), sp("exec_lo"), imm(0)), - ins("v_bfi_b32", v(6), sp("vcc_lo"), sp("exec_lo"), imm(3)), - ): - bad_use = ins("s_and_b32", s(12), s(7), sp("exec_lo")) - out, writes = L.analyse([[ - ins("v_cmp_eq_u32_e32", sp("vcc_lo"), v(0), v(1)), - bad, - ins("v_readfirstlane_b32", s(7), v(6)), - bad_use, - ]], [[]]) - assert id(bad) not in writes, bad["op"] - assert 7 not in out[id(bad_use)] and ("v", 6) not in out[id(bad_use)], bad["op"] - -def test_wave32_vcc_hi_isolation(): - use = ins("s_nop", imm(0)) - vcmp_lo = ins("v_cmp_eq_u32_e64", sp("vcc_lo"), v(0), imm(1)) - vcmp_hi = ins("v_cmp_lt_f32_e64", sp("vcc_hi"), v(0), v(1)) - - # In wave32, writing plain data to vcc_hi does not clear vcc (vcc_lo), and vice versa. - m_data_hi = L.analyse( - [[vcmp_lo, vcmp_hi, ins("s_mov_b32", sp("vcc_hi"), imm(0x5)), use]], - [[]], - wave64=False, - )[0][id(use)] - assert m_data_hi == {"vcc": L.MASK} - - m_data_lo = L.analyse( - [[vcmp_lo, vcmp_hi, ins("s_mov_b32", sp("vcc_lo"), imm(0x5)), use]], - [[]], - wave64=False, - )[0][id(use)] - assert m_data_lo == {"vcc_hi": L.MASK} - - # v_add_co_u32 / v_mad_u64_u32 / s_and_saveexec_b32 / s_wqm_b32 writing vcc_hi in wave32 produce a vcc_hi mask - # without clobbering vcc, and s_mov_b32 vcc_hi, s_mask vs s_mov_b32 s_dst, vcc_hi propagate it. - for hi_prod in ( - ins("v_add_co_u32", v(2), sp("vcc_hi"), v(0), v(1)), - ins("v_mad_u64_u32", {"k": "vgpr", "r": 2, "n": 2}, sp("vcc_hi"), v(0), v(1), {"k": "vgpr", "r": 4, "n": 2}), - ins("s_and_saveexec_b32", sp("vcc_hi"), sp("vcc")), - ins("s_wqm_b32", sp("vcc_hi"), sp("vcc_lo")), - ): - got = L.analyse([[vcmp_lo, hi_prod, ins("s_mov_b32", s(4), sp("vcc_hi")), use]], [[]], wave64=False)[0][id(use)] - assert got == {"vcc": L.MASK, "vcc_hi": L.MASK, 4: L.MASK}, hi_prod["op"] - - # CFG join: mask on one branch, EITHER (0/-1) on the other preserves vcc_hi as MASK in wave32; - # mask vs plain data drops vcc_hi while keeping vcc. - out_join = L.analyse( - [[vcmp_lo], [vcmp_hi], [ins("s_mov_b32", sp("vcc_hi"), imm(-1))], [use]], - [[1, 2], [3], [3], []], - wave64=False, - )[0][id(use)] - assert out_join == {"vcc": L.MASK, "vcc_hi": L.MASK} - - out_drop = L.analyse( - [[vcmp_lo], [vcmp_hi], [ins("s_mov_b32", sp("vcc_hi"), imm(0x5))], [use]], - [[1, 2], [3], [3], []], - wave64=False, - )[0][id(use)] - assert out_drop == {"vcc": L.MASK} - - # In wave64, plain-data writes to vcc_hi still clear vcc as a single 64-bit mask. - out_w64 = L.analyse( - [[ins("v_cmp_lt_u32_e64", sp("vcc"), v(0), imm(32)), - ins("s_mov_b32", sp("vcc_hi"), imm(0x5)), - use]], - [[]], - wave64=True, - )[0][id(use)] - assert out_w64 == {} - - -if __name__ == "__main__": - test_straight_line() - test_joins() - test_parked_masks() - test_masks_through_a_vgpr() - test_vmov_mask_copy_is_exec_gated() - test_bfm64_and_half_kinds() - test_b64_mask_imm_and_include_either() - test_writelane_sdwa_dpp_swaps_stores_and_div_scale() - test_v_and_or_xnor_bfi_track_vector_masks() - test_wave32_vcc_hi_isolation() - print("ok") diff --git a/tests/test_lds_fuzz.py b/tests/test_lds_fuzz.py deleted file mode 100644 index 3698a1614..000000000 --- a/tests/test_lds_fuzz.py +++ /dev/null @@ -1,428 +0,0 @@ -"""tools/lds_fuzz.py without a GPU: the reference model's instruction semantics and the generator's guarantees -(every access in bounds, no two lanes racing on the same bytes).""" -from pathlib import Path -import struct -import sys -import unittest - -sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "tools")) -import lds_fuzz as f - - -class Swizzle(unittest.TestCase): - # Offsets as llvm-mc 23 (-mcpu=gfx1013) encodes the swizzle() macros of ds_swizzle_b32. - def test_quad_perm(self): - offset = 0x801B # swizzle(QUAD_PERM,3,2,1,0) - self.assertEqual([f.swizzle_src(lane, offset) for lane in range(8)], [3, 2, 1, 0, 7, 6, 5, 4]) - - def test_bitmask_or(self): - self.assertEqual(f.swizzle_src(3, 0x020F), 19) # swizzle(BITMASK_PERM,"1pppp"): bit 4 set - self.assertEqual(f.swizzle_src(19, 0x000F), 3) # swizzle(BITMASK_PERM,"0pppp"): bit 4 cleared - - def test_reverse_and_broadcast(self): - self.assertEqual([f.swizzle_src(lane, 0x1C1F) for lane in range(8)], [7, 6, 5, 4, 3, 2, 1, 0]) # REVERSE,8 - self.assertEqual({f.swizzle_src(lane, 0x0078) for lane in range(8, 16)}, {11}) # BROADCAST,8,3 - - def test_bitmask_stays_in_its_32_lane_group(self): - self.assertEqual(f.swizzle_src(32 + 3, 0x1C1F), 32 + (3 ^ 7)) # REVERSE,8 in the upper group - self.assertEqual(f.swizzle_src(32 + 3, 0x7C1F), 32 + (3 ^ 31)) # REVERSE,32: still lanes 32-63 - - -class Atomics(unittest.TestCase): - def test_signed_and_unsigned_min_max(self): - neg = 0xFFFFFFFF - self.assertEqual(f.atomic("min_i32", 1, neg), neg) - self.assertEqual(f.atomic("min_u32", 1, neg), 1) - self.assertEqual(f.atomic("max_i32", 1, neg), 1) - self.assertEqual(f.atomic("max_u32", 1, neg), neg) - - def test_wrapping_add_sub(self): - self.assertEqual(f.atomic("add", 0xFFFFFFFF, 2), 1) - self.assertEqual(f.atomic("sub", 1, 2), 0xFFFFFFFF) - - -class Generator(unittest.TestCase): - def programs(self): - return f.programs(seed=11, count=60, waves=(64, 32)) - - def test_deterministic(self): - a, b = f.Program(3, 5, 64), f.Program(3, 5, 64) - self.assertEqual(a.asm(), b.asm()) - self.assertEqual(a.model(), b.model()) - - def test_accesses_in_bounds_and_race_free(self): - for p in self.programs(): - for op in p.ops: - if "addr" not in op: - continue - stride, base, off = op["addr"] - if op["kind"] in ("read2", "write2", "wrxchg2"): - unit = 256 if op["st64"] else 4 - spans = [[(t * stride + base + o * unit, 4) for o in (op["o0"], op["o1"])] - for t in range(f.THREADS)] - else: - size = {"read": lambda: f.READS[op["name"]][0], "write": lambda: f.WRITES[op["name"]][0]}.get( - op["kind"], lambda: 4)() - spans = [[(t * stride + base + off, size)] for t in range(f.THREADS)] - for ss in spans: - for a, n in ss: - self.assertTrue(0 <= a and a + n <= f.LDS_BYTES, (p.name, op)) - if op["kind"] in ("write", "write2", "wrxchg2", "atomic_rtn", "wrxchg", "cmpst"): - self.assertTrue(p.disjoint(spans), (p.name, op)) - - def test_only_order_independent_atomics_share_addresses(self): - for p in self.programs(): - for op in p.ops: - if op["kind"] == "atomic": - self.assertIn(op["op"], f.SHARED_ATOMICS) - - def test_no_exec_keeps_the_rest_of_the_program(self): - a, b = f.Program(1, 32, 32), f.Program(1, 32, 32, no_exec=("bpermute",)) - self.assertEqual(len(a.ops), len(b.ops)) - for x, y in zip(a.ops, b.ops): - if x["kind"] == "bpermute": - self.assertIsNone(y["exec"]) - else: - self.assertEqual(x, y) - - def test_permute_is_generated_and_no_exec_clears_only_permute(self): - self.assertIn("permute", f.EXEC_KINDS) - found = 0 - for idx in range(40): - a = f.Program(1, idx, 64, permute=True) - b = f.Program(1, idx, 64, no_exec=("permute",), permute=True) - self.assertEqual(len(a.ops), len(b.ops)) - for x, y in zip(a.ops, b.ops): - if x["kind"] == "permute": - if x["exec"] is not None: - found += 1 - self.assertIsNone(y["exec"]) - self.assertEqual({k: v for k, v in x.items() if k not in ("exec", "hyp")}, - {k: v for k, v in y.items() if k not in ("exec", "hyp")}) - else: - self.assertEqual(x, y) - self.assertGreater(found, 0, "expected at least one permute op with non-None exec mask") - - - def test_wrxchg2_is_generated_and_may_alias_the_data(self): - self.assertIn("wrxchg2", f.EXEC_KINDS) - found = [op for idx in range(200) for op in f.Program(2, idx, 64).ops if op["kind"] == "wrxchg2"] - self.assertTrue(found, "expected the generator to emit ds_wrxchg2") - for op in found: - self.assertLessEqual(op["dst"] + 1, f.HW_VGPRS - 1) - self.assertTrue(any(op["dst"] in (op["src0"], op["src1"]) for op in found), - "expected some ops to alias vdst with the data pair") - - -class Wrxchg2(unittest.TestCase): - """The two-dword exchange: element-scaled offsets, a 64-element st64 step, and data0 back on a repeated offset.""" - - def model(self, threads=8, **op): - p = f.Program(1, 0, 32) - p.threads = threads - base = {"kind": "wrxchg2", "addr": (0, 0, 0), "dst": 20, "src0": 22, "src1": 23, "exec": None, - "st64": False, "o0": 0, "o1": 0} - base.update(op) - p.ops = [base] - return p, *p.model() - - @staticmethod - def init_lds(p, dword): - return ((dword * p.lds_mul) & f.M32) ^ p.lds_xor - - @staticmethod - def init_reg(p, t, r): - k, c = p.pool_init[r] - return ((t * k) & f.M32) ^ c - - @staticmethod - def word(lds, dword): - return struct.unpack_from(" 0. - for t in (0, 1, 2, 3, 4, 6, 7): - self.assertEqual(regs[t][21], 0) - # Low half: inactive lanes keep their original v21. - for t in (8, 15, 31): - self.assertEqual(regs[t][21], init_regs[t][21]) - # High half: target lane 32+5=37 is INACTIVE, so it keeps its original v21 even though 32,35,40 targeted it. - self.assertEqual(regs[37][21], init_regs[37][21]) - # High half: active lanes 32, 35, 40 receive nobody -> 0. - for t in (32, 35, 40): - self.assertEqual(regs[t][21], 0) - self.assertIn("ds_permute_b32 v21, v6, v20 offset:0", p.asm()) - - with f.perturbed("permute_lowest_wins"): - bad_regs, _ = p.model() - self.assertEqual(bad_regs[5][21], init_regs[0][20]) - - def test_permute_half_isolation_and_offset(self): - # Identity + offset:8 (+2 lanes) mod 32 within each 32-lane half, all lanes active. - p = f.Program(2, 1, 64) - p.ops = [{"kind": "permute", "mul": 1, "add": 0, "offset": 8, "src": 20, "dst": 22, "exec": None}] - base = f.Program(2, 1, 64) - base.ops = [] - init_regs, _ = base.model() - regs, _ = p.model() - for t in range(64): - src_lane = (t & ~31) | ((t - 2) & 31) - self.assertEqual(regs[t][22], init_regs[src_lane][20]) - - def test_permute_wave64_cross_models_the_measured_gfx12_behaviour(self): - # the same program under the perturbation that mirrors what GFX12 measures: +2 lanes mod 64, across halves - p = f.Program(2, 1, 64) - p.ops = [{"kind": "permute", "mul": 1, "add": 0, "offset": 8, "src": 20, "dst": 22, "exec": None}] - base = f.Program(2, 1, 64) - base.ops = [] - init_regs, _ = base.model() - with f.perturbed("permute_wave64_cross"): - regs, _ = p.model() - for t in range(64): - src_lane = (t & ~63) | ((t - 2) & 63) - self.assertEqual(regs[t][22], init_regs[src_lane][20]) - - def test_d16_hi_read_keeps_the_low_half(self): - p = f.Program(1, 0, 64) - p.ops = [{"kind": "read", "name": "ds_read_u16_d16_hi", "addr": (0, 0, 0), "dst": 20, "exec": None}] - before = f.Program(1, 0, 64) - before.ops = [] - old = before.model()[0][0][20] - regs, lds = p.model() - self.assertEqual(regs[0][20], (old & 0xFFFF) | (struct.unpack_from(" -3" - status, out = self.run_main(gpu) - self.assertEqual(status, 2, out) - self.assertIn("harness errors", out) - - def test_short_dump_is_a_harness_error(self): - def gpu(_p, _spv, _build, _entry, _emulate, dump): - dump.write_bytes(bytes(256)) - return 0, "" - status, out = self.run_main(gpu) - self.assertEqual(status, 2, out) - self.assertIn("256 of", out) - - UNPINNED = "device: llvmpipe (LLVM 20.1.2, 256 bits) (subgroup 8..8)\ncompute subgroup size: 32 not available" - - def wrong_dump(self, msg): - """A run whose words are all zero, as a narrower subgroup leaves cross-lane results.""" - def gpu(p, _spv, _build, _entry, _emulate, dump): - dump.write_bytes(bytes(4 * p.out_words)) - return 0, msg - return gpu - - def test_unpinned_wave32_is_a_skip_not_a_mismatch(self): - status, out = self.run_main(self.wrong_dump(self.UNPINNED), ("--wave", "32")) - self.assertEqual(status, 2, out) # nothing ran - self.assertNotIn("MISMATCH", out) - self.assertIn("2 skipped", out) - self.assertIn("can't run it at 32 lanes", out) - - def test_unpinned_wave32_warning_does_not_hide_a_later_harness_failure(self) -> None: - passing = iter((False, True)) - - def gpu(p: f.Program, _spv: Path, _build: str, _entry: dict[str, object], - _emulate: bool, dump: Path) -> tuple[int, str]: - if next(passing): - self.correct_dump(p, dump) - return 0, "compute subgroup size: 32" - return 1, self.UNPINNED + "\nFAILED vkQueueSubmit -> -4" - - status, out = self.run_main(gpu, ("--wave", "32")) - self.assertEqual(status, 2, out) - self.assertIn("FAILED vkQueueSubmit", out) - self.assertIn("1/1 programs that ran match", out) - self.assertIn("1 harness errors", out) - self.assertIn("0 skipped", out) - - def test_pinned_wave32_is_still_compared(self): - status, out = self.run_main(self.wrong_dump("compute subgroup size: 32"), ("--wave", "32")) - self.assertEqual(status, 1, out) - self.assertIn("MISMATCH", out) - - def test_emulated_wave64_is_compared_at_any_subgroup_size(self): - # --wave64-emulate output uses no subgroup operations, so llvmpipe's 8 lanes are a real test of it. - status, out = self.run_main(self.wrong_dump(self.UNPINNED), ("--emulate",)) - self.assertEqual(status, 1, out) - self.assertIn("MISMATCH", out) - self.assertIn("0 skipped", out) - - -class UnpinnedSubgroup(unittest.TestCase): - """compute_fixture.unpinned_subgroup reads vk_compute_test's VKC_SUBGROUP_SIZE line.""" - - def test_not_available_gives_the_size(self): - from compute_fixture import unpinned_subgroup - self.assertEqual(unpinned_subgroup("device: X (subgroup 8..8)\ncompute subgroup size: 32 not available\n"), 32) - - def test_pinned_or_missing_line_gives_none(self): - from compute_fixture import unpinned_subgroup - self.assertIsNone(unpinned_subgroup("device: X (subgroup 32..64)\ncompute subgroup size: 32\n")) - self.assertIsNone(unpinned_subgroup("device: X (subgroup 32..32)\n1 groups x 64: 0 mismatches\n")) - self.assertIsNone(unpinned_subgroup("")) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/test_lds_fuzz_cli.py b/tests/test_lds_fuzz_cli.py deleted file mode 100644 index bd46a60c5..000000000 --- a/tests/test_lds_fuzz_cli.py +++ /dev/null @@ -1,147 +0,0 @@ -import contextlib -import io -import os -import subprocess -import sys -import tempfile -import unittest -from pathlib import Path -from unittest.mock import patch - -sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "tools")) -import lds_fuzz as f - - -class CLIValidation(unittest.TestCase): - def test_zero_programs_must_fail(self): - args = ["lds_fuzz.py", "--programs", "0", "--model-only"] - with patch.object(sys, "argv", args): - with self.assertRaises(SystemExit) as result: - f.main() - self.assertEqual(result.exception.code, 2) - - def test_malformed_show_must_fail(self): - args = ["lds_fuzz.py", "--show", "invalido"] - with patch.object(sys, "argv", args): - with self.assertRaises(SystemExit) as result: - f.main() - self.assertEqual(result.exception.code, 2) - - def test_invalid_counts(self): - for option, value in [ - ("--programs", "0"), - ("--programs", "-1"), - ("--max-report", "0"), - ("--max-report", "-2"), - ]: - with self.subTest(option=option, value=value): - args = ["lds_fuzz.py", option, value, "--model-only"] - with patch.object(sys, "argv", args): - with contextlib.redirect_stderr(io.StringIO()): - with self.assertRaises(SystemExit) as result: - f.main() - self.assertEqual(result.exception.code, 2) - - def test_invalid_show_formats(self): - for value in [ - "invalido", "1", "1:2:3:4", - "1:-1", "1:0:16", "a:0", - "1:b", "1:0:invalido", "1:0:", - ]: - with self.subTest(value=value): - with patch.object(sys, "argv", ["lds_fuzz.py", "--show", value]): - with contextlib.redirect_stderr(io.StringIO()): - with self.assertRaises(SystemExit) as result: - f.main() - self.assertEqual(result.exception.code, 2) - - def test_valid_show_formats(self): - for value, seed, index, wave in [ - ("7:1", 7, 1, 64), - ("7:1:32", 7, 1, 32), - ("7:1:64", 7, 1, 64), - ]: - with self.subTest(value=value): - with patch.object(sys, "argv", ["lds_fuzz.py", "--show", value]): - with patch.object(f, "show") as show_mock: - self.assertEqual(f.main(), 0) - show_mock.assert_called_once_with(seed, index, wave, ()) - - def test_positive_count_boundary(self): - args = [ - "lds_fuzz.py", "--programs", "1", - "--max-report", "1", "--wave", "32", "--model-only", - ] - output = io.StringIO() - with patch.object(sys, "argv", args): - with contextlib.redirect_stdout(output): - self.assertEqual(f.main(), 0) - self.assertIn("1 programs generated and modelled", output.getvalue()) - - def test_pc_tail_ubo_forwarded_to_translator_and_vk_compute_test(self): - with tempfile.TemporaryDirectory() as tmp_str: - tmp = Path(tmp_str) - cmds = [] - - def fake_run(cmd, **kw): - cmds.append((list(cmd), kw.get("env"))) - (tmp / "spirv").mkdir(parents=True, exist_ok=True) - (tmp / "spirv" / "index.json").write_text("{}", encoding="utf-8") - return subprocess.CompletedProcess(cmd, 0, "", "") - - with patch.object(f.mc_command, "mc_command", return_value=["llvm-mc"]), \ - patch.object(f.subprocess, "run", side_effect=fake_run): - f.translate([], tmp, False) - f.translate([], tmp, False, pc_tail=True) - self.assertNotIn("--pc-tail-ubo", cmds[0][0]) - self.assertIn("--pc-tail-ubo", cmds[1][0]) - - build = tmp / "build" - build.mkdir() - (build / ("vk_compute_test" + (".exe" if os.name == "nt" else ""))).touch() - prog = f.Program(1, 0, 32) - clean_env = {k: v for k, v in os.environ.items() if k != "LEONIDA_PC_TAIL_UBO"} - with patch.dict(os.environ, clean_env, clear=True), \ - patch.object(f.subprocess, "run", side_effect=fake_run): - f.run_gpu(prog, tmp / "a.spv", str(build), {}, False, tmp / "a.bin") - f.run_gpu(prog, tmp / "a.spv", str(build), {}, False, tmp / "a.bin", pc_tail=True) - self.assertNotIn("LEONIDA_PC_TAIL_UBO", cmds[2][1]) - self.assertEqual(cmds[3][1]["LEONIDA_PC_TAIL_UBO"], "1") - - def test_pc_tail_ubo_from_flag_or_env(self): - with tempfile.TemporaryDirectory() as tmp_str: - tmp = Path(tmp_str) - for extra, env_val, want in ( - ([], "", False), - (["--pc-tail-ubo"], "", True), - ([], "1", True), - ([], "yes", True), - ([], "0", False), - ): - with self.subTest(extra=extra, env_val=env_val): - seen_t, seen_g = [], [] - - def fake_translate(progs, work, _emulate, pc_tail=False): - seen_t.append(pc_tail) - (work / "spirv").mkdir(parents=True, exist_ok=True) - for p in progs: - (work / "spirv" / (p.name + ".spv")).touch() - return {p.name: {} for p in progs} - - def fake_run_gpu(p, _spv, _build, _entry, _emulate, dump, pc_tail=False): - seen_g.append(pc_tail) - return 77, "unsupported: test" - - argv = ["lds_fuzz.py", "--programs", "1", "--wave", "32", "--work", str(tmp), *extra] - with patch.dict(os.environ, {"LEONIDA_PC_TAIL_UBO": env_val}), \ - patch.object(sys, "argv", argv), \ - patch.object(f, "translate", side_effect=fake_translate), \ - patch.object(f, "run_gpu", side_effect=fake_run_gpu), \ - contextlib.redirect_stdout(io.StringIO()): - f.main() - self.assertEqual(seen_t, [want]) - self.assertEqual(seen_g, [want]) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/test_lds_fuzz_hw.py b/tests/test_lds_fuzz_hw.py deleted file mode 100644 index ce83a23fc..000000000 --- a/tests/test_lds_fuzz_hw.py +++ /dev/null @@ -1,516 +0,0 @@ -"""tools/lds_fuzz.py --oracle hw without a GPU: the native kernel text (GFX11 mnemonics, operand order, LDS size, -entry EXEC), the op-mix options, the deliberate model errors and the exit-77 contract. The last test runs on the -hardware when the oracle tools are present and is skipped otherwise. Standard library only.""" -import contextlib -import io -import os -import struct -import sys -import unittest -from pathlib import Path -from unittest.mock import patch - -TOOLS = Path(__file__).resolve().parents[1] / "tools" -sys.path.insert(0, str(TOOLS)) -import lds_fuzz as f # noqa: E402 -from hw_oracle import asm, runner # noqa: E402 - - -def lines(p, arch="gfx1150"): - return p.hw_lines(arch) - - -class DsSpelling(unittest.TestCase): - def test_gfx11_renames(self): - for old, new in {"ds_read_b32": "ds_load_b32", "ds_read_u8_d16_hi": "ds_load_u8_d16_hi", - "ds_read2_b32": "ds_load_2addr_b32", "ds_read2st64_b32": "ds_load_2addr_stride64_b32", - "ds_write_b128": "ds_store_b128", "ds_write_b8_d16_hi": "ds_store_b8_d16_hi", - "ds_write2_b32": "ds_store_2addr_b32", "ds_write2st64_b32": "ds_store_2addr_stride64_b32", - "ds_wrxchg_rtn_b32": "ds_storexchg_rtn_b32", "ds_cmpst_rtn_b32": "ds_cmpstore_rtn_b32"}.items(): - self.assertEqual(asm.ds_mnemonic(old, "gfx1150"), new) - self.assertEqual(asm.ds_mnemonic(old, "gfx1201"), new) - self.assertEqual(asm.ds_mnemonic(old, "gfx1030"), old) - - def test_unrenamed_ops_keep_their_names(self): - for op in ("ds_add_u32", "ds_max_rtn_i32", "ds_and_b32", "ds_swizzle_b32", "ds_bpermute_b32", - "ds_permute_b32", "v_add_nc_u32_e32", "s_barrier"): - self.assertEqual(asm.ds_mnemonic(op, "gfx1150"), op) - - def test_cmpstore_takes_the_store_value_first_on_gfx11(self): - line = "ds_cmpst_rtn_b32 v22, v6, v28, v35 offset:12" # vdst, vaddr, compare, store - self.assertEqual(asm.ds_line(line, "gfx1150"), "ds_cmpstore_rtn_b32 v22, v6, v35, v28 offset:12") - self.assertEqual(asm.ds_line(line, "gfx1201"), "ds_cmpstore_rtn_b32 v22, v6, v35, v28 offset:12") - self.assertEqual(asm.ds_line(line, "gfx1030"), line) - nortn = "ds_cmpst_b32 v6, v28, v35" # vaddr, compare, store - for arch in ("gfx1150", "gfx1201"): # measured on gfx1100 and gfx1201 - self.assertEqual(asm.ds_line(nortn, arch), "ds_cmpstore_b32 v6, v35, v28") - self.assertEqual(asm.ds_line(nortn, "gfx1030"), nortn) - with self.assertRaises(ValueError): - asm.ds_line("ds_cmpst_rtn_b32 v22, v6, 5", "gfx1150") - - def test_gfx12_spells_the_barrier_and_the_lds_wait_its_own_way(self): - self.assertEqual(asm.sync_lines("s_barrier", "gfx1201"), ["s_barrier_signal -1", "s_barrier_wait -1"]) - self.assertEqual(asm.sync_lines("s_waitcnt lgkmcnt(0)", "gfx1201"), ["s_wait_dscnt 0"]) - for arch in ("gfx1030", "gfx1150"): - for line in ("s_barrier", "s_waitcnt lgkmcnt(0)"): - self.assertEqual(asm.sync_lines(line, arch), [line]) - for line in ("s_waitcnt vmcnt(0)", "ds_bpermute_b32 v1, v2, v3", "s_endpgm"): - self.assertEqual(asm.sync_lines(line, "gfx1201"), [line]) - - def test_kernel_carries_its_lds_size_and_registers(self): - k = asm.Kernel(["s_endpgm"], 64, 64, 8, raw=True, lds=4096, vgprs=40) - text, names, _ = asm.module_text([k, asm.Kernel(["s_endpgm"], 64, 64, 8, raw=True)], "gfx1150", wave=64) - self.assertIn(".amdhsa_group_segment_fixed_size 4096", text) - self.assertIn(".amdhsa_group_segment_fixed_size 0", text) - self.assertIn(".group_segment_fixed_size: 4096", text) - self.assertIn(".amdhsa_next_free_vgpr 40", text) - self.assertIn(".vgpr_count: 40", text) - for bad in ({"lds": 6}, {"lds": 1 << 20}, {"vgprs": 0}): - with self.assertRaises(ValueError): - asm.Kernel([], **bad) - - -class Native(unittest.TestCase): - def test_gfx11_kernel_body(self): - p = f.Program(1, 4, 64) - body = lines(p) - self.assertEqual(body[0], "s_mov_b64 s[10:11], exec") - self.assertTrue(any(ln.startswith("ds_load_b32") for ln in body)) - self.assertTrue(any(ln.startswith("ds_store_b32") for ln in body)) - self.assertFalse(any(ln.startswith(("buffer_", "ds_read", "ds_write")) for ln in body), body) - stores = [ln for ln in body if ln.startswith("global_store_b32")] - self.assertEqual(len(stores), len(f.POOL) + f.LDS_DWORDS // 64) - self.assertTrue(all(ln.endswith("s[2:3]") or "s[2:3] offset:" in ln for ln in stores)) - self.assertEqual(body[-1], "s_endpgm") - self.assertNotIn("s_mov_b64 exec, -1", body) - - def test_wave32_saves_exec_lo_only(self): - body = lines(f.Program(1, 4, 32)) - self.assertEqual(body[0], "s_mov_b32 s10, exec_lo") - self.assertNotIn("exec_hi", " ".join(body)) - restore = [ln for ln in body if ln.startswith("s_mov_b32 exec_lo, s10")] - masked = [op for op in f.Program(1, 4, 32).ops if op["exec"] is not None] - self.assertEqual(len(restore), len(masked)) - - def test_gfx10_spellings(self): - body = lines(f.Program(1, 4, 64), "gfx1030") - self.assertTrue(any(ln.startswith("global_store_dword") for ln in body)) - self.assertTrue(any(ln.startswith("ds_read_b32") for ln in body)) - self.assertFalse(any(ln.startswith("ds_load") for ln in body)) - - def test_cmpst_text_per_architecture(self): - p = f.Program(1, 0, 64) - p.ops = [{"kind": "cmpst", "addr": (4, 0, 0), "src": 20, "src2": 21, "dst": 22, "exec": None, "cmp_hit": False}] - self.assertIn("ds_cmpstore_rtn_b32 v22, v6, v21, v20 offset:0", lines(p)) - self.assertIn("ds_cmpst_rtn_b32 v22, v6, v20, v21 offset:0", lines(p, "gfx1030")) - - def test_translator_text_is_unchanged(self): - text = f.Program(1, 4, 64).asm() - self.assertIn("buffer_store_dword v20, v6, s[0:3], 0 offen offset:0", text) - self.assertIn("s_mov_b64 exec, -1", text) - self.assertIn("; group: 64,1,1", text) - - def test_partial_wave_exec_masks_stay_inside_the_group(self): - p = f.Program(1, 0, 64, threads=32) - self.assertTrue(p.partial_wave) - self.assertEqual(p.asm_exec(0xFFFFFFFFFFFFFFFF, True), ["s_mov_b32 exec_lo, 0xffffffff", "s_mov_b32 exec_hi, 0x0"]) - p64 = f.Program(1, 0, 64) - self.assertEqual(p64.asm_exec(0xFFFFFFFFFFFFFFFF, True), ["s_mov_b32 exec_lo, 0xffffffff", - "s_mov_b32 exec_hi, 0xffffffff"]) - - -class OpMix(unittest.TestCase): - def test_defaults_do_not_change_the_programs(self): - a, b = f.Program(5, 7, 32), f.Program(5, 7, 32, threads=64, permute=False, swizzle_exec=False) - self.assertEqual((a.name, a.asm(), a.ops), (b.name, b.asm(), b.ops)) - self.assertEqual(a.name, "cs_ldsfuzz_s5_7_w32") - self.assertFalse(a.hyp_ops) - self.assertTrue(all(op["kind"] not in ("permute",) for op in a.ops)) - - def test_options_change_the_name_and_the_draws(self): - names = {f.Program(5, 7, 64, **kw).name for kw in ({}, {"permute": True}, {"swizzle_exec": True}, - {"threads": 128})} - self.assertEqual(len(names), 4) - - def test_permute_programs_carry_a_hypothesis(self): - progs = f.programs(3, 40, (64, 32), permute=True) - perm = [p for p in progs if any(op["kind"] == "permute" for op in p.ops)] - self.assertTrue(perm) - parities = set() - for p in perm: - for i, op in enumerate(p.ops): - self.assertEqual(i in p.hyp_ops, op["kind"] == "permute") - if op["kind"] == "permute": - parities.add(op["mul"] % 2) - self.assertEqual(parities, {0, 1}) # generates both colliding and bijective multipliers - - def test_swizzle_exec_hypothesis_only_under_a_mask(self): - progs = f.programs(3, 60, (32,), swizzle_exec=True) - swz = [op for p in progs for op in p.ops if op["kind"] == "swizzle"] - self.assertTrue(any(op["exec"] is not None for op in swz)) - for op in swz: - self.assertEqual("hyp" in op, op["exec"] is not None) - - def test_group_sizes_accesses_stay_in_bounds_and_race_free(self): - for threads in (32, 128, 256, "mix"): - for p in f.programs(4, 25, (64, 32), threads=threads, permute=True, swizzle_exec=True): - self.assertIn(p.threads, f.GROUP_SIZES) - self.assertEqual(p.out_words, p.threads * len(f.POOL) + f.LDS_DWORDS) - for op in p.ops: - if "addr" not in op or op["kind"] in ("read", "read2", "atomic"): - continue - stride, base, off = op["addr"] - unit = (256 if op.get("st64") else 4) - offs = (op["o0"] * unit, op["o1"] * unit) if op["kind"] == "write2" else (off,) - size = f.WRITES[op["name"]][0] if op["kind"] == "write" else 4 - spans = [[(t * stride + base + o, size) for o in offs] for t in range(p.threads)] - self.assertTrue(p.disjoint(spans), (p.name, op)) - - def test_bad_group_sizes(self): - for bad in (0, 48, 100, 2048, "x"): - with self.assertRaises(ValueError): - f.Program(1, 0, 64, threads=bad) - - def test_bpermute_and_permute_stay_in_their_32_lane_group_in_big_groups(self): - p = f.Program(1, 0, 32, threads=128) - p.ops = [{"kind": "bpermute", "mul": 1, "add": 9, "offset": 0, "src": 20, "dst": 21, "exec": None}, - {"kind": "permute", "mul": 3, "add": 5, "offset": 0, "src": 22, "dst": 23, "exec": None}] - regs, _ = p.model() - init = f.Program(1, 0, 32, threads=128) - init.ops = [] - r0 = init.model()[0] - for t in range(128): - self.assertEqual(regs[t][21], r0[(t & ~31) | ((t + 9) & 31)][20]) - self.assertEqual(sorted(regs[t][23] for t in range(32, 64)), sorted(r0[t][22] for t in range(32, 64))) - - def test_permute_model(self): - p = f.Program(1, 0, 32) - p.ops = [{"kind": "permute", "mul": 1, "add": 1, "offset": 0, "src": 20, "dst": 21, - "exec": 0x0000FFFF, "hyp": "x"}] - regs, _ = p.model() - init = f.Program(1, 0, 32) - init.ops = [] - r0 = init.model()[0] - for t in range(64): # lane L sends to lane L + 1 of its wave; lanes 16..31 are off - lane = t & 31 - if lane >= 16: - self.assertEqual(regs[t][21], r0[t][21]) # off lanes keep their value - else: - self.assertEqual(regs[t][21], 0 if lane == 0 else r0[t - 1][20]) # lane 0 gets nothing - - def test_swizzle_under_exec_reads_zero_from_an_off_lane(self): - p = f.Program(1, 0, 32) - p.ops = [{"kind": "swizzle", "offset": 0x8000 | 0b00011011, "src": 20, "dst": 21, # quad perm 3,2,1,0 - "exec": 0x7, "hyp": "x"}] - regs, _ = p.model() - init = f.Program(1, 0, 32) - init.ops = [] - r0 = init.model()[0] - self.assertEqual([regs[t][21] for t in range(3)], [0, r0[2][20], r0[1][20]]) # lane 0 reads lane 3 (off) - self.assertEqual(regs[3][21], r0[3][21]) - - -class Perturbations(unittest.TestCase): - """Each deliberate error changes the model's result on a program that uses the op, so the comparison can fail.""" - - def test_every_perturbation_is_visible_on_some_program(self): - progs = f.programs(1, 150, (64, 32), permute=True, swizzle_exec=True) - for name, (fam, _) in f.PERTURBATIONS.items(): - changed = 0 - for p in progs: - if not any(f.op_family(op) == fam or f.op_family(op).startswith(fam + "_") or - f.op_family(op).endswith("_" + fam) for op in p.ops): - continue - want = p.model() - with f.perturbed(name): - got = p.model() - changed += want[0] != got[0] or want[1] != got[1] - self.assertGreater(changed, 0, f"{name} changes nothing on 300 programs") - - def test_perturbed_restores_the_model(self): - p = f.Program(1, 3, 64) - before = p.model() - with f.perturbed("cmpst_swap", "max_i32_unsigned"): - self.assertIn("cmpst_swap", f.PERTURB) - self.assertFalse(f.PERTURB) - self.assertEqual(before, p.model()) - with self.assertRaises(ValueError): - f.perturbed("nonsense") - - def test_atomic_perturbations(self): - neg = 0xFFFFFFFF - with f.perturbed("max_i32_unsigned"): - self.assertEqual(f.atomic("max_i32", 1, neg), neg) - self.assertEqual(f.atomic("max_i32", 1, neg), 1) - with f.perturbed("min_u32_signed"): - self.assertEqual(f.atomic("min_u32", 1, neg), neg) - self.assertEqual(f.atomic("min_u32", 1, neg), 1) - - -class FakeOracle: - """What runner.Oracle gives run_hw: arch, run(kernels) -> one list of words (or a str) per kernel.""" - - arch = "gfx1150" - device = "fake" - - def __init__(self, programs, mutate=None, reject=()): - self.by_text = {tuple(p.hw_lines(self.arch)): p for p in programs} - self.mutate, self.reject, self.kernels = mutate, set(reject), [] - - def run(self, kernels): - out = [] - for k in kernels: - self.kernels.append(k) - p = self.by_text[tuple(k.lines)] - if p.name in self.reject: - out.append("assembler rejected: instruction not supported on this GPU") - continue - regs, lds = p.model() - words = [regs[t][r] for t in range(p.threads) for r in f.POOL] + list(struct.unpack(f"<{f.LDS_DWORDS}I", lds)) - if self.mutate: - words = self.mutate(p, words) - out.append(words) - return out - - def close(self): - pass - - -class RunHw(unittest.TestCase): - def run_hw(self, oracle, progs, **kw): - a = type("A", (), dict(seed=1, no_exec=(), opts={}, max_report=3, minimize=False, keep=None, **kw))() - tally, results = {}, [] - out = io.StringIO() - with contextlib.redirect_stdout(out): - rc = f.run_hw(oracle, progs, a, tally, results) - return rc, out.getvalue(), tally, results - - def test_kernels_are_launched_as_the_program_is(self): - progs = f.programs(1, 3, (32, 64), threads="mix") - o = FakeOracle(progs) - rc, out, tally, _ = self.run_hw(o, progs) - self.assertEqual(rc, 0, out) - self.assertEqual(len(o.kernels), len(progs)) - for k in o.kernels: - p = o.by_text[tuple(k.lines)] - self.assertEqual((k.wave, k.threads, k.words, k.lds, k.raw), (p.wave, p.threads, p.out_words, - f.LDS_BYTES, True)) - self.assertGreaterEqual(k.vgprs, max(f.POOL) + 1) - - def test_a_backend_without_lds_support_is_unavailable_not_a_mismatch(self): - progs = f.programs(1, 2, (32,)) - - class NoLds(FakeOracle): - def run(self, kernels): - raise RuntimeError("k0: LDS, scratch memory and COMPUTE_PGM_RSRC3 are not supported by the launcher") - rc, out, *_ = self.run_hw(NoLds(progs), progs) - self.assertEqual(rc, 77) - self.assertIn("unavailable", out) - - class Broken(FakeOracle): - def run(self, kernels): - raise RuntimeError("hw_oracle exited 3: something else") - with self.assertRaises(RuntimeError): - self.run_hw(Broken(progs), progs) - - def test_gfx12_runs_cmpst_programs(self): - # The ds_cmpstore operand order is measured on gfx1201 too, so these are no longer skipped there. - with_cmpst = next(p for p in f.programs(1, 60, (32,)) if any(o["kind"] == "cmpst" for o in p.ops)) - for arch in ("gfx1201", "gfx1150", "gfx1030"): - self.assertIsNone(f.hw_skip_reason(with_cmpst, arch), arch) - - def test_gfx12_skips_only_wave64_programs_with_a_bpermute(self): - has_bp = lambda p: any(o["kind"] == "bpermute" for o in p.ops) - w64 = next(p for p in f.programs(1, 60, (64,)) if has_bp(p)) - w32 = next(p for p in f.programs(1, 60, (32,)) if has_bp(p)) - plain = next(p for p in f.programs(1, 60, (64,)) if not has_bp(p)) - self.assertIn("all 64 lanes", f.hw_skip_reason(w64, "gfx1201")) - self.assertIsNone(f.hw_skip_reason(w32, "gfx1201")) - self.assertIsNone(f.hw_skip_reason(plain, "gfx1201")) - for arch in ("gfx1150", "gfx1030"): # halves stay separate there (measured) - self.assertIsNone(f.hw_skip_reason(w64, arch), arch) - f.PERTURB.add("bpermute_wave64_cross") # the model that crosses halves can run them - try: - self.assertIsNone(f.hw_skip_reason(w64, "gfx1201")) - finally: - f.PERTURB.discard("bpermute_wave64_cross") - - def test_gfx12_skips_wave64_permute_programs_the_same_way(self): - # measured on an RX 9070 (gfx1201): a wave64 ds_permute_b32 delivers to lane (l + 32) & 63, like bpermute - has_pm = lambda p: any(o["kind"] == "permute" for o in p.ops) - w64 = next(p for p in f.programs(1, 60, (64,), permute=True) if has_pm(p) and - not any(o["kind"] == "bpermute" for o in p.ops)) - w32 = next(p for p in f.programs(1, 60, (32,), permute=True) if has_pm(p)) - self.assertIn("all 64 lanes", f.hw_skip_reason(w64, "gfx1201")) - self.assertIsNone(f.hw_skip_reason(w32, "gfx1201")) - for arch in ("gfx1150", "gfx1030"): # halves stay separate there (measured) - self.assertIsNone(f.hw_skip_reason(w64, arch), arch) - f.PERTURB.add("permute_wave64_cross") # the model that crosses halves can run them - try: - self.assertIsNone(f.hw_skip_reason(w64, "gfx1201")) - finally: - f.PERTURB.discard("permute_wave64_cross") - - def test_gfx12_kernels_use_its_barrier_and_lds_wait(self): - p = f.programs(1, 1, (64,))[0] # every kernel waits and barriers after each op - g12, g11 = p.hw_lines("gfx1201"), p.hw_lines("gfx1150") - self.assertIn("s_barrier", g11) - self.assertNotIn("s_barrier", g12) - self.assertNotIn("s_waitcnt lgkmcnt(0)", g12) - self.assertEqual(g12.count("s_barrier_signal -1"), g11.count("s_barrier")) - self.assertEqual(g12.count("s_barrier_wait -1"), g11.count("s_barrier")) - self.assertEqual(g12.count("s_wait_dscnt 0"), g11.count("s_waitcnt lgkmcnt(0)")) - self.assertEqual(p.hw_lines("gfx1030").count("s_barrier"), g11.count("s_barrier")) - - def test_a_flipped_word_is_a_mismatch(self): - progs = f.programs(1, 4, (32,)) - - def flip(p, words): - words[5] ^= 1 - return words - rc, out, tally, _ = self.run_hw(FakeOracle(progs, mutate=flip), progs) - self.assertEqual(rc, 1, out) - self.assertEqual(set(tally["hw"].values()), {"mismatch"}) - self.assertIn("MISMATCH", out) - - def test_every_word_is_compared(self): - p = f.Program(1, 1, 32) - for index in (0, len(f.POOL) * p.threads - 1, len(f.POOL) * p.threads, p.out_words - 1): - def flip(_p, words, index=index): - words[index] ^= 0x80000000 - return words - rc, out, *_ = self.run_hw(FakeOracle([p], mutate=flip), [p]) - self.assertEqual(rc, 1, (index, out)) - - def test_rejected_programs_are_skips_not_passes(self): - progs = f.programs(1, 3, (32,)) - rc, out, tally, _ = self.run_hw(FakeOracle(progs, reject=[progs[1].name]), progs) - self.assertEqual(rc, 0, out) - self.assertEqual(tally["hw"][progs[1].name], "rejected") - self.assertIn("rejected 1", out) - rc, out, *_ = self.run_hw(FakeOracle(progs, reject=[p.name for p in progs]), progs) - self.assertEqual(rc, 2, out) # nothing ran: not a pass - - def test_a_failed_hypothesis_is_a_mismatch(self): - progs = [p for p in f.programs(2, 40, (32,), permute=True) if p.hyp_ops][:3] - self.assertTrue(progs) - - def flip(p, words): - words[0] ^= 1 - return words - rc, out, tally, _ = self.run_hw(FakeOracle(progs, mutate=flip), progs) - self.assertEqual(rc, 1) - self.assertIn("hyp_only 3", out) - - def test_negative_control_detects_each_perturbation(self): - progs = f.programs(1, 200, (64, 32), permute=True, swizzle_exec=True) - rc, out, tally, results = self.run_hw(FakeOracle(progs), progs) - self.assertEqual(rc, 0, out) - for name, (cases, bad) in f.negative_control(results).items(): - self.assertGreater(cases, 0, name) - self.assertGreater(bad, 0, f"{name} is not detected") - - def test_family_table_and_attribution(self): - progs = f.programs(1, 20, (32,)) - _, _, tally, results = self.run_hw(FakeOracle(progs), progs) - table = f.family_table(results, tally["hw"]) - self.assertTrue(all(row[1] == 0 for row in table.values())) - self.assertEqual(sum(r[0] for r in table.values()), sum(len(p.ops) for p in progs)) - self.assertEqual(f.attribute(results), {}) - - -class Main(unittest.TestCase): - def main(self, *argv): - out = io.StringIO() - with patch.object(sys, "argv", ["lds_fuzz.py", *argv]), contextlib.redirect_stdout(out): - return f.main(), out.getvalue() - - def test_exit_77_when_the_oracle_is_unavailable(self): - with patch.object(runner, "open_oracle", side_effect=runner.Unavailable("no AMD clang")): - rc, out = self.main("--oracle", "hw", "--programs", "2") - self.assertEqual(rc, 77) - self.assertIn("hardware oracle unavailable: no AMD clang", out) - - def test_an_rdna4_gpu_is_supported(self): - # the blanket exit 77 for gfx1170+ is gone: the tool runs there (asm.sync_lines respells GFX12, the - # per-program hw_skip_reason skips a wave64 bpermute), so a fake oracle gets past the gate and runs - for arch in ("gfx1201", "gfx1170"): - oracle = FakeOracle([]) - oracle.arch = arch - with patch.object(runner, "open_oracle", return_value=oracle): - oracle.by_text = {tuple(p.hw_lines(arch)): p for p in f.programs(1, 6, (32,))} - rc, out = self.main("--oracle", "hw", "--programs", "6", "--wave", "32") - self.assertEqual(rc, 0, (arch, out)) - self.assertIn("hardware oracle: fake", out) - self.assertNotIn("hardware oracle unavailable", out) - - def test_exit_77_with_a_missing_compiler(self): - with patch.dict(os.environ, {"LEONIDA_AMD_CLANG": str(TOOLS / "no-such-clang.exe")}): - rc, out = self.main("--oracle", "translator,hw", "--programs", "1") - self.assertEqual(rc, 77, out) - - def test_hw_options_need_the_hardware(self): - for opt in ("--perturb=cmpst_swap", "--negative-control", "--minimize"): - with patch.object(sys, "argv", ["lds_fuzz.py", opt, "--programs", "1"]): - with contextlib.redirect_stderr(io.StringIO()): - with self.assertRaises(SystemExit) as r: - f.main() - self.assertEqual(r.exception.code, 2, opt) - - def test_oracle_names_are_checked(self): - with patch.object(sys, "argv", ["lds_fuzz.py", "--oracle", "gpu"]): - with contextlib.redirect_stderr(io.StringIO()): - with self.assertRaises(SystemExit) as r: - f.main() - self.assertEqual(r.exception.code, 2) - - def test_model_only_with_the_wider_op_mix(self): - rc, out = self.main("--model-only", "--extended", "--programs", "5") - self.assertEqual(rc, 0) - self.assertIn("10 programs generated", out) - - def test_only_filters_by_index(self): - oracle = FakeOracle([]) - with patch.object(runner, "open_oracle", return_value=oracle): - oracle.by_text = {tuple(p.hw_lines("gfx1150")): p for p in f.programs(1, 6, (32,))} - rc, out = self.main("--oracle", "hw", "--programs", "6", "--wave", "32", "--only", "1,4") - self.assertEqual(rc, 0, out) - self.assertIn("programs 2,", out) - - def test_show_prints_the_native_body(self): - rc, out = self.main("--show", "1:2:32", "--hw-arch", "gfx1150", "--extended") - self.assertEqual(rc, 0) - self.assertIn("s_mov_b32 s10, exec_lo", out) - - -class OnHardware(unittest.TestCase): - """The oracle itself, when its tools and an AMD GPU are present: the programs of seed 1 match the model, and - the negative control catches a wrong ds_cmpst.""" - - @classmethod - def setUpClass(cls): - try: - cls.oracle = runner.open_oracle() - except runner.Unavailable as e: - raise unittest.SkipTest(f"no hardware oracle: {e}") - if asm.family(cls.oracle.arch) == "gfx10": - raise unittest.SkipTest("the cmpstore operand order is measured on GFX11") - - @classmethod - def tearDownClass(cls): - cls.oracle.close() - - def test_programs_match_and_a_wrong_model_does_not(self): - progs = f.programs(1, 40, (32, 64), permute=True, swizzle_exec=True, threads="mix") - a = type("A", (), dict(seed=1, no_exec=(), opts={}, max_report=3, minimize=False, keep=None))() - tally, results = {}, [] - with contextlib.redirect_stdout(io.StringIO()): - rc = f.run_hw(self.oracle, progs, a, tally, results) - self.assertEqual(rc, 0, tally) - for name in ("cmpst_swap", "max_i32_unsigned", "bpermute_inactive_reads"): - cases, bad = f.negative_control(results, only=name)[name] - self.assertTrue(cases and bad, (name, cases, bad)) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/test_leonida_mods.py b/tests/test_leonida_mods.py deleted file mode 100644 index 256bfe092..000000000 --- a/tests/test_leonida_mods.py +++ /dev/null @@ -1,202 +0,0 @@ -"""tools/leonida_mods.py: local mod manifests, folders and ZIP packages. No game data. - - python -I tests/test_leonida_mods.py -v -""" -import contextlib -import io -import json -import os -from pathlib import Path -import sys -import tempfile -import unittest -import zipfile - -ROOT = Path(__file__).resolve().parents[1] -sys.path.insert(0, str(ROOT / "tools")) -import leonida_mods # noqa: E402 - -MANDY = { - "name": "Mandy in the prison intro", - "enabled": True, - "game_version": "1.0.2.1", - "archetype_swaps": [ - {"from": "player_story000_00", "to": "cs_mandy", "when": "always"} - ], -} - - -def write_json(path, data): - path.parent.mkdir(parents=True, exist_ok=True) - with open(path, "w", encoding="utf-8", newline="\n") as f: - json.dump(data, f, indent=2) - f.write("\n") - - -def read_json(path): - with open(path, encoding="utf-8") as f: - return json.load(f) - - -def cli(*argv): - out, err = io.StringIO(), io.StringIO() - with contextlib.redirect_stdout(out), contextlib.redirect_stderr(err): - code = leonida_mods.main(list(argv)) - return code, out.getvalue(), err.getvalue() - - -class ManifestTests(unittest.TestCase): - def test_hashes_match_the_runtime_contract(self): - self.assertEqual(leonida_mods.joaat("player_story000_00"), 0xE472B687) - self.assertEqual(leonida_mods.joaat("cs_mandy"), 0xD7C0CDFF) - self.assertEqual(leonida_mods.parse_model_id("0xD7C0CDFF"), 0xD7C0CDFF) - with self.assertRaises(ValueError): - leonida_mods.parse_model_id("0x") - with self.assertRaises(ValueError): - leonida_mods.parse_model_id("0x123456789") - - def test_manifest_validation_matches_runtime_rules(self): - mod = leonida_mods.validate_manifest(MANDY, "mandy_prison_intro") - self.assertEqual(mod.name, "Mandy in the prison intro") - self.assertEqual(mod.swaps[0].from_id, 0xE472B687) - self.assertEqual(mod.swaps[0].to_id, 0xD7C0CDFF) - - def bad(data, needle): - with self.assertRaises(leonida_mods.ModsError) as cm: - leonida_mods.validate_manifest(data, "bad") - self.assertIn(needle, str(cm.exception)) - - bad({"enabled": "yes"}, '"enabled" must be true or false') - bad({"archetype_swaps": [{"from": "a", "to": "b", "when": "mission:intro"}]}, - '"when" can only be "always"') - bad({"archetype_swaps": [{"from": "cs_mandy", "to": "0xD7C0CDFF"}]}, "with itself") - bad({"archetype_swaps": "all"}, '"archetype_swaps" must be a list') - bad([1, 2], "not a JSON object") - - -class ManagerTests(unittest.TestCase): - def test_new_list_enable_disable_and_uninstall(self): - with tempfile.TemporaryDirectory() as tmp: - mods = os.path.join(tmp, "mods") - code, out, err = cli("--dir", mods, "new", "lucia_to_mandy", "--name", "Mandy", - "--game-version", "1.0.2.1", - "--swap", "player_story000_00=cs_mandy") - self.assertEqual((code, err), (0, "")) - self.assertIn("created lucia_to_mandy", out) - manifest = Path(mods, "lucia_to_mandy", "mod.json") - self.assertEqual(read_json(manifest)["archetype_swaps"][0]["to"], "cs_mandy") - - code, out, err = cli("--dir", mods, "disable", "lucia_to_mandy") - self.assertEqual((code, err), (0, "")) - self.assertFalse(read_json(manifest)["enabled"]) - - code, out, err = cli("--dir", mods, "list", "--json") - self.assertEqual((code, err), (0, "")) - report = json.loads(out) - self.assertEqual(report["mods"][0]["folder"], "lucia_to_mandy") - self.assertFalse(report["mods"][0]["enabled"]) - - code, out, err = cli("--dir", mods, "uninstall", "lucia_to_mandy", "--yes") - self.assertEqual((code, err), (0, "")) - self.assertFalse(manifest.exists()) - - def test_install_folder_package_and_pack_round_trip(self): - with tempfile.TemporaryDirectory() as tmp: - package = Path(tmp, "package", "mandy_prison_intro") - write_json(package / "mod.json", MANDY) - mods = os.path.join(tmp, "mods") - code, out, err = cli("--dir", mods, "install", str(Path(tmp, "package"))) - self.assertEqual((code, err), (0, "")) - self.assertIn("installed mandy_prison_intro", out) - installed = Path(mods, "mandy_prison_intro", "mod.json") - self.assertEqual(read_json(installed), MANDY) - - packed = Path(tmp, "mandy.leonidamod") - code, out, err = cli("--dir", mods, "pack", "mandy_prison_intro", "--out", str(packed)) - self.assertEqual((code, err), (0, "")) - self.assertTrue(packed.is_file()) - with zipfile.ZipFile(packed) as archive: - self.assertEqual(archive.namelist(), ["mandy_prison_intro/mod.json"]) - - other_mods = os.path.join(tmp, "other-mods") - code, out, err = cli("--dir", other_mods, "install", str(packed), "--disable") - self.assertEqual((code, err), (0, "")) - installed_copy = Path(other_mods, "mandy_prison_intro", "mod.json") - self.assertFalse(read_json(installed_copy)["enabled"]) - - def test_zip_install_rejects_path_traversal(self): - with tempfile.TemporaryDirectory() as tmp: - package = Path(tmp, "bad.zip") - with zipfile.ZipFile(package, "w") as archive: - archive.writestr("mod.json", json.dumps(MANDY)) - archive.writestr("../escape.txt", "nope") - code, out, err = cli("--dir", os.path.join(tmp, "mods"), "install", str(package)) - self.assertEqual(code, 2) - self.assertEqual(out, "") - self.assertIn("unsafe ZIP member", err) - self.assertFalse(Path(tmp, "escape.txt").exists()) - - def test_check_reports_broken_manifest(self): - with tempfile.TemporaryDirectory() as tmp: - broken = Path(tmp, "mods", "broken") - broken.mkdir(parents=True) - broken.joinpath("mod.json").write_text("{not json", encoding="utf-8") - code, out, err = cli("--dir", os.path.join(tmp, "mods"), "check") - self.assertEqual(code, 1) - self.assertIn("skipped broken:", out) - self.assertEqual(err, "") - - def test_run_print_builds_gta6rt_command(self): - with tempfile.TemporaryDirectory() as tmp: - port = Path(tmp, "port") - game = Path(tmp, "game") - port.mkdir() - game.mkdir() - # the launcher runtime_executable() looks for here: Windows takes only gta6rt.exe - launcher = "gta6rt.exe" if os.name == "nt" else "gta6rt.sh" - port.joinpath(launcher).write_bytes(b"MZ" if os.name == "nt" else b"#!/bin/sh\n") - port.joinpath("game_path.txt").write_text(str(game) + "\n", encoding="utf-8") - image = game / leonida_mods.EXPECTED_EXE - image.write_bytes(b"MZ") - code, out, err = cli("--port", str(port), "run", "--dry-run", "--print", - "--archetype-lookup", "1A2B3C0", "--", "--windowed") - self.assertEqual((code, err), (0, "")) - self.assertIn(" --dry-run ", " " + out) - self.assertIn("--mods", out) - self.assertIn(os.path.join(str(port), "mods"), out) - self.assertIn("--archetype-lookup 1A2B3C0", out) - self.assertTrue(out.rstrip().endswith("--windowed")) - - -class SamplesAndGuiTests(unittest.TestCase): - def test_bundled_basic_mods_are_valid_and_safe(self): - mods, errors = leonida_mods.load_mods(str(ROOT / "mods")) - self.assertEqual(errors, []) - by_folder = {m.folder: m for m in mods} - self.assertIn("mandy_prison_intro", by_folder) - self.assertIn("monalisa_player_model", by_folder) - self.assertIn("lucia_cutscene_model", by_folder) - self.assertIn("mandy_to_monalisa", by_folder) - self.assertTrue(by_folder["mandy_prison_intro"].enabled) - self.assertFalse(by_folder["monalisa_player_model"].enabled) - self.assertFalse(by_folder["lucia_cutscene_model"].enabled) - self.assertFalse(by_folder["mandy_to_monalisa"].enabled) - active = leonida_mods.active_swaps(mods) - self.assertEqual(active, {0xE472B687: by_folder["mandy_prison_intro"].swaps[0]}) - - def test_gui_is_an_explicit_lazy_tkinter_entry_point(self): - source = (ROOT / "tools" / "leonida_mods.py").read_text(encoding="utf-8") - self.assertIn('commands.add_parser("gui"', source) - self.assertIn("import tkinter as tk", source) - self.assertLess(source.index("def run_gui"), source.index("import tkinter as tk")) - args = leonida_mods.build_parser().parse_args(["--dir", "mods", "gui"]) - self.assertEqual(args.command, "gui") - - def test_windows_launcher_opens_the_gui(self): - launcher = (ROOT / "Mods.bat").read_text(encoding="utf-8") - self.assertIn("leonida_mods.py", launcher) - self.assertIn(" gui ", launcher + " ") - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/test_leonida_tui.py b/tests/test_leonida_tui.py deleted file mode 100644 index 58d8b8107..000000000 --- a/tests/test_leonida_tui.py +++ /dev/null @@ -1,412 +0,0 @@ -"""Stdlib LEONIDA TUI helpers (no TTY interaction, no game data). - - python -I tests/test_leonida_tui.py -""" -import os -import sys -import tempfile -import unittest -from unittest import mock - -ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) -sys.path.insert(0, ROOT) -sys.path.insert(0, os.path.join(ROOT, "tools")) - -import leonida_tui # noqa: E402 -import make_game # noqa: E402 - - -class EligibleTest(unittest.TestCase): - def test_no_tui_flag_disables(self): - self.assertFalse(leonida_tui.tui_eligible(True)) - - -class JobsBoundsTest(unittest.TestCase): - def test_clamp_and_defaults(self): - with mock.patch.object(leonida_tui.os, "cpu_count", return_value=8): - lo, half, hi = leonida_tui.cpu_jobs_bounds() - self.assertEqual((lo, half, hi), (1, 4, 8)) - self.assertEqual(leonida_tui.clamp_jobs(0), 1) - self.assertEqual(leonida_tui.clamp_jobs(1), 1) - self.assertEqual(leonida_tui.clamp_jobs(4), 4) - self.assertEqual(leonida_tui.clamp_jobs(99), 8) - - def test_read_key_timeout_zero_polls_once(self): - # Regression: timeout 0.0 used to skip the kbhit loop entirely on Windows. - calls = {"hit": 0} - - class FakeMsvcrt: - def kbhit(self): - calls["hit"] += 1 - return False - - def getwch(self): - raise AssertionError("should not read when kbhit is false") - - with mock.patch.object(leonida_tui, "os") as fake_os: - fake_os.name = "nt" - with mock.patch.dict(sys.modules, {"msvcrt": FakeMsvcrt()}): - # Re-import path: _read_key imports msvcrt inside the nt branch. - self.assertIsNone(leonida_tui._read_key(0.0)) - self.assertEqual(calls["hit"], 1) - - def test_nt_arrow_scan_codes(self): - seq = iter(["\xe0", "H", "\xe0", "P", "\xe0", "K", "\xe0", "M", - "\xe0", "I", "\xe0", "Q", "\xe0", "G", "\xe0", "O"]) - - class FakeMsvcrt: - def getwch(self): - return next(seq) - - self.assertEqual(leonida_tui._nt_consume(FakeMsvcrt()), "Up") - self.assertEqual(leonida_tui._nt_consume(FakeMsvcrt()), "Down") - self.assertEqual(leonida_tui._nt_consume(FakeMsvcrt()), "Left") - self.assertEqual(leonida_tui._nt_consume(FakeMsvcrt()), "Right") - self.assertEqual(leonida_tui._nt_consume(FakeMsvcrt()), "PageUp") - self.assertEqual(leonida_tui._nt_consume(FakeMsvcrt()), "PageDown") - self.assertEqual(leonida_tui._nt_consume(FakeMsvcrt()), "Home") - self.assertEqual(leonida_tui._nt_consume(FakeMsvcrt()), "End") - - def test_wheel_delta_to_keys(self): - self.assertEqual(leonida_tui._nt_wheel_delta_to_keys(120), ["Up"]) - self.assertEqual(leonida_tui._nt_wheel_delta_to_keys(-240), ["Down", "Down"]) - self.assertEqual(leonida_tui._nt_wheel_delta_to_keys(0), []) - # Horizontal is inverted vs keyboard: tilt right → previous tab (Left). - self.assertEqual(leonida_tui._nt_wheel_delta_to_keys(120, horizontal=True), ["Left"]) - self.assertEqual(leonida_tui._nt_wheel_delta_to_keys(-120, horizontal=True), ["Right"]) - - def test_sgr_mouse_wheel(self): - self.assertEqual(leonida_tui._parse_sgr_mouse("64;10;5", "M"), "Up") - self.assertEqual(leonida_tui._parse_sgr_mouse("65;1;1", "m"), "Down") - self.assertEqual(leonida_tui._parse_sgr_mouse("66;1;1", "M"), "Left") - self.assertEqual(leonida_tui._parse_sgr_mouse("67;1;1", "M"), "Right") - self.assertIsNone(leonida_tui._parse_sgr_mouse("0;1;1", "M")) # click ignored - - -class StageConsoleTest(unittest.TestCase): - def test_write_and_snapshot(self): - with tempfile.TemporaryDirectory() as tmp: - path = os.path.join(tmp, "shaders.log") - c = leonida_tui.StageConsole("shaders", path, maxlen=3) - c.write_line("a") - c.write_line("b") - c.write_line("c") - c.write_line("d") - self.assertEqual(c.snapshot(10), ["b", "c", "d"]) - c.close() - with open(path, encoding="utf-8") as f: - self.assertEqual(f.read().splitlines(), ["a", "b", "c", "d"]) - - def test_wrap_log_lines_breaks_and_keeps_newest(self): - rows = leonida_tui.wrap_log_lines(["abcdefghij", "xyz"], width=4, max_rows=3) - self.assertEqual(rows, ["efgh", "ij", "xyz"]) - - -class CapturePopenTest(unittest.TestCase): - def test_pipes_stdio_and_detaches_console_on_windows(self): - kw = leonida_tui.capture_popen_kwargs() - self.assertIs(kw["stdout"], __import__("subprocess").PIPE) - self.assertIs(kw["stderr"], __import__("subprocess").STDOUT) - if os.name == "nt": - self.assertEqual(kw["creationflags"], __import__("subprocess").CREATE_NO_WINDOW) - else: - self.assertNotIn("creationflags", kw) - - -class InterruptKeyTest(unittest.TestCase): - def test_ctrl_c_char_force_exits(self): - calls = {"exit": 0} - - class FakeMsvcrt: - def getwch(self): - return "\x03" - - with mock.patch.object(leonida_tui, "force_exit_interrupt", - side_effect=lambda: calls.__setitem__("exit", 1)): - self.assertIsNone(leonida_tui._nt_consume(FakeMsvcrt())) - self.assertEqual(calls["exit"], 1) - - -class RestoreConsoleTest(unittest.TestCase): - def test_leave_alt_clears_and_restores_modes(self): - chunks = [] - - class Fake: - def write(self, data): - chunks.append(data) - return len(data) - - def flush(self): - pass - - leonida_tui.restore_console(Fake(), ansi=True, leave_alt=True) - text = "".join(chunks) - self.assertIn("\033[?1049l", text) - self.assertIn("\033[?7h", text) - self.assertIn("\033[?25h", text) - self.assertIn("\033[H", text) - self.assertIn("\033[J", text) - - -class BuildRuntimeCaptureTest(unittest.TestCase): - def test_script_no_longer_shares_the_parent_console(self): - path = os.path.join(ROOT, "scripts", "build_runtime.ps1") - with open(path, encoding="utf-8") as f: - text = f.read() - # The old Start-Process line shared the console; the new one must hide + redirect. - self.assertNotRegex(text, r"Start-Process[^\n]*-NoNewWindow") - self.assertIn("-WindowStyle Hidden", text) - self.assertIn("-RedirectStandardOutput", text) - self.assertIn("Write-Output", text) - self.assertNotIn("Write-Host", text) - - -class BoardSelectTest(unittest.TestCase): - def test_tab_cycles_and_digit_selects(self): - with tempfile.TemporaryDirectory() as tmp: - board = leonida_tui.LeonidaBoard(["shaders", "assets", "runtime"], tmp) - self.assertEqual(board.stages[board.selected], "shaders") - board._handle_key("Tab") - self.assertEqual(board.stages[board.selected], "assets") - board._handle_key("3") - self.assertEqual(board.stages[board.selected], "runtime") - board._handle_key("Left") - self.assertEqual(board.stages[board.selected], "assets") - board.write("assets", "hello") - self.assertIn("hello", board.consoles["assets"].snapshot(5)) - board.stop() - for c in board.consoles.values(): - c.close() - - def test_other_stage_lines_do_not_dirty_visible_pane(self): - with tempfile.TemporaryDirectory() as tmp: - board = leonida_tui.LeonidaBoard(["shaders", "assets"], tmp) - board._dirty = False - board.write("assets", "hidden") - self.assertFalse(board._dirty) - board.write("shaders", "visible") - self.assertTrue(board._dirty) - board.stop() - for c in board.consoles.values(): - c.close() - - def test_up_scrolls_log_and_end_returns_to_live(self): - with tempfile.TemporaryDirectory() as tmp: - board = leonida_tui.LeonidaBoard(["shaders"], tmp) - for i in range(20): - board.write("shaders", f"line-{i}") - self.assertEqual(board.scroll, 0) - board._handle_key("Up") - board._handle_key("Up") - self.assertEqual(board.scroll, 2) - board._handle_key("End") - self.assertEqual(board.scroll, 0) - board._handle_key("Up") - board._handle_key("Tab") # only one stage; still resets scroll - self.assertEqual(board.scroll, 0) - board.stop() - for c in board.consoles.values(): - c.close() - - def test_wheel_keys_scroll_like_arrows(self): - with tempfile.TemporaryDirectory() as tmp: - board = leonida_tui.LeonidaBoard(["shaders"], tmp) - for i in range(20): - board.write("shaders", f"line-{i}") - board._handle_key("Up") # wheel-up maps to Up - self.assertEqual(board.scroll, 1) - board._handle_key("Down") # wheel-down maps to Down - self.assertEqual(board.scroll, 0) - board.stop() - for c in board.consoles.values(): - c.close() - - -class StageScopeTest(unittest.TestCase): - def test_routes_log_into_stage_console(self): - with tempfile.TemporaryDirectory() as tmp: - with leonida_tui.LeonidaBoard(["shaders", "assets"], tmp) as board: - with leonida_tui.stage_scope("shaders"): - make_game.log("from shaders") - self.assertTrue(any("from shaders" in line for line in board.consoles["shaders"].snapshot(20))) - self.assertEqual(board.consoles["shaders"].status, "done") - - def test_stray_stdout_lands_in_active_pane(self): - with tempfile.TemporaryDirectory() as tmp: - with mock.patch.object(leonida_tui, "enable_ansi", return_value=False), \ - mock.patch.object(leonida_tui, "term_size", return_value=(80, 24)): - with leonida_tui.LeonidaBoard(["shaders", "assets"], tmp) as board: - with leonida_tui.stage_scope("assets"): - print("leaked line from library") - # Flush any buffered proxy content. - sys.stdout.flush() - self.assertTrue( - any("leaked line from library" in line - for line in board.consoles["assets"].snapshot(20))) - - def test_redraw_row_count_matches_terminal_height(self): - with tempfile.TemporaryDirectory() as tmp: - captured = [] - - class FakeOut: - encoding = "utf-8" - - def write(self, data): - captured.append(data) - return len(data) - - def flush(self): - pass - - def isatty(self): - return False - - def fileno(self): - return 1 - - fake = FakeOut() - with mock.patch.object(leonida_tui, "enable_ansi", return_value=False), \ - mock.patch.object(leonida_tui, "term_size", return_value=(80, 24)), \ - mock.patch.object(sys, "stdout", fake), \ - mock.patch.object(sys, "stderr", fake): - board = leonida_tui.LeonidaBoard(["shaders"], tmp) - board._real_out = fake - board._real_err = fake - board._ansi = False - board.write("shaders", "line one") - board._redraw(force=True) - board.stop() - for c in board.consoles.values(): - c.close() - text = "".join(captured) - # Non-ANSI path joins exactly height rows with no trailing newline → no scroll. - self.assertEqual(text.count("\n"), 23) # 24 rows → 23 separators - self.assertIn("line one", text) - - -class SerialOverlapTest(unittest.TestCase): - def test_overlap_false_runs_in_order(self): - order = [] - - def record(name): - def fn(*a, **k): - order.append(name) - return fn - - with tempfile.TemporaryDirectory() as tmp: - game = os.path.join(tmp, "g") - out = os.path.join(tmp, "o") - work = os.path.join(tmp, "w") - os.makedirs(game) - with mock.patch.object(make_game, "shaders", side_effect=record("shaders")), \ - mock.patch.object(make_game, "assets", side_effect=record("assets")), \ - mock.patch.object(make_game, "runtime", side_effect=record("runtime")), \ - mock.patch.object(make_game, "pipelines", side_effect=record("pipelines")), \ - mock.patch.object(make_game, "log"), \ - mock.patch.object(make_game, "verify_runtime_build"), \ - mock.patch.object(make_game, "pipeline_check_exe", return_value="x"): - make_game.run_build_stages( - ["shaders", "assets", "runtime", "pipelines"], - game=game, work=work, out=out, v={}, wav=False, jobs=2, - runtime_build=None, emulate=False, keep_emulated=True, fallbacks=(), - overlap=False) - self.assertEqual(order, ["shaders", "assets", "runtime", "pipelines"]) - - def test_overlap_waits_for_runtime_before_pipelines_even_if_checker_exists(self): - """Flyander/#1797: a stale vk_pipeline_check on disk must not start pipelines mid-rebuild.""" - import threading - import time - - order = [] - lock = threading.Lock() - - def record(name, hold=0.0): - def fn(*a, **k): - with lock: - order.append(f"start-{name}") - if hold: - time.sleep(hold) - with lock: - order.append(f"end-{name}") - return fn - - with tempfile.TemporaryDirectory() as tmp: - game = os.path.join(tmp, "g") - out = os.path.join(tmp, "o") - work = os.path.join(tmp, "w") - os.makedirs(game) - with mock.patch.object(make_game, "shaders", side_effect=record("shaders")), \ - mock.patch.object(make_game, "assets", side_effect=record("assets")), \ - mock.patch.object(make_game, "runtime", side_effect=record("runtime", hold=0.15)), \ - mock.patch.object(make_game, "pipelines", side_effect=record("pipelines")), \ - mock.patch.object(make_game, "log"), \ - mock.patch.object(make_game, "verify_runtime_build"), \ - mock.patch.object(make_game, "pipeline_check_exe", return_value="stale_checker"): - make_game.run_build_stages( - ["shaders", "assets", "runtime", "pipelines"], - game=game, work=work, out=out, v={}, wav=False, jobs=2, - runtime_build=None, emulate=False, keep_emulated=True, fallbacks=(), - overlap=True) - self.assertIn("end-runtime", order) - self.assertIn("start-pipelines", order) - self.assertLess(order.index("end-runtime"), order.index("start-pipelines")) - - -class SetupDefaultsTest(unittest.TestCase): - def test_esc_keeps_clamped_defaults(self): - keys = iter(["Esc"]) - - def fake_key(timeout_s=0.05): - try: - return next(keys) - except StopIteration: - return "Enter" - - with mock.patch.object(leonida_tui.os, "cpu_count", return_value=8), \ - mock.patch.object(leonida_tui, "_read_key", side_effect=fake_key), \ - mock.patch.object(leonida_tui, "enable_ansi", return_value=False), \ - mock.patch.object(leonida_tui, "term_size", return_value=(80, 24)), \ - mock.patch("sys.stdout"): - cfg = leonida_tui.run_setup(7, default_overlap=False) - self.assertEqual(cfg.jobs, 7) - self.assertFalse(cfg.overlap) - - def test_jobs_cannot_exceed_cpu_count(self): - keys = iter(["Right", "Right", "Right", "Enter"]) - - def fake_key(timeout_s=0.05): - try: - return next(keys) - except StopIteration: - return None - - with mock.patch.object(leonida_tui.os, "cpu_count", return_value=4), \ - mock.patch.object(leonida_tui, "_read_key", side_effect=fake_key), \ - mock.patch.object(leonida_tui, "enable_ansi", return_value=False), \ - mock.patch.object(leonida_tui, "term_size", return_value=(80, 24)), \ - mock.patch("sys.stdout"): - cfg = leonida_tui.run_setup(4, default_overlap=True) - self.assertEqual(cfg.jobs, 4) - - def test_arrows_select_row_and_change_values(self): - # Down to Overlap, Right toggles off, Up to Jobs, Left lowers jobs, Enter. - keys = iter(["Down", "Right", "Up", "Left", "Enter"]) - - def fake_key(timeout_s=0.05): - try: - return next(keys) - except StopIteration: - return None - - with mock.patch.object(leonida_tui.os, "cpu_count", return_value=8), \ - mock.patch.object(leonida_tui, "_read_key", side_effect=fake_key), \ - mock.patch.object(leonida_tui, "enable_ansi", return_value=False), \ - mock.patch.object(leonida_tui, "term_size", return_value=(80, 24)), \ - mock.patch("sys.stdout"): - cfg = leonida_tui.run_setup(4, default_overlap=True) - self.assertEqual(cfg.jobs, 3) - self.assertFalse(cfg.overlap) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/test_library_shaders_stage.py b/tests/test_library_shaders_stage.py deleted file mode 100644 index 09253ffe0..000000000 --- a/tests/test_library_shaders_stage.py +++ /dev/null @@ -1,456 +0,0 @@ -"""make_game.py's pipeline-library step (library_shaders): the compute pipelines of the library in shaders.rpf, which -the executable creates with Xbox device slot 67 (docs/shader_library.md, docs/fspx.md). - - python -I tests/test_library_shaders_stage.py - -Synthetic files only, no game data: the stage tests mock the tools the way tests/test_fspx_shaders_stage.py does, and -the end-to-end test runs the repository's real shader_library.py and rdna2spirv.py on a synthetic archive. -""" -import hashlib -import io -import json -import os -import shutil -import sys -import tempfile -import unittest -from unittest import mock - -ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) -sys.path.insert(0, ROOT) -sys.path.insert(0, os.path.join(ROOT, "tests")) -import make_game # noqa: E402 -from test_shader_library import NONE, archive as make_archive, build, kind0, prog # noqa: E402 - - -class LibraryStage(unittest.TestCase): - def setUp(self): - self.tmp = tempfile.TemporaryDirectory() - self.addCleanup(self.tmp.cleanup) - self.work = os.path.join(self.tmp.name, "work") - self.game = os.path.join(self.tmp.name, "game") - os.makedirs(self.game) - self.archive = os.path.join(self.game, make_game.LIBRARY_ARCHIVE) - self.write_archive(b"synthetic archive") - self.unpacked = os.path.join(self.work, "shaders", "library") - self.spirv = os.path.join(self.work, "shaders", "spirv", "library") - self.carve = os.path.join(self.work, "shaders", "dxbc") - self.calls = [] - self.translations = {"lib_cs_00007": ("c" * 64, "s" * 64, b"synthetic module")} - self.raw_index = None - - def write_archive(self, data): - with open(self.archive, "wb") as f: - f.write(data) - - def fake_py(self, tool, *args): - self.calls.append((tool, args)) - if tool == "shader_library.py": - os.makedirs(os.path.join(self.unpacked, "disasm"), exist_ok=True) - open(os.path.join(self.unpacked, "disasm", "lib_cs_00007.s"), "w", encoding="utf-8", newline="\n").close() - - def fake_translate(self, disasm, spirv, jobs, emulate=False, fallbacks=()): - self.calls.append(("translate", (disasm, spirv, jobs, emulate, fallbacks))) - os.makedirs(spirv, exist_ok=True) - if self.raw_index is not None: - if self.raw_index is not False: - with open(os.path.join(spirv, "index.json"), "w", encoding="utf-8", newline="\n") as f: - f.write(self.raw_index) - return - index = {} - for name, (code, state, module) in self.translations.items(): - index[name] = {"stage": "cs", "fspx_code_sha256": code, "fspx_state_sha256": state} - with open(os.path.join(spirv, name + ".spv"), "wb") as f: - f.write(module) - with open(os.path.join(spirv, "index.json"), "w", encoding="utf-8", newline="\n") as f: - json.dump(index, f) - - def run_step(self, signature="llvm-mc 23", jobs=4, emulate=False, fallbacks=(), py=None, translate=None): - self.calls = [] - with mock.patch.object(make_game, "py", py or self.fake_py), \ - mock.patch.object(make_game, "translate", translate or self.fake_translate), \ - mock.patch.object(make_game, "log", lambda *a: None): - make_game.library_shaders(self.game, self.work, signature, jobs, emulate=emulate, fallbacks=fallbacks) - return [tool for tool, _ in self.calls] - - def test_runs_once_then_nothing(self): - os.makedirs(self.carve) - self.assertEqual(self.run_step(), ["shader_library.py", "translate"]) - (_, unpack), (_, translate) = self.calls - self.assertEqual(unpack, (self.archive, "--out", self.unpacked, "--stages", "cs", "--disasm", "--jobs", "4", - "--carve", self.carve)) - self.assertEqual(translate, (os.path.join(self.unpacked, "disasm"), self.spirv, 4, False, ())) - self.assertTrue(os.path.isfile(os.path.join(self.spirv, "library_build.json"))) - self.assertEqual(self.run_step(), []) - - def test_without_a_carve_the_sources_are_not_named(self): - self.run_step() - (_, unpack), _ = self.calls - self.assertNotIn("--carve", unpack) - - def test_no_archive_skips_the_step(self): - os.unlink(self.archive) - self.assertEqual(self.run_step(), []) - self.assertFalse(os.path.exists(self.spirv)) - - def test_archive_that_is_gone_takes_the_old_index_with_it(self): - self.assertEqual(self.run_step(), ["shader_library.py", "translate"]) - index = os.path.join(self.spirv, "index.json") - settings = os.path.join(self.spirv, "library_build.json") - self.assertTrue(os.path.isfile(index) and os.path.isfile(settings)) - os.unlink(self.archive) - self.assertEqual(self.run_step(), []) - self.assertFalse(os.path.exists(index)) - self.assertFalse(os.path.exists(settings)) - self.write_archive(b"synthetic archive") - self.assertEqual(self.run_step(), ["shader_library.py", "translate"]) - self.assertTrue(os.path.isfile(index) and os.path.isfile(settings)) - - def test_inputs_that_change_the_output_translate_again(self): - self.run_step() - self.assertEqual(self.run_step(), []) - self.assertEqual(self.run_step(signature="llvm-mc 24"), ["shader_library.py", "translate"]) - self.assertEqual(self.run_step(signature="llvm-mc 24", emulate=True), ["shader_library.py", "translate"]) - (_, translate_args) = self.calls[1] - self.assertEqual(translate_args[2:], (4, True, ())) - self.assertEqual(self.run_step(signature="llvm-mc 24", emulate=True, fallbacks=("--bary-fallback",)), - ["shader_library.py", "translate"]) - (_, translate_args) = self.calls[1] - self.assertEqual(translate_args[2:], (4, True, ("--bary-fallback",))) - self.write_archive(b"another archive") - self.assertEqual(self.run_step(signature="llvm-mc 24", emulate=True, fallbacks=("--bary-fallback",)), - ["shader_library.py", "translate"]) - with mock.patch.object(make_game, "translation_sources_digest", return_value="another translator"): - self.assertEqual(self.run_step(signature="llvm-mc 24", emulate=True, fallbacks=("--bary-fallback",)), - ["shader_library.py", "translate"]) - with mock.patch.object(make_game, "sources_digest", return_value="another library tool"): - self.assertEqual(self.run_step(signature="llvm-mc 24", emulate=True, fallbacks=("--bary-fallback",)), - ["shader_library.py", "translate"]) - - def test_empty_index_is_translated_again_and_drops_stale_modules(self): - self.run_step() - stale = os.path.join(self.spirv, "lib_cs_00007.spv") - self.assertTrue(os.path.isfile(stale)) - with open(os.path.join(self.spirv, "index.json"), "w", encoding="utf-8", newline="\n") as f: - f.write("{}") - self.translations = {} - self.assertEqual(self.run_step(), ["shader_library.py", "translate"]) - self.assertFalse(os.path.exists(stale)) - self.assertEqual(self.run_step(), ["shader_library.py", "translate"]) - - def test_rebuild_cleans_stale_unpacked_state_and_sidecars_for_removed_program(self): - self.run_step() - fspx_dir = os.path.join(self.unpacked, "fspx") - disasm_dir = os.path.join(self.unpacked, "disasm") - os.makedirs(fspx_dir, exist_ok=True) - os.makedirs(disasm_dir, exist_ok=True) - stale_files = [ - os.path.join(self.unpacked, "lib_cs_00099.dxbc"), - os.path.join(fspx_dir, "lib_cs_00099.code"), - os.path.join(fspx_dir, "lib_cs_00099.state"), - os.path.join(fspx_dir, "lib_cs_00099.json"), - os.path.join(disasm_dir, "lib_cs_00099.s"), - ] - for path in stale_files: - with open(path, "wb") as f: - f.write(b"stale") - self.write_archive(b"updated archive") - self.assertEqual(self.run_step(), ["shader_library.py", "translate"]) - for path in stale_files: - self.assertFalse(os.path.exists(path), f"stale unpacked artifact survived rebuild: {path}") - - def test_missing_cached_module_is_rebuilt(self): - self.run_step() - self.assertEqual(self.run_step(), []) - module = os.path.join(self.spirv, "lib_cs_00007.spv") - os.remove(module) - self.assertEqual(self.run_step(), ["shader_library.py", "translate"]) - self.assertTrue(os.path.isfile(module)) - self.assertEqual(self.run_step(), []) - - def test_key_clash_fails_and_leaves_no_index(self): - self.translations = {"lib_cs_00001": ("c" * 64, "s" * 64, b"module one"), - "lib_cs_00002": ("c" * 64, "s" * 64, b"module two")} - with self.assertRaises(SystemExit), mock.patch("sys.stderr", new_callable=io.StringIO) as err: - self.run_step() - self.assertIn("lib_cs_00001", err.getvalue()) - self.assertIn("lib_cs_00002", err.getvalue()) - self.assertFalse(os.path.exists(os.path.join(self.spirv, "index.json"))) - self.assertFalse(os.path.exists(os.path.join(self.spirv, "library_build.json"))) - - def test_same_code_key_is_allowed_with_other_state_or_same_module(self): - self.translations = {"lib_cs_00001": ("c" * 64, "a" * 64, b"module A"), - "lib_cs_00002": ("c" * 64, "b" * 64, b"module B"), - "lib_cs_00003": ("c" * 64, "a" * 64, b"module A")} - self.assertEqual(self.run_step(), ["shader_library.py", "translate"]) - self.assertTrue(os.path.isfile(os.path.join(self.spirv, "library_build.json"))) - - def test_a_stopped_translation_leaves_no_marker_and_no_old_modules(self): - self.run_step() - with open(os.path.join(self.spirv, "notes.txt"), "w", encoding="utf-8", newline="\n") as f: - f.write("keep\n") - - def stop_translate(*args, **kwargs): - raise KeyboardInterrupt - - with self.assertRaises(KeyboardInterrupt): - self.run_step(signature="llvm-mc 24", translate=stop_translate) - self.assertFalse(os.path.exists(os.path.join(self.spirv, "index.json"))) - self.assertFalse(os.path.exists(os.path.join(self.spirv, "library_build.json"))) - self.assertFalse(os.path.exists(os.path.join(self.spirv, "lib_cs_00007.spv"))) - self.assertTrue(os.path.isfile(os.path.join(self.spirv, "notes.txt"))) - self.assertEqual(self.run_step(signature="llvm-mc 24"), ["shader_library.py", "translate"]) - self.assertEqual(self.run_step(signature="llvm-mc 24"), []) - - def test_malformed_and_missing_cached_metadata_rebuild(self): - self.run_step() - self.assertEqual(self.run_step(), []) - index_path = os.path.join(self.spirv, "index.json") - settings_path = os.path.join(self.spirv, "library_build.json") - - for bad_index in ("{broken", "[]", "null", - json.dumps({"lib_cs_00007": {"error": "synthetic failure"}}), - json.dumps({"lib_cs_00007": {"stage": "cs", "fspx_code_sha256": "short"}}), - json.dumps({"lib_cs_00007": {"stage": "ps", "fspx_code_sha256": "c" * 64}})): - with self.subTest(bad_index=bad_index): - with open(index_path, "w", encoding="utf-8", newline="\n") as f: - f.write(bad_index) - self.assertEqual(self.run_step(), ["shader_library.py", "translate"]) - self.assertEqual(self.run_step(), []) - - os.remove(index_path) - self.assertEqual(self.run_step(), ["shader_library.py", "translate"]) - with open(settings_path, "w", encoding="utf-8", newline="\n") as f: - f.write("{broken") - self.assertEqual(self.run_step(), ["shader_library.py", "translate"]) - self.assertEqual(self.run_step(), []) - - def test_malformed_or_missing_output_index_fails_cleanly(self): - for raw in (False, "{broken", "[]"): - with self.subTest(raw=raw): - self.raw_index = raw - with self.assertRaises(SystemExit), mock.patch("sys.stderr", new_callable=io.StringIO) as err: - self.run_step() - self.assertIn("unreadable index", err.getvalue()) - self.assertFalse(os.path.exists(os.path.join(self.spirv, "index.json"))) - self.assertFalse(os.path.exists(os.path.join(self.spirv, "library_build.json"))) - - def test_parallel_translate_shards_use_requested_jobs_and_ignore_stale_parts_on_rebuild(self): - spawned = [] - merges = [] - - class FakeShard: - def __init__(self, shard_idx, count): - self.shard_idx = shard_idx - self.count = count - - def poll(self): - return 0 - - def wait(self, timeout=None): - return 0 - - def fake_popen(cmd, **kwargs): - shard_arg = cmd[cmd.index("--shard") + 1] - idx, count = (int(part) for part in shard_arg.split("/")) - spawned.append(cmd) - out_dir = cmd[cmd.index("--out") + 1] - with open(os.path.join(out_dir, f"shard{idx}.json"), "w", encoding="utf-8", newline="\n") as f: - json.dump({"index": idx, "count": count}, f) - with open(os.path.join(out_dir, f"index.part{idx}.json"), "w", encoding="utf-8", newline="\n") as f: - if idx == 0: - json.dump({"lib_cs_00007": {"stage": "cs", "fspx_code_sha256": "c" * 64, - "fspx_state_sha256": "s" * 64}}, f) - else: - json.dump({}, f) - return FakeShard(idx, count) - - def fake_py(tool, *args): - self.calls.append((tool, args)) - if tool == "shader_library.py": - self.fake_py(tool, *args) - elif tool == "rdna2spirv.py": - merges.append(args) - self.assertIn("--merge", args) - out_dir = args[args.index("--out") + 1] - for name, (code, state, module) in self.translations.items(): - with open(os.path.join(out_dir, name + ".spv"), "wb") as f: - f.write(module) - with open(os.path.join(out_dir, "index.json"), "w", encoding="utf-8", newline="\n") as f: - json.dump({name: {"stage": "cs", "fspx_code_sha256": code, "fspx_state_sha256": state} - for name, (code, state, _) in self.translations.items()}, f) - - with mock.patch.object(make_game, "py", fake_py), \ - mock.patch.object(make_game.subprocess, "Popen", side_effect=fake_popen), \ - mock.patch.object(make_game, "log", lambda *a: None): - make_game.library_shaders(self.game, self.work, "llvm-mc 23", jobs=3, emulate=True, - fallbacks=("--bary-fallback",)) - self.assertEqual([cmd[cmd.index("--shard") + 1] for cmd in spawned], ["0/3", "1/3", "2/3"]) - for cmd in spawned: - self.assertIn("--no-asm", cmd) - self.assertIn("--wave64-emulate", cmd) - self.assertIn("--bary-fallback", cmd) - self.assertEqual(len(merges), 1) - self.assertTrue(os.path.isfile(os.path.join(self.spirv, make_game.SHARD_PLAN))) - - # Archive change with identical jobs/flags/translator must drop shards.json and rerun all 3 shards. - spawned.clear() - merges.clear() - self.write_archive(b"updated archive") - make_game.library_shaders(self.game, self.work, "llvm-mc 23", jobs=3, emulate=True, - fallbacks=("--bary-fallback",)) - self.assertEqual([cmd[cmd.index("--shard") + 1] for cmd in spawned], ["0/3", "1/3", "2/3"]) - self.assertEqual(len(merges), 1) - - def test_failed_shard_cleans_index_and_prevents_build_marker(self): - class FailingShard: - def __init__(self, rc): - self.rc = rc - - def poll(self): - return self.rc - - def wait(self, timeout=None): - return self.rc - - rcs = iter([0, 2]) - - with mock.patch.object(make_game, "py", self.fake_py), \ - mock.patch.object(make_game.subprocess, "Popen", side_effect=lambda *a, **kw: FailingShard(next(rcs))), \ - mock.patch.object(make_game.time, "sleep", lambda *a: None), \ - mock.patch.object(make_game, "log", lambda *a: None), \ - mock.patch("sys.stderr", new_callable=io.StringIO) as err: - with self.assertRaises(SystemExit): - make_game.library_shaders(self.game, self.work, "llvm-mc 23", jobs=2) - self.assertIn("shard 1 exited with 2", err.getvalue()) - self.assertFalse(os.path.exists(os.path.join(self.spirv, "index.json"))) - self.assertFalse(os.path.exists(os.path.join(self.spirv, "library_build.json"))) - - def test_real_tools_generate_state_keyed_library_index(self): - if not (shutil.which("spirv-as") and shutil.which("spirv-val")): - self.skipTest("spirv-as / spirv-val not on PATH") - # Four compute pipelines across multiple jobs: two share RDNA2 code bytes with distinct kind-0 states. - code_a = prog(0x12345678, body=0) - code_b = prog(0x87654321, body=0) - code_c = prog(0x11223344, body=0) - state_a = kind0(threads=(32, 1, 1)) - state_b = kind0(threads=(64, 1, 1)) - state_c = kind0(threads=(16, 2, 1)) - state_d = kind0(threads=(8, 8, 1)) - lib = build([], [(0, NONE, 0, NONE), (1, NONE, 1, NONE), (2, NONE, 2, NONE), (3, NONE, 3, NONE)], - [state_a, state_b, state_c, state_d], [code_a, code_a, code_b, code_c]) - self.write_archive(make_archive(lib)) - mc = os.path.join(self.tmp.name, "fake_mc.py") - with open(mc, "w", encoding="utf-8", newline="\n") as f: - f.write("print('\\ts_endpgm')\n") - outputs = {} - for jobs in (1, 2): - work = os.path.join(self.tmp.name, f"work_{jobs}") - spirv = os.path.join(work, "shaders", "spirv", "library") - with mock.patch.dict(os.environ, {"LLVM_MC": f'"{sys.executable}" "{mc}"'}), \ - mock.patch.object(make_game, "log", lambda *a: None): - make_game.library_shaders(self.game, work, "fake-mc", jobs=jobs) - with open(os.path.join(spirv, "index.json"), encoding="utf-8") as f: - index = json.load(f) - with open(os.path.join(spirv, make_game.SHARD_PLAN), encoding="utf-8") as f: - self.assertEqual(json.load(f)["jobs"], jobs) - for s in range(jobs): - with open(os.path.join(spirv, f"shard{s}.json"), encoding="utf-8") as f: - self.assertEqual(json.load(f), {"index": s, "count": jobs}) - self.assertTrue(os.path.isfile(os.path.join(spirv, f"index.part{s}.json"))) - spvs = {} - for name in index: - with open(os.path.join(spirv, name + ".spv"), "rb") as f: - spvs[name] = f.read() - self.assertTrue(make_game.fspx_cache_complete(spirv)) - outputs[jobs] = (index, spvs) - - index1, spvs1 = outputs[1] - index2, spvs2 = outputs[2] - self.assertEqual(index1, index2) - self.assertEqual(spvs1, spvs2) - self.assertEqual(sorted(index2), ["lib_cs_00000", "lib_cs_00001", "lib_cs_00002", "lib_cs_00003"]) - self.assertEqual(index2["lib_cs_00000"]["fspx_code_sha256"], hashlib.sha256(code_a).hexdigest()) - self.assertEqual(index2["lib_cs_00001"]["fspx_code_sha256"], hashlib.sha256(code_a).hexdigest()) - self.assertEqual(index2["lib_cs_00002"]["fspx_code_sha256"], hashlib.sha256(code_b).hexdigest()) - self.assertEqual(index2["lib_cs_00003"]["fspx_code_sha256"], hashlib.sha256(code_c).hexdigest()) - self.assertEqual(index2["lib_cs_00000"]["fspx_state_sha256"], hashlib.sha256(state_a).hexdigest()) - self.assertEqual(index2["lib_cs_00001"]["fspx_state_sha256"], hashlib.sha256(state_b).hexdigest()) - self.assertEqual(index2["lib_cs_00002"]["fspx_state_sha256"], hashlib.sha256(state_c).hexdigest()) - self.assertEqual(index2["lib_cs_00003"]["fspx_state_sha256"], hashlib.sha256(state_d).hexdigest()) - self.assertEqual(index2["lib_cs_00000"]["local_size"], [32, 1, 1]) - self.assertEqual(index2["lib_cs_00001"]["local_size"], [64, 1, 1]) - self.assertEqual(index2["lib_cs_00002"]["local_size"], [16, 2, 1]) - self.assertEqual(index2["lib_cs_00003"]["local_size"], [8, 8, 1]) - - -class ShadersStageWithLibrary(unittest.TestCase): - """The whole shaders() stage with shaders.rpf in the game folder: library_shaders() runs after the corpus - (and any DLL steps), and changing shaders.rpf alone only re-runs library_shaders() when the corpus marker stays - current.""" - - def test_library_runs_after_corpus_and_alone_when_archive_changes(self): - with tempfile.TemporaryDirectory() as t: - work, game = os.path.join(t, "work"), os.path.join(t, "game") - os.makedirs(game) - archive_path = os.path.join(game, make_game.LIBRARY_ARCHIVE) - with open(archive_path, "wb") as f: - f.write(b"archive v1") - ran = [] - translate_jobs = [] - dxbc = os.path.join(work, "shaders", "dxbc") - - def write(text, *parts): - os.makedirs(os.path.dirname(os.path.join(*parts)), exist_ok=True) - with open(os.path.join(*parts), "w", encoding="utf-8", newline="\n") as f: - f.write(text) - - def fake_py(tool, *args): - ran.append(tool) - if tool == "shader_carve.py": - write('[{"file": "shader.dxbc"}]', dxbc, "index.json") - elif tool == "fssm_unpack.py": - write('[{"name": "shader"}]', dxbc, "fssm_index.json") - elif tool == "shader_disasm.py": - write("s_endpgm\n", dxbc, "disasm", "shader.s") - elif tool == "shader_library.py": - write("s_endpgm\n", work, "shaders", "library", "disasm", "lib_cs_00007.s") - - def fake_translate(disasm, spirv, jobs, emulate=False, fallbacks=()): - ran.append("translate") - translate_jobs.append((spirv, jobs)) - if os.path.basename(spirv) == "library": - write(json.dumps({"lib_cs_00007": {"stage": "cs", "fspx_code_sha256": "c" * 64, - "fspx_state_sha256": "s" * 64}}), - spirv, "index.json") - write("spv", spirv, "lib_cs_00007.spv") - else: - write('{"shader": {"stage": "cs"}}', spirv, "index.json") - - def stage(): - ran.clear() - translate_jobs.clear() - with mock.patch.object(make_game, "py", fake_py), \ - mock.patch.object(make_game, "need", lambda *a: None), \ - mock.patch.object(make_game, "translate", fake_translate), \ - mock.patch.object(make_game, "llvm_mc_signature", return_value="llvm-mc 23"), \ - mock.patch.object(make_game, "log", lambda *a: None): - make_game.shaders(game, work, 2) - return list(ran) - - self.assertEqual(stage(), ["shader_carve.py", "fssm_unpack.py", "shader_disasm.py", "translate", - "shader_library.py", "translate"]) - self.assertEqual(translate_jobs, [(os.path.join(work, "shaders", "spirv"), 2), - (os.path.join(work, "shaders", "spirv", "library"), 2)]) - self.assertEqual(stage(), []) - with open(archive_path, "wb") as f: - f.write(b"archive v2") - self.assertEqual(stage(), ["shader_library.py", "translate"]) - self.assertEqual(translate_jobs, [(os.path.join(work, "shaders", "spirv", "library"), 2)]) - self.assertEqual(stage(), []) - self.assertTrue(os.path.isfile(os.path.join(work, "shaders", "spirv", "index.json"))) - self.assertTrue(os.path.isfile(os.path.join(work, "shaders", "spirv", "library", "index.json"))) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/test_limit_window.py b/tests/test_limit_window.py deleted file mode 100644 index 3b6944a35..000000000 --- a/tests/test_limit_window.py +++ /dev/null @@ -1,76 +0,0 @@ -"""--limit ending inside a stream: the index tools leave that stream out instead of counting its whole stored size. - -story_index (#712) and navmesh_index (#766) already inflate only inside the scan window; anim_index, rbf0_index, -restofworld_index and bvh_index inflated up to the end of the archive, so a stream that started in the window but -ended after it was counted as readable and readable + zero + unread exceeded the span. rpf9_carve.py has its own -test in test_rpf9_carve.py. -""" -import hashlib -import os -import struct -import sys -import tempfile -import unittest -import zlib - -ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) -sys.path.insert(0, os.path.join(ROOT, "tools")) - -import anim_index # noqa: E402 -import bvh_index # noqa: E402 -import rbf0_index # noqa: E402 -import restofworld_index # noqa: E402 - -GAP = 0x100 - - -def noisy(n, seed): - """Bytes zlib can't shrink, so a stream's stored size is about n.""" - out = bytearray() - while len(out) < n: - out += hashlib.sha256(bytes([seed]) + len(out).to_bytes(4, "little")).digest() - return bytes(out[:n]) - - -def summary_of(result): - """The tools return (rows, summary), (rows, records, summary) or (rows, [summary]).""" - last = result[-1] - return last[0] if isinstance(last, list) else last - - -def first_of(summary, *keys): - for key in keys: - if key in summary: - return summary[key] - raise KeyError(keys) - - -class LimitWindowTest(unittest.TestCase): - def setUp(self): - self.tmp = tempfile.TemporaryDirectory() - self.first = zlib.compress(noisy(4000, 1)) - data = bytearray(0x40 + GAP) + self.first + zlib.compress(noisy(4000, 2)) - data[0:4] = b"9FPR" - struct.pack_into(" +0"], probe.POS_ZERO) - self.assertEqual(by_what["-FLT_MIN div:2 -> -0"], probe.NEG_ZERO) - self.assertEqual(by_what["-FLT_MIN clamp div:2 -> +0"], probe.POS_ZERO) - self.assertEqual(by_what["legacy FLT_MIN div:2 -> +0"], probe.POS_ZERO) - - # Subnormal product flush and legacy 0 * anything -> +0 after input flush. - self.assertEqual(by_what["2^-126 * 0.5 + 2^-126 (prod flushed)"], probe.FLT_MIN) - self.assertEqual(by_what["mac 2^-126 * 0.5 + 2^-126"], probe.FLT_MIN) - self.assertEqual(by_what["subnorm * +inf + -1 -> -1"], probe.NEG_ONE) - self.assertEqual(by_what["subnorm * qNaN + 1 -> 1"], probe.ONE) - - def test_mode_sanity_rejects_broken_denorm_control(self): - class BrokenModeOracle: - device = "fake" - arch = "gfx1010" - - def run(self, kernels, words=1): - return [[probe.POS_ZERO] for _ in kernels] - - def close(self): - pass - - with mock.patch.object(hw_runner, "open_oracle", return_value=BrokenModeOracle()): - with contextlib.redirect_stdout(io.StringIO()): - rc = probe.main(["--oracle", "hw"]) - self.assertEqual(rc, 2) - - -class HardwareSkipTests(unittest.TestCase): - """--oracle hw on a GPU without the GFX10.1 mad opcodes is a skip (77), not a traceback.""" - - def _main_with_arch(self, arch): - from hw_oracle import runner - - class Stub: - device = "stub" - closed = False - - def __init__(self): - self.arch = arch - - def run(self, programs, words=4): - raise AssertionError("no kernel may run on " + arch) - - def close(self): - Stub.closed = True - - saved = runner.open_oracle - runner.open_oracle = lambda **kw: Stub() - try: - with contextlib.redirect_stdout(io.StringIO()) as out: - rc = probe.main(["--oracle", "translator,hw"]) - finally: - runner.open_oracle = saved - return rc, out.getvalue(), Stub.closed - - def test_rdna2_and_gfx11_skip(self): - for arch in ("gfx1030", "gfx1036", "gfx1100"): - rc, out, closed = self._main_with_arch(arch) - self.assertEqual(rc, 77, arch) - self.assertIn("hardware oracle unavailable: v_mad_f32", out) - self.assertTrue(closed, arch) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/test_make_game_argparse.py b/tests/test_make_game_argparse.py deleted file mode 100644 index 84080b270..000000000 --- a/tests/test_make_game_argparse.py +++ /dev/null @@ -1,736 +0,0 @@ -"""Unit tests for make_game.py argument parsing, validation, stage sequencing, --jobs, and --wav handling. - - python -I tests/test_make_game_argparse.py -""" -import argparse -import io -import os -import shutil -import subprocess -import sys -import tempfile -import unittest -from unittest.mock import MagicMock, patch - -ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) -if ROOT not in sys.path: - sys.path.insert(0, ROOT) -import make_game - - -class ArgparseDefaultsAndTypesTest(unittest.TestCase): - """Test argument parsing defaults, types, and flags in make_game.py.""" - - def test_default_argument_values(self): - with patch.object(sys, "argv", ["make_game.py"]): - with patch("make_game.below_normal"): - with patch("make_game.choose_game", return_value=os.path.abspath("C:/dummy_game")): - with patch("make_game.check", return_value={"expected_exe": "game.exe"}): - with patch("make_game.preflight"), patch("make_game.cross_build_missing", return_value=[]), \ - patch("make_game.verify_runtime_build"): - with patch("make_game.shaders"): - with patch("make_game.assets"): - with patch("make_game.runtime"): - with patch("make_game.pipelines"): - with patch("make_game.log"): - orig_parse_args = argparse.ArgumentParser.parse_args - captured = [] - - def wrap_parse(parser_self, *args, **kwargs): - res = orig_parse_args(parser_self, *args, **kwargs) - captured.append(res) - return res - - with patch.object(argparse.ArgumentParser, "parse_args", wrap_parse): - ret = make_game.main() - self.assertEqual(ret, 0) - - self.assertEqual(len(captured), 1) - a = captured[0] - self.assertIsNone(a.game) - self.assertIsNone(a.out) - self.assertIsNone(a.work) - self.assertIsNone(a.stages) - self.assertFalse(a.check) - self.assertFalse(a.full_check) - self.assertFalse(a.wav) - self.assertFalse(a.find) - expected_default_jobs = max(1, (os.cpu_count() or 2) // 2) - self.assertEqual(a.jobs, expected_default_jobs) - - def test_custom_arguments_parsed_correctly(self): - test_argv = [ - "make_game.py", - "--game", "C:/custom/game", - "--out", "C:/custom/out", - "--work", "D:/custom/work", - "--stages", "shaders,assets", - "--check", - "--full-check", - "--wav", - "--jobs", "8", - "--find", - ] - with patch.object(sys, "argv", test_argv): - orig_parse_args = argparse.ArgumentParser.parse_args - captured = [] - - def wrap_parse(parser_self, *args, **kwargs): - res = orig_parse_args(parser_self, *args, **kwargs) - captured.append(res) - return res - - with patch.object(argparse.ArgumentParser, "parse_args", wrap_parse): - with patch("make_game.below_normal"): - with patch("make_game.find_dumps", return_value=[]): - with patch("make_game.log"): - with patch("sys.stdout", new_callable=io.StringIO): - ret = make_game.main() - self.assertEqual(ret, 0) - - self.assertEqual(len(captured), 1) - a = captured[0] - self.assertEqual(a.game, "C:/custom/game") - self.assertEqual(a.out, "C:/custom/out") - self.assertEqual(a.work, "D:/custom/work") - self.assertEqual(a.stages, "shaders,assets") - self.assertTrue(a.check) - self.assertTrue(a.full_check) - self.assertTrue(a.wav) - self.assertEqual(a.jobs, 8) - self.assertTrue(a.find) - - def test_non_integer_jobs_rejected_by_argparse(self): - with patch.object(sys, "argv", ["make_game.py", "--jobs", "four"]): - with patch("sys.stderr", new_callable=io.StringIO) as mock_err: - with self.assertRaises(SystemExit) as ctx: - make_game.main() - self.assertEqual(ctx.exception.code, 2) - self.assertIn("invalid int value", mock_err.getvalue()) - - def test_zero_or_negative_jobs_rejected_by_argparse(self): - # 0 would start no translation shard and merge an empty index; a negative count, the same. - for jobs in ("0", "-2"): - with patch.object(sys, "argv", ["make_game.py", "--jobs", jobs]): - with patch("sys.stderr", new_callable=io.StringIO) as mock_err: - with self.assertRaises(SystemExit) as ctx: - make_game.main() - self.assertEqual(ctx.exception.code, 2, jobs) - self.assertIn("must be at least 1", mock_err.getvalue()) - - def test_empty_path_options_rejected_by_argparse(self): - # An empty value used to read as "not given": --out "" built into the default folder. - for option in ("--game", "--out", "--work", "--runtime-build"): - for value in ("", " "): - with patch.object(sys, "argv", ["make_game.py", option, value]): - with patch("sys.stderr", new_callable=io.StringIO) as mock_err: - with self.assertRaises(SystemExit) as ctx: - make_game.main() - self.assertEqual(ctx.exception.code, 2, (option, value)) - self.assertIn("must not be empty", mock_err.getvalue(), (option, value)) - - def test_path_options_omitted_or_given_still_parse(self): - class Stop(Exception): - pass - - orig_parse_args = argparse.ArgumentParser.parse_args - captured = [] - - def wrap_parse(parser_self, *args, **kwargs): - captured.append(orig_parse_args(parser_self, *args, **kwargs)) - raise Stop - - paths = ["--game", "G", "--out", "O", "--work", "W", "--runtime-build", "R"] - for argv in (["make_game.py"], ["make_game.py", *paths]): - with patch.object(sys, "argv", argv): - with patch.object(argparse.ArgumentParser, "parse_args", wrap_parse): - with self.assertRaises(Stop): - make_game.main() - omitted, given = captured - for name in ("game", "out", "work", "runtime_build"): - self.assertIsNone(getattr(omitted, name)) - self.assertEqual((given.game, given.out, given.work, given.runtime_build), ("G", "O", "W", "R")) - - def test_unrecognized_argument_rejected(self): - with patch.object(sys, "argv", ["make_game.py", "--unrecognized-option"]): - with patch("sys.stderr", new_callable=io.StringIO) as mock_err: - with self.assertRaises(SystemExit) as ctx: - make_game.main() - self.assertEqual(ctx.exception.code, 2) - self.assertIn("unrecognized arguments", mock_err.getvalue()) - - -class StageValidationAndSequencingTest(unittest.TestCase): - """Test stage parsing, stage validation, and stage execution sequencing.""" - - def setUp(self): - self.tmp = tempfile.TemporaryDirectory() - self.game_dir = os.path.join(self.tmp.name, "game") - self.out_dir = os.path.join(self.tmp.name, "out") - self.work_dir = os.path.join(self.tmp.name, "work") - os.makedirs(self.game_dir) - os.makedirs(self.out_dir) - os.makedirs(self.work_dir) - - def tearDown(self): - self.tmp.cleanup() - - def run_main(self, *extra_args): - base_argv = [ - "make_game.py", - "--game", self.game_dir, - "--out", self.out_dir, - "--work", self.work_dir, - "--no-tui", - *extra_args, - ] - with patch.object(sys, "argv", base_argv): - with patch("make_game.below_normal"): - with patch("make_game.check", return_value={"expected_exe": "Leonida.exe"}): - with patch("make_game.preflight"), patch("make_game.verify_runtime_build"): - with patch("make_game.log"): - with patch("make_game.shaders") as mock_shaders: - with patch("make_game.assets") as mock_assets: - with patch("make_game.runtime") as mock_runtime: - with patch("make_game.pipelines") as mock_pipelines: - ret = make_game.main() - return ret, { - "shaders": mock_shaders, - "assets": mock_assets, - "runtime": mock_runtime, - "pipelines": mock_pipelines, - } - - def test_unknown_stage_rejected(self): - with patch.object(sys, "argv", ["make_game.py", "--game", self.game_dir, - "--out", self.out_dir, "--work", self.work_dir, - "--stages", "invalid_stage"]): - with patch("make_game.below_normal"): - with patch("make_game.check", return_value={"expected_exe": "Leonida.exe"}): - with patch("make_game.log"): - with patch("sys.stderr", new_callable=io.StringIO) as mock_err: - with self.assertRaises(SystemExit) as ctx: - make_game.main() - self.assertEqual(ctx.exception.code, 2) - self.assertIn("unknown stage 'invalid_stage'", mock_err.getvalue()) - - def test_mixed_valid_and_unknown_stage_rejected(self): - with patch.object(sys, "argv", ["make_game.py", "--game", self.game_dir, - "--out", self.out_dir, "--work", self.work_dir, - "--stages", "shaders,badstage,assets"]): - with patch("make_game.below_normal"): - with patch("make_game.check", return_value={"expected_exe": "Leonida.exe"}): - with patch("make_game.log"): - with patch("sys.stderr", new_callable=io.StringIO) as mock_err: - with self.assertRaises(SystemExit) as ctx: - make_game.main() - self.assertEqual(ctx.exception.code, 2) - self.assertIn("unknown stage 'badstage'", mock_err.getvalue()) - - def test_invalid_stages_rejected_before_game_access(self): - for stages in ("", " ", ",,", " , , ", "badstage", "shaders,badstage"): - with ( - self.subTest(stages=stages), - patch.object(sys, "argv", ["make_game.py", "--stages", stages]), - patch("make_game.below_normal"), - patch("make_game.choose_game", return_value=self.game_dir) as choose, - patch("make_game.check", return_value={}) as check, - patch("make_game.preflight") as preflight, - patch("make_game.shaders") as shaders, - patch("make_game.log"), - patch("sys.stderr", new_callable=io.StringIO) as error, - ): - with self.assertRaises(SystemExit) as ctx: - make_game.main() - self.assertEqual(ctx.exception.code, 2) - self.assertIn("--stages", error.getvalue()) - choose.assert_not_called() - check.assert_not_called() - preflight.assert_not_called() - shaders.assert_not_called() - - def test_whitespace_and_empty_items_in_stages(self): - ret, mocks = self.run_main("--stages", " shaders , , assets ") - self.assertEqual(ret, 0) - mocks["shaders"].assert_called_once() - mocks["assets"].assert_called_once() - mocks["runtime"].assert_not_called() - mocks["pipelines"].assert_not_called() - - def test_independent_stages_all_run_when_listed_out_of_order(self): - """shaders/assets/runtime overlap; pipelines starts after shaders and a selected runtime finish. - wave64_settings is patched: left to probe the installed GPU it returns keep_emulated=False on native-wave64 - RDNA2 under the AMD Windows driver, and the test then failed there (TEST-461).""" - manager = MagicMock() - with patch.object(sys, "argv", ["make_game.py", "--game", self.game_dir, - "--out", self.out_dir, "--work", self.work_dir, "--no-tui", - "--stages", "pipelines,runtime,assets,shaders"]), \ - patch("make_game.wave64_settings", return_value=(False, True)): - with patch("make_game.below_normal"): - with patch("make_game.check", return_value={"expected_exe": "Leonida.exe"}): - with patch("make_game.preflight"): - with patch("make_game.log"): - with patch("make_game.pipeline_check_exe", return_value="vk_pipeline_check"), \ - patch("make_game.verify_runtime_build"): - with patch("make_game.shaders", manager.shaders): - with patch("make_game.assets", manager.assets): - with patch("make_game.runtime", manager.runtime): - with patch("make_game.pipelines", manager.pipelines): - ret = make_game.main() - self.assertEqual(ret, 0) - - manager.shaders.assert_called_once_with( - os.path.abspath(self.game_dir), os.path.abspath(self.work_dir), unittest.mock.ANY, - emulate=unittest.mock.ANY, keep_emulated=True, fallbacks=unittest.mock.ANY) - manager.assets.assert_called_once_with( - os.path.abspath(self.game_dir), os.path.abspath(self.work_dir), False, unittest.mock.ANY, - dump_jobs=unittest.mock.ANY) - self.assertIsNotNone(manager.assets.call_args.kwargs["dump_jobs"]) - manager.runtime.assert_called_once_with( - os.path.abspath(self.game_dir), os.path.abspath(self.out_dir), unittest.mock.ANY, None, - unittest.mock.ANY, work=os.path.abspath(self.work_dir)) - manager.pipelines.assert_called_once_with( - os.path.abspath(self.work_dir), os.path.abspath(self.out_dir), unittest.mock.ANY, - runtime_build=None) - - def test_single_stage_execution_isolates_stages(self): - for stage in ("shaders", "assets", "runtime", "pipelines"): - ret, mocks = self.run_main("--stages", stage) - self.assertEqual(ret, 0) - for s_name, mock_fn in mocks.items(): - if s_name == stage: - mock_fn.assert_called_once() - else: - mock_fn.assert_not_called() - - def test_check_flag_exits_early_without_running_build_stages(self): - with patch.object(sys, "argv", ["make_game.py", "--game", self.game_dir, "--check"]): - with patch("make_game.below_normal"): - with patch("make_game.check", return_value={"expected_exe": "Leonida.exe"}) as mock_check: - with patch("make_game.preflight") as mock_preflight: - with patch("make_game.shaders") as mock_shaders: - ret = make_game.main() - self.assertEqual(ret, 0) - mock_check.assert_called_once_with(os.path.abspath(self.game_dir), False) - mock_preflight.assert_not_called() - mock_shaders.assert_not_called() - - def test_find_flag_exits_early_without_running_check_or_stages(self): - with patch.object(sys, "argv", ["make_game.py", "--find"]): - with patch("make_game.below_normal"): - with patch("make_game.find_dumps", return_value=[(self.game_dir, {"title": "Test", "version": "1.0"})]) as mock_find: - with patch("make_game.check") as mock_check: - with patch("sys.stdout", new_callable=io.StringIO) as mock_out: - ret = make_game.main() - self.assertEqual(ret, 0) - mock_find.assert_called_once() - mock_check.assert_not_called() - self.assertIn("1 found", mock_out.getvalue()) - - -class JobsHandlingTest(unittest.TestCase): - """Test --jobs default computation, command-line overrides, and forwarding.""" - - def test_jobs_default_calculation_scenarios(self): - scenarios = [ - (None, 1), - (1, 1), - (2, 1), - (4, 2), - (8, 4), - (16, 8), - (64, 32), - ] - for cpus, expected in scenarios: - with self.subTest(cpus=cpus, expected=expected): - with patch("os.cpu_count", return_value=cpus): - calc = max(1, (os.cpu_count() or 2) // 2) - self.assertEqual(calc, expected) - - def test_custom_jobs_forwarded_to_shaders(self): - with tempfile.TemporaryDirectory() as tmp: - game = os.path.join(tmp, "game") - out = os.path.join(tmp, "out") - work = os.path.join(tmp, "work") - os.makedirs(game) - with patch.object(sys, "argv", ["make_game.py", "--game", game, "--out", out, "--work", work, - "--no-tui", "--stages", "shaders", "--jobs", "6"]): - # main() clamps --jobs to the machine's hardware threads; pin them so 6 is in range anywhere - # (the GitHub Windows runners have 4). - with patch("make_game.leonida_tui.os.cpu_count", return_value=16), \ - patch("make_game.below_normal"): - with patch("make_game.check", return_value={"expected_exe": "g.exe"}): - with patch("make_game.preflight") as mock_preflight: - with patch("make_game.log"): - with patch("make_game.shaders") as mock_shaders, \ - patch("make_game.wave64_settings", return_value=(True, True)) as probe, \ - patch("make_game.runtime_gpu_per_vertex", return_value=None), \ - patch("make_game.runtime_gpu_barycentric_fallback", return_value=None), \ - patch("make_game.runtime_gpu_max_push_constants", return_value=None), \ - patch("make_game.runtime_gpu_mesh_draws_crash", return_value=None): - ret = make_game.main() - self.assertEqual(ret, 0) - probe.assert_called_once_with("auto", mesh_compute=False) - mock_preflight.assert_called_once_with( - ["shaders"], os.path.abspath(work), False, None, - emulate=True, keep_emulated=True, fallbacks=(), jobs=6) - mock_shaders.assert_called_once_with(os.path.abspath(game), os.path.abspath(work), 6, - emulate=True, keep_emulated=True, fallbacks=()) - - def test_custom_jobs_forwarded_to_assets(self): - with tempfile.TemporaryDirectory() as tmp: - game = os.path.join(tmp, "game") - out = os.path.join(tmp, "out") - work = os.path.join(tmp, "work") - os.makedirs(game) - with patch.object(sys, "argv", ["make_game.py", "--game", game, "--out", out, "--work", work, - "--no-tui", "--stages", "assets", "--wav", "--jobs", "10"]): - # main() clamps --jobs to the machine's hardware threads; pin them so 10 is in range anywhere. - with patch("make_game.below_normal"), patch("make_game.leonida_tui.os.cpu_count", return_value=16): - with patch("make_game.check", return_value={"expected_exe": "g.exe"}): - with patch("make_game.preflight"): - with patch("make_game.log"): - with patch("make_game.assets") as mock_assets: - ret = make_game.main() - self.assertEqual(ret, 0) - mock_assets.assert_called_once_with( - os.path.abspath(game), os.path.abspath(work), True, 10, dump_jobs=None) - - def test_translate_spawns_exact_job_count(self): - with tempfile.TemporaryDirectory() as tmp: - disasm = os.path.join(tmp, "disasm") - spirv = os.path.join(tmp, "spirv") - os.makedirs(disasm) - mock_proc = MagicMock() - mock_proc.poll.return_value = 0 - with patch("subprocess.Popen", return_value=mock_proc) as mock_popen: - with patch("make_game.py") as mock_py: - with patch("make_game.log"): - make_game.translate(disasm, spirv, jobs=4) - self.assertEqual(mock_popen.call_count, 4) - for i in range(4): - args = mock_popen.call_args_list[i][0][0] - self.assertIn("--shard", args) - shard_idx = args.index("--shard") - self.assertEqual(args[shard_idx + 1], f"{i}/4") - mock_py.assert_called_once_with("rdna2spirv.py", disasm, "--out", spirv, "--merge") - - -class WavValidationTest(unittest.TestCase): - """Test --wav validation in preflight and assets stage behavior.""" - - def setUp(self): - # preflight runs `dotnet --list-sdks` (#223). Follow the test's faked shutil.which instead: the SDK counts as - # installed exactly when the test says dotnet is on PATH, so no real dotnet is needed and none is consulted. - patcher = patch("make_game.dotnet_sdk_ok", side_effect=lambda: bool(shutil.which("dotnet"))) - patcher.start() - self.addCleanup(patcher.stop) - - - @patch.object(sys, "version_info", (3, 12, 0)) - @patch("make_game.ensure_submodule") - def test_preflight_wav_requires_ffmpeg_when_assets_included(self, _mock_submodule): - with patch("shutil.which", return_value=None): - with patch("sys.stderr", new_callable=io.StringIO) as mock_err: - with self.assertRaises(SystemExit) as ctx: - make_game.preflight(stages=["assets"], work="C:/dummy_work", wav=True) - self.assertEqual(ctx.exception.code, 1) - self.assertIn("ffmpeg (needed for --wav)", mock_err.getvalue()) - - @patch.object(sys, "version_info", (3, 12, 0)) - @patch("make_game.ensure_submodule") - def test_preflight_wav_passes_when_ffmpeg_present(self, _mock_submodule): - def fake_which(cmd): - if cmd in ("ffmpeg", "dotnet"): - return f"/usr/bin/{cmd}" - return None - - with patch("shutil.which", side_effect=fake_which): - with patch("shutil.disk_usage") as mock_disk: - mock_disk.return_value = MagicMock(free=500 * (2**30)) - with patch("os.makedirs"): - make_game.preflight(stages=["assets"], work="C:/dummy_work", wav=True) - - @patch.object(sys, "version_info", (3, 12, 0)) - def test_preflight_wav_without_assets_does_not_require_ffmpeg(self): - def fake_which(cmd): - if cmd in ("llvm-mc", "spirv-as", "spirv-val"): - return f"/usr/bin/{cmd}" - return None - - with patch("shutil.which", side_effect=fake_which): - with patch.dict(os.environ, {"LLVM_MC": "llvm-mc"}): - with patch("shutil.disk_usage") as mock_disk: - mock_disk.return_value = MagicMock(free=50 * (2**30)) - with patch("os.makedirs"): - # Assets stage not included; ffmpeg is not required even though wav=True - make_game.preflight(stages=["shaders"], work="C:/dummy_work", wav=True) - - @patch.object(sys, "version_info", (3, 12, 0)) - @patch("make_game.ensure_submodule") - def test_preflight_assets_without_wav_does_not_require_ffmpeg(self, _mock_submodule): - def fake_which(cmd): - if cmd == "dotnet": - return "/usr/bin/dotnet" - return None - - with patch("shutil.which", side_effect=fake_which): - with patch("shutil.disk_usage") as mock_disk: - mock_disk.return_value = MagicMock(free=500 * (2**30)) - with patch("os.makedirs"): - make_game.preflight(stages=["assets"], work="C:/dummy_work", wav=False) - - def test_assets_wav_fails_when_ogg_directory_missing(self): - with tempfile.TemporaryDirectory() as tmp: - work = os.path.join(tmp, "work") - game = os.path.join(tmp, "game") - out = os.path.join(work, "assets") - # Populate manifest files so archive processing loops don't run external tools - for rel in make_game.MODEL_ARCHIVES: - name = os.path.splitext(os.path.basename(rel))[0] - for mode in ("models", "textures"): - p = os.path.join(out, name, mode) - os.makedirs(p, exist_ok=True) - with open(os.path.join(p, "manifest.json"), "w", encoding="utf-8") as f: - f.write("{}") - with open(os.path.join(p, make_game.DECODER_RECORD), "w", encoding="utf-8") as f: - f.write(make_game.decoder_digest()) - audio_dir = os.path.join(out, "audio") - os.makedirs(audio_dir, exist_ok=True) - with open(os.path.join(audio_dir, "audio_manifest.json"), "w", encoding="utf-8") as f: - f.write("{}") - os.makedirs(game, exist_ok=True) - - with patch("make_game.rpf9dump", return_value="fake_dump"): - with patch("make_game.log"): - with patch("make_game.py"): - with patch("sys.stderr", new_callable=io.StringIO) as mock_err: - with self.assertRaises(SystemExit) as ctx: - make_game.assets(game, work, wav=True, jobs=2) - self.assertEqual(ctx.exception.code, 1) - self.assertIn("no Ogg Opus output to decode", mock_err.getvalue()) - - def test_assets_wav_invokes_audio_wav_tool_when_ogg_exists(self): - with tempfile.TemporaryDirectory() as tmp: - work = os.path.join(tmp, "work") - game = os.path.join(tmp, "game") - out = os.path.join(work, "assets") - # Populate manifests for model archives - for rel in make_game.MODEL_ARCHIVES: - name = os.path.splitext(os.path.basename(rel))[0] - for mode in ("models", "textures"): - p = os.path.join(out, name, mode) - os.makedirs(p, exist_ok=True) - with open(os.path.join(p, "manifest.json"), "w", encoding="utf-8") as f: - f.write("{}") - with open(os.path.join(p, make_game.DECODER_RECORD), "w", encoding="utf-8") as f: - f.write(make_game.decoder_digest()) - - ogg_dir = os.path.join(out, "audio", "ogg") - wav_dir = os.path.join(out, "audio", "wav") - xma_dir = os.path.join(out, "audio", "xma") - os.makedirs(ogg_dir, exist_ok=True) - os.makedirs(xma_dir, exist_ok=True) - os.makedirs(game, exist_ok=True) - - manifest_dir = os.path.join(out, "audio") - # A step counts as done by its marker, not by its folder (a stopped run leaves the folder too). - for name in ("audio_manifest.json", "ogg.done", "xma.done"): - with open(os.path.join(manifest_dir, name), "w", encoding="utf-8") as f: - f.write("{}") - - with patch("make_game.rpf9dump", return_value="fake_dump"): - with patch("make_game.log"): - with patch("make_game.py") as mock_py: - make_game.assets(game, work, wav=True, jobs=4) - mock_py.assert_called_with("audio_wav.py", ogg_dir, "--out", wav_dir, "--jobs", "4") - - def test_assets_passes_jobs_to_the_ogg_opus_step(self): - # --jobs reached audio_wav.py only: with --jobs 1 the bank export still started half the CPU count of processes - with tempfile.TemporaryDirectory() as tmp: - work = os.path.join(tmp, "work") - game = os.path.join(tmp, "game") - out = os.path.join(work, "assets") - for rel in make_game.MODEL_ARCHIVES: - name = os.path.splitext(os.path.basename(rel))[0] - for mode in ("models", "textures"): - p = os.path.join(out, name, mode) - os.makedirs(p, exist_ok=True) - with open(os.path.join(p, "manifest.json"), "w", encoding="utf-8") as f: - f.write("{}") - with open(os.path.join(p, make_game.DECODER_RECORD), "w", encoding="utf-8") as f: - f.write(make_game.decoder_digest()) - audio = os.path.join(out, "audio") - os.makedirs(os.path.join(audio, "xma"), exist_ok=True) - os.makedirs(game, exist_ok=True) - for name in ("audio_manifest.json", "xma.done"): # no ogg.done: the Ogg Opus step is still to run - with open(os.path.join(audio, name), "w", encoding="utf-8") as f: - f.write("{}") - - with patch("make_game.rpf9dump", return_value="fake_dump"), patch("make_game.log"), \ - patch("make_game.py") as mock_py: - make_game.assets(game, work, wav=False, jobs=3) - mock_py.assert_any_call("awc_opus.py", os.path.join(audio, "awc"), os.path.join(audio, "ogg"), "--jobs", "3") - - def test_assets_without_wav_skips_audio_wav(self): - with tempfile.TemporaryDirectory() as tmp: - work = os.path.join(tmp, "work") - game = os.path.join(tmp, "game") - out = os.path.join(work, "assets") - for rel in make_game.MODEL_ARCHIVES: - name = os.path.splitext(os.path.basename(rel))[0] - for mode in ("models", "textures"): - p = os.path.join(out, name, mode) - os.makedirs(p, exist_ok=True) - with open(os.path.join(p, "manifest.json"), "w", encoding="utf-8") as f: - f.write("{}") - with open(os.path.join(p, make_game.DECODER_RECORD), "w", encoding="utf-8") as f: - f.write(make_game.decoder_digest()) - - manifest_dir = os.path.join(out, "audio") - os.makedirs(manifest_dir, exist_ok=True) - for name in ("audio_manifest.json", "ogg.done", "xma.done"): - with open(os.path.join(manifest_dir, name), "w", encoding="utf-8") as f: - f.write("{}") - os.makedirs(os.path.join(manifest_dir, "ogg"), exist_ok=True) - os.makedirs(os.path.join(manifest_dir, "xma"), exist_ok=True) - os.makedirs(game, exist_ok=True) - - with patch("make_game.rpf9dump", return_value="fake_dump"): - with patch("make_game.log"): - with patch("make_game.py") as mock_py: - make_game.assets(game, work, wav=False, jobs=2) - for call_item in mock_py.call_args_list: - self.assertNotEqual(call_item[0][0], "audio_wav.py") - - -class PathContainmentAndDiskSpaceTest(unittest.TestCase): - """Test rejection of output paths inside game folder and preflight disk space checks.""" - - def setUp(self): - # preflight runs `dotnet --list-sdks` (#223). Follow the test's faked shutil.which instead: the SDK counts as - # installed exactly when the test says dotnet is on PATH, so no real dotnet is needed and none is consulted. - patcher = patch("make_game.dotnet_sdk_ok", side_effect=lambda: bool(shutil.which("dotnet"))) - patcher.start() - self.addCleanup(patcher.stop) - - def test_out_inside_game_folder_fails(self): - with tempfile.TemporaryDirectory() as tmp: - game = os.path.join(tmp, "game") - out = os.path.join(game, "out") - work = os.path.join(tmp, "work") - os.makedirs(game) - with patch.object(sys, "argv", ["make_game.py", "--game", game, "--out", out, "--work", work]): - with patch("make_game.below_normal"): - with patch("make_game.check", return_value={"expected_exe": "g.exe"}): - with patch("sys.stderr", new_callable=io.StringIO) as mock_err: - with self.assertRaises(SystemExit) as ctx: - make_game.main() - self.assertEqual(ctx.exception.code, 1) - self.assertIn("--out and --work must be outside the game folder", mock_err.getvalue()) - - def test_work_inside_game_folder_fails(self): - with tempfile.TemporaryDirectory() as tmp: - game = os.path.join(tmp, "game") - out = os.path.join(tmp, "out") - work = os.path.join(game, "work") - os.makedirs(game) - with patch.object(sys, "argv", ["make_game.py", "--game", game, "--out", out, "--work", work]): - with patch("make_game.below_normal"): - with patch("make_game.check", return_value={"expected_exe": "g.exe"}): - with patch("sys.stderr", new_callable=io.StringIO) as mock_err: - with self.assertRaises(SystemExit) as ctx: - make_game.main() - self.assertEqual(ctx.exception.code, 1) - self.assertIn("--out and --work must be outside the game folder", mock_err.getvalue()) - - @unittest.skipUnless(os.name == "nt", "paths compare without case only on Windows") - def test_out_inside_game_folder_in_other_case_fails(self): - with tempfile.TemporaryDirectory() as tmp: - game = os.path.join(tmp, "Game") - out = os.path.join(tmp, "GAME", "out") # the same folder on Windows - work = os.path.join(tmp, "work") - os.makedirs(game) - with patch.object(sys, "argv", ["make_game.py", "--game", game, "--out", out, "--work", work]): - with patch("make_game.below_normal"): - with patch("make_game.check", return_value={"expected_exe": "g.exe"}): - with patch("sys.stderr", new_callable=io.StringIO) as mock_err: - with self.assertRaises(SystemExit) as ctx: - make_game.main() - self.assertEqual(ctx.exception.code, 1) - self.assertIn("--out and --work must be outside the game folder", mock_err.getvalue()) - - @patch.object(sys, "version_info", (3, 12, 0)) - def test_preflight_space_calculation_and_failure(self): - # Shaders needs 30GB, Assets needs 370GB -> 400GB total - def fake_which(cmd): - if cmd in ("dotnet", "llvm-mc", "spirv-as", "spirv-val"): - return f"/bin/{cmd}" - return None - - with patch("shutil.which", side_effect=fake_which): - with patch.dict(os.environ, {"LLVM_MC": "llvm-mc"}): - with patch("make_game.ensure_submodule"): - with patch("os.makedirs"): - with patch("shutil.disk_usage") as mock_disk: - mock_disk.return_value = MagicMock(free=100 * (2**30)) # 100 GB available < 400 GB - with patch("sys.stderr", new_callable=io.StringIO) as mock_err: - with self.assertRaises(SystemExit) as ctx: - make_game.preflight(["shaders", "assets"], work="C:/work") - self.assertEqual(ctx.exception.code, 1) - self.assertIn("about 400 GB is needed", mock_err.getvalue()) - - -class ToolAvailableTest(unittest.TestCase): - """Test make_game.tool_available command line and path detection.""" - - def test_empty_command_is_false(self): - self.assertFalse(make_game.tool_available("")) - self.assertFalse(make_game.tool_available(" ")) - - def test_existing_executable_file_is_true(self): - self.assertTrue(make_game.tool_available(sys.executable)) - self.assertTrue(make_game.tool_available(f'"{sys.executable}"')) - - def test_command_head_on_path_is_true(self): - with patch("shutil.which", return_value="/bin/custom-tool"): - self.assertTrue(make_game.tool_available("custom-tool -v")) - self.assertTrue(make_game.tool_available('"custom-tool" arg1 arg2')) - - def test_nonexistent_tool_is_false(self): - with patch("shutil.which", return_value=None): - self.assertFalse(make_game.tool_available("nonexistent_utility_12345")) - - -class SubprocessCliSmokeTest(unittest.TestCase): - """Smoke test make_game.py via subprocess to ensure clean entrypoint execution.""" - - def test_help_flag_displays_usage_and_options(self): - make_game_py = os.path.join(ROOT, "make_game.py") - p = subprocess.run([sys.executable, "-I", make_game_py, "--help"], - capture_output=True, text=True) - self.assertEqual(p.returncode, 0, p.stderr) - self.assertIn("--game", p.stdout) - self.assertIn("--stages", p.stdout) - self.assertIn("--jobs", p.stdout) - self.assertIn("--wav", p.stdout) - self.assertIn("--check", p.stdout) - self.assertIn("--find", p.stdout) - - def test_find_flag_executes_without_error(self): - make_game_py = os.path.join(ROOT, "make_game.py") - p = subprocess.run([sys.executable, "-I", make_game_py, "--find"], - capture_output=True, text=True) - self.assertEqual(p.returncode, 0, p.stderr) - self.assertIn("found", p.stdout) - - def test_invalid_jobs_option_fails_cli_parsing(self): - make_game_py = os.path.join(ROOT, "make_game.py") - p = subprocess.run([sys.executable, "-I", make_game_py, "--jobs", "not_an_int"], - capture_output=True, text=True) - self.assertEqual(p.returncode, 2) - self.assertIn("invalid int value", p.stderr) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/test_make_game_assets_decoder.py b/tests/test_make_game_assets_decoder.py deleted file mode 100644 index cc8a242ef..000000000 --- a/tests/test_make_game_assets_decoder.py +++ /dev/null @@ -1,124 +0,0 @@ -"""make_game.py: the assets stage exports models and textures again when the decoder that made them changed. - -Standard library only; no game data, no .NET: the exporter is a fake that writes a manifest.json the way rpf9dump -does when an export finishes. - - python -I tests/test_make_game_assets_decoder.py -""" -import os -import shutil -import subprocess -import sys -import tempfile -import unittest -from unittest import mock - -ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) -sys.path.insert(0, ROOT) -import make_game # noqa: E402 - - -class AssetsDecoderTest(unittest.TestCase): - def setUp(self): - tmp = tempfile.TemporaryDirectory() - self.addCleanup(tmp.cleanup) - self.work = tmp.name - self.models = os.path.join(self.work, "assets", "scene", "models") - # The later steps of the stage are marked done so only the model and texture loop runs. - audio = os.path.join(self.work, "assets", "audio") - os.makedirs(audio) - for name in ("audio_manifest.json", "ogg.done", "xma.done"): - with open(os.path.join(audio, name), "w"): - pass - - def export(self, digest): - """Run assets() with a fake exporter and the given decoder digest; returns the modes it exported.""" - ran = [] - - def fake_run(cmd, *a, **k): - folder = os.path.join(cmd[3], "scene", cmd[1]) - os.makedirs(folder, exist_ok=True) - with open(os.path.join(folder, "manifest.json"), "w") as f: - f.write("{}") - ran.append(cmd[1]) - with mock.patch.object(make_game, "MODEL_ARCHIVES", ["scene.rpf"]), \ - mock.patch.object(make_game, "decoder_digest", lambda: digest), \ - mock.patch.object(make_game, "rpf9dump", lambda w: "rpf9dump"), \ - mock.patch.object(make_game, "run", fake_run), \ - mock.patch.object(make_game.shutil, "which", lambda n: None), \ - mock.patch.object(make_game, "log", lambda *a: None): - make_game.assets(os.path.join(self.work, "game"), self.work, False, 1) - return ran - - def test_the_same_decoder_skips_and_another_one_exports_again(self): - self.assertEqual(self.export("d1"), ["models", "textures"]) - with open(os.path.join(self.models, make_game.DECODER_RECORD), encoding="utf-8") as f: - self.assertEqual(f.read(), "d1\n") - self.assertEqual(self.export("d1"), []) - # A file of the old decoder must not survive: rpf9dump keeps the files it finds. - with open(os.path.join(self.models, "old.bin"), "w"): - pass - self.assertEqual(self.export("d2"), ["models", "textures"]) - self.assertFalse(os.path.exists(os.path.join(self.models, "old.bin"))) - self.assertEqual(self.export("d2"), []) - - def test_a_folder_without_the_record_exports_again(self): - self.export("d1") - os.remove(os.path.join(self.models, make_game.DECODER_RECORD)) - self.assertEqual(self.export("d1"), ["models"]) - - def test_an_exporter_that_cannot_be_built_keeps_the_old_export(self): - self.export("d1") - with mock.patch.object(make_game, "MODEL_ARCHIVES", ["scene.rpf"]), \ - mock.patch.object(make_game, "decoder_digest", lambda: "d2"), \ - mock.patch.object(make_game, "rpf9dump", side_effect=SystemExit(1)), \ - mock.patch.object(make_game, "log", lambda *a: None): - with self.assertRaises(SystemExit): - make_game.assets(os.path.join(self.work, "game"), self.work, False, 1) - self.assertTrue(os.path.isfile(os.path.join(self.models, "manifest.json"))) - with open(os.path.join(self.models, make_game.DECODER_RECORD), encoding="utf-8") as f: - self.assertEqual(f.read(), "d1\n") - self.assertEqual(self.export("d2"), ["models", "textures"]) - - def test_the_digest_follows_the_exporter_sources(self): - with tempfile.TemporaryDirectory() as tools: - os.makedirs(os.path.join(tools, "rpf9dump")) - digests = [] - for text in ("a", "b"): - with open(os.path.join(tools, "rpf9dump", "Program.cs"), "w", newline="\n") as f: - f.write(text) - make_game.decoder_digest.cache_clear() - with mock.patch.object(make_game, "TOOLS", tools): - digests.append(make_game.decoder_digest()) - make_game.decoder_digest.cache_clear() - self.assertNotEqual(*digests) - - @unittest.skipUnless(shutil.which("git"), "needs git") - def test_the_digest_follows_an_uncommitted_submodule_edit(self): - with tempfile.TemporaryDirectory() as root: - sub = os.path.join(root, "third_party", "rpf9-explorer") - os.makedirs(sub) - src = os.path.join(sub, "Decoder.cs") - - def git(*args): - subprocess.run(["git", "-C", sub, "-c", "user.name=t", "-c", "user.email=t@example.invalid", - "-c", "commit.gpgsign=false", *args], check=True, capture_output=True) - - with open(src, "w", newline="\n") as f: - f.write("a\n") - git("init", "-q") - git("add", "Decoder.cs") - git("commit", "-q", "-m", "x") - digests = [] - for text in ("a\n", "b\n"): - with open(src, "w", newline="\n") as f: - f.write(text) - make_game.decoder_digest.cache_clear() - with mock.patch.object(make_game, "ROOT", root): - digests.append(make_game.decoder_digest()) - make_game.decoder_digest.cache_clear() - self.assertNotEqual(*digests) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/test_make_game_assets_pools.py b/tests/test_make_game_assets_pools.py deleted file mode 100644 index 0f580a15d..000000000 --- a/tests/test_make_game_assets_pools.py +++ /dev/null @@ -1,161 +0,0 @@ -"""Texture pools in make_game.assets() must not collide on their basename (no game files). - - python -I tests/test_make_game_assets_pools.py -""" -import contextlib -import io -import json -import os -import sys -import tempfile -import unittest -from unittest import mock - -ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) -sys.path.insert(0, ROOT) -sys.path.insert(0, os.path.join(ROOT, "tools")) - -import make_game # noqa: E402 -import ttpf_assets # noqa: E402 - - -class AssetsPoolsTest(unittest.TestCase): - def setUp(self): - self.tmp = tempfile.TemporaryDirectory() - self.addCleanup(self.tmp.cleanup) - self.game = os.path.join(self.tmp.name, "game") - self.work = os.path.join(self.tmp.name, "work") - self.out = os.path.join(self.work, "assets") - # Mark the other assets stages done so only the texture-pool loop runs. - for rel in make_game.MODEL_ARCHIVES: - stem = os.path.splitext(os.path.basename(rel))[0] - for mode in ("models", "textures"): - self.stub(os.path.join(self.out, stem, mode, "manifest.json")) - with open(os.path.join(self.out, stem, mode, make_game.DECODER_RECORD), "w") as f: - f.write(make_game.decoder_digest()) - self.stub(os.path.join(self.out, "audio", "audio_manifest.json")) - self.stub(os.path.join(self.out, "audio", "ogg.done")) - self.stub(os.path.join(self.out, "audio", "xma.done")) - - def stub(self, path): - os.makedirs(os.path.dirname(path), exist_ok=True) - with open(path, "w"): - pass - - def pool(self, rel, size=100): - path = os.path.join(self.game, *rel.split("/")) - os.makedirs(os.path.dirname(path), exist_ok=True) - with open(path, "wb") as f: - f.write(b"x" * size) - return path - - def run_assets(self, decoder=None): - """Run assets() with a fake exporter; return (source, pool directory) per ttpf call. With decoder, that is - the decoder digest for the run (the model and texture stubs get its record, so only the pools can differ).""" - calls = [] - digest = decoder or make_game.decoder_digest() - for rel in make_game.MODEL_ARCHIVES: - stem = os.path.splitext(os.path.basename(rel))[0] - for mode in ("models", "textures"): - with open(os.path.join(self.out, stem, mode, make_game.DECODER_RECORD), "w") as f: - f.write(digest) - - def fake_run(cmd, *a, **k): - if cmd[1] == "ttpf": - src, dest = cmd[2], cmd[3] - pool_dir = os.path.join(dest, os.path.splitext(os.path.basename(src))[0]) - os.makedirs(pool_dir, exist_ok=True) - with open(os.path.join(pool_dir, "manifest.json"), "w") as f: - json.dump({"src": src, "Count": 0, "Textures": []}, f) - calls.append((src, pool_dir)) - - with mock.patch.object(make_game, "rpf9dump", lambda w: "rpf9dump"), \ - mock.patch.object(make_game, "run", fake_run), \ - mock.patch.object(make_game.shutil, "which", lambda n: None), \ - mock.patch.object(make_game, "log", lambda *a: None), \ - mock.patch.object(make_game, "decoder_digest", lambda: digest), \ - mock.patch.object(ttpf_assets, "complete_pool", lambda *a: (0, 0)): - make_game.assets(self.game, self.work, False, 1) - return calls - - def test_same_basename_in_two_folders_exports_both(self): - a = self.pool("data/ttdb/A/pool.ttpf") - b = self.pool("data/ttdb/B/pool.ttpf", 101) - calls = self.run_assets() - self.assertEqual([src for src, _ in calls], [a, b]) - dirs = [d for _, d in calls] - self.assertEqual(len(set(dirs)), 2) - for src, d in calls: - self.assertEqual(os.path.basename(d), "pool") - self.assertTrue(os.path.isfile(os.path.join(d, "manifest.json")), src) - # A resumed build finds both manifests and must not export either pool again. - self.assertEqual(self.run_assets(), []) - - def test_unique_pool_keeps_its_existing_output_folder(self): - p = self.pool("data/ttdb/pool.ttpf") - self.assertEqual(self.run_assets(), [(p, os.path.join(self.out, "ttpf", "pool"))]) - - def test_same_basename_in_different_packs_stays_separate(self): - a = self.pool("pack/a/data/ttdb/pool.ttpf") - b = self.pool("pack/b/data/ttdb/pool.ttpf", 101) - self.assertEqual([d for _, d in self.run_assets()], [ - os.path.join(self.out, "ttpf_pack", "a", "pool"), - os.path.join(self.out, "ttpf_pack", "b", "pool"), - ]) - - def test_collision_is_scoped_to_one_destination_namespace(self): - loose = self.pool("data/ttdb/pool.ttpf") - packed = self.pool("pack/a/data/ttdb/pool.ttpf", 101) - self.assertEqual([d for _, d in self.run_assets()], [ - os.path.join(self.out, "ttpf", "pool"), - os.path.join(self.out, "ttpf_pack", "a", "pool"), - ]) - self.assertEqual(len({loose, packed}), 2) - - def test_another_decoder_exports_the_pool_again(self): - p = self.pool("data/ttdb/pool.ttpf") - pool_dir = os.path.join(self.out, "ttpf", "pool") - self.assertEqual(self.run_assets("d1"), [(p, pool_dir)]) - with open(os.path.join(pool_dir, make_game.DECODER_RECORD), encoding="utf-8") as f: - self.assertEqual(f.read(), "d1\n") - self.assertEqual(self.run_assets("d1"), []) - # rpf9dump keeps the DDS it finds, so the old decoder's files must be gone before the new export. - self.stub(os.path.join(pool_dir, "000000_old.dds")) - self.assertEqual(self.run_assets("d2"), [(p, pool_dir)]) - self.assertFalse(os.path.exists(os.path.join(pool_dir, "000000_old.dds"))) - with open(os.path.join(pool_dir, make_game.DECODER_RECORD), encoding="utf-8") as f: - self.assertEqual(f.read(), "d2\n") - self.assertEqual(self.run_assets("d2"), []) - - def test_a_pool_without_the_record_exports_again(self): - p = self.pool("data/ttdb/pool.ttpf") - pool_dir = os.path.join(self.out, "ttpf", "pool") - self.run_assets("d1") - os.remove(os.path.join(pool_dir, make_game.DECODER_RECORD)) - self.assertEqual(self.run_assets("d1"), [(p, pool_dir)]) - - def test_a_colliding_pool_keeps_its_own_record(self): - a = self.pool("data/ttdb/A/pool.ttpf") - b = self.pool("data/ttdb/B/pool.ttpf", 101) - dirs = [d for _, d in self.run_assets("d1")] - self.assertEqual(len(set(dirs)), 2) - for d in dirs: - self.assertTrue(os.path.isfile(os.path.join(d, make_game.DECODER_RECORD)), d) - self.assertEqual([src for src, _ in self.run_assets("d2")], [a, b]) - - def test_a_broken_calibration_profile_stops_the_build_with_one_error_line(self): - # The profile is hand-written, so a typo must name the file in one ERROR line, not raise a JSONDecodeError. - self.pool("data/ttdb/pool.ttpf") - with open(os.path.join(self.work, "bcpack-calibration.json"), "w", encoding="utf-8") as f: - f.write("{") - stderr = io.StringIO() - with contextlib.redirect_stderr(stderr), self.assertRaises(SystemExit) as caught: - self.run_assets() - self.assertEqual(caught.exception.code, 1) - self.assertIn("ERROR:", stderr.getvalue()) - self.assertIn("bcpack-calibration.json", stderr.getvalue()) - self.assertNotIn("Traceback", stderr.getvalue()) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/test_make_game_container.py b/tests/test_make_game_container.py deleted file mode 100644 index 4dffea0e7..000000000 --- a/tests/test_make_game_container.py +++ /dev/null @@ -1,209 +0,0 @@ -"""Unit tests for make_game.py's packaged-container message: a store .xvc (an XVD file) given as --game, found by ---find, or sitting alone in the folder given, is named as an encrypted container instead of "not found". - -The headers are synthetic: 4 KiB with only the fields make_game reads. No game file is needed. - - python -I tests/test_make_game_container.py -""" -import io -import os -import struct -import sys -import tempfile -import unittest -from contextlib import redirect_stderr, redirect_stdout -from unittest.mock import patch - -ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) -if ROOT not in sys.path: - sys.path.insert(0, ROOT) -import make_game - - -def xvd_bytes(*, flags=0x41, content_type=1, xvc_data_length=0x1000, version=(1, 2, 0, 1), magic=b"msft-xvd", - size=0x1000): - """A synthetic XVD header: zero signature, then the fields make_game reads at their file offsets.""" - b = bytearray(max(size, 0x1000)) - b[0x200:0x208] = magic - struct.pack_into(" None: - self.tmp = tempfile.TemporaryDirectory() - self.addCleanup(self.tmp.cleanup) - self.game_dir = os.path.join(self.tmp.name, "game") - self.out_dir = os.path.join(self.tmp.name, "out") - self.work_dir = os.path.join(self.tmp.name, "work") - os.makedirs(self.game_dir, exist_ok=True) - - def test_dry_run_check_flag_exits_cleanly_without_invoking_build_stages(self) -> None: - dummy_version = { - "title": "Grand Theft Auto VI", - "version": "1.0.2.1", - "files": {}, - "expected_exe": "game_scarlett_master.exe", - } - argv = ["make_game.py", "--game", self.game_dir, "--check"] - with mock.patch.object(sys, "argv", argv), \ - mock.patch("make_game.below_normal"), \ - mock.patch("make_game.check", return_value=dummy_version) as mock_check, \ - mock.patch("make_game.preflight") as mock_preflight, \ - mock.patch("make_game.shaders") as mock_shaders, \ - mock.patch("make_game.assets") as mock_assets, \ - mock.patch("make_game.runtime") as mock_runtime, \ - mock.patch("make_game.pipelines") as mock_pipelines, \ - mock.patch("make_game.log"): - ret = make_game.main() - self.assertEqual(ret, 0) - mock_check.assert_called_once_with(os.path.abspath(self.game_dir), False) - mock_preflight.assert_not_called() - mock_shaders.assert_not_called() - mock_assets.assert_not_called() - mock_runtime.assert_not_called() - mock_pipelines.assert_not_called() - self.assertFalse(os.path.exists(self.out_dir)) - self.assertFalse(os.path.exists(self.work_dir)) - - def test_dry_run_full_check_passes_full_flag_and_halts_before_build(self) -> None: - dummy_version = { - "title": "Grand Theft Auto VI", - "version": "1.0.2.1", - "files": {}, - "expected_exe": "game_scarlett_master.exe", - } - argv = ["make_game.py", "--game", self.game_dir, "--check", "--full-check"] - with mock.patch.object(sys, "argv", argv), \ - mock.patch("make_game.below_normal"), \ - mock.patch("make_game.check", return_value=dummy_version) as mock_check, \ - mock.patch("make_game.preflight") as mock_preflight, \ - mock.patch("make_game.shaders") as mock_shaders, \ - mock.patch("make_game.assets") as mock_assets, \ - mock.patch("make_game.runtime") as mock_runtime, \ - mock.patch("make_game.pipelines") as mock_pipelines, \ - mock.patch("make_game.log"): - ret = make_game.main() - self.assertEqual(ret, 0) - mock_check.assert_called_once_with(os.path.abspath(self.game_dir), True) - mock_preflight.assert_not_called() - mock_shaders.assert_not_called() - mock_assets.assert_not_called() - mock_runtime.assert_not_called() - mock_pipelines.assert_not_called() - - def test_dry_run_check_failure_aborts_immediately_without_side_effects(self) -> None: - argv = ["make_game.py", "--game", self.game_dir, "--check"] - stderr_buf = io.StringIO() - with mock.patch.object(sys, "argv", argv), \ - mock.patch("make_game.below_normal"), \ - mock.patch("make_game.load_version", side_effect=SystemExit(1)), \ - mock.patch("sys.stderr", stderr_buf), \ - mock.patch("make_game.preflight") as mock_preflight, \ - mock.patch("make_game.shaders") as mock_shaders: - with self.assertRaises(SystemExit) as ctx: - make_game.main() - self.assertEqual(ctx.exception.code, 1) - mock_preflight.assert_not_called() - mock_shaders.assert_not_called() - - def test_dry_run_find_dumps_mode_scans_without_invoking_check_or_build(self) -> None: - found_sample = [ - (os.path.join(self.tmp.name, "dump1"), {"title": "Title 1", "version": "1.0.2.1"}), - (os.path.join(self.tmp.name, "dump2"), {"title": "Title 2", "version": "1.0.2.1"}), - ] - argv = ["make_game.py", "--find"] - stdout_buf = io.StringIO() - with mock.patch.object(sys, "argv", argv), \ - mock.patch("make_game.below_normal"), \ - mock.patch("make_game.find_dumps", return_value=found_sample) as mock_find, \ - mock.patch("sys.stdout", stdout_buf), \ - mock.patch("make_game.check") as mock_check, \ - mock.patch("make_game.preflight") as mock_preflight: - ret = make_game.main() - self.assertEqual(ret, 0) - mock_find.assert_called_once() - mock_check.assert_not_called() - mock_preflight.assert_not_called() - output = stdout_buf.getvalue() - self.assertIn("Title 1 1.0.2.1", output) - self.assertIn("Title 2 1.0.2.1", output) - self.assertIn("2 found", output) - - def test_explicit_dry_run_flag_validation(self) -> None: - argv = ["make_game.py", "--dry-run"] - stderr_buf = io.StringIO() - with mock.patch.object(sys, "argv", argv), \ - mock.patch("sys.stderr", stderr_buf): - with self.assertRaises(SystemExit) as ctx: - make_game.main() - self.assertEqual(ctx.exception.code, 2) - self.assertIn("unrecognized arguments: --dry-run", stderr_buf.getvalue()) - - def test_simulated_dry_run_wrapper_invokes_check_only(self) -> None: - def invoke_with_dry_run(args: list[str]) -> tuple[int, bool]: - clean_args = [] - is_dry = False - for a in args: - if a == "--dry-run": - is_dry = True - clean_args.append("--check") - else: - clean_args.append(a) - with mock.patch.object(sys, "argv", ["make_game.py", *clean_args]), \ - mock.patch("make_game.below_normal"), \ - mock.patch("make_game.check", return_value={"expected_exe": "g.exe"}), \ - mock.patch("make_game.preflight") as mock_pf, \ - mock.patch("make_game.log"): - code = make_game.main() - return code, mock_pf.called - - ret_code, ran_preflight = invoke_with_dry_run(["--game", self.game_dir, "--dry-run"]) - self.assertEqual(ret_code, 0) - self.assertFalse(ran_preflight) - - -class SkipAssetsAndStageIsolationTest(unittest.TestCase): - """Test skipping asset processing and isolating pipeline stages.""" - - def setUp(self) -> None: - self.tmp = tempfile.TemporaryDirectory() - self.addCleanup(self.tmp.cleanup) - self.game_dir = os.path.join(self.tmp.name, "game") - self.out_dir = os.path.join(self.tmp.name, "out") - self.work_dir = os.path.join(self.tmp.name, "work") - os.makedirs(self.game_dir, exist_ok=True) - os.makedirs(self.out_dir, exist_ok=True) - os.makedirs(self.work_dir, exist_ok=True) - - def test_stages_omitting_assets_completely_skips_asset_stage(self) -> None: - argv = [ - "make_game.py", - "--game", self.game_dir, - "--out", self.out_dir, - "--work", self.work_dir, - "--stages", "shaders,runtime,pipelines", - ] - with mock.patch.object(sys, "argv", argv), \ - mock.patch("make_game.below_normal"), \ - mock.patch("make_game.check", return_value={"expected_exe": "game.exe"}), \ - mock.patch("make_game.preflight"), \ - mock.patch("make_game.verify_runtime_build"), \ - mock.patch("make_game.shaders") as mock_shaders, \ - mock.patch("make_game.assets") as mock_assets, \ - mock.patch("make_game.runtime") as mock_runtime, \ - mock.patch("make_game.pipelines") as mock_pipelines, \ - mock.patch("make_game.log"): - ret = make_game.main() - self.assertEqual(ret, 0) - mock_shaders.assert_called_once() - mock_assets.assert_not_called() - mock_runtime.assert_called_once() - mock_pipelines.assert_called_once() - - def test_skip_assets_preflight_bypasses_dotnet_sdk_and_submodule_checks(self) -> None: - # The runtime stage is Windows-only, and preflight refuses it elsewhere before any check this test is - # about; with no Windows-only stages the same checks run on every system. - with mock.patch("sys.version_info", (3, 12, 0)), \ - mock.patch.object(make_game, "WINDOWS_ONLY", ()), \ - mock.patch.object(make_game, "visual_cpp_tools_ok", return_value=True), \ - mock.patch.object(make_game, "dotnet_sdk_ok") as mock_dotnet, \ - mock.patch.object(make_game, "ensure_submodule") as mock_submodule, \ - mock.patch.object(make_game, "tool_available", return_value=True), \ - mock.patch.object(make_game, "pipeline_check_exe", return_value="/bin/vk_pipeline_check"), \ - mock.patch("shutil.which", return_value="/usr/bin/tool"), \ - mock.patch("shutil.disk_usage", return_value=mock.Mock(free=100 * (2**30))): - make_game.preflight(["shaders", "pipelines"], self.work_dir, wav=True) # no runtime: Windows-only - mock_dotnet.assert_not_called() - mock_submodule.assert_not_called() - - def test_skip_assets_preflight_avoids_ffmpeg_requirement_even_when_wav_requested(self) -> None: - with mock.patch("sys.version_info", (3, 12, 0)), \ - mock.patch.object(make_game, "dotnet_sdk_ok", return_value=True), \ - mock.patch.object(make_game, "tool_available", return_value=True), \ - mock.patch("shutil.which", side_effect=lambda cmd: None if cmd == "ffmpeg" else "/bin/ok"), \ - mock.patch("shutil.disk_usage", return_value=mock.Mock(free=50 * (2**30))): - make_game.preflight(["shaders"], self.work_dir, wav=True) - - def test_skip_assets_preflight_reduces_disk_space_requirement(self) -> None: - stderr_buf = io.StringIO() - with mock.patch("sys.version_info", (3, 12, 0)), \ - mock.patch.object(make_game, "dotnet_sdk_ok", return_value=True), \ - mock.patch.object(make_game, "ensure_submodule"), \ - mock.patch.object(make_game, "tool_available", return_value=True), \ - mock.patch("shutil.which", return_value="/bin/ok"), \ - mock.patch("sys.stderr", stderr_buf), \ - mock.patch("shutil.disk_usage", return_value=mock.Mock(free=50 * (2**30))): - with self.assertRaises(SystemExit) as ctx: - make_game.preflight(["shaders", "assets"], self.work_dir, wav=False) - self.assertEqual(ctx.exception.code, 1) - self.assertIn("400 GB is needed", stderr_buf.getvalue()) - - with mock.patch("sys.version_info", (3, 12, 0)), \ - mock.patch.object(make_game, "tool_available", return_value=True), \ - mock.patch("shutil.which", return_value="/bin/ok"), \ - mock.patch("shutil.disk_usage", return_value=mock.Mock(free=50 * (2**30))): - make_game.preflight(["shaders"], self.work_dir, wav=False) - - def test_skip_assets_cli_argument_rejection(self) -> None: - argv = ["make_game.py", "--skip-assets"] - stderr_buf = io.StringIO() - with mock.patch.object(sys, "argv", argv), \ - mock.patch("sys.stderr", stderr_buf): - with self.assertRaises(SystemExit) as ctx: - make_game.main() - self.assertEqual(ctx.exception.code, 2) - self.assertIn("unrecognized arguments: --skip-assets", stderr_buf.getvalue()) - - def test_skip_assets_filter_logic_generates_isolated_stage_list(self) -> None: - def filter_stages(all_stages: list[str], skip_assets: bool) -> list[str]: - if skip_assets: - return [s for s in all_stages if s != "assets"] - return list(all_stages) - - stages_with_skip = filter_stages(make_game.STAGES, skip_assets=True) - self.assertNotIn("assets", stages_with_skip) - self.assertEqual(stages_with_skip, ["check", "shaders", "runtime", "pipelines"]) - - stages_without_skip = filter_stages(make_game.STAGES, skip_assets=False) - self.assertIn("assets", stages_without_skip) - self.assertEqual(stages_without_skip, make_game.STAGES) - - -class PipelineStageIsolationTest(unittest.TestCase): - """Test pipelines stage isolation, driver cache creation, and error boundaries.""" - - def setUp(self) -> None: - self.tmp = tempfile.TemporaryDirectory() - self.addCleanup(self.tmp.cleanup) - self.work_dir = os.path.join(self.tmp.name, "work") - self.out_dir = os.path.join(self.tmp.name, "out") - os.makedirs(self.work_dir, exist_ok=True) - os.makedirs(self.out_dir, exist_ok=True) - - def test_pipelines_fails_when_spirv_index_is_missing(self) -> None: - dummy_exe = os.path.join(self.tmp.name, "vk_pipeline_check.exe") - with open(dummy_exe, "w", encoding="utf-8") as f: - f.write("dummy") - with mock.patch("make_game.pipeline_check_exe", return_value=dummy_exe): - stderr_buf = io.StringIO() - with mock.patch("sys.stderr", stderr_buf): - with self.assertRaises(SystemExit) as ctx: - make_game.pipelines(self.work_dir, self.out_dir) - self.assertEqual(ctx.exception.code, 1) - self.assertIn("No translated shaders yet: run the shaders stage first.", stderr_buf.getvalue()) - - def test_pipelines_fails_when_pipeline_check_exe_not_built_on_windows(self) -> None: - spirv_dir = os.path.join(self.work_dir, "shaders", "spirv") - os.makedirs(spirv_dir, exist_ok=True) - with open(os.path.join(spirv_dir, "index.json"), "w", encoding="utf-8") as f: - f.write("{}") - - with mock.patch("make_game.pipeline_check_exe", return_value=None), \ - mock.patch.object(make_game.os, "name", "nt"): - stderr_buf = io.StringIO() - with mock.patch("sys.stderr", stderr_buf): - with self.assertRaises(SystemExit) as ctx: - make_game.pipelines(self.work_dir, self.out_dir) - self.assertEqual(ctx.exception.code, 1) - self.assertIn("vk_pipeline_check.exe wasn't built", stderr_buf.getvalue()) - - def test_pipelines_fails_when_pipeline_check_exe_not_built_on_posix(self) -> None: - spirv_dir = os.path.join(self.work_dir, "shaders", "spirv") - os.makedirs(spirv_dir, exist_ok=True) - with open(os.path.join(spirv_dir, "index.json"), "w", encoding="utf-8") as f: - f.write("{}") - - with mock.patch("make_game.pipeline_check_exe", return_value=None), \ - mock.patch.object(make_game.os, "name", "posix"): - stderr_buf = io.StringIO() - with mock.patch("sys.stderr", stderr_buf): - with self.assertRaises(SystemExit) as ctx: - make_game.pipelines(self.work_dir, self.out_dir) - self.assertEqual(ctx.exception.code, 1) - self.assertIn("vk_pipeline_check wasn't built", stderr_buf.getvalue()) - - def test_pipelines_executes_compiler_isolated_with_expected_command_line(self) -> None: - spirv_dir = os.path.join(self.work_dir, "shaders", "spirv") - os.makedirs(spirv_dir, exist_ok=True) - index_path = os.path.join(spirv_dir, "index.json") - with open(index_path, "w", encoding="utf-8") as f: - f.write('{"shader_0": {}}') # a finished translation is never empty - - dummy_exe = os.path.join(self.tmp.name, "vk_pipeline_check.exe") - with open(dummy_exe, "w", encoding="utf-8") as f: - f.write("binary") - - expected_cache = os.path.join(self.out_dir, "pipeline_cache.bin") - executed_cmds = [] - - def fake_run(args: list[str], **kwargs: object) -> int: - executed_cmds.append(args) - return 0 - - # The usage probe (checker_supports) really launches the checker, so it is stubbed too: CreateProcess on a - # text file named .exe makes native Windows show a modal "Unsupported 16-Bit Application" dialog that blocks - # the run. A checker without --inflight-file is what the old dummy answered. - with mock.patch("make_game.pipeline_check_exe", return_value=dummy_exe), \ - mock.patch("make_game.checker_supports", return_value=False) as supports, \ - mock.patch("make_game.run", side_effect=fake_run), \ - mock.patch.object(make_game.subprocess, "run", side_effect=AssertionError("launched the dummy")), \ - mock.patch("make_game.log"): - make_game.pipelines(self.work_dir, self.out_dir) - - supports.assert_called_once() - self.assertEqual(len(executed_cmds), 1) - self.assertEqual(executed_cmds[0], [dummy_exe, spirv_dir, expected_cache]) - - def test_pipelines_stage_alone_invokes_no_asset_or_shader_compilers(self) -> None: - game_dir = os.path.join(self.tmp.name, "game") - os.makedirs(game_dir, exist_ok=True) - argv = [ - "make_game.py", - "--game", game_dir, - "--out", self.out_dir, - "--work", self.work_dir, - "--stages", "pipelines", - ] - with mock.patch.object(sys, "argv", argv), \ - mock.patch("make_game.below_normal"), \ - mock.patch("make_game.check", return_value={"expected_exe": "game.exe"}), \ - mock.patch("make_game.preflight"), \ - mock.patch("make_game.shaders") as mock_shaders, \ - mock.patch("make_game.assets") as mock_assets, \ - mock.patch("make_game.runtime") as mock_runtime, \ - mock.patch("make_game.pipelines") as mock_pipelines, \ - mock.patch("make_game.log"): - ret = make_game.main() - self.assertEqual(ret, 0) - mock_shaders.assert_not_called() - mock_assets.assert_not_called() - mock_runtime.assert_not_called() - mock_pipelines.assert_called_once_with(os.path.abspath(self.work_dir), os.path.abspath(self.out_dir), - mock.ANY, runtime_build=None) - - -class StageResumptionAndStepIsolationTest(unittest.TestCase): - """Test step resumption markers and stage decoupling without invoking external tools.""" - - def setUp(self) -> None: - self.tmp = tempfile.TemporaryDirectory() - self.addCleanup(self.tmp.cleanup) - self.game_dir = os.path.join(self.tmp.name, "game") - self.work_dir = os.path.join(self.tmp.name, "work") - self.out_dir = os.path.join(self.tmp.name, "out") - os.makedirs(self.game_dir, exist_ok=True) - os.makedirs(self.work_dir, exist_ok=True) - os.makedirs(self.out_dir, exist_ok=True) - - def test_shaders_stage_skips_finished_steps_based_on_markers(self) -> None: - dxbc_dir = os.path.join(self.work_dir, "shaders", "dxbc") - spirv_dir = os.path.join(self.work_dir, "shaders", "spirv") - os.makedirs(os.path.join(dxbc_dir, "disasm")) - os.makedirs(spirv_dir, exist_ok=True) - - with open(os.path.join(dxbc_dir, "index.json"), "w", encoding="utf-8") as f: - f.write('[{"file": "shader.dxbc"}]') - with open(os.path.join(dxbc_dir, "fssm_index.json"), "w", encoding="utf-8") as f: - f.write('[{"name": "shader"}]') - with open(os.path.join(dxbc_dir, "disasm", "shader.s"), "w", encoding="utf-8", newline="\n") as f: - f.write("synthetic listing\n") - with open(os.path.join(dxbc_dir, "disasm.done"), "w", encoding="utf-8") as f: - f.write("test llvm-mc 21\n") - with open(os.path.join(spirv_dir, "index.json"), "w", encoding="utf-8") as f: - f.write('{"shader": {}}') # a bare {} is an empty merge and is translated again (translated_index_is_empty) - with open(os.path.join(spirv_dir, "wave64_emulate.txt"), "w", encoding="utf-8") as f: - f.write("off\n") - with open(os.path.join(spirv_dir, "translation_sources.sha256"), "w", encoding="utf-8") as f: - f.write(make_game.translation_sources_digest() + "\n") - - with mock.patch("make_game.py") as mock_py, \ - mock.patch("make_game.llvm_mc_signature", return_value="test llvm-mc 21"), \ - mock.patch("make_game.translate") as mock_translate, \ - mock.patch("make_game.log"): - make_game.shaders(self.game_dir, self.work_dir, jobs=2, emulate=False, keep_emulated=True) - mock_py.assert_not_called() - mock_translate.assert_not_called() - - def test_shaders_step_invalidation_when_early_marker_missing(self) -> None: - dxbc_dir = os.path.join(self.work_dir, "shaders", "dxbc") - spirv_dir = os.path.join(self.work_dir, "shaders", "spirv") - os.makedirs(dxbc_dir, exist_ok=True) - os.makedirs(spirv_dir, exist_ok=True) - - disasm_done = os.path.join(dxbc_dir, "disasm.done") - spirv_index = os.path.join(spirv_dir, "index.json") - with open(disasm_done, "w", encoding="utf-8") as f: - f.write("done\n") - with open(spirv_index, "w", encoding="utf-8") as f: - f.write("{}\n") - - fake_py_calls = [] - - def fake_py(tool: str, *args: str) -> None: - fake_py_calls.append(tool) - if tool == "shader_carve.py": - with open(os.path.join(dxbc_dir, "index.json"), "w", encoding="utf-8") as f: - f.write('[{"file": "shader.dxbc"}]') - elif tool == "fssm_unpack.py": - with open(os.path.join(dxbc_dir, "fssm_index.json"), "w", encoding="utf-8") as f: - f.write('[{"name": "shader"}]') - elif tool == "shader_disasm.py": - disasm = os.path.join(dxbc_dir, "disasm") - os.makedirs(disasm, exist_ok=True) - with open(os.path.join(disasm, "shader.s"), "w", encoding="utf-8", newline="\n") as f: - f.write("synthetic listing\n") - - with mock.patch("make_game.py", side_effect=fake_py), \ - mock.patch("make_game.llvm_mc_signature", return_value="test llvm-mc 21"), \ - mock.patch("make_game.translate") as mock_translate, \ - mock.patch("make_game.need"), \ - mock.patch("make_game.log"): - make_game.shaders(self.game_dir, self.work_dir, jobs=1, emulate=False, keep_emulated=False) - - self.assertIn("shader_carve.py", fake_py_calls) - self.assertIn("fssm_unpack.py", fake_py_calls) - - def test_assets_stage_skips_existing_markers(self) -> None: - assets_dir = os.path.join(self.work_dir, "assets") - audio_dir = os.path.join(assets_dir, "audio") - os.makedirs(audio_dir, exist_ok=True) - - for rel in make_game.MODEL_ARCHIVES: - name = os.path.splitext(os.path.basename(rel))[0] - for mode in ("models", "textures"): - dest = os.path.join(assets_dir, name, mode) - os.makedirs(dest, exist_ok=True) - with open(os.path.join(dest, "manifest.json"), "w", encoding="utf-8") as f: - f.write("{}") - with open(os.path.join(dest, make_game.DECODER_RECORD), "w", encoding="utf-8") as f: - f.write(make_game.decoder_digest()) - - with open(os.path.join(audio_dir, "audio_manifest.json"), "w", encoding="utf-8") as f: - f.write("{}") - with open(os.path.join(audio_dir, "ogg.done"), "w", encoding="utf-8") as f: - f.write("done\n") - with open(os.path.join(audio_dir, "xma.done"), "w", encoding="utf-8") as f: - f.write("done\n") - - with mock.patch("make_game.rpf9dump") as exporter, \ - mock.patch("make_game.run") as mock_run, \ - mock.patch("make_game.py") as mock_py, \ - mock.patch("shutil.which", return_value=None), \ - mock.patch("make_game.log"): - make_game.assets(self.game_dir, self.work_dir, wav=False, jobs=1) - exporter.assert_not_called() - mock_run.assert_not_called() - mock_py.assert_not_called() - - def test_texture_pools_resume_only_when_their_listed_dds_files_exist(self) -> None: - assets = Path(self.work_dir, "assets") - audio = assets / "audio" - audio.mkdir(parents=True) - for marker in ("audio_manifest.json", "ogg.done", "xma.done"): - (audio / marker).touch() - - # Identically named pools in the base game and a pack have distinct completion markers. - game = Path(self.game_dir) - base_source = game / "data" / "ttdb" / "sample.ttpf" - pack_source = game / "pack" / "story" / "data" / "ttdb" / "sample.ttpf" - base_dest = assets / "ttpf" - pack_dest = assets / "ttpf_pack" / "story" - for src, dest in ((base_source, base_dest), (pack_source, pack_dest)): - src.parent.mkdir(parents=True) - src.touch() - (dest / "sample").mkdir(parents=True) - (dest / "sample" / "first.dds").write_bytes(b"completed sibling") - (dest / "sample" / make_game.DECODER_RECORD).write_text(make_game.decoder_digest(), encoding="utf-8") - (pack_dest / "sample" / "second.dds").mkdir() - - valid = json.dumps({"Count": 2, "Textures": [{"File": "first.dds"}, {"File": None}]}) - legacy = json.dumps({"Count": 2, "Textures": [{"File": "first.dds"}, {"File": "second.dds"}]}) - base_call = mock.call(["rpf9dump", "ttpf", str(base_source), str(base_dest)]) - pack_call = mock.call(["rpf9dump", "ttpf", str(pack_source), str(pack_dest)]) - def publish_catalog(cmd): - (Path(cmd[3]) / "sample" / "manifest.json").write_text(valid, encoding="utf-8") - - for case, base_manifest, pack_manifest, expected in ( - ("complete including skipped rows", valid, valid, []), - ("listed DDS is missing", legacy, valid, [base_call]), - ("listed DDS is a directory", valid, legacy, [pack_call]), - ("missing texture list", "{}", valid, [base_call]), - ("incomplete row list", '{"Count": 2, "Textures": [{"File": "first.dds"}]}', valid, [base_call]), - ("missing File field", valid, '{"Count": 1, "Textures": [{}]}', [pack_call]), - ("incomplete JSON", valid, "{", [pack_call]), - ): - with self.subTest(case=case): - (base_dest / "sample" / "manifest.json").write_text(base_manifest, encoding="utf-8") - (pack_dest / "sample" / "manifest.json").write_text(pack_manifest, encoding="utf-8") - with mock.patch.object(make_game, "MODEL_ARCHIVES", ()), \ - mock.patch.object(make_game, "rpf9dump", return_value="rpf9dump"), \ - mock.patch.object(make_game, "run", side_effect=publish_catalog) as run, \ - mock.patch.object(make_game, "log"), mock.patch("shutil.which", return_value=None): - make_game.assets(self.game_dir, self.work_dir, wav=False, jobs=1) - self.assertEqual(run.call_args_list, expected) - - def test_pending_exports_refresh_the_existing_helper_once(self) -> None: - # Built under the repo (not --work) so `dotnet -o` is not pointed at a locked remote path. - output = os.path.join(self.tmp.name, "tools", "rpf9dump", "bin", "Release", "net8.0") - os.makedirs(output) - exe = os.path.join(output, "rpf9dump.exe" if os.name == "nt" else "rpf9dump") - with open(exe, "wb") as f: - f.write(b"previous build") - os.makedirs(os.path.join(self.tmp.name, "third_party", "rpf9-explorer", "Core")) - os.makedirs(os.path.join(self.work_dir, "assets", "audio")) - - with mock.patch.object(make_game, "ROOT", self.tmp.name), \ - mock.patch.object(make_game, "MODEL_ARCHIVES", ["scene.rpf"]), \ - mock.patch.object(make_game, "need"), mock.patch.object(make_game, "py"), \ - mock.patch.object(make_game, "run") as run, mock.patch("shutil.which", return_value=None): - make_game.assets(self.game_dir, self.work_dir, wav=False, jobs=1) - - commands = [call.args[0] for call in run.call_args_list] - self.assertEqual(commands[0][:2], ["dotnet", "build"]) - self.assertIn("-o", commands[0]) - self.assertEqual(commands[0][commands[0].index("-o") + 1], output) - self.assertEqual([(cmd[0], cmd[1]) for cmd in commands[1:]], - [(exe, mode) for mode in ("models", "textures", "audio", "xma")]) - - def test_drop_removes_existing_marker_files(self) -> None: - p1 = os.path.join(self.work_dir, "m1.txt") - p2 = os.path.join(self.work_dir, "m2.txt") - p3 = os.path.join(self.work_dir, "nonexistent.txt") - with open(p1, "w", encoding="utf-8") as f: - f.write("1") - with open(p2, "w", encoding="utf-8") as f: - f.write("2") - self.assertTrue(os.path.isfile(p1)) - self.assertTrue(os.path.isfile(p2)) - - make_game.drop(p1, p2, p3) - self.assertFalse(os.path.isfile(p1)) - self.assertFalse(os.path.isfile(p2)) - - def test_mark_creates_expected_asset_marker(self) -> None: - marker = os.path.join(self.work_dir, "step.done") - make_game.mark(marker, "custom_step") - - with open(marker, "r", encoding="utf-8") as f: - self.assertEqual(f.read().strip(), "custom_step finished") - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/test_make_game_empty_translation.py b/tests/test_make_game_empty_translation.py deleted file mode 100644 index 0d310226b..000000000 --- a/tests/test_make_game_empty_translation.py +++ /dev/null @@ -1,263 +0,0 @@ -"""make_game.py: an empty translated shader index is not kept, and a later stage refuses one. - -Standard library only; no GPU, no Vulkan SDK, no game data: the shard processes and rdna2spirv.py are mocked. - - python -I tests/test_make_game_empty_translation.py -""" -import io -import json -import os -import sys -import tempfile -import unittest -from unittest import mock - -ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) -sys.path.insert(0, ROOT) -import make_game # noqa: E402 - - -def write(path, text): - os.makedirs(os.path.dirname(path), exist_ok=True) - with open(path, "w", encoding="utf-8") as f: - f.write(text) - - -class Done: - def poll(self): - return 0 - - def wait(self): - return 0 - - def terminate(self): - pass - - def kill(self): - pass - - -class TranslateEmptyIndexTest(unittest.TestCase): - """translate(): a merge that published nothing is an error and must not leave a marker behind.""" - - def setUp(self): - tmp = tempfile.TemporaryDirectory() - self.addCleanup(tmp.cleanup) - self.disasm = os.path.join(tmp.name, "dxbc", "disasm") - self.spirv = os.path.join(tmp.name, "spirv") - os.makedirs(self.disasm) - - def translate_with_index(self, text): - def fake_py(tool, *args): - if "--merge" in args: - write(os.path.join(self.spirv, "index.json"), text) - - with mock.patch.object(make_game, "log", lambda *a: None), \ - mock.patch.object(make_game, "py", side_effect=fake_py), \ - mock.patch.object(make_game.subprocess, "Popen", lambda *a, **k: Done()): - make_game.translate(self.disasm, self.spirv, 1) - - def test_an_empty_index_is_removed_with_the_plan_and_the_retry_fails(self): - for _ in range(2): - with self.assertRaises(SystemExit) as cm: - self.translate_with_index("{}") - self.assertEqual(cm.exception.code, 1) - self.assertFalse(os.path.exists(os.path.join(self.spirv, "index.json"))) - self.assertFalse(os.path.exists(os.path.join(self.spirv, make_game.SHARD_PLAN))) - - def test_an_unreadable_index_is_removed(self): - with self.assertRaises(SystemExit) as cm: - self.translate_with_index("not json") - self.assertEqual(cm.exception.code, 1) - self.assertFalse(os.path.exists(os.path.join(self.spirv, "index.json"))) - - def test_a_non_empty_index_is_kept(self): - self.translate_with_index(json.dumps({"shader_0": {"stage": "ps"}})) - with open(os.path.join(self.spirv, "index.json"), encoding="utf-8") as f: - self.assertEqual(json.load(f), {"shader_0": {"stage": "ps"}}) - - def test_a_failed_shard_removes_a_stale_index_and_skips_merge(self): - index = os.path.join(self.spirv, "index.json") - write(index, json.dumps({"old": {}})) - states = iter([None, 1]) - - class FailingShard(Done): - def poll(self): - return next(states, 1) - - def wait(self): - return 1 - - err = io.StringIO() - merge_py = mock.Mock() - with mock.patch.object(make_game, "log", lambda *a: None), \ - mock.patch.object(make_game, "py", merge_py), \ - mock.patch.object(make_game.time, "sleep", lambda *a: None), \ - mock.patch.object(make_game.subprocess, "Popen", lambda *a, **k: FailingShard()), \ - mock.patch("sys.stderr", err), \ - self.assertRaises(SystemExit) as cm: - make_game.translate(self.disasm, self.spirv, 1) - self.assertEqual(cm.exception.code, 1) - self.assertIn("rdna2spirv.py: shard 0 exited with 1.", err.getvalue()) - self.assertFalse(os.path.exists(index)) - merge_py.assert_not_called() - - -class TranslateLockedIndexTest(unittest.TestCase): - """translate(): an index that cannot be read or removed (on Windows, a file an antivirus scan or the indexer - holds) ends the stage with its own message naming the file once, not with a PermissionError traceback.""" - - setUp = TranslateEmptyIndexTest.setUp - translate_with_index = TranslateEmptyIndexTest.translate_with_index - - def locked(self, path): - return PermissionError(13, "Permission denied", path) - - def failure(self, text, open_locked=False, shard_code=0): - index = os.path.join(self.spirv, "index.json") - real_remove, real_open = os.remove, open - - def remove(path, *a, **k): - if os.path.abspath(path) == os.path.abspath(index): - raise self.locked(path) - return real_remove(path, *a, **k) - - def opener(path, mode="r", *a, **k): - if open_locked and mode == "r" and os.path.abspath(path) == os.path.abspath(index): - raise self.locked(path) - return real_open(path, mode, *a, **k) - - class Exited(Done): - def poll(self): - return shard_code - - def wait(self): - return shard_code - - err = io.StringIO() - merge_py = mock.Mock() - with mock.patch.object(make_game.os, "remove", remove), \ - mock.patch("builtins.open", opener), \ - mock.patch.object(make_game.subprocess, "Popen", lambda *a, **k: Exited()), \ - mock.patch("sys.stderr", err), \ - self.assertRaises(SystemExit) as cm: - if shard_code: - write(index, text) - with mock.patch.object(make_game, "log", lambda *a: None), \ - mock.patch.object(make_game, "py", merge_py): - make_game.translate(self.disasm, self.spirv, 1) - else: - self.translate_with_index(text) - if shard_code: - merge_py.assert_not_called() - self.assertEqual(cm.exception.code, 1) - message = err.getvalue() - self.assertIn(f"{index} could not be removed (Permission denied): delete it before running", message) - self.assertNotIn(repr(index), message) - return message - - def test_an_unopenable_index_that_cannot_be_removed(self): - message = self.failure('{"shader_0": {}}', open_locked=True) - index = os.path.join(self.spirv, "index.json") - self.assertIn(f"--merge wrote an unreadable {index}: Permission denied.", message) - - def test_an_unparsable_index_that_cannot_be_removed(self): - self.assertIn("--merge wrote an unreadable", self.failure("not json")) - - def test_an_empty_index_that_cannot_be_removed(self): - self.assertIn("translated 0 shaders", self.failure("{}")) - - def test_a_stale_index_after_a_failed_shard_that_cannot_be_removed(self): - self.assertIn("rdna2spirv.py: shard 0 exited with 1.", self.failure('{"old": {}}', shard_code=1)) - - -class RequireTranslatedShadersTest(unittest.TestCase): - def setUp(self): - tmp = tempfile.TemporaryDirectory() - self.addCleanup(tmp.cleanup) - self.work = tmp.name - self.spirv = os.path.join(self.work, "shaders", "spirv") - os.makedirs(self.spirv) - - def call(self): - err = io.StringIO() - with mock.patch("sys.stderr", err): - return make_game.require_translated_shaders(self.work), err.getvalue() - - def test_missing_index_names_the_stage(self): - with self.assertRaises(SystemExit) as cm: - self.call() - self.assertEqual(cm.exception.code, 1) - - def test_an_empty_index_is_refused(self): - write(os.path.join(self.spirv, "index.json"), "{}") - with self.assertRaises(SystemExit) as cm: - self.call() - self.assertEqual(cm.exception.code, 1) - - def test_an_unreadable_index_is_refused(self): - write(os.path.join(self.spirv, "index.json"), "not json") - with self.assertRaises(SystemExit) as cm: - self.call() - self.assertEqual(cm.exception.code, 1) - - def test_a_non_empty_index_is_accepted(self): - write(os.path.join(self.spirv, "index.json"), '{"shader_0": {}}') - self.assertEqual(self.call()[0], self.spirv) - - -class ShadersStageTest(unittest.TestCase): - """shaders(): a saved `{}` from a merge that produced nothing is translated again, and its plan goes with it.""" - - def setUp(self): - tmp = tempfile.TemporaryDirectory() - self.addCleanup(tmp.cleanup) - self.work = tmp.name - self.dxbc = os.path.join(self.work, "shaders", "dxbc") - self.spirv = os.path.join(self.work, "shaders", "spirv") - - def index(self): - return os.path.join(self.spirv, "index.json") - - def plan(self): - return os.path.join(self.spirv, make_game.SHARD_PLAN) - - def run_stage(self): - ran = [] - - def fake_py(tool, *args): - if tool == "shader_carve.py": - write(os.path.join(self.dxbc, "index.json"), json.dumps([{"file": "shader.dxbc"}])) - elif tool == "fssm_unpack.py": - write(os.path.join(self.dxbc, "fssm_index.json"), json.dumps([{"name": "shader"}])) - elif tool == "shader_disasm.py": - write(os.path.join(self.dxbc, "disasm", "shader.s"), "synthetic listing\n") - - def fake_translate(disasm, spirv, jobs, emulate=False, fallbacks=()): - ran.append("translate") - write(os.path.join(self.spirv, "index.json"), json.dumps({"shader_0": {"stage": "ps"}})) - - with mock.patch.object(make_game, "py", fake_py), \ - mock.patch.object(make_game, "need", lambda *a: None), \ - mock.patch.object(make_game, "translate", fake_translate), \ - mock.patch.object(make_game, "llvm_mc_signature", return_value="test llvm-mc 21"), \ - mock.patch.object(make_game, "log", lambda *a: None): - make_game.shaders(os.path.join(self.work, "game"), self.work, 2) - return ran - - def test_an_empty_saved_index_is_translated_again_without_its_plan(self): - self.assertEqual(self.run_stage(), ["translate"]) - write(self.index(), "{}") - write(self.plan(), "{}") - self.assertEqual(self.run_stage(), ["translate"]) - self.assertFalse(os.path.exists(self.plan())) - - def test_a_saved_index_that_names_a_shader_is_kept(self): - self.run_stage() - self.assertEqual(self.run_stage(), []) - with open(self.index(), encoding="utf-8") as f: - self.assertEqual(json.load(f), {"shader_0": {"stage": "ps"}}) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/test_make_game_interrupt.py b/tests/test_make_game_interrupt.py deleted file mode 100644 index 53e543b00..000000000 --- a/tests/test_make_game_interrupt.py +++ /dev/null @@ -1,54 +0,0 @@ -"""make_game.py: end of input at a prompt and Ctrl+C give one line, not a traceback (no game files needed). - - python -I tests/test_make_game_interrupt.py -""" -import contextlib -import io -import os -import sys -import unittest -from unittest.mock import patch - -ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) -if ROOT not in sys.path: - sys.path.insert(0, ROOT) -import make_game # noqa: E402 - -COPY = {"title": "Xbox Series package", "version": "1.0.2.1"} - - -class PromptWithoutInput(unittest.TestCase): - def choose(self, found): - err = io.StringIO() - with (patch("make_game.find_dumps", return_value=found), patch("make_game.log"), - patch.object(sys, "stdin", **{"isatty.return_value": True}), - patch("builtins.input", side_effect=EOFError), contextlib.redirect_stdout(io.StringIO()), - contextlib.redirect_stderr(err), self.assertRaises(SystemExit) as stop): - make_game.choose_game() - return stop.exception.code, err.getvalue() - - def test_game_folder_prompt(self): - code, err = self.choose([]) - self.assertEqual(code, 1) - self.assertIn("Give the folder with --game", err) - - def test_which_copy_prompt(self): - code, err = self.choose([("D:/a", COPY), ("D:/b", COPY)]) - self.assertEqual(code, 1) - self.assertIn("choose one with --game", err) - - -class CtrlC(unittest.TestCase): - def test_one_line_and_exit_130(self): - err = io.StringIO() - with patch("make_game.main", side_effect=KeyboardInterrupt), contextlib.redirect_stderr(err): - self.assertEqual(make_game.cli(), 130) - self.assertEqual(err.getvalue().strip(), "Stopped. Run it again to continue where it left off.") - - def test_other_exit_codes_pass_through(self): - with patch("make_game.main", return_value=0): - self.assertEqual(make_game.cli(), 0) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/test_make_game_paths.py b/tests/test_make_game_paths.py deleted file mode 100644 index f37fef0a5..000000000 --- a/tests/test_make_game_paths.py +++ /dev/null @@ -1,144 +0,0 @@ -"""Build destinations must stay outside the game folder, including through directory links. - - python -I tests/test_make_game_paths.py - -Only empty temporary directories are used; no game files or build tools are needed. -""" -from contextlib import ExitStack -import io -import os -import subprocess -import sys -import tempfile -import unittest -from unittest.mock import patch - -ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) -sys.path.insert(0, ROOT) -import make_game - - -class BuildDestinationTest(unittest.TestCase): - def setUp(self): - tmp = tempfile.TemporaryDirectory() - self.addCleanup(tmp.cleanup) - self.root = tmp.name - self.game = os.path.join(self.root, "game") - os.mkdir(self.game) - self.alias = os.path.join(self.root, "game-link") - - def link(self, target, path): - if os.name == "nt": - # Junctions work without Developer Mode or symlink privileges on Windows. - result = subprocess.run(["cmd", "/c", "mklink", "/J", path, target], - capture_output=True, text=True) - if result.returncode: - self.skipTest("cannot create a directory junction: " + result.stderr) - self.addCleanup(os.rmdir, path) - else: - os.symlink(target, path, target_is_directory=True) - self.addCleanup(os.unlink, path) - - @staticmethod - def version(*top_level): - """A version manifest whose files sit in these top-level folders: at a drive-root --game, main() takes the - dump's own entries from the manifest (BUILD-2367), not from os.listdir.""" - return {"expected_exe": top_level[0] + "\\game.exe", - "files": {f"{name}/a.rpf": {} for name in top_level}} - - def run_build(self, game, out, work, rejected, version=None): - argv = ["make_game.py", "--game", game, "--out", out, "--work", work, - "--stages", "runtime", "--no-tui"] - with ExitStack() as stack: - stack.enter_context(patch.object(sys, "argv", argv)) - stack.enter_context(patch("make_game.below_normal")) - stack.enter_context(patch("make_game.check", return_value=version or {})) - stack.enter_context(patch("make_game.log")) - stack.enter_context(patch("make_game.verify_runtime_build")) - preflight = stack.enter_context(patch("make_game.preflight")) - build_runtime = stack.enter_context(patch("make_game.runtime")) - stderr = stack.enter_context(patch("sys.stderr", new_callable=io.StringIO)) - if rejected: - with self.assertRaises(SystemExit) as error: - make_game.main() - self.assertEqual(error.exception.code, 1) - self.assertIn("--out and --work must be outside the game folder", stderr.getvalue()) - preflight.assert_not_called() - build_runtime.assert_not_called() - else: - self.assertEqual(make_game.main(), 0) - preflight.assert_called_once() - build_runtime.assert_called_once() - - def test_destinations_through_game_link_are_rejected(self): - self.link(self.game, self.alias) - for option in ("out", "work"): - for suffix in ("", "new", os.path.join("new", "nested")): - with self.subTest(option=option, suffix=suffix): - destinations = {name: os.path.join(self.root, name) for name in ("out", "work")} - destinations[option] = os.path.join(self.alias, suffix) - self.run_build(self.game, **destinations, rejected=True) - self.assertFalse(os.path.exists(os.path.join(self.game, "new"))) - - def test_game_link_cannot_hide_destinations_in_real_game_folder(self): - self.link(self.game, self.alias) - for option in ("out", "work"): - with self.subTest(option=option): - destinations = {name: os.path.join(self.root, name) for name in ("out", "work")} - destinations[option] = os.path.join(self.game, "new") - self.run_build(self.alias, **destinations, rejected=True) - - def test_link_to_unrelated_output_folder_is_allowed(self): - target = os.path.join(self.root, "output") - os.mkdir(target) - alias = os.path.join(self.root, "output-link") - self.link(target, alias) - self.run_build(self.game, os.path.join(alias, "new"), - os.path.join(self.root, "work"), rejected=False) - - def test_drive_root_game_folder_rules(self): - if os.name != "nt": - self.skipTest("Windows drive root check") - drive = os.path.splitdrive(self.root)[0] + "\\" - content_dir = os.path.join(drive, "Content") - independent_dir = os.path.join(drive, "Leonida_Build") - version = self.version("Content") - # Allowed: destination is an independent folder on the drive root - self.run_build(drive, independent_dir, os.path.join(independent_dir, "work"), rejected=False, version=version) - # Rejected: destination is inside the game dump's own top-level entry - self.run_build(drive, os.path.join(content_dir, "out"), os.path.join(self.root, "work"), rejected=True, - version=version) - # Rejected: destination is the drive root itself - self.run_build(drive, drive, os.path.join(self.root, "work"), rejected=True, version=version) - - def test_drive_root_checks_entries_on_each_volume(self): - if os.name != "nt": - self.skipTest("Windows drive root check") - root = os.path.splitdrive(self.root)[0] + "\\" - other_root = "Z:\\" if root.upper() != "Z:\\" else "Y:\\" - junction = os.path.join(root, "MountedContent") - mounted_content = os.path.join(other_root, "Package") - - def realpath(path): - if os.path.normcase(path) == os.path.normcase(junction): - return mounted_content - return os.path.normpath(path) - - # A junction target on a different volume must not end the search before the matching entry. - for entries, protected in ( - (["MountedContent", "Content"], os.path.join(root, "Content")), - (["Content", "MountedContent"], mounted_content), - ): - version = self.version(*entries) - with patch("os.path.realpath", side_effect=realpath): - for option in ("out", "work"): - with self.subTest(protected=protected, option=option): - destinations = {name: os.path.join(self.root, name) for name in ("out", "work")} - destinations[option] = os.path.join(protected, "build") - self.run_build(root, **destinations, rejected=True, version=version) - self.run_build(root, os.path.join(other_root, "Build"), - os.path.join(other_root, "Scratch"), rejected=False, version=version) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/test_make_game_pick.py b/tests/test_make_game_pick.py deleted file mode 100644 index 3162de3b3..000000000 --- a/tests/test_make_game_pick.py +++ /dev/null @@ -1,189 +0,0 @@ -"""Unit tests for make_game.py --pick: the folder dialog, with a stand-in tkinter and stand-in kdialog/zenity -runs (no display needed). - - python -I tests/test_make_game_pick.py -""" -import io -import os -import sys -import types -import unittest -from contextlib import redirect_stderr -from unittest.mock import MagicMock, patch - -ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) -if ROOT not in sys.path: - sys.path.insert(0, ROOT) -import make_game - - -def fake_tkinter(answers, tk_error=None): - """A tkinter whose folder dialog returns `answers` in turn ("" is a cancel).""" - tk = types.ModuleType("tkinter") - root = MagicMock() - if tk_error: - tk.Tk = MagicMock(side_effect=tk_error) - else: - tk.Tk = MagicMock(return_value=root) - filedialog = types.ModuleType("tkinter.filedialog") - filedialog.askdirectory = MagicMock(side_effect=list(answers)) - messagebox = types.ModuleType("tkinter.messagebox") - messagebox.showwarning = MagicMock() - tk.filedialog, tk.messagebox = filedialog, messagebox - modules = {"tkinter": tk, "tkinter.filedialog": filedialog, "tkinter.messagebox": messagebox} - return modules, root, filedialog, messagebox - - -VERSION = {"title": "Test", "version": "1.0.2.1"} - - -class PickGameTest(unittest.TestCase): - """The Tk dialog: Windows, macOS, and Linux without kdialog or zenity.""" - - def setUp(self): - p = patch("make_game.native_picker", return_value=None) - p.start() - self.addCleanup(p.stop) - - def test_returns_a_supported_folder(self): - modules, root, dialog, warn = fake_tkinter([os.path.join("D:", "game")]) - with patch.dict(sys.modules, modules), patch("make_game.match_version", return_value=VERSION), \ - patch("make_game.log"): - self.assertEqual(make_game.pick_game(), os.path.normpath(os.path.join("D:", "game"))) - self.assertEqual(dialog.askdirectory.call_count, 1) - warn.showwarning.assert_not_called() - root.destroy.assert_called_once() - - def test_asks_again_after_an_unsupported_folder(self): - modules, root, dialog, warn = fake_tkinter(["wrong", "right"]) - with patch.dict(sys.modules, modules), \ - patch("make_game.match_version", side_effect=lambda d: VERSION if d.endswith("right") else None), \ - patch("make_game.log"): - self.assertTrue(make_game.pick_game().endswith("right")) - self.assertEqual(dialog.askdirectory.call_count, 2) - warn.showwarning.assert_called_once() - root.destroy.assert_called_once() - - def test_cancel_stops_with_a_pointer_to_game(self): - modules, root, _, _ = fake_tkinter([""]) - err = io.StringIO() - with patch.dict(sys.modules, modules), redirect_stderr(err), self.assertRaises(SystemExit) as stop: - make_game.pick_game() - self.assertEqual(stop.exception.code, 1) - self.assertIn("--game", err.getvalue()) - root.destroy.assert_called_once() # the hidden window goes even when the build stops - - def test_no_display_stops_with_a_pointer_to_game(self): - modules, _, dialog, _ = fake_tkinter([], tk_error=RuntimeError("no display name")) - err = io.StringIO() - with patch.dict(sys.modules, modules), redirect_stderr(err), self.assertRaises(SystemExit) as stop: - make_game.pick_game() - self.assertEqual(stop.exception.code, 1) - self.assertIn("--game", err.getvalue()) - self.assertIn("no display name", err.getvalue()) - dialog.askdirectory.assert_not_called() - - -def runs(*results): - """A subprocess.run whose calls return (returncode, stdout) from `results` in turn.""" - return MagicMock(side_effect=[types.SimpleNamespace(returncode=c, stdout=o) for c, o in results]) - - -class NativePickerTest(unittest.TestCase): - def env(self, **values): - return patch.dict(os.environ, values, clear=True) - - def test_kde_prefers_kdialog(self): - with self.env(DISPLAY=":0", XDG_CURRENT_DESKTOP="KDE"), patch.object(make_game.os, "name", "posix"), \ - patch.object(make_game.sys, "platform", "linux"), \ - patch("make_game.shutil.which", side_effect=lambda t: "/usr/bin/" + t): - self.assertEqual(make_game.native_picker(), ("kdialog", "/usr/bin/kdialog")) - - def test_other_desktops_prefer_zenity(self): - with self.env(WAYLAND_DISPLAY="wayland-0", XDG_CURRENT_DESKTOP="GNOME"), \ - patch.object(make_game.os, "name", "posix"), patch.object(make_game.sys, "platform", "linux"), \ - patch("make_game.shutil.which", side_effect=lambda t: "/usr/bin/" + t): - self.assertEqual(make_game.native_picker(), ("zenity", "/usr/bin/zenity")) - - def test_takes_whichever_is_installed(self): - with self.env(DISPLAY=":0", XDG_CURRENT_DESKTOP="KDE"), patch.object(make_game.os, "name", "posix"), \ - patch.object(make_game.sys, "platform", "linux"), \ - patch("make_game.shutil.which", side_effect=lambda t: "/usr/bin/zenity" if t == "zenity" else None): - self.assertEqual(make_game.native_picker(), ("zenity", "/usr/bin/zenity")) - - def test_none_without_a_display_or_on_windows_and_macos(self): - which = patch("make_game.shutil.which", return_value="/usr/bin/x") - with self.env(), patch.object(make_game.os, "name", "posix"), \ - patch.object(make_game.sys, "platform", "linux"), which: - self.assertIsNone(make_game.native_picker()) - for name, platform in (("nt", "win32"), ("posix", "darwin")): - with self.env(DISPLAY=":0"), patch.object(make_game.os, "name", name), \ - patch.object(make_game.sys, "platform", platform), which: - self.assertIsNone(make_game.native_picker()) - - -class PickNativeTest(unittest.TestCase): - """The desktop's dialog on Linux, run through kdialog or zenity.""" - - def pick(self, tool, run, version=lambda d: VERSION): - with patch("make_game.native_picker", return_value=(tool, "/usr/bin/" + tool)), \ - patch("make_game.subprocess.run", run), patch("make_game.match_version", side_effect=version), \ - patch("make_game.log"): - return make_game.pick_game() - - def test_kdialog_returns_a_supported_folder(self): - run = runs((0, "/games/leonida\n")) - self.assertEqual(self.pick("kdialog", run), os.path.normpath("/games/leonida")) - cmd = run.call_args[0][0] - self.assertEqual(cmd[0], "/usr/bin/kdialog") - self.assertIn("--getexistingdirectory", cmd) - - def test_zenity_asks_again_from_the_last_folder_after_a_warning(self): - run = runs((0, "/games/wrong\n"), (0, ""), (0, "/games/right\n")) - got = self.pick("zenity", run, version=lambda d: VERSION if d.endswith("right") else None) - self.assertTrue(got.endswith("right")) - ask1, warn, ask2 = (c[0][0] for c in run.call_args_list) - self.assertIn("--directory", ask1) - self.assertIn("--warning", warn) - self.assertIn("--filename=" + os.path.join(os.path.normpath("/games/wrong"), ""), ask2) - - def test_cancel_stops_with_a_pointer_to_game(self): - err = io.StringIO() - with redirect_stderr(err), self.assertRaises(SystemExit) as stop: - self.pick("kdialog", runs((1, ""))) - self.assertEqual(stop.exception.code, 1) - self.assertIn("--game", err.getvalue()) - - def test_a_broken_tool_falls_back_to_tk(self): - modules, root, dialog, _ = fake_tkinter(["/games/leonida"]) - with patch.dict(sys.modules, modules): - self.assertEqual(self.pick("zenity", runs((255, ""))), os.path.normpath("/games/leonida")) - dialog.askdirectory.assert_called_once() - root.destroy.assert_called_once() - - -class PickArgumentsTest(unittest.TestCase): - def test_pick_and_game_are_exclusive(self): - err = io.StringIO() - with patch.object(sys, "argv", ["make_game.py", "--pick", "--game", "D:/game"]), \ - patch("make_game.pick_game") as pick, redirect_stderr(err), self.assertRaises(SystemExit) as stop: - make_game.main() - self.assertEqual(stop.exception.code, 2) - self.assertIn("--pick and --game", err.getvalue()) - pick.assert_not_called() - - def test_pick_replaces_the_search(self): - chosen = os.path.abspath("picked") - with patch.object(sys, "argv", ["make_game.py", "--pick", "--check"]), \ - patch("make_game.below_normal"), \ - patch("make_game.pick_game", return_value=chosen) as pick, \ - patch("make_game.choose_game") as search, \ - patch("make_game.check", return_value={"expected_exe": "game.exe"}) as check: - self.assertEqual(make_game.main(), 0) - pick.assert_called_once() - search.assert_not_called() - self.assertEqual(check.call_args[0][0], chosen) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/test_make_game_pipeline_batches.py b/tests/test_make_game_pipeline_batches.py deleted file mode 100644 index cd1941c66..000000000 --- a/tests/test_make_game_pipeline_batches.py +++ /dev/null @@ -1,235 +0,0 @@ -"""Pipeline batching and memory-crash recovery through the real make_game.pipelines orchestration. - -The child is a small scripted checker speaking the production CLI/file protocol. Each invocation is a real -process, with synthetic index entries and controlled exits; no GPU, compiler, game data or packages are needed. -""" -import contextlib -import io -import json -import os -from pathlib import Path -import subprocess -import sys -import tempfile -import unittest -from unittest import mock - -ROOT = Path(__file__).resolve().parent.parent -sys.path.insert(0, str(ROOT)) -import make_game # noqa: E402 - - -CHECKER = r''' -import json -import os -from pathlib import Path -import signal -import sys - -spirv, cache, *args = sys.argv[1:] -spirv, cache = Path(spirv), Path(cache) -config = json.loads((spirv / "control.json").read_text(encoding="utf-8")) -names = sorted(json.loads((spirv / "index.json").read_text(encoding="utf-8")), key=lambda n: n.encode("utf-8")) -def option(flag, default=None): - return args[args.index(flag) + 1] if flag in args else default -start = int(option("--start", 0)) -count = int(option("--count", len(names))) -selected = names[start:start + count] -skip_path = option("--skip-file") -skipped = Path(skip_path).read_text(encoding="utf-8").splitlines() if skip_path else [] -active = [name for name in selected if name not in skipped] -inflight = option("--inflight-file") -def record(event): - with (spirv / "calls.jsonl").open("a", encoding="utf-8", newline="\n") as f: - f.write(json.dumps(dict(event=event, pid=os.getpid(), selected=selected, active=active, args=args)) + "\n") -record("started") -if config.get("setup_error") or config.get("probe_setup_error") and count == 1 and option("--jobs") == "1": - print("no Vulkan physical devices found", file=sys.stderr) - sys.exit(config.get("setup_exit", 2)) -if config.get("interrupt") or config.get("interrupt_probe") and count == 1 and option("--jobs") == "1": - if os.name == "nt": - import ctypes - ctypes.windll.kernel32.ExitProcess(0xC000013A) - else: - os.kill(os.getpid(), signal.SIGTERM) -if config.get("crash_before_work"): - sys.exit(70) -if config.get("probe_crash_before_work") and count == 1 and option("--jobs") == "1": - report = config.get("probe_report", "missing") - if inflight and report != "missing": - Path(inflight).write_text("unrelated\tpipeline\n" if report == "other" else "", - encoding="utf-8", newline="\n") - sys.exit(70) -crasher = config.get("crasher") -if crasher in active or len(active) > config.get("max_batch", 1000000): - if inflight: - suspects = [crasher] if crasher in active else active[:config.get("suspects", 2)] - Path(inflight).write_text("".join(n + "\tpipeline\n" for n in suspects), encoding="utf-8", newline="\n") - sys.exit(70) -# This stand-in's cache contains completed names so the test can detect lost checkpoints and repeated work. -completed = json.loads(cache.read_text(encoding="utf-8")) if cache.exists() else [] -cache.write_text(json.dumps(completed + active), encoding="utf-8", newline="\n") -record("completed") -if inflight: - Path(inflight).write_text("", encoding="utf-8", newline="\n") -sys.exit(1 if skipped and set(selected).intersection(skipped) or config.get("invalid") in active else 0) -''' - - -class PipelineBatchesTest(unittest.TestCase): - def setUp(self): - tmp = tempfile.TemporaryDirectory(prefix="pipeline batches ") - self.addCleanup(tmp.cleanup) - self.root = Path(tmp.name) - self.work = self.root / "work" - self.spirv = self.work / "shaders" / "spirv" - self.spirv.mkdir(parents=True) - self.out = self.root / "out" - self.names = [f"m_{i:02d}" for i in range(7)] - self.write_index(self.names) - self.child = self.root / "checker.py" - self.child.write_text(CHECKER, encoding="utf-8", newline="\n") - self.commands = [] - - def write_index(self, names): - (self.spirv / "index.json").write_text(json.dumps({n: {} for n in reversed(names)}), - encoding="utf-8", newline="\n") - - def invoke(self, control=None, range_support=True): - (self.spirv / "control.json").write_text(json.dumps(control or {}), encoding="utf-8", newline="\n") - def run(args, hint="", check=True, **kwargs): - args = [str(a) for a in args] - self.commands.append(args) - done = subprocess.run([sys.executable, "-I", str(self.child), *args[1:]], - capture_output=True, text=True, timeout=15) - if check and done.returncode: - raise SystemExit(1) - return done.returncode - def supports(exe, *options): - return range_support or "--start" not in options - logs, err = [], io.StringIO() - # create=True keeps the regression runnable on the old implementation, which lacks this constant. - with mock.patch.object(make_game, "pipeline_check_exe", return_value="synthetic-checker"), \ - mock.patch.object(make_game, "checker_supports", side_effect=supports), \ - mock.patch.object(make_game, "PIPELINE_BATCH_SIZE", 3, create=True), \ - mock.patch.object(make_game, "run", side_effect=run), \ - mock.patch.object(make_game, "log", side_effect=logs.append), contextlib.redirect_stderr(err): - try: - make_game.pipelines(str(self.work), str(self.out), jobs=2) - except SystemExit as exc: - return exc.code, logs, err.getvalue() - return 0, logs, err.getvalue() - - def calls(self, event=None): - path = self.spirv / "calls.jsonl" - rows = [json.loads(line) for line in path.read_text(encoding="utf-8").splitlines()] if path.exists() else [] - return [row for row in rows if event is None or row["event"] == event] - - def test_bounded_processes_cover_the_sorted_index_and_tail(self): - code, _, err = self.invoke() - self.assertEqual(code, 0, err) - completed = self.calls("completed") - self.assertEqual([r["selected"] for r in completed], [self.names[:3], self.names[3:6], self.names[6:]]) - self.assertEqual(len({r["pid"] for r in completed}), 3) - self.assertEqual(json.loads((self.out / "pipeline_cache.bin").read_text(encoding="utf-8")), self.names) - self.assertTrue(all(r["args"][r["args"].index("--jobs") + 1] == "2" for r in completed)) - - def test_collective_memory_crash_splits_without_skipping_healthy_modules(self): - code, logs, err = self.invoke({"max_batch": 2}) - self.assertEqual(code, 0, err) - # Diagnostic one-module probes are also successful; the final bounded work must still cover every name. - checked = {n for row in self.calls("completed") for n in row["active"]} - self.assertEqual(checked, set(self.names)) - self.assertFalse((self.out / "pipeline_crashes.txt").exists()) - self.assertTrue(any("smaller" in line for line in logs), logs) - - def test_a_real_crasher_stays_failed_when_later_batches_pass(self): - code, _, err = self.invoke({"crasher": "m_01"}) - self.assertNotEqual(code, 0) - self.assertEqual((self.out / "pipeline_crashes.txt").read_text(encoding="utf-8"), "m_01\n") - self.assertIn("m_01", err) - checked = {n for row in self.calls("completed") for n in row["active"]} - self.assertEqual(checked, set(self.names) - {"m_01"}) - - def test_one_inflight_module_is_not_blacklisted_when_it_survives_alone(self): - self.write_index(self.names[:2]) # small corpora need the same protection as multi-batch runs - code, _, err = self.invoke({"max_batch": 1, "suspects": 1}) - self.assertEqual(code, 0, err) - self.assertFalse((self.out / "pipeline_crashes.txt").exists()) - self.assertEqual({n for row in self.calls("completed") for n in row["active"]}, set(self.names[:2])) - - def test_interrupting_a_diagnostic_probe_stops_before_more_batches(self): - code, _, _ = self.invoke({"max_batch": 2, "interrupt_probe": True}) - self.assertNotEqual(code, 0) - self.assertEqual(len(self.calls()), 2) # the failed batch and the interrupted diagnostic probe - self.assertFalse((self.out / "pipeline_crashes.txt").exists()) - - def test_a_validation_failure_does_not_hide_the_remaining_batches(self): - code, _, _ = self.invoke({"invalid": "m_01"}) - self.assertNotEqual(code, 0) - self.assertEqual([n for row in self.calls("completed") for n in row["active"]], self.names) - self.assertFalse((self.out / "pipeline_crashes.txt").exists()) - - def test_setup_errors_and_interrupts_stop_immediately(self): - for control in ({"setup_error": True}, {"interrupt": True}): - with self.subTest(control=control): - trace = self.spirv / "calls.jsonl" - if trace.exists(): - trace.unlink() - self.commands.clear() - code, _, _ = self.invoke(control) - self.assertNotEqual(code, 0) - self.assertEqual(len(self.calls()), 1) - - def test_native_setup_exit_one_stops_instead_of_checking_every_range(self): - code, _, _ = self.invoke({"setup_error": True, "setup_exit": 1}) - self.assertNotEqual(code, 0) - self.assertEqual(len(self.calls()), 1) - - def test_native_setup_exit_one_in_a_probe_stops_before_splitting(self): - code, _, _ = self.invoke({"max_batch": 2, "probe_setup_error": True, "setup_exit": 1}) - self.assertNotEqual(code, 0) - self.assertEqual(len(self.calls()), 2) - self.assertFalse((self.out / "pipeline_crashes.txt").exists()) - - def assert_inconclusive_probe_stops(self, report): - code, logs, err = self.invoke({"max_batch": 2, "probe_crash_before_work": True, - "probe_report": report}) - self.assertNotEqual(code, 0) - self.assertEqual(len(self.calls()), 2) # failed batch, then the first inconclusive probe - self.assertEqual(self.calls()[-1]["selected"], [self.names[0]]) - self.assertFalse((self.out / "pipeline_crashes.txt").exists()) - self.assertFalse(any("took vk_pipeline_check down" in line for line in logs), logs) - self.assertIn("inconclusive", err) - - def test_abnormal_probe_without_a_report_does_not_blacklist_a_module(self): - self.assert_inconclusive_probe_stops("missing") - - def test_abnormal_probe_with_an_empty_report_does_not_blacklist_a_module(self): - self.assert_inconclusive_probe_stops("empty") - - def test_abnormal_probe_reporting_another_module_does_not_blacklist_the_selected_one(self): - self.assert_inconclusive_probe_stops("other") - - def test_a_crash_before_work_cannot_retry_forever_or_claim_success(self): - code, _, err = self.invoke({"crash_before_work": True}) - self.assertNotEqual(code, 0) - self.assertLessEqual(len(self.calls()), 4) - self.assertTrue(err) - - def test_an_older_checker_gets_no_unsupported_range_arguments(self): - code, _, err = self.invoke(range_support=False) - self.assertEqual(code, 0, err) - self.assertEqual(len(self.commands), 1) - self.assertNotIn("--start", self.commands[0]) - self.assertNotIn("--count", self.commands[0]) - - def test_small_indices_keep_the_single_run(self): - self.write_index(self.names[:2]) - code, _, err = self.invoke() - self.assertEqual(code, 0, err) - self.assertEqual(len(self.commands), 1) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/test_make_game_pipeline_preflight.py b/tests/test_make_game_pipeline_preflight.py deleted file mode 100644 index 01e61aec7..000000000 --- a/tests/test_make_game_pipeline_preflight.py +++ /dev/null @@ -1,267 +0,0 @@ -"""make_game.py: a missing vk_pipeline_check is reported in preflight, before a long shader build. - - python -I tests/test_make_game_pipeline_preflight.py - -Standard library only. Every path is synthetic and every tool is mocked: no game files, GPU, Vulkan SDK or -build output is needed. -""" -import io -import os -import sys -import tempfile -import unittest -from unittest import mock - -ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) -if ROOT not in sys.path: - sys.path.insert(0, ROOT) - -import make_game # noqa: E402 - - -class PreflightEnv: - def setUp(self): - tmp = tempfile.TemporaryDirectory() - self.addCleanup(tmp.cleanup) - self.root = tmp.name - self.work = os.path.join(self.root, "work") - os.makedirs(self.work) - # Satisfy every other prerequisite so only the checker under test can make preflight fail. - for patcher in (mock.patch("sys.version_info", (3, 12, 0)), - mock.patch.dict(os.environ, {"LLVM_MC": "llvm-mc"}), - mock.patch("shutil.which", return_value="/bin/tool"), - mock.patch("shutil.disk_usage", return_value=mock.Mock(free=500 * 2**30))): - patcher.start() - self.addCleanup(patcher.stop) - - def write_shader_index(self): - spirv = os.path.join(self.work, "shaders", "spirv") - os.makedirs(spirv) - with open(os.path.join(spirv, "index.json"), "w", encoding="utf-8") as f: - f.write('{"shader_0": {}}') # a finished translation is never empty - - def assert_preflight_fails(self, stages, match): - err = io.StringIO() - with mock.patch("sys.stderr", err): - with self.assertRaises(SystemExit) as ctx: - make_game.preflight(stages, self.work) - self.assertEqual(ctx.exception.code, 1) - self.assertIn(match, err.getvalue()) - return err.getvalue() - - -class PipelinePreflightTest(PreflightEnv, unittest.TestCase): - def test_pipelines_without_checker_fails_in_preflight(self): - with mock.patch("os.name", "nt"), mock.patch.object(make_game, "pipeline_check_exe", return_value=None): - err = self.assert_preflight_fails(["shaders", "pipelines"], "vk_pipeline_check") - self.assertIn("Install these first, then run the build again:", err) - - def test_main_does_not_start_shaders_when_checker_is_missing(self): - game = os.path.join(self.root, "game") - out = os.path.join(self.root, "out") - os.makedirs(game) - argv = ["make_game.py", "--game", game, "--work", self.work, "--out", out, - "--stages", "shaders,pipelines", "--no-tui"] - with mock.patch.object(sys, "argv", argv), \ - mock.patch("os.name", "nt"), \ - mock.patch.object(make_game, "below_normal"), \ - mock.patch.object(make_game, "check", return_value={"expected_exe": "game.exe"}), \ - mock.patch.object(make_game, "pipeline_check_exe", return_value=None), \ - mock.patch.object(make_game, "shaders") as shaders, \ - mock.patch.object(make_game, "pipelines") as pipelines, \ - mock.patch.object(make_game, "log"), \ - mock.patch("sys.stderr", io.StringIO()): - with self.assertRaises(SystemExit) as ctx: - make_game.main() - self.assertEqual(ctx.exception.code, 1) - shaders.assert_not_called() - pipelines.assert_not_called() - - def test_checker_already_built_still_requires_shaders(self): - with mock.patch("os.name", "nt"), \ - mock.patch.object(make_game, "pipeline_check_exe", return_value="vk_pipeline_check.exe"): - self.assert_preflight_fails(["pipelines"], "No translated shaders yet") - - def test_checker_already_built_passes_preflight(self): - self.write_shader_index() - with mock.patch.object(make_game, "pipeline_check_exe", return_value="/bin/vk_pipeline_check"): - make_game.preflight(["pipelines"], self.work) - - @unittest.skipUnless(os.name == "posix", "requires POSIX execute permissions") - def test_non_executable_linux_checker_without_cmake_fails_preflight(self): - self.write_shader_index() - checker_dir = os.path.join(self.root, "runtime", "build", "linux") - os.makedirs(checker_dir) - checker = os.path.join(checker_dir, "vk_pipeline_check") - with open(checker, "wb"): - pass - os.chmod(checker, 0o644) - with mock.patch.object(make_game, "ROOT", self.root), \ - mock.patch("shutil.which", return_value=None), \ - mock.patch.object(make_game, "build_pipeline_check") as build: - self.assert_preflight_fails(["pipelines"], "CMake 3.24 or newer") - build.assert_not_called() - - def test_runtime_stage_builds_the_checker_so_it_is_not_required(self): - # On Windows runtime produces vk_pipeline_check.exe when the Vulkan SDK is installed. - self.write_shader_index() - with mock.patch("os.name", "nt"), \ - mock.patch.dict(os.environ, {"VULKAN_SDK": r"C:\Vulkan"}), \ - mock.patch.object(make_game, "visual_cpp_tools_ok", return_value=True), \ - mock.patch.object(make_game, "pipeline_check_exe", return_value=None): - make_game.preflight(["runtime", "pipelines"], self.work) - - def test_runtime_without_vulkan_sdk_does_not_build_the_checker(self): - # scripts/build_runtime.ps1 builds vk_pipeline_check.exe only 'if defined VULKAN_SDK': a combined - # Windows run without it would still spend hours in the shaders stage and fail in pipelines. - for sdk in (None, ""): - with self.subTest(sdk=sdk), mock.patch("os.name", "nt"), \ - mock.patch.dict(os.environ), \ - mock.patch.object(make_game, "visual_cpp_tools_ok", return_value=True), \ - mock.patch.object(make_game, "pipeline_check_exe", return_value=None): - if sdk is None: - os.environ.pop("VULKAN_SDK", None) - else: - os.environ["VULKAN_SDK"] = sdk - err = self.assert_preflight_fails(["runtime", "pipelines"], "VULKAN_SDK") - self.assertIn("vk_pipeline_check", err) - - def test_missing_checker_is_listed_with_other_missing_prerequisites(self): - with mock.patch("os.name", "nt"), \ - mock.patch("shutil.which", side_effect=lambda t: None if t == "llvm-mc" else "/bin/tool"), \ - mock.patch.object(make_game, "pipeline_check_exe", return_value=None): - err = self.assert_preflight_fails(["shaders", "pipelines"], "vk_pipeline_check") - self.assertIn("llvm-mc (LLVM 21+ with the AMDGPU target)", err) - self.assertEqual(err.count("vk_pipeline_check"), 1) - - - -class LinuxPipelineCheckTest(PreflightEnv, unittest.TestCase): - """Off Windows preflight builds the checker itself once every other prerequisite is there.""" - - def setUp(self): - super().setUp() - for patcher in (mock.patch("os.name", "posix"), - mock.patch.object(make_game, "pipeline_check_exe", return_value=None)): - patcher.start() - self.addCleanup(patcher.stop) - - def test_missing_shader_index_stops_before_building_checker(self): - with mock.patch.object(make_game, "pipeline_check_exe", side_effect=[None, None, "/bin/vk_pipeline_check"]), \ - mock.patch.object(make_game, "build_pipeline_check") as build: - self.assert_preflight_fails(["pipelines"], "No translated shaders yet") - build.assert_not_called() - - def test_builds_the_checker_after_the_checks(self): - self.write_shader_index() - with mock.patch.object(make_game, "pipeline_check_exe", side_effect=[None, None, "/bin/vk_pipeline_check"]), \ - mock.patch.object(make_game, "build_pipeline_check") as build: - make_game.preflight(["pipelines"], self.work, jobs=3) - build.assert_called_once_with(3) - - def test_a_checker_built_where_it_isnt_looked_for_fails_in_preflight(self): - with mock.patch.object(make_game, "build_pipeline_check") as build: - self.assert_preflight_fails(["shaders", "pipelines"], "delete runtime/build/linux") - build.assert_called_once() - - def test_missing_built_checker_does_not_initialize_asset_submodule(self): - with mock.patch.object(make_game, "dotnet_sdk_ok", return_value=True), \ - mock.patch.object(make_game, "build_pipeline_check") as build, \ - mock.patch.object(make_game, "ensure_submodule") as initialize: - self.assert_preflight_fails(["shaders", "assets", "pipelines"], "delete runtime/build/linux") - build.assert_called_once() - initialize.assert_not_called() - - def test_without_cmake_nothing_is_built(self): - with mock.patch("shutil.which", side_effect=lambda t: None if t == "cmake" else "/bin/tool"), \ - mock.patch.object(make_game, "build_pipeline_check") as build: - err = self.assert_preflight_fails(["pipelines"], "CMake 3.24 or newer") - self.assertIn("vk_pipeline_check", err) - build.assert_not_called() - - def test_another_missing_prerequisite_stops_before_the_build(self): - with mock.patch("shutil.which", side_effect=lambda t: None if t == "llvm-mc" else "/bin/tool"), \ - mock.patch.object(make_game, "build_pipeline_check") as build: - self.assert_preflight_fails(["shaders", "pipelines"], "llvm-mc") - build.assert_not_called() - - def test_a_built_checker_is_not_rebuilt(self): - self.write_shader_index() - with mock.patch.object(make_game, "pipeline_check_exe", return_value="/bin/vk_pipeline_check"), \ - mock.patch.object(make_game, "build_pipeline_check") as build: - make_game.preflight(["pipelines"], self.work) - build.assert_not_called() - - def put_checker_older_than_its_source(self): - """runtime/build/linux/vk_pipeline_check built before its source last changed (a pull since the build).""" - build = os.path.join(self.root, "runtime", "build", "linux") - test = os.path.join(self.root, "runtime", "test") - os.makedirs(build) - os.makedirs(test) - checker = os.path.join(build, "vk_pipeline_check") - for path, text in ((checker, ""), (os.path.join(test, "vk_pipeline_check.cpp"), '#include "gate.h"\n'), - (os.path.join(test, "gate.h"), "")): - with open(path, "w", encoding="utf-8") as f: - f.write(text) - os.utime(checker, (1_000_000, 1_000_000)) - os.utime(os.path.join(test, "vk_pipeline_check.cpp"), (500_000, 500_000)) - return checker - - def test_a_checker_older_than_its_sources_is_rebuilt(self): - # Old #7148: a checker from before a pull was taken as it was, and the stage checked with the old program. - self.write_shader_index() - checker = self.put_checker_older_than_its_source() - with mock.patch.object(make_game, "ROOT", self.root), mock.patch.object(make_game, "pipeline_check_exe", return_value=checker), mock.patch.object(make_game, "build_pipeline_check") as build: - self.assertEqual(make_game.stale_checker(checker), ["runtime/test/gate.h"]) - make_game.preflight(["pipelines"], self.work, jobs=4) - build.assert_called_once_with(4) - - def test_a_current_checker_in_the_build_folder_is_not_rebuilt(self): - self.write_shader_index() - checker = self.put_checker_older_than_its_source() - future = os.path.getmtime(os.path.join(self.root, "runtime", "test", "gate.h")) + 60 - os.utime(checker, (future, future)) - with mock.patch.object(make_game, "ROOT", self.root), mock.patch.object(make_game, "pipeline_check_exe", return_value=checker), mock.patch.object(make_game, "build_pipeline_check") as build: - self.assertEqual(make_game.stale_checker(checker), []) - make_game.preflight(["pipelines"], self.work) - build.assert_not_called() - - def test_a_stale_checker_without_cmake_is_used_with_a_warning(self): - self.write_shader_index() - checker = self.put_checker_older_than_its_source() - with mock.patch.object(make_game, "ROOT", self.root), mock.patch("shutil.which", side_effect=lambda t: None if t == "cmake" else "/bin/tool"), mock.patch.object(make_game, "pipeline_check_exe", return_value=checker), mock.patch.object(make_game, "build_pipeline_check") as build: - make_game.preflight(["pipelines"], self.work) - build.assert_not_called() - with mock.patch.object(make_game, "log") as log, mock.patch.object(make_game, "checker_supports", side_effect=SystemExit(0)): - with self.assertRaises(SystemExit): - make_game.pipelines(self.work, os.path.join(self.root, "out")) - warning = log.call_args_list[0].args[0] - self.assertIn("WARNING", warning) - self.assertIn("runtime/test/gate.h", warning) - self.assertIn("cmake --build runtime/build/linux --target vk_pipeline_check", warning) - - def test_a_checker_outside_the_build_folder_is_not_compared(self): - # --runtime-build and the like: their time stamps say nothing about this checkout's sources. - self.put_checker_older_than_its_source() - elsewhere = os.path.join(self.root, "elsewhere", "vk_pipeline_check") - os.makedirs(os.path.dirname(elsewhere)) - with open(elsewhere, "w", encoding="utf-8"): - pass - os.utime(elsewhere, (1_000_000, 1_000_000)) - with mock.patch.object(make_game, "ROOT", self.root): - self.assertEqual(make_game.stale_checker(elsewhere), []) - - def test_the_build_uses_the_readme_folder(self): - with mock.patch.object(make_game, "ROOT", self.root), \ - mock.patch.object(make_game, "log"), \ - mock.patch.object(make_game, "run") as run: - make_game.build_pipeline_check(2) - configure, build = (c.args[0] for c in run.call_args_list) - folder = os.path.join(self.root, "runtime", "build", "linux") - self.assertEqual(configure[:5], ["cmake", "-S", os.path.join(self.root, "runtime"), "-B", folder]) - self.assertEqual(build, ["cmake", "--build", folder, "--parallel", "2", "--target", "vk_pipeline_check"]) - self.assertIn("Vulkan headers", run.call_args_list[1].kwargs["hint"]) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/test_make_game_pipelines.py b/tests/test_make_game_pipelines.py deleted file mode 100644 index 6f20719c2..000000000 --- a/tests/test_make_game_pipelines.py +++ /dev/null @@ -1,366 +0,0 @@ -"""make_game.py: vk_pipeline_check selection and arguments in the pipelines stage. - -Standard library only; no GPU, no Vulkan SDK, no game data: the checker is mocked. -""" -import io -import json -import os -import sys -import tempfile -import unittest -from unittest import mock - -ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) -sys.path.insert(0, ROOT) -import make_game # noqa: E402 - - -class PipelinesJobsTest(unittest.TestCase): - def setUp(self): - tmp = tempfile.TemporaryDirectory() - self.addCleanup(tmp.cleanup) - self.root = tmp.name - self.game = os.path.join(self.root, "game") - self.work = os.path.join(self.root, "work") - self.out = os.path.join(self.root, "out") - spirv = os.path.join(self.work, "shaders", "spirv") - os.makedirs(self.game) - os.makedirs(spirv) - with open(os.path.join(spirv, "index.json"), "w", encoding="utf-8") as f: - f.write('{"shader_0": {}}') # a finished translation is never empty - - def checker_args(self, call): - with mock.patch.object(make_game, "pipeline_check_exe", return_value="vk_pipeline_check.exe"), \ - mock.patch.object(make_game, "run", return_value=0) as run, \ - mock.patch.object(make_game, "log", lambda *a: None): - call() - self.assertEqual(run.call_count, 1) - return [str(a) for a in run.call_args.args[0]] - - def jobs_of(self, args): - self.assertEqual(args.count("--jobs"), 1, args) - return args[args.index("--jobs") + 1] - - def main_with(self, *extra): - argv = ["make_game.py", "--game", self.game, "--work", self.work, "--out", self.out, - "--stages", "pipelines", "--no-tui", *extra] - with mock.patch.object(sys, "argv", argv), mock.patch.object(make_game, "below_normal"), \ - mock.patch.object(make_game, "check", return_value={"expected_exe": "g.exe"}), \ - mock.patch.object(make_game, "preflight"): - self.assertEqual(make_game.main(), 0) - - def test_the_stage_passes_its_jobs(self): - args = self.checker_args(lambda: make_game.pipelines(self.work, self.out, 7)) - self.assertEqual(self.jobs_of(args), "7") - self.assertEqual(args[1:3], [os.path.join(self.work, "shaders", "spirv"), - os.path.join(self.out, "pipeline_cache.bin")]) - - def test_jobs_on_the_command_line_reach_the_checker(self): - # main() clamps --jobs to the machine's hardware threads; pin them so 5 is in range anywhere (the - # GitHub Windows runners have 4). - with mock.patch.object(make_game.leonida_tui.os, "cpu_count", return_value=16): - self.assertEqual(self.jobs_of(self.checker_args(lambda: self.main_with("--jobs", "5"))), "5") - - def test_windows_reuses_the_checker_from_the_supplied_runtime_build(self): - supplied = os.path.join(self.root, "unpacked runtime") - os.makedirs(supplied) - checker = os.path.join(supplied, "vk_pipeline_check.exe") - for name in (*make_game.RUNTIME_FILES, "vk_pipeline_check.exe"): - with open(os.path.join(supplied, name), "wb"): - pass - argv = ["make_game.py", "--game", self.game, "--work", self.work, "--out", self.out, - "--stages", "runtime,pipelines", "--runtime-build", supplied, "--jobs", "3"] - with mock.patch.object(sys, "argv", argv), mock.patch.object(make_game, "ROOT", self.root), \ - mock.patch("os.name", "nt"), mock.patch.object(make_game, "below_normal"), \ - mock.patch.object(make_game, "check", return_value={"expected_exe": "g.exe"}), \ - mock.patch.object(make_game, "log"), mock.patch.object(make_game, "run") as run, \ - mock.patch.object(make_game, "verify_runtime_build"): - self.assertEqual(make_game.main(), 0) - run.assert_called_once() - self.assertEqual(run.call_args.args[0][0], checker) - self.assertEqual(self.jobs_of(run.call_args.args[0]), "3") - - def test_the_default_matches_the_checker_default(self): - # vk_pipeline_check's own default is half the hardware threads, as is make_game.py's --jobs. - want = str(max(1, (os.cpu_count() or 2) // 2)) - self.assertEqual(self.jobs_of(self.checker_args(lambda: self.main_with())), want) - - def test_the_stage_log_names_compute_and_graphics_pipelines(self): - # The stage runs vk_pipeline_check without --stage, and its default is all: cs become compute pipelines, - # ps/vs/ms/gs become graphics pipelines with partner stubs, so the announce line must not claim compute only. - logs = [] - with mock.patch.object(make_game, "pipeline_check_exe", return_value="vk_pipeline_check.exe"), \ - mock.patch.object(make_game, "checker_supports", return_value=False), \ - mock.patch.object(make_game, "run", return_value=0), \ - mock.patch.object(make_game, "log", logs.append): - make_game.pipelines(self.work, self.out) - announce = [m for m in logs if "creating" in m] - self.assertEqual(len(announce), 1, logs) - self.assertIn("graphics", announce[0]) - self.assertIn("compute", announce[0]) - - -ABORT = 0x80000003 # how Windows reports the driver's LLVM abort (#884) - - -class PipelinesCrashRetryTest(unittest.TestCase): - """A module that takes vk_pipeline_check down is skipped and the rest is checked; the checker is scripted.""" - - def setUp(self): - tmp = tempfile.TemporaryDirectory() - self.addCleanup(tmp.cleanup) - self.work = os.path.join(tmp.name, "work") - self.out = os.path.join(tmp.name, "out") - self.spirv = os.path.join(self.work, "shaders", "spirv") - os.makedirs(self.spirv) - with open(os.path.join(self.spirv, "index.json"), "w", encoding="utf-8") as f: - f.write('{"b_mod": {}, "a_mod": {}, "c_mod": {}}') - self.inflight = os.path.join(self.out, "pipeline_inflight.txt") - self.skip = os.path.join(self.out, "pipeline_crashes.txt") - self.calls = [] - - def stage(self, script, supports=True): - """script(args, call_number) -> exit code; it may write the in-flight file first.""" - def fake_run(args, hint="", check=True, **kw): - args = [str(a) for a in args] - self.calls.append(args) - code = script(args, len(self.calls)) - if code in (0, 1) and "--inflight-file" in args: - # A native checker that finishes its shader pass clears this report, even on validation failure. - with open(args[args.index("--inflight-file") + 1], "w", encoding="utf-8", newline="\n") as f: - f.write("") - if check and code != 0: # as run() does - raise SystemExit(1) - return code - logs = [] - with mock.patch.object(make_game, "pipeline_check_exe", return_value="vk_pipeline_check.exe"), \ - mock.patch.object(make_game, "checker_supports", return_value=supports), \ - mock.patch.object(make_game, "run", side_effect=fake_run), \ - mock.patch.object(make_game, "log", logs.append): - try: - make_game.pipelines(self.work, self.out) - return None, logs - except SystemExit: - return sys.stderr, logs - - def inflight_is(self, *names): - """As vk_pipeline_check writes it: namephase, where a module can die in either phase.""" - with open(self.inflight, "w", encoding="utf-8") as f: - f.write("".join(f"{n}\t{'module' if i % 2 else 'pipeline'}\n" for i, n in enumerate(names))) - - def skipped(self, args): - return args[args.index("--skip-file") + 1] if "--skip-file" in args else None - - def is_probe(self, args): - return ("--count" in args and args[args.index("--count") + 1] == "1" - and "--jobs" in args and args[args.index("--jobs") + 1] == "1") - - def test_bom_marked_index_reaches_the_native_checker_and_preserves_range(self): - with open(os.path.join(self.spirv, "index.json"), "w", encoding="utf-8-sig", newline="\n") as f: - f.write('{"b_mod": {}, "a_mod": {}, "c_mod": {}}') - failed, _ = self.stage(lambda args, n: 0) - self.assertIsNone(failed) - self.assertEqual(len(self.calls), 1) - self.assertEqual(self.calls[0][self.calls[0].index("--count") + 1], "3") - self.assertEqual(make_game.pipeline_names(self.spirv), ["a_mod", "b_mod", "c_mod"]) - - def test_a_named_module_is_skipped_and_the_rest_checked(self): - def script(args, n): - if self.is_probe(args): - self.inflight_is("b_mod") - return ABORT # it must reproduce alone before it is added to the crash list - if n == 1: - self.inflight_is("b_mod") - return ABORT - self.assertEqual(self.skipped(args), self.skip) - with open(self.skip, encoding="utf-8") as f: - self.assertEqual(f.read(), "b_mod\n") - return 1 # the skipped module counts as failed - err = io.StringIO() - with mock.patch("sys.stderr", err): - failed, logs = self.stage(script) - self.assertIsNotNone(failed) - self.assertEqual(len(self.calls), 3) - self.assertIn("--inflight-file", self.calls[0]) - self.assertIsNone(self.skipped(self.calls[0])) - self.assertTrue(any("b_mod took vk_pipeline_check down" in m and "0x80000003" in m for m in logs), logs) - self.assertIn("1 module(s) took the driver down", err.getvalue()) - self.assertIn("b_mod", err.getvalue()) - self.assertFalse(os.path.exists(self.inflight)) - - def test_several_in_flight_are_tried_alone_and_only_the_crasher_is_skipped(self): - def script(args, n): - if self.is_probe(args): # the global index is name-sorted, so a_mod=0, b_mod=1, c_mod=2 - self.assertEqual(args[args.index("--count") + 1], "1") - if args[args.index("--start") + 1] == "2": - self.inflight_is("c_mod") - return ABORT if args[args.index("--start") + 1] == "2" else 0 - if n == 1: - self.inflight_is("a_mod", "c_mod") - return ABORT - with open(self.skip, encoding="utf-8") as f: - self.assertEqual(f.read(), "c_mod\n") - return 1 - with mock.patch("sys.stderr", io.StringIO()): - failed, _ = self.stage(script) - self.assertIsNotNone(failed) - starts = [c[c.index("--start") + 1] for c in self.calls if self.is_probe(c)] - self.assertEqual(starts, ["0", "2"]) - - def test_a_crash_with_nothing_in_flight_stops_after_reaching_one_entry(self): - err = io.StringIO() - with mock.patch("sys.stderr", err): - failed, _ = self.stage(lambda args, n: ABORT) - self.assertIsNotNone(failed) - self.assertEqual(len(self.calls), 2) # range of 3, then its first single-entry subrange - self.assertIn("no module could be named", err.getvalue()) - - def test_ctrl_c_is_not_retried(self): - def script(args, n): - self.inflight_is("b_mod") - return 0xC000013A - with mock.patch("sys.stderr", io.StringIO()): - failed, _ = self.stage(script) - self.assertIsNotNone(failed) - self.assertEqual(len(self.calls), 1) - - def test_the_retries_stop(self): - all_names = [f"m{i}" for i in range(20)] - with open(os.path.join(self.spirv, "index.json"), "w", encoding="utf-8", newline="\n") as f: - json.dump({name: {} for name in all_names}, f) - names = iter(all_names) - def script(args, n): - if self.is_probe(args): - self.inflight_is(sorted(all_names)[int(args[args.index("--start") + 1])]) - return ABORT - self.inflight_is(next(names)) - return ABORT - err = io.StringIO() - with mock.patch("sys.stderr", err): - failed, _ = self.stage(script) - self.assertIsNotNone(failed) - self.assertEqual(len([c for c in self.calls if not self.is_probe(c)]), make_game.PIPELINE_CRASH_RETRIES + 1) - self.assertIn("still crashed after", err.getvalue()) - - def test_the_crash_report_names_the_module_and_its_spirv_hash(self): - blob = b"\x03\x02\x23\x07" - with open(os.path.join(self.spirv, "b_mod.spv"), "wb") as f: - f.write(blob) - - def script(args, n): - if self.is_probe(args): - self.inflight_is("b_mod") - return ABORT - if n == 1: - self.inflight_is("b_mod") - return ABORT - return 1 - - err = io.StringIO() - with mock.patch("sys.stderr", err): - failed, _ = self.stage(script) - self.assertIsNotNone(failed) - with open(os.path.join(self.out, "pipeline_crashes.json"), encoding="utf-8") as f: - doc = json.load(f) - self.assertEqual(doc, {"modules": [{"name": "b_mod", "spv_sha256": - __import__("hashlib").sha256(blob).hexdigest()}]}) - self.assertIn("pipeline_crashes.json", err.getvalue()) - - def test_the_crash_report_survives_a_range_that_cannot_name_a_module(self): - # A module was already named and recorded, then the driver aborts without naming - # another one. The give-up path must keep the report instead of skipping it. - blob = b"\x03\x02\x23\x07" - with open(os.path.join(self.spirv, "b_mod.spv"), "wb") as f: - f.write(blob) - named = [] - - def script(args, n): - if self.is_probe(args): - self.inflight_is("b_mod") - return ABORT - if not named: - named.append(n) - self.inflight_is("b_mod") - return ABORT - - err = io.StringIO() - with mock.patch("sys.stderr", err): - failed, _ = self.stage(script) - self.assertIsNotNone(failed) - self.assertIn("no module could be named", err.getvalue()) - with open(os.path.join(self.out, "pipeline_crashes.json"), encoding="utf-8") as f: - doc = json.load(f) - self.assertEqual([m["name"] for m in doc["modules"]], ["b_mod"]) - self.assertEqual(doc["modules"][0]["spv_sha256"], - __import__("hashlib").sha256(blob).hexdigest()) - - def test_a_failed_crash_report_does_not_hide_the_checker_diagnostic(self): - # The report is best-effort: a path that cannot be written warns, then the normal - # checker failure still names the modules. - os.makedirs(os.path.join(self.out, "pipeline_crashes.json")) - - def script(args, n): - if self.is_probe(args): - self.inflight_is("b_mod") - return ABORT - if n == 1: - self.inflight_is("b_mod") - return ABORT - return 1 - - with mock.patch("sys.stderr", io.StringIO()): - err, logs = self.stage(script) - self.assertIsNotNone(err) - self.assertIn("vk_pipeline_check", err.getvalue()) - self.assertIn("b_mod", err.getvalue()) - self.assertTrue(any("cannot write pipeline_crashes.json" in line for line in logs)) - - def test_a_clean_run_drops_an_old_crash_report(self): - os.makedirs(self.out) - report = os.path.join(self.out, "pipeline_crashes.json") - with open(report, "w", encoding="utf-8") as f: - f.write('{"modules": []}') - failed, _ = self.stage(lambda args, n: 0) - self.assertIsNone(failed) - self.assertFalse(os.path.exists(report)) - - def test_a_clean_run_is_one_call_and_an_old_skip_list_is_dropped(self): - os.makedirs(self.out) - with open(self.skip, "w", encoding="utf-8") as f: - f.write("b_mod\n") # from an earlier build: every module gets a fresh chance - failed, logs = self.stage(lambda args, n: 0) - self.assertIsNone(failed) - self.assertEqual(len(self.calls), 1) - self.assertIsNone(self.skipped(self.calls[0])) - self.assertFalse(os.path.exists(self.skip)) - self.assertIn("pipelines: done", logs) - - - def test_an_older_checker_gets_the_old_invocation(self): - # Before --inflight-file the checker took unknown arguments as the cache path (it would write the cache into - # pipeline_inflight.txt), so an older build runs as before: one call, no new flags, a crash stops the stage. - def script(args, n): - self.inflight_is("b_mod") - return ABORT - with mock.patch("sys.stderr", io.StringIO()): - failed, logs = self.stage(script, supports=False) - self.assertIsNotNone(failed) - self.assertEqual(len(self.calls), 1) - self.assertNotIn("--inflight-file", self.calls[0]) - self.assertNotIn("--skip-file", self.calls[0]) - self.assertTrue(any("has no --inflight-file" in m for m in logs), logs) - - def test_support_is_read_from_the_usage_line(self): - new = "usage: vk_pipeline_check ... [--inflight-file F] [--skip-file F]\n" - old = "usage: vk_pipeline_check [cache.bin] [--jobs N] [--isolate [--isolate-batch N]]\n" - for usage, want in ((new, True), (old, False)): - done = mock.Mock(stdout="", stderr=usage, returncode=2) - with mock.patch.object(make_game.subprocess, "run", return_value=done) as sp: - self.assertEqual(make_game.checker_supports("vk.exe", "--inflight-file", "--skip-file"), want) - self.assertEqual(sp.call_args.args[0], ["vk.exe"]) # no arguments: usage only, no Vulkan - with mock.patch.object(make_game.subprocess, "run", side_effect=OSError("not an executable")): - self.assertFalse(make_game.checker_supports("vk.exe", "--inflight-file")) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/test_make_game_platform.py b/tests/test_make_game_platform.py deleted file mode 100644 index c68685df6..000000000 --- a/tests/test_make_game_platform.py +++ /dev/null @@ -1,675 +0,0 @@ -"""Platform-specific build stages, runtime packaging and vk_pipeline_check discovery. - - python -I tests/test_make_game_platform.py - -No game data: stage selection uses mocks, and the packaging and discovery tests create synthetic files. -""" -import io -import json -import os -import shlex -import subprocess -import sys -import tempfile -import unittest -from unittest import mock - -ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) -if ROOT not in sys.path: - sys.path.insert(0, ROOT) - -import make_game # noqa: E402 - -STAGE_FUNCS = ("shaders", "assets", "runtime", "pipelines") - - -class DefaultStagesTest(unittest.TestCase): - def setUp(self): - self.tmp = tempfile.TemporaryDirectory() - self.game = os.path.join(self.tmp.name, "game") - os.makedirs(self.game) - - def tearDown(self): - self.tmp.cleanup() - - def run_main(self, os_name, *args, lacking=("clang-cl",)): - argv = ["make_game.py", "--game", self.game, "--out", os.path.join(self.tmp.name, "out"), "--no-tui", *args] - mocks = {n: mock.MagicMock() for n in STAGE_FUNCS} - with mock.patch.object(sys, "argv", argv), \ - mock.patch.object(make_game.os, "name", os_name), \ - mock.patch.object(make_game, "cross_build_missing", return_value=list(lacking)), \ - mock.patch.object(make_game, "below_normal"), \ - mock.patch.object(make_game, "check", return_value={"expected_exe": "game.exe"}), \ - mock.patch.object(make_game, "preflight") as preflight, \ - mock.patch.object(make_game, "verify_runtime_build"), \ - mock.patch.object(make_game, "log"), \ - mock.patch.multiple(make_game, **mocks): - self.assertEqual(make_game.main(), 0) - return preflight.call_args.args[0], {n: m.called for n, m in mocks.items()} - - def test_default_stages_leave_runtime_out_off_windows_without_the_cross_build(self): - stages, ran = self.run_main("posix") - self.assertEqual(stages, ["check", "shaders", "assets", "pipelines"]) - self.assertEqual(ran, {"shaders": True, "assets": True, "runtime": False, "pipelines": True}) - - def test_default_stages_keep_runtime_off_windows_with_the_cross_build(self): - stages, ran = self.run_main("posix", lacking=()) - self.assertEqual(stages, make_game.STAGES) - self.assertTrue(ran["runtime"]) - - def test_default_stages_keep_runtime_on_windows(self): - stages, ran = self.run_main("nt") - self.assertEqual(stages, make_game.STAGES) - self.assertTrue(ran["runtime"]) - - def test_explicit_full_stage_list_reaches_preflight_off_windows(self): - stages, _ = self.run_main("posix", "--stages", ",".join(make_game.STAGES), "--wave64-emulate", "off") - self.assertEqual(stages, make_game.STAGES) - - def test_explicit_stages_are_kept_as_given(self): - stages, _ = self.run_main("posix", "--stages", "shaders,runtime") - self.assertEqual(stages, ["shaders", "runtime"]) - - def test_default_stages_keep_runtime_off_windows_with_a_runtime_build(self): - stages, ran = self.run_main("posix", "--runtime-build", self.tmp.name) - self.assertEqual(stages, make_game.STAGES) - self.assertTrue(ran["runtime"]) - - -class PreflightTest(unittest.TestCase): - def preflight(self, lacking, work): - with mock.patch.object(make_game.os, "name", "posix"), \ - mock.patch.object(make_game.sys, "version_info", (3, 12, 0)), \ - mock.patch.object(make_game, "cross_build_missing", return_value=lacking), \ - mock.patch.object(make_game, "cross_configure") as configure, \ - mock.patch.object(make_game, "visual_cpp_tools_ok") as vs: - make_game.preflight(["runtime"], work) - vs.assert_not_called() - return configure - - def test_runtime_off_windows_without_the_cross_build_fails_before_any_work(self): - err = io.StringIO() - with tempfile.TemporaryDirectory() as work, \ - mock.patch("sys.stderr", err), \ - mock.patch.object(make_game.shutil, "disk_usage") as usage: - with self.assertRaises(SystemExit) as ctx: - self.preflight(["clang-cl", "the xwin SDK"], os.path.join(work, "w")) - self.assertEqual(ctx.exception.code, 1) - self.assertIn("clang-cl (for the runtime stage, or pass --runtime-build)", err.getvalue()) - self.assertIn("the xwin SDK (for the runtime stage", err.getvalue()) - usage.assert_not_called() - self.assertFalse(os.path.exists(os.path.join(work, "w"))) - - def test_runtime_off_windows_configures_the_cross_build_before_any_work(self): - with tempfile.TemporaryDirectory() as work: - self.preflight([], os.path.join(work, "w")).assert_called_once_with() - - -class CrossBuildMissingTest(unittest.TestCase): - def setUp(self): - self.sdk = self.enterContext(tempfile.TemporaryDirectory()) - os.makedirs(os.path.join(self.sdk, "VC", "Tools", "MSVC")) - os.makedirs(os.path.join(self.sdk, "Windows Kits", "10", "Lib", "10.0.26100", "um", "x64")) - - def missing(self, have=("cmake", *make_game.CROSS_TOOLS), major=23, sdk=None, configured=None): - def which(t): - return t if t.startswith("/") and t in have else f"/usr/bin/{t}" if t in have else None - majors = major if callable(major) else (lambda exe="clang-cl": major) - with mock.patch.object(make_game.shutil, "which", side_effect=which), \ - mock.patch.object(make_game, "clang_cl_major", side_effect=majors) as self.major, \ - mock.patch.object(make_game, "configured_cross_tools", return_value=configured or {}), \ - mock.patch.dict(os.environ, {"XWIN_DIR": sdk if sdk is not None else self.sdk}): - return make_game.cross_build_missing() - - def test_a_full_versioned_set_counts(self): - self.assertEqual(self.missing(have=("cmake", *(f"{t}-21" for t in make_game.CROSS_TOOLS))), []) - self.major.assert_called_once_with("clang-cl-21") - - def test_an_old_plain_set_does_not_hide_a_newer_versioned_one(self): - have = ("cmake", *make_game.CROSS_TOOLS, *(f"{t}-21" for t in make_game.CROSS_TOOLS)) - self.assertEqual(self.missing(have=have, major=lambda exe="clang-cl": 18 if exe == "clang-cl" else 21), []) - - def test_versions_are_not_mixed_and_the_missing_one_is_named(self): - have = ("cmake", "clang-cl-21", "lld-link-21", "llvm-lib-21", "llvm-rc-21", "llvm-mt-20") - (item,) = self.missing(have=have) - self.assertTrue(item.startswith("llvm-mt-21: LLVM 19 or newer"), item) - - def test_a_configured_build_folder_needs_only_its_own_tools(self): - tools = {"CMAKE_CXX_COMPILER": "/opt/llvm-21/bin/clang-cl", "CMAKE_LINKER": "/opt/llvm-21/bin/lld-link", - "CMAKE_AR": "llvm-lib", "CMAKE_MT": "/opt/llvm-21/bin/llvm-mt", "CMAKE_RC_COMPILER": "llvm-rc"} - have = ("cmake", "llvm-lib", "llvm-rc", "/opt/llvm-21/bin/clang-cl", "/opt/llvm-21/bin/lld-link", - "/opt/llvm-21/bin/llvm-mt") - self.assertEqual(self.missing(have=have, configured=tools), []) - self.major.assert_not_called() - (item,) = self.missing(have=have[:-1], configured=tools) - self.assertTrue(item.startswith("/opt/llvm-21/bin/llvm-mt, which runtime/build/windows was configured with")) - self.assertIn("delete runtime/build/windows", item) - - def test_everything_there(self): - self.assertEqual(self.missing(), []) - - def test_missing_llvm_tools_are_named_together(self): - (item,) = self.missing(have=("cmake", "clang-cl", "llvm-lib", "llvm-rc", "llvm-mt")) - self.assertTrue(item.startswith("lld-link: LLVM 19 or newer")) - (item,) = self.missing(have=("cmake",)) - self.assertTrue(item.startswith(", ".join(make_game.CROSS_TOOLS) + ":")) - - def test_clang_older_than_19_is_refused(self): - (item,) = self.missing(major=18) - self.assertIn("this one is 18", item) - self.assertEqual(self.missing(major=None), []) - - def test_cmake_and_the_sdk(self): - missing = self.missing(have=make_game.CROSS_TOOLS, sdk=os.path.join(self.sdk, "nothing")) - self.assertEqual(len(missing), 2) - self.assertEqual(missing[0], "CMake 3.24 or newer") - self.assertIn("xwin", missing[1]) - - def test_xwin_dir_defaults_to_the_documented_folder(self): - home = self.enterContext(tempfile.TemporaryDirectory()) - env = {k: v for k, v in os.environ.items() if k != "XWIN_DIR"} - with mock.patch.dict(os.environ, env, clear=True), \ - mock.patch.object(make_game.os.path, "expanduser", side_effect=lambda p: p.replace("~", home, 1)): - self.assertIsNone(make_game.xwin_dir()) - sdk = os.path.join(home, ".local", "share", "xwin-sdk") - os.makedirs(os.path.join(sdk, "VC", "Tools", "MSVC")) - self.assertIsNone(make_game.xwin_dir()) - os.makedirs(os.path.join(sdk, "Windows Kits", "10", "Lib", "10.0.26100", "um", "x64")) - self.assertEqual(make_game.xwin_dir(), sdk) - - -class RuntimeBuildPreflightTest(unittest.TestCase): - def preflight(self, build, files, err=None): - for name in files: - open(os.path.join(build, name), "wb").close() - err = io.StringIO() if err is None else err - with mock.patch.object(make_game.os, "name", "posix"), \ - mock.patch("sys.stderr", err), \ - mock.patch.object(make_game.sys, "version_info", (3, 12, 0)), \ - mock.patch.object(make_game, "visual_cpp_tools_ok", return_value=False) as vs: - make_game.preflight(["runtime"], os.path.join(build, "w"), runtime_build=build) - vs.assert_not_called() - return err.getvalue() - - def test_runtime_off_windows_passes_with_a_complete_build(self): - with tempfile.TemporaryDirectory() as build: - self.preflight(build, make_game.RUNTIME_FILES) - - def test_runtime_build_without_the_tls_host_fails_before_any_work(self): - err = io.StringIO() - with tempfile.TemporaryDirectory() as build: - with self.assertRaises(SystemExit) as ctx: - self.preflight(build, ["gta6rt.exe"], err=err) - self.assertEqual(ctx.exception.code, 1) - self.assertIn("gta6rt_tls_host.dll", err.getvalue()) - self.assertFalse(os.path.exists(os.path.join(build, "w"))) - - -class RuntimePackagingTest(unittest.TestCase): - def setUp(self): - self.root = self.enterContext(tempfile.TemporaryDirectory()) - self.build = os.path.join(self.root, "runtime", "build") - self.game = os.path.join(self.root, "game") - self.out = os.path.join(self.root, "out") - os.makedirs(self.build) - os.makedirs(self.game) - self.write_artifact("gta6rt.exe", b"runtime") - - def write_artifact(self, name, contents): - with open(os.path.join(self.build, name), "wb") as f: - f.write(contents) - - def test_first_load_hint(self): - self.write_artifact("gta6rt_tls_host.dll", b"TLS host") - image = "Player's Test.exe" - out = os.path.join(self.root, "Port Files") - for platform in ("nt", "posix"): - with self.subTest(platform=platform), mock.patch.object(make_game.os, "name", platform), \ - mock.patch.object(make_game, "log") as log: - path = os.path.join(self.game, image) - with open(path, "wb"): - pass - make_game.runtime(self.game, out, {"expected_exe": image}, self.build) - command = log.call_args.args[0].splitlines()[-1].strip() - if platform == "nt": - self.assertIn("--dry-run", command) - self.assertIn("gta6rt.exe'", command) - self.assertIn("Player''s Test.exe'", command) - else: - self.assertEqual(shlex.split(command), [os.path.join(out, "gta6rt.sh"), "--dry-run"]) - os.remove(path) - make_game.runtime(self.game, out, {"expected_exe": image}, self.build) - self.assertIn("is missing", log.call_args.args[0]) - self.assertNotIn("--dry-run", log.call_args.args[0]) - - @unittest.skipIf(os.name == "nt", "executes the generated POSIX launcher") - def test_wine_first_boot_uses_the_packaged_game_and_shader_paths(self): - image = "Player's test.exe" - # The launcher resolves its own path with `readlink -f` and lets `cd` settle the game directory, so what the - # runtime sees is the physical path. On macOS the temporary directory is /var/..., a symlink to /private/var, - # so the expectations are realpath'd too; on Linux the two are already equal. - def real(path): - return os.path.realpath(path) - - work = os.path.join(self.root, "Shader cache '$HOME'") - self.write_artifact("gta6rt_tls_host.dll", b"") - self.write_artifact("gta6rt.exe", b"import os, sys, json\n" - b"print(json.dumps([os.getcwd(), sys.argv[1:], os.getenv('LEONIDA_SHADERS'), " - b"os.getenv('LEONIDA_D3D12')]))\n") - make_game.runtime(self.game, self.out, {"expected_exe": image}, self.build, work=work) - launcher = os.path.join(self.out, "gta6rt.sh") - env = dict(os.environ, WINE=sys.executable) - env.pop("LEONIDA_D3D12", None) - env.pop("LEONIDA_SHADERS", None) - missing = subprocess.run([launcher, "--run"], cwd=self.root, env=env, capture_output=True, text=True) - self.assertNotEqual(missing.returncode, 0) - self.assertIn(image, missing.stderr) - with open(os.path.join(self.game, image), "wb"): - pass - for mode in ("--dry-run", "--init"): - with self.subTest(mode=mode): - result = subprocess.check_output([launcher, mode], cwd=self.root, env=env) - self.assertEqual(json.loads(result), [ - real(self.game), [mode, "./" + image, "--overlay", "Z:" + real(self.out) + "/overlay"], - None, "vulkan", - ]) - env.update(LEONIDA_SHADERS="D:/custom", LEONIDA_D3D12="trace") - result = subprocess.check_output([launcher, "--run"], cwd=self.root, env=env) - self.assertEqual(json.loads(result)[2:], ["D:/custom", "trace"]) - result = subprocess.check_output([launcher, "--run", "other.exe", "--", "two words"], cwd=self.root, env=env) - self.assertEqual(json.loads(result)[:2], [real(self.root), ["--run", "other.exe", "--", "two words"]]) - - work = os.path.join(self.out, "Shader cache '$HOME'") - make_game.runtime(self.game, self.out, {"expected_exe": image}, self.build, work=work) - moved = self.out + " moved" - os.rename(self.out, moved) - env.pop("LEONIDA_SHADERS") - result = subprocess.check_output([os.path.join(moved, "gta6rt.sh"), "--dry-run"], cwd=self.root, env=env) - self.assertEqual(json.loads(result)[2], "Z:" + real(moved) + "/Shader cache '$HOME'/shaders/spirv") - - def test_runtime_records_shader_work_directory(self): - self.write_artifact("gta6rt_tls_host.dll", b"TLS host") - work = os.path.join(self.root, "Shader Work \u03bb") - with mock.patch.object(make_game, "log"): - make_game.runtime(self.game, self.out, {"expected_exe": "game.exe"}, self.build, work=work) - with open(os.path.join(self.out, "shader_path.txt"), "rb") as f: - recorded = f.read() - self.assertEqual(recorded, os.fsencode(os.path.join(work, "shaders", "spirv"))) - - def package(self): - with mock.patch.object(make_game.os, "name", "nt"), \ - mock.patch.object(make_game, "ROOT", self.root), \ - mock.patch.object(make_game, "run"), \ - mock.patch.object(make_game, "log"): - make_game.runtime(self.game, self.out, {"expected_exe": "game.exe"}) - - def test_runtime_copies_executable_and_tls_host_together(self): - self.write_artifact("gta6rt_tls_host.dll", b"TLS host") - - self.package() - - with open(os.path.join(self.out, "gta6rt.exe"), "rb") as f: - self.assertEqual(f.read(), b"runtime") - with open(os.path.join(self.out, "gta6rt_tls_host.dll"), "rb") as f: - self.assertEqual(f.read(), b"TLS host") - with open(os.path.join(self.out, "game_path.txt"), encoding="utf-8") as f: - self.assertEqual(f.read(), self.game) - - def test_runtime_rejects_missing_tls_host_before_copying(self): - err = io.StringIO() - with mock.patch("sys.stderr", err), self.assertRaises(SystemExit) as ctx: - self.package() - - self.assertEqual(ctx.exception.code, 1) - self.assertIn("gta6rt_tls_host.dll", err.getvalue()) - self.assertFalse(os.path.exists(self.out)) - - def test_runtime_build_starts_powershell_by_its_full_path(self): - # The stage started "powershell" by name. CreateProcess searches System32 but not - # System32\WindowsPowerShell\v1.0, so on a PC whose PATH had lost that folder the stage ended in a - # FileNotFoundError traceback after the earlier stages had run. - self.write_artifact("gta6rt_tls_host.dll", b"TLS host") - system_root = os.path.join(self.root, "Windows") - folder = os.path.join(system_root, "System32", "WindowsPowerShell", "v1.0") - os.makedirs(folder) - exe = os.path.join(folder, "powershell.exe") - with open(exe, "wb"): - pass - with mock.patch.object(make_game.os, "name", "nt"), \ - mock.patch.object(make_game, "ROOT", self.root), \ - mock.patch.dict(os.environ, {"SystemRoot": system_root, "PATH": ""}), \ - mock.patch.object(make_game, "run") as run, \ - mock.patch.object(make_game, "log"): - make_game.runtime(self.game, self.out, {"expected_exe": "game.exe"}) - - command = run.call_args.args[0] - self.assertEqual(command[0], exe) - self.assertIn(os.path.join(self.root, "scripts", "build_runtime.ps1"), command) - - def test_powershell_is_the_bare_name_where_the_file_is_not_at_its_usual_place(self): - with mock.patch.dict(os.environ, {"SystemRoot": os.path.join(self.root, "nowhere")}): - self.assertEqual(make_game.windows_powershell(), "powershell") - - -class ConfiguredCrossToolsTest(unittest.TestCase): - def test_reads_cmakes_compiler_files_newest_last(self): - root = self.enterContext(tempfile.TemporaryDirectory()) - files = os.path.join(root, "runtime", "build", "windows", "CMakeFiles") - with mock.patch.object(make_game, "ROOT", root): - self.assertEqual(make_game.configured_cross_tools(), {}) - for version, compiler in (("3.31.0", "/old/clang-cl"), ("4.5.1", "/usr/bin/clang-cl")): - os.makedirs(os.path.join(files, version)) - with open(os.path.join(files, version, "CMakeCXXCompiler.cmake"), "w", encoding="utf-8") as f: - f.write(f'set(CMAKE_CXX_COMPILER "{compiler}")\nset(CMAKE_CXX_COMPILER_ARG1 "")\n' - 'set(CMAKE_AR "llvm-lib")\nset(CMAKE_LINKER "/usr/bin/lld-link")\n' - 'set(CMAKE_MT "/usr/bin/llvm-mt")\n') - os.utime(os.path.join(files, version, "CMakeCXXCompiler.cmake"), (1, 1 if version == "3.31.0" else 2)) - with open(os.path.join(files, "4.5.1", "CMakeRCCompiler.cmake"), "w", encoding="utf-8") as f: - f.write('set(CMAKE_RC_COMPILER "llvm-rc")\n') - with mock.patch.object(make_game, "ROOT", root): - self.assertEqual(make_game.configured_cross_tools(), { - "CMAKE_CXX_COMPILER": "/usr/bin/clang-cl", "CMAKE_AR": "llvm-lib", "CMAKE_LINKER": "/usr/bin/lld-link", - "CMAKE_MT": "/usr/bin/llvm-mt", "CMAKE_RC_COMPILER": "llvm-rc"}) - - -class CrossBuildTest(unittest.TestCase): - def setUp(self): - self.root = self.enterContext(tempfile.TemporaryDirectory()) - self.build = os.path.join(self.root, "runtime", "build", "windows") - self.game = os.path.join(self.root, "game") - self.out = os.path.join(self.root, "out") - os.makedirs(self.game) - - def runtime(self, xwin="/sdk", ninja=True, suffix="", configured=None): - def which(t): - if t == "ninja": - return "/usr/bin/ninja" if ninja else None - return f"/usr/bin/{t}" if suffix else None - def fake_run(args, hint="", **kw): - if args[1] == "--build": - os.makedirs(self.build, exist_ok=True) - for name in make_game.RUNTIME_FILES: - with open(os.path.join(self.build, name), "wb") as f: - f.write(name.encode()) - with mock.patch.object(make_game.os, "name", "posix"), \ - mock.patch.object(make_game, "ROOT", self.root), \ - mock.patch.object(make_game, "xwin_dir", return_value=xwin), \ - mock.patch.object(make_game.shutil, "which", side_effect=which), \ - mock.patch.object(make_game, "cross_tool_suffix", return_value=suffix), \ - mock.patch.object(make_game, "configured_cross_tools", return_value=configured or {}), \ - mock.patch.object(make_game, "run", side_effect=fake_run) as self.run_mock, \ - mock.patch.object(make_game, "log"): - make_game.runtime(self.game, self.out, {"expected_exe": "game.exe"}, None, 4) - return [c.args[0] for c in self.run_mock.call_args_list] - - def test_cross_builds_the_loader_and_packages_it_for_wine(self): - configure, build = self.runtime() - toolchain = os.path.join(self.root, "runtime", "cmake", "clang-cl-xwin.cmake") - self.assertEqual(configure, ["cmake", "-S", os.path.join(self.root, "runtime"), "-B", self.build, - "-G", "Ninja", "-DCMAKE_BUILD_TYPE=RelWithDebInfo", - "--toolchain", toolchain, "-DXWIN_DIR=/sdk"]) - self.assertEqual(build, ["cmake", "--build", self.build, "--parallel", "4", - "--target", "gta6rt", "gta6rt_tls_host"]) - for name in make_game.RUNTIME_FILES: - with open(os.path.join(self.out, name), "rb") as f: - self.assertEqual(f.read(), name.encode()) - self.assertTrue(os.path.isfile(os.path.join(self.out, "gta6rt.sh"))) - - def test_versioned_tools_are_passed_until_the_folder_records_its_tools(self): - for cache in (False, True): - if cache: - open(os.path.join(self.build, "CMakeCache.txt"), "w").close() - configure, _ = self.runtime(suffix="-21") - for var, name in make_game.CROSS_VARS.items(): - self.assertIn(f"-DCMAKE_{var}=/usr/bin/{name}-21", configure) - configure, _ = self.runtime(suffix="-21", configured={"CMAKE_CXX_COMPILER": "/usr/bin/clang-cl-21"}) - self.assertFalse(any(a.startswith("-DCMAKE_CXX_COMPILER") for a in configure)) - - def test_without_ninja_cmake_picks_the_generator(self): - configure, _ = self.runtime(ninja=False) - self.assertNotIn("-G", configure) - self.assertIn("-DCMAKE_BUILD_TYPE=RelWithDebInfo", configure) - - def test_an_existing_build_folder_keeps_its_generator_and_build_type(self): - os.makedirs(self.build) - open(os.path.join(self.build, "CMakeCache.txt"), "w").close() - configure, _ = self.runtime() - self.assertNotIn("-G", configure) - self.assertFalse(any(a.startswith("-DCMAKE_BUILD_TYPE") for a in configure)) - self.assertIn("-DXWIN_DIR=/sdk", configure) - - def test_without_an_sdk_nothing_runs(self): - err = io.StringIO() - with mock.patch("sys.stderr", err), self.assertRaises(SystemExit): - self.runtime(xwin=None) - self.run_mock.assert_not_called() - self.assertIn("xwin", err.getvalue()) - self.assertFalse(os.path.exists(self.out)) - - -class RuntimeBuildPackagingTest(unittest.TestCase): - def test_windows_native_build_receives_the_requested_jobs(self): - with tempfile.TemporaryDirectory() as root: - build = os.path.join(root, "runtime", "build") - os.makedirs(build) - for name in make_game.RUNTIME_FILES: - open(os.path.join(build, name), "wb").close() - with mock.patch.object(make_game.os, "name", "nt"), \ - mock.patch.object(make_game, "ROOT", root), \ - mock.patch.object(make_game, "run") as run, mock.patch.object(make_game, "log"): - make_game.runtime(root, os.path.join(root, "out"), {"expected_exe": "game.exe"}, jobs=1) - command = run.call_args.args[0] - self.assertEqual(command[command.index("-File") + 1:], - [os.path.join(root, "scripts", "build_runtime.ps1"), "-Jobs", "1"]) - - def test_off_windows_copies_the_build_and_writes_a_wine_launcher(self): - with tempfile.TemporaryDirectory() as root: - build, game, out = (os.path.join(root, n) for n in ("build", "game", "out")) - os.makedirs(build) - os.makedirs(game) - for name in make_game.RUNTIME_FILES: - with open(os.path.join(build, name), "wb") as f: - f.write(name.encode()) - with mock.patch.object(make_game.os, "name", "posix"), \ - mock.patch.object(make_game, "run") as run, \ - mock.patch.object(make_game, "log"): - make_game.runtime(game, out, {"expected_exe": "game.exe"}, build) - run.assert_not_called() - for name in make_game.RUNTIME_FILES: - with open(os.path.join(out, name), "rb") as f: - self.assertEqual(f.read(), name.encode()) - launcher = os.path.join(out, "gta6rt.sh") - with open(launcher, encoding="utf-8") as f: - text = f.read() - self.assertTrue(text.startswith("#!/bin/sh\n")) - self.assertIn('"${WINE:-wine}" "$here/gta6rt.exe" "$@"', text) - if os.name != "nt": - self.assertTrue(os.access(launcher, os.X_OK)) - - -class PipelineCheckExeTest(unittest.TestCase): - def setUp(self): - self.tmp = tempfile.TemporaryDirectory() - self.build = os.path.join(self.tmp.name, "runtime", "build") - os.makedirs(os.path.join(self.build, "linux")) - self.root = mock.patch.object(make_game, "ROOT", self.tmp.name) - self.root.start() - - def tearDown(self): - self.root.stop() - self.tmp.cleanup() - - def touch(self, *parts): - p = os.path.join(self.build, *parts) - open(p, "w").close() - return p - - def exe(self, os_name, runtime_build=None): - with mock.patch.object(make_game.os, "name", os_name): - return make_game.pipeline_check_exe(runtime_build) - - def test_linux_prefers_the_readme_build_folder(self): - self.assertIsNone(self.exe("posix")) - plain = self.touch("vk_pipeline_check") - os.chmod(plain, 0o755) - self.assertEqual(self.exe("posix"), plain) - readme = self.touch("linux", "vk_pipeline_check") - os.chmod(readme, 0o755) - self.assertEqual(self.exe("posix"), readme) - - @unittest.skipUnless(os.name == "posix", "requires POSIX execute permissions") - def test_non_executable_linux_checker_does_not_hide_the_fallback(self): - preferred = self.touch("linux", "vk_pipeline_check") - os.chmod(preferred, 0o644) - fallback = self.touch("vk_pipeline_check") - os.chmod(fallback, 0o755) - self.assertEqual(self.exe("posix"), fallback) - - def test_windows_finds_only_the_exe(self): - self.touch("linux", "vk_pipeline_check") - self.assertIsNone(self.exe("nt")) - exe = self.touch("vk_pipeline_check.exe") - self.assertEqual(self.exe("nt"), exe) - - def test_windows_prefers_supplied_checker_and_falls_back_to_local_build(self): - local = self.touch("vk_pipeline_check.exe") - with tempfile.TemporaryDirectory() as supplied: - self.assertEqual(self.exe("nt", supplied), local) - bundled = os.path.join(supplied, "vk_pipeline_check.exe") - with open(bundled, "wb"): - pass - self.assertEqual(self.exe("nt", supplied), bundled) - - def test_pipelines_off_windows_runs_the_linux_build(self): - exe = self.touch("linux", "vk_pipeline_check") - os.chmod(exe, 0o755) - self.touch("vk_pipeline_check.exe") - work = os.path.join(self.tmp.name, "work") - os.makedirs(os.path.join(work, "shaders", "spirv")) - with open(os.path.join(work, "shaders", "spirv", "index.json"), "w") as f: - f.write('{"shader_0": {}}') # a finished translation is never empty - out = os.path.join(self.tmp.name, "out") - with mock.patch.object(make_game.os, "name", "posix"), \ - mock.patch.object(make_game, "log"), \ - mock.patch.object(make_game, "run", return_value=0) as run: - make_game.pipelines(work, out, runtime_build=self.build) - self.assertEqual(run.call_args.args[0][0], exe) - - def test_pipelines_off_windows_without_the_build_says_how_to_build_it(self): - err = io.StringIO() - with mock.patch.object(make_game.os, "name", "posix"), mock.patch("sys.stderr", err): - with self.assertRaises(SystemExit): - make_game.pipelines(os.path.join(self.tmp.name, "work"), os.path.join(self.tmp.name, "out")) - self.assertIn("cmake -S runtime -B runtime/build/linux", err.getvalue()) - - -class RuntimeStageCopyTest(unittest.TestCase): - """runtime() with --runtime-build: the build's files go to the output folder, which may be the build folder.""" - - def run_stage(self, build, out, *, work=None): - for name in make_game.RUNTIME_FILES: - with open(os.path.join(build, name), "wb") as f: - f.write(name.encode()) - with mock.patch.object(make_game, "log"), mock.patch.object(make_game.os, "name", "posix"): - make_game.runtime(os.path.join(build, "game"), out, {"expected_exe": "game.exe"}, - runtime_build=build, work=work) - - def test_directory_at_a_generated_path_leaves_the_previous_runtime_untouched(self): - outputs = (*make_game.RUNTIME_FILES, "game_path.txt", "shader_path.txt", "gta6rt.sh") - for blocked in outputs: - with self.subTest(blocked=blocked), tempfile.TemporaryDirectory() as build, \ - tempfile.TemporaryDirectory() as out: - directory = os.path.join(out, blocked) - os.mkdir(directory) - marker = os.path.join(directory, "marker") - with open(marker, "wb") as f: - f.write(b"existing directory content") - previous = {name: b"previous " + name.encode() for name in outputs if name != blocked} - for name, contents in previous.items(): - with open(os.path.join(out, name), "wb") as f: - f.write(contents) - - error = io.StringIO() - with mock.patch.object(sys, "stderr", error), self.assertRaises((SystemExit, OSError)) as failure: - self.run_stage(build, out, work=os.path.join(build, "work")) - - for name, contents in previous.items(): - with open(os.path.join(out, name), "rb") as f: - self.assertEqual(f.read(), contents, name) - with open(marker, "rb") as f: - self.assertEqual(f.read(), b"existing directory content") - self.assertIsInstance(failure.exception, SystemExit) - self.assertIn(directory, error.getvalue()) - - def test_directory_collision_is_checked_before_building(self): - with tempfile.TemporaryDirectory() as out: - os.mkdir(os.path.join(out, "game_path.txt")) - with mock.patch.object(make_game, "run") as build, \ - mock.patch.object(make_game, "cross_build_runtime") as cross_build, \ - mock.patch.object(sys, "stderr"), self.assertRaises(SystemExit): - make_game.runtime(out, out, {"expected_exe": "game.exe"}) - build.assert_not_called() - cross_build.assert_not_called() - - def test_the_build_is_copied_to_another_folder(self): - with tempfile.TemporaryDirectory() as build, tempfile.TemporaryDirectory() as out: - self.run_stage(build, out) - for name in make_game.RUNTIME_FILES: - with open(os.path.join(out, name), "rb") as f: - self.assertEqual(f.read(), name.encode()) - self.assertTrue(os.path.isfile(os.path.join(out, "game_path.txt"))) - - def test_the_build_folder_as_the_output_folder(self): - # shutil.copy2 of a file onto itself raises SameFileError, and the stage stopped before game_path.txt - with tempfile.TemporaryDirectory() as build: - self.run_stage(build, build) - for name in make_game.RUNTIME_FILES: - with open(os.path.join(build, name), "rb") as f: - self.assertEqual(f.read(), name.encode()) - self.assertTrue(os.path.isfile(os.path.join(build, "game_path.txt"))) - - def test_an_older_copy_in_the_output_folder_is_replaced(self): - with tempfile.TemporaryDirectory() as build, tempfile.TemporaryDirectory() as out: - with open(os.path.join(out, make_game.RUNTIME_FILES[0]), "wb") as f: - f.write(b"old") - self.run_stage(build, out) - with open(os.path.join(out, make_game.RUNTIME_FILES[0]), "rb") as f: - self.assertEqual(f.read(), make_game.RUNTIME_FILES[0].encode()) - - -class RedirectedConsoleEncodingTest(unittest.TestCase): - """`--find` must survive a dump path no single-byte code page can write. - - Windows encodes a redirected stdout (make_game.py > build.log) with the console's ANSI code page, and - `python -I` ignores PYTHONUTF8, so a path with a character outside that code page -- a Cyrillic, Greek or - CJK user name in the profile a dump sits under -- reached print() as UnicodeEncodeError and ended the - listing with a traceback (stderr escapes such characters; stdout was strict). The dump below sits under a - private-use character that no ANSI code page maps, so before the fix the child dies the same way on every - Windows locale; on UTF-8 systems the character prints and this passes either way. - """ - - def setUp(self): - self.tmp = tempfile.TemporaryDirectory() - self.addCleanup(self.tmp.cleanup) - - def test_find_lists_a_dump_whose_path_the_console_code_page_cannot_write(self): - home = os.path.join(self.tmp.name, "home") - dump = os.path.join(home, "Downloads", "GTA6-\ue9c3") - os.makedirs(dump) - with open(os.path.join(ROOT, "game", "xbox-1.0.2.1.json"), encoding="utf-8") as f: - sizes = json.load(f)["files"] - for name in make_game.PROBES: # match_version() reads only names and sizes - with open(os.path.join(dump, name), "wb") as f: - f.truncate(sizes[name]["size"]) - env = dict(os.environ, USERPROFILE=home, HOME=home) - r = subprocess.run([sys.executable, "-I", os.path.join(ROOT, "make_game.py"), "--find"], - capture_output=True, env=env, cwd=ROOT, encoding="utf-8", errors="replace") - self.assertEqual(r.returncode, 0, r.stderr) - self.assertNotIn("Traceback", r.stderr) - self.assertNotIn("UnicodeEncodeError", r.stderr) - self.assertTrue(any(f"GTA6-{c}" in r.stdout for c in ("\ue9c3", "?")), - f"the synthetic dump was not listed: {r.stdout!r}") - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/test_make_game_preflight.py b/tests/test_make_game_preflight.py deleted file mode 100644 index c3a83e4e3..000000000 --- a/tests/test_make_game_preflight.py +++ /dev/null @@ -1,1340 +0,0 @@ -"""Unit test suite covering make_game.py prerequisite checking, version string parsing, and toolchain detection. - - python -I tests/test_make_game_preflight.py - python -m unittest discover -s tests -v - -Tests use synthetic manifests, mock environments, and isolated temporary directories so they are deterministic, -fast, and contain zero game data. -""" -from collections import namedtuple -import functools -import io -import json -import os -import re -import shutil -import subprocess -import sys -import tempfile -import unittest -from unittest import mock - -ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) -if ROOT not in sys.path: - sys.path.insert(0, ROOT) - -import make_game # noqa: E402 - -Usage = namedtuple("Usage", ["total", "used", "free"]) - - -class PreflightTestBase(unittest.TestCase): - def assert_fails(self, fn, *args, match=None, **kwargs): - stderr_buf = io.StringIO() - with mock.patch("sys.stderr", stderr_buf): - with self.assertRaises(SystemExit) as ctx: - fn(*args, **kwargs) - self.assertEqual(ctx.exception.code, 1) - err = stderr_buf.getvalue() - if match: - self.assertIn(match, err) - return err - - -class VersionParsingAndMatchingTest(PreflightTestBase): - def test_versions_loads_valid_manifest(self): - manifests = make_game.versions() - self.assertGreaterEqual(len(manifests), 1) - v = manifests[0] - self.assertIn("title", v) - self.assertIn("version", v) - self.assertIn("files", v) - self.assertIn("expected_exe", v) - self.assertEqual(v["version"], "1.0.2.1") - self.assertEqual(v["expected_exe"], "game_scarlett_master.exe") - - def test_version_string_parsing_and_ordering(self): - manifests = make_game.versions() - parsed = [tuple(map(int, v["version"].split("."))) for v in manifests] - self.assertIn((1, 0, 2, 1), parsed) - self.assertGreater((1, 0, 2, 1), (1, 0, 2, 0)) - self.assertGreater((1, 0, 2, 0), (1, 0, 1, 9)) - self.assertGreater((2, 0, 0, 0), (1, 9, 9, 9)) - - def test_versions_custom_directory_and_json_filtering(self): - with tempfile.TemporaryDirectory() as tmp: - v1_path = os.path.join(tmp, "b_1.0.0.json") - v2_path = os.path.join(tmp, "a_2.0.0.json") - txt_path = os.path.join(tmp, "readme.txt") - - with open(v1_path, "w", encoding="utf-8") as f: - json.dump({"title": "Custom B", "version": "1.0.0", "files": {}, "expected_exe": "b.exe"}, f) - with open(v2_path, "w", encoding="utf-8") as f: - json.dump({"title": "Custom A", "version": "2.0.0", "files": {}, "expected_exe": "a.exe"}, f) - with open(txt_path, "w", encoding="utf-8") as f: - f.write("ignored") - - with mock.patch.object(make_game, "VERSIONS", tmp): - loaded = make_game.versions() - self.assertEqual(len(loaded), 2) - # sorted by filename in os.listdir - self.assertEqual(loaded[0]["version"], "2.0.0") - self.assertEqual(loaded[1]["version"], "1.0.0") - - def test_match_version_success_on_probes(self): - with tempfile.TemporaryDirectory() as tmp: - manifest = make_game.versions()[0] - for probe_name in make_game.PROBES: - size = manifest["files"][probe_name]["size"] - probe_path = os.path.join(tmp, probe_name) - with open(probe_path, "wb") as f: - f.truncate(size) - - matched = make_game.match_version(tmp) - self.assertIsNotNone(matched) - self.assertEqual(matched["version"], manifest["version"]) - - def test_match_version_missing_probe_returns_none(self): - with tempfile.TemporaryDirectory() as tmp: - manifest = make_game.versions()[0] - # Create 2 probes, skip appdata0.rpf - for probe_name in ("MicrosoftGame.Config", "Catalog000.bin"): - size = manifest["files"][probe_name]["size"] - probe_path = os.path.join(tmp, probe_name) - with open(probe_path, "wb") as f: - f.truncate(size) - - self.assertIsNone(make_game.match_version(tmp)) - - def test_match_version_wrong_probe_size_returns_none(self): - with tempfile.TemporaryDirectory() as tmp: - manifest = make_game.versions()[0] - for probe_name in make_game.PROBES: - size = manifest["files"][probe_name]["size"] - probe_path = os.path.join(tmp, probe_name) - with open(probe_path, "wb") as f: - f.truncate(size + 1 if probe_name == "MicrosoftGame.Config" else size) - - self.assertIsNone(make_game.match_version(tmp)) - - def test_match_version_empty_directory_returns_none(self): - with tempfile.TemporaryDirectory() as tmp: - self.assertIsNone(make_game.match_version(tmp)) - - def test_load_version_success(self): - with tempfile.TemporaryDirectory() as tmp: - manifest = make_game.versions()[0] - for probe_name in make_game.PROBES: - size = manifest["files"][probe_name]["size"] - probe_path = os.path.join(tmp, probe_name) - with open(probe_path, "wb") as f: - f.truncate(size) - - loaded = make_game.load_version(tmp) - self.assertEqual(loaded["version"], manifest["version"]) - - def test_load_version_failure_reports_supported_versions(self): - with tempfile.TemporaryDirectory() as tmp: - err = self.assert_fails(make_game.load_version, tmp, - match="This doesn't look like a supported version of the game") - self.assertIn("Supported:", err) - self.assertIn("1.0.2.1", err) - for name in make_game.PROBES: - self.assertIn(f"Missing {name}.", err) - - def test_a_probe_whose_name_differs_only_in_case_is_named(self): - with tempfile.TemporaryDirectory() as tmp: - manifest = make_game.versions()[0] - for probe_name in make_game.PROBES: - with open(os.path.join(tmp, probe_name.lower()), "wb") as f: - f.truncate(manifest["files"][probe_name]["size"]) - if os.path.exists(os.path.join(tmp, "MicrosoftGame.Config")): - self.skipTest("case-insensitive file system: the lower-cased names open under the package's") - mismatches = make_game.probe_mismatches(tmp, manifest) - self.assertIn("Missing MicrosoftGame.Config: there is microsoftgame.config, but file names are " - "case-sensitive", mismatches[0]) - self.assertIn("Rename it to MicrosoftGame.Config", mismatches[0]) - self.assertIn("Missing Catalog000.bin: there is catalog000.bin", mismatches[1]) - self.assertEqual(len(mismatches), 2) # appdata0.rpf is lower case in the package too: it matches - - def test_other_case_ignores_the_exact_name_and_unrelated_files(self): - with tempfile.TemporaryDirectory() as tmp: - for name in ("Catalog000.bin.bak", "Catalog000.bin"): - open(os.path.join(tmp, name), "wb").close() - self.assertIsNone(make_game.other_case(tmp, "Catalog000.bin")) - self.assertIsNone(make_game.other_case(os.path.join(tmp, "absent"), "Catalog000.bin")) - - -class GameCheckTest(PreflightTestBase): - def test_check_nonexistent_directory_fails(self): - self.assert_fails(make_game.check, "nonexistent_dir_0xdeadbeef", full=False, - match="Game folder not found: nonexistent_dir_0xdeadbeef") - - def test_check_option_reports_each_version_probe_mismatch(self): - with tempfile.TemporaryDirectory() as tmp: - with open(os.path.join(tmp, "MicrosoftGame.Config"), "wb") as config: - config.write(b"test") - os.mkdir(os.path.join(tmp, "Catalog000.bin")) - manifests = [ - {"title": "Synthetic", "version": version, "files": { - "MicrosoftGame.Config": {"size": size}, - "Catalog000.bin": {"size": 8}, - "appdata0.rpf": {"size": 16}, - }} - for version, size in [("1.0", 6), ("2.0", 10)] - ] - with mock.patch.object(make_game, "versions", return_value=manifests), \ - mock.patch.object(sys, "argv", ["make_game.py", "--check", "--game", tmp]): - err = self.assert_fails(make_game.main) - - self.assertIn("Synthetic 1.0\n Wrong size for MicrosoftGame.Config (4 bytes, expected 6).", err) - self.assertIn("Synthetic 2.0\n Wrong size for MicrosoftGame.Config (4 bytes, expected 10).", err) - self.assertEqual(err.count("Catalog000.bin is not a regular file."), 2) - self.assertEqual(err.count("Missing appdata0.rpf."), 2) - - def test_check_synthetic_game_all_files_present_with_exe(self): - with tempfile.TemporaryDirectory() as tmp: - manifest_dir = os.path.join(tmp, "manifests") - game_dir = os.path.join(tmp, "game") - os.makedirs(manifest_dir) - os.makedirs(game_dir) - - v_info = { - "title": "Synthetic Port Test", - "version": "9.9.9.9", - "expected_exe": "test_game.exe", - "files": { - "MicrosoftGame.Config": {"size": 16}, - "Catalog000.bin": {"size": 32}, - "appdata0.rpf": {"size": 64}, - "sub/data.bin": {"size": 128}, - }, - } - with open(os.path.join(manifest_dir, "custom.json"), "w", encoding="utf-8") as f: - json.dump(v_info, f) - - for rel, info in v_info["files"].items(): - p = os.path.join(game_dir, rel) - os.makedirs(os.path.dirname(p), exist_ok=True) - with open(p, "wb") as f: - f.truncate(info["size"]) - - exe_p = os.path.join(game_dir, v_info["expected_exe"]) - with open(exe_p, "wb") as f: - f.truncate(256) - - stdout_buf = io.StringIO() - with mock.patch.object(make_game, "VERSIONS", manifest_dir): - with mock.patch("sys.stdout", stdout_buf): - res = make_game.check(game_dir, full=False) - - self.assertEqual(res["version"], "9.9.9.9") - self.assertIn("all files present", stdout_buf.getvalue()) - self.assertIn("Executable found.", stdout_buf.getvalue()) - - def test_check_missing_files_fails(self): - with tempfile.TemporaryDirectory() as tmp: - manifest_dir = os.path.join(tmp, "manifests") - game_dir = os.path.join(tmp, "game") - os.makedirs(manifest_dir) - os.makedirs(game_dir) - - v_info = { - "title": "Synthetic Missing Test", - "version": "9.9.9.9", - "expected_exe": "test_game.exe", - "files": { - "MicrosoftGame.Config": {"size": 16}, - "Catalog000.bin": {"size": 32}, - "appdata0.rpf": {"size": 64}, - "missing.bin": {"size": 100}, - }, - } - with open(os.path.join(manifest_dir, "custom.json"), "w", encoding="utf-8") as f: - json.dump(v_info, f) - - for rel in ("MicrosoftGame.Config", "Catalog000.bin", "appdata0.rpf"): - p = os.path.join(game_dir, rel) - with open(p, "wb") as f: - f.truncate(v_info["files"][rel]["size"]) - - with mock.patch.object(make_game, "VERSIONS", manifest_dir): - self.assert_fails(make_game.check, game_dir, full=False, - match="1 file(s) missing or different") - - def test_check_wrong_size_file_fails(self): - with tempfile.TemporaryDirectory() as tmp: - manifest_dir = os.path.join(tmp, "manifests") - game_dir = os.path.join(tmp, "game") - os.makedirs(manifest_dir) - os.makedirs(game_dir) - - v_info = { - "title": "Synthetic Size Test", - "version": "9.9.9.9", - "expected_exe": "test_game.exe", - "files": { - "MicrosoftGame.Config": {"size": 16}, - "Catalog000.bin": {"size": 32}, - "appdata0.rpf": {"size": 64}, - "extra.bin": {"size": 100}, - }, - } - with open(os.path.join(manifest_dir, "custom.json"), "w", encoding="utf-8") as f: - json.dump(v_info, f) - - for rel, info in v_info["files"].items(): - p = os.path.join(game_dir, rel) - with open(p, "wb") as f: - f.truncate(info["size"] + 5 if rel == "extra.bin" else info["size"]) - - with mock.patch.object(make_game, "VERSIONS", manifest_dir): - self.assert_fails(make_game.check, game_dir, full=False, - match="1 file(s) missing or different") - - def test_check_missing_exe_logs_warning_and_proceeds(self): - with tempfile.TemporaryDirectory() as tmp: - manifest_dir = os.path.join(tmp, "manifests") - game_dir = os.path.join(tmp, "game") - os.makedirs(manifest_dir) - os.makedirs(game_dir) - - v_info = { - "title": "Synthetic No Exe", - "version": "9.9.9.9", - "expected_exe": "custom_loader.exe", - "files": { - "MicrosoftGame.Config": {"size": 16}, - "Catalog000.bin": {"size": 32}, - "appdata0.rpf": {"size": 64}, - }, - } - with open(os.path.join(manifest_dir, "custom.json"), "w", encoding="utf-8") as f: - json.dump(v_info, f) - - for rel, info in v_info["files"].items(): - p = os.path.join(game_dir, rel) - with open(p, "wb") as f: - f.truncate(info["size"]) - - stdout_buf = io.StringIO() - with mock.patch.object(make_game, "VERSIONS", manifest_dir): - with mock.patch("sys.stdout", stdout_buf): - res = make_game.check(game_dir, full=False) - - self.assertEqual(res["version"], "9.9.9.9") - self.assertIn("custom_loader.exe is not in the folder", stdout_buf.getvalue()) - - -class ToolchainDetectionTest(PreflightTestBase): - def test_tool_available_direct_file(self): - self.assertTrue(make_game.tool_available(sys.executable)) - - def test_tool_available_quoted_string(self): - self.assertTrue(make_game.tool_available(f'"{sys.executable}"')) - - def test_tool_available_command_with_arguments(self): - self.assertTrue(make_game.tool_available(f'"{sys.executable}" -I')) - - def test_tool_available_shutil_which_lookup(self): - with mock.patch("shutil.which", return_value=r"C:\bin\custom_tool.exe"): - self.assertTrue(make_game.tool_available("custom_tool")) - - def test_tool_available_nonexistent_command(self): - self.assertFalse(make_game.tool_available("nonexistent_compiler_xyz_789")) - - def test_tool_available_empty_and_whitespace(self): - self.assertFalse(make_game.tool_available("")) - self.assertFalse(make_game.tool_available(" ")) - self.assertFalse(make_game.tool_available('""')) - - APPDATA_ENV = {"LOCALAPPDATA": r"C:\Users\u\AppData\Local", "APPDATA": r"C:\Users\u\AppData\Roaming"} - - def test_appdata_hint_names_the_folder_llvm_mc_is_in(self): - with mock.patch("os.name", "nt"), mock.patch.dict(os.environ, self.APPDATA_ENV): - for cmd, var in ((r"C:\Users\u\AppData\Local\Leonida\llvm-mc\llvm-mc.exe", "LOCALAPPDATA"), - (r'"c:\users\U\appdata\roaming\llvm\llvm-mc.exe"', "APPDATA")): - with self.subTest(cmd=cmd): - hint = make_game.appdata_hint(cmd) - self.assertIn(f"LLVM_MC points into %{var}%", hint) - self.assertIn(r"%USERPROFILE%\.leonida\llvm-mc", hint) - - def test_appdata_hint_is_empty_outside_appdata(self): - with mock.patch("os.name", "nt"), mock.patch.dict(os.environ, self.APPDATA_ENV): - for cmd in ("llvm-mc", r"D:\Tools\llvm-mc\llvm-mc.exe", r"C:\Users\u\.leonida\llvm-mc\llvm-mc.exe", - r"C:\Users\u\AppData\LocalLow\llvm-mc.exe", "wsl -d Ubuntu -e /usr/lib/llvm-21/bin/llvm-mc"): - with self.subTest(cmd=cmd): - self.assertEqual(make_game.appdata_hint(cmd), "") - - def test_appdata_hint_is_empty_off_windows(self): - with mock.patch("os.name", "posix"), mock.patch.dict(os.environ, self.APPDATA_ENV): - self.assertEqual(make_game.appdata_hint(r"C:\Users\u\AppData\Local\llvm-mc.exe"), "") - - def test_need_success_returns_tool(self): - self.assertEqual(make_game.need(sys.executable, "Install python"), sys.executable) - - def test_need_failure_exits_with_hint(self): - self.assert_fails(make_game.need, "ghost_compiler", "Please install it.", - match="'ghost_compiler' was not found on PATH. Please install it.") - - -class PreflightPrerequisiteTest(PreflightTestBase): - def setUp(self): - super().setUp() - # preflight runs `dotnet --list-sdks` (#223). Follow the test's faked shutil.which instead: the SDK counts as - # installed exactly when the test says dotnet is on PATH, so no real dotnet is needed and none is consulted. - patcher = mock.patch("make_game.dotnet_sdk_ok", side_effect=lambda: bool(shutil.which("dotnet"))) - patcher.start() - self.addCleanup(patcher.stop) - - def test_preflight_success_all_tools_present_and_space_sufficient(self): - with tempfile.TemporaryDirectory() as tmp_work: - with mock.patch("sys.version_info", (3, 12, 0)), \ - mock.patch("shutil.which", return_value="/usr/bin/tool"), \ - mock.patch("make_game.tool_available", return_value=True), \ - mock.patch("make_game.ensure_submodule", return_value=None) as ensure_submodule, \ - mock.patch("make_game.visual_cpp_tools_ok", return_value=True), \ - mock.patch("shutil.disk_usage", return_value=Usage(1000 * 2**30, 200 * 2**30, 800 * 2**30)): - # off Windows runtime checks the cross-build instead (tests/test_make_game_platform.py) - stages = ["shaders", "assets"] + (["runtime"] if os.name == "nt" else []) - make_game.preflight(stages, tmp_work, wav=True) - ensure_submodule.assert_called_once_with() - - def test_preflight_aggregates_multiple_missing_tools_and_deduplicates(self): - with tempfile.TemporaryDirectory() as tmp_work: - with mock.patch("sys.version_info", (3, 12, 0)), \ - mock.patch("shutil.which", return_value=None), \ - mock.patch("make_game.tool_available", return_value=False), \ - mock.patch.object(make_game, "ROOT", tmp_work), \ - mock.patch("os.path.isfile", return_value=False), \ - mock.patch("os.name", "nt"): - err = self.assert_fails(make_game.preflight, ["shaders", "assets", "runtime"], tmp_work, wav=True, - match="Install these first, then run the build again:") - self.assertIn("ffmpeg (needed for --wav)", err) - self.assertIn("llvm-mc (LLVM 21+ with the AMDGPU target)", err) - self.assertIn("spirv-as:", err) - self.assertIn("spirv-val:", err) - self.assertIn(".NET 8 SDK", err) - self.assertIn("Visual Studio 2022", err) - - def test_preflight_accepts_spaced_llvm_mc_resolved_by_which(self): - with tempfile.TemporaryDirectory() as tmp_work: - mc = os.path.join(tmp_work, "LLVM Tools", "llvm-mc") - available = {mc: mc + ".exe", "spirv-as": "spirv-as", "spirv-val": "spirv-val"} - with mock.patch.dict(os.environ, {"LLVM_MC": mc}), \ - mock.patch("shutil.which", side_effect=available.get), \ - mock.patch("shutil.disk_usage", return_value=Usage(100 * 2**30, 0, 100 * 2**30)): - make_game.preflight(["shaders"], tmp_work) - - def test_preflight_explains_llvm_mc_hidden_in_appdata(self): - env = {"LOCALAPPDATA": r"C:\Users\u\AppData\Local", - "LLVM_MC": r"C:\Users\u\AppData\Local\Leonida\llvm-mc\llvm-mc.exe"} - available = {"spirv-as": "spirv-as", "spirv-val": "spirv-val"} - with tempfile.TemporaryDirectory() as tmp_work, \ - mock.patch.dict(os.environ, env), \ - mock.patch("os.name", "nt"), \ - mock.patch("sys.version_info", (3, 12, 0)), \ - mock.patch("shutil.which", side_effect=available.get), \ - mock.patch("os.path.isfile", return_value=False): - err = self.assert_fails(make_game.preflight, ["shaders"], tmp_work, - match="llvm-mc (LLVM 21+ with the AMDGPU target)") - self.assertIn("LLVM_MC points into %LOCALAPPDATA%", err) - - def test_preflight_rejects_visual_studio_installer_without_cpp_tools(self): - with tempfile.TemporaryDirectory() as tmp_work, \ - mock.patch("os.name", "nt"), \ - mock.patch("os.path.isfile", return_value=True), \ - mock.patch("subprocess.run", return_value=mock.Mock(returncode=0, stdout=b"\r\n")): - self.assert_fails(make_game.preflight, ["runtime"], tmp_work, match="Visual Studio 2022") - - def test_visual_cpp_tools_accepts_matching_installation(self): - with mock.patch("os.path.isfile", return_value=True), \ - mock.patch("subprocess.run", return_value=mock.Mock(returncode=0, stdout=b"C:\\VS\r\n")) as run: - self.assertTrue(make_game.visual_cpp_tools_ok()) - self.assertEqual(run.call_args.args[0][1:], ["-latest", "-products", "*", "-requires", - "Microsoft.VisualStudio.Component.VC.Tools.x86.x64", - "-property", "installationPath"]) - - def test_preflight_python_version_check(self): - with tempfile.TemporaryDirectory() as tmp_work: - with mock.patch("sys.version_info", (3, 11, 9)), \ - mock.patch("shutil.which", return_value="/usr/bin/tool"), \ - mock.patch("make_game.tool_available", return_value=True), \ - mock.patch("make_game.ensure_submodule", return_value=None), \ - mock.patch("os.path.isfile", return_value=True), \ - mock.patch("shutil.disk_usage", return_value=Usage(1000 * 2**30, 100 * 2**30, 900 * 2**30)): - self.assert_fails(make_game.preflight, ["shaders"], tmp_work, wav=False, - match="Python 3.12 or newer:") - - def test_preflight_wav_without_assets_does_not_require_ffmpeg(self): - with tempfile.TemporaryDirectory() as tmp_work: - def mock_which(cmd): - return None if cmd == "ffmpeg" else f"/bin/{cmd}" - - with mock.patch("sys.version_info", (3, 12, 0)), \ - mock.patch("shutil.which", side_effect=mock_which), \ - mock.patch("make_game.tool_available", return_value=True), \ - mock.patch("shutil.disk_usage", return_value=Usage(1000 * 2**30, 100 * 2**30, 900 * 2**30)): - # wav=True with ["shaders"] stage only: ffmpeg not required - make_game.preflight(["shaders"], tmp_work, wav=True) - - def test_preflight_assets_without_wav_does_not_require_ffmpeg(self): - with tempfile.TemporaryDirectory() as tmp_work: - def mock_which(cmd): - return None if cmd == "ffmpeg" else f"/bin/{cmd}" - - with mock.patch("sys.version_info", (3, 12, 0)), \ - mock.patch("shutil.which", side_effect=mock_which), \ - mock.patch("make_game.ensure_submodule", return_value=None), \ - mock.patch("shutil.disk_usage", return_value=Usage(1000 * 2**30, 100 * 2**30, 900 * 2**30)): - # wav=False with ["assets"] stage: ffmpeg not required - make_game.preflight(["assets"], tmp_work, wav=False) - - def test_preflight_disk_space_insufficient(self): - with tempfile.TemporaryDirectory() as tmp_work: - with mock.patch("sys.version_info", (3, 12, 0)), \ - mock.patch("shutil.which", return_value="/usr/bin/tool"), \ - mock.patch("make_game.tool_available", return_value=True), \ - mock.patch("make_game.ensure_submodule", return_value=None), \ - mock.patch("os.path.isfile", return_value=True), \ - mock.patch("shutil.disk_usage", return_value=Usage(500 * 2**30, 485 * 2**30, 15 * 2**30)): - # Shaders needs 30 GB, only 15 GB free - self.assert_fails(make_game.preflight, ["shaders"], tmp_work, wav=False, - match="15 GB free on the drive of") - - def test_preflight_charges_space_only_when_shaders_need_to_be_rebuilt(self): - cases = ( - ("current translation", {}, {}, False, True), - ("matching emulation", {"spirv/wave64_emulate.txt": "on"}, {"emulate": True}, False, True), - ("auto keeps emulation", {"spirv/wave64_emulate.txt": "on"}, {"keep_emulated": True}, False, True), - ("missing disassembly marker", {"dxbc/disasm.done": None}, {}, False, False), - ("old disassembly marker", {"dxbc/disasm.done": "shader_disasm.py finished"}, {}, False, False), - ("changed LLVM", {"dxbc/disasm.done": "old llvm-mc"}, {}, False, False), - ("stale translator", {"spirv/translation_sources.sha256": "stale"}, {}, False, False), - ("old translation without fingerprint", {"spirv/translation_sources.sha256": None}, {}, False, False), - ("needs emulation", {}, {"emulate": True}, False, False), - ("explicit native mode", {"spirv/wave64_emulate.txt": "on"}, {}, False, False), - ("interrupted unpack", {"dxbc/fssm_index.json": None}, {}, False, False), - ("interrupted translation", {"spirv/index.json": None}, {}, False, False), - ("old disassembly layout", {}, {}, True, False), - ) - fingerprint = make_game.translation_sources_digest() - usage = Usage(500 * 2**30, 485 * 2**30, 15 * 2**30) - for name, changed, settings, legacy_layout, reusable in cases: - with self.subTest(name=name), tempfile.TemporaryDirectory() as work: - files = { - "dxbc/index.json": '[{"file": "shader.dxbc"}]', - "dxbc/fssm_index.json": '[{"name": "shader"}]', - "dxbc/disasm.done": "test llvm-mc 21", - "spirv/index.json": "{}", - "spirv/translation_sources.sha256": fingerprint, - "spirv/wave64_emulate.txt": "off", - **changed, - } - shader_root = os.path.join(work, "shaders") - for name, content in files.items(): - if content is not None: - path = os.path.join(shader_root, name) - os.makedirs(os.path.dirname(path), exist_ok=True) - with open(path, "w", encoding="utf-8") as handle: - handle.write(content + "\n") - disasm_parts = ("disasm",) if legacy_layout else ("dxbc", "disasm") - disasm = os.path.join(shader_root, *disasm_parts) - os.makedirs(disasm) - with open(os.path.join(disasm, "shader.s"), "w", encoding="utf-8", newline="\n") as f: - f.write("synthetic listing\n") - with mock.patch("sys.version_info", (3, 12, 0)), \ - mock.patch("make_game.llvm_mc_signature", return_value="test llvm-mc 21"), \ - mock.patch("make_game.tool_available", return_value=True), \ - mock.patch("shutil.which", return_value="/usr/bin/tool"), \ - mock.patch("shutil.disk_usage", return_value=usage), \ - mock.patch("sys.stdout", io.StringIO()): - if reusable: - make_game.preflight(["shaders"], work, **settings) - else: - self.assert_fails(make_game.preflight, ["shaders"], work, - match="about 30 GB is needed", **settings) - - - def test_preflight_disk_space_stage_accumulation(self): - with tempfile.TemporaryDirectory() as tmp_work: - with mock.patch("sys.version_info", (3, 12, 0)), \ - mock.patch("shutil.which", return_value="/usr/bin/tool"), \ - mock.patch("make_game.tool_available", return_value=True), \ - mock.patch("make_game.ensure_submodule", return_value=None) as ensure_submodule, \ - mock.patch("shutil.disk_usage", return_value=Usage(500 * 2**30, 250 * 2**30, 250 * 2**30)): - # shaders (30) + assets (370) = 400 GB needed, only 250 GB free - err = self.assert_fails(make_game.preflight, ["shaders", "assets"], tmp_work, wav=False, - match="about 400 GB is needed") - self.assertIn("250 GB free", err) - ensure_submodule.assert_not_called() - - def test_preflight_suggests_loader_only_when_dropping_assets_makes_it_fit(self): - gib = 1 << 30 - loader_build = ["check", "shaders", "runtime"] - full_build = [*loader_build, "assets"] - cases = ( - ("reusable shader outputs", full_build, 10 * gib, True, False, True), - ("asset export only", ["assets"], 250 * gib, False, False, False), - ("shader and asset exports only", ["shaders", "assets"], 250 * gib, False, False, False), - ("WAV export requested", full_build, 250 * gib, False, True, False), - ) - with mock.patch.multiple( - make_game, - mc_command=mock.Mock(return_value=["llvm-mc"]), - dotnet_sdk_ok=mock.Mock(return_value=True), - ensure_submodule=mock.Mock(), - visual_cpp_tools_ok=mock.Mock(return_value=True), - cross_build_missing=mock.Mock(return_value=[]), - assets_exported=mock.Mock(return_value=False), - ), mock.patch("shutil.which", return_value="/usr/bin/tool"): - for name, stages, free, reusable, wav, expect_hint in cases: - usage = Usage(500 * gib, 500 * gib - free, free) - with self.subTest(name=name), tempfile.TemporaryDirectory() as work, \ - mock.patch("shutil.disk_usage", return_value=usage), \ - mock.patch.object(make_game, "shader_outputs_reusable", return_value=reusable): - err = self.assert_fails(make_game.preflight, stages, work, wav=wav, - match="is needed") - self.assertEqual("--stages check,shaders,runtime" in err, expect_hint) - - def test_low_disk_cli_suggests_a_working_stage_selection(self): - gib = 1 << 30 - with tempfile.TemporaryDirectory() as tmp, mock.patch.multiple( - make_game, - below_normal=mock.DEFAULT, - check=mock.Mock(return_value={"expected_exe": "synthetic.exe"}), - mc_command=mock.Mock(return_value=["llvm-mc"]), - dotnet_sdk_ok=mock.Mock(return_value=True), - ensure_submodule=mock.DEFAULT, - visual_cpp_tools_ok=mock.Mock(return_value=True), - cross_build_missing=mock.Mock(return_value=[]), - cross_configure=mock.DEFAULT, - pipeline_check_exe=mock.Mock(return_value="vk_pipeline_check"), - assets_exported=mock.Mock(return_value=False), - shader_outputs_reusable=mock.Mock(return_value=False), - wave64_settings=mock.Mock(return_value=(False, False)), - runtime_gpu_per_vertex=mock.Mock(return_value=True), - verify_runtime_build=mock.DEFAULT, - log=mock.DEFAULT, - shaders=mock.DEFAULT, - assets=mock.DEFAULT, - runtime=mock.DEFAULT, - pipelines=mock.DEFAULT, - ) as stages, mock.patch("shutil.which", return_value="available-tool"), \ - mock.patch("shutil.disk_usage") as disk: - argv = ["make_game.py", "--game", os.path.join(tmp, "input"), "--out", os.path.join(tmp, "out")] - with mock.patch.object(sys, "argv", argv): - disk.return_value = Usage(500 * gib, 470 * gib + 1, 30 * gib - 1) - error = self.assert_fails(make_game.main, match="about 400 GB is needed") - self.assertNotIn("--stages", error) - - disk.return_value = Usage(500 * gib, 470 * gib, 30 * gib) - error = self.assert_fails(make_game.main, match="about 400 GB is needed") - suggestion = re.search(r"--stages ([a-z,]+)", error) - self.assertIsNotNone(suggestion, error) - for stage in ("shaders", "assets", "runtime", "pipelines"): - stages[stage].assert_not_called() - - with mock.patch.object(sys, "argv", [*argv, "--stages", suggestion.group(1)]): - self.assertEqual(make_game.main(), 0) - stages["shaders"].assert_called_once() - stages["runtime"].assert_called_once() - stages["assets"].assert_not_called() - stages["pipelines"].assert_not_called() - - def test_preflight_counts_assets_again_with_wav_even_when_exported(self): - # --wav decodes again over the exported audio (assets_exported says it is finished), so the 370 GB stays. - with tempfile.TemporaryDirectory() as tmp_work: - with mock.patch("sys.version_info", (3, 12, 0)), \ - mock.patch("make_game.assets_exported", return_value=True), \ - mock.patch("make_game.tool_available", return_value=True), \ - mock.patch("make_game.ensure_submodule", return_value=None), \ - mock.patch("shutil.which", return_value="/usr/bin/tool"), \ - mock.patch("os.path.isfile", return_value=True), \ - mock.patch("shutil.disk_usage", return_value=Usage(500 * 2**30, 250 * 2**30, 250 * 2**30)): - # Without --wav the exported assets are credited, so 250 GB free is enough for the asset tools. - make_game.preflight(["assets"], tmp_work, wav=False) - err = self.assert_fails(make_game.preflight, ["assets"], tmp_work, wav=True, - match="about 370 GB is needed") - # c506d00c: the loader-only hint is offered only when shaders and runtime are selected and not --wav - self.assertNotIn("without exporting assets", err) - - def test_ensure_submodule_present_is_noop(self): - with tempfile.TemporaryDirectory() as tmp: - core_dir = os.path.join(tmp, "third_party", "rpf9-explorer", "Core") - os.makedirs(core_dir) - with open(os.path.join(core_dir, "Core.cs"), "w") as f: - f.write("// dummy") - - with mock.patch.object(make_game, "ROOT", tmp): - make_game.ensure_submodule() - - def test_ensure_submodule_missing_fails_cleanly(self): - with tempfile.TemporaryDirectory() as tmp: - with mock.patch.object(make_game, "ROOT", tmp), \ - mock.patch("shutil.which", return_value=None): - self.assert_fails(make_game.ensure_submodule, - match="git clone --recursive https://github.com/ProjectLeonidaL/leonida") - - def test_ensure_submodule_zip_with_git_does_not_say_install_git(self): - with tempfile.TemporaryDirectory() as tmp: - not_a_repo = subprocess.CompletedProcess([], 128) - with mock.patch.object(make_game, "ROOT", tmp), \ - mock.patch("shutil.which", return_value="/usr/bin/git"), \ - mock.patch("subprocess.run", return_value=not_a_repo): - err = self.assert_fails(make_game.ensure_submodule, - match="git clone --recursive https://github.com/ProjectLeonidaL/leonida") - self.assertNotIn("Install Git", err) - - def test_ensure_submodule_names_the_clone_command_the_readme_gives(self): - # the hint once named a repository that had gone private; the README is where the address is kept current - with open(os.path.join(ROOT, "README.md"), encoding="utf-8") as f: - readme = f.read() - with tempfile.TemporaryDirectory() as tmp: - with mock.patch.object(make_game, "ROOT", tmp), \ - mock.patch("shutil.which", return_value=None): - err = self.assert_fails(make_game.ensure_submodule, match="git clone --recursive ") - clone = re.search(r"git clone --recursive https://github\.com/[\w.-]+/[\w.-]+", err) - self.assertIsNotNone(clone, err) - self.assertIn(f"`{clone.group(0)}`", readme) - - def test_ensure_submodule_failed_fetch_in_clone_names_the_fetch(self): - with tempfile.TemporaryDirectory() as tmp: - results = [subprocess.CompletedProcess([], 0), subprocess.CompletedProcess([], 1)] - with mock.patch.object(make_game, "ROOT", tmp), \ - mock.patch("shutil.which", return_value="/usr/bin/git"), \ - mock.patch("subprocess.run", side_effect=results), \ - mock.patch.object(make_game, "log"): - err = self.assert_fails(make_game.ensure_submodule, - match="fetching third_party/rpf9-explorer failed") - self.assertIn("git submodule update --init --recursive", err) - self.assertNotIn("Download ZIP", err) - - -class GameDiscoveryTest(unittest.TestCase): - def setUp(self): - self.home = self.enterContext(tempfile.TemporaryDirectory()) - self.desktop = os.path.join(self.home, "Desktop") - self.downloads = os.path.join(self.home, "Downloads") - self.version = {"title": "Synthetic", "version": "1.0", "files": { - "MicrosoftGame.Config": {"size": 3}, - "Catalog000.bin": {"size": 4}, - "appdata0.rpf": {"size": 5}, - }} - - def write_probes(self, folder): - os.makedirs(folder) - for name, info in self.version["files"].items(): - with open(os.path.join(folder, name), "wb") as file: - file.truncate(info["size"]) - - def discover(self, known=()): - """find_dumps() over the synthetic home folder only; `known` is what the shell reports for Downloads, - Desktop and Documents.""" - roots = (self.home, self.desktop, self.downloads, *known) - isdir = os.path.isdir - with mock.patch("os.path.expanduser", return_value=self.home), \ - mock.patch("os.path.isdir", side_effect=lambda path: path in roots and isdir(path)), \ - mock.patch.object(make_game, "known_folders", return_value=list(known)), \ - mock.patch.object(make_game, "versions", return_value=[self.version]): - return make_game.find_dumps() - - def test_find_searches_known_folders_moved_into_onedrive(self): - # OneDrive's Known Folder Move: Explorer's Desktop and Documents are ~\OneDrive\Desktop and - # ~\OneDrive\Documents, two levels below the home folder, so the home root alone never reaches inside them. - desktop = os.path.join(self.home, "OneDrive", "Desktop") - documents = os.path.join(self.home, "OneDrive", "Documents") - on_desktop = os.path.join(desktop, "GTA VI") - in_documents = os.path.join(documents, "Games", "GTA VI") - self.write_probes(on_desktop) - self.write_probes(in_documents) - - self.assertEqual(self.discover(), []) - self.assertEqual(self.discover(known=(desktop, documents)), - [(on_desktop, self.version), (in_documents, self.version)]) - - def test_find_reports_a_copy_once_when_known_folders_are_not_moved(self): - package = os.path.join(self.desktop, "Package") - self.write_probes(package) - self.assertEqual(self.discover(known=(self.downloads, self.desktop)), [(package, self.version)]) - - def test_known_folders_from_the_shell(self): - folders = make_game.known_folders() - if os.name != "nt": - self.assertEqual(folders, []) - return - self.assertEqual(len(folders), len(make_game.KNOWN_FOLDERS)) - for folder in folders: - self.assertTrue(os.path.isabs(folder), folder) - self.assertEqual(make_game.known_folders(), folders) # the shell's buffers are freed, calls repeat cleanly - - def test_find_searches_below_rejected_folder_with_config(self): - outer = os.path.join(self.desktop, "Backup") - package = os.path.join(outer, "Package") - self.write_probes(package) - with open(os.path.join(outer, "MicrosoftGame.Config"), "wb") as config: - config.write(b"abc") - self.write_probes(os.path.join(outer, "Other", "TooDeep")) - - self.assertEqual(self.discover(), [(package, self.version)]) - - def test_find_revisits_aliased_root_with_more_depth(self): - target = os.path.join(self.downloads, "Outer", "Inner") - package = os.path.join(self.desktop, "Package") - self.write_probes(os.path.join(target, "Package")) - self.write_probes(package) - realpath = os.path.realpath - - def resolve(path): - if path == self.desktop or path.startswith(self.desktop + os.sep): - path = os.path.join(target, os.path.relpath(path, self.desktop)) - return realpath(path) - - with mock.patch("os.path.realpath", side_effect=resolve): - self.assertEqual(self.discover(), [(package, self.version)]) - - - def test_discovery_roots_follow_the_platform(self): - # Elsewhere than Windows a copy on another disk or on a share shows up under a mount point, so those are - # searched too: /Volumes is where macOS mounts drives and mount_smbfs shares, /run/media is Fedora's. - with mock.patch.object(make_game.os, "name", "posix"), \ - mock.patch.object(make_game, "known_folders", return_value=[]): - roots = make_game.discovery_roots(self.home) - self.assertIn(os.path.join(self.home, "Downloads"), roots) - for root in ("/mnt", "/media", "/run/media", "/Volumes"): - self.assertIn(root, roots) - self.assertEqual([r for r in roots if r.endswith(":\\")], []) - - def test_volume_roots_add_the_users_mount_folders(self): - # udisks2 mounts a drive at /media// --out / -> exit 2, catalogue untouched - r1 = subprocess.run(py + ["census", cat_dir, "--out", cat_file], capture_output=True, text=True) - self.assertEqual(r1.returncode, 2) - self.assertIn("inside input folder", r1.stderr) - with open(cat_file, "rb") as fh: - self.assertEqual(fh.read(), raw_0drp) - - # resolve --out / -> exit 2, catalogue untouched - r2 = subprocess.run(py + ["resolve", cat_dir, "--out", cat_file], capture_output=True, text=True) - self.assertEqual(r2.returncode, 2) - self.assertIn("inside input folder", r2.stderr) - with open(cat_file, "rb") as fh: - self.assertEqual(fh.read(), raw_0drp) - - # census --out /sub/report.json (existing and non-existing nested dir) -> exit 2 - nested_out = os.path.join(sub_dir, "report.json") - r3 = subprocess.run(py + ["census", cat_dir, "--out", nested_out], capture_output=True, text=True) - self.assertEqual(r3.returncode, 2) - self.assertIn("inside input folder", r3.stderr) - self.assertFalse(os.path.exists(nested_out)) - - missing_nested = os.path.join(cat_dir, "missing_sub", "report.json") - r3b = subprocess.run(py + ["census", cat_dir, "--out", missing_nested], capture_output=True, text=True) - self.assertEqual(r3b.returncode, 2) - self.assertIn("inside input folder", r3b.stderr) - - # Relative path with '..' and trailing slash still resolves inside -> exit 2 - trav_out = os.path.join(sibling_dir, "..", "cats", "sub", "report.json") - r3c = subprocess.run( - py + ["resolve", cat_dir + os.sep, "--out", trav_out], - capture_output=True, - text=True, - ) - self.assertEqual(r3c.returncode, 2) - self.assertIn("inside input folder", r3c.stderr) - self.assertFalse(os.path.exists(nested_out)) - - # Windows case and separator differences still match -> exit 2 - if os.name == "nt": - mixed_out = os.path.join(cat_dir, "SUB", "report.json").replace("\\", "/") - r3d = subprocess.run(py + ["census", cat_dir, "--out", mixed_out], capture_output=True, text=True) - self.assertEqual(r3d.returncode, 2) - self.assertIn("inside input folder", r3d.stderr) - self.assertFalse(os.path.exists(nested_out)) - # Different drive letters must not raise ValueError - self.assertFalse(pc._is_under_dir(r"Z:\elsewhere\report.json", r"C:\cats")) - - # Symlink outside pointing at a file inside -> exit 2, target untouched - link_out = os.path.join(sibling_dir, "link.0drp") - try: - os.symlink(cat_file, link_out) - except (OSError, NotImplementedError): - link_out = None - if link_out is not None: - r_sym = subprocess.run(py + ["census", cat_dir, "--out", link_out], capture_output=True, text=True) - self.assertEqual(r_sym.returncode, 2) - self.assertIn("inside input folder", r_sym.stderr) - with open(cat_file, "rb") as fh: - self.assertEqual(fh.read(), raw_0drp) - - # inspect --out -> exit 2, file untouched - r4 = subprocess.run(py + ["inspect", cat_file, "--out", cat_file], capture_output=True, text=True) - self.assertEqual(r4.returncode, 2) - self.assertIn("overwrite", r4.stderr) - with open(cat_file, "rb") as fh: - self.assertEqual(fh.read(), raw_0drp) - - # resolve --names-file --out -> exit 2, names untouched - names_file = os.path.join(sibling_dir, "names.txt") - with open(names_file, "w", encoding="utf-8") as fh: - fh.write("synth_body_full_03\n") - r5 = subprocess.run( - py + ["resolve", cat_dir, "--names-file", names_file, "--out", names_file], - capture_output=True, - text=True, - ) - self.assertEqual(r5.returncode, 2) - self.assertIn("overwrite", r5.stderr) - with open(names_file, encoding="utf-8") as fh: - self.assertEqual(fh.read(), "synth_body_full_03\n") - - # census --out /report.json (shares string prefix "_out") -> exit 0 - sibling_out = os.path.join(sibling_dir, "report.json") - r6 = subprocess.run(py + ["census", cat_dir, "--out", sibling_out], capture_output=True, text=True) - self.assertEqual(r6.returncode, 0, r6.stderr) - with open(sibling_out, encoding="utf-8") as fh: - rep = json.load(fh) - self.assertEqual(rep["catalogues"], 1) - self.assertEqual(rep["presets"], 5) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/test_ped_extra_uvs.py b/tests/test_ped_extra_uvs.py deleted file mode 100644 index 52e210a40..000000000 --- a/tests/test_ped_extra_uvs.py +++ /dev/null @@ -1,312 +0,0 @@ -"""Preserve authored UV sets through the actual skinned producer and ped CLIs. - -All geometry and skin streams are synthetic. glTF defines TEXCOORD_n as VEC2 -float or normalized unsigned byte/short attributes with consecutive set indices: -https://github.com/KhronosGroup/glTF/blob/5b00b913b74c8f0260c64578b98a09ef2dde0b41/specification/2.0/Specification.adoc#meshes-attributes - - python -I tests/test_ped_extra_uvs.py -""" -import hashlib -import json -from pathlib import Path -import struct -import subprocess -import sys -import tempfile -import unittest -from unittest import mock - -ROOT = Path(__file__).resolve().parents[1] -sys.path.insert(0, str(ROOT / "tools")) -sys.path.insert(0, str(ROOT / "tests")) - -import glb_writer -import ped_assemble as pa -import skinned_glb -import test_skinned_glb as skin_fixture - - -POSITIONS = [(0, 0, 0), (1, 0, 0), (0, 1, 0), - (2, 0, 0), (3, 0, 0), (2, 1, 0)] -UV0 = [(0, 0), (1, 0), (0, 1), (0.25, 0), (0.75, 0), (0.25, 1)] -EXTRA = { - 1: [(i / 8, 0.5 + i / 16) for i in range(6)], - 2: [((10 + 30 * i) / 255, (240 - 20 * i) / 255) for i in range(6)], - 3: [((1000 + 4000 * i) / 65535, (62000 - 5000 * i) / 65535) for i in range(6)], -} - - -def write_json(path, value): - path.write_text(json.dumps(value) + "\n", encoding="utf-8", newline="\n") - - -def encode_glb(doc, blob): - raw = json.dumps(doc, separators=(",", ":")).encode("utf-8") - raw += b" " * (-len(raw) % 4) - blob = bytes(blob) + b"\0" * (-len(blob) % 4) - return (struct.pack("<4sII", b"glTF", 2, 28 + len(raw) + len(blob)) - + struct.pack(" 1 tris", result.stdout) - part = json.loads(culled.read_text(encoding="utf-8")) - self.assertEqual(part["positions"], [list(row) for row in POSITIONS[3:]]) - self.assertEqual(part["triangles"], [[0, 1, 2]]) - self.assertEqual(part.get("uvs_extra"), - {str(key): [list(row) for row in rows[3:]] for key, rows in EXTRA.items()}) - # Supply the source skin's joint order so the normal ped skin-remapping - # path is exercised as well. This assertion concerns vertex data only. - joint_names = [producer_doc["nodes"][index]["name"] - for index in producer_doc["skins"][0]["joints"]] - manifest = self.root / "manifest.json" - write_json(manifest, {"parts": [part], "skeleton": { - "coord_space": "y-up", "joints": [{"name": name} for name in joint_names], - }}) - assembled = self.root / "assembled.glb" - self.cli("ped_assemble.py", "assemble", "--manifest", manifest, "-o", assembled, - "--source-space", "y-up", "--no-cull", "--no-standing-offset") - out_doc, after = attributes(assembled) - self.assertEqual(len(out_doc["skins"][0]["joints"]), len(joint_names)) - for name in ("POSITION", "NORMAL", "TEXCOORD_0", "TEXCOORD_1", "TEXCOORD_2", "TEXCOORD_3", - "JOINTS_0", "JOINTS_1", "WEIGHTS_0", "WEIGHTS_1"): - self.assertEqual(after[name], f32_rows(before[name][3:]), name) - self.assertEqual(after["indices"], [(0,), (1,), (2,)]) - direct = self.root / "culled.glb" - self.cli("ped_assemble.py", "cull-overlap", *options, "-o", direct) - _, direct_data = attributes(direct) - self.assertEqual(direct_data, after) - self.assertTrue(all(hashlib.sha256(path.read_bytes()).digest() == digest - for path, digest in originals.items())) - - def test_no_extra_sets_keep_existing_json_and_attributes(self): - source = self.root / "primary.glb" - write_geometry(source, extra=False) - loaded = pa.read_glb_parts(str(source))[0] - self.assertEqual(loaded.uvs_extra, {}) - self.assertNotIn("uvs_extra", pa.part_to_dict(loaded)) - output = self.root / "primary-out.glb" - self.cli("ped_assemble.py", "assemble", source, "-o", output, - "--source-space", "y-up", "--no-cull", "--no-standing-offset") - _, before = attributes(source) - _, after = attributes(output) - self.assertEqual(before, after) - - def test_sparse_extra_sets_use_the_same_precheck_and_overrides(self): - source = self.root / "sparse.glb" - write_geometry(source) - doc, blob = skinned_glb.read_glb(str(source)) - blob = bytearray(blob) - attrs = doc["meshes"][0]["primitives"][0]["attributes"] - - def add_view(data): - blob.extend(b"\0" * (-len(blob) % 4)) - index = len(doc["bufferViews"]) - doc["bufferViews"].append({"buffer": 0, "byteOffset": len(blob), "byteLength": len(data)}) - blob.extend(data) - return index - - first = doc["accessors"][attrs["TEXCOORD_1"]] - first.pop("bufferView") - first.pop("byteOffset") - first["sparse"] = {"count": 2, - "indices": {"bufferView": add_view(bytes((1, 4))), "componentType": 5121}, - "values": {"bufferView": add_view(struct.pack("<4f", .25, .75, .125, .875))}} - doc["accessors"][attrs["TEXCOORD_2"]]["sparse"] = { - "count": 2, "indices": {"bufferView": add_view(bytes((0, 5))), "componentType": 5121}, - "values": {"bufferView": add_view(bytes((77, 33, 199, 22)))}, - } - doc["buffers"][0]["byteLength"] = len(blob) - source.write_bytes(encode_glb(doc, blob)) - original = source.read_bytes() - output = self.root / "sparse-out.glb" - self.cli("ped_assemble.py", "assemble", source, "-o", output, - "--source-space", "y-up", "--no-cull", "--no-standing-offset") - _, data = attributes(output) - expected1 = [(0, 0), (.25, .75), (0, 0), (0, 0), (.125, .875), (0, 0)] - expected2 = EXTRA[2].copy() - expected2[0], expected2[5] = (77 / 255, 33 / 255), (199 / 255, 22 / 255) - for channel, rows in ((1, expected1), (2, expected2), (3, EXTRA[3])): - self.assertIn(f"TEXCOORD_{channel}", data) - self.assertEqual(data[f"TEXCOORD_{channel}"], f32_rows(rows)) - self.assertEqual(source.read_bytes(), original) - - first["type"] = "VEC3" - malformed = self.root / "wrong-shape.glb" - malformed.write_bytes(encode_glb(doc, blob)) - rejected_output = self.root / "must-not-exist.glb" - result = subprocess.run([sys.executable, "-I", str(ROOT / "tools/ped_assemble.py"), - "assemble", str(malformed), "-o", str(rejected_output)], - capture_output=True, text=True, timeout=30) - self.assertEqual(result.returncode, 2, result.stdout + result.stderr) - self.assertIn("expected VEC2", result.stderr) - self.assertNotIn("Traceback", result.stderr) - self.assertFalse(rejected_output.exists()) - - def test_extra_implicit_rows_share_the_import_budget_across_instances(self): - source = self.root / "zero.glb" - write_geometry(source) - doc, blob = skinned_glb.read_glb(str(source)) - attrs = doc["meshes"][0]["primitives"][0]["attributes"] - for channel in (1, 2, 3): - doc["accessors"][attrs[f"TEXCOORD_{channel}"]] = { - "componentType": 5126, "count": 6, "type": "VEC2", - } - for instances in (1, 2): - with self.subTest(instances=instances): - doc["nodes"] = [{"name": f"instance_{i}", "mesh": 0} for i in range(instances)] - doc["scenes"] = [{"nodes": list(range(instances))}] - source.write_bytes(encode_glb(doc, blob)) - # A small test-only cap exercises the same per-file boundary without - # allocating a million Python rows. Every fixture is valid glTF. - rows = 18 * instances - with mock.patch.object(pa, "MAX_IMPLICIT_ACCESSOR_ROWS", rows): - parts = pa.read_glb_parts(str(source)) - self.assertEqual(len(parts), instances) - for part in parts: - self.assertEqual(part.uvs_extra, {key: [(0.0, 0.0)] * 6 for key in (1, 2, 3)}) - with mock.patch.object(pa, "MAX_IMPLICIT_ACCESSOR_ROWS", rows - 1): - with self.assertRaisesRegex(pa.PedAssembleError, "implicit accessor rows"): - pa.read_glb_parts(str(source)) - - def test_extra_indices_cannot_replace_primary_or_leave_gaps(self): - for extra in ({0: UV0}, {2: UV0}, {1.0: UV0}, {True: UV0}, {1: UV0[:-1]}): - with self.subTest(extra=list(extra)): - part = pa.MeshPart("invalid", POSITIONS, [(0, 1, 2)], coord_space="y-up", - uvs=UV0, uvs_extra=extra) - with self.assertRaises(pa.PedAssembleError): - pa.build_assembled_glb([part], apply_standing=False) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/test_ped_glb_material_defaults.py b/tests/test_ped_glb_material_defaults.py deleted file mode 100644 index 59402abd4..000000000 --- a/tests/test_ped_glb_material_defaults.py +++ /dev/null @@ -1,187 +0,0 @@ -"""GLB material defaults through the real writer, importer, and assembly CLI. - -Synthetic fixtures only. Literal expectations follow the pinned Khronos schema: -https://github.com/KhronosGroup/glTF/blob/5b00b913b74c8f0260c64578b98a09ef2dde0b41/specification/2.0/schema/material.pbrMetallicRoughness.schema.json -The same revision's Specification.adoc#default-material applies these defaults -when a primitive does not reference a material. -""" -import copy -import json -from pathlib import Path -import struct -import subprocess -import sys -import tempfile -import unittest - -ROOT = Path(__file__).resolve().parents[1] -sys.path.insert(0, str(ROOT / "tools")) -import ped_assemble as pa - -DEFAULTS = {"baseColorFactor": [1.0, 1.0, 1.0, 1.0], "metallicFactor": 1.0, "roughnessFactor": 1.0} -CLAY = {"baseColorFactor": [0.8, 0.8, 0.8, 1.0], "metallicFactor": 0.0, "roughnessFactor": 0.85} -OMISSIONS = ("baseColorFactor", "metallicFactor", "roughnessFactor", "pbrMetallicRoughness", - "empty_pbr", "empty_material", "no_reference", "no_materials") - - -def split_glb(data): - length = struct.unpack_from("I", len(payload)) + kind + payload + struct.pack(">I", zlib.crc32(kind + payload)) - return b"".join(( - b"\x89PNG\r\n\x1a\n", chunk(b"IHDR", struct.pack(">IIBBBBB", 1, 1, 8, 6, 0, 0, 0)), - chunk(b"IDAT", zlib.compress(bytes([0, r, g, b, 255]))), chunk(b"IEND", b""), - )) - - -IMAGES = (png(30, 80, 150), png(128, 128, 255), png(0, 220, 10)) - - -def part(material=None): - return pa.MeshPart( - "surface", [(0.0, 0.0, 0.0), (1.0, 0.0, 0.0), (0.0, 1.0, 0.0)], [(0, 1, 2)], - coord_space="y-up", material=material, - ) - - -def split_glb(data): - length = struct.unpack_from(" 1 tris", result.stdout) - self.cli("assemble", serialized, "-o", rebuilt, "--no-cull", "--no-standing-offset", - "--source-space", "y-up") - self.assertEqual(rebuilt.read_bytes(), direct.read_bytes()) - - doc, blob = split_glb(rebuilt.read_bytes()) - self.assertEqual(len(doc["images"]), 1 if shared else 3) - embedded = [] - for image in doc["images"]: - view = doc["bufferViews"][image["bufferView"]] - start = view.get("byteOffset", 0) - embedded.append(blob[start:start + view["byteLength"]]) - self.assertEqual(set(embedded), set(payloads)) - primitive = doc["meshes"][0]["primitives"][0] - self.assertEqual(doc["accessors"][primitive["indices"]]["count"], 3) - self.assertEqual(doc["accessors"][primitive["attributes"]["POSITION"]]["count"], 3) - restored, _ = pa.load_parts_from_path(str(serialized)) - self.assertEqual(restored[0].positions, [(2.0, 0.0, 0.0), (3.0, 0.0, 0.0), (2.0, 1.0, 0.0)]) - self.assertEqual(restored[0].uvs, [(0.25, 0.25), (0.5, 0.25), (0.25, 0.5)]) - self.assertEqual({path: path.read_bytes() for path in originals}, originals) - - def test_no_texture_serialization_is_unchanged(self): - source = part() - expected = {"name": "surface", "role": "other", "coord_space": "y-up", "translation": [0.0, 0.0, 0.0], - "positions": [[0.0, 0.0, 0.0], [1.0, 0.0, 0.0], [0.0, 1.0, 0.0]], "triangles": [[0, 1, 2]]} - self.assertEqual(pa.part_to_dict(source), expected) - source.material = pa.MaterialSpec() - expected["material"] = {"name": "default", "base_color_factor": [0.8, 0.8, 0.8, 1.0], - "metallic_factor": 0.0, "roughness_factor": 0.85, - "alpha_mode": "OPAQUE", "double_sided": False} - self.assertEqual(pa.part_to_dict(source), expected) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/test_ped_snorm.py b/tests/test_ped_snorm.py deleted file mode 100644 index 8c7566c7b..000000000 --- a/tests/test_ped_snorm.py +++ /dev/null @@ -1,170 +0,0 @@ -"""Signed-normalized glTF endpoints through the real ped importer and CLI. - -The glTF accessor-data-types contract maps -128/-127 and -32768/-32767 to -1. -KHR_mesh_quantization permits these POSITION/TEXCOORD component types: -https://github.com/KhronosGroup/glTF/blob/5b00b913b74c8f0260c64578b98a09ef2dde0b41/extensions/2.0/Khronos/KHR_mesh_quantization/README.md -""" -from __future__ import annotations - -import json -from pathlib import Path -import struct -import subprocess -import sys -import tempfile -import unittest - -ROOT = Path(__file__).resolve().parents[1] -sys.path.insert(0, str(ROOT / "tools")) -import glb_skinning -import ped_assemble as pa - - -def make_glb(component_type, values, one, *, normalized, interleaved=False, sparse=None): - """Repack a real writer triangle; every vertex row/offset is four-byte aligned.""" - part = pa.MeshPart(name="quantized", coord_space="y-up", - positions=[(0.0, 0.0, 0.0), (0.0, 1.0, 0.0), (1.0, 0.0, 0.0)], - triangles=[(0, 1, 2)], uvs=[(0.0, 0.0), (0.0, 1.0), (1.0, 0.0)]) - original, _ = pa.build_assembled_glb([part], apply_standing=False) - doc, binary, _ = glb_skinning.parse_glb(original) - data = bytearray(binary) - fmt = {5120: "b", 5121: "B", 5122: "h", 5123: "H", 5126: "f"}[component_type] - - def view(raw, **fields): - data.extend(bytes(-len(data) % 4)) - index = len(doc["bufferViews"]) - doc["bufferViews"].append(dict(buffer=0, byteOffset=len(data), byteLength=len(raw), **fields)) - data.extend(raw) - return index - - attrs = doc["meshes"][0]["primitives"][0]["attributes"] - for name, width in (("POSITION", 3), ("TEXCOORD_0", 2)): - accessor = doc["accessors"][attrs[name]] - rows = [(v, one if i == 1 else 0, *([0] if width == 3 else [])) for i, v in enumerate(values)] - if sparse is not None: - rows = [(0, 0, *([0] if width == 3 else [])), - (0, one, *([0] if width == 3 else [])), - (one, 0, *([0] if width == 3 else []))] - size = struct.calcsize("<" + fmt * width) - stride = (size + 3) // 4 * 4 + (4 if interleaved else 0) - offset = 4 if interleaved else 0 - raw = bytearray(b"PAD!" if offset else b"") - for row in rows: - raw.extend(struct.pack("<" + fmt * width, *row)) - raw.extend(bytes(stride - size)) - accessor.update(bufferView=view(bytes(raw), byteStride=stride, target=34962), byteOffset=offset, - componentType=component_type, normalized=normalized) - if sparse is not None: - if sparse == "implicit": - del accessor["bufferView"] - del accessor["byteOffset"] - rows = [(0,) * width] * 3 - replacement = (values[0],) + (0,) * (width - 1) - accessor["sparse"] = dict(count=1, indices=dict(bufferView=view(b"\0"), componentType=5121), - values=dict(bufferView=view(struct.pack("<" + fmt * width, *replacement)))) - rows[0] = replacement - if name == "POSITION": - accessor["min"] = [min(row[c] for row in rows) for c in range(3)] - accessor["max"] = [max(row[c] for row in rows) for c in range(3)] - doc["buffers"][0]["byteLength"] = len(data) - doc["extensionsUsed"] = ["KHR_mesh_quantization"] - doc["extensionsRequired"] = ["KHR_mesh_quantization"] - encoded = json.dumps(doc, separators=(",", ":")).encode() - encoded += b" " * (-len(encoded) % 4) - data.extend(bytes(-len(data) % 4)) - return (struct.pack("<4sII", b"glTF", 2, 28 + len(encoded) + len(data)) - + struct.pack(" seed value (others are 0).""" - return d.reference(prefix(v, s) + list(body) + d.observe(list(regs))) - - -class Reference(unittest.TestCase): - def test_packed_halves_follow_op_sel_and_op_sel_hi(self): - v = {2: 0x00050003, 3: 0x00070002} - self.assertEqual(run("v_pk_add_u16 v1, v2, v3", v=v)[0], 0x000C0005) - # low result from (hi v2, lo v3) = 5 + 2, high result from (lo v2, lo v3) = 3 + 2 - self.assertEqual(run("v_pk_add_u16 v1, v2, v3 op_sel:[1,0] op_sel_hi:[0,0]", v=v)[0], 0x00050007) - self.assertEqual(run("v_pk_mul_lo_u16 v1, v2, v3", v={2: 0x01000100, 3: 0x01000101})[0], 0x00000100) - self.assertEqual(run("v_pk_max_i16 v1, v2, v3", v={2: 0x7FFF8000, 3: 0x80000001})[0], 0x7FFF0001) - self.assertEqual(run("v_pk_min_u16 v1, v2, v3", v={2: 0x7FFF8000, 3: 0x80000001})[0], 0x7FFF0001) - - def test_clamp_saturates_and_its_absence_wraps(self): - v = {2: 0x7FFFFFFF, 3: 0x00010001} - self.assertEqual(run("v_pk_add_i16 v1, v2, v3", v=v)[0], 0x80000000) - self.assertEqual(run("v_pk_add_i16 v1, v2, v3 clamp", v=v)[0], 0x7FFF0000) # 0x7fff+1 sat; -1+1 = 0 - self.assertEqual(run("v_pk_add_u16 v1, v2, v3 clamp", v=v)[0], 0x8000FFFF) # 0xffff+1 sat - self.assertEqual(run("v_pk_sub_u16 v1, v3, v2 clamp", v=v)[0], 0) - self.assertEqual(run("v_pk_mad_i16 v1, v2, v3, v3 clamp", v={2: 0x80008000, 3: 0xFFFFFFFF})[0], 0x7FFF7FFF) - self.assertEqual(run("v_mad_u16 v1, v2, v2, 1 clamp", v={2: 0x100})[0], 0xFFFF) - self.assertEqual(run("v_sub_nc_i16 v1, v2, v3 clamp", v={2: 0x8000, 3: 1})[0], 0x8000) - - def test_packed_shifts_use_the_low_four_bits(self): - self.assertEqual(run("v_pk_lshlrev_b16 v1, v2, v3", v={2: 0x00110001, 3: 0x00030003})[0], 0x00060006) - self.assertEqual(run("v_pk_ashrrev_i16 v1, v2, v3", v={2: 0x000F0004, 3: 0x8000F000})[0], 0xFFFFFF00) - - def test_16bit_ops_keep_the_other_half(self): - v = {1: 0xAAAABBBB, 2: 0x00050003, 3: 0x00070002} - self.assertEqual(run("v_add_nc_u16 v1, v2, v3", v=v)[0], 0xAAAA0005) - # op_sel:[1,1,1]: high halves in, result to the high half, low half kept - self.assertEqual(run("v_add_nc_u16 v1, v2, v3 op_sel:[1,1,1]", v=v)[0], 0x000CBBBB) - self.assertEqual(run("v_max_u16_e64 v1, v2, v3 op_sel:[0,1,0]", v=v)[0], 0xAAAA0007) - self.assertEqual(run("v_med3_i16 v1, v2, -1, v3 op_sel:[0,0,0,1]", v=v)[0], 0x0002BBBB) - self.assertEqual(run("v_lshrrev_b16_e64 v1, 17, v2", v=v)[0], 0xAAAA0001) - - def test_constants_are_their_32_bit_value(self): - # measured on gfx1036: an inline constant is split like a register; a float constant is its f32 bits; a - # 16-bit op's literal has 16 bits - self.assertEqual(run("v_add_nc_u16 v1, 1.0, 0 op_sel:[1,0,0]")[0], 0x3F80) - self.assertEqual(run("v_add_nc_u16 v1, 1.0, 0")[0], 0) - self.assertEqual(run("v_add_nc_u16 v1, -16, 0 op_sel:[1,0,0]")[0], 0xFFFF) - self.assertEqual(run("v_max_u16_e64 v1, 0.15915494, 0")[0], 0xF983) - self.assertEqual(run("v_add_nc_u16 v1, 0xffff, 0 op_sel:[1,0,0]")[0], 0) - self.assertEqual(run("v_pk_add_u16 v1, 0x12345678, 0")[0], 0x12345678) - self.assertEqual(run("v_pk_add_u16 v1, 1.0, 0")[0], 0x3F800000) - - -class Generator(unittest.TestCase): - def lines(self, known=False, literals=True, n=3000, seed=1): - real = d.KNOWN, d.LITERALS - d.KNOWN, d.LITERALS = known, literals - try: - gen = d.Gen(d.random.Random(seed)) - return [line for _ in range(n) for line in gen.op(d.ALL_OPS)] - finally: - d.KNOWN, d.LITERALS = real - - @staticmethod - def split(line): - op, _, rest = line.partition(" ") - args, mods = d.parse(rest) - return op, args[1:], mods - - def test_every_op_is_generated_with_its_modifiers(self): - lines = self.lines() - seen = {re.sub(r"_e64$", "", line.split()[0]) for line in lines} - self.assertEqual(set(d.ALL_OPS) - seen, set()) - for word in (" op_sel:", " op_sel_hi:", " clamp"): - self.assertTrue(any(word in line for line in lines), word) - for line in lines: - op, srcs, mods = self.split(line) - base = op[:-4] if op.endswith("_e64") else op - self.assertTrue(op.endswith("_e64") == (base in d.E64), line) - table = d.OPS_PK if base in d.OPS_PK else d.OPS_16 - n, _, cl = table[base] - self.assertEqual(len(srcs), n, line) - if "clamp" in mods: - self.assertIsNotNone(cl, line) - self.assertEqual(len(mods.get("op_sel", [0] * (n if base in d.OPS_PK else n + 1))), - n if base in d.OPS_PK else n + 1, line) - - def test_sources_respect_the_constant_bus(self): - for line in self.lines(): - _, srcs, _ = self.split(line) - lits = [x for x in srcs if x.startswith("0x")] - self.assertLessEqual(len(lits), 1, line) - self.assertLessEqual(len(set(x for x in srcs if x.startswith("s")) | set(lits)), 2, line) - if not line.startswith("v_pk_"): - self.assertTrue(all(int(x, 16) <= 0xFFFF for x in lits), line) - self.assertFalse(any("0x" in line for line in self.lines(literals=False))) - - def test_known_divergences_are_left_out_by_default(self): - def const_hi(lines): - for line in lines: - op, srcs, mods = self.split(line) - if op not in d.OPS_PK or op in d.PK_SHIFTS: - continue - n = len(srcs) - sel, hi = mods.get("op_sel", [0] * n), mods.get("op_sel_hi", [1] * n) - if any(d.is_const(x) and (sel[i] or hi[i]) for i, x in enumerate(srcs)): - return True - return False - self.assertFalse(const_hi(self.lines())) - self.assertTrue(const_hi(self.lines(known=True))) - - -class Translated(unittest.TestCase): - def test_harness_canaries(self): - with contextlib.redirect_stdout(io.StringIO()): - self.assertTrue(d.self_test()) - - def test_short_seeded_run_matches(self): - counts, failures = d.run_suite(80, 5, 5, d.ALL_OPS) - self.assertEqual(failures, [], failures[:1]) - self.assertEqual(counts["skip"], {}) - self.assertEqual(counts["pass"], 80) - - def test_hand_cases_match_the_translator(self): - seeds = {1: 0xAAAABBBB, 2: 0x7FFF8000, 3: 0x80000001, 4: 0x00050003, 5: 0x00070002} - cases = ["v_pk_add_i16 v1, v2, v3 clamp", "v_pk_sub_u16 v1, v3, v2 op_sel:[1,0] op_sel_hi:[0,1] clamp", - "v_pk_mad_i16 v1, v2, v3, s4 clamp", "v_pk_lshlrev_b16 v1, 17, v4", - "v_pk_mad_u16 v1, v4, 3, v5 op_sel_hi:[1,0,1]", "v_add_nc_u16 v1, v4, v5 op_sel:[1,1,1]", - "v_mad_i16 v1, v2, v3, -1 op_sel:[1,0,0,1] clamp", "v_med3_u16 v1, v2, 0x1234, v4 op_sel:[0,0,1,0]", - "v_max_i16_e64 v1, v2, v3 op_sel:[1,1,0]", "v_add_nc_u16 v1, 1.0, s5 op_sel:[0,0,1]", - "v_ashrrev_i16_e64 v1, -16, v2", "v_sub_nc_i16 v1, v2, v3 clamp"] - for case in cases: - with self.subTest(case=case): - self.assertIsNone(d.check(prefix(seeds, {4: 0x00030004, 5: 0xFFFF0001}) + [case] - + d.observe([1, 2, 3, 4]))) - - def test_a_wrong_translation_is_caught(self): - lines = prefix({2: 5}) + ["v_pk_add_u16 v1, v2, 1 op_sel_hi:[1,0]"] + d.observe([1, 2, 3, 4]) - self.assertIsNone(d.check(lines)) - want = d.reference(lines) - real = d.translated - try: - d.translated = lambda _lines: [want[0] ^ 0x10000] + want[1:] - self.assertIn("word 0 (v1)", d.check(lines)) - finally: - d.translated = real - - def test_shrinking_keeps_the_instruction_that_matters(self): - lines = d.generate(d.random.Random(2), 5, ["v_pk_add_u16", "v_add_nc_u16", "v_med3_i16"]) - body = lines[d.N_SEED:-d.N_OBS] - target = body[len(body) // 2] - real = d.translated - try: - d.translated = lambda l: [w ^ (1 if target in l else 0) for w in d.reference(l)] - small = d.shrink(lines) - finally: - d.translated = real - kept = [line for line in small if not line.startswith(("v_mov_b32_e32", "s_mov_b32"))] - self.assertEqual(kept, [target]) - - -class Cli(unittest.TestCase): - def main(self, *argv): - out = io.StringIO() - with contextlib.redirect_stdout(out), contextlib.redirect_stderr(io.StringIO()): - try: - rc = d.main(list(argv)) - except SystemExit as e: - rc = e.code - return rc, out.getvalue() - - def test_exit_codes(self): - rc, out = self.main("--list-ops") - self.assertEqual(rc, 0) - self.assertIn("v_pk_mad_i16", out) - self.assertEqual(self.main("--ops", "v_nope")[0], 2) - self.assertEqual(self.main("--oracle", "gpu")[0], 2) - rc, out = self.main("--programs", "5", "--seed", "1") - self.assertEqual(rc, 0, out) - real = d.translated - try: - d.translated = lambda l: [w ^ 1 for w in d.reference(l)] - rc, out = self.main("--programs", "3", "--seed", "1", "--ops", "v_pk_max_u16") - finally: - d.translated = real - self.assertEqual(rc, 1) - self.assertIn("MISMATCH", out) - - def test_a_run_where_every_program_was_skipped_is_not_a_success(self): - def refuse(lines, *args): - raise d.Skip("unsupported form") - real = d.translated - try: - d.translated = refuse - rc, out = self.main("--programs", "3", "--seed", "1", "--ops", "v_pk_max_u16") - finally: - d.translated = real - self.assertEqual(rc, 2, out) - self.assertIn("no program ran: every one was skipped", out) - - def test_hardware_oracle_without_the_tools_exits_77(self): - env = dict(os.environ, LEONIDA_AMD_CLANG=str(TOOL.parent / "no-such-clang.exe")) - r = subprocess.run([sys.executable, "-I", str(TOOL), "--oracle", "hw", "--programs", "3"], - capture_output=True, text=True, env=env) - self.assertEqual(r.returncode, 77, r.stdout + r.stderr) - self.assertIn("unavailable", r.stdout) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/test_pk_int16_clamp_probe.py b/tests/test_pk_int16_clamp_probe.py deleted file mode 100644 index b214d6cbf..000000000 --- a/tests/test_pk_int16_clamp_probe.py +++ /dev/null @@ -1,171 +0,0 @@ -"""Unit and oracle-backed tests for tools/pk_int16_clamp_probe.py. Standard library only; no game files.""" -from contextlib import redirect_stdout -import io -import json -import os -import sys -import tempfile -import unittest -import unittest.mock - -ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) -TOOLS = os.path.join(ROOT, "tools") -sys.dont_write_bytecode = True -for p in (TOOLS, os.path.join(TOOLS, "hw_oracle")): - if p not in sys.path: - sys.path.insert(0, p) - -import pk_int16_clamp_probe as probe # noqa: E402 -from hw_oracle import runner as hw_runner # noqa: E402 - - -def _mock_oracle(results, *, arch="gfx1036", device="Mock GFX10"): - oracle = unittest.mock.MagicMock() - oracle.arch = arch - oracle.device = device - oracle.run.return_value = results - return oracle - - -def _expected_results_for(ops, waves): - out = [] - for _wave in waves: - for op in ops: - for clamp in probe.CLAMP_MODES: - out.append([ - probe.expected_pk_int16(op, c.src0, c.src1, sel=c.sel, selhi=c.selhi, clamp=clamp) - for c in probe.CASES - ]) - return out - - -class PkInt16ClampProbeTests(unittest.TestCase): - def test_self_test(self): - out = io.StringIO() - with redirect_stdout(out): - rc = probe.main(["--self-test"]) - self.assertEqual(rc, 0) - self.assertIn("self-test ok", out.getvalue()) - - def test_model_distinguishes_wrap_from_saturation(self): - # Every target op must agree between plain and clamp, including wrapping mul_lo overflows. - overflow_seen = False - for op in probe.TARGET_OPS: - for c in probe.CASES: - plain = probe.expected_pk_int16(op, c.src0, c.src1, sel=c.sel, selhi=c.selhi, clamp=False) - clamped = probe.expected_pk_int16(op, c.src0, c.src1, sel=c.sel, selhi=c.selhi, clamp=True) - self.assertEqual(plain, clamped, f"{op} {c.name}") - if op == "v_pk_mul_lo_u16" and c.name == "pow2_overflow_wrap": - self.assertEqual(clamped, 0x00000000) - overflow_seen = True - self.assertTrue(overflow_seen) - - # Control op (v_pk_add_u16) must differ on overflowing cases. - ctrl_diffs = sum( - probe.expected_pk_int16("v_pk_add_u16", c.src0, c.src1, sel=c.sel, selhi=c.selhi, clamp=False) - != probe.expected_pk_int16("v_pk_add_u16", c.src0, c.src1, sel=c.sel, selhi=c.selhi, clamp=True) - for c in probe.CASES - ) - self.assertGreater(ctrl_diffs, 0) - - def test_kernel_lines_and_build_jobs(self): - kernels, meta = probe.build_jobs(["v_pk_mul_lo_u16", "v_pk_max_i16"], [32, 64]) - self.assertEqual(len(kernels), 8) - self.assertEqual(meta[0], (32, "v_pk_mul_lo_u16", False)) - self.assertEqual(meta[-1], (64, "v_pk_max_i16", True)) - lines = probe.kernel_lines("v_pk_mul_lo_u16", True) - self.assertIn("v_pk_mul_lo_u16 v2, v0, 0x02000400 clamp", lines) - self.assertIn("v_pk_mul_lo_u16 v2, -16, v1 op_sel:[1,0] op_sel_hi:[0,1] clamp", lines) - self.assertIn("v_pk_mul_lo_u16 v2, s4, v1 op_sel:[0,1] op_sel_hi:[1,0] clamp", lines) - self.assertIn("v_pk_mul_lo_u16 v2, v2, v1 clamp", lines) - self.assertIn("v_pk_mul_lo_u16 v2, v0, v2 clamp", lines) - self.assertEqual(lines[-2:], ["s_waitcnt vmcnt(0)", "s_endpgm"]) - - def test_mocked_oracle_success_and_json_lf(self): - results = _expected_results_for(probe.OPS, [32, 64]) - oracle = _mock_oracle(results) - with tempfile.TemporaryDirectory() as td: - jpath = os.path.join(td, "sub", "report.json") - out = io.StringIO() - with unittest.mock.patch.object(hw_runner, "open_oracle", return_value=oracle): - with redirect_stdout(out): - rc = probe.main(["--json", jpath]) - self.assertEqual(rc, 0) - self.assertIn("mismatches=0, wave_diffs=0, target_clamp_diffs=0", out.getvalue()) - oracle.close.assert_called_once() - with open(jpath, "rb") as f: - raw = f.read() - self.assertNotIn(b"\r\n", raw) - doc = json.loads(raw.decode("utf-8")) - self.assertEqual(doc["total_cases"], 2 * len(probe.OPS) * 2 * len(probe.CASES)) - self.assertEqual(doc["mismatches"], 0) - self.assertEqual(doc["target_clamp_diffs"], 0) - self.assertGreater(doc["control_clamp_diffs"], 0) - - def test_mocked_oracle_mismatch_control_and_harness_error(self): - # Flip one wave64 output to catch both model mismatch and wave_diffs. - results = _expected_results_for(["v_pk_mul_lo_u16"], [32, 64]) - results[-1][0] ^= 0xFFFF - oracle = _mock_oracle(results) - with unittest.mock.patch.object(hw_runner, "open_oracle", return_value=oracle): - with redirect_stdout(io.StringIO()): - rc = probe.main(["--ops", "v_pk_mul_lo_u16"]) - self.assertEqual(rc, 1) - - # Control op returning plain words for clamp should fail control check. - ctrl_results = _expected_results_for(["v_pk_add_u16"], [32]) - ctrl_results[1] = list(ctrl_results[0]) - oracle_ctrl = _mock_oracle(ctrl_results) - with unittest.mock.patch.object(hw_runner, "open_oracle", return_value=oracle_ctrl): - with redirect_stdout(io.StringIO()): - rc_ctrl = probe.main(["--ops", "v_pk_add_u16", "--waves", "32"]) - self.assertEqual(rc_ctrl, 1) - - # Harness string error returns exit 2. - oracle_err = _mock_oracle(["compile failed", [0] * len(probe.CASES)]) - with unittest.mock.patch.object(hw_runner, "open_oracle", return_value=oracle_err): - with redirect_stdout(io.StringIO()): - rc_err = probe.main(["--ops", "v_pk_mul_lo_u16", "--waves", "32"]) - self.assertEqual(rc_err, 2) - - def test_unavailable_non_gfx10_and_cli_errors(self): - with unittest.mock.patch.object(hw_runner, "open_oracle", side_effect=hw_runner.Unavailable("no gpu")): - with redirect_stdout(io.StringIO()): - self.assertEqual(probe.main([]), 77) - - non_gfx10 = _mock_oracle([], arch="gfx1100", device="RDNA3") - with unittest.mock.patch.object(hw_runner, "open_oracle", return_value=non_gfx10): - with redirect_stdout(io.StringIO()): - self.assertEqual(probe.main([]), 77) - non_gfx10.close.assert_called_once() - - with tempfile.TemporaryDirectory() as td: - with self.assertRaises(SystemExit) as cm: - with unittest.mock.patch.object(sys, "stderr", io.StringIO()): - probe.main(["--json", td]) - self.assertEqual(cm.exception.code, 2) - - with self.assertRaises(SystemExit) as cm2: - with unittest.mock.patch.object(sys, "stderr", io.StringIO()): - probe.main(["--ops", "v_not_an_op"]) - self.assertEqual(cm2.exception.code, 2) - - def test_live_hw_oracle_when_configured(self): - try: - hw_runner.find_clang() - except hw_runner.Unavailable as e: - self.skipTest(str(e)) - arch = "gfx1036" if os.environ.get("LEONIDA_AMD_CLANG") else None - out = io.StringIO() - argv = ["--waves", "32,64"] - if arch: - argv.extend(["--hw-arch", arch]) - with redirect_stdout(out): - rc = probe.main(argv) - if rc == 77: - self.skipTest(out.getvalue().strip() or "GFX10 oracle unavailable") - self.assertEqual(rc, 0, out.getvalue()) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/test_pknorm_probe.py b/tests/test_pknorm_probe.py deleted file mode 100644 index c674e071b..000000000 --- a/tests/test_pknorm_probe.py +++ /dev/null @@ -1,77 +0,0 @@ -"""tools/pknorm_probe.py: its near-tie inputs tell single from double rounding of v_cvt_pknorm_i16/u16_f32, and the -translator side gives 0 for every NaN half. Standard library only; no GPU, no LLVM, no game files. - -The near-tie words below are worked out by hand, not taken from the tool's own model. x is the f32 the word encodes; -"exact" is x * 32767 (i16) or x * 65535 (u16) without rounding; "f32" is that product rounded to f32 (ulp 2^-23 on -[1, 2), 2^-15 on [256, 512)), which is what a plain OpFMul gives before RoundEven. RDNA2 rounds once (gfx1036, -SHADER-339) and so does the translator since SHADER-363: - - 0x38400180 (i16) x ~ 4.5778e-5; exact 1.5 - 1.4e-9: once -> 1; f32 rounds it to 1.5, even -> 2 - 0x37c000c0 (u16) x ~ 2.2889e-5; exact 1.5 - 3.5e-10: once -> 1; f32 rounds it to 1.5 -> 2 - 0x3c004101 (i16) x ~ 7.8280e-3; exact 256.5 + 1.5e-5 (under half an f32 ulp, 2^-16): once -> 257; f32 256.5, even -> 256 - 0x3b008081 (u16) x ~ 1.9608e-3; exact 128.5 + 7.6e-6 (under 2^-17): once -> 129; f32 128.5, even -> 128 -""" -import os -import struct -import sys -import unittest -from fractions import Fraction - -ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) -sys.dont_write_bytecode = True -sys.path.insert(0, os.path.join(ROOT, "tools")) -sys.path.insert(0, os.path.join(ROOT, "tests", "semantic")) - -import pknorm_probe as probe # noqa: E402 - -BY_HAND = { # (op, word): (single, double) - ("v_cvt_pknorm_i16_f32", 0x38400180): (1, 2), - ("v_cvt_pknorm_u16_f32", 0x37C000C0): (1, 2), - ("v_cvt_pknorm_i16_f32", 0x3C004101): (257, 256), - ("v_cvt_pknorm_u16_f32", 0x3B008081): (129, 128), -} - - -def f32(word): - return struct.unpack(" tie, single > double) # the side of the tie picks the word - - def test_cases_cover_every_nan_and_near_tie_in_both_halves(self): - cases = probe.cases() - for op in probe.OPS: - for w in probe.NANS + probe.NEAR_TIES[op]: - with self.subTest(op=op, word=hex(w)): - self.assertTrue(any(c[0] == op and c[1] == w for c in cases)) - self.assertTrue(any(c[0] == op and c[2] == w for c in cases)) - - def test_nan_reference_is_zero(self): - for op in probe.OPS: - for w in probe.NANS: - self.assertEqual(probe.single_half(op, w), 0, (op, hex(w))) - - -class Translator(unittest.TestCase): - def test_translator_rounds_once_on_the_near_ties_and_zeroes_nan(self): - # SHADER-363: the translator rounds the exact product once, as RDNA2 does (gfx1036, SHADER-339). - cases = [(op, word, probe.NANS[0]) for op, word in BY_HAND] + [(op, probe.NANS[3], 0) for op in probe.OPS] - got = probe.run_translator(cases) - for (op, word, _), w in zip(cases[:len(BY_HAND)], got): - self.assertEqual(w, BY_HAND[(op, word)][0], (op, hex(word))) # low half: single rounding; high: NaN -> 0 - for w in got[len(BY_HAND):]: - self.assertEqual(w, 0) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/test_pool_workers.py b/tests/test_pool_workers.py deleted file mode 100644 index 965064744..000000000 --- a/tests/test_pool_workers.py +++ /dev/null @@ -1,212 +0,0 @@ -"""A process pool gets at most 61 workers on Windows, in every tool that takes --jobs for one. - - python -I tests/test_pool_workers.py - -Above 61 workers concurrent.futures.ProcessPoolExecutor raises `ValueError: max_workers must be <= 61` on Windows -and multiprocessing.Pool hangs (tools/pool_workers.py has the measurement). awc_opus.py, awc_shorts.py, -world_lights_paths.py, world_build.py, anim_clips.py and anim_glb.py (--coverage) handed --jobs to a pool as it was. - -Each tool is run through its own code three ways: with the limit patched in and the pool class replaced by one -that records its size and runs the work in this process (so the cap is checked on every platform); the two audio -tools from the command line with --jobs 62; and, on Windows, with 62 jobs and the real pool. Every input is built -here: an empty folder, a file of zeros, or the synthetic archives of tests/test_anim_clips.py and -tests/test_anim_glb.py. -""" -import argparse -import concurrent.futures -import multiprocessing -import os -import subprocess -import sys -import tempfile -import unittest -from unittest import mock - -ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) -TOOLS = os.path.join(ROOT, "tools") -sys.path.insert(0, TOOLS) -sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) - -import anim_clips # noqa: E402 -import anim_glb # noqa: E402 -import awc_opus # noqa: E402 -import awc_shorts # noqa: E402 -import pool_workers # noqa: E402 -import world_build # noqa: E402 -import world_lights_paths # noqa: E402 -from test_anim_clips import two_sequence_dictionary, write_rpf # noqa: E402 -from test_anim_glb import joaat32, part_resource, skeleton_resource, write_archive # noqa: E402 - -WINDOWS_LIMIT = 61 -SIZES = [] # the size each recording pool was created with - - -class RecordingExecutor: - """Stands in for ProcessPoolExecutor: notes its size and runs each job at once, in this process.""" - - def __init__(self, max_workers=None): - SIZES.append(max_workers) - - def __enter__(self): - return self - - def __exit__(self, *exc): - return False - - def submit(self, fn, *args, **kwargs): - future = concurrent.futures.Future() - future.set_result(fn(*args, **kwargs)) - return future - - def map(self, fn, jobs): - return [fn(job) for job in jobs] - - -class RecordingPool: - """Stands in for multiprocessing.Pool the same way.""" - - def __init__(self, processes=None): - SIZES.append(processes) - - def __enter__(self): - return self - - def __exit__(self, *exc): - return False - - def imap_unordered(self, fn, jobs, chunksize=1): - return [fn(job) for job in jobs] - - -def quiet(fn, *args, **kwargs): - with open(os.devnull, "w", encoding="utf-8") as sink, mock.patch.object(sys, "stdout", sink): - return fn(*args, **kwargs) - - -class ProcessWorkersTest(unittest.TestCase): - def test_limit_is_the_platforms(self): - self.assertEqual(pool_workers.MAX_PROCESS_WORKERS, WINDOWS_LIMIT if os.name == "nt" else None) - - def test_jobs_are_lowered_only_above_the_limit(self): - with mock.patch.object(pool_workers, "MAX_PROCESS_WORKERS", WINDOWS_LIMIT): - self.assertEqual([pool_workers.process_workers(n) for n in (1, 2, 60, 61, 62, 64, 4096)], - [1, 2, 60, 61, 61, 61, 61]) - with mock.patch.object(pool_workers, "MAX_PROCESS_WORKERS", None): - self.assertEqual([pool_workers.process_workers(n) for n in (1, 61, 62, 4096)], [1, 61, 62, 4096]) - - -class ToolPoolSizeTest(unittest.TestCase): - """Each tool, asked for more jobs than the limit, creates its pool at the limit and still does the work.""" - - def setUp(self): - self.tmp = tempfile.TemporaryDirectory() - self.addCleanup(self.tmp.cleanup) - self.root = self.tmp.name - SIZES.clear() - patcher = mock.patch.object(pool_workers, "MAX_PROCESS_WORKERS", WINDOWS_LIMIT) - patcher.start() - self.addCleanup(patcher.stop) - - def path(self, name): - return os.path.join(self.root, name) - - def test_awc_opus(self): - os.mkdir(self.path("banks")) - with mock.patch.object(awc_opus, "ProcessPoolExecutor", RecordingExecutor): - for jobs, size in ((2, 2), (61, 61), (62, 61), (200, 61)): - self.assertEqual(quiet(awc_opus.main, [self.path("banks"), self.path("ogg"), "--jobs", str(jobs)]), 0) - self.assertEqual(SIZES.pop(), size) - - def test_awc_shorts(self): - os.mkdir(self.path("banks")) - with mock.patch.object(awc_shorts, "ProcessPoolExecutor", RecordingExecutor): - for jobs, size in ((2, 2), (62, 61), (200, 61)): - args = [self.path("banks"), self.path("shorts.csv"), "--jobs", str(jobs)] - self.assertEqual(quiet(awc_shorts.main, args), 0) - self.assertEqual(SIZES.pop(), size) - - def test_world_lights_paths(self): - with open(self.path("zeros.rpf"), "wb") as f: - f.write(bytes(4096)) - one = world_lights_paths.scan(self.path("zeros.rpf"), jobs=1) - with mock.patch.object(world_lights_paths, "ProcessPoolExecutor", RecordingExecutor): - for jobs, size in ((2, 2), (62, 61), (200, 61)): - self.assertEqual(world_lights_paths.scan(self.path("zeros.rpf"), jobs=jobs), one) - self.assertEqual(SIZES.pop(), size) - - def test_world_build(self): - with mock.patch.object(concurrent.futures, "ProcessPoolExecutor", RecordingExecutor): - for workers, size in ((2, 2), (62, 61), (200, 61)): - self.assertEqual(list(world_build._run_jobs(abs, iter(range(-300, 0)), workers)), - list(range(300, 0, -1))) - self.assertEqual(SIZES.pop(), size) - - def test_anim_clips(self): - rpf = self.path("synthetic.rpf") - write_rpf(rpf, [two_sequence_dictionary("first@dict"), two_sequence_dictionary("second@dict")]) - rows, one = anim_clips.scan(rpf, jobs=1) - self.assertEqual(len(rows), 2) # two work items, so jobs > 1 does open a pool - self.assertEqual(SIZES, []) - with mock.patch.object(multiprocessing, "Pool", RecordingPool): - for jobs, size in ((2, 2), (62, 61), (200, 61)): - _, many = anim_clips.scan(rpf, jobs=jobs) - self.assertEqual(many["counts"], one["counts"]) - self.assertEqual(SIZES.pop(), size) - - - def test_anim_glb_coverage(self): - packs, anim = self.path("packs.rpf"), self.path("anim.rpf") - skin = [[(0, 200), (1, 55)], [(1, 255)], [(0, 128), (1, 127)], [(1, 255)]] - palette = [joaat32("skel_c"), joaat32("skel_a")] - skeleton = write_archive(packs, [[skeleton_resource()], list(part_resource(palette, "u8x4", skin))])[0] - write_rpf(anim, [two_sequence_dictionary("first@dict"), two_sequence_dictionary("second@dict")]) - - def coverage(jobs): - args = argparse.Namespace(archive=packs, skeleton=(skeleton, None), anim=anim, jobs=jobs) - return anim_glb.coverage(args)["counts"] - - one = coverage(1) - self.assertEqual((one["dictionaries"], one["bone_tracks_in_skeleton"]), (2, 6)) - self.assertEqual(SIZES, []) - with mock.patch.object(concurrent.futures, "ProcessPoolExecutor", RecordingExecutor): - for jobs, size in ((2, 2), (61, 61), (62, 61), (200, 61)): - self.assertEqual(coverage(jobs), one) - self.assertEqual(SIZES.pop(), size) - - -class CommandLineTest(unittest.TestCase): - """The audio tools default --jobs to half the CPU count and make_game.py hands its own to awc_opus.py.""" - - def run_tool(self, tool, *args): - return subprocess.run([sys.executable, "-I", os.path.join(TOOLS, tool), *args], capture_output=True, - text=True, encoding="utf-8", errors="replace") - - def test_62_jobs_is_not_an_error(self): - with tempfile.TemporaryDirectory() as d: - banks = os.path.join(d, "banks") - os.mkdir(banks) - for tool, out in (("awc_opus.py", os.path.join(d, "ogg")), ("awc_shorts.py", os.path.join(d, "s.csv"))): - with self.subTest(tool=tool): - r = self.run_tool(tool, banks, out, "--jobs", "62") - self.assertEqual(r.returncode, 0, r.stdout + r.stderr) - self.assertNotIn("Traceback", r.stderr) - self.assertIn("0 banks", r.stdout) - - -@unittest.skipUnless(os.name == "nt", "the 61-worker limit is Windows's; elsewhere 62 workers always worked") -class RealPoolOnWindowsTest(unittest.TestCase): - """62 jobs through the real ProcessPoolExecutor, which starts a worker per job it is given, not all 61.""" - - def test_world_build_run_jobs(self): - self.assertEqual(list(world_build._run_jobs(abs, [-1, -2, -3], 62)), [1, 2, 3]) - - def test_world_lights_paths_scan(self): - with tempfile.TemporaryDirectory() as d: - path = os.path.join(d, "zeros.rpf") - with open(path, "wb") as f: - f.write(bytes(4096)) - self.assertEqual(world_lights_paths.scan(path, jobs=62), world_lights_paths.scan(path, jobs=1)) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/test_pr_conflict_label.py b/tests/test_pr_conflict_label.py deleted file mode 100644 index 087f47811..000000000 --- a/tests/test_pr_conflict_label.py +++ /dev/null @@ -1,157 +0,0 @@ -"""tools/pr_conflict_label.py labels conflicting pull requests `needs rebase` and unlabels them once they merge. - - python -I tests/test_pr_conflict_label.py - -A fake GitHub API stands in for the network, so this checks the calls the tool makes: which pull requests get the -label, that one whose merge GitHub has not computed yet is asked again and otherwise left alone, that the label is -created only when it is first needed, that `--dry-run` writes nothing, and that the workflow runs the tool without -checking out pull request code. Standard library only; no network, no game files. -""" -import os -import re -import sys -import unittest - -ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) -sys.path.insert(0, os.path.join(ROOT, "tools")) -import pr_conflict_label as pcl # noqa: E402 - -REPO = "owner/name" - - -class FakeApi: - """Pull requests as {number: [mergeable answers in order, the last one repeating]} plus their labels.""" - - def __init__(self, prs, labeled=(), label_exists=False, closed=()): - self.answers = {n: list(a) for n, a in prs.items()} - self.labels = {n: ({pcl.LABEL} if n in labeled else set()) for n in prs} - self.closed = set(closed) - self.label_exists = label_exists - self.calls = [] - - def __call__(self, method, path, body=None): - self.calls.append((method, path, body)) - m = re.fullmatch(rf"/repos/{REPO}/pulls/(\d+)", path) - if method == "GET" and m: - n = int(m.group(1)) - answers = self.answers[n] - mergeable = answers.pop(0) if len(answers) > 1 else answers[0] - return {"number": n, "state": "closed" if n in self.closed else "open", "mergeable": mergeable, - "labels": [{"name": name} for name in sorted(self.labels[n])]} - if method == "GET" and path.startswith(f"/repos/{REPO}/pulls?"): - page = int(re.search(r"[?&]page=(\d+)", path).group(1)) - numbers = sorted(self.answers) - return [{"number": n} for n in numbers[(page - 1) * 100:page * 100]] - if method == "POST" and path == f"/repos/{REPO}/labels": - if self.label_exists: - raise pcl.ApiError(422, "already_exists") - self.label_exists = True - return {} - m = re.fullmatch(rf"/repos/{REPO}/issues/(\d+)/labels", path) - if method == "POST" and m: - self.labels[int(m.group(1))] |= set(body["labels"]) - return [] - m = re.fullmatch(rf"/repos/{REPO}/issues/(\d+)/labels/needs%20rebase", path) - if method == "DELETE" and m: - n = int(m.group(1)) - if pcl.LABEL not in self.labels[n]: - raise pcl.ApiError(404, "Label does not exist") - self.labels[n].discard(pcl.LABEL) - return None - raise AssertionError(f"unexpected call {method} {path}") - - def writes(self): - return [c for c in self.calls if c[0] != "GET"] - - -def run(api, numbers, **kw): - return pcl.run(api, REPO, numbers, sleep=lambda s: None, out=lambda s: None, **kw) - - -class DecideTest(unittest.TestCase): - def test_every_case(self): - self.assertEqual(pcl.decide(False, False), "add") - self.assertEqual(pcl.decide(True, True), "remove") - self.assertIsNone(pcl.decide(False, True)) # already labeled - self.assertIsNone(pcl.decide(True, False)) # clean and unlabeled - self.assertIsNone(pcl.decide(None, False)) # not computed: never guess - self.assertIsNone(pcl.decide(None, True)) - - -class RunTest(unittest.TestCase): - def test_labels_conflicts_and_unlabels_rebased_ones(self): - api = FakeApi({1: [False], 2: [True], 3: [True], 4: [False]}, labeled={3, 4}) - done = run(api, [1, 2, 3, 4]) - self.assertEqual(done, {"add": [1], "remove": [3], "unknown": []}) - self.assertEqual(api.labels, {1: {pcl.LABEL}, 2: set(), 3: set(), 4: {pcl.LABEL}}) - - def test_an_uncomputed_merge_is_asked_again_then_left_alone(self): - api = FakeApi({1: [None, None, False], 2: [None]}, labeled={2}) - done = run(api, [1, 2], attempts=4) - self.assertEqual(done, {"add": [1], "remove": [], "unknown": [2]}) - self.assertEqual(api.labels[2], {pcl.LABEL}) # unknown keeps the label it had - self.assertEqual(sum(1 for c in api.calls if c[1] == f"/repos/{REPO}/pulls/2"), 4) - - def test_the_label_is_created_once_and_only_when_needed(self): - api = FakeApi({1: [True], 2: [True]}) - run(api, [1, 2]) - self.assertEqual(api.writes(), []) - api = FakeApi({1: [False], 2: [False]}) - run(api, [1, 2]) - self.assertEqual(sum(1 for c in api.writes() if c[1] == f"/repos/{REPO}/labels"), 1) - - def test_an_existing_label_is_not_an_error(self): - api = FakeApi({1: [False]}, label_exists=True) - self.assertEqual(run(api, [1])["add"], [1]) - - def test_a_label_removed_in_between_is_not_an_error(self): - api = FakeApi({1: [True]}, labeled={1}) - api.labels[1].discard(pcl.LABEL) - orig = api.__call__ - - def stale(method, path, body=None): # the GET still reports the label someone just removed - result = orig(method, path, body) - if method == "GET" and path.endswith("/pulls/1"): - result["labels"] = [{"name": pcl.LABEL}] - return result - self.assertEqual(pcl.run(stale, REPO, [1], sleep=lambda s: None, out=lambda s: None)["remove"], [1]) - - def test_closed_pull_requests_are_skipped(self): - api = FakeApi({1: [False]}, closed={1}) - self.assertEqual(run(api, [1]), {"add": [], "remove": [], "unknown": []}) - self.assertEqual(api.writes(), []) - - def test_dry_run_writes_nothing(self): - api = FakeApi({1: [False], 2: [True]}, labeled={2}) - done = run(api, [1, 2], dry_run=True) - self.assertEqual((done["add"], done["remove"]), ([1], [2])) - self.assertEqual(api.writes(), []) - - def test_open_pull_numbers_follows_pages(self): - api = FakeApi({n: [True] for n in range(1, 251)}) - self.assertEqual(pcl.open_pull_numbers(api, REPO), list(range(1, 251))) - - -class WorkflowTest(unittest.TestCase): - def setUp(self): - with open(os.path.join(ROOT, ".github", "workflows", "conflict-label.yml"), encoding="utf-8") as f: - self.text = f.read() - - def test_runs_this_tool(self): - self.assertIn("python3 -I tools/pr_conflict_label.py", self.text) - - def test_never_checks_out_pull_request_code(self): - # pull_request_target runs with a write token; checking out the head would run untrusted code with it. - self.assertIn("pull_request_target", self.text) - self.assertNotRegex(self.text, r"github\.event\.pull_request\.head|github\.head_ref|refs/pull/") - self.assertRegex(self.text, r"ref:\s*\$\{\{\s*github\.event\.repository\.default_branch\s*\}\}") - self.assertIn("persist-credentials: false", self.text) - - def test_token_is_limited_to_pull_requests(self): - self.assertRegex(self.text, r"(?m)^permissions:\s*\{\}\s*$") - job_perms = re.findall(r"(?m)^\s{6}(\w[\w-]*):\s*(read|write)\s*$", self.text) - self.assertEqual(dict(job_perms), {"contents": "read", "pull-requests": "write"}) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/test_printable_bytes.py b/tests/test_printable_bytes.py deleted file mode 100644 index b7cc38326..000000000 --- a/tests/test_printable_bytes.py +++ /dev/null @@ -1,61 +0,0 @@ -"""The text test the index tools share: tools/story_index.py, tools/anim_index.py and tools/restofworld_index.py. - - python -I tests/test_printable_bytes.py - -A stream is called text when more than 90% of its first 512 bytes are printable ASCII, a tab or a line ending. The -C0 control bytes other than those three (0x0B, 0x0C, 0x0E..0x1F) are not text. Every byte here is built by the -test; no game file is used. -""" -import os -import sys -import unittest - -ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) -sys.path.insert(0, os.path.join(ROOT, "tools")) - -import anim_index # noqa: E402 -import restofworld_index # noqa: E402 -import story_index # noqa: E402 - -TOOLS = (story_index, anim_index, restofworld_index) - -# No tool has a signature for these: what is left is the text test and the raw fallback. -CONTROLS = bytes(range(0x0E, 0x20)) * 28 # 504 bytes, none of them printable -TEXT = b"key\tvalue\r\nname\tsynthetic entry\r\n" * 16 # tabs and CRLF count as text - - -def signature(tool, data): - return tool.classify(data, 0, len(data))["signature"] - - -class PrintableBytes(unittest.TestCase): - def test_control_bytes_are_not_text(self): - for tool in TOOLS: - with self.subTest(tool=tool.__name__): - self.assertFalse(tool._printable(CONTROLS)) - self.assertEqual(signature(tool, CONTROLS), "raw:0e0f1011") - - def test_each_remaining_control_byte_is_not_printable(self): - for tool in TOOLS: - for byte in (0x00, 0x08, 0x0B, 0x0C, 0x0E, 0x1B, 0x1F, 0x7F, 0x80, 0xFF): - with self.subTest(tool=tool.__name__, byte=hex(byte)): - self.assertFalse(tool._printable(bytes([byte]) * 64)) - - def test_ascii_with_tabs_and_line_endings_is_text(self): - for tool in TOOLS: - with self.subTest(tool=tool.__name__): - self.assertTrue(tool._printable(TEXT)) - self.assertEqual(signature(tool, TEXT), "text") - for byte in (0x09, 0x0A, 0x0D, 0x20, 0x7E): - self.assertTrue(tool._printable(bytes([byte]) * 64), hex(byte)) - - def test_the_ninety_percent_bound_is_unchanged(self): - for tool in TOOLS: - with self.subTest(tool=tool.__name__): - self.assertTrue(tool._printable(b"a" * 93 + b"\x01" * 7)) # 93% text - self.assertFalse(tool._printable(b"a" * 90 + b"\x01" * 10)) # exactly 90% is not "more than" - self.assertFalse(tool._printable(b"a" * 63)) # under 64 bytes is never text - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/test_progress_dashboard.py b/tests/test_progress_dashboard.py deleted file mode 100644 index ad22e8149..000000000 --- a/tests/test_progress_dashboard.py +++ /dev/null @@ -1,660 +0,0 @@ -"""tools/progress_dashboard.py: parsers, classification, the no-game-data rule and the output-folder rule. - - python -I tests/test_progress_dashboard.py - -Every input is written here by hand (Markdown tables, JUnit XML, a CTest log, a fake work folder whose shader names -are sentinels). No game files, no GPU, no network: the GitHub path is fed synthetic gh output. -""" -import contextlib -import io -import json -import os -from pathlib import Path -import subprocess -import sys -import tempfile -from types import SimpleNamespace -import unittest -from unittest import mock - -HERE = os.path.dirname(os.path.abspath(__file__)) -ROOT = os.path.dirname(HERE) -sys.path.insert(0, os.path.join(ROOT, "tools")) - -import progress_dashboard as pd # noqa: E402 - -TOOL = os.path.join(ROOT, "tools", "progress_dashboard.py") -SENTINEL = "SENTINEL_SHADER_NAME_must_not_appear" - - -class Markdown(unittest.TestCase): - def test_tables_keep_pipes_inside_code(self): - t = pd.md_tables("## Translator status and runtime contract\n\n| Piece | Contract |\n|---|---|\n| A | `x|y` is **GPU-checked** |\n") - self.assertEqual(len(t), 1) - heading, header, rows, line = t[0] - self.assertEqual(heading, "Translator status and runtime contract") - self.assertEqual(rows[0][1], "`x|y` is **GPU-checked**") - self.assertEqual(line, 3) - - def test_plain_strips_links_and_emphasis(self): - self.assertEqual(pd.plain("**GPU-checked** ([measurement](http://x)) `v_mac_f32`"), "GPU-checked (measurement) v_mac_f32") - - -class Contract(unittest.TestCase): - def test_classification_order_and_evidence(self): - cases = { - "**not yet GPU-verified**; Source: LLVM `SIInstrInfo.cpp`": ("not_gpu", "partial"), - "**GPU-checked** (TEST-298) on an NVIDIA GeForce RTX 2060": ("gpu", "verified"), - "Source: LLVM `VOPProfileI2F`": ("reference", "implemented"), - "a count over the corpus: 0 of the 26,503 shaders": ("corpus", "implemented"), - "CPU-checked by DenormalFlushTests": ("cpu", "implemented"), - "The translator emits OpFAdd.": ("unstated", "unknown"), - } - for text, (kind, status) in cases.items(): - with self.subTest(text=text): - k, s, words = pd.classify_contract(text) - self.assertEqual((k, s), (kind, status)) - if kind != "unstated": - self.assertIn(words.lower(), text.lower()) - - def test_open_items_are_detected_only_by_explicit_words(self): - self.assertTrue(pd.OPEN.search("Still open: on some inputs the result is undefined")) - self.assertFalse(pd.OPEN.search("s_getreg_b32 is unsupported and there are no traps")) - - -class Tests(unittest.TestCase): - def test_junit_honors_each_reports_encoding(self): - xml = '' - with tempfile.TemporaryDirectory() as root: - paths = [] - for codec, declared, name in (("utf-16", "UTF-16", "日本語"), ("latin-1", "ISO-8859-1", "café"), - ("ascii", "not-a-codec", "bad")): - path = os.path.join(root, codec + ".xml") - with open(path, "wb") as f: - f.write(xml.format(declared, name).encode(codec)) - paths.append(path) - col = pd.Collector() - with mock.patch.object(pd, "ROOT", root), mock.patch.object(pd, "last_commit_time", return_value=None): - pd.collect_ctest(col, SimpleNamespace(junit=paths)) - self.assertEqual([(c["name"], c["status"]) for c in col.components], [("日本語", "failed"), ("café", "failed")]) - self.assertEqual([s["status"] for s in col.sources if s["id"] == "junit"], ["ok", "ok", "invalid"]) - - def test_unittest_file_is_skipped_only_when_all_cases_skip(self): - with tempfile.TemporaryDirectory() as directory, mock.patch.object(pd, "ROOT", directory): - file = os.path.join(directory, "test_sample.py") - for skipped in (0, 1, 2): - with self.subTest(skipped=skipped): - with open(file, "w", encoding="utf-8", newline="\n") as f: - f.write(f"import unittest\nclass Sample(unittest.TestCase):\n" - f" @unittest.skipIf({skipped} > 0, 'synthetic')\n" - f" def test_first(self): pass\n" - f" @unittest.skipIf({skipped} > 1, 'synthetic')\n" - f" def test_second(self): pass\n" - f"unittest.main()\n") - result = pd.run_one_test("test_sample.py", 15) - self.assertEqual(result["result"], "pass", result) - self.assertEqual(result["cases"], 2) - self.assertEqual(result["all_skipped"], skipped == 2) - - def test_junit_ctest_and_pytest_flavours(self): - ctest = '' \ - '' - rows = pd.parse_junit(ctest) - self.assertEqual([(n, r) for n, r, _, _ in rows], [("loader", "pass"), ("xmem", "fail")]) - self.assertNotIn("me", rows[1][3]) # paths are reduced to their last component - pytest = '' \ - '' - self.assertEqual([(n, r) for n, r, _, _ in pd.parse_junit(pytest)], [("tests.a::t[1-2]", "pass"), ("tests.a::t[1_2]", "skip")]) - - def test_lasttest_log(self): - log = "Start testing: Nov 22 10:00 X\n1/2 Test: loader\nTest time = 0.91 sec\nTest Passed.\n2/2 Test: xmem\nTest Failed.\n" - self.assertEqual(pd.parse_lasttest(log), [("loader", "pass", 0.91), ("xmem", "fail", None)]) - - def test_lasttest_uses_ctest_verdicts_after_captured_output(self) -> None: - cases = ( - ("required", "ready", "Test Pass Reason:\nRequired regular expression found. Regex=[ready]", "pass"), - ("forbidden", "Test Passed.\nerror", "Test Fail Reason:\nError regular expression found in output. Regex=[error]", "fail"), - ("missing", "stopped", "Test Fail Reason:\nRequired regular expression not found. Regex=[ready]", "fail"), - ("unavailable", "unavailable", "Test Pass Reason:\nSkip regular expression found in output. Regex=[unavailable]", "skip"), - ("ordinary", "Test Fail Reason:\nunrelated test output", "Test Passed.", "pass"), - ) - log = "\n".join( - f"{index}/{len(cases)} Test: {name}\nOutput:\n{'-' * 58}\n{output}\n\n" - f"Test time = 0.01 sec\n{'-' * 58}\n{verdict}\n" - for index, (name, output, verdict, _expected) in enumerate(cases, 1) - ) - self.assertEqual(pd.parse_lasttest(log), [(name, expected, 0.01) for name, _, _, expected in cases]) - - def test_lasttest_ignores_a_nested_ctest_log(self) -> None: - separator = "-" * 58 - inner = ( - f"Start testing: Nov 22 10:00 X\n{separator}\n1/1 Testing: outer\n1/1 Test: outer\n" - f"Output:\n{separator}\n\nTest time = 0.01 sec\n{separator}\n" - f'Test Passed.\n"outer" end time: Nov 22 10:00 X\n"outer" time elapsed: 00:00:00\n' - f"{separator}\n\nEnd testing: Nov 22 10:00 X" - ) - log = ( - f"Start testing: Nov 22 10:00 X\n{separator}\n1/2 Testing: outer\n1/2 Test: outer\n" - f"Output:\n{separator}\n{inner}\nouter fails\n\n" - f'Test time = 0.23 sec\n{separator}\nTest Failed.\n"outer" end time: Nov 22 10:00 X\n' - f'"outer" time elapsed: 00:00:00\n{separator}\n\n2/2 Test: next\n' - "Test time = 0.02 sec\nTest Passed.\n" - ) - self.assertEqual(pd.parse_lasttest(log), [("outer", "fail", 0.23), ("next", "pass", 0.02)]) - - def test_ci_selection_matches_the_workflow_rule(self): - files = pd.ci_test_files() - self.assertIn("tests/test_progress_dashboard.py", files) - self.assertFalse(any(f.startswith("tests/semantic/") for f in files)) - for f in files[:20]: - with open(os.path.join(ROOT, f), encoding="utf-8") as fh: - text = fh.read() - self.assertIn("__main__", text) - self.assertIsNone(pd.PYTEST_MARKERS.search(text)) - - def test_unlistable_subfolder_raises_instead_of_a_partial_scan(self): - # os.walk skips a directory it cannot list unless onerror raises; the selection and the digest - # used to silently drop the sub-folder and report the rest as complete. - def walk(top, onerror=None, **kwargs): - if onerror is not None: - onerror(PermissionError(13, "Permission denied", os.path.join(top, "locked"))) - return - yield # pragma: no cover - - with mock.patch.object(pd.os, "walk", side_effect=walk): - with self.assertRaises(PermissionError): - pd.ci_test_files() - with self.assertRaises(PermissionError): - pd.code_digest() - - -class Freshness(unittest.TestCase): - def collect(self, results): - with tempfile.TemporaryDirectory() as out: - with open(os.path.join(out, "unit_results.json"), "w", encoding="utf-8", newline="\n") as f: - json.dump(results, f) - col = pd.Collector() - pd.collect_unit(col, out, type("A", (), {"run_tests": False})()) - return {c["name"]: (c["status"], c["freshness"]) for c in col.components} - - def base(self, digest, code): - return {"ran_at": "2026-11-22T10:00:00Z", "commit": None, "code_digest": code, - "results": [{"test": "tests/test_progress_dashboard.py", "result": "pass", "digest": digest}]} - - def test_unchanged_test_and_code_is_current(self): - got = self.collect(self.base(pd.file_digest("tests/test_progress_dashboard.py"), pd.code_digest())) - self.assertEqual(got["test_progress_dashboard.py"], ("verified", "current")) - - def test_changed_test_file_needs_revalidation(self): - got = self.collect(self.base("0" * 16, pd.code_digest())) - self.assertEqual(got["test_progress_dashboard.py"], ("partial", "revalidation_required")) - - def test_changed_tools_need_revalidation(self): - got = self.collect(self.base(pd.file_digest("tests/test_progress_dashboard.py"), "0" * 16)) - self.assertEqual(got["test_progress_dashboard.py"], ("partial", "revalidation_required")) - - def test_changed_shader_helper_needs_revalidation(self): - with tempfile.TemporaryDirectory() as root, mock.patch.object(pd, "ROOT", root): - for directory in ("tools", "scripts", "runtime/test/shaders", "tests"): - Path(root, directory).mkdir(parents=True) - test = "tests/test_progress_dashboard.py" - Path(root, test).touch() - helper = Path(root, "runtime/test/shaders/compute_fixture.py") - helper.write_bytes(b"shift = 0\n") - cached = self.base(pd.file_digest(test), pd.code_digest()) - self.assertEqual(self.collect(cached)["test_progress_dashboard.py"], ("verified", "current")) - - helper.write_bytes(b"shift = 1\n") - self.assertEqual(self.collect(cached)["test_progress_dashboard.py"], ("partial", "revalidation_required")) - - def test_code_edited_during_the_run_is_never_current(self): - got = self.collect(self.base(pd.file_digest("tests/test_progress_dashboard.py"), None)) - self.assertEqual(got["test_progress_dashboard.py"], ("verified", "unknown")) - - def test_ctest_junit_passes_age_like_lasttest_log(self): - ctest_suite = '{}' - sources = { - "runtime/build/Testing/Temporary/LastTest.log": (100, "1/1 Test: local\nTest Passed.\n"), - "before.xml": (100, ctest_suite.format( - '' - '')), - "after.xml": (300, ctest_suite.format('')), - "pytest.xml": (100, '' - ''), - } - with tempfile.TemporaryDirectory() as root: - junit = [] - for name, (mtime, text) in sources.items(): - path = os.path.join(root, *name.split("/")) - os.makedirs(os.path.dirname(path), exist_ok=True) - with open(path, "w", encoding="utf-8", newline="\n") as f: - f.write(text) - os.utime(path, (mtime, mtime)) - if name.endswith(".xml"): - junit.append(path) - col = pd.Collector() - with mock.patch.object(pd, "ROOT", root), mock.patch.object(pd, "last_commit_time", return_value=200): - pd.collect_ctest(col, SimpleNamespace(junit=junit)) - - outcomes = {c["name"]: (c["status"], c["freshness"]) for c in col.components} - self.assertEqual(outcomes, { - "local": ("partial", "revalidation_required"), - "older": ("partial", "revalidation_required"), - "failed": ("failed", "failed"), - "skipped": ("unknown", "unknown"), - "newer": ("verified", "current"), - "unrelated": ("verified", "current"), - }) - metric = next(m for m in col.metrics if m["id"] == "runtime.current") - self.assertEqual((metric["numerator"], metric["denominator"]), (2, 6)) - - - def test_local_ctest_junit_replaces_log_and_keeps_independent_run(self): - with tempfile.TemporaryDirectory() as tmp, mock.patch.object(pd, "ROOT", tmp), \ - mock.patch.object(pd, "last_commit_time", return_value=0): - log = Path(tmp, "runtime/build/Testing/Temporary/LastTest.log") - log.parent.mkdir(parents=True) - log.write_text("1/1 Test: probe\nTest Passed.\n", encoding="utf-8") - local = Path(tmp, "local.xml") - local.write_text('' - '', encoding="utf-8") - other = Path(tmp, "other.xml") - other.write_text('', encoding="utf-8") - col = pd.Collector() - pd.collect_ctest(col, SimpleNamespace(ctest_junit=str(local), junit=[str(local), str(other)])) - self.assertEqual([(c["group"], c["status"]) for c in col.components], - [("ctest", "unknown"), ("junit:other.xml", "verified")]) - metric = next(m for m in col.metrics if m["id"] == "runtime.current") - self.assertEqual((metric["numerator"], metric["denominator"]), (1, 2)) - - for path, status in [(other, "invalid"), (Path(tmp, "absent.xml"), "missing")]: - with self.subTest(status=status): - col = pd.Collector() - pd.collect_ctest(col, SimpleNamespace(ctest_junit=str(path), junit=[])) - self.assertEqual(col.components, []) - self.assertEqual([(s["id"], s["status"]) for s in col.sources], [("ctest_junit", status)]) - - -class GpuLog(unittest.TestCase): - LOG = "\n".join([ - "using runtime/build/RelWithDebInfo", - "cs_bounds ok", - "ps_texoff SKIP (VK_KHR_maintenance8 missing)", - "cs_bpermute32 lane 3: got 0x00000000, want 0x00000007", - "2 of 3 pass, 1 skipped", - ]) - - def test_lines_and_summary(self): - rows, summary = pd.parse_gpu_log(self.LOG) - self.assertEqual([(n, r) for n, r, _ in rows], [("cs_bounds", "pass"), ("ps_texoff", "skip"), ("cs_bpermute32", "fail")]) - self.assertIn("want 0x00000007", rows[2][2]) - self.assertEqual(summary, (2, 3, 1)) - - def test_panel_groups_by_gpu_label(self): - with tempfile.TemporaryDirectory() as tmp: - log = os.path.join(tmp, "check.txt") - with open(log, "w", encoding="utf-8", newline="\n") as f: - f.write(self.LOG + "\n") - col = pd.Collector() - pd.collect_gpu(col, [log + "=RTX 4060, 576.02, Windows 11"]) - self.assertEqual({c["group"] for c in col.components}, {"RTX 4060, 576.02, Windows 11"}) - self.assertEqual(sorted(c["status"] for c in col.components)[0], "failed") - m = next(m for m in col.metrics if m["id"] == "gpu.current") - self.assertEqual(m["denominator"], 2) # the skip is not counted - - -class Github(unittest.TestCase): - def test_default_repo_is_the_one_the_readme_clones(self): - # --github once read a repository that had gone private; the README is where the address is kept current - with open(os.path.join(ROOT, "README.md"), encoding="utf-8") as f: - self.assertIn(f"`git clone --recursive https://github.com/{pd.DEFAULT_REPO}`", f.read()) - - def test_d3d_states(self): - self.assertEqual(pd.d3d_state("@a", "#291 merged, #819, #831 on main", "")[0], "partial") - self.assertEqual(pd.d3d_state("@a", "#1489 merged, #907 closed", "")[0], "implemented") - self.assertEqual(pd.d3d_state("@a", "—", "")[0], "unknown") - self.assertEqual(pd.d3d_state("—", "—", "")[0], "missing") - - def test_d3d_states_follow_the_merged_list(self): - merged, open_prs = {819, 831, 291}, {900} - # the table still lists #819 without "merged", but it merged: the item is implemented - self.assertEqual(pd.d3d_state("@a", "#291 merged, #819", "PR open", merged, open_prs)[0], "implemented") - self.assertEqual(pd.d3d_state("@a", "#819, #900", "", merged, open_prs)[0], "partial") - # a bare reference that is neither merged nor open was closed without merging: it does not count - self.assertEqual(pd.d3d_state("@a", "#777", "", merged, open_prs)[0], "unknown") - self.assertEqual(pd.d3d_state("@a", "—", "PR open", merged, open_prs)[0], "partial") - - def test_item_ids(self): - self.assertEqual(pd.item_ids("D3D-86: answer D3D12_OPTIONS1 in CheckFeatureSupport"), ["D3D-86"]) - self.assertEqual(pd.item_ids("pknorm_probe: NaN gives 0 (SHADER-339)"), ["SHADER-339"]) - self.assertEqual(pd.item_ids("Docs/Tests: SHADER-4 and SHADER-4 again, TEST-9"), ["SHADER-4", "TEST-9"]) - self.assertEqual(pd.item_ids("hash with SHA-256, write UTF-8, read OPTIONS2-1 and D3D12-3"), []) - self.assertEqual(pd.item_ids(None), []) - - def test_d3d_metric_counts_merged_pull_requests_not_only_table_rows(self): - body = ("| ID | Title | Owner | PR | Status |\n|---|---|---|---|---|\n" - "| D3D-1 | a | @a | #50 | PR open |\n| D3D-2 | b | @b | #51 | PR open |\n") - merged = [{"number": n, "title": f"D3D-{n}: x", "mergedAt": "2026-11-22T10:00:00Z", "author": {"login": "x"}} - for n in (10, 11, 12)] - open_prs = [{"number": 50, "title": "D3D-1: a", "isDraft": False, "author": {"login": "x"}}, - {"number": 51, "title": "D3D-2: b", "isDraft": False, "author": {"login": "x"}}] - - def fake_gh(args, timeout=60): - if args[:2] == ["pr", "list"]: - return merged if "merged" in args else open_prs - if args[:2] == ["issue", "view"]: - return {"body": body, "updatedAt": "2026-11-22T00:00:00Z"} - if args[:2] == ["issue", "list"] and "D3D12" in args[args.index("--search") + 1]: - return [{"number": 313, "title": "D3D12 → Vulkan layer: critical path, who builds what"}] - return [] - col = pd.Collector() - with mock.patch.object(pd, "gh_json", fake_gh), mock.patch.object(pd.shutil, "which", lambda _: "/usr/bin/gh"): - pd.collect_github(col, "o/r", "me") - m = next(m for m in col.metrics if m["id"] == "d3d12.merged") - self.assertEqual((m["numerator"], m["denominator"]), (3, 5)) - - def run_d3d_metric(self, body, merged, open_prs): - """The d3d12.merged metric for a #313 body and the repository's merged and open PR lists (None: unreadable).""" - def fake_gh(args, timeout=60): - if args[:2] == ["pr", "list"]: - return merged if "merged" in args else open_prs - if args[:2] == ["issue", "view"]: - return {"body": body, "updatedAt": "2026-11-22T00:00:00Z"} - if args[:2] == ["issue", "list"] and "D3D12" in args[args.index("--search") + 1]: - return [{"number": 313, "title": "D3D12 → Vulkan layer: critical path, who builds what"}] - return [] - col = pd.Collector() - with mock.patch.object(pd, "gh_json", fake_gh), mock.patch.object(pd.shutil, "which", lambda _: "/usr/bin/gh"): - pd.collect_github(col, "o/r", "me") - return next(m for m in col.metrics if m["id"] == "d3d12.merged") - - D3D_BODY = ("| ID | Title | Owner | PR | Status |\n|---|---|---|---|---|\n" - "| D3D-4 | b | @b | #60 merged | merged |\n| D3D-5 | c | @c | #61 | PR open |\n") - - def run_d3d_lookup(self, issues, d3d_issue=None, readable=True): - """collect_github() with these open issues answering the D3D12 title search: the collector, the summary and - every gh call made.""" - calls = [] - - def fake_gh(args, timeout=60): - calls.append(args) - if args[:2] == ["issue", "view"]: - return {"body": self.D3D_BODY, "updatedAt": "2026-11-22T00:00:00Z"} if readable else None - if args[:2] == ["issue", "list"] and "D3D12" in args[args.index("--search") + 1]: - return issues - return [] - col = pd.Collector() - with mock.patch.object(pd, "gh_json", fake_gh), mock.patch.object(pd.shutil, "which", lambda _: "/usr/bin/gh"): - summary = pd.collect_github(col, "o/r", None, d3d_issue) - return col, summary, calls - - @staticmethod - def viewed(calls): - return [a[2] for a in calls if a[:2] == ["issue", "view"]] - - def test_d3d_issue_is_found_by_title_not_by_a_fixed_number(self): - # #313 was the tracking issue in the repository the project started in; here that number is something else - col, summary, calls = self.run_d3d_lookup([ - {"number": 12, "title": "d3d12_vulkan_device: a crash in the Vulkan layer"}, - {"number": 90, "title": "D3D12 -> Vulkan layer: critical path (continues the one below)"}, - {"number": 41, "title": "D3D12 → Vulkan layer: critical path, who builds what, open methods"}, - ]) - self.assertEqual(self.viewed(calls), ["41"]) # the oldest issue with the title; never "313" - self.assertEqual(summary["d3d_issue"], 41) - self.assertEqual(col.panels["d3d12"]["title"], "D3D12 → Vulkan layer items (#41)") - source = next(s for s in col.sources if s["id"] == "github_d3d12") - self.assertEqual((source["status"], source["records"]), ("ok", 2)) - self.assertTrue(any(m["id"] == "d3d12.merged" for m in col.metrics)) - - def test_no_d3d_issue_is_reported_and_no_other_issue_is_read(self): - for issues in ([], None, [{"number": 313, "title": "tests: an unrelated pull request"}]): - with self.subTest(issues=issues): - col, summary, calls = self.run_d3d_lookup(issues) - self.assertEqual(self.viewed(calls), []) - self.assertNotIn("d3d_issue", summary) - source = next(s for s in col.sources if s["id"] == "github_d3d12") - self.assertEqual(source["status"], "missing") - self.assertIn("--d3d-issue", source["note"]) - self.assertEqual(col.panels["d3d12"]["title"], "D3D12 → Vulkan layer items") - self.assertFalse(any(m["id"] == "d3d12.merged" for m in col.metrics)) - - def test_d3d_issue_option_names_the_issue(self): - col, summary, calls = self.run_d3d_lookup([{"number": 41, "title": "D3D12 → Vulkan layer: x"}], d3d_issue=7) - self.assertEqual(self.viewed(calls), ["7"]) - self.assertFalse(any(a[:2] == ["issue", "list"] and "D3D12" in a[a.index("--search") + 1] for a in calls)) - self.assertEqual(summary["d3d_issue"], 7) - - def test_unreadable_d3d_issue_is_reported(self): - col, _, _ = self.run_d3d_lookup([], d3d_issue=7, readable=False) - source = next(s for s in col.sources if s["id"] == "github_d3d12") - self.assertEqual(source["status"], "invalid") - self.assertIn("#7", source["note"]) - - def test_d3d_issue_option_is_checked(self): - for argv in (["--out", "x", "--d3d-issue", "7"], ["--out", "x", "--github", "--d3d-issue", "0"]): - with self.subTest(argv=argv), contextlib.redirect_stderr(io.StringIO()) as err: - with self.assertRaises(SystemExit) as stop: - pd.main(argv) - self.assertEqual(stop.exception.code, 2) - self.assertIn("--d3d-issue", err.getvalue()) - - @staticmethod - def prs(*pairs): - return [{"number": n, "title": t, "isDraft": False, "mergedAt": "2026-11-22T10:00:00Z", "author": {"login": "x"}} - for n, t in pairs] - - def test_d3d_id_with_an_open_pr_is_not_counted_as_merged(self): - body = ("| ID | Title | Owner | PR | Status |\n|---|---|---|---|---|\n" - "| D3D-3 | a | @a | #819 | PR open |\n| D3D-4 | b | @b | #60 merged | merged |\n") - merged = self.prs((291, "D3D-3: first part"), (60, "D3D-4: b"), (292, "D3D-20: c"), (293, "D3D-21: d")) - open_prs = self.prs((819, "D3D-3: rest"), (820, "D3D-20: more")) - m = self.run_d3d_metric(body, merged, open_prs) - # D3D-4 (table: merged) and D3D-21 (merged PR, no open PR); not D3D-3 (table: open) or D3D-20 (open PR) - self.assertEqual((m["numerator"], m["denominator"]), (2, 4)) - self.assertNotIn("note", m) - - def test_d3d_metric_says_so_when_a_pr_list_could_not_be_read(self): - body = ("| ID | Title | Owner | PR | Status |\n|---|---|---|---|---|\n" - "| D3D-4 | b | @b | #60 merged | merged |\n| D3D-5 | c | @c | #61 | PR open |\n") - m = self.run_d3d_metric(body, self.prs((70, "D3D-9: x")), None) - self.assertEqual((m["numerator"], m["denominator"]), (1, 2)) # table rows only - self.assertIn("partial", m["title"]) - self.assertIn("could not be read", m["note"]) - - def test_merged_pull_requests_are_implemented(self): - merged = [{"number": 10, "title": "D3D-1: a", "mergedAt": "2026-11-22T10:00:00Z", "author": {"login": "x"}}, - {"number": 12, "title": "docs: b", "mergedAt": "2026-11-22T12:00:00Z", "author": {"login": "y"}}] - open_prs = [{"number": 13, "title": "D3D-2: c", "isDraft": True, "author": {"login": "z"}}] - col = pd.Collector() - latest = pd.collect_pulls(col, "o/r", merged, open_prs) - got = {c["number"]: (c["status"], c["group"]) for c in col.components} - self.assertEqual(got, {10: ("implemented", "D3D items"), 12: ("implemented", "no item ID"), 13: ("partial", "D3D items")}) - self.assertEqual([p["number"] for p in latest], [12, 10]) # newest merge first - m = {m["id"]: (m["numerator"], m["denominator"]) for m in col.metrics} - self.assertEqual(m["merged.prs"], (2, 3)) - self.assertEqual(m["merged.items"], (1, 2)) - self.assertNotIn("merged_at", next(c for c in col.components if c["number"] == 13)) - - def test_pull_request_limit_is_reported(self): - col = pd.Collector() - pd.collect_pulls(col, "o/r", [{"number": 1, "title": "a", "mergedAt": "x"}], [], limit=1) - self.assertIn("limit was reached", col.sources[0]["note"]) - - -class Corpus(unittest.TestCase): - def test_counts_only_never_names(self): - with tempfile.TemporaryDirectory() as tmp: - work = os.path.join(tmp, "work") - sh = os.path.join(work, "shaders") # make_game.py's layout - os.makedirs(os.path.join(sh, "dxbc")) - os.makedirs(os.path.join(sh, "spirv")) - carved = [{"name": f"{SENTINEL}_{i}", "stage": "pixel" if i < 3 else "compute"} for i in range(5)] - with open(os.path.join(sh, "dxbc", "index.json"), "w", encoding="utf-8", newline="\n") as f: - json.dump(carved, f) - with open(os.path.join(sh, "spirv", "index.json"), "w", encoding="utf-8", newline="\n") as f: - json.dump({f"{SENTINEL}_0": {"stage": "pixel"}, f"{SENTINEL}_3": {"stage": "compute"}, - f"{SENTINEL}_4": {"error": "x"}}, f) - col = pd.Collector() - pd.collect_corpus(col, work) - got = {(c["group"], c["status"]): c["count"] for c in col.components} - self.assertEqual(got, {("pixel", "implemented"): 1, ("pixel", "failed"): 2, - ("compute", "implemented"): 1, ("compute", "failed"): 1}) - m = next(m for m in col.metrics if m["id"] == "corpus.validated") - self.assertEqual((m["numerator"], m["denominator"]), (2, 5)) - # everything the collector holds can reach the page (notes and panels included), so check all of it - held = json.dumps(vars(col), default=str) - self.assertNotIn(SENTINEL, held) - self.assertNotIn(tmp, held) - self.assertNotIn(json.dumps(tmp)[1:-1], held) - - -class Scrub(unittest.TestCase): - def test_paths_outside_the_repository_lose_their_file_name(self): - sep = os.sep - work = os.path.join(tempfile.gettempdir(), "work", "shaders", "dxbc", f"{SENTINEL}.fssm") - self.assertEqual(pd.scrub(f"FAIL: cannot read {work}"), "FAIL: cannot read ") - self.assertEqual(pd.scrub(f"see /home/someone/work/{SENTINEL}.fssm now"), "see now") - self.assertEqual(pd.scrub("in " + os.path.join(pd.HOME, "work", f"{SENTINEL}.fssm")), "in ") - self.assertEqual(pd.scrub(f"C:{sep}work{sep}{SENTINEL}_a.fssm, C:{sep}{SENTINEL}_b.fssm"), " ") - - def test_paths_inside_the_repository_become_relative(self): - line = "Error: " + os.path.join(ROOT, "tools", "text_tables.py") + " line 3" - self.assertEqual(pd.scrub(line), "Error: tools/text_tables.py line 3") - - def test_checkout_path_with_spaces_becomes_relative(self): - with tempfile.TemporaryDirectory() as tmp: - checkout = os.path.join(tmp, "Checkout with spaces [1]") - path = os.path.join(checkout, "tools", "text_tables.py") - os.makedirs(os.path.dirname(path)) - with open(path, "wb"): - pass - with mock.patch.object(pd, "ROOT", checkout): - self.assertEqual(pd.scrub(f"Error: {path} line 3"), "Error: tools/text_tables.py line 3") - self.assertEqual(pd.scrub(f'File "{path}", line 3'), 'File "tools/text_tables.py", line 3') - self.assertEqual(pd.scrub(f"Checkout: {checkout}"), "Checkout: .") - self.assertEqual(pd.scrub(f"Checkout {checkout} is ready"), "Checkout . is ready") - sibling = os.path.join(checkout + "x", f"{SENTINEL}.fssm") - self.assertEqual(pd.scrub(f"Error: {sibling} line 3"), "Error: line 3") - if os.name == "nt": - alternate = os.path.join(checkout.swapcase(), "tools", "text_tables.py").replace("\\", "/") - self.assertEqual(pd.scrub(f"Error: {alternate} line 3"), "Error: tools/text_tables.py line 3") - - def test_urls_and_relative_paths_stay(self): - self.assertEqual(pd.scrub("see https://github.com/ItsNotRexed/Leonida/issues/1"), - "see https://github.com/ItsNotRexed/Leonida/issues/1") - self.assertEqual(pd.scrub("tests/test_x.py failed"), "tests/test_x.py failed") - - -class Outputs(unittest.TestCase): - def test_login_without_github_is_an_argument_error(self): - with tempfile.TemporaryDirectory() as tmp: - out = os.path.join(tmp, "out") - cmd = [sys.executable, "-I", TOOL, "--out", out, "--login", "fixture-reviewer"] - result = subprocess.run(cmd, capture_output=True, cwd=ROOT, timeout=120) - self.assertEqual(result.returncode, 2, result.stderr.decode("utf-8", "replace")) - self.assertIn(b"--login requires --github", result.stderr) - self.assertFalse(os.path.exists(out)) - - def test_nonpositive_test_options_are_argument_errors(self): - with tempfile.TemporaryDirectory() as tmp: - out = os.path.join(tmp, "out") - for option in ("--jobs", "--test-timeout"): - for value in ("0", "-1"): - with self.subTest(option=option, value=value): - cmd = [sys.executable, "-I", TOOL, "--out", out, "--run-tests", - "--tests", "test_progress_dashboard", option, value] - result = subprocess.run(cmd, capture_output=True, cwd=ROOT, timeout=120) - self.assertEqual(result.returncode, 2, result.stderr.decode("utf-8", "replace")) - self.assertIn(f"{option} must be a positive integer".encode("ascii"), result.stderr) - self.assertFalse(os.path.exists(out)) - - def test_invalid_test_filter_is_an_argument_error(self): - with tempfile.TemporaryDirectory() as tmp: - out = os.path.join(tmp, "out") - result = subprocess.run([sys.executable, "-I", TOOL, "--out", out, "--run-tests", "--tests", "["], - capture_output=True, cwd=ROOT, timeout=120) - self.assertEqual(result.returncode, 2, result.stderr.decode("utf-8", "replace")) - self.assertIn(b"--tests", result.stderr) - self.assertIn(b"unterminated character set", result.stderr) - self.assertNotIn(b"Traceback", result.stderr) - self.assertFalse(os.path.exists(out)) - - def test_out_inside_the_repository_is_refused(self): - r = subprocess.run([sys.executable, "-I", TOOL, "--out", os.path.join(ROOT, "progress_out_test")], - capture_output=True, cwd=ROOT, timeout=120) - self.assertEqual(r.returncode, 2) - self.assertFalse(os.path.exists(os.path.join(ROOT, "progress_out_test"))) - - def test_save_text_refreshes_when_fixed_temp_name_is_a_directory(self): - with tempfile.TemporaryDirectory() as tmp: - out = os.path.join(tmp, "report.json") - stale = out + ".tmp" - os.mkdir(stale) - pd.save_text(out, '{"ok": 1}\n') - with open(out, encoding="utf-8") as f: - self.assertEqual(f.read(), '{"ok": 1}\n') - self.assertTrue(os.path.isdir(stale)) - self.assertEqual([n for n in os.listdir(tmp) if n.startswith("report.json.")], - ["report.json.tmp"]) - - def test_page_snapshot_history_and_dedupe(self): - with tempfile.TemporaryDirectory() as tmp: - out = os.path.join(tmp, "out") - cmd = [sys.executable, "-I", TOOL, "--out", out] - r1 = subprocess.run(cmd, capture_output=True, cwd=ROOT, timeout=300) - self.assertEqual(r1.returncode, 0, r1.stderr.decode("utf-8", "replace")) - with open(os.path.join(out, "progress.html"), encoding="utf-8") as f: - page = f.read() - self.assertNotIn("/*__PROGRESS_DATA__*/null", page) - self.assertNotIn("/*__PROGRESS_LOGO__*/", page) - if os.path.isfile(pd.LOGO): # the logo is embedded: the page needs no other file - self.assertIn('src="data:image/png;base64,', page) - self.assertIn('"schema": "leonida.progress/1"', page) - with open(os.path.join(out, "progress.html"), "rb") as f: - self.assertNotIn(b"\r\n", f.read()) # LF on every platform - r2 = subprocess.run(cmd, capture_output=True, cwd=ROOT, timeout=300) - self.assertIn(b"no change since the last snapshot", r2.stdout) - self.assertEqual(len(os.listdir(os.path.join(out, "snapshots"))), 1) - with open(os.path.join(out, "history.json"), encoding="utf-8") as f: - self.assertEqual(len(json.load(f)), 1) - - def test_unmatched_test_filter_preserves_cached_results(self): - with tempfile.TemporaryDirectory() as out: - cached = os.path.join(out, "unit_results.json") - previous = b'{"results":[{"test":"tests/test_progress_dashboard.py","result":"pass"}]}\n' - with open(cached, "wb") as f: - f.write(previous) - cmd = [sys.executable, "-I", TOOL, "--out", out, "--run-tests", "--tests", "^no-such-fixture$"] - result = subprocess.run(cmd, capture_output=True, cwd=ROOT, timeout=120) - self.assertEqual(result.returncode, 2, result.stderr.decode("utf-8", "replace")) - self.assertIn(b"--tests did not match any test files", result.stderr) - with open(cached, "rb") as f: - self.assertEqual(f.read(), previous) - - def test_missing_logo_leaves_no_image(self): - old = pd.LOGO - try: - pd.LOGO = os.path.join(ROOT, "assets", "no_such_logo.png") - self.assertEqual(pd.logo_src(), "") - self.assertIn('src=""', pd.render_page({"schema": pd.SCHEMA}, [])) - finally: - pd.LOGO = old - - def test_script_element_cannot_be_closed_by_data(self): - snap = {"schema": pd.SCHEMA, "x": ""} - self.assertNotIn("", pd.render_page(snap, [])) - - def test_out_as_existing_file_is_refused(self): - with tempfile.TemporaryDirectory() as tmp: - file_out = os.path.join(tmp, "not_a_dir") - with open(file_out, "wb") as f: - f.write(b"x") - err = io.StringIO() - with contextlib.redirect_stderr(err): - rc = pd.main(["--out", file_out]) - self.assertEqual(rc, 2) - self.assertIn("is not a directory", err.getvalue()) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/test_ps_helper_probe.py b/tests/test_ps_helper_probe.py deleted file mode 100644 index 1f1b28162..000000000 --- a/tests/test_ps_helper_probe.py +++ /dev/null @@ -1,122 +0,0 @@ -"""tools/ps_helper_probe.py: the analysis on a CPU model of what gfx1036 does (each check, and that it fails when the -model breaks that rule), the programs' shape, and (with LEONIDA_PS_ORACLE_BUILD set to a runtime build -and an AMD GPU selected) the measurement itself. Standard library only.""" -import os -import struct -import sys -import unittest - -ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) -sys.path.insert(0, os.path.join(ROOT, "tools")) -import ps_helper_probe as H # noqa: E402 - -W, Hh = H.SIZE - - -def u32(v): - return struct.unpack(" 0 and j > 0 and i + j < 1 - cov = {(x, y) for y in range(Hh) for x in range(W) if inside((x, y))} - quads = sorted({(x // 2, y // 2) for x, y in cov}, key=lambda q: (q[1], q[0])) - if empty_quads: - quads.insert(0, (99, 99)) # a quad with no covered pixel takes lanes 0..3 - lane, wave_of = {}, {} - for n, q in enumerate(quads): - for k in range(4): - p = (2 * q[0] + (k & 1), 2 * q[1] + (k >> 1)) - if swap_lanes: - k ^= 1 - lane[p], wave_of[p] = (n % 16) * 4 + k, n // 16 - entry, wqm = {}, {} - for p in cov: - w = wave_of[p] - entry[w] = entry.get(w, 0) | 1 << lane[p] - if helpers_at_entry: - for k in (1, 2, 3): - entry[w] |= 1 << lane[H.neighbour(p, k)] - for p in lane: - wqm[wave_of[p]] = wqm.get(wave_of[p], 0) | 1 << lane[p] - res = {n: {(x, y): H.CLEAR for y in range(Hh) for x in range(W)} for n in H.PROGRAMS} - for p in cov: - e, q = entry[wave_of[p]], wqm[wave_of[p]] - x, y = H.ndc(p) - res["masks"][p] = (lane[p], e & 0xFFFFFFFF, e >> 32, q & 0xFFFFFFFF) - res["self"][p] = (lane[p], q >> 32, u32(x), u32(y)) - nb = {k: H.ndc(H.neighbour(p, k)) for k in (1, 2, 3)} - if flat_helpers: - nb = {k: (x, y) if H.neighbour(p, k) not in cov else v for k, v in nb.items()} - res["nb12"][p] = (u32(nb[1][0]), u32(nb[1][1]), u32(nb[2][0]), u32(nb[2][1])) - res["nb3"][p] = (u32(nb[3][0]), u32(nb[3][1])) * 2 - i, j = H.bary(H.neighbour(p, 1)) - res["nowqm_ij"][p] = (u32(i), u32(j), 0xDEADBEEF, H.SENTINEL) - res["nowqm_masks"][p] = (lane[p], e & 0xFFFFFFFF, e >> 32, e & 0xFFFFFFFF) - res["helper_export"][p] = (0x3F800000,) * 4 - if helper_export: - outside = next(p for p in lane if p not in cov) - res["helper_export"][outside] = (0x3F800000,) * 4 - return res - - -class Analysis(unittest.TestCase): - def failing(self, res): - return [n for n, ok, _d in H.analyze(res) if not ok] - - def test_the_measured_behaviour_passes_every_check(self): - checks = H.analyze(model()) - self.assertEqual([n for n, ok, _d in checks if not ok], []) - self.assertEqual(len(checks), 10) - - def test_each_rule_broken_fails_its_check(self): - for flag, check in (("helpers_at_entry", "entry EXEC"), ("empty_quads", "quads packed"), - ("swap_lanes", "lane % 4"), ("helper_export", "an exp"), - ("flat_helpers", "after s_wqm a helper")): - with self.subTest(flag=flag): - failing = self.failing(model(**{flag: True})) - self.assertTrue(any(n.startswith(check) for n in failing), failing) - - def test_full_coverage_has_no_helpers_to_measure(self): - res = model() - for p in res["masks"]: - if res["masks"][p] == H.CLEAR: - for name in H.PROGRAMS: - res[name][p] = res[name][next(iter(q for q in res["masks"] if res["masks"][q] != H.CLEAR))] - self.assertIn("partial quads at the edge", self.failing(res)) - - def test_geometry(self): - self.assertEqual(H.bary((0, 0)), H.bary((0, 0))) - i, j = H.bary((0, 0)) - self.assertTrue(0 < i < 0.1 and 0 < j < 0.1) - self.assertEqual([H.neighbour((4, 6), k) for k in (1, 2, 3)], [(5, 6), (4, 7), (5, 7)]) - self.assertEqual(H.ndc((0, 0)), (-1 + 1 / 16, -1 + 1 / 16)) - - -class Programs(unittest.TestCase): - def test_every_program_ends_and_exports_once(self): - for name in H.PROGRAMS: - with self.subTest(name=name): - lines = H.program(name) - self.assertEqual(lines[-1], "s_endpgm") - self.assertEqual(sum(ln.startswith("exp ") for ln in lines), 1) - self.assertEqual("s_wqm_b64 exec, exec" in lines, H.PROGRAMS[name][0]) - - -@unittest.skipUnless(os.environ.get("LEONIDA_PS_ORACLE_BUILD"), "set LEONIDA_PS_ORACLE_BUILD to a runtime build " - "and select an AMD GPU (LEONIDA_VK_DEVICE) to measure helper lanes on hardware") -class OnHardware(unittest.TestCase): - def test_helper_lanes_at_a_triangle_edge(self): - try: - _device, res = H.measure(os.environ["LEONIDA_PS_ORACLE_BUILD"]) - except H.ps_oracle.Unavailable as e: - self.skipTest(str(e)) - self.assertEqual([(n, d) for n, ok, d in H.analyze(res) if not ok], []) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/test_ps_interp_modes.py b/tests/test_ps_interp_modes.py deleted file mode 100644 index 37765082d..000000000 --- a/tests/test_ps_interp_modes.py +++ /dev/null @@ -1,410 +0,0 @@ -"""The PS interpolation-mode decoder reads PSV0 elements, ISG1 read masks, FSSM read methods -and classifies the single barycentric pair; malformed containers are refused. - -Covers tools/ps_interp_modes.py (SHADER-181). All containers here are synthetic: the PSV0 -layout is the one dxc writes (lib/DxilContainer/DxilPipelineStateValidation.cpp), the -interpolation-mode numbers are DXIL::InterpolationMode ("must match D3D_INTERPOLATION_MODE") -and the class names come from the SPI_PS_INPUT_ENA fields (Mesa gfx103.json). -""" -import contextlib -import errno -import io -import json -import os -import struct -import subprocess -import sys -import tempfile -import unittest -from unittest import mock - -ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) -TOOLS = os.path.join(ROOT, "tools") -TOOL = os.path.join(TOOLS, "ps_interp_modes.py") -sys.path.insert(0, TOOLS) - -import ps_interp_modes # noqa: E402 - - -def psv0(elements, inputs=None, strings=b"\0TEXCOORD\0", semidx=(0,), resources=0): - """Build a PSV0 chunk payload. elements are (row, cols, kind, ctype, mode) tuples.""" - if inputs is None: - inputs = len(elements) - heap = strings.ljust((len(strings) + 3) & ~3, b"\0") - body = b"".join(struct.pack(" (class, ENA bit), bit numbers from Mesa gfx103.json SPI_PS_INPUT_ENA - expect = {2: ("persp_center", 0x2), 3: ("persp_centroid", 0x4), 6: ("persp_sample", 0x1), - 4: ("linear_center", 0x20), 5: ("linear_centroid", 0x40), - 7: ("linear_sample", 0x10), 1: ("flat", 0)} - for mode, (cls, bit) in expect.items(): - self.assertEqual(ps_interp_modes.interp_class(0, mode), (cls, bit)) - self.assertEqual(ps_interp_modes.interp_class(3, 4), ("linear_center", 0x20)) - - def test_system_value_kinds_are_system_inputs(self): - self.assertEqual(ps_interp_modes.interp_class(13, 1), ("system", 0)) - self.assertEqual(ps_interp_modes.interp_class(12, 1), ("system", 0)) - - def test_unknown_mode_is_other(self): - self.assertEqual(ps_interp_modes.interp_class(0, 0), ("other", 0)) - self.assertEqual(ps_interp_modes.interp_class(0, 8), ("other", 0)) - - -class ReadMethodTest(unittest.TestCase): - def test_flag_bits_decode_to_read_methods(self): - self.assertEqual(ps_interp_modes.read_method(0x01), {"mov": True, "p1p2": False, - "param16": False, "f16_ops": False}) - self.assertEqual(ps_interp_modes.read_method(0x02), {"mov": False, "p1p2": True, - "param16": False, "f16_ops": False}) - self.assertEqual(ps_interp_modes.read_method(0x1A), {"mov": False, "p1p2": True, - "param16": True, "f16_ops": True}) - self.assertEqual(ps_interp_modes.read_method(0x09), {"mov": True, "p1p2": False, - "param16": True, "f16_ops": False}) - - -class DisasmFactsTest(unittest.TestCase): - def test_v_interp_lines_decode_to_kinds_and_ij(self): - text = ("\tv_interp_p1_f32_e32 v2, v0, attr2.x\n" - "\tv_interp_p2_f32_e32 v2, v1, attr2.x\n" - "\tv_interp_mov_f32 v5, p0, attr3.x\n" - "\tv_interp_p1ll_f16 v6, v0, attr1.x\n") - per, ij = ps_interp_modes.disasm_facts(text) - self.assertEqual(per, {2: {"p1p2"}, 3: {"mov"}, 1: {"f16"}}) - self.assertEqual(ij, {"v0", "v1"}) - - def test_mov_p0_is_not_an_ij_operand(self): - per, ij = ps_interp_modes.disasm_facts("\tv_interp_mov_f32 v5, p10, attr0.x\n") - self.assertEqual(per, {0: {"mov"}}) - self.assertEqual(ij, set()) - - -class PairClassTest(unittest.TestCase): - def rows(self, *specs): - return [{"kind": k, "mode": m, "rw": rw} for k, m, rw in specs] - - def test_perspective_generic_wins_the_pair(self): - rows = self.rows((3, 4, 0xF), (0, 2, 0xF)) - self.assertEqual(ps_interp_modes.pair_class(rows, [], {0: {"p1p2"}}, {"v0"}), "persp_center") - - def test_live_position_alone_interpolates_linear(self): - rows = self.rows((3, 4, 0xF), (0, 2, 0)) - self.assertEqual(ps_interp_modes.pair_class(rows, [], {0: {"p1p2"}}, {"v0"}), "linear_center") - - def test_mode5_position_is_linear_centroid(self): - rows = self.rows((3, 5, 0xF)) - self.assertEqual(ps_interp_modes.pair_class(rows, [], {0: {"p1p2"}}, {"v0"}), "linear_centroid") - - def test_position_plus_flat_row_stays_flat(self): - # a shader that reads SV_Position and a Constant row: the interpolation reads the - # flat row (P0 semantics, any pair) and the position comes from the system VGPRs - rows = self.rows((3, 5, 0xF), (0, 1, 0xF)) - self.assertEqual(ps_interp_modes.pair_class(rows, [], {1: {"p1p2"}}, {"v0"}), "flat_only") - - def test_constant_rows_only_is_flat(self): - rows = self.rows((0, 1, 0xF)) - self.assertEqual(ps_interp_modes.pair_class(rows, [], {0: {"p1p2"}}, {"v0"}), "flat_only") - - def test_no_interpolation_at_all(self): - self.assertEqual(ps_interp_modes.pair_class(self.rows((3, 4, 0xF)), [], {}, set()), "none") - - def test_raw_barycentric_read_without_v_interp(self): - self.assertEqual(ps_interp_modes.pair_class(self.rows(), [], {}, {"v0"}), "raw_bary") - - -class ShaderRowTest(unittest.TestCase): - def test_end_to_end_row_from_synthetic_container(self): - c = dxbc_container({ - b"PSV0": psv0([(0, 4, 3, 3, 4), (1, 4, 0, 3, 2)]), - b"ISG1": isg1([(0, 0xF, "SV_Position"), (1, 0xF, "TEXCOORD0")]), - }) - with tempfile.TemporaryDirectory() as tmp: - dx = os.path.join(tmp, "a.dxbc") - fs = os.path.join(tmp, "fssm", "a.fssm") - ds = os.path.join(tmp, "disasm", "a.s") - os.mkdir(os.path.join(tmp, "fssm")) - os.mkdir(os.path.join(tmp, "disasm")) - with open(dx, "wb") as f: f.write(c) - with open(fs, "wb") as f: f.write(fssm([(0, 0xF, 0x02), (1, 0xF, 0x02)])) - with open(ds, "w") as f: f.write("v_interp_p1_f32_e32 v2, v0, attr1.x\n") - row = ps_interp_modes.shader_row(dx, fs, ds) - self.assertEqual(row["pair_class"], "persp_center") - self.assertEqual([i["class"] for i in row["inputs"]], ["linear_center", "persp_center"]) - self.assertEqual([i["rw"] for i in row["inputs"]], [15, 15]) - self.assertEqual([t["p1p2"] for t in row["table"]], [True, True]) - self.assertEqual(row["usage"], {"1": ["p1p2"]}) - - def test_unparsable_psv0_returns_none(self): - with tempfile.TemporaryDirectory() as tmp: - dx = os.path.join(tmp, "b.dxbc") - with open(dx, "wb") as f: f.write(dxbc_container({b"PSV0": psv0([])[:20]})) - self.assertIsNone(ps_interp_modes.shader_row(dx, None, None)) - - def test_component_packed_same_row_preserves_each_element_rw_and_name(self): - # Two inputs packed into register row 1: TEXCOORD0.xy (start_col=0, cols=2, mask=0x3, rw=0x3, read) and - # TEXCOORD1.zw (start_col=2, cols=2, mask=0xC, rw=0x0, unread), with noff=0 in PSV0 so names come from ISG1. - elems = [ - struct.pack(" p1p2": 1}) - - -class CliTest(unittest.TestCase): - def test_directory_census_with_stage_index(self): - with tempfile.TemporaryDirectory() as tmp: - os.mkdir(os.path.join(tmp, "fssm")) - os.mkdir(os.path.join(tmp, "disasm")) - with open(os.path.join(tmp, "ps1.dxbc"), "wb") as f: - f.write(dxbc_container({b"PSV0": psv0([(0, 4, 0, 3, 2)]), - b"ISG1": isg1([(0, 0xF, "TEXCOORD0")])})) - with open(os.path.join(tmp, "fssm", "ps1.fssm"), "wb") as f: - f.write(fssm([(0, 0xF, 0x02)])) - with open(os.path.join(tmp, "disasm", "ps1.s"), "w") as f: - f.write("v_interp_p1_f32_e32 v2, v0, attr0.x\n") - with open(os.path.join(tmp, "vs1.dxbc"), "wb") as f: - f.write(dxbc_container({b"PSV0": psv0([(0, 4, 0, 3, 2)])})) - with open(os.path.join(tmp, "index.json"), "w") as f: - json.dump([{"name": "ps1", "file": "ps1.dxbc", "stage": "ps"}, - {"name": "vs1", "file": "vs1.dxbc", "stage": "vs"}], f) - out = subprocess.run([sys.executable, "-I", TOOL, tmp, "--json"], - capture_output=True, text=True, check=True) - doc = json.loads(out.stdout) - self.assertEqual(len(doc["files"]), 1) - self.assertEqual(doc["tally"]["pair_class"], {"persp_center": 1}) - self.assertEqual(doc["tally"]["mode_by_kind"], {"kind0 mode2": 1}) - - def write_two_shaders(self, tmp): - """Two synthetic PS containers; the census tallies them without FSSM/disasm sidecars.""" - for name in ("ps1", "ps2"): - with open(os.path.join(tmp, name + ".dxbc"), "wb") as f: - f.write(dxbc_container({b"PSV0": psv0([(0, 4, 0, 3, 2)]), - b"ISG1": isg1([(0, 0xF, "TEXCOORD0")])})) - - def test_limit_below_one_is_refused(self): - with tempfile.TemporaryDirectory() as tmp: - self.write_two_shaders(tmp) - for bad in ("0", "-1"): - with self.subTest(limit=bad): - p = subprocess.run([sys.executable, "-I", TOOL, tmp, "--json", "--limit", bad], - capture_output=True, text=True) - self.assertEqual(p.returncode, 2) - self.assertIn("must be at least 1", p.stderr) - self.assertEqual(p.stdout, "") - - def test_positive_limit_still_caps_the_census(self): - with tempfile.TemporaryDirectory() as tmp: - self.write_two_shaders(tmp) - p = subprocess.run([sys.executable, "-I", TOOL, tmp, "--json", "--limit", "1"], - capture_output=True, text=True, check=True) - self.assertEqual(len(json.loads(p.stdout)["files"]), 1) - - def test_directory_named_dxbc_is_skipped(self): - with tempfile.TemporaryDirectory() as tmp: - self.write_two_shaders(tmp) - os.mkdir(os.path.join(tmp, "bogus.dxbc")) - p = subprocess.run([sys.executable, "-I", TOOL, tmp, "--json"], - capture_output=True, text=True) - self.assertEqual(p.returncode, 0, p.stderr) - self.assertEqual(len(json.loads(p.stdout)["files"]), 2) - - def test_scan_io_failures_do_not_emit_a_partial_census(self): - with tempfile.TemporaryDirectory() as tmp: - self.write_two_shaders(tmp) - failing_path = os.path.join(tmp, "ps2.dxbc") - error = PermissionError(errno.EACCES, "permission denied", failing_path) - original = ps_interp_modes.shader_row - - def fail_second(path, fssm_path, disasm_path): - if path == failing_path: - raise error - return original(path, fssm_path, disasm_path) - - for target, options, path, diagnostic in ( - ("files_of", {"side_effect": OSError(errno.EIO, "I/O error", tmp)}, tmp, "cannot list"), - ("shader_row", {"side_effect": fail_second}, failing_path, "cannot read"), - ): - with self.subTest(target=target): - out, err = io.StringIO(), io.StringIO() - with mock.patch.object(ps_interp_modes, target, **options), contextlib.redirect_stdout(out), \ - contextlib.redirect_stderr(err): - self.assertEqual(ps_interp_modes.main([tmp, "--json"]), 2) - self.assertEqual(out.getvalue(), "") - self.assertEqual(len(err.getvalue().splitlines()), 1) - self.assertIn(diagnostic, err.getvalue()) - self.assertIn(path, err.getvalue()) - - def test_missing_path_is_an_error(self): - out = subprocess.run([sys.executable, "-I", TOOL, "Z:/nope"], - capture_output=True, text=True) - self.assertEqual(out.returncode, 2) - self.assertIn("does not exist", out.stderr) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/test_ps_oracle.py b/tests/test_ps_oracle.py deleted file mode 100644 index 0e5f29363..000000000 --- a/tests/test_ps_oracle.py +++ /dev/null @@ -1,349 +0,0 @@ -"""tools/ps_oracle.py: the msgpack subset, the PAL ELF rewrite that puts new pixel-shader code in a pipeline binary, -the binary file format, and (with LEONIDA_PS_ORACLE_BUILD set to a runtime build and an AMD GPU selected) a real -draw with patched code. Standard library only.""" -import os -import struct -import sys -import tempfile -import unittest -from unittest.mock import patch - -ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) -sys.path.insert(0, os.path.join(ROOT, "tools")) -import ps_oracle as P # noqa: E402 - -S_ENDPGM = struct.pack(" 41 VGPRs, rounded to the wave64 granule 4 - rsrc1 = struct.unpack_from("= min(10, size) for size, sampled in per.values())) - self.assertEqual(sum(sampled for _, sampled in per.values()), len(picked)) - - def test_fixed_seed_is_stable_and_seed_matters(self): - ps = {k: v for k, v in synthetic_index().items() if v["stage"] == "ps"} - first = ps_sweep.pick_sample(ps, 40, 7)[0] - self.assertEqual(first, ps_sweep.pick_sample(ps, 40, 7)[0]) - self.assertNotEqual(first, ps_sweep.pick_sample(ps, 40, 8)[0]) - - def test_sample_command_writes_numbers_only_to_stdout(self): - with tempfile.TemporaryDirectory() as tmp: - spirv, out = os.path.join(tmp, "spirv"), os.path.join(tmp, "out") - os.makedirs(spirv) - with open(os.path.join(spirv, "index.json"), "w", encoding="utf-8", newline="\n") as f: - json.dump(synthetic_index(), f) - buf = io.StringIO() - with contextlib.redirect_stdout(buf): - ps_sweep.main(["sample", "--spirv", spirv, "--out", out, "--n", "40"]) - self.assertNotIn("a1", buf.getvalue().replace("sampled", "")) - self.assertIn("population 133", buf.getvalue()) - with open(os.path.join(out, "sample.json"), encoding="utf-8") as f: - self.assertEqual(len(json.load(f)), int(buf.getvalue().split("sampled ")[1].split()[0])) - - -class VertexShader(unittest.TestCase): - def test_outputs_match_inputs_and_flat_locations(self): - glsl = ps_sweep.vs_glsl([0, 2, 5], {2}) - self.assertIn("layout(location=0) out vec4 o0;", glsl) - self.assertIn("layout(location=2) flat out vec4 o2;", glsl) - self.assertIn("layout(location=5) out vec4 o5;", glsl) - self.assertNotIn("o1", glsl) - self.assertIn("gl_VertexIndex", glsl) - - def test_no_inputs(self): - glsl = ps_sweep.vs_glsl([], set()) - self.assertNotIn("out vec4", glsl) - self.assertIn("gl_Position", glsl) - - def test_f16_halves_are_decoded_from_the_params_own_words(self): - # --f16-interp-fallback: the PS reads param 1's halves at locations 26 and 27 and the raw param itself is not an - # input, so a default translation would read param 1's words per vertex at location 1. - glsl = ps_sweep.vs_glsl([3, 26, 27], set(), {"1": [26, 27]}) - raw1 = ps_sweep._raw_glsl(1) - self.assertIn(f"vec4 r = {raw1};", glsl) - self.assertIn("o26 = vec4(unpackHalf2x16(w.x)[0], unpackHalf2x16(w.y)[0], unpackHalf2x16(w.z)[0], " - "unpackHalf2x16(w.w)[0]);", glsl) - self.assertIn("o27 = vec4(unpackHalf2x16(w.x)[1],", glsl) - self.assertIn(f"o3 = {ps_sweep._raw_glsl(3)};", glsl) - self.assertNotIn(f"o26 = {ps_sweep._raw_glsl(26)}", glsl) - self.assertNotIn("o1 =", glsl) - - def test_without_halves_the_text_is_unchanged(self): - self.assertEqual(ps_sweep.vs_glsl([0, 2], {2}), ps_sweep.vs_glsl([0, 2], {2}, {})) - self.assertNotIn("unpackHalf2x16", ps_sweep.vs_glsl([0, 2], {2}, None)) - - -class GeometryShaderLookup(unittest.TestCase): - def test_job_env_drops_inherited_per_job_variables(self): - base = {"PATH": "p", "VKS_GS": "stale.spv", "VKS_TEX": "1", "VKS_NEED_MAINTENANCE8": "1"} - env = ps_sweep.job_env(base, 9, "z", {}, None) - for k in ps_sweep.JOB_VARS: - self.assertNotIn(k, env) - self.assertEqual((env["PATH"], env["VKS_TIMEOUT_S"]), ("p", "9")) - env = ps_sweep.job_env(base, 9, "t", {"needs_maintenance8": True}, "g.spv") - self.assertEqual((env["VKS_GS"], env["VKS_TEX"], env["VKS_NEED_MAINTENANCE8"]), ("g.spv", "1", "1")) - - def test_gs_is_the_bary_gs_file_beside_the_pixel_shader(self): - with tempfile.TemporaryDirectory() as d: - self.assertIsNone(ps_sweep.gs_for(d, "x1")) - open(os.path.join(d, "x1.bary_gs.spv"), "wb").close() - self.assertEqual(ps_sweep.gs_for(d, "x1"), os.path.join(d, "x1.bary_gs.spv")) - self.assertIsNone(ps_sweep.gs_for(d, "x2")) - - -class Classification(unittest.TestCase): - def setUp(self): - self.tmp = tempfile.TemporaryDirectory() - self.addCleanup(self.tmp.cleanup) - - def raw(self, name, values): - path = os.path.join(self.tmp.name, name) - write_raw(path, values) - return path - - @staticmethod - def rec(code): - return {"i": 0, "code": code, "reason": "", "targets": 1} - - def classify(self, a, b): - return ps_sweep.classify_pair(self.rec(0), self.rec(0), self.raw("a", a), self.raw("b", b)) - - def test_ok_within_tolerance(self): - self.assertEqual(self.classify([0.5, 1.0, 2.0, -1.0], [0.5004, 1.0004, 2.0, -1.0]), ("OK on both", "")) - - def test_differs_beyond_tolerance_with_tier(self): - self.assertEqual(self.classify([0.5, 1.0], [0.5, 1.5]), ("differs beyond tolerance", "gross (>0.1)")) - self.assertEqual(self.classify([0.5, 1.0], [0.5, 1.05]), ("differs beyond tolerance", "moderate (>1e-2)")) - self.assertEqual(self.classify([0.5, 1.0], [0.5, 1.005]), ("differs beyond tolerance", "small (>1e-3)")) - - def test_nan_and_zero_on_one_side_only(self): - nan = float("nan") - self.assertEqual(self.classify([0.5, 1.0], [0.5, nan]), ("NaN or zero on one GPU only", "nan")) - self.assertEqual(self.classify([0.5, 1.0], [0.0, 0.0]), ("NaN or zero on one GPU only", "zero")) - self.assertEqual(self.classify([0.5, 1.0], [-1.0, -1.0]), ("NaN or zero on one GPU only", "unwritten")) - self.assertEqual(self.classify([nan, 1.0], [nan, 1.0]), ("OK on both", "")) # NaN on both is not a difference - - def test_non_finite_values_compare_per_component(self): - nan, inf = float("nan"), float("inf") - gross = ("differs beyond tolerance", "gross (>0.1)") - # NaN in different components of the two outputs - self.assertEqual(self.classify([nan, 1.0], [1.0, nan]), gross) - # an infinity against a finite value, and against the opposite infinity - self.assertEqual(self.classify([inf, 1.0], [1.0, 1.0]), gross) - self.assertEqual(self.classify([inf, 1.0], [-inf, 1.0]), gross) - # the same non-finite value at the same component matches - self.assertEqual(self.classify([inf, nan, 1.0], [inf, nan, 1.0]), ("OK on both", "")) - - def test_not_translated_is_its_own_class(self): - rec = {"code": ps_sweep.NOT_TRANSLATED, "reason": "not translated"} - ok = {"code": 0, "reason": ""} - self.assertEqual(ps_sweep.classify_pair(rec, ok, "x", "y"), ("not translated", "")) - self.assertEqual(ps_sweep.classify_pair(ok, rec, "x", "y"), ("not translated", "")) - - def test_failures_and_timeouts(self): - # A non-success code takes precedence; neither path should even be opened. - for a, b, expected in ((0, 77, ("fails on one GPU", "b: missing device feature")), - (4, 0, ("fails on one GPU", "a: exit 4")), - (77, 5, ("fails on both", "77/5")), - (3, 0, ("timeout", "")), (0, 3, ("timeout", ""))): - with self.subTest(a=a, b=b): - result = ps_sweep.classify_pair(self.rec(a), self.rec(b), self.tmp.name, self.tmp.name) - self.assertEqual(result, expected) - - -class CompareCommand(unittest.TestCase): - def test_readback_shapes(self): - one = struct.pack("0.1)"), - (1, 1, b"", b"", "invalid readback", "a: wrong output size"), - (1, 1, one[:-4], one[:-4], "invalid readback", "a: wrong output size"), - (1, 1, one, one[:-4], "invalid readback", "b: wrong output size"), - (1, 1, two, two, "invalid readback", "a: wrong output size"), - (1, 1, one, one + b"\x00", "invalid readback", "b: wrong output size"), - (2, 2, one, one, "invalid readback", "a: wrong output size"), - (1, 2, one, one, "invalid readback", "target counts differ"), - (None, 1, one, one, "invalid readback", "invalid target count"), - (0, 0, b"", b"", "invalid readback", "invalid target count"), - (9, 9, one * 9, one * 9, "invalid readback", "invalid target count"), - (1, True, one, one, "invalid readback", "invalid target count"), - (1, 1, one, None, "invalid readback", "b: missing output"), - ] - with tempfile.TemporaryDirectory() as tmp: - out = Path(tmp) - sample = [{"name": str(i), "stratum": [False, "none", "structured"]} for i in range(len(cases))] - (out / "sample.json").write_text(json.dumps(sample), encoding="utf-8", newline="\n") - for side, tag in enumerate(("a", "b")): - folder = out / f"{tag}_z" - folder.mkdir() - with (folder / "results_0.jsonl").open("w", encoding="utf-8", newline="\n") as f: - for i, case in enumerate(cases): - rec = {"i": i, "code": 0, "reason": ""} - if case[side] is not None: - rec["targets"] = case[side] - f.write(json.dumps(rec) + "\n") - data = case[2 + side] - if data is not None: - (folder / f"{i}.raw").write_bytes(data) - with contextlib.redirect_stdout(io.StringIO()): - ps_sweep.main(["compare", "--out", tmp]) - rows = json.loads((out / "classes_z.json").read_text(encoding="utf-8")) - self.assertEqual([(r["class"], r["sub"]) for r in rows], [case[-2:] for case in cases]) - - def test_rerun_overrides_and_counts(self): - with tempfile.TemporaryDirectory() as out: - with open(os.path.join(out, "sample.json"), "w", encoding="utf-8", newline="\n") as f: - json.dump([{"name": "x", "stratum": [False, "none", "structured"]}, - {"name": "y", "stratum": [False, "none", "structured"]}], f) - for tag, codes in (("a", (0, 3)), ("b", (0, 0))): - d = os.path.join(out, f"{tag}_z") - os.makedirs(d) - with open(os.path.join(d, "results_0.jsonl"), "w", encoding="utf-8", newline="\n") as f: - for i, c in enumerate(codes): - f.write(json.dumps({"i": i, "code": c, "reason": "", "targets": 1}) + "\n") - write_raw(os.path.join(d, "0.raw"), [0.25] * 8) - write_raw(os.path.join(d, "1.raw"), [0.25] * 8) - # shader 1 timed out on a while another process was starting: its re-run is clean - re = os.path.join(out, "a_z_re") - os.makedirs(re) - with open(os.path.join(re, "results_0.jsonl"), "w", encoding="utf-8", newline="\n") as f: - f.write(json.dumps({"i": 1, "code": 0, "reason": "", "targets": 1}) + "\n") - write_raw(os.path.join(re, "1.raw"), [0.25] * 8) - buf = io.StringIO() - with contextlib.redirect_stdout(buf): - ps_sweep.main(["compare", "--out", out, "--tags", "a", "b"]) - self.assertIn("OK on both: 2", buf.getvalue()) - self.assertNotIn("timeout", buf.getvalue()) - - def test_exact_readbacks_and_rerun(self): - from pathlib import Path - - with tempfile.TemporaryDirectory() as tmp: - out = Path(tmp) - clear = struct.pack("I", first + len(sections) + 16) + b"\0" * 4) - return b"PSIN" + struct.pack(">I", first) + rows + bytes(data) + sections - - -ROOT_T, ITEM_T, STR_T = joaat("RootThing"), joaat("ItemThing"), 0x10 -KIND = joaat("KindEnum") - -# RootThing (0x90 bytes): every container shape the decoder reads. -ROOT_MEMBERS = [ - (0x100, 0, 0x05, 0, 0, ITEM_T), # 0: element descriptor, ItemThing - (0x100, 0, 0x15, 0, 0, 0), # 1: element descriptor, u32 - (0x100, 0, 0x4A, 0, 0, 0), # 2: element descriptor, u32 hash (map key) - (joaat("items"), 0x00, 0x5C, 0, 0, 0), # {u32 count, u32 capacity, ptr} -> ItemThing[] - (joaat("values"), 0x10, 0x52, 0, 1, 0), # {ptr, u16 count, u16 capacity} -> u32[] - (joaat("sorted"), 0x20, 0x71, 0, 0, 2 | (1 << 16)), # binary map u32 hash -> u32 - (joaat("hashed"), 0x38, 0x75, 0, 0, 2 | (1 << 16)), # SwissTable u32 hash -> u32 - (joaat("open"), 0x48, 0x73, 0, 0, 2 | (1 << 16)), # open addressing u32 hash -> u32 - (joaat("child"), 0x58, 0x07, 0, 0, 0), # pointer to an ItemThing block - (joaat("label"), 0x60, 0x42, 0, 0, 0), # string pointer - (joaat("short"), 0x68, 0x44, 0, 0, 0), # 16-byte string, stored in place - (joaat("kind"), 0x78, 0x62, 0, 0, KIND), # 32-bit enum - (joaat("fixed"), 0x7C, 0x50, 0, 1, 3), # u32[3] in place - (joaat("odd"), 0x88, 0x77, 0, 0, 0), # a type this tool does not decode -] -SCHEMA = [ - (ROOT_T, 0x1, 0x90, 3, ROOT_MEMBERS), - (ITEM_T, 0x2, 0x8, 2, [(joaat("x"), 0, 0x21, 0, 0, 0), (joaat("n"), 4, 0x15, 0, 0, 0)]), -] -ENUMS = [(KIND, 0x3, [(0, joaat("KIND_A")), (1, joaat("KIND_B"))])] - - -def sample(kind=1): - """Blocks: 1 root, 2 ItemThing[2], 3 u32[3], 4 map pairs, 5 SwissTable group, 6 open slots, 7 one ItemThing, - 8 strings.""" - k1, k2 = joaat("alpha"), joaat("beta") - lo, hi = sorted((k1, k2)) - root = bytearray(0x90) - struct.pack_into("I", blob, 4)[0] - blocks, fills = D.block_table(blob, first) - self.assertTrue(fills) - self.assertEqual([(t, s) for t, _, s in blocks], [(0x15, 4), (0x16, 17)]) - self.assertEqual(blocks[0][1] % 16, 0) - self.assertEqual(blocks[1][1], blocks[0][1] + 16) - - def test_missing_end_row(self): - blob = make_container([(0x15, b"\0" * 4)], [], end_row=False) - with self.assertRaisesRegex(ValueError, "fill|padding"): - D.block_table(blob, struct.unpack_from(">I", blob, 4)[0]) - - def test_bad_fill(self): - blob = make_container([(0x15, b"\0" * 4)], [], fill=b"\0" * 8) - with self.assertRaisesRegex(ValueError, "fill"): - D.block_table(blob, struct.unpack_from(">I", blob, 4)[0]) - - def test_blocks_past_the_region_are_rejected(self): - # A damaged size must not make the walker allocate gigabytes (review on #1077). - blob = bytearray(make_container([(0x15, b"\0" * 4), (0x16, b"\0" * 32)], [])) - struct.pack_into("I", blob, 4)[0]) - stats = __import__("collections").Counter() - self.assertFalse(D.measure(bytes(blob), stats)) - self.assertEqual(stats["containers"], 0) - - def test_first_row_is_what_psin_index_calls_version(self): - blob = make_container([(0x16, b"\0" * 0x230)], []) - record = D.psin_index.parse(blob) - self.assertEqual((record["version"], record["table_bytes"]), (0x16, 0x230)) - - -class TestWalk(unittest.TestCase): - def setUp(self): - self.container = D.Container(sample()) - self.stats = __import__("collections").Counter() - self.tree = D.Walker(self.container, self.stats, keep=True).run() - - def test_every_byte_is_reached(self): - self.assertEqual(self.stats["bytes reached"], self.stats["bytes"]) - self.assertEqual(self.stats["blocks reached"], 8) - - def test_arrays(self): - self.assertEqual(self.tree[f"{joaat('items'):08x}"], - [{f"{joaat('x'):08x}": 1.5, f"{joaat('n'):08x}": 10}, - {f"{joaat('x'):08x}": 2.5, f"{joaat('n'):08x}": 20}]) - self.assertEqual(self.tree[f"{joaat('values'):08x}"], [1, 2, 3]) - self.assertEqual(self.tree[f"{joaat('fixed'):08x}"], [7, 8, 9]) - self.assertEqual(self.stats["array 5c block type matches element"], 1) - self.assertEqual(self.stats["array 52 block type matches element"], 1) - - def test_maps(self): - lo, hi = sorted((joaat("alpha"), joaat("beta"))) - self.assertEqual(self.tree[f"{joaat('sorted'):08x}"], [[f"{lo:08x}", 100], [f"{hi:08x}", 200]]) - self.assertEqual(sorted(v for _, v in self.tree[f"{joaat('hashed'):08x}"]), [11, 22]) - self.assertEqual(self.tree[f"{joaat('open'):08x}"], [[f"{joaat('alpha'):08x}", 33]]) - for check in ("map 71 first word 1", "map 71 keys ascending", "map 75 used slots == count", - "map 75 groups a power of two", "map 73 used slots == count"): - self.assertEqual(self.stats[check], 1, check) - - def test_pointers_and_strings(self): - self.assertEqual(self.tree[f"{joaat('child'):08x}"], {f"{joaat('x'):08x}": 3.5, f"{joaat('n'):08x}": 30}) - self.assertEqual(self.tree[f"{joaat('label'):08x}"], "hello") - self.assertEqual(self.tree[f"{joaat('short'):08x}"], "abc") - self.assertEqual(self.stats["short strings in place"], 1) - - def test_struct_pointer_past_block_end_is_rejected(self): - # ItemThing is 8 bytes; pointing at offset 6 of an 8-byte block leaves only 2 bytes inside the block. - root = bytearray(0x90) - struct.pack_into("= 2**31 for 0x62 enums. - for listed, stored in ((-1, -1), (0xFFFFFFF0, -16)): - c = D.Container(sample(kind=stored)) - c.enums[KIND]["values"].append({"value": listed, "name": joaat("KIND_X")}) - stats = __import__("collections").Counter() - tree = D.Walker(c, stats, keep=True).run() - self.assertEqual(stats["enum value listed"], 1) - self.assertEqual(stats["enum value not listed"], 0) - self.assertEqual(tree[f"{joaat('kind'):08x}"], listed) - - def test_bad_pointer_is_counted_not_followed(self): - blob = bytearray(sample()) - root_at = D.Container(bytes(blob)).blocks[0][1] - struct.pack_into("I", 16) + b"\x70" * 8 + make_section("CHKS", b"\0" * 8) - self.assertFalse(D.measure(blob, stats)) - self.assertEqual(stats["skipped: no LSCH or LRSC section"], 1) - - def test_root_out_of_range(self): - blob = make_container([(ROOT_T, b"\0" * 0x90)], SCHEMA, ENUMS, root=3) - stats = __import__("collections").Counter() - self.assertTrue(D.measure(blob, stats)) - self.assertEqual(stats["root out of range"], 1) - - def test_inline_and_fixed_arrays_are_bounded_to_enclosing_block(self): - # 16-byte block with 0x54 inline array of char[4] claiming count=capacity=50000: - # must be rejected as out of bounds rather than performing 50,000 OOB reads. - inline_schema = [(0xAAAA0002, 0, 16, 2, [ - (0x22222222, 0, 0x54, 0, 1, 0), - (0x00000100, 0, 0x40, 0, 0, 4), - ])] - blob = make_container([(0xAAAA0002, struct.pack(" 16). - fixed_schema = [(0xAAAA0003, 0, 16, 2, [ - (0x33333333, 0, 0x50, 0, 1, 100), - (0x00000100, 0, 0x40, 0, 0, 4), - ])] - blob2 = make_container([(0xAAAA0003, bytes(16))], fixed_schema, []) - stats2 = __import__("collections").Counter() - self.assertTrue(D.measure(blob2, stats2)) - self.assertEqual(stats2["fixed array out of bounds"], 1) - self.assertEqual(stats2["char arrays"], 0) - - def test_map_75_zero_groups_is_not_power_of_two(self): - map_schema = [(0xAAAA0001, 0, 16, 2, [ - (0x11111111, 0, 0x75, 0, 0, (2 << 16) | 1), - (0x00000100, 0, 0x15, 0, 0, 0), - (0x00000100, 0, 0x15, 0, 0, 0), - ])] - blob = make_container([(0xAAAA0001, struct.pack(" past 16 - (joaat("arr"), 8, 0x5C, 0, 0, 0), # 16-byte header at +8 -> past 16 - (joaat("smap"), 4, 0x71, 0, 0, 0 | (0 << 16)), # 20-byte header at +4 -> past 16 - (joaat("inline"), 12, 0x54, 0, 0, 0), # 8-byte header at +12 -> past 16 - ])] - blob = make_container([(0xAAAA0014, bytes(16))], schema, []) - stats = __import__("collections").Counter() - self.assertTrue(D.measure(blob, stats)) - self.assertEqual(stats["walk error"], 0) - self.assertEqual(stats["member past block end"], 3) - self.assertEqual(stats["inline array out of bounds"], 1) - - def test_short_string_length_mismatch_and_oob_slot(self): - # Length byte claims 64 bytes in a 16-byte short-string slot: must return None, not read into LSCH. - schema = [(0xAAAA0015, 1, 16, 2, [(joaat("short"), 0, 0x44, 0, 0, 0)])] - payload = bytearray(b"A" * 15 + bytes([0x80 | 64])) - blob = make_container([(0xAAAA0015, bytes(payload))], schema, []) - stats = __import__("collections").Counter() - tree = D.Walker(D.Container(blob), stats, keep=True).run() - self.assertEqual(tree, {f"{joaat('short'):08x}": None}) - self.assertEqual(stats["short string length mismatch"], 1) - self.assertEqual(stats["short strings in place"], 0) - - # Short-string slot starting at +8 in a 16-byte block extends past the block end. - oob_schema = [(0xAAAA0016, 1, 16, 2, [(joaat("short"), 8, 0x44, 0, 0, 0)])] - blob2 = make_container([(0xAAAA0016, bytes(16))], oob_schema, []) - stats2 = __import__("collections").Counter() - tree2 = D.Walker(D.Container(blob2), stats2, keep=True).run() - self.assertEqual(tree2, {f"{joaat('short'):08x}": None}) - self.assertEqual(stats2["member past block end"], 1) - - -class TestCli(unittest.TestCase): - def run_tool(self, *args): - return subprocess.run([sys.executable, "-I", TOOL, *args], capture_output=True, text=True) - - def test_counts_on_a_folder(self): - with tempfile.TemporaryDirectory() as tmp: - with open(os.path.join(tmp, "000000001000.bin"), "wb") as f: - f.write(sample()) - with open(os.path.join(tmp, "000000002000.bin"), "wb") as f: - f.write(b"\x78\xda not psin") - r = self.run_tool(tmp, "--json") - self.assertEqual(r.returncode, 0, r.stderr) - got = json.loads(r.stdout) - self.assertEqual((got["PSIN files"], got["containers"], got["containers fully reached"]), (1, 1, 1)) - self.assertEqual(got["bytes reached"], got["bytes"]) - - def test_dump_prints_the_tree(self): - with tempfile.TemporaryDirectory() as tmp: - path = os.path.join(tmp, "one.bin") - with open(path, "wb") as f: - f.write(sample()) - r = self.run_tool(path, "--dump") - self.assertEqual(r.returncode, 0, r.stderr) - tree = json.loads(r.stdout)[f"{ROOT_T:08x}"] - self.assertEqual(tree[f"{joaat('label'):08x}"], "hello") - self.assertEqual(self.run_tool(tmp, "--dump").returncode, 2) - - def test_missing_source_is_one_line(self): - r = self.run_tool(os.path.join(tempfile.gettempdir(), "no-such-psin-folder")) - self.assertEqual(r.returncode, 2) - self.assertEqual(len(r.stderr.strip().splitlines()), 1) - - def test_dump_of_a_bad_container_is_one_line(self): - with tempfile.TemporaryDirectory() as tmp: - path = os.path.join(tmp, "bad.bin") - with open(path, "wb") as f: - f.write(sample()[:-5]) - r = self.run_tool(path, "--dump") - self.assertEqual(r.returncode, 2) - self.assertIn("incomplete", r.stderr) - - def test_a_single_file_without_the_magic_is_refused(self): - with tempfile.TemporaryDirectory() as tmp: - path = os.path.join(tmp, "not-psin.bin") - with open(path, "wb") as f: - f.write(b"\x78\xda not psin") - r = self.run_tool(path, "--json") - self.assertEqual(r.returncode, 2) - self.assertEqual(r.stdout, "") - self.assertEqual(len(r.stderr.strip().splitlines()), 1) - self.assertIn("not a PSIN container", r.stderr) - - def test_a_folder_still_skips_a_file_without_the_magic(self): - # the negative control: the same bytes inside a folder are skipped, not refused - with tempfile.TemporaryDirectory() as tmp: - with open(os.path.join(tmp, "000000003000.bin"), "wb") as f: - f.write(b"\x78\xda not psin") - r = self.run_tool(tmp, "--json") - self.assertEqual(r.returncode, 0, r.stderr) - self.assertEqual(json.loads(r.stdout), {}) - - def test_dump_missing_file_returns_2(self): - with tempfile.TemporaryDirectory() as tmp: - missing = os.path.join(tmp, "missing.bin") - r = self.run_tool(missing, "--dump") - self.assertEqual(r.returncode, 2) - self.assertIn("ERROR:", r.stderr) - self.assertEqual(len(r.stderr.strip().splitlines()), 1) - - def test_dump_oserror_returns_2_without_traceback(self): - import io - import unittest.mock - from contextlib import redirect_stderr - - with tempfile.TemporaryDirectory() as tmp: - path = os.path.join(tmp, "locked.bin") - with open(path, "wb") as f: - f.write(sample()) - err = io.StringIO() - with unittest.mock.patch.object(sys, "argv", ["psin_data.py", path, "--dump"]), \ - unittest.mock.patch("builtins.open", side_effect=OSError("I/O error")), \ - redirect_stderr(err): - rc = D.main() - self.assertEqual(rc, 2) - self.assertIn("ERROR:", err.getvalue()) - self.assertIn("I/O error", err.getvalue()) - self.assertNotIn("Traceback", err.getvalue()) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/test_psin_index.py b/tests/test_psin_index.py deleted file mode 100644 index eb9786dab..000000000 --- a/tests/test_psin_index.py +++ /dev/null @@ -1,420 +0,0 @@ -"""Synthetic tests for tools/psin_index.py (no game data).""" -import json -import os -import struct -import subprocess -import sys -import tempfile -import unittest -import unittest.mock - -ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) -TOOL = os.path.join(ROOT, "tools", "psin_index.py") -sys.path.insert(0, os.path.join(ROOT, "tools")) - -import psin_index as P # noqa: E402 - - -def make_section(tag, payload=b""): - size = 8 + len(payload) - return tag.encode("latin-1") + struct.pack(">I", size) + payload - - -def make_psin(sections, version=22, table_bytes=0, first=None): - body = b"".join(make_section(tag, payload) for tag, payload in sections) - first = 16 if first is None else first - header = bytearray(max(first, 16)) - header[0:4] = b"PSIN" - struct.pack_into(">I", header, 4, first) - struct.pack_into("I", 5392) + b"\x99\xfe\x66\x9f"), - ]) - got = P.parse(blob) - self.assertTrue(got["complete"]) - self.assertEqual(got["rsc_version"], 122) - self.assertEqual(got["sections"][0]["rsc_magic"], "0DRP") - self.assertEqual(got["checksum_size"], 5392) - self.assertEqual(got["checksum"], "99fe669f") - - def test_not_psin(self): - self.assertIsNone(P.parse(b"NOPE" + b"\x00" * 20)) - - def test_first_section_outside_file(self): - blob = make_psin([("LSCH", b"")], first=16) - blob = blob[:4] + struct.pack(">I", 9999) + blob[8:] - got = P.parse(blob) - self.assertFalse(got["complete"]) - self.assertIn("outside", got["error"]) - - def test_first_section_must_exist(self): - for padding in (0, 1, 7): - with self.subTest(padding=padding): - blob = make_psin([], first=32, table_bytes=16) + b"\0" * padding - got = P.parse(blob) - self.assertFalse(got["complete"]) - self.assertEqual(got["sections"], []) - self.assertIn("first section header", got["error"]) - - def test_empty_first_section_payload_is_valid(self): - got = P.parse(make_psin([("LSCH", b"")], first=32, table_bytes=16)) - self.assertTrue(got["complete"]) - self.assertEqual(got["sections"][0]["size"], 8) - - def test_truncated_section(self): - blob = make_psin([("LSCH", b"\x00" * 8)]) - got = P.parse(blob[:-2]) - self.assertFalse(got["complete"]) - - def test_zero_size_section(self): - blob = make_psin([("LSCH", b"")]) - blob = blob[:20] + struct.pack(">I", 0) + blob[24:] - got = P.parse(blob) - self.assertFalse(got["complete"]) - self.assertIn("size 0", got["error"]) - - def test_trailing_bytes(self): - blob = make_psin([("LSCH", b"")]) + b"junk" - got = P.parse(blob) - self.assertFalse(got["complete"]) - self.assertIn("ended at", got["error"]) - - -def make_lsch(structs): - """structs: [(hash, signature, size, align_log2, [(hash, offset, type, sub, index, ref), ...]), ...]""" - heads = b"".join(struct.pack("> 6 - h = (h + (h << 3)) & 0xFFFFFFFF - h ^= h >> 11 - return (h + (h << 15)) & 0xFFFFFFFF - - -SCHEMA = [ - (joaat("Outer"), 0x11111111, 0x20, 3, [ - (0x100, 0, 5, 0, 0, joaat("Inner")), # element descriptor of the array below - (joaat("items"), 0x00, 0x5C, 0, 0, 0), # array of Inner, element at index 0 - (joaat("kind"), 0x10, 0x62, 0, 0, joaat("Kind")), - (joaat("scale"), 0x14, 0x21, 0, 0, 0), - ]), - (joaat("Inner"), 0x22222222, 0x8, 2, [ - (joaat("a"), 0, 0x21, 0, 0, 0), - (joaat("b"), 4, 0x21, 0, 0, 0), - ]), -] -ENUMS = [ - (joaat("Kind"), 0x33333333, [(0, joaat("KIND_A")), (1, joaat("KIND_B")), (-1, joaat("KIND_NONE"))]), - (joaat("Flags"), 0x44444444, [(1, joaat("F_ONE")), (4, joaat("F_FOUR"))]), -] - - -def make_lsns(blocks): - """An LSNS payload: block count, (kind, bytes) table, then the blocks (filler records).""" - table = struct.pack("I", 9999) + good[8:], # first section past EOF - "00000002.bin": make_psin([], first=32, table_bytes=16), # no first section header - "00000003.bin": good[:-4], # LENM cut short - "00000004.bin": good, - } - with tempfile.TemporaryDirectory() as tmp: - for name, blob in cases.items(): - with open(os.path.join(tmp, name), "wb") as f: - f.write(blob) - p = subprocess.run([sys.executable, "-I", TOOL, tmp, "--json", "--schema"], - capture_output=True, text=True) - self.assertEqual(p.returncode, 0, p.stderr) - files = {r["file"]: r for r in json.loads(p.stdout)["files"]} - self.assertEqual(len(files), 4) - for r in files.values(): # one shape for every record - self.assertEqual(set(r["schema"]), {"structs", "enums", "lsch", "lenm", "reason"}) - first = files["00000001.bin"]["schema"] - self.assertEqual((first["structs"], first["enums"], first["lsch"], first["lenm"]), ([], [], False, False)) - self.assertIn("outside the file", first["reason"]) - self.assertIn("first section header", files["00000002.bin"]["schema"]["reason"]) - cut = files["00000003.bin"]["schema"] - self.assertTrue(cut["lsch"]) - self.assertFalse(cut["lenm"]) - self.assertEqual(len(cut["structs"]), 2) - self.assertIn("no whole LENM section", cut["reason"]) - self.assertEqual(files["00000004.bin"]["schema"]["reason"], "") - t = subprocess.run([sys.executable, "-I", TOOL, tmp, "--schema"], capture_output=True, text=True) - self.assertEqual(t.returncode, 0, t.stderr) - self.assertNotIn("Traceback", t.stderr) - self.assertIn("schema: no whole LSCH section", t.stdout) - - def test_schema_reason_for_missing_and_bad_sections(self): - got = P.parse(make_psin([("LGID", b"")]), schema=True)["schema"] - self.assertEqual(got["reason"], "no LSCH section; no LENM section") - got = P.parse(make_psin([("LSCH", b"\x01\x02\x03"), ("LENM", b"")]), schema=True)["schema"] - self.assertFalse(got["lsch"]) - self.assertTrue(got["lenm"]) - self.assertIn("LSCH: no struct count", got["reason"]) - - def test_json_schema(self): - with tempfile.TemporaryDirectory() as tmp: - with open(os.path.join(tmp, "00000001.bin"), "wb") as f: - f.write(make_psin([("LSCH", make_lsch(SCHEMA)), ("LENM", make_lenm(ENUMS))])) - p = subprocess.run([sys.executable, "-I", TOOL, tmp, "--json", "--schema"], - capture_output=True, text=True) - self.assertEqual(p.returncode, 0, p.stderr) - doc = json.loads(p.stdout) - s = doc["summary"] - self.assertEqual((s["lsch_decoded"], s["lenm_decoded"], s["structs"], s["members"], - s["enums"], s["enum_values"], s["schema_errors"]), (1, 1, 2, 6, 2, 5, 0)) - self.assertEqual(len(doc["files"][0]["schema"]["structs"][0]["members"]), 4) - t = subprocess.run([sys.executable, "-I", TOOL, tmp, "--schema"], capture_output=True, text=True) - self.assertEqual(t.returncode, 0, t.stderr) - self.assertIn(f"struct {joaat('Outer'):08x}", t.stdout) - self.assertIn("structs=2 members=6", t.stdout) - - - def test_json_directory(self): - with tempfile.TemporaryDirectory() as tmp: - good = make_psin([("LSCH", b""), ("CHKS", b"\x00" * 4)]) - with open(os.path.join(tmp, "00000001.bin"), "wb") as f: - f.write(good) - with open(os.path.join(tmp, "00000002.bin"), "wb") as f: - f.write(b"not a psin") - with open(os.path.join(tmp, "00000003.bin"), "wb") as f: - f.write(make_psin([])) - p = subprocess.run([sys.executable, "-I", TOOL, tmp, "--json"], - capture_output=True, text=True) - self.assertEqual(p.returncode, 0, p.stderr) - doc = json.loads(p.stdout) - self.assertEqual(doc["summary"]["files"], 2) - self.assertEqual(doc["summary"]["complete"], 1) - self.assertEqual(doc["summary"]["incomplete"], 1) - self.assertEqual(doc["summary"]["section_tags"], {"CHKS": 1, "LSCH": 1}) - - def test_limit_below_one_is_refused(self): - with tempfile.TemporaryDirectory() as tmp: - path = os.path.join(tmp, "00000001.bin") - with open(path, "wb") as f: - f.write(make_psin([("LSCH", b"")])) - for value in ("0", "-1"): - p = subprocess.run([sys.executable, "-I", TOOL, tmp, "--limit", value], - capture_output=True, text=True) - self.assertEqual(p.returncode, 2) - self.assertIn("must be at least 1", p.stderr) - - def test_missing_source_is_one_line(self): - with tempfile.TemporaryDirectory() as tmp: - for missing in (os.path.join(tmp, "nope"), os.path.join(tmp, "nope.bin")): - p = subprocess.run([sys.executable, "-I", TOOL, missing, "--json"], - capture_output=True, text=True) - self.assertEqual(p.returncode, 2, p.stderr) - self.assertNotIn("Traceback", p.stderr) - self.assertIn(missing, p.stderr) - self.assertEqual(p.stdout, "") - - def test_unlistable_folder_is_one_line(self): - with tempfile.TemporaryDirectory() as tmp: - # A folder that cannot be listed (no permission); patched so the test runs the same on every OS. - with unittest.mock.patch("os.listdir", side_effect=PermissionError(13, "Permission denied")): - code, err = run_main([tmp]) - self.assertEqual(code, 2) - self.assertIn("Permission denied", err) - - -def run_main(argv): - import io - from contextlib import redirect_stderr, redirect_stdout - err = io.StringIO() - with unittest.mock.patch.object(sys, "argv", ["psin_index.py", *argv]), \ - redirect_stdout(io.StringIO()), redirect_stderr(err): - code = P.main() - return code, err.getvalue() - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/test_psin_names.py b/tests/test_psin_names.py deleted file mode 100644 index 17bb9dcb1..000000000 --- a/tests/test_psin_names.py +++ /dev/null @@ -1,337 +0,0 @@ -"""Synthetic tests for tools/psin_names.py (no game data: every name and hash is invented).""" -import json -import os -import struct -import subprocess -import sys -import tempfile -import unittest - -ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) -TOOL = os.path.join(ROOT, "tools", "psin_names.py") -sys.path.insert(0, os.path.join(ROOT, "tools")) -sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) - -import psin_names as N # noqa: E402 -from test_psin_data import make_container, ptr # noqa: E402 -from test_psin_index import joaat # noqa: E402 - - -def mm64(name): - return N.murmur3_x64_128(name.encode())[0] - - -ROOT_T = joaat("PropSet") -MODEL, KEY, MODELS, OTHER = joaat("model"), joaat("key"), joaat("models"), joaat("other") -MEMBERS = [ - (0x100, 0, 0x4A, 0, 0, 0), # 0: element descriptor, u32 hash - (MODEL, 0x00, 0x4A, 0, 0, 0), # u32 name hash - (OTHER, 0x04, 0x4D, 0, 0, 0), # u32 hash that is not a listed name - (KEY, 0x08, 0x4F, 0, 0, 0), # u64 name key - (MODELS, 0x10, 0x5C, 0, 0, 0), # {u32 count, u32 capacity, ptr} -> u32 hash[] -] -SCHEMA = [(ROOT_T, 0x3, 0x20, 1, MEMBERS)] -NAMES = ["prop_crate_01", "prop_barrel_02", "Prop_Lamp_03"] - - -def sample(model="prop_crate_01", key="prop_crate_01", models=("prop_barrel_02", "prop_lamp_03"), other=0x12345678): - root = bytearray(0x20) - struct.pack_into(" bytes: - return tag.encode("ascii") + struct.pack(">I", 8 + len(payload)) + payload - - -def build_synthetic_psch_psin(*, bad_array_desc: bool = False, bad_pmap_size: bool = False, - with_stdn: bool = True) -> bytes: - """Build a synthetic complete PMAP/PSCH/PSIG/STNS PSIN container.""" - # Blocks at +0x10: - # block 1: struct 0x11111111, byte size 32 - # block 2: anonymous scalar block type 0x1, length 16 - b1_len = 36 if bad_pmap_size else 32 - b2_len = 16 - data_area = bytearray(16 + b1_len + b2_len) - data_area[0:4] = b"PSIN" - struct.pack_into(">I", data_area, 4, len(data_area)) # first_section - data_area[8:16] = b"pppppppp" - - # PMAP - pmap_pay = struct.pack(">IHHH6s", 1, 0, 0, 2, b"pppppp") - pmap_pay += struct.pack(">4I", 0x11111111, 16, 0, b1_len) - pmap_pay += struct.pack(">4I", 0x00000001, 16 + b1_len, 0, b2_len) - - # PSCH (3 entries: Outer 0x11111111, Inner 0x22222222, Kind 0x33333333) - outer_members = [ - (0x100, 0x0C, 0, 0, 0x22222222), # [0] array elem descriptor (Inner) - (0xAA01, 0x0D, 10, 0, 9 if bad_array_desc else 0), # [1] array pointing to [0] - (0xAA02, 0x0E, 1, 16, 0x33333333), # [2] enum Kind - (0x100, 0x0B, 0, 0, 0), # [3] map val elem descriptor - (0x100, 0x07, 0, 0, 0), # [4] map key elem descriptor - (0xAA03, 0x10, 1, 20, (3 << 16) | 4), # [5] map (key=[4], val=[3]) - ] - inner_members = [(0xBB01, 0x07, 0, 0, 0)] - enum_values = [(0xCC01, 0, 1), (0xCC02, 0, -2)] - - e0 = struct.pack(">BBHII", 0, 12, len(outer_members), 32, 0) + b"".join( - struct.pack(">IBBHI", *m) for m in outer_members - ) - e1 = struct.pack(">BBHII", 0, 12, len(inner_members), 16, 0) + b"".join( - struct.pack(">IBBHI", *m) for m in inner_members - ) - e2 = struct.pack(">BBH", 1, 0, len(enum_values)) + b"".join( - struct.pack(">IIq", *v) for v in enum_values - ) - - dir_end = 12 + 3 * 8 - o0 = dir_end - o1 = o0 + len(e0) - o2 = o1 + len(e1) - psch_pay = ( - struct.pack(">I", 3) - + struct.pack(">II", 0x11111111, o0) - + struct.pack(">II", 0x22222222, o1) - + struct.pack(">II", 0x33333333, o2) - + e0 + e1 + e2 - ) - psig_pay = struct.pack(">3I", 0x01020304, 0x05060708, 0x090A0B0C) - stns_rec = bytes(range(16)) - stns_pay = struct.pack("<3I", 1, 0x101, 16) + stns_rec + b"\x00\x00\x00\x00" - - sections = [ - _sec("PMAP", pmap_pay), - _sec("PSCH", psch_pay), - _sec("PSIG", psig_pay), - ] - if with_stdn: - sections.append(_sec("STDN", stns_rec)) - sections.append(_sec("STNS", stns_pay)) - total = len(data_area) + sum(len(s) for s in sections) + 20 - sections.append(_sec("CHKS", struct.pack(">II", total, 0xCAFEBABE) + b"zppp")) - return bytes(data_area) + b"".join(sections) - - -class PsinPschTests(unittest.TestCase): - def test_parse_validates_pmap_psch_psig_stns_and_cross_checks(self): - blob = build_synthetic_psch_psin() - self.assertTrue(psin_psch.is_psch_container(blob)) - rep = psin_psch.parse_psch_container(blob) - self.assertTrue(rep["valid"], rep["errors"]) - self.assertEqual(rep["pmap_blocks"], 2) - self.assertEqual(rep["pmap_struct_blocks"], 1) - self.assertEqual(rep["pmap_anon_kinds"], {"0x1": 1}) - self.assertTrue(rep["pmap_exact_end"]) - self.assertEqual((rep["structs"], rep["members"], rep["enums"], rep["enum_values"]), (2, 7, 1, 2)) - self.assertEqual(rep["psig_count"], 3) - self.assertEqual((rep["stns_blocks"], rep["stns_records"], rep["stns_tail_pad"]), (1, 1, 4)) - self.assertTrue(rep["stdn_match"]) - - # Empty (count=0) or 2-block STNS sections pad to a 16-byte boundary with 12 zero bytes. - stns_zero = psin_psch.decode_stns(struct.pack("I", lsch_psin, 4, 16) - lsch_blob = bytes(lsch_psin) + _sec("LSCH", b"") + _sec("LENM", b"") + _sec("CHKS", b"\x00" * 12) - psch_blob = build_synthetic_psch_psin(with_stdn=False) - - rows = [] - for off, data in ((0x1000, lsch_blob), (0x2000, psch_blob)): - with open(os.path.join(carve, f"{off:012x}.bin"), "wb") as f: - f.write(data) - rows.append({"off": off, "stored": len(data), "size": len(data), "head": data[:16].hex()}) - with open(os.path.join(carve, "index.json"), "w", encoding="utf-8", newline="\n") as f: - json.dump({"summary": {"archive": "synthetic", "files": len(rows)}, "files": rows}, f) - - out_json = os.path.join(tmp, "out", "psch.json") - p = subprocess.run([sys.executable, "-I", TOOL, carve, "--json", out_json], - capture_output=True, text=True, encoding="utf-8", errors="replace") - self.assertEqual(p.returncode, 0, p.stdout + p.stderr) - with open(out_json, "rb") as f: - raw = f.read() - self.assertIn(b"\n", raw) - self.assertNotIn(b"\r\n", raw) - rep = json.loads(raw.decode("utf-8")) - self.assertEqual(rep["containers"], 1) - self.assertEqual(rep["valid_containers"], 1) - - # Collision refusal - p2 = subprocess.run([sys.executable, "-I", TOOL, carve, "--json", os.path.join(carve, "00002000".rjust(12, "0") + ".bin")], - capture_output=True, text=True, encoding="utf-8", errors="replace") - self.assertEqual(p2.returncode, 2) - self.assertIn("overwrite", p2.stderr) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/test_psocache_extract.py b/tests/test_psocache_extract.py deleted file mode 100644 index b53bcfe19..000000000 --- a/tests/test_psocache_extract.py +++ /dev/null @@ -1,165 +0,0 @@ -"""CPU test for tools/psocache_extract.py on synthetic RPF9 archives built by this test. - -The cache inside is a tiny file that satisfies the layout `psocache_inspect` checks: a 0x80 header, one 0x70 -record, one 0x18 record, two 8-byte index entries, a 32-byte meta entry and a 0x100-byte code entry. The cache -is split across two zlib streams in the archive, with zero padding, a stream before it and a stream after it. -""" - -import os -import struct -import subprocess -import sys -import tempfile -import unittest -import zlib - -ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) -TOOL = os.path.join(ROOT, "tools", "psocache_extract.py") - -HEADER = 0x80 -GRAPHICS = 1 -COMPUTE = 1 -META_INDEX = 1 -SHADER_INDEX = 1 -META_SIZE = 32 -CODE_SIZE = 0x100 -CACHE_SIZE = ( - HEADER - + GRAPHICS * 0x70 - + COMPUTE * 0x18 - + META_INDEX * 8 - + SHADER_INDEX * 8 - + META_SIZE - + CODE_SIZE -) -SPLIT = 200 -END_PGM = b"\x00\x00\x81\xbf" -CODE_END = b"\x00\x00\x9f\xbf" - - -def build_cache(): - data = bytearray(CACHE_SIZE) - data[0:4] = b"PS\x00\x09" - struct.pack_into("<4I", data, 0x50, GRAPHICS, COMPUTE, META_INDEX, SHADER_INDEX) - struct.pack_into("<2I", data, 0x60, META_SIZE, CODE_SIZE) - off = HEADER - struct.pack_into("/disasm/.s plus the empty /.dxbc container translate() reads beside it.""" - with open(os.path.join(tmp, "disasm", name + ".s"), "w", encoding="utf-8", newline="\n") as f: - f.write(f"; {name} code 0x100..0x200\n" + "".join("\t" + ln + "\n" for ln in lines)) - with open(os.path.join(tmp, name + ".dxbc"), "wb") as f: - f.write(EMPTY_DXBC) - - -def scan(lines_by_name): - with tempfile.TemporaryDirectory() as tmp: - disasm = os.path.join(tmp, "disasm") - os.mkdir(disasm) - for name, lines in lines_by_name.items(): - write_listing(tmp, name, lines) - with warnings.catch_warnings(): - warnings.simplefilter("ignore", ResourceWarning) - records = {os.path.splitext(os.path.basename(p))[0]: P.scan_one(p) for p in P.listings(disasm)} - gc.collect() - return records - - -class ScanTests(unittest.TestCase): - @classmethod - def setUpClass(cls): - cls.records = scan(LISTINGS) - - def test_every_listing_reaches_the_metadata_call(self): - for name, r in self.records.items(): - self.assertIsNone(r["error"], name) - self.assertEqual(r["stage"], "ps") - - def test_sites_name_access_low_and_high(self): - self.assertEqual(self.records["ps_table32"]["sites"], [[2, "user", "zero", "table"]]) - self.assertEqual(sorted(map(tuple, self.records["ps_two32"]["sites"])), - [(4, "user_off", "zero", "table"), (6, "user", "zero", "scalar")]) - self.assertEqual(sorted(map(tuple, self.records["ps_mixed"]["sites"])), - [(0, "user", "user", "global"), (2, "user", "zero", "table")]) - self.assertEqual(self.records["ps_const_base"]["sites"], [[None, "other", "zero", "table"]]) - - def test_flag_is_shader_meta_truncates_high(self): - for name, r in self.records.items(): - self.assertEqual(r["truncates_high"], r["instrumented_truncates_high"], name) - self.assertTrue(self.records["ps_table32"]["truncates_high"]) - self.assertFalse(self.records["ps_ptr64"]["truncates_high"]) - self.assertFalse(self.records["ps_const_base"]["truncates_high"]) - - def test_instrumentation_is_removed_afterwards(self): - self.assertEqual(shader_meta._record_ptr_pair.__module__, "shader_meta") - self.assertEqual(shader_meta._step_state.__module__, "shader_meta") - self.assertEqual(shader_meta.collect.__module__, "shader_meta") - - def test_summary(self): - s = P.summarise(list(self.records.values())) - self.assertEqual(s["total"], 7) - self.assertEqual(s["truncating_shaders"], {"ps": 3}) - self.assertEqual(s["pointer_mode"]["ps"], {"all truncated": 2, "some truncated": 1, "none truncated": 1, - "no pointer": 3}) - self.assertEqual(s["truncated_pointers_per_shader"]["ps"], {"1": 2, "2": 1}) - self.assertEqual(s["truncated_pointer_access"]["ps"], {"scalar": 1, "table": 3}) - self.assertEqual(s["truncated_pointer_low_half"]["ps"], {"user": 3, "user_off": 1}) - self.assertEqual(s["truncated_pointer_sgpr"]["ps"], {"s2": 2, "s4": 1, "s6": 1}) - self.assertEqual(s["truncated_pointer_kind_in_index"]["ps"], {"ptr32_lo": 4}) - self.assertEqual(s["untruncated_site_high_half"]["ps"], {"user (global)": 1, "user (table)": 1}) - self.assertEqual(s["not_seen"]["ps"], {"shaders with lo not a user SGPR, hi zero (table)": 1, - "shaders with a VGPR-addressed global_*": 1, - "VGPR-addressed global_* instructions": 1}) - self.assertEqual(s["flag_mismatches"], 0) - out = io.StringIO() - P.print_summary(s, out) - self.assertIn("truncate a pointer's high dword: 3: ps 3", out.getvalue()) - self.assertNotIn("ps_table32", out.getvalue()) - - -class SummaryTests(unittest.TestCase): - def test_not_reached_and_mismatch_are_counted(self): - records = [ - {"stage": "cs", "error": "Unsupported: x"}, - {"stage": "cs", "error": None, "sites": [[4, "user", "zero", "table"]], "truncates_high": False, - "instrumented_truncates_high": False, "user_sgpr_reads": [{"sgpr": 4, "kind": "ptr32_lo"}]}, - ] - s = P.summarise(records) - self.assertEqual(s["shaders"], {"cs": 2}) - self.assertEqual(s["reached_metadata"], {"cs": 1}) - self.assertEqual(s["not_reached"], {"Unsupported: x": 1}) - self.assertEqual(s["flag_mismatches"], 1) - - def test_pointer_used_both_ways(self): - records = [{"stage": "ms", "error": None, "truncates_high": True, "instrumented_truncates_high": True, - "sites": [[16, "user", "zero", "table"], [16, "user", "unknown", "scalar"]], - "user_sgpr_reads": [{"sgpr": 16, "kind": "ptr64_lo"}]}] - s = P.summarise(records) - self.assertEqual(s["pointer_mode"]["ms"], {"some truncated": 1}) - self.assertEqual(s["truncated_also_used_untruncated"], {"ms": 1}) - self.assertEqual(s["truncated_pointer_kind_in_index"]["ms"], {"ptr64_lo": 1}) - - def test_cli_writes_lf_json_without_names(self): - with tempfile.TemporaryDirectory() as tmp: - disasm = os.path.join(tmp, "disasm") - os.mkdir(disasm) - write_listing(tmp, "ps_table32", LISTINGS["ps_table32"]) - out, idx = os.path.join(tmp, "s.json"), os.path.join(tmp, "i.json") - with warnings.catch_warnings(): - warnings.simplefilter("ignore", ResourceWarning) - stdout = sys.stdout - sys.stdout = io.StringIO() - try: - rc = P.main([disasm, "--jobs", "1", "--json", out, "--index-out", idx]) - finally: - sys.stdout = stdout - self.assertEqual(rc, 0) - for path in (out, idx): - with open(path, "rb") as f: - data = f.read() - self.assertNotIn(b"\r\n", data) - self.assertNotIn(b"ps_table32", data) - with open(idx, encoding="utf-8") as f: - self.assertEqual(json.load(f), {"0": {"stage": "ps", "user_sgpr_reads": [{"sgpr": 2, "kind": "ptr32_lo"}]}}) - - def test_json_and_index_out_name_two_files(self): - with tempfile.TemporaryDirectory() as tmp: - disasm = os.path.join(tmp, "disasm") - os.mkdir(disasm) - write_listing(tmp, "ps_table32", LISTINGS["ps_table32"]) - one = os.path.join(tmp, "r.json") - stderr = sys.stderr - sys.stderr = io.StringIO() - try: - with self.assertRaises(SystemExit) as cm: - P.main([disasm, "--jobs", "1", "--json", one, "--index-out", one]) - finally: - message = sys.stderr.getvalue() - sys.stderr = stderr - self.assertEqual(cm.exception.code, 2) - self.assertIn("one file", message) - self.assertFalse(os.path.exists(one)) - - def test_limit_below_one_is_rejected(self): - with tempfile.TemporaryDirectory() as tmp: - disasm = os.path.join(tmp, "disasm") - os.mkdir(disasm) - write_listing(tmp, "ps_table32", LISTINGS["ps_table32"]) - for bad in ("0", "-1"): - stderr = sys.stderr - sys.stderr = io.StringIO() - try: - with self.assertRaises(SystemExit) as cm: - P.main([disasm, "--limit", bad]) - finally: - message = sys.stderr.getvalue() - sys.stderr = stderr - self.assertEqual(cm.exception.code, 2) - self.assertIn("--limit", message) - self.assertIn("at least 1", message) - - def test_missing_folder(self): - stderr = sys.stderr - sys.stderr = io.StringIO() - try: - self.assertEqual(P.main([os.path.join(ROOT, "no-such-folder-here")]), 2) - finally: - sys.stderr = stderr - - def test_limit_must_be_positive(self): - for value in ("0", "-1"): - with self.subTest(limit=value): - stderr = sys.stderr - sys.stderr = io.StringIO() - try: - with self.assertRaises(SystemExit) as cm: - P.main([os.path.join(ROOT, "tools"), "--limit", value]) - finally: - message = sys.stderr.getvalue() - sys.stderr = stderr - self.assertEqual(cm.exception.code, 2) - self.assertIn("argument --limit: must be at least 1", message) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/test_rbf0_encode.py b/tests/test_rbf0_encode.py deleted file mode 100644 index 9224cd042..000000000 --- a/tests/test_rbf0_encode.py +++ /dev/null @@ -1,442 +0,0 @@ -"""Synthetic tests for tools/rbf0_encode.py. - - python -I tests/test_rbf0_encode.py - -Every byte here is built by the test. No game file, game asset path or game name is used. -""" -import io -import json -import math -import os -import struct -import subprocess -import sys -import tempfile -import unittest -from contextlib import redirect_stderr, redirect_stdout - -ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) -sys.path.insert(0, os.path.join(ROOT, "tools")) - -import rbf0_encode # noqa: E402 -import rbf0_tree # noqa: E402 - -PROLOGUE = rbf0_tree.PROLOGUE - - -class Stream: - """Builds an RBF0 record stream; a descriptor gets its name on first use, as the format requires.""" - - def __init__(self, wide=True): - self.wide = wide - self.out = bytearray(b"RBF0" + (PROLOGUE if wide else b"")) - self.names = [] - - def _rec(self, name, kind): - if name in self.names: - self.out += bytes((self.names.index(name), kind)) - else: - self.names.append(name) - raw = name.encode() - self.out += bytes((len(self.names) - 1, kind)) + struct.pack(" 64000: - b += _value(2, 0x60, struct.pack(" Item(attrs=2) -> Child(text), then a value after the child.""" - b = bytearray(WIDE) - b += _open(0, b"TestRoot") - b += _open(1, b"Item", attrs=2) - b += _value(2, 0x10, struct.pack(" None: - source = os.path.join(self.root, "text.bin") - expected = "first\rsecond\r\n" - with open(source, "wb") as f: - f.write(WIDE + _open(0, b"TestRoot") + _text(expected.encode("utf-8")) + CLOSE) - out = os.path.join(self.root, "tree.json") - xml_dir = os.path.join(self.root, "xml") - - self.assertEqual(rbf0_tree.main([source, out, "--xml", xml_dir, "--quiet"]), 0) - - tree = ET.parse(os.path.join(xml_dir, "00000000.xml")) - self.assertEqual(tree.findtext(".//text"), expected) - - def test_json_and_xml(self): - blob = bytearray(WIDE) - blob += _open(0, b"TestRoot", attrs=1) - blob += _value(1, 0x60, struct.pack(" clamped to 1.0 - (-0.5, 0.0), # 1 / -0.5 = -2.0 -> clamped to 0.0 - (2.0, 0.5), # 1 / 2.0 = 0.5 -> stays 0.5 - ) - with tempfile.TemporaryDirectory() as directory: - for src_val, want in cases: - with self.subTest(src=src_val): - spv = self.translate_rcp(Path(directory), "v_rcp_iflag_f32_e64 v0, v1 clamp", src_val) - self.assert_rcp_pipeline(spv, scale_bits=None, clamp=True) - self.assertEqual(si.run(spv).vgpr[0], fbits(want)) - - def test_omod_multipliers(self): - cases = ( - ("mul:2", 0x40000000, 0.5, 4.0), - ("mul:4", 0x40800000, 0.5, 8.0), - ("div:2", 0x3F000000, 0.5, 1.0), - ("mul:2", 0x40000000, -4.0, -0.5), - ("mul:4", 0x40800000, 4.0, 1.0), - ("div:2", 0x3F000000, 2.0, 0.25), - ) - with tempfile.TemporaryDirectory() as directory: - for mod, scale_bits, src_val, want in cases: - with self.subTest(mod=mod, src=src_val): - spv = self.translate_rcp(Path(directory), f"v_rcp_iflag_f32_e64 v0, v1 {mod}", src_val) - self.assert_rcp_pipeline(spv, scale_bits=scale_bits, clamp=False) - self.assertEqual(si.run(spv).vgpr[0], fbits(want)) - - def test_omod_before_clamp(self): - cases = ( - ("mul:2 clamp", 0x40000000, 0.5, 1.0), # clamp(2.0 * 2.0) = 1.0 - ("mul:2 clamp", 0x40000000, 4.0, 0.5), # clamp(0.25 * 2.0) = 0.5 - ("clamp div:2", 0x3F000000, 0.5, 1.0), # clamp(2.0 * 0.5) = 1.0 (clamp-first would give 0.5) - ("clamp div:2", 0x3F000000, -0.5, 0.0), # clamp(-2.0 * 0.5) = 0.0 - ) - with tempfile.TemporaryDirectory() as directory: - for mods, scale_bits, src_val, want in cases: - with self.subTest(mods=mods, src=src_val): - spv = self.translate_rcp(Path(directory), f"v_rcp_iflag_f32_e64 v0, v1 {mods}", src_val) - self.assert_rcp_pipeline(spv, scale_bits=scale_bits, clamp=True) - self.assertEqual(si.run(spv).vgpr[0], fbits(want)) - - def test_source_and_output_modifiers_combined(self): - cases = ( - ("v_rcp_iflag_f32_e64 v0, -v1 clamp", True, False, None, True, -0.5, 1.0), - ("v_rcp_iflag_f32_e64 v0, -v1 mul:2", True, False, 0x40000000, False, 0.5, -4.0), - ("v_rcp_iflag_f32_e64 v0, |v1| mul:2", False, True, 0x40000000, False, -0.5, 4.0), - ("v_rcp_iflag_f32_e64 v0, |v1| clamp", False, True, None, True, -0.5, 1.0), - ("v_rcp_iflag_f32_e64 v0, -|v1| mul:2 clamp", True, True, 0x40000000, True, 0.5, 0.0), - ("v_rcp_iflag_f32_e64 v0, -|v1| mul:2", True, True, 0x40000000, False, -0.5, -4.0), - ) - with tempfile.TemporaryDirectory() as directory: - for insn, neg, abs_, scale_bits, clamp, src_val, want in cases: - with self.subTest(insn=insn, src=src_val): - spv = self.translate_rcp(Path(directory), insn, src_val) - self.assert_rcp_pipeline( - spv, neg=neg, abs_=abs_, scale_bits=scale_bits, clamp=clamp - ) - self.assertEqual(si.run(spv).vgpr[0], fbits(want)) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/test_rdna2_decode.py b/tests/test_rdna2_decode.py deleted file mode 100644 index 55364fe20..000000000 --- a/tests/test_rdna2_decode.py +++ /dev/null @@ -1,504 +0,0 @@ -"""Unit tests for the pure-Python RDNA2 binary ISA decoder (tools/rdna2_decode.py, #1901). - -Covers: - - All major RDNA2 encoding families (SOP1, SOP2, SOPC, SOPK, SOPP, SMEM, VOP1, VOP2, VOPC, - VINTRP, VOP3, VOP3B, VOP3P, DPP16, DPP8, SDWA, DS, MUBUF, MTBUF, MIMG + NSA + BVH, EXP, - FLAT/GLOBAL) from hand-encoded instruction words (no LLVM, no GPU, no game files). - - Special cases: VOP3P `v_dot4_i32_i8` with `op_sel` 2 / `op_sel_hi` 5 (`0xCC165008 0x0C0E0501`, - which `llvm-mc` rejects), LLVM `VCCTuple` scalar ranges ending in `vcc_lo,vcc_hi`, `s_waitcnt`, - `s_setreg_imm32_b32`, `ds_swizzle_b32`, and `shader_disasm.disasm(..., backend="python")`. - - Round-trip translation: raw RDNA2 machine code -> `rdna2_decode.disasm_bytes` -> `rdna2spirv.translate` - -> `spirv_mini_interp` value verification. - - Optional full-suite parity test against `llvm-mc` across all `runtime/test/shaders/*.asm` when - `LLVM_MC` (or `llvm-mc` on PATH) is available. -""" -from __future__ import annotations - -import glob -import os -import re -import shutil -import struct -import subprocess -import sys -import tempfile -import unittest -import warnings -from unittest.mock import patch - -HERE = os.path.dirname(os.path.abspath(__file__)) -ROOT = os.path.dirname(HERE) -TOOLS = os.path.join(ROOT, "tools") -SEMANTIC = os.path.join(HERE, "semantic") - -sys.dont_write_bytecode = True -for p in (TOOLS, SEMANTIC): - if p not in sys.path: - sys.path.insert(0, p) - -import rdna2_decode # noqa: E402 -import rdna2spirv # noqa: E402 -import shader_disasm # noqa: E402 -import shader_ir # noqa: E402 -import spirv_mini_interp as si # noqa: E402 - - -def words(*ws: int) -> bytes: - return b"".join(struct.pack(" sgpr 7, src0=256+2) - w_rfl = (0x3F << 25) | (7 << 17) | (2 << 9) | (256 + 2) - # v_fmaak_f32 v8, v2, v3, 0x3f800000 (VOP2 op=0x2d, vdst=8, vsrc1=3, src0=256+2) - w_fmaak = (0x2D << 25) | (8 << 17) | (3 << 9) | (256 + 2) - # v_cmp_eq_u32_e32 vcc_lo, 0, v2 (VOPC op=0xc2, vsrc1=2, src0=128) - w_cmp = (0x3E << 25) | (0xC2 << 17) | (2 << 9) | 128 - code = words(w_mov, w_rfl, w_fmaak, 0x3F800000, w_cmp) - info = rdna2_decode.decode_bytes(code, wave32=True) - self.assertEqual(info["invalid"], 0) - self.assertEqual([i["op"] for i in info["insns"]], - ["v_mov_b32_e32", "v_readfirstlane_b32", "v_fmaak_f32", "v_cmp_eq_u32_e32"]) - self.assertEqual(info["insns"][0]["args"][1]["v"], 1.0) - self.assertEqual(info["insns"][1]["args"][0]["k"], "sgpr") - self.assertEqual(info["insns"][1]["args"][0]["r"], 7) - self.assertEqual(info["insns"][2]["args"][3], {"k": "imm", "v": 0x3F800000}) - self.assertEqual(info["insns"][3]["args"][0]["t"], "vcc_lo") - # Wave64 uses `vcc` instead of `vcc_lo`. - info64 = rdna2_decode.decode_bytes(words(w_cmp), wave32=False) - self.assertEqual(info64["insns"][0]["args"][0]["t"], "vcc") - - def test_vop3p_dot4_i8_with_opsel_that_llvm_mc_rejects(self): - # Raw RDNA2 hardware-measured word from docs/fspx.md & tests/semantic/test_alu_dot4_i8.py: - # 0xCC165008 0x0C0E0501 = v_dot4_i32_i8 v8, v1, v2, v3 op_sel:[0,1,0] op_sel_hi:[1,0,1] - code = words(0xCC165008, 0x0C0E0501) - info = rdna2_decode.decode_bytes(code) - self.assertEqual(info["invalid"], 0) - ins = info["insns"][0] - self.assertEqual(ins["op"], "v_dot4_i32_i8") - self.assertEqual([a["r"] for a in ins["args"]], [8, 1, 2, 3]) - self.assertEqual(ins["mods"], ["op_sel:[0,1,0]", "op_sel_hi:[1,0,1]"]) - # Formatting + shader_ir re-parse round-trips identically. - line = rdna2_decode.format_insn(ins) - reparsed = shader_ir.parse_line(line) - self.assertEqual(reparsed["op"], ins["op"]) - self.assertEqual(reparsed["mods"], ins["mods"]) - - def test_smem_vcc_tuple_and_offsets(self): - # s_buffer_load_dwordx8 [s100..s105,vcc_lo,vcc_hi], s[0:3], null (SMEM op=0x0b, sdata=100, sbase=0, soff=125) - w0 = (0x3D << 26) | (0x0B << 18) | (100 << 6) | 0 - w1 = (125 << 25) - info = rdna2_decode.decode_bytes(words(w0, w1)) - self.assertEqual(info["invalid"], 0) - ins = info["insns"][0] - self.assertEqual(ins["op"], "s_buffer_load_dwordx8") - self.assertEqual(ins["args"][0], { - "k": "slist", "r": [100, 101, 102, 103, 104, 105, "vcc_lo", "vcc_hi"], "n": 8, - }) - self.assertEqual(ins["args"][2], {"k": "special", "t": "null", "neg": False, "abs": False}) - - def test_mubuf_mtbuf_mimg_global_ds_exp_vintrp(self): - # MUBUF: buffer_load_format_d16_xyzw v[8:9], v5, s[4:7], 0 offen (encoding verified against llvm-mc) - b_mubuf = bytes([0x00, 0x10, 0x0C, 0xE2, 0x05, 0x08, 0x01, 0x80]) - # MIMG BVH: image_bvh_intersect_ray v[20:23], [v2..v12], s[4:7] - b_bvh = bytes([0x07, 0x9F, 0x98, 0xF1, 0x02, 0x14, 0x01, 0x00, - 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x00, 0x00]) - # EXP: exp mrt0 v0, v1, v2, v3 done vm - w_exp0 = (0x3E << 26) | (1 << 12) | (1 << 11) | (0 << 4) | 0xF - w_exp1 = 0 | (1 << 8) | (2 << 16) | (3 << 24) - # VINTRP: v_interp_p1_f32 v2, v0, attr1.y (op=0, vdst=2, attr=1, chan=1, vsrc=0) - w_vint = (0x32 << 26) | (2 << 18) | (0 << 16) | (1 << 10) | (1 << 8) | 0 - # GLOBAL: global_store_dword v[4:5], v1, off offset:-4 (seg=2, op=0x1c, saddr=125) - w_glb0 = (0x37 << 26) | (0x1C << 18) | (2 << 14) | (0xFFC) - w_glb1 = (125 << 16) | (1 << 8) | 4 - code = b_mubuf + b_bvh + words(w_exp0, w_exp1, w_vint, w_glb0, w_glb1) - info = rdna2_decode.decode_bytes(code) - self.assertEqual(info["invalid"], 0) - self.assertEqual([i["op"] for i in info["insns"]], [ - "buffer_load_format_d16_xyzw", - "image_bvh_intersect_ray", - "exp", - "v_interp_p1_f32", - "global_store_dword", - ]) - self.assertEqual(info["insns"][1]["args"][1], {"k": "vlist", "r": list(range(2, 13))}) - self.assertEqual(info["insns"][1]["mods"], []) - self.assertEqual(info["insns"][2]["mods"], ["done", "vm"]) - self.assertEqual(info["insns"][3]["args"][2], {"k": "attr", "a": 1, "c": 1}) - self.assertEqual(info["insns"][4]["args"][2]["t"], "off") - self.assertEqual(info["insns"][4]["mods"], ["offset:-4"]) - - def test_sdwa_inline_sources(self): - values = list(range(65)) + list(range(-1, -17, -1)) - floats = [0.5, -0.5, 1.0, -1.0, 2.0, -2.0, 4.0, -4.0, 0.15915494] - constants = [(128 + i, "imm", v) for i, v in enumerate(values)] - constants += [(240 + i, "fimm", v) for i, v in enumerate(floats)] - # gfx1013 v_mov_b32, v_add_f32 and v_cmp_eq_f32 SDWA encodings. - for opcode in (0x7E0002F9, 0x060000F9, 0x7C0400F9): - slots = (0,) if opcode == 0x7E0002F9 else (0, 1) - for slot in slots: - for code, kind, value in constants: - with self.subTest(opcode=hex(opcode), slot=slot, code=code): - first = opcode - second = code | (1 << 23) - if slot == 1: - first |= code << 9 - second = 1 | (1 << 31) - ins = rdna2_decode.decode_bytes(words(first, second))["insns"][0] - operand = ins["args"][1 + slot] - self.assertEqual((operand["k"], operand["v"]), (kind, value)) - - def test_roundtrip_binary_to_spirv_and_interpreter(self): - # Synthetic pixel shader binary: v_mov_b32 v0, 1.0; v_add_f32 v1, v0, 2.0; exp mrt0 v0, v1, v0, v1 done vm; s_endpgm - w_mov = (0x3F << 25) | (0 << 17) | (1 << 9) | 242 # v0 = 1.0 - w_add = (0x03 << 25) | (1 << 17) | (0 << 9) | 244 # v1 = 2.0 + v0 = 3.0 - w_exp0 = (0x3E << 26) | (1 << 12) | (1 << 11) | 0xF - w_exp1 = 0 | (1 << 8) | (0 << 16) | (1 << 24) - w_end = 0xBF810000 - code = words(w_mov, w_add, w_exp0, w_exp1, w_end) - - asm, bad, err = shader_disasm.disasm(code, "gfx1013", backend="python") - self.assertEqual(bad, 0) - self.assertEqual(err, "") - with tempfile.TemporaryDirectory() as tmp: - disasm_dir = os.path.join(tmp, "disasm") - os.mkdir(disasm_dir) - with open(os.path.join(tmp, "ps_dec.dxbc"), "wb") as f: - f.write(b"DXBC" + bytes(28)) - src = os.path.join(disasm_dir, "ps_dec.s") - with open(src, "w", encoding="utf-8") as f: - f.write("; ps_dec code 0x0..0x14 (python), gfx1013, 0 invalid words\n" + asm) - with warnings.catch_warnings(): - warnings.simplefilter("ignore", ResourceWarning) - spv = rdna2spirv.translate(src) - out = si.run_fragment(spv)["%out_mrt0"] - self.assertEqual(list(out), [0x3F800000, 0x40400000, 0x3F800000, 0x40400000]) - - def test_flat_scratch_vaddr_off_and_lds_loads(self): - # LLVM GFX10/GFX10.30 disassembler vectors (gfx10_flat.txt / gfx1030_new.txt): - # - SCRATCH (seg=1) only uses VGPR vaddr in SV mode (saddr == 0x7d); SS mode (SGPR saddr) and GFX10.30 - # ST mode (saddr == 0x7f) emit `off` for vaddr. - # - Direct-to-LDS global/scratch loads (lds=1) omit VDST. - for hexcode, asm in ( - # SCRATCH SS mode (SGPR saddr -> vaddr is off) - ("004030dc00000101", "scratch_load_dword v1, off, s1"), - ("204030dc00000101", "scratch_load_dword v1, off, s1 offset:32"), - ("004030dc00007e01", "scratch_load_dword v1, off, exec_lo"), - ("004030dc00007c01", "scratch_load_dword v1, off, m0"), - ("004070dc00020100", "scratch_store_dword off, v2, s1"), - ("0c4070dc00020100", "scratch_store_dword off, v2, s1 offset:12"), - ("004064dc00020100", "scratch_store_byte_d16_hi off, v2, s1"), - # Non-zero don't-care addr bits in SS mode still decode as off. - ("004030dc05000101", "scratch_load_dword v1, off, s1"), - # SCRATCH ST mode (GFX10.30 saddr == 0x7f -> vaddr and saddr are both off) - ("004030dc00007f01", "scratch_load_dword v1, off, off"), - ("004038dc00007f01", "scratch_load_dwordx4 v[1:4], off, off"), - ("ff4770dc00027f00", "scratch_store_dword off, v2, off offset:2047"), - # SCRATCH SV mode control (saddr == 0x7d -> VGPR vaddr kept, including v0) - ("004030dc02007d01", "scratch_load_dword v1, v2, off"), - ("005030dc00007d05", "scratch_load_dword v5, v0, off dlc"), - ("ff4f70dc00027d00", "scratch_store_dword v0, v2, off offset:-1"), - # Direct-to-LDS global and scratch loads (lds=1 -> VDST omitted) - ("00a430dc02000400", "global_load_dword v2, s[4:5] offset:1024 lds"), - ("00a430dc02007d00", "global_load_dword v[2:3], off offset:1024 lds"), - ("00a424dc02000400", "global_load_sbyte v2, s[4:5] offset:1024 lds"), - ("006430dc02007d00", "scratch_load_dword v2, off offset:1024 lds"), - ("006430dc00000400", "scratch_load_dword off, s4 offset:1024 lds"), - ("006430dc00007f00", "scratch_load_dword off, off offset:1024 lds"), - # Non-zero don't-care vdst bits in lds mode still omit VDST. - ("00a430dc02000407", "global_load_dword v2, s[4:5] offset:1024 lds"), - # Non-LDS global load control (VDST kept) - ("008430dc02000401", "global_load_dword v1, v2, s[4:5] offset:1024"), - ): - with self.subTest(hexcode=hexcode, asm=asm): - raw = bytes.fromhex(hexcode) - dec = rdna2_decode.decode_bytes(raw) - self.assertEqual(dec["invalid"], 0) - (ins,) = dec["insns"] - expected = shader_ir.parse_line(asm) - for field in ("op", "args", "mods"): - self.assertEqual(ins[field], expected[field]) - # Formatted text also round-trips cleanly through shader_ir.parse_line. - text, bad = rdna2_decode.disasm_bytes(raw) - self.assertEqual(bad, 0) - reparsed = shader_ir.parse_line(text.strip()) - for field in ("op", "args", "mods"): - self.assertEqual(reparsed[field], expected[field]) - - def test_parity_with_llvm_mc_on_shader_fixtures(self): - mc = os.environ.get("LLVM_MC") or shutil.which("llvm-mc") or shutil.which("llvm-mc-18") - if not mc: - self.skipTest("llvm-mc not available") - asms = sorted(glob.glob(os.path.join(ROOT, "runtime", "test", "shaders", "*.asm"))) - self.assertGreater(len(asms), 50) - - def norm_op(op): - for suf in ("_e32", "_e64", "_sdwa", "_dpp"): - if op.endswith(suf): - op = op[:-len(suf)] - return op - - def norm_arg(a, op=""): - k = a["k"] - if k in ("vgpr", "sgpr"): - return (k, a["r"], a.get("n", 1), bool(a.get("neg")), bool(a.get("abs")), bool(a.get("sext"))) - if k == "imm": - # LLVM 18 disassembles SOPP branch offsets unsigned (0xfff0), LLVM 21/22 signed (-16). - mask = 0xFFFF if op in rdna2_decode._SOPP_BRANCHES else 0xFFFFFFFF - return ("imm", a["v"] & mask, bool(a.get("neg")), bool(a.get("abs"))) - if k == "fimm": - return ("fimm", round(a["v"], 6), bool(a.get("neg")), bool(a.get("abs"))) - if k in ("vlist", "slist"): - return (k, tuple(a["r"])) - if k == "attr": - return ("attr", a["a"], a["c"]) - return (k, a.get("t", ""), bool(a.get("neg")), bool(a.get("abs"))) - - checked = 0 - for path in asms: - with open(path, encoding="utf-8") as f: - txt = f.read() - m = re.search(r"^;\s*mattr:\s*(\S+)", txt, re.M) - mattr = m.group(1) if m else "" - wave32 = "-wavefrontsize32" not in mattr and "+wavefrontsize64" not in mattr - cmd = [mc, "-triple=amdgcn--amdpal", "-mcpu=gfx1013", "-show-encoding"] - if mattr: - cmd.append("-mattr=" + mattr) - if os.path.basename(path) == "vs_clip.asm": - cmd.append("-defsym=PARAM_SLOT=1") - r = subprocess.run(cmd, input=txt, text=True, capture_output=True) - if r.returncode != 0 or "error:" in r.stderr: - continue - raw = bytearray() - for ln in r.stdout.splitlines(): - if "; encoding:" not in ln or ln.lstrip().startswith("."): - continue - ins = shader_ir.parse_line(ln) - if ins and ins["enc"]: - raw.extend(bytes.fromhex(ins["enc"])) - dcmd = [mc, "-disassemble", "-triple=amdgcn--amdpal", "-mcpu=gfx1013", "-show-encoding"] - if mattr: - dcmd.append("-mattr=" + mattr) - dr = subprocess.run(dcmd, input=" ".join(f"0x{b:02x}" for b in raw), text=True, capture_output=True) - llvm_insns = [] - pc = 0 - for ln in dr.stdout.splitlines(): - if "; encoding:" not in ln or ln.lstrip().startswith("."): - continue - ins = shader_ir.parse_line(ln) - if ins and ins["enc"]: - ins["pc"] = pc - pc += len(ins["enc"]) // 2 - llvm_insns.append(ins) - dec = rdna2_decode.decode_bytes(bytes(raw), wave32=wave32) - self.assertEqual(dec["invalid"], 0, path) - self.assertEqual(len(dec["insns"]), len(llvm_insns), path) - for li, di in zip(llvm_insns, dec["insns"]): - self.assertEqual(di["enc"], li["enc"], path) - self.assertEqual(norm_op(di["op"]), norm_op(li["op"]), path) - self.assertEqual([norm_arg(x, di["op"]) for x in di["args"]], - [norm_arg(x, li["op"]) for x in li["args"]], - f"{path}: {li['op']}") - self.assertEqual(sorted(di["mods"]), sorted(li["mods"]), f"{path}: {li['op']}") - checked += 1 - self.assertGreater(checked, 5000) - - def test_permlane_op_sel_is_fi_and_bound_ctrl(self): - # VOP3 0x377 / 0x378, `v11, v2, s4, s5`: op_sel has two bits here, [FI, BOUND_CTRL] (docs/design.md, SHADER-74). - for opcode, name in ((0x377, "v_permlane16_b32"), (0x378, "v_permlanex16_b32")): - for bits, mods in ((0, []), (1, ["op_sel:[1,0]"]), (2, ["op_sel:[0,1]"]), (3, ["op_sel:[1,1]"])): - with self.subTest(name=name, bits=bits): - code = words(0xD400000B | opcode << 16 | bits << 11, 0x00140902) - ins, = rdna2_decode.decode_bytes(code)["insns"] - expected = shader_ir.parse_line(f"{name} v11, v2, s4, s5") - self.assertEqual((ins["op"], ins["args"], ins["mods"]), (name, expected["args"], mods)) - - def test_exp_targets_match_the_parsed_listing(self): - # shader_ir.operand reads the null target as the special register of that name, the others as targets. - for code, asm in ((words(0xF8000090, 0), "exp null off, off, off, off"), - (words(0xF800180F, 0x03020100), "exp mrt0 v0, v1, v2, v3 done vm")): - with self.subTest(asm=asm): - ins, = rdna2_decode.decode_bytes(code)["insns"] - expected = shader_ir.parse_line(asm) - for field in ("op", "args", "mods"): - self.assertEqual(ins[field], expected[field]) - - def test_sdwa_inline_constants_and_sgpr(self): - # Exact encodings from runtime/test/shaders/ps_sdwa_f16_const.asm: - # 1) v_add_f16_sdwa v2, 1.0, v1 dst_sel:WORD_0 dst_unused:UNUSED_PRESERVE src0_sel:WORD_1 src1_sel:WORD_0 - # 2) v_mul_f16_sdwa v3, 2.0, v1 dst_sel:WORD_0 dst_unused:UNUSED_PRESERVE src0_sel:BYTE_1 src1_sel:WORD_1 - # 3) v_add_f16_sdwa v4, s8, v1 dst_sel:WORD_0 dst_unused:UNUSED_PRESERVE src0_sel:WORD_1 src1_sel:WORD_0 - # 4) v_cvt_f16_u16_sdwa v5, 1.0 dst_sel:WORD_0 dst_unused:UNUSED_PRESERVE src0_sel:WORD_1 (VOP1 opc 0x50) - # 5) v_cmp_eq_u32_sdwa vcc_lo, 5, -1 src0_sel:WORD_0 src1_sel:WORD_0 (VOPC opc 0xc2, s0=133, s1=193) - raw = bytes([ - 0xF9, 0x02, 0x04, 0x64, 0xF2, 0x14, 0x85, 0x04, - 0xF9, 0x02, 0x06, 0x6A, 0xF4, 0x14, 0x81, 0x05, - 0xF9, 0x02, 0x08, 0x64, 0x08, 0x14, 0x85, 0x04, - 0xF9, 0xA0, 0x0A, 0x7E, 0xF2, 0x14, 0x85, 0x00, - 0xF9, 0x82, 0x85, 0x7D, 0x85, 0x00, 0x84, 0x84, - ]) - dec = rdna2_decode.decode_bytes(raw, wave32=True) - self.assertEqual(dec["invalid"], 0) - insns = dec["insns"] - self.assertEqual(len(insns), 5) - - self.assertEqual(insns[0]["op"], "v_add_f16_sdwa") - self.assertEqual(insns[0]["args"][1]["k"], "fimm") - self.assertEqual(insns[0]["args"][1]["v"], 1.0) - self.assertEqual(insns[0]["args"][2]["k"], "vgpr") - self.assertEqual(insns[0]["args"][2]["r"], 1) - - self.assertEqual(insns[1]["op"], "v_mul_f16_sdwa") - self.assertEqual(insns[1]["args"][1]["k"], "fimm") - self.assertEqual(insns[1]["args"][1]["v"], 2.0) - - self.assertEqual(insns[2]["op"], "v_add_f16_sdwa") - self.assertEqual(insns[2]["args"][1]["k"], "sgpr") - self.assertEqual(insns[2]["args"][1]["r"], 8) - - self.assertEqual(insns[3]["op"], "v_cvt_f16_u16_sdwa") - self.assertEqual(insns[3]["args"][1]["k"], "fimm") - self.assertEqual(insns[3]["args"][1]["v"], 1.0) - - self.assertEqual(insns[4]["op"], "v_cmp_eq_u32_sdwa") - self.assertEqual(insns[4]["args"][1]["k"], "imm") - self.assertEqual(insns[4]["args"][1]["v"], 5) - self.assertEqual(insns[4]["args"][2]["k"], "imm") - self.assertEqual(insns[4]["args"][2]["v"], -1) - - # Verify formatted text round-trips cleanly through shader_ir.parse_line. - text, bad = rdna2_decode.disasm_bytes(raw, wave32=True) - self.assertEqual(bad, 0) - parsed = [shader_ir.parse_line(ln) for ln in text.splitlines() if ln.strip()] - self.assertEqual(len(parsed), 5) - self.assertEqual(parsed[0]["args"][1]["k"], "fimm") - self.assertEqual(parsed[0]["args"][1]["v"], 1.0) - self.assertEqual(parsed[3]["args"][1]["k"], "fimm") - self.assertEqual(parsed[3]["args"][1]["v"], 1.0) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/test_rdna2spirv_cli.py b/tests/test_rdna2spirv_cli.py deleted file mode 100644 index 6ce0777e6..000000000 --- a/tests/test_rdna2spirv_cli.py +++ /dev/null @@ -1,618 +0,0 @@ -"""rdna2spirv.py command-line validation and SPIR-V output tests. - - python -I tests/test_rdna2spirv_cli.py - -Synthetic inputs only. The end-to-end retry test also needs SPIRV-Tools on PATH. -""" -import argparse -import io -import json -import os -import shutil -import subprocess -import sys -import tempfile -import unittest -from contextlib import redirect_stderr, redirect_stdout -from pathlib import Path -from unittest import mock - -ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) -sys.path.insert(0, os.path.join(ROOT, "tools")) -TOOL = os.path.join(ROOT, "tools", "rdna2spirv.py") - -import rdna2spirv # noqa: E402 - - -class ArgumentTypes(unittest.TestCase): - def test_limit(self): - self.assertEqual(rdna2spirv._limit_arg("200"), 200) - self.assertEqual(rdna2spirv._limit_arg("1"), 1) - for text in ("0", "-1", "-200", "x", ""): - with self.subTest(text=text), self.assertRaises(argparse.ArgumentTypeError): - rdna2spirv._limit_arg(text) - - def test_shard(self): - self.assertEqual(rdna2spirv._shard_arg("0/8"), (0, 8)) - self.assertEqual(rdna2spirv._shard_arg("7/8"), (7, 8)) - self.assertEqual(rdna2spirv._shard_arg("0/1"), (0, 1)) - for text in ("0/0", "8/8", "9/8", "-1/8", "1/-8", "a/b", "0", "0/8/1", "", "/8"): - with self.subTest(text=text), self.assertRaises(argparse.ArgumentTypeError): - rdna2spirv._shard_arg(text) - - def test_max_structured_depth(self): - self.assertEqual(rdna2spirv._depth_arg("0"), 0) - self.assertEqual(rdna2spirv._depth_arg("64"), 64) - for text in ("-1", "x", "", "1.5"): - with self.subTest(text=text), self.assertRaises(argparse.ArgumentTypeError): - rdna2spirv._depth_arg(text) - - def test_max_structured_depth_sets_the_bound(self): - # SHADER-427: the option replaces MAX_STRUCTURED_DEPTH for the run; without it the default is 64, written out - # here rather than read from the module so that changing the default fails this test. - self.assertEqual(rdna2spirv.MAX_STRUCTURED_DEPTH, 64) - with tempfile.TemporaryDirectory() as tmp, \ - mock.patch.object(rdna2spirv, "MAX_STRUCTURED_DEPTH", rdna2spirv.MAX_STRUCTURED_DEPTH): - for extra, expected in (([], 64), (["--max-structured-depth", "0"], 0), - (["--max-structured-depth", "40"], 40)): - with self.subTest(extra=extra), \ - mock.patch.object(sys, "argv", [TOOL, tmp, "--out", os.path.join(tmp, "o")] + extra), \ - redirect_stdout(io.StringIO()): - rdna2spirv.MAX_STRUCTURED_DEPTH = 64 - rdna2spirv.main() - self.assertEqual(rdna2spirv.MAX_STRUCTURED_DEPTH, expected) - - -class SourceDiscovery(unittest.TestCase): - """The src argument is a .s file or a folder of .s files; other names are not inputs.""" - - def run_main(self, src, out): - def spirv_tool(cmd, **kwargs): - tool = cmd[0] - if tool == "spirv-as": - Path(kwargs.get("cwd", ""), cmd[3]).write_bytes(b"new module") - elif tool == "spirv-val": - self.assertEqual(Path(kwargs.get("cwd", ""), cmd[-1]).read_bytes(), b"new module") - else: - self.fail(f"unexpected tool: {tool}") - return subprocess.CompletedProcess(cmd, 0, "", "") - - output = io.StringIO() - with mock.patch.object(sys, "argv", [TOOL, str(src), "--out", str(out)]), \ - mock.patch.object(rdna2spirv.subprocess, "run", side_effect=spirv_tool), \ - redirect_stdout(output): - rdna2spirv.main() - return output.getvalue() - - def test_missing_src_is_refused_with_usage_error(self): - with tempfile.TemporaryDirectory() as tmp: - out = os.path.join(tmp, "spirv") - # The .s suffix matters: without isfile() a missing shader path would be trusted as a file. - p = subprocess.run([sys.executable, "-I", TOOL, os.path.join(tmp, "absent.s"), "--out", out], - capture_output=True, text=True, errors="replace") - self.assertEqual(p.returncode, 2, p.stderr) - self.assertIn("not a .s file or a folder of .s files", p.stderr) - self.assertNotIn("Traceback", p.stderr) - self.assertFalse(os.path.exists(out)) - - def test_directory_ending_in_s_as_src_is_a_directory(self): - # A .s suffix alone is not a shader: an existing directory is still scanned as a folder. - with tempfile.TemporaryDirectory() as tmp: - src = os.path.join(tmp, "shader.s") - os.mkdir(src) - p = subprocess.run([sys.executable, "-I", TOOL, src, "--out", os.path.join(tmp, "spirv")], - capture_output=True, text=True, errors="replace") - self.assertEqual(p.returncode, 0, p.stderr) - self.assertNotIn("Traceback", p.stderr) - self.assertIn("0 shaders:", p.stdout) - - def test_non_file_non_dir_entry_is_skipped(self): - # Covers entries that are neither files nor directories (broken symlinks, FIFOs, devices). - # is_file() rejects them; `not is_dir()` would feed one to translate() and crash. - class OddEntry: - name = "foo.s" - path = os.path.join("not-a-file", "foo.s") - - def is_file(self): - return False - - def is_dir(self): - return False - - class FakeScandir: - def __enter__(self): - return iter([OddEntry()]) - - def __exit__(self, *exc): - return False - - with tempfile.TemporaryDirectory() as tmp: - src = os.path.join(tmp, "disasm") - os.mkdir(src) - output = io.StringIO() - with mock.patch.object(sys, "argv", [TOOL, src, "--out", os.path.join(tmp, "spirv")]), \ - mock.patch.object(rdna2spirv.os, "scandir", lambda path: FakeScandir()), \ - redirect_stdout(output): - rdna2spirv.main() - self.assertIn("0 shaders:", output.getvalue()) - - def test_directory_ending_in_s_is_skipped(self): - with tempfile.TemporaryDirectory() as tmp: - root = Path(tmp) - src = root / "disasm" - src.mkdir() - (src / "ps_ok.s").write_text("\ts_endpgm\n", encoding="utf-8") - (root / "ps_ok.dxbc").write_bytes(b"DXBC" + bytes(28)) - (src / "nested.s").mkdir() # a directory that looks like a shader - out = root / "spirv" - out.mkdir() - stdout = self.run_main(src, out) - self.assertIn("1 pass spirv-val", stdout) - self.assertTrue((out / "ps_ok.spv").is_file()) - self.assertFalse((out / "nested.spv").exists()) - - def test_a_new_output_folder_with_missing_parents_still_works(self): - # The ancestor walk in the --out guard must not reject folders that simply don't exist yet. - with tempfile.TemporaryDirectory() as tmp: - root = Path(tmp) - src = root / "disasm" - src.mkdir() - (src / "ps_ok.s").write_text("\ts_endpgm\n", encoding="utf-8") - (root / "ps_ok.dxbc").write_bytes(b"DXBC" + bytes(28)) - out = root / "new" / "deep" / "spirv" - stdout = self.run_main(src, out) - self.assertIn("1 pass spirv-val", stdout) - self.assertTrue((out / "ps_ok.spv").is_file()) - - def test_non_s_file_as_src_is_refused_with_usage_error(self): - with tempfile.TemporaryDirectory() as tmp: - src = os.path.join(tmp, "notes.txt") - Path(src).write_text("not a shader", encoding="utf-8") - p = subprocess.run([sys.executable, "-I", TOOL, src, "--out", os.path.join(tmp, "spirv")], - capture_output=True, text=True, errors="replace") - self.assertEqual(p.returncode, 2, p.stderr) - self.assertNotIn("Traceback", p.stderr) - - -class CommandLine(unittest.TestCase): - def test_bad_limit_or_shard_is_refused_before_out_is_made(self): - with tempfile.TemporaryDirectory() as tmp: - src = os.path.join(tmp, "disasm") - os.mkdir(src) - with open(os.path.join(src, "ps_x.s"), "w", encoding="utf-8") as f: - f.write("\ts_endpgm\n") - for args, message in ((["--limit", "0"], "must be at least 1"), - (["--limit", "-5"], "must be at least 1"), - (["--shard", "0/0"], "need n >= 1"), - (["--shard", "9/8"], "need n >= 1 and 0 <= i < n"), - (["--shard", "a/b"], "expected i/n")): - out = os.path.join(tmp, "spirv") - with self.subTest(args=args): - p = subprocess.run([sys.executable, "-I", TOOL, src, "--out", out, *args], - capture_output=True, text=True, errors="replace") - self.assertEqual(p.returncode, 2) - self.assertIn(message, p.stderr) - self.assertNotIn("Traceback", p.stderr) - self.assertFalse(os.path.exists(out)) # 9/8 used to write an empty index.part9.json - - -class OutputFolderValidation(unittest.TestCase): - """--out must be a folder path: a file there is a usage error, never a traceback.""" - - def setUp(self): - self.tmp = Path(self.enterContext(tempfile.TemporaryDirectory())) - self.src = self.tmp / "disasm" - self.src.mkdir() - (self.src / "ps_x.s").write_text("\ts_endpgm\n", encoding="utf-8") - - def run_tool(self, out, *extra, timeout=None): - return subprocess.run([sys.executable, "-I", TOOL, str(self.src), "--out", os.fspath(out), *extra], - capture_output=True, text=True, errors="replace", timeout=timeout) - - def assert_usage_error(self, p, message): - self.assertEqual(p.returncode, 2, p.stderr) - self.assertNotIn("Traceback", p.stderr) - # argparse prints its usage and one error line; no exception text besides that line. - self.assertEqual(len([line for line in p.stderr.splitlines() if "error:" in line]), 1, p.stderr) - self.assertIn(message, p.stderr) - - def test_a_file_at_out_is_refused_and_left_alone(self): - out = self.tmp / "out.txt" - out.write_text("keep", encoding="utf-8") - p = self.run_tool(out) - self.assert_usage_error(p, "is a file, not a folder") - self.assertEqual(out.read_text(encoding="utf-8"), "keep") - - def test_an_out_under_a_file_is_refused_and_the_file_is_left_alone(self): - blocker = self.tmp / "blocker.txt" - blocker.write_text("keep", encoding="utf-8") - p = self.run_tool(blocker / "sub") - self.assert_usage_error(p, "cannot create") - self.assertEqual(blocker.read_text(encoding="utf-8"), "keep") - self.assertFalse((blocker / "sub").exists()) - - def test_a_file_at_out_is_refused_with_merge(self): - out = self.tmp / "out.txt" - out.write_text("keep", encoding="utf-8") - p = self.run_tool(out, "--merge") - self.assert_usage_error(p, "is a file, not a folder") - self.assertEqual(out.read_text(encoding="utf-8"), "keep") - - def test_a_file_at_out_with_a_trailing_separator_is_refused(self): - out = self.tmp / "out.txt" - out.write_text("keep", encoding="utf-8") - p = self.run_tool(str(out) + os.sep) - self.assertEqual(p.returncode, 2, p.stderr) - self.assertNotIn("Traceback", p.stderr) - self.assertIn(str(out), p.stderr) - self.assertEqual(out.read_text(encoding="utf-8"), "keep") - - def test_an_unmapped_drive_root_is_refused_without_hanging(self): - if os.name != "nt": - self.skipTest("unmapped drive roots are a Windows path case") - drive = next((f"{c}:\\" for c in "ZYXWVUTSRQPONMLKJIHGFEDCBA" if not os.path.exists(f"{c}:\\")), None) - if drive is None: - self.skipTest("every drive letter exists on this machine") - out = os.path.join(drive, "shaders") - p = self.run_tool(out, timeout=30) - # A root that does not exist used to make the ancestor walk spin forever. - self.assert_usage_error(p, "cannot create") - - def test_a_symlink_to_a_file_at_out_is_refused(self): - target = self.tmp / "target.txt" - target.write_text("keep", encoding="utf-8") - link = self.tmp / "link-out" - try: - os.symlink(target, link) - except (OSError, NotImplementedError) as e: - self.skipTest(f"symlinks are not available here: {e}") - p = self.run_tool(link) - self.assert_usage_error(p, "is a file, not a folder") - self.assertEqual(target.read_text(encoding="utf-8"), "keep") - - -class OutputInsideInput(unittest.TestCase): - """--out equal to the input folder, or inside it, is refused before anything is written (BUILD-1044).""" - - def setUp(self): - self.tmp = Path(self.enterContext(tempfile.TemporaryDirectory())) - self.src = self.tmp / "disasm" - self.src.mkdir() - (self.src / "ps_x.s").write_text("\ts_endpgm\n", encoding="utf-8") - (self.tmp / "ps_x.dxbc").write_bytes(b"DXBC" + bytes(28)) - - def run_tool(self, out): - return subprocess.run([sys.executable, "-I", TOOL, str(self.src), "--out", os.fspath(out)], - capture_output=True, text=True, timeout=120) - - def assert_refused(self, out): - p = self.run_tool(out) - self.assertEqual(p.returncode, 2, p.stdout + p.stderr) - self.assertNotIn("Traceback", p.stderr) - self.assertEqual(len(p.stderr.strip().splitlines()), 1, p.stderr) - self.assertTrue(p.stderr.startswith("ERROR: --out "), p.stderr) - self.assertIn("separate output folder", p.stderr) - self.assertFalse((self.src / "ps_x.spvasm").exists()) - self.assertFalse((self.src / "ps_x.spv").exists()) - self.assertFalse((self.src / "index.json").exists()) - - def test_out_equal_to_the_input_folder_is_refused(self): - self.assert_refused(self.src) - - def test_out_inside_the_input_folder_is_refused(self): - out = self.src / "spirv" - self.assert_refused(out) - self.assertFalse(out.exists()) # refused before mkdir, not left as an empty folder - - def test_a_distinct_out_folder_still_translates(self): - out = self.tmp / "spirv" - - def spirv_tool(cmd, **kwargs): - if cmd[0] == "spirv-as": - Path(kwargs.get("cwd", ""), cmd[3]).write_bytes(b"new module") - return subprocess.CompletedProcess(cmd, 0, "", "") - - with mock.patch.object(sys, "argv", [TOOL, str(self.src), "--out", str(out)]), \ - mock.patch.object(rdna2spirv.subprocess, "run", side_effect=spirv_tool): - self.assertIsNone(rdna2spirv.main()) - self.assertTrue((out / "ps_x.spv").is_file()) - self.assertTrue((out / "index.json").is_file()) - - -class ValidatedOutput(unittest.TestCase): - def setUp(self): - root = Path(self.enterContext(tempfile.TemporaryDirectory())) - self.src = root / "disasm" / "ps_fixture.s" - self.src.parent.mkdir() - self.src.write_text("\ts_endpgm\n", encoding="utf-8") - (root / "ps_fixture.dxbc").write_bytes(b"DXBC" + bytes(28)) - self.out = root / "spirv" - self.out.mkdir() - self.module = self.out / "ps_fixture.spv" - self.index = self.out / "index.json" - - def translate(self, *, reject_at=None): - def spirv_tool(cmd, **kwargs): - tool = cmd[0] - if tool == "spirv-as": - Path(kwargs.get("cwd", ""), cmd[3]).write_bytes(b"new module") - elif tool == "spirv-val": - self.assertEqual(Path(kwargs.get("cwd", ""), cmd[-1]).read_bytes(), b"new module") - if reject_at is None: - self.assertFalse(self.module.exists(), "the binary was published before validation") - else: - self.fail(f"unexpected tool: {tool}") - rejected = tool == reject_at - return subprocess.CompletedProcess(cmd, int(rejected), "", "synthetic rejection" if rejected else "") - - output = io.StringIO() - with mock.patch.object(sys, "argv", [TOOL, str(self.src), "--out", str(self.out)]), \ - mock.patch.object(rdna2spirv.subprocess, "run", side_effect=spirv_tool), redirect_stdout(output): - self.exit_code = rdna2spirv.main() - return output.getvalue() - - def test_existing_single_s_file_still_translates(self): - self.assertIn("1 pass spirv-val", self.translate()) - - def test_missing_required_inputs_retire_stale_outputs_and_continue(self): - listing_dir = self.src.parent - root = listing_dir.parent - missing = ("cs_dispatch", "ms_reanchor") - for name in missing: - (root / (name + ".dxbc")).write_bytes((root / "ps_fixture.dxbc").read_bytes()) - (listing_dir / (name + ".s")).write_bytes(self.src.read_bytes()) - (self.out / (name + ".spv")).write_bytes(b"previous module") - (listing_dir / "ms_reanchor.s").write_bytes( - b"\ts_endpgm ; encoding: [0x00,0x00,0x81,0xbf]\n; invalid instruction encoding\n") - self.index.write_bytes(json.dumps(dict.fromkeys(missing, {})).encode()) - self.src = listing_dir - err = io.StringIO() - with redirect_stderr(err): - output = self.translate() - self.assertEqual(self.exit_code, 1) - self.assertIn("3 shaders: 1 translated, 1 pass spirv-val", output) - self.assertIn("2 of 3 selected shaders missing required inputs", err.getvalue()) - for name in missing: - self.assertIn(name, err.getvalue()) - self.assertFalse((self.out / (name + ".spv")).exists()) - self.assertTrue(self.module.exists()) - self.assertEqual(set(json.loads(self.index.read_bytes())), {"ps_fixture"}) - - def test_missing_dispatch_invalidates_completed_shard(self): - src = self.src.with_name("cs_dispatch.s") - src.write_bytes(self.src.read_bytes()) - container = self.src.parent.parent / "ps_fixture.dxbc" - shutil.copyfile(container, container.with_name("cs_dispatch.dxbc")) - part = self.out / "index.part0.json" - stale = self.out / "cs_dispatch.spv" - for interrupted in (False, True): - with self.subTest(interrupted=interrupted): - selection = src - if interrupted: - # The compute input retires its module, then the next listing hits a read error. - container.unlink() - container.mkdir() - selection = src.parent - stale.write_bytes(b"old compute") - self.module.write_bytes(b"previous pixel") - part.write_bytes(b'{"cs_dispatch": {}, "ps_fixture": {}}') - self.index.write_bytes(part.read_bytes()) - result = subprocess.run([sys.executable, "-I", TOOL, str(selection), "--out", str(self.out), - "--shard", "0/1"], capture_output=True, text=True) - self.assertEqual(result.returncode, 1, result.stderr) - self.assertIn("missing translation input", result.stderr) - if interrupted: - self.assertIn("ps_fixture.dxbc", result.stderr) - self.assertFalse(part.exists()) - self.assertFalse(self.index.exists()) - self.assertFalse(stale.exists()) - self.assertEqual(self.module.read_bytes(), b"previous pixel") - - @unittest.skipUnless(shutil.which("spirv-as") and shutil.which("spirv-val"), "requires SPIRV-Tools") - def test_failed_shard_retry_cannot_be_merged(self): - def run(out, *args, hide_tools=False): - env = os.environ.copy() - if hide_tools: - env["PATH"] = str(self.out) - return subprocess.run([sys.executable, "-I", TOOL, str(self.src.parent), - "--out", str(out), *args], env=env, capture_output=True, text=True) - - def success(out, *args): - result = run(out, *args) - self.assertEqual(result.returncode, 0, result.stderr) - - def snapshot(out): - return {p.name: p.read_bytes() for p in out.iterdir() if p.is_file()} - - self.src.with_name("ps_other.s").write_bytes(self.src.read_bytes()) - shutil.copyfile(self.src.parent.parent / "ps_fixture.dxbc", self.src.parent.parent / "ps_other.dxbc") - for shard in ("0/2", "1/2"): - success(self.out, "--shard", shard) - success(self.out, "--merge") - baseline = snapshot(self.out) - self.assertEqual(set(json.loads(self.index.read_bytes())), {"ps_fixture", "ps_other"}) - for assembler in ("spirv-as", "python"): - with self.subTest(assembler=assembler): - value = 1 if assembler == "spirv-as" else 2 - self.src.write_bytes(f"\tv_mov_b32_e32 v0, {value}\n\ts_endpgm\n".encode()) - result = run(self.out, "--shard", "0/2", "--assembler", assembler, hide_tools=True) - self.assertFalse(self.index.exists()) - merge = run(self.out, "--merge") - self.assertEqual(merge.returncode, 2, merge.stdout) - self.assertEqual(result.returncode, 2, result.stderr) - self.assertIn("SPIRV-Tools", result.stderr) - self.assertFalse((self.out / "index.part0.json").exists()) - for name in ("ps_fixture.spv", "ps_other.spv", "shard1.json", "index.part1.json"): - self.assertEqual((self.out / name).read_bytes(), baseline[name], name) - success(self.out, "--shard", "0/2") - success(self.out, "--merge") - self.assertNotEqual(self.module.read_bytes(), baseline[self.module.name]) - baseline = snapshot(self.out) - fresh = self.out.with_name("fresh") - for shard in ("0/2", "1/2"): - success(fresh, "--shard", shard) - success(fresh, "--merge") - self.assertEqual(snapshot(self.out), snapshot(fresh)) - - def test_missing_assembler_is_one_setup_error(self): - err = io.StringIO() - with mock.patch.object(sys, "argv", [TOOL, str(self.src), "--out", str(self.out)]), \ - mock.patch.object(rdna2spirv.subprocess, "run", - side_effect=FileNotFoundError(2, "No such file or directory", "spirv-as")), \ - redirect_stdout(io.StringIO()), redirect_stderr(err): - code = rdna2spirv.main() - message = err.getvalue() - self.assertEqual(code, 2, message) - self.assertIn("spirv-as", message) - self.assertIn("SPIRV-Tools", message) - self.assertNotIn("Traceback", message) - self.assertEqual(len(message.strip().splitlines()), 1, message) - self.assertFalse(self.module.exists()) - self.assertEqual(list(self.out.glob("*.tmp")), []) - - def test_missing_validator_does_not_publish_the_module(self): - def spirv_tool(cmd, **kwargs): - if cmd[0] == "spirv-as": - Path(kwargs.get("cwd", ""), cmd[3]).write_bytes(b"new module") - return subprocess.CompletedProcess(cmd, 0, "", "") - raise FileNotFoundError(2, "No such file or directory", "spirv-val") - - err = io.StringIO() - with mock.patch.object(sys, "argv", [TOOL, str(self.src), "--out", str(self.out)]), \ - mock.patch.object(rdna2spirv.subprocess, "run", side_effect=spirv_tool), \ - redirect_stdout(io.StringIO()), redirect_stderr(err): - code = rdna2spirv.main() - message = err.getvalue() - self.assertEqual(code, 2, message) - self.assertIn("spirv-val", message) - self.assertIn("SPIRV-Tools", message) - self.assertNotIn("Traceback", message) - self.assertEqual(len(message.strip().splitlines()), 1, message) - self.assertFalse(self.module.exists()) - self.assertFalse(self.index.exists()) - self.assertEqual(list(self.out.glob("*.tmp")), []) - - def test_validator_rejection_does_not_publish_binary(self): - self.assertIn("INVALID: synthetic rejection", self.translate(reject_at="spirv-val")) - self.assertFalse(self.module.exists()) - self.assertEqual(json.loads(self.index.read_text(encoding="utf-8")), {}) - self.assertTrue((self.out / "ps_fixture.spvasm").is_file()) - self.assertEqual(list(self.out.glob("*.tmp")), []) - - def test_rejection_clears_retried_shader_but_preserves_unrelated_output(self): - other = self.out / "cs_other.spv" - other.write_bytes(b"unrelated module") - previous = {"cs_other": {"stage": "cs"}} - for tool in ("spirv-as", "spirv-val"): - with self.subTest(tool=tool): - self.module.write_bytes(b"old module") - self.index.write_text(json.dumps({**previous, "ps_fixture": {"stage": "ps"}}), encoding="utf-8") - self.assertIn("INVALID: synthetic rejection", self.translate(reject_at=tool)) - self.assertFalse(self.module.exists()) - self.assertEqual(json.loads(self.index.read_text(encoding="utf-8")), previous) - self.assertEqual(other.read_bytes(), b"unrelated module") - - def test_unsupported_clears_retried_shader_but_preserves_unrelated_output(self): - # s_barrier is compute-only, so this PS is Unsupported before any SPIR-V tool runs. A module an - # earlier run published for it must not survive: the index is make_game.py's proof of completion. - self.src.write_text("\ts_barrier\n\ts_endpgm\n", encoding="utf-8") - other = self.out / "cs_other.spv" - other.write_bytes(b"unrelated module") - previous = {"cs_other": {"stage": "cs"}} - self.module.write_bytes(b"old module") - self.index.write_text(json.dumps({**previous, "ps_fixture": {"stage": "ps"}}), encoding="utf-8") - output = self.translate() - self.assertIn("s_barrier outside compute", output) - self.assertFalse(self.module.exists()) - self.assertEqual(json.loads(self.index.read_text(encoding="utf-8")), previous) - self.assertEqual(other.read_bytes(), b"unrelated module") - self.assertEqual(list(self.out.glob("*.tmp")), []) - - def test_translator_error_clears_retried_shader(self): - self.module.write_bytes(b"old module") - self.index.write_text(json.dumps({"ps_fixture": {"stage": "ps"}}), encoding="utf-8") - output = io.StringIO() - with mock.patch.object(rdna2spirv, "translate", side_effect=ValueError("synthetic translator error")), \ - mock.patch.object(sys, "argv", [TOOL, str(self.src), "--out", str(self.out)]), \ - redirect_stdout(output): - rdna2spirv.main() - self.assertIn("translator error ValueError", output.getvalue()) - self.assertFalse(self.module.exists()) - self.assertEqual(json.loads(self.index.read_text(encoding="utf-8")), {}) - - def test_translator_bug_in_one_program_does_not_end_the_run(self): - for error in (AssertionError("synthetic assert"), TypeError("synthetic"), AttributeError("synthetic")): - with self.subTest(error=type(error).__name__): - self.module.write_bytes(b"old module") - self.index.write_text(json.dumps({"ps_fixture": {"stage": "ps"}}), encoding="utf-8") - output = io.StringIO() - with mock.patch.object(rdna2spirv, "translate", side_effect=error), \ - mock.patch.object(sys, "argv", [TOOL, str(self.src), "--out", str(self.out)]), \ - redirect_stdout(output): - rdna2spirv.main() - self.assertIn(f"translator error {type(error).__name__}", output.getvalue()) - self.assertFalse(self.module.exists()) - self.assertEqual(json.loads(self.index.read_text(encoding="utf-8")), {}) - - def test_validation_success_publishes_binary_and_metadata(self): - self.assertIn("1 pass spirv-val", self.translate()) - self.assertEqual(self.module.read_bytes(), b"new module") - self.assertIn("ps_fixture", json.loads(self.index.read_text(encoding="utf-8"))) - - -class EmptyShader(unittest.TestCase): - """A .s with no tab-indented instruction parses to an empty shader. - - It used to translate to a module that passes spirv-val, lands in index.json and does no work at all, which is - what a hand-written or re-indented .s looks like: found while writing a fixture with spaces instead of tabs. - """ - - def test_no_instructions_is_reported_and_no_module_is_published(self): - with tempfile.TemporaryDirectory() as tmp: - src = os.path.join(tmp, "disasm") - os.mkdir(src) - with open(os.path.join(src, "ps_empty.s"), "w", encoding="utf-8") as f: - f.write("; ps_empty code 0x0..0x0 (synthetic), gfx1013, 0 invalid words\n s_endpgm\n") - with open(os.path.join(tmp, "ps_empty.dxbc"), "wb") as f: - f.write(b"DXBC" + bytes(28)) - out = os.path.join(tmp, "spirv") - p = subprocess.run([sys.executable, "-I", TOOL, src, "--out", out], capture_output=True, text=True, errors="replace") - self.assertEqual(p.returncode, 0, p.stderr) - self.assertIn("0 translated", p.stdout, p.stdout) - self.assertIn("no instructions (nothing tab-indented?)", p.stdout, p.stdout) - self.assertFalse(os.path.exists(os.path.join(out, "ps_empty.spv"))) - - -class PopsInvocationInterlock(unittest.TestCase): - """SHADER-350: POPS pixel interlock shaders must emit OpBeginInvocationInterlockEXT and OpEndInvocationInterlockEXT.""" - - def test_straight_line_pops_pixel_shader_emits_begin_and_end_interlock(self): - gen = rdna2spirv.Gen("ps") - gen.uses_pops = True - gen.body = ["OpNoOp"] - spv = rdna2spirv.assemble(gen) - self.assertEqual(spv.count("OpBeginInvocationInterlockEXT"), 1) - self.assertEqual(spv.count("OpEndInvocationInterlockEXT"), 1) - self.assertLess(spv.index("OpBeginInvocationInterlockEXT"), spv.index("OpEndInvocationInterlockEXT")) - - def test_branching_pops_pixel_shader_emits_begin_and_end_interlock(self): - gen = rdna2spirv.Gen("ps") - gen.uses_pops = True - gen.blocks = [["OpNoOp"]] - gen.succ = [[]] - spv = rdna2spirv.assemble(gen) - self.assertEqual(spv.count("OpBeginInvocationInterlockEXT"), 1) - self.assertEqual(spv.count("OpEndInvocationInterlockEXT"), 1) - self.assertLess(spv.index("OpBeginInvocationInterlockEXT"), spv.index("OpEndInvocationInterlockEXT")) - - def test_non_pops_pixel_shader_omits_interlock_ops(self): - gen = rdna2spirv.Gen("ps") - gen.uses_pops = False - gen.body = ["OpNoOp"] - spv = rdna2spirv.assemble(gen) - self.assertEqual(spv.count("OpBeginInvocationInterlockEXT"), 0) - self.assertEqual(spv.count("OpEndInvocationInterlockEXT"), 0) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/test_rdna2spirv_decode.py b/tests/test_rdna2spirv_decode.py deleted file mode 100644 index 43b08e522..000000000 --- a/tests/test_rdna2spirv_decode.py +++ /dev/null @@ -1,553 +0,0 @@ -from __future__ import annotations - -import os -import struct -import sys -import tempfile -import unittest -import warnings - -ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) -sys.dont_write_bytecode = True -sys.path.insert(0, os.path.join(ROOT, "tools")) - -import rdna2spirv # noqa: E402 - -STUB_DXBC = b"DXBC" + bytes(24) + struct.pack("> 2) != 0x35) and not VOP3P (0x00 != 0xCC) - raw[3] = 0x00 - - # Diff at bit 41 (SRC1) - val_printed = int.from_bytes(printed, "little") | (0x80 << 41) - p_bytes = val_printed.to_bytes(8, "little") - self.assertFalse(rdna2spirv.same_encoding(bytes(raw), p_bytes, "v_mov_b32", 2)) - - # Diff at bit 14 - val_printed = int.from_bytes(printed, "little") | (1 << 14) - p_bytes = val_printed.to_bytes(8, "little") - self.assertFalse(rdna2spirv.same_encoding(bytes(raw), p_bytes, "v_pk_add_f16", 3)) - - def test_vop3_boundary_and_opcode_checks(self): - # VOP3 byte 3 has (byte >> 2) == 0x35, e.g. 0xD4 (0xD4 >> 2 == 0x35) - raw = bytearray(8) - raw[3] = 0xD4 - val_raw = int.from_bytes(raw, "little") - - # 1. Unused SRC1 (bits 49:41): raw stored 0, printed 0x80 -> tolerated - val_printed = val_raw | (0x80 << 41) - printed = val_printed.to_bytes(8, "little") - self.assertTrue(rdna2spirv.same_encoding(bytes(raw), printed, "v_rcp_f32", 2)) - - # Raw has non-zero at SRC1: rejected - raw_nonzero = (val_raw | (1 << 41)).to_bytes(8, "little") - self.assertFalse(rdna2spirv.same_encoding(raw_nonzero, printed, "v_rcp_f32", 2)) - - # Printed has invalid diff value (not 0x80): rejected - val_printed_bad = val_raw | (0x81 << 41) - self.assertFalse(rdna2spirv.same_encoding(bytes(raw), val_printed_bad.to_bytes(8, "little"), "v_rcp_f32", 2)) - val_printed_bad2 = val_raw | (0x40 << 41) - self.assertFalse(rdna2spirv.same_encoding(bytes(raw), val_printed_bad2.to_bytes(8, "little"), "v_rcp_f32", 2)) - - # 2. Unused SRC2 (bits 58:50): raw stored 0, printed 0x80 -> tolerated - val_printed2 = val_raw | (0x80 << 50) - printed2 = val_printed2.to_bytes(8, "little") - self.assertTrue(rdna2spirv.same_encoding(bytes(raw), printed2, "v_sub_f32", 3)) - - # Raw has non-zero at SRC2: rejected - raw_nonzero2 = (val_raw | (1 << 50)).to_bytes(8, "little") - self.assertFalse(rdna2spirv.same_encoding(raw_nonzero2, printed2, "v_rcp_f32", 2)) - - # 3. Both SRC1 and SRC2 unused fields stored 0, printed 0x80 -> tolerated - val_both = val_raw | (0x80 << 41) | (0x80 << 50) - printed_both = val_both.to_bytes(8, "little") - self.assertTrue(rdna2spirv.same_encoding(bytes(raw), printed_both, "v_rcp_f32", 2)) - - # 4. Other bits modified (e.g. bit 0) -> rejected - val_other = val_both | 1 - self.assertFalse(rdna2spirv.same_encoding(bytes(raw), val_other.to_bytes(8, "little"), "v_rcp_f32", 2)) - - def test_vop3_implicit_and_scalar_destinations(self): - raw = (0xD4 << 24).to_bytes(8, "little") - val_raw = int.from_bytes(raw, "little") - src1 = (val_raw | (0x80 << 41)).to_bytes(8, "little") - src2 = (val_raw | (0x80 << 50)).to_bytes(8, "little") - # Both comparison inputs are used even when the EXEC destination is implicit. - self.assertFalse(rdna2spirv.same_encoding(raw, src1, "v_cmpx_lt_f16_e64", 2)) - self.assertTrue(rdna2spirv.same_encoding(raw, src2, "v_cmpx_lt_f16_e64", 2)) - # The carry-out destination is not a source. Only the carry-in form uses SRC2. - self.assertTrue(rdna2spirv.same_encoding(raw, src2, "v_add_co_u32", 4)) - self.assertFalse(rdna2spirv.same_encoding(raw, src2, "v_add_co_ci_u32", 5)) - - def test_vop3p_boundary_and_packed_opcodes(self): - # VOP3P byte 3 is 0xCC - raw = bytearray(8) - raw[3] = 0xCC - val_raw = int.from_bytes(raw, "little") - - # Two-source packed ops: bit 14 (op_sel_hi[2]) diff is tolerated - val_p14 = val_raw | (1 << 14) - printed14 = val_p14.to_bytes(8, "little") - - two_src_ops = ("v_pk_add_f16", "v_pk_mul_f16", "v_pk_sub_f16", "v_pk_min_f16", "v_pk_max_f16") - for op in two_src_ops: - with self.subTest(op=op): - self.assertTrue(rdna2spirv.same_encoding(bytes(raw), printed14, op, 3)) - - # Three-source packed ops (fma/mad): bit 14 diff is NOT tolerated - three_src_ops = ("v_pk_fma_f16", "v_pk_mad_i16", "v_pk_fma_i16", "v_pk_mad_u16") - for op in three_src_ops: - with self.subTest(op=op): - self.assertFalse(rdna2spirv.same_encoding(bytes(raw), printed14, op, 4)) - - # Non-packed ops with VOP3P encoding: bit 14 diff is NOT tolerated - for op in ("v_mov_b32", "v_add_f32", "s_mov_b32"): - with self.subTest(op=op): - self.assertFalse(rdna2spirv.same_encoding(bytes(raw), printed14, op, 3)) - - # A two-source packed op tolerates both defaults, but has a live SRC1. - val_defaults = val_raw | (1 << 14) | (0x80 << 50) - printed_defaults = val_defaults.to_bytes(8, "little") - self.assertTrue(rdna2spirv.same_encoding(bytes(raw), printed_defaults, "v_pk_add_f16", 3)) - changed_src1 = (val_defaults | (0x80 << 41)).to_bytes(8, "little") - self.assertFalse(rdna2spirv.same_encoding(bytes(raw), changed_src1, "v_pk_add_f16", 3)) - - # Extra bit modified -> rejected - bad = (val_defaults | 2).to_bytes(8, "little") - self.assertFalse(rdna2spirv.same_encoding(bytes(raw), bad, "v_pk_add_f16", 3)) - - -class TestBaseOpDecoder(unittest.TestCase): - """Exercise base_op() opcode suffix stripping.""" - - def test_strip_standard_suffixes(self): - self.assertEqual(rdna2spirv.base_op("v_add_f32_e32"), "v_add_f32") - self.assertEqual(rdna2spirv.base_op("v_fma_f32_e64"), "v_fma_f32") - self.assertEqual(rdna2spirv.base_op("v_mov_b32_sdwa"), "v_mov_b32") - self.assertEqual(rdna2spirv.base_op("v_mov_b32_dpp"), "v_mov_b32") - - def test_base_op_boundary_cases(self): - self.assertEqual(rdna2spirv.base_op("s_endpgm"), "s_endpgm") - self.assertEqual(rdna2spirv.base_op("exp"), "exp") - self.assertEqual(rdna2spirv.base_op("v_mov_b32"), "v_mov_b32") - # Suffix embedded in name but not at the end - self.assertEqual(rdna2spirv.base_op("v_add_e32_co"), "v_add_e32_co") - self.assertEqual(rdna2spirv.base_op("v_sub_e64_co"), "v_sub_e64_co") - # Exact suffix string - self.assertEqual(rdna2spirv.base_op("_e32"), "") - self.assertEqual(rdna2spirv.base_op("_e64"), "") - self.assertEqual(rdna2spirv.base_op("_sdwa"), "") - self.assertEqual(rdna2spirv.base_op("_dpp"), "") - # Empty string and short identifiers - self.assertEqual(rdna2spirv.base_op(""), "") - self.assertEqual(rdna2spirv.base_op("v"), "v") - - -class TestFormatDecoderBoundary(unittest.TestCase): - """Exercise typed-buffer format decoding functions and boundaries in Gen.""" - - def setUp(self): - self.gen = rdna2spirv.Gen("ps") - - def test_invalid_format_codes_raise_unsupported(self): - for code in (0, -1, 999, 255, 100, 127): # 42 (10_11_11 SINT) is a format since #2022 and #2432 - with self.subTest(code=code): - with self.assertRaisesRegex(rdna2spirv.Unsupported, r"format .* \(not in FORMATS\)"): - self.gen.decode_format(["%w0", "%w1", "%w2", "%w3"], code) - - with self.assertRaisesRegex(rdna2spirv.Unsupported, r"format .* \(not in FORMATS\)"): - self.gen.encode_format(["%f0"], ["%i0"], code) - - def test_decode_format_all_kinds_produce_4_components(self): - words = [f"%w{i}" for i in range(4)] - for code, (size, kind, widths) in rdna2spirv.Gen.FORMATS.items(): - with self.subTest(code=code, kind=kind): - out = self.gen.decode_format(words, code) - self.assertEqual(len(out), 4, f"format {code} ({kind}) must yield exactly 4 components") - - def test_decode_format_short_words_channel_replication(self): - # 1-channel format 22 (f32, (32,)): replicates word 0 across all 4 components - out1 = self.gen.decode_format(["%w0"], 22) - self.assertEqual(out1, ["%w0", "%w0", "%w0", "%w0"]) - - # 2-channel format 64 (f32, (32, 32)): replicates words [0, 1] as [0, 1, 0, 1] - out2 = self.gen.decode_format(["%w0", "%w1"], 64) - self.assertEqual(out2, ["%w0", "%w1", "%w0", "%w1"]) - - # 3-channel format 74 (f32, (32, 32, 32)): replicates words [0, 1, 2] as [0, 1, 2, 0] - out3 = self.gen.decode_format(["%w0", "%w1", "%w2"], 74) - self.assertEqual(out3, ["%w0", "%w1", "%w2", "%w0"]) - - # 4-channel format 77 (f32, (32, 32, 32, 32)): keeps words [0, 1, 2, 3] - out4 = self.gen.decode_format(["%w0", "%w1", "%w2", "%w3"], 77) - self.assertEqual(out4, ["%w0", "%w1", "%w2", "%w3"]) - - # u32 format 20 (1-comp) and i32 format 21 (1-comp) - self.assertEqual(self.gen.decode_format(["%u0"], 20), ["%u0", "%u0", "%u0", "%u0"]) - self.assertEqual(self.gen.decode_format(["%i0"], 21), ["%i0", "%i0", "%i0", "%i0"]) - - def test_decode_format_fixed_vs_dynamic_normalization(self): - words = ["%w0", "%w1", "%w2", "%w3"] - # UNORM format 1 (8,) - self.assertEqual(len(self.gen.tbuffer_norm_fns), 0) - self.gen.decode_format(words, 1, fixed=True) - self.assertIn(8, self.gen.tbuffer_norm_fns) - - # Dynamic UNORM format 7 (16,) without fixed does not add to tbuffer_norm_fns - fns_count = len(self.gen.tbuffer_norm_fns) - self.gen.decode_format(words, 7, fixed=False) - self.assertEqual(len(self.gen.tbuffer_norm_fns), fns_count) - - # decode_any_format (one OpIEqual/OpSelect per format code) went away with SHADER-849's table decode; - # tests/semantic/test_format_decode_table.py checks that path, and format_decode_call is checked below. - - def test_format_decode_call_builds_and_caches_function(self): - words = ["%w0", "%w1", "%w2", "%w3"] - self.assertIsNone(self.gen.fmt_fn) - comps1 = self.gen.format_decode_call("%fmt_var", words) - self.assertEqual(len(comps1), 4) - self.assertIsNotNone(self.gen.fmt_fn) - first_fn = self.gen.fmt_fn - - # Subsequent call reuses the cached function - comps2 = self.gen.format_decode_call("%fmt_var2", words) - self.assertEqual(len(comps2), 4) - self.assertIs(self.gen.fmt_fn, first_fn) - - def test_encode_format_saturation_and_boundary(self): - fcomps = ["%f0", "%f1", "%f2", "%f3"] - icomps = ["%i0", "%i1", "%i2", "%i3"] - - # Narrow uint format 60 (8, 8, 8, 8): must saturate each component using UMin - initial_lines = len(self.gen.body) - res60 = self.gen.encode_format(fcomps, icomps, 60) - self.assertEqual(len(res60), 1) - emitted = "\n".join(self.gen.body[initial_lines:]) - self.assertIn("OpExtInst %uint %glsl UMin", emitted) - - # f32 format 64 (2 comps): passes through first 2 fcomps - self.assertEqual(self.gen.encode_format(fcomps, icomps, 64), ["%f0", "%f1"]) - - # u32 format 72 (3 comps): passes through first 3 icomps - self.assertEqual(self.gen.encode_format(fcomps, icomps, 72), ["%i0", "%i1", "%i2"]) - - def test_int_format_masks_structure(self): - u_mask, si_mask = rdna2spirv.Gen.int_format_masks() - self.assertEqual(len(u_mask), 16) - self.assertEqual(len(si_mask), 16) - self.assertTrue(all(isinstance(x, int) for x in u_mask)) - self.assertTrue(all(isinstance(x, int) for x in si_mask)) - - flags = self.gen.fmt_int_flags("%t_word1") - self.assertEqual(len(flags), 2) - emitted = "\n".join(self.gen.body) - self.assertIn("OpBitFieldUExtract %uint %t_word1", emitted) - - -class TestInstructionDecoderBoundary(unittest.TestCase): - """Exercise opcode decoder failure modes and boundary parameter checks in Gen.""" - - def setUp(self): - self.gen = rdna2spirv.Gen("ps") - - def test_invalid_opcodes_raise_unsupported(self): - invalid_ops = ("v_bogus_fake_op", "s_not_an_instruction", "", "12345", "v_!@#$%") - for op in invalid_ops: - with self.subTest(op=op): - with self.assertRaises(rdna2spirv.Unsupported) as cm: - self.gen._insn({"op": op, "args": [], "mods": []}) - self.assertEqual(str(cm.exception), op) - - def test_mode_opcodes_without_immediates(self): - for op, error in (("s_denorm_mode", "denormal mode"), ("s_round_mode", "requires an immediate")): - with self.subTest(op=op), self.assertRaisesRegex(rdna2spirv.Unsupported, error): - self.gen._insn({"op": op, "args": [], "mods": []}) - - def test_dpp_invalid_opcodes_and_boundary_modifiers(self): - # DPP combined with SDWA - with self.assertRaisesRegex(rdna2spirv.Unsupported, "DPP with SDWA"): - self.gen.insn({"op": "v_mov_b32_sdwa_dpp", "args": [], "mods": []}) - - # Missing DPP control (none of dpp8, quad_perm, or row_* supplied) - with self.assertRaisesRegex(rdna2spirv.Unsupported, "DPP control"): - self.gen.insn({"op": "v_mov_b32_dpp", "args": [], "mods": []}) - - # Conflicting DPP controls (quad_perm and row_mirror simultaneously) - with self.assertRaisesRegex(rdna2spirv.Unsupported, "DPP controls"): - self.gen.insn({ - "op": "v_mov_b32_dpp", - "args": [{"k": "vgpr", "r": 0}, {"k": "vgpr", "r": 1}], - "mods": ["quad_perm:[0,1,2,3]", "row_mirror"], - }) - - # DPP invalid flag (bound_ctrl out of range 0..1) - with self.assertRaisesRegex(rdna2spirv.Unsupported, "DPP flag"): - self.gen.insn({ - "op": "v_mov_b32_dpp", - "args": [{"k": "vgpr", "r": 0}, {"k": "vgpr", "r": 1}], - "mods": ["quad_perm:[0,1,2,3]", "bound_ctrl:2"], - }) - - # DPP out-of-range row_mask (> 0xF) - with self.assertRaisesRegex(rdna2spirv.Unsupported, "DPP mask"): - self.gen.insn({ - "op": "v_mov_b32_dpp", - "args": [{"k": "vgpr", "r": 0}, {"k": "vgpr", "r": 1}], - "mods": ["quad_perm:[0,1,2,3]", "row_mask:0x10"], - }) - - # DPP invalid non-integer modifier - with self.assertRaisesRegex(rdna2spirv.Unsupported, "DPP row_mask"): - self.gen.insn({ - "op": "v_mov_b32_dpp", - "args": [{"k": "vgpr", "r": 0}, {"k": "vgpr", "r": 1}], - "mods": ["quad_perm:[0,1,2,3]", "row_mask:invalid_hex"], - }) - - # DPP operands boundary (fewer than 2 operands) - with self.assertRaisesRegex(rdna2spirv.Unsupported, "DPP operands"): - self.gen.insn({ - "op": "v_mov_b32_dpp", - "args": [{"k": "vgpr", "r": 0}], - "mods": ["quad_perm:[0,1,2,3]"], - }) - - -class TestTranslateIntegrationBoundaryChecks(unittest.TestCase): - """End-to-end translation boundary checks on synthetic shaders with truncated blobs or invalid opcodes.""" - - def test_short_and_truncated_native_blob(self): - with tempfile.TemporaryDirectory() as tmp: - disasm = os.path.join(tmp, "disasm") - fssm = os.path.join(tmp, "fssm") - os.makedirs(disasm) - os.makedirs(fssm) - - with open(os.path.join(tmp, "ps_trunc.dxbc"), "wb") as f: - f.write(STUB_DXBC) - - # Native blob is only 4 bytes (shorter than 8-byte instruction encoding) - with open(os.path.join(fssm, "ps_trunc.fssm"), "wb") as f: - f.write(bytes(4)) - - shader_text = ( - "ps_trunc.s:\n" - "\tv_mov_b32 v0, 1.0 ; encoding: [0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00]\n" - "; invalid instruction encoding at 0x10\n" - "\texp mrt0 v0, v0, v0, v0 done vm ; encoding: [0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00]\n" - "\ts_endpgm ; encoding: [0x00,0x00,0x81,0xbf]\n" - ) - src = os.path.join(disasm, "ps_trunc.s") - with open(src, "w", encoding="utf-8") as f: - f.write(shader_text) - - with warnings.catch_warnings(): - warnings.simplefilter("ignore", ResourceWarning) - with self.assertRaisesRegex(rdna2spirv.Unsupported, "undecodable words \\(cannot re-anchor\\)"): - rdna2spirv.translate(src) - - def test_fall_through_into_undecodable_words_is_refused(self): - # SHADER-813: llvm-mc skips words it cannot decode (e.g. some v_dot4_i32_i8 op_sel forms). When a reachable - # instruction runs into them the path used to end there, so the export after the gap was dropped and the - # module translated, valid and silent. It must be refused instead. - mov0 = [0xF2, 0x02, 0x00, 0x7E] - mov1 = [0xF2, 0x02, 0x02, 0x7E] - export = [0x0F, 0x18, 0x00, 0xF8, 0x00, 0x01, 0x00, 0x01] - endpgm = [0x00, 0x00, 0x81, 0xBF] - gap = [0x00, 0x50, 0x16, 0xCC, 0x01, 0x05, 0x0E, 0x0C] # the word from the finding, as llvm-mc leaves it - - def enc(words): - return ",".join(f"0x{b:02x}" for b in words) - - with tempfile.TemporaryDirectory() as tmp: - disasm = os.path.join(tmp, "disasm") - fssm = os.path.join(tmp, "fssm") - os.makedirs(disasm) - os.makedirs(fssm) - with open(os.path.join(tmp, "ps_gap.dxbc"), "wb") as f: - f.write(STUB_DXBC) - with open(os.path.join(fssm, "ps_gap.fssm"), "wb") as f: - f.write(bytes(mov0 + mov1 + gap + export + endpgm)) - shader_text = ( - "ps_gap.s:\n" - f"\tv_mov_b32_e32 v0, 1.0 ; encoding: [{enc(mov0)}]\n" - f"\tv_mov_b32_e32 v1, 1.0 ; encoding: [{enc(mov1)}]\n" - "; invalid instruction encoding at 0x8\n" - f"\texp mrt0 v0, v1, v0, v1 done vm ; encoding: [{enc(export)}]\n" - f"\ts_endpgm ; encoding: [{enc(endpgm)}]\n" - ) - src = os.path.join(disasm, "ps_gap.s") - with open(src, "w", encoding="utf-8") as f: - f.write(shader_text) - with warnings.catch_warnings(): - warnings.simplefilter("ignore", ResourceWarning) - with self.assertRaisesRegex(rdna2spirv.Unsupported, "fall-through into undecodable words"): - rdna2spirv.translate(src) - - def test_fall_through_into_undecodable_words_at_the_end_of_the_range_is_refused(self): - # SHADER-813 follow-up (@Flyander): the skipped words come after the last printed instruction but inside the - # code range the header declares, so the path runs into them as well - mov0 = [0xF2, 0x02, 0x00, 0x7E] - mov1 = [0xF2, 0x02, 0x02, 0x7E] - gap = [0x00, 0x50, 0x16, 0xCC, 0x01, 0x05, 0x0E, 0x0C] - - def enc(words): - return ",".join(f"0x{b:02x}" for b in words) - - with tempfile.TemporaryDirectory() as tmp: - disasm = os.path.join(tmp, "disasm") - fssm = os.path.join(tmp, "fssm") - os.makedirs(disasm) - os.makedirs(fssm) - with open(os.path.join(tmp, "ps_tail.dxbc"), "wb") as f: - f.write(STUB_DXBC) - with open(os.path.join(fssm, "ps_tail.fssm"), "wb") as f: - f.write(bytes(mov0 + mov1 + gap)) - shader_text = ( - "; ps_tail code 0x0..0x10 (header), gfx1013, 2 invalid words\n" - f"\tv_mov_b32_e32 v0, 1.0 ; encoding: [{enc(mov0)}]\n" - f"\tv_mov_b32_e32 v1, 1.0 ; encoding: [{enc(mov1)}]\n" - "; invalid instruction encoding at 0x8\n" - ) - src = os.path.join(disasm, "ps_tail.s") - with open(src, "w", encoding="utf-8") as f: - f.write(shader_text) - with warnings.catch_warnings(): - warnings.simplefilter("ignore", ResourceWarning) - with self.assertRaisesRegex(rdna2spirv.Unsupported, "fall-through into undecodable words"): - rdna2spirv.translate(src) - - def test_native_blob_mismatched_encoding_reachable_normalized(self): - with tempfile.TemporaryDirectory() as tmp: - disasm = os.path.join(tmp, "disasm") - fssm = os.path.join(tmp, "fssm") - os.makedirs(disasm) - os.makedirs(fssm) - - with open(os.path.join(tmp, "ps_norm.dxbc"), "wb") as f: - f.write(STUB_DXBC) - - # Blob has sufficient length (64 bytes of zeros), but encoding bytes differ completely. - # Re-anchoring fails to match, marks instruction normalized, and reachable_code rejects it. - with open(os.path.join(fssm, "ps_norm.fssm"), "wb") as f: - f.write(bytes(64)) - - shader_text = ( - "ps_norm.s:\n" - "\tv_mov_b32 v0, 1.0 ; encoding: [0x11,0x22,0x33,0x44,0x55,0x66,0x77,0x88]\n" - "; invalid instruction encoding at 0x10\n" - "\texp mrt0 v0, v0, v0, v0 done vm ; encoding: [0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00]\n" - "\ts_endpgm ; encoding: [0x00,0x00,0x81,0xbf]\n" - ) - src = os.path.join(disasm, "ps_norm.s") - with open(src, "w", encoding="utf-8") as f: - f.write(shader_text) - - with warnings.catch_warnings(): - warnings.simplefilter("ignore", ResourceWarning) - with self.assertRaisesRegex(rdna2spirv.Unsupported, "reachable instruction with normalized encoding"): - rdna2spirv.translate(src) - - def test_invalid_opcode_in_shader_listing(self): - with tempfile.TemporaryDirectory() as tmp: - disasm = os.path.join(tmp, "disasm") - os.makedirs(disasm) - - with open(os.path.join(tmp, "ps_inv.dxbc"), "wb") as f: - f.write(STUB_DXBC) - - shader_text = ( - "ps_inv.s:\n" - "\tv_bogus_unsupported_opcode v0, 1.0\n" - "\texp mrt0 v0, v0, v0, v0 done vm\n" - "\ts_endpgm\n" - ) - src = os.path.join(disasm, "ps_inv.s") - with open(src, "w", encoding="utf-8") as f: - f.write(shader_text) - - with warnings.catch_warnings(): - warnings.simplefilter("ignore", ResourceWarning) - with self.assertRaisesRegex(rdna2spirv.Unsupported, "v_bogus_unsupported_opcode"): - rdna2spirv.translate(src) - - def test_empty_or_no_tab_indented_instructions(self): - with tempfile.TemporaryDirectory() as tmp: - disasm = os.path.join(tmp, "disasm") - os.makedirs(disasm) - - with open(os.path.join(tmp, "ps_empty.dxbc"), "wb") as f: - f.write(STUB_DXBC) - - # Not tab-indented: parse_file ignores non-tabbed lines - shader_text = ( - "ps_empty.s:\n" - "v_mov_b32 v0, 1.0\n" - "s_endpgm\n" - ) - src = os.path.join(disasm, "ps_empty.s") - with open(src, "w", encoding="utf-8") as f: - f.write(shader_text) - - with warnings.catch_warnings(): - warnings.simplefilter("ignore", ResourceWarning) - with self.assertRaisesRegex(rdna2spirv.Unsupported, "no instructions \\(nothing tab-indented\\?\\)"): - rdna2spirv.translate(src) - - def test_invalid_shader_stage_prefix(self): - with tempfile.TemporaryDirectory() as tmp: - disasm = os.path.join(tmp, "disasm") - os.makedirs(disasm) - - with open(os.path.join(tmp, "xx_unknown.dxbc"), "wb") as f: - f.write(STUB_DXBC) - - shader_text = ( - "xx_unknown.s:\n" - "\tv_mov_b32 v0, 1.0\n" - "\ts_endpgm\n" - ) - src = os.path.join(disasm, "xx_unknown.s") - with open(src, "w", encoding="utf-8") as f: - f.write(shader_text) - - with warnings.catch_warnings(): - warnings.simplefilter("ignore", ResourceWarning) - with self.assertRaisesRegex(rdna2spirv.Unsupported, "stage xx"): - rdna2spirv.translate(src) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/test_rdna2spirv_merge.py b/tests/test_rdna2spirv_merge.py deleted file mode 100644 index 84f94d3de..000000000 --- a/tests/test_rdna2spirv_merge.py +++ /dev/null @@ -1,334 +0,0 @@ -"""tools/rdna2spirv.py --merge: an incomplete shard set is refused, not published as a partial index. - - python -I tests/test_rdna2spirv_merge.py -""" -import json -import subprocess -import sys -import tempfile -import unittest -from pathlib import Path - -ROOT = Path(__file__).resolve().parents[1] -sys.path.insert(0, str(ROOT / "tools")) -import rdna2spirv as R # noqa: E402 - -TOOL = ROOT / "tools" / "rdna2spirv.py" - - -class MergeShardPartsTest(unittest.TestCase): - def setUp(self): - self.tmp = tempfile.TemporaryDirectory() - self.addCleanup(self.tmp.cleanup) - self.out = Path(self.tmp.name) - - def part(self, index, doc): - (self.out / f"index.part{index}.json").write_text(json.dumps(doc), encoding="utf-8") - - def marker(self, index, count): - (self.out / f"shard{index}.json").write_text(json.dumps({"index": index, "count": count}), encoding="utf-8") - - def plan(self, jobs): - (self.out / "shards.json").write_text(json.dumps({"jobs": jobs}), encoding="utf-8") - - def merge_error(self): - with self.assertRaises(R.ShardSetError) as cm: - R.merge_shard_parts(str(self.out)) - return str(cm.exception) - - def test_complete_set_merges(self): - self.part(0, {"a": {"r": 1}}) - self.part(1, {"b": {"r": 2}}) - self.marker(0, 2) - self.marker(1, 2) - self.assertEqual(R.merge_shard_parts(str(self.out)), {"a": {"r": 1}, "b": {"r": 2}}) - - def test_a_complete_set_of_empty_parts_is_refused(self): - # Every shard finished but translated nothing: index.json must not say the corpus is done. - self.part(0, {}) - self.part(1, {}) - self.marker(0, 2) - self.marker(1, 2) - self.assertIn("holds no shaders", self.merge_error()) - - def test_a_part_that_is_not_json_is_named(self): - # A shard killed mid-write leaves a truncated part; the merge must say which part to delete, not traceback. - (self.out / "index.part0.json").write_text('{"a": {', encoding="utf-8") - self.marker(0, 1) - message = self.merge_error() - self.assertIn("cannot read", message) - self.assertIn("index.part0.json", message) - self.assertIn("delete that part", message) - - def test_missing_part_is_refused(self): - self.part(0, {"a": {}}) - self.marker(0, 3) - self.marker(1, 3) - self.marker(2, 3) - message = self.merge_error() - self.assertIn("incomplete shard set", message) - self.assertIn("1 of 3", message) - self.assertIn("missing [1, 2]", message) - - def test_extra_part_is_refused(self): - for i in range(3): - self.part(i, {}) - self.marker(i, 2) - message = self.merge_error() - self.assertIn("incomplete shard set", message) - self.assertIn("unexpected [2]", message) - - def test_parts_and_markers_must_match(self): - self.part(0, {}) - self.part(1, {}) - self.marker(0, 2) - self.assertIn("index parts and shard markers disagree", self.merge_error()) - - def test_a_part_without_its_marker_is_refused(self): - # A part left by an older rdna2spirv.py that did not write markers mixed with a newer set. - for i in range(3): - self.part(i, {}) - self.marker(1, 3) - self.marker(2, 3) - message = self.merge_error() - self.assertIn("index parts and shard markers disagree", message) - self.assertIn("parts [0, 1, 2]", message) - self.assertIn("markers [1, 2]", message) - - def test_marker_counts_must_agree(self): - self.part(0, {}) - self.part(1, {}) - self.marker(0, 2) - self.marker(1, 3) - self.assertIn("disagree on the shard count", self.merge_error()) - - def test_plan_count_is_used_without_markers(self): - self.part(0, {}) - self.plan(2) - self.assertIn("incomplete shard set", self.merge_error()) - - def test_legacy_parts_without_metadata_still_merge(self): - self.part(0, {"a": {}}) - self.part(1, {"b": {}}) - self.assertEqual(sorted(R.merge_shard_parts(str(self.out))), ["a", "b"]) - - def test_legacy_set_with_double_digit_indices_merges(self): - for i in range(12): - self.part(i, {str(i): {}}) - self.assertEqual(set(R.merge_shard_parts(str(self.out))), {str(i) for i in range(12)}) - - def test_large_gaps_have_a_bounded_diagnostic(self): - self.part(0, {"a": {}}) - self.part(10_000, {"b": {}}) - for expected in (None, 10_001): - with self.subTest(expected=expected): - if expected: - self.plan(expected) - message = self.merge_error() - self.assertIn("incomplete shard set", message) - self.assertIn("missing [1, 2", message) - self.assertIn("9983 more", message) - self.assertLess(len(message), 300) - - def test_plan_and_markers_that_agree_merge(self): - self.part(0, {"a": {}}) - self.part(1, {"b": {}}) - self.marker(0, 2) - self.marker(1, 2) - self.plan(2) - self.assertEqual(sorted(R.merge_shard_parts(str(self.out))), ["a", "b"]) - - def test_markers_must_match_the_plan_count(self): - self.part(0, {}) - self.part(1, {}) - self.marker(0, 2) - self.marker(1, 2) - self.plan(3) - self.assertIn("shard markers say 2 shards but the plan says 3", self.merge_error()) - - def test_malformed_plan_fails_closed(self): - self.part(0, {}) - self.part(1, {}) - self.marker(0, 2) - self.marker(1, 2) - (self.out / "shards.json").write_text("not json\n", encoding="utf-8") - self.assertIn("cannot read the shard plan", self.merge_error()) - - def test_plan_without_a_usable_job_count_fails_closed(self): - self.part(0, {}) - self.plan(0) - self.assertIn("cannot read the shard plan", self.merge_error()) - - def test_a_gap_is_refused_when_the_count_is_unknown(self): - self.part(0, {}) - self.part(2, {}) - message = self.merge_error() - self.assertIn("not contiguous from 0", message) - self.assertIn("missing [1]", message) - - def test_merge_with_no_parts_is_refused(self): - self.assertIn("no index.part", self.merge_error()) - - def test_a_corrupt_marker_is_refused(self): - self.part(0, {}) - self.marker(0, 2) - (self.out / "shard0.json").write_text("not json\n", encoding="utf-8") - self.assertIn("cannot read the shard marker", self.merge_error()) - - def test_a_marker_without_index_or_count_is_refused(self): - self.part(0, {}) - (self.out / "shard0.json").write_text('{"count": 2}\n', encoding="utf-8") - self.assertIn("is not a shard marker", self.merge_error()) - - def test_unexpected_part_name_is_refused(self): - (self.out / "index.partx.json").write_text("{}", encoding="utf-8") - self.assertIn("not an index.part", self.merge_error()) - - -class MergeCliTest(unittest.TestCase): - def setUp(self): - self.tmp = tempfile.TemporaryDirectory() - self.addCleanup(self.tmp.cleanup) - self.out = Path(self.tmp.name) - - def part(self, index, doc): - (self.out / f"index.part{index}.json").write_text(json.dumps(doc), encoding="utf-8") - - def marker(self, index, count): - (self.out / f"shard{index}.json").write_text(json.dumps({"index": index, "count": count}), encoding="utf-8") - - def run_merge(self): - return subprocess.run([sys.executable, "-I", str(TOOL), str(self.out), "--out", str(self.out), "--merge"], - capture_output=True, text=True, timeout=120) - - def test_cli_refuses_a_complete_set_of_empty_parts(self): - self.part(0, {}) - self.part(1, {}) - self.marker(0, 2) - self.marker(1, 2) - result = self.run_merge() - self.assertEqual(result.returncode, 2, result.stdout + result.stderr) - self.assertIn("holds no shaders", result.stderr) - self.assertNotIn("Traceback", result.stderr) - self.assertFalse((self.out / "index.json").exists()) - - def test_cli_refuses_a_partial_set_and_writes_no_index(self): - self.part(0, {"a": {}}) - self.marker(0, 2) - self.marker(1, 2) - result = self.run_merge() - self.assertEqual(result.returncode, 2, result.stdout + result.stderr) - self.assertIn("ERROR: incomplete shard set", result.stderr) - self.assertNotIn("Traceback", result.stderr) - self.assertFalse((self.out / "index.json").exists()) - - def test_cli_removes_the_previous_index_when_the_merge_fails(self): - # The old index describes the previous corpus; after a failed merge the parts no longer match it. - (self.out / "index.json").write_text(json.dumps({"old": {}}), encoding="utf-8") - self.part(0, {"a": {}}) - self.marker(0, 2) - self.marker(1, 2) - result = self.run_merge() - self.assertEqual(result.returncode, 2, result.stdout + result.stderr) - self.assertIn("ERROR: incomplete shard set", result.stderr) - self.assertFalse((self.out / "index.json").exists()) - - def test_cli_merges_a_complete_set(self): - self.part(0, {"a": {}}) - self.part(1, {"b": {}}) - self.marker(0, 2) - self.marker(1, 2) - result = self.run_merge() - self.assertEqual(result.returncode, 0, result.stdout + result.stderr) - self.assertIn("merged 2 entries", result.stdout) - merged = json.loads((self.out / "index.json").read_text(encoding="utf-8")) - self.assertEqual(sorted(merged), ["a", "b"]) - - - def test_cli_refuses_a_marker_count_that_disagrees_with_the_plan(self): - self.part(0, {}) - self.part(1, {}) - self.marker(0, 2) - self.marker(1, 2) - (self.out / "shards.json").write_text(json.dumps({"jobs": 3}), encoding="utf-8") - result = self.run_merge() - self.assertEqual(result.returncode, 2, result.stdout + result.stderr) - self.assertIn("shard markers say 2 shards but the plan says 3", result.stderr) - self.assertNotIn("Traceback", result.stderr) - self.assertFalse((self.out / "index.json").exists()) - - def test_cli_refuses_a_part_that_is_not_json(self): - (self.out / "index.part0.json").write_text('{"a": {', encoding="utf-8") - self.marker(0, 1) - result = self.run_merge() - self.assertEqual(result.returncode, 2, result.stdout + result.stderr) - self.assertIn("ERROR: cannot read", result.stderr) - self.assertIn("index.part0.json", result.stderr) - self.assertIn("delete that part", result.stderr) - self.assertNotIn("Traceback", result.stderr) - self.assertFalse((self.out / "index.json").exists()) - - def test_cli_refuses_a_malformed_plan(self): - self.part(0, {"a": {}}) - self.part(1, {"b": {}}) - self.marker(0, 2) - self.marker(1, 2) - (self.out / "shards.json").write_text("not json\n", encoding="utf-8") - result = self.run_merge() - self.assertEqual(result.returncode, 2, result.stdout + result.stderr) - self.assertIn("cannot read the shard plan", result.stderr) - self.assertNotIn("Traceback", result.stderr) - self.assertFalse((self.out / "index.json").exists()) - - def test_cli_refuses_a_corrupt_marker(self): - self.part(0, {"a": {}}) - self.marker(0, 2) - (self.out / "shard0.json").write_text("not json\n", encoding="utf-8") - result = self.run_merge() - self.assertEqual(result.returncode, 2, result.stdout + result.stderr) - self.assertIn("cannot read the shard marker", result.stderr) - self.assertNotIn("Traceback", result.stderr) - self.assertFalse((self.out / "index.json").exists()) - - -class ShardRoundTripTest(unittest.TestCase): - """The writer and the merge through the real CLI, on an empty input directory (no .s and no llvm-mc needed).""" - - def setUp(self): - self.tmp = tempfile.TemporaryDirectory() - self.addCleanup(self.tmp.cleanup) - self.src = Path(self.tmp.name) / "src" - self.out = Path(self.tmp.name) / "out" - self.src.mkdir() - self.out.mkdir() - - def run_tool(self, *args): - return subprocess.run([sys.executable, "-I", str(TOOL), str(self.src), "--out", str(self.out), *args], - capture_output=True, text=True, timeout=120) - - def test_a_shard_writes_its_marker_and_part_and_merge_needs_the_whole_set(self): - first = self.run_tool("--shard", "0/2") - self.assertEqual(first.returncode, 0, first.stdout + first.stderr) - self.assertTrue((self.out / "index.part0.json").is_file()) - marker = json.loads((self.out / "shard0.json").read_text(encoding="utf-8")) - self.assertEqual(marker, {"index": 0, "count": 2}) - - partial = self.run_tool("--merge") - self.assertEqual(partial.returncode, 2, partial.stdout + partial.stderr) - self.assertIn("incomplete shard set", partial.stderr) - self.assertFalse((self.out / "index.json").exists()) - - second = self.run_tool("--shard", "1/2") - self.assertEqual(second.returncode, 0, second.stdout + second.stderr) - self.assertTrue((self.out / "index.part1.json").is_file()) - self.assertTrue((self.out / "shard1.json").is_file()) - - # Both shards finished, but over an empty source they hold nothing: the merge refuses to publish {}. - full = self.run_tool("--merge") - self.assertEqual(full.returncode, 2, full.stdout + full.stderr) - self.assertIn("holds no shaders", full.stderr) - self.assertFalse((self.out / "index.json").exists()) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/test_rdna2spirv_pixelinput.py b/tests/test_rdna2spirv_pixelinput.py deleted file mode 100644 index c834d6ef9..000000000 --- a/tests/test_rdna2spirv_pixelinput.py +++ /dev/null @@ -1,312 +0,0 @@ -import pytest -"""SHADER-15: the translator uses the FSSM pixel-input table (interpolant count, fp16 mask). - -All blobs and shaders here are built by hand; no game data is used, and nothing needs -llvm-mc, spirv-as/val or a GPU: the .s listings are written directly in the disassembler -listing format, and values are checked with tests/semantic/spirv_mini_interp.py. - -Rule under test (tools/rdna2spirv.py, PS input path): - * When a sidecar fssm/.fssm next to the disasm directory holds a non-empty - pixel-input table (tools/fssm_header.py), every table position 0..count-1 is declared - as a fragment input at that Location, including positions the code never reads (the - table overcounts the code's distinct v_interp attrs in 775 of 12,101 corpus PS). - Position in the table is the v_interp attr number, not the record's slot byte. - * A 32-bit v_interp read (p1/p2/mov) of a position flagged 16-bit (flag bit 4) sees the - value rounded to f16 (round to nearest, f16 denormals flushed to signed zero, - and back to f32). Reads through the *_f16 - opcodes already narrow to f16 and are unchanged. - * Without a sidecar, or with a sidecar holding no table, the output is byte-identical - to the old code-driven path (no new declarations, no quantization, no new metadata). -""" - -import gc -import os -import struct -import sys -import tempfile -import warnings - -ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) -sys.path.insert(0, os.path.join(ROOT, "tools")) -sys.path.insert(0, os.path.join(ROOT, "tests", "semantic")) - -import rdna2spirv # noqa: E402 -from spirv_mini_interp import run_fragment # noqa: E402 - -# An empty DXBC container (no ISG1): pixel shaders that only read barycentrics through -# v_interp need no input signature. -STUB_DXBC = b"DXBC" + bytes(24) + struct.pack(".s, .dxbc and optionally fssm/.fssm.""" - disasm = tmp_path / "disasm" - disasm.mkdir(exist_ok=True) - (tmp_path / f"{name}.dxbc").write_bytes(STUB_DXBC) - if fssm is not None: - (tmp_path / "fssm").mkdir(exist_ok=True) - (tmp_path / "fssm" / f"{name}.fssm").write_bytes(fssm) - src = disasm / f"{name}.s" - src.write_text(f"; {name} synthetic\n" + body) - return str(src) - - -def translate(path): - with warnings.catch_warnings(): - warnings.simplefilter("ignore", ResourceWarning) # translate() leaves its .dxbc handle to the GC - result = rdna2spirv.translate(path) - gc.collect() - return result - - -def mrt0_words(spvasm, **run_options): - out = run_fragment(spvasm, **run_options) - assert list(out) == ["%out_mrt0"], f"expected exactly one output, got {sorted(out)}" - return tuple(out["%out_mrt0"]) - - -def f16_roundtrip_bits(word): - """Independent oracle: f32 -> f16 (round to nearest even, f16 denormals flushed) -> f32, as bits. - - OpQuantizeToF16 returns +0/-0 for a magnitude below the smallest normal f16, so the oracle - flushes exactly like the interpreter and the hardware are supposed to. - """ - as_float = struct.unpack(" str: - """Create a temporary test compute shader and translate it to SPIR-V assembly text.""" - with tempfile.TemporaryDirectory() as tmp: - disasm_dir = os.path.join(tmp, "disasm") - fssm_dir = os.path.join(tmp, "fssm") - os.makedirs(disasm_dir, exist_ok=True) - os.makedirs(fssm_dir, exist_ok=True) - - with open(os.path.join(tmp, f"{name}.dxbc"), "wb") as f: - f.write(STUB_DXBC) - with open(os.path.join(fssm_dir, f"{name}.fssm"), "wb") as f: - f.write(DEFAULT_CS_FSSM) - - src = os.path.join(disasm_dir, f"{name}.s") - full_body = f"; {name} synthetic test\n{body}\n\ts_endpgm\n" - with open(src, "w", encoding="utf-8") as f: - f.write(full_body) - - return rdna2spirv.translate(src) - - -class TestRdna2SpirvXdxrRules(unittest.TestCase): - def test_buffer_load_ushort(self): - """buffer_load_ushort loads 16 bits zero-extended into destination register.""" - asm = translate_cs("cs_load_ushort", "\tbuffer_load_ushort v0, v1, s[0:3], 0 offen") - self.assertIn("OpConvertUToPtr %_ptr_PSB_arr", asm) - self.assertIn("OpLoad %uint", asm) - self.assertTrue("65535" in asm or "0xffff" in asm.lower()) - - def test_buffer_load_sshort_signed(self): - """buffer_load_sshort loads 16 bits sign-extended into destination register.""" - asm = translate_cs("cs_load_short", "\tbuffer_load_sshort v0, v1, s[0:3], 0 offen") - self.assertIn("OpConvertUToPtr %_ptr_PSB_arr", asm) - self.assertIn("OpLoad %uint", asm) - self.assertIn("OpBitFieldSExtract", asm) - - def test_tbuffer_load_format_8_uint(self): - """tbuffer_load_format_x with BUF_FMT_8_UINT decodes format 5 into uint.""" - asm = translate_cs("cs_tb_8_uint", "\ttbuffer_load_format_x v0, v1, s[0:3], 0 format:[BUF_FMT_8_UINT] offen") - self.assertIn("OpConvertUToPtr %_ptr_PSB_arr", asm) - self.assertIn("OpLoad %uint", asm) - self.assertIn("OpBitFieldUExtract %uint", asm) - - def test_global_atomic_fmax(self): - """global_atomic_fmax emits CAS loop with GLSL NMax.""" - asm = translate_cs("cs_atomic_fmax", "\tglobal_atomic_fmax v0, v1, s[0:1]") - self.assertIn("OpAtomicCompareExchange %uint", asm) - self.assertIn("NMax", asm) - - def test_global_atomic_fmin(self): - """global_atomic_fmin emits CAS loop with GLSL NMin.""" - asm = translate_cs("cs_atomic_fmin", "\tglobal_atomic_fmin v0, v1, s[0:1]") - self.assertIn("OpAtomicCompareExchange %uint", asm) - self.assertIn("NMin", asm) - - def test_global_atomic_fmax_with_glc(self): - """global_atomic_fmax with glc stores the pre-op value into vdst.""" - asm = translate_cs("cs_atomic_fmax_glc", "\tglobal_atomic_fmax v0, v1, v2, s[0:1] glc") - self.assertIn("OpAtomicCompareExchange %uint", asm) - self.assertIn("NMax", asm) - self.assertIn("OpStore", asm) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/test_recomp_census.py b/tests/test_recomp_census.py deleted file mode 100644 index c4130257c..000000000 --- a/tests/test_recomp_census.py +++ /dev/null @@ -1,135 +0,0 @@ -"""Unit tests for tools/recomp_census.py: the .pdata recompiler census. - -The PE fixture is built byte by byte — a minimal PE32+ image whose .pdata lists -three functions over .text: one clean, one containing an unhandled (x87) insn, -one exercising indirect control flow — so the test needs no game files and no -third-party packages. - - python -I tests/test_recomp_census.py -""" -import os -import struct -import sys -import tempfile -import unittest - -ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) -if ROOT not in sys.path: - sys.path.insert(0, ROOT) -TOOLS_DIR = os.path.join(ROOT, "tools") -if TOOLS_DIR not in sys.path: - sys.path.insert(0, TOOLS_DIR) - -import recomp_census as rc # noqa: E402 -import pe_inspect # noqa: E402 - -TEXT_RVA = 0x1000 -TEXT_RAW = 0x200 -TEXT_SIZE = 0x2000 -IMAGE_BASE = 0x140000000 - - -def build_pe() -> bytes: - """PE32+ with .text holding 3 functions and .pdata/.xdata describing them.""" - opt_size = 240 - buf = bytearray(TEXT_RAW + TEXT_SIZE) - buf[0:2] = b"MZ" - struct.pack_into(" None: - at = TEXT_RAW + (rva - TEXT_RVA) - buf[at:at + len(blob)] = blob - - # fn1 @ 0x1000: mov eax,5; add eax,3; ret (clean) - place(0x1000, bytes.fromhex("b805000000" "83c003" "c3")) - # fn2 @ 0x1010: mov eax,1; fldz (x87); ret (gap) - place(0x1010, bytes.fromhex("b801000000" "d9e8" "c3")) - # fn3 @ 0x1020: mov rax,target; jmp rax; ret (indirect) - target = IMAGE_BASE + 0x102F - place(0x1020, bytes.fromhex("48b8" + target.to_bytes(8, "little").hex() + "ffe0" "c3")) - place(0x102F, bytes.fromhex("c3")) - # .pdata: (begin, end, unwind_rva) - entries = [(0x1000, 0x1009, 0x2100), (0x1010, 0x1018, 0x2104), (0x1020, 0x1030, 0x2108)] - for i, (b, e, u) in enumerate(entries): - place(0x2000 + i * 12, struct.pack(" name of its two-path comparison helper -HELPERS = { - "bvh_index": "same_output_path", - "anim_index": "same_report_path", - "gamedata_xml": None, - "gamedata_index": None, - "navmesh_decode": "same_report_path", - "world_census": "same_report_path", -} - - -def load(name): - spec = importlib.util.spec_from_file_location(f"case_{name}", TOOLS / f"{name}.py") - module = importlib.util.module_from_spec(spec) - spec.loader.exec_module(module) - return module - - -def helper(module, name): - if HELPERS[name]: - return getattr(module, HELPERS[name]) - found = [v for k, v in vars(module).items() - if callable(v) and k.startswith("same_") and k.endswith("_path")] - assert len(found) == 1, (name, found) - return found[0] - - -class ReportPathCaseTest(unittest.TestCase): - def setUp(self): - self._tmp = tempfile.TemporaryDirectory() - self.dir = pathlib.Path(self._tmp.name) - probe = self.dir / "Probe" - probe.touch() - self.insensitive = (self.dir / "probe").exists() - probe.unlink() - - def tearDown(self): - self._tmp.cleanup() - - def test_new_paths_that_differ_only_in_case(self): - upper, lower = self.dir / "new" / "B.json", self.dir / "new" / "b.json" - for name in HELPERS: - with self.subTest(tool=name): - same = helper(load(name), name) - self.assertTrue(same(str(upper), str(upper))) - self.assertEqual(same(str(upper), str(lower)), self.insensitive) - self.assertFalse(same(str(upper), str(self.dir / "new" / "c.json"))) - - def test_new_paths_that_differ_only_in_accent_form(self): - if sys.platform != "darwin" or not self.insensitive: - self.skipTest("APFS/HFS+ name normalization") - composed, decomposed = self.dir / "café.json", self.dir / "CAFÉ.json" - for name in HELPERS: - with self.subTest(tool=name): - self.assertTrue(helper(load(name), name)(str(composed), str(decomposed))) - - def test_world_census_follows_the_folding_volume(self): - """The archive guard asks report_paths, so a case-insensitive APFS volume refuses a report that would - overwrite the archive; its own realpath+normcase copy answered "two files" there.""" - module = load("world_census") - composed = self.dir / "café.json" - decomposed = self.dir / unicodedata.normalize("NFD", "café.json") - folding = [True] - with mock.patch.object(report_paths, "sys", mock.Mock(platform="darwin")), \ - mock.patch.object(report_paths, "case_insensitive_volume", lambda path: folding[0]): - self.assertTrue(module.same_report_path(str(composed), str(decomposed))) - folding[0] = False - self.assertFalse(module.same_report_path(str(composed), str(decomposed))) - - def test_bvh_index_refuses_case_only_report_pair(self): - source = self.dir / "in.rpf" - source.write_bytes(bytes(4096)) - out = self.dir / "o" - r = subprocess.run([sys.executable, "-I", str(TOOLS / "bvh_index.py"), str(source), - "--out", str(out / "B.json"), "--csv", str(out / "b.json")], - cwd=ROOT, capture_output=True, text=True, timeout=60) - if self.insensitive: - self.assertEqual(r.returncode, 2, r.stderr) - self.assertIn("--out and --csv must use different paths", r.stderr) - self.assertFalse(out.exists() and any(out.iterdir())) - else: - self.assertEqual(r.returncode, 0, r.stderr) - self.assertEqual(sorted(p.name for p in out.iterdir()), ["B.json", "b.json"]) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/test_report_paths.py b/tests/test_report_paths.py deleted file mode 100644 index 34c6d1f24..000000000 --- a/tests/test_report_paths.py +++ /dev/null @@ -1,222 +0,0 @@ -"""tools/report_paths.py, the one `same_report_path` the tools share, and the tools that use it. - - python -I tests/test_report_paths.py - -Standard library only; everything runs in a temporary folder on hand-built paths, no game data. The macOS -case-insensitive-volume branch is exercised with patches, so it runs on every platform. -""" -import ast -import os -import pathlib -import posixpath -import sys -import tempfile -import unittest -from unittest import mock - -ROOT = pathlib.Path(__file__).resolve().parent.parent -TOOLS = ROOT / "tools" -sys.path.insert(0, str(TOOLS)) -import report_paths # noqa: E402 - -# Tools that use report_paths and must not define their own copy again. -SHARED = ("anim_index", "awc_manifest", "gamedata_index", "gamedata_xml", "gen_d3d12_stubs", "glb_inspect", - "navmesh_index", "rpf_probe", "tile_probe", "world_index", "world_lights_paths", "world_names") -# The one tool that still carries its own copy (an open pull request edits its call site). Do not add to this list: -# import report_paths instead. -LEGACY_COPIES = {"navmesh_decode"} - - -def touch(path): - pathlib.Path(path).parent.mkdir(parents=True, exist_ok=True) - with open(path, "wb") as f: - f.write(b"x") - - -class SamePathTests(unittest.TestCase): - def setUp(self): - self.tmp = tempfile.TemporaryDirectory() - self.addCleanup(self.tmp.cleanup) - self.dir = os.path.realpath(self.tmp.name) - - def p(self, *parts): - return os.path.join(self.dir, *parts) - - def test_same_spelling_and_other_spelling(self): - touch(self.p("a", "r.json")) - self.assertTrue(report_paths.same_report_path(self.p("a", "r.json"), self.p("a", "r.json"))) - self.assertTrue(report_paths.same_report_path(self.p("a", "r.json"), self.p("a", "..", "a", ".", "r.json"))) - - def test_different_files(self): - touch(self.p("a.json")) - touch(self.p("b.json")) - self.assertFalse(report_paths.same_report_path(self.p("a.json"), self.p("b.json"))) - - def test_paths_that_do_not_exist_yet(self): - self.assertTrue(report_paths.same_report_path(self.p("new", "x.json"), self.p("new", "..", "new", "x.json"))) - self.assertFalse(report_paths.same_report_path(self.p("new", "x.json"), self.p("new", "y.json"))) - - def test_one_missing_one_present_is_not_an_error(self): - touch(self.p("a.json")) - self.assertFalse(report_paths.same_report_path(self.p("a.json"), self.p("missing.json"))) - self.assertFalse(report_paths.same_report_path(self.p("missing.json"), self.p("a.json"))) - - def test_hard_link(self): - touch(self.p("a.json")) - try: - os.link(self.p("a.json"), self.p("link.json")) - except (OSError, NotImplementedError, AttributeError) as e: - self.skipTest(f"hard links unavailable: {e}") - self.assertTrue(report_paths.same_report_path(self.p("a.json"), self.p("link.json"))) - - def test_symlink(self): - touch(self.p("a.json")) - try: - os.symlink(self.p("a.json"), self.p("sym.json")) - except (OSError, NotImplementedError, AttributeError) as e: - self.skipTest(f"symlinks unavailable: {e}") - self.assertTrue(report_paths.same_report_path(self.p("a.json"), self.p("sym.json"))) - self.assertTrue(report_paths.same_report_path(self.p("sym.json"), self.p("a.json"))) - - def test_case_only_difference_follows_the_volume(self): - # On a volume that ignores case (Windows, macOS's default) `B.json` and `b.json` are one file; elsewhere two. - touch(self.p("probe.tmp")) - insensitive = os.path.exists(self.p("PROBE.TMP")) - got = report_paths.same_report_path(self.p("new", "B.json"), self.p("new", "b.json")) - self.assertEqual(got, insensitive or os.path.normcase("A") == os.path.normcase("a")) - - -class MacVolumeTests(unittest.TestCase): - """The macOS branch: pathconf says whether the volume folds case. Patched, so it runs anywhere.""" - - def darwin(self, case_sensitive_result): - fake_os = mock.Mock(wraps=os, pathconf=mock.Mock(return_value=case_sensitive_result)) - # macOS's normcase keeps case. The host's would fold it on Windows, before the volume check this class tests. - fake_os.path.normcase = posixpath.normcase - return mock.patch.multiple(report_paths, sys=mock.Mock(platform="darwin"), os=fake_os) - - def test_not_macos_is_never_case_insensitive(self): - with mock.patch.object(report_paths, "sys", mock.Mock(platform="linux")): - self.assertFalse(report_paths.case_insensitive_volume(os.getcwd())) - - def test_macos_case_insensitive_volume_folds_case_and_accents(self): - with self.darwin(0): - self.assertTrue(report_paths.case_insensitive_volume(os.getcwd())) - self.assertEqual(report_paths.path_key("/tmp/leonida_x/R.json"), report_paths.path_key("/tmp/leonida_x/r.json")) - self.assertEqual(report_paths.path_key("/tmp/leonida_x/café.json"), - report_paths.path_key("/tmp/leonida_x/café.json")) - self.assertTrue(report_paths.same_report_path("/tmp/leonida_x/R.json", "/tmp/leonida_x/r.json")) - - def test_macos_case_sensitive_volume_keeps_case(self): - with self.darwin(1): - self.assertFalse(report_paths.case_insensitive_volume(os.getcwd())) - self.assertNotEqual(report_paths.path_key("/tmp/leonida_x/R.json"), report_paths.path_key("/tmp/leonida_x/r.json")) - - def test_macos_pathconf_failure_counts_as_case_insensitive(self): - # The macOS default; folding can only refuse a pair of reports, never let one overwrite the other. - for error in (OSError("no such file"), ValueError("bad name")): - with self.subTest(error=type(error).__name__), mock.patch.multiple( - report_paths, sys=mock.Mock(platform="darwin"), - os=mock.Mock(wraps=os, pathconf=mock.Mock(side_effect=error))): - self.assertTrue(report_paths.case_insensitive_volume(os.getcwd())) - - def test_macos_probe_walks_up_to_an_existing_folder(self): - with self.darwin(0): - self.assertTrue(report_paths.case_insensitive_volume("/definitely/not/there/at/all/x.json")) - asked = report_paths.os.pathconf.call_args[0][0] - self.assertTrue(os.path.exists(asked), asked) - - -class FoldingVolumeTests(unittest.TestCase): - """A volume that ignores case without normcase or pathconf saying so is found with one scratch folder.""" - - def setUp(self): - self.tmp = tempfile.TemporaryDirectory() - self.addCleanup(self.tmp.cleanup) - self.dir = os.path.realpath(self.tmp.name) - - def p(self, *parts): - return os.path.join(self.dir, *parts) - - def volume_folds_case(self): - touch(self.p("probe.tmp")) - return os.path.exists(self.p("PROBE.TMP")) - - def test_case_only_difference_follows_the_volume(self): - os.makedirs(self.p("reports")) - self.assertEqual(report_paths.same_name_on_folding_volume(self.p("reports", "R.json"), - self.p("reports", "r.json")), - self.volume_folds_case()) - - def test_other_spellings_of_one_folder_are_one_report(self): - os.makedirs(self.p("reports")) - self.assertTrue(report_paths.same_name_on_folding_volume(self.p("reports", "R.json"), - self.p("reports", ".", "R.json"))) - - def test_names_that_differ_by_more_than_case_never_ask_the_volume(self): - os.makedirs(self.p("reports")) - with mock.patch.object(report_paths.tempfile, "TemporaryDirectory", - side_effect=AssertionError("asked the volume")): - self.assertFalse(report_paths.same_name_on_folding_volume(self.p("reports", "out.json"), - self.p("reports", "lights.json"))) - - def test_it_leaves_no_scratch_folder_behind(self): - os.makedirs(self.p("reports")) - report_paths.same_name_on_folding_volume(self.p("reports", "R.json"), self.p("reports", "r.json")) - self.assertEqual(sorted(os.listdir(self.p("reports"))), []) - - def test_a_folder_that_does_not_exist_is_not_created(self): - self.assertFalse(report_paths.same_name_on_folding_volume(self.p("missing", "R.json"), - self.p("missing", "r.json"))) - self.assertFalse(os.path.exists(self.p("missing"))) - - def test_same_report_path_asks_the_volume_when_the_name_rules_disagree(self): - # The name rules say "different"; the volume has the last word on a pair that differs only by case. - with mock.patch.object(report_paths, "_resolved_key", side_effect=os.path.realpath), \ - mock.patch.object(report_paths, "_same_resolved_name", return_value=True) as probe: - self.assertTrue(report_paths.same_report_path(self.p("R.json"), self.p("r.json"))) - probe.assert_called_once_with(os.path.realpath(self.p("R.json")), os.path.realpath(self.p("r.json"))) - - def test_each_path_is_resolved_once_per_call(self): - # #6220's review: the key and the volume probe both want the resolved names, so resolving each path - # once costs two realpath calls per guard, not four. A guard runs once per input file, so this is the - # whole cost: on main the same call resolves four times. - with mock.patch.object(report_paths.os.path, "realpath", wraps=os.path.realpath) as resolved: - report_paths.same_report_path(self.p("out.json"), self.p("lights.json")) - self.assertEqual(resolved.call_count, 2, "each path is resolved once, not once per check") - - -class NoPrivateCopiesTests(unittest.TestCase): - def functions(self, tool): - tree = ast.parse((TOOLS / f"{tool}.py").read_text(encoding="utf-8")) - return {n.name for n in tree.body if isinstance(n, ast.FunctionDef)} - - def test_switched_tools_import_the_helper_and_define_no_copy(self): - for tool in SHARED: - with self.subTest(tool=tool): - source = (TOOLS / f"{tool}.py").read_text(encoding="utf-8") - self.assertIn("from report_paths import same_report_path", source) - names = self.functions(tool) - self.assertFalse({"same_report_path", "_same_report_path", "_path_key", "_case_insensitive_volume"} & names, - f"{tool} defines its own copy; use tools/report_paths.py") - - def test_no_new_copies_of_same_report_path(self): - copies = set() - for path in sorted(TOOLS.glob("*.py")): - if path.name == "report_paths.py": - continue - if any("same_report_path" in name for name in self.functions(path.stem)): - copies.add(path.stem) - self.assertEqual(copies - LEGACY_COPIES, set(), - "a tool defines its own same_report_path: import it from tools/report_paths.py instead") - - def test_tools_still_expose_same_report_path(self): - # gamedata_xml.py and others call it by this name (and tests or sibling tools may import it). - for tool in ("gamedata_index", "gamedata_xml", "navmesh_index", "world_index"): - with self.subTest(tool=tool): - module = __import__(tool) - self.assertIs(module.same_report_path, report_paths.same_report_path) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/test_report_source_collision.py b/tests/test_report_source_collision.py deleted file mode 100644 index 99b2056df..000000000 --- a/tests/test_report_source_collision.py +++ /dev/null @@ -1,130 +0,0 @@ -"""A report tool must never truncate the file it was asked to index. - -Run with ``python -I tests/test_report_source_collision.py``. Set ``LEONIDA_TOOLS_DIR`` -to compare against another revision of the tools (used as the negative control: -on main these tests fail because the source file is replaced by the report). - -All inputs are built here by hand; no game file or game data is used. -""" -import os -import struct -import subprocess -import sys -import tempfile -import unittest -import zlib - -ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) -TOOLS_DIR = os.environ.get("LEONIDA_TOOLS_DIR", os.path.join(ROOT, "tools")) -SENTINEL = b"SYNTHETIC-SOURCE-DO-NOT-OVERWRITE\n" * 4 - - -def make_bink(): - """A Bink 2 stream bink_index will accept: the header shape of tests/test_bink_index.py, with the - sentinel after it so the source is still recognisable as the file the tool must not replace. - - bink_index checks a single named file's header before it indexes it (target_problem), because a wrong path - or a mislabelled file used to come back as a successful scan of 0 streams. The plain sentinel is neither a - KB2 stream nor an RPF archive, so the tool was right to refuse it: the fixture is what was wrong. - """ - return struct.pack("<4s10I", b"KB2a", 40, 1, 0, 1, 16, 16, 30, 1, 0, 1) + bytes(4) + SENTINEL - - -def make_rpf(payload, head_size=0x40): - head = bytearray(head_size) - head[0:4] = b"9FPR" - struct.pack_into(" list[tuple[int, str]]: - """Return (lineno, source_line) for any open(...) call not managed by a with statement.""" - src = path.read_text(encoding="utf-8") - tree = ast.parse(src, filename=str(path)) - managed: set[int] = set() - for node in ast.walk(tree): - if isinstance(node, (ast.With, ast.AsyncWith)): - for item in node.items: - if isinstance(item.context_expr, ast.Call): - managed.add(id(item.context_expr)) - lines = src.splitlines() - bare: list[tuple[int, str]] = [] - for node in ast.walk(tree): - if isinstance(node, ast.Call) and isinstance(node.func, ast.Name) and node.func.id == "open": - if id(node) not in managed: - bare.append((node.lineno, lines[node.lineno - 1].strip())) - return bare - - -class ResourceHygieneTest(unittest.TestCase): - def test_no_unmanaged_open_calls(self): - for rel in ( - "tools/rdna2spirv.py", - "tools/amd_swizzle.py", - "tools/awc_opus.py", - "tools/wave64_graphics_scan.py", - "tools/tex_export.py", - "tools/tex_mode_probe.py", - "tools/shader_disasm.py", - "tools/hashdict.py", - "tools/d3d12_xs_surface.py", - ): - with self.subTest(file=rel): - bare = _bare_open_calls(ROOT / rel) - self.assertEqual(bare, [], f"unmanaged open() calls in {rel}: {bare}") - - def test_import_rdna2spirv_no_resource_warning(self): - r = subprocess.run( - [ - sys.executable, - "-W", - "error::ResourceWarning", - "-c", - f"import sys; sys.path.insert(0, {str(ROOT / 'tools')!r}); import rdna2spirv", - ], - capture_output=True, - text=True, - check=False, - ) - self.assertEqual(r.returncode, 0, r.stderr) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/test_restofworld_index.py b/tests/test_restofworld_index.py deleted file mode 100644 index 80447c240..000000000 --- a/tests/test_restofworld_index.py +++ /dev/null @@ -1,671 +0,0 @@ -"""Synthetic-header tests for tools/restofworld_index.py. - - python -I tests/test_restofworld_index.py - -Every byte is built by this test. No game file, asset name or payload is used. -""" -import contextlib -import csv -import io -import json -import os -import struct -import subprocess -import sys -import tempfile -import unittest -import unittest.mock -import zlib - -ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) -TOOL = os.path.join(ROOT, "tools", "restofworld_index.py") -sys.path.insert(0, os.path.join(ROOT, "tools")) - -import restofworld_index # noqa: E402 - - -def psin(): - sizes = [0x30, 0x10, 0x20, 8, 0x58, 0x14] - tags = [b"LSCH", b"LENM", b"LSNS", b"LGID", b"LRSC", b"CHKS"] - data = bytearray(0x20 + sum(sizes)) - data[:4] = b"PSIN" - data[4:8] = (0x20).to_bytes(4, "big") - struct.pack_into("" - return data + bytes(max(0, 64 - len(data))) - - -def respage(): - return b"\x42\x40\x00\x00" + bytes(60) - - -def zero(): - return bytes(64) - - -def typehash(): - return struct.pack(" stream with len(descs) entries.""" - header = bytearray(0x60) - struct.pack_into(" None: - blob = _synth_pg_tex_dict([ - _synth_tex_descriptor(0, 256, 256, 71, mips=7), - _synth_tex_descriptor(0x10000, 1, 2, 28, mips=2), - ]) - row = restofworld_index.classify(blob, 0x2000, 128) - self.assertEqual(row["count"], 2) - self.assertIn("tex980=2;dict=1", row["detail"]) - self.assertIn("R8G8B8A8_UNORM:1", row["detail"]) - summary = restofworld_index.summarise([row], span=128, zero=0, unread=0) - self.assertEqual((summary["texture_dictionaries"], summary["texture_headers"]), (1, 2)) - - def test_small_texture_with_invalid_mip_count_is_excluded(self) -> None: - for mips in (0, 3): - with self.subTest(mips=mips): - descriptor = _synth_tex_descriptor(0, 1, 2, 28, mips=mips) - self.assertEqual(restofworld_index.find_rage_textures(descriptor), []) - - def test_non_dict_resource_page_with_linear_f16_texture(self): - header = bytearray(0x60) - struct.pack_into(" not standalone pgDictionary - blob = bytes(header) + _synth_tex_descriptor(0x0, 16, 4, 10, flags_lo=0, mips=1) # R16G16B16A16_FLOAT - row = restofworld_index.classify(blob, 0x3000, 96) - self.assertEqual(row["signature"], "zero-prefix") - self.assertEqual(row["count"], 1) - self.assertIn("tex980=1;dict=0", row["detail"]) - self.assertIn("R16G16B16A16_FLOAT:1", row["detail"]) - - def test_negative_controls_reject_bad_dtype_unaligned_and_unknown_fmt(self): - bad_dtype = _synth_pg_tex_dict([_synth_tex_descriptor(0x0, 256, 256, 71, dtype=0x123)]) - bad_align = _synth_pg_tex_dict([_synth_tex_descriptor(0x10, 256, 256, 71)]) - bad_fmt = _synth_pg_tex_dict([_synth_tex_descriptor(0x0, 256, 256, 250)]) - for blob in (bad_dtype, bad_align, bad_fmt): - row = restofworld_index.classify(blob, 0x4000, 64) - self.assertEqual(row["signature"], "zero-prefix") - self.assertIsNone(row["count"]) - self.assertNotIn("tex980=", row["detail"]) - - def test_scan_rpf_reports_texture_summary_past_256_bytes(self): - # Put the 0x980 descriptor past byte 256 so scan_rpf must keep the zero-prefix body to find it. - header = bytearray(0x140) - struct.pack_into(" len(self.buf): - self.buf.extend(b"\x00" * (pos - len(self.buf))) - self.buf.extend(b"\x00" * size) - return pos - - def put_bytes(self, payload, align=16): - pos = self.alloc(len(payload), align=align) - self.buf[pos:pos + len(payload)] = payload - return pos - - def pad_to(self, target_size): - if len(self.buf) < target_size: - self.buf.extend(b"\x00" * (target_size - len(self.buf))) - - -def _populate_drawable( - sys_arena, - gfx_arena, - d_off, - embedded, - label, - lod_specs, - bone_count=0, - with_shader_cb=False, - empty_txd=False, - with_renderer=False, -): - """Populate a synthetic rmcDrawable at `d_off` inside `sys_arena` and append buffers to `gfx_arena`.""" - struct.pack_into(" 1 else 0)) * 32, align=16) - - struct.pack_into(" 0: - bmap_off = sys_arena.alloc(bone_count * 4, align=4) - struct.pack_into(" 65536 - return [bytes(sys_a.buf)], [bytes(gfx_a.buf[:65536]), bytes(gfx_a.buf[65536:])] - - -def make_fragment_2x2(): - """2 system pages + 2 graphics pages fragment whose page-map sits in system page 1.""" - sys_a = _Arena(176) - gfx_a = _Arena() - child_off = sys_a.alloc(192, align=16) - - struct.pack_into(" (non-model) to verify clean skipping.""" - sys_a = _Arena(64) - hashes = sys_a.alloc(4, align=8) - ptrs = sys_a.alloc(8, align=8) - tex = sys_a.alloc(128, align=16) - struct.pack_into(" 0: - pad = (-len(out)) % 16 - out.extend(b"\x00" * pad) - group_offsets.append(len(out)) - if raw[:3] == b"KB2": - out.extend(raw) - else: - out.extend(zlib.compress(raw)) - recorded.append((group_offsets, group)) - - out.extend(b"\x00" * 64) - return bytes(out), recorded - - -class ModelJoinTests(unittest.TestCase): - def setUp(self): - self.tmp = tempfile.TemporaryDirectory() - self.root = self.tmp.name - - def tearDown(self): - self.tmp.cleanup() - - def _build_full_corpus_entries(self): - sys1, gfx1 = make_standalone_drawable_1x1() - sys2, gfx2 = make_drawable_dict_1x2() - sys3, gfx3 = make_fragment_2x2() - txd_s, txd_g = make_texture_dict_1x1() - return [ - [make_bink2()], - [make_0drp_page()], - txd_s + txd_g, - sys1 + gfx1, - sys2 + gfx2, - sys3 + gfx3, - ] - - def test_joins_a_short_declared_final_system_page(self): - system, graphics = make_standalone_drawable_1x1() - first = bytearray(system[0].ljust(65536, b"\0")) - _write_page_map(first, 65536 - 64, sys_pages=2, gfx_pages=1) - struct.pack_into("= 1" in result.stdout - - -def test_reconcile_compatible(): - dwords, _ = rsc.pack_layout(ROOT_SIG) - reads = [{"sgpr": 0, "kind": "const32"}, - {"sgpr": 4, "kind": "ptr64_lo"}, - {"sgpr": 5, "kind": "ptr64_hi"}, - {"sgpr": 6, "kind": "tsharp"}] - assert rsc.reconcile(reads, dwords) == [] - - -@pytest.mark.parametrize(("base", "model"), [(0, []), (4, ["--model", "console"])]) -def test_cli_checks_explicit_pointer_pairs(tmp_path, base, model): - sig_path = tmp_path / "sig.json" - sig_path.write_text(json.dumps({"params": [{"type": "cbv"}, {"type": "srv"}]}), - encoding="utf-8", newline="\n") - index_path = tmp_path / "index.json" - for hi, status in ((base + 1, 0), (base + 3, 1)): - pair = [base, hi] - reads = [{"sgpr": base, "kind": "ptr64_lo", "pair": pair}, - {"sgpr": hi, "kind": "ptr64_hi", "pair": pair}] - index_path.write_text(json.dumps({"fixture": {"stage": "cs", "user_sgpr_reads": reads}}), - encoding="utf-8", newline="\n") - result = subprocess.run([sys.executable, "-I", TOOL, index_path, "--rootsig", sig_path, *model], - capture_output=True, text=True) - assert result.returncode == status, result.stdout + result.stderr - if status: - assert f"pair {pair} does not name both halves of one root address" in result.stdout - - -@pytest.mark.parametrize(("sgpr", "kind", "needle"), [ - (0, "ptr64_lo", "incompatible"), # s0 is a constant dword, not a VA - (31, "const32", "8 dwords"), # layout ends at s7 - (4, "ptr64_hi", "paired lo"), # s4 is sub 0 of the CBV pair - (5, "ptr64_lo", "high half"), # s5 is the high half of the CBV pair - (7, "ptr64_lo", "high half"), # s7 is the high half of the table pair - (0, "nope", "unknown read kind"), - (-1, "tsharp", "8 dwords"), # negative index must not alias last table dword - (-9, "tsharp", "8 dwords"), # beyond layout must not crash -]) -def test_reconcile_contradictions(sgpr, kind, needle): - dwords, _ = rsc.pack_layout(ROOT_SIG) - issues = rsc.reconcile([{"sgpr": sgpr, "kind": kind}], dwords) - assert len(issues) == 1 and needle in issues[0] - - -def test_cluster_groups_shapes(): - index = { - "a": {"user_sgpr_reads": [{"sgpr": 0, "kind": "const32"}]}, - "b": {"user_sgpr_reads": [{"sgpr": 0, "kind": "const32"}]}, - "c": {"user_sgpr_reads": [{"sgpr": 4, "kind": "ptr64_lo"}]}, - } - ranked = rsc.cluster(index) - assert ranked[0][1] == 2 and ranked[1][1] == 1 - - -def test_cluster_ties_and_example_names_are_stable(): - index = { - "z_const": {"user_sgpr_reads": [{"sgpr": 0, "kind": "const32"}]}, - "y_ptr": {"user_sgpr_reads": [{"sgpr": 2, "kind": "ptr64_lo"}]}, - "a_const": {"user_sgpr_reads": [{"sgpr": 0, "kind": "const32"}]}, - "b_ptr": {"user_sgpr_reads": [{"sgpr": 2, "kind": "ptr64_lo"}]}, - } - ranked = rsc.cluster(index) - assert ranked == rsc.cluster(dict(reversed(list(index.items())))) - assert [row[2] for row in ranked] == [["a_const", "z_const"], ["b_ptr", "y_ptr"]] - - -def test_cli_hard_fail_on_contradiction(tmp_path): - index = {"bad": {"user_sgpr_reads": [{"sgpr": 31, "kind": "const32"}]}} - index_path = tmp_path / "index.json" - index_path.write_text(json.dumps(index), encoding="utf-8") - sig_path = tmp_path / "sig.json" - sig_path.write_text(json.dumps(ROOT_SIG), encoding="utf-8") - r = subprocess.run( - [sys.executable, "-I", TOOL, str(index_path), - "--rootsig", str(sig_path)], - capture_output=True, text=True) - assert r.returncode == 1 - assert "CONTRADICTION bad" in r.stdout - - -@pytest.mark.parametrize(("sgpr", "status", "diagnostic"), [ - (4, 0, "1 compatible"), - (5, 1, "s5 (ptr32_lo) reads the high half of the address"), - (6, 0, "1 compatible"), - (7, 1, "s7 (ptr32_lo) reads the high half of the address"), -]) -def test_cli_32bit_pointer_must_use_low_address_slot( - tmp_path: Path, sgpr: int, status: int, diagnostic: str, -) -> None: - index = {"shader": {"user_sgpr_reads": [{"sgpr": sgpr, "kind": "ptr32_lo"}]}} - index_path = tmp_path / "index.json" - index_path.write_text(json.dumps(index), encoding="utf-8") - sig_path = tmp_path / "sig.json" - sig_path.write_text(json.dumps(ROOT_SIG), encoding="utf-8") - result = subprocess.run([sys.executable, "-I", TOOL, str(index_path), "--rootsig", str(sig_path)], - capture_output=True, text=True) - assert result.returncode == status, result.stdout + result.stderr - assert diagnostic in result.stdout - - -@pytest.mark.parametrize("bad_index", ["not json", "[]", '{"a": 1}']) -def test_bad_index_shape_is_one_error_not_a_traceback(tmp_path, bad_index): - index_path = tmp_path / "index.json" - index_path.write_text(bad_index, encoding="utf-8") - sig_path = tmp_path / "sig.json" - sig_path.write_text(json.dumps(ROOT_SIG), encoding="utf-8") - r = subprocess.run([sys.executable, "-I", TOOL, str(index_path), "--rootsig", str(sig_path)], - capture_output=True, text=True) - assert r.returncode == 2 - assert "ERROR:" in r.stderr - assert "Traceback" not in r.stderr - - -@pytest.mark.parametrize("bad_sig", ["not json", "[]"]) -def test_bad_rootsig_shape_is_one_error_not_a_traceback(tmp_path, bad_sig): - index_path = tmp_path / "index.json" - index_path.write_text("{}", encoding="utf-8") - sig_path = tmp_path / "sig.json" - sig_path.write_text(bad_sig, encoding="utf-8") - r = subprocess.run([sys.executable, "-I", TOOL, str(index_path), "--rootsig", str(sig_path)], - capture_output=True, text=True) - assert r.returncode == 2 - assert "ERROR:" in r.stderr - assert "Traceback" not in r.stderr - - -def test_missing_files_are_one_error(tmp_path): - r = subprocess.run([sys.executable, "-I", TOOL, str(tmp_path / "missing_index.json"), - "--rootsig", str(tmp_path / "missing_sig.json")], - capture_output=True, text=True) - assert r.returncode == 2 - assert "ERROR: cannot read" in r.stderr - assert "Traceback" not in r.stderr - - -@pytest.mark.parametrize("bad_params", ["abc", {"type": "cbv"}, [1], ["cbv"]]) -def test_bad_param_shapes_are_one_error_not_a_traceback(tmp_path, bad_params): - index_path = tmp_path / "index.json" - index_path.write_text("{}", encoding="utf-8") - sig_path = tmp_path / "sig.json" - sig_path.write_text(json.dumps({"params": bad_params}), encoding="utf-8") - r = subprocess.run([sys.executable, "-I", TOOL, str(index_path), "--rootsig", str(sig_path)], - capture_output=True, text=True) - assert r.returncode == 2 - assert "ERROR:" in r.stderr - assert "Traceback" not in r.stderr - - -@pytest.mark.parametrize("bad_reads", [ - 3, {"sgpr": 0}, ["x"], [{"kind": "const32"}], [{"sgpr": 0}], - [{"sgpr": 0, "kind": ["const32"]}], [{"sgpr": 0, "kind": {"a": 1}}], -]) -def test_bad_read_shapes_are_one_error_not_a_traceback(tmp_path, bad_reads): - index_path = tmp_path / "index.json" - index_path.write_text(json.dumps({"s": {"user_sgpr_reads": bad_reads}}), encoding="utf-8") - sig_path = tmp_path / "sig.json" - sig_path.write_text(json.dumps(ROOT_SIG), encoding="utf-8") - r = subprocess.run([sys.executable, "-I", TOOL, str(index_path), "--rootsig", str(sig_path)], - capture_output=True, text=True) - assert r.returncode == 2 - assert "ERROR:" in r.stderr - assert "Traceback" not in r.stderr - - -def test_cli_hard_fail_on_negative_sgpr(tmp_path): - index = {"bad": {"user_sgpr_reads": [{"sgpr": -1, "kind": "tsharp"}]}} - index_path = tmp_path / "index.json" - index_path.write_text(json.dumps(index), encoding="utf-8") - sig_path = tmp_path / "sig.json" - sig_path.write_text(json.dumps(ROOT_SIG), encoding="utf-8") - result = subprocess.run( - [sys.executable, "-I", TOOL, str(index_path), - "--rootsig", str(sig_path)], - capture_output=True, text=True) - assert result.returncode == 1 - assert "CONTRADICTION bad" in result.stdout - assert "s-1 read but layout has 8 dwords" in result.stdout - - -@pytest.mark.parametrize("sgpr", [True, False, 1.0, "1", None, [], {}]) -def test_reconcile_rejects_noninteger_sgpr(sgpr): - dwords, _ = rsc.pack_layout(ROOT_SIG) - # Including a real index catches bool/int and float/int key collisions. - reads = [{"sgpr": 1, "kind": "const32"}, - {"sgpr": sgpr, "kind": "const32"}] - assert rsc.reconcile(reads, dwords) == [ - f"invalid SGPR index {sgpr!r}: expected an integer"] - - -def test_cluster_preserves_invalid_index_distinctions(): - index = { - "valid": {"user_sgpr_reads": [{"sgpr": 1, "kind": "const32"}]}, - "invalid": {"user_sgpr_reads": [ - {"sgpr": 1, "kind": "const32"}, - {"sgpr": True, "kind": "const32"}, - {"sgpr": "1", "kind": "const32"}, - {"sgpr": [], "kind": "const32"}]}, - } - ranked = rsc.cluster(index) - assert len(ranked) == 2 - assert sum(count for _, count, _ in ranked) == 2 - - # Valid SGPRs must keep numeric order even when an invalid index is present. - index["mixed"] = {"user_sgpr_reads": [ - {"sgpr": 10, "kind": "const32"}, - {"sgpr": "bad", "kind": "const32"}, - {"sgpr": 2, "kind": "const32"}]} - mixed_shape = next(shape for shape, _, names in rsc.cluster(index) - if names == ["mixed"]) - assert mixed_shape == ((2, "const32"), (10, "const32"), - ("invalid:'bad'", "const32")) - - -def test_cli_rejects_noninteger_sgprs_with_cluster(tmp_path): - index = {"bad": {"user_sgpr_reads": [ - {"sgpr": 1, "kind": "const32"}, - {"sgpr": True, "kind": "const32"}, - {"sgpr": "1", "kind": "const32"}, - {"sgpr": 1.0, "kind": "const32"}, - {"sgpr": [], "kind": "const32"}]}} - index_path = tmp_path / "index.json" - index_path.write_text(json.dumps(index), encoding="utf-8") - sig_path = tmp_path / "sig.json" - sig_path.write_text(json.dumps(ROOT_SIG), encoding="utf-8") - result = subprocess.run( - [sys.executable, "-I", TOOL, str(index_path), - "--rootsig", str(sig_path), "--cluster"], - capture_output=True, text=True) - assert result.returncode == 1 - assert "CONTRADICTION bad" in result.stdout - assert "invalid SGPR index" in result.stdout - assert "read-set shapes" in result.stdout - assert "Traceback" not in result.stderr - - -# --model console: rt::rootsig::pack_stage's layout (D3D-448). The package's FidelityFX compute signatures have this -# shape (two tables, then four root CBVs); their programs read the tables at s4/s5 as 32-bit pointers and copy each -# root CBV's 64-bit VA as two dwords. Hand-written here: shapes and register numbers only. -FSR_SHAPE = {"version": "1.1", "flags": 0, "params": [ - {"type": "table", "ranges": [{"kind": "srv", "count": 1}]}, - {"type": "table", "ranges": [{"kind": "uav", "count": 1}]}, - {"type": "cbv"}, {"type": "cbv"}, {"type": "cbv"}, {"type": "cbv"}]} -FSR_READS = [{"sgpr": 4, "kind": "ptr32_lo"}, {"sgpr": 5, "kind": "ptr32_lo"}, - {"sgpr": 6, "kind": "const32"}, {"sgpr": 7, "kind": "const32"}] - - -def test_console_layout_compute(): - dwords, error = rsc.pack_layout(FSR_SHAPE, "cs") - assert error == "" - assert len(dwords) == 14 # s0..s3 driver, then 10 dwords: the programs' USER_SGPR count - assert [d["ptype"] for d in dwords[:4]] == ["driver"] * 4 - assert [(d["param"], d["sub"]) for d in dwords[4:]] == [ - (0, 0), (1, 0), (2, 0), (2, 1), (3, 0), (3, 1), (4, 0), (4, 1), (5, 0), (5, 1)] - - -def test_console_layout_stage_bases(): - for stage, base in (("ps", 8), ("vs", 8), ("gs", 8), ("ms", 16)): - dwords, error = rsc.pack_layout(ROOT_SIG, stage) - assert error == "" and len(dwords) == base + 4 + 2 + 1, stage # constants 4, cbv 2, table 1 - dwords, error = rsc.pack_layout(ROOT_SIG, "hs") - assert dwords == [] and "no console base" in error - - -def test_console_layout_spill_refused(): - sig = {"version": "1.1", "flags": 0, "params": [{"type": "table"} for _ in range(17)]} - assert rsc.pack_layout(sig, "ms")[1] != "" # 17 one-dword tables past s31 - sig["params"].pop() - assert rsc.pack_layout(sig, "ms")[1] == "" # 16 fill s16..s31 - dwords, error = rsc.pack_layout({"params": [{"type": "constants", "count": 29}]}, "cs") - assert dwords == [] and "param 0" in error and "spill" in error - - -def test_console_reconcile_fsr_reads(): - console, _ = rsc.pack_layout(FSR_SHAPE, "cs") - assert rsc.reconcile(FSR_READS, console) == [] - s0, _ = rsc.pack_layout(FSR_SHAPE) - issues = rsc.reconcile(FSR_READS, s0) - assert any("s5 (ptr32_lo) reads the high half" in i for i in issues) - - -def test_whole_address_copy_needs_both_halves(): - console, _ = rsc.pack_layout(FSR_SHAPE, "cs") - one_half = [{"sgpr": 6, "kind": "const32"}] - assert any("incompatible" in i for i in rsc.reconcile(one_half, console)) - - -def test_driver_block_reads(): - console, _ = rsc.pack_layout(FSR_SHAPE, "cs") - assert rsc.reconcile([{"sgpr": 1, "kind": "const32"}], console) == [] # a system value - issues = rsc.reconcile([{"sgpr": 0, "kind": "ptr64_lo"}], console) - assert any("driver block" in i for i in issues) # a spill pointer - - -def test_cli_console_model_uses_each_shaders_stage(tmp_path): - index = {"a.cs": {"stage": "cs", "user_sgpr_reads": FSR_READS}, - "b.ps": {"stage": "ps", "user_sgpr_reads": [{"sgpr": 8, "kind": "ptr32_lo"}]}} - index_path = tmp_path / "index.json" - index_path.write_text(json.dumps(index), encoding="utf-8") - sig_path = tmp_path / "sig.json" - sig_path.write_text(json.dumps(FSR_SHAPE), encoding="utf-8") - console = subprocess.run([sys.executable, "-I", TOOL, str(index_path), "--rootsig", str(sig_path), - "--model", "console"], capture_output=True, text=True) - assert console.returncode == 0, console.stdout + console.stderr - assert "2 shaders: 2 compatible, 0 contradictory" in console.stdout - plain = subprocess.run([sys.executable, "-I", TOOL, str(index_path), "--rootsig", str(sig_path)], - capture_output=True, text=True) - assert plain.returncode == 1 and "CONTRADICTION" in plain.stdout diff --git a/tests/test_root_spill_census.py b/tests/test_root_spill_census.py deleted file mode 100644 index d936853db..000000000 --- a/tests/test_root_spill_census.py +++ /dev/null @@ -1,271 +0,0 @@ -"""tools/root_spill_census.py on hand-written index data (no game files, no GPU). - - python -I tests/test_root_spill_census.py -""" -import json -import os -import subprocess -import sys -import tempfile -import unittest - -ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) -TOOL = os.path.join(ROOT, "tools", "root_spill_census.py") -sys.path.insert(0, os.path.join(ROOT, "tools")) - -import root_spill_census as rsc # noqa: E402 - - -def reads(*pairs): - return [{"sgpr": s, "kind": k} for s, k in pairs] - - -# Register-based ABI, nothing spilled: constants below the base, pointers from the base up. -NO_SPILL = { - "a.ps": {"stage": "ps", "user_sgpr_reads": reads((1, "const32"), (8, "ptr32_lo"), (9, "ptr32_lo"), (31, "const32"))}, - "b.ps": {"stage": "ps", "user_sgpr_reads": reads((8, "ptr32_lo"), (10, "const32"))}, - "c.cs": {"stage": "cs", "user_sgprs": 6, "user_sgpr_reads": reads((1, "const32"), (4, "ptr32_lo"), (5, "const32"))}, - "d.cs": {"stage": "cs", "user_sgprs": 14, "user_sgpr_reads": reads((4, "ptr32_lo"), (13, "ptr32_lo"))}, - "e.gs": {"stage": "gs", "user_sgpr_reads": reads((2, "const32"), (8, "ptr64_lo"), (9, "ptr64_hi"))}, - "f.vs": {"stage": "vs", "user_sgpr_reads": []}, -} - -# A compute shader that spilled the way section 7 measured it: a 64-bit pointer in s[0:1]. -SPILLED = { - "s.cs": {"stage": "cs", "user_sgprs": 32, - "user_sgpr_reads": reads((0, "ptr64_lo"), (1, "ptr64_hi"), (4, "ptr32_lo"), (31, "const32"))}, -} - - -class CensusTest(unittest.TestCase): - def test_no_spill_corpus(self): - s = rsc.census(NO_SPILL)["stages"] - for stage in s.values(): - self.assertEqual(stage["shaders_with_spill_pointer_candidate"], 0) - self.assertEqual(stage["spill_pointer_candidates"], {}) - self.assertEqual(s["ps"]["highest_sgpr_read"], {"s10": 1, "s31": 1}) - self.assertEqual(s["ps"]["highest_read_kind"], {"const32": 2}) - self.assertEqual(s["ps"]["max_highest_sgpr_read"], 31) - self.assertEqual(s["cs"]["highest_read_kind"], {"const32": 1, "pointer": 1}) - self.assertEqual(s["vs"]["highest_sgpr_read"], {}) - self.assertIsNone(s["vs"]["max_highest_sgpr_read"]) - - def test_user_sgprs_budget(self): - cs = rsc.census(NO_SPILL)["stages"]["cs"] - self.assertEqual(cs["max_user_sgprs"], 14) - self.assertEqual(cs["max_root_dwords"], 10) # 14 - base s4 - self.assertEqual(cs["root_dwords_available"], 28) # 32 - base s4 - self.assertEqual(cs["shaders_using_all_user_sgprs"], 0) - self.assertNotIn("max_user_sgprs", rsc.census(NO_SPILL)["stages"]["ps"]) # not recorded for ps - - def test_spill_pointer_below_base(self): - cs = rsc.census(SPILLED)["stages"]["cs"] - self.assertEqual(cs["shaders_with_spill_pointer_candidate"], 1) - self.assertEqual(cs["spill_pointer_candidates"], {"s0:ptr64_lo": 1, "s1:ptr64_hi": 1}) - self.assertEqual(cs["shaders_using_all_user_sgprs"], 1) - - def test_base_decides_what_is_below(self): - # The same GS pointer at s8 is a candidate once the base is moved above it. - gs = rsc.census(NO_SPILL, base={"gs": 10})["stages"]["gs"] - self.assertEqual(gs["spill_pointer_candidates"], {"s8:ptr64_lo": 1, "s9:ptr64_hi": 1}) - # A stage with no base reports no candidates rather than guessing one. - self.assertIsNone(rsc.census(NO_SPILL, base={})["stages"]["ps"]["base"]) - self.assertEqual(rsc.census(NO_SPILL, base={})["stages"]["ps"]["spill_pointer_candidates"], {}) - - def test_boundary_at_each_default_base(self): - # A pointer one SGPR below the base is a candidate; at the base and one above it is not. - for stage, base in rsc.DEFAULT_BASE.items(): - for sgpr, expected in ((base - 1, 1), (base, 0), (base + 1, 0)): - index = {"x": {"stage": stage, "user_sgpr_reads": reads((sgpr, "ptr32_lo"))}} - got = rsc.census(index)["stages"][stage]["shaders_with_spill_pointer_candidate"] - self.assertEqual(got, expected, f"{stage} s{sgpr}") - - def test_rts0_parts_counted(self): - carve = [{"name": "x", "parts": {"DXIL": 1, "PRIV": 2}}, - {"name": "y", "parts": {"DXIL": 1, "RTS0": 3}}, - {"name": "z"}] - out = rsc.census(NO_SPILL, carve=carve) - self.assertEqual(out["containers"], 3) - self.assertEqual(out["containers_with_rts0"], 1) - self.assertNotIn("containers", rsc.census(NO_SPILL)) - - def test_malformed_reads_are_skipped(self): - index = {"m": {"stage": "cs", "user_sgpr_reads": [{"kind": "ptr32_lo"}, {"sgpr": "0", "kind": "ptr64_lo"}]}} - cs = rsc.census(index)["stages"]["cs"] - self.assertEqual(cs["shaders"], 1) - self.assertEqual(cs["spill_pointer_candidates"], {}) - - -class CliTest(unittest.TestCase): - def run_tool(self, index, *args): - with tempfile.TemporaryDirectory() as tmp: - path = os.path.join(tmp, "index.json") - with open(path, "w", encoding="utf-8") as f: - json.dump(index, f) - report = os.path.join(tmp, "report.json") - result = subprocess.run([sys.executable, "-I", TOOL, path, "--json", report, *args], - capture_output=True, text=True) - summary = None - if os.path.exists(report): - with open(report, encoding="utf-8") as f: - summary = json.load(f) - return result, summary - - def test_expect_no_spill_passes_and_fails(self): - ok, summary = self.run_tool(NO_SPILL, "--expect-no-spill") - self.assertEqual(ok.returncode, 0, ok.stderr) - self.assertEqual(summary["stages"]["cs"]["max_root_dwords"], 10) - self.assertIn("cs: 2 shaders; base s4; spill-pointer candidates 0", ok.stdout) - bad, _ = self.run_tool(SPILLED, "--expect-no-spill") - self.assertEqual(bad.returncode, 1) - self.assertIn("SPILL POINTER CANDIDATES", bad.stderr) - plain, _ = self.run_tool(SPILLED) # without the flag a spill is reported, not a failure - self.assertEqual(plain.returncode, 0, plain.stderr) - - def test_partial_base_keeps_the_other_defaults(self): - # The review's case: a PS address read at s7 (below the PS base s8). Overriding only cs must not drop ps. - index = {"p.ps": {"stage": "ps", "user_sgpr_reads": reads((7, "ptr32_lo"))}} - default, _ = self.run_tool(index, "--expect-no-spill") - self.assertEqual(default.returncode, 1, default.stderr) - partial, summary = self.run_tool(index, "--expect-no-spill", "--base", "cs=4") - self.assertEqual(partial.returncode, 1, partial.stderr) - self.assertEqual(summary["stages"]["ps"]["base"], 8) - moved, summary = self.run_tool(index, "--expect-no-spill", "--base", "ps=7") - self.assertEqual(moved.returncode, 0, moved.stderr) # a named stage does take the override - self.assertEqual(summary["stages"]["ps"]["base"], 7) - - def test_bad_base_is_a_usage_error(self): - for assignment in ("ps", "ps=bad", "=8", "ps=-1"): - result, summary = self.run_tool(NO_SPILL, "--base", assignment) - self.assertEqual(result.returncode, 2, result.stderr) - self.assertIn("expected STAGE=SGPR", result.stderr) - self.assertNotIn("Traceback", result.stderr) - self.assertIsNone(summary) - - def test_list_index_is_refused(self): - result, summary = self.run_tool([{"stage": "ps"}]) - self.assertEqual(result.returncode, 2) - self.assertIn("not a translator index", result.stderr) - self.assertIsNone(summary) - - def test_json_creates_missing_parent_folder(self): - with tempfile.TemporaryDirectory() as tmp: - idx = os.path.join(tmp, "index.json") - with open(idx, "w", encoding="utf-8") as f: - json.dump(NO_SPILL, f) - out = os.path.join(tmp, "reports", "sub", "report.json") - r = subprocess.run([sys.executable, "-I", TOOL, idx, "--json", out], - capture_output=True, text=True) - self.assertEqual(r.returncode, 0, r.stderr) - self.assertTrue(os.path.isfile(out)) - with open(out, encoding="utf-8") as f: - rep = json.load(f) - self.assertIn("stages", rep) - - def test_json_refuses_a_folder(self): - with tempfile.TemporaryDirectory() as tmp: - idx = os.path.join(tmp, "index.json") - with open(idx, "w", encoding="utf-8") as f: - json.dump(NO_SPILL, f) - sub = os.path.join(tmp, "other_dir") - os.makedirs(sub) - for target in (tmp, sub): - with self.subTest(target=target): - r = subprocess.run([sys.executable, "-I", TOOL, idx, "--json", target], - capture_output=True, text=True) - self.assertEqual(r.returncode, 2) - self.assertIn("is a folder, not a file", r.stderr) - self.assertNotIn("Traceback", r.stderr) - - def test_json_refuses_to_overwrite_an_input_index(self): - with tempfile.TemporaryDirectory() as tmp: - idx = os.path.join(tmp, "index.json") - with open(idx, "w", encoding="utf-8") as f: - json.dump(NO_SPILL, f) - with open(idx, "rb") as f: - before = f.read() - # Direct match - r1 = subprocess.run([sys.executable, "-I", TOOL, idx, "--json", idx], - capture_output=True, text=True) - self.assertEqual(r1.returncode, 2) - self.assertIn("must not overwrite an input index", r1.stderr) - self.assertNotIn("Traceback", r1.stderr) - with open(idx, "rb") as f: - self.assertEqual(f.read(), before) - - # Dot-aliased spelling - alias = os.path.join(tmp, ".", "index.json") - r2 = subprocess.run([sys.executable, "-I", TOOL, idx, "--json", alias], - capture_output=True, text=True) - self.assertEqual(r2.returncode, 2) - self.assertIn("must not overwrite an input index", r2.stderr) - - # With --carve - carve = os.path.join(tmp, "carve.json") - with open(carve, "w", encoding="utf-8") as f: - json.dump([{"name": "x"}], f) - r3 = subprocess.run([sys.executable, "-I", TOOL, idx, "--carve", carve, "--json", carve], - capture_output=True, text=True) - self.assertEqual(r3.returncode, 2) - self.assertIn("must not overwrite an input index", r3.stderr) - - def test_json_in_input_folder_can_be_written_twice(self): - with tempfile.TemporaryDirectory() as tmp: - idx = os.path.join(tmp, "index.json") - with open(idx, "w", encoding="utf-8") as f: - json.dump(NO_SPILL, f) - out = os.path.join(tmp, "report.json") - r1 = subprocess.run([sys.executable, "-I", TOOL, idx, "--json", out], - capture_output=True, text=True) - self.assertEqual(r1.returncode, 0, r1.stderr) - self.assertTrue(os.path.isfile(out)) - # Run again: overwriting earlier report must succeed - r2 = subprocess.run([sys.executable, "-I", TOOL, idx, "--json", out], - capture_output=True, text=True) - self.assertEqual(r2.returncode, 0, r2.stderr) - - def test_json_failed_write_is_one_error_line(self): - with tempfile.TemporaryDirectory() as tmp: - idx = os.path.join(tmp, "index.json") - with open(idx, "w", encoding="utf-8") as f: - json.dump(NO_SPILL, f) - blocker = os.path.join(tmp, "not_a_dir") - with open(blocker, "wb") as f: - f.write(b"file") - out = os.path.join(blocker, "out.json") - r = subprocess.run([sys.executable, "-I", TOOL, idx, "--json", out], - capture_output=True, text=True) - self.assertEqual(r.returncode, 2) - self.assertIn("error: cannot write", r.stderr) - self.assertNotIn("Traceback", r.stderr) - - - def test_index_saved_with_bom_is_read(self): - # PowerShell 5.1 Set-Content and some editors save JSON with a UTF-8 BOM; the index is still JSON. - with tempfile.TemporaryDirectory() as tmp: - path = os.path.join(tmp, "index.json") - with open(path, "wb") as f: - f.write(b"\xef\xbb\xbf" + json.dumps(NO_SPILL).encode("utf-8")) - result = subprocess.run([sys.executable, "-I", TOOL, path], capture_output=True, text=True) - self.assertEqual(result.returncode, 0, result.stderr) - self.assertNotIn("Traceback", result.stderr) - self.assertIn("cs: 2 shaders; base s4", result.stdout) - - - def test_carve_index_saved_with_bom_is_read(self): - with tempfile.TemporaryDirectory() as tmp: - index = os.path.join(tmp, "index.json") - with open(index, "w", encoding="utf-8") as f: - json.dump(NO_SPILL, f) - carve = os.path.join(tmp, "carve.json") - with open(carve, "wb") as f: - f.write(b"\xef\xbb\xbf" + json.dumps([{"name": "x", "parts": {"RTS0": 1}}]).encode("utf-8")) - result = subprocess.run([sys.executable, "-I", TOOL, index, "--carve", carve], - capture_output=True, text=True) - self.assertEqual(result.returncode, 0, result.stderr) - self.assertNotIn("Traceback", result.stderr) - self.assertIn("containers: 1, with an RTS0 part: 1", result.stdout) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/test_rootsig_census.py b/tests/test_rootsig_census.py deleted file mode 100644 index 884222aaa..000000000 --- a/tests/test_rootsig_census.py +++ /dev/null @@ -1,276 +0,0 @@ -import json -import os -import struct -import subprocess -import sys -import tempfile -import unittest - -ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) -sys.path.insert(0, os.path.join(ROOT, "tools")) -TOOL = os.path.join(ROOT, "tools", "rootsig_census.py") -import rootsig_census as R - - -def container(chunks): - """A minimal DXBC container: magic, 24 zero bytes, chunk count at 28, offsets at 32.""" - head = bytearray(b"DXBC" + b"\0" * 24) - head += struct.pack("= 2 - base = 24 + 12 * len(params) - entries, body, tables = bytearray(), bytearray(), [] - - def push(data): - off = base + len(body) - body.extend(data) - return off - - for param in params: - kind, vis = param[0], param[1] - if kind == "table": - off = push(struct.pack("<2I", param[2], 0)) - tables.append((off - base, param[2])) - entries += struct.pack("<3I", 0, vis, off) - elif kind == "constants": - off = push(struct.pack("<4I", 0, 0, param[2], 0)) - entries += struct.pack("<3I", 1, vis, off) - else: - dtype = {"cbv": 2, "srv": 3, "uav": 4}[kind] - off = push(struct.pack("<3I", 0, 0, 0) if v11 else struct.pack("<2I", 0, 0)) - entries += struct.pack("<3I", dtype, vis, off) - for at, nranges in tables: - if not nranges: - continue - ranges_off = base + len(body) - for j in range(nranges): - body += struct.pack("<6I", 0, 1, 0, 0, 0, j) if v11 else struct.pack("<5I", 0, 1, 0, 0, j) - struct.pack_into("" + bytes(6) # ADAT inside METADATA, its "header" is text and zeros - bank = len(data) + (-len(data)) % 0x10 - data += bytes(bank - len(data)) - if with_bank: - data += b"ADAT" + struct.pack("", p.stderr) - self.assertFalse(os.path.exists(out), args) - - def test_scan_limit_excludes_crossing_stream(self): - with tempfile.TemporaryDirectory() as tmp: - arc = os.path.join(tmp, "tiny.rpf") - streams = make_archive(arc) - stored = len(streams[0]) - rows, summary = rpf9_names.scan_archive(arc, start=0x40, limit=stored) - self.assertEqual(len(rows), 1) - self.assertEqual(summary["streams"], 1) - self.assertEqual(summary["unread_bytes"], 0) - - rows, summary = rpf9_names.scan_archive(arc, start=0x40, limit=stored - 1) - self.assertEqual(rows, []) - self.assertEqual(summary["streams"], 0) - self.assertEqual(summary["unread_bytes"], stored - 1) - self.assertEqual(summary["span"], stored - 1) - - def test_missing_archive(self): - with tempfile.TemporaryDirectory() as tmp: - out = os.path.join(tmp, "out.json") - p = self.run_tool(os.path.join(tmp, "missing.rpf"), out, "--quiet") - self.assertEqual(p.returncode, 2, p.stderr) - self.assertFalse(os.path.exists(out)) - - def test_empty_archive_raises_not_rpf9(self): - with tempfile.TemporaryDirectory() as tmp: - empty = os.path.join(tmp, "empty.rpf") - open(empty, "wb").close() - with tracked_mmaps() as created: - with self.assertRaisesRegex(ValueError, "not an RPF9 archive"): - rpf9_names.scan_archive(empty) - self.assertEqual(created, []) - - def test_scan_archive_closes_mmap_on_success(self): - with tempfile.TemporaryDirectory() as tmp: - arc = os.path.join(tmp, "tiny.rpf") - make_archive(arc) - with tracked_mmaps() as created: - rows, summary = rpf9_names.scan_archive(arc) - self.assertEqual(len(rows), 3) - self.assertEqual(summary["streams"], 4) - self.assertEqual(len(created), 1) - self.assertTrue(created[0].closed) - os.remove(arc) - self.assertFalse(os.path.exists(arc)) - - def test_bink2_video_is_skipped_with_its_embedded_stream(self): - before = stream(b"before.#dr") - inner = stream(b"hidden.#ft") - video = bink2(inner, total=0x20 + len(inner) + 16) - after = stream(b"after.#dd") - with tempfile.TemporaryDirectory() as tmp: - arc = os.path.join(tmp, "v.rpf") - make_blob(arc, before, bytes(5), video, after) - rows, summary = rpf9_names.scan_archive(arc) - names = sorted(n for row in rows for n in row["names"]) - self.assertEqual(names, ["after.#dd", "before.#dr"], summary) - self.assertEqual(summary["streams"], 2, summary) - self.assertEqual(summary["bink2_files"], 1, summary) - self.assertEqual(summary["bink2_bytes"], len(video), summary) - self.assertEqual(sum(r["stored"] for r in rows), len(before) + len(after)) - self.assertEqual(summary["zero_padding"] + summary["unread_bytes"] + len(before) + len(after) - + summary["bink2_bytes"], summary["span"], summary) - self.assertEqual(summary["zero_padding"], 5 + 4096, summary) - self.assertEqual(summary["unread_bytes"], 0, summary) - - def test_bink2_gap_before_video_counts_as_unread(self): - video = bink2() - with tempfile.TemporaryDirectory() as tmp: - arc = os.path.join(tmp, "v.rpf") - make_blob(arc, b"junk!", video) - rows, summary = rpf9_names.scan_archive(arc) - self.assertEqual(summary["bink2_files"], 1, summary) - self.assertEqual(summary["unread_bytes"], 5, summary) - self.assertEqual(summary["zero_padding"], 4096, summary) - self.assertEqual(summary["unread_bytes"] + summary["zero_padding"] + summary["bink2_bytes"], - summary["span"], summary) - - def test_implausible_bink2_header_is_not_a_video(self): - good = stream(b"real.#dr") - bad_headers = { - "zero_width": bink2(w=0), - "huge_height": bink2(h=9000), - "runs_past_end": bink2()[:4] + struct.pack(" 0 for m in seen), seen) - self.assertEqual(summary["streams"], 2, summary) - self.assertEqual(rows[0]["size"], 65, rows) - self.assertEqual(rows[0]["offset"], 0x40, rows) - self.assertEqual(rows[0]["names"], ["alpha.#dr"], rows) - self.assertEqual(rows[1]["offset"], 0x40 + len(first), rows) - self.assertEqual(rows[1]["names"], ["bravo.#ft"], rows) - - def test_name_across_first_feed_boundary(self): - first = stream(b"alpha.#dr") - # With level 0 this arrives almost verbatim: the second name straddles - # the first compressed feed and the final stream shares its last read. - text = b" " * (rpf9_names.INITIAL_FEED - 10) + b"bravo.#ft " + b" " * 9000 - second = zlib.compress(text, level=0) - with tempfile.TemporaryDirectory() as tmp: - arc = os.path.join(tmp, "t.rpf") - make_blob(arc, first, second, stream(b"charlie.#dd")) - rows, summary = rpf9_names.scan_archive(arc) - self.assertEqual(summary["streams"], 3) - self.assertEqual([r["names"] for r in rows], [["alpha.#dr"], ["bravo.#ft"], ["charlie.#dd"]]) - self.assertEqual(rows[1]["size"], len(text)) - self.assertEqual(rows[1]["stored"], len(second)) - self.assertEqual(rows[2]["offset"], 0x40 + len(first) + len(second)) - - def test_scan_archive_closes_mmap_on_validation_errors(self): - cases = ( - ("bad_magic", b"NOPE" + bytes(60), None, "not an RPF9 archive"), - ("bad_data_start", b"RPF9" + struct.pack(" resource page counts (at 0x48) - system[0x20:0x28] = struct.pack(" name hashes - system[0x28:0x2A] = struct.pack(" texture pointer array - system[0x38:0x3A] = struct.pack("= count - system[t + 0x08:t + 0x0C] = struct.pack(" inline-name descriptor - system[t + 0x38:t + 0x3A] = struct.pack("/ and then die with an unhandled FileNotFoundException - # from FileInfo.Length. Both mistakes are usage errors (exit 2) and must leave the output alone. - with tempfile.TemporaryDirectory() as tmp: - root = Path(tmp) - for label, src in (("missing", root / "missing.rpf"), ("directory", root)): - with self.subTest(source=label): - out = root / f"out-{label}" - done = run("ttpf", src, out) - self.assertEqual(done.returncode, 2, done.stdout + done.stderr) - self.assertIn("source is not a file", done.stderr) - self.assertNotIn("Unhandled exception", done.stderr) - self.assertFalse(out.exists(), f"{label} source left {out} behind") - - def test_failed_xma_write_exits_nonzero_and_rerun_completes(self): - with tempfile.TemporaryDirectory() as tmp: - root = Path(tmp) - src = root / "audio.rpf" - awc_rpf(src) - wav = root / "out" / "audio" / "xma" / "audio_0001_at_0000000000001000" / "00001234.xma.wav" - # A folder under the final name: Util.WriteAtomic writes to a unique .*.partial, so a folder named - # .partial blocks nothing, but the rename into place cannot replace a folder. - wav.mkdir(parents=True) # the write of this one stream fails - failed = run("xma", src, root / "out") - self.assertNotEqual(failed.returncode, 0, failed.stdout + failed.stderr) - self.assertFalse(wav.is_file()) - wav.rmdir() - retry = run("xma", src, root / "out") - self.assertEqual(retry.returncode, 0, retry.stdout + retry.stderr) - self.assertEqual(wav.read_bytes()[:4], b"RIFF") - self.assertEqual(wav.read_bytes()[-64:], b"\x11" * 64) - - def test_failed_texture_write_exits_nonzero_and_withholds_manifest(self): - # A per-item write failure must fail the run like ttpf and xma do: make_game resumes the - # textures/models stages on the mere existence of manifest.json, so a manifest published after a - # failed DDS write would mark the stage finished with the file missing forever. - with tempfile.TemporaryDirectory() as tmp: - root = Path(tmp) - src = root / "textures.rpf" - texture_dictionary_rpf(src) - sub = root / "out" / "textures" / "textures" - dds = sub / "dictionary_at_0000000000001010" / "000_probe.dds" - dds.mkdir(parents=True) # a folder under the final name: the write of this one DDS fails - failed = run("textures", src, root / "out") - self.assertNotEqual(failed.returncode, 0, failed.stdout + failed.stderr) - self.assertFalse(dds.is_file(), failed.stdout) # the blocked write must not have succeeded - self.assertFalse((sub / "manifest.json").exists(), failed.stdout) - self.assertFalse((sub / "manifest.json.partial").exists()) - dds.rmdir() - retry = run("textures", src, root / "out") - self.assertEqual(retry.returncode, 0, retry.stdout + retry.stderr) - self.assertTrue((sub / "manifest.json").exists()) - self.assertEqual(dds.read_bytes()[:4], b"DDS ") - - def test_unknown_mode_exits_nonzero_before_the_source_or_output_is_touched(self): - with tempfile.TemporaryDirectory() as tmp: - root = Path(tmp) - src = root / "package.rpf" # never created: the mode is rejected before the source is opened - out = root / "out" - bad = run("invalidmode", src, out) - self.assertNotEqual(bad.returncode, 0, bad.stdout + bad.stderr) - self.assertIn("unknown mode 'invalidmode'", bad.stdout + bad.stderr) - self.assertNotIn("ok=0 fail=0 skip=0", bad.stdout, "an unknown mode still reported a finished run") - self.assertFalse(out.exists(), "an unknown mode created the output folder") - self.assertEqual([p.name for p in root.iterdir()], [], "an unknown mode touched the work folder") - - def test_usage_lists_every_mode(self): - short = run() - self.assertEqual(short.returncode, 2, short.stdout + short.stderr) - self.assertIn("usage: rpf9dump", short.stdout) - for mode in ("ttpf", "models", "textures", "audio", "xma"): - self.assertIn(mode, short.stdout, f"usage does not list {mode}") - - def test_start_past_eof_exits_2_before_creating_output(self): - with tempfile.TemporaryDirectory() as tmp: - root = Path(tmp) - src = root / "tiny.rpf" - src.write_bytes(bytes(16)) - for mode in ("models", "textures"): - with self.subTest(mode=mode): - out = root / f"out-{mode}" - done = run(mode, src, out, "--start", "1024") - self.assertEqual(done.returncode, 2, done.stdout + done.stderr) - self.assertIn("--start", done.stderr) - self.assertNotIn("Unhandled exception", done.stderr) - self.assertFalse(out.exists(), f"{mode} left {out} behind on --start past EOF") - - def test_start_plus_length_overflow_is_clamped_and_does_not_crash(self): - with tempfile.TemporaryDirectory() as tmp: - root = Path(tmp) - src = root / "tiny.rpf" - src.write_bytes(bytes(16)) - for mode in ("models", "textures"): - with self.subTest(mode=mode): - out = root / f"out-{mode}" - done = run(mode, src, out, "--start", "8", "--length", str((1 << 63) - 1)) - self.assertEqual(done.returncode, 0, done.stdout + done.stderr) - self.assertNotIn("Unhandled exception", done.stderr) - manifest = json.loads((out / "tiny" / mode / "manifest.json").read_text(encoding="utf-8")) - self.assertEqual(manifest["Count"], 0) - self.assertEqual(manifest["Scan"]["Start"], 8) - self.assertEqual(manifest["Scan"]["Length"], 8) - - def test_short_source_under_64_bytes_does_not_crash(self): - with tempfile.TemporaryDirectory() as tmp: - root = Path(tmp) - for size in (0, 16): - src = root / f"tiny_{size}.rpf" - src.write_bytes(bytes(size)) - for mode in ("models", "textures"): - with self.subTest(size=size, mode=mode): - out = root / f"out-{mode}-{size}" - done = run(mode, src, out) - self.assertEqual(done.returncode, 0, done.stdout + done.stderr) - self.assertNotIn("Unhandled exception", done.stderr) - manifest = json.loads((out / f"tiny_{size}" / mode / "manifest.json").read_text(encoding="utf-8")) - self.assertEqual(manifest["Count"], 0) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/test_rpf_probe.py b/tests/test_rpf_probe.py deleted file mode 100644 index 531e95bef..000000000 --- a/tests/test_rpf_probe.py +++ /dev/null @@ -1,353 +0,0 @@ -"""Tests for tools/rpf_probe.py, built from synthetic archive headers (no game data). - - python -I tests/test_rpf_probe.py -""" -import contextlib -import errno -import importlib.util -import io -import json -import os -import struct -import stat -import subprocess -import sys -import tempfile -import unittest -from unittest import mock - -ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) - - -def load_module(): - path = os.path.join(ROOT, "tools", "rpf_probe.py") - spec = importlib.util.spec_from_file_location("rpf_probe_under_test", path) - module = importlib.util.module_from_spec(spec) - spec.loader.exec_module(module) - return module - - -probe = load_module() - - -def archive_bytes(version=b"4FPR", words=(0x10, 0x20, 0x30, 0x40), pad_to=None, tail=b""): - """Little-endian 'RPF4' magic, four header words, then optional padding and payload.""" - data = version + struct.pack("<4I", *words) - if pad_to is not None and len(data) < pad_to: - data += b"\x00" * (pad_to - len(data)) - return data + tail - - -class EntropyTests(unittest.TestCase): - def test_empty_is_zero(self): - self.assertEqual(probe.entropy(b""), 0.0) - - def test_single_symbol_is_zero(self): - self.assertEqual(probe.entropy(b"\x00" * 16), 0.0) - - def test_two_equally_frequent_symbols(self): - self.assertEqual(probe.entropy(b"\x00\x01" * 8), 1.0) - - def test_all_byte_values_once(self): - self.assertEqual(probe.entropy(bytes(range(256))), 8.0) - - -class ProbeTests(unittest.TestCase): - def setUp(self): - tmp = tempfile.TemporaryDirectory() - self.addCleanup(tmp.cleanup) - self.dir = tmp.name - - def write(self, data, name="a.rpf"): - path = os.path.join(self.dir, name) - os.makedirs(os.path.dirname(path), exist_ok=True) - with open(path, "wb") as f: - f.write(data) - return path - - def test_version_and_header_words(self): - row = probe.probe(self.write(archive_bytes(words=(0x0, 0xFFFFFFFF, 0x1234, 0x10)))) - self.assertEqual(row["version"], "RPF4") - self.assertEqual(row["header_words"], ["0x0", "0xffffffff", "0x1234", "0x10"]) - - def test_natural_order_magic_is_not_a_version(self): - self.assertEqual(probe.probe(self.write(b"RPF4" + b"\x00" * 16))["version"], None) - - def test_other_magic_has_no_version(self): - self.assertEqual(probe.probe(self.write(b"DDS " + b"\x00" * 30))["version"], None) - - def test_short_file_has_no_words(self): - row = probe.probe(self.write(b"4FPR" + b"\x00" * 4)) - self.assertEqual(row["version"], "RPF4") - self.assertEqual(row["header_words"], []) - self.assertEqual(row["head_entropy"], 0.0) - self.assertFalse(row["looks_encrypted"]) - - def test_zero_filled_body_is_not_flagged(self): - row = probe.probe(self.write(archive_bytes(words=(0, 0, 0, 0), pad_to=1024))) - self.assertEqual(row["head_entropy"], 0.0) - self.assertFalse(row["looks_encrypted"]) - - def test_dense_body_is_flagged(self): - row = probe.probe(self.write(archive_bytes(tail=bytes(range(256)) * 16))) - self.assertGreater(row["head_entropy"], 7.9) - self.assertTrue(row["looks_encrypted"]) - - def test_only_the_first_64_kib_is_read(self): - path = self.write(archive_bytes(pad_to=0x10000, tail=bytes(range(256)) * 16)) - row = probe.probe(path) - self.assertEqual(row["size"], 0x10000 + 4096) - self.assertEqual(row["head_entropy"], 0.0) - self.assertFalse(row["looks_encrypted"]) - - def test_size_is_the_full_file(self): - self.assertEqual(probe.probe(self.write(archive_bytes(pad_to=0x10000)))["size"], 0x10000) - - -class MainTests(unittest.TestCase): - def setUp(self): - tmp = tempfile.TemporaryDirectory() - self.addCleanup(tmp.cleanup) - self.tmp = tmp.name - self.game = os.path.join(self.tmp, "game") - os.makedirs(self.game) - self.out = os.path.join(self.tmp, "reports", "rpf.json") - - def write(self, rel, data): - path = os.path.join(self.game, rel) - os.makedirs(os.path.dirname(path), exist_ok=True) - with open(path, "wb") as f: - f.write(data) - return path - - def run_main(self): - out = io.StringIO() - with mock.patch("sys.argv", ["rpf_probe.py", self.game, "--out", self.out]), contextlib.redirect_stdout(out): - self.assertEqual(probe.main(), 0) - return out.getvalue() - - def rows(self): - with open(self.out, encoding="utf-8") as f: - return json.load(f) - - def test_collects_rpf_files_recursively_and_sorts_by_size(self): - small = self.write("a.rpf", archive_bytes()) - large = self.write("sub/b.RPF", archive_bytes(pad_to=4096)) - self.write("sub/notes.txt", b"ignored") - out = self.run_main() - rows = self.rows() - self.assertEqual([os.path.basename(r["file"]) for r in rows], ["b.RPF", "a.rpf"]) - self.assertEqual(os.path.normpath(rows[0]["file"]), os.path.normpath(large)) - self.assertEqual(os.path.normpath(rows[1]["file"]), os.path.normpath(small)) - self.assertIn("2 archives", out) - self.assertIn("'RPF4': 2", out) - - def test_equal_sized_archives_are_sorted_by_path(self): - self.write("z.rpf", archive_bytes()) - self.write("a.rpf", archive_bytes()) - with mock.patch.object(probe.os, "walk", return_value=[(self.game, [], ["z.rpf", "a.rpf"])]): - self.run_main() - - self.assertEqual([os.path.basename(row["file"]) for row in self.rows()], ["a.rpf", "z.rpf"]) - - def test_creates_the_output_directory(self): - self.write("a.rpf", archive_bytes()) - self.run_main() - self.assertTrue(os.path.isfile(self.out)) - - @unittest.skipIf(os.name == "nt", "POSIX permission bits") - def test_refresh_preserves_private_report_permissions(self): - self.write("a.rpf", archive_bytes()) - self.run_main() - os.chmod(self.out, 0o600) - self.write("b.rpf", archive_bytes()) - self.run_main() - self.assertEqual(len(self.rows()), 2) - self.assertEqual(stat.S_IMODE(os.stat(self.out).st_mode), 0o600) - - def test_empty_game_directory(self): - out = self.run_main() - self.assertEqual(self.rows(), []) - self.assertIn("0 archives", out) - - def assert_input_refused(self, destination, archive): - with open(archive, "rb") as f: - before = f.read() - script = os.path.join(ROOT, "tools", "rpf_probe.py") - result = subprocess.run( - [sys.executable, "-I", script, self.game, "--out", destination], - capture_output=True, text=True, timeout=30, - ) - self.assertEqual(result.returncode, 2, result.stderr) - self.assertEqual(result.stdout, "") - self.assertEqual(len(result.stderr.splitlines()), 1, result.stderr) - self.assertIn("would overwrite an input archive", result.stderr) - with open(archive, "rb") as f: - self.assertEqual(f.read(), before) - - def test_report_cannot_replace_an_input_archive(self): - archive = self.write("a.rpf", archive_bytes()) - self.assert_input_refused(archive, archive) - - def test_report_cannot_replace_a_nested_archive(self): - archive = self.write("sub/a.RPF", archive_bytes()) - self.assert_input_refused(archive, archive) - - def test_report_cannot_replace_a_normalized_input_path(self): - archive = self.write("a.rpf", archive_bytes()) - os.mkdir(os.path.join(self.game, "sub")) - destination = os.path.join(self.game, "sub", "..", "a.rpf") - self.assert_input_refused(destination, archive) - - def test_report_cannot_replace_a_hard_link_to_an_archive(self): - archive = self.write("a.rpf", archive_bytes()) - destination = os.path.join(self.tmp, "alias.json") - try: - os.link(archive, destination) - except (OSError, NotImplementedError) as e: - self.skipTest(f"hard links unavailable: {e}") - self.assert_input_refused(destination, archive) - self.assertTrue(os.path.samefile(archive, destination)) - - def test_report_cannot_replace_a_symlink_to_an_archive(self): - archive = self.write("a.rpf", archive_bytes()) - destination = os.path.join(self.tmp, "alias.json") - try: - os.symlink(archive, destination) - except (OSError, NotImplementedError) as e: - self.skipTest(f"symlinks unavailable: {e}") - self.assert_input_refused(destination, archive) - self.assertTrue(os.path.islink(destination)) - - def test_report_cannot_replace_the_target_of_a_scanned_symlink(self): - archive = os.path.join(self.tmp, "external.rpf") - with open(archive, "wb") as f: - f.write(archive_bytes()) - try: - os.symlink(archive, os.path.join(self.game, "linked.rpf")) - except (OSError, NotImplementedError) as e: - self.skipTest(f"symlinks unavailable: {e}") - self.assert_input_refused(archive, archive) - - def test_existing_unrelated_report_can_be_replaced(self): - original = archive_bytes() - archive = self.write("a.rpf", original) - os.makedirs(os.path.dirname(self.out)) - with open(self.out, "w", encoding="utf-8") as f: - f.write("previous report\n") - self.run_main() - self.assertEqual([r["file"] for r in self.rows()], [archive]) - with open(archive, "rb") as f: - self.assertEqual(f.read(), original) - - def test_replace_retry_failure_preserves_the_existing_report(self): - previous = '[{"previous": true}]\n' - out_dir = os.path.dirname(self.out) - os.makedirs(out_dir, exist_ok=True) - with open(self.out, "w", encoding="utf-8", newline="\n") as f: - f.write(previous) - with mock.patch.object(probe, "replace_retry", side_effect=OSError(13, "Permission denied")): - with self.assertRaises(OSError): - probe._write_json_report(self.out, [{"new": True}]) - with open(self.out, encoding="utf-8") as f: - self.assertEqual(f.read(), previous) - - @unittest.skipUnless(os.name == "posix", "requires a POSIX file size limit") - def test_failed_write_preserves_the_existing_report(self): - self.write("demo.rpf", b"9FPR" + struct.pack(") - vlen = _align16(blk_arr_voff + blk_cnt * 8) - - virt = bytearray(vlen) - - def put_vptr(off, target): - struct.pack_into(" 0 else 0.0 - struct.pack_into(" 0: - put_vptr(anim_desc_voff + 0x60, tracks_voff) - struct.pack_into(" unsorted - h0 = struct.unpack_from(" 99/60 = 1.65s) - multi = build_synthetic_rsc8(block_frames=[64, 37], anim_payload_len=64) - res_m = rsc8_audio.decode_rsc8(multi, stream_id=0x00112233) - self.assertTrue(res_m["valid"], res_m["checks"]) - self.assertEqual(res_m["anim"]["block_count"], 2) - self.assertEqual(res_m["anim"]["frame_count"], 100) - self.assertEqual(res_m["anim"]["max_block_size"], res_m["anim_desc"]["max_block_size"]) - self.assertAlmostEqual(res_m["clip"]["duration"], 99 / 60.0, places=5) - - # Reordered sub-allocation: track directory placed at virt+0xB0, anim block after it - reord = build_synthetic_rsc8(frames=120, tracks_before_anim=True) - res_r = rsc8_audio.decode_rsc8(reord, stream_id=0x00112233) - self.assertTrue(res_r["valid"], res_r["checks"]) - self.assertEqual(res_r["anim_desc"]["track_ptr"], 0xB0) - self.assertGreater(res_r["anim"]["blocks"][0]["voff"], 0xB0) - - # Flagged version 0x01001F41 (bit 24 set, base version 8001) - flagged = build_synthetic_rsc8(version=0x01001F41, frames=79) - res_f = rsc8_audio.decode_rsc8(flagged, stream_id=0x00112233) - self.assertTrue(res_f["valid"], res_f["checks"]) - self.assertEqual(res_f["version"], 0x01001F41) - self.assertEqual(res_f["version_base"], 8001) - self.assertEqual(res_f["version_flags"], 0x0100) - - # Non-deep mode omits skipped track and property-dependent duration checks rather than reporting False/True - res_nd = rsc8_audio.decode_rsc8(multi, deep=False) - self.assertTrue(res_nd["valid"], res_nd["checks"]) - self.assertNotIn("clip_duration_matches_frames", res_nd["checks"]) - self.assertNotIn("tracks_sorted", res_nd["checks"]) - self.assertNotIn("tracks_schema_ok", res_nd["checks"]) - - # Non-60 fps clip (fps=30, 61 frames -> 2.0s) validates in both deep and shallow (--no-deep) modes - clip_30fps = build_synthetic_rsc8(frames=61, fps=30) - res_30_deep = rsc8_audio.decode_rsc8(clip_30fps, deep=True) - res_30_shallow = rsc8_audio.decode_rsc8(clip_30fps, deep=False) - self.assertTrue(res_30_deep["valid"], res_30_deep["checks"]) - self.assertAlmostEqual(res_30_deep["clip"]["duration"], 2.0, places=5) - self.assertTrue(res_30_shallow["valid"], res_30_shallow["checks"]) - self.assertNotIn("clip_duration_matches_frames", res_30_shallow["checks"]) - - def test_reject_truncated_props_and_zero_fps(self): - blob = bytearray(build_synthetic_rsc8(frames=60)) - dec = rsc8_audio.decode_rsc8(bytes(blob)) - # Shrink props_size so descriptors cannot fit - struct.pack_into("> 6 - h = (h + (h << 3)) & 0xFFFFFFFF - h ^= h >> 11 - return (h + (h << 15)) & 0xFFFFFFFF - - -def build_synthetic_markers(records): - """16-byte cue records: u32 name hash, f32 value, u32 sample offset, u32 extra. No header.""" - return b"".join(struct.pack(" bytes: - """Build a minimal valid 64-bit PE image in memory with .text and .rdata sections.""" - sec_align = 0x1000 - file_align = 0x200 - - def align_up(x: int, a: int) -> int: - return (x + a - 1) & ~(a - 1) - - text_len = max(align_up(len(text_bytes), sec_align), sec_align) - text_data = text_bytes.ljust(text_len, b"\xc3") - - rdata_len = max(align_up(len(rdata_bytes), sec_align), sec_align) - rdata_data = rdata_bytes.ljust(rdata_len, b"\x00") - - text_rva = 0x1000 - rdata_rva = text_rva + text_len - size_of_image = rdata_rva + rdata_len - - dos = b"MZ" + b"\x00" * 0x3A + struct.pack(""), # was reported as mem::H::?$Pool - (".?AV?$Map@_KPEBD@util@@", "util::Map"), - (".?AV?$Flags@W4Mode@gfx@@@gfx@@", "gfx::Flags"), - (".?AV?$Fixed@$0BA@$0?0$00@math@@", "math::Fixed<16, -1, 1>"), - (".?AV?$Tuple@$$V@core@@", "core::Tuple<>"), - (".?AV?$Tuple@HN$$QEAM@core@@", "core::Tuple"), - (".?AVInner@?$Outer@_N@core@@", "core::Outer::Inner"), - ): - with self.subTest(mangled=mangled): - self.assertEqual(rtti_scan.simple_name(mangled), name) - - def test_back_references(self): - # Inside a template the digits count that template's own names: 0 is Pair, 1 Node, 2 scene. - self.assertEqual(rtti_scan.simple_name(".?AV?$Pair@VNode@scene@@VEdge@2@@scene@@"), - "scene::Pair") - # A template that was named once is one back-reference: 2 is List. - self.assertEqual(rtti_scan.simple_name(".?AV?$Wrap@VIterator@?$List@H@core@@V123@@core@@"), - "core::Wrap::Iterator, core::List::Iterator>") - - def test_pointer_reference_array_and_function_arguments(self): - for mangled, name in ( - (".?AV?$Callback@$$A6AXAEBUEvent@ui@@H@Z@ui@@", "ui::Callback"), - (".?AV?$Sink@P6AXPEAX0@_E@io@@", "io::Sink"), - (".?AV?$Span@AEAY03$$CBH@io@@", "io::Span"), - (".?AV?$Ref@AEBQEAUNode@scene@@@scene@@", "scene::Ref"), - # A pointer to a function pointer or to an array goes inside the brackets, not after them. - (".?AV?$Cb@PEAP6AXH@Z@lab@@", "lab::Cb"), - (".?AV?$Cb@QEAP6AXH@Z@lab@@", "lab::Cb"), - (".?AV?$Cb@P6AP6AXH@ZXZ@lab@@", "lab::Cb"), - (".?AV?$Cb@AEAY03P6AXH@Z@lab@@", "lab::Cb"), - (".?AV?$Cb@PEAY03$$CBH@lab@@", "lab::Cb"), - (".?AV?$Arr@$$BY01H@lab@@", "lab::Arr"), - ): - with self.subTest(mangled=mangled): - self.assertEqual(rtti_scan.simple_name(mangled), name) - - def test_anonymous_namespace_and_local_classes(self): - for mangled, name in ( - (".?AVWorker@?A0x1234abcd@jobs@@", "jobs::`anonymous namespace'::Worker"), - (".?AV@?1??Run@Task@jobs@@QEAAXH@Z@", "`jobs::Task::Run'::`2'::"), - (".?AV@?0???0Task@jobs@@QEAA@XZ@", "`jobs::Task::Task'::`1'::"), - (".?AV@?0???RTask@jobs@@QEBAHH@Z@", "`jobs::Task::operator()'::`1'::"), - # A conversion operator is named after the type it returns: two of them in one class stay apart. - (".?AVX@?0???BObj@@QEBAHXZ@", "`Obj::operator int'::`1'::X"), - (".?AVX@?0???BObj@@QEBAP6AXH@ZXZ@", "`Obj::operator void (*)(int)'::`1'::X"), - (".?AV@?5???$Each@H@List@core@@SA_NPEBVNode@2@0@Z@", "`core::List::Each'::`6'::"), - (".?AV?$Holder@V@?1??Run@Task@jobs@@QEAAXH@Z@H@jobs@@", - "jobs::Holder<`jobs::Task::Run'::`2'::, int>"), - ): - with self.subTest(mangled=mangled): - self.assertEqual(rtti_scan.simple_name(mangled), name) - - def test_enum_and_union(self): - self.assertEqual(rtti_scan.simple_name(".?AW4Mode@gfx@@"), "gfx::Mode") - self.assertEqual(rtti_scan.simple_name(".?ATBits@gfx@@"), "gfx::Bits") - - def test_a_form_that_is_not_read_stays_mangled(self): - # No made-up scope chain: a pointer to a member function, a template cut short, a name that never ends, - # an array with a negative number of dimensions or a negative size. - for mangled in (".?AV?$Bind@P8Task@jobs@@EAAXXZ@jobs@@", ".?AV?$Pool@@", ".?AV?$Pool@H@", ".?AV9@@", - ".?AV?$Arr@$$BY?0H@lab@@", ".?AV?$Arr@$$BY0?1H@lab@@", ".?AV?$Arr@AEAY?0H@lab@@", - ".?AV" + "?$A@V" * 5000 + "@"): - with self.subTest(mangled=mangled[:40]): - self.assertEqual(rtti_scan.simple_name(mangled), mangled) - - -class RttiScanCoreTest(unittest.TestCase): - def setUp(self): - self.tmp = tempfile.TemporaryDirectory() - self.image_base = 0x140000000 - - def tearDown(self): - self.tmp.cleanup() - - def run_tool(self, *args): - return subprocess.run([sys.executable, "-I", TOOL, *args], capture_output=True, text=True, errors="replace") - - def test_type_descriptor_detection_and_parsing(self): - rdata = bytearray(0x1000) - # TypeDescriptor 1 at RVA 0x2000 (offset 0): 16 bytes prefix + mangled name - rdata[0:16] = b"\x00" * 16 - rdata[16:32] = b".?AVPlayer@@\x00\x00\x00\x00" - - # TypeDescriptor 2 at RVA 0x2040 (offset 0x40) - rdata[0x40:0x50] = b"\x00" * 16 - rdata[0x50:0x70] = b".?AUWeapon@Item@@\x00\x00\x00" - - # TypeDescriptor 3 at RVA 0x2080 (offset 0x80) - rdata[0x80:0x90] = b"\x00" * 16 - rdata[0x90:0xB0] = b".?AWRenderState@@\x00" - - pe_bytes = make_synthetic_pe(text_bytes=b"\x90" * 0x10, rdata_bytes=bytes(rdata)) - img_path = os.path.join(self.tmp.name, "td_test.exe") - with open(img_path, "wb") as f: - f.write(pe_bytes) - - out_json = os.path.join(self.tmp.name, "out.json") - p = self.run_tool(img_path, "--out", out_json) - self.assertEqual(p.returncode, 0, p.stderr) - - with open(out_json, "r", encoding="utf-8") as f: - data = json.load(f) - - self.assertEqual(data["type_descriptors"], 3) - self.assertEqual(len(data["classes"]), 0) # No COLs yet - - def test_single_inheritance_hierarchy_and_vtable(self): - rdata = bytearray(0x1000) - - # TD Animal at RVA 0x2000 - rdata[0x000:0x010] = b"\x00" * 16 - rdata[0x010:0x028] = b".?AVAnimal@@\x00\x00\x00\x00" - - # TD Dog at RVA 0x2040 - rdata[0x040:0x050] = b"\x00" * 16 - rdata[0x050:0x068] = b".?AVDog@@\x00\x00\x00\x00\x00" - - # BCD Animal at RVA 0x2080 (first field is rvaTypeDescriptor) - rdata[0x080:0x09C] = struct.pack(""])]) - self.assertEqual([(v["rva"], v["class"], v["slots"]) for v in scanned["vtables"]], - [(0x2100, "`jobs::Task::Run'::`2'::Job", 1)]) - - def test_multiple_and_virtual_inheritance(self): - rdata = bytearray(0x1000) - - # Base A TD at 0x2000 - rdata[0x000:0x010] = b"\x00" * 16 - rdata[0x010:0x028] = b".?AVBaseA@@\x00\x00\x00\x00\x00" - - # Base B TD at 0x2040 - rdata[0x040:0x050] = b"\x00" * 16 - rdata[0x050:0x068] = b".?AVBaseB@@\x00\x00\x00\x00\x00" - - # Derived TD at 0x2080 - rdata[0x080:0x090] = b"\x00" * 16 - rdata[0x090:0x0B0] = b".?AVDerived@@\x00\x00\x00" - - # BCDs at 0x20C0, 0x20E0, 0x2100 - rdata[0x0C0:0x0DC] = struct.pack(" vtable at 0x2200 (2 slots) - rdata[0x1F8:0x200] = struct.pack(" vtable at 0x2220 (1 slot) - rdata[0x218:0x220] = struct.pack(" bytes: - return b"".join(struct.pack("<4I", 0, 0, 0, count) for count in mandelbrot_counts(width)) - - -class MandelbrotReadbackTest(unittest.TestCase): - def run_frame(self, data: bytes | None) -> tuple[int, str]: - with tempfile.TemporaryDirectory() as directory: - work = Path(directory) - args = SimpleNamespace(filter="ps_mandelbrot.asm", build=directory, llvm_mc="unused") - - def launch(cmd: list[str], **kwargs: object) -> tuple[int, str]: - if cmd[0] == sys.executable: - (work / "spirv" / "ps_mandelbrot.spv").touch() - elif Path(cmd[0]).stem == "vk_harness": - if data is not None: - Path(cmd[-1]).write_bytes(data) - else: - self.fail(f"unexpected command: {cmd}") - return 0, "" - - output = io.StringIO() - with (patch.object(rgt, "assemble_to_s", side_effect=lambda _mc, _src, dst, _name: Path(dst).touch()), - patch.object(rgt, "spirv_as"), - patch.object(rgt, "run_cmd", side_effect=launch), - redirect_stdout(output)): - result = rgt.run_suite(args, directory) - return result, output.getvalue() - - def test_missing_empty_short_or_partial_frames_fail_the_test(self) -> None: - for label, data in ( - ("missing", None), ("empty", b""), ("one complete pixel", reference_frame(1)), - ("partial pixel", bytes(8)), - ): - with self.subTest(label=label): - result, output = self.run_frame(data) - self.assertEqual(result, 1, output) - self.assertIn("FAIL ps_mandelbrot", output) - # a frame that was never written is reported as a missing readback (TEST-837) before its size is read - self.assertIn("missing readback" if data is None else "expected 4096 pixels", output) - - def test_complete_frame_still_compares_the_iteration_counts(self) -> None: - correct = reference_frame(64) - result, output = self.run_frame(correct) - self.assertEqual(result, 0, output) - self.assertIn("4096/4096 iteration counts match", output) - wrong = bytearray(correct) - struct.pack_into(" str: - fd, path = tempfile.mkstemp(suffix=".raw") - with os.fdopen(fd, "wb") as f: - f.write(data) - self.addCleanup(os.remove, path) - return path - - def test_good_frames_pass(self): - grad = b"".join(struct.pack("<4f", (i % 64 + 0.5) / 64, (i // 64 + 0.5) / 64, 0.5, 1.0) for i in range(4096)) - self.assertTrue(rgt.check_grad(self.raw(grad), 0.5, 1.0)[0]) - - def test_bary_checks_both_interpolation_paths(self) -> None: - triangle = [] - for y in range(64): - for x in range(64): - u, v = (x + 0.5) / 64, (y + 0.5) / 64 - triangle.append((u, v, u / 2, v / 2)) - wrong_raw = triangle.copy() - u, v, i, _ = wrong_raw[1337] - wrong_raw[1337] = (u, v, i, 0.0) - with tempfile.TemporaryDirectory() as work: - (Path(work) / "ps_bary.spv").touch() - for name, frame, expected in ( - ("triangle gradient", triangle, True), - ("both paths return zero", [(0.0, 0.0, 0.0, 0.0)] * 4096, False), - ("one raw barycentric is wrong", wrong_raw, False), - ): - with self.subTest(frame=name): - raw = self.raw(b"".join(struct.pack("<4f", *pixel) for pixel in frame)) - with patch.object(check, "pixels", return_value=(frame, "")): - standalone = check.pixel_test(work, work, "ps_bary") - self.assertEqual((rgt.check_bary(raw)[0], standalone == ""), (expected, expected)) - - def test_d16_gradient_rejects_swapped_halves(self): - # Binary16 encodings of UNORM8 texels 0, 32, ... 224. - words = (0x0000, 0x3004, 0x3404, 0x3606, 0x3804, 0x3905, 0x3a06, 0x3b07) - levels = [struct.unpack(" int: - # Only the low 16 bits of the first three exports carry an interpolation result. - return 0xffff0000 | struct.unpack(" tuple[int, str]: - """run_suite on one pixel test whose harness writes `data` as its readback (None: writes nothing).""" - with tempfile.TemporaryDirectory() as directory: - work = Path(directory) - args = SimpleNamespace(filter=f"{name}.asm", build=directory, llvm_mc="unused") - - def launch(cmd: list[str], **kwargs: object) -> tuple[int, str]: - if cmd[0] == sys.executable: - (work / "spirv" / f"{name}.spv").touch() - elif Path(cmd[0]).stem == "vk_harness": - if data is not None: - Path(cmd[-1]).write_bytes(data) - else: - self.fail(f"unexpected command: {cmd}") - return 0, "" - - output = io.StringIO() - with (patch.object(rgt, "assemble_to_s", side_effect=lambda _mc, _src, dst, _name: Path(dst).touch()), - patch.object(rgt, "spirv_as"), - patch.object(rgt, "run_cmd", side_effect=launch), - # ps_ij_computed is skipped under either PerVertexKHR fallback, which is on by default on a device - # where PerVertexKHR does not compile (or with no device): this test is about its readback - patch.object(rgt, "bary_fallback", return_value=False), - patch.object(rgt, "f16_interp_fallback", return_value=False), - redirect_stdout(output)): - result = rgt.run_suite(args, directory) - return result, output.getvalue() - - def test_bad_readbacks_fail_the_test_without_stopping_the_suite(self) -> None: - for name in ("ps_interp_f16_high", "ps_ij_computed"): - for label, data in (("missing", None), ("empty", b""), ("partial pixel", bytes(8)), - ("one byte short of a frame", bytes(64 * 64 * 16 - 1))): - with self.subTest(test=name, readback=label): - result, output = self.run_test(name, data) - self.assertEqual(result, 1, output) - self.assertIn(f"FAIL {name}", output) - self.assertIn("0/1 passed", output) # the summary line: the suite ran to its end - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/test_run_gpu_tests.py b/tests/test_run_gpu_tests.py deleted file mode 100644 index 7c165201f..000000000 --- a/tests/test_run_gpu_tests.py +++ /dev/null @@ -1,844 +0,0 @@ -"""scripts/run_gpu_tests.py: how it judges the output of a compute "dump" test (no device needed).""" -import contextlib -import io -import json -import os -from pathlib import Path -import struct -import sys -import tempfile -from types import SimpleNamespace -import unittest -from unittest.mock import patch - -sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "scripts")) -import run_gpu_tests as rgt -import check # runtime/test/shaders, on the path once run_gpu_tests is imported - -WANT = [55, 48] -DEVICE_32 = "device: X (subgroup 32..32)\n" -DEVICE_64 = "device: X (subgroup 32..64)\n" -CONFIRMED = "compute subgroup size: 64\n" - - -class BarycentricFallbackSelection(unittest.TestCase): - def setUp(self): - rgt._BARYCENTRIC_FALLBACK.clear() - - def test_env_override(self): - with patch.dict(os.environ, {"LEONIDA_BARY_FALLBACK": "1"}, clear=False): - self.assertTrue(rgt.bary_fallback()) - with patch.dict(os.environ, {"LEONIDA_BARY_FALLBACK": "0"}, clear=False): - proc = SimpleNamespace(stdout='{"barycentric_fallback": true}\n') - with patch.object(rgt.subprocess, "run", return_value=proc): - self.assertFalse(rgt.bary_fallback()) - - def test_anv_probe_is_selected_when_env_is_unset(self): - with patch.dict(os.environ, {}, clear=False): - os.environ.pop("LEONIDA_BARY_FALLBACK", None) - proc = SimpleNamespace(stdout='{"barycentric_fallback": true}\n') - with patch.object(rgt.subprocess, "run", return_value=proc): - self.assertTrue(rgt.bary_fallback()) - - def test_env_override_beats_the_probe(self): - """#5933: =0 brings back native barycentrics on a device the probe flags (gfx90c on AMD's Windows driver), - and =1 does not need the probe at all.""" - proc = SimpleNamespace(stdout='{"barycentric_fallback": true, "vendor_id": 4098, "device_id": 5607, ' - '"driver_id": 1}\n') - with patch.object(rgt.subprocess, "run", return_value=proc) as run: - with patch.dict(os.environ, {"LEONIDA_BARY_FALLBACK": "0"}, clear=False): - self.assertIs(rgt.bary_fallback(), False) - with patch.dict(os.environ, {"LEONIDA_BARY_FALLBACK": "1"}, clear=False): - self.assertIs(rgt.bary_fallback(), True) - run.assert_not_called() - with patch.dict(os.environ, {}, clear=False): - os.environ.pop("LEONIDA_BARY_FALLBACK", None) - self.assertIs(rgt.bary_fallback(), True) - run.assert_called_once() - - def test_probe_failure_is_not_a_fallback(self): - with patch.dict(os.environ, {}, clear=False): - os.environ.pop("LEONIDA_BARY_FALLBACK", None) - with patch.object(rgt.subprocess, "run", side_effect=OSError("no Vulkan")): - self.assertIs(rgt.bary_fallback(), False) - - -def dump(words, pad=8): - return "out[0..7] = " + " ".join(str(w) for w in (list(words) + [0] * pad)[:8]) + "\n" - - -def judge(rc, msg, **kw): - kw = {"wave64": False, "partial": False, "emulated": False, **kw} - return rgt.judge_cs_dump(rc, msg, WANT, **kw) - - -class DumpWords(unittest.TestCase): - def test_eight_decimal_words(self): - self.assertEqual(rgt.dump_words("noise\n" + dump(WANT) + "tail\n"), WANT + [0] * 6) - - def test_anything_else_is_not_a_dump(self): - for line in ("out[0..7] = 55 48\n", "out[0..7] = 55 48 BAD 0 0 0 0 0\n", "out[0..7] = 1 BAD 3\n", - "out[0..7] = 55 48 0 0 0 0 0\n", "out[0..7] = 55 48 0 0 0 0 0 0 0\n", - "out[0..7] = 55 48 0 0 0 0 0 0 x\n", "out[0..7] = \n", "no dump here\n"): - with self.subTest(line=line): - self.assertIsNone(rgt.dump_words(line)) - - -class PackedFormatFixture(unittest.TestCase): - def test_filtered_suite_counts_a_packed_store_mismatch(self): - name = "cs_fmt_1010102" - with tempfile.TemporaryDirectory() as tmp: - args = SimpleNamespace(filter=name, build=tmp, llvm_mc="unused") - - def translate(_cmd, env=None, gpu=True): - (Path(tmp) / "spirv" / f"{name}.spv").touch() - return 0, "" - - output = io.StringIO() - problem = "word 15: expected 0xffe00003, got 0xe00003ff" - with (patch.object(rgt, "assemble_to_s", side_effect=lambda _mc, _src, dst, _name: Path(dst).touch()), - patch.object(rgt, "spirv_as"), - patch.object(rgt, "run_cmd", side_effect=translate), - patch.object(rgt, "fmt_1010102_test", return_value=problem) as check_fmt, - contextlib.redirect_stdout(output)): - self.assertEqual(rgt.run_suite(args, tmp), 1) - check_fmt.assert_called_once() - self.assertIn(problem, output.getvalue()) - self.assertIn("0/1 passed", output.getvalue()) - - -class FrameReadbackTest(unittest.TestCase): - def test_only_a_frame_written_by_this_run_can_pass(self): - name = "ps_ops" - pixels = struct.pack("<4I", 0x48804300, 5, 7, 0xBFFFFFFC) * 4096 - for existing, writes_frame, expected in ((True, False, 1), (False, False, 1), (True, True, 0)): - with self.subTest(existing=existing, writes_frame=writes_frame), tempfile.TemporaryDirectory() as tmp: - raw = Path(tmp, "raw", f"{name}.raw") - if existing: - raw.parent.mkdir() - raw.write_bytes(pixels) - args = SimpleNamespace(filter="ps_ops.asm", build=tmp, llvm_mc="unused") - - def launch(cmd, **kwargs): - if cmd[:3] == [sys.executable, "-I", rgt.TRANSLATOR]: - (Path(tmp) / "spirv" / f"{name}.spv").touch() - elif writes_frame: - raw.write_bytes(pixels) - return SimpleNamespace(returncode=0, stdout="", stderr="") - - output = io.StringIO() - with (patch.object(rgt, "assemble_to_s", side_effect=lambda _mc, _src, dst, _name: Path(dst).touch()), - patch.object(rgt, "spirv_as"), - patch.object(rgt, "bary_fallback", return_value=False), - patch.object(rgt, "f16_interp_fallback", return_value=False), - patch.object(rgt.subprocess, "run", side_effect=launch), - contextlib.redirect_stdout(output)): - self.assertEqual(rgt.run_suite(args, tmp), expected, output.getvalue()) - if expected: - self.assertIn("missing readback", output.getvalue()) - self.assertFalse(raw.exists()) - else: - self.assertEqual(raw.read_bytes(), pixels) - - -class TextureTestOnASmallPushConstantDevice(unittest.TestCase): - """vk_texture_test exits 77 on a device with 128 push constant bytes: a SKIP, not a FAIL.""" - UNSUPPORTED_MSG = "unsupported: need 144 push constant bytes, device has 128\n" - - def run_one(self, name, require_pass=False): - with tempfile.TemporaryDirectory() as tmp: - args = SimpleNamespace(filter=name, build=tmp, llvm_mc="unused", require_pass=require_pass) - - def launch(cmd: list[str], **_kwargs: object) -> SimpleNamespace: - if cmd[:3] == [sys.executable, "-I", rgt.TRANSLATOR]: - (Path(tmp) / "spirv" / f"{name}.spv").touch() - return SimpleNamespace(returncode=0, stdout="", stderr="") - return SimpleNamespace(returncode=77, stdout="", stderr=self.UNSUPPORTED_MSG) - - output = io.StringIO() - with (patch.object(rgt, "assemble_to_s", side_effect=lambda _mc, _src, dst, _name: Path(dst).touch()), - patch.object(rgt, "spirv_as"), - patch.object(rgt.subprocess, "run", side_effect=launch), - contextlib.redirect_stdout(output), contextlib.redirect_stderr(output)): - rc = rgt.run_suite(args, tmp) - return rc, output.getvalue() - - def test_bindless_texture_and_gather_tests_skip(self): - for name in ("ps_cube_sample", "ps_texture_sample_d16", "ps_gather_wrap", "ps_array_resinfo"): - with self.subTest(name=name): - rc, out = self.run_one(name) - self.assertEqual(rc, 0, out) - self.assertIn("SKIP (unsupported: need 144 push constant bytes, device has 128)", out) - self.assertIn("0/1 passed, 1 skipped", out) - self.assertNotIn("no runnable", out) - - def test_require_pass_rejects_a_skip_only_run(self): - rc, out = self.run_one("ps_gather_wrap", require_pass=True) - self.assertEqual(rc, 1, out) - self.assertIn("0/1 passed, 1 skipped", out) - self.assertIn("--require-pass: no GPU tests passed", out) - - -class BindlessTestOnASmallPushConstantDevice(unittest.TestCase): - """vk_bindless_test (ps_tex) exits 77 below its 144 push constant bytes (TEST-149): a SKIP with that reason.""" - - def run_ps_tex(self, rc, msg): - with tempfile.TemporaryDirectory() as tmp: - args = SimpleNamespace(filter="ps_tex.asm", build=tmp, llvm_mc="unused") # not ps_texoff etc. - - def run(cmd, env=None, gpu=True): - if Path(cmd[0]).stem == "vk_bindless_test": - return rc, msg - (Path(tmp) / "spirv" / "ps_tex.spv").touch() # rdna2spirv.py "translating" the shader - return 0, "" - - output = io.StringIO() - with (patch.object(rgt, "assemble_to_s", side_effect=lambda _mc, _src, dst, _name: Path(dst).touch()), - patch.object(rgt, "spirv_as"), - patch.object(rgt, "run_cmd", side_effect=run), - contextlib.redirect_stdout(output), contextlib.redirect_stderr(output)): - suite_rc = rgt.run_suite(args, tmp) - return suite_rc, output.getvalue() - - def test_too_few_push_constant_bytes_skip(self): - rc, out = self.run_ps_tex(77, "device: X\nunsupported: need 144 push constant bytes, device has 128") - self.assertEqual(rc, 0, out) - self.assertIn("SKIP (unsupported: need 144 push constant bytes, device has 128)", out) - self.assertIn("0/1 passed, 1 skipped", out) - - def test_other_failures_still_fail(self): - rc, out = self.run_ps_tex(1, "device: X\nps_tex: 12 pixels differ") - self.assertEqual(rc, 1, out) - self.assertIn("0/1 passed", out) - self.assertNotIn("skipped", out) - - -class StoreHelperUnsupported(unittest.TestCase): - """vk_store_test exits 77 when the device lacks a feature (TEST-469): a SKIP that quotes why, not a FAIL.""" - - def run_store(self, shader, rc, msg): - with tempfile.TemporaryDirectory() as tmp: - args = SimpleNamespace(filter=f"{shader}.asm", build=tmp, llvm_mc="unused") - - def run(cmd, env=None, gpu=True): - if Path(cmd[0]).stem == "vk_store_test": - return rc, msg - (Path(tmp) / "spirv" / f"{shader}.spv").touch() # rdna2spirv.py "translating" the shader - return 0, "" - - output = io.StringIO() - with (patch.object(rgt, "assemble_to_s", side_effect=lambda _mc, _src, dst, _name: Path(dst).touch()), - patch.object(rgt, "spirv_as"), - patch.object(rgt, "run_cmd", side_effect=run), - contextlib.redirect_stdout(output), contextlib.redirect_stderr(output)): - suite_rc = rgt.run_suite(args, tmp) - return suite_rc, output.getvalue() - - def test_unsupported_is_a_skip_with_its_reason(self): - for shader in ("cs_imgstore", "cs_imgload", "cs_imgload_tfe", "cs_imgload_d16", "cs_imgload_d16_tfe"): - with self.subTest(shader=shader): - rc, out = self.run_store(shader, 77, "unsupported: shaderStorageImageWriteWithoutFormat=0\ndevice: X") - self.assertEqual(rc, 0, out) - self.assertIn("SKIP (unsupported: shaderStorageImageWriteWithoutFormat=0)", out) - self.assertIn("0/1 passed, 1 skipped", out) - - def test_other_failures_still_fail(self): - rc, out = self.run_store("cs_imgstore", 1, "device: X\nFAILED: texel 3 is 0x0") - self.assertEqual(rc, 1, out) - self.assertIn("FAILED: texel 3 is 0x0", out) - self.assertNotIn("skipped", out) - - -INT64 = "unsupported: m.spv declares Int64 and the device has no shaderInt64\n" -INT64_SKIP = "SKIP (unsupported: m.spv declares Int64 and the device has no shaderInt64)" -# judge_cs_dump quotes the reason without the "unsupported:" prefix (87da93277, which wins over the wave64 skip). -INT64_JUDGE_SKIP = "SKIP (m.spv declares Int64 and the device has no shaderInt64)" - - -class ComputeFeatureUnsupported(unittest.TestCase): - """vk_compute_test exits 77 with an "unsupported: ..." line when the module needs a feature the device lacks - (Int64, Float64, OpFmaKHR): a SKIP that quotes it in every compute test, not only under --require-wave64.""" - - def test_judge_skips_a_named_feature_in_every_mode(self): - self.assertEqual(judge(77, DEVICE_32 + INT64), (None, INT64_JUDGE_SKIP)) - self.assertEqual(judge(77, DEVICE_32 + INT64, partial=True), (None, INT64_JUDGE_SKIP)) - # A 64-wide device without Int64: the feature is the cause, not the subgroup width. - self.assertEqual(judge(77, DEVICE_64 + INT64, wave64=True), (None, INT64_JUDGE_SKIP)) - - def test_judge_keeps_the_wave64_wording_and_fails_a_bare_77(self): - self.assertEqual(judge(77, DEVICE_32 + "full 64-wide compute subgroups unavailable\n", wave64=True), - (None, "SKIP (no 64-wide compute subgroup on this device)")) - ok, _ = judge(77, DEVICE_32 + "something else went wrong\n") - self.assertIs(ok, False) - - def run_compute(self, shader, rc, msg): - calls = [] - with tempfile.TemporaryDirectory() as tmp: - args = SimpleNamespace(filter=f"{shader}.asm", build=tmp, llvm_mc="unused") - - def run(cmd, env=None, gpu=True): - if Path(cmd[0]).stem == "vk_compute_test": - calls.append(cmd) - return rc, msg - (Path(tmp) / "spirv" / f"{shader}.spv").touch() - return 0, "" - - output = io.StringIO() - with (patch.dict(rgt.os.environ, {"LEONIDA_W64_EMULATE": ""}, clear=False), - patch.object(rgt, "assemble_to_s", side_effect=lambda _mc, _src, dst, _name: Path(dst).touch()), - patch.object(rgt, "spirv_as"), - patch.object(rgt, "run_cmd", side_effect=run), - contextlib.redirect_stdout(output), contextlib.redirect_stderr(output)): - suite_rc = rgt.run_suite(args, tmp) - return suite_rc, output.getvalue(), calls - - def test_every_compute_call_site_skips(self): - # One shader per way the runner reads vk_compute_test: judge_cs_dump (cs_bounds), its own checks (cs_lds, - # cs_workgroup_yz, cs_heap_init), one dispatch per input (cs_cvt_f32_sat), cs_f64_add and wavemask_check. - for shader in ("cs_bounds", "cs_lds", "cs_workgroup_yz", "cs_heap_init", "cs_cvt_f32_sat", "cs_f64_add", - "cs_wavemask"): - with self.subTest(shader=shader): - rc, out, _ = self.run_compute(shader, 77, "device: X (subgroup 32..32)\n" + INT64) - self.assertEqual(rc, 0, out) - self.assertIn(INT64_SKIP, out) - self.assertIn("0/1 passed, 1 skipped", out) - - def test_one_refused_input_stops_the_per_input_loop(self): - _, _, calls = self.run_compute("cs_cvt_f32_sat", 77, INT64) - self.assertEqual(len(calls), 1) - - def test_check_py_helpers_skip_a_named_feature(self): - # check.py's own runner and the cs_fmt_* rows go through dump_test/compute_test, not run_cmd. - with tempfile.TemporaryDirectory() as tmp, patch.object(check, "run", return_value=(77, INT64)): - for result in (check.dump_test(tmp, tmp, "cs_fmt_1010102", [1], 1), - check.compute_test(tmp, tmp, "cs_bounds", "1", "dump")): - self.assertIsInstance(result, check.Skip) - self.assertEqual(result, INT64_SKIP) - with tempfile.TemporaryDirectory() as tmp, patch.object(check, "run", return_value=(77, "no reason")): - self.assertEqual(check.dump_test(tmp, tmp, "cs_fmt_1010102", [1], 1), "exit 77: no reason") - - def test_a_check_py_skip_counts_as_skipped(self): - # The cs_fmt_* rows record (name, not problem, problem): a Skip there is a skip, not a failure. - with tempfile.TemporaryDirectory() as tmp: - args = SimpleNamespace(filter="cs_fmt_1010102.asm", build=tmp, llvm_mc="unused") - - def translate(_cmd, env=None, gpu=True): - (Path(tmp) / "spirv" / "cs_fmt_1010102.spv").touch() - return 0, "" - - output = io.StringIO() - with (patch.object(rgt, "assemble_to_s", side_effect=lambda _mc, _src, dst, _name: Path(dst).touch()), - patch.object(rgt, "spirv_as"), - patch.object(rgt, "run_cmd", side_effect=translate), - patch.object(rgt, "fmt_1010102_test", return_value=check.Skip(INT64_SKIP)), - contextlib.redirect_stdout(output), contextlib.redirect_stderr(output)): - rc = rgt.run_suite(args, tmp) - self.assertEqual(rc, 0, output.getvalue()) - self.assertIn("SKIP cs_fmt_1010102", output.getvalue()) - self.assertIn("0/1 passed, 1 skipped", output.getvalue()) - - def test_a_bare_77_still_fails(self): - for shader in ("cs_bounds", "cs_lds", "cs_heap_init"): - with self.subTest(shader=shader): - rc, out, _ = self.run_compute(shader, 77, "device: X (subgroup 32..32)\nsomething else went wrong") - self.assertEqual(rc, 1, out) - self.assertNotIn("skipped", out) - - -class FilterWithoutRunnableCases(unittest.TestCase): - """A filter selecting only an input shader (cs_bench_mix) must not report 0/0 passed with exit 0.""" - - def run_filter(self, name, translate_rc=0, spv=True): - with tempfile.TemporaryDirectory() as tmp: - args = SimpleNamespace(filter=name, build=tmp, llvm_mc="unused") - - def translate(_cmd, env=None, gpu=True): - if spv: - (Path(tmp) / "spirv" / f"{name}.spv").touch() - return translate_rc, "" - - out, err = io.StringIO(), io.StringIO() - with (patch.object(rgt, "assemble_to_s", side_effect=lambda _mc, _src, dst, _name: Path(dst).touch()) as asm, - patch.object(rgt, "spirv_as"), - patch.object(rgt, "run_cmd", side_effect=translate) as run, - patch.object(rgt, "fmt_1010102_test", return_value=None), - contextlib.redirect_stdout(out), contextlib.redirect_stderr(err)): - rc = rgt.run_suite(args, tmp) - return rc, out.getvalue(), err.getvalue(), asm, run - - def test_benchmark_input_reports_no_runnable_cases(self): - rc, out, err, _, _ = self.run_filter("cs_bench_mix") - self.assertEqual(rc, 2, out + err) - self.assertIn("--filter 'cs_bench_mix' selected cs_bench_mix but no runnable GPU test cases", err) - self.assertIn("inputs without a GPU test row", err) - self.assertIn("benchmark tool", err) - self.assertIn("=== rdna2spirv.py ===", out) - self.assertNotIn("0/0 passed", out) - - def test_translation_failure_stays_a_failure(self): - rc, out, err, _, _ = self.run_filter("cs_bench_mix", translate_rc=1) - self.assertEqual((rc, err), (1, "")) - rc, out, err, _, _ = self.run_filter("cs_bench_mix", spv=False) - self.assertEqual((rc, err), (1, "")) - self.assertIn("missing .spv (translation failed)", out) - self.assertIn("0/1 passed", out) - - def test_supported_case_still_passes(self): - rc, out, err, _, _ = self.run_filter("cs_fmt_1010102") - self.assertEqual((rc, err), (0, "")) - self.assertIn("1/1 passed", out) - - def test_unmatched_filter_fails_before_the_tools_run(self): - rc, out, err, asm, run = self.run_filter("unmatched_nicofilter") - self.assertEqual(rc, 2) - self.assertEqual(err, "error: --filter 'unmatched_nicofilter' matched no GPU test cases\n") - asm.assert_not_called() - run.assert_not_called() - - -class WholeWaveDump(unittest.TestCase): - """wave64: run with --require-wave64 (the whole-wave mask tests).""" - def judge(self, rc, msg): - return judge(rc, msg, wave64=True) - - def test_passes_with_the_words_and_the_confirmation(self): - self.assertEqual(self.judge(0, DEVICE_64 + CONFIRMED + dump(WANT)), (True, "55 48")) - - def test_a_device_without_64_wide_subgroups_skips(self): - ok, detail = self.judge(77, DEVICE_32 + "full 64-wide compute subgroups unavailable\n") - self.assertIs(ok, None) - self.assertTrue(detail.startswith("SKIP")) - - def test_a_77_with_an_unsupported_reason_keeps_that_reason(self): - """A 64-wide device, a module that needs OpFmaKHR the device lacks: the skip names OpFmaKHR, not the subgroup.""" - msg = ("unsupported: cs_x.spv needs OpFmaKHR (VK_KHR_shader_fma, shaderFmaFloat32) and the device lacks it; " - "translate with --fma glsl\n") - ok, detail = self.judge(77, DEVICE_64 + msg) - self.assertIs(ok, None) - self.assertTrue(detail.startswith("SKIP (cs_x.spv needs OpFmaKHR"), detail) - self.assertNotIn("64-wide", detail) - - def test_right_words_without_the_confirmation_fail(self): # a vk_compute_test that ignores the flag - ok, detail = self.judge(0, DEVICE_64 + dump(WANT)) - self.assertIs(ok, False) - self.assertIn("not confirmed", detail) - - def test_wrong_word_and_harness_errors_fail(self): - for i in range(len(WANT)): - wrong = list(WANT) - wrong[i] ^= 1 - with self.subTest(word=i): - self.assertIs(self.judge(0, CONFIRMED + dump(wrong))[0], False) - self.assertIs(self.judge(1, "Vulkan pipeline failed\n")[0], False) # an error is not a skip - self.assertIs(self.judge(1, CONFIRMED + dump(WANT))[0], False) - - def test_malformed_dump_lines_fail_without_raising(self): - for line in ("out[0..7] = 55 48\n", "out[0..7] = 55 48 BAD 0 0 0 0 0\n", "out[0..7] = 1 BAD 3\n", - "out[0..7] = 55 48 0 0 0 0 0 0 0\n"): - with self.subTest(line=line): - ok, detail = self.judge(0, CONFIRMED + line) - self.assertIs(ok, False) - self.assertIn(line.strip(), detail) - - -class NotWholeWave(unittest.TestCase): - """Dumps run without --require-wave64: cs_store, emulated wave64 (#152) and partial-group tests.""" - def test_plain_dump_needs_no_confirmation_and_a_77_is_a_failure(self): - self.assertEqual(judge(0, dump(WANT)), (True, "55 48")) - self.assertIs(judge(77, "unavailable\n")[0], False) - - def test_a_77_with_an_unsupported_reason_is_a_skip(self): - """A module that needs OpFmaKHR on a device without VK_KHR_shader_fma: vk_compute_test exits 77 with a reason.""" - msg = ("unsupported: cs_x.spv needs OpFmaKHR (VK_KHR_shader_fma, shaderFmaFloat32) and the device lacks it; " - "translate with --fma glsl\n") - for kw in ({}, {"emulated": True}, {"partial": True}): - with self.subTest(**kw): - ok, detail = judge(77, DEVICE_32 + msg, **kw) - self.assertIs(ok, None) - self.assertTrue(detail.startswith("SKIP (cs_x.spv needs OpFmaKHR"), detail) - self.assertIs(judge(77, DEVICE_32 + "no reason given\n")[0], False) # a bare 77 stays a failure - - def test_hex_words(self): - ok, detail = rgt.judge_cs_dump(0, dump([0x400080FF, 7]), [0x400080FF, 7], wave64=False, partial=False, - emulated=False, hexwords=True) - self.assertEqual((ok, detail), (True, "0x400080ff 0x7")) - - def test_emulated_wave64_runs_on_any_subgroup_size_without_the_confirmation(self): - self.assertEqual(judge(0, DEVICE_32 + dump(WANT), emulated=True), (True, "55 48")) - self.assertIs(judge(77, DEVICE_32, emulated=True)[0], False) # no skip: it must run here - self.assertIs(judge(0, DEVICE_32 + dump([1, 2]), emulated=True)[0], False) - - def test_partial_group_skips_unless_the_device_reports_a_64_subgroup(self): - ok, detail = judge(0, DEVICE_32 + dump(WANT), partial=True) - self.assertIs(ok, None) - self.assertTrue(detail.startswith("SKIP")) - self.assertEqual(judge(0, DEVICE_64 + dump(WANT), partial=True), (True, "55 48")) # no confirmation line - self.assertIs(judge(0, DEVICE_64 + dump([1, 2]), partial=True)[0], False) - - def test_partial_group_emulated_runs_everywhere(self): - self.assertEqual(judge(0, DEVICE_32 + dump(WANT), partial=True, emulated=True), (True, "55 48")) - - def test_malformed_dump_lines_fail_in_every_mode(self): - for kw in ({}, {"emulated": True}, {"partial": True, "emulated": True}): - with self.subTest(**kw): - self.assertIs(judge(0, DEVICE_64 + "out[0..7] = 55 48 BAD 0 0 0 0 0\n", **kw)[0], False) - - - -class UniformBranchCheck(unittest.TestCase): - """check_uniform_branch (ps_uniform_branch, ps_scc_mask32) must reject a readback in which no bit=0 pixel got - s5 = 8: that is what a translator deciding the branch per lane draws (#477, measured on RTX 5080 and RX 9070 XT: - 1856 (8,1) / 192 (8,0) / 2048 (7,0) with the vote, 1856 / 0 / 2240 without).""" - - @staticmethod - def judge(rows): - import os - import struct - import tempfile - fd, path = tempfile.mkstemp(suffix=".raw") - try: - with os.fdopen(fd, "wb") as f: # the rows repeated over a full 64x64 frame (a short one fails, TEST-29) - for k in range(64 * 64): - s5, bit, bary = rows[k % len(rows)] - f.write(struct.pack("<2I2f", s5, bit, bary, 0.0)) - return rgt.check_uniform_branch(path) - finally: - os.remove(path) - - def test_wave_vote_passes(self): - ok, detail = self.judge([(8, 1, 0.5), (8, 0, 0.1), (7, 0, 0.1)]) - self.assertTrue(ok, detail) - - def test_per_lane_decision_fails(self): - ok, detail = self.judge([(8, 1, 0.5), (7, 0, 0.1), (7, 0, 0.1)]) - self.assertFalse(ok) - self.assertIn("no bit=0 pixel got s5=8", detail) - - def test_set_bit_without_8_fails(self): - self.assertFalse(self.judge([(7, 1, 0.5), (8, 0, 0.1), (7, 0, 0.1)])[0]) - - -class Wave32LaneDumps(unittest.TestCase): - """run_gpu_tests.py skips cs_wqm_w32 and cs_w32_lane_wrap below 32 lanes with check.py's rule.""" - def test_process_exit_takes_precedence_in_both_runners(self): - import check - name = "cs_w32_lane_wrap" - narrow = "device: synthetic (subgroup 8..16)\n" - for code, msg, skipped in ((1, narrow, False), (0, narrow, True), - (77, "unsupported: device feature unavailable\n", True)): - with self.subTest(code=code), tempfile.TemporaryDirectory() as tmp: - with patch.object(check, "run", return_value=(code, msg)): - verdict = check.compute_test(tmp, tmp, name, "1", "dump", needs_32_lanes=True) - with self.subTest(runner="check.py"): - self.assertEqual(isinstance(verdict, check.Skip), skipped, verdict) - if not skipped: - self.assertIn("exit 1", verdict) - - def launch(cmd, **kwargs): - if cmd[:3] == [sys.executable, "-I", rgt.TRANSLATOR]: - (Path(tmp) / "spirv" / f"{name}.spv").touch() - return 0, "" - return code, msg - - args = SimpleNamespace(filter=name, build=tmp, llvm_mc="unused") - output = io.StringIO() - with (patch.object(rgt, "assemble_to_s", side_effect=lambda mc, src, dst, n: Path(dst).touch()), - patch.object(rgt, "spirv_as"), patch.object(rgt, "run_cmd", side_effect=launch), - contextlib.redirect_stdout(output)): - status = rgt.run_suite(args, tmp) - self.assertEqual(status, 0 if skipped else 1, output.getvalue()) - self.assertIn(f"{'SKIP' if skipped else 'FAIL'} {name}", output.getvalue()) - - def test_uses_check_py_rule(self): - import check - self.assertIs(rgt.narrow_subgroup_skip, check.narrow_subgroup_skip) - self.assertIs(rgt.wave32_lane_skip, check.wave32_lane_skip) - self.assertIs(rgt.WAVE32_LANE_DUMPS, check.WAVE32_LANE_DUMPS) - self.assertIs(rgt.WAVE32_LANE_ENV, check.WAVE32_LANE_ENV) - - def test_unpinned_rule(self): - self.assertEqual(rgt.wave32_lane_skip("device: X (subgroup 8..32)\ncompute subgroup size: 32 not available\n"), - "SKIP (the device can't run this shader at 32 lanes on request)") - self.assertIsNone(rgt.wave32_lane_skip("device: X (subgroup 8..32)\ncompute subgroup size: 32\n")) - observed = "compute subgroup size: 32 (observed: all 20 invocations of a 20x1x1 group)\n" - self.assertIsNone(rgt.wave32_lane_skip("device: Apple M3 Max (subgroup 4..32)\n" + observed)) - wrong = "compute subgroup size: 32 observed wrong in 4 of 64 invocations; invocation 60 has SubgroupSize 32\n" - self.assertIsNone(rgt.wave32_lane_skip("device: X (subgroup 4..32)\n" + wrong)) - ok, detail = rgt.judge_cs_dump(1, "device: X (subgroup 4..32)\n" + wrong, [1], wave64=False, partial=False, - emulated=False) - self.assertIs(ok, False) - self.assertIn("observed wrong", detail) - - def test_rule(self): - self.assertEqual(rgt.narrow_subgroup_skip("device: llvmpipe (subgroup 8..8)\n"), - "SKIP (subgroup 8 is narrower than 32 lanes)") - for out in ("device: X (subgroup 32..32)\n", "device: X (subgroup 8..32)\n", "device: X (subgroup 32..64)\n", - "no device line\n"): - with self.subTest(out=out): - self.assertIsNone(rgt.narrow_subgroup_skip(out)) - - -class SubgroupPinSkip(unittest.TestCase): - """A device that cannot pin the wave size a shader was translated for skips, not fails. GCN3/GCN4 report - 64..64, so cs_barrier_loop's wave32 fixture runs at 64 lanes and its words say nothing; check.py skips it - already (unpinned_subgroup_skip), the runner used to judge it and report a failure.""" - MSG = "device: X (subgroup 64..64)\ncompute subgroup size: 32 not available\n" + dump(WANT) - - def test_unpinned_size_is_a_skip(self): - self.assertEqual(rgt.subgroup_pin_skip(self.MSG, {"VKC_SUBGROUP_SIZE": "32"}), - "SKIP (the device can't run this shader at 32 lanes on request)") - - def test_no_pin_requested_is_judged(self): - for env in (None, {}, {"VKC_SGPRS": "0x1"}, {"VKH_SUBGROUP_SIZE": "64"}): - with self.subTest(env=env): - self.assertIsNone(rgt.subgroup_pin_skip(self.MSG, env)) - - def test_a_honoured_pin_is_judged(self): - out = "device: X (subgroup 32..64)\ncompute subgroup size: 32\n" + dump(WANT) - self.assertIsNone(rgt.subgroup_pin_skip(out, {"VKC_SUBGROUP_SIZE": "32"})) - self.assertIsNone(rgt.subgroup_pin_skip("device: X (subgroup 32..64)\n" + dump(WANT), - {"VKC_SUBGROUP_SIZE": "32"})) - - def test_only_wave_width_fixtures_carry_the_rule(self): - self.assertIn("cs_barrier_loop", rgt.WAVE32_PIN_DUMPS) - # everything else is judged at the device's own width, as before, so a 64-only device keeps testing it - for name in ("cs_store", "cs_smem_soffset_imm", "cs_w32_int_ext", "cs_barrier_divergent", - "cs_barrier_early_end", "cs_w32_lds_u8_d16"): - with self.subTest(name=name): - self.assertNotIn(name, rgt.WAVE32_PIN_DUMPS) - - -class ComputedIJWithoutPerVertexInputs(unittest.TestCase): - """ps_ij_computed (SHADER-177): without PerVertexKHR inputs (--bary-fallback, --f16-interp-fallback, the latter on - by default on MoltenVK) the translator refuses the computed I/J pair, so there is no .spv. Both runners SKIP it - there, before their missing-.spv check; a missing .spv without a fallback stays a translation failure.""" - NAME = "ps_ij_computed" - - def run_suite(self, bary, f16): - with tempfile.TemporaryDirectory() as tmp: - args = SimpleNamespace(filter=self.NAME, build=tmp, llvm_mc="unused") - env = {"LEONIDA_BARY_FALLBACK": "1" if bary else "0", "LEONIDA_F16_INTERP_FALLBACK": "1" if f16 else "0"} - out = io.StringIO() - with (patch.dict(rgt.os.environ, env), - patch.object(rgt, "assemble_to_s", side_effect=lambda _mc, _src, dst, _name: Path(dst).touch()), - patch.object(rgt, "spirv_as"), - patch.object(rgt, "run_cmd", return_value=(0, "1 shaders: 0 translated, 0 pass spirv-val")), # refused - contextlib.redirect_stdout(out), contextlib.redirect_stderr(out)): - rc = rgt.run_suite(args, tmp) - return rc, out.getvalue() - - def test_run_gpu_tests_skips_under_either_fallback(self): - for bary, f16 in ((True, False), (False, True)): - with self.subTest(bary=bary, f16=f16): - rc, out = self.run_suite(bary, f16) - self.assertIn("SKIP (computed I/J pairs need PerVertexKHR inputs", out) - self.assertIn("0/1 passed, 1 skipped", out) - self.assertNotIn("missing .spv", out) - self.assertEqual(rc, 0, out) - - def test_run_gpu_tests_missing_spv_without_fallback_still_fails(self): - rc, out = self.run_suite(False, False) - self.assertIn("missing .spv (translation failed)", out) - self.assertEqual(rc, 1, out) - - def test_check_py_skips_before_its_spv_check(self): - import check - with tempfile.TemporaryDirectory() as tmp: - for bary, f16 in ((True, False), (False, True)): - with self.subTest(bary=bary, f16=f16), \ - patch.object(check, "BARY_FALLBACK", bary), patch.object(check, "F16_HALVES", f16): - self.assertIsInstance(check.pixel_test("unused", tmp, self.NAME), check.Skip) - with patch.object(check, "BARY_FALLBACK", False), patch.object(check, "F16_HALVES", False): - self.assertEqual(check.pixel_test("unused", tmp, self.NAME), f"missing {self.NAME}.spv") - - -class F16InterpUnderBaryFallback(unittest.TestCase): - """ps_interp_f16_high and ms_f16_pack under LEONIDA_BARY_FALLBACK=1. --bary-fallback alone has no PerVertexKHR - inputs, so the f16 halves can't be interpolated and both are skipped. With --f16-interp-fallback as well (on by - itself where the device has no fragmentShaderBarycentric, the usual reason for the bary fallback) the pixel shader - reads the decoded halves its producer exports, so both run (llvmpipe, which has neither: both pass).""" - SKIP = "SKIP (per-vertex f16 interpolants need barycentrics)" - DRAWN = "unsupported: drawn by the stub harness" - - def run_suite(self, name, bary, f16): - drawn = [] - - def run_cmd(cmd, env=None, gpu=True): - if rgt.TRANSLATOR in cmd: # the translator publishes a module for every input - out = cmd[cmd.index("--out") + 1] - for s in os.listdir(cmd[cmd.index(rgt.TRANSLATOR) + 1]): - Path(out, Path(s).stem + ".spv").touch() - return 0, "" - if os.path.basename(cmd[0]).startswith("vk_harness"): - drawn.append(cmd) - return rgt.UNSUPPORTED, self.DRAWN - return 0, "" - - with tempfile.TemporaryDirectory() as tmp: - args = SimpleNamespace(filter=name, build=tmp, llvm_mc="unused") - env = {"LEONIDA_BARY_FALLBACK": "1" if bary else "0", "LEONIDA_F16_INTERP_FALLBACK": "1" if f16 else "0"} - out = io.StringIO() - with (patch.dict(rgt.os.environ, env), - patch.dict(sys.modules, {"bary_fallback_gs": SimpleNamespace(build_for_index=lambda _d: [])}), - patch.object(rgt, "assemble_to_s", side_effect=lambda _mc, _src, dst, _name: Path(dst).touch()), - patch.object(rgt, "spirv_as"), - patch.object(rgt, "run_cmd", side_effect=run_cmd), - contextlib.redirect_stdout(out), contextlib.redirect_stderr(out)): - rc = rgt.run_suite(args, tmp) - return rc, out.getvalue(), drawn - - def test_run_gpu_tests_draws_them_with_the_f16_fallback(self): - for name in ("ps_interp_f16_high", "ms_f16_pack"): - with self.subTest(name=name): - rc, out, drawn = self.run_suite(name, bary=True, f16=True) - self.assertNotIn(self.SKIP, out) - self.assertIn(self.DRAWN, out) - self.assertEqual(len(drawn), 1, out) - self.assertTrue(drawn[0][2].endswith("ps_interp_f16_high.spv"), drawn) - self.assertEqual(rc, 0, out) - - def test_run_gpu_tests_skips_them_under_the_bary_fallback_alone(self): - for name in ("ps_interp_f16_high", "ms_f16_pack"): - with self.subTest(name=name): - rc, out, drawn = self.run_suite(name, bary=True, f16=False) - self.assertIn(self.SKIP, out) - self.assertEqual(drawn, [], out) - self.assertEqual(rc, 0, out) - - def test_check_py_draws_it_with_the_f16_fallback(self): - import check - name = "ps_interp_f16_high" - with tempfile.TemporaryDirectory() as tmp: - Path(tmp, name + ".spv").touch() - with patch.object(check, "pixels", return_value=(check.Skip("x"), self.DRAWN)): - for bary, f16, want in ((True, True, f"SKIP ({self.DRAWN})"), - (True, False, "SKIP (per-vertex interpolants need " - "VK_KHR_fragment_shader_barycentric)"), - (False, True, f"SKIP ({self.DRAWN})")): - with self.subTest(bary=bary, f16=f16), \ - patch.object(check, "BARY_FALLBACK", bary), patch.object(check, "F16_HALVES", f16): - self.assertEqual(check.pixel_test("unused", tmp, name), want) - - -class TestProgramThatDiesBeforeItsVerdict(unittest.TestCase): - """The rows whose test program judges itself show its last output line. A program that died first (a driver - crash while it creates a pipeline: exit -11 on Linux, 0xC0000005 on Windows) has only printed its device or - extension line, or nothing, so the FAIL line must carry the exit status to say what happened.""" - DIED = { # one row each: what its program had printed when it died - "cs_lds": "device: X\n", "cs_exec64": "device: X\n", "cs_bvh": "device: X\n", "cs_wavemask": "device: X\n", - "cs_imgstore": "device: X\n", "cs_imgload": "device: X\n", "cs_sample_lz_int_d16": "device: X\n", - "ps_texture_sample": "device: X\nenabled VK_KHR_maintenance8\n", - "ps_texture_sample_d16": "device: X\nenabled VK_KHR_maintenance8\n", - "ps_cube_sample": "device: X\n", "ps_gather_wrap": "device: X\n", - "ps_tex": "", "ps_imgatomic": "", - } - - def run_one(self, name, code, printed): - with tempfile.TemporaryDirectory() as tmp: - args = SimpleNamespace(filter=name + ".asm", build=tmp, llvm_mc="unused", require_pass=False) # one row - - def launch(cmd: list[str], **_kwargs: object) -> SimpleNamespace: - if cmd[:3] == [sys.executable, "-I", rgt.TRANSLATOR]: - (Path(tmp) / "spirv" / f"{name}.spv").touch() - return SimpleNamespace(returncode=0, stdout="", stderr="") - return SimpleNamespace(returncode=code, stdout="", stderr=printed) - - output = io.StringIO() - with (patch.object(rgt, "assemble_to_s", side_effect=lambda _mc, _src, dst, _name: Path(dst).touch()), - patch.object(rgt, "spirv_as"), - patch.object(rgt.subprocess, "run", side_effect=launch), - contextlib.redirect_stdout(output), contextlib.redirect_stderr(output)): - rc = rgt.run_suite(args, tmp) - rows = [ln.split(None, 2) for ln in output.getvalue().splitlines() if ln.startswith(" FAIL")] - return rc, rows, output.getvalue() - - def test_the_fail_line_says_the_program_died(self): - for code in (-11, 0xC0000005): - for name, printed in self.DIED.items(): - with self.subTest(name=name, code=code): - rc, rows, out = self.run_one(name, code, printed) - self.assertEqual(rc, 1, out) - self.assertEqual(len(rows), 1, out) - last = printed.splitlines()[-1] if printed else "no test output" - self.assertEqual(rows[0][1:], [name, f"exit {code}: {last}"], out) - - def test_no_pixel_count_for_a_frame_that_was_never_read(self): - _rc, rows, out = self.run_one("ps_gather_wrap", -11, "device: X\n") - self.assertNotIn("pixels differ", rows[0][2], out) - - def test_a_verdict_keeps_its_line(self): - self.assertEqual(rgt.verdict_line(0, "device: X\ncs_lds: 64 lanes mirrored"), "cs_lds: 64 lanes mirrored") - self.assertEqual(rgt.verdict_line(0, ""), "") - self.assertEqual(rgt.verdict_line(1, "device: X\ncs_lds: lane 3 differs"), "exit 1: cs_lds: lane 3 differs") - rc, rows, out = self.run_one("cs_imgstore", 0, "device: X\ncs_imgstore: 64 texels match\n") - self.assertEqual((rc, rows), (0, []), out) - self.assertIn("PASS cs_imgstore cs_imgstore: 64 texels match", out) - - -class FmaFusedSuite(unittest.TestCase): - """run_gpu_tests.py runs cs_fma_fused under --filter, honoring LEONIDA_FMA=khr vs default glsl.""" - RADV_SPLIT = [0x00000000, 0xA8800000, 0x3A000000, 0x00000000, 0x00000000, 0x00000000, 0x28800000, 0x00007351] - - def run_fma(self, rc, msg, fma_env=None, fma_mode=None): - with tempfile.TemporaryDirectory() as tmp: - if fma_mode: - (Path(tmp) / "spirv").mkdir(parents=True, exist_ok=True) - (Path(tmp) / "spirv" / "index.json").write_text( - json.dumps({"cs_fma_fused": {"fma": fma_mode}}), encoding="utf-8") - args = SimpleNamespace(filter="cs_fma_fused", build=tmp, llvm_mc="unused") - - def fake_run(cmd, env=None, gpu=True): - if Path(cmd[0]).stem == "vk_compute_test": - self.assertEqual((env or {}).get("VKC_SGPRS"), rgt.FMA_FUSED_ENV["VKC_SGPRS"]) - return rc, msg - (Path(tmp) / "spirv" / "cs_fma_fused.spv").touch() - return 0, "" - - output = io.StringIO() - env_patch = {"LEONIDA_FMA": fma_env} if fma_env is not None else {} - with (patch.dict(rgt.os.environ, env_patch, clear=False), - patch.object(rgt, "assemble_to_s", side_effect=lambda _mc, _src, dst, _name: Path(dst).touch()), - patch.object(rgt, "spirv_as"), - patch.object(rgt, "run_cmd", side_effect=fake_run), - contextlib.redirect_stdout(output), contextlib.redirect_stderr(output)): - if fma_env is None: - rgt.os.environ.pop("LEONIDA_FMA", None) - code = rgt.run_suite(args, tmp) - return code, output.getvalue() - - def test_glsl_accepts_radv_split_and_khr_rejects_it(self): - rc, out = self.run_fma(0, dump(self.RADV_SPLIT), fma_env=None) - self.assertEqual(rc, 0, out) - self.assertIn("PASS cs_fma_fused", out) - self.assertIn("5/7 split", out) - rc, out = self.run_fma(0, dump(self.RADV_SPLIT), fma_env="khr") - self.assertEqual(rc, 1, out) - self.assertIn("FAIL cs_fma_fused", out) - - def test_recorded_exact_mode_makes_the_gpu_suite_strict(self): - # TEST-1147: run_gpu_tests must read the same index field as check.py, or an exact build judged - # in a fresh shell accepts split words that the GPU driver really produced. - import check - rc, out = self.run_fma(0, dump(check.FMA_FUSED), fma_mode="exact") - self.assertEqual(rc, 0, out) - rc, out = self.run_fma(0, dump(self.RADV_SPLIT), fma_mode="exact") - self.assertEqual(rc, 1, out) - self.assertIn("FAIL cs_fma_fused", out) - - def test_recorded_glsl_mode_ignores_stale_exact_env(self): - rc, out = self.run_fma(0, dump(self.RADV_SPLIT), fma_mode="glsl", fma_env="exact") - self.assertEqual(rc, 0, out) - self.assertIn("5/7 split", out) - - def test_khr_fused_passes_and_exit_77_skips(self): - import check - rc, out = self.run_fma(0, dump(check.FMA_FUSED), fma_env="khr") - self.assertEqual(rc, 0, out) - self.assertIn("8/8 fused exact (single-rounded FMA: OpFmaKHR or --fma exact)", out) - rc, out = self.run_fma(77, "unsupported: no VK_KHR_shader_fma", fma_env="khr") - self.assertEqual(rc, 0, out) - self.assertIn("SKIP (unsupported: no VK_KHR_shader_fma)", out) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/test_run_gpu_tests_paths.py b/tests/test_run_gpu_tests_paths.py deleted file mode 100644 index 1c5d77115..000000000 --- a/tests/test_run_gpu_tests_paths.py +++ /dev/null @@ -1,265 +0,0 @@ -"""run_gpu_tests.py: a filtered run still builds the vertex shader a selected test draws with, and relative --build -/--work paths keep working for test programs that run in another working directory (vk_texture_test).""" -import io -import os -from pathlib import Path -import subprocess -import sys -import tempfile -import unittest -from types import SimpleNamespace -from unittest.mock import patch - -ROOT = Path(__file__).resolve().parents[1] -sys.path.insert(0, str(ROOT / "scripts")) -import run_gpu_tests - - -class DrawShaders(unittest.TestCase): - def test_texture_sample_brings_vs_ids(self): - self.assertEqual(run_gpu_tests.with_draw_shaders(["ps_texture_sample.asm"]), - ["ps_texture_sample.asm", "vs_ids.asm"]) - - def test_cube_sample_brings_vs_ids(self): - self.assertEqual(run_gpu_tests.with_draw_shaders(["ps_cube_sample.asm"]), - ["ps_cube_sample.asm", "vs_ids.asm"]) - - def test_flat_still_brings_vs_ids(self): - self.assertEqual(run_gpu_tests.with_draw_shaders(["ps_flat.asm"]), ["ps_flat.asm", "vs_ids.asm"]) - - def test_each_filtered_clip_case_brings_ps_clip_color(self): - for name in run_gpu_tests.CLIP_CASES: - with self.subTest(name=name): - selected = f"{name}.asm" - self.assertEqual(run_gpu_tests.with_draw_shaders([selected]), [selected, "ps_clip_color.asm"]) - - def test_vs_ids_is_not_added_twice(self): - files = ["ps_flat.asm", "ps_texture_sample.asm", "vs_ids.asm"] - self.assertEqual(run_gpu_tests.with_draw_shaders(files), files) - - def test_other_shaders_add_nothing(self): - self.assertEqual(run_gpu_tests.with_draw_shaders(["ps_ops.asm"]), ["ps_ops.asm"]) - - def test_every_shader_named_exists(self): - shaders = Path(run_gpu_tests.SHADER_DIR) - for name, extra in run_gpu_tests.DRAWN_WITH.items(): - # the clip cases (#193) are variants of vs_clip.asm with different signatures, not files of their own - source = "vs_clip" if name in run_gpu_tests.CLIP_CASES else name - self.assertTrue((shaders / f"{source}.asm").is_file(), name) - self.assertTrue((shaders / extra).is_file(), extra) - - -class FilterSelection(unittest.TestCase): - def test_reused_work_translates_only_selected_shaders_and_dependencies(self): - passes = [] - - def write_disassembly(_llvm, _asm, path, name): - Path(path).write_text(name, encoding="utf-8") - - def translate(cmd, gpu=True): - inputs = Path(cmd[3]) - files = sorted(inputs.glob("*.s")) - passes.append([path.name for path in files]) - for path in files: - self.assertEqual(path.read_text(encoding="utf-8"), path.stem) - self.assertTrue((inputs.parent / f"{path.stem}.dxbc").is_file()) - return 1, "stop before running GPU tests" - - with tempfile.TemporaryDirectory() as tmp, \ - patch("sys.stdout", io.StringIO()), \ - patch.object(run_gpu_tests, "assemble_to_s", side_effect=write_disassembly), \ - patch.object(run_gpu_tests, "run_cmd", side_effect=translate): - for shader_filter in ("ps_bary", "ps_flat"): - args = SimpleNamespace(filter=shader_filter, llvm_mc="unused") - self.assertEqual(run_gpu_tests.run_suite(args, tmp), 1) - - self.assertEqual(passes, [["ps_bary.s"], ["ps_flat.s", "vs_ids.s"]]) - disasm = Path(tmp) / "disasm" - self.assertEqual((disasm / "ps_bary.s").read_text(encoding="utf-8"), "ps_bary") - self.assertTrue((disasm / "ps_flat.s").is_file()) - self.assertTrue((disasm / "vs_ids.s").is_file()) - - def test_unmatched_filter_fails_before_running_shader_tools(self): - args = SimpleNamespace(filter="no_matching_shader", build="unused") - err = io.StringIO() - with tempfile.TemporaryDirectory() as tmp, \ - patch("sys.stderr", err), \ - patch.object(run_gpu_tests, "run_cmd", return_value=(0, "")) as run, \ - patch.object(run_gpu_tests, "spirv_as") as assemble: - work = Path(tmp) / "work" - self.assertEqual(run_gpu_tests.run_suite(args, str(work)), 2) - self.assertIn(args.filter, err.getvalue()) - run.assert_not_called() - assemble.assert_not_called() - self.assertFalse(work.exists()) - - -class RelativePaths(unittest.TestCase): - def test_build_and_work_become_absolute(self): - ext = ".exe" if os.name == "nt" else "" - seen = {} - - def suite(a, work): - seen["build"], seen["work"] = a.build, work - return 0 - - with tempfile.TemporaryDirectory() as tmp: - build = Path(tmp) / "build" - build.mkdir() - for tool in ("vk_compute_test", "vk_store_test", "vk_harness"): - (build / (tool + ext)).touch() - old = os.getcwd() - os.chdir(tmp) - try: - with (patch.object(sys, "argv", ["run_gpu_tests.py", "--build", "build", "--work", "work"]), - patch.object(run_gpu_tests, "run_suite", side_effect=suite)): - self.assertEqual(run_gpu_tests.main(), 0) - finally: - os.chdir(old) - # Compare resolved paths: Windows can spell the temp directory with an 8.3 name (RUNNER~1). - for got, want in ((seen["build"], build), (seen["work"], Path(tmp) / "work")): - self.assertTrue(os.path.isabs(got), got) - self.assertEqual(Path(got).resolve(), want.resolve()) - - -class WorkDirectory(unittest.TestCase): - def test_file_blocking_work_directory_is_a_cli_error(self): - ext = ".exe" if os.name == "nt" else "" - for blocked_child in ("", "spirv"): - with self.subTest(blocked_child=blocked_child), tempfile.TemporaryDirectory() as tmp: - build = Path(tmp) / "build" - build.mkdir() - for tool in run_gpu_tests.REQUIRED_TEST_PROGRAMS: - (build / (tool + ext)).touch() - work = Path(tmp) / "work" - blocker = work / blocked_child - blocker.parent.mkdir(exist_ok=True) - blocker.write_text("keep me", encoding="utf-8") - - result = subprocess.run( - [sys.executable, "-I", run_gpu_tests.__file__, "--build", str(build), - "--work", str(work), "--filter", "cs_lds"], - capture_output=True, text=True, timeout=10, - ) - self.assertEqual(result.returncode, 2, result.stderr) - self.assertIn("error: cannot prepare GPU test directory", result.stderr) - self.assertIn(str(blocker), result.stderr) - self.assertNotIn("Traceback", result.stderr) - self.assertEqual(blocker.read_text(encoding="utf-8"), "keep me") - - -class BuildConfigurations(unittest.TestCase): - def test_single_configuration_directory_is_preferred(self): - with tempfile.TemporaryDirectory() as tmp: - root = Path(tmp) - for directory in (root, root / "RelWithDebInfo"): - directory.mkdir(exist_ok=True) - for tool in run_gpu_tests.REQUIRED_TEST_PROGRAMS: - (directory / (tool + ".exe")).touch() - self.assertEqual(run_gpu_tests.find_test_programs(str(root), ".exe"), str(root)) - - def test_visual_studio_relwithdebinfo_is_found(self): - with tempfile.TemporaryDirectory() as tmp: - build = Path(tmp) - config = build / "RelWithDebInfo" - config.mkdir() - for tool in run_gpu_tests.REQUIRED_TEST_PROGRAMS: - (config / (tool + ".exe")).touch() - self.assertEqual(run_gpu_tests.find_test_programs(str(build), ".exe"), str(config)) - - def test_visual_studio_release_is_found(self): - with tempfile.TemporaryDirectory() as tmp: - build = Path(tmp) - config = build / "Release" - config.mkdir() - for tool in run_gpu_tests.REQUIRED_TEST_PROGRAMS: - (config / (tool + ".exe")).touch() - self.assertEqual(run_gpu_tests.find_test_programs(str(build), ".exe"), str(config)) - - def test_incomplete_configuration_is_skipped(self): - with tempfile.TemporaryDirectory() as tmp: - build = Path(tmp) - incomplete = build / "RelWithDebInfo" - release = build / "Release" - incomplete.mkdir() - release.mkdir() - for tool in run_gpu_tests.REQUIRED_TEST_PROGRAMS[:-1]: - (incomplete / (tool + ".exe")).touch() - for tool in run_gpu_tests.REQUIRED_TEST_PROGRAMS: - (release / (tool + ".exe")).touch() - self.assertEqual(run_gpu_tests.find_test_programs(str(build), ".exe"), str(release)) - - def test_missing_programs_returns_no_directory(self): - with tempfile.TemporaryDirectory() as tmp: - self.assertIsNone(run_gpu_tests.find_test_programs(tmp, ".exe")) - - - def test_relwithdebinfo_is_preferred_over_release(self): - with tempfile.TemporaryDirectory() as tmp: - build = Path(tmp) - for config_name in run_gpu_tests.BUILD_CONFIGS: - config = build / config_name - config.mkdir() - for tool in run_gpu_tests.REQUIRED_TEST_PROGRAMS: - (config / (tool + ".exe")).touch() - self.assertEqual(run_gpu_tests.find_test_programs(str(build), ".exe"), - str(build / "RelWithDebInfo")) - - def test_extensionless_executables_are_supported(self): - with tempfile.TemporaryDirectory() as tmp: - for tool in run_gpu_tests.REQUIRED_TEST_PROGRAMS: - (Path(tmp) / tool).touch() - self.assertEqual(run_gpu_tests.find_test_programs(tmp, ""), tmp) - - def test_programs_are_not_combined_across_directories(self): - with tempfile.TemporaryDirectory() as tmp: - build = Path(tmp) - (build / "RelWithDebInfo").mkdir() - (build / "Release").mkdir() - for tool in run_gpu_tests.REQUIRED_TEST_PROGRAMS[:2]: - (build / "RelWithDebInfo" / (tool + ".exe")).touch() - for tool in run_gpu_tests.REQUIRED_TEST_PROGRAMS[2:]: - (build / "Release" / (tool + ".exe")).touch() - self.assertIsNone(run_gpu_tests.find_test_programs(str(build), ".exe")) - - def test_missing_program_error_lists_per_directory_files(self): - ext = ".exe" if os.name == "nt" else "" - with tempfile.TemporaryDirectory() as tmp: - build = Path(tmp) / "build output" - rel = build / "RelWithDebInfo" - rel.mkdir(parents=True) - (rel / ("vk_compute_test" + ext)).touch() - (rel / ("vk_store_test" + ext)).touch() - with (patch.object(sys, "argv", ["run_gpu_tests.py", "--build", str(build)]), - self.assertRaises(SystemExit) as caught): - run_gpu_tests.main() - message = str(caught.exception) - # names the build folder, says the configuration subfolders were searched, and lists what is missing - self.assertIn(str(build), message) - self.assertIn("RelWithDebInfo", message) - self.assertIn("vk_harness" + ext, message) - - def test_main_passes_visual_studio_config_directory_to_suite(self): - ext = ".exe" if os.name == "nt" else "" - for config_name in run_gpu_tests.BUILD_CONFIGS: - with self.subTest(config=config_name), tempfile.TemporaryDirectory() as tmp: - build = Path(tmp) / "build" - config = build / config_name - config.mkdir(parents=True) - for tool in run_gpu_tests.REQUIRED_TEST_PROGRAMS: - (config / (tool + ext)).touch() - seen = {} - - def suite(a, work): - seen["build"] = a.build - return 0 - - with (patch.object(sys, "argv", [ - "run_gpu_tests.py", "--build", str(build), "--work", str(Path(tmp) / "work")]), - patch.object(run_gpu_tests, "run_suite", side_effect=suite)): - self.assertEqual(run_gpu_tests.main(), 0) - self.assertEqual(Path(seen["build"]).resolve(), config.resolve()) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/test_run_gpu_tests_python_assembler.py b/tests/test_run_gpu_tests_python_assembler.py deleted file mode 100644 index 31a99aa90..000000000 --- a/tests/test_run_gpu_tests_python_assembler.py +++ /dev/null @@ -1,141 +0,0 @@ -"""Tests for pure-Python SPIR-V assembly and --disasm-dir / --no-validate in run_gpu_tests.py and rdna2spirv.py.""" -import io -import json -import os -from pathlib import Path -import struct -import sys -import tempfile -from types import SimpleNamespace -import unittest -from unittest.mock import patch - -ROOT = Path(__file__).resolve().parents[1] -sys.path.insert(0, str(ROOT / "scripts")) -sys.path.insert(0, str(ROOT / "tools")) - -import rdna2spirv -import run_gpu_tests - - -class PythonAssemblerTests(unittest.TestCase): - def test_resolve_assembler_auto_and_explicit(self) -> None: - self.assertEqual(run_gpu_tests.resolve_assembler("python"), "python") - self.assertEqual(run_gpu_tests.resolve_assembler("spirv-as"), "spirv-as") - with patch.object(run_gpu_tests.shutil, "which", return_value="/usr/bin/spirv-as"): - self.assertEqual(run_gpu_tests.resolve_assembler("auto"), "spirv-as") - with patch.object(run_gpu_tests.shutil, "which", return_value=None): - self.assertEqual(run_gpu_tests.resolve_assembler("auto"), "python") - with self.assertRaises(ValueError): - run_gpu_tests.resolve_assembler("bogus") - - def test_spirv_as_python_assembles_helper_shaders(self) -> None: - with tempfile.TemporaryDirectory() as tmp: - for name, src in ( - ("vs_tri.spv", run_gpu_tests.VS_TRI_SPVASM), - ("fs_passthru.spv", run_gpu_tests.make_fs_passthru(0)), - ): - out = Path(tmp) / name - run_gpu_tests.spirv_as(src, str(out), assembler="python") - data = out.read_bytes() - self.assertGreaterEqual(len(data), 20) - self.assertEqual(struct.unpack(" None: - with tempfile.TemporaryDirectory() as tmp: - spvasm = Path(tmp) / "fs_passthru.spvasm" - spv = Path(tmp) / "fs_passthru.spv" - asm = run_gpu_tests.make_fs_passthru(0) - with patch.object(rdna2spirv, "_run_spirv_tool", - side_effect=AssertionError("external spirv tool called")) as run_tool: - res = rdna2spirv.assemble_spirv(str(spvasm), str(spv), asm_text=asm, - assembler="python", validate=False) - run_tool.assert_not_called() - self.assertEqual(res.returncode, 0) - self.assertTrue(spv.is_file()) - self.assertEqual(struct.unpack(" None: - with tempfile.TemporaryDirectory() as tmp: - root = Path(tmp) - disasm = root / "disasm" - fssm = root / "fssm" - out = root / "out" - disasm.mkdir() - fssm.mkdir() - # Minimal valid compute listing (s_endpgm) and synthetic 0x148-byte FSSM header. - (disasm / "cs_noop.s").write_text("; synthetic\n\ts_endpgm\n", encoding="utf-8", newline="\n") - hdr = bytearray(0x148) - hdr[0:4] = b"FSSM" - struct.pack_into("<4I", hdr, 0x138, 0x8088, 64, 1, 1) - (fssm / "cs_noop.fssm").write_bytes(bytes(hdr)) - stdout = io.StringIO() - with patch("sys.stdout", stdout), \ - patch.object(sys, "argv", [ - "rdna2spirv.py", str(disasm), "--out", str(out), "--assembler", "python", "--no-validate", - ]), \ - patch.object(rdna2spirv, "_run_spirv_tool", - side_effect=AssertionError("external spirv tool called")): - rc = rdna2spirv.main() - self.assertIn(rc, (0, None)) - self.assertIn("1 shaders: 1 translated, 1 assembled (spirv-val skipped)", stdout.getvalue()) - spv = out / "cs_noop.spv" - self.assertTrue(spv.is_file()) - self.assertEqual(struct.unpack(" None: - with tempfile.TemporaryDirectory() as tmp: - build = Path(tmp) / "build" - build.mkdir() - ext = ".exe" if os.name == "nt" else "" - for prog in run_gpu_tests.TEST_PROGRAMS: - (build / (prog + ext)).write_bytes(b"") - missing = Path(tmp) / "no_such_disasm" - err = io.StringIO() - with patch("sys.stderr", err), \ - patch.object(sys, "argv", ["run_gpu_tests.py", "--build", str(build), "--disasm-dir", str(missing)]): - rc = run_gpu_tests.main() - self.assertEqual(rc, 2) - self.assertIn("--disasm-dir is not a directory", err.getvalue()) - - def test_run_suite_reuses_existing_work_listings(self) -> None: - listing = b"; synthetic\n\ts_endpgm\n" - run_command = run_gpu_tests.run_cmd - for placement in ("in-place", "hard-link", "separate"): - with self.subTest(placement=placement), tempfile.TemporaryDirectory() as tmp: - work = Path(tmp) / "work" - working = work / "disasm" / "cs_lds.s" - working.parent.mkdir(parents=True) - source = working if placement == "in-place" else Path(tmp) / "source" / working.name - source.parent.mkdir(exist_ok=True) - source.write_bytes(listing) - if placement == "hard-link": - try: - os.link(source, working) - except OSError as exc: - self.skipTest(f"hard links unavailable: {exc}") - - args = SimpleNamespace(assembler="python", no_validate=True, disasm_dir=str(source.parent), - filter="cs_lds", build=str(work), require_pass=True) - - def run(command, env=None, gpu=True): - if not gpu: - selected = Path(command[3]) - self.assertNotEqual(selected, working.parent) - self.assertEqual((selected / working.name).read_bytes(), listing) - return run_command(command, env=env, gpu=False) - self.assertTrue(Path(command[1]).is_file()) - return 0, "synthetic GPU result" - - with (patch.object(run_gpu_tests, "run_cmd", side_effect=run) as launches, - patch.object(sys, "stdout", io.StringIO())): - self.assertEqual(run_gpu_tests.run_suite(args, str(work)), 0) - self.assertEqual(launches.call_count, 2) - self.assertEqual(source.read_bytes(), listing) - self.assertEqual(working.read_bytes(), listing) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/test_run_gpu_wavemask.py b/tests/test_run_gpu_wavemask.py deleted file mode 100644 index 70a59f31d..000000000 --- a/tests/test_run_gpu_wavemask.py +++ /dev/null @@ -1,86 +0,0 @@ -"""run_gpu_tests.py's cs_wavemask, with a fake vk_compute_test: it asks for a 64-wide subgroup only for the native -build. With LEONIDA_W64_EMULATE=1 it runs on any subgroup size, as check.py does (W64_EMULATED).""" -import contextlib -import io -from pathlib import Path -import sys -import tempfile -from types import SimpleNamespace -import unittest -from unittest.mock import patch - -ROOT = Path(__file__).resolve().parents[1] -sys.path.insert(0, str(ROOT / "scripts")) -import run_gpu_tests - -PASS32 = "device: fake (subgroup 32..32)\n1 groups x 64: 0 mismatches" - - -class WavemaskCheck(unittest.TestCase): - def run_check(self, emulated, rc, msg): - calls = [] - - def fake(cmd, env=None): - calls.append(cmd) - return rc, msg - - with patch.object(run_gpu_tests, "run_cmd", side_effect=fake): - result = run_gpu_tests.wavemask_check("vk_compute_test", "cs_wavemask.spv", None, emulated) - self.assertEqual(len(calls), 1) - return result, calls[0] - - def test_native_build_requires_wave64_and_skips_without_it(self): - result, cmd = self.run_check(False, 77, "device: fake (subgroup 32..32)") - self.assertIn("--require-wave64", cmd) - self.assertIsNone(result[0]) - self.assertIn("SKIP", result[1]) - - def test_native_build_needs_the_subgroup_confirmed(self): - result, _ = self.run_check(False, 0, PASS32) - self.assertIs(result[0], False) - - def test_native_build_passes_on_a_64_wide_subgroup(self): - result, _ = self.run_check(False, 0, "compute subgroup size: 64\n1 groups x 64: 0 mismatches") - self.assertIs(result[0], True) - - def test_emulated_build_runs_on_a_32_wide_subgroup(self): - result, cmd = self.run_check(True, 0, PASS32) - self.assertNotIn("--require-wave64", cmd) - self.assertEqual(result, (True, "1 groups x 64: 0 mismatches")) - - def test_emulated_build_reports_mismatches(self): - result, _ = self.run_check(True, 1, "device: fake (subgroup 32..32)\nlane 40: got 0, want 1") - self.assertIs(result[0], False) - - - -class WavemaskInTheSuite(unittest.TestCase): - """run_suite runs cs_wavemask once and reports it once (no assembler or GPU needed).""" - - def test_one_run_and_one_row(self): - compute_runs = [] - - def fake_run_cmd(cmd, env=None, gpu=True): - if cmd[0] == sys.executable: # the translator: leave the .spv it would write - Path(cmd[cmd.index("--out") + 1], "cs_wavemask.spv").touch() - return 0, "" - compute_runs.append(cmd) - return 77, "device: fake (subgroup 32..32)" - - out = io.StringIO() - with tempfile.TemporaryDirectory() as tmp: - args = SimpleNamespace(filter="cs_wavemask", llvm_mc="llvm-mc", build=tmp) - with (patch.object(run_gpu_tests, "assemble_to_s", # run_suite copies the .s it writes (#769) - side_effect=lambda _mc, _src, dst, _name: Path(dst).touch()), - patch.object(run_gpu_tests, "spirv_as"), - patch.object(run_gpu_tests, "w64_emulated", return_value=False), - patch.object(run_gpu_tests, "run_cmd", side_effect=fake_run_cmd), contextlib.redirect_stdout(out)): - self.assertEqual(run_gpu_tests.run_suite(args, tmp), 0) - self.assertEqual(len(compute_runs), 1, compute_runs) - rows = [line for line in out.getvalue().splitlines() if "cs_wavemask" in line] - self.assertEqual(len(rows), 1, out.getvalue()) - self.assertIn("SKIP (no 64-wide compute subgroup on this device)", rows[0]) - self.assertIn("0/1 passed, 1 skipped", out.getvalue()) - -if __name__ == "__main__": - unittest.main() diff --git a/tests/test_run_semantic_tests.py b/tests/test_run_semantic_tests.py deleted file mode 100644 index f9f3e86ae..000000000 --- a/tests/test_run_semantic_tests.py +++ /dev/null @@ -1,138 +0,0 @@ -"""scripts/run_semantic_tests.py on a throwaway suite: it finds what unittest discover finds, and a failing, crashing -or unimportable file always makes it exit 1 with that file named, in parallel and with -j 1. - - python -I tests/test_run_semantic_tests.py -""" -import contextlib -import io -import os -import subprocess -import sys -import tempfile -import unittest - -ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) -sys.path.insert(0, os.path.join(ROOT, "scripts")) - -import run_semantic_tests as r # noqa: E402 - -PASS = "import unittest\nimport helper\nclass T(unittest.TestCase):\n def test_a(self): self.assertEqual(helper.X, 1)\n" \ - " def test_b(self): pass\n" -FAIL = "import unittest\nclass T(unittest.TestCase):\n def test_a(self): self.assertEqual(1, 2, 'boom-msg')\n" -BROKEN = "import no_such_module_anywhere\n" - - -def suite(tmp, files): - for rel, text in files.items(): - path = os.path.join(tmp, *rel.split("/")) - os.makedirs(os.path.dirname(path), exist_ok=True) - with open(path, "w", encoding="utf-8") as f: - f.write(text) - return tmp - - -def run(*argv): - out = io.StringIO() - with contextlib.redirect_stdout(out), contextlib.redirect_stderr(io.StringIO()): - code = r.main(list(argv)) - return code, out.getvalue() - - -def cli(*argv): - return subprocess.run([sys.executable, "-I", os.path.join(ROOT, "scripts", "run_semantic_tests.py"), *argv], - capture_output=True, text=True, timeout=15) - - -class RunnerTest(unittest.TestCase): - def test_custom_patterns_find_only_python_modules_in_packages(self): - with tempfile.TemporaryDirectory() as tmp: - suite(tmp, {"case_one.py": "", "case_two.txt": "", "case_bad-name.py": "", - "pkg/__init__.py": "", "pkg/case_two.py": "", "plain/case_three.py": ""}) - self.assertEqual(r.test_modules(tmp, "case_*.py"), ["case_one", "pkg.case_two"]) - self.assertEqual(r.test_modules(tmp, "*"), ["case_one", "pkg.__init__", "pkg.case_two"]) - - def test_pattern_selects_files_without_importing_excluded_modules(self): - for jobs in (1, 2): - for flag in ("-p", "--pattern"): - with self.subTest(jobs=jobs, flag=flag), tempfile.TemporaryDirectory() as tmp: - suite(tmp, {"helper.py": "X = 1\n", "case_one.py": PASS, - "pkg/__init__.py": "", "pkg/case_two.py": PASS, - "test_excluded.py": "raise AssertionError('excluded module imported')\n", - "plain/case_three.py": BROKEN}) - result = cli(tmp, "-j", str(jobs), flag, "case_*.py") - self.assertEqual(result.returncode, 0, result.stdout + result.stderr) - self.assertNotIn("excluded module imported", result.stdout + result.stderr) - if jobs == 1: - self.assertIn("Ran 4 tests", result.stderr) - else: - self.assertIn("2 files, 4 tests, 0 files failed", result.stdout) - - def test_pattern_no_matches_is_an_error_in_both_modes(self): - for jobs in (1, 2): - with self.subTest(jobs=jobs), tempfile.TemporaryDirectory() as tmp: - suite(tmp, {"test_excluded.py": BROKEN}) - result = cli(tmp, "-j", str(jobs), "--pattern", "case_*.py") - self.assertEqual(result.returncode, 1, result.stdout + result.stderr) - self.assertIn("no case_*.py files", result.stdout) - self.assertNotIn("Traceback", result.stderr) - - def test_matching_failure_is_not_hidden_by_pattern_selection(self): - for jobs in (1, 2): - with self.subTest(jobs=jobs), tempfile.TemporaryDirectory() as tmp: - suite(tmp, {"case_fail.py": FAIL, "test_excluded.py": BROKEN}) - result = cli(tmp, "-j", str(jobs), "--pattern", "case_*.py") - self.assertEqual(result.returncode, 1, result.stdout + result.stderr) - self.assertIn("boom-msg", result.stdout + result.stderr) - self.assertNotIn("no_such_module_anywhere", result.stdout + result.stderr) - - def test_omitting_pattern_keeps_the_default_selection(self): - for jobs in (1, 2): - with self.subTest(jobs=jobs), tempfile.TemporaryDirectory() as tmp: - suite(tmp, {"helper.py": "X = 1\n", "test_pass.py": PASS, - "case_excluded.py": "raise AssertionError('custom module imported')\n"}) - result = cli(tmp, "-j", str(jobs)) - self.assertEqual(result.returncode, 0, result.stdout + result.stderr) - self.assertNotIn("custom module imported", result.stdout + result.stderr) - - def test_finds_what_discover_finds(self): - with tempfile.TemporaryDirectory() as tmp: - suite(tmp, {"test_one.py": "", "helper.py": "", "pkg/__init__.py": "", "pkg/test_two.py": "", - "plain_dir/test_three.py": "", "testx.py": ""}) - # discover enters packages only, and its pattern is test*.py - self.assertEqual(r.test_modules(tmp), ["test_one", "testx", "pkg.test_two"]) - - def test_all_pass(self): - with tempfile.TemporaryDirectory() as tmp: - suite(tmp, {"helper.py": "X = 1\n", "test_p1.py": PASS, "test_p2.py": PASS}) - code, out = run(tmp, "-j", "2") - self.assertEqual(code, 0, out) - self.assertIn("2 files, 4 tests, 0 files failed", out) - - def test_a_failure_or_import_error_is_reported_and_fails_the_run(self): - with tempfile.TemporaryDirectory() as tmp: - suite(tmp, {"helper.py": "X = 1\n", "test_p.py": PASS, "test_f.py": FAIL, "test_b.py": BROKEN}) - code, out = run(tmp, "-j", "3") - self.assertEqual(code, 1, out) - self.assertIn("==== FAILED: test_f", out) - self.assertIn("boom-msg", out) # the failing file's own output is shown - self.assertIn("==== FAILED: test_b", out) - self.assertIn("2 files failed", out) - self.assertTrue(out.rstrip().endswith("test_b, test_f"), out) - - def test_one_job_runs_discover_and_keeps_its_exit_code(self): - with tempfile.TemporaryDirectory() as tmp: - suite(tmp, {"helper.py": "X = 1\n", "test_p.py": PASS, "test_f.py": FAIL}) - self.assertEqual(run(tmp, "-j", "1")[0], 1) - with tempfile.TemporaryDirectory() as tmp: - suite(tmp, {"helper.py": "X = 1\n", "test_p.py": PASS}) - self.assertEqual(run(tmp, "-j", "1")[0], 0) - - def test_an_empty_suite_fails(self): - with tempfile.TemporaryDirectory() as tmp: - code, out = run(tmp, "-j", "2") - self.assertEqual(code, 1) - self.assertIn("no test*.py files", out) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/test_run_wine_test_fixtures.py b/tests/test_run_wine_test_fixtures.py deleted file mode 100644 index 57cef27ec..000000000 --- a/tests/test_run_wine_test_fixtures.py +++ /dev/null @@ -1,94 +0,0 @@ -"""Check how the Wine runner handles CTest fixture metadata with benign child scripts.""" - -import json -from pathlib import Path -import subprocess -import sys -import tempfile -import unittest - -RUNNER = Path(__file__).resolve().parents[1] / "scripts" / "run_wine_tests.py" -WINDOWS_ROOT = "synthetic-checkout" - - -class WineFixtureSetupTests(unittest.TestCase): - def run_fixture(self, setup_status: int, *, fixture: bool = True, disabled: bool = False, - dependent: bool = False, duplicate_setup: bool = False, - ) -> tuple[int, str, list[str]]: - with tempfile.TemporaryDirectory() as directory: - root = Path(directory) - trace = root / "launches.txt" - - def entry(name: str, status: int, properties: dict[str, object], *, - test_name: str | None = None) -> dict[str, object]: - (root / f"{name}.py").write_text( - "from pathlib import Path\n" - "with Path(__file__).with_name('launches.txt').open('a', encoding='utf-8', newline='\\n') as f:\n" - f" f.write({name!r} + '\\n')\n" - f"raise SystemExit({status})\n", - encoding="utf-8", newline="\n", - ) - return {"name": test_name or name, "command": [f"{WINDOWS_ROOT}/{name}.py"], - "properties": [{"name": key, "value": value} for key, value in properties.items()]} - - setup_props: dict[str, object] = {"SKIP_RETURN_CODE": 77, "DISABLED": disabled} - consumer_props: dict[str, object] = {"DEPENDS": ["setup"]} - if fixture: - setup_props["FIXTURES_SETUP"] = ["input"] - consumer_props["FIXTURES_REQUIRED"] = ["input"] - setup = entry("setup", setup_status, setup_props) - consumer = entry("consumer", 0, consumer_props) - tests = [consumer, setup] if fixture else [setup, consumer] - if duplicate_setup: - tests.append(entry("second_setup", 0, setup_props, test_name="setup")) - if dependent: - tests.append(entry("dependent", 0, {"DEPENDS": ["consumer"]})) - listing = root / "ctest.json" - listing.write_text(json.dumps({"tests": tests}), encoding="utf-8", newline="\n") - result = subprocess.run( - [sys.executable, "-I", str(RUNNER), "--tests", str(listing), "--windows-root", WINDOWS_ROOT, - "--root", directory, "--require", "consumer", "--wine", f'"{Path(sys.executable).as_posix()}"'], - capture_output=True, text=True, timeout=15, - ) - return result.returncode, result.stdout + result.stderr, trace.read_text(encoding="utf-8").splitlines() - - def test_fixture_setup_is_run_before_an_earlier_listed_consumer(self) -> None: - status, output, calls = self.run_fixture(0) - self.assertEqual(status, 0, output) - self.assertEqual(calls, ["setup", "consumer"]) - - def test_explicit_dependency_still_runs_after_the_fixture_consumer(self) -> None: - status, output, calls = self.run_fixture(0, dependent=True) - self.assertEqual(status, 0, output) - self.assertEqual(calls, ["setup", "consumer", "dependent"]) - - def test_failed_setup_blocks_a_required_consumer(self) -> None: - status, output, calls = self.run_fixture(3) - self.assertEqual(status, 1, output) - self.assertEqual(calls, ["setup"]) - self.assertIn("[FAIL] consumer", output) - self.assertIn("failed fixture setup: setup", output) - - def test_passing_setup_with_same_name_does_not_hide_failure(self) -> None: - status, output, calls = self.run_fixture(3, duplicate_setup=True) - self.assertEqual(status, 1, output) - self.assertEqual(calls, ["setup", "second_setup"]) - self.assertIn("failed fixture setup: setup", output) - - def test_skipped_or_disabled_setup_does_not_block(self) -> None: - for status, disabled, expected in ((77, False, ["setup", "consumer"]), (3, True, ["consumer"])): - with self.subTest(disabled=disabled): - code, output, calls = self.run_fixture(status, disabled=disabled) - self.assertEqual(code, 0, output) - self.assertEqual(calls, expected) - - def test_generic_depends_does_not_turn_an_optional_failure_into_a_block(self) -> None: - status, output, calls = self.run_fixture(3, fixture=False) - self.assertEqual(status, 0, output) - self.assertEqual(calls, ["setup", "consumer"]) - self.assertIn("[FAIL] setup", output) - self.assertIn("[PASS] consumer", output) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/test_run_wine_tests.py b/tests/test_run_wine_tests.py deleted file mode 100644 index 4507b2293..000000000 --- a/tests/test_run_wine_tests.py +++ /dev/null @@ -1,927 +0,0 @@ -"""Tests for scripts/run_wine_tests.py: path mapping, per-test statuses and the job's exit code. - - python -I tests/test_run_wine_tests.py - -No Wine and no game data: `wine` is the Python interpreter and every "build artifact" is a tiny script that exits -with a chosen code, so the runner's own logic is what is under test. -""" -from __future__ import annotations - -import argparse -import contextlib -import io -import json -import os -from pathlib import Path -import subprocess -import sys -import tempfile -import time -import unittest -from unittest import mock - -ROOT = Path(__file__).resolve().parents[1] -SCRIPTS = ROOT / "scripts" -if str(SCRIPTS) not in sys.path: - sys.path.insert(0, str(SCRIPTS)) - -import run_wine_tests as rwt # noqa: E402 - -WINDOWS_ROOT = "D:/win/root" - - -def ctest_entry(name, command, properties=None): - entry = {"name": name} - if command is not None: - entry["command"] = command - if properties: - entry["properties"] = [{"name": k, "value": v} for k, v in properties.items()] - return entry - - -class PathMappingTest(unittest.TestCase): - def test_paths_under_the_windows_checkout_are_mapped(self): - self.assertEqual(rwt.map_path("D:/win/root", WINDOWS_ROOT, "/repo"), "/repo") - self.assertEqual(rwt.map_path("D:\\win\\root\\runtime\\build", WINDOWS_ROOT, "/repo"), - os.path.join("/repo", "runtime", "build")) - self.assertEqual(rwt.map_path("d:/WIN/root/a/b.exe", WINDOWS_ROOT, "/repo"), os.path.join("/repo", "a", "b.exe")) - self.assertEqual(rwt.map_path("D:/win/root/", WINDOWS_ROOT, "/repo"), "/repo") - - def test_paths_outside_the_checkout_are_not_mapped(self): - for path in ("D:/win/root2/a.exe", "C:/Windows/system32/cmd.exe", "/usr/bin/cmake", ""): - with self.subTest(path=path): - self.assertIsNone(rwt.map_path(path, WINDOWS_ROOT, "/repo")) - - def test_parent_segments_cannot_escape_windows_root(self): - self.assertIsNone(rwt.map_path("D:/win/root/../outside.exe", WINDOWS_ROOT, "/repo")) - self.assertEqual(rwt.map_path("D:/win/root/inside/../runner.exe", WINDOWS_ROOT, "/repo"), - os.path.join("/repo", "runner.exe")) - - def test_dot_and_repeated_separators_normalize_before_mapping(self): - self.assertEqual(rwt.map_path("D:/win/root/./runner.exe", WINDOWS_ROOT, "/repo"), - os.path.join("/repo", "runner.exe")) - self.assertEqual(rwt.map_path("D:/win/root//sub//runner.exe", WINDOWS_ROOT, "/repo"), - os.path.join("/repo", "sub", "runner.exe")) - self.assertIsNone(rwt.map_path("D:/win/root/../../outside.exe", WINDOWS_ROOT, "/repo")) - - def test_wine_path_uses_the_z_drive(self): - self.assertEqual(rwt.wine_path("/tmp/x y"), "Z:" + os.path.abspath("/tmp/x y").replace("/", "\\")) - - def test_properties_are_flattened(self): - self.assertEqual(rwt.properties(ctest_entry("t", ["x"], {"SKIP_RETURN_CODE": "77", "WILL_FAIL": "1"})), - {"SKIP_RETURN_CODE": "77", "WILL_FAIL": "1"}) - self.assertEqual(rwt.properties({"name": "t"}), {}) - - def test_ctest_booleans_are_not_python_truthiness(self): - for value in ("1", "ON", "true", "yes", " 1 "): - with self.subTest(value=value): - self.assertTrue(rwt.truthy(value)) - for value in ("0", "", None, "false", "no"): - with self.subTest(value=value): - self.assertFalse(rwt.truthy(value)) - - -class RunTestTest(unittest.TestCase): - def setUp(self): - self._tmp = tempfile.TemporaryDirectory() - self.root = Path(self._tmp.name) - self.artifact = self.root / "artifact" - self.artifact.mkdir() - self.args = argparse.Namespace(windows_root=WINDOWS_ROOT, root=str(self.root), timeout=10.0) - self.wine = [sys.executable] - - def tearDown(self): - self._tmp.cleanup() - - def program(self, name, body): - path = self.artifact / name - path.write_text(body, encoding="utf-8") - return str(path) - - def exiting(self, code, name=None): - return self.program(name or f"exit{code}.py", f"import sys\nsys.exit({code})\n") - - def command_for(self, exe, *args): - """The same program as ctest would list it: a path in the Windows checkout.""" - parts = Path(exe).relative_to(self.root).parts - return [WINDOWS_ROOT + "/" + "/".join(parts), *args] - - def run_entry(self, entry): - return rwt.run_test(entry, self.args, self.wine) - - def test_a_passing_test(self): - status, detail = self.run_entry(ctest_entry("ok", self.command_for(self.exiting(0)))) - self.assertEqual(status, "pass") - self.assertIn("exit 0", detail) - - def test_a_failing_test_reports_the_exit_code(self): - status, detail = self.run_entry(ctest_entry("bad", self.command_for(self.exiting(3)))) - self.assertEqual(status, "fail") - self.assertIn("exit 3", detail) - - def test_a_disabled_test_is_skipped_without_launching(self) -> None: - built = self.command_for(self.exiting(0)) - missing = self.command_for(self.artifact / "missing.exe") - for command in (built, missing, None): - with self.subTest(command=command), \ - mock.patch.object(rwt, "run_test_process", wraps=rwt.run_test_process) as launch: - status, detail = self.run_entry(ctest_entry("disabled", command, {"DISABLED": True})) - launch.assert_not_called() - self.assertEqual(status, "skip", detail) - self.assertIn("disabled by CTest", detail) - - def test_a_false_disabled_property_still_runs_the_test(self) -> None: - command = self.command_for(self.exiting(0)) - status, detail = self.run_entry(ctest_entry("enabled", command, {"DISABLED": "0"})) - self.assertEqual(status, "pass", detail) - - def test_a_test_without_a_command_fails(self): - status, detail = self.run_entry(ctest_entry("unbuilt", None)) - self.assertEqual(status, "fail") - self.assertIn("no command", detail) - - def test_a_test_that_runs_a_runner_program_is_skipped(self): - status, detail = self.run_entry(ctest_entry("python-test", ["/usr/bin/cmake", "-P", "x.cmake"])) - self.assertEqual(status, "skip") - self.assertIn("not a program from the build", detail) - - def test_a_missing_executable_fails(self): - status, detail = self.run_entry(ctest_entry("gone", [WINDOWS_ROOT + "/artifact/gone.py"])) - self.assertEqual(status, "fail") - self.assertIn("not in the artifact", detail) - - def test_will_fail_inverts_the_exit_code(self): - exe = self.exiting(2) - status, _ = self.run_entry(ctest_entry("expected", self.command_for(exe), {"WILL_FAIL": "1"})) - self.assertEqual(status, "pass") - - def test_will_fail_zero_does_not_invert_the_exit_code(self): - # A JSON property value is a string; "0" must stay false. - status, detail = self.run_entry(ctest_entry("normal", self.command_for(self.exiting(0)), {"WILL_FAIL": "0"})) - self.assertEqual(status, "pass", detail) - - def test_the_skip_return_code_is_a_skip(self): - status, detail = self.run_entry( - ctest_entry("skipped", self.command_for(self.exiting(77)), {"SKIP_RETURN_CODE": "77"})) - self.assertEqual(status, "skip") - self.assertIn("exit 77", detail) - - def test_invalid_skip_return_codes_fail_before_launch(self): - command = self.command_for(self.exiting(0)) - for value in ("invalid", True, 1.5, -1, 256): - with self.subTest(value=value), mock.patch.object(rwt.subprocess, "run") as launch: - status, detail = self.run_entry(ctest_entry("invalid", command, {"SKIP_RETURN_CODE": value})) - self.assertEqual(status, "fail") - self.assertIn("invalid CTest SKIP_RETURN_CODE", detail) - launch.assert_not_called() - - def test_ctest_environment_is_applied_only_to_its_child(self) -> None: - exe = self.program("show_environment.py", - "import os\n" - "for key in ('LEONIDA_HOST_ADAPTER', 'LEONIDA_WINE_TEST_INHERITED', " - "'LEONIDA_WINE_TEST_VALUE', 'LEONIDA_WINE_TEST_EMPTY'):\n" - " print(repr(os.environ.get(key)))\n") - command = self.command_for(exe) - env = {"LEONIDA_HOST_ADAPTER": "inherited", "LEONIDA_WINE_TEST_INHERITED": "keep"} - props = {"ENVIRONMENT": ["LEONIDA_HOST_ADAPTER=warp", "LEONIDA_WINE_TEST_VALUE=path=a;b", - "LEONIDA_WINE_TEST_EMPTY="]} - with mock.patch.dict(os.environ, env): - os.environ.pop("LEONIDA_WINE_TEST_VALUE", None) - os.environ.pop("LEONIDA_WINE_TEST_EMPTY", None) - status, detail = self.run_entry(ctest_entry("with_environment", command, props)) - self.assertEqual(status, "pass", detail) - self.assertEqual(detail.splitlines()[1:], ["'warp'", "'keep'", "'path=a;b'", "''"]) - status, detail = self.run_entry(ctest_entry("without_environment", command)) - self.assertEqual(status, "pass", detail) - self.assertEqual(detail.splitlines()[1:], ["'inherited'", "'keep'", "None", "None"]) - - def test_malformed_ctest_environment_fails_before_launch(self) -> None: - command = self.command_for(self.exiting(0)) - props = {"ENVIRONMENT": ["missing_equals"]} - with mock.patch.object(rwt, "run_test_process", wraps=rwt.run_test_process) as launch: - status, detail = self.run_entry(ctest_entry("bad_environment", command, props)) - launch.assert_not_called() - self.assertEqual(status, "fail", detail) - self.assertIn("invalid CTest ENVIRONMENT", detail) - - def test_wines_crash_debugger_is_turned_off_for_the_child(self) -> None: - exe = self.program("show_overrides.py", "import os\nprint(os.environ.get('WINEDLLOVERRIDES'))\n") - command = self.command_for(exe) - cases = ((None, None, "winedbg.exe=d"), - ("mscoree,mshtml=", None, "mscoree,mshtml=;winedbg.exe=d"), - ("dxgi=n; ", None, "dxgi=n;winedbg.exe=d"), - ("mscoree=", "d3d12=n", "d3d12=n;winedbg.exe=d"), - ("winedbg.exe=b", None, "winedbg.exe=b"), - ("mscoree=", "WineDbg.exe=n,b", "WineDbg.exe=n,b")) - for inherited, listed, expected in cases: - props = {"ENVIRONMENT": [f"WINEDLLOVERRIDES={listed}"]} if listed is not None else None - with self.subTest(inherited=inherited, listed=listed), mock.patch.dict(os.environ): - os.environ.pop("WINEDLLOVERRIDES", None) - if inherited is not None: - os.environ["WINEDLLOVERRIDES"] = inherited - status, detail = self.run_entry(ctest_entry("overrides", command, props)) - self.assertEqual(status, "pass", detail) - self.assertEqual(detail.splitlines()[1:], [expected]) - # The runner's own environment stays as it was. - self.assertEqual(os.environ.get("WINEDLLOVERRIDES"), inherited) - - def test_without_debugger_keeps_the_other_overrides(self) -> None: - self.assertEqual(rwt.without_debugger(""), "winedbg.exe=d") - self.assertEqual(rwt.without_debugger(" ; "), "winedbg.exe=d") - self.assertEqual(rwt.without_debugger("a=n;b="), "a=n;b=;winedbg.exe=d") - self.assertEqual(rwt.without_debugger("a=n;winedbg.exe=d"), "a=n;winedbg.exe=d") - - def test_ctest_output_expressions_determine_the_result(self): - usage = {"PASS_REGULAR_EXPRESSION": ["alternative", "usage: gta6rt"]} - forbidden = {"FAIL_REGULAR_EXPRESSION": ["running ", r"module\(s\) mapped"]} - for code, output, props, expected in ( - (2, "usage: gta6rt", usage | forbidden, "pass"), - (0, "unexpected output", usage, "fail"), - (2, "usage: gta6rt\n1 module(s) mapped", usage | forbidden, "fail"), - (0, "running tiny_game.exe", forbidden, "fail"), - (2, "unexpected output", forbidden, "fail"), - (77, "unexpected output", usage | {"SKIP_RETURN_CODE": 77}, "skip"), - (0, "running tiny_game.exe", forbidden | {"WILL_FAIL": True}, "pass"), - ): - with self.subTest(code=code, output=output, props=props): - exe = self.program("regex.py", f"import sys\nprint({output!r}, file=sys.stderr)\nsys.exit({code})\n") - status, detail = self.run_entry(ctest_entry("regex", self.command_for(exe), props)) - self.assertEqual(status, expected, detail) - - def test_a_scalar_output_expression_is_matched_as_one_pattern(self): - required = {"PASS_REGULAR_EXPRESSION": "usage: gta6rt"} - forbidden = {"FAIL_REGULAR_EXPRESSION": r"module\(s\) mapped"} - for code, output, props, expected in ( - (3, "unexpected output", required, "fail"), - (2, "usage: gta6rt", required, "pass"), - (0, "unexpected output", forbidden, "pass"), - (0, "1 module(s) mapped", forbidden, "fail"), - ): - with self.subTest(output=output, props=props): - exe = self.program("regex.py", f"import sys\nprint({output!r})\nsys.exit({code})\n") - status, detail = self.run_entry(ctest_entry("regex", self.command_for(exe), props)) - self.assertEqual(status, expected, detail) - - def test_skip_output_overrides_a_normal_exit_status(self): - skip_pattern = "SKIP: missing adapter" - exe = self.program("skip.py", f"print({skip_pattern!r})\nraise SystemExit(3)\n") - for expression in (skip_pattern, ["different reason", skip_pattern]): - with self.subTest(expression=expression): - entry = ctest_entry("skip", self.command_for(exe), {"SKIP_REGULAR_EXPRESSION": expression}) - status, detail = rwt.run_test(entry, self.args, [sys.executable, "-I"]) - self.assertEqual(status, "skip", detail) - self.assertIn("SKIP_REGULAR_EXPRESSION", detail) - - entry = ctest_entry("no_match", self.command_for(exe), {"SKIP_REGULAR_EXPRESSION": ["different reason"]}) - status, detail = rwt.run_test(entry, self.args, [sys.executable, "-I"]) - self.assertEqual(status, "fail", detail) - - def test_a_signal_termination_fails_even_with_success_overrides(self): - # The mocked negative returncode keeps the test portable across Windows and POSIX. - exe = self.exiting(0) - fake = mock.Mock(returncode=-11, stdout=b"usage: gta6rt") - for props in ({"WILL_FAIL": True}, {"PASS_REGULAR_EXPRESSION": ["usage: gta6rt"]}, - {"SKIP_REGULAR_EXPRESSION": ["usage: gta6rt"]}): - with self.subTest(props=props), mock.patch.object(rwt, "run_test_process", return_value=fake): - entry = ctest_entry("segv", self.command_for(exe), props | {"SKIP_RETURN_CODE": 77}) - status, detail = self.run_entry(entry) - self.assertEqual(status, "fail") - self.assertIn("signal 11", detail) - - def test_a_timeout_is_reported_without_hanging(self): - slow = self.program("slow.py", "import time\ntime.sleep(5)\n") - self.args.timeout = 0.2 - status, detail = self.run_entry(ctest_entry("slow", self.command_for(slow))) - self.assertEqual(status, "fail") - self.assertIn("timed out after 0.2 s", detail) - - @unittest.skipUnless(os.name == "posix", "POSIX process groups") - def test_timeout_stops_a_helper_even_after_the_launcher_exits(self): - import fcntl - - guard_path = self.artifact / "helper.lock" - stop_path = self.artifact / "stop" - helper = self.program("helper.py", """ -import fcntl -from pathlib import Path -import time - -with open("helper.lock", "a") as guard: - fcntl.flock(guard, fcntl.LOCK_EX) - print("helper ready", flush=True) - deadline = time.monotonic() + 10 - while not Path("stop").exists() and time.monotonic() < deadline: - time.sleep(0.01) -""") - launcher = self.program("launcher.py", f""" -import subprocess -import sys - -subprocess.Popen([sys.executable, {helper!r}]) -""") - self.args.timeout = 1 - entry = ctest_entry("tree", self.command_for(launcher)) - try: - status, detail = self.run_entry(entry) - self.assertEqual(status, "fail", detail) - self.assertIn("timed out", detail) - self.assertIn("helper ready", detail) - with guard_path.open("a") as guard: - deadline = time.monotonic() + 1 - while True: - try: - fcntl.flock(guard, fcntl.LOCK_EX | fcntl.LOCK_NB) - break - except BlockingIOError: - if time.monotonic() >= deadline: - self.fail("helper still holds its lock after the test timed out") - time.sleep(0.01) - finally: - stop_path.touch() - - def test_a_short_ctest_timeout_still_fails_a_will_fail_test(self): - slow = self.program("slow_failure.py", "import sys, time\ntime.sleep(1)\nsys.exit(1)\n") - entry = ctest_entry("slow_failure", self.command_for(slow), {"TIMEOUT": 0.2, "WILL_FAIL": True}) - status, detail = self.run_entry(entry) - self.assertEqual(status, "fail", detail) - self.assertIn("timed out after 0.2 s", detail) - - def test_ctest_timeout_cannot_remove_or_extend_the_runner_limit(self): - exe = self.exiting(0) - for timeout in (0, "20"): - with self.subTest(timeout=timeout): - entry = ctest_entry("bounded", self.command_for(exe), {"TIMEOUT": timeout}) - result = rwt.subprocess.CompletedProcess([], 0, stdout=b"") - with mock.patch.object(rwt, "run_test_process", return_value=result) as run: - status, detail = self.run_entry(entry) - self.assertEqual(status, "pass", detail) - self.assertEqual(run.call_args.kwargs["timeout"], self.args.timeout) - - def test_an_unstartable_wine_fails_the_test_instead_of_aborting_the_run(self): - status, detail = rwt.run_test(ctest_entry("ok", self.command_for(self.exiting(0))), self.args, - ["definitely-not-a-real-wine-xyz"]) - self.assertEqual(status, "fail") - self.assertIn("could not start", detail) - - def test_arguments_and_working_directory_are_mapped(self): - report = self.root / "report.json" - script = self.program("report.py", ( - "import json, os, sys\n" - "json.dump({'argv': sys.argv[1:], 'cwd': os.getcwd()}, open(os.environ['REPORT_PATH'], 'w'))\n")) - (self.artifact / "sub").mkdir() - entry = ctest_entry("mapped", self.command_for(script, WINDOWS_ROOT + "/artifact/data.bin", "--flag"), - {"WORKING_DIRECTORY": WINDOWS_ROOT + "/artifact/sub"}) - with mock.patch.dict(os.environ, {"REPORT_PATH": str(report)}): - status, detail = self.run_entry(entry) - self.assertEqual(status, "pass", detail) - seen = json.loads(report.read_text(encoding="utf-8")) - self.assertEqual(len(seen["argv"]), 2) - self.assertTrue(seen["argv"][0].startswith("Z:"), seen["argv"][0]) - self.assertTrue(seen["argv"][0].endswith("data.bin"), seen["argv"][0]) - self.assertEqual(seen["argv"][1], "--flag") - self.assertEqual(os.path.normcase(os.path.realpath(seen["cwd"])), - os.path.normcase(os.path.realpath(self.artifact / "sub"))) - - def test_invalid_mapped_working_directory_fails_without_starting_wine(self): - exe = self.exiting(0) - (self.artifact / "file").touch() - for name in ("missing", "file"): - cwd = WINDOWS_ROOT + f"/artifact/{name}" - with self.subTest(cwd=cwd), mock.patch.object(rwt.subprocess, "run", wraps=rwt.subprocess.run) as run: - entry = ctest_entry("bad_cwd", self.command_for(exe), {"WORKING_DIRECTORY": cwd}) - status, detail = self.run_entry(entry) - self.assertEqual(status, "fail") - self.assertIn("working directory", detail) - self.assertIn(cwd, detail) - run.assert_not_called() - - -@unittest.skipIf(os.name == "nt", "the runner and its dosdevices links are for Linux and macOS") -class DriveMapTest(unittest.TestCase): - def setUp(self): - self._tmp = tempfile.TemporaryDirectory() - base = Path(self._tmp.name) - self.root = base / "checkout" - (self.root / "runtime" / "build" / "generated").mkdir(parents=True) - (self.root / "runtime" / "build" / "generated" / "cs.spv").write_text("spirv", encoding="utf-8") - self.prefix = base / "prefix" - (self.prefix / "dosdevices").mkdir(parents=True) - self.link = self.prefix / "dosdevices" / "d:" - - def tearDown(self): - self._tmp.cleanup() - - def test_the_drive_leads_to_the_checkout_and_is_removed_afterwards(self): - with rwt.DriveMap("D:/a/Leonida/Leonida", str(self.root), str(self.prefix)) as drive: - seen = self.link / "a" / "Leonida" / "Leonida" / "runtime" / "build" / "generated" / "cs.spv" - self.assertEqual(seen.read_text(encoding="utf-8"), "spirv") - self.assertIn("drive d: maps", drive.note) - scratch = drive.scratch - self.assertFalse(os.path.lexists(self.link)) - self.assertFalse(os.path.exists(scratch)) - self.assertTrue((self.root / "runtime" / "build" / "generated" / "cs.spv").is_file()) # links only - - def test_backslashes_and_a_lower_case_drive_are_accepted(self): - with rwt.DriveMap("d:\\work\\leonida\\", str(self.root), str(self.prefix)): - self.assertTrue((self.link / "work" / "leonida" / "runtime" / "build").is_dir()) - - def test_a_drive_the_prefix_already_has_is_left_alone(self): - other = self.prefix / "elsewhere" - other.mkdir() - os.symlink(other, self.link) - with rwt.DriveMap("D:/a/Leonida/Leonida", str(self.root), str(self.prefix)) as drive: - self.assertIn("already set", drive.note) - self.assertEqual(os.readlink(self.link), str(other)) - - def test_drive_created_during_setup_is_left_alone(self): - other = self.prefix / "concurrent" - other.mkdir() - scratch = self.prefix / "scratch" - scratch.mkdir() - symlink = os.symlink - - def add_mapping(target, link): - if Path(link) == self.link: - symlink(other, self.link) - symlink(target, link) - - with mock.patch.object(rwt.tempfile, "mkdtemp", return_value=str(scratch)), \ - mock.patch.object(rwt.os, "symlink", side_effect=add_mapping): - with rwt.DriveMap(WINDOWS_ROOT, str(self.root), str(self.prefix)) as drive: - self.assertIn("already set", drive.note) - - self.assertEqual(os.readlink(self.link), str(other)) - self.assertFalse(scratch.exists()) - - def test_failed_drive_setup_removes_scratch_directory(self): - scratch = self.prefix / "scratch" - scratch.mkdir() - with mock.patch.object(rwt.tempfile, "mkdtemp", return_value=str(scratch)), \ - mock.patch.object(rwt.os, "symlink", side_effect=PermissionError("link denied")): - with self.assertRaisesRegex(PermissionError, "link denied"): - with rwt.DriveMap(WINDOWS_ROOT, str(self.root), str(self.prefix)): - self.fail("drive setup unexpectedly succeeded") - - self.assertFalse(scratch.exists()) - self.assertFalse(os.path.lexists(self.link)) - - def test_no_prefix_or_no_drive_letter_maps_nothing(self): - with rwt.DriveMap("D:/a/b", str(self.root), str(self.prefix / "absent")) as drive: - self.assertIn("no Wine prefix", drive.note) - with rwt.DriveMap("/home/runner/work", str(self.root), str(self.prefix)) as drive: - self.assertIn("no drive letter", drive.note) - self.assertFalse(os.path.lexists(self.link)) - - def test_main_maps_the_drive_while_the_tests_run(self): - # The "Wine" here is the Python interpreter, so the program reads the drive through its dosdevices link, which - # is where Wine resolves D:/win/root/... too. - probe = self.root / "probe.py" - listing = self.root / "ctest.json" - for windows_root, checkout in ((WINDOWS_ROOT, self.link / "win" / "root"), ("D:/", self.link)): - with self.subTest(windows_root=windows_root): - target = checkout / "runtime" / "build" / "generated" / "cs.spv" - probe.write_text(f"import sys\nsys.exit(0 if open({str(target)!r}).read() == 'spirv' else 1)\n", - encoding="utf-8", newline="\n") - command = [windows_root.rstrip("/") + "/probe.py"] - listing.write_text(json.dumps({"tests": [ctest_entry("compiled_in_path", command)]}), - encoding="utf-8", newline="\n") - argv = ["run_wine_tests.py", "--tests", str(listing), "--windows-root", windows_root, - "--root", str(self.root), "--wine", sys.executable.replace(os.sep, "/"), - "--require", "compiled_in_path"] - out = io.StringIO() - with mock.patch.dict(os.environ, {"WINEPREFIX": str(self.prefix)}), \ - mock.patch.object(sys, "argv", argv), contextlib.redirect_stdout(out): - code = rwt.main() - self.assertEqual(code, 0, out.getvalue()) - self.assertIn("[PASS] compiled_in_path", out.getvalue()) - self.assertFalse(os.path.lexists(self.link)) - - -class MainTest(unittest.TestCase): - def setUp(self): - self._tmp = tempfile.TemporaryDirectory() - self.root = Path(self._tmp.name) - self.artifact = self.root / "artifact" - self.artifact.mkdir() - for name, code in (("ok.py", 0), ("bad.py", 1)): - (self.artifact / name).write_text(f"import sys\nsys.exit({code})\n", encoding="utf-8") - # main() maps the checkout's drive into $WINEPREFIX: keep it away from a real prefix (~/.wine). - env = mock.patch.dict(os.environ, {"WINEPREFIX": str(self.root / "no-prefix")}) - env.start() - self.addCleanup(env.stop) - - def tearDown(self): - self._tmp.cleanup() - - def list_tests(self, entries): - path = self.root / "ctest.json" - path.write_text(json.dumps({"tests": entries}), encoding="utf-8") - return str(path) - - def command(self, name): - return [WINDOWS_ROOT + "/artifact/" + name] - - def run_main(self, entries, *extra, stderr=False, root=None, wine=sys.executable): - listing = self.list_tests(entries) - argv = ["run_wine_tests.py", "--tests", listing, "--windows-root", WINDOWS_ROOT, - "--root", str(self.root if root is None else root)] - if wine is not None: - argv += ["--wine", wine.replace(os.sep, "/")] - argv += extra - out, err = io.StringIO(), io.StringIO() - with mock.patch.object(sys, "argv", argv), contextlib.redirect_stdout(out), contextlib.redirect_stderr(err): - code = rwt.main() - return code, out.getvalue(), err.getvalue() - - def test_a_required_test_that_passes_exits_zero(self): - code, out, _ = self.run_main([ctest_entry("ok", self.command("ok.py"))], "--require", "ok") - self.assertEqual(code, 0) - self.assertIn("1 passed, 0 failed, 0 skipped under Wine (1 tests)", out) - - def test_child_sees_eof_even_when_the_runner_has_input(self): - (self.artifact / "stdin.py").write_text( - "import sys\nassert sys.stdin.read() == ''\n", encoding="utf-8", newline="\n") - listing = self.list_tests([ctest_entry("stdin", self.command("stdin.py"))]) - proc = subprocess.run( - [sys.executable, "-I", str(SCRIPTS / "run_wine_tests.py"), "--tests", listing, - "--windows-root", WINDOWS_ROOT, "--root", str(self.root), - "--wine", f'"{sys.executable.replace(os.sep, "/")}"', "--require", "stdin"], - input="input meant for the caller\n", capture_output=True, text=True, timeout=10) - self.assertEqual(proc.returncode, 0, proc.stdout + proc.stderr) - self.assertIn("[PASS] stdin", proc.stdout) - - def test_relative_root_launches_the_artifact_from_its_working_directory(self): - (self.artifact / "check_cwd.py").write_text( - # resolve() on both sides: on Windows tempfile hands out the 8.3 name (RUNNER~1) and the module's - # path resolves to the long one, so the two spellings differ while naming one folder. - "from pathlib import Path\nassert Path.cwd().resolve() == Path(__file__).resolve().parent\n", - encoding="utf-8", newline="\n") - entry = ctest_entry("ok", self.command("check_cwd.py")) - with contextlib.chdir(self.root): - code, out, _ = self.run_main([entry], "--require", "ok", root=".") - self.assertEqual(code, 0, out) - self.assertIn("[PASS] ok", out) - - @unittest.skipUnless(os.name == "posix", "uses a symlink as a Wine executable") - def test_relative_wine_command_is_resolved_before_changing_directories(self): - (self.root / "local wine").symlink_to(sys.executable) - command = "'./local wine' -B" - entry = ctest_entry("ok", self.command("ok.py")) - with contextlib.chdir(self.root): - for wine, env in ((command, "missing-wine"), (None, command)): - with self.subTest(wine=wine), mock.patch.dict(os.environ, {"WINE": env}): - code, out, _ = self.run_main([entry], "--require", "ok", wine=wine) - self.assertEqual(code, 0, out) - self.assertIn("[PASS] ok", out) - - def test_a_required_test_that_fails_exits_one(self): - code, out, _ = self.run_main([ctest_entry("bad", self.command("bad.py"))], "--require", "bad") - self.assertEqual(code, 1) - self.assertIn("required tests that did not pass: bad", out) - - def test_a_required_test_that_is_not_listed_exits_one(self): - code, out, _ = self.run_main([ctest_entry("ok", self.command("ok.py"))], "--require", "absent") - self.assertEqual(code, 1) - self.assertIn("required test not listed", out) - - def test_unrequired_failures_are_reported_but_do_not_fail_the_job(self): - code, out, _ = self.run_main([ctest_entry("bad", self.command("bad.py"))]) - self.assertEqual(code, 0) - self.assertIn("[FAIL] bad", out) - - def test_malformed_skip_return_code_does_not_stop_later_tests(self): - entries = [ - ctest_entry("bad_property", self.command("ok.py"), {"SKIP_RETURN_CODE": "invalid"}), - ctest_entry("ok", self.command("ok.py")), - ] - code, out, err = self.run_main(entries, "--require", "ok") - self.assertEqual(code, 0, err) - self.assertIn("[FAIL] bad_property", out) - self.assertIn("invalid CTest SKIP_RETURN_CODE", out) - self.assertIn("[PASS] ok", out) - - def test_the_summary_table_is_appended(self): - summary = self.root / "summary.md" - code, _, _ = self.run_main([ctest_entry("ok", self.command("ok.py")), ctest_entry("bad", self.command("bad.py"))], - "--summary", str(summary), "--label", "Wine 11", "--require", "ok") - self.assertEqual(code, 0) - text = summary.read_text(encoding="utf-8") - self.assertIn("### Windows tests under Wine 11", text) - self.assertIn("| `ok` | pass | yes |", text) - self.assertIn("| `bad` | fail | |", text) - - def test_the_summary_names_a_required_test_that_is_not_listed(self): - summary = self.root / "summary.md" - code, _, _ = self.run_main([ctest_entry("ok", self.command("ok.py"))], "--summary", str(summary), - "--require", "ok", "--require", "absent", "--require", "absent") - self.assertEqual(code, 1) - text = summary.read_text(encoding="utf-8") - self.assertIn("| `ok` | pass | yes |", text) - self.assertEqual(text.count("| `absent` | missing: not listed by the Windows build | yes |"), 1) - - def test_a_summary_in_a_missing_folder_creates_it(self): - summary = self.root / "missing" / "sub" / "summary.md" - code, _, err = self.run_main([ctest_entry("ok", self.command("ok.py"))], - "--summary", str(summary), "--label", "Wine 12") - self.assertEqual(code, 0) - self.assertEqual(err, "") - self.assertIn("### Windows tests under Wine 12", summary.read_text(encoding="utf-8")) - - def test_an_unwritable_summary_is_one_error_line(self): - blocker = self.root / "blocker" - blocker.write_text("not a folder", encoding="utf-8") - summary = blocker / "summary.md" # its parent is a file, not a folder - code, _, err = self.run_main([ctest_entry("ok", self.command("ok.py"))], "--summary", str(summary)) - self.assertEqual(code, 1) - self.assertNotIn("Traceback", err) - self.assertIn("ERROR: cannot write the summary", err) - self.assertEqual(len(err.strip().splitlines()), 1, err) - - def test_a_file_that_is_not_json_is_one_error_line(self): - listing = self.root / "notes.txt" - listing.write_text("this is not ctest output\n", encoding="utf-8") - argv = ["run_wine_tests.py", "--tests", str(listing), "--windows-root", WINDOWS_ROOT, - "--root", str(self.root), "--wine", sys.executable.replace(os.sep, "/")] - out, err = io.StringIO(), io.StringIO() - with mock.patch.object(sys, "argv", argv), contextlib.redirect_stdout(out), contextlib.redirect_stderr(err): - code = rwt.main() - self.assertEqual(code, 2) - self.assertIn("ERROR: cannot read", err.getvalue()) - self.assertNotIn("Traceback", err.getvalue()) - - def test_json_that_is_not_ctest_output_is_one_error_line(self): - code, _, err = self.run_main_json([{"name": "t"}]) - self.assertEqual(code, 2) - self.assertIn("not the output of ctest", err) - - def test_missing_tests_is_not_a_zero_test_run(self): - code, _, err = self.run_main_json({}) - self.assertEqual(code, 2) - self.assertIn("not the output of ctest", err) - - def test_scalar_tests_rows_are_rejected(self): - code, _, err = self.run_main_json({"tests": ["binary", 3, None]}) - self.assertEqual(code, 2) - self.assertIn("not the output of ctest", err) - - def test_malformed_command_and_property_rows_are_rejected_before_launch(self): - for fields in ( - {"command": "D:/win/root/artifact/ok.py"}, - {"command": [42]}, - {"command": [self.command("ok.py")[0], "embedded\0null"]}, - {"properties": {"TIMEOUT": 10}}, - {"properties": [{"name": "TIMEOUT"}]}, - {"properties": [{"name": ["TIMEOUT"], "value": 10}]}, - {"properties": [{"name": "WORKING_DIRECTORY", "value": 42}]}, - {"properties": [{"name": "WORKING_DIRECTORY", "value": "D:/win/\0root"}]}, - {"properties": [{"name": "PASS_REGULAR_EXPRESSION", "value": [42]}]}, - {"properties": [{"name": "FAIL_REGULAR_EXPRESSION", "value": {"bad": True}}]}, - {"properties": [{"name": "SKIP_REGULAR_EXPRESSION", "value": None}]}, - {"name": []}, - ): - with self.subTest(fields=fields): - good = ctest_entry("ok", self.command("ok.py")) - with mock.patch.object(rwt, "DriveMap") as drive, \ - mock.patch.object(rwt, "run_test", return_value=("pass", "")) as launch: - code, _, err = self.run_main([good, good | fields]) - self.assertEqual(code, 2) - self.assertIn("not the output of ctest", err) - drive.assert_not_called() - launch.assert_not_called() - - def test_an_unbuilt_test_without_a_command_is_valid_inventory(self): - code, out, err = self.run_main([{"name": "unbuilt"}], "--require", "unbuilt") - self.assertEqual(code, 1) - self.assertIn("[FAIL] unbuilt", out) - self.assertIn("no command", out) - self.assertEqual(err, "") - - def test_ctest_property_strings_and_expression_lists_are_valid_inventory(self): - properties = { - "WORKING_DIRECTORY": WINDOWS_ROOT + "/artifact", - "PASS_REGULAR_EXPRESSION": ["good", "also good"], - "FAIL_REGULAR_EXPRESSION": "unexpected", - "SKIP_REGULAR_EXPRESSION": [], - "MEASUREMENTS": {"custom": "value"}, - } - row = ctest_entry("ok", self.command("ok.py"), properties) - with mock.patch.object(rwt, "run_test", return_value=("pass", "")) as launch: - code, _, err = self.run_main([row], "--require", "ok") - self.assertEqual(code, 0) - self.assertEqual(err, "") - launch.assert_called_once() - - def test_an_explicit_empty_tests_list_is_accepted(self): - code, out, _ = self.run_main_json({"tests": []}) - self.assertEqual(code, 0) - self.assertIn("0 passed, 0 failed, 0 skipped under Wine (0 tests)", out) - - def run_main_json(self, document): - listing = self.root / "wrong.json" - listing.write_text(json.dumps(document), encoding="utf-8") - argv = ["run_wine_tests.py", "--tests", str(listing), "--windows-root", WINDOWS_ROOT, - "--root", str(self.root), "--wine", sys.executable.replace(os.sep, "/")] - out, err = io.StringIO(), io.StringIO() - with mock.patch.object(sys, "argv", argv), contextlib.redirect_stdout(out), contextlib.redirect_stderr(err): - code = rwt.main() - return code, out.getvalue(), err.getvalue() - - def test_a_bad_timeout_is_refused_by_argparse(self): - for text in ("0", "-1", "abc", "nan", "inf", "-inf"): - with self.subTest(text=text): - with self.assertRaises(argparse.ArgumentTypeError): - rwt.positive_seconds(text) - self.assertEqual(rwt.positive_seconds("0.5"), 0.5) - - def test_a_nonfinite_timeout_is_a_usage_error(self): - for text in ("nan", "inf", "-inf"): - with self.subTest(text=text): - with self.assertRaises(SystemExit) as ctx: - self.run_main([ctest_entry("ok", self.command("ok.py"))], "--timeout", text) - self.assertEqual(ctx.exception.code, 2) - - def test_a_blank_wine_is_a_usage_error(self): - with self.assertRaises(SystemExit) as ctx: - self.run_main([ctest_entry("ok", self.command("ok.py"))], "--wine", "") - self.assertEqual(ctx.exception.code, 2) - - def test_an_unclosed_quote_in_wine_is_a_usage_error(self): - with self.assertRaises(SystemExit) as ctx: - self.run_main([ctest_entry("ok", self.command("ok.py"))], "--wine", "wine 'unclosed") - self.assertEqual(ctx.exception.code, 2) - - def test_wine_quoting_is_still_split(self): - self.assertEqual(rwt.wine_command("prog 'two words'"), ["prog", "two words"]) - with self.assertRaises(argparse.ArgumentTypeError): - rwt.wine_command(" ") - - @staticmethod - def workflow_commands(out): - return [line for line in out.splitlines() if line.startswith("::")] - - def test_no_workflow_commands_outside_github_actions(self): - with mock.patch.dict(os.environ): - os.environ.pop("GITHUB_ACTIONS", None) - code, out, _ = self.run_main([ctest_entry("ok", self.command("ok.py"))]) - self.assertEqual(code, 0) - self.assertEqual(self.workflow_commands(out), []) - - def test_github_actions_gets_a_start_notice_a_timeout_warning_and_an_end_notice(self): - # A job cancelled at its time limit shows no log to a reader without a login, but its annotations stay. - (self.artifact / "slow.py").write_text("import time\ntime.sleep(5)\n", encoding="utf-8", newline="\n") - entries = [ctest_entry("ok", self.command("ok.py")), ctest_entry("slow", self.command("slow.py"))] - with mock.patch.dict(os.environ, {"GITHUB_ACTIONS": "true"}): - code, out, _ = self.run_main(entries, "--timeout", "0.2", "--label", "wine-9.0") - self.assertEqual(code, 0) - commands = self.workflow_commands(out) - self.assertEqual(len(commands), 4, out) - self.assertEqual(commands[0], "::notice::run_wine_tests: 2 tests to run under wine-9.0") - self.assertRegex(commands[1], r"^::warning::slow timed out after 0\.2 s under wine-9\.0, \d+ s into the run; " - r"it printed nothing$") - self.assertEqual(commands[2], "::notice::run_wine_tests: 1 failed under wine-9.0:%0A" - "slow: timed out after 0.2 s") - self.assertRegex(commands[3], r"^::notice::run_wine_tests: 1 passed, 1 failed, 0 skipped under wine-9\.0 " - r"in \d+ s(; slowest: [a-z]+ \d+ s(, [a-z]+ \d+ s)?)?$") - - def test_notices_name_every_failed_and_skipped_test(self): - # The job log and the step summary need a login: these notices are the verdicts anyone can read. - (self.artifact / "says.py").write_text("import sys\nprint('step 1')\nprint('line 9: x == y')\nsys.exit(3)\n", - encoding="utf-8", newline="\n") - (self.artifact / "skips.py").write_text("import sys\nprint('SKIP: no device')\nsys.exit(77)\n", - encoding="utf-8", newline="\n") - entries = [ctest_entry("ok", self.command("ok.py")), ctest_entry("says", self.command("says.py")), - ctest_entry("bad", self.command("bad.py")), - ctest_entry("skips", self.command("skips.py"), {"SKIP_RETURN_CODE": "77"}), - ctest_entry("tool", ["/usr/bin/cmake", "-P", "x.cmake"])] - with mock.patch.dict(os.environ, {"GITHUB_ACTIONS": "true"}): - code, out, _ = self.run_main(entries, "--label", "wine-9.0") - self.assertEqual(code, 0) - commands = self.workflow_commands(out) - self.assertEqual(len(commands), 4, out) - self.assertRegex(commands[1], r"^::notice::run_wine_tests: 2 failed under wine-9\.0:%0A" - r"says: exit 3 in \d+\.\d s; failing lines: line 9: x == y%0A" - r"bad: exit 1 in \d+\.\d s$") - self.assertRegex(commands[2], r"^::notice::run_wine_tests: 2 skipped under wine-9\.0:%0A" - r"skips: exit 77 \(skip\) in \d+\.\d s; last line: SKIP: no device%0A" - r"tool: runs /usr/bin/cmake, not a program from the build$") - self.assertRegex(commands[3], r"^::notice::run_wine_tests: 1 passed, 2 failed, 2 skipped under wine-9\.0 ") - - def test_no_failed_or_skipped_notice_when_every_test_passes(self): - with mock.patch.dict(os.environ, {"GITHUB_ACTIONS": "true"}): - code, out, _ = self.run_main([ctest_entry("ok", self.command("ok.py"))]) - self.assertEqual(code, 0) - self.assertEqual(len(self.workflow_commands(out)), 2, out) - - def test_verdict_lines_are_bounded(self): - self.assertEqual(rwt.verdict_line("t", ""), "t") - self.assertEqual(rwt.verdict_line("t", "exit 1 in 0.1 s\n\n"), "t: exit 1 in 0.1 s") - self.assertEqual(rwt.verdict_line("t", "exit 1 in 0.1 s\nfirst\n last\tone \r\n\n"), - "t: exit 1 in 0.1 s; last line: last one") - long = rwt.verdict_line("t", "exit 1 in 0.1 s\n" + "x" * 1000) - self.assertEqual(len(long), rwt.VERDICT_CHARS) - self.assertTrue(long.endswith("x..."), long) - skipped = rwt.verdict_line("t", "exit 77 (skip) in 0.1 s\nSKIP: device unavailable " + "x" * 1000, - failed=False) - self.assertEqual(len(skipped), rwt.SKIP_CHARS) - self.assertTrue(skipped.startswith("t: exit 77 (skip) in 0.1 s; last line: SKIP: device unavailable x"), - skipped) - - def test_a_failed_tests_entry_quotes_its_failed_checks(self): - # In CI the last line of most failed tests was the runtime's log, which did not say what failed. - detail = ("exit 1 in 0.1 s\nPASS opens\nFAIL reports STATUS_NOT_FOUND\n[rt] bcrypt: host call failed\n" - "[PASS] a failed open clears ppv\nline 12: a == b\nrow 3: ours 1 host 2 MISMATCH\nDIFF rgba8\n" - "21 check(s), 4 failure(s)\n[rt] d3d12: arena peak\n") - self.assertEqual(rwt.verdict_line("t", detail), - "t: exit 1 in 0.1 s; failing lines: FAIL reports STATUS_NOT_FOUND | line 12: a == b | " - "row 3: ours 1 host 2 MISMATCH (and 1 more); last line: 21 check(s), 4 failure(s)") - self.assertEqual(rwt.verdict_line("t", "exit 1 in 0.1 s\nstep\nFAIL: the last one\n"), - "t: exit 1 in 0.1 s; failing lines: FAIL: the last one") - self.assertEqual(rwt.verdict_line("t", "exit 1 in 0.1 s\n[rt] only the log\n"), - "t: exit 1 in 0.1 s; last line: [rt] only the log") - self.assertEqual(rwt.verdict_line("t", "exit 77 (skip) in 0.1 s\nSKIP: device unavailable\n", failed=False), - "t: exit 77 (skip) in 0.1 s; last line: SKIP: device unavailable") - long = rwt.verdict_line("t", "exit 1 in 0.1 s\nFAIL " + "y" * 500 + "\nend\n") - self.assertEqual(long, "t: exit 1 in 0.1 s; failing lines: FAIL " + "y" * (rwt.LINE_CHARS - 8) - + "...; last line: end") - - def test_verdict_notices_split_at_whole_entries(self): - lines = [f"test{i}: exit 1" for i in range(5)] - self.assertEqual(rwt.verdict_notices([], 4), []) - self.assertEqual(rwt.verdict_notices(lines, 4), ["\n".join(lines)]) - with mock.patch.object(rwt, "NOTICE_CHARS", 2 * len(lines[0]) + 2): - self.assertEqual(rwt.verdict_notices(lines, 4), ["\n".join(lines[:2]), "\n".join(lines[2:4]), lines[4]]) - self.assertEqual(rwt.verdict_notices(lines, 2), - ["\n".join(lines[:2]), "\n".join(lines[2:4] + ["... and 1 more"])]) - - def test_a_long_failed_list_is_split_over_numbered_notices(self): - # GitHub cuts a notice at 4096 characters, which lost the end of both skipped lists in CI. - entries = [ctest_entry(f"bad{i}", self.command("bad.py")) for i in range(2)] - with mock.patch.dict(os.environ, {"GITHUB_ACTIONS": "true"}), mock.patch.object(rwt, "NOTICE_CHARS", 30): - code, out, _ = self.run_main(entries, "--label", "wine-9.0") - self.assertEqual(code, 0) - commands = self.workflow_commands(out) - self.assertEqual(len(commands), 4, out) - for part in (1, 2): - self.assertRegex(commands[part], rf"^::notice::run_wine_tests: 2 failed under wine-9\.0 \({part} of 2\):%0A" - rf"bad{part - 1}: exit 1 in \d+\.\d s$") - - def test_timeout_warning_carries_the_last_output(self): - def hang(argv, *, cwd, env, timeout): - raise subprocess.TimeoutExpired(argv, timeout, output=b"step 1\r\n\r\nstep 2\n") - - with mock.patch.dict(os.environ, {"GITHUB_ACTIONS": "true"}), \ - mock.patch.object(rwt, "run_test_process", hang): - code, out, _ = self.run_main([ctest_entry("stuck", self.command("ok.py"))], "--timeout", "7") - self.assertEqual(code, 0) - warnings = [line for line in self.workflow_commands(out) if line.startswith("::warning::")] - self.assertEqual(len(warnings), 1, out) - self.assertRegex(warnings[0], r"^::warning::stuck timed out after 7\.0 s under Wine, \d+ s into the run; " - r"its last output:%0Astep 1%0Astep 2$") - - def test_timeout_tail_is_bounded(self): - self.assertEqual(rwt.timeout_tail("timed out after 120.0 s\n"), "it printed nothing") - self.assertEqual(rwt.timeout_tail("timed out after 120.0 s\n \n\n"), "it printed nothing") - many = "timed out after 120.0 s\n" + "".join(f"line {i}\n" for i in range(40)) - self.assertEqual(rwt.timeout_tail(many).splitlines(), - ["its last output:"] + [f"line {i}" for i in range(40 - rwt.TAIL_LINES, 40)]) - long = rwt.timeout_tail("timed out after 120.0 s\n" + "x" * 5000 + "\nend\n") - self.assertEqual(long, "its last output:\n" + "x" * (rwt.TAIL_CHARS - 4) + "\nend") - - def test_slowest_lists_the_longest_tests_first(self): - self.assertEqual(rwt.slowest([]), "") - self.assertEqual(rwt.slowest([(0.4, "quick")]), "") - timings = [(2.0, "b"), (0.5, "quick"), (41.2, "a"), (9.0, "c")] - self.assertEqual(rwt.slowest(timings), "; slowest: a 41 s, c 9 s, b 2 s") - many = rwt.slowest([(float(i + 1), f"t{i}") for i in range(rwt.SLOWEST_LISTED + 3)]) - self.assertEqual(len(many.split(", ")), rwt.SLOWEST_LISTED) - self.assertTrue(many.startswith(f"; slowest: t{rwt.SLOWEST_LISTED + 2} {rwt.SLOWEST_LISTED + 3} s, "), many) - - def test_end_notice_names_the_slowest_tests(self): - # The log of a job is unreadable without a login: the notice is where a slow test that passed shows up. - entries = [ctest_entry("ok", self.command("ok.py")), ctest_entry("bad", self.command("bad.py"))] - with mock.patch.dict(os.environ, {"GITHUB_ACTIONS": "true"}), mock.patch.object(rwt, "SLOWEST_SECONDS", 0.0): - code, out, _ = self.run_main(entries, "--label", "wine-9.0") - self.assertEqual(code, 0) - self.assertRegex(self.workflow_commands(out)[-1], - r"^::notice::run_wine_tests: 1 passed, 1 failed, 0 skipped under wine-9\.0 in \d+ s; " - r"slowest: (ok|bad) \d+ s, (ok|bad) \d+ s$") - - def test_slow_test_notices_are_capped(self): - entries = [ctest_entry(f"ok{i}", self.command("ok.py")) for i in range(4)] - with mock.patch.dict(os.environ, {"GITHUB_ACTIONS": "true"}), \ - mock.patch.object(rwt, "SLOW_SECONDS", 0.0), mock.patch.object(rwt, "MAX_SLOW_NOTICES", 2): - code, out, _ = self.run_main(entries) - self.assertEqual(code, 0) - slow = [line for line in self.workflow_commands(out) if line.startswith("::notice::ok")] - self.assertEqual(len(slow), 2, out) - self.assertRegex(slow[0], r"^::notice::ok0: pass after \d+ s under Wine$") - - def test_workflow_command_data_is_escaped(self): - out = io.StringIO() - with mock.patch.dict(os.environ, {"GITHUB_ACTIONS": "true"}), contextlib.redirect_stdout(out): - rwt.annotate("warning", "50% done\r\nnext") - self.assertEqual(out.getvalue(), "::warning::50%25 done%0D%0Anext\n") - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/test_runner_calls_all_tests.py b/tests/test_runner_calls_all_tests.py deleted file mode 100644 index 4a0317f89..000000000 --- a/tests/test_runner_calls_all_tests.py +++ /dev/null @@ -1,129 +0,0 @@ -"""The __main__ runner of every standard-library test file actually runs its top-level test functions. - - python -I tests/test_runner_calls_all_tests.py - -tests/test_ci_registration.py sorts tests/test_*.py into CI jobs: a file without a PYTEST_FILE_MARKERS match but -with a __main__ guard runs in the standard-library loop as ``python -I tests/.py``, and pytest never -imports it. When such a runner forgets to call one of the file's top-level ``def test_*`` functions, those -checks run nowhere while the run still prints ok and exits 0 -- tests/test_cfg_structure.py carried a dead -test_depth() this way (PR #3122 fixes it), and tests/test_feature_scan.py had the sibling bug of swallowing its -only unrouted assert (PR #3051). This is the runner counterpart of tests/test_ci_registration.py: it reuses -that file's classification straight from the workflow (so it cannot drift from ci.yml) and fails for every -stdlib-mode file whose __main__ block neither names each top-level test function nor dispatches the whole set -through the ``globals()`` loop some runners use. Intentional non-calls live in RUNNER_SKIPS with their reason, -so a new dead test cannot hide behind a documented one. - -Only the tracked test files and the workflow are read; no game files, no build tools, no pytest. -""" -import ast -import os -import sys -import unittest - -sys.dont_write_bytecode = True -sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) -import test_ci_registration as registration # noqa: E402 - -# Top-level test functions a stdlib-mode runner deliberately does not call. Every entry needs a reason; a name -# neither listed here nor reached by the runner fails the check below. -RUNNER_SKIPS = { - "tests/test_cfg_structure.py": { - # One-line wrapper around _check_random_graphs(), which the runner already calls; listing it would run - # the 18,000-graph sweep twice. - "test_random_graphs", - # Dead on upstream/main at 16282101: its four S.depth() asserts run nowhere. PR #3122 adds the call; - # drop this entry once that merges and the runner calls test_depth() first. - "test_depth", - }, - "tests/test_feature_scan.py": { - # Its __main__ runner calls every test_* through run_tests([... for ... in globals().items() ...]), a - # comprehension dispatches_tests() does not follow, so each top-level test is listed here. - "test_feature_scan", - "test_short_signature", - "test_part_payload_outside_container_is_unreadable", - "test_bad_shaders_folder_is_one_line", - "test_out_inside_corpus_is_a_usage_error", - "test_duplicate_shader_names_keep_file_stages", - "test_v_perm_b32_selectors", - "test_typed_buffers_and_psv0", - "test_a_test_that_raises_fails_the_run_and_the_rest_still_run", - "test_a_failed_check_fails_only_its_own_test", - "test_out_via_directory_alias_into_corpus_is_a_usage_error", - "test_out_hard_link_to_carved_index_is_a_usage_error", - }, -} - - -def runner_block(tree): - """The module's real ``if __name__ == "__main__":`` node, or None (a bare mention satisfies the loop's grep).""" - for node in tree.body: - if isinstance(node, ast.If) and "__main__" in ast.dump(node.test) and "__name__" in ast.dump(node.test): - return node - return None - - -def dispatches_tests(block): - """True when the runner runs its tests through a loop over module globals and calls the loop variable.""" - for node in ast.walk(block): - if not isinstance(node, ast.For): - continue - targets = {t.id for t in ast.walk(node.target) if isinstance(t, ast.Name)} - if not any(isinstance(n, ast.Call) and isinstance(n.func, ast.Name) - and n.func.id in ("globals", "locals", "vars") for n in ast.walk(node)): - continue - if any(isinstance(n, ast.Call) and isinstance(n.func, ast.Name) and n.func.id in targets - for n in ast.walk(node)): - return True - return False - - -def uncalled_tests(source): - """Top-level test functions the file's __main__ runner never runs; None when there is no real guard.""" - tree = ast.parse(source) - block = runner_block(tree) - if block is None: - return None # test_ci_registration already fails files the loop runs without a guard - if dispatches_tests(block): - return [] - names = {n.id for n in ast.walk(block) if isinstance(n, ast.Name)} - names |= {n.attr for n in ast.walk(block) if isinstance(n, ast.Attribute)} - return [node.name for node in tree.body - if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)) - and node.name.startswith("test") and node.name not in names] - - -class RunnerCallsTestsTest(unittest.TestCase): - @classmethod - def setUpClass(cls): - cls.rules = registration.ci_rules(registration.ROOT) - cls.files = [f for f in registration.claimed_test_files(registration.ROOT) - if registration.job_of(registration.ROOT, f, cls.rules) == "stdlib"] - - def test_the_scan_sees_the_stdlib_files(self): - # A classification that collapses to nothing must not turn the check below into a silent no-op. - self.assertGreaterEqual(len(self.files), 100, - f"only {len(self.files)} stdlib-mode test files found: {self.files[:5]}") - self.assertIn("tests/test_cfg_structure.py", self.files) - - def test_every_stdlib_runner_calls_its_test_functions(self): - dead = [] - for rel in self.files: - missing = uncalled_tests(registration.read(registration.ROOT, rel)) - if not missing: # None (no guard) and [] (every test reached) both pass - continue - skips = RUNNER_SKIPS.get(rel, ()) - dead += [f" {rel}: {name}() is defined but its __main__ runner never calls it, so the python -I loop " - f"runs it nowhere and still prints ok; call it, or add it to RUNNER_SKIPS with a reason" - for name in missing if name not in skips] - self.assertEqual(dead, [], "dead top-level tests in stdlib-mode runners:\n" + "\n".join(dead)) - - def test_a_dropped_call_is_flagged(self): - # Bite check on a file this PR does not touch: losing one runner call must be reported, not absorbed. - source = registration.read(registration.ROOT, "tests/test_lane_masks.py") - self.assertEqual(uncalled_tests(source), []) - sabotaged = source.replace(" test_straight_line()", " # dropped for the bite check", 1) - self.assertEqual(uncalled_tests(sabotaged), ["test_straight_line"]) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/test_runtime_paths.py b/tests/test_runtime_paths.py deleted file mode 100644 index 5063a2cfb..000000000 --- a/tests/test_runtime_paths.py +++ /dev/null @@ -1,329 +0,0 @@ -"""The Runtime workflow's path filter still lists every file under tools/ that its jobs read. - - python -I tests/test_runtime_paths.py - -``.github/workflows/runtime.yml`` starts on the paths it lists, not on everything outside an ignore list -(BUILD-856): a change to a tool the runtime build never reads should not queue a Windows, Wine and llvmpipe run. -The price is that the list can fall behind. If ``tools/rdna2spirv.py`` starts importing a new ``tools/foo.py``, -that pull request still runs Runtime (it touches ``rdna2spirv.py``), but a later one that changes only -``foo.py`` would skip the GPU tests without anyone noticing. This test recomputes what the jobs read and fails -when an entry is missing: - -* the seeds are the code that runs during the jobs: the CMake files under ``runtime/`` and the workflow's - ``jobs:``, with ``#`` comments removed, and the Python under ``runtime/`` plus the scripts the workflow runs. - A ``tools/`` a CMake line or a job step spells out is needed; so is a ``tools`` module a Python seed - imports (the scripts and shader checks put ``tools/`` on ``sys.path``) and a ``tools/`` file it names in a - string, such as ``os.path.join(TOOLS, "rdna2spirv.py")``; -* from there, each needed tool's sibling imports, the ``tools/`` data files it names (``gfx10_formats.json`` is - loaded by name, which a ``.py``-only scan misses), modules it loads with ``importlib`` and ``tools/`` - subdirectories it names, to a fixed point. - -Comments, docstrings and the C++, shader and header sources are not read as dependencies: a ``tools/`` in -them says where a table or a test came from, not that the build runs it, and counting those would make every -such note a required entry. - -It also checks that the ``push`` and ``pull_request`` lists match, except an unfiltered push to ``main`` (no -``paths:``) which runs every commit via ``leonida-legacy-ci.yml``; pull requests still need the same complete path -list in that workflow's paths-filter block. No ``tools/`` entry names a -file that no longer exists. Listing more than the jobs need is allowed on purpose: an extra run costs one -queue slot, a missing entry loses the build for a tool the workflow reads. - -Only tracked sources and the workflow are read; no game files, no build tools, no PyYAML. -""" -import ast -import os -import re -import subprocess -import tempfile -import unittest - -ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) -WORKFLOW = ".github/workflows/runtime.yml" -LEGACY_WORKFLOW = ".github/workflows/leonida-legacy-ci.yml" - -# Entries that are needed for reasons a source scan cannot see: the build's own trees, the workflow, and the -# file that decides the line endings every checked-out source gets. -ALWAYS = ("runtime/**", "third_party/**", WORKFLOW, ".gitattributes") - -TOOLS_REF = re.compile(r"tools/([A-Za-z0-9_][A-Za-z0-9_.-]*)") -SCRIPT_REF = re.compile(r"scripts/[A-Za-z0-9_./-]+\.py") - - -def read(root, rel): - with open(os.path.join(root, rel), encoding="utf-8", errors="replace") as f: - return f.read() - - -def legacy_runtime_paths(root): - """Pull-request Runtime paths from leonida-legacy-ci.yml's paths-filter runtime: block.""" - path = os.path.join(root, LEGACY_WORKFLOW) - if not os.path.isfile(path): - return None - text = read(root, LEGACY_WORKFLOW) - block = re.search(r"filters:\s*\|\s*\n\s*runtime:\s*\n((?:\s+- .*\n)+)", text, re.M) - if not block: - return None - return [line.strip()[1:].strip().strip("\"'") for line in block.group(1).splitlines()] - - -def path_lists(root): - """{event: [paths]} for the events that filter on paths, exactly as the workflow spells them.""" - text = read(root, WORKFLOW) - legacy = os.path.isfile(os.path.join(root, LEGACY_WORKFLOW)) - lists = {} - for event in ("push", "pull_request"): - match = re.search(r"^ %s:\n((?: .*\n)+)" % event, text, re.M) - if not match: - if legacy and event == "push": - lists[event] = [] - continue - if legacy and event == "pull_request": - pr_paths = legacy_runtime_paths(root) - if pr_paths is None: - raise AssertionError(f"{LEGACY_WORKFLOW} has no runtime paths-filter block") - lists[event] = pr_paths - continue - raise AssertionError(f"{WORKFLOW} has no `{event}:` trigger the way this test expects it") - body = match.group(1) - paths = re.search(r"^ paths:\n((?: - .*\n)+)", body, re.M) - if not paths: - # An unfiltered push to main (no `paths:`) runs on every commit; pull requests still use a path list. - lists[event] = [] - continue - lists[event] = [line.strip()[1:].strip().strip("\"'") for line in paths.group(1).splitlines()] - return lists - - -def covered(path, patterns): - for pattern in patterns: - if pattern.endswith("/**"): - if path.startswith(pattern[:-2]): - return True - elif path == pattern: - return True - return False - - -def tracked(root, top): - result = subprocess.run(["git", "ls-files", "-z", "--", top], cwd=root, capture_output=True, text=True) - if result.returncode == 0 and result.stdout: - return [n for n in result.stdout.split("\0") if n] - names = [] # no git: walk, as tests/test_docs_links.py does - for base, dirs, files in os.walk(os.path.join(root, top)): - dirs[:] = [d for d in dirs if d not in (".git", "__pycache__", "build")] - for name in files: - names.append(os.path.relpath(os.path.join(base, name), root).replace(os.sep, "/")) - return names - - -def python_refs(source): - """(modules, strings) of a Python file: what it imports, including importlib.import_module("x") and - __import__("x"), and its string constants other than docstrings. Comments never reach the AST.""" - try: - tree = ast.parse(source) - except SyntaxError: - return set(), set() - docstrings = set() - for node in ast.walk(tree): - if isinstance(node, (ast.Module, ast.ClassDef, ast.FunctionDef, ast.AsyncFunctionDef)) and node.body: - first = node.body[0] - if isinstance(first, ast.Expr) and isinstance(first.value, ast.Constant): - docstrings.add(id(first.value)) - modules, strings = set(), set() - for node in ast.walk(tree): - if isinstance(node, ast.Import): - modules.update(alias.name.split(".")[0] for alias in node.names) - elif isinstance(node, ast.ImportFrom) and node.module and node.level == 0: - modules.add(node.module.split(".")[0]) - elif isinstance(node, ast.Call) and node.args and isinstance(node.args[0], ast.Constant): - func = node.func - name = func.attr if isinstance(func, ast.Attribute) else getattr(func, "id", "") - if name in ("import_module", "__import__") and isinstance(node.args[0].value, str): - modules.add(node.args[0].value.split(".")[0]) - if isinstance(node, ast.Constant) and isinstance(node.value, str) and id(node) not in docstrings: - strings.add(node.value) - return modules, strings - - -def strip_hash_comments(text): - """CMake and YAML without their # comments (a # inside a quoted string is rare enough in both to ignore).""" - return "\n".join(line.split("#", 1)[0] for line in text.splitlines()) - - -def needed(root): - """{tools entry: why} for everything under tools/ the Runtime jobs read.""" - tools = os.path.join(root, "tools") - entries = os.listdir(tools) - modules = {e[:-3] for e in entries if e.endswith(".py")} - data = {e for e in entries if os.path.isfile(os.path.join(tools, e)) and not e.endswith(".py")} - subdirs = {e for e in entries if os.path.isdir(os.path.join(tools, e)) and not e.startswith((".", "__"))} - - def entry(name): - name = name.rstrip(".") - if name in subdirs: - return f"tools/{name}/**" - if name in modules or name.endswith(".py") and name[:-3] in modules: - return f"tools/{name if name.endswith('.py') else name + '.py'}" - if name in data: - return f"tools/{name}" - return None - - def spelled(text): - for name in TOOLS_REF.findall(text): - first = name.split("/")[0] - yield first if first in subdirs else name - - def python_names(source, own_dir): - """tools/ entries a Python file imports or names in a string; own_dir's files shadow tools/.""" - imports, strings = python_refs(source) - names = {m + ".py" for m in imports - if m in modules and not (own_dir and os.path.exists(os.path.join(own_dir, m + ".py")))} - for s in strings: - names.update(spelled(s)) - base = s.rstrip("/").split("/")[-1] - if base in data or base in subdirs or base.endswith(".py") and base[:-3] in modules: - if not (own_dir and "/" not in s and os.path.exists(os.path.join(own_dir, base))): - names.add(base) - return names - - workflow = read(root, WORKFLOW) - # Only what the jobs run: the trigger's own list would make every listed entry "needed". - jobs = strip_hash_comments(workflow[workflow.find("\njobs:"):] if "\njobs:" in workflow else "") - found = {} - for name in spelled(jobs): - hit = entry(name) - if hit: - found.setdefault(hit, f"run by {WORKFLOW}") - runtime = tracked(root, "runtime") - cmake = [f for f in runtime if f.endswith(".cmake") or f.split("/")[-1] == "CMakeLists.txt"] - python = [f for f in runtime if f.endswith(".py")] + sorted(set(SCRIPT_REF.findall(jobs))) - for seed in cmake: - for name in spelled(strip_hash_comments(read(root, seed))): - hit = entry(name) - if hit: - found.setdefault(hit, f"named in {seed}") - for seed in python: - if os.path.isfile(os.path.join(root, seed)): - own = os.path.dirname(os.path.join(root, seed)) - for name in python_names(read(root, seed), own): - hit = entry(name) - if hit: - found.setdefault(hit, f"read by {seed}") - - queue = list(found) - while queue: - current = queue.pop() - if current.endswith("/**"): - sources = [f for f in tracked(root, current[:-3]) if f.endswith(".py")] - elif current.endswith(".py"): - sources = [current] - else: - continue - for source in sources: - for name in python_names(read(root, source), None): - hit = entry(name) - if hit and hit not in found: - found[hit] = f"via {source}" - queue.append(hit) - return found - - -def problems(root): - lists = path_lists(root) - issues = [] - events = sorted(lists) - for other in events[1:]: - if lists[other] != lists[events[0]]: - if lists.get("push") == [] and "push" in (events[0], other): - continue - issues.append(f"the `{events[0]}` and `{other}` path lists differ") - # When push has no path filter, only the pull_request list is checked for missing entries. - patterns = lists.get("pull_request") or lists.get("push") or lists[events[0]] - for must in ALWAYS: - if must not in patterns: - issues.append(f"{must}: missing (always needed)") - for script in sorted(set(SCRIPT_REF.findall(read(root, WORKFLOW)))): - if not covered(script, patterns): - issues.append(f"{script}: run by the workflow but not listed") - for path, why in sorted(needed(root).items()): - if not covered(path, patterns): - issues.append(f"{path}: missing ({why})") - for pattern in patterns: - if pattern.startswith("tools/") and not pattern.endswith("/**"): - if not os.path.exists(os.path.join(root, pattern)): - issues.append(f"{pattern}: listed but does not exist") - return issues - - -class RepositoryRuntimePathsTest(unittest.TestCase): - def test_the_scan_sees_the_repository(self): - found = needed(ROOT) - # The translator the GPU tests run through and the stub generator CMake runs at configure time. - self.assertIn("tools/rdna2spirv.py", found) - self.assertIn("tools/gen_d3d12_stubs.py", found) - - def test_every_tool_the_jobs_read_triggers_the_workflow(self): - issues = problems(ROOT) - self.assertFalse(issues, f"{WORKFLOW} path filter:\n" + "\n".join(f" {i}" for i in issues)) - - -class SyntheticTreeTest(unittest.TestCase): - """The scan flags what a path grep misses, on a tree built for the purpose.""" - - def build(self, tmp, listed): - def write(rel, text): - path = os.path.join(tmp, rel) - os.makedirs(os.path.dirname(path), exist_ok=True) - with open(path, "w", encoding="utf-8", newline="\n") as f: - f.write(text) - - paths = "".join(f' - "{p}"\n' for p in ALWAYS + ("scripts/**",) + tuple(listed)) - write(WORKFLOW, "name: Runtime\n\non:\n push:\n branches: [main]\n paths:\n" + paths + - " pull_request:\n paths:\n" + paths + "\njobs:\n x:\n steps:\n" - " - run: python3 -I scripts/run_gpu_tests.py\n") - write("runtime/CMakeLists.txt", "add_custom_command(COMMAND python tools/translator.py)\n") - write("scripts/run_gpu_tests.py", "import sys\nimport subgroup_info\n") - write("tools/translator.py", "import lanes\nimport json\nTABLE = 'formats.json'\nRUN = 'tools/runner.py'\n") - write("tools/runner.py", "X = 1\n") - write("tools/lanes.py", "import importlib\nM = importlib.import_module('late')\n") - write("tools/late.py", "ORACLE = 'oracle'\n") - write("tools/oracle/run.py", "import helper\n") - write("tools/helper.py", "X = 1\n") - write("tools/formats.json", "{}\n") - write("tools/subgroup_info.py", "X = 1\n") - write("tools/unrelated.py", "X = 1\n") - # Notes, not reads: none of these may make tools/unrelated.py a required entry. - write("runtime/src/table.h", "// generated by tools/unrelated.py\nconst char *k = \"tools/unrelated.py\";\n") - write("runtime/test/shaders/probe.asm", "; checked with tools/unrelated.py\n") - write("runtime/test/shaders/check.py", '"""Words from tools/unrelated.py."""\n# see tools/unrelated.py\n') - write("runtime/cmake/extra.cmake", "# tools/unrelated.py made this list\n") - - def test_a_complete_list_passes(self): - with tempfile.TemporaryDirectory() as tmp: - self.build(tmp, ["tools/translator.py", "tools/lanes.py", "tools/late.py", "tools/oracle/**", - "tools/helper.py", "tools/formats.json", "tools/subgroup_info.py", - "tools/runner.py"]) - self.assertEqual(problems(tmp), []) - self.assertNotIn("tools/unrelated.py", needed(tmp)) - - def test_each_kind_of_dependency_is_reported_when_missing(self): - with tempfile.TemporaryDirectory() as tmp: - self.build(tmp, ["tools/translator.py", "tools/gone.py"]) - issues = "\n".join(problems(tmp)) - for missing in ("tools/lanes.py", "tools/late.py", "tools/oracle/**", "tools/helper.py", - "tools/formats.json", "tools/subgroup_info.py", "tools/runner.py"): - self.assertIn(f"{missing}: missing", issues) - self.assertIn("tools/gone.py: listed but does not exist", issues) - - def test_lists_that_differ_are_reported(self): - with tempfile.TemporaryDirectory() as tmp: - self.build(tmp, []) - path = os.path.join(tmp, WORKFLOW) - text = read(tmp, WORKFLOW).replace(' paths:\n', ' paths:\n - "tools/extra.py"\n', 1) - with open(path, "w", encoding="utf-8", newline="\n") as f: - f.write(text) - self.assertTrue(any("path lists differ" in i for i in problems(tmp))) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/test_sad_diff.py b/tests/test_sad_diff.py deleted file mode 100644 index 8b97cf8c7..000000000 --- a/tests/test_sad_diff.py +++ /dev/null @@ -1,150 +0,0 @@ -"""tools/sad_diff.py: the SAD-family reference against hand-pinned ISA words, the source-kind sweep, -and a short seeded differential run. Standard library only; no GPU, no game files. - -The family is v_sad_u8, v_sad_hi_u8, v_sad_u16, v_sad_u32, v_msad_u8, v_qsad_pk_u16_u8 and -v_mqsad_pk_u16_u8 (docs/design.md's "Sum of absolute differences" and v_qsad contract rows). -""" -import os -import random -import re -import sys -import unittest - -sys.path.insert(0, os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "tools")) -import sad_diff as d # noqa: E402 - - -def run(*body): - """The reference's four exported words for a program.""" - return d.reference(list(body)) - - -class Reference(unittest.TestCase): - def test_plain_ops_pinned_words(self): - # 0x01020304 against 0xFF00FF00: |01-FF|+|02-00|+|03-FF|+|04-00| = 254+2+252+4 = 512 - # the op overwrites v8 (its own S0/S2), v11 is never written and reads 0 - self.assertEqual(run("v_mov_b32 v8, 0x01020304", "v_mov_b32 v9, 0xFF00FF00", - "v_mov_b32 v10, 5", "v_sad_u8 v8, v8, v9, v10"), - [517, 0xFF00FF00, 5, 0]) - self.assertEqual(run("v_mov_b32 v8, 0x01020304", "v_mov_b32 v9, 0xFF00FF00", - "v_mov_b32 v10, 5", "v_sad_hi_u8 v11, v8, v9, v10")[3], - 0x02000005) - # halves 0xFFFF vs 0x0001 twice: 65534 + 65534 = 0x1FFFC - self.assertEqual(run("v_mov_b32 v8, 0x0001FFFF", "v_mov_b32 v9, 0xFFFF0001", - "v_sad_u16 v11, v8, v9, 0")[3], 0x0001FFFC) - self.assertEqual(run("v_mov_b32 v8, 0", "v_mov_b32 v9, 0xFFFFFFFF", - "v_sad_u32 v11, v8, v9, 1")[3], 0) # wraps - self.assertEqual(run("v_mov_b32 v8, 0x01020304", "v_mov_b32 v9, 0xFF000000", - "v_mov_b32 v10, 5", "v_msad_u8 v11, v8, v9, v10")[3], - 259) # only the FF byte - - def test_quad_windows_slide_one_byte(self): - # S0 = 0x08070605_04030201 against S1 = 0x04030201: the four rolling windows give 0, 4, 8, 12; - # the result lands in v[10:11], overwriting the S1 seed that lived in v10 - self.assertEqual(run("v_mov_b32 v8, 0x04030201", "v_mov_b32 v9, 0x08070605", - "v_mov_b32 v10, 0x04030201", "v_qsad_pk_u16_u8 v[10:11], v[8:9], v10, 0"), - [0x04030201, 0x08070605, 0x00040000, 0x000C0008]) - # S1 = 0 masks every byte (each window adds nothing), so D = S2: v11 unwritten gives the - # accumulator's high word 0, and the result overwrites the v[10:11] it read - self.assertEqual(run("v_mov_b32 v8, 0xFFFFFFFF", "v_mov_b32 v9, 0xFFFFFFFF", - "v_mov_b32 v10, 5", - "v_mqsad_pk_u16_u8 v[10:11], v[8:9], 0, v[10:11]")[2], 5) - - def test_64bit_constant_rule(self): - # A hex literal as a 64-bit operand has a zero high word; an inline constant sign-extends. - lit = run("v_qsad_pk_u16_u8 v[8:9], 0xFFFF8000, 0, 0") - pair = run("v_mov_b32 v8, 0xFFFF8000", "v_qsad_pk_u16_u8 v[8:9], v[8:9], 0, 0") - self.assertEqual(lit, [0x027E027E, 0x00FF01FE, 0, 0]) # lanes 638, 638, 510, 255 - self.assertEqual(lit, pair) - self.assertEqual(run("v_qsad_pk_u16_u8 v[8:9], -16, 0, 0"), - [0x03FC03ED, 0x03FC03FC, 0, 0]) # lanes 1005, 1020, 1020, 1020 - - def test_hi_accumulator_wraps_at_32_bits(self): - # byte sum 512 (<< 16 = 0x02000000) plus 0xFFFF0000 wraps at 32 bits to 0x01FF0000 - self.assertEqual(run("v_mov_b32 v8, 0x01020304", "v_mov_b32 v9, 0xFF00FF00", - "v_sad_hi_u8 v11, v8, v9, 0xFFFF0000")[3], 0x01FF0000) - - -class Generator(unittest.TestCase): - def test_generation_is_deterministic(self): - self.assertEqual(d.program(random.Random(5), 6), d.program(random.Random(5), 6)) - self.assertNotEqual(d.program(random.Random(5), 6), d.program(random.Random(6), 6)) - - def test_ops_subset_is_respected(self): - rng = random.Random(1) - ops = ["v_sad_u8", "v_qsad_pk_u16_u8"] - for _ in range(30): - lines, used = d.program(rng, 4, ops) - self.assertTrue(set(used) <= set(ops)) - self.assertTrue(lines) # seeds and ops only, no exp/s_endpgm - # the sweep over the same subset enumerates only those ops, every kind combination - cases = d.sweep_ops(ops) - self.assertEqual(set(op for op, _ in cases), set(ops)) - self.assertEqual(len(cases), 125 + 80) - - def test_results_land_in_exported_registers(self): - # every op's destination (whole register or pair) is inside the exported v8..v11 - dst = re.compile(r"^v(_?\S+) ") - rng = random.Random(2) - for _ in range(30): - lines, _ = d.program(rng, 4) - for line in lines: - first = line.split()[0] - if first not in d.OP_FORMS: - continue - m = re.match(r"^v\[(\d+):(\d+)\]", line.split()[1]) - if m: - lo, hi = int(m.group(1)), int(m.group(2)) - self.assertTrue(8 <= lo and hi <= 11) - else: - self.assertGreaterEqual(int(line.split()[1].rstrip(",").lstrip("v")), 8) - self.assertLessEqual(int(line.split()[1].rstrip(",").lstrip("v")), 11) - - -class Translated(unittest.TestCase): - def test_harness_canaries(self): - self.assertTrue(d.self_test()) - - def test_short_seeded_run_matches(self): - counts, failure = d.run_suite(15, 3, 5) - self.assertEqual(failure, None) - self.assertEqual(counts["skip"], {}) - self.assertEqual(counts["pass"], 15) - - def test_sweep_covers_the_whole_kind_space(self): - # 5 kinds ^ 3 positions for a plain op, 4 x 5 x 4 for a quad op's 64-bit S0/S2 - counts, failure = d.run_sweep(4, ["v_sad_u8"]) - self.assertEqual((failure, counts["skip"]), (None, {})) - self.assertEqual(counts["pass"], 125) - counts, failure = d.run_sweep(4, ["v_qsad_pk_u16_u8"]) - self.assertEqual((failure, counts["skip"]), (None, {})) - self.assertEqual(counts["pass"], 80) - - def test_a_wrong_translation_is_caught(self): - lines = ["v_mov_b32 v8, 0x01020304", "v_mov_b32 v9, 0xFF00FF00", "v_mov_b32 v10, 5", - "v_sad_u8 v8, v8, v9, v10"] - real = d.translate_listing - try: - d.translate_listing = lambda l, n, t: [516] + real(l, n, t)[1:] - self.assertIn("expected 0x00000205, actual 0x00000204", d.check(lines)) - finally: - d.translate_listing = real - - -class EverythingSkipped(unittest.TestCase): - def test_a_run_where_every_program_was_skipped_is_not_a_success(self): - import contextlib - import io - from unittest import mock - - def refuse(lines, name, tmpdir): - raise d.rdna2spirv.Unsupported("unsupported form") - out = io.StringIO() - with (mock.patch.object(d, "translate_listing", refuse), mock.patch.object(sys, "argv", ["sad_diff.py", "--programs", "3"]), - contextlib.redirect_stdout(out)): - rc = d.main() - self.assertEqual(rc, 2, out.getvalue()) - self.assertIn("no program ran: every one was skipped", out.getvalue()) - -if __name__ == "__main__": - unittest.main() diff --git a/tests/test_salu_diff.py b/tests/test_salu_diff.py deleted file mode 100644 index 2126a607b..000000000 --- a/tests/test_salu_diff.py +++ /dev/null @@ -1,304 +0,0 @@ -"""tools/salu_diff.py: the scalar-ALU reference against hand-worked values, and a short seeded fuzz run (FUZZ-4). -Standard library only; no GPU.""" -import contextlib -import io -from pathlib import Path -import subprocess -import sys -import unittest -import unittest.mock - -TOOL = Path(__file__).resolve().parents[1] / "tools" / "salu_diff.py" -sys.path.insert(0, str(TOOL.parent)) -import salu_diff as d # noqa: E402 - - -def run(*body, regs=(4, 5, 6), seeds=None): - """The reference's four exported words for a program; seeds maps SGPR -> value.""" - lines = [f"s_mov_b32 s{r}, 0x{v:x}" for r, v in (seeds or {}).items()] + list(body) - return d.reference(lines + d.observe(list(regs))) - - -class Reference(unittest.TestCase): - def test_carries_borrows_and_signed_overflow(self): - self.assertEqual(run("s_add_u32 s4, -1, 1"), [0, 0, 0, 1]) # carry out - self.assertEqual(run("s_sub_u32 s4, 0, 1"), [0xFFFFFFFF, 0, 0, 1]) # borrow - self.assertEqual(run("s_add_i32 s4, 0x7fffffff, 1"), [0x80000000, 0, 0, 1]) # signed overflow - self.assertEqual(run("s_add_i32 s4, -1, 1"), [0, 0, 0, 0]) # no overflow - self.assertEqual(run("s_sub_u32 s4, 0, 1", "s_addc_u32 s5, 1, 1"), [0xFFFFFFFF, 3, 0, 0]) - self.assertEqual(run("s_sub_u32 s4, 0, 1", "s_subb_u32 s5, 1, 1"), [0xFFFFFFFF, 0xFFFFFFFF, 0, 1]) - - def test_min_max_scc_is_strict(self): - # SCC = 1 only when S0 is the one chosen; a tie picks S1 (SHADER-40). - self.assertEqual(run("s_min_i32 s4, 5, 5")[3], 0) - self.assertEqual(run("s_min_i32 s4, -1, 1")[::3], [0xFFFFFFFF, 1]) - self.assertEqual(run("s_min_u32 s4, -1, 1")[::3], [1, 0]) - self.assertEqual(run("s_max_i32 s4, 7, 7")[3], 0) - - def test_bit_scans_and_counts(self): - self.assertEqual(run("s_ff0_i32_b32 s4, 3", "s_ff1_i32_b32 s5, 0x100", "s_ff1_i32_b32 s6, 0")[:3], - [2, 8, 0xFFFFFFFF]) - self.assertEqual(run("s_flbit_i32_b32 s4, 1", "s_flbit_i32_b32 s5, 0", "s_bcnt0_i32_b32 s6, 0xff")[:3], - [31, 0xFFFFFFFF, 24]) - self.assertEqual(run("s_ff1_i32_b64 s4, s[6:7]", seeds={6: 0, 7: 2})[0], 33) - - def test_field_ops(self): - self.assertEqual(run("s_bfe_u32 s4, 0xf0, 0x40004")[0], 0xF) - self.assertEqual(run("s_bfe_i32 s4, 0xf0, 0x40004")[0], 0xFFFFFFFF) - self.assertEqual(run("s_bfm_b32 s4, 4, 8")[0], 0xF00) - # a field past bit 31 stops there (gfx1150 hardware, LLVM constantFoldBFE): width 127 at offset 28 is 4 bits - self.assertEqual(run("s_bfe_i32 s4, 0xd2f90159, 0x7f001c")[0], 0xFFFFFFFD) - self.assertEqual(run("s_bfe_u32 s4, 0xd2f90159, 0x7f001c")[0], 0xD) - self.assertEqual(run("s_bitset1_b32 s4, 3", seeds={4: 0x10})[0], 0x18) - - def test_sopk_extends_its_immediate(self): - self.assertEqual(run("s_movk_i32 s4, 0x8000")[0], 0xFFFF8000) - self.assertEqual(run("s_cmpk_lt_u32 s4, 0x8000", seeds={4: 5})[3], 1) # zero-extended - self.assertEqual(run("s_cmpk_lt_i32 s4, 0x8000", seeds={4: 5})[3], 0) # -32768 - self.assertEqual(run("s_addk_i32 s4, 1", seeds={4: 0x7FFFFFFF}), [0x80000000, 0, 0, 1]) - - def test_scc_survives_ops_that_do_not_write_it(self): - self.assertEqual(run("s_cmp_eq_u32 1, 1", "s_mov_b32 s4, 0", "s_bfm_b32 s5, 1, 1")[3], 1) - - def test_cmov_selects_on_scc_and_keeps_it(self): - seeds = {4: 0x11111111, 5: 0x22222222, 6: 0x33333333, 7: 0x44444444} - for scc in (0, 1): - with self.subTest(scc=scc): - cmp = f"s_cmp_eq_u32 {scc}, 1" - self.assertEqual(run(cmp, "s_cmov_b32 s4, s5", seeds=seeds)[::3], [(0x11111111, 0x22222222)[scc], scc]) - self.assertEqual(run(cmp, "s_cmovk_i32 s4, 0x8000", seeds=seeds)[::3], [(0x11111111, 0xFFFF8000)[scc], scc]) - self.assertEqual(run(cmp, "s_cmovk_i32 s4, 0x7fff", seeds=seeds)[0], (0x11111111, 0x7FFF)[scc]) - self.assertEqual(run(cmp, "s_cmov_b64 s[4:5], s[6:7]", regs=(4, 5, 8), seeds=seeds), - [(0x11111111, 0x33333333)[scc], (0x22222222, 0x44444444)[scc], 0, scc]) - for op in ("s_cmov_b32", "s_cmovk_i32", "s_cmov_b64"): - self.assertFalse(d.writes_scc(op), op) - self.assertIn(op, d.SCC_CONSUMERS) - - def test_movrels_reads_s0_plus_m0(self): - seeds = {r: 0x100 + r for r in d.REGS} - self.assertEqual(run("s_mov_b32 m0, 3", "s_movrels_b32 s4, s5", seeds=seeds)[0], 0x108) - self.assertEqual(run("s_mov_b32 m0, 0", "s_movrels_b32 s4, s5", seeds=seeds)[0], 0x105) - self.assertEqual(run("s_mov_b32 m0, 6", "s_movrels_b64 s[4:5], s[8:9]", seeds=seeds)[:2], [0x10E, 0x10F]) - # D overlapping the source: both words are read before either is written - self.assertEqual(run("s_mov_b32 m0, 2", "s_movrels_b64 s[4:5], s[4:5]", seeds=seeds)[:2], [0x106, 0x107]) - with self.assertRaises(d.RefError): # past the seeded SGPRs - run("s_mov_b32 m0, 7", "s_movrels_b32 s4, s19", seeds=seeds) - - def test_absdiff_mul_hi_and_lshl_add(self): - self.assertEqual(run("s_absdiff_i32 s4, 0x7FFFFFFF, 0x80000000")[::3], [1, 1]) - self.assertEqual(run("s_absdiff_i32 s4, 5, 5")[::3], [0, 0]) - self.assertEqual(run("s_mul_hi_i32 s4, -1, 1")[::3], [0xFFFFFFFF, 0]) - self.assertEqual(run("s_cmp_eq_u32 1, 1", "s_mul_hi_i32 s4, -1, 1")[::3], [0xFFFFFFFF, 1]) - self.assertEqual(run("s_lshl1_add_u32 s4, 0x80000000, 0")[::3], [0, 1]) - self.assertEqual(run("s_lshl2_add_u32 s4, 3, 4")[::3], [16, 0]) - self.assertEqual(run("s_lshl4_add_u32 s4, 0x0FFFFFFF, 0x10")[::3], [0, 1]) - - def test_sext_flbit_and_pack(self): - self.assertEqual(run("s_sext_i32_i8 s4, 0x80")[0], 0xFFFFFF80) - self.assertEqual(run("s_sext_i32_i8 s4, 0x7F")[0], 0x7F) - self.assertEqual(run("s_sext_i32_i16 s4, 0x8000")[0], 0xFFFF8000) - self.assertEqual(run("s_sext_i32_i16 s4, 0x7FFF")[0], 0x7FFF) - self.assertEqual(run("s_flbit_i32 s4, 0")[0], 0xFFFFFFFF) - self.assertEqual(run("s_flbit_i32 s4, 1")[0], 31) - self.assertEqual(run("s_flbit_i32 s4, 0x80000000")[0], 1) - self.assertEqual(run("s_pack_ll_b32_b16 s4, 0x12345678, 0xABCDEF01")[0], 0xEF015678) - self.assertEqual(run("s_pack_lh_b32_b16 s4, 0x12345678, 0xABCDEF01")[0], 0xABCD5678) - self.assertEqual(run("s_pack_hh_b32_b16 s4, 0x12345678, 0xABCDEF01")[0], 0xABCD1234) - - -class Translated(unittest.TestCase): - def test_harness_canaries(self): - self.assertTrue(d.self_test()) - - def test_short_seeded_run_matches(self): - # 32-bit data ops only: 64-bit ones and s_wqm_b32 follow the translator's lane-mask model. s_bfe_* - # control words stay inside offset + width <= 32 by default (past it is an open hardware question in - # #156). s_ff0/ff1_i32_b32 wait for SHADER-46 (#349): main reads a constant source as a lane mask. - ops = sorted(o for o, (form, _) in d.OPS.items() - if "64" not in form and o not in ("s_wqm_b32", "s_ff0_i32_b32", "s_ff1_i32_b32")) - counts, failures = d.run_suite(60, 4, 5, ops) - self.assertEqual(failures, [], failures[:1]) - self.assertEqual(counts["skip"], {}) - self.assertEqual(counts["pass"], 60) - - def test_bfe_control_words_stay_in_range_by_default(self): - rng = d.random.Random(1) - for _ in range(300): - ctl = int(d.emit(rng, "s_bfe_i32").rsplit(", ", 1)[1], 0) - self.assertLessEqual((ctl & 31) + (ctl >> 16 & 0x7F), 32) - - def test_min_max_ties_match_since_shader_40(self): - # #332 is on main: s_min/max ties leave SCC 0 in the translator too. - counts, failures = d.run_suite(40, 5, 3, ["s_max_i32", "s_max_u32", "s_min_i32", "s_min_u32"]) - self.assertEqual((counts["pass"], failures), (40, [])) - - def test_a_wrong_translation_is_caught(self): - lines = ["s_mov_b32 s4, 5", "s_min_i32 s5, s4, s4"] + d.observe([4, 5, 6]) - want = d.reference(lines) - real = d.translated - try: - d.translated = lambda _lines: want[:3] + [want[3] ^ 1] - self.assertIn("word 3 (SCC)", d.check(lines)) - d.translated = lambda _lines: [want[0] ^ 1] + want[1:] - self.assertIn("word 0 (s4)", d.check(lines)) - finally: - d.translated = real - - -class Generator(unittest.TestCase): - def test_movrels_stays_inside_the_seeded_sgprs(self): - rng = d.random.Random(3) - for m0 in range(8): - for _ in range(200): - for op in ("s_movrels_b32", "s_movrels_b64"): - line = d.emit(rng, op, m0) - name, rest = line.split(" ", 1) - src = rest.split(", ")[1] - if name == "s_movrels_b64": - self.assertEqual(m0 % 2, 0, line) # no odd-aligned pair - lo = int(src[2:src.index(":")]) - self.assertLessEqual(lo + m0 + 1, d.REGS[-1], line) - else: - self.assertLessEqual(int(src[1:]) + m0, d.REGS[-1], line) - - def test_m0_is_set_only_with_movrels_and_survives_shrinking(self): - plain = d.generate(d.random.Random(4), 3, ["s_add_u32"]) - self.assertFalse(any(line.startswith("s_mov_b32 m0") for line in plain)) - lines = d.generate(d.random.Random(4), 3, ["s_movrels_b32"]) - self.assertTrue(lines[len(d.REGS)].startswith("s_mov_b32 m0, ")) - self.assertEqual(d.shrink(lines, check_fn=lambda _l: "mismatch")[:len(d.REGS) + 1], lines[:len(d.REGS) + 1]) - - def test_selects_and_relative_reads_match_the_translator(self): - seeds = [f"s_mov_b32 s{r}, 0x{0x100 + r:x}" for r in d.REGS] - for body in (["s_mov_b32 m0, 2", "s_movrels_b64 s[4:5], s[8:9]"], - ["s_mov_b32 m0, 3", "s_movrels_b32 s4, s5"], - ["s_cmp_eq_u32 0, 1", "s_cmov_b32 s4, s5", "s_cmovk_i32 s6, -2"], - ["s_cmp_eq_u32 1, 1", "s_cmov_b64 s[4:5], s[8:9]", "s_cmovk_i32 s6, 0x8000"]): - with self.subTest(body=body): - self.assertIsNone(d.check(seeds + body + d.observe([4, 5, 6]))) - ops = ["s_cmov_b32", "s_cmovk_i32", "s_cmov_b64", "s_movrels_b32", "s_movrels_b64", "s_cmp_lt_i32", - "s_add_u32", "s_mov_b64", "s_lshl_b64"] - for branches in (False, True): - with self.subTest(branches=branches): - counts, failures = d.run_suite(60, 6, 6, ops, branches=branches) - self.assertEqual((counts["pass"], counts["skip"], failures), (60, {}, [])) - - def test_two_source_forms_share_one_literal_word(self) -> None: - for op in ("s_add_u32", "s_bfm_b64", "s_cmp_eq_u32"): - for operands in (("0x12345", "0x23456"), ("0x12345", "0x12345")): - with self.subTest(op=op, operands=operands): - with unittest.mock.patch.object(d, "_src32", side_effect=operands): - line = d.emit(d.random.Random(2), op) - sources = line.split(" ", 1)[1].split(", ")[-2:] - literals = [source for source in sources if source.startswith("0x")] - self.assertEqual(len(set(literals)), 1, line) - self.assertEqual(len(literals), 2 if operands[0] == operands[1] else 1, line) - - -class Branches(unittest.TestCase): - """--branches: SCC consumer chains and s_cbranch_scc0/1 forward over 1..3 instructions.""" - - def test_reference_takes_the_branch_on_the_right_scc(self): - body = ("s_cmp_eq_u32 1, 1", "s_cbranch_scc1 +2", "s_mov_b32 s4, 7", "s_mov_b32 s5, 8", "s_mov_b32 s6, 9") - self.assertEqual(run(*body), [0, 0, 9, 1]) # taken: s4, s5 skipped - self.assertEqual(run(*(b.replace("scc1", "scc0") for b in body)), [7, 8, 9, 1]) # not taken - self.assertEqual(run("s_cmp_eq_u32 0, 1", "s_cbranch_scc0 +1", "s_mov_b32 s4, 7")[::3], [0, 0]) - - def test_a_consumer_chain_carries_scc(self): - # 0 - 1 borrows; s_addc adds it in and carries out of 0xffffffff + 0 + 1; s_cselect keeps that SCC - self.assertEqual(run("s_sub_u32 s4, 0, 1", "s_addc_u32 s5, s4, 0", "s_cselect_b32 s6, 5, 6"), [0xFFFFFFFF, 0, 5, 1]) - - def test_listing_offsets_count_literals(self): - lines = ["s_cbranch_scc0 +3", "s_add_u32 s4, s5, 0x12345", "s_movk_i32 s4, 0x8000", "s_cmp_lt_u32 s4, -1"] - self.assertEqual(d.listing(lines)[0], ("s_cbranch_scc0 4", 4)) # 8 + 4 + 4 bytes - self.assertEqual([n for _, n in d.listing(lines)], [4, 8, 4, 4]) - - def test_shrinking_keeps_the_skipped_range_consistent(self): - body = ["s_cbranch_scc1 +2", "s_mov_b32 s4, 1", "s_mov_b32 s5, 2", "s_mov_b32 s6, 3"] - self.assertEqual(d.drop(body, 1), ["s_cbranch_scc1 +1", "s_mov_b32 s5, 2", "s_mov_b32 s6, 3"]) - self.assertEqual(d.drop(body, 3), body[:3]) - - def test_every_producer_meets_every_consumer_and_both_branches(self): - ops = sorted(o for o in d.OPS if o not in d.LANE_MASK_OPS) - producers = {o for o in ops if d.writes_scc(o)} - seen = set() - rng = d.random.Random(1) - for _ in range(5000): # seed 1 meets the last of the 560 pairs at program 3,548 - lines = d.generate(rng, rng.randrange(1, 7), ops, branches=True) - for prev, nxt in zip(lines, lines[1:]): - op, after = prev.split()[0], nxt.split()[0] - if op in producers and (after in d.SCC_CONSUMERS or after in d.SCC_BRANCHES): - seen.add((op, after)) - want = {(p, c) for p in producers for c in d.SCC_CONSUMERS + d.SCC_BRANCHES} - self.assertEqual(want - seen, set()) - - def test_short_seeded_run_matches(self): - ops = sorted(o for o in d.OPS if o not in d.LANE_MASK_OPS) - counts, failures = d.run_suite(60, 3, 5, ops, branches=True) - self.assertEqual((counts["pass"], counts["skip"], failures), (60, {}, [])) - - def test_a_misplaced_branch_target_is_caught(self): - # One dword too far: the instruction after the skipped range is skipped too. - lines = (["s_mov_b32 s4, 1", "s_cmp_eq_u32 s4, s4", "s_cbranch_scc1 +1", "s_mov_b32 s5, 0x12345678", - "s_mov_b32 s6, 3"] + d.observe([4, 5, 6])) - self.assertIsNone(d.check(lines)) - real = d.listing - try: - d.listing = lambda ls: [(f"{t.rsplit(' ', 1)[0]} {int(t.rsplit(' ', 1)[1]) + 1}" - if t.startswith("s_cbranch") else t, n) for t, n in real(ls)] - self.assertIn("word 2 (s6)", d.check(lines)) - finally: - d.listing = real - - -class CliOps(unittest.TestCase): - def test_ops_whitespace_and_duplicates_are_normalized(self): - cases = [ - ("s_add_u32, s_sub_u32", ["s_add_u32", "s_sub_u32"]), - ("s_add_u32,s_add_u32", ["s_add_u32"]), - ] - for raw, expected in cases: - with unittest.mock.patch.object(d, "run_suite", wraps=d.run_suite) as spy: - out = io.StringIO() - with contextlib.redirect_stdout(out): - rc = d.main(["--programs", "2", "--max-ops", "2", "--ops", raw]) - self.assertEqual(rc, 0, out.getvalue()) - spy.assert_called_once() - self.assertEqual(spy.call_args.args[3], expected) - - def test_ops_unknown_and_empty_tokens_report_on_stderr(self): - cases = [ - ("nope", "unknown ops: nope"), - ("s_add_u32,", "--ops must be a comma-separated list of opcodes"), - (",", "--ops must be a comma-separated list of opcodes"), - (" , ", "--ops must be a comma-separated list of opcodes"), - ("", "--ops must be a comma-separated list of opcodes"), - ] - for raw, message in cases: - proc = subprocess.run( - [sys.executable, "-I", str(TOOL), "--programs", "1", "--ops", raw], - capture_output=True, text=True, encoding="utf-8", errors="replace", - ) - self.assertEqual(proc.returncode, 2, proc.stdout + proc.stderr) - self.assertIn(message, proc.stderr) - self.assertEqual(proc.stdout, "") - self.assertNotIn("Traceback", proc.stderr) - - -class EverythingSkipped(unittest.TestCase): - def test_a_run_where_every_program_was_skipped_is_not_a_success(self): - import contextlib - import io - from unittest import mock - - def refuse(lines, *args): - raise d.Skip("unsupported form") - out = io.StringIO() - with mock.patch.object(d, "translated", refuse), contextlib.redirect_stdout(out): - rc = d.main(["--programs", "3", "--seed", "1"]) - self.assertEqual(rc, 2, out.getvalue()) - self.assertIn("no program ran: every one was skipped", out.getvalue()) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/test_sampler_lod_probe.py b/tests/test_sampler_lod_probe.py deleted file mode 100644 index a3174ddd3..000000000 --- a/tests/test_sampler_lod_probe.py +++ /dev/null @@ -1,86 +0,0 @@ -"""tools/sampler_lod_probe.py without a GPU: the descriptor fields sit where the runtime reads them, the measured model -gives the gfx1036 levels, and the kernel builds. - - python -I tests/test_sampler_lod_probe.py -""" -import os -import sys -import unittest - -ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) -sys.path.insert(0, os.path.join(ROOT, "tools")) -sys.path.insert(0, os.path.join(ROOT, "tools", "hw_oracle")) - -import sampler_lod_probe as p # noqa: E402 - -# What gfx1036 (Radeon iGPU, AMD 26.10.1) read for every row, wave32 and wave64 alike: -# tools/sampler_lod_probe.py --oracle hw. All 43 are pinned, so a change to rdna2_level shows without a GPU. -MEASURED = { - "calib_lod0": 0, "calib_lod1": 1, "calib_lod2": 2, "calib_lod3": 3, "calib_lod4": 4, "calib_lod5": 5, - "calib_lod6": 6, "lz": 0, "s_min2_l0": 2, "s_min2_lz": 2, "s_max1_l4": 1, "s_max0_l3": 0, "s_bias+2_l1": 3, - "s_bias+2_lz": 2, "s_bias-1_l3": 2, "s_bias+2_max3_l3": 3, "s_bias+0.5_l1": 2, "l1.25": 1, "l1.5": 2, - "l1.75": 2, "mipnone_l3": 0, "mipnone_min2_l0": 0, "mipnone_t_min3_l0": 3, "mipnone_t_min2.25": 2, - "mipnone_t_min2.5": 2, "mipnone_base1_tmin3": 3, "t_min3_l1": 3, "t_min3_lz": 3, "t_min3_l5": 5, - "t_min2.5_l0": 3, "t_min2.5_l2.6": 3, "t_min2.25_l0": 2, "t_min2.75_l0": 3, "t_min2.25_lz": 2, "l0.5": 1, - "l2.5": 3, "s_min1.5_l0": 2, "s_max1.5_l4": 2, "l1.49": 1, "base1_l0": 1, "base1_s_min1_l0": 2, - "base1_t_min2_l0": 2, "base1_t_min2_lz": 2, -} - - -def field(word, lo, width): - return (word >> lo) & ((1 << width) - 1) - - -class FieldsTest(unittest.TestCase): - def test_sampler_words_match_check_py(self): - sys.path.insert(0, os.path.join(ROOT, "runtime", "test", "shaders")) - import check - for s in ((1, 0.0, 15.0, 0.0), (1, 2.0, 15.0, 0.0), (1, 0.0, 1.5, -1.0), (0, 1.0, 15.0, 0.5)): - with self.subTest(s=s): - self.assertEqual(p.sampler_words(s), list(check.ssharp_words(s[0], s[1], s[2], s[3]))) - - def test_image_mip_fields(self): - w = p.image_words("gfx1036", (1, 2.5)) - self.assertEqual(field(w[1], 8, 12), round(2.5 * 256)) # MIN_LOD, 4.8 fixed - self.assertEqual(field(w[3], 12, 4), 1) # BASE_LEVEL - self.assertEqual(field(w[3], 16, 4), p.LEVELS - 1) # LAST_LEVEL - self.assertEqual(field(w[5], 4, 4), p.LEVELS - 1) # MAX_MIP - self.assertEqual(field(w[3], 28, 4), 9) # SQ_RSRC_IMG_2D - - def test_gfx11_is_refused(self): - with self.assertRaises(ValueError): - p.image_words("gfx1150", (0, 0.0)) - - -class RowsTest(unittest.TestCase): - def test_names_are_unique_and_calibration_comes_first(self): - rows = p.rows() - self.assertEqual(len({r[0] for r in rows}), len(rows)) - self.assertEqual([r[0] for r in rows[:p.LEVELS]], [f"calib_lod{n}" for n in range(p.LEVELS)]) - - def test_model_gives_the_measured_levels(self): - by_name = {r[0]: r for r in p.rows()} - self.assertEqual(set(MEASURED), set(by_name), "every row is pinned to its measured level") - for name, level in MEASURED.items(): - _n, instr, lod, s, t = by_name[name] - with self.subTest(name): - self.assertEqual(p.rdna2_level(instr, lod, s, t), level) - - def test_rows_tell_the_hardware_from_vulkan(self): - differ = [r[0] for r in p.rows() if p.rdna2_level(*r[1:]) != p.vulkan_level(*r[1:])] - self.assertIn("l1.5", differ) # an exact .5 rounds up on the hardware, down on Vulkan - self.assertIn("t_min2.5_l0", differ) # the T#'s MIN_LOD clamps the fractional LOD, not the level - self.assertNotIn("l1.49", differ) - - def test_kernel_builds_for_rdna2(self): - rows = p.rows() - lines = p.kernel("gfx1036", rows) - text = "\n".join(lines) - self.assertEqual(sum("image_sample_l " in ln for ln in lines), sum(r[1] == "l" for r in rows)) - self.assertEqual(sum("image_sample_lz " in ln for ln in lines), sum(r[1] == "lz" for r in rows)) - self.assertEqual(text.count("global_store_b32"), len(rows)) - self.assertTrue(lines[-1].startswith(" .long")) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/test_sampler_source_census.py b/tests/test_sampler_source_census.py deleted file mode 100644 index 7e744ec2e..000000000 --- a/tests/test_sampler_source_census.py +++ /dev/null @@ -1,595 +0,0 @@ -"""tools/sampler_source_census.py on hand-written listings and containers (no game files, no GPU).""" -import contextlib -import io -import json -import os -import struct -import subprocess -import sys -import tempfile -import unittest - -ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) -sys.path.insert(0, os.path.join(ROOT, "tools")) - -import sampler_source_census as ssc # noqa: E402 - -TOOL = os.path.join(ROOT, "tools", "sampler_source_census.py") -SFI0_SMP = 1 << 26 -SAMPLE = ("image_sample v[0:3], v[4:5], s[20:27], s[28:31] dmask:0xf dim:SQ_RSRC_IMG_2D", 8) -END = ("s_endpgm", 4) - - -def enc(n): - """A placeholder `; encoding:` of n bytes: the census only needs the length (for code offsets).""" - return "; encoding: [" + ",".join(["0x00"] * n) + "]" - - -def listing(name, lines): - """lines: (text, bytes) pairs -> a tab-indented listing as tools/shader_disasm.py writes it.""" - end = 0x100 + sum(n for _, n in lines) - body = "".join(f"\t{text:<40}{enc(n)}\n" for text, n in lines) - return f"; {name}.fssm code 0x100..0x{end:x}\n{body}" - - -def dxbc(flags): - """A DXBC container holding only an SFI0 part with the given feature flags.""" - sfi0 = b"SFI0" + struct.pack("/shaders/dxbc folder: carve index, containers, FSSM headers and disasm listings.""" - - def __init__(self): - self.tmp = tempfile.TemporaryDirectory() - self.root = self.tmp.name - self.disasm = os.path.join(self.root, "disasm") - os.makedirs(self.disasm) - os.makedirs(os.path.join(self.root, "fssm")) - self.index = [] - - def add(self, name, stage, lines, flags=0, rsrc2=None, text=None, blob=None): - self.index.append({"file": name + ".dxbc", "stage": stage}) - if flags is not None: - with open(os.path.join(self.root, name + ".dxbc"), "wb") as f: - f.write(dxbc(flags)) - with open(os.path.join(self.disasm, name + ".s"), "w", encoding="utf-8", newline="\n") as f: - f.write(listing(name, lines) if text is None else text) - if rsrc2 is not None or blob is not None: - with open(os.path.join(self.root, "fssm", name + ".fssm"), "wb") as f: - f.write(blob if blob is not None else bytes(0x138) + struct.pack("GadgetBlock")) - f.write(b"\0Sprocket\0Count\0Sprocket\0Count\0") - - def tearDown(self): - self.tmp.cleanup() - - def test_collect_counts_index_and_json_keys(self): - keys = sk.collect_keys([self.jsav]) - # 2 block ids + group + 4 fields - self.assertEqual(len(keys), 7) - self.assertEqual(keys[sk.joaat(b"WidgetBlock")], 2) # index entry + inner key - self.assertIn("7 distinct keys", run(["collect", self.jsav])) - - def test_collect_from_extracted_folder(self): - out = os.path.join(self.dir, "x") - with contextlib.redirect_stdout(io.StringIO()): - saves.extract(self.jsav, out) - self.assertEqual(set(sk.collect_keys([out])), set(sk.collect_keys([self.jsav]))) - - def test_directory_scan_reads_jsav_files(self): - # #844: a folder of .jsav saves counts the same as naming each file - with open(self.jsav, "rb") as f: - data = f.read() - folder = os.path.join(self.dir, "saves") - os.makedirs(folder) - for name in ("a.jsav", "b.ASAV", "c.bin", "d"): - with open(os.path.join(folder, name), "wb") as f: - f.write(data) - one = sk.collect_keys([self.jsav]) - self.assertEqual(sk.collect_keys([folder]), collections.Counter({k: 4 * n for k, n in one.items()})) - - def test_unlistable_subfolder_is_a_clean_error_not_a_silent_skip(self): - # os.walk skips a directory it cannot list unless onerror raises; the collection used to report - # the remaining saves and exit 0, hiding the incomplete directory. - with open(self.jsav, "rb") as f: - data = f.read() - folder = os.path.join(self.dir, "saves_sub") - os.makedirs(folder) - with open(os.path.join(folder, "a.jsav"), "wb") as f: - f.write(data) - sub = os.path.join(folder, "sub") - os.makedirs(sub) - with open(os.path.join(sub, "b.jsav"), "wb") as f: - f.write(data) - os.chmod(sub, 0o000) - try: - try: - os.listdir(sub) - self.skipTest("the sub-folder is still listable (running as root, or Windows)") - except OSError: - pass - err = io.StringIO() - with contextlib.redirect_stderr(err), contextlib.redirect_stdout(io.StringIO()): - rc = sk.main(["collect", folder]) - self.assertEqual(rc, 1) - self.assertIn("error:", err.getvalue()) - self.assertIn(sub, err.getvalue()) - self.assertNotIn("Traceback", err.getvalue()) - finally: - os.chmod(sub, 0o755) - - def test_unlistable_subfolder_is_a_clean_error_when_chmod_is_not_enough(self): - # The chmod case above self-skips on Windows and as root, and CI only runs this file on - # windows-latest, so the guard went unexercised there. Forcing os.scandir to raise for one - # folder gives the same PermissionError os.walk hits for real, on every platform. - with open(self.jsav, "rb") as f: - data = f.read() - folder = os.path.join(self.dir, "saves_scandir") - os.makedirs(folder) - with open(os.path.join(folder, "a.jsav"), "wb") as f: - f.write(data) - sub = os.path.join(folder, "sub") - os.makedirs(sub) - with open(os.path.join(sub, "b.jsav"), "wb") as f: - f.write(data) - real_scandir = os.scandir - locked = os.path.normcase(os.path.abspath(sub)) - - def scandir(path, *args, **kwargs): - if os.path.normcase(os.path.abspath(str(path))) == locked: - raise PermissionError(13, "Access is denied", str(path)) - return real_scandir(path, *args, **kwargs) - - err = io.StringIO() - with mock.patch.object(sk.os, "scandir", scandir): - with contextlib.redirect_stderr(err), contextlib.redirect_stdout(io.StringIO()): - rc = sk.main(["collect", folder]) - self.assertEqual(rc, 1, err.getvalue()) - self.assertIn("error:", err.getvalue()) - self.assertIn(sub, err.getvalue()) - self.assertNotIn("Traceback", err.getvalue()) - - def test_resolve_counts_per_family(self): - res = os.path.join(self.dir, "res.json") - text = run(["resolve", self.jsav, "--dict", self.dict, "--out", res]) - line = {ln.split()[0]: int(ln.split()[1]) for ln in text.splitlines()[1:] if ln.startswith(" ") - and ln.split()[1].isdigit()} - self.assertEqual(line["joaat"], 5) # WidgetBlock, GadgetBlock (zlib), Colour, spinRate, CodeGroup - self.assertEqual(line["joaat_lower"], 0) - self.assertEqual(line["fnv1a"], 0) - with open(res, encoding="utf-8") as f: - got = json.load(f) - self.assertEqual(got["%08x" % sk.joaat(b"GadgetBlock")], ["GadgetBlock"]) - self.assertNotIn("%08x" % sk.joaat(b"MysteryField"), got) - - def resolve_cli(self, *args): - tool = os.path.join(ROOT, "tools", "save_keys.py") - return subprocess.run([sys.executable, "-I", tool, "resolve", *args], cwd=ROOT, capture_output=True, text=True) - - def test_out_naming_an_input_is_refused(self): - # --out must not replace the user's dictionary, a save, a file found in an input folder, or a hard link to one - folder = os.path.join(self.dir, "saves") - os.makedirs(folder) - inside = os.path.join(folder, "more.json") - with open(inside, "w", encoding="utf-8") as f: - f.write("{}") - cases = [(self.dict, [self.jsav]), (self.jsav, [self.jsav]), (inside, [folder])] - link = os.path.join(self.dir, "link.bin") - try: - os.link(self.dict, link) - except (OSError, NotImplementedError) as e: - with self.subTest(out=os.path.basename(link)): - self.skipTest(f"hard links unavailable: {e}") - else: - cases.append((link, [self.jsav])) - for out, inputs in cases: - with self.subTest(out=os.path.basename(out)): - with open(out, "rb") as f: - before = f.read() - r = self.resolve_cli(*inputs, "--dict", self.dict, "--out", out) - self.assertEqual(r.returncode, 1, r.stderr) - self.assertIn("refusing to overwrite", r.stderr) - self.assertNotIn("Traceback", r.stderr) - with open(out, "rb") as f: - self.assertEqual(f.read(), before) - - def test_out_in_a_missing_folder_is_one_error_line(self): - r = self.resolve_cli(self.jsav, "--dict", self.dict, "--out", os.path.join(self.dir, "nope", "res.json")) - self.assertEqual(r.returncode, 1) - self.assertIn("error: the folder for --out", r.stderr) - self.assertNotIn("Traceback", r.stderr) - self.assertEqual(r.stdout, "") # refused before the resolve ran - - def test_rejects_negative_compose_count(self): - result = self.resolve_cli(self.dir, "--dict", self.dict, "--compose", "-1") - self.assertEqual(result.returncode, 2, result.stderr) - self.assertIn("--compose must be 0 or more", result.stderr) - - def test_compose_finds_two_word_names(self): - text = run(["resolve", self.jsav, "--dict", self.dict, "--compose", "50"]) - self.assertIn("joaat, composed 1 more keys", text) # SprocketCount from Sprocket + Count - self.assertIn("total (joaat) 6 of 7 keys", text) - - -class MalformedJsavTest(unittest.TestCase): - """A lying JSAV entry count must warn and skip the table, not abort a whole batch.""" - - def collect(self, data, name="save.jsav"): - tmp = tempfile.TemporaryDirectory() - self.addCleanup(tmp.cleanup) - path = os.path.join(tmp.name, name) - with open(path, "wb") as f: - f.write(data) - err = io.StringIO() - with contextlib.redirect_stderr(err): - keys = sk.collect_keys([path]) - return keys, err.getvalue(), path - - def jsav(self, n_code, n_script=0, entries=(), tail=b""): - data = bytearray(b"JSAV" + struct.pack("" + name + b"")) - self.assertIn(name, got) - self.assertNotIn(name[81:], got) - - def test_a_run_past_the_limit_is_left_out_whole(self): - blob = b"Q" * (sk.IDENT_MAX + 1) - got = self.harvest(blob, b"Q" * sk.IDENT_MAX) - self.assertIn(b"Q" * sk.IDENT_MAX, got) - self.assertFalse([name for name in got if len(name) > sk.IDENT_MAX]) - self.assertNotIn(b"Q", got) - self.assertEqual({name for name in got if set(name) == {ord("Q")}}, {b"Q" * sk.IDENT_MAX}) - - def test_a_127_character_name_is_harvested(self): - name = b"Vehicle" + b"Part" * 30 - self.assertEqual(self.harvest(name), {name}) - - -class ComposeDeterminism(unittest.TestCase): - """`--compose` must report one answer for one input: tied word counts used to pick words in hash order.""" - - WORDS = ["Widget", "Gadget", "Sprocket", "Colour", "Spin", "Rate", "Mystery", "Field", "Alpha", - "Bravo", "Charlie", "Delta", "Echo", "Foxtrot", "Golf", "Hotel", "India", "Juliet", "Kilo", - "Lima"] - - def keys(self): - return {sk.joaat(b"Alpha"), sk.joaat(b"Gadget")} - - def test_the_vocabulary_does_not_depend_on_the_input_order(self): - # compose() builds its Counter by iterating a set, so the words it chose followed hash order: the same - # twenty words in reverse picked a different six. The six are now the alphabetically first, so Alpha is - # one of them and Gadget, far down the list, is not. - forward = sk.compose([w.encode() for w in self.WORDS], self.keys(), 6) - reverse = sk.compose([w.encode() for w in reversed(self.WORDS)], self.keys(), 6) - self.assertEqual(forward, reverse) - self.assertEqual(set(forward[0]), {sk.joaat(b"Alpha")}) - self.assertNotIn(sk.joaat(b"Gadget"), forward[0]) - - def test_a_tie_is_broken_by_the_word(self): - keys = {sk.joaat(b"Alpha"), sk.joaat(b"Zulu")} - hits, tried = sk.compose({b"Alpha", b"Bravo", b"Zulu"}, keys, 2) - self.assertEqual(tried, 18) # 6 one-word and 3 x 4 two-word candidates - self.assertEqual(set(hits), {sk.joaat(b"Alpha")}) # Alpha and Bravo win; Zulu is out of the six - - def test_the_cli_report_is_identical_across_runs(self): - # Hash randomisation already varies per process, so the same command disagreed with itself. - with tempfile.TemporaryDirectory() as tmp: - save = os.path.join(tmp, "k.json") - with open(save, "w", encoding="utf-8") as f: - f.write('{"%s": 1}' % key("AlphaBravo")) - dic = os.path.join(tmp, "words.bin") - with open(dic, "wb") as f: - for w in self.WORDS: - f.write(b"\0" + w.encode() + b"\0") - tool = os.path.join(ROOT, "tools", "save_keys.py") - runs = [subprocess.run([sys.executable, "-I", tool, "resolve", save, "--dict", dic, - "--compose", "6"], cwd=ROOT, capture_output=True, text=True) - for _ in range(5)] - for r in runs: - self.assertEqual(r.returncode, 0, r.stderr) - self.assertEqual(len({r.stdout for r in runs}), 1, [r.stdout for r in runs]) - composed = [ln for ln in runs[0].stdout.splitlines() if "composed" in ln][0] - # AlphaBravo is not a harvested string, so only the two-word pass can resolve it; Alpha and Bravo are - # both inside the six ties that used to be chosen in hash order. - self.assertEqual(composed.split()[2], "1") - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/test_saves.py b/tests/test_saves.py deleted file mode 100644 index e5776936d..000000000 --- a/tests/test_saves.py +++ /dev/null @@ -1,1037 +0,0 @@ -"""Tests for tools/saves.py: ASAV/JSAV/SLAYER1 parsing, the byte-exact JSAV rebuild, extract/pack, diff, and the -import into the offline XGameSave folder layout. Every container here is synthetic, built by the test itself; no real -save data is used or quoted. - - python -I tests/test_saves.py -""" -import contextlib -import errno -import io -import json -import os -import struct -import subprocess -import sys -import tempfile -import unittest -from unittest import mock - -ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) -TOOL = os.path.join(ROOT, "tools", "saves.py") -sys.path.insert(0, os.path.join(ROOT, "tools")) -import saves # noqa: E402 - -CODE_GROUP = "$0x11111111" -SCRIPT_GROUP = "$0x22222222" - - -def block(group, h, body): - """One synthetic block in the retail shape: {"":{"$0x":{...}}}, compact JSON.""" - return json.dumps({group: {"$0x%08x" % h: body}}, separators=(",", ":")).encode() - - -def make_jsav(n_code=3, n_script=2, seed=0): - hashes, blocks = [], [] - for i in range(n_code + n_script): - h = 0x10000000 + seed * 0x100 + i - group = CODE_GROUP if i < n_code else SCRIPT_GROUP - body = {"$0xaaaa0000": i, "$0xbbbb0000": {"$x": 1.5, "$y": -2.25, "$z": 0.0}, - "$0xcccc0000": {"$content": "int_array", "$data": list(range(i + 1))}} - hashes.append(h) - blocks.append(block(group, h, body)) - return saves.build_jsav(3, n_code, hashes, [1] * len(blocks), blocks), hashes, blocks - - -def make_asav(kind=3, title="Slot title", slot="SLOT0", payload=b"\x0a\x00\x00\x00", ts=1700000000): - d = bytearray(saves.ASAV_HDR) - struct.pack_into("<4sIIIIIII", d, 0, b"ASAV", 1, kind, 1, 0, saves.ASAV_HDR, 0, saves.ASAV_HDR + len(payload)) - struct.pack_into(" bytes: - rem = len(buf) % 16 - return buf if rem == 0 else buf + b"\x00" * (16 - rem) - - -def build_synthetic_qtable(*, pad_to_bytes: int = 0) -> bytes: - """Build a valid 7-record, 2-tree synthetic object-tree payload.""" - # Preorder record layout for 7 records (odd count => zero gap after 0x28 + 7*8): - # Tree 0 (root 0, hash 0x11111111): - # [0] 32B wrapper struct (type 0xAAAA0001, flags 0xFFFF0000) -> ptr array [1] - # [1] pointer array (count=2, stride=8, flags=0x10000, elem=0xBBBB0001) -> [2], [3] (64B) - # [2] 48B struct (type 0xAAAA0002, leaf or 0 ptrs) - # [3] 64B struct (type 0xAAAA0003) - # Tree 1 (root 4, hash 0x22222222): - # [4] 48B struct (type 0xAAAA0004) -> [5] and [6] - # [5] value array (count=3, stride=12, flags=0, elem=0xBBBB0002) -> align16(48+36)=96B - # [6] 32B leaf struct (type 0xAAAA0005) - sizes = [32, 64, 48, 64, 48, 96, 32] - if pad_to_bytes: - # Enlarge leaf value array [5] so align16 stays exact. - other_bytes = 40 + len(sizes) * 8 + sum(sizes) - sizes[5] - cnt5 = max(3, (pad_to_bytes - other_bytes - 48) // 12) - sizes[5] = ((48 + cnt5 * 12) + 15) & ~15 - else: - cnt5 = 3 - - table_end = 40 + len(sizes) * 8 # 96 = 0x60, 16-byte aligned because 7 is odd - offsets = [] - cur = table_end - for sz in sizes: - offsets.append(cur) - cur += sz - - def qptr(target_idx: int) -> int: - return Q_PTR_HIGH | (offsets[target_idx] + 8) - - recs = [ - # [0] 32B wrapper -> [1] - struct.pack("<4I2Q", 0x11111111, 0xFFFF0000, 0xAAAA0001, 0, qptr(1), 0), - # [1] ptr array count=2, stride=8, flags=0x10000 -> 48 + 16 = 64B - struct.pack("<12I2Q", 0, 0, 0x14, 0, 2, 2, 8, 0x10000, 0, 0, 0xBBBB0001, 0, qptr(2), qptr(3)), - # [2] 48B struct (leaf) - struct.pack("<4I", 0, 0, 0xAAAA0002, 0) + b"\x01" * 32, - # [3] 64B struct (leaf) - struct.pack("<4I", 0, 0, 0xAAAA0003, 0) + b"\x02" * 48, - # [4] 48B struct (root 0x22222222) -> qptr(5) at +0x10 and qptr(6) at +0x20 - struct.pack("<4IQ2Q", 0x22222222, 0, 0xAAAA0004, 0, qptr(5), 0, qptr(6)) + bytes(8), - # [5] value array (cnt5, stride=12, flags=0, elem=0xBBBB0002) - _pad16(struct.pack("<12I", 0, 0, 0x14, 0, cnt5, cnt5, 12, 0, 0, 0, 0xBBBB0002, 0) + b"\x03" * (cnt5 * 12)), - # [6] 32B leaf struct - struct.pack("<4I2Q", 0, 0, 0xAAAA0005, 0, 42, 99), - ] - for i, r in enumerate(recs): - assert len(r) == sizes[i], f"rec {i} len {len(r)} != {sizes[i]}" - - header = struct.pack("<10I", 0, 0, 0, 0, 0, len(offsets), 0, 0, 0, 0) - offset_table = struct.pack(f"<{len(offsets)}Q", *offsets) - return header + offset_table + b"".join(recs) - - -class ScriptQtableTests(unittest.TestCase): - def test_parse_validates_synthetic_forest_and_invariants(self): - blob = build_synthetic_qtable() - rep = script_qtable.parse_qtable(blob) - self.assertTrue(rep["valid"]) - self.assertEqual(rep["record_count"], 7) - self.assertEqual(rep["root_count"], 2) - self.assertEqual(rep["distinct_root_hashes"], 2) - self.assertTrue(rep["root_bijection_holds"]) - self.assertTrue(rep["contiguous_preorder"]) - self.assertEqual(rep["total_pointers"], 5) - self.assertEqual(rep["resolved_pointers"], 5) - self.assertEqual(rep["unresolved_pointers"], 0) - self.assertEqual(rep["array_records"], 2) - self.assertEqual(rep["array_size_exact"], 2) - self.assertEqual(rep["array_pointer_records"], 1) - self.assertEqual(rep["array_value_records"], 1) - self.assertEqual(rep["struct_records"], 5) - self.assertEqual(rep["struct_wrappers"], 1) - self.assertEqual(rep["array_strides"], {"8": 1, "12": 1}) - self.assertEqual(rep["struct_sizes"], {"32": 2, "48": 2, "64": 1}) - - def test_load_joins_split_64k_streams_from_carve_dir(self): - big = build_synthetic_qtable(pad_to_bytes=70_000) - self.assertGreater(len(big), 65536) - chunk0 = big[:65536] - chunk1 = big[65536:] - - with tempfile.TemporaryDirectory() as tmp: - carve = os.path.join(tmp, "carve") - os.makedirs(carve) - rows = [ - {"off": 0x1000, "stored": 500, "size": len(b"PSIN" + bytes(120)), "head": (b"PSIN" + bytes(12)).hex()}, - {"off": 0x2000, "stored": 10000, "size": len(chunk0), "head": chunk0[:16].hex()}, - {"off": 0x5000, "stored": 2000, "size": len(chunk1), "head": chunk1[:16].hex()}, - {"off": 0x9000, "stored": 400, "size": 128, "head": (b"PSIN" + bytes(12)).hex()}, - ] - with open(os.path.join(carve, f"{rows[0]['off']:012x}.bin"), "wb") as f: - f.write(b"PSIN" + bytes(124)) - with open(os.path.join(carve, f"{rows[1]['off']:012x}.bin"), "wb") as f: - f.write(chunk0) - with open(os.path.join(carve, f"{rows[2]['off']:012x}.bin"), "wb") as f: - f.write(chunk1) - with open(os.path.join(carve, f"{rows[3]['off']:012x}.bin"), "wb") as f: - f.write(b"PSIN" + bytes(124)) - with open(os.path.join(carve, "index.json"), "w", encoding="utf-8", newline="\n") as f: - json.dump({"summary": {"archive": "synthetic", "files": len(rows)}, "files": rows}, f) - - out_json = os.path.join(tmp, "out", "qtable.json") - p = subprocess.run( - [sys.executable, "-I", TOOL, carve, "--root-hash", "0x11111111", "--type-hash", "0xBBBB0002", "--json", out_json], - capture_output=True, text=True, encoding="utf-8", errors="replace", - ) - self.assertEqual(p.returncode, 0, p.stdout + p.stderr) - with open(out_json, "rb") as f: - raw = f.read() - self.assertIn(b"\n", raw) - self.assertNotIn(b"\r\n", raw) - rep = json.loads(raw.decode("utf-8")) - self.assertEqual(rep["location"]["offset_hex"], "0x2000") - self.assertEqual(rep["location"]["chunks"], 2) - self.assertEqual(rep["root_query"]["matches"], 1) - self.assertEqual(rep["root_query"]["trees"][0]["nodes"], 4) - self.assertEqual(rep["type_query"]["array_matches"], 1) - self.assertEqual(rep["type_query"]["distinct_trees"], 1) - - def test_detects_corrupt_pointer_and_refuses_input_overwrite(self): - bad = bytearray(build_synthetic_qtable()) - # Corrupt the last record's u64 at +0x10 into a dangling 0x71717171 pointer - struct.pack_into(" bytes: - table_end = 40 + 4 * 8 # 72; align16(72) == 80 - first_off = 80 - offsets = [first_off + i * 32 for i in range(4)] - - def pack_rec(rkey: int, thash: int, ptrs: list[int]) -> bytes: - w = [0, 0] - for idx, tgt in enumerate(ptrs): - w[idx] = Q_PTR_HIGH | (offsets[tgt] + 8) - return struct.pack("<4I2Q", rkey, 0, thash, 0, w[0], w[1]) - - recs = b"".join([ - pack_rec(0x11111111, 0xAAAA0001, r0_ptrs), - pack_rec(0, 0xAAAA0002, r1_ptrs), - pack_rec(0, 0xAAAA0003, []), - pack_rec(0, 0xAAAA0004, []), - ]) - header = struct.pack("<10I", 0, 0, 0, 0, 0, 4, 0, 0, 0, 0) - return header + struct.pack("<4Q", *offsets) + bytes(first_off - table_end) + recs - - ok_rep = script_qtable.parse_qtable(build_4rec([1, 3], [2])) - self.assertTrue(ok_rep["contiguous_preorder"]) - self.assertTrue(ok_rep["valid"]) - - bad_interleaved = script_qtable.parse_qtable(build_4rec([1, 2], [3])) - self.assertFalse(bad_interleaved["contiguous_preorder"]) - self.assertFalse(bad_interleaved["valid"]) - - bad_sibling_order = script_qtable.parse_qtable(build_4rec([3, 1], [2])) - self.assertFalse(bad_sibling_order["contiguous_preorder"]) - self.assertFalse(bad_sibling_order["valid"]) - - # Header claiming 11 records in 64B payload must raise ValueError, not struct.error. - trunc = bytearray(64) - struct.pack_into(" seed value (others are 0).""" - lines = ([f"v_mov_b32 v{r}, 0x{(v or {}).get(r, 0):x}" for r in d.VREGS] - + [f"s_mov_b32 s{r}, 0x{(s or {}).get(r, 0):x}" for r in d.SREGS] + [f"s_mov_b32 vcc_lo, {vcc}"]) - return d.reference(lines + list(body) + d.observe(list(regs))) - - -class Reference(unittest.TestCase): - def test_source_select_and_sext(self): - # BYTE_1 of 0x8000 is 0x80: zero-extended 0x80, sign-extended 0xffffff80 - mov = "v_mov_b32_sdwa v1, {} dst_sel:DWORD dst_unused:UNUSED_PAD src0_sel:BYTE_1" - self.assertEqual(run(mov.format("v2"), v={2: 0x8000})[0], 0x80) - self.assertEqual(run(mov.format("sext(v2)"), v={2: 0x8000})[0], 0xFFFFFF80) - # a constant is narrowed too: WORD_1 of -16 (0xfffffff0) is 0xffff - self.assertEqual(run(mov.format("-16").replace("BYTE_1", "WORD_1"))[0], 0xFFFF) - - def test_destination_select_and_unused_bits(self): - line = "v_mov_b32_sdwa v1, v2 dst_sel:BYTE_2 dst_unused:{} src0_sel:DWORD" - seeds = {1: 0x11223344, 2: 0xA5} - self.assertEqual(run(line.format("UNUSED_PAD"), v=seeds)[0], 0x00A50000) - self.assertEqual(run(line.format("UNUSED_SEXT"), v=seeds)[0], 0xFFA50000) # bits below stay 0 - self.assertEqual(run(line.format("UNUSED_PRESERVE"), v=seeds)[0], 0x11A53344) - - def test_integer_clamp_saturates(self): - self.assertEqual(run("v_sub_nc_u32_sdwa v1, 1, 2 clamp dst_sel:DWORD dst_unused:UNUSED_PAD " - "src0_sel:DWORD src1_sel:DWORD")[0], 0) - self.assertEqual(run("v_add_nc_u32_sdwa v1, v2, 1 clamp dst_sel:DWORD dst_unused:UNUSED_PAD " - "src0_sel:DWORD src1_sel:DWORD", v={2: 0xFFFFFFFF})[0], 0xFFFFFFFF) - - def test_f16_neg_abs_on_the_selected_half(self): - # WORD_1 of 0x40000000 is 2.0; -|2.0| * 3.0 = -6.0 = 0xc600 - self.assertEqual(run("v_mul_f16_sdwa v1, -|v2|, v3 dst_sel:WORD_0 dst_unused:UNUSED_PAD " - "src0_sel:WORD_1 src1_sel:WORD_0", v={2: 0x40000000, 3: 0x4200})[0], 0xC600) - - def test_float_constants(self): - # measured on gfx1036: in an f16 op 1.0 is 0x3c00 over a zero high half, so WORD_1 of it is +0.0 - add = "v_add_f16_sdwa v1, 1.0, v2 dst_sel:WORD_0 dst_unused:UNUSED_PAD src0_sel:{} src1_sel:WORD_0" - self.assertEqual(run(add.format("DWORD"), v={2: 0x3800})[0], 0x3E00) # 1.0 + 0.5 - self.assertEqual(run(add.format("WORD_1"), v={2: 0x3800})[0], 0x3800) # 0.0 + 0.5 - # in an integer op (v_cvt_f16_u16 included) it is the f32 bits: WORD_1 of -2.0 is 0xc000 = 49152 -> 0x7a00 - self.assertEqual(run("v_add_nc_u32_sdwa v1, 1.0, 0 dst_sel:DWORD dst_unused:UNUSED_PAD " - "src0_sel:DWORD src1_sel:DWORD")[0], 0x3F800000) - self.assertEqual(run("v_cvt_f16_u16_sdwa v1, -2.0 dst_sel:WORD_0 dst_unused:UNUSED_PAD src0_sel:WORD_1")[0], - 0x7A00) - # v_cmp_class_f16's mask is an f16 operand too: 0.5 is 0x00003800 (BYTE_3=0, BYTE_1=0x38), - # 1.0 is 0x00003C00 (WORD_1=0), and -2.0 is 0x0000C000 (BYTE_3=0), not f32 0x3F000000/0x3F800000/0xC0000000 - self.assertEqual(run("v_cmp_class_f16_sdwa vcc_lo, v2, 0.5 src0_sel:WORD_0 src1_sel:BYTE_3", - v={2: 0xBC00}, vcc=1)[3], 0) - self.assertEqual(run("v_cmp_class_f16_sdwa vcc_lo, v2, 0.5 src0_sel:WORD_0 src1_sel:BYTE_1", - v={2: 0xBC00})[3], 1) # 0x38 has bit 3 (-normal) - self.assertEqual(run("v_cmp_class_f16_sdwa vcc_lo, 2.0, 1.0 src0_sel:DWORD src1_sel:WORD_1", - vcc=1)[3], 0) - self.assertEqual(run("v_cmp_class_f16_sdwa vcc_lo, v2, -2.0 src0_sel:DWORD src1_sel:BYTE_3", - v={2: 0x0001}, vcc=1)[3], 0) # f32 BYTE_3=0xC0 falsely sets bit 7 - self.assertEqual(run("v_cmp_class_f16_sdwa vcc_lo, v2, 0x8 src0_sel:WORD_0 src1_sel:DWORD", - v={2: 0xBC00})[3], 1) # -1.0 is -normal (bit 3) - - def test_16bit_result_with_dword_dst_zeroes_the_high_half(self): - # measured on gfx1036 whatever dst_unused says; the non-SDWA f16 forms keep the high half instead - for unused in d.UNUSED: - self.assertEqual(run(f"v_add_f16_sdwa v1, v2, v3 dst_sel:DWORD dst_unused:{unused} " - "src0_sel:WORD_0 src1_sel:WORD_0", v={1: 0xDEAD0000, 2: 0x3C00, 3: 0x3C00})[0], - 0x4000) - - def test_fract_of_negative_zero_is_positive_zero(self): - self.assertEqual(run("v_fract_f16_sdwa v1, v2 dst_sel:WORD_0 dst_unused:UNUSED_PAD src0_sel:WORD_0", - v={2: 0x8000})[0], 0) - self.assertEqual(run("v_fract_f16_sdwa v1, v2 dst_sel:WORD_0 dst_unused:UNUSED_PAD src0_sel:WORD_0", - v={2: 0x8001})[0], 0x3BFF) # 1 - tiny rounds to 1.0, stops - - def test_compares_and_cndmask(self): - cmp = "v_cmp_lt_{}16_sdwa vcc_lo, v2, v3 src0_sel:WORD_1 src1_sel:WORD_0" - seeds = {2: 0x80000000, 3: 1} # WORD_1 = 0x8000: -32768 signed, 32768 unsigned - self.assertEqual(run(cmp.format("i"), v=seeds)[3], 1) - self.assertEqual(run(cmp.format("u"), v=seeds, vcc=1)[3], 0) - self.assertEqual(run(cmp.format("i"), "v_cndmask_b32_sdwa v1, v2, v3, vcc_lo dst_sel:DWORD " - "dst_unused:UNUSED_PAD src0_sel:DWORD src1_sel:BYTE_0", v=seeds)[0], 1) - - def test_constant_shift_amount_is_selected(self): - # the #2005 case: WORD_1 of 0x40001 is 4 - self.assertEqual(run("v_lshlrev_b32_sdwa v1, s4, v2 dst_sel:DWORD dst_unused:UNUSED_PAD " - "src0_sel:WORD_1 src1_sel:DWORD", v={2: 1}, s={4: 0x40001})[0], 0x10) - - def test_nan_operands_are_skipped_not_guessed(self): - with self.assertRaises(d.Skip): - run("v_max_f16_sdwa v1, v2, v3 dst_sel:WORD_0 dst_unused:UNUSED_PAD src0_sel:WORD_0 src1_sel:WORD_0", - v={2: 0x7E00}) - # a compare is defined for NaN: unordered - self.assertEqual(run("v_cmp_u_f16_sdwa vcc_lo, v2, v3 src0_sel:WORD_0 src1_sel:WORD_0", v={2: 0x7E00})[3], 1) - - -class Generator(unittest.TestCase): - def lines(self, n=2500, known=False, seed=1): - real, d.KNOWN = d.KNOWN, known - try: - rng = d.random.Random(seed) - return [d.emit(rng, rng.choice(sorted(d.OPS))) for _ in range(n)] - finally: - d.KNOWN = real - - def test_every_op_is_generated(self): - seen = {line.split()[0][:-len("_sdwa")] for line in self.lines()} - self.assertEqual(set(d.OPS) - seen, set()) - - def test_known_divergences_are_left_out_by_default(self): - def known_form(line): - op, args, mods, _ = d.parse(line) - family, form, width = d.OPS[op][:3] - src0 = d.parse_src(args[1]) - if op in d.SHIFTS and src0["tok"][0] != "v" and (mods["src0_sel"] != "DWORD" or src0["sext"]): - return "shift-const-sel" - if form != "vopc" and width == 16 and mods["dst_sel"] == "DWORD": - return "dword-16bit" - srcs = args[1:3] if form != "vop1" else args[1:2] - if family == "f16" and any(a in d.FLOAT_CONSTS and mods.get(f"src{i}_sel") != "DWORD" - for i, a in enumerate(srcs)): - return "f16-const-sel" - return None - self.assertEqual({known_form(line) for line in self.lines()} - {None}, {"dword-16bit", "f16-const-sel"}) - self.assertEqual({known_form(line) for line in self.lines(known=True)} - {None}, - set(d.KNOWN_DIVERGENCES) | {"dword-16bit", "f16-const-sel"}) - - def test_forms_main_translates_again_are_generated_by_default(self): - # #2187 (dst_sel:DWORD zeroes a 16-bit result's high half) and #2209 (src_sel on an f16 float constant) are - # on main, so a default run must keep both forms in, or a regression of either goes unseen - self.assertEqual(set(d.KNOWN_DIVERGENCES), {"shift-const-sel"}) - lines = self.lines() - self.assertTrue(any(d.OPS[line.split()[0][:-5]][2] == 16 and "dst_sel:DWORD" in line for line in lines)) - # each source on its own: the same operand is a float constant and its own selector is not DWORD - selected = set() - for line in lines: - op, args, mods, _ = d.parse(line) - family, form = d.OPS[op][:2] - if family != "f16": - continue - srcs = args[1:3] if form != "vop1" else args[1:2] - for i, a in enumerate(srcs): - if a in d.FLOAT_CONSTS and mods.get(f"src{i}_sel", "DWORD") != "DWORD": - selected.add(i) - self.assertEqual(selected, {0, 1}) - - -class Translated(unittest.TestCase): - ALLOWED_SKIPS = ("reference: ", "translator unsupported: v_cmp_class_f16", - "translator unsupported: v_cvt_f16_u16 output modifier", - "translator unsupported: v_cvt_f16_i16 output modifier") - - def test_harness_canaries(self): - with contextlib.redirect_stdout(io.StringIO()): - self.assertTrue(d.self_test()) - - def test_short_seeded_run_matches(self): - counts, failures = d.run_suite(60, 5, 4, sorted(d.OPS)) - self.assertEqual(failures, [], failures[:1]) - self.assertEqual([r for r in counts["skip"] if not r.startswith(self.ALLOWED_SKIPS)], []) - self.assertGreaterEqual(counts["pass"], 50) - - def test_hand_cases_match_the_translator(self): - # the Reference cases outside KNOWN_DIVERGENCES, so a sabotaged sdwa_src / sdwa_dst fails here directly - seeds = {1: 0x11223344, 2: 0x400080A5, 3: 0x80004200} - prefix = ([f"v_mov_b32 v{r}, 0x{seeds.get(r, 0):x}" for r in d.VREGS] - + [f"s_mov_b32 s{r}, 0x40001" for r in d.SREGS] + ["s_mov_b32 vcc_lo, 0"]) - cases = [f"v_mov_b32_sdwa v1, sext(v2) dst_sel:DWORD dst_unused:UNUSED_PAD src0_sel:BYTE_{n}" for n in (0, 1)] - cases += [f"v_mov_b32_sdwa v1, v2 dst_sel:{sel} dst_unused:{u} src0_sel:BYTE_0" - for sel in ("BYTE_1", "BYTE_2", "WORD_1") for u in d.UNUSED] - cases += ["v_sub_nc_u32_sdwa v1, 1, 2 clamp dst_sel:DWORD dst_unused:UNUSED_PAD src0_sel:DWORD src1_sel:DWORD", - "v_mul_f16_sdwa v1, -|v2|, v3 dst_sel:WORD_1 dst_unused:UNUSED_PRESERVE src0_sel:WORD_1 " - "src1_sel:WORD_0", - "v_fract_f16_sdwa v1, v3 dst_sel:WORD_0 dst_unused:UNUSED_SEXT src0_sel:WORD_1", - "v_cmp_lt_i16_sdwa vcc_lo, v3, v2 src0_sel:WORD_1 src1_sel:BYTE_0", - "v_lshlrev_b32_sdwa v1, v2, v3 dst_sel:DWORD dst_unused:UNUSED_PAD src0_sel:BYTE_3 " - "src1_sel:WORD_0"] - for case in cases: - with self.subTest(case=case): - self.assertIsNone(d.check(prefix + [case, "v_cmp_lt_u16_sdwa vcc_lo, v1, v2 src0_sel:BYTE_2 " - "src1_sel:BYTE_0"] + d.observe([1, 2, 3]))) - - def test_a_wrong_translation_is_caught(self): - lines = (["v_mov_b32 v2, 0x8000", "s_mov_b32 vcc_lo, 0", - "v_mov_b32_sdwa v1, sext(v2) dst_sel:DWORD dst_unused:UNUSED_PAD src0_sel:BYTE_1", - "v_cmp_eq_u32_sdwa vcc_lo, v1, v1 src0_sel:DWORD src1_sel:DWORD"] + d.observe([1, 2, 3])) - self.assertIsNone(d.check(lines)) - want = d.reference(lines) - real = d.translated - try: - d.translated = lambda _lines: want[:3] + [want[3] ^ 1] - self.assertIn("word 3 (VCC)", d.check(lines)) - d.translated = lambda _lines: [0x80] + want[1:] # sext() ignored - self.assertIn("word 0 (v1)", d.check(lines)) - finally: - d.translated = real - - def test_shrinking_keeps_the_instruction_that_matters(self): - rng = d.random.Random(2) - lines = d.generate(rng, 4, ["v_add_nc_u32", "v_xor_b32"]) - target = lines[d.N_SEED + 2] - real = d.translated - try: - # a fake translator that is wrong exactly when `target` is in the program - d.translated = lambda l: [w ^ (1 if target in l else 0) for w in d.reference(l)] - small = d.shrink(lines) - finally: - d.translated = real - self.assertEqual(small[d.N_SEED:-d.N_OBS], [target]) - - -class Cli(unittest.TestCase): - def main(self, *argv): - out = io.StringIO() - with contextlib.redirect_stdout(out), contextlib.redirect_stderr(io.StringIO()): - try: - rc = d.main(list(argv)) - except SystemExit as e: - rc = e.code - return rc, out.getvalue() - - def test_exit_codes(self): - rc, out = self.main("--list-ops") - self.assertEqual(rc, 0) - self.assertIn("v_cmp_class_f16", out) - self.assertEqual(self.main("--ops", "v_nope")[0], 2) - self.assertEqual(self.main("--oracle", "gpu")[0], 2) - rc, out = self.main("--programs", "5", "--seed", "1", "--family", "int") - self.assertEqual(rc, 0, out) - real = d.translated - try: - d.translated = lambda l: [w ^ 1 for w in d.reference(l)] - rc, out = self.main("--programs", "3", "--seed", "1", "--ops", "v_xor_b32") - finally: - d.translated = real - self.assertEqual(rc, 1) - self.assertIn("MISMATCH", out) - - def test_hardware_oracle_without_the_tools_exits_77(self): - import os - import subprocess - env = dict(os.environ, LEONIDA_AMD_CLANG=str(TOOL.parent / "no-such-clang.exe")) - r = subprocess.run([sys.executable, "-I", str(TOOL), "--oracle", "hw", "--programs", "3"], - capture_output=True, text=True, env=env) - self.assertEqual(r.returncode, 77, r.stdout + r.stderr) - self.assertIn("unavailable", r.stdout) - - def test_a_gpu_without_sdwa_exits_77(self): - import unittest.mock - from hw_oracle import runner - - class NoSdwa: - arch, device, closed = "gfx1150", "stub", False - - def close(self): - NoSdwa.closed = True - with unittest.mock.patch.object(runner, "open_oracle", return_value=NoSdwa()): - rc, out = self.main("--oracle", "hw", "--programs", "3") - self.assertEqual(rc, 77) - self.assertIn("no SDWA", out) - self.assertTrue(NoSdwa.closed) - - -class EverythingSkipped(unittest.TestCase): - def test_a_run_where_every_program_was_skipped_is_not_a_success(self): - import contextlib - import io - from unittest import mock - - def refuse(lines, *args): - raise d.Skip("unsupported form") - out = io.StringIO() - with mock.patch.object(d, "translated", refuse), contextlib.redirect_stdout(out): - rc = d.main(["--programs", "3", "--seed", "1"]) - self.assertEqual(rc, 2, out.getvalue()) - self.assertIn("no program ran: every one was skipped", out.getvalue()) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/test_semantic_mutants.py b/tests/test_semantic_mutants.py deleted file mode 100644 index 42ac9917a..000000000 --- a/tests/test_semantic_mutants.py +++ /dev/null @@ -1,201 +0,0 @@ -"""tools/semantic_mutants.py: branch lookup, mutant generation, and one end-to-end run on a weak and a strong test.""" -import os -import subprocess -import sys -import tempfile -import textwrap -import unittest - -ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) -sys.path.insert(0, os.path.join(ROOT, "tools")) - -import semantic_mutants as sm # noqa: E402 - -TOOL = os.path.join(ROOT, "tools", "semantic_mutants.py") - -SOURCE = textwrap.dedent('''\ - F1 = {"v_a": "InverseSqrt", "v_b": "Sqrt", # a comment "v_z": "Nope" - "v_c": "Exp2"} - class Gen: - def op(self, op, a): - if op == "v_other": - self.emit(f"{r} = OpIAdd %uint {x} {y}") - elif op in ("v_one", "v_two", - "v_three"): - x, y = a - self.emit(f"{r} = OpIAdd %uint {x} {y}") # a comment with OpISub in it - self.emit(f"{s} = OpSelect %uint {c} {x} {self.cu(0)}") - self.emit(f"{t} = OpExtInst %uint %glsl UMin {x} {self.cu(31)}") - # self.emit(f"{u} = OpIAdd %uint {x} {y}") is a comment line - elif op == "v_four": - pass - - def helper(self): - return 1 - ''').split("\n") - - -class BranchLookup(unittest.TestCase): - def test_multiline_condition_and_end(self): - first, last = sm.find_branch(SOURCE, "v_three") - self.assertEqual(SOURCE[first].strip()[:5], "elif ") - self.assertIn('"v_one"', SOURCE[first]) - self.assertIn("comment line", SOURCE[last]) # the branch runs up to the next elif - self.assertEqual(sm.branch_ops(SOURCE, first), ["v_one", "v_two", "v_three"]) - - def test_missing_op_and_function(self): - with self.assertRaises(LookupError): - sm.find_branch(SOURCE, "v_five") - first, last = sm.find_function(SOURCE, "helper") - self.assertIn("def helper", SOURCE[first]) - self.assertIn("return 1", SOURCE[last]) - - -class Generation(unittest.TestCase): - def setUp(self): - first, last = sm.find_branch(SOURCE, "v_one") - self.mutants = sm.mutants_for(SOURCE, first, last) - self.labels = [m.label for m in self.mutants] - - def test_operators(self): - self.assertIn("OpIAdd -> OpISub", self.labels) - self.assertIn("OpSelect arms swapped", self.labels) - self.assertIn("UMin -> UMax", self.labels) - self.assertIn("UMin -> SMin", self.labels) - self.assertIn("self.cu(31) -> self.cu(32)", self.labels) - self.assertIn("self.cu(31) -> self.cu(30)", self.labels) - self.assertIn("self.cu(0) -> self.cu(1)", self.labels) - self.assertNotIn("self.cu(0) -> self.cu(-1)", self.labels) - self.assertIn("last operand {y} -> {x}", self.labels) - - def test_comments_and_other_branches_are_left_alone(self): - other = SOURCE.index(next(s for s in SOURCE if 'if op == "v_other"' in s)) + 2 # its emit line, 1-based - for m in self.mutants: - self.assertNotIn("comment line", m.old) # a commented-out line is never mutated - self.assertNotEqual(m.line, other) # nor a line of another branch - select = next(m for m in self.mutants if m.label == "OpSelect arms swapped") - self.assertIn("{c} {self.cu(0)} {x}", select.new) - # the comment's own OpISub is not a mutation site: exactly one IAdd -> ISub on that line - line = SOURCE.index(next(s for s in SOURCE if "a comment with OpISub" in s)) + 1 - self.assertEqual(sum(1 for m in self.mutants if m.line == line and m.label == "OpIAdd -> OpISub"), 1) - self.assertFalse(any(m.line == line and m.label == "OpISub -> OpIAdd" for m in self.mutants)) - - -class Tables(unittest.TestCase): - def test_entry_takes_the_other_values_of_its_table(self): - labels = [m.label for m in sm.table_mutants(SOURCE, "v_a")] - self.assertEqual(labels, ['table entry "v_a": "InverseSqrt" -> "Sqrt"', - 'table entry "v_a": "InverseSqrt" -> "Exp2"']) # never the commented "Nope" - m = sm.table_mutants(SOURCE, "v_c")[0] - self.assertIn('"v_c": "InverseSqrt"', m.new) - self.assertEqual(sm.table_mutants(SOURCE, "v_missing"), []) - - def test_table_only_op_on_the_real_translator(self): - # v_rsq_f32 is translated through the F1 table, with no `if op` branch of its own. - p = subprocess.run([sys.executable, "-I", TOOL, os.path.join(ROOT, "tests", "semantic", "test_ps_semantics.py"), - "--op", "v_rsq_f32", "--list"], capture_output=True, text=True, timeout=120) - self.assertEqual(p.returncode, 0, p.stdout + p.stderr) - self.assertIn('table entry "v_rsq_f32": "InverseSqrt" -> "Sqrt"', p.stdout) - - -SAD_TEST = textwrap.dedent('''\ - import os, sys, unittest - sys.path.insert(0, {semantic!r}) - import support - - class T(unittest.TestCase): - def run_sad(self, s0, s1): - lines = [f"v_mov_b32 v0, {{s0:#x}}", f"v_mov_b32 v1, {{s1:#x}}", "v_mov_b32 v2, 0", - "v_sad_u8 v3, v0, v1, v2", "exp mrt0 v3, v3, v3, v3 done vm", "s_endpgm"] - return support.mrt0_words(support.translate_lines("ps_sad_probe", lines))[0] - - def test_sad(self): - self.assertEqual(self.run_sad(0x04030201, 0), 10) - {extra} - if __name__ == "__main__": - unittest.main() - ''') -MAIN_BLOCK = 'if __name__ == "__main__":\n unittest.main()\n' -assert SAD_TEST.endswith(MAIN_BLOCK) -STRONG_EXTRA = ''' - def test_sad_reversed(self): - self.assertEqual(self.run_sad(0, 0x04030201), 10) -''' - - -class EndToEnd(unittest.TestCase): - """v_sad_u8's UMax line: replacing UMax(xa, ya) by UMax(xa, xa) is only right when every byte of S0 >= S1's.""" - - def umax_line(self): - with open(os.path.join(ROOT, "tools", "rdna2spirv.py"), encoding="utf-8") as f: - lines = f.read().split("\n") - first, last = sm.find_branch(lines, "v_sad_u8") - for i in range(first, last + 1): - if "UMax {xa} {ya}" in lines[i]: - return i + 1 - self.skipTest("v_sad_u8's UMax line moved") - - def run_tool(self, extra, main_block=True): - line = self.umax_line() - source = SAD_TEST.format(semantic=os.path.join(ROOT, "tests", "semantic"), extra=extra) - if not main_block: - source = source.replace(MAIN_BLOCK, "") - self.assertNotIn("__main__", source) - with tempfile.TemporaryDirectory() as tmp: - test = os.path.join(tmp, "test_sad_probe.py") - with open(test, "w", encoding="utf-8", newline="\n") as f: - f.write(source) - p = subprocess.run([sys.executable, "-I", TOOL, test, "--lines", f"{line}-{line}"], - capture_output=True, text=True, timeout=600) - return p.returncode, p.stdout + p.stderr - - def test_weak_test_lets_the_operand_mutant_survive(self): - code, out = self.run_tool("") - self.assertEqual(code, 1, out) - self.assertRegex(out, r"SURVIVED\s+line \d+: last operand \{ya\} -> \{xa\}") - - def test_strong_test_catches_it(self): - code, out = self.run_tool(STRONG_EXTRA) - self.assertRegex(out, r"caught\s+line \d+: last operand \{ya\} -> \{xa\}") - - def test_file_without_a_main_block_still_runs_its_tests(self): - # Eight tests/semantic files have no `__main__` block; started as a script they ran nothing, so the baseline - # passed and every mutant was reported SURVIVED. - code, out = self.run_tool(STRONG_EXTRA, main_block=False) - self.assertNotEqual(code, 2, out) - self.assertRegex(out, r"caught\s+line \d+: last operand \{ya\} -> \{xa\}") - - def test_file_with_no_tests_is_a_baseline_error(self): - line = self.umax_line() - with tempfile.TemporaryDirectory() as tmp: - test = os.path.join(tmp, "test_empty_probe.py") - with open(test, "w", encoding="utf-8", newline="\n") as f: - f.write("import unittest\n") - p = subprocess.run([sys.executable, "-I", TOOL, test, "--lines", f"{line}-{line}"], - capture_output=True, text=True, timeout=600) - self.assertEqual(p.returncode, 2, p.stdout + p.stderr) - self.assertIn("no tests ran", p.stderr) - - -class RunTestEncoding(unittest.TestCase): - def test_utf8_bytes_outside_windows_codepage_do_not_crash(self): - with tempfile.TemporaryDirectory() as tmp: - test = os.path.join(tmp, "test_utf8_out.py") - with open(test, "w", encoding="utf-8", newline="\n") as f: - f.write("import sys\nsys.stdout.buffer.write(b'fail: \\xe2\\x86\\x90 bad\\n')\nsys.exit(1)\n") - ok, last = sm.run_test(test, os.path.join(ROOT, "tools"), 30) - self.assertEqual((ok, last), (False, "fail: \u2190 bad")) - - def test_invalid_utf8_bytes_are_replaced_not_raised(self): - with tempfile.TemporaryDirectory() as tmp: - test = os.path.join(tmp, "test_bad_bytes.py") - with open(test, "w", encoding="utf-8", newline="\n") as f: - f.write("import sys\nsys.stderr.buffer.write(b'raw: \\xff\\xfe\\n')\nsys.exit(1)\n") - ok, last = sm.run_test(test, os.path.join(ROOT, "tools"), 30) - self.assertIs(ok, False) - self.assertIn("raw:", last) - self.assertIn("\ufffd", last) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/test_semantic_translator_use.py b/tests/test_semantic_translator_use.py deleted file mode 100644 index b862c9e84..000000000 --- a/tests/test_semantic_translator_use.py +++ /dev/null @@ -1,232 +0,0 @@ -"""Every tests/semantic/test_*.py actually runs tools/rdna2spirv.py. - - python -I tests/test_semantic_translator_use.py - -A translator regression test that reimplements the answer in Python and never calls the translator -passes whatever the translator does, so it is not a regression test. This guard reads the test -files (it does not import them) and requires each one to reach ``rdna2spirv``: - -* a direct ``import rdna2spirv`` / ``from rdna2spirv import ...``; -* an import of a helper in tests/semantic (``support``, ``regen_fixtures``, another test module) - that itself reaches the translator, followed transitively; -* a subprocess/runpy test or a meta-test whose own string names ``rdna2spirv.py``. - -``ALLOWLIST`` is deliberately short and reviewed: it holds the interpreter self-tests, the fixture -drift check, and the files whose subject is hand-written SPIR-V. A new entry needs a reason and a -name that says why the file must not call the translator. - -This checks that a file *reaches* the translator, not that every assertion depends on it: a file that -imports ``support`` and asserts nothing about its output still passes. The pattern it is meant to -stop is the one that imports nothing from the repository at all and models the instruction itself. -""" -import ast -import os -import tempfile -import unittest - -ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) -SEMANTIC = os.path.join(ROOT, "tests", "semantic") - -# Files that legitimately do not invoke the translator. Keep this list short; every entry is a -# promise that the file tests something other than translation (or tests the translator's input). -ALLOWLIST = { - "test_spirv_tools_required.py": "meta-test: fails CI when spirv-as/spirv-val are missing, so translator tests cannot skip quietly", - "test_interp.py": "self-test of spirv_mini_interp.py against hand-written SPIR-V", - "test_spirv_wave_interp.py": "self-test of spirv_wave_interp.py against hand-written SPIR-V", - "test_fixtures.py": "checks fixtures/disasm/*.s against regen_fixtures.py; the listing is the subject", - "test_alu_frexp.py": "hand-written SPIR-V run by spirv_mini_interp.py; no translator output", - "test_alu_ldexp.py": "hand-written SPIR-V run by spirv_mini_interp.py; no translator output", -} - -# Debt from before this guard: files that model the answer instead of running the translator. They are -# expected to be replaced, so an entry here never has to be kept in step with another PR: fixing the file, -# or deleting it, simply removes it from the debt. Do not move a file here to silence the guard. -DEBT = { - "test_valu_div_fixup.py": "private oracle whose rules RDNA2 disagrees with; TEST-545 replaces it", - "test_alu_cndmask_b64.py": "private oracle merged before this guard (2026-11-22); should translate a listing", - "test_int_to_float.py": "private oracle merged before this guard (2026-11-22); should translate a listing", - "test_lds_add_sub_src2_u32.py": "private oracle merged before this guard (2026-11-22); should translate a listing", - "test_salu_add_sub_co_u32.py": "private oracle merged before this guard (2026-11-22); should translate a listing", - "test_salu_and_saveexec_b64.py": "private oracle merged before this guard (2026-11-22); should translate a listing", - "test_salu_andn2_saveexec_b64.py": "private oracle merged before this guard (2026-11-22); should translate a listing", - "test_salu_nand_nor_saveexec_b64.py": "private oracle merged before this guard (2026-11-22); should translate a listing", - "test_salu_or_saveexec_b64.py": "private oracle merged before this guard (2026-11-22); should translate a listing", - "test_salu_orn2_saveexec_b64.py": "private oracle merged before this guard (2026-11-22); should translate a listing", - "test_salu_xnor_saveexec_b64.py": "private oracle merged before this guard (2026-11-22); should translate a listing", - "test_salu_xor_saveexec_b64.py": "private oracle merged before this guard (2026-11-22); should translate a listing", - "test_valu_alignbyte_b32.py": "private oracle merged before this guard (2026-11-22); should translate a listing", - "test_valu_cvt_f32_f64.py": "private oracle merged before this guard (2026-11-22); should translate a listing", - "test_valu_dot4_int.py": "private oracle merged before this guard (2026-11-22); should translate a listing", - "test_valu_dot8_int.py": "private oracle merged before this guard (2026-11-22); should translate a listing", - "test_valu_fma_f64.py": "private oracle merged before this guard (2026-11-22); should translate a listing", - "test_valu_fract_f16.py": "private oracle merged before this guard (2026-11-22); should translate a listing", - "test_valu_fract_f64.py": "private oracle merged before this guard (2026-11-22); should translate a listing", - "test_valu_frexp_exp_i32_f64.py": "private oracle merged before this guard (2026-11-22); should translate a listing", - "test_valu_frexp_f64.py": "private oracle merged before this guard (2026-11-22); should translate a listing", - "test_valu_frexp_mant_f64.py": "private oracle merged before this guard (2026-11-22); should translate a listing", - "test_valu_lerp_u8.py": "private oracle merged before this guard (2026-11-22); should translate a listing", - "test_valu_minmax_f64.py": "private oracle merged before this guard (2026-11-22); should translate a listing", - "test_valu_mul_f64.py": "private oracle merged before this guard (2026-11-22); should translate a listing", - "test_valu_mul_hi.py": "private oracle merged before this guard (2026-11-22); should translate a listing", - "test_valu_pack_b32_f16.py": "private oracle merged before this guard (2026-11-22); should translate a listing", - "test_valu_perm_b32.py": "private oracle merged before this guard (2026-11-22); should translate a listing", - "test_valu_pk_add_f16.py": "private oracle merged before this guard (2026-11-22); should translate a listing", - "test_valu_pk_fma_f16.py": "private oracle merged before this guard (2026-11-22); should translate a listing", - "test_valu_pk_minmax_f16.py": "private oracle merged before this guard (2026-11-22); should translate a listing", - "test_valu_pk_mul_f16.py": "private oracle merged before this guard (2026-11-22); should translate a listing", - "test_valu_rcp_f16.py": "private oracle merged before this guard (2026-11-22); should translate a listing", - "test_valu_rcp_f64.py": "private oracle merged before this guard (2026-11-22); should translate a listing", - "test_valu_rsq_f16.py": "private oracle merged before this guard (2026-11-22); should translate a listing", - "test_valu_rsq_f64.py": "private oracle merged before this guard (2026-11-22); should translate a listing", - "test_valu_sad_u32.py": "private oracle merged before this guard (2026-11-22); should translate a listing", - "test_valu_sqrt_f16.py": "private oracle merged before this guard (2026-11-22); should translate a listing", - "test_valu_sqrt_f64.py": "private oracle merged before this guard (2026-11-22); should translate a listing", - "test_valu_trig_f64.py": "private oracle merged before this guard (2026-11-22); should translate a listing", -} - - -def _parse(path): - with open(path, encoding="utf-8", errors="replace") as f: - return ast.parse(f.read(), path) - - -def _imports(tree): - """(module, bound name, line) for every import, at any nesting depth, relative ones included. - - The bound name is what the module body can use: ``import support`` binds ``support``, - ``from support import translate_lines`` binds ``translate_lines``. - """ - for node in ast.walk(tree): - if isinstance(node, ast.Import): - for alias in node.names: - yield alias.name, alias.asname or alias.name.split(".")[0], node.lineno - elif isinstance(node, ast.ImportFrom): - module = node.module or "" - if node.level > 1: # from ..x import y: outside tests/semantic - continue - for alias in node.names: - yield module, alias.asname or alias.name, node.lineno - - -def _used_names(tree): - """Every name loaded in the module body: an import that is never referenced cannot reach anything.""" - return {node.id for node in ast.walk(tree) if isinstance(node, ast.Name) and isinstance(node.ctx, ast.Load)} - - -def _docstring_literals(tree): - found = set() - for node in ast.walk(tree): - if isinstance(node, (ast.Module, ast.ClassDef, ast.FunctionDef, ast.AsyncFunctionDef)) and node.body: - first = node.body[0] - if (isinstance(first, ast.Expr) and isinstance(first.value, ast.Constant) - and isinstance(first.value.value, str)): - found.add(id(first.value)) - return found - - -def _process_names_translator(tree): - """The line of a non-docstring string naming rdna2spirv.py, when the file also drives a process.""" - imports_process = any(module.split(".")[0] in ("subprocess", "runpy") for module, _, _ in _imports(tree)) - if not imports_process: - return None - docstrings = _docstring_literals(tree) - for node in ast.walk(tree): - if (isinstance(node, ast.Constant) and isinstance(node.value, str) - and "rdna2spirv.py" in node.value and id(node) not in docstrings): - return node.lineno - return None - - -def _first_line(path): - """A useful line number for a file that never reaches the translator: its first import, else 1.""" - try: - tree = _parse(path) - except SyntaxError: - return 1 - lines = [line for _, _, line in _imports(tree)] - return min(lines) if lines else 1 - - -def _reaches(path, seen, semantic_dir): - """True when `path` imports (and uses) the translator, a helper that does, or names it to a subprocess.""" - path = os.path.normpath(path) - if path in seen: - return False - seen = seen | {path} - tree = _parse(path) - used = _used_names(tree) | {"*"} # a star import has no name to match - if _process_names_translator(tree) is not None: - return True - for module, binding, _ in _imports(tree): - if binding not in used: - continue # imported and never referenced: it cannot reach the translator - if module.split(".")[0] == "rdna2spirv": - return True - helper = os.path.join(semantic_dir, (module.split(".")[0] or binding) + ".py") - if os.path.isfile(helper) and _reaches(helper, seen, semantic_dir): - return True - return False - - -def offenders(semantic_dir=SEMANTIC, allowlist=None, debt=None): - """[(relative path, line, reason)] for test files that do not reach rdna2spirv and are not allowed.""" - allowlist = ALLOWLIST if allowlist is None else allowlist - debt = DEBT if debt is None else debt - found = [] - for name in sorted(os.listdir(semantic_dir)): - if not (name.startswith("test_") and name.endswith(".py")): - continue - if name in allowlist or name in debt: - continue - path = os.path.join(semantic_dir, name) - if _reaches(path, set(), semantic_dir): - continue - found.append((os.path.join("tests", "semantic", name), _first_line(path), - "imports no rdna2spirv and no helper that does")) - return found - - -class TranslatorUseTests(unittest.TestCase): - def test_every_semantic_test_reaches_the_translator(self): - bad = offenders() - if bad: - self.fail( - "translator regression tests that never run tools/rdna2spirv.py:\n" - + "\n".join(f" {path}:{line}: {why}" for path, line, why in bad) - + "\n\nCall support.translate_fixture/translate_lines/translate_listing (or import " - "rdna2spirv) so the test observes the translator, or add a reviewed ALLOWLIST entry " - "in tests/test_semantic_translator_use.py saying why the file must not.") - - def test_allowlist_entries_are_real_and_still_needed(self): - """A stale entry would silently exempt a file that now calls the translator.""" - for name, why in ALLOWLIST.items(): - path = os.path.join(SEMANTIC, name) - self.assertTrue(os.path.isfile(path), f"ALLOWLIST names a missing file: {name}") - self.assertTrue(why.strip(), f"ALLOWLIST entry {name} has no reason") - self.assertFalse(_reaches(path, set(), SEMANTIC), - f"{name} now reaches rdna2spirv; remove its ALLOWLIST entry") - - def test_detector_on_a_synthetic_tree(self): - """A guard that accepts everything cannot pass: check direct, helper, process and silent files.""" - with tempfile.TemporaryDirectory() as tmp: - files = { - "support.py": "import rdna2spirv\nrdna2spirv.translate\n", - "test_direct.py": "import rdna2spirv\nrdna2spirv.translate\n", - "test_helper.py": "import support\nsupport.translate_lines\n", - "test_nested.py": "def f():\n import support\n return support.translate_lines\n", - "test_process.py": "import subprocess\nCMD = 'tools/rdna2spirv.py'\n", - "test_silent.py": "import spirv_mini_interp\n", - "test_unused.py": "import support\n", # an unused import reaches nothing - } - for name, text in files.items(): - with open(os.path.join(tmp, name), "w", encoding="utf-8", newline="\n") as f: - f.write(text) - self.assertEqual(offenders(tmp, allowlist={}, debt={}), [ - (os.path.join("tests", "semantic", "test_silent.py"), 1, - "imports no rdna2spirv and no helper that does"), - (os.path.join("tests", "semantic", "test_unused.py"), 1, - "imports no rdna2spirv and no helper that does")]) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/test_sgd5_effects.py b/tests/test_sgd5_effects.py deleted file mode 100644 index 5b6268f7b..000000000 --- a/tests/test_sgd5_effects.py +++ /dev/null @@ -1,254 +0,0 @@ -"""Count and resolve hand-built SGD5 effects with python -I tests/test_sgd5_effects.py.""" -from contextlib import redirect_stderr, redirect_stdout -import io -import json -import os -from pathlib import Path -import struct -import sys -import tempfile -import unittest -from unittest.mock import patch -import zlib - -sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "tools")) -import sgd5_effects -import shader_carve - - -def u32(value): - return struct.pack("/spirv: a module and an index entry per shader it validated.""" - self.asked.append(list(names)) - fallback = any(os.environ.get(v) == "1" for v in FALLBACKS) - spirv = Path(work) / "spirv" - spirv.mkdir(parents=True) - index = {} - for n in names: - if n == "ps_ij_computed" and fallback: - continue # "computed I/J pair under --f16-interp-fallback: no PerVertexKHR inputs" - (spirv / (n + ".spv")).write_bytes(b"\x03\x02\x23\x07") - (spirv / (n + ".spvasm")).write_text("; SPIR-V\n", encoding="utf-8") - index[n] = {"stage": n[:2]} - (spirv / "index.json").write_text(json.dumps(index), encoding="utf-8") - return 0 - - def run_build(self, names, env): - stubs = {"spirv_stubs": types.SimpleNamespace(generate_for_index=lambda *a: None), - "bary_fallback_gs": types.SimpleNamespace(build_for_index=lambda *a: None)} - clean = {k: v for k, v in os.environ.items() if k not in FALLBACKS} - stdout = io.StringIO() - with mock.patch.dict(os.environ, {**clean, **env}, clear=True), \ - mock.patch.dict(sys.modules, stubs), \ - mock.patch.object(self.build, "translate_tests", self.fake_translate), \ - mock.patch.object(sys, "argv", ["build.py", str(self.out), *names]), \ - contextlib.redirect_stdout(stdout): - try: - status = self.build.main() - except SystemExit as e: - status = e.code - return status, stdout.getvalue() - - def test_each_fallback_builds_the_rest_without_ps_ij_computed(self): - for var in FALLBACKS: - with self.subTest(fallback=var): - self.fresh() - status, printed = self.run_build(["cs_store", "ps_ij_computed"], {var: "1"}) - self.assertEqual(status, 0, printed) - self.assertEqual(self.asked, [["cs_store"]]) - self.assertTrue((self.out / "spirv" / "cs_store.spv").is_file()) - self.assertFalse((self.out / "spirv" / "ps_ij_computed.spv").exists()) - self.assertIn("ps_ij_computed", printed) - self.assertIn("PerVertexKHR", printed) - - def test_the_whole_list_builds_under_a_fallback(self): - # Before: "Translation did not produce validated SPIR-V for: ps_ij_computed", and an empty /spirv. - status, printed = self.run_build([], {"LEONIDA_F16_INTERP_FALLBACK": "1"}) - self.assertEqual(status, 0, printed) - self.assertNotIn("ps_ij_computed", self.asked[0]) - published = {p.stem for p in (self.out / "spirv").glob("*.spv")} - self.assertEqual(published, set(self.asked[0])) - self.assertIn("ps_interp_f16_high", published) # the f16 halves still translate under this fallback - - def test_without_a_fallback_ps_ij_computed_is_still_built(self): - status, printed = self.run_build(["cs_store", "ps_ij_computed"], {"LEONIDA_BARY_FALLBACK": "0"}) - self.assertEqual(status, 0, printed) - self.assertEqual(self.asked, [["cs_store", "ps_ij_computed"]]) - self.assertTrue((self.out / "spirv" / "ps_ij_computed.spv").is_file()) - - def test_standalone_barycentric_override_and_probe(self): - for value, probe, want in (("1", False, True), ("0", True, False), - ("", True, True), ("", False, False)): - with self.subTest(value=value, probe=probe), \ - mock.patch.dict(os.environ, {"LEONIDA_BARY_FALLBACK": value}, clear=False): - proc = SimpleNamespace(stdout=json.dumps({"barycentric_fallback": probe}) + "\n") - with mock.patch.object(self.build.subprocess, "run", return_value=proc): - self.assertIs(self.build.barycentric_fallback(), want) - - def test_a_missing_module_without_a_fallback_still_fails_the_batch(self): - keep = self.fake_translate - - def refuse(work, names): - keep(work, names) - os.remove(os.path.join(work, "spirv", "cs_store.spv")) - return 0 - self.fake_translate = refuse - try: - status, _ = self.run_build(["cs_store"], {}) - finally: - self.fake_translate = keep - self.assertIn("did not produce validated SPIR-V for: cs_store", str(status)) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/test_shader_carve.py b/tests/test_shader_carve.py deleted file mode 100644 index 24a9e7393..000000000 --- a/tests/test_shader_carve.py +++ /dev/null @@ -1,659 +0,0 @@ -"""Synthetic byte buffer DXBC container scanning, magic marker detection, and chunk boundary validation. - - python -I tests/test_shader_carve.py - -Validates tools/shader_carve.py without touching game files or proprietary assets: -- DXBC container chunk table parsing, byte offset calculation, and chunk boundary validation -- Shader model version packing and stage mapping (including unknown stage fallback) -- RPF9 entry regex marker detection, name length/character constraints, and stored-size backreference -- Candidate size filtering, raw deflate decompression error handling, and container integrity checks -- End-to-end archive carving, duplicate variant naming, filename character sanitization, and index.json output -""" -import contextlib -import hashlib -import io -import json -import mmap -import os -import struct -import subprocess -import sys -import tempfile -import unittest -from unittest import mock -import zlib - -ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) -TOOL = os.path.join(ROOT, "tools", "shader_carve.py") -sys.path.insert(0, os.path.join(ROOT, "tools")) -import shader_carve # noqa: E402 - - -def make_dxbc(chunks: list) -> bytes: - """Build a synthetic DXBC container from a list of (fourcc_bytes, payload_bytes).""" - n = len(chunks) - head = 32 + 4 * n - offsets = [] - body = bytearray() - for fourcc, payload in chunks: - offsets.append(head + len(body)) - body.extend(fourcc) - body.extend(struct.pack(" bytes: - """Build a synthetic DXIL chunk payload with packed shader model version and stage kind.""" - return struct.pack(" bytes: - """Compress data using raw DEFLATE (wbits=-15, matching shader_carve.py decompression).""" - compressor = zlib.compressobj(wbits=-15) - return compressor.compress(data) + compressor.flush() - - -def make_rpf_entry(name: str, kind: int, uncompressed_data: bytes, entry_id: int = 1, - compressed_override: bytes = None, stored_override: int = None, - size_override: int = None, mismatch_backref: bool = False) -> bytes: - """Build a synthetic RPF entry matching shader_carve.ENTRY regex.""" - compressed = compress_raw_deflate(uncompressed_data) if compressed_override is None else compressed_override - stored = len(compressed) if stored_override is None else stored_override - size = len(uncompressed_data) if size_override is None else size_override - stored_ref = (stored + 1) if mismatch_backref else stored - - hdr = ( - name.encode("latin-1") - + b"\x00" - + bytes([kind]) - + struct.pack(" 0x7e) are rejected - high_entry = make_rpf_entry("f\x80b", 1, b"DXBC" + bytes(range(40))) - self.assertIsNone(shader_carve.ENTRY.search(high_entry)) - - def test_stored_size_backreference_enforcement(self): - valid = make_rpf_entry("test_shader", 1, b"DXBC" + bytes(range(40)), mismatch_backref=False) - self.assertIsNotNone(shader_carve.ENTRY.search(valid)) - - invalid = make_rpf_entry("test_shader", 1, b"DXBC" + bytes(range(40)), mismatch_backref=True) - self.assertIsNone(shader_carve.ENTRY.search(invalid)) - - def test_stream_scanning_multiple_entries(self): - entry1 = make_rpf_entry("shader_one", 1, b"DXBC" + bytes(range(40))) - entry2 = make_rpf_entry("shader_two", 2, b"DXBC" + bytes(range(50))) - stream = entry1 + entry2 - - matches = list(shader_carve.ENTRY.finditer(stream)) - self.assertEqual(len(matches), 2) - self.assertEqual(matches[0].group(1), b"shader_one") - self.assertEqual(matches[0].start(), 0) - self.assertEqual(matches[1].group(1), b"shader_two") - self.assertEqual(matches[1].start(), len(entry1)) - - -class CandidateValidationRulesTest(unittest.TestCase): - def test_stored_size_bounds(self): - # 16 < stored < 64 << 20 - self.assertFalse(16 < 16 < 64 << 20) - self.assertTrue(16 < 17 < 64 << 20) - self.assertTrue(16 < (64 << 20) - 1 < 64 << 20) - self.assertFalse(16 < (64 << 20) < 64 << 20) - - def test_uncompressed_size_bounds(self): - # 32 < size < 256 << 20 - self.assertFalse(32 < 32 < 256 << 20) - self.assertTrue(32 < 33 < 256 << 20) - self.assertTrue(32 < (256 << 20) - 1 < 256 << 20) - self.assertFalse(32 < (256 << 20) < 256 << 20) - - def test_corrupt_deflate_raises_error(self): - corrupt_bytes = b"\xff\x00\xee\xdd\xcc\xbb\xaa\x99" * 4 - with self.assertRaises(zlib.error): - zlib.decompressobj(-15).decompress(corrupt_bytes, 100) - - def test_magic_check_failure(self): - uncompressed = b"FAIL" + bytes(range(50)) - comp = compress_raw_deflate(uncompressed) - decomp = zlib.decompressobj(-15).decompress(comp, len(uncompressed) + 1) - self.assertNotEqual(decomp[:4], b"DXBC") - - def test_size_mismatch_failure(self): - uncompressed = b"DXBC" + bytes(range(50)) - actual_len = len(uncompressed) - declared_size = actual_len + 10 - self.assertNotEqual(actual_len, declared_size) - - -class ShaderCarveCliIntegrationTest(unittest.TestCase): - def setUp(self): - self.tmp = tempfile.TemporaryDirectory() - self.dir = self.tmp.name - self.archive = os.path.join(self.dir, "test_shaders.rpf") - self.out = os.path.join(self.dir, "out") - - def tearDown(self): - self.tmp.cleanup() - - def run_carve(self, archive_path: str, out_path: str) -> subprocess.CompletedProcess: - return subprocess.run( - [sys.executable, "-I", TOOL, archive_path, out_path], - capture_output=True, - text=True, - ) - - def test_carve_synthetic_archive_with_variants_and_sanitization(self): - # 1. Valid vs shader with DXIL and PRIV chunks - dxil_vs = make_dxil_payload(0x65, 1, 40) - dxbc_vs = make_dxbc([(b"DXIL", dxil_vs), (b"PRIV", b"XBOX_PRIV_DATA_VS")]) - entry_vs = make_rpf_entry("vs_main", 1, dxbc_vs, entry_id=1) - - # 2. Valid ps shader with DXIL chunk - dxil_ps = make_dxil_payload(0x66, 0, 48) - dxbc_ps = make_dxbc([(b"DXIL", dxil_ps)]) - entry_ps = make_rpf_entry("ps_main", 0, dxbc_ps, entry_id=2) - - # 3. Duplicate variant 1 of ps_main - entry_ps_var1 = make_rpf_entry("ps_main", 0, dxbc_ps, entry_id=3) - - # 4. Duplicate variant 2 of ps_main - entry_ps_var2 = make_rpf_entry("ps_main", 0, dxbc_ps, entry_id=4) - - # 5. Valid shader with special characters in name that need sanitization - dxil_gs = make_dxil_payload(0x60, 2, 40) - dxbc_gs = make_dxbc([(b"DXIL", dxil_gs)]) - entry_special = make_rpf_entry("folder/sub:name?light*test", 2, dxbc_gs, entry_id=5) - - # 6. Valid container without DXIL chunk (PRIV only) - dxbc_nodxil = make_dxbc([(b"PRIV", b"ONLY_PRIV_CHUNK_PAYLOAD_HERE")]) - entry_nodxil = make_rpf_entry("priv_only_shader", 5, dxbc_nodxil, entry_id=6) - - # Candidate to reject 1: corrupt deflate stream - bad_deflate_entry = make_rpf_entry( - "corrupt_deflate", - 0, - b"DXBC" + bytes(range(40)), - entry_id=7, - compressed_override=b"\xff\x00\xab\xcd" * 8, - stored_override=32, - size_override=44, - ) - - # Candidate to reject 2: valid deflate, but magic is not DXBC - bad_magic_raw = b"NOPE" + bytes(range(50)) - bad_magic_entry = make_rpf_entry("bad_magic_tag", 0, bad_magic_raw, entry_id=8) - - # Candidate to reject 3: decompressed length does not match declared size - bad_size_raw = b"DXBC" + bytes(range(50)) - bad_size_entry = make_rpf_entry( - "bad_size_entry", - 0, - bad_size_raw, - entry_id=9, - size_override=len(bad_size_raw) + 20, - ) - - # Candidate to skip: stored <= 16 (silently skipped by bounds check) - skip_stored_entry = make_rpf_entry( - "skip_low_stored", - 0, - b"DXBC" + bytes(range(40)), - entry_id=10, - stored_override=16, - size_override=44, - ) - - # Candidate to skip: size <= 32 (silently skipped by bounds check) - skip_size_entry = make_rpf_entry( - "skip_low_size", - 0, - b"DXBC" + bytes(range(40)), - entry_id=11, - stored_override=25, - size_override=32, - ) - - archive_content = ( - entry_vs - + entry_ps - + entry_ps_var1 - + entry_ps_var2 - + entry_special - + entry_nodxil - + bad_deflate_entry - + bad_magic_entry - + bad_size_entry - + skip_stored_entry - + skip_size_entry - ) - - with open(self.archive, "wb") as f: - f.write(archive_content) - - res = self.run_carve(self.archive, self.out) - self.assertEqual(res.returncode, 0, res.stderr) - - # 6 valid shaders carved, 3 corrupt candidates rejected - self.assertIn("6 shaders carved, 3 candidates rejected", res.stdout) - self.assertIn("stages:", res.stdout) - self.assertIn("shader models:", res.stdout) - self.assertIn("parts:", res.stdout) - - # Verify created DXBC container files - expected_files = { - "vs_main.dxbc": dxbc_vs, - "ps_main.dxbc": dxbc_ps, - "ps_main~1.dxbc": dxbc_ps, - "ps_main~2.dxbc": dxbc_ps, - "folder_sub_name_light_test.dxbc": dxbc_gs, - "priv_only_shader.dxbc": dxbc_nodxil, - } - for filename, expected_bytes in expected_files.items(): - filepath = os.path.join(self.out, filename) - self.assertTrue(os.path.isfile(filepath), f"Missing expected output file: {filename}") - with open(filepath, "rb") as f: - self.assertEqual(f.read(), expected_bytes) - - # Verify index.json metadata - index_path = os.path.join(self.out, "index.json") - self.assertTrue(os.path.isfile(index_path)) - with open(index_path, "r", encoding="utf-8") as f: - index = json.load(f) - - self.assertEqual(len(index), 6) - - self.assertEqual(index[0]["name"], "vs_main") - self.assertEqual(index[0]["file"], "vs_main.dxbc") - self.assertEqual(index[0]["stage"], "vs") - self.assertEqual(index[0]["sm"], "6.5") - self.assertIn("DXIL", index[0]["parts"]) - self.assertIn("PRIV", index[0]["parts"]) - - self.assertEqual(index[1]["name"], "ps_main") - self.assertEqual(index[1]["file"], "ps_main.dxbc") - self.assertEqual(index[1]["stage"], "ps") - self.assertEqual(index[1]["sm"], "6.6") - - self.assertEqual(index[2]["name"], "ps_main") - self.assertEqual(index[2]["file"], "ps_main~1.dxbc") - - self.assertEqual(index[3]["name"], "ps_main") - self.assertEqual(index[3]["file"], "ps_main~2.dxbc") - - self.assertEqual(index[4]["name"], "folder/sub:name?light*test") - self.assertEqual(index[4]["file"], "folder_sub_name_light_test.dxbc") - self.assertEqual(index[4]["stage"], "gs") - self.assertEqual(index[4]["sm"], "6.0") - - self.assertEqual(index[5]["name"], "priv_only_shader") - self.assertEqual(index[5]["file"], "priv_only_shader.dxbc") - self.assertIsNone(index[5]["stage"]) - self.assertIsNone(index[5]["sm"]) - self.assertIn("PRIV", index[5]["parts"]) - - def test_carve_rejects_unfinished_deflate_stream(self): - dxbc = make_dxbc([(b"DXIL", make_dxil_payload(0x66, 5))]) - compressor = zlib.compressobj(wbits=-15) - compressed = compressor.compress(dxbc) + compressor.flush(zlib.Z_SYNC_FLUSH) - with open(self.archive, "wb") as f: - f.write(make_rpf_entry("synthetic", 1, dxbc, compressed_override=compressed)) - - res = self.run_carve(self.archive, self.out) - self.assertEqual(res.returncode, 1, res.stderr) - self.assertIn("no shaders carved", res.stderr) - self.assertIn("rejected candidates: 1", res.stderr) - self.assertEqual(os.listdir(self.out), []) - - def test_empty_carve_preserves_an_existing_index(self): - dxbc = make_dxbc([(b"PRIV", bytes(range(32)))]) - with open(self.archive, "wb") as f: - f.write(make_rpf_entry("valid", 1, dxbc)) - initial = self.run_carve(self.archive, self.out) - self.assertEqual(initial.returncode, 0, initial.stderr) - index_path = os.path.join(self.out, "index.json") - with open(index_path, "rb") as f: - previous = f.read() - with open(self.archive, "wb") as f: - f.write(b"no shader entries") - - res = self.run_carve(self.archive, self.out) - - self.assertEqual(res.returncode, 1, res.stderr) - self.assertIn("no shaders carved", res.stderr) - self.assertIn("rejected candidates: 0", res.stderr) - with open(index_path, "rb") as f: - self.assertEqual(f.read(), previous) - self.assertEqual(sorted(os.listdir(self.out)), ["index.json", "valid.dxbc"]) - - def test_carve_rejects_incomplete_parts_and_continues(self): - valid = make_dxbc([(b"PRIV", bytes(range(32)))]) - short_directory = bytearray(valid) - struct.pack_into("= (3, 11), - "requires the CPython Py_buffer ABI") - def test_refusal_and_invalid_offsets_fall_back_once(self): - for offset, error in ((ctypes.c_size_t(-1).value, None), (1, None), (None, OSError())): - scan = mock.Mock(return_value=offset, side_effect=error) - with (self.subTest(offset=offset, error=error), - mock.patch.dict(os.environ, LEONIDA_SHADER_CARVE_NATIVE="1"), - mock.patch.object(accel, "_load_native", return_value=scan), - mapped(b"\x00\x00abc" + trailer()) as mapping, - accel.entry_search(mapping, shader_carve.ENTRY) as search): - self.assertEqual(search(0).span(), (2, len(mapping))) - self.assertIsNone(search(3)) - scan.assert_called_once() - self.assertTrue(mapping.closed) - - -class NativeParityTest(unittest.TestCase): - @classmethod - def setUpClass(cls): - if sys.implementation.name != "cpython" or sys.version_info < (3, 11): - raise unittest.SkipTest("requires the CPython Py_buffer ABI") - try: - scan = accel._load_native(ctypes) - except (OSError, AttributeError) as error: - if os.environ.get("LEONIDA_TEST_REQUIRE_SHADER_CARVE_NATIVE") == "1": - raise - raise unittest.SkipTest(f"build the optional release library first: {error}") from error - if scan is None: - raise unittest.SkipTest("native scanner is unsupported on this platform") - cls.scan = staticmethod(scan) - - def test_raw_search_parity(self): - rng = random.Random(19278) - samples = [b"", b"xy" + trailer(), b"abc" + trailer()[:-1], - b"a" * 200 + trailer(), b"A" * 201 + trailer(), - b"abc" + trailer(repeat=b"1235") + b"xyz" + trailer(), - b"abc\x00\x00" + bytes(12) + b"second" + trailer(), - b"\x20!~A" + trailer(), b"\x7f!~A" + trailer(), - b"\xff!~A" + trailer()] - samples.extend(b"\x80" * offset + b"!~A" + trailer() for offset in range(32)) - for _ in range(1500): - sample = bytearray() - for _ in range(rng.randrange(1, 6)): - word = rng.randbytes(4) - header = trailer(word, repeat=word if rng.randrange(2) else rng.randbytes(4)) - name = bytes(rng.choices(range(0x21, 0x7f), k=rng.randrange(240))) - sample.extend(rng.randbytes(rng.randrange(40)) + name + header[:rng.randrange(12, 19)]) - samples.append(bytes(sample)) - - for case, data in enumerate(samples): - buffer = ctypes.create_string_buffer(data) - positions = range(len(data) + 1) if case < 42 else ( - 0, len(data), *(rng.randrange(len(data)) for _ in range(10))) - for pos in positions: - expected = shader_carve.ENTRY.search(data, pos) - self.assertEqual(self.scan(buffer, len(data), pos), - len(data) if expected is None else expected.start(), (case, pos)) - - def test_mmap_and_carve_output_and_errors(self): - dxbc = make_dxbc([(b"PRIV", bytes(range(96)))]) - valid = make_rpf_entry("synthetic", 1, dxbc) - invalid = make_rpf_entry("broken", 1, dxbc, compressed_override=b"\xff" * 30) - with tempfile.TemporaryDirectory() as directory: - root = Path(directory) - archive = root / "input" - for case, (data, expected_status) in enumerate(((b"\x00" + invalid + valid * 2, 0), - (invalid, 1), (b"\x00" * 17, 1), (b"", 2))): - with self.subTest(case=case): - archive.write_bytes(data) - py_out, native_out = root / f"py{case}", root / f"native{case}" - reference = run_carve(archive, py_out, False) - scan = mock.Mock(wraps=self.scan) - with mock.patch.object(accel, "_load_native", return_value=scan): - native = run_carve(archive, native_out, True) - self.assertEqual(reference[0], expected_status) - self.assertEqual(native, reference) - self.assertEqual({path.name: path.read_bytes() for path in py_out.glob("*")}, - {path.name: path.read_bytes() for path in native_out.glob("*")}) - self.assertEqual(scan.call_count, (2, 1, 1, 0)[case]) - archive.unlink() - - def test_randomized_archive_output(self): - rng = random.Random(4459) - archive_bytes = bytearray() - for case in range(1500): - archive_bytes.extend(rng.randbytes(rng.randrange(512)) + b"\x00") - name = f"entry_{rng.randrange(40):02d}" - dxbc = make_dxbc([(b"PRIV", rng.randbytes(rng.randrange(32, 256)))]) - options = ({}, {"compressed_override": b"\xff" * 30}, {"stored_override": 1}, - {"size_override": len(dxbc) + 1}, {"mismatch_backref": True}) - archive_bytes.extend(make_rpf_entry(name, rng.randrange(256), dxbc, case, - **rng.choice(options))) - with tempfile.TemporaryDirectory() as directory: - root = Path(directory) - archive = root / "input" - archive.write_bytes(archive_bytes) - reference = run_carve(archive, root / "py", False) - scan = mock.Mock(wraps=self.scan) - with mock.patch.object(accel, "_load_native", return_value=scan): - native = run_carve(archive, root / "native", True) - self.assertEqual(reference[0], 0) - self.assertEqual(native, reference) - self.assertGreater(scan.call_count, 1000) - self.assertEqual({path.name: path.read_bytes() for path in (root / "py").iterdir()}, - {path.name: path.read_bytes() for path in (root / "native").iterdir()}) - - -def benchmark(): - rng = random.Random(19278) - dxbc = make_dxbc([(b"PRIV", rng.randbytes(512))]) - entry = make_rpf_entry("synthetic", 1, dxbc) - with tempfile.TemporaryDirectory() as directory: - root = Path(directory) - archive = root / "input" - for label, data, expected in (("sparse", (rng.randbytes(8 << 20) + b"\x00" + entry) * 8, 8), - ("dense", entry * 512, 512)): - archive.write_bytes(data) - scan_times, carve_times = {}, {} - for native in (False, True): - scan_samples, carve_samples = [], [] - for repeat in range(3): - with (mock.patch.dict(os.environ, LEONIDA_SHADER_CARVE_NATIVE=str(int(native))), - mapped(data) as mapping, accel.entry_search(mapping, shader_carve.ENTRY) as search): - start = perf_counter() - count, pos = 0, 0 - while (match := search(pos)) is not None: - count += 1 - pos = match.end() + int.from_bytes(match[3], "little") - scan_samples.append(perf_counter() - start) - if count != expected: - raise RuntimeError(f"{label}: expected {expected} scanner matches, got {count}") - start = perf_counter() - status, stdout, stderr = run_carve(archive, root / f"{label}-{native}-{repeat}", native) - carve_samples.append(perf_counter() - start) - if status != 0 or not stdout.startswith(f"{expected} shaders carved, 0 candidates rejected"): - raise RuntimeError(f"{label}: unexpected carve result: {stdout}{stderr}") - scan_times[native], carve_times[native] = median(scan_samples), median(carve_samples) - for phase, times in (("scan", scan_times), ("full carve", carve_times)): - print(f"{label} {phase}: {times[False]:.6f}s Python / {times[True]:.6f}s native" - f" = {times[False] / times[True]:.2f}x") - - -if __name__ == "__main__": - if sys.argv[1:] == ["--benchmark"]: - if accel._load_native(ctypes) is None: - sys.exit("native scanner is unsupported on this platform") - benchmark() - else: - unittest.main() diff --git a/tests/test_shader_checks.py b/tests/test_shader_checks.py deleted file mode 100644 index 20758886b..000000000 --- a/tests/test_shader_checks.py +++ /dev/null @@ -1,1167 +0,0 @@ -"""Exercise the synthetic Vulkan test runner without a Vulkan device.""" -import ast -import contextlib -import io -import json -import re -import struct -import subprocess -from pathlib import Path -import sys -import tempfile -import unittest -from unittest.mock import patch - -sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "runtime" / "test" / "shaders")) -import check - - -GOOD_FMT = struct.pack("<64I", *check.FMT_1010102_WORDS, *[0xEEEEEEEE] * 48) -GOOD_XY_XYZ = struct.pack("<192I", *check.FMT_XY_XYZ_WORDS, *[0xEEEEEEEE] * 108) -GOOD_TBUFFER_STORE = struct.pack("<192I", *check.TBUFFER_STORE_WORDS, *[0xEEEEEEEE] * 140) -FULL_WAVE = ((0, "compute subgroup size: 64\n0 mismatches\n"), - (0, "compute subgroup size: 64\nout[0..7] = 32 16 24 40 8 48 4008636142 4008636142\n")) - -# The other wave64-only dump tests (#73's cs_wm_*, the cs_w64x_* cross-half tests): name -> expected out[] words. -WAVE64_DUMPS = {n: w for n, w in check.CS_DUMPS + check.W64X_DUMPS + check.W64X_PARTIAL - if n not in (*check.WAVE32_DUMPS, "cs_wave64_ballot")} -# A group smaller than a wave can't ask for full subgroups: it asks for subgroup size 64 and reads the device's range. -PARTIAL = {n for n, _ in check.W64X_PARTIAL} -WAVE32_WORDS = {n: w for n, w in check.CS_DUMPS if n in check.WAVE32_DUMPS and n not in ("cs_store", "cs_smem_soffset_imm")} - - -# All check.py cases, including the six vk_store_test shaders and the three mesh fixtures, and TEST-184's -# vk_store_test "words" fixtures and image_get_lod draws. -TOTAL = (len(check.COMPUTE) + 7 + len(check.CS_DUMPS) + len(check.W64X_DUMPS) + len(check.W64X_PARTIAL) + 6 - + len(check.PIXEL_TESTS) + len(check.CLIP_TESTS) + len(check.BOUNDS) + len(check.GLOBAL_OFFSET) - + len(check.MIP_TEST_PASSES) + len(check.GRADIENT_TESTS) - + len(check.STORE_WORDS) + len(check.GET_LOD_TESTS) - + len(check.TEXTURE_CONSTANTS) + 16) # three mesh fixtures, ps_tex, ps_imgatomic, ps_table_fetch, six compute fixtures, - # ps_ssharp, vs_base_ids, main's standalone cs_fmt_d16_xyz / cs_heap_init dumps (net one more case) and cs_fmt_all -CVT = {bits: [u, s] for bits, u, s in check.CVT_F32_SAT_CASES} - - -def words_output(name, flip=None): - """What vk_store_test prints in "words" mode when the shader left check.store_words(name) in the three images; - flip = (image, word index) changes one word.""" - lines = ["device: fake"] - for image, words in zip(check.STORE_IMAGES, check.store_words(name)): - words = [w ^ 1 if flip == (image, i) else w for i, w in enumerate(words)] - lines.append(f"{image} words: " + " ".join(f"{w:#010x}" for w in words)) - return "\n".join(lines) + "\n" - - -def cvt_answer(env, wrong_for=None): - """A device running cs_cvt_f32_sat on the word in VKC_SGPRS (s4 reads 0 without it).""" - bits = int((env or {}).get("VKC_SGPRS", "0"), 0) - words = [0xBAD, 0xBAD] if bits == wrong_for else CVT.get(bits, [0, 0]) - return 0, "out[0..7] = " + " ".join(map(str, words + [0xEEEEEEEE] * 6)) + "\n" - - -class Wave64Checks(unittest.TestCase): - def run_checks(self, wavemask, ballot, *, missing_ballot=False, emulated=False, fmt=(0, GOOD_FMT)): - def harness(_tool, shader, *args, env=None): - name = Path(shader).stem - if name == "cs_fmt_1010102": - self.assertEqual(args, ("1", "dump")) - self.fmt_env, dump = env, Path(env["VKC_DUMP"]) - self.assertFalse(dump.exists()) - if fmt[1] is not None: - dump.write_bytes(fmt[1]) - return fmt[0], "out[0..7] = 0 0 0 0 0 0 0 0\n" # stdout is not the oracle - if name == "cs_fmt_sint32": - self.assertEqual((args, env["VKC_OUT_WORDS"]), (("1", "dump"), "64")) - Path(env["VKC_DUMP"]).write_bytes(struct.pack("<64I", *check.FMT_SINT32_WORDS)) - return 0, "" - if name == "cs_fmt_d16_xyz": - self.assertEqual((args, env["VKC_OUT_WORDS"]), (("1", "dump"), "80")) - Path(env["VKC_DUMP"]).write_bytes(struct.pack("<80I", *check.FMT_D16_XYZ_WORDS)) - return 0, "" - if name == "cs_fmt_int_narrow": - self.assertEqual((args, env["VKC_OUT_WORDS"]), (("1", "dump"), "136")) - Path(env["VKC_DUMP"]).write_bytes(struct.pack("<136I", *check.FMT_INT_NARROW_WORDS)) - return 0, "" - if name in ("cs_fmt_xy_xyz", "cs_tbuffer_store"): - self.assertEqual((args, env["VKC_OUT_WORDS"]), (("1", "dump"), "192")) - Path(env["VKC_DUMP"]).write_bytes(GOOD_XY_XYZ if name == "cs_fmt_xy_xyz" else GOOD_TBUFFER_STORE) - return 0, "out[0..7] = 0 0 0 0 0 0 0 0\n" - if name == "cs_fmt_all": - self.assertEqual((args, env["VKC_OUT_WORDS"]), (("1", "dump"), str(len(check.FMT_ALL_WORDS)))) - Path(env["VKC_DUMP"]).write_bytes(struct.pack(f"<{len(check.FMT_ALL_WORDS)}I", *check.FMT_ALL_WORDS)) - return 0, "out[0..7] = 0 0 0 0 0 0 0 0\n" - if name == "cs_heap_init": - # The seeded words come back only if check.py wrote the init file and sized the buffer for it. - path = (env or {}).get("VKC_HEAP_INIT") - seeded = bool(path) and Path(path).read_bytes() == check.HEAP_INIT_FILE and \ - env.get("VKC_OUT_WORDS") == "68" - words = check.HEAP_INIT_EXPECTED if seeded else [0xEEEEEEEE] * 8 - return 0, "out[0..7] = " + " ".join(map(str, words)) + "\n" - if name == "cs_user_sgprs": - # The seeded words come back only if check.py passed them in VKC_SGPRS. - seeded = (env or {}).get("VKC_SGPRS") == check.USER_SGPRS_ENV["VKC_SGPRS"] - words = check.USER_SGPRS_WORDS if seeded else [0] * 4 + [0xEEEEEEEE] * 4 - return 0, "out[0..7] = " + " ".join(map(str, words)) + "\n" - if name == "cs_cvt_f32_sat": - return cvt_answer(env) - if name == "cs_fma_fused": - # The operands come in through VKC_SGPRS; without them the fused words are not produced. - self.assertEqual((env or {}).get("VKC_SGPRS"), check.FMA_FUSED_ENV["VKC_SGPRS"]) - return 0, "out[0..7] = " + " ".join(map(str, check.FMA_FUSED)) + "\n" - self.assertNotIn("VKC_SGPRS", env or {}) - if name in PARTIAL: - self.assertNotIn("--require-wave64", args) - words = (WAVE64_DUMPS[name] + [0] * 8)[:8] - narrow = wavemask[0] == 77 - return 0, f"device: gpu (subgroup 32..{32 if narrow else 64})\nout[0..7] = " + " ".join(map(str, words)) + "\n" - if emulated: - self.assertNotIn("--require-wave64", args) - if name in WAVE64_DUMPS: - words = (WAVE64_DUMPS[name] + [0] * 8)[:8] - return 0, "out[0..7] = " + " ".join(map(str, words)) + "\n" - if name == "cs_wavemask": - return 0, "0 mismatches\n" - if name == "cs_wave64_ballot": - return 0, "out[0..7] = 32 16 24 40 8 48 4008636142 4008636142\n" - if name in WAVE64_DUMPS: - self.assertIn("--require-wave64", args) - if wavemask[0] == 77: # same device as cs_wavemask: no 64-wide subgroups - return wavemask - words = (WAVE64_DUMPS[name] + [0] * 8)[:8] - return 0, "compute subgroup size: 64\nout[0..7] = " + " ".join(map(str, words)) + "\n" - if name in ("cs_wavemask", "cs_wave64_ballot"): - self.assertIn("--require-wave64", args) - if name == "cs_wavemask": - return wavemask - self.assertFalse(missing_ballot, "missing shader was sent to the harness") - return ballot - self.assertNotIn("--require-wave64", args) - if name == "cs_bounds": - # 0x12345678, the in-bounds reload, the OOB load's 0, then the untouched 0xEEEEEEEE fill. - return 0, "out[0..7] = 305419896 305419896 0 4008636142 4008636142 4008636142 4008636142 4008636142\n" - if name == "cs_cmpx_class_f32": - return 0, "out[0..7] = " + " ".join(map(str, check.CMPX_CLASS_WORDS)) + "\n" - if name in {n for n, _, _ in check.GLOBAL_OFFSET}: - groups, words = next((g, w) for n, g, w in check.GLOBAL_OFFSET if n == name) - self.assertEqual(args[0], groups) - return 0, "out[0..7] = " + " ".join(map(str, words)) + "\n" - if name in dict(check.BOUNDS): # the SMEM / raw MUBUF rule tests: their words, then the 0xee fill - words = (dict(check.BOUNDS)[name] + [0xEEEEEEEE] * 8)[:8] - return 0, "out[0..7] = " + " ".join(map(str, words)) + "\n" - if name == "cs_cvt_pk_u8": - return 0, "out[0..7] = " + " ".join(map(str, check.CVT_PK_U8_WORDS)) + "\n" - if name == "cs_pk_mul_lo_const": - return 0, "out[0..7] = " + " ".join(map(str, check.PK_MUL_LO_WORDS)) + "\n" - if name == "cs_store": - return 0, "out[0..7] = " + " ".join(map(str, (check.CS_STORE + [0] * 8)[:8])) + "\n" - if name == "cs_smem_soffset_imm": - return 0, "out[0..7] = " + " ".join(map(str, check.CS_SMEM)) + "\n" - if name in WAVE32_WORDS: # wave32 dumps run on any subgroup size - return 0, "out[0..7] = " + " ".join(map(str, (WAVE32_WORDS[name] + [0] * 8)[:8])) + "\n" - if name == "cs_workgroup_yz": # #186: vk_compute_test's 2x3x4 Y/Z histogram line - return 0, "2x3x4 workgroup Y/Z: 0 mismatches\n" - if name in ("cs_imgstore", "cs_imgload", "cs_imgload_tfe", "cs_imgload_d16", "cs_imgload_d16_tfe", - "cs_sample_lz_int_d16"): # vk_store_test checks - return 0, "0 bad\n0 bad\n0 bad\n" - if name in check.STORE_WORDS: # vk_store_test "words": the three images, judged by check.py - self.assertEqual(args, ("words",)) - return 0, words_output(name) - return 0, "0 mismatches\n" - - with tempfile.TemporaryDirectory() as tmp: - spirv = Path(tmp) / "spirv" - spirv.mkdir() - (spirv / "cs_wavemask.spv").touch() - for name in (*WAVE64_DUMPS, *check.STORE_WORDS): - (spirv / f"{name}.spv").touch() - if not missing_ballot: - (spirv / "cs_wave64_ballot.spv").touch() - output = io.StringIO() - with (patch.object(sys, "argv", ["check.py", tmp]), patch.object(check, "run", side_effect=harness), - patch.object(check, "clip_test", return_value=""), - patch.object(check, "pixel_test", return_value=""), patch.object(check, "texture_mip_test", return_value=""), - patch.object(check, "bindless_test", return_value=""), patch.object(check, "W64_EMULATED", emulated), - patch.object(check, "texture_gradient_a16_test", return_value=""), - patch.object(check, "texture_constant_test", return_value=""), - patch.object(check, "base_ids_test", return_value=""), - patch.object(check, "get_lod_test", return_value=""), - patch.object(check, "sampler_test", return_value=""), - patch.object(check, "table_fetch_test", return_value=""), - contextlib.redirect_stdout(output)): - status = check.main() - return status, output.getvalue() - - def test_wave32_only_device_skips_full_wave_checks(self): - unsupported = 77, "full 64-wide compute subgroups unavailable\n" - status, out = self.run_checks(unsupported, unsupported) - self.assertEqual(status, 0, out) - self.assertRegex(out, r"cs_wavemask +SKIP") - self.assertRegex(out, r"cs_wave64_ballot +SKIP") - self.assertRegex(out, r"cs_exec64 +ok") - self.assertIn(f"{TOTAL - 5 - len(WAVE64_DUMPS)} of {TOTAL} pass, {5 + len(WAVE64_DUMPS)} skipped", out) - - def test_full_wave_checks_pass_with_expected_results(self): - status, out = self.run_checks(*FULL_WAVE) - self.assertEqual(status, 0, out) - self.assertRegex(out, r"cs_wave64_ballot +ok") - self.assertIn(f"{TOTAL - 3} of {TOTAL} pass, 3 skipped", out) - - def test_emulated_wave64_runs_without_a_64_wide_subgroup(self): - # LEONIDA_W64_EMULATE=1: the shaders were translated with --wave64-emulate, so no wave64 test asks the - # harness for a 64-wide subgroup, and a 32-wide device runs them all. - unsupported = 77, "full 64-wide compute subgroups unavailable\n" - status, out = self.run_checks(unsupported, unsupported, emulated=True) - self.assertEqual(status, 0, out) - self.assertRegex(out, r"cs_w64x_wg128_branches +ok") - self.assertIn(f"{TOTAL - 3} of {TOTAL} pass, 3 skipped", out) - - def test_ballot_mismatches_and_harness_errors_fail(self): - wavemask = 0, "compute subgroup size: 64\n0 mismatches\n" - for ballot, detail in ( - ((0, "compute subgroup size: 64\nout[0..7] = 16 16 0 64 0 64 0 0\n"), "exit 0"), - ((0, "compute subgroup size: 64\nout[0..7] = corrupt\n"), "exit 0"), - ((0, "out[0..7] = 32 16 24 40 8 48 0 0\n"), "64-wide subgroup was not confirmed"), - ((1, "Vulkan pipeline failed\n"), "exit 1"), - ): - with self.subTest(ballot=ballot): - status, out = self.run_checks(wavemask, ballot) - self.assertEqual(status, 1, out) - self.assertRegex(out, rf"cs_wave64_ballot +{detail}") - self.assertIn(f"{TOTAL - 4} of {TOTAL} pass, 3 skipped", out) - - def test_fmt_1010102_compares_the_whole_dump(self): - words = list(struct.unpack("<64I", GOOD_FMT)) - for fmt, detail in ( - ((0, struct.pack("<64I", *words[:15], 0xE00003FF, *words[16:])), "word 15: expected 0xffe00003, got 0xe00003ff"), - ((0, struct.pack("<64I", *words[:63], 0)), "word 63: expected 0xeeeeeeee, got 0x00000000"), - ((0, GOOD_FMT[:-4]), "expected 256 dump bytes, got 252"), - ((0, GOOD_FMT + bytes(4)), "expected 256 dump bytes, got 260"), - ((0, None), "no VKC_DUMP file written"), - ((1, GOOD_FMT), "exit 1"), - ): - with self.subTest(detail=detail): - status, out = self.run_checks(*FULL_WAVE, fmt=fmt) - self.assertEqual(status, 1, out) - self.assertRegex(out, rf"cs_fmt_1010102 +{detail}") - self.assertIn(f"{TOTAL - 4} of {TOTAL} pass, 3 skipped", out) - - def test_fmt_1010102_child_env_is_private(self): - parent = {"VK_DRIVER_FILES": "driver.json", "VKC_OUT_WORDS": "128", "VKC_DUMP": "caller.bin"} - with patch.dict(check.os.environ, parent): - status, out = self.run_checks(*FULL_WAVE) - for key, value in parent.items(): - self.assertEqual(check.os.environ[key], value) - self.assertEqual(status, 0, out) - self.assertRegex(out, r"cs_fmt_1010102 +ok") - self.assertEqual((self.fmt_env["VK_DRIVER_FILES"], self.fmt_env["VKC_OUT_WORDS"]), ("driver.json", "64")) - self.assertNotEqual(self.fmt_env["VKC_DUMP"], parent["VKC_DUMP"]) - self.assertFalse(Path(self.fmt_env["VKC_DUMP"]).exists()) - - def test_missing_wave64_fixture_fails_even_on_wave32(self): - unsupported = 77, "full 64-wide compute subgroups unavailable\n" - status, out = self.run_checks(unsupported, unsupported, missing_ballot=True) - self.assertEqual(status, 1, out) - self.assertIn("missing cs_wave64_ballot.spv", out) - - -class FloatToIntSweep(unittest.TestCase): - """check.cvt_f32_sat_test sends each input in VKC_SGPRS and judges both words of every dispatch.""" - - def sweep(self, wrong_for=None): - sent = [] - - def harness(_tool, shader, *_args, env=None): - self.assertEqual(Path(shader).stem, "cs_cvt_f32_sat") - sent.append(int(env["VKC_SGPRS"], 0)) - return cvt_answer(env, wrong_for) - - with patch.object(check, "run", side_effect=harness): - return check.cvt_f32_sat_test("tools", "spirv"), sent - - def test_every_input_is_sent_and_exact(self): - problem, sent = self.sweep() - self.assertEqual(problem, "") - self.assertEqual(sent, [bits for bits, _, _ in check.CVT_F32_SAT_CASES]) - - def test_one_wrong_input_fails_and_is_named(self): - problem, _ = self.sweep(wrong_for=0x4F000000) - self.assertIn("1 of 16 inputs wrong", problem) - self.assertIn("0x4f000000", problem) - - def test_a_device_that_cannot_pin_the_wave_size_skips_instead_of_failing(self): - # Before: on a 4..32 device (Apple under MoltenVK) every dispatch came back as unpinned_subgroup_skip's Skip, - # and the sweep reported it as "16 of 16 inputs wrong, first 0x00000000: SKIP (...)", a failure. - calls = [] - - def harness(_tool, _shader, *_args, env=None): - calls.append(env.get("VKC_SUBGROUP_SIZE")) - return 1, "compute subgroup size: 32 not available\n" - - with patch.object(check, "run", side_effect=harness), \ - patch.object(check, "subgroup_size", return_value=32): - problem = check.cvt_f32_sat_test("tools", "spirv") - self.assertIsInstance(problem, check.Skip) - self.assertIn("can't run this shader at 32 lanes", problem) - self.assertNotIn("inputs wrong", problem) - self.assertEqual(calls, ["32"]) # the first dispatch decides; the other 15 would say the same - - def test_inputs_match_the_interpreter_test(self): - # The GPU sweep and tests/semantic/test_float_to_int.py must judge the same inputs the same way. - src = (Path(__file__).resolve().parent / "semantic" / "test_float_to_int.py").read_text(encoding="utf-8") - cases = next(ast.literal_eval(n.value) for n in ast.walk(ast.parse(src)) - if isinstance(n, ast.Assign) and getattr(n.targets[0], "id", "") == "CASES") - self.assertEqual(tuple(cases), check.CVT_F32_SAT_CASES) - - -class MeshWorkgroupChecks(unittest.TestCase): - def test_every_group_has_its_own_pixel(self): - pixels = [struct.pack("<4f", 32 * g, 32 * g + 1, 32 * g + 31, 1) for g in range(24)] # #209's v5 - self.assertEqual(check.check_mesh_v5(b"".join(pixels)), "") - pixels[6], pixels[2] = pixels[2], pixels[6] - self.assertIn("2/24 mismatches; first (0,1,0)", check.check_mesh_v5(b"".join(pixels))) - self.assertIn("384 bytes", check.check_mesh_v5(b"".join(pixels[:-1]))) - - def test_a_previous_groups_file_cannot_pass_the_mesh_check(self): - with tempfile.TemporaryDirectory() as tmp: - spirv = Path(tmp) - (spirv / "ms_v5_workgroup.spv").touch() - (spirv / "fs_passthru.spv").touch() - raw = spirv / "groups.raw" - raw.write_bytes(b"".join(struct.pack("<4f", 32 * g, 32 * g + 1, 32 * g + 31, 1) - for g in range(24))) - with patch.object(check, "run", return_value=(0, "")): - self.assertIn("missing readback: groups.raw", check.mesh_v5_test(tmp, spirv, raw)) - self.assertFalse(raw.exists()) - - def test_readback_cleanup_failure_does_not_start_the_harness(self): - with tempfile.TemporaryDirectory() as tmp: - raw = Path(tmp) / "groups.raw" - raw.mkdir() - with patch.object(check, "run") as launch: - status, message = check.run_readback(raw, launch, "unused") - launch.assert_not_called() - self.assertEqual(status, 1) - self.assertIn("could not remove the previous readback", message) - self.assertTrue(raw.is_dir()) - - -MESH_GRADIENT = [((i % 64 + .5) / 64, (i // 64 + .5) / 64, .5, 1.0) for i in range(4096)] - - -class MeshGradientChecks(unittest.TestCase): - """ms_w64x_ballot and ms_wave_info_s3 with a fake vk_harness that writes `pixels` and reports `subgroups`.""" - - def run_mesh(self, name, pixels, subgroups): - def harness(cmd, **_kw): - Path(cmd[3]).write_bytes(b"".join(struct.pack("<4f", *p) for p in pixels)) - return subprocess.CompletedProcess(cmd, 0, "", f"device: fake (subgroup {subgroups})\n") - - with tempfile.TemporaryDirectory() as tmp: - for shader in (name, "fs_passthru"): - (Path(tmp) / f"{shader}.spv").touch() - with patch.object(check, "W64_EMULATED", False), \ - patch.object(check.subprocess, "run", side_effect=harness): - return check.mesh_w64x_test(tmp, tmp, name) - - def test_a_nan_readback_fails(self): - nan = float("nan") - for name in ("ms_w64x_ballot", "ms_wave_info_s3"): - problem = self.run_mesh(name, [(nan, nan, nan, nan)] * 4096, "32..64") - self.assertIn("4096 of 4096 pixels differ", problem, name) - pixels = list(MESH_GRADIENT) - pixels[5] = (pixels[5][0], pixels[5][1], nan, 1.0) - self.assertIn("1 of 4096 pixels differ", self.run_mesh(name, pixels, "32..64"), name) - - def test_the_gradient_passes(self): - for name in ("ms_w64x_ballot", "ms_wave_info_s3"): - self.assertEqual(self.run_mesh(name, MESH_GRADIENT, "32..64"), "", name) - - def test_wave_info_is_judged_on_a_32_wide_device(self): - # Its wave id is LocalInvocationIndex >> 6, whatever the subgroup width; only the ballot needs 64 lanes. - self.assertEqual(self.run_mesh("ms_wave_info_s3", MESH_GRADIENT, "32..32"), "") - wrong = [(r, g, 0.0, a) for r, g, _, a in MESH_GRADIENT] - self.assertIn("4096 of 4096 pixels differ", self.run_mesh("ms_wave_info_s3", wrong, "32..32")) - self.assertIsNone(self.run_mesh("ms_w64x_ballot", MESH_GRADIENT, "32..32")) - - -class PixelDeviceLimits(unittest.TestCase): - """pixel_test with a fake harness: the device's limits decide SKIP instead of a failure.""" - - def run_pixel(self, name, code, out, data=b""): - def harness(_tool, _vs, _fs, raw, env=None): - if data: - Path(raw).write_bytes(data) - return code, out - - with tempfile.TemporaryDirectory() as tmp: - spirv = Path(tmp) / "spirv" - spirv.mkdir() - (spirv / f"{name}.spv").touch() - with patch.object(check, "run", side_effect=harness): - return check.pixel_test(tmp, str(spirv), name) - - @staticmethod - def bitmask_pixels(subgroup): - lanes = min(subgroup, 32) - return b"".join(struct.pack("<4I", i % lanes, (i % lanes) ^ 9, (((i % lanes) & 5) | 16) ^ 1, 0) - for i in range(64 * 64)) - - def test_shader_needing_missing_barycentrics_skips(self): - problem = self.run_pixel("ps_bary", 77, - "unsupported: ps_bary.spv reads BaryCoordKHR and the device has no " - "VK_KHR_fragment_shader_barycentric\n") - self.assertIsInstance(problem, check.Skip) - self.assertIn("BaryCoordKHR", problem) - - def test_other_harness_errors_still_fail(self): - problem = self.run_pixel("ps_ops", 1, "FAILED vkCreateDevice -> -9\n") - self.assertNotIsInstance(problem, check.Skip) - self.assertIn("vk_harness failed", problem) - - def test_nan_payload_exception_is_limited_to_kosmickrisp(self): - payloads = self.readlane_pixels((0x7fc12345, 0xffc54321, 0x3f800000, 0x3f000000)) - canonical = self.readlane_pixels((0x7fc00000, 0x7fc00000, 0x3f800000, 0x3f000000)) - for driver in ("driver: KosmicKrisp\n", "driver: MoltenVK\n", ""): - with self.subTest(driver=driver): - out = f"device: Apple M1 Pro (subgroup 32..32)\n{driver}ok 64x64\n" - self.assertEqual(self.run_pixel("ps_nan_payload", 0, out, payloads), "") - problem = self.run_pixel("ps_nan_payload", 0, out, canonical) - if driver == "driver: KosmicKrisp\n": - self.assertEqual(problem, "") - else: - self.assertIn("unexpected words", problem) - - def test_kosmickrisp_still_rejects_bad_nan_and_finite_words(self): - out = "driver: KosmicKrisp\nok 64x64\n" - for words in ((0x7fc00001, 0x7fc00000, 0x3f800000, 0x3f000000), - (0x7f800000, 0x7fc00000, 0x3f800000, 0x3f000000), - (0x7fc00000, 0x7fc00000, 0x7fc00000, 0x3f000000)): - with self.subTest(words=words): - problem = self.run_pixel("ps_nan_payload", 0, out, self.readlane_pixels(words)) - self.assertIn("unexpected words", problem) - - def test_bitmask_perm_skips_below_32_lanes(self): - out = "device: fake (subgroup 8..8)\nok 64x64\n" - problem = self.run_pixel("ps_bitmask_perm", 0, out, data=self.bitmask_pixels(8)) - self.assertIsInstance(problem, check.Skip) - self.assertIn("narrower than 32 lanes", problem) - - def test_bitmask_perm_is_judged_at_32_lanes(self): - out = "device: fake (subgroup 32..32)\nok 64x64\n" - self.assertEqual(self.run_pixel("ps_bitmask_perm", 0, out, data=self.bitmask_pixels(32)), "") - - def test_bitmask_perm_skips_when_the_frame_is_short_below_32_lanes(self): - out = "device: fake (subgroup 8..8)\nok 64x64\n" - problem = self.run_pixel("ps_bitmask_perm", 0, out, data=b"short") - self.assertIsInstance(problem, check.Skip) - self.assertIn("narrower than 32 lanes", problem) - - def test_bitmask_perm_skips_without_a_subgroup_width(self): - problem = self.run_pixel("ps_bitmask_perm", 0, "ok 64x64\n", data=self.bitmask_pixels(32)) - self.assertIsInstance(problem, check.Skip) - self.assertIn("no subgroup width", problem) - - @staticmethod - def readlane_pixels(words=(0x40000079, 0x40000010, 0x40000064, 0x400000be)): - return struct.pack("<4I", *words) * (64 * 64) - - def test_wave64_pixel_shader_skips_where_64_cannot_be_required(self): - out = "device: fake (subgroup 8..8)\nok 64x64\n" - problem = self.run_pixel("ps_w64x_readlane", 0, out, data=self.readlane_pixels((0, 0, 0, 0))) - self.assertIsInstance(problem, check.Skip) - self.assertIn("64-wide fragment subgroup", problem) - self.assertIn("8..8", problem) - - def test_wave64_pixel_shader_skips_where_the_harness_says_64_is_not_available(self): - # vk_harness.cpp's line for a size the device could not take; it must not read as "64 was required". - out = "device: fake (subgroup 32..32)\nfragment subgroup size: 64 not available\nok 64x64\n" - problem = self.run_pixel("ps_w64x_readlane", 0, out, data=self.readlane_pixels()) - self.assertIsInstance(problem, check.Skip) - self.assertIn("64-wide fragment subgroup", problem) - - def test_wave64_pixel_shader_is_judged_when_64_was_required(self): - # The line as vk_harness.cpp prints it when the size took effect: "fragment subgroup size: %u\n". - out = "device: fake (subgroup 32..64)\nfragment subgroup size: 64\nok 64x64\n" - self.assertEqual(self.run_pixel("ps_w64x_readlane", 0, out, data=self.readlane_pixels()), "") - problem = self.run_pixel("ps_w64x_readlane", 0, out, data=self.readlane_pixels((0, 0, 0, 0))) - self.assertNotIsInstance(problem, check.Skip) - self.assertIn("pixels differ", problem) - - def test_wide_pixel_skip_reads_the_line_vk_harness_prints(self): - # Keeps the check and the harness in step: the format string is read from vk_harness.cpp, not written here. - harness = Path(__file__).resolve().parents[1] / "runtime" / "test" / "vk_harness.cpp" - source = harness.read_text(encoding="utf-8") - formats = re.findall(r'"(fragment subgroup size: %u[^"]*)\\n"', source) - self.assertEqual(sorted(formats), ["fragment subgroup size: %u", "fragment subgroup size: %u not available"]) - taken, refused = (f.replace("%u", "64") + "\n" for f in sorted(formats)) - self.assertIsNone(check.wide_pixel_skip("ps_w64x_readlane", "device: fake (subgroup 32..64)\n" + taken)) - self.assertIsInstance(check.wide_pixel_skip("ps_w64x_readlane", "device: fake (subgroup 32..32)\n" + refused), - check.Skip) - - def test_bitmask_perm_skips_when_variable_device_runs_narrow_fragment_subgroup(self): - out = "device: Intel(R) HD Graphics 530 (subgroup 8..32)\nok 64x64\n" - for width in (8, 16): - with self.subTest(width=width): - # In SIMD8/SIMD16, "10p0i" targets lanes >= 16 (out of bounds), returning 0 or wrapped values. - data = b"".join(struct.pack("<4I", i % width, (i % width) ^ 9, 0, 0) for i in range(64 * 64)) - problem = self.run_pixel("ps_bitmask_perm", 0, out, data=data) - self.assertIsInstance(problem, check.Skip) - self.assertIn(f"{width} lanes", problem) - - def test_bitmask_perm_narrow_run_still_judges_the_sources_that_run(self): - # At 16 lanes "pippi" (lane ^ 9) stays inside the running lanes, so a wrong word there is a failure. - out = "device: Intel(R) HD Graphics 530 (subgroup 8..32)\nok 64x64\n" - bad = b"".join(struct.pack("<4I", i % 16, i % 16, 0, 0) for i in range(64 * 64)) - problem = self.run_pixel("ps_bitmask_perm", 0, out, data=bad) - self.assertNotIsInstance(problem, check.Skip) - self.assertIn("wrong", problem) - # At 8 lanes every "pippi" source is lane 8 or above, so nothing can be judged and any word skips. - any8 = b"".join(struct.pack("<4I", i % 8, 12345, 0, 0) for i in range(64 * 64)) - self.assertIsInstance(self.run_pixel("ps_bitmask_perm", 0, out, data=any8), check.Skip) - - def test_bitmask_perm_judges_variable_device_at_32_lanes(self): - out = "device: Intel(R) HD Graphics 530 (subgroup 8..32)\nok 64x64\n" - self.assertEqual(self.run_pixel("ps_bitmask_perm", 0, out, data=self.bitmask_pixels(32)), "") - bad = b"".join(struct.pack("<4I", i % 32, (i % 32) ^ 9, 0, 0) for i in range(64 * 64)) - problem = self.run_pixel("ps_bitmask_perm", 0, out, data=bad) - self.assertNotIsInstance(problem, check.Skip) - self.assertIn("wrong", problem) - - def test_bitmask_perm_fails_broken_lanes_instead_of_skipping(self): - # Fixed 32..32 device producing only lanes 0..15, or 8..32 device producing incomplete/too-narrow lanes. - simd16 = b"".join(struct.pack("<4I", i % 16, (i % 16) ^ 9, 0, 0) for i in range(64 * 64)) - problem = self.run_pixel("ps_bitmask_perm", 0, "device: fake (subgroup 32..32)\nok 64x64\n", data=simd16) - self.assertNotIsInstance(problem, check.Skip) - self.assertIn("wrong", problem) - - out = "device: fake (subgroup 8..32)\nok 64x64\n" - for lanes in (1, 4, 15): - with self.subTest(lanes=lanes): - bad = b"".join(struct.pack("<4I", i % lanes, (i % lanes) ^ 9, 0, 0) for i in range(64 * 64)) - problem = self.run_pixel("ps_bitmask_perm", 0, out, data=bad) - self.assertNotIsInstance(problem, check.Skip) - self.assertIn("wrong", problem) - - @staticmethod - def vcmpx_pixels(words=(0xf05b2a48, 0xf05e8a12, 0xb174be18, 0x15550000)): - return b"".join(struct.pack("<4I", *words) for _ in range(64 * 64)) - - def test_vcmpx_forms_skips_on_variable_fragment_subgroup(self): - # TEST-205: no lane IDs in mrt0, so the skip is from the reported range (same class as #1318). - out = "device: Intel UHD 770 (subgroup 8..32)\nok 64x64\n" - problem = self.run_pixel("ps_vcmpx_forms", 0, out, data=self.vcmpx_pixels()) - self.assertIsInstance(problem, check.Skip) - self.assertIn("8..32", problem) - self.assertIn("needs 32", problem) - - def test_vcmpx_forms_skips_below_32_lanes(self): - out = "device: fake (subgroup 8..8)\nok 64x64\n" - problem = self.run_pixel("ps_vcmpx_forms", 0, out, data=self.vcmpx_pixels()) - self.assertIsInstance(problem, check.Skip) - self.assertIn("narrower than 32 lanes", problem) - - def test_vcmpx_forms_is_judged_at_32_lanes(self): - out = "device: NVIDIA (subgroup 32..32)\nok 64x64\n" - self.assertEqual(self.run_pixel("ps_vcmpx_forms", 0, out, data=self.vcmpx_pixels()), "") - bad = self.vcmpx_pixels((0, 0, 0, 0xffff)) # lane-mask-looking word3, as on UHD 770 - problem = self.run_pixel("ps_vcmpx_forms", 0, out, data=bad) - self.assertNotIsInstance(problem, check.Skip) - self.assertIn("differ", problem) - - def test_vcmpx_forms_skips_without_a_subgroup_width(self): - problem = self.run_pixel("ps_vcmpx_forms", 0, "ok 64x64\n", data=self.vcmpx_pixels()) - self.assertIsInstance(problem, check.Skip) - self.assertIn("no subgroup width", problem) - - -class SeededPixelTests(unittest.TestCase): - """ps_vcc_x2 reads a V# from s[0:3]; check.py hands vk_harness that V# and the heap words behind it (TEST-19).""" - - def run_pixel_test(self, words, code=0, out=""): - seen = {} - - def harness(_tool, _vs, _fs, raw, env=None): - seen["env"] = env - if not code: - Path(raw).write_bytes(struct.pack("<4I", *words) * (64 * 64)) - return code, out - - with tempfile.TemporaryDirectory() as tmp: - (Path(tmp) / "ps_vcc_x2.spv").touch() - with patch.object(check, "run", side_effect=harness): - problem = check.pixel_test(tmp, tmp, "ps_vcc_x2") - return problem, seen["env"] or {} - - def test_v_sharp_and_heap_reach_the_harness(self): - problem, env = self.run_pixel_test((0x11223344, 0x55667788, 0, 0)) - self.assertEqual(problem, "") - self.assertEqual(env.get("VKH_SGPRS"), "0x1000,0,16,0") - self.assertEqual(env.get("VKH_HEAP"), "0x1000=0x11223344,0x1004=0x55667788") - - def test_unseeded_result_fails(self): - problem, _ = self.run_pixel_test((0, 0, 0, 0)) - self.assertIn("4096 of 4096 pixels differ", problem) - - def test_device_without_buffer_addresses_skips(self): - problem, _ = self.run_pixel_test((), code=77, out="unsupported: VKH_HEAP needs bufferDeviceAddress\n") - self.assertIsInstance(problem, check.Skip) - self.assertIn("needs bufferDeviceAddress", problem) - - -class SignedZeroUnjudgedWords(unittest.TestCase): - """cs_signed_zero_nan's -0 products (words 0, 2 and 3) aren't judged on Apple GPUs, which return +0 for them with - or without SignedZeroInfNanPreserve (#1203), and its 0 * inf NaN check (word 5) isn't judged on Mesa llvmpipe, - which returns 0 there with or without it (#664). Their other words still are, and every other device judges all.""" - APPLE_WORDS = [0, 0x80000000, 0, 0, 1, 1, 1, 0x7C00] # what MoltenVK returned in #664 - LLVMPIPE = "llvmpipe (LLVM 21.1.8, 256 bits)" - LLVMPIPE_WORDS = [0x80000000, 0x80000000, 0x80008000, 0x8000, 1, 0, 1, 0x7C00] # what llvmpipe returned in #664 - - def compute(self, device, words, subgroup="32..32"): - out = f"device: {device} (subgroup {subgroup})\nout[0..7] = " + " ".join(map(str, words)) + "\n" - with patch.object(check, "run", return_value=(0, out)): - return check.compute_test("tools", "spirv", "cs_signed_zero_nan", "1", "dump", - expected_words=check.SIGNED_ZERO_NAN) - - def test_apple_does_not_judge_the_minus_zero_products(self): - self.assertEqual(self.compute("Apple M1 Max", self.APPLE_WORDS), "") - - def test_apple_still_judges_the_nan_checks(self): - words = list(self.APPLE_WORDS) - words[4] = 0 # an x != x NaN check folded to false, as without the execution mode - self.assertNotEqual(self.compute("Apple M1 Max", words), "") - - def test_llvmpipe_does_not_judge_the_zero_times_inf_check(self): - self.assertEqual(self.compute(self.LLVMPIPE, self.LLVMPIPE_WORDS, "8..8"), "") - - def test_llvmpipe_still_judges_the_other_words(self): - for i, wrong in ((4, 0), (6, 0), (0, 0), (7, 0)): # a folded NaN check, a lost -0, a lost NaN conversion - words = list(self.LLVMPIPE_WORDS) - words[i] = wrong - self.assertNotEqual(self.compute(self.LLVMPIPE, words, "8..8"), "", i) - - def test_other_devices_judge_every_word(self): - self.assertNotEqual(self.compute("AMD Radeon RX 9070 XT", self.APPLE_WORDS), "") - self.assertNotEqual(self.compute("AMD Radeon RX 9070 XT", self.LLVMPIPE_WORDS), "") - self.assertEqual(self.compute("AMD Radeon RX 9070 XT", check.SIGNED_ZERO_NAN), "") - - def test_only_cs_signed_zero_nan_has_unjudged_words(self): - out = "device: Apple M1 Max (subgroup 32..32)\n" - self.assertEqual(check.judged_words("cs_store", out, check.CS_STORE), check.CS_STORE) - - def test_run_gpu_tests_uses_the_same_rule(self): - sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "scripts")) - import run_gpu_tests - for device, words in (("Apple M1 Max (subgroup 32..32)", self.APPLE_WORDS), - (self.LLVMPIPE + " (subgroup 8..8)", self.LLVMPIPE_WORDS)): - msg = f"device: {device}\nout[0..7] = " + " ".join(map(str, words)) + "\n" - want = check.judged_words("cs_signed_zero_nan", msg, check.SIGNED_ZERO_NAN) - ok, _ = run_gpu_tests.judge_cs_dump(0, msg, want, wave64=False, partial=False, emulated=False) - self.assertTrue(ok, device) - ok, _ = run_gpu_tests.judge_cs_dump(0, msg, check.SIGNED_ZERO_NAN, wave64=False, partial=False, - emulated=False) - self.assertFalse(ok, device) - - -class TextureMipChecks(unittest.TestCase): - def test_mip_draw_reports_unsupported_device_and_preserves_other_failures(self): - with tempfile.TemporaryDirectory() as tmp: - directory = Path(tmp) - (directory / ("vk_texture_test" + check.EXE)).touch() - for shader in (check.TEXTURE_MIP_TEST, *check.TEXTURE_MIP_DEPENDENCIES): - (directory / (shader + ".spv")).touch() - with patch.object(check, "run", return_value=(77, "unsupported device")): - self.assertIsInstance(check.texture_mip_test(tmp, tmp), check.Skip) - with patch.object(check, "run", return_value=(1, "device lost")): - failure = check.texture_mip_test(tmp, tmp) - self.assertNotIsInstance(failure, check.Skip) - self.assertIn("device lost", failure) - - def test_implicit_mip_checks_every_channel_through_last_pixel(self): - pixel = struct.pack("<4f", 0, 1, 1, 1) - image = pixel * (64 * 64) - self.assertEqual(check.texture_mip_mismatch(image, 1), "") - for channel in range(4): - damaged = bytearray(image) - struct.pack_into(" -3\n")): - failure = check.store_words_test("tools", tmp, "cs_imgatomic") - self.assertNotIsInstance(failure, check.Skip) - self.assertIn("exit 1", failure) - self.assertEqual(check.store_words_test("tools", tmp, "cs_resinfo"), "missing cs_resinfo.spv") - - -class GetLodChecks(unittest.TestCase): - """TEST-184: image_get_lod frames, (clamped, calculated) pairs within a sixteenth of a level.""" - - @staticmethod - def frame(pixel): - return struct.pack("<4f", *pixel) * (64 * 64) - - def run_test(self, name, frames, code=0, out=""): - """get_lod_test with a fake vk_texture_test that writes frames[S# word 1]; returns (result, calls).""" - calls = [] - - def harness(_tool, _vs, _fs, raw, *args, env=None): - calls.append(args) - if not code: - Path(raw).write_bytes(frames[args[2]]) - return code, out - - with tempfile.TemporaryDirectory() as tmp: - for shader in ("vk_texture_test" + check.EXE, "vs_ids.spv", name + ".spv"): - (Path(tmp) / shader).touch() - with patch.object(check, "run", side_effect=harness): - return check.get_lod_test(tmp, tmp, name), calls - - def test_expected_frames_pass_within_the_tolerance(self): - for name, draws in check.GET_LOD_TESTS.items(): - with self.subTest(name=name): - frames = {limits: self.frame(want) for limits, _, want in draws} - result, calls = self.run_test(name, frames) - self.assertEqual(result, "") - self.assertEqual([c[2] for c in calls], [limits for limits, _, _ in draws]) - self.assertEqual(["--two-mip" in c for c in calls], [two_mip for _, two_mip, _ in draws]) - want = check.GET_LOD_TESTS["ps_get_lod"][0][2] - near = tuple(v + 1 / 32 for v in want) - self.assertEqual(check.get_lod_problem(self.frame(near), want), "") - self.assertIn("4096 of 4096 pixels differ", check.get_lod_problem(self.frame(tuple(v + 1 / 8 for v in want)), want)) - - def test_swapped_results_an_unclamped_lod_and_bad_frames_fail(self): - clamped_first = check.GET_LOD_TESTS["ps_get_lod"][1][2] # (0, 1, 3, 0) under MAX_LOD 0.25 - for what, pixel in (("calculated LOD first", (1.0, 0.0, 3.0, 0.0)), - ("sampler limit not applied", (1.0, 1.0, 3.0, 1.0)), - ("LOD of the unscaled coordinate", (0.0, 1.0, 1.0, 0.0)), - ("NaN", (0.0, float("nan"), 3.0, 0.0))): - with self.subTest(what): - self.assertIn("pixels differ", check.get_lod_problem(self.frame(pixel), clamped_first)) - one_bad = bytearray(self.frame(clamped_first)) - struct.pack_into("> 3 | x >> 3 << 4, *check.texoff_words(x, y)[1:])), - ("constant offset wrong", lambda x, y: (x >> 3 | y >> 3 << 4, 0x0744, *check.texoff_words(x, y)[2:])), - ("gather offset dropped", lambda x, y: (*check.texoff_words(x, y)[:2], 0x3443, 0x3344)), - ("descriptor miss", lambda x, y: (0x08, 0x0808, 0x8888, 0x0000)), - ): - with self.subTest(what): - self.assertIn("pixels differ", check.texoff_problem(self.dump(words), self.LIMITS)[0]) - self.assertIn("pixel count", check.texoff_problem(self.dump()[:-16], self.LIMITS)[0]) - - def test_wide_offsets_are_judged_only_inside_the_device_limits(self): - wide_wrong = self.dump(lambda x, y: (x >> 3 | y >> 3 << 4, 0x4461, *check.texoff_words(x, y)[2:])) - self.assertIn("pixels differ", check.texoff_problem(wide_wrong, self.LIMITS)[0]) - for out in ("texel offset limits: -8..7, gather -8..7\n", "no limits printed\n"): - problem, covered = check.texoff_problem(wide_wrong, out) - self.assertEqual(problem, "") - self.assertIn("not judged", covered) - self.assertIn("pixels differ", check.texoff_problem(self.dump(lambda x, y: (0x44, 0x0761, 0, 0)), out)[0]) - - def test_device_without_maintenance8_is_a_skip(self): - with tempfile.TemporaryDirectory() as tmp: - (Path(tmp) / "ps_texoff.spv").touch() - answer = 77, "unsupported: VK_KHR_maintenance8 (non-constant texel Offset)\n" - with patch.object(check, "run", return_value=answer) as run: - result = check.pixel_test("tools", tmp, "ps_texoff") - self.assertEqual(run.call_args.kwargs["env"]["VKT_NEED_MAINTENANCE8"], "1") - self.assertIn("vk_texture_test", run.call_args.args[0]) - self.assertIsInstance(result, check.Skip) - self.assertEqual(result, "SKIP (unsupported: VK_KHR_maintenance8 (non-constant texel Offset))") - - -class Wave32LaneDumps(unittest.TestCase): - """cs_wqm_w32 and cs_w32_lane_wrap need 32 lanes: skipped where the widest subgroup is narrower (llvmpipe: 8).""" - def run_dump(self, name, code, out): - want = dict(check.CS_DUMPS)[name] - with patch.object(check, "run", return_value=(code, out)): - return check.compute_test("tools", "spirv", name, "1", "dump", expected_words=want, - needs_32_lanes=name in check.WAVE32_LANE_DUMPS) - - @staticmethod - def words(name, flip=False): - w = list(dict(check.CS_DUMPS)[name]) - if flip: - w[0] ^= 1 - return "out[0..7] = " + " ".join(map(str, (w + [0] * 8)[:8])) + "\n" - - def test_lane_dumps_are_wave32_dumps(self): - self.assertTrue(set(check.WAVE32_LANE_DUMPS) <= set(check.WAVE32_DUMPS)) - self.assertTrue(set(check.WAVE32_LANE_DUMPS) <= set(dict(check.CS_DUMPS))) - - def test_skipped_below_32_lanes_whatever_the_words(self): - for name in check.WAVE32_LANE_DUMPS: - for flip in (False, True): - with self.subTest(name=name, flip=flip): - problem = self.run_dump(name, 0, "device: llvmpipe (subgroup 8..8)\n" + self.words(name, flip)) - self.assertIsInstance(problem, check.Skip) - self.assertEqual(problem, "SKIP (subgroup 8 is narrower than 32 lanes)") - - def test_judged_on_32_lanes_and_wider(self): - for name in check.WAVE32_LANE_DUMPS: - for dev in ("device: gpu (subgroup 32..32)\n", "device: gpu (subgroup 32..64)\n", - "device: gpu (subgroup 8..32)\n", ""): - with self.subTest(name=name, dev=dev): - self.assertEqual(self.run_dump(name, 0, dev + self.words(name)), "") - problem = self.run_dump(name, 0, dev + self.words(name, flip=True)) - self.assertTrue(problem) - self.assertNotIsInstance(problem, check.Skip) - - def test_other_dumps_are_not_skipped_on_narrow_devices(self): - out = "device: llvmpipe (subgroup 8..8)\nout[0..7] = 1 2 3 4 5 6 7 8\n" - with patch.object(check, "run", return_value=(0, out)): - problem = check.compute_test("tools", "spirv", "cs_store", "1", "dump", expected_words=check.CS_STORE) - self.assertTrue(problem) - self.assertNotIsInstance(problem, check.Skip) - - def test_lane_dumps_request_32_lanes(self): - # #774: like run_gpu_tests.py, so an 8..32 device (Intel ANV) doesn't judge the dump at a narrower size. - for name in check.WAVE32_LANE_DUMPS: - with self.subTest(name=name), patch.object(check, "run", return_value=(0, self.words(name))) as run: - check.compute_test("tools", "spirv", name, "1", "dump", expected_words=dict(check.CS_DUMPS)[name], - needs_32_lanes=True) - self.assertEqual(run.call_args.kwargs["env"]["VKC_SUBGROUP_SIZE"], "32") - - def test_other_dumps_keep_the_default_size(self): - with patch.object(check, "run", return_value=(0, self.words("cs_store"))) as run: - check.compute_test("tools", "spirv", "cs_store", "1", "dump", expected_words=check.CS_STORE) - self.assertNotIn("env", run.call_args.kwargs) - - def test_recorded_wave_size_is_requested(self): - # cs_barrier_loop is wave32 but not a lane dump: left to the default it ran 64-wide on an RX 9070 (32..64), - # two waves instead of four, and failed in check.py while run_gpu_tests.py (which reads index.json) passed. - with tempfile.TemporaryDirectory() as tmp: - Path(tmp, "index.json").write_text(json.dumps({"cs_barrier_loop": {"subgroup_size": 32}, - "cs_store": {}}), encoding="utf-8") - with patch.object(check, "run", return_value=(0, "out[0..7] = 128 96 64 32 128 96 64 0\n")) as run: - self.assertEqual(check.compute_test("tools", tmp, "cs_barrier_loop", "1", "dump", - expected_words=[128, 96, 64, 32, 128, 96, 64]), "") - self.assertEqual(run.call_args.kwargs["env"]["VKC_SUBGROUP_SIZE"], "32") - with patch.object(check, "run", return_value=(0, self.words("cs_store"))) as run: - check.compute_test("tools", tmp, "cs_store", "1", "dump", expected_words=check.CS_STORE) - self.assertNotIn("env", run.call_args.kwargs) # nothing recorded: the default size - with patch.object(check, "run", return_value=(0, "out[0..7] = 0 0 0 0 0 0 0 0\n")) as run: - check.compute_test("tools", tmp, "cs_barrier_loop", "1", "dump", expected_words=[1], - env={"VKC_SUBGROUP_SIZE": "64"}) - self.assertEqual(run.call_args.kwargs["env"]["VKC_SUBGROUP_SIZE"], "64") # a caller's choice wins - - def test_recorded_wave_size_that_cannot_be_pinned_is_a_skip(self): - with tempfile.TemporaryDirectory() as tmp: - Path(tmp, "index.json").write_text(json.dumps({"cs_barrier_loop": {"subgroup_size": 32}}), - encoding="utf-8") - out = "compute subgroup size: 32 not available\nout[0..7] = 0 0 0 0 0 0 0 0\n" - with patch.object(check, "run", return_value=(0, out)): - problem = check.compute_test("tools", tmp, "cs_barrier_loop", "1", "dump", expected_words=[128]) - self.assertIsInstance(problem, check.Skip) - - def test_skipped_when_32_lanes_cannot_be_pinned(self): - for name in check.WAVE32_LANE_DUMPS: - for flip in (False, True): - with self.subTest(name=name, flip=flip): - out = ("device: gpu (subgroup 8..32)\ncompute subgroup size: 32 not available\n" - + self.words(name, flip)) - problem = self.run_dump(name, 0, out) - self.assertIsInstance(problem, check.Skip) - self.assertIn("at 32 lanes on request", problem) - - def test_judged_when_32_lanes_are_pinned(self): - for name in check.WAVE32_LANE_DUMPS: - with self.subTest(name=name): - out = "device: gpu (subgroup 8..32)\ncompute subgroup size: 32\n" - self.assertEqual(self.run_dump(name, 0, out + self.words(name)), "") - self.assertNotIsInstance(self.run_dump(name, 0, out + self.words(name, flip=True)), check.Skip) - - def test_judged_when_32_lanes_are_observed(self): - # MoltenVK: no compute stage in requiredSubgroupSizeStages, but vk_compute_test's cs_wave_probe saw 32 lanes. - out = "device: Apple M3 Max (subgroup 4..32)\ncompute subgroup size: 32 (observed: all 64 invocations of a " \ - "64x1x1 group, full subgroups)\n" - for name in check.WAVE32_LANE_DUMPS: - with self.subTest(name=name): - self.assertEqual(self.run_dump(name, 0, out + self.words(name)), "") - problem = self.run_dump(name, 0, out + self.words(name, flip=True)) - self.assertTrue(problem) - self.assertNotIsInstance(problem, check.Skip) - - def test_failed_when_the_observed_size_is_wrong(self): - out = ("device: gpu (subgroup 4..32)\ncompute subgroup size: 32 observed wrong in 64 of 64 invocations; " - "invocation 0 has SubgroupSize 32, lane 0, subgroup 0, a ballot of 16 lanes\n") - for name in check.WAVE32_LANE_DUMPS: - with self.subTest(name=name): - problem = self.run_dump(name, 1, out) - self.assertNotIsInstance(problem, check.Skip) - self.assertIn("observed wrong", problem) - - -class SamplerMipChecks(unittest.TestCase): - """The S#/T# oracle check.py judges vk_sampler_test with, against hand-worked levels.""" - - def test_levels_follow_the_s_and_t_fields(self): - want = {"point": (0, 1), "point max_lod 0": (0, 0), "point min_lod 1": (1, 1), "point bias +1": (1, 1), - "point bias -1": (0, 0), "none": (0, 0), "none min_lod 1": (0, 0), "point base 1": (1, 1)} - self.assertEqual({name for name, _, _ in check.SAMPLER_CASES}, set(want)) - for name, words, view in check.SAMPLER_CASES: - with self.subTest(name=name): - self.assertEqual((check.sampler_level(words, view, 0), check.sampler_level(words, view, 1)), want[name]) - - def test_s_words_put_the_fields_where_mesa_does(self): - self.assertEqual(check.ssharp_words(1, min_lod=1, max_lod=15, bias=-1), (0x92, 0xf00100, 0x04003f00, 0)) - - @staticmethod - def image(level_lz, level_implicit): - return b"".join(struct.pack("<4f", *check.sampler_texel(level_lz, x, y), *check.sampler_texel(level_implicit, x, y)) - for y in range(64) for x in range(64)) - - def test_every_channel_and_the_last_pixel_are_judged(self): - words, view = check.ssharp_words(1), (0, 1) - good = self.image(0, 1) - self.assertEqual(check.sampler_mismatch(good, words, view), "") - for channel in range(4): - bad = bytearray(good) - struct.pack_into(" None: - words, view = check.ssharp_words(1), (0, 1) - good = self.image(0, 1) - self.assertEqual(check.sampler_mismatch(good, words, view), "") - for channel in range(4): - with self.subTest(channel=channel): - bad = bytearray(good) - struct.pack_into("> 3) | (px >> 3) << 4, *w[1:]))( - check.texoff_words(px, py, "ps_texoff_forms")))): - with self.subTest(label): - problem, _ = check.texoff_problem(self.dump(broken), "device: gpu\n", name="ps_texoff_forms") - self.assertIn("pixels differ", problem) - - -class PixelTestRegistry(unittest.TestCase): - def test_pixel_tests_include_every_pixel_fixture(self): - # A repeated PIXEL_TESTS assignment silently dropped ps_texoff once; keep the registry explicit. - for name in ("ps_texoff", "ps_texoff_forms", "ps_wqm", "ps_scc_mask32"): - with self.subTest(name=name): - self.assertIn(name, check.PIXEL_TESTS) - self.assertEqual(len(check.PIXEL_TESTS), len(set(check.PIXEL_TESTS))) - - def test_pixel_test_runs_the_harness_once(self): - # A duplicated pixels() line ran the whole shader twice and could hide a first-call failure behind a - # second-call success. - with tempfile.TemporaryDirectory() as tmp: - (Path(tmp) / "ps_legacy_mul.spv").touch() - want = check.PIXEL_BITS["ps_legacy_mul"] - with patch.object(check, "pixels", return_value=([want], "")) as pixels: - self.assertEqual(check.pixel_test("tools", tmp, "ps_legacy_mul"), "") - self.assertEqual(pixels.call_count, 1) diff --git a/tests/test_shader_diff.py b/tests/test_shader_diff.py deleted file mode 100644 index 692285c58..000000000 --- a/tests/test_shader_diff.py +++ /dev/null @@ -1,186 +0,0 @@ -"""Tests for tools/shader_diff.py (no game data, no GPU, no llvm-mc). - -Run from the repository root: - python -m pytest tests/test_shader_diff.py -v -""" -import os -import random -import re -import sys - -import pytest - -ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) -sys.path.insert(0, os.path.join(ROOT, "tools")) - -import shader_diff as sd - - -@pytest.mark.parametrize("seed", [3179, 1, 99]) -def test_integer_operands_never_read_float_results(seed): - # Seed 3179 exhausts the clean register pool before an integer add. Floating - # results may differ in NaN payload, so their bits cannot feed integer checks. - # Seeds 1 and 99 check the general invariant without requiring exhaustion. - lines, writers = sd.generate_program(random.Random(seed), 150) - float_results = set() - recovered = False - for line in lines: - op = line.split()[0] - regs = [int(value) for value in re.findall(r"\bv(\d+)\b", line)] - if not regs: - continue - dst, *sources = regs - if op in sd._FLOAT_OPS: - float_results.add(dst) - else: - assert not (set(sources) & float_results), line - if op == "v_mov_b32" and float_results == set(sd.SCRATCH): - recovered = True - float_results.discard(dst) - if seed == 3179: - assert recovered, "fixture must reach the exhausted-pool boundary" - for reg, (op, index) in writers.items(): - assert lines[index - 1].startswith(f"{op.split('/')[0]} v{reg},") - assert not any(line.split()[1] == f"v{reg}," for line in lines[index:]) - assert (lines, writers) == sd.generate_program(random.Random(seed), 150) - - - - -@pytest.mark.parametrize("seed", [1, 17, 99]) -def test_program_generation_is_deterministic(seed): - lines, writers = sd.generate_program(random.Random(seed), 6) - assert (lines, writers) == sd.generate_program(random.Random(seed), 6) - dst = int(lines[-1].split()[1].strip("v,")) - assert dst in sd.EXPORT_REGS - assert writers[dst] == ("v_mov_b32/sgpr-copy", len(lines)) - for reg in sd.EXPORT_REGS: - op, index = writers[reg] - assert lines[index - 1].startswith(f"{op.split('/')[0]} v{reg},") - assert not any(line.split()[1] == f"v{reg}," for line in lines[index:]) - - -@pytest.mark.parametrize("seed, n_ops, expected_reg, seed_only", [ - pytest.param(24, 6, 10, True, id="preserve-three-alu-results"), - pytest.param(3, 18, 11, False, id="replace-oldest-last-alu-write"), -]) -def test_scalar_copy_destination_from_write_history(seed, n_ops, expected_reg, seed_only): - lines, writers = sd.generate_program(random.Random(seed), n_ops) - history = {f"v{reg},": [] for reg in sd.EXPORT_REGS} - for index, line in enumerate(lines[:-1], 1): - op, dst, operands = line.split(maxsplit=2) - if dst in history: - history[dst].append((op, index)) - - selected = history[f"v{expected_reg},"] - others = [writes for dst, writes in history.items() if dst != f"v{expected_reg},"] - for writes in history.values(): - assert writes[0][0] == "v_mov_b32" - assert all(op != "v_mov_b32" for op, _ in writes[1:]) - assert all(len(writes) >= 2 for writes in others) - if seed_only: - assert len(selected) == 1 - else: - assert len(selected) >= 2 - # Another output received an ALU result earlier but was rewritten later. - assert any(writes[1][1] < selected[1][1] for writes in others) - assert all(selected[-1][1] < writes[-1][1] for writes in others) - - op, dst, src = lines[-1].split() - assert (op, dst) == ("v_mov_b32", f"v{expected_reg},") - assert src.startswith("s") and src[1:].isdigit() - assert writers[expected_reg] == ("v_mov_b32/sgpr-copy", len(lines)) - for reg in sd.EXPORT_REGS: - if reg != expected_reg: - assert writers[reg] == history[f"v{reg},"][-1] - - -def test_run_one_observes_scalar_copy(monkeypatch): - lines, writers = sd.generate_program(random.Random(17), 1) - assert sd.run_one("ps_scalar_copy", lines, writers) == ("match", "") - write_listing = sd._write_listing - opcode, dst, src = lines[-1].split() - assert opcode == "v_mov_b32" and src.startswith("s") - - def corrupt_scalar_copy(path, body, with_export): - if with_export: - # Only the translated listing gets the wrong scalar (seeds are under 256). - body = body[:-1] + [f"{opcode} {dst} 12345"] - write_listing(path, body, with_export) - - monkeypatch.setattr(sd, "_write_listing", corrupt_scalar_copy) - status, detail = sd.run_one("ps_scalar_copy", lines, writers) - assert status == "mismatch", detail - reg = int(dst.strip("v,")) - assert f"lane word {sd.EXPORT_REGS.index(reg)}" in detail - assert f"last writer v_mov_b32/sgpr-copy at body line {len(lines)} for v{reg}" in detail - - -def test_compare_pair_flags_known_bad(): - bad = sd.compare_pair([1, 2, 3, 4], [1, 2, 3, 5]) - assert bad is not None and "lane word 3" in bad - assert sd.compare_pair([1, 2, 3, 4], [1, 2, 3, 4]) is None - - -@pytest.mark.parametrize("op", ["v_add_f32", "v_add_f32_e32", "v_add_f32_e64"]) -def test_compare_pair_both_nan_matches(op): - qnan = 0x7FC00001 - writers = {reg: (op, 1) for reg in sd.EXPORT_REGS} - assert sd.compare_pair([qnan] * 4, [0x7FC00002] * 4, writers=writers) is None - bad = sd.compare_pair([qnan] * 4, [0x3F800000] * 4, writers=writers) - assert bad is not None and "only one side is NaN" in bad - assert f"last writer {op} at body line 1" in bad - - -@pytest.mark.parametrize("changed_word, replacement, width, expected", [ - (1, 0x7FC00000, 4, ("lane word 1", "0xffffffff", "0x7fc00000", "v_mov_b32 at body line 4")), - (2, 3, 4, ("lane word 2", "v_mov_b32 at body line 5")), - (None, None, 3, ("shape mismatch: cpu has 4 words, spv has 3",)), -]) -def test_run_one_reports_the_first_actual_mismatch(monkeypatch, changed_word, replacement, width, expected): - lines = ["v_mov_b32 v8, 0x7f800000", "v_mov_b32 v12, 0xff800000", - "v_add_f32 v8, v8, v12", "v_mov_b32 v9, 0xffffffff", - "v_mov_b32 v10, 1", "v_mov_b32 v11, 2"] - writers = {8: ("v_add_f32", 3), 9: ("v_mov_b32", 4), 10: ("v_mov_b32", 5), 11: ("v_mov_b32", 6)} - assert sd.run_one("ps_mixed_outputs", lines, writers) == ("match", "") - run_fragment = sd.run_fragment - - def mutate_export(spvasm): - outputs = run_fragment(spvasm) - words = list(outputs["%out_mrt0"]) - words[0] = 0x7FC00001 # Different payload for a floating-point NaN is allowed. - if changed_word is not None: - words[changed_word] = replacement - outputs["%out_mrt0"] = words[:width] - return outputs - - monkeypatch.setattr(sd, "run_fragment", mutate_export) - status, detail = sd.run_one("ps_mixed_outputs", lines, writers) - assert status == "mismatch" - for fragment in expected: - assert fragment in detail - assert "v_add_f32 at body line 3" not in detail - - -def test_unsupported_op_is_a_counted_skip(): - status, detail = sd.run_one( - "ps_probe_skip", ["v_interp_p1_f32 v8, v9, v10"], - {8: ("v_interp_p1_f32", 1)}) - assert status == "skip" - assert detail - - -def test_small_fixed_seed_run_is_clean(): - counts, first_failure = sd.run_suite(5, seed=20261121, max_ops=4) - assert counts["mismatch"] == 0, first_failure - assert counts["harness-error"] == 0, first_failure - assert counts["pass"] == 5, counts - - -def test_cli_reports_the_number_of_programs_run(capsys): - assert sd.main(["--programs", "5", "--limit", "2"]) == 0 - assert capsys.readouterr().out.startswith("2 programs (seed 1): 2 pass,") - - -def test_self_test_passes(): - assert sd.self_test() is True diff --git a/tests/test_shader_diff_exit.py b/tests/test_shader_diff_exit.py deleted file mode 100644 index 0a061824d..000000000 --- a/tests/test_shader_diff_exit.py +++ /dev/null @@ -1,150 +0,0 @@ -"""shader_diff.py exit codes: a harness error is 2, not a mismatch (no GPU, no game data).""" -import contextlib -import io -import os -import sys -import unittest -from unittest import mock - -ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) -sys.path.insert(0, os.path.join(ROOT, "tools")) - -import shader_diff as sd # noqa: E402 -from spirv_mini_interp import UnsupportedConstruct # noqa: E402 - - -class ReplayIndex(unittest.TestCase): - def test_replays_exact_case_without_running_predecessors(self): - # Compare actual generated instructions, their last writers and the case name. - args = ["--seed", "7", "--max-ops", "4"] - with mock.patch.object(sd, "run_one", wraps=sd.run_one) as execute, mock.patch("sys.stdout"): - self.assertEqual(sd.main([*args, "--programs", "4"]), 0) - full_run = execute.call_args_list.copy() - for index in (0, 3): - execute.reset_mock() - self.assertEqual(sd.main([*args, "--program-index", str(index)]), 0) - self.assertEqual(execute.call_args_list, [full_run[index]]) - - def test_rejects_invalid_or_ambiguous_selection(self): - for args in (["--program-index", "-1"], ["--program-index", "2", "--limit", "1"], - ["--program-index", "2", "--programs", "3"]): - with self.subTest(args=args), mock.patch("sys.stderr"), self.assertRaises(SystemExit) as caught: - sd.main(args) - self.assertEqual(caught.exception.code, 2) - - -class HarnessErrorExit(unittest.TestCase): - def test_harness_error_alone_exits_2(self): - def boom(*_a): - raise RuntimeError("broken harness") - with mock.patch.object(sd, "run_one", boom), mock.patch("sys.stdout"): - self.assertEqual(sd.main(["--programs", "2"]), 2) - - def test_unexpected_translator_failures_exit_2(self): - for error_type in (IndexError, KeyError, ValueError): - with self.subTest(error=error_type.__name__): - out = io.StringIO() - with ( - mock.patch.object(sd.rdna2spirv, "translate", side_effect=error_type("broken translator")), - contextlib.redirect_stdout(out), - ): - self.assertEqual(sd.main(["--programs", "1"]), 2) - self.assertIn("0 skipped, 1 harness errors", out.getvalue()) - self.assertIn(f"{error_type.__name__}:", out.getvalue()) - self.assertIn("broken translator", out.getvalue()) - - def test_unsupported_translation_is_a_skip(self): - out = io.StringIO() - with ( - mock.patch.object(sd.rdna2spirv, "translate", side_effect=sd.rdna2spirv.Unsupported("test opcode")), - contextlib.redirect_stdout(out), - ): - # exit 2: a run where every program was skipped is not a success (#4448) - self.assertEqual(sd.main(["--programs", "1"]), 2) - self.assertIn("1 skipped, 0 harness errors", out.getvalue()) - self.assertIn("translator unsupported: test opcode", out.getvalue()) - - def test_unexpected_interpreter_failure_exits_2(self): - out = io.StringIO() - with mock.patch.object(sd, "run_fragment", side_effect=RuntimeError("broken interpreter")): - with contextlib.redirect_stdout(out): - self.assertEqual(sd.main(["--programs", "1"]), 2) - self.assertIn("0 skipped, 1 harness errors", out.getvalue()) - self.assertIn("RuntimeError: broken interpreter", out.getvalue()) - - def test_unsupported_interpreter_construct_is_a_skip(self): - out = io.StringIO() - with mock.patch.object(sd, "run_fragment", side_effect=UnsupportedConstruct("test construct")): - with contextlib.redirect_stdout(out): - sd.main(["--programs", "1"]) - self.assertIn("1 skipped, 0 harness errors", out.getvalue()) - self.assertIn("test construct", out.getvalue()) - - def test_a_run_where_every_program_was_skipped_is_not_a_success(self): - out = io.StringIO() - with mock.patch.object(sd, "run_fragment", side_effect=UnsupportedConstruct("test construct")): - with contextlib.redirect_stdout(out): - self.assertEqual(sd.main(["--programs", "2"]), 2) - self.assertIn("no program ran: every one was skipped", out.getvalue()) - - def test_some_skips_next_to_passes_still_exit_0(self): - out = io.StringIO() - calls = iter([("match", ""), ("skip", "unsupported form")]) - with mock.patch.object(sd, "run_one", lambda *_a: next(calls)): - with contextlib.redirect_stdout(out): - self.assertEqual(sd.main(["--programs", "2"]), 0) - self.assertIn("1 pass, 0 mismatch, 1 skipped", out.getvalue()) - - def test_mismatch_still_exits_1(self): - with mock.patch.object(sd, "run_one", lambda *_a: ("mismatch", "lane word 0")), mock.patch("sys.stdout"): - self.assertEqual(sd.main(["--programs", "1"]), 1) - - -class ArgumentValidation(unittest.TestCase): - """--programs, --limit and --max-ops must be at least 1. - - Before this, `--limit 0` and `--limit -1` ran no program and printed - "0 programs (seed 1): 0 pass, 0 mismatch ..." with exit 0, which reads as a - pass, and `--max-ops 0` died with `ValueError: empty range in randrange(1, 1)`. - """ - - def _rejected(self, argv, option): - err = io.StringIO() - with contextlib.redirect_stderr(err): - with self.assertRaises(SystemExit) as caught: - sd.main(argv) - self.assertEqual(caught.exception.code, 2) - self.assertIn(option, err.getvalue()) - self.assertIn("at least 1", err.getvalue()) - - def test_limit_zero_is_rejected(self): - self._rejected(["--limit", "0"], "--limit") - - def test_limit_negative_is_rejected(self): - self._rejected(["--limit", "-5"], "--limit") - - def test_programs_zero_is_rejected(self): - self._rejected(["--programs", "0"], "--programs") - - def test_programs_negative_is_rejected(self): - self._rejected(["--programs", "-1"], "--programs") - - def test_max_ops_zero_is_rejected(self): - self._rejected(["--max-ops", "0"], "--max-ops") - - def test_max_ops_negative_is_rejected(self): - self._rejected(["--max-ops", "-2"], "--max-ops") - - def test_a_valid_limit_still_runs_that_many_programs(self): - out = io.StringIO() - with mock.patch.object(sd, "run_one", lambda *_a: ("match", "")), contextlib.redirect_stdout(out): - self.assertEqual(sd.main(["--programs", "5", "--limit", "1"]), 0) - self.assertIn("1 programs", out.getvalue()) - - def test_the_defaults_are_unchanged(self): - a = sd.main(["--programs", "1", "--limit", "1"]) - self.assertIn(a, (0, 1)) # 1 pass or 1 mismatch; never an argparse exit - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/test_shader_disasm.py b/tests/test_shader_disasm.py deleted file mode 100644 index ef3172125..000000000 --- a/tests/test_shader_disasm.py +++ /dev/null @@ -1,490 +0,0 @@ -"""The disassembler must stop with a reason instead of writing empty .s files and calling them clean. - -Issue: the official Windows LLVM build ships no llvm-mc and has no AMDGPU target. Before this check, a -"llvm-mc" that existed but could not disassemble produced empty output, counted 0 invalid words, and every -shader was reported "clean" (and make_game.py translated nothing). The probe now catches it once, up front. - - python -I tests/test_shader_disasm.py -""" -import json -import os -import subprocess -import sys -import tempfile -import unittest - -ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) -TOOL = os.path.join(ROOT, "tools", "shader_disasm.py") - -# Two instructions: s_nop 0 then s_endpgm. The probe sends only the s_endpgm, so a fake tool can tell the -# one-instruction probe from the real shader by the input it receives. -CODE = b"\x00\x00\x80\xbf\x00\x00\x81\xbf" -PROBE = "0x00 0x00 0x81 0xbf" -ASM = "\ts_nop 0 ; encoding: [0x00,0x00,0x80,0xbf]\n\ts_endpgm ; encoding: [0x00,0x00,0x81,0xbf]\n" - - -def fssm() -> bytes: - """A minimal FSSM blob: the code offset at 0xC0, then s_nop + s_endpgm at offset + 0x28.""" - blob = bytearray(0x200) - blob[0:4] = b"FSSM" - blob[0xC0:0xC4] = (0x100).to_bytes(4, "little") - blob[0x128:0x12C] = CODE - return bytes(blob) - - -class DisasmFailureTest(unittest.TestCase): - def setUp(self): - self.tmp = tempfile.TemporaryDirectory() - self.dir = self.tmp.name - self.fssm = os.path.join(self.dir, "one.fssm") - with open(self.fssm, "wb") as f: - f.write(fssm()) - - def tearDown(self): - self.tmp.cleanup() - - def run_tool(self, llvm_mc: str, out: str) -> subprocess.CompletedProcess: - env = dict(os.environ, LLVM_MC=llvm_mc) - return subprocess.run([sys.executable, "-I", TOOL, self.fssm, "--out", out, "--jobs", "1"], - capture_output=True, text=True, errors="replace", env=env) - - def fake(self, body: str) -> str: - path = os.path.join(self.dir, "fake_mc.py") - with open(path, "w", encoding="utf-8") as f: - f.write(body) - return f'"{sys.executable}" "{path}"' # a command line, not just a path: LLVM_MC must accept both - - def test_python_backend_uses_the_fssm_wave_size(self): - compare = (0x3E << 25) | (0xC2 << 17) | (2 << 9) | 128 - for flag, operand in ((0, "vcc"), (0x20, "vcc_lo")): - with self.subTest(operand=operand): - blob = bytearray(fssm()) - blob[0xD4] = flag - blob[0x128:0x12C] = compare.to_bytes(4, "little") - with open(self.fssm, "wb") as f: - f.write(blob) - out = os.path.join(self.dir, operand) - result = subprocess.run([sys.executable, "-I", TOOL, self.fssm, "--out", out, "--backend", "python"], - capture_output=True, text=True) - self.assertEqual(result.returncode, 0, result.stderr) - with open(os.path.join(out, "one.s"), encoding="utf-8") as f: - self.assertIn(f" {operand},", f.read()) - - def test_missing_tool(self): - out = os.path.join(self.dir, "out") - p = self.run_tool("definitely-not-an-llvm-mc", out) - self.assertEqual(p.returncode, 1) - self.assertIn("could not be started", p.stderr) - - def test_no_amdgpu_target(self): - mc = self.fake("import sys\n" - "sys.stderr.write('LLVM ERROR: No available targets are compatible with triple " - "\\\"amdgcn--amdpal\\\"\\n')\n" - "sys.exit(1)\n") - p = self.run_tool(mc, os.path.join(self.dir, "out")) - self.assertEqual(p.returncode, 1) - self.assertIn("No available targets", p.stderr) - self.assertIn("AMDGPU target", p.stderr) - - def test_undecodable_probe_error_is_reported_without_a_traceback(self): - # 0x81 is invalid in both UTF-8 and cp1252 (the -I locale on Windows). - mc = self.fake("import sys\n" - "sys.stdin.read()\n" - "sys.stderr.buffer.write(b'llvm-mc: \\x81\\x8d\\x8f\\x90\\x9d\\xff\\n')\n" - "sys.exit(1)\n") - p = self.run_tool(mc, os.path.join(self.dir, "out")) - self.assertEqual(p.returncode, 1, p.stderr) - self.assertIn("did not disassemble an s_endpgm: llvm-mc: ", p.stderr) - self.assertNotIn("Traceback", p.stderr) - - def test_undecodable_shader_error_is_reported_without_a_traceback(self): - mc = self.fake("import sys\n" - "if sys.stdin.read().strip() == %r:\n" - " print('\\ts_endpgm ; encoding: [0x00,0x00,0x81,0xbf]')\n" - " sys.exit(0)\n" - "sys.stderr.buffer.write(b'error: \\x81\\x8d\\x8f\\x90\\x9d\\xff\\n')\n" - "sys.exit(1)\n" % PROBE) - out = os.path.join(self.dir, "out") - p = self.run_tool(mc, out) - self.assertEqual(p.returncode, 1, p.stderr) - self.assertIn("'failed': 1", p.stdout) - self.assertIn("produced no disassembly", p.stderr) - self.assertNotIn("Traceback", p.stderr) - self.assertEqual(sorted(os.listdir(out)), []) - - def test_empty_output_is_a_failure_and_writes_nothing(self): - mc = self.fake("import sys\n" - "if sys.stdin.read().strip() == %r:\n" - " print('\\ts_endpgm ; encoding: [0x00,0x00,0x81,0xbf]')\n" % PROBE) - out = os.path.join(self.dir, "out") - p = self.run_tool(mc, out) - self.assertEqual(p.returncode, 1) - self.assertIn("produced no disassembly", p.stderr) - self.assertEqual(sorted(os.listdir(out)), []) - - def test_llvm_error_discards_partial_disassembly(self): - mc = self.fake("import sys\n" - "sys.stdin.read()\n" - "if '-show-encoding' in sys.argv:\n" - " print('s_nop 0')\n" - " sys.stderr.write('error: disassembly stopped\\n')\n" - " sys.exit(1)\n" - "print('s_endpgm')\n") - out = os.path.join(self.dir, "out") - p = self.run_tool(mc, out) - self.assertEqual(p.returncode, 1, p.stdout) - self.assertIn("'failed': 1", p.stdout) - self.assertIn(self.fssm, p.stderr) - self.assertIn("error: disassembly stopped", p.stderr) - self.assertEqual(len(p.stderr.splitlines()), 1) - self.assertEqual(sorted(os.listdir(out)), []) - - def test_no_code_is_an_error_when_no_listings_are_written(self): - with open(self.fssm, "wb") as f: - f.write(b"FSSM\x01\x01" + bytes(320)) - mc = self.fake("import sys\n" - "sys.stdin.read()\n" - "print('s_endpgm')\n") - out = os.path.join(self.dir, "out") - p = self.run_tool(mc, out) - self.assertEqual(p.returncode, 1, p.stdout) - self.assertIn("'no s_endpgm': 1", p.stdout) - self.assertIn(self.fssm, p.stderr) - self.assertEqual(len(p.stderr.splitlines()), 1) - self.assertEqual(sorted(os.listdir(out)), []) - - def test_a_real_disassembly_is_written(self): - mc = self.fake("import sys\n" - "probe = sys.stdin.read().strip() == %r\n" - "print('\\ts_endpgm ; encoding: [0x00,0x00,0x81,0xbf]' if probe else %r)\n" - % (PROBE, ASM)) - out = os.path.join(self.dir, "out") - p = self.run_tool(mc, out) - self.assertEqual(p.returncode, 0, p.stderr) - written = os.listdir(out) - self.assertEqual(written, ["one.s"]) - with open(os.path.join(out, "one.s"), encoding="utf-8") as f: - body = f.read() - self.assertIn("s_endpgm", body) - self.assertIn("0 invalid words", body) - - -class DisasmInputTest(unittest.TestCase): - """Short blobs, bad --jobs/--limit and an empty folder end with a reason, not a traceback.""" - - def setUp(self): - self.tmp = tempfile.TemporaryDirectory() - self.dir = self.tmp.name - self.src = os.path.join(self.dir, "fssm") - os.makedirs(self.src) - mc = os.path.join(self.dir, "fake_mc.py") - with open(mc, "w", encoding="utf-8") as f: - f.write("import sys\n" - "probe = sys.stdin.read().strip() == %r\n" - "print('\\ts_endpgm ; encoding: [0x00,0x00,0x81,0xbf]' if probe else %r)\n" % (PROBE, ASM)) - self.mc = f'"{sys.executable}" "{mc}"' - - def tearDown(self): - self.tmp.cleanup() - - def run_tool(self, *args: str) -> subprocess.CompletedProcess: - env = dict(os.environ, LLVM_MC=self.mc) - return subprocess.run([sys.executable, "-I", TOOL, *args], - capture_output=True, text=True, errors="replace", env=env) - - def write(self, name: str, data: bytes) -> None: - with open(os.path.join(self.src, name), "wb") as f: - f.write(data) - - def test_skip_existing_only_reuses_published_nonempty_listings(self): - for name in ("kept", "empty", "unfinished"): - self.write(name + ".fssm", fssm()) - out = os.path.join(self.dir, "out") - os.mkdir(out) - kept = os.path.join(out, "kept.s") - with open(kept, "w", encoding="utf-8", newline="\n") as f: - f.write("completed listing\n") - open(os.path.join(out, "empty.s"), "w").close() - open(os.path.join(out, ".disasm-abandoned.tmp"), "w").close() - - result = self.run_tool(self.src, "--out", out, "--skip-existing") - self.assertEqual(result.returncode, 0, result.stderr) - self.assertIn("'reused': 1", result.stdout) - self.assertIn("'clean': 2", result.stdout) - with open(kept, encoding="utf-8") as f: - self.assertEqual(f.read(), "completed listing\n") - for name in ("empty", "unfinished"): - with open(os.path.join(out, name + ".s"), encoding="utf-8") as f: - self.assertIn("s_endpgm", f.read()) - - result = self.run_tool(self.src, "--out", out, "--skip-existing") - self.assertEqual(result.returncode, 0, result.stderr) - self.assertIn("'reused': 3", result.stdout) - - def test_code_range_scans_a_blob_shorter_than_the_header(self): - sys.path.insert(0, os.path.join(ROOT, "tools")) - try: - import shader_disasm - finally: - sys.path.pop(0) - self.assertEqual(shader_disasm.code_range(b"FSSM" + CODE), (None, 12, "scan")) - self.assertEqual(shader_disasm.code_range(b"FSSM"), (None, None, "scan")) - self.assertEqual(shader_disasm.code_range(b""), (None, None, "scan")) - - def test_code_range_stops_before_a_constant_data_block(self): - """s_endpgm, count N, N dwords, s_endpgm, s_code_end padding: the block is data, not code.""" - sys.path.insert(0, os.path.join(ROOT, "tools")) - try: - import shader_disasm - finally: - sys.path.pop(0) - endpgm = b"\x00\x00\x81\xbf" - code_end = b"\x00\x00\x9f\xbf" - for n in (0, 1, 8, 32): - data = n.to_bytes(4, "little") + bytes(range(1, 1 + 4 * n)) - blob = bytearray(fssm()) - blob[0x12C:0x12C + 4 + len(data) + 4 + 8] = endpgm + data + endpgm + code_end * 2 - start, end, how = shader_disasm.code_range(bytes(blob)) - self.assertEqual((start, end, how), (0x128, 0x128 + len(CODE), "header"), n) - # A count that does not match the distance to the closing s_endpgm is not a data block. - blob = bytearray(fssm()) - blob[0x12C:0x12C + 16] = endpgm + (3).to_bytes(4, "little") + b"\x01\x00\x00\x00" + endpgm - self.assertEqual(shader_disasm.code_range(bytes(blob))[1], 0x12C + 16) - # Ordinary code (a second program after the first) is kept whole. - blob = bytearray(fssm()) - blob[0x12C:0x12C + 8] = b"\x00\x00\x80\xbf" + endpgm - self.assertEqual(shader_disasm.code_range(bytes(blob))[1], 0x12C + 8) - - def test_a_short_blob_does_not_stop_the_others(self): - self.write("a_good.fssm", fssm()) - self.write("b_short.fssm", b"FSSM" + CODE) # 12 bytes: no room for the code offset at 0xC0 - self.write("c_good.fssm", fssm()) - out = os.path.join(self.dir, "out") - p = self.run_tool(self.src, "--out", out, "--jobs", "1") - self.assertEqual(p.returncode, 0, p.stderr) - self.assertNotIn("Traceback", p.stderr) - self.assertEqual(sorted(os.listdir(out)), ["a_good.s", "c_good.s"]) - self.assertIn("'clean': 2", p.stdout) - self.assertIn("'scan failed': 1", p.stdout) - - def test_directory_with_fssm_suffix_does_not_count_toward_limit(self): - os.mkdir(os.path.join(self.src, "a_cache.fssm")) - self.write("b_shader.fssm", fssm()) - out = os.path.join(self.dir, "out") - - result = self.run_tool(self.src, "--out", out, "--limit", "1") - - self.assertEqual(result.returncode, 0, result.stderr) - self.assertEqual(os.listdir(out), ["b_shader.s"]) - - def test_fallback_scan_ignores_unaligned_endpgm(self) -> None: - blob = bytearray(0x110) - blob[:4] = b"FSSM" - blob[0x101:0x105] = CODE[-4:] # the same bytes in metadata, straddling two words - blob[0x108:0x110] = CODE - self.write("fallback.fssm", bytes(blob)) - out = os.path.join(self.dir, "out") - - result = self.run_tool(self.src, "--out", out, "--jobs", "1") - - self.assertEqual(result.returncode, 0, result.stderr) - with open(os.path.join(out, "fallback.s"), encoding="utf-8") as listing: - self.assertIn("..0x110 (scan)", listing.readline()) - - def test_unpack_index_selects_current_blobs(self): - self.write("current.fssm", fssm()) - self.write("obsolete.fssm", fssm()) - index = os.path.join(self.dir, "fssm_index.json") - with open(index, "w", encoding="utf-8") as f: - json.dump([{"name": "current"}], f) - out = os.path.join(self.dir, "out") - result = self.run_tool(self.src, "--out", out, "--unpack-index", index) - self.assertEqual(result.returncode, 0, result.stderr) - self.assertEqual(os.listdir(out), ["current.s"]) - self.assertTrue(os.path.isfile(os.path.join(self.src, "obsolete.fssm"))) - - def test_a_full_run_removes_listings_of_shaders_no_longer_there(self): - self.write("current.fssm", fssm()) - out = os.path.join(self.dir, "out") - os.makedirs(out) - for name, body in (("stale.s", "; gone\n"), ("notes.txt", "keep\n")): - with open(os.path.join(out, name), "w", encoding="utf-8") as f: - f.write(body) - result = self.run_tool(self.src, "--out", out, "--jobs", "1") - self.assertEqual(result.returncode, 0, result.stderr) - entries = os.listdir(out) - self.assertIn("current.s", entries) - self.assertIn("notes.txt", entries) # not ours to remove - self.assertNotIn("stale.s", entries) - self.assertIn("removed 1 stale .s file(s)", result.stdout) - - def test_a_limited_run_leaves_the_other_listings_alone(self): - self.write("a_shader.fssm", fssm()) - self.write("b_shader.fssm", fssm()) - out = os.path.join(self.dir, "out") - os.makedirs(out) - with open(os.path.join(out, "b_shader.s"), "w", encoding="utf-8") as f: - f.write("; already there\n") - result = self.run_tool(self.src, "--out", out, "--limit", "1", "--jobs", "1") - self.assertEqual(result.returncode, 0, result.stderr) - self.assertNotIn("stale", result.stdout) - self.assertIn("a_shader.s", os.listdir(out)) - with open(os.path.join(out, "b_shader.s"), encoding="utf-8") as f: - self.assertEqual(f.read(), "; already there\n") - - def test_a_failed_probe_does_not_delete_an_older_listing(self): - self.write("one.fssm", fssm()) - out = os.path.join(self.dir, "out") - os.makedirs(out) - with open(os.path.join(out, "old.s"), "w", encoding="utf-8") as f: - f.write("; usable\n") - env = dict(os.environ, LLVM_MC="definitely-not-an-llvm-mc") - p = subprocess.run([sys.executable, "-I", TOOL, self.src, "--out", out], - capture_output=True, text=True, errors="replace", env=env) - self.assertEqual(p.returncode, 1, p.stderr) - self.assertIn("could not be started", p.stderr) - self.assertTrue(os.path.isfile(os.path.join(out, "old.s"))) # pruning waits for a successful decode - - def test_jobs_and_limit_must_be_at_least_one(self): - self.write("one.fssm", fssm()) - out = os.path.join(self.dir, "out") - for flag, value in (("--jobs", "0"), ("--jobs", "-2"), ("--limit", "0"), ("--limit", "-1")): - with self.subTest(flag=flag, value=value): - p = self.run_tool(self.src, "--out", out, flag, value) - self.assertEqual(p.returncode, 2, p.stderr) - self.assertIn("must be at least 1", p.stderr) - self.assertFalse(os.path.exists(out)) - - def test_a_folder_without_fssm_files_is_an_error(self): - for args in ((self.src,), (self.src, "--out", os.path.join(self.dir, "out"))): - with self.subTest(args=args): - p = self.run_tool(*args) - self.assertEqual(p.returncode, 1, p.stderr) - self.assertIn("no .fssm files", p.stderr) - self.assertNotIn("Traceback", p.stderr) - - def test_a_missing_source_is_an_error(self): - p = self.run_tool(os.path.join(self.dir, "nope"), "--out", os.path.join(self.dir, "out")) - self.assertEqual(p.returncode, 2, p.stderr) - self.assertIn("does not exist", p.stderr) - self.assertNotIn("Traceback", p.stderr) - - def test_an_out_that_is_a_file_is_an_error(self): - self.write("one.fssm", fssm()) - out = os.path.join(self.dir, "out") - with open(out, "w", encoding="utf-8") as f: - f.write("keep") - p = self.run_tool(self.src, "--out", out) - self.assertEqual(p.returncode, 1, p.stderr) - self.assertIn("cannot create the output folder", p.stderr) - self.assertNotIn("Traceback", p.stderr) - with open(out, encoding="utf-8") as f: - self.assertEqual(f.read(), "keep") - - -class DisasmOutputCollisionTest(unittest.TestCase): - """A planned /.s that is a folder or names an input is refused before llvm-mc is probed.""" - - def setUp(self): - self.tmp = tempfile.TemporaryDirectory() - self.dir = self.tmp.name - self.src = os.path.join(self.dir, "fssm") - os.makedirs(self.src) - self.probe_marker = os.path.join(self.dir, "probe_ran") - mc = os.path.join(self.dir, "fake_mc.py") - with open(mc, "w", encoding="utf-8", newline="\n") as f: - f.write("import sys\n" - f"open({self.probe_marker!r}, 'w').close()\n" - f"probe = sys.stdin.read().strip() == {PROBE!r}\n" - f"print('\\ts_endpgm ; encoding: [0x00,0x00,0x81,0xbf]' if probe else {ASM!r})\n") - self.mc = f'"{sys.executable}" "{mc}"' - case_probe = os.path.join(self.dir, "CaseProbe") - open(case_probe, "wb").close() - self.case_insensitive = os.path.exists(os.path.join(self.dir, "caseprobe")) - os.unlink(case_probe) - - def tearDown(self): - self.tmp.cleanup() - - def run_tool(self, *args: str) -> subprocess.CompletedProcess: - env = dict(os.environ, LLVM_MC=self.mc) - return subprocess.run([sys.executable, "-I", TOOL, *args, "--jobs", "1"], - capture_output=True, text=True, env=env) - - def write(self, path: str) -> bytes: - data = fssm() - with open(path, "wb") as f: - f.write(data) - return data - - def assert_refused(self, p: subprocess.CompletedProcess, message: str) -> None: - self.assertEqual(p.returncode, 1, p.stderr) - self.assertIn(message, p.stderr) - self.assertNotIn("Traceback", p.stderr) - self.assertFalse(os.path.exists(self.probe_marker), "llvm-mc was probed before the output was checked") - - def assert_unchanged(self, path: str, data: bytes) -> None: - with open(path, "rb") as f: - self.assertEqual(f.read(), data) - - def test_an_input_named_like_its_listing_is_not_overwritten(self): - inp = os.path.join(self.dir, "foo.s") - data = self.write(inp) - self.assert_refused(self.run_tool(inp, "--out", self.dir), "would overwrite input") - self.assert_unchanged(inp, data) - - def test_the_default_out_of_a_file_in_disasm_does_not_overwrite_it(self): - os.makedirs(os.path.join(self.dir, "disasm")) - inp = os.path.join(self.dir, "disasm", "foo.s") - data = self.write(inp) - self.assert_refused(self.run_tool(inp), "would overwrite input") - self.assert_unchanged(inp, data) - - def test_skip_existing_does_not_reuse_the_input_as_its_listing(self): - inp = os.path.join(self.dir, "foo.s") - data = self.write(inp) - self.assert_refused(self.run_tool(inp, "--out", self.dir, "--skip-existing"), "would overwrite input") - self.assert_unchanged(inp, data) - - def test_a_case_variant_of_the_input_is_the_input_where_case_is_ignored(self): - inp = os.path.join(self.dir, "FOO.S") - data = self.write(inp) - p = self.run_tool(inp, "--out", self.dir) - if self.case_insensitive: - self.assert_refused(p, "would overwrite input") - else: - self.assertEqual(p.returncode, 0, p.stderr) - self.assertTrue(os.path.isfile(os.path.join(self.dir, "FOO.s"))) - self.assert_unchanged(inp, data) - - def test_a_listing_hard_linked_to_its_input_is_refused(self): - inp = os.path.join(self.src, "one.fssm") - data = self.write(inp) - out = os.path.join(self.dir, "out") - os.makedirs(out) - try: - os.link(inp, os.path.join(out, "one.s")) - except (AttributeError, OSError) as e: - self.skipTest(f"hard links unavailable: {e}") - # --skip-existing would otherwise count the linked FSSM as a finished listing. - self.assert_refused(self.run_tool(self.src, "--out", out, "--skip-existing"), "would overwrite input") - self.assert_unchanged(inp, data) - - def test_a_folder_where_a_listing_goes_is_refused(self): - self.write(os.path.join(self.src, "one.fssm")) - out = os.path.join(self.dir, "out") - os.makedirs(os.path.join(out, "one.s")) - self.assert_refused(self.run_tool(self.src, "--out", out), "destination is a folder") - self.assertTrue(os.path.isdir(os.path.join(out, "one.s"))) - - def test_a_listing_next_to_a_different_input_is_written(self): - inp = os.path.join(self.dir, "foo.fssm") - data = self.write(inp) - p = self.run_tool(inp, "--out", self.dir) - self.assertEqual(p.returncode, 0, p.stderr) - self.assert_unchanged(inp, data) - self.assertTrue(os.path.isfile(os.path.join(self.dir, "foo.s"))) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/test_shader_index.py b/tests/test_shader_index.py deleted file mode 100644 index be067ffb6..000000000 --- a/tests/test_shader_index.py +++ /dev/null @@ -1,107 +0,0 @@ -"""Index-identity metadata for tools/rdna2spirv.py (no game data, no GPU). - -Run from the repository root: python -m pytest tests/test_shader_index.py -Needs nothing but the standard library: Gen objects are built by hand and the -hashes are computed over temp files, so these run on every CI leg including -Windows without llvm-mc. -""" -import hashlib -import os -import sys - -sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "tools")) -import rdna2spirv # noqa: E402 -from rdna2spirv import Gen, Unsupported, shader_meta - - -def _gen(stage="ps", wave64=False): - g = Gen(stage) - g.wave64 = wave64 - return g - - -def test_basic_fields_and_subgroup_size(): - m = shader_meta(_gen("ps"), "") - assert m["stage"] == "ps" - assert m["wave64"] is False - assert m["subgroup_size"] == 32 - assert m["wave64_emulated"] is False - assert m["push_constant_bytes"] == 4 * rdna2spirv.USER_SGPRS + 16 - - -def test_wave64_compute_requests_64(): - m = shader_meta(_gen("cs", wave64=True), "") - assert m["wave64"] is True - assert m["subgroup_size"] == 64 - assert m["wave64_emulated"] is False - - -def test_wave64_graphics_is_emulated(): - # 64-wide subgroups can only be requested for compute/mesh; VS/PS/GS - # wave64 stays emulated as per-32-lane halves (docs/design.md). - for stage in ("vs", "ps", "gs"): - assert shader_meta(_gen(stage, wave64=True), "")["wave64_emulated"] is True - assert shader_meta(_gen("ms", wave64=True), "OpCapability MeshShadingEXT")["wave64_emulated"] is False - - -def test_vertex_signature_passthrough(tmp_path): - g = _gen("vs") - g.vertex_inputs = [(0, 3)] - g.vertex_signature = [{"register": 0, "mask": 7, "system_value": 0, "component_type": 3}] - m = shader_meta(g, "") - assert m["vertex_inputs"] == [{"location": 0, "type": "float"}] - assert m["vertex_input_signature"] == [ - {"register": 0, "mask": 7, "system_value": 0, "component_type": 3}] - - -def test_dynamic_and_fixed_format_flags(): - m = shader_meta(_gen("cs"), "") - assert "dynamic_format" not in m - assert "fixed_format_codes" not in m - g = _gen("cs") - g.dynamic_format = True - g.fixed_format_codes = {22, 44} - m = shader_meta(g, "") - assert m["dynamic_format"] is True - assert m["fixed_format_codes"] == [22, 44] - - -def test_src_and_fssm_hashes(tmp_path): - src = tmp_path / "t.s" - fssm = tmp_path / "t.fssm" - src.write_bytes(b"s_endpgm\n") - fssm.write_bytes(b"XBCH fake\n") - m = shader_meta(_gen("cs"), "", src_path=os.fspath(src), fssm_path=os.fspath(fssm)) - assert m["src_sha256"] == hashlib.sha256(b"s_endpgm\n").hexdigest() - assert m["fssm_sha256"] == hashlib.sha256(b"XBCH fake\n").hexdigest() - - -def test_missing_sidecars_omitted(): - m = shader_meta(_gen("cs"), "", src_path="/no/such.s", fssm_path="/no/such.fssm") - assert "src_sha256" not in m - assert "fssm_sha256" not in m - - -def test_decode_unknown_raises_with_code(): - g = _gen("cs") - try: - g.decode_format(["%x"], 511) - except Unsupported as e: - assert "511" in str(e) - else: - raise AssertionError("decode_format(511) did not raise") - - -def test_encode_unknown_raises_with_code(): - g = _gen("cs") - try: - g.encode_format(["%x"], ["%y"], 511) - except Unsupported as e: - assert "511" in str(e) - else: - raise AssertionError("encode_format(511) did not raise") - - -def test_known_format_still_works(): - # 22 = 4-byte f32: covered by FORMATS, must not raise. - assert len(_gen("cs").decode_format(["%w0"], 22)) == 4 diff --git a/tests/test_shader_ir.py b/tests/test_shader_ir.py deleted file mode 100644 index 0a6802366..000000000 --- a/tests/test_shader_ir.py +++ /dev/null @@ -1,401 +0,0 @@ -"""Tests for tools/shader_ir.py, built from synthetic AMDGPU disassembly (no game data). - - python -I tests/test_shader_ir.py -""" -import contextlib -import errno -import importlib.util -import io -import os -import subprocess -import sys -import tempfile -import unittest -from unittest import mock - -ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) - - -def load_module(): - path = os.path.join(ROOT, "tools", "shader_ir.py") - spec = importlib.util.spec_from_file_location("shader_ir_under_test", path) - module = importlib.util.module_from_spec(spec) - spec.loader.exec_module(module) - return module - - -shader_ir = load_module() - - -class OperandTests(unittest.TestCase): - def test_single_registers(self): - self.assertEqual( - shader_ir.operand("s5"), - {"k": "sgpr", "r": 5, "n": 1, "neg": False, "abs": False}, - ) - self.assertEqual( - shader_ir.operand("v3"), - {"k": "vgpr", "r": 3, "n": 1, "neg": False, "abs": False}, - ) - - def test_register_ranges(self): - self.assertEqual( - shader_ir.operand("s[4:7]"), - {"k": "sgpr", "r": 4, "n": 4, "neg": False, "abs": False}, - ) - self.assertEqual( - shader_ir.operand("v[0:0]"), - {"k": "vgpr", "r": 0, "n": 1, "neg": False, "abs": False}, - ) - - def test_negation_and_absolute_value(self): - self.assertTrue(shader_ir.operand("-v2")["neg"]) - self.assertTrue(shader_ir.operand("|s1|")["abs"]) - both = shader_ir.operand("-|v2|") - self.assertTrue(both["neg"]) - self.assertTrue(both["abs"]) - - def test_inline_and_float_constants(self): - self.assertEqual(shader_ir.operand("0x10"), {"k": "imm", "v": 16}) - self.assertEqual(shader_ir.operand("-5"), {"k": "imm", "v": -5}) - self.assertEqual(shader_ir.operand("1.5"), {"k": "fimm", "v": 1.5, "abs": False}) - self.assertEqual(shader_ir.operand("-2.5e1"), {"k": "fimm", "v": -25.0, "abs": False}) - self.assertEqual(shader_ir.operand("|1.0|"), {"k": "fimm", "v": 1.0, "abs": True}) - # The regex accepts leading-zero decimals; int(core, 0) used to reject them and abort the run. - self.assertEqual(shader_ir.operand("010"), {"k": "imm", "v": 10}) - self.assertEqual(shader_ir.operand("0001"), {"k": "imm", "v": 1}) - self.assertEqual(shader_ir.operand("08"), {"k": "imm", "v": 8}) - self.assertEqual(shader_ir.operand("-010"), {"k": "imm", "v": -10}) - - def test_hardware_fp_modifiers_on_constants(self): - # LLVM AMDGPUInstPrinter::printOperandAndFPInputMods emits neg(), ||, -|| and the - # assembler also accepts abs() / neg(abs()). Keep abs/neg as VOP3 FP modifier flags rather - # than folding neg into two's-complement negation (neg(1) is bit-31 flip 0x80000001, not -1 = 0xffffffff) - # or folding outer '-' of -|x| into v before FAbs. - self.assertEqual(shader_ir.operand("neg(0)"), {"k": "imm", "v": 0, "neg": True}) - self.assertEqual(shader_ir.operand("neg(1)"), {"k": "imm", "v": 1, "neg": True}) - self.assertEqual(shader_ir.operand("neg(-1)"), {"k": "imm", "v": -1, "neg": True}) - self.assertEqual(shader_ir.operand("neg(5)"), {"k": "imm", "v": 5, "neg": True}) - self.assertEqual(shader_ir.operand("neg(0x3f800000)"), {"k": "imm", "v": 0x3F800000, "neg": True}) - self.assertEqual(shader_ir.operand("neg(1.0)"), {"k": "fimm", "v": 1.0, "abs": False, "neg": True}) - self.assertEqual(shader_ir.operand("neg(-1.0)"), {"k": "fimm", "v": -1.0, "abs": False, "neg": True}) - self.assertEqual(shader_ir.operand("-|1.0|"), {"k": "fimm", "v": 1.0, "abs": True, "neg": True}) - self.assertEqual(shader_ir.operand("-|-2.0|"), {"k": "fimm", "v": -2.0, "abs": True, "neg": True}) - self.assertEqual(shader_ir.operand("-|0.15915494|"), {"k": "fimm", "v": 0.15915494, "abs": True, "neg": True}) - self.assertEqual(shader_ir.operand("neg(|1.0|)"), {"k": "fimm", "v": 1.0, "abs": True, "neg": True}) - self.assertEqual(shader_ir.operand("|0xbf800000|"), {"k": "imm", "v": 0xBF800000, "abs": True}) - self.assertEqual(shader_ir.operand("-|0x3f800000|"), {"k": "imm", "v": 0x3F800000, "abs": True, "neg": True}) - self.assertEqual(shader_ir.operand("-|0|"), {"k": "imm", "v": 0, "abs": True, "neg": True}) - self.assertEqual(shader_ir.operand("|-0x10|"), {"k": "imm", "v": -16, "abs": True}) - self.assertEqual(shader_ir.operand("abs(0xbf800000)"), {"k": "imm", "v": 0xBF800000, "abs": True}) - self.assertEqual(shader_ir.operand("neg(abs(0x3f800000))"), {"k": "imm", "v": 0x3F800000, "abs": True, "neg": True}) - self.assertEqual(shader_ir.operand("abs(1.0)"), {"k": "fimm", "v": 1.0, "abs": True}) - self.assertEqual(shader_ir.operand("-abs(1.0)"), {"k": "fimm", "v": 1.0, "abs": True, "neg": True}) - self.assertEqual(shader_ir.operand("neg(neg(1.0))"), {"k": "fimm", "v": 1.0, "abs": False}) - self.assertEqual(shader_ir.operand("-neg(0x3f800000)"), {"k": "imm", "v": 0x3F800000}) - - def test_negation_and_abs_of_registers_compose(self): - self.assertTrue(shader_ir.operand("neg(v1)")["neg"]) - self.assertFalse(shader_ir.operand("neg(neg(v1))")["neg"]) - self.assertFalse(shader_ir.operand("-neg(v1)")["neg"]) - self.assertEqual( - shader_ir.operand("|neg(v1)|"), - {"k": "vgpr", "r": 1, "n": 1, "neg": False, "abs": True}, - ) - self.assertEqual( - shader_ir.operand("-|neg(v1)|"), - {"k": "vgpr", "r": 1, "n": 1, "neg": True, "abs": True}, - ) - self.assertEqual( - shader_ir.operand("abs(v1)"), - {"k": "vgpr", "r": 1, "n": 1, "neg": False, "abs": True}, - ) - self.assertEqual( - shader_ir.operand("-abs(v1)"), - {"k": "vgpr", "r": 1, "n": 1, "neg": True, "abs": True}, - ) - self.assertEqual( - shader_ir.operand("abs(neg(v1))"), - {"k": "vgpr", "r": 1, "n": 1, "neg": False, "abs": True}, - ) - - def test_sign_extension(self): - self.assertTrue(shader_ir.operand("sext(v1)")["sext"]) - self.assertFalse(shader_ir.operand("sext(v1)")["neg"]) - self.assertTrue(shader_ir.operand("-sext(v1)")["neg"]) - self.assertTrue(shader_ir.operand("sext(neg(v1))")["neg"]) - self.assertTrue(shader_ir.operand("|sext(v1)|")["abs"]) - self.assertTrue(shader_ir.operand("|sext(v1)|")["sext"]) - - def test_ttmp_registers(self): - self.assertEqual(shader_ir.operand("ttmp5"), {"k": "ttmp", "t": "ttmp5"}) - self.assertEqual(shader_ir.operand("ttmp[4:5]"), {"k": "ttmp", "t": "ttmp[4:5]"}) - - def test_non_contiguous_vgpr_list(self): - self.assertEqual(shader_ir.operand("[v1, v2, v3]"), {"k": "vlist", "r": [1, 2, 3]}) - - def test_attribute_and_interpolation(self): - self.assertEqual(shader_ir.operand("attr2.w"), {"k": "attr", "a": 2, "c": 3}) - self.assertEqual(shader_ir.operand("p10"), {"k": "interp", "t": "p10"}) - - def test_export_targets(self): - self.assertEqual(shader_ir.operand("pos0"), {"k": "target", "t": "pos0"}) - self.assertEqual(shader_ir.operand("mrt1"), {"k": "target", "t": "mrt1"}) - self.assertEqual(shader_ir.operand("mrtz"), {"k": "target", "t": "mrtz"}) - - def test_special_registers_including_null(self): - for name in ("vcc_lo", "exec", "m0", "scc", "null", "off"): - with self.subTest(name=name): - self.assertEqual(shader_ir.operand(name)["k"], "special") - self.assertEqual(shader_ir.operand(name)["t"], name) - - def test_hardware_register_and_counter_forms(self): - self.assertEqual(shader_ir.operand("hwreg(0x1234)")["k"], "special") - self.assertEqual(shader_ir.operand("vmcnt(3)")["k"], "special") - self.assertEqual(shader_ir.operand("sendmsg(MSG_GS)")["k"], "special") - - def test_unknown_operand_falls_back_to_raw(self): - self.assertEqual(shader_ir.operand("weirdthing"), {"k": "raw", "t": "weirdthing"}) - - def test_llvm23_lit_is_the_constant(self): - # LLVM 23 prints lit(V) for a literal it could also show as an inline constant (v_fma_mix* sources). - for text, plain in (("lit(0x42200000)", "0x42200000"), ("|lit(0x3f800000)|", "|0x3f800000|"), - ("neg(lit(0x3f800000))", "neg(0x3f800000)"), ("-lit(0x3f800000)", "neg(0x3f800000)")): - with self.subTest(text=text): - self.assertEqual(shader_ir.operand(text), shader_ir.operand(plain)) - - def test_llvm23_lit_of_a_register_is_not_unwrapped(self): - # lit() wraps a constant; a register inside it is not a literal and must not parse as the register (or as a - # constant): it keeps the lit(...) text, which the translator refuses as before lit() was read. - for text in ("lit(v2)", "lit(s4)", "-lit(v2)", "lit(vcc_lo)"): - with self.subTest(text=text): - op = shader_ir.operand(text) - self.assertNotIn(op["k"], ("vgpr", "sgpr", "imm", "fimm")) - self.assertIn("lit(", op.get("t", "")) - - -class SplitArgsTests(unittest.TestCase): - def test_commas_inside_parentheses_stay_together(self): - self.assertEqual( - shader_ir.split_args("a, b(1, 2), c"), - ["a", " b(1, 2)", " c"], - ) - - def test_commas_inside_brackets_stay_together(self): - self.assertEqual(shader_ir.split_args("[v1, v2], v3"), ["[v1, v2]", " v3"]) - - def test_trailing_comma_is_dropped(self): - self.assertEqual(shader_ir.split_args("v0,"), ["v0"]) - - def test_empty_text(self): - self.assertEqual(shader_ir.split_args(""), []) - - -class ParseLineTests(unittest.TestCase): - def test_operation_and_operands(self): - ins = shader_ir.parse_line("\tv_add_f32 v0, v1, v2") - self.assertEqual(ins["op"], "v_add_f32") - self.assertEqual([a["k"] for a in ins["args"]], ["vgpr", "vgpr", "vgpr"]) - self.assertEqual(ins["mods"], []) - self.assertIsNone(ins["enc"]) - - def test_encoding_bytes(self): - ins = shader_ir.parse_line("\tv_mov_b32 v0, v1 ; encoding: [0x0a,0xff]") - self.assertEqual(ins["enc"], "0aff") - self.assertEqual(len(ins["args"]), 2) - - def test_leading_zero_decimal_operand_does_not_abort_a_line(self): - ins = shader_ir.parse_line("\tv_mov_b32_e32 v0, 010 ; encoding: [0x00,0x00,0x02,0x7e]") - self.assertEqual(ins["op"], "v_mov_b32_e32") - self.assertEqual(ins["args"][1], {"k": "imm", "v": 10}) - - def test_comment_or_blank_lines_are_skipped(self): - self.assertIsNone(shader_ir.parse_line("; only a comment")) - self.assertIsNone(shader_ir.parse_line("")) - self.assertIsNone(shader_ir.parse_line(" \t ")) - - def test_modifiers_are_removed_from_the_operands(self): - ins = shader_ir.parse_line( - "\tbuffer_load_dword v5, v[0:3], s[4:7], 0 offen offset:8 glc slc" - ) - self.assertEqual(ins["mods"], ["offen", "offset:8", "glc", "slc"]) - self.assertEqual([a["k"] for a in ins["args"]], ["vgpr", "vgpr", "sgpr", "imm"]) - self.assertEqual(ins["args"][1]["n"], 4) - self.assertEqual(ins["args"][2]["n"], 4) - - def test_dpp_modifiers_keep_their_bracket_lists(self): - ins = shader_ir.parse_line( - "\tv_mov_b32_dpp v0, v1 quad_perm:[1,0,3,2] row_mask:0xf bank_mask:0xf" - ) - self.assertEqual( - ins["mods"], - ["quad_perm:[1,0,3,2]", "row_mask:0xf", "bank_mask:0xf"], - ) - self.assertEqual(len(ins["args"]), 2) - - def test_ds_swizzle_offset_modifier_with_spaces_stays_intact(self): - for mod in ( - "offset:swizzle(QUAD_PERM, 3, 2, 1, 0)", - 'offset:swizzle(BITMASK_PERM, "00p01")', - "offset:swizzle(BROADCAST, 4, 0)", - "offset:swizzle(SWAP, 1)", - "offset:swizzle(REVERSE, 4)", - ): - with self.subTest(mod=mod): - ins = shader_ir.parse_line(f"\tds_swizzle_b32 v0, v1 {mod} gds") - self.assertEqual(ins["op"], "ds_swizzle_b32") - self.assertEqual(ins["mods"], [mod, "gds"]) - self.assertEqual( - ins["args"], - [ - {"k": "vgpr", "r": 0, "n": 1, "neg": False, "abs": False}, - {"k": "vgpr", "r": 1, "n": 1, "neg": False, "abs": False}, - ], - ) - - def test_exp_target_is_split_from_its_operands(self): - ins = shader_ir.parse_line("\texp mrt0 v0, v1, v2, v3") - self.assertEqual(len(ins["args"]), 5) - self.assertEqual(ins["args"][0], {"k": "target", "t": "mrt0"}) - self.assertEqual(ins["args"][1]["k"], "vgpr") - - def test_exp_null_off_target(self): - ins = shader_ir.parse_line("\texp null off, v0, v1, v2") - self.assertEqual([a["t"] for a in ins["args"][:2]], ["null", "off"]) - self.assertEqual(len(ins["args"]), 5) - - def test_sendmsg_commas_stay_in_one_operand(self): - ins = shader_ir.parse_line("\ts_sendmsg sendmsg(MSG_GS, GS_OP_NOP)") - self.assertEqual(len(ins["args"]), 1) - self.assertEqual(ins["args"][0]["k"], "special") - - def test_no_operands(self): - self.assertEqual(shader_ir.parse_line("\ts_endpgm")["args"], []) - - -class ParseFileTests(unittest.TestCase): - def write(self, text): - tmp = tempfile.TemporaryDirectory() - self.addCleanup(tmp.cleanup) - path = os.path.join(tmp.name, "shader_abc.s") - with open(path, "w", encoding="utf-8", newline="\n") as f: - f.write(text) - return path - - def test_header_start_and_pc_stepping(self): - path = self.write( - "; shader.cs_5_0 code 0x00000100..0x00000110\n" - "\tv_mov_b32 v0, 1.0 ; encoding: [0x01,0x02]\n" - "\tv_add_f32 v1, v0, v2 ; encoding: [0x03,0x04]\n" - "\tv_sub_f32 v3, v1, v0 ; no encoding bytes here\n" - "\t.directive skipped\n" - "plain text is not an instruction\n" - "; ---\n" - "\tv_mul_f32 v4, v3, v2 ; encoding: [0x05,0x06]\n" - "; invalid instruction encoding [0xdead]\n" - ) - info = shader_ir.parse_file(path) - self.assertEqual(info["name"], "shader_abc") - self.assertEqual(info["code_start"], 0x100) - self.assertEqual([i["op"] for i in info["insns"]], - ["v_mov_b32", "v_add_f32", "v_sub_f32"]) - # pc advances by the encoding length; an instruction without bytes keeps the offset. - self.assertEqual([i["pc"] for i in info["insns"]], [0x100, 0x102, 0x104]) - self.assertEqual(info["invalid"], 1) - - def test_tab_between_mnemonic_and_operands(self): - path = self.write( - "; sample code 0x0..0x4 (header)\n" - "\ts_mov_b32\ts3, 1 ; encoding: [0x81,0x00,0x83,0xbe]\n" - ) - ins = shader_ir.parse_file(path)["insns"][0] - self.assertEqual(ins["op"], "s_mov_b32") - self.assertEqual(ins["args"], [ - {"k": "sgpr", "r": 3, "n": 1, "neg": False, "abs": False}, - {"k": "imm", "v": 1}, - ]) - - def test_file_without_a_header_starts_at_zero(self): - path = self.write("\tv_mov_b32 v0, v1 ; encoding: [0xaa,0xbb]\n") - info = shader_ir.parse_file(path) - self.assertEqual(info["code_start"], 0) - self.assertEqual(info["insns"][0]["pc"], 0) - self.assertEqual(info["insns"][0]["enc"], "aabb") - - def test_header_only_file_has_no_instructions(self): - path = self.write("; shader.cs_6_0 code 0x00001000..0x00001008\n") - info = shader_ir.parse_file(path) - self.assertEqual(info["code_start"], 0x1000) - self.assertEqual(info["insns"], []) - self.assertEqual(info["invalid"], 0) - - -class CliInputTest(unittest.TestCase): - """The tool read sys.argv by hand: no arguments, a bad --limit or a missing folder ended in a traceback.""" - - def run_tool(self, *args): - return subprocess.run([sys.executable, "-I", os.path.join(ROOT, "tools", "shader_ir.py"), *args], - capture_output=True, text=True, timeout=60) - - def test_census_reports_input_io_errors_without_a_partial_summary(self): - with tempfile.TemporaryDirectory() as tmp: - first = os.path.join(tmp, "first.s") - second = os.path.join(tmp, "second.s") - for path in (first, second): - with open(path, "w", encoding="utf-8", newline="\n") as f: - f.write("\ts_endpgm\n") - parse_file = shader_ir.parse_file - - def fail_second(path): - if path == second: - raise PermissionError(errno.EACCES, "permission denied", second) - return parse_file(path) - - for owner, attr, effect, path, diagnostic in ( - (shader_ir.os, "scandir", OSError(errno.EIO, "I/O error", tmp), tmp, "cannot list"), - (shader_ir, "parse_file", fail_second, second, "cannot read")): - with self.subTest(operation=attr): - stdout, stderr = io.StringIO(), io.StringIO() - with mock.patch.object(owner, attr, side_effect=effect), \ - contextlib.redirect_stdout(stdout), contextlib.redirect_stderr(stderr): - self.assertEqual(shader_ir.main([tmp]), 2) - self.assertEqual(stdout.getvalue(), "") - self.assertEqual(len(stderr.getvalue().strip().splitlines()), 1) - self.assertIn(diagnostic, stderr.getvalue()) - self.assertIn(path, stderr.getvalue()) - - def test_bad_arguments_are_usage_errors(self): - with tempfile.TemporaryDirectory() as tmp: - not_a_folder = os.path.join(tmp, "one.s") - with open(not_a_folder, "w", encoding="utf-8") as f: - f.write("s_endpgm\n") - cases = ((), (tmp, "--limit", "x"), (tmp, "--limit", "0"), - (os.path.join(tmp, "missing"),), (not_a_folder,)) - for args in cases: - with self.subTest(args=args): - p = self.run_tool(*args) - self.assertEqual(p.returncode, 2, p.stderr) - self.assertIn("usage:", p.stderr) - self.assertNotIn("Traceback", p.stderr) - - def test_s_directory_does_not_count_toward_limit(self): - with tempfile.TemporaryDirectory() as tmp: - os.mkdir(os.path.join(tmp, "a_cache.s")) - with open(os.path.join(tmp, "b_shader.s"), "w", encoding="utf-8") as f: - f.write("\ts_endpgm ; encoding: [0x00,0x00,0x81,0xbf]\n") - result = self.run_tool(tmp, "--limit", "1") - self.assertEqual(result.returncode, 0, result.stderr) - self.assertIn("1 shaders, 1 instructions", result.stdout) - - def test_folder_with_limit_still_works(self): - with tempfile.TemporaryDirectory() as tmp: - for name in ("a.s", "b.s"): - with open(os.path.join(tmp, name), "w", encoding="utf-8") as f: - f.write(" s_endpgm ; encoding: [0x00,0x00,0x81,0xbf]\n") - p = self.run_tool(tmp, "--limit", "1") - self.assertEqual(p.returncode, 0, p.stderr) - self.assertTrue(p.stdout.startswith("1 shaders,"), p.stdout) # --limit 1 of the two files - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/test_shader_ir_parse.py b/tests/test_shader_ir_parse.py deleted file mode 100644 index 1b6555215..000000000 --- a/tests/test_shader_ir_parse.py +++ /dev/null @@ -1,67 +0,0 @@ -"""Parity and edge-case tests for tools/shader_ir.py parse_line(), split_args(), and operand().""" -import os -import sys -import unittest - -ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) -sys.path.insert(0, os.path.join(ROOT, "tools")) - -import shader_ir # noqa: E402 - - -class ShaderIRParseTests(unittest.TestCase): - def test_split_args_plain_and_nested(self): - self.assertEqual(shader_ir.split_args(""), []) - self.assertEqual(shader_ir.split_args(" "), []) - self.assertEqual(shader_ir.split_args("v0, v1, 4"), ["v0", " v1", " 4"]) - self.assertEqual(shader_ir.split_args("v0, v1, "), ["v0", " v1"]) - self.assertEqual(shader_ir.split_args("v0, , v1"), ["v0", " ", " v1"]) - self.assertEqual(shader_ir.split_args("[v0, v1], s[4:7], neg(|v2|)"), - ["[v0, v1]", " s[4:7]", " neg(|v2|)"]) - - def test_operand_fast_paths_and_modifiers(self): - self.assertEqual(shader_ir.operand("v3"), {"k": "vgpr", "r": 3, "n": 1, "neg": False, "abs": False}) - self.assertEqual(shader_ir.operand("-|s12|"), {"k": "sgpr", "r": 12, "n": 1, "neg": True, "abs": True}) - self.assertEqual(shader_ir.operand("vcc"), {"k": "special", "t": "vcc", "neg": False, "abs": False}) - self.assertEqual(shader_ir.operand("null"), {"k": "special", "t": "null", "neg": False, "abs": False}) - self.assertEqual(shader_ir.operand("0"), {"k": "imm", "v": 0}) - self.assertEqual(shader_ir.operand("-16"), {"k": "imm", "v": -16}) - self.assertEqual(shader_ir.operand("010"), {"k": "imm", "v": 10}) - self.assertEqual(shader_ir.operand("|42|"), {"k": "imm", "v": 42, "abs": True}) - self.assertEqual(shader_ir.operand("-|42|"), {"k": "imm", "v": 42, "abs": True, "neg": True}) - self.assertEqual(shader_ir.operand("0x10"), {"k": "imm", "v": 16}) - self.assertEqual(shader_ir.operand("neg(1)"), {"k": "imm", "v": 1, "neg": True}) - self.assertEqual(shader_ir.operand("abs(v2)"), {"k": "vgpr", "r": 2, "n": 1, "neg": False, "abs": True}) - self.assertEqual(shader_ir.operand("sext(v4)"), - {"k": "vgpr", "r": 4, "n": 1, "neg": False, "abs": False, "sext": True}) - self.assertEqual(shader_ir.operand("s[4:7]"), {"k": "sgpr", "r": 4, "n": 4, "neg": False, "abs": False}) - self.assertEqual(shader_ir.operand("[v0, v2]"), {"k": "vlist", "r": [0, 2]}) - self.assertEqual(shader_ir.operand("[s100, vcc_lo, vcc_hi]"), - {"k": "slist", "r": [100, "vcc_lo", "vcc_hi"], "n": 3}) - self.assertEqual(shader_ir.operand("attr2.z"), {"k": "attr", "a": 2, "c": 2}) - self.assertEqual(shader_ir.operand("p10"), {"k": "interp", "t": "p10"}) - self.assertEqual(shader_ir.operand("mrt0"), {"k": "target", "t": "mrt0"}) - self.assertEqual(shader_ir.operand("ttmp[4:5]"), {"k": "ttmp", "t": "ttmp[4:5]"}) - self.assertEqual(shader_ir.operand("1.5"), {"k": "fimm", "v": 1.5, "abs": False}) - self.assertEqual(shader_ir.operand("vmcnt(0)"), {"k": "special", "t": "vmcnt(0)"}) - - def test_parse_line_modifiers_sendmsg_and_encoding(self): - ins = shader_ir.parse_line( - "\tbuffer_load_dword v0, v1, s[4:7], 0 offen offset:16 glc ; encoding: [0x10,0x10,0x30,0xe0,0x01,0x00,0x01,0x80]" - ) - self.assertEqual(ins["op"], "buffer_load_dword") - self.assertEqual(ins["mods"], ["offen", "offset:16", "glc"]) - self.assertEqual(ins["enc"], "101030e001000180") - self.assertEqual(len(ins["args"]), 4) - - sm = shader_ir.parse_line("\ts_sendmsg sendmsg(MSG_GS, GS_OP_EMIT, 0) ; plain comment") - self.assertEqual(sm["op"], "s_sendmsg") - self.assertEqual(sm["args"], [{"k": "special", "t": "sendmsg(MSG_GS|GS_OP_EMIT|0)"}]) - self.assertIsNone(sm["enc"]) - - f64 = shader_ir.parse_line("\tv_add_f64 v[0:1], v[2:3], 0x1") - self.assertTrue(f64["args"][2].get("f64_literal")) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/test_shader_library.py b/tests/test_shader_library.py deleted file mode 100644 index eaf596daa..000000000 --- a/tests/test_shader_library.py +++ /dev/null @@ -1,446 +0,0 @@ -"""Unit tests for tools/shader_library.py (the pipeline library in the zlib part of shaders.rpf). - - python -I tests/test_shader_library.py - -Zero game data: every library and archive is built here from synthetic bytes. -""" -import contextlib -import hashlib -import io -import json -import os -import struct -import sys -import tempfile -import unittest -import zlib - -ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) -sys.path.insert(0, os.path.join(ROOT, "tools")) - -import shader_library as sl # noqa: E402 -import shader_meta # noqa: E402 - -ENDPGM = struct.pack("> 16) & 0xFFFF, 0): - out += struct.pack(".dxbc for its input signature: Unsupported for - that shader, not a FileNotFoundError that stops the run.""" - import rdna2spirv - with tempfile.TemporaryDirectory() as tmp: - src = os.path.join(tmp, "lib.bin") - with open(src, "wb") as f: - f.write(sample()) - out = os.path.join(tmp, "out") - self.run_main(src, "--out", out, "--stages", "ps") - os.makedirs(os.path.join(out, "disasm")) - s_path = os.path.join(out, "disasm", "lib_ps_00000.s") - with open(s_path, "w", encoding="utf-8", newline="\n") as f: - f.write("; lib_ps_00000 code 0x24..0x30 (fspx), gfx1013, 0 invalid words\n\ts_endpgm\n") - rdna2spirv._STAGES = None # stage_of caches the first index.json it reads - try: - with self.assertRaisesRegex(rdna2spirv.Unsupported, "no shader container"): - rdna2spirv.translate(s_path) - finally: - rdna2spirv._STAGES = None - - def test_carve_reports_corrupt_and_unreadable_containers(self): - with tempfile.TemporaryDirectory() as tmp: - carve = os.path.join(tmp, "carve") - os.makedirs(carve) - with open(os.path.join(carve, "PS_A.dxbc"), "wb") as f: - f.write(dxbc(D_PS)) - with open(os.path.join(carve, "VS_C.dxbc"), "wb") as f: - f.write(dxbc(D_VS)[:20]) # truncated header - with open(os.path.join(carve, "MS_D.dxbc"), "wb") as f: - f.write(dxbc(D_MS)[:-4]) # truncated part payload - os.makedirs(os.path.join(carve, "CS_B.dxbc")) # exists on disk, unreadable OSError - index = [ - {"name": "PS_A", "file": "PS_A.dxbc"}, - {"name": "gone", "file": "gone.dxbc"}, # missing: skipped silently - {"name": "VS_C", "file": "VS_C.dxbc"}, - {"name": "MS_D", "file": "MS_D.dxbc"}, - {"name": "CS_B", "file": "CS_B.dxbc"}, - ] - with open(os.path.join(carve, "index.json"), "w", encoding="utf-8", newline="\n") as f: - json.dump(index, f) - src = os.path.join(tmp, "lib.bin") - with open(src, "wb") as f: - f.write(sample()) - out = os.path.join(tmp, "out") - stdout, stderr = io.StringIO(), io.StringIO() - with contextlib.redirect_stdout(stdout), contextlib.redirect_stderr(stderr): - rc = sl.main([src, "--out", out, "--carve", carve]) - self.assertEqual(rc, 0) - self.assertIn("1 of 4 named by a carved shader's HASH digest, 3 not in the carve, " - "3 unreadable/corrupt containers", stdout.getvalue()) - err_lines = stderr.getvalue().splitlines() - self.assertEqual(len(err_lines), 3) - self.assertEqual(err_lines[0], "carve: VS_C.dxbc: truncated DXBC header") - self.assertEqual(err_lines[1], "carve: MS_D.dxbc: truncated DXBC part payload") - self.assertTrue(err_lines[2].startswith("carve: CS_B.dxbc: ") and len(err_lines[2]) > len("carve: CS_B.dxbc: ")) - self.assertNotIn("gone.dxbc", stderr.getvalue()) - self.assertTrue(os.path.isfile(os.path.join(out, "lib_ps_00000.dxbc"))) - - def test_carve_missing_only_stays_silent(self): - with tempfile.TemporaryDirectory() as tmp: - carve = os.path.join(tmp, "carve") - os.makedirs(carve) - with open(os.path.join(carve, "PS_A.dxbc"), "wb") as f: - f.write(dxbc(D_PS)) - index = [ - {"name": "PS_A", "file": "PS_A.dxbc"}, - {"name": "gone", "file": "gone.dxbc"}, - ] - with open(os.path.join(carve, "index.json"), "w", encoding="utf-8", newline="\n") as f: - json.dump(index, f) - src = os.path.join(tmp, "lib.bin") - with open(src, "wb") as f: - f.write(sample()) - out = os.path.join(tmp, "out") - stdout, stderr = io.StringIO(), io.StringIO() - with contextlib.redirect_stdout(stdout), contextlib.redirect_stderr(stderr): - rc = sl.main([src, "--out", out, "--carve", carve]) - self.assertEqual(rc, 0) - self.assertEqual(stderr.getvalue(), "") - self.assertIn("1 of 4 named by a carved shader's HASH digest, 3 not in the carve\n", stdout.getvalue()) - self.assertNotIn("unreadable/corrupt", stdout.getvalue()) - - def test_carve_single_corrupt_container_and_direct_api(self): - with tempfile.TemporaryDirectory() as tmp: - carve = os.path.join(tmp, "carve") - os.makedirs(carve) - with open(os.path.join(carve, "PS_A.dxbc"), "wb") as f: - f.write(dxbc(D_PS)) - with open(os.path.join(carve, "ZERO.dxbc"), "wb") as f: - f.write(bytes(64)) # valid length/count=0, wrong magic - index = [ - {"name": "PS_A", "file": "PS_A.dxbc"}, - {"name": "ZERO", "file": "ZERO.dxbc"}, - ] - with open(os.path.join(carve, "index.json"), "w", encoding="utf-8", newline="\n") as f: - json.dump(index, f) - direct_err = io.StringIO() - with contextlib.redirect_stderr(direct_err): - digests = sl.carve_digests(carve) - self.assertEqual(digests, {D_PS: [("PS_A", os.path.join(carve, "PS_A.dxbc"))]}) - self.assertEqual(direct_err.getvalue().splitlines(), ["carve: ZERO.dxbc: not a DXBC container"]) - src = os.path.join(tmp, "lib.bin") - with open(src, "wb") as f: - f.write(sample()) - out = os.path.join(tmp, "out") - stdout, stderr = io.StringIO(), io.StringIO() - with contextlib.redirect_stdout(stdout), contextlib.redirect_stderr(stderr): - rc = sl.main([src, "--out", out, "--carve", carve]) - self.assertEqual(rc, 0) - self.assertIn("1 of 4 named by a carved shader's HASH digest, 3 not in the carve, " - "1 unreadable/corrupt container\n", stdout.getvalue()) - self.assertEqual(stderr.getvalue().splitlines(), ["carve: ZERO.dxbc: not a DXBC container"]) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/test_shader_link_check.py b/tests/test_shader_link_check.py deleted file mode 100644 index a7a54bba4..000000000 --- a/tests/test_shader_link_check.py +++ /dev/null @@ -1,575 +0,0 @@ -"""Shader-stage matching with hand-written modules and a synthetic pipeline manifest.""" -import contextlib -import io -import json -import os -from pathlib import Path -import struct -import subprocess -import sys -import tempfile -import unittest -from unittest.mock import patch - -ROOT = Path(__file__).resolve().parents[1] -sys.path.insert(0, str(ROOT / "tools")) -import shader_link_check as link # noqa: E402 -import spirv_interface as spv # noqa: E402 -import spirv_stubs # noqa: E402 - - -class ModuleFixture: - """Binary interface declarations. Drivers are exercised by separate GLSL fixtures.""" - - MODELS = {"vs": 0, "gs": 3, "ms": 5365, "ps": 4, "cs": 5} - - def __init__(self, stage, start_id=1): - self.stage = stage - self.next_id = start_id - self.code = [] - self.entries = [] - self.ids = [] - self.uint = self.emit_type(spv.OP_TYPE_INT, 32, 0) - - def allocate(self): - self.next_id += 1 - return self.next_id - 1 - - def emit(self, opcode, *args): - self.code.extend([((len(args) + 1) << 16) | opcode, *args]) - - def emit_type(self, opcode, *args): - result = self.allocate() - self.emit(opcode, result, *args) - return result - - def literal(self, value): - result = self.allocate() - self.emit(spv.OP_CONSTANT, self.uint, result, value) - return result - - def numeric(self, width=32, components=1, kind="f"): - if kind == "f": - element = self.emit_type(spv.OP_TYPE_FLOAT, width) - else: - element = self.emit_type(spv.OP_TYPE_INT, width, int(kind == "i")) - return element if components == 1 else self.emit_type(spv.OP_TYPE_VECTOR, element, components) - - def array(self, element, length): - return self.emit_type(spv.OP_TYPE_ARRAY, element, self.literal(length)) - - def decorate(self, identifier, decoration, *operands): - self.emit(spv.OP_DECORATE, identifier, decoration, *operands) - - def member(self, identifier, member, decoration, *operands): - self.emit(spv.OP_MEMBER_DECORATE, identifier, member, decoration, *operands) - - def variable(self, storage, shape, location=None, component=None, index=None, *flags): - pointer = self.emit_type(spv.OP_TYPE_POINTER, storage, shape) - identifier = self.allocate() - self.emit(spv.OP_VARIABLE, pointer, identifier, storage) - self.ids.append(identifier) - for decoration, value in ((spv.DEC_LOCATION, location), (spv.DEC_COMPONENT, component), - (spv.DEC_INDEX, index)): - if value is not None: - self.decorate(identifier, decoration, value) - for decoration in flags: - self.decorate(identifier, decoration) - return identifier - - def entry(self, name, ids, stage=None, *, model=None): - raw = name.encode("utf-8") + b"\x00" - raw += bytes(-len(raw) % 4) - string = struct.unpack(f"<{len(raw) // 4}I", raw) - function = self.allocate() - if model is None: - model = self.MODELS[stage or self.stage] - args = (model, function, *string, *ids) - self.entries.extend([((len(args) + 1) << 16) | spv.OP_ENTRY_POINT, *args]) - - def binary(self, big_endian=False): - if not self.entries: - self.entry("main", self.ids) - words = [spv.SPIRV_MAGIC, 0x00010500, 0, self.next_id, 0, *self.entries, *self.code] - endian = ">" if big_endian else "<" - return struct.pack(f"{endian}{len(words)}I", *words) - - def reflect(self, entry="main", **kwargs): - return spv.reflect_module(self.binary(), entry=entry, **kwargs) - - -def simple(stage, storage, location, component=None, width=32, components=4, kind="f", array_count=None): - shader = ModuleFixture(stage, start_id=5 if storage == spv.STORAGE_INPUT else 1) - shape = shader.numeric(width, components, kind) - if array_count is not None: - shape = shader.array(shape, array_count) - shader.variable(storage, shape, location, component) - return shader - - -def output(location=0, **kwargs): - return simple("vs", spv.STORAGE_OUTPUT, location, **kwargs) - - -def input(location=0, **kwargs): - return simple("ps", spv.STORAGE_INPUT, location, **kwargs) - - -def kinds(producer, consumer, **kwargs): - return [item.kind for item in link.compare_stages(producer.reflect(), consumer.reflect(), **kwargs)] - - -class ReflectTest(unittest.TestCase): - def test_reads_other_byte_order(self): - shader = output() - self.assertEqual(spv.reflect_module(shader.binary(big_endian=True)), shader.reflect()) - - def test_skips_correctly_decorated_builtins(self): - shader = ModuleFixture("vs") - position = shader.variable(spv.STORAGE_OUTPUT, shader.numeric(32, 4)) - shader.decorate(position, spv.DEC_BUILTIN, 0) - self.assertEqual(shader.reflect().outputs, ()) - - def test_skips_builtin_block(self): - shader = ModuleFixture("gs") - block = shader.emit_type(spv.OP_TYPE_STRUCT, shader.numeric(32, 4)) - shader.decorate(block, spv.DEC_BLOCK) - shader.member(block, 0, spv.DEC_BUILTIN, 0) - shader.variable(spv.STORAGE_INPUT, shader.array(block, 3)) - self.assertEqual(shader.reflect().inputs, ()) - - def test_missing_location_is_an_error(self): - shader = ModuleFixture("vs") - shader.variable(spv.STORAGE_OUTPUT, shader.numeric()) - with self.assertRaisesRegex(spv.InterfaceError, "missing a Location"): - shader.reflect() - - def test_64_bit_vector_spans_locations_and_can_share_remaining_components(self): - shader = output(width=64, components=3) - shader.variable(spv.STORAGE_OUTPUT, shader.numeric(32, 2), 1, 2) - declarations = shader.reflect().outputs - self.assertEqual(len(declarations), 2) - used = list(declarations[0].varyings[0].occupied()) - self.assertEqual(used[-1], spv.Address(1, 1)) - - def test_rejects_component_overlap(self): - shader = output(width=64, components=3) - shader.variable(spv.STORAGE_OUTPUT, shader.numeric(), 1, 1) - with self.assertRaisesRegex(spv.InterfaceError, "overlap.*location 1, component 1"): - shader.reflect() - - def test_keeps_fragment_dual_source_outputs_separate(self): - shader = ModuleFixture("ps") - shape = shader.numeric(32, 4) - shader.variable(spv.STORAGE_OUTPUT, shape, 0, index=0) - shader.variable(spv.STORAGE_OUTPUT, shape, 0, index=1) - self.assertEqual([d.varyings[0].address.index for d in shader.reflect().outputs], [0, 1]) - - def test_rejects_vector_that_spills_32_bits_into_another_location(self): - shader = input(component=2, components=3) - with self.assertRaisesRegex(spv.InterfaceError, "extends beyond its Location"): - shader.reflect() - - def test_rejects_64_bit_vec2_at_component_2(self): - shader = output(width=64, components=2, component=2) - with self.assertRaisesRegex(spv.InterfaceError, "Component 0"): - shader.reflect() - - def test_allows_64_bit_scalar_at_component_2(self): - shader = output(width=64, components=1, component=2) - used = list(shader.reflect().outputs[0].varyings[0].occupied()) - self.assertEqual(used, [spv.Address(0, 2), spv.Address(0, 3)]) - - def test_rejects_unbounded_expansion(self): - shader = output(array_count=spv.MAX_EXPANDED_LOCATIONS + 1) - with self.assertRaisesRegex(spv.InterfaceError, "too many interface locations"): - shader.reflect() - - def test_uses_selected_entry_interface_ids(self): - shader = ModuleFixture("ps") - first = shader.variable(spv.STORAGE_INPUT, shader.numeric(), 2) - second = shader.variable(spv.STORAGE_INPUT, shader.numeric(), 6) - shader.entry("main", [first]) - shader.entry("other", [second]) - self.assertEqual(shader.reflect().inputs[0].varyings[0].address.location, 2) - self.assertEqual(shader.reflect("other").inputs[0].varyings[0].address.location, 6) - - def test_same_name_in_different_stages_requires_stage_to_select(self): - shader = ModuleFixture("vs") - shader.entry("main", []) - shader.entry("main", [], stage="ps") - with self.assertRaisesRegex(spv.InterfaceError, "ambiguous"): - shader.reflect() - self.assertEqual(shader.reflect(stage="ps").stage, "ps") - - def test_entry_can_reference_resources_other_than_io(self): - shader = ModuleFixture("ps") - shader.variable(2, shader.numeric()) # Uniform, a different interface. - self.assertEqual(shader.reflect().inputs, ()) - - def test_grouped_decorations_apply_to_members_and_variables(self): - shader = ModuleFixture("vs") - struct_type = shader.emit_type(spv.OP_TYPE_STRUCT, shader.numeric(32, 2)) - shader.decorate(struct_type, spv.DEC_BLOCK) - block = shader.variable(spv.STORAGE_OUTPUT, struct_type) - scalar = shader.variable(spv.STORAGE_OUTPUT, shader.numeric()) - group = shader.allocate() - shader.emit(spv.OP_DECORATION_GROUP, group) - shader.decorate(group, spv.DEC_LOCATION, 2) - shader.emit(spv.OP_GROUP_MEMBER_DECORATE, group, struct_type, 0) - shader.emit(spv.OP_GROUP_DECORATE, group, scalar) - component_group = shader.allocate() - shader.emit(spv.OP_DECORATION_GROUP, component_group) - shader.decorate(component_group, spv.DEC_COMPONENT, 2) - shader.emit(spv.OP_GROUP_DECORATE, component_group, scalar) - declarations = shader.reflect().outputs - self.assertEqual([d.symbol for d in declarations], [block, scalar]) - self.assertEqual([d.varyings[0].address for d in declarations], [spv.Address(2), spv.Address(2, 2)]) - - def test_conflicting_decoration_group_is_rejected(self): - shader = output() - group = shader.allocate() - shader.emit(spv.OP_DECORATION_GROUP, group) - shader.decorate(group, spv.DEC_LOCATION, 5) - shader.emit(spv.OP_GROUP_DECORATE, group, shader.ids[0]) - with self.assertRaisesRegex(spv.InterfaceError, "conflicting Location"): - shader.reflect() - - def test_malformed_header_instruction_and_references(self): - shader = output() - with self.assertRaisesRegex(spv.InterfaceError, "complete"): - spv.reflect_module(shader.binary() + b"\x00") - with self.assertRaisesRegex(spv.InterfaceError, "magic"): - spv.reflect_module(b"\x00" * 4 + shader.binary()[4:]) - with self.assertRaisesRegex(spv.InterfaceError, "instruction length"): - spv.reflect_module(shader.binary()[:-4]) - with self.assertRaisesRegex(spv.InterfaceError, "instruction length"): - spv.reflect_module(shader.binary() + bytes(4)) - missing = ModuleFixture("vs") - missing.entry("main", [missing.allocate()]) - with self.assertRaisesRegex(spv.InterfaceError, "missing variable"): - missing.reflect() - - def test_passthrough_geometry_gets_explicit_unsupported_diagnostic(self): - shader = simple("gs", spv.STORAGE_INPUT, 0, array_count=3) - shader.decorate(shader.ids[0], spv.DEC_PASSTHROUGH_NV) - with self.assertRaisesRegex(spv.InterfaceError, "passthrough"): - shader.reflect() - - -class LinkingTest(unittest.TestCase): - def test_matches_the_projects_generated_partner_modules(self): - vertex = spv.reflect_module(spirv_stubs.build_vs_stub([2, 9]), stage="vs") - pixel = spv.reflect_module(spirv_stubs.build_ps_stub([9, 2], flat_locations=[2]), stage="ps") - self.assertEqual(link.compare_stages(vertex, pixel), []) - - def test_numeric_match_ignores_module_local_ids_and_optional_component_zero(self): - self.assertEqual(kinds(output(), input(component=0)), []) - - def test_unconsumed_outputs_are_allowed(self): - producer = output() - producer.variable(spv.STORAGE_OUTPUT, producer.numeric(), 7) - self.assertEqual(kinds(producer, input()), []) - - def test_missing_output_and_conflicting_start_are_distinct(self): - self.assertEqual(kinds(output(), input(3)), ["missing-output"]) - self.assertEqual(kinds(output(), input(component=2, components=2)), ["location-mismatch"]) - - def test_float_width_and_integer_sign_are_part_of_type(self): - self.assertEqual(kinds(output(components=2, width=16), input(components=2)), ["type-mismatch"]) - self.assertEqual(kinds(output(components=2, kind="u"), input(components=2, kind="i")), ["type-mismatch"]) - - def test_maintenance4_relaxes_only_a_wider_vector_output(self): - self.assertEqual(kinds(output(), input(components=2)), ["type-mismatch"]) - self.assertEqual(kinds(output(), input(components=2), maintenance4=True), []) - self.assertEqual(kinds(output(components=2), input(), maintenance4=True), ["type-mismatch"]) - self.assertEqual(kinds(output(), input(components=1), maintenance4=True), ["type-mismatch"]) - - def test_maintenance4_does_not_unwrap_and_relax_aggregate_shapes(self): - producer = output(array_count=3) - consumer = input(components=2, array_count=3) - self.assertEqual(kinds(producer, consumer, maintenance4=True), ["type-mismatch"]) - self.assertEqual(kinds(output(), simple("gs", spv.STORAGE_INPUT, 0, components=2, array_count=3), - maintenance4=True), ["type-mismatch"]) - - def test_geometry_input_strips_outer_array_only(self): - geometry = ModuleFixture("gs") - member = geometry.array(geometry.numeric(32, 4), 2) - geometry.variable(spv.STORAGE_INPUT, geometry.array(member, 3), 0) - self.assertEqual(kinds(output(array_count=2), geometry), []) - self.assertEqual(kinds(output(array_count=3), geometry), ["type-mismatch"]) - - def test_fragment_per_vertex_matches_non_array_vertex_output(self): - fragment = simple("ps", spv.STORAGE_INPUT, 0, array_count=3) - fragment.decorate(fragment.ids[0], spv.DEC_PER_VERTEX) - self.assertEqual(kinds(output(), fragment), []) - self.assertEqual(kinds(output(array_count=3), fragment), ["type-mismatch"]) - - def test_mesh_nv_and_ext_outputs_match_fragment_domains(self): - for name, model in (("MeshNV", 5268), ("MeshEXT", 5365)): - with self.subTest(model=name): - mesh = ModuleFixture("ms") - vec4 = mesh.numeric(32, 4) - mesh.variable(spv.STORAGE_OUTPUT, mesh.array(vec4, 3), location=0) - primitive = mesh.variable(spv.STORAGE_OUTPUT, mesh.array(vec4, 1), location=1) - mesh.decorate(primitive, spv.DEC_PER_PRIMITIVE) - mesh.entry("main", mesh.ids, model=model) - - reflected = mesh.reflect() - self.assertEqual(reflected.stage, "ms") - self.assertEqual(mesh.reflect(stage="ms"), reflected) - self.assertTrue(all(d.indexed_by_vertex_or_primitive for d in reflected.outputs)) - shape = spv.NumericType("f", 32, 4) - self.assertEqual( - [d.varyings for d in reflected.outputs], - [(spv.Varying(spv.Address(0), shape),), (spv.Varying(spv.Address(1), shape, True),)], - ) - - fragment = input() - fragment_primitive = fragment.variable(spv.STORAGE_INPUT, fragment.numeric(32, 4), location=1) - self.assertEqual(kinds(mesh, fragment), ["per-primitive-mismatch"]) - fragment.decorate(fragment_primitive, spv.DEC_PER_PRIMITIVE) - self.assertEqual(kinds(mesh, fragment), []) - - def test_matching_structure_members_keep_order_and_locations(self): - def block(stage, storage, locations): - shader = ModuleFixture(stage) - shape = shader.emit_type(spv.OP_TYPE_STRUCT, shader.numeric(32, 2), shader.numeric(32, 2)) - shader.decorate(shape, spv.DEC_BLOCK) - for i, location in enumerate(locations): - shader.member(shape, i, spv.DEC_LOCATION, location) - shader.variable(storage, shape) - return shader - - producer = block("vs", spv.STORAGE_OUTPUT, (1, 3)) - self.assertEqual(kinds(producer, block("ps", spv.STORAGE_INPUT, (1, 3))), []) - self.assertEqual(kinds(producer, block("ps", spv.STORAGE_INPUT, (1, 2))), ["location-mismatch"]) - self.assertEqual(kinds(producer, block("ps", spv.STORAGE_INPUT, (3, 1))), ["location-mismatch"]) - self.assertEqual(kinds(producer, input(location=1, components=2)), ["structure-mismatch"]) - - def test_location_on_structure_allocates_consecutive_members(self): - shader = ModuleFixture("vs") - wide = shader.numeric(64, 3) - shape = shader.emit_type(spv.OP_TYPE_STRUCT, wide, shader.numeric()) - shader.variable(spv.STORAGE_OUTPUT, shape, 5) - declarations = shader.reflect().outputs - self.assertEqual([v.address.location for v in declarations[0].varyings], [5, 7]) - - def test_array_length_uses_literal_specialization_default(self) -> None: - producer = ModuleFixture("vs") - length = producer.allocate() - producer.emit(50, producer.uint, length, 2) # OpSpecConstant with default length 2 - producer.decorate(length, 1, 7) # SpecId 7 - shape = producer.emit_type(spv.OP_TYPE_ARRAY, producer.numeric(components=4), length) - producer.variable(spv.STORAGE_OUTPUT, shape, location=0) - - self.assertEqual(kinds(producer, input(array_count=2)), []) - self.assertEqual(kinds(producer, input(array_count=3)), ["type-mismatch"]) - - def test_matrix_and_array_of_columns_are_distinct_types(self): - vertices = ModuleFixture("vs") - column = vertices.numeric(32, 2) - vertices.variable(spv.STORAGE_OUTPUT, vertices.emit_type(spv.OP_TYPE_MATRIX, column, 3), 0) - fragment = ModuleFixture("ps") - column = fragment.numeric(32, 2) - fragment.variable(spv.STORAGE_INPUT, fragment.emit_type(spv.OP_TYPE_MATRIX, column, 3), 0) - self.assertEqual(kinds(vertices, fragment), []) - self.assertEqual(kinds(vertices, input(components=2, array_count=3)), ["type-mismatch"]) - - -class CommandLineTest(unittest.TestCase): - def setUp(self): - directory = tempfile.TemporaryDirectory() - self.addCleanup(directory.cleanup) - self.directory = Path(directory.name) - self.vs = self.module("vertex", output()) - self.ps = self.module("pixel", input()) - self.bad = self.module("bad_pixel", input(location=8)) - self.manifest = self.directory / "pairs.json" - self.report = self.directory / "report.json" - - def module(self, name, builder): - path = self.directory / (name + ".spv") - path.write_bytes(builder.binary()) - return path - - def command(self, *args): - return subprocess.run([sys.executable, "-I", ROOT / "tools" / "shader_link_check.py", *args], - capture_output=True, text=True, timeout=15) - - def write_manifest(self, *items): - self.manifest.write_text(json.dumps({"version": 1, "pipelines": items}), encoding="utf-8") - - def run_batch(self, *extra): - return self.command("batch", self.manifest, "--shader-dir", self.directory, *extra) - - def test_direct_match(self): - result = self.command("check", "--vs", self.vs, "--ps", self.ps) - self.assertEqual(result.returncode, 0, result.stderr) - self.assertIn("compatible (1 links checked)", result.stdout) - - def test_direct_entry_overrides(self): - vertex, pixel = output(), input() - vertex.entry("Vertex", vertex.ids) - pixel.entry("Pixel", pixel.ids) - paths = ("--vs", self.module("v", vertex), "--ps", self.module("p", pixel)) - for options in (("--vs-entry", "Vertex", "--ps-entry", "Pixel"), - ("--entry", "Vertex", "--ps-entry", "Pixel")): - with self.subTest(options=options): - result = self.command("check", *paths, *options) - self.assertEqual(result.returncode, 0, result.stdout + result.stderr) - self.assertIn("compatible (1 links checked)", result.stdout) - missing = self.command("check", *paths, "--entry", "Vertex") - self.assertEqual(missing.returncode, 2) - self.assertIn("[module-error]", missing.stdout) - - def test_direct_entry_requires_its_stage(self): - result = self.command("check", "--vs", self.vs, "--ps", self.ps, "--gs-entry", "Geometry") - self.assertEqual(result.returncode, 2) - self.assertIn("--gs-entry requires --gs", result.stderr) - - def test_incompatible_pipeline_returns_one_and_reports_location(self): - result = self.command("check", "--vs", self.vs, "--ps", self.bad) - self.assertEqual(result.returncode, 1) - self.assertIn("vs -> ps at location 8, component 0 [missing-output]", result.stdout) - - def test_wrong_stage_and_missing_module_return_two(self): - result = self.command("check", "--vs", self.ps, "--ps", self.directory / "missing.spv") - self.assertEqual(result.returncode, 2) - self.assertIn("is ps, expected vs", result.stdout) - self.assertIn("[module-error]", result.stdout) - self.assertNotIn("Traceback", result.stderr) - - def test_invalid_slot_combination_returns_two(self): - result = self.command("check", "--vs", self.vs, "--ms", self.vs, "--ps", self.ps) - self.assertEqual(result.returncode, 2) - self.assertIn("expected vs+ps", result.stderr) - - def test_batch_checks_other_pipelines_after_an_error_and_reports_all(self): - self.write_manifest({"name": "broken", "vs": "vertex", "ps": "missing"}, - {"name": "bad", "vs": "vertex", "ps": "bad_pixel"}, - {"name": "valid", "vs": "vertex", "ps": "pixel"}) - result = self.run_batch("--report", self.report, "--quiet") - self.assertEqual(result.returncode, 2, result.stderr) - self.assertNotIn("valid: compatible", result.stdout) - report = json.loads(self.report.read_bytes()) - self.assertEqual(report["summary"], {"compatible": 1, "incompatible": 1, "invalid": 1}) - self.assertEqual([pipeline["name"] for pipeline in report["pipelines"]], ["broken", "bad", "valid"]) - self.assertEqual(report["pipelines"][1]["problems"][0]["location"]["location"], 8) - self.assertNotIn(b"\r\n", self.report.read_bytes()) - - def test_three_stage_chain_does_not_compare_across_geometry(self): - geometry = simple("gs", spv.STORAGE_INPUT, 0, array_count=3) - geometry.variable(spv.STORAGE_OUTPUT, geometry.numeric(32, 4), 8) - gs = self.module("geometry", geometry) - result = self.command("check", "--vs", self.vs, "--gs", gs, "--ps", self.bad) - self.assertEqual(result.returncode, 0, result.stdout + result.stderr) - self.assertIn("compatible (2 links checked)", result.stdout) - - def test_alternate_entry_names_are_resolved_per_stage(self): - shader = input() - shader.entry("ColorMain", shader.ids) - self.module("alternative", shader) - self.write_manifest({"name": "alt", "vs": "vertex", "ps": {"shader": "alternative", "entry": "ColorMain"}}) - result = self.run_batch() - self.assertEqual(result.returncode, 0, result.stdout + result.stderr) - - def test_duplicate_manifest_key_is_rejected_with_path_and_key(self): - # The last stage value would produce a valid pipeline if the duplicate were ignored. - self.manifest.write_text( - '{"version": 1, "pipelines": [' - '{"name": "dup", "vs": "missing", "vs": "vertex", "ps": "pixel"}]}', - encoding="utf-8", - ) - result = self.run_batch("--report", self.report) - self.assertEqual(result.returncode, 2) - self.assertIn(str(self.manifest), result.stderr) - self.assertIn("duplicate key 'vs'", result.stderr) - self.assertFalse(self.report.exists()) - - def test_bad_manifest_fields_return_clean_error(self): - cases = [ - {"version": True, "pipelines": []}, - {"pipelines": [{"name": "x", "vs": "../vertex", "ps": "pixel"}]}, - {"pipelines": [{"name": "x", "vs": "vertex", "ps": "pixel"}] * 2}, - {"pipelines": [{"name": "x", "vs": "vertex", "ps": {"path": "pixel.spv"}}]}, - ] - for document in cases: - with self.subTest(document=document): - self.manifest.write_text(json.dumps(document), encoding="utf-8") - result = self.run_batch() - self.assertEqual(result.returncode, 2) - self.assertIn("shader_link_check: error:", result.stderr) - self.assertNotIn("Traceback", result.stderr) - - def test_manifest_saved_with_a_windows_bom_is_read(self): - # Notepad and PowerShell 5's Out-File -Encoding utf8 put a BOM first; that is not a manifest error. - self.manifest.write_bytes(b"\xef\xbb\xbf" + json.dumps( - {"version": 1, "pipelines": [{"name": "bom", "vs": "vertex", "ps": "pixel"}]}).encode("utf-8")) - result = self.run_batch() - self.assertEqual(result.returncode, 0, result.stderr) - self.assertIn("bom: compatible", result.stdout) - - def test_corpus_style_names_are_accepted_and_paths_are_not(self): - # make_game's corpus names (shader_carve stems) contain "~", "!", "&", "(", a leading "." and more: 21,043 of - # 26,503 on a 1.0.2.1 copy failed the old [a-zA-Z0-9_.-] rule. Only names that leave --shader-dir fail. - for stem in ("VS~1", "pixel!2&x", "a(b)c", "x y", "_~-.ok", ".dotted"): - with self.subTest(stem=stem): - (self.directory / (stem + ".spv")).write_bytes(self.vs.read_bytes()) - self.write_manifest({"name": "n", "vs": stem, "ps": "pixel"}) - result = self.run_batch() - self.assertEqual(result.returncode, 0, result.stdout + result.stderr) - for stem in ("../vertex", "..", ".", "sub/vertex", "sub\\vertex", "C:vertex", "a|b", "a\x00b", - " vertex", ""): - with self.subTest(stem=stem): - self.write_manifest({"name": "n", "vs": stem, "ps": "pixel"}) - result = self.run_batch() - self.assertEqual(result.returncode, 2, result.stdout + result.stderr) - self.assertIn("expected a shader name without directories", result.stderr) - - def test_report_preserves_inputs(self): - original = self.vs.read_bytes() - result = self.command("check", "--vs", self.vs, "--ps", self.ps, "--report", self.vs) - self.assertEqual(result.returncode, 2) - self.assertEqual(self.vs.read_bytes(), original) - self.write_manifest({"name": "x", "vs": "vertex", "ps": "pixel"}) - result = self.run_batch("--report", self.manifest) - self.assertEqual(result.returncode, 2) - self.assertTrue(json.loads(self.manifest.read_text())["pipelines"]) - - def test_existing_report_cannot_be_a_hard_link_to_an_input(self): - original = self.vs.read_bytes() - try: - os.link(self.vs, self.report) - except OSError as exc: - self.skipTest(f"hard links unavailable: {exc}") - result = self.command("check", "--vs", self.vs, "--ps", self.ps, "--report", self.report) - self.assertEqual(result.returncode, 2, result.stderr) - self.assertIn("report would overwrite an input file", result.stderr) - self.assertTrue(self.report.samefile(self.vs)) - self.assertEqual(self.vs.read_bytes(), original) - - def test_missing_report_path_still_cannot_match_an_input_path(self): - with self.assertRaisesRegex(ValueError, "report would overwrite an input file"): - link.ensure_report_is_separate(self.report, [self.report]) - - def test_inspect_keeps_types_and_components(self): - shader = self.module("with_component", input(location=3, component=2, components=2)) - result = self.command("inspect", shader) - self.assertEqual(result.returncode, 0) - self.assertEqual(json.loads(result.stdout)["inputs"][0]["varyings"], - [{"location": 3, "component": 2, "index": 0, "type": "vec2", - "per_primitive": False}]) - - def test_shader_is_reflected_once_for_repeated_pipelines(self): - self.write_manifest(*({"name": f"pair-{i}", "vs": "vertex", "ps": "pixel"} for i in range(20))) - output_stream = io.StringIO() - with patch.object(link, "reflect_module", wraps=link.reflect_module) as reflect: - with contextlib.redirect_stdout(output_stream): - result = link.main(["batch", str(self.manifest), "--shader-dir", str(self.directory), "--quiet"]) - self.assertEqual(result, 0) - self.assertEqual(reflect.call_count, 2) - - -if __name__ == "__main__": - unittest.main(verbosity=2) diff --git a/tests/test_shader_meta.py b/tests/test_shader_meta.py deleted file mode 100644 index b87a762b4..000000000 --- a/tests/test_shader_meta.py +++ /dev/null @@ -1,752 +0,0 @@ -"""Unit tests for tools/shader_meta.py and rdna2spirv.shader_meta() (standard library only, no game data). - - python -I tests/test_shader_meta.py -""" -import gc -import hashlib -import json -import os -import struct -import sys -import tempfile -import unittest -import warnings - -ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) -sys.path.insert(0, os.path.join(ROOT, "tools")) - -import rdna2spirv # noqa: E402 -import shader_meta as M # noqa: E402 - - -def make_dxbc(chunks): - head = 32 + 4 * len(chunks) - offsets, body = [], b"" - for fourcc, payload in chunks: - offsets.append(head + len(body)) - body += fourcc + struct.pack(" 64-bit descriptor-table pointer, offset by (s2 << 5) (32-byte T# stride) - # s2 -> 32-bit descriptor index constant - # s3 -> 32-bit scalar constant copied to v4 - # s[12:15] -> literal S# built from immediates (example from docs/design.md) - lines = [ - "s_lshl_b32 s4, s2, 5", - "s_add_u32 s6, s0, s4", - "s_addc_u32 s7, s1, 0", - "s_load_dwordx8 s[16:23], s[6:7], 0x0", - "s_mov_b32 s12, 0x92", - "s_mov_b32 s13, 0x00c00000", - "s_mov_b32 s14, 0x14500000", - "s_mov_b32 s15, 0", - "v_mov_b32_e32 v0, 0.5", - "v_mov_b32_e32 v1, 0.5", - "image_sample v[4:7], v[0:1], s[16:23], s[12:15] dmask:0xf dim:SQ_RSRC_IMG_2D", - "v_add_nc_u32_e32 v4, s3, v4", - "exp mrt0 v4, v5, v6, v7 done vm", - "s_endpgm", - ] - fssm_bytes = b"FSSM" + b"\x01\x02\x03\x04" * 16 - dxbc = make_dxbc([ - isg1_chunk([("SV_Position", 0, 0, 0xF, 0x3, 1, 3)]), - sfi0_chunk(M.SFI0_RESOURCE_DESCRIPTOR_HEAP_INDEXING), - ]) - _, meta = translate_synthetic("ps_meta_test", lines, dxbc=dxbc, fssm=fssm_bytes) - - self.assertEqual(meta["fssm_sha256"], hashlib.sha256(fssm_bytes).hexdigest()) - self.assertEqual(meta["user_sgpr_reads"], [ - {"sgpr": 0, "kind": "ptr64_lo", "pair": [0, 1]}, - {"sgpr": 1, "kind": "ptr64_hi", "pair": [0, 1]}, - {"sgpr": 2, "kind": "const32"}, - {"sgpr": 3, "kind": "const32"}, - ]) - self.assertEqual(meta["descriptor_strides"], [32]) - self.assertEqual(meta["literal_samplers"], [[0x92, 0x00C00000, 0x14500000, 0]]) - self.assertEqual(meta["descriptor_access"], { - "table_loads": True, - "truncates_table_ptr_high": False, - "resource_heap_directly_indexed": True, - "sampler_heap_directly_indexed": False, - }) - self.assertEqual(meta["input_signature"][0]["semantic"], "SV_Position") - self.assertNotIn("uses_code_base", meta) - - def test_truncated_32bit_table_pointer_and_vscale_stride(self): - # Descriptor-table pointer in s2 with high dword forced to 0 (below 4 GB), stride 16 via VGPR shift. - lines = [ - "s_mov_b32 s3, 0", - "v_mov_b32_e32 v2, 1", - "v_lshlrev_b32_e32 v3, 4, v2", - "v_readfirstlane_b32 s4, v3", - "s_load_dwordx4 s[8:11], s[2:3], s4", - "v_mov_b32_e32 v0, s8", - "exp mrt0 v0, v0, v0, v0 done vm", - "s_endpgm", - ] - _, meta = translate_synthetic("ps_trunc_ptr", lines) - # s3 was written before any read, so only s2 is read-before-write (and classified ptr32_lo). - self.assertEqual(meta["user_sgpr_reads"], [{"sgpr": 2, "kind": "ptr32_lo"}]) - self.assertEqual(meta["descriptor_strides"], [16]) - self.assertEqual(meta["descriptor_access"], { - "table_loads": True, - "truncates_table_ptr_high": True, - }) - - def test_uses_code_base_without_false_user_ptr(self): - # s_getpc_b64 + s_load_dwordx4 reads code-embedded data; must set uses_code_base=True and NOT - # claim any user SGPR was read or that a descriptor table was loaded. - lines = [ - "s_getpc_b64 s[4:5] ; encoding: [0x04,0x1c,0x84,0xbe]", - "s_add_u32 s4, s4, 64 ; encoding: [0x04,0xff,0x04,0x80,0x40,0x00,0x00,0x00]", - "s_addc_u32 s5, s5, 0 ; encoding: [0x05,0x80,0x05,0x82]", - "s_load_dwordx4 s[8:11], s[4:5], 0x0 ; encoding: [0x02,0x02,0x08,0xf4,0x00,0x00,0x00,0x00]", - "v_mov_b32_e32 v0, s8 ; encoding: [0x08,0x02,0x00,0x7e]", - "exp mrt0 v0, v0, v0, v0 done vm ; encoding: [0x0f,0x08,0x00,0xf8,0x00,0x00,0x00,0x00]", - "s_endpgm ; encoding: [0x00,0x00,0x81,0xbf]", - ] - _, meta = translate_synthetic("ps_codebase", lines) - self.assertTrue(meta["uses_code_base"]) - self.assertNotIn("user_sgpr_reads", meta) - self.assertNotIn("descriptor_access", meta) - - def test_compute_excludes_workgroup_id_sgprs_and_detects_vsharp(self): - # RSRC2 0x8088: 4 user SGPRs (s0..s3 = V#), TGID_X enabled in s4 (system SGPR, NOT user data). - fssm = bytearray(0x148) - struct.pack_into("<4I", fssm, 0x138, 0x8088, 64, 1, 1) - lines = [ - "v_lshlrev_b32_e32 v1, 2, v0", - "v_mov_b32_e32 v2, s4", - "buffer_store_dword v2, v1, s[0:3], 0 offen", - "s_endpgm", - ] - _, meta = translate_synthetic("cs_vsharp", lines, fssm=bytes(fssm)) - self.assertEqual(meta["user_sgprs"], 4) - # s4 (workgroup id) is excluded; s0..s3 are classified as vsharp. - self.assertEqual(meta["user_sgpr_reads"], [ - {"sgpr": 0, "kind": "vsharp"}, - {"sgpr": 1, "kind": "vsharp"}, - {"sgpr": 2, "kind": "vsharp"}, - {"sgpr": 3, "kind": "vsharp"}, - ]) - self.assertEqual(meta["fssm_sha256"], hashlib.sha256(bytes(fssm)).hexdigest()) - - def test_branch_control_flow_must_write_and_literal_sampler_disagreement(self): - # Block 0 branches to block 1 (writes s5, s6 and sets s12=0x92) or block 2 (writes s6 only and sets s12=0x11). - # Block 3 reads s5 (unread on path 0->2 -> MUST appear in user_sgpr_reads), reads s6 (written on BOTH arms -> - # must NOT appear in user_sgpr_reads), and samples with s[12:15] (s12 differs across arms -> must NOT be - # emitted as a literal sampler). - lines = [ - "s_cmp_eq_u32 s0, 0 ; encoding: [0x00,0x80,0x00,0xbf]", - "s_cbranch_scc1 5 ; encoding: [0x05,0x00,0x85,0xbf]", - "s_mov_b32 s5, 1 ; encoding: [0x81,0x03,0x85,0xbe]", - "s_mov_b32 s6, 2 ; encoding: [0x82,0x03,0x86,0xbe]", - "s_mov_b32 s12, 0x92 ; encoding: [0xff,0x03,0x8c,0xbe,0x92,0x00,0x00,0x00]", - "s_branch 2 ; encoding: [0x02,0x00,0x82,0xbf]", - "s_mov_b32 s6, 3 ; encoding: [0x83,0x03,0x86,0xbe]", - "s_mov_b32 s12, 0x11 ; encoding: [0x91,0x03,0x8c,0xbe]", - "s_mov_b32 s13, 0 ; encoding: [0x80,0x03,0x8d,0xbe]", - "s_mov_b32 s14, 0 ; encoding: [0x80,0x03,0x8e,0xbe]", - "s_mov_b32 s15, 0 ; encoding: [0x80,0x03,0x8f,0xbe]", - "s_load_dwordx8 s[16:23], s[2:3], 0x0 ; encoding: [0x01,0x04,0x0c,0xf4,0x00,0x00,0x00,0x00]", - "v_mov_b32_e32 v0, 0.5 ; encoding: [0xf0,0x02,0x00,0x7e]", - "v_mov_b32_e32 v1, 0.5 ; encoding: [0xf0,0x02,0x02,0x7e]", - "image_sample v[4:7], v[0:1], s[16:23], s[12:15] dmask:0xf dim:SQ_RSRC_IMG_2D ; encoding: [0x00,0x0f,0x80,0xf0,0x00,0x04,0x64,0x00]", - "v_add_nc_u32_e32 v4, s5, v4 ; encoding: [0x05,0x08,0x08,0x4a]", - "v_add_nc_u32_e32 v5, s6, v5 ; encoding: [0x06,0x0a,0x0a,0x4a]", - "exp mrt0 v4, v5, v6, v7 done vm ; encoding: [0x0f,0x08,0x00,0xf8,0x04,0x05,0x06,0x07]", - "s_endpgm ; encoding: [0x00,0x00,0x81,0xbf]", - ] - _, meta = translate_synthetic("ps_cfg_meta", lines) - sgprs = {r["sgpr"]: r["kind"] for r in meta["user_sgpr_reads"]} - self.assertEqual(sgprs, {0: "const32", 2: "ptr64_lo", 3: "ptr64_hi", 5: "const32"}) - self.assertNotIn("literal_samplers", meta) - - def test_global_ptr64_and_mul_stride(self): - # global_load_dword via user-SGPR pair s[4:5], plus s_mul_i32 48-byte stride into s_load_dwordx8. - lines = [ - "s_mul_i32 s8, s2, 48", - "s_load_dwordx8 s[16:23], s[0:1], s8", - "v_mov_b32_e32 v0, 0", - "global_load_dword v1, v0, s[4:5]", - "v_add_nc_u32_e32 v1, s16, v1", - "exp mrt0 v1, v1, v1, v1 done vm", - "s_endpgm", - ] - _, meta = translate_synthetic("ps_global_stride", lines) - self.assertEqual(meta["user_sgpr_reads"], [ - {"sgpr": 0, "kind": "ptr64_lo", "pair": [0, 1]}, - {"sgpr": 1, "kind": "ptr64_hi", "pair": [0, 1]}, - {"sgpr": 2, "kind": "const32"}, - {"sgpr": 4, "kind": "ptr64_lo", "pair": [4, 5]}, - {"sgpr": 5, "kind": "ptr64_hi", "pair": [4, 5]}, - ]) - self.assertEqual(meta["descriptor_strides"], [48]) - - def test_index_json_compatible_with_vk_pipeline_check(self): - lines = [ - "s_lshl_b32 s4, s2, 5", - "s_load_dwordx8 s[16:23], s[0:1], s4", - "s_mov_b32 s12, 0x92", - "s_mov_b32 s13, 0", - "s_mov_b32 s14, 0", - "s_mov_b32 s15, 0", - "v_mov_b32_e32 v0, 0.5", - "v_mov_b32_e32 v1, 0.5", - "image_sample v[4:7], v[0:1], s[16:23], s[12:15] dmask:0xf dim:SQ_RSRC_IMG_2D", - "exp mrt0 v4, v5, v6, v7 done vm", - "s_endpgm", - ] - dxbc = make_dxbc([ - isg1_chunk([("POSITION", 0, 0, 0x7, 0x7, 0, 3)]), - sfi0_chunk(M.SFI0_RESOURCE_DESCRIPTOR_HEAP_INDEXING), - ]) - _, ps_meta = translate_synthetic("ps_one", lines, dxbc=dxbc, fssm=b"FSSM1234") - fssm_cs = bytearray(0x148) - struct.pack_into("<4I", fssm_cs, 0x138, 0x8088, 64, 1, 1) - _, cs_meta = translate_synthetic("cs_two", ["s_mov_b64 exec, -1", "s_endpgm"], fssm=bytes(fssm_cs)) - - dumped = json.dumps({"ps_one": ps_meta, "cs_two": cs_meta}, indent=0, sort_keys=True) - parsed = vk_pipeline_check_read_index(dumped) - self.assertEqual(parsed, { - "ps_one": {"stage": "ps", "subgroup_size": 32}, - "cs_two": {"stage": "cs", "subgroup_size": 64}, - }) - - - def test_imm_u32_applies_vop3_abs_before_neg(self): - import shader_ir - self.assertEqual(M._imm_u32(shader_ir.operand("-|1.0|")), 0xBF800000) - self.assertEqual(M._imm_u32(shader_ir.operand("-|-2.0|")), 0xC0000000) - self.assertEqual(M._imm_u32(shader_ir.operand("neg(0x3f800000)")), 0xBF800000) - self.assertEqual(M._imm_u32(shader_ir.operand("|0xbf800000|")), 0x3F800000) - self.assertEqual(M._imm_u32(shader_ir.operand("-|0|")), 0x80000000) - self.assertEqual(M._imm_u32(shader_ir.operand("neg(1)")), 0x80000001) - - -class OperandClassificationTests(unittest.TestCase): - @staticmethod - def _parse(lines): - import shader_ir - return [shader_ir.parse_line(ln) for ln in lines] - - def test_split_operands_scalar_rmw(self): - import shader_ir - cases = [ - ("s_cmov_b32 s2, s4", [2, 4], [2]), - ("s_cmov_b64 s[2:3], s[4:5]", [2, 3, 4, 5], [2, 3]), - ("s_bitset0_b32 s3, 7", [3], [3]), - ("s_bitset1_b32 s3, s5", [3, 5], [3]), - ("s_bitset0_b64 s[4:5], 33", [4, 5], [4, 5]), - ("s_bitset1_b64 s[4:5], s6", [4, 5, 6], [4, 5]), - ] - for asm, want_reads, want_writes in cases: - with self.subTest(asm=asm): - reads, writes = M._split_operands(shader_ir.parse_line(asm)) - self.assertEqual(reads, want_reads) - self.assertEqual(writes, want_writes) - - def test_split_operands_v_div_scale_dual_dst(self): - import shader_ir - cases = [ - ("v_div_scale_f32 v0, s4, v1, v2, s6", [6], [4]), - ("v_div_scale_f32_e64 v0, s4, v1, v2, v1", [], [4]), - ("v_div_scale_f32 v0, s[4:5], s7, v1, v2", [7], [4, 5]), - ("v_div_scale_f64 v[0:1], s[4:5], v[2:3], v[4:5], s[6:7]", [6, 7], [4, 5]), - ("v_div_scale_f64 v[0:1], vcc, v[2:3], v[4:5], v[2:3]", [], []), - ] - for asm, want_reads, want_writes in cases: - with self.subTest(asm=asm): - reads, writes = M._split_operands(shader_ir.parse_line(asm)) - self.assertEqual(reads, want_reads) - self.assertEqual(writes, want_writes) - - def test_analyse_scalar_rmw_keeps_live_user_sgprs_and_invalidates_tags(self): - # Each RMW op on an unwritten user SGPR (or pair) must record a user_sgpr_read. - # s10 is written first, so s_bitset1_b32 on s10 must NOT mark s10 as a user SGPR. - # s12 is initialized to a constant then conditionally overwritten by s_cmov_b32, - # invalidating the constant tag so s[12:15] is NOT emitted as a literal sampler. - insns = self._parse([ - "s_mov_b32 s10, 0", - "s_bitset1_b32 s10, 1", - "s_cmov_b32 s0, 1", - "s_cmov_b64 s[2:3], s[20:21]", - "s_bitset0_b32 s4, 2", - "s_bitset1_b32 s5, 3", - "s_bitset0_b64 s[6:7], 4", - "s_bitset1_b64 s[8:9], 35", - "s_mov_b32 s12, 0x92", - "s_mov_b32 s13, 0", - "s_mov_b32 s14, 0", - "s_mov_b32 s15, 0", - "s_cmov_b32 s12, s11", - "image_sample v[4:7], v[0:1], s[24:31], s[12:15] dmask:0xf dim:SQ_RSRC_IMG_2D", - "s_endpgm", - ]) - got = M.analyse_instructions([insns], [[]]) - sgprs = {r["sgpr"]: r["kind"] for r in got["user_sgpr_reads"]} - for r in (0, 2, 3, 4, 5, 6, 7, 8, 9, 11, 20, 21): - self.assertIn(r, sgprs, f"expected s{r} in user_sgpr_reads") - self.assertNotIn(10, sgprs) - self.assertNotIn(12, sgprs) - self.assertEqual(got["literal_samplers"], []) - - def test_analyse_v_div_scale_sdst_not_user_sgpr_even_when_read_after(self): - # s4 (f32 wave32 sdst) and s[6:7] (f64 wave64 sdst) are scratch outputs written by - # v_div_scale_* and then read later; neither may fabricate a user SGPR. - # s2 and s[8:9] are source operands and MUST be reported as user SGPRs. - insns = self._parse([ - "v_div_scale_f32 v0, s4, s2, v1, s2", - "v_mov_b32_e32 v2, s4", - "v_div_scale_f64 v[4:5], s[6:7], v[2:3], v[6:7], s[8:9]", - "s_or_b64 s[10:11], s[6:7], s[6:7]", - "s_endpgm", - ]) - got = M.analyse_instructions([insns], [[]]) - sgprs = [r["sgpr"] for r in got["user_sgpr_reads"]] - self.assertEqual(sgprs, [2, 8, 9]) - - def test_translate_synthetic_scalar_rmw_user_sgprs(self): - lines = [ - "s_cmp_eq_u32 s0, 0", - "s_cmov_b32 s1, 42", - "s_bitset0_b32 s2, 1", - "s_bitset1_b32 s3, 2", - "s_bitset0_b64 s[4:5], 5", - "s_bitset1_b64 s[6:7], 36", - "v_mov_b32_e32 v0, s1", - "v_add_nc_u32_e32 v0, s2, v0", - "v_add_nc_u32_e32 v0, s3, v0", - "v_add_nc_u32_e32 v0, s4, v0", - "v_add_nc_u32_e32 v0, s5, v0", - "v_add_nc_u32_e32 v0, s6, v0", - "v_add_nc_u32_e32 v0, s7, v0", - "exp mrt0 v0, v0, v0, v0 done vm", - "s_endpgm", - ] - _, meta = translate_synthetic("ps_rmw_user", lines) - sgprs = [r["sgpr"] for r in meta["user_sgpr_reads"]] - self.assertEqual(sgprs, [0, 1, 2, 3, 4, 5, 6, 7]) - - def test_global_atomic_ptr64_and_truncated_ptr32(self): - # global_atomic_add without glc (saddr at a[2]) and with glc (saddr at a[3]) must classify - # 64-bit user-SGPR pointers and 32-bit high-zeroed pointers the same way as global_load/store. - lines = [ - "v_mov_b32_e32 v0, 0", - "v_mov_b32_e32 v1, 1", - "global_atomic_add v0, v1, s[0:1]", - "global_atomic_add v2, v0, v1, s[2:3] glc", - "s_mov_b32 s5, 0", - "global_atomic_add v3, v0, v1, s[4:5] glc", - "exp mrt0 v2, v3, v2, v3 done vm", - "s_endpgm", - ] - _, meta = translate_synthetic("ps_global_atomic_meta", lines) - self.assertEqual(meta["user_sgpr_reads"], [ - {"sgpr": 0, "kind": "ptr64_lo", "pair": [0, 1]}, - {"sgpr": 1, "kind": "ptr64_hi", "pair": [0, 1]}, - {"sgpr": 2, "kind": "ptr64_lo", "pair": [2, 3]}, - {"sgpr": 3, "kind": "ptr64_hi", "pair": [2, 3]}, - {"sgpr": 4, "kind": "ptr32_lo"}, - ]) - self.assertEqual(meta["descriptor_access"], { - "table_loads": False, - "truncates_table_ptr_high": True, - }) - - def test_s_mulk_i32_stride_and_constant_folding(self): - # s_mulk_i32 scales a descriptor index (32-byte stride) and folds signed 16-bit constants. - lines = [ - "s_mov_b32 s4, s2", - "s_mulk_i32 s4, 32", - "s_load_dwordx8 s[16:23], s[0:1], s4", - "s_mov_b32 s12, 0x49", - "s_mulk_i32 s12, 2", - "s_mov_b32 s13, 1", - "s_mulk_i32 s13, -1", - "s_mov_b32 s14, 0", - "s_mov_b32 s15, 0", - "v_mov_b32_e32 v0, 0.5", - "v_mov_b32_e32 v1, 0.5", - "image_sample v[4:7], v[0:1], s[16:23], s[12:15] dmask:0xf dim:SQ_RSRC_IMG_2D", - "exp mrt0 v4, v5, v6, v7 done vm", - "s_endpgm", - ] - _, meta = translate_synthetic("ps_mulk_meta", lines) - self.assertEqual(meta["descriptor_strides"], [32]) - self.assertEqual(meta["literal_samplers"], [[0x92, 0xFFFFFFFF, 0, 0]]) - - def test_s_brev_b32_constant_folding(self): - # A literal S# with one dword bit-reversed by s_brev_b32 from an immediate or a known SGPR. - lines = [ - "s_mov_b32 s12, 0x92", - "s_brev_b32 s13, 1", - "s_mov_b32 s20, 0x3", - "s_brev_b32 s14, s20", - "s_mov_b32 s15, 0", - "v_mov_b32_e32 v0, 0.5", - "v_mov_b32_e32 v1, 0.5", - "image_sample v[4:7], v[0:1], s[0:7], s[12:15] dmask:0xf dim:SQ_RSRC_IMG_2D", - "exp mrt0 v4, v5, v6, v7 done vm", - "s_endpgm", - ] - _, meta = translate_synthetic("ps_brev_meta", lines) - self.assertEqual(meta["literal_samplers"], [[0x92, 0x80000000, 0xC0000000, 0]]) - - def test_s_brev_b32_of_unknown_source_is_not_a_literal(self): - # s_brev_b32 of a user SGPR leaves its destination unknown, so no literal S# is recorded. - lines = [ - "s_mov_b32 s12, 0x92", - "s_brev_b32 s13, s2", - "s_mov_b32 s14, 0", - "s_mov_b32 s15, 0", - "v_mov_b32_e32 v0, 0.5", - "v_mov_b32_e32 v1, 0.5", - "image_sample v[4:7], v[0:1], s[0:7], s[12:15] dmask:0xf dim:SQ_RSRC_IMG_2D", - "exp mrt0 v4, v5, v6, v7 done vm", - "s_endpgm", - ] - _, meta = translate_synthetic("ps_brev_user_meta", lines) - self.assertNotIn("literal_samplers", meta) - - def test_scalar_store_pointer_and_vsharp(self): - # s_store_dword* classifies its 2-SGPR pointer pair without marking table_loads, - # and s_buffer_store_dword* classifies its 4-SGPR resource descriptor as vsharp. - insns = self._parse([ - "s_store_dword s8, s[0:1], 0x0", - "s_mov_b32 s3, 0", - "s_store_dwordx4 s[8:11], s[2:3], 0x0", - "s_buffer_store_dword s8, s[4:7], 0x0", - "s_endpgm", - ]) - got = M.analyse_instructions([insns], [[]]) - self.assertEqual(got["user_sgpr_reads"], [ - {"sgpr": 0, "kind": "ptr64_lo", "pair": [0, 1]}, - {"sgpr": 1, "kind": "ptr64_hi", "pair": [0, 1]}, - {"sgpr": 2, "kind": "ptr32_lo"}, - {"sgpr": 4, "kind": "vsharp"}, - {"sgpr": 5, "kind": "vsharp"}, - {"sgpr": 6, "kind": "vsharp"}, - {"sgpr": 7, "kind": "vsharp"}, - {"sgpr": 8, "kind": "const32"}, - {"sgpr": 9, "kind": "const32"}, - {"sgpr": 10, "kind": "const32"}, - {"sgpr": 11, "kind": "const32"}, - ]) - self.assertFalse(got["table_loads"]) - self.assertTrue(got["truncates_high"]) - - @staticmethod - def _literal_samplers_with(build_s13): - # A literal S# in s[12:15]: s12 = 0x92, s14 = s15 = 0, and s13 built by the given hand-written lines. - # s8 = 0x80000000 and s9 = 0xf0 are known constants; s3 is a user SGPR (not a known constant). - import shader_ir - lines = ["s_mov_b32 s8, 0x80000000", "s_mov_b32 s9, 0xf0", "s_mov_b32 s12, 0x92", *build_s13, - "s_mov_b32 s14, 0", "s_mov_b32 s15, 0", - "image_sample v[4:7], v[0:1], s[16:23], s[12:15] dmask:0xf dim:SQ_RSRC_IMG_2D", "s_endpgm"] - return M.analyse_instructions([[shader_ir.parse_line(ln) for ln in lines]], [[]])["literal_samplers"] - - def test_inverted_scalar_logic_folds_into_literal_sampler(self): - # s_not_b32, s_nand_b32, s_nor_b32 and s_xnor_b32 of known constants give a known constant, so a literal - # S# with a dword built by one of them is reported in literal_samplers. - cases = [ - (["s_not_b32 s13, 0"], 0xFFFFFFFF), - (["s_not_b32 s13, s9"], 0xFFFFFF0F), - (["s_not_b32 s13, s8"], 0x7FFFFFFF), - (["s_mov_b32 s13, 0xf0", "s_not_b32 s13, s13"], 0xFFFFFF0F), # source and destination are one register - (["s_nand_b32 s13, s9, 0x30"], 0xFFFFFFCF), - (["s_nand_b32 s13, s8, s8"], 0x7FFFFFFF), - (["s_nor_b32 s13, s9, 0x0f"], 0xFFFFFF00), - (["s_nor_b32 s13, 0, 0"], 0xFFFFFFFF), - (["s_xnor_b32 s13, s9, 0xff"], 0xFFFFFFF0), - (["s_xnor_b32 s13, s9, s9"], 0xFFFFFFFF), - # The case found with #4289 open: the complement of 0, then a second fold of the result. - (["s_not_b32 s13, 0", "s_and_b32 s13, s13, 0xffff00ff"], 0xFFFF00FF), - ] - for build, want in cases: - with self.subTest(build=build): - self.assertEqual(self._literal_samplers_with(build), [[0x92, want, 0, 0]]) - - def test_shift_bitfield_min_max_abs_fold_into_literal_sampler(self): - # s_ashr_i32, s_bfm_b32, s_bfe_u32, s_min_u32, s_max_u32 and s_abs_i32 of known constants give a known - # constant. The expected values are the ones the translator computes for immediates (rdna2spirv.py). - cases = [ - (["s_ashr_i32 s13, s8, 4"], 0xF8000000), # the sign bit comes in from the left - (["s_ashr_i32 s13, s9, 4"], 0x0000000F), - (["s_ashr_i32 s13, s8, 36"], 0xF8000000), # the shift count is taken modulo 32 - (["s_bfm_b32 s13, 4, 8"], 0x00000F00), # width 4, offset 8 - (["s_bfm_b32 s13, 0, 8"], 0x00000000), - (["s_bfm_b32 s13, 31, 1"], 0xFFFFFFFE), - (["s_bfe_u32 s13, s9, 0x40004"], 0x0000000F), # offset 4, width 4 - (["s_bfe_u32 s13, s8, 0x20001f"], 0x00000001), # offset 31, width 32: the field stops at bit 31 - (["s_bfe_u32 s13, s9, 0x4"], 0x00000000), # width 0 - (["s_min_u32 s13, s9, 0x10"], 0x00000010), - (["s_min_u32 s13, s8, s9"], 0x000000F0), # unsigned: 0x80000000 is the larger value - (["s_max_u32 s13, s9, 0x10"], 0x000000F0), - (["s_max_u32 s13, s8, s9"], 0x80000000), - (["s_abs_i32 s13, s9"], 0x000000F0), - (["s_abs_i32 s13, -16"], 0x00000010), - (["s_abs_i32 s13, s8"], 0x80000000), # the most negative value has no positive form - ] - for build, want in cases: - with self.subTest(build=build): - self.assertEqual(self._literal_samplers_with(build), [[0x92, want, 0, 0]]) - - def test_shift_bitfield_min_max_abs_of_unknown_source_is_not_a_literal(self): - for build in (["s_ashr_i32 s13, s3, 4"], - ["s_mov_b32 s13, 0", "s_ashr_i32 s13, s9, s3"], - ["s_bfm_b32 s13, s3, 8"], - ["s_bfe_u32 s13, s3, 0x40004"], - ["s_bfe_u32 s13, s9, s3"], - ["s_min_u32 s13, s9, s3"], - ["s_max_u32 s13, s3, s9"], - ["s_mov_b32 s13, 0", "s_abs_i32 s13, s3"]): - with self.subTest(build=build): - self.assertEqual(self._literal_samplers_with(build), []) - - def test_inverted_scalar_logic_of_unknown_source_is_not_a_literal(self): - # A source that is not a known constant (the user SGPR s3) must not give a literal sampler, also when the - # destination held a known constant before the operation. - for build in (["s_not_b32 s13, s3"], - ["s_mov_b32 s13, 0", "s_not_b32 s13, s3"], - ["s_nand_b32 s13, s3, 0x30"], - ["s_nor_b32 s13, s9, s3"], - ["s_mov_b32 s13, 0", "s_xnor_b32 s13, s3, s9"]): - with self.subTest(build=build): - self.assertEqual(self._literal_samplers_with(build), []) - - def test_slist_operands_classify_pointers_and_descriptors(self): - # LLVM VCCTuple slist syntax ([s0, s1], [s4, s5, s6, s7], ...) must be classified - # identically to contiguous s[a:b] ranges. - lines = [ - "s_load_dwordx4 s[16:19], [s0, s1], 0x0", - "v_mov_b32_e32 v0, 0", - "global_load_dword v1, v0, [s2, s3]", - "buffer_load_dword v2, v0, [s4, s5, s6, s7], 0 offen", - "v_add_nc_u32_e32 v1, v1, v2", - "v_add_nc_u32_e32 v1, s16, v1", - "exp mrt0 v1, v1, v1, v1 done vm", - "s_endpgm", - ] - _, meta = translate_synthetic("ps_slist_meta", lines) - self.assertEqual(meta["user_sgpr_reads"], [ - {"sgpr": 0, "kind": "ptr64_lo", "pair": [0, 1]}, - {"sgpr": 1, "kind": "ptr64_hi", "pair": [0, 1]}, - {"sgpr": 2, "kind": "ptr64_lo", "pair": [2, 3]}, - {"sgpr": 3, "kind": "ptr64_hi", "pair": [2, 3]}, - {"sgpr": 4, "kind": "vsharp"}, - {"sgpr": 5, "kind": "vsharp"}, - {"sgpr": 6, "kind": "vsharp"}, - {"sgpr": 7, "kind": "vsharp"}, - ]) - self.assertTrue(meta["descriptor_access"]["table_loads"]) - - # Also verify slist tsharp, ssharp, and literal sampler via analyse_instructions. - insns = self._parse([ - "s_mov_b32 s20, 0x92", - "s_mov_b32 s21, 0", - "s_mov_b32 s22, 0", - "s_mov_b32 s23, 0", - "image_sample v[0:3], v[0:1], [s0, s1, s2, s3, s4, s5, s6, s7], [s20, s21, s22, s23] dmask:0xf dim:SQ_RSRC_IMG_2D", - "image_sample v[4:7], v[0:1], [s0, s1, s2, s3, s4, s5, s6, s7], [s8, s9, s10, s11] dmask:0xf dim:SQ_RSRC_IMG_2D", - "s_endpgm", - ]) - got = M.analyse_instructions([insns], [[]]) - kinds = {r["sgpr"]: r["kind"] for r in got["user_sgpr_reads"]} - for r in range(8): - self.assertEqual(kinds[r], "tsharp") - for r in range(8, 12): - self.assertEqual(kinds[r], "ssharp") - self.assertEqual(got["literal_samplers"], [[0x92, 0, 0, 0]]) - - # A VCCTuple slist mixing a user SGPR with vcc_lo must classify the SGPR without crashing. - insns_vcc = self._parse([ - "global_load_dword v0, v1, [s0, vcc_lo]", - "s_endpgm", - ]) - got_vcc = M.analyse_instructions([insns_vcc], [[]]) - self.assertEqual(got_vcc["user_sgpr_reads"], [{"sgpr": 0, "kind": "ptr64_lo"}]) - - def test_read_dxbc_meta_bounds_container_total_and_part_offsets(self): - good = make_dxbc([sfi0_chunk(M.SFI0_RESOURCE_DESCRIPTOR_HEAP_INDEXING)]) - # Positive control: valid container followed by trailing bytes still parses SFI0. - meta_ok = M.read_dxbc_meta(good + b"\x00" * 32) - self.assertTrue(meta_ok.get("sfi0_resource_heap_directly_indexed")) - - # Declared total larger than buffer length -> truncated container rejected. - trunc = bytearray(good) - struct.pack_into(":{line}:{col}: {kind}\n{src}\n{' ' * (col - 1)}^\n" - - -def messages(*diags): - """The llvm-mc messages section shader_disasm.py appends to a .s file.""" - return "\n; --- llvm-mc messages ---\n; " + "".join(diags).strip().replace("\n", "\n; ") + "\n" - - -def echo(hex_bytes): - """llvm-mc's input as shader_disasm.py writes it: space-separated 0xNN tokens.""" - return " ".join(f"0x{b:02x}" for b in bytes.fromhex(hex_bytes)) - - -class TestFamilyClassification(unittest.TestCase): - def test_known_families(self): - cases = [ - ("s_buffer_load_dword", "smem"), - ("s_load_dwordx4", "smem"), - ("s_mov_b32", "scalar"), - ("s_add_u32", "scalar"), - ("v_mov_b32", "vector"), - ("v_fma_f32", "vector"), - ("ds_read_b32", "lds"), - ("ds_write_b32", "lds"), - ("buffer_load_dword", "buffer"), - ("tbuffer_load_format_x", "buffer"), - ("image_sample", "image"), - ("image_load", "image"), - ("global_load_dword", "global"), - ("global_store_dword", "global"), - ("flat_load_dword", "flat"), - ("flat_store_dword", "flat"), - ("scratch_load_dword", "scratch"), - ("scratch_store_dword", "scratch"), - ("exp", "export"), - ("unknown_instruction", "other"), - ] - for mnemonic, expected_family in cases: - with self.subTest(mnemonic=mnemonic): - self.assertEqual(P.family(mnemonic), expected_family) - - -class TestInstructionClassification(unittest.TestCase): - def test_alu_instructions(self): - alu_cases = [ - "v_mov_b32", "v_add_f32", "v_sub_f32", "v_mul_f32", "v_fma_f32", - "v_cmp_gt_f32", "v_cndmask_b32", "v_cvt_f32_u32", "v_and_b32", - "v_lshlrev_b32", "v_med3_f32", "v_bfi_b32", "v_bfe_u32", - "s_mov_b32", "s_add_u32", "s_sub_u32", "s_and_b64", "s_or_b64", - "s_xor_b64", "s_lshl_b64", "s_cmp_eq_u32", "s_cselect_b32", - ] - for m in alu_cases: - with self.subTest(mnemonic=m): - self.assertEqual(P.classify_instruction(m), "alu") - self.assertTrue(P.is_alu(m)) - self.assertFalse(P.is_memory(m)) - self.assertFalse(P.is_branch(m)) - - def test_memory_instructions(self): - mem_cases = [ - "s_load_dword", "s_load_dwordx4", "s_buffer_load_dword", - "ds_read_b32", "ds_write_b32", "buffer_load_dword", - "buffer_store_dword", "tbuffer_load_format_x", - "tbuffer_store_format_xyzw", "image_sample", "image_sample_lz", - "image_load", "image_store", "global_load_dword", - "global_store_dword", "flat_load_dword", "flat_store_dword", - "scratch_load_dword", "scratch_store_dword", - ] - for m in mem_cases: - with self.subTest(mnemonic=m): - self.assertEqual(P.classify_instruction(m), "memory") - self.assertTrue(P.is_memory(m)) - self.assertFalse(P.is_alu(m)) - self.assertFalse(P.is_branch(m)) - - def test_branch_instructions(self): - branch_cases = [ - "s_branch", "s_cbranch_scc0", "s_cbranch_scc1", - "s_cbranch_vccz", "s_cbranch_vccnz", "s_cbranch_execz", - "s_cbranch_execnz", "s_setpc_b64", "s_swappc_b64", - "s_rfe_b64", "s_call_b64", - ] - for m in branch_cases: - with self.subTest(mnemonic=m): - self.assertEqual(P.classify_instruction(m), "branch") - self.assertTrue(P.is_branch(m)) - self.assertFalse(P.is_alu(m)) - self.assertFalse(P.is_memory(m)) - - def test_export_and_other_instructions(self): - self.assertEqual(P.classify_instruction("exp"), "export") - self.assertEqual(P.classify_instruction("s_nop"), "other") - self.assertEqual(P.classify_instruction("s_endpgm"), "other") - self.assertEqual(P.classify_instruction("s_barrier"), "other") - self.assertEqual(P.classify_instruction("s_waitcnt"), "other") - self.assertEqual(P.classify_instruction("s_waitcnt_vscnt"), "other") - self.assertEqual(P.classify_instruction("s_sendmsg"), "other") - self.assertEqual(P.classify_instruction(""), "other") - self.assertEqual(P.classify_instruction("nonexistent_opcode"), "other") - - -class TestRatiosAndCategoryCounting(unittest.TestCase): - def test_count_categories_from_list(self): - mnemonics = [ - "v_mov_b32", "v_add_f32", "s_load_dword", "s_cbranch_scc0", - "exp", "s_nop", "s_endpgm" - ] - counts = P.count_categories(mnemonics) - self.assertEqual(counts["alu"], 2) - self.assertEqual(counts["memory"], 1) - self.assertEqual(counts["branch"], 1) - self.assertEqual(counts["export"], 1) - self.assertEqual(counts["other"], 2) - self.assertEqual(counts["total"], 7) - - def test_count_categories_from_dict(self): - mnemonics = { - "v_add_f32": 10, - "v_mul_f32": 5, - "buffer_load_dword": 5, - "s_branch": 2, - } - counts = P.count_categories(mnemonics) - self.assertEqual(counts["alu"], 15) - self.assertEqual(counts["memory"], 5) - self.assertEqual(counts["branch"], 2) - self.assertEqual(counts["export"], 0) - self.assertEqual(counts["other"], 0) - self.assertEqual(counts["total"], 22) - - def test_compute_ratios_balanced(self): - counts = {"alu": 50, "memory": 25, "branch": 25, "export": 0, "other": 0, "total": 100} - r = P.compute_ratios(counts) - self.assertEqual(r["alu_ratio"], 0.50) - self.assertEqual(r["memory_ratio"], 0.25) - self.assertEqual(r["branch_ratio"], 0.25) - self.assertEqual(r["alu_to_memory"], 2.0) - - def test_compute_ratios_empty(self): - counts = {"alu": 0, "memory": 0, "branch": 0, "export": 0, "other": 0, "total": 0} - r = P.compute_ratios(counts) - self.assertEqual(r["alu_ratio"], 0.0) - self.assertEqual(r["memory_ratio"], 0.0) - self.assertEqual(r["branch_ratio"], 0.0) - self.assertEqual(r["alu_to_memory"], 0.0) - - def test_compute_ratios_zero_memory(self): - counts = {"alu": 10, "memory": 0, "branch": 2, "export": 0, "other": 0, "total": 12} - r = P.compute_ratios(counts) - self.assertEqual(r["alu_to_memory"], float("inf")) - - -class TestRegisterFootprint(unittest.TestCase): - def test_single_registers(self): - line = "\tv_add_f32 v5, v2, v0" - regs = P.parse_registers(line) - self.assertEqual(regs["vgprs"], {0, 2, 5}) - self.assertEqual(regs["sgprs"], set()) - self.assertEqual(regs["special"], set()) - - def test_register_ranges(self): - line = "\ts_load_dwordx4 s[4:7], s[0:1], 0x0" - regs = P.parse_registers(line) - self.assertEqual(regs["sgprs"], {0, 1, 4, 5, 6, 7}) - self.assertEqual(regs["vgprs"], set()) - - def test_mixed_vgpr_and_sgpr(self): - line = "\timage_sample v[0:3], v[8:9], s[16:23], s[24:27] dmask:0xf" - regs = P.parse_registers(line) - self.assertEqual(regs["vgprs"], {0, 1, 2, 3, 8, 9}) - self.assertEqual(regs["sgprs"], {16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27}) - - def test_special_registers(self): - line = "\tv_cndmask_b32 v0, v1, v2, vcc" - regs = P.parse_registers(line) - self.assertIn("vcc", regs["special"]) - self.assertEqual(regs["vgprs"], {0, 1, 2}) - - line2 = "\ts_mov_b64 exec, s[0:1]" - regs2 = P.parse_registers(line2) - self.assertIn("exec", regs2["special"]) - self.assertEqual(regs2["sgprs"], {0, 1}) - - def test_comments_stripped_for_registers(self): - line = "\tv_mov_b32 v1, 1.0 ; encoding: [0x00,0x00,0x80,0xbf] v255 s99" - regs = P.parse_registers(line) - self.assertEqual(regs["vgprs"], {1}) - self.assertEqual(regs["sgprs"], set()) - - def test_footprint_calculation(self): - shader = ( - "; synthetic pixel shader\n" - "\ts_load_dwordx2 s[0:1], s[2:3], 0x10\n" - "\tv_mov_b32 v0, 1.0\n" - "\tv_add_f32 v31, v0, v0\n" - "\ts_cbranch_scc0 0x10\n" - "\ts_endpgm\n" - ) - fp = P.register_footprint(shader) - self.assertEqual(fp["max_vgpr"], 31) - self.assertEqual(fp["vgpr_count"], 32) - self.assertEqual(fp["unique_vgprs"], 2) - self.assertEqual(fp["vgprs"], [0, 31]) - - self.assertEqual(fp["max_sgpr"], 3) - self.assertEqual(fp["sgpr_count"], 4) - self.assertEqual(fp["unique_sgprs"], 4) - self.assertEqual(fp["sgprs"], [0, 1, 2, 3]) - - def test_footprint_empty(self): - fp = P.register_footprint([]) - self.assertEqual(fp["max_vgpr"], -1) - self.assertEqual(fp["max_sgpr"], -1) - self.assertEqual(fp["vgpr_count"], 0) - self.assertEqual(fp["sgpr_count"], 0) - self.assertEqual(fp["vgprs"], []) - self.assertEqual(fp["sgprs"], []) - - -class TestProfileShader(unittest.TestCase): - def test_profile_shader_synthetic(self): - text = ( - "; ps_sample code 0x0..0x40\n" - "\ts_load_dwordx4 s[0:3], s[4:5], 0x0\n" - "\tv_mov_b32 v0, 1.0\n" - "\tv_add_f32 v1, v0, v0\n" - "\tv_mul_f32 v2, v1, v0\n" - "\ts_cbranch_scc0 0x20\n" - "\texp mrt0 v0, v1, v2, v2 done vm\n" - "\ts_endpgm\n" - ) - prof = P.profile_shader(text) - self.assertEqual(prof["total_instructions"], 7) - cats = prof["categories"] - self.assertEqual(cats["alu"], 3) # v_mov_b32, v_add_f32, v_mul_f32 - self.assertEqual(cats["memory"], 1) # s_load_dwordx4 - self.assertEqual(cats["branch"], 1) # s_cbranch_scc0 - self.assertEqual(cats["export"], 1) # exp - self.assertEqual(cats["other"], 1) # s_endpgm - - ratios = prof["ratios"] - self.assertAlmostEqual(ratios["alu_ratio"], 3 / 7, places=5) - self.assertAlmostEqual(ratios["memory_ratio"], 1 / 7, places=5) - self.assertAlmostEqual(ratios["branch_ratio"], 1 / 7, places=5) - self.assertEqual(ratios["alu_to_memory"], 3.0) - - regs = prof["registers"] - self.assertEqual(regs["max_vgpr"], 2) - self.assertEqual(regs["vgpr_count"], 3) - self.assertEqual(regs["max_sgpr"], 5) - self.assertEqual(regs["sgpr_count"], 6) - - -class TestWarningWords(unittest.TestCase): - def test_header_words_with_or_without_llvm_diagnostics(self): - header = "; cs_test code 0x10..0x20 (header), gfx1013, 2 invalid words\n" - self.assertEqual(P.warning_words(header + "\ts_endpgm\n"), ([], 2)) - diagnostics = messages(diag(1, 1, echo("feffffff"))) - self.assertEqual(P.warning_words(header + diagnostics), (["fe ff ff ff"], 1)) - self.assertEqual(P.warning_words(header.replace("2 invalid", "1 invalid") + diagnostics), - (["fe ff ff ff"], 0)) - - def test_positions_in_echo(self): - self.assertEqual(P.warning_words(messages(diag(1, 1, echo("feffffff")))), (["fe ff ff ff"], 0)) - # Standalone LLVM: line 2 of the input, indented two spaces, so column 3. - self.assertEqual(P.warning_words(messages(diag(2, 3, " " + echo("ffffffd7 000081bf")))), - (["ff ff ff d7"], 0)) - long_src = echo("00" * 2048 + "feffffff") - self.assertEqual(P.warning_words(messages(diag(1, 10241, long_src))), (["fe ff ff ff"], 0)) - - def test_unresolved_positions_and_tokens(self): - src = echo("070080bf feffffff") - self.assertEqual(P.warning_words(messages(diag(1, 21, src))), (["fe ff ff ff"], 0)) - for pos in ("0:21", "1:0", "1:2", "1:20", "1:22", "1:26", "1:36", "1:40", "1:" + "9" * 5000, "x:21", - "1:21:5", None): - with self.subTest(pos=str(pos)[:12]): - head = "" + (f":{pos}" if pos else "") + ": warning: invalid instruction encoding" - self.assertEqual(P.warning_words(messages(f"{head}\n{src}\n")), ([], 1)) - for src in ("0xfe 0xff 0xff", "0xfe 0xff 0xff 0xf", "0xfe 0xff 0xff 0xfff", "0xfe,0xff,0xff,0xff", - "0xfe 0xff 0xff 0xzz", "x0xfe 0xff 0xff 0xff"): - with self.subTest(src=src): - self.assertEqual(P.warning_words(messages(diag(1, 1, src))), ([], 1)) - - def test_missing_or_truncated_echo_stays_in_its_diagnostic(self): - warning = ":1:1: warning: invalid instruction encoding\n" - tail = diag(1, 21, echo("070080bf ffff")) # LLVM's genuine warning for a two-byte tail - self.assertEqual(P.warning_words(messages(warning)), ([], 1)) - self.assertEqual(P.warning_words(messages(warning, diag(1, 1, echo("ffffffd7")))), (["ff ff ff d7"], 1)) - self.assertEqual(P.warning_words(messages(tail, diag(1, 1, echo("ffff0000")))), (["ff ff 00 00"], 1)) - # A missing echo must not borrow bytes mentioned by the next diagnostic. - note = ":1:1: note: " + echo("00112233") - self.assertEqual(P.warning_words(messages(f":1:20: warning: invalid instruction encoding\n{note}\n")), - ([], 1)) - - def test_only_the_messages_section_and_warning_class(self): - src = echo("feffffff") - stray = "\ts_nop 0\n; :1:1: warning: invalid instruction encoding\n; " + src + "\n" - section = messages(diag(1, 1, echo("ffffffd7"))) - self.assertEqual(P.warning_words(stray + section), (["ff ff ff d7"], 0)) - for header in ("; --- llvm-mc messages ---", "; --- llvm-mc messages --- ", "; --- llvm-mc messages"): - with self.subTest(header=header): - text = stray + section.replace("; --- llvm-mc messages ---", header) - self.assertEqual(P.warning_words(text), ([], 0)) - unrelated = messages(diag(1, 1, src, "error: invalid instruction encoding"), - diag(1, 1, src, "note: text mentioning: warning: invalid instruction encoding"), - diag(1, 1, src, "warning: potentially undefined instruction encoding"), - diag(1, 1, src, "warning: invalid instruction encoding, again"), - "; :1:1: warning: invalid instruction encoding\n" + src + "\n") - self.assertEqual(P.warning_words(unrelated), ([], 0)) - self.assertEqual(P.warning_words(""), ([], 0)) - - -class TestCommandLineEndToEnd(unittest.TestCase): - def setUp(self): - self.tmp = tempfile.TemporaryDirectory() - self.disasm_dir = os.path.join(self.tmp.name, "disasm") - os.makedirs(self.disasm_dir, exist_ok=True) - - def tearDown(self): - self.tmp.cleanup() - - def write(self, name, text): - with open(os.path.join(self.disasm_dir, name + ".s"), "w", encoding="utf-8") as f: - f.write(text) - - def run_profile(self, extra=()): - out_json = os.path.join(self.tmp.name, "custom_profile.json") - cmd = [sys.executable, "-I", os.path.join(ROOT, "tools", "shader_profile.py"), self.disasm_dir, "--out", out_json] - res = subprocess.run(cmd + list(extra), capture_output=True, text=True) - self.assertEqual(res.returncode, 0, f"CLI failed: {res.stderr}") - with open(out_json, encoding="utf-8") as f: - return res.stdout, json.load(f, parse_constant=self.fail) - - def test_cli_default_report_is_next_to_disasm_directory(self): - shader_dir = os.path.join(self.tmp.name, "work", "shaders", "dxbc") - disasm_dir = os.path.join(shader_dir, "disasm") - os.makedirs(disasm_dir) - tool = os.path.join(ROOT, "tools", "shader_profile.py") - result = subprocess.run([sys.executable, "-I", tool, disasm_dir], capture_output=True, text=True) - self.assertEqual(result.returncode, 0, result.stderr) - with open(os.path.join(shader_dir, "profile.json"), encoding="utf-8") as report: - self.assertEqual(json.load(report)["shaders"], 0) - - def test_cli_bad_source_or_out_is_one_line(self): - tool = os.path.join(ROOT, "tools", "shader_profile.py") - a_file = os.path.join(self.disasm_dir, "ps_001.s") - with open(a_file, "w", encoding="utf-8") as f: - f.write("\tv_mov_b32 v0, 1.0\n") - missing = os.path.join(self.tmp.name, "missing") - out_in_missing = os.path.join(self.tmp.name, "no_dir", "profile.json") - out_is_dir = os.path.join(self.tmp.name, "out_dir") - os.mkdir(out_is_dir) - for args, message in (([missing], "does not exist"), ([a_file], "is not a folder"), - ([self.disasm_dir, "--out", out_in_missing], "folder for"), - ([self.disasm_dir, "--out", out_is_dir], "cannot write")): - with self.subTest(case=message): - res = subprocess.run([sys.executable, "-I", tool, *args], capture_output=True, text=True) - self.assertEqual(res.returncode, 2) - self.assertIn(message, res.stderr) - self.assertNotIn("Traceback", res.stderr) - self.assertFalse(os.path.exists(os.path.join(self.tmp.name, "profile.json"))) - - def test_cli_alu_without_memory_writes_null(self): - with open(os.path.join(self.disasm_dir, "ps_001.s"), "w", encoding="utf-8") as f: - f.write("\tv_mov_b32 v0, 1.0\n\ts_endpgm\n") - _, data = self.run_profile() - self.assertEqual(data["categories"]["alu"], 1) - self.assertEqual(data["categories"]["memory"], 0) - self.assertIsNone(data["ratios"]["alu_to_memory"]) - - def test_cli_counts_category_occurrences_by_stage(self): - self.write("ps_first", "\tv_mov_b32 v0, 1\n" * 2) - self.write("ps_second", "\tv_mov_b32 v1, 2\n\ts_endpgm\n") - self.write("vs_first", "\ts_load_dword s0, s[2:3], 0\n") - self.write("unclassified", "") - self.write("zz_foo", "\tv_mov_b32 v2, 1\n") - self.write("LIB_helper", "\ts_endpgm\n") - _, data = self.run_profile() - stages = data["categories_by_stage"] - self.assertEqual(list(stages), ["?", "lib", "ps", "vs"]) - self.assertEqual(stages["ps"], {"alu": 3, "memory": 0, "branch": 0, - "export": 0, "other": 1, "total": 4}) - self.assertEqual(stages["vs"]["memory"], 1) - self.assertEqual(stages["?"]["alu"], 1) - self.assertEqual(stages["lib"]["total"], 1) - for key, count in data["categories"].items(): - self.assertEqual(sum(stage[key] for stage in stages.values()), count) - - def test_cli_empty_corpus(self): - stdout, data = self.run_profile() - self.assertEqual(data["shaders"], 0) - self.assertEqual(data["categories_by_stage"], {}) - self.assertEqual(data["ratios"]["alu_to_memory"], 0.0) - self.assertEqual(data["undecoded"], {"warnings": 0, "unresolved": 0, "by_word": []}) - self.assertIn(" undecoded: 0 LLVM warnings, 0 distinct words, 0 unresolved", stdout) - - def test_cli_takes_the_stage_from_the_carve_index(self): - """Most corpus names carry no stage prefix; shader_carve.py's index.json (next to the disasm folder) has - the stage from each container's program header, so it wins over the name. Names it doesn't list keep - the name-prefix fallback.""" - with open(os.path.join(self.tmp.name, "index.json"), "w", encoding="utf-8") as f: - json.dump([{"name": "Foo", "file": "Foo_1.dxbc", "stage": "cs"}, - {"name": "CS_Bar", "file": "CS_Bar.dxbc", "stage": "ms"}], f) - for name in ("Foo_1", "CS_Bar", "vs_unlisted"): - self.write(name, "\tv_mov_b32 v0, 1\n\ts_endpgm\n") - _, data = self.run_profile(["--per-shader"]) - self.assertEqual({row["name"]: row["stage"] for row in data["per_shader"]}, - {"Foo_1": "cs", "CS_Bar": "ms", "vs_unlisted": "vs"}) - self.assertEqual(sorted(data["registers"]), ["cs", "ms", "vs"]) - - def test_cli_counts_only_instructions(self): - with open(os.path.join(self.disasm_dir, "ps_001.s"), "w", encoding="utf-8") as f: - f.write("\t.text\n\t.long 0\n\t; comment with v7\n\t\t\n\tv_mov_b32 v0, 1\n\ts_endpgm\n") - _, data = self.run_profile(["--per-shader"]) - self.assertEqual(data["categories"]["total"], 2) - self.assertEqual({row["m"] for row in data["by_mnemonic"]}, {"v_mov_b32", "s_endpgm"}) - self.assertEqual(data["per_shader"][0]["instructions"], 2) - self.assertEqual(data["per_shader"][0]["vgpr_count"], 1) - - def test_cli_execution_and_json_output(self): - s1 = ( - "; ps_001 code 0x0..0x20\n" - "\tv_mov_b32 v0, 1.0\n" - "\tv_add_f32 v1, v0, v0\n" - "\ts_load_dword s0, s[2:3], 0x0\n" - "\ts_endpgm\n" - ) - s2 = ( - "; vs_002 code 0x0..0x20\n" - "\ts_branch 0x10\n" - "\texp pos0 v0, v1, v2, v3 done vm\n" - "\ts_nop 0\n" - "; :5:1: warning: invalid instruction encoding\n" - "; 0x12 0x34 0x56 0x78\n" - ) - with open(os.path.join(self.disasm_dir, "ps_001.s"), "w", encoding="utf-8") as f: - f.write(s1) - with open(os.path.join(self.disasm_dir, "vs_002.s"), "w", encoding="utf-8") as f: - f.write(s2) - - stdout, data = self.run_profile() - self.assertIn("2 shaders", stdout) - self.assertIn("ALU:", stdout) - self.assertIn("Memory:", stdout) - self.assertIn("Branch:", stdout) - - self.assertEqual(data["shaders"], 2) - self.assertIn("families", data) - self.assertIn("categories", data) - self.assertIn("ratios", data) - self.assertIn("by_mnemonic", data) - # vs_002's warning lines are not in an llvm-mc messages section. - self.assertEqual(data["undecoded"], {"warnings": 0, "unresolved": 0, "by_word": []}) - - cats = data["categories"] - self.assertEqual(cats["alu"], 2) - self.assertEqual(cats["memory"], 1) - self.assertEqual(cats["branch"], 1) - self.assertEqual(cats["export"], 1) - self.assertEqual(cats["other"], 2) - - ratios = data["ratios"] - self.assertGreater(ratios["alu_ratio"], 0.0) - self.assertGreater(ratios["memory_ratio"], 0.0) - self.assertEqual(ratios["alu_to_memory"], 2.0) - - # Register pressure per stage: ps_001 uses v0-v1 and s0-s3, vs_002 uses v0-v3 and no SGPR. - regs = data["registers"] - self.assertEqual(regs["ps"], {"shaders": 1, "vgpr_max": 2, "vgpr_mean": 2.0, "sgpr_max": 4, - "sgpr_mean": 4.0, "vgpr_hist": {"32": 1}}) - self.assertEqual(regs["vs"]["vgpr_max"], 4) - self.assertEqual(regs["vs"]["sgpr_max"], 0) - self.assertIn("ps registers: VGPR max 2", stdout) - self.assertNotIn("per_shader", data) - - _, data = self.run_profile(["--per-shader"]) - self.assertEqual(data["per_shader"], [ - {"name": "ps_001", "stage": "ps", "instructions": 4, "vgpr_count": 2, "sgpr_count": 4}, - {"name": "vs_002", "stage": "vs", "instructions": 3, "vgpr_count": 4, "sgpr_count": 0}, - ]) - - def test_cli_ignores_directories_with_shader_suffix(self): - self.write("cs_main", "\ts_endpgm\n") - os.mkdir(os.path.join(self.disasm_dir, "cs_cache.s")) - - _, data = self.run_profile(["--per-shader"]) - - self.assertEqual(data["shaders"], 1) - self.assertEqual([shader["name"] for shader in data["per_shader"]], ["cs_main"]) - - def test_profile_rankings_do_not_depend_on_directory_order(self) -> None: - self.write("ps_vector", "\n".join(( - "\tv_add_f32 v0, v0, v1", - "\tv_add_f32 v0, v0, v1", - "\tv_and_b32 v0, v0, v1", - "\tv_max_f32 v0, v0, v1", - "\tv_min_f32 v0, v0, v1", - "\tv_mov_b32 v0, v1", - "\tv_or_b32 v0, v0, v1", - "\tv_xor_b32 v0, v0, v1", - "\ts_endpgm", - ))) - self.write("ps_scalar", "\n".join(( - "\ts_add_u32 s0, s0, s1", - "\ts_and_b32 s0, s0, s1", - "\ts_mov_b32 s0, s1", - "\ts_nop 0", - "\ts_or_b32 s0, s0, s1", - "\ts_xor_b32 s0, s0, s1", - "\ts_endpgm", - ))) - with os.scandir(self.disasm_dir) as scan: - entries = sorted(scan, key=lambda entry: entry.name) - report = os.path.join(self.tmp.name, "profile.json") - args = ["shader_profile.py", self.disasm_dir, "--out", report] - - def profile(order: list[os.DirEntry[str]]) -> tuple[str, bytes]: - stdout = io.StringIO() - with (patch.object(P.os, "scandir", return_value=nullcontext(order)), - patch.object(sys, "argv", args), redirect_stdout(stdout)): - self.assertIsNone(P.main()) - with open(report, "rb") as output: - return stdout.getvalue(), output.read() - - forward, data = profile(entries) - reverse, reversed_data = profile(list(reversed(entries))) - self.assertEqual(data, reversed_data) - self.assertEqual(forward, reverse) - rankings = json.loads(data)["by_mnemonic"] - self.assertEqual(rankings[0], {"m": "s_endpgm", "shaders": 2, "count": 2}) - self.assertEqual([row["m"] for row in rankings[1:]], sorted(row["m"] for row in rankings[1:])) - most_widespread = next(line for line in forward.splitlines() if "most widespread:" in line) - self.assertEqual(most_widespread.removeprefix(" most widespread: "), - ", ".join(f"{row['m']} ({row['shaders']})" for row in rankings[:12])) - - def test_cli_warning_words_from_llvm_messages(self): - a = echo("070080bf feffffff ffffffd7 050080bf feffffff 000081bf") - b = echo("090080bf ffffffd7 000081bf") - nop9, endpgm = "\ts_nop 9 ; encoding: [0x09,0x00,0x80,0xbf]\n", "\ts_endpgm ; encoding: [0x00,0x00,0x81,0xbf]\n" - self.write("cs_probe", "; cs_probe code 0x128..0x140 (header), gfx1013, 3 invalid words\n" - "\ts_nop 7 ; encoding: [0x07,0x00,0x80,0xbf]\n\ts_nop 5 ; encoding: [0x05,0x00,0x80,0xbf]\n" - + endpgm + messages(diag(1, 21, a), diag(1, 41, a), diag(1, 81, a))) - self.write("ps_probe", "; ps_probe code 0x128..0x134 (header), gfx1013, 1 invalid words\n" + nop9 + endpgm - + messages(diag(1, 21, b))) - self.write("vs_clean", "; vs_clean code 0x128..0x130 (header), gfx1013, 0 invalid words\n" + nop9 + endpgm) - rows = [{"word": "ff ff ff d7", "shaders": 2, "count": 2}, {"word": "fe ff ff ff", "shaders": 1, "count": 2}] - - stdout, data = self.run_profile() - self.assertEqual(data["undecoded"], {"warnings": 4, "unresolved": 0, "by_word": rows}) - self.assertEqual({r["m"]: (r["shaders"], r["count"]) for r in data["by_mnemonic"]}, - {"s_nop": (3, 4), "s_endpgm": (3, 3)}) - self.assertIn("\n undecoded: 4 LLVM warnings, 2 distinct words, 0 unresolved (words only in the JSON report)\n", - stdout) - per_stdout, per_data = self.run_profile(["--per-shader"]) - self.assertEqual(per_data["undecoded"], data["undecoded"]) - self.assertEqual([e["name"] for e in per_data["per_shader"]], ["cs_probe", "ps_probe", "vs_clean"]) - for out in (stdout, per_stdout): - for private in ("ff ff", "fe ff", "cs_probe", "ps_probe", "vs_clean"): - self.assertNotIn(private, out) - - self.write("gs_tail", "; gs_tail code 0x128..0x132 (header), gfx1013, 1 invalid words\n" - "\ts_nop 7 ; encoding: [0x07,0x00,0x80,0xbf]\n" + messages(diag(1, 21, echo("070080bf ffff")))) - stdout, data = self.run_profile() - self.assertEqual(data["undecoded"], {"warnings": 5, "unresolved": 1, "by_word": rows}) - self.assertIn(" undecoded: 5 LLVM warnings, 2 distinct words, 1 unresolved", stdout) - - def test_cli_ranks_words_by_count_then_shaders_then_word(self): - self.write("cs_1", "\ts_nop 0\n" + messages(diag(1, 1, echo("01" * 4)), diag(2, 1, echo("aa" * 4)), - diag(3, 1, echo("aa" * 4)))) - self.write("ps_2", "\ts_nop 0\n" + messages(diag(1, 1, echo("bb" * 4)), diag(2, 1, echo("00" * 4)))) - self.write("vs_3", "\ts_nop 0\n" + messages(diag(1, 1, echo("bb" * 4)))) - expected = {"warnings": 6, "unresolved": 0, "by_word": [ - {"word": "bb bb bb bb", "shaders": 2, "count": 2}, - {"word": "aa aa aa aa", "shaders": 1, "count": 2}, - {"word": "00 00 00 00", "shaders": 1, "count": 1}, - {"word": "01 01 01 01", "shaders": 1, "count": 1}]} - for extra in ([], ["--per-shader"]): - with self.subTest(extra=extra): - self.assertEqual(self.run_profile(extra)[1]["undecoded"], expected) - - def test_register_summary_histogram(self): - summary = P.register_summary({"cs": [(10, 4), (40, 8), (100, 20), (300, 2)]}) - self.assertEqual(summary["cs"]["vgpr_hist"], {"32": 1, "64": 1, "128": 1, ">256": 1}) - self.assertEqual(summary["cs"]["vgpr_max"], 300) - self.assertEqual(summary["cs"]["sgpr_mean"], 8.5) - self.assertEqual(P.register_summary({}), {}) - - def test_same_output_path_identity(self): - a = os.path.join(self.disasm_dir, "a.json") - self.assertTrue(P.same_output_path(a, a)) - b = os.path.join(self.disasm_dir, "b.json") - self.assertFalse(P.same_output_path(a, b)) - - def assert_carve_index_output_refused(self, output): - tool = os.path.join(ROOT, "tools", "shader_profile.py") - res = subprocess.run( - [sys.executable, "-I", tool, self.disasm_dir, "--out", output], - capture_output=True, - text=True, - ) - self.assertEqual(res.returncode, 2, res.stderr) - self.assertIn("ERROR: output would overwrite the shader carve index", res.stderr) - - def test_cli_reserves_the_carve_index_path(self): - self.write("cs_main", "\ts_endpgm\n") - index = os.path.join(self.tmp.name, "index.json") - self.assert_carve_index_output_refused(index) - self.assertFalse(os.path.exists(index)) - original = '[{"file": "cs_main.dxbc", "stage": "cs"}]' - with open(index, "w", encoding="utf-8") as f: - f.write(original) - self.assert_carve_index_output_refused(index) - with open(index, encoding="utf-8") as f: - self.assertEqual(f.read(), original) - - def test_cli_refuses_a_hard_link_to_the_carve_index(self): - self.write("cs_main", "\ts_endpgm\n") - index = os.path.join(self.tmp.name, "index.json") - original = '[{"file": "cs_main.dxbc", "stage": "cs"}]' - with open(index, "w", encoding="utf-8") as f: - f.write(original) - alias = os.path.join(self.tmp.name, "alias.json") - try: - os.link(index, alias) - except OSError as error: - self.skipTest(f"hard links are unavailable: {error}") - self.assert_carve_index_output_refused(alias) - with open(index, encoding="utf-8") as f: - self.assertEqual(f.read(), original) - - def test_cli_refuses_output_overwriting_input_shader(self): - tool = os.path.join(ROOT, "tools", "shader_profile.py") - shader_file = os.path.join(self.disasm_dir, "ps_001.s") - original_content = "\tv_mov_b32 v0, 1.0\n\ts_endpgm\n" - with open(shader_file, "w", encoding="utf-8") as f: - f.write(original_content) - - res = subprocess.run( - [sys.executable, "-I", tool, self.disasm_dir, "--out", shader_file], - capture_output=True, - text=True, - ) - self.assertEqual(res.returncode, 2) - self.assertIn("ERROR: output would overwrite input shader", res.stderr) - with open(shader_file, "r", encoding="utf-8") as f: - self.assertEqual(f.read(), original_content) - - def test_unreadable_listing_reports_its_path_and_preserves_report(self): - from io import StringIO - from unittest.mock import patch - - self.write("cs_main", "\ts_endpgm\n") - listing = os.path.join(self.disasm_dir, "cs_main.s") - report = os.path.join(self.tmp.name, "profile.json") - original = b'{"previous": true}\n' - with open(report, "wb") as f: - f.write(original) - - def open_listing(path, *args, **kwargs): - if path == listing: - raise PermissionError(13, "Cannot read listing", listing) - return open(path, *args, **kwargs) - - stderr = StringIO() - with (patch.object(P, "open", open_listing, create=True), - patch.object(sys, "argv", ["shader_profile.py", self.disasm_dir, "--out", report]), - patch.object(sys, "stderr", stderr)): - self.assertEqual(P.main(), 2) - - self.assertEqual(stderr.getvalue().splitlines(), [f"ERROR: cannot read {listing}: Cannot read listing"]) - with open(report, "rb") as f: - self.assertEqual(f.read(), original) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/test_shader_stage_manifest.py b/tests/test_shader_stage_manifest.py deleted file mode 100644 index 283eb0227..000000000 --- a/tests/test_shader_stage_manifest.py +++ /dev/null @@ -1,263 +0,0 @@ -"""Unit and caller integration tests for tools/shader_stage_manifest.py. - - py -3.13 -I tests/test_shader_stage_manifest.py -v - -Zero game data: all tests use synthetic temporary manifests. -""" -import json -import os -import subprocess -import sys -import tempfile -import unittest -from unittest.mock import patch - -ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) -sys.path.insert(0, ROOT) -sys.path.insert(0, os.path.join(ROOT, "tools")) - -import make_game # noqa: E402 -from shader_stage_manifest import shader_stems # noqa: E402 - -FSSM_UNPACK = os.path.join(ROOT, "tools", "fssm_unpack.py") -SHADER_DISASM = os.path.join(ROOT, "tools", "shader_disasm.py") - - -class ShaderStemsTests(unittest.TestCase): - def setUp(self): - self.tmp = tempfile.TemporaryDirectory() - self.dir = self.tmp.name - - def tearDown(self): - self.tmp.cleanup() - - def write_json(self, name: str, data) -> str: - path = os.path.join(self.dir, name) - with open(path, "w", encoding="utf-8") as f: - json.dump(data, f) - return path - - def write_bytes(self, name: str, raw: bytes) -> str: - path = os.path.join(self.dir, name) - with open(path, "wb") as f: - f.write(raw) - return path - - def test_valid_carve_index_with_suffix_and_duplicates(self): - path = self.write_json("index.json", [ - {"file": "ps_water.dxbc"}, - {"file": "vs-main_01.dxbc"}, - {"file": "shader.v1.dxbc"}, - {"file": "ps_water.dxbc"}, - ]) - self.assertEqual( - shader_stems(path, "file", ".dxbc"), - {"ps_water", "vs-main_01", "shader.v1"}, - ) - - def test_valid_unpack_index_without_suffix(self): - path = self.write_json("fssm_index.json", [ - {"name": "cs_bloom_0"}, - {"name": "gs-pass.v2"}, - {"name": "cs_bloom_0"}, - ]) - self.assertEqual( - shader_stems(path, "name"), - {"cs_bloom_0", "gs-pass.v2"}, - ) - - def test_empty_list_returns_empty_set(self): - path = self.write_json("empty.json", []) - self.assertEqual(shader_stems(path, "file", ".dxbc"), set()) - self.assertEqual(shader_stems(path, "name"), set()) - - def test_rejects_traversal_stems_after_suffix_stripping(self): - for bad in ("..dxbc", "...dxbc", ".dxbc"): - with self.subTest(value=bad): - path = self.write_json("bad_suffix.json", [{"file": bad}]) - with self.assertRaises(ValueError) as ctx: - shader_stems(path, "file", ".dxbc") - self.assertIn(path, str(ctx.exception)) - - def test_rejects_bare_dot_stems_without_suffix(self): - for bad in (".", ".."): - with self.subTest(value=bad): - path = self.write_json("bad_dots.json", [{"name": bad}]) - with self.assertRaises(ValueError) as ctx: - shader_stems(path, "name") - self.assertIn(path, str(ctx.exception)) - - def test_rejects_separators_drive_prefixes_and_nul_bytes(self): - bad_values = [ - "../a.dxbc", - "sub/a.dxbc", - "sub\\a.dxbc", - "C:a.dxbc", - "C:\\a.dxbc", - "a\x00b.dxbc", - "a\nb.dxbc", - ] - for bad in bad_values: - with self.subTest(value=bad): - path = self.write_json("bad_path.json", [{"file": bad}]) - with self.assertRaises(ValueError) as ctx: - shader_stems(path, "file", ".dxbc") - self.assertIn(path, str(ctx.exception)) - - def test_rejects_wrong_suffix(self): - path = self.write_json("wrong_suffix.json", [{"file": "ps_water.fssm"}]) - with self.assertRaises(ValueError) as ctx: - shader_stems(path, "file", ".dxbc") - self.assertIn(path, str(ctx.exception)) - - def test_rejects_missing_or_invalid_field_values(self): - cases = [ - [{"other": "ps_water.dxbc"}], - [{"file": None}], - [{"file": 123}], - [{"file": ""}], - ["ps_water.dxbc"], - [123], - [None], - ] - for idx, rows in enumerate(cases): - with self.subTest(case=idx): - path = self.write_json(f"bad_row_{idx}.json", rows) - with self.assertRaises(ValueError) as ctx: - shader_stems(path, "file", ".dxbc") - self.assertIn(path, str(ctx.exception)) - - def test_rejects_non_list_root(self): - for idx, root in enumerate(({}, "x", 42, None, True)): - with self.subTest(root=root): - path = self.write_json(f"bad_root_{idx}.json", root) - with self.assertRaises(ValueError) as ctx: - shader_stems(path, "file", ".dxbc") - self.assertIn(path, str(ctx.exception)) - - def test_malformed_json_raises_value_error_with_path(self): - for idx, raw in enumerate((b"", b"{bad", b"[{\"file\": \"a.dxbc\"")): - with self.subTest(case=idx): - path = self.write_bytes(f"malformed_{idx}.json", raw) - with self.assertRaises(ValueError) as ctx: - shader_stems(path, "file", ".dxbc") - self.assertIn(path, str(ctx.exception)) - - def test_invalid_utf8_raises_value_error_with_path(self): - path = self.write_bytes("bad_utf8.json", b"\xff\xfe\xfd") - with self.assertRaises(ValueError) as ctx: - shader_stems(path, "file", ".dxbc") - self.assertIn(path, str(ctx.exception)) - - def test_index_saved_with_a_utf8_bom_is_read(self): - # Windows PowerShell 5.1 (Set-Content, Out-File) and old Notepad write JSON with a UTF-8 BOM. - carve = self.write_bytes( - "index.json", - b"\xef\xbb\xbf" + json.dumps([{"file": "ps_water.dxbc"}]).encode("utf-8"), - ) - unpack = self.write_bytes( - "fssm_index.json", - b"\xef\xbb\xbf" + json.dumps([{"name": "cs_bloom_0"}]).encode("utf-8"), - ) - self.assertEqual(shader_stems(carve, "file", ".dxbc"), {"ps_water"}) - self.assertEqual(shader_stems(unpack, "name"), {"cs_bloom_0"}) - - -class CallerIntegrationTests(unittest.TestCase): - def setUp(self): - self.tmp = tempfile.TemporaryDirectory() - self.dir = self.tmp.name - - def tearDown(self): - self.tmp.cleanup() - - def test_make_game_unpacked_shader_stems_rejects_traversal_and_bad_json(self): - dxbc = os.path.join(self.dir, "dxbc") - os.makedirs(dxbc) - with open(os.path.join(dxbc, "fssm_index.json"), "w", encoding="utf-8") as f: - json.dump([{"name": "."}], f) - with open(os.path.join(dxbc, "index.json"), "w", encoding="utf-8") as f: - json.dump([{"file": "..dxbc"}], f) - self.assertIsNone(make_game.unpacked_shader_stems(dxbc)) - - with open(os.path.join(dxbc, "index.json"), "w", encoding="utf-8") as f: - json.dump([{"file": "...dxbc"}], f) - with open(os.path.join(dxbc, "fssm_index.json"), "w", encoding="utf-8") as f: - json.dump([{"name": ".."}], f) - self.assertIsNone(make_game.unpacked_shader_stems(dxbc)) - - with open(os.path.join(dxbc, "index.json"), "w", encoding="utf-8") as f: - f.write("{truncated") - self.assertIsNone(make_game.unpacked_shader_stems(dxbc)) - - def test_fssm_unpack_carve_index_rejects_traversal_and_malformed_json(self): - src = os.path.join(self.dir, "carved") - os.makedirs(src) - for name, content, expected_msg in ( - ("dot.json", json.dumps([{"file": "..dxbc"}]), "expected a shader basename"), - ("dotdot.json", json.dumps([{"file": "...dxbc"}]), "expected a shader basename"), - ("bad.json", "{not json", "invalid JSON"), - ): - with self.subTest(case=name): - idx = os.path.join(self.dir, name) - with open(idx, "w", encoding="utf-8") as f: - f.write(content) - r = subprocess.run( - [sys.executable, "-I", FSSM_UNPACK, src, "--carve-index", idx], - capture_output=True, - text=True, - ) - self.assertNotEqual(r.returncode, 0) - self.assertIn(idx, r.stderr) - self.assertIn(expected_msg, r.stderr) - self.assertNotIn("Traceback", r.stderr) - - def test_make_game_treats_decoder_recursion_limit_as_an_unusable_index(self): - with open(os.path.join(self.dir, "index.json"), "w", encoding="utf-8", newline="\n") as f: - f.write("[]") - # Decoders can use different stack limits across Python versions. - with patch("shader_stage_manifest.json.load", side_effect=RecursionError("decoder depth limit")): - self.assertIsNone(make_game.unpacked_shader_stems(self.dir)) - - def test_shader_commands_name_the_index_when_an_integer_exceeds_the_decoder_limit(self): - src = os.path.join(self.dir, "empty") - os.makedirs(src) - index = os.path.join(self.dir, "integer.json") - with open(index, "w", encoding="utf-8", newline="\n") as f: - f.write('[{"ignored":' + "1" * 641 + "}]") - for script, flag in ((FSSM_UNPACK, "--carve-index"), (SHADER_DISASM, "--unpack-index")): - with self.subTest(flag=flag): - result = subprocess.run( - [sys.executable, "-I", "-X", "int_max_str_digits=640", script, src, flag, index], - capture_output=True, text=True, timeout=15, - ) - self.assertNotEqual(result.returncode, 0) - self.assertIn(index, result.stderr) - self.assertIn("invalid JSON", result.stderr) - self.assertNotIn("Traceback", result.stderr) - - def test_shader_disasm_unpack_index_rejects_traversal_and_malformed_json(self): - fssm_dir = os.path.join(self.dir, "fssm") - os.makedirs(fssm_dir) - for name, content, expected_msg in ( - ("dot.json", json.dumps([{"name": "."}]), "expected a shader basename"), - ("dotdot.json", json.dumps([{"name": ".."}]), "expected a shader basename"), - ("bad.json", "[{\"name\":", "invalid JSON"), - ): - with self.subTest(case=name): - idx = os.path.join(self.dir, name) - with open(idx, "w", encoding="utf-8") as f: - f.write(content) - r = subprocess.run( - [sys.executable, "-I", SHADER_DISASM, fssm_dir, "--unpack-index", idx], - capture_output=True, - text=True, - ) - self.assertNotEqual(r.returncode, 0) - self.assertIn(idx, r.stderr) - self.assertIn(expected_msg, r.stderr) - self.assertNotIn("Traceback", r.stderr) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/test_shader_stage_resume.py b/tests/test_shader_stage_resume.py deleted file mode 100644 index 1b5cc2870..000000000 --- a/tests/test_shader_stage_resume.py +++ /dev/null @@ -1,578 +0,0 @@ -"""Shader stage of make_game.py: resuming a stopped build, Windows-safe carve names, an empty unpack (#126). - -Standard library only; no game data: the tools are mocked or fed hand-made inputs. -""" -import ast -import io -import json -import os -import shutil -import subprocess -import sys -import tempfile -import unittest -from unittest import mock - -ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) -sys.path.insert(0, ROOT) -sys.path.insert(0, os.path.join(ROOT, "tools")) -import make_game # noqa: E402 -import shader_carve # noqa: E402 - -UNPACK = os.path.join(ROOT, "tools", "fssm_unpack.py") - - -class CarveFileNameTest(unittest.TestCase): - def names(self, *shader_names): - seen, used = {}, set() - return [shader_carve.file_name(n, seen, used) for n in shader_names] - - def test_repeated_name_gets_a_suffix(self): - self.assertEqual(self.names("ps_a", "ps_a", "ps_a"), ["ps_a.dxbc", "ps_a~1.dxbc", "ps_a~2.dxbc"]) - - def test_names_differing_only_in_case_do_not_share_a_file(self): - out = self.names("PS_Water", "ps_water") - self.assertEqual(len({n.lower() for n in out}), 2, out) - - def test_names_that_sanitize_to_the_same_file_do_not_share_it(self): - out = self.names("a:b", "a_b", "a?b") - self.assertEqual(len({n.lower() for n in out}), 3, out) - - def test_suffix_never_lands_on_a_real_name(self): - out = self.names("x~1", "x", "x") - self.assertEqual(len({n.lower() for n in out}), 3, out) - - def test_windows_device_names_are_prefixed(self): - for dev in ("CON", "nul", "Aux", "PRN", "COM1", "lpt9", "con.vs"): - name = self.names(dev)[0] - self.assertNotIn(name.split(".")[0].upper(), shader_carve.RESERVED, name) - self.assertEqual(self.names("CONSOLE")[0], "CONSOLE.dxbc") - - -class EmptyUnpackTest(unittest.TestCase): - def test_nothing_unpacked_fails_clearly_and_writes_no_index(self): - with tempfile.TemporaryDirectory() as d: - with open(os.path.join(d, "junk.dxbc"), "wb") as f: - f.write(b"DXBC" + bytes(60)) # no parts: nothing to unpack - r = subprocess.run([sys.executable, "-I", UNPACK, d], capture_output=True, text=True, errors="replace") - self.assertEqual(r.returncode, 1, r.stdout + r.stderr) - self.assertIn("ERROR", r.stderr) - self.assertNotIn("Traceback", r.stderr) - self.assertFalse(os.path.exists(os.path.join(d, "fssm_index.json"))) - - def test_empty_folder_fails_clearly(self): - with tempfile.TemporaryDirectory() as d: - r = subprocess.run([sys.executable, "-I", UNPACK, d], capture_output=True, text=True, errors="replace") - self.assertEqual(r.returncode, 1, r.stdout + r.stderr) - self.assertNotIn("Traceback", r.stderr) - - -class ShaderStageResumeTest(unittest.TestCase): - """Which steps shaders() runs for a given work folder. The tools are mocked; each mock writes what the real - tool writes last, so the next run sees the same files a real one would.""" - - def setUp(self): - self.tmp = tempfile.TemporaryDirectory() - self.work = self.tmp.name - self.dxbc = os.path.join(self.work, "shaders", "dxbc") - self.spirv = os.path.join(self.work, "shaders", "spirv") - self.ran = [] - self.real_llvm_mc_signature = make_game.llvm_mc_signature - version_probe = mock.patch.object(make_game, "llvm_mc_signature", return_value="test llvm-mc 21") - self.llvm_mc_signature = version_probe.start() - self.addCleanup(version_probe.stop) - - def tearDown(self): - self.tmp.cleanup() - - def touch(self, *parts): - p = os.path.join(*parts) - os.makedirs(os.path.dirname(p), exist_ok=True) - with open(p, "w", encoding="utf-8") as f: - if p == os.path.join(self.dxbc, "index.json"): - json.dump([{"file": "s0.dxbc"}], f) - elif p == os.path.join(self.dxbc, "fssm_index.json"): - json.dump([{"name": "s0"}], f) - elif p.endswith(".s"): - f.write("synthetic listing\n") - - def fake_py(self, tool, *args): - self.ran.append(tool) - if tool == "shader_carve.py": - self.touch(self.dxbc, "index.json") - elif tool == "fssm_unpack.py": - self.assertEqual(args[-2:], ("--carve-index", os.path.join(self.dxbc, "index.json"))) - self.touch(self.dxbc, "fssm_index.json") - elif tool == "shader_disasm.py": - self.assertEqual(args[1:3], ("--unpack-index", os.path.join(self.dxbc, "fssm_index.json"))) - self.touch(self.dxbc, "disasm", "s0.s") - - def fake_translate(self, disasm, spirv, jobs, emulate=False, fallbacks=()): - self.ran.append("translate (emulated)" if emulate else "translate") - self.touch(spirv, "index.json") - - def run_stage(self, emulate=None, jobs=2): - self.ran = [] - kw = {} if emulate is None else {"emulate": emulate} - with mock.patch.object(make_game, "py", self.fake_py), \ - mock.patch.object(make_game, "need", lambda *a: None), \ - mock.patch.object(make_game, "translate", self.fake_translate), \ - mock.patch.object(make_game, "log", lambda *a: None): - make_game.shaders(os.path.join(self.work, "game"), self.work, jobs, **kw) - return self.ran - - def test_fresh_folder_runs_every_step_then_nothing(self): - self.assertEqual(self.run_stage(), ["shader_carve.py", "fssm_unpack.py", "shader_disasm.py", "translate"]) - self.assertEqual(self.run_stage(), []) - - def test_llvm_version_change_at_the_same_path_refreshes_only_the_dependent_steps(self): - wrapper = os.path.join(self.work, "fake llvm-mc.py") - with open(wrapper, "w", encoding="utf-8") as f: - f.write("import os, sys\n" - "assert sys.argv[1:] == ['--version']\n" - "print('LLVM version ' + os.environ['TEST_LLVM_VERSION'])\n") - command = f'"{sys.executable}" "{wrapper}"' - with mock.patch.object(make_game, "llvm_mc_signature", self.real_llvm_mc_signature): - with mock.patch.dict(os.environ, {"LLVM_MC": command, "TEST_LLVM_VERSION": "23.1.5"}): - self.run_stage() - self.assertEqual(self.run_stage(), []) - self.touch(self.dxbc, "disasm", "old.s") - self.touch(self.dxbc, "disasm", "notes.txt") - self.touch(self.spirv, make_game.SHARD_PLAN) - with mock.patch.dict(os.environ, {"LLVM_MC": command, "TEST_LLVM_VERSION": "21.1.0"}): - self.assertEqual(self.run_stage(), ["shader_disasm.py", "translate"]) - self.assertFalse(os.path.exists(os.path.join(self.dxbc, "disasm", "old.s"))) - self.assertTrue(os.path.isfile(os.path.join(self.dxbc, "disasm", "notes.txt"))) - self.assertFalse(os.path.exists(os.path.join(self.spirv, make_game.SHARD_PLAN))) - self.assertEqual(self.run_stage(), []) - - def test_llvm_change_leaves_no_completion_markers_if_disassembly_stops(self): - self.run_stage() - self.touch(self.spirv, make_game.SHARD_PLAN) - self.llvm_mc_signature.return_value = "test llvm-mc 23" - with mock.patch.object(make_game, "py", side_effect=KeyboardInterrupt): - with self.assertRaises(KeyboardInterrupt): - make_game.shaders(os.path.join(self.work, "game"), self.work, 2) - self.assertFalse(os.path.exists(os.path.join(self.dxbc, "disasm.done"))) - self.assertFalse(os.path.exists(os.path.join(self.spirv, "index.json"))) - self.assertFalse(os.path.exists(os.path.join(self.spirv, make_game.SHARD_PLAN))) - self.assertEqual(self.run_stage(), ["shader_disasm.py", "translate"]) - self.assertEqual(self.run_stage(), []) - - def test_version_probe_fails_with_a_clear_error_for_a_failed_command(self): - failed = subprocess.CompletedProcess([], 1, stdout="", stderr="distribution not found") - with mock.patch.object(make_game.subprocess, "run", return_value=failed), \ - mock.patch.object(make_game, "mc_command", return_value=["wsl", "-e", "llvm-mc"]), \ - mock.patch("sys.stderr", new_callable=io.StringIO) as stderr: - with self.assertRaises(SystemExit) as exc: - self.real_llvm_mc_signature() - self.assertEqual(exc.exception.code, 1) - self.assertIn("Check LLVM_MC: distribution not found", stderr.getvalue()) - - def test_unpack_stopped_after_creating_fssm_folder_runs_again(self): - self.touch(self.dxbc, "index.json") - os.makedirs(os.path.join(self.dxbc, "fssm")) # what a stopped fssm_unpack.py leaves - self.assertEqual(self.run_stage(), ["fssm_unpack.py", "shader_disasm.py", "translate"]) - - def test_disasm_stopped_after_many_files_runs_again(self): - self.touch(self.dxbc, "index.json") - self.touch(self.dxbc, "fssm_index.json") - for i in range(1200): # past the old 1000-file threshold - self.touch(self.dxbc, "disasm", f"s{i}.s") - self.assertEqual(self.run_stage(), ["shader_disasm.py", "translate"]) - - def test_disassembly_resume_keeps_completed_listings_for_the_same_llvm(self): - self.touch(self.dxbc, "index.json") - self.touch(self.dxbc, "fssm_index.json") - listing = os.path.join(self.dxbc, "disasm", "s0.s") - - def stop(tool, *args): - self.assertEqual(tool, "shader_disasm.py") - self.assertNotIn("--skip-existing", args) - self.touch(listing) - raise KeyboardInterrupt - - for change_llvm in (False, True): - with self.subTest(change_llvm=change_llvm): - if change_llvm: - os.remove(os.path.join(self.dxbc, "disasm.done")) - with mock.patch.object(self, "fake_py", side_effect=stop): - with self.assertRaises(KeyboardInterrupt): - self.run_stage() - if change_llvm: - self.llvm_mc_signature.return_value = "different llvm-mc" - disassemble = self.fake_py - - def check_reuse(tool, *args): - self.assertEqual("--skip-existing" in args, not change_llvm) - self.assertEqual(os.path.isfile(listing), not change_llvm) - disassemble(tool, *args) - - with mock.patch.object(self, "fake_py", side_effect=check_reuse): - self.assertEqual(self.run_stage(), ["shader_disasm.py", "translate"]) - self.assertTrue(os.path.isfile(os.path.join(self.dxbc, "disasm.done"))) - self.assertFalse(os.path.exists(os.path.join(self.dxbc, "disasm.started"))) - - def test_finished_disassembly_repairs_missing_recorded_listing_before_translation(self): - self.touch(self.dxbc, "index.json") - self.touch(self.dxbc, "fssm_index.json") - with open(os.path.join(self.dxbc, "index.json"), "w", encoding="utf-8", newline="\n") as f: - json.dump([{"file": name + ".dxbc"} for name in ("s0", "s1", "unsupported")], f) - with open(os.path.join(self.dxbc, "fssm_index.json"), "w", encoding="utf-8", newline="\n") as f: - json.dump([{"name": name} for name in ("s0", "s1", "unsupported")], f) - - original = self.fake_py - - def disassemble(tool, *args): - original(tool, *args) - self.touch(self.dxbc, "disasm", "s1.s") - - with mock.patch.object(self, "fake_py", side_effect=disassemble): - self.assertEqual(self.run_stage(), ["shader_disasm.py", "translate"]) - self.assertEqual(self.run_stage(), []) - os.remove(os.path.join(self.dxbc, "disasm", "s1.s")) - self.assertFalse(make_game.shader_outputs_reusable(self.work, False, False)) - - with mock.patch.object(make_game, "fail", side_effect=SystemExit(1)) as fail: - with self.assertRaises(SystemExit): - self.run_stage() - fail.assert_called_once_with("Shader disassembly did not restore all expected listings") - self.assertFalse(os.path.isfile(os.path.join(self.spirv, "index.json"))) - self.assertFalse(os.path.isfile(os.path.join(self.dxbc, "disasm.done"))) - - def repair(tool, *args): - self.assertIn("--skip-existing", args) - self.assertTrue(os.path.isfile(os.path.join(self.dxbc, "disasm", "s0.s"))) - disassemble(tool, *args) - - with mock.patch.object(self, "fake_py", side_effect=repair): - self.assertEqual(self.run_stage(), ["shader_disasm.py", "translate"]) - self.assertTrue(make_game.shader_outputs_reusable(self.work, False, False)) - - def test_finished_disassembly_repairs_a_zero_byte_listing(self): - self.assertEqual(self.run_stage(), ["shader_carve.py", "fssm_unpack.py", "shader_disasm.py", "translate"]) - listing = os.path.join(self.dxbc, "disasm", "s0.s") - self.assertGreater(os.path.getsize(listing), 0) - open(listing, "wb").close() - - self.assertFalse(make_game.shader_outputs_reusable(self.work, False, False)) - self.assertEqual(self.run_stage(), ["shader_disasm.py", "translate"]) - self.assertGreater(os.path.getsize(listing), 0) - self.assertEqual(self.run_stage(), []) - - def test_deleting_every_listing_and_the_translation_disassembles_again(self): - # README.md, "Low disk space": deleting the .s files with spirv/index.json must not leave the stage - # looking finished with zero shaders. - self.assertEqual(self.run_stage(), ["shader_carve.py", "fssm_unpack.py", "shader_disasm.py", "translate"]) - disasm = os.path.join(self.dxbc, "disasm") - for name in os.listdir(disasm): - if name.endswith(".s"): - os.remove(os.path.join(disasm, name)) - os.remove(os.path.join(self.spirv, "index.json")) - - self.assertFalse(make_game.shader_outputs_reusable(self.work, False, False)) - self.assertEqual(self.run_stage(), ["shader_disasm.py", "translate"]) - self.assertTrue(os.path.isfile(os.path.join(disasm, "s0.s"))) - self.assertTrue(make_game.shader_outputs_reusable(self.work, False, False)) - self.assertEqual(self.run_stage(), []) - - def test_translation_stopped_after_many_files_runs_again(self): - self.run_stage() - os.remove(os.path.join(self.spirv, "index.json")) # stopped before --merge - for i in range(1200): - self.touch(self.spirv, f"s{i}.spv") - self.assertEqual(self.run_stage(), ["translate"]) - - def test_failed_disasm_leaves_no_marker(self): - self.touch(self.dxbc, "index.json") - self.touch(self.dxbc, "fssm_index.json") - - def failing_py(tool, *args): - raise SystemExit(1) - with mock.patch.object(make_game, "py", failing_py), \ - mock.patch.object(make_game, "need", lambda *a: None), \ - mock.patch.object(make_game, "log", lambda *a: None): - with self.assertRaises(SystemExit): - make_game.shaders(os.path.join(self.work, "game"), self.work, 2) - self.assertFalse(os.path.exists(os.path.join(self.dxbc, "disasm.done"))) - - def test_rerunning_a_step_reruns_the_steps_after_it(self): - self.run_stage() - os.remove(os.path.join(self.dxbc, "fssm_index.json")) - self.assertEqual(self.run_stage(), ["fssm_unpack.py", "shader_disasm.py", "translate"]) - - def test_old_unpack_index_with_a_noncurrent_shader_is_refreshed(self): - self.run_stage() - with open(os.path.join(self.dxbc, "fssm_index.json"), "w", encoding="utf-8") as f: - json.dump([{"name": "s0"}, {"name": "removed"}], f) - self.assertFalse(make_game.shader_outputs_reusable(self.work, False, False)) - self.assertEqual(self.run_stage(), ["fssm_unpack.py", "shader_disasm.py", "translate"]) - self.assertEqual(self.run_stage(), []) - - def test_old_disassembly_with_a_noncurrent_shader_is_refreshed(self): - self.run_stage() - self.touch(self.dxbc, "disasm", "removed.s") - self.assertFalse(make_game.shader_outputs_reusable(self.work, False, False)) - self.assertEqual(self.run_stage(), ["shader_disasm.py", "translate"]) - self.assertFalse(os.path.exists(os.path.join(self.dxbc, "disasm", "removed.s"))) - self.assertEqual(self.run_stage(), []) - - def test_legacy_folder_without_llvm_version_refreshes_disassembly_once(self): - self.touch(self.dxbc, "index.json") - self.touch(self.dxbc, "fssm_index.json") - self.touch(self.dxbc, "disasm", "s0.s") - self.touch(self.spirv, "index.json") # translated by a build from before disasm.done - self.assertEqual(self.run_stage(), ["shader_disasm.py", "translate"]) - self.assertTrue(os.path.isfile(os.path.join(self.dxbc, "disasm.done"))) - self.assertEqual(self.run_stage(), []) - - def test_legacy_completion_marker_with_a_missing_listing_disassembles_everything_again(self): - # A disasm.done from before the listings were recorded holds only the llvm-mc signature: with a listing - # missing it can't tell which ones are current, so the whole disassembly runs again, not a resume. - self.touch(self.dxbc, "index.json") - self.touch(self.dxbc, "fssm_index.json") - self.touch(self.spirv, "index.json") - with open(os.path.join(self.dxbc, "disasm.done"), "w", encoding="utf-8", newline="\n") as f: - f.write(make_game.llvm_mc_signature() + "\n") - os.makedirs(os.path.join(self.dxbc, "disasm")) - self.assertFalse(make_game.shader_outputs_reusable(self.work, False, False)) - - original = self.fake_py - - def disassemble(tool, *args): - self.assertNotIn("--skip-existing", args) - original(tool, *args) - - with mock.patch.object(self, "fake_py", side_effect=disassemble): - self.assertEqual(self.run_stage(), ["shader_disasm.py", "translate"]) - self.assertTrue(make_game.shader_outputs_reusable(self.work, False, False)) - self.assertEqual(self.run_stage(), []) - - def test_old_disassembly_layout_is_rebuilt_in_the_current_location(self): - self.touch(self.dxbc, "index.json") - self.touch(self.dxbc, "fssm_index.json") - self.touch(self.work, "shaders", "disasm", "old.s") # disasm next to the carve folder, the old layout - self.touch(self.spirv, "index.json") - self.assertEqual(self.run_stage(), ["shader_disasm.py", "translate"]) - self.assertTrue(os.path.isfile(os.path.join(self.dxbc, "disasm", "s0.s"))) - self.assertFalse(os.path.exists(os.path.join(self.dxbc, "disasm", "old.s"))) - - # SHADER-11: the translation depends on --wave64-emulate, so a change of mode translates again. - def mode(self): - with open(os.path.join(self.spirv, "wave64_emulate.txt"), encoding="utf-8") as f: - return f.read().strip() - - def test_the_mode_is_recorded_beside_the_translation(self): - self.run_stage(emulate=True) - self.assertEqual(self.mode(), "on") - self.run_stage(emulate=False) - self.assertEqual(self.mode(), "off") - - def test_turning_emulation_on_translates_again_once(self): - self.run_stage(emulate=False) - self.assertEqual(self.run_stage(emulate=True), ["translate (emulated)"]) - self.assertEqual(self.run_stage(emulate=True), []) - - def test_turning_emulation_off_translates_again_once(self): - self.run_stage(emulate=True) - self.assertEqual(self.run_stage(emulate=False), ["translate"]) - self.assertEqual(self.run_stage(emulate=False), []) - - def test_a_folder_from_before_the_mode_file_counts_as_not_emulated(self): - self.run_stage(emulate=False) - os.remove(os.path.join(self.spirv, "wave64_emulate.txt")) - self.assertEqual(self.run_stage(emulate=False), []) # nothing translated, so still no mode file - self.assertEqual(self.run_stage(emulate=True), ["translate (emulated)"]) - - # A kill between the merge (index.json appears) and the end of shaders() must not leave a finished folder - # whose mode is unknown or wrong. - def kill_after_merge(self, emulate): - def translate_then_die(disasm, spirv, jobs, emulate=False, fallbacks=()): - self.touch(spirv, "index.json") # rdna2spirv.py --merge finished ... - raise KeyboardInterrupt # ... and the PC died right after - with mock.patch.object(make_game, "py", self.fake_py), \ - mock.patch.object(make_game, "need", lambda *a: None), \ - mock.patch.object(make_game, "translate", translate_then_die), \ - mock.patch.object(make_game, "log", lambda *a: None): - with self.assertRaises(KeyboardInterrupt): - make_game.shaders(os.path.join(self.work, "game"), self.work, 2, emulate=emulate) - - def test_a_kill_right_after_the_merge_keeps_the_finished_emulated_translation(self): - self.kill_after_merge(emulate=True) - self.assertEqual(self.run_stage(emulate=True), []) # hours of translation are not redone - self.assertEqual(self.mode(), "on") - - def test_a_kill_right_after_an_emulated_merge_is_not_mistaken_for_a_native_translation(self): - self.kill_after_merge(emulate=True) - self.assertEqual(self.run_stage(emulate=False), ["translate"]) # off was asked for: native, not "off" - - def test_a_kill_right_after_a_native_merge_counts_as_native(self): - self.kill_after_merge(emulate=False) - self.assertEqual(self.run_stage(emulate=False), []) - self.assertEqual(self.run_stage(emulate=True), ["translate (emulated)"]) - - # `auto` can answer differently from one run to the next (a GPU asleep or hidden, vulkaninfo missing): an - # emulated translation is exact on every GPU, so auto keeps it instead of translating the corpus again. - def run_auto(self, emulate): - self.ran = [] - with mock.patch.object(make_game, "py", self.fake_py), \ - mock.patch.object(make_game, "need", lambda *a: None), \ - mock.patch.object(make_game, "translate", self.fake_translate), \ - mock.patch.object(make_game, "log", lambda *a: None): - make_game.shaders(os.path.join(self.work, "game"), self.work, 2, emulate=emulate, keep_emulated=True) - return self.ran - - def test_auto_keeps_an_emulated_translation_when_this_run_would_not_emulate(self): - self.run_stage(emulate=True) - self.assertEqual(self.run_auto(emulate=False), []) - self.assertEqual(self.mode(), "on") - - def test_auto_still_translates_again_when_a_native_translation_needs_emulation(self): - self.run_stage(emulate=False) - self.assertEqual(self.run_auto(emulate=True), ["translate (emulated)"]) - - def test_an_explicit_off_still_translates_an_emulated_folder_again(self): - self.run_stage(emulate=True) - self.assertEqual(self.run_stage(emulate=False), ["translate"]) - - def test_a_mode_change_does_not_redo_the_steps_before_translation(self): - self.run_stage(emulate=False) - self.assertEqual(self.run_stage(emulate=True), ["translate (emulated)"]) - self.assertTrue(os.path.isfile(os.path.join(self.dxbc, "disasm.done"))) - - # The translation also depends on the translator's own files: one made from other files, or from unknown ones, is - # translated again once, and nothing before it is redone. - def sources_file(self): - return os.path.join(self.spirv, "translation_sources.sha256") - - def record_sources(self, digest): - with open(self.sources_file(), "w", encoding="utf-8") as f: - f.write(digest + "\n") - - def copy_tools(self): - tools = os.path.join(self.work, "tools") - os.makedirs(tools) - for name in make_game.TRANSLATION_SOURCES + ("shader_disasm.py",): - shutil.copy(os.path.join(make_game.TOOLS, name), tools) - patch = mock.patch.object(make_game, "TOOLS", tools) - patch.start() - self.addCleanup(patch.stop) - return tools - - def test_an_unreadable_sources_file_translates_again(self): - self.run_stage() - with open(self.sources_file(), "wb") as f: - f.write(b"\xff\xfe\x00") - self.assertEqual(self.run_stage(), ["translate"]) - self.assertEqual(self.run_stage(), []) - - def test_editing_any_translation_source_translates_again_once(self): - tools = self.copy_tools() - self.run_stage() - for name in make_game.TRANSLATION_SOURCES: - with open(os.path.join(tools, name), "ab") as f: - f.write(b"\n") - self.assertEqual(self.run_stage(), ["translate"], name) - self.assertEqual(self.run_stage(), [], name) - - def test_editing_another_tool_or_changing_jobs_keeps_the_translation(self): - tools = self.copy_tools() - self.run_stage() - with open(os.path.join(tools, "shader_disasm.py"), "ab") as f: - f.write(b"\n") - self.assertEqual(self.run_stage(), []) - self.assertEqual(self.run_stage(jobs=7), []) - - def test_an_invalid_mode_file_refreshes_the_translation(self): - self.run_stage(emulate=True) - with open(os.path.join(self.spirv, "wave64_emulate.txt"), "wb") as f: - f.write(b"\xff") - self.assertEqual(self.run_stage(emulate=False), ["translate"]) - self.assertEqual(self.mode(), "off") - - def test_auto_keeps_emulating_when_translating_again_for_new_sources(self): - self.run_stage(emulate=True) - self.record_sources("0" * 64) - self.assertEqual(self.run_auto(emulate=False), ["translate (emulated)"]) - self.assertEqual(self.mode(), "on") - self.assertEqual(self.run_auto(emulate=False), []) - - def test_auto_keeps_emulating_through_a_failed_rebuild_for_new_sources(self): - self.run_stage(emulate=True) - self.record_sources("0" * 64) - - def failing_translate(disasm, spirv, jobs, emulate=False, fallbacks=()): - self.assertTrue(emulate) - raise SystemExit(1) - with mock.patch.object(make_game, "py", self.fake_py), \ - mock.patch.object(make_game, "need", lambda *a: None), \ - mock.patch.object(make_game, "translate", failing_translate), \ - mock.patch.object(make_game, "log", lambda *a: None): - with self.assertRaises(SystemExit): - make_game.shaders(os.path.join(self.work, "game"), self.work, 2, emulate=False, keep_emulated=True) - self.assertFalse(os.path.exists(os.path.join(self.spirv, "index.json"))) - self.assertEqual(self.run_auto(emulate=False), ["translate (emulated)"]) - self.assertEqual(self.mode(), "on") - - def test_an_explicit_off_translates_natively_for_new_sources(self): - self.run_stage(emulate=True) - self.record_sources("0" * 64) - self.assertEqual(self.run_stage(emulate=False), ["translate"]) - self.assertEqual(self.mode(), "off") - - def test_a_kill_right_after_a_merge_for_new_sources_keeps_the_translation(self): - self.run_stage() - self.record_sources("0" * 64) - self.kill_after_merge(emulate=False) - self.assertEqual(self.run_stage(), []) # hours of translation are not redone - - -class TranslationSourcesTest(unittest.TestCase): - def test_the_list_covers_every_local_module_the_translator_imports(self): - seen, todo = set(), ["rdna2spirv"] - while todo: - name = todo.pop() - if name in seen: - continue - seen.add(name) - with open(os.path.join(make_game.TOOLS, name + ".py"), encoding="utf-8") as f: - tree = ast.parse(f.read()) - for node in ast.walk(tree): # function-level imports too - if isinstance(node, ast.Import): - mods = [a.name for a in node.names] - elif isinstance(node, ast.ImportFrom) and node.module and not node.level: - mods = [node.module] - else: - continue - todo += [m.split(".")[0] for m in mods - if os.path.isfile(os.path.join(make_game.TOOLS, m.split(".")[0] + ".py"))] - self.assertEqual({n + ".py" for n in seen}, - {n for n in make_game.TRANSLATION_SOURCES if n.endswith(".py")}) - - -class MergePublishesLastTest(unittest.TestCase): - """rdna2spirv.py --merge writes the stubs before index.json, which tells make_game.py the translation finished.""" - - def merge(self, out): - tool = os.path.join(make_game.TOOLS, "rdna2spirv.py") - return subprocess.run([sys.executable, "-I", tool, out, "--out", out, "--merge"], - capture_output=True, text=True, errors="replace") - - def test_a_failed_stub_write_leaves_no_index_and_a_retry_publishes_it(self): - with tempfile.TemporaryDirectory() as out: - with open(os.path.join(out, "index.part0.json"), "w", encoding="utf-8") as f: - json.dump({"s0": {"stage": "ps", "inputs": [0]}}, f) - blocker = os.path.join(out, "stubs") - open(blocker, "w").close() # a plain file where the stubs folder goes - r = self.merge(out) - self.assertNotEqual(r.returncode, 0, r.stdout + r.stderr) - self.assertFalse(os.path.exists(os.path.join(out, "index.json"))) - os.remove(blocker) - r = self.merge(out) - self.assertEqual(r.returncode, 0, r.stdout + r.stderr) - self.assertTrue(os.path.isfile(os.path.join(out, "index.json"))) - self.assertTrue(os.path.isfile(os.path.join(out, "stubs", "vs_0.spv"))) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/test_shader_stats.py b/tests/test_shader_stats.py deleted file mode 100644 index 6cfb69cd3..000000000 --- a/tests/test_shader_stats.py +++ /dev/null @@ -1,273 +0,0 @@ -"""Unit tests for scripts/shader_stats.py (standard library only, no GPU). - - python -I tests/test_shader_stats.py -""" -import os -import runpy -import subprocess -import sys -import tempfile -import unittest -from unittest import mock - -ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) -SCRIPT = os.path.join(ROOT, "scripts", "shader_stats.py") - -# ps_flat's listing as llvm-mc prints it: 8 instructions, highest VGPR v5. -PS_FLAT = """; ps_flat code 0x0..0x0 (synthetic), gfx1013, 0 invalid words -\tv_interp_mov_f32_e32 v2, p0, attr1.x ; encoding: [0x02,0x04,0x0a,0xc8] -\tv_add_nc_u32_e32 v3, 1, v2 ; encoding: [0x81,0x04,0x06,0x4a] -\tv_interp_p1_f32_e32 v4, v0, attr0.x ; encoding: [0x00,0x00,0x10,0xc8] -\tv_interp_p2_f32_e32 v4, v1, attr0.x ; encoding: [0x01,0x00,0x11,0xc8] -\tv_interp_p1_f32_e32 v5, v0, attr0.y ; encoding: [0x00,0x01,0x14,0xc8] -\tv_interp_p2_f32_e32 v5, v1, attr0.y ; encoding: [0x01,0x01,0x15,0xc8] -\texp mrt0 v2, v3, v4, v5 done vm ; encoding: [0x0f,0x18,0x00,0xf8,0x02,0x03,0x04,0x05] -\ts_endpgm ; encoding: [0x00,0x00,0x81,0xbf] -""" - -# Every RADV statistic reported: this full output must stay byte for byte as it was. -COMPLETE = ["ps_flat,ps,Instructions,16", "ps_flat,ps,VGPRs,8", "ps_flat,ps,SGPRs,20", "ps_flat,ps,Scratch size,1024", - "ps_flat,ps,Spilled VGPRs,2", "ps_flat,ps,Spilled SGPRs,1", "ps_flat,ps,Subgroups per SIMD,16", - "ps_flat,ps,Driver pipeline hash,abc"] -COMPLETE_SUMMARY = ("ps: 1 shaders, code growth median 2.00x (p90 2.00x, max 2.00x); VGPRs median 8 vs original 6; " - "scratch in 1, spills in 1; waves/SIMD median 16\n") -COMPLETE_DETAILS = """shader stage orig aco growth v_orig VGPRs SGPRs scratch spills waves -ps_flat ps 8 16 2.00 6 8 20 1024 3 16 - -""" -NOTHING = "ps: 1 shaders, code growth n/a; VGPRs n/a; scratch n/a, spills n/a; waves/SIMD n/a\n" - - -class ShaderStats(unittest.TestCase): - def run_stats(self, rows, details=True, listings=None, header="name,stage,statistic,value", extra=()): - with tempfile.TemporaryDirectory() as tmp: - disasm = os.path.join(tmp, "disasm") - os.makedirs(disasm) - for name, text in (listings or {"ps_flat": PS_FLAT}).items(): - with open(os.path.join(disasm, name + ".s"), "w", encoding="utf-8") as f: - f.write(text) - csv_path = os.path.join(tmp, "stats.csv") - with open(csv_path, "w", encoding="utf-8") as f: - f.write(header + "\n" + "".join(f"{r}\n" for r in rows)) - cmd = [sys.executable, "-I", SCRIPT, csv_path, disasm] + (["--details"] if details else []) + list(extra) - return subprocess.run(cmd, capture_output=True, text=True) - - def detail(self, r, name="ps_flat"): - return next(ln for ln in r.stdout.splitlines() if ln.startswith(name + " ")).split() - - def test_growth_registers_and_scratch(self): - r = self.run_stats(["ps_flat,ps,Instructions,16", "ps_flat,ps,VGPRs,8", "ps_flat,ps,SGPRs,20", - "ps_flat,ps,Scratch size,1024", "ps_flat,ps,Spilled VGPRs,2", - "ps_flat,ps,Subgroups per SIMD,16", "ps_flat,ps,Driver pipeline hash,abc"]) - self.assertEqual(r.returncode, 0, r.stderr) - line = next(ln for ln in r.stdout.splitlines() if ln.startswith("ps_flat")) - self.assertEqual(line.split(), ["ps_flat", "ps", "8", "16", "2.00", "6", "8", "20", "1024", ">=2", "16"]) - self.assertIn("ps: 1 shaders, code growth median 2.00x", r.stdout) - self.assertIn("scratch in 1, spills in 1", r.stdout) - - def test_empty_listing_has_no_growth_denominator(self): - rows = ["ps_empty,ps,Instructions,16"] - listings = {"ps_empty": "; no instructions\n"} - result = self.run_stats(rows, listings=listings) - self.assertEqual(result.returncode, 0, result.stderr) - self.assertEqual(self.detail(result, "ps_empty")[2:5], ["0", "16", "-"]) - self.assertIn("code growth n/a", result.stdout) - - result = self.run_stats(rows + ["ps_flat,ps,Instructions,16"], details=False, - listings={**listings, "ps_flat": PS_FLAT}) - self.assertEqual(result.returncode, 0, result.stderr) - self.assertIn("code growth median 2.00x (p90 2.00x, max 2.00x) (1 of 2)", result.stdout) - - def test_original_vgpr_count_includes_non_contiguous_image_addresses(self) -> None: - listing = ("\timage_sample v[6:9], [v1, v31, v2], s[0:7], s[8:11] dmask:0xf\n" - "\ts_endpgm\n") - result = self.run_stats(["ps_nsa,ps,VGPRs,24"], listings={"ps_nsa": listing}) - self.assertEqual(result.returncode, 0, result.stderr) - self.assertEqual(self.detail(result, "ps_nsa")[5:7], ["32", "24"]) - self.assertIn("VGPRs median 24 vs original 32", result.stdout) - - def test_unreadable_listing_has_a_path_specific_error(self): - with tempfile.TemporaryDirectory() as tmp: - stats = os.path.join(tmp, "stats.csv") - listing = os.path.join(tmp, "ps_flat.s") - with open(stats, "w", encoding="utf-8", newline="\n") as f: - f.write("name,stage,statistic,value\n" + COMPLETE[0] + "\n") - with open(listing, "w", encoding="utf-8", newline="\n") as f: - f.write(PS_FLAT) - open_file = open - - def locked(path, *args, **kwargs): - if path == listing: - raise PermissionError(13, "Permission denied", path) - return open_file(path, *args, **kwargs) - - with mock.patch("builtins.open", side_effect=locked), \ - mock.patch.object(sys, "argv", [SCRIPT, stats, tmp]), self.assertRaises(SystemExit) as caught: - runpy.run_path(SCRIPT, run_name="__main__") - self.assertIn(listing, str(caught.exception)) - self.assertIn("Permission denied", str(caught.exception)) - - def test_shaders_without_a_listing_are_left_out(self): - r = self.run_stats(["ps_other,ps,Instructions,10"], details=False) - self.assertNotEqual(r.returncode, 0) - self.assertIn("no shader is in both", r.stderr) - - def test_complete_radv_output_is_unchanged(self): - r = self.run_stats(COMPLETE) - self.assertEqual((r.returncode, r.stderr, r.stdout), (0, "", COMPLETE_DETAILS + COMPLETE_SUMMARY)) - r = self.run_stats(COMPLETE, details=False) - self.assertEqual((r.returncode, r.stderr, r.stdout), (0, "", COMPLETE_SUMMARY)) - - def test_other_driver_statistics_are_shown_raw_not_interpreted(self): - rows = ["ps_flat,ps,Foo count (bytes),123", 'ps_flat,ps,"Bar, total",18446744073709551615', - "ps_flat,ps,Register Count,24", "ps_flat,ps,stage,99"] - r = self.run_stats(rows) - self.assertEqual(r.returncode, 0, r.stderr) - self.assertEqual(self.detail(r), ["ps_flat", "ps", "8", "-", "-", "6", "-", "-", "-", "-", "-"]) - lines = r.stdout.splitlines() - i = lines.index(" Bar, total = 18446744073709551615") - self.assertEqual(lines[i + 1:i + 3], [" Foo count (bytes) = 123", " Register Count = 24"]) - self.assertIn(" stage = 99", lines) - self.assertTrue(r.stdout.endswith("\n" + NOTHING), r.stdout) - r = self.run_stats(rows, details=False) - self.assertEqual((r.returncode, r.stdout), (0, NOTHING)) - self.assertEqual(len(r.stderr.splitlines()), 1, r.stderr) - self.assertEqual(r.stderr, "additional driver statistics (see --details): Bar, total; Foo count (bytes); Register Count; stage\n") - - def test_partial_statistics_state_their_subset(self): - rows = ["ps_flat,ps,Instructions,16", "ps_flat,ps,VGPRs,8", "ps_flat,ps,SGPRs,20", "ps_flat,ps,Scratch size,1024", - "ps_flat,ps,Spilled VGPRs,2", "ps_flat,ps,Spilled SGPRs,0", "ps_flat,ps,Subgroups per SIMD,16", - "ps_part,ps,Instructions,12"] - listings = {"ps_flat": PS_FLAT, "ps_part": PS_FLAT} - r = self.run_stats(rows, listings=listings) - self.assertEqual(r.returncode, 0, r.stderr) - self.assertEqual(self.detail(r, "ps_part"), ["ps_part", "ps", "8", "12", "1.50", "6", "-", "-", "-", "-", "-"]) - r = self.run_stats(rows, details=False, listings=listings) - self.assertEqual((r.returncode, r.stderr), (0, "")) - self.assertEqual(r.stdout, "ps: 2 shaders, code growth median 1.75x (p90 1.50x, max 2.00x); " - "VGPRs median 8 vs original 6 (1 of 2); scratch in 1 (1 of 2), spills in 1 (1 of 2); " - "waves/SIMD median 16 (1 of 2)\n") - - def test_measured_zero_differs_from_missing_and_one_spill_counter_is_a_lower_bound(self): - cases = [(["Scratch size,0", "Spilled VGPRs,0", "Spilled SGPRs,0"], "0", "0", "scratch in 0, spills in 0;"), - (["Spilled SGPRs,3"], "-", ">=3", "scratch n/a, spills in 1;"), - (["Spilled VGPRs,0"], "-", "-", "scratch n/a, spills n/a;")] - for stats, scratch, spilled, summary in cases: - with self.subTest(stats=stats): - r = self.run_stats(["ps_flat,ps,Instructions,16"] + ["ps_flat,ps," + s for s in stats]) - self.assertEqual(r.returncode, 0, r.stderr) - self.assertEqual(self.detail(r)[8:10], [scratch, spilled]) - self.assertIn(summary, r.stdout) - - def test_values_are_exact_or_unavailable(self): - r = self.run_stats(["ps_flat,ps,Instructions,18446744073709551615"]) - self.assertEqual(r.returncode, 0, r.stderr) - self.assertEqual(self.detail(r)[3], "18446744073709551615") - r = self.run_stats(["ps_flat,ps,Instructions,12.0"]) - self.assertEqual(self.detail(r)[3], "12") - for stat, column in [("Instructions,nan", 3), ("Instructions,", 3), ("Instructions,inf", 3), - ("Instructions," + "9" * 400, 3), ("VGPRs,abc", 6)]: - with self.subTest(stat=stat[:20]): - r = self.run_stats(["ps_flat,ps," + stat]) - self.assertEqual(r.returncode, 0, r.stderr) - self.assertNotIn("Traceback", r.stderr) - self.assertEqual(self.detail(r)[column], "-") - - def test_integral_decimal_counters_keep_all_digits(self): - for raw in ("9007199254740993.0", "9.007199254740993e15"): - with self.subTest(raw=raw): - result = self.run_stats([f"ps_flat,ps,Instructions,{raw}"]) - self.assertEqual(result.returncode, 0, result.stderr) - self.assertEqual(self.detail(result)[3], "9007199254740993") - - def test_missing_required_header_is_rejected_with_path_and_line(self): - r = self.run_stats(["ps_flat,ps,Instructions,16"], header="name,stage,statistic") - self.assertNotEqual(r.returncode, 0) - self.assertNotIn("Traceback", r.stderr) - self.assertIn("stats.csv: line 1:", r.stderr) - self.assertIn("missing required header column(s): value", r.stderr) - - def test_duplicate_required_header_is_rejected_before_rows(self): - r = self.run_stats(["ps_flat,ps_flat,ps,Instructions,16"], header="name,name,stage,statistic,value") - self.assertNotEqual(r.returncode, 0) - self.assertNotIn("Traceback", r.stderr) - self.assertIn("stats.csv: line 1:", r.stderr) - self.assertIn("duplicated required header column(s): name", r.stderr) - - def test_broken_quoted_record_does_not_report_partial_statistics(self): - result = self.run_stats([ - "ps_flat,ps,Instructions,16", - 'ps_flat,ps,VGPRs,"8', - "ps_flat,ps,Spilled VGPRs,2", - ]) - self.assertEqual(result.returncode, 1) - self.assertEqual(result.stdout, "") - self.assertIn("stats.csv:", result.stderr) - self.assertIn("unexpected end of data", result.stderr) - self.assertNotIn("Traceback", result.stderr) - - def test_short_row_missing_a_cell_is_rejected_with_its_line(self): - r = self.run_stats(["ps_flat,ps,Instructions"]) - self.assertNotEqual(r.returncode, 0) - self.assertNotIn("Traceback", r.stderr) - self.assertIn("stats.csv: line 2:", r.stderr) - self.assertIn("row missing required column(s): value", r.stderr) - - def test_extra_headed_columns_and_explicitly_blank_value_remain_accepted(self): - r = self.run_stats(["ps_flat,ps,Instructions,,abc", "ps_flat,ps,VGPRs,8,xyz"], - header="name,stage,statistic,value,extra") - self.assertEqual(r.returncode, 0, r.stderr) - d = self.detail(r) - self.assertEqual((d[3], d[6]), ("-", "8")) - - def test_row_wider_than_the_header_is_rejected_with_its_line(self): - r = self.run_stats(["ps_flat,ps,Instructions,16", "ps_flat,ps,VGPRs,8,unheaded"]) - self.assertEqual(r.returncode, 1) - self.assertEqual(r.stdout, "") - self.assertIn("stats.csv: line 3: row has more fields than the header", r.stderr) - self.assertNotIn("Traceback", r.stderr) - - def run_args(self, *args): - return subprocess.run([sys.executable, "-I", SCRIPT, *args], capture_output=True, text=True) - - def test_help_goes_to_stdout_with_exit_code_0(self): - for flag in ("-h", "--help"): - r = self.run_args(flag) - self.assertEqual(r.returncode, 0, r.stderr) - self.assertIn(" [--details]", r.stdout) - self.assertEqual(r.stderr, "") - - def test_help_wins_over_other_arguments(self): - r = self.run_args("stats.csv", "disasm", "--help") - self.assertEqual(r.returncode, 0, r.stderr) - self.assertIn("--details", r.stdout) - - def test_wrong_argument_count_is_a_usage_error(self): - for args in ((), ("stats.csv",), ("stats.csv", "disasm", "extra")): - r = self.run_args(*args) - self.assertEqual(r.returncode, 2, args) - self.assertIn("usage: shader_stats.py", r.stderr) - self.assertEqual(r.stdout, "") - - def test_unknown_option_is_refused_not_ignored(self): - # --detail (a typo) used to print the summary with exit code 0, as if no option had been given. - r = self.run_stats(COMPLETE, details=False, extra=["--detail"]) - self.assertEqual(r.returncode, 2) - self.assertIn("unknown option --detail", r.stderr) - self.assertEqual(r.stdout, "") - - def test_details_is_still_accepted_anywhere(self): - r = self.run_stats(COMPLETE, details=False, extra=["--details"]) - self.assertEqual(r.returncode, 0, r.stderr) - self.assertEqual(self.detail(r)[0], "ps_flat") - - def test_header_only_report_is_a_valid_empty_report(self): - r = self.run_stats([], details=False) - self.assertNotEqual(r.returncode, 0) - self.assertNotIn("Traceback", r.stderr) - self.assertNotIn("missing required", r.stderr) - self.assertIn("no shader is in both", r.stderr) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/test_shell_launchers.py b/tests/test_shell_launchers.py deleted file mode 100644 index d8cad6ae5..000000000 --- a/tests/test_shell_launchers.py +++ /dev/null @@ -1,114 +0,0 @@ -"""Build.sh and Mods.sh, the Linux and macOS counterparts of Build.bat and Mods.bat, start the right Python. - - python -I tests/test_shell_launchers.py - -Each launcher is run with a PATH that holds only stub interpreters: shell scripts that answer the version check with -the version they are given and otherwise record their arguments. The launcher must pick the first one that is 3.12 -or newer, run make_game.py (or the mod manager) through it with -I and every argument unchanged, from any folder, -pass the exit code back, and stop with a message when there is none. POSIX only (/bin/sh); no Python is started -for real, no compiler and no game files. -""" -import os -import shutil -import subprocess -import tempfile -import unittest -from pathlib import Path - -ROOT = Path(__file__).resolve().parents[1] -LAUNCHERS = {"Build.sh": ["make_game.py"], "Mods.sh": ["tools/leonida_mods.py", "gui"]} - -STUB = """#!/bin/sh -if [ "$1" = -c ]; then - exit {ok} -fi -for a in "$@"; do printf '%s\\n' "$a"; done > "$LEONIDA_STUB_LOG.{name}" -exit {status} -""" - - -@unittest.skipIf(os.name == "nt" or not os.path.exists("/bin/sh"), "POSIX shell launchers") -class ShellLauncherTest(unittest.TestCase): - def setUp(self): - tmp = tempfile.TemporaryDirectory() - self.addCleanup(tmp.cleanup) - self.tmp = Path(tmp.name) - self.bin = self.tmp / "bin" - self.bin.mkdir() - self.log = self.tmp / "log" - # PATH holds the stubs and the one external command the launchers run, dirname (cd, pwd, command -v and - # printf are shell builtins), so the machine's own pythons in /usr/bin can't be picked instead. - tools = self.tmp / "tools" - tools.mkdir() - dirname = shutil.which("dirname") - if not dirname: - self.skipTest("no dirname") - (tools / "dirname").symlink_to(dirname) - self.path = os.pathsep.join([str(self.bin), str(tools)]) - - def stub(self, name, ok=True, status=0): - path = self.bin / name - path.write_text(STUB.format(ok=0 if ok else 1, name=name, status=status), encoding="utf-8", newline="\n") - path.chmod(0o755) - - def run_launcher(self, launcher, *args, cwd=None): - env = {"PATH": self.path, "LEONIDA_STUB_LOG": str(self.log), "HOME": str(self.tmp)} - return subprocess.run(["/bin/sh", str(ROOT / launcher), *args], cwd=cwd or self.tmp, env=env, - capture_output=True, text=True, timeout=60) - - def recorded(self, name): - return (self.tmp / f"log.{name}").read_text(encoding="utf-8").splitlines() - - def test_the_first_new_enough_python_runs_the_tool_with_every_argument(self): - for launcher, tool in LAUNCHERS.items(): - with self.subTest(launcher=launcher): - for name in ("python3.14", "python3.13", "python3.12", "python3", "python"): - (self.bin / name).unlink(missing_ok=True) - self.stub("python3.13", ok=False) # too old: skipped - self.stub("python3.12") - self.stub("python3") # also new enough, but later in the order - args = ["--out", "/mnt/a b/Leonida", "", "it's", "$HOME", "*"] - p = self.run_launcher(launcher, *args) - self.assertEqual(p.returncode, 0, p.stderr) - want = ["-I", str(ROOT / tool[0]), *tool[1:], *args] - self.assertEqual(self.recorded("python3.12"), want) - self.assertFalse((self.tmp / "log.python3").exists()) - - def test_python3_is_used_when_there_is_no_versioned_name(self): - self.stub("python3") - p = self.run_launcher("Build.sh", "--check") - self.assertEqual(p.returncode, 0, p.stderr) - self.assertEqual(self.recorded("python3"), ["-I", str(ROOT / "make_game.py"), "--check"]) - - def test_the_exit_code_comes_back(self): - self.stub("python3", status=7) - self.assertEqual(self.run_launcher("Build.sh").returncode, 7) - - def test_started_from_another_folder(self): - self.stub("python3") - elsewhere = self.tmp / "elsewhere" - elsewhere.mkdir() - p = self.run_launcher("Build.sh", "--find", cwd=elsewhere) - self.assertEqual(p.returncode, 0, p.stderr) - self.assertEqual(self.recorded("python3")[1], str(ROOT / "make_game.py")) - - def test_without_a_new_enough_python_it_says_so(self): - self.stub("python3", ok=False) - for launcher in LAUNCHERS: - with self.subTest(launcher=launcher): - p = self.run_launcher(launcher) - self.assertEqual(p.returncode, 1) - self.assertIn("Python 3.12 or newer is needed", p.stderr) - self.assertFalse((self.tmp / "log.python3").exists()) - - def test_the_launchers_are_executable_and_lf(self): - for launcher in LAUNCHERS: - with self.subTest(launcher=launcher): - path = ROOT / launcher - self.assertTrue(os.access(path, os.X_OK), f"{launcher} lost its executable bit") - self.assertNotIn(b"\r", path.read_bytes()) - self.assertTrue(path.read_bytes().startswith(b"#!/bin/sh\n")) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/test_skin_streams.py b/tests/test_skin_streams.py deleted file mode 100644 index 3d3176ad3..000000000 --- a/tests/test_skin_streams.py +++ /dev/null @@ -1,610 +0,0 @@ -"""Synthetic-data tests for tools/skin_streams.py (ASSET-12, the joint-index and skin-weight format). - - python -I tests/test_skin_streams.py - -Every byte here is built by the test: a synthetic drawable system page, a synthetic graphics page and a -synthetic RPF9-style archive made of page-aligned zlib streams. No game file, value or name is used. -""" -import contextlib -import io -import json -import os -import struct -import subprocess -import sys -import tempfile -import unittest -import zlib -from unittest import mock - -ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) -TOOL = os.path.join(ROOT, "tools", "skin_streams.py") -sys.path.insert(0, os.path.join(ROOT, "tools")) - -import skin_streams as ss # noqa: E402 - - -class Page: - """A little big-endian-free allocator for the synthetic system page.""" - - def __init__(self, size=0x1000): - self.buf = bytearray(size) - self.at = 0x180 # leave room for the drawable header - - def put(self, data): - at = self.at - self.buf[at:at + len(data)] = data - self.at += len(data) - return at - - def u16(self, at, value): - struct.pack_into(" (size, fmt, offset, data bytes); slot 0 must be present as the position. - """ - geometry = page.put(b"\0" * 160) - vb = page.put(b"\0" * 80) - fvf = page.put(b"\0" * 0x13C) - lod = page.put(b"\0" * 16) - model = page.put(b"\0" * 56) - geo_array = page.put(struct.pack(" 8 else b"".join(struct.pack(" None: - slots = { - 0: (8, 16, 96, bytes(24)), - 16: (4, 28, 128, bytes((255, 0, 0, 0)) * 3), - 20: (8, 12, 144, struct.pack("<12H", 300, 700, 0, 0, - 403, 700, 0, 0, 399, 700, 0, 0)), - } - system, gfx = build_resource(slots, vertices=3, bones=400) - stats = self.run_scan(system, gfx) - validated = stats["validated"]["weighted-4inf-16bit"] - self.assertEqual(validated["descriptor-mismatch"], 0) - self.assertEqual(validated["weighted-components"], 3) - self.assertEqual(validated["components-out-of-range"], 1) - - def test_unaligned_resource_is_not_a_candidate(self): - system, gfx, _mesh = rigid_mesh() - stats = self.run_scan(system, gfx, extra=zlib.compress(system, 9)) - self.assertEqual(stats["resources"], 1) # only the aligned copy counts - - def test_empty_archive_is_zero_resources_not_a_traceback(self): - with tempfile.TemporaryDirectory() as tmp: - path = os.path.join(tmp, "empty.rpf") - open(path, "wb").close() - stats = ss.scan_archive(path, 64, lambda _text: None) - self.assertEqual((stats["resources"], stats["meshes"], stats["candidates"]), (0, 0, 0)) - self.assertEqual(ss.main([path]), 0) - - def test_rigid_scan(self): - system, gfx, _mesh = rigid_mesh(sixteen=True) - stats = self.run_scan(system, gfx) - self.assertEqual(stats["layouts"].get("rigid-16bit", {"meshes": 0})["meshes"], 1) - self.assertEqual(stats["validated"]["rigid-16bit"]["components-out-of-range"], 0) - - def test_scan_finds_fragment_with_null_optional_pointers(self): - system, gfx, _mesh = weighted_mesh("weighted-8inf-8bit", vertices=12, bones=7) - b = bytearray(system) - for at in (16, 32, 40): - struct.pack_into(" ok - 20: (8, 30, 104, bytes(16))}, 2, 6) # format 30 with 8 bytes must be refused - with self.assertRaises(ss.Skip): - ss.walk_resource(system, "drawable") - - -class TestCli(unittest.TestCase): - @staticmethod - def _archive(tmp, name="synthetic.rpf"): - system, gfx, _mesh = weighted_mesh("weighted-8inf-8bit", vertices=12, bones=7) - data = build_archive(system, gfx) - path = os.path.join(tmp, name) - with open(path, "wb") as fh: - fh.write(data) - return path, data - - def test_json_over_an_input_archive_is_refused(self): - with tempfile.TemporaryDirectory() as tmp: - path, data = self._archive(tmp) - other = os.path.join(tmp, ".", "synthetic.rpf") - r = subprocess.run([sys.executable, "-I", TOOL, path, "--json", other], - capture_output=True, text=True, errors="replace") - self.assertEqual(r.returncode, 2, r.stderr) - self.assertIn("would overwrite the input", r.stderr) - self.assertNotIn("Traceback", r.stderr) - self.assertEqual(r.stdout, "") - with open(path, "rb") as fh: - self.assertEqual(fh.read(), data) - - def test_json_that_is_a_directory_is_refused_before_the_scan(self): - with tempfile.TemporaryDirectory() as tmp: - path, _ = self._archive(tmp) - r = subprocess.run([sys.executable, "-I", TOOL, path, "--json", tmp], - capture_output=True, text=True, errors="replace") - self.assertEqual(r.returncode, 2, r.stderr) - self.assertIn("is a directory", r.stderr) - self.assertNotIn("Traceback", r.stderr) - self.assertEqual(r.stdout, "") - - def test_json_in_a_missing_folder_is_created(self): - with tempfile.TemporaryDirectory() as tmp: - path, _ = self._archive(tmp) - out = os.path.join(tmp, "reports", "sub", "out.json") - r = subprocess.run([sys.executable, "-I", TOOL, path, "--json", out], - capture_output=True, text=True, errors="replace") - self.assertEqual(r.returncode, 0, r.stderr) - with open(out, encoding="utf-8") as fh: - report = json.load(fh) - self.assertIn(path, report) - self.assertEqual(report[path]["resources"], 1) - - def test_json_that_cannot_be_written_is_one_error_line(self): - with tempfile.TemporaryDirectory() as tmp: - path, _ = self._archive(tmp) - blocker = os.path.join(tmp, "blocker") - with open(blocker, "w", encoding="utf-8") as fh: - fh.write("a file, not a folder") - out = os.path.join(blocker, "out.json") - r = subprocess.run([sys.executable, "-I", TOOL, path, "--json", out], - capture_output=True, text=True, errors="replace") - self.assertEqual(r.returncode, 2, r.stderr) - self.assertIn("cannot write", r.stderr) - self.assertNotIn("Traceback", r.stderr) - self.assertIn("synthetic.rpf: 1 resources", r.stdout) - - def test_invalid_sample_is_refused(self): - with tempfile.TemporaryDirectory() as tmp: - path, _ = self._archive(tmp) - for sample in ("0", "-1"): - with self.subTest(sample=sample): - r = subprocess.run([sys.executable, "-I", TOOL, path, "--sample", sample], - capture_output=True, text=True, errors="replace") - self.assertEqual(r.returncode, 2, r.stderr) - self.assertIn("--sample must be at least 1", r.stderr) - self.assertNotIn("Traceback", r.stderr) - - def test_unreadable_archive_reports_its_path_without_writing_json(self): - with tempfile.TemporaryDirectory() as tmp: - path, _ = self._archive(tmp) - out = os.path.join(tmp, "report.json") - stderr = io.StringIO() - error = PermissionError(13, "input is locked", path) - with (mock.patch.object(ss, "open", create=True, side_effect=error), - contextlib.redirect_stderr(stderr)): - self.assertEqual(ss.main([path, "--json", out]), 2) - self.assertEqual(stderr.getvalue().splitlines(), - [f"error: cannot read {path}: input is locked"]) - self.assertFalse(os.path.exists(out)) - - def test_missing_or_directory_input_is_refused(self): - with tempfile.TemporaryDirectory() as tmp: - missing = os.path.join(tmp, "missing.rpf") - r = subprocess.run([sys.executable, "-I", TOOL, missing], - capture_output=True, text=True, errors="replace") - self.assertEqual(r.returncode, 2, r.stderr) - self.assertIn("not a file", r.stderr) - self.assertNotIn("Traceback", r.stderr) - - r2 = subprocess.run([sys.executable, "-I", TOOL, tmp], - capture_output=True, text=True, errors="replace") - self.assertEqual(r2.returncode, 2, r2.stderr) - self.assertIn("not a file", r2.stderr) - self.assertNotIn("Traceback", r2.stderr) - - -if __name__ == "__main__": - unittest.main(verbosity=2) diff --git a/tests/test_skinned_glb.py b/tests/test_skinned_glb.py deleted file mode 100644 index 2fa34cb1d..000000000 --- a/tests/test_skinned_glb.py +++ /dev/null @@ -1,864 +0,0 @@ -"""Synthetic tests for tools/skinned_glb.py. - - python -I tests/test_skinned_glb.py - -Every model, skeleton, skin stream and GLB here is built by the test. No game -file, value or name is used. The fixture is a three-bone ped skeleton, a -two-entry drawable palette and a three-vertex 8-influence skin buffer. -""" -import hashlib -import json -import math -import os -import struct -import subprocess -import sys -import tempfile -import unittest -from unittest import mock - -ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) -sys.path.insert(0, os.path.join(ROOT, "tools")) - -import glb_writer # noqa: E402 -import skinned_glb # noqa: E402 - - -def _matrix(translation=(0.0, 0.0, 0.0)): - return [1.0, 0.0, 0.0, 0.0, - 0.0, 1.0, 0.0, 0.0, - 0.0, 0.0, 1.0, 0.0, - float(translation[0]), float(translation[1]), float(translation[2]), 1.0] - - -def _write_json(path, value): - with open(path, "w", encoding="utf-8") as handle: - json.dump(value, handle, indent=2) - - -def _write_glb(path): - primitive = { - "positions": [(0.0, 0.0, 0.0), (1.0, 0.0, 0.0), (0.0, 1.0, 0.0)], - "normals": [(0.0, 0.0, 1.0)] * 3, - "uvs": [(0.0, 0.0), (1.0, 0.0), (0.0, 1.0)], - "indices": [0, 1, 2], - } - with open(path, "wb") as handle: - handle.write(glb_writer.build_glb([primitive])) - - -def _read(path): - with open(path, "rb") as handle: - return handle.read() - - -def _section_word(offset, fmt): - return ((offset // 2) << 8) | fmt - - -def _skin_buffer(j0, j1, w0, w1, *, omit_slot=None, formats=None, offsets=None, size=0x160): - """Graphics buffer with the measured 23-word section header and per-slot rows.""" - formats = {6: 0x26, 7: 0x26, 8: 0x25, 9: 0x25, **(formats or {})} - offsets = {6: 0x100, 7: 0x110, 8: 0x120, 9: 0x130, **(offsets or {})} - data = {6: w0, 7: w1, 8: j0, 9: j1} - blob = bytearray(size) - for slot in (6, 7, 8, 9): - if slot == omit_slot: - continue - struct.pack_into(" len(blob): - raise ValueError("test skin stream does not fit its buffer") - blob[offsets[slot]:end] = data[slot] - return bytes(blob) - - -def _packed_indices(rows): - """Pack four u8 joint indices per vertex into the 0x8C four-u32 layout. - - Bits 12-31 get a recognisable pattern, including bits 12-15, so a decoder - that masks 16 bits instead of 12 fails instead of passing. - """ - return b"".join( - struct.pack("<4I", *(0xA5CFF000 | index for index in row)) for row in rows - ) - - -def _packed_buffer(j0_rows, j1_rows): - _j0, _j1, w0, w1 = _streams() - return _skin_buffer( - _packed_indices(j0_rows), _packed_indices(j1_rows), w0, w1, - formats={8: 0x8C, 9: 0x8C}, - offsets={8: 0x120, 9: 0x160}, - size=0x1A0, - ) - - -def _skeleton(): - """A three-bone RAGE Z-up bind pose: root, spine, left upper arm.""" - return [ - {"index": 0, "name": "SKEL_ROOT", "parent": None, "bind_matrix": _matrix()}, - {"index": 1, "name": "SKEL_Spine", "parent": 0, - "bind_matrix": _matrix((0.0, 0.0, 1.0))}, - {"index": 2, "name": "SKEL_L_UpperArm", "parent": 1, - "bind_matrix": _matrix((1.0, 0.0, 1.0))}, - ] - - -def _palette(): - return [ - skinned_glb.joaat32("SKEL_Spine"), - skinned_glb.joaat32("GM_TEST_L_UpperArm01_O"), - ] - - -def _streams(): - j0 = bytes([0, 1, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0]) - j1 = bytes(12) - w0 = bytes([64, 191, 0, 0, 128, 127, 0, 0, 255, 0, 0, 0]) - w1 = bytes(12) - return j0, j1, w0, w1 - - -def _component(root, *, own_skeleton=None, omit_slot=None, buffer=None, mesh_blob=None): - directory = os.path.join(root, "component") - os.makedirs(os.path.join(directory, "buffers")) - if buffer is None: - j0, j1, w0, w1 = _streams() - buffer = _skin_buffer(j0, j1, w0, w1, omit_slot=omit_slot) - with open(os.path.join(directory, "buffers", "01_0.bin"), "wb") as handle: - handle.write(buffer) - _write_glb(os.path.join(directory, "model.glb")) - model = { - "buffer_files": ["buffers/01_0.bin"], - "glb": "model.glb", - "vertex_count": 3, - "drawable": { - "name": "synthetic", - "buffers": [{"bytes": len(buffer), "gfx_off": 0}], - "geometries": [{"vertex_buffer": 0, "index_buffer": 0}], - "models": [{"bone_palette": _palette()}], - "strings": ["GM_TEST_L_UpperArm01_O"], - }, - "meshes": [{ - "geometry": 0, - "model": 0, - "name": "synthetic_mesh", - "vertex_count": 3, - "skinned": True, - "skin_influences": 8, - }], - } - if own_skeleton is not None: - model["drawable"]["skeleton"] = own_skeleton - if mesh_blob is not None: - model["drawable"]["buffers"][0]["mesh_blob"] = mesh_blob - _write_json(os.path.join(directory, "model.json"), model) - return directory - - -def _read_model(directory): - with open(os.path.join(directory, "model.json"), encoding="utf-8") as handle: - return json.load(handle) - - -def _skeleton_dir(root): - directory = os.path.join(root, "skeleton") - os.makedirs(directory) - _write_json(os.path.join(directory, "model.json"), { - "drawable": {"skeleton": _skeleton()}, - }) - return directory - - -def _accessor(gltf, binary, index): - payload, accessor = skinned_glb.accessor_bytes(gltf, binary, index) - return payload, accessor - - -def _world_matrices(gltf): - nodes = gltf["nodes"] - parent = {} - for index, node in enumerate(nodes): - for child in node.get("children", []): - parent[child] = index - cache = {} - - def world(index): - if index in cache: - return cache[index] - matrix = nodes[index].get( - "matrix", [1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, - 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0]) - if index in parent: - matrix = skinned_glb.mat_mul(world(parent[index]), matrix) - cache[index] = matrix - return matrix - - return world - - -def _transform(matrix, point): - return [ - sum(matrix[column * 4 + row] * point[column] for column in range(3)) + matrix[12 + row] - for row in range(3) - ] - - -class InterleavedAccessorTest(unittest.TestCase): - def test_last_attribute_can_end_at_the_last_bin_byte(self) -> None: - gltf = { - "bufferViews": [{"buffer": 0, "byteStride": 24, "byteLength": 48}], - "accessors": [{"bufferView": 0, "byteOffset": 12, "componentType": 5126, - "count": 2, "type": "VEC3"}], - } - vertices = struct.pack("<12f", 1, 2, 3, 0, 1, 0, 4, 5, 6, 0, 0, 1) - normals, _ = skinned_glb.accessor_bytes(gltf, vertices, 0) - self.assertEqual(normals, struct.pack("<6f", 0, 1, 0, 0, 0, 1)) - with self.assertRaisesRegex(skinned_glb.SkinError, "outside the BIN chunk"): - skinned_glb.accessor_bytes(gltf, vertices[:-1], 0) - - -class SkinnedGlbTest(unittest.TestCase): - def setUp(self): - self.temp = tempfile.TemporaryDirectory() - self.root = self.temp.name - - def tearDown(self): - self.temp.cleanup() - - def _build(self): - skeleton = _skeleton_dir(self.root) - component = _component(self.root) - payload, stats = skinned_glb.build_skinned_glb(skeleton, [component]) - gltf, binary = skinned_glb.read_glb(self._write(payload)) - return gltf, binary, stats - - def _write(self, payload): - path = os.path.join(self.root, "out.glb") - with open(path, "wb") as handle: - handle.write(payload) - return path - - def test_joint_count_and_palette_resolution(self): - _gltf, _binary, stats = self._build() - self.assertEqual(stats["ped_joints"], 3) - self.assertEqual(stats["component_joints"], 1) - self.assertEqual(stats["joints"], 4) - self.assertEqual(stats["vertices"], 3) - self.assertEqual(stats["triangles"], 1) - self.assertEqual(stats["source_weight_sum_min"], 255) - self.assertEqual(stats["source_weight_sum_max"], 255) - - def test_local_child_listed_before_its_parent_keeps_the_own_skeleton_link(self): - skeleton = _skeleton_dir(self.root) - component = _component(self.root) - model = _read_model(component) - model["drawable"]["skeleton"] = [ - {"name": "HelperParent", "parent_name": "SKEL_Spine", - "bind_matrix": _matrix((0.0, 0.0, 2.0))}, - {"name": "HelperChild", "parent_name": "HelperParent", - "bind_matrix": _matrix((0.0, 0.0, 3.0))}, - ] - model["drawable"]["models"][0]["bone_palette"] = [ - skinned_glb.joaat32("HelperChild"), - skinned_glb.joaat32("HelperParent"), - ] - _write_json(os.path.join(component, "model.json"), model) - - payload, stats = skinned_glb.build_skinned_glb(skeleton, [component]) - gltf, _binary = skinned_glb.read_glb(self._write(payload)) - self.assertEqual(stats["component_joints"], 2) - by_name = {node.get("name"): index for index, node in enumerate(gltf["nodes"])} - parent, child = by_name["HelperParent"], by_name["HelperChild"] - self.assertIn(child, gltf["nodes"][parent].get("children", [])) - self.assertIn(parent, gltf["nodes"][by_name["SKEL_Spine"]].get("children", [])) - - def test_local_child_under_a_parent_the_palette_never_lists(self): - skeleton = _skeleton_dir(self.root) - component = _component(self.root) - model = _read_model(component) - model["drawable"]["skeleton"] = [ - {"name": "HelperParent", "parent_name": "SKEL_Spine", - "bind_matrix": _matrix((0.0, 0.0, 2.0))}, - {"name": "HelperMiddle", "parent": 0, "bind_matrix": _matrix((0.0, 0.0, 3.0))}, - {"name": "HelperChild", "parent": 1, "bind_matrix": _matrix((0.0, 0.0, 4.0))}, - ] - model["drawable"]["models"][0]["bone_palette"] = [ - skinned_glb.joaat32("HelperChild"), - skinned_glb.joaat32("GM_TEST_L_UpperArm01_O"), - ] - _write_json(os.path.join(component, "model.json"), model) - - payload, stats = skinned_glb.build_skinned_glb(skeleton, [component]) - gltf, _binary = skinned_glb.read_glb(self._write(payload)) - self.assertEqual(stats["component_joints"], 4) - by_name = {node.get("name"): index for index, node in enumerate(gltf["nodes"])} - parent, middle, child = (by_name["HelperParent"], by_name["HelperMiddle"], - by_name["HelperChild"]) - self.assertIn(middle, gltf["nodes"][parent].get("children", [])) - self.assertIn(child, gltf["nodes"][middle].get("children", [])) - self.assertIn(parent, gltf["nodes"][by_name["SKEL_Spine"]].get("children", [])) - - def test_normalized_byte_uvs_have_aligned_output_rows(self) -> None: - from anim_glb import pack_glb - - skeleton = _skeleton_dir(self.root) - component = _component(self.root) - source_path = os.path.join(component, "model.glb") - source, source_bin = skinned_glb.read_glb(source_path) - uv_index = source["meshes"][0]["primitives"][0]["attributes"]["TEXCOORD_0"] - uv_accessor = source["accessors"][uv_index] - uv_view = source["bufferViews"][uv_accessor["bufferView"]] - uv_accessor.update(componentType=5121, normalized=True) - uv_view.update(byteStride=4, byteLength=12) - offset = uv_view["byteOffset"] - rows = bytes((0, 255, 0, 0, 64, 128, 0, 0, 255, 0, 0, 0)) - source_bin = source_bin[:offset] + rows + source_bin[offset + len(rows):] - with open(source_path, "wb") as handle: - handle.write(pack_glb(source, source_bin)) - - payload, _ = skinned_glb.build_skinned_glb(skeleton, [component]) - gltf, binary = skinned_glb.read_glb(self._write(payload)) - index = gltf["meshes"][0]["primitives"][0]["attributes"]["TEXCOORD_0"] - accessor = gltf["accessors"][index] - view = gltf["bufferViews"][accessor["bufferView"]] - self.assertEqual((accessor["componentType"], accessor["normalized"]), (5121, True)) - self.assertEqual((view.get("byteStride"), view["byteLength"]), (4, 12)) - start = view["byteOffset"] - self.assertEqual(binary[start:start + view["byteLength"]], rows) - self.assertEqual(_accessor(gltf, binary, index)[0], bytes((0, 255, 64, 128, 255, 0))) - - def test_weight_sums_are_one(self): - gltf, binary, _stats = self._build() - primitive = gltf["meshes"][0]["primitives"][0] - w0, _ = _accessor(gltf, binary, primitive["attributes"]["WEIGHTS_0"]) - w1, _ = _accessor(gltf, binary, primitive["attributes"]["WEIGHTS_1"]) - for vertex in range(3): - values = struct.unpack_from("<4f", w0, 16 * vertex) + \ - struct.unpack_from("<4f", w1, 16 * vertex) - self.assertAlmostEqual(sum(values), 1.0, places=6) - self.assertGreater(values[0], 0.0) - - def test_joint_indices_are_in_skin_range(self): - gltf, binary, _stats = self._build() - joint_count = len(gltf["skins"][0]["joints"]) - self.assertEqual(joint_count, 4) - primitive = gltf["meshes"][0]["primitives"][0] - j0, _ = _accessor(gltf, binary, primitive["attributes"]["JOINTS_0"]) - j1, _ = _accessor(gltf, binary, primitive["attributes"]["JOINTS_1"]) - for vertex in range(3): - indices = struct.unpack_from("<4H", j0, 8 * vertex) + \ - struct.unpack_from("<4H", j1, 8 * vertex) - for index in indices: - self.assertLess(index, joint_count) - # The second palette entry is the added helper joint (index 3). - self.assertEqual(struct.unpack_from("<4H", j0, 0), (1, 3, 0, 0)) - - def test_inverse_bind_round_trip(self): - gltf, binary, _stats = self._build() - skin = gltf["skins"][0] - ibm_payload, ibm_accessor = _accessor(gltf, binary, skin["inverseBindMatrices"]) - self.assertEqual(ibm_accessor["count"], len(skin["joints"])) - inverse_binds = [struct.unpack_from("<16f", ibm_payload, 64 * index) - for index in range(len(skin["joints"]))] - world = _world_matrices(gltf) - for joint, inverse_bind in zip(skin["joints"], inverse_binds): - product = skinned_glb.mat_mul(world(joint), inverse_bind) - expected = [1.0 if index in (0, 5, 10, 15) else 0.0 for index in range(16)] - for actual, wanted in zip(product, expected): - self.assertAlmostEqual(actual, wanted, places=5) - - primitive = gltf["meshes"][0]["primitives"][0] - positions, _ = _accessor(gltf, binary, primitive["attributes"]["POSITION"]) - j0, _ = _accessor(gltf, binary, primitive["attributes"]["JOINTS_0"]) - j1, _ = _accessor(gltf, binary, primitive["attributes"]["JOINTS_1"]) - w0, _ = _accessor(gltf, binary, primitive["attributes"]["WEIGHTS_0"]) - w1, _ = _accessor(gltf, binary, primitive["attributes"]["WEIGHTS_1"]) - for vertex in range(3): - point = struct.unpack_from("<3f", positions, 12 * vertex) - indices = struct.unpack_from("<4H", j0, 8 * vertex) + \ - struct.unpack_from("<4H", j1, 8 * vertex) - weights = struct.unpack_from("<4f", w0, 16 * vertex) + \ - struct.unpack_from("<4f", w1, 16 * vertex) - result = [0.0, 0.0, 0.0] - for index, weight in zip(indices, weights): - matrix = skinned_glb.mat_mul(world(skin["joints"][index]), - inverse_binds[index]) - moved = _transform(matrix, point) - for axis in range(3): - result[axis] += weight * moved[axis] - for actual, wanted in zip(result, point): - self.assertAlmostEqual(actual, wanted, places=5) - - def test_numpy_and_stdlib_weight_paths_agree(self): - if skinned_glb._np is None: - self.skipTest("numpy is not importable, so the optional path cannot be compared") - j0, j1, w0, w1 = _streams() - j0 = bytearray(j0) - j0[2] = 200 # zero-weight component outside the two-entry palette - j0 = bytes(j0) - with_numpy = skinned_glb.normalise_weights(j0, j1, w0, w1, 3, 2, [1, 3], 4) - saved = skinned_glb._np - try: - skinned_glb._np = None - without_numpy = skinned_glb.normalise_weights(j0, j1, w0, w1, 3, 2, [1, 3], 4) - finally: - skinned_glb._np = saved - for key in ("j0", "j1", "w0", "w1"): - self.assertEqual(with_numpy[key], without_numpy[key], key) - self.assertEqual(with_numpy["sum_min"], without_numpy["sum_min"]) - self.assertEqual(with_numpy["sum_max"], without_numpy["sum_max"]) - self.assertAlmostEqual(struct.unpack_from("<4f", with_numpy["w0"], 0)[0], 64 / 255, delta=1e-6) - - def test_only_weighted_joint_indices_must_fit_unsigned_short(self): - backends = [None] if skinned_glb._np is None else [None, skinned_glb._np] - palette = [65536, 65535] - for backend in backends: - with self.subTest(backend=backend), mock.patch.object(skinned_glb, "_np", backend): - for second_set in (False, True): - w0, w1 = bytes([255, 0, 0, 0]), bytes(4) - if second_set: - w0, w1 = w1, w0 - with self.subTest(second_set=second_set): - with self.assertRaisesRegex(skinned_glb.SkinError, "UNSIGNED_SHORT"): - skinned_glb.normalise_weights(bytes(4), bytes(4), w0, w1, 1, 2, palette, 65537) - joints = bytes([1, 0, 0, 0]) - out = skinned_glb.normalise_weights(joints, joints, w0, w1, 1, 2, palette, 65537) - weighted, unused = ("j1", "j0") if second_set else ("j0", "j1") - self.assertEqual(struct.unpack("<4H", out[weighted]), (65535, 0, 0, 0)) - self.assertEqual(out[unused], bytes(8)) - - def test_full_export_without_numpy(self): - skeleton = _skeleton_dir(self.root) - component = _component(self.root) - saved = skinned_glb._np - try: - skinned_glb._np = None - payload, stats = skinned_glb.build_skinned_glb(skeleton, [component]) - finally: - skinned_glb._np = saved - gltf, binary = skinned_glb.read_glb(self._write(payload)) - self.assertEqual(stats["joints"], 4) - primitive = gltf["meshes"][0]["primitives"][0] - w0, _ = _accessor(gltf, binary, primitive["attributes"]["WEIGHTS_0"]) - for vertex in range(3): - self.assertAlmostEqual(sum(struct.unpack_from("<4f", w0, 16 * vertex)), 1.0, places=6) - - def test_packed_joint_stream_decodes_to_four_u8_indices(self): - j0_rows = [(1, 2, 0, 0), (1, 2, 0, 0), (2, 1, 0, 0)] - j1_rows = [(3, 0, 0, 0)] * 3 - component = _component(self.root, buffer=_packed_buffer(j0_rows, j1_rows)) - model = _read_model(component) - streams = skinned_glb.read_skin_streams(component, model, model["meshes"][0]) - self.assertEqual(streams["j0"], bytes([1, 2, 0, 0, 1, 2, 0, 0, 2, 1, 0, 0])) - self.assertEqual(streams["j1"], bytes([3, 0, 0, 0] * 3)) - - def test_packed_joint_index_above_u8_is_rejected(self): - j0_rows = [(1, 2, 0, 0), (1, 2, 0, 0), (256, 0, 0, 0)] - j1_rows = [(3, 0, 0, 0)] * 3 - component = _component(self.root, buffer=_packed_buffer(j0_rows, j1_rows)) - model = _read_model(component) - with self.assertRaisesRegex(skinned_glb.SkinError, "does not fit u8"): - skinned_glb.read_skin_streams(component, model, model["meshes"][0]) - - def test_short_packed_joint_stream_is_rejected(self): - j0 = _packed_indices([(1, 2, 0, 0)] * 3)[:47] - j1 = _packed_indices([(3, 0, 0, 0)] * 3) - _j0, _j1, w0, w1 = _streams() - buffer = _skin_buffer( - j0, j1, w0, w1, - formats={8: 0x8C, 9: 0x8C}, - offsets={8: 0x150, 9: 0x120}, - size=0x17F, - ) - component = _component(self.root, buffer=buffer) - model = _read_model(component) - with self.assertRaisesRegex(skinned_glb.SkinError, "outside its graphics buffer"): - skinned_glb.read_skin_streams(component, model, model["meshes"][0]) - - def test_missing_joint_stream_is_rejected(self): - component = _component(self.root, omit_slot=8) - skeleton = _skeleton_dir(self.root) - with self.assertRaises(skinned_glb.SkinError): - skinned_glb.build_skinned_glb(skeleton, [component]) - - def test_mesh_blob_sections_supply_the_stream_offsets(self): - j0, j1, w0, w1 = _streams() - buffer = bytearray(_skin_buffer(j0, j1, w0, w1)) - for slot in (6, 7, 8, 9): - struct.pack_into(" other for v in r] for r in self.rows]) - - def __eq__(self, other): - return _FakeMask([[v == other for v in r] for r in self.rows]) - - def __ge__(self, other): - return _FakeMask([[v >= other for v in r] for r in self.rows]) - - def __itruediv__(self, col): - for r, d in zip(self.rows, col.vals): - for i in range(len(r)): - r[i] = r[i] / d - return self - - def __getitem__(self, key): - if isinstance(key, _FakeMask): - return _FakeVec([v for r, mr in zip(self.rows, key.rows) for v, m in zip(r, mr) if m]) - if isinstance(key, tuple) and len(key) == 2 and key[0] == slice(None): - return _FakeArray([r[key[1]] for r in self.rows]) - raise TypeError(key) - - def __setitem__(self, key, value): - assert isinstance(key, _FakeMask) - for r, mr in zip(self.rows, key.rows): - for i, m in enumerate(mr): - if m: - r[i] = value - - def tobytes(self): - if self.rows and isinstance(self.rows[0][0], float): - return b"".join(struct.pack(".tmp must stay intact after exporting . - skeleton = _skeleton_dir(self.root) - component = _component(self.root) - old_buf = os.path.join(component, "buffers", "01_0.bin") - new_buf_rel = "buffers/export.glb.tmp" - new_buf = os.path.join(component, "buffers", "export.glb.tmp") - os.replace(old_buf, new_buf) - model_json_path = os.path.join(component, "model.json") - with open(model_json_path, "r", encoding="utf-8") as handle: - model = json.load(handle) - model["buffer_files"] = [new_buf_rel] - _write_json(model_json_path, model) - before_hash = hashlib.sha256(_read(new_buf)).hexdigest() - - out = os.path.join(component, "buffers", "export.glb") - result = subprocess.run( - [sys.executable, "-I", os.path.join(ROOT, "tools", "skinned_glb.py"), out, - "--skeleton", skeleton, "--component", component], - capture_output=True, text=True, check=False, - ) - self.assertEqual(result.returncode, 0, result.stderr) - self.assertTrue(_read(out).startswith(b"glTF")) - self.assertTrue(os.path.exists(new_buf)) - self.assertEqual(hashlib.sha256(_read(new_buf)).hexdigest(), before_hash) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/test_smem_neg_probe.py b/tests/test_smem_neg_probe.py deleted file mode 100644 index 991ebdd23..000000000 --- a/tests/test_smem_neg_probe.py +++ /dev/null @@ -1,215 +0,0 @@ -"""tools/smem_neg_probe.py without a GPU: encodings, translator expectations, kernel builder, and oracle lifecycle. - - python -I tests/test_smem_neg_probe.py -""" -import contextlib -import io -import os -import sys -import unittest -from unittest import mock - -ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) -sys.path.insert(0, os.path.join(ROOT, "tools")) -sys.path.insert(0, os.path.join(ROOT, "tools", "hw_oracle")) - -import runner # noqa: E402 -import smem_neg_probe as p # noqa: E402 - - -class SmemNegProbeTest(unittest.TestCase): - def test_seed_bounds(self): - self.assertEqual(p.seed(-0x40), (p.SEED - 0x40) & 0xFFFFFFFF) - self.assertEqual(p.seed(0), p.SEED) - self.assertEqual(p.seed(0xBC), p.SEED + 0xBC) - self.assertIsNone(p.seed(-0x44)) - self.assertIsNone(p.seed(0xC0)) - - def test_sbuf_raw_encoding(self): - lines = p.sbuf_raw(48, 12, 0x7D, -4) - self.assertEqual(lines, [".long 0xf4200c06", ".long 0xfa1ffffc"]) - - def test_translator_sbuf_bounds(self): - self.assertEqual(p.translator_sbuf(0, 0), [0]) - self.assertEqual(p.translator_sbuf(0xFC, 0), [0xFC]) - self.assertEqual(p.translator_sbuf(0x100, 0), [None]) - self.assertEqual(p.translator_sbuf(0xFFFFFFFC, 8), [4]) - self.assertEqual(p.translator_sbuf(0xFFFFFFFC, 0), [None]) - - def test_expected_and_kernel_lines(self): - want = p.expected() - self.assertEqual(list(want.keys()), [r[0] for r in p.ROWS]) - self.assertEqual(want["sload_imm_m4"], [(p.SEED - 4) & 0xFFFFFFFF]) - self.assertEqual(want["sload_x2_soff4_m10"], [(p.SEED - 0xC) & 0xFFFFFFFF, (p.SEED - 8) & 0xFFFFFFFF]) - self.assertEqual(want["sbuf_soffm4_imm8"], [p.SEED + 4]) - self.assertEqual(want["sbuf_soffm4"], [None]) - - lines, order = p.kernel_lines() - self.assertEqual(len(order), sum(len(r[2]) for r in p.ROWS)) - self.assertEqual(lines[-1], "s_endpgm") - - def test_translator_mode_prints_every_row(self): - buf = io.StringIO() - with contextlib.redirect_stdout(buf): - rc = p.main(["--oracle", "translator"]) - self.assertEqual(rc, 0) - out = buf.getvalue() - for name, *_ in p.ROWS: - self.assertIn(name, out) - - -class OracleLifecycleTest(unittest.TestCase): - def _expected_flat(self): - want = p.expected() - flat = [] - for name, *_ in p.ROWS: - flat.extend(0 if v is None else v for v in want[name]) - return flat - - def _run_hw(self, fake_oracle): - buf = io.StringIO() - with ( - mock.patch.object(runner, "open_oracle", return_value=fake_oracle) as open_mock, - mock.patch.object(runner, "Oracle", side_effect=AssertionError("Oracle() called directly")), - contextlib.redirect_stdout(buf), - ): - rc = p.main(["--oracle", "hw"]) - open_mock.assert_called_once_with() - return rc, buf.getvalue() - - def test_hw_uses_open_oracle_and_closes_on_match(self): - flat = self._expected_flat() - - class FakeOracle: - device = "fake-gpu" - arch = "gfx1036" - closed = False - - def run(self, kernels): - return [list(flat)] - - def close(self): - self.closed = True - - fake = FakeOracle() - rc, out = self._run_hw(fake) - self.assertEqual(rc, 0) - self.assertTrue(fake.closed) - self.assertIn("device: fake-gpu (gfx1036)", out) - self.assertNotIn("DIFFERS", out) - - def test_hw_closes_on_mismatch(self): - flat = self._expected_flat() - - class FakeOracle: - device = "fake-gpu" - arch = "gfx1036" - closed = False - - def run(self, kernels): - return [[0] * len(flat)] - - def close(self): - self.closed = True - - fake = FakeOracle() - rc, out = self._run_hw(fake) - self.assertEqual(rc, 1) - self.assertTrue(fake.closed) - self.assertIn("DIFFERS", out) - - def test_hw_accepts_tuple_oracle_results(self): - flat = self._expected_flat() - - class FakeOracle: - device = "fake-gpu" - arch = "gfx1036" - closed = False - - def run(self, kernels): - return (tuple(flat),) - - def close(self): - self.closed = True - - fake = FakeOracle() - rc, out = self._run_hw(fake) - self.assertEqual(rc, 0) - self.assertTrue(fake.closed) - self.assertNotIn("DIFFERS", out) - - def test_hw_closes_on_malformed_oracle_results(self): - flat = self._expected_flat() - - class FakeOracle: - device = "fake-gpu" - arch = "gfx1036" - - def __init__(self, responses): - self.responses = responses - self.closed = False - - def run(self, kernels): - return self.responses[kernels[0].wave] - - def close(self): - self.closed = True - - bad_cases = [ - ("empty_results", [], "expected 1"), - ("none_results", None, "NoneType"), - ("str_results", "bad", "str"), - ("extra_results", [list(flat), list(flat)], "got 2"), - ("none_kernel_result", [None], "NoneType"), - ("int_kernel_result", [123], "int"), - ("short_words", [[0] * 4], f"expected {len(flat)} words, got 4"), - ("overlong_zeros", [[0] * (len(flat) + 1)], f"expected {len(flat)} words, got {len(flat) + 1}"), - ("overlong_matching", [list(flat) + [0]], f"expected {len(flat)} words, got {len(flat) + 1}"), - ("non_int_word", [[None] * len(flat)], "NoneType"), - ("bool_word", [[True] * len(flat)], "bool"), - ] - for label, bad_ret, hint in bad_cases: - for fail_wave in (32, 64): - with self.subTest(case=label, wave=fail_wave): - responses = {32: [list(flat)], 64: [list(flat)]} - responses[fail_wave] = bad_ret - fake = FakeOracle(responses) - rc, out = self._run_hw(fake) - self.assertEqual(rc, 2) - self.assertTrue(fake.closed) - self.assertIn(f"wave{fail_wave}:", out) - self.assertIn(hint, out) - self.assertNotIn("device:", out) - - def test_hw_closes_on_kernel_rejection(self): - class FakeOracle: - device = "fake-gpu" - arch = "gfx1036" - closed = False - - def run(self, kernels): - return ["assembler rejected"] - - def close(self): - self.closed = True - - fake = FakeOracle() - rc, out = self._run_hw(fake) - self.assertEqual(rc, 2) - self.assertTrue(fake.closed) - self.assertIn("kernel rejected", out) - - def test_hw_unavailable_returns_77(self): - buf = io.StringIO() - with ( - mock.patch.object(runner, "open_oracle", side_effect=runner.Unavailable("no device")), - mock.patch.object(runner, "Oracle", side_effect=AssertionError("Oracle() called directly")), - contextlib.redirect_stdout(buf), - ): - rc = p.main(["--oracle", "hw"]) - self.assertEqual(rc, 77) - self.assertIn("no device", buf.getvalue()) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/test_smh_groom.py b/tests/test_smh_groom.py deleted file mode 100644 index a76d60829..000000000 --- a/tests/test_smh_groom.py +++ /dev/null @@ -1,1048 +0,0 @@ -"""Pure synthetic unit tests for tools/smh_groom.py (no game files, stdlib only). - -Run with: - python -I tests/test_smh_groom.py -""" -from __future__ import annotations - -import gc -import json -import math -import os -import struct -import subprocess -import sys -import tempfile -import tracemalloc -import unittest -from unittest import mock -import zlib - -ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) -TOOLS = os.path.join(ROOT, "tools") -if TOOLS not in sys.path: - sys.path.insert(0, TOOLS) - -import glb_writer # noqa: E402 -import smh_groom # noqa: E402 - - -def _align16(data: bytes) -> bytes: - pad = (-len(data)) % 16 - return data + (b"\x00" * pad) - - -def build_synthetic_groom_buffers( - *, - guides_pos: list[list[tuple[float, float, float]]] | None = None, - triangles: list[tuple[int, int, int]] | None = None, - tri_count: list[tuple[int, int, int, int]] | None = None, - tri_region: list[int] | None = None, - uvs: list[tuple[float, float]] | None = None, - strand_totals: tuple[int, int] | None = None, - flags: int = 0x443, - length_random: tuple[float, float] = (0.0, 1.0), - seeds: tuple[int, int] = (0x12345678, 0x89ABCDEF), - regions: list[tuple[int, int, int, int, int]] | None = None, - bone_hashes: tuple[int, ...] = (0x34C53E77, 0x11223344), - style_hashes: tuple[int, ...] = (0x34C53E77, 0x89EA2ED6, 0x89EA2ED6, 0x89EA2ED6, 0x74792000, 0xD54A2D40), - include_optional: bool = True, - tail_bytes: bytes = b"", - sentinel_2c: int = 0xFFFFFFFF, - include_ext_3c: bool = False, - unset_rig_floats: bool = False, - style_params_f16: dict[int, float] | None = None, -) -> tuple[bytes, bytes]: - """Build a synthetic (system_page, gpu_buffer) pair for unit testing.""" - if guides_pos is None: - # 4 guides in a small square scalp patch, 4 nodes per guide growing straight along +Z. - roots = [ - (-0.05, 0.00, 0.70), - (0.05, 0.00, 0.70), - (0.05, 0.05, 0.70), - (-0.05, 0.05, 0.70), - ] - heights = (0.00, 0.04, 0.08, 0.12) - guides_pos = [ - [(rx, ry, rz + dz) for dz in heights] - for (rx, ry, rz) in roots - ] - guides = len(guides_pos) - ppg = len(guides_pos[0]) - nodes = guides * ppg - if triangles is None: - triangles = [(0, 1, 2), (0, 2, 3)] - tris = len(triangles) - if tri_count is None: - tri_count = [(12, 4, 0, 0) for _ in range(tris)] - if tri_region is None: - tri_region = [0 for _ in range(tris)] - if uvs is None: - uvs = [(i / max(guides - 1, 1), 0.5) for i in range(guides)] - - # Compute exact arc lengths per guide. - guide_lengths: list[float] = [] - for g in guides_pos: - acc = 0.0 - for j in range(ppg - 1): - p0, p1 = g[j], g[j + 1] - acc += math.hypot(p1[0] - p0[0], p1[1] - p0[1], p1[2] - p0[2]) - guide_lengths.append(acc) - - gpu = bytearray(smh_groom.HEADER_SIZE) - header = [0] * 40 - - def append_array(hdr_off: int, payload: bytes) -> int: - # 4-byte align each array. - pad = (-len(gpu)) % 4 - if pad: - gpu.extend(b"\x00" * pad) - start = len(gpu) - gpu.extend(payload) - if hdr_off is not None: - header[hdr_off // 4] = start - return start - - # Required arrays. - pos_vals: list[float] = [] - for g_idx, g in enumerate(guides_pos): - for k_idx, (x, y, z) in enumerate(g): - pos_vals.extend((x, y, z, float(k_idx) / max(ppg - 1, 1))) - append_array(0x44, struct.pack(f"<{nodes * 4}e", *pos_vals)) - append_array(0x40, struct.pack(f"<{tris * 3}H", *(i for t in triangles for i in t))) - append_array(0x48, bytes(c for row in tri_count for c in row)) - append_array(0x4C, bytes(tri_region)) - append_array(0x30, struct.pack(f"<{guides}e", *guide_lengths)) - append_array(0x08, struct.pack(f"<{guides * 2}e", *(v for uv in uvs for v in uv))) - append_array(0x10, bytes([0, 1, 0, 0, 0, 0, 0, 0] * guides)) - append_array(0x14, bytes([192, 64, 0, 0, 0, 0, 0, 0] * guides)) - - if include_optional: - append_array(0x00, bytes([64, 128, 192, 255] * guides)) - append_array(0x04, bytes([32, 96, 160, 0] * guides)) - append_array(0x0C, bytes([64, 128, 191, 255] * guides)) - append_array(0x18, bytes(12 * guides)) - append_array(0x28, bytes([128, 128, 255, 0] * guides)) - append_array(0x34, bytes(4 * nodes)) - append_array(0x38, bytes(2 * nodes)) - - if tail_bytes: - append_array(smh_groom.TAIL_OFFSET, tail_bytes) - if include_ext_3c: - append_array(smh_groom.EXT_3C_OFFSET, b"\xAA" * 16) - - # Pad GPU buffer to multiple of 4 bytes (dword count in descriptor). - pad = (-len(gpu)) % 4 - if pad: - gpu.extend(b"\x00" * pad) - - header[smh_groom.SENTINEL_OFFSET // 4] = sentinel_2c - header[0x50 // 4] = flags - header[0x54 // 4] = (nodes << 8) | 0x01 - header[0x58 // 4] = guides | (tris << 16) - header[0x5C // 4] = ppg - lr_word = struct.unpack("= 0x120 bytes + descriptor + bone hashes + region records). - xs = [p[0] for g in guides_pos for p in g] - ys = [p[1] for g in guides_pos for p in g] - zs = [p[2] for g in guides_pos for p in g] - if strand_totals is None: - strand_totals = (sum(c[0] for c in tri_count), sum(c[1] for c in tri_count)) - if regions is None: - regions = [(tris, guides, strand_totals[0], 0, strand_totals[1])] - - sysd = bytearray(0x120) - struct.pack_into(" bytes: - """Pack (system, gpu) into native RAGE resource wire framing (16 zero prefix + 16-aligned zlib streams).""" - out = bytearray(b"\x00" * 16) - out.extend(_align16(zlib.compress(system))) - if split_gpu_chunks <= 1: - out.extend(_align16(zlib.compress(gpu))) - else: - step = max(1, (len(gpu) + split_gpu_chunks - 1) // split_gpu_chunks) - for start in range(0, len(gpu), step): - out.extend(_align16(zlib.compress(gpu[start:start + step]))) - return bytes(out) - - -def _reference_scatter_one( - t: int, - n_tris: int, - per_tri: list[int], - tri_region: bytes, - density_scale: float, - blocked: set[int], - seed_word: int, -) -> tuple[int, bool, int, tuple[float, float, float]]: - """Independent scalar reference implementation of smh_gen_1_CS_InterpolateStrands RNG.""" - m32 = 0xFFFFFFFF - m24 = 0xFFFFFF - ds32 = struct.unpack("> 16 - v6 = (v5 * v11 + 0x31CD17D1) & m32 - v7 = (v6 * v5) & m32 - v5 ^= v5 >> 16 - v6 ^= v6 >> 16 - v7 = (v7 + s0) & m32 - v7 ^= v7 >> 16 - v8 = ((v9 ^ v11) + ((v7 * v5) & m32)) & m32 - v10 = (((v8 * v6) & m32) + v5) & m32 - pick = (v8 >> 16) % n_tris - v5 = (((v10 * v8) & m32) + v6) & m32 - v6 = (((v5 * v10) & m32) + v7) & m32 - tri = pick - rid = tri_region[pick] - if rid != 0 and rid in blocked: - culled = True - continue - culled = False - v20 = v5 >> 8 - u = (v6 & m24) * (2.0 ** -24) - p = struct.unpack("> 12 - x2 ^= x2 >> 12 - x1 = (((k & m24) * (x2 & m24)) + x1) & m32 - a = (x1 & m24) ^ (x1 >> 12) - x1 = (((k & m24) * (x1 & m24)) + x2) & m32 - b = (x1 & m24) ^ (x1 >> 12) - u1 = a * (2.0 ** -24) - u2 = b * (2.0 ** -24) - r = math.sqrt(u1) - return tri, culled, seed, (1.0 - r, (1.0 - u2) * r, u2 * r) - - -class ParsingTests(unittest.TestCase): - def test_system_page_signature_validation(self): - sysd, _ = build_synthetic_groom_buffers() - self.assertTrue(smh_groom.system_page_is_groom(sysd)) - - # Too short - self.assertFalse(smh_groom.system_page_is_groom(sysd[:0xDF])) - # Non-zero vtable prefix - bad_prefix = bytearray(sysd) - bad_prefix[0] = 1 - self.assertFalse(smh_groom.system_page_is_groom(bad_prefix)) - # Wrong TYPE_ID - bad_type = bytearray(sysd) - struct.pack_into(" 0) - self.assertEqual(groom.tail, b"\x01\x02\x03\x04\x05\x06\x07\x08") - self.assertAlmostEqual(groom.length_random[0], 0.5, places=3) - self.assertAlmostEqual(groom.length_random[1], 0.4, places=3) - - # Normalized bone weights sum to 1.0 (192/256 = 0.75, 64/256 = 0.25). - bw = groom.bone_weights() - self.assertEqual(len(bw), 4) - self.assertAlmostEqual(bw[0][0], 0.75, places=5) - self.assertAlmostEqual(bw[0][1], 0.25, places=5) - self.assertAlmostEqual(sum(bw[0]), 1.0, places=5) - - summary = groom.summary() - self.assertEqual(summary["guides"], 4) - self.assertEqual(summary["tailBytes"], 8) - self.assertTrue(summary["hasExt3c"]) - self.assertLess(summary["storedLengthMaxErrorM"], 0.001) - self.assertIn("ext_18", summary["optionalArrays"]) - self.assertIn("direction", summary["optionalArrays"]) - self.assertIn("node_4", summary["optionalArrays"]) - self.assertIn("node_2", summary["optionalArrays"]) - - def test_parse_standalone_gpu_buffer_without_system_page(self): - _, gpu = build_synthetic_groom_buffers(include_optional=False) - groom = smh_groom.parse(None, gpu, archive="raw.smh", offset=0) - self.assertEqual(groom.system, b"") - self.assertEqual(groom.strand_totals, (24, 8)) - self.assertIsNone(groom.style_preset_hash) - self.assertIsNone(groom.part_class_hash) - self.assertIsNone(groom.part_class) - self.assertFalse(groom.has_unset_rig_floats) - self.assertIsNone(groom.style_params) - self.assertAlmostEqual(groom.box[0][0], -0.05, places=2) - self.assertAlmostEqual(groom.box[1][2], 0.82, places=2) - - def test_system_page_metadata_hashes_and_part_class_mapping(self): - for part_hash, expected_name in smh_groom.PART_CLASS_NAMES.items(): - with self.subTest(part_hash=hex(part_hash), expected=expected_name): - hashes = ( - smh_groom.SKEL_HEAD_HASH, - smh_groom.UNUSED_HASH_FILL, - smh_groom.UNUSED_HASH_FILL, - smh_groom.UNUSED_HASH_FILL, - 0x74792000, - part_hash, - ) - sysd, gpu = build_synthetic_groom_buffers(style_hashes=hashes) - parsed_sys = smh_groom.parse_system_page(sysd) - self.assertEqual(parsed_sys["slot_bone_hashes"], hashes[:4]) - self.assertEqual(parsed_sys["style_preset_hash"], 0x74792000) - self.assertEqual(parsed_sys["part_class_hash"], part_hash) - self.assertEqual(parsed_sys["part_class"], expected_name) - - groom = smh_groom.parse(sysd, gpu) - self.assertEqual(groom.style_preset_hash, 0x74792000) - self.assertEqual(groom.part_class_hash, part_hash) - self.assertEqual(groom.part_class, expected_name) - summary = groom.summary() - self.assertEqual(summary["stylePresetHash"], "0x74792000") - self.assertEqual(summary["partClassHash"], hex(part_hash)) - self.assertEqual(summary["partClass"], expected_name) - - # Unmapped slot 5 hash leaves part_class as None while preserving raw hash. - sysd_unk, gpu_unk = build_synthetic_groom_buffers( - style_hashes=(smh_groom.SKEL_HEAD_HASH, 0x89EA2ED6, 0x89EA2ED6, 0x89EA2ED6, 0x12345678, 0xDEADBEEF), - ) - groom_unk = smh_groom.parse(sysd_unk, gpu_unk) - self.assertEqual(groom_unk.style_preset_hash, 0x12345678) - self.assertEqual(groom_unk.part_class_hash, 0xDEADBEEF) - self.assertIsNone(groom_unk.part_class) - - def test_system_page_unset_child_rig_floats(self): - sysd_adult, gpu_adult = build_synthetic_groom_buffers(unset_rig_floats=False) - groom_adult = smh_groom.parse(sysd_adult, gpu_adult) - self.assertFalse(groom_adult.has_unset_rig_floats) - self.assertFalse(groom_adult.summary()["hasUnsetRigFloats"]) - - sysd_child, gpu_child = build_synthetic_groom_buffers(unset_rig_floats=True) - parsed_child = smh_groom.parse_system_page(sysd_child) - self.assertTrue(parsed_child["has_unset_rig_floats"]) - groom_child = smh_groom.parse(sysd_child, gpu_child) - self.assertTrue(groom_child.has_unset_rig_floats) - self.assertTrue(groom_child.summary()["hasUnsetRigFloats"]) - - def test_system_page_half_float_style_parameters(self): - style_f16 = { - 0xE8: 0.1, # strand width - 0xEA: 0.28, # longest guide (m) - 0xEE: 0.28, # longest guide copy (m) - 0xF0: 0.75, # braid-correlated parameter - 0xF8: 0.1, # curl/frizz block 0: amount 0 - 0xFA: 0.05, # amount 1 - 0xFC: 0.003, # radius 0 (m) - 0xFE: 0.004, # radius 1 (m) - 0x100: 12.75, # frequency 0 (/m) - 0x102: 61.0, # frequency 1 (/m) - 0x104: 0.08, # curl/frizz block 1: amount 0 - 0x106: 0.02, # amount 1 - 0x108: 0.003, # radius 0 (m) - 0x10A: 0.0007, # radius 1 (m, curly-correlated) - 0x10C: 70.0, # frequency 0 (/m) - 0x10E: 74.5, # frequency 1 (/m) - } - sysd, gpu = build_synthetic_groom_buffers(style_params_f16=style_f16) - groom = smh_groom.parse(sysd, gpu) - sp = groom.style_params - self.assertIsNotNone(sp) - self.assertAlmostEqual(sp["strandWidth"], 0.1, places=3) - self.assertAlmostEqual(sp["longestGuideM"], 0.28, places=3) - self.assertAlmostEqual(sp["longestGuideAltM"], 0.28, places=3) - self.assertAlmostEqual(sp["braidParam"], 0.75, places=3) - self.assertAlmostEqual(sp["curlFrizz0"]["amounts"][0], 0.1, places=3) - self.assertAlmostEqual(sp["curlFrizz0"]["amounts"][1], 0.05, places=3) - self.assertAlmostEqual(sp["curlFrizz0"]["radiiM"][0], 0.003, places=4) - self.assertAlmostEqual(sp["curlFrizz0"]["radiiM"][1], 0.004, places=4) - self.assertAlmostEqual(sp["curlFrizz0"]["frequenciesPerM"][0], 12.75, places=2) - self.assertAlmostEqual(sp["curlFrizz0"]["frequenciesPerM"][1], 61.0, places=2) - self.assertAlmostEqual(sp["curlFrizz1"]["amounts"][0], 0.08, places=3) - self.assertAlmostEqual(sp["curlFrizz1"]["amounts"][1], 0.02, places=3) - self.assertAlmostEqual(sp["curlFrizz1"]["radiiM"][0], 0.003, places=4) - self.assertAlmostEqual(sp["curlFrizz1"]["radiiM"][1], 0.0007, places=4) - self.assertAlmostEqual(sp["curlFrizz1"]["frequenciesPerM"][0], 70.0, places=1) - self.assertAlmostEqual(sp["curlFrizz1"]["frequenciesPerM"][1], 74.5, places=1) - - # Non-finite half-float (NaN = 0x7E00) decodes cleanly as None without crashing. - mut_nan = bytearray(sysd) - struct.pack_into("= split for o in right)) - self.assertEqual(left + right, [off1, off2]) - - # memoryview inputs work identically to bytes/bytearray (contiguous byte, typed, 2D, empty, and strided). - self.assertEqual(list(smh_groom.scan_offsets(memoryview(raw), chunk=73)), [off1, off2]) - - padded = raw + bytes((-len(raw)) % 4) - for fmt in ("B", "h", "I"): - with self.subTest(memoryview_fmt=fmt): - self.assertEqual(list(smh_groom.scan_offsets(memoryview(padded).cast(fmt), chunk=73)), [off1, off2]) - self.assertEqual( - list(smh_groom.scan_offsets(memoryview(padded).cast("B", shape=(2, len(padded) // 2)), chunk=73)), - [off1, off2], - ) - self.assertEqual(list(smh_groom.scan_offsets(memoryview(b"").cast("I"))), []) - - strided_buf = bytearray(2 * len(raw)) - strided_buf[::2] = raw - strided_view = memoryview(strided_buf)[::2] - self.assertEqual(list(smh_groom.scan_offsets(strided_view, chunk=73)), [off1, off2]) - - strided_u32_buf = bytearray(2 * len(padded)) - mv_u32 = memoryview(strided_u32_buf).cast("I") - mv_u32[::2] = memoryview(padded).cast("I") - self.assertEqual(list(smh_groom.scan_offsets(mv_u32[::2], chunk=73)), [off1, off2]) - - # A resource at a misaligned offset is never yielded, even when chunk alignment places it at block offset 0. - misaligned = b"9FPR" + b"\xAB" * 0x40 + res1 - self.assertEqual(list(smh_groom.scan_offsets(misaligned, chunk=0x44)), []) - - # Non-positive chunk sizes are rejected with GroomError. - for bad_chunk in (0, -16, False): - with self.subTest(bad_chunk=bad_chunk): - with self.assertRaises(smh_groom.GroomError): - list(smh_groom.scan_offsets(raw, chunk=bad_chunk)) - - def test_load_groom_all_file_formats(self): - sysd, gpu = build_synthetic_groom_buffers() - native = pack_native_resource(sysd, gpu) - raw_zlib = native[16:] - rpf_like = b"9FPR" + b"\x00" * 0x3C + native - - with tempfile.TemporaryDirectory() as tmp: - for name, payload in ( - ("native.smh", native), - ("zlib.smh", raw_zlib), - ("gpu.smh", gpu), - ("pack.rpf", rpf_like), - ): - p = os.path.join(tmp, name) - with open(p, "wb") as f: - f.write(payload) - g = smh_groom.load_groom(p) - self.assertEqual(g.guides, 4, name) - self.assertEqual(g.triangles_n, 2, name) - - # Explicit offset into archive. - g_off = smh_groom.load_groom(os.path.join(tmp, "pack.rpf"), offset=0x40) - self.assertEqual(g_off.offset, 0x40) - - def test_group_lod_chains_contiguous_and_split(self): - box = ((-0.1, -0.1, 0.6), (0.1, 0.1, 0.85)) - other_box = ((-0.1, -0.1, 0.3), (0.1, 0.1, 0.45)) - - def row(off, guides, s0=1000, s1=200, b=box, ppg=8, flags=0x443): - return {"offset": off, "guides": guides, "ppg": ppg, "flags": flags, "s0": s0, "s1": s1, "box": b, "error": None} - - # Asset A is split around Asset B: A_lod0, B_lod0, B_lod1, A_lod1, A_lod2 - rows = [ - row(0x100, 120, b=box), - row(0x200, 60, s0=500, s1=100, b=other_box), - row(0x300, 36, s0=500, s1=100, b=other_box), - row(0x400, 72, b=box), - row(0x500, 44, b=box), - ] - chains = smh_groom.group_lod_chains(rows) - self.assertEqual(len(chains), 2) - self.assertEqual([r["guides"] for r in chains[0]], [120, 72, 44]) - self.assertEqual([r["guides"] for r in chains[1]], [60, 36]) - - -class RngAndInterpolationTests(unittest.TestCase): - def test_mul24_and_pcg_exact_vectors(self): - # Top 8 bits are ignored by v_mad_u32_u24. - self.assertEqual(smh_groom.mul24(0xFF000003, 0xAA000005), 15) - self.assertEqual(smh_groom.mul24(0xFFFFFF, 0xFFFFFF), (0xFFFFFF * 0xFFFFFF) & 0xFFFFFFFF) - - # Verify PCG bit-exactness and [0, 1) range. - for state in (0, 1, 0x12345678, 0xDEADBEEF, 0xFFFFFFFF): - v = (state * 0x2C9277B5 + 0xAC564B05) & 0xFFFFFFFF - w = (((v >> ((v >> 28) + 4)) ^ v) * 0x108EF2D9) & 0xFFFFFFFF - expected_u24 = ((w >> 22) ^ (w & 0xFFFFFF)) & 0xFFFFFFFF - self.assertEqual(smh_groom.pcg_u24(state), expected_u24) - f = smh_groom.pcg_float(state) - self.assertGreaterEqual(f, 0.0) - self.assertLess(f, 1.0) - self.assertEqual(f, expected_u24 * (2.0 ** -24)) - - def test_class0_scatter_matches_independent_reference_bit_for_bit(self): - sysd, gpu = build_synthetic_groom_buffers( - triangles=[(0, 1, 2), (0, 2, 3), (1, 2, 3)], - tri_count=[(30, 5, 0, 0), (10, 2, 0, 0), (50, 8, 0, 0)], - tri_region=[0, 1, 2], - seeds=(0x5EED1234, 0xCAFEBABE), - ) - groom = smh_groom.parse(sysd, gpu) - ds = 1.0 / 50.0 - res = smh_groom.scatter(groom, count=64, strand_class=0, density_scale=ds, region_mask={1}) - res2 = smh_groom.scatter(groom, count=64, strand_class=0, density_scale=ds, region_mask={1}) - self.assertEqual(res, res2) - - per_tri = [30, 10, 50] - for t in range(64): - e_tri, e_culled, e_seed, e_bary = _reference_scatter_one( - t, 3, per_tri, bytes([0, 1, 2]), ds, {1}, 0x5EED1234, - ) - self.assertEqual(res["tri"][t], e_tri) - self.assertEqual(res["culled"][t], e_culled) - self.assertEqual(res["seed"][t], e_seed) - for c in range(3): - self.assertAlmostEqual(res["bary"][t][c], e_bary[c], places=7) - self.assertAlmostEqual(sum(res["bary"][t]), 1.0, places=6) - self.assertTrue(all(w >= -1e-7 for w in res["bary"][t])) - - def test_region_zero_is_never_culled(self): - sysd, gpu = build_synthetic_groom_buffers(tri_region=[0, 0]) - groom = smh_groom.parse(sysd, gpu) - res = smh_groom.scatter(groom, count=32, strand_class=0, region_mask={0}) - self.assertFalse(any(res["culled"])) - - # Masking the only non-zero region culls every strand. - sysd2, gpu2 = build_synthetic_groom_buffers(tri_region=[7, 7]) - groom2 = smh_groom.parse(sysd2, gpu2) - res2 = smh_groom.scatter(groom2, count=32, strand_class=0, region_mask={7}) - self.assertTrue(all(res2["culled"])) - - def test_strand_interpolation_and_length_trimming(self): - # Full-length strands (length_random = (0.0, 1.0)): exact barycentric blend. - sysd, gpu = build_synthetic_groom_buffers(length_random=(0.0, 1.0)) - groom = smh_groom.parse(sysd, gpu) - out = smh_groom.generate_strands(groom, count=40, strand_class=0) - self.assertEqual(len(out["points"]), 40) - for i in range(40): - tri = out["tri"][i] - b0, b1, b2 = out["bary"][i] - g0, g1, g2 = groom.triangles[tri] - for k in range(groom.nodes_per_guide): - ex = b0 * groom.positions[g0][k][0] + b1 * groom.positions[g1][k][0] + b2 * groom.positions[g2][k][0] - ey = b0 * groom.positions[g0][k][1] + b1 * groom.positions[g1][k][1] + b2 * groom.positions[g2][k][1] - ez = b0 * groom.positions[g0][k][2] + b1 * groom.positions[g1][k][2] + b2 * groom.positions[g2][k][2] - px, py, pz = out["points"][i][k] - self.assertAlmostEqual(px, ex, places=4) - self.assertAlmostEqual(py, ey, places=4) - self.assertAlmostEqual(pz, ez, places=4) - eu = b0 * groom.uvs[g0][0] + b1 * groom.uvs[g1][0] + b2 * groom.uvs[g2][0] - ev = b0 * groom.uvs[g0][1] + b1 * groom.uvs[g1][1] + b2 * groom.uvs[g2][1] - self.assertAlmostEqual(out["uv"][i][0], eu, places=5) - self.assertAlmostEqual(out["uv"][i][1], ev, places=5) - self.assertEqual(out["live"][i], groom.nodes_per_guide) - self.assertAlmostEqual(out["length"][i], 0.12, places=3) - - # Trimmed strands (length_random = (1.0, 0.25)): lengths fall in [0.03, 0.12], - # and trimmed strands repeat their tip node. - sysd_t, gpu_t = build_synthetic_groom_buffers(length_random=(1.0, 0.25)) - groom_t = smh_groom.parse(sysd_t, gpu_t) - trimmed = smh_groom.generate_strands(groom_t, count=80, strand_class=0) - saw_trimmed = False - for i in range(80): - self.assertGreaterEqual(trimmed["length"][i], 0.029) - self.assertLessEqual(trimmed["length"][i], 0.121) - live = trimmed["live"][i] - self.assertGreaterEqual(live, 2) - self.assertLessEqual(live, groom_t.nodes_per_guide) - if live < groom_t.nodes_per_guide: - saw_trimmed = True - tip = trimmed["points"][i][live - 1] - for tail_k in range(live, groom_t.nodes_per_guide): - self.assertEqual(trimmed["points"][i][tail_k], tip) - self.assertTrue(saw_trimmed, "expected at least one trimmed strand") - - # max_strands returns exact prefix. - capped = smh_groom.generate_strands(groom_t, count=80, strand_class=0, max_strands=10) - self.assertEqual(len(capped["points"]), 10) - self.assertEqual(capped["points"], trimmed["points"][:10]) - self.assertEqual(capped["live"], trimmed["live"][:10]) - - def test_scatter_max_accepted_skips_culled_and_matches_full(self): - # 10 triangles where 9 are in blocked region 1 and 1 is in unblocked region 2, - # ensuring early candidates are culled before reaching 1 or 5 accepted strands. - triangles = [(0, 1, 2), (0, 2, 3)] * 5 - tri_count = [(20, 4, 0, 0)] * 10 - tri_region = [1] * 9 + [2] - sysd, gpu = build_synthetic_groom_buffers( - triangles=triangles, - tri_count=tri_count, - tri_region=tri_region, - length_random=(0.5, 0.4), - seeds=(0x5EED1234, 0xCAFEBABE), - ) - groom = smh_groom.parse(sysd, gpu) - - # Non-positive max_accepted returns empty lists immediately. - for cap in (0, -1): - empty = smh_groom.scatter(groom, count=500, strand_class=0, region_mask={1}, max_accepted=cap) - self.assertEqual(empty, {"tri": [], "culled": [], "bary": [], "seed": []}) - - full = smh_groom.scatter(groom, count=500, strand_class=0, region_mask={1}) - self.assertEqual(len(full["tri"]), 500) - accepted_idx = [i for i, c in enumerate(full["culled"]) if not c] - self.assertGreaterEqual(len(accepted_idx), 5) - self.assertGreater(accepted_idx[0], 0, "expected at least one culled candidate before first accepted") - self.assertGreater(accepted_idx[4], 4, "expected culled candidates before fifth accepted") - - original_scatter = smh_groom.scatter - for limit in (1, 5): - with self.subTest(max_accepted=limit): - capped_roots = smh_groom.scatter( - groom, count=500, strand_class=0, region_mask={1}, max_accepted=limit, - ) - expected_idx = accepted_idx[:limit] - for key in ("tri", "culled", "bary", "seed"): - self.assertEqual(len(capped_roots[key]), limit) - self.assertFalse(any(capped_roots["culled"])) - self.assertEqual(capped_roots["tri"], [full["tri"][i] for i in expected_idx]) - self.assertEqual(capped_roots["bary"], [full["bary"][i] for i in expected_idx]) - self.assertEqual(capped_roots["seed"], [full["seed"][i] for i in expected_idx]) - - fast_strands = smh_groom.generate_strands( - groom, count=500, strand_class=0, region_mask={1}, max_strands=limit, - ) - with mock.patch.object( - smh_groom, - "scatter", - lambda g, c, sc, ds, rm, _ma=None: original_scatter(g, c, sc, ds, rm, None), - ): - full_strands = smh_groom.generate_strands( - groom, count=500, strand_class=0, region_mask={1}, max_strands=limit, - ) - self.assertEqual(fast_strands, full_strands) - - # When max_accepted exceeds total accepted, all accepted roots are returned in order. - all_accepted = smh_groom.scatter( - groom, count=500, strand_class=0, region_mask={1}, max_accepted=10000, - ) - self.assertEqual(len(all_accepted["tri"]), len(accepted_idx)) - self.assertEqual(all_accepted["tri"], [full["tri"][i] for i in accepted_idx]) - - # When every region is masked, max_accepted returns empty lists without error. - none_accepted = smh_groom.scatter( - groom, count=500, strand_class=0, region_mask={1, 2}, max_accepted=5, - ) - self.assertEqual(none_accepted, {"tri": [], "culled": [], "bary": [], "seed": []}) - - -class GlbExportTests(unittest.TestCase): - def test_glb_export_all_geometry_modes(self): - sysd, gpu = build_synthetic_groom_buffers(length_random=(0.5, 0.4)) - groom = smh_groom.parse(sysd, gpu) - - expected_modes = { - "tubes": smh_groom.MODE_TRIANGLES, - "ribbons": smh_groom.MODE_TRIANGLES, - "curves": smh_groom.MODE_LINES, - "line-strip": smh_groom.MODE_LINE_STRIP, - } - for geom, expected_mode in expected_modes.items(): - with self.subTest(geometry=geom): - blob, meta = smh_groom.to_glb(groom, max_strands=12, geometry=geom) - self.assertTrue(blob.startswith(b"glTF")) - self.assertEqual(len(blob) % 4, 0) - parsed = glb_writer.read_glb_summary(blob) - self.assertEqual(parsed["version"], 2) - self.assertEqual(parsed["bin_bytes"] % 4, 0) - gltf = parsed["json"] - prims = gltf["meshes"][0]["primitives"] - self.assertGreaterEqual(len(prims), 3) - # First primitive is scalp triangles (mode 4). - self.assertEqual(prims[0]["mode"], smh_groom.MODE_TRIANGLES) - self.assertEqual(prims[0]["extras"]["shaderIndex"], 0) - self.assertIn("NORMAL", prims[0]["attributes"]) - # Subsequent primitives use the selected strand/guide mode. - for prim in prims[1:]: - self.assertEqual(prim["mode"], expected_mode) - if geom in ("tubes", "ribbons"): - self.assertIn("NORMAL", prim["attributes"]) - else: - self.assertNotIn("NORMAL", prim["attributes"]) - self.assertEqual(meta["geometry"], geom) - self.assertEqual(meta["strandsShown"][0], 12) - - def test_glb_curves_shorthand_and_y_up_conversion(self): - sysd, gpu = build_synthetic_groom_buffers() - groom = smh_groom.parse(sysd, gpu) - blob_z, _ = smh_groom.to_glb(groom, scalp=True, guides=False, classes=(), curves=True, up_axis="z") - blob_y, _ = smh_groom.to_glb(groom, scalp=True, guides=False, classes=(), curves=True, up_axis="y") - acc_z = glb_writer.read_glb_summary(blob_z)["json"]["accessors"][0] - acc_y = glb_writer.read_glb_summary(blob_y)["json"]["accessors"][0] - # RAGE root z=0.70 maps to glTF y=0.70 when up_axis="z", and stays z=0.70 when up_axis="y". - self.assertAlmostEqual(acc_z["min"][1], 0.70, places=2) - self.assertAlmostEqual(acc_y["min"][2], 0.70, places=2) - - def test_glb_nothing_to_export_raises(self): - sysd, gpu = build_synthetic_groom_buffers() - groom = smh_groom.parse(sysd, gpu) - with self.assertRaises(smh_groom.GroomError): - smh_groom.to_glb(groom, scalp=False, guides=False, classes=()) - - def test_glb_max_strands_early_stop_byte_identical_and_bounded_memory(self): - # 128 triangles x density 255 = 32,640 total candidates; max_strands=1 should - # produce a byte-identical GLB while keeping scatter allocations O(max_strands). - groom = smh_groom.parse( - *build_synthetic_groom_buffers( - triangles=[(0, 1, 2)] * 128, - tri_count=[(255, 0, 0, 0)] * 128, - ) - ) - self.assertEqual(groom.strand_totals[0], 32640) - - roots_capped = smh_groom.scatter(groom, count=32640, strand_class=0, max_accepted=1) - for key in ("tri", "culled", "bary", "seed"): - self.assertEqual(len(roots_capped[key]), 1) - - original_scatter = smh_groom.scatter - if not tracemalloc.is_tracing(): - gc.collect() - tracemalloc.start() - try: - blob_fast, meta_fast = smh_groom.to_glb( - groom, max_strands=1, classes=(0,), scalp=False, guides=False, geometry="curves", - ) - peak_fast = tracemalloc.get_traced_memory()[1] - finally: - tracemalloc.stop() - - gc.collect() - tracemalloc.start() - try: - with mock.patch.object( - smh_groom, - "scatter", - lambda g, c, sc, ds, rm, _ma=None: original_scatter(g, c, sc, ds, rm, None), - ): - blob_full, meta_full = smh_groom.to_glb( - groom, max_strands=1, classes=(0,), scalp=False, guides=False, geometry="curves", - ) - peak_full = tracemalloc.get_traced_memory()[1] - finally: - tracemalloc.stop() - - self.assertLess(peak_fast * 10, peak_full) - else: - blob_fast, meta_fast = smh_groom.to_glb( - groom, max_strands=1, classes=(0,), scalp=False, guides=False, geometry="curves", - ) - with mock.patch.object( - smh_groom, - "scatter", - lambda g, c, sc, ds, rm, _ma=None: original_scatter(g, c, sc, ds, rm, None), - ): - blob_full, meta_full = smh_groom.to_glb( - groom, max_strands=1, classes=(0,), scalp=False, guides=False, geometry="curves", - ) - - self.assertEqual(blob_fast, blob_full) - self.assertEqual(meta_fast, meta_full) - self.assertEqual(meta_fast["strandsShown"][0], 1) - self.assertEqual(meta_fast["strandTotals"][0], 32640) - - -class ErrorHandlingTests(unittest.TestCase): - def test_truncated_and_corrupt_buffers(self): - sysd, gpu = build_synthetic_groom_buffers() - - # Truncated header - with self.assertRaises(smh_groom.GroomError): - smh_groom.parse(sysd, gpu[:0x80]) - - # Inconsistent node count - bad_counts = bytearray(gpu) - struct.pack_into(" None: - if not SPIRV_VAL: - return - with tempfile.NamedTemporaryFile(suffix=".spv", delete=False) as f: - f.write(spv) - path = f.name - try: - r = subprocess.run( - [SPIRV_VAL, "--target-env", target_env, "--allow-offset-texture-operand", path], - capture_output=True, text=True, - ) - if r.returncode != 0: - raise AssertionError(f"spirv-val failed ({target_env}):\n{r.stderr}") - finally: - os.unlink(path) - - -class SpirvAsmUnitTests(unittest.TestCase): - def test_unicode_separators_remain_in_literal_strings(self): - literal = "first\u0085second\u2028third\u2029last" - expected = literal.encode("utf-8") + b"\x00" - expected += b"\x00" * (-len(expected) % 4) - for newline in ("\n", "\r\n", "\r"): - with self.subTest(newline=newline): - asm = f'%str = OpString "{literal}"{newline}OpNop{newline}' - spv = spirv_asm.assemble(asm) - words = _literal_words(spv, 7, 1) # OpString result ID precedes its literal. - self.assertEqual(struct.pack(f"<{len(words)}I", *words), expected) - - def test_literal_line_endings_preserve_bytes(self): - comment = '; An unmatched " in this comment is ordinary text.' - for ending in ("\r", "\r\n", "\n"): - with self.subTest(literal_ending=ending): - operand = f'first \\"; middle{ending}last' - expected = f'first "; middle{ending}last'.encode("utf-8") - asm = f'{comment}\r\n%str = OpString "{operand}"\r\nOpNop\r\n' - words = _literal_words(spirv_asm.assemble(asm), 7, 1) - self.assertEqual(struct.pack(f"<{len(words)}I", *words).split(b"\0", 1)[0], expected) - - def test_error_line_after_multiline_literal_is_physical_line(self): - asm = '; comment\r\n%str = OpString "first\rsecond\r\nthird\nlast"\r\nOpNotReal\n' - with self.assertRaisesRegex(spirv_asm.SpirvAsmError, r"line 6: unknown opcode"): - spirv_asm.assemble(asm) - - def test_cli_preserves_literal_crlf_in_source_file(self): - with tempfile.TemporaryDirectory() as directory: - src = os.path.join(directory, "literal.spvasm") - dst = os.path.join(directory, "literal.spv") - literal = b"first\r\nsecond" - with open(src, "wb") as f: - f.write(b'%str = OpString "' + literal + b'"\nOpNop\n') - result = subprocess.run([sys.executable, "-I", os.path.join(TOOLS, "spirv_asm.py"), src, "-o", dst], - capture_output=True, text=True) - self.assertEqual(result.returncode, 0, result.stderr) - with open(dst, "rb") as f: - words = _literal_words(f.read(), 7, 1) - self.assertEqual(struct.pack(f"<{len(words)}I", *words).split(b"\0", 1)[0], literal) - - def test_instruction_boundaries_follow_tokens_across_physical_lines(self): - canonical = ( - "OpCapability Shader\n" - "OpMemoryModel Logical GLSL450\n" - 'OpEntryPoint GLCompute %main "main"\n' - "OpExecutionMode %main LocalSize 1 1 1\n" - '%file = OpString "OpNop ; = %id"\n' - "%int = OpTypeInt 32 1\n" - "%pair = OpTypeStruct %int %int\n" - "%void = OpTypeVoid\n" - "%fn = OpTypeFunction %void\n" - "%main = OpFunction %void None %fn\n" - "%entry = OpLabel\n" - "OpNop\nOpReturn\nOpFunctionEnd\n" - ) - mixed = ( - "OpCapability Shader OpMemoryModel\r\nLogical GLSL450\n" - 'OpEntryPoint GLCompute %main "main" OpExecutionMode %main LocalSize 1 1 1\n' - '%file = OpString "OpNop ; = %id" %int\r=\nOpTypeInt 32 ; signedness follows\n1 ' - "%pair = OpTypeStruct %int\n%int\n" - "%void = OpTypeVoid %fn = OpTypeFunction %void\n" - "%main = OpFunction %void None\n%fn %entry = OpLabel\n" - "OpNop OpReturn OpFunctionEnd\n" - ) - assembled = spirv_asm.assemble(mixed) - self.assertEqual(assembled, spirv_asm.assemble(canonical)) - _validate(assembled) - - def test_prefixed_specialization_mnemonic_can_start_a_physical_line(self): - prefix = "%int = OpTypeInt 32 1\n%one = OpSpecConstant %int 1\n" - canonical = prefix + "%two = OpSpecConstantOp %int IAdd %one %one\nOpNop\n" - wrapped = prefix + "%two = OpSpecConstantOp %int\nOpIAdd %one\n%one OpNop\n" - self.assertEqual(spirv_asm.assemble(wrapped), spirv_asm.assemble(canonical)) - - def test_result_id_starts_instruction_on_its_physical_line(self): - text = '%str = OpString "first\r\nlast" %x\r=\nOpNotReal\n' - with self.assertRaisesRegex(spirv_asm.SpirvAsmError, r"line 2: unknown opcode"): - spirv_asm.assemble(text) - - def test_later_unterminated_literal_reports_its_physical_line(self): - text = '%str = OpString "first\rlast" %bad = OpString "unterminated' - with self.assertRaisesRegex(spirv_asm.SpirvAsmError, r"line 2: unterminated string"): - spirv_asm.assemble(text) - - def test_reject_repeated_type_result_ids(self): - declarations = ( - ("OpTypeInt 32 0", "OpTypeFloat 32"), - ("OpTypeBool", "OpTypeBool"), - ("OpTypeInt 32 0", "OpTypeBool"), - ("OpTypeBool", "OpTypeInt 32 0"), - ) - for first, second in declarations: - with self.subTest(first=first, second=second): - with self.assertRaisesRegex(spirv_asm.SpirvAsmError, r"line 2: type ID %t is already defined"): - spirv_asm.assemble(f"%t = {first}\n%t = {second}\n") - - def test_forward_pointer_can_be_completed_once(self): - declaration = "%node_ptr = OpTypePointer PhysicalStorageBuffer %node\n" - asm = ( - "OpCapability Shader\n" - "OpCapability PhysicalStorageBufferAddresses\n" - 'OpExtension "SPV_KHR_physical_storage_buffer"\n' - "OpMemoryModel PhysicalStorageBuffer64 GLSL450\n" - 'OpEntryPoint GLCompute %main "main"\n' - "OpExecutionMode %main LocalSize 1 1 1\n" - "OpTypeForwardPointer %node_ptr PhysicalStorageBuffer\n" - "%node = OpTypeStruct %node_ptr\n" - f"{declaration}" - "%void = OpTypeVoid\n" - "%fn = OpTypeFunction %void\n" - "%main = OpFunction %void None %fn\n" - "%entry = OpLabel\n" - "OpReturn\n" - "OpFunctionEnd\n" - ) - _validate(spirv_asm.assemble(asm)) - with self.assertRaisesRegex(spirv_asm.SpirvAsmError, r"line 10: type ID %node_ptr is already defined"): - spirv_asm.assemble(asm.replace(declaration, declaration * 2)) - - def test_assembler_leaves_non_type_redefinitions_to_validator(self): - for body in ( - "%t = OpTypeBool\n%t = OpUndef %uint\n", - "%t = OpUndef %uint\n%t = OpTypeBool\n", - "%t = OpConstant %uint 1\n%t = OpConstant %uint 2\n", - ): - with self.subTest(body=body): - self.assertTrue(spirv_asm.assemble("%uint = OpTypeInt 32 0\n" + body)) - - def test_header_and_target_env_versions(self): - asm = ( - "OpCapability Shader\n" - "OpMemoryModel Logical GLSL450\n" - 'OpEntryPoint GLCompute %main "main"\n' - "OpExecutionMode %main LocalSize 1 1 1\n" - "%void = OpTypeVoid\n" - "%fn = OpTypeFunction %void\n" - "%main = OpFunction %void None %fn\n" - "%entry = OpLabel\n" - "OpReturn\n" - "OpFunctionEnd\n" - ) - for env, expected_ver in ( - ("vulkan1.0", 0x00010000), - ("vulkan1.1", 0x00010300), - ("vulkan1.1spv1.4", 0x00010400), - ("vulkan1.2", 0x00010500), - ("vulkan1.3", 0x00010600), - ): - spv = spirv_asm.assemble(asm, target_env=env) - magic, ver, gen, bound, schema = struct.unpack_from("<5I", spv, 0) - self.assertEqual(magic, 0x07230203) - self.assertEqual(ver, expected_ver) - self.assertEqual(gen, 0) - self.assertGreater(bound, 1) - self.assertEqual(schema, 0) - _validate(spv, target_env=env) - - def test_constants_strings_bit_enums_and_control_flow(self): - # Exercises int32/int64/float32/float64/neg-zero/hex-float constants, GLSL.std.450 OpExtInst, - # BitEnum multi-flag ascending-bit parameter ordering (MemoryAccess Aligned|Nontemporal), - # OpSwitch, OpPhi, comments inside/outside lines, and escaped string literals. - asm = ( - "; leading comment\n" - "OpCapability Shader\n" - "OpCapability Int64\n" - "OpCapability Float64\n" - 'OpExtension "SPV_KHR_storage_buffer_storage_class"\n' - '%glsl = OpExtInstImport "GLSL.std.450" ; inline comment\n' - "OpMemoryModel Logical GLSL450\n" - 'OpEntryPoint GLCompute %main "main"\n' - "OpExecutionMode %main LocalSize 4 1 1\n" - '%str = OpString "hello; \\"world\\""\n' - "%void = OpTypeVoid\n" - "%fn = OpTypeFunction %void\n" - "%uint = OpTypeInt 32 0\n" - "%ulong = OpTypeInt 64 0\n" - "%float = OpTypeFloat 32\n" - "%double = OpTypeFloat 64\n" - "%ptr_fn_u = OpTypePointer Function %uint\n" - "%c0 = OpConstant %uint 0\n" - "%c1 = OpConstant %uint 1\n" - "%c_hex = OpConstant %uint 0xDEADBEEF\n" - "%c64 = OpConstant %ulong 0x1122334455667788\n" - "%fneg0 = OpConstant %float -0.0\n" - "%fhex = OpConstant %float 0x1.8p+0\n" - "%dval = OpConstant %double 3.5\n" - "%main = OpFunction %void None %fn\n" - "%entry = OpLabel\n" - "%var = OpVariable %ptr_fn_u Function\n" - "OpStore %var %c_hex Nontemporal|Aligned 4\n" - "%ld = OpLoad %uint %var Aligned|Nontemporal 4\n" - "%absf = OpExtInst %float %glsl FAbs %fneg0\n" - "%sumf = OpFAdd %float %absf %fhex\n" - "%sum64 = OpIAdd %ulong %c64 %c64\n" - "OpSelectionMerge %merge None\n" - "OpSwitch %ld %def 0 %case0 1 %case1\n" - "%case0 = OpLabel\n" - "OpBranch %merge\n" - "%case1 = OpLabel\n" - "OpBranch %merge\n" - "%def = OpLabel\n" - "OpBranch %merge\n" - "%merge = OpLabel\n" - "%phi = OpPhi %uint %c0 %case0 %c1 %case1 %ld %def\n" - "OpReturn\n" - "OpFunctionEnd\n" - ) - spv = spirv_asm.assemble(asm, target_env="vulkan1.2") - _validate(spv) - # Verify 64-bit constant words appear little-endian (lo32 then hi32) and -0.0 is 0x80000000. - words = struct.unpack(f"<{len(spv) // 4}I", spv) - self.assertIn(0x55667788, words) - self.assertIn(0x11223344, words) - self.assertIn(0x80000000, words) - self.assertIn(0x3FC00000, words) # 0x1.8p+0 = 1.5f - # A selector produced by a pure-ID instruction still needs its 64-bit result type. - asm64 = asm.replace("OpSwitch %ld %def 0 %case0 1 %case1", - "OpSwitch %sum64 %def 0 %case0 0x100000001 %case1") - spv64 = spirv_asm.assemble(asm64, target_env="vulkan1.2") - self.assertEqual(len(spv64), len(spv) + 8) # one extra word per case literal - _validate(spv64) - - def test_subword_integer_literals_use_the_declared_signedness(self) -> None: - for width, signed, token, expected in ( - (8, 1, "0x80", 0xFFFFFF80), - (16, 1, "0x8000", 0xFFFF8000), - (16, 1, "-32768", 0xFFFF8000), - (16, 0, "0x8000", 0x00008000), - ): - with self.subTest(width=width, signed=signed, token=token): - asm = f'''OpCapability Shader -OpCapability Int{width} -OpMemoryModel Logical GLSL450 -OpEntryPoint GLCompute %main "main" -OpExecutionMode %main LocalSize 1 1 1 -%void = OpTypeVoid -%fn = OpTypeFunction %void -%short = OpTypeInt {width} {signed} -%value = OpConstant %short {token} -%main = OpFunction %void None %fn -%entry = OpLabel -OpSelectionMerge %merge None -OpSwitch %value %merge {token} %case -%case = OpLabel -OpBranch %merge -%merge = OpLabel -OpReturn -OpFunctionEnd -''' - spv = spirv_asm.assemble(asm, target_env="vulkan1.2") - words = struct.unpack(f"<{len(spv) // 4}I", spv) - literals = {} - offset = 5 - while offset < len(words): - count, opcode = words[offset] >> 16, words[offset] & 0xFFFF - if opcode in (43, 251): # OpConstant, OpSwitch - literals[opcode] = words[offset + 3] - offset += count - self.assertEqual(literals, {43: expected, 251: expected}) - _validate(spv) - - def test_hex_float_inf_nan_and_string_escapes_match_spirv_as(self): - # Regression tests for PR #2251 review (@FreddyxS): - # 1) Width-aware hex-float Inf and NaN payload spellings (f16, f32, f64). - # 2) SPIRV-Tools string backslash decoding (\n -> literal 'n', not LF). - asm = ( - "OpCapability Shader\n" - "OpCapability Float16\n" - "OpCapability Float64\n" - "OpMemoryModel Logical GLSL450\n" - 'OpEntryPoint GLCompute %main "main"\n' - "OpExecutionMode %main LocalSize 1 1 1\n" - 'OpName %main "left\\nright"\n' - "%void = OpTypeVoid\n" - "%fn = OpTypeFunction %void\n" - "%f16 = OpTypeFloat 16\n" - "%f32 = OpTypeFloat 32\n" - "%f64 = OpTypeFloat 64\n" - "%h_inf = OpConstant %f16 0x1p+16\n" - "%h_nan = OpConstant %f16 0x1.8p+16\n" - "%f_inf = OpConstant %f32 0x1p+128\n" - "%f_ninf = OpConstant %f32 -0x1p+128\n" - "%f_nan = OpConstant %f32 0x1.8p+128\n" - "%d_inf = OpConstant %f64 0x1p+1024\n" - "%d_nan = OpConstant %f64 0x1.8p+1024\n" - "%main = OpFunction %void None %fn\n" - "%entry = OpLabel\n" - "OpReturn\n" - "OpFunctionEnd\n" - ) - spv = spirv_asm.assemble(asm, target_env="vulkan1.2") - _validate(spv) - words = struct.unpack(f"<{len(spv) // 4}I", spv) - self.assertIn(0x7C00, words) # f16 +Inf - self.assertIn(0x7E00, words) # f16 qNaN - self.assertIn(0x7F800000, words) # f32 +Inf - self.assertIn(0xFF800000, words) # f32 -Inf - self.assertIn(0x7FC00000, words) # f32 qNaN - self.assertIn(0x7FF00000, words) # f64 +Inf hi word - self.assertIn(0x7FF80000, words) # f64 qNaN hi word - # Verify exact byte-for-byte parity (excluding header generator word [2]) with spirv-as when present. - if SPIRV_AS: - with tempfile.TemporaryDirectory() as d: - sa, sv = os.path.join(d, "m.spvasm"), os.path.join(d, "m.spv") - with open(sa, "w", encoding="utf-8", newline="\n") as f: - f.write(asm) - subprocess.run([SPIRV_AS, sa, "-o", sv, "--target-env", "vulkan1.2"], check=True) - with open(sv, "rb") as f: - ref_words = struct.unpack(f"<{os.path.getsize(sv) // 4}I", f.read()) - self.assertEqual(len(words), len(ref_words)) - self.assertEqual(words[:2] + words[3:], ref_words[:2] + ref_words[3:]) - - def test_translated_shaders_validate_and_match_spirv_as(self): - # Translate diverse synthetic shaders (PS ALU/dot4/f16/branches, CS LDS/atomics/wave64-emulate) - # and verify every binary assembled by spirv_asm passes spirv-val. - ps_lines = [ - "v_mov_b32_e32 v1, 0x01020304", - "v_mov_b32_e32 v2, 0x05060708", - "v_mov_b32_e32 v3, 0x3f800000", - "v_dot4_i32_i8 v4, v1, v2, v3", - "v_add_f32_e32 v5, v3, 1.5", - "v_pk_add_f16 v6, v1, v2 op_sel:[0,1] op_sel_hi:[1,0]", - "exp mrt0 v4, v5, v6, v3 done vm", - "s_endpgm", - ] - spvasm = support.translate_lines("ps_spirv_asm_smoke", ps_lines) - spv = spirv_asm.assemble(spvasm, target_env="vulkan1.2") - _validate(spv) - # Also test a wave64-emulated compute shader (exercises OpControlBarrier, Workgroup arrays, loops, - # PhysicalStorageBuffer, OpAtomic*, OpSwitch/structured CF, Int64). - import json - cs_lines = [ - "s_load_dwordx2 s[4:5], s[0:1], 0x0", - "s_waitcnt lgkmcnt(0)", - "v_lshlrev_b32_e32 v1, 2, v0", - "ds_write_b32 v1, v0", - "s_waitcnt lgkmcnt(0)", - "s_barrier", - "ds_read_b32 v2, v1", - "s_waitcnt lgkmcnt(0)", - "v_cmp_lt_u32_e64 vcc, v0, 32", - "v_cndmask_b32_e64 v3, v2, v0, vcc", - "global_store_dword v1, v3, s[4:5]", - "s_endpgm", - ] - with tempfile.TemporaryDirectory() as d: - os.makedirs(os.path.join(d, "disasm")) - os.makedirs(os.path.join(d, "fspx")) - s_path = os.path.join(d, "disasm", "cs_spirv_asm_w64.s") - with open(s_path, "w", encoding="utf-8", newline="\n") as f: - f.write("; cs_spirv_asm_w64 code 0x0..0x100, gfx1013, 0 invalid words\n") - for ln in cs_lines: - f.write(f"\t{ln} ; encoding: [0x00,0x00,0x00,0x00]\n") - with open(os.path.join(d, "fspx", "cs_spirv_asm_w64.json"), "w", encoding="utf-8", newline="\n") as f: - json.dump({"rsrc2": (8 << 1) | (16 << 15), "threads": [64, 1, 1]}, f) - old_w64 = rdna2spirv.WAVE64_EMULATE - try: - rdna2spirv.WAVE64_EMULATE = True - cs_spvasm = rdna2spirv.translate(s_path) - finally: - rdna2spirv.WAVE64_EMULATE = old_w64 - cs_spv = spirv_asm.assemble(cs_spvasm, target_env="vulkan1.2") - _validate(cs_spv) - - def test_rdna2spirv_assembler_python_no_asm_skips_spvasm_file(self): - import json - with tempfile.TemporaryDirectory() as d: - os.makedirs(os.path.join(d, "disasm")) - os.makedirs(os.path.join(d, "fspx")) - s_path = os.path.join(d, "disasm", "cs_tiny.s") - out_dir = os.path.join(d, "out") - with open(s_path, "w", encoding="utf-8", newline="\n") as f: - f.write("; cs_tiny code 0x0..0x10, gfx1013, 0 invalid words\n") - f.write("\tv_mov_b32_e32 v0, 1.0 ; encoding: [0xf2,0x02,0x00,0x7e]\n") - f.write("\ts_endpgm ; encoding: [0x00,0x00,0x81,0xbf]\n") - with open(os.path.join(d, "fspx", "cs_tiny.json"), "w", encoding="utf-8", newline="\n") as f: - json.dump({"rsrc2": (4 << 1), "threads": [32, 1, 1]}, f) - if SPIRV_VAL: - r = subprocess.run( - [sys.executable, "-I", os.path.join(TOOLS, "rdna2spirv.py"), - s_path, "--out", out_dir, "--assembler", "python", "--no-asm"], - capture_output=True, text=True, - ) - self.assertEqual(r.returncode, 0, r.stderr + r.stdout) - self.assertTrue(os.path.isfile(os.path.join(out_dir, "cs_tiny.spv"))) - self.assertFalse(os.path.exists(os.path.join(out_dir, "cs_tiny.spvasm"))) - - def test_cli_and_error_cases(self): - with self.assertRaises(spirv_asm.SpirvAsmError): - spirv_asm.assemble("OpNotARealOpcode %x\n") - with self.assertRaises(spirv_asm.SpirvAsmError): - spirv_asm.assemble("OpTypeVoid\n") # missing result id - with self.assertRaises(spirv_asm.SpirvAsmError): - spirv_asm.assemble("%x = OpCapability Shader\n") # unexpected result id - with self.assertRaises(spirv_asm.SpirvAsmError): - spirv_asm.assemble('%s = OpString "unterminated\n') - with self.assertRaises(spirv_asm.SpirvAsmError): - spirv_asm.assemble("OpCapability NotACapability\n") - with self.assertRaises(spirv_asm.SpirvAsmError): - spirv_asm.assemble("OpCapability Shader\n", target_env="invalid") - - with tempfile.TemporaryDirectory() as d: - src = os.path.join(d, "min.spvasm") - dst = os.path.join(d, "min.spv") - with open(src, "w", encoding="utf-8", newline="\n") as f: - f.write( - "OpCapability Shader\nOpMemoryModel Logical GLSL450\n" - 'OpEntryPoint GLCompute %m "main"\nOpExecutionMode %m LocalSize 1 1 1\n' - "%v = OpTypeVoid\n%ft = OpTypeFunction %v\n%m = OpFunction %v None %ft\n" - "%l = OpLabel\nOpReturn\nOpFunctionEnd\n" - ) - rc = spirv_asm.main([src, "-o", dst, "--target-env", "vulkan1.2"]) - self.assertEqual(rc, 0) - with open(dst, "rb") as f: - _validate(f.read()) - - def test_invalid_id_spelling_in_results_and_references(self): - for identifier in ("%", "%bad-name", "%bad.name", "%\u0436"): - for line in (f"{identifier} = OpLabel", f"OpBranch {identifier}"): - with self.subTest(line=line): - with self.assertRaisesRegex(spirv_asm.SpirvAsmError, "line 2: invalid ID"): - spirv_asm.assemble(f"OpCapability Shader\n{line}\n") - - def test_cli_invalid_id_leaves_existing_output(self): - with tempfile.TemporaryDirectory() as d: - src = os.path.join(d, "bad.spvasm") - dst = os.path.join(d, "existing.spv") - with open(src, "w", encoding="utf-8", newline="\n") as f: - f.write("OpCapability Shader\n%bad.name = OpTypeVoid\n") - with open(dst, "wb") as f: - f.write(b"existing output") - result = subprocess.run([sys.executable, "-I", os.path.join(TOOLS, "spirv_asm.py"), src, "-o", dst], - capture_output=True, text=True) - self.assertEqual(result.returncode, 1, result.stderr) - self.assertIn("line 2: invalid ID", result.stderr) - self.assertEqual(len(result.stderr.splitlines()), 1) - with open(dst, "rb") as f: - self.assertEqual(f.read(), b"existing output") - - def test_cli_source_that_is_not_utf8_is_one_error_line(self): - with tempfile.TemporaryDirectory() as d: - src = os.path.join(d, "bad.spvasm") - dst = os.path.join(d, "bad.spv") - with open(src, "wb") as f: - f.write(b"OpCapability Shader\n; \xb1\xff\n") - r = subprocess.run([sys.executable, "-I", os.path.join(TOOLS, "spirv_asm.py"), src, "-o", dst], - capture_output=True, text=True) - self.assertEqual(r.returncode, 1, r.stderr) - self.assertNotIn("Traceback", r.stderr) - self.assertIn("ERROR:", r.stderr) - self.assertFalse(os.path.exists(dst)) - - -_INT_HEAD = ( - "OpCapability Shader\nOpCapability Int64\nOpCapability Int16\nOpCapability Int8\n" - "OpMemoryModel Logical GLSL450\n" - "%i8 = OpTypeInt 8 1\n%u8 = OpTypeInt 8 0\n%i16 = OpTypeInt 16 1\n%u16 = OpTypeInt 16 0\n" - "%i32 = OpTypeInt 32 1\n%u32 = OpTypeInt 32 0\n%i64 = OpTypeInt 64 1\n%u64 = OpTypeInt 64 0\n" -) - - -def _switch(sel_type, literal): - return (_INT_HEAD + "%void = OpTypeVoid\n%fn = OpTypeFunction %void\n" - f"%k = OpConstant %{sel_type} 0\n%f = OpFunction %void None %fn\n%l0 = OpLabel\n" - f"OpSelectionMerge %m None\nOpSwitch %k %m {literal} %l1\n%l1 = OpLabel\nOpBranch %m\n" - "%m = OpLabel\nOpReturn\nOpFunctionEnd\n") - - -# (SPIR-V text, words spirv-as gives for the literal, or None where spirv-as refuses it). Measured with the -# Vulkan SDK 1.4.363.1 spirv-as (BUILD-1012). -_INT_LITERAL_CASES = [] -for _t, _lit, _words in ( - ("u32", "4294967295", [0xFFFFFFFF]), ("u32", "4294967296", None), ("u32", "0x100000000", None), - ("u32", "-1", None), ("u32", "-0", None), ("u32", "+5", [5]), - ("i32", "-1", [0xFFFFFFFF]), ("i32", "2147483647", [0x7FFFFFFF]), ("i32", "2147483648", None), - ("i32", "-2147483648", [0x80000000]), ("i32", "-2147483649", None), ("i32", "0xFFFFFFFF", [0xFFFFFFFF]), - ("i32", "0x80000000", [0x80000000]), ("i32", "0x100000000", None), ("i32", "-0x1", [0xFFFFFFFF]), - ("u16", "65535", [0xFFFF]), ("u16", "65536", None), ("u16", "-1", None), ("u16", "0x10000", None), - ("i16", "-1", [0xFFFFFFFF]), ("i16", "32767", [0x7FFF]), ("i16", "32768", None), - ("i16", "-32768", [0xFFFF8000]), ("i16", "-32769", None), ("i16", "-0x8001", None), - ("i16", "0xFFFF", [0xFFFFFFFF]), ("i16", "0x8000", [0xFFFF8000]), ("i16", "0x10000", None), - ("u8", "255", [0xFF]), ("u8", "256", None), ("u8", "-1", None), - ("i8", "127", [0x7F]), ("i8", "128", None), ("i8", "-128", [0xFFFFFF80]), ("i8", "-129", None), - ("i8", "0xFF", [0xFFFFFFFF]), ("i8", "0x80", [0xFFFFFF80]), - # A signed hex literal (+0x...) is a value, not a bit pattern: it must fit the signed range (@mrbean56, #3931). - ("i16", "+0xFFFF", None), ("i16", "+0x8000", None), ("i16", "+0x7FFF", [0x7FFF]), ("i8", "+0x80", None), - ("i32", "+0xFFFFFFFF", None), ("i32", "+0x7FFFFFFF", [0x7FFFFFFF]), ("i64", "+0xFFFFFFFFFFFFFFFF", None), - ("u16", "+0xFFFF", [0xFFFF]), ("u32", "+0xFFFFFFFF", [0xFFFFFFFF]), - ("u64", "18446744073709551615", [0xFFFFFFFF, 0xFFFFFFFF]), ("u64", "18446744073709551616", None), - ("u64", "-1", None), - ("i64", "-1", [0xFFFFFFFF, 0xFFFFFFFF]), ("i64", "9223372036854775807", [0xFFFFFFFF, 0x7FFFFFFF]), - ("i64", "9223372036854775808", None), ("i64", "-9223372036854775809", None), - ("i64", "0xFFFFFFFFFFFFFFFF", [0xFFFFFFFF, 0xFFFFFFFF]), -): - _INT_LITERAL_CASES.append((f"OpConstant %{_t} {_lit}", _INT_HEAD + f"%c = OpConstant %{_t} {_lit}\n", _words)) -for _lit, _words in (("4294967295", [0xFFFFFFFF]), ("4294967296", None), ("-1", None)): - _INT_LITERAL_CASES.append((f"OpDecorate Location {_lit}", _INT_HEAD + f"OpDecorate %u32 Location {_lit}\n", - _words)) - _INT_LITERAL_CASES.append((f"OpGroupMemberDecorate {_lit}", - _INT_HEAD + f"%g = OpDecorationGroup\nOpGroupMemberDecorate %g %u32 {_lit}\n", - _words)) -for _t, _lit, _words in ( - ("u32", "4294967295", [0xFFFFFFFF]), ("u32", "4294967296", None), ("u32", "-1", None), - ("i32", "-1", [0xFFFFFFFF]), ("i32", "2147483648", None), - ("i16", "0xFFFF", [0xFFFFFFFF]), ("i16", "0x8000", [0xFFFF8000]), ("i16", "32768", None), - ("u16", "65536", None), ("i8", "0x80", [0xFFFFFF80]), - ("i32", "+0xFFFFFFFF", None), ("i16", "+0x8000", None), ("i32", "0xFFFFFFFF", [0xFFFFFFFF]), - ("u64", "18446744073709551615", [0xFFFFFFFF, 0xFFFFFFFF]), ("u64", "18446744073709551616", None), - ("u64", "-1", None), ("i64", "-1", [0xFFFFFFFF, 0xFFFFFFFF]), -): - _INT_LITERAL_CASES.append((f"OpSwitch %{_t} case {_lit}", _switch(_t, _lit), _words)) - - -def _literal_words(spv: bytes, opcode: int, skip: int): - """The words after the first `skip` operand words of the last instruction with `opcode` (the literal).""" - words = struct.unpack(f"<{len(spv) // 4}I", spv) - i, found = 5, None - while i < len(words): - n = words[i] >> 16 - if words[i] & 0xFFFF == opcode: - found = list(words[i + 1 + skip:i + n]) - i += n - return found - - -# opcode and leading operand words before the literal: OpConstant (result type, result), OpDecorate (target, -# decoration), OpGroupMemberDecorate (group, then the struct id the literal pairs with), OpSwitch (selector, -# default); a switch target label follows its literal. -_LITERAL_AT = {"OpConstant": (43, 2), "OpDecorate": (71, 2), "OpGroupMemberDecorate": (75, 2), "OpSwitch": (251, 2)} - - -class IntegerLiteralRangeTests(unittest.TestCase): - """BUILD-1012: an integer literal that doesn't fit its type is refused as spirv-as refuses it, not masked.""" - - def check_case(self, name, text, expected): - op = name.split()[0] - opcode, skip = _LITERAL_AT[op] - if expected is None: - with self.assertRaises(spirv_asm.SpirvAsmError): - spirv_asm.assemble(text) - return - got = _literal_words(spirv_asm.assemble(text), opcode, skip) - if op == "OpSwitch": - got = got[:-1] # the case's target label - self.assertEqual(got, expected) - - def test_literals_fit_their_type_or_are_refused(self): - for name, text, expected in _INT_LITERAL_CASES: - with self.subTest(name): - self.check_case(name, text, expected) - - def test_refusal_names_the_literal_and_the_type(self): - with self.assertRaisesRegex(spirv_asm.SpirvAsmError, - r"line 14: integer 4294967296 does not fit in a 32-bit unsigned integer"): - spirv_asm.assemble(_INT_HEAD + "%c = OpConstant %u32 4294967296\n") - with self.assertRaisesRegex(spirv_asm.SpirvAsmError, r"negative number in an unsigned literal: -1"): - spirv_asm.assemble(_INT_HEAD + "%c = OpConstant %u16 -1\n") - - @unittest.skipUnless(SPIRV_AS, "spirv-as not installed") - def test_cases_match_spirv_as(self): - with tempfile.TemporaryDirectory() as d: - src, dst = os.path.join(d, "m.spvasm"), os.path.join(d, "m.spv") - for name, text, expected in _INT_LITERAL_CASES: - with self.subTest(name): - with open(src, "w", encoding="utf-8", newline="\n") as f: - f.write(text) - r = subprocess.run([SPIRV_AS, src, "-o", dst, "--target-env", "vulkan1.2"], - capture_output=True, text=True) - if expected is None: - self.assertNotEqual(r.returncode, 0, f"spirv-as accepted {name}") - continue - self.assertEqual(r.returncode, 0, r.stderr) - with open(dst, "rb") as f: - ref = f.read() - got = spirv_asm.assemble(text) - a = struct.unpack(f"<{len(got) // 4}I", got) - b = struct.unpack(f"<{len(ref) // 4}I", ref) - self.assertEqual(a[:2] + a[3:], b[:2] + b[3:]) - - -def _selector_module(sel_type, literal, later): - """A compute shader with an OpSwitch on `%sel = OpIAdd %sel_type %c0 %c0`. - - `later` puts the block that defines `%sel` textually AFTER the block with the OpSwitch (the layout of SHADER-1089); - otherwise the definition comes first. spirv-as refuses the `later` layout ("The selector operand for OpSwitch must - be the result of an instruction that generates an integer scalar") and spirv-val refuses its block order ("Invalid - OpSwitch: selector id N has no type"): blocks must be laid out so that a block precedes every block it dominates. - """ - head = ( - "OpCapability Shader\nOpCapability Int64\nOpMemoryModel Logical GLSL450\n" - 'OpEntryPoint GLCompute %main "main"\nOpExecutionMode %main LocalSize 1 1 1\n' - "%void = OpTypeVoid\n%fn = OpTypeFunction %void\n%uint = OpTypeInt 32 0\n%ulong = OpTypeInt 64 0\n" - f"%c0 = OpConstant %{sel_type} 0\n%main = OpFunction %void None %fn\n%entry = OpLabel\n" - ) - define = f"%sel = OpIAdd %{sel_type} %c0 %c0\n" - switch = f"OpSelectionMerge %exit None\nOpSwitch %sel %exit {literal} %exit\n" - tail = "%exit = OpLabel\nOpReturn\nOpFunctionEnd\n" - if later: - return head + "OpBranch %dom\n%sw = OpLabel\n" + switch + "%dom = OpLabel\n" + define + "OpBranch %sw\n" + tail - return head + "OpBranch %dom\n%dom = OpLabel\n" + define + "OpBranch %sw\n%sw = OpLabel\n" + switch + tail - - -def _switch_instruction(spv: bytes): - """The words of the (only) OpSwitch instruction, its header word first.""" - words = struct.unpack(f"<{len(spv) // 4}I", spv) - i = 5 - while i < len(words): - n = words[i] >> 16 - if words[i] & 0xFFFF == 251: - return list(words[i:i + n]) - i += n - raise AssertionError("no OpSwitch in the module") - - -class SelectorMustBeDefinedBeforeTests(unittest.TestCase): - """SHADER-1089: an OpSwitch selector with no type yet is an error, not a silent 32-bit guess for the case literals.""" - - SELECTOR_ERROR = r"line \d+: OpSwitch selector %sel has no known type: it must be defined before the OpSwitch" - - def test_repro_with_a_64_bit_selector_defined_in_a_later_block_is_refused(self): - with self.assertRaisesRegex(spirv_asm.SpirvAsmError, self.SELECTOR_ERROR): # was five words (0x500fb) - spirv_asm.assemble(_selector_module("ulong", "1", later=True)) - - def test_literal_above_32_bits_with_a_later_selector_gives_the_same_error(self): - for literal in ("0x100000001", "4294967296", "0xFFFFFFFFFFFFFFFF"): # was an out-of-range error on a 32-bit guess - with self.subTest(literal=literal): - with self.assertRaisesRegex(spirv_asm.SpirvAsmError, self.SELECTOR_ERROR): - spirv_asm.assemble(_selector_module("ulong", literal, later=True)) - - def test_32_bit_selector_defined_later_is_refused_too(self): - with self.assertRaisesRegex(spirv_asm.SpirvAsmError, self.SELECTOR_ERROR): # was five words, silently - spirv_asm.assemble(_selector_module("uint", "1", later=True)) - - def test_selector_defined_nowhere_is_refused(self): - text = _selector_module("ulong", "1", later=False).replace("%sel = OpIAdd %ulong %c0 %c0\n", "") - with self.assertRaisesRegex(spirv_asm.SpirvAsmError, self.SELECTOR_ERROR): - spirv_asm.assemble(text) - - def test_the_error_names_the_line_of_the_switch(self): - text = _selector_module("ulong", "1", later=True) - switch_line = text.splitlines().index("OpSwitch %sel %exit 1 %exit") + 1 - with self.assertRaisesRegex(spirv_asm.SpirvAsmError, f"^line {switch_line}: OpSwitch selector %sel"): - spirv_asm.assemble(text) - - def test_selector_defined_before_is_unchanged_and_valid(self): - for sel_type, literal, length in (("ulong", "1", 6), ("ulong", "0x100000001", 6), ("uint", "1", 5)): - with self.subTest(sel_type=sel_type, literal=literal): - spv = spirv_asm.assemble(_selector_module(sel_type, literal, later=False)) - self.assertEqual(len(_switch_instruction(spv)), length) - _validate(spv) - - def test_selector_that_is_a_function_parameter_or_phi_or_load_is_typed(self): - head = ( - "OpCapability Shader\nOpCapability Int64\nOpMemoryModel Logical GLSL450\n" - 'OpEntryPoint GLCompute %main "main"\nOpExecutionMode %main LocalSize 1 1 1\n' - "%void = OpTypeVoid\n%ulong = OpTypeInt 64 0\n%fnp = OpTypeFunction %void %ulong\n%fn = OpTypeFunction %void\n" - "%ptr = OpTypePointer Function %ulong\n%c0 = OpConstant %ulong 0\n" - ) - param = (head + "%f = OpFunction %void None %fnp\n%p = OpFunctionParameter %ulong\n%e = OpLabel\n" - "OpSelectionMerge %x None\nOpSwitch %p %x 0x100000001 %x\n%x = OpLabel\nOpReturn\nOpFunctionEnd\n" - "%main = OpFunction %void None %fn\n%me = OpLabel\nOpReturn\nOpFunctionEnd\n") - self.assertEqual(len(_switch_instruction(spirv_asm.assemble(param))), 6) - load = (head + "%main = OpFunction %void None %fn\n%e = OpLabel\n%v = OpVariable %ptr Function\n" - "%sel = OpLoad %ulong %v\nOpSelectionMerge %x None\nOpSwitch %sel %x 0x100000001 %x\n" - "%x = OpLabel\nOpReturn\nOpFunctionEnd\n") - self.assertEqual(len(_switch_instruction(spirv_asm.assemble(load))), 6) - - -_FLOAT_HEAD = ( - "OpCapability Shader\nOpCapability Float16\nOpCapability Float64\nOpMemoryModel Logical GLSL450\n" - "%f16 = OpTypeFloat 16\n%f32 = OpTypeFloat 32\n%f64 = OpTypeFloat 64\n" -) - - -def _float_constant(type_name: str, literal: str) -> list[int]: - """The literal words of `%c = OpConstant % ` as spirv_asm encodes them.""" - spv = spirv_asm.assemble(_FLOAT_HEAD + f"%c = OpConstant %{type_name} {literal}\n") - return _literal_words(spv, 43, 2) - - -class FloatLiteralTests(unittest.TestCase): - """Float constant bits as SPIRV-Tools' HexFloat parser (source/util/hex_float.h) gives them.""" - - def _check(self, cases): - for type_name, literal, expected in cases: - with self.subTest(type=type_name, literal=literal): - self.assertEqual(_float_constant(type_name, literal), expected) - - def test_hex_float_digits_that_do_not_fit_are_truncated_toward_zero(self): - # old #4330 (@mrbean56): rounding to nearest gave the next value up for each of these. - self._check(( - ("f32", "0x1.0000018p0", [0x3F800000]), ("f32", "-0x1.0000018p0", [0xBF800000]), - ("f32", "0x1.fffffffp127", [0x7F7FFFFF]), ("f32", "0x1.8p-149", [0x00000001]), - ("f32", "0x1.8p-150", [0x00000000]), ("f32", "-0x1p-150", [0x80000000]), - ("f32", "0x1.8p+0", [0x3FC00000]), ("f32", "0x1p+128", [0x7F800000]), ("f32", "0x1p+129", [0x7F800000]), - ("f16", "0x1.003p0", [0x3C00]), ("f16", "0x1.ffep15", [0x7BFF]), ("f16", "0x1.8p-24", [0x0001]), - ("f64", "0x1.0000000000000cp0", [0x00000000, 0x3FF00000]), - ("f64", "0x1.fffffffffffff8p1023", [0xFFFFFFFF, 0x7FEFFFFF]), - )) - - def test_decimal_is_rounded_once_to_f32_and_f16_narrows_that_toward_zero(self): - # old #3911 (@lumenpearson): each of these decimals reads as a double on an f32 tie, which rounding the double - # again broke the wrong way; strtof rounds the decimal once. A 16-bit decimal is that f32 cut toward zero. - self._check(( - ("f32", "1.00000005960464477539062500000001", [0x3F800001]), - ("f32", "-1.00000005960464477539062500000001", [0xBF800001]), - ("f32", "1.000000059604644775390625", [0x3F800000]), - ("f32", "1.00000017881393432617187499999999", [0x3F800001]), - ("f32", "1.000000178813934326171875", [0x3F800002]), - ("f32", "7.00649232162408535461864791644958065640130970938257885878534141944895541342930300743319094181060791" - "015625000001e-46", [0x00000001]), - ("f32", "0.1", [0x3DCCCCCD]), ("f32", "3.4028235e38", [0x7F7FFFFF]), ("f32", "-0.0", [0x80000000]), - ("f16", "1.0006", [0x3C00]), ("f16", "-1.0006", [0xBC00]), ("f16", "65535", [0x7BFF]), - ("f16", "5e-8", [0x0000]), ("f16", "0.1", [0x2E66]), ("f16", "1.5", [0x3E00]), - ("f64", "0.1", [0x9999999A, 0x3FB99999]), - )) - - def test_decimal_that_overflows_or_is_not_finite_is_refused(self): - # old #4286: these were emitted as infinities (or NaN); spirv-as refuses each one. - for type_name, literal in ( - ("f64", "1e400"), ("f64", "-1e400"), ("f64", "1.8e308"), ("f32", "1e39"), ("f32", "-3.4028236e38"), - ("f16", "65536"), ("f16", "1e5"), ("f32", "inf"), ("f32", "-inf"), ("f64", "nan"), - ("f64", "infinity"), ("f32", "1_0"), - ): - with self.subTest(type=type_name, literal=literal): - with self.assertRaisesRegex(spirv_asm.SpirvAsmError, r"line 8: .*float literal"): - _float_constant(type_name, literal) - # Underflow is not an error: the value rounds to zero, as strtod gives it. - self._check(( - ("f64", "1.7976931348623157e308", [0xFFFFFFFF, 0x7FEFFFFF]), ("f64", "-1e-400", [0x00000000, 0x80000000]), - ("f32", "3.4028235e38", [0x7F7FFFFF]), ("f32", "1e-50", [0x00000000]), ("f16", "65504", [0x7BFF]), - ("f32", "1.", [0x3F800000]), ("f32", ".5", [0x3F000000]), ("f32", "+2E1", [0x41A00000]), - )) - - def test_bfloat16_constant_is_the_top_half_of_an_f32(self): - # old #4237: OpTypeFloat 16 BFloat16KHR constants were encoded as IEEE halves (1.5 was 0x3E00). - head = _FLOAT_HEAD + "%bf = OpTypeFloat 16 BFloat16KHR\n%bf0 = OpTypeFloat 16 0\n" - for type_name, literal, expected in ( - ("bf", "1.5", [0x3FC0]), ("bf", "-2", [0xC000]), ("bf", "0.1", [0x3DCC]), ("bf", "1.0078125", [0x3F81]), - ("bf", "1.00390625", [0x3F80]), ("bf", "3.4e38", [0x7F7F]), ("bf", "0x1.fep0", [0x3FFF]), - ("bf", "0x1.ffp0", [0x3FFF]), ("bf", "-0x1p+128", [0xFF80]), ("bf", "0x1.8p+128", [0x7FC0]), - ("bf0", "1.5", [0x3FC0]), ("f16", "1.5", [0x3E00]), - ): - with self.subTest(type=type_name, literal=literal): - spv = spirv_asm.assemble(head + f"%c = OpConstant %{type_name} {literal}\n") - self.assertEqual(_literal_words(spv, 43, 2), expected) - with self.assertRaisesRegex(spirv_asm.SpirvAsmError, r"line 10: .* 1e39 is out of range for a bfloat16"): - spirv_asm.assemble(head + "%c = OpConstant %bf 1e39\n") - - -class DebugPrintfTests(unittest.TestCase): - def test_debugprintf_by_name_as_spirv_dis_writes_it(self): - # old #4322: the instruction name spirv-dis prints for NonSemantic.DebugPrintf was refused as an integer. - def module(inst): - return ( - 'OpCapability Shader\nOpExtension "SPV_KHR_non_semantic_info"\n' - '%dp = OpExtInstImport "NonSemantic.DebugPrintf"\nOpMemoryModel Logical GLSL450\n' - 'OpEntryPoint GLCompute %main "main"\nOpExecutionMode %main LocalSize 1 1 1\n' - '%fmt = OpString "x=%u"\n%void = OpTypeVoid\n%fn = OpTypeFunction %void\n%uint = OpTypeInt 32 0\n' - '%u7 = OpConstant %uint 7\n%main = OpFunction %void None %fn\n%l = OpLabel\n' - f'%p = OpExtInst %void %dp {inst} %fmt %u7\nOpReturn\nOpFunctionEnd\n' - ) - spv = spirv_asm.assemble(module("DebugPrintf")) - self.assertEqual(spv, spirv_asm.assemble(module("1"))) - ext_inst = _literal_words(spv, 12, 0) - self.assertEqual(len(ext_inst), 6) # result type, result, set, instruction, format, one argument - self.assertEqual(ext_inst[3], 1) - _validate(spv) - with self.assertRaisesRegex(spirv_asm.SpirvAsmError, "invalid integer literal 'Printf'"): - spirv_asm.assemble(module("Printf")) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/test_spirv_asm_tables.py b/tests/test_spirv_asm_tables.py deleted file mode 100644 index abdd8534f..000000000 --- a/tests/test_spirv_asm_tables.py +++ /dev/null @@ -1,300 +0,0 @@ -"""Grammar-table integrity and binary-encoding round-trip tests for tools/spirv_asm_tables.py.""" -import os -import struct -import sys -import unittest - -ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) -TOOLS = os.path.join(ROOT, "tools") -if TOOLS not in sys.path: - sys.path.insert(0, TOOLS) - -import spirv_asm # noqa: E402 -from spirv_asm_tables import BIT_ENUMS, GLSL_STD_450, INSTRUCTIONS, VALUE_ENUMS # noqa: E402 - - -class InstructionsTableTests(unittest.TestCase): - def test_schema_and_non_empty(self): - self.assertGreater(len(INSTRUCTIONS), 300) - for name, spec in INSTRUCTIONS.items(): - self.assertIsInstance(name, str) - self.assertTrue(name.startswith("Op"), name) - self.assertIsInstance(spec, tuple, name) - self.assertEqual(len(spec), 4, name) - opcode, has_type, has_result, operands = spec - self.assertIsInstance(opcode, int, name) - self.assertTrue(0 <= opcode <= 0xFFFF, f"{name}: {opcode}") - self.assertIsInstance(has_type, bool, name) - self.assertIsInstance(has_result, bool, name) - self.assertIsInstance(operands, tuple, name) - for op_spec in operands: - self.assertIsInstance(op_spec, tuple, name) - self.assertEqual(len(op_spec), 2, name) - kind, quant = op_spec - self.assertIsInstance(kind, str, name) - self.assertIn(quant, ("", "?", "*"), f"{name}: {op_spec}") - - def test_core_opcodes_and_flags(self): - expected = { - "OpNop": (0, False, False), - "OpExtInst": (12, True, True), - "OpTypeInt": (21, False, True), - "OpTypeFloat": (22, False, True), - "OpConstant": (43, True, True), - "OpImageSampleExplicitLod": (88, True, True), - "OpImageSampleDrefExplicitLod": (90, True, True), - "OpImageDrefGather": (97, True, True), - } - for name, (opc, ht, hr) in expected.items(): - with self.subTest(op=name): - got_opc, got_ht, got_hr, _ = INSTRUCTIONS[name] - self.assertEqual((got_opc, got_ht, got_hr), (opc, ht, hr)) - - -class GlslExtTableTests(unittest.TestCase): - def test_schema_and_unique_opcodes(self): - self.assertGreater(len(GLSL_STD_450), 50) - seen = {} - for name, opc in GLSL_STD_450.items(): - self.assertIsInstance(name, str) - self.assertIsInstance(opc, int) - self.assertGreater(opc, 0) - self.assertNotIn(opc, seen, f"duplicate GLSL opcode {opc}: {name} vs {seen.get(opc)}") - seen[opc] = name - - def test_expected_glsl_opcodes(self): - expected = { - "RoundEven": 2, - "Trunc": 3, - "FAbs": 4, - "Floor": 8, - "Ceil": 9, - "Fract": 10, - "Sqrt": 31, - "InverseSqrt": 32, - "FMin": 37, - "FMax": 40, - "FClamp": 43, - "Fma": 50, - "PackHalf2x16": 58, - "UnpackHalf2x16": 62, - } - for name, opc in expected.items(): - with self.subTest(fn=name): - self.assertEqual(GLSL_STD_450[name], opc) - - -class EnumsTableTests(unittest.TestCase): - def test_value_enums_schema(self): - self.assertGreater(len(VALUE_ENUMS), 10) - for enum_name, members in VALUE_ENUMS.items(): - self.assertIsInstance(enum_name, str) - self.assertIsInstance(members, dict) - self.assertGreater(len(members), 0, enum_name) - for k, spec in members.items(): - self.assertIsInstance(k, str) - self.assertIsInstance(spec, tuple) - self.assertEqual(len(spec), 2) - val, extra = spec - self.assertIsInstance(val, int) - self.assertIsInstance(extra, tuple) - - def test_bit_enums_power_of_two_masks(self): - self.assertGreater(len(BIT_ENUMS), 5) - for enum_name, members in BIT_ENUMS.items(): - self.assertIsInstance(enum_name, str) - self.assertIsInstance(members, dict) - for k, spec in members.items(): - self.assertIsInstance(k, str) - self.assertIsInstance(spec, tuple) - self.assertEqual(len(spec), 2) - mask, extra = spec - self.assertIsInstance(mask, int) - self.assertGreaterEqual(mask, 0) - if mask != 0: - self.assertEqual(mask & (mask - 1), 0, f"{enum_name}.{k}: {mask:#x}") - self.assertIsInstance(extra, tuple) - - def test_image_operands_bit_flags_and_order(self): - img_ops = BIT_ENUMS["ImageOperands"] - expected = { - "None": (0, ()), - "Bias": (1, ("IdRef",)), - "Lod": (2, ("IdRef",)), - "Grad": (4, ("IdRef", "IdRef")), - "ConstOffset": (8, ("IdRef",)), - "Offset": (16, ("IdRef",)), - "ConstOffsets": (32, ("IdRef",)), - "Sample": (64, ("IdRef",)), - "MinLod": (128, ("IdRef",)), - "Offsets": (65536, ("IdRef",)), - } - for name, want in expected.items(): - with self.subTest(flag=name): - self.assertEqual(img_ops[name], want) - self.assertLess(img_ops["Grad"][0], img_ops["Offset"][0]) - self.assertLess(img_ops["Offset"][0], img_ops["MinLod"][0]) - - -# Every instruction alias in SPIRV-Headers' spirv.core.grammar.json (each instruction's "aliases"), alias -> opname. -# spirv-as accepts either spelling and writes the same words for both. -INSTRUCTION_ALIASES = { - "OpArbitraryFloatAddINTEL": "OpArbitraryFloatAddALTERA", - "OpArbitraryFloatCastFromIntINTEL": "OpArbitraryFloatCastFromIntALTERA", - "OpArbitraryFloatCastINTEL": "OpArbitraryFloatCastALTERA", - "OpArbitraryFloatCastToIntINTEL": "OpArbitraryFloatCastToIntALTERA", - "OpArbitraryFloatCbrtINTEL": "OpArbitraryFloatCbrtALTERA", - "OpArbitraryFloatDivINTEL": "OpArbitraryFloatDivALTERA", "OpArbitraryFloatEQINTEL": "OpArbitraryFloatEQALTERA", - "OpArbitraryFloatGEINTEL": "OpArbitraryFloatGEALTERA", "OpArbitraryFloatGTINTEL": "OpArbitraryFloatGTALTERA", - "OpArbitraryFloatHypotINTEL": "OpArbitraryFloatHypotALTERA", - "OpArbitraryFloatLEINTEL": "OpArbitraryFloatLEALTERA", "OpArbitraryFloatLTINTEL": "OpArbitraryFloatLTALTERA", - "OpArbitraryFloatMulINTEL": "OpArbitraryFloatMulALTERA", - "OpArbitraryFloatRSqrtINTEL": "OpArbitraryFloatRSqrtALTERA", - "OpArbitraryFloatRecipINTEL": "OpArbitraryFloatRecipALTERA", - "OpArbitraryFloatSinCosPiINTEL": "OpArbitraryFloatSinCosPiALTERA", - "OpArbitraryFloatSqrtINTEL": "OpArbitraryFloatSqrtALTERA", - "OpArbitraryFloatSubINTEL": "OpArbitraryFloatSubALTERA", - "OpControlBarrierArriveINTEL": "OpControlBarrierArriveEXT", - "OpControlBarrierWaitINTEL": "OpControlBarrierWaitEXT", - "OpCooperativeMatrixConvertNV": "OpCooperativeMatrixConvertUseEXT", - "OpCooperativeMatrixPerElementOpNV": "OpCooperativeMatrixPerElementOpEXT", - "OpCooperativeMatrixReduceNV": "OpCooperativeMatrixReduceEXT", - "OpCrossWorkgroupCastToPtrINTEL": "OpCrossWorkgroupCastToPtrALTERA", - "OpDecorateStringGOOGLE": "OpDecorateString", "OpDemoteToHelperInvocationEXT": "OpDemoteToHelperInvocation", - "OpFPGARegINTEL": "OpFPGARegALTERA", "OpFixedCosINTEL": "OpFixedCosALTERA", - "OpFixedCosPiINTEL": "OpFixedCosPiALTERA", "OpFixedExpINTEL": "OpFixedExpALTERA", - "OpFixedLogINTEL": "OpFixedLogALTERA", "OpFixedRecipINTEL": "OpFixedRecipALTERA", - "OpFixedRsqrtINTEL": "OpFixedRsqrtALTERA", "OpFixedSinCosINTEL": "OpFixedSinCosALTERA", - "OpFixedSinCosPiINTEL": "OpFixedSinCosPiALTERA", "OpFixedSinINTEL": "OpFixedSinALTERA", - "OpFixedSinPiINTEL": "OpFixedSinPiALTERA", "OpFixedSqrtINTEL": "OpFixedSqrtALTERA", - "OpGroupNonUniformPartitionNV": "OpGroupNonUniformPartitionEXT", - "OpMemberDecorateStringGOOGLE": "OpMemberDecorateString", - "OpPtrCastToCrossWorkgroupINTEL": "OpPtrCastToCrossWorkgroupALTERA", - "OpRayQueryGetClusterIdNV": "OpRayQueryGetIntersectionClusterIdNV", - "OpReadPipeBlockingINTEL": "OpReadPipeBlockingALTERA", "OpReportIntersectionNV": "OpReportIntersectionKHR", - "OpSDotAccSatKHR": "OpSDotAccSat", "OpSDotKHR": "OpSDot", "OpSUDotAccSatKHR": "OpSUDotAccSat", - "OpSUDotKHR": "OpSUDot", "OpTaskSequenceAsyncINTEL": "OpTaskSequenceAsyncALTERA", - "OpTaskSequenceCreateINTEL": "OpTaskSequenceCreateALTERA", "OpTaskSequenceGetINTEL": "OpTaskSequenceGetALTERA", - "OpTaskSequenceReleaseINTEL": "OpTaskSequenceReleaseALTERA", - "OpTypeAccelerationStructureNV": "OpTypeAccelerationStructureKHR", - "OpTypeCooperativeVectorNV": "OpTypeVectorIdEXT", "OpTypeTaskSequenceINTEL": "OpTypeTaskSequenceALTERA", - "OpUDotAccSatKHR": "OpUDotAccSat", "OpUDotKHR": "OpUDot", - "OpWritePipeBlockingINTEL": "OpWritePipeBlockingALTERA", -} - -ALIAS_MODULE = """ -OpCapability Shader -OpCapability DemoteToHelperInvocation -OpCapability DotProduct -OpCapability DotProductInput4x8BitPacked -OpExtension "SPV_GOOGLE_hlsl_functionality1" -OpExtension "SPV_GOOGLE_user_type" -OpMemoryModel Logical GLSL450 -OpEntryPoint Fragment %main "main" %target -OpExecutionMode %main OriginUpperLeft -OpDecorate %target Location 0 -OpDecorateStringGOOGLE %target UserSemantic "SV_Target0" -OpMemberDecorateStringGOOGLE %pair 0 UserSemantic "PAIR0" -%void = OpTypeVoid -%fn = OpTypeFunction %void -%int = OpTypeInt 32 1 -%uint = OpTypeInt 32 0 -%pair = OpTypeStruct %int -%out_int = OpTypePointer Output %int -%target = OpVariable %out_int Output -%a = OpConstant %uint 16909060 -%b = OpConstant %uint 84281096 -%main = OpFunction %void None %fn -%entry = OpLabel -%dot = OpSDotKHR %int %a %b PackedVectorFormat4x8Bit -OpStore %target %dot -OpDemoteToHelperInvocationEXT -OpReturn -OpFunctionEnd -""" - - -class InstructionAliasTests(unittest.TestCase): - def test_every_alias_has_its_canonical_entry(self): - for alias, canonical in INSTRUCTION_ALIASES.items(): - with self.subTest(alias=alias): - self.assertIn(alias, INSTRUCTIONS) - self.assertEqual(INSTRUCTIONS[alias], INSTRUCTIONS[canonical]) - - def test_alias_spellings_assemble_like_canonical_ones(self): - # The same module with each alias opname replaced by the instruction it names. - canonical = "\n".join(" ".join(INSTRUCTION_ALIASES.get(token, token) for token in line.split(" ")) - for line in ALIAS_MODULE.splitlines()) - for alias, opname in (("OpDecorateStringGOOGLE", "OpDecorateString"), - ("OpMemberDecorateStringGOOGLE", "OpMemberDecorateString"), - ("OpSDotKHR", "OpSDot"), - ("OpDemoteToHelperInvocationEXT", "OpDemoteToHelperInvocation")): - self.assertIn(alias, ALIAS_MODULE.split()) - self.assertNotIn(alias, canonical.split()) - self.assertIn(opname, canonical.split()) - self.assertEqual(spirv_asm.assemble(ALIAS_MODULE, target_env="vulkan1.3"), - spirv_asm.assemble(canonical, target_env="vulkan1.3")) - - -class AssembleRoundTripTests(unittest.TestCase): - def test_assemble_module_matches_table_opcodes(self): - asm = "\n".join( - [ - "OpCapability Shader", - '%glsl = OpExtInstImport "GLSL.std.450"', - "OpMemoryModel Logical GLSL450", - 'OpEntryPoint Fragment %main "main"', - "OpExecutionMode %main OriginUpperLeft", - "%void = OpTypeVoid", - "%fn_t = OpTypeFunction %void", - "%float = OpTypeFloat 32", - "%c_neg = OpConstant %float -2.5", - "%main = OpFunction %void None %fn_t", - "%entry = OpLabel", - "%res = OpExtInst %float %glsl FAbs %c_neg", - "OpReturn", - "OpFunctionEnd", - ] - ) - spv = spirv_asm.assemble(asm, target_env="vulkan1.2") - self.assertEqual(len(spv) % 4, 0) - words = struct.unpack(f"<{len(spv) // 4}I", spv) - self.assertEqual(words[0], spirv_asm.SPIRV_MAGIC) - self.assertEqual(words[1], spirv_asm.TARGET_ENV_VERSION["vulkan1.2"]) - self.assertGreater(words[3], 1) - self.assertEqual(words[4], 0) - - decoded = [] - idx = 5 - while idx < len(words): - header = words[idx] - wc = header >> 16 - opc = header & 0xFFFF - self.assertGreater(wc, 0) - decoded.append((opc, words[idx : idx + wc])) - idx += wc - self.assertEqual(idx, len(words)) - - expected_opcodes = [ - INSTRUCTIONS["OpCapability"][0], - INSTRUCTIONS["OpExtInstImport"][0], - INSTRUCTIONS["OpMemoryModel"][0], - INSTRUCTIONS["OpEntryPoint"][0], - INSTRUCTIONS["OpExecutionMode"][0], - INSTRUCTIONS["OpTypeVoid"][0], - INSTRUCTIONS["OpTypeFunction"][0], - INSTRUCTIONS["OpTypeFloat"][0], - INSTRUCTIONS["OpConstant"][0], - INSTRUCTIONS["OpFunction"][0], - INSTRUCTIONS["OpLabel"][0], - INSTRUCTIONS["OpExtInst"][0], - INSTRUCTIONS["OpReturn"][0], - INSTRUCTIONS["OpFunctionEnd"][0], - ] - self.assertEqual([opc for opc, _ in decoded], expected_opcodes) - ext_inst_words = decoded[11][1] - self.assertEqual(ext_inst_words[4], GLSL_STD_450["FAbs"]) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/test_spirv_gs_to_compute.py b/tests/test_spirv_gs_to_compute.py deleted file mode 100644 index 34d8b2b7e..000000000 --- a/tests/test_spirv_gs_to_compute.py +++ /dev/null @@ -1,440 +0,0 @@ -"""tools/spirv_gs_to_compute.py: a translated geometry shader as a compute capture pass (SHADER-159).""" -import json -import os -from pathlib import Path -import re -import shutil -import subprocess -import sys - -import pytest - -from conftest import HAVE_SPIRV, make_dxbc, requires_tools, signature_chunk - -ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) -sys.path.insert(0, os.path.join(ROOT, "tools")) -import spirv_gs_to_compute as gsc # noqa: E402 - -# gs_tri's signature, as scripts/run_gpu_tests.py builds it: SV_Position in register 0, TEXCOORD0 in register 1. -GS_DXBC = make_dxbc([signature_chunk(b"ISG1", [(0, 1, 0xF), (1, 0, 0xF)]), - signature_chunk(b"OSG1", [(0, 1, 0xF), (1, 0, 0xF)])]) - - -@pytest.fixture -def gs_tri(make_shader): - asm = open(os.path.join(ROOT, "runtime", "test", "shaders", "gs_tri.asm"), encoding="utf-8").read() - shader = make_shader(asm, name="gs_tri", dxbc=GS_DXBC) - spvasm = shader.translate() - assert "OpEntryPoint Geometry" in spvasm - return shader, spvasm - - -@requires_tools -def test_layout(gs_tri): - _, spvasm = gs_tri - _, lay = gsc.rewrite(spvasm) - assert lay == {"verts_in": 3, "max_verts": 3, "topology": "triangle_strip", - "inputs": ["position", "location 1"], "outputs": ["position", "location 1"], "local_size": 64} - - -@requires_tools -def test_compute_module(gs_tri): - shader, spvasm = gs_tri - out, _ = gsc.rewrite(spvasm) - assert "OpCapability Geometry" not in out - assert re.search(r"OpEntryPoint GLCompute %\w+ \"main\"", out) - assert re.search(r"OpExecutionMode %\w+ LocalSize 64 1 1", out) - assert "OpEmitVertex" not in out and "OpEndPrimitive" not in out - # no outputs are left, and the only inputs are GlobalInvocationId and the subgroup lane the GS already read - assert not re.search(r"OpVariable %\w+ Output\b", out) - inputs = re.findall(r"(%\w+) = OpVariable %\w+ Input\b", out) - builtins = {v: re.search(rf"OpDecorate {v} BuiltIn (\w+)", out).group(1) for v in inputs} - assert sorted(builtins.values()) == ["GlobalInvocationId", "SubgroupLocalInvocationId"] - # three emits, two outputs each, go to the record buffer - assert len(re.findall(r"OpAccessChain %gsc_ptr_sb_v4 %gsc_rec ", out)) == 6 - for b in (0, 1, 2): - assert f"Binding {b}" in out - shader.validate(out) # spirv-as + spirv-val, as for the translator's own output - - -@requires_tools -def test_rejects_non_geometry(make_shader): - shader = make_shader("v_mov_b32 v1, 1.0\ns_endpgm", name="cs_not_gs") - with pytest.raises(gsc.Unsupported): - gsc.rewrite(shader.translate()) - - -@requires_tools -def test_cli_writes_module_and_layout(gs_tri, tmp_path): - shader, spvasm = gs_tri - sa, sv = tmp_path / "gs.spvasm", tmp_path / "gs.spv" - sa.write_text(spvasm) - subprocess.run(["spirv-as", str(sa), "-o", str(sv), "--target-env", "vulkan1.2"], check=True) - out = tmp_path / "cs.spv" - r = subprocess.run([sys.executable, "-I", os.path.join(ROOT, "tools", "spirv_gs_to_compute.py"), str(sv), - str(out), "--layout", str(tmp_path / "lay.json")], capture_output=True, text=True) - assert r.returncode == 0, r.stderr - assert out.exists() and (tmp_path / "lay.json").exists() - subprocess.run(["spirv-val", "--target-env", "vulkan1.2", str(out)], check=True) - - -# A hand-built GS whose entry block branches, with an OpPhi naming the entry label as a predecessor (the translator -# emits those for guarded loads: its block_label is %entry until the first new label). The primitive-count check -# splits the entry block, so the OpPhi must name the block that now ends the entry code (review of #1331). -PHI_GS = """\ -OpCapability Shader -OpCapability Geometry -OpMemoryModel Logical GLSL450 -OpEntryPoint Geometry %main "main" %in_pos %out_pos -OpExecutionMode %main Triangles -OpExecutionMode %main Invocations 1 -OpExecutionMode %main OutputTriangleStrip -OpExecutionMode %main OutputVertices 3 -OpDecorate %in_pos BuiltIn Position -OpDecorate %out_pos BuiltIn Position -%void = OpTypeVoid -%fn = OpTypeFunction %void -%bool = OpTypeBool -%uint = OpTypeInt 32 0 -%float = OpTypeFloat 32 -%v4float = OpTypeVector %float 4 -%u0 = OpConstant %uint 0 -%u1 = OpConstant %uint 1 -%u3 = OpConstant %uint 3 -%arr = OpTypeArray %v4float %u3 -%ptr_in_arr = OpTypePointer Input %arr -%ptr_in_v4 = OpTypePointer Input %v4float -%ptr_out_v4 = OpTypePointer Output %v4float -%in_pos = OpVariable %ptr_in_arr Input -%out_pos = OpVariable %ptr_out_v4 Output -%main = OpFunction %void None %fn -%entry = OpLabel -%c = OpIEqual %bool %u0 %u1 -OpSelectionMerge %m None -OpBranchConditional %c %t %m -%t = OpLabel -OpBranch %m -%m = OpLabel -%x = OpPhi %uint %u1 %t %u0 %entry -%p = OpAccessChain %ptr_in_v4 %in_pos %x -%v = OpLoad %v4float %p -OpStore %out_pos %v -OpEmitVertex -OpEmitVertex -OpEmitVertex -OpEndPrimitive -OpReturn -OpFunctionEnd -""" - - -@pytest.mark.parametrize("newline", ["\n", "\r\n"], ids=["lf", "crlf"]) -def test_rewrite_preserves_unicode_separators_in_quoted_names(newline): - entry_name = "main\u2028capture" - debug_name = "geometry\u0085capture" - geometry = PHI_GS.replace('"main"', f'"{entry_name}"', 1).replace( - "OpDecorate %in_pos", f'OpName %main "{debug_name}"\nOpDecorate %in_pos', 1, - ) - - lowered, _ = gsc.rewrite(geometry.replace("\n", newline)) - - assert f'OpEntryPoint GLCompute %main "{entry_name}"' in lowered - assert f'OpName %main "{debug_name}"' in lowered - assert "OpEntryPoint Geometry" not in lowered - - -@pytest.mark.skipif(not HAVE_SPIRV, reason="needs spirv-as and spirv-val on PATH") -def test_phi_from_entry_block_names_the_split_block(tmp_path): - out, _ = gsc.rewrite(PHI_GS) - assert "%x = OpPhi %uint %u1 %t %u0 %gsc_body" in out - sa, sv = tmp_path / "cs.spvasm", tmp_path / "cs.spv" - sa.write_text(out) - subprocess.run(["spirv-as", str(sa), "-o", str(sv), "--target-env", "vulkan1.2"], check=True) - r = subprocess.run(["spirv-val", "--target-env", "vulkan1.2", str(sv)], capture_output=True, text=True) - assert r.returncode == 0, r.stderr - - -@pytest.mark.skipif(not HAVE_SPIRV or not shutil.which("spirv-dis"), reason="needs SPIRV-Tools on PATH") -@pytest.mark.parametrize("target", ["vulkan1.0", "vulkan1.1", "vulkan1.2"]) -def test_cli_preserves_valid_capture_across_spirv_versions(tmp_path: Path, target: str) -> None: - source, output = tmp_path / "gs.spv", tmp_path / "cs.spv" - subprocess.run(["spirv-as", "--target-env", target, "-", "-o", source], input=PHI_GS, text=True, check=True) - subprocess.run(["spirv-val", "--target-env", target, source], check=True) - tool = os.path.join(ROOT, "tools", "spirv_gs_to_compute.py") - result = subprocess.run([sys.executable, "-I", tool, source, output], capture_output=True, text=True) - assert result.returncode == 0, result.stderr - result = subprocess.run(["spirv-val", "--target-env", target, output], capture_output=True, text=True) - assert result.returncode == 0, result.stderr - assert output.read_bytes()[4:8] == source.read_bytes()[4:8] - - -@pytest.mark.skipif(not HAVE_SPIRV, reason="needs spirv-as and spirv-val on PATH") -def test_lowers_in_bounds_geometry_interface_access_chains(tmp_path: Path) -> None: - geometry = PHI_GS.replace( - "%p = OpAccessChain %ptr_in_v4 %in_pos %x", - "%p = OpInBoundsAccessChain %ptr_in_v4 %in_pos %x", - ).replace( - "%out_pos = OpVariable %ptr_out_v4 Output", - "%ptr_out_float = OpTypePointer Output %float\n%out_pos = OpVariable %ptr_out_v4 Output", - ).replace( - "OpStore %out_pos %v", - "OpStore %out_pos %v\n" - "%out_x = OpInBoundsAccessChain %ptr_out_float %out_pos %u0\n" - "%x_value = OpCompositeExtract %float %v 0\n" - "OpStore %out_x %x_value", - ) - - def validate(name: str, assembly: str) -> None: - module = tmp_path / f"{name}.spv" - subprocess.run(["spirv-as", "--target-env", "vulkan1.2", "-", "-o", str(module)], - input=assembly, text=True, check=True) - result = subprocess.run(["spirv-val", "--target-env", "vulkan1.2", str(module)], - capture_output=True, text=True) - assert result.returncode == 0, result.stderr - - validate("geometry", geometry) - lowered, _ = gsc.rewrite(geometry) - assert "%p = OpAccessChain %gsc_ptr_sb_v4 %gsc_in " in lowered - assert "%out_x = OpAccessChain %gsc_ptr_pv_f %gsc_out0 %u0" in lowered - validate("compute", lowered) - - -@pytest.fixture -def gs_module(tmp_path): - if not (HAVE_SPIRV and shutil.which("spirv-dis")): - pytest.skip("needs SPIRV-Tools on PATH") - source = tmp_path / "gs.spv" - subprocess.run(["spirv-as", "--target-env", "vulkan1.2", "-", "-o", str(source)], - input=PHI_GS, text=True, check=True) - return source - - -@pytest.mark.parametrize("overlap", ["input-output", "input-layout", "output-layout", "hardlinked-layout"]) -def test_cli_rejects_overlapping_paths_without_writing(tmp_path, gs_module, overlap): - source = gs_module - output = tmp_path / "cs.spv" - layout = tmp_path / "layout.json" - original = source.read_bytes() - if overlap == "input-output": - output = source - elif overlap == "input-layout": - layout = source - elif overlap == "output-layout": - subdir = tmp_path / "subdir" - subdir.mkdir() - layout = subdir / ".." / output.name - else: - try: - os.link(source, layout) - except OSError as e: - pytest.skip(f"hard links unavailable: {e}") - - result = subprocess.run([sys.executable, "-I", os.path.join(ROOT, "tools", "spirv_gs_to_compute.py"), - str(source), str(output), "--layout", str(layout)], capture_output=True, text=True) - assert result.returncode == 2, result.stderr - assert "same file" in result.stderr - assert source.read_bytes() == original - assert not (tmp_path / "cs.spv").exists() - if overlap == "hardlinked-layout": - assert layout.read_bytes() == original - - -def test_cli_accepts_distinct_module_and_layout_paths(tmp_path, gs_module): - output = tmp_path / "cs.spv" - layout = tmp_path / "layout.json" - original = gs_module.read_bytes() - result = subprocess.run([sys.executable, "-I", os.path.join(ROOT, "tools", "spirv_gs_to_compute.py"), - str(gs_module), str(output), "--layout", str(layout)], capture_output=True, text=True) - assert result.returncode == 0, result.stderr - assert gs_module.read_bytes() == original - assert json.loads(layout.read_text(encoding="utf-8"))["topology"] == "triangle_strip" - subprocess.run(["spirv-val", "--target-env", "vulkan1.2", str(output)], check=True) - - -@pytest.mark.skipif(not HAVE_SPIRV, reason="needs spirv-as and spirv-val on PATH") -@pytest.mark.parametrize("controls", [ - (), - ("SignedZeroInfNanPreserve 32", "DenormPreserve 16"), - ("DenormFlushToZero 32", "RoundingModeRTE 32", "RoundingModeRTZ 16"), -], ids=["opt-out", "translator-default", "explicit"]) -def test_capture_preserves_float_control_modes(tmp_path: Path, controls: tuple[str, ...]) -> None: - capabilities = "".join(f"OpCapability {control.split()[0]}\n" for control in controls) - modes = [f"OpExecutionMode %main {control}" for control in controls] - geometry = PHI_GS.replace( - "OpMemoryModel", capabilities + "OpMemoryModel", 1, - ).replace( - "OpDecorate %in_pos", "".join(f"{mode}\n" for mode in modes) + "OpDecorate %in_pos", 1, - ).replace( - "OpStore %out_pos %v", "%neg = OpFNegate %v4float %v\nOpStore %out_pos %neg", - ) - - def validate(name: str, assembly: str) -> None: - module = tmp_path / f"{name}.spv" - subprocess.run(["spirv-as", "--target-env", "vulkan1.2", "-", "-o", str(module)], - input=assembly, text=True, check=True) - subprocess.run(["spirv-val", "--target-env", "vulkan1.2", str(module)], check=True) - - validate("geometry", geometry) - lowered, _ = gsc.rewrite(geometry) - validate("compute", lowered) - execution_modes = [line for line in lowered.splitlines() if line.startswith("OpExecutionMode ")] - assert execution_modes == ["OpExecutionMode %main LocalSize 64 1 1", *modes] - - -def test_help_is_a_clean_exit_zero(capsys): - for flag in ("-h", "--help"): - assert gsc.main(["spirv_gs_to_compute.py", flag]) == 0 - out = capsys.readouterr().out - assert "spirv_gs_to_compute.py in.spv out.spv" in out - assert "SPIRV-Tools" in out - - -@pytest.mark.skipif(not HAVE_SPIRV, reason="needs spirv-as and spirv-val on PATH") -@pytest.mark.parametrize("targets,expected_targets", [ - ("%in_pos", ""), - ("%out_pos", ""), - ("%in_pos %v %out_pos %x", "%v %x"), - ("%v %x", "%v %x"), -], ids=["removed-input", "removed-output", "mixed", "live-only"]) -def test_group_decorate_keeps_only_live_capture_targets(tmp_path: Path, targets: str, - expected_targets: str) -> None: - geometry = PHI_GS.replace( - "OpDecorate %in_pos BuiltIn Position", "OpDecorate %in_pos Location 0", - ).replace( - "%void = OpTypeVoid", - "OpDecorate %relaxed RelaxedPrecision\n" - "%relaxed = OpDecorationGroup\n" - f"OpGroupDecorate %relaxed {targets} ; keep only module IDs\n" - "%void = OpTypeVoid", - ) - - lowered, _ = gsc.rewrite(geometry) - for name, assembly in (("geometry", geometry), ("compute", lowered)): - module = tmp_path / f"{name}.spv" - subprocess.run(["spirv-as", "--target-env", "vulkan1.2", "-", "-o", str(module)], - input=assembly, text=True, check=True) - subprocess.run(["spirv-val", "--target-env", "vulkan1.2", str(module)], check=True) - - group_uses = [line.partition(";")[0].strip() for line in lowered.splitlines() - if line.strip().startswith("OpGroupDecorate ")] - expected = [f"OpGroupDecorate %relaxed {expected_targets}"] if expected_targets else [] - assert group_uses == expected - - -def test_builtin_load_and_output_store_with_memory_operands(): - gs = PHI_GS.replace( - 'OpEntryPoint Geometry %main "main" %in_pos %out_pos', - 'OpEntryPoint Geometry %main "main" %in_pos %out_pos %prim_id %inv_id', - ).replace( - "OpDecorate %out_pos BuiltIn Position", - "OpDecorate %out_pos BuiltIn Position\n" - "OpDecorate %prim_id BuiltIn PrimitiveId\n" - "OpDecorate %inv_id BuiltIn InvocationId", - ).replace( - "%out_pos = OpVariable %ptr_out_v4 Output", - "%ptr_in_u = OpTypePointer Input %uint\n" - "%out_pos = OpVariable %ptr_out_v4 Output\n" - "%prim_id = OpVariable %ptr_in_u Input\n" - "%inv_id = OpVariable %ptr_in_u Input", - ).replace( - "%v = OpLoad %v4float %p\nOpStore %out_pos %v", - "%pid = OpLoad %uint %prim_id Aligned 4\n" - "%iid = OpLoad %uint %inv_id Volatile\n" - "%v = OpLoad %v4float %p\n" - "OpStore %out_pos %v Aligned 16", - ) - out, _ = gsc.rewrite(gs) - assert "%prim_id" not in out and "%inv_id" not in out - assert "%pid = OpCopyObject %uint %gsc_prim" in out - assert "%iid = OpCopyObject %uint " in out - assert "OpStore %gsc_out0 %v" in out - if HAVE_SPIRV: - res = subprocess.run(["spirv-as", "--target-env", "vulkan1.2", "-", "-o", os.devnull], - input=out, text=True, capture_output=True) - assert res.returncode == 0, res.stderr - - bad_gs = gs.replace("%pid = OpLoad %uint %prim_id Aligned 4", "OpCopyMemory %prim_id %inv_id") - with pytest.raises(gsc.Unsupported, match="%prim_id"): - gsc.rewrite(bad_gs) - - -@pytest.mark.skipif(not HAVE_SPIRV, reason="needs spirv-as and spirv-val on PATH") -@pytest.mark.parametrize("before_first,before_second", [ - ("", ""), - ("OpLine %source 1 1\n", ""), - ("", "OpNoLine\n"), - ("OpLine %source 1 1\n", "OpNoLine\n"), -], ids=["no-debug", "line", "no-line", "mixed"]) -def test_entry_debug_lines_keep_locals_before_capture_setup(tmp_path: Path, before_first: str, - before_second: str) -> None: - geometry = PHI_GS.replace( - "OpDecorate %in_pos", '%source = OpString "synthetic.glsl"\nOpDecorate %in_pos', 1, - ).replace( - "%out_pos = OpVariable", "%ptr_local = OpTypePointer Function %float\n%out_pos = OpVariable", 1, - ).replace( - "%entry = OpLabel", - f"%entry = OpLabel\n{before_first}%first = OpVariable %ptr_local Function\n" - f"{before_second}%second = OpVariable %ptr_local Function", - ).replace( - "OpStore %out_pos %v", - "%x_value = OpCompositeExtract %float %v 0\n" - "OpStore %first %x_value\n" - "%first_value = OpLoad %float %first\n" - "OpStore %second %first_value\n" - "%second_value = OpLoad %float %second\n" - "%position = OpCompositeInsert %v4float %second_value %v 0\n" - "OpStore %out_pos %position", - ) - - lowered, _ = gsc.rewrite(geometry) - for name, assembly in (("geometry", geometry), ("compute", lowered)): - module = tmp_path / f"{name}.spv" - subprocess.run(["spirv-as", "--target-env", "vulkan1.2", "-", "-o", str(module)], - input=assembly, text=True, check=True) - subprocess.run(["spirv-val", "--target-env", "vulkan1.2", str(module)], check=True) - - assert lowered.index("%first = OpVariable") < lowered.index("%gsc_gidv = OpLoad") - assert lowered.index("%second = OpVariable") < lowered.index("%gsc_gidv = OpLoad") - - -def test_pointers_derived_from_interface_access_chains_take_the_new_storage_class(tmp_path: Path) -> None: - # Old #4126: a copy of, or an access chain into, a pointer from an input or output access chain kept its Input / - # Output result type, while its base now points into the input buffer or a private variable. - geometry = PHI_GS.replace( - "%out_pos = OpVariable %ptr_out_v4 Output", - "%ptr_in_float = OpTypePointer Input %float\n%ptr_out_float = OpTypePointer Output %float\n" - "%out_pos = OpVariable %ptr_out_v4 Output", - ).replace( - "%v = OpLoad %v4float %p\nOpStore %out_pos %v", - "%pc = OpCopyObject %ptr_in_v4 %p\n" - "%py = OpInBoundsAccessChain %ptr_in_float %pc %u1\n" - "%y = OpLoad %float %py\n" - "%v = OpLoad %v4float %pc\n" - "OpStore %out_pos %v\n" - "%ox = OpAccessChain %ptr_out_float %out_pos %u0\n" - "%oc = OpCopyObject %ptr_out_float %ox\n" - "OpStore %oc %y", - ) - lowered, _ = gsc.rewrite(geometry) - assert "%pc = OpCopyObject %gsc_ptr_sb_v4 %p\n" in lowered - assert "%py = OpInBoundsAccessChain %gsc_ptr_sb_f %pc %u1\n" in lowered - assert "%ox = OpAccessChain %gsc_ptr_pv_f %gsc_out0 %u0\n" in lowered - assert "%oc = OpCopyObject %gsc_ptr_pv_f %ox\n" in lowered - assert "%ptr_in_v4 %p" not in lowered and "%ptr_in_float %pc" not in lowered - if HAVE_SPIRV: - for name, assembly in (("geometry", geometry), ("compute", lowered)): - module = tmp_path / f"{name}.spv" - subprocess.run(["spirv-as", "--target-env", "vulkan1.2", "-", "-o", str(module)], - input=assembly, text=True, check=True) - subprocess.run(["spirv-val", "--target-env", "vulkan1.2", str(module)], check=True) - - # OpPtrAccessChain gets the same treatment; a pointer to some other type is refused rather than mistyped. - ptr_chain = geometry.replace("%py = OpInBoundsAccessChain %ptr_in_float %pc %u1", - "%py = OpPtrAccessChain %ptr_in_float %pc %u0 %u1") - assert "%py = OpPtrAccessChain %gsc_ptr_sb_f %pc %u0 %u1\n" in gsc.rewrite(ptr_chain)[0] - odd = geometry.replace( - "%ptr_in_float = OpTypePointer Input %float", - "%ptr_in_float = OpTypePointer Input %float\n%ptr_in_uint = OpTypePointer Input %uint", - ).replace("%y = OpLoad %float %py", "%y = OpLoad %float %py\n%pu = OpAccessChain %ptr_in_uint %pc %u0") - with pytest.raises(gsc.Unsupported, match="unhandled type"): - gsc.rewrite(odd) diff --git a/tests/test_spirv_gs_to_compute_bounds.py b/tests/test_spirv_gs_to_compute_bounds.py deleted file mode 100644 index 90badc450..000000000 --- a/tests/test_spirv_gs_to_compute_bounds.py +++ /dev/null @@ -1,536 +0,0 @@ -"""Unit and semantic execution tests for OutputVertices bounds in tools/spirv_gs_to_compute.py (SHADER-617). - -Verifies that: -- OpEmitVertex guards record/meta SSBO stores and %gsc_n increments on n < OutputVertices, so a geometry - shader emitting past OutputVertices drops excess vertices rather than overflowing into primitive p+1's - record slots or meta count slot; -- OpEndPrimitive and OpReturn stay strictly within primitive p's meta slice (count <= OutputVertices), - including OutputVertices == 0 and repeated OpEndPrimitive calls after dropped emits; -- OpPhi predecessors are rewritten across every split block — entry block, forward if/else branches - containing OpEmitVertex, and loop-header back-edges from a latch block containing OpEmitVertex. - -Standard library only (runs with `python -I tests/test_spirv_gs_to_compute_bounds.py` and under pytest). -No game data, no GPU required; runs spirv-as + spirv-val when available on PATH. -""" -import os -import re -import shutil -import subprocess -import sys -import tempfile -import unittest - -ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) -sys.path.insert(0, os.path.join(ROOT, "tools")) -import spirv_gs_to_compute as gsc # noqa: E402 - -MASK32 = 0xFFFFFFFF - - -def _make_gs(body_lines, max_verts=3, verts_in=3, topology="OutputTriangleStrip", extra_consts=""): - return f"""\ -OpCapability Shader -OpCapability Geometry -OpMemoryModel Logical GLSL450 -OpEntryPoint Geometry %main "main" %in_pos %out_pos -OpExecutionMode %main Triangles -OpExecutionMode %main Invocations 1 -OpExecutionMode %main {topology} -OpExecutionMode %main OutputVertices {max_verts} -OpDecorate %in_pos BuiltIn Position -OpDecorate %out_pos BuiltIn Position -%void = OpTypeVoid -%fn = OpTypeFunction %void -%bool = OpTypeBool -%uint = OpTypeInt 32 0 -%float = OpTypeFloat 32 -%v4float = OpTypeVector %float 4 -%u0 = OpConstant %uint 0 -%u1 = OpConstant %uint 1 -%u2 = OpConstant %uint 2 -%u3 = OpConstant %uint 3 -%u5 = OpConstant %uint 5 -%f0 = OpConstant %float 0 -%f1 = OpConstant %float 1 -%f2 = OpConstant %float 2 -%f3 = OpConstant %float 3 -%f4 = OpConstant %float 4 -%f5 = OpConstant %float 5 -%v_a = OpConstantComposite %v4float %f1 %f0 %f0 %f1 -%v_b = OpConstantComposite %v4float %f2 %f0 %f0 %f1 -%v_c = OpConstantComposite %v4float %f3 %f0 %f0 %f1 -%v_d = OpConstantComposite %v4float %f4 %f0 %f0 %f1 -%v_e = OpConstantComposite %v4float %f5 %f0 %f0 %f1 -{extra_consts}%arr = OpTypeArray %v4float %u{verts_in} -%ptr_in_arr = OpTypePointer Input %arr -%ptr_in_v4 = OpTypePointer Input %v4float -%ptr_out_v4 = OpTypePointer Output %v4float -%in_pos = OpVariable %ptr_in_arr Input -%out_pos = OpVariable %ptr_out_v4 Output -%main = OpFunction %void None %fn -""" + "\n".join(body_lines) + "\nOpFunctionEnd\n" - - -def run_capture_spvasm(spvasm, gid_x, prim_count, in_data, rec_buf, meta_buf): - """Execute a lowered GLCompute capture module for one invocation (GlobalInvocationId.x = gid_x). - - Models the exact instruction subset emitted by spirv_gs_to_compute.py and our synthetic GS fixtures, - and checks OpPhi incoming-block labels at runtime so any missed predecessor relabeling fails loudly. - """ - consts = {} - var_init = {} - blocks = {} - cur_lbl = None - in_main = False - - for raw in spvasm.splitlines(): - s = raw.strip() - if not s or s.startswith(";"): - continue - m = re.match(r"^(%\w+)\s*=\s*(Op\w+)(?:\s+(.*))?$", s) - if m: - res, op, rest = m.group(1), m.group(2), (m.group(3) or "").split() - else: - parts = s.split() - res, op, rest = None, parts[0], parts[1:] - - if op == "OpConstant": - typ, lit = rest[0], rest[1] - consts[res] = float(lit) if "float" in typ else int(lit) - elif op == "OpConstantComposite": - consts[res] = tuple(consts[x] for x in rest[1:]) - elif op == "OpVariable" and not in_main: - if len(rest) >= 3: - var_init[res] = consts[rest[2]] - else: - var_init[res] = None - elif op == "OpFunction": - in_main = (res == "%main") - elif op == "OpFunctionEnd": - in_main = False - elif in_main: - if op == "OpLabel": - cur_lbl = res - blocks[cur_lbl] = [] - elif cur_lbl is not None: - blocks[cur_lbl].append((res, op, rest)) - - assert blocks, "no basic blocks found in %main" - entry_lbl = next(iter(blocks)) - priv = {k: (v if v is not None else (0.0, 0.0, 0.0, 0.0)) for k, v in var_init.items()} - vals = dict(consts) - ptrs = {} - - lbl = entry_lbl - prev_lbl = None - steps = 0 - while True: - steps += 1 - assert steps < 10000, f"possible infinite loop at {lbl}" - insns = blocks[lbl] - # Evaluate all OpPhi instructions at block entry simultaneously using prev_lbl. - phi_updates = {} - i = 0 - while i < len(insns) and insns[i][1] == "OpPhi": - res, _, rest = insns[i] - pairs = list(zip(rest[1::2], rest[2::2])) - matched = [vals[v_id] for v_id, pred in pairs if pred == prev_lbl] - assert len(matched) == 1, ( - f"OpPhi {res} in {lbl} expected predecessor {prev_lbl}, got {[p for _, p in pairs]}" - ) - phi_updates[res] = matched[0] - i += 1 - vals.update(phi_updates) - - for res, op, rest in insns[i:]: - if op in ("OpSelectionMerge", "OpLoopMerge"): - continue - elif op == "OpReturn": - return - elif op == "OpBranch": - prev_lbl, lbl = lbl, rest[0] - break - elif op == "OpBranchConditional": - prev_lbl = lbl - lbl = rest[1] if vals[rest[0]] else rest[2] - break - elif op == "OpAccessChain": - base = rest[1] - idxs = [vals[x] for x in rest[2:]] - ptrs[res] = (base, tuple(idxs)) - elif op == "OpLoad": - src = rest[1] - if src == "%gsc_gid": - vals[res] = (gid_x, 0, 0) - elif src in priv: - vals[res] = priv[src] - else: - base, idxs = ptrs[src] - if base == "%gsc_in": - if idxs == (0,): - vals[res] = prim_count - elif len(idxs) == 2 and idxs[0] == 2: - vals[res] = in_data[idxs[1]] - elif len(idxs) == 3 and idxs[0] == 2: - vals[res] = in_data[idxs[1]][idxs[2]] - else: - raise AssertionError(f"unexpected %gsc_in load {idxs}") - elif base == "%gsc_rec": - vals[res] = rec_buf[idxs[1]] - elif base == "%gsc_meta": - vals[res] = meta_buf[idxs[1]] - else: - raise AssertionError(f"unexpected load from {base} {idxs}") - elif op == "OpStore": - dst, v = rest[0], vals[rest[1]] - if dst in priv: - priv[dst] = v - else: - base, idxs = ptrs[dst] - if base == "%gsc_rec": - assert idxs[0] == 0 and 0 <= idxs[1] < len(rec_buf), ( - f"OOB %gsc_rec store at index {idxs[1]} (len={len(rec_buf)})" - ) - rec_buf[idxs[1]] = v - elif base == "%gsc_meta": - assert idxs[0] == 0 and 0 <= idxs[1] < len(meta_buf), ( - f"OOB %gsc_meta store at index {idxs[1]} (len={len(meta_buf)})" - ) - meta_buf[idxs[1]] = v - else: - raise AssertionError(f"unexpected store to {base} {idxs}") - elif op == "OpCompositeExtract": - vals[res] = vals[rest[1]][int(rest[2])] - elif op == "OpIAdd": - vals[res] = (vals[rest[1]] + vals[rest[2]]) & MASK32 - elif op == "OpIMul": - vals[res] = (vals[rest[1]] * vals[rest[2]]) & MASK32 - elif op == "OpUGreaterThanEqual": - vals[res] = (vals[rest[1]] & MASK32) >= (vals[rest[2]] & MASK32) - elif op == "OpULessThan": - vals[res] = (vals[rest[1]] & MASK32) < (vals[rest[2]] & MASK32) - elif op == "OpIEqual": - vals[res] = (vals[rest[1]] & MASK32) == (vals[rest[2]] & MASK32) - elif op == "OpBitcast" or op == "OpCopyObject": - vals[res] = vals[rest[1]] - else: - raise AssertionError(f"unsupported op in test interpreter: {op} {rest}") - - -def maybe_validate_spirv(spvasm): - import spirv_asm - binary = spirv_asm.assemble(spvasm) - assert len(binary) >= 20 and binary[:4] == b"\x03\x02\x23\x07", "invalid SPIR-V binary magic" - sas, sval = shutil.which("spirv-as"), shutil.which("spirv-val") - if not (sas and sval): - return - with tempfile.TemporaryDirectory() as d: - sa = os.path.join(d, "cs.spvasm") - sv = os.path.join(d, "cs.spv") - with open(sa, "w", encoding="utf-8") as f: - f.write(spvasm) - subprocess.run([sas, "--target-env", "vulkan1.2", sa, "-o", sv], check=True) - subprocess.run([sval, "--target-env", "vulkan1.2", sv], check=True) - - -class TestSpirvGsToComputeEmitBounds(unittest.TestCase): - def test_over_emit_clamped_and_neighbor_primitive_uncorrupted(self): - # OutputVertices = 3, but GS emits 5 vertices + OpEndPrimitive + OpReturn. - gs = _make_gs([ - "%entry = OpLabel", - "OpStore %out_pos %v_a", "OpEmitVertex", - "OpStore %out_pos %v_b", "OpEmitVertex", - "OpStore %out_pos %v_c", "OpEmitVertex", - "OpStore %out_pos %v_d", "OpEmitVertex", - "OpStore %out_pos %v_e", "OpEmitVertex", - "OpEndPrimitive", - "OpReturn", - ], max_verts=3) - out, lay = gsc.rewrite(gs) - self.assertEqual(lay["max_verts"], 3) - self.assertEqual(len(re.findall(r"OpULessThan %bool %\w+ %gsc_k3\b", out)), 5) - maybe_validate_spirv(out) - - sentinel_rec = (99.0, 99.0, 99.0, 99.0) - sentinel_meta = 0xCAFEBABE - # Two primitives: p=0 uses rec[0..2], meta[0..3]; p=1 uses rec[3..5], meta[4..7]. - rec = [sentinel_rec] * 6 - meta = [sentinel_meta] * 8 - in_data = [(0.0, 0.0, 0.0, 1.0)] * 6 - - run_capture_spvasm(out, gid_x=0, prim_count=2, in_data=in_data, rec_buf=rec, meta_buf=meta) - # Primitive 0 captured only its first 3 vertices and clamped count to 3. - self.assertEqual(rec[:3], [(1.0, 0.0, 0.0, 1.0), (2.0, 0.0, 0.0, 1.0), (3.0, 0.0, 0.0, 1.0)]) - self.assertEqual(meta[:4], [3, 0, 0, 1]) - # Primitive 1's records and meta count/flags must remain completely untouched. - self.assertEqual(rec[3:], [sentinel_rec] * 3) - self.assertEqual(meta[4:], [sentinel_meta] * 4) - - # Running primitive 1 afterwards writes cleanly into its own slice without affecting primitive 0. - run_capture_spvasm(out, gid_x=1, prim_count=2, in_data=in_data, rec_buf=rec, meta_buf=meta) - self.assertEqual(rec[:3], [(1.0, 0.0, 0.0, 1.0), (2.0, 0.0, 0.0, 1.0), (3.0, 0.0, 0.0, 1.0)]) - self.assertEqual(meta[:4], [3, 0, 0, 1]) - self.assertEqual(rec[3:], [(1.0, 0.0, 0.0, 1.0), (2.0, 0.0, 0.0, 1.0), (3.0, 0.0, 0.0, 1.0)]) - self.assertEqual(meta[4:], [3, 0, 0, 1]) - - # Out-of-range invocation (gid_x >= prim_count) returns immediately without touching buffers. - run_capture_spvasm(out, gid_x=2, prim_count=2, in_data=in_data, rec_buf=rec, meta_buf=meta) - self.assertEqual(meta, [3, 0, 0, 1, 3, 0, 0, 1]) - - def test_repeated_end_primitive_after_dropped_emit_stays_in_bounds(self): - # OutputVertices = 2: emit v_a, emit v_b, EndPrimitive, emit v_c (dropped), EndPrimitive, Return. - gs = _make_gs([ - "%entry = OpLabel", - "OpStore %out_pos %v_a", "OpEmitVertex", - "OpStore %out_pos %v_b", "OpEmitVertex", - "OpEndPrimitive", - "OpStore %out_pos %v_c", "OpEmitVertex", - "OpEndPrimitive", - "OpReturn", - ], max_verts=2) - out, _ = gsc.rewrite(gs) - maybe_validate_spirv(out) - - sentinel_rec = (-1.0, -1.0, -1.0, -1.0) - rec = [sentinel_rec] * 4 - meta = [0xDEAD] * 6 - run_capture_spvasm(out, gid_x=0, prim_count=2, in_data=[], rec_buf=rec, meta_buf=meta) - self.assertEqual(rec[:2], [(1.0, 0.0, 0.0, 1.0), (2.0, 0.0, 0.0, 1.0)]) - self.assertEqual(meta[:3], [2, 0, 1]) - self.assertEqual(rec[2:], [sentinel_rec, sentinel_rec]) - self.assertEqual(meta[3:], [0xDEAD, 0xDEAD, 0xDEAD]) - - def test_zero_output_vertices_drops_all_emits(self): - gs = _make_gs([ - "%entry = OpLabel", - "OpStore %out_pos %v_a", "OpEmitVertex", - "OpEndPrimitive", - "OpReturn", - ], max_verts=0) - out, lay = gsc.rewrite(gs) - self.assertEqual(lay["max_verts"], 0) - maybe_validate_spirv(out) - - rec = [] - meta = [0x1111, 0x2222] - run_capture_spvasm(out, gid_x=0, prim_count=2, in_data=[], rec_buf=rec, meta_buf=meta) - self.assertEqual(meta, [0, 0x2222]) - - def test_under_emit_preserves_exact_count_and_strip_flags(self): - gs = _make_gs([ - "%entry = OpLabel", - "OpStore %out_pos %v_a", "OpEmitVertex", - "OpEndPrimitive", - "OpStore %out_pos %v_b", "OpEmitVertex", - "OpEndPrimitive", - "OpReturn", - ], max_verts=4) - out, _ = gsc.rewrite(gs) - maybe_validate_spirv(out) - - sentinel_rec = (0.0, 0.0, 0.0, 0.0) - rec = [sentinel_rec] * 8 - meta = [99] * 10 - run_capture_spvasm(out, gid_x=0, prim_count=2, in_data=[], rec_buf=rec, meta_buf=meta) - self.assertEqual(rec[:2], [(1.0, 0.0, 0.0, 1.0), (2.0, 0.0, 0.0, 1.0)]) - self.assertEqual(rec[2:4], [sentinel_rec, sentinel_rec]) - self.assertEqual(meta[:3], [2, 1, 1]) - self.assertEqual(meta[5:], [99] * 5) - - def test_phi_predecessors_updated_for_entry_and_branch_emits(self): - # %then emits a vertex and branches to %merge; %entry also branches directly to %merge. - # Both %entry and %then are split, so %merge's OpPhi must name their final merge labels. - gs = _make_gs([ - "%entry = OpLabel", - "OpStore %out_pos %v_a", - "OpEmitVertex", - "%cond = OpIEqual %bool %u0 %u0", - "OpSelectionMerge %merge None", - "OpBranchConditional %cond %then %merge", - "%then = OpLabel", - "OpStore %out_pos %v_b", - "OpEmitVertex", - "OpBranch %merge", - "%merge = OpLabel", - "%idx = OpPhi %uint %u1 %then %u0 %entry", - "%p = OpAccessChain %ptr_in_v4 %in_pos %idx", - "%v = OpLoad %v4float %p", - "OpStore %out_pos %v", - "OpEmitVertex", - "OpEndPrimitive", - "OpReturn", - ], max_verts=3) - out, _ = gsc.rewrite(gs) - maybe_validate_spirv(out) - - # Neither %entry nor %then should remain as OpPhi predecessors after splitting. - phi_line = next(ln.strip() for ln in out.splitlines() if "%idx = OpPhi" in ln) - self.assertNotIn(" %entry", phi_line) - self.assertNotIn(" %then", phi_line) - - in_data = [(10.0, 0.0, 0.0, 1.0), (20.0, 0.0, 0.0, 1.0), (30.0, 0.0, 0.0, 1.0)] - rec = [(0.0, 0.0, 0.0, 0.0)] * 3 - meta = [99] * 4 - # Runtime OpPhi predecessor check verifies %merge sees the exact split predecessor label. - run_capture_spvasm(out, gid_x=0, prim_count=1, in_data=in_data, rec_buf=rec, meta_buf=meta) - self.assertEqual(rec, [(1.0, 0.0, 0.0, 1.0), (2.0, 0.0, 0.0, 1.0), (20.0, 0.0, 0.0, 1.0)]) - self.assertEqual(meta, [3, 0, 0, 1]) - - def test_loop_over_emit_updates_backedge_phi_and_clamps(self): - # Loop emits 5 times with OutputVertices = 3; %latch contains OpEmitVertex and branches back - # to %hdr whose OpPhi appears BEFORE %latch in the module. - gs = _make_gs([ - "%entry = OpLabel", - "OpBranch %hdr", - "%hdr = OpLabel", - "%i = OpPhi %uint %u0 %entry %i1 %latch", - "%more = OpULessThan %bool %i %u5", - "OpLoopMerge %exit %latch None", - "OpBranchConditional %more %body %exit", - "%body = OpLabel", - "OpBranch %latch", - "%latch = OpLabel", - "OpStore %out_pos %v_a", - "OpEmitVertex", - "%i1 = OpIAdd %uint %i %u1", - "OpBranch %hdr", - "%exit = OpLabel", - "OpEndPrimitive", - "OpReturn", - ], max_verts=3) - out, _ = gsc.rewrite(gs) - maybe_validate_spirv(out) - - phi_line = next(ln.strip() for ln in out.splitlines() if "%i = OpPhi" in ln) - self.assertIn(" %gsc_body", phi_line) - self.assertNotIn(" %latch", phi_line) - - sentinel_rec = (77.0, 77.0, 77.0, 77.0) - rec = [sentinel_rec] * 6 - meta = [0xBEEF] * 8 - run_capture_spvasm(out, gid_x=0, prim_count=2, in_data=[], rec_buf=rec, meta_buf=meta) - self.assertEqual(rec[:3], [(1.0, 0.0, 0.0, 1.0)] * 3) - self.assertEqual(meta[:4], [3, 0, 0, 1]) - self.assertEqual(rec[3:], [sentinel_rec] * 3) - self.assertEqual(meta[4:], [0xBEEF] * 4) - - def test_emit_vertex_in_loop_header_before_loop_merge_rejected(self): - # An OpEmitVertex in a loop header before OpLoopMerge would move OpLoopMerge into the - # split merge block while the back-edge still targets %hdr; rewrite() must reject it. - gs = _make_gs([ - "%entry = OpLabel", - "OpBranch %hdr", - "%hdr = OpLabel", - "%i = OpPhi %uint %u0 %entry %i1 %cont", - "OpStore %out_pos %v_a", - "OpEmitVertex", - "%more = OpULessThan %bool %i %u5", - "OpLoopMerge %exit %cont None", - "OpBranchConditional %more %cont %exit", - "%cont = OpLabel", - "%i1 = OpIAdd %uint %i %u1", - "OpBranch %hdr", - "%exit = OpLabel", - "OpEndPrimitive", - "OpReturn", - ], max_verts=3) - with self.assertRaises(gsc.Unsupported) as ctx: - gsc.rewrite(gs) - self.assertIn("OpLoopMerge", str(ctx.exception)) - - def test_pc_tail_ubo_in_set1_binding0_shifts_capture_bindings(self): - # A GS translated with --pc-tail-ubo that reads the heap base or code base already binds %pc_tail as a - # Uniform block at (DescriptorSet 1, Binding 0). Lowering it to compute must shift %gsc_in, %gsc_rec, and - # %gsc_meta to Bindings 1, 2, 3 so no two variables share (set=1, binding=0) with different descriptor types. - gs_base = _make_gs([ - "%entry = OpLabel", - "%p_tail = OpAccessChain %_ptr_Uniform_uint_tail %pc_tail %u2", - "%code_lo = OpLoad %uint %p_tail", - "OpStore %out_pos %v_a", - "OpEmitVertex", - "OpEndPrimitive", - "OpReturn", - ], max_verts=3) - gs_with_pc_tail = gs_base.replace( - 'OpEntryPoint Geometry %main "main" %in_pos %out_pos', - 'OpEntryPoint Geometry %main "main" %in_pos %out_pos %pc_tail', - ).replace( - "OpDecorate %out_pos BuiltIn Position", - "OpDecorate %out_pos BuiltIn Position\n" - "OpDecorate %PcTail Block\n" - "OpMemberDecorate %PcTail 0 Offset 0\n" - "OpMemberDecorate %PcTail 1 Offset 4\n" - "OpMemberDecorate %PcTail 2 Offset 8\n" - "OpMemberDecorate %PcTail 3 Offset 12\n" - "OpDecorate %pc_tail DescriptorSet 1\n" - "OpDecorate %pc_tail Binding 0", - ).replace( - "%main = OpFunction %void None %fn", - "%PcTail = OpTypeStruct %uint %uint %uint %uint\n" - "%_ptr_Uniform_PcTail = OpTypePointer Uniform %PcTail\n" - "%_ptr_Uniform_uint_tail = OpTypePointer Uniform %uint\n" - "%pc_tail = OpVariable %_ptr_Uniform_PcTail Uniform\n" - "%main = OpFunction %void None %fn", - ) - out, lay = gsc.rewrite(gs_with_pc_tail) - maybe_validate_spirv(out) - self.assertEqual(lay.get("base_binding"), 1) - _, deco = gsc.parse(out) - set1_map = {} - for var, ds in deco.items(): - if "DescriptorSet 1" in ds: - b = next(int(x.split()[1]) for x in ds if x.startswith("Binding ")) - self.assertNotIn(b, set1_map, f"duplicate (DescriptorSet 1, Binding {b}) on {var} and {set1_map.get(b)}") - set1_map[b] = var - self.assertEqual(set1_map, {0: "%pc_tail", 1: "%gsc_in", 2: "%gsc_rec", 3: "%gsc_meta"}) - - def test_end_to_end_translated_gs_with_pc_tail_ubo(self): - # End-to-end check with tools/rdna2spirv.py (PC_TAIL_UBO = True) on gs_tri.asm reading the heap base - # via s_load_dword, lowered by tools/spirv_gs_to_compute.py and assembled with tools/spirv_asm.py. - import struct - import rdna2spirv - - def sig_chunk(fourcc): - out = struct.pack("") - self.assertEqual(spv.NumericType("u", 64, 4).describe(), "vec4") - - # 16-bit and 32-bit occupy 1 component slot per element. - self.assertEqual(spv.NumericType("f", 16, 1).location_masks(0), (0b0001,)) - self.assertEqual(spv.NumericType("f", 16, 2).location_masks(2), (0b1100,)) - self.assertEqual(spv.NumericType("u", 32, 3).location_masks(1), (0b1110,)) - self.assertEqual(spv.NumericType("i", 32, 4).location_masks(0), (0b1111,)) - - # 64-bit types occupy 2 component slots per element. - self.assertEqual(spv.NumericType("f", 64, 1).location_masks(0), (0b0011,)) - self.assertEqual(spv.NumericType("i", 64, 1).location_masks(2), (0b1100,)) - self.assertEqual(spv.NumericType("u", 64, 2).location_masks(0), (0b1111,)) - self.assertEqual(spv.NumericType("f", 64, 3).location_masks(0), (0b1111, 0b0011)) - self.assertEqual(spv.NumericType("f", 64, 4).location_masks(0), (0b1111, 0b1111)) - - def test_numeric_type_mask_errors(self): - with self.assertRaisesRegex(spv.InterfaceError, "extends beyond its Location"): - spv.NumericType("f", 32, 2).location_masks(3) - with self.assertRaisesRegex(spv.InterfaceError, "extends beyond its Location"): - spv.NumericType("f", 16, 3).location_masks(2) - for comp in (1, 3): - with self.subTest(odd_component=comp): - with self.assertRaisesRegex(spv.InterfaceError, "odd Component"): - spv.NumericType("f", 64, 1).location_masks(comp) - for components in (3, 4): - with self.subTest(wide_components=components): - with self.assertRaisesRegex(spv.InterfaceError, "spanning two locations needs Component 0"): - spv.NumericType("f", 64, components).location_masks(2) - - def test_aggregate_type_describe_and_masks(self): - vec2 = spv.NumericType("f", 32, 2) - dvec3 = spv.NumericType("f", 64, 3) - arr = spv.AggregateType("array", (vec2,), 3) - mat = spv.AggregateType("matrix", (spv.NumericType("f", 32, 4),), 2) - nested = spv.AggregateType("struct", (vec2, dvec3)) - - self.assertEqual(arr.describe(), "array[3]>") - self.assertEqual(mat.describe(), "matrix[2]>") - self.assertEqual(nested.describe(), "struct{vec2, vec3}") - - self.assertEqual(arr.location_masks(2), (0b1100, 0b1100, 0b1100)) - self.assertEqual(mat.location_masks(0), (0b1111, 0b1111)) - self.assertEqual(nested.location_masks(0), (0b0011, 0b1111, 0b0011)) - - with self.assertRaisesRegex(spv.InterfaceError, "nonzero Component"): - nested.location_masks(1) - - def test_aggregate_type_expansion_limits(self): - f32 = spv.NumericType("f", 32) - at_limit = spv.AggregateType("array", (f32,), spv.MAX_EXPANDED_LOCATIONS) - self.assertEqual(len(at_limit.location_masks(0)), spv.MAX_EXPANDED_LOCATIONS) - - over_array = spv.AggregateType("array", (f32,), spv.MAX_EXPANDED_LOCATIONS + 1) - with self.assertRaisesRegex(spv.InterfaceError, "aggregate uses too many interface locations"): - over_array.location_masks(0) - - half = spv.AggregateType("array", (f32,), spv.MAX_EXPANDED_LOCATIONS // 2 + 1) - over_struct = spv.AggregateType("struct", (half, half)) - with self.assertRaisesRegex(spv.InterfaceError, "structure uses too many interface locations"): - over_struct.location_masks(0) - - def test_address_varying_and_declaration_helpers(self): - a0 = spv.Address(1, 0, 0) - a1 = spv.Address(1, 0, 1) - a2 = spv.Address(1, 2, 0) - a3 = spv.Address(2, 0, 0) - self.assertEqual(sorted([a3, a2, a1, a0]), [a0, a1, a2, a3]) - self.assertEqual(a0.describe(), "location 1, component 0") - self.assertEqual(a1.describe(), "location 1, component 0, index 1") - - varying = spv.Varying(spv.Address(4, 0, 1), spv.NumericType("f", 64, 3), per_primitive=True) - self.assertEqual( - list(varying.occupied()), - [ - spv.Address(4, 0, 1), - spv.Address(4, 1, 1), - spv.Address(4, 2, 1), - spv.Address(4, 3, 1), - spv.Address(5, 0, 1), - spv.Address(5, 1, 1), - ], - ) - self.assertEqual(varying.describe(), "vec3 per-primitive at location 4, component 0, index 1") - - plain_v = spv.Varying(spv.Address(0, 2), spv.NumericType("f", 32, 2)) - self.assertEqual(spv.Declaration((plain_v,), 7).describe(), "%7 (vec2 at location 0, component 2)") - self.assertEqual( - spv.Declaration((plain_v,), 7, structure=True).describe(), - "struct %7 (vec2 at location 0, component 2)", - ) - self.assertEqual( - spv.Declaration((plain_v,), 7, structure=True, block=True).describe(), - "block %7 (vec2 at location 0, component 2)", - ) - - -class ModuleStructureAndDecorationsTest(unittest.TestCase): - def test_rejects_ids_outside_bound_and_duplicate_definitions(self): - # ID 0 definition. - b = SpirvBuilder("vs") - b.emit(spv.OP_TYPE_FLOAT, 0, 32) - with self.assertRaisesRegex(spv.InterfaceError, "ID %0 is outside the SPIR-V bound"): - spv.Module(b.build()) - - # ID equal to bound. - b = SpirvBuilder("vs") - b.emit(spv.OP_TYPE_FLOAT, 99, 32) - with self.assertRaisesRegex(spv.InterfaceError, "ID %99 is outside the SPIR-V bound"): - spv.Module(b.build(bound=10)) - - # Duplicate definition across two instructions. - b = SpirvBuilder("vs") - f32 = b.float_type(32) - b.emit(spv.OP_TYPE_INT, f32, 32, 0) - with self.assertRaisesRegex(spv.InterfaceError, f"duplicate definition of ID %{f32}"): - spv.Module(b.build()) - - def test_rejects_bad_operand_counts_on_declarations(self): - cases = [ - ("OpTypeInt_short", spv.OP_TYPE_INT, (1, 32)), - ("OpTypeInt_long", spv.OP_TYPE_INT, (1, 32, 0, 9)), - ("OpTypeFloat_short", spv.OP_TYPE_FLOAT, (1,)), - ("OpTypeFloat_long", spv.OP_TYPE_FLOAT, (1, 16, 0, 0)), - ("OpTypeVector_short", spv.OP_TYPE_VECTOR, (1, 2)), - ("OpTypeMatrix_long", spv.OP_TYPE_MATRIX, (1, 2, 3, 4)), - ("OpTypeArray_short", spv.OP_TYPE_ARRAY, (1, 2)), - ("OpTypePointer_short", spv.OP_TYPE_POINTER, (1, spv.STORAGE_OUTPUT)), - ("OpTypeStruct_empty_operands", spv.OP_TYPE_STRUCT, ()), - ("OpConstant_short", spv.OP_CONSTANT, (1, 2)), - ("OpVariable_short", spv.OP_VARIABLE, (1, 2)), - ("OpVariable_too_long", spv.OP_VARIABLE, (1, 2, spv.STORAGE_OUTPUT, 3, 4)), - ("OpEntryPoint_short", spv.OP_ENTRY_POINT, (MODEL_VS, 1)), - ("OpDecorate_short", spv.OP_DECORATE, (1,)), - ("OpMemberDecorate_short", spv.OP_MEMBER_DECORATE, (1, 0)), - ("OpDecorationGroup_empty", spv.OP_DECORATION_GROUP, ()), - ("OpDecorationGroup_extra", spv.OP_DECORATION_GROUP, (1, 2)), - ("OpGroupDecorate_short", spv.OP_GROUP_DECORATE, (1,)), - ("OpGroupMemberDecorate_short", spv.OP_GROUP_MEMBER_DECORATE, (1, 2)), - ] - for label, opcode, args in cases: - with self.subTest(case=label): - b = SpirvBuilder("vs") - b.emit(opcode, *args) - with self.assertRaisesRegex(spv.InterfaceError, "invalid operands"): - spv.Module(b.build(bound=20, auto_entry=False)) - - def test_variable_with_optional_initializer_is_accepted(self): - b = SpirvBuilder("vs") - f32 = b.float_type(32) - zero = b.constant(f32, 0) - var = b.variable(spv.STORAGE_OUTPUT, f32, location=3, initializer=zero) - iface = b.reflect() - self.assertEqual(len(iface.outputs), 1) - self.assertEqual(iface.outputs[0].symbol, var) - self.assertEqual(iface.outputs[0].varyings[0].address, spv.Address(3)) - - def test_accepts_encoded_float_outside_interface(self): - b = SpirvBuilder("vs") - bf16 = b.emit_type(spv.OP_TYPE_FLOAT, 16, 0) # BFloat16KHR - b.constant(bf16, 0x3F00) - b.variable(spv.STORAGE_OUTPUT, b.numeric("f", 32, 4), location=3) - output, = b.reflect().outputs - self.assertEqual( - output.varyings, - (spv.Varying(spv.Address(3), spv.NumericType("f", 32, 4)),), - ) - - def test_rejects_encoded_float_varying(self): - b = SpirvBuilder("vs") - bf16 = b.emit_type(spv.OP_TYPE_FLOAT, 16, 0) # BFloat16KHR - b.variable(spv.STORAGE_OUTPUT, bf16, location=3) - with self.assertRaisesRegex(spv.InterfaceError, "unsupported floating-point encoding"): - b.reflect() - - def test_ignores_non_interface_decorations_and_validates_known_ones(self): - b = SpirvBuilder("ps") - v = b.variable(spv.STORAGE_INPUT, b.numeric("f", 32, 4), location=2) - # Non-interface decorations with 0, 1, or more operands are ignored. - b.decorate(v, DEC_FLAT) - b.decorate(v, DEC_NO_PERSPECTIVE) - b.decorate(v, DEC_DESCRIPTOR_SET, 0) - b.decorate(v, DEC_BINDING, 7) - b.decorate(v, DEC_OFFSET, 16) - # Duplicate identical known decoration is idempotent. - b.decorate(v, spv.DEC_LOCATION, 2) - iface = b.reflect() - self.assertEqual(len(iface.inputs), 1) - self.assertEqual(iface.inputs[0].varyings[0].address, spv.Address(2)) - - # Value decoration missing its operand. - b_missing = SpirvBuilder("vs") - var = b_missing.variable(spv.STORAGE_OUTPUT, b_missing.numeric("f", 32)) - b_missing.decorate(var, spv.DEC_LOCATION) - with self.assertRaisesRegex(spv.InterfaceError, "invalid Location decoration"): - spv.Module(b_missing.build()) - - # Value decoration with extra operands. - b_extra = SpirvBuilder("vs") - var = b_extra.variable(spv.STORAGE_OUTPUT, b_extra.numeric("f", 32)) - b_extra.decorate(var, spv.DEC_COMPONENT, 0, 1) - with self.assertRaisesRegex(spv.InterfaceError, "invalid Component decoration"): - spv.Module(b_extra.build()) - - # Flag decoration with unexpected operand. - b_flag = SpirvBuilder("vs") - s = b_flag.struct_type(b_flag.numeric("f", 32)) - b_flag.decorate(s, spv.DEC_BLOCK, 1) - with self.assertRaisesRegex(spv.InterfaceError, "invalid Block decoration"): - spv.Module(b_flag.build()) - - # Conflicting known decoration on same target. - b_conflict = SpirvBuilder("vs") - var = b_conflict.variable(spv.STORAGE_OUTPUT, b_conflict.numeric("f", 32), location=1) - b_conflict.decorate(var, spv.DEC_LOCATION, 4) - with self.assertRaisesRegex(spv.InterfaceError, "conflicting Location decorations"): - spv.Module(b_conflict.build()) - - def test_decoration_groups_apply_regardless_of_instruction_order(self): - b = SpirvBuilder("vs") - struct_id = b.struct_type(b.numeric("f", 32, 2), b.numeric("f", 32, 2)) - b.decorate(struct_id, spv.DEC_BLOCK) - blk = b.variable(spv.STORAGE_OUTPUT, struct_id) - var = b.variable(spv.STORAGE_OUTPUT, b.numeric("f", 32)) - - g_loc = b.decoration_group() - g_empty = b.decoration_group() - # Group use emitted BEFORE decorating the group itself. - b.emit(spv.OP_GROUP_MEMBER_DECORATE, g_loc, struct_id, 0) - b.emit(spv.OP_GROUP_DECORATE, g_empty, var) - b.decorate(g_loc, spv.DEC_LOCATION, 5) - b.member_decorate(struct_id, 1, spv.DEC_LOCATION, 6) - b.decorate(var, spv.DEC_LOCATION, 5) - b.decorate(var, spv.DEC_COMPONENT, 2) - - iface = b.reflect() - self.assertEqual([d.symbol for d in iface.outputs], [blk, var]) - self.assertEqual([v.address for v in iface.outputs[0].varyings], [spv.Address(5, 0), spv.Address(6, 0)]) - self.assertEqual(iface.outputs[1].varyings[0].address, spv.Address(5, 2)) - - def test_decoration_group_errors(self): - # Undefined group. - b = SpirvBuilder("vs") - var = b.variable(spv.STORAGE_OUTPUT, b.numeric("f", 32), location=0) - missing_group = b.alloc() - b.emit(spv.OP_GROUP_DECORATE, missing_group, var) - with self.assertRaisesRegex(spv.InterfaceError, f"undefined decoration group %{missing_group}"): - spv.Module(b.build()) - - # Unpaired OpGroupMemberDecorate operands (even operand count: group + struct + member + dangling struct). - b = SpirvBuilder("vs") - s = b.struct_type(b.numeric("f", 32)) - g = b.decoration_group() - b.emit(spv.OP_GROUP_MEMBER_DECORATE, g, s, 0, s) - with self.assertRaisesRegex(spv.InterfaceError, "unpaired group member decoration"): - spv.Module(b.build()) - - # Decoration group targeting another decoration group. - b = SpirvBuilder("vs") - g1 = b.decoration_group() - g2 = b.decoration_group() - b.decorate(g1, spv.DEC_LOCATION, 0) - b.emit(spv.OP_GROUP_DECORATE, g1, g2) - with self.assertRaisesRegex(spv.InterfaceError, "decoration groups cannot decorate each other"): - spv.Module(b.build()) - - # Conflicting member decoration via group. - b = SpirvBuilder("vs") - s = b.struct_type(b.numeric("f", 32)) - b.member_decorate(s, 0, spv.DEC_LOCATION, 1) - g = b.decoration_group() - b.decorate(g, spv.DEC_LOCATION, 2) - b.emit(spv.OP_GROUP_MEMBER_DECORATE, g, s, 0) - with self.assertRaisesRegex(spv.InterfaceError, "conflicting Location decorations"): - spv.Module(b.build()) - - -class TypeAndConstantResolutionTest(unittest.TestCase): - def test_array_length_constant_widths_and_signedness(self): - cases = [ - ("u16", 16, False, (0x00010003,), 3), # masks to 16 bits - ("i16", 16, True, (5,), 5), - ("u32", 32, False, (4,), 4), - ("i32", 32, True, (2,), 2), - ("u64", 64, False, (3, 0), 3), - ("i64", 64, True, (6, 0), 6), - ] - for label, width, signed, words, expected in cases: - with self.subTest(case=label): - b = SpirvBuilder("vs") - int_t = b.int_type(width, signed=signed) - length_id = b.constant(int_t, *words) - arr_t = b.emit_type(spv.OP_TYPE_ARRAY, b.numeric("f", 32), length_id) - b.variable(spv.STORAGE_OUTPUT, arr_t, location=0) - v = b.reflect().outputs[0].varyings[0] - self.assertEqual(v.type, spv.AggregateType("array", (spv.NumericType("f", 32),), expected)) - - def test_array_length_accepts_int8_constants(self): - for opcode in (spv.OP_CONSTANT, spv.OP_SPEC_CONSTANT): - for signed, count in ((False, 0x82), (True, 5)): - with self.subTest(opcode=opcode, signed=signed): - b = SpirvBuilder("vs") - length_type = b.int_type(8, signed=signed) - length_id = b.alloc() - b.emit(opcode, length_type, length_id, count) - arr_t = b.emit_type(spv.OP_TYPE_ARRAY, b.float_type(), length_id) - b.variable(spv.STORAGE_OUTPUT, arr_t, location=0) - varying = b.reflect().outputs[0].varyings[0] - self.assertEqual(varying.type, spv.AggregateType("array", (spv.NumericType("f", 32),), count)) - - def test_array_length_constant_errors(self): - # Not an OpConstant (references an undefined ID). - b = SpirvBuilder("vs") - arr_t = b.emit_type(spv.OP_TYPE_ARRAY, b.numeric("f", 32), b.alloc()) - b.variable(spv.STORAGE_OUTPUT, arr_t, location=0) - with self.assertRaisesRegex(spv.InterfaceError, "not a literal OpConstant"): - b.reflect() - - # Non-integer constant (float). - b = SpirvBuilder("vs") - f_const = b.constant(b.float_type(32), 0x3F800000) - arr_t = b.emit_type(spv.OP_TYPE_ARRAY, b.numeric("f", 32), f_const) - b.variable(spv.STORAGE_OUTPUT, arr_t, location=0) - with self.assertRaisesRegex(spv.InterfaceError, "must be an integer"): - b.reflect() - - # Unsupported integer width for array length. - b = SpirvBuilder("vs") - u24 = b.int_type(24) - c = b.constant(u24, 3) - arr_t = b.emit_type(spv.OP_TYPE_ARRAY, b.numeric("f", 32), c) - b.variable(spv.STORAGE_OUTPUT, arr_t, location=0) - with self.assertRaisesRegex(spv.InterfaceError, "must be an integer"): - b.reflect() - - # Wrong literal word count (64-bit integer with only 1 word). - b = SpirvBuilder("vs") - u64 = b.int_type(64, signed=False) - bad_lit = b.constant(u64, 2) - arr_t = b.emit_type(spv.OP_TYPE_ARRAY, b.numeric("f", 32), bad_lit) - b.variable(spv.STORAGE_OUTPUT, arr_t, location=0) - with self.assertRaisesRegex(spv.InterfaceError, "invalid literal width"): - b.reflect() - - # Zero and negative signed counts. - bad_counts = [ - ("zero_u8", 8, False, (0,)), - ("neg_i8", 8, True, (0xFFFFFF80,)), - ("zero_u32", 32, False, (0,)), - ("neg_i16", 16, True, (0x8000,)), - ("neg_i32", 32, True, (0xFFFFFFFF,)), - ("neg_i64", 64, True, (0, 0x80000000)), - ] - for label, width, signed, literal in bad_counts: - with self.subTest(case=label): - b = SpirvBuilder("vs") - c = b.constant(b.int_type(width, signed=signed), *literal) - arr_t = b.emit_type(spv.OP_TYPE_ARRAY, b.numeric("f", 32), c) - b.variable(spv.STORAGE_OUTPUT, arr_t, location=0) - with self.assertRaisesRegex(spv.InterfaceError, "must be positive"): - b.reflect() - - def test_all_numeric_types_matrices_and_nested_aggregates(self): - b = SpirvBuilder("vs") - loc = 0 - expected = [] - for kind in ("f", "i", "u"): - for width in (16, 32, 64): - t = b.numeric(kind, width, 1) - b.variable(spv.STORAGE_OUTPUT, t, location=loc) - expected.append((loc, spv.NumericType(kind, width, 1))) - loc += 1 - - # Matrix of f32 and f16, 2D array, and nested struct inside array. - mat = b.matrix(3, 4, 32) - b.variable(spv.STORAGE_OUTPUT, mat, location=loc) - expected.append((loc, spv.AggregateType("matrix", (spv.NumericType("f", 32, 4),), 3))) - loc += 3 - - arr2d = b.array(b.array(b.numeric("u", 16, 2), 2), 3) - b.variable(spv.STORAGE_OUTPUT, arr2d, location=loc) - expected.append(( - loc, - spv.AggregateType("array", (spv.AggregateType("array", (spv.NumericType("u", 16, 2),), 2),), 3), - )) - loc += 6 - - inner = b.struct_type(b.numeric("f", 32, 2), b.numeric("i", 32, 1)) - arr_of_struct = b.array(inner, 2) - b.variable(spv.STORAGE_OUTPUT, arr_of_struct, location=loc) - expected.append(( - loc, - spv.AggregateType( - "array", - (spv.AggregateType("struct", (spv.NumericType("f", 32, 2), spv.NumericType("i", 32, 1))),), - 2, - ), - )) - - iface = b.reflect() - got = [(d.varyings[0].address.location, d.varyings[0].type) for d in iface.outputs] - self.assertEqual(got, expected) - - def test_shared_type_reuses_shape_cache_and_big_endian_round_trips(self): - b = SpirvBuilder("vs") - shared_vec4 = b.numeric("f", 32, 4) - b.variable(spv.STORAGE_OUTPUT, shared_vec4, location=0) - b.variable(spv.STORAGE_OUTPUT, shared_vec4, location=1) - le_iface = spv.reflect_module(b.build(big_endian=False)) - be_iface = spv.reflect_module(b.build(big_endian=True)) - self.assertEqual(le_iface, be_iface) - self.assertIs(le_iface.outputs[0].varyings[0].type, le_iface.outputs[1].varyings[0].type) - - def test_invalid_shapes_are_rejected(self): - # Unsupported numeric width / signedness. - for opcode, args in ( - (spv.OP_TYPE_FLOAT, (8,)), - (spv.OP_TYPE_INT, (8, 0)), - (spv.OP_TYPE_INT, (32, 2)), - ): - with self.subTest(bad_numeric=(opcode, args)): - b = SpirvBuilder("vs") - t = b.emit_type(opcode, *args) - b.variable(spv.STORAGE_OUTPUT, t, location=0) - with self.assertRaisesRegex(spv.InterfaceError, "unsupported numeric type"): - b.reflect() - - # Invalid vectors: components=1, components=5, vector of vector. - for setup in ( - lambda b: b.emit_type(spv.OP_TYPE_VECTOR, b.float_type(32), 1), - lambda b: b.emit_type(spv.OP_TYPE_VECTOR, b.float_type(32), 5), - lambda b: b.emit_type(spv.OP_TYPE_VECTOR, b.numeric("f", 32, 2), 2), - ): - b = SpirvBuilder("vs") - b.variable(spv.STORAGE_OUTPUT, setup(b), location=0) - with self.assertRaisesRegex(spv.InterfaceError, "invalid varying vector type"): - b.reflect() - - # Invalid matrices: integer column, scalar float column, cols=1, cols=5. - for setup in ( - lambda b: b.emit_type(spv.OP_TYPE_MATRIX, b.numeric("i", 32, 2), 2), - lambda b: b.emit_type(spv.OP_TYPE_MATRIX, b.float_type(32), 2), - lambda b: b.emit_type(spv.OP_TYPE_MATRIX, b.numeric("f", 32, 2), 1), - lambda b: b.emit_type(spv.OP_TYPE_MATRIX, b.numeric("f", 32, 2), 5), - ): - b = SpirvBuilder("vs") - b.variable(spv.STORAGE_OUTPUT, setup(b), location=0) - with self.assertRaisesRegex(spv.InterfaceError, "invalid varying matrix type"): - b.reflect() - - # Pointer used as varying payload. - b = SpirvBuilder("vs") - inner_ptr = b.pointer(spv.STORAGE_OUTPUT, b.float_type(32)) - b.variable(spv.STORAGE_OUTPUT, inner_ptr, location=0) - with self.assertRaisesRegex(spv.InterfaceError, "unsupported pointer"): - b.reflect() - - # Missing/unknown type ID. - b = SpirvBuilder("vs") - b.variable(spv.STORAGE_OUTPUT, b.alloc(), location=0) - with self.assertRaisesRegex(spv.InterfaceError, "missing or unsupported varying type"): - b.reflect() - - # Empty nested struct. - b = SpirvBuilder("vs") - empty_inner = b.struct_type() - outer = b.struct_type(empty_inner) - b.variable(spv.STORAGE_OUTPUT, outer, location=0) - with self.assertRaisesRegex(spv.InterfaceError, "empty structure in graphics interface"): - b.reflect() - - # Decorated nested struct member. - b = SpirvBuilder("vs") - inner = b.struct_type(b.float_type(32)) - b.member_decorate(inner, 0, spv.DEC_LOCATION, 0) - outer = b.struct_type(inner) - b.variable(spv.STORAGE_OUTPUT, outer, location=0) - with self.assertRaisesRegex(spv.InterfaceError, "decorated nested interface structure members"): - b.reflect() - - def test_cyclic_and_excessively_deep_types_are_rejected(self): - # Cyclic type: array referencing itself via forward ID. - b = SpirvBuilder("vs") - self_arr = b.alloc() - one = b.u32_const(1) - b.emit(spv.OP_TYPE_ARRAY, self_arr, self_arr, one) - b.variable(spv.STORAGE_OUTPUT, self_arr, location=0) - with self.assertRaisesRegex(spv.InterfaceError, "cyclic or excessively deep"): - b.reflect() - - # Excessively deep nesting (> MAX_TYPE_DEPTH). - b = SpirvBuilder("vs") - t = b.float_type(32) - for _ in range(spv.MAX_TYPE_DEPTH + 1): - t = b.array(t, 1) - b.variable(spv.STORAGE_OUTPUT, t, location=0) - with self.assertRaisesRegex(spv.InterfaceError, "cyclic or excessively deep"): - b.reflect() - - -class EntryPointSelectionTest(unittest.TestCase): - def test_all_supported_stages_infer_and_match(self): - for stage in ("vs", "gs", "ps", "ms"): - with self.subTest(stage=stage): - b = SpirvBuilder(stage) - iface = b.reflect() - self.assertEqual(iface.stage, stage) - self.assertEqual(iface.entry, "main") - self.assertEqual(iface.inputs, ()) - self.assertEqual(iface.outputs, ()) - self.assertEqual(b.reflect(stage=stage).stage, stage) - - def test_multiple_entry_points_and_stage_disambiguation(self): - b = SpirvBuilder("vs") - v_out = b.variable(spv.STORAGE_OUTPUT, b.numeric("f", 32, 4), location=1, add_to_interface=False) - p_in = b.variable(spv.STORAGE_INPUT, b.numeric("f", 32, 2), location=3, add_to_interface=False) - p_alt = b.variable(spv.STORAGE_INPUT, b.numeric("i", 32, 1), location=7, add_to_interface=False) - b.entry_point("main", [v_out], stage="vs") - b.entry_point("main", [p_in], stage="ps") - b.entry_point("PixelAlt", [p_alt], stage="ps") - - data = b.build() - with self.assertRaisesRegex(spv.InterfaceError, "ambiguous without a stage"): - spv.reflect_module(data) - - vs_iface = spv.reflect_module(data, stage="vs") - self.assertEqual(vs_iface.stage, "vs") - self.assertEqual([d.symbol for d in vs_iface.outputs], [v_out]) - - ps_iface = spv.reflect_module(data, stage="ps") - self.assertEqual(ps_iface.stage, "ps") - self.assertEqual([d.symbol for d in ps_iface.inputs], [p_in]) - - alt_iface = spv.reflect_module(data, entry="PixelAlt") - self.assertEqual(alt_iface.stage, "ps") - self.assertEqual(alt_iface.entry, "PixelAlt") - self.assertEqual([d.symbol for d in alt_iface.inputs], [p_alt]) - - def test_entry_point_errors(self): - # Missing entry point. - b = SpirvBuilder("vs") - with self.assertRaisesRegex(spv.InterfaceError, "entry point 'other' not found"): - b.reflect(entry="other") - - # Wrong stage. - with self.assertRaisesRegex(spv.InterfaceError, "entry point 'main' is vs, expected ps"): - b.reflect(stage="ps") - - # Duplicate same name + same stage. - b_dup = SpirvBuilder("vs") - b_dup.entry_point("main", [], stage="vs") - b_dup.entry_point("main", [], stage="vs") - with self.assertRaisesRegex(spv.InterfaceError, "ambiguous"): - b_dup.reflect(stage="vs") - - # Unsupported execution models (Compute, Tessellation, TaskEXT). - for model in (MODEL_CS, MODEL_TESC, MODEL_TESE, MODEL_TASK_EXT): - with self.subTest(model=model): - b_unsup = SpirvBuilder("vs") - b_unsup.entry_point("main", [], model=model) - with self.assertRaisesRegex(spv.InterfaceError, f"unsupported execution model {model}"): - b_unsup.reflect() - with self.assertRaisesRegex(spv.InterfaceError, f"is {model}, expected vs"): - b_unsup.reflect(stage="vs") - - # Entry point referencing a missing OpVariable. - b_missing_var = SpirvBuilder("vs") - ghost = b_missing_var.alloc() - b_missing_var.entry_point("main", [ghost]) - with self.assertRaisesRegex(spv.InterfaceError, f"missing variable %{ghost}"): - b_missing_var.reflect() - - def test_accepts_repeated_interface_ids_before_spirv_1_4(self): - for version in (0x00010000, 0x00010300): - with self.subTest(version=hex(version)): - builder = SpirvBuilder("vs", version=version) - scalar = builder.numeric("f", 32) - first = builder.variable(spv.STORAGE_OUTPUT, scalar, location=0) - second = builder.variable(spv.STORAGE_OUTPUT, scalar, location=1) - builder.entry_point("main", [second, first, second, first]) - module = spv.Module(builder.build()) - self.assertEqual(module.entry_points[0].interface_ids, (second, first)) - self.assertEqual([d.symbol for d in builder.reflect().outputs], [first, second]) - - def test_rejects_repeated_interface_ids_from_spirv_1_4(self): - for version in (0x00010400, 0x00010500): - with self.subTest(version=hex(version)): - builder = SpirvBuilder("vs", version=version) - output = builder.variable(spv.STORAGE_OUTPUT, builder.numeric("f", 32), location=0) - builder.entry_point("main", [output, output]) - with self.assertRaisesRegex(spv.InterfaceError, "duplicate entry-point interface ID"): - builder.reflect() - - def test_ignores_resource_storage_classes_with_descriptor_bindings(self): - b = SpirvBuilder("ps") - opaque_type = b.alloc() # Not even in TYPE_OPS; non-I/O variables are skipped before type lookup. - for idx, storage in enumerate(( - STORAGE_UNIFORM_CONSTANT, - STORAGE_UNIFORM, - STORAGE_WORKGROUP, - STORAGE_PRIVATE, - STORAGE_PUSH_CONSTANT, - STORAGE_STORAGE_BUFFER, - )): - var = b.variable(storage, opaque_type) - b.decorate(var, DEC_DESCRIPTOR_SET, 0) - b.decorate(var, DEC_BINDING, idx) - color = b.variable(spv.STORAGE_OUTPUT, b.numeric("f", 32, 4), location=0) - - iface = b.reflect() - self.assertEqual(iface.inputs, ()) - self.assertEqual([d.symbol for d in iface.outputs], [color]) - - -class StageInterfacesAndLayoutTest(unittest.TestCase): - def test_inputs_and_outputs_sorted_and_separated(self): - b = SpirvBuilder("vs") - # Add in unsorted order, sharing locations across input and output directions. - in_hi = b.variable(spv.STORAGE_INPUT, b.numeric("f", 32, 2), location=4, component=2) - in_lo = b.variable(spv.STORAGE_INPUT, b.numeric("f", 32, 2), location=4, component=0) - in_zero = b.variable(spv.STORAGE_INPUT, b.numeric("f", 32, 4), location=0) - out_hi = b.variable(spv.STORAGE_OUTPUT, b.numeric("f", 32, 4), location=4) - out_lo = b.variable(spv.STORAGE_OUTPUT, b.numeric("f", 32, 4), location=0) - - # Mix in non-declaration instructions (OpCapability, OpExecutionMode, OpName, OpFunction). - b.emit_prefix(OP_CAPABILITY, 1) - b.emit_prefix(OP_MEMORY_MODEL, 0, 1) - func_id = b.entry_point("main") - b.emit(OP_EXECUTION_MODE, func_id, 7) - b.emit(OP_NAME, out_lo, *encode_string_words("out0")) - void_t = b.emit_type(OP_TYPE_VOID) - fn_t = b.emit_type(OP_TYPE_FUNCTION, void_t) - b.emit(OP_FUNCTION, void_t, func_id, 0, fn_t) - b.emit(OP_FUNCTION_END) - - iface = b.reflect() - self.assertEqual([d.symbol for d in iface.inputs], [in_zero, in_lo, in_hi]) - self.assertEqual([d.symbol for d in iface.outputs], [out_lo, out_hi]) - - def test_component_packing_and_dual_source_outputs(self): - b = SpirvBuilder("ps") - # Pack four distinct components into location 1 (c=0, c=1..2, c=3). - c3 = b.variable(spv.STORAGE_INPUT, b.numeric("f", 32, 1), location=1, component=3) - c1 = b.variable(spv.STORAGE_INPUT, b.numeric("f", 32, 2), location=1, component=1) - c0 = b.variable(spv.STORAGE_INPUT, b.numeric("f", 32, 1), location=1, component=0) - # Dual-source outputs at location 0 with index 1 and index 0. - src1 = b.variable(spv.STORAGE_OUTPUT, b.numeric("f", 32, 4), location=0, index=1) - src0 = b.variable(spv.STORAGE_OUTPUT, b.numeric("f", 32, 4), location=0, index=0) - - iface = b.reflect() - self.assertEqual([d.symbol for d in iface.inputs], [c0, c1, c3]) - self.assertEqual([d.symbol for d in iface.outputs], [src0, src1]) - self.assertEqual([d.varyings[0].address for d in iface.outputs], [spv.Address(0, 0, 0), spv.Address(0, 0, 1)]) - - def test_invalid_address_decorations_and_pointer_mismatch(self): - # Missing Location. - b = SpirvBuilder("vs") - v = b.variable(spv.STORAGE_OUTPUT, b.numeric("f", 32)) - with self.assertRaisesRegex(spv.InterfaceError, f"vs output variable %{v}: user varying is missing a Location"): - b.reflect() - - # Component > 3. - b = SpirvBuilder("vs") - b.variable(spv.STORAGE_OUTPUT, b.numeric("f", 32), location=0, component=4) - with self.assertRaisesRegex(spv.InterfaceError, "invalid Component or Index"): - b.reflect() - - # Index > 1. - b = SpirvBuilder("ps") - b.variable(spv.STORAGE_OUTPUT, b.numeric("f", 32), location=0, index=2) - with self.assertRaisesRegex(spv.InterfaceError, "invalid Component or Index"): - b.reflect() - - # Pointer storage class mismatch. - b = SpirvBuilder("vs") - wrong_ptr = b.pointer(spv.STORAGE_INPUT, b.numeric("f", 32)) - var = b.alloc() - b.emit(spv.OP_VARIABLE, wrong_ptr, var, spv.STORAGE_OUTPUT) - b.decorate(var, spv.DEC_LOCATION, 0) - b.interface_ids.append(var) - with self.assertRaisesRegex(spv.InterfaceError, "does not match its storage class"): - b.reflect() - - # Non-pointer type on OpVariable. - b = SpirvBuilder("vs") - not_ptr = b.numeric("f", 32) - var = b.alloc() - b.emit(spv.OP_VARIABLE, not_ptr, var, spv.STORAGE_OUTPUT) - b.decorate(var, spv.DEC_LOCATION, 0) - b.interface_ids.append(var) - with self.assertRaisesRegex(spv.InterfaceError, "does not match its storage class"): - b.reflect() - - def test_builtins_skipped_and_mixed_builtin_struct_rejected(self): - b = SpirvBuilder("vs") - pos = b.variable(spv.STORAGE_OUTPUT, b.numeric("f", 32, 4)) - b.decorate(pos, spv.DEC_BUILTIN, 0) - - builtin_blk = b.struct_type(b.numeric("f", 32, 4), b.numeric("f", 32, 1)) - b.decorate(builtin_blk, spv.DEC_BLOCK) - b.member_decorate(builtin_blk, 0, spv.DEC_BUILTIN, 0) - b.member_decorate(builtin_blk, 1, spv.DEC_BUILTIN, 1) - b.variable(spv.STORAGE_OUTPUT, builtin_blk) - - user_out = b.variable(spv.STORAGE_OUTPUT, b.numeric("f", 32, 2), location=0) - iface = b.reflect() - self.assertEqual([d.symbol for d in iface.outputs], [user_out]) - - # Mixed BuiltIn and user member in same struct is rejected. - b_mixed = SpirvBuilder("vs") - mixed = b_mixed.struct_type(b_mixed.numeric("f", 32, 4), b_mixed.numeric("f", 32, 2)) - b_mixed.decorate(mixed, spv.DEC_BLOCK) - b_mixed.member_decorate(mixed, 0, spv.DEC_BUILTIN, 0) - b_mixed.member_decorate(mixed, 1, spv.DEC_LOCATION, 0) - b_mixed.variable(spv.STORAGE_OUTPUT, mixed) - with self.assertRaisesRegex(spv.InterfaceError, "mixed built-in and user-defined"): - b_mixed.reflect() - - def test_struct_and_block_layouts(self): - # Block with explicit member locations, components, and per-member PerPrimitiveEXT. - b = SpirvBuilder("ps") - blk_t = b.struct_type(b.numeric("f", 32, 2), b.numeric("f", 32, 2), b.numeric("u", 32, 1)) - b.decorate(blk_t, spv.DEC_BLOCK) - b.member_decorate(blk_t, 0, spv.DEC_LOCATION, 2) - b.member_decorate(blk_t, 0, spv.DEC_COMPONENT, 0) - b.member_decorate(blk_t, 1, spv.DEC_LOCATION, 2) - b.member_decorate(blk_t, 1, spv.DEC_COMPONENT, 2) - b.member_decorate(blk_t, 2, spv.DEC_LOCATION, 5) - b.member_decorate(blk_t, 2, spv.DEC_PER_PRIMITIVE) - blk_var = b.variable(spv.STORAGE_INPUT, blk_t) - - # Non-block struct with variable-level Location auto-assigning multi-location members. - s_t = b.struct_type( - b.numeric("f", 64, 3), # 2 locations: 10..11 - b.matrix(2, 4, 32), # 2 locations: 12..13 - b.numeric("f", 32, 1), # 1 location: 14 - ) - s_var = b.variable(spv.STORAGE_INPUT, s_t, location=10) - - iface = b.reflect() - self.assertEqual([d.symbol for d in iface.inputs], [blk_var, s_var]) - - blk_decl, s_decl = iface.inputs - self.assertTrue(blk_decl.structure) - self.assertTrue(blk_decl.block) - self.assertEqual( - [(v.address, v.per_primitive) for v in blk_decl.varyings], - [(spv.Address(2, 0), False), (spv.Address(2, 2), False), (spv.Address(5, 0), True)], - ) - - self.assertTrue(s_decl.structure) - self.assertFalse(s_decl.block) - self.assertEqual([v.address for v in s_decl.varyings], [spv.Address(10), spv.Address(12), spv.Address(14)]) - - def test_struct_and_block_error_cases(self): - # Non-block struct without Location on variable. - b = SpirvBuilder("vs") - s = b.struct_type(b.numeric("f", 32)) - b.member_decorate(s, 0, spv.DEC_LOCATION, 0) - b.variable(spv.STORAGE_OUTPUT, s) - with self.assertRaisesRegex(spv.InterfaceError, "non-block structure needs a Location"): - b.reflect() - - # Component or Index on entire structure variable. - for kw in ({"component": 1}, {"index": 1}): - with self.subTest(struct_dec=kw): - b = SpirvBuilder("ps") - s = b.struct_type(b.numeric("f", 32)) - b.variable(spv.STORAGE_OUTPUT, s, location=0, **kw) - with self.assertRaisesRegex(spv.InterfaceError, "Component or Index on an entire varying structure"): - b.reflect() - - # Both struct variable and a member declare Location. - b = SpirvBuilder("vs") - s = b.struct_type(b.numeric("f", 32)) - b.decorate(s, spv.DEC_BLOCK) - b.member_decorate(s, 0, spv.DEC_LOCATION, 2) - b.variable(spv.STORAGE_OUTPUT, s, location=1) - with self.assertRaisesRegex(spv.InterfaceError, "both the structure and its members declare Locations"): - b.reflect() - - # Empty top-level Block struct. - b = SpirvBuilder("vs") - empty = b.struct_type() - b.decorate(empty, spv.DEC_BLOCK) - b.variable(spv.STORAGE_OUTPUT, empty) - with self.assertRaisesRegex(spv.InterfaceError, "empty structure in graphics interface"): - b.reflect() - - # Block member missing Location when block variable has no Location. - b = SpirvBuilder("vs") - s = b.struct_type(b.numeric("f", 32), b.numeric("f", 32)) - b.decorate(s, spv.DEC_BLOCK) - b.member_decorate(s, 0, spv.DEC_LOCATION, 0) - b.variable(spv.STORAGE_OUTPUT, s) - with self.assertRaisesRegex(spv.InterfaceError, "missing a Location"): - b.reflect() - - def test_stage_indexed_arrays_per_vertex_and_per_primitive(self): - # GS input requires outer array and strips it; GS output does not. - gs = SpirvBuilder("gs") - gs_in = gs.variable(spv.STORAGE_INPUT, gs.array(gs.numeric("f", 32, 4), 3), location=0) - gs_out = gs.variable(spv.STORAGE_OUTPUT, gs.numeric("f", 32, 4), location=0) - gs_iface = gs.reflect() - self.assertEqual(gs_iface.inputs[0].symbol, gs_in) - self.assertTrue(gs_iface.inputs[0].indexed_by_vertex_or_primitive) - self.assertEqual(gs_iface.inputs[0].varyings[0].type, spv.NumericType("f", 32, 4)) - self.assertEqual(gs_iface.outputs[0].symbol, gs_out) - self.assertFalse(gs_iface.outputs[0].indexed_by_vertex_or_primitive) - - # GS input without outer array is rejected. - gs_bad = SpirvBuilder("gs") - gs_bad.variable(spv.STORAGE_INPUT, gs_bad.numeric("f", 32, 4), location=0) - with self.assertRaisesRegex(spv.InterfaceError, "gs requires an outer per-vertex or per-primitive array"): - gs_bad.reflect() - - # MS output requires outer array and supports PerPrimitiveEXT (including on blocks). - ms = SpirvBuilder("ms") - prim_blk = ms.struct_type(ms.numeric("u", 32, 1)) - ms.decorate(prim_blk, spv.DEC_BLOCK) - ms.member_decorate(prim_blk, 0, spv.DEC_LOCATION, 2) - ms.variable(spv.STORAGE_OUTPUT, ms.array(prim_blk, 64), flags=(spv.DEC_PER_PRIMITIVE,)) - ms.variable(spv.STORAGE_OUTPUT, ms.array(ms.numeric("f", 32, 4), 32), location=0) - ms_iface = ms.reflect() - self.assertTrue(all(d.indexed_by_vertex_or_primitive for d in ms_iface.outputs)) - self.assertFalse(ms_iface.outputs[0].varyings[0].per_primitive) - self.assertTrue(ms_iface.outputs[1].varyings[0].per_primitive) - - # MS output without outer array is rejected. - ms_bad = SpirvBuilder("ms") - ms_bad.variable(spv.STORAGE_OUTPUT, ms_bad.numeric("f", 32, 4), location=0) - with self.assertRaisesRegex(spv.InterfaceError, "ms requires an outer per-vertex or per-primitive array"): - ms_bad.reflect() - - # PS input with PerVertexKHR strips outer array; without array is rejected. - ps = SpirvBuilder("ps") - ps.variable(spv.STORAGE_INPUT, ps.array(ps.numeric("f", 32, 3), 3), location=1, flags=(spv.DEC_PER_VERTEX,)) - ps_iface = ps.reflect() - self.assertTrue(ps_iface.inputs[0].indexed_by_vertex_or_primitive) - self.assertEqual(ps_iface.inputs[0].varyings[0].type, spv.NumericType("f", 32, 3)) - - ps_bad = SpirvBuilder("ps") - ps_bad.variable(spv.STORAGE_INPUT, ps_bad.numeric("f", 32, 3), location=1, flags=(spv.DEC_PER_VERTEX,)) - with self.assertRaisesRegex(spv.InterfaceError, "ps requires an outer per-vertex or per-primitive array"): - ps_bad.reflect() - - # PerVertexKHR is rejected on non-(ps, input) variables. - for stage, storage in (("vs", spv.STORAGE_INPUT), ("vs", spv.STORAGE_OUTPUT), ("ps", spv.STORAGE_OUTPUT)): - with self.subTest(per_vertex_invalid=(stage, storage)): - bad = SpirvBuilder(stage) - bad.variable(storage, bad.array(bad.numeric("f", 32), 3), location=0, flags=(spv.DEC_PER_VERTEX,)) - with self.assertRaisesRegex(spv.InterfaceError, "PerVertexKHR is only supported on fragment inputs"): - bad.reflect() - - def test_unsupported_modes_passthrough_and_patch(self): - for dec, pattern in ((spv.DEC_PASSTHROUGH_NV, "passthrough"), (spv.DEC_PATCH, "tessellation patch")): - with self.subTest(variable_mode=pattern): - b = SpirvBuilder("vs") - b.variable(spv.STORAGE_OUTPUT, b.numeric("f", 32), location=0, flags=(dec,)) - with self.assertRaisesRegex(spv.InterfaceError, pattern): - b.reflect() - - with self.subTest(member_mode=pattern): - b = SpirvBuilder("vs") - s = b.struct_type(b.numeric("f", 32)) - b.decorate(s, spv.DEC_BLOCK) - b.member_decorate(s, 0, spv.DEC_LOCATION, 0) - b.member_decorate(s, 0, dec) - b.variable(spv.STORAGE_OUTPUT, s) - with self.assertRaisesRegex(spv.InterfaceError, pattern): - b.reflect() - - def test_overlap_detection_across_scalars_aggregates_structs_and_indices(self): - # Matrix at loc 2..4 overlaps scalar at loc 4. - b = SpirvBuilder("vs") - b.variable(spv.STORAGE_OUTPUT, b.matrix(3, 4, 32), location=2) - b.variable(spv.STORAGE_OUTPUT, b.numeric("f", 32, 1), location=4) - with self.assertRaisesRegex(spv.InterfaceError, "overlap.*location 4, component 0"): - b.reflect() - - # Array at component 2 leaves components 0..1 free, but overlaps component 3. - b_ok = SpirvBuilder("vs") - b_ok.variable(spv.STORAGE_OUTPUT, b_ok.array(b_ok.numeric("f", 32, 2), 2), location=1, component=2) - b_ok.variable(spv.STORAGE_OUTPUT, b_ok.numeric("f", 32, 2), location=2, component=0) - self.assertEqual(len(b_ok.reflect().outputs), 2) - - b_hit = SpirvBuilder("vs") - b_hit.variable(spv.STORAGE_OUTPUT, b_hit.array(b_hit.numeric("f", 32, 2), 2), location=1, component=2) - b_hit.variable(spv.STORAGE_OUTPUT, b_hit.numeric("f", 32, 1), location=2, component=3) - with self.assertRaisesRegex(spv.InterfaceError, "overlap.*location 2, component 3"): - b_hit.reflect() - - # Intra-struct overlap between two block members. - b_blk = SpirvBuilder("ps") - blk = b_blk.struct_type(b_blk.numeric("f", 32, 3), b_blk.numeric("f", 32, 2)) - b_blk.decorate(blk, spv.DEC_BLOCK) - b_blk.member_decorate(blk, 0, spv.DEC_LOCATION, 1) - b_blk.member_decorate(blk, 1, spv.DEC_LOCATION, 1) - b_blk.member_decorate(blk, 1, spv.DEC_COMPONENT, 2) - b_blk.variable(spv.STORAGE_INPUT, blk) - with self.assertRaisesRegex(spv.InterfaceError, "ps input variable.*overlap.*location 1, component 2"): - b_blk.reflect() - - # Duplicate dual-source index 1 at same location overlaps. - b_ds = SpirvBuilder("ps") - b_ds.variable(spv.STORAGE_OUTPUT, b_ds.numeric("f", 32, 4), location=0, index=1) - b_ds.variable(spv.STORAGE_OUTPUT, b_ds.numeric("f", 32, 1), location=0, component=2, index=1) - with self.assertRaisesRegex(spv.InterfaceError, "overlap.*location 0, component 2, index 1"): - b_ds.reflect() - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/test_spirv_interp_bits.py b/tests/test_spirv_interp_bits.py deleted file mode 100644 index 06c85d7e4..000000000 --- a/tests/test_spirv_interp_bits.py +++ /dev/null @@ -1,123 +0,0 @@ -"""tests/spirv_interp.py keeps the exact 32-bit pattern of a float made by OpBitcast (issue #509, as #533 did for -tests/semantic/spirv_mini_interp.py). - - python -I tests/test_spirv_interp_bits.py - -Hand-written SPIR-V only, standard library only. No translator, no game data. -""" -import os -import struct -import sys -import unittest - -sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) -import spirv_interp as si # noqa: E402 - -# Signalling NaNs (exponent all ones, bit 22 clear, mantissa not zero), a quiet NaN and two ordinary values. -# Going through a Python float set bit 22 of the first four. -WORDS = (0xFFA3A095, 0x7F800001, 0x7FBFFFFF, 0xFF800001, 0x7FC00001, 0x3F800000, 0x80000000) - -MODULE = """\ -OpCapability Shader -OpMemoryModel Logical GLSL450 -OpEntryPoint Fragment %main "main" %out_mrt0 -%void = OpTypeVoid -%fn = OpTypeFunction %void -%bool = OpTypeBool -%uint = OpTypeInt 32 0 -%float = OpTypeFloat 32 -%v2float = OpTypeVector %float 2 -%c0 = OpConstant %uint 0 -%c4 = OpConstant %uint 4 -%f1 = OpConstant %float 1 -%t = OpConstantTrue %bool -%cw = OpConstant %uint {word} -%arr = OpTypeArray %uint %c4 -%null = OpConstantNull %arr -%_ptr_Function_arr = OpTypePointer Function %arr -%_ptr_Function_uint = OpTypePointer Function %uint -%_ptr_Output_float = OpTypePointer Output %float -%vgpr = OpVariable %_ptr_Function_arr Function %null -%sgpr = OpVariable %_ptr_Function_arr Function %null -%out_mrt0 = OpVariable %_ptr_Output_float Output -%main = OpFunction %void None %fn -%entry = OpLabel -{body}OpReturn -OpFunctionEnd -""" - - -def run(word, body): - return si.run(MODULE.format(word=word, body=body)) - - -class BitcastKeepsBits(unittest.TestCase): - def test_round_trip_through_every_pass_through(self): - # uint -> float -> OpCopyObject -> composite -> OpSelect -> a float Output and back to a uint in v0. - body = ("%x = OpBitcast %float %cw\n" - "%y = OpCopyObject %float %x\n" - "%v = OpCompositeConstruct %v2float %f1 %y\n" - "%e = OpCompositeExtract %float %v 1\n" - "%s = OpSelect %float %t %e %f1\n" - "OpStore %out_mrt0 %s\n" - "%w = OpBitcast %uint %s\n" - "%p = OpAccessChain %_ptr_Function_uint %vgpr %c0\n" - "OpStore %p %w\n") - for word in WORDS: - with self.subTest(word=f"{word:#010x}"): - r = run(word, body) - self.assertEqual(r.vgpr[0], word) - self.assertEqual(si.f2u(r.outputs["out_mrt0"]), word) - - def test_still_a_nan_to_float_operations(self): - r = run(0xFFA3A095, "%x = OpBitcast %float %cw\n%n = OpIsNan %bool %x\n" - "%k = OpSelect %uint %n %c4 %c0\n" - "%p = OpAccessChain %_ptr_Function_uint %vgpr %c0\nOpStore %p %k\n") - self.assertEqual(r.vgpr[0], 4) - - def test_arithmetic_gives_a_nan(self): - # Arithmetic drops the kept pattern: SPIR-V does not fix the bits of a NaN result, so only "a NaN" is - # asserted (exponent all ones, mantissa not zero). - r = run(0xFFA3A095, "%x = OpBitcast %float %cw\n%y = OpFAdd %float %x %f1\n%w = OpBitcast %uint %y\n" - "%p = OpAccessChain %_ptr_Function_uint %vgpr %c0\nOpStore %p %w\n") - self.assertEqual(r.vgpr[0] & 0x7F800000, 0x7F800000) - self.assertNotEqual(r.vgpr[0] & 0x007FFFFF, 0) - - def test_helpers(self): - for word in WORDS: - with self.subTest(word=f"{word:#010x}"): - self.assertEqual(si.f2u(si.u2f(word)), word) - self.assertEqual(si.f2u(1.5), 0x3FC00000) # a plain float still converts as before - - -class HalfNanRuleTests(unittest.TestCase): - """si.half_to_float / si.float_to_half pin one NaN rule on every Python version. - - struct's ' double keeps it on every version) canonicalizes too - payload = struct.unpack(" infinity - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/test_spirv_interp_f64_glsl.py b/tests/test_spirv_interp_f64_glsl.py deleted file mode 100644 index cefc1fd28..000000000 --- a/tests/test_spirv_interp_f64_glsl.py +++ /dev/null @@ -1,266 +0,0 @@ -"""Regression tests for 64-bit %double and %v2double GLSL.std.450 execution in tests/spirv_interp.py.""" - -import math -import struct -import sys -import tempfile -import unittest -from pathlib import Path - -TEST_DIR = Path(__file__).resolve().parent -sys.path[:0] = [str(TEST_DIR.parent / "tools"), str(TEST_DIR)] - -from listing import translate_listing # noqa: E402 -import spirv_interp # noqa: E402 - - -def f64_bits(x): - return struct.unpack("> 32 - - -def f32_round(x): - return struct.unpack(" 2 and parts[1] == "="} - local_type = definitions[base][1] - assert definitions[definitions[local_type][2]][0] == "OpTypeArray" - assert f"OpDecorate {base} Binding {m.metal_ids(m.capacities())[binding]}" in text - for i in range(depth): - copy = f"%copy{i}" - assert definitions[copy] == ["OpCopyObject", local_type, base] - base = copy - foreign_type = definitions["%foreign_samplers"][1] - assert definitions[definitions[foreign_type][2]][0] == "OpTypeRuntimeArray" - assert definitions["%foreign_copy"] == ["OpCopyObject", foreign_type, "%foreign_samplers"] diff --git a/tests/test_spirv_metal_set0_aliases.py b/tests/test_spirv_metal_set0_aliases.py deleted file mode 100644 index 379360930..000000000 --- a/tests/test_spirv_metal_set0_aliases.py +++ /dev/null @@ -1,405 +0,0 @@ -"""Regression tests for tools/spirv_metal_set0.py file hygiene and aliased set-0 bindings. - -Standard library only; uses synthetic SPIR-V disassembly, no game data and no external SPIRV-Tools binaries. - - python -I -W error::ResourceWarning tests/test_spirv_metal_set0_aliases.py -v -""" -import ast -import contextlib -import gc -import io -import os -import re -import sys -import tempfile -import unittest -import warnings - -ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) -TOOLS_DIR = os.path.join(ROOT, "tools") -TOOL_PATH = os.path.join(TOOLS_DIR, "spirv_metal_set0.py") -if TOOLS_DIR not in sys.path: - sys.path.insert(0, TOOLS_DIR) - -import spirv_metal_set0 as m # noqa: E402 - - -def _parse_defs_and_order(text): - """Parse SSA definitions, check for duplicates and declaration-before-use ordering.""" - defs = {} - def_line = {} - decs = [] - lines = text.splitlines() - for idx, ln in enumerate(lines): - m_dec = re.match(r"^\s*OpDecorate (%\S+) (\S+) (\d+)$", ln) - if m_dec: - decs.append((m_dec.group(1), m_dec.group(2), int(m_dec.group(3)))) - continue - m_def = re.match(r"^\s*(%\S+) = (.*)$", ln) - if not m_def: - continue - rid, rhs = m_def.group(1), m_def.group(2) - if rid in defs: - raise AssertionError(f"duplicate SSA definition for {rid} at line {idx + 1}: {ln}") - defs[rid] = rhs - def_line[rid] = idx - - # Verify declaration-before-use for constants, array types, pointers, and variables. - for rid, rhs in defs.items(): - cur = def_line[rid] - parts = rhs.split() - op = parts[0] - if op == "OpConstant": - ty = parts[1] - assert def_line[ty] < cur, f"{rid} uses {ty} before definition" - elif op == "OpTypeRuntimeArray": - elem = parts[1] - assert def_line[elem] < cur, f"{rid} uses {elem} before definition" - elif op == "OpTypeArray": - elem, length = parts[1], parts[2] - assert def_line[elem] < cur, f"{rid} uses {elem} before definition" - assert def_line[length] < cur, f"{rid} uses {length} before definition" - elif op == "OpTypePointer": - pointee = parts[2] - assert def_line[pointee] < cur, f"{rid} uses {pointee} before definition" - elif op == "OpVariable": - ptr = parts[1] - assert def_line[ptr] < cur, f"{rid} uses {ptr} before definition" - - return defs, def_line, decs - - -class TestFileHygiene(unittest.TestCase): - def test_capacities_and_print_layout_emit_no_resource_warning(self): - with tempfile.TemporaryDirectory() as tmp: - good_hdr = os.path.join(tmp, "good.h") - bad_hdr = os.path.join(tmp, "bad.h") - with open(good_hdr, "w", encoding="utf-8") as f: - f.write("std::array bindings = {{{VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE, 16}, " - "{VK_DESCRIPTOR_TYPE_SAMPLER, 8}}};\n") - with open(bad_hdr, "w", encoding="utf-8") as f: - f.write("// missing table\n") - - with warnings.catch_warnings(): - warnings.simplefilter("error", ResourceWarning) - counts = m.capacities() - self.assertEqual(len(counts), 26) - self.assertEqual(m.capacities(good_hdr), [16, 8]) - with self.assertRaises(SystemExit): - m.capacities(bad_hdr) - with contextlib.redirect_stdout(io.StringIO()): - self.assertEqual(m.main(["spirv_metal_set0.py", "--print-layout"]), 0) - gc.collect() - - def test_spirv_metal_set0_has_no_unmanaged_open_calls(self): - with open(TOOL_PATH, encoding="utf-8") as f: - src = f.read() - tree = ast.parse(src, filename=TOOL_PATH) - managed = set() - for node in ast.walk(tree): - if isinstance(node, (ast.With, ast.AsyncWith)): - for item in node.items: - if isinstance(item.context_expr, ast.Call): - managed.add(id(item.context_expr)) - bare = [ - node.lineno - for node in ast.walk(tree) - if isinstance(node, ast.Call) - and isinstance(node.func, ast.Name) - and node.func.id == "open" - and id(node) not in managed - ] - self.assertEqual(bare, []) - - -class TestSingleAndAliasedBindings(unittest.TestCase): - def test_single_variable_bindings_keep_canonical_msl_ids(self): - module = """\ - OpDecorate %images DescriptorSet 0 - OpDecorate %images Binding 0 - OpDecorate %samplers DescriptorSet 0 - OpDecorate %samplers Binding 1 - OpDecorate %desc_map DescriptorSet 0 - OpDecorate %desc_map Binding 2 - %uint = OpTypeInt 32 0 - %float = OpTypeFloat 32 - %img2d = OpTypeImage %float 2D 0 0 0 1 Unknown - %smp = OpTypeSampler - %rt_img = OpTypeRuntimeArray %img2d - %rt_smp = OpTypeRuntimeArray %smp - %ptr_img = OpTypePointer UniformConstant %rt_img - %ptr_smp = OpTypePointer UniformConstant %rt_smp - %rt_map = OpTypeRuntimeArray %uint - %map = OpTypeStruct %rt_map - %ptr_map = OpTypePointer StorageBuffer %map - %images = OpVariable %ptr_img UniformConstant - %samplers = OpVariable %ptr_smp UniformConstant - %desc_map = OpVariable %ptr_map StorageBuffer -""" - counts = m.capacities() - out = m.rewrite(module, counts) - defs, _, decs = _parse_defs_and_order(out) - - self.assertEqual(defs["%msl_cap_b0"], f"OpConstant %uint {counts[0]}") - self.assertEqual(defs["%msl_arr_b0"], "OpTypeArray %img2d %msl_cap_b0") - self.assertEqual(defs["%msl_ptr_b0"], "OpTypePointer UniformConstant %msl_arr_b0") - self.assertEqual(defs["%images"], "OpVariable %msl_ptr_b0 UniformConstant") - - self.assertEqual(defs["%msl_cap_b1"], f"OpConstant %uint {counts[1]}") - self.assertEqual(defs["%msl_arr_b1"], "OpTypeArray %smp %msl_cap_b1") - self.assertEqual(defs["%msl_ptr_b1"], "OpTypePointer UniformConstant %msl_arr_b1") - self.assertEqual(defs["%samplers"], "OpVariable %msl_ptr_b1 UniformConstant") - self.assertEqual(defs["%desc_map"], "OpVariable %ptr_map StorageBuffer") - - bindings = {vid: val for vid, kind, val in decs if kind == "Binding"} - self.assertEqual(bindings, {"%images": 0, "%samplers": 4096, "%desc_map": 5120}) - - def test_distinct_element_type_aliases_at_same_binding(self): - # Mirrors tools/rdna2spirv.py emitting %images + typed %itx* aliases at binding 0 - # and %images_arr + %itx1_1 at binding 3, plus a 3D alias at binding 0. - module = """\ - OpDecorate %images DescriptorSet 0 - OpDecorate %images Binding 0 - OpDecorate %samplers DescriptorSet 0 - OpDecorate %samplers Binding 1 - OpDecorate %images_arr DescriptorSet 0 - OpDecorate %images_arr Binding 3 - OpDecorate %itx1_0 DescriptorSet 0 - OpDecorate %itx1_0 Binding 0 - OpDecorate %itx2_0 DescriptorSet 0 - OpDecorate %itx2_0 Binding 0 - OpDecorate %itx3d_0 DescriptorSet 0 - OpDecorate %itx3d_0 Binding 0 - OpDecorate %itx1_1 DescriptorSet 0 - OpDecorate %itx1_1 Binding 3 - %uint = OpTypeInt 32 0 - %int = OpTypeInt 32 1 - %float = OpTypeFloat 32 - %img2d = OpTypeImage %float 2D 0 0 0 1 Unknown - %smp = OpTypeSampler - %img2da = OpTypeImage %float 2D 0 1 0 1 Unknown - %itximg1_0 = OpTypeImage %uint 2D 0 0 0 1 Unknown - %itximg2_0 = OpTypeImage %int 2D 0 0 0 1 Unknown - %img_3d = OpTypeImage %float 3D 0 0 0 1 Unknown - %itximg1_1 = OpTypeImage %uint 2D 0 1 0 1 Unknown - %rt_img = OpTypeRuntimeArray %img2d - %ptr_img = OpTypePointer UniformConstant %rt_img - %rt_smp = OpTypeRuntimeArray %smp - %ptr_smp = OpTypePointer UniformConstant %rt_smp - %rt_imga = OpTypeRuntimeArray %img2da - %ptr_imga = OpTypePointer UniformConstant %rt_imga - %rt_itx10 = OpTypeRuntimeArray %itximg1_0 - %ptr_itx10 = OpTypePointer UniformConstant %rt_itx10 - %rt_itx20 = OpTypeRuntimeArray %itximg2_0 - %ptr_itx20 = OpTypePointer UniformConstant %rt_itx20 - %rt_3d0 = OpTypeRuntimeArray %img_3d - %ptr_3d0 = OpTypePointer UniformConstant %rt_3d0 - %rt_itx11 = OpTypeRuntimeArray %itximg1_1 - %ptr_itx11 = OpTypePointer UniformConstant %rt_itx11 - %images = OpVariable %ptr_img UniformConstant - %samplers = OpVariable %ptr_smp UniformConstant - %images_arr = OpVariable %ptr_imga UniformConstant - %itx1_0 = OpVariable %ptr_itx10 UniformConstant - %itx2_0 = OpVariable %ptr_itx20 UniformConstant - %itx3d_0 = OpVariable %ptr_3d0 UniformConstant - %itx1_1 = OpVariable %ptr_itx11 UniformConstant -""" - counts = m.capacities() - ids = m.metal_ids(counts) - out = m.rewrite(module, counts) - defs, _, decs = _parse_defs_and_order(out) - - # OpConstant is emitted once per binding that has UniformConstant runtime arrays. - b0_consts = [rid for rid, rhs in defs.items() if rhs == f"OpConstant %uint {counts[0]}"] - b1_b3_consts = [rid for rid, rhs in defs.items() if rhs == f"OpConstant %uint {counts[3]}"] - self.assertEqual(b0_consts, ["%msl_cap_b0"]) - self.assertEqual(counts[1], counts[3]) - self.assertEqual(b1_b3_consts, ["%msl_cap_b1", "%msl_cap_b3"]) - for b in (0, 1, 3): - self.assertEqual(out.count(f"%msl_cap_b{b} = "), 1) - - # Every variable keeps the exact element type of its original runtime array and binding capacity. - expected_vars = { - "%images": ("%img2d", "%msl_cap_b0", ids[0]), - "%samplers": ("%smp", "%msl_cap_b1", ids[1]), - "%images_arr": ("%img2da", "%msl_cap_b3", ids[3]), - "%itx1_0": ("%itximg1_0", "%msl_cap_b0", ids[0]), - "%itx2_0": ("%itximg2_0", "%msl_cap_b0", ids[0]), - "%itx3d_0": ("%img_3d", "%msl_cap_b0", ids[0]), - "%itx1_1": ("%itximg1_1", "%msl_cap_b3", ids[3]), - } - bindings = {vid: val for vid, kind, val in decs if kind == "Binding"} - seen_ptrs = set() - for var_id, (elem, cap, expected_bind) in expected_vars.items(): - self.assertEqual(bindings[var_id], expected_bind) - m_var = re.match(r"^OpVariable (%\S+) UniformConstant$", defs[var_id]) - self.assertIsNotNone(m_var, defs[var_id]) - ptr_id = m_var.group(1) - seen_ptrs.add(ptr_id) - m_ptr = re.match(r"^OpTypePointer UniformConstant (%\S+)$", defs[ptr_id]) - self.assertIsNotNone(m_ptr, defs[ptr_id]) - arr_id = m_ptr.group(1) - self.assertEqual(defs[arr_id], f"OpTypeArray {elem} {cap}") - - # Distinct element types get distinct pointer types. - self.assertEqual(len(seen_ptrs), len(expected_vars)) - - def test_reversed_decoration_order_still_declares_cap_before_first_array(self): - # %itx1_0 is decorated before %images, yet %ptr_img is declared before %ptr_itx. - module = """\ - OpDecorate %itx1_0 DescriptorSet 0 - OpDecorate %itx1_0 Binding 0 - OpDecorate %images DescriptorSet 0 - OpDecorate %images Binding 0 - %uint = OpTypeInt 32 0 - %int = OpTypeInt 32 1 - %float = OpTypeFloat 32 - %img2d = OpTypeImage %float 2D 0 0 0 1 Unknown - %itximg1_0 = OpTypeImage %int 2D 0 0 0 1 Unknown - %rt_img = OpTypeRuntimeArray %img2d - %ptr_img = OpTypePointer UniformConstant %rt_img - %rt_itx = OpTypeRuntimeArray %itximg1_0 - %ptr_itx = OpTypePointer UniformConstant %rt_itx - %images = OpVariable %ptr_img UniformConstant - %itx1_0 = OpVariable %ptr_itx UniformConstant -""" - out = m.rewrite(module, [4096]) - defs, def_line, decs = _parse_defs_and_order(out) - - self.assertLess(def_line["%msl_cap_b0"], def_line["%msl_arr_b0"]) - self.assertLess(def_line["%msl_cap_b0"], def_line["%msl_arr_b0_1"]) - self.assertEqual(defs["%images"], "OpVariable %msl_ptr_b0 UniformConstant") - self.assertEqual(defs["%itx1_0"], "OpVariable %msl_ptr_b0_1 UniformConstant") - self.assertEqual(defs["%msl_arr_b0"], "OpTypeArray %img2d %msl_cap_b0") - self.assertEqual(defs["%msl_arr_b0_1"], "OpTypeArray %itximg1_0 %msl_cap_b0") - self.assertEqual([(v, val) for v, k, val in decs if k == "Binding"], [("%itx1_0", 0), ("%images", 0)]) - - def test_same_binding_and_same_optypepointer_shares_sized_type_without_duplicates(self): - module = """\ - OpDecorate %images DescriptorSet 0 - OpDecorate %images Binding 0 - OpDecorate %alias DescriptorSet 0 - OpDecorate %alias Binding 0 - OpDecorate %single DescriptorSet 0 - OpDecorate %single Binding 0 - %uint = OpTypeInt 32 0 - %float = OpTypeFloat 32 - %img2d = OpTypeImage %float 2D 0 0 0 1 Unknown - %rt_img = OpTypeRuntimeArray %img2d - %ptr_img = OpTypePointer UniformConstant %rt_img - %ptr_one = OpTypePointer UniformConstant %img2d - %images = OpVariable %ptr_img UniformConstant - %alias = OpVariable %ptr_img UniformConstant - %single = OpVariable %ptr_one UniformConstant -""" - out = m.rewrite(module, [128]) - defs, _, decs = _parse_defs_and_order(out) - - self.assertEqual(defs["%msl_cap_b0"], "OpConstant %uint 128") - self.assertEqual(defs["%msl_arr_b0"], "OpTypeArray %img2d %msl_cap_b0") - self.assertEqual(defs["%msl_ptr_b0"], "OpTypePointer UniformConstant %msl_arr_b0") - self.assertEqual(defs["%images"], "OpVariable %msl_ptr_b0 UniformConstant") - self.assertEqual(defs["%alias"], "OpVariable %msl_ptr_b0 UniformConstant") - self.assertEqual(defs["%single"], "OpVariable %ptr_one UniformConstant") - self.assertEqual(out.count("%msl_cap_b0 = "), 1) - self.assertEqual(out.count("%msl_arr_b0 = "), 1) - self.assertEqual(out.count("%msl_ptr_b0 = "), 1) - self.assertEqual({v: val for v, k, val in decs if k == "Binding"}, - {"%images": 0, "%alias": 0, "%single": 0}) - - def test_same_binding_and_same_element_via_distinct_pointers(self): - module = """\ - OpDecorate %v1 DescriptorSet 0 - OpDecorate %v1 Binding 0 - OpDecorate %v2 DescriptorSet 0 - OpDecorate %v2 Binding 0 - %uint = OpTypeInt 32 0 - %float = OpTypeFloat 32 - %img2d = OpTypeImage %float 2D 0 0 0 1 Unknown - %rt_a = OpTypeRuntimeArray %img2d - %ptr_a = OpTypePointer UniformConstant %rt_a - %rt_b = OpTypeRuntimeArray %img2d - %ptr_b = OpTypePointer UniformConstant %rt_b - %v1 = OpVariable %ptr_a UniformConstant - %v2 = OpVariable %ptr_b UniformConstant -""" - out = m.rewrite(module, [64]) - defs, def_line, _ = _parse_defs_and_order(out) - - for var_id in ("%v1", "%v2"): - m_var = re.match(r"^OpVariable (%\S+) UniformConstant$", defs[var_id]) - self.assertIsNotNone(m_var) - ptr_id = m_var.group(1) - self.assertLess(def_line[ptr_id], def_line[var_id]) - m_ptr = re.match(r"^OpTypePointer UniformConstant (%\S+)$", defs[ptr_id]) - self.assertIsNotNone(m_ptr) - self.assertEqual(defs[m_ptr.group(1)], "OpTypeArray %img2d %msl_cap_b0") - - def test_late_uint_is_defined_before_the_synthesized_array_length(self) -> None: - module = """\ - OpDecorate %images DescriptorSet 0 - OpDecorate %images Binding 0 - %float = OpTypeFloat 32 - %img2d = OpTypeImage %float 2D 0 0 0 1 Unknown - %rt_img = OpTypeRuntimeArray %img2d - %ptr_img = OpTypePointer UniformConstant %rt_img - %images = OpVariable %ptr_img UniformConstant - %uint = OpTypeInt 32 0 - %old_count = OpConstant %uint 4 -""" - _parse_defs_and_order(module) - defs, _, _ = _parse_defs_and_order(m.rewrite(module, [64])) - - self.assertEqual(defs["%msl_cap_b0"], "OpConstant %uint 64") - self.assertEqual(defs["%images"], "OpVariable %msl_ptr_b0 UniformConstant") - self.assertEqual(defs["%old_count"], "OpConstant %uint 4") - - def test_preexisting_msl_ids_in_input_never_collide(self): - module = """\ - OpDecorate %images DescriptorSet 0 - OpDecorate %images Binding 0 - OpDecorate %itx1_0 DescriptorSet 0 - OpDecorate %itx1_0 Binding 0 - %uint = OpTypeInt 32 0 - %int = OpTypeInt 32 1 - %float = OpTypeFloat 32 -%msl_cap_b0 = OpConstant %uint 7 -%msl_arr_b0 = OpTypeFloat 16 -%msl_ptr_b0 = OpTypeStruct %float -%msl_arr_b0_1 = OpConstant %uint 9 - %img2d = OpTypeImage %float 2D 0 0 0 1 Unknown - %itximg1_0 = OpTypeImage %int 2D 0 0 0 1 Unknown - %rt_img = OpTypeRuntimeArray %img2d - %ptr_img = OpTypePointer UniformConstant %rt_img - %rt_itx = OpTypeRuntimeArray %itximg1_0 - %ptr_itx = OpTypePointer UniformConstant %rt_itx - %images = OpVariable %ptr_img UniformConstant - %itx1_0 = OpVariable %ptr_itx UniformConstant -""" - out = m.rewrite(module, [4096]) - defs, _, _ = _parse_defs_and_order(out) - - # Pre-existing IDs keep their original definitions untouched. - self.assertEqual(defs["%msl_cap_b0"], "OpConstant %uint 7") - self.assertEqual(defs["%msl_arr_b0"], "OpTypeFloat 16") - self.assertEqual(defs["%msl_ptr_b0"], "OpTypeStruct %float") - self.assertEqual(defs["%msl_arr_b0_1"], "OpConstant %uint 9") - - # Newly synthesized IDs avoid every existing definition and match each variable's element type. - m_img = re.match(r"^OpVariable (%\S+) UniformConstant$", defs["%images"]) - m_itx = re.match(r"^OpVariable (%\S+) UniformConstant$", defs["%itx1_0"]) - self.assertIsNotNone(m_img) - self.assertIsNotNone(m_itx) - ptr_img, ptr_itx = m_img.group(1), m_itx.group(1) - self.assertNotEqual(ptr_img, ptr_itx) - - arr_img = re.match(r"^OpTypePointer UniformConstant (%\S+)$", defs[ptr_img]).group(1) - arr_itx = re.match(r"^OpTypePointer UniformConstant (%\S+)$", defs[ptr_itx]).group(1) - cap_img = re.match(r"^OpTypeArray %img2d (%\S+)$", defs[arr_img]).group(1) - cap_itx = re.match(r"^OpTypeArray %itximg1_0 (%\S+)$", defs[arr_itx]).group(1) - self.assertEqual(cap_img, cap_itx) - self.assertEqual(defs[cap_img], "OpConstant %uint 4096") - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/test_spirv_metal_set0_cli_errors.py b/tests/test_spirv_metal_set0_cli_errors.py deleted file mode 100644 index 18a58e25a..000000000 --- a/tests/test_spirv_metal_set0_cli_errors.py +++ /dev/null @@ -1,109 +0,0 @@ -"""spirv_metal_set0.py on the command line: a SPIRV-Tools program that is missing or fails is one ERROR line. - - python -I tests/test_spirv_metal_set0_cli_errors.py - -`spirv_metal_set0.py in.spv out.spv` ended in a traceback when spirv-dis or spirv-as could not be started -(FileNotFoundError) or rejected its input (CalledProcessError). No SPIRV-Tools are needed here: SPIRV_DIS and -SPIRV_AS point at stand-ins. The Python interpreter is the one that works on every platform: as "spirv-dis" it runs -the input file, so an input that is a script printing two disassembly lines is a spirv-dis that succeeds, and a -missing input is one that fails; as "spirv-as" it rejects `--target-env` and fails. -""" -import contextlib -import io -import os -import subprocess -import sys -import tempfile -import unittest -from unittest import mock - -ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) -TOOL = os.path.join(ROOT, "tools", "spirv_metal_set0.py") -sys.path.insert(0, os.path.join(ROOT, "tools")) - -import spirv_metal_set0 as m # noqa: E402 - -PRINTS_A_DISASSEMBLY = 'print("; Version: 1.5")\nprint(" OpCapability Shader")\n' -HINT = "(SPIRV-Tools must be on PATH, or set SPIRV_DIS / SPIRV_AS)" - - -class CliErrorTest(unittest.TestCase): - def setUp(self): - self.tmp = tempfile.TemporaryDirectory() - self.addCleanup(self.tmp.cleanup) - self.src = os.path.join(self.tmp.name, "in.spv") - self.out = os.path.join(self.tmp.name, "out.spv") - self.missing = os.path.join(self.tmp.name, "no-such-spirv-tool") - with open(self.src, "w", encoding="utf-8", newline="\n") as f: - f.write(PRINTS_A_DISASSEMBLY) - - def run_tool(self, dis, asm, src=None): - env = dict(os.environ, SPIRV_DIS=dis, SPIRV_AS=asm) - # The tool is a Python child: piped, it writes in the locale encoding (the ANSI code page on Windows), so read - # it back in that encoding. UTF-8 would turn a non-ASCII temp path into replacement characters. - return subprocess.run([sys.executable, "-I", TOOL, src or self.src, self.out], env=env, capture_output=True, - text=True, errors="replace") - - def assert_failed(self, result): - self.assertEqual(result.returncode, 1, result.stdout + result.stderr) - self.assertNotIn("Traceback", result.stderr) - self.assertEqual(result.stdout, "") - self.assertFalse(os.path.exists(self.out)) - return result.stderr.splitlines() - - def test_spirv_dis_that_cannot_be_started(self): - lines = self.assert_failed(self.run_tool(self.missing, sys.executable)) - self.assertEqual(len(lines), 1, lines) - self.assertTrue(lines[0].startswith(f"ERROR: {self.missing}: "), lines) - self.assertTrue(lines[0].endswith(HINT), lines) - - def test_spirv_dis_that_rejects_the_input(self): - absent = os.path.join(self.tmp.name, "absent.spv") - lines = self.assert_failed(self.run_tool(sys.executable, sys.executable, src=absent)) - self.assertEqual(len(lines), 1, lines) - # The stand-in's own complaint about the file follows the exit status. - self.assertTrue(lines[0].startswith(f"ERROR: {sys.executable} failed with exit status 2: "), lines) - self.assertIn("absent.spv", lines[0]) - - def test_spirv_as_that_cannot_be_started(self): - lines = self.assert_failed(self.run_tool(sys.executable, self.missing)) - self.assertEqual(len(lines), 1, lines) - self.assertTrue(lines[0].startswith(f"ERROR: {self.missing}: "), lines) - self.assertTrue(lines[0].endswith(HINT), lines) - - def test_spirv_as_that_fails(self): - lines = self.assert_failed(self.run_tool(sys.executable, sys.executable)) - # spirv-as writes to the terminal itself; the tool's own line comes last. - self.assertEqual(lines[-1], f"ERROR: {sys.executable} failed with exit status 2") - self.assertEqual([line for line in lines if line.startswith("ERROR: ")], lines[-1:]) - - def test_usage_and_layout_still_work_through_cli(self): - usage = "Usage: spirv_metal_set0.py in.spv out.spv" - for args, code, expected in ((["--print-layout"], 0, "binding 0: 4096 descriptors"), (["--help"], 0, usage), - ([], 2, usage), (["only.spv"], 2, usage)): - with self.subTest(args=args): - out, err = io.StringIO(), io.StringIO() - with contextlib.redirect_stdout(out), contextlib.redirect_stderr(err): - self.assertEqual(m.cli(["spirv_metal_set0.py", *args]), code) - self.assertIn(expected, (err if code else out).getvalue()) - self.assertEqual((out if code else err).getvalue(), "") - - def test_cli_reports_the_first_line_the_program_wrote(self): - failure = subprocess.CalledProcessError(1, ["spirv-dis", "in.spv"], stderr="\n error: 1: bad\nmore\n") - err = io.StringIO() - with mock.patch.object(m.subprocess, "run", side_effect=failure), contextlib.redirect_stderr(err): - self.assertEqual(m.cli(["spirv_metal_set0.py", "in.spv", "out.spv"]), 1) - self.assertEqual(err.getvalue(), "ERROR: spirv-dis failed with exit status 1: error: 1: bad\n") - - def test_an_unreadable_file_of_the_tool_itself_is_not_blamed_on_spirv_tools(self): - absent = os.path.join(self.tmp.name, "vulkan_bindless.h") - capacities, err = m.capacities, io.StringIO() - with mock.patch.object(m, "capacities", side_effect=lambda: capacities(absent)), \ - contextlib.redirect_stderr(err): - self.assertEqual(m.cli(["spirv_metal_set0.py", "in.spv", "out.spv"]), 1) - self.assertTrue(err.getvalue().startswith(f"ERROR: {absent}: "), err.getvalue()) - self.assertNotIn("SPIRV-Tools", err.getvalue()) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/test_spirv_metal_set0_extra.py b/tests/test_spirv_metal_set0_extra.py deleted file mode 100644 index 5f8b63c62..000000000 --- a/tests/test_spirv_metal_set0_extra.py +++ /dev/null @@ -1,1043 +0,0 @@ -"""Expanded stdlib-only unit tests for tools/spirv_metal_set0.py. - -Covers bindless capacity parsing from vulkan_bindless.h and custom headers, -metal_ids() layout math, rewrite() across all 26 bindings, non-set-0 / -push-constant / non-runtime-array / pre-sized / raw-ID / error branches, -synthetic SPIR-V binary word header/magic/endianness/bounds handling, -out-of-place vs in-place CLI execution via mocked spirv-dis/spirv-as, ---print-layout, invalid argument handling, and __main__ entry guard. - -Standard library only; no spirv-dis/spirv-as/spirv-val binary, no GPU, -and no game data. - - python -I tests/test_spirv_metal_set0_extra.py -v -""" -import contextlib -import io -import os -import re -import runpy -import struct -import subprocess -import sys -import tempfile -import unittest -from unittest import mock -import warnings - -ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) -TOOLS_DIR = os.path.join(ROOT, "tools") -TOOL_PATH = os.path.join(TOOLS_DIR, "spirv_metal_set0.py") -if TOOLS_DIR not in sys.path: - sys.path.insert(0, TOOLS_DIR) - -import spirv_metal_set0 as m # noqa: E402 - - -SPIRV_MAGIC = 0x07230203 -SPIRV_VERSION_1_0 = 0x00010000 -SPIRV_VERSION_1_5 = 0x00010500 - -OP_MEMORY_MODEL = 14 -OP_CAPABILITY = 17 -OP_TYPE_VOID = 19 -OP_TYPE_INT = 21 -OP_TYPE_FLOAT = 22 -OP_TYPE_IMAGE = 25 -OP_TYPE_SAMPLER = 26 -OP_TYPE_ARRAY = 28 -OP_TYPE_RUNTIME_ARRAY = 29 -OP_TYPE_STRUCT = 30 -OP_TYPE_POINTER = 32 -OP_CONSTANT = 43 -OP_VARIABLE = 59 -OP_DECORATE = 71 - -CAP_SHADER = 1 -CAP_RUNTIME_DESCRIPTOR_ARRAY = 5301 -ADDR_LOGICAL = 0 -MEM_GLSL450 = 1 - -DEC_BLOCK = 2 -DEC_BINDING = 33 -DEC_DESCRIPTOR_SET = 34 - -SC_UNIFORM_CONSTANT = 0 -SC_PUSH_CONSTANT = 9 -SC_STORAGE_BUFFER = 12 - -STORAGE_CLASS_BY_NAME = { - "UniformConstant": SC_UNIFORM_CONSTANT, - "PushConstant": SC_PUSH_CONSTANT, - "StorageBuffer": SC_STORAGE_BUFFER, -} -STORAGE_CLASS_BY_CODE = {v: k for k, v in STORAGE_CLASS_BY_NAME.items()} - -DIM_BY_CODE = {0: "1D", 1: "2D", 2: "3D"} -DIM_BY_NAME = {v: k for k, v in DIM_BY_CODE.items()} - -FMT_BY_CODE = {0: "Unknown", 33: "R32ui"} -FMT_BY_NAME = {v: k for k, v in FMT_BY_CODE.items()} - - -def _encode_inst(opcode: int, *operands: int) -> list[int]: - """Encode one SPIR-V instruction into 32-bit binary words.""" - wc = 1 + len(operands) - return [(wc << 16) | opcode, *operands] - - -def _pack_spv( - inst_words: list[int], - *, - version: int = SPIRV_VERSION_1_5, - generator: int = 0, - bound: int | None = None, - schema: int = 0, - endian: str = "<", -) -> bytes: - """Pack a 5-word SPIR-V header and instruction stream into binary bytes.""" - if bound is None: - max_id = 0 - pos = 0 - while pos < len(inst_words): - wc = inst_words[pos] >> 16 - op = inst_words[pos] & 0xFFFF - if wc < 1 or pos + wc > len(inst_words): - break - ops = inst_words[pos + 1 : pos + wc] - if op in (OP_TYPE_VOID, OP_TYPE_INT, OP_TYPE_FLOAT, OP_TYPE_IMAGE, OP_TYPE_SAMPLER, - OP_TYPE_ARRAY, OP_TYPE_RUNTIME_ARRAY, OP_TYPE_STRUCT, OP_TYPE_POINTER): - max_id = max(max_id, ops[0]) - elif op in (OP_CONSTANT, OP_VARIABLE): - max_id = max(max_id, ops[1]) - elif op == OP_DECORATE: - max_id = max(max_id, ops[0]) - pos += wc - bound = max_id + 1 - words = [SPIRV_MAGIC, version, generator, bound, schema, *inst_words] - return struct.pack(f"{endian}{len(words)}I", *words) - - -def _decode_spv(data: bytes) -> tuple[tuple[int, int, int, int, int], list[tuple[int, list[int]]]]: - """Validate SPIR-V binary header/endianness/word-bounds and decode instructions.""" - if len(data) < 20 or len(data) % 4 != 0: - raise ValueError(f"invalid SPIR-V byte length: {len(data)}") - words = list(struct.unpack(f"<{len(data) // 4}I", data)) - magic, version, generator, bound, schema = words[:5] - if magic == 0x03022307: - raise ValueError("wrong endianness (big-endian SPIR-V magic)") - if magic != SPIRV_MAGIC: - raise ValueError(f"bad SPIR-V magic: {magic:#010x}") - if bound < 1: - raise ValueError(f"invalid SPIR-V ID bound: {bound}") - if schema != 0: - raise ValueError(f"unsupported non-zero schema: {schema}") - insts = [] - pos = 5 - while pos < len(words): - wc = words[pos] >> 16 - op = words[pos] & 0xFFFF - if wc < 1 or pos + wc > len(words): - raise ValueError(f"truncated or zero-length instruction at word {pos}") - insts.append((op, words[pos + 1 : pos + wc])) - pos += wc - return (magic, version, generator, bound, schema), insts - - -def _synthetic_spv_to_disasm(data: bytes) -> str: - """Decode synthetic SPIR-V binary words into spirv-dis-style assembly text.""" - header, insts = _decode_spv(data) - _, version, generator, bound, schema = header - major = (version >> 16) & 0xFF - minor = (version >> 8) & 0xFF - lines = [ - "; SPIR-V", - f"; Version: {major}.{minor}", - f"; Generator: {generator}", - f"; Bound: {bound}", - f"; Schema: {schema}", - ] - indent = " " * 15 - def lhs(res_id: int) -> str: - return f"%{res_id}".rjust(12) - - for op, ops in insts: - if op == OP_CAPABILITY: - name = {CAP_SHADER: "Shader", CAP_RUNTIME_DESCRIPTOR_ARRAY: "RuntimeDescriptorArray"}[ops[0]] - lines.append(f"{indent}OpCapability {name}") - elif op == OP_MEMORY_MODEL: - lines.append(f"{indent}OpMemoryModel Logical GLSL450") - elif op == OP_DECORATE: - if ops[1] == DEC_DESCRIPTOR_SET: - lines.append(f"{indent}OpDecorate %{ops[0]} DescriptorSet {ops[2]}") - elif ops[1] == DEC_BINDING: - lines.append(f"{indent}OpDecorate %{ops[0]} Binding {ops[2]}") - elif ops[1] == DEC_BLOCK: - lines.append(f"{indent}OpDecorate %{ops[0]} Block") - else: - raise ValueError(f"unsupported decoration {ops[1]}") - elif op == OP_TYPE_VOID: - lines.append(f"{lhs(ops[0])} = OpTypeVoid") - elif op == OP_TYPE_INT: - lines.append(f"{lhs(ops[0])} = OpTypeInt {ops[1]} {ops[2]}") - elif op == OP_TYPE_FLOAT: - lines.append(f"{lhs(ops[0])} = OpTypeFloat {ops[1]}") - elif op == OP_TYPE_IMAGE: - dim = DIM_BY_CODE[ops[2]] - fmt = FMT_BY_CODE[ops[7]] - lines.append( - f"{lhs(ops[0])} = OpTypeImage %{ops[1]} {dim} {ops[3]} {ops[4]} {ops[5]} {ops[6]} {fmt}" - ) - elif op == OP_TYPE_SAMPLER: - lines.append(f"{lhs(ops[0])} = OpTypeSampler") - elif op == OP_TYPE_ARRAY: - lines.append(f"{lhs(ops[0])} = OpTypeArray %{ops[1]} %{ops[2]}") - elif op == OP_TYPE_RUNTIME_ARRAY: - lines.append(f"{lhs(ops[0])} = OpTypeRuntimeArray %{ops[1]}") - elif op == OP_TYPE_STRUCT: - members = " ".join(f"%{m_id}" for m_id in ops[1:]) - lines.append(f"{lhs(ops[0])} = OpTypeStruct {members}".rstrip()) - elif op == OP_TYPE_POINTER: - sc = STORAGE_CLASS_BY_CODE[ops[1]] - lines.append(f"{lhs(ops[0])} = OpTypePointer {sc} %{ops[2]}") - elif op == OP_CONSTANT: - lines.append(f"{lhs(ops[1])} = OpConstant %{ops[0]} {ops[2]}") - elif op == OP_VARIABLE: - sc = STORAGE_CLASS_BY_CODE[ops[2]] - lines.append(f"{lhs(ops[1])} = OpVariable %{ops[0]} {sc}") - else: - raise ValueError(f"unsupported opcode {op}") - return "\n".join(lines) + "\n" - - -def _synthetic_disasm_to_spv(text: str, target_env: str) -> bytes: - """Assemble synthetic spirv-dis text (including rewritten %msl_* IDs) into SPIR-V words.""" - id_map: dict[str, int] = {} - next_id = 1 - - def resolve(tok: str) -> int: - nonlocal next_id - if tok in id_map: - return id_map[tok] - if tok[1:].isdigit(): - val = int(tok[1:]) - id_map[tok] = val - next_id = max(next_id, val + 1) - return val - val = next_id - next_id += 1 - id_map[tok] = val - return val - - # Pre-register numeric IDs so newly synthesized %msl_* names never collide. - for tok in re.findall(r"%\S+", text): - if tok[1:].isdigit(): - resolve(tok) - - inst_words: list[int] = [] - for raw in text.splitlines(): - line = raw.strip() - if not line or line.startswith(";"): - continue - if line.startswith("OpCapability "): - cap = {"Shader": CAP_SHADER, "RuntimeDescriptorArray": CAP_RUNTIME_DESCRIPTOR_ARRAY}[line.split()[1]] - inst_words.extend(_encode_inst(OP_CAPABILITY, cap)) - elif line == "OpMemoryModel Logical GLSL450": - inst_words.extend(_encode_inst(OP_MEMORY_MODEL, ADDR_LOGICAL, MEM_GLSL450)) - elif line.startswith("OpDecorate "): - parts = line.split() - tid = resolve(parts[1]) - if parts[2] == "DescriptorSet": - inst_words.extend(_encode_inst(OP_DECORATE, tid, DEC_DESCRIPTOR_SET, int(parts[3]))) - elif parts[2] == "Binding": - inst_words.extend(_encode_inst(OP_DECORATE, tid, DEC_BINDING, int(parts[3]))) - elif parts[2] == "Block": - inst_words.extend(_encode_inst(OP_DECORATE, tid, DEC_BLOCK)) - else: - raise ValueError(f"unsupported OpDecorate: {line}") - else: - lhs, rhs = [p.strip() for p in line.split("=", 1)] - rid = resolve(lhs) - parts = rhs.split() - opname = parts[0] - if opname == "OpTypeVoid": - inst_words.extend(_encode_inst(OP_TYPE_VOID, rid)) - elif opname == "OpTypeInt": - inst_words.extend(_encode_inst(OP_TYPE_INT, rid, int(parts[1]), int(parts[2]))) - elif opname == "OpTypeFloat": - inst_words.extend(_encode_inst(OP_TYPE_FLOAT, rid, int(parts[1]))) - elif opname == "OpTypeImage": - inst_words.extend(_encode_inst( - OP_TYPE_IMAGE, - rid, - resolve(parts[1]), - DIM_BY_NAME[parts[2]], - int(parts[3]), - int(parts[4]), - int(parts[5]), - int(parts[6]), - FMT_BY_NAME[parts[7]], - )) - elif opname == "OpTypeSampler": - inst_words.extend(_encode_inst(OP_TYPE_SAMPLER, rid)) - elif opname == "OpTypeArray": - inst_words.extend(_encode_inst(OP_TYPE_ARRAY, rid, resolve(parts[1]), resolve(parts[2]))) - elif opname == "OpTypeRuntimeArray": - inst_words.extend(_encode_inst(OP_TYPE_RUNTIME_ARRAY, rid, resolve(parts[1]))) - elif opname == "OpTypeStruct": - inst_words.extend(_encode_inst(OP_TYPE_STRUCT, rid, *[resolve(p) for p in parts[1:]])) - elif opname == "OpTypePointer": - inst_words.extend(_encode_inst(OP_TYPE_POINTER, rid, STORAGE_CLASS_BY_NAME[parts[1]], resolve(parts[2]))) - elif opname == "OpConstant": - inst_words.extend(_encode_inst(OP_CONSTANT, resolve(parts[1]), rid, int(parts[2]))) - elif opname == "OpVariable": - inst_words.extend(_encode_inst(OP_VARIABLE, resolve(parts[1]), rid, STORAGE_CLASS_BY_NAME[parts[2]])) - else: - raise ValueError(f"unsupported op: {line}") - - ver = SPIRV_VERSION_1_5 if target_env == "spv1.5" else SPIRV_VERSION_1_0 - return _pack_spv(inst_words, version=ver, bound=next_id) - - -def _build_mixed_bindless_spv_words() -> list[int]: - """Build synthetic SPIR-V instruction words with set-0, set-1, and PushConstant resources.""" - # IDs: - # 1=uint, 2=float, 3=img2d, 4=smp, 5=rt_img, 6=rt_smp, 7=ptr_img, 8=ptr_smp - # 9=rt_map, 10=struct_map, 11=ptr_map, 12=ptr_pc_u32 - # 13=images (set 0, b0), 14=samplers (set 0, b1), 15=desc_map (set 0, b2) - # 16=push_consts, 17=set1_var (set 1, b0) - words: list[int] = [] - words.extend(_encode_inst(OP_CAPABILITY, CAP_SHADER)) - words.extend(_encode_inst(OP_CAPABILITY, CAP_RUNTIME_DESCRIPTOR_ARRAY)) - words.extend(_encode_inst(OP_MEMORY_MODEL, ADDR_LOGICAL, MEM_GLSL450)) - words.extend(_encode_inst(OP_DECORATE, 13, DEC_DESCRIPTOR_SET, 0)) - words.extend(_encode_inst(OP_DECORATE, 13, DEC_BINDING, 0)) - words.extend(_encode_inst(OP_DECORATE, 14, DEC_DESCRIPTOR_SET, 0)) - words.extend(_encode_inst(OP_DECORATE, 14, DEC_BINDING, 1)) - words.extend(_encode_inst(OP_DECORATE, 15, DEC_DESCRIPTOR_SET, 0)) - words.extend(_encode_inst(OP_DECORATE, 15, DEC_BINDING, 2)) - words.extend(_encode_inst(OP_DECORATE, 10, DEC_BLOCK)) - words.extend(_encode_inst(OP_DECORATE, 17, DEC_DESCRIPTOR_SET, 1)) - words.extend(_encode_inst(OP_DECORATE, 17, DEC_BINDING, 0)) - words.extend(_encode_inst(OP_TYPE_INT, 1, 32, 0)) - words.extend(_encode_inst(OP_TYPE_FLOAT, 2, 32)) - words.extend(_encode_inst(OP_TYPE_IMAGE, 3, 2, 1, 0, 0, 0, 1, 0)) - words.extend(_encode_inst(OP_TYPE_SAMPLER, 4)) - words.extend(_encode_inst(OP_TYPE_RUNTIME_ARRAY, 5, 3)) - words.extend(_encode_inst(OP_TYPE_RUNTIME_ARRAY, 6, 4)) - words.extend(_encode_inst(OP_TYPE_POINTER, 7, SC_UNIFORM_CONSTANT, 5)) - words.extend(_encode_inst(OP_TYPE_POINTER, 8, SC_UNIFORM_CONSTANT, 6)) - words.extend(_encode_inst(OP_TYPE_RUNTIME_ARRAY, 9, 1)) - words.extend(_encode_inst(OP_TYPE_STRUCT, 10, 9)) - words.extend(_encode_inst(OP_TYPE_POINTER, 11, SC_STORAGE_BUFFER, 10)) - words.extend(_encode_inst(OP_TYPE_POINTER, 12, SC_PUSH_CONSTANT, 1)) - words.extend(_encode_inst(OP_VARIABLE, 7, 13, SC_UNIFORM_CONSTANT)) - words.extend(_encode_inst(OP_VARIABLE, 8, 14, SC_UNIFORM_CONSTANT)) - words.extend(_encode_inst(OP_VARIABLE, 11, 15, SC_STORAGE_BUFFER)) - words.extend(_encode_inst(OP_VARIABLE, 12, 16, SC_PUSH_CONSTANT)) - words.extend(_encode_inst(OP_VARIABLE, 7, 17, SC_UNIFORM_CONSTANT)) - return words - - -def _make_fake_spirv_tools(dis_name="spirv-dis", asm_name="spirv-as"): - """Return a subprocess.run replacement backed by the synthetic SPIR-V binary codec.""" - calls: list[list[str]] = [] - - def fake_run(cmd, check=False, capture_output=False, text=False, input=None, errors=None): - calls.append(list(cmd)) - exe = cmd[0] - if exe == dis_name: - in_path = cmd[1] - try: - with open(in_path, "rb") as f: - data = f.read() - disasm = _synthetic_spv_to_disasm(data) - except (OSError, ValueError) as exc: - if check: - raise subprocess.CalledProcessError(1, cmd, output="", stderr=str(exc)) from exc - return subprocess.CompletedProcess(cmd, 1, "", str(exc)) - return subprocess.CompletedProcess(cmd, 0, disasm, "") - if exe == asm_name: - # Expect: [asm, "--target-env", target, "-", "-o", out_path] - target_env = cmd[cmd.index("--target-env") + 1] - out_path = cmd[cmd.index("-o") + 1] - try: - out_bytes = _synthetic_disasm_to_spv(input, target_env) - with open(out_path, "wb") as f: - f.write(out_bytes) - except (OSError, ValueError) as exc: - if check: - raise subprocess.CalledProcessError(1, cmd, output="", stderr=str(exc)) from exc - return subprocess.CompletedProcess(cmd, 1, "", str(exc)) - return subprocess.CompletedProcess(cmd, 0, "", "") - raise AssertionError(f"unexpected subprocess command: {cmd!r}") - - return fake_run, calls - - -class TestCapacities(unittest.TestCase): - def test_default_bindless_header_all_26_entries_and_cross_check(self): - counts = m.capacities() - expected = [4096, 1024, 1, 1024, 1024] + [256] * 21 - self.assertEqual(counts, expected) - self.assertEqual(len(counts), 26) - self.assertEqual(sum(counts), 12545) - - with open(m.BINDLESS_H, encoding="utf-8") as f: - hdr = f.read() - self.assertIn("inline constexpr std::uint32_t binding_count = 26;", hdr) - self.assertIn("inline constexpr std::array bindings =", hdr) - - def test_custom_header_parsing_variants(self): - cases = [ - ("empty_table", "std::array bindings = {{}};\n", []), - ( - "single_line", - "std::array bindings = {{{VK_DESCRIPTOR_TYPE_SAMPLER, 7}}};\n", - [7], - ), - ( - "multiline_mixed_types_and_comments", - """ - // unrelated header prefix - inline constexpr std::array bindings = {{ - {VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE, 128}, - {VK_DESCRIPTOR_TYPE_SAMPLER, 32}, - {VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, 1}, - {VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, 64}, - }}; - """, - [128, 32, 1, 64], - ), - ] - with tempfile.TemporaryDirectory() as tmp: - for name, body, expected in cases: - with self.subTest(case=name): - p = os.path.join(tmp, f"{name}.h") - with open(p, "w", encoding="utf-8") as f: - f.write(body) - self.assertEqual(m.capacities(p), expected) - - def test_missing_file_raises_file_not_found(self): - with tempfile.TemporaryDirectory() as tmp: - missing = os.path.join(tmp, "missing_bindless.h") - with self.assertRaises(FileNotFoundError): - m.capacities(missing) - - def test_missing_or_mismatched_bindings_table_raises_system_exit(self): - bad_headers = [ - ("empty_file", "", "no `bindings` table"), - ("wrong_type_name", "std::array bindings = {{ {VK_DESCRIPTOR_TYPE_SAMPLER, 4} }};", "no `bindings` table"), - ( - "too_few_entries", - "std::array bindings = {{ {VK_DESCRIPTOR_TYPE_SAMPLER, 1}, {VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE, 2} }};", - "`bindings` declares 3 entries, found 2", - ), - ( - "too_many_entries", - "std::array bindings = {{ {VK_DESCRIPTOR_TYPE_SAMPLER, 1}, {VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE, 2} }};", - "`bindings` declares 1 entries, found 2", - ), - ( - "unmatched_entry_syntax", - "std::array bindings = {{ {NOT_A_VK_DESCRIPTOR, 1} }};", - "`bindings` declares 1 entries, found 0", - ), - ] - with tempfile.TemporaryDirectory() as tmp: - for name, body, msg_part in bad_headers: - with self.subTest(case=name): - p = os.path.join(tmp, f"{name}.h") - with open(p, "w", encoding="utf-8") as f: - f.write(body) - with self.assertRaises(SystemExit) as ctx: - m.capacities(p) - self.assertIn(p, str(ctx.exception)) - self.assertIn(msg_part, str(ctx.exception)) - - -class TestMetalIds(unittest.TestCase): - def test_empty_single_and_zero_capacities(self): - self.assertEqual(m.metal_ids([]), []) - self.assertEqual(m.metal_ids([42]), [0]) - self.assertEqual(m.metal_ids([10, 0, 5, 0, 1]), [0, 10, 10, 15, 15]) - - def test_vulkan_bindless_ids_contiguous_and_non_overlapping(self): - counts = m.capacities() - ids = m.metal_ids(counts) - self.assertEqual(len(ids), 26) - self.assertEqual(ids[0], 0) - self.assertEqual(ids[:6], [0, 4096, 5120, 5121, 6145, 7169]) - self.assertEqual(ids[8], 7937) - self.assertEqual(ids[20], 11009) - self.assertEqual(ids[25], 12289) - for b in range(len(counts) - 1): - self.assertEqual(ids[b + 1], ids[b] + counts[b]) - self.assertEqual(ids[-1] + counts[-1], sum(counts)) - - seen_total = 0 - for b in range(len(counts)): - if b > 0: - self.assertGreater(ids[b], ids[b - 1] + counts[b - 1] - 1) - seen_total += counts[b] - self.assertEqual(seen_total, 12545) - - -class TestRewrite(unittest.TestCase): - def test_all_26_vulkan_bindless_bindings(self): - counts = m.capacities() - ids = m.metal_ids(counts) - lines = [ - " OpCapability Shader", - " OpCapability RuntimeDescriptorArray", - " OpMemoryModel Logical GLSL450", - ] - for b in range(26): - lines.append(f" OpDecorate %v{b} DescriptorSet 0") - lines.append(f" OpDecorate %v{b} Binding {b}") - lines.extend([ - " %uint = OpTypeInt 32 0", - " %float = OpTypeFloat 32", - " %img2d = OpTypeImage %float 2D 0 0 0 1 Unknown", - " %smp = OpTypeSampler", - " %rt_map = OpTypeRuntimeArray %uint", - " %map = OpTypeStruct %rt_map", - " %ptr_map = OpTypePointer StorageBuffer %map", - ]) - for b in range(26): - if b == 2: - continue - elem = "%smp" if b == 1 else "%img2d" - lines.append(f" %rt_b{b} = OpTypeRuntimeArray {elem}") - lines.append(f" %ptr_b{b} = OpTypePointer UniformConstant %rt_b{b}") - for b in range(26): - if b == 2: - lines.append(" %v2 = OpVariable %ptr_map StorageBuffer") - else: - lines.append(f" %v{b} = OpVariable %ptr_b{b} UniformConstant") - - out = m.rewrite("\n".join(lines) + "\n", counts) - out_lines = out.splitlines() - - for b in range(26): - self.assertIn(f" OpDecorate %v{b} Binding {ids[b]}", out_lines) - if b == 2: - self.assertIn(" %v2 = OpVariable %ptr_map StorageBuffer", out_lines) - self.assertNotIn("%msl_cap_b2 ", out) - self.assertNotIn("%msl_arr_b2 ", out) - self.assertNotIn("%msl_ptr_b2 ", out) - else: - elem = "%smp" if b == 1 else "%img2d" - cap_line = f"%msl_cap_b{b} = OpConstant %uint {counts[b]}" - arr_line = f"%msl_arr_b{b} = OpTypeArray {elem} %msl_cap_b{b}" - ptr_line = f"%msl_ptr_b{b} = OpTypePointer UniformConstant %msl_arr_b{b}" - orig_ptr_line = f" %ptr_b{b} = OpTypePointer UniformConstant %rt_b{b}" - idx = out_lines.index(orig_ptr_line) - self.assertEqual(out_lines[idx + 1 : idx + 4], [cap_line, arr_line, ptr_line]) - self.assertIn(f" %v{b} = OpVariable %msl_ptr_b{b} UniformConstant", out_lines) - - def test_push_constants_and_other_descriptor_sets_untouched(self): - module = """\ - OpDecorate %set0_img DescriptorSet 0 - OpDecorate %set0_img Binding 0 - OpDecorate %set0_smp DescriptorSet 0 - OpDecorate %set0_smp Binding 1 - OpDecorate %set1_in DescriptorSet 1 - OpDecorate %set1_in Binding 0 - OpDecorate %set1_high DescriptorSet 1 - OpDecorate %set1_high Binding 99 - OpDecorate %set2_uc DescriptorSet 2 - OpDecorate %set2_uc Binding 0 - %uint = OpTypeInt 32 0 - %float = OpTypeFloat 32 - %img2d = OpTypeImage %float 2D 0 0 0 1 Unknown - %smp = OpTypeSampler - %rt_img = OpTypeRuntimeArray %img2d - %rt_smp = OpTypeRuntimeArray %smp - %ptr_img = OpTypePointer UniformConstant %rt_img - %ptr_smp = OpTypePointer UniformConstant %rt_smp - %ptr_pc = OpTypePointer PushConstant %uint - %ptr_s1hi = OpTypePointer UniformConstant %rt_img - %ptr_s2uc = OpTypePointer UniformConstant %rt_img - %set0_img = OpVariable %ptr_img UniformConstant - %set0_smp = OpVariable %ptr_smp UniformConstant - %user_data = OpVariable %ptr_pc PushConstant - %set1_in = OpVariable %ptr_img StorageBuffer - %set1_high = OpVariable %ptr_s1hi UniformConstant - %set2_uc = OpVariable %ptr_s2uc UniformConstant -""" - out = m.rewrite(module, [8, 4]) - self.assertIn("OpDecorate %set0_img Binding 0", out) - self.assertIn("OpDecorate %set0_smp Binding 8", out) - # Set 1 (including binding 99 >= len(counts)), Set 2, and PushConstant stay untouched. - self.assertIn("OpDecorate %set1_in DescriptorSet 1", out) - self.assertIn("OpDecorate %set1_in Binding 0", out) - self.assertIn("OpDecorate %set1_high DescriptorSet 1", out) - self.assertIn("OpDecorate %set1_high Binding 99", out) - self.assertIn("OpDecorate %set2_uc DescriptorSet 2", out) - self.assertIn("OpDecorate %set2_uc Binding 0", out) - self.assertIn("%user_data = OpVariable %ptr_pc PushConstant", out) - self.assertIn("%set1_in = OpVariable %ptr_img StorageBuffer", out) - self.assertIn("%set1_high = OpVariable %ptr_s1hi UniformConstant", out) - self.assertIn("%set2_uc = OpVariable %ptr_s2uc UniformConstant", out) - - def test_non_runtime_array_set0_resources_rebind_without_retyping_or_uint32(self): - # No OpTypeInt 32 0 is present, yet none of these set-0 bindings use OpTypeRuntimeArray - # under OpTypePointer UniformConstant, so rewriting succeeds without raising. - module = """\ - OpDecorate %single DescriptorSet 0 - OpDecorate %single Binding 0 - OpDecorate %fixed DescriptorSet 0 - OpDecorate %fixed Binding 1 - OpDecorate %ubo DescriptorSet 0 - OpDecorate %ubo Binding 2 - OpDecorate %mismatch DescriptorSet 0 - OpDecorate %mismatch Binding 3 - OpDecorate %dangling DescriptorSet 0 - OpDecorate %dangling Binding 4 - %float = OpTypeFloat 32 - %img2d = OpTypeImage %float 2D 0 0 0 1 Unknown - %sint = OpTypeInt 32 1 - %c16 = OpConstant %sint 16 - %fixed_arr = OpTypeArray %img2d %c16 - %ubo_blk = OpTypeStruct %float - %ptr_single = OpTypePointer UniformConstant %img2d - %ptr_fixed = OpTypePointer UniformConstant %fixed_arr - %ptr_ubo = OpTypePointer Uniform %ubo_blk - %ptr_mis_sb = OpTypePointer StorageBuffer %fixed_arr -%ptr_dangling = OpTypePointer UniformConstant %missing_pointee - %single = OpVariable %ptr_single UniformConstant - %fixed = OpVariable %ptr_fixed UniformConstant - %ubo = OpVariable %ptr_ubo Uniform - %mismatch = OpVariable %ptr_mis_sb UniformConstant - %dangling = OpVariable %ptr_dangling UniformConstant -""" - counts = [10, 20, 1, 5, 2] - out = m.rewrite(module, counts) - self.assertIn("OpDecorate %single Binding 0", out) - self.assertIn("OpDecorate %fixed Binding 10", out) - self.assertIn("OpDecorate %ubo Binding 30", out) - self.assertIn("OpDecorate %mismatch Binding 31", out) - self.assertIn("OpDecorate %dangling Binding 36", out) - self.assertIn("%single = OpVariable %ptr_single UniformConstant", out) - self.assertIn("%fixed = OpVariable %ptr_fixed UniformConstant", out) - self.assertIn("%ubo = OpVariable %ptr_ubo Uniform", out) - self.assertIn("%mismatch = OpVariable %ptr_mis_sb UniformConstant", out) - self.assertIn("%dangling = OpVariable %ptr_dangling UniformConstant", out) - self.assertNotIn("%msl_", out) - - def test_partial_decorations_and_missing_var_def(self): - module = """\ -OpDecorate %only_set DescriptorSet 0 -OpDecorate %only_bind Binding 1 -OpDecorate %orphan DescriptorSet 0 -OpDecorate %orphan Binding 1 -%u = OpTypeInt 32 0 -""" - out = m.rewrite(module, [5, 7]) - self.assertIn("OpDecorate %only_set DescriptorSet 0", out) - self.assertIn("OpDecorate %only_bind Binding 1", out) - self.assertIn("OpDecorate %orphan Binding 5", out) - self.assertNotIn("%msl_", out) - - def test_raw_numeric_ids_custom_uint_and_crlf_and_shared_pointer(self): - module = ( - "; Header comment\r\n" - "OpName %10 \"images\"\r\n" - "OpDecorate %10 DescriptorSet 0\r\n" - "OpDecorate %10 Binding 1\r\n" - "OpDecorate %11 DescriptorSet 0\r\n" - "OpDecorate %11 Binding 0\r\n" - "%1 = OpTypeVoid\r\n" - "%2 = OpTypeInt 32 1\r\n" - "%3 = OpTypeInt 64 0\r\n" - "%4 = OpTypeInt 32 0\r\n" - "%5 = OpTypeFloat 32\r\n" - "%6 = OpTypeImage %5 2D 0 0 0 1 Unknown\r\n" - "%7 = OpTypeRuntimeArray %6\r\n" - "%8 = OpTypePointer UniformConstant %7\r\n" - "%9 = OpTypePointer Function %5\r\n" - "%10 = OpVariable %8 UniformConstant\r\n" - "%11 = OpVariable %8 UniformConstant\r\n" - ) - out = m.rewrite(module, [16, 8]) - self.assertNotIn("\r\n", out) - self.assertTrue(out.endswith("\n")) - self.assertIn("OpDecorate %11 Binding 0", out) - self.assertIn("OpDecorate %10 Binding 16", out) - # First OpTypeInt 32 0 is %4 (not %2 signed or %3 64-bit). - self.assertIn("%msl_cap_b0 = OpConstant %4 16", out) - self.assertIn("%msl_cap_b1 = OpConstant %4 8", out) - self.assertIn("%11 = OpVariable %msl_ptr_b0 UniformConstant", out) - self.assertIn("%10 = OpVariable %msl_ptr_b1 UniformConstant", out) - # Sorted binding order (b0 then b1) inserted immediately after %8, not after %9. - lines = out.splitlines() - idx8 = lines.index("%8 = OpTypePointer UniformConstant %7") - self.assertEqual(lines[idx8 + 1 : idx8 + 7], [ - "%msl_cap_b0 = OpConstant %4 16", - "%msl_arr_b0 = OpTypeArray %6 %msl_cap_b0", - "%msl_ptr_b0 = OpTypePointer UniformConstant %msl_arr_b0", - "%msl_cap_b1 = OpConstant %4 8", - "%msl_arr_b1 = OpTypeArray %6 %msl_cap_b1", - "%msl_ptr_b1 = OpTypePointer UniformConstant %msl_arr_b1", - ]) - idx9 = lines.index("%9 = OpTypePointer Function %5") - self.assertEqual(lines[idx9 + 1], "%10 = OpVariable %msl_ptr_b1 UniformConstant") - - def test_empty_and_no_set0_modules(self): - self.assertEqual(m.rewrite("", [4]), "\n") - plain = "OpCapability Shader\nOpMemoryModel Logical GLSL450\n" - self.assertEqual(m.rewrite(plain, [4]), plain) - - def test_out_of_bounds_set0_binding_raises_system_exit(self): - for b, counts in ((2, [10, 20]), (26, m.capacities()), (100, m.capacities())): - with self.subTest(binding=b, count_len=len(counts)): - text = f"OpDecorate %bad DescriptorSet 0\nOpDecorate %bad Binding {b}\n" - with self.assertRaises(SystemExit) as ctx: - m.rewrite(text, counts) - self.assertIn("%bad", str(ctx.exception)) - self.assertIn(f"binding {b}", str(ctx.exception)) - - def test_missing_uint32_type_raises_when_runtime_array_rewritten(self): - base = """\ -OpDecorate %images DescriptorSet 0 -OpDecorate %images Binding 0 -{int_decl} -%float = OpTypeFloat 32 -%img2d = OpTypeImage %float 2D 0 0 0 1 Unknown -%rt_img = OpTypeRuntimeArray %img2d -%ptr_img = OpTypePointer UniformConstant %rt_img -%images = OpVariable %ptr_img UniformConstant -""" - for label, int_decl in ( - ("no_int", ""), - ("signed_32", "%s32 = OpTypeInt 32 1"), - ("unsigned_64", "%u64 = OpTypeInt 64 0"), - ): - with self.subTest(case=label): - with self.assertRaises(SystemExit) as ctx: - m.rewrite(base.format(int_decl=int_decl), [4096]) - self.assertIn("no 32-bit uint type", str(ctx.exception)) - - -class TestMainAndCli(unittest.TestCase): - def _call_main(self, argv): - out, err = io.StringIO(), io.StringIO() - # tools/spirv_metal_set0.py:31 uses open(path).read() without a context manager, which emits - # ResourceWarning under unittest's default filter on redirected stderr; isolate tool stderr here. - with warnings.catch_warnings(): - warnings.simplefilter("ignore", ResourceWarning) - with contextlib.redirect_stdout(out), contextlib.redirect_stderr(err): - code = m.main(argv) - return code, out.getvalue(), err.getvalue() - - def test_print_layout_outputs_26_formatted_ranges_without_subprocess(self): - with mock.patch.object(m.subprocess, "run") as run_mock: - code, out, err = self._call_main(["spirv_metal_set0.py", "--print-layout"]) - run_mock.assert_not_called() - self.assertEqual(code, 0) - self.assertEqual(err, "") - lines = out.splitlines() - self.assertEqual(len(lines), 26) - self.assertEqual(lines[0], "binding 0: 4096 descriptors at IDs 0..4095") - self.assertEqual(lines[1], "binding 1: 1024 descriptors at IDs 4096..5119") - self.assertEqual(lines[2], "binding 2: 1 descriptors at IDs 5120..5120") - self.assertEqual(lines[3], "binding 3: 1024 descriptors at IDs 5121..6144") - self.assertEqual(lines[4], "binding 4: 1024 descriptors at IDs 6145..7168") - self.assertEqual(lines[25], "binding 25: 256 descriptors at IDs 12289..12544") - - def test_print_layout_uses_capacities_table(self): - with mock.patch.object(m, "capacities", return_value=[3, 1, 2]): - code, out, err = self._call_main(["spirv_metal_set0.py", "--print-layout"]) - self.assertEqual(code, 0) - self.assertEqual(err, "") - self.assertEqual(out.splitlines(), [ - "binding 0: 3 descriptors at IDs 0..2", - "binding 1: 1 descriptors at IDs 3..3", - "binding 2: 2 descriptors at IDs 4..5", - ]) - - def test_invalid_argc_returns_2_and_prints_usage_to_stderr(self): - bad_argvs = [ - [], - ["spirv_metal_set0.py"], - ["spirv_metal_set0.py", "in.spv"], - ["spirv_metal_set0.py", "--unknown"], - ["spirv_metal_set0.py", "--print-layout", "in.spv", "out.spv"], - ["spirv_metal_set0.py", "in.spv", "out.spv", "extra"], - ] - for argv in bad_argvs: - with self.subTest(argv=argv), mock.patch.object(m.subprocess, "run") as run_mock: - code, out, err = self._call_main(argv) - run_mock.assert_not_called() - self.assertEqual(code, 2) - self.assertEqual(out, "") - self.assertIn("Usage: spirv_metal_set0.py in.spv out.spv", err) - self.assertIn("--print-layout", err) - - def test_print_layout_with_extra_arg_falls_through_to_two_arg_mode(self): - with mock.patch.object( - m.subprocess, - "run", - side_effect=[ - subprocess.CompletedProcess([], 0, "OpCapability Shader\n", ""), - subprocess.CompletedProcess([], 0, "", ""), - ], - ) as run_mock: - code, out, err = self._call_main(["spirv_metal_set0.py", "--print-layout", "out.spv"]) - self.assertEqual((code, out, err), (0, "", "")) - self.assertEqual(run_mock.call_args_list[0].args[0], ["spirv-dis", "--print-layout"]) - self.assertEqual( - run_mock.call_args_list[1].args[0], - ["spirv-as", "--target-env", "vulkan1.2", "-", "-o", "out.spv"], - ) - - def test_cli_subprocess_isolated_print_layout_and_bad_args(self): - r_layout = subprocess.run( - [sys.executable, "-I", TOOL_PATH, "--print-layout"], - capture_output=True, - text=True, - cwd=ROOT, - ) - self.assertEqual(r_layout.returncode, 0, r_layout.stderr) - self.assertEqual(r_layout.stderr, "") - self.assertEqual(len(r_layout.stdout.splitlines()), 26) - self.assertEqual(r_layout.stdout.splitlines()[0], "binding 0: 4096 descriptors at IDs 0..4095") - - for args in ([], ["only_one.spv"], ["a.spv", "b.spv", "c.spv"]): - with self.subTest(args=args): - r = subprocess.run( - [sys.executable, "-I", TOOL_PATH, *args], - capture_output=True, - text=True, - cwd=ROOT, - ) - self.assertEqual(r.returncode, 2) - self.assertEqual(r.stdout, "") - self.assertIn("Usage: spirv_metal_set0.py in.spv out.spv", r.stderr) - self.assertNotIn("Traceback", r.stderr) - - def test_synthetic_spv_out_of_place_and_in_place_binary_round_trip(self): - in_bytes = _pack_spv(_build_mixed_bindless_spv_words(), version=SPIRV_VERSION_1_5) - fake_run, calls = _make_fake_spirv_tools() - - with tempfile.TemporaryDirectory() as tmp: - unicode_dir = os.path.join(tmp, "dir-\u00e9-\u2603") - os.makedirs(unicode_dir) - in_path = os.path.join(unicode_dir, "in.spv") - out_path = os.path.join(unicode_dir, "out.spv") - with open(in_path, "wb") as f: - f.write(in_bytes) - - with mock.patch.dict(os.environ, {}, clear=False), \ - mock.patch.object(m.subprocess, "run", side_effect=fake_run): - os.environ.pop("SPIRV_DIS", None) - os.environ.pop("SPIRV_AS", None) - code, out, err = self._call_main(["spirv_metal_set0.py", in_path, out_path]) - - self.assertEqual(code, 0) - self.assertEqual(out, "") - self.assertEqual(err, "") - self.assertEqual(calls, [ - ["spirv-dis", in_path], - ["spirv-as", "--target-env", "spv1.5", "-", "-o", out_path], - ]) - - # Original input file is preserved untouched for out-of-place conversion. - with open(in_path, "rb") as f: - self.assertEqual(f.read(), in_bytes) - - with open(out_path, "rb") as f: - out_bytes = f.read() - header, insts = _decode_spv(out_bytes) - self.assertEqual(header[0], SPIRV_MAGIC) - self.assertEqual(header[1], SPIRV_VERSION_1_5) - self.assertEqual(header[4], 0) - - decs = [ops for op, ops in insts if op == OP_DECORATE] - bindings_by_id = {ops[0]: ops[2] for ops in decs if ops[1] == DEC_BINDING} - sets_by_id = {ops[0]: ops[2] for ops in decs if ops[1] == DEC_DESCRIPTOR_SET} - self.assertEqual(sets_by_id, {13: 0, 14: 0, 15: 0, 17: 1}) - # Set-0 bindings rewritten per vulkan_bindless.h; set-1 binding 0 stays 0. - self.assertEqual(bindings_by_id, {13: 0, 14: 4096, 15: 5120, 17: 0}) - - consts = {ops[1]: ops[2] for op, ops in insts if op == OP_CONSTANT} - arrays = {ops[0]: (ops[1], consts[ops[2]]) for op, ops in insts if op == OP_TYPE_ARRAY} - ptrs = {ops[0]: (ops[1], ops[2]) for op, ops in insts if op == OP_TYPE_POINTER} - vars_by_id = {ops[1]: (ops[0], ops[2]) for op, ops in insts if op == OP_VARIABLE} - - # %13 (images) and %14 (samplers) are retyped to sized arrays [4096] and [1024]; - # %15 (desc_map StorageBuffer), %16 (PushConstant), and %17 (set 1) keep original types. - self.assertEqual(arrays[ptrs[vars_by_id[13][0]][1]], (3, 4096)) - self.assertEqual(arrays[ptrs[vars_by_id[14][0]][1]], (4, 1024)) - self.assertEqual(vars_by_id[15], (11, SC_STORAGE_BUFFER)) - self.assertEqual(vars_by_id[16], (12, SC_PUSH_CONSTANT)) - self.assertEqual(vars_by_id[17], (7, SC_UNIFORM_CONSTANT)) - - # In-place conversion: argv[1] == argv[2]. - inplace_path = os.path.join(unicode_dir, "inplace.spv") - with open(inplace_path, "wb") as f: - f.write(in_bytes) - calls.clear() - with mock.patch.object(m.subprocess, "run", side_effect=fake_run): - code, out, err = self._call_main(["spirv_metal_set0.py", inplace_path, inplace_path]) - self.assertEqual(code, 0) - self.assertEqual(out, "") - self.assertEqual(err, "") - self.assertEqual(calls, [ - ["spirv-dis", inplace_path], - ["spirv-as", "--target-env", "spv1.5", "-", "-o", inplace_path], - ]) - with open(inplace_path, "rb") as f: - self.assertEqual(f.read(), out_bytes) - - def test_target_env_extraction_and_env_var_overrides(self): - cases = [ - ("; Version: 1.0\n", "spv1.0"), - ("; SPIR-V\n; Version: 1.5\n", "spv1.5"), - ("; Version: 1.6\n", "spv1.6"), - ("; SPIR-V without version comment\n", "vulkan1.2"), - ] - for header_text, expected_target in cases: - with self.subTest(expected_target=expected_target): - disasm = header_text + "OpCapability Shader\n" - seen_cmds = [] - - def run_stub(cmd, check=False, capture_output=False, text=False, input=None, errors=None): - seen_cmds.append((list(cmd), check, capture_output, text, input)) - if len(seen_cmds) == 1: - return subprocess.CompletedProcess(cmd, 0, disasm, "") - return subprocess.CompletedProcess(cmd, 0, "", "") - - with mock.patch.dict(os.environ, {"SPIRV_DIS": "/opt/bin/dis", "SPIRV_AS": "/opt/bin/as"}), \ - mock.patch.object(m.subprocess, "run", side_effect=run_stub): - code, out, err = self._call_main(["spirv_metal_set0.py", "in.spv", "out.spv"]) - - self.assertEqual((code, out, err), (0, "", "")) - self.assertEqual(seen_cmds[0][0], ["/opt/bin/dis", "in.spv"]) - self.assertTrue(seen_cmds[0][1]) - self.assertTrue(seen_cmds[0][2]) - self.assertTrue(seen_cmds[0][3]) - self.assertEqual(seen_cmds[1][0], ["/opt/bin/as", "--target-env", expected_target, "-", "-o", "out.spv"]) - self.assertTrue(seen_cmds[1][1]) - self.assertTrue(seen_cmds[1][3]) - self.assertEqual(seen_cmds[1][4], disasm) - - def test_invalid_spirv_binary_words_and_missing_or_directory_paths(self): - fake_run, calls = _make_fake_spirv_tools() - valid_words = _build_mixed_bindless_spv_words() - - bad_inputs = [ - ("empty_file", b""), - ("truncated_header_8B", struct.pack("<2I", SPIRV_MAGIC, SPIRV_VERSION_1_5)), - ("unaligned_21B", _pack_spv([], bound=1) + b"\x00"), - ("big_endian_magic", struct.pack(">5I", SPIRV_MAGIC, SPIRV_VERSION_1_5, 0, 2, 0)), - ("wrong_magic", struct.pack("<5I", 0xDEADBEEF, SPIRV_VERSION_1_5, 0, 2, 0)), - ("non_zero_schema", _pack_spv([], bound=1, schema=1)), - ("zero_bound", _pack_spv([], bound=0)), - ("zero_word_count_inst", _pack_spv([OP_CAPABILITY], bound=2)), - ("truncated_inst_bounds", _pack_spv(valid_words[:-1], bound=18)), - ] - with tempfile.TemporaryDirectory() as tmp: - for label, blob in bad_inputs: - with self.subTest(case=label): - calls.clear() - in_path = os.path.join(tmp, f"{label}.spv") - out_path = os.path.join(tmp, f"{label}.out.spv") - with open(in_path, "wb") as f: - f.write(blob) - with mock.patch.object(m.subprocess, "run", side_effect=fake_run): - with self.assertRaises(subprocess.CalledProcessError): - m.main(["spirv_metal_set0.py", in_path, out_path]) - self.assertEqual(calls, [["spirv-dis", in_path]]) - self.assertFalse(os.path.exists(out_path)) - - # Missing input file and directory passed as input file both fail at spirv-dis. - missing_in = os.path.join(tmp, "does_not_exist.spv") - dir_in = os.path.join(tmp, "a_directory") - os.makedirs(dir_in) - for label, bad_path in (("missing_file", missing_in), ("directory_input", dir_in)): - with self.subTest(case=label): - calls.clear() - out_path = os.path.join(tmp, f"{label}.out.spv") - with mock.patch.object(m.subprocess, "run", side_effect=fake_run): - with self.assertRaises(subprocess.CalledProcessError): - m.main(["spirv_metal_set0.py", bad_path, out_path]) - self.assertEqual(calls, [["spirv-dis", bad_path]]) - self.assertFalse(os.path.exists(out_path)) - - def test_spirv_as_failure_missing_executable_and_rewrite_abort(self): - with tempfile.TemporaryDirectory() as tmp: - in_path = os.path.join(tmp, "in.spv") - out_path = os.path.join(tmp, "out.spv") - with open(in_path, "wb") as f: - f.write(_pack_spv(_build_mixed_bindless_spv_words())) - - # 1. Missing spirv-dis binary raises FileNotFoundError before calling spirv-as. - with mock.patch.object(m.subprocess, "run", side_effect=FileNotFoundError("no spirv-dis")) as run_mock: - with self.assertRaises(FileNotFoundError): - m.main(["spirv_metal_set0.py", in_path, out_path]) - self.assertEqual(run_mock.call_count, 1) - self.assertFalse(os.path.exists(out_path)) - - # 2. rewrite() SystemExit aborts before spirv-as is invoked. - bad_spv = _pack_spv([ - *_encode_inst(OP_DECORATE, 2, DEC_DESCRIPTOR_SET, 0), - *_encode_inst(OP_DECORATE, 2, DEC_BINDING, 99), - ], bound=3) - with open(in_path, "wb") as f: - f.write(bad_spv) - fake_run, calls = _make_fake_spirv_tools() - with mock.patch.object(m.subprocess, "run", side_effect=fake_run): - with self.assertRaises(SystemExit) as ctx: - m.main(["spirv_metal_set0.py", in_path, out_path]) - self.assertIn("binding 99", str(ctx.exception)) - self.assertEqual(calls, [["spirv-dis", in_path]]) - self.assertFalse(os.path.exists(out_path)) - - # 3. spirv-as failure raises CalledProcessError. - dis_ok = subprocess.CompletedProcess(["spirv-dis", in_path], 0, "; Version: 1.5\nOpCapability Shader\n", "") - asm_fail = subprocess.CalledProcessError(1, ["spirv-as"], stderr="bad asm") - with mock.patch.object(m.subprocess, "run", side_effect=[dis_ok, asm_fail]) as run_mock: - with self.assertRaises(subprocess.CalledProcessError): - m.main(["spirv_metal_set0.py", in_path, out_path]) - self.assertEqual(run_mock.call_count, 2) - - def test_main_guard_handles_stdout_reconfigure_errors_and_exit_codes(self): - class _Stream(io.StringIO): - def __init__(self, exc): - super().__init__() - self._exc = exc - - def reconfigure(self, **_kwargs): - raise self._exc - - for exc in (AttributeError("no reconfigure"), ValueError("bad"), OSError("io")): - with self.subTest(exc=type(exc).__name__): - out_stream = _Stream(exc) - err_stream = io.StringIO() - with warnings.catch_warnings(): - warnings.simplefilter("ignore", ResourceWarning) - with mock.patch.object(sys, "argv", ["spirv_metal_set0.py", "--print-layout"]), \ - mock.patch.object(sys, "stdout", out_stream), \ - mock.patch.object(sys, "stderr", err_stream): - with self.assertRaises(SystemExit) as ctx: - runpy.run_path(TOOL_PATH, run_name="__main__") - self.assertEqual(ctx.exception.code, 0) - self.assertEqual(err_stream.getvalue(), "") - self.assertEqual(len(out_stream.getvalue().splitlines()), 26) - - err_stream = io.StringIO() - with warnings.catch_warnings(): - warnings.simplefilter("ignore", ResourceWarning) - with mock.patch.object(sys, "argv", ["spirv_metal_set0.py"]), \ - mock.patch.object(sys, "stdout", io.StringIO()), \ - mock.patch.object(sys, "stderr", err_stream): - with self.assertRaises(SystemExit) as ctx: - runpy.run_path(TOOL_PATH, run_name="__main__") - self.assertEqual(ctx.exception.code, 2) - self.assertIn("Usage: spirv_metal_set0.py in.spv out.spv", err_stream.getvalue()) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/test_spirv_opt.py b/tests/test_spirv_opt.py deleted file mode 100644 index f5cdc9aa4..000000000 --- a/tests/test_spirv_opt.py +++ /dev/null @@ -1,571 +0,0 @@ -"""Tests for tools/spirv_opt.py (sound basic-block SPIR-V peephole optimizer, #884).""" -import contextlib -import io -import json -import os -import shutil -import subprocess -import sys -import tempfile -import unittest - -ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) -TOOLS = os.path.join(ROOT, "tools") -SEMANTIC = os.path.join(ROOT, "tests", "semantic") -for _p in (TOOLS, SEMANTIC): - if _p not in sys.path: - sys.path.insert(0, _p) - -import rdna2spirv # noqa: E402 -import spirv_opt # noqa: E402 -import support # noqa: E402 - -SPIRV_AS = shutil.which("spirv-as") -SPIRV_VAL = shutil.which("spirv-val") - - -def _validate(spvasm: str) -> None: - if not (SPIRV_AS and SPIRV_VAL): - return - with tempfile.TemporaryDirectory() as d: - sa, sv = os.path.join(d, "m.spvasm"), os.path.join(d, "m.spv") - with open(sa, "w", encoding="utf-8", newline="\n") as f: - f.write(spvasm) - for cmd in ( - [SPIRV_AS, sa, "-o", sv, "--target-env", "vulkan1.2"], - [SPIRV_VAL, "--target-env", "vulkan1.2", "--allow-offset-texture-operand", sv], - ): - r = subprocess.run(cmd, capture_output=True, text=True) - if r.returncode != 0: - raise AssertionError(f"{cmd[0]} failed:\n{r.stderr}") - - -class SpirvOptTests(unittest.TestCase): - def test_alu_chain_bit_exact_and_shrinks_significantly(self): - lines = [ - "v_mov_b32_e32 v1, 0x01020304", - "v_mov_b32_e32 v2, 0x05060708", - "v_mov_b32_e32 v3, 0x000003e8", - "v_dot4_i32_i8 v8, v1, v2, v3", - "v_dot4c_i32_i8 v8, v1, v2", - "v_add_f32_e32 v9, v8, 1.0", - "v_mul_f32_e32 v10, v9, 2.0", - "exp mrt0 v8, v9, v10, v8 done vm", - "s_endpgm", - ] - raw = support.translate_lines("ps_opt_alu", lines) - opt = spirv_opt.optimize(raw) - _validate(opt) - self.assertEqual(support.mrt0_words(opt), support.mrt0_words(raw)) - # Straight-line ALU chain should shed >50% of its lines (register traffic, %active loads, round-trip bitcasts, - # unused push-constant prologue loads, and duplicate pure expressions). - self.assertLess(len(opt.splitlines()), len(raw.splitlines()) * 0.5) - self.assertNotIn("OpLoad %bool %active", opt) - - def test_dynamic_register_indexing_preserved_soundly(self): - # v_movrels_b32 / s_movrels_b32 use dynamic OpAccessChain into %vgpr / %sgpr; optimizer must NOT - # drop stores or forward stale values across dynamic accesses. - lines = [ - "v_mov_b32_e32 v1, 0x11111111", - "v_mov_b32_e32 v2, 0x22222222", - "v_mov_b32_e32 v3, 0x33333333", - "s_mov_b32 m0, 1", - "v_movrels_b32_e32 v8, v1", # reads v[1 + 1] = v2 = 0x22222222 - "s_mov_b32 m0, 2", - "v_movrels_b32_e32 v9, v1", # reads v[1 + 2] = v3 = 0x33333333 - "v_movreld_b32_e32 v1, v8", # writes v[1 + 2] = v3 = 0x22222222 - "v_mov_b32_e32 v10, v3", # must observe the dynamic write -> 0x22222222, NOT stale 0x33333333! - "exp mrt0 v8, v9, v10, v2 done vm", - "s_endpgm", - ] - raw = support.translate_lines("ps_opt_dyn_reg", lines) - opt = spirv_opt.optimize(raw) - _validate(opt) - expected = [0x22222222, 0x33333333, 0x22222222, 0x22222222] - self.assertEqual(support.mrt0_words(raw), expected) - self.assertEqual(support.mrt0_words(opt), expected) - - def test_control_flow_and_exec_masking_preserved(self): - # Branches + exec masking across blocks: intra-block forwarding must reset at OpLabel boundaries. - lines = [ - "v_mov_b32_e32 v1, 10 ; encoding: [0x8a,0x02,0x02,0x7e]", - "v_mov_b32_e32 v2, 20 ; encoding: [0x94,0x02,0x04,0x7e]", - "v_mov_b32_e32 v8, 0 ; encoding: [0x80,0x02,0x10,0x7e]", - "s_mov_b32 s4, 0 ; encoding: [0x80,0x03,0x84,0xbe]", - "s_cmp_eq_u32 s4, 0 ; encoding: [0x04,0x80,0x06,0xbf]", - "s_cbranch_scc0 2 ; encoding: [0x02,0x00,0x84,0xbf]", - "v_add_nc_u32_e32 v8, v1, v2 ; encoding: [0x01,0x05,0x10,0x4a]", - "s_branch 1 ; encoding: [0x01,0x00,0x82,0xbf]", - "v_sub_nc_u32_e32 v8, v2, v1 ; encoding: [0x02,0x03,0x10,0x4c]", - "v_add_nc_u32_e32 v9, v8, 5 ; encoding: [0x85,0x10,0x12,0x4a]", - "exp mrt0 v8, v9, v1, v2 done vm ; encoding: [0x0f,0x18,0x00,0xf8,0x08,0x09,0x01,0x02]", - "s_endpgm ; encoding: [0x00,0x00,0x81,0xbf]", - ] - raw = support.translate_lines("ps_opt_cf", lines) - opt = spirv_opt.optimize(raw) - _validate(opt) - self.assertEqual(support.mrt0_words(opt), support.mrt0_words(raw)) - self.assertEqual(support.mrt0_words(opt), [30, 35, 10, 20]) - # Non-divergent scalar-branch shader never stores %active: cross-block read-only propagation eliminates - # every OpLoad %bool %active and the dead %active OpVariable across all blocks. - self.assertNotIn("OpLoad %bool %active", opt) - self.assertNotIn("%active = OpVariable", opt) - - def test_cross_block_constant_folding_and_dead_func_vars(self): - # Constant integer/bit folding + algebraic identities across straight-line ALU. - lines = [ - "v_mov_b32_e32 v1, 2", - "v_lshlrev_b32_e32 v2, 2, v1", # 2 << (2 & 0x1f) -> folds (2 & 0x1f) and shift - "v_add_nc_u32_e32 v3, v2, 0", # + 0 identity - "v_xor_b32_e32 v4, v3, v3", # x ^ x -> 0 - "v_or_b32_e32 v5, v3, 0", # | 0 identity - "exp mrt0 v2, v3, v4, v5 done vm", - "s_endpgm", - ] - raw = support.translate_lines("ps_opt_fold", lines) - opt = spirv_opt.optimize(raw) - _validate(opt) - self.assertEqual(support.mrt0_words(opt), [8, 8, 0, 8]) - self.assertNotIn("OpBitwiseXor", opt) - self.assertNotIn("OpIAdd", opt) - # Unused Function-scope variables (%m0, %scc, %active, etc.) should be removed. - self.assertNotIn("%m0 = OpVariable", opt) - self.assertNotIn("%active = OpVariable", opt) - - def test_trivial_phi_and_dominator_cse_in_loop(self): - # Hand-crafted SPIR-V module exercising trivial OpPhi (identical incoming + self-loop) and - # dominator-tree OpAccessChain + Input OpLoad CSE across a structured loop. - spvasm = """ OpCapability Shader - OpMemoryModel Logical GLSL450 - OpEntryPoint Fragment %main "main" %in0 %out0 - OpExecutionMode %main OriginUpperLeft - OpDecorate %in0 Location 0 - OpDecorate %in0 Flat - OpDecorate %out0 Location 0 - %void = OpTypeVoid - %fn = OpTypeFunction %void - %bool = OpTypeBool - %uint = OpTypeInt 32 0 - %v4uint = OpTypeVector %uint 4 - %_ptr_In = OpTypePointer Input %uint - %_ptr_Out = OpTypePointer Output %v4uint - %_ptr_Fun = OpTypePointer Function %uint - %c0 = OpConstant %uint 0 - %c1 = OpConstant %uint 1 - %c4 = OpConstant %uint 4 - %true = OpConstantTrue %bool - %false = OpConstantFalse %bool - %in0 = OpVariable %_ptr_In Input - %out0 = OpVariable %_ptr_Out Output - %main = OpFunction %void None %fn - %entry = OpLabel - %local = OpVariable %_ptr_Fun Function %c0 - %v0 = OpLoad %uint %in0 - OpStore %local %v0 - OpBranch %head - %head = OpLabel - %phi = OpPhi %uint %v0 %entry %phi %cont - %i = OpPhi %uint %c0 %entry %inext %cont - OpLoopMerge %exit %cont None - OpBranch %body - %body = OpLabel - %v1 = OpLoad %uint %in0 - %sum = OpIAdd %uint %phi %v1 - %cond = OpULessThan %bool %i %c4 - OpSelectionMerge %merge None - OpBranchConditional %cond %cont %exit - %merge = OpLabel - OpUnreachable - %cont = OpLabel - %inext = OpIAdd %uint %i %c1 - OpBranch %head - %exit = OpLabel - %res = OpCompositeConstruct %v4uint %phi %v0 %c0 %c1 - OpStore %out0 %res - OpReturn - OpFunctionEnd -""" - _validate(spvasm) - opt = spirv_opt.optimize(spvasm) - _validate(opt) - # Trivial self-referential %phi must collapse to %v0, duplicate %v1 = OpLoad %in0 CSEs to %v0, - # dead %sum and dead %local OpVariable are eliminated. - self.assertNotIn("%phi = OpPhi", opt) - self.assertEqual(opt.count("OpLoad %uint %in0"), 1) - self.assertNotIn("%local = OpVariable", opt) - self.assertNotIn("%sum = OpIAdd", opt) - - def test_alias_signed_unsigned_index_volatile_and_aggregate_overlap(self): - # Regression tests for standalone memory aliasing cases (PR #2298 review): - # 1) Store 1 via %uint 0, store 2 via %int 0, load via first pointer -> must observe 2, not 1. - # 2) Store 1, Volatile store 2, ordinary load -> must NOT forward stale 1. - # 3) Store 1, Volatile load, store 2 -> must NOT kill store 1 before volatile load. - # 4) Store element 0 = 1, store whole array = {2, 2}, load element 0 -> must NOT forward stale 1. - spv_idx = """ OpCapability Shader - OpMemoryModel Logical GLSL450 - OpEntryPoint Fragment %main "main" %out0 - OpExecutionMode %main OriginUpperLeft - OpDecorate %out0 Location 0 - %void = OpTypeVoid - %fn = OpTypeFunction %void - %uint = OpTypeInt 32 0 - %int = OpTypeInt 32 1 - %c2 = OpConstant %uint 2 - %arr = OpTypeArray %uint %c2 - %v4uint = OpTypeVector %uint 4 - %_ptr_Fa = OpTypePointer Function %arr - %_ptr_Fu = OpTypePointer Function %uint - %_ptr_Out = OpTypePointer Output %v4uint - %u0 = OpConstant %uint 0 - %s0 = OpConstant %int 0 - %u1 = OpConstant %uint 1 - %u2 = OpConstant %uint 2 - %out0 = OpVariable %_ptr_Out Output - %main = OpFunction %void None %fn - %entry = OpLabel - %a = OpVariable %_ptr_Fa Function - %p0 = OpAccessChain %_ptr_Fu %a %u0 - %p1 = OpAccessChain %_ptr_Fu %a %s0 - OpStore %p0 %u1 - OpStore %p1 %u2 - %r = OpLoad %uint %p0 - %vec = OpCompositeConstruct %v4uint %r %u0 %u0 %u0 - OpStore %out0 %vec - OpReturn - OpFunctionEnd -""" - _validate(spv_idx) - opt_idx = spirv_opt.optimize(spv_idx) - _validate(opt_idx) - self.assertIn("OpCompositeConstruct %v4uint %u2 %u0 %u0 %u0", opt_idx) - - spv_vol_store = """ OpCapability Shader - OpMemoryModel Logical GLSL450 - OpEntryPoint Fragment %main "main" %out0 - OpExecutionMode %main OriginUpperLeft - OpDecorate %out0 Location 0 - %void = OpTypeVoid - %fn = OpTypeFunction %void - %uint = OpTypeInt 32 0 - %v4uint = OpTypeVector %uint 4 - %_ptr_Fu = OpTypePointer Function %uint - %_ptr_Out = OpTypePointer Output %v4uint - %u0 = OpConstant %uint 0 - %u1 = OpConstant %uint 1 - %u2 = OpConstant %uint 2 - %out0 = OpVariable %_ptr_Out Output - %main = OpFunction %void None %fn - %entry = OpLabel - %x = OpVariable %_ptr_Fu Function - OpStore %x %u1 - OpStore %x %u2 Volatile - %r = OpLoad %uint %x - %vec = OpCompositeConstruct %v4uint %r %u0 %u0 %u0 - OpStore %out0 %vec - OpReturn - OpFunctionEnd -""" - _validate(spv_vol_store) - opt_vs = spirv_opt.optimize(spv_vol_store) - _validate(opt_vs) - self.assertIn("OpStore %x %u2 Volatile", opt_vs) - self.assertIn("%r = OpLoad %uint %x", opt_vs) - self.assertIn("OpCompositeConstruct %v4uint %r %u0 %u0 %u0", opt_vs) - - spv_vol_load = """ OpCapability Shader - OpMemoryModel Logical GLSL450 - OpEntryPoint Fragment %main "main" %out0 - OpExecutionMode %main OriginUpperLeft - OpDecorate %out0 Location 0 - %void = OpTypeVoid - %fn = OpTypeFunction %void - %uint = OpTypeInt 32 0 - %v4uint = OpTypeVector %uint 4 - %_ptr_Fu = OpTypePointer Function %uint - %_ptr_Out = OpTypePointer Output %v4uint - %u0 = OpConstant %uint 0 - %u1 = OpConstant %uint 1 - %u2 = OpConstant %uint 2 - %out0 = OpVariable %_ptr_Out Output - %main = OpFunction %void None %fn - %entry = OpLabel - %x = OpVariable %_ptr_Fu Function - OpStore %x %u1 - %r = OpLoad %uint %x Volatile - OpStore %x %u2 - %vec = OpCompositeConstruct %v4uint %r %u0 %u0 %u0 - OpStore %out0 %vec - OpReturn - OpFunctionEnd -""" - _validate(spv_vol_load) - opt_vl = spirv_opt.optimize(spv_vol_load) - _validate(opt_vl) - self.assertIn("OpStore %x %u1", opt_vl) - self.assertIn("%r = OpLoad %uint %x Volatile", opt_vl) - self.assertIn("OpStore %x %u2", opt_vl) - - spv_agg = """ OpCapability Shader - OpMemoryModel Logical GLSL450 - OpEntryPoint Fragment %main "main" %out0 - OpExecutionMode %main OriginUpperLeft - OpDecorate %out0 Location 0 - %void = OpTypeVoid - %fn = OpTypeFunction %void - %uint = OpTypeInt 32 0 - %c2 = OpConstant %uint 2 - %arr = OpTypeArray %uint %c2 - %v4uint = OpTypeVector %uint 4 - %_ptr_Fa = OpTypePointer Function %arr - %_ptr_Fu = OpTypePointer Function %uint - %_ptr_Out = OpTypePointer Output %v4uint - %u0 = OpConstant %uint 0 - %u1 = OpConstant %uint 1 - %u2 = OpConstant %uint 2 - %a22 = OpConstantComposite %arr %u2 %u2 - %out0 = OpVariable %_ptr_Out Output - %main = OpFunction %void None %fn - %entry = OpLabel - %a = OpVariable %_ptr_Fa Function - %p0 = OpAccessChain %_ptr_Fu %a %u0 - OpStore %p0 %u1 - OpStore %a %a22 - %r = OpLoad %uint %p0 - %vec = OpCompositeConstruct %v4uint %r %u0 %u0 %u0 - OpStore %out0 %vec - OpReturn - OpFunctionEnd -""" - _validate(spv_agg) - opt_agg = spirv_opt.optimize(spv_agg) - _validate(opt_agg) - self.assertIn("OpStore %a %a22", opt_agg) - self.assertIn("%r = OpLoad %uint %p0", opt_agg) - self.assertIn("OpCompositeConstruct %v4uint %r %u0 %u0 %u0", opt_agg) - - def test_wave64_emulated_compute_validates_and_shrinks(self): - cs_lines = [ - "s_load_dwordx2 s[4:5], s[0:1], 0x0", - "s_waitcnt lgkmcnt(0)", - "v_mov_b32_e32 v1, 0x3f800000", - "v_add_f32_e32 v2, v1, 2.0", - "v_mul_f32_e32 v3, v2, 3.0", - "v_lshlrev_b32_e32 v4, 2, v0", - "ds_write_b32 v4, v3", - "s_waitcnt lgkmcnt(0)", - "s_barrier", - "ds_read_b32 v5, v4", - "s_waitcnt lgkmcnt(0)", - "v_cmp_lt_u32_e64 vcc, v0, 32", - "v_cndmask_b32_e64 v6, v5, v3, vcc", - "global_store_dword v4, v6, s[4:5]", - "s_endpgm", - ] - with tempfile.TemporaryDirectory() as d: - os.makedirs(os.path.join(d, "disasm")) - os.makedirs(os.path.join(d, "fspx")) - s_path = os.path.join(d, "disasm", "cs_opt_w64.s") - with open(s_path, "w", encoding="utf-8", newline="\n") as f: - f.write("; cs_opt_w64 code 0x0..0x100, gfx1013, 0 invalid words\n") - for ln in cs_lines: - f.write(f"\t{ln} ; encoding: [0x00,0x00,0x00,0x00]\n") - with open(os.path.join(d, "fspx", "cs_opt_w64.json"), "w", encoding="utf-8", newline="\n") as f: - json.dump({"rsrc2": (8 << 1) | (16 << 15), "threads": [64, 1, 1]}, f) - old_w64, old_opt = rdna2spirv.WAVE64_EMULATE, rdna2spirv.OPT_SPIRV - try: - rdna2spirv.WAVE64_EMULATE = True - rdna2spirv.OPT_SPIRV = False - raw = rdna2spirv.translate(s_path) - rdna2spirv.OPT_SPIRV = True - opt = rdna2spirv.translate(s_path) - finally: - rdna2spirv.WAVE64_EMULATE, rdna2spirv.OPT_SPIRV = old_w64, old_opt - _validate(opt) - self.assertLess(len(opt.splitlines()), len(raw.splitlines())) - - def test_decorations_on_deleted_ids_removed_and_surviving_kept(self): - # Deleting a dead NoContraction float op must also drop its OpDecorate line so spirv-val stays clean, - # while a live NoContraction float op keeps its OpDecorate. - lines = [ - "v_mov_b32_e32 v1, 1.0", - "v_add_f32_e32 v2, v1, 2.0", # dead: overwritten below before any read - "v_mul_f32_e32 v2, v1, 3.0", # live: exported - "exp mrt0 v2, v2, v2, v2 done vm", - "s_endpgm", - ] - raw = support.translate_lines("ps_opt_dec", lines) - opt = spirv_opt.optimize(raw) - _validate(opt) - self.assertEqual(support.mrt0_words(opt), support.mrt0_words(raw)) - self.assertIn("NoContraction", opt) - # Dead OpFAdd must be gone along with its decoration. - self.assertNotIn("OpFAdd", opt) - - def test_cli_round_trip(self): - raw = support.translate_lines("ps_opt_cli", [ - "v_mov_b32_e32 v1, 42", - "exp mrt0 v1, v1, v1, v1 done vm", - "s_endpgm", - ]) - with tempfile.TemporaryDirectory() as d: - src, dst = os.path.join(d, "in.spvasm"), os.path.join(d, "out.spvasm") - with open(src, "w", encoding="utf-8", newline="\n") as f: - f.write(raw) - rc = spirv_opt.main([src, "-o", dst]) - self.assertEqual(rc, 0) - with open(dst, encoding="utf-8") as f: - opt = f.read() - _validate(opt) - self.assertEqual(support.mrt0_words(opt), [42] * 4) - - def test_cli_passes_below_one_is_usage_error(self): - raw = support.translate_lines("ps_opt_cli_passes", [ - "v_mov_b32_e32 v1, 42", - "exp mrt0 v1, v1, v1, v1 done vm", - "s_endpgm", - ]) - with tempfile.TemporaryDirectory() as d: - src = os.path.join(d, "in.spvasm") - with open(src, "w", encoding="utf-8", newline="\n") as f: - f.write(raw) - for bad in ("0", "-1"): - dst = os.path.join(d, f"out{bad}.spvasm") - with contextlib.redirect_stderr(io.StringIO()) as err: - with self.assertRaises(SystemExit) as cm: - spirv_opt.main([src, "-o", dst, "--passes", bad]) - self.assertEqual(cm.exception.code, 2) - self.assertIn("--passes must be at least 1", err.getvalue()) - self.assertFalse(os.path.exists(dst)) - dst = os.path.join(d, "out1.spvasm") - self.assertEqual(spirv_opt.main([src, "-o", dst, "--passes", "1"]), 0) - self.assertTrue(os.path.exists(dst)) - - def test_trivial_phi_requires_strict_dominance(self): - # 1. Reachable loop header %hdr has: - # - %p_dead whose sole non-self operand %u comes from unreachable %dead, - # - %p_body whose sole non-self operand %x comes from non-dominating %latch, and - # - %p_self whose sole non-self operand %s is defined later in %hdr itself - # (cand_blk == b, exercising strict vs. non-strict dominance). - # None of %u, %x, or %s strictly dominates %hdr, so trivial OpPhi simplification - # must leave all three phis intact instead of creating a use-not-dominated-by-def - # or self-referential '%s = OpIAdd %uint %s %c1' violation. - # 2. Control: %p_ok = OpPhi %uint %v0 %entry %p_ok %latch IS strictly dominated by - # %entry's %v0 and must still fold to %v0. - spv = "\n".join([ - " OpCapability Shader", - " OpMemoryModel Logical GLSL450", - ' OpEntryPoint Fragment %main "main" %in0 %out0', - " OpExecutionMode %main OriginUpperLeft", - " OpDecorate %in0 Location 0", - " OpDecorate %in0 Flat", - " OpDecorate %out0 Location 0", - " %void = OpTypeVoid", - " %fn_t = OpTypeFunction %void", - " %uint = OpTypeInt 32 0", - " %v4uint = OpTypeVector %uint 4", - " %bool = OpTypeBool", - " %ptr_in_u = OpTypePointer Input %uint", - " %ptr_out_v4 = OpTypePointer Output %v4uint", - " %in0 = OpVariable %ptr_in_u Input", - " %out0 = OpVariable %ptr_out_v4 Output", - " %c0 = OpConstant %uint 0", - " %c1 = OpConstant %uint 1", - " %false = OpConstantFalse %bool", - " %main = OpFunction %void None %fn_t", - " %entry = OpLabel", - " %v0 = OpLoad %uint %in0", - " OpBranch %hdr", - " %dead = OpLabel", - " %u0 = OpLoad %uint %in0", - " %u = OpIAdd %uint %u0 %c1", - " OpBranch %hdr", - " %hdr = OpLabel", - " %p_dead = OpPhi %uint %p_dead %entry %u %dead", - " %p_body = OpPhi %uint %p_body %entry %x %latch", - " %p_self = OpPhi %uint %p_self %entry %s %latch", - " %p_ok = OpPhi %uint %v0 %entry %p_ok %latch", - " %s = OpIAdd %uint %p_self %c1", - " OpLoopMerge %exit %latch None", - " OpBranchConditional %false %latch %exit", - " %latch = OpLabel", - " %x = OpIAdd %uint %p_body %c1", - " OpBranch %hdr", - " %exit = OpLabel", - " %vec = OpCompositeConstruct %v4uint %p_dead %p_body %p_ok %p_self", - " OpStore %out0 %vec", - " OpReturn", - " OpFunctionEnd", - "", - ]) - opt = spirv_opt.optimize(spv) - # Non-strictly-dominating phis (including %p_self where cand_blk == b) must survive. - self.assertIn("%p_dead = OpPhi", opt) - self.assertIn("%p_body = OpPhi", opt) - self.assertIn("%p_self = OpPhi", opt) - self.assertIn("%s = OpIAdd %uint %p_self %c1", opt) - # Strictly dominated trivial phi %p_ok must still fold away. - self.assertNotIn("%p_ok = OpPhi", opt) - self.assertIn("OpCompositeConstruct %v4uint %p_dead %p_body %v0 %p_self", opt) - - def test_decorate_id_string_and_group_preserved_or_cleaned(self): - # Live ops decorated via OpDecorateString, OpDecorateStringGOOGLE, OpDecorateId, or - # OpGroupDecorate (including tab-separated lines) must not be folded/CSE'd away; dead - # ones removed by DCE must have their decoration lines dropped (or target removed from - # OpGroupDecorate) with no dangling SSA IDs left in the module header. - spv = "\n".join([ - " OpCapability Shader", - ' OpExtension "SPV_GOOGLE_decorate_string"', - " OpMemoryModel Logical GLSL450", - ' OpEntryPoint Fragment %main "main" %out0', - " OpExecutionMode %main OriginUpperLeft", - " OpDecorate %out0 Location 0", - " %grp = OpDecorationGroup", - " OpDecorate %grp NoContraction", - " OpGroupDecorate %grp %live_grp %dead_grp", - " OpGroupDecorate\t%grp %dead_only", - ' OpDecorateString\t%live_str UserSemantic "keep"', - ' OpDecorateString\t%dead_str UserSemantic "drop"', - ' OpDecorateStringGOOGLE %live_g HlslSemanticGOOGLE "KEEP"', - ' OpDecorateStringGOOGLE\t%dead_g HlslSemanticGOOGLE "DROP"', - " OpDecorateId %live_id CounterBuffer %out0", - " OpDecorateId\t%dead_id CounterBuffer %out0", - " %void = OpTypeVoid", - " %fn_t = OpTypeFunction %void", - " %uint = OpTypeInt 32 0", - " %v4uint = OpTypeVector %uint 4", - " %ptr_out_v4 = OpTypePointer Output %v4uint", - " %out0 = OpVariable %ptr_out_v4 Output", - " %c0 = OpConstant %uint 0", - " %c1 = OpConstant %uint 1", - " %main = OpFunction %void None %fn_t", - " %entry = OpLabel", - " %live_grp = OpIAdd %uint %c1 %c0", - " %dead_grp = OpIAdd %uint %c1 %c0", - " %dead_only = OpIAdd %uint %c1 %c0", - " %live_str = OpIAdd %uint %c1 %c0", - " %dead_str = OpIAdd %uint %c1 %c0", - " %live_g = OpIAdd %uint %c1 %c0", - " %dead_g = OpIAdd %uint %c1 %c0", - " %live_id = OpIAdd %uint %c1 %c0", - " %dead_id = OpIAdd %uint %c1 %c0", - " %vec = OpCompositeConstruct %v4uint %live_grp %live_str %live_g %live_id", - " OpStore %out0 %vec", - " OpReturn", - " OpFunctionEnd", - "", - ]) - opt = spirv_opt.optimize(spv) - # All four live decorated ops must survive (not folded to %c1) along with their decorations. - for live in ("%live_grp", "%live_str", "%live_g", "%live_id"): - self.assertIn(f"{live} = OpIAdd", opt) - self.assertIn('OpDecorateString\t%live_str UserSemantic "keep"', opt) - self.assertIn('OpDecorateStringGOOGLE %live_g HlslSemanticGOOGLE "KEEP"', opt) - self.assertIn("OpDecorateId %live_id CounterBuffer %out0", opt) - self.assertIn("OpGroupDecorate %grp %live_grp", opt) - # All dead decorated ops and their dangling decorations must be gone. - for dead in ("%dead_grp", "%dead_only", "%dead_str", "%dead_g", "%dead_id"): - self.assertNotIn(dead, opt) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/test_spirv_stubs.py b/tests/test_spirv_stubs.py deleted file mode 100644 index d136b598f..000000000 --- a/tests/test_spirv_stubs.py +++ /dev/null @@ -1,289 +0,0 @@ -"""Tests for tools/spirv_stubs.py and graphics pipeline metadata in tools/rdna2spirv.py. - -Runs with the standard library only (no GPU required): - python -I tests/test_spirv_stubs.py -When spirv-val is on PATH, every generated stub is also validated with spirv-val --target-env vulkan1.2. -""" -import json -import os -import shutil -import struct -import subprocess -import sys -import tempfile -import unittest -from contextlib import contextmanager -from pathlib import Path -from unittest.mock import patch - -ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) -sys.path.insert(0, os.path.join(ROOT, "tools")) - -import rdna2spirv # noqa: E402 -import spirv_stubs # noqa: E402 - - -def decode_spirv_words(data): - assert len(data) >= 20 and len(data) % 4 == 0 - words = list(struct.unpack(f"<{len(data) // 4}I", data)) - magic, version, _gen, bound, schema = words[:5] - assert magic == spirv_stubs.SPIRV_MAGIC - assert version == spirv_stubs.SPIRV_VERSION_1_0 - assert bound > 1 - assert schema == 0 - insts = [] - i = 5 - while i < len(words): - wc = words[i] >> 16 - op = words[i] & 0xFFFF - assert wc >= 1 and i + wc <= len(words) - insts.append((op, words[i + 1 : i + wc])) - i += wc - return bound, insts - - -class SpirvStubsTests(unittest.TestCase): - def _maybe_spirv_val(self, data): - val = shutil.which("spirv-val") - if not val: - return - with tempfile.TemporaryDirectory() as tmp: - p = os.path.join(tmp, "stub.spv") - with open(p, "wb") as f: - f.write(data) - r = subprocess.run([val, "--target-env", "vulkan1.2", p], capture_output=True, text=True) - self.assertEqual(r.returncode, 0, f"spirv-val failed:\n{r.stderr}") - - def test_stub_name_canonical(self): - self.assertEqual(spirv_stubs.stub_name("vs", []), "vs_empty.spv") - self.assertEqual(spirv_stubs.stub_name("vs", [3, 0, 1, 0]), "vs_0_1_3.spv") - self.assertEqual(spirv_stubs.stub_name("ps", []), "ps_empty.spv") - self.assertEqual(spirv_stubs.stub_name("ps", [2, 1]), "ps_1_2.spv") - - def test_vs_stubs_decode_and_validate(self): - for locs in ([], [0], [0, 2, 5]): - data = spirv_stubs.build_vs_stub(locs) - _, insts = decode_spirv_words(data) - decs = [args for op, args in insts if op == spirv_stubs.OP_DECORATE] - # BuiltIn Position + one Location decoration per unique output location. - self.assertTrue(any(d[1:] == [spirv_stubs.DEC_BUILTIN, spirv_stubs.BUILTIN_POSITION] for d in decs)) - got_locs = sorted(d[2] for d in decs if len(d) == 3 and d[1] == spirv_stubs.DEC_LOCATION) - self.assertEqual(got_locs, sorted(locs)) - self._maybe_spirv_val(data) - - def test_ps_stubs_decode_and_validate(self): - for locs, flat in (([], []), ([0], []), ([0, 1, 4], [1])): - data = spirv_stubs.build_ps_stub(locs, flat_locations=flat) - _, insts = decode_spirv_words(data) - # Must declare OriginUpperLeft. - modes = [args for op, args in insts if op == spirv_stubs.OP_EXECUTION_MODE] - self.assertTrue(any(m[1] == spirv_stubs.MODE_ORIGIN_UPPER_LEFT for m in modes)) - decs = [args for op, args in insts if op == spirv_stubs.OP_DECORATE] - # Location 0 output + each input location. - got_locs = sorted(d[2] for d in decs if len(d) == 3 and d[1] == spirv_stubs.DEC_LOCATION) - self.assertEqual(got_locs, sorted([0] + list(locs))) - flat_decs = [d for d in decs if len(d) == 2 and d[1] == spirv_stubs.DEC_FLAT] - self.assertEqual(len(flat_decs), len(flat)) - self._maybe_spirv_val(data) - - def test_failed_rebuild_keeps_existing_stub(self): - index = {"ps": {"stage": "ps", "inputs": [0, 2]}} - - @contextmanager - def interrupted_open(path, mode): - self.assertEqual(Path(path).parent, target.parent) - with open(path, mode) as f: - write = f.write - - def interrupted_write(data): - write(data[:7]) - raise OSError("injected write failure") - - with patch.object(f, "write", interrupted_write): - yield f - - failures = ( - ("write", patch.object(spirv_stubs, "open", interrupted_open, create=True)), - ("replace", patch.object(spirv_stubs.os, "replace", side_effect=PermissionError("injected replace failure"))), - ) - for step, failure in failures: - with self.subTest(step=step), tempfile.TemporaryDirectory() as tmp: - written = spirv_stubs.generate_for_index(tmp, index) - target = Path(tmp) / "stubs" / written[0] - original = target.read_bytes() - self._maybe_spirv_val(original) - with failure, self.assertRaisesRegex(OSError, f"injected {step} failure"): - spirv_stubs.generate_for_index(tmp, index) - self.assertEqual(target.read_bytes(), original) - self.assertEqual(list(target.parent.iterdir()), [target]) - - @unittest.skipUnless(os.name == "nt", "Windows replacement sharing") - def test_rebuild_retries_transient_windows_replace_denial(self): - index = {"ps": {"stage": "ps", "inputs": [0, 2]}} - with tempfile.TemporaryDirectory() as tmp: - written = spirv_stubs.generate_for_index(tmp, index) - replace = os.replace - error = OSError(0, "injected sharing denial", None, 5) - - def retry_replace(src, dst): - if attempt.call_count == 1: - raise error - replace(src, dst) - - with patch.object(spirv_stubs.os, "replace", side_effect=retry_replace) as attempt: - self.assertEqual(spirv_stubs.generate_for_index(tmp, index), written) - self.assertEqual(attempt.call_count, 2) - self.assertEqual(os.listdir(os.path.join(tmp, "stubs")), written) - - @unittest.skipUnless(os.name == "posix", "POSIX file mode") - def test_rebuild_preserves_existing_mode(self): - index = {"ps": {"stage": "ps", "inputs": [0]}} - with tempfile.TemporaryDirectory() as tmp: - written = spirv_stubs.generate_for_index(tmp, index) - target = Path(tmp) / "stubs" / written[0] - target.chmod(0o640) - self.assertEqual(spirv_stubs.generate_for_index(tmp, index), written) - self.assertEqual(target.stat().st_mode & 0o777, 0o640) - - def test_required_stubs_and_deduplication(self): - index = { - "cs_a": {"stage": "cs"}, - "ps_a": {"stage": "ps", "inputs": [0, 1], "outputs": [0]}, - "ps_b": {"stage": "ps", "inputs": [1, 0], "outputs": [0, 1]}, # same VS stub as ps_a - "ps_c": {"stage": "ps", "outputs": [0]}, - "vs_a": {"stage": "vs", "outputs": [0, 1]}, - "ms_a": {"stage": "ms", "params": [0, 1]}, # same PS stub as vs_a - "gs_a": {"stage": "gs", "gs_inputs": [0, 1], "gs_outputs": [0, 1], - "gs_input_locations": [1], "gs_output_locations": [1]}, - "gs_legacy": {"stage": "gs", "gs_inputs": [1, 0, 1], "gs_outputs": [1, 0], - "gs_output_locations": None}, - } - with tempfile.TemporaryDirectory() as tmp: - written = spirv_stubs.generate_for_index(tmp, index) - self.assertEqual(written, ["ps_0_1.spv", "ps_1.spv", "vs_empty.spv", "vs_0_1.spv", "vs_1.spv"]) - for fname in written: - path = os.path.join(tmp, "stubs", fname) - self.assertTrue(os.path.isfile(path)) - with open(path, "rb") as f: - self._maybe_spirv_val(f.read()) - - # CLI smoke test on index.json. - with open(os.path.join(tmp, "index.json"), "w", encoding="utf-8") as f: - json.dump(index, f) - self.assertEqual(spirv_stubs.main([tmp]), 0) - - -class ShaderMetaTests(unittest.TestCase): - def test_shader_meta_graphics_fields(self): - # PS with flat + interpolated inputs and depth write. - g = rdna2spirv.Gen("ps") - g.inputs = {"%in_0": 0, "%in_1": 1} - g.interpolated = {"%in_1"} - g.outputs = {"%out_0": "mrt0", "%out_2": "mrt2"} - g.writes_depth = True - m = rdna2spirv.shader_meta(g, "OpCapability Shader\n") - self.assertEqual(m["stage"], "ps") - self.assertEqual(m["inputs"], [0, 1]) - self.assertEqual(m["outputs"], [0, 2]) - self.assertTrue(m["writes_depth"]) - - # GS separating BuiltIn Position (sv == 1) from Location registers. - gg = rdna2spirv.Gen("gs") - gg.gs = {"in": [(0, 1), (1, 0), (3, 0)], "out": [(0, 1), (2, 0)], "nreg": 2, "maxv": 4} - mg = rdna2spirv.shader_meta(gg, "OpCapability Geometry\n") - self.assertEqual(mg["gs_inputs"], [0, 1, 3]) - self.assertEqual(mg["gs_outputs"], [0, 2]) - self.assertEqual(mg["gs_input_locations"], [1, 3]) - self.assertEqual(mg["gs_output_locations"], [2]) - self.assertIn("geometryShader", mg["features"]) - - -class MalformedIndexTest(unittest.TestCase): - def run_tool(self, contents): - with tempfile.TemporaryDirectory() as tmp: - with open(os.path.join(tmp, "index.json"), "w", encoding="utf-8") as f: - f.write(contents) - tool = os.path.join(ROOT, "tools", "spirv_stubs.py") - return subprocess.run([sys.executable, "-I", tool, tmp], capture_output=True, text=True) - - def test_bad_index_json_is_one_error_not_a_traceback(self): - p = self.run_tool("not json") - self.assertNotEqual(p.returncode, 0) - self.assertIn("cannot read", p.stderr) - self.assertIn("index.json", p.stderr) - self.assertNotIn("Traceback", p.stderr) - - def test_help_prints_usage_and_exits_zero(self): - tool = os.path.join(ROOT, "tools", "spirv_stubs.py") - for flag in ("-h", "--help"): - with self.subTest(flag=flag): - p = subprocess.run([sys.executable, "-I", tool, flag], capture_output=True, text=True) - self.assertEqual(p.returncode, 0) - self.assertIn("spirv_stubs.py ", p.stdout) - self.assertEqual(p.stderr, "") - self.assertEqual(spirv_stubs.main([flag]), 0) - - def test_valid_json_of_the_wrong_shape_is_one_error(self): - for contents in ("5", "[]"): - with self.subTest(contents=contents): - p = self.run_tool(contents) - self.assertNotEqual(p.returncode, 0) - self.assertIn("cannot read", p.stderr) - self.assertIn("expected a JSON object", p.stderr) - self.assertNotIn("Traceback", p.stderr) - - def test_invalid_graphics_locations_are_one_error_not_a_traceback(self): - cases = ( - ("ps_bad", {"stage": "ps", "inputs": ["not-a-location"]}), - ("vs_bad", {"stage": "vs", "outputs": [None]}), - ("ms_bad", {"stage": "ms", "params": [-1]}), - ("gs_bad", {"stage": "gs", "gs_input_locations": [0x100000000]}), - ) - for name, metadata in cases: - with self.subTest(shader=name): - p = self.run_tool(json.dumps({name: metadata})) - self.assertNotEqual(p.returncode, 0) - self.assertIn("cannot generate stubs", p.stderr) - self.assertIn("index.json", p.stderr) - if name in ("ms_bad", "gs_bad"): - self.assertIn("invalid Location", p.stderr) - self.assertNotIn("Traceback", p.stderr) - - def test_malformed_location_types_stop_the_entire_preflight(self): - cases = ( - {"stage": "ps", "inputs": [1.9]}, - {"stage": "vs", "outputs": [True]}, - {"stage": "ms", "params": ["3"]}, - {"stage": "gs", "gs_input_locations": "23"}, - {"stage": "gs", "gs_output_locations": {"2": 0}}, - {"stage": "gs", "gs_input_locations": None, "gs_inputs": [0.5]}, - ) - for meta in cases: - with self.subTest(meta=meta), tempfile.TemporaryDirectory() as tmp: - index = {"good": {"stage": "ps", "inputs": [0]}, "bad": meta} - with self.assertRaisesRegex(ValueError, "bad: invalid graphics interface locations"): - spirv_stubs.generate_for_index(tmp, index) - self.assertFalse(os.path.exists(os.path.join(tmp, "stubs"))) - - def test_non_finite_location_is_one_error_not_a_traceback(self): - p = self.run_tool('{"ps_bad": {"stage": "ps", "inputs": [1e999]}}') - self.assertNotEqual(p.returncode, 0) - self.assertIn("ps_bad: invalid graphics interface locations", p.stderr) - self.assertNotIn("Traceback", p.stderr) - - -class IndexEncodingTest(unittest.TestCase): - def test_index_saved_with_a_utf8_bom_is_read(self): - # A Windows editor or PowerShell `>` writes the BOM; the JSON behind it is unchanged. - with tempfile.TemporaryDirectory() as tmp: - with open(os.path.join(tmp, "index.json"), "w", encoding="utf-8-sig") as f: - json.dump({"ps_a": {"stage": "ps", "inputs": [0]}}, f) - tool = os.path.join(ROOT, "tools", "spirv_stubs.py") - p = subprocess.run([sys.executable, "-I", tool, tmp], capture_output=True, text=True) - self.assertEqual(p.returncode, 0, p.stderr) - self.assertIn("wrote 1 stubs", p.stdout) - self.assertEqual(os.listdir(os.path.join(tmp, "stubs")), ["vs_0.spv"]) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/test_split_big_switch.py b/tests/test_split_big_switch.py deleted file mode 100644 index 25709c229..000000000 --- a/tests/test_split_big_switch.py +++ /dev/null @@ -1,205 +0,0 @@ -"""Unit tests and spirv-val validation for rdna2spirv.split_big_switch (SHADER-77 / #539). - -Runs with the standard library only (spirv-as/spirv-val test skips if SPIRV-Tools are not on PATH): - python3 -I tests/test_split_big_switch.py - pytest tests/test_split_big_switch.py -""" -import os -import re -import shutil -import subprocess -import sys -import tempfile -import unittest - -ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) -sys.path.insert(0, os.path.join(ROOT, "tools")) -import rdna2spirv # noqa: E402 - -HAVE_SPIRV_TOOLS = bool(shutil.which("spirv-as") and shutil.which("spirv-val")) - - -def make_dispatch_module(n_cases): - """Build a minimal valid Vulkan 1.2 SPIR-V compute module with an n_cases dispatch OpSwitch.""" - cases = " ".join(f"{i} %b{i}" for i in range(n_cases)) - lines = [ - " OpCapability Shader", - " OpMemoryModel Logical GLSL450", - ' OpEntryPoint GLCompute %main "main"', - " OpExecutionMode %main LocalSize 1 1 1", - " %void = OpTypeVoid", - " %fn = OpTypeFunction %void", - " %uint = OpTypeInt 32 0", - " %_ptr_uint = OpTypePointer Function %uint", - " %bool = OpTypeBool", - " %c0 = OpConstant %uint 0", - " %c_done = OpConstant %uint 4294967295", - " %main = OpFunction %void None %fn", - " %entry = OpLabel", - " %pc = OpVariable %_ptr_uint Function", - " OpStore %pc %c0", - " OpBranch %loop", - " %loop = OpLabel", - " OpLoopMerge %loop_exit %loop_cont None", - " OpBranch %loop_hdr", - " %loop_hdr = OpLabel", - " %pcv = OpLoad %uint %pc", - " %done = OpIEqual %bool %pcv %c_done", - " OpSelectionMerge %not_done None", - " OpBranchConditional %done %loop_exit %not_done", - " %not_done = OpLabel", - " OpSelectionMerge %sw_merge None", - f" OpSwitch %pcv %sw_default {cases}", - ] - for i in range(n_cases): - lines.append(f"%b{i} = OpLabel") - lines.append(" OpStore %pc %c_done") - lines.append(" OpBranch %sw_merge") - lines += [ - "%sw_default = OpLabel", - " OpStore %pc %c_done", - " OpBranch %sw_merge", - "%sw_merge = OpLabel", - " OpBranch %loop_cont", - "%loop_cont = OpLabel", - " OpBranch %loop", - "%loop_exit = OpLabel", - " OpReturn", - " OpFunctionEnd", - "", - ] - return "\n".join(lines) - - -class SplitBigSwitchTests(unittest.TestCase): - def test_at_or_below_limit_is_unchanged(self): - for n_cases in (10, 16383): - with self.subTest(n_cases=n_cases): - src = make_dispatch_module(n_cases) - out = rdna2spirv.split_big_switch(src) - self.assertEqual(out, src) - self.assertEqual(len(re.findall(r"^\s*OpSwitch\b", out, re.M)), 1) - self.assertNotIn("%c_swchunk", out) - self.assertNotIn("OpUDiv", out) - - def test_above_case_limit_splits_into_two_chunks(self): - n_cases = 16384 - src = make_dispatch_module(n_cases) - out = rdna2spirv.split_big_switch(src) - self.assertNotEqual(out, src) - - chunk = rdna2spirv.SWITCH_CHUNK - self.assertEqual(chunk, 16000) - self.assertIn(f"%c_swchunk = OpConstant %uint {chunk}", out) - - # %pcc = OpUDiv must sit immediately before OpSelectionMerge %sw_merge None. - self.assertRegex( - out, - r"%pcc = OpUDiv %uint %pcv %c_swchunk\n\s*OpSelectionMerge %sw_merge None\n" - r"\s*OpSwitch %pcc %sw_default 0 %swc0 1 %swc1\n", - ) - - # Two inner chunk switches + one outer switch = 3 OpSwitch instructions. - switches = re.findall(r"^\s*OpSwitch\b.*$", out, re.M) - self.assertEqual(len(switches), 3) - for k in (0, 1): - self.assertIn(f"%swc{k} = OpLabel", out) - self.assertIn(f"OpSelectionMerge %swm{k} None", out) - self.assertRegex(out, rf"(?m)^\s*OpSwitch %pcv %swm{k} ") - - # Boundary blocks route to their chunk's merge; merges sit before %sw_default. - self.assertRegex(out, r"%b0 = OpLabel\n[^\n]+\n\s*OpBranch %swm0\n") - self.assertRegex(out, r"%b15999 = OpLabel\n[^\n]+\n\s*OpBranch %swm0\n") - self.assertRegex(out, r"%b16000 = OpLabel\n[^\n]+\n\s*OpBranch %swm1\n") - self.assertRegex(out, r"%b16383 = OpLabel\n[^\n]+\n\s*OpBranch %swm1\n") - self.assertRegex( - out, - r"%swm0 = OpLabel\n\s*OpBranch %sw_merge\n" - r"%swm1 = OpLabel\n\s*OpBranch %sw_merge\n" - r"%sw_default = OpLabel", - ) - - def test_37220_cases_structure_and_routing(self): - # 37,220 cases => 3 + 2 * 37,220 = 74,443 words in the original OpSwitch (matching #539). - n_cases = 37220 - self.assertEqual(3 + 2 * n_cases, 74443) - src = make_dispatch_module(n_cases) - out = rdna2spirv.split_big_switch(src) - - self.assertIn("%c_swchunk = OpConstant %uint 16000", out) - self.assertRegex( - out, - r"%pcc = OpUDiv %uint %pcv %c_swchunk\n\s*OpSelectionMerge %sw_merge None\n" - r"\s*OpSwitch %pcc %sw_default 0 %swc0 1 %swc1 2 %swc2\n", - ) - - # 1 outer + 3 inner switches, every inner switch well below both 16,383 cases and 65,535 words. - switches = re.findall(r"^\s*OpSwitch\b.*$", out, re.M) - self.assertEqual(len(switches), 4) - for k, expected_count in ((0, 16000), (1, 16000), (2, 5220)): - m = re.search(rf"^\s*OpSwitch %pcv %swm{k} (.+)$", out, re.M) - self.assertIsNotNone(m, f"missing inner switch for chunk {k}") - n_pairs = len(m.group(1).split()) // 2 - self.assertEqual(n_pairs, expected_count) - self.assertLessEqual(n_pairs, 16383) - self.assertLessEqual(3 + 2 * n_pairs, 65535) - - # Representative blocks across all 3 chunks route to %swm0 / %swm1 / %swm2. - self.assertRegex(out, r"%b0 = OpLabel\n[^\n]+\n\s*OpBranch %swm0\n") - self.assertRegex(out, r"%b15999 = OpLabel\n[^\n]+\n\s*OpBranch %swm0\n") - self.assertRegex(out, r"%b16000 = OpLabel\n[^\n]+\n\s*OpBranch %swm1\n") - self.assertRegex(out, r"%b31999 = OpLabel\n[^\n]+\n\s*OpBranch %swm1\n") - self.assertRegex(out, r"%b32000 = OpLabel\n[^\n]+\n\s*OpBranch %swm2\n") - self.assertRegex(out, r"%b37219 = OpLabel\n[^\n]+\n\s*OpBranch %swm2\n") - self.assertRegex( - out, - r"%swm0 = OpLabel\n\s*OpBranch %sw_merge\n" - r"%swm1 = OpLabel\n\s*OpBranch %sw_merge\n" - r"%swm2 = OpLabel\n\s*OpBranch %sw_merge\n" - r"%sw_default = OpLabel", - ) - - @unittest.skipUnless(HAVE_SPIRV_TOOLS, "needs spirv-as and spirv-val on PATH") - def test_37220_cases_spirv_as_and_spirv_val(self): - # Negative control: raw 37,220-case OpSwitch (74,443 words > 65,535 limit) fails spirv-as/spirv-val. - # Positive control: split_big_switch output assembles and passes spirv-val --target-env vulkan1.2. - raw = make_dispatch_module(37220) - split = rdna2spirv.split_big_switch(raw) - - with tempfile.TemporaryDirectory() as td: - raw_spvasm = os.path.join(td, "raw.spvasm") - raw_spv = os.path.join(td, "raw.spv") - with open(raw_spvasm, "w", encoding="utf-8") as f: - f.write(raw) - r_as_raw = subprocess.run( - ["spirv-as", "--target-env", "vulkan1.2", raw_spvasm, "-o", raw_spv], - capture_output=True, text=True, - ) - if r_as_raw.returncode == 0: - r_val_raw = subprocess.run( - ["spirv-val", "--target-env", "vulkan1.2", raw_spv], - capture_output=True, text=True, - ) - self.assertNotEqual( - r_val_raw.returncode, 0, - "expected unsplit 74,443-word OpSwitch to fail spirv-val", - ) - - split_spvasm = os.path.join(td, "split.spvasm") - split_spv = os.path.join(td, "split.spv") - with open(split_spvasm, "w", encoding="utf-8") as f: - f.write(split) - r_as = subprocess.run( - ["spirv-as", "--target-env", "vulkan1.2", split_spvasm, "-o", split_spv], - capture_output=True, text=True, - ) - self.assertEqual(r_as.returncode, 0, f"spirv-as failed:\n{r_as.stderr}") - r_val = subprocess.run( - ["spirv-val", "--target-env", "vulkan1.2", split_spv], - capture_output=True, text=True, - ) - self.assertEqual(r_val.returncode, 0, f"spirv-val failed:\n{r_val.stderr}") - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/test_story_index.py b/tests/test_story_index.py deleted file mode 100644 index 720441cba..000000000 --- a/tests/test_story_index.py +++ /dev/null @@ -1,527 +0,0 @@ -"""Synthetic-header tests for tools/story_index.py. - - python -I tests/test_story_index.py - -Every byte here is built by the test. No game file or game asset name is used. -""" -import contextlib -import csv -import io -import json -import os -import struct -import subprocess -import sys -import tempfile -import unittest -import zlib -from unittest import mock - -ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) -TOOL = os.path.join(ROOT, "tools", "story_index.py") -sys.path.insert(0, os.path.join(ROOT, "tools")) - -import story_index # noqa: E402 - - -def psin(): - data = bytearray(0x200) - data[:4] = b"PSIN" - tags = [b"LSCH", b"LENM", b"LSNS", b"LGID", b"LRSC", b"CHKS"] - sizes = [0x40, 0x30, 0x28, 0x10, 0x18, 0x14] - pos = 0x40 - for tag, size in zip(tags, sizes): - data[pos:pos + 4] = tag - data[pos + 4:pos + 8] = size.to_bytes(4, "big") - pos += size - return bytes(data) - - -def page(): - data = bytearray(0x60) - struct.pack_into("" - return data + bytes(max(0, 64 - len(data))) - - -def raw(): - return b"\x11\x22\x33\x44" + bytes(60) - - -def zero(): - return bytes(64) - - -def text(): - return b"A" * 80 - - -def bink(): - data = bytearray(0x40) - data[:4] = b"KB2n" - struct.pack_into(" int | np.ndarray: - """Invert global block coordinates (img_x, img_y) to raw stored block index.""" - tile_x = img_x // tw - tile_y = img_y // th - x = img_x % tw - y = img_y % th - tiles_x = wblocks // tw - tile = tile_y * tiles_x + tile_x - - is_scalar = not isinstance(img_x, np.ndarray) - inner = 0 if is_scalar else np.zeros_like(img_x, dtype=np.int64) - xi = yi = 0 - for k, c in enumerate(seq): - if c == "x": - bit = (x >> xi) & 1 - xi += 1 - else: - bit = (y >> yi) & 1 - yi += 1 - inner |= bit << k - - per = tw * th - return tile * per + inner - - -def forward_coordinates( - stored_idx: int | np.ndarray, - seq: str | list[str], - tw: int, - th: int, - wblocks: int, -) -> tuple[int | np.ndarray, int | np.ndarray]: - """Forward mapping from stored block index to global block coordinates (img_x, img_y).""" - per = tw * th - tile = stored_idx // per - inner = stored_idx % per - is_scalar = not isinstance(stored_idx, np.ndarray) - x = 0 if is_scalar else np.zeros_like(stored_idx, dtype=np.int64) - y = 0 if is_scalar else np.zeros_like(stored_idx, dtype=np.int64) - xi = yi = 0 - for k, c in enumerate(seq): - bit = (inner >> k) & 1 - if c == "x": - x |= bit << xi - xi += 1 - else: - y |= bit << yi - yi += 1 - tiles_x = wblocks // tw - img_x = (tile % tiles_x) * tw + x - img_y = (tile // tiles_x) * th + y - return img_x, img_y - - -def make_synthetic_gradient_bc1(wb: int, hb: int) -> np.ndarray: - """Create a 2D grid of BC1 blocks with smooth horizontal (R) and vertical (G) gradient.""" - blocks = np.zeros((hb * wb, 8), dtype=np.uint8) - for by in range(hb): - for bx in range(wb): - disp_idx = by * wb + bx - r5 = (bx * 31) // max(1, wb - 1) - g6 = (by * 63) // max(1, hb - 1) - rgb565 = (r5 << 11) | (g6 << 5) - blocks[disp_idx, 0] = rgb565 & 0xFF - blocks[disp_idx, 1] = (rgb565 >> 8) & 0xFF - return blocks - - -def make_synthetic_gradient_bc3(wb: int, hb: int) -> np.ndarray: - """Create a 2D grid of BC3 blocks with smooth gradient in endpoints and alpha.""" - blocks = np.zeros((hb * wb, 16), dtype=np.uint8) - for by in range(hb): - for bx in range(wb): - disp_idx = by * wb + bx - r5 = (bx * 31) // max(1, wb - 1) - g6 = (by * 63) // max(1, hb - 1) - rgb565 = (r5 << 11) | (g6 << 5) - blocks[disp_idx, 8] = rgb565 & 0xFF - blocks[disp_idx, 9] = (rgb565 >> 8) & 0xFF - blocks[disp_idx, 0] = (bx * 255) // max(1, wb - 1) - return blocks - - -def swizzle_blocks(disp_blocks: np.ndarray, seq: str | list[str], tw: int, th: int, wb: int) -> bytes: - """Swizzle row-major display blocks into stored order using the specified bit sequence.""" - nblocks = len(disp_blocks) - pos = swizzle_search.positions(seq, nblocks, tw, th, wb) - stored = np.zeros_like(disp_blocks) - stored[np.arange(nblocks)] = disp_blocks[pos] - return stored.tobytes() - - -@unittest.skipUnless(HAVE_NUMPY, "numpy required") -class TestSwizzleCoordinateInversionAndBitmask(unittest.TestCase): - def test_positions_permutation_bijectivity(self): - """positions must map raw blocks to a complete permutation of range(nblocks).""" - patterns = [ - ("xyxy", 4, 4, 16, 2), # Morton order, square - ("yxyx", 4, 4, 16, 2), # Transposed Morton - ("xxyy", 4, 4, 16, 2), # Clustered X then Y - ("yyxx", 4, 4, 16, 2), # Clustered Y then X - ("xyxyxy", 8, 8, 32, 2), # 64 blocks/tile, 6-bit - ("xyxyx", 8, 4, 32, 2), # Asymmetric: 32 blocks/tile (tw=8, th=4) - ("yxyxy", 4, 8, 16, 4), # Asymmetric: 32 blocks/tile (tw=4, th=8) - ] - for seq, tw, th, wb, rows in patterns: - with self.subTest(seq=seq, tw=tw, th=th, wb=wb): - tiles_x = wb // tw - nblocks = tiles_x * rows * tw * th - pos = swizzle_search.positions(seq, nblocks, tw, th, wb) - self.assertEqual(len(pos), nblocks) - self.assertEqual(pos.min(), 0) - self.assertEqual(pos.max(), nblocks - 1) - np.testing.assert_array_equal(np.sort(pos), np.arange(nblocks)) - - def test_coordinate_inversion_roundtrip_scalar(self): - """Scalar forward_coordinates and invert_coordinates must invert each other exactly.""" - seq = "xyxxyy" - tw, th = 8, 8 - wb = 32 - hb = 16 - for by in range(hb): - for bx in range(wb): - stored = invert_coordinates(bx, by, seq, tw, th, wb) - rx, ry = forward_coordinates(stored, seq, tw, th, wb) - self.assertEqual((rx, ry), (bx, by), f"Mismatch at ({bx}, {by}) -> stored={stored}") - - def test_coordinate_inversion_roundtrip_vector(self): - """Vectorized forward and invert coordinates must round-trip across all blocks.""" - test_cases = [ - ("xyxy", 4, 4, 16, 8), - ("xxyy", 4, 4, 16, 8), - ("xyxyxy", 8, 8, 32, 16), - ("xyxyx", 8, 4, 32, 8), - ("yxyxy", 4, 8, 16, 16), - ] - for seq, tw, th, wb, hb in test_cases: - with self.subTest(seq=seq, tw=tw, th=th): - nblocks = wb * hb - stored_indices = np.arange(nblocks, dtype=np.int64) - ix, iy = forward_coordinates(stored_indices, seq, tw, th, wb) - recovered = invert_coordinates(ix, iy, seq, tw, th, wb) - np.testing.assert_array_equal(recovered, stored_indices) - - def test_positions_matches_forward_coordinates(self): - """Linear display positions from swizzle_search.positions must match forward coordinates.""" - seq = "xyxyxy" - tw, th = 8, 8 - wb = 32 - nblocks = 32 * 16 - pos = swizzle_search.positions(seq, nblocks, tw, th, wb) - stored_indices = np.arange(nblocks, dtype=np.int64) - ix, iy = forward_coordinates(stored_indices, seq, tw, th, wb) - expected_pos = iy * wb + ix - np.testing.assert_array_equal(pos, expected_pos) - - def test_synthetic_bitmask_isolation(self): - """Each bit position k in seq must route strictly to either x or y coordinate.""" - for seq in ("xyxyxy", "xxyyxx", "yyxxyy", "xyxyx", "yxyxy"): - bits = len(seq) - xbits = seq.count("x") - ybits = seq.count("y") - tw = 1 << xbits - th = 1 << ybits - wb = tw * 2 - with self.subTest(seq=seq): - for k in range(bits): - inner_mask = 1 << k - ix, iy = forward_coordinates(inner_mask, seq, tw, th, wb) - expected_xi = seq[:k].count("x") - expected_yi = seq[:k].count("y") - if seq[k] == "x": - self.assertEqual(ix, 1 << expected_xi, f"Bit {k} must shift into x at bit {expected_xi}") - self.assertEqual(iy, 0, f"Bit {k} in seq marked 'x' must leave y as 0") - else: - self.assertEqual(iy, 1 << expected_yi, f"Bit {k} must shift into y at bit {expected_yi}") - self.assertEqual(ix, 0, f"Bit {k} in seq marked 'y' must leave x as 0") - - def test_synthetic_bitmask_composite_patterns(self): - """Composite bitmask patterns must separate correctly across X and Y coordinate bits.""" - seq = "xyxyxy" - tw, th, wb = 8, 8, 16 - ix, iy = forward_coordinates(63, seq, tw, th, wb) - self.assertEqual((ix, iy), (7, 7)) - - ix, iy = forward_coordinates(21, seq, tw, th, wb) - self.assertEqual((ix, iy), (7, 0)) - - ix, iy = forward_coordinates(42, seq, tw, th, wb) - self.assertEqual((ix, iy), (0, 7)) - - def test_multi_tile_striding(self): - """Cross-tile indexing must preserve row-major tile ordering across columns and rows.""" - seq = "xyxy" - tw, th = 4, 4 - wb = 16 - per = tw * th - - self.assertEqual(forward_coordinates(0 * per, seq, tw, th, wb), (0, 0)) - self.assertEqual(forward_coordinates(1 * per, seq, tw, th, wb), (4, 0)) - self.assertEqual(forward_coordinates(4 * per, seq, tw, th, wb), (0, 4)) - self.assertEqual(forward_coordinates(5 * per, seq, tw, th, wb), (4, 4)) - - -@unittest.skipUnless(HAVE_NUMPY, "numpy required") -class TestSwizzleSearchPermutationMatching(unittest.TestCase): - def test_bc1_square_tile_search_matching(self): - """search() must identify ground truth BC1 swizzle sequence as the minimum score winner.""" - bpe = 8 - tile_bytes = 512 - tw, th = 8, 8 - wpx = 64 - wb = wpx // 4 - hb = 8 - seq_true = "xyxyxy" - - disp = make_synthetic_gradient_bc1(wb, hb) - data = swizzle_blocks(disp, seq_true, tw, th, wb) - - results = swizzle_search.search(data, bpe, tile_bytes, [wpx], ntiles=2) - self.assertGreater(len(results), 0, "search() must return candidate results") - - best_score, best_wpx, best_seq = results[0] - self.assertEqual(best_seq, seq_true, "Best candidate must match ground truth swizzle") - self.assertEqual(best_wpx, wpx, "Best candidate must match ground truth width") - - second_score = results[1][0] - self.assertLess(best_score, second_score, "Ground truth score must be strictly lower than runner up") - - def test_bc3_square_tile_search_matching(self): - """search() must identify ground truth BC3 (bpe=16) swizzle sequence as winner.""" - bpe = 16 - tile_bytes = 1024 - tw, th = 8, 8 - wpx = 64 - wb = wpx // 4 - hb = 8 - seq_true = "yxyxxy" - - disp = make_synthetic_gradient_bc3(wb, hb) - data = swizzle_blocks(disp, seq_true, tw, th, wb) - - results = swizzle_search.search(data, bpe, tile_bytes, [wpx], ntiles=2) - self.assertGreater(len(results), 0) - - best_score, best_wpx, best_seq = results[0] - self.assertEqual(best_seq, seq_true) - self.assertEqual(best_wpx, wpx) - self.assertLess(best_score, results[1][0]) - - def test_asymmetric_tile_search_matching(self): - """search() must match ground truth for non-square tiles where bits is odd.""" - bpe = 8 - tile_bytes = 256 - tw, th = 8, 4 - wpx = 64 - wb = wpx // 4 - hb = 8 - seq_true = "xyxyx" - - disp = make_synthetic_gradient_bc1(wb, hb) - data = swizzle_blocks(disp, seq_true, tw, th, wb) - - results = swizzle_search.search(data, bpe, tile_bytes, [wpx], ntiles=4) - self.assertGreater(len(results), 0) - - best_score, best_wpx, best_seq = results[0] - self.assertEqual(best_seq, seq_true) - self.assertEqual(best_wpx, wpx) - self.assertLess(best_score, results[1][0]) - - def test_width_candidate_discrimination(self): - """search() must discriminate between correct width and wrong candidate widths.""" - bpe = 8 - tile_bytes = 512 - tw, th = 8, 8 - true_wpx = 128 - wb = true_wpx // 4 # 32 blocks (4 tiles wide) - hb = 8 # 1 tile high - seq_true = "xyxyxy" - - disp = make_synthetic_gradient_bc1(wb, hb) - data = swizzle_blocks(disp, seq_true, tw, th, wb) - - # Candidate widths including true width (128) and wrong width (64) - results = swizzle_search.search(data, bpe, tile_bytes, [64, 128], ntiles=4) - self.assertGreater(len(results), 0) - self.assertEqual(results[0][1], true_wpx) - self.assertEqual(results[0][2], seq_true) - # Verify score of correct width is strictly better than wrong width - score_true_width = results[0][0] - wrong_width_scores = [r[0] for r in results if r[1] != true_wpx] - self.assertLess(score_true_width, min(wrong_width_scores)) - - def test_search_scores_are_sorted(self): - """search() results must be sorted in ascending order of roughness score.""" - bpe = 8 - tile_bytes = 512 - tw, th = 8, 8 - wb, hb = 16, 8 - disp = make_synthetic_gradient_bc1(wb, hb) - data = swizzle_blocks(disp, "xyxyxy", tw, th, wb) - - results = swizzle_search.search(data, bpe, tile_bytes, [64], ntiles=2) - scores = [r[0] for r in results] - self.assertEqual(scores, sorted(scores)) - - def test_search_skips_incompatible_tile_widths(self): - """search() must cleanly skip widths where wblocks is not divisible by tw.""" - bpe = 8 - tile_bytes = 512 - data = bytes(512 * 4) - results = swizzle_search.search(data, bpe, tile_bytes, [48], ntiles=2) - self.assertEqual(results, []) - - def test_search_empty_when_buffer_too_small(self): - """search() must return empty list if raw data is smaller than one row of tiles.""" - bpe = 8 - tile_bytes = 65536 - data = bytes(128) - results = swizzle_search.search(data, bpe, tile_bytes, [1024], ntiles=48) - self.assertEqual(results, []) - - -class TestSwizzleSearchCliAndRender(unittest.TestCase): - @unittest.skipUnless(HAVE_NUMPY and HAVE_PIL, "numpy and PIL required") - def test_default_tile_target_previews_a_short_complete_row(self) -> None: - with tempfile.TemporaryDirectory() as td: - blob = Path(td) / "two_tiles.bin" - preview = Path(td) / "preview.png" - red_block = bytes.fromhex("00 f8 00 00 00 00 00 00") - green_block = bytes.fromhex("e0 07 00 00 00 00 00 00") - blob.write_bytes(red_block * 64 + green_block * 64) - - result = subprocess.run( - [sys.executable, "-I", str(TOOL), str(blob), "--tile", "512", "--widths", "64", - "--out", str(preview)], - capture_output=True, text=True, - ) - self.assertEqual(result.returncode, 0, result.stderr) - with Image.open(preview) as image: - self.assertEqual(image.size, (64, 32)) - expected_row = bytes((255, 0, 0)) * 32 + bytes((0, 255, 0)) * 32 - self.assertEqual(image.tobytes(), expected_row * 32) - - @unittest.skipUnless(HAVE_NUMPY, "numpy required") # the tool imports numpy before it parses arguments - def test_cli_bad_numeric_arguments_are_usage_errors(self): - """Bad --bpe/--tile/--widths/--tiles must be usage errors, not arithmetic tracebacks.""" - cases = [ - (["--bpe", "0"], "--bpe must be at least 1"), - (["--bpe", "4"], "--bpe must be 8 or 16"), - (["--tile", "0"], "--tile must be a multiple"), - (["--tile", "1"], "--tile must be a multiple"), - (["--tile", "3"], "--tile must be a multiple"), - (["--tile", "24"], "--tile / --bpe must be a power of two"), - (["--widths", "0"], "--widths must be positive multiples of 4"), - (["--widths", "abc"], "--widths must be a comma-separated list"), - (["--tiles", "0"], "--tiles must be at least 1"), - ] - with tempfile.TemporaryDirectory() as td: - blob = Path(td) / "valid.bin" - blob.write_bytes(bytes(8 * 16 * 8)) - for args, expected in cases: - with self.subTest(args=args): - result = subprocess.run( - [sys.executable, "-I", str(TOOL), str(blob)] + args, - capture_output=True, text=True, - ) - self.assertEqual(result.returncode, 2, result.stderr) - self.assertIn(expected, result.stderr) - self.assertNotIn("Traceback", result.stderr) - - @unittest.skipUnless(HAVE_NUMPY, "numpy required") - def test_cli_missing_input_is_an_error_not_a_traceback(self): - with tempfile.TemporaryDirectory() as tmp: - missing = os.path.join(tmp, "definitely_missing_path") - result = subprocess.run( - [sys.executable, "-I", str(TOOL), missing], capture_output=True, text=True - ) - self.assertEqual(result.returncode, 2) - self.assertIn("ERROR: cannot read", result.stderr) - self.assertIn("definitely_missing_path", result.stderr) - self.assertNotIn("Traceback", result.stderr) - - @unittest.skipUnless(HAVE_NUMPY, "numpy required") # the tool imports numpy before it parses arguments - def test_preview_with_no_fitting_layout_reports_the_problem(self): - """CLI with tiny blob and --out must exit 1, report 'no layout', and not create file.""" - with tempfile.TemporaryDirectory() as td: - blob = Path(td) / "tiny.bin" - blob.write_bytes(bytes(32)) - preview = Path(td) / "preview.png" - result = subprocess.run( - [sys.executable, "-I", str(TOOL), str(blob), "--out", str(preview)], - capture_output=True, - text=True, - ) - self.assertEqual(result.returncode, 1) - self.assertIn("no layout", result.stderr.lower()) - self.assertNotIn("Traceback", result.stderr) - self.assertFalse(preview.exists()) - - @unittest.skipUnless(HAVE_NUMPY, "numpy required") - def test_cli_successful_search_output(self): - """CLI on valid synthetic buffer must exit 0 and print formatted scores and bit sequences.""" - with tempfile.TemporaryDirectory() as td: - blob = Path(td) / "valid.bin" - blob.write_bytes(bytes(8 * 16 * 8)) - result = subprocess.run( - [ - sys.executable, - "-I", - str(TOOL), - str(blob), - "--bpe", - "8", - "--tile", - "512", - "--widths", - "64", - "--tiles", - "2", - ], - capture_output=True, - text=True, - ) - self.assertEqual(result.returncode, 0) - self.assertIn("score", result.stdout) - self.assertIn("bits(low->high)", result.stdout) - self.assertNotIn("Traceback", result.stderr) - - @unittest.skipUnless(HAVE_NUMPY and HAVE_PIL, "numpy and PIL required") - def test_preview_rejects_input_and_hardlink_alias(self): - """A preview must not overwrite the input or a hard link to it.""" - for hardlink in (False, True): - with self.subTest(hardlink=hardlink): - with tempfile.TemporaryDirectory() as td: - blob = Path(td) / "input.png" - original = bytes(8 * 16 * 8) - blob.write_bytes(original) - - output = Path(td) / "alias.png" if hardlink else blob - if hardlink: - try: - os.link(blob, output) - except (OSError, NotImplementedError) as e: - self.skipTest(f"hard links unavailable: {e}") - - result = subprocess.run( - [ - sys.executable, "-I", str(TOOL), str(blob), - "--bpe", "8", - "--tile", "512", - "--widths", "64", - "--tiles", "2", - "--out", str(output), - ], - capture_output=True, - text=True, - ) - - self.assertNotEqual(result.returncode, 0, result.stdout) - self.assertIn("overwrite", result.stderr.lower()) - self.assertEqual(blob.read_bytes(), original) - self.assertEqual(output.read_bytes(), original) - - @unittest.skipUnless(HAVE_NUMPY and HAVE_PIL, "numpy and PIL required") - def test_preview_ranks_thin_candidates_by_their_existing_edges(self) -> None: - from PIL import Image - - green = bytes.fromhex("e007 0000 00000000") - white = bytes.fromhex("ffff 0000 00000000") - with tempfile.TemporaryDirectory() as td: - blob = Path(td) / "input.bin" - preview = Path(td) / "preview.png" - # Two complete green tiles for an 8x8 candidate. The narrower - # candidate also samples a third tile and sees a green/white edge. - blob.write_bytes(green * 4 + white * 2) - result = subprocess.run( - [sys.executable, "-I", str(TOOL), str(blob), "--tile", "16", - "--widths", "4,8", "--tiles", "3", "--out", str(preview)], - capture_output=True, text=True, check=False, - ) - self.assertEqual(result.returncode, 0, result.stderr) - with Image.open(preview) as image: - self.assertEqual(image.size, (8, 8)) - self.assertEqual(image.getcolors(), [(64, (0, 255, 0))]) - self.assertNotIn("nan", result.stdout.lower()) - - @unittest.skipUnless(HAVE_NUMPY and HAVE_PIL, "numpy and PIL required") - def test_render_bc1_synthetic_output(self): - """render() must decode synthetic BC1 data and save a valid PNG preview.""" - with tempfile.TemporaryDirectory() as td: - out_path = Path(td) / "preview_bc1.png" - data = bytes(8 * 16 * 8) - swizzle_search.render(data, 8, 512, 64, "xyxyxy", str(out_path)) - self.assertTrue(out_path.exists()) - self.assertGreater(out_path.stat().st_size, 0) - with open(out_path, "rb") as f: - header = f.read(8) - self.assertEqual(header, b"\x89PNG\r\n\x1a\n") - - @unittest.skipUnless(HAVE_NUMPY and HAVE_PIL, "numpy and PIL required") - def test_render_bc3_synthetic_output(self): - """render() must decode synthetic BC3/BC10 data and save a valid PNG preview.""" - with tempfile.TemporaryDirectory() as td: - out_path = Path(td) / "preview_bc3.png" - data = bytes(16 * 16 * 8) - swizzle_search.render(data, 16, 1024, 64, "xyxyxy", str(out_path)) - self.assertTrue(out_path.exists()) - self.assertGreater(out_path.stat().st_size, 0) - with open(out_path, "rb") as f: - header = f.read(8) - self.assertEqual(header, b"\x89PNG\r\n\x1a\n") - - -def _load_swizzle_search_no_numpy(): - if HAVE_NUMPY: - return swizzle_search - spec = importlib.util.spec_from_file_location("swizzle_search_out_guard_test", str(TOOL)) - mod = importlib.util.module_from_spec(spec) - with mock.patch.dict(sys.modules, {"numpy": mock.MagicMock()}): - spec.loader.exec_module(mod) - return mod - - -class TestSwizzleSearchOutGuard(unittest.TestCase): - @classmethod - def setUpClass(cls): - cls.mod = _load_swizzle_search_no_numpy() - - def test_bad_out_paths_fail_before_search(self): - with tempfile.TemporaryDirectory() as td: - root = Path(td) - blob = root / "blob.bin" - blob.write_bytes(bytes(64)) - existing_dir = root / "outdir" - existing_dir.mkdir() - regular_file = root / "notadir.txt" - regular_file.write_text("x", encoding="utf-8") - - bad_outs = ( - "", - " ", - "bad\x00out.png", - str(existing_dir), - str(root / "trailing") + os.sep, - str(regular_file / "sub" / "preview.png"), - ) - for bad in bad_outs: - with self.subTest(out=bad): - err = io.StringIO() - with mock.patch.object(self.mod, "search") as mock_search: - with mock.patch.object(sys, "stderr", err): - rc = self.mod.main([str(blob), "--out", bad]) - self.assertEqual(rc, 2) - mock_search.assert_not_called() - self.assertIn("ERROR:", err.getvalue()) - self.assertNotIn("Traceback", err.getvalue()) - - def test_empty_search_without_out_reports_error(self): - with tempfile.TemporaryDirectory() as td: - blob = Path(td) / "blob.bin" - blob.write_bytes(bytes(64)) - err = io.StringIO() - with mock.patch.object(self.mod, "search", return_value=[]): - with mock.patch.object(sys, "stderr", err): - rc = self.mod.main([str(blob)]) - self.assertEqual(rc, 1) - self.assertIn("ERROR: no layout fits", err.getvalue()) - - def test_valid_nested_out_creates_parent_dirs_and_handles_render_oserror(self): - with tempfile.TemporaryDirectory() as td: - root = Path(td) - blob = root / "blob.bin" - blob.write_bytes(bytes(512)) - nested_out = root / "nested" / "sub" / "preview.png" - - with mock.patch.object(self.mod, "search", return_value=[(1.0, 64, "xyxy")]), \ - mock.patch.object(self.mod, "render") as mock_render: - rc = self.mod.main([str(blob), "--bpe", "8", "--tile", "128", "--widths", "64", "--out", str(nested_out)]) - self.assertIn(rc, (0, None)) - self.assertTrue((root / "nested" / "sub").is_dir()) - mock_render.assert_called_once() - - err = io.StringIO() - with mock.patch.object(self.mod, "search", return_value=[(1.0, 64, "xyxy")]), \ - mock.patch.object(self.mod, "render", side_effect=PermissionError("denied")), \ - mock.patch.object(sys, "stderr", err): - rc_err = self.mod.main([str(blob), "--bpe", "8", "--tile", "128", "--widths", "64", "--out", str(nested_out)]) - self.assertEqual(rc_err, 2) - self.assertIn("ERROR:", err.getvalue()) - self.assertIn("denied", err.getvalue()) - self.assertNotIn("Traceback", err.getvalue()) - - def test_nested_out_does_not_create_dirs_when_blob_missing(self): - with tempfile.TemporaryDirectory() as td: - root = Path(td) - missing_blob = root / "missing.bin" - nested_out = root / "never_created" / "sub" / "preview.png" - err = io.StringIO() - with mock.patch.object(sys, "stderr", err): - rc = self.mod.main([str(missing_blob), "--out", str(nested_out)]) - self.assertEqual(rc, 2) - self.assertFalse((root / "never_created").exists()) - self.assertIn("ERROR:", err.getvalue()) - - def test_render_valueerror_unknown_extension_returns_exit_2(self): - with tempfile.TemporaryDirectory() as td: - root = Path(td) - blob = root / "blob.bin" - blob.write_bytes(bytes(512)) - bad_ext_out = root / "preview.unrecognized" - err = io.StringIO() - with mock.patch.object(self.mod, "search", return_value=[(1.0, 64, "xyxy")]), \ - mock.patch.object(self.mod, "render", side_effect=ValueError("unknown file extension: .unrecognized")), \ - mock.patch.object(sys, "stderr", err): - rc = self.mod.main([str(blob), "--bpe", "8", "--tile", "128", "--widths", "64", "--out", str(bad_ext_out)]) - self.assertEqual(rc, 2) - self.assertIn("ERROR:", err.getvalue()) - self.assertIn("unknown file extension: .unrecognized", err.getvalue()) - self.assertNotIn("Traceback", err.getvalue()) - - -def test_preview_with_no_fitting_layout_reports_the_problem(tmp_path=None): - """Module-level compatibility wrapper for pytest with tmp_path fixture.""" - if not HAVE_NUMPY: - raise unittest.SkipTest("numpy required") - td = None - if tmp_path is None: - td = tempfile.TemporaryDirectory() - tmp_path = Path(td.name) - try: - blob = tmp_path / "tiny.bin" - blob.write_bytes(bytes(32)) - preview = tmp_path / "preview.png" - result = subprocess.run( - [sys.executable, "-I", str(TOOL), str(blob), "--out", str(preview)], - capture_output=True, - text=True, - ) - assert result.returncode == 1 - assert "no layout" in result.stderr.lower() - assert "Traceback" not in result.stderr - assert not preview.exists() - finally: - if td is not None: - td.cleanup() - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/test_tex_export.py b/tests/test_tex_export.py deleted file mode 100644 index eef043f68..000000000 --- a/tests/test_tex_export.py +++ /dev/null @@ -1,716 +0,0 @@ -"""Tests for tools/tex_export.py, on synthetic textures and swizzle equations (no game data, no addrlib header). - - python -m pytest tests/test_tex_export.py -q -""" -import pytest # noqa: E402 (keeps the CI bash loop from running this file) - -import json -import os -import struct -import sys -from collections.abc import Callable -from pathlib import Path - -sys.path.insert(0, os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "tools")) - -np = pytest.importorskip("numpy") -import tex_export as T # noqa: E402 - - -def linear_eq(bpe, xor=False): - """A 4 KB equation in the shape eq4k returns: byte bits, then x bits, then y bits (row-major in the tile). - With xor=True each x bit also takes a y bit, which keeps it a bijection but no longer row-major.""" - lb = (4096 // bpe).bit_length() - 1 - xb, yb = (lb + 1) // 2, lb - (lb + 1) // 2 - low = bpe.bit_length() - 1 - xs = [(1 << k, (1 << (k % yb)) if xor else 0) for k in range(xb)] - return [(0, 0)] * low + xs + [(0, 1 << k) for k in range(yb)] - - -@pytest.fixture -def eq(monkeypatch): - """Install synthetic equations in eq4k's cache, so nothing reads the addrlib header.""" - def install(bpe, xor=False): - monkeypatch.setitem(T._EQ, bpe, linear_eq(bpe, xor)) - return install - - -def tile(elements, offs, nbytes): - """Inverse of detiling: put each row-major element at the address detile_offsets gives it.""" - bpe = elements.shape[1] - buf = np.zeros(nbytes, np.uint8) - buf.reshape(-1, bpe)[offs] = elements - return buf.tobytes() - - -def gradient(we, he, bpe): - y, x = np.mgrid[0:he, 0:we] - e = np.zeros((he * we, bpe), np.uint8) - e[:, 0] = (x * 255 // max(1, we - 1)).reshape(-1) - e[:, 1] = (y * 255 // max(1, he - 1)).reshape(-1) - e[:, 2] = 128 - e[:, 3] = 255 - return e - - -def noise(nbytes, seed=1): - return np.random.default_rng(seed).integers(0, 256, nbytes, dtype=np.uint8).tobytes() - - -def write_blob(carve, archive, off, data): - d = os.path.join(carve, archive) - os.makedirs(d, exist_ok=True) - with open(os.path.join(d, f"{off:012x}.bin"), "wb") as f: - f.write(data) - - -def texture(fmt, fmt_name, w, h, mips, data_off=0, gpu=0x1000, **extra): - t = {"archive": "x.rpf", "cpu": 0xABC, "q_index": 3, "gpu": gpu, "gpu_size": 0, "fmt": fmt, - "fmt_name": fmt_name, "w": w, "h": h, "mips": mips, "data_off": data_off} - t.update(extra) - return t - - -# ---- eq4k ---- - -def test_import_does_not_read_the_addrlib_header(monkeypatch): - import importlib.util - import amd_swizzle - - def no_header(*a, **k): - raise AssertionError("load() called at import") - - monkeypatch.setattr(amd_swizzle, "load", no_header) - spec = importlib.util.spec_from_file_location("tex_export_fresh", T.__file__) - spec.loader.exec_module(importlib.util.module_from_spec(spec)) - - -def test_eq4k_reads_the_patterns_once_and_picks_the_entry_for_bpe(monkeypatch): - calls = [] - bits8 = [0, 0, 0] + [1 << k for k in range(5)] + [(1 << k) << 16 for k in range(4)] - bits4 = [0, 0] + [1 << k for k in range(5)] + [(1 << k) << 16 for k in range(5)] - nibbles = {"NIBBLE01": [bits8[:8], bits4[:8]], "NIBBLE2": [bits8[8:12], bits4[8:12]], - "NIBBLE3": [[0] * 4], "NIBBLE4": [[0] * 4]} - tables = {"GFX10_SW_4K_S_PATINFO": [(1, 1, 1, 0, 0, "SW_4K_S 4 bpe"), (1, 0, 0, 0, 0, "SW_4K_S 8 bpe")]} - - def fake_load(): - calls.append(1) - return nibbles, tables - - monkeypatch.setattr(T, "load", fake_load) - monkeypatch.setattr(T, "_PATTERNS", []) - monkeypatch.setattr(T, "_EQ", {}) - assert T.eq4k(8) == linear_eq(8) - assert T.eq4k(4) == linear_eq(4) - assert T.eq4k(8) == linear_eq(8) - assert len(calls) == 1 - - -# ---- detile_offsets / level_bytes ---- - -@pytest.mark.parametrize("bpe", [1, 2, 4, 8, 16]) -def test_linear_equation_detiles_row_major_tiles(eq, bpe): - eq(bpe) - offs, bw, bh = T.detile_offsets(bpe, 2 * 64, 2 * 64) - assert bw * bh * bpe == 4096 - we = 2 * 64 - y, x = np.divmod(np.arange(we * we), we) - tile_index = (y // bh) * (we // bw) + x // bw - assert np.array_equal(offs, tile_index * (4096 // bpe) + (y % bh) * bw + x % bw) - - -@pytest.mark.parametrize("bpe", [4, 8, 16]) -def test_offsets_are_a_permutation_of_whole_tiles(eq, bpe): - eq(bpe, xor=True) - _, bw, bh = T.detile_offsets(bpe, 1, 1) - we, he = 3 * bw, 2 * bh - offs, _, _ = T.detile_offsets(bpe, we, he) - assert sorted(offs.tolist()) == list(range(we * he)) - assert T.level_bytes(we, he, bpe, bw, bh) == 6 * 4096 - - -def test_partial_tiles_are_padded_to_whole_tiles(eq): - eq(4) - _, bw, bh = T.detile_offsets(4, 1, 1) - assert T.level_bytes(1, 1, 4, bw, bh) == 4096 - assert T.level_bytes(bw + 1, bh, 4, bw, bh) == 2 * 4096 - offs, _, _ = T.detile_offsets(4, bw + 1, 1) - assert int(offs.max()) == 4096 // 4 # first element of the second tile - assert len(set(offs.tolist())) == bw + 1 - - -# ---- dds_bytes ---- - -def test_dds_header_is_a_dx10_texture2d(): - payload = bytes(range(64)) - b = T.dds_bytes(16, 8, 71, payload) - assert len(b) == 128 + 20 + len(payload) - assert b[:4] == b"DDS " - size, flags, h, w, linear = struct.unpack_from(" None: - carve = tmp_path / "carve" - out = tmp_path / "out" - eq(2) - offsets, _, _ = T.detile_offsets(2, 4, 4) - top = np.tile(np.arange(254, 258, dtype=" None: - if pillow_failure == "missing": - monkeypatch.setitem(sys.modules, "PIL", None) - else: - image = pytest.importorskip("PIL.Image") - - def cannot_open(*args: object, **kwargs: object) -> None: - raise OSError("synthetic Pillow DDS decode failure") - - monkeypatch.setattr(image, "open", cannot_open) - - carve, expected = build_case(eq, tmp_path, 28, top_first=False) - out = tmp_path / "out" - row = texture(28, "R8G8B8A8_UNORM", 64, 64, mips=2) - - assert T.export_one(row, carve, str(out), {}) == "ok:last" - assert (out / "x.rpf" / row["export"]["file"]).read_bytes()[148:] == expected - - -def test_gpu_chain_parts_are_read_in_order(eq, tmp_path): - carve, expected = build_case(eq, tmp_path, 10, top_first=True) - with open(os.path.join(carve, "x.rpf", f"{0x1000:012x}.bin"), "rb") as f: - blob = f.read() - os.remove(os.path.join(carve, "x.rpf", f"{0x1000:012x}.bin")) - cut = 12345 - write_blob(carve, "x.rpf", 0x1000, blob[:cut]) - write_blob(carve, "x.rpf", 0x9000, blob[cut:]) - t = texture(10, "R16G16B16A16_FLOAT", 64, 64, mips=2, - gpu_chain=[[0x1000, cut], [0x9000, len(blob) - cut]]) - out = str(tmp_path / "out") - assert T.export_one(t, carve, out, {}) == "ok:first" - with open(os.path.join(out, "x.rpf", t["export"]["file"]), "rb") as f: - assert f.read()[148:] == expected - - -def test_blob_cache_is_reused_for_the_same_blob(eq, tmp_path): - carve, _ = build_case(eq, tmp_path, 10, top_first=True) - cache = {} - t = texture(10, "R16G16B16A16_FLOAT", 64, 64, mips=2) - assert T.export_one(t, carve, str(tmp_path / "out"), cache) == "ok:first" - os.remove(os.path.join(carve, "x.rpf", f"{0x1000:012x}.bin")) # a second read would fail - t2 = texture(10, "R16G16B16A16_FLOAT", 64, 64, mips=2) - assert T.export_one(t2, carve, str(tmp_path / "out"), cache) == "ok:first" - - -def test_blob_cache_distinguishes_different_gpu_chains_at_same_offset(eq, tmp_path): - carve, expected = build_case(eq, tmp_path, 10, top_first=True) - with open(os.path.join(carve, "x.rpf", f"{0x1000:012x}.bin"), "rb") as f: - blob = f.read() - os.remove(os.path.join(carve, "x.rpf", f"{0x1000:012x}.bin")) - cut = 12345 - write_blob(carve, "x.rpf", 0x1000, blob[:cut]) - write_blob(carve, "x.rpf", 0x9000, blob[cut:]) - cache = {} - out = str(tmp_path / "out") - short = texture(10, "R16G16B16A16_FLOAT", 16, 16, mips=1, gpu=0x1000, gpu_size=cut) - assert T.export_one(short, carve, out, cache) == "ok:first" - chained = texture(10, "R16G16B16A16_FLOAT", 64, 64, mips=2, q_index=4, - gpu=0x1000, gpu_size=len(blob), - gpu_chain=[[0x1000, cut], [0x9000, len(blob) - cut]]) - assert T.export_one(chained, carve, out, cache) == "ok:first" - with open(os.path.join(out, "x.rpf", chained["export"]["file"]), "rb") as f: - assert f.read()[148:] == expected - - -@pytest.mark.parametrize("fmt", [9999, 6, 7, 8]) # 6-8: 12-byte R32G32B32 has no SW_4K_S equation -def test_unsupported_format_is_reported(fmt): - assert T.export_one(texture(fmt, "X", 4, 4, 1), "unused", "unused", {}) == "unsupported format" - - -@pytest.mark.parametrize("fmt,bpe", [(61, 1), (56, 2), (10, 8), (28, 4)]) -@pytest.mark.parametrize("w,h", [(5, 3), (5, 1), (1, 5)]) -def test_score_prefers_a_smooth_gradient(fmt, bpe, w, h): - if fmt in T.PILLOW_OK: - pytest.importorskip("PIL") - pixels = max(w, h) - values = [i * 240 // (pixels - 1) for i in range(pixels)] - zigzag = values[::2] + values[1::2][::-1] - copies = min(w, h) - ramp = b"".join(bytes([value]) * bpe for value in values * copies) - rough = b"".join(bytes([value]) * bpe for value in zigzag * copies) - assert T.score_image(w, h, fmt, ramp, bpe) < T.score_image(w, h, fmt, rough, bpe) - - -def test_bc2_srgb_is_scored_as_bc2(): - pytest.importorskip("PIL") - payload = noise(4 * 4 * 16) - assert T.score_image(16, 16, 75, payload, 16) == T.score_image(16, 16, 74, payload, 16) - - -@pytest.mark.parametrize("fmt", [81, 87, 91]) -def test_score_falls_back_to_raw_elements_when_pillow_cannot_decode(monkeypatch, fmt): - PIL_Image = pytest.importorskip("PIL.Image") - bpe, blk = T.FMT[fmt] - - def unimplemented(*args, **kwargs): - raise NotImplementedError(f"Unimplemented DXGI format {fmt}") - monkeypatch.setattr(PIL_Image, "open", unimplemented) - payload = noise(4 * 4 * bpe, seed=fmt) - score = T.score_image(4 * blk, 4 * blk, fmt, payload, bpe) - assert 0 < score < 1e6 - monkeypatch.setattr(T, "PILLOW_OK", set()) # the branch formats outside PILLOW_OK take - assert score == T.score_image(4 * blk, 4 * blk, fmt, payload, bpe) - - -def test_single_element_has_no_edge_transitions(): - assert T.score_image(1, 1, 61, b"\x80", 1) == 0 - - -def test_data_outside_the_blob_is_reported(eq, tmp_path): - eq(8) - carve = str(tmp_path / "carve") - write_blob(carve, "x.rpf", 0x1000, bytes(100)) - t = texture(10, "R16G16B16A16_FLOAT", 64, 64, mips=1) - assert T.export_one(t, carve, str(tmp_path / "out"), {}) == "data outside GPU blob" - assert "export" not in t - - -# ---- main ---- - -def test_main_writes_the_log_and_honours_limit(eq, tmp_path, monkeypatch, capsys): - carve, _ = build_case(eq, tmp_path, 10, top_first=True) - index = tmp_path / "textures_index.json" - good = texture(10, "R16G16B16A16_FLOAT", 64, 64, mips=2) - bad = texture(9999, "X", 4, 4, 1, gpu=0x2000) - index.write_text(json.dumps([bad, good]), encoding="utf-8") - out = tmp_path / "out" - monkeypatch.setattr(sys, "argv", ["tex_export.py", str(index), carve, str(out)]) - T.main() - log = json.loads((out / "export_log.json").read_text(encoding="utf-8")) - assert [t["gpu"] for t in log] == [0x1000, 0x2000] # sorted by (archive, gpu) - assert log[0]["export"]["place"] == "first" and "export" not in log[1] - assert "2 textures:" in capsys.readouterr().out - - monkeypatch.setattr(sys, "argv", ["tex_export.py", str(index), carve, str(out), "--limit", "1"]) - T.main() - assert len(json.loads((out / "export_log.json").read_text(encoding="utf-8"))) == 1 - - -@pytest.mark.parametrize("value", ["0", "-1", "x"]) -def test_main_rejects_a_limit_below_one(tmp_path, monkeypatch, capsys, value): - # --limit 0 exported every texture (0 read as "no limit") and -1 silently dropped the last one. - index = tmp_path / "textures_index.json" - index.write_text("[]", encoding="utf-8") - out = tmp_path / "out" - monkeypatch.setattr(sys, "argv", ["tex_export.py", str(index), str(tmp_path), str(out), "--limit", value]) - with pytest.raises(SystemExit) as e: - T.main() - assert e.value.code == 2 - assert "--limit" in capsys.readouterr().err - assert not out.exists() - - -# ---- --png ---- - -def read_png(path): - """(width, height, RGBA bytes) of a PNG as encode_png writes it: 8-bit RGBA, filter 0 on every row.""" - import zlib - with open(path, "rb") as f: - b = f.read() - assert b[:8] == b"\x89PNG\r\n\x1a\n" - pos, idat, ihdr = 8, b"", None - while pos < len(b): - n, kind = struct.unpack_from(">I4s", b, pos) - body = b[pos + 8:pos + 8 + n] - if kind == b"IHDR": - ihdr = struct.unpack(">IIBBBBB", body) - elif kind == b"IDAT": - idat += body - pos += 12 + n - w, h, depth, ctype, _, _, interlace = ihdr - assert (depth, ctype, interlace) == (8, 6, 0) - raw = zlib.decompress(idat) - stride = 1 + w * 4 - assert len(raw) == h * stride - assert all(raw[y * stride] == 0 for y in range(h)) - return w, h, b"".join(raw[y * stride + 1:(y + 1) * stride] for y in range(h)) - - -def png_main(tmp_path, monkeypatch, capsys, textures, carve, *flags): - index = tmp_path / "textures_index.json" - index.write_text(json.dumps(textures), encoding="utf-8") - out = tmp_path / "out" - monkeypatch.setattr(sys, "argv", ["tex_export.py", str(index), carve, str(out), *flags]) - code = T.main() - return out, code, capsys.readouterr().out - - -def tree(out): - return sorted(os.path.relpath(os.path.join(r, f), out) for r, _, fs in os.walk(out) for f in fs) - - -def test_main_accepts_png(tmp_path, monkeypatch): - # the usage line documented --png, but argparse stopped with "unrecognized arguments" - index = tmp_path / "textures_index.json" - index.write_text("[]", encoding="utf-8") - monkeypatch.setattr(sys, "argv", ["tex_export.py", str(index), str(tmp_path), str(tmp_path / "out"), "--png"]) - assert T.main() is None - - -def test_png_is_written_beside_the_dds_with_the_texels(eq, tmp_path, monkeypatch, capsys): - carve, expected = build_case(eq, tmp_path, 28, top_first=True) - t = texture(28, "R8G8B8A8_UNORM", 64, 64, mips=2) - out, code, text = png_main(tmp_path, monkeypatch, capsys, [t], carve, "--png") - assert code is None - stem = f"{0xABC:012x}_3_64x64_R8G8B8A8_UNORM" - assert tree(out) == ["export_log.json", f"x.rpf{os.sep}{stem}.dds", f"x.rpf{os.sep}{stem}.png"] - w, h, rgba = read_png(out / "x.rpf" / (stem + ".png")) - assert (w, h) == (64, 64) - assert rgba == expected # RGBA8 texels pass through unchanged (the gradient sets alpha to 255) - log = json.loads((out / "export_log.json").read_text(encoding="utf-8")) - assert log[0]["export"]["png"] == "written" - assert text.splitlines() == ["1 textures: {'ok:first': 1} -> " + str(out), "png: {'written': 1}"] - - -def test_packed_r10g10b10a2_writes_a_png(eq, tmp_path, monkeypatch, capsys): - eq(4) - packed = struct.pack(" red 255, 128 (green and blue 0, alpha 255) - (54, "R16_FLOAT", [0x3C00, 0x3800], [255, 0, 0, 255, 128, 0, 0, 255]), - # (+inf, NaN, -1, 0.5) and (0.25, 2, 0, 1): +inf and 2 saturate, NaN and negatives give 0 - (10, "R16G16B16A16_FLOAT", [0x7C00, 0x7E00, 0xBC00, 0x3800, 0x3400, 0x4000, 0x0000, 0x3C00], - [255, 0, 0, 128, 64, 255, 0, 255]), -]) -def test_half_float_png_export(eq, tmp_path, monkeypatch, capsys, fmt, name, codes, rgba): - eq(T.FMT[fmt][0]) - texels = struct.pack(f"<{len(codes)}H", *codes) - carve = str(tmp_path / "carve") - write_blob(carve, "x.rpf", 0x1000, texels.ljust(4096, b"\0")) - out, code, text = png_main(tmp_path, monkeypatch, capsys, [texture(fmt, name, 2, 1, 1)], carve, "--png") - assert code is None - assert text.splitlines()[1] == "png: {'written': 1}" - assert next(out.rglob("*.dds")).read_bytes()[148:] == texels - assert read_png(next(out.rglob("*.png"))) == (2, 1, bytes(rgba)) - - -def test_r32_float_png_export(eq, tmp_path, monkeypatch, capsys): - # dds_png reads R32_FLOAT as linear red: 1.0 and 0.5 -> red 255, 128 (green and blue 0, alpha 255) - eq(4) - texels = struct.pack(" {out}\n" - log = json.loads((out / "export_log.json").read_text(encoding="utf-8")) - assert set(log[0]["export"]) == {"file", "place", "score", "heuristic"} - - -def test_failed_png_write_keeps_the_texture_ok_and_is_counted(eq, tmp_path, monkeypatch, capsys): - carve, _ = build_case(eq, tmp_path, 28, top_first=True) - stem = f"{0xABC:012x}_3_64x64_R8G8B8A8_UNORM" - blocked = tmp_path / "out" / "x.rpf" / (stem + ".png") - blocked.mkdir(parents=True) # a directory at the PNG's path makes the write fail - t = texture(28, "R8G8B8A8_UNORM", 64, 64, mips=2) - out, code, text = png_main(tmp_path, monkeypatch, capsys, [t], carve, "--png") - assert code is None - assert (out / "x.rpf" / (stem + ".dds")).is_file() and blocked.is_dir() - entry = json.loads((out / "export_log.json").read_text(encoding="utf-8"))[0]["export"] - assert entry["png"].startswith("error:") - lines = text.splitlines() - assert lines[0].startswith("1 textures: {'ok:first': 1}") - assert lines[1] == "png: {'" + entry["png"] + "': 1}" - - -def test_stale_export_entry_is_not_counted(eq, tmp_path, monkeypatch, capsys): - carve, _ = build_case(eq, tmp_path, 28, top_first=True) - stale = {"file": "old.dds", "place": "first", "score": 1.0, "png": "written"} - t = texture(28, "R8G8B8A8_UNORM", 64, 64, mips=2, gpu=0x5000, export=stale) # blob 0x5000 does not exist - out, code, text = png_main(tmp_path, monkeypatch, capsys, [t], carve, "--png") - assert text.splitlines()[0].startswith("1 textures: {'error:FileNotFoundError': 1}") - assert text.splitlines()[1] == "png: {}" - -def test_texture_io_error_fails_the_run_but_preserves_successes(eq, tmp_path, monkeypatch, capsys): - carve, _ = build_case(eq, tmp_path, 28, top_first=True) - good = texture(28, "R8G8B8A8_UNORM", 64, 64, mips=2) - missing = texture(28, "R8G8B8A8_UNORM", 64, 64, mips=2, gpu=0x5000) - index = tmp_path / "index.json" - index.write_text(json.dumps([good, missing]), encoding="utf-8") - out = tmp_path / "out" - _argv(monkeypatch, index, carve, out) - assert T.main() == 1 - captured = capsys.readouterr() - assert "1 texture(s) could not be read or written" in captured.err - assert "000000005000.bin" in captured.err - assert "error:FileNotFoundError" in captured.out - exported, failed = json.loads((out / "export_log.json").read_text(encoding="utf-8")) - assert (out / "x.rpf" / exported["export"]["file"]).is_file() - assert "export" not in failed - - -def test_main_reports_export_log_write_failure(tmp_path, monkeypatch, capsys): - index = tmp_path / "index.json" - index.write_text("[]", encoding="utf-8") - out = tmp_path / "out" - (out / "export_log.json").mkdir(parents=True) - _argv(monkeypatch, index, tmp_path, out) - assert T.main() == 1 - captured = capsys.readouterr() - assert "ERROR: cannot write" in captured.err - assert "export_log.json" in captured.err - assert not captured.out - - -# ---- bad index / --out guards (#1607's class in main) ---- - -def _argv(monkeypatch, index, carve, out, *extra): - monkeypatch.setattr(sys, "argv", ["tex_export.py", str(index), str(carve), str(out), *extra]) - - -def test_main_reports_a_non_list_index_as_one_error_line(tmp_path, monkeypatch, capsys): - index = tmp_path / "textures_index.json" - index.write_text('{"files": []}', encoding="utf-8") - out = tmp_path / "out" - _argv(monkeypatch, index, tmp_path, out) - assert T.main() == 2 - err = capsys.readouterr().err - assert err.startswith("ERROR: cannot read "), err - assert len(err.strip().splitlines()) == 1, err - assert not out.exists() - - -def test_main_reports_an_index_row_without_keys(tmp_path, monkeypatch, capsys): - index = tmp_path / "textures_index.json" - index.write_text('[{"gpu": 0}]', encoding="utf-8") - _argv(monkeypatch, index, tmp_path, tmp_path / "out") - assert T.main() == 2 - err = capsys.readouterr().err - assert "ERROR: cannot read " in err, err - assert "row has no 'archive'" in err, err - assert "Traceback" not in err - - -def test_main_reads_an_index_saved_with_a_utf8_bom(tmp_path, monkeypatch, capsys): - index = tmp_path / "textures_index.json" - index.write_text("\ufeff[]", encoding="utf-8") # Notepad and PowerShell's ">" write a BOM - out = tmp_path / "out" - _argv(monkeypatch, index, tmp_path, out) - assert T.main() is None # read as an empty texture list; nothing to export - assert (out / "export_log.json").read_text(encoding="utf-8") == "[]" - assert capsys.readouterr().err == "" - - -def test_main_rejects_an_out_that_is_a_file(tmp_path, monkeypatch, capsys): - index = tmp_path / "textures_index.json" - index.write_text("[]", encoding="utf-8") - out = tmp_path / "existing.txt" - out.write_text("x", encoding="utf-8") - _argv(monkeypatch, index, tmp_path, out) - assert T.main() == 2 - err = capsys.readouterr().err - assert "is a file, not a folder" in err, err - assert out.read_text(encoding="utf-8") == "x" - - -def test_main_reports_an_out_under_an_existing_file(tmp_path, monkeypatch, capsys): - index = tmp_path / "textures_index.json" - index.write_text("[]", encoding="utf-8") - blocker = tmp_path / "file.txt" - blocker.write_text("x", encoding="utf-8") - _argv(monkeypatch, index, tmp_path, blocker / "sub") - assert T.main() == 2 - err = capsys.readouterr().err - assert "ERROR: cannot create " in err, err - assert "Traceback" not in err - - -def test_main_reports_a_dangling_symlink_out(tmp_path, monkeypatch, capsys): - index = tmp_path / "textures_index.json" - index.write_text("[]", encoding="utf-8") - link = tmp_path / "dangling-out" - try: - os.symlink(str(tmp_path / "missing-target"), str(link)) - except (OSError, NotImplementedError): - pytest.skip("symlinks are not available") - _argv(monkeypatch, index, tmp_path, link) - assert T.main() == 2 - err = capsys.readouterr().err - assert "ERROR: cannot create " in err, err - assert "Traceback" not in err - - -def test_main_still_accepts_an_empty_list(tmp_path, monkeypatch, capsys): - index = tmp_path / "textures_index.json" - index.write_text("[]", encoding="utf-8") - out = tmp_path / "out" - _argv(monkeypatch, index, tmp_path, out) - assert T.main() in (None, 0) # main() has no explicit return; sys.exit(None) is exit 0 - assert (out / "export_log.json").is_file() - - -def test_main_refuses_to_overwrite_input_index_as_export_log(tmp_path, monkeypatch, capsys): - out = tmp_path / "out" - out.mkdir() - index = out / "export_log.json" - original = '[{"archive": "a", "gpu": 0}, {"archive": "b", "gpu": 1}]\n' - index.write_text(original, encoding="utf-8", newline="\n") - _argv(monkeypatch, index, tmp_path, out, "--limit", "1") - assert T.main() == 2 - err = capsys.readouterr().err - assert "ERROR:" in err and "must not overwrite" in err, err - assert index.read_text(encoding="utf-8") == original - if os.name == "nt": - _argv(monkeypatch, out / "EXPORT_LOG.JSON", tmp_path, out, "--limit", "1") - assert T.main() == 2 - err = capsys.readouterr().err - assert "ERROR:" in err and "must not overwrite" in err, err - assert index.read_text(encoding="utf-8") == original diff --git a/tests/test_tex_headers.py b/tests/test_tex_headers.py deleted file mode 100644 index 836f55ca2..000000000 --- a/tests/test_tex_headers.py +++ /dev/null @@ -1,1211 +0,0 @@ -"""Unit tests for tools/tex_headers.py: DDS header synthesis, mipmap dimension calculations, -GFX10 format mapping, and texture descriptor parsing from synthetic blobs. - - python -I tests/test_tex_headers.py -""" -import contextlib -import io -import json -import os -import struct -import subprocess -import sys -import tempfile -import unittest -from unittest import mock - -ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) -if ROOT not in sys.path: - sys.path.insert(0, ROOT) -TOOLS_DIR = os.path.join(ROOT, "tools") -if TOOLS_DIR not in sys.path: - sys.path.insert(0, TOOLS_DIR) - -import tex_headers - - -class TestGFX10FormatMapping(unittest.TestCase): - def test_known_bc_format_mappings(self): - cases = [ - (169, 71, "BC1_UNORM"), - (170, 72, "BC1_UNORM_SRGB"), - (171, 74, "BC2_UNORM"), - (172, 75, "BC2_UNORM_SRGB"), - (173, 77, "BC3_UNORM"), - (174, 78, "BC3_UNORM_SRGB"), - (175, 80, "BC4_UNORM"), - (176, 81, "BC4_SNORM"), - (177, 83, "BC5_UNORM"), - (178, 84, "BC5_SNORM"), - (179, 95, "BC6H_UF16"), - (180, 96, "BC6H_SF16"), - (181, 98, "BC7_UNORM"), - (182, 99, "BC7_UNORM_SRGB"), - ] - for gfx10_code, expected_dxgi, expected_name in cases: - with self.subTest(gfx10=gfx10_code, name=expected_name): - dxgi_id, name = tex_headers.map_gfx10_format(gfx10_code) - self.assertEqual(dxgi_id, expected_dxgi) - self.assertEqual(name, expected_name) - - def test_known_uncompressed_mappings(self): - cases = [ - (1, 61, "R8_UNORM"), - (7, 56, "R16_UNORM"), - (13, 54, "R16_FLOAT"), - (14, 49, "R8G8_UNORM"), - (22, 41, "R32_FLOAT"), - (29, 34, "R16G16_FLOAT"), - (36, 26, "R11G11B10_FLOAT"), - (50, 24, "R10G10B10A2_UNORM"), - (56, 28, "R8G8B8A8_UNORM"), - (130, 29, "R8G8B8A8_UNORM_SRGB"), - (64, 16, "R32G32_FLOAT"), - (71, 10, "R16G16B16A16_FLOAT"), - (77, 2, "R32G32B32A32_FLOAT"), - ] - for gfx10_code, expected_dxgi, expected_name in cases: - with self.subTest(gfx10=gfx10_code, name=expected_name): - dxgi_id, name = tex_headers.map_gfx10_format(gfx10_code) - self.assertEqual(dxgi_id, expected_dxgi) - self.assertEqual(name, expected_name) - - def test_packed_formats_follow_top_bit_first_names(self): - # GFX10 names list widths from the top bit: 2_10_10_10 is R10G10B10A2, 10_11_11 is R11G11B10. - with open(os.path.join(TOOLS_DIR, "gfx10_formats.json"), encoding="utf-8") as f: - names = json.load(f) - for gfx10, dxgi, name in ((36, 26, "10_11_11_FLOAT"), (50, 24, "2_10_10_10_UNORM"), - (54, 25, "2_10_10_10_UINT")): - with self.subTest(gfx10=gfx10): - self.assertEqual(names[str(gfx10)], "GFX10_FORMAT_" + name) - self.assertEqual(tex_headers.map_gfx10_format(gfx10)[0], dxgi) - self.assertEqual(tex_headers.dxgi_to_gfx10(dxgi), gfx10) - for gfx10 in (43, 44, 48): # 11_11_10_FLOAT, 10_10_10_2_*: no DXGI format has these layouts - with self.subTest(gfx10=gfx10), self.assertRaises(ValueError): - tex_headers.map_gfx10_format(gfx10) - - def test_unsupported_gfx10_raises(self): - for invalid in [0, 9999, -1, 400]: - with self.subTest(invalid=invalid): - with self.assertRaises(ValueError): - tex_headers.map_gfx10_format(invalid) - - def test_dxgi_to_gfx10_roundtrip(self): - major_dxgi = [71, 72, 74, 77, 78, 80, 83, 95, 96, 98, 99, 28, 29, 56, 61] - for dxgi_id in major_dxgi: - with self.subTest(dxgi=dxgi_id): - gfx10 = tex_headers.dxgi_to_gfx10(dxgi_id) - mapped_dxgi, _ = tex_headers.map_gfx10_format(gfx10) - self.assertEqual(mapped_dxgi, dxgi_id) - - def test_unsupported_dxgi_raises(self): - with self.assertRaises(ValueError): - tex_headers.dxgi_to_gfx10(99999) - - def test_dxgi_dict_integrity(self): - for dxgi_id, name in tex_headers.DXGI.items(): - self.assertIsInstance(dxgi_id, int) - self.assertIsInstance(name, str) - self.assertTrue(len(name) > 0) - - -class TestMipmapCalculations(unittest.TestCase): - def test_calc_mipmap_count(self): - cases = [ - (1, 1, 1, 1), - (2, 2, 1, 2), - (4, 4, 1, 3), - (8, 8, 1, 4), - (256, 256, 1, 9), - (1024, 1024, 1, 11), - (1920, 1080, 1, 11), - (4096, 4096, 1, 13), - (512, 64, 1, 10), - (64, 64, 16, 7), - ] - for w, h, d, expected in cases: - with self.subTest(w=w, h=h, d=d): - self.assertEqual(tex_headers.calc_mipmap_count(w, h, d), expected) - - def test_calc_mipmap_count_zero_or_negative(self): - self.assertEqual(tex_headers.calc_mipmap_count(0, 100), 0) - self.assertEqual(tex_headers.calc_mipmap_count(100, 0), 0) - self.assertEqual(tex_headers.calc_mipmap_count(-10, 100), 0) - self.assertEqual(tex_headers.calc_mipmap_count(100, 100, 0), 0) - - def test_calc_mipmap_dimensions_full_chain(self): - levels = tex_headers.calc_mipmap_dimensions(16, 16, 1, mips=0) - expected = [ - (16, 16, 1), - (8, 8, 1), - (4, 4, 1), - (2, 2, 1), - (1, 1, 1), - ] - self.assertEqual(levels, expected) - - def test_calc_mipmap_dimensions_non_square(self): - levels = tex_headers.calc_mipmap_dimensions(32, 8, 1, mips=0) - expected = [ - (32, 8, 1), - (16, 4, 1), - (8, 2, 1), - (4, 1, 1), - (2, 1, 1), - (1, 1, 1), - ] - self.assertEqual(levels, expected) - - def test_calc_mipmap_dimensions_limited_count(self): - levels = tex_headers.calc_mipmap_dimensions(1024, 1024, 1, mips=3) - expected = [ - (1024, 1024, 1), - (512, 512, 1), - (256, 256, 1), - ] - self.assertEqual(levels, expected) - - def test_calc_mipmap_dimensions_3d_volume(self): - levels = tex_headers.calc_mipmap_dimensions(16, 16, 8, mips=0) - expected = [ - (16, 16, 8), - (8, 8, 4), - (4, 4, 2), - (2, 2, 1), - (1, 1, 1), - ] - self.assertEqual(levels, expected) - - def test_calc_mipmap_dimensions_invalid(self): - self.assertEqual(tex_headers.calc_mipmap_dimensions(0, 10), []) - self.assertEqual(tex_headers.calc_mipmap_dimensions(10, -5), []) - - def test_calc_mip_level_bytes_bc1(self): - # BC1 is 8 bytes per 4x4 block - # 4x4 -> 1 block = 8 bytes - self.assertEqual(tex_headers.calc_mip_level_bytes(4, 4, 1, fmt=71), 8) - # 1024x1024 -> 256x256 blocks = 65536 blocks * 8 bytes = 524288 bytes - self.assertEqual(tex_headers.calc_mip_level_bytes(1024, 1024, 1, fmt=71), 524288) - # Sub-block mip levels (2x2, 1x1) must still pad to a 4x4 block - self.assertEqual(tex_headers.calc_mip_level_bytes(2, 2, 1, fmt=71), 8) - self.assertEqual(tex_headers.calc_mip_level_bytes(1, 1, 1, fmt=71), 8) - - def test_calc_mip_level_bytes_bc7(self): - # BC7 is 16 bytes per 4x4 block - self.assertEqual(tex_headers.calc_mip_level_bytes(4, 4, 1, fmt=98), 16) - self.assertEqual(tex_headers.calc_mip_level_bytes(1024, 1024, 1, fmt=98), 1048576) - self.assertEqual(tex_headers.calc_mip_level_bytes(1, 1, 1, fmt=98), 16) - - def test_calc_mip_level_bytes_uncompressed(self): - # R8_UNORM = 1 byte per pixel - self.assertEqual(tex_headers.calc_mip_level_bytes(64, 64, 1, fmt=61), 4096) - # R8G8B8A8_UNORM = 4 bytes per pixel - self.assertEqual(tex_headers.calc_mip_level_bytes(64, 64, 1, fmt=28), 16384) - # R16G16B16A16_FLOAT = 8 bytes per pixel - self.assertEqual(tex_headers.calc_mip_level_bytes(64, 64, 1, fmt=10), 32768) - # R32G32B32A32_FLOAT = 16 bytes per pixel - self.assertEqual(tex_headers.calc_mip_level_bytes(64, 64, 1, fmt=2), 65536) - - def test_calc_mip_level_bytes_aligned(self): - # 8 bytes aligned to 256 -> 256 - self.assertEqual(tex_headers.calc_mip_level_bytes(4, 4, 1, fmt=71, align=256), 256) - # 8 bytes aligned to 4096 -> 4096 - self.assertEqual(tex_headers.calc_mip_level_bytes(4, 4, 1, fmt=71, align=4096), 4096) - - def test_calc_mip_level_bytes_unsupported_format(self): - with self.assertRaises(ValueError): - tex_headers.calc_mip_level_bytes(64, 64, 1, fmt=9999) - - -class TestCompactMipLayout(unittest.TestCase): - def test_descriptor_mode_is_flag_plus_tile_mode(self): - cases = { - 0: (0, 65536), 1: (0, 65536), - 2: (1, 4096), 3: (1, 4096), - 4: (2, 4096), 5: (2, 4096), - 6: (3, 4096), 7: (3, 4096), - 32: (0, 65536), 34: (1, 4096), 36: (2, 4096), 38: (3, 4096), - 18: (9, 4096), 20: (10, 4096), 22: (11, 4096), 24: (12, 4096), - } - for mode, (tile_mode, tile_bytes) in cases.items(): - with self.subTest(mode=mode): - self.assertEqual(tex_headers.gfx10_tile_mode(mode), tile_mode) - self.assertEqual(tex_headers.gfx10_tile_bytes(mode), tile_bytes) - - def test_invalid_mode_rejected(self): - for mode in (-1, -32, "4", None): - with self.subTest(mode=mode): - with self.assertRaises(ValueError): - tex_headers.gfx10_tile_mode(mode) - - def test_known_4k_chain_sizes(self): - lay = tex_headers.compact_layout_for_dxgi(256, 256, 71, 7) - self.assertEqual(lay["size"], 45056) - self.assertEqual(lay["first_tail"], 2) - self.assertEqual(lay["block_w"], 32) - self.assertEqual(lay["block_h"], 16) - self.assertEqual([m["region"] for m in lay["mips"]], - [32768, 8192, 4096, 4096, 4096, 4096, 4096]) - self.assertEqual([m["offset"] for m in lay["mips"][:2]], [12288, 4096]) - self.assertEqual((lay["mips"][2]["tile_x"], lay["mips"][2]["tile_y"]), (16, 0)) - self.assertEqual((lay["mips"][6]["tile_x"], lay["mips"][6]["tile_y"]), (8, 4)) - - def test_known_1024_chain_matches_allocation(self): - lay = tex_headers.compact_layout_for_dxgi(1024, 1024, 71, 9) - self.assertEqual(lay["size"], 700416) - self.assertEqual(lay["first_tail"], 4) - self.assertEqual([m["region"] for m in lay["mips"][:4]], - [524288, 131072, 32768, 8192]) - self.assertEqual([m["offset"] for m in lay["mips"][:4]], - [176128, 45056, 12288, 4096]) - self.assertTrue(tex_headers.compact_span_matches(lay, 700416)) - - def test_known_64k_tile_chain(self): - lay = tex_headers.compact_layout_for_dxgi(1024, 1024, 98, 9, - tile=tex_headers.COMPACT_TILE_64K) - self.assertEqual(lay["tile"], 65536) - self.assertEqual(lay["first_tail"], 3) - self.assertEqual(lay["size"], 1441792) - self.assertEqual([m["region"] for m in lay["mips"][:3]], - [1048576, 262144, 65536]) - - def test_non_square_chain(self): - lay = tex_headers.compact_layout_for_dxgi(512, 256, 71, 7) - self.assertEqual(lay["size"], 90112) - self.assertEqual(lay["first_tail"], 3) - self.assertEqual([m["region"] for m in lay["mips"][:3]], - [65536, 16384, 4096]) - self.assertEqual(lay["mips"][3]["pixels_w"], 64) - self.assertEqual(lay["mips"][3]["pixels_h"], 32) - - def test_single_mip_is_padded_to_one_tile(self): - lay = tex_headers.compact_layout_for_dxgi(64, 64, 71, 1) - self.assertEqual(lay["size"], 4096) - self.assertEqual(lay["first_tail"], 1) - self.assertEqual(lay["mips"][0]["offset"], 0) - self.assertEqual(lay["mips"][0]["region"], 4096) - self.assertFalse(lay["mips"][0]["in_tail"]) - - def test_sub_tile_mips_share_the_tail(self): - lay = tex_headers.compact_layout_for_dxgi(8, 4, 71, 2) - self.assertEqual(lay["size"], 4096) - self.assertEqual(lay["first_tail"], 0) - self.assertTrue(all(m["in_tail"] for m in lay["mips"])) - self.assertEqual([(m["tile_x"], m["tile_y"]) for m in lay["mips"]], - [(16, 0), (8, 8)]) - - def test_uncompressed_chain_is_sized_by_pixels(self): - lay = tex_headers.compact_layout_for_dxgi(128, 128, 28, 8) - self.assertEqual(lay["element_bytes"], 4) - self.assertEqual(lay["size"], 90112) - self.assertEqual(lay["first_tail"], 3) - self.assertEqual([m["region"] for m in lay["mips"][:3]], - [65536, 16384, 4096]) - self.assertEqual(lay["mips"][0]["blocks_w"], 128) - self.assertEqual(lay["mips"][0]["blocks_h"], 128) - - def test_size_is_standalone_regions_plus_one_tail_tile(self): - for args in [(256, 256, 71, 7), (1024, 1024, 98, 9), - (128, 256, 98, 6), (512, 256, 28, 9)]: - with self.subTest(args=args): - lay = tex_headers.compact_layout_for_dxgi(*args) - standalone = sum(m["region"] for m in lay["mips"] if not m["in_tail"]) - tail = lay["tile"] if lay["first_tail"] < len(lay["mips"]) else 0 - self.assertEqual(lay["size"], standalone + tail) - self.assertTrue(tex_headers.compact_span_matches(lay, lay["size"])) - - def test_inconsistent_span_rejected(self): - lay = tex_headers.compact_layout_for_dxgi(256, 256, 71, 7) - self.assertTrue(tex_headers.compact_span_matches(lay, 45056)) - self.assertFalse(tex_headers.compact_span_matches(lay, 45057)) - self.assertFalse(tex_headers.compact_span_matches(lay, 40960)) - self.assertFalse(tex_headers.compact_span_matches(lay, None)) - - def test_invalid_mip_counts_rejected(self): - for width, height, mips in [(256, 256, 0), (256, 256, -1), - (64, 64, 20), (1, 1, 2)]: - with self.subTest(width=width, height=height, mips=mips): - with self.assertRaises(ValueError): - tex_headers.compact_surface_layout(width, height, mips, 8, 4) - - def test_invalid_sizes_rejected(self): - bad = [ - dict(width=0, height=256, mips=1, element_bytes=8, block=4), - dict(width=256, height=-1, mips=1, element_bytes=8, block=4), - dict(width=256, height=256, mips=7, element_bytes=3, block=4), - dict(width=256, height=256, mips=7, element_bytes=12, block=4), - dict(width=256, height=256, mips=7, element_bytes=8, block=2), - dict(width=256, height=256, mips=7, element_bytes=8, block=4, tile=8192), - ] - for case in bad: - with self.subTest(case=case): - with self.assertRaises(ValueError): - tex_headers.compact_surface_layout(**case) - - def test_unknown_dxgi_format_rejected(self): - with self.assertRaises(ValueError): - tex_headers.compact_layout_for_dxgi(256, 256, 9999, 7) - - def test_parse_etpf_record(self): - a = (512 - 1) | ((256 - 1) << 14) | (7 << 28) - b = 1 | (71 << 3) | (0 << 11) | (1 << 21) | (4 << 23) - c = 0x1234 | (0x103 << 21) - d = 0x04030201 - desc = tex_headers.parse_etpf_texture_record(struct.pack(" bit 10 set) - (54, 8, 3), # 3D volume: depth - 1 = 7 (odd -> bit 10 set) - ] - for fmt, depth, dim in cases: - with self.subTest(fmt=fmt, depth=depth, dim=dim): - a = (64 - 1) | ((64 - 1) << 14) | (1 << 28) - b = 0 | (fmt << 3) | ((depth - 1) << 10) | (dim << 21) | (1 << 23) - desc = tex_headers.parse_etpf_texture_record(struct.pack(" 16 pages). - self.assertEqual(tex_headers.decode_etpf_chunk_pages(11, 0), (16,)) - - # Multi-chunk codes spanning the 11-bit meta / extra boundary: - # codes (6, 21, 15, 16) -> pages (6, 18, 64, 128). - val20 = 6 | (21 << 5) | (15 << 10) | (16 << 15) - meta = val20 & 0x7FF - extra_low = val20 >> 11 - # Upper 13 bits of extra carry (align_group=2, pad_pages=9); reserved bits 9..18 = 0. - extra = extra_low | (2 << 19) | (9 << 21) - self.assertEqual(tex_headers.decode_etpf_chunk_pages(meta, extra), (6, 18, 64, 128)) - self.assertEqual(tex_headers.etpf_streaming_padding(extra), (2, 9)) - self.assertEqual(tex_headers.etpf_streaming_padding(0), (0, 0)) - - # Negative controls: unknown 5-bit code (9, 17, 31 not in table). - for bad_code in (9, 17, 25, 31): - with self.subTest(bad_code=bad_code): - self.assertIsNone(tex_headers.decode_etpf_chunk_pages(bad_code, 0)) - - # Negative controls: non-zero code after zero terminator. - self.assertIsNone(tex_headers.decode_etpf_chunk_pages(1 << 5, 0)) - self.assertIsNone(tex_headers.decode_etpf_chunk_pages(1 | (2 << 10), 0)) - - # Negative control: non-zero reserved bits (extra >> 9) & 0x3FF. - for bit in (9, 13, 18): - with self.subTest(reserved_bit=bit): - self.assertIsNone(tex_headers.decode_etpf_chunk_pages(1, 1 << bit)) - - # Negative controls: out-of-range or non-integer inputs. - for bad_meta, bad_extra in [(-1, 0), (0x800, 0), (0, -1), (0, 1 << 32), ("1", 0), (0, None)]: - with self.subTest(meta=bad_meta, extra=bad_extra): - self.assertIsNone(tex_headers.decode_etpf_chunk_pages(bad_meta, bad_extra)) - - def test_array_surface_layout(self): - lay = tex_headers.array_layout_for_dxgi(256, 256, 3, 83, 6, tile=tex_headers.COMPACT_TILE_64K) - self.assertTrue(lay["mip_major"]) - self.assertEqual(lay["depth"], 3) - self.assertEqual(lay["tile"], 65536) - self.assertEqual(lay["first_tail"], 1) - self.assertEqual(lay["slice_size"], 131072) - self.assertEqual(lay["size"], 3 * lay["slice_size"]) - # Packed tail sits at offset 0 with slice_stride == tile; standalone mip 0 follows depth * tile. - self.assertEqual(lay["mips"][1]["offset"], 0) - self.assertEqual(lay["mips"][1]["slice_stride"], 65536) - self.assertEqual(lay["mips"][0]["offset"], 3 * 65536) - self.assertEqual(lay["mips"][0]["slice_stride"], lay["mips"][0]["region"]) - - # Negative controls: depth <= 0 or unknown format. - for bad_depth in (0, -1, "3"): - with self.subTest(depth=bad_depth): - with self.assertRaises(ValueError): - tex_headers.array_surface_layout(256, 256, bad_depth, 6, 16, 4) - with self.assertRaises(ValueError): - tex_headers.array_layout_for_dxgi(256, 256, 2, 9999, 6) - - def test_cubemap_surface_layout(self): - # non_tail=0 (mode 18): single 6-face snapshot at offset 0. - lay0 = tex_headers.cubemap_layout_for_dxgi(128, 128, 71, 6, non_tail=0) - self.assertEqual(lay0["data_offset"], 0) - self.assertEqual(lay0["face_size"], 12288) - self.assertEqual(lay0["full_bytes"], 73728) - self.assertEqual(lay0["padded_full_bytes"], 73728) - self.assertEqual(lay0["size"], 73728) - self.assertEqual(lay0["snapshots"], 1) - self.assertEqual(lay0["depth"], 6) - # Explicit matching 1-chunk list is accepted for non_tail=0. - lay0_pages = tex_headers.cubemap_layout_for_dxgi(128, 128, 71, 6, non_tail=0, chunk_pages=(18,)) - self.assertEqual(lay0_pages["size"], 73728) - - # Streaming non_tail=1 below 36-page 64 KiB padding threshold: 18 pages stays 18 pages. - lay1_small = tex_headers.cubemap_layout_for_dxgi(128, 128, 71, 6, non_tail=1, chunk_pages=(6, 18)) - self.assertEqual(lay1_small["full_bytes"], 18 * 4096) - self.assertEqual(lay1_small["padded_full_bytes"], 18 * 4096) - self.assertEqual(lay1_small["data_offset"], 6 * 4096) - self.assertEqual(lay1_small["size"], 24 * 4096) - self.assertEqual(lay1_small["snapshots"], 2) - - # Streaming non_tail=2 at exact 36-page threshold (128x128 BC7 -> 6 * 24576 = 36 * 4096) - # rounds final chunk up to 64 KiB boundary (48 pages = 196608 bytes). - lay2_thresh = tex_headers.cubemap_layout_for_dxgi(128, 128, 98, 6, non_tail=2, chunk_pages=(6, 12, 48)) - self.assertEqual(lay2_thresh["full_bytes"], 36 * 4096) - self.assertEqual(lay2_thresh["padded_full_bytes"], 48 * 4096) - self.assertEqual(lay2_thresh["data_offset"], 18 * 4096) - self.assertEqual(lay2_thresh["size"], 66 * 4096) - self.assertEqual(lay2_thresh["snapshots"], 3) - - # Streaming non_tail=3 above threshold (256x256 BC1 -> 6 * 45056 = 66 * 4096 -> 80 * 4096). - lay3 = tex_headers.cubemap_layout_for_dxgi(256, 256, 71, 7, non_tail=3, chunk_pages=(6, 12, 24, 80)) - self.assertEqual(lay3["full_bytes"], 66 * 4096) - self.assertEqual(lay3["padded_full_bytes"], 80 * 4096) - self.assertEqual(lay3["data_offset"], 42 * 4096) - self.assertEqual(lay3["size"], 122 * 4096) - - # Negative controls: bad non_tail, wrong len(chunk_pages), final chunk size mismatch, bad format. - for bad_nt in (-1, 4, "1"): - with self.subTest(non_tail=bad_nt): - with self.assertRaises(ValueError): - tex_headers.cubemap_layout_for_dxgi(128, 128, 71, 6, non_tail=bad_nt) - with self.assertRaises(ValueError): - tex_headers.cubemap_layout_for_dxgi(128, 128, 71, 6, non_tail=1, chunk_pages=(18,)) - with self.assertRaises(ValueError): - tex_headers.cubemap_layout_for_dxgi(128, 128, 71, 6, non_tail=0, chunk_pages=(6, 18)) - with self.assertRaises(ValueError): - tex_headers.cubemap_layout_for_dxgi(128, 128, 71, 6, non_tail=1, chunk_pages=(6, 16)) - with self.assertRaises(ValueError): - tex_headers.cubemap_layout_for_dxgi(128, 128, 98, 6, non_tail=2, chunk_pages=(6, 12, 36)) - with self.assertRaises(ValueError): - tex_headers.cubemap_layout_for_dxgi(128, 128, 9999, 6, non_tail=0) - - def test_volume_surface_layout(self): - v1 = tex_headers.volume_layout_for_dxgi(256, 32, 8, 54) - self.assertEqual(v1["size"], 262144) - self.assertEqual((v1["block_d"], v1["padded_d"]), (16, 16)) - - v2 = tex_headers.volume_layout_for_dxgi(32, 32, 32, 10) - self.assertEqual(v2["size"], 262144) - self.assertEqual((v2["block_d"], v2["padded_d"]), (8, 32)) - - v3 = tex_headers.volume_layout_for_dxgi(32, 64, 32, 10) - self.assertEqual(v3["size"], 524288) - self.assertEqual((v3["block_d"], v3["padded_d"]), (8, 32)) - - # Negative controls: mips != 1, BC format, invalid dims, invalid element size, unknown format. - for bad_mips in (0, 2): - with self.subTest(mips=bad_mips): - with self.assertRaises(ValueError): - tex_headers.volume_layout_for_dxgi(32, 32, 32, 10, mips=bad_mips) - with self.assertRaises(ValueError): - tex_headers.volume_layout_for_dxgi(32, 32, 8, 71) - with self.assertRaises(ValueError): - tex_headers.volume_layout_for_dxgi(32, 32, 8, 9999) - for bad_args in [(0, 32, 8, 1, 2), (32, -1, 8, 1, 2), (32, 32, 0, 1, 2), (32, 32, 8, 1, 3)]: - with self.subTest(bad_args=bad_args): - with self.assertRaises(ValueError): - tex_headers.volume_surface_layout(*bad_args) - - -class TestDDSHeaderSynthesis(unittest.TestCase): - def test_dds_header_2d_basic(self): - hdr = tex_headers.dds_header(512, 256, depth=1, mips=1, fmt=28, is_cube=False, linear_size=512 * 256 * 4) - self.assertEqual(len(hdr), 148) - self.assertEqual(hdr[:4], b"DDS ") - - info = tex_headers.parse_dds_header(hdr) - self.assertEqual(info["magic"], b"DDS ") - self.assertEqual(info["width"], 512) - self.assertEqual(info["height"], 256) - self.assertEqual(info["depth"], 0) - self.assertEqual(info["mips"], 1) - self.assertEqual(info["fourcc"], b"DX10") - self.assertEqual(info["dxgi_format"], 28) - self.assertEqual(info["resource_dimension"], tex_headers.D3D10_RESOURCE_DIMENSION_TEXTURE2D) - self.assertEqual(info["misc_flags"], 0) - self.assertEqual(info["array_size"], 1) - - def test_dds_header_with_mips(self): - hdr = tex_headers.dds_header(1024, 1024, depth=1, mips=11, fmt=71) - info = tex_headers.parse_dds_header(hdr) - self.assertEqual(info["width"], 1024) - self.assertEqual(info["height"], 1024) - self.assertEqual(info["mips"], 11) - self.assertTrue(info["flags"] & tex_headers.DDSD_MIPMAPCOUNT) - self.assertTrue(info["caps"] & tex_headers.DDSCAPS_MIPMAP) - self.assertTrue(info["caps"] & tex_headers.DDSCAPS_COMPLEX) - self.assertEqual(info["dxgi_format"], 71) - - def test_dds_header_3d_volume(self): - hdr = tex_headers.dds_header(64, 64, depth=16, mips=1, fmt=28) - info = tex_headers.parse_dds_header(hdr) - self.assertEqual(info["depth"], 16) - self.assertTrue(info["flags"] & tex_headers.DDSD_DEPTH) - self.assertTrue(info["caps2"] & tex_headers.DDSCAPS2_VOLUME) - self.assertEqual(info["resource_dimension"], tex_headers.D3D10_RESOURCE_DIMENSION_TEXTURE3D) - - def test_dds_header_cubemap(self): - hdr = tex_headers.dds_header(256, 256, depth=1, mips=1, fmt=28, is_cube=True) - info = tex_headers.parse_dds_header(hdr) - self.assertTrue(info["caps2"] & tex_headers.DDSCAPS2_CUBEMAP_ALLFACES) - self.assertEqual(info["misc_flags"], tex_headers.D3D10_RESOURCE_MISC_TEXTURECUBE) - self.assertEqual(info["array_size"], 1) - - def test_dds_cubemap_array_size_matches_payload(self): - # DDS_HEADER_DXT10.arraySize counts cubes, each containing six faces: - # https://learn.microsoft.com/en-us/windows/win32/direct3ddds/dds-header-dxt10 - # Check the serialized field directly, independently of our header parser. - for cubes in (1, 2, 6): - with self.subTest(cubes=cubes): - # One RGBA texel per face, with distinct values for every face. - payload = b"".join(bytes((face, 0, 0, 255)) for face in range(cubes * 6)) - dds = tex_headers.dds_bytes(1, 1, fmt=28, payload=payload, - is_cube=True, array_size=cubes) - fmt, dimension, misc, array_size, _ = struct.unpack_from(" None: - cases = ( - # 6x5 RGBA8 top level (120 bytes) and 3x2 next level (24 bytes). - (6, 5, 28, bytes(range(144)), 0x8, 24), - # 9x5 BC1 top level (six blocks) and 4x2 next level (one block). - (9, 5, 71, bytes(range(56)), 0x80000, 48), - ) - for width, height, fmt, payload, expected_flags, expected_size in cases: - with self.subTest(dxgi_format=fmt): - dds = tex_headers.dds_bytes(width, height, fmt, payload, mips=2) - self.assertEqual(dds[148:], payload) - _, flags, got_height, got_width, pitch_or_size, _, mips = struct.unpack_from("<7I", dds, 4) - self.assertEqual((got_width, got_height, mips), (width, height, 2)) - self.assertEqual((flags & (0x8 | 0x80000), pitch_or_size), (expected_flags, expected_size)) - - def test_dds_header_2d_array(self): - hdr = tex_headers.dds_header(256, 256, depth=1, mips=1, fmt=83, is_cube=False, array_size=5) - info = tex_headers.parse_dds_header(hdr) - self.assertEqual(info["resource_dimension"], tex_headers.D3D10_RESOURCE_DIMENSION_TEXTURE2D) - self.assertEqual(info["misc_flags"], 0) - self.assertEqual(info["array_size"], 5) - self.assertTrue(info["caps"] & tex_headers.DDSCAPS_COMPLEX) - self.assertEqual(info["caps2"], 0) - blob = tex_headers.dds_bytes(16, 16, fmt=71, payload=b"\x00" * 128, array_size=4) - self.assertEqual(tex_headers.parse_dds_header(blob)["array_size"], 4) - - def test_dds_bytes_payload(self): - payload = b"\xAA\xBB\xCC\xDD" * 32 # Sixteen BC1 blocks at eight bytes each. - data = tex_headers.dds_bytes(16, 16, fmt=71, payload=payload) - self.assertEqual(len(data), 148 + len(payload)) - self.assertEqual(data[148:], payload) - info = tex_headers.parse_dds_header(data) - self.assertEqual(info["width"], 16) - self.assertEqual(info["height"], 16) - self.assertEqual(info["pitch_linear"], len(payload)) - - def test_parse_corrupt_headers(self): - # Truncated header (< 128 bytes) - with self.assertRaises(ValueError): - tex_headers.parse_dds_header(b"DDS " + b"\x00" * 50) - - # Bad magic - with self.assertRaises(ValueError): - tex_headers.parse_dds_header(b"NOTD" + b"\x00" * 140) - - # Bad header size (not 124) - bad_size = bytearray(b"DDS " + b"\x00" * 140) - struct.pack_into(" None: - cpu_off, gpu_off, index = self._make_synthetic_texture_blobs(w=2, h=3, fmt=28, mips=2) - output = os.path.join(self.carve, "textures.json") - with mock.patch.object(sys, "argv", ["tex_headers.py", self.carve, "--out", output]), \ - contextlib.redirect_stdout(io.StringIO()): - tex_headers.main() - with open(output, encoding="utf-8") as handle: - entries = json.load(handle) - self.assertEqual(len(entries), 1) - entry = entries[0] - self.assertEqual((entry["w"], entry["h"], entry["depth"], entry["mips"]), (2, 3, 1, 2)) - self.assertEqual(entry["fmt_name"], "R8G8B8A8_UNORM") - self.assertEqual((entry["cpu"], entry["gpu"], entry["data_off"], entry["q_index"]), - (cpu_off, gpu_off, 0x1000, index)) - - def test_narrow_texture_requires_a_known_type_and_valid_mips(self) -> None: - for dtype, mips in ((0x900, 1), (0x980, 0), (0x980, 3)): - with self.subTest(dtype=dtype, mips=mips): - self._make_synthetic_texture_blobs(w=1, h=2, fmt=28, mips=mips, dtype=dtype) - self.assertEqual(tex_headers.scan_archive(self.carve, self.arch), []) - - def test_scan_archive_invalid_dimensions_rejected(self): - # Zero width - self._make_synthetic_texture_blobs(w=0, h=256) - self.assertEqual(len(tex_headers.scan_archive(self.carve, self.arch)), 0) - - # Height > 16384 - self._make_synthetic_texture_blobs(w=256, h=20000) - self.assertEqual(len(tex_headers.scan_archive(self.carve, self.arch)), 0) - - # Depth > 2048 - self._make_synthetic_texture_blobs(w=256, h=256, depth=3000) - self.assertEqual(len(tex_headers.scan_archive(self.carve, self.arch)), 0) - - def test_scan_archive_unknown_format_rejected(self): - # Format not in DXGI - self._make_synthetic_texture_blobs(fmt=254) - self.assertEqual(len(tex_headers.scan_archive(self.carve, self.arch)), 0) - - def test_scan_archive_gpu_chain_and_skips(self): - cpu_off = 0x1000 - gpu1_off = 0x2000 - gpu2_off = 0x3000 - bink_off = 0x4000 - - qwords = [0] * 32 - qwords[0] = 0 - qwords[1] = 0x123456789ABCDEF0 - k = 10 - qwords[k - 2] = 1 - qwords[k - 1] = 0x980 - qwords[k] = 0x60000000 + 0x1000 - qwords[k + 4] = struct.unpack("> 16) is 5 - data = self._create_synthetic_page(mips=5, b6=42) - res = tex_headers.parse_texture_dict_page(data) - self.assertEqual(len(res), 2) - self.assertEqual(res[0]["b6"], 42) - self.assertEqual(res[0]["mips"], 5) - self.assertEqual(res[1]["b6"], 42) - self.assertEqual(res[1]["mips"], 5) - - def test_truncated_buffer_raises_value_error(self): - with self.assertRaises(ValueError): - tex_headers.parse_texture_dict_page(b"\x00" * 399) - - def test_all_zeros_returns_empty_list(self): - # Null pointers return no texture records - res = tex_headers.parse_texture_dict_page(b"\x00" * 400) - self.assertEqual(res, []) - - def test_invalid_pointer_tag_skipped(self): - buf = bytearray(self._create_synthetic_page()) - # Pointer without 0x5... tag (e.g. 0x10000040) - struct.pack_into(" np.ndarray: - """Create a 2D smooth pattern of BC1 blocks with varying color endpoints.""" - bpe = 8 - y_coord, x_coord = np.mgrid[0:hb, 0:wb] - img_r = (np.sin(x_coord / 5.0) * 0.5 + 0.5) * 255.0 - img_g = (np.cos(y_coord / 5.0) * 0.5 + 0.5) * 255.0 - img_b = ((x_coord + y_coord) % 32) * (255.0 / 32.0) - - raw_blocks = np.zeros((hb, wb, bpe), dtype=np.uint8) - for y in range(hb): - for x in range(wb): - r = int(img_r[y, x] / 255.0 * 31) - g = int(img_g[y, x] / 255.0 * 63) - b = int(img_b[y, x] / 255.0 * 31) - c = (r << 11) | (g << 5) | b - c_lo, c_hi = c & 0xFF, (c >> 8) & 0xFF - raw_blocks[y, x] = [c_lo, c_hi, c_lo, c_hi, 0, 0, 0, 0] - return raw_blocks - - -def make_swizzled_gpu_buffer( - raw_blocks: np.ndarray, - offsets: np.ndarray, - bpe: int, - total_size: int, - start_offset: int, -) -> bytes: - """Pack 2D blocks into a swizzled GPU buffer at start_offset with pseudo-noise background.""" - hb, wb, _ = raw_blocks.shape - noise = (np.arange(total_size, dtype=np.uint8) * 37 + 11) % 251 - buf = bytearray(noise.tobytes()) - for y in range(hb): - for x in range(wb): - idx = int(offsets[y, x]) - pos = start_offset + idx * bpe - buf[pos : pos + bpe] = bytes(raw_blocks[y, x]) - return bytes(buf) - - -class TestDescriptorFormatClassification(unittest.TestCase): - """Test texture descriptor format classification and CLI format validation.""" - - def test_bc_bpe_valid_formats(self): - self.assertEqual(tex_mode_probe.bc_bpe("BC1"), 8) - self.assertEqual(tex_mode_probe.bc_bpe("BC2"), 16) - self.assertEqual(tex_mode_probe.bc_bpe("BC3"), 16) - - def test_bc_bpe_dxgi_format_suffixes(self): - cases = [ - ("BC1_UNORM", 8), - ("BC1_UNORM_SRGB", 8), - ("BC1_TYPELESS", 8), - ("BC2_UNORM", 16), - ("BC2_UNORM_SRGB", 16), - ("BC2_TYPELESS", 16), - ("BC3_UNORM", 16), - ("BC3_UNORM_SRGB", 16), - ("BC3_TYPELESS", 16), - ] - for fmt_name, expected_bpe in cases: - with self.subTest(fmt_name=fmt_name): - self.assertEqual(tex_mode_probe.bc_bpe(fmt_name), expected_bpe) - - def test_bc_bpe_unsupported_bc_formats(self): - unsupported = [ - "BC4", "BC4_UNORM", "BC4_SNORM", - "BC5", "BC5_UNORM", "BC5_SNORM", - "BC6H", "BC6H_UF16", "BC6H_SF16", - "BC7", "BC7_UNORM", "BC7_UNORM_SRGB", - ] - for fmt_name in unsupported: - with self.subTest(fmt_name=fmt_name): - self.assertIsNone(tex_mode_probe.bc_bpe(fmt_name)) - - def test_bc_bpe_uncompressed_and_unknown_formats(self): - invalids = [ - "R8_UNORM", - "R8G8B8A8_UNORM", - "R16G16B16A16_FLOAT", - "UNKNOWN", - "", - "bc1", - "bc1_unorm", - "BC10_UNORM", - ] - for fmt_name in invalids: - with self.subTest(fmt_name=fmt_name): - self.assertIsNone(tex_mode_probe.bc_bpe(fmt_name)) - - def test_probe_refuses_formats_without_a_color_scorer(self): - for fmt in ["BC4", "BC5", "BC6H", "BC7"]: - with self.subTest(fmt=fmt): - with tempfile.TemporaryDirectory() as tmp_dir: - index = os.path.join(tmp_dir, "index.json") - with open(index, "w", encoding="utf-8") as f: - f.write("[]") - with mock.patch.object(tex_mode_probe, "load", return_value=({}, {})), \ - mock.patch.object(sys, "argv", ["tex_mode_probe.py", index, tmp_dir, "--fmt", fmt]), \ - mock.patch("sys.stderr", new_callable=io.StringIO) as mock_stderr: - with self.assertRaises(SystemExit) as exc: - tex_mode_probe.main() - self.assertEqual(exc.exception.code, 2) - self.assertIn(fmt, mock_stderr.getvalue()) - self.assertIn("no color scorer", mock_stderr.getvalue()) - - def test_format_prefix_does_not_select_an_unsupported_index_row(self): - with tempfile.TemporaryDirectory() as tmp_dir: - index = os.path.join(tmp_dir, "index.json") - rows = [{"fmt_name": "BC10_UNORM", "w": 256, "h": 256, "archive": "synthetic", "gpu": 16}] - with open(index, "w", encoding="utf-8") as f: - json.dump(rows, f) - with mock.patch.object(tex_mode_probe, "load", return_value=({}, {})), \ - mock.patch.object(sys, "argv", ["tex_mode_probe.py", index, tmp_dir, "--fmt", "BC1"]), \ - mock.patch("sys.stdout", new_callable=io.StringIO) as mock_stdout: - tex_mode_probe.main() - self.assertEqual(mock_stdout.getvalue(), "winners: []\nprobed 0 of 0 textures; 0 skipped\n") - - def test_descriptor_index_filtering(self): - descriptors = [ - {"fmt_name": "BC1_UNORM", "w": 256, "h": 256, "archive": "a", "gpu": 1, "flags": 0, "data_off": 0, "gpu_size": 4096}, - {"fmt_name": "BC1_UNORM", "w": 512, "h": 512, "archive": "a", "gpu": 2, "flags": 0, "data_off": 0, "gpu_size": 4096}, - {"fmt_name": "BC1_UNORM", "w": 255, "h": 256, "archive": "a", "gpu": 3, "flags": 0, "data_off": 0, "gpu_size": 4096}, - {"fmt_name": "BC1_UNORM", "w": 256, "h": 254, "archive": "a", "gpu": 4, "flags": 0, "data_off": 0, "gpu_size": 4096}, - {"fmt_name": "BC2_UNORM", "w": 256, "h": 256, "archive": "a", "gpu": 5, "flags": 0, "data_off": 0, "gpu_size": 4096}, - {"fmt_name": "BC4_UNORM", "w": 256, "h": 256, "archive": "a", "gpu": 6, "flags": 0, "data_off": 0, "gpu_size": 4096}, - {"fmt_name": "BC10_UNORM", "w": 256, "h": 256, "archive": "a", "gpu": 7, "flags": 0, "data_off": 0, "gpu_size": 4096}, - ] - with tempfile.TemporaryDirectory() as tmp_dir: - idx_file = os.path.join(tmp_dir, "index.json") - with open(idx_file, "w", encoding="utf-8") as f: - json.dump(descriptors, f) - - with open(idx_file, encoding="utf-8") as f: - all_texs = json.load(f) - - filtered_bc1 = [ - t for t in all_texs - if t["fmt_name"].startswith("BC1") - and tex_mode_probe.bc_bpe(t["fmt_name"]) is not None - and t["w"] >= 256 and t["h"] >= 256 - ] - self.assertEqual(len(filtered_bc1), 2) - self.assertEqual(filtered_bc1[0]["gpu"], 1) - self.assertEqual(filtered_bc1[1]["gpu"], 2) - - filtered_bc2 = [ - t for t in all_texs - if t["fmt_name"].startswith("BC2") - and tex_mode_probe.bc_bpe(t["fmt_name"]) is not None - and t["w"] >= 256 and t["h"] >= 256 - ] - self.assertEqual(len(filtered_bc2), 1) - self.assertEqual(filtered_bc2[0]["gpu"], 5) - - filtered_bc4 = [ - t for t in all_texs - if t["fmt_name"].startswith("BC4") - and tex_mode_probe.bc_bpe(t["fmt_name"]) is not None - and t["w"] >= 256 and t["h"] >= 256 - ] - self.assertEqual(len(filtered_bc4), 0) - - def test_descriptor_flags_mip_extraction(self): - cases = [ - (0x00000000, 0), - (0x00010001, 1), - (0x00040003, 4), - (0x000B0000, 11), - (0x00FF0000, 255), - (0x12050000, 5), - ] - for flags, expected_mips in cases: - with self.subTest(flags=hex(flags)): - extracted = (flags >> 16) & 0xFF - self.assertEqual(extracted, expected_mips) - - -class TestArgumentValidation(unittest.TestCase): - """Test CLI argument parsing and validator functions.""" - - def test_positive_int_valid_inputs(self): - self.assertEqual(tex_mode_probe.positive_int("1"), 1) - self.assertEqual(tex_mode_probe.positive_int("12"), 12) - self.assertEqual(tex_mode_probe.positive_int("500"), 500) - - def test_positive_int_rejects_zero_and_negative(self): - for bad in ["0", "-1", "-10"]: - with self.subTest(value=bad): - with self.assertRaises(argparse.ArgumentTypeError) as exc: - tex_mode_probe.positive_int(bad) - self.assertIn("must be at least 1", str(exc.exception)) - - def test_positive_int_rejects_non_integers(self): - for bad in ["abc", "", "1.5", "None"]: - with self.subTest(value=bad): - with self.assertRaises(argparse.ArgumentTypeError) as exc: - tex_mode_probe.positive_int(bad) - self.assertIn("not a whole number", str(exc.exception)) - - def test_probe_refuses_invalid_indexes_before_loading_tables(self): - for contents, diagnostic in ((None, "cannot read texture index"), ("[", "cannot read texture index"), - ("{}", "texture index must contain a list")): - with self.subTest(contents=contents), tempfile.TemporaryDirectory() as directory: - index = os.path.join(directory, "index.json") - if contents is not None: - with open(index, "w", encoding="utf-8", newline="\n") as f: - f.write(contents) - stderr = io.StringIO() - with mock.patch.object(tex_mode_probe, "load") as load, \ - mock.patch.object(sys, "argv", ["tex_mode_probe.py", index, directory]), \ - mock.patch.object(sys, "stderr", stderr), self.assertRaises(SystemExit) as exc: - tex_mode_probe.main() - load.assert_not_called() - self.assertEqual(exc.exception.code, 2) - self.assertIn(diagnostic, stderr.getvalue()) - self.assertIn(index, stderr.getvalue()) - - def test_probe_refuses_a_count_below_one_cli(self): - for val in ["0", "-1", "x"]: - with self.subTest(value=val): - with tempfile.TemporaryDirectory() as td: - index = os.path.join(td, "index.json") - with open(index, "w", encoding="utf-8") as f: - f.write("[]") - with mock.patch.object(tex_mode_probe, "load", side_effect=AssertionError("should not load addrlib")), \ - mock.patch.object(sys, "argv", ["tex_mode_probe.py", index, td, "--n", val]), \ - mock.patch("sys.stderr", new_callable=io.StringIO) as mock_stderr: - with self.assertRaises(SystemExit) as exc: - tex_mode_probe.main() - self.assertEqual(exc.exception.code, 2) - self.assertIn("--n", mock_stderr.getvalue()) - - -class TestGpuBlobAssembly(unittest.TestCase): - """Test GPU buffer loading with single file and chained multi-part files.""" - - def test_gpu_blob_single_file_fallback(self): - with tempfile.TemporaryDirectory() as td: - arch_dir = os.path.join(td, "archive_a") - os.makedirs(arch_dir, exist_ok=True) - gpu_id = 0x1000 - content = b"SingleGpuBlobData12345" - with open(os.path.join(arch_dir, f"{gpu_id:012x}.bin"), "wb") as f: - f.write(content) - - t = {"archive": "archive_a", "gpu": gpu_id, "gpu_size": len(content)} - blob = tex_mode_probe.gpu_blob(td, t) - self.assertEqual(blob, content) - - def test_gpu_blob_multi_file_gpu_chain(self): - with tempfile.TemporaryDirectory() as td: - arch_dir = os.path.join(td, "archive_b") - os.makedirs(arch_dir, exist_ok=True) - part1 = b"PartOne_" - part2 = b"PartTwo_" - part3 = b"PartThree" - off1, off2, off3 = 0x2000, 0x3000, 0x4000 - with open(os.path.join(arch_dir, f"{off1:012x}.bin"), "wb") as f: - f.write(part1) - with open(os.path.join(arch_dir, f"{off2:012x}.bin"), "wb") as f: - f.write(part2) - with open(os.path.join(arch_dir, f"{off3:012x}.bin"), "wb") as f: - f.write(part3) - - t = { - "archive": "archive_b", - "gpu": off1, - "gpu_size": len(part1) + len(part2) + len(part3), - "gpu_chain": [ - [off1, len(part1)], - [off2, len(part2)], - [off3, len(part3)], - ], - } - blob = tex_mode_probe.gpu_blob(td, t) - self.assertEqual(blob, part1 + part2 + part3) - - -class TestMipBytesAndAlignment(unittest.TestCase): - """Test mip byte size calculation and alignment rounding.""" - - def test_block_dimension_quantization(self): - cases = [ - (1, 1, 1, 1), - (2, 2, 1, 1), - (3, 3, 1, 1), - (4, 4, 1, 1), - (5, 4, 2, 1), - (4, 5, 1, 2), - (5, 5, 2, 2), - (8, 8, 2, 2), - (9, 8, 3, 2), - (256, 256, 64, 64), - (257, 257, 65, 65), - ] - for w, h, exp_bw, exp_bh in cases: - with self.subTest(w=w, h=h): - bw = max(1, (w + 3) // 4) - bh = max(1, (h + 3) // 4) - self.assertEqual(bw, exp_bw) - self.assertEqual(bh, exp_bh) - - def test_mip_bytes_alignment_rounding(self): - # 4x4, bpe=8 -> 1 block = 8 bytes - self.assertEqual(tex_mode_probe.mip_bytes(4, 4, 8, 1), 8) - self.assertEqual(tex_mode_probe.mip_bytes(4, 4, 8, 256), 256) - self.assertEqual(tex_mode_probe.mip_bytes(4, 4, 8, 4096), 4096) - self.assertEqual(tex_mode_probe.mip_bytes(4, 4, 8, 65536), 65536) - - # 256x256, bpe=8 -> 64*64*8 = 32768 bytes - self.assertEqual(tex_mode_probe.mip_bytes(256, 256, 8, 1), 32768) - self.assertEqual(tex_mode_probe.mip_bytes(256, 256, 8, 4096), 32768) - self.assertEqual(tex_mode_probe.mip_bytes(256, 256, 8, 65536), 65536) - - # 256x256, bpe=16 -> 64*64*16 = 65536 bytes - self.assertEqual(tex_mode_probe.mip_bytes(256, 256, 16, 4096), 65536) - self.assertEqual(tex_mode_probe.mip_bytes(256, 256, 16, 65536), 65536) - - def test_mip_bytes_non_power_of_two(self): - # 37x19, bpe=8: bw=10, bh=5, 50 blocks * 8 = 400 bytes - self.assertEqual(tex_mode_probe.mip_bytes(37, 19, 8, 1), 400) - self.assertEqual(tex_mode_probe.mip_bytes(37, 19, 8, 256), 512) - self.assertEqual(tex_mode_probe.mip_bytes(37, 19, 8, 4096), 4096) - - def test_mip_chain_layout_and_placement_offsets(self): - w, h, bpe, align = 256, 256, 8, 4096 - top = tex_mode_probe.mip_bytes(w, h, bpe, align) - self.assertEqual(top, 32768) - - # Single mip: chain == top - chain_1 = sum(tex_mode_probe.mip_bytes(max(1, w >> i), max(1, h >> i), bpe, align) for i in range(1)) - self.assertEqual(chain_1, top) - start_first_1 = 0x100 - start_last_1 = 0x100 + chain_1 - top - self.assertEqual(start_first_1, start_last_1) - - # 4 mips: - # mip 0: 256x256 -> 32768 - # mip 1: 128x128 -> 8192 - # mip 2: 64x64 -> 4096 - # mip 3: 32x32 -> 4096 - # chain = 32768 + 8192 + 4096 + 4096 = 49152 - chain_4 = sum(tex_mode_probe.mip_bytes(max(1, w >> i), max(1, h >> i), bpe, align) for i in range(4)) - self.assertEqual(chain_4, 49152) - start_first_4 = 0 - start_last_4 = 0 + chain_4 - top - self.assertEqual(start_last_4, 16384) - self.assertGreater(start_last_4, start_first_4) - - -@unittest.skipUnless(HAVE_NUMPY, "numpy required for tex_mode_probe tiling tests") -class TestOffsetsForTilingModes(unittest.TestCase): - """Test macro/micro-tile geometry and swizzled offset generation.""" - - def test_tile_geometry_4k_and_64k(self): - cases = [ - # bb, bpe, expected_elems, expected_bw, expected_bh - (12, 8, 512, 32, 16), - (12, 16, 256, 16, 16), - (16, 8, 8192, 128, 64), - (16, 16, 4096, 64, 64), - ] - for bb, bpe, exp_elems, exp_bw, exp_bh in cases: - with self.subTest(bb=bb, bpe=bpe): - elems = (1 << bb) // bpe - lb = elems.bit_length() - 1 - bw = 1 << ((lb + 1) // 2) - bh = elems // bw - self.assertEqual(elems, exp_elems) - self.assertEqual(bw, exp_bw) - self.assertEqual(bh, exp_bh) - self.assertEqual(bw * bh, exp_elems) - - def test_offsets_single_tile_bijection_4k_bc1(self): - o = tex_mode_probe.offsets_for(SYNTHETIC_EQ_4K_BC1, 12, 8, 32, 16) - self.assertEqual(o.shape, (16, 32)) - self.assertEqual(o.min(), 0) - self.assertEqual(o.max(), 511) - self.assertEqual(len(np.unique(o)), 512) - - def test_offsets_single_tile_bijection_64k_bc1(self): - o = tex_mode_probe.offsets_for(SYNTHETIC_EQ_64K_BC1, 16, 8, 128, 64) - self.assertEqual(o.shape, (64, 128)) - self.assertEqual(o.min(), 0) - self.assertEqual(o.max(), 8191) - self.assertEqual(len(np.unique(o)), 8192) - - def test_offsets_single_tile_bijection_4k_bc2_3(self): - o = tex_mode_probe.offsets_for(SYNTHETIC_EQ_4K_BC2_3, 12, 16, 16, 16) - self.assertEqual(o.shape, (16, 16)) - self.assertEqual(o.min(), 0) - self.assertEqual(o.max(), 255) - self.assertEqual(len(np.unique(o)), 256) - - def test_offsets_single_tile_bijection_64k_bc2_3(self): - o = tex_mode_probe.offsets_for(SYNTHETIC_EQ_64K_BC2_3, 16, 16, 64, 64) - self.assertEqual(o.shape, (64, 64)) - self.assertEqual(o.min(), 0) - self.assertEqual(o.max(), 4095) - self.assertEqual(len(np.unique(o)), 4096) - - def test_offsets_multi_tile_grid(self): - # 64x64 blocks = 2x4 tiles of 32x16 - o = tex_mode_probe.offsets_for(SYNTHETIC_EQ_4K_BC1, 12, 8, 64, 64) - self.assertEqual(o.shape, (64, 64)) - self.assertEqual(o.min(), 0) - self.assertEqual(o.max(), 4095) - self.assertEqual(len(np.unique(o)), 4096) - - # Check macro-tile partition spacing: - tile_0_0 = o[0:16, 0:32] - tile_1_0 = o[0:16, 32:64] - tile_0_1 = o[16:32, 0:32] - self.assertEqual(set(tile_0_0.flat) & set(tile_1_0.flat), set()) - self.assertEqual(set(tile_0_0.flat) & set(tile_0_1.flat), set()) - self.assertEqual(tile_1_0.min(), 512) - self.assertEqual(tile_0_1.min(), 1024) - - def test_offsets_non_tile_multiple(self): - # wb=35, hb=19 with tile 32x16 -> 2x2 macro tiles - o = tex_mode_probe.offsets_for(SYNTHETIC_EQ_4K_BC1, 12, 8, 35, 19) - self.assertEqual(o.shape, (19, 35)) - self.assertEqual(len(np.unique(o)), 19 * 35) - self.assertLess(o.max(), 4 * 512) - - def test_offsets_zero_equation(self): - eq_zero = [(0, 0)] * 12 - o = tex_mode_probe.offsets_for(eq_zero, 12, 8, 64, 32) - self.assertEqual(o.shape, (32, 64)) - # Within tile (0, 0), all values evaluate to 0 - self.assertTrue(np.all(o[0:16, 0:32] == 0)) - # Within tile (1, 0), macro offset is 1 * 512 - self.assertTrue(np.all(o[0:16, 32:64] == 512)) - # Within tile (0, 1), macro offset is (1 * 2 + 0) * 512 = 1024 - self.assertTrue(np.all(o[16:32, 0:32] == 1024)) - - -class TestCandidatePatternFiltering(unittest.TestCase): - """Test candidate extraction and pattern filtering from addrlib tables.""" - - def test_candidate_filtering_and_deduplication(self): - tab = { - "GFX10_SW_64K_S_PATINFO": [(0, 0, 0, 0, 0, "1 pipes 8 bpe")], - "GFX10_SW_4K_D_PATINFO": [(0, 0, 0, 0, 0, "1 pipes 8 bpe")], - "GFX10_SW_64K_R_X_1xaa_PATINFO": [(0, 0, 0, 0, 0, "1 pipes 8 bpe")], - "GFX10_SW_64K_Z_PATINFO": [(0, 0, 0, 0, 0, "1 pipes 8 bpe")], - "GFX10_SW_256K_S_PATINFO": [(0, 0, 0, 0, 0, "1 pipes 8 bpe")], - "GFX10_SW_4K_S_DUPE_PATINFO": [(0, 0, 0, 0, 0, "1 pipes 8 bpe")], - } - - def mock_equation(nib, e, bb): - if "DUPE" in e[5] or bb == 12: - return [(0, 0)] * bb - return [(1, 0)] * bb - - cands = {} - for tname, ents in tab.items(): - for size, bb in (("_64K_", 16), ("_4K_", 12)): - if size in tname and ("_S" in tname or "_D" in tname or "_R_X_1xaa" in tname): - for e in ents: - if " 8 bpe" in e[5]: - eq = mock_equation(None, e, bb) - cands.setdefault( - (bb, tuple(eq)), - f"{tname.replace('GFX10_SW_', '').replace('_PATINFO', '')} {e[5][:22]}", - ) - - # 64K_Z is excluded (_Z not in _S, _D, _R_X_1xaa) - # 256K_S is excluded (neither _64K_ nor _4K_) - # Both 4K entries generate [(0, 0)]*12 so they deduplicate to a single entry in cands - keys = list(cands.keys()) - self.assertEqual(len(keys), 2) - bbs = {k[0] for k in keys} - self.assertEqual(bbs, {12, 16}) - - def test_candidate_bpe_matching(self): - tab = { - "GFX10_SW_4K_S_PATINFO": [ - (0, 0, 0, 0, 0, "1 pipes 8 bpe"), - (0, 0, 0, 0, 0, "1 pipes 16 bpe"), - (0, 0, 0, 0, 0, "1 pipes 4 bpe"), - ] - } - bpe_8_matches = [e for e in tab["GFX10_SW_4K_S_PATINFO"] if f" {tex_mode_probe.bc_bpe('BC1')} bpe" in e[5]] - bpe_16_matches = [e for e in tab["GFX10_SW_4K_S_PATINFO"] if f" {tex_mode_probe.bc_bpe('BC3')} bpe" in e[5]] - self.assertEqual(len(bpe_8_matches), 1) - self.assertEqual(len(bpe_16_matches), 1) - self.assertIn("8 bpe", bpe_8_matches[0][5]) - self.assertIn("16 bpe", bpe_16_matches[0][5]) - - -@unittest.skipUnless(HAVE_NUMPY, "numpy required for tex_mode_probe end-to-end probing") -class TestTextureModeProbing(unittest.TestCase): - """Test texture mode probing logic and winner ranking with synthetic chunks.""" - - def setUp(self): - self.wb, self.hb = 64, 64 - self.w, self.h = 256, 256 - self.bpe = 8 - self.mips = 2 - self.flags = (self.mips << 16) | 1 - - self.raw_blocks = make_synthetic_bc1_blocks(self.wb, self.hb) - self.o_correct = tex_mode_probe.offsets_for(SYNTHETIC_EQ_4K_BC1, 12, self.bpe, self.wb, self.hb) - - self.top = tex_mode_probe.mip_bytes(self.w, self.h, self.bpe, 4096) - self.chain = sum( - tex_mode_probe.mip_bytes(max(1, self.w >> i), max(1, self.h >> i), self.bpe, 4096) - for i in range(self.mips) - ) - - self.nib = { - "NIBBLE01": [[0] * 8, [0] * 8], - "NIBBLE2": [[0] * 4, [0] * 4], - "NIBBLE3": [[0] * 4, [0] * 4], - "NIBBLE4": [[0] * 4, [0] * 4], - } - self.entry_correct = (0, 0, 0, 0, 0, "synthetic 8 bpe") - self.entry_incorrect = (1, 1, 1, 1, 1, "synthetic 8 bpe") - self.tab = { - "GFX10_SW_4K_S_PATINFO": [self.entry_correct], - "GFX10_SW_4K_D_PATINFO": [self.entry_incorrect], - } - - def _mock_equation(self, nib, entry, bb): - if entry == self.entry_correct: - return SYNTHETIC_EQ_4K_BC1 - # Alternate permutation with swapped coordinates: - return [ - (0, 0), (0, 0), (0, 0), - (0, 1), (1, 0), - (0, 2), (2, 0), - (0, 4), (4, 0), - (0, 8), (8, 0), - (0, 16), - ][:bb] - - def test_probe_winner_selection_top_mip_first(self): - # Pack data at 'first' placement (start = 0) - gpu_bytes = make_swizzled_gpu_buffer( - self.raw_blocks, self.o_correct, self.bpe, self.chain, start_offset=0 - ) - - with tempfile.TemporaryDirectory() as td: - arch_dir = os.path.join(td, "arch0") - os.makedirs(arch_dir, exist_ok=True) - gpu_file = os.path.join(arch_dir, f"{0x1000:012x}.bin") - with open(gpu_file, "wb") as f: - f.write(gpu_bytes) - - index_file = os.path.join(td, "textures_index.json") - with open(index_file, "w", encoding="utf-8") as f: - json.dump([{ - "archive": "arch0", - "gpu": 0x1000, - "gpu_size": len(gpu_bytes), - "fmt_name": "BC1_UNORM", - "w": self.w, - "h": self.h, - "flags": self.flags, - "data_off": 0, - }], f) - - with mock.patch.object(tex_mode_probe, "load", return_value=(self.nib, self.tab)), \ - mock.patch.object(tex_mode_probe, "equation", side_effect=self._mock_equation), \ - mock.patch.object(sys, "argv", ["tex_mode_probe.py", index_file, td, "--fmt", "BC1"]), \ - mock.patch("sys.stdout", new_callable=io.StringIO) as mock_stdout: - tex_mode_probe.main() - - output = mock_stdout.getvalue() - self.assertIn("best", output) - self.assertIn("4K_S", output) - self.assertIn("[first]", output) - self.assertIn("winners: [(('4K_S', 'first'), 1)]", output) - self.assertIn("probed 1 of 1 textures; 0 skipped", output) - - def test_probe_winner_selection_top_mip_last(self): - # Pack data at 'last' placement (start = chain - top = 8192) - start_last = self.chain - self.top - gpu_bytes = make_swizzled_gpu_buffer( - self.raw_blocks, self.o_correct, self.bpe, self.chain, start_offset=start_last - ) - - with tempfile.TemporaryDirectory() as td: - arch_dir = os.path.join(td, "arch0") - os.makedirs(arch_dir, exist_ok=True) - gpu_file = os.path.join(arch_dir, f"{0x2000:012x}.bin") - with open(gpu_file, "wb") as f: - f.write(gpu_bytes) - - index_file = os.path.join(td, "textures_index.json") - with open(index_file, "w", encoding="utf-8") as f: - json.dump([{ - "archive": "arch0", - "gpu": 0x2000, - "gpu_size": len(gpu_bytes), - "fmt_name": "BC1_UNORM", - "w": self.w, - "h": self.h, - "flags": self.flags, - "data_off": 0, - }], f) - - with mock.patch.object(tex_mode_probe, "load", return_value=(self.nib, self.tab)), \ - mock.patch.object(tex_mode_probe, "equation", side_effect=self._mock_equation), \ - mock.patch.object(sys, "argv", ["tex_mode_probe.py", index_file, td, "--fmt", "BC1"]), \ - mock.patch("sys.stdout", new_callable=io.StringIO) as mock_stdout: - tex_mode_probe.main() - - output = mock_stdout.getvalue() - self.assertIn("best", output) - self.assertIn("4K_S", output) - self.assertIn("[last]", output) - self.assertIn("winners: [(('4K_S', 'last'), 1)]", output) - self.assertIn("probed 1 of 1 textures; 0 skipped", output) - - def test_probe_top_mip_after_non_aligned_tile_grid(self) -> None: - # The 132x136 lower mip is 33x34 BC1 blocks, requiring 2x3 tiles of 32x16 blocks. - # The 264x272 top mip is 66x68 blocks, requiring 3x5 tiles. - width, height = 264, 272 - top_blocks_w, top_blocks_h = 66, 68 - block = np.array([0, 248, 0, 248, 0, 0, 0, 0], dtype=np.uint8) - top = np.tile(block, (top_blocks_h, top_blocks_w, 1)) - offsets = tex_mode_probe.offsets_for(SYNTHETIC_EQ_4K_BC1, 12, 8, top_blocks_w, top_blocks_h) - gpu = make_swizzled_gpu_buffer(top, offsets, 8, (6 + 15) * 4096, start_offset=6 * 4096) - - with tempfile.TemporaryDirectory() as directory: - archive = os.path.join(directory, "synthetic") - os.mkdir(archive) - with open(os.path.join(archive, f"{0x1000:012x}.bin"), "wb") as f: - f.write(gpu) - index = os.path.join(directory, "index.json") - with open(index, "w", encoding="utf-8", newline="\n") as f: - json.dump([{"archive": "synthetic", "gpu": 0x1000, "gpu_size": len(gpu), - "fmt_name": "BC1_UNORM", "w": width, "h": height, - "flags": self.flags, "data_off": 0}], f) - table = {"GFX10_SW_4K_S_PATINFO": [self.entry_correct]} - with mock.patch.object(tex_mode_probe, "load", return_value=(self.nib, table)), \ - mock.patch.object(tex_mode_probe, "equation", return_value=SYNTHETIC_EQ_4K_BC1), \ - mock.patch.object(sys, "argv", ["tex_mode_probe.py", index, directory]), \ - mock.patch("sys.stdout", new_callable=io.StringIO) as stdout: - tex_mode_probe.main() - - self.assertRegex(stdout.getvalue(), r"best 0\.0000 4K_S .*? \[last\]") - self.assertIn("winners: [(('4K_S', 'last'), 1)]", stdout.getvalue()) - - def test_probe_skips_truncated_gpu_segment(self): - # Provide a GPU segment file that is too short for any candidate - truncated_bytes = b"\x00" * 128 - - with tempfile.TemporaryDirectory() as td: - arch_dir = os.path.join(td, "arch0") - os.makedirs(arch_dir, exist_ok=True) - gpu_file = os.path.join(arch_dir, f"{0x3000:012x}.bin") - with open(gpu_file, "wb") as f: - f.write(truncated_bytes) - - index_file = os.path.join(td, "textures_index.json") - with open(index_file, "w", encoding="utf-8") as f: - json.dump([{ - "archive": "arch0", - "gpu": 0x3000, - "gpu_size": len(truncated_bytes), - "fmt_name": "BC1_UNORM", - "w": self.w, - "h": self.h, - "flags": self.flags, - "data_off": 0, - }], f) - - with mock.patch.object(tex_mode_probe, "load", return_value=(self.nib, self.tab)), \ - mock.patch.object(tex_mode_probe, "equation", side_effect=self._mock_equation), \ - mock.patch.object(sys, "argv", ["tex_mode_probe.py", index_file, td, "--fmt", "BC1"]), \ - mock.patch("sys.stdout", new_callable=io.StringIO) as mock_stdout: - tex_mode_probe.main() - - output = mock_stdout.getvalue() - self.assertIn("skipped: no candidate fits in the GPU blob", output) - self.assertIn("winners: []", output) - self.assertIn("probed 0 of 1 textures; 1 skipped", output) - - def test_probe_multi_part_gpu_chain(self): - # Split GPU buffer into 2 chained parts: - start_last = self.chain - self.top - gpu_bytes = make_swizzled_gpu_buffer( - self.raw_blocks, self.o_correct, self.bpe, self.chain, start_offset=start_last - ) - half = len(gpu_bytes) // 2 - part1 = gpu_bytes[:half] - part2 = gpu_bytes[half:] - off1, off2 = 0x6001, 0x6002 - - with tempfile.TemporaryDirectory() as td: - arch_dir = os.path.join(td, "arch_chain") - os.makedirs(arch_dir, exist_ok=True) - with open(os.path.join(arch_dir, f"{off1:012x}.bin"), "wb") as f: - f.write(part1) - with open(os.path.join(arch_dir, f"{off2:012x}.bin"), "wb") as f: - f.write(part2) - - index_file = os.path.join(td, "textures_index.json") - with open(index_file, "w", encoding="utf-8") as f: - json.dump([{ - "archive": "arch_chain", - "gpu": off1, - "gpu_size": len(gpu_bytes), - "gpu_chain": [[off1, len(part1)], [off2, len(part2)]], - "fmt_name": "BC1_UNORM", - "w": self.w, - "h": self.h, - "flags": self.flags, - "data_off": 0, - }], f) - - with mock.patch.object(tex_mode_probe, "load", return_value=(self.nib, self.tab)), \ - mock.patch.object(tex_mode_probe, "equation", side_effect=self._mock_equation), \ - mock.patch.object(sys, "argv", ["tex_mode_probe.py", index_file, td, "--fmt", "BC1"]), \ - mock.patch("sys.stdout", new_callable=io.StringIO) as mock_stdout: - tex_mode_probe.main() - - output = mock_stdout.getvalue() - self.assertIn("best", output) - self.assertIn("4K_S", output) - self.assertIn("[last]", output) - self.assertIn("winners: [(('4K_S', 'last'), 1)]", output) - self.assertIn("probed 1 of 1 textures; 0 skipped", output) - - def test_probe_linear_score_reporting(self): - # Verify linear score reporting when segment is full vs truncated - gpu_bytes = make_swizzled_gpu_buffer( - self.raw_blocks, self.o_correct, self.bpe, self.chain, start_offset=0 - ) - - with tempfile.TemporaryDirectory() as td: - arch_dir = os.path.join(td, "arch0") - os.makedirs(arch_dir, exist_ok=True) - gpu_file = os.path.join(arch_dir, f"{0x4000:012x}.bin") - with open(gpu_file, "wb") as f: - f.write(gpu_bytes) - - index_file = os.path.join(td, "textures_index.json") - with open(index_file, "w", encoding="utf-8") as f: - json.dump([{ - "archive": "arch0", - "gpu": 0x4000, - "gpu_size": len(gpu_bytes), - "fmt_name": "BC1_UNORM", - "w": self.w, - "h": self.h, - "flags": self.flags, - "data_off": 0, - }], f) - - with mock.patch.object(tex_mode_probe, "load", return_value=(self.nib, self.tab)), \ - mock.patch.object(tex_mode_probe, "equation", side_effect=self._mock_equation), \ - mock.patch.object(sys, "argv", ["tex_mode_probe.py", index_file, td, "--fmt", "BC1"]), \ - mock.patch("sys.stdout", new_callable=io.StringIO) as mock_stdout: - tex_mode_probe.main() - - output = mock_stdout.getvalue() - self.assertIn("linear", output) - self.assertNotIn("linear -1.0000", output) - - def test_probe_empty_index_outputs_empty_winners(self): - with tempfile.TemporaryDirectory() as td: - index_file = os.path.join(td, "textures_index.json") - with open(index_file, "w", encoding="utf-8") as f: - json.dump([], f) - - with mock.patch.object(tex_mode_probe, "load", return_value=(self.nib, self.tab)), \ - mock.patch.object(sys, "argv", ["tex_mode_probe.py", index_file, td, "--fmt", "BC1"]), \ - mock.patch("sys.stdout", new_callable=io.StringIO) as mock_stdout: - tex_mode_probe.main() - - output = mock_stdout.getvalue() - self.assertEqual(output.strip(), "winners: []\nprobed 0 of 0 textures; 0 skipped") - - def test_probe_max_texture_limit_arg(self): - gpu_bytes = make_swizzled_gpu_buffer( - self.raw_blocks, self.o_correct, self.bpe, self.chain, start_offset=0 - ) - - with tempfile.TemporaryDirectory() as td: - arch_dir = os.path.join(td, "arch0") - os.makedirs(arch_dir, exist_ok=True) - for gpu_id in (0x5001, 0x5002, 0x5003): - with open(os.path.join(arch_dir, f"{gpu_id:012x}.bin"), "wb") as f: - f.write(gpu_bytes) - - index_file = os.path.join(td, "textures_index.json") - with open(index_file, "w", encoding="utf-8") as f: - json.dump([ - {"archive": "arch0", "gpu": 0x5001, "gpu_size": len(gpu_bytes), "fmt_name": "BC1_UNORM", "w": self.w, "h": self.h, "flags": self.flags, "data_off": 0}, - {"archive": "arch0", "gpu": 0x5002, "gpu_size": len(gpu_bytes), "fmt_name": "BC1_UNORM", "w": self.w, "h": self.h, "flags": self.flags, "data_off": 0}, - {"archive": "arch0", "gpu": 0x5003, "gpu_size": len(gpu_bytes), "fmt_name": "BC1_UNORM", "w": self.w, "h": self.h, "flags": self.flags, "data_off": 0}, - ], f) - - with mock.patch.object(tex_mode_probe, "load", return_value=(self.nib, self.tab)), \ - mock.patch.object(tex_mode_probe, "equation", side_effect=self._mock_equation), \ - mock.patch.object(sys, "argv", ["tex_mode_probe.py", index_file, td, "--fmt", "BC1", "--n", "1"]), \ - mock.patch("sys.stdout", new_callable=io.StringIO) as mock_stdout: - tex_mode_probe.main() - - output = mock_stdout.getvalue() - lines = [line for line in output.strip().splitlines() if "256x256" in line] - self.assertEqual(len(lines), 1) - self.assertIn("probed 1 of 1 textures; 0 skipped", output) - - -# Maintain compatibility with pytest parameterised runners: -if pytest is not None: - @pytest.mark.parametrize("fmt", ["BC4", "BC5", "BC6H", "BC7"]) - def test_probe_refuses_formats_without_a_color_scorer_pytest(fmt, monkeypatch, capsys, tmp_path): - index = tmp_path / "index.json" - index.write_text("[]", encoding="utf-8") - monkeypatch.setattr(tex_mode_probe, "load", lambda: ({}, {})) - monkeypatch.setattr(sys, "argv", ["tex_mode_probe.py", str(index), str(tmp_path), "--fmt", fmt]) - with pytest.raises(SystemExit) as exc: - tex_mode_probe.main() - assert exc.value.code == 2 - assert fmt in capsys.readouterr().err - - @pytest.mark.parametrize("value", ["0", "-1", "x"]) - def test_probe_refuses_a_count_below_one_pytest(value, monkeypatch, capsys, tmp_path): - index = tmp_path / "index.json" - index.write_text("[]", encoding="utf-8") - monkeypatch.setattr(tex_mode_probe, "load", lambda: pytest.fail("the probe must stop before loading addrlib")) - monkeypatch.setattr(sys, "argv", ["tex_mode_probe.py", str(index), str(tmp_path), "--n", value]) - with pytest.raises(SystemExit) as exc: - tex_mode_probe.main() - assert exc.value.code == 2 - assert "--n" in capsys.readouterr().err - - @pytest.mark.parametrize( - "data_size, candidate_count, parts, mips", - [(32760, 0, 1, 2), (32768, 1, 1, 2), (40960, 2, 1, 2), (32768, 1, 2, 2), - (40960, 2, 3, 2), (32768, 1, 1, 1)], - ) - def test_probe_reports_available_candidates_pytest( - data_size: int, candidate_count: int, parts: int, mips: int, - monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str], tmp_path: Path, - ) -> None: - eq = [(0, 0)] * 3 + [(1 << i, 0) for i in range(5)] + [(0, 1 << i) for i in range(4)] - entry = (0, 0, 0, 0, 0, "synthetic 8 bpe") - monkeypatch.setattr(tex_mode_probe, "load", lambda: ({}, {"GFX10_SW_4K_S_PATINFO": [entry]})) - monkeypatch.setattr(tex_mode_probe, "equation", lambda nib, e, bb: eq) - carve = tmp_path / "synthetic" - carve.mkdir() - cuts = [data_size * i // parts for i in range(parts + 1)] - chain = [[16 + 0x100000 * i, cuts[i + 1] - cuts[i]] for i in range(parts)] - for off, size in chain: - (carve / f"{off:012x}.bin").write_bytes(bytes(size)) - row = { - "fmt_name": "BC1_UNORM", - "w": 256, - "h": 256, - "archive": "synthetic", - "gpu": 16, - "flags": mips << 16, - "data_off": 0, - "gpu_size": data_size, - } - if parts > 1: - row["gpu_chain"] = chain - index = tmp_path / "index.json" - index.write_text(json.dumps([row]), encoding="utf-8") - monkeypatch.setattr(sys, "argv", ["tex_mode_probe.py", str(index), str(tmp_path)]) - - tex_mode_probe.main() - - out = capsys.readouterr().out - if candidate_count == 0: - assert out == ( - "256x256 BC1_UNORM gpu=0x10 skipped: no candidate fits in the GPU blob\n" - "winners: []\nprobed 0 of 1 textures; 1 skipped\n" - ) - else: - second = "n/a" if candidate_count == 1 else "0.0000 4K_S synthetic 8 bpe [last]" - assert out == ( - f"256x256 BC1_UNORM mips={mips} gpu={data_size} best 0.0000 4K_S synthetic 8 bpe [first]" - f" 2nd {second} linear 0.0000\n" - "winners: [(('4K_S', 'first'), 1)]\n" - "probed 1 of 1 textures; 0 skipped\n" - ) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/test_texel_offsets.py b/tests/test_texel_offsets.py deleted file mode 100644 index 12e23a135..000000000 --- a/tests/test_texel_offsets.py +++ /dev/null @@ -1,268 +0,0 @@ -"""Texel offsets of image_sample*_o / image_gather4*_o in tools/rdna2spirv.py: the shape of the SPIR-V. - -These tests feed the translator hand-written ``.s`` listings, so they need neither llvm-mc nor spirv-tools. - -docs/design.md, "Texel offsets": the first address dword packs signed 6-bit offsets, x = [5:0], y = [13:8], -z = [21:16], which become the Offset image operand. Sampled values are checked on a GPU by -runtime/test/shaders/ps_texoff.asm. That test cannot see the sign extension on a driver that itself keeps only the -low six bits of an Offset: on an AMD Radeon RX 6800 (driver 26.11.2) a translator that read the fields unsigned -(60 for -4) sampled the same texels. So the extraction is pinned down here: OpBitFieldSExtract, bit 8k, 6 bits wide. -""" -import re - -import pytest - -from listing import translate_listing - -# v10 = the offset dword, v11.. = the coordinates (and LOD); v3 is what listing.EPILOGUE exports. -PROLOGUE = "\n".join(f"v_mov_b32 v{r}, 0" for r in (3, 10, 11, 12, 13, 14)) -DESC = "s[8:15], s[16:19]" -FORMS = [ # (instruction, SPIR-V op that takes the Offset, offset components) - (f"image_sample_lz_o v[4:5], v[10:12], {DESC} dmask:0x3 dim:SQ_RSRC_IMG_2D", "OpImageSampleExplicitLod", 2), - (f"image_sample_l_o v[4:5], v[10:13], {DESC} dmask:0x3 dim:SQ_RSRC_IMG_2D", "OpImageSampleExplicitLod", 2), - (f"image_sample_o v[4:5], v[10:12], {DESC} dmask:0x3 dim:SQ_RSRC_IMG_2D", "OpImageSampleImplicitLod", 2), - (f"image_sample_lz_o v[4:5], v[10:13], {DESC} dmask:0x3 dim:SQ_RSRC_IMG_3D", "OpImageSampleExplicitLod", 3), - (f"image_sample_o v[4:5], v[10:11], {DESC} dmask:0x3 dim:SQ_RSRC_IMG_2D a16", "OpImageSampleImplicitLod", 2), - (f"image_sample_lz_o v[4:5], v[10:11], {DESC} dmask:0x3 dim:SQ_RSRC_IMG_2D a16", "OpImageSampleExplicitLod", 2), - (f"image_sample_l_o v[4:5], v[10:12], {DESC} dmask:0x3 dim:SQ_RSRC_IMG_2D a16", "OpImageSampleExplicitLod", 2), - (f"image_sample_b_o v[4:5], v[10:12], {DESC} dmask:0x3 dim:SQ_RSRC_IMG_2D a16", "OpImageSampleImplicitLod", 2), - (f"image_sample_c_lz_o v4, v[10:12], {DESC} dmask:0x1 dim:SQ_RSRC_IMG_2D a16", "OpImageSampleDrefExplicitLod", 2), - (f"image_sample_c_o v4, v[10:13], {DESC} dmask:0x1 dim:SQ_RSRC_IMG_2D", "OpImageSampleDrefImplicitLod", 2), - (f"image_sample_c_b_o v4, v[10:14], {DESC} dmask:0x1 dim:SQ_RSRC_IMG_2D", "OpImageSampleDrefImplicitLod", 2), - (f"image_sample_c_o v4, v[10:12], {DESC} dmask:0x1 dim:SQ_RSRC_IMG_2D a16", "OpImageSampleDrefImplicitLod", 2), - (f"image_sample_cl_o v[4:5], v[10:13], {DESC} dmask:0x3 dim:SQ_RSRC_IMG_2D", "OpImageSampleImplicitLod", 2), - (f"image_sample_c_b_cl_o v4, v[10:15], {DESC} dmask:0x1 dim:SQ_RSRC_IMG_2D", "OpImageSampleDrefImplicitLod", 2), - (f"image_gather4_lz_o v[4:7], v[10:12], {DESC} dmask:0x1 dim:SQ_RSRC_IMG_2D", "OpImageGather", 2), -] - - -def offset_fields(spv, op): - """[(first bit, width, signed)] of the Offset operand shared by every numeric path for ``op``.""" - consts = {m[1]: int(m[2]) for m in re.finditer(r"(%\w+) = OpConstant %uint (\d+)", spv)} - lines = [ln for ln in spv.splitlines() if f"= {op} " in ln] - assert lines and all("Offset" in ln and "ConstOffset" not in ln for ln in lines), lines - # Typed gathers have one path per numeric class. Each path must apply the same offset. - def offset_operand(line): - toks = line.split() - mask = next(i for i, t in enumerate(toks) if "Offset" in t.split("|")) - return toks[mask + 1 + toks[mask].split("|").index("Offset")] # operands follow the mask in mask order - offsets = {offset_operand(line) for line in lines} - assert len(offsets) == 1, lines - vec = offsets.pop() - parts = re.search(rf"{re.escape(vec)} = OpCompositeConstruct %v\dint (.+)", spv)[1].split() - fields = [] - for part in parts: - bits = re.search(rf"{re.escape(part)} = OpBitcast %int (%\w+)", spv)[1] - ext = re.search(rf"{re.escape(bits)} = OpBitField([SU])Extract %uint %\w+ (%\w+) (%\w+)", spv) - fields.append((consts[ext[2]], consts[ext[3]], ext[1] == "S")) - return fields - - -@pytest.mark.parametrize("asm,op,n", FORMS, ids=[f[0].split()[0] + "_" + f[0].rsplit("_", 1)[1] for f in FORMS]) -def test_offset_is_signed_six_bit_fields_at_byte_steps(asm, op, n, tmp_path): - spv = translate_listing(tmp_path, PROLOGUE + "\n" + asm) - assert offset_fields(spv, op) == [(8 * k, 6, True) for k in range(n)] - - -def test_sample_without_o_has_no_offset(tmp_path): - spv = translate_listing(tmp_path, PROLOGUE + f"\nimage_sample_lz v[4:5], v[11:12], {DESC} dmask:0x3 dim:SQ_RSRC_IMG_2D") - assert "Offset" not in "".join(ln for ln in spv.splitlines(True) if "OpImageSample" in ln) - - -# ---- --texel-offset-fallback: the offset folded into the coordinate, no VK_KHR_maintenance8 ---- - -import shutil # noqa: E402 -import subprocess # noqa: E402 - -import rdna2spirv # noqa: E402 (put on sys.path by listing) - -SAMPLES = [f for f in FORMS if f[1] != "OpImageGather"] - - -@pytest.fixture -def fallback(monkeypatch): - monkeypatch.setattr(rdna2spirv, "TEXEL_OFFSET_FALLBACK", True) - - -def _shift_fields(spv): - """Fields of the offset vector the fallback converts to float (OpConvertSToF of the OpCompositeConstruct).""" - consts = {m[1]: int(m[2]) for m in re.finditer(r"(%\w+) = OpConstant %uint (\d+)", spv)} - for m in re.finditer(r"%\w+ = OpConvertSToF %(?:v\d)?float (%\w+)", spv): - src = m[1] - c = re.search(rf"{re.escape(src)} = OpCompositeConstruct %v\dint (.+)", spv) - parts = c[1].split() if c else [src] - fields = [] - for part in parts: - b = re.search(rf"{re.escape(part)} = OpBitcast %int (%\w+)", spv) - ext = b and re.search(rf"{re.escape(b[1])} = OpBitField([SU])Extract %uint %\w+ (%\w+) (%\w+)", spv) - if not ext: - break - fields.append((consts[ext[2]], consts[ext[3]], ext[1] == "S")) - else: - return fields - raise AssertionError("no offset vector converted to float") - - -@pytest.mark.parametrize("asm,op,n", SAMPLES, ids=[f[0].split()[0] + "_" + f[0].rsplit("_", 1)[1] for f in SAMPLES]) -def test_fallback_folds_the_offset(asm, op, n, tmp_path, fallback): - spv = translate_listing(tmp_path, PROLOGUE + "\n" + asm) - samples = [ln for ln in spv.splitlines() if "OpImageSample" in ln] - assert samples and not any(" Offset " in ln for ln in samples), samples - assert _shift_fields(spv) == [(8 * k, 6, True) for k in range(n)] - assert "OpImageQuerySizeLod" in spv and "OpImageQueryLevels" in spv - assert re.search(r"= OpFDiv %(?:v\d)?float %\w+ %\w+", spv) and "OpCapability ImageQuery" in spv - implicit = asm.startswith(("image_sample_o ", "image_sample_b_o ", "image_sample_c_o ", "image_sample_c_b_o ", - "image_sample_cl_o ", "image_sample_c_b_cl_o ")) - assert ("OpImageQueryLod" in spv) == implicit - if implicit: - # Grad with the derivatives of the unshifted coordinate: same LOD as the sample without the offset. - assert "OpImageSampleImplicitLod" not in spv and "OpImageSampleDrefImplicitLod" not in spv - if asm.startswith("image_sample_c_"): - assert re.search(r"OpImageSampleDrefExplicitLod %float %\w+ %\w+ %\w+ Grad(\|MinLod)? %\w+ %\w+( %\w+)?$", samples[0]) - else: - assert re.search(r"OpImageSampleExplicitLod %v4float %\w+ %\w+ Grad(\|MinLod)? %\w+ %\w+( %\w+)?$", samples[0]) - assert ("MinLod" in samples[0]) == ("_cl_o " in asm) - assert "OpDPdx" in spv and "OpDPdy" in spv - assert ("Exp2" in spv) == asm.startswith(("image_sample_b_o ", "image_sample_c_b_o ", "image_sample_c_b_cl_o ")) - assert "OpCapability ImageGatherExtended" not in spv - - -def test_fallback_keeps_gather_offsets(tmp_path, fallback): - gather, op, n = FORMS[-1] - spv = translate_listing(tmp_path, PROLOGUE + "\n" + gather) - assert offset_fields(spv, op) == [(8 * k, 6, True) for k in range(n)] - assert "OpCapability ImageGatherExtended" in spv - - -@pytest.mark.skipif(not (shutil.which("spirv-as") and shutil.which("spirv-val")), reason="needs spirv-as and spirv-val") -@pytest.mark.parametrize("asm,op,n", SAMPLES, ids=[f[0].split()[0] + "_" + f[0].rsplit("_", 1)[1] for f in SAMPLES]) -def test_fallback_needs_no_maintenance8(asm, op, n, tmp_path, fallback): - """spirv-val without --allow-offset-texture-operand: the module needs no VK_KHR_maintenance8.""" - spv = translate_listing(tmp_path, PROLOGUE + "\n" + asm) - src, out = tmp_path / "m.spvasm", tmp_path / "m.spv" - src.write_text(spv, encoding="utf-8") - for cmd in (["spirv-as", "--target-env", "vulkan1.2", str(src), "-o", str(out)], - ["spirv-val", "--target-env", "vulkan1.2", str(out)]): - r = subprocess.run(cmd, capture_output=True, text=True) - assert r.returncode == 0, r.stdout + r.stderr - - -# ---- the folded level follows the S#'s MIP_FILTER (word 2 [27:26]; SHADER-699) ---- - -MIP_NONE, MIP_POINT, MIP_LINEAR = 0, 1, 2 -SAMPLE_L_O = FORMS[1][0] # image_sample_l_o: v13 is the LOD, s[16:19] the S#, so s18 is word 2 - - -def _defs(spv): - return {m[1]: m[2].split() for m in re.finditer(r"^\s*(%\w+) = (.+)$", spv, re.M)} - - -def _folded_level(spv, lod, word2=None, levels=4): - """Evaluate the level operand of the fallback's OpImageQuerySizeLod for a given LOD (and run-time S# word 2). - - A small evaluator over the integer and float ops the level chain uses, with every float result rounded to - binary32 as the module computes it. The LOD enters as the value the level rounding reads (the operand of - Floor, or of an OpFAdd with 0.5); the run-time word 2 as the operand of the OpBitFieldUExtract at bit 26.""" - import math - import struct - d = _defs(spv) - size_q = [v for v in d.values() if v[0] == "OpImageQuerySizeLod"] - assert len(size_q) == 1, size_q - uconst = {k: int(v[2]) for k, v in d.items() if v[0] == "OpConstant" and v[1] in ("%uint", "%int")} - fconst = {k: float(v[2]) for k, v in d.items() if v[:2] == ["OpConstant", "%float"]} - fconst.update({k: struct.unpack("= ev(a[1]) - if op[0] == "OpISub": - return ev(a[0]) - ev(a[1]) - if op[0] == "OpConvertFToS": - return int(ev(a[0])) - if op[0] == "OpIEqual": - return ev(a[0]) == ev(a[1]) - if op[0] == "OpSelect": - return ev(a[1]) if ev(a[0]) else ev(a[2]) - if op[0] == "OpBitFieldUExtract": - return ev(a[0]) >> ev(a[1]) & ((1 << ev(a[2])) - 1) - if op[0] == "OpExtInst": - fn, args = op[3], [ev(y) for y in op[4:]] - if fn == "Floor": - return float(math.floor(args[0])) - if fn == "Ceil": - return float(math.ceil(args[0])) - if fn == "SClamp": - return min(max(args[0], args[1]), args[2]) - raise AssertionError(f"unexpected op in the level chain: {x} = {' '.join(op)}") - return ev(size_q[0][-1]) - - -def _f32(bits): - import struct - return struct.unpack("> shift) & 0x3F), n) - return float(b * p.W + x) - - -class RowsTest(unittest.TestCase): - def test_sext6(self): - self.assertEqual([p.sext6(v) for v in (0, 0x1F, 0x20, 0x3F, 0x40, 0x7F)], [0, 31, -32, -1, 0, -1]) - - def test_rows_with_a_negative_field_tell_signed_from_unsigned(self): - for name, dim, start, off in p.ROWS: - field = (off >> (8 if dim == "2d" else 16)) & 0x3F - if field & 0x20 and field != 0x3F: - with self.subTest(name): - self.assertNotEqual(p.expected(dim, start, off), unsigned_reading(dim, start, off)) - - def test_both_axes_are_covered(self): - self.assertEqual({d for _n, d, _s, _o in p.ROWS}, {"2d", "3d"}) - self.assertEqual(len({n for n, *_ in p.ROWS}), len(p.ROWS)) - - def test_expected_values(self): - self.assertEqual(p.expected("2d", (5, 40), 0x20 << 8), 8 * 64 + 5) # 40 - 32 - self.assertEqual(p.expected("2d", (5, 10), 0x20 << 8), 0 * 64 + 5) # clamps at row 0 - self.assertEqual(p.expected("2d", (5, 40), 0xC0 << 8), 40 * 64 + 5) # bits 14-15 ignored - self.assertEqual(p.expected("3d", (20, 40), (0x3C << 16) | (0x3F << 8) | 0x3E), 36 * 64 + 18) - - def test_kernels_build_for_rdna2_and_rdna3(self): - for arch in ("gfx1036", "gfx1150"): - for dim in ("2d", "3d"): - rows = [r for r in p.ROWS if r[1] == dim] - lines = p.kernel(arch, dim, rows) - with self.subTest(arch=arch, dim=dim): - self.assertEqual(sum("image_sample_lz_o" in ln for ln in lines), len(rows)) - self.assertIn(f"dim:SQ_RSRC_IMG_{dim.upper()}", "\n".join(lines)) - self.assertEqual(lines[-1].startswith(" .long"), True) - - def test_3d_descriptor_type_and_depth(self): - t = p.words("gfx1036", "3d") - self.assertEqual(t[3] >> 28, p.SQ_RSRC_IMG_3D) - self.assertEqual(t[4], p.D3D - 1) - self.assertEqual(p.sampler_words()[0] & 0x1FF, 2 | 2 << 3 | 2 << 6) - - -class OracleLifecycleTest(unittest.TestCase): - def _run_hw(self, fake_oracle): - import contextlib - import io - from unittest import mock - import runner - - buf = io.StringIO() - with ( - mock.patch.object(runner, "open_oracle", return_value=fake_oracle) as open_mock, - mock.patch.object(runner, "Oracle", side_effect=AssertionError("Oracle() called directly")), - contextlib.redirect_stdout(buf), - ): - rc = p.main(["--oracle", "hw"]) - open_mock.assert_called_once_with() - return rc, buf.getvalue() - - def test_hw_uses_open_oracle_and_closes_on_match(self): - import struct - - class FakeOracle: - device = "fake-gpu" - arch = "gfx1036" - closed = False - - def run(self, kernels): - text = "\n".join(kernels[0].lines) - dim = "2d" if "SQ_RSRC_IMG_2D" in text else "3d" - rows = [r for r in p.ROWS if r[1] == dim] - return [[struct.unpack("= 2 and isinstance(node.args[1], ast.Constant): - mode = node.args[1].value - for k in node.keywords: - if k.arg == "mode" and isinstance(k.value, ast.Constant): - mode = k.value.value - if isinstance(mode, str) and "b" not in mode: - found.append(node.lineno) - elif name in ("read_text", "write_text"): - found.append(node.lineno) - return found - - -class TextEncoding(unittest.TestCase): - def test_detector_finds_the_unpinned_forms(self): - src = ( - "open('a')\n" # 1 - "open('a', 'w', newline='\\n')\n" # 2 - "open('a', mode='a')\n" # 3 - "os.fdopen(3, 'w', newline='\\n')\n" # 4 - "p.write_text('x')\n" # 5 - "p.read_text()\n" # 6 - "open('a', encoding='utf-8')\n" # pinned - "open('a', 'w', encoding='utf-8', newline='\\n')\n" # pinned - "open('a', 'rb')\n" # binary - "open('a', 'wb')\n" # binary - "os.open('a', 0)\n" # not a text open - "webbrowser.open('u')\n" # not a file - "p.write_text('x', encoding='utf-8')\n" # pinned - ) - self.assertEqual(unpinned_encodings(src), [1, 2, 3, 4, 5, 6]) - - def test_every_text_file_call_pins_its_encoding(self): - bad = [] - count = 0 - for path in python_files(): - count += 1 - with open(path, encoding="utf-8") as f: - for line in unpinned_encodings(f.read()): - bad.append(f"{os.path.relpath(path, ROOT)}:{line}") - self.assertGreater(count, 50, "the scan found almost no Python files; is the layout different?") - self.assertEqual(bad, [], "text files opened without encoding= (locale code page): " + ", ".join(bad)) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/test_text_tables.py b/tests/test_text_tables.py deleted file mode 100644 index ba633f0d9..000000000 --- a/tests/test_text_tables.py +++ /dev/null @@ -1,576 +0,0 @@ -"""Tests for tools/text_tables.py, built from synthetic resources and conversation data (no game data). - - python -I tests/test_text_tables.py -""" -import contextlib -import csv -import errno -import importlib.util -import io -import json -import os -import struct -import tempfile -import unittest -from unittest.mock import patch - -ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) - - -def load_module(): - path = os.path.join(ROOT, "tools", "text_tables.py") - spec = importlib.util.spec_from_file_location("text_tables_under_test", path) - module = importlib.util.module_from_spec(spec) - spec.loader.exec_module(module) - return module - - -T = load_module() - - -def ptr(off): - return struct.pack(" text. ``pad`` adds bytes before the tables so they can cross a 64 KiB boundary. - """ - labels = list(strings) - blob = bytearray() - blob_offsets = [] - for label in labels: - blob_offsets.append(len(blob)) - blob += strings[label].encode("utf-8") + b"\0" - head = bytearray(0x10) + b"0DRP" + bytes(0x0C) - desc_at = len(head) - desc_len = 8 + 4 + 4 + 8 + 4 + 4 + 8 + 4 + 4 + 8 - index_at = desc_at + desc_len + pad - hash_at = index_at + 16 * len(labels) - blob_at = hash_at + 16 * len(labels) - desc = (ptr(index_at) + struct.pack(".bin per inflated stream.""" - files, off = [], 0x1000 - for data in streams: - write(os.path.join(tmp, f"{off:012x}.bin"), data) - files.append({"off": off, "stored": len(data), "size": len(data), "pre": "", "head": data[:16].hex()}) - off += 0x20000 - with open(os.path.join(tmp, "index.json"), "w", encoding="utf-8") as fh: - json.dump({"files": files, "summary": {}}, fh) - - def test_resource_across_64k_streams(self): - res = make_resource(EN, pad=T.BLOCK) # tables start past the first 64 KiB - streams = [res[:T.BLOCK], res[T.BLOCK:], make_resource(DE), CONV] - with tempfile.TemporaryDirectory() as tmp: - self.carve(tmp, streams) - scan = T.Scan() - for label, off, data in T.blobs(tmp): - scan.add(label, off, data) - self.assertEqual(sorted(lang for _s, _o, lang, _t in scan.tables), ["de", "en"]) - self.assertEqual(scan.tables[0][1], 0x1000) - - def test_resource_across_a_128k_first_stream(self): - # A resource's first stream can be any whole number of 64 KiB blocks (docs/page_directory.md): 41 data.rpf - # resources start with a 128 or 192 KiB stream whose descriptors end in the next stream. - res = make_resource(EN, pad=2 * T.BLOCK) # tables start past the first 128 KiB - streams = [res[:2 * T.BLOCK], res[2 * T.BLOCK:], make_resource(DE), CONV] - with tempfile.TemporaryDirectory() as tmp: - self.carve(tmp, streams) - scan = T.Scan() - for label, off, data in T.blobs(tmp): - scan.add(label, off, data) - self.assertEqual(sorted(lang for _s, _o, lang, _t in scan.tables), ["de", "en"]) - - def test_whole_block_streams_continue_and_others_end_the_chain(self): - for first, joined in ((T.BLOCK, True), (2 * T.BLOCK, True), (3 * T.BLOCK, True), - (T.BLOCK + 16, False), (T.BLOCK - 16, False)): - with self.subTest(first=first): - rows = [{"off": 0, "size": first}, {"off": 1, "size": 100}] - data = {0: bytes(first), 1: b"b" * 100} - offsets = [o for o, _d in T._chains(rows, lambda r: data[r["off"]])] - self.assertEqual(offsets, [0] if joined else [0, 1]) - - def test_short_stream_ends_the_chain(self): - rows = [{"off": 0, "size": 100}, {"off": 1, "size": 50}] - data = {0: b"a" * 100, 1: b"b" * 50} - self.assertEqual([o for o, _d in T._chains(rows, lambda r: data[r["off"]])], [0, 1]) - - def test_new_resource_ends_the_chain(self): - rows = [{"off": 0, "size": T.BLOCK}, {"off": 1, "size": 10}] - data = {0: bytes(T.BLOCK), 1: bytes(0x10) + b"0DRP"} - self.assertEqual([o for o, _d in T._chains(rows, lambda r: data[r["off"]])], [0, 1]) - - -class TestDialogue(unittest.TestCase): - def test_waves_and_text(self): - scan = T.Scan() - scan.add("a", 0, make_resource(EN)) - scan.add("b", 0, make_resource(DE)) - scan.add("c", 0, CONV) - rows = list(scan.dialogue_rows()) - self.assertEqual([(r["wave"], r["label"], r["speaker"]) for r in rows], - [("zz_rootau_abcd_01", "ZZ_LINE_A_1", "A"), ("zz_rootau_abcd_02", "ZZ_LINE_B_2", "B")]) - self.assertEqual(rows[0]["text_en"], EN["ZZ_LINE_A_1"]) - self.assertEqual(rows[1]["text_de"], DE["ZZ_LINE_B_2"]) - self.assertEqual(scan.languages(), ["en", "de"]) - - def test_lowercase_in_label(self): - scan = T.Scan() - scan.add("c", 0, b"ZZ_KEYAU_ABCD\x00ZZ_TIMELEFT_90s_1\x00") - self.assertEqual(scan.pairs["ZZ_KEYAU_ABCD"], ["ZZ_TIMELEFT_90s_1"]) - - -class TestCli(unittest.TestCase): - def test_unreadable_subdirectory_preserves_previous_tables_report(self): - with tempfile.TemporaryDirectory() as tmp: - source = os.path.join(tmp, "source") - blocked = os.path.join(source, "blocked") - os.makedirs(blocked) - write(os.path.join(source, "visible.bin"), make_resource(EN)) - write(os.path.join(blocked, "hidden.bin"), make_resource(DE)) - report = os.path.join(tmp, "tables.csv") - previous = b"previous complete report\n" - write(report, previous) - scandir = os.scandir - - def scan(path): - if path == blocked: - raise PermissionError(errno.EACCES, "Permission denied", path) - return scandir(path) - - with (patch.object(os, "scandir", side_effect=scan), - contextlib.redirect_stderr(io.StringIO()) as error, - contextlib.redirect_stdout(io.StringIO()) as output): - self.assertEqual(T.main([source, "--tables", report]), 2) - - self.assertEqual(output.getvalue(), "") - self.assertEqual(len(error.getvalue().splitlines()), 1) - self.assertIn("cannot read input", error.getvalue()) - self.assertIn(repr(blocked), error.getvalue()) - with open(report, "rb") as fh: - self.assertEqual(fh.read(), previous) - - def test_csv_exports_explicitly_empty_strings(self) -> None: - strings = {"ZZ_SYNTHETIC_BLANK": "", "ZZ_SYNTHETIC_LINE": "This is the text you know"} - with tempfile.TemporaryDirectory() as tmp: - source = write(os.path.join(tmp, "strings.bin"), make_resource(strings)) - tables_csv = os.path.join(tmp, "tables.csv") - strings_csv = os.path.join(tmp, "strings.csv") - with contextlib.redirect_stdout(io.StringIO()): - self.assertEqual(T.main([source, "--tables", tables_csv, "--strings", strings_csv]), 0) - with open(tables_csv, encoding="utf-8", newline="") as f: - self.assertEqual([row["strings"] for row in csv.DictReader(f)], ["2"]) - with open(strings_csv, encoding="utf-8", newline="") as f: - self.assertEqual({row["hash"]: row["text"] for row in csv.DictReader(f)}, - {f"{T.joaat(label):08x}": text for label, text in strings.items()}) - - def test_end_to_end(self): - with tempfile.TemporaryDirectory() as tmp: - src = os.path.join(tmp, "src") - os.mkdir(src) - write(os.path.join(src, "en.bin"), make_resource(EN)) - write(os.path.join(src, "de.bin"), make_resource(DE)) - write(os.path.join(src, "conv.pso"), CONV) - labels = os.path.join(tmp, "labels.json") - with open(labels, "w", encoding="utf-8") as fh: - json.dump({f"{T.joaat('zz_menu_title'):08x}": "zz_menu_title"}, fh) - outs = {k: os.path.join(tmp, f"{k}.csv") for k in ("dialogue", "tables", "strings")} - with contextlib.redirect_stdout(io.StringIO()) as log: - self.assertEqual(T.main([src, "--labels", labels, "--dialogue", outs["dialogue"], - "--tables", outs["tables"], "--strings", outs["strings"]]), 0) - self.assertIn("2 string tables", log.getvalue()) - self.assertIn("1 dialogue keys, 2 lines", log.getvalue()) - with open(outs["tables"], encoding="utf-8", newline="") as fh: - tables = list(csv.DictReader(fh)) - self.assertEqual({(t["lang"], t["strings"], t["resolved"], t["group"]) for t in tables}, - {("en", "3", "3", "ZZ_LINE"), ("de", "3", "3", "ZZ_LINE")}) # 2 of 3 share ZZ_LINE - with open(outs["strings"], encoding="utf-8", newline="") as fh: - strings = list(csv.DictReader(fh)) - self.assertIn(("ZZ_MENU_TITLE", "das Menü"), {(s["label"], s["text"]) for s in strings}) - self.assertFalse([f for f in os.listdir(tmp) if f.startswith(".text_tables-")], - "staging files must not be left behind") - - def test_failed_later_write_leaves_earlier_reports_intact(self): - with tempfile.TemporaryDirectory() as tmp: - src = os.path.join(tmp, "src") - os.mkdir(src) - write(os.path.join(src, "conv.pso"), CONV) - dialogue = os.path.join(tmp, "dialogue.csv") - old = "OLD GOOD REPORT\n" - with open(dialogue, "w", encoding="utf-8") as fh: - fh.write(old) - tables = os.path.join(tmp, "tables.csv") - os.mkdir(tables) # a later output that cannot be written - with contextlib.redirect_stderr(io.StringIO()) as err: - self.assertEqual(T.main([src, "--dialogue", dialogue, "--tables", tables]), 2) - self.assertIn("cannot write", err.getvalue()) - with open(dialogue, encoding="utf-8") as fh: - self.assertEqual(fh.read(), old) - self.assertFalse([f for f in os.listdir(tmp) if f.startswith(".text_tables-")]) - - @unittest.skipUnless(os.name == "nt", "Windows denies os.replace on a file held open by a reader") - def test_reader_holding_a_later_report_keeps_all_reports(self): - with tempfile.TemporaryDirectory() as tmp: - src = os.path.join(tmp, "src") - os.mkdir(src) - write(os.path.join(src, "conv.pso"), CONV) - dialogue = os.path.join(tmp, "dialogue.csv") - tables = os.path.join(tmp, "tables.csv") - old_dialogue, old_tables = "OLD DIALOGUE\n", "OLD TABLES\n" - for path, text in ((dialogue, old_dialogue), (tables, old_tables)): - with open(path, "w", encoding="utf-8") as fh: - fh.write(text) - with open(tables, "rb"): # a reader keeps the second output open - with contextlib.redirect_stderr(io.StringIO()) as err: - self.assertEqual(T.main([src, "--dialogue", dialogue, "--tables", tables]), 2) - self.assertIn("cannot write", err.getvalue()) - with open(dialogue, encoding="utf-8") as fh: - self.assertEqual(fh.read(), old_dialogue) - with open(tables, encoding="utf-8") as fh: - self.assertEqual(fh.read(), old_tables) - self.assertFalse([f for f in os.listdir(tmp) if f.startswith(".text_tables-")], - "staging and backup files must not be left behind") - - def test_report_cannot_replace_the_carve_index(self): - with tempfile.TemporaryDirectory() as tmp: - source = os.path.join(tmp, "carve") - os.mkdir(source) - index = write(os.path.join(source, "index.json"), b'{"files": []}') - with contextlib.redirect_stderr(io.StringIO()) as err, self.assertRaises(SystemExit) as code: - T.main([source, "--tables", index]) - self.assertEqual(code.exception.code, 2) - self.assertIn("must not overwrite an input", err.getvalue()) - with open(index, "rb") as f: - self.assertEqual(f.read(), b'{"files": []}') - - def test_two_outputs_naming_one_file_are_refused(self): - with tempfile.TemporaryDirectory() as tmp: - src = os.path.join(tmp, "src") - os.mkdir(src) - write(os.path.join(src, "conv.pso"), CONV) - out = os.path.join(tmp, "same.csv") - with contextlib.redirect_stderr(io.StringIO()) as err: - with self.assertRaises(SystemExit) as cm: - T.main([src, "--dialogue", out, "--tables", out]) - self.assertEqual(cm.exception.code, 2) - self.assertIn("distinct", err.getvalue()) - self.assertFalse(os.path.exists(out), "no report may be written before the check") - - def test_missing_input(self): - # "/nonexistent" is a drive-root path on Windows (C:\nonexistent), which really exists on some hosts. - # Use a path inside a fresh temp directory so the input is guaranteed to be missing on every platform. - with tempfile.TemporaryDirectory() as tmp: - missing = os.path.join(tmp, "missing-input") - self.assertFalse(os.path.exists(missing)) - with contextlib.redirect_stderr(io.StringIO()): - self.assertEqual(T.main([missing]), 2) - - def test_missing_parent_and_hardlinked_outputs_rejected_upfront(self): - with tempfile.TemporaryDirectory() as tmp: - src = write(os.path.join(tmp, "en.bin"), make_resource(EN)) - missing_parent = os.path.join(tmp, "no_such_dir", "out.csv") - err = io.StringIO() - with contextlib.redirect_stderr(err), self.assertRaises(SystemExit) as cm: - T.main([src, "--tables", missing_parent]) - self.assertEqual(cm.exception.code, 2) - self.assertIn("parent directory does not exist", err.getvalue()) - - first = write(os.path.join(tmp, "first.csv"), b"old\n") - alias = os.path.join(tmp, "alias.csv") - try: - os.link(first, alias) - except OSError: - self.skipTest("hard links unavailable") - err = io.StringIO() - with contextlib.redirect_stderr(err), self.assertRaises(SystemExit) as cm: - T.main([src, "--dialogue", first, "--tables", alias]) - self.assertEqual(cm.exception.code, 2) - self.assertIn("distinct", err.getvalue()) - - def test_invalid_json_labels_is_clean_error_not_traceback(self): - with tempfile.TemporaryDirectory() as tmp: - src = write(os.path.join(tmp, "en.bin"), make_resource(EN)) - bad_labels = os.path.join(tmp, "bad.json") - with open(bad_labels, "w", encoding="utf-8") as fh: - fh.write("{not valid json") - err = io.StringIO() - with contextlib.redirect_stderr(err): - rc = T.main([src, "--labels", bad_labels]) - self.assertEqual(rc, 2) - self.assertIn("cannot read input", err.getvalue()) - - def test_wrong_shape_labels_json_is_clean_error(self): - with tempfile.TemporaryDirectory() as tmp: - src = write(os.path.join(tmp, "en.bin"), make_resource(EN)) - for text in ("[1, 2]", '"x"', "null"): - with self.subTest(text): - labels = os.path.join(tmp, "labels.json") - with open(labels, "w", encoding="utf-8", newline="\n") as fh: - fh.write(text) - err = io.StringIO() - with contextlib.redirect_stderr(err): - rc = T.main([src, "--labels", labels]) - self.assertEqual(rc, 2) - self.assertIn("cannot read input", err.getvalue()) - - def test_carve_folder_with_wrong_shape_index_is_clean_error(self): - for name, text in (("list", "[]"), ("nofiles", "{}"), ("badrow", '{"files": [1]}')): - with self.subTest(name), tempfile.TemporaryDirectory() as tmp: - with open(os.path.join(tmp, "index.json"), "w", encoding="utf-8", newline="\n") as fh: - fh.write(text) - err = io.StringIO() - with contextlib.redirect_stderr(err): - rc = T.main([tmp]) - self.assertEqual(rc, 2) - self.assertIn("cannot read input", err.getvalue()) - - -UNDECIDED = {"ZZ_CODE_1": "qqq zzz", "ZZ_CODE_2": "xkcd 42"} # no script, letter or word decides: xx - - -def rpf9_header(data_off=0x800): - return b"9FPR" + struct.pack(" bool: - """True for a constant mode string that can write text ("w", "a+", "xt", "r+", ...).""" - return (isinstance(mode, str) and bool(mode) and set(mode) <= MODE_CHARS and "b" not in mode - and (any(c in mode for c in "wax") or ("r" in mode and "+" in mode))) - - -def call_mode(node: ast.Call, index: int): - mode = None - if len(node.args) > index and isinstance(node.args[index], ast.Constant): - mode = node.args[index].value - for k in node.keywords: - if k.arg == "mode" and isinstance(k.value, ast.Constant): - mode = k.value.value - return mode - - -def mode_index(func): - """Position of the mode argument for the file-opening calls this test knows, or None for any other call.""" - name = getattr(func, "attr", getattr(func, "id", None)) - if name in TEMPFILES: - return 0 - if name == "fdopen": - return 1 - if name != "open": - return None - if isinstance(func, ast.Name): - return 1 # the builtin open - owner = func.value.id if isinstance(func.value, ast.Name) else None - if owner in NOT_TEXT_OPENS: - return None - return 1 if owner in MODULE_OPENS else 0 # anything else is taken as Path.open(mode) - - -def unpinned_text_writes(source: str): - """Line numbers of text-mode writes in `source` that pass no `newline=`.""" - found = [] - for node in ast.walk(ast.parse(source)): - if not isinstance(node, ast.Call) or any(k.arg == "newline" for k in node.keywords): - continue - name = getattr(node.func, "attr", getattr(node.func, "id", None)) - if name == "write_text": - found.append(node.lineno) - continue - index = mode_index(node.func) - if index is not None and text_write_mode(call_mode(node, index)): - found.append(node.lineno) - return found - - -class TextWriteLineEndings(unittest.TestCase): - def test_detector_finds_the_unpinned_forms(self): - src = ( - "open('a', 'w')\n" # 1 - "open('a', 'w', encoding='utf-8')\n" # 2 - "open('a', mode='a')\n" # 3 - "os.fdopen(3, 'w', encoding='utf-8')\n" # 4 - "p.write_text('x', encoding='utf-8')\n" # 5 - "open('a', 'w', newline='\\n')\n" # pinned - "open('a', 'w', newline='')\n" # pinned - "open('a', 'wb')\n" # binary - "open('a')\n" # read - "open('a', 'r', encoding='utf-8')\n" # read - "p.write_text('x', newline='\\n')\n" # pinned - "pathlib.Path('a').open('w', encoding='utf-8')\n" # 12 - "p.open(mode='a')\n" # 13 - "io.open('out.txt', 'w')\n" # 14 - "tempfile.NamedTemporaryFile('w', delete=False)\n" # 15 - "NamedTemporaryFile(mode='w+', encoding='utf-8')\n" # 16 - "tempfile.SpooledTemporaryFile(mode='wt')\n" # 17 - "gzip.open('out.txt.gz', 'wt')\n" # 18 - "tempfile.NamedTemporaryFile(mode='w', newline='\\n')\n" # pinned - "tempfile.NamedTemporaryFile()\n" # binary (the default w+b) - "tempfile.NamedTemporaryFile('w+b')\n" # binary - "p.open()\n" # read - "p.open('rb')\n" # read - "zf.open('words.txt')\n" # a member name, not a mode - "codecs.open('a', 'w', 'utf-8')\n" # no newline translation in codecs - "tarfile.open('a', 'w:gz')\n" # an archive mode, binary - "os.open('a', os.O_WRONLY)\n" # flags, not a mode string - ) - self.assertEqual(unpinned_text_writes(src), [1, 2, 3, 4, 5, 12, 13, 14, 15, 16, 17, 18]) - - def test_detector_finds_unpinned_text_update_modes(self): - src = ( - "open('a', 'r+')\n" - "p.open(mode='rt+')\n" - "os.fdopen(3, 'r+t')\n" - "open('a', 'r+', newline='\\n')\n" - "open('a', 'rb+')\n" - "open('a', 'r')\n" - ) - self.assertEqual(unpinned_text_writes(src), [1, 2, 3]) - - def test_every_text_write_pins_its_newline(self): - bad = [] - count = 0 - for path in python_files(): - count += 1 - with open(path, encoding="utf-8") as f: - for line in unpinned_text_writes(f.read()): - bad.append(f"{os.path.relpath(path, ROOT)}:{line}") - self.assertGreater(count, 50, "the scan found almost no Python files; is the layout different?") - self.assertEqual(bad, [], "text writes without newline= (CRLF on Windows, LF elsewhere): " + ", ".join(bad)) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/test_texture_readback_sync.py b/tests/test_texture_readback_sync.py deleted file mode 100644 index 318514e02..000000000 --- a/tests/test_texture_readback_sync.py +++ /dev/null @@ -1,71 +0,0 @@ -"""Exercise the texture synchronization CMake check with a synthetic cube harness.""" - -import os -from pathlib import Path -import shutil -import subprocess -import sys -import tempfile -import unittest - -CHECK = Path(__file__).resolve().parents[1] / "runtime/test/check_texture_readback_sync.cmake" -CMAKE = shutil.which("cmake") -FRAME_BYTES = 64 * 64 * 16 -HARNESS = """\ -import os -from pathlib import Path -import sys - -assert sys.argv[1] == "cube" -assert os.environ["VK_INSTANCE_LAYERS"] == "VK_LAYER_KHRONOS_validation" -mode = os.environ["LEONIDA_SYNTHETIC_READBACK_MODE"] -output = Path(sys.argv[2]) -if mode in ("full", "hazard"): - output.write_bytes(bytes(64 * 64 * 16)) -elif mode == "short": - output.write_bytes(b"short") -if mode == "hazard": - print("SYNC-HAZARD", file=sys.stderr) -print('Insert instance layer "VK_LAYER_KHRONOS_validation"', file=sys.stderr) -print("vk_texture_test cube: PASSED (4096 pixels)") -""" - - -@unittest.skipUnless(CMAKE, "CMake is required to exercise the texture synchronization check") -class TextureReadbackSyncTests(unittest.TestCase): - def test_requires_fresh_complete_readback(self): - cases = ( - ("fresh", "full", False, 0), - ("valid rerun", "full", True, 0), - ("missing", "none", False, 1), - ("stale full-size file", "none", True, 1), - ("short", "short", False, 1), - ("sync hazard", "hazard", False, 1), - ) - for name, mode, preseeded, expected in cases: - with self.subTest(name=name), tempfile.TemporaryDirectory() as tmp: - root = Path(tmp) - shader_dir = root / "shaders" - shader_dir.mkdir() - output = shader_dir / "cube readback.raw" - if preseeded: - output.write_bytes(b"x" * FRAME_BYTES) - harness = root / "harness.py" - harness.write_text(HARNESS, encoding="utf-8", newline="\n") - - result = subprocess.run( - [CMAKE, f"-DRUNNER={sys.executable}", f"-DTOOL={harness}", - f"-DSPIRV={shader_dir.name}", f"-DOUTPUT={output.name}", "-P", str(CHECK)], - cwd=root, env=dict(os.environ, LEONIDA_SYNTHETIC_READBACK_MODE=mode), - capture_output=True, encoding="utf-8", errors="replace", - timeout=10, check=False, - ) - self.assertEqual(result.returncode, expected, result.stdout + result.stderr) - if expected == 0: - self.assertEqual(output.read_bytes(), bytes(FRAME_BYTES)) - if mode == "hazard": - self.assertIn("SYNC-HAZARD", result.stderr) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/test_tile_probe.py b/tests/test_tile_probe.py deleted file mode 100644 index 63af7251d..000000000 --- a/tests/test_tile_probe.py +++ /dev/null @@ -1,191 +0,0 @@ -"""Input checks for tools/tile_probe.py, on a synthetic blob (no game data). - - python -I tests/test_tile_probe.py - -The probe needs numpy, so those tests skip without it; the checks that run before it are also tested with numpy -blocked. -""" -import importlib.util -import os -import subprocess -import sys -import tempfile -import unittest - -ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) -TOOL = os.path.join(ROOT, "tools", "tile_probe.py") -HAVE_NUMPY = importlib.util.find_spec("numpy") is not None -# the tool is documented as `python -I`, which does not see a --user install of Pillow -HAVE_PIL_ISOLATED = subprocess.run([sys.executable, "-I", "-c", "import PIL"], - capture_output=True, check=False).returncode == 0 - - -@unittest.skipUnless(HAVE_NUMPY, "tile_probe.py needs numpy") -class TileProbeInputTest(unittest.TestCase): - def setUp(self): - self.tmp = tempfile.TemporaryDirectory() - self.blob = os.path.join(self.tmp.name, "blob.bin") - with open(self.blob, "wb") as f: - f.write(bytes(range(256)) * 64) # 16 KiB: smaller blobs give no candidate width - - def tearDown(self): - self.tmp.cleanup() - - def run_tool(self, *args): - return subprocess.run([sys.executable, "-I", TOOL, *args], capture_output=True, text=True, timeout=120) - - def test_missing_file_is_a_message_not_a_traceback(self): - p = self.run_tool(os.path.join(self.tmp.name, "missing.bin")) - self.assertEqual(p.returncode, 2, p.stderr) - self.assertIn("missing.bin", p.stderr) - self.assertNotIn("Traceback", p.stderr) - - def test_offset_outside_the_file_is_an_error(self): - # Before: -5 quietly probed the last five bytes, the file size and more printed nothing, and both exited 0. - for offset in ("-5", "16384", "99999"): - with self.subTest(offset=offset): - p = self.run_tool(self.blob, "--offset", offset) - self.assertEqual(p.returncode, 1, p.stderr) - self.assertIn("outside", p.stderr) - self.assertEqual(p.stdout, "") - - def test_empty_file_is_an_error(self): - empty = os.path.join(self.tmp.name, "empty.bin") - open(empty, "wb").close() - p = self.run_tool(empty) - self.assertEqual(p.returncode, 1, p.stderr) - self.assertIn("0 bytes", p.stderr) - - def test_a_sample_with_no_candidate_layout_is_an_error(self): - # Before: an 8-byte or 4 KiB blob printed nothing, wrote no preview and exited 0. - tiny = os.path.join(self.tmp.name, "tiny.bin") - with open(tiny, "wb") as f: - f.write(bytes(4096)) - preview = os.path.join(self.tmp.name, "preview.png") - for extra in ((), ("--out", preview)): - with self.subTest(extra=extra): - p = self.run_tool(tiny, *extra) - self.assertEqual(p.returncode, 1, p.stderr) - self.assertIn("no layout fits", p.stderr) - self.assertIn("tiny.bin", p.stderr) - self.assertNotIn("Traceback", p.stderr) - self.assertEqual(p.stdout, "") - self.assertFalse(os.path.exists(preview), "a run with no layout writes no preview") - - def test_out_cannot_overwrite_the_input(self): - # Before: --out naming the blob saved the preview over it after the probe, destroying the sample. - with open(self.blob, "rb") as f: - before = f.read() - p = self.run_tool(self.blob, "--out", self.blob) - self.assertEqual(p.returncode, 1, p.stderr) - self.assertIn("overwrite the input", p.stderr) - self.assertNotIn("Traceback", p.stderr) - with open(self.blob, "rb") as f: - self.assertEqual(f.read(), before, "the sample is left as it was") - - def test_out_directory_is_a_message_not_a_traceback(self): - p = self.run_tool(self.blob, "--out", self.tmp.name) - self.assertEqual(p.returncode, 1, p.stderr) - self.assertIn("is a directory", p.stderr) - self.assertNotIn("Traceback", p.stderr) - - def test_out_under_a_regular_file_is_a_message_not_a_traceback(self): - # Before: os.makedirs raised FileExistsError (NotADirectoryError on Windows) out of check_preview_path. - p = self.run_tool(self.blob, "--out", os.path.join(self.blob, "sub", "p.png")) - self.assertEqual(p.returncode, 1, p.stderr) - self.assertIn("--out", p.stderr) - self.assertNotIn("Traceback", p.stderr) - - def test_out_creates_a_missing_folder(self): - sys.path.insert(0, os.path.join(ROOT, "tools")) - import tile_probe - preview = os.path.join(self.tmp.name, "previews", "deep", "best.png") - tile_probe.check_preview_path(preview, self.blob) - self.assertTrue(os.path.isdir(os.path.dirname(preview)), "the preview's folder is created") - - @unittest.skipIf(HAVE_PIL_ISOLATED, "this interpreter's -I can import Pillow") - def test_preview_without_pillow_is_a_message_not_a_traceback(self): - # Before: the probe ran, then render()'s lazy PIL import raised after all the work was done. - p = self.run_tool(self.blob, "--out", os.path.join(self.tmp.name, "preview.png")) - self.assertEqual(p.returncode, 1, p.stderr) - self.assertIn("Pillow", p.stderr) - self.assertNotIn("Traceback", p.stderr) - - def test_offset_inside_the_file_still_probes(self): - p = self.run_tool(self.blob, "--offset", "0") - self.assertEqual(p.returncode, 0, p.stderr) - self.assertIn("score", p.stdout) - - def test_block_feature_rejects_unsupported_bpe(self): - import numpy as np - sys.path.insert(0, os.path.join(ROOT, "tools")) - import tile_probe - - for bad_bpe in (1, 2, 4, 12): - with self.subTest(bpe=bad_bpe), self.assertRaises(ValueError): - tile_probe.block_feature(np.zeros((4, bad_bpe), np.uint8), bad_bpe) - - def test_render_packs_ddscaps_texture_and_rejects_unfitting_layout(self): - import struct - import types - from unittest import mock - - sys.path.insert(0, os.path.join(ROOT, "tools")) - import tile_probe - - captured = [] - - class _FakeImage: - size = (256, 64) - - def convert(self, _mode): - return self - - def save(self, _out): - pass - - fake_image_mod = types.SimpleNamespace(open=lambda bio: (captured.append(bio.getvalue()), _FakeImage())[1]) - fake_pil = types.SimpleNamespace(Image=fake_image_mod) - blob = bytes(256 * 256) - with mock.patch.dict(sys.modules, {"PIL": fake_pil, "PIL.Image": fake_image_mod}): - tile_probe.render(blob, 0, 8, 256, "4k", os.path.join(self.tmp.name, "ok.png")) - self.assertEqual(len(captured), 1) - caps = struct.unpack_from(" - - - - 500 600 700 - 0.1 0.5 1.0 - 0.1 0.5 1.0 - 0.1 0.5 1.0 - -1.0 0.0 2.0 - - - -""" - -SYNTH_MOD = b""" - - - 0.5 0.0 - 0.8 0.25 - 0.4 0.25 - 0.2 0.25 - 100.0 500.0 - - - - 1.2 1.0 - 250.0 250.0 - SYNTH_PLAIN_1 - - - - 0.0 1.0 - 0.0 1.0 - - - -""" - - -class TimecyclePairsTests(unittest.TestCase): - def test_summarize_synthetic_documents(self): - summary = tp.summarize_documents([ - ("timecycle_keyframe_data", SYNTH_KF), - ("timecycle_modifier_data", SYNTH_MOD), - ]) - self.assertEqual(summary["keyframe_docs"], 1) - self.assertEqual(summary["modifier_docs"], 1) - self.assertEqual(summary["modifiers"], {"total": 3, "plain": 2, "axis": 1}) - self.assertEqual(summary["plain_token_counts"], {"0": 1, "2": 7}) - self.assertEqual(summary["second_number"]["eq0"], 1) - self.assertEqual(summary["second_number"]["between_0_1"], 3) - self.assertEqual(summary["second_number"]["eq1"], 1) - self.assertEqual(summary["second_number"]["gt1"], 2) - self.assertEqual(summary["rgb_triplet_b_equality"], {"frac_all_equal": 1}) - self.assertEqual(summary["per_variable_b_constancy"]["both_b0_and_b1"], 1) - self.assertEqual(summary["per_variable_b_constancy"]["mixed_within_single_doc"], 1) - fc = summary["vars_with_b_outside_0_1"]["far_clip"] - self.assertEqual(fc["count"], 2) - self.assertEqual(fc["a_eq_b"], 1) - self.assertEqual(fc["a_lt_b"], 1) - self.assertEqual(fc["keyframe_range"], [500.0, 700.0]) - - def test_modifier_patterns_do_not_round_values_onto_endpoints(self): - values = ("-0.0000001", "0.0000001", "0.9999999", "1.0000001", "0", "1") - modifiers = "".join(f"2 {b}" for b in values) - blob = f"{modifiers}".encode() - summary = tp.summarize_documents([("timecycle_modifier_data", blob)]) - self.assertEqual(summary["per_modifier_b_pattern"], { - "outside_0_1": 2, "in_0_1_with_frac": 2, "all_b_eq_0": 1, "all_b_eq_1": 1, - }) - self.assertEqual(summary["second_number"]["distinct_round6"], 2) - - def test_non_ascii_root_extensions_are_not_target_documents(self): - for suffix in ("\u00e9", "\u6f22", "\u0301", "\u00b7"): - for target, payload in (("timecycle_modifier_data", SYNTH_MOD), ("timecycle_keyframe_data", SYNTH_KF)): - with self.subTest(suffix=suffix, target=target), tempfile.TemporaryDirectory() as tmp: - lookalike = payload.replace(target.encode(), (target + suffix).encode("utf-8")) - # These are valid XML names, but they identify different document types. - self.assertEqual(tp.ET.fromstring(lookalike).tag, target + suffix) - path = os.path.join(tmp, "lookalike.xml") - with open(path, "wb") as f: - f.write(lookalike) - self.assertEqual(tp.load_documents([path]), []) - self.assertEqual(tp.load_documents([tmp]), []) - valid = os.path.join(tmp, "valid.xml") - with open(valid, "wb") as f: - f.write(payload) - self.assertEqual(tp.load_documents([tmp]), [(target, payload)]) - - def test_carved_source_skips_non_ascii_root_extensions(self): - lookalike = SYNTH_MOD.replace(b"timecycle_modifier_data", "timecycle_modifier_data\u00e9".encode("utf-8")) - - class Source: - rows = [{"off": 0}, {"off": 1}] - - def read(self, row): - return (lookalike, SYNTH_MOD)[row["off"]] - - docs = tp._iter_source_docs(Source()) - self.assertEqual(docs, [("timecycle_modifier_data", SYNTH_MOD)]) - self.assertEqual(tp.summarize_documents(docs)["modifiers"]["total"], 3) - - def test_carved_root_name_boundary_can_arrive_in_the_next_stream(self): - marker = b" log.txt, or a pipe from make_game.py) is encoded with the console's ANSI -code page, and `python -I` ignores PYTHONUTF8 and PYTHONIOENCODING. A caller path with a character outside that -code page, such as a Cyrillic, Greek or CJK user name, or a Polish one under a code page without it, reached print() -as UnicodeEncodeError and ended the run. stderr escapes such characters (backslashreplace); stdout was strict. #1406 -fixed make_game.py. Every CLI tool now starts its __main__ block by setting errors="replace" on stdout, and so do -the programs under scripts/ and viewer/, which are run the same way. - -The paths below use a private-use character that no ANSI code page maps, so before the fix these tools died on any -Windows locale. On a UTF-8 console the character prints, and the test passes either way. Standard library only; -no game files (the inputs are zero bytes or an empty folder). -""" -import os -import re -import subprocess -import sys -import tempfile -import unittest - -ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) -TOOLS = os.path.join(ROOT, "tools") -PROGRAM_DIRS = ("tools", "scripts", "viewer") -# Still without the guard because open pull requests change this file; it gets the guard there or after them. -NOT_YET_GUARDED = { - "scripts/run_wine_tests.py", # open Wine runner pull requests change this file -} -MARK = "" -# Python 3.15 turns UTF-8 mode on by default, even under -I, and then a redirected stdout cannot fail this way. -# -X utf8=0 keeps the code page these tests are about, so they still catch a missing guard there. -PYTHON = [sys.executable, "-I", "-X", "utf8=0"] - - -class EveryToolGuardsStdout(unittest.TestCase): - def test_every_main_block_reconfigures_stdout(self): - missing = [] - for folder in PROGRAM_DIRS: - for name in sorted(os.listdir(os.path.join(ROOT, folder))): - rel = folder + "/" + name - if not name.endswith(".py") or rel in NOT_YET_GUARDED: - continue - with open(os.path.join(ROOT, folder, name), encoding="utf-8") as f: - text = f.read() - m = re.search(r"^if __name__ == ['\"]__main__['\"]:\n", text, re.M) - if m and 'sys.stdout.reconfigure(errors="replace")' not in text[m.end():m.end() + 400]: - missing.append(rel) - self.assertEqual(missing, [], "programs whose __main__ block doesn't set errors='replace' on stdout") - - -class MeasuredCrashes(unittest.TestCase): - # Each of these prints its input path to stdout and died with UnicodeEncodeError on Windows 11 given a zeroed - # input under a private-use-named folder, on every run (audio_wav, hashdict and shader_profile die the same way - # only once their --out already exists, so they are covered by the static check above rather than here). - CASES = [("analyze_4240_full.py", False), ("meshlet_page.py", False)] - - def test_a_path_outside_the_code_page_does_not_crash(self): - with tempfile.TemporaryDirectory() as tmp: - folder = os.path.join(tmp, "in-" + MARK) - os.makedirs(folder) - src = os.path.join(folder, "x" + MARK + ".bin") - with open(src, "wb") as f: - f.write(bytes(4096)) - out = os.path.join(tmp, "out-" + MARK) - for tool, with_out in self.CASES: - with self.subTest(tool=tool): - argv = [src] + (["--out", out] if with_out else []) - r = subprocess.run(PYTHON + [os.path.join(TOOLS, tool)] + argv, - capture_output=True, cwd=ROOT, timeout=300) - err = r.stderr.decode("utf-8", "replace") - self.assertNotIn("UnicodeEncodeError", err) - - -class ScriptsAndViewer(unittest.TestCase): - # Both died with UnicodeEncodeError on Windows 11 with stdout redirected: the audit after writing its report - # (exit 1), the viewer before it started serving. - def test_audit_with_a_report_path_outside_the_code_page(self): - with tempfile.TemporaryDirectory() as tmp: - disasm = os.path.join(tmp, "disasm-" + MARK) - os.makedirs(disasm) - report = os.path.join(tmp, "rep-" + MARK + ".json") - audit = os.path.join(ROOT, "scripts", "audit_shader4_regs.py") - r = subprocess.run(PYTHON + [audit, disasm, "--json", report], - capture_output=True, cwd=ROOT, timeout=300) - err = r.stderr.decode("utf-8", "replace") - self.assertNotIn("Traceback", err) - self.assertEqual(r.returncode, 0, err) - self.assertTrue(os.path.isfile(report)) - self.assertIn(b"wrote ", r.stdout) - - def test_viewer_with_a_world_path_outside_the_code_page(self): - with tempfile.TemporaryDirectory() as tmp: - world = os.path.join(tmp, "world-" + MARK) - os.makedirs(world) - serve = os.path.join(ROOT, "viewer", "serve.py") - proc = subprocess.Popen(PYTHON + [serve, "--world", world, "--port", "0"], - stdout=subprocess.PIPE, stderr=subprocess.PIPE, cwd=ROOT) - try: - line = proc.stdout.readline() # the viewer prints this line once it is listening - running = proc.poll() is None - finally: - proc.kill() - _, err = proc.communicate(timeout=60) - err = err.decode("utf-8", "replace") - self.assertNotIn("Traceback", err) - self.assertIn(b"viewer: http://127.0.0.1:", line) - self.assertTrue(running, err) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/test_translate.py b/tests/test_translate.py deleted file mode 100644 index d151c36e2..000000000 --- a/tests/test_translate.py +++ /dev/null @@ -1,1912 +0,0 @@ -"""Regression tests for tools/rdna2spirv.py (RDNA2 -> SPIR-V). - -Run from the repository root: python -m pytest tests -Needs llvm-mc (AMDGPU target) and spirv-tools; the tests skip themselves when those are missing. -""" -import glob -import math -import os -import re -import struct -from pathlib import Path - -import pytest - -import rdna2spirv -from conftest import (EMPTY_DXBC, KNOWN_VAL_ISSUES, ROOT, SAMPLE_DXBC, Shader, make_dxbc, mesh_psv0_chunk, - requires_tools, signature_chunk) - -pytestmark = requires_tools - -SAMPLES = sorted(glob.glob(os.path.join(ROOT, "runtime", "test", "shaders", "*.asm"))) -SAMPLES += sorted(glob.glob(os.path.join(ROOT, "tests", "semantic", "fixtures", "ps_*.asm"))) - -# One minimal pixel shader per instruction family listed in the "Supported" section of rdna2spirv.py's docstring. -# Each body is wrapped in a program that exports its result so nothing is optimised away. -SUPPORTED = { - "v_mov": "v_mov_b32 v0, 1.0", - "v_add_f32": "v_mov_b32 v1, 1.0\nv_add_f32 v0, v1, v1", - "v_sub_f32": "v_mov_b32 v1, 2.0\nv_sub_f32 v0, v1, 1.0", - "v_mul_f32": "v_mov_b32 v1, 2.0\nv_mul_f32 v0, v1, v1", - "v_fma_f32": "v_mov_b32 v1, 2.0\nv_fma_f32 v0, v1, v1, v1", - "v_max_f32": "v_mov_b32 v1, 2.0\nv_max_f32 v0, v1, 1.0", - "v_min_f32": "v_mov_b32 v1, 2.0\nv_min_f32 v0, v1, 1.0", - "v_rcp_f32": "v_mov_b32 v1, 4.0\nv_rcp_f32 v0, v1", - "v_sqrt_f32": "v_mov_b32 v1, 4.0\nv_sqrt_f32 v0, v1", - "v_floor_f32": "v_mov_b32 v1, 1.5\nv_floor_f32 v0, v1", - "v_fract_f32": "v_mov_b32 v1, 1.5\nv_fract_f32 v0, v1", - "v_cvt_f32_u32": "v_mov_b32 v1, 7\nv_cvt_f32_u32 v0, v1", - "v_cvt_u32_f32": "v_mov_b32 v1, 7.0\nv_cvt_u32_f32 v0, v1", - "v_add_nc_u32": "v_mov_b32 v1, 7\nv_add_nc_u32 v0, v1, v1", - "v_and_b32": "v_mov_b32 v1, 7\nv_and_b32 v0, 3, v1", - "v_lshlrev_b32": "v_mov_b32 v1, 7\nv_lshlrev_b32 v0, 2, v1", - "v_lshrrev_b32": "v_mov_b32 v1, 7\nv_lshrrev_b32 v0, 1, v1", - "v_bfe_u32": "v_mov_b32 v1, 0xf0\nv_bfe_u32 v0, v1, 4, 4", - "v_med3_f32": "v_mov_b32 v1, 2.0\nv_med3_f32 v0, v1, 1.0, 4.0", - "s_mov_b32": "s_mov_b32 s40, 5\nv_mov_b32 v0, s40", - "s_add_u32": "s_mov_b32 s40, 5\ns_add_u32 s41, s40, 3\nv_mov_b32 v0, s41", -} - - -def program(body): - return f"{body}\nv_mov_b32 v8, v0\nexp mrt0 v8, v8, v8, v8 done vm\ns_endpgm\n" - - -@pytest.mark.parametrize("path", SAMPLES, ids=[os.path.basename(p) for p in SAMPLES]) -def test_gpu_samples_translate_and_validate(path, make_shader): - """The hand-written GPU-harness and semantic shader samples must translate to valid SPIR-V.""" - stem = os.path.splitext(os.path.basename(path))[0] - name = stem if stem.startswith(("vs_", "ps_", "cs_", "gs_", "ms_")) else "ps_" + stem # the prefix selects the stage - if name.startswith(("gs_", "ms_")) and stem not in SAMPLE_DXBC: - pytest.skip(f"no synthetic DXBC (ISG1/OSG1 for gs, PSV0 for ms) defined for {stem} in conftest.SAMPLE_DXBC") - with open(path, encoding="utf-8") as f: - shader = make_shader(f.read(), name, dxbc=SAMPLE_DXBC.get(stem, EMPTY_DXBC)) - shader.validate(shader.translate(), KNOWN_VAL_ISSUES.get(stem)) - - -@pytest.mark.parametrize("case", sorted(SUPPORTED)) -def test_supported_instruction(case, make_shader): - shader = make_shader(program(SUPPORTED[case])) - shader.validate(shader.translate()) - - -# VOP1/VOP2 DPP source controls. The source lane is a shuffle followed by row/bank masking; a lane that the -# instruction leaves unwritten keeps its old destination, including for non-mov ops. -DPP_CASES = { - "quad_perm": "v_mov_b32_dpp v1, v0 quad_perm:[1,0,3,2] row_mask:0xf bank_mask:0xf", - "quad_perm_masked": "v_mov_b32_dpp v1, v0 quad_perm:[1,0,3,2] row_mask:0x1 bank_mask:0x3", - "row_shl": "v_mov_b32_dpp v1, v0 row_shl:1 row_mask:0xf bank_mask:0xf", - "row_shr_bound": "v_mov_b32_dpp v1, v0 row_shr:1 row_mask:0xf bank_mask:0xf bound_ctrl:1", - "row_ror": "v_mov_b32_dpp v1, v0 row_ror:4 row_mask:0xf bank_mask:0xf", - "row_share": "v_mov_b32_dpp v1, v0 row_share:2 row_mask:0xf bank_mask:0xf", - "row_xmask": "v_mov_b32_dpp v1, v0 row_xmask:4 row_mask:0xf bank_mask:0xf", - "row_mirror": "v_mov_b32_dpp v1, v0 row_mirror row_mask:0xf bank_mask:0xf", - "row_half_mirror": "v_mov_b32_dpp v1, v0 row_half_mirror row_mask:0xf bank_mask:0xf", - "dpp8": "v_mov_b32_dpp v1, v0 dpp8:[7,6,5,4,3,2,1,0] fi:1", - "vop1_not_bank": "v_not_b32_dpp v1, v0 quad_perm:[0,1,2,3] row_mask:0xf bank_mask:0x1", - "vop2_add_shr": "v_add_nc_u32_dpp v1, v0, v2 row_shr:1 row_mask:0xf bank_mask:0xf", -} - - -@pytest.mark.parametrize("case", sorted(DPP_CASES)) -def test_dpp_controls_translate_and_validate(case, make_shader): - shader = make_shader(program("v_mov_b32 v0, v0\n" + DPP_CASES[case])) - spvasm = shader.translate() - shader.validate(spvasm) - assert "OpGroupNonUniformShuffle" in spvasm - - -@pytest.mark.parametrize("mods", [[], ["row_share:20"], ["row_shl:0"], ["row_shl:1", "row_shr:2"]]) -def test_dpp_bad_control_is_rejected(mods): - """A missing, out-of-range or duplicate DPP control must fail instead of guessing.""" - gen = rdna2spirv.Gen("ps") - ins = {"op": "v_mov_b32_dpp", "args": [{"k": "vgpr", "r": 1}, {"k": "vgpr", "r": 0}], "mods": mods} - with pytest.raises(rdna2spirv.Unsupported): - gen.insn(ins) - - -def test_dpp_wave64_emulation_goes_through_workgroup_memory(make_shader, monkeypatch): - """--wave64-emulate must not leave a subgroup shuffle in a DPP shader.""" - shader = make_shader("s_mov_b64 exec, -1\n" - "v_mov_b32_dpp v1, v0 quad_perm:[1,0,3,2] row_mask:0xf bank_mask:0xf\n" - "s_endpgm\n", name="cs_dpp_w64") - monkeypatch.setattr(rdna2spirv, "WAVE64_EMULATE", True) - spvasm = shader.translate() - shader.validate(spvasm) - assert "OpGroupNonUniform" not in spvasm and "%sg_lane" not in spvasm - assert "%x_buf" in spvasm and "OpControlBarrier" in spvasm - - -def test_translation_is_deterministic(make_shader): - shader = make_shader(program(SUPPORTED["v_fma_f32"])) - assert shader.translate() == shader.translate() - - -def test_unsupported_instruction_is_reported_not_guessed(make_shader): - """Anything outside the supported set must raise Unsupported rather than emit a wrong program.""" - shader = make_shader(program("v_mov_b32 v1, 1.0\nv_sat_pk_u8_i16 v0, v1")) - with pytest.raises(rdna2spirv.Unsupported): - shader.translate() - - -@pytest.mark.parametrize("a16", [False, True], ids=["a32", "a16"]) -@pytest.mark.parametrize("d16", [False, True], ids=["f32", "d16"]) -def test_explicit_mip_depth_compare(make_shader, a16, d16): - # Under A16 the reference is still f32; XY share v1 and LOD is the low half of v2. - if a16: - moves = "v_mov_b32 v1, 0x3a003400\nv_mov_b32 v2, 0x40003c00\n" - address, modifier = "v[0:2]", " a16" - else: - moves = "v_mov_b32 v1, 0.25\nv_mov_b32 v2, 0.75\nv_mov_b32 v3, 1.0\n" - address, modifier = "v[0:3]", "" - shader = make_shader("v_mov_b32 v0, 0.5\n" + moves + - f"image_sample_c_l v4, {address}, s[0:7], s[8:11] dmask:0x1 dim:SQ_RSRC_IMG_2D" + - modifier + (" d16" if d16 else "") + "\ns_waitcnt vmcnt(0)\nexp mrt0 v4, v4, v4, v4 done vm\ns_endpgm\n") - spv = shader.translate() - shader.validate(spv) - sample = re.search(r"(%\w+) = OpImageSampleDrefExplicitLod %float %\w+ %\w+ (%\w+) Lod (%\w+)", spv) - assert sample - defs = dict(re.findall(r"(%\w+) = (.+)", spv)) - - def float_source_register(value: str) -> list[str]: - load = defs[value].split()[-1] # f32 bitcast - ptr = defs[load].split()[-1] # raw VGPR word - return defs[ptr].split()[-2:] - - result, ref, lod = sample.groups() - assert float_source_register(ref) == ["%vgpr", "%c0"] - if a16: - unpacked_half = lod - while defs[unpacked_half].startswith("OpBitcast "): # a bitcast round trip is the original id - unpacked_half = defs[unpacked_half].split()[-1] - op, _, pair, half = defs[unpacked_half].split() - assert (op, half) == ("OpCompositeExtract", "0") - raw = defs[pair].split()[-1] - assert defs[defs[raw].split()[-1]].endswith("%vgpr %c2") - else: - assert float_source_register(lod) == ["%vgpr", "%c3"] - bits = next(name for name, code in defs.items() if code == f"OpBitcast %uint {result}") - assert any(code == f"OpShiftRightLogical %uint {bits} %c10" for code in defs.values()) == d16 - - -@pytest.mark.parametrize("sample", [ - "v[4:5], v[0:3], s[0:7], s[8:11] dmask:0x3 dim:SQ_RSRC_IMG_2D", - "v4, v[0:4], s[0:7], s[8:11] dmask:0x1 dim:SQ_RSRC_IMG_3D", -]) -def test_explicit_mip_depth_compare_unmodelled_forms(make_shader, sample): - shader = make_shader(f"image_sample_c_l {sample}\ns_endpgm\n") - with pytest.raises(rdna2spirv.Unsupported, match="scalar 2D depth comparison"): - shader.translate() - - -@pytest.mark.parametrize("d16", [False, True], ids=["f32", "d16"]) -def test_depth_compare_sample_result_width(make_shader, d16): - """image_sample_c_lz returns one value: f32 bits, or with d16 an f16 in the low half like every other d16 sample - result. Written as f32 bits under d16, every compare result would read back as 0 (1.0 = 0x3f800000).""" - shader = make_shader("v_mov_b32 v0, 0.5\nv_mov_b32 v1, 0.5\nv_mov_b32 v2, 0.25\n" - "image_sample_c_lz v4, v[0:2], s[0:7], s[8:11] dmask:0x1 dim:SQ_RSRC_IMG_2D" - + (" d16" if d16 else "") + "\nexp mrt0 v4, v4, v4, v4 done vm\ns_endpgm\n", "ps_dref") - spvasm = shader.translate() - shader.validate(spvasm) - dref = re.search(r"^\s*(%\w+) = OpImageSampleDrefExplicitLod %float ", spvasm, re.M) - assert dref, "the depth compare sample is missing" - d = re.escape(dref.group(1)) - bitcast = re.search(rf"^\s*(%\w+) = OpBitcast %uint {d}$", spvasm, re.M) - assert bitcast, "the depth compare bitcast is missing" - bc = re.escape(bitcast.group(1)) - as_f16 = re.search(rf"^\s*%\w+ = OpShiftRightLogical %uint {bc} %c10$", spvasm, re.M) - assert bool(as_f16) == d16 - - - -@pytest.mark.parametrize("export,depth", [ - ("exp mrtz v2, off, off, off vm", True), # Z only (SPI_SHADER_32_R) - ("exp mrtz v2, v3, off, off vm", True), # Z and stencil (32_GR) - ("exp mrtz off, v3, off, off vm", False), # stencil only (32_GR) - ("exp mrtz off, off, v3, off vm", False), # sample mask only, 32-bit - ("exp mrtz v2, v2, v3, v3 compr vm", False), # stencil and sample mask, 16-bit (UINT16_ABGR) -], ids=["z", "z-stencil", "stencil", "mask", "compr"]) -def test_mrtz_depth_only_from_an_enabled_x(make_shader, export, depth): - """exp mrtz carries Z in x only when x is on in an uncompressed export; the 16-bit form holds stencil and sample - mask, never Z (Mesa ac_nir_lower_ps_late.c emit_ps_mrtz_export). Without a depth the shader must not replace it.""" - shader = make_shader("v_mov_b32 v2, 0.5\nv_mov_b32 v3, 1\n" + export + "\nexp mrt0 v2, v2, v2, v2 done vm\n" - "s_endpgm\n", "ps_mrtz") - spvasm = shader.translate() - shader.validate(spvasm) - assert ("BuiltIn FragDepth" in spvasm) == depth - assert ("DepthReplacing" in spvasm) == depth - - -@pytest.mark.parametrize("body", [ - "", # straight line (SHADER-350) - "s_cmp_eq_u32 s20, 0\ns_cbranch_scc1 1\nv_mov_b32 v0, 1.0\n", # branching control flow -], ids=["straight-line", "branch"]) -def test_pops_interlock_begins_and_ends_once(make_shader, body): - """A PS that reads src_pops_exiting_wave_id runs in one fragment-shader interlock: one - OpBeginInvocationInterlockEXT, then one OpEndInvocationInterlockEXT (SPV_EXT_fragment_shader_interlock: each - exactly once, begin before end). Validated against spirv-val.""" - shader = make_shader("v_mov_b32 v0, 0.5\ns_mov_b32 s20, src_pops_exiting_wave_id\n" + body + - "exp mrt0 v0, v0, v0, v0 done vm\ns_endpgm\n", "ps_pops") - spvasm = shader.translate() - shader.validate(spvasm) - assert "PixelInterlockOrderedEXT" in spvasm - assert spvasm.count("OpBeginInvocationInterlockEXT") == 1 - assert spvasm.count("OpEndInvocationInterlockEXT") == 1 - assert spvasm.index("OpBeginInvocationInterlockEXT") < spvasm.index("OpEndInvocationInterlockEXT") - -def test_constants_asked_for_late_are_defined(make_shader): - """assemble writes the uint constants before the format tables, which then ask gen.cu for their own. In a shader - whose only typed access is a d16 store nothing else used 128, so fmt_size_arr's length was %c80 with no - definition and the module failed spirv-val.""" - shader = make_shader("v_mov_b32 v1, 0x9c004000\nv_mov_b32 v2, 0\n" - "buffer_store_format_d16_xy v1, v2, s[0:3], 0 offen\n" - "exp mrt0 v0, v0, v0, v0 done vm\ns_endpgm\n", "ps_late_constants") - spvasm = shader.translate() - assert re.search(r"%fmt_size_arr = OpTypeArray %uint %c80$", spvasm, re.M) - defs = [m.start() for m in re.finditer(r"^\s*%c80 = OpConstant %uint 128$", spvasm, re.M)] - assert len(defs) == 1 and defs[0] < spvasm.index("%fmt_size_arr = OpTypeArray") - shader.validate(spvasm) - - -def test_a16_sample_gradients_use_full_vgprs(make_shader): - path = os.path.join(ROOT, "runtime", "test", "shaders", "ps_texture_grad_a16.asm") - with open(path, encoding="utf-8") as fixture: - shader = make_shader(fixture.read(), "ps_texture_grad_a16") - spvasm = shader.translate() - sample = re.search(r"= OpImageSampleExplicitLod %v4float %\w+ %\w+ Grad (%\w+) (%\w+)$", spvasm, re.M) - assert sample, "the explicit-gradient sample is missing" - definitions = dict(re.findall(r"^\s*(%\w+) = (Op[^\n]+)", spvasm, re.M)) - - # Trace dPdx and dPdy back to the fixture's full 32-bit derivative words, in operand order. - for vector, registers in zip(sample.groups(), ((8, 9), (10, 11))): - assert definitions[vector].startswith("OpCompositeConstruct %v2float ") - components = definitions[vector].split()[2:] - assert len(components) == 2 - for component, register in zip(components, registers): - cast, float_type, word = definitions[component].split() - assert (cast, float_type) == ("OpBitcast", "%float") - load, word_type, pointer = definitions[word].split() - assert (load, word_type) == ("OpLoad", "%uint") - *access, index = definitions[pointer].split() - assert access == ["OpAccessChain", "%_ptr_Function_uint", "%vgpr"] - assert definitions[index] == f"OpConstant %uint {register}" - shader.validate(spvasm) - - -def test_unknown_stage_is_rejected(make_shader): - shader = make_shader(program("v_mov_b32 v0, 1.0"), name="xx_test") - with pytest.raises(rdna2spirv.Unsupported): - shader.translate() - - -def test_compute_translates_and_validates(make_shader): - shader = make_shader("v_mov_b32 v1, 1\ns_endpgm\n", name="cs_test") - shader.validate(shader.translate()) - - -def test_cs_store_packed_atomic_pointers(make_shader): - """Packed stores need element zero of the physical dword array for Metal atomics.""" - with open(os.path.join(ROOT, "runtime", "test", "shaders", "cs_store.asm"), encoding="utf-8") as f: - spvasm = make_shader(f.read(), "cs_store").translate() - defs = dict(re.findall(r"^\s*(%\w+) = (Op[^\n]+)", spvasm, re.M)) - atomics = re.findall(r"= (OpAtomicAnd|OpAtomicOr) %uint (%\w+) ", spvasm) - assert {op for op, ptr in atomics} == {"OpAtomicAnd", "OpAtomicOr"} - for _, ptr in atomics: - access = defs[ptr].split() - assert access[:2] == ["OpAccessChain", "%_ptr_PSB_uint"] - _, _, base, index = access - assert defs[base].startswith("OpConvertUToPtr %_ptr_PSB_arr ") - assert defs[index] == "OpConstant %uint 0" - - -def test_compute_thread_group_size_sgpr_is_written(make_shader): - """TG_SIZE_EN (RSRC2 bit 10) adds the thread-group SGPR after the workgroup ids (s5 here); the prologue writes it - (tests/semantic/test_cs_tg_size.py runs it).""" - shader = make_shader("s_endpgm\n", name="cs_test", cs_header=(0x8088 | 1 << 10, (64, 1, 1))) - assert "%tgv" in shader.translate() - - -@pytest.mark.parametrize("group", [(0, 1, 1), (2048, 1, 1)], ids=["empty", "over-1024"]) -def test_compute_bad_group_size_is_rejected(make_shader, group): - shader = make_shader("s_endpgm\n", name="cs_test", cs_header=(0x8088, group)) - with pytest.raises(rdna2spirv.Unsupported): - shader.translate() - - -def test_geometry_emit_cut_starts_a_new_triangle_strip(tmp_path: Path) -> None: - asm = (Path(__file__).parent / "semantic" / "fixtures" / "gs_emit_cut.asm").read_text(encoding="utf-8") - position = [(0, 1, 0xf)] - dxbc = make_dxbc([signature_chunk(b"ISG1", position), signature_chunk(b"OSG1", position)]) - shader = Shader(tmp_path, "gs_emit_cut", asm, dxbc=dxbc) - module = shader.translate() - shader.validate(module) - assert "OpExecutionMode %main OutputTriangleStrip" in module - # EXEC stays on throughout the fixture. Each end terminates the current strip after its last vertex. - strips: list[list[int]] = [[]] - vertex = 0 - for event in re.findall(r"^\s*(OpEmitVertex|OpEndPrimitive)$", module, re.MULTILINE): - if event == "OpEndPrimitive": - strips.append([]) - else: - strips[-1].append(vertex) - vertex += 1 - assert strips == [[0, 1, 2], [3, 4, 5], []] - assert len(re.findall(r"OpEmitVertex\s+OpEndPrimitive", module)) == 2 # both run under the same EXEC guard - - -def test_geometry_without_signatures_is_rejected(make_shader): - """A gs needs ISG1/OSG1 to know which registers LDS holds and which outputs to write.""" - with open(os.path.join(ROOT, "runtime", "test", "shaders", "gs_tri.asm"), encoding="utf-8") as f: - shader = make_shader(f.read(), "gs_tri") # empty DXBC - with pytest.raises(rdna2spirv.Unsupported): - shader.translate() - - -def test_gs_packed_input_register_emits_one_variable(make_shader): - """Packed ISG1 elements sharing a register must emit one %gs_inN variable and pass spirv-val.""" - with open(os.path.join(ROOT, "runtime", "test", "shaders", "gs_tri.asm"), encoding="utf-8") as f: - asm = f.read() - dxbc = make_dxbc([ - signature_chunk(b"ISG1", [(0, 1, 0xF), (1, 0, 0x3), (1, 0, 0xC)]), - signature_chunk(b"OSG1", [(0, 1, 0xF), (1, 0, 0xF)]), - ]) - shader = make_shader(asm, "gs_tri_packed", dxbc=dxbc) - spvasm = shader.translate() - assert spvasm.count("%gs_in1 = OpVariable") == 1 - assert spvasm.count("OpDecorate %gs_in1 Location 1") == 1 - meta = rdna2spirv.shader_meta(rdna2spirv.translate.last_gen, spvasm) - assert meta["gs_inputs"] == [0, 1] - assert meta["gs_input_locations"] == [1] - shader.validate(spvasm) - - -def test_gs_conflicting_position_and_user_in_same_register_rejected(make_shader): - """Sharing one GS input register between SV_Position and a user varying cannot map to one variable.""" - with open(os.path.join(ROOT, "runtime", "test", "shaders", "gs_tri.asm"), encoding="utf-8") as f: - asm = f.read() - dxbc = make_dxbc([ - signature_chunk(b"ISG1", [(0, 1, 0x3), (0, 0, 0xC)]), - signature_chunk(b"OSG1", [(0, 1, 0xF), (1, 0, 0xF)]), - ]) - shader = make_shader(asm, "gs_tri_conflict", dxbc=dxbc) - with pytest.raises(rdna2spirv.Unsupported): - shader.translate() - - -@pytest.mark.parametrize("kw", [dict(topology=1), dict(threads=(2048, 1, 1)), dict(max_vertices=0)], - ids=["not-triangles", "over-1024-threads", "no-vertices"]) -def test_mesh_bad_psv0_is_rejected(make_shader, kw): - with open(os.path.join(ROOT, "runtime", "test", "shaders", "ms_tri.asm"), encoding="utf-8") as f: - shader = make_shader(f.read(), "ms_tri", dxbc=make_dxbc([mesh_psv0_chunk(**kw)])) - with pytest.raises(rdna2spirv.Unsupported): - shader.translate() - - -def test_mesh_without_psv0_is_rejected(make_shader): - with open(os.path.join(ROOT, "runtime", "test", "shaders", "ms_tri.asm"), encoding="utf-8") as f: - shader = make_shader(f.read(), "ms_tri") # empty DXBC - with pytest.raises(rdna2spirv.Unsupported): - shader.translate() - - -def test_wave32_readlane_writelane_mask_31(make_shader): - """SHADER-52: wave32 lane select is & 31; wave64 keeps & 63.""" - with open(os.path.join(ROOT, "runtime", "test", "shaders", "cs_w32_lane_wrap.asm"), encoding="utf-8") as f: - w32 = make_shader(f.read(), name="cs_w32_lane_wrap", cs_header=(0x8088, (32, 1, 1))) - w32_spv = w32.translate() - w32.validate(w32_spv) - assert "OpBitwiseAnd %uint" in w32_spv and "%c1f" in w32_spv # 31 - # Every readlane/writelane mask in this wave32 program is 31, never 63. - assert not re.search(r"OpBitwiseAnd %uint %\w+ %c3f\b", w32_spv) - assert rdna2spirv.translate.last_gen.wave64 is False - - with open(os.path.join(ROOT, "runtime", "test", "shaders", "cs_w64x_readlane.asm"), encoding="utf-8") as f: - w64 = make_shader(f.read(), name="cs_w64x_readlane") - w64_spv = w64.translate() - assert rdna2spirv.translate.last_gen.wave64 is True - assert re.search(r"OpBitwiseAnd %uint %\w+ %c3f\b", w64_spv) # 63 - - -@pytest.mark.parametrize("threads", [96, 128], ids=["96-threads", "128-threads"]) -def test_mesh_v5_seed_and_threads_constant(make_shader, threads): - """Mesh prologue computes v5 = %wlin * NumThreads + %lidx and registers NumThreads before assembly (7b82460).""" - with open(os.path.join(ROOT, "runtime", "test", "shaders", "ms_tri.asm"), encoding="utf-8") as f: - asm = f.read() - dxbc = make_dxbc([mesh_psv0_chunk(threads=(threads, 1, 1), max_vertices=64, max_primitives=64)]) - shader = make_shader(asm, name=f"ms_v5_seed_{threads}", dxbc=dxbc) - spvasm = shader.translate() - cid = f"%c{threads:x}" - assert f"{cid} = OpConstant %uint {threads}" in spvasm - assert f"%wbase = OpIMul %uint %wlin {cid}" in spvasm - assert "%v5v = OpIAdd %uint %wbase %lidx" in spvasm - assert "%v5p = OpAccessChain %_ptr_Function_uint %vgpr %c5" in spvasm - assert "OpStore %v5p %v5v" in spvasm - shader.validate(spvasm, KNOWN_VAL_ISSUES.get("ms_tri")) -def test_mesh_cull_primitive_is_block_bool(make_shader): - """CullPrimitiveEXT must be a Block bool member (VUID-07036); array-of-bool trips SPIRV-Tools ≤2025.1.""" - with open(os.path.join(ROOT, "runtime", "test", "shaders", "ms_v5_workgroup.asm"), encoding="utf-8") as f: - shader = make_shader(f.read(), "ms_v5_workgroup", dxbc=SAMPLE_DXBC["ms_v5_workgroup"]) - spvasm = shader.translate() - shader.validate(spvasm) - assert "OpDecorate %ms_cull_blk Block" in spvasm - assert "OpMemberDecorate %ms_cull_blk 0 BuiltIn CullPrimitiveEXT" in spvasm - assert "OpMemberDecorate %ms_cull_blk 0 PerPrimitiveEXT" in spvasm - assert "%ms_cull_blk = OpTypeStruct %bool" in spvasm - assert re.search(r"%ms_arr_cull = OpTypeArray %ms_cull_blk %c\w+", spvasm) - assert "OpDecorate %ms_cull BuiltIn CullPrimitiveEXT" not in spvasm - assert re.search(r"OpAccessChain %_ptr_Out_bool_ms %ms_cull %\w+ %c0", spvasm) - - -# ---- pos1..pos3: ClipDistance / CullDistance / misc exports (VS & MS) ---- - -def _vgpr_to_index_map(spvasm, array_var, ptr_type): - """Trace each OpStore to `array_var[idx]` back to the VGPR index loaded from `%vgpr`.""" - import re - vgpr_of = {} - val_of = {} - ptr_idx = {} - stores = {} - for line in spvasm.splitlines(): - m = re.match(r"\s*(%\w+) = OpAccessChain %_ptr_Function_uint %vgpr %c([0-9a-f]+)", line) - if m: - vgpr_of[m.group(1)] = int(m.group(2), 16) - continue - m = re.match(r"\s*(%\w+) = OpLoad %uint (%\w+)", line) - if m and m.group(2) in vgpr_of: - val_of[m.group(1)] = vgpr_of[m.group(2)] - continue - m = re.match(r"\s*(%\w+) = OpBitcast %float (%\w+)", line) - if m and m.group(2) in val_of: - val_of[m.group(1)] = val_of[m.group(2)] - continue - m = re.match(rf"\s*(%\w+) = OpAccessChain {re.escape(ptr_type)} {re.escape(array_var)} %c(\d+)", line) - if m: - ptr_idx[m.group(1)] = int(m.group(2)) - continue - m = re.match(r"\s*(%\w+) = OpSelect %float %\w+ (%\w+) %\w+", line) - if m and m.group(2) in val_of: - val_of[m.group(1)] = val_of[m.group(2)] - continue - m = re.match(r"\s*OpStore (%\w+) (%\w+)", line) - if m and m.group(1) in ptr_idx and m.group(2) in val_of: - stores[ptr_idx[m.group(1)]] = val_of[m.group(2)] - return stores - - -def _ms_header_asm(pos_exports): - return ( - "v_mbcnt_lo_u32_b32 v0, -1, 0\n" - "v_mbcnt_hi_u32_b32 v0, -1, v0\n" - "s_mov_b32 m0, 0x1003\n" - "s_sendmsg sendmsg(MSG_GS_ALLOC_REQ)\n" - "v_mov_b32 v1, 0.0\n" - "v_mov_b32 v2, 1.0\n" - "v_mov_b32 v10, 0.25\n" - "v_mov_b32 v11, 0.5\n" - "v_mov_b32 v12, 1.0\n" - "v_mov_b32 v13, 2.0\n" - "v_mov_b32 v14, 4.0\n" - "exp pos0 v1, v1, v1, v2\n" - f"{pos_exports}\n" - "v_mov_b32 v9, 0x200400\n" - "exp prim v9, off, off, off done\n" - "s_endpgm\n" - ) - - -def _vs_header_asm(pos_exports): - return ( - "v_mov_b32 v1, 0.0\n" - "v_mov_b32 v2, 1.0\n" - "v_mov_b32 v10, 0.25\n" - "v_mov_b32 v11, 0.5\n" - "v_mov_b32 v12, 1.0\n" - "v_mov_b32 v13, 2.0\n" - "v_mov_b32 v14, 4.0\n" - "exp pos0 v1, v1, v1, v2\n" - f"{pos_exports}\n" - "s_endpgm\n" - ) - - -@pytest.mark.parametrize("n_comp,exp_line,mask", [ - (1, "exp pos1 v10, off, off, off done", 0x1), - (4, "exp pos1 v10, v11, v12, v13 done", 0xF), -], ids=["1-comp", "4-comp"]) -def test_vs_clip_distance_pos1(make_shader, n_comp, exp_line, mask): - import re - dxbc = make_dxbc([signature_chunk(b"OSG1", [(0, 1, 0xF), (1, 2, mask)])]) - shader = make_shader(_vs_header_asm(exp_line), name="vs_clip_test", dxbc=dxbc) - spvasm = shader.translate() - shader.validate(spvasm) - assert "OpCapability ClipDistance" in spvasm - assert "OpCapability CullDistance" not in spvasm - assert "OpDecorate %out_clip BuiltIn ClipDistance" in spvasm - assert f"%arr_clip = OpTypeArray %float %c{n_comp}" in spvasm - chains = re.findall(r"OpAccessChain %_ptr_Output_float %out_clip %c(\d+)", spvasm) - assert [int(x) for x in chains] == list(range(n_comp)) - assert _vgpr_to_index_map(spvasm, "%out_clip", "%_ptr_Output_float") == {i: 10 + i for i in range(n_comp)} - meta = rdna2spirv.shader_meta(rdna2spirv.translate.last_gen, spvasm) - assert meta["clip_distance_count"] == n_comp - assert "shaderClipDistance" in meta["features"] - assert "shaderCullDistance" not in meta["features"] - assert 1 not in meta.get("outputs", []) - - -@pytest.mark.parametrize("n_comp,exp_line,mask", [ - (1, "exp pos1 v10, off, off, off done", 0x1), - (4, "exp pos1 v10, v11, v12, v13 done", 0xF), -], ids=["1-comp", "4-comp"]) -def test_ms_clip_distance_pos1(make_shader, n_comp, exp_line, mask): - import re - dxbc = make_dxbc([mesh_psv0_chunk(), signature_chunk(b"OSG1", [(0, 1, 0xF), (1, 2, mask)])]) - shader = make_shader(_ms_header_asm(exp_line), name="ms_clip_test", dxbc=dxbc) - spvasm = shader.translate() - shader.validate(spvasm, KNOWN_VAL_ISSUES.get("ms_tri")) - assert "OpCapability ClipDistance" in spvasm - assert "OpDecorate %ms_vtx_blk Block" in spvasm - assert "OpMemberDecorate %ms_vtx_blk 0 BuiltIn Position" in spvasm - assert "OpMemberDecorate %ms_vtx_blk 1 BuiltIn ClipDistance" in spvasm - assert f"%ms_arr_clip = OpTypeArray %float %c{n_comp}" in spvasm - chains = re.findall(r"OpAccessChain %_ptr_Function_float %ms_clip %c(\d+)", spvasm) - assert [int(x) for x in chains] == list(range(n_comp)) * 2 # the export writes, then the copy to the output - assert _vgpr_to_index_map(spvasm, "%ms_clip", "%_ptr_Function_float") == {i: 10 + i for i in range(n_comp)} - # Copied to the mesh output one float at a time: SPIRV-Cross turns a whole-array store there into a C array - # assignment that Metal rejects (SHADER-155). - out_chains = re.findall(r"OpAccessChain %_ptr_Out_float_ms %ms_out_vtx %mli %c1 %c(\d+)", spvasm) - assert [int(x) for x in out_chains] == list(range(n_comp)) - assert "OpLoad %ms_arr_clip" not in spvasm - meta = rdna2spirv.shader_meta(rdna2spirv.translate.last_gen, spvasm) - assert "shaderClipDistance" in meta["features"] - assert 1 not in meta.get("outputs", []) - assert 1 not in meta.get("params", []) - - -def test_vs_clip_and_cull_distances_across_pos1_pos2(make_shader): - """2 clip distances + 3 cull distances pack contiguously: pos1.xy=clip[0..1], pos1.zw=cull[0..1], pos2.x=cull[2].""" - import re - dxbc = make_dxbc([signature_chunk(b"OSG1", [(0, 1, 0xF), (1, 2, 0x3), (2, 3, 0x7)])]) - asm = _vs_header_asm("exp pos1 v10, v11, v12, v13\nexp pos2 v14, off, off, off done") - shader = make_shader(asm, name="vs_clip_cull", dxbc=dxbc) - spvasm = shader.translate() - shader.validate(spvasm) - assert "OpCapability ClipDistance" in spvasm - assert "OpCapability CullDistance" in spvasm - assert "%arr_clip = OpTypeArray %float %c2" in spvasm - assert "%arr_cull = OpTypeArray %float %c3" in spvasm - clip_chains = re.findall(r"OpAccessChain %_ptr_Output_float %out_clip %c(\d+)", spvasm) - cull_chains = re.findall(r"OpAccessChain %_ptr_Output_float %out_cull %c(\d+)", spvasm) - assert [int(x) for x in clip_chains] == [0, 1] - assert [int(x) for x in cull_chains] == [0, 1, 2] - assert _vgpr_to_index_map(spvasm, "%out_clip", "%_ptr_Output_float") == {0: 10, 1: 11} - assert _vgpr_to_index_map(spvasm, "%out_cull", "%_ptr_Output_float") == {0: 12, 1: 13, 2: 14} - meta = rdna2spirv.shader_meta(rdna2spirv.translate.last_gen, spvasm) - assert "shaderClipDistance" in meta["features"] - assert "shaderCullDistance" in meta["features"] - assert meta["clip_distance_count"] == 2 - assert meta["cull_distance_count"] == 3 - assert not ({1, 2} & set(meta.get("outputs", []))) - assert not ({1, 2} & set(meta.get("params", []))) - - -def test_vs_misc_pos1_shifts_clip_to_pos2(make_shader): - """When OSG1 declares SV_RenderTargetArrayIndex (sysv=4), pos1 is the misc vector and ClipDistance starts at pos2.""" - import re - dxbc = make_dxbc([signature_chunk(b"OSG1", [(0, 1, 0xF), (1, 4, 0x1), (2, 2, 0x3)])]) - asm = _vs_header_asm("exp pos1 off, off, v14, off\nexp pos2 v10, v11, off, off done") - shader = make_shader(asm, name="vs_misc_clip", dxbc=dxbc) - spvasm = shader.translate() - shader.validate(spvasm) - assert "OpCapability ShaderLayer" in spvasm - assert "OpCapability ClipDistance" in spvasm - assert "OpDecorate %out_layer BuiltIn Layer" in spvasm - assert "%arr_clip = OpTypeArray %float %c2" in spvasm - clip_chains = re.findall(r"OpAccessChain %_ptr_Output_float %out_clip %c(\d+)", spvasm) - assert [int(x) for x in clip_chains] == [0, 1] - - -def test_pos1_without_osg1_is_ignored(make_shader): - """Without OSG1 declaring SV_ClipDistance/SV_CullDistance, pos1 exports are discarded in both VS and MS.""" - vs = make_shader(_vs_header_asm("exp pos1 v10, off, off, off done"), name="vs_no_osg1_pos1") - vs_spv = vs.translate() - vs.validate(vs_spv) - assert "OpCapability ClipDistance" not in vs_spv - assert "BuiltIn ClipDistance" not in vs_spv - vs_meta = rdna2spirv.shader_meta(rdna2spirv.translate.last_gen, vs_spv) - assert "clip_distance_count" not in vs_meta - assert "shaderClipDistance" not in vs_meta["features"] - assert 1 not in vs_meta.get("outputs", []) - - ms = make_shader(_ms_header_asm("exp pos1 v10, off, off, off done"), name="ms_no_osg1_pos1", - dxbc=make_dxbc([mesh_psv0_chunk()])) - ms_spv = ms.translate() - ms.validate(ms_spv, KNOWN_VAL_ISSUES.get("ms_tri")) - assert "OpCapability ClipDistance" not in ms_spv - assert "BuiltIn ClipDistance" not in ms_spv - assert "%ms_out_pos" in ms_spv and "%ms_vtx_blk" not in ms_spv - ms_meta = rdna2spirv.shader_meta(rdna2spirv.translate.last_gen, ms_spv) - assert "shaderClipDistance" not in ms_meta["features"] - assert 1 not in ms_meta.get("params", []) - - -def test_ms_dummy_all_off_pos1_does_not_emit_clip(make_shader): - """An all-off dummy pos1 export in a mesh shader must not emit ClipDistance or change the output block.""" - dxbc = make_dxbc([mesh_psv0_chunk(), signature_chunk(b"OSG1", [(0, 1, 0xF), (1, 2, 0x1)])]) - shader = make_shader(_ms_header_asm("exp pos1 off, off, off, off done"), name="ms_dummy_pos1", dxbc=dxbc) - spvasm = shader.translate() - shader.validate(spvasm, KNOWN_VAL_ISSUES.get("ms_tri")) - assert "OpCapability ClipDistance" not in spvasm - assert "%ms_out_pos" in spvasm - assert "%ms_vtx_blk" not in spvasm - - -def test_ms_clip_and_cull_distances_across_pos1_pos2(make_shader): - """Mesh shader with 2 clip + 3 cull distances emits both arrays in %ms_vtx_blk and maps v10..v14.""" - dxbc = make_dxbc([mesh_psv0_chunk(), signature_chunk(b"OSG1", [(0, 1, 0xF), (1, 2, 0x3), (2, 3, 0x7)])]) - asm = _ms_header_asm("exp pos1 v10, v11, v12, v13\nexp pos2 v14, off, off, off done") - shader = make_shader(asm, name="ms_clip_cull", dxbc=dxbc) - spvasm = shader.translate() - shader.validate(spvasm, KNOWN_VAL_ISSUES.get("ms_tri")) - assert "OpCapability ClipDistance" in spvasm - assert "OpCapability CullDistance" in spvasm - assert "OpMemberDecorate %ms_vtx_blk 0 BuiltIn Position" in spvasm - assert "OpMemberDecorate %ms_vtx_blk 1 BuiltIn ClipDistance" in spvasm - assert "OpMemberDecorate %ms_vtx_blk 2 BuiltIn CullDistance" in spvasm - assert "%ms_arr_clip = OpTypeArray %float %c2" in spvasm - assert "%ms_arr_cull_d = OpTypeArray %float %c3" in spvasm - assert _vgpr_to_index_map(spvasm, "%ms_clip", "%_ptr_Function_float") == {0: 10, 1: 11} - assert _vgpr_to_index_map(spvasm, "%ms_cull_dist", "%_ptr_Function_float") == {0: 12, 1: 13, 2: 14} - meta = rdna2spirv.shader_meta(rdna2spirv.translate.last_gen, spvasm) - assert "shaderClipDistance" in meta["features"] - assert "shaderCullDistance" in meta["features"] - assert not ({1, 2} & set(meta.get("outputs", []))) - assert not ({1, 2} & set(meta.get("params", []))) - - -def test_wave64_detected_from_mask_ops_without_exec_markers(make_shader): - """#210 part 2 / SHADER-28: s_bcnt1_i32_b64 on ordinary SGPRs marks the shader wave64 (no exec_hi / saveexec).""" - shader = make_shader( - "; mattr: +wavefrontsize64,-wavefrontsize32\n" - "v_and_b32_e32 v5, 5, v0\nv_cmp_ne_u32_e64 s[20:21], 0, v5\n" - "s_bcnt1_i32_b64 s30, s[20:21]\nv_mov_b32 v1, s30\ns_endpgm\n", - name="cs_mask_detect_ci", - ) - asm = shader.translate() - shader.validate(asm) - assert rdna2spirv.translate.last_gen.wave64 - - -def test_wave64_bfm64_and_half_cmp_emit_wave_ops(make_shader): - """Wave64 s_bfm_b64 must use wave_lane() and reconstruct the 64-bit mask; 32-bit half ops must guard their half.""" - bfm = make_shader("s_mov_b64 exec, -1\ns_bfm_b64 s[6:7], 16, 8\ns_bcnt1_i32_b64 s8, s[6:7]\ns_endpgm\n", - name="cs_bfm64_ci") - asm_bfm = bfm.translate() - bfm.validate(asm_bfm) - assert "OpGroupNonUniformBitwiseOr" in asm_bfm - assert "OpLoad %v3uint %local_id" in asm_bfm and "OpLoad %uint %sg_lane" not in asm_bfm - - hcmp = make_shader("s_mov_b32 exec_lo, 0\ns_mov_b32 exec_hi, 0xffff\ns_mov_b64 s[6:7], exec\n" - "s_cmp_eq_u32 s6, 0\ns_cmp_lg_u32 s7, 0\ns_endpgm\n", name="cs_halfcmp_ci") - asm_hcmp = hcmp.translate() - hcmp.validate(asm_hcmp) - # Low-half s_cmp_eq_u32: lane < 32 (%c20) guards OpSelect(..., %true) feeding OpGroupNonUniformAll. - assert re.search( - r"(%t\d+) = OpULessThan %bool %t\d+ %c20\n\s*" - r"(%t\d+) = OpSelect %bool \1 %t\d+ %true\n\s*" - r"%t\d+ = OpGroupNonUniformAll %bool %c3 \2", - asm_hcmp, - ), "low-half s_cmp_eq_u32 did not guard OpGroupNonUniformAll with lane < 32" - # High-half s_cmp_lg_u32: lane >= 32 (%c20) guards OpLogicalAnd feeding OpGroupNonUniformAny. - assert re.search( - r"(%t\d+) = OpUGreaterThanEqual %bool %t\d+ %c20\n\s*" - r"(%t\d+) = OpLogicalAnd %bool \1 %t\d+\n\s*" - r"%t\d+ = OpGroupNonUniformAny %bool %c3 \2", - asm_hcmp, - ), "high-half s_cmp_lg_u32 did not guard OpGroupNonUniformAny with lane >= 32" - - # Copying vcc_lo / vcc_hi to a 32-bit SGPR preserves half identity for wave64 s_bcnt1_i32_b32. - vcc_half = make_shader( - "s_mov_b64 exec, -1\nv_cmp_gt_u32_e32 vcc_lo, 16, v0\n" - "s_mov_b32 s6, vcc_lo\ns_bcnt1_i32_b32 s8, s6\n" - "s_mov_b32 s7, vcc_hi\ns_bcnt1_i32_b32 s9, s7\ns_endpgm\n", - name="cs_vcchalf_ci", - ) - asm_vcc = vcc_half.translate() - vcc_half.validate(asm_vcc) - assert asm_vcc.count("OpBitCount %uint %c0") == 2 - - -def test_wave64_bpermute_reads_zero_from_lanes_that_are_not_running(make_shader): - """Native wave64 ds_bpermute: a source lane missing from a partial wave must read 0, not an undefined shuffle.""" - shader = make_shader("s_mov_b64 exec, -1\nv_lshlrev_b32_e32 v1, 2, v0\nds_bpermute_b32 v2, v1, v0\n" - "s_waitcnt lgkmcnt(0)\ns_endpgm\n", name="cs_bperm64_ci") - asm = shader.translate() - shader.validate(asm) - assert rdna2spirv.translate.last_gen.wave64 - assert re.search( - r"(%t\d+) = OpGroupNonUniformBallot %v4uint_bal %c3 %true\n\s*" - r"(%t\d+) = OpGroupNonUniformBallotBitExtract %bool %c3 \1 (%t\d+)\n\s*" - r"(%t\d+) = OpSelect %uint \2 \3 %t\d+\n\s*" - r"(%t\d+) = OpGroupNonUniformShuffle %uint %c3 %t\d+ \4\n\s*" - r"(%t\d+) = OpSelect %uint \2 %cffffffff %c0\n\s*" - r"%t\d+ = OpBitwiseAnd %uint \5 \6\n", - asm, - ), "wave64 ds_bpermute did not keep the shuffle only where the source lane is running" - - - -def test_wave32_bpermute_zeroes_inactive_and_missing_source_lanes(make_shader): - """Wave32 ds_bpermute (RDNA ISA 10.4.4): the source value is 0 where the source lane is off in EXEC, and the - shuffle result is kept only where the source lane is running, as in the wave64 path.""" - shader = make_shader( - "v_cmp_ne_u32_e32 vcc_lo, 0, v0\ns_and_saveexec_b32 s4, vcc_lo\n" - "v_lshlrev_b32_e32 v1, 2, v0\nds_bpermute_b32 v2, v1, v0\ns_waitcnt lgkmcnt(0)\ns_endpgm\n", - name="cs_bperm32_ci", - ) - asm = shader.translate() - shader.validate(asm) - assert not rdna2spirv.translate.last_gen.wave64 - shuffle = re.search( - r"(%t\d+) = OpSelect %uint (%t\d+) %t\d+ %c0\n\s*" - r"(%t\d+) = OpGroupNonUniformBallot %v4uint_bal %c3 %true\n\s*" - r"(%t\d+) = OpGroupNonUniformBallotBitExtract %bool %c3 \3 (%t\d+)\n\s*" - r"(%t\d+) = OpSelect %uint \4 \5 %t\d+\n\s*" - r"(%t\d+) = OpGroupNonUniformShuffle %uint %c3 \1 \6\n\s*" - r"(%t\d+) = OpSelect %uint \4 %cffffffff %c0\n\s*" - r"(?P%t\d+) = OpBitwiseAnd %uint \7 \8\n", - asm, - ) - assert shuffle, "wave32 ds_bpermute must mask inactive and missing source lanes" - active_id = shuffle.group(2) - assert (f"{active_id} = OpLoad %bool %active" in asm or f"OpStore %active {active_id}" in asm), \ - "source mask must read the active lane predicate" - assert f"OpBitwiseAnd %uint {shuffle['result']} " in asm, "the destination write must also mask the shuffle" - -WQM_MASK = "s_mov_b64 exec, -1\nv_cmp_gt_u32_e32 vcc_lo, 16, v0\ns_wqm_b64 s[6:7], vcc\ns_bcnt1_i32_b64 s8, s[6:7]\ns_endpgm\n" -WQM_DATA = "s_mov_b32 s20, 0x00800010\ns_mov_b32 s21, 1\ns_wqm_b64 s[22:23], s[20:21]\ns_add_u32 s24, s22, s23\ns_endpgm\n" - - -def test_wqm_on_a_lane_mask_gathers_the_quad_and_votes_scc(make_shader, monkeypatch): - """s_wqm on a lane mask ORs the lane's bit with its quad's (two OpGroupNonUniformQuadSwap, horizontal then - vertical) and SCC is the wave-wide any. Emulated, the four lanes of the quad come through %x_buf instead.""" - shader = make_shader(WQM_MASK, name="cs_wqm_mask_ci") - asm = shader.translate() - shader.validate(asm) - assert "OpCapability GroupNonUniformQuad" in asm - assert asm.count("OpGroupNonUniformQuadSwap %uint %c3") == 2 - assert re.search(r"OpGroupNonUniformQuadSwap %uint %c3 %t\d+ %c0\n(?:.*\n)*?.*OpGroupNonUniformQuadSwap %uint %c3 %t\d+ %c1\n", asm) - assert "OpGroupNonUniformAny" in asm # SCC: any bit of the result in the wave - monkeypatch.setattr(rdna2spirv, "WAVE64_EMULATE", True) - emulated = shader.translate() - shader.validate(emulated) - assert "OpGroupNonUniform" not in emulated and "GroupNonUniformQuad" not in emulated - assert "%x_buf" in emulated - - -def test_wqm_on_data_is_a_bit_operation(make_shader): - """A register that is not a lane mask is data: per 32-bit word (x | x>>1 | x>>2 | x>>3) & 0x11111111, times 15.""" - shader = make_shader(WQM_DATA, name="cs_wqm_data_ci") - asm = shader.translate() - shader.validate(asm) - assert "OpGroupNonUniform" not in asm - for k in (1, 2, 3): # three shifts per word, two words (s_wqm_b64) - assert len(re.findall(rf"OpShiftRightLogical %uint %t\d+ %c{k}\n", asm)) == 2 - assert len(re.findall(r"OpBitwiseAnd %uint %t\d+ %c11111111\n", asm)) == 2 - assert len(re.findall(r"OpIMul %uint %t\d+ %cf\n", asm)) == 2 - assert re.search(r"OpBitwiseOr %uint %t\d+ %t\d+\n(?:.*\n)*?.*OpStore %scc", asm) # SCC = low | high != 0 - - -def test_wqm_without_quad_operations_outside_fragment_and_compute(make_shader): - """Quad operations are only guaranteed in fragment and compute shaders: a vertex shader shuffles from the four - lanes of the quad instead.""" - shader = make_shader("v_cmp_gt_u32_e32 vcc_lo, 1, v0\ns_wqm_b32 s8, vcc_lo\nv_cndmask_b32_e64 v6, 0, 1, s8\n" - "exp pos0 v6, v6, v6, v6 done\ns_endpgm\n", name="vs_wqm_ci") - asm = shader.translate() - shader.validate(asm) - assert "QuadSwap" not in asm and "GroupNonUniformQuad" not in asm - assert asm.count("OpGroupNonUniformShuffle") == 4 - - -def test_wave64_wqm_b32_changes_and_votes_only_its_half(make_shader): - """s_wqm_b32 exec_hi in wave64 writes the lanes 32-63 of EXEC only (exec_half_write) and SCC votes over them.""" - shader = make_shader("s_mov_b32 exec_hi, 0x102\ns_wqm_b32 exec_hi, exec_hi\ns_cselect_b32 s9, 1, 0\ns_endpgm\n", - name="cs_wqm_half_ci") - asm = shader.translate() - shader.validate(asm) - assert rdna2spirv.translate.last_gen.wave64 - assert re.search(r"(%t\d+) = OpUGreaterThanEqual %bool %t\d+ %c20\n(?:.*\n)*?.*OpLogicalAnd %bool \1 %t\d+\n" - r"(?:.*\n)*?.*OpGroupNonUniformAny", asm) - - -def test_wqm_in_a_pixel_shader_uses_the_fragment_quad(make_shader): - shader = make_shader("v_cmp_gt_u32_e32 vcc_lo, 1, v0\ns_wqm_b32 s8, vcc_lo\nv_cndmask_b32_e64 v6, 0, 1, s8\n" - "exp mrt0 v6, v6, v6, v6 done vm\ns_endpgm\n", name="ps_wqm_ci") - asm = shader.translate() - shader.validate(asm) - assert asm.count("OpGroupNonUniformQuadSwap") == 2 and "OpCapability GroupNonUniformQuad" in asm - - -FLOAT_CONTROLS_CS = """\ -v_mov_b32_e32 v1, 0x80000000 -v_mul_f32_e32 v2, v1, v1 -v_lshlrev_b32_e32 v3, 2, v0 -buffer_store_dword v2, v3, s[0:3], 0 offen -s_endpgm -""" - - -@pytest.mark.parametrize("stage", ["ps", "cs"]) -def test_float_controls_declared(stage, make_shader): - """Every module declares SignedZeroInfNanPreserve for 32-bit floats, so the driver keeps NaN, inf and -0 as - RDNA2 computes them (AMD folded x != x to false and turned -0 products into +0 without it; see - runtime/test/shaders/cs_signed_zero_nan.asm), and DenormPreserve for 16-bit floats, so it keeps an f16 denormal - instead of flushing it (NVIDIA read the 0x0040 of ps_sdwa_f16_const's `src0_sel:BYTE_1` as +0 without it, - SHADER-526). Its index entry names the device properties the runtime checks.""" - body = FLOAT_CONTROLS_CS if stage == "cs" else program("v_mul_f32 v1, v0, v0") - shader = make_shader(body, name=f"{stage}_float_controls") - spv = shader.translate() - shader.validate(spv) - assert "OpCapability SignedZeroInfNanPreserve" in spv - assert "OpExecutionMode %main SignedZeroInfNanPreserve 32" in spv - assert "OpCapability DenormPreserve" in spv - assert "OpExecutionMode %main DenormPreserve 16" in spv - meta = rdna2spirv.shader_meta(rdna2spirv.translate.last_gen, spv) - assert meta["float_controls"] == ["shaderSignedZeroInfNanPreserveFloat32", "shaderDenormPreserveFloat16"] - - -def test_no_float_controls_leaves_them_out(make_shader, monkeypatch): - """--no-float-controls (FLOAT_CONTROLS = False), for a driver without the properties: no capability, no - execution mode, no index entry, and the module still validates.""" - monkeypatch.setattr(rdna2spirv, "FLOAT_CONTROLS", False) - shader = make_shader(FLOAT_CONTROLS_CS, name="cs_no_float_controls") - spv = shader.translate() - shader.validate(spv) - assert "SignedZeroInfNanPreserve" not in spv - assert "DenormPreserve" not in spv - meta = rdna2spirv.shader_meta(rdna2spirv.translate.last_gen, spv) - assert "float_controls" not in meta - - -EMULATE_SAMPLES = [p for p in SAMPLES if os.path.basename(p).startswith(("cs_", "ms_"))] - - -@pytest.mark.parametrize("path", EMULATE_SAMPLES, ids=[os.path.basename(p) for p in EMULATE_SAMPLES]) -def test_wave64_emulate_uses_no_subgroup_ops(path, make_shader, monkeypatch): - """--wave64-emulate: a wave64 compute or mesh shader validates and uses no subgroup operation (everything - cross-lane goes through %x_buf); a wave32 one comes out exactly as without the flag.""" - stem = os.path.splitext(os.path.basename(path))[0] - if stem.startswith("ms_") and stem not in SAMPLE_DXBC: - pytest.skip(f"no synthetic PSV0 for {stem} in conftest.SAMPLE_DXBC") - with open(path, encoding="utf-8") as f: - shader = make_shader(f.read(), stem, dxbc=SAMPLE_DXBC.get(stem, EMPTY_DXBC)) - plain = shader.translate() - monkeypatch.setattr(rdna2spirv, "WAVE64_EMULATE", True) - emulated = shader.translate() - if not rdna2spirv.translate.last_gen.wave64: - assert emulated == plain - return - shader.validate(emulated, KNOWN_VAL_ISSUES.get(stem)) - assert "OpGroupNonUniform" not in emulated and "%sg_lane" not in emulated - assert "%x_buf" in emulated and emulated.count("OpControlBarrier") >= 2 - - -# SHADER-91: a native wave32 compute shader whose s_barrier isn't in a top-level block runs in barrier rounds. -BARRIER_SAMPLES = ("cs_barrier_divergent", "cs_barrier_early_end", "cs_barrier_loop") - - -@pytest.mark.parametrize("stem", BARRIER_SAMPLES) -def test_nested_barrier_runs_in_barrier_rounds(stem, make_shader): - """No OpControlBarrier is left among the blocks (the cases of the switch over %pc): s_barrier ends a segment - there. The only two are before the round loop and at its end, where the whole workgroup is.""" - with open(os.path.join(ROOT, "runtime", "test", "shaders", stem + ".asm"), encoding="utf-8") as f: - shader = make_shader(f.read(), stem) - asm = shader.translate() - shader.validate(asm) - assert rdna2spirv.translate.last_gen.control_flow == "barrier rounds" - blocks = asm[asm.index("OpSwitch %pcv"):asm.index("%sw_default = OpLabel")] - assert "OpControlBarrier" not in blocks and "OpStore %x_bar %true" in blocks - assert asm.count("OpControlBarrier") == 2 - head, tail = asm.index("OpLoopMerge %loop_exit %loop_cont"), asm.index("%loop_cont = OpLabel") - assert asm.index("OpControlBarrier") < head and asm.rindex("OpControlBarrier") > tail - assert "OpAtomicIAdd" in asm[tail - 2000:tail] and "%x_buf = OpVariable" in asm - - -def test_top_level_barrier_keeps_the_plain_translation(make_shader): - """A barrier in a block every invocation runs (the top level of the structured tree) stays one OpControlBarrier - in place: no rounds for a shader that doesn't need them.""" - shader = make_shader("v_lshlrev_b32_e32 v2, 2, v0\nds_write_b32 v2, v0\ns_waitcnt lgkmcnt(0)\ns_barrier\n" - "v_readfirstlane_b32 s5, v0\ns_cmp_lg_u32 s5, 0\ns_cbranch_scc1 2\n" # skips the 2-dword read - "ds_read_b32 v4, v2\ns_endpgm\n", "cs_barrier_top") - asm = shader.translate() - shader.validate(asm) - assert rdna2spirv.translate.last_gen.control_flow == "structured" - assert asm.count("OpControlBarrier") == 1 and "%x_bar" not in asm and "%x_buf" not in asm - - -def test_top_level_barrier_over_the_depth_bound_runs_in_barrier_rounds(make_shader, monkeypatch): - """SHADER-427 review: the barrier-rounds decision uses the same capped tree as assemble(). A top-level barrier - is uniform only while the tree is structured; once the tree nests deeper than MAX_STRUCTURED_DEPTH it is - emitted in the dispatch loop, where the barrier sits in a switch case, so the shader has to run in rounds.""" - n = 4 - chain = "".join(f"s_cmp_eq_u32 s0, {i}\ns_cbranch_scc0 {3 + 2 * (n - i - 1)}\n" for i in range(n)) - shader = make_shader("v_lshlrev_b32_e32 v2, 2, v0\nds_write_b32 v2, v0\ns_waitcnt lgkmcnt(0)\ns_barrier\n" - + chain + "v_lshlrev_b32_e32 v3, 2, v0\nds_write_b32 v3, v0\ns_endpgm\n", - "cs_barrier_top_deep") - structured = shader.translate() - shader.validate(structured) - gen = rdna2spirv.translate.last_gen - assert gen.control_flow == "structured" and not gen.bar_rounds and gen.nesting > 1 - assert structured.count("OpControlBarrier") == 1 and "%x_bar" not in structured - - monkeypatch.setattr(rdna2spirv, "MAX_STRUCTURED_DEPTH", gen.nesting - 1) - rounds = shader.translate() - shader.validate(rounds) - gen = rdna2spirv.translate.last_gen - assert gen.bar_rounds and gen.control_flow == "barrier rounds" - blocks = rounds[rounds.index("OpSwitch %pcv"):rounds.index("%sw_default = OpLabel")] - assert "OpControlBarrier" not in blocks and "OpStore %x_bar %true" in blocks - - -def test_barrier_rounds_are_wave32_compute_only(make_shader, monkeypatch): - """Native wave64 (AMD's 64-wide subgroups) keeps the barrier where s_barrier is; under --wave64-emulate the - emulated round loop already holds the only barrier.""" - with open(os.path.join(ROOT, "runtime", "test", "shaders", "cs_barrier_divergent.asm"), encoding="utf-8") as f: - src = f.read() - shader = make_shader("s_mov_b64 exec, -1\n" + src, "cs_barrier_divergent_w64") # a 64-bit EXEC write: wave64 - asm = shader.translate() - gen = rdna2spirv.translate.last_gen - assert gen.wave64 and not gen.bar_rounds and gen.control_flow == "structured" - assert asm.count("OpControlBarrier") == 2 and "%x_bar" not in asm - monkeypatch.setattr(rdna2spirv, "WAVE64_EMULATE", True) - shader.translate() - gen = rdna2spirv.translate.last_gen - # #2089: --wave64-emulate keeps structured control flow where it can (was a round loop per barrier) - assert gen.emulate and not gen.bar_rounds and gen.control_flow in ("emulated wave64 structured", - "emulated wave64 rounds") - - -# SHADER-36: image_gather4_l(_o) runs every texel of its 2x2 footprint through the S#'s CLAMP_X/CLAMP_Y. -def _gather_l(s_word0, dynamic=False, s_word1=0): - return program( - "s_mov_b32 s8, 0\ns_mov_b32 s9, 0\ns_mov_b32 s10, 0\ns_mov_b32 s11, 0\n" - "s_mov_b32 s12, 0\ns_mov_b32 s13, 0\ns_mov_b32 s14, 0\ns_mov_b32 s15, 0\n" - f"s_mov_b32 s16, {s_word0}\ns_mov_b32 s17, {s_word1}\ns_mov_b32 s18, 0\ns_mov_b32 s19, 0\n" - # A loaded word, not s16 + 0: SHADER-315 folds scalar ALU on constants, which made the sampler a literal. - + ("s_load_dword s16, s[0:1], 0x0\ns_waitcnt lgkmcnt(0)\n" if dynamic else "") - + "v_mov_b32 v10, 0.5\nv_mov_b32 v11, 0.5\nv_mov_b32 v12, 0\n" - "image_gather4_l v[0:3], v[10:12], s[8:15], s[16:19] dmask:0x1 dim:SQ_RSRC_IMG_2D") - - -def _count(text, op): - return len(re.findall(rf"= {op} ", text)) - - -def _gather_address_bit_offsets(text: str) -> list[int]: - constants = {name: int(value) for name, value in re.findall(r"(%\w+) = OpConstant %uint (\d+)", text)} - fields = re.findall(r"OpBitFieldUExtract %uint %\w+ (%\w+) (%\w+)", text) - return [constants[offset] for offset, width in fields if constants[width] == 3] - - -@pytest.mark.parametrize("mx", range(4)) -@pytest.mark.parametrize("my", range(4)) -def test_gather4_l_literal_sampler_emits_only_the_code_its_modes_need(mx, my, make_shader): - """CLAMP_X = bits [2:0], CLAMP_Y = [5:3]; 0 wrap, 1 mirror, 2 clamp, 3 mirror once. Each axis maps its two - texel coordinates: wrap = 1 OpSRem + 1 OpSLessThan (the modulo's fix-up), mirror = the same + 1 OpSLessThan - (the reflection), mirror once = 1 OpSGreaterThanEqual. No OpSMod: AMD's Windows driver gave it the dividend's - sign for a negative coordinate (Gen.gather_addr).""" - shader = make_shader(_gather_l(mx | my << 3)) - text = shader.translate() - shader.validate(text) - assert _count(text, "OpSMod") == 0 - assert _count(text, "OpSRem") == 2 * (mx in (0, 1)) + 2 * (my in (0, 1)) - assert _count(text, "OpSLessThan") == 2 * (mx in (0, 1)) + 2 * (mx == 1) + 2 * (my in (0, 1)) + 2 * (my == 1) - assert _count(text, "OpSGreaterThanEqual") == 2 * (mx == 3) + 2 * (my == 3) - assert _gather_address_bit_offsets(text) == [] # the sampler modes are literals - - -def _gather_rounded_lod(defs): - """The LOD the explicit-LOD gather rounds to a mip: the operand of the Floor whose fraction (an FSub from the same - LOD) is compared with %fhalf_g.""" - cmp, = (e for e in defs.values() if e.startswith("OpFOrdGreaterThanEqual %bool ") and e.endswith(" %fhalf_g")) - sub = defs[cmp.split()[2]].split() - assert sub[:2] == ["OpFSub", "%float"], sub - lod, floor = sub[2], sub[3] - assert defs[floor].split() == ["OpExtInst", "%float", "%glsl", "Floor", lod] - return lod - - -def test_gather4_l_literal_lod_bounds_feed_mip_selection(make_shader): - shader = make_shader(_gather_l(0x12, s_word1=(192 << 12) | 64)) # [0.25, 0.75] in unsigned 4.8 - text = shader.translate() - shader.validate(text) - defs = dict(re.findall(r"^\s*(%\w+) = (.+)$", text, re.M)) - clamp = defs[_gather_rounded_lod(defs)].split() - assert clamp[:4] == ["OpExtInst", "%float", "%glsl", "FClamp"] - for limit, bits in zip(clamp[-2:], (0x3e800000, 0x3f400000)): - cast, scalar, value = defs[limit].split() - assert (cast, scalar) == ("OpBitcast", "%float") - assert defs[value] == f"OpConstant %uint {bits}" - - -def test_gather4_l_run_time_lod_bounds_clamp_without_fclamp(make_shader): - # A run-time S# here (the real game shape) must not use FClamp: LLPC 26.10.1 miscompiles it on this path and - # leaves the gather at mip 0 when MIN_LOD should raise it (#1032). FMax then FMin is the same clamp. - asm = ("s_mov_b32 s8, 0\ns_mov_b32 s9, 0\ns_mov_b32 s10, 0\ns_mov_b32 s11, 0\n" - "s_mov_b32 s12, 0\ns_mov_b32 s13, 0\ns_mov_b32 s14, 0\ns_mov_b32 s15, 0\n" - "s_load_dwordx4 s[16:19], s[0:1], 0\n" - "v_mov_b32 v10, 0.5\nv_mov_b32 v11, 0.5\nv_mov_b32 v12, 0\n" - "image_gather4_l v[0:3], v[10:12], s[8:15], s[16:19] dmask:0x1 dim:SQ_RSRC_IMG_2D") - shader = make_shader(program(asm)) - text = shader.translate() - shader.validate(text) - defs = dict(re.findall(r"^\s*(%\w+) = (.+)$", text, re.M)) - # The LOD rounds to the nearest mip, ties up (SHADER-152); the lod it rounds is the clamp's FMin. - clamp = defs[_gather_rounded_lod(defs)].split() - assert clamp[:4] == ["OpExtInst", "%float", "%glsl", "FMin"] - assert "FMax" in text - assert "FClamp" not in text - - -def test_gather4_l_run_time_sampler_selects_the_mode_from_the_sgpr(make_shader): - shader = make_shader(_gather_l(0x12, dynamic=True)) - text = shader.translate() - shader.validate(text) - assert _gather_address_bit_offsets(text) == [0, 3] # CLAMP_X and CLAMP_Y - # Four coordinates, each through all four modes: wrap and mirror an OpSRem and a fix-up OpSLessThan each (8), - # mirror one more OpSLessThan (4), SHADER-348 border-mode range tests two OpSLessThan each (8), mirror once an - # OpSGreaterThanEqual (4). - assert _count(text, "OpSMod") == 0 and _count(text, "OpSRem") == 8 - assert _count(text, "OpSLessThan") == 20 and _count(text, "OpSGreaterThanEqual") == 4 - - -@pytest.mark.parametrize("word0", [4, 0x28, 0x8000]) -def test_gather4_l_literal_half_border_or_unnormalized_sampler_is_unsupported(word0, make_shader): - with pytest.raises(rdna2spirv.Unsupported): - make_shader(_gather_l(word0)).translate() - - -# SHADER-348: modes 6 (clamp border) and 7 (mirror once border) give a tap outside the image the border colour's -# channel, BORDER_COLOR_TYPE = S# word 3 [31:30] (0 transparent black, 1 opaque black, 2 opaque white, 3 table). -def _gather_l_border(word0, word3, dynamic=False, dmask=1): - return program( - "s_mov_b32 s8, 0\ns_mov_b32 s9, 0\ns_mov_b32 s10, 0\ns_mov_b32 s11, 0\n" - "s_mov_b32 s12, 0\ns_mov_b32 s13, 0\ns_mov_b32 s14, 0\ns_mov_b32 s15, 0\n" - f"s_mov_b32 s16, {word0}\ns_mov_b32 s17, 0\ns_mov_b32 s18, 0\ns_mov_b32 s19, {word3}\n" - + ("s_load_dword s16, s[0:1], 0x0\ns_load_dword s19, s[0:1], 0x4\ns_waitcnt lgkmcnt(0)\n" - if dynamic else "") - + "v_mov_b32 v10, 0.5\nv_mov_b32 v11, 0.5\nv_mov_b32 v12, 0\n" - f"image_gather4_l v[0:3], v[10:12], s[8:15], s[16:19] dmask:{dmask:#x} dim:SQ_RSRC_IMG_2D") - - -def _float_bits(text, name): - defs = dict(re.findall(r"^\s*(%\w+) = (.+)$", text, re.M)) - expr = defs[name].split() - if expr[:2] == ["OpBitcast", "%float"]: - expr = defs[expr[2]].split() - assert expr[:2] in (["OpConstant", "%uint"], ["OpConstant", "%float"]), expr - return int(expr[2]) if expr[1] == "%uint" else struct.unpack("= 4 - - -# SHADER-152: the explicit-LOD gather's mip is the nearest one, ties up, like the native gather on Radeon -# (LOD 0.5 with bounds [0,1] picked mip 1); the old RoundEven picked mip 0 there. It is computed as -# floor(LOD) + (fraction >= 0.5), exact in binary32, not Floor(LOD + 0.5), whose sum rounds 0x3effffff up to 1.0. -def _gather_l_at_lod(lod, word1=0x100000): - return program( - "s_mov_b32 s8, 0\ns_mov_b32 s9, 0\ns_mov_b32 s10, 0\ns_mov_b32 s11, 0\n" - "s_mov_b32 s12, 0\ns_mov_b32 s13, 0\ns_mov_b32 s14, 0\ns_mov_b32 s15, 0\n" - # S# word 1: by default MIN_LOD 0, MAX_LOD 1.0 (unsigned 4.8), so the clamp below is [0, 1]. - f"s_mov_b32 s16, 0\ns_mov_b32 s17, {word1:#x}\ns_mov_b32 s18, 0\ns_mov_b32 s19, 0\n" - f"v_mov_b32 v10, 0.5\nv_mov_b32 v11, 0.5\nv_mov_b32 v12, {lod}\n" - "image_gather4_l v[0:3], v[10:12], s[8:15], s[16:19] dmask:0x1 dim:SQ_RSRC_IMG_2D") - - -def test_gather4_l_rounds_the_lod_tie_up(make_shader): - """The LOD is clamped to the S# bounds first, then floored, and its fraction compared with 0.5; the result is - not rounded to even (which would send a 0.5 tie to mip 0), and no +0.5 is added in binary32.""" - shader = make_shader(_gather_l_at_lod(0.5)) - text = shader.translate() - shader.validate(text) - defs = dict(re.findall(r"^\s*(%\w+) = (.+)$", text, re.M)) - clamp = re.search(r"(%\w+) = OpExtInst %float %glsl FClamp (%\w+) (%\w+) (%\w+)", text) - assert clamp, text - assert _gather_rounded_lod(defs) == clamp.group(1) # the clamped LOD, not the raw one - assert "= OpExtInst %float %glsl RoundEven" not in text - assert not re.search(r"= OpFAdd %float %\w+ %fhalf_g", text), text - - -def _f32(x): - return struct.unpack("= 1 << 31 else v - if op == "OpBitcast": - v = ev(args[0]) - if e[1] == "%float": - return _f32_bits(v & 0xFFFFFFFF) - return v if e[1] == "%int" else v & 0xFFFFFFFF - if op == "OpImageQueryLevels": - return levels - if op == "OpExtInst": - fn, a = args[1], [ev(x) for x in args[2:]] - out = {"Floor": lambda: float(math.floor(a[0])), "FClamp": lambda: min(max(a[0], a[1]), a[2]), - "FMax": lambda: max(a), "FMin": lambda: min(a), "SMax": lambda: max(a), "SMin": lambda: min(a), - "SClamp": lambda: min(max(a[0], a[1]), a[2])}[fn]() - return _f32(out) if isinstance(out, float) else out - a = [ev(x) for x in args] - return {"OpFAdd": lambda: _f32(a[0] + a[1]), "OpFSub": lambda: _f32(a[0] - a[1]), - "OpIAdd": lambda: a[0] + a[1], "OpISub": lambda: a[0] - a[1], - "OpConvertFToS": lambda: int(a[0]), "OpFOrdGreaterThanEqual": lambda: a[0] >= a[1], - "OpSelect": lambda: a[1] if a[0] else a[2]}[op]() - - level, = re.findall(r"= OpImageQuerySizeLod %v2int %\w+ (%\w+)$", text, re.M) - return ev(level) - - -@pytest.mark.parametrize("word1, lod, mip", [ - (0x100000, _f32_bits(0x3effffff), 0), # just below 0.5: Floor(lod + 0.5) rounded the sum to 1.0 and gave mip 1 - (0x100000, 0.5, 1), (0x100000, _f32_bits(0x3f000001), 1), (0x100000, 0.25, 0), (0x100000, 0.75, 1), - (0x100000, -1.0, 0), (0x100000, 2.0, 1), # clamped to the S# bounds [0, 1] first - (0xfff000, _f32_bits(0x3fbfffff), 1), (0xfff000, 1.5, 2), (0xfff000, 2.5, 3), - (0xfff000, _f32_bits(0x401fffff), 2), (0xfff000, 9.0, 3), # the last clamped to levels - 1 -]) -def test_gather4_l_mip_is_the_nearest_level_in_binary32(word1, lod, mip, make_shader): - shader = make_shader(_gather_l_at_lod(0, word1=word1)) - text = shader.translate() - shader.validate(text) - assert _translated_gather_mip(text, lod, 4) == mip - - -def test_gather4_l_binary32_sum_rounds_just_below_half_up(): - # Negative control: the old Floor(lod + 0.5) in binary32 gives mip 1 for 0x3effffff (the sum is halfway between - # 1 - 2^-24 and 1.0 and rounds to even); computed exactly it is mip 0. - lod = _f32_bits(0x3effffff) - assert math.floor(_f32(lod + 0.5)) == 1 - assert math.floor(lod) + (lod - math.floor(lod) >= 0.5) == 0 - - -def _gather_mip(lod, levels): - """Reference for the translated sequence: clamp to [0, levels-1] after floor(lod + 0.5).""" - return min(max(math.floor(lod + 0.5), 0), levels - 1) - - -@pytest.mark.parametrize("lod, levels, mip", [ - (-2.0, 4, 0), (-1.5, 4, 0), (-0.5, 4, 0), (-0.1, 4, 0), - (0.0, 4, 0), (0.25, 4, 0), (0.499, 4, 0), - (0.5, 4, 1), (0.501, 4, 1), (0.75, 4, 1), - (1.5, 4, 2), (2.5, 4, 3), (3.5, 4, 3), (3.6, 4, 3), # the last two are clamped to levels-1 - (0.5, 2, 1), (1.5, 2, 1), (10.0, 1, 0), -]) -def test_gather_mip_rounds_ties_up_and_clamps_to_the_level_range(lod, levels, mip): - assert _gather_mip(lod, levels) == mip - - -def test_gather_mip_old_round_even_differs_only_at_ties(): - # Negative control for the rule: Python's round() is round-half-to-even, the old translator's choice. - assert (_gather_mip(0.5, 4), round(0.5)) == (1, 0) - assert (_gather_mip(2.5, 4), round(2.5)) == (3, 2) - assert (_gather_mip(1.5, 4), round(1.5)) == (2, 2) -# ---- Irreducible CFG node splitting (compute shaders) ---- - -IRREDUCIBLE_PATTERNS = { - # 2-entry SCC with s_branch + s_cbranch_scc0 (all 1-dword insns; offsets are relative dwords from next_pc) - "scc0_branch": """\ -s_mov_b32 s1, 0 -s_cmp_eq_u32 s0, 0 -s_cbranch_scc0 3 -s_add_u32 s1, s1, 1 -s_cmp_lt_u32 s1, 4 -s_cbranch_scc0 4 -s_add_u32 s1, s1, 2 -s_cmp_lt_u32 s1, 8 -s_cbranch_scc0 1 -s_branch -7 -v_mov_b32 v1, s1 -s_endpgm -""", - # 2-entry SCC with s_cbranch_scc1 - "scc1": """\ -s_mov_b32 s1, 0 -s_cmp_eq_u32 s0, 0 -s_cbranch_scc1 3 -s_add_u32 s1, s1, 1 -s_cmp_ge_u32 s1, 4 -s_cbranch_scc1 3 -s_add_u32 s1, s1, 2 -s_cmp_lt_u32 s1, 8 -s_cbranch_scc1 -6 -v_mov_b32 v1, s1 -s_endpgm -""", - # 2-entry SCC with s_cbranch_vccnz - "vccnz": """\ -s_mov_b32 s1, 0 -v_cmp_gt_u32_e32 vcc_lo, 4, v0 -s_cbranch_vccnz 3 -s_add_u32 s1, s1, 1 -v_cmp_gt_u32_e32 vcc_lo, 8, v0 -s_cbranch_vccnz 3 -s_add_u32 s1, s1, 2 -v_cmp_lt_u32_e32 vcc_lo, 2, v0 -s_cbranch_vccnz -6 -v_mov_b32 v1, s1 -s_endpgm -""", - # Nested irreducible cycle {A, B} inside an outer reducible loop headed by H (pc=2) - "nested_in_reducible": """\ -s_mov_b32 s1, 0 -s_mov_b32 s2, 0 -s_add_u32 s2, s2, 1 -s_cmp_eq_u32 s0, 0 -s_cbranch_scc0 3 -s_add_u32 s1, s1, 1 -s_cmp_eq_u32 s1, 3 -s_cbranch_scc1 3 -s_add_u32 s1, s1, 2 -s_cmp_lt_u32 s1, 6 -s_cbranch_scc1 -6 -s_cmp_lt_u32 s2, 4 -s_cbranch_scc1 -11 -v_mov_b32 v1, s1 -s_endpgm -""", -} - - -@pytest.mark.parametrize("pattern", sorted(IRREDUCIBLE_PATTERNS)) -def test_irreducible_cfg_node_splitting(pattern, make_shader, monkeypatch): - """Irreducible CFGs (2-entry SCCs and nested irreducible cycles) structure via node splitting and pass spirv-val.""" - asm = IRREDUCIBLE_PATTERNS[pattern] - shader = make_shader(asm, name=f"cs_irred_{pattern}") - - # Without node splitting, the shader genuinely falls back to the dispatch loop. - monkeypatch.setattr(rdna2spirv.cfg_structure, "split_irreducible", lambda succ, **kw: None) - spv_fallback = shader.translate() - meta_fallback = rdna2spirv.shader_meta(rdna2spirv.translate.last_gen, spv_fallback) - assert meta_fallback["control_flow"] == "dispatch loop" - assert "OpSwitch" in spv_fallback - - # With node splitting enabled, the shader becomes structured and passes spirv-val. - monkeypatch.undo() - spv_struct = shader.translate() - shader.validate(spv_struct) - meta_struct = rdna2spirv.shader_meta(rdna2spirv.translate.last_gen, spv_struct) - assert meta_struct["control_flow"] == "structured" - assert "OpLoopMerge" in spv_struct - assert "OpSwitch" not in spv_struct - - -def test_deep_structured_nesting_uses_the_dispatch_loop(make_shader, monkeypatch): - """SHADER-299: a tree nested deeper than MAX_STRUCTURED_DEPTH is emitted in the flat dispatch-loop form, which - validates at the same depth in a fraction of the time; raising the bound brings the structured form back.""" - # cfg_structure hoists tails past 16 guards deep (#1904), so a chain never structures deeper than 16; the bound is - # set below that here so the chain still exceeds it. - monkeypatch.setattr(rdna2spirv, "MAX_STRUCTURED_DEPTH", 8) - n = 24 - body = "".join(f"s_cmp_eq_u32 s0, {i}\ns_cbranch_scc0 {3 + 2 * (n - i - 1)}\n" for i in range(n)) - shader = make_shader(body + "v_mov_b32 v8, s0\nexp mrt0 v8, v8, v8, v8 done vm\ns_endpgm\n", - name="ps_nesting_bound") - asm = shader.translate() - shader.validate(asm) - gen = rdna2spirv.translate.last_gen - assert gen.nesting > rdna2spirv.MAX_STRUCTURED_DEPTH - assert gen.control_flow == "dispatch loop" and "OpSwitch %pcv" in asm - - monkeypatch.setattr(rdna2spirv, "MAX_STRUCTURED_DEPTH", gen.nesting) - structured = shader.translate() - shader.validate(structured) - assert rdna2spirv.translate.last_gen.control_flow == "structured" - assert "OpSwitch" not in structured - - # SHADER-427: 0 (--max-structured-depth 0) never falls back, whatever the depth. - monkeypatch.setattr(rdna2spirv, "MAX_STRUCTURED_DEPTH", 0) - unbounded = shader.translate() - shader.validate(unbounded) - assert rdna2spirv.translate.last_gen.control_flow == "structured" - assert rdna2spirv.translate.last_gen.nesting == gen.nesting - assert unbounded == structured - - -MASK_REUSE_HEAD = "; mattr: +wavefrontsize64,-wavefrontsize32\nv_mbcnt_lo_u32_b32 v1, -1, 0\nv_mbcnt_hi_u32_b32 v1, -1, v1\n" - - -def emulated_exchanges(make_shader, monkeypatch, body, name="cs_reuse"): - """Translate `body` (wave64 compute) with --wave64-emulate; return (SPIR-V, number of mask-word ORs). Every - whole-mask exchange ORs two words (lanes 0-31 and 32-63), so the count is two per exchange.""" - shader = make_shader(MASK_REUSE_HEAD + body + "s_endpgm\n", name) - monkeypatch.setattr(rdna2spirv, "WAVE64_EMULATE", True) - asm = shader.translate() - shader.validate(asm) - return asm, asm.count("OpAtomicOr") - - -def test_wave64_emulate_reuses_a_mask_exchange(make_shader, monkeypatch): - """The same register value (or EXEC) read as a whole mask twice in a block is exchanged once; a rewrite of the - register or of EXEC gets a new exchange.""" - cmp = "v_cmp_eq_u32_e64 s[4:5], 5, v1\n" - _, same = emulated_exchanges(make_shader, monkeypatch, cmp + "s_bcnt1_i32_b64 s6, s[4:5]\ns_bcnt1_i32_b64 s7, s[4:5]\n") - _, rewritten = emulated_exchanges( - make_shader, monkeypatch, cmp + "s_bcnt1_i32_b64 s6, s[4:5]\nv_cmp_gt_u32_e64 s[4:5], 40, v1\ns_bcnt1_i32_b64 s7, s[4:5]\n") - _, same_exec = emulated_exchanges(make_shader, monkeypatch, "s_bcnt1_i32_b64 s6, exec\ns_bcnt1_i32_b64 s7, exec\n") - _, new_exec = emulated_exchanges( - make_shader, monkeypatch, "s_bcnt1_i32_b64 s6, exec\nv_cmpx_gt_u32_e32 10, v1\ns_bcnt1_i32_b64 s7, exec\n") - _, pair = emulated_exchanges( # s4 and s5 hold the same value: one exchange serves v_mbcnt_lo(s4) and _hi(s5) - make_shader, monkeypatch, cmp + "v_mbcnt_lo_u32_b32 v3, s4, 0\nv_mbcnt_hi_u32_b32 v3, s5, v3\n") - _, half = emulated_exchanges( # s5 rewritten, s4 kept: two exchanges - make_shader, monkeypatch, - cmp + "v_mbcnt_lo_u32_b32 v3, s4, 0\nv_cmp_gt_u32_e64 s[6:7], 40, v1\ns_and_b32 s5, s5, s7\n" - "v_mbcnt_hi_u32_b32 v3, s5, v3\n") - assert (same, rewritten, same_exec, new_exec, pair, half) == (2, 4, 2, 4, 2, 4) - - -def test_mesh_s3_wave_id_emits_local_index_shift_and_bfe(make_shader): - """Mesh shader prologue initializes s3[27:24] from LocalInvocationIndex >> 6 and s_bfe_u32 extracts it.""" - path = os.path.join(ROOT, "runtime", "test", "shaders", "ms_wave_info_s3.asm") - with open(path, encoding="utf-8") as f: - shader = make_shader(f.read(), "ms_wave_info_s3", dxbc=SAMPLE_DXBC["ms_wave_info_s3"]) - asm = shader.translate() - shader.validate(asm) - assert "%wave = OpShiftRightLogical %uint %lidx %c6" in asm - assert "%mwi = OpShiftLeftLogical %uint %wave %c18" in asm - assert "OpStore %s3p %mwi" in asm - assert "OpBitFieldUExtract %uint" in asm - - -PK_F16_REPRO_513 = """\ -; mattr: +wavefrontsize64,-wavefrontsize32 -v_mov_b32_e32 v27, 0xbdd53e00 -v_mov_b32_e32 v32, 0x3d3d32a5 -v_and_b32_e32 v7, 7, v0 -v_lshlrev_b32_e32 v7, 7, v7 -v_or_b32_e32 v20, 0x3c00, v7 -v_pk_add_f16 v31, v32, v20 op_sel:[0,0] op_sel_hi:[0,0] -v_pk_mul_f16 v34, v27, v31 op_sel:[0,0] op_sel_hi:[0,0] -v_lshlrev_b32_e32 v1, 2, v0 -buffer_store_dword v34, v1, s[0:3], 0 offen -v_add_nc_u32_e32 v2, 256, v1 -buffer_store_dword v31, v2, s[0:3], 0 offen -s_endpgm -""" - - -@pytest.mark.parametrize("emulate", [False, True], ids=["wave64", "wave64-emulate"]) -def test_pk_f16_int_pack_repro_513(emulate, make_shader, monkeypatch): - """SHADER-70 (#513): v_pk_*_f16 packs with integer IEEE-754 RTE instead of PackHalf2x16 so drivers cannot fold - UnpackHalf2x16(PackHalf2x16(x)) back to unrounded f32, and produces exact RTE bits on the #513 repro.""" - import sys - - semantic_dir = os.path.join(ROOT, "tests", "semantic") - if semantic_dir not in sys.path: - sys.path.insert(0, semantic_dir) - import spirv_mini_interp - - shader = make_shader(PK_F16_REPRO_513, name="cs_pk_f16_repro_513") - monkeypatch.setattr(rdna2spirv, "WAVE64_EMULATE", emulate) - spv = shader.translate() - shader.validate(spv) - assert "PackHalf2x16" not in spv - - sg_size = 32 if emulate else 64 - mem = spirv_mini_interp.run_workgroup( - spv, 64, sg_size, - inputs_for=lambda i: {"%wg_id": (0, 0, 0), "%local_id": (i, 0, 0), "%sg_lane": i % sg_size}, - push_constants=[0, 0, 0xFFFFFFFF, 0x31016FAC] + [0] * 28, - memory={}, - ) - assert [mem[256 + 4 * i] for i in range(3)] == [0x3CD53CD5, 0x3D553D55, 0x3DD53DD5] - assert [mem[4 * i] for i in range(3)] == [0x3F403F40, 0x40004000, 0x40604060] - - -@pytest.mark.parametrize("op_asm", [ - "v_pk_add_f16 v3, v1, v2", - "v_pk_mul_f16 v3, v1, v2", - "v_pk_max_f16 v3, v1, v2", - "v_pk_min_f16 v3, v1, v2", - "v_pk_fma_f16 v3, v1, v2, v4", - "v_add_f16_e64 v3, v1, v2", -]) -def test_pk_and_scalar_f16_ops_emit_no_packhalf2x16(op_asm, make_shader): - """All v_pk_*_f16 instructions and scalar f16_out ops validate and avoid GLSL PackHalf2x16.""" - body = ( - "v_mov_b32 v1, 0x3c003800\n" - "v_mov_b32 v2, 0x40003c00\n" - "v_mov_b32 v3, 0x00000000\n" - "v_mov_b32 v4, 0x38003400\n" - f"{op_asm}\n" - "v_mov_b32 v0, v3" - ) - shader = make_shader(program(body)) - spv = shader.translate() - shader.validate(spv) - assert "PackHalf2x16" not in spv - - -@pytest.mark.parametrize("body", [ - "buffer_load_format_d16_xyzw v[2:3], v1, s[0:3], 0 offen\ns_waitcnt vmcnt(0)\nexp mrt0 v2, v3, v2, v3 done vm", - "v_mov_b32 v2, 1.0\nv_mov_b32 v3, 0.5\nv_mov_b32 v4, 0.25\nv_mov_b32 v5, 2.0\n" - "buffer_store_format_xyzw v[2:5], v1, s[0:3], 0 offen\nexp mrt0 v2, v3, v4, v5 done vm", -], ids=["d16-load", "store"]) -def test_buffer_format_f16_narrowing_avoids_packhalf2x16(make_shader, body): - """The f16 of a d16 typed buffer load, and of an f16 format a typed buffer store writes, narrow with integer RTE - like the d16 image results (#489): PackHalf2x16 rounds toward zero on AMD drivers.""" - shader = make_shader("s_mov_b32 s0, 0x1000\ns_mov_b32 s1, 0\ns_mov_b32 s2, 0x100\ns_mov_b32 s3, 0x31001fac\n" - "v_mov_b32 v1, 0\n" + body + "\ns_endpgm\n", "ps_buf_f16") - spv = shader.translate() - shader.validate(spv) - assert "PackHalf2x16" not in spv - - -def test_repeated_tbuffer_loads_share_normalization(make_shader): - """A packed fixed format with 10- and 2-bit fields needs two exact quotients, regardless of load count.""" - load = "tbuffer_load_format_xyzw v[4:7], v0, s[0:3], 0 format:[BUF_FMT_2_10_10_10_UNORM] offen" - shader = make_shader((load + "\ns_waitcnt vmcnt(0)\n") * 8 + "exp mrt0 v4, v5, v6, v7 done vm\ns_endpgm\n", - "ps_repeated_tbuffer") - spv = shader.translate() - shader.validate(spv) - assert spv.count("FindUMsb") == 2 - - -def test_array_resinfo_queries_width_height_layers_and_mip_count(make_shader): - shader = make_shader( - "v_mov_b32_e32 v1, 1\n" - "image_get_resinfo v[4:7], v1, s[8:15] dmask:0xf dim:SQ_RSRC_IMG_2D_ARRAY\n" - "s_waitcnt vmcnt(0)\nexp mrt0 v4, v5, v6, v7 done vm\ns_endpgm\n", - name="ps_array_resinfo", - ) - asm = shader.translate() - shader.validate(asm) - assert "OpDecorate %images_arr Binding 3" in asm - size = re.search(r"(%\w+) = OpImageQuerySizeLod %v3int (%\w+) %\w+", asm) - assert size and f"OpImageQueryLevels %int {size[2]}" in asm - for axis in range(3): - assert f"OpCompositeExtract %int {size[1]} {axis}" in asm - - -class _ResinfoStub: - """Just enough of the generator for Gen.resinfo_words; the lines are evaluated by _eval_resinfo.""" - def __init__(self): - self.n, self.lines = 0, [] - - def tmp(self): - self.n += 1 - return f"%t{self.n}" - - def cu(self, v): - return f"%c{v & 0xFFFFFFFF:x}" - - def emit(self, s): - self.lines.append(s) - - def as_int(self, u): - i = self.tmp() - self.emit(f"{i} = OpBitcast %int {u}") - return i - - -def _eval_resinfo(lines, view, level, word3): - """view: (width, height, layers, levels) of the Vulkan view, which starts at the T#'s BASE_LEVEL. Values are - Python ints (uint words); OpImageQuerySizeLod refuses a level the view doesn't have, as Vulkan leaves it undefined.""" - width, height, layers, levels = view - env = {"%img": None, "%level": level, "%word3": word3} - - def val(x): - return int(x[2:], 16) if x.startswith("%c") else env[x] - for line in lines: - dst, _, op, _type, *args = line.split() - if op == "OpImageQueryLevels": - env[dst] = levels - elif op == "OpImageQuerySizeLod": - lod = val(args[1]) - assert 0 <= lod < levels, f"OpImageQuerySizeLod at level {lod} of a {levels}-level view" - env[dst] = (max(1, width >> lod), max(1, height >> lod), layers) - elif op == "OpCompositeExtract": - env[dst] = env[args[0]][int(args[1])] - elif op == "OpExtInst": - assert args[1] == "UMax" - env[dst] = max(val(args[2]), val(args[3])) - elif op == "OpBitFieldUExtract": - env[dst] = (val(args[0]) >> val(args[1])) & ((1 << val(args[2])) - 1) - else: - a = [val(x) for x in args] - env[dst] = {"OpBitcast": lambda: a[0], "OpULessThan": lambda: a[0] < a[1], - "OpSelect": lambda: a[1] if a[0] else a[2], "OpIAdd": lambda: (a[0] + a[1]) & 0xFFFFFFFF, - "OpShiftRightLogical": lambda: a[0] >> a[1] if a[1] < 32 else 0}[op]() - return env - - -@pytest.mark.parametrize("array", [False, True]) -def test_resinfo_words_follow_rdna2(array): - """SHADER-388 (tools/image_query_probe.py on gfx1036): a 2D depth word is 0; a 2D array's layer count is - minified from BASE_LEVEL; past the last level width, height and depth are 0 and the level count stays; a level - with bit 31 set is past the last level too (the address VGPR is unsigned).""" - cases = { # (T# full size w, h, layers, BASE_LEVEL, LAST_LEVEL, level) -> words, as measured - (16, 4, 1, 0, 4, 0): [16, 4, 0, 5], (16, 4, 1, 0, 4, 3): [2, 1, 0, 5], (16, 4, 1, 0, 4, 5): [0, 0, 0, 5], - (16, 4, 1, 1, 4, 0): [8, 2, 0, 4], (16, 4, 1, 0, 4, 0x80000000): [0, 0, 0, 5], - } if not array else { - (256, 256, 6, 0, 8, 1): [128, 128, 3, 9], (256, 256, 7, 0, 8, 2): [64, 64, 1, 9], - (256, 256, 100, 1, 8, 3): [16, 16, 6, 8], (256, 256, 100, 0, 8, 0): [256, 256, 100, 9], - (16, 4, 6, 0, 2, 3): [0, 0, 0, 3], (16, 4, 6, 0, 2, 9): [0, 0, 0, 3], - } - for (w, h, layers, base, last, level), want in cases.items(): - stub = _ResinfoStub() - ids = rdna2spirv.Gen.resinfo_words(stub, "%img", "%level", array, "%word3") - view = (max(1, w >> base), max(1, h >> base), layers, last - base + 1) - env = _eval_resinfo(stub.lines, view, level, base << 12 | last << 16 | (10 if array else 9) << 28) - assert [env[i] & 0xFFFFFFFF for i in ids] == want, (w, h, layers, base, last, level) - - -def test_image_sample_d16_avoids_packhalf2x16(make_shader): - """d16 image_sample packs f32->f16 via integer ops (no PackHalf2x16) and pass spirv-val.""" - sample_asm = ( - "s_load_dwordx8 s[8:15], s[0:1], 0x0\ns_waitcnt lgkmcnt(0)\n" - "s_mov_b32 s16, 0x92\ns_mov_b32 s17, 0\ns_mov_b32 s18, 0\ns_mov_b32 s19, 0\n" - "image_sample v[4:5], v[0:1], s[8:15], s[16:19] dmask:0xf dim:SQ_RSRC_IMG_2D d16\n" - "s_waitcnt vmcnt(0)\nexp mrt0 v4, v5, v4, v5 done vm\ns_endpgm\n" - ) - sh1 = make_shader(sample_asm, name="ps_d16_sample_ci") - asm1 = sh1.translate() - sh1.validate(asm1) - assert "PackHalf2x16" not in asm1 - assert "OpBitwiseOr %uint" in asm1 and "OpSelect %uint" in asm1 - - -@pytest.mark.parametrize("suffix,last_addr", [("lz", 1), ("l", 2), ("l_o", 3)]) -def test_gather_d16_avoids_packhalf2x16(make_shader, suffix, last_addr): - gather_asm = ( - "s_load_dwordx8 s[8:15], s[0:1], 0x0\ns_waitcnt lgkmcnt(0)\n" - "s_mov_b32 s16, 0x92\ns_mov_b32 s17, 0\ns_mov_b32 s18, 0\ns_mov_b32 s19, 0\n" - f"image_gather4_{suffix} v[4:5], v[0:{last_addr}], s[8:15], s[16:19] dmask:0x1 dim:SQ_RSRC_IMG_2D d16\n" - "s_waitcnt vmcnt(0)\nexp mrt0 v4, v5, v4, v5 done vm\ns_endpgm\n" - ) - sh2 = make_shader(gather_asm, name=f"ps_d16_gather_{suffix}_ci") - asm2 = sh2.translate() - sh2.validate(asm2) - assert "PackHalf2x16" not in asm2 - assert "OpBitwiseOr %uint" in asm2 and "OpSelect %uint" in asm2 - for ty in ("%v4float", "%v4uint_st", "%v4int_st"): - assert asm2.count(f"OpImageFetch {ty} ") == (0 if suffix == "lz" else 4) - - -def _load_mini_interp(): - import sys - semantic_dir = os.path.join(ROOT, "tests", "semantic") - if semantic_dir not in sys.path: - sys.path.insert(0, semantic_dir) - import spirv_mini_interp - return spirv_mini_interp - - -def test_fma_mix_decodes_fimm_as_binary16_and_preserves_other_half(make_shader): - """v_fma_mix{lo_f16,hi_f16,_f32} with op_sel_hi=1 decode fimm literals (e.g. 1.5, -2.0) as - f16 instead of f32 bit patterns, preserve the unwritten dst half, and emit no PackHalf2x16.""" - si = _load_mini_interp() - ps = ( - "; fma_mix_fimm\n" - "v_mov_b32 v1, 0x40000000\n" # f32 2.0 - "v_mov_b32 v2, 0x3e800000\n" # f32 0.25 - "v_mov_b32 v3, 0xbeef0000\n" # sentinel high half - # 1.5 (f16) * 2.0 (f32) + 0.25 (f32) = 3.25 -> f16 0x4280; high half 0xbeef preserved - "v_fma_mixlo_f16 v3, 1.5, v1, v2 op_sel:[0,0,0] op_sel_hi:[1,0,0]\n" - "v_mov_b32 v4, 0x0000cafe\n" # sentinel low half - "v_mov_b32 v5, 0x3f800000\n" # f32 1.0 - # (-2.0 (f16)) * 1.5 (f16) + 1.0 (f32) = -2.0 -> f16 0xc000; low half 0xcafe preserved - "v_fma_mixhi_f16 v4, -2.0, 1.5, v5 op_sel:[0,0,0] op_sel_hi:[1,1,0]\n" - # (-2.0 (f16)) * 1.5 (f16) + 0.25 (f32) = -2.75 -> f32 0xc0300000 - "v_fma_mix_f32 v6, -2.0, 1.5, v2 op_sel:[0,0,0] op_sel_hi:[1,1,0]\n" - "exp mrt0 v3, v4, v6, v3 done vm\n" - "s_endpgm\n" - ) - shader = make_shader(ps, name="ps_fma_mix_fimm") - spv = shader.translate() - shader.validate(spv) - - out = si.run_fragment(spv)["%out_mrt0"] - assert out[0] == 0xBEEF4280 - assert out[1] == 0xC000CAFE - assert out[2] == 0xC0300000 - assert "PackHalf2x16" not in spv - - -@pytest.mark.parametrize("op,sentinel,shift,f32_bits,expected_half", [ - # RTE tie-to-even: 1.0 + 2^-11 -> 0x3c00 (even), 1.0 + 3*2^-11 -> 0x3c02 (even) - ("v_fma_mixlo_f16", 0xBEEF0000, 0, 0x3F801000, 0x3C00), - ("v_fma_mixlo_f16", 0xBEEF0000, 0, 0x3F803000, 0x3C02), - ("v_fma_mixhi_f16", 0x0000CAFE, 16, 0x3F801000, 0x3C00), - ("v_fma_mixhi_f16", 0x0000CAFE, 16, 0x3F803000, 0x3C02), - # Subnormals & subnormal ties: 2^-15 -> 0x0200, 2^-24 -> 0x0001, 2^-25 -> 0x0000, 3*2^-25 -> 0x0002 - ("v_fma_mixlo_f16", 0x12340000, 0, 0x38000000, 0x0200), - ("v_fma_mixlo_f16", 0x12340000, 0, 0x33800000, 0x0001), - ("v_fma_mixlo_f16", 0x12340000, 0, 0x33000000, 0x0000), - ("v_fma_mixhi_f16", 0x00005678, 16, 0x33C00000, 0x0002), - # Overflow to +-Inf, -0.0, quiet NaN - ("v_fma_mixlo_f16", 0xAAAA0000, 0, 0x477FF000, 0x7C00), - ("v_fma_mixhi_f16", 0x0000BBBB, 16, 0xC77FF000, 0xFC00), - ("v_fma_mixlo_f16", 0xCCCC0000, 0, 0x80000000, 0x8000), - ("v_fma_mixhi_f16", 0x0000DDDD, 16, 0x7FC00000, 0x7E00), -]) -def test_fma_mix_f16_rte_edge_cases_and_half_preservation( - op, sentinel, shift, f32_bits, expected_half, make_shader -): - """v_fma_mixlo_f16 / v_fma_mixhi_f16 round f32 results with exact IEEE-754 binary16 RTE - (ties-to-even, subnormals, overflow, -0.0, quiet NaN) while preserving the other dst half.""" - si = _load_mini_interp() - # Fma(1.0, x, -0.0) yields x (preserving -0.0 when x == -0.0) - ps = ( - "; fma_mix_f16_rte\n" - "v_mov_b32 v1, 0x3f800000\n" - f"v_mov_b32 v2, {f32_bits:#010x}\n" - "v_mov_b32 v3, 0x80000000\n" - f"v_mov_b32 v4, {sentinel:#010x}\n" - f"{op} v4, v1, v2, v3 op_sel:[0,0,0] op_sel_hi:[0,0,0]\n" - "exp mrt0 v4, v4, v4, v4 done vm\n" - "s_endpgm\n" - ) - shader = make_shader(ps, name="ps_fma_mix_f16_rte") - spv = shader.translate() - shader.validate(spv) - assert "PackHalf2x16" not in spv - - out = si.run_fragment(spv)["%out_mrt0"] - expected_word = sentinel | (expected_half << shift) - assert out[0] == expected_word - - -@pytest.mark.parametrize("suffix,fmt_code,expected_word", [ - ("xy", 29, 0x3C013C00), # format 29 = (4, "f16", (16, 16)): lo=0x3c00, hi=0x3c01 (toward zero, SHADER-358) - ("x", 13, 0x00003C00), # format 13 = (2, "f16", (16,)): lo=0x3c00 -]) -def test_encode_format_f16_uses_f16_bits_rte(suffix, fmt_code, expected_word, make_shader): - """buffer_store_format_{x,xy} with f16 V# formats packs without PackHalf2x16, validates with spirv-val, and - stores the f16 bits RDNA2 does: rounded toward zero, as measured in SHADER-358 (was tie-to-even before it).""" - si = _load_mini_interp() - base = 0x1000 - vdata = "v2" if suffix == "x" else "v[2:3]" - sel = 0x22C if suffix == "xy" else 0x204 # XY01 for 2-comp, X001 for 1-comp (RDNA2 store COMP_SWAP) - ps = ( - "; buffer_store_format_f16_rte\n" - f"s_mov_b32 s0, {base:#x}\n" - "s_mov_b32 s1, 0\n" - "s_mov_b32 s2, 0x100\n" - f"s_mov_b32 s3, {fmt_code << 12 | 0x30000000 | sel:#x}\n" - "v_mov_b32 v1, 0\n" - "v_mov_b32 v2, 0x3f801000\n" # 1.0 + 2^-11 -> 0x3c00 (tie to even) - "v_mov_b32 v3, 0x3f803000\n" # 1.0 + 3*2^-11 -> 0x3c01 (toward zero) - f"buffer_store_format_{suffix} {vdata}, v1, s[0:3], 0 offen\n" - "s_waitcnt vmcnt(0)\n" - "exp mrt0 v2, v3, v2, v3 done vm\n" - "s_endpgm\n" - ) - shader = make_shader(ps, name=f"ps_encode_format_f16_{suffix}") - spv = shader.translate() - shader.validate(spv) - assert "PackHalf2x16" not in spv - - mem = {base: 0} - si.run_fragment(spv, memory=mem) - assert mem[base] == expected_word - - -@pytest.mark.parametrize("fmt, expected", [(56, 0x80000000), (57, 0x40810000)]) -@pytest.mark.parametrize("packed", [False, True]) -def test_normalized_buffer_store_nan(fmt, expected, packed, make_shader): - # RGBA = positive signaling NaN, negative quiet NaN, -infinity, +0.5. - # gfx1036 stored zero for both NaNs, clamped infinity and rounded 0.5 to even. - if packed: - inputs = "v_mov_b32 v4, 0xfe017c01\nv_mov_b32 v5, 0x3800fc00\n" - store = "buffer_store_format_d16_xyzw v[4:5]" - else: - inputs = ("v_mov_b32 v4, 0x7f800001\nv_mov_b32 v5, 0xffc01000\n" - "v_mov_b32 v6, 0xff800000\nv_mov_b32 v7, 0.5\n") - store = "buffer_store_format_xyzw v[4:7]" - src = ("s_mov_b32 s0, 0x1000\ns_mov_b32 s1, 0\ns_mov_b32 s2, 4\n" - f"s_mov_b32 s3, {0x31000fac | fmt << 12:#x}\n" + inputs + - f"{store}, off, s[0:3], 0\ns_waitcnt vmcnt(0)\ns_endpgm\n") - shader = make_shader(src, name="ps_store_nan") - spv = shader.translate() - shader.validate(spv) - memory = {0x1000: 0xDEADBEEF} - _load_mini_interp().run_fragment(spv, memory=memory) - assert memory[0x1000] == expected - - -@pytest.mark.parametrize("fmt", [22, 20]) # 32_FLOAT, 32_UINT -def test_unnormalized_buffer_store_keeps_nan_bits(fmt, make_shader): - src = ("s_mov_b32 s0, 0x1000\ns_mov_b32 s1, 0\ns_mov_b32 s2, 4\n" - f"s_mov_b32 s3, {0x31000fac | fmt << 12:#x}\n" - "v_mov_b32 v4, 0xffc01000\nbuffer_store_format_x v4, off, s[0:3], 0\ns_endpgm\n") - shader = make_shader(src, name="ps_raw_store_nan") - memory = {0x1000: 0} - _load_mini_interp().run_fragment(shader.translate(), memory=memory) - assert memory[0x1000] == 0xFFC01000 - - -# GFX10 32-bit integer formats by component count: UINT code, SINT code (gfx10_formats.json). -INT32_FORMATS = [(1, 20, 21), (2, 62, 63), (3, 72, 73), (4, 75, 76)] - - -@pytest.mark.parametrize("n, uint_fmt, sint_fmt", INT32_FORMATS) -def test_int32_buffer_formats_load_and_store_raw_bits(n, uint_fmt, sint_fmt, make_shader): - """SHADER-257: the 32-bit SINT typed-buffer formats (and 32_32_32_UINT) load and store each dword unchanged, as - their UINT twins do. Negative values and NaN-like patterns must survive both ways; a load's missing channels - repeat the format's own, as for every other format (SHADER-86).""" - si = _load_mini_interp() - words = [0xFFFFFFFF, 0x80000000, 0x7FC01000, 0x00000005][:n] - for fmt in (uint_fmt, sint_fmt): - desc = (f"s_mov_b32 s0, 0x1000\ns_mov_b32 s1, 0\ns_mov_b32 s2, {4 * n}\n" - f"s_mov_b32 s3, {0x31000fac | fmt << 12:#x}\n") - load = desc + ("buffer_load_format_xyzw v[4:7], off, s[0:3], 0\ns_waitcnt vmcnt(0)\n" - "exp mrt0 v4, v5, v6, v7 done vm\ns_endpgm\n") - shader = make_shader(load, name=f"ps_int32_load_{fmt}") - spv = shader.translate() - shader.validate(spv) - memory = {0x1000 + 4 * i: w for i, w in enumerate(words)} - out = si.run_fragment(spv, memory=memory)["%out_mrt0"] - assert list(out) == [words[c % n] for c in range(4)], fmt - - store_sel = 0x22C if n == 2 else 0xFAC # XY01 for 2-comp RG (XYZW selects (x, w) on RDNA2 MUBUF stores) - store_desc = (f"s_mov_b32 s0, 0x1000\ns_mov_b32 s1, 0\ns_mov_b32 s2, {4 * n}\n" - f"s_mov_b32 s3, {0x31000000 | store_sel | fmt << 12:#x}\n") - setup = "".join(f"v_mov_b32 v{4 + i}, {w:#x}\n" for i, w in enumerate(words)) - regs = "v4" if n == 1 else f"v[4:{3 + n}]" - store = store_desc + setup + f"buffer_store_format_{'xyzw'[:n]} {regs}, off, s[0:3], 0\ns_endpgm\n" - shader = make_shader(store, name=f"ps_int32_store_{fmt}") - spv = shader.translate() - shader.validate(spv) - memory = {0x1000 + 4 * i: 0xDEADBEEF for i in range(5)} - si.run_fragment(spv, memory=memory) - assert [memory[0x1000 + 4 * i] for i in range(5)] == words + [0xDEADBEEF] * (5 - n), fmt - - -@pytest.mark.parametrize("fmt, shifts, channels", [(56, (0, 8, 16, 24), (64, 128, 191, 255)), - (50, (0, 10, 20, 30), (256, 512, 767, 3))]) -@pytest.mark.parametrize("packed", [False, True]) -@pytest.mark.parametrize("components", [1, 4]) -@pytest.mark.parametrize("bgra", [False, True]) -def test_buffer_store_format_bgra(fmt, shifts, channels, packed, components, bgra, make_shader): - # gfx1036 writes the red source into the third field of the BGRA view, even for store_format_x. - values = (0x38003400, 0x3c003a00) if packed else (0x3e800000, 0x3f000000, 0x3f400000, 0x3f800000) - order = (2, 1, 0, 3) if bgra else (0, 1, 2, 3) - selectors = sum((4 + channel) << (3 * i) for i, channel in enumerate(order)) - inputs = "".join(f"v_mov_b32 v{4 + i}, {value:#x}\n" for i, value in enumerate(values)) - regs = "v4" if components == 1 else ("v[4:5]" if packed else "v[4:7]") - op = "buffer_store_format_" + ("d16_" if packed else "") + "xyzw"[:components] - src = ("s_mov_b32 s0, 0x1000\ns_mov_b32 s1, 0\ns_mov_b32 s2, 4\n" - f"s_mov_b32 s3, {0x31000000 | fmt << 12 | selectors:#x}\n" + inputs + - f"{op} {regs}, off, s[0:3], 0\ns_endpgm\n") - shader = make_shader(src, name="ps_store_bgra") - spv = shader.translate() - shader.validate(spv) - memory = {0x1000: 0xdeadbeef} - _load_mini_interp().run_fragment(spv, memory=memory) - expected = sum(channels[c] << shift for c, shift in zip(order, shifts) if c < components) - assert memory[0x1000] == expected - - -@pytest.mark.parametrize("fmt, packed, inputs, expected", [ - (60, True, (0x01000101, 0x00fe00ff), (0xfeffffff,)), - (27, False, (65536, 65537), (0xffffffff,)), - (69, False, (65534, 65535, 65536, 0xffffffff), (0xfffffffe, 0xffffffff)), - (75, False, (65534, 65535, 65536, 0xffffffff), (65534, 65535, 65536, 0xffffffff)), -]) -def test_uint_buffer_store_saturation(fmt, packed, inputs, expected, make_shader): - # Native gfx1036 clips each channel to the destination's width. The 32-bit control keeps every bit. - setup = "".join(f"v_mov_b32 v{4 + i}, {v:#x}\n" for i, v in enumerate(inputs)) - selectors = 0x22c if fmt == 27 else 0xfac # XY01 for RG16, XYZW for RGBA - components = 4 if packed else len(inputs) - op = "buffer_store_format_" + ("d16_" if packed else "") + "xyzw"[:components] - src = ("s_mov_b32 s0, 0x1000\ns_mov_b32 s1, 0\ns_mov_b32 s2, 16\n" - f"s_mov_b32 s3, {0x31000000 | fmt << 12 | selectors:#x}\n" + setup + - f"{op} v[4:{3 + len(inputs)}], off, s[0:3], 0\ns_endpgm\n") - shader = make_shader(src, name="ps_store_uint") - spv = shader.translate() - shader.validate(spv) - memory = {0x1000 + 4 * i: 0xdeadbeef for i in range(4)} - _load_mini_interp().run_fragment(spv, memory=memory) - assert tuple(memory[0x1000 + 4 * i] for i in range(4)) == expected + (0xdeadbeef,) * (4 - len(expected)) - - -def test_remaining_d16_paths_avoid_packhalf2x16(make_shader): - """buffer_format d16 and image_sample_c_lz d16 avoid PackHalf2x16 and validate with spirv-val.""" - tbuf_asm = ( - "s_mov_b32 s0, 0x1000\n" - "s_mov_b32 s1, 0\n" - "s_mov_b32 s2, 0x100\n" - f"s_mov_b32 s3, {77 << 12 | 0x30000000:#x}\n" # format 77 = f32x4 - "v_mov_b32 v0, 0\n" - "buffer_load_format_d16_xy v2, v0, s[0:3], 0 offen\n" - "s_waitcnt vmcnt(0)\n" - "exp mrt0 v2, v2, v2, v2 done vm\n" - "s_endpgm\n" - ) - sh1 = make_shader(tbuf_asm, name="ps_tbuffer_d16_nopack") - spv1 = sh1.translate() - sh1.validate(spv1) - assert "PackHalf2x16" not in spv1 - - cmplz_asm = ( - "s_load_dwordx8 s[8:15], s[0:1], 0x0\ns_waitcnt lgkmcnt(0)\n" - "s_mov_b32 s16, 0x92\ns_mov_b32 s17, 0\ns_mov_b32 s18, 0\ns_mov_b32 s19, 0\n" - "image_sample_c_lz v4, v[0:2], s[8:15], s[16:19] dmask:0x1 dim:SQ_RSRC_IMG_2D d16\n" - "s_waitcnt vmcnt(0)\n" - "exp mrt0 v4, v4, v4, v4 done vm\n" - "s_endpgm\n" - ) - sh2 = make_shader(cmplz_asm, name="ps_sample_c_lz_d16_nopack") - spv2 = sh2.translate() - sh2.validate(spv2) - assert "PackHalf2x16" not in spv2 - - -WAVE64_SCMP_MASK_CASES = """\ -; mattr: +wavefrontsize64,-wavefrontsize32 -v_cmp_lt_u32_e64 vcc, v0, 17 -s_and_b64 s[6:7], vcc, exec -s_cmp_eq_u32 vcc_lo, vcc_hi -s_cmp_lg_u32 exec_lo, exec_hi -s_cmp_eq_u32 s6, s7 -s_cmp_eq_u32 vcc_lo, 0x80000003 -s_cmp_lt_u32 exec_hi, s4 -s_cmp_gt_i32 s6, 0 -s_cmp_eq_u64 vcc, s[4:5] -s_cmp_lg_u64 exec, 0x12345678 -s_endpgm -""" - - -@pytest.mark.parametrize("emulate", [False, True], ids=["wave64", "wave64-emulate"]) -def test_wave64_scmp_mask_halves_and_scalars_validate(emulate, make_shader, monkeypatch): - """Opposite-half s_cmp_*_u32, ordering compares on mask halves, and mask-vs-scalar/imm u32/u64 - compares translate and pass spirv-val in both native wave64 and --wave64-emulate modes.""" - shader = make_shader(WAVE64_SCMP_MASK_CASES, name="cs_w64_scmp_masks") - monkeypatch.setattr(rdna2spirv, "WAVE64_EMULATE", emulate) - spv = shader.translate() - shader.validate(spv) - if emulate: - assert "OpGroupNonUniform" not in spv - else: - assert "OpGroupNonUniformBitwiseOr" in spv diff --git a/tests/test_ttpf_assets.py b/tests/test_ttpf_assets.py deleted file mode 100644 index b2a9fca03..000000000 --- a/tests/test_ttpf_assets.py +++ /dev/null @@ -1,438 +0,0 @@ -"""Exercise the assets stage, existing C# catalogs and downstream texture lookup.""" -import contextlib -from contextlib import ExitStack -import io -import json -import os -from pathlib import Path -import sys -import tempfile -import unittest -from unittest import mock - -ROOT = Path(__file__).resolve().parents[1] -sys.path[:0] = [str(ROOT), str(ROOT / "tools"), str(ROOT / "tests")] -import make_game -import ttpf_assets -import ttpf_mips -import world_build -from test_calibrated_texture import synthetic_profile -from test_ttpf_mips import build_bc1_bcpack_pool - - -class TextureAssets(unittest.TestCase): - def setUp(self): - tmp = tempfile.TemporaryDirectory() - self.addCleanup(tmp.cleanup) - self.root = Path(tmp.name) - self.game = self.root / "game" - self.work = self.root / "work" - audio = self.work / "assets/audio" - audio.mkdir(parents=True) - for marker in ("audio_manifest.json", "ogg.done", "xma.done"): - (audio / marker).touch() - self.pool = self.game / "data/pool.ttpf" - self.pool.parent.mkdir(parents=True) - self.folder = self.work / "assets/ttpf/pool" - self.folder.mkdir(parents=True) - (self.folder / make_game.DECODER_RECORD).write_text(make_game.decoder_digest(), encoding="utf-8") - self.catalog = self.folder / "manifest.json" - self.row = dict(Index=0, AssetKey="CAFEBABE12345678", SourceMips=5, BaseMipLevel=0, - Mips=0, File=None, DxgiFormat=71, Limitation="BCPack") - self.stack = ExitStack() - self.addCleanup(self.stack.close) - self.stack.enter_context(mock.patch.object(make_game, "MODEL_ARCHIVES", ())) - self.stack.enter_context(mock.patch.object(make_game, "log")) - - def build(self): - make_game.assets(str(self.game), str(self.work), False, 1) - - def legacy(self, **changes): - self.catalog.write_text(json.dumps({"Count": 1, "Textures": [self.row | changes]}), encoding="utf-8") - - def row_after_export(self): - return json.loads(self.catalog.read_bytes())["Textures"][0] - - def test_partial_upgrade_failure_then_resume(self): - _, linear, _ = build_bc1_bcpack_pool(self.pool) - self.legacy(File="partial.dds", BaseMipLevel=2, Mips=3, Limitation=None) - partial = self.folder / "partial.dds" - partial.write_bytes(b"previous mip chain") - prior = self.catalog.read_bytes() - replace = os.replace - - def fail_catalog(src, dest): - if dest == self.catalog: - raise OSError("simulated write failure") - replace(src, dest) - - with mock.patch.object(os, "replace", side_effect=fail_catalog), self.assertRaises(OSError): - self.build() - self.assertEqual(prior, self.catalog.read_bytes()) - self.assertEqual(partial.read_bytes(), b"previous mip chain") - self.build() - row = self.row_after_export() - path = self.folder / row["File"] - self.assertEqual((row["Mips"], row["BaseMipLevel"]), (5, 0)) - self.assertEqual(path.read_bytes()[148:], b"".join(linear.values())) - self.assertEqual(world_build.index_ttpf_textures(self.work / "assets")[row["AssetKey"]], str(path)) - # The lower-mip file the row named is gone once the manifest names the full chain: it was kept through - # the failed run above, and it is not stored a second time after the successful one. - self.assertFalse(partial.exists()) - # decoder.sha256 is the decoder record assets() keeps in an exported texture folder (BUILD-1228) - self.assertEqual(sorted(p.name for p in self.folder.iterdir() if p.name != "decoder.sha256"), - sorted([row["File"], "manifest.json"])) - with mock.patch.object(ttpf_assets.ttpf, "Pool", side_effect=AssertionError("unexpected reopen")): - self.build() - - def upgrade(self, other_rows=(), file="partial.dds"): - """A pool whose one BCPack texture has a lower-mip export in `file`; returns that file's path.""" - build_bc1_bcpack_pool(self.pool) - first = self.row | dict(File=file, BaseMipLevel=2, Mips=3, Limitation=None) - self.catalog.write_text(json.dumps({"Count": 1 + len(other_rows), "Textures": [first, *other_rows]}), - encoding="utf-8") - old = self.folder / file - old.write_bytes(b"previous mip chain") - return old - - def test_superseded_file_another_row_names_is_kept(self): - # Not a block-compressed format, so the pass leaves this row alone; it names the same file. - other = dict(Index=1, AssetKey="0123456789ABCDEF", SourceMips=1, BaseMipLevel=0, Mips=1, - File="partial.dds", DxgiFormat=28, Limitation=None) - old = self.upgrade(other_rows=[other]) - self.build() - rows = json.loads(self.catalog.read_bytes())["Textures"] - self.assertTrue(rows[0]["File"].startswith("000000_bcpack_")) - self.assertEqual(rows[1]["File"], "partial.dds") - self.assertEqual(old.read_bytes(), b"previous mip chain") - - def test_superseded_file_that_cannot_be_removed_does_not_fail_the_export(self): - old = self.upgrade() - unlink = Path.unlink - - def in_use(path, *args, **kwargs): - if path.name == "partial.dds": - raise PermissionError(13, "The process cannot access the file because it is being used") - return unlink(path, *args, **kwargs) - - stderr = io.StringIO() - with mock.patch.object(Path, "unlink", in_use), contextlib.redirect_stderr(stderr): - self.build() - self.assertTrue(self.row_after_export()["File"].startswith("000000_bcpack_")) - self.assertTrue(old.exists()) - # Not hidden: a folder that stays double-sized has its reason on screen. - self.assertIn("pool: 1 replaced DDS file(s) could not be removed", stderr.getvalue()) - # And not forever: the manifest lists it, so the next build removes it once nothing holds it, although - # that build finds the pass stamped and writes nothing else. - self.assertEqual(json.loads(self.catalog.read_bytes())[ttpf_assets.PENDING], ["partial.dds"]) - with mock.patch.object(ttpf_assets.ttpf, "Pool", side_effect=AssertionError("unexpected reopen")): - self.build() - self.assertFalse(old.exists()) - self.assertNotIn(ttpf_assets.PENDING, json.loads(self.catalog.read_bytes())) - self.build() # nothing left to do: no further write, no error - self.assertTrue(self.row_after_export()["File"].startswith("000000_bcpack_")) - - def test_a_run_stopped_after_the_switch_is_finished_by_the_next(self): - # The manifest that switches the rows already lists the file to remove, so a build stopped between that - # write and the removal leaves nothing behind for good. - old = self.upgrade() - with mock.patch.object(ttpf_assets, "finish_replaced"): - self.build() - self.assertTrue(old.exists()) - self.assertEqual(json.loads(self.catalog.read_bytes())[ttpf_assets.PENDING], ["partial.dds"]) - self.build() - self.assertFalse(old.exists()) - self.assertNotIn(ttpf_assets.PENDING, json.loads(self.catalog.read_bytes())) - - def complete_with_row_file(self, file): - """Run the pass on a manifest whose row names `file`; returns the folder's file names afterwards.""" - self.upgrade() - manifest = json.loads(self.catalog.read_bytes()) - manifest["Textures"][0]["File"] = file - self.assertEqual(ttpf_assets.complete_pool(self.pool, self.folder, manifest, ("v1-strict", None)), (1, 0)) - return sorted(p.name for p in self.folder.iterdir()) - - def test_a_row_that_named_the_new_file_in_other_letter_case_keeps_it(self): - # On Windows and macOS that name is the file the pass has just published; removing it removed the export. - names = self.complete_with_row_file("000000_BCPACK_V1-STRICT.DDS") - row = self.row_after_export() - self.assertEqual(row["File"], "000000_bcpack_v1-strict.dds") - self.assertTrue((self.folder / row["File"]).is_file(), names) - self.assertGreater((self.folder / row["File"]).stat().st_size, 148) - - def test_a_row_that_named_the_manifest_does_not_remove_it(self): - names = self.complete_with_row_file("manifest.json") - self.assertIn("manifest.json", names) - self.assertTrue(self.row_after_export()["File"].startswith("000000_bcpack_")) - - def test_only_dds_files_are_removed(self): - (self.folder / "notes.txt").write_text("mine", encoding="utf-8") - names = self.complete_with_row_file("notes.txt") - self.assertIn("notes.txt", names) - - def test_removal_looks_at_each_file_once_not_once_per_pair(self): - # 50 rows and 50 replaced files: 100 files to look at, not 2,500 pairs. A pool completes most of its - # textures in one pass, so a per-pair check takes minutes to hours on a real one. - rows = [dict(File=f"{i:06d}_bcpack_v1-strict.dds") for i in range(50)] - replaced = {f"{i:06d}.dds" for i in range(50)} - for name in [row["File"] for row in rows] + sorted(replaced): - (self.folder / name).write_bytes(b"dds") - stat, calls = os.stat, [] - - def counted(path, *args, **kwargs): - calls.append(path) - return stat(path, *args, **kwargs) - - with mock.patch.object(ttpf_assets.os, "stat", counted), \ - mock.patch.object(ttpf_assets.os.path, "samefile", side_effect=AssertionError("per-pair check")): - self.assertEqual(ttpf_assets.remove_replaced(self.folder, replaced, rows), []) - self.assertLessEqual(len(calls), 100, len(calls)) - # The replaced files are gone and the rows' files stay. - self.assertEqual(sorted(p.name for p in self.folder.iterdir() if p.name != "decoder.sha256"), - sorted(row["File"] for row in rows)) - - def test_only_a_file_in_the_pool_folder_is_removed(self): - # A row is trusted for a file name, not for a path: nothing outside the pool's folder is touched. - outside = self.folder.parent / "outside.dds" - outside.write_bytes(b"not this pool's") - self.upgrade() - manifest = json.loads(self.catalog.read_bytes()) - manifest["Textures"][0]["File"] = "../outside.dds" - written, blocked = ttpf_assets.complete_pool(self.pool, self.folder, manifest, ("v1-strict", None)) - self.assertEqual((written, blocked), (1, 0)) - self.assertTrue(self.row_after_export()["File"].startswith("000000_bcpack_")) - self.assertEqual(outside.read_bytes(), b"not this pool's") - - def test_profile_added_after_strict_rejection(self): - build_bc1_bcpack_pool(self.pool, ref_dists=[250] + [0] * 1023) - self.legacy() - self.build() - row = self.row_after_export() - self.assertIsNone(row["File"]) - self.assertIn("BCPackLimitation", row) - try: - from calibrated_texture import native - native() - except (ImportError, OSError) as exc: - self.skipTest(str(exc)) - profile = self.work / "bcpack-calibration.json" - config = synthetic_profile() - profile.write_text(json.dumps(config), encoding="utf-8") - self.build() - row = self.row_after_export() - original = self.folder / row["File"] - # Read now: the build with the changed profile replaces this file and then removes it (remove_replaced). - original_bytes = original.read_bytes() - self.assertEqual(original_bytes[:4], b"DDS ") - self.assertNotIn("BCPackLimitation", row) - config["bc1"]["selectors"][0] = [mask ^ 1 for mask in config["bc1"]["selectors"][0]] - profile.write_text(json.dumps(config), encoding="utf-8") - self.build() - updated = self.folder / self.row_after_export()["File"] - self.assertNotEqual(updated, original) - self.assertNotEqual(updated.read_bytes(), original_bytes) - self.assertFalse(original.exists()) - - @unittest.skipUnless(os.environ.get("RPF9DUMP_DLL"), "requires the built rpf9dump") - def test_new_base_and_pack_pools(self): - dll = Path(os.environ["RPF9DUMP_DLL"]).resolve() - exe = dll.with_suffix(".exe" if os.name == "nt" else "") - pack = self.game / "pack/story/data/pool.ttpf" - pack.parent.mkdir(parents=True) - _, linear, _ = build_bc1_bcpack_pool(self.pool) - pack.write_bytes(self.pool.read_bytes()) - with mock.patch.object(make_game, "rpf9dump", return_value=str(exe)): - self.build() - for folder in (self.folder, self.work / "assets/ttpf_pack/story/pool"): - row = json.loads((folder / "manifest.json").read_bytes())["Textures"][0] - self.assertEqual(row["Mips"], 5) - self.assertEqual((folder / row["File"]).read_bytes()[148:], b"".join(linear.values())) - - def test_complete_pool_handles_unmapped_range_without_crashing(self): - # If pool.codecs() raises ValueError (e.g., an unmapped hole inside a texture's span), - # complete_pool must record BCPackLimitation on that row instead of aborting the pool. - build_bc1_bcpack_pool(self.pool) - self.legacy() - with mock.patch.object(ttpf_assets.ttpf.Pool, "codecs", - side_effect=ValueError("texture range is not completely mapped")): - self.build() - row = self.row_after_export() - self.assertIsNone(row["File"]) - self.assertEqual(row["BCPackLimitation"], "texture range is not completely mapped") - - -BC_FORMAT = next(iter(ttpf_mips.BC_FORMATS)) -NOT_BC = "R8G8B8A8_UNORM" - - -def synthetic_row(**changes): - out = {"DxgiFormat": BC_FORMAT, "File": None, "BaseMipLevel": 0, "Mips": 1, "SourceMips": 1} - out.update(changes) - return out - - -class PublishWriter(unittest.TestCase): - """`publish` stages in the destination folder and must never leave the staging file behind.""" - - def setUp(self): - tmp = tempfile.TemporaryDirectory() - self.addCleanup(tmp.cleanup) - self.dir = Path(tmp.name) - - def names(self): - return sorted(p.name for p in self.dir.iterdir()) - - def test_writes_the_bytes_and_leaves_no_staging_file(self): - ttpf_assets.publish(self.dir / "manifest.json", b'{"Textures": []}') - self.assertEqual((self.dir / "manifest.json").read_bytes(), b'{"Textures": []}') - self.assertEqual(self.names(), ["manifest.json"]) - - def test_replaces_the_previous_contents(self): - target = self.dir / "manifest.json" - target.write_bytes(b"old contents that are longer") - ttpf_assets.publish(target, b"new") - self.assertEqual(target.read_bytes(), b"new") - self.assertEqual(self.names(), ["manifest.json"]) - - def test_failed_replace_keeps_the_previous_bytes_and_no_temp(self): - target = self.dir / "manifest.json" - target.write_bytes(b"previous") - with mock.patch.object(ttpf_assets.os, "replace", side_effect=OSError(5, "access denied")), \ - self.assertRaises(OSError): - ttpf_assets.publish(target, b"replacement") - self.assertEqual(target.read_bytes(), b"previous") - self.assertEqual(self.names(), ["manifest.json"]) - - @unittest.skipUnless(os.name == "posix", "POSIX file modes only") - def test_preserves_the_destination_mode(self): - target = self.dir / "manifest.json" - target.write_bytes(b"previous") - os.chmod(target, 0o640) - ttpf_assets.publish(target, b"replacement") - self.assertEqual(target.stat().st_mode & 0o777, 0o640) - self.assertEqual(self.names(), ["manifest.json"]) - - -class CandidateRules(unittest.TestCase): - def test_other_formats_are_never_candidates(self): - self.assertFalse(ttpf_assets.candidate(synthetic_row(DxgiFormat=NOT_BC, File=None), None)) - - def test_a_strict_decoder_claim_is_a_candidate_without_a_profile(self): - self.assertTrue(ttpf_assets.candidate(synthetic_row(BCPackDecoder="bc1-strict"), None)) - - def test_a_calibrated_decoder_claim_needs_a_profile(self): - self.assertFalse(ttpf_assets.candidate(synthetic_row(BCPackDecoder="bc1-calibrated"), None)) - self.assertTrue(ttpf_assets.candidate(synthetic_row(BCPackDecoder="bc1-calibrated"), {"version": 1})) - - def test_a_missing_file_is_a_candidate(self): - self.assertTrue(ttpf_assets.candidate(synthetic_row(File=None), None)) - - def test_a_lower_mip_start_or_a_partial_chain_is_a_candidate(self): - self.assertTrue(ttpf_assets.candidate(synthetic_row(File="000001.dds", BaseMipLevel=2), None)) - self.assertTrue(ttpf_assets.candidate(synthetic_row(File="000001.dds", Mips=2, SourceMips=5), None)) - - def test_a_complete_chain_with_a_file_is_not_a_candidate(self): - self.assertFalse(ttpf_assets.candidate(synthetic_row(File="000001.dds", Mips=5, SourceMips=5), None)) - - -class ProfileRules(unittest.TestCase): - def setUp(self): - tmp = tempfile.TemporaryDirectory() - self.addCleanup(tmp.cleanup) - self.work = Path(tmp.name) - - def write(self, text): - (self.work / "bcpack-calibration.json").write_text(text, encoding="utf-8") - - def test_missing_calibration_is_the_strict_profile(self): - self.assertEqual(ttpf_assets.load_profile(self.work), (ttpf_assets.strict_stamp(), None)) - - def test_a_decoder_source_edit_changes_both_stamps_and_the_pass_is_done_again(self): - # A pool stamped before a bcpack.py fix kept its limited rows for good: the strict stamp was a constant. - tools = self.work / "tools" - tools.mkdir() - for name in ttpf_assets.DECODER_SOURCES: - (tools / name).write_text(f"# {name}\n", encoding="utf-8") - self.write(json.dumps({"version": 1})) - with mock.patch.object(ttpf_assets, "__file__", str(tools / "ttpf_assets.py")), \ - mock.patch.dict(sys.modules, {"calibrated_texture": mock.Mock()}): - old = ttpf_assets.strict_stamp(), ttpf_assets.load_profile(self.work)[0] - with open(tools / "bcpack.py", "a", encoding="utf-8") as f: - f.write("# fixed\n") - new = ttpf_assets.strict_stamp(), ttpf_assets.load_profile(self.work)[0] - self.assertTrue(new[0].endswith("-strict")) - self.assertEqual(len(f"000000_bcpack_{new[0][:19]}.dds"), 37) - (tools / "tex_headers.py").unlink() - with self.assertRaises(FileNotFoundError): - ttpf_assets.strict_stamp() - self.assertNotEqual(old[0], new[0]) - self.assertNotEqual(old[1], new[1]) - manifest = {"BCPackPass": old[0], "Textures": [synthetic_row(BCPackDecoder=old[0])]} - with mock.patch.object(ttpf_assets.ttpf, "Pool", side_effect=RuntimeError("opened")): - with self.assertRaisesRegex(RuntimeError, "opened"): - ttpf_assets.complete_pool("missing.ttpf", self.work, manifest, (new[0], None)) - - def test_another_calibration_version_is_an_error(self): - self.write(json.dumps({"version": 2})) - with self.assertRaises(ValueError): - ttpf_assets.load_profile(self.work) - - def test_a_non_object_calibration_is_an_error(self): - self.write("[]") - with self.assertRaises(ValueError): - ttpf_assets.load_profile(self.work) - - def test_malformed_json_is_an_error(self): - self.write("{") - with self.assertRaises(ValueError): - ttpf_assets.load_profile(self.work) - - def test_malformed_json_names_the_profile(self): - self.write("{") - with self.assertRaises(ValueError) as caught: - ttpf_assets.load_profile(self.work) - self.assertIn("bcpack-calibration.json", str(caught.exception)) - - -class CompletePoolEarlyReturn(unittest.TestCase): - def test_a_matching_pass_stamp_returns_before_opening_the_pool(self): - manifest = {"BCPackPass": "v1-deadbeef", "Textures": [synthetic_row()]} - with mock.patch.object(ttpf_assets, "publish") as publish, \ - mock.patch.object(ttpf_assets.ttpf, "Pool") as pool: - self.assertEqual(ttpf_assets.complete_pool("missing.rpf", "/tmp/out", manifest, ("v1-deadbeef", None)), - (0, 0)) - publish.assert_not_called() - pool.assert_not_called() - - def test_no_candidates_returns_before_opening_the_pool(self): - manifest = {"BCPackPass": "v1-new", - "Textures": [synthetic_row(File="000001.dds", Mips=5, SourceMips=5)]} - with mock.patch.object(ttpf_assets.ttpf, "Pool") as pool: - self.assertEqual(ttpf_assets.complete_pool("missing.rpf", "/tmp/out", manifest, ("v1-other", None)), - (0, 0)) - pool.assert_not_called() - - - def test_a_pool_hashes_the_decoder_sources_once_for_all_its_strict_fallback_rows(self): - # With a profile, each row the calibrated decoder can't take falls back to strict decoding; hashing the - # sources per row read them 32 times over for 32 rows. A new pass computes the stamp again. - pool = mock.Mock(chunks=[(0,)], virtual_size=64) - pool.descriptor.return_value = {"base": 0, "dimension": 1, "format": 71} - pool.span.return_value = 8 - pool.codecs.return_value = ttpf_assets.bcpack.SUPPORTED_REBUILD_CODECS - calibrated = mock.Mock() - calibrated.LocalDecoder.return_value.formats = set() - with tempfile.TemporaryDirectory() as out, ExitStack() as stack: - stack.enter_context(mock.patch.dict(sys.modules, calibrated_texture=calibrated)) - stack.enter_context(mock.patch.object(ttpf_assets.ttpf, "Pool", return_value=pool)) - stack.enter_context(mock.patch.object(ttpf_assets.ttpf, "analyze", side_effect=ValueError("limited"))) - stamps = stack.enter_context(mock.patch.object(ttpf_assets, "strict_stamp", - wraps=ttpf_assets.strict_stamp)) - for passes in (1, 2): - manifest = {"Textures": [synthetic_row(Index=i) for i in range(32)]} - self.assertEqual(ttpf_assets.complete_pool("synthetic", out, manifest, ("v1-profile", {})), (0, 32)) - self.assertEqual(stamps.call_count, passes) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/test_ttpf_export_resume.py b/tests/test_ttpf_export_resume.py deleted file mode 100644 index e63d7e3cb..000000000 --- a/tests/test_ttpf_export_resume.py +++ /dev/null @@ -1,150 +0,0 @@ -"""Integration check for a built rpf9dump. Set RPF9DUMP_DLL to its Release DLL to run it.""" - -import json -import os -from pathlib import Path -import struct -import subprocess -import sys -import tempfile -import unittest -import zlib - -sys.path.insert(0, str(Path(__file__).resolve().parent)) -from test_ttpf_mips import build_bc1_bcpack_pool, pack_etpf_record, write_rds5_pool - - -def write_pool(pool): - # An unmapped catalog entry and two distinct, single-mip BC1 textures, one per zlib chunk. - records = [pack_etpf_record(16, 16, 1, 0, 71, 1, 1, 2, base) for base in (0, 4096, 8192)] - write_rds5_pool(pool, records, [b"a" * 4096, b"b" * 4096]) - - -def export(pool, out): - return subprocess.run(["dotnet", os.environ["RPF9DUMP_DLL"], "ttpf", pool, out], - capture_output=True, text=True) - - -def textures(folder): - return json.loads((folder / "manifest.json").read_text(encoding="utf-8"))["Textures"] - - -@unittest.skipUnless(os.environ.get("RPF9DUMP_DLL"), "requires a built rpf9dump") -class TtpfExportResumeTest(unittest.TestCase): - def test_manifest_preserves_volume_shape(self): - with tempfile.TemporaryDirectory() as tmp: - root = Path(tmp) - pool = root / "volume.ttpf" - record = pack_etpf_record(8, 8, 1, 0, 10, 8, 3, 2, 4096) - write_rds5_pool(pool, [record], [bytes(4096)]) - result = export(pool, root / "out") - self.assertEqual(result.returncode, 0, result.stdout + result.stderr) - folder = root / "out" / pool.stem - row, = textures(folder) - self.assertEqual((row["Dimension"], row["Depth"], row["SourceMips"]), (3, 8, 1)) - self.assertIsNotNone(row["File"], row["Limitation"]) - header = (folder / row["File"]).read_bytes() - self.assertEqual(struct.unpack_from("> 1, r >> 1), - g=(g >> 1, g >> 1), - b=(b >> 1, b >> 1), - a=(127, 127), - pbits=(r & 1, r & 1), - ) - - -def pack_bc6h_block(code, *, part=0, fields=None, indices=None): - """Assemble one 16-byte BC6H block for any of the 14 valid mode codes.""" - _, _, _, reg = ttpf.bcpack._BC6H_INFO[code] - plan, hdr = ttpf.bcpack._bc6h_plan(code) - blk = code - fields = fields or [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]] - for c, q, bit_idx, pos in plan: - bit = ((part >> bit_idx) & 1) if c < 0 else ((fields[c][q] >> bit_idx) & 1) - if bit: - blk |= 1 << pos - pos = hdr - indices = [0] * 16 if indices is None else indices - if reg == 1: - for p in range(16): - nb = 3 if p == 0 else 4 - blk |= (indices[p] & ((1 << nb) - 1)) << pos - pos += nb - else: - anchor1 = ttpf._bptc.load_bc7()["anchor2"][part] - for p in range(16): - nb = 2 if (p == 0 or p == anchor1) else 3 - blk |= (indices[p] & ((1 << nb) - 1)) << pos - pos += nb - assert pos == 128, f"BC6H mode {code:#x} ended at bit {pos}" - return blk.to_bytes(16, "little") - - -def solid_bc6h(r, g, b, *, signed=False): - """Mode 0x0F (16-bit base, zero delta) solid BC6H block for float16 RGB.""" - fields = [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]] - for c, v in enumerate((r, g, b)): - neg = signed and v < 0 - hv = struct.unpack(" 0: - off |= (((x + mip["tile_x"]) >> (s - 1)) & 1) << bit - elif s < 0: - off |= (((y + mip["tile_y"]) >> (-s - 1)) & 1) << bit - at = (y * mip["blocks_w"] + x) * eb - out[mip_off + off:mip_off + off + eb] = linear[at:at + eb] - - -def retile_volume(layout, linear): - eb = layout["element_bytes"] - pat = ttpf.VOLUME_PATTERNS_4K[{1: 0, 2: 1, 4: 2, 8: 3, 16: 4}[eb]] - bw, bh, bd = layout["block_w"], layout["block_h"], layout["block_d"] - mip = layout["mips"][0] - w, h, d = mip["blocks_w"], mip["blocks_h"], mip["blocks_d"] - tiles_x = mip["padded_w"] // bw - out = bytearray(layout["size"]) - for z in range(d): - z_base = (z // bd) * layout["z_tile_stride"] - z_in_tile = 0 - for bit, s in enumerate(pat): - if s >= 101: - z_in_tile |= ((z >> (s - 101)) & 1) << bit - for y in range(h): - y_tile = (y // bh) * tiles_x - y_in_tile = z_in_tile - for bit, s in enumerate(pat): - if s < 0: - y_in_tile |= ((y >> (-s - 1)) & 1) << bit - for x in range(w): - off = z_base + (y_tile + x // bw) * layout["tile"] + y_in_tile - for bit, s in enumerate(pat): - if 0 < s < 100: - off |= ((x >> (s - 1)) & 1) << bit - at = ((z * h + y) * w + x) * eb - out[off:off + eb] = linear[at:at + eb] - return bytes(out) - - -def solid_chain(layout, fmt=71, color_fn=None): - """Build block-linear bytes for every mip; each block is one solid BC colour.""" - eb = layout["element_bytes"] - out = {} - is_hdr = fmt in (95, 96) - # Smooth gradient at the top level; every lower mip is the 2x2 block mean. - top = layout["mips"][0] - colours = {} - for y in range(top["blocks_h"]): - for x in range(top["blocks_w"]): - if color_fn is not None: - colours[(0, x, y)] = color_fn(x, y, top["blocks_w"], top["blocks_h"]) - elif fmt == 95: - colours[(0, x, y)] = (x * 16.0 / max(1, top["blocks_w"] - 1), - y * 8.0 / max(1, top["blocks_h"] - 1), 1.5) - elif fmt == 96: - colours[(0, x, y)] = (-4.0 + x * 8.0 / max(1, top["blocks_w"] - 1), - -2.0 + y * 4.0 / max(1, top["blocks_h"] - 1), 0.5) - else: - colours[(0, x, y)] = (min(255, x * 255 // max(1, top["blocks_w"] - 1)), - min(255, y * 255 // max(1, top["blocks_h"] - 1)), 128) - for m in range(1, len(layout["mips"])): - pm = layout["mips"][m - 1] - cm = layout["mips"][m] - for y in range(cm["blocks_h"]): - for x in range(cm["blocks_w"]): - acc = [0.0, 0.0, 0.0] if is_hdr else [0, 0, 0] - n = 0 - for dy in range(2): - for dx in range(2): - px, py = min(pm["blocks_w"] - 1, 2 * x + dx), min(pm["blocks_h"] - 1, 2 * y + dy) - q = colours[(m - 1, px, py)] - for k in range(3): - acc[k] += q[k] - n += 1 - colours[(m, x, y)] = tuple((a / n) if is_hdr else (a // n) for a in acc) - for mip in layout["mips"]: - buf = bytearray(mip["blocks_w"] * mip["blocks_h"] * eb) - for y in range(mip["blocks_h"]): - for x in range(mip["blocks_w"]): - at = (y * mip["blocks_w"] + x) * eb - c = colours[(mip["index"], x, y)] - if fmt == 80: - blk = solid_bc4(c[0]) - elif fmt == 83: - blk = solid_bc5(c[0], c[1]) - elif fmt in (95, 96): - blk = solid_bc6h(c[0], c[1], c[2], signed=(fmt == 96)) - elif fmt in (98, 99): - blk = solid_bc7(c[0], c[1], c[2]) - else: - blk = solid_bc1(c)[:eb].ljust(eb, b"\0") - buf[at:at + eb] = blk - out[mip["index"]] = bytes(buf) - return out - - -def write_rds5_pool(path, records, chunks, area=None): - """Write a synthetic RDS5/ETPF pool with one or more zlib-compressed chunks. - - `area` is the size of the record region in bytes. The default, len(records) * 24, fits - every 8-byte asset key after the 16-byte descriptors. A smaller area (at least - len(records) * 16) lets the key array continue into the 32-byte ID region, as most - retail pools do.""" - count = len(chunks) + 2 - table_end = 24 + (count - 1) * 8 - etpf = ttpf.align(table_end, 256) - area = len(records) * 24 if area is None else area - metadata = 16 + area + len(records) * 32 - padded = ttpf.align(metadata, 4096) - - source = etpf + padded - virt = padded - entries = [] - packed_chunks = [] - for raw in chunks: - assert len(raw) % 4096 == 0 and len(raw) > 0 - packed_payload = zlib.compress(raw, 9) - pad = (-len(packed_payload)) % 256 - entries.append((source // 256) | (8 << 26) | ((virt // 4096) << 30) | (pad << 52)) - packed_chunks.append((source, packed_payload)) - source += len(packed_payload) + pad - virt += len(raw) - - vsize = virt - entries.append((source // 256) | ((vsize // 4096) << 30)) - - header = bytearray(24) - header[0:4] = b"RDS5" - struct.pack_into(" c1=black: index 0 -> white, index 3 -> (c0 + 2*c1)/3 - white = ttpf.decode_pixels(71, struct.pack(" e1=70): index 0 -> 210, index 1 -> 70, index 2 -> (6*210+70)//7 = 190 - bits8 = 0 | (1 << 3) | (2 << 6) - blk8 = bytes([210, 70]) + bits8.to_bytes(6, "little") - px8 = ttpf.decode_pixels(80, blk8, 1, 1) - self.assertEqual(px8[0], (210.0, 210.0, 210.0)) - self.assertEqual(px8[1], (70.0, 70.0, 70.0)) - self.assertEqual(px8[2], (190.0, 190.0, 190.0)) - - # BC4 6-value mode (e0=50 <= e1=150): index 6 -> 0, index 7 -> 255 - bits6 = 0 | (1 << 3) | (6 << 6) | (7 << 9) - blk6 = bytes([50, 150]) + bits6.to_bytes(6, "little") - px6 = ttpf.decode_pixels(80, blk6, 1, 1) - self.assertEqual(px6[0], (50.0, 50.0, 50.0)) - self.assertEqual(px6[1], (150.0, 150.0, 150.0)) - self.assertEqual(px6[2], (0.0, 0.0, 0.0)) - self.assertEqual(px6[3], (255.0, 255.0, 255.0)) - - # BC5 (fmt=83): channel R from first BC4 block, channel G from second, B=0.0 - px5 = ttpf.decode_pixels(83, blk8 + blk6, 1, 1) - self.assertEqual(px5[0], (210.0, 50.0, 0.0)) - self.assertEqual(px5[1], (70.0, 150.0, 0.0)) - self.assertEqual(px5[2], (190.0, 0.0, 0.0)) - self.assertEqual(px5[3], (210.0, 255.0, 0.0)) - - def test_block_means_sub_block_clamping(self): - # 4x4 block where only the top-left 2x2 texels are active; remaining 12 are zero-padded. - pixels = [] - for y in range(4): - for x in range(4): - pixels.append((200.0, 100.0, 50.0) if (x < 2 and y < 2) else (0.0, 0.0, 0.0)) - clamped = ttpf.block_means(pixels, 1, 1, pixels_w=2, pixels_h=2) - self.assertEqual(clamped, [(200.0, 100.0, 50.0)]) - unclamped = ttpf.block_means(pixels, 1, 1) - self.assertEqual(unclamped, [(50.0, 25.0, 12.5)]) - - def test_bc7_all_eight_modes_and_reserved(self): - tab = ttpf._bptc.load_bc7() - # Reserved mode (b0 == 0): decodes to all-zero black. - self.assertEqual(ttpf.decode_pixels(98, b"\x00" * 16, 1, 1), [(0.0, 0.0, 0.0)] * 16) - self.assertEqual(ttpf.decode_pixels(99, b"\x00" * 16, 1, 1), [(0.0, 0.0, 0.0)] * 16) - - # Mode 0: 3 subsets, 4-bit endpoints + per-endpoint p-bit -> 5-bit expanded via MSB rep. - # Subset 0: (15,0,0) p=1 -> (255,8,8); Subset 1: (0,15,0) p=0 -> (0,247,0); Subset 2: (0,0,15) p=1 -> (8,8,255). - blk0 = pack_bc7_block( - 0, part=0, - r=(15, 15, 0, 0, 0, 0), g=(0, 0, 15, 15, 0, 0), b=(0, 0, 0, 0, 15, 15), - pbits=(1, 1, 0, 0, 1, 1), - ) - px0 = ttpf.decode_pixels(98, blk0, 1, 1) - exp0 = [(255.0, 8.0, 8.0), (0.0, 247.0, 0.0), (8.0, 8.0, 255.0)] - for p, sub in enumerate(tab["partition3"][0]): - self.assertEqual(px0[p], exp0[sub], f"mode 0 pixel {p}") - - # Mode 1: 2 subsets, 6-bit endpoints + shared per-subset p-bit -> 7-bit expanded. - # Subset 0: r=0..63, p=1 -> 2..255; Subset 1: g=32..32, p=0 -> 129..129. - # Index 3 on 3-bit table has weight 27 -> ((37*2 + 27*255 + 32) >> 6) = 109. - idx1 = [3 if p == 1 else 0 for p in range(16)] - blk1 = pack_bc7_block( - 1, part=0, - r=(0, 63, 0, 0), g=(0, 0, 32, 32), b=(0, 0, 0, 0), - pbits=(1, 0), idx1=idx1, - ) - px1 = ttpf.decode_pixels(98, blk1, 1, 1) - self.assertEqual(px1[0], (2.0, 2.0, 2.0)) - self.assertEqual(px1[1], (109.0, 2.0, 2.0)) - self.assertEqual(px1[2], (0.0, 129.0, 0.0)) # partition2[0][2] == 1 - - # Mode 2: 3 subsets, 5-bit endpoints (no p-bits), 2-bit indices. - blk2 = pack_bc7_block( - 2, part=1, - r=(31, 0, 16, 16, 0, 0), g=(0, 0, 0, 0, 31, 31), b=(0, 31, 0, 0, 0, 0), - idx1=[3 if p == 1 else 0 for p in range(16)], - ) - px2 = ttpf.decode_pixels(98, blk2, 1, 1) - self.assertEqual(px2[0], (255.0, 0.0, 0.0)) - # pixel 1 is subset 0 in partition3[1]; idx=3 -> weight 64 -> (0, 0, 255) - self.assertEqual(tab["partition3"][1][1], 0) - self.assertEqual(px2[1], (0.0, 0.0, 255.0)) - - # Mode 3: 2 subsets, 7-bit + per-endpoint p-bit (exact 8-bit), 2-bit indices. - # Subset 0: R=0..255, idx=1 (w=21) -> (21*255 + 32)>>6 = 84. - blk3 = pack_bc7_block( - 3, part=0, - r=(0, 127, 50, 50), g=(0, 0, 100, 100), b=(0, 0, 0, 0), - pbits=(0, 1, 0, 0), idx1=[1 if p == 1 else 0 for p in range(16)], - ) - px3 = ttpf.decode_pixels(98, blk3, 1, 1) - self.assertEqual(px3[0], (0.0, 0.0, 0.0)) - self.assertEqual(px3[1], (84.0, 0.0, 0.0)) - self.assertEqual(px3[2], (100.0, 200.0, 0.0)) - - # Mode 4: 1 subset, 5-bit color, 6-bit alpha, rotation + index selection (isel=0 and isel=1). - # Color endpoints: R=0..255, G=0..0, B=0..0. Alpha endpoints: A=0..255. - # idx1[1]=1 (2-bit, w=21 -> 84), idx2[1]=4 (3-bit, w=37 -> 147). - for rot, isel, expected in ( - (0, 0, (84.0, 0.0, 0.0)), # color uses idx1 (84), no swap - (0, 1, (147.0, 0.0, 0.0)), # color uses idx2 (147), no swap - (1, 0, (147.0, 0.0, 0.0)), # rot=1 swaps R and A -> R gets alpha(idx2=147) - (2, 0, (84.0, 147.0, 0.0)), # rot=2 swaps G and A -> G gets alpha(147) - (3, 1, (147.0, 0.0, 84.0)), # isel=1: color=idx2(147), alpha=idx1(84), rot=3 puts A into B - ): - blk4 = pack_bc7_block( - 4, rot=rot, isel=isel, - r=(0, 31), g=(0, 0), b=(0, 0), a=(0, 63), - idx1=[1 if p == 1 else 0 for p in range(16)], - idx2=[4 if p == 1 else 0 for p in range(16)], - ) - px4 = ttpf.decode_pixels(98, blk4, 1, 1) - self.assertEqual(px4[1], expected, f"mode 4 rot={rot} isel={isel}") - - # Mode 5: 1 subset, 7-bit color, 8-bit alpha, rotation, 2-bit color & alpha indices. - blk5 = pack_bc7_block( - 5, rot=2, - r=(64, 64), g=(0, 0), b=(16, 16), a=(0, 200), - idx1=[0] * 16, idx2=[3 if p == 5 else 0 for p in range(16)], - ) - px5 = ttpf.decode_pixels(98, blk5, 1, 1) - self.assertEqual(px5[0], (129.0, 0.0, 32.0)) - self.assertEqual(px5[5], (129.0, 200.0, 32.0)) # rot=2 swaps A into G - - # Mode 6: 1 subset, 7-bit RGBA + per-endpoint p-bit (exact 8-bit), 4-bit indices. - # idx=5 has weight 21 -> ((43*20 + 21*220 + 32) >> 6) = 86. - blk6 = pack_bc7_block( - 6, r=(10, 110), g=(0, 0), b=(127, 127), a=(127, 127), - pbits=(0, 0), idx1=[5 if p == 3 else 0 for p in range(16)], - ) - px6 = ttpf.decode_pixels(99, blk6, 1, 1) - self.assertEqual(px6[0], (20.0, 0.0, 254.0)) - self.assertEqual(px6[3], (86.0, 0.0, 254.0)) - - # Mode 7: 2 subsets, 5-bit RGBA + per-endpoint p-bit -> 6-bit expanded, 2-bit indices. - blk7 = pack_bc7_block( - 7, part=0, - r=(31, 31, 0, 0), g=(0, 0, 31, 31), b=(0, 0, 0, 0), a=(31, 31, 31, 31), - pbits=(1, 1, 1, 1), - ) - px7 = ttpf.decode_pixels(98, blk7, 1, 1) - self.assertEqual(px7[0], (255.0, 4.0, 4.0)) - self.assertEqual(px7[2], (4.0, 255.0, 4.0)) - - def test_bc6h_modes_uf16_sf16_and_reserved(self): - lut = ttpf._f16_lut() - # Reserved modes (0x13, 0x17, 0x1B, 0x1F) decode to zero. - for bad_mode in (0x13, 0x17, 0x1B, 0x1F): - blk_bad = bytes([bad_mode]) + b"\x00" * 15 - self.assertEqual(ttpf.decode_pixels(95, blk_bad, 1, 1), [(0.0, 0.0, 0.0)] * 16) - self.assertEqual(ttpf.decode_pixels(96, blk_bad, 1, 1), [(0.0, 0.0, 0.0)] * 16) - - # Mode 0x03 (1-region untransformed 10-bit): UF16 max endpoint 1023 -> 0xFFFF -> 0x7BF7 -> ~65024.0 - blk03 = pack_bc6h_block(0x03, fields=[[0, 1023, 0, 0], [512, 512, 0, 0], [0, 0, 0, 0]], - indices=[0, 15] + [0] * 14) - px03_u = ttpf.decode_pixels(95, blk03, 1, 1) - self.assertEqual(px03_u[0][0], 0.0) - self.assertAlmostEqual(px03_u[1][0], lut[(0xFFFF * 31) >> 6], places=5) - self.assertGreater(px03_u[0][1], 1.0) - # Same bit pattern as SF16: 1023 -> -1 (negative!), 512 -> -512 (max negative magnitude -> -65504.0). - px03_s = ttpf.decode_pixels(96, blk03, 1, 1) - self.assertEqual(px03_s[0][0], 0.0) - self.assertLess(px03_s[1][0], 0.0) - self.assertEqual(px03_s[0][1], -65504.0) - - # Mode 0x0B (1-region transformed 12-bit base + 8-bit delta, reversed rw[11:10]). - # e0 = 0x900 (2304, uses both bits 11 and 8), delta = -16 -> e1 = 2288. - blk0b = pack_bc6h_block(0x0B, fields=[[0x900, (-16) & 0xFF, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]], - indices=[0, 15] + [0] * 14) - px0b = ttpf.decode_pixels(95, blk0b, 1, 1) - exp_e0 = ttpf._bc6h_finish(ttpf._bc6h_unquantize(0x900, 12, False), False, lut) - exp_e1 = ttpf._bc6h_finish(ttpf._bc6h_unquantize(0x8F0, 12, False), False, lut) - self.assertEqual(px0b[0][0], exp_e0) - self.assertEqual(px0b[1][0], exp_e1) - - # Mode 0x0F (1-region transformed 16-bit base + 4-bit delta, reversed rw[15:10]). - # Test exact round-trip of large positive UF16 and negative SF16 via solid_bc6h, - # plus -32768 clamp in SF16 -> finite -65504.0 (never -inf/NaN). - px_hi = ttpf.decode_pixels(95, solid_bc6h(128.0, 0.5, 0.0, signed=False), 1, 1) - self.assertAlmostEqual(px_hi[0][0], 128.0, places=2) - self.assertAlmostEqual(px_hi[0][1], 0.5, places=3) - px_neg = ttpf.decode_pixels(96, solid_bc6h(-12.5, 3.25, -0.25, signed=True), 1, 1) - self.assertAlmostEqual(px_neg[0][0], -12.5, places=2) - self.assertAlmostEqual(px_neg[0][1], 3.25, places=2) - self.assertAlmostEqual(px_neg[0][2], -0.25, places=3) - blk_min16 = pack_bc6h_block(0x0F, fields=[[0x8000, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]) - px_min16 = ttpf.decode_pixels(96, blk_min16, 1, 1) - self.assertEqual(px_min16[0][0], -65504.0) - - # Mode 0x02 (2-region transformed 11-bit base, deltas (5,4,4)) with partition 1. - # Subset 0: R=1000, Subset 1: R=1000+10=1010..1000-6=994. - blk02 = pack_bc6h_block( - 0x02, part=1, - fields=[[1000, 0, 10, (-6) & 0x1F], [0, 0, 0, 0], [0, 0, 0, 0]], - indices=[0] * 16, - ) - px02 = ttpf.decode_pixels(95, blk02, 1, 1) - sm1 = ttpf._bptc.load_bc7()["partition2"][1] - exp_s0 = ttpf._bc6h_finish(ttpf._bc6h_unquantize(1000, 11, False), False, lut) - exp_s1 = ttpf._bc6h_finish(ttpf._bc6h_unquantize(1010, 11, False), False, lut) - for p, sub in enumerate(sm1): - self.assertEqual(px02[p][0], exp_s0 if sub == 0 else exp_s1, f"mode 0x02 pixel {p}") - - # Mode 0x1E (2-region untransformed 6-bit) in SF16: negative subset 1 endpoint. - blk1e = pack_bc6h_block( - 0x1E, part=0, - fields=[[16, 16, (-16) & 0x3F, (-16) & 0x3F], [0, 0, 0, 0], [0, 0, 0, 0]], - indices=[0] * 16, - ) - px1e = ttpf.decode_pixels(96, blk1e, 1, 1) - self.assertGreater(px1e[0][0], 0.0) - self.assertEqual(px1e[2][0], -px1e[0][0]) - - def test_hdr_tonemap_metric(self): - same = [(0.0, 1.0, 500.0), (1000.0, 0.25, 65504.0)] - self.assertEqual(ttpf.mean_abs_error(same, same, hdr=True), 0.0) - # Bounded even on extreme HDR highlights. - hi_err = ttpf.mean_abs_error([(0.0, 0.0, 0.0)], [(65504.0, 65504.0, 65504.0)], hdr=True) - self.assertGreater(hi_err, 250.0) - self.assertLess(hi_err, 255.0) - # Signed sensitivity for SF16: -1.0 -> -127.5, +1.0 -> +127.5 -> diff = 255.0. - sign_err = ttpf.mean_abs_error([(-1.0, -1.0, -1.0)], [(1.0, 1.0, 1.0)], hdr=True) - self.assertAlmostEqual(sign_err, 255.0, places=5) - - -class Bc2AndBc3CheckTest(unittest.TestCase): - def run_check(self, fmt, lower_colour): - import io - from contextlib import redirect_stdout - # Black then white, selector 3: the high-resolution image is uniform gray 170. - top_colour = struct.pack(" None: - # Explicit alpha bytes precede the color block. Black comes before - # white, but BC2 still uses both interpolated colors. - block = struct.pack(" black): selector 1 = black, selector 0 = white. -BC1_LEFT_BLACK = struct.pack(" 3x2 blocks: a flat zip of 2x1 predictions would misalign rows. - ((20, 12), bc1_column(4), bc1_column(2), 0.0), - ((20, 12), bc1_column(4), bc1_black, 85.0), - # Child texels 6-7 are padding: only the visible half of the edge block counts. - ((12, 8), bc1_black, bc1_column(1, BC1_LEFT_BLACK), 0.0), - ((12, 8), bc1_black, bc1_column(1, BC1_LEFT_WHITE), 127.5), - # Parent texels 10-11 are padding and must not leak into child texel 4. - ((10, 8), bc1_column(2, BC1_LEFT_BLACK), bc1_black, 0.0), - ((10, 8), bc1_column(2, BC1_LEFT_WHITE), bc1_black, 127.5), - ) - for (w, h), parent_fn, child_fn, expected in cases: - with self.subTest(size=(w, h), expected=expected): - self.assertAlmostEqual(pair_error(odd_mip(0, w, h), parent_fn, - odd_mip(1, w // 2, h // 2), child_fn), - expected, places=9) - - def test_matches_block_downsample_on_power_of_two_chains(self): - rng = random.Random(1) - for w, h in ((16, 8), (8, 8), (4, 4), (2, 2), (1, 1)): - with self.subTest(size=(w, h)): - parent = odd_mip(0, w, h) - child = odd_mip(1, max(1, w // 2), max(1, h // 2)) - bw, bh = parent["blocks_w"], parent["blocks_h"] - data = bytes(rng.randrange(256) for _ in range(8 * bw * bh)) - px = ttpf.decode_pixels(71, data, bw, bh) - old = ttpf.downsample2(ttpf.block_means(px, bw, bh, w, h), bw, bh) - new = ttpf.predict_child_means(px, parent, child) - self.assertEqual(len(new), len(old)) - for a, b in zip(new, old): - for x, y in zip(a, b): - self.assertAlmostEqual(x, y, places=9) - - def test_matches_nested_list_box_filter_on_odd_sizes(self): - rng = random.Random(2) - for w, h in ((28, 20), (22, 14), (6, 1), (1, 6)): - with self.subTest(size=(w, h)): - parent = odd_mip(0, w, h) - child = odd_mip(1, max(1, w // 2), max(1, h // 2)) - bw, bh = parent["blocks_w"], parent["blocks_h"] - px = ttpf.decode_pixels(71, bytes(rng.randrange(256) for _ in range(8 * bw * bh)), bw, bh) - grid = [[px[y * bw * 4 + x] for x in range(w)] for y in range(h)] - cw, ch = child["pixels_w"], child["pixels_h"] - texels = [[tuple(sum(grid[min(h - 1, 2 * y + dy)][min(w - 1, 2 * x + dx)][k] - for dy in (0, 1) for dx in (0, 1)) / 4 for k in range(3)) - for x in range(cw)] for y in range(ch)] - expected = [] - for by in range(0, ch, 4): - for bx in range(0, cw, 4): - cell = [t for row in texels[by:by + 4] for t in row[bx:bx + 4]] - expected.append(tuple(sum(t[k] for t in cell) / len(cell) for k in range(3))) - got = ttpf.predict_child_means(px, parent, child) - self.assertEqual(len(got), child["blocks_w"] * child["blocks_h"]) - for a, b in zip(got, expected): - for x, y in zip(a, b): - self.assertAlmostEqual(x, y, places=9) - - def test_mismatched_geometry_is_rejected(self): - parent = odd_mip(0, 12, 8) - px = ttpf.decode_pixels(71, BC1_BLACK * 6, 3, 2) - for child in (odd_mip(1, 5, 4), odd_mip(1, 6, 3), dict(odd_mip(1, 6, 4), blocks_w=1)): - with self.subTest(child=child), self.assertRaises(ttpf.MipGeometryError): - ttpf.predict_child_means(px, parent, child) - with self.assertRaises(ttpf.MipGeometryError): - ttpf.predict_child_means(px[:-1], parent, odd_mip(1, 6, 4)) - with self.assertRaises(ttpf.MipGeometryError): - ttpf.visible_block_means([(0.0, 0.0, 0.0)], odd_mip(1, 6, 4)) - with self.assertRaises(ValueError): - ttpf.mean_abs_error([(0.0, 0.0, 0.0)], [(0.0, 0.0, 0.0)] * 2) - - -def linear_layout(sizes, first_tail=0, depth=1): - """Fake layout storing each mip block-linear, mip-major across `depth` slices.""" - mips, off = [], 0 - for i, (w, h) in enumerate(sizes): - m = odd_mip(i, w, h) - m.update(offset=off, region=8 * m["blocks_w"] * m["blocks_h"], tile_x=0, tile_y=0) - m["slice_stride"] = m["region"] - mips.append(m) - off += m["region"] * depth - return dict(mips=mips, size=off, slice_size=off // depth, face_size=off, tile=4096, - first_tail=first_tail, element_bytes=8) - - -def run_shape_check(shape, sizes, chunks, first_tail=0, depth=1): - layout = linear_layout(sizes, first_tail, depth) - if shape == "cubemap": - layout.update(data_offset=0, full_bytes=6 * layout["size"], snapshots=1) - w, h = sizes[0] - d = dict(base=0, format=71, width=w, height=h, depth=depth, mips=len(sizes), non_tail=0) - a = dict(layout=layout, descriptor=d, available=True, full_chain=True) - if shape != "2d": - a["shape"] = shape - tiled = b"".join(chunks) + bytes(1 << 17) - buf = io.StringIO() - with mock.patch.object(ttpf, "analyze", lambda pool, index: a), \ - mock.patch.object(ttpf, "_read_range_or_block", lambda *args, **kw: tiled), \ - mock.patch.object(ttpf, "detile", lambda lay, mip, data: bytes( - data[:8 * mip["blocks_w"] * mip["blocks_h"]])), \ - redirect_stdout(buf): - code = ttpf.check(None, 0) - return code, json.loads(buf.getvalue()) - - -class OddBlockShapeCheckTest(unittest.TestCase): - """check() on 12x8 -> 6x4 BC1 (3x2 parent blocks) for each 2D-family shape. The container - and tiling are faked (block-linear mips); OddBlockPoolTest covers the real path.""" - SIZES = ((12, 8), (6, 4)) - - def chunk(self, level, block_fn): - return bc1_blocks(odd_mip(level, *self.SIZES[level]), block_fn) - - def test_2d_edge_column_and_tail_origin(self): - parent = self.chunk(0, bc1_column(2)) - code, result = run_shape_check("2d", self.SIZES, [parent, self.chunk(1, bc1_column(1))], - first_tail=1) - self.assertEqual(code, 0, result) - self.assertEqual(result["chain_error"], [0.0]) - # The fake tile-origin read sees parent blocks 0-1 (black) where the white edge belongs. - self.assertEqual(result["tail_origin_control"], 127.5) - code, result = run_shape_check("2d", self.SIZES, [parent, self.chunk(1, bc1_black)], - first_tail=1) - self.assertEqual(code, 1, result) - self.assertEqual(result["chain_error"], [127.5]) - - def test_array_reports_the_slice_with_a_dropped_edge(self): - parents = [self.chunk(0, bc1_column(2))] * 3 - children = [self.chunk(1, bc1_column(1)), self.chunk(1, bc1_black), - self.chunk(1, bc1_column(1))] - code, result = run_shape_check("2d_array", self.SIZES, parents + children, depth=3) - self.assertEqual(code, 1, result) - self.assertEqual(result["per_slice_max_error"], [0.0, 127.5, 0.0]) - self.assertEqual(result["max_error"], 127.5) - - def test_cube_reports_the_face_with_a_dropped_edge_and_tail_origin(self): - chunks = [] - for face in range(6): - chunks += [self.chunk(0, bc1_column(2)), - self.chunk(1, bc1_black if face == 4 else bc1_column(1))] - code, result = run_shape_check("cubemap", self.SIZES, chunks, first_tail=1) - self.assertEqual(code, 1, result) - self.assertEqual(result["per_face_max_error"], [0.0, 0.0, 0.0, 0.0, 127.5, 0.0]) - self.assertEqual(result["tail_origin_control"], 127.5) - - def test_mismatched_mip_geometry_is_blocked(self): - sizes = ((12, 8), (5, 4)) - chunks = [bc1_blocks(odd_mip(0, 12, 8), bc1_black), bc1_blocks(odd_mip(1, 5, 4), bc1_black)] - code, result = run_shape_check("2d", sizes, chunks) - self.assertEqual(code, 2, result) - self.assertIn("geometry", result["blocked"]) - - -def odd_bc1_pool(path, width, height, parent_fn, child_fn): - """Write a two-mip BC1 pool through the real layout and tiling.""" - layout = ttpf.surface_layout(width, height, 71, 2, 4096) - payload = bytearray(layout["size"]) - for mip, block_fn in zip(layout["mips"], (parent_fn, child_fn)): - retile_to(layout, mip, bc1_blocks(mip, block_fn), payload) - non_tail = layout["first_tail"] - record = pack_etpf_record(width, height, 2 - non_tail, non_tail, 71, 1, 1, 2, 4096) - write_rds5_pool(path, [record], [payload]) - - -class OddBlockPoolTest(unittest.TestCase): - """Before the fix the changed 12x8, 8x12 and 12x12 children passed with error 0.""" - CASES = ( - # (width, height, parent, child, rc, chain_error) - (12, 8, bc1_black, bc1_black, 0, [0.0]), - (12, 8, bc1_black, bc1_single(1, 0), 1, [127.5]), - (8, 12, bc1_black, bc1_black, 0, [0.0]), - (8, 12, bc1_black, bc1_single(0, 1), 1, [127.5]), - (12, 12, bc1_black, bc1_black, 0, [0.0]), - (12, 12, bc1_black, bc1_single(1, 1), 1, [63.75]), - (12, 8, bc1_column(2), bc1_column(1), 0, [0.0]), - (16, 8, bc1_black, bc1_black, 0, [0.0]), - (16, 8, bc1_black, bc1_single(1, 0), 1, [127.5]), - (256, 256, bc1_black, bc1_black, 0, [0.0]), - (256, 256, bc1_black, bc1_single(31, 31), 0, [0.25]), - ) - - def run_check(self, *case): - with tempfile.TemporaryDirectory() as tmp: - path = os.path.join(tmp, "odd.ttpf") - odd_bc1_pool(path, *case) - pool = ttpf.Pool(path) - buf = io.StringIO() - try: - with redirect_stdout(buf): - code = ttpf.check(pool, 0) - finally: - pool.close() - return code, json.loads(buf.getvalue()) - - def test_odd_block_counts_cover_every_child_block(self): - for w, h, parent_fn, child_fn, rc, errs in self.CASES: - with self.subTest(size=(w, h), rc=rc, chain_error=errs): - code, result = self.run_check(w, h, parent_fn, child_fn) - self.assertEqual(code, rc, result) - self.assertEqual(result["chain_error"], errs) - - def test_cli_rejects_a_dropped_edge_block(self): - with tempfile.TemporaryDirectory() as tmp: - path = os.path.join(tmp, "odd.ttpf") - odd_bc1_pool(path, 12, 8, bc1_black, bc1_single(1, 0)) - proc = subprocess.run([sys.executable, "-I", TOOL, "check", path, "0"], - capture_output=True, text=True, check=False) - self.assertEqual(proc.returncode, 1, proc.stdout + proc.stderr) - result = json.loads(proc.stdout) - self.assertEqual(result["max_error"], 127.5) - self.assertTrue(result["full_chain"]) - - -class VisibleExportTest(unittest.TestCase): - """Before the fix 17x13 BC1 exported its 2x2-block child as 3x2 storage blocks (208 bytes).""" - RED = (255, 0, 0) - - def test_export_packs_visible_blocks_only(self): - def child(x, y): - return solid_bc1(self.RED) if y == 1 else bc1_black(x, y) - for w, h in ((17, 13), (17, 16), (16, 13), (16, 16)): - with self.subTest(size=(w, h)), tempfile.TemporaryDirectory() as tmp: - path, out = os.path.join(tmp, "edge.ttpf"), os.path.join(tmp, "edge.dds") - odd_bc1_pool(path, w, h, bc1_black, child) - pool = ttpf.Pool(path) - try: - with redirect_stdout(io.StringIO()): - self.assertEqual(ttpf.export(pool, 0, out), 0) - finally: - pool.close() - with open(out, "rb") as f: - blob = f.read() - pw, ph, cw, ch = (w + 3) // 4, (h + 3) // 4, (w // 2 + 3) // 4, (h // 2 + 3) // 4 - self.assertEqual(len(blob) - 148, 8 * (pw * ph + cw * ch)) - self.assertEqual(struct.unpack_from(" None: - layout = self.layout - linear = solid_chain(layout) - payload = bytearray(layout["size"]) - for mip in layout["mips"]: - retile_to(layout, mip, linear[mip["index"]], payload) - top_start = layout["mips"][0]["offset"] - path = os.path.join(self.tmp.name, "partially-readable.ttpf") - record = pack_etpf_record(256, 256, 6, 1, 71, 1, 1, 4, 4096, meta=0x103) - write_rds5_pool(path, [record], [payload[:top_start], payload[top_start:]]) - # Give the lower mip chunk an unsupported codec. The second chunk is still valid zlib. - with open(path, "r+b") as f: - f.seek(24) - entry, = struct.unpack(" None: - # Room for exactly one key after the descriptors: the other two sit in the ID region. - with tempfile.TemporaryDirectory() as tmp: - path = self.write(tmp, "straddle.ttpf", area=self.RECORDS * 16 + 8) - self.assertEqual(self.keys(path), [0x1234567890ABCDEF + i for i in range(self.RECORDS)]) - - def test_keys_inside_the_record_area_are_unchanged(self) -> None: - with tempfile.TemporaryDirectory() as tmp: - path = self.write(tmp, "plain.ttpf") - self.assertEqual(self.keys(path), [0x1234567890ABCDEF + i for i in range(self.RECORDS)]) - - def test_a_key_split_by_the_records_ids_boundary_is_refused(self) -> None: - # A record area that cuts the first key in half, as TtpfReader refuses it. - with tempfile.TemporaryDirectory() as tmp: - path = self.write(tmp, "split.ttpf", area=self.RECORDS * 16 + 4) - with closing(ttpf.Pool(path)) as pool: - with self.assertRaises(ValueError): - pool.descriptor(0) - - -class PoolCacheTest(unittest.TestCase): - def test_zlib_chunk_rejects_a_decoded_size_larger_than_its_range(self) -> None: - with tempfile.TemporaryDirectory() as temp: - path = os.path.join(temp, "pool.ttpf") - record = pack_etpf_record(4, 4, 1, 0, 71, 1, 1, 4, 4096) - write_rds5_pool(path, [record], [bytes(8192)]) - with open(path, "r+b") as stream: - stream.seek(8) - stream.write(struct.pack(" None: - with tempfile.TemporaryDirectory() as temp, ExitStack() as stack: - record = pack_etpf_record(4, 4, 1, 0, 71, 1, 1, 4, 4096) - pools = [] - payloads = (bytes((0x11,)) * 4096, bytes((0x22,)) * 4096) - for i, payload in enumerate(payloads): - path = os.path.join(temp, f"pool_{i}.ttpf") - write_rds5_pool(path, [record], [payload]) - pools.append(stack.enter_context(closing(ttpf.Pool(path)))) - self.assertEqual(pools[0].chunks, pools[1].chunks) - cache = {} - for pool, payload in zip(pools, payloads): - self.assertEqual(pool.read_range(4096, 4096, cache), payload) - self.assertEqual(pools[0].read_range(4096, 4096, cache), payloads[0]) - - -class SyntheticBcpackPoolTest(unittest.TestCase): - def setUp(self): - self.tmp = tempfile.TemporaryDirectory() - self.addCleanup(self.tmp.cleanup) - - def test_bc4_and_bc5_decode_pixels(self): - bc4_blk = bytes([200, 100]) + (0).to_bytes(6, "little") - px4 = ttpf.decode_pixels(80, bc4_blk, 1, 1) - self.assertEqual(len(px4), 16) - self.assertEqual(px4[0], (200.0, 200.0, 200.0)) - bc5_blk = bc4_blk + bytes([50, 25]) + (0).to_bytes(6, "little") - px5 = ttpf.decode_pixels(83, bc5_blk, 1, 1) - self.assertEqual(len(px5), 16) - self.assertEqual(px5[0], (200.0, 50.0, 0.0)) - - def test_bc1_bcpack_pool_check_export_and_scan(self): - import io - from contextlib import redirect_stdout - path = os.path.join(self.tmp.name, "bc1_bcpack.ttpf") - layout, linear, expected_tiled = build_bc1_bcpack_pool(path) - pool = ttpf.Pool(path) - self.addCleanup(pool.close) - - a = ttpf.analyze(pool, 0) - self.assertTrue(a["full_chain"]) - self.assertEqual(a["mip_codecs"][0], [1]) - with self.assertRaises(ttpf.BcpackRequired): - pool.read_range(a["descriptor"]["base"], layout["size"], bcpack_mode="off") - self.assertEqual(pool.read_range(a["descriptor"]["base"], layout["size"]), expected_tiled) - - buf = io.StringIO() - with redirect_stdout(buf): - code = ttpf.check(pool, 0) - res = json.loads(buf.getvalue()) - self.assertEqual(code, 0, res) - self.assertLess(res["max_error"], 4.0) - - out_dds = os.path.join(self.tmp.name, "bc1_bcpack.dds") - with redirect_stdout(io.StringIO()): - self.assertEqual(ttpf.export(pool, 0, out_dds), 0) - with open(out_dds, "rb") as f: - dds = f.read() - self.assertEqual(dds[148:], b"".join(linear[m["index"]] for m in layout["mips"])) - - scan_out = os.path.join(self.tmp.name, "scan_bcpack.json") - with redirect_stdout(io.StringIO()): - ttpf.scan_pools([path], scan_out) - with open(scan_out, encoding="utf-8") as f: - total = json.load(f)["total"] - self.assertEqual((total["after_full"], total["after_skip"]), (0, 1)) - self.assertEqual((total["after_bcpack_full"], total["after_bcpack_skip"], - total["bcpack_unlocked_full"]), (1, 0, 1)) - - def test_provisional_history_strict_refusal_and_opt_in(self): - import io - from contextlib import redirect_stdout - path = os.path.join(self.tmp.name, "bc1_prov.ttpf") - layout = ttpf.surface_layout(64, 64, 71, 5, ttpf.tile_bytes(4)) - nblocks = layout["size"] // 8 - # Block 0 references provisional entry 6 (256 + 0 - 250 = 6). - build_bc1_bcpack_pool(path, ref_dists=[250] + [0] * (nblocks - 1)) - pool = ttpf.Pool(path) - self.addCleanup(pool.close) - - buf = io.StringIO() - with redirect_stdout(buf): - code_strict = ttpf.check(pool, 0) - self.assertEqual(code_strict, 2) - self.assertIn("provisional BCPack history required", json.loads(buf.getvalue())["blocked"]) - - buf2 = io.StringIO() - with redirect_stdout(buf2): - code_prov = ttpf.check(pool, 0, allow_provisional=True) - self.assertEqual(code_prov, 0, buf2.getvalue()) - - def test_bc7_bcpack_pool_export_and_scan(self): - import io - from contextlib import redirect_stdout - sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) - import test_bcpack as tb - - # 64x64 DXGI 98 (BC7_UNORM, 16-byte blocks), 1 mip, 4 KiB tiles, codec 7. - layout = ttpf.surface_layout(64, 64, 98, 1, ttpf.tile_bytes(4)) - mip = layout["mips"][0] - nblocks = mip["blocks_w"] * mip["blocks_h"] - # Solid mode-6 BC7 blocks with distinct per-block endpoints. - linear = bytearray() - for i in range(nblocks): - r0 = (i * 5) & 0x7F - g0 = (i * 3 + 17) & 0x7F - b0 = (i * 7 + 31) & 0x7F - acc = (1 << 6) | (r0 << 7) | (r0 << 14) | (g0 << 21) | (g0 << 28) | (b0 << 35) | (b0 << 42) - acc |= (0x7F << 49) | (0x7F << 56) | (1 << 63) | (1 << 64) - linear += acc.to_bytes(16, "little") - payload = bytearray(layout["size"]) - retile_to(layout, mip, bytes(linear), payload) - # Fill any unused tail padding blocks in the tile with mode-6 blocks too. - mode6_pad = (1 << 6).to_bytes(16, "little") - for off in range(0, len(payload), 16): - if payload[off:off + 16] == b"\x00" * 16: - payload[off:off + 16] = mode6_pad - packed_payload = tb.encode_bc7_mode6_blocks(bytes(payload)) - - path = os.path.join(self.tmp.name, "bc7_bcpack.ttpf") - pad = (-len(packed_payload)) % 256 - count = 3 - table_end = 24 + (count - 1) * 8 - etpf = ttpf.align(table_end, 256) - padded = ttpf.align(16 + 24 + 32, 4096) - source = etpf + padded - chunk_end = source + len(packed_payload) + pad - virt = padded - vsize = virt + layout["size"] - entry = (source // 256) | (7 << 26) | ((virt // 4096) << 30) | (pad << 52) - sentinel = (chunk_end // 256) | ((vsize // 4096) << 30) - header = bytearray(24) - header[0:4] = b"RDS5" - struct.pack_into(" 6 | (21 << 5) = 0x2A6 - meta = 6 | (21 << 5) - base = ttpf.align(16 + 24 + 32, 4096) - packed_mips = mips - non_tail - rec = pack_etpf_record(width, height, packed_mips, non_tail, fmt, depth, 2, mode, - base, meta=meta, extra=extra) - write_rds5_pool(path, [rec], chunks) - return layout, linear_faces - - def test_cubemap_mode18_and_streaming_mode20(self): - import io - from contextlib import redirect_stdout - - for non_tail, mode, expected_offset, expected_pages in [ - (0, 18, 0, ()), - (1, 20, 6 * 4096, (6, 18)), - ]: - with self.subTest(non_tail=non_tail, mode=mode): - path = os.path.join(self.tmp.name, f"cube_mode{mode}.ttpf") - layout, linear_faces = self._build_cubemap_pool(path, non_tail=non_tail, mode=mode) - pool = ttpf.Pool(path) - self.addCleanup(pool.close) - - a = ttpf.analyze(pool, 0) - self.assertEqual(a["shape"], "cubemap") - self.assertTrue(a["span_matches"]) - self.assertTrue(a["full_chain"]) - self.assertEqual(a["layout"]["data_offset"], expected_offset) - - ok_meta, pages = ttpf.validate_chunk_metadata(pool, a["descriptor"], a["allocation_span"]) - self.assertTrue(ok_meta) - self.assertEqual(pages, expected_pages) - - desc = ttpf.describe(pool, 0) - self.assertEqual(desc["shape"], "cubemap") - self.assertEqual(desc["data_offset"], expected_offset) - self.assertEqual(desc["snapshots"], non_tail + 1) - - buf = io.StringIO() - with redirect_stdout(buf): - rc = ttpf.check(pool, 0) - res = json.loads(buf.getvalue()) - self.assertEqual(rc, 0, res) - self.assertEqual(len(res["per_face_max_error"]), 6) - self.assertLessEqual(res["max_error"], 6.0) - self.assertGreater(res["tail_origin_control"], 5 * res["max_error"]) - - out_dds = os.path.join(self.tmp.name, f"cube_mode{mode}.dds") - with redirect_stdout(io.StringIO()): - self.assertEqual(ttpf.export(pool, 0, out_dds), 0) - with open(out_dds, "rb") as f: - dds = f.read() - self.assertEqual(dds[:4], b"DDS ") - caps2 = struct.unpack_from(" 1 else 1) - buf = bytearray(layout["full_bytes"]) - for face in range(6): - color = (face * 35, 60 + face * 25, 20 + face * 30) - for m in layout["mips"]: - lin = solid_bc1(color) * (m["blocks_w"] * m["blocks_h"]) - retile_to(layout, m, lin, buf, base_offset=face * layout["face_size"]) - path = os.path.join(self.tmp.name, name) - rec = pack_etpf_record(w, h, mips, 0, 71, 6, 2, 18, base, meta=0, extra=0) - write_rds5_pool(path, [rec], [bytes(buf)]) - pool = ttpf.Pool(path) - self.addCleanup(pool.close) - out = io.StringIO() - with redirect_stdout(out): - rc = ttpf.check(pool, 0) - self.assertEqual(rc, 0) - res = json.loads(out.getvalue()) - self.assertEqual(res["first_tail"], 0 if mips > 1 else 1) - self.assertIsNone(res["tail_origin_control"]) - if mips == 1: - self.assertIsNone(res["max_error"]) - else: - self.assertLessEqual(res["max_error"], 1.0) - - # Mid-chunk base mismatch rejected by validate_chunk_metadata. - misaligned = os.path.join(self.tmp.name, "cube_mid_chunk.ttpf") - rec = pack_etpf_record(32, 32, 1, 0, 71, 6, 2, 18, base + 4096, meta=6, extra=0) - write_rds5_pool(misaligned, [rec], [bytes(6 * 4096)]) - pool_m = ttpf.Pool(misaligned) - self.addCleanup(pool_m.close) - ok_meta, _ = ttpf.validate_chunk_metadata(pool_m, pool_m.descriptor(0), 6 * 4096) - self.assertFalse(ok_meta) - - # non_tail == 3 alignment-padding validation (align_group 1/2/3 positive + negative). - # Group 1: chunk0 (4 pages) + pad (12) == 16; chunks = [4, 16, 64]. - # Group 2: chunk0 (1) + chunk1 (3) + pad (12) == 16. - # Group 3: chunk0 (1) + chunk1 (3) + pad (4) == 8. - cases = [ - ("g1_ok", (4 | (11 << 5) | (15 << 10)), (1 << 19) | (12 << 21), [4, 16, 64], True), - ("g1_bad", (4 | (11 << 5) | (15 << 10)), (1 << 19) | (11 << 21), [4, 16, 64], False), - ("g2_ok", (1 | (3 << 5) | (11 << 10)), (2 << 19) | (12 << 21), [1, 3, 16], True), - ("g3_ok", (1 | (3 << 5) | (8 << 10)), (3 << 19) | (4 << 21), [1, 3, 8], True), - ("g0_bad", (1 | (3 << 5) | (8 << 10)), (0 << 19) | (4 << 21), [1, 3, 8], False), - ] - for tag, val20, hi_extra, page_counts, expected in cases: - meta = val20 & 0x7FF - extra = ((val20 >> 11) & 0x1FF) | hi_extra - p_path = os.path.join(self.tmp.name, f"align_{tag}.ttpf") - chunks = [bytes(pg * 4096) for pg in page_counts] - span = sum(len(c) for c in chunks) - r = pack_etpf_record(256, 256, 6, 3, 71, 1, 1, 4, base, meta=meta, extra=extra) - write_rds5_pool(p_path, [r], chunks) - pl = ttpf.Pool(p_path) - self.addCleanup(pl.close) - ok_al, _ = ttpf.validate_chunk_metadata(pl, pl.descriptor(0), span) - self.assertEqual(ok_al, expected, tag) - - -class SyntheticVolumePoolTest(unittest.TestCase): - def setUp(self): - self.tmp = tempfile.TemporaryDirectory() - self.addCleanup(self.tmp.cleanup) - - def _build_volume_pool(self, path, width, height, depth, fmt, mips=1, mode=2): - eb = ttpf.element_bytes(fmt) - if fmt in ttpf.VOLUME_FLOAT_FORMATS and mips == 1: - layout = ttpf.volume_surface_layout(width, height, depth, mips, eb) - channels = ttpf.VOLUME_FLOAT_FORMATS[fmt] - vals = [] - for z in range(depth): - for y in range(height): - for x in range(width): - if channels == 1: - vals.append(10.0 + 0.05 * z + 0.1 * x + 0.1 * y) - else: - vals.extend(( - 10.0 + 0.02 * z + 0.05 * x, - 5.0 + 0.02 * z + 0.05 * y, - 8.0 + 0.01 * z, - 1.0, - )) - linear = struct.pack(f"<{len(vals)}e", *vals) - tiled = retile_volume(layout, linear) - else: - layout = None - linear = b"" - tiled = b"\x00" * 4096 - base = ttpf.align(16 + 24 + 32, 4096) - rec = pack_etpf_record(width, height, mips, 0, fmt, depth, 3, mode, base) - write_rds5_pool(path, [rec], [tiled]) - return layout, linear, tiled - - def test_volume_fmt54_and_fmt10_round_trip_check_export_and_scan(self): - import io - from contextlib import redirect_stdout - - cases = [ - # fmt=54 (R16_FLOAT): depth=8 pads to block_d=16 -> padded_d=16 - (16, 8, 8, 54, 16, 16), - # fmt=10 (R16G16B16A16_FLOAT): block_d=8 -> padded_d=8 - (8, 8, 8, 10, 8, 8), - ] - for w, h, d, fmt, exp_bd, exp_pd in cases: - with self.subTest(dims=(w, h, d), fmt=fmt): - path = os.path.join(self.tmp.name, f"vol_fmt{fmt}.ttpf") - layout, linear, tiled = self._build_volume_pool(path, w, h, d, fmt) - pool = ttpf.Pool(path) - self.addCleanup(pool.close) - - a = ttpf.analyze(pool, 0) - self.assertEqual(a["shape"], "volume") - self.assertTrue(a["span_matches"]) - self.assertTrue(a["full_chain"]) - self.assertEqual((a["layout"]["block_d"], a["layout"]["padded_d"]), (exp_bd, exp_pd)) - - desc = ttpf.describe(pool, 0) - self.assertEqual(desc["shape"], "volume") - self.assertEqual((desc["block_d"], desc["padded_d"]), (exp_bd, exp_pd)) - - # Byte-exact 3D detile round-trip. - self.assertEqual(ttpf.detile_volume(layout, tiled), linear) - - buf = io.StringIO() - with redirect_stdout(buf): - rc = ttpf.check(pool, 0) - res = json.loads(buf.getvalue()) - self.assertEqual(rc, 0, res) - self.assertLess(res["volume_3d_z_diff"], 0.5 * res["volume_2d_control_z_diff"]) - - out_dds = os.path.join(self.tmp.name, f"vol_fmt{fmt}.dds") - with redirect_stdout(io.StringIO()): - self.assertEqual(ttpf.export(pool, 0, out_dds), 0) - with open(out_dds, "rb") as f: - dds = f.read() - self.assertEqual(dds[:4], b"DDS ") - dds_depth = struct.unpack_from(" +64 bytes); pixel (x=0, y=4) sets Y2 (bit 7 -> +128 bytes). - layout = ttpf.surface_layout(128, 128, 28, 1, tile=65536) - mip = layout["mips"][0] - tiled = bytearray(65536) - tiled[64:68] = b"\x11\x22\x33\x44" - tiled[128:132] = b"\x55\x66\x77\x88" - det = ttpf.detile(layout, mip, bytes(tiled)) - self.assertEqual(det[4 * 4:4 * 4 + 4], b"\x11\x22\x33\x44") - self.assertEqual(det[(4 * 128) * 4:(4 * 128) * 4 + 4], b"\x55\x66\x77\x88") - - def test_decode_pixels_all_validated_uncompressed_formats(self): - self.assertEqual(ttpf.ELEMENT_BYTES[11], 8) - for fmt in sorted(ttpf.UNCOMPRESSED_2D_FORMATS): - with self.subTest(fmt=fmt): - raw = self._encode_pixel(fmt, 64, 128, 192, 255) - px = ttpf.decode_pixels(fmt, raw, 1, 1) - self.assertEqual(len(px), 1) - r, g, b = px[0] - if fmt in (61, 65, 56): - self.assertAlmostEqual(r, 64.0, places=3) - self.assertAlmostEqual(g, 64.0, places=3) - self.assertAlmostEqual(b, 64.0, places=3) - elif fmt == 49: - self.assertEqual((r, g, b), (64.0, 128.0, 0.0)) - elif fmt == 54: - self.assertAlmostEqual(r, 1.0, places=3) - self.assertAlmostEqual(g, 1.0, places=3) - self.assertAlmostEqual(b, 1.0, places=3) - elif fmt == 10: - self.assertAlmostEqual(r, 1.0, places=3) - self.assertAlmostEqual(g, 2.0, places=3) - self.assertAlmostEqual(b, 3.0, places=3) - else: # 11, 28, 29, 87, 91 - self.assertAlmostEqual(r, 64.0, places=3) - self.assertAlmostEqual(g, 128.0, places=3) - self.assertAlmostEqual(b, 192.0, places=3) - # Non-finite float16 values clamp cleanly in _hdr_tonemap. - self.assertEqual(ttpf._hdr_tonemap(float("nan")), 0.0) - self.assertEqual(ttpf._hdr_tonemap(float("inf")), 255.0) - self.assertEqual(ttpf._hdr_tonemap(float("-inf")), -255.0) - - def test_uncompressed_2d_check_export_and_scan(self): - import io - from contextlib import redirect_stdout, redirect_stderr - - cases = [ - # (name, w, h, fmt, mips, mode, expect_tail_control) - ("dxgi11_1mip_4k", 8, 4, 11, 1, 2, False), - ("dxgi11_multi_4k", 32, 32, 11, 4, 2, True), - ("dxgi28_multi_64k", 256, 256, 28, 5, 0, True), - ("dxgi28_odd_4k", 17, 13, 28, 4, 2, True), - ("dxgi49_multi_4k", 64, 64, 49, 4, 2, True), - ("dxgi56_multi_4k", 64, 64, 56, 4, 2, True), - ("dxgi54_multi_64k", 128, 128, 54, 3, 0, False), - ("dxgi61_multi_64k", 256, 256, 61, 4, 0, True), - ("dxgi65_multi_4k", 64, 64, 65, 5, 2, True), - ("dxgi87_multi_4k", 64, 64, 87, 5, 2, True), - ("dxgi10_multi_4k", 32, 32, 10, 4, 2, True), - ] - for name, w, h, fmt, mips, mode, expect_ctrl in cases: - with self.subTest(case=name): - path = os.path.join(self.tmp.name, f"{name}.ttpf") - _, expected_payload = self._build_uncompressed_pool(path, w, h, fmt, mips, mode) - pool = ttpf.Pool(path) - self.addCleanup(pool.close) - - buf = io.StringIO() - with redirect_stdout(buf): - rc = ttpf.check(pool, 0) - res = json.loads(buf.getvalue()) - self.assertEqual(rc, 0, res) - if mips > 1: - self.assertLessEqual(res["max_error"], 1.0, res) - if expect_ctrl and res["tail_origin_control"] is not None: - self.assertGreater(res["tail_origin_control"], 6.0, res) - - out_dds = os.path.join(self.tmp.name, f"{name}.dds") - with redirect_stdout(io.StringIO()): - erc = ttpf.export(pool, 0, out_dds) - self.assertEqual(erc, 0) - with open(out_dds, "rb") as f: - dds = f.read() - self.assertEqual(dds[:4], b"DDS ") - flags, dh, dw, pitch = struct.unpack_from("= 101)): - bits = sorted(abs(s) - (100 if s >= 101 else 0) for s in pat if keep(s)) - self.assertEqual(bits, list(range(1, len(bits) + 1)), axis) - - def test_tile_extents_follow_from_the_bit_order(self): - tex = sys.modules["tex_headers"] # imported by ttpf_mips.py - for log, pat in ttpf.VOLUME_PATTERNS_4K.items(): - with self.subTest(element_bytes=1 << log): - want = (1 << sum(0 < s < 100 for s in pat), 1 << sum(s < 0 for s in pat), 1 << sum(s >= 101 for s in pat)) - self.assertEqual(tex._VOLUME_4K_TILE[log], want) - lay = tex.volume_surface_layout(64, 64, 32, 1, 1 << log) - self.assertEqual((lay["block_w"], lay["block_h"], lay["block_d"]), want) - self.assertEqual(lay["z_tile_stride"] % 4096, 0) - - -class UnmappedSentinelSpanTest(unittest.TestCase): - def setUp(self): - self.tmp = tempfile.TemporaryDirectory() - self.addCleanup(self.tmp.cleanup) - - def test_span_skips_unmapped_sentinels_and_rejects_unmapped_base(self): - # A valid 256x256 BC1 texture followed by unmapped ETPF records (base=0 and base=0x1FFFFF*4096), - # and then a second valid texture, must resolve both mapped spans cleanly and return None for - # the unmapped records (including in scan_pools, which previously passed a negative span). - layout = ttpf.surface_layout(256, 256, 71, 7, ttpf.tile_bytes(4)) - size = layout["size"] - base0 = 4096 - base1 = base0 + size - rec0 = pack_etpf_record(256, 256, 5, 2, 71, 1, 1, 4, base0) - rec_zero = pack_etpf_record(256, 256, 5, 2, 71, 1, 1, 4, 0) - rec_max = pack_etpf_record(256, 256, 5, 2, 71, 1, 1, 4, 0x1FFFFF * 4096) - rec1 = pack_etpf_record(256, 256, 5, 2, 71, 1, 1, 4, base1) - - for label, recs, chunks, mapped_indices in ( - ("zero_between", [rec0, rec_zero, rec1], [bytes(size), bytes(size)], (0, 2)), - ("max_between", [rec0, rec_max, rec1], [bytes(size), bytes(size)], (0, 2)), - ("trailing_zero_and_max", [rec0, rec_zero, rec_max], [bytes(size)], (0,)), - ): - with self.subTest(case=label): - path = os.path.join(self.tmp.name, f"{label}.ttpf") - write_rds5_pool(path, recs, chunks) - pool = ttpf.Pool(path) - self.addCleanup(pool.close) - for idx in mapped_indices: - d = pool.descriptor(idx) - self.assertEqual(pool.span(idx, d["base"]), size) - a = ttpf.analyze(pool, idx) - self.assertTrue(a["span_matches"], a) - self.assertNotIn("blocked", a) - for idx in range(len(recs)): - if idx not in mapped_indices: - d = pool.descriptor(idx) - self.assertIsNone(pool.span(idx, d["base"])) - a = ttpf.analyze(pool, idx) - self.assertEqual(a["blocked"], "no mapped allocation") - scan_out = os.path.join(self.tmp.name, f"{label}.json") - with redirect_stdout(io.StringIO()): - ttpf.scan_pools([path], scan_out) - with open(scan_out, encoding="utf-8") as f: - total = json.load(f)["total"] - self.assertEqual(total["chunk_metadata_fail"], 0) - self.assertEqual(total["chunk_metadata_ok"], len(mapped_indices)) - - -class DetileFastPathTest(unittest.TestCase): - def test_coalesce_x_runs_merges_contiguous_blocks(self): - self.assertEqual(ttpf._coalesce_x_runs([], 16), []) - self.assertEqual(ttpf._coalesce_x_runs([0, 16, 32, 128, 144, 64], 16), - [(0, 48), (128, 32), (64, 16)]) - - def test_detile_matches_reference_formula_across_all_element_sizes_and_tiles(self): - def ref_detile(layout, mip, tiled): - pat = (ttpf.PATTERNS_4K if layout["tile"] == 4096 else ttpf.PATTERNS_64K)[ - {1: 0, 2: 1, 4: 2, 8: 3, 16: 4}[layout["element_bytes"]]] - bw, bh = layout["block_w"], layout["block_h"] - eb = layout["element_bytes"] - out = bytearray(mip["blocks_w"] * mip["blocks_h"] * eb) - for y in range(mip["blocks_h"]): - for x in range(mip["blocks_w"]): - off = ((y // bh) * (mip["padded_w"] // bw) + x // bw) * layout["tile"] - for bit, s in enumerate(pat): - if s > 0: - off |= (((x + mip["tile_x"]) >> (s - 1)) & 1) << bit - elif s < 0: - off |= (((y + mip["tile_y"]) >> (-s - 1)) & 1) << bit - at = (y * mip["blocks_w"] + x) * eb - out[at:at + eb] = tiled[off:off + eb] - return bytes(out) - - for fmt, eb in ((61, 1), (49, 2), (28, 4), (71, 8), (98, 16)): - for tile in (4096, 65536): - layout = ttpf.surface_layout(60, 44, fmt, 4, tile=tile) - for idx, mip in enumerate(layout["mips"]): - nbytes = max(mip["padded_w"] * mip["padded_h"] * eb, tile) - tiled = bytes((i * 131 + 17) & 255 for i in range(nbytes)) - with self.subTest(fmt=fmt, tile=tile, level=idx): - self.assertEqual(ttpf.detile(layout, mip, tiled), ref_detile(layout, mip, tiled)) - - # Truncated input falls back to the exact slice behavior without raising ValueError. - layout_t = ttpf.surface_layout(64, 64, 98, 1, tile=4096) - mip_t = layout_t["mips"][0] - short_tiled = bytes(range(200)) - self.assertEqual(ttpf.detile(layout_t, mip_t, short_tiled), ref_detile(layout_t, mip_t, short_tiled)) - - - @staticmethod - def _ref_detile(layout, mip, tiled): - pat = (ttpf.PATTERNS_4K if layout["tile"] == 4096 else ttpf.PATTERNS_64K)[ - {1: 0, 2: 1, 4: 2, 8: 3, 16: 4}[layout["element_bytes"]]] - bw, bh, eb = layout["block_w"], layout["block_h"], layout["element_bytes"] - out = bytearray(mip["blocks_w"] * mip["blocks_h"] * eb) - for y in range(mip["blocks_h"]): - for x in range(mip["blocks_w"]): - off = ((y // bh) * (mip["padded_w"] // bw) + x // bw) * layout["tile"] - for bit, s in enumerate(pat): - if s > 0: - off |= (((x + mip["tile_x"]) >> (s - 1)) & 1) << bit - elif s < 0: - off |= (((y + mip["tile_y"]) >> (-s - 1)) & 1) << bit - at = (y * mip["blocks_w"] + x) * eb - out[at:at + eb] = tiled[off:off + eb] - return bytes(out) - - def test_narrow_shapes_stream_and_match_reference(self): - for w, h in ((16384, 1), (1, 16384), (1, 1), (3, 1), (1, 3)): - for tile in (4096, 65536): - layout = ttpf.surface_layout(w, h, 28, 1, tile=tile) - mip = layout["mips"][0] - nbytes = max(mip["padded_w"] * mip["padded_h"] * 4, tile) - full = bytes((i * 131 + 17) & 255 for i in range(nbytes)) - for tiled in (full, full[:nbytes // 3 + 5]): # complete and truncated input - with self.subTest(w=w, h=h, tile=tile, size=len(tiled)): - self.assertEqual(ttpf.detile(layout, mip, tiled), - self._ref_detile(layout, mip, tiled)) - - def test_volume_slice_nonzero_z_truncated_matches_reference(self): - layout = ttpf.volume_surface_layout(16, 8, 8, 1, 2) - w, h, d = (layout["mips"][0][k] for k in ("blocks_w", "blocks_h", "blocks_d")) - linear = bytes((i * 7 + 3) & 255 for i in range(w * h * d * 2)) - tiled = retile_volume(layout, linear) - for z in (0, 3, 7): - self.assertEqual(ttpf.detile_volume_slice(layout, tiled, z), - linear[z * w * h * 2:(z + 1) * w * h * 2]) - # Truncated allocation: the exact slice-copy fallback must match a per-element reference. - eb = layout["element_bytes"] - pat = ttpf.VOLUME_PATTERNS_4K[{1: 0, 2: 1, 4: 2, 8: 3, 16: 4}[eb]] - bw, bh, bd = layout["block_w"], layout["block_h"], layout["block_d"] - tiles_x = layout["mips"][0]["padded_w"] // bw - cut = tiled[:len(tiled) // 2 + 3] - for z in (1, 5): - ref = bytearray(w * h * eb) - for y in range(h): - for x in range(w): - off = (z // bd) * layout["z_tile_stride"] + ((y // bh) * tiles_x + x // bw) * layout["tile"] - for bit, s in enumerate(pat): - if s >= 101: - off |= ((z >> (s - 101)) & 1) << bit - elif s < 0: - off |= ((y >> (-s - 1)) & 1) << bit - elif 0 < s < 100: - off |= ((x >> (s - 1)) & 1) << bit - at = (y * w + x) * eb - ref[at:at + eb] = cut[off:off + eb] - self.assertEqual(ttpf.detile_volume_slice(layout, cut, z), bytes(ref)) - self.assertEqual(ttpf.detile_volume_slice(layout, tiled, 0), linear[:w * h * 2]) - - -# --- The BC1/BC4 decode and block_means as they were before the table-driven rewrite ------- -# Kept verbatim as the reference the fast paths must reproduce float for float. - -def _ref_rgb565(c): - return ((c >> 11) & 31) * 255.0 / 31, ((c >> 5) & 63) * 255.0 / 63, (c & 31) * 255.0 / 31 - - -def _ref_bc1_block(data, at, four_color=False): - c0, c1, idx = struct.unpack_from(" c1: - pal = [p0, p1, tuple((2 * a + b) / 3 for a, b in zip(p0, p1)), - tuple((a + 2 * b) / 3 for a, b in zip(p0, p1))] - else: - pal = [p0, p1, tuple((a + b) / 2 for a, b in zip(p0, p1)), (0.0, 0.0, 0.0)] - return [pal[(idx >> (2 * (y * 4 + x))) & 3] for y in range(4) for x in range(4)] - - -def _ref_bc4_block(data, at): - e0, e1 = data[at], data[at + 1] - bits = int.from_bytes(data[at + 2:at + 8], "little") - if e0 > e1: - pal = [e0, e1] + [((7 - i) * e0 + i * e1) // 7 for i in range(1, 7)] - else: - pal = [e0, e1] + [((5 - i) * e0 + i * e1) // 5 for i in range(1, 5)] + [0, 255] - vals = [pal[(bits >> (3 * (y * 4 + x))) & 7] for y in range(4) for x in range(4)] - return [(float(v),) * 3 for v in vals] - - -def _ref_decode_pixels(fmt, data, blocks_w, blocks_h): - px = [] - for by in range(blocks_h): - rows = [[None] * (blocks_w * 4) for _ in range(4)] - for bx in range(blocks_w): - at = (by * blocks_w + bx) * 16 - if fmt in (71, 72): - blk = _ref_bc1_block(data, (by * blocks_w + bx) * 8) - elif fmt in (74, 75, 77, 78): - blk = _ref_bc1_block(data, at + 8, four_color=True) - elif fmt in (80,): - blk = _ref_bc4_block(data, (by * blocks_w + bx) * 8) - elif fmt in (83,): - a = _ref_bc4_block(data, at) - b = _ref_bc4_block(data, at + 8) - blk = [(p[0], q[0], 0.0) for p, q in zip(a, b)] - else: - return None - for y in range(4): - for x in range(4): - rows[y][bx * 4 + x] = blk[y * 4 + x] - px.extend(rows) - return [p for row in px for p in row] - - -def _ref_block_means(pixels, blocks_w, blocks_h, pixels_w=None, pixels_h=None, block=4): - if block == 1: - return list(pixels) - pw = blocks_w * block if pixels_w is None else pixels_w - ph = blocks_h * block if pixels_h is None else pixels_h - out = [] - for by in range(blocks_h): - for bx in range(blocks_w): - acc = [0.0, 0.0, 0.0] - n = 0 - for y in range(block): - if by * block + y >= ph: - continue - for x in range(block): - if bx * block + x >= pw: - continue - q = pixels[(by * block + y) * (blocks_w * block) + bx * block + x] - for k in range(3): - acc[k] += q[k] - n += 1 - out.append((acc[0] / n, acc[1] / n, acc[2] / n) if n else (0.0, 0.0, 0.0)) - return out - - -def _float_bits(pixels): - """Every channel's IEEE bits (so -0.0 counts); each channel must be a float. All NaNs map - to one: which NaN comes out of `NaN + NaN` follows the operand order the interpreter's - float add happens to use (it differs between a cold and a specialized `+`), in the scalar - loop as much as here, and no consumer of the means reads it (`_hdr_tonemap` maps NaN to 0).""" - flat = [c for p in pixels for c in p] - assert all(type(c) is float for c in flat), "a channel is not a float" - return struct.pack(f"<{len(flat)}d", *[float("nan") if c != c else c for c in flat]) - - -class BcFastDecodeParityTest(unittest.TestCase): - """decode_bc1_block / decode_bc4_block / decode_pixels / block_means against the scalar - code they replaced, plus hand-derived values that need no reference.""" - - def assert_same_pixels(self, got, want): - self.assertEqual(len(got), len(want)) - self.assertEqual(_float_bits(got), _float_bits(want)) - - def test_bc1_hand_derived_palette_and_pixel_order(self): - red, blue = 0xF800, 0x001F - # c0 > c1: four colors; index = row number, so row y is all pal[y]. - blk = struct.pack(" None: - code, err = self.main_with(fail_validation=True) - self.assertEqual(code, 2) - self.assertIn("compute32", err) - - def test_main_succeeds_when_the_control_was_rejected(self): - for kwargs in ({}, {"fail_assembly": True}): - with self.subTest(**kwargs): - code, err = self.main_with(**kwargs) - self.assertEqual(code, 0) - self.assertEqual(err, "") - - def test_out_in_a_missing_folder_creates_it(self): - # #934's class: a --out whose parent does not exist used to lose the whole run to a traceback. - with tempfile.TemporaryDirectory() as tmp: - out = os.path.join(tmp, "nested", "dir", "atlas.json") - code, err = self.main_with(argv=["turing_atlas.py", "--out", out]) - self.assertEqual((code, err), (0, "")) - self.assertTrue(os.path.isfile(out)) - - def test_reports_atlas_output_write_error(self): - with tempfile.TemporaryDirectory() as tmp: - parent = os.path.join(tmp, "existing-file") - with open(parent, "w", encoding="utf-8") as f: - f.write("keep me") - out = os.path.join(parent, "atlas.json") - code, err = self.main_with(argv=["turing_atlas.py", "--out", out]) - - self.assertEqual(code, 2) - self.assertIn(f"cannot write {out}", err) - with open(parent, encoding="utf-8") as f: - self.assertEqual(f.read(), "keep me") - - def test_out_cannot_be_a_directory(self): - with tempfile.TemporaryDirectory() as tmp: - code, err = self.main_with(argv=["turing_atlas.py", "--out", tmp]) - self.assertEqual(code, 2) - self.assertIn("--out is a folder", err) - - trailing = os.path.join(tmp, "new_folder") + os.sep - code, err = self.main_with(argv=["turing_atlas.py", "--out", trailing]) - self.assertEqual(code, 2) - self.assertIn("--out is a folder", err) - - for empty_out in ("", " "): - with self.subTest(empty_out=repr(empty_out)): - code, err = self.main_with(argv=["turing_atlas.py", "--out", empty_out]) - self.assertEqual(code, 2) - self.assertIn("turing_atlas: error:", err) - - - def test_missing_tools_skip_without_treating_it_as_a_control_failure(self): - with patch.object(turing_atlas.shutil, "which", return_value=None): - self.assertEqual(turing_atlas.validate_cases(), - {"skipped": "spirv-as/spirv-val not on PATH (Vulkan SDK)"}) - code, err = self.main_with(tools=False) - self.assertEqual(code, 0) - self.assertEqual(err, "") - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/test_u16_high_half.py b/tests/test_u16_high_half.py deleted file mode 100644 index b30a8bfac..000000000 --- a/tests/test_u16_high_half.py +++ /dev/null @@ -1,167 +0,0 @@ -"""16-bit high-half reads must not follow ``OpShiftRightLogical %uint u 16`` with a 16-bit extract (#1506). - -AMD's Windows LLPC compiler (observed on RDNA2 drivers 22.40.84.06 in #1506 and 24.10.24) drops the ``>> 16`` when -either ``OpBitwiseAnd %uint (u >> 16) 0xFFFF`` or ``OpBitFieldSExtract %int (u >> 16) 0 16`` follows two partial-half -writes to ``u`` and feeds ``OpIAdd``, ``OpIMul``, or ``OpShiftLeftLogical``. On a 32-bit value ``OpShiftRightLogical`` -already clears bits 16..31 and ``OpShiftRightArithmetic`` already sign-extends bits 16..31, so ``Gen.u16_half`` and -``Gen.i16_half`` emit those single shifts for high halves and narrow in place only for low halves. -""" -import os -import re -import subprocess -import sys - -import pytest - -import spirv_interp as si -from conftest import HAVE_SPIRV -from listing import translate_listing - -sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), "semantic")) -import spirv_mini_interp as mini # noqa: E402 - - -def _shr16_then_extract16(spvasm): - """Return any ``(%shr, %use)`` where ``%shr = OpShiftRightLogical %uint ... %c10`` feeds either - ``OpBitwiseAnd %uint %shr %cffff`` or ``OpBitFieldSExtract %int (OpBitcast %int %shr) %c0 %c10``.""" - shr_ids = set(re.findall(r"(%\w+)\s*=\s*OpShiftRightLogical %uint %\w+ %c10\b", spvasm)) - # Map OpBitcast %int %shr -> %shr so signed extracts of a shifted value are caught too. - cast_to_shr = {dst: src for dst, src in re.findall(r"(%\w+)\s*=\s*OpBitcast %int (%\w+)\b", spvasm) - if src in shr_ids} - bad = [(m.group(2), m.group(1)) - for m in re.finditer(r"(%\w+)\s*=\s*OpBitwiseAnd %uint (%\w+) %cffff\b", spvasm) - if m.group(2) in shr_ids] - bad += [(cast_to_shr[m.group(2)], m.group(1)) - for m in re.finditer(r"(%\w+)\s*=\s*OpBitFieldSExtract %int (%\w+) %c0 %c10\b", spvasm) - if m.group(2) in cast_to_shr] - return bad - - -PROLOGUE = ( - "v_mov_b32 v1, 0x41b1af48\n" - "v_mov_b32 v2, 0x9e00ccd9\n" - "v_mov_b32 v4, 0x40004200\n" - "v_mov_b32 v3, 0xaaaa5555\n" - "s_mov_b32 s4, 0x41b1138b\n" -) - -U16_HIGH_HALF_OPS = [ - ("v_lshlrev_b16", "v_lshlrev_b16_e64 v3, v1, v2 op_sel:[1,1,0]"), - ("v_add_u16", "v_add_u16_e64 v3, v1, v2 op_sel:[1,1,0]"), - ("v_mul_lo_u16", "v_mul_lo_u16_e64 v3, v1, v2 op_sel:[1,1,0]"), - ("v_mad_u16", "v_mad_u16 v3, v1, v2, v4 op_sel:[1,1,1,0]"), - ("v_min3_u16", "v_min3_u16 v3, v1, v2, v4 op_sel:[1,1,1,0]"), - ("v_cvt_f16_u16", "v_cvt_f16_u16_e64 v3, v1 op_sel:[1,0]"), - ("v_pack_b32_f16", "v_pack_b32_f16 v3, v1, v2 op_sel:[1,1]"), - ("v_frexp_mant_f16", "v_frexp_mant_f16_e64 v3, v1 op_sel:[1,0]"), - ("v_ldexp_f16", "v_ldexp_f16 v3, v1, v2 op_sel:[1,0,0]"), - ("s_bitreplicate_b64_b32", "s_bitreplicate_b64_b32 s[6:7], s4"), -] - -I16_HIGH_HALF_OPS = [ - ("v_ashrrev_i16", "v_ashrrev_i16_e64 v3, v1, v2 op_sel:[1,1,0]"), - ("v_add_i16", "v_add_i16_e64 v3, v1, v2 op_sel:[1,1,0]"), - ("v_sub_i16", "v_sub_i16_e64 v3, v1, v2 op_sel:[1,1,0]"), - ("v_min_i16", "v_min_i16_e64 v3, v1, v2 op_sel:[1,1,0]"), - ("v_max_i16", "v_max_i16_e64 v3, v1, v2 op_sel:[1,1,0]"), - ("v_mad_i16", "v_mad_i16 v3, v1, v2, v4 op_sel:[1,1,1,0]"), - ("v_min3_i16", "v_min3_i16 v3, v1, v2, v4 op_sel:[1,1,1,0]"), - ("v_cvt_f16_i16", "v_cvt_f16_i16_e64 v3, v2 op_sel:[1,0]"), - ("v_ldexp_f16_exp", "v_ldexp_f16 v3, v1, v2 op_sel:[0,1,0]"), -] - - -def _validate_spv(tmp_path, spvasm): - if not HAVE_SPIRV: - return - asm_path = tmp_path / "p.spvasm" - spv_path = tmp_path / "p.spv" - asm_path.write_text(spvasm, encoding="utf-8", newline="\n") - for cmd in (["spirv-as", "--target-env", "vulkan1.2", str(asm_path), "-o", str(spv_path)], - ["spirv-val", "--target-env", "vulkan1.2", str(spv_path)]): - r = subprocess.run(cmd, capture_output=True, text=True) - assert r.returncode == 0, r.stdout + r.stderr - - -@pytest.mark.parametrize("name,asm", U16_HIGH_HALF_OPS, ids=[o[0] for o in U16_HIGH_HALF_OPS]) -def test_u16_no_redundant_extract_after_shr16(name, asm, tmp_path): - spvasm = translate_listing(tmp_path, PROLOGUE + asm) - assert re.search(r"OpShiftRightLogical %uint %\w+ %c10\b", spvasm), asm - assert _shr16_then_extract16(spvasm) == [], f"{name} narrowed OpShiftRightLogical >> 16 to 16 bits" - - -@pytest.mark.parametrize("name,asm", I16_HIGH_HALF_OPS, ids=[o[0] for o in I16_HIGH_HALF_OPS]) -def test_i16_uses_ashr16_not_shr16_sextract(name, asm, tmp_path): - spvasm = translate_listing(tmp_path, PROLOGUE + asm) - assert re.search(r"OpShiftRightArithmetic %int %\w+ %c10\b", spvasm), asm - assert _shr16_then_extract16(spvasm) == [], f"{name} narrowed OpShiftRightLogical >> 16 via SExtract" - _validate_spv(tmp_path, spvasm) - - -def test_d16_buffer_store_no_redundant_extract_after_shr16(tmp_path): - asm = ( - "v_mov_b32 v1, 0x9c004000\n" - "v_mov_b32 v2, 0\n" - "buffer_store_format_d16_xy v1, v2, s[0:3], 0 offen\n" - ) - spvasm = translate_listing(tmp_path, asm) - assert re.search(r"OpShiftRightLogical %uint %\w+ %c10\b", spvasm) - assert re.search(r"OpShiftRightArithmetic %int %\w+ %c10\b", spvasm) - assert _shr16_then_extract16(spvasm) == [] - _validate_spv(tmp_path, spvasm) - - -def test_issue_1506_sequence_computes_exact_shift_and_validates(tmp_path): - """Exact minimized instruction sequence from #1506 (valu_fuzz --family f16 --show 2:163:64).""" - asm = "\n".join([ - "v_mov_b32 v24, 0x41b1af48", - "v_mov_b32 v26, 0x3e00ccd9", - "v_mov_b32 v31, 0x40004200", - "v_mov_b32 v34, 0xc09946b2", - "v_mov_b32 v7, 3", - "v_or_b32 v20, 0x3c00, v7", - "v_pk_max_f16 v30, v26, v24 op_sel:[0,0] op_sel_hi:[1,1]", - "v_min_i16_e64 v20, v24, v31 op_sel:[1,0,1]", - "v_fma_f16_e64 v20, v34, v26, v26 op_sel:[0,0,1,0]", - "v_lshlrev_b16_e64 v30, v30, v20 op_sel:[1,1,0]", - ]) - spvasm = translate_listing(tmp_path, asm) - assert _shr16_then_extract16(spvasm) == [] - state = si.run(spvasm) - assert state.vgpr[20] == 0x41B1D803 - assert state.vgpr[30] == 0x41B18362 - _validate_spv(tmp_path, spvasm) - - -@pytest.mark.parametrize("asm,want", [ - ("v_add_u16_e64 v3, v1, v2 op_sel:[1,1,0]", 0xAAAA0000 | ((0x41B1 + 0x9E00) & 0xFFFF)), - ("v_mul_lo_u16_e64 v3, v1, v2 op_sel:[1,1,0]", 0xAAAA0000 | ((0x41B1 * 0x9E00) & 0xFFFF)), - ("v_mad_u16 v3, v1, v2, v4 op_sel:[1,1,1,0]", 0xAAAA0000 | ((0x41B1 * 0x9E00 + 0x4000) & 0xFFFF)), - ("v_min3_u16 v3, v1, v2, v4 op_sel:[1,1,1,0]", 0xAAAA4000), - ("v_pack_b32_f16 v3, v1, v2 op_sel:[1,1]", 0x9E0041B1), - # Signed high-half operations with negative high half 0x9E00 (-25088): - ("v_ashrrev_i16_e64 v3, v1, v2 op_sel:[1,1,0]", 0xAAAA0000 | (((-25088) >> (0x41B1 & 15)) & 0xFFFF)), - ("v_add_i16_e64 v3, v1, v2 op_sel:[1,1,0] clamp", 0xAAAA0000 | ((0x41B1 - 25088) & 0xFFFF)), - ("v_min_i16_e64 v3, v1, v2 op_sel:[1,1,0]", 0xAAAA9E00), - ("v_max_i16_e64 v3, v1, v2 op_sel:[1,1,0]", 0xAAAA41B1), - ("v_mad_i16 v3, v1, v2, v4 op_sel:[1,1,1,0] clamp", 0xAAAA8000), - ("v_min3_i16 v3, v1, v2, v4 op_sel:[1,1,1,0]", 0xAAAA9E00), -]) -def test_16bit_high_half_values(asm, want, tmp_path): - spvasm = translate_listing(tmp_path, PROLOGUE + asm) - assert mini.run_fragment(spvasm)["%out_mrt0"][0] == want - - -def test_s_bitreplicate_high_half_value(tmp_path): - spvasm = translate_listing(tmp_path, PROLOGUE + "s_bitreplicate_b64_b32 s[6:7], s4") - state = si.run(spvasm) - - def rep16(x): - out = 0 - for b in range(16): - if (x >> b) & 1: - out |= 3 << (2 * b) - return out - - assert state.sgpr[6] == rep16(0x138B) - assert state.sgpr[7] == rep16(0x41B1) diff --git a/tests/test_user_sgpr_census.py b/tests/test_user_sgpr_census.py deleted file mode 100644 index 321423149..000000000 --- a/tests/test_user_sgpr_census.py +++ /dev/null @@ -1,398 +0,0 @@ -"""tools/user_sgpr_census.py on hand-written index.json data (no game files, no GPU).""" -import contextlib -import json -import os -from pathlib import Path -import subprocess -import sys -import tempfile -from unittest import mock - -import pytest - -ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) -sys.path.insert(0, os.path.join(ROOT, "tools")) - -import report_paths # noqa: E402 -import user_sgpr_census as usc # noqa: E402 - - -def reads(*pairs): - return [{"sgpr": s, "kind": k} for s, k in pairs] - - -INDEX = { - "a.ps": {"stage": "ps", "user_sgpr_reads": reads((8, "ptr32_lo"), (9, "const32"))}, - "b.ps": {"stage": "ps", "user_sgpr_reads": reads((1, "const32"), (8, "ptr32_lo"), (11, "ptr32_lo"))}, - "c.ps": {"stage": "ps", "user_sgpr_reads": reads((9, "ptr32_lo"))}, - "d.cs": {"stage": "cs", "user_sgpr_reads": reads((4, "ptr32_lo"), (5, "const32"))}, - "e.gs": {"stage": "gs", "user_sgpr_reads": reads((2, "const32"), (8, "ptr64_lo"), (9, "ptr64_hi"))}, - "f.vs": {"stage": "vs", "user_sgpr_reads": []}, -} - - -def test_lowest_pointer_per_stage(): - s = usc.census(INDEX) - assert s["ps"]["shaders"] == 3 - assert s["ps"]["lowest_pointer_sgpr"] == {"s8": 2, "s9": 1} - assert s["ps"]["most_common_lowest_pointer_sgpr"] == 8 - assert s["ps"]["lowest_pointer_kind"] == {"ptr32_lo": 3} - assert s["cs"]["most_common_lowest_pointer_sgpr"] == 4 - assert s["gs"]["lowest_pointer_kind"] == {"ptr64_lo": 1} - assert s["vs"]["most_common_lowest_pointer_sgpr"] is None - - -def test_tie_most_common_prefers_smaller_sgpr_regardless_of_insertion_order(tmp_path, capsys): - """Equal highest counts must pick the smaller SGPR, not depend on dict insertion order.""" - forward = {"x": {"stage": "ps", "user_sgpr_reads": reads((8, "ptr32_lo"))}, - "y": {"stage": "ps", "user_sgpr_reads": reads((9, "ptr32_lo"))}} - reversed_order = {"y": forward["y"], "x": forward["x"]} - - a = usc.census(forward) - b = usc.census(reversed_order) - assert a["ps"]["most_common_lowest_pointer_sgpr"] == 8 - assert b["ps"]["most_common_lowest_pointer_sgpr"] == 8 - - # --expect must agree for both orderings. - p = tmp_path / "index.json" - p.write_text(json.dumps(reversed_order), encoding="utf-8") - assert usc.main([str(p), "--expect", "ps=8"]) == 0 - assert usc.main([str(p), "--expect", "ps=9"]) == 1 - capsys.readouterr() - - -def test_const_reads_are_not_pointers(): - s = usc.census({"x": {"stage": "ps", "user_sgpr_reads": reads((0, "const32"), (3, "const32"))}}) - assert s["ps"]["lowest_pointer_sgpr"] == {} - assert s["ps"]["shaders_reading_kind"] == {"const32": 1} - - -def model_two_dword_tables_from_s0(): - """Shaders packed as runtime/src/root_signature.h does today: tables are 64-bit VAs from s0.""" - return { - "t0": {"stage": "ps", "user_sgpr_reads": reads((0, "ptr64_lo"), (1, "ptr64_hi"), (2, "ptr64_lo"), (3, "ptr64_hi"))}, - "t1": {"stage": "ps", "user_sgpr_reads": reads((0, "ptr64_lo"), (1, "ptr64_hi"), (2, "const32"))}, - } - - -def model_one_dword_tables_from_s8(): - """Shaders packed with a stage base (PS s8) and one-dword tables: 32-bit VAs, high half implicit zero.""" - return { - "t0": {"stage": "ps", "user_sgpr_reads": reads((8, "ptr32_lo"), (9, "ptr32_lo"))}, - "t1": {"stage": "ps", "user_sgpr_reads": reads((1, "const32"), (8, "ptr32_lo"), (9, "const32"), (10, "ptr32_lo"))}, - } - - -def test_the_two_packing_models_are_told_apart(): - a = usc.census(model_two_dword_tables_from_s0())["ps"] - b = usc.census(model_one_dword_tables_from_s8(), base={"ps": 8})["ps"] - # two dwords per table: pointers two SGPRs apart, never a 32-bit pointer, high halves read - assert a["pointer_gap"] == {2: 1} - assert a["after_ptr32"] == {} - assert a["most_common_lowest_pointer_sgpr"] == 0 - assert a["shaders_reading_kind"].get("ptr64_hi") == 2 - # one dword per table from s8: pointers adjacent, no high halves, a system read below the base - assert b["pointer_gap"] == {1: 1, 2: 1} - # t0: s8 -> s9 is a pointer, s9 -> s10 not read; t1: s8 -> s9 const32, s10 -> s11 not read - assert b["after_ptr32"] == {"const32": 1, "not read": 2, "pointer": 1} - assert b["most_common_lowest_pointer_sgpr"] == 8 - assert "ptr64_hi" not in b["shaders_reading_kind"] - assert b["below_base"] == {"s1:const32": 1} - - -@pytest.mark.parametrize("output_kind", ["same-path", "relative-alias", "hard-link", "folding-volume-case"]) -def test_json_report_refuses_to_overwrite_index(tmp_path, capsys, output_kind): - assert usc.same_report_path is report_paths.same_report_path - index = tmp_path / "index.json" - original = json.dumps(INDEX).encode("utf-8") - index.write_bytes(original) - output = index - if output_kind == "relative-alias": - subdir = tmp_path / "subdir" - subdir.mkdir() - output = subdir / ".." / index.name - elif output_kind == "hard-link": - output = tmp_path / "alias.json" - try: - output.hardlink_to(index) - except OSError as err: - pytest.skip(f"hard links unavailable: {err}") - elif output_kind == "folding-volume-case": - output = tmp_path / "INDEX.JSON" - - # same_report_path resolves each path once and calls the private helpers since #6268, so a case-folded volume is - # simulated by patching those: the public path_key / same_name_on_folding_volume are no longer on its path. - probe = mock.Mock(return_value=True) - ctx = (mock.patch.multiple(report_paths, _resolved_key=mock.Mock(side_effect=str), - _same_resolved_name=probe) - if output_kind == "folding-volume-case" else contextlib.nullcontext()) - with ctx, (mock.patch.object(os.path, "samefile", side_effect=OSError("not same")) - if output_kind == "folding-volume-case" else contextlib.nullcontext()): - with pytest.raises(SystemExit) as exc: - usc.main([str(index), "--json", str(output)]) - if output_kind == "folding-volume-case": - probe.assert_called_once() - - assert exc.value.code == 2 - assert "--json must not overwrite the input index" in capsys.readouterr().err - assert index.read_bytes() == original - - -def test_json_report_accepts_a_separate_output(tmp_path): - index = tmp_path / "index.json" - output = tmp_path / "summary.json" - index.write_text(json.dumps(INDEX), encoding="utf-8") - - assert usc.main([str(index), "--json", str(output)]) == 0 - assert json.loads(output.read_text(encoding="utf-8"))["ps"]["lowest_pointer_sgpr"] == {"s8": 2, "s9": 1} - assert json.loads(index.read_text(encoding="utf-8")) == INDEX - - -def test_expect_passes_and_fails(tmp_path, capsys): - p = tmp_path / "index.json" - p.write_text(json.dumps(INDEX), encoding="utf-8") - assert usc.main([str(p), "--expect", "ps=8", "cs=4"]) == 0 - assert usc.main([str(p), "--expect", "ps=0"]) == 1 - assert "expected s0, got s8" in capsys.readouterr().err - - -def test_cli_rejects_malformed_stage_assignment(): - with tempfile.TemporaryDirectory() as tmp: - index = Path(tmp, "index.json") - report = Path(tmp, "report.json") - index.write_text(json.dumps(INDEX), encoding="utf-8") - tool = os.path.join(ROOT, "tools", "user_sgpr_census.py") - for option in ("--base", "--expect"): - for assignment in ("ps", "ps=bad", "=8", "ps=-1"): - result = subprocess.run( - [sys.executable, "-I", tool, str(index), "--json", str(report), option, assignment], - capture_output=True, text=True, - ) - assert result.returncode == 2, result.stderr - assert "expected STAGE=SGPR" in result.stderr - assert "Traceback" not in result.stderr - assert not report.exists() - - -TOOL = os.path.join(ROOT, "tools", "user_sgpr_census.py") - - -def run_cli(*args): - # A piped Python child writes in the locale encoding (the ANSI code page on Windows): read it back in that - # encoding, or a non-ASCII temp path in the error line no longer matches. - return subprocess.run([sys.executable, "-I", TOOL, *map(str, args)], capture_output=True, text=True, - errors="replace") - - -def assert_one_error_line(result, *fragments): - assert result.returncode == 2, result.stdout + result.stderr - assert "Traceback" not in result.stderr - lines = result.stderr.splitlines() - assert len(lines) == 1 and lines[0].startswith("ERROR: "), result.stderr - for fragment in fragments: - assert fragment in lines[0] - assert result.stdout == "" - - -@pytest.mark.parametrize("kind", ["missing", "folder", "empty", "not-json", "not-utf8", "nested-too-deep"]) -def test_cli_unreadable_index_is_one_error_line(tmp_path, kind): - index = tmp_path / "index.json" - if kind == "folder": - index.mkdir() - elif kind != "missing": - index.write_bytes({"empty": b"", "not-json": b"{not json", "not-utf8": b"\xff\xfe{}", - "nested-too-deep": b"[" * 100000}[kind]) - report = tmp_path / "report.json" - - result = run_cli(index, "--json", report) - - assert_one_error_line(result, "cannot read", str(index)) - assert not report.exists() - - -WRONG_SHAPES = [ - ([], "expected a JSON object of shader -> metadata entries"), - ("text", "expected a JSON object of shader -> metadata entries"), - ({"a.ps": []}, "a.ps: each shader entry must be a JSON object"), - ({"a.ps": {"stage": 3}}, "a.ps: 'stage' must be a string"), - ({"a.ps": {"stage": "ps", "user_sgpr_reads": {"sgpr": 8}}}, "a.ps: 'user_sgpr_reads' must be a JSON array"), - ({"a.ps": {"stage": "ps", "user_sgpr_reads": [8]}}, "a.ps: each read needs 'sgpr' and 'kind' fields"), - ({"a.ps": {"stage": "ps", "user_sgpr_reads": [{"sgpr": 8}]}}, "a.ps: each read needs 'sgpr' and 'kind' fields"), - ({"a.ps": {"stage": "ps", "user_sgpr_reads": [{"kind": "const32"}]}}, - "a.ps: each read needs 'sgpr' and 'kind' fields"), - ({"a.ps": {"stage": "ps", "user_sgpr_reads": [{"sgpr": "8", "kind": "ptr32_lo"}]}}, - "a.ps: each read 'sgpr' must be a nonnegative integer"), - ({"a.ps": {"stage": "ps", "user_sgpr_reads": [{"sgpr": -1, "kind": "ptr32_lo"}]}}, - "a.ps: each read 'sgpr' must be a nonnegative integer"), - ({"a.ps": {"stage": "ps", "user_sgpr_reads": [{"sgpr": True, "kind": "ptr32_lo"}]}}, - "a.ps: each read 'sgpr' must be a nonnegative integer"), - ({"a.ps": {"stage": "ps", "user_sgpr_reads": [{"sgpr": 8.5, "kind": "ptr32_lo"}]}}, - "a.ps: each read 'sgpr' must be a nonnegative integer"), - ({"a.ps": {"stage": "ps", "user_sgpr_reads": [{"sgpr": 8, "kind": None}]}}, - "a.ps: each read kind must be a string"), - # A good entry first: the whole index is checked, not only its first shader. - ({**INDEX, "z.ps": {"stage": "ps", "user_sgpr_reads": [{"sgpr": 8, "kind": ["ptr32_lo"]}]}}, - "z.ps: each read kind must be a string"), -] - - -@pytest.mark.parametrize("document,message", WRONG_SHAPES, ids=[str(i) for i in range(len(WRONG_SHAPES))]) -def test_wrongly_shaped_index_is_one_error_line(tmp_path, capsys, document, message): - index = tmp_path / "index.json" - report = tmp_path / "report.json" - index.write_text(json.dumps(document), encoding="utf-8") - - assert usc.main([str(index), "--json", str(report), "--base", "ps=8", "--expect", "ps=8"]) == 2 - - captured = capsys.readouterr() - assert captured.err == f"ERROR: {index}: {message}\n" - assert captured.out == "" - assert not report.exists() - - -def test_cli_wrongly_shaped_index_has_no_traceback(tmp_path): - index = tmp_path / "index.json" - index.write_text(json.dumps({"a.ps": {"stage": "ps", "user_sgpr_reads": [{"sgpr": 8}, {"sgpr": 9, "kind": "x"}]}}), - encoding="utf-8") - - assert_one_error_line(run_cli(index), "a.ps: each read needs 'sgpr' and 'kind' fields") - - -def test_entries_without_stage_or_reads_are_still_counted(tmp_path, capsys): - index = tmp_path / "index.json" - index.write_text(json.dumps({"a": {}, "b": {"user_sgpr_reads": None}, "c.ps": {"stage": "ps"}, - "d.ps": {"stage": "ps", "user_sgpr_reads": reads((8, "ptr32_lo"))}}), - encoding="utf-8") - report = tmp_path / "report.json" - - assert usc.main([str(index), "--json", str(report)]) == 0 - - summary = json.loads(report.read_text(encoding="utf-8")) - assert (summary["?"]["shaders"], summary["ps"]["shaders"]) == (2, 2) - assert summary["ps"]["lowest_pointer_sgpr"] == {"s8": 1} - assert capsys.readouterr().err == "" - - -def test_load_index_accepts_utf8_bom(tmp_path): - index = tmp_path / "index.json" - index.write_bytes(b"\xef\xbb\xbf" + json.dumps(INDEX).encode("utf-8")) - assert usc.load_index(index) == INDEX - report = tmp_path / "report.json" - result = run_cli(index, "--json", report) - assert result.returncode == 0, result.stderr - assert json.loads(report.read_text(encoding="utf-8"))["ps"]["lowest_pointer_sgpr"] == {"s8": 2, "s9": 1} - - -@pytest.mark.parametrize("kind", ["missing-folder", "folder", "under-a-file"]) -def test_cli_unwritable_report_is_one_error_line(tmp_path, kind): - index = tmp_path / "index.json" - index.write_text(json.dumps(INDEX), encoding="utf-8") - if kind == "missing-folder": - report = tmp_path / "missing" / "report.json" - elif kind == "folder": - report = tmp_path / "report.json" - report.mkdir() - else: - blocker = tmp_path / "blocker" - blocker.write_bytes(b"keep") - report = blocker / "report.json" - - result = run_cli(index, "--json", report) - - assert result.returncode == 2, result.stdout + result.stderr - assert "Traceback" not in result.stderr - lines = result.stderr.splitlines() - assert len(lines) == 1 and lines[0].startswith(f"ERROR: cannot write {report}: "), result.stderr - assert "ps: 3 shaders" in result.stdout # the census itself ran and was printed - assert json.loads(index.read_text(encoding="utf-8")) == INDEX - if kind == "under-a-file": - assert blocker.read_bytes() == b"keep" - - -# --pairs (D3D-318): the VS and PS of one technique, named alike apart from the stage token. - -def test_technique_names(): - assert usc.technique("!VS_Water_0123abcd_Wrapped", "vs") == "Water" - assert usc.technique("#PS_Water_89abcdef_Wrapped", "ps") == "Water" - assert usc.technique("PS_Water", "ps") == "Water" - assert usc.technique("!VS_Water_0123abcd_Wrapped", "ps") is None # the token must match the stage - assert usc.technique("standard_0123abcd_Wrapped", "vs") is None - - -def root_block(params, stage, omit_invisible): - """User-SGPR reads of `stage` for root parameters [(kind, {stages that can see it})] packed from s8, one dword - each: in root order with a hole for an invisible parameter (one block), or without it (per-stage omission).""" - out, sgpr = [], 8 - for kind, stages in params: - if stage in stages: - out.append((sgpr, kind)) - if stage in stages or not omit_invisible: - sgpr += 1 - return reads(*out) - - -# A, both stages; B, pixel only; C and D, both stages. -PARAMS = [("ptr32_lo", {"vs", "ps"}), ("const32", {"ps"}), ("ptr32_lo", {"vs", "ps"}), ("const32", {"vs", "ps"})] - - -def technique_index(omit_invisible): - return {f"{prefix}{stage.upper()}_Fog_{h}_Wrapped": {"stage": stage, "user_sgpr_reads": - root_block(PARAMS, stage, omit_invisible)} - for prefix, stage, h in (("!", "vs", "0123abcd"), ("#", "ps", "89abcdef"))} - - -def test_one_block_in_root_order_agrees(): - pc = usc.pair_census(technique_index(omit_invisible=False)) - assert pc["techniques_with_vs_and_ps"] == 1 and pc["combinations"] == 1 - # VS s8 A, s10 C, s11 D; PS s8 A, s9 B, s10 C, s11 D: three shared reads, all the same kind. - assert (pc["shared_same_kind"], pc["shared_different_kind"]) == (3, 0) - assert pc["combinations_with_a_one_sided_sgpr_below_a_shared_one"] == 1 - assert (pc["above_one_sided_same_kind"], pc["above_one_sided_different_kind"]) == (2, 0) - - -def test_per_stage_omission_disagrees(): - pc = usc.pair_census(technique_index(omit_invisible=True)) - # VS s8 A, s9 C, s10 D against PS s8 A, s9 B, s10 C, s11 D: C and D sit one SGPR lower in the VS. - assert (pc["shared_same_kind"], pc["shared_different_kind"]) == (1, 2) - - -def test_unpaired_shaders_only_feed_the_control(): - index = { - "!VS_Sky_0123abcd_Wrapped": {"stage": "vs", "user_sgpr_reads": reads((8, "ptr32_lo"), (9, "const32"))}, - "#PS_Rain_89abcdef_Wrapped": {"stage": "ps", "user_sgpr_reads": reads((8, "ptr32_lo"), (9, "ptr32_lo"))}, - "c.cs": {"stage": "cs", "user_sgpr_reads": reads((8, "ptr32_lo"))}, - } - pc = usc.pair_census(index) - assert pc["techniques_with_vs_and_ps"] == 0 and pc["combinations"] == 0 - assert pc["control_all_vs_ps"] == {"combinations": 1, "shared_same_kind": 1, "shared_different_kind": 1} - - -def test_index_saved_with_a_utf8_bom_is_read(tmp_path, capsys): - """A carve index edited on Windows can carry a BOM; it is still the same JSON.""" - p = tmp_path / "index.json" - p.write_bytes(b"\xef\xbb\xbf" + json.dumps(INDEX).encode("utf-8")) - assert usc.main([str(p)]) == 0 - out = capsys.readouterr() - assert "ps: 3 shaders" in out.out - assert "ERROR" not in out.err - - -def test_bom_does_not_hide_broken_json(tmp_path, capsys): - """Skipping the BOM still leaves a strict JSON parse: a broken index is one ERROR line and exit 2.""" - p = tmp_path / "index.json" - p.write_bytes(b"\xef\xbb\xbf{\"a.ps\": }") - assert usc.main([str(p)]) == 2 - assert "ERROR: cannot read" in capsys.readouterr().err - - -def test_pairs_cli_writes_the_report_and_no_names(): - with tempfile.TemporaryDirectory() as tmp: - index = Path(tmp, "index.json") - report = Path(tmp, "report.json") - index.write_text(json.dumps(technique_index(omit_invisible=False)), encoding="utf-8") - result = subprocess.run([sys.executable, "-I", os.path.join(ROOT, "tools", "user_sgpr_census.py"), - str(index), "--pairs", "--json", str(report)], capture_output=True, text=True) - assert result.returncode == 0, result.stderr - assert "VS/PS pairs: 1 techniques with both stages" in result.stdout - assert "Fog" not in result.stdout - assert json.loads(report.read_text(encoding="utf-8"))["vs_ps_pairs"]["shared_different_kind"] == 0 diff --git a/tests/test_valu_fuzz.py b/tests/test_valu_fuzz.py deleted file mode 100644 index 6b69e41a4..000000000 --- a/tests/test_valu_fuzz.py +++ /dev/null @@ -1,838 +0,0 @@ -"""CPU checks for tools/valu_fuzz.py (FUZZ-2, FUZZ-5): the reference models and the generators, no GPU. - -The GPU side (vk_compute_test, rdna2spirv.py) is what the fuzzer compares against; these tests make sure the models it -compares with are right, so a mismatch is the translator's and not the fuzzer's. -""" -import os -import random -import re -import shutil -import struct -import subprocess -import sys -import threading -from fractions import Fraction -from itertools import permutations -from pathlib import Path - -import pytest - -HERE = os.path.dirname(os.path.abspath(__file__)) -ROOT = os.path.dirname(HERE) -sys.path.insert(0, os.path.join(ROOT, "tools")) -import valu_fuzz as vf # noqa: E402 - - -# ------------------------------------------------------------------ numbers - -def test_f16_round_trips_every_finite_half(): - for h in range(0x10000): - if (h & 0x7C00) == 0x7C00: - continue - v = vf.f16_value(h) - bits, uncertain = vf.to_f16(v) - if v == 0 or vf.is_f16_denorm(h): - continue # zeros come back as +0 (callers set the sign); denormals are uncertain by design - assert not uncertain and bits == h, hex(h) - - -def test_to_f16_matches_pythons_round_to_nearest_even(): - rng = random.Random(1) - for _ in range(20000): - x = rng.uniform(-60000, 60000) * rng.choice((1, 1e-2, 1e-3)) - want = struct.unpack("> 28) & 3 == mode and w >> 30 == 0 and (w >> 24) & 1 == 0 and (w >> 12) & 0x3F == 22 - assert vf.word3(mode, "gfx10") == w | 1 << 24 - - -@pytest.mark.parametrize("args,want", [ - # RAW (3): offs + 4k + 4 > num_records is out of range, per dword (docs/design.md, RX 6800 and gfx1150 rows) - ((3, 18, 0, 0, 0, 0, 3), True), ((3, 18, 0, 0, 0xc, 0xc, 1), False), ((3, 18, 0, 0, 8, 16, 0), False), - ((3, 20, 0, 0, 13, 13, 1), False), ((3, 20, 0, 0, 12, 12, 1), True), ((3, 20, 0, 0, 12, 12, 2), False), - # soffset is part of the checked offset in RAW mode only - ((3, 24, 0, 0, 8, 16, 0), True), ((3, 24, 0, 0, 8, 24, 0), False), - # STRUCTURED_WITH_OFFSET (0): idx >= N or off + 4k + 4 > stride - ((0, 4, 16, 3, 12, 12, 0), True), ((0, 4, 16, 4, 0, 0, 0), False), ((0, 4, 16, 0, 12, 12, 1), False), - # STRUCTURED (1): idx >= N only; the whole access goes through - ((1, 4, 16, 3, 100, 100, 3), True), ((1, 4, 16, 4, 0, 0, 0), False), ((1, 0, 16, 0, 0, 0, 0), False), - # DISABLED (2): N == 0 only - ((2, 1, 0, 500, 100, 100, 0), True), ((2, 0, 0, 0, 0, 0, 0), False), -]) -def test_buffer_dword_ok(args, want): - assert vf.buffer_dword_ok(*args) is want - - -def test_out_of_range_loads_read_zero_and_stores_drop(): - # RAW V# of 2 slots and a bit: threads 0 and 1 are in range, 2 is cut after its first dword, the rest are out - p = _mem(a_mode=3, a_n=2 * vf.SLOT + 4, a_stride=0, soff=0) - r, r2 = vf.POOL[0], vf.POOL[4] - p.ops = [_op("store_off", 2, 0, r), _op("load_off", 2, 0, r2)] - regs, mem = p.model() - assert regs[1][r2].v == regs[1][r].v and regs[1][r2 + 1].v == regs[1][r + 1].v # in range - assert regs[2][r2].v == regs[2][r].v and regs[2][r2 + 1].v == 0 # straddles: per dword - assert regs[5][r2].v == 0 and regs[5][r2 + 1].v == 0 # out of range: 0 - assert mem[5 * vf.SLOT // 4] == vf.FILL_VK # and its store was dropped - assert mem[2 * vf.SLOT // 4 + 1] == vf.FILL_VK # the straddling store's 2nd dword too - - -def test_structured_modes_check_the_index_only(): - r, r2 = vf.POOL[0], vf.POOL[4] - p = _mem(b_mode=1, b_n=3, b_stride=vf.SLOT, soff=0) - p.ops = [_op("store_idx", 4, 0, r), _op("load_idx", 4, 0, r2)] - regs, mem = p.model() - assert [regs[t][r2].v == regs[t][r].v for t in (0, 2)] == [True, True] - assert all(regs[3][r2 + j].v == 0 for j in range(4)) # index 3 >= num_records 3 - p = _mem(b_mode=0, b_n=100, b_stride=vf.SLOT, soff=0) - p.ops = [_op("store_io", 1, 48, r), _op("load_io", 1, 48, r2)] # off = 48 + 4 * (t & 3) <= 60 - regs, mem = p.model() - assert regs[3][r2].v == regs[3][r].v and mem[3 * vf.SLOT // 4 + (48 + 12) // 4] == regs[3][r].v - - -def test_scalar_loads_read_the_slot_of_the_waves_first_thread(): - for wave in (32, 64): - p = _mem(wave=wave, a_mode=3, a_n=1 << 20, a_stride=0, s_stride=0, s_n=1 << 20, soff=0) - r, r2 = vf.POOL[0], vf.POOL[4] - p.ops = [_op("store_off", 1, 8, r), _op("sload", 1, 8, r2, imm=8), _op("sbuf", 1, 8, r2 + 1, imm=8)] - regs, mem = p.model() - for t in range(vf.THREADS): - first = t - t % wave - assert regs[t][r2].v == regs[first][r].v and regs[t][r2 + 1].v == regs[first][r].v - - -def test_s_buffer_load_bound_is_num_records_times_stride_and_ignores_oob_select(): - r2 = vf.POOL[4] - for mode in range(4): - # stride 4, 5 records = 20 bytes: the dword at 16 is in (nothing stored: the fill), the one at 20 is out - p = _mem(s_stride=4, s_n=5, s_mode=mode, a_mode=3, a_n=1 << 20, a_stride=0, soff=0) - p.ops = [_op("sbuf", 2, 16, r2, imm=16)] - regs, _ = p.model() - assert regs[0][r2].v == vf.FILL_VK and regs[0][r2 + 1].v == 0 - - -def test_perturbed_models_differ(): - p = _mem(a_mode=3, a_n=2 * vf.SLOT + 4, a_stride=0, soff=0) - p.ops = [_op("store_off", 2, 0, vf.POOL[0]), _op("load_off", 2, 0, vf.POOL[4])] - good, _ = p.model() - vf.PERTURB.add("whole_access") - try: - bad, _ = p.model() - finally: - vf.PERTURB.discard("whole_access") - assert good[2][vf.POOL[4] + 1].v == 0 and good[2][vf.POOL[4]].v != 0 - assert bad[2][vf.POOL[4]].v == 0 # all or nothing - assert vf.PERTURB == set() - - -def test_mem_accesses_stay_in_the_threads_slot(): - for p in vf.programs("mem", 4, 40, (32,)): - for op in p.ops: - extra = 12 if op["kind"] in ("store_io", "load_io") else 0 - assert 0 <= op["off"] + op["soff"] and op["off"] + op["soff"] + extra + 4 * op["n"] <= vf.SLOT, op - - -def test_mem_generator_reaches_every_kind_and_mode(): - kinds, modes = set(), set() - for p in vf.programs("mem", 1, 300, (32,)): - kinds |= {op["kind"] for op in p.ops} - modes |= {p.a_mode, p.b_mode, p.s_mode} - assert kinds == set(vf.MEM_OPS) and modes == {0, 1, 2, 3} - - -def test_f16_pack_of_a_signaling_nan_half_is_uncertain_and_a_quiet_one_is_compared(): - assert vf.is_f16_snan(0x7C96) and vf.is_f16_snan(0xFC01) and not vf.is_f16_snan(0x7E96) - assert not vf.is_f16_snan(0x7C00) and not vf.is_f16_snan(0x3C00) - p = vf.F16Family(1, 0, 32) - R = {r: vf.Reg(0x3C007E96) for r in vf.POOL} # a quiet NaN low half - d, s0, s1 = vf.POOL[1], vf.POOL[2], vf.POOL[3] - p.step({"name": "v_pack_b32_f16", "d": d, "s": [s0, s1], "opsel": [0, 1]}, R) - assert R[d].v == 0x3C007E96 and not R[d].ulo and not R[d].uhi - - -def test_compare_counts_the_words_it_does_not_judge(): - p = vf.F16Family(1, 0, 32) - data = struct.pack(f"<{vf.THREADS * len(vf.POOL)}I", *([0] * (vf.THREADS * len(vf.POOL)))) - vf.compare(p, data) - want, _ = p.model() - assert p.uncertain_words == sum(1 for t in range(vf.THREADS) for r in vf.POOL if want[t][r].ulo or want[t][r].uhi) - - -def test_unknown_skip_op_is_a_usage_error(monkeypatch, capsys): - monkeypatch.setattr(sys, "argv", ["valu_fuzz.py", "--family", "mem", "--model-only", "--skip-op", "store_raw"]) - with pytest.raises(SystemExit) as exc: - vf.main() - assert exc.value.code == 2 and "unknown op store_raw" in capsys.readouterr().err - - -def test_f16_pack_of_a_nan_half_is_uncertain(): - p = vf.F16Family(1, 0, 32) - R = {r: vf.Reg(0x3C007C96) for r in vf.POOL} # high half 1.0, low half a signaling NaN - d, s0, s1 = vf.POOL[1], vf.POOL[2], vf.POOL[3] - p.step({"name": "v_pack_b32_f16", "d": d, "s": [s0, s1], "opsel": [0, 1]}, R) - assert R[d].v == 0x3C007C96 and R[d].ulo and not R[d].uhi - - -# ------------------------------------------------------------------ the hardware kernels (text only, no GPU) - -def test_hw_kernels_use_the_mnemonics_of_their_family(): - p = vf.programs("mem", 3, 1, (32,))[0] - k10, k11 = "\n".join(p.hw_lines("gfx10")), "\n".join(p.hw_lines("gfx11")) - assert "global_store_dword " in k10 and "global_store_b32 " in k11 - assert "dword" not in "\n".join(ln for ln in k11.splitlines() if ln.startswith(("buffer_", "s_load", "s_buffer"))) - assert "s_add_u32 s44, s2, 0x1000" in k11 and "s[2:3]" in k11 # the V#s are built from the output pointer - assert f"{vf.word3(p.a_mode, 'gfx11'):#x}" in k11 and f"{vf.word3(p.a_mode, 'gfx10'):#x}" in k10 - - -def test_hw_mem_kernel_waits_for_stores_and_invalidates_the_scalar_cache(): - p = _mem(soff=0) - p.ops = [_op("store_off", 1, 0, vf.POOL[0]), _op("sload", 1, 0, vf.POOL[4], imm=0)] - text = p.hw_body("gfx11") - i_st = next(i for i, ln in enumerate(text) if ln.startswith("buffer_store")) - i_ld = next(i for i, ln in enumerate(text) if ln.startswith("s_load")) - assert "s_waitcnt_vscnt null, 0x0" in text[i_st:i_ld] and "s_dcache_inv" in text[i_st:i_ld] - asm_text = "\n".join(p.asm_body()) - assert "s_dcache_inv" not in asm_text and "s_waitcnt_vscnt" not in asm_text # the translator path is unchanged - vf.HW_SYNC = "none" - try: - assert not any("vscnt" in ln or "dcache" in ln for ln in p.hw_body("gfx11")) - finally: - vf.HW_SYNC = "scalar" - - -def test_f16_16bit_integer_opsel_is_encoded_where_the_gfx11_assembler_has_no_spelling(): - p = vf.F16Family(1, 0, 32) - op = {"name": "v_lshlrev_b16", "d": 22, "s": [20, 21], "enc": "e64", "opsel": [1, 0, 1], - "text": "v_lshlrev_b16_e64 v22, v20, v21 op_sel:[1,0,1]"} - p.ops = [op] - t11, t10 = "\n".join(p.hw_body("gfx11")), "\n".join(p.hw_body("gfx10")) - w0, w1 = vf.vop3_words(vf.GFX11_VOP3_OPCODE["v_lshlrev_b16"], 22, [20, 21], 0b1001) - assert f".long {w0:#x}" in t11 and f".long {w1:#x}" in t11 and "v_lshlrev_b16_e64" not in t11.split("// ")[0] - assert "v_lshlrev_b16_e64 v22, v20, v21 op_sel:[1,0,1]" in t10 # GFX10 assembles it - op["opsel"] = [0, 0, 0] - op["text"] = "v_lshlrev_b16_e64 v22, v20, v21 op_sel:[0,0,0]" - assert "v_lshlrev_b16_e64 v22, v20, v21" in p.hw_body("gfx11") and "op_sel" not in "\n".join(p.hw_body("gfx11")) - - -def _amd_tool(name): - clang = os.environ.get("LEONIDA_AMD_CLANG") - if not clang or not os.path.isfile(clang): - return None - tool = os.path.join(os.path.dirname(clang), name + (".exe" if os.name == "nt" else "")) - return tool if os.path.isfile(tool) else None - - -@pytest.mark.skipif(_amd_tool("llvm-mc") is None, reason="AMD llvm-mc (next to LEONIDA_AMD_CLANG) not found") -def test_gfx11_opcode_table_matches_llvm_mc(): - from hw_oracle import asm - - mc = _amd_tool("llvm-mc") - cmd = [mc, "-triple=amdgcn-amd-amdhsa", "-mcpu=gfx1150", "-show-encoding"] - - def assemble(text): - return subprocess.run(cmd, input=text, capture_output=True, text=True) - - true16 = asm.needs_true16(lambda text: assemble(text).returncode == 0) - for name, opcode in vf.GFX11_VOP3_OPCODE.items(): - text = f"{name} v20, v21, v22\n" - r = assemble(asm.true16_spelling(text) if true16 else text) - assert r.returncode == 0 and "encoding: [" in r.stdout, (name, r.stderr, r.stdout) - got = [int(b, 16) for b in r.stdout.split("encoding: [")[1].split("]")[0].split(",")] - w0, w1 = vf.vop3_words(opcode, 20, [21, 22], 0) - want = [w0 & 255, w0 >> 8 & 255, w0 >> 16 & 255, w0 >> 24, w1 & 255, w1 >> 8 & 255, w1 >> 16 & 255, w1 >> 24] - assert got == want, name - - -@pytest.mark.skipif(_amd_tool("clang") is None, reason="AMD clang (LEONIDA_AMD_CLANG) not found") -@pytest.mark.parametrize("family", sorted(vf.FAMILIES)) -@pytest.mark.parametrize("arch", ["gfx1150", "gfx1030", "gfx1170", "gfx1200", "gfx1201"]) -def test_hw_kernels_assemble(family, arch): - from hw_oracle import asm - fam = asm.family(arch) - cmd = [os.environ["LEONIDA_AMD_CLANG"], "--target=amdgcn-amd-amdhsa", f"-mcpu={arch}"] - assembler = ["-x", "assembler", "-c", "-", "-o", os.devnull] - - def assemble(text, wave=32): - return subprocess.run(cmd + (["-mwavefrontsize64"] if wave == 64 else []) + assembler, - input=text, capture_output=True, text=True) - - true16 = fam != "gfx10" and asm.needs_true16(lambda text: assemble(text).returncode == 0) - for p in vf.programs(family, 2, 12, (32, 64)): - k = asm.Kernel(p.hw_lines(fam), p.wave, vf.THREADS, p.out_words(), raw=True, vgprs=vf.HW_VGPRS, sgprs=vf.HW_SGPRS) - text = asm.module_text([k], arch, wave=p.wave)[0] - if true16: # what the runner assembles: the same respellings, same order - text = asm.true16_spelling(text) - if fam != "gfx10": - text = asm.opsel16_spelling(text) - r = assemble(text, p.wave) - assert r.returncode == 0, (arch, p.name, r.stderr[-600:]) # mem on gfx12xx too, in GFX12 spelling - - -def test_mem_kernels_in_gfx12_spelling(): - # GFX12 has no s_waitcnt_vscnt or buffer_gl0/gl1_inv, wants a null (not 0) MUBUF soffset, and assembles the legacy - # s_waitcnt vmcnt/lgkmcnt to the old encoding, so the gfx12 text names the split counters - for sync in ("none", "min", "sinv", "scalar", "full"): - old = vf.HW_SYNC - vf.HW_SYNC = sync - try: - for p in vf.programs("mem", 3, 20, (32, 64)): - g12, g11 = p.hw_lines("gfx12"), p.hw_lines("gfx11") - text = "\n".join(g12) - for gone in ("s_waitcnt_vscnt", "buffer_gl0_inv", "buffer_gl1_inv", "s_waitcnt vmcnt", "s_waitcnt lgkmcnt"): - assert gone not in text, (sync, p.name, gone) - assert not any(ln.startswith("buffer_") and re.search(r"\], 0\b", ln) for ln in g12), (sync, p.name) - assert any(ln.startswith("buffer_") for ln in g12) and "s_wait_loadcnt 0x0" in g12, (sync, p.name) - if sync in ("min", "scalar", "full"): - assert ("s_wait_storecnt 0x0" in g12) == ("s_waitcnt_vscnt null, 0x0" in g11), (sync, p.name) - if sync == "full" and "buffer_gl0_inv" in g11: - assert "global_inv scope:SCOPE_DEV" in g12, p.name - # the respelling is gfx12-only: the gfx11 kernel and the translator's text keep the GFX10/GFX11 forms - assert "s_waitcnt vmcnt(0)" in g11 and "s_wait_loadcnt 0x0" not in g11, (sync, p.name) - assert "s_wait_loadcnt" not in p.asm() and "s_waitcnt vmcnt(0)" in p.asm(), (sync, p.name) - finally: - vf.HW_SYNC = old - - -def test_gfx10_word3_is_refused_on_gfx12(monkeypatch, capsys): - # --gfx10-word3 sets bit 24 (GFX10 RESOURCE_LEVEL), which gfx12-rsrc.json names WRITE_COMPRESS_ENABLE - from hw_oracle import runner - - class Fake: - def __init__(self, arch): - self.arch, self.device, self.ran = arch, "fake", False - - def run(self, kernels): - self.ran = True - return ["assembler rejected: fake"] * len(kernels) - - def close(self): - pass - - for arch, want in (("gfx1201", 2), ("gfx1150", 2)): - fake = Fake(arch) - monkeypatch.setattr(runner, "open_oracle", lambda **kw: fake) - monkeypatch.setattr(sys, "argv", ["valu_fuzz.py", "--family", "mem", "--oracle", "hw", "--programs", "2", - "--gfx10-word3"]) - assert vf.main() == want, arch - out = capsys.readouterr().out - assert ("WRITE_COMPRESS_ENABLE" in out) == (arch == "gfx1201"), (arch, out[-300:]) - assert fake.ran == (arch != "gfx1201"), arch # refused before any kernel on gfx12; gfx11 still runs it - vf.W3_LAYOUT = None - - -def test_vsharp_word3_per_family(): - # GFX12 keeps GFX11's word 3 (gfx12-rsrc.json: same DST_SEL/FORMAT/OOB_SELECT bits, 32_FLOAT = 22 in the GFX11 - # table); GFX10 adds RESOURCE_LEVEL; a family without a known layout is refused, not given GFX11's by default - for mode in range(4): - assert vf.word3(mode, "gfx12") == vf.word3(mode, "gfx11") == 0xFAC | (22 << 12) | (mode << 28) - assert vf.word3(mode, "gfx10") == vf.word3(mode, "gfx11") | (1 << 24) - with pytest.raises(ValueError): - vf.word3(0, "gfx13") - - -def test_oracle_hw_exits_77_without_the_tools(monkeypatch, capsys, tmp_path): - monkeypatch.setenv("LEONIDA_AMD_CLANG", str(tmp_path / "no-such-clang.exe")) - for family in sorted(vf.FAMILIES): - monkeypatch.setattr(sys, "argv", ["valu_fuzz.py", "--family", family, "--oracle", "hw", "--programs", "2"]) - assert vf.main() == 77 - assert "hardware oracle unavailable" in capsys.readouterr().out - - -def test_hw_family_skip_reason_is_per_family(): - # the old blanket gate (asm.rdna23_skip_reason) refused every family on gfx1170+; every family runs on every - # architecture asm.family knows now (mem on gfx12xx in GFX12 spelling), and an unknown one is refused by name - for arch in ("gfx1030", "gfx1100", "gfx1150", "gfx1170", "gfx1200", "gfx1201"): - for family in sorted(vf.FAMILIES): - assert vf.hw_family_skip_reason(family, arch) is None, (family, arch) - why = vf.hw_family_skip_reason("mem", "gfx1300") - assert why and "gfx1300" in why, why - - -def test_oracle_hw_runs_on_an_rdna4_gpu(monkeypatch, capsys): - # regression: the blanket gate used to exit 77 for every family on gfx1170+ ("the kernels here do not - # assemble for it"), which is false for f16; the run now gets past the gate (the fake oracle rejects the - # kernels, so the exit code is 2, not 77) - from hw_oracle import runner - - class Fake: - def __init__(self, arch): - self.arch, self.device = arch, "fake" - - def run(self, kernels): - return ["assembler rejected: fake"] * len(kernels) - - def close(self): - pass - - for arch in ("gfx1170", "gfx1201"): - for family in sorted(vf.FAMILIES): - monkeypatch.setattr(runner, "open_oracle", lambda **kw: Fake(arch)) - monkeypatch.setattr(sys, "argv", ["valu_fuzz.py", "--family", family, "--oracle", "hw", "--programs", "2"]) - assert vf.main() == 2, (arch, family) - out = capsys.readouterr().out - assert "hardware oracle: fake" in out - assert "hardware oracle unavailable" not in out - - -def test_oracle_option_is_validated(monkeypatch): - for argv in (["--oracle", "gpu"], ["--negative-control"], ["--oracle", "translator", "--negative-control"]): - monkeypatch.setattr(sys, "argv", ["valu_fuzz.py", "--family", "mem", "--model-only", *argv]) - with pytest.raises(SystemExit) as exc: - vf.main() - assert exc.value.code == 2 - - -# ------------------------------------------------------------------ assembling (needs llvm-mc) - -def _mc(): - try: - sys.path.insert(0, os.path.join(ROOT, "runtime", "test", "shaders")) - import mc_command - cmd = mc_command.mc_command() - subprocess.run(cmd + ["--version"], capture_output=True, check=True) - return cmd - except Exception: - return None - - -def _mc_accepts_f16_opsel(mc): - """llvm-mc 21+ is needed for op_sel on 16-bit VOP3 (docs/testing.md); older builds reject the modifier. - - Probe a fixed instruction rather than a generated program, so a generator bug can never turn into a skip. The - probe is the form llvm-mc 18 rejects (docs/testing.md): a 16-bit integer op, which GFX10 has only as op_sel VOP3. - An f16 VOP2 op's VOP3 form takes no op_sel on GFX10 (tools/valu_fuzz.py), so no assembler accepts that as a probe. - """ - probe = "v_ashrrev_i16_e64 v0, v1, v2 op_sel:[0,0,0]\n" - r = subprocess.run(mc + ["-triple=amdgcn--amdpal", "-mcpu=gfx1013"], input=probe, - capture_output=True, text=True) - return r.returncode == 0 and "error:" not in r.stderr - - -def test_f16_opsel_probe_distinguishes_old_assemblers(): - # A fake assembler that rejects everything stands in for LLVM < 21; one that accepts stdin stands in for 21+. - reject = [sys.executable, "-c", "import sys; sys.exit(1)"] - accept = [sys.executable, "-c", "import sys; sys.stdin.read()"] - assert _mc_accepts_f16_opsel(reject) is False - assert _mc_accepts_f16_opsel(accept) is True - - -@pytest.mark.skipif(_mc() is None, reason="llvm-mc with the AMDGPU target not found") -@pytest.mark.parametrize("family", sorted(vf.FAMILIES)) -def test_programs_assemble_for_gfx1013(family): - mc = _mc() - if family == "f16" and not _mc_accepts_f16_opsel(mc): - pytest.skip("llvm-mc 21+ is needed for op_sel on 16-bit VOP3 (docs/testing.md); set LLVM_MC") - for p in vf.programs(family, 1, 6, (32, 64)): - cmd = mc + ["-triple=amdgcn--amdpal", "-mcpu=gfx1013", "-show-encoding"] - if p.wave == 64: - cmd.append("-mattr=+wavefrontsize64,-wavefrontsize32") - r = subprocess.run(cmd, input=p.asm(), capture_output=True, text=True) - assert r.returncode == 0 and "error:" not in r.stderr, r.stderr[-800:] - - -def test_model_only_runs_every_family(capsys, monkeypatch): - for family in sorted(vf.FAMILIES): - monkeypatch.setattr(sys, "argv", ["valu_fuzz.py", "--family", family, "--programs", "4", "--model-only"]) - assert vf.main() == 0 - assert "programs generated and modelled" in capsys.readouterr().out - - -@pytest.mark.parametrize("extra", [ - ["--programs", "0"], - ["--programs", "-5"], - ["--max-report", "0"], - ["--max-report", "-1"], -]) -def test_cli_rejects_non_positive_programs_and_max_report(extra, capsys, monkeypatch): - monkeypatch.setattr(sys, "argv", ["valu_fuzz.py", "--family", "f16", "--model-only", *extra]) - with pytest.raises(SystemExit) as exc: - vf.main() - assert exc.value.code == 2 - assert "--programs and --max-report must be at least 1" in capsys.readouterr().err - - -@pytest.mark.parametrize("bad", ["", "1", "a:b", "1:2:64:99", "1:-1", "1:2:16"]) -def test_cli_rejects_invalid_show(bad, capsys, monkeypatch): - monkeypatch.setattr(sys, "argv", ["valu_fuzz.py", "--family", "f16", "--show", bad]) - with pytest.raises(SystemExit) as exc: - vf.main() - assert exc.value.code == 2 - assert "--show expects SEED:INDEX[:WAVE] with INDEX >= 0 and WAVE in 32, 64" in capsys.readouterr().err - - -@pytest.mark.parametrize("spec", ["1:0", "1:2:32", "1:2:64"]) -def test_cli_show_valid_formats(spec, capsys, monkeypatch): - monkeypatch.setattr(sys, "argv", ["valu_fuzz.py", "--family", "f16", "--show", spec]) - assert vf.main() == 0 - assert "; model, thread 0:" in capsys.readouterr().out - - -# ------------------------------------------------------------------ runner (translator and GPU faked) - -UNPINNED = "device: llvmpipe (LLVM 20.1.2, 256 bits) (subgroup 8..8)\ncompute subgroup size: 32 not available" - - -def _run_main(monkeypatch, capsys, tmp_path, msg, extra): - """main() for two mem programs, every run returning all-zero words and vk_compute_test output `msg`.""" - def translate(progs, work, _emulate): - (work / "spirv").mkdir(parents=True, exist_ok=True) - for p in progs: - (work / "spirv" / (p.name + ".spv")).touch() - return {p.name: {} for p in progs}, "" - - def run_gpu(p, _spv, _build, _entry, _emulate, dump): - dump.write_bytes(bytes(4 * p.out_words())) - return 0, msg - - monkeypatch.setattr(vf, "translate", translate) - monkeypatch.setattr(vf, "run_gpu", run_gpu) - monkeypatch.setattr(sys, "argv", ["valu_fuzz.py", "--family", "mem", "--programs", "2", "--work", str(tmp_path), - *extra]) - status = vf.main() - return status, capsys.readouterr().out - - -def test_unpinned_wave32_is_a_skip_not_a_mismatch(monkeypatch, capsys, tmp_path): - status, out = _run_main(monkeypatch, capsys, tmp_path, UNPINNED, ["--wave", "32"]) - assert status == 2, out # nothing ran - assert "MISMATCH" not in out - assert "2 skipped" in out and "can't run it at 32 lanes" in out - - -def test_pinned_wave32_is_still_compared(monkeypatch, capsys, tmp_path): - status, out = _run_main(monkeypatch, capsys, tmp_path, "compute subgroup size: 32", ["--wave", "32"]) - assert status == 1, out - assert "MISMATCH" in out - - -def test_emulated_wave64_is_compared_at_any_subgroup_size(monkeypatch, capsys, tmp_path): - status, out = _run_main(monkeypatch, capsys, tmp_path, UNPINNED, ["--wave", "64", "--emulate"]) - assert status == 1, out - assert "MISMATCH" in out and "0 skipped" in out - - -def test_gpu_timeout_is_a_harness_error_and_next_program_runs(monkeypatch, capsys, tmp_path): - build = tmp_path / "build" - build.mkdir() - (build / ("vk_compute_test" + (".exe" if os.name == "nt" else ""))).touch() - progs = vf.programs("f16", 1, 2, (32,)) - attempted = [] - - def translate(progs, work, _emulate): - (work / "spirv").mkdir() - for p in progs: - (work / "spirv" / (p.name + ".spv")).touch() - return {p.name: {} for p in progs}, "" - - def run(cmd, *, env, timeout, **kwargs): - assert timeout == 0.25 - name = os.path.splitext(os.path.basename(cmd[1]))[0] - attempted.append(name) - if name == progs[0].name: - raise subprocess.TimeoutExpired(cmd, timeout) - with open(env["VKC_DUMP"], "wb") as dump: - dump.write(bytes(4 * progs[1].out_words())) - return subprocess.CompletedProcess(cmd, 0, "compute subgroup size: 32", "") - - def compare(prog, data): - prog.uncertain_words = 0 - return [] - - monkeypatch.setenv("LEONIDA_GPU_TEST_TIMEOUT", "0.25") - monkeypatch.delenv("LEONIDA_PC_TAIL_UBO", raising=False) - monkeypatch.setattr(vf, "translate", translate) - monkeypatch.setattr(vf.subprocess, "run", run) - monkeypatch.setattr(vf, "compare", compare) - monkeypatch.setattr(sys, "argv", ["valu_fuzz.py", "--family", "f16", "--programs", "2", "--wave", "32", - "--build", str(build), "--work", str(tmp_path)]) - - assert vf.main() == 2 - assert attempted == [p.name for p in progs] - out = capsys.readouterr().out - assert f"ERROR {progs[0].name}" in out and "timed out after 0.25 s" in out - assert "1/1 programs that ran match" in out and "1 harness errors" in out - - -def test_failed_gpu_child_with_unpinned_warning_is_a_harness_error(monkeypatch, capsys, tmp_path): - """vk_compute_test prints the unpinned-subgroup warning, writes a full dump and then exits 1: that is a failed - run, not a skip, so the fuzzer exits 2 even when the other program matches.""" - build = tmp_path / "build" - build.mkdir() - (build / ("vk_compute_test" + (".exe" if os.name == "nt" else ""))).touch() - progs = vf.programs("f16", 1, 2, (32,)) - - def translate(progs, work, _emulate): - (work / "spirv").mkdir() - for p in progs: - (work / "spirv" / (p.name + ".spv")).touch() - return {p.name: {} for p in progs}, "" - - def run(cmd, *, env, timeout, **kwargs): - name = os.path.splitext(os.path.basename(cmd[1]))[0] - prog = next(p for p in progs if p.name == name) - with open(env["VKC_DUMP"], "wb") as dump: - dump.write(bytes(4 * prog.out_words())) - if name == progs[0].name: - return subprocess.CompletedProcess(cmd, 1, UNPINNED + "\n", "vkQueueSubmit failed\n") - return subprocess.CompletedProcess(cmd, 0, "compute subgroup size: 32", "") - - def compare(prog, data): - prog.uncertain_words = 0 - return [] - - monkeypatch.delenv("LEONIDA_PC_TAIL_UBO", raising=False) - monkeypatch.setattr(vf, "translate", translate) - monkeypatch.setattr(vf.subprocess, "run", run) - monkeypatch.setattr(vf, "compare", compare) - monkeypatch.setattr(sys, "argv", ["valu_fuzz.py", "--family", "f16", "--programs", "2", "--wave", "32", - "--build", str(build), "--work", str(tmp_path)]) - - assert vf.main() == 2 - out = capsys.readouterr().out - assert f"ERROR {progs[0].name}: exit 1" in out and f"SKIP {progs[0].name}" not in out - assert "1/1 programs that ran match" in out and "0 skipped" in out and "1 harness errors" in out - - -def test_pc_tail_ubo_forwarded_to_translator_and_vk_compute_test(monkeypatch, tmp_path): - cmds = [] - - def fake_run(cmd, **kw): - cmds.append((list(cmd), kw.get("env"))) - out_dir = tmp_path / "spirv" - out_dir.mkdir(parents=True, exist_ok=True) - (out_dir / "index.json").write_text("{}", encoding="utf-8") - return subprocess.CompletedProcess(cmd, 0, "", "") - - monkeypatch.setattr(vf.mc_command, "mc_command", lambda: ["llvm-mc"]) - monkeypatch.setattr(vf.subprocess, "run", fake_run) - vf.translate([], tmp_path, False) - vf.translate([], tmp_path, False, pc_tail=True) - assert "--pc-tail-ubo" not in cmds[0][0] - assert "--pc-tail-ubo" in cmds[1][0] - - build = tmp_path / "build" - build.mkdir() - (build / ("vk_compute_test" + (".exe" if os.name == "nt" else ""))).touch() - monkeypatch.delenv("LEONIDA_PC_TAIL_UBO", raising=False) - prog = vf.FAMILIES["mem"](1, 0, 32) - vf.run_gpu(prog, tmp_path / "a.spv", str(build), {}, False, tmp_path / "a.bin") - vf.run_gpu(prog, tmp_path / "a.spv", str(build), {}, False, tmp_path / "a.bin", pc_tail=True) - assert "LEONIDA_PC_TAIL_UBO" not in cmds[2][1] - assert cmds[3][1]["LEONIDA_PC_TAIL_UBO"] == "1" - - -def test_pc_tail_ubo_from_flag_or_env(monkeypatch, tmp_path): - for extra, env_val, want in ( - ([], "", False), - (["--pc-tail-ubo"], "", True), - ([], "1", True), - ([], "true", True), - ([], "0", False), - ): - seen_t, seen_g = [], [] - - def fake_translate(progs, work, _emulate, pc_tail=False): - seen_t.append(pc_tail) - (work / "spirv").mkdir(parents=True, exist_ok=True) - for p in progs: - (work / "spirv" / (p.name + ".spv")).touch() - return {p.name: {} for p in progs}, "" - - def fake_run_gpu(p, _spv, _build, _entry, _emulate, dump, pc_tail=False): - seen_g.append(pc_tail) - return 77, "unsupported: test" - - monkeypatch.setenv("LEONIDA_PC_TAIL_UBO", env_val) - monkeypatch.setattr(vf, "translate", fake_translate) - monkeypatch.setattr(vf, "run_gpu", fake_run_gpu) - monkeypatch.setattr(sys, "argv", ["valu_fuzz.py", "--family", "mem", "--programs", "1", - "--wave", "32", "--work", str(tmp_path), *extra]) - vf.main() - assert seen_t == [want] and seen_g == [want], (extra, env_val) - - -def test_parallel_assembly_preserves_wave_flags_and_inputs(monkeypatch, tmp_path): - progs = vf.programs("f16", 1, 2, (32, 64)) - waves = {prog.asm(): prog.wave for prog in progs} - barrier = None - - def fake_assemble(cmd, *, input, **kwargs): - assert ("-mattr=+wavefrontsize64,-wavefrontsize32" in cmd) == (waves[input] == 64) - if barrier: - barrier.wait(timeout=10) - return subprocess.CompletedProcess(cmd, 0, "\t.text\ns_endpgm\n", "") - - def fake_translate(cmd, **kwargs): - output = Path(cmd[cmd.index("--out") + 1]) - assert len(list((output.parent / "disasm").glob("*.s"))) == len(progs) - assert len(list((output.parent / "fssm").glob("*.fssm"))) == len(progs) - output.mkdir() - (output / "index.json").write_text("{}", encoding="utf-8", newline="\n") - return subprocess.CompletedProcess(cmd, 0, "", "") - - monkeypatch.setattr(vf.mc_command, "mc_command", lambda: ["llvm-mc"]) - monkeypatch.setattr(vf.mc_command, "run", fake_assemble) - monkeypatch.setattr(vf.subprocess, "run", fake_translate) - serial = tmp_path / "serial" - parallel = tmp_path / "parallel" - vf.translate(progs, serial, False) - barrier = threading.Barrier(2) - vf.translate(progs, parallel, False, asm_jobs=2) - for path in serial.rglob("*"): - if path.is_file(): - assert path.read_bytes() == (parallel / path.relative_to(serial)).read_bytes() - - -def test_parallel_assembly_bounds_submitted_jobs(monkeypatch, tmp_path): - programs = vf.programs("f16", 1, 5, (32, 64)) - submitted = 0 - collected = 0 - peak = 0 - - class MeasuringExecutor(vf.ThreadPoolExecutor): - def submit(self, fn, *args, **kwargs): - nonlocal submitted, peak - future = super().submit(fn, *args, **kwargs) - submitted += 1 - peak = max(peak, submitted - collected) - collect = future.result - - def result(*args, **kwargs): - nonlocal collected - collected += 1 - return collect(*args, **kwargs) - - future.result = result - return future - - def fake_translate(cmd, **kwargs): - output = Path(cmd[cmd.index("--out") + 1]) - output.mkdir() - (output / "index.json").write_text("{}", encoding="utf-8", newline="\n") - return subprocess.CompletedProcess(cmd, 0, "", "") - - monkeypatch.setattr(vf, "ThreadPoolExecutor", MeasuringExecutor) - monkeypatch.setattr(vf.mc_command, "mc_command", lambda: ["llvm-mc"]) - monkeypatch.setattr(vf.mc_command, "run", lambda cmd, **kw: subprocess.CompletedProcess(cmd, 0, "s_endpgm\n", "")) - monkeypatch.setattr(vf.subprocess, "run", fake_translate) - vf.translate(programs, tmp_path, False, asm_jobs=2) - assert submitted == collected == len(programs) - assert peak == 4 diff --git a/tests/test_valu_int_diff.py b/tests/test_valu_int_diff.py deleted file mode 100644 index d87b1fc1d..000000000 --- a/tests/test_valu_int_diff.py +++ /dev/null @@ -1,38 +0,0 @@ -"""Tests for tools/valu_int_diff.py: integer & packed-16bit VALU differential fuzzer (no game data, stdlib only).""" -import os -import sys -import unittest - -ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) -TOOLS = os.path.join(ROOT, "tools") -if TOOLS not in sys.path: - sys.path.insert(0, TOOLS) - -import valu_int_diff # noqa: E402 - - -class ValuIntDiffTests(unittest.TestCase): - def test_self_test_and_negative_controls(self): - valu_int_diff.self_test() - - def test_seeded_100_programs_match(self): - fail = valu_int_diff.run_fuzz(programs=100, seed=11, max_ops=16, spirv_val=False) - self.assertIsNone(fail) - - def test_reference_catches_perturbed_translator_output(self): - # Verify our comparison would catch a wrong clamp/wrap or op_sel output. - lines = [ - "v_mov_b32_e32 v0, 0xffffffff", - "v_mov_b32_e32 v1, 0x00000005", - "v_add_nc_u32_e64 v0, v0, v1 clamp", - "exp mrt0 v0, v0, v0, v0 done vm", - "s_endpgm", - ] - got = valu_int_diff.translate_and_run(lines, name="ps_valu_int_neg_ctrl") - self.assertEqual(got, [0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF]) - wrong_unclamped = valu_int_diff.eval_ref_op("v_add_nc_u32", [0xFFFFFFFF, 5], 0, clamp=False) - self.assertNotEqual(got[0], wrong_unclamped) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/test_values.py b/tests/test_values.py deleted file mode 100644 index 7bfbe77e9..000000000 --- a/tests/test_values.py +++ /dev/null @@ -1,129 +0,0 @@ -"""Computed values for the instruction families listed in rdna2spirv.py's "Supported" docstring. - -Each case runs a tiny pixel shader through the translator and the SPIR-V interpreter (tests/spirv_interp.py) and -compares v3 with a reference written in plain Python from the RDNA2 ISA definition of the instruction. No GPU, -llvm-mc or spirv-tools needed. These tests check values; spirv-val validity is covered by test_translate.py. -""" -import math -import struct - -import pytest - -import spirv_interp as si -from listing import translate_listing - -M = 0xFFFFFFFF - - -def fb(x): - return si.f2u(si.f32(x)) - - -def run_v3(tmp_path, asm, v1=0, v2=0, v4=0): - pre = f"v_mov_b32 v1, {v1:#x}\nv_mov_b32 v2, {v2:#x}\nv_mov_b32 v4, {v4:#x}\n" - return si.run(translate_listing(tmp_path, pre + asm)).vgpr[3] - - -def s(x): - return x & M - - -# id: (asm, v1, v2, v4, expected bits of v3) -CASES = { - # float ALU - "v_add_f32": ("v_add_f32 v3, v1, v2", fb(1.5), fb(2.25), 0, fb(3.75)), - "v_sub_f32": ("v_sub_f32 v3, v1, v2", fb(1.5), fb(2.25), 0, fb(-0.75)), - "v_subrev_f32": ("v_subrev_f32 v3, v1, v2", fb(1.5), fb(2.25), 0, fb(0.75)), - "v_mul_f32": ("v_mul_f32 v3, v1, v2", fb(1.5), fb(-2.0), 0, fb(-3.0)), - "v_fma_f32": ("v_fma_f32 v3, v1, v2, v4", fb(1.5), fb(2.0), fb(0.25), fb(3.25)), - "v_max_f32": ("v_max_f32 v3, v1, v2", fb(1.5), fb(-2.0), 0, fb(1.5)), - "v_min_f32": ("v_min_f32 v3, v1, v2", fb(1.5), fb(-2.0), 0, fb(-2.0)), - "v_rcp_f32": ("v_rcp_f32 v3, v1", fb(4.0), 0, 0, fb(0.25)), - "v_rsq_f32": ("v_rsq_f32 v3, v1", fb(4.0), 0, 0, fb(0.5)), - "v_sqrt_f32": ("v_sqrt_f32 v3, v1", fb(9.0), 0, 0, fb(3.0)), - "v_exp_f32": ("v_exp_f32 v3, v1", fb(3.0), 0, 0, fb(8.0)), - "v_log_f32": ("v_log_f32 v3, v1", fb(8.0), 0, 0, fb(3.0)), - "v_floor_f32": ("v_floor_f32 v3, v1", fb(-1.5), 0, 0, fb(-2.0)), - "v_ceil_f32": ("v_ceil_f32 v3, v1", fb(-1.5), 0, 0, fb(-1.0)), - "v_trunc_f32": ("v_trunc_f32 v3, v1", fb(-1.5), 0, 0, fb(-1.0)), - "v_fract_f32": ("v_fract_f32 v3, v1", fb(-1.25), 0, 0, fb(0.75)), - "v_med3_f32": ("v_med3_f32 v3, v1, v2, v4", fb(5.0), fb(1.0), fb(3.0), fb(3.0)), - "v_med3_f32_clamp": ("v_med3_f32 v3, v1, v2, v4 clamp", fb(2.0), fb(0.5), fb(1.5), fb(1.0)), - "v_med3_f32_mul_2": ("v_med3_f32 v3, v1, v2, v4 mul:2", fb(2.0), fb(0.5), fb(1.5), fb(3.0)), - "v_med3_f32_clamp_div_2": ("v_med3_f32 v3, v1, v2, v4 clamp div:2", fb(2.0), fb(0.5), fb(1.5), fb(0.75)), - "neg_modifier": ("v_add_f32 v3, -v1, v2", fb(1.5), fb(2.0), 0, fb(0.5)), - "abs_modifier": ("v_add_f32 v3, |v1|, v2", fb(-1.5), fb(2.0), 0, fb(3.5)), - "clamp": ("v_add_f32_e64 v3, v1, v2 clamp", fb(1.5), fb(2.0), 0, fb(1.0)), - "mul_2": ("v_add_f32_e64 v3, v1, v2 mul:2", fb(1.5), fb(2.0), 0, fb(7.0)), - # conversions - "v_cvt_f32_u32": ("v_cvt_f32_u32 v3, v1", 7, 0, 0, fb(7.0)), - "v_cvt_f32_i32": ("v_cvt_f32_i32 v3, v1", s(-7), 0, 0, fb(-7.0)), - "v_cvt_u32_f32": ("v_cvt_u32_f32 v3, v1", fb(7.9), 0, 0, 7), - "v_cvt_i32_f32": ("v_cvt_i32_f32 v3, v1", fb(-7.9), 0, 0, s(-7)), - # integer ALU - "v_add_nc_u32": ("v_add_nc_u32 v3, v1, v2", 0xFFFFFFFF, 2, 0, 1), - "v_sub_nc_u32": ("v_sub_nc_u32 v3, v1, v2", 5, 7, 0, s(-2)), - "v_and_b32": ("v_and_b32 v3, v1, v2", 0xF0F0, 0xFF00, 0, 0xF000), - "v_or_b32": ("v_or_b32 v3, v1, v2", 0xF0F0, 0x0F00, 0, 0xFFF0), - "v_xor_b32": ("v_xor_b32 v3, v1, v2", 0xFF, 0x0F, 0, 0xF0), - "v_lshlrev_b32": ("v_lshlrev_b32 v3, v1, v2", 4, 0x0F, 0, 0xF0), - "v_lshrrev_b32": ("v_lshrrev_b32 v3, v1, v2", 4, 0xF0, 0, 0x0F), - "v_ashrrev_i32": ("v_ashrrev_i32 v3, v1, v2", 4, 0x80000000, 0, 0xF8000000), - "v_lshlrev_b32_wraps_amount": ("v_lshlrev_b32 v3, v1, v2", 36, 1, 0, 16), # shift amount is v1 & 31 - "v_bfe_u32": ("v_bfe_u32 v3, v1, v2, v4", 0xABCD1234, 8, 12, 0xD12), - "v_mul_u32_u24": ("v_mul_u32_u24 v3, v1, v2", 0x01000003, 5, 0, 15), # only the low 24 bits are used - "v_mad_u32_u24": ("v_mad_u32_u24 v3, v1, v2, v4", 3, 5, 100, 115), - "v_not_b32": ("v_not_b32 v3, v1", 0x0F0F0F0F, 0, 0, 0xF0F0F0F0), - "v_or3_b32": ("v_or3_b32 v3, v1, v2, v4", 1, 2, 4, 7), - "v_add3_u32": ("v_add3_u32 v3, v1, v2, v4", 1, 2, 4, 7), - "v_xor3_b32": ("v_xor3_b32 v3, v1, v2, v4", 7, 3, 1, 5), - "v_bcnt_u32_b32": ("v_bcnt_u32_b32 v3, v1, v2", 0xFF00FF, 1, 0, 17), - # f16 packing - "v_pack_b32_f16": ("v_pack_b32_f16 v3, v1, v2", 0xAAAA3C00, 0xBBBB4000, 0, 0x40003C00), - "v_pack_b32_f16_sel": ("v_pack_b32_f16 v3, v1, v2 op_sel:[1,0,0]", 0x3C00BBBB, 0xAAAA4000, 0, 0x4000 << 16 | 0x3C00), - "v_pack_b32_f16_sel_hi": ("v_pack_b32_f16 v3, v1, v2 op_sel:[0,1,0]", 0xAAAA3C00, 0x4000BBBB, 0, 0x4000 << 16 | 0x3C00), - # SHADER-260: a `neg` on this instruction flips the sign bit of the half it packs (gfx1036, IEEE mode 0), not - # of the whole 32-bit source, and only that half. - "v_pack_b32_f16_neg_lo": ("v_pack_b32_f16 v3, neg(v1), v2", 0xAAAA3C00, 0xBBBB4000, 0, 0x4000BC00), - "v_pack_b32_f16_neg_hi_sel": ("v_pack_b32_f16 v3, v1, neg(v2) op_sel:[0,1,0]", 0xAAAA3C00, 0x4000BBBB, 0, - 0xC0003C00), - # `abs` is the ISA's sign clear (|S|), applied before `neg`; it has no hardware run of this instruction yet. - "v_pack_b32_f16_abs_lo": ("v_pack_b32_f16 v3, abs(v1), v2", 0xAAAABC00, 0xBBBB4000, 0, 0x40003C00), - "v_pack_b32_f16_abs_snan": ("v_pack_b32_f16 v3, abs(v1), v2", 0xAAAAFC01, 0xBBBB4000, 0, 0x40007C01), - "v_pack_b32_f16_neg_abs": ("v_pack_b32_f16 v3, -abs(v1), v2", 0xAAAA3C00, 0xBBBB4000, 0, 0x4000BC00), - # 16-bit float add keeps the other half of the destination (GFX10 partial write; see docs/design.md). - # These pin the translator's keep; they do not reproduce the AMD driver quirk in valu_fuzz f16 - # seed 3 programme 38, where the same keep is lost on the GPU (driver 26.11.1, RX 9070). - "v_add_f16_e64_keep_hi": ("v_mov_b32 v3, 0xCD524000\nv_add_f16_e64 v3, v3, v1", 0x3C00, 0, 0, 0xCD524200), - "v_add_f16_e32_keep_hi": ("v_mov_b32 v3, 0xCD524000\nv_add_f16 v3, v1, v2", 0x3C00, 0x4200, 0, 0xCD524400), - # 16-bit integer (VOP3 form keeps the high half of the destination; see docs/design.md) - "v_add_u16_e64": ("v_add_u16_e64 v3, v1, v2", 0xFFFF, 2, 0, 1), -} - - -@pytest.mark.parametrize("case", sorted(CASES)) -def test_value(case, tmp_path): - asm, v1, v2, v4, want = CASES[case] - got = run_v3(tmp_path, asm, v1, v2, v4) - assert got == want, f"{asm}: got {got:#010x}, want {want:#010x}" - - -def test_scalar_alu(tmp_path): - asm = ("s_mov_b32 s40, 0x12\ns_add_u32 s41, s40, 0xff\ns_lshl_b32 s42, s41, 4\ns_and_b32 s43, s42, 0xfff0\n" - "s_or_b32 s44, s43, 1\ns_lshr_b32 s45, s44, 1\ns_mul_i32 s46, s45, 3\nv_mov_b32 v3, s46\n") - s41 = 0x12 + 0xFF - s42 = s41 << 4 - s43 = s42 & 0xFFF0 - s45 = (s43 | 1) >> 1 - got = si.run(translate_listing(tmp_path, asm)).vgpr[3] - assert got == (s45 * 3) & M - - -def test_inline_float_constants(tmp_path): - asm = "v_mov_b32 v1, 0.5\nv_add_f32 v3, v1, 4.0" - assert si.run(translate_listing(tmp_path, asm)).vgpr[3] == fb(4.5) - - -def test_export_reaches_mrt0(tmp_path): - res = si.run(translate_listing(tmp_path, "v_mov_b32 v3, 0x3f800000")) - assert res.outputs["out_mrt0"] == (1.0, 1.0, 1.0, 1.0) diff --git a/tests/test_vcmp16_opsel_probe.py b/tests/test_vcmp16_opsel_probe.py deleted file mode 100644 index b4833cbcd..000000000 --- a/tests/test_vcmp16_opsel_probe.py +++ /dev/null @@ -1,70 +0,0 @@ -"""tools/vcmp16_opsel_probe.py without a GPU: the raw compare and control words are llvm-mc's with OPSEL where llvm-mc -puts it, the rows tell the two hypotheses apart, and the kernel builds. - - python -I tests/test_vcmp16_opsel_probe.py -""" -import os -import sys -import unittest - -ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) -sys.path.insert(0, os.path.join(ROOT, "tools")) -sys.path.insert(0, os.path.join(ROOT, "tools", "hw_oracle")) - -import vcmp16_opsel_probe as p # noqa: E402 - - -def le_bytes(w0, w1): - return list(w0.to_bytes(4, "little") + w1.to_bytes(4, "little")) - - -class EncodingTest(unittest.TestCase): - def test_compares_without_opsel_are_llvm_mc_words(self): - # llvm-mc 21.1.8 -mcpu=gfx1036 -show-encoding for `v_cmp__e64 s10, v1, v2` - self.assertEqual(le_bytes(*p.words("lt", "f16", (0, 0))), [0x0A, 0x00, 0xC9, 0xD4, 0x01, 0x05, 0x02, 0x00]) - self.assertEqual(le_bytes(*p.words("gt", "u16", (0, 0))), [0x0A, 0x00, 0xAC, 0xD4, 0x01, 0x05, 0x02, 0x00]) - self.assertEqual(le_bytes(*p.words("lt", "i16", (0, 0))), [0x0A, 0x00, 0x89, 0xD4, 0x01, 0x05, 0x02, 0x00]) - # `v_cmp_lt_f16_e64 s10, -v1, v2` - self.assertEqual(le_bytes(*p.words("lt", "f16", (0, 0), True))[7], 0x20) - - def test_opsel_sits_where_llvm_mc_puts_it_on_v_add_nc_u16(self): - # llvm-mc for `v_add_nc_u16 v0, v1, v2 op_sel:[1,0,0]` / [0,1,0] / [1,1,0]: byte 1 = 0x08 / 0x10 / 0x18 - self.assertEqual(p.OPSEL_SRC0 >> 8, 0x08) - self.assertEqual(p.OPSEL_SRC1 >> 8, 0x10) - self.assertEqual(le_bytes(*p.words("lt", "f16", (1, 1)))[1], 0x18) # the finding's d4c9180a - - def test_control_answers(self): - self.assertEqual(p.control_answer((0, 0), True), 0x000C) - self.assertEqual(p.control_answer((1, 1), True), 0x0340) - self.assertEqual({p.control_answer(s, False) for _n, s in p.control_rows()}, {0x000C}) - - -class RowsTest(unittest.TestCase): - def test_names_are_unique(self): - rows = p.rows() - self.assertEqual(len({r[0] for r in rows}), len(rows)) - - def test_every_kind_and_opsel_bit_has_a_row_that_tells_the_hypotheses_apart(self): - telling = [r for r in p.rows() if p.answer(r, True) != p.answer(r, False)] - for kind in ("f16", "u16", "i16"): - for opsel in ((1, 0), (0, 1), (1, 1)): - with self.subTest(kind=kind, opsel=opsel): - self.assertTrue(any(r[2] == kind and r[4] == opsel for r in telling)) - - def test_i16_reads_the_high_half_signed(self): - row = next(r for r in p.rows() if r[0] == "i16_lt_opsel01") - self.assertEqual(p.half_value(0x8000, "i16"), -32768) - self.assertEqual(p.answer(row, True), 0) # 5 < 3: false - row = next(r for r in p.rows() if r[0] == "i16_lt_opsel10") - self.assertEqual(p.answer(row, True), 1) # -32768 < 7 - - def test_kernel_builds(self): - rows = p.rows() - lines = p.kernel(rows) - self.assertEqual(sum(ln.startswith(".long 0xd4") for ln in lines), len(rows)) - self.assertEqual(sum(ln.startswith(".long 0xd703") for ln in lines), len(p.control_rows())) - self.assertEqual("\n".join(lines).count("global_store_b32"), len(rows) + len(p.control_rows())) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/test_veh_spawn_intensities.py b/tests/test_veh_spawn_intensities.py deleted file mode 100644 index d73f37d18..000000000 --- a/tests/test_veh_spawn_intensities.py +++ /dev/null @@ -1,199 +0,0 @@ -"""Synthetic checks for tools/veh_spawn_intensities.py: the aggregate census of the vehicle -spawn-intensity table, band ranges, mud-band placement and rain grouping. Every entry name and -value in the fixtures is made up; the checker also asserts the CLI never prints key names, which -is game data. - - python -I tests/test_veh_spawn_intensities.py -""" -import contextlib -import io -import json -import os -import subprocess -import sys -import tempfile -import unittest - -ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) -TOOL = os.path.join(ROOT, "tools", "veh_spawn_intensities.py") -sys.path.insert(0, os.path.join(ROOT, "tools")) - -import veh_spawn_intensities as vsi # noqa: E402 - -# Entries shaped like the table: one 7-band ladder, one variant with mud in band 6, one 2-band. -A_SETS = [(-1.0, 0.0, 0.0, 0.0), (0.0, 0.1, 0.0, 0.0), (0.1, 0.2, 0.0, 0.0), (0.2, 0.4, 0.0, 0.0), - (0.3, 0.6, 0.0, 0.0), (0.4, 0.8, 0.0, 0.0), (0.5, 1.0, 0.8, 1.0)] -B_SETS = A_SETS[:5] + [(0.45, 0.9, 0.9, 1.0), (0.5, 1.0, 0.8, 1.0)] -C_SETS = [(0.1, 0.3, 0.0, 0.0), (0.3, 0.9, 0.0, 0.0)] - -DOC = """ - - - - spawn_alpha_test - - {a_sets} - - - - - spawn_beta_test - - {b_sets} - - - - - spawn_gamma_test - - {c_sets} - - - - - -""".format( - a_sets="".join(f'' - f'' for a, b, c, d in A_SETS), - b_sets="".join(f'' - f'' for a, b, c, d in B_SETS), - c_sets="".join(f'' - f'' for a, b, c, d in C_SETS), -) - -WANT = { - "bands_with_mud": [0, 0, 0, 0, 0, 1, 2], - "entries": 3, - "rain_group_sizes": [1, 1, 1], - "rain_groups": 3, - "set_counts": [2, 7], - "signature_groups": [1, 1, 1], - "signatures": 3, - "per_set_ranges": [ - {"DirtMax": [0.0, 0.3], "DirtMin": [-1.0, 0.1], "MudMax": [0.0, 0.0], "MudMin": [0.0, 0.0]}, - {"DirtMax": [0.1, 0.9], "DirtMin": [0.0, 0.3], "MudMax": [0.0, 0.0], "MudMin": [0.0, 0.0]}, - {"DirtMax": [0.2, 0.2], "DirtMin": [0.1, 0.1], "MudMax": [0.0, 0.0], "MudMin": [0.0, 0.0]}, - {"DirtMax": [0.4, 0.4], "DirtMin": [0.2, 0.2], "MudMax": [0.0, 0.0], "MudMin": [0.0, 0.0]}, - {"DirtMax": [0.6, 0.6], "DirtMin": [0.3, 0.3], "MudMax": [0.0, 0.0], "MudMin": [0.0, 0.0]}, - {"DirtMax": [0.8, 0.9], "DirtMin": [0.4, 0.45], "MudMax": [0.0, 1.0], "MudMin": [0.0, 0.9]}, - {"DirtMax": [1.0, 1.0], "DirtMin": [0.5, 0.5], "MudMax": [1.0, 1.0], "MudMin": [0.8, 0.8]}, - ], -} - - -def write_doc(directory): - path = os.path.join(directory, "graphics.xml") - with open(path, "w", encoding="utf-8", newline="\n") as f: - f.write(DOC) - return path - - -class RecordsTest(unittest.TestCase): - def test_records_and_aggregates(self): - with tempfile.TemporaryDirectory() as tmp: - self.assertEqual(vsi.census(write_doc(tmp)), WANT) - - -class CliTest(unittest.TestCase): - def run_tool(self, *argv): - out, err = io.StringIO(), io.StringIO() - with contextlib.redirect_stdout(out), contextlib.redirect_stderr(err): - status = vsi.main(list(argv)) - return status, out.getvalue(), err.getvalue() - - def test_other_document_with_valid_table_is_rejected(self): - with tempfile.TemporaryDirectory() as tmp: - path = os.path.join(tmp, "other.xml") - report = os.path.join(tmp, "report.json") - with open(path, "w", encoding="utf-8", newline="\n") as f: - f.write(DOC.replace("CGraphicsDefinitionsData", "UnrelatedRoot")) - status, out, err = self.run_tool(path, "--json", report) - self.assertEqual(status, 2) - self.assertEqual(out, "") - self.assertEqual(err, "ERROR: expected CGraphicsDefinitionsData document root\n") - self.assertFalse(os.path.exists(report)) - - def test_stdout_aggregates_and_no_key_names(self): - with tempfile.TemporaryDirectory() as tmp: - status, out, err = self.run_tool(write_doc(tmp)) - self.assertEqual(status, 0, err) - self.assertEqual(json.loads(out), WANT) - # Entry keys and Name values are the table's own text: the aggregate never carries them. - for token in ("spawn_alpha_test", "spawn_beta_test", "spawn_gamma_test"): - self.assertNotIn(token, out) - self.assertNotIn(token, err) - - def test_json_output_matches_and_is_well_formed(self): - with tempfile.TemporaryDirectory() as tmp: - report = os.path.join(tmp, "report.json") - status, _, err = self.run_tool(write_doc(tmp), "--json", report) - self.assertEqual(status, 0, err) - with open(report, encoding="utf-8") as f: - self.assertEqual(json.load(f), WANT) - - def test_json_over_the_input_is_refused(self): - with tempfile.TemporaryDirectory() as tmp: - path = write_doc(tmp) - status, _, err = self.run_tool(path, "--json", path) - self.assertEqual(status, 2) - self.assertIn("--json must not overwrite the input", err) - with open(path, encoding="utf-8") as f: - self.assertIn("spawn_alpha_test", f.read()) # the input document is untouched - - def test_bad_input_is_one_error_line(self): - with tempfile.TemporaryDirectory() as tmp: - path = os.path.join(tmp, "broken.xml") - with open(path, "w", encoding="utf-8") as f: - f.write("") - status, _, err = self.run_tool(path) - self.assertEqual(status, 2) - self.assertTrue(err.startswith("ERROR:")) - self.assertNotIn("Traceback", err) - - def test_a_non_finite_value_is_refused(self): - with tempfile.TemporaryDirectory() as tmp: - path = write_doc(tmp) - with open(path, encoding="utf-8") as f: - doc = f.read().replace('DirtMin value="-1"', 'DirtMin value="NaN"', 1) - with open(path, "w", encoding="utf-8", newline="\n") as f: - f.write(doc) - report = os.path.join(tmp, "report.json") - status, out, err = self.run_tool(path, "--json", report) - self.assertEqual(status, 2) - self.assertTrue(err.startswith("ERROR:"), err) - self.assertFalse(os.path.exists(report)) - with open(path, encoding="utf-8") as f: # the input document is untouched - self.assertIn('DirtMin value="NaN"', f.read()) - - def test_carve_directory_input(self): - with tempfile.TemporaryDirectory() as tmp: - blob = DOC.encode("utf-8") - first, second = blob[:256], blob[256:] - rows = [] - for i, chunk in enumerate((first, second)): - off = 0x1000 + i * len(first) - with open(os.path.join(tmp, f"{off:012x}.bin"), "wb") as f: - f.write(chunk) - rows.append({"off": off, "stored": len(chunk), "size": len(chunk), - "pre": "00" * 16, "head": chunk[:16].hex()}) - with open(os.path.join(tmp, "index.json"), "w", encoding="utf-8") as f: - json.dump({"files": rows}, f) - status, out, err = self.run_tool(tmp) - self.assertEqual(status, 0, err) - self.assertEqual(json.loads(out), WANT) - - def test_carve_without_the_document_is_an_error(self): - with tempfile.TemporaryDirectory() as tmp: - empty = os.path.join(tmp, "0x1000.bin") - with open(empty, "wb") as f: - f.write(b"other plain bytes no xml") - with open(os.path.join(tmp, "index.json"), "w", encoding="utf-8") as f: - json.dump({"files": [{"off": 0x1000, "stored": 24, "size": 24, - "pre": "00" * 16, "head": "other plain bytes ".encode().hex()[:32]}]}, f) - status, _, err = self.run_tool(tmp) - self.assertEqual(status, 2) - self.assertIn("ERROR:", err) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/test_vertex_input_locations.py b/tests/test_vertex_input_locations.py deleted file mode 100644 index 21f6ef8e3..000000000 --- a/tests/test_vertex_input_locations.py +++ /dev/null @@ -1,43 +0,0 @@ -"""Unit tests for rdna2spirv.vertex_input_locations (standard library only, no game data). - - python -I tests/test_vertex_input_locations.py - -SHADER-644: a packed vertex ISG1 signature declares xy and zw of one register as two elements. Each register must -become one Vulkan vertex input, or the SPIR-V declares %vin{reg} twice and fails spirv-val. -""" -import os -import sys -import unittest - -ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) -sys.path.insert(0, os.path.join(ROOT, "tools")) - -import rdna2spirv # noqa: E402 - -FLOAT, UINT = 3, 1 - - -class VertexInputLocationsTest(unittest.TestCase): - def test_distinct_registers_keep_order(self): - sig = [(2, 0xF, 0, FLOAT), (0, 0x7, 0, FLOAT), (1, 0x3, 0, UINT)] - self.assertEqual(rdna2spirv.vertex_input_locations(sig), [(2, FLOAT), (0, FLOAT), (1, UINT)]) - - def test_packed_register_is_declared_once(self): - sig = [(0, 0x3, 0, FLOAT), (0, 0xC, 0, FLOAT), (1, 0xF, 0, FLOAT)] - self.assertEqual(rdna2spirv.vertex_input_locations(sig), [(0, FLOAT), (1, FLOAT)]) - - def test_three_elements_in_one_register(self): - sig = [(4, 0x1, 0, UINT), (4, 0x2, 0, UINT), (4, 0xC, 0, UINT)] - self.assertEqual(rdna2spirv.vertex_input_locations(sig), [(4, UINT)]) - - def test_mixed_component_types_in_one_register_are_rejected(self): - sig = [(0, 0x3, 0, FLOAT), (0, 0xC, 0, UINT)] - with self.assertRaises(rdna2spirv.Unsupported): - rdna2spirv.vertex_input_locations(sig) - - def test_empty_signature(self): - self.assertEqual(rdna2spirv.vertex_input_locations([]), []) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/test_vertex_types.py b/tests/test_vertex_types.py deleted file mode 100644 index 7ad8f8c95..000000000 --- a/tests/test_vertex_types.py +++ /dev/null @@ -1,630 +0,0 @@ -"""Synthetic-data tests for tools/vertex_types.py. - - python -I tests/test_vertex_types.py - -Every byte here is built by the test. No game file, value or name is used. -""" -import contextlib -import io -import json -import math -import os -import pathlib -import random -import struct -import subprocess -import sys -import tempfile -import unittest -import zlib -from unittest import mock - -ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) -TOOL = os.path.join(ROOT, "tools", "vertex_types.py") -sys.path.insert(0, os.path.join(ROOT, "tools")) - -import vertex_types as vt # noqa: E402 - -GRID = 10 # GRID x GRID vertices, 2 * (GRID - 1)^2 triangles - - -def pack_position(x, y, z): - """Inverse of the 0x42 slot-0 packing: x bits 8-31, y low byte bits 0-7 and high 16 bits 32-47, z bits 48-63.""" - return (y & 0xFF) | (x << 8) | ((y >> 8) << 32) | (z << 48) - - -def grid_triangles(grid=GRID): - tris = [] - for j in range(grid - 1): - for i in range(grid - 1): - a, b, c, d = j * grid + i, j * grid + i + 1, (j + 1) * grid + i, (j + 1) * grid + i + 1 - tris += [(a, b, c), (b, d, c)] - return tris - - -def group_for(tris, n): - """A meshlet group: each meshlet references all n vertices and takes up to 128 of the triangles.""" - assert n <= 128 - chunks = [tris[i:i + 128] for i in range(0, len(tris), 128)] - recs, words, refs = bytearray(), bytearray(), bytearray() - vbase = tbase = 0 - for m, part in enumerate(chunks): - recs += struct.pack("<4I", (n - 1) | ((len(part) - 1) << 7), vbase | (tbase << 16), 0x7FF7FF, 0x7FF) - for a, b, c in part: - words += struct.pack(" None: - decode = vt.NORMAL_CANDIDATES["snorm10_xyz"] - values = struct.pack("<2I", 512 | (511 << 10), 513 | (511 << 10)) - diagonal = 1.0 / math.sqrt(2.0) - expected = (-diagonal, diagonal, 0.0) - self.assertEqual(decode(values, 0), expected) - self.assertEqual(decode(values, 1), expected) - - def test_normal_probe_uses_clamped_snorm10_direction_for_face_agreement(self) -> None: - mesh = bytearray(block(grid=2)) - slots, _, _ = vt.parse_slots(mesh) - struct.pack_into("<4Q", mesh, slots[0][1], pack_position(0, 0, 0), pack_position(31, 218, 0), - pack_position(0, 0, 100), pack_position(31, 218, 100)) - struct.pack_into("<4I", mesh, slots[2][1], *([512 | (511 << 10)] * 4)) - _, report = measure(bytes(mesh)) - # Without the clamp, the packed normal's absolute dot product - # crosses the 0.8 face-agreement threshold. - self.assertEqual(report["tags"]["slot2:21"]["facenormal_snorm10_xyz_median"], 0.0) - - def test_constant_colour_and_known_normal(self): - _, out = measure(block()) - col = out["tags"]["slot1:26"] - for k in range(4): - self.assertEqual(col[f"byte{k}_constant_blocks"], 1) - self.assertEqual(col["byte3_255"], GRID * GRID) - nrm = out["tags"]["slot2:21"] - self.assertEqual(nrm["facenormal_snorm8_xyz_median"], 1.0) - self.assertEqual(nrm["unit_snorm8"], GRID * GRID) - - def test_0x21_octahedral_normal_in_either_width(self): - # +z in the 10-bit form (bit 31 set, x = y = 512) and in the 8-bit form (bit 31 clear, bytes 0-1 = 128); - # each scores 1.0 only under its own branch of the decode - for word in (0x80000000 | 512 | 512 << 10, 128 | 128 << 8): - _, out = measure(block(normal=struct.pack("= 0 else -1), (1 - abs(x)) * (1 if y >= 0 else -1) - if bits == 10: - q = [round((c + 1) * 1023 / 2) for c in (x, y)] - return 0x80000000 | q[0] | q[1] << 10 | 0x2AA << 20 - q = [round((c + 1) * 127.5) for c in (x, y)] - return q[0] | q[1] << 8 | 0x55 << 16 - - def test_round_trip_both_widths_and_hemispheres(self): - rng = random.Random(7) - for _ in range(500): - v = [rng.gauss(0, 1) for _ in range(3)] - l = sum(c * c for c in v) ** 0.5 - n = [c / l for c in v] - for bits, tol in ((10, 0.005), (8, 0.03)): - d = vt.normal_0x21(self.encode(n, bits)) - self.assertAlmostEqual(sum(a * a for a in d), 1.0, places=9) - self.assertGreater(sum(a * b for a, b in zip(d, n)), 1 - tol) - - def test_bit31_selects_the_width(self): - # the same low 20 bits: with bit 31 they are 10-bit x = 1023, y = 512, i.e. +x; without it bytes 0-1 are - # 0xFF, 0x03, an 8-bit pair near (+1, -1) that folds to a vector close to -z - w = 1023 | 512 << 10 - hi = vt.normal_0x21(0x80000000 | w) - lo = vt.normal_0x21(w) - self.assertGreater(hi[0], 0.999) - self.assertLess(lo[0], 0.1) - self.assertLess(lo[2], -0.9) - - -class Tangent0x21Tests(unittest.TestCase): - def test_10bit_tangent_is_unit_and_perpendicular_to_the_normal(self): - rng = random.Random(3) - for _ in range(2000): - w = 0x80000000 | rng.getrandbits(31) - n = vt.normal_0x21(w) - t, sign = vt.tangent_0x21(w) - self.assertAlmostEqual(sum(a * a for a in t), 1.0, places=9) - self.assertLess(abs(sum(a * b for a, b in zip(n, t))), 1e-9) - self.assertEqual(sign, 1 if (w >> 30) & 1 else -1) - - def test_10bit_angle_turns_the_tangent_about_the_normal(self): - # normal +z: b1 = -x, b2 = -y, tangent = (-cos, sin, 0) for angle = v * 2pi / 1023 - pi - base = 0x80000000 | 512 | 512 << 10 - for v in (0, 256, 511, 767, 1023): - ang = v * 2 * math.pi / 1023 - math.pi - t, _ = vt.tangent_0x21(base | v << 20) - self.assertAlmostEqual(t[0], -math.cos(ang), delta=2e-3) - self.assertAlmostEqual(t[1], math.sin(ang), delta=2e-3) - - def test_negative_z_normal_uses_the_other_basis_sign(self): - # x = y = 0 folds to -z with the octahedral corner (1023, 1023); the basis stays perpendicular there - w = 0x80000000 | 1023 | 1023 << 10 | 300 << 20 - n = vt.normal_0x21(w) - t, _ = vt.tangent_0x21(w) - self.assertLess(n[2], -0.99) - self.assertLess(abs(sum(a * b for a, b in zip(n, t))), 1e-9) - - def test_8bit_tangent_is_octahedral_in_bits_16_to_29(self): - t, sign = vt.tangent_0x21(127 << 16 | 64 << 23) - self.assertGreater(t[0], 0.999) - self.assertEqual(sign, -1) - t, sign = vt.tangent_0x21(64 << 16 | 127 << 23 | 1 << 30) - self.assertGreater(t[1], 0.999) - self.assertEqual(sign, 1) - - -class BlockRunTests(unittest.TestCase): - """Blocks stored back to back, with their groups after the whole run in the same order.""" - - def test_two_blocks_then_two_groups(self): - data = block(with_group=False) + block(grid=8, with_group=False) + padded_group() + padded_group(8) - T, errors = measure_stream(data) - self.assertEqual((T.get("blocks"), T["vertices"], T["run_blocks"], errors), (2, 100 + 64, 2, {})) - - def test_groups_out_of_order_fail_the_density_check(self): - data = block(with_group=False) + block(grid=8, with_group=False) + padded_group(8) + padded_group() - T, errors = measure_stream(data) - self.assertEqual((T.get("blocks"), errors), (None, {"group does not cover the block densely": 2})) - - def test_blocks_without_a_group_in_the_stream_are_counted(self): - data = block(with_group=False) + block(with_group=False) + block(with_group=False) + padded_group() - T, errors = measure_stream(data) - self.assertEqual((T.get("blocks"), errors), (1, {"no group in the stream for a later block of the run": 2})) - - def test_single_block_unchanged(self): - T, errors = measure_stream(block()) - self.assertEqual((T.get("blocks"), T["run_blocks"], errors), (1, 1, {})) - with self.assertRaises(vt.BlockError): - measure_stream(block(with_group=False)) - - -def block_with_streams(extra, grid=GRID): - """block() with more (slot, tag, per-vertex bytes) streams appended after its own, before the group.""" - n = grid * grid - buf = bytearray(block(grid=grid, with_group=False)) - for slot, tag, data in extra: - struct.pack_into(" 0 exactly when -v" side; w = 3 is the other - for w, agree in ((0, True), (3, False)): - _, out = measure(block27(word27(1, 0, 0, w))) - t = out["tag27"] - self.assertEqual(t["11:vertices"], self.N) - self.assertEqual(t["11:unit"], self.N) - self.assertEqual(t[f"11:w{w}"], self.N) - self.assertEqual(t["11:perp_face"], t["11:perp_face_n"]) - self.assertEqual(t["11:uv3_along_u"], t["11:uv3_n"]) - self.assertEqual(t["11:uv3_w_plus_minus_v"], t["11:uv3_along_u"] if agree else 0) - - def test_vector_along_the_normal_fails_the_checks(self): - _, out = measure(block27(word27(0, 0, 1, 3))) - t = out["tag27"] - self.assertEqual(t["11:unit"], self.N) - self.assertEqual(t["11:perp_face"], 0) - self.assertNotIn("11:uv3_along_u", t) - - def test_non_unit_vectors_are_counted(self): - _, out = measure(block27(word27(0.5, 0, 0, 3))) - self.assertEqual(out["tag27"]["11:unit"], 0) - - def test_no_0x27_slot_no_counts(self): - _, out = measure(block()) - self.assertEqual(out["tag27"], {}) - - -class Rpf9ValidationTests(unittest.TestCase): - """RPF9 archive header validation in iter_blocks (contract shared with rpf9_names.scan_archive).""" - - @staticmethod - def _run(args): - return subprocess.run([sys.executable, "-I", TOOL, *args], capture_output=True, text=True, errors="replace") - - def test_invalid_headers_are_errors(self): - cases = [ - ("empty", b""), - ("short header", b"RPF9"), - ("wrong magic", b"XRP9" + struct.pack("\\]+") -# Quoted attribute values may hold '>' (the fallback writes a whole ', re.S) -_MODULE = re.compile(r'', re.S) -_IMPORT_FROM = re.compile(r"""^\s*import\b[^;]*?\bfrom\s*["']([^"']+)["']""", re.M) -# An exact release: three@0.160.0 on npm CDNs, three.js/r128 on cdnjs. A range, a tag or no version fails. -_EXACT_VERSION = re.compile(r"@\d+\.\d+\.\d+/|/r\d+/") - - -def _sri_ok(value: str) -> bool: - algo, _, digest = value.partition("-") - sizes = {"sha256": 32, "sha384": 48, "sha512": 64} - if algo not in ("sha384", "sha512"): - return False - try: - return len(base64.b64decode(digest, validate=True)) == sizes[algo] - except ValueError: - return False - - -def _attrs(text: str) -> dict[str, str]: - return {k.lower(): v[1:-1] for k, v in _ATTR.findall(text)} - - -def problems(html: str) -> list[str]: - """What is wrong with the remote scripts of one viewer page; empty when every one is pinned and hashed.""" - out: list[str] = [] - covered: set[str] = set() # remote URLs whose bytes are checked by an integrity hash - prefixes: set[str] = set() # import map prefixes ("three/addons/" -> a CDN folder) - preload: dict[str, str] = {} - - for kind, raw in _TAG.findall(html): - attrs = _attrs(raw) - urls = _URL.findall(raw) - if not urls: - continue - integrity = attrs.get("integrity", "") - if not _sri_ok(integrity): - out.append(f"<{kind}> loading {urls[0]} has no sha384/sha512 integrity hash") - continue - if attrs.get("crossorigin") != "anonymous": - out.append(f"<{kind}> loading {urls[0]} needs crossorigin=\"anonymous\" for its integrity check") - if kind.lower() == "link": - if attrs.get("rel") != "modulepreload": - out.append(f" loading {urls[0]} is not a modulepreload") - preload[attrs.get("href", "")] = integrity - # A ' - self.assertIn("no sha384/sha512 integrity hash", problems(html)[0]) - - def test_classic_script_with_integrity_but_floating_version(self): - html = f'' - self.assertEqual(problems(html), ["https://cdn.example/lib@1/x.js is not pinned to an exact version"]) - - def test_integrity_needs_crossorigin(self): - html = f'' - self.assertIn("crossorigin", problems(html)[0]) - - def test_sha256_and_bad_base64_are_rejected(self): - for value in ("sha256-" + base64.b64encode(bytes(32)).decode(), "sha384-abc", "sha384-" + "A" * 63 + "!"): - html = f'' - self.assertTrue(problems(html), value) - - def test_fallback_must_reuse_the_hash(self): - bad = (f'") - self.assertIn("does not reuse", problems(bad)[0]) - good = (f'") - self.assertEqual(problems(good), []) - - def test_import_map_without_integrity(self): - html = ('\n' - '') - found = problems(html) - self.assertIn("import map entry lib -> https://cdn.example/lib@1.2.3/lib.js has no integrity hash", found) - - def test_import_through_prefix_needs_a_hash(self): - html = ('\n' - f'\n' - '') - found = problems(html) - self.assertIn("module import lib/a.js -> https://cdn.example/lib@1.2.3/a.js has no integrity hash", found) - - def test_preload_and_map_must_agree(self): - other = "sha384-" + base64.b64encode(bytes([1]) * 48).decode() - html = ('\n' - f'') - self.assertIn("disagree", problems(html)[0]) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/test_viewer_serve.py b/tests/test_viewer_serve.py deleted file mode 100644 index 9cb88a0fc..000000000 --- a/tests/test_viewer_serve.py +++ /dev/null @@ -1,531 +0,0 @@ -"""Tests for viewer/serve.py: the loopback Host check, /world/ path resolution and the HTTP layer. - - python -I tests/test_viewer_serve.py - -Everything runs on a temporary world folder and a loopback server: no game data, no browser, no network beyond -127.0.0.1, standard library only. -""" -from __future__ import annotations - -import argparse -import functools -import http.server -import os -from pathlib import Path -import socket -import subprocess -import sys -import tempfile -import threading -import unittest -import urllib.parse -from unittest import mock - -ROOT = Path(__file__).resolve().parents[1] -VIEWER = ROOT / "viewer" -if str(VIEWER) not in sys.path: - sys.path.insert(0, str(VIEWER)) - -import serve # noqa: E402 - - -class HostAllowedTest(unittest.TestCase): - """Only a Host header naming this machine may be answered (DNS rebinding).""" - - def test_loopback_hosts_are_allowed(self): - for host in ("127.0.0.1", "127.0.0.1:8765", "localhost", "localhost:1", "LOCALHOST:8765", - "localhost.", "[::1]", "[::1]:8765"): - with self.subTest(host=host): - self.assertTrue(serve.host_allowed(host)) - - def test_other_hosts_are_refused(self): - for host in ("", "evil.example", "evil.example:8765", "127.0.0.1.evil.example", - "0.0.0.0:8765", "::1", "localhost.evil.example:8765"): - with self.subTest(host=host): - self.assertFalse(serve.host_allowed(host)) - - def test_a_request_without_a_host_header_is_allowed(self): - # Browsers always send Host; a missing one is a local tool, not a web page. - self.assertTrue(serve.host_allowed(None)) - - def test_well_formed_edge_cases_are_allowed(self): - for host in (" localhost ", "localhost:80 ", "localhost.:8765", "127.0.0.1.", "127.0.0.1:65535", "localhost:0", - "[::1]:0", "[::1]:00080"): - with self.subTest(host=host): - self.assertTrue(serve.host_allowed(host)) - - def test_malformed_ports_are_refused(self): - # Each of these used to be allowed: the port after the colon was never looked at. - for host in ("localhost:", "localhost:abc", "localhost:-1", "localhost:+80", "localhost: 80", - "localhost:8 0", "localhost:65536", "localhost:99999", "localhost:123456", - "localhost:80", "127.0.0.1:0x50", "localhost:80.", "localhost:" + "9" * 5000): - with self.subTest(host=host[:40]): - self.assertFalse(serve.host_allowed(host)) - - def test_malformed_ipv6_literals_are_refused(self): - # The first seven used to be allowed: everything after "]" was ignored. - for host in ("[::1]junk", "[::1]x:8765", "[::1].", "[::1]]", "[::1]:", "[::1]:abc", "[::1]:8765:1", - "[::1", "::1]", "[[::1]", "[]", "[]:8765", "[::1%25eth0]", "[0:0:0:0:0:0:0:1]x"): - with self.subTest(host=host): - self.assertFalse(serve.host_allowed(host)) - - def test_other_malformed_hosts_are_refused(self): - for host in (":8765", ":", "localhost..", "localhost..:8765", "127.0.0.1:80:80", "localhost:8765:1", - "localhost\t:8765", "local host", "localhost\x00"): - with self.subTest(host=host): - self.assertFalse(serve.host_allowed(host)) - - -class SafeWorldPathTest(unittest.TestCase): - """safe_world_path resolves /world/... inside the world folder or refuses it.""" - - def setUp(self): - self._tmp = tempfile.TemporaryDirectory() - self.root = Path(self._tmp.name) - self.world = self.root / "world" - (self.world / "sub").mkdir(parents=True) - (self.world / "ok.bin").write_bytes(b"world-bytes") - (self.world / "sub" / "inner.bin").write_bytes(b"inner") - # A file the world must never reach, next to the world folder. - (self.root / "secret.txt").write_text("secret", encoding="utf-8") - - def tearDown(self): - self._tmp.cleanup() - - def resolve(self, request_path): - return serve.safe_world_path(str(self.world), request_path) - - def test_a_world_file_resolves_to_its_real_path(self): - resolved = self.resolve("/world/ok.bin") - self.assertIsNotNone(resolved) - self.assertEqual(os.path.normcase(os.path.realpath(resolved)), - os.path.normcase(os.path.realpath(self.world / "ok.bin"))) - - def test_a_nested_world_file_resolves(self): - self.assertIsNotNone(self.resolve("/world/sub/inner.bin")) - - def test_query_and_fragment_are_not_part_of_the_path(self): - self.assertIsNotNone(self.resolve("/world/ok.bin?cache=1")) - self.assertIsNotNone(self.resolve("/world/ok.bin#top")) - - def test_requests_outside_world_are_refused(self): - for path in ("/ok.bin", "/", "/world", "/world/../secret.txt", "/world/sub/../../secret.txt", - "/world/%2e%2e/secret.txt", "/world/..%2fsecret.txt", "/world/..\\secret.txt", - "/world//ok.bin", "/world/./ok.bin", "/world/", "/world/sub/", "/world/sub"): - with self.subTest(path=path): - self.assertIsNone(self.resolve(path)) - - def test_nul_bytes_and_drive_letters_are_refused(self): - for path in ("/world/ok%00.bin", "/world/C:secret.txt", "/world/sub/inner.bin:stream"): - with self.subTest(path=path): - self.assertIsNone(self.resolve(path)) - - def test_windows_reserved_device_names_are_refused(self): - for name in ("CON", "con.txt", "NUL", "COM1", "LPT9.log", "aux."): - with self.subTest(name=name): - self.assertIsNone(self.resolve("/world/" + name)) - - def test_windows_device_aliases_are_refused_without_isreserved(self): - # Python 3.12 has no os.path.isreserved. Check the fallback on newer Pythons too, - # before realpath or any other filesystem call can touch a console or serial device. - names = ("COM\u00b9", "com\u00b2.glb", "COM\u00b3.json", "LPT\u00b9", "lpt\u00b2.glb", - "LPT\u00b3.json", "CONIN$", "conout$.bin", - "NUL .glb", "COM1 .glb", "LPT9 .json") - with mock.patch.object(serve.os.path, "isreserved", None, create=True): - with mock.patch.object(serve.os.path, "realpath", - side_effect=AssertionError("device path reached realpath")) as realpath: - for name in names: - for prefix in ("/world/", "/world/sub/"): - with self.subTest(name=name, prefix=prefix): - self.assertIsNone(self.resolve(prefix + urllib.parse.quote(name, safe=""))) - realpath.assert_not_called() - - def test_device_like_regular_filenames_still_resolve(self): - for name in ("COM10.glb", "LPT10.json", "COM\u2074.glb", "COM1_mesh.glb", "console.glb", - "my.CON", "input.CONIN$"): - with self.subTest(name=name): - self.assertIsNotNone(self.resolve("/world/" + urllib.parse.quote(name, safe=""))) - - def test_a_missing_world_or_bad_argument_is_refused(self): - self.assertIsNone(serve.safe_world_path("", "/world/ok.bin")) - self.assertIsNone(serve.safe_world_path(str(self.world), None)) - self.assertIsNone(serve.safe_world_path(str(self.world), b"/world/ok.bin")) - - def test_a_symlink_out_of_the_world_is_refused(self): - link = self.world / "escape.bin" - try: - os.symlink(self.root / "secret.txt", link) - except (OSError, NotImplementedError) as e: # Windows without the privilege - self.skipTest(f"cannot create a symlink here: {e}") - self.assertIsNone(self.resolve("/world/escape.bin")) - - -def raw_request(port, target, host="127.0.0.1", method="GET", extra_headers=()): - """Send a request without letting a client library normalise the target path or merge headers. - `extra_headers` are raw "Name: value" lines sent after Host, e.g. a second Host field.""" - lines = [f"{method} {target} HTTP/1.1"] - if host is not None: - lines.append(f"Host: {host}") - lines += list(extra_headers) - lines += ["Connection: close", "", ""] - with socket.create_connection(("127.0.0.1", port), timeout=10) as sock: - sock.sendall("\r\n".join(lines).encode("latin-1")) - chunks = [] - while True: - data = sock.recv(65536) - if not data: - break - chunks.append(data) - raw = b"".join(chunks) - head, _, body = raw.partition(b"\r\n\r\n") - status = int(head.split(b"\r\n", 1)[0].split()[1]) - return status, head.decode("latin-1"), body - - -class HandlerTest(unittest.TestCase): - """/world/ files are served with the guards in front of them; a foreign Host gets 403.""" - - @classmethod - def setUpClass(cls): - cls._tmp = tempfile.TemporaryDirectory() - root = Path(cls._tmp.name) - world = root / "world" - (world / "sub").mkdir(parents=True) - (world / "ok.bin").write_bytes(b"world-bytes") - (world / "model.glb").write_bytes(b"glTF") - (root / "site").mkdir() - (root / "site" / "index.html").write_text("viewer", encoding="utf-8") - (root / "secret.txt").write_text("secret", encoding="utf-8") - - class QuietHandler(serve.Handler): - def log_message(self, *args): - pass - - QuietHandler.world = str(world) # a class body cannot see the enclosing function's locals - - cls.server = http.server.ThreadingHTTPServer( - ("127.0.0.1", 0), functools.partial(QuietHandler, directory=str(root / "site"))) - cls.port = cls.server.server_address[1] - cls.thread = threading.Thread(target=cls.server.serve_forever, daemon=True) - cls.thread.start() - - @classmethod - def tearDownClass(cls): - cls.server.shutdown() - cls.server.server_close() - cls.thread.join(5) - cls._tmp.cleanup() - - def test_a_world_file_is_served_without_caching(self): - status, head, body = raw_request(self.port, "/world/ok.bin", host=f"127.0.0.1:{self.port}") - self.assertEqual(status, 200) - self.assertEqual(body, b"world-bytes") - self.assertIn("cache-control: no-store", head.lower()) - - def test_the_glb_mime_type_is_registered(self): - status, head, _ = raw_request(self.port, "/world/model.glb", host=f"localhost:{self.port}") - self.assertEqual(status, 200) - self.assertIn("content-type: model/gltf-binary", head.lower()) - - def test_head_and_query_strings_work(self): - status, _, body = raw_request(self.port, "/world/ok.bin?cache=1", host="127.0.0.1", method="HEAD") - self.assertEqual(status, 200) - self.assertEqual(body, b"") - - def test_a_missing_host_header_is_served(self): - status, _, body = raw_request(self.port, "/world/ok.bin", host=None) - self.assertEqual(status, 200) - self.assertEqual(body, b"world-bytes") - - def test_a_foreign_host_gets_403(self): - for target in ("/world/ok.bin", "/index.html"): - with self.subTest(target=target): - status, head, _ = raw_request(self.port, target, host="evil.example:8765") - self.assertEqual(status, 403) - self.assertIn("cache-control: no-store", head.lower()) - - def test_duplicate_host_headers_get_400(self): - # headers.get("Host") returned only the first field, so a loopback Host followed by a foreign one was served. - loopback = f"127.0.0.1:{self.port}" - cases = { - "loopback then foreign": (loopback, ["Host: evil.example"]), - "foreign then loopback": ("evil.example", [f"Host: {loopback}"]), - "the same loopback twice": (loopback, [f"Host: {loopback}"]), - "a lowercase second field": (loopback, ["host: evil.example"]), - "an empty second field": (loopback, ["Host:"]), - "three fields": (loopback, [f"Host: localhost:{self.port}", "Host: [::1]"]), - } - for method in ("GET", "HEAD"): - for target in ("/world/ok.bin", "/index.html"): - for label, (host, extra) in cases.items(): - with self.subTest(method=method, target=target, case=label): - status, head, body = raw_request(self.port, target, host=host, method=method, - extra_headers=extra) - self.assertEqual(status, 400) - self.assertIn("cache-control: no-store", head.lower()) - self.assertNotIn(b"world-bytes", body) - self.assertNotIn(b"viewer", body) - - def test_a_malformed_host_gets_403(self): - for host in (f"127.0.0.1:{self.port}junk", "localhost:abc", f"[::1]evil.example:{self.port}", - "localhost:" + "9" * 5000): - with self.subTest(host=host[:40]): - status, _, body = raw_request(self.port, "/world/ok.bin", host=host) - self.assertEqual(status, 403) - self.assertNotIn(b"world-bytes", body) - - def test_traversal_attempts_get_403(self): - for target in ("/world/../secret.txt", "/world/%2e%2e/secret.txt", - "/world/sub/../../secret.txt", "/world/..%5csecret.txt"): - with self.subTest(target=target): - status, _, body = raw_request(self.port, target, host=f"127.0.0.1:{self.port}") - self.assertEqual(status, 403) - self.assertNotIn(b"secret", body) - - def test_windows_device_aliases_get_403_without_opening_them(self): - targets = ("/world/COM%C2%B9.glb", "/world/sub/lpt%C2%B2.json", "/world/CONIN%24", - "/world/CONOUT%24.bin", "/world/NUL%20.glb") - with mock.patch.object(serve.os.path, "isreserved", None, create=True): - # If the path guard regresses, fail without ever opening an actual Windows device. - with mock.patch("builtins.open", side_effect=AssertionError("device path reached open")) as opened: - for method in ("GET", "HEAD"): - for target in targets: - with self.subTest(method=method, target=target): - status, _, _ = raw_request(self.port, target, method=method) - self.assertEqual(status, 403) - opened.assert_not_called() - - def test_the_viewer_page_itself_is_served(self): - # http.server itself folds a leading "//" into "/" before the handler sees the path. - for target in ("/index.html", "/", "/?x=1", "/index.html?v=2", "/index.html#pos", "//index.html"): - for method in ("GET", "HEAD"): - with self.subTest(target=target, method=method): - status, head, body = raw_request(self.port, target, host=f"127.0.0.1:{self.port}", - method=method) - self.assertEqual(status, 200) - self.assertIn("content-type: text/html", head.lower()) - if method == "GET": - self.assertIn(b"viewer", body) - - def test_nothing_else_outside_world_is_served(self): - # These reached SimpleHTTPRequestHandler unguarded: on Windows /NUL opened the device (200, empty) and - # the stream, trailing-dot and trailing-space forms returned the page or the server's own source. - site = Path(self._tmp.name) / "site" - (site / "other.txt").write_text("other-bytes", encoding="utf-8") - (site / "sub").mkdir(exist_ok=True) - (site / "sub" / "index.html").write_text("nested", encoding="utf-8") - targets = ("/NUL", "/nul.html", "/CON", "/COM1", "/CONIN%24", "/index.html::$DATA", "/index.html::%24DATA", - "/index.html.", "/index.html%20", "/index.html/", "/INDEX.HTML", "/index%2Ehtml", - "/./index.html", "/sub/../index.html", "/other.txt", "/other.txt::$DATA", - "/sub/", "/sub/index.html", "/../secret.txt", "/%2e%2e/secret.txt", "/..%5csecret.txt", - "/world", "/worldx/ok.bin", "/favicon.ico") - with mock.patch("builtins.open", side_effect=AssertionError("a refused path reached open")) as opened: - for method in ("GET", "HEAD"): - for target in targets: - with self.subTest(method=method, target=target): - status, head, body = raw_request(self.port, target, method=method) - self.assertEqual(status, 404) - self.assertIn("cache-control: no-store", head.lower()) - for leaked in (b"viewer", b"<title>nested", b"other-bytes", b"secret", b"world-bytes"): - self.assertNotIn(leaked, body) - opened.assert_not_called() - - def test_translate_path_refuses_what_send_head_refuses(self): - handler = serve.Handler.__new__(serve.Handler) # no socket: only the path mapping is under test - handler.directory = str(Path(self._tmp.name) / "site") - handler.world = None - for target in ("/NUL", "/index.html::$DATA", "/index.html.", "/other.txt", "/world/ok.bin"): - with self.subTest(target=target): - self.assertEqual(handler.translate_path(target), "") - self.assertTrue(handler.translate_path("/index.html").endswith("index.html")) - - -class NoWorldHandlerTest(unittest.TestCase): - """Without --world the page is still served and /world/ is simply absent (the viewer shows test terrain).""" - - def test_world_paths_are_404_and_the_page_is_served(self): - with tempfile.TemporaryDirectory() as tmp: - site = Path(tmp) / "site" - (site / "world").mkdir(parents=True) - (site / "index.html").write_text("<title>viewer", encoding="utf-8") - (site / "world" / "world.json").write_text("{}", encoding="utf-8") - - class QuietHandler(serve.Handler): - world = None - - def log_message(self, *args): - pass - - server = http.server.ThreadingHTTPServer( - ("127.0.0.1", 0), functools.partial(QuietHandler, directory=str(site))) - thread = threading.Thread(target=server.serve_forever, daemon=True) - thread.start() - try: - port = server.server_address[1] - status, _, body = raw_request(port, "/", host=f"127.0.0.1:{port}") - self.assertEqual(status, 200) - self.assertIn(b"viewer", body) - # A world folder that happens to sit in the viewer folder is not served: /world/ exists only - # with --world, behind safe_world_path. - for target in ("/world/world.json", "/world/NUL", "/world/world.json::$DATA"): - with self.subTest(target=target): - status, _, body = raw_request(port, target, host=f"127.0.0.1:{port}") - self.assertEqual(status, 404) - self.assertNotIn(b"{}", body) - finally: - server.shutdown() - server.server_close() - thread.join(5) - - -class WorldArgumentTest(unittest.TestCase): - def test_explicit_world_must_be_a_directory(self): - with tempfile.TemporaryDirectory() as tmp: - missing = Path(tmp) / "missing" - file = Path(tmp) / "world.json" - file.write_text("{}", encoding="utf-8") - for path in (missing, file): - with self.subTest(path=path): - result = subprocess.run( - [sys.executable, "-I", str(VIEWER / "serve.py"), "--port", "0", - "--world", str(path)], - capture_output=True, text=True, errors="replace", timeout=5) - self.assertEqual(result.returncode, 2) - self.assertIn("--world", result.stderr) - self.assertIn(str(path), result.stderr) - self.assertNotIn("Traceback", result.stderr) - - -class PortArgumentTest(unittest.TestCase): - """--port is 0-65535; outside that it used to reach socketserver and raise OverflowError.""" - - def test_valid_ports(self): - self.assertEqual(serve.port_number("0"), 0) - self.assertEqual(serve.port_number("8765"), 8765) - self.assertEqual(serve.port_number("65535"), 65535) - - def test_invalid_ports_are_refused_by_argparse(self): - for text in ("-1", "65536", "70000", "abc", "", - "8_080", " 80", "+80", "٠", "٣٣"): - with self.subTest(text=text): - with self.assertRaises(argparse.ArgumentTypeError): - serve.port_number(text) - - def test_the_cli_reports_a_bad_port_without_a_traceback(self): - result = subprocess.run( - [sys.executable, "-I", str(VIEWER / "serve.py"), "--port", "70000"], - capture_output=True, text=True, errors="replace") - self.assertEqual(result.returncode, 2) - self.assertIn("must be 0-65535", result.stderr) - self.assertNotIn("Traceback", result.stderr) - - def test_the_cli_reports_a_port_in_use_without_a_traceback(self): - with socket.socket() as taken: - taken.bind(("127.0.0.1", 0)) - taken.listen(1) - port = taken.getsockname()[1] - result = subprocess.run( - [sys.executable, "-I", str(VIEWER / "serve.py"), "--port", str(port)], - capture_output=True, text=True, errors="replace", timeout=60) - self.assertEqual(result.returncode, 2) - self.assertIn(f"can't listen on port {port}", result.stderr) - self.assertIn("--port 0", result.stderr) - self.assertNotIn("Traceback", result.stderr) - - def test_a_second_viewer_on_the_same_port_is_refused(self): - """Two real viewers. With SO_REUSEADDR set, Windows let the second one bind the port the first was serving: - it printed its URL and never got a request. The test above holds the port with a plain socket, which - Windows does refuse to share, so it did not see this.""" - first = subprocess.Popen([sys.executable, "-I", str(VIEWER / "serve.py"), "--port", "0"], - stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, text=True) - second = None - try: - line = first.stdout.readline() # it is serving now - self.assertIn("viewer: http://127.0.0.1:", line) - port = urllib.parse.urlsplit(line.split()[1]).port - second = subprocess.Popen([sys.executable, "-I", str(VIEWER / "serve.py"), "--port", str(port)], - stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True) - try: - out, err = second.communicate(timeout=20) - except subprocess.TimeoutExpired: - self.fail(f"a second viewer is serving port {port} next to the first one") - finally: - for proc in (first, second): - if proc is not None: - if proc.poll() is None: - proc.kill() - proc.communicate() - self.assertEqual(second.returncode, 2, err) - self.assertEqual(out, "") - self.assertIn(f"can't listen on port {port}", err) - self.assertNotIn("Traceback", err) - - def test_a_restart_binds_the_port_a_closed_viewer_just_served(self): - handler = functools.partial(serve.Handler, directory=str(VIEWER)) - port = 0 - with mock.patch.object(serve.Handler, "log_message", lambda *args: None): - for _ in range(3): - server = serve.ViewerServer(("127.0.0.1", port), handler) - port = server.server_address[1] - thread = threading.Thread(target=server.serve_forever, daemon=True) - thread.start() - try: - with socket.create_connection(("127.0.0.1", port), timeout=10) as client: - client.sendall(f"GET / HTTP/1.0\r\nHost: 127.0.0.1:{port}\r\n\r\n".encode("ascii")) - self.assertTrue(client.recv(64).startswith(b"HTTP/1.0 200")) - finally: - server.shutdown() - server.server_close() - thread.join(10) - self.assertFalse(thread.is_alive(), "the server thread is still running after shutdown()") - - @unittest.skipIf(os.name == "nt", "sends SIGINT, which a Windows child started this way does not get") - def test_ctrl_c_stops_the_viewer_without_a_traceback(self): - import signal - # A test runner started in the background has SIGINT ignored, and a child inherits that: Python then - # leaves it ignored and Ctrl+C would never arrive. Give the child the default disposition back. - proc = subprocess.Popen([sys.executable, "-I", str(VIEWER / "serve.py"), "--port", "0"], - stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, errors="replace", - preexec_fn=lambda: signal.signal(signal.SIGINT, signal.SIG_DFL)) - try: - self.assertIn("viewer: http://127.0.0.1:", proc.stdout.readline()) # it is serving now - proc.send_signal(signal.SIGINT) - out, err = proc.communicate(timeout=60) - finally: - if proc.poll() is None: - proc.kill() - proc.communicate() - self.assertEqual(proc.returncode, 0) - self.assertIn("viewer: stopped", out) - self.assertNotIn("Traceback", err) - - def test_ctrl_c_right_after_the_serving_line_still_stops_the_viewer(self): - """The test above sends SIGINT as soon as it reads the serving line. When the signal was handled before main() - was inside its try, the KeyboardInterrupt escaped (exit -2, a traceback): 24 of 300 runs with 12 at once - under load. Here the interrupt comes from printing that line, every time.""" - import contextlib - import io - from unittest import mock - - def print_then_ctrl_c(*args, **kwargs): - print(*args, **kwargs) - if args and str(args[0]).startswith("viewer: http://127.0.0.1:"): - raise KeyboardInterrupt - - out = io.StringIO() - world = serve.Handler.world - try: - with mock.patch.object(sys, "argv", ["serve.py", "--port", "0"]), \ - mock.patch.object(serve, "print", print_then_ctrl_c, create=True), \ - contextlib.redirect_stdout(out): - serve.main() - except KeyboardInterrupt: - self.fail("a Ctrl+C right after the serving line escaped main()") - finally: - serve.Handler.world = world - self.assertIn("viewer: http://127.0.0.1:", out.getvalue()) - self.assertIn("viewer: stopped", out.getvalue()) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/test_viewer_streaming.cjs b/tests/test_viewer_streaming.cjs deleted file mode 100644 index 8248181d8..000000000 --- a/tests/test_viewer_streaming.cjs +++ /dev/null @@ -1,952 +0,0 @@ -const assert = require('node:assert/strict'); -const { readFileSync } = require('node:fs'); -const { join } = require('node:path'); -const vm = require('node:vm'); -const { test } = require('node:test'); - -// Exercise the viewer's actual loading and streaming code without WebGL, a network or game data. -const html = readFileSync(join(__dirname, '..', 'viewer', 'index.html'), 'utf8'); -const viewerModule = html.match(/"} - html = trace.render_report(report) - payload = re.search(r'', html).group(1) - self.assertNotIn("<", payload) - self.assertEqual(json.loads(payload), report) - - def test_cli_writes_a_report_and_preserves_an_existing_file(self): - with tempfile.TemporaryDirectory() as tmp: - path = Path(tmp) / "wave.html" - args = ["--max-ops", "1", "--out", str(path)] - with redirect_stdout(io.StringIO()): - self.assertEqual(trace.main(args), 0) - original = path.read_bytes() - self.assertIn(b'id="wave-data"', original) - self.assertNotIn(b"WAVE_TRACE_DATA", original) - with redirect_stderr(io.StringIO()): - self.assertEqual(trace.main(args), 2) - self.assertEqual(path.read_bytes(), original) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/test_windows_process_priority.py b/tests/test_windows_process_priority.py deleted file mode 100644 index ab964d557..000000000 --- a/tests/test_windows_process_priority.py +++ /dev/null @@ -1,69 +0,0 @@ -"""Regression checks for the Windows pseudo-handle passed to SetPriorityClass.""" - -import ctypes -import importlib -import subprocess -import sys -import unittest -from ctypes import wintypes -from pathlib import Path -from types import SimpleNamespace -from unittest import mock - -TOOLS = Path(__file__).resolve().parents[1] / "tools" -sys.path.insert(0, str(TOOLS)) - -MODULES = ("bvh_index", "manifest_verifier", "navmesh_index", "rpf9_carve") -BELOW_NORMAL_PRIORITY_CLASS = 0x00004000 - - -class WindowsProcessPriorityTest(unittest.TestCase): - def test_win32_signatures(self): - for name in MODULES: - with self.subTest(module=name): - module = importlib.import_module(name) - kernel32 = mock.Mock() - with ( - mock.patch.object(module, "os", SimpleNamespace(name="nt")), - mock.patch.object(ctypes, "windll", SimpleNamespace(kernel32=kernel32), create=True), - ): - module.below_normal() - self.assertEqual(kernel32.GetCurrentProcess.argtypes, ()) - self.assertIs(kernel32.GetCurrentProcess.restype, wintypes.HANDLE) - self.assertEqual(kernel32.SetPriorityClass.argtypes, (wintypes.HANDLE, wintypes.DWORD)) - self.assertIs(kernel32.SetPriorityClass.restype, wintypes.BOOL) - kernel32.SetPriorityClass.assert_called_once_with( - kernel32.GetCurrentProcess.return_value, BELOW_NORMAL_PRIORITY_CLASS - ) - - @unittest.skipUnless(sys.platform == "win32", "requires Windows process priority classes") - def test_child_process_reaches_below_normal_priority(self): - # Start every child at normal priority so a swallowed error cannot pass the test. - probe = """ -import ctypes -import importlib -import sys -from ctypes import wintypes - -sys.path.insert(0, sys.argv[1]) -importlib.import_module(sys.argv[2]).below_normal() -kernel32 = ctypes.WinDLL("kernel32") -kernel32.GetCurrentProcess.argtypes = () -kernel32.GetCurrentProcess.restype = wintypes.HANDLE -kernel32.GetPriorityClass.argtypes = (wintypes.HANDLE,) -kernel32.GetPriorityClass.restype = wintypes.DWORD -print(kernel32.GetPriorityClass(kernel32.GetCurrentProcess())) -""" - for name in MODULES: - with self.subTest(module=name): - result = subprocess.run( - [sys.executable, "-I", "-B", "-c", probe, str(TOOLS), name], - creationflags=subprocess.NORMAL_PRIORITY_CLASS, - capture_output=True, encoding="utf-8", errors="replace", timeout=30, - ) - self.assertEqual(result.returncode, 0, result.stderr) - self.assertEqual(result.stdout.strip(), str(BELOW_NORMAL_PRIORITY_CLASS), result.stderr) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/test_wint_diff.py b/tests/test_wint_diff.py deleted file mode 100644 index 0152482b5..000000000 --- a/tests/test_wint_diff.py +++ /dev/null @@ -1,383 +0,0 @@ -"""tools/wint_diff.py: the whole-wave reference against hand-worked values, a short seeded fuzz run, and canaries. -Standard library only; no GPU.""" -import contextlib -import io -import os -from pathlib import Path -import re -import subprocess -import sys -import unittest -import unittest.mock - -TOOL = Path(__file__).resolve().parents[1] / "tools" / "wint_diff.py" -sys.path.insert(0, str(TOOL.parent)) -import wint_diff as d # noqa: E402 - - -def program(body, wave=32, obs=(1, 2, 3, 4)): - """Every data VGPR starts as the lane number, s = N, s20/s[20:21] = lanes < 4, s21/s[22:23] = lanes < 2, - VCC = no lane.""" - init = ["v_mbcnt_lo_u32_b32 v0, -1, 0"] + (["v_mbcnt_hi_u32_b32 v0, -1, v0"] if wave == 64 else []) - init += [f"v_mov_b32_e32 v{v}, v0" for v in d.DREGS] + [f"s_mov_b32 s{s}, {s}" for s in d.SREGS] - m1, m2, vcc = d.masks(wave) - init += [f"v_cmp_lt_u32_e64 {m1}, v0, 4", f"v_cmp_lt_u32_e64 {m2}, v0, 2", f"v_cmp_ne_u32_e64 {vcc}, 0, 0"] - return d.Program(init, list(body), list(obs), wave) - - -def run(body, wave=32, obs=(1, 2, 3, 4)): - p = program(body, wave, obs) - return d.reference(p.lines(), wave) - - -class Reference(unittest.TestCase): - def test_carry_out_and_in_under_exec(self): - out = run(["s_mov_b32 exec_lo, 0xf", # lanes 0..3 - "v_add_co_u32_e64 v1, s20, v0, -2", # lanes 2 and 3 carry: s20 = 0b1100 - "v_add_co_ci_u32_e64 v2, s21, v0, 0, s20", # v2 = lane + carry - "v_cndmask_b32_e64 v3, 7, 9, s20"]) - self.assertEqual(out[0], (0xFFFFFFFE, 0, 7, 0)) - self.assertEqual(out[3], (1, 4, 9, 3)) - self.assertEqual(out[5], (5, 5, 5, 5)) # inactive: untouched - - def test_borrow(self): - # 0 - 0 - borrow(1) = 0xffffffff with a borrow out; s20 holds lanes 0..3 as the borrow in - out = run(["v_sub_co_ci_u32_e64 v1, s21, 0, 0, s20", "v_cndmask_b32_e64 v2, 0, 1, s21"]) - self.assertEqual(out[1][:2], (0xFFFFFFFF, 1)) - self.assertEqual(out[4][:2], (0, 0)) - - def test_clamp_saturates_d_and_keeps_the_carry(self): - # v1 = lane + 0xfffffffe saturates from lane 2 on; v2 = lane - 2 saturates to 0 in lanes 0 and 1; - # both masks still get the real carry / borrow - out = run(["v_add_co_u32_e64 v1, s20, v0, -2 clamp", "v_sub_co_u32_e64 v2, s21, v0, 2 clamp", - "v_cndmask_b32_e64 v3, 0, 1, s20", "v_cndmask_b32_e64 v4, 0, 1, s21"]) - self.assertEqual(out[0], (0xFFFFFFFE, 0, 0, 1)) - self.assertEqual(out[1], (0xFFFFFFFF, 0, 0, 1)) - self.assertEqual(out[2], (0xFFFFFFFF, 0, 1, 0)) - self.assertEqual(out[5], (0xFFFFFFFF, 3, 1, 0)) - - def test_clamp_counts_the_carry_in(self): - # carry in = lanes 0..3. Lane 0: -1 + 0 + 1 and 0 - 0 - 1 overflow only through the carry in - out = run(["v_add_co_ci_u32_e64 v1, s21, -1, v0, s20 clamp", "v_cndmask_b32_e64 v2, 0, 1, s21", - "v_subrev_co_ci_u32_e64 v3, vcc_lo, v0, 0, s20 clamp", "v_cndmask_b32_e64 v4, 0, 1, vcc_lo"]) - self.assertEqual(out[0], (0xFFFFFFFF, 1, 0, 1)) - self.assertEqual(out[4], (0xFFFFFFFF, 1, 0, 1)) - for line in ("v_add_co_u32_e32 v1, vcc_lo, v0, v2 clamp", "v_xor_b32_e64 v1, v0, v2 clamp", - "v_add_nc_u16 v1, v0, v2 clamp", "s_mov_b32 s20, 1 clamp", "v_writelane_b32 v1, s20, 3 clamp", - "v_mbcnt_lo_u32_b32 v0, -1, 0 clamp", "v_xor_b32_e64 v1, v0, v2 op_sel:[1,0,0]", - "s_mov_b32 s20, 1 op_sel:[1,0]"): - with self.subTest(line=line), self.assertRaises(d.RefError): - run([line]) - # rejected before it runs: EXEC keeps its value (it used to become 1) - st = d.State(32) - before = st.exec - with self.assertRaises(d.RefError): - d.step(st, "s_mov_b32 exec_lo, 1 clamp") - self.assertEqual(st.exec, before) - - def test_inactive_lanes_get_a_zero_mask_bit(self): - # s20 starts as lanes 0..3; a compare that is true everywhere but runs on lanes 2..31 clears lanes 0 and 1 - out = run(["s_mov_b32 exec_lo, 0xfffffffc", "v_cmp_t_u32_e64 s20, v0, v0", "s_mov_b32 exec_lo, -1", - "v_cndmask_b32_e64 v1, 0, 1, s20"]) - self.assertEqual([out[lane][0] for lane in range(4)], [0, 0, 1, 1]) - - def test_cmpx_writes_exec(self): - out = run(["v_cmpx_gt_i32_e64 v0, 29", "v_mov_b32_e32 v1, 77"]) - self.assertEqual([out[lane][0] for lane in (28, 29, 30, 31)], [28, 29, 77, 77]) - - def test_mad64_carry(self): - # u64: (2^32 - 1)^2 + (2^64 - 1) = 2^65 - 2^33: low 64 bits 0xfffffffe_00000000, bit 64 set - out = run(["v_mov_b32_e32 v4, -1", "v_mov_b32_e32 v5, -1", - "v_mad_u64_u32 v[2:3], s20, -1, -1, v[4:5]", "v_cndmask_b32_e64 v1, 0, 1, s20"], - obs=(2, 3, 1, 1)) - self.assertEqual(out[7], (0, 0xFFFFFFFE, 1, 1)) - # i64: -1 * lane + 0 is negative for lane > 0: the carry is the sign of the exact result - out = run(["v_mov_b32_e32 v4, 0", "v_mov_b32_e32 v5, 0", - "v_mad_i64_i32 v[2:3], s20, -1, v0, v[4:5]", "v_cndmask_b32_e64 v1, 0, 1, s20"], - obs=(2, 3, 1, 1)) - self.assertEqual(out[0], (0, 0, 0, 0)) - self.assertEqual(out[6], (0xFFFFFFFA, 0xFFFFFFFF, 1, 1)) - - def test_16bit_writes_one_half(self): - out = run(["v_mov_b32_e32 v1, 0x12345678", "v_mov_b32_e32 v2, 0x00030004", - "v_add_nc_u16 v1, v2, v2 op_sel:[1,0,1]", # 3 + 4 into the high half - "v_mov_b32_e32 v3, 0x12345678", "v_mul_lo_u16_e64 v3, v2, -1"]) # 4 * 0xffff: 0xfffc - self.assertEqual(out[0][:3], (0x00075678, 0x00030004, 0x1234FFFC)) - - def test_wave64_exec_hi_and_pairs(self): - out = run(["s_mov_b32 exec_lo, 0", "s_mov_b32 exec_hi, 0x80000001", # lanes 32 and 63 - "v_cmp_ge_u32_e64 s[20:21], v0, 33", "v_add_nc_u32_e64 v1, v0, 100", - "s_mov_b32 exec_lo, -1", "s_mov_b32 exec_hi, -1", - "v_cndmask_b32_e64 v2, 0, 1, s[20:21]"], wave=64) - self.assertEqual([out[lane][:2] for lane in (0, 32, 33, 63)], [(0, 0), (132, 0), (33, 0), (163, 1)]) - - def test_data_in_a_mask_sgpr_is_read_bit_by_bit(self): - out = run(["s_mov_b32 s20, 0xa", "v_cndmask_b32_e64 v1, 0, 1, s20"]) - self.assertEqual([out[lane][0] for lane in range(5)], [0, 1, 0, 1, 0]) - - -class Generator(unittest.TestCase): - def lines(self, known=False, wave=32, n=3000, seed=1): - real, d.KNOWN = d.KNOWN, known - try: - rng = d.random.Random(seed) - return [line for _ in range(n) for line in d.Gen(rng, wave, d.ALL_OPS).op()] - finally: - d.KNOWN = real - - @staticmethod - def opname(line): - op = line.split()[0] - if op == "s_mov_b32": - dst = line.split()[1].rstrip(",") - return "exec" if dst.startswith("exec") else "vcc" if dst.startswith("vcc") else "smask" - return re.sub(r"_e(32|64)$", "", op) - - def test_empty_op_selection_raises_value_error(self): - for wave in (32, 64): - for ops in ([], ["v_nonexistent_op"]): - with self.subTest(call="Gen", wave=wave, ops=ops): - with self.assertRaisesRegex(ValueError, r"^no ops selected$"): - d.Gen(d.random.Random(0), wave, ops) - with self.subTest(call="generate", wave=wave, ops=ops): - with self.assertRaisesRegex(ValueError, r"^no ops selected$"): - d.generate(d.random.Random(0), 1, ops, wave) - with self.subTest(call="run_suite", wave=wave, ops=ops): - with self.assertRaisesRegex(ValueError, r"^no ops selected$"): - d.run_suite(1, 0, 1, ops, (wave,)) - - def test_every_op_is_generated(self): - for wave in (32, 64): - seen = {self.opname(line) for line in self.lines(wave=wave)} - self.assertEqual(set(d.ALL_OPS) - seen, set(), wave) - - def test_clamp_only_on_the_e64_carry_ops(self): - for wave in (32, 64): - lines = self.lines(wave=wave) - clamped = [line for line in lines if line.endswith(" clamp")] - self.assertEqual({self.opname(line) for line in clamped}, set(d.CARRY), wave) - self.assertTrue(all(line.split()[0].endswith("_e64") for line in clamped), wave) - plain = [line for line in lines if line.split()[0].endswith("_e64") and self.opname(line) in d.CARRY - and not line.endswith(" clamp")] - self.assertTrue(plain, wave) - - def test_known_divergences_are_left_out_by_default(self): - def forms(lines): - out = set() - for line in lines: - op, _, rest = line.partition(" ") - rest = rest.removesuffix(" clamp") - if op == "s_mov_b32" and rest.startswith("vcc"): - out.add("vcc-data-mask") - if op.startswith("s_"): - continue - srcs = [a.strip() for a in rest.split(",")] - # drop the destination, the mask destinations and the mask operands (carry-in, cndmask selector) - skip = 0 if op.startswith("v_cmpx_") else 2 if "_co_" in op or op in d.MAD64 else 1 - srcs = srcs[skip:-1] if op.startswith("v_cndmask") or "_co_ci_" in op else srcs[skip:] - if any(re.fullmatch(r"s2[0-3]|vcc_lo|vcc_hi", s) for s in srcs): - out.add("mask-as-data") - return out - for wave in (32, 64): - self.assertEqual(forms(self.lines(wave=wave)), set(), wave) - self.assertEqual(forms(self.lines(known=True, wave=wave)), set(d.KNOWN_DIVERGENCES), wave) - - -class Translated(unittest.TestCase): - def test_harness_canaries(self): - with contextlib.redirect_stdout(io.StringIO()): - self.assertTrue(d.self_test()) - - def test_short_seeded_run_matches(self): - counts, failures = d.run_suite(40, 7, 6, d.ALL_OPS, (32, 64)) - self.assertEqual(failures, [], failures[:1]) - self.assertEqual(counts["skip"], {}) - self.assertEqual(counts["pass"], 40) - - def test_hand_cases_match_the_translator(self): - cases = [ - (32, ["s_mov_b32 exec_lo, 0x0000ff0f", "v_add_co_u32_e64 v1, s20, v0, -2", - "v_add_co_ci_u32_e64 v2, s21, v0, 0, s20", "v_cndmask_b32_e64 v3, 7, 9, s20", - "v_mad_i64_i32 v[4:5], s21, -1, v0, v[12:13]", "v_cmpx_gt_i32_e64 v0, 9", - "v_add_nc_u16 v12, v2, v2 op_sel:[1,0,1]"]), - # a carry-out written under a narrow EXEC is 0 in the lanes that were off - (32, ["s_mov_b32 exec_lo, 0xfffffffc", "v_add_co_u32_e64 v2, s20, v0, -1", "s_mov_b32 exec_lo, -1", - "v_cndmask_b32_e64 v1, 0, 1, s20", "v_mov_b32_e32 v3, 0", "v_mov_b32_e32 v12, 0"]), - (64, ["s_mov_b32 exec_hi, 0x80000001", "v_cmp_ge_u32_e64 s[20:21], v0, 33", - "v_sub_co_ci_u32_e64 v1, s[22:23], 0, v0, s[20:21]", "s_mov_b32 s22, 0xa", "s_mov_b32 s23, 0x3", - "v_cndmask_b32_e64 v2, 0, 1, s[22:23]", "v_add_co_ci_u32_e32 v3, vcc, 5, v0, vcc"]), - ] - for wave, body in cases: - with self.subTest(wave=wave): - self.assertIsNone(d.check(program(body, wave, (1, 2, 3, 12 if wave == 32 else 4)))) - - def test_clamp_cases_match_the_translator(self): - cases = [ - # lane + 0xffffffff + carry in: the sum's low word is the lane again, and in lane 0 only the carry in - # overflows - (32, ["s_mov_b32 exec_lo, 0xfffffff3", "v_add_co_ci_u32_e64 v3, vcc_lo, v0, -1, s21 clamp", - "v_add_co_u32_e64 v1, s20, v0, -2 clamp", "v_sub_co_u32_e64 v2, s21, v0, 2 clamp", - "s_mov_b32 exec_lo, -1", "v_subrev_co_ci_u32_e64 v12, s20, v0, 3, s21 clamp"]), - # lane - 0xffffffff - borrow in: with the borrow in, the low word is the lane again - (64, ["s_mov_b32 exec_hi, 0xfffffff3", "v_add_co_u32_e64 v1, s[22:23], v0, -40 clamp", - "v_sub_co_ci_u32_e64 v2, vcc, v0, -1, s[22:23] clamp", - "v_subrev_co_u32_e64 v3, s[20:21], 40, v0 clamp", "v_cndmask_b32_e64 v4, 0, 1, vcc"]), - ] - for wave, body in cases: - with self.subTest(wave=wave): - self.assertIsNone(d.check(program(body, wave, (1, 2, 3, 12 if wave == 32 else 4)))) - - def test_a_wrong_translation_is_caught(self): - prog = program(["s_mov_b32 exec_lo, 0xf", "v_add_co_u32_e64 v1, s20, v0, -2", - "v_cndmask_b32_e64 v2, 7, 9, s20"]) - self.assertIsNone(d.check(prog)) - want = d.reference(prog.lines(), 32) - real = d.translated - try: - # one lane's word off: a write that ignored EXEC on lane 9 - d.translated = lambda lines, wave: [w if lane != 9 else (want[9][0] ^ 4,) + w[1:] - for lane, w in enumerate(want)] - self.assertIn("lane 9 word 0 (v1)", d.check(prog)) - d.translated = lambda lines, wave: want[:31] + [None] - self.assertIn("lane 31", d.check(prog)) - finally: - d.translated = real - - def test_shrinking_keeps_the_instruction_that_matters(self): - prog = d.generate(d.random.Random(2), 5, ["v_add_nc_u32", "v_xor_b32", "exec"], 32) - target = next(line for line in prog.body if not line.startswith("s_")) - real = d.translated - try: - d.translated = lambda lines, wave: [tuple(w ^ (target in lines) for w in lane) - for lane in d.reference(lines, wave)] - small = d.shrink(prog) - finally: - d.translated = real - self.assertEqual(small.body, [target]) - - -class Cli(unittest.TestCase): - def main(self, *argv): - out = io.StringIO() - with contextlib.redirect_stdout(out), contextlib.redirect_stderr(io.StringIO()): - try: - rc = d.main(list(argv)) - except SystemExit as e: - rc = e.code - return rc, out.getvalue() - - def test_exit_codes(self): - rc, out = self.main("--list-ops") - self.assertEqual(rc, 0) - self.assertIn("v_mad_i64_i32", out) - self.assertRegex(out, r"v_sub_co_ci_u32 +carry, clamp \(e64\)") - self.assertEqual(self.main("--ops", "v_nope")[0], 2) - self.assertEqual(self.main("--oracle", "gpu")[0], 2) - self.assertEqual(self.main("--wave", "16")[0], 2) - rc, out = self.main("--programs", "4", "--seed", "1", "--wave", "both") - self.assertEqual(rc, 0, out) - real = d.translated - try: - d.translated = lambda lines, wave: [tuple(w ^ 1 for w in lane) for lane in d.reference(lines, wave)] - rc, out = self.main("--programs", "2", "--seed", "1", "--ops", "v_xor_b32") - finally: - d.translated = real - self.assertEqual(rc, 1) - self.assertIn("MISMATCH", out) - - def test_a_run_where_every_program_was_skipped_is_not_a_success(self): - def refuse(lines, wave): - raise d.Skip("unsupported form") - real = d.translated - try: - d.translated = refuse - rc, out = self.main("--programs", "3", "--seed", "1", "--ops", "v_xor_b32") - finally: - d.translated = real - self.assertEqual(rc, 2, out) - self.assertIn("no program ran: every one was skipped", out) - self.assertIn("3 skipped", out) - - def test_hardware_oracle_without_the_tools_exits_77(self): - env = dict(os.environ, LEONIDA_AMD_CLANG=str(TOOL.parent / "no-such-clang.exe")) - r = subprocess.run([sys.executable, "-I", str(TOOL), "--oracle", "hw", "--programs", "3"], - capture_output=True, text=True, env=env) - self.assertEqual(r.returncode, 77, r.stdout + r.stderr) - self.assertIn("unavailable", r.stdout) - - def test_hardware_kernel_stores_every_lane(self): - prog = program(["v_mov_b32_e32 v1, 5"], wave=64) - k = d.hw_kernel(prog) - self.assertEqual((k.wave, k.threads, k.words, k.raw), (64, 64, 256, True)) - self.assertEqual(k.lines[-3:], ["v_lshlrev_b32 v20, 4, v0", "global_store_b128 v20, v[8:11], s[2:3]", - "s_endpgm"]) - words = list(range(256)) - self.assertEqual(d.hw_words(words, 64)[1], (4, 5, 6, 7)) - self.assertEqual(d.hw_words("assembler rejected: x", 64), "assembler rejected: x") - - -class OracleGuards(unittest.TestCase): - def setUp(self): - self.orig_known = d.KNOWN - - def tearDown(self): - d.KNOWN = self.orig_known - - def test_hw_words_refuses_none_or_short_words(self): - with self.assertRaises(RuntimeError) as ctx: - d.hw_words(None, 32) - self.assertIn("no result from the hardware runner", str(ctx.exception)) - - with self.assertRaises(RuntimeError) as ctx: - d.hw_words([0] * 50, 32) - self.assertIn("the hardware runner returned 50 words (expected 128)", str(ctx.exception)) - - def test_check_refuses_none_or_short_lanes(self): - p = program(["v_mov_b32_e32 v1, 5"], wave=32) - with self.assertRaises(RuntimeError) as ctx: - d.check(p, backends=("hw",), hw=None) - self.assertIn("no result from the hardware runner", str(ctx.exception)) - - with self.assertRaises(RuntimeError) as ctx: - d.check(p, backends=("hw",), hw=[(0, 0, 0, 0)] * 10) - self.assertIn("the hardware runner returned 10 lanes (expected 32)", str(ctx.exception)) - - def test_run_suite_refuses_short_or_none_oracle_results(self): - mock_oracle = unittest.mock.MagicMock() - mock_oracle.run.return_value = [[0] * 128] * 2 - with self.assertRaises(RuntimeError) as ctx: - d.run_suite(programs=3, seed=1, max_ops=2, ops=["v_mov_b32"], backends=("hw",), oracle=mock_oracle) - self.assertIn("the hardware runner returned 2 results for 3 programs", str(ctx.exception)) - - mock_oracle.run.return_value = None - with self.assertRaises(RuntimeError) as ctx: - d.run_suite(programs=3, seed=1, max_ops=2, ops=["v_mov_b32"], backends=("hw",), oracle=mock_oracle) - self.assertIn("the hardware runner returned 0 results for 3 programs", str(ctx.exception)) - - def test_main_exits_2_on_oracle_count_mismatch(self): - mock_oracle = unittest.mock.MagicMock() - mock_oracle.device = "mock device" - mock_oracle.run.return_value = [[0] * 128] * 2 - out, err = io.StringIO(), io.StringIO() - with unittest.mock.patch("hw_oracle.runner.open_oracle", return_value=mock_oracle): - with contextlib.redirect_stdout(out), contextlib.redirect_stderr(err): - rc = d.main(["--oracle", "hw", "--programs", "3", "--seed", "1"]) - self.assertEqual(rc, 2) - self.assertIn("harness error: the hardware runner returned 2 results for 3 programs", out.getvalue()) - mock_oracle.close.assert_called_once() - - def test_main_shrink_refuses_empty_oracle_result(self): - mock_oracle = unittest.mock.MagicMock() - mock_oracle.device = "mock device" - mock_oracle.run.side_effect = [[[0x11111111] * 128], []] - out, err = io.StringIO(), io.StringIO() - with unittest.mock.patch("hw_oracle.runner.open_oracle", return_value=mock_oracle): - with contextlib.redirect_stdout(out), contextlib.redirect_stderr(err): - rc = d.main(["--oracle", "hw", "--programs", "1", "--seed", "1"]) - self.assertEqual(rc, 2) - self.assertIn("harness error:", out.getvalue()) - mock_oracle.close.assert_called_once() - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/test_world_archetypes.py b/tests/test_world_archetypes.py deleted file mode 100644 index 250fc2fe3..000000000 --- a/tests/test_world_archetypes.py +++ /dev/null @@ -1,353 +0,0 @@ -"""Tests for tools/world_archetypes.py, built from synthetic 0x7a resources (no game data). - - python -I tests/test_world_archetypes.py -""" -import contextlib -import importlib.util -import io -import json -import math -import os -import struct -import sys -import tempfile -import unittest -import zlib -from contextlib import redirect_stdout - -ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) - - -def load_tool(): - path = os.path.join(ROOT, "tools", "world_archetypes.py") - spec = importlib.util.spec_from_file_location("world_archetypes_under_test", path) - module = importlib.util.module_from_spec(spec) - spec.loader.exec_module(module) - return module - - -WA = load_tool() -WI = WA.WI -J = WA.joaat_cs -SYS = 0x50000000 -BASE, MLO = J("CBaseArchetypeDef"), J("CMloArchetypeDef") -S = math.sqrt(0.5) - - -def build(structs, blocks): - """A valid 0x7a resource. structs: [(hash, size, [(member hash, offset, type)])]; blocks: [(hash, bytes)].""" - st = 0x60 - mt = st + 32 * len(structs) - member_at, p = [], mt - for _, _, members in structs: - member_at.append(p) - p += 16 * len(members) - bt = (p + 15) & ~15 - p = bt + 16 * len(blocks) - data_at = [] - for _, payload in blocks: - p = (p + 15) & ~15 - data_at.append(p) - p += len(payload) - b = bytearray(p + 16) - b[0x10:0x15] = b"0DRPz" - struct.pack_into(" +Y - lo, _ = WA.world_box(e, *box, conjugate=True, use_scale=False) - self.assertAlmostEqual(lo[1], -1.0, places=6) # conjugate: +X -> -Y - - def test_scale_xy_and_z(self): - e = {"position": [0, 0, 0], "scale_xy": 2.0, "scale_z": 3.0} - lo, hi = WA.world_box(e, (-1.0, -1.0, 0.0), (1.0, 1.0, 1.0), conjugate=True, use_scale=True) - self.assertEqual((lo, hi), ([-2.0, -2.0, 0.0], [2.0, 2.0, 3.0])) - lo, hi = WA.world_box(e, (-1.0, -1.0, 0.0), (1.0, 1.0, 1.0), conjugate=True, use_scale=False) - self.assertEqual((lo, hi), ([-1.0, -1.0, 0.0], [1.0, 1.0, 1.0])) - - def test_zero_scales_collapse_only_their_axes(self): - box = ((-1.0, -2.0, -3.0), (2.0, 4.0, 4.0)) - for zero in (0.0, -0.0): - cases = [ - (zero, 3.0, ([10.0, 20.0, 21.0], [10.0, 20.0, 42.0])), - (2.0, zero, ([8.0, 16.0, 30.0], [14.0, 28.0, 30.0])), - (zero, zero, ([10.0, 20.0, 30.0], [10.0, 20.0, 30.0])), - ] - for sxy, sz, expected in cases: - with self.subTest(scale_xy=sxy, scale_z=sz): - e = {"position": [10.0, 20.0, 30.0], "scale_xy": sxy, "scale_z": sz} - self.assertEqual(WA.world_box(e, *box, conjugate=True, use_scale=True), expected) - self.assertEqual(WA.world_box(e, *box, conjugate=True, use_scale=False), - ([9.0, 18.0, 27.0], [12.0, 24.0, 34.0])) - - def test_missing_and_none_scales_still_default_to_one(self): - for scales in ({}, {"scale_xy": None}, {"scale_z": None}, {"scale_xy": None, "scale_z": None}): - with self.subTest(scales=scales): - e = {"position": [10.0, 20.0, 30.0], **scales} - self.assertEqual(WA.world_box(e, (-1.0, -2.0, -3.0), (2.0, 4.0, 4.0), - conjugate=True, use_scale=True), - ([9.0, 18.0, 27.0], [12.0, 24.0, 34.0])) - - -class ExtentsTest(unittest.TestCase): - def test_conjugate_matches_and_scale_is_ignored(self): - defs_b, m = scene() - defs = {d["name"]: d for d in WA.parse_archetypes(defs_b)} - ents = [] - row = WI.parse_resource(m, collect=ents) - res = WA.check_extents([(row, ents)], defs) - self.assertEqual(res["maps_fully_defined"], 1) - self.assertEqual((res["rotation"]["conjugate_matches"], res["rotation"]["stored_matches"]), (1, 0)) - self.assertLess(res["rotation"]["conjugate_median_error_m"], 1e-4) - self.assertEqual((res["scale"]["unscaled_matches"], res["scale"]["scaled_matches"]), (1, 0)) - self.assertEqual(res["scale"]["scaled_exceeds_extents"], 1) - - def test_map_with_an_undefined_archetype_is_not_judged(self): - defs_b, m = scene() - defs = {d["name"]: d for d in WA.parse_archetypes(defs_b) if d["name"] == ROCK} - ents = [] - row = WI.parse_resource(m, collect=ents) - self.assertEqual(WA.check_extents([(row, ents)], defs)["maps_fully_defined"], 0) - - def test_zero_scale_maps_are_included_in_scale_comparisons(self): - defs = {d["name"]: d for d in WA.parse_archetypes(maptypes([(CRATE, 1, *CRATE_BOX)]))} - for zero in (0.0, -0.0): - for sxy, sz in ((zero, 1.0), (1.0, zero), (zero, zero)): - with self.subTest(scale_xy=sxy, scale_z=sz): - m = mapfile([entity(CRATE, (0.0, 0.0, 0.0), sxy=sxy, sz=sz)], *CRATE_BOX) - ents = [] - row = WI.parse_resource(m, collect=ents) - res = WA.check_extents([(row, ents)], defs) - self.assertEqual(res["maps_fully_defined"], 1) - self.assertEqual(res["scale"], {"maps": 1, "scaled_matches": 0, "unscaled_matches": 1, - "scaled_exceeds_extents": 0, "unscaled_exceeds_extents": 0}) - - def test_missing_and_none_scales_are_not_counted_as_scaled(self): - defs = {CRATE: {"bb_min": CRATE_BOX[0], "bb_max": CRATE_BOX[1]}} - row = {"entities_min": CRATE_BOX[0], "entities_max": CRATE_BOX[1]} - for scales in ({}, {"scale_xy": None}, {"scale_z": None}, {"scale_xy": None, "scale_z": None}): - with self.subTest(scales=scales): - res = WA.check_extents([(row, [{"archetype": CRATE, **scales}])], defs) - self.assertEqual(res["maps_fully_defined"], 1) - self.assertEqual(res["scale"]["maps"], 0) - - -class CliTest(unittest.TestCase): - def setUp(self): - self.tmp = tempfile.TemporaryDirectory() - self.addCleanup(self.tmp.cleanup) - - def run_cli(self, path): - out = os.path.join(self.tmp.name, "out", "archetypes.json") - with redirect_stdout(io.StringIO()): - self.assertEqual(WA.main([path, "--out", out, "--check-extents"]), 0) - with open(out, "rb") as f: - raw = f.read() - self.assertNotIn(b"\r\n", raw) - return json.loads(raw) - - def check(self, doc): - s = doc["summary"] - self.assertEqual((s["maptypes"], s["archetypes"], s["names"]), (1, 2, 2)) - self.assertEqual((s["kinds"], s["asset_types"]), ({"base": 2}, {"1": 1, "2": 1})) - self.assertEqual(doc["schemas"]["base"]["size"], SIZE) - self.assertEqual(doc["extents"]["rotation"]["conjugate_matches"], 1) - - def test_folder_of_carved_files(self): - defs, m = scene() - folder = os.path.join(self.tmp.name, "carved") - os.makedirs(folder) - for name, data in (("a.bin", defs), ("b.bin", m)): - with open(os.path.join(folder, name), "wb") as f: - f.write(data) - self.check(self.run_cli(folder)) - - def test_rpf9_window(self): - defs, m = scene() - path = os.path.join(self.tmp.name, "levels.rpf") - with open(path, "wb") as f: - f.write(rpf([defs, m])) - self.check(self.run_cli(path)) - - def cli_error(self, argv): - err = io.StringIO() - with redirect_stdout(io.StringIO()), contextlib.redirect_stderr(err), self.assertRaises(SystemExit) as cm: - WA.main(argv) - self.assertEqual(cm.exception.code, 2) - self.assertNotIn("Traceback", err.getvalue()) - return err.getvalue() - - def test_out_equal_to_the_input_is_refused_and_leaves_it_alone(self): - path = os.path.join(self.tmp.name, "carved.bin") - with open(path, "wb") as f: - f.write(b"\x00" * 3000) - self.assertIn("overwrite the input", self.cli_error([path, "--out", path])) - with open(path, "rb") as f: - self.assertEqual(f.read(), b"\x00" * 3000) - - def test_out_under_a_regular_file_or_naming_a_folder_is_one_error(self): - path = os.path.join(self.tmp.name, "carved.bin") - with open(path, "wb") as f: - f.write(b"\x00" * 64) - self.assertIn("--out", self.cli_error([path, "--out", os.path.join(path, "sub", "r.json")])) - self.assertIn("folder", self.cli_error([path, "--out", self.tmp.name])) - - def test_missing_path_is_an_error(self): - with redirect_stdout(io.StringIO()), self.assertRaises(SystemExit): - sys.stderr, saved = io.StringIO(), sys.stderr - try: - WA.main([os.path.join(self.tmp.name, "nope")]) - finally: - sys.stderr = saved - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/test_world_build.py b/tests/test_world_build.py deleted file mode 100644 index 6524d9210..000000000 --- a/tests/test_world_build.py +++ /dev/null @@ -1,2279 +0,0 @@ -"""Synthetic unit and integration tests for the world-build pipeline (no game data). - - python -I tests/test_world_build.py -v - -Covers: - - tools/dds_png.py (DDS header parsing, BGRA8/RGBA8/BGRX8/BC1/BC2/BC3/BC4/BC5, downscale, PNG encoder) - - tools/glb_writer.py (OBJ parser, bounds, binary glTF 2.0 writer, texture dedup, 32-bit indices, summary) - - tools/world_build.py (manifest discovery, TTPF indexing, texture resolution, spatial/grid/no-tex/limit builds, - --base-color-param selection with GLB pixel readback) - - viewer/serve.py (safe_world_path traversal hardening) - -Every texture, mesh, manifest, and archive layout is generated synthetically in memory or a temporary directory. -""" -import functools -import http.client -import importlib.util -import json -import math -import os -import socket -import stat -import struct -import subprocess -import sys -import tempfile -import threading -import unittest -import unittest.mock -import zlib -from http.server import HTTPServer, ThreadingHTTPServer - -ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) -TOOLS = os.path.join(ROOT, "tools") -VIEWER = os.path.join(ROOT, "viewer") - -if TOOLS not in sys.path: - sys.path.insert(0, TOOLS) - -import dds_png # noqa: E402 -import glb_writer # noqa: E402 -import world_build # noqa: E402 - - -def _load_viewer_serve(): - path = os.path.join(VIEWER, "serve.py") - spec = importlib.util.spec_from_file_location("viewer_serve_under_test", path) - if spec is None or spec.loader is None: - raise ImportError(f"cannot load viewer/serve.py from {path}") - mod = importlib.util.module_from_spec(spec) - sys.modules["viewer_serve_under_test"] = mod - spec.loader.exec_module(mod) - return mod - - -viewer_serve = _load_viewer_serve() - - -# --------------------------------------------------------------------------- -# Independent synthetic DDS builders (no game files, pure spec bit layouts) -# --------------------------------------------------------------------------- - -def make_bgra8_dds(width: int, height: int, rgba_pixels: bytes) -> bytes: - """Build a legacy 32-bit BGRA8 DDS matching tools/rpf9dump/Program.cs Util.BgraDds.""" - assert len(rgba_pixels) == width * height * 4 - bgra = bytearray(len(rgba_pixels)) - for i in range(0, len(rgba_pixels), 4): - r, g, b, a = rgba_pixels[i:i + 4] - bgra[i:i + 4] = bytes((b, g, r, a)) - hdr = bytearray(128) - struct.pack_into(" bytes: - """Build a DX10 DDS container (128-byte legacy header + 20-byte DX10 extension + payload).""" - hdr = bytearray(128) - hdr[0:4] = b"DDS " - flags = 0x1007 | (0x80000 if compressed else 0x8) - pitch = len(payload) if compressed else width * 4 - struct.pack_into(" bytes: - """Build a legacy FourCC compressed DDS (DXT1/DXT3/DXT5/ATI1/ATI2).""" - assert len(fourcc) == 4 - hdr = bytearray(128) - hdr[0:4] = b"DDS " - struct.pack_into(" bytes: - """Pack one 8-byte BC1/DXT1 block from two RGB565 endpoints and 16 2-bit codes.""" - assert len(codes) == 16 - bits = 0 - for i, c in enumerate(codes): - bits |= (c & 3) << (2 * i) - return struct.pack(" bytes: - """Pack one 16-byte BC2/DXT3 block (16 4-bit alphas + 8-byte color block).""" - assert len(alphas4) == 16 - alpha_bits = 0 - for i, a4 in enumerate(alphas4): - alpha_bits |= (a4 & 0xF) << (4 * i) - return struct.pack(" bytes: - """Pack one 8-byte BC4 / BC3-alpha interpolated block (2 endpoints + 16 3-bit codes).""" - assert len(codes) == 16 - bits = 0 - for i, c in enumerate(codes): - bits |= (c & 7) << (3 * i) - return bytes((a0 & 0xFF, a1 & 0xFF)) + bits.to_bytes(6, "little") - - -def pack_bc3_block(a0: int, a1: int, alpha_codes, c0: int, c1: int, color_codes) -> bytes: - """Pack one 16-byte BC3/DXT5 block (8-byte interpolated alpha + 8-byte color block).""" - return pack_bc4_block(a0, a1, alpha_codes) + pack_bc1_block(c0, c1, color_codes) - - -def pack_bc5_block(r0: int, r1: int, r_codes, g0: int, g1: int, g_codes) -> bytes: - """Pack one 16-byte BC5 two-channel block (R BC4 block + G BC4 block).""" - return pack_bc4_block(r0, r1, r_codes) + pack_bc4_block(g0, g1, g_codes) - - -# --------------------------------------------------------------------------- -# Independent PNG validator (RFC 2083, full CRC32 + zlib + scanline unfilter) -# --------------------------------------------------------------------------- - -def _paeth(a: int, b: int, c: int) -> int: - p = a + b - c - pa = abs(p - a) - pb = abs(p - b) - pc = abs(p - c) - if pa <= pb and pa <= pc: - return a - if pb <= pc: - return b - return c - - -def parse_and_validate_png(data: bytes) -> tuple[int, int, bytes]: - """Independently validate a PNG byte stream and return (width, height, rgba_bytes). - - Verifies: - - 8-byte PNG signature - - exact chunk framing & zlib.crc32 on EVERY chunk - - IHDR first, 8-bit RGBA (color_type=6), deflate/standard/non-interlaced - - zlib decompression of concatenated IDAT chunks and exact scanline unfiltering - - IEND last with length 0 and no trailing bytes - """ - sig = b"\x89PNG\r\n\x1a\n" - if not isinstance(data, (bytes, bytearray)): - raise AssertionError(f"PNG must be bytes, got {type(data).__name__}") - if data[:8] != sig: - raise AssertionError(f"bad PNG signature: {data[:8]!r}") - - pos = 8 - chunks = [] - while pos < len(data): - if pos + 12 > len(data): - raise AssertionError(f"truncated PNG chunk header at offset {pos}") - length, ctype = struct.unpack_from(">I4s", data, pos) - pos += 8 - if pos + length + 4 > len(data): - raise AssertionError(f"truncated PNG chunk {ctype!r} payload at offset {pos}") - cdata = data[pos:pos + length] - pos += length - stored_crc, = struct.unpack_from(">I", data, pos) - pos += 4 - calc_crc = zlib.crc32(ctype + cdata) & 0xFFFFFFFF - if stored_crc != calc_crc: - raise AssertionError( - f"CRC mismatch on PNG chunk {ctype!r}: stored=0x{stored_crc:08X}, calc=0x{calc_crc:08X}" - ) - chunks.append((ctype, cdata)) - if ctype == b"IEND": - break - - if pos != len(data): - raise AssertionError(f"trailing bytes after IEND: {len(data) - pos}") - if len(chunks) < 3: - raise AssertionError(f"too few PNG chunks: {[c[0] for c in chunks]}") - if chunks[0][0] != b"IHDR": - raise AssertionError(f"first PNG chunk must be IHDR, got {chunks[0][0]!r}") - if chunks[-1][0] != b"IEND" or len(chunks[-1][1]) != 0: - raise AssertionError(f"last PNG chunk must be empty IEND, got {chunks[-1][0]!r} len={len(chunks[-1][1])}") - - ihdr = chunks[0][1] - if len(ihdr) != 13: - raise AssertionError(f"IHDR length must be 13, got {len(ihdr)}") - width, height, bit_depth, color_type, compression, filter_method, interlace = struct.unpack(">IIBBBBB", ihdr) - if (bit_depth, color_type, compression, filter_method, interlace) != (8, 6, 0, 0, 0): - raise AssertionError( - f"unexpected IHDR format: bit_depth={bit_depth}, color_type={color_type}, " - f"comp={compression}, filter={filter_method}, interlace={interlace}" - ) - - idat_blob = b"".join(cdata for ctype, cdata in chunks if ctype == b"IDAT") - if not idat_blob: - raise AssertionError("PNG has no IDAT chunks") - raw = zlib.decompress(idat_blob) - bpp = 4 - stride = width * bpp - expected_len = height * (1 + stride) - if len(raw) != expected_len: - raise AssertionError(f"decompressed IDAT length {len(raw)} != expected {expected_len}") - - out = bytearray(height * stride) - prev = bytes(stride) - for y in range(height): - row_start = y * (1 + stride) - ftype = raw[row_start] - filt = raw[row_start + 1:row_start + 1 + stride] - recon = bytearray(stride) - if ftype == 0: - recon[:] = filt - elif ftype == 1: - for x in range(stride): - a = recon[x - bpp] if x >= bpp else 0 - recon[x] = (filt[x] + a) & 0xFF - elif ftype == 2: - for x in range(stride): - recon[x] = (filt[x] + prev[x]) & 0xFF - elif ftype == 3: - for x in range(stride): - a = recon[x - bpp] if x >= bpp else 0 - b = prev[x] - recon[x] = (filt[x] + ((a + b) >> 1)) & 0xFF - elif ftype == 4: - for x in range(stride): - a = recon[x - bpp] if x >= bpp else 0 - b = prev[x] - c = prev[x - bpp] if x >= bpp else 0 - recon[x] = (filt[x] + _paeth(a, b, c)) & 0xFF - else: - raise AssertionError(f"unsupported PNG scanline filter type {ftype} at row {y}") - out[y * stride:(y + 1) * stride] = recon - prev = bytes(recon) - - return width, height, bytes(out) - - -# --------------------------------------------------------------------------- -# Independent binary glTF 2.0 (.glb) validator -# --------------------------------------------------------------------------- - -def parse_and_validate_glb(data: bytes) -> tuple[dict, bytes]: - """Independently validate a binary glTF 2.0 (.glb) container and return (gltf_json, bin_chunk).""" - if len(data) < 20: - raise AssertionError(f"GLB too short: {len(data)} bytes") - magic, version, total_len = struct.unpack_from("<4sII", data, 0) - if magic != b"glTF": - raise AssertionError(f"bad GLB magic: {magic!r}") - if version != 2: - raise AssertionError(f"bad GLB version: {version}") - if total_len != len(data): - raise AssertionError(f"GLB length mismatch: header={total_len}, actual={len(data)}") - if total_len % 4 != 0: - raise AssertionError(f"GLB total length {total_len} not 4-byte aligned") - - json_len, json_type = struct.unpack_from(" total_len: - raise AssertionError("JSON chunk extends past EOF") - gltf = json.loads(data[20:json_end].decode("utf-8")) - - bin_data = b"" - if json_end < total_len: - if json_end + 8 > total_len: - raise AssertionError("truncated BIN chunk header") - bin_len, bin_type = struct.unpack_from(" len(bin_data): - raise AssertionError(f"bufferView[{idx}] overflows BIN chunk ({off}+{length} > {len(bin_data)})") - - return gltf, bin_data - - -def read_accessor_floats(gltf: dict, bin_data: bytes, acc_idx: int) -> list[tuple[float, ...]]: - """Extract float32 vectors from a glTF accessor.""" - acc = gltf["accessors"][acc_idx] - assert acc["componentType"] == 5126, f"expected FLOAT(5126), got {acc['componentType']}" - comps = {"SCALAR": 1, "VEC2": 2, "VEC3": 3, "VEC4": 4}[acc["type"]] - bv = gltf["bufferViews"][acc["bufferView"]] - base = bv.get("byteOffset", 0) + acc.get("byteOffset", 0) - stride = bv.get("byteStride") or (comps * 4) - fmt = f"<{comps}f" - return [struct.unpack_from(fmt, bin_data, base + i * stride) for i in range(acc["count"])] - - -def read_accessor_indices(gltf: dict, bin_data: bytes, acc_idx: int) -> list[int]: - """Extract scalar integer indices from a glTF accessor.""" - acc = gltf["accessors"][acc_idx] - fmt_map = {5121: " (132, 130, 132), c0 <= c1 -> exact mid (66, 65, 66), code 3 -> (0,0,0,0). - c0, c1 = 0x0000, 0x8410 - self.assertLessEqual(c0, c1) - codes = [0, 1, 2, 3, 3, 3, 2, 1, 0, 2, 3, 1, 1, 0, 3, 2] - palette = [ - (0, 0, 0, 255), - (132, 130, 132, 255), - (66, 65, 66, 255), - (0, 0, 0, 0), - ] - dds = make_fourcc_dds(4, 4, b"DXT1", pack_bc1_block(c0, c1, codes)) - w, h, rgba = dds_png.decode_dds(dds) - self.assertEqual((w, h), (4, 4)) - expected = b"".join(bytes(palette[c]) for c in codes) - self.assertEqual(rgba, expected) - - # Also check c0 == c1 still enters 3-color + transparent mode (code 3 -> (0,0,0,0)). - dds_eq = make_dx10_dds(4, 4, 71, pack_bc1_block(0xF800, 0xF800, [0, 3] * 8), compressed=True) - w_eq, h_eq, rgba_eq = dds_png.decode_dds(dds_eq) - self.assertEqual((w_eq, h_eq), (4, 4)) - self.assertEqual(rgba_eq[0:4], bytes((255, 0, 0, 255))) - self.assertEqual(rgba_eq[4:8], bytes((0, 0, 0, 0))) - - def test_bc1_odd_3x3_size(self): - # Sentinel code 3 fills column 3 and row 3; decoded 3x3 image must clip them cleanly. - c0, c1 = 0xF800, 0x001F - block_codes = [ - 0, 1, 2, 3, - 1, 2, 0, 3, - 2, 0, 1, 3, - 3, 3, 3, 3, - ] - palette = [ - (255, 0, 0, 255), - (0, 0, 255, 255), - (170, 0, 85, 255), - (85, 0, 170, 255), - ] - dds = make_fourcc_dds(3, 3, b"DXT1", pack_bc1_block(c0, c1, block_codes)) - w, h, rgba = dds_png.decode_dds(dds) - self.assertEqual((w, h), (3, 3)) - self.assertEqual(len(rgba), 3 * 3 * 4) - visible_codes = [0, 1, 2, 1, 2, 0, 2, 0, 1] - expected = b"".join(bytes(palette[c]) for c in visible_codes) - self.assertEqual(rgba, expected) - - def test_bc2_explicit_4bit_alpha(self): - alphas4 = [0x0, 0x8, 0xF, 0x1, 0x2, 0x4, 0x7, 0xA, 0xC, 0xE, 0x0, 0x8, 0xF, 0x5, 0x9, 0xB] - color_codes = [0, 1, 2, 3] * 4 - c0, c1 = 0xF800, 0x001F - rgb_pal = [(255, 0, 0), (0, 0, 255), (170, 0, 85), (85, 0, 170)] - dds = make_fourcc_dds(4, 4, b"DXT3", pack_bc2_block(alphas4, c0, c1, color_codes)) - w, h, rgba = dds_png.decode_dds(dds) - self.assertEqual((w, h), (4, 4)) - expected = b"".join(bytes((*rgb_pal[cc], a4 * 17)) for a4, cc in zip(alphas4, color_codes)) - self.assertEqual(rgba, expected) - # Explicitly pin 0x0 -> 0, 0x8 -> 136, 0xF -> 255 - self.assertEqual((rgba[3], rgba[7], rgba[11]), (0, 136, 255)) - - def test_bc3_interpolated_alpha_both_modes(self): - c0, c1 = 0x07E0, 0x0000 # pure green at code 0 - color_codes = [0] * 16 - - with self.subTest("a0 > a1 (8-value palette)"): - # 210 / 7 = 30 exact step -> [210, 0, 180, 150, 120, 90, 60, 30] - a_codes = [0, 1, 2, 3, 4, 5, 6, 7, 7, 6, 5, 4, 3, 2, 1, 0] - a_pal = [210, 0, 180, 150, 120, 90, 60, 30] - dds = make_fourcc_dds(4, 4, b"DXT5", pack_bc3_block(210, 0, a_codes, c0, c1, color_codes)) - w, h, rgba = dds_png.decode_dds(dds) - self.assertEqual((w, h), (4, 4)) - expected = b"".join(bytes((0, 255, 0, a_pal[c])) for c in a_codes) - self.assertEqual(rgba, expected) - - with self.subTest("a0 <= a1 (6-value palette + literal 0 and 255)"): - # (200 - 50) / 5 = 30 exact step -> [50, 200, 80, 110, 140, 170, 0, 255] - a_codes = [0, 1, 2, 3, 4, 5, 6, 7, 6, 7, 0, 1, 2, 3, 4, 5] - a_pal = [50, 200, 80, 110, 140, 170, 0, 255] - dds = make_fourcc_dds(4, 4, b"DXT5", pack_bc3_block(50, 200, a_codes, c0, c1, color_codes)) - w, h, rgba = dds_png.decode_dds(dds) - self.assertEqual((w, h), (4, 4)) - expected = b"".join(bytes((0, 255, 0, a_pal[c])) for c in a_codes) - self.assertEqual(rgba, expected) - self.assertEqual(rgba[6 * 4 + 3], 0) - self.assertEqual(rgba[7 * 4 + 3], 255) - - def test_bc4_single_channel_grayscale(self): - codes = [0, 1, 2, 3, 4, 5, 6, 7, 0, 1, 2, 3, 4, 5, 6, 7] - pal = [210, 0, 180, 150, 120, 90, 60, 30] - block = pack_bc4_block(210, 0, codes) - expected = b"".join(bytes((pal[c], pal[c], pal[c], 255)) for c in codes) - - for label, dds in [ - ("DX10 BC4_UNORM", make_dx10_dds(4, 4, 80, block, compressed=True)), - ("Legacy ATI1", make_fourcc_dds(4, 4, b"ATI1", block)), - ]: - with self.subTest(label): - w, h, rgba = dds_png.decode_dds(dds) - self.assertEqual((w, h), (4, 4)) - self.assertEqual(rgba, expected) - - def test_bc5_normal_map_z_reconstruction(self): - # Pixels 0..14: r=128, g=128 -> flat tangent normal, reconstructed z >= 254. - # Pixel 15: r=255, g=128 -> steep normal (nx=1, ny~0), reconstructed z < 200. - r_codes = [0] * 15 + [1] - g_codes = [0] * 16 - block = pack_bc5_block(128, 255, r_codes, 128, 128, g_codes) - - for label, dds in [ - ("DX10 BC5_UNORM", make_dx10_dds(4, 4, 83, block, compressed=True)), - ("Legacy ATI2", make_fourcc_dds(4, 4, b"ATI2", block)), - ]: - with self.subTest(label): - w, h, rgba = dds_png.decode_dds(dds) - self.assertEqual((w, h), (4, 4)) - for i in range(15): - r, g, b, a = rgba[i * 4:i * 4 + 4] - self.assertEqual((r, g, a), (128, 128, 255)) - self.assertGreaterEqual(b, 254) - r15, g15, b15, a15 = rgba[15 * 4:16 * 4] - self.assertEqual((r15, g15, a15), (255, 128, 255)) - self.assertLess(b15, 200) - - def test_downscale_rgba_4x4_to_2x2_exact(self): - # 4 quadrants whose 2x2 channel sums are exact multiples of 4. - grid = [ - (0, 40, 80, 200), (4, 44, 84, 204), (100, 0, 200, 252), (100, 0, 200, 252), - (8, 48, 88, 208), (12, 52, 92, 212), (200, 40, 100, 252), (200, 40, 100, 252), - (10, 20, 30, 40), (30, 40, 50, 60), (255, 255, 255, 255), (255, 255, 255, 255), - (50, 60, 70, 80), (70, 80, 90, 100), (255, 255, 255, 255), (255, 255, 255, 255), - ] - rgba4 = b"".join(bytes(p) for p in grid) - w, h, out = dds_png.downscale_rgba(4, 4, rgba4, 2) - self.assertEqual((w, h), (2, 2)) - expected = bytes([ - 6, 46, 86, 206, - 150, 20, 150, 252, - 47, 57, 67, 70, # colours weighted by alpha (dds_png, 62804d0d): sum(c*a) / sum(a) - 255, 255, 255, 255, - ]) - self.assertEqual(out, expected) - - # No-op when max_size == 0 - self.assertEqual(dds_png.downscale_rgba(4, 4, rgba4, 0), (4, 4, rgba4)) - - def test_encode_png_and_dds_to_png_roundtrip_with_independent_validator(self): - pixels = bytes([ - 255, 0, 0, 255, - 0, 255, 0, 128, - 0, 0, 255, 64, - 12, 34, 56, 0, - 200, 150, 100, 255, - 10, 20, 30, 240, - ]) - png = dds_png.encode_png(3, 2, pixels) - self.assertEqual(parse_and_validate_png(png), (3, 2, pixels)) - - # dds_to_png_bytes + dds_file_to_png_bytes + max_size downscale - rgba4 = bytes(i % 256 for i in range(4 * 4 * 4)) - dds = make_bgra8_dds(4, 4, rgba4) - png_full = dds_png.dds_to_png_bytes(dds, max_size=0) - self.assertEqual(parse_and_validate_png(png_full), (4, 4, rgba4)) - - png_small = dds_png.dds_to_png_bytes(dds, max_size=2) - ws, hs, _ = parse_and_validate_png(png_small) - self.assertEqual((ws, hs), (2, 2)) - - with tempfile.TemporaryDirectory() as tmp: - dds_path = os.path.join(tmp, "sample.dds") - with open(dds_path, "wb") as f: - f.write(dds) - png_from_file = dds_png.dds_file_to_png_bytes(dds_path, max_size=0) - self.assertEqual(parse_and_validate_png(png_from_file), (4, 4, rgba4)) - - def test_invalid_dds_raises_dds_error(self): - with self.subTest("invalid magic"): - with self.assertRaises(dds_png.DdsError): - dds_png.decode_dds(b"NOPE" + b"\x00" * 124) - - with self.subTest("truncated header"): - with self.assertRaises(dds_png.DdsError): - dds_png.decode_dds(b"DDS " + b"\x00" * 40) - - with self.subTest("truncated uncompressed payload"): - good = make_bgra8_dds(4, 4, bytes(4 * 4 * 4)) - with self.assertRaises(dds_png.DdsError): - dds_png.decode_dds(good[:-10]) - - with self.subTest("truncated BC1 payload"): - good_bc1 = make_fourcc_dds(4, 4, b"DXT1", pack_bc1_block(0xF800, 0x001F, [0] * 16)) - with self.assertRaises(dds_png.DdsError): - dds_png.decode_dds(good_bc1[:-3]) - - with self.subTest("unsupported DXGI format"): - bad_dxgi = make_dx10_dds(4, 4, 9999, bytes(64), compressed=False) - with self.assertRaises(dds_png.DdsError): - dds_png.decode_dds(bad_dxgi) - - def test_bc4_and_bc5_snorm_signed_decoding(self): - # r0 = -127 (0x81), r1 = +127 (0x7F) -> s0 <= s1 mode: - # codes [0, 1, 2, 3, 4, 5, 6, 7] -> [0, 255, 51, 102, 153, 204, 0, 255] - codes = [0, 1, 2, 3, 4, 5, 6, 7] * 2 - expected_vals = [0, 255, 51, 102, 153, 204, 0, 255] * 2 - block4 = pack_bc4_block(0x81, 0x7F, codes) - expected_bc4 = b"".join(bytes((v, v, v, 255)) for v in expected_vals) - - for label, dds in [ - ("DX10 BC4_SNORM (81)", make_dx10_dds(4, 4, 81, block4, compressed=True)), - ("Legacy BC4S", make_fourcc_dds(4, 4, b"BC4S", block4)), - ]: - with self.subTest(label): - hdr = dds_png.parse_dds_header(dds) - self.assertEqual(hdr["format"], "BC4_SNORM") - w, h, rgba = dds_png.decode_dds(dds) - self.assertEqual((w, h), (4, 4)) - self.assertEqual(rgba, expected_bc4) - - # -128 (0x80) clamps to -127 (-1.0 -> 0); s0=0, s1=-128 -> s0 > s1 mode - block4_clamp = pack_bc4_block(0, 0x80, [0, 1] + [0] * 14) - _, _, rgba_clamp = dds_png.decode_dds(make_dx10_dds(4, 4, 81, block4_clamp, compressed=True)) - self.assertEqual(rgba_clamp[0], 128) # 0.0 -> 128 - self.assertEqual(rgba_clamp[4], 0) # -128 clamped to -127 -> 0 - - # BC5_SNORM: signed (0, 0) -> flat normal (128, 128, 255, 255); (+127, 0) -> steep normal (255, 128, <200, 255) - r_codes = [0] * 15 + [1] - g_codes = [0] * 16 - block5 = pack_bc5_block(0, 0x7F, r_codes, 0, 0, g_codes) - for label, dds in [ - ("DX10 BC5_SNORM (84)", make_dx10_dds(4, 4, 84, block5, compressed=True)), - ("Legacy BC5S", make_fourcc_dds(4, 4, b"BC5S", block5)), - ]: - with self.subTest(label): - hdr = dds_png.parse_dds_header(dds) - self.assertEqual(hdr["format"], "BC5_SNORM") - w, h, rgba = dds_png.decode_dds(dds) - self.assertEqual((w, h), (4, 4)) - r0, g0, b0, a0 = rgba[0:4] - self.assertEqual((r0, g0, a0), (128, 128, 255)) - self.assertGreaterEqual(b0, 254) - r15, g15, b15, a15 = rgba[15 * 4:16 * 4] - self.assertEqual((r15, g15, a15), (255, 128, 255)) - self.assertLess(b15, 200) - - def test_legacy_rgb_without_alphapixels_forces_opaque_alpha(self): - # DDPF_RGB (0x40) WITHOUT DDPF_ALPHAPIXELS (0x1), even with stray non-zero dwABitMask, - # must ignore alpha bits and force alpha = 255. - raw = bytearray(make_bgra8_dds(2, 1, bytes([10, 20, 30, 0, 40, 50, 60, 12]))) - struct.pack_into(" (170, 0, 85), NOT transparent black). - c0, c1 = 0x001F, 0xF800 - self.assertLess(c0, c1) - color_codes = [0, 1, 2, 3] * 4 - rgb_pal = [(0, 0, 255), (255, 0, 0), (85, 0, 170), (170, 0, 85)] - - bc2 = make_fourcc_dds(4, 4, b"DXT3", pack_bc2_block([0xF] * 16, c0, c1, color_codes)) - _, _, rgba2 = dds_png.decode_dds(bc2) - self.assertEqual(rgba2, b"".join(bytes((*rgb_pal[c], 255)) for c in color_codes)) - - bc3 = make_fourcc_dds(4, 4, b"DXT5", pack_bc3_block(255, 255, [0] * 16, c0, c1, color_codes)) - _, _, rgba3 = dds_png.decode_dds(bc3) - self.assertEqual(rgba3, b"".join(bytes((*rgb_pal[c], 255)) for c in color_codes)) - - def test_downscale_rgba_odd_and_1px_dimensions(self): - for (w, h, max_s, exp_w, exp_h) in [ - (3, 3, 2, 1, 1), - (1, 5, 2, 1, 2), - (5, 1, 2, 2, 1), - (1, 1, 1, 1, 1), - (4, 4, 1, 1, 1), - ]: - with self.subTest(size=(w, h), max_size=max_s): - buf = bytes([80, 120, 160, 255] * (w * h)) - nw, nh, out = dds_png.downscale_rgba(w, h, buf, max_s) - self.assertEqual((nw, nh), (exp_w, exp_h)) - self.assertEqual(len(out), exp_w * exp_h * 4) - self.assertEqual(out, bytes([80, 120, 160, 255] * (exp_w * exp_h))) - - -# --------------------------------------------------------------------------- -# 2. tools/glb_writer.py tests -# --------------------------------------------------------------------------- - -class GlbWriterTest(unittest.TestCase): - def test_negative_obj_scale_preserves_front_faces_and_normals(self): - vertices = "v 0 0 0\nv 1 0 0\nv 0 1 0\nvn 0 0 1\n" - for face in ("f 1 2 3", "f 1//1 2//1 3//1"): - with self.subTest(face=face): - prim, = glb_writer.parse_obj(vertices + face, is_path=False, up_axis="y", scale=-2) - corners = [prim["positions"][index] for index in prim["indices"]] - self.assertEqual(corners, [(0, 0, 0), (0, -2, 0), (-2, 0, 0)]) - self.assertEqual(prim["normals"], [(0, 0, -1)] * 3) - - def test_parse_obj_quads_negative_indices_normals_uv_flip_zup_and_groups(self): - # Group 0: quad in XY plane (Z-up) using positive indices, no vn -> auto unit normals. - # Group 1: single triangle containing (1, 2, 3) using negative indices. - obj = "\n".join([ - "g mesh_0", - "v 0 0 0", - "v 2 0 0", - "v 2 2 0", - "v 0 2 0", - "vt 0.0 0.2", - "vt 1.0 0.2", - "vt 1.0 0.8", - "vt 0.0 0.8", - "f 1/1 2/2 3/3 4/4", - "g mesh_1", - "v 1 2 3", - "v 3 2 3", - "v 1 4 3", - "vt 0.25 0.25", - "vt 0.75 0.25", - "vt 0.25 0.75", - "f -3/-3 -2/-2 -1/-1", - "", - ]) - prims = glb_writer.parse_obj(obj, is_path=False, up_axis="z", offset=(0, 0, 0), scale=1.0) - self.assertEqual(len(prims), 2) - self.assertEqual(prims[0]["group_index"], 0) - self.assertEqual(prims[1]["group_index"], 1) - - # Quad fan-triangulated -> 2 tris = 6 indices - self.assertEqual(len(prims[0]["indices"]), 6) - - # Auto-computed unit normals for missing vn - self.assertEqual(len(prims[0]["normals"]), len(prims[0]["positions"])) - for nx, ny, nz in prims[0]["normals"]: - self.assertAlmostEqual(math.sqrt(nx * nx + ny * ny + nz * nz), 1.0, places=5) - - # UV V-flip: vt (u, v) -> (u, 1 - v) - uv0_rounded = {(round(u, 4), round(v, 4)) for u, v in prims[0]["uvs"]} - self.assertEqual(uv0_rounded, {(0.0, 0.8), (1.0, 0.8), (1.0, 0.2), (0.0, 0.2)}) - - # Z-up -> Y-up transform: (1, 2, 3) -> (1, 3, -2) - pos1_rounded = {(round(x, 4), round(y, 4), round(z, 4)) for x, y, z in prims[1]["positions"]} - self.assertEqual(pos1_rounded, {(1.0, 3.0, -2.0), (3.0, 3.0, -2.0), (1.0, 3.0, -4.0)}) - - # Negative indices resolved -> 1 tri = 3 indices - self.assertEqual(len(prims[1]["indices"]), 3) - - # compute_bounds matches exact transformed extents across both groups - bounds = glb_writer.compute_bounds(prims) - self.assertIsNotNone(bounds) - for got, exp in zip(bounds, [0.0, 0.0, -4.0, 3.0, 3.0, 0.0]): - self.assertAlmostEqual(got, exp, places=5) - - # Also verify is_path=True with offset and scale - with tempfile.TemporaryDirectory() as tmp: - obj_path = os.path.join(tmp, "mesh.obj") - with open(obj_path, "w", encoding="utf-8") as f: - f.write("v 1 2 3\nv 2 2 3\nv 1 3 3\nf 1 2 3\n") - p_file = glb_writer.parse_obj(obj_path, is_path=True, up_axis="z", offset=(10.0, 20.0, 30.0), scale=2.0) - self.assertEqual(len(p_file), 1) - pts = {(round(x, 4), round(y, 4), round(z, 4)) for x, y, z in p_file[0]["positions"]} - # (1,2,3) Z-up -> (1,3,-2) * 2 + (10,20,30) = (12, 26, 26) - self.assertIn((12.0, 26.0, 26.0), pts) - b = glb_writer.compute_bounds(p_file) - self.assertAlmostEqual(b[3] - b[0], 2.0, places=5) - - def test_textured_glb_dedup_alignment_bounds_and_png_roundtrip(self): - obj = "\n".join([ - "g mesh_0", - "usemtl mat_a", - "v 0 0 0", - "v 2 0 0", - "v 0 0 4", - "vt 0 0", - "vt 1 0", - "vt 0 1", - "f 1/1 2/2 3/3", - "g mesh_1", - "usemtl mat_b", - "v 5 0 0", - "v 7 0 0", - "v 5 0 4", - "vt 0 0", - "vt 1 0", - "vt 0 1", - "f 4/4 5/5 6/6", - "", - ]) - prims = glb_writer.parse_obj(obj, is_path=False, up_axis="z") - self.assertEqual([p["material"] for p in prims], ["mat_a", "mat_b"]) - - png_bytes = dds_png.encode_png(2, 2, bytes([ - 255, 0, 0, 255, 0, 255, 0, 255, - 0, 0, 255, 255, 255, 255, 0, 255, - ])) - materials = { - "mat_a": {"name": "mat_a", "png_bytes": png_bytes}, - "mat_b": {"name": "mat_b", "png_bytes": png_bytes}, - } - - glb_data = glb_writer.build_glb(prims, materials=materials) - gltf, bin_data = parse_and_validate_glb(glb_data) - - # Deduplication: two primitives/materials sharing identical png_bytes -> 1 image & 1 texture - self.assertEqual(len(gltf["images"]), 1) - self.assertEqual(len(gltf["textures"]), 1) - self.assertEqual(len(gltf["samplers"]), 1) - self.assertEqual(gltf["images"][0]["mimeType"], "image/png") - - # Image bufferView MUST NOT have "target" and MUST be 4-byte aligned - img_bv = gltf["bufferViews"][gltf["images"][0]["bufferView"]] - self.assertNotIn("target", img_bv) - self.assertEqual(img_bv.get("byteOffset", 0) % 4, 0) - - # Exact round-trip of embedded PNG bytes from BIN chunk - off = img_bv.get("byteOffset", 0) - embedded_png = bin_data[off:off + img_bv["byteLength"]] - self.assertEqual(embedded_png, png_bytes) - self.assertEqual(parse_and_validate_png(embedded_png)[0:2], (2, 2)) - - # Both materials point to the single deduplicated texture index 0 - self.assertEqual(len(gltf["materials"]), 2) - for mat in gltf["materials"]: - self.assertEqual(mat["pbrMetallicRoughness"]["baseColorTexture"]["index"], 0) - - # Check UNSIGNED_SHORT (5123) indices and exact POSITION min/max on every primitive - mesh_prims = [p for m in gltf["meshes"] for p in m["primitives"]] - self.assertEqual(len(mesh_prims), 2) - for mp in mesh_prims: - idx_acc = gltf["accessors"][mp["indices"]] - self.assertEqual(idx_acc["componentType"], 5123) - pos_acc = gltf["accessors"][mp["attributes"]["POSITION"]] - pts = read_accessor_floats(gltf, bin_data, mp["attributes"]["POSITION"]) - exp_min = [min(p[k] for p in pts) for k in range(3)] - exp_max = [max(p[k] for p in pts) for k in range(3)] - for k in range(3): - self.assertAlmostEqual(pos_acc["min"][k], exp_min[k], places=5) - self.assertAlmostEqual(pos_acc["max"][k], exp_max[k], places=5) - - # write_glb + read_glb_summary roundtrip - with tempfile.TemporaryDirectory() as tmp: - out_path = os.path.join(tmp, "out.glb") - stats = glb_writer.write_glb(out_path, prims, materials=materials) - self.assertEqual(stats["primitives"], 2) - self.assertEqual(stats["textures"], 1) - self.assertEqual(stats["triangles"], 2) - with open(out_path, "rb") as f: - disk_data = f.read() - self.assertEqual(disk_data, glb_data) - summary = glb_writer.read_glb_summary(disk_data) - self.assertEqual(summary["version"], 2) - self.assertEqual(summary["total_bytes"], len(disk_data)) - self.assertEqual(len(summary["json"]["images"]), 1) - - def test_untextured_glb_has_no_images_and_valid_clay_material(self): - prims = glb_writer.parse_obj("v 0 0 0\nv 1 0 0\nv 0 1 0\nf 1 2 3\n", is_path=False) - glb_data = glb_writer.build_glb(prims, materials=None) - gltf, _ = parse_and_validate_glb(glb_data) - self.assertNotIn("images", gltf) - self.assertNotIn("textures", gltf) - self.assertNotIn("samplers", gltf) - self.assertEqual(len(gltf["materials"]), 1) - pbr = gltf["materials"][0]["pbrMetallicRoughness"] - self.assertEqual(len(pbr["baseColorFactor"]), 4) - self.assertNotIn("baseColorTexture", pbr) - - def test_large_primitive_65536_vertices_uses_unsigned_int_indices(self): - # 65536 unique vertex positions referenced by 21846 triangles -> 65536 vertices in one primitive. - lines = [f"v {i & 255} {(i >> 8) & 255} 0" for i in range(65536)] - lines.append("vt 0 0") - lines.append("vn 0 0 1") - for k in range(0, 65535, 3): - lines.append(f"f {k + 1}/1/1 {k + 2}/1/1 {k + 3}/1/1") - lines.append("f 65534/1/1 65535/1/1 65536/1/1") - obj = "\n".join(lines) + "\n" - - prims = glb_writer.parse_obj(obj, is_path=False, up_axis="z") - self.assertEqual(len(prims), 1) - glb_data = glb_writer.build_glb(prims) - gltf, bin_data = parse_and_validate_glb(glb_data) - mp = gltf["meshes"][0]["primitives"][0] - pos_acc = gltf["accessors"][mp["attributes"]["POSITION"]] - idx_acc = gltf["accessors"][mp["indices"]] - self.assertEqual(pos_acc["count"], 65536) - self.assertEqual(idx_acc["componentType"], 5125) # UNSIGNED_INT - indices = read_accessor_indices(gltf, bin_data, mp["indices"]) - self.assertEqual(max(indices), 65535) - - def test_empty_primitives_and_corrupt_glb_raise_glb_error(self): - with self.assertRaises(glb_writer.GlbError): - glb_writer.build_glb([]) - - for label, bad in [ - ("empty", b""), - ("short", b"glTF\x02\x00\x00\x00"), - ("bad magic", b"NOPE" + struct.pack(" max vertex index is 65534 (< 0xFFFF restart index), so UNSIGNED_SHORT (5123) is valid. - positions = [(float(i & 255), float((i >> 8) & 255), 0.0) for i in range(65535)] - normals = [(0.0, 1.0, 0.0)] * 65535 - indices = list(range(65535)) # 21845 triangles, divisible by 3 - glb_data = glb_writer.build_glb([{"positions": positions, "normals": normals, "uvs": [], "indices": indices}]) - gltf, bin_data = parse_and_validate_glb(glb_data) - mp = gltf["meshes"][0]["primitives"][0] - self.assertEqual(gltf["accessors"][mp["attributes"]["POSITION"]]["count"], 65535) - self.assertEqual(gltf["accessors"][mp["indices"]]["componentType"], 5123) - decoded_idx = read_accessor_indices(gltf, bin_data, mp["indices"]) - self.assertEqual(max(decoded_idx), 65534) - - -# --------------------------------------------------------------------------- -# 3. tools/world_build.py tests -# --------------------------------------------------------------------------- - -def _cube_obj(cx: float, cy: float, cz: float, half: float = 1.0, groups: int = 1) -> str: - """Synthetic Z-up cube(s) OBJ with UVs and normals.""" - lines = ["vn 0 0 1", "vt 0 0", "vt 1 0", "vt 1 1", "vt 0 1"] - v_base = 1 - for g in range(groups): - gx = cx + g * (half * 2.5) - x0, x1 = gx - half, gx + half - y0, y1 = cy - half, cy + half - z0, z1 = cz - half, cz + half - lines.append(f"g mesh_{g}") - verts = [ - (x0, y0, z0), (x1, y0, z0), (x1, y1, z0), (x0, y1, z0), - (x0, y0, z1), (x1, y0, z1), (x1, y1, z1), (x0, y1, z1), - ] - for vx, vy, vz in verts: - lines.append(f"v {vx} {vy} {vz}") - faces = [ - (0, 1, 2, 3), (4, 5, 6, 7), - (0, 1, 5, 4), (2, 3, 7, 6), - (1, 2, 6, 5), (3, 0, 4, 7), - ] - for a, b, c, d in faces: - lines.append( - f"f {v_base + a}/1/1 {v_base + b}/2/1 {v_base + c}/3/1 {v_base + d}/4/1" - ) - v_base += 8 - return "\n".join(lines) + "\n" - - -def _write_synthetic_assets(assets_dir: str, *, origin_overlap: bool = False) -> dict: - """Create a 100% synthetic tree matching rpf9dump's layout.""" - models_dir = os.path.join(assets_dir, "arch_a", "models") - os.makedirs(models_dir, exist_ok=True) - ttpf_dir = os.path.join(assets_dir, "ttpf", "pool_a") - os.makedirs(ttpf_dir, exist_ok=True) - - # 1) Embedded BGRA8 DDS for model 1 - wall_rgba = bytes([220, 40, 40, 255] * 16) - wall_dds = make_bgra8_dds(4, 4, wall_rgba) - wall_tex_dir = os.path.join(models_dir, "model_one_tex") - os.makedirs(wall_tex_dir, exist_ok=True) - wall_dds_path = os.path.join(wall_tex_dir, "000_wall.dds") - with open(wall_dds_path, "wb") as f: - f.write(wall_dds) - - # 2) Valid BC1 DDS in TTPF pool for model 2 material 0 - brick_bc1 = make_dx10_dds(4, 4, 71, pack_bc1_block(0xF800, 0x001F, [0, 1, 2, 3] * 4), compressed=True) - brick_dds_path = os.path.join(ttpf_dir, "000000_brick_diff.dds") - with open(brick_dds_path, "wb") as f: - f.write(brick_bc1) - - # 3) Corrupt DDS in TTPF pool for model 2 material 1 (must trigger graceful fallback) - corrupt_dds_path = os.path.join(ttpf_dir, "000001_corrupt.dds") - with open(corrupt_dds_path, "wb") as f: - f.write(b"NOT_A_VALID_DDS_PAYLOAD") - - ttpf_manifest = { - "src": "synthetic_pool_a.ttpf", - "Version": 1, - "Count": 2, - "Metadata": {}, - "Textures": [ - { - "Index": 0, - "Name": "brick_diff", - "Id": 1, - "AssetKey": "AABBCCDDEEFF0011", - "Width": 4, - "Height": 4, - "DxgiFormat": 71, - "Mips": 1, - "SourceMips": 1, - "BaseMipLevel": 0, - "Limitation": None, - "File": "000000_brick_diff.dds", - }, - { - "Index": 1, - "Name": "corrupt_tex", - "Id": 2, - "AssetKey": "AABBCCDDEEFF0022", - "Width": 4, - "Height": 4, - "DxgiFormat": 71, - "Mips": 1, - "SourceMips": 1, - "BaseMipLevel": 0, - "Limitation": None, - "File": "000001_corrupt.dds", - }, - ], - } - with open(os.path.join(ttpf_dir, "manifest.json"), "w", encoding="utf-8") as f: - json.dump(ttpf_manifest, f, indent=2) - - if origin_overlap: - # Both models sit at origin with negative Z (-1..+1) -> overlapping in spatial, min_y < 0 until lifted. - m1_center = (0.0, 0.0, 0.0) - m2_center = (0.0, 0.0, 0.0) - m1_groups, m2_groups = 1, 1 - else: - # Distant world coords -> 2 distinct spatial chunks (x=10 vs x=350, >256m apart). - m1_center = (10.0, 10.0, 1.0) - m2_center = (350.0, 10.0, 1.0) - m1_groups, m2_groups = 1, 2 - - with open(os.path.join(models_dir, "model_one.obj"), "w", encoding="utf-8") as f: - f.write(_cube_obj(*m1_center, half=1.0, groups=m1_groups)) - - with open(os.path.join(models_dir, "model_two.obj"), "w", encoding="utf-8") as f: - f.write(_cube_obj(*m2_center, half=1.0, groups=m2_groups)) - - m2_shaders = [0] if m2_groups == 1 else [0, 1] - m2_materials = [ - { - "ShaderIndex": 0, - "Shader": "11111111", - "Preset": "22222222", - "RenderBucket": 0, - "Textures": [ - { - "Param": "2B5170FD", - "TextureIndex": -1, - "Name": "55667788", - "Id64": "AABBCCDDEEFF0011", - "Tag": "00000000", - } - ], - }, - ] - if m2_groups == 2: - m2_materials.append({ - "ShaderIndex": 1, - "Shader": "33333333", - "Preset": "44444444", - "RenderBucket": 0, - "Textures": [ - { - "Param": "2B5170FD", - "TextureIndex": -1, - "Name": "99AABBCC", - "Id64": "AABBCCDDEEFF0022", - "Tag": "00000000", - } - ], - }) - - models_manifest = { - "src": "synthetic_arch_a.rpf", - "Count": 2, - "Items": [ - { - "Offset": 4096, - "File": "model_one.obj", - "Name": "model_one", - "Meshes": m1_groups, - "Verts": 8 * m1_groups, - "Tris": 12 * m1_groups, - "IsFragment": False, - "HasBoneBindings": False, - "Min": [m1_center[0] - 1.0, m1_center[1] - 1.0, m1_center[2] - 1.0], - "Max": [m1_center[0] + 1.0, m1_center[1] + 1.0, m1_center[2] + 1.0], - "MeshShaders": [0], - "Embedded": [ - { - "Index": 0, - "Name": "wall", - "Width": 4, - "Height": 4, - "Format": "BGRA8", - "Hash": "11223344", - "Key": None, - } - ], - "Materials": [ - { - "ShaderIndex": 0, - "Shader": "00000001", - "Preset": "00000002", - "RenderBucket": 0, - "Textures": [ - { - "Param": "2B5170FD", - "TextureIndex": 0, - "Name": "11223344", - "Id64": "0000000000000000", - "Tag": "00000000", - } - ], - } - ], - }, - { - "Offset": 8192, - "File": "model_two.obj", - "Name": "model_two", - "Meshes": m2_groups, - "Verts": 8 * m2_groups, - "Tris": 12 * m2_groups, - "IsFragment": False, - "HasBoneBindings": False, - "Min": [m2_center[0] - 1.0, m2_center[1] - 1.0, m2_center[2] - 1.0], - "Max": [m2_center[0] + 1.0 + (2.5 if m2_groups == 2 else 0.0), m2_center[1] + 1.0, m2_center[2] + 1.0], - "MeshShaders": m2_shaders, - "Embedded": [], - "Materials": m2_materials, - }, - ], - } - models_manifest_path = os.path.join(models_dir, "manifest.json") - with open(models_manifest_path, "w", encoding="utf-8") as f: - json.dump(models_manifest, f, indent=2) - - return { - "models_dir": models_dir, - "models_manifest_path": models_manifest_path, - "models_manifest": models_manifest, - "wall_dds_path": wall_dds_path, - "brick_dds_path": brick_dds_path, - "corrupt_dds_path": corrupt_dds_path, - } - - -def _chunk_disk_path(world_dir: str, chunk_url: str) -> str: - rel = chunk_url[len("world/"):] if chunk_url.startswith("world/") else chunk_url.lstrip("/") - return os.path.join(world_dir, *rel.split("/")) - - -NORMAL_RGBA = (128, 128, 255, 255) -ALBEDO_RGBA = (240, 40, 20, 255) -PLAIN_RGBA = (20, 70, 140, 255) -ALBEDO_PARAM = "C8E8C282" -NORMAL_PARAM = "C6F46E79" -TTPF_ALBEDO_KEY = "AABBCCDDEEFF0011" - - -def _uniform_bgra_dds(rgba, size=4): - return make_bgra8_dds(size, size, bytes(rgba) * (size * size)) - - -def _half_float_dds(dxgi, texel_codes, size=4, pad=4): - """A DX10 R16_FLOAT (54) or R16G16B16A16_FLOAT (10) DDS of one repeated texel, rows padded by pad bytes.""" - texel = struct.pack(f"<{len(texel_codes)}H", *texel_codes) - row = texel * size - data = bytearray(make_dx10_dds(size, size, dxgi, (row + bytes(pad)) * size)) - struct.pack_into(" (128, 64, 255, 255); 0.75 -> 191 in red only. - cases = (("normal-first", "000_normal.dds", _half_float_dds(10, (0x3800, 0x3400, 0x3C00, 0x3C00)), - (128, 64, 255, 255)), - ("unannotated", "002_plain.dds", _half_float_dds(54, (0x3A00,)), (191, 0, 0, 255))) - for case, name, data, expected in cases: - with self.subTest(case=case), tempfile.TemporaryDirectory() as tmp: - assets_dir = os.path.join(tmp, "assets") - out_dir = os.path.join(tmp, "world") - _write_param_fixture(assets_dir, PARAM_CASES[case]) - with open(os.path.join(assets_dir, "models", "tri_tex", name), "wb") as f: - f.write(data) - proc = self._run_cli(assets_dir, out_dir) - self.assertEqual(proc.returncode, 0, proc.stderr) - stats, _, pixel = self._read_world(out_dir) - self.assertEqual(stats["textures_embedded"], 1) - self.assertEqual(pixel, expected) - - def test_selected_param_picks_albedo_regardless_of_order(self): - for case in ("normal-first", "albedo-first"): - for value in (ALBEDO_PARAM, "0xc8e8c282"): - with self.subTest(case=case, value=value): - self._assert_textured(ALBEDO_RGBA, PARAM_CASES[case], "--base-color-param", value) - - def test_selected_param_without_resolvable_match_is_clay(self): - cases = ( - ("no-albedo", PARAM_CASES["no-albedo"], True), - ("unannotated", PARAM_CASES["unannotated"], True), - ("unresolved-match", [_param_ref(ALBEDO_PARAM, 7), _param_ref(NORMAL_PARAM, 0)], True), - ("no-materials", [], False), - ) - for case, refs, materials in cases: - with self.subTest(case=case): - self._assert_clay(refs, "--base-color-param", ALBEDO_PARAM, materials=materials) - - def test_first_resolvable_match_wins(self): - refs = [_param_ref(ALBEDO_PARAM, 7), _param_ref(NORMAL_PARAM, 0), _param_ref(ALBEDO_PARAM, 1)] - self._assert_textured(ALBEDO_RGBA, refs, "--base-color-param", ALBEDO_PARAM) - - def test_selected_param_resolves_external_ttpf(self): - refs = [_param_ref(NORMAL_PARAM, 0), _param_ref(ALBEDO_PARAM, -1, TTPF_ALBEDO_KEY)] - self._assert_textured(NORMAL_RGBA, refs, ttpf=True) - self._assert_textured(ALBEDO_RGBA, refs, "--base-color-param", ALBEDO_PARAM, ttpf=True) - - def test_no_textures_with_param_is_clay(self): - stats, gltf, pixel = self._export( - PARAM_CASES["normal-first"], "--no-textures", "--base-color-param", ALBEDO_PARAM - ) - self.assertIsNone(pixel) - self.assertEqual(stats["textures_embedded"], 0) - self.assertEqual(gltf.get("images", []), []) - - def test_api_matches_cli(self): - with tempfile.TemporaryDirectory() as tmp: - assets_dir = os.path.join(tmp, "assets") - out_dir = os.path.join(tmp, "world") - _write_param_fixture(assets_dir, PARAM_CASES["normal-first"]) - world_build.build_world(assets_dir, out_dir, base_color_param="0xC8E8C282") - stats, _, pixel = self._read_world(out_dir) - self.assertEqual(stats["textures_embedded"], 1) - self.assertEqual(pixel, ALBEDO_RGBA) - - def test_invalid_param_rejected_before_output(self): - for value in ("C8E8C28", "C8E8C2822", "0xZZZZZZZZ", ""): - with self.subTest(value=value), tempfile.TemporaryDirectory() as tmp: - assets_dir = os.path.join(tmp, "assets") - out_dir = os.path.join(tmp, "world") - _write_param_fixture(assets_dir, PARAM_CASES["normal-first"]) - proc = self._run_cli(assets_dir, out_dir, "--base-color-param", value) - self.assertEqual(proc.returncode, 2, proc.stderr) - self.assertIn("--base-color-param", proc.stderr) - with self.assertRaises(ValueError): - world_build.build_world(assets_dir, out_dir, base_color_param=value) - self.assertFalse(os.path.exists(out_dir)) - - -class WorldBuildTest(unittest.TestCase): - TOOL = os.path.join(TOOLS, "world_build.py") - - def _run_cli(self, assets_dir: str, out_dir: str, *extra_args: str) -> subprocess.CompletedProcess: - cmd = [sys.executable, "-I", self.TOOL, assets_dir, "--out", out_dir, *extra_args] - return subprocess.run(cmd, capture_output=True, text=True, errors="replace") - - @staticmethod - def _output_snapshot(directory): - snapshot = {} - for root, dirs, files in os.walk(directory): - for name in dirs: - snapshot[os.path.relpath(os.path.join(root, name), directory)] = None - for name in files: - path = os.path.join(root, name) - with open(path, "rb") as f: - snapshot[os.path.relpath(path, directory)] = f.read() - return snapshot - - def test_compute_spawn_keeps_large_chunks_within_viewer_load_radius(self): - load_radius = 1400.0 # viewer/index.html LOAD_R - floor = [{"bounds": [x, -2.0, -7000.0, x + 4000.0, 0.0, -3000.0]} for x in (1000.0, 5000.0, 9000.0)] - tower = [{"bounds": [-500.0, 0.0, -500.0, -490.0, 3000.0, -490.0]}] - for chunks, b in ((floor, floor[1]["bounds"]), (tower, tower[0]["bounds"])): - with self.subTest(bounds=b): - spawn = world_build._compute_spawn(chunks) - self.assertEqual(spawn[0], 0.5 * (b[0] + b[3])) - nearest = [min(max(p, lo), hi) for p, lo, hi in zip(spawn, b[:3], b[3:])] - self.assertLess(math.dist(spawn, nearest), load_radius) - small = [{"bounds": [10.0, 0.0, 20.0, 110.0, 5.0, 120.0]}] - self.assertEqual(world_build._compute_spawn(small), [60.0, 30.0, 180.0]) - self.assertEqual(world_build._compute_spawn([]), [0.0, 20.0, 40.0]) - - def test_unusable_input_preserves_output_and_reports_failure(self): - cases = ("unrelated_directory", "corrupt_manifest", "invalid_schema", "empty_manifest", - "missing_objs", "empty_geometry", "invalid_file_fields") - for existing_output in (False, True): - for case in cases: - with self.subTest(existing_output=existing_output, case=case), tempfile.TemporaryDirectory() as tmp: - assets = os.path.join(tmp, "assets") - output = os.path.join(tmp, "world") - info = _write_synthetic_assets(assets, origin_overlap=False) - if existing_output: - world_build.build_world(assets, output, textures=False) - before = self._output_snapshot(output) - source = assets - if case == "unrelated_directory": - source = os.path.join(tmp, "wrong_input") - os.mkdir(source) - elif case in ("corrupt_manifest", "invalid_schema", "empty_manifest", "invalid_file_fields"): - content = { - "corrupt_manifest": "{broken", - "invalid_schema": '{"Items": null}', - "empty_manifest": '{"Items": []}', - "invalid_file_fields": '{"Items": [{"File": ""}, {"File": 123}]}', - }[case] - with open(info["models_manifest_path"], "w", encoding="utf-8") as f: - f.write(content) - else: - for root, _, files in os.walk(assets): - for name in files: - if name.endswith(".obj"): - path = os.path.join(root, name) - if case == "missing_objs": - os.remove(path) - else: - with open(path, "w", encoding="utf-8") as f: - f.write("# Synthetic OBJ without faces\nv 0 0 0\n") - diagnostic = "No readable model manifests" if case in ( - "unrelated_directory", "corrupt_manifest", "invalid_schema") else "No usable models" - with self.assertRaisesRegex(ValueError, diagnostic): - world_build.build_world(source, output, textures=False) - self.assertEqual(self._output_snapshot(output), before) - result = self._run_cli(source, output, "--no-textures") - self.assertEqual(result.returncode, 1, result.stdout + result.stderr) - self.assertIn("ERROR:", result.stderr) - self.assertIn(diagnostic, result.stderr) - self.assertIn(source, result.stderr) - self.assertNotIn("world built:", result.stdout) - self.assertEqual(self._output_snapshot(output), before) - if not existing_output: - self.assertFalse(os.path.exists(output)) - - def test_malformed_optional_material_arrays_match_missing_fields(self): - cases = ( - ("MeshShaders", 7), - ("MeshShaders", "0"), - ("MeshShaders", {"0": 0}), - ("Embedded", True), - ("Materials", 7), - ("Materials", {"0": {}}), - ("Textures", 1.5), - ) - with tempfile.TemporaryDirectory() as tmp: - assets, output = os.path.join(tmp, "assets"), os.path.join(tmp, "world") - path = _write_synthetic_assets(assets)["models_manifest_path"] - with open(path, encoding="utf-8") as f: - original = f.read() - - def build(manifest): - with open(path, "w", encoding="utf-8") as f: - json.dump(manifest, f) - result = world_build.build_world(assets, output) - self.assertEqual(result["stats"]["models"], 2) - return self._output_snapshot(output) - - for field, malformed in cases: - with self.subTest(field=field, malformed=malformed): - manifest = json.loads(original) - record = manifest["Items"][0] - if field == "Textures": - record = record["Materials"][0] - del record[field] - expected = build(manifest) - record[field] = malformed - self.assertEqual(build(manifest), expected) - - def test_limit_zero_explicitly_replaces_world_with_empty_output(self): - with tempfile.TemporaryDirectory() as tmp: - assets, output = os.path.join(tmp, "assets"), os.path.join(tmp, "world") - _write_synthetic_assets(assets, origin_overlap=False) - for cli in (False, True): - world_build.build_world(assets, output, textures=False) - empty_source = os.path.join(tmp, "empty_input") - os.makedirs(empty_source, exist_ok=True) - if cli: - result = self._run_cli(empty_source, output, "--no-textures", "--limit", "0") - self.assertEqual(result.returncode, 0, result.stdout + result.stderr) - else: - world_build.build_world(empty_source, output, textures=False, limit=0) - with open(os.path.join(output, "world.json"), encoding="utf-8") as f: - document = json.load(f) - self.assertEqual(document["stats"]["models"], 0) - self.assertEqual(document["chunks"], []) - self.assertEqual(os.listdir(os.path.join(output, "chunks")), []) - - def test_limit_does_not_fall_back_to_unselected_models(self): - with tempfile.TemporaryDirectory() as tmp: - assets, output = os.path.join(tmp, "assets"), os.path.join(tmp, "world") - info = _write_synthetic_assets(assets, origin_overlap=False) - world_build.build_world(assets, output, textures=False) - before = self._output_snapshot(output) - with open(info["models_manifest_path"], encoding="utf-8") as f: - manifest = json.load(f) - manifest["Items"].insert(0, {"File": "missing.obj"}) - with open(info["models_manifest_path"], "w", encoding="utf-8") as f: - json.dump(manifest, f) - with self.assertRaisesRegex(ValueError, "1 selected manifest items"): - world_build.build_world(assets, output, textures=False, limit=1) - self.assertEqual(self._output_snapshot(output), before) - - def test_mixed_input_still_builds_usable_models(self): - with tempfile.TemporaryDirectory() as tmp: - assets, output = os.path.join(tmp, "assets"), os.path.join(tmp, "world") - info = _write_synthetic_assets(assets, origin_overlap=False) - with open(info["models_manifest_path"], encoding="utf-8") as f: - manifest = json.load(f) - manifest["Items"].append({"File": "missing.obj"}) - with open(info["models_manifest_path"], "w", encoding="utf-8") as f: - json.dump(manifest, f) - result = world_build.build_world(assets, output, textures=False, jobs=4) - self.assertEqual(result["stats"]["models"], 2) - self.assertEqual(len(result["chunks"]), 2) - - def test_discover_index_and_resolve_textures(self): - with tempfile.TemporaryDirectory() as tmp: - assets_dir = os.path.join(tmp, "assets") - info = _write_synthetic_assets(assets_dir) - - manifests = world_build.discover_model_manifests(assets_dir) - self.assertEqual(len(manifests), 1) - self.assertEqual( - os.path.normcase(os.path.abspath(manifests[0])), - os.path.normcase(os.path.abspath(info["models_manifest_path"])), - ) - - ttpf_index = world_build.index_ttpf_textures(assets_dir) - self.assertIn("AABBCCDDEEFF0011", ttpf_index) - self.assertEqual( - os.path.normcase(os.path.abspath(ttpf_index["AABBCCDDEEFF0011"])), - os.path.normcase(os.path.abspath(info["brick_dds_path"])), - ) - - item1, item2 = info["models_manifest"]["Items"] - res1 = world_build.resolve_model_textures(info["models_dir"], item1, ttpf_index) - self.assertEqual( - os.path.normcase(os.path.abspath(res1[0])), - os.path.normcase(os.path.abspath(info["wall_dds_path"])), - ) - - res2 = world_build.resolve_model_textures(info["models_dir"], item2, ttpf_index) - self.assertEqual( - os.path.normcase(os.path.abspath(res2[0])), - os.path.normcase(os.path.abspath(info["brick_dds_path"])), - ) - self.assertEqual( - os.path.normcase(os.path.abspath(res2[1])), - os.path.normcase(os.path.abspath(info["corrupt_dds_path"])), - ) - - def test_spatial_build_two_chunks_and_corrupt_texture_fallback(self): - with tempfile.TemporaryDirectory() as tmp: - assets_dir = os.path.join(tmp, "assets") - out_dir = os.path.join(tmp, "world") - _write_synthetic_assets(assets_dir, origin_overlap=False) - - world_doc = world_build.build_world(assets_dir, out_dir) - stats = world_doc["stats"] - self.assertEqual(stats["models"], 2) - self.assertEqual(stats["chunks"], 2) - self.assertEqual(stats["textures_embedded"], 2) - self.assertGreaterEqual(stats["textures_skipped"], 1) - - world_json_path = os.path.join(out_dir, "world.json") - self.assertTrue(os.path.isfile(world_json_path)) - with open(world_json_path, encoding="utf-8") as f: - world = json.load(f) - - self.assertIn("spawn", world) - self.assertEqual(len(world["spawn"]), 3) - self.assertTrue(all(isinstance(v, (int, float)) and math.isfinite(v) for v in world["spawn"])) - - chunks = world["chunks"] - self.assertEqual(len(chunks), 2) - total_images = 0 - for c in chunks: - self.assertIn("id", c) - self.assertRegex(c["url"], r"^world/chunks/c_.*\.glb$") - bounds = c["bounds"] - self.assertEqual(len(bounds), 6) - for k in range(3): - self.assertLessEqual(bounds[k], bounds[k + 3]) - - glb_path = _chunk_disk_path(out_dir, c["url"]) - self.assertTrue(os.path.isfile(glb_path), f"missing chunk file {glb_path}") - with open(glb_path, "rb") as f: - glb_bytes = f.read() - summary = glb_writer.read_glb_summary(glb_bytes) - self.assertEqual(summary["version"], 2) - gltf, bin_data = parse_and_validate_glb(glb_bytes) - for img in gltf.get("images", []): - bv = gltf["bufferViews"][img["bufferView"]] - off = bv.get("byteOffset", 0) - parse_and_validate_png(bin_data[off:off + bv["byteLength"]]) - total_images += len(gltf.get("images", [])) - - # Model 1 (BGRA8 wall) + Model 2 mat 0 (BC1 brick) embedded; corrupt mat 1 skipped gracefully. - self.assertEqual(total_images, 2) - - def test_grid_layout_non_overlapping_and_min_y_non_negative(self): - with tempfile.TemporaryDirectory() as tmp: - assets_dir = os.path.join(tmp, "assets") - out_dir = os.path.join(tmp, "world_grid") - _write_synthetic_assets(assets_dir, origin_overlap=True) - - p = self._run_cli(assets_dir, out_dir, "--grid-layout") - self.assertEqual(p.returncode, 0, p.stdout + p.stderr) - - with open(os.path.join(out_dir, "world.json"), encoding="utf-8") as f: - world = json.load(f) - self.assertEqual(world["layout"], "grid") - self.assertGreaterEqual(len(world["chunks"]), 1) - - prim_boxes = [] - for c in world["chunks"]: - self.assertGreaterEqual(c["bounds"][1], -1e-4) - glb_path = _chunk_disk_path(out_dir, c["url"]) - with open(glb_path, "rb") as f: - glb_bytes = f.read() - glb_writer.read_glb_summary(glb_bytes) - gltf, bin_data = parse_and_validate_glb(glb_bytes) - for mesh in gltf.get("meshes", []): - for mp in mesh.get("primitives", []): - pts = read_accessor_floats(gltf, bin_data, mp["attributes"]["POSITION"]) - mn = [min(pt[k] for pt in pts) for k in range(3)] - mx = [max(pt[k] for pt in pts) for k in range(3)] - self.assertGreaterEqual(mn[1], -1e-4, f"primitive min_y < 0: {mn}") - prim_boxes.append((mn, mx)) - - self.assertEqual(len(prim_boxes), 2) - eps = 1e-3 - for i in range(len(prim_boxes)): - for j in range(i + 1, len(prim_boxes)): - a_min, a_max = prim_boxes[i] - b_min, b_max = prim_boxes[j] - separated = any( - a_max[k] <= b_min[k] + eps or b_max[k] <= a_min[k] + eps - for k in range(3) - ) - self.assertTrue( - separated, - f"grid-layout models overlap: box{i}=({a_min}, {a_max}) vs box{j}=({b_min}, {b_max})", - ) - - def test_no_textures_flag_produces_zero_images(self): - with tempfile.TemporaryDirectory() as tmp: - assets_dir = os.path.join(tmp, "assets") - out_dir = os.path.join(tmp, "world_notex") - _write_synthetic_assets(assets_dir, origin_overlap=False) - - p = self._run_cli(assets_dir, out_dir, "--no-textures") - self.assertEqual(p.returncode, 0, p.stdout + p.stderr) - - with open(os.path.join(out_dir, "world.json"), encoding="utf-8") as f: - world = json.load(f) - self.assertEqual(len(world["chunks"]), 2) - for c in world["chunks"]: - glb_path = _chunk_disk_path(out_dir, c["url"]) - with open(glb_path, "rb") as f: - glb_bytes = f.read() - gltf, _ = parse_and_validate_glb(glb_bytes) - self.assertEqual(len(gltf.get("images", [])), 0) - self.assertEqual(len(gltf.get("textures", [])), 0) - - def test_limit_flag_caps_processed_models(self): - with tempfile.TemporaryDirectory() as tmp: - assets_dir = os.path.join(tmp, "assets") - out_dir = os.path.join(tmp, "world_limit") - _write_synthetic_assets(assets_dir, origin_overlap=False) - - p = self._run_cli(assets_dir, out_dir, "--limit", "1") - self.assertEqual(p.returncode, 0, p.stdout + p.stderr) - - with open(os.path.join(out_dir, "world.json"), encoding="utf-8") as f: - world = json.load(f) - self.assertEqual(world["stats"]["models"], 1) - self.assertEqual(len(world["chunks"]), 1) - glb_path = _chunk_disk_path(out_dir, world["chunks"][0]["url"]) - with open(glb_path, "rb") as f: - glb_writer.read_glb_summary(f.read()) - - def test_textures_manifest_excluded_and_zero_sentinel_keys_ignored(self): - with tempfile.TemporaryDirectory() as tmp: - assets_dir = os.path.join(tmp, "assets") - info = _write_synthetic_assets(assets_dir) - - # Add an rpf9dump textures/manifest.json that must NOT be picked up as a model manifest. - tex_dir = os.path.join(assets_dir, "arch_a", "textures") - os.makedirs(tex_dir, exist_ok=True) - with open(os.path.join(tex_dir, "manifest.json"), "w", encoding="utf-8") as f: - json.dump({"Items": [{"Dir": "txd_0", "Textures": []}]}, f) - - # Add a TTPF entry with all-zero sentinel AssetKey that must NOT be indexed. - zero_dds = os.path.join(assets_dir, "ttpf", "pool_a", "zero.dds") - with open(zero_dds, "wb") as f: - f.write(make_bgra8_dds(2, 2, bytes([255, 255, 255, 255] * 4))) - ttpf_manifest_path = os.path.join(assets_dir, "ttpf", "pool_a", "manifest.json") - with open(ttpf_manifest_path, encoding="utf-8") as f: - doc = json.load(f) - doc["Textures"].append({"AssetKey": "0000000000000000", "File": "zero.dds"}) - with open(ttpf_manifest_path, "w", encoding="utf-8") as f: - json.dump(doc, f) - - manifests = world_build.discover_model_manifests(assets_dir) - self.assertEqual(len(manifests), 1) - self.assertEqual( - os.path.normcase(os.path.abspath(manifests[0])), - os.path.normcase(os.path.abspath(info["models_manifest_path"])), - ) - - ttpf_index = world_build.index_ttpf_textures(assets_dir) - self.assertNotIn("0000000000000000", ttpf_index) - - def test_stale_chunks_cleaned_on_rebuild_parallel_jobs_and_missing_assets_error(self): - with tempfile.TemporaryDirectory() as tmp: - assets_dir = os.path.join(tmp, "assets") - out_dir = os.path.join(tmp, "world") - _write_synthetic_assets(assets_dir, origin_overlap=False) - - # Build 2 chunks with --jobs 4 (parallel workers + shared cache). - res_full = world_build.build_world(assets_dir, out_dir, jobs=4) - self.assertEqual(len(res_full["chunks"]), 2) - chunks_dir = os.path.join(out_dir, "chunks") - before_files = sorted(os.listdir(chunks_dir)) - self.assertEqual(len(before_files), 2) - - # Include a partial generated chunk and unrelated files in the same directory. - obsolete = ["c_-3_12.glb", "c_0_-7.glb.tmp"] - unrelated = ["my-model.glb", "my-model.glb.tmp", "c_01_0.glb", "c_-0_0.glb"] - for name in obsolete + unrelated: - with open(os.path.join(chunks_dir, name), "wb") as f: - f.write(b"fixture") - res_limited = world_build.build_world(assets_dir, out_dir, limit=1, jobs=4) - self.assertEqual(len(res_limited["chunks"]), 1) - after_files = sorted(os.listdir(chunks_dir)) - expected = [f"{res_limited['chunks'][0]['id']}.glb"] + unrelated - self.assertEqual(after_files, sorted(expected)) - - # Non-existent assets_dir raises FileNotFoundError in API and returns exit 1 in CLI. - missing = os.path.join(tmp, "does_not_exist") - with self.assertRaises(FileNotFoundError): - world_build.build_world(missing, out_dir) - p = self._run_cli(missing, out_dir) - self.assertNotEqual(p.returncode, 0) - - -class WorldBuildStagingTest(unittest.TestCase): - """A rebuild that fails or is interrupted must leave the previous world.json and its chunks as they were.""" - - _snapshot = staticmethod(WorldBuildTest._output_snapshot) - - @staticmethod - def _failing_write_glb(exc: BaseException, fail_on_call: int = 2): - """Wrap the real write_glb so that call number `fail_on_call` raises `exc` instead of writing.""" - real = glb_writer.write_glb - lock = threading.Lock() - calls = [0] - - def write_glb(path, *args, **kwargs): - with lock: - calls[0] += 1 - n = calls[0] - if n == fail_on_call: - raise exc - return real(path, *args, **kwargs) - - return write_glb - - def _previous_world(self, tmp: str) -> tuple[str, str, dict]: - # The previous world is untextured; the failing rebuild embeds textures, so every chunk it - # would publish differs from the one on disk and an early overwrite shows up in the snapshot. - assets, output = os.path.join(tmp, "assets"), os.path.join(tmp, "world") - _write_synthetic_assets(assets, origin_overlap=False) - world_build.build_world(assets, output, textures=False) - before = self._snapshot(output) - self.assertEqual(sum(1 for k in before if k.startswith("chunks" + os.sep)), 2) - return assets, output, before - - def test_successful_build_publishes_every_chunk_and_world_json(self): - for jobs in (1, 4): - with self.subTest(jobs=jobs), tempfile.TemporaryDirectory() as tmp: - assets, output = os.path.join(tmp, "assets"), os.path.join(tmp, "world") - _write_synthetic_assets(assets, origin_overlap=False) - result = world_build.build_world(assets, output, jobs=jobs) - with open(os.path.join(output, "world.json"), encoding="utf-8") as f: - document = json.load(f) - self.assertEqual(document, result) - self.assertEqual(len(document["chunks"]), 2) - for chunk in document["chunks"]: - with open(_chunk_disk_path(output, chunk["url"]), "rb") as f: - parse_and_validate_glb(f.read()) - self.assertEqual(sorted(os.listdir(output)), ["chunks", "world.json"]) - self.assertEqual(sorted(os.listdir(os.path.join(output, "chunks"))), - sorted(f"{c['id']}.glb" for c in document["chunks"])) - - def test_failed_chunk_write_leaves_existing_world_untouched(self): - failures = (glb_writer.GlbError("synthetic broken asset"), OSError("synthetic write error"), - KeyboardInterrupt()) - for exc in failures: - for jobs in (1, 4): - with self.subTest(exc=type(exc).__name__, jobs=jobs), tempfile.TemporaryDirectory() as tmp: - assets, output, before = self._previous_world(tmp) - with unittest.mock.patch.object(glb_writer, "write_glb", self._failing_write_glb(exc)): - with self.assertRaises(type(exc)): - world_build.build_world(assets, output, jobs=jobs) - self.assertEqual(self._snapshot(output), before) - - def test_failed_first_build_leaves_no_output_directory(self): - with tempfile.TemporaryDirectory() as tmp: - assets, output = os.path.join(tmp, "assets"), os.path.join(tmp, "world") - _write_synthetic_assets(assets, origin_overlap=False) - with unittest.mock.patch.object(glb_writer, "write_glb", self._failing_write_glb(OSError("disk full"))): - with self.assertRaises(OSError): - world_build.build_world(assets, output) - self.assertFalse(os.path.exists(output)) - - def test_corrupt_staged_chunk_is_rejected_before_publishing(self): - real = glb_writer.write_glb - - def truncating_write_glb(path, *args, **kwargs): - info = real(path, *args, **kwargs) - with open(path, "r+b") as f: - f.truncate(16) - return info - - with tempfile.TemporaryDirectory() as tmp: - assets, output, before = self._previous_world(tmp) - with unittest.mock.patch.object(glb_writer, "write_glb", truncating_write_glb): - with self.assertRaises(ValueError): - world_build.build_world(assets, output) - self.assertEqual(self._snapshot(output), before) - - def test_world_json_write_failure_restores_previous_chunks(self): - with tempfile.TemporaryDirectory() as tmp: - assets, output, before = self._previous_world(tmp) - world_path = os.path.join(output, "world.json") - replace = glb_writer._replace - - def fail_manifest_replace(source, destination): - if destination == world_path: - raise OSError("synthetic world.json rename error") - replace(source, destination) - - with unittest.mock.patch.object(glb_writer, "_replace", fail_manifest_replace): - with self.assertRaisesRegex(OSError, "world.json rename"): - world_build.build_world(assets, output) - self.assertEqual(self._snapshot(output), before) - - def _kill_during_publication(self, assets, output, point): - child = """ -import os -import sys -tools, assets, output, point = sys.argv[1:] -sys.path.insert(0, tools) -import glb_writer -import world_build - -replace = glb_writer._replace -chunks = os.path.join(output, 'chunks') -def kill_after_rename(src, dst): - adds_chunk = os.path.dirname(dst) == chunks and not os.path.lexists(dst) - replace(src, dst) - if ((point == 'backup' and os.path.basename(os.path.dirname(dst)) == 'previous') - or (point == 'new' and adds_chunk) - or (point == 'manifest' and dst == os.path.join(output, 'world.json'))): - os._exit(77) - -glb_writer._replace = kill_after_rename -world_build.build_world(assets, output) -""" - run = subprocess.run([sys.executable, "-I", "-c", child, TOOLS, assets, output, point], - capture_output=True, text=True, timeout=30) - self.assertEqual(run.returncode, 77, run.stderr) - - def _rerun_with_missing_assets(self, tmp, output): - # Recovery has to happen even if the new export cannot start. - run = subprocess.run([sys.executable, "-I", WorldBuildTest.TOOL, - os.path.join(tmp, "missing"), "--out", output], - capture_output=True, text=True, timeout=30) - self.assertEqual(run.returncode, 1, run.stderr) - self.assertIn("assets path does not exist:", run.stderr) - - def test_killed_after_backing_up_live_chunk_restores_previous_world(self): - with tempfile.TemporaryDirectory() as tmp: - assets, output, before = self._previous_world(tmp) - self._kill_during_publication(assets, output, "backup") - self.assertEqual(len(os.listdir(os.path.join(output, "chunks"))), 1) - self._rerun_with_missing_assets(tmp, output) - self.assertEqual(self._snapshot(output), before) - - @unittest.skipUnless(os.name == "nt", "Windows refuses to replace a read-only destination") - def test_killed_after_installing_readonly_chunk_restores_previous_world(self): - with tempfile.TemporaryDirectory() as tmp: - assets, output, before = self._previous_world(tmp) - chunk_dir = os.path.join(output, "chunks") - chunks = [os.path.join(chunk_dir, name) for name in os.listdir(chunk_dir)] - for chunk in chunks: - os.chmod(chunk, stat.S_IREAD) - - self._kill_during_publication(assets, output, "new") - self.assertNotEqual(self._snapshot(output), before) - self._rerun_with_missing_assets(tmp, output) - - self.assertEqual(self._snapshot(output), before) - for chunk in chunks: - self.assertFalse(os.stat(chunk).st_mode & stat.S_IWRITE) - - def test_killed_after_installing_new_chunk_removes_it_on_recovery(self): - with tempfile.TemporaryDirectory() as tmp: - assets, output, _ = self._previous_world(tmp) - world_build.build_world(assets, output, limit=0) - before = self._snapshot(output) - self._kill_during_publication(assets, output, "new") - self.assertEqual(len(os.listdir(os.path.join(output, "chunks"))), 1) - self._rerun_with_missing_assets(tmp, output) - self.assertEqual(self._snapshot(output), before) - - def test_killed_after_manifest_commit_keeps_the_new_world(self): - with tempfile.TemporaryDirectory() as tmp: - assets, output, before = self._previous_world(tmp) - reference = os.path.join(tmp, "reference") - world_build.build_world(assets, reference) - expected = self._snapshot(reference) - self.assertNotEqual(expected, before) - self._kill_during_publication(assets, output, "manifest") - self._rerun_with_missing_assets(tmp, output) - self.assertEqual(self._snapshot(output), expected) - - def test_recovery_that_cannot_restore_a_chunk_can_be_retried(self): - with tempfile.TemporaryDirectory() as tmp: - assets, output, before = self._previous_world(tmp) - self._kill_during_publication(assets, output, "backup") - interrupted = self._snapshot(output) - with unittest.mock.patch.object(glb_writer, "_replace", side_effect=PermissionError("file in use")): - with self.assertRaisesRegex(OSError, "could not recover the previous world"): - world_build.build_world(assets, output) - self.assertEqual(self._snapshot(output), interrupted) - self._rerun_with_missing_assets(tmp, output) - self.assertEqual(self._snapshot(output), before) - - def test_staging_left_by_a_killed_build_is_removed_on_the_next_build(self): - with tempfile.TemporaryDirectory() as tmp: - assets, output = os.path.join(tmp, "assets"), os.path.join(tmp, "world") - _write_synthetic_assets(assets, origin_overlap=False) - leftover = os.path.join(output, world_build.CHUNK_STAGING_PREFIX + "killed") - os.makedirs(leftover) - with open(os.path.join(leftover, "c_0_0.glb"), "wb") as f: - f.write(b"partial") - world_build.build_world(assets, output) - self.assertEqual(sorted(os.listdir(output)), ["chunks", "world.json"]) - - def test_stale_cleanup_preserves_staging_with_unrestored_previous_chunks(self): - prefix = world_build.CHUNK_STAGING_PREFIX - with tempfile.TemporaryDirectory() as tmp: - empty = os.path.join(tmp, prefix + "empty") - os.makedirs(empty) - incomplete = os.path.join(tmp, prefix + "incomplete") - os.makedirs(os.path.join(incomplete, "previous")) # an empty previous/ holds nothing to recover - with open(os.path.join(incomplete, "c_1_0.glb"), "wb") as f: - f.write(b"partial") - recovery = os.path.join(tmp, prefix + "recovery") - os.makedirs(os.path.join(recovery, "previous")) - with open(os.path.join(recovery, "previous", "c_0_0.glb"), "wb") as f: - f.write(b"previous chunk") - unrelated = os.path.join(tmp, "notes") - os.makedirs(unrelated) - - world_build._remove_stale_staging(tmp) - - self.assertEqual(sorted(os.listdir(tmp)), sorted([prefix + "recovery", "notes"])) - with open(os.path.join(recovery, "previous", "c_0_0.glb"), "rb") as f: - self.assertEqual(f.read(), b"previous chunk") - - -# --------------------------------------------------------------------------- -# 4. viewer/serve.py tests -# --------------------------------------------------------------------------- - -class ViewerServeTest(unittest.TestCase): - def test_canceled_chunk_download_does_not_report_a_server_error(self): - errors = [] - - class Server(HTTPServer): - def handle_error(self, request, client_address): - errors.append(sys.exc_info()[1]) - - class QuietHandler(viewer_serve.Handler): - def log_message(self, format, *args): - pass - - with tempfile.TemporaryDirectory() as world_dir: - # Large enough that the client can close before the server finishes sending it. - with open(os.path.join(world_dir, "chunk.glb"), "wb") as f: - f.truncate(16 * 1024 * 1024) - QuietHandler.world = world_dir - with Server(("127.0.0.1", 0), functools.partial(QuietHandler, directory=VIEWER)) as srv: - srv.timeout = 5 - thread = threading.Thread(target=srv.handle_request, daemon=True) - thread.start() - try: - with socket.create_connection(srv.server_address, timeout=5) as conn: - # Force a TCP reset when the partially consumed response is closed. - linger = struct.pack("HH" if os.name == "nt" else "ii", 1, 0) - conn.setsockopt(socket.SOL_SOCKET, socket.SO_LINGER, linger) - conn.sendall(b"GET /world/chunk.glb HTTP/1.1\r\nHost: localhost\r\n\r\n") - with conn.makefile("rb") as response: - self.assertTrue(response.readline().startswith(b"HTTP/1.0 200")) - finally: - thread.join(timeout=5) - self.assertFalse(thread.is_alive()) - self.assertEqual(errors, []) - - def test_safe_world_path_allows_valid_paths(self): - with tempfile.TemporaryDirectory() as tmp: - world_dir = os.path.join(tmp, "world") - chunks_dir = os.path.join(world_dir, "chunks") - os.makedirs(chunks_dir, exist_ok=True) - expected_json = os.path.realpath(os.path.join(world_dir, "world.json")) - expected_glb = os.path.realpath(os.path.join(chunks_dir, "c_0_0.glb")) - - got_json = viewer_serve.safe_world_path(world_dir, "/world/world.json") - self.assertIsNotNone(got_json) - self.assertEqual(os.path.normcase(os.path.realpath(got_json)), os.path.normcase(expected_json)) - - got_glb = viewer_serve.safe_world_path(world_dir, "/world/chunks/c_0_0.glb") - self.assertIsNotNone(got_glb) - self.assertEqual(os.path.normcase(os.path.realpath(got_glb)), os.path.normcase(expected_glb)) - - got_query = viewer_serve.safe_world_path(world_dir, "/world/world.json?cache=1") - self.assertIsNotNone(got_query) - self.assertEqual(os.path.normcase(os.path.realpath(got_query)), os.path.normcase(expected_json)) - - def test_safe_world_path_blocks_traversal_and_drive_escapes(self): - with tempfile.TemporaryDirectory() as tmp: - world_dir = os.path.join(tmp, "world") - os.makedirs(os.path.join(world_dir, "chunks"), exist_ok=True) - attacks = [ - "/world/../secret.txt", - "/world/%2e%2e/secret.txt", - "/world/..\\secret.txt", - "/world/C:/Windows/win.ini", - "/world/chunks/../../outside.txt", - "/world/%2e%2e%5csecret.txt", - "/world/chunks/..%2f..%2foutside.txt", - "/world/", - "/world/chunks/", - "/world/chunks", - "/world/a\x00b", - "/world/NUL", - "/world/chunks/CON", - "/world/COM1.txt", - "/world/LPT9", - "/world/world.json:ads", - "/notworld/world.json", - ] - for req_path in attacks: - with self.subTest(req_path=req_path): - self.assertIsNone(viewer_serve.safe_world_path(world_dir, req_path)) - - def test_handler_http_serves_world_and_forbids_escapes_even_with_denied_file(self): - with tempfile.TemporaryDirectory() as tmp: - world_dir = os.path.join(tmp, "world") - chunks_dir = os.path.join(world_dir, "chunks") - os.makedirs(chunks_dir, exist_ok=True) - with open(os.path.join(world_dir, "world.json"), "w", encoding="utf-8") as f: - json.dump({"spawn": [0, 10, 20], "chunks": []}, f) - with open(os.path.join(chunks_dir, "c_0_0.glb"), "wb") as f: - f.write(b"glTF\x02\x00\x00\x00\x14\x00\x00\x00\x00\x00\x00\x00JSON") - # Decoy file literally named __denied__ MUST NOT be leaked on blocked requests. - with open(os.path.join(world_dir, "__denied__"), "w", encoding="utf-8") as f: - f.write("DECOY_DENIED_PAYLOAD") - with open(os.path.join(tmp, "secret.txt"), "w", encoding="utf-8") as f: - f.write("OUTSIDE_SECRET") - - # Optional symlink escape test (skipped silently if OS denies symlink creation). - escape_link = os.path.join(world_dir, "escape.txt") - has_symlink = False - try: - os.symlink(os.path.join(tmp, "secret.txt"), escape_link) - has_symlink = True - except OSError: - pass - - class QuietHandler(viewer_serve.Handler): - def log_message(self, format, *args): - pass - - QuietHandler.world = os.path.abspath(world_dir) - srv = ThreadingHTTPServer( - ("127.0.0.1", 0), - functools.partial(QuietHandler, directory=VIEWER), - ) - port = srv.server_address[1] - thread = threading.Thread(target=srv.serve_forever, daemon=True) - thread.start() - try: - conn = http.client.HTTPConnection("127.0.0.1", port, timeout=5) - try: - conn.request("GET", "/world/world.json") - r = conn.getresponse() - body = r.read() - self.assertEqual(r.status, 200) - self.assertEqual(json.loads(body.decode("utf-8"))["spawn"], [0, 10, 20]) - - conn.request("GET", "/world/chunks/c_0_0.glb") - r = conn.getresponse() - body = r.read() - self.assertEqual(r.status, 200) - self.assertEqual(r.getheader("Content-Type"), "model/gltf-binary") - self.assertTrue(body.startswith(b"glTF")) - - blocked = [ - "/world/../secret.txt", - "/world/%2e%2e/secret.txt", - "/world/NUL", - "/world/chunks/", - "/world/", - ] - if has_symlink: - blocked.append("/world/escape.txt") - for bad_path in blocked: - with self.subTest(bad_path=bad_path): - conn.request("GET", bad_path) - r = conn.getresponse() - body = r.read() - self.assertEqual(r.status, 403) - self.assertNotIn(b"DECOY_DENIED_PAYLOAD", body) - self.assertNotIn(b"OUTSIDE_SECRET", body) - finally: - conn.close() - finally: - srv.shutdown() - srv.server_close() - - def test_host_allowed_accepts_loopback_names_only(self): - for host in ("127.0.0.1", "127.0.0.1:8765", "localhost", "LOCALHOST:8765", "localhost.:8765", - "[::1]", "[::1]:8765", None): - with self.subTest(host=host): - self.assertTrue(viewer_serve.host_allowed(host)) - for host in ("evil.example", "evil.example:8765", "127.0.0.1.evil.example", "localhost.evil.example:8765", - "192.168.1.5:8765", "0.0.0.0:8765", "[::2]:8765", ""): - with self.subTest(host=host): - self.assertFalse(viewer_serve.host_allowed(host)) - - def test_handler_refuses_a_foreign_host_header(self): - # DNS rebinding: a web page points its own domain at 127.0.0.1, so the request arrives here with that domain. - with tempfile.TemporaryDirectory() as tmp: - world_dir = os.path.join(tmp, "world") - os.makedirs(world_dir) - with open(os.path.join(world_dir, "world.json"), "w", encoding="utf-8") as f: - f.write('{"spawn": "WORLD_PAYLOAD"}') - - class QuietHandler(viewer_serve.Handler): - def log_message(self, format, *args): - pass - - QuietHandler.world = os.path.abspath(world_dir) - srv = ThreadingHTTPServer(("127.0.0.1", 0), functools.partial(QuietHandler, directory=VIEWER)) - port = srv.server_address[1] - threading.Thread(target=srv.serve_forever, daemon=True).start() - try: - for host, status in ((f"rebind.example:{port}", 403), ("evil.example", 403), - (f"localhost:{port}", 200), (f"127.0.0.1:{port}", 200)): - for path in ("/world/world.json", "/index.html"): - with self.subTest(host=host, path=path): - conn = http.client.HTTPConnection("127.0.0.1", port, timeout=5) - try: - conn.request("GET", path, headers={"Host": host}) - r = conn.getresponse() - body = r.read() - finally: - conn.close() - self.assertEqual(r.status, status) - if status == 403: - self.assertNotIn(b"WORLD_PAYLOAD", body) - finally: - srv.shutdown() - srv.server_close() - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/test_world_build_output_lock.py b/tests/test_world_build_output_lock.py deleted file mode 100644 index 7b461a2f7..000000000 --- a/tests/test_world_build_output_lock.py +++ /dev/null @@ -1,157 +0,0 @@ -"""Concurrent-output regression tests for tools/world_build.py (no game data). - -A world build stages chunks in the output directory, publishes them one at a time, -then prunes stale chunks. Two builds on one output must not interleave: the -second one must fail while the first holds the lock, and the next build must -work again after the lock is released. -""" -from contextlib import contextmanager -import os -import subprocess -import sys -import tempfile -import time -import unittest -from unittest import mock - -HERE = os.path.dirname(os.path.abspath(__file__)) -ROOT = os.path.dirname(HERE) -TOOLS = os.path.join(ROOT, "tools") -for path in (TOOLS, HERE): - if path not in sys.path: - sys.path.insert(0, path) - -import test_world_build as twb # noqa: E402 -import world_build as wb # noqa: E402 - -CHILD_HOLD_LOCK = """ -import sys, time -sys.path.insert(0, sys.argv[1]) -import world_build as wb -with wb._exclusive_output(sys.argv[2]): - with open(sys.argv[3], 'w', encoding='ascii') as fh: - fh.write('ready') - time.sleep(30) -""" - - -@contextmanager -def _lock_held_by_child(tmp, out): - """Hold ``_exclusive_output(out)`` in a child process for the body of the ``with``.""" - ready = os.path.join(tmp, "ready") - proc = subprocess.Popen( - [sys.executable, "-I", "-c", CHILD_HOLD_LOCK, TOOLS, out, ready], - stdout=subprocess.PIPE, - stderr=subprocess.PIPE, - text=True, - ) - try: - deadline = time.time() + 10 - while not os.path.isfile(ready): - if proc.poll() is not None: - raise AssertionError("lock holder exited before becoming ready") - if time.time() >= deadline: - raise AssertionError("lock holder never became ready") - time.sleep(0.05) - yield - finally: - proc.terminate() - try: - proc.communicate(timeout=5) - except subprocess.TimeoutExpired: - proc.kill() - proc.communicate(timeout=5) - - -def _short_path(path): - """The 8.3 spelling of an existing ``path``, or None when the volume has none.""" - import ctypes - get_short = ctypes.windll.kernel32.GetShortPathNameW - get_short.argtypes = [ctypes.c_wchar_p, ctypes.c_wchar_p, ctypes.c_uint] - get_short.restype = ctypes.c_uint - buf = ctypes.create_unicode_buffer(1024) - if not get_short(path, buf, len(buf)): - return None - short = buf.value - return None if os.path.normcase(short) == os.path.normcase(path) else short - - -class WorldBuildOutputLockTests(unittest.TestCase): - def test_second_process_refuses_while_first_holds_output(self): - with tempfile.TemporaryDirectory() as tmp: - assets = os.path.join(tmp, "assets") - out = os.path.join(tmp, "world") - twb._write_synthetic_assets(assets, origin_overlap=False) - with _lock_held_by_child(tmp, out): - with self.assertRaisesRegex(RuntimeError, "another world_build is using"): - wb.build_world(assets, out, textures=False) - self.assertFalse(os.path.exists(os.path.join(out, "chunks"))) - - def _assert_other_spelling_refused(self, tmp, parent, other_parent): - # The child locks /World; a build through /World is the same folder - # and must be refused, both before the folder exists (two first runs) and after. - assets = os.path.join(tmp, "assets") - twb._write_synthetic_assets(assets, origin_overlap=False) - out = os.path.join(parent, "World") - other = os.path.join(other_parent, "World") - with _lock_held_by_child(tmp, out): - for state in ("missing", "existing"): - if state == "existing": - os.makedirs(out, exist_ok=True) - self.assertTrue(state == "missing" or os.path.samefile(out, other)) - with self.subTest(output=state): - with self.assertRaisesRegex(RuntimeError, "another world_build is using"): - wb.build_world(assets, other, textures=False) - self.assertFalse(os.path.exists(os.path.join(out, "world.json"))) - self.assertFalse(os.path.exists(os.path.join(out, "chunks"))) - - def test_short_name_spelling_of_a_held_output_is_refused(self): - if os.name != "nt": - self.skipTest("8.3 short names are Windows only") - with tempfile.TemporaryDirectory() as tmp: - parent = os.path.join(tmp, "LongOutputFolderName") - os.makedirs(parent) - short = _short_path(parent) - if short is None: - self.skipTest("8.3 short names are unavailable on this volume") - self._assert_other_spelling_refused(tmp, parent, short) - - def test_linked_parent_spelling_of_a_held_output_is_refused(self): - with tempfile.TemporaryDirectory() as tmp: - parent = os.path.join(tmp, "real") - os.makedirs(parent) - link = os.path.join(tmp, "link") - if os.name == "nt": - import _winapi - _winapi.CreateJunction(parent, link) - else: - try: - os.symlink(parent, link, target_is_directory=True) - except (OSError, NotImplementedError): - self.skipTest("symbolic links are not available here") - try: - self._assert_other_spelling_refused(tmp, parent, link) - finally: - if os.name == "nt": - os.rmdir(link) # removes the junction, not its target - - def test_build_world_holds_the_output_lock_and_releases_it(self): - with tempfile.TemporaryDirectory() as tmp: - assets = os.path.join(tmp, "assets") - out = os.path.join(tmp, "world") - twb._write_synthetic_assets(assets, origin_overlap=False) - calls = [] - - @contextmanager - def fake_lock(path): - calls.append(path) - yield - - with mock.patch.object(wb, "_exclusive_output", fake_lock): - wb.build_world(assets, out, textures=False) - wb.build_world(assets, out, textures=False) - self.assertEqual(calls, [os.path.abspath(out)] * 2) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/test_world_census.py b/tests/test_world_census.py deleted file mode 100644 index d834fadef..000000000 --- a/tests/test_world_census.py +++ /dev/null @@ -1,1049 +0,0 @@ -"""Tests for tools/world_census.py, built from synthetic 0x7a resources (no game data). - - python -I tests/test_world_census.py -""" -import argparse -import contextlib -import hashlib -import importlib.util -import io -import json -import os -import shutil -import struct -import subprocess -import sys -import tempfile -import unittest -import zlib -from pathlib import Path -from unittest import mock - -ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) - - -def load(name, path): - spec = importlib.util.spec_from_file_location(name, path) - module = importlib.util.module_from_spec(spec) - spec.loader.exec_module(module) - return module - - -WC = load("world_census_under_test", os.path.join(ROOT, "tools", "world_census.py")) -TWI = load("world_index_test_builder", os.path.join(ROOT, "tests", "test_world_index.py")) - - -def make_archive(path): - """A small RPF9: normal map, zlib-split map, raw-split map, meta and a duplicate.""" - out = bytearray(0x40) - out[:4] = b"9FPR" - struct.pack_into(" 1000: - raise RuntimeError("shard planning never finished") - return other + int(self) - - for size in (0, -5): - Counted.adds = 0 - with self.subTest(size=size), self.assertRaises(ValueError): - WC._expected_shards(0, 10, Counted(size)) - - def test_cli_rejects_shard_size_and_jobs_below_one(self): - with tempfile.TemporaryDirectory() as tmp: - arc = os.path.join(tmp, "sample.rpf") - make_archive(arc) - out = os.path.join(tmp, "out") - tool = os.path.join(ROOT, "tools", "world_census.py") - for flag, value in (("--shard-size", "0"), ("--shard-size", "-1"), ("--jobs", "0")): - with self.subTest(flag=flag, value=value): - # A subprocess with a timeout, so the old endless loop fails the test instead of hanging it. - p = subprocess.run([sys.executable, "-I", tool, arc, "--out", out, flag, value], - capture_output=True, text=True, timeout=10) - self.assertEqual(p.returncode, 2, p.stderr) - self.assertIn("must be at least 1", p.stderr) - self.assertNotIn("Traceback", p.stderr) - self.assertFalse(os.path.exists(out)) - - def test_jobs_above_the_platform_limit_are_rejected(self): - """--jobs 100 crashed on Windows: ProcessPoolExecutor allows at most 61 workers there.""" - saved = WC.MAX_JOBS - try: - WC.MAX_JOBS = 61 - self.assertEqual(WC.job_count("61"), 61) - for value in ("62", "100"): - with self.subTest(value=value), self.assertRaises(argparse.ArgumentTypeError) as ctx: - WC.job_count(value) - self.assertIn("at most 61", str(ctx.exception)) - WC.MAX_JOBS = None - self.assertEqual(WC.job_count("100"), 100) - finally: - WC.MAX_JOBS = saved - self.assertEqual(WC.MAX_JOBS, 61 if os.name == "nt" else None) - - @unittest.skipUnless(os.name == "nt", "the 61-worker limit is Windows-only") - def test_cli_rejects_jobs_above_61_on_windows(self): - with tempfile.TemporaryDirectory() as tmp: - arc = os.path.join(tmp, "sample.rpf") - make_archive(arc) - tool = os.path.join(ROOT, "tools", "world_census.py") - p = subprocess.run([sys.executable, "-I", tool, arc, "--out", os.path.join(tmp, "out"), "--jobs", "100"], - capture_output=True, text=True, timeout=30) - self.assertEqual(p.returncode, 2, p.stderr) - self.assertIn("must be at most 61", p.stderr) - self.assertNotIn("Traceback", p.stderr) - - -def aligned(*parts): - """Concatenate parts, each starting on a 16-byte boundary (the walker only accepts aligned streams).""" - out = bytearray() - for part in parts: - out.extend(b"\0" * (((len(out) + 15) & ~15) - len(out))) - out.extend(part) - return bytes(out) - - -def with_block(blob, name, size, pointer): - """Add a third block-table entry (the builder leaves 0x220.. free) to a map resource.""" - b = bytearray(blob) - struct.pack_into(" 0x700 - self.assertEqual(WC.required_len(longer), 0x800) - self.assertTrue(WC.needs_more(longer)) - self.assertFalse(WC.needs_more(self.blob)) - - def test_graphics_block_does_not_count(self): - gfx = self.patched("= legacy["end"]]) - rebuilt, new_rows = self.scan(self.arc, "--resume", to_scan=2) - self.assertTrue(rebuilt["census_exact"]) - self.assertEqual(new_rows, rows) - - -def setUpModule(): - # The tools' main() prints its summary JSON; keep it out of the test log (tests that check it redirect again). - quiet = contextlib.redirect_stdout(io.StringIO()) - quiet.__enter__() - unittest.addModuleCleanup(quiet.__exit__, None, None, None) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/test_world_drawable_lookup.py b/tests/test_world_drawable_lookup.py deleted file mode 100644 index 1882917b0..000000000 --- a/tests/test_world_drawable_lookup.py +++ /dev/null @@ -1,73 +0,0 @@ -"""Synthetic coverage of the report join and its ambiguous/missing evidence.""" -from itertools import product -import json -from pathlib import Path -import sys -import tempfile -import unittest - -sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "tools")) -import world_drawable_lookup as lookup -import world_names - - -class DrawableLookupTest(unittest.TestCase): - def test_only_export_candidates_with_consistent_evidence(self): - with tempfile.TemporaryDirectory() as tmp: - root = Path(tmp) - names = ["one", "many", "conflict", "wrong_key", "unaligned", "cached", "missing_key"] - definitions, streams, placements = [], [], [] - for i, name in enumerate(names): - h = world_names.joaat(name) - definitions.append({"name": h, "asset_name": h, "asset_type": 2}) - key = world_names.hash64(name) - placements.append({"archetype": f"{h:x}", "key": f"{key:x}", "position": [0, 0, 0], - "rotation": [0, 0, 0, 1], "lod_level": 6}) - streams.append({"offset": 4096 * i + 16, "names": [name + ".#dr"]}) - streams.append({"offset": 4096 * 8 + 16, "names": ["many.#dr"]}) - definitions.append(dict(definitions[2], asset_type=1)) - placements[3]["key"] = "0" - streams[4]["offset"] += 1 - placements[-1].pop("key") - for file, data in [("defs", {"archetypes": definitions}), - ("names", {"summary": {"archive": "test.rpf"}, "files": streams}), - ("manifest", {"Items": [{"Name": "cached"}]})]: - (root / file).write_text(json.dumps(data), encoding="utf-8", newline="\n") - (root / "entities").write_text("\n".join(map(json.dumps, placements)), encoding="utf-8", newline="\n") - result = lookup.lookup(root / "entities", root / "defs", root / "names", [root / "manifest"]) - self.assertEqual(result["outcomes"], {"candidate": 1, "ambiguous": 1, "unresolved": 3, - "listed_in_manifest": 1, "missing_or_invalid_key": 1}) - self.assertEqual(sorted(r["offsets"] for r in result["candidates"]), [[16], [4112, 32784]]) - - def test_scan_window_matches_exhaustive_intervals(self): - for weights in product((0, 1, 3), repeat=4): - rows = [{"status": "ambiguous", "offsets": [1, 4], "placements": 100}] - for offset, weight in zip((1, 4, 5, 9), weights): - if weight: - for n in (weight, 1): # Two distinct identities at this offset. - rows.append({"status": "candidate", "offsets": [offset], "placements": n}) - report = {"archive": "one.rpf", "candidates": rows} - for budget in range(1, 12): - choices = [] - for start in range(10): - for length in range(1, budget + 1): - hits = [r for r in rows if r["status"] == "candidate" - and start <= r["offsets"][0] < start + length] - if hits: - first = min(r["offsets"][0] for r in hits) - last = max(r["offsets"][0] for r in hits) - choices.append((-sum(r["placements"] for r in hits), last, first, len(hits))) - result = lookup.export_window(report, budget) - if choices: - score, last, first, count = min(choices) - self.assertEqual(result, {"archive": "one.rpf", "start": first, "length": last-first+1, - "predicted_placements": -score, "predicted_identities": count}) - else: - self.assertIsNone(result) - for invalid in (0, -1, 1 << 63): - with self.assertRaises(ValueError): - lookup.export_window(report, invalid) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/test_world_drawable_verify.py b/tests/test_world_drawable_verify.py deleted file mode 100644 index af5882d04..000000000 --- a/tests/test_world_drawable_verify.py +++ /dev/null @@ -1,60 +0,0 @@ -"""Synthetic export windows and keyed model observations.""" -import json -from pathlib import Path -import sys -import tempfile -import unittest - -sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "tools")) -import world_drawable_verify as verifier -import world_names - - -class VerifyTest(unittest.TestCase): - def setUp(self): - tmp = tempfile.TemporaryDirectory() - self.addCleanup(tmp.cleanup) - self.root = Path(tmp.name) - - def write(self, name, data): - path = self.root / name - path.write_text(json.dumps(data), encoding="utf-8", newline="\n") - return path - - def test_join_counts_and_window_edges(self): - candidates = [] - for name, offset in [("one", 10), ("two", 12), ("three", 13), ("four", 14), ("five", 20)]: - candidates.append({"archetype": format(world_names.joaat(name), "x"), - "key": format(world_names.hash64(name), "x"), "offsets": [offset], - "status": "candidate", "placements": 3}) - # A 32-bit match alone cannot confirm the prediction. - candidates[1]["archetype"] = candidates[0]["archetype"] - candidates.append(dict(candidates[0], status="ambiguous", offsets=[10, 15])) - predictions = self.write("lookup", {"archive": "source.rpf", "candidates": candidates}) - export = {"src": "source.rpf", "Scan": {"Start": 10, "Length": 10}, - "Items": [{"Name": "one.#dr", "Offset": 10}, {"Name": "one", "Offset": 12}, - {"Name": "three", "Offset": 18}, {"Name": "", "Offset": 14}]} - first = self.write("first", export) - second = self.write("second", dict(export, Items=export["Items"][:1])) - result = verifier.verify(predictions, [first, second, first]) - self.assertEqual([r["status"] for r in result["rows"]], - ["confirmed", "conflicting_name", "conflicting_offset", "missing_evidence", - "outside_windows"]) - self.assertEqual(result["placements"], {s: 3 for s in result["identities"]}) - self.assertEqual(result["rows"][0]["duplicate_observations"], 1) - self.assertEqual(result["rows"][0]["other_identity_offsets"], [12]) - full = self.write("full", dict(export, Scan={})) - self.assertEqual(verifier.verify(predictions, [full])["identities"]["missing_evidence"], 2) - - def test_reject_unrelated_archive_and_bad_bounds(self): - predictions = self.write("lookup", {"archive": "source.rpf", "candidates": []}) - for source, scan in [("elsewhere/source.rpf", {}), ("source.rpf", {"Start": 0}), - ("source.rpf", {"Start": True, "Length": 5}), - ("source.rpf", {"Start": 0, "Length": 2})]: - manifest = self.write("manifest", {"src": source, "Scan": scan, "Items": [{"Offset": 2}]}) - with self.subTest(source=source, scan=scan), self.assertRaises(ValueError): - verifier.verify(predictions, [manifest]) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/test_world_drawable_verify_archive_aliases.py b/tests/test_world_drawable_verify_archive_aliases.py deleted file mode 100644 index 448732a41..000000000 --- a/tests/test_world_drawable_verify_archive_aliases.py +++ /dev/null @@ -1,96 +0,0 @@ -"""Source-archive identity checks using synthetic reports and placeholder files only.""" -import json -import os -from pathlib import Path -import subprocess -import sys -import tempfile -import unittest -from unittest import mock - -ROOT = Path(__file__).resolve().parents[1] -sys.path.insert(0, str(ROOT / "tools")) -import world_drawable_verify as verifier -import world_names - - -class ArchiveAliasTests(unittest.TestCase): - def setUp(self): - temp = tempfile.TemporaryDirectory() - self.addCleanup(temp.cleanup) - self.root = Path(temp.name) - self.archive = self.root / "source.bin" - self.archive.write_bytes(b"synthetic file identity only") - - def reports(self, predicted_source, exported_source): - name = "synthetic_drawable" - candidate = {"archetype": format(world_names.joaat(name), "x"), - "key": format(world_names.hash64(name), "x"), "offsets": [16], - "status": "candidate", "placements": 4} - predictions = self.root / "predictions.json" - predictions.write_text(json.dumps({"archive": str(predicted_source), "candidates": [candidate]}), - encoding="utf-8", newline="\n") - manifest = self.root / "manifest.json" - manifest.write_text(json.dumps({"src": str(exported_source), "Scan": {}, - "Items": [{"Name": name, "Offset": 16}]}), - encoding="utf-8", newline="\n") - return predictions, manifest - - def hard_link(self): - alias = self.root / "archive-alias.bin" - try: - os.link(self.archive, alias) - except (OSError, NotImplementedError) as error: - self.skipTest(f"hard links unavailable: {error}") - return alias - - def assert_confirmed(self, result): - self.assertEqual(result["identities"], {"confirmed": 1}) - self.assertEqual(result["placements"], {"confirmed": 4}) - self.assertEqual(result["rows"][0]["exact_observations"], 1) - - def test_hard_link_to_source_archive_is_accepted(self): - predictions, manifest = self.reports(self.archive, self.hard_link()) - self.assert_confirmed(verifier.verify(predictions, [manifest])) - - def test_symlink_to_source_archive_is_accepted(self): - alias = self.root / "archive-alias.bin" - try: - alias.symlink_to(self.archive) - except (OSError, NotImplementedError) as error: - self.skipTest(f"symlinks unavailable: {error}") - predictions, manifest = self.reports(self.archive, alias) - self.assert_confirmed(verifier.verify(predictions, [manifest])) - - def test_cli_accepts_source_archive_alias(self): - predictions, manifest = self.reports(self.archive, self.hard_link()) - result = subprocess.run( - [sys.executable, "-I", str(ROOT / "tools" / "world_drawable_verify.py"), - str(predictions), str(manifest)], capture_output=True, text=True, encoding="utf-8") - self.assertEqual(result.returncode, 0, result.stderr) - self.assertEqual(result.stderr, "") - self.assert_confirmed(json.loads(result.stdout)) - - def test_distinct_archive_with_identical_bytes_is_rejected(self): - other = self.root / "different.bin" - other.write_bytes(self.archive.read_bytes()) - self.assertFalse(os.path.samefile(self.archive, other)) - predictions, manifest = self.reports(self.archive, other) - with self.assertRaisesRegex(ValueError, "different source archive"): - verifier.verify(predictions, [manifest]) - - def test_offline_reports_keep_normalized_path_matching(self): - missing = self.root / "offline.bin" - predictions, manifest = self.reports(missing, self.root / "unused" / ".." / missing.name) - self.assertFalse(missing.exists()) - self.assert_confirmed(verifier.verify(predictions, [manifest])) - - def test_unavailable_metadata_does_not_accept_different_paths(self): - predictions, manifest = self.reports(self.archive, self.hard_link()) - with mock.patch.object(verifier.os.path, "samefile", side_effect=PermissionError("metadata unavailable")): - with self.assertRaisesRegex(ValueError, "different source archive"): - verifier.verify(predictions, [manifest]) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/test_world_grid_atlas.py b/tests/test_world_grid_atlas.py deleted file mode 100644 index 803878abd..000000000 --- a/tests/test_world_grid_atlas.py +++ /dev/null @@ -1,581 +0,0 @@ -"""world_grid_atlas.py: grid geometry, archive order, alignment and a forward check on synthetic grids. - - python -I tests/test_world_grid_atlas.py - -The order, alignment, fill and fit logic is plain Python and is tested on the standard library alone. The forward -check builds a synthetic work folder and carve: four grids on an 8 x 12 tile map (cells 0..95, so text order and -numeric order differ), tile textures written as DDS files at known cells and stored in text order of the cell, the -fallback mosaics built from those tiles, grid documents as XML and an MHIU terrain grid. It runs the CLI and checks -that every tile comes back at its cell. Those tests need numpy and Pillow and are skipped without them. No game -data is used. -""" -import itertools -import json -import math -import os -import random -import struct -import subprocess -import sys -import tempfile -import unittest -from unittest import mock - -ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) -TOOLS = os.path.join(ROOT, "tools") -TOOL = os.path.join(TOOLS, "world_grid_atlas.py") -sys.path.insert(0, TOOLS) - -import world_grid_atlas as wga # noqa: E402 - -try: - import numpy as np - import PIL # noqa: F401 - HAVE_NUMPY = True -except ImportError: - HAVE_NUMPY = False - -DOC = {"origin": (0.0, 0.0, 0.0), "width": 4096, "height": 6144, "tileSize": 512, "zInflation": 1000.0} - - -class PlainLogicTest(unittest.TestCase): - def test_geometry_of_the_measured_grid(self): - g = wga.geometry({"origin": (-5120.0, 7680.0, 0.0), "width": 16384, "height": 33792, - "tileSize": 512, "zInflation": 1000.0}) - self.assertEqual((g["columns"], g["rows"]), (32, 66)) - self.assertEqual((g["x_min"], g["x_max"], g["y_min"], g["y_max"]), (-13312, 3072, -9216, 24576)) - self.assertEqual((g["z_min"], g["z_max"]), (-1000, 1000)) - - def test_geometry_rejects_a_partial_tile(self): - with self.assertRaises(ValueError): - wga.geometry({**DOC, "width": 4000}) - with self.assertRaises(ValueError): - wga.geometry({**DOC, "tileSize": 0}) - with self.assertRaises(ValueError): - wga.geometry({**DOC, "width": 4096.5}) - - def test_row_zero_is_north(self): - g = wga.geometry(DOC) - self.assertEqual(wga.cell_box(g, 0), (-2048, 2560, -1536, 3072)) - self.assertEqual(wga.cell_box(g, 95), (1536, -3072, 2048, -2560)) - with self.assertRaises(ValueError): - wga.cell_box(g, 96) - - def test_text_order(self): - self.assertEqual(wga.text_order(12), [0, 1, 10, 11, 2, 3, 4, 5, 6, 7, 8, 9]) - - def test_ascending_steps_per_spelling(self): - cells = [1, 10, 11, 2, 20] # text order - s = wga.ascending_steps(cells, 8) - self.assertEqual(s["text"], [4, 4]) - self.assertEqual(s["numeric"], [3, 4]) - self.assertEqual(wga.ascending_steps([], 8)["text"], [0, 0]) - - def test_fill_by_order_places_exact_gaps_only(self): - order = list(range(10)) - placed, dropped, left = wga.fill_by_order(6, {0: 1, 3: 4, 5: 9}, order) - # tiles 1, 2 fill cells 2, 3 exactly; tile 4 has 4 free cells (5..8) for 1 tile: left unplaced - self.assertEqual(placed, {0: 1, 1: 2, 2: 3, 3: 4, 5: 9}) - self.assertEqual((dropped, left), (0, 1)) - - def test_fill_by_order_fills_the_ends(self): - placed, _, left = wga.fill_by_order(3, {1: 1}, [0, 1, 2]) - self.assertEqual(placed, {0: 0, 1: 1, 2: 2}) - self.assertEqual(left, 0) - - def test_fill_by_order_drops_an_anchor_out_of_order(self): - placed, dropped, _ = wga.fill_by_order(3, {0: 5, 1: 2, 2: 7}, list(range(10))) - # cells 5, 2, 7: (5, 7) and (2, 7) are equally long, so either may be kept; one anchor is dropped - self.assertEqual(dropped, 1) - self.assertEqual(placed[2], 7) - cells = [placed[i] for i in sorted(placed)] - self.assertTrue(all(b > a for a, b in zip(cells, cells[1:]))) - - def test_fill_by_order_keeps_the_longest_consistent_anchors(self): - """One wrong early anchor must not drop the correct ones after it.""" - placed, dropped, left = wga.fill_by_order(5, {0: 9, 1: 1, 2: 2, 3: 3, 4: 4}, list(range(10))) - self.assertEqual(dropped, 1) - self.assertEqual({i: placed[i] for i in (1, 2, 3, 4)}, {1: 1, 2: 2, 3: 3, 4: 4}) - self.assertNotEqual(placed.get(0), 9) - # two anchors on one cell: only one is kept - placed, dropped, _ = wga.fill_by_order(2, {0: 3, 1: 3}, list(range(5))) - self.assertEqual(dropped, 1) - - def test_longest_increasing_matches_brute_force(self): - rnd = random.Random(7) - for _ in range(300): - pos = [rnd.randrange(8) for _ in range(rnd.randint(0, 8))] - pairs = list(enumerate(pos)) - got = wga.longest_increasing(pairs) - self.assertTrue(all(b[1] > a[1] and b[0] > a[0] for a, b in zip(got, got[1:]))) - best = 0 - for k in range(len(pos), 0, -1): - if any(all(b > a for a, b in zip(c, c[1:])) for c in itertools.combinations(pos, k)): - best = k - break - self.assertEqual(len(got), best) - - def test_main_archive_and_counts(self): - recs = [{"archive": a} for a in ("levels", "levels", "minigame", "levels")] - self.assertEqual(wga.archive_counts(recs), {"levels": 3, "minigame": 1}) - self.assertEqual(wga.main_archive(recs), "levels") - self.assertIsNone(wga.main_archive([])) - - def test_inside_is_inclusive(self): - self.assertTrue(wga.inside(-1000.0, 1000.0, -1000.0, 1000.0)) - self.assertFalse(wga.inside(-1000.5, 0.0, -1000.0, 1000.0)) - self.assertFalse(wga.inside(0.0, 1000.5, -1000.0, 1000.0)) - - def test_align_matches_brute_force(self): - rnd = random.Random(340) - for _ in range(300): - n, m = rnd.randint(1, 4), rnd.randint(4, 7) - if n > m: - continue - s = [[rnd.choice([0.0, 0.0, rnd.random()]) for _ in range(m)] for _ in range(n)] - path = wga.align(s) - self.assertEqual(len(path), n) - self.assertTrue(all(b > a for a, b in zip(path, path[1:]))) - best = max(sum(s[i][j] for i, j in enumerate(c)) for c in itertools.combinations(range(m), n)) - self.assertAlmostEqual(sum(s[i][j] for i, j in enumerate(path)), best) - - def test_align_needs_enough_slots(self): - self.assertEqual(wga.align([]), []) - with self.assertRaises(ValueError): - wga.align([[1.0], [1.0]]) - - def test_linear_fit(self): - xs = [float(x) for x in range(33000, 50000, 500)] - f = wga.linear_fit(xs, [(x - 32768) / 40.96 for x in xs]) - self.assertAlmostEqual(1 / f["slope"], 40.96, places=6) - self.assertAlmostEqual(-f["intercept"] / f["slope"], 32768, places=3) - self.assertAlmostEqual(f["r"], 1.0) - with self.assertRaises(ValueError): - wga.linear_fit([1.0, 1.0], [2.0, 3.0]) - - def test_load_manifests_accepts_utf8_bom(self): - with tempfile.TemporaryDirectory() as td: - tex_dir = os.path.join(td, "assets", "levels", "textures") - os.makedirs(tex_dir) - manifest = { - "Items": [{ - "Offset": 0x1000, - "Dir": "dictionary_at_0000000000001000", - "Textures": [{ - "Index": 0, - "Name": "watersystemheightmap", - "Width": 64, - "Height": 64, - "Format": "R16_UNORM", - }], - }] - } - with open(os.path.join(tex_dir, "manifest.json"), "wb") as f: - f.write(b"\xef\xbb\xbf" + json.dumps(manifest).encode("utf-8")) - recs = wga.load_manifests(td) - self.assertEqual(len(recs), 1) - self.assertEqual(recs[0]["name"], "watersystemheightmap") - - -# ---- synthetic work folder and carve --------------------------------------------------------------------------- - -def dds(width, height, dxgi, payload, bpp): - head = bytearray(148) - head[:4] = b"DDS " - struct.pack_into("<7I", head, 4, 124, 0x1 | 0x2 | 0x4 | 0x8 | 0x1000, height, width, width * bpp, 0, 1) - struct.pack_into("<2I4s", head, 76, 32, 0x4, b"DX10") - struct.pack_into("\n\n' - f'\tGS_TYPE_2D_TEXTURE_ATLAS\n\t{name}\n' - f'\t{name}-\n' - f'\t{suffix}\n' - f'\t\n' - f'\t{fallback}\n' - f'\t\n\t\n' - f'\t\n\t\n\t\n' - f'\t\n\t\n' - f'\t\n\t\t\n\t\t\tmapswap_test\n' - f'\t\t\t{fallback}_tblux\n' - f'\t\t\tt-\n\t\t\n\t\n\n').encode() - - -def mhiu(width, height, bounds, heights): - """Full-width rows, default 23; `heights` is a list of rows of u8 values (row 0 = min y).""" - table, packed = bytearray(), bytearray() - for row in heights: - table += struct.pack(" list of (offset, dir, [texture records]) - self.files = {} # path -> bytes - self.rows = [] - - def tearDown(self): - self.tmp.cleanup() - - # -- writers -- - def add_dict(self, archive, textures): - items = self.items.setdefault(archive, []) - offset = 0x2010 + 0x10000 * len(items) - d = f"dictionary_at_{offset:016X}" - recs = [] - for index, (name, fmt, data, w, h) in enumerate(textures): - path = os.path.join(self.work, "assets", archive, "textures", d, f"{index:03d}_{name}.dds") - self.files[path] = data - recs.append({"Index": index, "Name": name, "Width": w, "Height": h, "Format": fmt, - "MipCount": 1, "Hash": "00000000", "Key": None}) - items.append({"Offset": offset, "Dir": d, "Textures": recs}) - - def add_stream(self, data): - off = 0x1000 * (len(self.rows) + 1) - with open(os.path.join(self.carve, f"{off:012x}.bin"), "wb") as f: - f.write(data) - self.rows.append({"off": off, "stored": len(data), "size": len(data), "head": data[:16].hex(), "pre": ""}) - - def finish(self): - for path, data in self.files.items(): - os.makedirs(os.path.dirname(path), exist_ok=True) - with open(path, "wb") as f: - f.write(data) - for archive, items in self.items.items(): - with open(os.path.join(self.work, "assets", archive, "textures", "manifest.json"), "w") as f: - json.dump({"src": archive, "Count": len(items), "Scan": {}, "Items": items}, f) - with open(os.path.join(self.carve, "index.json"), "w", encoding="utf-8") as f: - json.dump({"summary": {"archive": "synthetic", "files": len(self.rows)}, "files": self.rows}, f) - - def run_tool(self, *extra): - out = os.path.join(self.root, "out.json") - p = subprocess.run([sys.executable, "-I", TOOL, self.work, "--carve", self.carve, "--json", out, *extra], - capture_output=True, text=True, encoding="utf-8", errors="replace") - data = None - if p.returncode == 0: - with open(out, encoding="utf-8") as f: - data = json.load(f) - return p, data - - # -- world -- - def mosaic(self, cells, p, fill, channels=None): - shape = (self.ROWS * p, self.COLS * p) + ((channels,) if channels else ()) - out = np.empty(shape) - out[...] = fill - for cell, block in cells.items(): - r, c = divmod(cell, self.COLS) - out[r * p:(r + 1) * p, c * p:(c + 1) * p] = block - return out - - def build(self, order_key=str): - """Write the four grids; tile dictionaries are stored sorted by order_key(cell).""" - g = self.geom - truth = {} - # water height: 64 px tiles, 4 px per cell in the fallback; cell 10 is a flat tile between 1 and 11 - height_cells = sorted((set(int(c) for c in self.rnd.choice(96, 24, replace=False)) | {1, 11, 12}) - {10}) - tiles, fb = {}, {} - for cell in height_cells + [10]: - x0, y0, x1, y1 = wga.cell_box(g, cell) - if cell == 10: - t = np.full((64, 64), 20480.0) - else: - ys = y1 - (np.arange(64) + 0.5) * 8 - xs = x0 + (np.arange(64) + 0.5) * 8 - z = np.array([[terrain(x, y) for x in xs] for y in ys]) - t = np.round(32768 + 40.96 * z) - tiles[cell] = t - fb[cell] = t[8::16, 8::16] - for cell in sorted(tiles, key=order_key): - self.add_dict("levels", [("watersystemheightmap", "R16_UNORM", r16_dds(tiles[cell]), 64, 64)]) - truth["watersystemheightmap"] = sorted(tiles, key=order_key) - self.height_fallback = self.mosaic(fb, 4, 20480.0) - self.add_dict("levels", [("watersystemheightmap_gfb", "R16_UNORM", r16_dds(self.height_fallback), 32, 48)]) - # fog pair: shared dictionaries, 32 px tiles, 4 px per cell; one tile has detail only in fog2, three flat - fog_cells = sorted(set(int(c) for c in self.rnd.choice(96, 20, replace=False))) - flat = set(fog_cells[5:8]) - only_b = fog_cells[2] - fa, fbb = {}, {} - for cell in sorted(fog_cells, key=order_key): - a = np.full((32, 32), 1000.0) if cell in flat or cell == only_b else self.rnd.integers(0, 60000, (32, 32)) - b = np.full((32, 32), 2000.0) if cell in flat else self.rnd.integers(0, 60000, (32, 32)) - fa[cell], fbb[cell] = a[4::8, 4::8], b[4::8, 4::8] - self.add_dict("textures", [("fog", "R16_UNORM", r16_dds(a), 32, 32), - ("fog2", "R16_UNORM", r16_dds(b), 32, 32)]) - truth["fog"] = sorted(fog_cells, key=order_key) - self.fog_flat, self.fog_only_b = flat, only_b - self.add_dict("textures", [("fog_gfb", "R16_UNORM", r16_dds(self.mosaic(fa, 4, 1000.0)), 32, 48), - ("fog_gfb2", "R16_UNORM", r16_dds(self.mosaic(fbb, 4, 2000.0)), 32, 48)]) - # shoreline: 64 px BGRA tiles, 8 px per cell; features are whole 8 px blocks; two identical tiles; one blank - bg = np.array([0, 128, 0, 128]) - shore_cells = sorted(set(int(c) for c in self.rnd.choice(96, 16, replace=False))) - twin = self.rnd.random((8, 8)) < 0.3 - st, sf = {}, {} - for i, cell in enumerate(shore_cells): - mask = twin if i in (3, 4) else (np.zeros((8, 8), bool) if i == 6 else self.rnd.random((8, 8)) < 0.3) - small = np.where(mask[..., None], np.array([255, 200, 40, 255]), bg) - st[cell] = np.kron(small, np.ones((8, 8, 1))) - sf[cell] = small - for cell in sorted(shore_cells, key=order_key): - self.add_dict("levels", [("shore", "B8G8R8A8_UNORM", bgra_dds(st[cell]), 64, 64)]) - truth["shore"] = sorted(shore_cells, key=order_key) - self.shore_blank = shore_cells[6] - self.add_dict("levels", [("shore_gfb", "B8G8R8A8_UNORM", bgra_dds(self.mosaic(sf, 8, bg, 4)), 64, 96)]) - # documents and terrain - for doc in (grid_xml("WaterSystemHeightMap", "watersystemheightmap", "watersystemheightmap_gfb"), - grid_xml("fogA", "fog", "fog_gfb"), grid_xml("fogB", "fog2", "fog_gfb2"), - grid_xml("shorelinegrid1", "shore", "shore_gfb")): - self.add_stream(doc) - w = h = 128 - bounds = (-2048.0, -3072.0, -50.0, 2048.0, 3072.0, 500.0) - rows = [] - for j in range(h): - y = bounds[1] + (j + 0.5) * (bounds[4] - bounds[1]) / h - rows.append([max(0, min(255, round((terrain(bounds[0] + (i + 0.5) * 4096 / w, y) + 50) / 550 * 255))) - for i in range(w)]) - self.add_stream(mhiu(w, h, bounds, rows)) - self.finish() - return truth - - def placements(self, data, name): - return {(p["offset"]): p["cell"] for p in data["placements"][name]} - - def stored(self, archive, name): - return [it["Offset"] for it in self.items[archive] if it["Textures"][0]["Name"] == name] - - # -- tests -- - def test_every_tile_returns_to_its_cell(self): - truth = self.build() - p, data = self.run_tool() - self.assertEqual(p.returncode, 0, p.stderr) - grids = {g["name"]: g for g in data["grids"]} - - height = self.placements(data, "watersystemheightmap") - offs = self.stored("levels", "watersystemheightmap") - self.assertEqual(height, dict(zip(offs, truth["watersystemheightmap"]))) # flat cell 10 placed by order - hg = grids["WaterSystemHeightMap"] - self.assertEqual(hg["anchors"], len(offs) - 1) - self.assertEqual(hg["anchor_order"]["text"][0], hg["anchor_order"]["text"][1]) - self.assertLess(hg["anchor_order"]["numeric"][0], hg["anchor_order"]["numeric"][1]) - - fog = self.placements(data, "fog") - offs = self.stored("textures", "fog") - want = dict(zip(offs, truth["fog"])) - fg = grids["fogA"] - self.assertEqual(fg["anchors"], len(offs) - 3) # the fog2-only tile is an anchor, flat ones are not - for off, cell in fog.items(): - self.assertEqual(cell, want[off]) - self.assertEqual(len(fog) + fg["unplaced"], len(offs)) - self.assertEqual(grids["fogB"]["placed"], fg["placed"]) - - shore = self.placements(data, "shore") - offs = self.stored("levels", "shore") - want = {o: c for o, c in zip(offs, truth["shore"]) if c != self.shore_blank} - self.assertEqual(shore, want) # the twin tiles resolved by order, blank one unplaced - sg = grids["shorelinegrid1"] - self.assertEqual(sg["unplaced"], 1) - self.assertEqual(sg["featureless_tiles"], 1) - self.assertEqual(sg["unplaced_with_features"], 0) - self.assertEqual(sg["anchors_moved_by_alignment"], 0) - self.assertEqual(sg["background"], [0, 128, 0, 128]) - self.assertEqual(sg["anchors"], len(offs) - 3) # the twins and the blank tile are not clear - for g in grids.values(): - self.assertEqual((g["duplicate_records"], g["unshared_dictionaries"], g["tiles_in_other_archives"]), - (0, 0, 0)) - self.assertEqual(hg["tile_size"], [64, 64]) - self.assertEqual(hg["fallback_format"], "R16_UNORM") - self.assertEqual(set(data["placements"]), {"watersystemheightmap", "fog", "fog2", "shore"}) - - def test_water_fit_recovers_the_scale_and_north_up(self): - self.build() - p, data = self.run_tool() - self.assertEqual(p.returncode, 0, p.stderr) - hg = next(g for g in data["grids"] if g["name"] == "WaterSystemHeightMap") - fit = hg["water_fit"][0] - self.assertAlmostEqual(fit["north_up"]["units_per_metre"], 40.96, delta=0.3) - self.assertAlmostEqual(fit["north_up"]["zero_metre_value"], 32768, delta=60) - self.assertGreater(fit["north_up"]["r"], 0.95) - self.assertLess(fit["south_up"]["r"], 0.5) - self.assertEqual(data["z_check"], [{"z_box": [-1000.0, 1000.0], "heightmaps_inside": 1, "heightmaps": 1}]) - self.assertIn("WaterSystemHeightMap: ", p.stdout) - - def test_numeric_storage_order_is_detected(self): - """Negative control: stored by numeric cell, the text-order check must report breaks.""" - self.build(order_key=lambda c: c) - p, data = self.run_tool() - self.assertEqual(p.returncode, 0, p.stderr) - hg = next(g for g in data["grids"] if g["name"] == "WaterSystemHeightMap") - self.assertEqual(hg["anchor_order"]["numeric"][0], hg["anchor_order"]["numeric"][1]) - self.assertLess(hg["anchor_order"]["text"][0], hg["anchor_order"]["text"][1]) - - def test_refuses_json_over_a_manifest(self): - self.build() - manifest = os.path.join(self.work, "assets", "levels", "textures", "manifest.json") - with open(manifest, "rb") as f: - before = f.read() - p = subprocess.run([sys.executable, "-I", TOOL, self.work, "--carve", self.carve, "--json", manifest], - capture_output=True, text=True) - self.assertEqual(p.returncode, 2) - self.assertIn("inside the exported assets", p.stderr) - with open(manifest, "rb") as f: - self.assertEqual(f.read(), before) - - def test_refuses_json_over_a_tile_texture(self): - self.build() - tile = next(pth for pth in self.files if pth.endswith("_watersystemheightmap.dds")) - with open(tile, "rb") as f: - before = f.read() - p = subprocess.run([sys.executable, "-I", TOOL, self.work, "--carve", self.carve, "--json", tile], - capture_output=True, text=True) - self.assertEqual(p.returncode, 2) - with open(tile, "rb") as f: - self.assertEqual(f.read(), before) - - def test_counts_duplicates_and_other_archives(self): - self.build() - first = next(it for it in self.items["levels"] if it["Textures"][0]["Name"] == "watersystemheightmap") - self.items["levels"].append(json.loads(json.dumps(first))) # the same dictionary listed twice - other = next(pth for pth in self.files if pth.endswith("_watersystemheightmap.dds")) - with open(other, "rb") as f: - data = f.read() - self.add_dict("minigame", [("watersystemheightmap", "R16_UNORM", data, 64, 64)]) - self.finish() - p, out = self.run_tool() - self.assertEqual(p.returncode, 0, p.stderr) - hg = next(g for g in out["grids"] if g["name"] == "WaterSystemHeightMap") - self.assertEqual((hg["duplicate_records"], hg["tiles_in_other_archives"]), (1, 1)) - self.assertIn("1 duplicate tile records ignored", p.stdout) - self.assertIn("1 tiles in other archives not placed", p.stdout) - - def test_says_when_there_is_no_heightmap(self): - self.build() - def magic(row): - with open(os.path.join(self.carve, f"{row['off']:012x}.bin"), "rb") as f: - return f.read(4) - self.rows = [r for r in self.rows if magic(r) != b"MHIU"] - self.finish() - p, data = self.run_tool() - self.assertEqual(p.returncode, 0, p.stderr) - self.assertIn("no heightmap in the carve, not checked", p.stdout) - self.assertIn("no MHIU heightmap", p.stdout) - - def test_refuses_json_inside_the_carve(self): - self.build() - out = os.path.join(self.carve, "sub", "grid.json") - p = subprocess.run([sys.executable, "-I", TOOL, self.work, "--carve", self.carve, "--json", out], - capture_output=True, text=True) - self.assertEqual(p.returncode, 2) - self.assertIn("inside the carve folder", p.stderr) - self.assertFalse(os.path.exists(out)) - - def test_reports_bad_inputs_in_one_line(self): - self.build() - blocker = os.path.join(self.root, "file") - with open(blocker, "w") as f: - f.write("x") - cases = [ - [os.path.join(self.root, "nowork"), "--carve", self.carve], - [self.work, "--carve", os.path.join(self.root, "nocarve")], - [self.work, "--carve", self.carve, "--json", self.root], - [self.work, "--carve", self.carve, "--json", os.path.join(blocker, "out.json")], - [self.carve, "--carve", self.carve], - ] - for args in cases: - p = subprocess.run([sys.executable, "-I", TOOL, *args], capture_output=True, text=True) - self.assertEqual(p.returncode, 2, args) - self.assertEqual(len(p.stderr.strip().splitlines()), 1, p.stderr) - - def test_reports_a_fallback_that_is_not_a_mosaic(self): - self.build() - path = next(pth for pth in self.files if pth.endswith("watersystemheightmap_gfb.dds")) - with open(path, "wb") as f: - f.write(r16_dds(np.full((40, 32), 20480.0))) - for it in self.items["levels"]: - for t in it["Textures"]: - if t["Name"] == "watersystemheightmap_gfb": - t["Height"] = 40 - self.finish() - p, _ = self.run_tool() - self.assertEqual(p.returncode, 2) - self.assertIn("mosaic", p.stderr) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/test_world_grid_atlas_native.py b/tests/test_world_grid_atlas_native.py deleted file mode 100644 index e191c6573..000000000 --- a/tests/test_world_grid_atlas_native.py +++ /dev/null @@ -1,165 +0,0 @@ -"""Synthetic parity and fallback checks for the optional atlas matcher. - - cargo build --release --locked --offline --manifest-path tools/world_atlas_native/Cargo.toml - python -I tests/test_world_grid_atlas_native.py - -Set LEONIDA_WORLD_ATLAS_BENCHMARK=1 to also time a synthetic workload. -""" - -import json -import os -from pathlib import Path -from statistics import median -import sys -from time import perf_counter -import unittest -from unittest import mock - -sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "tools")) - -import world_atlas_accel as accel # noqa: E402 -import world_grid_atlas as atlas # noqa: E402 - -try: - import numpy as np -except ImportError: - np = None - - -def images(tiles, cells, scale=1): - slots, size, _ = cells.shape - fallback = (cells.transpose(1, 0, 2).reshape(size, slots * size, 1) * 255).astype(float) - textures = (tiles[..., None] * 255).astype(float).repeat(scale, axis=1).repeat(scale, axis=2) - return list(textures), fallback, {"rows": 1, "columns": slots} - - -def run(inputs, enabled): - with mock.patch.dict(os.environ, {"LEONIDA_WORLD_ATLAS_NATIVE": "1" if enabled else "0"}): - return json.dumps(atlas.match_mask(*inputs)).encode("utf-8") - - -def reference(tiles, cells, order): - intersection = np.einsum("tij,cij->tc", tiles, cells) - union = tiles.sum((1, 2))[:, None] + cells.sum((1, 2))[None, :] - intersection - iou = np.where(union > 0, intersection / np.maximum(union, 1), 0.0) - top = np.sort(iou, 1)[:, ::-1] - clear = {i: int(iou[i].argmax()) for i in range(len(tiles)) if top[i, 0] - top[i, 1] > atlas.CLEAR_MARGIN} - path = atlas.align(iou[:, order].tolist()) - placed = {i: order[slot] for i, slot in enumerate(path) if iou[i, order[slot]] > 0} - return clear, placed, sorted(float(iou[i, cell]) for i, cell in placed.items()) - - -@unittest.skipIf(np is None, "NumPy is required") -class FallbackTest(unittest.TestCase): - def setUp(self): - cells = np.zeros((12, 3, 3), dtype=np.int32) - cells[2, 1, 0] = cells[10, 0, 1] = 1 - self.inputs = images(cells[[10, 2]], cells, scale=2) - self.expected = run(self.inputs, False) - - def tearDown(self): - accel._load.cache_clear() - - def test_opt_out_does_not_load(self): - with mock.patch.object(accel, "_load", side_effect=AssertionError("loaded while opted out")): - self.assertEqual(run(self.inputs, False), self.expected) - - def test_missing_or_broken_library_and_abi_mismatch(self): - for failure in (FileNotFoundError("missing"), OSError("bad binary"), None): - with self.subTest(failure=failure): - accel._load.cache_clear() - with mock.patch.object(accel.ctypes, "CDLL", side_effect=failure, return_value=object()) as load: - self.assertEqual(run(self.inputs, True), self.expected) - load.assert_called_once() - - def test_refusal_does_not_publish_partial_outputs(self): - def refuse(tiles, tiles_len, cells, cells_len, words, margin, out, out_len): - out[0].clear = 12345 - return -1 - - with mock.patch.object(accel, "_load", return_value=mock.Mock(side_effect=refuse)) as load: - self.assertEqual(run(self.inputs, True), self.expected) - load.return_value.assert_called_once() - - -@unittest.skipIf(np is None, "NumPy is required") -class NativeTest(unittest.TestCase): - def setUp(self): - if accel._load() is None: - self.skipTest("world_atlas_native release library is not built") - - def test_randomized_report_parity(self): - rng = np.random.default_rng(3927) - for case in range(1100): - slots = int(rng.integers(2, 27)) - count = int(rng.integers(1, slots + 1)) - size = int(rng.choice([1, 2, 3, 7, 8, 9, 16, 31, 32, 33])) - density = float(rng.choice([0, 0.03, 0.15, 0.35, 0.5, 1])) - cells = (rng.random((slots, size, size)) < density).astype(np.int32) - tiles = (rng.random((count, size, size)) < density).astype(np.int32) - if case % 3 == 0: - tiles[::2] = cells[rng.integers(slots, size=len(tiles[::2]))] - if case % 5 == 0: - cells[1] = cells[0] - order = atlas.text_order(slots) - with self.subTest(case=case), mock.patch.dict(os.environ, {"LEONIDA_WORLD_ATLAS_NATIVE": "1"}): - self.assertEqual(accel.match(np, tiles, cells, order, atlas.CLEAR_MARGIN), - reference(tiles, cells, order)) - inputs = images(tiles, cells, scale=2 if case % 4 == 0 else 1) - self.assertEqual(run(inputs, True), run(inputs, False)) - - def test_exact_margin_and_tied_alignment(self): - tiles = np.zeros((1, 3, 3), np.int32) - tiles.flat[:5] = 1 - cells = np.zeros((12, 3, 3), np.int32) - cells[2, 0, 0] = 1 - self.assertEqual(run(images(tiles, cells), True), run(images(tiles, cells), False)) - with mock.patch.dict(os.environ, {"LEONIDA_WORLD_ATLAS_NATIVE": "1"}): - order = atlas.text_order(len(cells)) - self.assertEqual(accel.match(np, tiles, cells, order, atlas.CLEAR_MARGIN), ({}, {0: 2}, [0.2])) - cells[10] = cells[2] - self.assertEqual(accel.match(np, tiles, cells, order, atlas.CLEAR_MARGIN), ({}, {0: 10}, [0.2])) - - def test_reference_errors(self): - for count, slots in [(0, 2), (1, 1), (3, 2)]: - cells = np.zeros((slots, 3, 3), np.int32) - inputs = images(np.zeros((count, 3, 3), np.int32), cells) - with self.subTest(count=count, slots=slots): - with self.assertRaises((ValueError, IndexError)) as slow: - run(inputs, False) - with self.assertRaises(type(slow.exception)) as fast: - run(inputs, True) - self.assertEqual(str(fast.exception), str(slow.exception)) - - @unittest.skipUnless(os.environ.get("LEONIDA_WORLD_ATLAS_BENCHMARK") == "1", "opt-in benchmark") - def test_synthetic_benchmark(self): - rng = np.random.default_rng(154) - slots, count, size = 2112, 268, 32 - cells = (rng.random((slots, size, size)) < 0.15).astype(np.int32) - order = atlas.text_order(slots) - tiles = cells[np.array(order)[np.sort(rng.choice(slots, count, replace=False))]].copy() - tiles ^= rng.random(tiles.shape) < 0.02 - inputs = images(tiles, cells) - with mock.patch.dict(os.environ, {"LEONIDA_WORLD_ATLAS_NATIVE": "1"}): - for label, slow, fast in [ - ("overlap + alignment", lambda: reference(tiles, cells, order), - lambda: accel.match(np, tiles, cells, order, atlas.CLEAR_MARGIN)), - ("match_mask report", lambda: run(inputs, False), lambda: run(inputs, True)), - ]: - def measure(fn): - start = perf_counter() - result = fn() - return perf_counter() - start, result - - slow_samples = [measure(slow) for _ in range(3)] - fast_samples = [measure(fast) for _ in range(3)] - for _, result in fast_samples: - self.assertEqual(result, slow_samples[0][1]) - slow_time = median(time for time, _ in slow_samples) - fast_time = median(time for time, _ in fast_samples) - print(f"{label}: {slow_time:.4f}s Python, {fast_time:.4f}s Rust ({slow_time / fast_time:.1f}x)", - flush=True) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/test_world_index.py b/tests/test_world_index.py deleted file mode 100644 index cb65b7464..000000000 --- a/tests/test_world_index.py +++ /dev/null @@ -1,954 +0,0 @@ -"""Tests for tools/world_index.py, built from synthetic 0x7a headers (no game data). - - python -I tests/test_world_index.py -""" -import contextlib -import csv -import errno -import importlib.util -import io -import json -import os -import struct -import sys -import tempfile -import unittest -import zlib -from unittest import mock - -ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) -sys.path.insert(0, os.path.join(ROOT, "tools")) -import report_paths - - -def load_tool(): - path = os.path.join(ROOT, "tools", "world_index.py") - spec = importlib.util.spec_from_file_location("world_index_under_test", path) - module = importlib.util.module_from_spec(spec) - spec.loader.exec_module(module) - return module - - -WI = load_tool() -PTR = 0x50000000 - - -def ptr(off): - return PTR | off - - -def member(hash_, off, ty, sub=0, ref=0, extra=0): - return struct.pack(".bin per stream plus index.json (off, stored).""" - folder = os.path.join(self.dir, "carve") - os.makedirs(folder) - files, off = [], 0x1000 - for part in parts: - stored = len(zlib.compress(part)) - with open(os.path.join(folder, f"{off:012x}.bin"), "wb") as f: - f.write(part) - files.append({"off": off, "stored": stored, "size": len(part)}) - off = ((off + stored + 15) & ~15) + gap - with open(os.path.join(folder, "index.json"), "w", encoding="utf-8", newline="\n") as f: - json.dump({"summary": {}, "files": files}, f) - return folder - - def test_carve_folder_joins_a_resource_split_over_two_files(self): - """scan_rpf appends the next contiguous stream while a 0DRPz resource needs a continuation; a carve - folder holds the same streams as files, and index.json says which ones were contiguous.""" - blob = make_resource() - rows, stats = WI.scan_path(self.carve([blob[:0x150], blob[0x150:], make_resource(map_file=False)])) - maps = [r for r in rows if r["kind"] == "map"] - self.assertEqual([(r["file"], r["size"]) for r in maps], [("000000001000.bin", len(blob))]) - self.assertEqual(len(rows), 2) - - def test_carve_folder_does_not_join_streams_that_were_not_contiguous(self): - blob = make_resource() - rows, _ = WI.scan_path(self.carve([blob[:0x150], blob[0x150:]], gap=0x10)) - self.assertEqual(rows, []) - - def test_carved_file_inflate_cap_matches_directory_scan(self): - resource = make_resource() - path = os.path.join(self.dir, "sample.bin") - with open(path, "wb") as f: - f.write(resource) - - for source in (path, self.dir): - for cap, expected in ((len(resource) - 1, 0), (len(resource), 1)): - with self.subTest(source=source, cap=cap): - entities = [] - rows, stats = WI.scan_path(source, max_inflate=cap, collect=entities) - self.assertEqual(len(rows), expected) - self.assertEqual(len(entities), expected) - self.assertEqual(stats["files"], expected) - self.assertEqual(stats["scanned_bytes"], expected * len(resource)) - - def test_directory_inflate_cap_does_not_exclude_large_archives(self): - resource = make_resource() - cap = len(resource) - with open(os.path.join(self.dir, "large.rpf"), "wb") as f: - f.write(make_rpf_streams([resource]) + bytes(cap)) - with open(os.path.join(self.dir, "oversized.bin"), "wb") as f: - f.write(resource + b"\0") - rows, stats = WI.scan_path(self.dir, max_inflate=cap) - self.assertEqual(len(rows), 1) - self.assertEqual(rows[0]["kind"], "map") - self.assertEqual(stats["files"], 1) - - def test_archetypes_out_counts_each_entity_once(self): - blob = make_resource() - path = os.path.join(self.dir, "sample.rpf") - with open(path, "wb") as f: - # One resource split over two streams (joined, parsed again) and one whole copy. - f.write(make_rpf_streams([blob[:0x150], blob[0x150:], blob, make_resource(map_file=False)])) - out = os.path.join(self.dir, "out.json") - arch = os.path.join(self.dir, "archetypes.json") - with contextlib.redirect_stdout(io.StringIO()): - self.assertEqual(WI.main([path, "--out", out, "--archetypes-out", arch]), 0) - with open(arch, encoding="utf-8") as f: - doc = json.load(f) - self.assertEqual(doc["archetypes"], {"deadbeef": 2}) - self.assertEqual(doc["keys"], {"deadbeef": "1122334455667788"}) - self.assertEqual(doc["summary"], {"entities": 2, "archetypes": 1, "with_key": 1, "key_conflicts": 0, - "incomplete_entities": 0}) - - def test_conflicting_keys_leave_the_hash_unverified(self): - agg = WI.ArchetypeCounts() - agg.append({"complete": True, "archetype": 1, "archetype_key": 5}) - agg.append({"complete": True, "archetype": 1, "archetype_key": 6}) - agg.append({"complete": True, "archetype": 2, "archetype_key": 7}) - agg.append({"complete": True, "archetype": None, "archetype_key": 8}) - doc = agg.to_json() - self.assertEqual(doc["archetypes"], {"00000001": 2, "00000002": 1}) - self.assertEqual(doc["keys"], {"00000002": "0000000000000007"}) - self.assertEqual(doc["conflicting_keys"], {"00000001": ["0000000000000005", "0000000000000006"]}) - self.assertEqual(doc["summary"]["key_conflicts"], 1) - - def test_entity_past_the_inflated_bytes_is_not_aggregated(self): - # The entity block starts at 0x400 (0x90 bytes); the bytes end at 0x448, just after archetypeName. - agg = WI.ArchetypeCounts() - row = WI.parse_resource(make_resource()[:0x448], agg) - self.assertIsNotNone(row) - self.assertEqual((agg.counts, agg.incomplete), ({}, 1)) - - def test_entity_block_starting_past_the_inflated_bytes_is_incomplete(self): - # The entity block is moved to 0x700, after the bytes kept; its entities must still be reported. - b = bytearray(make_resource()) + bytearray(0x90) - struct.pack_into("= 16: - return parts, spans - return None, None - - -class ThreeStreamJoinTest(unittest.TestCase): - def test_third_stream_follows_the_second_streams_real_end(self): - blob = make_resource() - # With 16 or more bytes of padding after the first two streams, "first stream start + both streams' - # lengths", rounded up to 16, lands inside the second stream instead of at the third. - parts, spans = padded_split(blob) - self.assertIsNotNone(parts, "no split with 16 bytes of padding under this zlib") - archive = make_rpf_streams(parts) - with tempfile.TemporaryDirectory() as tmp: - path = os.path.join(tmp, "three.rpf") - with open(path, "wb") as f: - f.write(archive) - rows, stats = WI.scan_rpf(path) - self.assertEqual(stats["streams"], 3) - self.assertEqual(len(rows), 1) - self.assertEqual(rows[0]["size"], len(blob)) - self.assertEqual(rows[0]["map_name"], 0x11223344) # the CMapData block lives in the third stream - self.assertEqual(stats["scanned_bytes"], sum(e - s for s, e in spans)) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/test_world_instancing.py b/tests/test_world_instancing.py deleted file mode 100644 index 3867ce4e3..000000000 --- a/tests/test_world_instancing.py +++ /dev/null @@ -1,550 +0,0 @@ -"""Tests for the instanced placement build (no game data). - -Covers glb_writer.pack_primitive / build_instanced_glb and world_build.py --placements with --instancing -gpu (EXT_mesh_gpu_instancing), nodes and bake: the per-placement TRS against the baked transform, mirrored -placements, one stored mesh per model and chunk, chunk bounds and triangle counts against the baked build, -process workers, textures and the outcome counts. Every model, entity and texture is synthetic. - - python -I tests/test_world_instancing.py -""" -import json -import math -import os -import random -import shutil -import struct -import sys -import tempfile -import unittest - -ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) -TESTS = os.path.dirname(os.path.abspath(__file__)) -for p in (os.path.join(ROOT, "tools"), TESTS): - if p not in sys.path: - sys.path.insert(0, p) - -import glb_writer # noqa: E402 -import test_world_build as twb # noqa: E402 (independent GLB reader, synthetic DDS fixtures) -import test_world_place as twp # noqa: E402 (synthetic box model and entity rows) -import world_build # noqa: E402 - -EXT = "EXT_mesh_gpu_instancing" - - -def matmul(a, b): - return [[sum(a[i][k] * b[k][j] for k in range(3)) for j in range(3)] for i in range(3)] - - -def trs_matrix(q, s): - r = glb_writer._quat_matrix(q) - return [[r[i][j] * s[j] for j in range(3)] for i in range(3)] - - -# RAGE (x, y, z) -> glTF (x, z, -y) -C = [[1, 0, 0], [0, 0, 1], [0, -1, 0]] -CT = [[1, 0, 0], [0, 0, -1], [0, 1, 0]] -MIRROR_Y = [[1, 0, 0], [0, -1, 0], [0, 0, 1]] - - -def read_chunk(world_dir, chunk_id): - with open(os.path.join(world_dir, "chunks", f"{chunk_id}.glb"), "rb") as f: - return twb.parse_and_validate_glb(f.read()) - - -def read_indices(gltf, bin_data, acc_idx): - acc = gltf["accessors"][acc_idx] - bv = gltf["bufferViews"][acc["bufferView"]] - fmt = "<%d%s" % (acc["count"], "H" if acc["componentType"] == 5123 else "I") - return list(struct.unpack_from(fmt, bin_data, bv.get("byteOffset", 0) + acc.get("byteOffset", 0))) - - -class PlacementTrsTest(unittest.TestCase): - def test_trs_equals_the_baked_transform(self): - rnd = random.Random(7) - for _ in range(500): - q = [rnd.uniform(-1, 1) for _ in range(4)] - sxy = rnd.choice([1.0, 2.5, 0.3, -1.0, -2.0]) - sz = rnd.choice([1.0, 0.5, 3.0, -1.0, -0.7]) - pos = [rnd.uniform(-5000, 5000) for _ in range(3)] - t, qi, si, mirrored = world_build.placement_trs(q, sxy, sz, pos) - self.assertTrue(all(v > 0 for v in si)) - self.assertEqual(mirrored, sz < 0) - m_rage, _, mirror = world_build.entity_transform(q, sxy, sz) - self.assertEqual(mirror, mirrored) - want = matmul(matmul(C, m_rage), CT) # the baked transform, in glTF axes - got = trs_matrix(qi, si) - if mirrored: - got = matmul(got, MIRROR_Y) # a mirrored placement draws the Y-mirrored mesh - for i in range(3): - for j in range(3): - self.assertAlmostEqual(got[i][j], want[i][j], places=9) - self.assertTrue(twp.close(t, (pos[0], pos[2], -pos[1]))) - self.assertAlmostEqual(sum(v * v for v in qi), 1.0, places=12) - - def test_instance_bounds_of_a_turned_box(self): - # Unit box, scale 2, turned 90 degrees about +Y, moved by (10, 0, 0): x 10..12, z -2..0 after the turn. - h = math.sqrt(0.5) - b = glb_writer.instance_bounds([0, 0, 0], [1, 1, 1], [10, 0, 0], [0, h, 0, h], [2, 2, 2]) - self.assertTrue(twp.close(b, [10, 0, -2, 12, 2, 0], 1e-12)) - - -def tri_prim(): - return glb_writer.pack_primitive({"positions": [(0, 0, 0), (1, 0, 0), (0, 1, 0)], "normals": [], - "indices": [0, 1, 2], "uvs": []}) - - -class InstancedGlbTest(unittest.TestCase): - def test_gpu_instance_bounds_follow_the_stored_translation_and_scale(self) -> None: - meshes = [{ - "primitives": [tri_prim()], - "instances": [((16_777_219, 0, 0), (0, 0, 0, 1), (1, 1.00000003, 1))], - }] - data, stats = glb_writer.build_instanced_glb(meshes) - gltf, binary = twb.parse_and_validate_glb(data) - attrs = gltf["nodes"][0]["extensions"][EXT]["attributes"] - (translation,) = twb.read_accessor_floats(gltf, binary, attrs["TRANSLATION"]) - (scale,) = twb.read_accessor_floats(gltf, binary, attrs["SCALE"]) - self.assertEqual(translation, (16_777_220, 0, 0)) - self.assertEqual(scale, (1, 1, 1)) - self.assertEqual(stats["bounds"], [16_777_220, 0, 0, 16_777_221, 1, 0]) - - def test_gpu_mode(self): - meshes = [{"name": "a", "primitives": [tri_prim()], - "instances": [((0, 0, 0), (0, 0, 0, 1), (1, 1, 1)), ((5, 0, 0), (0, 0, 0, 1), (2, 2, 2))]}, - {"name": "b", "primitives": [tri_prim()], "instances": [((0, 9, 0), (0, 0, 0, 1), (1, 1, 1))]}] - data, st = glb_writer.build_instanced_glb(meshes) - gltf, bin_data = twb.parse_and_validate_glb(data) - glb_writer.read_glb_summary(data) - self.assertEqual(gltf["extensionsUsed"], [EXT]) - self.assertEqual(gltf["extensionsRequired"], [EXT]) - self.assertEqual(len(gltf["meshes"]), 2) - self.assertEqual(len(gltf["nodes"]), 2) - self.assertEqual(gltf["scenes"][0]["nodes"], [0, 1]) - attrs = gltf["nodes"][0]["extensions"][EXT]["attributes"] - self.assertEqual(twb.read_accessor_floats(gltf, bin_data, attrs["TRANSLATION"]), [(0, 0, 0), (5, 0, 0)]) - self.assertEqual(twb.read_accessor_floats(gltf, bin_data, attrs["SCALE"]), [(1, 1, 1), (2, 2, 2)]) - self.assertEqual(gltf["accessors"][attrs["ROTATION"]]["type"], "VEC4") - self.assertNotIn("target", gltf["bufferViews"][gltf["accessors"][attrs["ROTATION"]]["bufferView"]]) - self.assertEqual((st["triangles"], st["stored_triangles"], st["instances"], st["meshes"]), (3, 2, 3, 2)) - self.assertTrue(twp.close(st["bounds"], [0, 0, 0, 7, 10, 0])) - - def test_nodes_mode_writes_one_node_per_instance(self): - h = math.sqrt(0.5) - meshes = [{"primitives": [tri_prim()], - "instances": [((0, 0, 0), (0, 0, 0, 1), (1, 1, 1)), ((1, 2, 3), (0, 0, h, h), (1, 1, 4))]}] - data, st = glb_writer.build_instanced_glb(meshes, mode="nodes") - gltf, _ = twb.parse_and_validate_glb(data) - self.assertNotIn("extensionsUsed", gltf) - self.assertEqual(gltf["nodes"][0], {"mesh": 0}) - self.assertEqual(gltf["nodes"][1]["translation"], [1, 2, 3]) - self.assertEqual(gltf["nodes"][1]["scale"], [1, 1, 4]) - self.assertTrue(twp.close(gltf["nodes"][1]["rotation"], [0, 0, h, h], 1e-12)) - self.assertEqual(len(gltf["meshes"]), 1) - self.assertEqual(st["instances"], 2) - - def test_indexed_material_is_preserved_in_both_instancing_modes(self) -> None: - primitive = { - "positions": [(0, 0, 0), (1, 0, 0), (0, 1, 0)], - "indices": [0, 1, 2], - "material_index": 2, - } - materials = {2: {"name": "paint", "base_color_factor": [0.25, 0.5, 0.75, 1.0]}} - meshes = [{"primitives": [glb_writer.pack_primitive(primitive)], - "instances": [((0, 0, 0), (0, 0, 0, 1), (1, 1, 1))]}] - for mode in ("gpu", "nodes"): - with self.subTest(mode=mode): - data, _ = glb_writer.build_instanced_glb(meshes, materials, mode=mode) - gltf, _ = twb.parse_and_validate_glb(data) - material_index = gltf["meshes"][0]["primitives"][0]["material"] - material = gltf["materials"][material_index] - self.assertEqual(material["name"], "paint") - self.assertEqual(material["pbrMetallicRoughness"]["baseColorFactor"], - [0.25, 0.5, 0.75, 1.0]) - - def test_rejects_mirroring_scale_and_bad_input(self): - bad = [{"primitives": [tri_prim()], "instances": [((0, 0, 0), (0, 0, 0, 1), (1, -1, 1))]}] - with self.assertRaisesRegex(glb_writer.GlbError, "determinant"): - glb_writer.build_instanced_glb(bad) - with self.assertRaisesRegex(glb_writer.GlbError, "no mesh"): - glb_writer.build_instanced_glb([{"primitives": [tri_prim()], "instances": []}]) - with self.assertRaisesRegex(glb_writer.GlbError, "mode"): - glb_writer.build_instanced_glb(bad, mode="other") - - def test_mirror_packed(self): - p = glb_writer.pack_primitive({"positions": [(0, 1, 0), (1, 2, 0), (0, 3, 1)], "normals": [], - "indices": [0, 1, 2], "uvs": []}) - m = world_build._mirror_packed(p) - pos = struct.unpack("<9f", m["positions"]) - self.assertEqual(pos[1::3], (-1.0, -2.0, -3.0)) - self.assertEqual(struct.unpack("<3H", m["indices"]), (0, 2, 1)) - self.assertEqual((m["min"][1], m["max"][1]), (-3.0, -1.0)) - nrm = struct.unpack("<9f", m["normals"]) - orig = struct.unpack("<9f", p["normals"]) - self.assertEqual(nrm[1::3], tuple(-v for v in orig[1::3])) - - def test_pack_round_trip(self): - with tempfile.TemporaryDirectory() as tmp: - path = os.path.join(tmp, "m.lpk") - p = tri_prim() - p["material"] = "tex_x" - world_build._write_pack(path, [p, tri_prim()]) - back = world_build._read_pack(path) - self.assertEqual(len(back), 2) - for k in ("positions", "normals", "uvs", "indices", "index_type", "vertices", "index_count", "min", "max"): - self.assertEqual(back[0][k], p[k]) - self.assertEqual(back[0]["material"], "tex_x") - - -# A placement set that exercises turns, non-uniform scale, both negative scales and two chunks. -def mixed_rows(): - S2 = math.sqrt(0.5) - return [ - twp.entity("test_box", (100, 200, 10), twp.stored_rotation_about_z(90), sxy=2.0, sz=1.0), - twp.entity("test_box", (110, 205, 12), [0.1, 0.2, 0.3, 0.9], sxy=1.5, sz=0.5), - twp.entity("test_box", (120, 210, 0), [0.0, S2, 0.0, S2], sxy=1.0, sz=-1.0), # mirrored - twp.entity("test_box", (130, 220, 0), [0.0, 0.0, 0.0, 1.0], sxy=-2.0, sz=1.0), # XY turn, not a mirror - twp.entity("test_box", (1000, 1000, 0), lod=5, key=False), # second chunk - twp.entity("test_box", (5, 5, 5), sxy=0.0), # degenerate - twp.entity("other_box", (0, 0, 0)), # unresolved - ] - - -class PlacementArchetypeParityTest(unittest.TestCase): - def test_integer_and_hex_string_parse_to_the_same_archetype(self): - rows = [ - {"archetype": 10, "position": [0, 0, 0], "rotation": [0, 0, 0, 1], "lod_level": 0}, - {"archetype": "a", "position": [0, 0, 0], "rotation": [0, 0, 0, 1], "lod_level": 0}, # 0xa == 10 - {"archetype": True, "position": [0, 0, 0], "rotation": [0, 0, 0, 1], "lod_level": 0}, # bool stays invalid - ] - with tempfile.TemporaryDirectory() as tmp: - path = os.path.join(tmp, "entities.jsonl") - twp.write_entities(path, rows) - loaded, load_counts = world_build.load_placements(path) - iter_counts = world_build._placement_counts() - itered = list(world_build.iter_placements(path, iter_counts)) - self.assertEqual([row["_arch"] for row in loaded], [10, 10]) - self.assertEqual([row["_arch"] for row in itered], [10, 10]) - self.assertEqual(load_counts, iter_counts) - self.assertEqual((load_counts["rows"], load_counts["malformed"], load_counts["selected"]), (3, 1, 2)) - - -class InstancedBuildTest(unittest.TestCase): - def setUp(self): - self.tmp = tempfile.mkdtemp() - self.addCleanup(lambda: shutil.rmtree(self.tmp, ignore_errors=True)) - self.assets = twp.write_assets(self.tmp) - - def build(self, rows, name="world", **kw): - ents = os.path.join(self.tmp, f"{name}.jsonl") - twp.write_entities(ents, rows) - kw.setdefault("textures", False) - out = os.path.join(self.tmp, name) - return world_build.build_world(self.assets, out, placements=ents, **kw), out - - def test_shared_geometry_per_chunk(self): - rows = [twp.entity("test_box", (10 + i, 10, 0)) for i in range(3)] - doc, out = self.build(rows) - self.assertEqual(doc["instancing"], "gpu") - (chunk,) = doc["chunks"] - self.assertEqual((chunk["models"], chunk["distinct_models"], chunk["triangles"], chunk["stored_triangles"]), - (3, 1, 36, 12)) - gltf, bin_data = read_chunk(out, chunk["id"]) - self.assertEqual((len(gltf["meshes"]), len(gltf["nodes"])), (1, 1)) - attrs = gltf["nodes"][0]["extensions"][EXT]["attributes"] - got = twb.read_accessor_floats(gltf, bin_data, attrs["TRANSLATION"]) - self.assertEqual(sorted(got), [(10, 0, -10), (11, 0, -10), (12, 0, -10)]) - self.assertEqual(doc["stats"]["stored_triangles"], 12) - self.assertEqual(doc["stats"]["max_chunk_bytes"], doc["stats"]["chunk_bytes"]) - - def test_same_chunks_bounds_and_counts_as_the_baked_build(self): - rows = [r for r in mixed_rows() if r["scale_xy"] != 0] # bake also places a flat (zero-scale) copy - gpu, _ = self.build(rows, "gpu") - bake, _ = self.build(rows, "bake", instancing="bake") - self.assertEqual([c["id"] for c in gpu["chunks"]], [c["id"] for c in bake["chunks"]]) - for a, b in zip(gpu["chunks"], bake["chunks"]): - self.assertTrue(twp.close(a["bounds"], b["bounds"], 1e-4), (a["bounds"], b["bounds"])) - self.assertEqual((a["models"], a["triangles"]), (b["models"], b["triangles"])) - pg, pb = gpu["stats"]["placements"], bake["stats"]["placements"] - for k in ("rows", "selected", "placed", "placed_unverified", "unresolved_archetype", "key_mismatch"): - self.assertEqual(pg[k], pb[k], k) - self.assertEqual((pg["degenerate_scale"], pg["mirrored"]), (0, 1)) - - def test_zero_scale_is_counted_not_placed(self): - doc, _ = self.build(mixed_rows()) - pl = doc["stats"]["placements"] - self.assertEqual((pl["degenerate_scale"], pl["placed"], pl["placed_unverified"]), (1, 4, 1)) - - def test_mirrored_placement_draws_a_mirrored_mesh(self): - doc, out = self.build([twp.entity("test_box", (10, 10, 0), sz=-1.0), twp.entity("test_box", (12, 10, 0))]) - gltf, bin_data = read_chunk(out, doc["chunks"][0]["id"]) - names = sorted(m.get("name", "") for m in gltf["meshes"]) - self.assertEqual(len(names), 2) - self.assertTrue(names[1].endswith("_mirror")) - by_name = {m["name"]: m for m in gltf["meshes"]} - plain, mirror = by_name[names[0]]["primitives"][0], by_name[names[1]]["primitives"][0] - a = read_indices(gltf, bin_data, plain["indices"]) - b = read_indices(gltf, bin_data, mirror["indices"]) - self.assertEqual(b, [x for t in zip(a[0::3], a[2::3], a[1::3]) for x in t]) - pa = twb.read_accessor_floats(gltf, bin_data, plain["attributes"]["POSITION"]) - pb = twb.read_accessor_floats(gltf, bin_data, mirror["attributes"]["POSITION"]) - self.assertEqual(pb, [(x, -y, z) for x, y, z in pa]) - # Mirrored about the model's Z (glTF Y): the box spans y 0..1 below the placement instead of above. - self.assertTrue(twp.close(doc["chunks"][0]["bounds"][1:5:3], [-1, 1], 1e-6)) - - def test_nodes_mode(self): - doc, out = self.build([twp.entity("test_box", (10 + i, 10, 0)) for i in range(4)], instancing="nodes") - gltf, _ = read_chunk(out, doc["chunks"][0]["id"]) - self.assertEqual((len(gltf["meshes"]), len(gltf["nodes"])), (1, 4)) - self.assertNotIn("extensionsRequired", gltf) - self.assertEqual(doc["instancing"], "nodes") - - def test_process_workers_give_the_same_world(self): - one, out1 = self.build(mixed_rows(), "one", jobs=1) - two, out2 = self.build(mixed_rows(), "two", jobs=2) - one.pop("spawn"), two.pop("spawn") - for c in one["chunks"] + two["chunks"]: - c.pop("url") - self.assertEqual(one, two) - for c in one["chunks"]: - with open(os.path.join(out1, "chunks", c["id"] + ".glb"), "rb") as f1, \ - open(os.path.join(out2, "chunks", c["id"] + ".glb"), "rb") as f2: - self.assertEqual(f1.read(), f2.read()) - - def test_missing_model_file_is_counted(self): - os.remove(os.path.join(self.assets, "levels", "models", "box.obj")) - with self.assertRaisesRegex(ValueError, "could be placed"): - self.build([twp.entity("test_box", (10, 10, 0))]) - self.assertFalse(os.path.exists(os.path.join(self.tmp, "world", "world.json"))) - - def test_pack_cache_is_removed(self): - _, out = self.build([twp.entity("test_box", (10, 10, 0))]) - self.assertEqual(sorted(os.listdir(out)), ["chunks", "world.json"]) - - def test_textured_instances_embed_the_texture_once(self): - assets = os.path.join(self.tmp, "tex_assets") - twb._write_param_fixture(assets, twb.PARAM_CASES["albedo-first"]) - ents = os.path.join(self.tmp, "tex.jsonl") - twp.write_entities(ents, [twp.entity("tri", (10 + i, 10, 0)) for i in range(5)]) - out = os.path.join(self.tmp, "tex_world") - doc = world_build.build_world(assets, out, placements=ents) - self.assertEqual(doc["stats"]["textures_embedded"], 1) - glb = os.path.join(out, "chunks", doc["chunks"][0]["id"] + ".glb") - _, rgba = twb._glb_first_base_color_pixel(glb) - self.assertEqual(rgba, tuple(twb.ALBEDO_RGBA)) - gltf, _ = read_chunk(out, doc["chunks"][0]["id"]) - self.assertEqual((len(gltf["images"]), len(gltf["meshes"])), (1, 1)) - - def test_texture_cache_respects_each_build_size(self) -> None: - assets = os.path.join(self.tmp, "tex_assets") - twb._write_param_fixture(assets, twb.PARAM_CASES["albedo-first"]) - ents = os.path.join(self.tmp, "tex.jsonl") - twp.write_entities(ents, [twp.entity("tri", (10, 10, 0))]) - - for limit, expected in ((1, 1), (0, 4), (2, 2)): - with self.subTest(limit=limit): - out = os.path.join(self.tmp, f"world_{limit}") - doc = world_build.build_world(assets, out, placements=ents, jobs=1, max_tex_size=limit) - gltf, bin_data = read_chunk(out, doc["chunks"][0]["id"]) - (image,) = gltf["images"] - view = gltf["bufferViews"][image["bufferView"]] - start = view.get("byteOffset", 0) - width, height, rgba = twb.parse_and_validate_png(bin_data[start:start + view["byteLength"]]) - self.assertEqual((width, height), (expected, expected)) - self.assertEqual(tuple(rgba[:4]), tuple(twb.ALBEDO_RGBA)) - - def test_rebuild_embeds_changed_texture_at_the_same_path(self) -> None: - assets = os.path.join(self.tmp, "tex_assets") - twb._write_param_fixture(assets, twb.PARAM_CASES["albedo-first"]) - ents = os.path.join(self.tmp, "tex.jsonl") - twp.write_entities(ents, [twp.entity("tri", (10, 10, 0))]) - out = os.path.join(self.tmp, "tex_world") - dds = os.path.join(assets, "models", "tri_tex", "001_albedo.dds") - - for color in (tuple(twb.ALBEDO_RGBA), (25, 90, 175, 255)): - with self.subTest(color=color): - with open(dds, "wb") as texture: - texture.write(twb._uniform_bgra_dds(color)) - doc = world_build.build_world(assets, out, placements=ents, jobs=1) - glb = os.path.join(out, "chunks", doc["chunks"][0]["id"] + ".glb") - _, rgba = twb._glb_first_base_color_pixel(glb) - self.assertEqual(rgba, color) - - def test_cli_instancing_option(self): - ents = os.path.join(self.tmp, "cli.jsonl") - twp.write_entities(ents, [twp.entity("test_box", (10, 10, 0))]) - out = os.path.join(self.tmp, "cli") - import contextlib - import io - buf = io.StringIO() - with contextlib.redirect_stdout(buf): - rc = world_build.main([self.assets, "--out", out, "--no-textures", "--placements", ents, - "--instancing", "nodes"]) - self.assertEqual(rc, 0) - self.assertIn("placements", buf.getvalue()) - with open(os.path.join(out, "world.json"), encoding="utf-8") as f: - self.assertEqual(json.load(f)["instancing"], "nodes") - - -class LodSetsTest(unittest.TestCase): - def test_bands_follow_the_parent_child_distances(self): - child = {1: [120, 130, 140], 2: [450], 3: [1000], 4: [1976], 6: [6000]} - own = {0: [124], 1: [450], 2: [1000], 3: [2000], 4: [4000], 5: [900, 1100], 6: [20000]} - bands, measured = world_build.lod_bands(child, own, [0, 1, 2, 3, 4, 5, 6]) - self.assertEqual(bands, {"hd": [0.0, 130.0], "lod": [130.0, 450.0], "slod1": [450.0, 1000.0], - "slod2": [1000.0, 1976.0], "slod3": [1976.0, 6000.0], "slod4": [6000.0, 20000.0], - "orphan_hd": [0.0, 1000.0]}) - self.assertEqual(measured["lod"]["child_lod_dist_median"], 130.0) - - def test_missing_tiers_still_give_contiguous_bands(self): - bands, _ = world_build.lod_bands({2: [450]}, {2: [1000]}, [0, 2]) - self.assertEqual(bands, {"hd": [0.0, 450.0], "slod1": [450.0, 1000.0]}) - - def build(self, rows, **kw): - tmp = tempfile.mkdtemp() - self.addCleanup(lambda: shutil.rmtree(tmp, ignore_errors=True)) - assets = twp.write_assets(tmp) - ents = os.path.join(tmp, "e.jsonl") - twp.write_entities(ents, rows) - out = os.path.join(tmp, "w") - return world_build.build_world(assets, out, placements=ents, textures=False, **kw), out - - def lod_row(self, pos, lod, child=None, own=None): - r = twp.entity("test_box", pos, lod=lod) - r["child_lod_dist"] = child - r["lod_dist"] = own - return r - - def test_one_chunk_per_tier_and_cell(self): - rows = [self.lod_row((10, 10, 0), 0, own=-1.0), self.lod_row((12, 10, 0), 0), - self.lod_row((10, 10, 0), 1, child=130.0, own=450.0), self.lod_row((10, 10, 0), 2, child=450.0, own=1000.0), - self.lod_row((300, 10, 0), 5, own=800.0)] - doc, out = self.build(rows, lod_sets=True, lod_levels=world_build.ALL_LOD_LEVELS) - ids = sorted(c["id"] for c in doc["chunks"]) - self.assertEqual(ids, ["c_hd_0_-1", "c_lod_0_-1", "c_orphan_hd_1_-1", "c_slod1_0_-1"]) - by = {c["id"]: c for c in doc["chunks"]} - self.assertEqual(by["c_hd_0_-1"]["cell"], [0.0, -256.0, 256.0, 0.0]) - self.assertEqual(by["c_hd_0_-1"]["lod"], "hd") - self.assertEqual(by["c_hd_0_-1"]["models"], 2) - self.assertEqual(doc["lod_bands"], {"hd": [0.0, 130.0], "lod": [130.0, 450.0], "slod1": [450.0, 1000.0], - "orphan_hd": [0.0, 800.0]}) - self.assertEqual(doc["stats"]["lod_tiers"]["hd"]["placements"], 2) - with open(os.path.join(out, "world.json"), encoding="utf-8") as f: - self.assertEqual(json.load(f)["lod_bands"]["lod"], [130.0, 450.0]) - - def test_export_uses_finer_lod_distance_when_child_distance_is_missing(self) -> None: - rows = [self.lod_row((10, 10, 0), 0, own=120.0), - self.lod_row((10, 10, 0), 1, own=450.0)] - _, out = self.build(rows, lod_sets=True, lod_levels=(0, 1)) - with open(os.path.join(out, "world.json"), encoding="utf-8") as handle: - world = json.load(handle) - self.assertEqual(sorted(chunk["lod"] for chunk in world["chunks"]), ["hd", "lod"]) - for chunk in world["chunks"]: - self.assertTrue(os.path.isfile(os.path.join(out, "chunks", f'{chunk["id"]}.glb'))) - self.assertEqual(world["lod_bands"], {"hd": [0.0, 120.0], "lod": [120.0, 450.0]}) - - def test_option_rules(self): - with self.assertRaisesRegex(ValueError, "lod-sets needs --instancing"): - self.build([self.lod_row((0, 0, 0), 0)], lod_sets=True, instancing="bake") - with tempfile.TemporaryDirectory() as tmp: - assets = twp.write_assets(tmp) - with self.assertRaisesRegex(ValueError, "lod-sets needs --placements"): - world_build.build_world(assets, os.path.join(tmp, "w"), lod_sets=True) - - def test_cli_rejects_unnamed_lod_levels_with_lod_sets(self): - import contextlib - import io - with tempfile.TemporaryDirectory() as tmp: - assets = twp.write_assets(tmp) - ents = os.path.join(tmp, "e.jsonl") - twp.write_entities(ents, [self.lod_row((10, 10, 0), level) for level in (7, 255)]) - out = os.path.join(tmp, "w") - for level in (7, 255): - with self.subTest(level=level), contextlib.redirect_stderr(io.StringIO()) as stderr: - result = world_build.main([assets, "--out", out, "--no-textures", "--placements", ents, - "--lod-sets", "--lod-levels", f"0,{level}"]) - self.assertEqual(result, 1) - self.assertIn(f"--lod-sets does not recognize lodLevel {level}", stderr.getvalue()) - self.assertFalse(os.path.exists(out)) - - def test_unnamed_lod_levels_work_without_lod_sets(self): - rows = [self.lod_row((10, 10, 0), level) for level in (7, 255)] - doc, _ = self.build(rows, lod_levels=(7, 255)) - self.assertEqual(doc["stats"]["placements"]["placed"], 2) - self.assertNotIn("lod_bands", doc) - - def test_cli_places_every_level_with_lod_sets(self): - import contextlib - import io - with tempfile.TemporaryDirectory() as tmp: - assets = twp.write_assets(tmp) - ents = os.path.join(tmp, "e.jsonl") - twp.write_entities(ents, [self.lod_row((10, 10, 0), 0), self.lod_row((10, 10, 0), 3, child=1000.0)]) - out = os.path.join(tmp, "w") - with contextlib.redirect_stdout(io.StringIO()): - self.assertEqual(world_build.main([assets, "--out", out, "--no-textures", "--placements", ents, - "--lod-sets"]), 0) - with open(os.path.join(out, "world.json"), encoding="utf-8") as f: - self.assertEqual(sorted(json.load(f)["lod_bands"]), ["hd", "slod2"]) - self.assertEqual(world_build.main([assets, "--out", out, "--no-textures", "--placements", ents, - "--lod-sets", "--lod-levels", "0"]), 0) - with open(os.path.join(out, "world.json"), encoding="utf-8") as f: - self.assertEqual(sorted(json.load(f)["lod_bands"]), ["hd"]) - - def test_prune_stale_chunks_removes_obsolete_lod_set_chunks(self): - import contextlib - import io - with tempfile.TemporaryDirectory() as tmp: - chunks_dir = os.path.join(tmp, "direct_chunks") - os.makedirs(chunks_dir) - for name in ("c_hd_0_-1.glb", "c_lod_0_-1.glb", "c_slod2_0_-1.glb", - "c_orphan_hd_1_-1.glb", "c_hd_0_-1.glb.tmp", "c_0_-1.glb", "unrelated.glb"): - with open(os.path.join(chunks_dir, name), "wb") as f: - f.write(b"x") - world_build._prune_stale_chunks(chunks_dir, {"c_hd_0_-1.glb"}) - self.assertEqual(sorted(os.listdir(chunks_dir)), ["c_hd_0_-1.glb", "unrelated.glb"]) - - assets = twp.write_assets(tmp) - ents = os.path.join(tmp, "e.jsonl") - twp.write_entities(ents, [self.lod_row((10, 10, 0), 0), self.lod_row((10, 10, 0), 3, child=1000.0)]) - out = os.path.join(tmp, "w") - out_chunks = os.path.join(out, "chunks") - with contextlib.redirect_stdout(io.StringIO()): - self.assertEqual(world_build.main([assets, "--out", out, "--no-textures", "--placements", ents, - "--lod-sets"]), 0) - self.assertEqual(sorted(os.listdir(out_chunks)), ["c_hd_0_-1.glb", "c_slod2_0_-1.glb"]) - # Narrowing --lod-levels must prune the obsolete slod2 chunk. - self.assertEqual(world_build.main([assets, "--out", out, "--no-textures", "--placements", ents, - "--lod-sets", "--lod-levels", "0"]), 0) - self.assertEqual(sorted(os.listdir(out_chunks)), ["c_hd_0_-1.glb"]) - # Switching to a non-LOD build must prune the obsolete c_hd_* chunk. - self.assertEqual(world_build.main([assets, "--out", out, "--no-textures", "--placements", ents, - "--lod-levels", "0"]), 0) - self.assertEqual(sorted(os.listdir(out_chunks)), ["c_0_-1.glb"]) - # Rebuilding with --lod-sets and then --limit 0 must clear all LOD chunks. - self.assertEqual(world_build.main([assets, "--out", out, "--no-textures", "--placements", ents, - "--lod-sets"]), 0) - self.assertEqual(world_build.main([assets, "--out", out, "--no-textures", "--placements", ents, - "--lod-sets", "--limit", "0"]), 0) - self.assertEqual(os.listdir(out_chunks), []) - - -class IterPlacementsTest(unittest.TestCase): - def test_same_rows_and_counts_as_load_placements(self): - good = [twp.entity("test_box", (1, 2, 3), sxy=2.0, sz=3.0), twp.entity("test_box", (9, 8, 7), lod=5), - twp.entity("test_box", (5, 5, 5), lod=1), twp.entity("test_box", (500, 5, 5))] - odd = [dict(twp.entity("test_box", (4, 5, 6)), lod_level=[]), - dict(twp.entity("test_box", (4, 5, 6)), position=[10 ** 400, 0, 0]), - dict(twp.entity("test_box", (4, 5, 6)), scale_xy="2.0", scale_z=10 ** 400)] - with tempfile.TemporaryDirectory() as tmp: - path = os.path.join(tmp, "e.jsonl") - twp.write_entities(path, good + odd, extra_lines=["{not json"]) - for kw in ({}, {"lod_levels": (0, 1)}, {"region": (0, 0, 100, 100)}): - rows, counts = world_build.load_placements(path, **kw) - c2 = world_build._placement_counts() - rows2 = list(world_build.iter_placements(path, c2, **kw)) - self.assertEqual(rows2, rows, kw) - self.assertEqual(c2, counts, kw) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/test_world_interior_names.py b/tests/test_world_interior_names.py deleted file mode 100644 index 9766b35e5..000000000 --- a/tests/test_world_interior_names.py +++ /dev/null @@ -1,426 +0,0 @@ -"""Tests for tools/world_interior_names.py, built from synthetic 0x7a resources (no game data). - - python -I tests/test_world_interior_names.py -""" -import io -import json -import math -import os -import struct -import sys -import tempfile -import unittest -import zlib -from contextlib import redirect_stdout - -ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) - - -# Imported by its real name: --jobs sends scan_window to worker processes, which import it by module name. -sys.path.insert(0, os.path.join(ROOT, "tools")) -import world_interior_names as T # noqa: E402 -WA, WI = T.WA, T.WI -J = WA.joaat_cs -SYS = 0x50000000 -S = math.sqrt(0.5) - - -def build(structs, blocks): - """A valid 0x7a resource. structs: [(hash, size, [(member hash, offset, type)])]; blocks: [(hash, bytes)].""" - st = 0x60 - p = st + 32 * len(structs) - member_at = [] - for _, _, members in structs: - member_at.append(p) - p += 16 * len(members) - bt = (p + 15) & ~15 - p = bt + 16 * len(blocks) - data_at = [] - for _, payload in blocks: - p = (p + 15) & ~15 - data_at.append(p) - p += len(payload) - b = bytearray(p + 16) - b[0x10:0x15] = b"0DRPz" - struct.pack_into(" bytes: - """A map resource with one entity that owns a light effect (one light, offset 1 m up).""" - r = Resource() - ent_members = [(M["position"], 0x00, 0x32), (M["rotation"], 0x10, 0x34), (M["scaleXY"], 0x20, 0x21), - (M["scaleZ"], 0x24, 0x21), (M["archetypeName"], 0x28, 0x4A), (M["extensions"], 0x30, 0x52)] - r.struct(T.ENTITY, 0x40, ent_members) - r.struct(T.MAPDATA, 0x10, [(M["name"], 0x00, 0x4A)]) - r.struct(T.LIGHT_EXT, EXT_SIZE, EXT_MEMBERS) - light_members = [m for m in LIGHT_MEMBERS if not posn_only or m[0] != M["position120"]] - r.struct(T.LIGHT, LIGHT_SIZE, light_members) - ent = bytearray(0x40) - s = math.sqrt(0.5) - struct.pack_into("<3f", ent, 0x00, 100.0, 200.0, 10.0) - struct.pack_into("<4f", ent, 0x10, 0.0, 0.0, s, s) # stored +90 degrees about Z: the entity turns -90 - struct.pack_into("<2f", ent, 0x20, scale_xy, scale_z) - struct.pack_into(" (0, -2, 3). - for a, b in zip(row["position"], (100.0, 198.0, 13.0)): - self.assertAlmostEqual(a, b, places=3) - for a, b in zip(row["direction"], (0.0, -1.0, 0.0)): - self.assertAlmostEqual(a, b, places=4) - self.assertEqual(row["archetype"], "cafef00d") - - def test_export_normalizes_the_stored_light_rotation(self) -> None: - resource = bytearray(map_resource()) - meta = T.Meta(resource) - (entity_offset,) = meta.objects(T.ENTITY) - rotation_offset = meta.off(T.ENTITY, "rotation") - assert rotation_offset is not None - struct.pack_into("<4f", resource, entity_offset + rotation_offset, 0.0, 0.0, 0.5, 0.5) - - (row,) = T.inspect_resource(resource, lights_out=True)["world_lights"] - self.assertEqual(row["position"], [100.0, 198.0, 13.0]) - self.assertEqual(row["direction"], [0.0, -1.0, 0.0]) - - def test_place_identity(self): - p, d = T.place([1.0, 2.0, 3.0], [0.0, 0.0, 1.0], [10.0, 0.0, 0.0], [0.0, 0.0, 0.0, 1.0], 1.0, 1.0) - self.assertEqual(p, [11.0, 2.0, 3.0]) - self.assertEqual(d, [0.0, 0.0, 1.0]) - - def test_unreferenced_effect_is_counted(self): - r = Resource() - r.struct(T.LIGHT_EXT, EXT_SIZE, EXT_MEMBERS) - r.struct(T.LIGHT, LIGHT_SIZE, LIGHT_MEMBERS) - eff = bytearray(EXT_SIZE) - struct.pack_into(" 1 and 1 -> 0 - self.assertEqual(s["num_links_matches_range"], 4) - self.assertEqual((s["components"], s["largest_component_nodes"]), (2, 3)) - self.assertEqual(s["isolated_nodes"], 1) - self.assertEqual((s["junction_nodes_resolved"], s["junction_entrances"]), (1, 3)) - self.assertEqual(s["junction_entrances_resolved"], 2) - self.assertEqual((s["signalised_junctions"], s["phases"], s["entrances_stop"]), (1, 2, 1)) - self.assertEqual(s["junction_nodes_flagged_junction"], 1) - self.assertEqual(hist["link_flag_bits"][10], 2) - self.assertEqual(hist["lanes_from"][0], 2) - # Even-sized samples take the stdlib median (the mean of the two middle - # values), not the upper-middle element lengths[len // 2] used before. - self.assertEqual(hist["link_length_m"], {"min": 10, "median": 25.0, "max": 40}) - self.assertEqual(hist["phase_duration_s"], {"min": 8.0, "median": 19.0, "max": 30.0}) - - -class ScanTest(unittest.TestCase): - def setUp(self): - self.tmp = tempfile.TemporaryDirectory() - self.rpf = os.path.join(self.tmp.name, "levels.rpf") - write_rpf(self.rpf, [light_resource(), map_resource(), node_resource(GRAPH_NODES), - link_resource(GRAPH_LINKS), junction_resource(100, [101], [5.0])]) - self.entities = os.path.join(self.tmp.name, "entities.jsonl") - with open(self.entities, "w", encoding="utf-8", newline="\n") as f: - for x in (0.0, 50.0): - f.write(json.dumps({"archetype": "a1b2c3d4", "position": [x, 0.0, 0.0], - "rotation": [0.0, 0.0, 0.0, 1.0], "scale_xy": 1.0, "scale_z": 1.0}) + "\n") - f.write(json.dumps({"archetype": "0badbeef", "position": [0, 0, 0], "rotation": [0, 0, 0, 1]}) + "\n") - - def tearDown(self): - self.tmp.cleanup() - - def test_a_truncated_rpf9_header_is_one_error_line(self) -> None: - # Before: scan() unpacked the data-start word from an unchecked 8-byte head, so a 5-byte "9FPR" file - # died in a struct.error traceback. A truncated header is a usage error: one ERROR line, exit 2. - short = os.path.join(self.tmp.name, "short.rpf") - with open(short, "wb") as f: - f.write(b"9FPR\x01") - err = io.StringIO() - with contextlib.redirect_stdout(io.StringIO()), contextlib.redirect_stderr(err): - rc = T.main([short]) - self.assertEqual(rc, 2) - self.assertIn(f"ERROR: {short}: the RPF9 header is 5 bytes, the format needs 8", err.getvalue()) - self.assertNotIn("Traceback", err.getvalue()) - self.assertNotIn("struct.error", err.getvalue()) - - def test_summary_write_failure_is_one_error_line(self) -> None: - # --out naming a directory: IsADirectoryError/PermissionError on most systems. The input half - # of main already answers with one ERROR line; the write half must too. - target = os.path.join(self.tmp.name, "as-a-directory") - os.makedirs(target) - err = io.StringIO() - with contextlib.redirect_stdout(io.StringIO()), contextlib.redirect_stderr(err): - rc = T.main([self.rpf, "--entities", self.entities, "--out", target]) - self.assertEqual(rc, 2) - self.assertIn("ERROR: cannot write", err.getvalue()) - self.assertNotIn("Traceback", err.getvalue()) - self.assertNotIn("IsADirectoryError", err.getvalue()) - self.assertNotIn("PermissionError", err.getvalue()) - - def test_lights_out_uses_posn_when_position120_is_absent(self) -> None: - archive = os.path.join(self.tmp.name, "posn-only.rpf") - write_rpf(archive, [light_resource(posn_only=True), map_resource(posn_only=True)]) - output = os.path.join(self.tmp.name, "posn-only.jsonl") - summary = os.path.join(self.tmp.name, "posn-only-summary.json") - with contextlib.redirect_stdout(io.StringIO()): - self.assertEqual(T.main([archive, "--entities", self.entities, "--out", summary, - "--lights-out", output]), 0) - with open(output, encoding="utf-8") as handle: - placements = [json.loads(line) for line in handle] - self.assertEqual([row["position"] for row in placements if row["owner"] == "entity"], - [[100.0, 198.0, 13.0]]) - self.assertEqual([row["position"] for row in placements if row["owner"] == "archetype"], - [[0.0, 0.0, 0.0], [0.0, 0.1, 0.0], [50.0, 0.0, 0.0], [50.0, 0.1, 0.0]]) - - def test_scan_and_summary(self): - total = T.scan(self.rpf) - summary = T.summarize(total, self.entities) - self.assertEqual(summary["light_resources"], 2) - self.assertEqual(summary["lights"]["lights"], 3) - self.assertEqual(summary["archetypes_with_lights"], 1) - self.assertEqual(summary["placement"]["entities"], 3) - self.assertEqual(summary["placement"]["entities_with_lights"], 2) - self.assertEqual(summary["placement"]["archetype_lights_placed"], 4) - self.assertEqual(summary["lane_graph"]["nodes"], 4) - self.assertEqual(summary["lane_graph"]["junctions"], 1) - self.assertEqual(summary["graph_resources"], {"junctions": 1, "links": 1, "nodes": 1}) - - def test_duplicate_light_definitions_compare_values_not_just_counts(self): - total = T.scan(self.rpf) - total["archetype_lights"] = { - 1: [[{"posn": [0, 1, 0]}], [{"posn": [0, 1, 0]}]], - 2: [[{"posn": [0, 1, 0]}], [{"posn": [1, 0, 0]}]], - 3: [[], [{"intensity": 2}]], - 4: [[{"intensity": 2}]], - } - summary = T.summarize(total) - self.assertEqual(summary["archetypes_defined_more_than_once"], 3) - self.assertEqual(summary["archetype_light_definitions_differ"], 2) - - def test_jobs_give_the_same_summary(self): - one = T.summarize(T.scan(self.rpf, jobs=1)) - two = T.summarize(T.scan(self.rpf, jobs=2)) - self.assertEqual(one, two) - - def test_cli_rejects_negative_start_before_scanning(self): - for start in ("-1", "-0x10"): - with self.subTest(start=start): - out = os.path.join(self.tmp.name, "summary.json") - err = io.StringIO() - with mock.patch.object(T, "scan", side_effect=AssertionError("unexpected scan")) as scan, \ - contextlib.redirect_stderr(err): - rc = T.main([self.rpf, f"--start={start}", "--out", out]) - scan.assert_not_called() - self.assertEqual(rc, 2) - self.assertIn("--start must be non-negative", err.getvalue()) - self.assertFalse(os.path.exists(out)) - - def test_cli_rejects_shared_report_destination(self): - out = os.path.join(self.tmp.name, "lights.json") - alias = os.path.join(self.tmp.name, ".", "lights.json") - err = io.StringIO() - with contextlib.redirect_stderr(err), self.assertRaises(SystemExit) as cm: - T.main([self.rpf, "--out", out, "--lights-out", alias]) - self.assertEqual(cm.exception.code, 2) - self.assertIn("--out and --lights-out must use different paths", err.getvalue()) - self.assertFalse(os.path.exists(out)) - - def test_cli_rejects_case_alias_before_scan_on_a_case_insensitive_volume(self): - marker = os.path.join(self.tmp.name, "case-check") - with open(marker, "w", encoding="utf-8"): - pass - if not os.path.exists(os.path.join(self.tmp.name, "CASE-CHECK")): - self.skipTest("test directory is case-sensitive") - original_files = set(os.listdir(self.tmp.name)) - - out = os.path.join(self.tmp.name, "lights.json") - alias = os.path.join(self.tmp.name, "LIGHTS.JSON") - err = io.StringIO() - # Exercise case-insensitive lookup without Windows's lexical normalization. - with mock.patch.object(T.os.path, "normcase", side_effect=lambda path: path), \ - mock.patch.object(T, "scan", side_effect=AssertionError("scan started before rejecting the alias")) as scan, \ - contextlib.redirect_stderr(err), \ - self.assertRaises(SystemExit) as cm: - T.main([self.rpf, "--out", out, "--lights-out", alias]) - scan.assert_not_called() - self.assertEqual(cm.exception.code, 2) - self.assertIn("--out and --lights-out must use different paths", err.getvalue()) - self.assertEqual(set(os.listdir(self.tmp.name)), original_files) - - def test_cli_writes_summary_and_placed_lights(self): - out = os.path.join(self.tmp.name, "summary.json") - lights = os.path.join(self.tmp.name, "lights.jsonl") - with contextlib.redirect_stdout(io.StringIO()): - rc = T.main([self.rpf, "--out", out, "--entities", self.entities, "--lights-out", lights]) - self.assertEqual(rc, 0) - with open(out, encoding="utf-8") as f: - summary = json.load(f) - limited = os.path.join(self.tmp.name, "limited.json") - limited_lights = os.path.join(self.tmp.name, "limited.jsonl") - with contextlib.redirect_stdout(io.StringIO()): - self.assertEqual(T.main([self.rpf, "--start", "0", "--limit", "0x1000", "--out", limited, - "--entities", self.entities, "--lights-out", limited_lights]), 0) - with open(limited, encoding="utf-8") as f: - self.assertEqual(json.load(f), summary) - with open(lights, encoding="utf-8") as f: - rows = [json.loads(line) for line in f] - self.assertEqual(len(rows), 1 + 4) # one entity light, 2 x 2 archetype lights - self.assertEqual(sorted(r["owner"] for r in rows), ["archetype"] * 4 + ["entity"]) - self.assertEqual(summary["placement"]["archetype_lights_placed"], 4) - xs = sorted(r["position"][0] for r in rows if r["owner"] == "archetype") - self.assertEqual(xs, [0.0, 0.0, 50.0, 50.0]) - - def test_cli_rejects_report_aliasing_an_input(self): - with open(self.rpf, "rb") as f: - rpf_bytes = f.read() - with open(self.entities, "rb") as f: - entities_bytes = f.read() - cases = [ - (["--out", self.rpf], "--out must use a different path than archive"), - (["--out", self.entities], "--out must use a different path than --entities"), - (["--lights-out", self.rpf], "--lights-out must use a different path than archive"), - (["--lights-out", self.entities], "--lights-out must use a different path than --entities"), - ] - for args, msg in cases: - err = io.StringIO() - with mock.patch.object(T, "scan", side_effect=AssertionError("scan started before rejecting the alias")) as scan, \ - contextlib.redirect_stderr(err), self.assertRaises(SystemExit) as cm: - T.main([self.rpf, "--entities", self.entities] + args) - scan.assert_not_called() - self.assertEqual(cm.exception.code, 2) - self.assertIn(msg, err.getvalue()) - with open(self.rpf, "rb") as f: - self.assertEqual(f.read(), rpf_bytes) - with open(self.entities, "rb") as f: - self.assertEqual(f.read(), entities_bytes) - - def test_light_export_preserves_zero_entity_scale(self) -> None: - write_rpf(self.rpf, [light_resource(), map_resource(scale_xy=0.0, scale_z=0.0)]) - lights = os.path.join(self.tmp.name, "zero-scale.jsonl") - with open(self.entities, "w", encoding="utf-8", newline="\n") as f: - for x, scales in ((10, {"scale_xy": 0.0, "scale_z": 0.0}), (20, {})): - f.write(json.dumps({"archetype": "a1b2c3d4", "position": [x, 0, 0], - "rotation": [0, 0, 0, 1], **scales}) + "\n") - - with contextlib.redirect_stdout(io.StringIO()): - self.assertEqual(T.main([self.rpf, "--entities", self.entities, "--lights-out", lights]), 0) - with open(lights, encoding="utf-8") as f: - rows = [json.loads(line) for line in f] - - self.assertEqual([row["owner"] for row in rows], ["entity", "archetype", "archetype", - "archetype", "archetype"]) - for row, position in zip(rows, ([100.0, 200.0, 10.0], [10.0, 0.0, 0.0], [10.0, 0.0, 0.0], - [20.0, 0.5, 2.5], [20.0, 0.0, 1.0])): - with self.subTest(owner=row["owner"], expected=position): - self.assertEqual(row["position"], position) - - def test_bad_entities_leaves_the_previous_lights_report_alone(self): - # --lights-out used to be opened (truncating it) before --entities was parsed. - lights = os.path.join(self.tmp.name, "lights.jsonl") - with open(lights, "w", encoding="utf-8", newline="\n") as f: - f.write('{"old": true}\n') - bad = os.path.join(self.tmp.name, "bad.jsonl") - with open(bad, "w", encoding="utf-8", newline="\n") as f: - f.write("{not json\n") - err = io.StringIO() - with contextlib.redirect_stderr(err): - rc = T.main([self.rpf, "--entities", bad, "--lights-out", lights]) - self.assertEqual(rc, 2) - with open(lights, encoding="utf-8") as f: - self.assertEqual(f.read(), '{"old": true}\n') - self.assertFalse(os.path.exists(lights + ".partial"), "a failed run left its staged report behind") - lines = err.getvalue().strip().splitlines() - self.assertEqual(len(lines), 1, lines) - self.assertIn("bad.jsonl", lines[0]) - self.assertNotIn("Traceback", err.getvalue()) - - def test_lights_report_that_is_a_directory_leaves_no_partial(self): - lights = os.path.join(self.tmp.name, "lights.jsonl") - os.makedirs(lights) - err = io.StringIO() - with contextlib.redirect_stderr(err): - rc = T.main([self.rpf, "--entities", self.entities, "--lights-out", lights]) - self.assertEqual(rc, 2) - self.assertFalse(os.path.exists(lights + ".partial"), "a failed replace left its staged report behind") - self.assertEqual(len(err.getvalue().strip().splitlines()), 1, err.getvalue()) - self.assertNotIn("Traceback", err.getvalue()) - - def test_bad_input_is_one_line(self): - err = io.StringIO() - with contextlib.redirect_stderr(err): - self.assertEqual(T.main([os.path.join(self.tmp.name, "missing.rpf")]), 2) - self.assertEqual(T.main([self.rpf, "--jobs", "0"]), 2) - self.assertEqual(T.main([self.rpf, "--entities", os.path.join(self.tmp.name, "none.jsonl")]), 2) - self.assertEqual(T.main([self.rpf, "--limit", "0"]), 2) - self.assertEqual(T.main([self.rpf, "--limit", "-1"]), 2) - lines = err.getvalue().strip().splitlines() - self.assertEqual(len(lines), 5) - self.assertEqual(lines[3], "ERROR: --limit must be at least 1") - self.assertEqual(lines[4], "ERROR: --limit must be at least 1") - - - def test_cli_refuses_malformed_entities_rows_before_the_scan(self): - good = '{"archetype": "a1b2c3d4", "position": [0.0, 0.0, 0.0], "rotation": [0.0, 0.0, 0.0, 1.0]}\n' - cases = [ - ("badjson", '{"archetype": "a1b2c3d4", "position": [0,0,0]\n', "not valid JSON"), - ("notjson", "garbage line\n", "not valid JSON"), - ("nonobject", "[1, 2, 3]\n", "not a JSON object"), - ("scalar", "123\n", "not a JSON object"), - ("badhex", '{"archetype": "zzz"}\n', "archetype is not a hex hash"), - ("unhashable", '{"archetype": {"x": 1}}\n', "archetype is not a hash:"), - ("shortrot", good.replace("[0.0, 0.0, 0.0, 1.0]", "[0.0, 0.0]"), "rotation is not 4 numbers"), - ("scalarpos", good.replace('"position": [0.0, 0.0, 0.0]', '"position": 5'), - "position is not 3 numbers"), - ("boolpos", good.replace('"position": [0.0, 0.0, 0.0]', '"position": [true, 0.0, 0.0]'), - "position is not 3 numbers"), - ("emptypos", good.replace('"position": [0.0, 0.0, 0.0]', '"position": []'), - "position is not 3 numbers"), - ("strscale", good.replace('1.0]}\n', '1.0], "scale_xy": "2"}\n'), "scale_xy is not a number"), - ] - for name, line, expected in cases: - with self.subTest(case=name): - ent = os.path.join(self.tmp.name, name + ".jsonl") - with open(ent, "w", encoding="utf-8", newline="\n") as f: - f.write(line) - err = io.StringIO() - with mock.patch.object(T, "scan", - side_effect=AssertionError("scan started before refusing the entities") - ) as scan, contextlib.redirect_stderr(err): - self.assertEqual(T.main([self.rpf, "--entities", ent]), 2) - scan.assert_not_called() - lines = err.getvalue().strip().splitlines() - self.assertEqual(len(lines), 1) - self.assertTrue(lines[0].startswith("ERROR: %s:1:" % ent), lines[0]) - self.assertIn(expected, lines[0]) - - def test_cli_refuses_non_utf8_entities_file(self): - ent = os.path.join(self.tmp.name, "binary.jsonl") - with open(ent, "wb") as f: - f.write(b"\xff\xfe binary garbage\n") - err = io.StringIO() - with mock.patch.object(T, "scan", - side_effect=AssertionError("scan started before refusing the entities")) as scan, \ - contextlib.redirect_stderr(err): - self.assertEqual(T.main([self.rpf, "--entities", ent]), 2) - scan.assert_not_called() - self.assertEqual(err.getvalue().strip().splitlines(), ["ERROR: %s: not UTF-8 text" % ent]) - - def test_malformed_entities_write_no_lights_file_or_summary(self): - ent = os.path.join(self.tmp.name, "late-bad.jsonl") - with open(ent, "w", encoding="utf-8", newline="\n") as f: - f.write('{"archetype": "a1b2c3d4", "position": [0.0, 0.0, 0.0], "rotation": [0.0, 0.0, 0.0, 1.0]}\n') - f.write('{"archetype": "zzz"}\n') - out = os.path.join(self.tmp.name, "never.json") - lights = os.path.join(self.tmp.name, "never.jsonl") - err = io.StringIO() - with contextlib.redirect_stderr(err): - self.assertEqual(T.main([self.rpf, "--out", out, "--entities", ent, "--lights-out", lights]), 2) - self.assertIn("archetype is not a hex hash", err.getvalue()) - self.assertFalse(os.path.exists(lights)) - self.assertFalse(os.path.exists(out)) - - def test_entities_rows_with_null_fields_and_blank_lines_are_accepted(self): - ent = os.path.join(self.tmp.name, "nulls.jsonl") - with open(ent, "w", encoding="utf-8", newline="\n") as f: - f.write("\n") - f.write(json.dumps({"archetype": "a1b2c3d4", "position": None, "rotation": None, - "scale_xy": None, "scale_z": None}) + "\n") - out = os.path.join(self.tmp.name, "nulls.json") - with contextlib.redirect_stdout(io.StringIO()): - self.assertEqual(T.main([self.rpf, "--out", out, "--entities", ent]), 0) - with open(out, encoding="utf-8") as f: - summary = json.load(f) - self.assertEqual(summary["placement"]["entities"], 1) - self.assertEqual(summary["placement"]["entities_with_lights"], 1) - self.assertEqual(summary["placement"]["archetype_lights_placed"], 2) - - -class GraphStatsFirstLinkTest(unittest.TestCase): - @staticmethod - def _node(idx, first_link): - return { - "address": (0, idx), "key": 100 + idx, "first_link": first_link, "num_links": 0, - "flags": 0, "road_class": 0, "kind": 0, "density": 0, - "speed": 10.0, "street": "", "position": [0.0, 0.0, 0.0], - } - - def test_graph_stats_handles_none_first_link_without_type_error(self): - # Integer followed by None used to crash with TypeError in firsts[i] <= firsts[i + 1]. - s_mixed, _ = T.graph_stats([self._node(0, 0), self._node(1, None)], [], []) - self.assertEqual(s_mixed["first_link_monotonic"], 0) - # A single node with None first_link must not vacuously report monotonic=1. - s_single_none, _ = T.graph_stats([self._node(0, None)], [], []) - self.assertEqual(s_single_none["first_link_monotonic"], 0) - s_leading_none, _ = T.graph_stats([self._node(0, None), self._node(1, 0)], [], []) - self.assertEqual(s_leading_none["first_link_monotonic"], 0) - s_ok, _ = T.graph_stats([self._node(0, 0), self._node(1, 0), self._node(2, 2)], [], []) - self.assertEqual(s_ok["first_link_monotonic"], 1) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/test_world_names.py b/tests/test_world_names.py deleted file mode 100644 index ceb2dc92b..000000000 --- a/tests/test_world_names.py +++ /dev/null @@ -1,593 +0,0 @@ -"""Synthetic tests for tools/world_names.py (no game data). - - python -I tests/test_world_names.py -""" -import contextlib -import importlib.util -import io -import json -import os -import tempfile -import unittest -from unittest import mock - -ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) - - -def load_tool(): - path = os.path.join(ROOT, "tools", "world_names.py") - spec = importlib.util.spec_from_file_location("world_names_under_test", path) - module = importlib.util.module_from_spec(spec) - spec.loader.exec_module(module) - return module - - -WN = load_tool() - - -class ManifestEnumerationTest(unittest.TestCase): - def test_an_unreadable_subtree_does_not_replace_the_dictionary(self): - with tempfile.TemporaryDirectory() as directory: - manifests = os.path.join(directory, "manifests") - os.mkdir(manifests) - blocked = os.path.join(manifests, "blocked") - output = os.path.join(directory, "dictionary.json") - with open(output, "wb") as f: - f.write(b"existing dictionary") - names = os.path.join(directory, "names.txt") - with open(names, "w", encoding="utf-8", newline="\n") as f: - f.write("synthetic_model\n") - - def walk(root, onerror=None): - if onerror: - onerror(PermissionError(13, "Permission denied", blocked)) - return iter(()) - - with mock.patch.object(WN.os, "walk", walk), contextlib.redirect_stderr(io.StringIO()) as err, \ - contextlib.redirect_stdout(io.StringIO()): - self.assertEqual(WN.main(["build", "--manifest", manifests, "--names", names, "--out", output]), 1) - self.assertIn(blocked, err.getvalue()) - with open(output, "rb") as f: - self.assertEqual(f.read(), b"existing dictionary") - - -class HashTest(unittest.TestCase): - def test_joaat_case_sensitive_field_names(self): - # Confirmed by the 0x7a schema member tables. - self.assertEqual(WN.joaat("CMapData", case_sensitive=True), 0xD3593FA6) - self.assertEqual(WN.joaat("CEntityDef", case_sensitive=True), 0xCE501483) - self.assertEqual(WN.joaat("archetypeName", case_sensitive=True), 0xA023A02C) - self.assertEqual(WN.joaat("name", case_sensitive=True), 0xE6E17F14) - self.assertEqual(WN.joaat("parent", case_sensitive=True), 0xA99C4651) - - def test_joaat_is_case_insensitive_by_default(self): - self.assertEqual(WN.joaat("PLAYER"), WN.joaat("player")) - self.assertNotEqual(WN.joaat("PLAYER", case_sensitive=True), - WN.joaat("player", case_sensitive=True)) - - def test_murmur3_known_vectors(self): - self.assertEqual(WN.murmur3_x64_128(b""), (0, 0)) - self.assertEqual(WN.murmur3_x64_128(b"hello"), - (0xCBD8A7B341BD9B02, 0x5B1E906A48AE1D19)) - self.assertEqual(WN.murmur3_x64_128(b"The quick brown fox jumps over the lazy dog"), - (0xE34BBC7BBC071B6C, 0x7A433CA9C49A9347)) - - def test_key64_is_low_murmur_word(self): - name = "synthetic_key_64" - self.assertEqual(WN.hash64(name), WN.murmur3_x64_128(name.encode())[0]) - - def test_u64_parse_and_format(self): - self.assertEqual(WN.parse_u64(0x1122334455667788), 0x1122334455667788) - self.assertEqual(WN.parse_u64("0x1122334455667788"), 0x1122334455667788) - self.assertEqual(WN.parse_u64("1122334455667788"), 0x1122334455667788) - self.assertEqual(WN.parse_u64(None), None) - self.assertEqual(WN.format_u64(0xAB), "00000000000000ab") - - -class DictionaryTest(unittest.TestCase): - def setUp(self): - self.tmp = tempfile.TemporaryDirectory() - self.dir = self.tmp.name - - def tearDown(self): - self.tmp.cleanup() - - def write(self, name, text): - path = os.path.join(self.dir, name) - with open(path, "w", encoding="utf-8") as handle: - handle.write(text) - return path - - def test_build_from_all_sources(self): - manifest = self.write("manifest.json", json.dumps({ - "Items": [ - {"Name": "synthetic_prop.#dr"}, - {"Name": "synthetic_prop_lod.#ft"}, - ] - })) - scan = self.write("scan.json", json.dumps({ - "entries": [{"Path": "recovered/models/synthetic_cell_a._dr_at_0000000000000010.r9modeldata"}] - })) - names = self.write("names.txt", "synthetic_name_a\n# comment\nsynthetic_name_b\n") - xml = self.write("common.xml", - "platform:/levels/synthetic/synthetic_cell_b.rpf" - "SyntheticCellC") - dictionary = WN.build_dictionary([manifest], [scan], [names], [xml]) - counts = dictionary.counts() - self.assertEqual(counts["exact_names"], 8) - self.assertEqual(counts["exact_hashes"], 8) - self.assertEqual(counts["exact_collisions"], 0) - for name in ("synthetic_prop", "synthetic_prop_lod", "synthetic_cell_a", - "synthetic_name_a", "synthetic_name_b", "synthetic_cell_b", - "synthetic_cell_b.rpf", "SyntheticCellC"): - self.assertIn(name, WN._unique_names(dictionary.names)) - - def test_rpf9_names_index(self): - index = self.write("rpf9_names.json", json.dumps({ - "summary": {"types": ["dr", "ft"]}, - "files": [ - {"offset": 16, "names": ["synthetic_tile_01_lod.#dr", "synthetic_tile_02_lod.#dr"]}, - {"offset": 64, "names": ["synthetic_frag.#ft"]}, - {"offset": 96, "names": "not a list"}, - ], - })) - dictionary = WN.build_dictionary(rpf9_names=[index]) - self.assertEqual(WN._unique_names(dictionary.names), - {"synthetic_tile_01_lod", "synthetic_tile_02_lod", "synthetic_frag"}) - with contextlib.redirect_stdout(io.StringIO()): - self.assertEqual(WN.main(["build", "--rpf9-names", index, - "--out", os.path.join(self.dir, "names.json")]), 0) - - def test_directory_manifest_discovery(self): - models = os.path.join(self.dir, "assets", "archive", "models") - os.makedirs(models) - path = os.path.join(models, "manifest.json") - with open(path, "w", encoding="utf-8") as handle: - json.dump({"Items": [{"Name": "synthetic_dir_model.#dr"}]}, handle) - dictionary = WN.build_dictionary([os.path.join(self.dir, "assets")]) - self.assertIn("synthetic_dir_model", WN._unique_names(dictionary.names)) - - def test_collision_is_ambiguous_without_key64_and_resolved_with_it(self): - dictionary = WN.NameDictionary() - dictionary.add("PLAYER") - dictionary.add("player") - self.assertEqual(dictionary.counts()["exact_collisions"], 1) - h = WN.joaat("player") - ambiguous = dictionary.match(h) - self.assertEqual(ambiguous["status"], "ambiguous") - resolved = dictionary.match(h, WN.hash64("player")) - self.assertEqual(resolved["status"], "resolved") - self.assertEqual(resolved["name"], "player") - self.assertIn("PLAYER", resolved["rejected"]) - resolved_upper = dictionary.match(h, WN.hash64("PLAYER")) - self.assertEqual(resolved_upper["name"], "PLAYER") - - def test_derived_lod_names_are_separate(self): - dictionary = WN.NameDictionary() - dictionary.add("synthetic_lod_base") - self.assertEqual(dictionary.derive_lod(), 2) - h = WN.joaat("synthetic_lod_base_lod") - without = dictionary.match(h, WN.hash64("synthetic_lod_base_lod")) - self.assertEqual(without["status"], "unresolved") - with_derived = dictionary.match(h, WN.hash64("synthetic_lod_base_lod"), - include_derived=True) - self.assertEqual(with_derived["status"], "resolved") - self.assertTrue(with_derived["derived"]) - self.assertEqual(with_derived["name"], "synthetic_lod_base_lod") - - def test_json_roundtrip(self): - dictionary = WN.NameDictionary() - dictionary.add("synthetic_roundtrip") - dictionary.derive_lod() - restored = WN.NameDictionary.from_json(json.loads(json.dumps(dictionary.to_json()))) - self.assertEqual(restored.counts()["exact_names"], 1) - self.assertEqual(restored.counts()["derived_names"], 2) - self.assertEqual(restored.match(WN.joaat("synthetic_roundtrip"))["name"], - "synthetic_roundtrip") - - -class ResolveTest(unittest.TestCase): - def setUp(self): - self.dictionary = WN.NameDictionary() - for name in ("synthetic_map_cell", "synthetic_parent_cell", "synthetic_prop", - "synthetic_lod_base"): - self.dictionary.add(name) - self.dictionary.derive_lod() - - def test_map_rows(self): - rows = [ - {"offset": 1, "map_name": WN.joaat("synthetic_map_cell"), - "parent": WN.joaat("synthetic_parent_cell"), - "map_name64": WN.format_u64(WN.hash64("synthetic_map_cell"))}, - {"offset": 2, "map_name": WN.joaat("synthetic_parent_cell"), "parent": 0}, - {"offset": 3, "kind": "meta"}, - ] - stats = WN.resolve_maps(rows, self.dictionary) - self.assertEqual(stats["rows"], 2) - self.assertEqual(stats["name_present"], 2) - self.assertEqual(stats["name_resolved"], 2) - self.assertEqual(stats["name_verified"], 1) - self.assertEqual(stats["parent_present"], 1) - self.assertEqual(stats["parent_resolved"], 1) - self.assertEqual(stats["parent_links"], 1) - self.assertEqual(stats["parent_links_resolved"], 1) - - def test_map_64_mismatch_is_unconfirmed(self): - rows = [{"map_name": WN.joaat("synthetic_map_cell"), - "map_name64": WN.format_u64(WN.hash64("synthetic_map_cell") + 1)}] - stats = WN.resolve_maps(rows, self.dictionary) - self.assertEqual(stats["name_resolved"], 0) - self.assertEqual(stats["name_unconfirmed"], 1) - - def test_archetype_counts(self): - exact = "synthetic_prop" - derived = "synthetic_lod_base_lod" - data = { - "archetypes": { - f"{WN.joaat(exact):08x}": 7, - f"{WN.joaat(derived):08x}": 3, - f"{WN.joaat('synthetic_missing'):08x}": 2, - }, - "keys": { - f"{WN.joaat(exact):08x}": WN.format_u64(WN.hash64(exact)), - f"{WN.joaat(derived):08x}": WN.format_u64(WN.hash64(derived)), - }, - } - stats = WN.resolve_archetypes(data, self.dictionary, include_derived=True) - self.assertEqual(stats["entities"], 12) - self.assertEqual(stats["unique_hashes"], 3) - self.assertEqual(stats["resolved_exact_entities"], 7) - self.assertEqual(stats["resolved_derived_entities"], 3) - self.assertEqual(stats["verified_entities"], 10) - self.assertEqual(stats["unresolved_entities"], 2) - - def test_archetype_counts_skip_overflowing_values(self): - name = WN.joaat_hex("synthetic_prop") - data = json.loads(f'{{"archetypes":{{"00000100":1e309,"00000200":-1e309,"{name}":7}}}}') - - stats = WN.resolve_archetypes(data, self.dictionary) - - self.assertEqual(stats["entities"], 7) - self.assertEqual(stats["unique_hashes"], 1) - self.assertEqual(stats["resolved_exact_entities"], 7) - - def test_archetype_32_only_is_rejected_by_key64(self): - dictionary = WN.NameDictionary() - dictionary.add("PLAYER") - dictionary.add("player") - h = WN.joaat("player") - stats = WN.resolve_archetypes( - {"archetypes": {f"{h:08x}": 4}, "keys": {f"{h:08x}": WN.format_u64(WN.hash64("player"))}}, - dictionary) - self.assertEqual(stats["resolved_exact_entities"], 4) - self.assertEqual(stats["unconfirmed_entities"], 0) - wrong = WN.resolve_archetypes( - {"archetypes": {f"{h:08x}": 4}, "keys": {f"{h:08x}": WN.format_u64(WN.hash64("PLAYER") + 1)}}, - dictionary) - self.assertEqual(wrong["unconfirmed_entities"], 4) - - -class CliTest(unittest.TestCase): - def test_write_json_preserves_existing_temp_sibling(self): - with tempfile.TemporaryDirectory() as tmp: - out = os.path.join(tmp, "names.json") - sibling = out + ".tmp" - with open(sibling, "w", encoding="utf-8") as f: - f.write("keep me") - - WN._write_json(out, {"names": {}}) - - with open(sibling, encoding="utf-8") as f: - self.assertEqual(f.read(), "keep me") - with open(out, encoding="utf-8") as f: - self.assertEqual(json.load(f), {"names": {}}) - self.assertCountEqual(os.listdir(tmp), ["names.json", "names.json.tmp"]) - - def test_xml_unterminated_comment_keeps_later_files(self): - with tempfile.TemporaryDirectory() as tmp: - xml = os.path.join(tmp, "concat.xml") - with open(xml, "w", encoding="utf-8") as handle: - handle.write("First" - "A&B\n" - '' - "levels/Cell&Prop.rpf") - with contextlib.redirect_stdout(io.StringIO()): - self.assertEqual(WN.main(["build", "--xml", xml, "--out", out]), 0) - with open(out, encoding="utf-8") as handle: - names = json.load(handle)["names"] - self.assertEqual(names, {WN.joaat_hex(name): [name] - for name in ("A&B", "Cell&Prop", "Cell&Prop.rpf")}) - - def test_xml_names_require_matching_end_tags_in_fragments(self): - fragment = ( - b"WrongElementWrongCase" - b"WrongPrefixUnclosed" - b"GoodOneGoodTwo" - b"GoodThree" - ) - with tempfile.TemporaryDirectory() as tmp: - xml = os.path.join(tmp, "fragment.xml") - with open(xml, "wb") as handle: - handle.write(fragment) - dictionary = WN.NameDictionary() - self.assertEqual(dictionary.add_xml(xml), 3) - names = dictionary.to_json()["names"] - self.assertEqual(sorted(name for group in names.values() for name in group), - ["GoodOne", "GoodThree", "GoodTwo"]) - - def test_resolve_rejects_a_malformed_dictionary(self): - with tempfile.TemporaryDirectory() as tmp: - dictionary = os.path.join(tmp, "names.json") - out = os.path.join(tmp, "report.json") - for field, data in (("names", [1]), ("derived", {"00000000": "name"}), - ("names", {"00000000": [42]})): - with self.subTest(field=field, data=data): - with open(dictionary, "w", encoding="utf-8") as handle: - json.dump({"format": 1, field: data}, handle) - err = io.StringIO() - with contextlib.redirect_stderr(err), contextlib.redirect_stdout(io.StringIO()): - self.assertNotEqual(WN.main(["resolve", "--dict", dictionary, "--out", out]), 0) - self.assertIn(dictionary, err.getvalue()) - self.assertIn(field, err.getvalue()) - self.assertFalse(os.path.exists(out)) - - def test_resolve_rejects_unrecognized_map_report(self): - with tempfile.TemporaryDirectory() as tmp: - dictionary = os.path.join(tmp, "names.json") - maps = os.path.join(tmp, "wrong.json") - out = os.path.join(tmp, "report.json") - with open(dictionary, "w", encoding="utf-8") as handle: - json.dump(WN.NameDictionary().to_json(), handle) - with open(maps, "w", encoding="utf-8") as handle: - json.dump({"summary": {}}, handle) - err = io.StringIO() - with contextlib.redirect_stderr(err): - self.assertNotEqual(WN.main(["resolve", "--dict", dictionary, "--maps", maps, "--out", out]), 0) - self.assertIn(maps, err.getvalue()) - self.assertFalse(os.path.exists(out)) - - def test_resolve_requires_a_recognized_archetype_table(self): - with tempfile.TemporaryDirectory() as tmp: - dictionary = os.path.join(tmp, "names.json") - archetypes = os.path.join(tmp, "archetypes.json") - out = os.path.join(tmp, "report.json") - with open(dictionary, "w", encoding="utf-8", newline="\n") as f: - json.dump(WN.NameDictionary().to_json(), f) - - args = ["resolve", "--dict", dictionary, "--archetypes", archetypes, "--out", out] - for wrong in ([], {"summary": {}}, {"archetypes": []}): - with self.subTest(report=wrong): - with open(archetypes, "w", encoding="utf-8", newline="\n") as f: - json.dump(wrong, f) - stdout, stderr = io.StringIO(), io.StringIO() - with contextlib.redirect_stdout(stdout), contextlib.redirect_stderr(stderr): - self.assertEqual(WN.main(args), 1) - self.assertIn(archetypes, stderr.getvalue()) - self.assertEqual(stdout.getvalue(), "") - self.assertFalse(os.path.exists(out)) - - for field in ("archetypes", "hashes"): - with self.subTest(field=field): - with open(archetypes, "w", encoding="utf-8", newline="\n") as f: - json.dump({field: {}}, f) - with contextlib.redirect_stdout(io.StringIO()): - self.assertEqual(WN.main(args), 0) - with open(out, encoding="utf-8") as f: - self.assertEqual(json.load(f)["archetypes"]["entities"], 0) - - def test_resolve_out_refuses_to_overwrite_an_input(self): - with tempfile.TemporaryDirectory() as tmp: - dictionary = os.path.join(tmp, "names.json") - maps = os.path.join(tmp, "maps.json") - archetypes = os.path.join(tmp, "archetypes.json") - with open(dictionary, "w", encoding="utf-8") as handle: - json.dump(WN.NameDictionary().to_json(), handle) - with open(maps, "w", encoding="utf-8") as handle: - json.dump({"maps": [{"map_name": WN.joaat("synthetic_cli_prop")}]}, handle) - with open(archetypes, "w", encoding="utf-8") as handle: - json.dump({"archetypes": {f"{WN.joaat('synthetic_cli_prop'):08x}": 1}}, handle) - with open(dictionary, "rb") as handle: - dict_bytes = handle.read() - - cases = [ - ("dict", ["--dict", dictionary]), - ("map", ["--dict", dictionary, "--maps", maps]), - ("archetype", ["--dict", dictionary, "--archetypes", archetypes]), - ] - for name, prefix in cases: - with self.subTest(input=name): - source = {"dict": dictionary, "map": maps, "archetype": archetypes}[name] - with open(source, "rb") as handle: - original = handle.read() - err = io.StringIO() - with contextlib.redirect_stderr(err), contextlib.redirect_stdout(io.StringIO()): - self.assertNotEqual(WN.main(["resolve", *prefix, "--out", source]), 0) - self.assertIn(f"would overwrite input {source}", err.getvalue()) - with open(source, "rb") as handle: - self.assertEqual(handle.read(), original) - - # A hard link is another spelling of the same inode. - hardlink = os.path.join(tmp, "dict_hardlink.json") - try: - os.link(dictionary, hardlink) - except OSError: - self.skipTest("hard links unsupported on this filesystem") - err = io.StringIO() - with contextlib.redirect_stderr(err), contextlib.redirect_stdout(io.StringIO()): - self.assertNotEqual(WN.main(["resolve", "--dict", dictionary, "--out", hardlink]), 0) - with open(dictionary, "rb") as handle: - self.assertEqual(handle.read(), dict_bytes) - - def test_parent_link_counts_only_map_rows(self) -> None: - dictionary = WN.NameDictionary() - dictionary.add("synthetic_parent") - dictionary.add("synthetic_metadata") - parent_hash = WN.joaat("synthetic_parent") - meta_hash = WN.joaat("synthetic_metadata") - rows = [ - {"kind": "map", "map_name": WN.joaat("synthetic_child"), "parent": parent_hash}, - {"kind": "map", "map_name": WN.joaat("synthetic_orphan"), "parent": meta_hash}, - {"kind": "map", "map_name": parent_hash, "parent": 0}, - {"kind": "meta", "name": meta_hash}, - ] - with tempfile.TemporaryDirectory() as tmp: - names = os.path.join(tmp, "names.json") - maps = os.path.join(tmp, "maps.json") - out = os.path.join(tmp, "report.json") - with open(names, "w", encoding="utf-8", newline="\n") as f: - json.dump(dictionary.to_json(), f) - with open(maps, "w", encoding="utf-8", newline="\n") as f: - json.dump({"resources": rows}, f) - with contextlib.redirect_stdout(io.StringIO()): - self.assertEqual(WN.main(["resolve", "--dict", names, "--maps", maps, "--out", out]), 0) - with open(out, encoding="utf-8") as f: - report = json.load(f)["maps"] - - self.assertEqual(report["rows"], 3) - self.assertEqual(report["parent_resolved"], 2) - self.assertEqual(report["parent_links"], 1) - self.assertEqual(report["parent_links_resolved"], 1) - - def test_resolve_links_parents_across_map_reports_in_either_order(self): - dictionary = WN.NameDictionary() - dictionary.add("synthetic_parent") - parent = WN.joaat("synthetic_parent") - with tempfile.TemporaryDirectory() as tmp: - names, children, parents = (os.path.join(tmp, f"{p}.json") - for p in ("names", "children", "parents")) - for path, data in ((names, dictionary.to_json()), - (children, [{"name": 1, "parent": parent}, {"name": 2, "parent": parent}]), - (parents, {"maps": [{"name": parent}]})): - with open(path, "w", encoding="utf-8", newline="\n") as f: - json.dump(data, f) - for first, second in ((children, parents), (parents, children)): - with self.subTest(first=first), contextlib.redirect_stdout(io.StringIO()) as out: - self.assertEqual(WN.main(["resolve", "--dict", names, "--maps", first, "--maps", second]), 0) - stats = json.loads(out.getvalue())["maps"] - self.assertEqual(stats["rows"], 3) - self.assertEqual(stats["parent_links"], 2) - self.assertEqual(stats["parent_links_resolved"], 2) - - def test_build_and_resolve(self): - with tempfile.TemporaryDirectory() as tmp: - manifest = os.path.join(tmp, "manifest.json") - with open(manifest, "w", encoding="utf-8") as handle: - json.dump({"Items": [{"Name": "synthetic_cli_prop.#dr"}]}, handle) - dictionary = os.path.join(tmp, "names.json") - with contextlib.redirect_stdout(io.StringIO()): - self.assertEqual(WN.main(["build", "--manifest", manifest, "--out", dictionary]), 0) - with open(dictionary, encoding="utf-8") as handle: - data = json.load(handle) - self.assertEqual(data["counts"]["exact_names"], 1) - - maps = os.path.join(tmp, "maps.json") - with open(maps, "w", encoding="utf-8") as handle: - json.dump({"maps": [{"map_name": WN.joaat("synthetic_cli_prop")}]}, handle) - report = os.path.join(tmp, "report.json") - with contextlib.redirect_stdout(io.StringIO()): - self.assertEqual(WN.main(["resolve", "--dict", dictionary, "--maps", maps, - "--out", report]), 0) - with open(report, encoding="utf-8") as handle: - result = json.load(handle) - self.assertEqual(result["maps"]["name_resolved"], 1) - - def test_build_out_refuses_to_overwrite_an_input(self): - with tempfile.TemporaryDirectory() as tmp: - manifest = os.path.join(tmp, "manifest.json") - scan = os.path.join(tmp, "scan.json") - names = os.path.join(tmp, "names.txt") - rpf9 = os.path.join(tmp, "rpf9_names.json") - xml = os.path.join(tmp, "common.xml") - models_dir = os.path.join(tmp, "assets", "archive", "models") - os.makedirs(models_dir) - dir_manifest = os.path.join(models_dir, "manifest.json") - - with open(manifest, "w", encoding="utf-8", newline="\n") as handle: - json.dump({"Items": [{"Name": "synthetic_m.#dr"}]}, handle) - with open(dir_manifest, "w", encoding="utf-8", newline="\n") as handle: - json.dump({"Items": [{"Name": "synthetic_dir_m.#dr"}]}, handle) - with open(scan, "w", encoding="utf-8", newline="\n") as handle: - json.dump({"entries": [{"Path": "models/synthetic_s._dr_at_0000000000000010.r9modeldata"}]}, handle) - with open(names, "w", encoding="utf-8", newline="\n") as handle: - handle.write("synthetic_n\n") - with open(rpf9, "w", encoding="utf-8", newline="\n") as handle: - json.dump({"files": [{"names": ["synthetic_r.#dr"]}]}, handle) - with open(xml, "w", encoding="utf-8", newline="\n") as handle: - handle.write("synthetic_x\n") - - cases = [ - ("manifest", ["--manifest", manifest], manifest), - ("manifest_dir", ["--manifest", os.path.join(tmp, "assets")], dir_manifest), - ("scan", ["--scan", scan], scan), - ("names", ["--names", names], names), - ("rpf9_names", ["--rpf9-names", rpf9], rpf9), - ("xml", ["--xml", xml], xml), - ] - for label, prefix, source in cases: - with self.subTest(input=label): - with open(source, "rb") as handle: - original = handle.read() - out_buf, err_buf = io.StringIO(), io.StringIO() - with contextlib.redirect_stdout(out_buf), contextlib.redirect_stderr(err_buf): - self.assertEqual(WN.main(["build", *prefix, "--out", source]), 1) - self.assertIn(f"would overwrite input {source}", err_buf.getvalue()) - self.assertEqual(out_buf.getvalue(), "") - with open(source, "rb") as handle: - self.assertEqual(handle.read(), original) - - # A hard link to either a direct input or a discovered directory manifest is refused too. - for label, prefix, source, link_name in ( - ("manifest_hardlink", ["--manifest", manifest], manifest, "manifest_link.json"), - ("dir_manifest_hardlink", ["--manifest", os.path.join(tmp, "assets")], dir_manifest, "dir_link.json"), - ): - hardlink = os.path.join(tmp, link_name) - try: - os.link(source, hardlink) - except OSError: - self.skipTest("hard links unsupported on this filesystem") - with self.subTest(input=label): - with open(source, "rb") as handle: - original = handle.read() - err_buf = io.StringIO() - with contextlib.redirect_stdout(io.StringIO()), contextlib.redirect_stderr(err_buf): - self.assertEqual(WN.main(["build", *prefix, "--out", hardlink]), 1) - self.assertIn(f"would overwrite input {source}", err_buf.getvalue()) - with open(source, "rb") as handle: - self.assertEqual(handle.read(), original) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/test_world_place.py b/tests/test_world_place.py deleted file mode 100644 index 13361ce9c..000000000 --- a/tests/test_world_place.py +++ /dev/null @@ -1,320 +0,0 @@ -"""Tests for placing models at their map placements (no game data). - -Covers world_index.py --entities-out and world_build.py --placements: the entity row format, the transform -(the conjugate of the stored quaternion, non-uniform scale, normals, mirroring, RAGE Z-up to glTF Y-up), the -name/key match against rpf9dump manifests, and the placement counts in world.json. Every model, entity and -resource is synthetic. - - python -I tests/test_world_place.py -""" -import contextlib -import io -import json -import math -import os -import sys -import tempfile -import unittest - -ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) -TESTS = os.path.dirname(os.path.abspath(__file__)) -for p in (os.path.join(ROOT, "tools"), TESTS): - if p not in sys.path: - sys.path.insert(0, p) - -import test_world_index as twi # noqa: E402 (synthetic 0x7a resource builder) -import world_build # noqa: E402 -import world_names # noqa: E402 - -WI = twi.WI -S2 = math.sqrt(0.5) - - -def stored_rotation_about_z(degrees): - """The quaternion a map file stores for a world rotation of `degrees` about +Z (stored = inverse).""" - h = math.radians(degrees) / 2 - return [0.0, 0.0, -math.sin(h), math.cos(h)] - - -def apply(m, v): - return tuple(sum(m[i][j] * v[j] for j in range(3)) for i in range(3)) - - -def close(a, b, tol=1e-9): - return all(abs(x - y) <= tol for x, y in zip(a, b)) - - -UNIT_BOX_OBJ = """# unit box 0..1 in RAGE axes (Z up) -v 0 0 0 -v 1 0 0 -v 1 1 0 -v 0 1 0 -v 0 0 1 -v 1 0 1 -v 1 1 1 -v 0 1 1 -f 1 3 2 -f 1 4 3 -f 5 6 7 -f 5 7 8 -f 1 2 6 -f 1 6 5 -f 2 3 7 -f 2 7 6 -f 3 4 8 -f 3 8 7 -f 4 1 5 -f 4 5 8 -""" - - -def write_assets(root, name="test_box"): - models = os.path.join(root, "assets", "levels", "models") - os.makedirs(models) - with open(os.path.join(models, "box.obj"), "w", encoding="utf-8") as f: - f.write(UNIT_BOX_OBJ) - with open(os.path.join(models, "manifest.json"), "w", encoding="utf-8") as f: - json.dump({"Items": [{"File": "box.obj", "Name": name + ".#dr", "Min": [0, 0, 0], "Max": [1, 1, 1]}]}, f) - return os.path.join(root, "assets") - - -def write_entities(path, rows, extra_lines=()): - with open(path, "w", encoding="utf-8") as f: - for r in rows: - f.write(json.dumps(r) + "\n") - for line in extra_lines: - f.write(line + "\n") - - -def entity(name, position, rotation=(0.0, 0.0, 0.0, 1.0), sxy=1.0, sz=1.0, lod=0, key=True): - row = {"archetype": f"{world_names.joaat(name):08x}", "position": list(position), "rotation": list(rotation), - "scale_xy": sxy, "scale_z": sz, "lod_level": lod} - if key is True: - row["key"] = f"{world_names.hash64(name):016x}" - elif key: - row["key"] = key - return row - - -class EntitiesOutTest(unittest.TestCase): - def test_one_row_per_entity(self): - with tempfile.TemporaryDirectory() as tmp: - src = os.path.join(tmp, "map.bin") - with open(src, "wb") as f: - f.write(twi.make_resource()) - ents, arch = os.path.join(tmp, "e.jsonl"), os.path.join(tmp, "a.json") - with contextlib.redirect_stdout(io.StringIO()): - rc = WI.main([src, "--out", os.path.join(tmp, "o.json"), "--entities-out", ents, "--archetypes-out", arch]) - self.assertEqual(rc, 0) - with open(ents, encoding="utf-8") as f: - rows = [json.loads(line) for line in f] - self.assertEqual(len(rows), 1) - r = rows[0] - self.assertEqual((r["archetype"], r["key"]), ("deadbeef", "1122334455667788")) - self.assertEqual(r["position"], [1.5, 2.5, 3.5]) - self.assertEqual(r["rotation"], [0.0, 0.0, 0.0, 1.0]) - self.assertEqual((r["scale_xy"], r["scale_z"], r["lod_level"]), (1.0, 1.0, 1)) - with open(arch, encoding="utf-8") as f: # the aggregate file is still written alongside - self.assertEqual(json.load(f)["archetypes"], {"deadbeef": 1}) - - def test_meta_resource_writes_no_rows(self): - with tempfile.TemporaryDirectory() as tmp: - src = os.path.join(tmp, "meta.bin") - with open(src, "wb") as f: - f.write(twi.make_resource(map_file=False)) - ents = os.path.join(tmp, "e.jsonl") - with contextlib.redirect_stdout(io.StringIO()): - self.assertEqual(WI.main([src, "--out", os.path.join(tmp, "o.json"), "--entities-out", ents]), 0) - with open(ents, encoding="utf-8") as f: - self.assertEqual(f.read(), "") - - def test_error_leaves_no_partial_file(self): - with tempfile.TemporaryDirectory() as tmp: - ents = os.path.join(tmp, "e.jsonl") - with contextlib.redirect_stderr(io.StringIO()): - rc = WI.main([os.path.join(tmp, "missing"), "--out", os.path.join(tmp, "o.json"), "--entities-out", ents]) - self.assertEqual(rc, 2) - self.assertFalse(os.path.exists(ents)) - - -class TransformTest(unittest.TestCase): - def test_identity(self): - m, n, mirror = world_build.entity_transform([0, 0, 0, 1], 1.0, 1.0) - self.assertTrue(close(apply(m, (1, 2, 3)), (1, 2, 3))) - self.assertFalse(mirror) - - def test_stored_quaternion_is_the_inverse(self): - # A world rotation of +90 degrees about Z takes +X to +Y; the file stores its inverse. - m, _, _ = world_build.entity_transform(stored_rotation_about_z(90), 1.0, 1.0) - self.assertTrue(close(apply(m, (1, 0, 0)), (0, 1, 0))) - self.assertTrue(close(apply(m, (0, 1, 0)), (-1, 0, 0))) - - def test_scale_is_applied_before_rotation(self): - m, _, _ = world_build.entity_transform(stored_rotation_about_z(90), 2.0, 3.0) - self.assertTrue(close(apply(m, (1, 0, 1)), (0, 2, 3))) - - def test_unnormalised_quaternion(self): - q = [v * 5 for v in stored_rotation_about_z(90)] - m, _, _ = world_build.entity_transform(q, 1.0, 1.0) - self.assertTrue(close(apply(m, (1, 0, 0)), (0, 1, 0))) - - def test_normals_use_the_inverse_transpose(self): - # Squash Z by 2: a 45-degree face normal tilts towards Z. - _, n, _ = world_build.entity_transform([0, 0, 0, 1], 1.0, 0.5) - v = apply(n, (S2, 0, S2)) - self.assertGreater(v[2], v[0]) - - def test_place_converts_to_gltf_y_up(self): - prims = [{"positions": [(1.0, 0.0, 0.0)], "normals": [(0.0, 0.0, 1.0)], "indices": [0, 0, 0], "uvs": []}] - out = world_build.place_primitives(prims, [0, 0, 0, 1], 1.0, 1.0, (100.0, 200.0, 10.0)) - self.assertTrue(close(out[0]["positions"][0], (101.0, 10.0, -200.0))) - self.assertTrue(close(out[0]["normals"][0], (0.0, 1.0, 0.0))) - self.assertEqual(prims[0]["positions"], [(1.0, 0.0, 0.0)]) # the cached model is not modified - - def test_negative_scale_flips_winding(self): - prims = [{"positions": [(0, 0, 0), (1, 0, 0), (0, 1, 0)], "normals": [], "indices": [0, 1, 2], "uvs": []}] - self.assertEqual(world_build.place_primitives(prims, [0, 0, 0, 1], 1.0, -1.0, (0, 0, 0))[0]["indices"], [0, 2, 1]) - self.assertEqual(world_build.place_primitives(prims, [0, 0, 0, 1], 1.0, 1.0, (0, 0, 0))[0]["indices"], [0, 1, 2]) - - -class PlacementLoadTest(unittest.TestCase): - def load(self, rows, **kwargs): - with tempfile.TemporaryDirectory() as tmp: - path = os.path.join(tmp, "entities.jsonl") - write_entities(path, rows) - return world_build.load_placements(path, **kwargs) - - def test_malformed_values_preserve_valid_neighbors(self): - before = entity("test_box", (1, 2, 3), sxy=2.0, sz=3.0) - after = entity("test_box", (9, 8, 7), sxy=-1.0, sz=0.5) - patches = ( - {"lod_level": []}, {"lod_level": {}}, - {"position": [10**400, 0, 0]}, {"rotation": [0, 0, 0, -(10**400)]}, - ) - for patch in patches: - with self.subTest(field=next(iter(patch))): - bad = dict(entity("test_box", (4, 5, 6)), **patch) - rows, counts = self.load([before, bad, after]) - self.assertEqual([row["_pos"] for row in rows], [[1.0, 2.0, 3.0], [9.0, 8.0, 7.0]]) - self.assertEqual([(row["_sxy"], row["_sz"]) for row in rows], [(2.0, 3.0), (-1.0, 0.5)]) - self.assertEqual(counts, {"rows": 3, "malformed": 1, "other_lod_level": 0, - "outside_region": 0, "selected": 2}) - - def test_invalid_optional_scales_keep_unit_fallback(self): - for field in ("scale_xy", "scale_z"): - for value in (None, "2.0", [], {}, float("nan"), float("inf"), -float("inf"), 10**400, -(10**400)): - with self.subTest(field=field, value=value): - middle = entity("test_box", (4, 5, 6), sxy=2.0, sz=3.0) - middle[field] = value - rows, counts = self.load([entity("test_box", (0, 0, 0)), middle, entity("test_box", (9, 8, 7))]) - self.assertEqual(counts["selected"], 3) - self.assertEqual(counts["malformed"], 0) - self.assertEqual((rows[1]["_sxy"], rows[1]["_sz"]), - (1.0, 3.0) if field == "scale_xy" else (2.0, 1.0)) - - def test_finite_scales_and_filter_counts_unchanged(self): - missing_lod = entity("test_box", (1, 1, 0)) - del missing_lod["lod_level"] - rows, counts = self.load([ - entity("test_box", (1, 1, 0), sxy=0, sz=-2.5), - entity("test_box", (2, 2, 0), sxy=-3, sz=0, lod=5), - entity("test_box", (1, 1, 0), lod=1), missing_lod, - entity("test_box", (10, 10, 0)), - ], region=(0, 0, 5, 5)) - self.assertEqual([(row["_sxy"], row["_sz"]) for row in rows], [(0.0, -2.5), (-3.0, 0.0)]) - self.assertEqual(counts, {"rows": 5, "malformed": 0, "other_lod_level": 2, - "outside_region": 1, "selected": 2}) - - -class PlacedBuildTest(unittest.TestCase): - def build(self, rows, extra_lines=(), **kw): - tmp = tempfile.mkdtemp() - self.addCleanup(lambda: __import__("shutil").rmtree(tmp, ignore_errors=True)) - assets = write_assets(tmp) - ents = os.path.join(tmp, "entities.jsonl") - write_entities(ents, rows, extra_lines) - doc = world_build.build_world(assets, os.path.join(tmp, "world"), textures=False, placements=ents, **kw) - return doc - - def test_counts_and_bounds(self): - rows = [ - entity("test_box", (100, 200, 10), stored_rotation_about_z(90), sxy=2.0, sz=1.0), # placed - entity("test_box", (1000, 1000, 0), lod=5, key=False), # unverified - entity("test_box", (0, 0, 0), key="0000000000000001"), # key mismatch - entity("other_box", (0, 0, 0)), # unresolved - entity("test_box", (0, 0, 0), lod=1), # LOD level - ] - doc = self.build(rows, extra_lines=["{not json", json.dumps({"archetype": "1", "position": [0, 0]})]) - pl = doc["stats"]["placements"] - self.assertEqual(pl["rows"], 7) - self.assertEqual(pl["malformed"], 2) - self.assertEqual(pl["other_lod_level"], 1) - self.assertEqual(pl["selected"], 4) - self.assertEqual((pl["placed"], pl["placed_unverified"], pl["key_mismatch"], pl["unresolved_archetype"]), - (1, 1, 1, 1)) - self.assertEqual(pl["distinct_models"], 1) - self.assertEqual(doc["layout"], "placements") - self.assertEqual(doc["stats"]["models"], 2) - by_id = {c["id"]: c for c in doc["chunks"]} - # Box 0..1 scaled (2, 2, 1), turned +90 degrees about Z, moved to (100, 200, 10): - # RAGE x 98..100, y 200..202, z 10..11 -> glTF X 98..100, Y 10..11, Z -202..-200. - self.assertTrue(close(by_id["c_0_-1"]["bounds"], [98, 10, -202, 100, 11, -200], 1e-4)) - self.assertTrue(close(by_id["c_3_-4"]["bounds"], [1000, 0, -1001, 1001, 1, -1000], 1e-4)) - self.assertEqual(by_id["c_0_-1"]["triangles"], 12) - - def test_region_and_lod_levels(self): - rows = [entity("test_box", (10, 10, 0)), entity("test_box", (500, 10, 0)), entity("test_box", (10, 10, 0), lod=1)] - pl = self.build(rows, region=(0, 0, 100, 100), lod_levels=(0, 1))["stats"]["placements"] - self.assertEqual((pl["selected"], pl["outside_region"], pl["placed"]), (2, 1, 2)) - - def test_build_continues_after_malformed_placement_rows(self): - rows = [entity("test_box", (10, 10, 0)), - entity("test_box", (0, 0, 0), lod=[]), - entity("test_box", (10**400, 0, 0)), - entity("test_box", (20, 20, 0), sxy=10**400, sz=-(10**400)), - entity("test_box", (30, 30, 0))] - doc = self.build(rows) - counts = doc["stats"]["placements"] - self.assertEqual((counts["rows"], counts["malformed"], counts["selected"], counts["placed"]), (5, 2, 3, 3)) - # Overflowing optional scales act like the existing missing-scale defaults, including geometry bounds. - control = self.build([rows[0], entity("test_box", (20, 20, 0)), rows[-1]]) - self.assertEqual(doc["stats"]["triangles"], control["stats"]["triangles"]) - self.assertEqual([chunk["bounds"] for chunk in doc["chunks"]], [chunk["bounds"] for chunk in control["chunks"]]) - - def test_nothing_placeable_leaves_output_unchanged(self): - with self.assertRaisesRegex(ValueError, "could be placed"): - self.build([entity("other_box", (0, 0, 0))]) - - def test_option_conflicts(self): - with tempfile.TemporaryDirectory() as tmp: - assets = write_assets(tmp) - ents = os.path.join(tmp, "e.jsonl") - write_entities(ents, [entity("test_box", (0, 0, 0))]) - with self.assertRaisesRegex(ValueError, "grid-layout"): - world_build.build_world(assets, os.path.join(tmp, "w"), placements=ents, grid_layout=True) - with self.assertRaisesRegex(ValueError, "--up z"): - world_build.build_world(assets, os.path.join(tmp, "w"), placements=ents, up_axis="y") - with self.assertRaises(FileNotFoundError): - world_build.build_world(assets, os.path.join(tmp, "w"), placements=os.path.join(tmp, "none")) - - def test_cli(self): - with tempfile.TemporaryDirectory() as tmp: - assets = write_assets(tmp) - ents = os.path.join(tmp, "e.jsonl") - write_entities(ents, [entity("test_box", (10, 10, 0)), entity("test_box", (900, 10, 0), lod=5)]) - out = io.StringIO() - with contextlib.redirect_stdout(out): - rc = world_build.main([assets, "--out", os.path.join(tmp, "w"), "--no-textures", "--placements", ents, - "--lod-levels", "0", "--region", "0,0,100,100"]) - self.assertEqual(rc, 0) - self.assertIn("placements:", out.getvalue()) - with open(os.path.join(tmp, "w", "world.json"), encoding="utf-8") as f: - pl = json.load(f)["stats"]["placements"] - self.assertEqual((pl["placed"], pl["other_lod_level"]), (1, 1)) - with contextlib.redirect_stderr(io.StringIO()): - with self.assertRaises(SystemExit): - world_build.main([assets, "--out", os.path.join(tmp, "w"), "--region", "5,5,1,1"]) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/test_world_placement_identity.py b/tests/test_world_placement_identity.py deleted file mode 100644 index 8892cad1f..000000000 --- a/tests/test_world_placement_identity.py +++ /dev/null @@ -1,153 +0,0 @@ -"""Placement identity through the split-stream --entities-out path (synthetic data only).""" -import contextlib -import io -import json -from pathlib import Path -import struct -import sys -import tempfile -import unittest - -TESTS = Path(__file__).resolve().parent -sys.path[:0] = [str(TESTS), str(TESTS.parent / "tools")] -import test_world_index as twi # noqa: E402 - - -STRIDE = 0x90 -PARENT_MAPS = (0xABCD, 0xCDEF0123) -UNSUPPORTED = 5 # one-based block ID of the unsupported class - - -def entity_ref(index): - return ((index * STRIDE) << 20) | 1 # block 1, byte offset in the upper bits - - -def make_map(links, pointers, parent_maps=PARENT_MAPS, *, map_name=0xABCDEF, first_x=10): - """Extend the stock fixture's CMapData root and its template CEntityDef.""" - blob = bytearray(twi.make_resource()) - template = blob[0x400:0x400 + STRIDE] - - def extend_members(header, additions): - old_table = struct.unpack_from(" arm64 static recompiler groundwork. - -Two layers are covered: - - * decoder: hand-assembled x86-64 bytes -> Insn fields, - * end-to-end: a hand-assembled x86-64 function is translated to arm64, packed into a - flat kernel image and executed under qemu-system-aarch64 with semihosting. The - runtime prints "R=xxxxxxxx" (the guest edi) which the test compares against an - expected value. - -Every fixture is built byte by byte here; no game files, no third-party packages. -The qemu tests skip cleanly when qemu-system-aarch64 is not installed. - - python -I tests/test_x64_recomp.py -""" -import os -import shutil -import sys -import unittest - -ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) -if ROOT not in sys.path: - sys.path.insert(0, ROOT) -TOOLS_DIR = os.path.join(ROOT, "tools") -if TOOLS_DIR not in sys.path: - sys.path.insert(0, TOOLS_DIR) - -import x64_recomp as x # noqa: E402 - -QEMU = os.environ.get( - "QEMU_AARCH64", - "/home/nolan/.nix-profile/bin/qemu-system-aarch64" - if os.path.exists("/home/nolan/.nix-profile/bin/qemu-system-aarch64") - else shutil.which("qemu-system-aarch64") or "") -HAS_QEMU = bool(QEMU) and os.path.exists(QEMU) - -GUEST_VA = 0x46000000 -SCRATCH = 0x47100000 # inside the kernel image's RW RAM window, away from ctx/stack - - -def asm(*hexes): - return bytes.fromhex("".join(h.replace(" ", "") for h in hexes)) - - -class DecodeTests(unittest.TestCase): - def one(self, code, base=0x1000): - return x.decode_one(code, 0, len(code), base) - - def test_basic_forms(self): - ins = self.one(asm("31 c0")) # xor eax,eax - self.assertEqual(ins.mnem, "xor") - self.assertEqual(ins.ops, (("r", 0, 4), ("r", 0, 4, False))) - self.assertEqual(ins.size, 2) - - ins = self.one(asm("48 89 e5")) # mov rbp,rsp - self.assertEqual(ins.mnem, "mov") - self.assertEqual(ins.ops, (("r", 5, 8), ("r", 4, 8, False))) - - ins = self.one(asm("b8 05 00 00 00")) # mov eax,5 - self.assertEqual(ins.ops, (("r", 0, 4, False), ("i", 5, 4))) - - ins = self.one(asm("83 c0 03")) # add eax,3 - self.assertEqual(ins.mnem, "add") - self.assertEqual(ins.ops, (("r", 0, 4), ("i", 3, 1))) - - ins = self.one(asm("48 b8 88 77 66 55 44 33 22 11")) # mov rax,imm64 - self.assertEqual(ins.size, 10) - self.assertEqual(ins.ops, (("r", 0, 8, False), ("i", 0x1122334455667788, 8))) - - ins = self.one(asm("b4 ff")) # mov ah,-1 (no REX: O-field 4..7 = hi8) - self.assertEqual(ins.ops, (("r", 0, 1, True), ("i", -1, 1))) - - def test_rex_and_extended_regs(self): - ins = self.one(asm("4c 89 f8")) # mov rax,r15 - self.assertEqual(ins.ops, (("r", 0, 8), ("r", 15, 8, False))) - ins = self.one(asm("41 54")) # push r12 - self.assertEqual(ins.ops, (("r", 12, 8, False),)) - - def test_modrm_mem(self): - ins = self.one(asm("48 8b 44 24 08")) # mov rax,[rsp+8] - m = ins.ops[1][1] - self.assertEqual(m["base"], 4) - self.assertIsNone(m["index"]) - self.assertEqual(m["disp"], 8) - - ins = self.one(asm("48 8b 04 b7")) # mov rax,[rdi+rsi*4] - m = ins.ops[1][1] - self.assertEqual(m["base"], 7) - self.assertEqual(m["index"], 6) - self.assertEqual(m["scale"], 2) - - ins = self.one(asm("48 8b 05 10 00 00 00")) # mov rax,[rip+0x10] - m = ins.ops[1][1] - self.assertTrue(m["rip"]) - self.assertEqual(m["abs"], 0x1000 + 7 + 0x10) - - def test_branches_and_immediates(self): - ins = self.one(asm("74 05")) # jz +5 - self.assertEqual(ins.kind, "branch") - self.assertEqual(ins.cc, "e") - self.assertEqual(ins.ops[0], ("a", 0x1007, 0)) - - ins = self.one(asm("e9 78 56 34 12")) # jmp rel32 - self.assertEqual(ins.ops[0], ("a", 0x1000 + 5 + 0x12345678, 0)) - - ins = self.one(asm("e8 fc ff ff ff")) # call -4 - self.assertEqual(ins.kind, "call") - self.assertEqual(ins.ops[0], ("a", 0x1000 + 5 - 4, 0)) - - ins = self.one(asm("c3")) - self.assertEqual(ins.kind, "ret") - - def test_cmov_setcc_shifts(self): - ins = self.one(asm("0f 44 c1")) # cmove eax,ecx - self.assertEqual(ins.mnem, "cmov") - self.assertEqual(ins.cc, "e") - ins = self.one(asm("0f 95 c0")) # setnz al - self.assertEqual(ins.mnem, "setcc") - self.assertEqual(ins.cc, "ne") - ins = self.one(asm("d3 e0")) # shl eax,cl - self.assertEqual(ins.mnem, "shl") - ins = self.one(asm("c1 e8 04")) # shr eax,4 - self.assertEqual(ins.mnem, "shr") - self.assertEqual(ins.ops[1], ("i", 4, 1)) - - def test_prefixes(self): - ins = self.one(asm("66 b8 34 12")) # mov ax,0x1234 - self.assertEqual(ins.ops, (("r", 0, 2, False), ("i", 0x1234, 2))) - ins = self.one(asm("f3 a4")) # rep movsb - self.assertEqual(ins.mnem, "movs") - self.assertEqual(ins.rep, "f3") - ins = self.one(asm("f2 ae")) # repne scasb - self.assertEqual(ins.mnem, "scas") - self.assertEqual(ins.rep, "f2") - ins = self.one(asm("f3 0f 1e fa")) # endbr64 (decoded, no crash) - self.assertEqual(ins.size, 4) - - -def run(code): - return x.run_result(code, GUEST_VA) - - -@unittest.skipUnless(HAS_QEMU, "qemu-system-aarch64 not installed") -class ExecTests(unittest.TestCase): - def test_mov_add_ret(self): - # mov eax,40; add eax,2; mov edi,eax; ret -> 42 - r, _ = run(asm("b8 28 00 00 00", "83 c0 02", "89 c7", "c3")) - self.assertEqual(r, 42) - - def test_sub_cmp_jcc_loop(self): - # sum = 0; ecx = 5; do { sum += ecx } while (--ecx != 0) -> 15 - # mov edi,0; mov ecx,5; L: add edi,ecx; dec ecx; jnz L; ret - r, _ = run(asm( - "bf 00 00 00 00", # mov edi,0 - "b9 05 00 00 00", # mov ecx,5 - "01 cf", # L: add edi,ecx - "ff c9", # dec ecx - "75 fa", # jnz -6 - "c3")) - self.assertEqual(r, 15) - - def test_unsigned_branch(self): - # cmp below/above: eax=3 vs 7 -> jb taken -> edi=1 - r, _ = run(asm( - "b8 03 00 00 00", # mov eax,3 - "83 f8 07", # cmp eax,7 - "72 06", # jb +6 - "bf 02 00 00 00", # mov edi,2 - "c3", - "bf 01 00 00 00", # mov edi,1 - "c3")) - self.assertEqual(r, 1) - - def test_signed_branch(self): - # -1 < 7 signed -> jl taken - r, _ = run(asm( - "b8 ff ff ff ff", # mov eax,-1 - "83 f8 07", # cmp eax,7 - "7c 06", # jl +6 - "bf 02 00 00 00", # mov edi,2 - "c3", - "bf 01 00 00 00", # mov edi,1 - "c3")) - self.assertEqual(r, 1) - - def test_call_and_ret(self): - # 00 call ->0x0c (callee sets edi=9, ret pops the pushed return ->0x05) - # 05 mov edi,7 ; 0a jmp ->0x12 ; 0c mov edi,9 ; 11 ret ; 12 ret - r, _ = run(asm( - "e8 07 00 00 00", # call +7 -> 0x0c - "bf 07 00 00 00", # mov edi,7 (return lands here) - "eb 06", # jmp +6 -> 0x12 - "bf 09 00 00 00", # callee: mov edi,9 - "c3", # ret -> guest pc 0x05 - "c3")) # end: ret -> sentinel -> exit - self.assertEqual(r, 7) - - def test_setcc_after_cmp(self): - # setg al when 9 > 4 -> edi=1 - r, _ = run(asm( - "b8 09 00 00 00", # mov eax,9 - "83 f8 04", # cmp eax,4 - "0f 9f c7", # setg dil - "0f b6 ff", # movzx edi,dil - "c3")) - self.assertEqual(r, 1) - - def test_cmov(self): - # cmovne: equal -> keep old; not-equal -> take new - r, _ = run(asm( - "bf 05 00 00 00", # mov edi,5 - "b8 01 00 00 00", # mov eax,1 - "83 f8 02", # cmp eax,2 (ne) - "bb 2a 00 00 00", # mov ebx,42 - "0f 45 fb", # cmovne edi,ebx - "c3")) - self.assertEqual(r, 42) - - def test_logic_clears_carry(self): - # stc then xor (clears CF) -> jae taken -> edi=1 - r, _ = run(asm( - "f9", # stc - "31 c0", # xor eax,eax - "73 06", # jae +6 - "bf 02 00 00 00", - "c3", - "bf 01 00 00 00", - "c3")) - self.assertEqual(r, 1) - - def test_adc_chain(self): - # 64-bit add via adc: lo=0xFFFFFFFF + 1 -> lo 0, carry into hi - r, _ = run(asm( - "b8 ff ff ff ff", # mov eax,-1 - "31 d2", # xor edx,edx - "83 c0 01", # add eax,1 (CF=1) - "83 d2 00", # adc edx,0 (edx=1) - "89 d7", # mov edi,edx - "c3")) - self.assertEqual(r, 1) - - def test_push_pop(self): - r, _ = run(asm( - "68 34 12 00 00", # push 0x1234 - "5f", # pop rdi - "c3")) - self.assertEqual(r, 0x1234) - - def test_imul(self): - r, _ = run(asm( - "b8 06 00 00 00", # mov eax,6 - "6b c0 07", # imul eax,eax,7 - "89 c7", # mov edi,eax - "c3")) - self.assertEqual(r, 42) - - def test_shifts(self): - r, _ = run(asm( - "b8 01 00 00 00", # mov eax,1 - "c1 e0 05", # shl eax,5 -> 32 - "c1 e8 02", # shr eax,2 -> 8 - "89 c7", - "c3")) - self.assertEqual(r, 8) - - def test_shift_sets_carry(self): - # shr sets CF=last bit out; jb reflects it - r, _ = run(asm( - "b8 03 00 00 00", # mov eax,3 - "d1 e8", # shr eax,1 -> CF=1 - "72 06", # jb +6 - "bf 02 00 00 00", - "c3", - "bf 01 00 00 00", - "c3")) - self.assertEqual(r, 1) - - def test_memory(self): - # mov [scratch],eax; mov edi,[scratch] - s = SCRATCH - r, _ = run(asm( - "b8 2a 00 00 00", # mov eax,42 - "a3 " + s.to_bytes(8, "little").hex(), # mov [scratch],eax (moffs) - "a1 " + s.to_bytes(8, "little").hex(), # mov eax,[scratch] - "89 c7", - "c3")) - self.assertEqual(r, 42) - - def test_lea_and_indexed_mem(self): - s = SCRATCH - r, _ = run(asm( - "bf " + s.to_bytes(4, "little").hex(), # mov edi,scratch - "c7 07 63 00 00 00", # mov dword [rdi],99 - "be " + (s + 4).to_bytes(4, "little").hex(), # mov esi,scratch+4 - "c7 06 58 02 00 00", # mov dword [rsi],600 - "8b 07", # mov eax,[rdi] =99 - "03 06", # add eax,[rsi] +600 - "89 c7", - "c3")) - self.assertEqual(r, 699) - - def test_movsx_movzx(self): - r, _ = run(asm( - "b1 ff", # mov cl,-1 - "0f be f9", # movsx edi,cl -> -1 - "c3")) - self.assertEqual(r, 0xFFFFFFFF) - - def test_neg_not_inc_dec(self): - r, _ = run(asm( - "b8 05 00 00 00", # mov eax,5 - "f7 d8", # neg eax -> -5 - "ff c0", # inc eax -> -4 - "f7 d0", # not eax -> ~-4 = 3 - "ff c8", # dec eax -> 2 - "89 c7", - "c3")) - self.assertEqual(r, 2) - - def test_div(self): - r, _ = run(asm( - "31 d2", # xor edx,edx - "b8 e7 03 00 00", # mov eax,999 - "b9 0a 00 00 00", # mov ecx,10 - "f7 f1", # div ecx -> eax=99 edx=9 - "89 c7", - "c3")) - self.assertEqual(r, 99) - - def test_rep_movsb(self): - s = SCRATCH - dst = SCRATCH + 0x100 - r, _ = run(asm( - "be " + s.to_bytes(4, "little").hex(), # mov esi,src - "c7 06 41 42 43 44", # src = 'ABCD' - "bf " + dst.to_bytes(4, "little").hex(), # mov edi,dst - "b9 04 00 00 00", # mov ecx,4 - "f3 a4", # rep movsb -> rdi=dst+4 - "8b 7f fc", # mov edi,[rdi-4] = the 4 copied bytes - "c3")) - self.assertEqual(r, 0x44434241) - - def test_repne_scasb(self): - s = SCRATCH - r, _ = run(asm( - "bf " + s.to_bytes(4, "little").hex(), # mov edi,buf - "c7 07 58 58 51 00", # buf = 'XXQ\0' - "b0 51", # mov al,'Q' - "b9 05 00 00 00", # mov ecx,5 - "f2 ae", # repne scasb - # found -> rdi = buf+3, ZF=1 -> sete - "0f 94 c0", # sete al - "0f b6 f8", # movzx edi,al - "c3")) - self.assertEqual(r, 1) - - def test_indirect_jump_via_table(self): - # jmp rax where rax = target inside the function -> dispatch table lookup - r, _ = run(asm( - "48 b8 " + (GUEST_VA + 18).to_bytes(8, "little").hex(), # mov rax,target (0x12) - "ff e0", # jmp rax - "bf 01 00 00 00", # (skipped) - "c3", - "bf 2b 00 00 00", # target: mov edi,43 - "c3")) - self.assertEqual(r, 43) - - def test_mov_imm64(self): - # mov r64,imm64 is the only insn with a full 8-byte immediate - r, _ = run(asm( - "48 b8 " + (GUEST_VA + 13).to_bytes(8, "little").hex(), # mov rax,V+13 - "48 8d 78 00", # lea rdi,[rax] - "48 81 ef " + GUEST_VA.to_bytes(4, "little").hex(), # sub rdi,GUEST_VA - "c3")) - self.assertEqual(r, 13) - - def test_high_byte_regs(self): - # b4 = mov ah,imm8 (no REX -> reg field 4..7 are the high bytes of regs 0..3) - r, _ = run(asm( - "b4 ff", # mov ah,0xff - "0f b6 fc", # movzx edi,ah -> 0xff - "c3")) - self.assertEqual(r, 0xFF) - - def test_pushf_popf(self): - # stc; pushf; clc; popf -> CF restored to 1 -> jb taken - r, _ = run(asm( - "f9", # stc - "9c", # pushf - "f8", # clc - "9d", # popf - "72 06", # jb +6 - "bf 02 00 00 00", - "c3", - "bf 01 00 00 00", - "c3")) - self.assertEqual(r, 1) - - def test_clc_clears_only_carry(self): - # stc; clc -> CF=0 -> jb not taken -> edi=2 - r, _ = run(asm( - "f9", # stc - "f8", # clc - "72 06", # jb +6 - "bf 02 00 00 00", - "c3", - "bf 01 00 00 00", - "c3")) - self.assertEqual(r, 2) - - def test_leave_and_frame(self): - r, _ = run(asm( - "55", # push rbp - "48 89 e5", # mov rbp,rsp - "48 83 ec 10", # sub rsp,16 - "c7 45 fc 2a 00 00 00", # mov dword [rbp-4],42 - "c9", # leave - "5d", # pop rbp - "bf 2a 00 00 00", # mov edi,42 - "c3")) - self.assertEqual(r, 42) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/test_xcl_compare.py b/tests/test_xcl_compare.py deleted file mode 100644 index 4a1c7a5fc..000000000 --- a/tests/test_xcl_compare.py +++ /dev/null @@ -1,267 +0,0 @@ -"""tools/xcl_compare.py: parsing of the test title's lines and the report it builds. - - python -I tests/test_xcl_compare.py - -Nothing here starts XCL or gta6rt, and no game files are read. The run tests start a small Python script that -prints the test title's line format in place of a title. -""" -import argparse -import os -from pathlib import Path -import sys -import tempfile -import unittest -from unittest import mock - -sys.path.insert(0, os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "tools")) -import xcl_compare as xc # noqa: E402 - - -class ParseResult(unittest.TestCase): - KNOWN = ["kernelx: GetConsoleType / XSystemGetDeviceType", "files: T:\\ title scratch storage", "argv"] - - def test_pass(self): - self.assertEqual(xc.parse_result("[PASS] argv", None, self.KNOWN), ("PASS", "argv", "")) - - def test_fail_with_colon_in_name_uses_the_running_check(self): - name = "kernelx: GetConsoleType / XSystemGetDeviceType" - got = xc.parse_result("[FAIL] " + name + ": GetConsoleType = 0", name, self.KNOWN) - self.assertEqual(got, ("FAIL", name, "GetConsoleType = 0")) - - def test_fail_with_colon_in_name_uses_known_names(self): - name = "kernelx: GetConsoleType / XSystemGetDeviceType" - got = xc.parse_result("[FAIL] " + name + ": GetConsoleType = 0", None, self.KNOWN) - self.assertEqual(got, ("FAIL", name, "GetConsoleType = 0")) - - def test_fail_unknown_name_splits_at_first_colon(self): - self.assertEqual(xc.parse_result("[FAIL] new check: why", None, []), ("FAIL", "new check", "why")) - - def test_skip(self): - self.assertEqual(xc.parse_result("[SKIP] argv", None, self.KNOWN), ("SKIP", "argv", "")) - - def test_other_lines(self): - for line in ("[RUN] argv", "[rt] unimplemented: kernelx.dll!GetConsoleType", "xcl_testtitle: start", ""): - self.assertIsNone(xc.parse_result(line, None, self.KNOWN)) - - -class Report(unittest.TestCase): - def runs(self): - x, l = xc.Run("XCL"), xc.Run("Leonida") - for n in ("a", "b", "c"): - x.set(n, status="PASS") - l.set("a", status="PASS") - l.set("b", status="FAIL", reason="null", unimplemented=["kernelx.dll!XMemAlloc"]) - l.set("c", status="HANG", reason="no output for 15 s", stack=["main: XTaskQueueTerminate"]) - l.set("d", status="FAIL", reason="only here") - return x, l - - def test_rows_follow_xcl_order_then_extra_checks(self): - x, l = self.runs() - r = xc.make_report(x, l, list(x.order), "gta6rt.exe", ".") - self.assertEqual([row["check"] for row in r["checks"]], ["a", "b", "c", "d"]) - - def test_counts_and_differences(self): - x, l = self.runs() - r = xc.make_report(x, l, list(x.order), "gta6rt.exe", ".") - self.assertEqual(r["summary"]["xcl"]["PASS"], 3) - self.assertEqual(r["summary"]["xcl"]["NOT RUN"], 1) - self.assertEqual(r["summary"]["leonida"], {"PASS": 1, "FAIL": 2, "SKIP": 0, "HANG": 1, "NOT RUN": 0}) - self.assertEqual(r["differences"], 3) - b = r["checks"][1] - self.assertEqual((b["leonida"], b["unimplemented"]), ("FAIL", ["kernelx.dll!XMemAlloc"])) - self.assertEqual(r["checks"][2]["stack"], ["main: XTaskQueueTerminate"]) - - def test_same_status_different_reason_differs(self): - x, l = xc.Run("XCL"), xc.Run("Leonida") - x.set("a", status="FAIL", reason="E_NOTIMPL") - l.set("a", status="FAIL", reason="null pointer") - x.set("b", status="FAIL", reason="same") - l.set("b", status="FAIL", reason="same") - r = xc.make_report(x, l, list(x.order), "gta6rt.exe", ".") - self.assertEqual([row["same"] for row in r["checks"]], [False, True]) - self.assertEqual(r["differences"], 1) - - -class Transcript(unittest.TestCase): - """run_title streams the title's output to the transcript file and keeps none of it on the Run.""" - - def test_output_goes_to_the_file(self): - class Sink: - def put(self, event): - pass - - script = "print('[RUN] a'); print('x' * 256); print('[PASS] a')" - with tempfile.TemporaryDirectory() as tmp: - path = os.path.join(tmp, "out.txt") - run = xc.Run("synthetic") - hung = xc.run_title([sys.executable, "-I", "-c", script], dict(os.environ), tmp, run, ["a"], 15, None, - Sink(), [], path) - with open(path, encoding="utf-8") as f: - lines = f.read().split("\n") - self.assertIsNone(hung) - self.assertEqual(run.checks["a"]["status"], "PASS") - self.assertTrue(lines[0].startswith("--- ")) - self.assertEqual(lines[1:4], ["[RUN] a", "x" * 256, "[PASS] a"]) - self.assertFalse(hasattr(run, "log")) - - -class Sink: - def put(self, event): - pass - - -class OutputEOF(unittest.TestCase): - def run_closed_pipe(self, after_close): - script = ("import os, time\n" - "print('[RUN] probe', flush=True)\n" - "os.close(1)\n" - "os.close(2)\n" + after_close) - run = xc.Run("synthetic") - with tempfile.TemporaryDirectory() as tmp: - hung = xc.run_title([sys.executable, "-I", "-c", script], os.environ, tmp, run, - ["probe"], 1, None, Sink(), []) - return hung, run - - def test_live_title_after_eof_returns_hung_check_for_restart(self): - hung, run = self.run_closed_pipe("time.sleep(3)") - self.assertEqual(hung, "probe") - self.assertEqual(run.checks["probe"]["status"], "HANG") - self.assertEqual(run.checks["probe"]["reason"], "no output for 1 s") - - def test_exit_after_eof_keeps_exit_code(self): - hung, run = self.run_closed_pipe("raise SystemExit(7)") - self.assertIsNone(hung) - self.assertEqual(run.exit_code, 7) - self.assertEqual(run.checks["probe"]["status"], "FAIL") - - -# A stand-in title: checks a, b and c; b hangs unless XCL_TESTTITLE_SKIP names it (or HONOUR_SKIP is 0). -FAKE_TITLE = """ -import os, sys, time -skip = os.environ.get("XCL_TESTTITLE_SKIP", "").split(";") -honour = os.environ.get("HONOUR_SKIP", "1") == "1" -for name in ("a", "b", "c"): - if honour and name in skip: - print("[SKIP] " + name, flush=True) - continue - print("[RUN] " + name, flush=True) - if name == "b": - time.sleep(60) - print("[PASS] " + name, flush=True) -""" - - -class Restart(unittest.TestCase): - """run_with_restarts: a hung check is recorded as HANG and the title is run again with it skipped.""" - - def run_fake(self, honour): - env = dict(os.environ, HONOUR_SKIP="1" if honour else "0") - cmd = [sys.executable, "-I", "-c", FAKE_TITLE] - attempts = [] - - def cmd_for(attempt): - attempts.append(attempt) - return cmd - - run = xc.Run("synthetic") - with tempfile.TemporaryDirectory() as tmp: - skip = xc.run_with_restarts(cmd_for, env, tmp, run, ["a", "b", "c"], 2, None, Sink(), [], 3, - os.path.join(tmp, "out.txt")) - return run, skip, attempts - - def test_hang_then_restart_with_the_check_skipped(self): - run, skip, attempts = self.run_fake(honour=True) - self.assertEqual(skip, ["b"]) - self.assertEqual(attempts, [0, 1]) - self.assertEqual(run.checks["b"]["status"], "HANG") - self.assertEqual(run.checks["b"]["reason"], "no output for 2 s") - self.assertEqual((run.checks["a"]["status"], run.checks["c"]["status"]), ("PASS", "PASS")) - - def test_stops_when_a_skipped_check_hangs_again(self): - run, skip, attempts = self.run_fake(honour=False) - self.assertEqual(skip, ["b"]) - self.assertEqual(attempts, [0, 1]) - self.assertEqual(run.checks["b"]["status"], "HANG") - self.assertNotIn("c", run.checks) # run_all marks it NOT RUN - - -class RestartTraces(unittest.TestCase): - """Hang restarts reset game/ and overlay/, while preserving earlier trace_N.jsonl files.""" - - def test_hang_restart_preserves_previous_trace_and_resets_game_and_overlay(self): - with tempfile.TemporaryDirectory() as tmp: - root = Path(tmp) - xcl_dir = root / "xcl" - rel = xcl_dir / "target" / "release" - rel.mkdir(parents=True) - for name in ("xcl.exe", "xcl_testtitle.exe", "testgame_mw.dll"): - (rel / name).write_bytes(b"stub") - testgame = xcl_dir / "tests" / "data" / "testgame" - testgame.mkdir(parents=True) - (testgame / "marker.txt").write_text("clean", encoding="utf-8", newline="\n") - - gta6rt = root / "gta6rt.exe" - gta6rt.write_bytes(b"stub") - - work = root / "work" - stale_dir = work / "leonida" - stale_dir.mkdir(parents=True) - stale_trace = stale_dir / "trace_stale.jsonl" - stale_trace.write_text("old\n", encoding="utf-8", newline="\n") - - seen = [] - - def fake_run_title(cmd, env, cwd, run, known, timeout, cdb, events, skip, transcript=None): - if run.label == "XCL": - for name in ("a", "b", "c"): - run.set(name, status="PASS") - return None - trace_path = Path(cmd[cmd.index("--trace") + 1]) - overlay_path = Path(cmd[cmd.index("--overlay") + 1]) - game_path = Path(cmd[cmd.index("--game-dir") + 1]) - attempt = len(seen) - seen.append({ - "attempt": attempt, - "trace": trace_path, - "overlay_existed": overlay_path.exists(), - "marker": (game_path / "marker.txt").read_text(encoding="utf-8"), - }) - overlay_path.mkdir(parents=True, exist_ok=True) - (overlay_path / "dirty.txt").write_text(f"attempt {attempt}\n", encoding="utf-8", newline="\n") - (game_path / "marker.txt").write_text(f"dirty {attempt}", encoding="utf-8", newline="\n") - trace_path.write_text(f'{{"attempt": {attempt}}}\n', encoding="utf-8", newline="\n") - if attempt == 0: - run.set("a", status="PASS") - run.set("b", status="HANG", reason="no output for 15 s") - return "b" - run.set("c", status="PASS") - return None - - args = argparse.Namespace( - xcl=str(xcl_dir), - gta6rt=str(gta6rt), - work=str(work), - timeout=15.0, - max_restarts=3, - skip=[], - cdb=None, - out=None, - ) - with mock.patch.object(xc, "run_title", side_effect=fake_run_title): - xc.run_all(args, Sink()) - - self.assertEqual(len(seen), 2) - self.assertFalse(stale_trace.exists()) - self.assertFalse(seen[1]["overlay_existed"]) - self.assertEqual(seen[1]["marker"], "clean") - - trace0 = work / "leonida" / "trace_0.jsonl" - trace1 = work / "leonida" / "trace_1.jsonl" - self.assertTrue(trace0.is_file(), "attempt 0 trace was deleted by attempt 1 restart") - self.assertTrue(trace1.is_file()) - self.assertEqual(trace0.read_text(encoding="utf-8"), '{"attempt": 0}\n') - self.assertEqual(trace1.read_text(encoding="utf-8"), '{"attempt": 1}\n') - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/test_xdxr_bvh.py b/tests/test_xdxr_bvh.py deleted file mode 100644 index 77ab6f188..000000000 --- a/tests/test_xdxr_bvh.py +++ /dev/null @@ -1,590 +0,0 @@ -"""Synthetic BVHs for tools/xdxr_bvh.py: layout, the traversal step, and closest hits against brute force. -No game data is read. - - python -I tests/test_xdxr_bvh.py -""" -import contextlib -import io -import math -import os -import random -import struct -import sys -import tempfile -import unittest - -ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) -sys.path.insert(0, os.path.join(ROOT, "tools")) - -import xdxr_bvh as X # noqa: E402 - -TRI = [[0.0, 0.0, 0.0], [1.0, 0.0, 0.0], [0.0, 1.0, 0.0]] - - -def rays(rng, n, spread=6.0, aim=3.0): - for _ in range(n): - o = [rng.uniform(-spread, spread) for _ in range(3)] - t = [rng.uniform(-aim, aim) for _ in range(3)] - yield o, [t[c] - o[c] for c in range(3)] - - -def same_hit(a, b): - if a is None or b is None: - return a is None and b is None - return (a["primitive"] == b["primitive"] and a["instance"] == b["instance"] - and math.isclose(a["t"], b["t"], rel_tol=1e-9, abs_tol=1e-12) - and all(math.isclose(a["bary"][k], b["bary"][k], abs_tol=1e-9) for k in range(2))) - - -class Layout(unittest.TestCase): - def test_pointer_encoding(self): - self.assertEqual(X.ptr(0x9B640 - 0x100 + 0x100 - 0x9B640 + 9941 * 64, X.BOX16), 0x136AC) # docs/bvh.md - self.assertEqual(X.ptr_offset(0x136AC), 9941 * 64) - self.assertEqual(X.ptr_type(0x136AC), X.BOX16) - with self.assertRaises(ValueError): - X.ptr(32, X.TRI0) - - def test_header_fields(self): - data, info = X.build_blas([TRI]) - flags, units, crc, n, *rest = struct.unpack_from("<4I6fIiIIII", data, 0) - self.assertEqual(flags, X.FLAG_BOTTOM_LEVEL | X.VERSION_2403) - self.assertEqual((units + 1) * 64, len(data)) - self.assertEqual(n, 1) - self.assertEqual(rest[0:6], [0.0, 0.0, 0.0, 1.0, 1.0, 0.0]) - nodes, _remap, root, elements, parents, cp = rest[6:] - self.assertEqual(root, info["root"]) - self.assertEqual(X.ptr_type(root), X.BOX32) - self.assertEqual(X.ptr_offset(root), nodes) - self.assertEqual(elements % 64, 0) - self.assertEqual(parents, 64) - self.assertEqual(cp, 0) - - def test_leaf_record(self): - data, info = X.build_blas([TRI], geometry_index=5, flags=0, opaque=True) - off = info["elements"] - self.assertEqual(struct.unpack_from("<9f", data, off), (0, 0, 0, 1, 0, 0, 0, 1, 0)) - gif, base, prim2, remap = struct.unpack_from("<4I", data, off + 48) - self.assertEqual(gif, 5 << 8 | 1) - self.assertEqual((base, prim2), (0, X.INVALID)) - self.assertEqual(remap & 0xFF, X.REMAP_IDENTITY) - - def test_unused_children_miss(self): - data, info = X.build_blas([TRI]) - root = X.ptr_offset(info["root"]) - self.assertEqual(struct.unpack_from("<4I", data, root)[1:], (X.INVALID,) * 3) - lo, hi = struct.unpack_from("<3f", data, root + 40), struct.unpack_from("<3f", data, root + 52) - self.assertTrue(all(lo[c] > hi[c] for c in range(3))) - - def test_box16_is_conservative(self): - rng = random.Random(7) - for _ in range(2000): - lo = [rng.uniform(-70000, 70000) for _ in range(3)] - hi = [x + rng.uniform(0, 3) for x in lo] - dlo, dhi = X.decode_box16(X.encode_box16(lo, hi)) - for c in range(3): - self.assertLessEqual(dlo[c], lo[c]) - self.assertGreaterEqual(dhi[c], hi[c]) - - def test_half_round_edges(self): - # runtime/src/xdxr_build.comp half_directed computes the same bits; check-build compares the GPU's BOX16 - # words with encode_box16, which uses this function - cases = [ - (0.0, False, 0x0000), (0.0, True, 0x0000), (-0.0, False, 0x8000), (-0.0, True, 0x8000), - (1.0, False, 0x3C00), (1.0, True, 0x3C00), (1.0001, False, 0x3C00), (1.0001, True, 0x3C01), - (-1.0001, False, 0xBC01), (-1.0001, True, 0xBC00), - (65504.0, True, 0x7BFF), (65505.0, False, 0x7BFF), (65505.0, True, 0x7C00), - (-65505.0, False, 0xFC00), (-65505.0, True, 0xFBFF), - (math.inf, False, 0x7BFF), (-math.inf, True, 0xFBFF), # an empty box stays min > max - (2.0 ** -14, False, 0x0400), (2.0 ** -14, True, 0x0400), - (3e-5, False, 0x0000), (3e-5, True, 0x0400), (-3e-5, False, 0x8400), (-3e-5, True, 0x8000), - (1e-30, True, 0x0400), (-1e-30, False, 0x8400), - ] - for x, up, want in cases: - self.assertEqual(X.half_round(x, up), want, (x, up)) - - def test_half_round_never_denormal(self): - rng = random.Random(3) - for _ in range(4000): - x = math.copysign(2.0 ** rng.uniform(-40, -10), rng.choice((-1, 1))) - for up in (False, True): - b = X.half_round(x, up) - self.assertFalse(b & 0x7C00 == 0 and b & 0x3FF, f"{x} -> denormal {b:#06x}") - v = X._half_value(b) - self.assertTrue(v >= x if up else v <= x) - - def test_box16_rounding_check(self): - data, _ = X.build_blas(X.random_scene(random.Random(4), 60), box16=True) - self.assertEqual(X.box16_rounding(data), []) - bad = bytearray(data) - root = X.ptr_offset(struct.unpack_from(" None: - triangles = [[(1, 0, 0), (2, 0, 0), (1, 1, 0)]] - blas, info = X.build_blas(triangles) - mem = X.Memory() - blas_va = mem.place(0x100000, blas) - # The x scale rounds down in float32. Its translation then places - # the triangle's left edge at x = 0 rather than x = 1. - matrix = [[16777217, 0, 0, -16777216], [0, 1, 0, 0], [0, 0, 1, 0]] - instance = X.Instance(matrix, blas_va, info["root"], info["bounds"]) - tlas, metadata = X.build_tlas([instance]) - root = X.ptr_offset(metadata["root"]) - instance_offset = X.ptr_offset(struct.unpack_from(" X.TRI3: - u = (X.ptr_offset(child) - self.info["elements"]) // 64 - struct.pack_into(" None: - # offsetToParents is the signed offset at +56 in the runtime header. - errors = self.corrupt(56, " None: - data, info = X.build_blas(X.grid_mesh(3), box16=True) - self.assertEqual(X.validate(data), []) - corrupt = bytearray(data) - root_unit = (X.ptr_offset(info["root"]) - info["elements"]) // X.UNIT - struct.pack_into("> 20} MiB") - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/test_zero_span_negative.py b/tests/test_zero_span_negative.py deleted file mode 100644 index dc6535e17..000000000 --- a/tests/test_zero_span_negative.py +++ /dev/null @@ -1,55 +0,0 @@ -"""Negative and out-of-range indices for tools/zero_span.py. - -The helper documents that its counts match len(buf[start:end]) and that all_zero() is true only for an empty -or all-zero slice. Python slices normalize negative indices and clamp out-of-range ones; the helper used to -clip only the upper bound, so the two disagreed for ranges such as buf[-5:10]. Synthetic buffers only. - - python -I tests/test_zero_span_negative.py -""" -import os -import sys -import unittest - -ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) -sys.path.insert(0, os.path.join(ROOT, "tools")) -import zero_span # noqa: E402 - -DATA = b"ABCDEFGHIJ" * 20 # 200 non-zero bytes -ZEROS = bytes(200) -RANGES = [ - (-30, 200), (-5, 10), (-200, -195), (-250, 250), - (0, -5), (0, 200), (195, 205), (190, 1000), (10, 5), -] - - -class ZeroSpanNegativeIndices(unittest.TestCase): - def test_counts_match_the_slice_for_negative_and_clamped_ranges(self): - for buf in (DATA, ZEROS): - for start, end in RANGES: - with self.subTest(buf=buf[:1], start=start, end=end): - zero, unread = zero_span.gap_split(buf, start, end) - self.assertEqual(zero + unread, len(buf[start:end])) - expected_zero = len(buf[start:end]) if not any(buf[start:end]) else 0 - self.assertEqual((zero, unread), (expected_zero, len(buf[start:end]) - expected_zero)) - - def test_all_zero_agrees_with_the_slice(self): - for buf in (DATA, ZEROS): - for start, end in RANGES: - with self.subTest(buf=buf[:1], start=start, end=end): - self.assertEqual(zero_span.all_zero(buf, start, end), not any(buf[start:end])) - - def test_exact_regressions(self): - self.assertEqual(zero_span.gap_split(DATA, -5, 10), (0, 0)) # slice is empty - self.assertEqual(zero_span.gap_split(DATA, -30, 200), (0, 30)) - self.assertEqual(zero_span.gap_split(ZEROS, -30, 200), (30, 0)) - self.assertFalse(zero_span.all_zero(DATA, 0, -5)) # 195 non-zero bytes - self.assertTrue(zero_span.all_zero(ZEROS, 0, -5)) - - def test_positive_ranges_are_unchanged(self): - self.assertEqual(zero_span.gap_split(DATA, 0, 10), (0, 10)) - self.assertEqual(zero_span.gap_split(ZEROS, 0, 10), (10, 0)) - self.assertEqual(zero_span.gap_split(DATA, 0, 1000), (0, 200)) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/winbatch.py b/tests/winbatch.py deleted file mode 100644 index 55d302853..000000000 --- a/tests/winbatch.py +++ /dev/null @@ -1,44 +0,0 @@ -"""Write a one-line Windows batch file (a fake tool for a test) that cmd.exe can run from any user folder. - -cmd.exe decodes a batch file with the console's OEM code page, not UTF-8, so a path with non-ASCII letters (a -user folder named in Cyrillic, say) written as UTF-8 becomes "The system cannot find the path specified". -Standard library only. -""" - - -def batch_path(path): - """A spelling of path that cmd.exe reads correctly from a batch file: as is when ASCII, else its 8.3 short name - (ASCII). Falls back to the long path where the volume has 8.3 names turned off.""" - if path.isascii(): - return path - import ctypes - buf = ctypes.create_unicode_buffer(32768) - n = ctypes.windll.kernel32.GetShortPathNameW(path, buf, len(buf)) - return buf.value if 0 < n < len(buf) else path - - -def _encodes(char): - try: - char.encode("oem") - return True - except UnicodeEncodeError: - return False - - -def write_python_cmd(cmd_path, python, script): - """Write cmd_path as a batch file that runs `python script` with the batch file's arguments. - - Raises unittest.SkipTest when a path has no 8.3 name and letters outside the OEM code page (Cyrillic on a - cp850 machine with 8.3 names off, say): cmd.exe couldn't run such a file in any encoding.""" - line = f'@"{batch_path(python)}" "{batch_path(script)}" %*\n' - try: - data = line.encode("oem") # the code page cmd.exe reads a batch file with - except UnicodeEncodeError: - import unittest - # Windows' "oem" codec doesn't report a useful position, so name the letters it can't encode here. - letters = "".join(sorted({c for c in line if not _encodes(c)})) - raise unittest.SkipTest(f"{letters!r} in a path has no 8.3 name and is outside the OEM code page," - " so cmd.exe can't run a batch file that names it; use an ASCII TEMP") from None - with open(cmd_path, "wb") as f: - f.write(data) - return cmd_path diff --git a/third_party/bcpack-rs/Cargo.toml b/third_party/bcpack-rs/Cargo.toml deleted file mode 100644 index 8f0cda870..000000000 --- a/third_party/bcpack-rs/Cargo.toml +++ /dev/null @@ -1,6 +0,0 @@ -[package] -name = "bcpack-rans" -version = "0.2.0" -edition = "2021" -license = "MIT OR Apache-2.0" -publish = false diff --git a/third_party/bcpack-rs/LICENSE-APACHE b/third_party/bcpack-rs/LICENSE-APACHE deleted file mode 100644 index 766eead37..000000000 --- a/third_party/bcpack-rs/LICENSE-APACHE +++ /dev/null @@ -1,15 +0,0 @@ -Apache License -Version 2.0, January 2004 -http://www.apache.org/licenses/ - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. diff --git a/third_party/bcpack-rs/LICENSE-MIT b/third_party/bcpack-rs/LICENSE-MIT deleted file mode 100644 index 7e357ee61..000000000 --- a/third_party/bcpack-rs/LICENSE-MIT +++ /dev/null @@ -1,21 +0,0 @@ -MIT License - -Copyright (c) 2026 Ahmet Dedeler - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. diff --git a/third_party/bcpack-rs/README.md b/third_party/bcpack-rs/README.md deleted file mode 100644 index 404ef2f3c..000000000 --- a/third_party/bcpack-rs/README.md +++ /dev/null @@ -1,7 +0,0 @@ -# BCPack entropy decoder - -Leonida uses `rans::decode_slice` to unpack BCPack lane symbols. The two Rust modules in `src/rans.rs` and `src/tables.rs` are copied verbatim from [Ahmet-Dedeler/bcpack-rs at 0a887de1edc9c22a425605091f1a8365fdf74dbb](https://github.com/Ahmet-Dedeler/bcpack-rs/tree/0a887de1edc9c22a425605091f1a8365fdf74dbb). The local Cargo manifest and module root expose these files as a standard-library-only crate. - -The upstream crate is licensed under MIT or Apache-2.0. Both license texts are included here. The rANS decoder and model tables also carry Microsoft's MIT notice. See [THIRD_PARTY_NOTICES.md](THIRD_PARTY_NOTICES.md). - -To update, copy both modules, both license files and the third-party notices from the same upstream revision. Update the revision here, then build the calibration library offline and run its synthetic DDS tests as described in the [calibrated export guide](../../tools/bcpack_calibration/README.md). diff --git a/third_party/bcpack-rs/THIRD_PARTY_NOTICES.md b/third_party/bcpack-rs/THIRD_PARTY_NOTICES.md deleted file mode 100644 index 945721111..000000000 --- a/third_party/bcpack-rs/THIRD_PARTY_NOTICES.md +++ /dev/null @@ -1,33 +0,0 @@ -# Third-party notices - -## Microsoft silicon-rans - -`src/tables.rs` and `python/bcpack_tables.py` contain the rANS model tables (`base_table`, -`freq_table`, `rf_table`, `rs_table`, `rn_table`) of `mdu_minirans.v` from -https://github.com/microsoft/silicon-rans (commit 2f6827d), generated by `tools/gen_tables.py`. -The per-lane decoder in `src/rans.rs` and `python/bcpack.py` is a port of that file's `decoder` -module. It is used under the following license: - -``` -MIT License - -Copyright (c) Microsoft Corporation. - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE -``` diff --git a/third_party/bcpack-rs/src/lib.rs b/third_party/bcpack-rs/src/lib.rs deleted file mode 100644 index 70020322c..000000000 --- a/third_party/bcpack-rs/src/lib.rs +++ /dev/null @@ -1,3 +0,0 @@ -//! Entropy decoder used by Leonida's calibrated texture reader. -pub mod rans; -pub mod tables; diff --git a/third_party/bcpack-rs/src/rans.rs b/third_party/bcpack-rs/src/rans.rs deleted file mode 100644 index 5dc2c0d90..000000000 --- a/third_party/bcpack-rs/src/rans.rs +++ /dev/null @@ -1,861 +0,0 @@ -//! Multi-lane MDU rANS decoder (entropy layer). -//! -//! Each lane is a cycle-level port of the `decoder` module in Microsoft's -//! MIT-licensed `silicon-rans` reference Verilog (`mdu_minirans.v`): two phases -//! per clock, a one-byte input buffer, a one-symbol output buffer, the -//! HDR0/HDR1/HDR2/PROCESSING/DRAINING control states, the flush bit, the 2-bit -//! alphabet narrowing, 8/16-bit fragment lengths (+1 / +257) and the legal end -//! states `L`, `L >> 8`, `L >> 16`. -//! -//! Two parts are not in the published Verilog and were established on retail -//! data (exact convergence on every lane of 15,000 sampled chunks, and every -//! structural variant fails, see `docs/BCPACK_SPEC.md`): -//! -//! * feeder: in phase 0 of each clock, lanes that request a byte are served -//! from the single stream in lane order, at most [`FEED_WINDOW`] bytes per -//! clock; a lane that is not served stalls for that clock; -//! * symbol vector: one slot per lane; a lane may hand over a symbol only while -//! its slot is empty, and all slots are released together once every lane -//! that is still active holds a symbol (lockstep). -//! -//! The byte schedule therefore depends only on the lane states, which is what -//! lets [`crate::encode`] build valid interleaved streams for tests. - -use crate::tables::{BASE_TABLE, FREQ_TABLE, RF_TABLE, RN_TABLE, RS_TABLE}; -use std::fmt; -use std::sync::OnceLock; - -/// rANS lower bound (`MDU_RANS_LOWER_LIMIT`). -pub const L: u32 = 1 << 24; -/// Bytes the feeder hands to the lanes per clock (`MDU_RANS_FEED_WINDOW`). -pub const FEED_WINDOW: usize = 8; -/// Maximum lanes per stream supported by this implementation. -pub const MAX_LANES: usize = 16; - -/// True for the three legal end states of a lane. -#[inline] -pub fn is_legal_end_state(x: u32) -> bool { - x == L || x == L >> 8 || x == L >> 16 -} - -/// One static model (alphabet index `eab` = bits - 1, model `q`). -#[derive(Clone, Debug)] -pub struct Model { - pub eab: u8, - pub q: u8, - base: [u16; 10], - freq: [u16; 10], - rf: [u32; 10], - rs: [u8; 10], - rn: [u16; 10], - nseg: u8, - /// Segment thresholds for the branch-free inverse: `base[k]` for enabled - /// segments 1..nseg, `0x10000` (never reached) for disabled ones. - thr: [u32; 10], - /// Full inverse table (cf -> symbol), built on first use. - lut: OnceLock>, -} - -impl Model { - fn build(eab: usize, q: usize) -> Model { - let mut thr = [0x10000u32; 10]; - for k in 1..eab + 2 { - thr[k] = BASE_TABLE[eab][q][k] as u32; - } - Model { - thr, - eab: eab as u8, - q: q as u8, - base: BASE_TABLE[eab][q], - freq: FREQ_TABLE[eab][q], - rf: RF_TABLE[eab][q], - rs: RS_TABLE[eab][q], - rn: RN_TABLE[eab][q], - nseg: (eab + 2) as u8, - lut: OnceLock::new(), - } - } - - /// The 65536-entry inverse table. Filled from the forward intervals - /// `[cf, cf + f)` of every symbol (cheap), plus `cf = 0` from the exact - /// path. A unit test checks it equals `inverse_exact` for every cf. - pub fn lut(&self) -> &[u16] { - self.lut.get_or_init(|| { - let mut t = vec![0u16; 65536].into_boxed_slice(); - for s in 0..(1u32 << (self.eab + 1)) { - let (f, cf) = self.forward(s as u16); - let end = (cf + f).min(65536); - for v in &mut t[cf as usize..end as usize] { - *v = s as u16; - } - } - t[0] = self.inverse_exact(0); - t - }) - } - - /// Symbol for the low 16 state bits, exactly as the Verilog computes it: - /// comparator chain over enabled segments, then the reciprocal multiply. - #[inline] - pub fn inverse_exact(&self, cf: u16) -> u16 { - let cf = cf as u32; - let mut seg = 0usize; - let mut k = self.nseg as usize - 1; - while k > 0 { - if cf >= self.base[k] as u32 { - seg = k; - break; - } - k -= 1; - } - let base_x = if seg == 0 { 0 } else { 1u32 << (seg - 1) }; - let dist = (cf - .wrapping_sub(self.base[seg] as u32) - .wrapping_add(self.rn[seg] as u32)) - & 0xFFFF; - let add_mul = dist.wrapping_mul(self.rf[seg]); - let steps = ((add_mul >> 15) >> self.rs[seg]) & 0x1FF; - ((base_x + steps) & 0x1FF) as u16 - } - - /// Branch-free inverse: the enabled segment bases are non-decreasing, so - /// the priority encoder equals the count of thresholds `cf` reaches. A unit - /// test checks this equals [`Model::inverse_exact`] for every model and cf. - #[inline(always)] - pub fn inverse_fast(&self, cf: u16) -> u16 { - let cf = cf as u32; - let mut seg = 0usize; - for k in 1..10 { - seg += (cf >= self.thr[k]) as usize; - } - let base_x = (1u32 << seg) >> 1; - let dist = (cf - .wrapping_sub(self.base[seg] as u32) - .wrapping_add(self.rn[seg] as u32)) - & 0xFFFF; - let steps = ((dist.wrapping_mul(self.rf[seg]) >> 15) >> self.rs[seg]) & 0x1FF; - ((base_x + steps) & 0x1FF) as u16 - } - - /// Inverse through the table. Same result as [`Model::inverse_exact`]. - #[inline] - pub fn inverse(&self, cf: u16) -> u16 { - self.lut()[cf as usize] - } - - /// `(freq, cumulative freq)` of `sym`. Slot 0 is reserved: a symbol whose - /// cumulative frequency would be 0 gets `(f - 1, 1)`. - #[inline] - pub fn forward(&self, sym: u16) -> (u32, u32) { - let s = sym as u32; - let seg = (32 - s.leading_zeros()) as usize; - let st = if seg == 0 { 0 } else { 1u32 << (seg - 1) }; - let fa = self.freq[seg] as u32; - let cfa = (self.base[seg] as u32).wrapping_add(fa.wrapping_mul(s - st)) & 0xFFFF; - if cfa == 0 { - (fa.wrapping_sub(1) & 0xFFFF, 1) - } else { - (fa, cfa) - } - } - - /// State after decoding `sym` from state `x`. - #[inline] - pub fn advance(&self, x: u32, sym: u16) -> u32 { - let (f, cf) = self.forward(sym); - f.wrapping_mul(x >> 16) - .wrapping_add(x & 0xFFFF) - .wrapping_sub(cf) - } -} - -static MODELS: OnceLock> = OnceLock::new(); - -/// The 9 x 16 models, built once. -pub fn model(eab: u8, q: u8) -> &'static Model { - let all = MODELS.get_or_init(|| { - let mut v = Vec::with_capacity(144); - for e in 0..9 { - for q in 0..16 { - v.push(Model::build(e, q)); - } - } - v - }); - &all[eab as usize * 16 + q as usize] -} - -/// Why a stream failed to decode. -#[derive(Clone, Debug, PartialEq, Eq)] -pub enum DecodeError { - /// A fragment header selects an alphabet index above 8 (undefined in the Verilog). - BadHeader { lane: usize, eab: u8 }, - /// No lane made progress for 64 clocks: the stream ran out or is not this format. - NoProgress { consumed: usize }, - /// The cycle budget ran out. - CycleLimit, - /// Every lane finished but these lanes ended outside the legal end states. - IllegalEndState { lanes: Vec }, - /// Bytes after the last consumed byte are not all zero padding. - TrailingData { consumed: usize, len: usize }, - /// Invalid arguments (lane count, block count). - Invalid(String), -} - -impl fmt::Display for DecodeError { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - match self { - DecodeError::BadHeader { lane, eab } => { - write!( - f, - "lane {lane}: fragment header selects alphabet index {eab} (> 8)" - ) - } - DecodeError::NoProgress { consumed } => { - write!( - f, - "no progress after {consumed} bytes (truncated stream or not BCPack BC1)" - ) - } - DecodeError::CycleLimit => write!(f, "cycle limit reached"), - DecodeError::IllegalEndState { lanes } => { - write!(f, "lanes {lanes:?} ended in an illegal rANS state") - } - DecodeError::TrailingData { consumed, len } => { - write!( - f, - "stream ended after {consumed} of {len} bytes but the rest is not zero padding" - ) - } - DecodeError::Invalid(s) => write!(f, "{s}"), - } - } -} - -impl std::error::Error for DecodeError {} - -/// Where lane bytes come from. -pub trait ByteSource { - /// Next byte for `lane`, or `None` if the stream is exhausted. - fn next(&mut self, lane: usize) -> Option; -} - -/// The normal case: one shared stream. -pub struct SliceSource<'a> { - pub data: &'a [u8], - pub pos: usize, -} - -impl ByteSource for SliceSource<'_> { - #[inline] - fn next(&mut self, _lane: usize) -> Option { - let b = *self.data.get(self.pos)?; - self.pos += 1; - Some(b) - } -} - -const IDLE: u8 = 0; -const HDR0: u8 = 1; -const HDR1: u8 = 2; -const HDR2: u8 = 3; -const PROC: u8 = 4; -const DRAIN: u8 = 5; - -#[derive(Clone)] -struct Lane { - ab: u8, - target: u32, - state: u8, - ib: u8, - ib_full: bool, - sym: u16, - sym_full: bool, - in_rem: u32, - out_rem: u32, - p0: u32, - p1: u32, - hdr3: bool, - flush: bool, - q: u8, - eab: u8, - model: &'static Model, - done: bool, - go: bool, - stall: bool, - nsyms: u32, - nbytes: u32, - nfrags: u32, - final_state: u32, -} - -impl Lane { - #[inline] - fn need_byte(&self) -> bool { - !self.ib_full - && match self.state { - HDR0 | HDR1 | HDR2 => true, - PROC => self.in_rem > 0, - _ => false, - } - } -} - -/// Per-lane statistics of a successful decode. -#[derive(Clone, Debug, Default)] -pub struct LaneStats { - pub bytes: u32, - pub fragments: u32, - pub final_state: u32, -} - -/// Result of [`decode_lanes`]: `symbols[lane * target + i]` (lane major). -#[derive(Clone, Debug)] -pub struct LaneOutput { - pub lanes: usize, - pub target: usize, - pub symbols: Vec, - pub consumed: usize, - pub cycles: u64, - pub stats: Vec, -} - -impl LaneOutput { - /// Symbols of one lane. - pub fn lane(&self, i: usize) -> &[u16] { - &self.symbols[i * self.target..(i + 1) * self.target] - } -} - -/// Decode `alphabet_bits.len()` lanes of `target` symbols each from a byte source. -/// -/// `alphabet_bits[i]` is lane i's symbol width minus 1 (the Verilog input). -/// `stream_len` bounds the cycle budget the same way as the reference model -/// (`64 * (lanes * target + stream_len) + 1000`). -pub fn decode_lanes( - src: &mut S, - alphabet_bits: &[u8], - target: usize, - stream_len: usize, -) -> Result { - let n = alphabet_bits.len(); - if n == 0 || n > MAX_LANES { - return Err(DecodeError::Invalid(format!( - "lane count {n} not in 1..={MAX_LANES}" - ))); - } - if target == 0 || target > u32::MAX as usize / 2 { - return Err(DecodeError::Invalid(format!("bad symbol count {target}"))); - } - let m0 = model(0, 0); - let mut lanes: Vec = alphabet_bits - .iter() - .map(|&ab| Lane { - ab, - target: target as u32, - state: IDLE, - ib: 0, - ib_full: false, - sym: 0, - sym_full: false, - in_rem: 0, - out_rem: 0, - p0: 0, - p1: 0, - hdr3: false, - flush: false, - q: 0, - eab: 0, - model: m0, - done: false, - go: true, - stall: false, - nsyms: 0, - nbytes: 0, - nfrags: 0, - final_state: 0, - }) - .collect(); - let mut symbols = vec![0u16; n * target]; - let mut slots: u32 = 0; - let mut pos: usize = 0; - let mut exhausted = false; - let mut cycle: u64 = 0; - let max_cycles: u64 = 64 * (n as u64 * target as u64 + stream_len as u64) + 1000; - let mut total_syms: u64 = 0; - let mut last_prog = (usize::MAX, u64::MAX, u32::MAX); - let mut last_change: u64 = 0; - - while cycle < max_cycles { - // ---------------- phase 0: forward update, feed, hand-off ---------------- - let mut served = 0usize; - for (i, ln) in lanes.iter_mut().enumerate() { - let bit = 1u32 << i; - let blocked_out = ln.sym_full && (slots & bit) != 0; - let need = ln.need_byte(); - let mut valid = false; - let mut byte = 0u8; - if need && !blocked_out && served < FEED_WINDOW && !exhausted { - match src.next(i) { - Some(b) => { - valid = true; - byte = b; - } - None => exhausted = true, - } - } - ln.stall = (need && !valid) || blocked_out; - if ln.stall { - continue; - } - if ln.state == PROC || ln.state == DRAIN { - ln.p0 = if ln.sym_full { - ln.model.advance(ln.p1, ln.sym) - } else { - ln.p1 - }; - } - if valid { - ln.ib = byte; - ln.ib_full = true; - pos += 1; - served += 1; - ln.nbytes += 1; - } - if ln.sym_full { - slots |= bit; - // nsyms < target: a symbol is only produced while out_rem > 0. - debug_assert!((ln.nsyms as usize) < target); - unsafe { *symbols.get_unchecked_mut(i * target + ln.nsyms as usize) = ln.sym }; - ln.nsyms += 1; - total_syms += 1; - ln.sym_full = false; - } - } - // ---------------- phase 1: header FSM, renorm, decode ---------------- - // (the lockstep bookkeeping is folded into the same pass: slots do not - // change in phase 1) - let mut active = 0u32; - let mut finished = true; - let mut state_sum = 0u32; - for (i, ln) in lanes.iter_mut().enumerate() { - if !ln.stall { - phase1(i, ln)?; - } - let bit = 1u32 << i; - if !(ln.done && !ln.sym_full && (slots & bit) == 0) { - active |= bit; - } - finished &= ln.done && !ln.sym_full; - state_sum += ln.state as u32; - } - // ---------------- lockstep symbol vector ---------------- - if slots != 0 && (slots & active) == active { - slots = 0; - } - cycle += 1; - if finished { - let bad: Vec = (0..n) - .filter(|&i| !is_legal_end_state(lanes[i].final_state)) - .collect(); - if !bad.is_empty() { - return Err(DecodeError::IllegalEndState { lanes: bad }); - } - let stats = lanes - .iter() - .map(|l| LaneStats { - bytes: l.nbytes, - fragments: l.nfrags, - final_state: l.final_state, - }) - .collect(); - return Ok(LaneOutput { - lanes: n, - target, - symbols, - consumed: pos, - cycles: cycle, - stats, - }); - } - let prog = (pos, total_syms, state_sum); - if prog != last_prog { - last_prog = prog; - last_change = cycle; - } else if cycle - last_change > 64 { - return Err(DecodeError::NoProgress { consumed: pos }); - } - } - Err(DecodeError::CycleLimit) -} - -/// Phase 1 of one lane (header FSM, renormalisation, symbol decode). -#[inline(always)] -fn phase1(i: usize, ln: &mut Lane) -> Result<(), DecodeError> { - { - { - match ln.state { - IDLE => { - if ln.go { - ln.go = false; - ln.state = HDR0; - ln.out_rem = ln.target; - ln.p0 = 0; - ln.p1 = 0; - } - } - HDR0 => { - if ln.ib_full { - let b = ln.ib; - ln.ib_full = false; - ln.in_rem = 0; - ln.state = HDR1; - ln.q = b & 15; - ln.hdr3 = b & 0x20 != 0; - ln.flush = b & 0x10 != 0; - let e = (ln.ab as i32 - (b >> 6) as i32) & 15; - ln.eab = if e < 10 { e as u8 } else { 9 }; - ln.nfrags += 1; - if ln.eab > 8 { - return Err(DecodeError::BadHeader { - lane: i, - eab: ln.eab, - }); - } - } - } - HDR1 => { - if ln.ib_full { - ln.ib_full = false; - ln.model = model(ln.eab, ln.q); - if ln.hdr3 { - ln.in_rem = ln.ib as u32; - ln.state = HDR2; - } else { - ln.in_rem = ln.ib as u32 + 1; - ln.state = PROC; - } - } - } - HDR2 => { - if ln.ib_full { - ln.ib_full = false; - ln.in_rem = (((ln.ib as u32) << 8) | (ln.in_rem & 0xFF)) + 257; - ln.state = PROC; - } - } - st => { - // PROC or DRAIN - let will = st == PROC && ln.p0 < L && ln.in_rem > 0 && ln.ib_full; - let x = if will { - ((ln.p0 & 0xFF_FFFF) << 8) | ln.ib as u32 - } else { - ln.p0 - }; - let nsf = x > L && ln.out_rem > 0; - if nsf { - ln.out_rem -= 1; - ln.sym = ln.model.inverse(x as u16); - } - let new_out = ln.out_rem; - ln.p1 = x; - ln.sym_full = nsf; - if st == PROC { - if will { - ln.in_rem -= 1; - ln.ib_full = false; - } - if ln.in_rem == 0 { - if new_out > 0 { - if x == L { - ln.state = HDR0; - if ln.flush { - ln.p1 = 0; - } - } else { - ln.state = DRAIN; - } - } else { - ln.done = true; - ln.state = IDLE; - ln.final_state = if nsf { ln.model.advance(x, ln.sym) } else { x }; - } - } - } else if x <= L { - if new_out > 0 { - ln.state = HDR0; - if ln.flush { - ln.p0 = 0; - ln.p1 = 0; - } - } else { - ln.state = IDLE; - ln.done = true; - ln.final_state = if nsf { ln.model.advance(x, ln.sym) } else { x }; - } - } - } - } - } - } - Ok(()) -} - -/// Fast decoder for the shared-stream case. Same clocked model as -/// [`decode_lanes`] (the tests check both agree on synthetic and real -/// streams), written with few data-dependent branches: the lanes spend almost -/// every clock in PROCESSING, so that path is computed with selects and the -/// rare state changes go through [`phase1`]. -pub fn decode_lanes_fast( - data: &[u8], - alphabet_bits: &[u8], - target: usize, -) -> Result { - let n = alphabet_bits.len(); - if n == 0 || n > MAX_LANES { - return Err(DecodeError::Invalid(format!( - "lane count {n} not in 1..={MAX_LANES}" - ))); - } - if target == 0 || target > u32::MAX as usize / 2 { - return Err(DecodeError::Invalid(format!("bad symbol count {target}"))); - } - if data.is_empty() { - return Err(DecodeError::NoProgress { consumed: 0 }); - } - let m0 = model(0, 0); - let lut0: &'static [u16] = m0.lut(); - let mut lanes: Vec = alphabet_bits - .iter() - .map(|&ab| Lane { - ab, - target: target as u32, - state: IDLE, - ib: 0, - ib_full: false, - sym: 0, - sym_full: false, - in_rem: 0, - out_rem: 0, - p0: 0, - p1: 0, - hdr3: false, - flush: false, - q: 0, - eab: 0, - model: m0, - done: false, - go: true, - stall: false, - nsyms: 0, - nbytes: 0, - nfrags: 0, - final_state: 0, - }) - .collect(); - let mut luts: Vec<&'static [u16]> = vec![lut0; n]; - // One spare slot per lane: the symbol store below writes unconditionally. - let stride = target + 1; - let mut store = vec![0u16; n * stride]; - let len = data.len(); - let mut slots: u32 = 0; - let mut pos: usize = 0; - let mut cycle: u64 = 0; - let max_cycles: u64 = 64 * (n as u64 * target as u64 + len as u64) + 1000; - let mut total_syms: u64 = 0; - let mut last_prog = (usize::MAX, u64::MAX, u32::MAX); - let mut last_change: u64 = 0; - - while cycle < max_cycles { - // ---------------- phase 0 ---------------- - let mut served = 0usize; - for (i, ln) in lanes.iter_mut().enumerate() { - let bit = 1u32 << i; - let st = ln.state; - let blocked_out = ln.sym_full & (slots & bit != 0); - let need = - !ln.ib_full & (((st >= HDR0) & (st <= HDR2)) | ((st == PROC) & (ln.in_rem > 0))); - let grant = need & !blocked_out & (served < FEED_WINDOW) & (pos < len); - let stall = (need & !grant) | blocked_out; - ln.stall = stall; - let go = !stall; - if st >= PROC { - let adv = ln.model.advance(ln.p1, ln.sym); - let np0 = if ln.sym_full { adv } else { ln.p1 }; - ln.p0 = if go { np0 } else { ln.p0 }; - } - let b = data[pos.min(len - 1)]; - ln.ib = if grant { b } else { ln.ib }; - ln.ib_full |= grant; - pos += grant as usize; - served += grant as usize; - ln.nbytes += grant as u32; - let push = go & ln.sym_full; - // nsyms <= target, and slot `target` is the spare. - unsafe { *store.get_unchecked_mut(i * stride + ln.nsyms as usize) = ln.sym }; - ln.nsyms += push as u32; - total_syms += push as u64; - slots |= (push as u32) << i; - ln.sym_full &= !push; - } - // ---------------- phase 1 ---------------- - let mut active = 0u32; - let mut finished = true; - let mut state_sum = 0u32; - for (i, ln) in lanes.iter_mut().enumerate() { - if !ln.stall { - let st = ln.state; - if st >= PROC { - let is_proc = st == PROC; - let will = is_proc & (ln.p0 < L) & (ln.in_rem > 0) & ln.ib_full; - let x = if will { - (ln.p0 << 8) | ln.ib as u32 - } else { - ln.p0 - }; - let nsf = (x > L) & (ln.out_rem > 0); - ln.sym = ln.model.inverse_fast(x as u16); - ln.out_rem -= nsf as u32; - ln.p1 = x; - ln.sym_full = nsf; - ln.in_rem -= will as u32; - ln.ib_full &= !will; - let change = if is_proc { ln.in_rem == 0 } else { x <= L }; - if change { - transition(ln, x, nsf); - } - } else { - phase1(i, ln)?; - if ln.state == PROC || ln.state == HDR2 { - luts[i] = ln.model.lut(); - } - } - } - let bit = 1u32 << i; - if !(ln.done & !ln.sym_full & (slots & bit == 0)) { - active |= bit; - } - finished &= ln.done & !ln.sym_full; - state_sum += ln.state as u32; - } - if slots != 0 && (slots & active) == active { - slots = 0; - } - cycle += 1; - if finished { - let bad: Vec = (0..n) - .filter(|&i| !is_legal_end_state(lanes[i].final_state)) - .collect(); - if !bad.is_empty() { - return Err(DecodeError::IllegalEndState { lanes: bad }); - } - let mut symbols = vec![0u16; n * target]; - for i in 0..n { - symbols[i * target..(i + 1) * target] - .copy_from_slice(&store[i * stride..i * stride + target]); - } - let stats = lanes - .iter() - .map(|l| LaneStats { - bytes: l.nbytes, - fragments: l.nfrags, - final_state: l.final_state, - }) - .collect(); - return Ok(LaneOutput { - lanes: n, - target, - symbols, - consumed: pos, - cycles: cycle, - stats, - }); - } - let prog = (pos, total_syms, state_sum); - if prog != last_prog { - last_prog = prog; - last_change = cycle; - } else if cycle - last_change > 64 { - return Err(DecodeError::NoProgress { consumed: pos }); - } - } - Err(DecodeError::CycleLimit) -} - -/// End of a fragment's input (PROCESSING) or of draining: same rules as [`phase1`]. -#[cold] -fn transition(ln: &mut Lane, x: u32, nsf: bool) { - let new_out = ln.out_rem; - if ln.state == PROC { - if new_out > 0 { - if x == L { - ln.state = HDR0; - if ln.flush { - ln.p1 = 0; - } - } else { - ln.state = DRAIN; - } - } else { - ln.done = true; - ln.state = IDLE; - ln.final_state = if nsf { ln.model.advance(x, ln.sym) } else { x }; - } - } else if new_out > 0 { - ln.state = HDR0; - if ln.flush { - ln.p0 = 0; - ln.p1 = 0; - } - } else { - ln.state = IDLE; - ln.done = true; - ln.final_state = if nsf { ln.model.advance(x, ln.sym) } else { x }; - } -} - -/// Decode lanes from a byte slice and check that everything after the last -/// consumed byte is zero padding. -pub fn decode_slice( - data: &[u8], - alphabet_bits: &[u8], - target: usize, -) -> Result { - let out = decode_lanes_fast(data, alphabet_bits, target)?; - if data[out.consumed..].iter().any(|&b| b != 0) { - return Err(DecodeError::TrailingData { - consumed: out.consumed, - len: data.len(), - }); - } - Ok(out) -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn inverse_matches_exact_division_for_every_model() { - // The reciprocal path must invert forward() for every cf, and the - // table must agree with the exact path everywhere (cf = 0 included). - for eab in 0..9u8 { - for q in 0..16u8 { - let m = model(eab, q); - assert_eq!(m.inverse(0), m.inverse_exact(0)); - assert_eq!(m.inverse_fast(0), m.inverse_exact(0)); - for cf in 1..=0xFFFFu32 { - let s = m.inverse(cf as u16); - assert_eq!(s, m.inverse_exact(cf as u16), "eab {eab} q {q} cf {cf}"); - assert_eq!( - s, - m.inverse_fast(cf as u16), - "fast: eab {eab} q {q} cf {cf}" - ); - let (f, c) = m.forward(s); - assert!(c <= cf && cf < c + f, "eab {eab} q {q} cf {cf} sym {s}"); - } - } - } - } -} diff --git a/third_party/bcpack-rs/src/tables.rs b/third_party/bcpack-rs/src/tables.rs deleted file mode 100644 index c7320a6f1..000000000 --- a/third_party/bcpack-rs/src/tables.rs +++ /dev/null @@ -1,914 +0,0 @@ -// Exact rANS model tables of the Xbox Series MDU decoder. -// -// Generated by tools/gen_tables.py from mdu_minirans.v in -// https://github.com/microsoft/silicon-rans (commit 2f6827d), MIT License, -// Copyright (c) Microsoft Corporation. See THIRD_PARTY_NOTICES.md. Do not edit. -// -// Index [eab][q][seg]: eab = alphabet bits - 1 (0..8), q = model (0..15), -// seg = 0 for symbol 0, k >= 1 for symbols [2^(k-1), 2^k). - -/// SHA-256 of the canonical table text (see `tools/gen_tables.py`). -pub const TABLES_SHA256: &str = "346464df83c8be00905672091f2c64ac2eb0bb02efa9074a78b7620956f362d7"; - -pub static BASE_TABLE: [[[u16; 10]; 16]; 9] = [ - [ - [0, 32768, 0, 0, 0, 0, 0, 0, 0, 0], - [0, 38761, 0, 0, 0, 0, 0, 0, 0, 0], - [0, 44484, 0, 0, 0, 0, 0, 0, 0, 0], - [0, 49818, 0, 0, 0, 0, 0, 0, 0, 0], - [0, 54623, 0, 0, 0, 0, 0, 0, 0, 0], - [0, 58721, 0, 0, 0, 0, 0, 0, 0, 0], - [0, 61911, 0, 0, 0, 0, 0, 0, 0, 0], - [0, 64036, 0, 0, 0, 0, 0, 0, 0, 0], - [0, 65121, 0, 0, 0, 0, 0, 0, 0, 0], - [0, 65477, 0, 0, 0, 0, 0, 0, 0, 0], - [0, 65534, 0, 0, 0, 0, 0, 0, 0, 0], - [0, 65535, 0, 0, 0, 0, 0, 0, 0, 0], - [0, 65535, 0, 0, 0, 0, 0, 0, 0, 0], - [0, 65535, 0, 0, 0, 0, 0, 0, 0, 0], - [0, 65535, 0, 0, 0, 0, 0, 0, 0, 0], - [0, 65535, 0, 0, 0, 0, 0, 0, 0, 0], - ], - [ - [0, 16384, 32768, 0, 0, 0, 0, 0, 0, 0], - [0, 21168, 38760, 0, 0, 0, 0, 0, 0, 0], - [0, 26354, 44484, 0, 0, 0, 0, 0, 0, 0], - [0, 31900, 49818, 0, 0, 0, 0, 0, 0, 0], - [0, 37750, 54624, 0, 0, 0, 0, 0, 0, 0], - [0, 43800, 58720, 0, 0, 0, 0, 0, 0, 0], - [0, 49850, 61912, 0, 0, 0, 0, 0, 0, 0], - [0, 55537, 64036, 0, 0, 0, 0, 0, 0, 0], - [0, 60308, 65120, 0, 0, 0, 0, 0, 0, 0], - [0, 63575, 65476, 0, 0, 0, 0, 0, 0, 0], - [0, 65132, 65534, 0, 0, 0, 0, 0, 0, 0], - [0, 65511, 65534, 0, 0, 0, 0, 0, 0, 0], - [0, 65533, 65534, 0, 0, 0, 0, 0, 0, 0], - [0, 65533, 65534, 0, 0, 0, 0, 0, 0, 0], - [0, 65533, 65534, 0, 0, 0, 0, 0, 0, 0], - [0, 65533, 65534, 0, 0, 0, 0, 0, 0, 0], - ], - [ - [0, 8192, 16384, 32768, 0, 0, 0, 0, 0, 0], - [0, 11073, 21168, 38760, 0, 0, 0, 0, 0, 0], - [0, 14406, 26354, 44484, 0, 0, 0, 0, 0, 0], - [0, 18234, 31900, 49816, 0, 0, 0, 0, 0, 0], - [0, 22624, 37750, 54624, 0, 0, 0, 0, 0, 0], - [0, 27657, 43800, 58720, 0, 0, 0, 0, 0, 0], - [0, 33414, 49850, 61912, 0, 0, 0, 0, 0, 0], - [0, 39920, 55536, 64036, 0, 0, 0, 0, 0, 0], - [0, 47024, 60308, 65120, 0, 0, 0, 0, 0, 0], - [0, 54201, 63576, 65476, 0, 0, 0, 0, 0, 0], - [0, 60388, 65132, 65532, 0, 0, 0, 0, 0, 0], - [0, 64250, 65512, 65532, 0, 0, 0, 0, 0, 0], - [0, 65456, 65530, 65532, 0, 0, 0, 0, 0, 0], - [0, 65529, 65530, 65532, 0, 0, 0, 0, 0, 0], - [0, 65529, 65530, 65532, 0, 0, 0, 0, 0, 0], - [0, 65529, 65530, 65532, 0, 0, 0, 0, 0, 0], - ], - [ - [0, 4096, 8192, 16384, 32768, 0, 0, 0, 0, 0], - [0, 5665, 11072, 21168, 38760, 0, 0, 0, 0, 0], - [0, 7539, 14406, 26352, 44480, 0, 0, 0, 0, 0], - [0, 9773, 18234, 31900, 49816, 0, 0, 0, 0, 0], - [0, 12447, 22624, 37752, 54624, 0, 0, 0, 0, 0], - [0, 15679, 27656, 43800, 58720, 0, 0, 0, 0, 0], - [0, 19640, 33414, 49848, 61912, 0, 0, 0, 0, 0], - [0, 24559, 39920, 55536, 64032, 0, 0, 0, 0, 0], - [0, 30704, 47024, 60308, 65120, 0, 0, 0, 0, 0], - [0, 38280, 54200, 63576, 65480, 0, 0, 0, 0, 0], - [0, 47169, 60388, 65132, 65528, 0, 0, 0, 0, 0], - [0, 56354, 64250, 65512, 65528, 0, 0, 0, 0, 0], - [0, 63248, 65456, 65524, 65528, 0, 0, 0, 0, 0], - [0, 65465, 65522, 65524, 65528, 0, 0, 0, 0, 0], - [0, 65521, 65522, 65524, 65528, 0, 0, 0, 0, 0], - [0, 65521, 65522, 65524, 65528, 0, 0, 0, 0, 0], - ], - [ - [0, 2048, 4096, 8192, 16384, 32768, 0, 0, 0, 0], - [0, 2865, 5664, 11072, 21168, 38768, 0, 0, 0, 0], - [0, 3858, 7540, 14408, 26352, 44480, 0, 0, 0, 0], - [0, 5063, 9772, 18232, 31904, 49824, 0, 0, 0, 0], - [0, 6536, 12448, 22624, 37752, 54624, 0, 0, 0, 0], - [0, 8366, 15680, 27656, 43800, 58720, 0, 0, 0, 0], - [0, 10688, 19640, 33416, 49848, 61904, 0, 0, 0, 0], - [0, 13713, 24560, 39920, 55536, 64032, 0, 0, 0, 0], - [0, 17758, 30704, 47024, 60304, 65120, 0, 0, 0, 0], - [0, 23272, 38280, 54200, 63576, 65472, 0, 0, 0, 0], - [0, 30841, 47168, 60388, 65136, 65520, 0, 0, 0, 0], - [0, 41006, 56354, 64248, 65512, 65520, 0, 0, 0, 0], - [0, 53291, 63248, 65456, 65512, 65520, 0, 0, 0, 0], - [0, 63380, 65464, 65508, 65512, 65520, 0, 0, 0, 0], - [0, 65505, 65506, 65508, 65512, 65520, 0, 0, 0, 0], - [0, 65505, 65506, 65508, 65512, 65520, 0, 0, 0, 0], - ], - [ - [0, 1024, 2048, 4096, 8192, 16384, 32768, 0, 0, 0], - [0, 1441, 2864, 5664, 11072, 21168, 38752, 0, 0, 0], - [0, 1951, 3858, 7540, 14408, 26352, 44480, 0, 0, 0], - [0, 2577, 5064, 9772, 18232, 31904, 49824, 0, 0, 0], - [0, 3350, 6536, 12448, 22624, 37744, 54624, 0, 0, 0], - [0, 4324, 8366, 15680, 27656, 43808, 58720, 0, 0, 0], - [0, 5581, 10688, 19640, 33416, 49856, 61920, 0, 0, 0], - [0, 7258, 13712, 24560, 39920, 55536, 64032, 0, 0, 0], - [0, 9579, 17758, 30704, 47024, 60304, 65120, 0, 0, 0], - [0, 12907, 23272, 38280, 54200, 63568, 65472, 0, 0, 0], - [0, 17852, 30840, 47168, 60384, 65136, 65504, 0, 0, 0], - [0, 25441, 41006, 56352, 64248, 65488, 65504, 0, 0, 0], - [0, 37208, 53292, 63248, 65456, 65488, 65504, 0, 0, 0], - [0, 53649, 63380, 65464, 65480, 65488, 65504, 0, 0, 0], - [0, 65147, 65474, 65476, 65480, 65488, 65504, 0, 0, 0], - [0, 65473, 65474, 65476, 65480, 65488, 65504, 0, 0, 0], - ], - [ - [0, 512, 1024, 2048, 4096, 8192, 16384, 32768, 0, 0], - [0, 722, 1440, 2864, 5664, 11072, 21184, 38784, 0, 0], - [0, 981, 1952, 3856, 7536, 14400, 26368, 44480, 0, 0], - [0, 1300, 2576, 5064, 9776, 18240, 31904, 49792, 0, 0], - [0, 1696, 3350, 6536, 12448, 22624, 37760, 54592, 0, 0], - [0, 2198, 4324, 8368, 15680, 27664, 43808, 58752, 0, 0], - [0, 2852, 5580, 10688, 19640, 33408, 49856, 61888, 0, 0], - [0, 3736, 7258, 13712, 24560, 39920, 55552, 64064, 0, 0], - [0, 4979, 9580, 17760, 30704, 47024, 60320, 65152, 0, 0], - [0, 6807, 12908, 23272, 38280, 54208, 63584, 65472, 0, 0], - [0, 9634, 17852, 30840, 47168, 60384, 65120, 65472, 0, 0], - [0, 14275, 25440, 41008, 56352, 64256, 65440, 65472, 0, 0], - [0, 22449, 37208, 53292, 63248, 65424, 65440, 65472, 0, 0], - [0, 37625, 53648, 63380, 65416, 65424, 65440, 65472, 0, 0], - [0, 60485, 65148, 65412, 65416, 65424, 65440, 65472, 0, 0], - [0, 65409, 65410, 65412, 65416, 65424, 65440, 65472, 0, 0], - ], - [ - [0, 256, 512, 1024, 2048, 4096, 8192, 16384, 32768, 0], - [0, 362, 722, 1440, 2864, 5664, 11072, 21184, 38784, 0], - [0, 492, 980, 1952, 3856, 7536, 14400, 26368, 44544, 0], - [0, 653, 1300, 2576, 5064, 9776, 18240, 31872, 49792, 0], - [0, 853, 1696, 3352, 6536, 12448, 22624, 37760, 54656, 0], - [0, 1108, 2198, 4324, 8368, 15680, 27648, 43776, 58752, 0], - [0, 1442, 2852, 5580, 10688, 19648, 33408, 49856, 61952, 0], - [0, 1895, 3736, 7256, 13712, 24560, 39936, 55552, 64000, 0], - [0, 2538, 4980, 9580, 17760, 30704, 47040, 60288, 65152, 0], - [0, 3497, 6808, 12908, 23272, 38272, 54208, 63552, 65408, 0], - [0, 5008, 9634, 17852, 30840, 47168, 60384, 65152, 65408, 0], - [0, 7575, 14276, 25440, 41008, 56352, 64256, 65344, 65408, 0], - [0, 12397, 22448, 37208, 53288, 63248, 65312, 65344, 65408, 0], - [0, 22767, 37624, 53648, 63376, 65296, 65312, 65344, 65408, 0], - [0, 47343, 60484, 65148, 65288, 65296, 65312, 65344, 65408, 0], - [0, 65281, 65282, 65284, 65288, 65296, 65312, 65344, 65408, 0], - ], - [ - [0, 128, 256, 512, 1024, 2048, 4096, 8192, 16384, 32768], - [0, 181, 362, 720, 1440, 2864, 5664, 11072, 21120, 38656], - [0, 246, 492, 980, 1952, 3856, 7552, 14400, 26368, 44544], - [0, 327, 652, 1300, 2576, 5056, 9760, 18240, 31872, 49920], - [0, 428, 852, 1696, 3352, 6528, 12448, 22656, 37760, 54528], - [0, 557, 1108, 2200, 4320, 8368, 15680, 27648, 43776, 58624], - [0, 725, 1442, 2852, 5584, 10688, 19648, 33408, 49792, 61952], - [0, 955, 1896, 3736, 7256, 13712, 24544, 39936, 55552, 64000], - [0, 1282, 2538, 4980, 9576, 17760, 30720, 47040, 60288, 65024], - [ - 0, 1772, 3496, 6808, 12904, 23264, 38272, 54208, 63616, 65280, - ], - [ - 0, 2554, 5008, 9632, 17856, 30848, 47168, 60416, 65152, 65280, - ], - [ - 0, 3904, 7576, 14276, 25440, 41008, 56352, 64256, 65152, 65280, - ], - [ - 0, 6523, 12396, 22448, 37208, 53296, 63232, 65088, 65152, 65280, - ], - [ - 0, 12594, 22768, 37624, 53648, 63376, 65056, 65088, 65152, 65280, - ], - [ - 0, 31006, 47344, 60484, 65032, 65040, 65056, 65088, 65152, 65280, - ], - [ - 0, 65025, 65026, 65028, 65032, 65040, 65056, 65088, 65152, 65280, - ], - ], -]; - -pub static FREQ_TABLE: [[[u16; 10]; 16]; 9] = [ - [ - [32768, 32768, 0, 0, 0, 0, 0, 0, 0, 0], - [38761, 26775, 0, 0, 0, 0, 0, 0, 0, 0], - [44484, 21052, 0, 0, 0, 0, 0, 0, 0, 0], - [49818, 15718, 0, 0, 0, 0, 0, 0, 0, 0], - [54623, 10913, 0, 0, 0, 0, 0, 0, 0, 0], - [58721, 6815, 0, 0, 0, 0, 0, 0, 0, 0], - [61911, 3625, 0, 0, 0, 0, 0, 0, 0, 0], - [64036, 1500, 0, 0, 0, 0, 0, 0, 0, 0], - [65121, 415, 0, 0, 0, 0, 0, 0, 0, 0], - [65477, 59, 0, 0, 0, 0, 0, 0, 0, 0], - [65534, 2, 0, 0, 0, 0, 0, 0, 0, 0], - [65535, 1, 0, 0, 0, 0, 0, 0, 0, 0], - [65535, 1, 0, 0, 0, 0, 0, 0, 0, 0], - [65535, 1, 0, 0, 0, 0, 0, 0, 0, 0], - [65535, 1, 0, 0, 0, 0, 0, 0, 0, 0], - [65535, 1, 0, 0, 0, 0, 0, 0, 0, 0], - ], - [ - [16384, 16384, 16384, 0, 0, 0, 0, 0, 0, 0], - [21168, 17592, 13388, 0, 0, 0, 0, 0, 0, 0], - [26354, 18130, 10526, 0, 0, 0, 0, 0, 0, 0], - [31900, 17918, 7859, 0, 0, 0, 0, 0, 0, 0], - [37750, 16874, 5456, 0, 0, 0, 0, 0, 0, 0], - [43800, 14920, 3408, 0, 0, 0, 0, 0, 0, 0], - [49850, 12062, 1812, 0, 0, 0, 0, 0, 0, 0], - [55537, 8499, 750, 0, 0, 0, 0, 0, 0, 0], - [60308, 4812, 208, 0, 0, 0, 0, 0, 0, 0], - [63575, 1901, 30, 0, 0, 0, 0, 0, 0, 0], - [65132, 402, 1, 0, 0, 0, 0, 0, 0, 0], - [65511, 23, 1, 0, 0, 0, 0, 0, 0, 0], - [65533, 1, 1, 0, 0, 0, 0, 0, 0, 0], - [65533, 1, 1, 0, 0, 0, 0, 0, 0, 0], - [65533, 1, 1, 0, 0, 0, 0, 0, 0, 0], - [65533, 1, 1, 0, 0, 0, 0, 0, 0, 0], - ], - [ - [8192, 8192, 8192, 8192, 0, 0, 0, 0, 0, 0], - [11073, 10095, 8796, 6694, 0, 0, 0, 0, 0, 0], - [14406, 11948, 9065, 5263, 0, 0, 0, 0, 0, 0], - [18234, 13666, 8958, 3930, 0, 0, 0, 0, 0, 0], - [22624, 15126, 8437, 2728, 0, 0, 0, 0, 0, 0], - [27657, 16143, 7460, 1704, 0, 0, 0, 0, 0, 0], - [33414, 16436, 6031, 906, 0, 0, 0, 0, 0, 0], - [39920, 15616, 4250, 375, 0, 0, 0, 0, 0, 0], - [47024, 13284, 2406, 104, 0, 0, 0, 0, 0, 0], - [54201, 9375, 950, 15, 0, 0, 0, 0, 0, 0], - [60388, 4744, 200, 1, 0, 0, 0, 0, 0, 0], - [64250, 1262, 10, 1, 0, 0, 0, 0, 0, 0], - [65456, 74, 1, 1, 0, 0, 0, 0, 0, 0], - [65529, 1, 1, 1, 0, 0, 0, 0, 0, 0], - [65529, 1, 1, 1, 0, 0, 0, 0, 0, 0], - [65529, 1, 1, 1, 0, 0, 0, 0, 0, 0], - ], - [ - [4096, 4096, 4096, 4096, 4096, 0, 0, 0, 0, 0], - [5665, 5407, 5048, 4398, 3347, 0, 0, 0, 0, 0], - [7539, 6867, 5973, 4532, 2632, 0, 0, 0, 0, 0], - [9773, 8461, 6833, 4479, 1965, 0, 0, 0, 0, 0], - [12447, 10177, 7564, 4218, 1364, 0, 0, 0, 0, 0], - [15679, 11977, 8072, 3730, 852, 0, 0, 0, 0, 0], - [19640, 13774, 8217, 3016, 453, 0, 0, 0, 0, 0], - [24559, 15361, 7808, 2124, 188, 0, 0, 0, 0, 0], - [30704, 16320, 6642, 1203, 52, 0, 0, 0, 0, 0], - [38280, 15920, 4688, 476, 7, 0, 0, 0, 0, 0], - [47169, 13219, 2372, 99, 1, 0, 0, 0, 0, 0], - [56354, 7896, 631, 4, 1, 0, 0, 0, 0, 0], - [63248, 2208, 34, 1, 1, 0, 0, 0, 0, 0], - [65465, 57, 1, 1, 1, 0, 0, 0, 0, 0], - [65521, 1, 1, 1, 1, 0, 0, 0, 0, 0], - [65521, 1, 1, 1, 1, 0, 0, 0, 0, 0], - ], - [ - [2048, 2048, 2048, 2048, 2048, 2048, 0, 0, 0, 0], - [2865, 2799, 2704, 2524, 2200, 1673, 0, 0, 0, 0], - [3858, 3682, 3434, 2986, 2266, 1316, 0, 0, 0, 0], - [5063, 4709, 4230, 3418, 2240, 982, 0, 0, 0, 0], - [6536, 5912, 5088, 3782, 2109, 682, 0, 0, 0, 0], - [8366, 7314, 5988, 4036, 1865, 426, 0, 0, 0, 0], - [10688, 8952, 6888, 4108, 1507, 227, 0, 0, 0, 0], - [13713, 10847, 7680, 3904, 1062, 94, 0, 0, 0, 0], - [17758, 12946, 8160, 3320, 602, 26, 0, 0, 0, 0], - [23272, 15008, 7960, 2344, 237, 4, 0, 0, 0, 0], - [30841, 16327, 6610, 1187, 48, 1, 0, 0, 0, 0], - [41006, 15348, 3947, 316, 1, 1, 0, 0, 0, 0], - [53291, 9957, 1104, 14, 1, 1, 0, 0, 0, 0], - [63380, 2084, 22, 1, 1, 1, 0, 0, 0, 0], - [65505, 1, 1, 1, 1, 1, 0, 0, 0, 0], - [65505, 1, 1, 1, 1, 1, 0, 0, 0, 0], - ], - [ - [1024, 1024, 1024, 1024, 1024, 1024, 1024, 0, 0, 0], - [1441, 1423, 1400, 1352, 1262, 1099, 837, 0, 0, 0], - [1951, 1907, 1841, 1717, 1493, 1133, 658, 0, 0, 0], - [2577, 2487, 2354, 2115, 1709, 1120, 491, 0, 0, 0], - [3350, 3186, 2956, 2544, 1890, 1055, 341, 0, 0, 0], - [4324, 4042, 3657, 2994, 2019, 932, 213, 0, 0, 0], - [5581, 5107, 4476, 3444, 2055, 754, 113, 0, 0, 0], - [7258, 6454, 5424, 3840, 1952, 531, 47, 0, 0, 0], - [9579, 8179, 6473, 4080, 1660, 301, 13, 0, 0, 0], - [12907, 10365, 7504, 3980, 1171, 119, 2, 0, 0, 0], - [17852, 12988, 8164, 3304, 594, 23, 1, 0, 0, 0], - [25441, 15565, 7673, 1974, 155, 1, 1, 0, 0, 0], - [37208, 16084, 4978, 552, 4, 1, 1, 0, 0, 0], - [53649, 9731, 1042, 4, 1, 1, 1, 0, 0, 0], - [65147, 327, 1, 1, 1, 1, 1, 0, 0, 0], - [65473, 1, 1, 1, 1, 1, 1, 0, 0, 0], - ], - [ - [512, 512, 512, 512, 512, 512, 512, 512, 0, 0], - [722, 718, 712, 700, 676, 632, 550, 418, 0, 0], - [981, 971, 952, 920, 858, 748, 566, 329, 0, 0], - [1300, 1276, 1244, 1178, 1058, 854, 559, 246, 0, 0], - [1696, 1654, 1593, 1478, 1272, 946, 526, 171, 0, 0], - [2198, 2126, 2022, 1828, 1498, 1009, 467, 106, 0, 0], - [2852, 2728, 2554, 2238, 1721, 1028, 376, 57, 0, 0], - [3736, 3522, 3227, 2712, 1920, 977, 266, 23, 0, 0], - [4979, 4601, 4090, 3236, 2040, 831, 151, 6, 0, 0], - [6807, 6101, 5182, 3752, 1991, 586, 59, 1, 0, 0], - [9634, 8218, 6494, 4082, 1652, 296, 11, 1, 0, 0], - [14275, 11165, 7784, 3836, 988, 74, 1, 1, 0, 0], - [22449, 14759, 8042, 2489, 272, 1, 1, 1, 0, 0], - [37625, 16023, 4866, 509, 1, 1, 1, 1, 0, 0], - [60485, 4663, 132, 1, 1, 1, 1, 1, 0, 0], - [65409, 1, 1, 1, 1, 1, 1, 1, 0, 0], - ], - [ - [256, 256, 256, 256, 256, 256, 256, 256, 256, 0], - [362, 360, 359, 356, 350, 338, 316, 275, 209, 0], - [492, 488, 486, 476, 460, 429, 374, 284, 164, 0], - [653, 647, 638, 622, 589, 529, 426, 280, 123, 0], - [853, 843, 828, 796, 739, 636, 473, 264, 85, 0], - [1108, 1090, 1063, 1011, 914, 748, 504, 234, 53, 0], - [1442, 1410, 1364, 1277, 1120, 860, 514, 189, 28, 0], - [1895, 1841, 1760, 1614, 1356, 961, 488, 132, 12, 0], - [2538, 2442, 2300, 2045, 1618, 1021, 414, 76, 3, 0], - [3497, 3311, 3050, 2591, 1875, 996, 292, 29, 1, 0], - [5008, 4626, 4109, 3247, 2041, 826, 149, 4, 1, 0], - [7575, 6701, 5582, 3892, 1918, 494, 34, 1, 1, 0], - [12397, 10051, 7380, 4020, 1245, 129, 1, 1, 1, 0], - [22767, 14857, 8012, 2432, 240, 1, 1, 1, 1, 0], - [47343, 13141, 2332, 35, 1, 1, 1, 1, 1, 0], - [65281, 1, 1, 1, 1, 1, 1, 1, 1, 0], - ], - [ - [128, 128, 128, 128, 128, 128, 128, 128, 128, 128], - [181, 181, 179, 180, 178, 175, 169, 157, 137, 105], - [246, 246, 244, 243, 238, 231, 214, 187, 142, 82], - [327, 325, 324, 319, 310, 294, 265, 213, 141, 61], - [428, 424, 422, 414, 397, 370, 319, 236, 131, 43], - [557, 551, 546, 530, 506, 457, 374, 252, 116, 27], - [725, 717, 705, 683, 638, 560, 430, 256, 95, 14], - [955, 941, 920, 880, 807, 677, 481, 244, 66, 6], - [1282, 1256, 1221, 1149, 1023, 810, 510, 207, 37, 2], - [1772, 1724, 1656, 1524, 1295, 938, 498, 147, 13, 1], - [2554, 2454, 2312, 2056, 1624, 1020, 414, 74, 1, 1], - [3904, 3672, 3350, 2791, 1946, 959, 247, 14, 1, 1], - [6523, 5873, 5026, 3690, 2011, 621, 58, 1, 1, 1], - [12594, 10174, 7428, 4006, 1216, 105, 1, 1, 1, 1], - [31006, 16338, 6570, 1137, 1, 1, 1, 1, 1, 1], - [65025, 1, 1, 1, 1, 1, 1, 1, 1, 1], - ], -]; - -pub static RF_TABLE: [[[u32; 10]; 16]; 9] = [ - [ - [32768, 32768, 0, 0, 0, 0, 0, 0, 0, 0], - [55403, 40102, 0, 0, 0, 0, 0, 0, 0, 0], - [48275, 51004, 0, 0, 0, 0, 0, 0, 0, 0], - [43107, 34156, 0, 0, 0, 0, 0, 0, 0, 0], - [39315, 49196, 0, 0, 0, 0, 0, 0, 0, 0], - [36571, 39389, 0, 0, 0, 0, 0, 0, 0, 0], - [34687, 37026, 0, 0, 0, 0, 0, 0, 0, 0], - [33536, 44739, 0, 0, 0, 0, 0, 0, 0, 0], - [32977, 40427, 0, 0, 0, 0, 0, 0, 0, 0], - [32798, 35545, 0, 0, 0, 0, 0, 0, 0, 0], - [32769, 32768, 0, 0, 0, 0, 0, 0, 0, 0], - [32769, 32768, 0, 0, 0, 0, 0, 0, 0, 0], - [32769, 32768, 0, 0, 0, 0, 0, 0, 0, 0], - [32769, 32768, 0, 0, 0, 0, 0, 0, 0, 0], - [32769, 32768, 0, 0, 0, 0, 0, 0, 0, 0], - [32769, 32768, 0, 0, 0, 0, 0, 0, 0, 0], - ], - [ - [32768, 32768, 32768, 0, 0, 0, 0, 0, 0, 0], - [50725, 61036, 40101, 0, 0, 0, 0, 0, 0, 0], - [40743, 59225, 51004, 0, 0, 0, 0, 0, 0, 0], - [33660, 59925, 34156, 0, 0, 0, 0, 0, 0, 0], - [56887, 63633, 49200, 0, 0, 0, 0, 0, 0, 0], - [49029, 35983, 39383, 0, 0, 0, 0, 0, 0, 0], - [43079, 44509, 37036, 0, 0, 0, 0, 0, 0, 0], - [38668, 63169, 44739, 0, 0, 0, 0, 0, 0, 0], - [35609, 55785, 40330, 0, 0, 0, 0, 0, 0, 0], - [33779, 35302, 34953, 0, 0, 0, 0, 0, 0, 0], - [32971, 41734, 32768, 0, 0, 0, 0, 0, 0, 0], - [32781, 45590, 32768, 0, 0, 0, 0, 0, 0, 0], - [32770, 32768, 32768, 0, 0, 0, 0, 0, 0, 0], - [32770, 32768, 32768, 0, 0, 0, 0, 0, 0, 0], - [32770, 32768, 32768, 0, 0, 0, 0, 0, 0, 0], - [32770, 32768, 32768, 0, 0, 0, 0, 0, 0, 0], - ], - [ - [32768, 32768, 32768, 32768, 0, 0, 0, 0, 0, 0], - [48485, 53182, 61036, 40101, 0, 0, 0, 0, 0, 0], - [37267, 44934, 59225, 51004, 0, 0, 0, 0, 0, 0], - [58887, 39285, 59932, 34152, 0, 0, 0, 0, 0, 0], - [47460, 35493, 63633, 49200, 0, 0, 0, 0, 0, 0], - [38824, 33257, 35983, 39383, 0, 0, 0, 0, 0, 0], - [64269, 65329, 44509, 37036, 0, 0, 0, 0, 0, 0], - [53795, 34380, 63161, 44739, 0, 0, 0, 0, 0, 0], - [45668, 40415, 55785, 40330, 0, 0, 0, 0, 0, 0], - [39621, 57266, 35320, 34953, 0, 0, 0, 0, 0, 0], - [35561, 56584, 41943, 32768, 0, 0, 0, 0, 0, 0], - [33424, 53177, 52429, 32768, 0, 0, 0, 0, 0, 0], - [32808, 56680, 32768, 32768, 0, 0, 0, 0, 0, 0], - [32772, 32768, 32768, 32768, 0, 0, 0, 0, 0, 0], - [32772, 32768, 32768, 32768, 0, 0, 0, 0, 0, 0], - [32772, 32768, 32768, 32768, 0, 0, 0, 0, 0, 0], - ], - [ - [32768, 32768, 32768, 32768, 32768, 0, 0, 0, 0, 0], - [47385, 49646, 53177, 61036, 40101, 0, 0, 0, 0, 0], - [35606, 39091, 44941, 59231, 50995, 0, 0, 0, 0, 0], - [54934, 63452, 39285, 59932, 34152, 0, 0, 0, 0, 0], - [43133, 52753, 35489, 63640, 49200, 0, 0, 0, 0, 0], - [34241, 44825, 33255, 35983, 39383, 0, 0, 0, 0, 0], - [54671, 38977, 65337, 44502, 37036, 0, 0, 0, 0, 0], - [43721, 34950, 34380, 63191, 44620, 0, 0, 0, 0, 0], - [34971, 32897, 40415, 55785, 40330, 0, 0, 0, 0, 0], - [56099, 33723, 57260, 35246, 37449, 0, 0, 0, 0, 0], - [45527, 40614, 56584, 42367, 32768, 0, 0, 0, 0, 0], - [38107, 33996, 53177, 32768, 32768, 0, 0, 0, 0, 0], - [33953, 60787, 61681, 32768, 32768, 0, 0, 0, 0, 0], - [32804, 36792, 32768, 32768, 32768, 0, 0, 0, 0, 0], - [32776, 32768, 32768, 32768, 32768, 0, 0, 0, 0, 0], - [32776, 32768, 32768, 32768, 32768, 0, 0, 0, 0, 0], - ], - [ - [32768, 32768, 32768, 32768, 32768, 32768, 0, 0, 0, 0], - [46847, 47952, 49637, 53177, 61008, 40113, 0, 0, 0, 0], - [34789, 36452, 39085, 44949, 59231, 50995, 0, 0, 0, 0], - [53019, 57005, 63460, 39268, 59919, 34169, 0, 0, 0, 0], - [41070, 45405, 52759, 35489, 63640, 49200, 0, 0, 0, 0], - [64173, 36702, 44829, 33255, 35983, 39383, 0, 0, 0, 0], - [50231, 59972, 38971, 65345, 44531, 36954, 0, 0, 0, 0], - [39151, 49495, 34953, 34380, 63191, 44620, 0, 0, 0, 0], - [60465, 41470, 32897, 40427, 55738, 40330, 0, 0, 0, 0], - [46139, 35772, 33723, 57260, 35395, 32768, 0, 0, 0, 0], - [34815, 32882, 40611, 56537, 43691, 32768, 0, 0, 0, 0], - [52370, 34980, 34005, 53092, 32768, 32768, 0, 0, 0, 0], - [40297, 53919, 60787, 37449, 32768, 32768, 0, 0, 0, 0], - [33883, 64404, 47663, 32768, 32768, 32768, 0, 0, 0, 0], - [32784, 32768, 32768, 32768, 32768, 32768, 0, 0, 0, 0], - [32784, 32768, 32768, 32768, 32768, 32768, 0, 0, 0, 0], - ], - [ - [32768, 32768, 32768, 32768, 32768, 32768, 32768, 0, 0, 0], - [46571, 47160, 47935, 49637, 53177, 61064, 40089, 0, 0, 0], - [34397, 35191, 36452, 39085, 44949, 59231, 50995, 0, 0, 0], - [52083, 53968, 57017, 63460, 39268, 59919, 34169, 0, 0, 0], - [40065, 42127, 45405, 52759, 35507, 63610, 49200, 0, 0, 0], - [62080, 33206, 36702, 44829, 33239, 36003, 39383, 0, 0, 0], - [48098, 52562, 59972, 38971, 65313, 44502, 37118, 0, 0, 0], - [36985, 41592, 49490, 34953, 34380, 63191, 44620, 0, 0, 0], - [56047, 32820, 41470, 32897, 40427, 55738, 40330, 0, 0, 0], - [41595, 51797, 35772, 33723, 57309, 35246, 32768, 0, 0, 0], - [60147, 41336, 32880, 40623, 56489, 45590, 32768, 0, 0, 0], - [42205, 34492, 34984, 33996, 54120, 32768, 32768, 0, 0, 0], - [57716, 33379, 53924, 60787, 32768, 32768, 32768, 0, 0, 0], - [40028, 55171, 64404, 32768, 32768, 32768, 32768, 0, 0, 0], - [32964, 51306, 32768, 32768, 32768, 32768, 32768, 0, 0, 0], - [32800, 32768, 32768, 32768, 32768, 32768, 32768, 0, 0, 0], - ], - [ - [32768, 32768, 32768, 32768, 32768, 32768, 32768, 32768, 0, 0], - [46474, 46733, 47127, 47935, 49637, 53092, 61008, 40137, 0, 0], - [34204, 34557, 35246, 36472, 39108, 44859, 59283, 50995, 0, 0], - [51622, 52593, 53946, 56968, 63430, 39291, 60026, 34100, 0, 0], - [39569, 40574, 42127, 45405, 52759, 35470, 63792, 49056, 0, 0], - [61064, 63132, 33189, 36712, 44799, 33255, 35926, 39569, 0, 0], - [47061, 49200, 52552, 59972, 38994, 65281, 44620, 36792, 0, 0], - [35926, 38108, 41592, 49490, 34953, 34344, 63072, 45590, 0, 0], - [53914, 58343, 32816, 41476, 32897, 40378, 55554, 43691, 0, 0], - [39435, 43999, 51802, 35772, 33706, 57260, 35545, 32768, 0, 0], - [55727, 65329, 41336, 32880, 40623, 56680, 47663, 32768, 0, 0], - [37609, 48085, 34486, 34989, 33962, 56680, 32768, 32768, 0, 0], - [47830, 36376, 33379, 53924, 61681, 32768, 32768, 32768, 0, 0], - [57076, 33506, 55166, 32961, 32768, 32768, 32768, 32768, 0, 0], - [35504, 57567, 63550, 32768, 32768, 32768, 32768, 32768, 0, 0], - [32832, 32768, 32768, 32768, 32768, 32768, 32768, 32768, 0, 0], - ], - [ - [ - 32768, 32768, 32768, 32768, 32768, 32768, 32768, 32768, 32768, 0, - ], - [ - 46346, 46603, 46733, 47127, 47935, 49637, 53092, 61008, 40137, 0, - ], - [ - 34100, 34380, 34521, 35246, 36472, 39108, 44859, 59075, 51150, 0, - ], - [ - 51385, 51862, 52593, 53946, 56968, 63430, 39383, 59919, 34100, 0, - ], - [ - 39337, 39804, 40525, 42154, 45405, 52759, 35470, 63550, 49345, 0, - ], - [ - 60568, 61568, 63132, 33189, 36712, 44859, 33288, 35849, 39569, 0, - ], - [ - 46539, 47595, 49200, 52552, 59919, 39017, 65281, 44384, 37449, 0, - ], - [ - 35414, 36452, 38130, 41579, 49490, 34916, 34380, 63550, 43691, 0, - ], - [ - 52883, 54962, 58356, 32816, 41476, 32864, 40525, 55188, 43691, 0, - ], - [ - 38381, 40537, 44006, 51802, 35791, 33689, 57456, 36158, 32768, 0, - ], - [ - 53601, 58028, 65329, 41336, 32880, 40623, 56299, 32768, 32768, 0, - ], - [ - 35437, 40059, 48089, 34486, 34989, 33962, 61681, 32768, 32768, 0, - ], - [ - 43307, 53415, 36373, 33387, 53903, 65028, 32768, 32768, 32768, 0, - ], - [ - 47162, 36136, 33504, 55188, 34953, 32768, 32768, 32768, 32768, 0, - ], - [ - 45360, 40855, 57555, 59919, 32768, 32768, 32768, 32768, 32768, 0, - ], - [ - 32896, 32768, 32768, 32768, 32768, 32768, 32768, 32768, 32768, 0, - ], - ], - [ - [ - 32768, 32768, 32768, 32768, 32768, 32768, 32768, 32768, 32768, 32768, - ], - [ - 46346, 46346, 46864, 46603, 47127, 47935, 49637, 53431, 61231, 39946, - ], - [ - 34100, 34100, 34380, 34521, 35246, 36314, 39199, 44859, 59075, 51150, - ], - [ - 51306, 51622, 51782, 52593, 54120, 57065, 63310, 39383, 59494, 34380, - ], - [ - 39199, 39569, 39756, 40525, 42260, 45344, 52593, 35545, 64035, 48771, - ], - [ - 60241, 60897, 61455, 63310, 33157, 36712, 44859, 33288, 36158, 38836, - ], - [ - 46282, 46798, 47595, 49128, 52593, 59919, 39017, 32768, 44151, 37449, - ], - [ - 35136, 35658, 36472, 38130, 41579, 49563, 34880, 34380, 63550, 43691, - ], - [ - 52347, 53431, 54962, 58406, 32800, 41425, 32897, 40525, 56680, 32768, - ], - [ - 37872, 38926, 40525, 44035, 51822, 35772, 33689, 57065, 40330, 32768, - ], - [ - 52552, 54693, 58053, 65281, 41323, 32897, 40525, 56680, 32768, 32768, - ], - [ - 34380, 36552, 40065, 48089, 34486, 34989, 33962, 37449, 32768, 32768, - ], - [ - 41152, 45707, 53409, 36373, 33371, 54033, 36158, 32768, 32768, 32768, - ], - [ - 42629, 52769, 36138, 33504, 55188, 39946, 32768, 32768, 32768, 32768, - ], - [ - 34630, 32860, 40858, 59023, 32768, 32768, 32768, 32768, 32768, 32768, - ], - [ - 33026, 32768, 32768, 32768, 32768, 32768, 32768, 32768, 32768, 32768, - ], - ], -]; - -pub static RS_TABLE: [[[u8; 10]; 16]; 9] = [ - [ - [15, 15, 0, 0, 0, 0, 0, 0, 0, 0], - [16, 15, 0, 0, 0, 0, 0, 0, 0, 0], - [16, 15, 0, 0, 0, 0, 0, 0, 0, 0], - [16, 14, 0, 0, 0, 0, 0, 0, 0, 0], - [16, 14, 0, 0, 0, 0, 0, 0, 0, 0], - [16, 13, 0, 0, 0, 0, 0, 0, 0, 0], - [16, 12, 0, 0, 0, 0, 0, 0, 0, 0], - [16, 11, 0, 0, 0, 0, 0, 0, 0, 0], - [16, 9, 0, 0, 0, 0, 0, 0, 0, 0], - [16, 6, 0, 0, 0, 0, 0, 0, 0, 0], - [16, 1, 0, 0, 0, 0, 0, 0, 0, 0], - [16, 0, 0, 0, 0, 0, 0, 0, 0, 0], - [16, 0, 0, 0, 0, 0, 0, 0, 0, 0], - [16, 0, 0, 0, 0, 0, 0, 0, 0, 0], - [16, 0, 0, 0, 0, 0, 0, 0, 0, 0], - [16, 0, 0, 0, 0, 0, 0, 0, 0, 0], - ], - [ - [14, 14, 14, 0, 0, 0, 0, 0, 0, 0], - [15, 15, 14, 0, 0, 0, 0, 0, 0, 0], - [15, 15, 14, 0, 0, 0, 0, 0, 0, 0], - [15, 15, 13, 0, 0, 0, 0, 0, 0, 0], - [16, 15, 13, 0, 0, 0, 0, 0, 0, 0], - [16, 14, 12, 0, 0, 0, 0, 0, 0, 0], - [16, 14, 11, 0, 0, 0, 0, 0, 0, 0], - [16, 14, 10, 0, 0, 0, 0, 0, 0, 0], - [16, 13, 8, 0, 0, 0, 0, 0, 0, 0], - [16, 11, 5, 0, 0, 0, 0, 0, 0, 0], - [16, 9, 0, 0, 0, 0, 0, 0, 0, 0], - [16, 5, 0, 0, 0, 0, 0, 0, 0, 0], - [16, 0, 0, 0, 0, 0, 0, 0, 0, 0], - [16, 0, 0, 0, 0, 0, 0, 0, 0, 0], - [16, 0, 0, 0, 0, 0, 0, 0, 0, 0], - [16, 0, 0, 0, 0, 0, 0, 0, 0, 0], - ], - [ - [13, 13, 13, 13, 0, 0, 0, 0, 0, 0], - [14, 14, 14, 13, 0, 0, 0, 0, 0, 0], - [14, 14, 14, 13, 0, 0, 0, 0, 0, 0], - [15, 14, 14, 12, 0, 0, 0, 0, 0, 0], - [15, 14, 14, 12, 0, 0, 0, 0, 0, 0], - [15, 14, 13, 11, 0, 0, 0, 0, 0, 0], - [16, 15, 13, 10, 0, 0, 0, 0, 0, 0], - [16, 14, 13, 9, 0, 0, 0, 0, 0, 0], - [16, 14, 12, 7, 0, 0, 0, 0, 0, 0], - [16, 14, 10, 4, 0, 0, 0, 0, 0, 0], - [16, 13, 8, 0, 0, 0, 0, 0, 0, 0], - [16, 11, 4, 0, 0, 0, 0, 0, 0, 0], - [16, 7, 0, 0, 0, 0, 0, 0, 0, 0], - [16, 0, 0, 0, 0, 0, 0, 0, 0, 0], - [16, 0, 0, 0, 0, 0, 0, 0, 0, 0], - [16, 0, 0, 0, 0, 0, 0, 0, 0, 0], - ], - [ - [12, 12, 12, 12, 12, 0, 0, 0, 0, 0], - [13, 13, 13, 13, 12, 0, 0, 0, 0, 0], - [13, 13, 13, 13, 12, 0, 0, 0, 0, 0], - [14, 14, 13, 13, 11, 0, 0, 0, 0, 0], - [14, 14, 13, 13, 11, 0, 0, 0, 0, 0], - [14, 14, 13, 12, 10, 0, 0, 0, 0, 0], - [15, 14, 14, 12, 9, 0, 0, 0, 0, 0], - [15, 14, 13, 12, 8, 0, 0, 0, 0, 0], - [15, 14, 13, 11, 6, 0, 0, 0, 0, 0], - [16, 14, 13, 9, 3, 0, 0, 0, 0, 0], - [16, 14, 12, 7, 0, 0, 0, 0, 0, 0], - [16, 13, 10, 2, 0, 0, 0, 0, 0, 0], - [16, 12, 6, 0, 0, 0, 0, 0, 0, 0], - [16, 6, 0, 0, 0, 0, 0, 0, 0, 0], - [16, 0, 0, 0, 0, 0, 0, 0, 0, 0], - [16, 0, 0, 0, 0, 0, 0, 0, 0, 0], - ], - [ - [11, 11, 11, 11, 11, 11, 0, 0, 0, 0], - [12, 12, 12, 12, 12, 11, 0, 0, 0, 0], - [12, 12, 12, 12, 12, 11, 0, 0, 0, 0], - [13, 13, 13, 12, 12, 10, 0, 0, 0, 0], - [13, 13, 13, 12, 12, 10, 0, 0, 0, 0], - [14, 13, 13, 12, 11, 9, 0, 0, 0, 0], - [14, 14, 13, 13, 11, 8, 0, 0, 0, 0], - [14, 14, 13, 12, 11, 7, 0, 0, 0, 0], - [15, 14, 13, 12, 10, 5, 0, 0, 0, 0], - [15, 14, 13, 12, 8, 2, 0, 0, 0, 0], - [15, 14, 13, 11, 6, 0, 0, 0, 0, 0], - [16, 14, 12, 9, 0, 0, 0, 0, 0, 0], - [16, 14, 11, 4, 0, 0, 0, 0, 0, 0], - [16, 12, 5, 0, 0, 0, 0, 0, 0, 0], - [16, 0, 0, 0, 0, 0, 0, 0, 0, 0], - [16, 0, 0, 0, 0, 0, 0, 0, 0, 0], - ], - [ - [10, 10, 10, 10, 10, 10, 10, 0, 0, 0], - [11, 11, 11, 11, 11, 11, 10, 0, 0, 0], - [11, 11, 11, 11, 11, 11, 10, 0, 0, 0], - [12, 12, 12, 12, 11, 11, 9, 0, 0, 0], - [12, 12, 12, 12, 11, 11, 9, 0, 0, 0], - [13, 12, 12, 12, 11, 10, 8, 0, 0, 0], - [13, 13, 13, 12, 12, 10, 7, 0, 0, 0], - [13, 13, 13, 12, 11, 10, 6, 0, 0, 0], - [14, 13, 13, 12, 11, 9, 4, 0, 0, 0], - [14, 14, 13, 12, 11, 7, 1, 0, 0, 0], - [15, 14, 13, 12, 10, 5, 0, 0, 0, 0], - [15, 14, 13, 11, 8, 0, 0, 0, 0, 0], - [16, 14, 13, 10, 2, 0, 0, 0, 0, 0], - [16, 14, 11, 2, 0, 0, 0, 0, 0, 0], - [16, 9, 0, 0, 0, 0, 0, 0, 0, 0], - [16, 0, 0, 0, 0, 0, 0, 0, 0, 0], - ], - [ - [9, 9, 9, 9, 9, 9, 9, 9, 0, 0], - [10, 10, 10, 10, 10, 10, 10, 9, 0, 0], - [10, 10, 10, 10, 10, 10, 10, 9, 0, 0], - [11, 11, 11, 11, 11, 10, 10, 8, 0, 0], - [11, 11, 11, 11, 11, 10, 10, 8, 0, 0], - [12, 12, 11, 11, 11, 10, 9, 7, 0, 0], - [12, 12, 12, 12, 11, 11, 9, 6, 0, 0], - [12, 12, 12, 12, 11, 10, 9, 5, 0, 0], - [13, 13, 12, 12, 11, 10, 8, 3, 0, 0], - [13, 13, 13, 12, 11, 10, 6, 0, 0, 0], - [14, 14, 13, 12, 11, 9, 4, 0, 0, 0], - [14, 14, 13, 12, 10, 7, 0, 0, 0, 0], - [15, 14, 13, 12, 9, 0, 0, 0, 0, 0], - [16, 14, 13, 9, 0, 0, 0, 0, 0, 0], - [16, 13, 8, 0, 0, 0, 0, 0, 0, 0], - [16, 0, 0, 0, 0, 0, 0, 0, 0, 0], - ], - [ - [8, 8, 8, 8, 8, 8, 8, 8, 8, 0], - [9, 9, 9, 9, 9, 9, 9, 9, 8, 0], - [9, 9, 9, 9, 9, 9, 9, 9, 8, 0], - [10, 10, 10, 10, 10, 10, 9, 9, 7, 0], - [10, 10, 10, 10, 10, 10, 9, 9, 7, 0], - [11, 11, 11, 10, 10, 10, 9, 8, 6, 0], - [11, 11, 11, 11, 11, 10, 10, 8, 5, 0], - [11, 11, 11, 11, 11, 10, 9, 8, 4, 0], - [12, 12, 12, 11, 11, 10, 9, 7, 2, 0], - [12, 12, 12, 12, 11, 10, 9, 5, 0, 0], - [13, 13, 13, 12, 11, 10, 8, 2, 0, 0], - [13, 13, 13, 12, 11, 9, 6, 0, 0, 0], - [14, 14, 13, 12, 11, 8, 0, 0, 0, 0], - [15, 14, 13, 12, 8, 0, 0, 0, 0, 0], - [16, 14, 12, 6, 0, 0, 0, 0, 0, 0], - [16, 0, 0, 0, 0, 0, 0, 0, 0, 0], - ], - [ - [7, 7, 7, 7, 7, 7, 7, 7, 7, 7], - [8, 8, 8, 8, 8, 8, 8, 8, 8, 7], - [8, 8, 8, 8, 8, 8, 8, 8, 8, 7], - [9, 9, 9, 9, 9, 9, 9, 8, 8, 6], - [9, 9, 9, 9, 9, 9, 9, 8, 8, 6], - [10, 10, 10, 10, 9, 9, 9, 8, 7, 5], - [10, 10, 10, 10, 10, 10, 9, 8, 7, 4], - [10, 10, 10, 10, 10, 10, 9, 8, 7, 3], - [11, 11, 11, 11, 10, 10, 9, 8, 6, 1], - [11, 11, 11, 11, 11, 10, 9, 8, 4, 0], - [12, 12, 12, 12, 11, 10, 9, 7, 0, 0], - [12, 12, 12, 12, 11, 10, 8, 4, 0, 0], - [13, 13, 13, 12, 11, 10, 6, 0, 0, 0], - [14, 14, 13, 12, 11, 7, 0, 0, 0, 0], - [15, 14, 13, 11, 0, 0, 0, 0, 0, 0], - [16, 0, 0, 0, 0, 0, 0, 0, 0, 0], - ], -]; - -pub static RN_TABLE: [[[u16; 10]; 16]; 9] = [ - [ - [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], - [1, 1, 0, 0, 0, 0, 0, 0, 0, 0], - [1, 1, 0, 0, 0, 0, 0, 0, 0, 0], - [0, 1, 0, 0, 0, 0, 0, 0, 0, 0], - [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], - [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], - [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], - [0, 1, 0, 0, 0, 0, 0, 0, 0, 0], - [0, 1, 0, 0, 0, 0, 0, 0, 0, 0], - [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], - [1, 0, 0, 0, 0, 0, 0, 0, 0, 0], - [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], - [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], - [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], - [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], - [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], - ], - [ - [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], - [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], - [1, 0, 1, 0, 0, 0, 0, 0, 0, 0], - [0, 1, 1, 0, 0, 0, 0, 0, 0, 0], - [0, 0, 1, 0, 0, 0, 0, 0, 0, 0], - [1, 1, 1, 0, 0, 0, 0, 0, 0, 0], - [0, 1, 0, 0, 0, 0, 0, 0, 0, 0], - [0, 0, 1, 0, 0, 0, 0, 0, 0, 0], - [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], - [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], - [1, 1, 0, 0, 0, 0, 0, 0, 0, 0], - [0, 1, 0, 0, 0, 0, 0, 0, 0, 0], - [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], - [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], - [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], - [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], - ], - [ - [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], - [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], - [1, 0, 0, 1, 0, 0, 0, 0, 0, 0], - [0, 1, 1, 1, 0, 0, 0, 0, 0, 0], - [1, 1, 0, 1, 0, 0, 0, 0, 0, 0], - [0, 1, 1, 1, 0, 0, 0, 0, 0, 0], - [0, 0, 1, 0, 0, 0, 0, 0, 0, 0], - [0, 0, 1, 1, 0, 0, 0, 0, 0, 0], - [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], - [0, 1, 1, 0, 0, 0, 0, 0, 0, 0], - [1, 1, 1, 0, 0, 0, 0, 0, 0, 0], - [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], - [1, 0, 0, 0, 0, 0, 0, 0, 0, 0], - [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], - [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], - [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], - ], - [ - [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], - [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], - [1, 0, 1, 1, 0, 0, 0, 0, 0, 0], - [1, 1, 1, 1, 1, 0, 0, 0, 0, 0], - [0, 1, 0, 1, 1, 0, 0, 0, 0, 0], - [1, 1, 1, 1, 1, 0, 0, 0, 0, 0], - [1, 1, 0, 0, 0, 0, 0, 0, 0, 0], - [0, 1, 0, 1, 1, 0, 0, 0, 0, 0], - [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], - [1, 1, 1, 1, 1, 0, 0, 0, 0, 0], - [1, 0, 1, 0, 0, 0, 0, 0, 0, 0], - [1, 1, 0, 0, 0, 0, 0, 0, 0, 0], - [1, 1, 0, 0, 0, 0, 0, 0, 0, 0], - [0, 1, 0, 0, 0, 0, 0, 0, 0, 0], - [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], - [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], - ], - [ - [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], - [1, 1, 0, 0, 1, 0, 0, 0, 0, 0], - [1, 1, 0, 1, 1, 0, 0, 0, 0, 0], - [1, 0, 0, 0, 0, 1, 0, 0, 0, 0], - [1, 1, 0, 0, 1, 1, 0, 0, 0, 0], - [0, 0, 0, 1, 1, 1, 0, 0, 0, 0], - [1, 1, 1, 0, 1, 1, 0, 0, 0, 0], - [0, 0, 0, 0, 1, 1, 0, 0, 0, 0], - [1, 1, 0, 1, 1, 0, 0, 0, 0, 0], - [0, 1, 1, 1, 0, 0, 0, 0, 0, 0], - [1, 1, 0, 0, 0, 0, 0, 0, 0, 0], - [0, 0, 0, 1, 0, 0, 0, 0, 0, 0], - [1, 0, 1, 1, 0, 0, 0, 0, 0, 0], - [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], - [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], - [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], - ], - [ - [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], - [1, 1, 0, 0, 0, 0, 0, 0, 0, 0], - [1, 0, 1, 0, 1, 1, 0, 0, 0, 0], - [0, 0, 0, 0, 0, 0, 1, 0, 0, 0], - [0, 1, 1, 0, 1, 1, 1, 0, 0, 0], - [1, 0, 0, 0, 0, 0, 1, 0, 0, 0], - [1, 1, 1, 1, 0, 0, 0, 0, 0, 0], - [0, 1, 1, 0, 0, 1, 1, 0, 0, 0], - [0, 1, 1, 0, 1, 1, 0, 0, 0, 0], - [1, 0, 1, 1, 1, 1, 0, 0, 0, 0], - [0, 0, 1, 0, 0, 1, 0, 0, 0, 0], - [1, 1, 1, 1, 1, 0, 0, 0, 0, 0], - [0, 1, 1, 1, 0, 0, 0, 0, 0, 0], - [1, 1, 0, 0, 0, 0, 0, 0, 0, 0], - [0, 1, 0, 0, 0, 0, 0, 0, 0, 0], - [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], - ], - [ - [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], - [1, 1, 1, 0, 0, 1, 1, 0, 0, 0], - [1, 0, 1, 1, 0, 0, 1, 0, 0, 0], - [1, 1, 1, 1, 0, 0, 0, 1, 0, 0], - [0, 0, 1, 1, 0, 0, 0, 1, 0, 0], - [0, 0, 1, 0, 0, 1, 0, 0, 0, 0], - [0, 1, 0, 1, 1, 0, 1, 1, 0, 0], - [0, 1, 1, 1, 0, 1, 1, 1, 0, 0], - [0, 0, 1, 1, 0, 1, 0, 0, 0, 0], - [1, 0, 0, 1, 1, 1, 0, 0, 0, 0], - [0, 0, 0, 1, 0, 0, 0, 0, 0, 0], - [1, 1, 0, 0, 0, 0, 0, 0, 0, 0], - [1, 0, 1, 1, 0, 0, 0, 0, 0, 0], - [0, 1, 0, 1, 0, 0, 0, 0, 0, 0], - [1, 1, 1, 0, 0, 0, 0, 0, 0, 0], - [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], - ], - [ - [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], - [0, 1, 1, 1, 0, 0, 1, 1, 0, 0], - [1, 0, 1, 1, 1, 0, 0, 0, 1, 0], - [1, 0, 1, 1, 1, 0, 1, 0, 1, 0], - [0, 0, 0, 0, 1, 0, 0, 1, 0, 0], - [0, 0, 0, 1, 0, 0, 1, 0, 0, 0], - [0, 0, 1, 0, 0, 0, 0, 1, 1, 0], - [0, 1, 1, 1, 1, 1, 0, 1, 0, 0], - [1, 1, 0, 1, 1, 1, 0, 1, 0, 0], - [0, 0, 0, 0, 1, 1, 1, 0, 0, 0], - [1, 0, 0, 0, 1, 0, 1, 0, 0, 0], - [1, 1, 1, 0, 0, 0, 0, 0, 0, 0], - [0, 0, 1, 1, 0, 0, 0, 0, 0, 0], - [1, 0, 1, 1, 0, 0, 0, 0, 0, 0], - [1, 0, 0, 0, 0, 0, 0, 0, 0, 0], - [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], - ], - [ - [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], - [0, 0, 0, 1, 1, 0, 0, 0, 0, 0], - [1, 1, 0, 1, 1, 1, 1, 0, 0, 1], - [1, 1, 0, 1, 1, 1, 1, 1, 0, 0], - [1, 0, 1, 0, 0, 0, 1, 0, 1, 0], - [1, 1, 1, 1, 0, 0, 0, 1, 0, 1], - [0, 1, 0, 1, 1, 0, 0, 0, 0, 1], - [0, 1, 1, 1, 1, 1, 0, 0, 1, 0], - [1, 0, 1, 1, 1, 1, 0, 0, 0, 0], - [0, 1, 0, 0, 0, 1, 1, 1, 0, 0], - [0, 1, 0, 0, 1, 0, 0, 0, 0, 0], - [0, 0, 0, 1, 0, 0, 0, 1, 0, 0], - [1, 0, 1, 1, 0, 0, 0, 0, 0, 0], - [1, 0, 1, 1, 1, 0, 0, 0, 0, 0], - [1, 1, 0, 0, 0, 0, 0, 0, 0, 0], - [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], - ], -]; diff --git a/third_party/rpf9-explorer b/third_party/rpf9-explorer deleted file mode 160000 index af5493366..000000000 --- a/third_party/rpf9-explorer +++ /dev/null @@ -1 +0,0 @@ -Subproject commit af549336624fdabf7d1bb6f00b8783e7e1ef692e diff --git a/third_party/xma/COPYING.LGPLv2.1 b/third_party/xma/COPYING.LGPLv2.1 deleted file mode 100644 index 40924c2a6..000000000 --- a/third_party/xma/COPYING.LGPLv2.1 +++ /dev/null @@ -1,502 +0,0 @@ - GNU LESSER GENERAL PUBLIC LICENSE - Version 2.1, February 1999 - - Copyright (C) 1991, 1999 Free Software Foundation, Inc. - 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - Everyone is permitted to copy and distribute verbatim copies - of this license document, but changing it is not allowed. - -[This is the first released version of the Lesser GPL. It also counts - as the successor of the GNU Library Public License, version 2, hence - the version number 2.1.] - - Preamble - - The licenses for most software are designed to take away your -freedom to share and change it. By contrast, the GNU General Public -Licenses are intended to guarantee your freedom to share and change -free software--to make sure the software is free for all its users. - - This license, the Lesser General Public License, applies to some -specially designated software packages--typically libraries--of the -Free Software Foundation and other authors who decide to use it. You -can use it too, but we suggest you first think carefully about whether -this license or the ordinary General Public License is the better -strategy to use in any particular case, based on the explanations below. - - When we speak of free software, we are referring to freedom of use, -not price. Our General Public Licenses are designed to make sure that -you have the freedom to distribute copies of free software (and charge -for this service if you wish); that you receive source code or can get -it if you want it; that you can change the software and use pieces of -it in new free programs; and that you are informed that you can do -these things. - - To protect your rights, we need to make restrictions that forbid -distributors to deny you these rights or to ask you to surrender these -rights. These restrictions translate to certain responsibilities for -you if you distribute copies of the library or if you modify it. - - For example, if you distribute copies of the library, whether gratis -or for a fee, you must give the recipients all the rights that we gave -you. You must make sure that they, too, receive or can get the source -code. If you link other code with the library, you must provide -complete object files to the recipients, so that they can relink them -with the library after making changes to the library and recompiling -it. And you must show them these terms so they know their rights. - - We protect your rights with a two-step method: (1) we copyright the -library, and (2) we offer you this license, which gives you legal -permission to copy, distribute and/or modify the library. - - To protect each distributor, we want to make it very clear that -there is no warranty for the free library. Also, if the library is -modified by someone else and passed on, the recipients should know -that what they have is not the original version, so that the original -author's reputation will not be affected by problems that might be -introduced by others. - - Finally, software patents pose a constant threat to the existence of -any free program. We wish to make sure that a company cannot -effectively restrict the users of a free program by obtaining a -restrictive license from a patent holder. Therefore, we insist that -any patent license obtained for a version of the library must be -consistent with the full freedom of use specified in this license. - - Most GNU software, including some libraries, is covered by the -ordinary GNU General Public License. This license, the GNU Lesser -General Public License, applies to certain designated libraries, and -is quite different from the ordinary General Public License. We use -this license for certain libraries in order to permit linking those -libraries into non-free programs. - - When a program is linked with a library, whether statically or using -a shared library, the combination of the two is legally speaking a -combined work, a derivative of the original library. The ordinary -General Public License therefore permits such linking only if the -entire combination fits its criteria of freedom. The Lesser General -Public License permits more lax criteria for linking other code with -the library. - - We call this license the "Lesser" General Public License because it -does Less to protect the user's freedom than the ordinary General -Public License. It also provides other free software developers Less -of an advantage over competing non-free programs. These disadvantages -are the reason we use the ordinary General Public License for many -libraries. However, the Lesser license provides advantages in certain -special circumstances. - - For example, on rare occasions, there may be a special need to -encourage the widest possible use of a certain library, so that it becomes -a de-facto standard. To achieve this, non-free programs must be -allowed to use the library. A more frequent case is that a free -library does the same job as widely used non-free libraries. In this -case, there is little to gain by limiting the free library to free -software only, so we use the Lesser General Public License. - - In other cases, permission to use a particular library in non-free -programs enables a greater number of people to use a large body of -free software. For example, permission to use the GNU C Library in -non-free programs enables many more people to use the whole GNU -operating system, as well as its variant, the GNU/Linux operating -system. - - Although the Lesser General Public License is Less protective of the -users' freedom, it does ensure that the user of a program that is -linked with the Library has the freedom and the wherewithal to run -that program using a modified version of the Library. - - The precise terms and conditions for copying, distribution and -modification follow. Pay close attention to the difference between a -"work based on the library" and a "work that uses the library". The -former contains code derived from the library, whereas the latter must -be combined with the library in order to run. - - GNU LESSER GENERAL PUBLIC LICENSE - TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION - - 0. This License Agreement applies to any software library or other -program which contains a notice placed by the copyright holder or -other authorized party saying it may be distributed under the terms of -this Lesser General Public License (also called "this License"). -Each licensee is addressed as "you". - - A "library" means a collection of software functions and/or data -prepared so as to be conveniently linked with application programs -(which use some of those functions and data) to form executables. - - The "Library", below, refers to any such software library or work -which has been distributed under these terms. A "work based on the -Library" means either the Library or any derivative work under -copyright law: that is to say, a work containing the Library or a -portion of it, either verbatim or with modifications and/or translated -straightforwardly into another language. (Hereinafter, translation is -included without limitation in the term "modification".) - - "Source code" for a work means the preferred form of the work for -making modifications to it. For a library, complete source code means -all the source code for all modules it contains, plus any associated -interface definition files, plus the scripts used to control compilation -and installation of the library. - - Activities other than copying, distribution and modification are not -covered by this License; they are outside its scope. The act of -running a program using the Library is not restricted, and output from -such a program is covered only if its contents constitute a work based -on the Library (independent of the use of the Library in a tool for -writing it). Whether that is true depends on what the Library does -and what the program that uses the Library does. - - 1. You may copy and distribute verbatim copies of the Library's -complete source code as you receive it, in any medium, provided that -you conspicuously and appropriately publish on each copy an -appropriate copyright notice and disclaimer of warranty; keep intact -all the notices that refer to this License and to the absence of any -warranty; and distribute a copy of this License along with the -Library. - - You may charge a fee for the physical act of transferring a copy, -and you may at your option offer warranty protection in exchange for a -fee. - - 2. You may modify your copy or copies of the Library or any portion -of it, thus forming a work based on the Library, and copy and -distribute such modifications or work under the terms of Section 1 -above, provided that you also meet all of these conditions: - - a) The modified work must itself be a software library. - - b) You must cause the files modified to carry prominent notices - stating that you changed the files and the date of any change. - - c) You must cause the whole of the work to be licensed at no - charge to all third parties under the terms of this License. - - d) If a facility in the modified Library refers to a function or a - table of data to be supplied by an application program that uses - the facility, other than as an argument passed when the facility - is invoked, then you must make a good faith effort to ensure that, - in the event an application does not supply such function or - table, the facility still operates, and performs whatever part of - its purpose remains meaningful. - - (For example, a function in a library to compute square roots has - a purpose that is entirely well-defined independent of the - application. Therefore, Subsection 2d requires that any - application-supplied function or table used by this function must - be optional: if the application does not supply it, the square - root function must still compute square roots.) - -These requirements apply to the modified work as a whole. If -identifiable sections of that work are not derived from the Library, -and can be reasonably considered independent and separate works in -themselves, then this License, and its terms, do not apply to those -sections when you distribute them as separate works. But when you -distribute the same sections as part of a whole which is a work based -on the Library, the distribution of the whole must be on the terms of -this License, whose permissions for other licensees extend to the -entire whole, and thus to each and every part regardless of who wrote -it. - -Thus, it is not the intent of this section to claim rights or contest -your rights to work written entirely by you; rather, the intent is to -exercise the right to control the distribution of derivative or -collective works based on the Library. - -In addition, mere aggregation of another work not based on the Library -with the Library (or with a work based on the Library) on a volume of -a storage or distribution medium does not bring the other work under -the scope of this License. - - 3. You may opt to apply the terms of the ordinary GNU General Public -License instead of this License to a given copy of the Library. To do -this, you must alter all the notices that refer to this License, so -that they refer to the ordinary GNU General Public License, version 2, -instead of to this License. (If a newer version than version 2 of the -ordinary GNU General Public License has appeared, then you can specify -that version instead if you wish.) Do not make any other change in -these notices. - - Once this change is made in a given copy, it is irreversible for -that copy, so the ordinary GNU General Public License applies to all -subsequent copies and derivative works made from that copy. - - This option is useful when you wish to copy part of the code of -the Library into a program that is not a library. - - 4. You may copy and distribute the Library (or a portion or -derivative of it, under Section 2) in object code or executable form -under the terms of Sections 1 and 2 above provided that you accompany -it with the complete corresponding machine-readable source code, which -must be distributed under the terms of Sections 1 and 2 above on a -medium customarily used for software interchange. - - If distribution of object code is made by offering access to copy -from a designated place, then offering equivalent access to copy the -source code from the same place satisfies the requirement to -distribute the source code, even though third parties are not -compelled to copy the source along with the object code. - - 5. A program that contains no derivative of any portion of the -Library, but is designed to work with the Library by being compiled or -linked with it, is called a "work that uses the Library". Such a -work, in isolation, is not a derivative work of the Library, and -therefore falls outside the scope of this License. - - However, linking a "work that uses the Library" with the Library -creates an executable that is a derivative of the Library (because it -contains portions of the Library), rather than a "work that uses the -library". The executable is therefore covered by this License. -Section 6 states terms for distribution of such executables. - - When a "work that uses the Library" uses material from a header file -that is part of the Library, the object code for the work may be a -derivative work of the Library even though the source code is not. -Whether this is true is especially significant if the work can be -linked without the Library, or if the work is itself a library. The -threshold for this to be true is not precisely defined by law. - - If such an object file uses only numerical parameters, data -structure layouts and accessors, and small macros and small inline -functions (ten lines or less in length), then the use of the object -file is unrestricted, regardless of whether it is legally a derivative -work. (Executables containing this object code plus portions of the -Library will still fall under Section 6.) - - Otherwise, if the work is a derivative of the Library, you may -distribute the object code for the work under the terms of Section 6. -Any executables containing that work also fall under Section 6, -whether or not they are linked directly with the Library itself. - - 6. As an exception to the Sections above, you may also combine or -link a "work that uses the Library" with the Library to produce a -work containing portions of the Library, and distribute that work -under terms of your choice, provided that the terms permit -modification of the work for the customer's own use and reverse -engineering for debugging such modifications. - - You must give prominent notice with each copy of the work that the -Library is used in it and that the Library and its use are covered by -this License. You must supply a copy of this License. If the work -during execution displays copyright notices, you must include the -copyright notice for the Library among them, as well as a reference -directing the user to the copy of this License. Also, you must do one -of these things: - - a) Accompany the work with the complete corresponding - machine-readable source code for the Library including whatever - changes were used in the work (which must be distributed under - Sections 1 and 2 above); and, if the work is an executable linked - with the Library, with the complete machine-readable "work that - uses the Library", as object code and/or source code, so that the - user can modify the Library and then relink to produce a modified - executable containing the modified Library. (It is understood - that the user who changes the contents of definitions files in the - Library will not necessarily be able to recompile the application - to use the modified definitions.) - - b) Use a suitable shared library mechanism for linking with the - Library. A suitable mechanism is one that (1) uses at run time a - copy of the library already present on the user's computer system, - rather than copying library functions into the executable, and (2) - will operate properly with a modified version of the library, if - the user installs one, as long as the modified version is - interface-compatible with the version that the work was made with. - - c) Accompany the work with a written offer, valid for at - least three years, to give the same user the materials - specified in Subsection 6a, above, for a charge no more - than the cost of performing this distribution. - - d) If distribution of the work is made by offering access to copy - from a designated place, offer equivalent access to copy the above - specified materials from the same place. - - e) Verify that the user has already received a copy of these - materials or that you have already sent this user a copy. - - For an executable, the required form of the "work that uses the -Library" must include any data and utility programs needed for -reproducing the executable from it. However, as a special exception, -the materials to be distributed need not include anything that is -normally distributed (in either source or binary form) with the major -components (compiler, kernel, and so on) of the operating system on -which the executable runs, unless that component itself accompanies -the executable. - - It may happen that this requirement contradicts the license -restrictions of other proprietary libraries that do not normally -accompany the operating system. Such a contradiction means you cannot -use both them and the Library together in an executable that you -distribute. - - 7. You may place library facilities that are a work based on the -Library side-by-side in a single library together with other library -facilities not covered by this License, and distribute such a combined -library, provided that the separate distribution of the work based on -the Library and of the other library facilities is otherwise -permitted, and provided that you do these two things: - - a) Accompany the combined library with a copy of the same work - based on the Library, uncombined with any other library - facilities. This must be distributed under the terms of the - Sections above. - - b) Give prominent notice with the combined library of the fact - that part of it is a work based on the Library, and explaining - where to find the accompanying uncombined form of the same work. - - 8. You may not copy, modify, sublicense, link with, or distribute -the Library except as expressly provided under this License. Any -attempt otherwise to copy, modify, sublicense, link with, or -distribute the Library is void, and will automatically terminate your -rights under this License. However, parties who have received copies, -or rights, from you under this License will not have their licenses -terminated so long as such parties remain in full compliance. - - 9. You are not required to accept this License, since you have not -signed it. However, nothing else grants you permission to modify or -distribute the Library or its derivative works. These actions are -prohibited by law if you do not accept this License. Therefore, by -modifying or distributing the Library (or any work based on the -Library), you indicate your acceptance of this License to do so, and -all its terms and conditions for copying, distributing or modifying -the Library or works based on it. - - 10. Each time you redistribute the Library (or any work based on the -Library), the recipient automatically receives a license from the -original licensor to copy, distribute, link with or modify the Library -subject to these terms and conditions. You may not impose any further -restrictions on the recipients' exercise of the rights granted herein. -You are not responsible for enforcing compliance by third parties with -this License. - - 11. If, as a consequence of a court judgment or allegation of patent -infringement or for any other reason (not limited to patent issues), -conditions are imposed on you (whether by court order, agreement or -otherwise) that contradict the conditions of this License, they do not -excuse you from the conditions of this License. If you cannot -distribute so as to satisfy simultaneously your obligations under this -License and any other pertinent obligations, then as a consequence you -may not distribute the Library at all. For example, if a patent -license would not permit royalty-free redistribution of the Library by -all those who receive copies directly or indirectly through you, then -the only way you could satisfy both it and this License would be to -refrain entirely from distribution of the Library. - -If any portion of this section is held invalid or unenforceable under any -particular circumstance, the balance of the section is intended to apply, -and the section as a whole is intended to apply in other circumstances. - -It is not the purpose of this section to induce you to infringe any -patents or other property right claims or to contest validity of any -such claims; this section has the sole purpose of protecting the -integrity of the free software distribution system which is -implemented by public license practices. Many people have made -generous contributions to the wide range of software distributed -through that system in reliance on consistent application of that -system; it is up to the author/donor to decide if he or she is willing -to distribute software through any other system and a licensee cannot -impose that choice. - -This section is intended to make thoroughly clear what is believed to -be a consequence of the rest of this License. - - 12. If the distribution and/or use of the Library is restricted in -certain countries either by patents or by copyrighted interfaces, the -original copyright holder who places the Library under this License may add -an explicit geographical distribution limitation excluding those countries, -so that distribution is permitted only in or among countries not thus -excluded. In such case, this License incorporates the limitation as if -written in the body of this License. - - 13. The Free Software Foundation may publish revised and/or new -versions of the Lesser General Public License from time to time. -Such new versions will be similar in spirit to the present version, -but may differ in detail to address new problems or concerns. - -Each version is given a distinguishing version number. If the Library -specifies a version number of this License which applies to it and -"any later version", you have the option of following the terms and -conditions either of that version or of any later version published by -the Free Software Foundation. If the Library does not specify a -license version number, you may choose any version ever published by -the Free Software Foundation. - - 14. If you wish to incorporate parts of the Library into other free -programs whose distribution conditions are incompatible with these, -write to the author to ask for permission. For software which is -copyrighted by the Free Software Foundation, write to the Free -Software Foundation; we sometimes make exceptions for this. Our -decision will be guided by the two goals of preserving the free status -of all derivatives of our free software and of promoting the sharing -and reuse of software generally. - - NO WARRANTY - - 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO -WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. -EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR -OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY -KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE -IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR -PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE -LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME -THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. - - 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN -WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY -AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU -FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR -CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE -LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING -RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A -FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF -SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH -DAMAGES. - - END OF TERMS AND CONDITIONS - - How to Apply These Terms to Your New Libraries - - If you develop a new library, and you want it to be of the greatest -possible use to the public, we recommend making it free software that -everyone can redistribute and change. You can do so by permitting -redistribution under these terms (or, alternatively, under the terms of the -ordinary General Public License). - - To apply these terms, attach the following notices to the library. It is -safest to attach them to the start of each source file to most effectively -convey the exclusion of warranty; and each file should have at least the -"copyright" line and a pointer to where the full notice is found. - - - Copyright (C) - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - -Also add information on how to contact you by electronic and paper mail. - -You should also get your employer (if you work as a programmer) or your -school, if any, to sign a "copyright disclaimer" for the library, if -necessary. Here is a sample; alter the names: - - Yoyodyne, Inc., hereby disclaims all copyright interest in the - library `Frob' (a library for tweaking knobs) written by James Random Hacker. - - , 1 April 1990 - Ty Coon, President of Vice - -That's all there is to it! diff --git a/third_party/xma/NOTICE.md b/third_party/xma/NOTICE.md deleted file mode 100644 index 1e2176829..000000000 --- a/third_party/xma/NOTICE.md +++ /dev/null @@ -1,12 +0,0 @@ -# XMA decoder third-party notice - -The Rust package `xma` is consumed as an external Cargo dependency by `runtime/xma_decoder`. Cargo pins the source to commit `27122f7dfcceb9a899555362ee0dde2d530e033c` in [omonkeyz/xbox-emulator](https://github.com/omonkeyz/xbox-emulator/tree/27122f7dfcceb9a899555362ee0dde2d530e033c/crates/compat/xma). The package declares LGPL-2.1-or-later. Its license text is retained in `COPYING.LGPLv2.1`. - -The upstream NOTICE identifies this package as a Rust port of FFmpeg's WMA Pro/XMA decoder from FFmpeg commit `76fa18983e3849595fdc332bf9fa583d5fe7a147`. Original notices: - -> Wmapro compatible decoder -> Copyright (c) 2007 Baptiste Coudurier, Benjamin Larsson, Ulion -> Copyright (c) 2008 - 2011 Sascha Sommer, Benjamin Larsson -> This file is part of FFmpeg and is licensed under the GNU Lesser General Public License, version 2.1 or later. - -Leonida's C ABI wrapper is independently written and licensed under GPL-3.0-or-later. No upstream implementation source is copied or vendored. diff --git a/third_party/xtaskqueue/Include/XAsync.h b/third_party/xtaskqueue/Include/XAsync.h deleted file mode 100644 index 9e7efe787..000000000 --- a/third_party/xtaskqueue/Include/XAsync.h +++ /dev/null @@ -1,132 +0,0 @@ -// Copyright (c) Microsoft Corporation -// Licensed under the MIT license. See LICENSE file in the project root for full license information. - -#if !defined(__cplusplus) - #error C++11 required -#endif - -#pragma once -#include "XTaskQueue.h" - -extern "C" -{ - -/// -/// An XAsyncBlock defines a piece of asynchronous work. An async block can be used -/// to poll for an async call's status and retrieve call results. An XAsyncBlock -/// needs to remain valid for the lifetime of an async call. -/// -/// If a completion callback is set, the lifetime of the call extends until that -/// callback has returned, because the callback receives this XAsyncBlock pointer. -/// The call's status can stop being E_PENDING before the callback runs (for -/// example, when the completion port of the queue has not been dispatched yet). -/// Do not reuse, modify, or free the XAsyncBlock until the completion callback -/// has been invoked; reusing it from within the completion callback is allowed. -/// If no completion callback is set, the block may be reused or freed once -/// XAsyncGetStatus no longer returns E_PENDING and any result has been -/// retrieved. -/// -struct XAsyncBlock; - -/// -/// Callback routine that is invoked when an async call completes. Use XAsyncGetStatus -/// or the async call's Get*Result method to obtain the results of the call. If the -/// call was canceled these methods will return E_ABORT. -/// -/// The completion callback marks the end of the async call. Until it has been -/// invoked, the XAsyncBlock must not be reused for another call or freed, even if -/// XAsyncGetStatus(asyncBlock, false) has already returned a completed status. -/// When a completion callback is set, use the callback (not polling -/// XAsyncGetStatus) to determine when the call has finished. -/// -/// A pointer to the XAsyncBlock that was passed to the async call. -/// -typedef void CALLBACK XAsyncCompletionRoutine(_Inout_ struct XAsyncBlock* asyncBlock); - -/// -/// Callback routine that is invoked on a worker asynchronously when XAsyncRun is called. -/// The result of the callback becomes the result of the async call. -/// -/// A pointer to the XAsyncBlock that was passed to XAsyncRun. -/// -/// -typedef HRESULT CALLBACK XAsyncWork(_Inout_ struct XAsyncBlock* asyncBlock); - -struct XAsyncBlock -{ - /// - /// The queue to queue the call on - /// - XTaskQueueHandle queue; - - /// - /// Optional context pointer to pass to the callback - /// - void* context; - - /// - /// Optional callback that will be invoked when the call completes. If set, - /// this XAsyncBlock must remain valid and unused by other calls until the - /// callback has been invoked. - /// - XAsyncCompletionRoutine* callback; - - /// - /// Internal use only - /// - unsigned char internal[sizeof(void*) * 4]; -}; - -/// -/// Returns the status of the asynchronous operation, optionally waiting -/// for it to complete. Once complete, you may call the api's get result -/// api if the async call has a resulting data payload. If it doesn't, calling -/// a get result method is unneeded. If a completion callback was set into -/// the asyncBlock, a wait will wait until the completion callback has -/// returned. -/// -/// Without a wait, the status reflects the result of the call and can stop -/// being E_PENDING before the completion callback has been invoked (the callback -/// is queued to the completion port of the task queue). A completed status from -/// a non-waiting call therefore does not mean the XAsyncBlock can be reused or -/// freed when a completion callback is set; wait for the callback to be invoked -/// first. Avoid mixing polling and a completion callback for the same call. -/// -/// A pointer to the XAsyncBlock that was passed to the async call. -/// If true, XAsyncGetStatus waits until the async call either completes or is canceled. -STDAPI XAsyncGetStatus( - _Inout_ XAsyncBlock* asyncBlock, - _In_ bool wait - ) noexcept; - -/// -/// Returns the required size of the buffer to pass to XAsyncGetResult. -/// -/// A pointer to the XAsyncBlock that was passed to the async call. -/// The required size of the buffer in bytes needed to hold the results. -STDAPI XAsyncGetResultSize( - _Inout_ XAsyncBlock* asyncBlock, - _Out_ size_t* bufferSize - ) noexcept; - -/// -/// Cancels an asynchronous operation. The status result will return E_ABORT, -/// the completion callback will be invoked and the event in the async block will be -/// signaled. This does nothing if the call has already completed. -/// -/// A pointer to the XAsyncBlock that was passed to the async call. -STDAPI_(void) XAsyncCancel( - _Inout_ XAsyncBlock* asyncBlock - ) noexcept; - -/// -/// Runs the given callback asynchronously. -/// -/// A pointer to an async block that is used to track the async call. -/// A pointer to a callback function to run asynchronously. -STDAPI XAsyncRun( - _Inout_ XAsyncBlock* asyncBlock, - _In_ XAsyncWork* work - ) noexcept; - -} // extern "C" diff --git a/third_party/xtaskqueue/Include/XAsyncProvider.h b/third_party/xtaskqueue/Include/XAsyncProvider.h deleted file mode 100644 index 404d9d55c..000000000 --- a/third_party/xtaskqueue/Include/XAsyncProvider.h +++ /dev/null @@ -1,171 +0,0 @@ -// Copyright (c) Microsoft Corporation -// Licensed under the MIT license. See LICENSE file in the project root for full license information. - -#if !defined(__cplusplus) - #error C++11 required -#endif - -#pragma once - -#include -#include "XAsync.h" - -extern "C" -{ - -enum class XAsyncOp : uint32_t -{ - /// - /// An async provider is invoked with this opcode during XAsyncBegin or XAsyncBeginAlloc. - /// If the provider implements this op code, they should start their asynchronous task, - /// either by calling XAsyncSchedule or through exterior means. This callback is - /// called synchronously in the XAsyncBegin call chain, so it should never block. - /// - Begin, - - /// - /// An async provider is invoked with this opcode when XAsyncSchedule has been called to - /// schedule work. Implementations should perform their asynchronous work and then call - /// XAsyncComplete with the data payload size. If additional work needs to be done they - /// can schedule it and return E_PENDING. - /// - DoWork, - - /// - /// An async provider is invoked with this opcode after an async call completes and the - /// user needs to get the resulting data payload. The buffer and bufferSize have - /// been arg checked. - /// - GetResult, - - /// - /// An async provider is invoked with this opcode when the async work should be canceled. If - /// you can cancel your work you should call XAsyncComplete with an error code of E_ABORT when - /// the work has been canceled. - /// - Cancel, - - /// - /// An async provider is invoked with this opcode when the async call is over and - /// data in the context can be cleaned up. - /// - Cleanup -}; - -/// -/// A data block passed to an async provider callback. Fields in this structure are filled -/// in as the call progresses. -/// -struct XAsyncProviderData -{ - /// - /// The async block for the call. - /// - XAsyncBlock* async; - - /// - /// Valid during a GetResult opcode and holds the size of the buffer. This will - /// be at least as large as the data size provided to XAsyncComplete. - /// - size_t bufferSize; - - /// - /// Valid during a GetResult opcode and holds the output data buffer. - /// - void* buffer; - - /// - /// Valid during any opcode this is a user provided context pointer that was provided - /// to XAsyncBegin. It should be freed during the Cleanup opcode. - /// - void* context; -}; - -/// -/// A callback function that implements the async call. This function will be invoked -/// multiple times with different XAsyncOp operation codes to indicate what work it -/// should perform. -/// -/// The async operatiopn to perform. -/// Data used to track the async call. -/// -typedef HRESULT CALLBACK XAsyncProvider(_In_ XAsyncOp op, _Inout_ const XAsyncProviderData* data); - -/// -/// Initializes an async block for use. Once begun calls such -/// as XAsyncGetStatus will provide meaningful data. It is assumed the -/// async work will begin on some system defined thread after this call -/// returns. The token and function parameters can be used to help identify -/// mismatched Begin/GetResult calls. The token is typically the function -/// pointer of the async API you are implementing, and the functionName parameter -/// is typically the __FUNCTION__ compiler macro. -/// -/// A pointer to the XAsyncBlock that holds data for the call. -/// An optional context pointer that will be stored in the XAsyncProviderData object passed back to the XAsyncProvider callback. -/// An optional arbitrary pointer that can be used to identify this call. -/// An optional string that names the async call. This is typically the __FUNCTION__ compiler macro. -/// The function callback to invoke to implement the async call. -STDAPI XAsyncBegin( - _Inout_ XAsyncBlock* asyncBlock, - _In_opt_ void* context, - _In_opt_ const void* identity, - _In_opt_ const char* identityName, - _In_ XAsyncProvider* provider - ) noexcept; - -/// -/// Schedules a callback to do async work. Calling this is optional. If the async work can be done -/// through a system - async mechanism like overlapped IO or async COM, there is no need to schedule -/// work. If work should be scheduled after a delay, pass the number of ms XAsyncSchedule should wait -/// before it schedules work. -/// -/// A pointer to the XAsyncBlock that was passed to XAsyncBegin. -/// How long the system should wait before scheduling the async call with the async queue. -STDAPI XAsyncSchedule( - _Inout_ XAsyncBlock* asyncBlock, - _In_ uint32_t delayInMs - ) noexcept; - -/// -/// Called when async work is completed and the results can be returned. -/// The caller should supply the resulting data payload size. If the call -/// has no data payload, pass zero. This sets the call's status immediately, -/// but any completion callback is queued to the completion port of the task -/// queue and runs later; the XAsyncBlock remains in use until that callback -/// has been invoked. -/// -/// A pointer to the XAsyncBlock that was passed to XAsyncBegin. -/// The resut of the call. This should not be E_PENDING as that result is reserved for an incomplete call. If you are canceling this call you should pass E_ABORT. -/// The required size in bytes of the call result. If the call has no data to return this should be zero. -STDAPI_(void) XAsyncComplete( - _Inout_ XAsyncBlock* asyncBlock, - _In_ HRESULT result, - _In_ size_t requiredBufferSize - ) noexcept; - -/// -/// Returns the result data for the asynchronous operation. After this call -/// the async block is completed and no longer associated with the -/// operation. The token parameter should match the token passed into -/// XAsyncBegin. If a completion callback was set, the async block still -/// must not be reused or freed until that callback has been invoked. -/// -/// A pointer to the XAsyncBlock that was passed to XAsyncBegin. -/// An optional pointer used to match this result call with a prior XAsyncBegin call. If an identity pointer was passed to XAsyncBegin, the same pointer must be passed here. -/// The size of the provided buffer, in bytes. -/// A pointer to the result buffer. -/// An optional pointer that contains the number of bytes written to the buffer. This is defined as the requiredResultSize passed to XAsyncComplete. -STDAPI XAsyncGetResult( - _Inout_ XAsyncBlock* asyncBlock, - _In_opt_ const void* identity, - _In_ size_t bufferSize, - _Out_writes_bytes_to_opt_(bufferSize, *bufferUsed) void* buffer, - _Out_opt_ size_t* bufferUsed - ) noexcept; - -/// -/// This is used generate an identity to pass to XAsyncBegin/XAsyncGetResult -/// -#define XASYNC_IDENTITY(method) #method - -} // extern "C" diff --git a/third_party/xtaskqueue/Include/XTaskQueue.h b/third_party/xtaskqueue/Include/XTaskQueue.h deleted file mode 100644 index bcb210f59..000000000 --- a/third_party/xtaskqueue/Include/XTaskQueue.h +++ /dev/null @@ -1,335 +0,0 @@ -// Copyright (c) Microsoft Corporation -// Licensed under the MIT license. See LICENSE file in the project root for full license information. - -#if !defined(__cplusplus) - #error C++11 required -#endif - -#pragma once -#include - -extern "C" -{ - -/// -/// A task queue contains and dispatches callbacks. A task queue has two ports: a worker port and -/// a completion port. Each port can have different rules for how queued calls -/// are dispatched. -/// -typedef struct XTaskQueueObject* XTaskQueueHandle; - -/// -/// A task queue port represents one port of a task queue. A port's lifetime is controlled -/// by its owning task queue. -/// -typedef struct XTaskQueuePortObject* XTaskQueuePortHandle; - -/// -/// Describes how task queue callbacks are processed. -/// -enum class XTaskQueueDispatchMode : uint32_t -{ - /// - /// Callbacks are invoked manually by XTaskQueueDispatch - /// - Manual, - - /// - /// Callbacks are queued to the system thread pool and will - /// be processed in order by the thread pool across multiple thread - /// pool threads. - /// - ThreadPool, - - /// - /// Callbacks are queued to the system thread pool and - /// will be processed one at a time. - /// - SerializedThreadPool, - - /// - /// Callbacks are not queued at all but are dispatched - /// immediately by the thread that submits them. - /// - Immediate -}; - -/// -/// Declares which port of a task queue to dispatch or submit -/// callbacks to. -/// -enum class XTaskQueuePort : uint32_t -{ - /// - /// Work callbacks - /// - Work, - - /// - /// Completion callbacks after work is done - /// - Completion -}; - -/// -/// A token returned when registering a callback to identify the registration. This token -/// is later used to unregister the callback. -/// -struct XTaskQueueRegistrationToken -{ - uint64_t token; -}; - -/// -/// A callback that is invoked by the task queue. -/// -/// A context pointer that was passed during XTaskQueueSubmitCallback. -/// If true, callbacks are being canceled because the queue is terminating. -/// -typedef void CALLBACK XTaskQueueCallback(_In_opt_ void* context, _In_ bool canceled); - -/// -/// A callback that is invoked by the task queue whenever an item is submitted for execution. -/// -/// A context pointer that was passed during XTaskQueueRegisterMonitor. -/// The task queue where the callback was submitted. -/// The port the callback was submitted to. -/// -typedef void CALLBACK XTaskQueueMonitorCallback(_In_opt_ void* context, _In_ XTaskQueueHandle queue, _In_ XTaskQueuePort port); - -/// -/// A callback that is invoked when a task queue is terminated. -/// -/// A context pointer that was passed during XTaskQueueTerminate. -typedef void CALLBACK XTaskQueueTerminatedCallback(_In_opt_ void* context); - -/// -/// Creates a Task Queue, which can be used to queue -/// and dispatch calls. Task Queues are -/// reference counted objects. Release the reference -/// by calling XTaskQueueCloseHandle. -/// -/// The dispatch mode for the "work" port of the queue. -/// The dispatch mode for the "completion" port of the queue. -/// The newly created queue. -STDAPI XTaskQueueCreate( - _In_ XTaskQueueDispatchMode workDispatchMode, - _In_ XTaskQueueDispatchMode completionDispatchMode, - _Out_ XTaskQueueHandle* queue - ) noexcept; - -/// -/// Creates a task queue composed of ports of other -/// task queues. A composite task queue will duplicate -/// the handles of queues that own the provided ports. -/// -/// The port to use for queuing work callbacks. -/// The port to use for queuing completion callbacks. -STDAPI XTaskQueueCreateComposite( - _In_ XTaskQueuePortHandle workPort, - _In_ XTaskQueuePortHandle completionPort, - _Out_ XTaskQueueHandle* queue - ) noexcept; - -/// -/// Returns the task queue port handle for the given -/// port. Task queue port handles are owned by the -/// task queue and do not have to be closed. They are -/// used when creating composite task queues. -/// -/// The task queue to get the port from. -/// The port to get. -STDAPI XTaskQueueGetPort( - _In_ XTaskQueueHandle queue, - _In_ XTaskQueuePort port, - _Out_ XTaskQueuePortHandle* portHandle - ) noexcept; - -/// -/// Duplicates the XTaskQueueHandle object. Use XTaskQueueCloseHandle to close it. -/// -/// The queue to reference. -/// The duplicated queue handle. -STDAPI XTaskQueueDuplicateHandle( - _In_ XTaskQueueHandle queueHandle, - _Out_ XTaskQueueHandle* duplicatedHandle - ) noexcept; - -/// -/// Processes an item in the task queue for the given port. If an item -/// is processed this will return true. If there are no items to process -/// this returns false. You can pass a timeout, which will cause -/// XTaskQueueDispatch to wait for something to arrive in the queue. -/// -/// The queue to dispatch work on. -/// The port to dispatch. -/// The number of ms to wait for work to arrive before returning false. -STDAPI_(bool) XTaskQueueDispatch( - _In_ XTaskQueueHandle queue, - _In_ XTaskQueuePort port, - _In_ uint32_t timeoutInMs - ) noexcept; - -/// -/// Closes the task queue. The queue is not actually destroyed until -/// all handles are closed and there are no outstanding callbacks -/// enqueued. -/// -/// The queue to close. -STDAPI_(void) XTaskQueueCloseHandle( - _In_ XTaskQueueHandle queue - ) noexcept; - -/// -/// Terminates a task queue by canceling all pending items and -/// preventing new items from being queued. Once a queue is terminated -/// its handle can be closed. New items cannot be enqueued to a task -/// queue that has been terminated. -/// -/// Each task queue terminates independently. For composite queues created -/// with XTaskQueueCreateComposite, terminating a composite queue does NOT -/// automatically terminate other queues sharing the same ports. -/// -/// When wait=true: -/// - Blocks until this queue's termination callback completes -/// - Does NOT wait for other independent queues (including composite delegates) -/// - Ensures this queue's termination callback has finished executing -/// - Safe to unload code/modules after this returns -/// -/// When wait=false: -/// - Returns immediately after initiating termination -/// - The termination callback will be invoked asynchronously when termination completes -/// -/// The termination callback is invoked after all work and completion callbacks -/// have been canceled or completed. After the termination callback returns, the -/// implementation will no longer access the queue's internal state. -/// -/// For coordinated shutdown of multiple queues sharing ports, use termination -/// callbacks to track completion of each queue before performing final cleanup. -/// -/// The queue to terminate. -/// True to wait for the termination to complete. -/// An optional context pointer to pass to the callback. -/// An optional callback that will be called when the queue has terminated. -STDAPI XTaskQueueTerminate( - _In_ XTaskQueueHandle queue, - _In_ bool wait, - _In_opt_ void* callbackContext, - _In_opt_ XTaskQueueTerminatedCallback* callback - ) noexcept; - -/// -/// Submits a callback to the queue for the given port. -/// -/// The queue to submit the callback to. -/// The port to submit the callback to. -/// An optional context pointer that will be passed to the callback. -/// A pointer to the callback function. -STDAPI XTaskQueueSubmitCallback( - _In_ XTaskQueueHandle queue, - _In_ XTaskQueuePort port, - _In_opt_ void* callbackContext, - _In_ XTaskQueueCallback* callback - ) noexcept; - -/// -/// Submits a callback to the queue for the given port. The callback will be added -/// to the queue after delayMs milliseconds. -/// -/// The queue to submit the callback to. -/// The port to submit the callback to. -/// The number of milliseconds to delay before submitting the callback to the queue. -/// An optional context pointer that will be passed to the callback. -/// A pointer to the callback function. -STDAPI XTaskQueueSubmitDelayedCallback( - _In_ XTaskQueueHandle queue, - _In_ XTaskQueuePort port, - _In_ uint32_t delayMs, - _In_opt_ void* callbackContext, - _In_ XTaskQueueCallback* callback - ) noexcept; - -/// -/// Registers a wait handle with the task queue. When the wait handle -/// is satisfied the task queue will invoke the given callback. This -/// provides an efficient way to add items to a task queue in -/// response to handles becoming signaled. -/// -/// The queue to submit the callback to. -/// The port to invoke the callback on. -/// The handle to monitor. -/// An optional context pointer that will be passed to the callback. -/// A pointer to the callback function. -/// A registration token. -STDAPI XTaskQueueRegisterWaiter( - _In_ XTaskQueueHandle queue, - _In_ XTaskQueuePort port, - _In_ HANDLE waitHandle, - _In_opt_ void* callbackContext, - _In_ XTaskQueueCallback* callback, - _Out_ XTaskQueueRegistrationToken* token - ) noexcept; - -/// -/// Unregisters a previously registered task queue waiter. -/// -/// The queue to remove the waiter from. -/// The token returned from XTaskQueueRegisterWaiter. -STDAPI_(void) XTaskQueueUnregisterWaiter( - _In_ XTaskQueueHandle queue, - _In_ XTaskQueueRegistrationToken token - ) noexcept; - -/// -/// Registers a callback that will be invoked whenever a callback -/// is submitted to this queue. -/// -/// The queue to register the submit callback to. -/// An optional context pointer to be passed to the callback. -/// A callback that will be invoked when a new callback is submitted to the queue. -/// A token used in a later call to XTaskQueueUnregisterMonitor to remove the callback. -STDAPI XTaskQueueRegisterMonitor( - _In_ XTaskQueueHandle queue, - _In_opt_ void* callbackContext, - _In_ XTaskQueueMonitorCallback* callback, - _Out_ XTaskQueueRegistrationToken* token - ) noexcept; - -/// -/// Unregisters a previously registered callback. This blocks if there are outstanding montior -/// callbacks. -/// -/// The queue to remove the submit callback from. -/// The token returned from XTaskQueueRegisterMonitor. -STDAPI_(void) XTaskQueueUnregisterMonitor( - _In_ XTaskQueueHandle queue, - _In_ XTaskQueueRegistrationToken token - ) noexcept; - -/// -/// Obtains a handle to the process task queue, or nullptr if there is no -/// process task queue. By default, there is a process task queue -/// that uses the thread pool for both work and completion ports. You -/// can replace the default process task queue by calling -/// XTaskQueueSetCurrentProcessTaskQueue, and you can prevent callers using -/// the process task queue by calling XTaskQueueSetCurrentProcessTaskQueue -/// with a null queue parameter. -/// -/// This API returns true if there is a process task queue available. -/// You are responsible for calling XTaskQueueCloseHandle on the handle -/// returned from this API. -/// -STDAPI_(bool) XTaskQueueGetCurrentProcessTaskQueue(_Out_ XTaskQueueHandle* queue) noexcept; - -/// -/// Sets the given task queue as the process wide task queue. The -/// queue can be set to nullptr, in which case XTaskQueueGetCurrentProcessTaskQueue will -/// also return nullptr. The provided queue will have its handle duplicated -/// and any existing process task queue will have its handle closed. -/// -/// The queue to set up as the default task queue for the procces. -STDAPI_(void) XTaskQueueSetCurrentProcessTaskQueue( - _In_opt_ XTaskQueueHandle queue - ) noexcept; - -} // extern "C" diff --git a/third_party/xtaskqueue/LICENSE b/third_party/xtaskqueue/LICENSE deleted file mode 100644 index de9d570d3..000000000 --- a/third_party/xtaskqueue/LICENSE +++ /dev/null @@ -1,23 +0,0 @@ -MIT License - -Copyright (c) 2017 Microsoft Corporation - -All rights reserved. - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. \ No newline at end of file diff --git a/third_party/xtaskqueue/README.md b/third_party/xtaskqueue/README.md deleted file mode 100644 index 21a43faa7..000000000 --- a/third_party/xtaskqueue/README.md +++ /dev/null @@ -1,14 +0,0 @@ -# XTaskQueue / XAsync (from microsoft/libHttpClient) - -The GDK's task queue and async-block implementation, taken unmodified from -[microsoft/libHttpClient](https://github.com/microsoft/libHttpClient) at commit -`c5007fd9cbdc785518ea6dccc5751b125d451cc1`. **MIT licence** (see `LICENSE`), which is compatible with Leonida's -GPL-3.0-or-later. - -Only what the task queue needs is copied: `Include/XAsync.h`, `Include/XAsyncProvider.h`, `Include/XTaskQueue.h`, -the Win32 sources and headers of `Source/Task/`, and `Source/Common/ResultMacros.h`. The HTTP and WebSocket stack is -not included and nothing here goes online. - -libHttpClient's own `pch.h` pulls in that whole stack, so `runtime/shims/xtaskqueue/pch.h` stands in for it with -the few macros and error codes `Source/Task` uses. To update: copy the same files from a newer commit, change the -commit above and rebuild `xgameruntime_test`. diff --git a/third_party/xtaskqueue/Source/Common/ResultMacros.h b/third_party/xtaskqueue/Source/Common/ResultMacros.h deleted file mode 100644 index 022a0d702..000000000 --- a/third_party/xtaskqueue/Source/Common/ResultMacros.h +++ /dev/null @@ -1,22 +0,0 @@ -#pragma once - -#define RETURN_HR(hr) return(hr) -#define RETURN_LAST_ERROR() return HRESULT_FROM_WIN32(GetLastError()) -#define RETURN_WIN32(win32err) return HRESULT_FROM_WIN32(win32err) - -#define RETURN_IF_FAILED(hr) do { HRESULT __hrRet = hr; if (FAILED(__hrRet)) { RETURN_HR(__hrRet); }} while (0, 0) -#define RETURN_IF_WIN32_BOOL_FALSE(win32BOOL) do { BOOL __boolRet = win32BOOL; if (!__boolRet) { RETURN_LAST_ERROR(); }} while (0, 0) -#define RETURN_IF_NULL_ALLOC(ptr) do { if ((ptr) == nullptr) { RETURN_HR(E_OUTOFMEMORY); }} while (0, 0) -#define RETURN_HR_IF(hr, condition) do { if (condition) { RETURN_HR(hr); }} while (0, 0) -#define RETURN_HR_IF_FALSE(hr, condition) do { if (!(condition)) { RETURN_HR(hr); }} while (0, 0) -#define RETURN_LAST_ERROR_IF(condition) do { if (condition) { RETURN_LAST_ERROR(); }} while (0, 0) -#define RETURN_LAST_ERROR_IF_NULL(ptr) do { if ((ptr) == nullptr) { RETURN_LAST_ERROR(); }} while (0, 0) - -#define LOG_IF_FAILED(hr) do { HRESULT __hrRet = hr; if (FAILED(__hrRet)) { HC_TRACE_ERROR(HTTPCLIENT, "%s: 0x%08X", #hr, __hrRet); }} while (0, 0) - -#define FAIL_FAST_MSG(fmt, ...) \ - HC_TRACE_ERROR(HTTPCLIENT, fmt, ##__VA_ARGS__); \ - ASSERT(false); \ - - -#define FAIL_FAST_IF_FAILED(hr) do { HRESULT __hrRet = hr; if (FAILED(__hrRet)) { FAIL_FAST_MSG("%s 0x%08X", #hr, __hrRet); }} while (0, 0) \ No newline at end of file diff --git a/third_party/xtaskqueue/Source/Task/ApiRefState.h b/third_party/xtaskqueue/Source/Task/ApiRefState.h deleted file mode 100644 index f3419b716..000000000 --- a/third_party/xtaskqueue/Source/Task/ApiRefState.h +++ /dev/null @@ -1,111 +0,0 @@ -// Copyright (c) Microsoft Corporation -// Licensed under the MIT license. See LICENSE file in the project root for full license information. - -#pragma once - -#include -#include -#include - -// Atomic reference count with an irreversible rundown marker. -// The final Release atomically sets the dying bit. -class ApiRefState final -{ -public: - struct ReleaseResult - { - uint32_t remaining; - bool startRundown; - }; - - // AddRef is also used internally during rundown. - uint32_t AddRef() noexcept - { - uint32_t current = m_state.load(); - - for (;;) - { - uint32_t refs = current & kRefMask; - - if (refs == kRefMask) - { - std::terminate(); - } - - if (m_state.compare_exchange_weak(current, current + 1)) - { - return refs; - } - } - } - - // Never acquire a new external reference after rundown starts. - bool TryAddRef() noexcept - { - uint32_t current = m_state.load(); - - for (;;) - { - uint32_t refs = current & kRefMask; - - if ((current & kDyingBit) != 0 || - refs == 0 || - refs == kRefMask) - { - return false; - } - - if (m_state.compare_exchange_weak(current, current + 1)) - { - return true; - } - } - } - - ReleaseResult Release() noexcept - { - uint32_t current = m_state.load(); - - for (;;) - { - uint32_t refs = current & kRefMask; - - if (refs == 0) - { - std::terminate(); - } - - const bool startRundown = - refs == 1 && (current & kDyingBit) == 0; - - uint32_t desired = - (current & kDyingBit) | (refs - 1); - - if (startRundown) - { - desired |= kDyingBit; - } - - if (m_state.compare_exchange_weak(current, desired)) - { - return { refs - 1, startRundown }; - } - } - } - - bool IsDying() const noexcept - { - return (m_state.load() & kDyingBit) != 0; - } - - uint32_t RefCount() const noexcept - { - return m_state.load() & kRefMask; - } - -private: - static constexpr uint32_t kDyingBit = 0x80000000u; - static constexpr uint32_t kRefMask = 0x7FFFFFFFu; - - std::atomic m_state{ 0 }; -}; diff --git a/third_party/xtaskqueue/Source/Task/AsyncLib.cpp b/third_party/xtaskqueue/Source/Task/AsyncLib.cpp deleted file mode 100644 index c69866515..000000000 --- a/third_party/xtaskqueue/Source/Task/AsyncLib.cpp +++ /dev/null @@ -1,1185 +0,0 @@ -// Copyright (c) Microsoft Corporation -// Licensed under the MIT license. See LICENSE file in the project root for full license information. - -#include "pch.h" -#include "XTaskQueuePriv.h" -#include "SpinLock.h" - -#define ASYNC_BLOCK_SIG 0x41535942 // ASYB -#define ASYNC_BLOCK_RESULT_SIG 0x41535242 // ASRB -#define ASYNC_STATE_SIG 0x41535445 // ASTE - -// Used by unit tests to verify we cleanup memory correctly. -std::atomic s_AsyncLibGlobalStateCount{ 0 }; - -// Set externally to enable pumping waits. -bool s_AsyncLibEnablePumpingWait = false; - -enum class ProviderCleanupLocation -{ - Destructor, // Cleanup provider in destructor - AfterDoWork, // Cleanup provider after DoWork - InCancel, // XAsyncCancel code is calling into provider - CleanedUp // Provider clean up has been called -}; - -// Note that there are two XAsyncBlock structures in play. -// There is the pointer allocated and passed to us by the user -// and there is our own local copy. We pass the local copy to -// async provider callbacks, and pass the user pointer to all -// user-visible callbacks. The AsyncBlockInternalGuard class keeps -// the state of these two classes in sync under a lock. This allows -// us to provide our own local task queue for use by the provider -// without the confusion of offering two queue pointers or modifying -// a structure the user passed to us. - -struct AsyncState -{ - uint32_t signature = ASYNC_STATE_SIG; - std::atomic refs{ 1 }; - std::atomic providerCleanup{ ProviderCleanupLocation::Destructor }; - std::atomic workScheduled{ false }; - bool valid = true; - XAsyncProvider* provider = nullptr; - XAsyncProviderData providerData{ }; - XAsyncBlock providerAsyncBlock { }; - XAsyncBlock* userAsyncBlock = nullptr; - XTaskQueueHandle queue = nullptr; - DefaultUnnamedMutex waitMutex; - DefaultUnnamedConditionVariable waitCondition; - bool waitSatisfied = false; - -#if _WIN32 - HANDLE waitEvent = nullptr; -#endif - - const void* identity = nullptr; - const char* identityName = nullptr; - - void* operator new(size_t size, size_t additional, const std::nothrow_t& tag) - { - return ::operator new(size + additional, tag); - } - - void operator delete(void* ptr) - { - ::operator delete(ptr); - } - - AsyncState() noexcept - { - ++s_AsyncLibGlobalStateCount; - } - - void AddRef() noexcept - { - ++refs; - } - - void Release() noexcept - { - if (--refs == 0) - { - delete this; - } - } - -private: - - ~AsyncState() noexcept - { - if (provider != nullptr) - { - // Have we already called cleanup? - ProviderCleanupLocation loc = providerCleanup.exchange(ProviderCleanupLocation::CleanedUp); - if (loc != ProviderCleanupLocation::CleanedUp) - { - (void)provider(XAsyncOp::Cleanup, &providerData); - } - } - - if (queue != nullptr) - { - XTaskQueueCloseHandle(queue); - } - -#if _WIN32 - if (waitEvent != nullptr) - { - CloseHandle(waitEvent); - } -#endif - - --s_AsyncLibGlobalStateCount; - } -}; - -struct AsyncBlockInternal -{ - AsyncState* state = nullptr; - HRESULT status = E_PENDING; - // Completer publishes the dead value (release) as its last write; DoLock's - // fast path acquire-loads it, so observing it means the block is done. - std::atomic signature{ ASYNC_BLOCK_SIG }; - std::atomic_flag lock = ATOMIC_FLAG_INIT; -}; -static_assert(sizeof(AsyncBlockInternal) <= sizeof(XAsyncBlock::internal), - "Unexpected size for AsyncBlockInternal"); -static_assert(std::alignment_of::value == std::alignment_of::value, - "Unexpected alignment for AsyncBlockInternal"); -static_assert(std::is_trivially_destructible::value, - "Unexpected nontrivial destructor for AsyncBlockInternal"); - -class AsyncStateRef -{ -public: - AsyncStateRef() noexcept - : m_state{ nullptr } - {} - explicit AsyncStateRef(AsyncState* state) noexcept - : m_state{ state } - { - if (m_state) - { - m_state->AddRef(); - } - } - AsyncStateRef(const AsyncStateRef&) = delete; - AsyncStateRef(AsyncStateRef&& other) noexcept - : m_state{ other.m_state } - { - other.m_state = nullptr; - } - AsyncStateRef& operator=(const AsyncStateRef&) = delete; - AsyncStateRef& operator=(AsyncStateRef&& other) noexcept - { - if (&other != this) { std::swap(m_state, other.m_state); } - return *this; - } - ~AsyncStateRef() noexcept - { - if (m_state) - { - m_state->Release(); - } - } - AsyncState* operator->() const noexcept - { - return m_state; - } - bool operator==(std::nullptr_t) const noexcept - { - return m_state == nullptr; - } - bool operator!=(std::nullptr_t) const noexcept - { - return m_state != nullptr; - } - void Attach(AsyncState* state) noexcept - { - ASSERT(!m_state); - m_state = state; - } - AsyncState* Detach() noexcept - { - AsyncState* p = m_state; - m_state = nullptr; - return p; - } - - AsyncState* Get() const { return m_state; } - -private: - AsyncState* m_state; -}; - -class AsyncBlockInternalGuard -{ -public: - AsyncBlockInternalGuard(_Inout_ XAsyncBlock* asyncBlock) noexcept : - m_internal(DoLock(asyncBlock)) - { - m_locked = m_internal != nullptr; - - if (!m_locked) - { - // We never locked because the block contains an invalid signature. We still - // need the block for access though (although that access will be read only). - m_internal = reinterpret_cast(asyncBlock->internal); - } - - if (m_internal->state != nullptr) - { - m_userInternal = reinterpret_cast(m_internal->state->userAsyncBlock->internal); - } - else - { - m_userInternal = m_internal; - } - - // If user internal != internal, we grab its lock. Note that - // lock ordering here is critical. It must always be - // state lock, then user lock. If state is not available, then - // it is just user lock. - - if (m_userInternal != m_internal) - { - SpinLock::Lock(m_userInternal->lock); - } - } - - ~AsyncBlockInternalGuard() noexcept - { - if (m_locked) - { - m_internal->lock.clear(); - if (m_userInternal != m_internal) - { - m_userInternal->lock.clear(); - } - - // Publish the dead signature LAST (after lock release) so it is our - // final store; a reader observing it knows the block is untouched after. - if (m_publishDeadSignature) - { - m_internal->signature.store(m_deadSignature, std::memory_order_release); - if (m_userInternal != m_internal) - { - m_userInternal->signature.store(m_deadSignature, std::memory_order_release); - } - } - } - } - - AsyncStateRef GetState() const noexcept - { - AsyncStateRef state{ m_internal->state }; - - if (state != nullptr && state->signature != ASYNC_STATE_SIG) - { - ASSERT(false); - return AsyncStateRef{}; - } - - return state; - } - - AsyncStateRef ExtractState(_In_ bool resultsRetrieved = false) noexcept - { - AsyncStateRef state{ m_internal->state }; - m_internal->state = nullptr; - m_userInternal->state = nullptr; - - // Defer the dead signature so it can't be seen while writes are pending; the - // destructor publishes it last. resultsRetrieved marks it to block re-get. - m_deadSignature = resultsRetrieved ? ASYNC_BLOCK_RESULT_SIG : 0u; - m_publishDeadSignature = true; - - if (state != nullptr && state->signature != ASYNC_STATE_SIG) - { - ASSERT(false); - return AsyncStateRef{}; - } - - return state; - } - - HRESULT GetStatus() const noexcept - { - return m_internal->status; - } - - bool GetResultsRetrieved() - { - return m_internal->signature.load(std::memory_order_acquire) == ASYNC_BLOCK_RESULT_SIG; - } - - bool TrySetTerminalStatus(HRESULT status) noexcept - { - ASSERT(m_locked || m_internal->status != E_PENDING); - if (m_locked && m_internal->status == E_PENDING) - { - ASSERT(m_userInternal->status == E_PENDING); - m_userInternal->status = status; - m_internal->status = status; - - return true; - } - else - { - return false; - } - } - -private: - AsyncBlockInternal * m_internal; - AsyncBlockInternal * m_userInternal; - bool m_locked = false; - - // ExtractState defers the dead signature so the destructor makes it the - // final store to the block (see ExtractState / ~AsyncBlockInternalGuard). - bool m_publishDeadSignature = false; - uint32_t m_deadSignature = 0; - - // Locks the correct async block and returns a pointer to the one - // we locked. - static AsyncBlockInternal* DoLock(_In_ XAsyncBlock* asyncBlock) - { - AsyncBlockInternal* lockedResult = reinterpret_cast(asyncBlock->internal); - - ASSERT(lockedResult); - - for (;;) - { - // If the signature of this block is wrong, that means that it's not currently - // in play. We can't lock because the lock flag could be invalid, and we can't - // fix up the lock flag without introducing a race condition with other potential - // lock calls. All calls further down guard against an invalid state, so all - // we do in this case is set the state to null. We return null as an indicator - // that we didn't lock. - // - // Acquire pairs with the completer's release store of the dead signature - // (~AsyncBlockInternalGuard): a non-live signature means it is done. - - if (lockedResult->signature.load(std::memory_order_acquire) != ASYNC_BLOCK_SIG) - { - lockedResult->state = nullptr; - return nullptr; - } - - SpinLock::Lock(lockedResult->lock); - - // We've locked the async block. We only ever want to keep a lock on one block - // to prevent deadlocks caused by lock ordering. If the state is still valid - // on this block, we ensure the async block we're locking is the permanent one - // associated with the async state. - - if (lockedResult->state != nullptr && asyncBlock != &lockedResult->state->providerAsyncBlock) - { - // Grab a state ref here because releasing the lock can allow - // the state to be cleared / released. - AsyncStateRef state(lockedResult->state); - lockedResult->lock.clear(); - - // Now lock the async block on the state struct - AsyncBlockInternal* stateAsyncBlockInternal = reinterpret_cast(state->providerAsyncBlock.internal); - SpinLock::Lock(stateAsyncBlockInternal->lock); - - // We locked the right object, but we need to check here to see if we - // lost the state after clearing the lock above. If we did, then this - // pointer is likely going to destruct as soon as we release - // our state ref. We should throw it away and grab the user block - // again. - - if (stateAsyncBlockInternal->state == nullptr) - { - stateAsyncBlockInternal->lock.clear(); - SpinLock::Lock(lockedResult->lock); - } - else - { - lockedResult = stateAsyncBlockInternal; - } - } - - // Completion in flight: locked with state extracted but dead signature not - // yet published. Wait for it so a waiter can't free the block early, then retry. - - if (lockedResult->state == nullptr) - { - lockedResult->lock.clear(); - - while (lockedResult->signature.load(std::memory_order_acquire) == ASYNC_BLOCK_SIG) - { - std::this_thread::yield(); - } - - lockedResult = reinterpret_cast(asyncBlock->internal); - continue; - } - - return lockedResult; - } - } -}; - -static void CALLBACK CompletionCallback(_In_ void* context, _In_ bool canceled); -static void CALLBACK WorkerCallback(_In_ void* context, _In_ bool canceled); -static void SignalWait(_In_ AsyncStateRef const& state); -static HRESULT SignalCompletion(_In_ AsyncStateRef const& state); -static HRESULT AllocStateNoCompletion(_Inout_ XAsyncBlock* asyncBlock, _Inout_ AsyncBlockInternal* internal, _In_ size_t contextSize); -static HRESULT AllocState(_Inout_ XAsyncBlock* asyncBlock, _In_ size_t contextSize); -static void CleanupState(_Inout_ AsyncStateRef&& state); -static void CleanupProviderForLocation(_Inout_ AsyncStateRef& state, _In_ ProviderCleanupLocation location); -static bool TrySetProviderCleanup(_Inout_ AsyncStateRef& state, _In_ ProviderCleanupLocation location); -static void RevertProviderCleanup(_Inout_ AsyncStateRef& state, _In_ ProviderCleanupLocation expected); - -static HRESULT AllocStateNoCompletion(_Inout_ XAsyncBlock* asyncBlock, _Inout_ AsyncBlockInternal* internal, _In_ size_t contextSize) -{ - AsyncStateRef state; - state.Attach(new (contextSize, std::nothrow) AsyncState); - RETURN_IF_NULL_ALLOC(state); - - if (contextSize != 0) - { - // User allocated additional context data. This was allocated as extra bytes at the end of - // async state. - state->providerData.context = (state.Get() + 1); - } - - // Addref the task queue. We duplicate with "Reference" to prevent spamming - // the handle tracker with each async call (and to prevent a needless allocation of - // the task queue handle wrapper). - - XTaskQueueHandle queue = asyncBlock->queue; - if (queue == nullptr) - { - RETURN_HR_IF(E_NO_TASK_QUEUE, XTaskQueueGetCurrentProcessTaskQueueWithOptions( - XTaskQueueDuplicateOptions::Reference, - &state->queue) == false); - } - else - { - RETURN_IF_FAILED(XTaskQueueDuplicateHandleWithOptions( - queue, - XTaskQueueDuplicateOptions::Reference, - &state->queue)); - } - - state->userAsyncBlock = asyncBlock; - state->providerData.async = &state->providerAsyncBlock; - -#if _WIN32 - state->waitEvent = CreateEvent(nullptr, TRUE, FALSE, nullptr); - RETURN_LAST_ERROR_IF(state->waitEvent == nullptr); -#endif - - // Note: needs to be the last failable thing we do. - RETURN_IF_FAILED(XTaskQueueSuspendTermination(state->queue)); - - internal->state = state.Detach(); - - // Duplicate the async block we've just configured - internal->state->providerAsyncBlock = *asyncBlock; - internal->state->providerAsyncBlock.queue = internal->state->queue; - - return S_OK; -} - -static HRESULT AllocState(_Inout_ XAsyncBlock* asyncBlock, _In_ size_t contextSize) -{ - // If the async block is already associated with another - // call, fail. - - // We need to guard against use of an active async block. We don't want - // to rely on the caller zeroing memory so we check a signature - // DWORD. This signature is cleared when the block can be reused. - auto internal = reinterpret_cast(asyncBlock->internal); - if (internal->signature.load(std::memory_order_acquire) == ASYNC_BLOCK_SIG) - { - RETURN_HR(E_INVALIDARG); - } - - // This could be a reused async block from a prior - // call, so zero everything. - for (auto i = 0u; i < sizeof(asyncBlock->internal); ++i) - { - asyncBlock->internal[i] = 0; - } - - // Construction is inherently single threaded - // (there is nothing we can do if the client tries to use the same - // XAsyncBlock in 2 calls at the same time) - internal = new (asyncBlock->internal) AsyncBlockInternal{}; - - HRESULT hr = AllocStateNoCompletion(asyncBlock, internal, contextSize); - - if (FAILED(hr)) - { - internal->signature.store(0, std::memory_order_release); - internal->status = hr; - } - - RETURN_IF_FAILED(hr); - return S_OK; -} - -static void CleanupState(_Inout_ AsyncStateRef&& state) -{ - if (state != nullptr) - { - // Should only cleanup state after calling ExtractState to clear it. - ASSERT((reinterpret_cast(state->providerData.async->internal))->state == nullptr); - - state->valid = false; - state->Release(); - } -} - -static void CleanupProviderForLocation(_Inout_ AsyncStateRef& state, _In_ ProviderCleanupLocation location) -{ - if (state->providerCleanup.compare_exchange_strong(location, ProviderCleanupLocation::CleanedUp)) - { - (void)state->provider(XAsyncOp::Cleanup, &state->providerData); - } -} - -static bool TrySetProviderCleanup(_Inout_ AsyncStateRef& state, _In_ ProviderCleanupLocation location) -{ - ProviderCleanupLocation expected = ProviderCleanupLocation::Destructor; - return state->providerCleanup.compare_exchange_strong(expected, location); -} - -static void RevertProviderCleanup(_Inout_ AsyncStateRef& state, _In_ ProviderCleanupLocation expected) -{ - (void)state->providerCleanup.compare_exchange_strong(expected, ProviderCleanupLocation::Destructor); -} - -static HRESULT SignalCompletion(_In_ AsyncStateRef const& state) -{ - HRESULT hr = S_OK; - - if (state->providerData.async->callback != nullptr) - { - AsyncStateRef callbackState(state.Get()); - hr = XTaskQueueSubmitCallback( - state->queue, - XTaskQueuePort::Completion, - callbackState.Get(), - CompletionCallback); - - if (SUCCEEDED(hr)) - { - callbackState.Detach(); - } - } - else - { - SignalWait(state); - } - - return hr; -} - -static void SignalWait(_In_ AsyncStateRef const& state) -{ - bool newlySatisfied; - { - std::lock_guard lock(state->waitMutex); - newlySatisfied = !state->waitSatisfied; - state->waitSatisfied = true; - state->waitCondition.notify_all(); - } -#if _WIN32 - SetEvent(state->waitEvent); -#endif - - // We should only come in here once, but we don't want - // to underflow task queue resumes and we already know - // from above if we're first marking this wait as - // satisfied, so use it. - - ASSERT(newlySatisfied); - if (newlySatisfied) - { - XTaskQueueResumeTermination(state->queue); - } -} - -static void CALLBACK CompletionCallback( - _In_ void* context, - _In_ bool canceled) -{ - // We must still let canceled callbacks through to clean - // up user data. - UNREFERENCED_PARAMETER(canceled); - - AsyncStateRef state; - state.Attach(static_cast(context)); - - // We always pass the user async block into the - // callback, but we don't trust it -- we check - // the callback field on our internal copy. - XAsyncBlock* asyncBlock = state->userAsyncBlock; - if (state->providerAsyncBlock.callback != nullptr) - { - state->providerAsyncBlock.callback(asyncBlock); - } - - SignalWait(state); -} - -static void CALLBACK WorkerCallback( - _In_ void* context, - _In_ bool canceled) -{ - AsyncStateRef state; - state.Attach(static_cast(context)); - state->workScheduled = false; - - if (!state->valid) - { - return; - } - - // If the queue is canceling callbacks, simply cancel this work. Since no - // new work for this call will be scheduled, if the call didn't cancel - // immediately do it ourselves. - - if (canceled) - { - XAsyncCancel(state->userAsyncBlock); - HRESULT callStatus; - { - AsyncBlockInternalGuard internal{ state->userAsyncBlock }; - callStatus = internal.GetStatus(); - } - - if (callStatus != E_ABORT) - { - XAsyncComplete(state->userAsyncBlock, E_ABORT, 0); - } - } - else - { - HRESULT result = state->provider(XAsyncOp::DoWork, &state->providerData); - - // Work routine can return E_PENDING if there is more work to do. Otherwise - // it either needs to be a failure or it should have called XAsyncComplete, which - // would have set a new value into the status. - - if (result != E_PENDING) - { - if (SUCCEEDED(result)) - { - result = E_UNEXPECTED; - } - - XAsyncComplete(&state->providerAsyncBlock, result, 0); - } - } - - // If the result of this call caused a completion with no payload, XAsyncComplete - // will change the provider cleanup to be "AfterWork", which is here. Cleanup - // the provider if we need to. - CleanupProviderForLocation(state, ProviderCleanupLocation::AfterDoWork); -} - -// -// Public APIs -// - -/// -/// Returns the status of the asynchronous operation, optionally waiting -/// for it to complete. Once complete, you may call XAsyncGetResult if -/// the async call has a resulting data payload. If it doesn't, calling -/// XAsyncGetResult is unneeded. -/// -STDAPI XAsyncGetStatus( - _Inout_ XAsyncBlock* asyncBlock, - _In_ bool wait - ) noexcept -{ - HRESULT result = E_PENDING; - AsyncStateRef state; - { - AsyncBlockInternalGuard internal{ asyncBlock }; - result = internal.GetStatus(); - state = internal.GetState(); - } - - // If we are being asked to wait, always check the wait state before - // looking at the hresult. Our wait waits until the completion runs - // so we may need to wait past when the status is set. - - if (wait) - { - if (state == nullptr) - { - ASSERT(result != E_PENDING); - RETURN_HR_IF(E_INVALIDARG, result == E_PENDING); - } - else - { -// This codebase compiles for multiple platforms on GitHub. This is only -// supported on win32 desktop platforms. It is enabled for Windows builds. -#if _WIN32 -#if WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_DESKTOP) - - // If we're being asked to wait from a STA thread, use a CoWait to ensure we - // don't totally gum up the thread. Then fall back to our normal condition - // variable check (both are signaled during completion). - - if (s_AsyncLibEnablePumpingWait) - { - APTTYPE aptType; - APTTYPEQUALIFIER aptQualifier; - if (SUCCEEDED(CoGetApartmentType(&aptType, &aptQualifier)) && aptType != APTTYPE_MTA && aptType != APTTYPE_NA) - { - DWORD idx; - (void)CoWaitForMultipleHandles(COWAIT_DEFAULT, INFINITE, 1, &state->waitEvent, &idx); - } - } -#endif -#endif - { - std::unique_lock lock(state->waitMutex); - - if (!state->waitSatisfied) - { - AsyncState* s = state.Get(); - state->waitCondition.wait(lock, [s] { return s->waitSatisfied; }); - } - } - - { - AsyncBlockInternalGuard internal{ asyncBlock }; - result = internal.GetStatus(); - } - } - } - - return result; -} - -/// -/// Returns the required size of the buffer to pass to XAsyncGetResult. -/// -STDAPI XAsyncGetResultSize( - _Inout_ XAsyncBlock* asyncBlock, - _Out_ size_t* bufferSize - ) noexcept -{ - HRESULT result = E_PENDING; - AsyncStateRef state; - { - AsyncBlockInternalGuard internal{ asyncBlock }; - result = internal.GetStatus(); - state = internal.GetState(); - } - - *bufferSize = state == nullptr ? 0 : state->providerData.bufferSize; - - return result; -} - -/// -/// Tries to cancel an asynchronous operation. If canceled the status result will return E_ABORT -/// and the completion callback will be invoked. -/// -STDAPI_(void) XAsyncCancel( - _Inout_ XAsyncBlock* asyncBlock - ) noexcept -{ - AsyncStateRef state; - { - AsyncBlockInternalGuard internal{ asyncBlock }; - state = internal.GetState(); - } - - if (state != nullptr) - { - // In case of cancel, failure, or success with no payload we will - // agressively clean up the provider at the end of DoWork. This can race - // with a cancel call. To prevent this we mark the provider cleanup as - // "in cancel", which prevents switching it to the aggressive DoWork - // cleanup. We switch out of "in cancel" when done. In the worst case this - // will defer provider cleanup to the state destructor, which is the natural - // place for it anyway. Anything else here is just an optimization to get the - // provider cleaned up sooner (the destructor location may be delayed until the - // completion callback fires, since it's hanging on to a state object ref). - - if (TrySetProviderCleanup(state, ProviderCleanupLocation::InCancel)) - { - (void)state->provider(XAsyncOp::Cancel, &state->providerData); - RevertProviderCleanup(state, ProviderCleanupLocation::InCancel); - } - } -} - -/// -/// Runs the given callback asynchronously. -/// -STDAPI XAsyncRun( - _Inout_ XAsyncBlock* asyncBlock, - _In_ XAsyncWork* work - ) noexcept -{ - RETURN_IF_FAILED(XAsyncBegin( - asyncBlock, - reinterpret_cast(work), - reinterpret_cast(XAsyncRun), - __FUNCTION__, - [](XAsyncOp op, const XAsyncProviderData* data) - { - switch (op) - { - case XAsyncOp::Begin: - return XAsyncSchedule(data->async, 0); - - case XAsyncOp::DoWork: - { - XAsyncWork* work = reinterpret_cast(data->context); - HRESULT hr = work(data->async); - XAsyncComplete(data->async, hr, 0); - } - break; - - case XAsyncOp::Cancel: - case XAsyncOp::Cleanup: - case XAsyncOp::GetResult: - break; - - } - - return S_OK; - })); - - return S_OK; -} - -// -// XAsyncProvider APIs -// - -/// -/// Initializes an async block for use. Once begun calls such -/// as XAsyncGetStatus will provide meaningful data. It is assumed the -/// async work will begin on some system defined thread after this call -/// returns. -/// -STDAPI XAsyncBegin( - _Inout_ XAsyncBlock* asyncBlock, - _In_opt_ void* context, - _In_opt_ const void* identity, - _In_opt_ const char* identityName, - _In_ XAsyncProvider* provider - ) noexcept -{ - RETURN_IF_FAILED(AllocState(asyncBlock, 0)); - - AsyncStateRef state; - { - AsyncBlockInternalGuard internal{ asyncBlock }; - state = internal.GetState(); - } - - state->provider = provider; - state->providerData.context = context; - state->identity = identity; - state->identityName = identityName; - - // We've successfully setup the call. Now kick off a - // Begin opcode. If this call fails, we use it to fail - // the async call, instead of failing XAsyncBegin. This is - // necessary to ensure that the async call state is properly - // cleaned up, both for us and for the user call. - - HRESULT hr = provider(XAsyncOp::Begin, &state->providerData); - if (FAILED(hr)) - { - XAsyncComplete(asyncBlock, hr, 0); - } - - return S_OK; -} - -/// -/// Initializes an async block for use. Once begun calls such -/// as XAsyncGetStatus will provide meaningful data. It is assumed the -/// async work will begin on some system defined thread after this call -/// returns. The token and function parameters can be used to help identify -/// mismatched Begin/GetResult calls. The token is typically the function -/// pointer of the async API you are implementing, and the functionName parameter -/// is typically the __FUNCTION__ compiler macro. -/// -/// This variant of XAsyncBegin will allocate additional memory of size contextSize -/// and use this as the context pointer for async provider callbacks. The memory -/// pointer is returned in 'context'. The lifetime of this memory is managed -/// by the async library and will be freed automatically when the call -/// completes. -/// -STDAPI XAsyncBeginAlloc( - _Inout_ XAsyncBlock* asyncBlock, - _In_opt_ const void* identity, - _In_opt_ const char* identityName, - _In_ XAsyncProvider* provider, - _In_ size_t contextSize, - _In_ size_t parameterBlockSize, - _In_opt_ void* parameterBlock - ) noexcept -{ - RETURN_HR_IF(E_INVALIDARG, contextSize == 0); - - if (parameterBlockSize != 0) - { - RETURN_HR_IF(E_INVALIDARG, parameterBlock == nullptr || parameterBlockSize > contextSize); - } - else - { - RETURN_HR_IF(E_INVALIDARG, parameterBlock != nullptr); - } - - RETURN_IF_FAILED(AllocState(asyncBlock, contextSize)); - - AsyncStateRef state; - { - AsyncBlockInternalGuard internal{ asyncBlock }; - state = internal.GetState(); - } - - // Alloc using a context size should always fail and not - // try to send a completion. - ASSERT(state != nullptr); - - state->provider = provider; - state->identity = identity; - state->identityName = identityName; - - ASSERT(state->providerData.context != nullptr); - memset(state->providerData.context, 0, contextSize); - - if (parameterBlockSize != 0) - { - memcpy(state->providerData.context, parameterBlock, parameterBlockSize); - } - - // We've successfully setup the call. Now kick off a - // Begin opcode. If this call fails, we use it to fail - // the async call, instead of failing XAsyncBegin. This is - // necessary to ensure that the async call state is properly - // cleaned up, both for us and for the user call. - - HRESULT hr = provider(XAsyncOp::Begin, &state->providerData); - - if (FAILED(hr)) - { - XAsyncComplete(asyncBlock, hr, 0); - } - - return S_OK; -} - -/// -/// Schedules a callback to do async work. Calling this is optional. If the async work can be done -/// through a system - async mechanism like overlapped IO or async COM, there is no need to schedule -/// work. If work should be scheduled after a delay, pass the number of ms XAsyncSchedule should wait -/// before it schedules work. -/// -STDAPI XAsyncSchedule( - _Inout_ XAsyncBlock* asyncBlock, - _In_ uint32_t delayInMs - ) noexcept -{ - HRESULT existingStatus; - AsyncStateRef state; - { - AsyncBlockInternalGuard internal{ asyncBlock }; - state = internal.GetState(); - existingStatus = internal.GetStatus(); - } - - // If the call already failed, return that failure code. - RETURN_HR_IF(existingStatus, FAILED(existingStatus) && existingStatus != E_PENDING); - - // If the call has completed, the state will be null. - RETURN_HR_IF(E_INVALIDARG, state == nullptr); - - bool priorScheduled = false; - state->workScheduled.compare_exchange_strong(priorScheduled, true); - - if (priorScheduled) - { - RETURN_HR(E_UNEXPECTED); - } - - RETURN_IF_FAILED(XTaskQueueSubmitDelayedCallback( - state->queue, - XTaskQueuePort::Work, - delayInMs, - state.Get(), - WorkerCallback)); - - // NOTE: The callback now owns the state ref. It could have run - // already, and state may be holding a dead pointer. Regardless, - // state should be detached here as it no longer owns - // the ref. - state.Detach(); - return S_OK; -} - -/// -/// Called when async work is completed and the results can be returned. -/// The caller should supply the resulting data payload size. If the call -/// has no data payload, pass zero. -/// providerData.bufferSize = requiredBufferSize; - } - } - - // Only signal / adjust needed buffer size if we were first to complete. - if (completedNow) - { - FAIL_FAST_IF_FAILED(SignalCompletion(state)); - } - - // At this point asyncBlock may be unsafe to touch. As we've cleaned up - // state we will mark the state so that the DoWork callback calls - // the Cleanup op on the provider. This gets it cleaned up sooner - // so it doesn't have to wait for the task queue to process it. - - if (doCleanup) - { - (void)TrySetProviderCleanup(state, ProviderCleanupLocation::AfterDoWork); - CleanupState(std::move(state)); - } -} - -/// -/// Returns the result data for the asynchronous operation. After this call -/// the async block is completed and no longer associated with the -/// operation. -/// -STDAPI XAsyncGetResult( - _Inout_ XAsyncBlock* asyncBlock, - _In_opt_ const void* identity, - _In_ size_t bufferSize, - _Out_writes_bytes_to_opt_(bufferSize, *bufferUsed) void* buffer, - _Out_opt_ size_t* bufferUsed - ) noexcept -{ - HRESULT result = E_PENDING; - AsyncStateRef state; - bool resultsAlreadyReturned; - - { - AsyncBlockInternalGuard internal{ asyncBlock }; - result = internal.GetStatus(); - state = internal.GetState(); - resultsAlreadyReturned = internal.GetResultsRetrieved(); - } - - if (SUCCEEDED(result)) - { - // If the call was successful and we've already returned - // results, fail now to prevent us interpreting a null - // state object as a zero payload success. Note if the - // call had completed with zero payload it gets cleaned - // up immediately and therefore a call to XAsyncGetResult - // never extracts and sets the results as retrieved. This - // means you can safely call this multiple times for calls - // that had no result payload, which is consistent with - // how XAsyncGetStatus works. We only want to guard against - // the case where results were offered once, but can't be - // offered again now that we've shut the call down. - - RETURN_HR_IF(E_ILLEGAL_METHOD_CALL, resultsAlreadyReturned); - - if (state == nullptr) - { - if (bufferUsed != nullptr) - { - *bufferUsed = 0; - } - } - else if (identity != state->identity) - { - // Call/Result mismatch. This XAsyncBlock was initiated by state->identityName - char buf[100]; - int sprintfResult; - if (state->identityName != nullptr) - { - sprintfResult = snprintf( - buf, - sizeof(buf), - "Call/Result mismatch. This XAsyncBlock was initiated by '%s'.\r\n", - state->identityName); - } - else - { - sprintfResult = snprintf(buf, sizeof(buf), "Call/Result mismatch\r\n"); - } - - result = E_INVALIDARG; - ASYNC_LIB_TRACE(result, buf); - ASSERT(false); - ASSERT(sprintfResult > 0); - } - else if (state->providerData.bufferSize == 0) - { - // Caller has not supplied a payload - result = E_NOT_SUPPORTED; - } - else if (buffer == nullptr) - { - result = E_INVALIDARG; - } - else if (bufferSize < state->providerData.bufferSize) - { - result = E_NOT_SUFFICIENT_BUFFER; - } - else - { - if (bufferUsed != nullptr) - { - *bufferUsed = state->providerData.bufferSize; - } - - state->providerData.bufferSize = bufferSize; - state->providerData.buffer = buffer; - result = state->provider(XAsyncOp::GetResult, &state->providerData); - } - } - - // Cleanup state if needed. - if (result != E_PENDING && state != nullptr) - { - { - AsyncBlockInternalGuard internal{ asyncBlock }; - internal.ExtractState(true); - } - - CleanupState(std::move(state)); - } - - return result; -} diff --git a/third_party/xtaskqueue/Source/Task/AtomicVector.h b/third_party/xtaskqueue/Source/Task/AtomicVector.h deleted file mode 100644 index 3227ff755..000000000 --- a/third_party/xtaskqueue/Source/Task/AtomicVector.h +++ /dev/null @@ -1,100 +0,0 @@ - -// Copyright (c) Microsoft Corporation -// Licensed under the MIT license. See LICENSE file in the project root for full license information. - -#pragma once - -// A wrapper around a vector that allows lock-free enumeration of the -// contents. Add/Remove requires a lock. -template -class AtomicVector -{ -public: - - template - HRESULT Add(_In_ TArg&& value) try - { - std::lock_guard lock(m_lock); - uint32_t bufferReadIdx = (m_indexAndRef & 0x80000000 ? 1 : 0); - uint32_t bufferWriteIdx = 1 - bufferReadIdx; - - m_buffers[bufferWriteIdx] = m_buffers[bufferReadIdx]; - m_buffers[bufferWriteIdx].push_back(std::forward(value)); - - // Now spin wait to swap the active buffer. - uint32_t expected = bufferReadIdx << 31; - uint32_t desired = bufferWriteIdx << 31; - - for (;;) - { - uint32_t expectedSwap = expected; - if (m_indexAndRef.compare_exchange_weak(expectedSwap, desired)) - { - break; - } - } - - // Now that the read buffer is not being used we can free - // up its contents. - m_buffers[bufferReadIdx].clear(); - m_buffers[bufferReadIdx].shrink_to_fit(); - - return S_OK; - } CATCH_RETURN(); - - template - void Remove(_In_ Func predicate) - { - std::lock_guard lock(m_lock); - uint32_t bufferReadIdx = (m_indexAndRef & 0x80000000 ? 1 : 0); - uint32_t bufferWriteIdx = 1 - bufferReadIdx; - - m_buffers[bufferWriteIdx] = m_buffers[bufferReadIdx]; - - auto &buffer = m_buffers[bufferWriteIdx]; - auto it = std::find_if(buffer.begin(), buffer.end(), predicate); - - if (it != buffer.end()) - { - buffer.erase(it); - } - - // Now spin wait to swap the active buffer. - uint32_t expected = bufferReadIdx << 31; - uint32_t desired = bufferWriteIdx << 31; - - for (;;) - { - uint32_t expectedSwap = expected; - if (m_indexAndRef.compare_exchange_weak(expectedSwap, desired)) - { - break; - } - } - - // Now that the read buffer is not being used we can free - // up its contents. - m_buffers[bufferReadIdx].clear(); - m_buffers[bufferReadIdx].shrink_to_fit(); - } - - template - void Visit(_In_ Func callback) - { - uint32_t indexAndRef = ++m_indexAndRef; - uint32_t bufferIdx = (indexAndRef & 0x80000000 ? 1 : 0); - - for (auto const &it : m_buffers[bufferIdx]) - { - callback(it); - } - - m_indexAndRef--; - } - -private: - - DefaultUnnamedMutex m_lock; - std::vector m_buffers[2]; - std::atomic m_indexAndRef { 0 }; -}; diff --git a/third_party/xtaskqueue/Source/Task/LocklessQueue.h b/third_party/xtaskqueue/Source/Task/LocklessQueue.h deleted file mode 100644 index 5b71bcc43..000000000 --- a/third_party/xtaskqueue/Source/Task/LocklessQueue.h +++ /dev/null @@ -1,913 +0,0 @@ -// Copyright (c) Microsoft Corporation -// Licensed under the MIT license. See LICENSE file in the project root for full license information. - -#pragma once -#include -#include -#include -#include "SpinLock.h" - -/***************************************************************************** - - LocklessQueue is a lock free queue that can take any trivially copyable type as a - payload. Internally it maintains a demand-allocated block of contiguous nodes that - are used as the nodes of a linked list. Data pushed into the queue uses a - copy, and popping data copies that same data out to your variable. - - An initial block size is created up front and the size of the block can be customized - via the constructor. If the queue runs out of space, it can create new blocks. This process - is also lock / wait free, although it has an increassed "push" cost as the new block - is allocated and initialized. If there is not enough memory to create a new block - push_back returns false. - - N.B. LocklessQueue MUST be either dynamically allocated or stack allocated as a - local variable. It cannot be used as a member variable in a class or structure - due to alignment restrictions. It can fail spectacularly if not aligned correctly. - - Typical Usage: - - struct MyPayload - { - uint32_t someData; - // etc... - }; - - LocklessQueue queue; - - MyPayload p = new MyPayload; - p->someData = 16; - queue.push_back(p); - - if (queue.pop_front(p)) - { - printf("Value: %d\r\n", p->someData); - delete p; - } - - - LocklessQueue is based on the the algorithm described in this paper: - - Simple, Fast, and Practical Non-Blocking and Blocking Concurrent Queue Algorithms - - Maged M. Michael Michael L. Scott - Department of Computer Science University of Rochester Rochester, NY 14627-0226 fmichael,scottg@cs.rochester.ed - - http://cs.rochester.edu/~scott/papers/1996_PODC_queues.pdf - - In addition to the above algorithm this variant introduces a heap of nodes. This helps keep the memory - contiguous and allows for single 64 bit swaps on 64 bit machines (as we don't need to store pointers). - - ******************************************************************************/ - -#ifdef HC_UNITTEST_API -// Unit-test hook: invoked by push after it has found the list's tail node and -// verified that the tail's next field is the end marker, immediately before it -// links the new node with a compare-exchange on that field. Tests use it to park -// a pushing thread inside that window so they can force interleavings. -struct LocklessQueueTestHooks -{ - using BeforeTailLinkHook = void (*)(); - - static std::atomic& BeforeTailLink() noexcept - { - static std::atomic hook{ nullptr }; - return hook; - } -}; -#endif - -// LocklessQueue needs certain alignment. Disable alignment warning. -#pragma warning(push) -#pragma warning(disable: 4324) - -template -class alignas(8) LocklessQueue -{ -public: - - // - // Creates a new lockless queue. The blockSize parameter indicates how many - // node elements are contained in a block. Additional blocks will be allocated - // as needed but for best performance use a block size that does not require - // additional allocation for your work load. Passing zero will use the - // minimum size. - // - LocklessQueue(_In_ uint32_t blockSize = 0x400) noexcept : - m_localHeap(*this), - m_heap(m_localHeap), - m_activeList(*this), - m_blockCache(nullptr), - m_lock{} - { - m_localHeap.init(blockSize); - Initialize(); - } - - // - // Creates a new lockless queue. The shared parameter provides another - // lockless queue that provides the heap for nodes. Queues that - // share the same node heap can share addresses. When a lockless queue - // that is sharing another queue's nodes is destroyed, any outstanding - // nodes in use are given back to the heap of the shared queue. Destroying - // the host queue before destroying queues sharing its heap results in - // undefined behavior. - // - LocklessQueue(_In_ LocklessQueue& shared) noexcept : - m_localHeap(*this), - m_heap(shared.m_heap), - m_activeList(*this), - m_blockCache(nullptr), - m_lock{} - { - Initialize(); - } - - ~LocklessQueue() noexcept - { - if (&m_heap != &m_localHeap) - { - // This queue is sharing a heap, so - // we need to put all outstanding nodes - // back - TData data; - while(pop_front(data)) {} - - // And the dummy node too. - Address dummy = m_activeList.head(); - Node* node = to_node(dummy); - m_heap.free(node, dummy); - } - } - - // - // Returns true if the queue is empty. Note that - // since there are no locks this is a snapshot in time. - // - bool empty() noexcept - { - return m_activeList.empty(); - } - - // - // Reserves a link node in the queue, allocating it if - // necessary. The node must be used in a later push_back - // or free_node call or it will be leaked. - // - bool reserve_node(_Out_ uint64_t& address) noexcept - { - Address a; - Node* n = m_heap.alloc(a); - - if (n != nullptr) - { - address = a; - return true; - } - else - { - address = 0; - return false; - } - } - - // - // Frees a previously reserved node. Freeing a node - // that has been pushed results in undefined behavior. It - // will be hard to debug. - // - void free_node(_In_ uint64_t address) noexcept - { - Address a; - a = address; - Node* n = to_node(a); - m_heap.free(n, a); - } - - // - // Pushes the given data onto the back - // of the queue. A copy is made of TData - // (which may throw, if TData's copy constructor can - // throw exceptions). - // If the push fails this returns false. - // - bool push_back(_In_ const TData& data) - { - TData copy = data; - return move_back(std::move(copy)); - } - - // - // Pushes the given data onto the back - // of the queue. - // - bool push_back(_In_ TData&& data) noexcept - { - return move_back(std::move(data)); - } - - // - // Pushes the given data onto the back of the queue, - // using a reserved node pointer. This never fails as - // the node pointer was preallocated. A copy of TData is - // made (which may throw, if TData's copy constructor can - // throw exceptions). - // - void push_back(_In_ const TData& data, _In_ uint64_t address) - { - TData copy = data; - move_back(std::move(copy), address); - } - - // - // Pushes the given data onto the back of the queue, - // using a reserved node pointer. This never fails as - // the node pointer was preallocated. - // - void push_back(_In_ TData&& data, _In_ uint64_t address) noexcept - { - move_back(std::move(data), address); - } - - // - // Pops TData off the head of the queue, returning - // true if successful or false if the queue is - // empty. - // - bool pop_front(_Out_ TData& data) noexcept - { - Address address; - Node* node = m_activeList.pop(address); - - if (node != nullptr) - { - data = node->data.load(); - node->data.store(TData {}); - m_heap.free(node, address); - return true; - } - - return false; - } - - // - // Pops TData off the front of the queue, returning - // true if successful, and returns a node address - // instead of placing the address back on the free - // list. This address can later be used in a push_back - // call or a free_node call. Failing to call either of these - // results in a leaked node. Returns false if the queue - // is empty. - // - bool pop_front(_Out_ TData& data, _Out_ uint64_t& address) noexcept - { - Address a; - Node* node = m_activeList.pop(a); - - if (node != nullptr) - { - data = node->data.load(); - node->data.store(TData {}); - address = a; - return true; - } - - return false; - } - - // - // Removes items from the queue that satisfy the given callback. The callback - // is of the form: - // - // bool callback(TData& data, uint64_t address); - // - // If the callback returns true, it is taking ownership of the data and the - // address. If it returns false, the node is placed back on the queue. - // - // This call is not completely lock-free. It does not impact calls to - // push or pop items from the queue, but it does guard against multiple - // calls to remove_if with a spinlock. This guarantees that all calls to - // remove_if "see" all the nodes, but makes the call non-reentrant. Don't - // call remove_if from the callback or you will busy wait. - // - // If there are interleaving calls to push_back while this action is in - // progress final node order is not guaranteed (nodes this API processes - // may be interleaved with newly pushed nodes). - // - template - void remove_if(TCallback callback) - { - LocklessQueue retain(*this); - TData entry; - uint64_t address; - - SpinLock lock(m_lock); - - while (pop_front(entry, address)) - { - if (!callback(entry, address)) - { - retain.move_back(std::move(entry), address); - } - } - - while (retain.pop_front(entry, address)) - { - move_back(std::move(entry), address); - } - } - -private: - - /* - * - * Structure Definitions - * - */ - - // Address - This represents the address of a node. - // Nodes live in a contiguous memory block, and there are multiple - // blocks. Address represents the position of the - // node and must be 64 bits. - - struct Address - { - uint64_t index : 32; - uint64_t block : 16; - uint64_t aba : 16; - - inline bool operator == (_In_ const Address& other) const - { - uint64_t v = *this; - uint64_t ov = other; - return v == ov; - } - - inline bool operator != (_In_ const Address& other) const - { - uint64_t v = *this; - uint64_t ov = other; - return v != ov; - } - - inline operator uint64_t () const - { - uint64_t v; - - // Note: this looks horribly inefficient. General consensus - // is this is the best way of doing type punning in a c++ compliant - // way, and disassembly of this code shows it amounts to the following: - // - // mov rax, QWORD PTR [rdx] - // - // So, no real call out to memcpy for retail. - - memcpy(&v, this, sizeof(v)); - return v; - } - - inline Address& operator = (_In_ uint64_t v) - { - memcpy(this, &v, sizeof(v)); - return *this; - } - }; - - static_assert(sizeof(Address) == sizeof(uint64_t), "LocklessQueue Address field must be 64 bits exactly"); - -#if _MSVC_LANG >= 201703L - static_assert(std::atomic
::is_always_lock_free, "LocklessQueue requires atomic
to be lock free"); -#endif - - // Payload - the TData stored in a node, held as an array of atomic words. - // List::pop copies a node's payload before it knows whether its head - // compare-exchange will succeed, and a stale popper can read a node that - // another thread has already popped and is overwriting or reusing. The value - // read in that case is discarded, but plain (non-atomic) accesses would still - // be a data race (#1072). Relaxed atomics make those accesses well defined; - // ordering comes from the atomic next/head/tail links, as before. - class Payload - { - public: - static_assert(std::is_trivially_copyable::value, "LocklessQueue payloads must be trivially copyable"); - - Payload() noexcept - { - for (auto& word : m_words) - { - word.store(0, std::memory_order_relaxed); - } - } - - Payload(const Payload&) = delete; - Payload& operator=(const Payload&) = delete; - - TData load() const noexcept - { - uintptr_t words[c_wordCount]; - for (size_t i = 0; i < c_wordCount; i++) - { - words[i] = m_words[i].load(std::memory_order_relaxed); - } - - TData data; - memcpy(&data, words, sizeof(TData)); - return data; - } - - void store(_In_ const TData& data) noexcept - { - uintptr_t words[c_wordCount]{}; - memcpy(words, &data, sizeof(TData)); - for (size_t i = 0; i < c_wordCount; i++) - { - m_words[i].store(words[i], std::memory_order_relaxed); - } - } - - private: - static constexpr size_t c_wordCount = (sizeof(TData) + sizeof(uintptr_t) - 1) / sizeof(uintptr_t); - std::atomic m_words[c_wordCount]; - }; - - // Node - each entry in a list is backed by a node, - // which contains a single 64 bit value representing - // the next node of a singly linked list and - // a payload of type TData. Nodes must be properly aligned - // in memory so std::atomic works consistently. We do this - // by using an aligned allocator. - struct alignas(8) Node - { - std::atomic
next; - Payload data; - }; - - // Block - Represents a contiguous block of nodes. Blocks are - // only created. Ideally only one block would be created for - // a particular use case of this queue, but if the queue runs - // out of space in a block it will create additional blocks. - // Blocks are linked together as a singly linked list. - // Blocks must be properly aligned in memory so std::atomic - // works consistently. We do this by using an aligned allocator. - struct alignas(8) Block - { - std::atomic next; - Node* nodes; - uint32_t id; - uint32_t padding; - }; - - // List - this is a fully lock free linked list with push and pop - // operations. Nodes are provided externally. - class List - { - public: - - List(_In_ LocklessQueue& owner) : - m_owner(owner) - {} - - void init(_In_ Address dummy, _In_ Address end) noexcept - { - m_head = dummy; - m_tail = dummy; - m_end = end; - } - - inline Address end() { return m_end; } - inline Address head() { return m_head.load(); } - - // End markers carry a generation tag in their aba field (see push), so - // compare only the marker's position. - inline bool is_end(_In_ const Address& address) const noexcept - { - return address.index == m_end.index && address.block == m_end.block; - } - - // Returns true if the queue is empty. Note that - // since there are no locks this is a snapshot in time. - bool empty() noexcept - { - Address head = m_head.load(); - Address tail = m_tail.load(); - Address next = m_owner.to_node(head)->next; - - if (head == m_head.load() && - head == tail && - is_end(next)) - { - return true; - } - - return false; - } - - // Push a new node onto the tail of the list. The address - // is the address of the node. The node next pointer is initialized - // and the address aba is incremented. - inline void push(_In_ Node* node, _In_ Address address) noexcept - { - address.aba++; - - // Tag the end marker with this push's aba. Lists that share a heap - // share the same end marker, and a pusher that read this node's end - // marker while it was the tail of one list may be preempted while the - // node is popped and pushed onto another list sharing the heap. An - // untagged marker would let that stale compare-exchange in push_range - // succeed and link the pusher's node into the wrong list (the task - // queue moves nodes between its pending and active lists this way, - // which silently stranded delayed callbacks). Every push increments - // the node's aba, so the stale value no longer matches. - Address end = m_end; - end.aba = address.aba; - node->next = end; - - push_range(address, address); - } - - // Push a range of nodes into the tail of the list. The tailAddress - // is the last node to push and the beginAddress is the first. The - // nodes all need to be pre-confgured to follow each other. - void push_range(_In_ Address beginAddress, _In_ Address tailAddress) noexcept - { - while(true) - { - Address tail = m_tail.load(); - Node* tailNode = m_owner.to_node(tail); - Address tailNext = tailNode->next.load(); - - if (tail == m_tail.load()) - { - if (is_end(tailNext)) - { - // The next of the tail points to an invalid node, so - // this really is the tail. Fix up the next pointer to - // point to our new node. If this succeeds we try to - // adjust the tail, which isn't guaranteed to succeed. - // That's OK, we can fix it up later. The compare-exchange - // includes the end marker's generation tag (see push). - -#ifdef HC_UNITTEST_API - if (auto hook = LocklessQueueTestHooks::BeforeTailLink().load()) - { - hook(); - } -#endif - - if (tailNode->next.compare_exchange_strong(tailNext, beginAddress)) - { - m_tail.compare_exchange_strong(tail, tailAddress); - break; - } - } - else - { - // What we thought was the tail is really not pointing to the - // end, so advance down the list. - - m_tail.compare_exchange_strong(tail, tailNext); - } - } - } - } - - // Pop a node from the head of the list. There is always a dummy - // node at the head of the list, so part of this process shifts - // data from head->next out to a temporary variable and then - // puts the data back in head once it is detached. Returns nullptr - // if the list is empty. - Node* pop(_Out_ Address& address) noexcept - { - while (true) - { - Address head = m_head.load(); - Address tail = m_tail.load(); - Node* headNode = m_owner.to_node(head); - Address next = headNode->next.load(); - - if (head == m_head.load()) - { - if (head == tail) - { - if (is_end(next)) - { - // List is empty - address = m_end; - return nullptr; - } - - // List is not empty, but is out of - // sync. Advance the tail. - - m_tail.compare_exchange_strong(tail, next); - } - else - { - // This is possibly the node we want. We are going to - // shift the head node out of the list, but the list - // actually uses a dummy head node, so we must copy the - // data out of the next node, save it off, and then - // put it into the head node once we safely detach it. - - TData data = m_owner.to_node(next)->data.load(); - - if (m_head.compare_exchange_strong(head, next)) - { - headNode->data.store(data); - address = head; - return headNode; - } - } - } - } - } - - private: - - LocklessQueue& m_owner; - std::atomic
m_head; - std::atomic
m_tail; - Address m_end; - }; - - // Heap - the cache of available nodes. This heap may be shared - // with other LocklessQueue instances in cases where you need to move - // items between lists and want to share the nodes. If you don't - // also share the heap, sharing nodes will corrupt the queue. - class Heap - { - public: - Heap(_In_ LocklessQueue& owner) : - m_freeList(owner) - {} - - ~Heap() - { - Block* block = m_blockList; - while(block != nullptr) - { - Block* d = block; - block = block->next; - delete[] d->nodes; - delete d; - } - } - - void init(_In_ uint32_t blockSize) noexcept - { - if (blockSize < 0x40) - { - blockSize = 0x40; - } - - m_blockSize = blockSize; - - while(!allocate_block() && m_blockSize > 0x40) - { - m_blockSize = m_blockSize >> 2; - } - } - - inline Address end() { return m_freeList.end(); } - - // Returns the node at the given address, caching the block it - // was in. - Node* to_node(_Inout_ std::atomic& blockCache, _In_ const Address& address) - { - Block* block = blockCache.load(); - - if (block == nullptr || block->id != address.block) - { - for(block = m_blockList; block != nullptr; block = block->next) - { - if (block->id == address.block) - { - blockCache = block; - break; - } - } - } - - return &block->nodes[address.index]; - } - - // Returns a node back to the heap - void free(_In_ Node* node, _In_ Address address) noexcept - { - m_freeList.push(node, address); - } - - // Pops a node off the heap, allocating a new - // block if needed. - Node* alloc(_Out_ Address& address) noexcept - { - Node* node; - - do - { - node = m_freeList.pop(address); - - // It's possible that pop_list fails right after - // allocating a block if there is heavy free - // list use (Ex another thread drains the free list - // after we alocate). So we must loop and possibly - // allocate again. We break out if allocation fails. - - if (node == nullptr && !allocate_block()) - { - break; - } - } while(node == nullptr); - - return node; - } - - private: - - std::atomic m_blockCount = { 0 }; - uint32_t m_blockSize = 0; - Block* m_blockList = nullptr; - List m_freeList; - - // Allocates a new block of m_blockSize and - // puts all of its nodes on the free list. Returns - // true if the allocation was successful. - bool allocate_block() noexcept - { - uint32_t blockId = m_blockCount.fetch_add(1) + 1; - - // Block ID stored in Address is 16 bits, so that's our - // max. - if (blockId > 0xFFFF) - { - return false; - } - - // Note: allocate nodes and block separately because alignment - // may not be the same. - Block* block = new (std::nothrow) Block; - if (block == nullptr) - { - return false; - } - - block->nodes = new (std::nothrow) Node[m_blockSize]; - if (block->nodes == nullptr) - { - delete block; - return false; - } - - block->id = blockId; - block->next = nullptr; - - // Connect all the nodes in the new block. Element zero is - // the "tail" of this block. - - Address prev{}; - for (uint32_t index = 0; index < m_blockSize; index++) - { - block->nodes[index].next = prev; - prev.block = static_cast(block->id); - prev.index = index; - prev.aba = 0; - } - - // Now connect this block to the tail. Because we never delete - // blocks we can safely traverse the linked list of blocks with - // no locks or fanciness. The startIndex will be zero except when - // we are first initializing m_blockList. Then we steal the first - // node to act as the free list's dummy node. - - uint32_t startIndex = 0; - - if (m_blockList == nullptr) - { - // Initial contruction. We need to store the block list - // and then initialize the free list. - - Address end{}; - Address a{}; - a.block = static_cast(block->id); - - block->nodes[0].next = end; - block->nodes[1].next = end; - startIndex = 1; - m_blockList = block; - m_freeList.init(a, end); - } - else - { - Block* tail = m_blockList; - Block* next = tail->next.load(); - - while(true) - { - while(next != nullptr) - { - tail = next; - next = tail->next.load(); - } - - Block* empty = nullptr; - - if(tail->next.compare_exchange_strong(empty, block)) - { - break; - } - - next = tail->next.load(); - } - } - - // Now add the tail and the head to the free list. - - Address rangeBegin{}; - Address rangeEnd{}; - - rangeBegin.block = rangeEnd.block = static_cast(block->id); - rangeBegin.index = m_blockSize - 1; - rangeEnd.index = startIndex; - m_freeList.push_range(rangeBegin, rangeEnd); - - return true; - } - }; - - /* - * - * Members - * - */ - - Heap m_localHeap; - Heap& m_heap; - List m_activeList; - std::atomic m_blockCache; - std::atomic_flag m_lock; - - /* - * - * Private APIs - * - */ - - // Workers for pushing nodes to the back - // of the queue. This always moves data - bool move_back(_In_ TData&& data) noexcept - { - Address address; - Node* node = m_heap.alloc(address); - - if (node != nullptr) - { - node->data.store(data); - m_activeList.push(node, address); - return true; - } - - return false; - } - - // Workers for pushing nodes to the back - // of the queue. This always moves data - void move_back(_In_ TData&& data, _In_ uint64_t address) noexcept - { - Address a; - a = address; - Node* n = to_node(a); - n->data.store(data); - m_activeList.push(n, a); - } - - // Called during construction after the heap - // is setup. - void Initialize() - { - Address end = m_heap.end(); - end.index++; - - Address dummy; - Node* n = m_heap.alloc(dummy); - - if (n != nullptr) - { - // Tag the end marker with the dummy's aba, as push does. - Address dummyEnd = end; - dummyEnd.aba = dummy.aba; - n->next = dummyEnd; - } - else - { - dummy = end; - } - - m_activeList.init(dummy, end); - } - - Node* to_node(_In_ const Address& address) - { - return m_heap.to_node(m_blockCache, address); - } -}; - -#pragma warning(pop) diff --git a/third_party/xtaskqueue/Source/Task/SpinLock.h b/third_party/xtaskqueue/Source/Task/SpinLock.h deleted file mode 100644 index 75c5c36f1..000000000 --- a/third_party/xtaskqueue/Source/Task/SpinLock.h +++ /dev/null @@ -1,72 +0,0 @@ -#pragma once -#include -#include -#include - -#if defined(_WIN32) || defined(__WINDOWS__) -#include -#elif (defined(_M_IX86) || defined(_M_X64)) -#include -#endif - -// -// SpinLock: A spinlock implementation based on std::atomic_flag that -// prevents CPU starvation. SpinLock can be used as a RAII wrapper around -// an external flag, or its static Lock API may be used to lock an -// external flag. -// -class SpinLock -{ -public: - SpinLock(_In_ std::atomic_flag& flag) : m_lock(flag) - { - Lock(m_lock); - } - - ~SpinLock() - { - m_lock.clear(std::memory_order_release); - } - - static void Lock(_In_ std::atomic_flag& flag) - { - unsigned int backoff = 1; - constexpr unsigned int maxBackoff = 1024; - - while (flag.test_and_set(std::memory_order_acquire)) { - for (unsigned int i = 0; i < backoff; ++i) { - cpu_pause(); - } - - // Exponential backoff with cap. If we are over the cap yield - // this thread. - - backoff = backoff << 1; - if (backoff >= maxBackoff) - { - backoff = maxBackoff; - std::this_thread::yield(); - } - } - } - -private: - std::atomic_flag& m_lock; - - static inline void cpu_pause() - { -#if defined(_M_IX86) || defined(_M_X64) - // x86/x64: Tells CPU we're spinning - // Reduces energy consumption - // Helps avoid memory order violations - // Maps to PAUSE instruction - _mm_pause(); -#elif defined(_M_ARM) || defined(_M_ARM64) - // ARM: Yields to other hardware threads - __yield(); -#else - // Other platforms: No specific CPU hint - // Still helps due to compiler barrier -#endif - } -}; \ No newline at end of file diff --git a/third_party/xtaskqueue/Source/Task/StaticArray.h b/third_party/xtaskqueue/Source/Task/StaticArray.h deleted file mode 100644 index 1dc58e2c3..000000000 --- a/third_party/xtaskqueue/Source/Task/StaticArray.h +++ /dev/null @@ -1,67 +0,0 @@ -// Copyright (c) Microsoft Corporation -// Licensed under the MIT license. See LICENSE file in the project root for full license information. - -#pragma once - -template -class StaticArray -{ -public: - - StaticArray() - { - } - - StaticArray(const StaticArray& other) - { - m_count = other.m_count; - for(uint32_t idx = 0; idx < m_count; idx++) - { - m_array[idx] = other.m_array[idx]; - } - } - - StaticArray& operator=(const StaticArray& other) - { - m_count = other.m_count; - for(uint32_t idx = 0; idx < m_count; idx++) - { - m_array[idx] = other.m_array[idx]; - } - return *this; - } - - uint32_t count() { return m_count; } - uint32_t capacity() { return ARRAYSIZE(m_array) - m_count; } - void clear() { m_count = 0; } - TData* data() { return m_array; } - TData& operator[](size_t idx) { return m_array[idx]; } - - void append(const TData& data) - { - ASSERT(m_count != ARRAYSIZE(m_array)); - m_array[m_count++] = data; - } - - void removeAt(uint32_t idx) - { - if (idx == m_count - 1) - { - m_count --; - } - else - { - for (uint32_t i = idx + 1; i < m_count; i++) - { - m_array[i - 1] = m_array[i]; - } - m_count--; - } - } - -private: - - uint32_t m_count = 0; - TData m_array[size]; - -}; diff --git a/third_party/xtaskqueue/Source/Task/TaskQueue.cpp b/third_party/xtaskqueue/Source/Task/TaskQueue.cpp deleted file mode 100644 index 853b65c18..000000000 --- a/third_party/xtaskqueue/Source/Task/TaskQueue.cpp +++ /dev/null @@ -1,3178 +0,0 @@ -// Copyright (c) Microsoft Corporation -// Licensed under the MIT license. See LICENSE file in the project root for full license information. - -#include "pch.h" -#include "referenced_ptr.h" -#include "XTaskQueuePriv.h" -#include "TaskQueueP.h" -#include "TaskQueueImpl.h" - -#if defined(HC_ENABLE_UNNAMED_OBJECT_DIAGNOSTICS) -namespace -{ -struct UnnamedObjectDiagnosticCounters -{ - std::atomic constructed[4]{}; - std::atomic destroyed[4]{}; -}; - -UnnamedObjectDiagnosticCounters& DiagnosticCounters() noexcept -{ - static UnnamedObjectDiagnosticCounters counters; - return counters; -} - -size_t DiagnosticTypeIndex(UnnamedObjectDiagnostics::Type type) noexcept -{ - return static_cast(type); -} -} - -namespace UnnamedObjectDiagnostics -{ -void RecordConstruction(Type type) noexcept -{ - ++DiagnosticCounters().constructed[DiagnosticTypeIndex(type)]; -} - -void RecordDestruction(Type type) noexcept -{ - ++DiagnosticCounters().destroyed[DiagnosticTypeIndex(type)]; -} -} - -STDAPI XTaskQueueGetSyncObjectDiagnosticSnapshot( - _Out_ XTaskQueueSyncObjectSnapshot* snapshot - ) noexcept -{ - RETURN_HR_IF(E_POINTER, snapshot == nullptr); - - auto loadCounts = [](UnnamedObjectDiagnostics::Type type) - { - const size_t index = DiagnosticTypeIndex(type); - auto& counters = DiagnosticCounters(); - const uint64_t destroyed = counters.destroyed[index].load(); - const uint64_t constructed = counters.constructed[index].load(); - return XTaskQueueSyncObjectCounts - { - constructed, - destroyed, - constructed - destroyed - }; - }; - - snapshot->mutex = loadCounts(UnnamedObjectDiagnostics::Type::Mutex); - snapshot->recursiveMutex = loadCounts(UnnamedObjectDiagnostics::Type::RecursiveMutex); - snapshot->conditionVariable = loadCounts(UnnamedObjectDiagnostics::Type::ConditionVariable); - snapshot->conditionVariableAny = loadCounts(UnnamedObjectDiagnostics::Type::ConditionVariableAny); -#if defined(HC_USE_UNNAMED_MUTEX) - snapshot->usesUnnamedConstructors = true; -#else - snapshot->usesUnnamedConstructors = false; -#endif - return S_OK; -} - -STDAPI XTaskQueueRunSyncObjectDiagnosticProbe( - _Out_ XTaskQueueSyncObjectSnapshot* before, - _Out_ XTaskQueueSyncObjectSnapshot* during, - _Out_ XTaskQueueSyncObjectSnapshot* after - ) noexcept -{ - RETURN_HR_IF(E_POINTER, before == nullptr || during == nullptr || after == nullptr); - RETURN_IF_FAILED(XTaskQueueGetSyncObjectDiagnosticSnapshot(before)); - - { - DefaultUnnamedMutex mutex; - DefaultUnnamedRecursiveMutex recursiveMutex; - DefaultUnnamedConditionVariable conditionVariable; - DefaultUnnamedConditionVariableAny conditionVariableAny; - - std::lock_guard mutexLock{ mutex }; - std::lock_guard outerRecursiveLock{ recursiveMutex }; - std::lock_guard innerRecursiveLock{ recursiveMutex }; - RETURN_IF_FAILED(XTaskQueueGetSyncObjectDiagnosticSnapshot(during)); - } - - return XTaskQueueGetSyncObjectDiagnosticSnapshot(after); -} -#endif - -// -// ApiRefs tracks global refcounts for all APIs. It is used to identify memory leaks -// in tests and can be called to wait for all refs to be released. -// -namespace ApiRefs -{ - std::atomic g_globalApiRefs{ 0 }; - DefaultUnnamedMutex g_waitMutex; - DefaultUnnamedConditionVariable g_waitCv; - - void GlobalAddRef() - { - g_globalApiRefs++; - } - - void GlobalRelease() - { - auto priorRefs = g_globalApiRefs.fetch_sub(1); - if (priorRefs == 1) - { - std::unique_lock lock(g_waitMutex); - g_waitCv.notify_all(); - } - } - - bool WaitZeroRefs(_In_ uint32_t timeoutMilliseconds) - { - // We are called after queues are deleted so it could be - // possible that the cv doesn't get signaled, so check for - // zero first before waiting. - std::unique_lock lock(g_waitMutex); - if (g_globalApiRefs.load() != 0) - { - g_waitCv.wait_for(lock, std::chrono::milliseconds(timeoutMilliseconds)); - return g_globalApiRefs == 0; - } - - return true; - } - -#ifdef HC_UNITTEST_API - std::atomic g_liveQueues{ 0 }; - std::atomic g_livePorts{ 0 }; - - void TrackLiveObject(ApiId id, int32_t delta) noexcept - { - switch (id) - { - case ApiId::TaskQueue: - g_liveQueues += delta; - break; - - case ApiId::TaskQueuePort: - g_livePorts += delta; - break; - - default: - break; - } - } -#endif -} - -#ifdef HC_UNITTEST_API -STDAPI_(void) XTaskQueueGetLiveObjectCounts( - _Out_ XTaskQueueLiveObjectCounts* counts - ) noexcept -{ - if (counts != nullptr) - { - counts->globalRefs = ApiRefs::g_globalApiRefs.load(); - counts->queues = static_cast(ApiRefs::g_liveQueues.load()); - counts->ports = static_cast(ApiRefs::g_livePorts.load()); - } -} -#endif - -namespace ProcessGlobals -{ - const XTaskQueueHandle g_invalidQueueHandle = (XTaskQueueHandle)(-1); - std::atomic g_defaultProcessQueue = { g_invalidQueueHandle }; - std::atomic g_processQueue = { g_invalidQueueHandle }; - -#ifdef SUSPEND_API - SuspendState g_suspendState; -#endif -} - -// -// SubmitCallback -// - -SubmitCallback::SubmitCallback( - _In_ XTaskQueueHandle queue) - : m_queue(queue) -{ - memset(m_buffer1, 0, sizeof(m_buffer1)); - memset(m_buffer2, 0, sizeof(m_buffer2)); -} - -HRESULT SubmitCallback::Register(_In_opt_ void* context, _In_ XTaskQueueMonitorCallback* callback, _Out_ XTaskQueueRegistrationToken* token) -{ - RETURN_HR_IF(E_POINTER, callback == nullptr || token == nullptr); - - token->token = 0; - - std::lock_guard lock(m_lock); - uint32_t bufferReadIdx = (m_indexAndRef & 0x80000000 ? 1 : 0); - uint32_t bufferWriteIdx = 1 - bufferReadIdx; - - for(uint32_t idx = 0; idx < ARRAYSIZE(m_buffer1); idx++) - { - if (token->token == 0 && m_buffers[bufferReadIdx][idx].Callback == nullptr) - { - token->token = ++m_nextToken; - m_buffers[bufferWriteIdx][idx].Token = token->token; - m_buffers[bufferWriteIdx][idx].Context = context; - m_buffers[bufferWriteIdx][idx].Callback = callback; - } - else - { - m_buffers[bufferWriteIdx][idx] = m_buffers[bufferReadIdx][idx]; - } - } - - RETURN_HR_IF(E_OUTOFMEMORY, token->token == 0); - - // Now spin wait to swap the active buffer. - uint32_t expected = bufferReadIdx << 31; - uint32_t desired = bufferWriteIdx << 31; - - for (;;) - { - uint32_t expectedSwap = expected; - if (m_indexAndRef.compare_exchange_weak(expectedSwap, desired)) - { - break; - } - } - - return S_OK; -} - -void SubmitCallback::Unregister(_In_ XTaskQueueRegistrationToken token) -{ - std::lock_guard lock(m_lock); - uint32_t bufferReadIdx = (m_indexAndRef & 0x80000000 ? 1 : 0); - uint32_t bufferWriteIdx = 1 - bufferReadIdx; - - for(uint32_t idx = 0; idx < ARRAYSIZE(m_buffer1); idx++) - { - if (m_buffers[bufferReadIdx][idx].Token == token.token) - { - m_buffers[bufferWriteIdx][idx].Callback = nullptr; - } - else - { - m_buffers[bufferWriteIdx][idx] = m_buffers[bufferReadIdx][idx]; - } - } - - // Now spin wait to swap the active buffer. - uint32_t expected = bufferReadIdx << 31; - uint32_t desired = bufferWriteIdx << 31; - - for (;;) - { - uint32_t expectedSwap = expected; - if (m_indexAndRef.compare_exchange_weak(expectedSwap, desired)) - { - break; - } - } -} - -void SubmitCallback::Invoke(_In_ XTaskQueuePort port) -{ - uint32_t indexAndRef = ++m_indexAndRef; - uint32_t bufferIdx = (indexAndRef & 0x80000000 ? 1 : 0); - - for(uint32_t idx = 0; idx < ARRAYSIZE(m_buffer1); idx++) - { - if (m_buffers[bufferIdx][idx].Callback != nullptr) - { - m_buffers[bufferIdx][idx].Callback( - m_buffers[bufferIdx][idx].Context, - m_queue, - port); - } - } - - m_indexAndRef--; -} - -// -// QueueWaitRegistry -// - -bool QueueWaitRegistry::Reserve() -{ - std::lock_guard lock(m_lock); - if (m_reserved == m_callbacks.capacity()) return false; - ++m_reserved; - return true; -} - -void QueueWaitRegistry::CancelReservation() -{ - std::lock_guard lock(m_lock); - --m_reserved; -} - -void QueueWaitRegistry::Publish(XTaskQueuePort port, XTaskQueueRegistrationToken portToken, - XTaskQueueRegistrationToken* token, bool retiredByPort) -{ - std::lock_guard lock(m_lock); - --m_reserved; - WaitRegistration reg{++m_nextToken, portToken.token, port, retiredByPort}; - m_callbacks.append(reg); - token->token = reg.Token; -} - -QueueWaitRegistry::WaitRegistration QueueWaitRegistry::Lookup( - XTaskQueueRegistrationToken token) -{ - std::lock_guard lock(m_lock); - for (uint32_t i = 0; i < m_callbacks.count(); ++i) - { - if (m_callbacks[i].Token == token.token) - return m_callbacks[i]; - } - return {}; -} - -void QueueWaitRegistry::Remove(XTaskQueueRegistrationToken token) -{ - std::lock_guard lock(m_lock); - for (uint32_t i = 0; i < m_callbacks.count(); ++i) - { - if (m_callbacks[i].Token == token.token) - { - m_callbacks.removeAt(i); - return; - } - } -} - -// -// TaskQueuePortImpl -// - -TaskQueuePortImpl::TaskQueuePortImpl() - : Api() -{ - m_header.m_signature = TASK_QUEUE_PORT_SIGNATURE; - m_header.m_runtimeIteration = GetCurrentRuntimeIteration(); - m_header.m_port = this; - m_header.m_queue = nullptr; -} - -TaskQueuePortImpl::~TaskQueuePortImpl() -{ - m_timer.Terminate(); - - EraseQueue(m_queueList.get()); - EraseQueue(m_pendingList.get()); - -#ifdef _WIN32 - // The last port release precludes new pins. Finish any native - // callbacks that entered before TryAddRef began refusing them. - while (!m_waits.empty()) - { - UnregisterWaitHandle({m_waits.begin()->first}); - } -#endif - - m_threadPool.Terminate(); - -#ifdef _WIN32 - if (m_queueEvent) CloseHandle(m_queueEvent); -#endif - - // Destroy these lists in order, since the pending lsit shares - // the node heap with the queue list. - - m_pendingList.reset(); - m_queueList.reset(); -} - -HRESULT TaskQueuePortImpl::Initialize( - _In_ XTaskQueueDispatchMode mode) -{ - m_dispatchMode = mode; - - m_queueList.reset(new (std::nothrow) LocklessQueue); - RETURN_IF_NULL_ALLOC(m_queueList); - - // Lockless lists can share their underlying heaps. This both reduces - // memory costs and allows node addresses from one list to be transferred - // to another. We use this frequently when transferring data across - // lists to eliminate the possibility of allocation failures. - - m_pendingList.reset(new (std::nothrow) LocklessQueue(*m_queueList.get())); - RETURN_IF_NULL_ALLOC(m_pendingList); - - // There should be very few simultaneous termination requests, so we can set the - // default heap size to the minimum. - - m_terminationList.reset(new (std::nothrow) LocklessQueue(0)); - RETURN_IF_NULL_ALLOC(m_terminationList); - - m_pendingTerminationList.reset(new (std::nothrow) LocklessQueue(*m_terminationList.get())); - RETURN_IF_NULL_ALLOC(m_pendingTerminationList); - - RETURN_IF_FAILED(m_timer.Initialize(this, [](void* context) - { - TaskQueuePortImpl* pthis = static_cast(context); - - // Keep the port alive while we process pending callbacks. The sweep - // takes and drops temporary references on queues attached to this - // port, and if a queue is closed concurrently one of those releases - // can be the last, destroying the queue and its port on this thread. - // Holding our own reference defers any port destruction to the - // Release below, after which we touch nothing. The timer can't be - // torn down underneath us before this AddRef because port - // destruction waits for in-flight timer callbacks. - pthis->AddRef(); - pthis->SubmitPendingCallbacks(); - pthis->Release(); // May destroy the port and its timer. - })); - -#ifdef _WIN32 - HANDLE evt = CreateEvent(nullptr, FALSE, FALSE, nullptr); - RETURN_LAST_ERROR_IF_NULL(evt); - m_queueEvent = evt; -#endif - - switch (mode) - { - case XTaskQueueDispatchMode::Manual: - // nothing - break; - - case XTaskQueueDispatchMode::ThreadPool: - case XTaskQueueDispatchMode::SerializedThreadPool: - RETURN_IF_FAILED(m_threadPool.Initialize(this, [](void* context, OS::ThreadPoolActionStatus& status) - { - TaskQueuePortImpl* pthis = static_cast(context); - pthis->ProcessThreadPoolCallback(status); - })); - break; - - case XTaskQueueDispatchMode::Immediate: - // nothing - break; - } - - return S_OK; -} - -HRESULT __stdcall TaskQueuePortImpl::QueueItem( - _In_ ITaskQueuePortContext* portContext, - _In_ uint32_t waitMs, - _In_opt_ void* callbackContext, - _In_ XTaskQueueCallback* callback) -{ - RETURN_IF_FAILED(VerifyNotTerminated(portContext)); - - QueueEntry entry; - referenced_ptr portContextHolder(portContext); - - entry.portContext = portContext; - entry.callback = callback; - entry.callbackContext = callbackContext; - entry.waitRegistration = nullptr; - entry.id = m_nextId++; - - if (waitMs == 0) - { - entry.enqueueTime = 0; - RETURN_HR_IF(E_OUTOFMEMORY, !AppendEntry(entry)); - } - else - { - // Delayed callbacks are ordered by a monotonic due time so stale timer - // callbacks and wall-clock adjustments cannot make one pending entry - // masquerade as another. - entry.enqueueTime = m_timer.GetDueTime(waitMs); - RETURN_HR_IF(E_OUTOFMEMORY, !m_pendingList->push_back(entry)); - - while (true) - { - const uint64_t publishedDueTime = m_timerDue.load(); - const uint64_t now = m_timer.GetCurrentTime(); - - // A one-shot timer callback may already be processing an overdue - // deadline without having advanced m_timerDue yet. Rearm that - // published deadline so this newly queued entry cannot be stranded - // behind the in-progress callback. - if (publishedDueTime != UINT64_MAX && publishedDueTime <= now) - { - if (!RearmTimerIfDueTimeUnchanged(publishedDueTime)) - { - continue; - } - } - else - { - ArmTimerIfEarlier(entry.enqueueTime); - } - - break; - } - } - - // QueueEntry now owns the ref. - portContextHolder.release(); - - // If we raced with termination, cancel the item we just added - if (portContext->GetStatus() != TaskQueuePortStatus::Active) - { - CancelPendingEntries(portContext, true); - } - - return S_OK; -} - -HRESULT __stdcall TaskQueuePortImpl::RegisterWaitHandle( - _In_ ITaskQueuePortContext* portContext, - _In_ HANDLE waitHandle, - _In_opt_ void* callbackContext, - _In_ XTaskQueueCallback* callback, - _Out_ XTaskQueueRegistrationToken* token) -{ - return RegisterWaitWithToken(portContext, waitHandle, callbackContext, callback, token, nullptr); -} - -HRESULT TaskQueuePortImpl::RegisterWaitWithToken(ITaskQueuePortContext* portContext, - HANDLE waitHandle, void* callbackContext, XTaskQueueCallback* callback, - XTaskQueueRegistrationToken* token, QueueWaitRegistry* registry) -{ - RETURN_HR_IF(E_INVALIDARG, callback == nullptr || waitHandle == nullptr || token == nullptr); - RETURN_HR_IF(E_POINTER, token == nullptr); - RETURN_IF_FAILED(VerifyNotTerminated(portContext)); - -#ifdef _WIN32 - referenced_ptr reg(new (std::nothrow) WaitRegistration); - RETURN_IF_NULL_ALLOC(reg.get()); - - void* capability = nullptr; - RETURN_IF_FAILED(portContext->QueryApi(TaskQueueInternal::kPinnableContextApiId, &capability)); - referenced_ptr pin; - *pin.address_of() = static_cast(capability); - RETURN_HR_IF(E_NOINTERFACE, !pin); - - reg->port = this; - reg->pinnable = pin.get(); - reg->queueEntry = {portContext, callbackContext, callback, reg.get(), 0, m_nextId++}; - try - { - reg->handleOwner = std::make_shared(); - } - CATCH_RETURN(); - RETURN_IF_WIN32_BOOL_FALSE(DuplicateHandle(GetCurrentProcess(), waitHandle, GetCurrentProcess(), - ®->handleOwner->handle, 0, FALSE, DUPLICATE_SAME_ACCESS)); - reg->threadpoolWait = CreateThreadpoolWait(WaitCallback, reg.get(), nullptr); - RETURN_LAST_ERROR_IF_NULL(reg->threadpoolWait); - - try - { - std::lock_guard lock(m_lock); - RETURN_IF_FAILED(VerifyNotTerminated(portContext)); - RETURN_HR_IF(E_OUTOFMEMORY, m_activeWaits == PORT_WAIT_MAX || m_nextWaitToken == UINT64_MAX); - reg->token = ++m_nextWaitToken; - m_waits.emplace(reg->token, reg); - // Termination must be able to deliver cancellation even under OOM. - if (!m_queueList->reserve_node(reg->cancelNode)) - { - m_waits.erase(reg->token); - return E_OUTOFMEMORY; - } - ++m_activeWaits; - // Lookup never holds the registry lock while entering the port. - if (registry) - { - registry->Publish(portContext->GetType(), {reg->token}, token, true); - reg->publicRegistry = referenced_ptr(registry); - reg->publicToken = *token; - } - else token->token = reg->token; - SetThreadpoolWait(reg->threadpoolWait, reg->handleOwner->handle, nullptr); - InvalidateWaitEpochLocked(); - } - CATCH_RETURN(); - - return S_OK; -#else - return E_NOTIMPL; -#endif -} - -void __stdcall TaskQueuePortImpl::UnregisterWaitHandle( - _In_ XTaskQueueRegistrationToken token) -{ -#ifdef _WIN32 - referenced_ptr reg; - referenced_ptr suppressedContext; - const bool reentrant = WaitCallbackFrame::ConfirmEntry(); - { - std::lock_guard lock(m_lock); - auto it = m_waits.find(token.token); - if (it == m_waits.end()) return; - reg = it->second; - RetireWaitLocked(reg.get(), WaitRegistration::State::Removed); - suppressedContext = std::move(reg->queuedContext); - if (suppressedContext) --m_readyEntries; - } - - DrainRetiredWait(reg); - { - std::unique_lock lock(m_lock); - m_waitFinished.wait(lock, [&] { - return !reg->running || (reentrant && reg->enteredUserCode); - }); - FinishRetirementLocked(reg.get()); - } -#else - UNREFERENCED_PARAMETER(token); -#endif -} - -HRESULT __stdcall TaskQueuePortImpl::PrepareTerminate( - _In_ ITaskQueuePortContext* portContext, - _In_ void* callbackContext, - _In_ XTaskQueueTerminatedCallback* callback, - _Out_ void** token) -{ - RETURN_HR_IF(E_POINTER, token == nullptr); - RETURN_HR_IF(E_INVALIDARG, callback == nullptr); - - std::unique_ptr term(new (std::nothrow) TerminationEntry); - RETURN_IF_NULL_ALLOC(term); - - { - std::lock_guard lock(m_terminationLock); - RETURN_HR_IF(E_OUTOFMEMORY, !m_terminationList->reserve_node(term->node)); - } - - term->callbackContext = callbackContext; - term->callback = callback; - term->portContext = portContext; - - // Mark the port as canceled, but don't overwrite - // terminating or terminated status. - portContext->TrySetStatus(TaskQueuePortStatus::Active, TaskQueuePortStatus::Canceled); - *token = term.release(); - - return S_OK; -} - -void __stdcall TaskQueuePortImpl::CancelTermination( - _In_ void* token) -{ - TerminationEntry* term = static_cast(token); - term->portContext->TrySetStatus(TaskQueuePortStatus::Canceled, TaskQueuePortStatus::Active); - - if (term->node != 0) - { - std::lock_guard lock(m_terminationLock); - m_terminationList->free_node(term->node); - } - - delete term; -} - -void __stdcall TaskQueuePortImpl::Terminate( - _In_ void* token) -{ - TerminationEntry* term = static_cast(token); - referenced_ptr cxt(term->portContext); - - // Prevent anything else from coming into the queue - cxt->SetStatus(TaskQueuePortStatus::Terminating); - - CancelPendingEntries(cxt.get(), true); - - // Are there existing suspends? AddSuspend returns - // true if this is the first suspend added. - if (cxt->AddSuspend()) - { - ScheduleTermination(term); - } - else - { - std::lock_guard lock(m_terminationLock); - m_pendingTerminationList->push_back(term, term->node); - term->node = 0; - } - - // Balance our add. Note we must use ResumeTermination - // here so we schedule the termination if this is the - // last remove. - ResumeTermination(cxt.get()); -} - -HRESULT __stdcall TaskQueuePortImpl::Attach( - _In_ ITaskQueuePortContext* portContext) try -{ - // Discover the private capability while the caller still owns - // the context. QueryApi returns an owned reference on success. - void* capability = nullptr; - HRESULT queryResult = portContext->QueryApi( - TaskQueueInternal::kPinnableContextApiId, - &capability); - - if (SUCCEEDED(queryResult) && capability != nullptr) - { - auto* pinnable = - static_cast(capability); - - struct CapabilityGuard - { - TaskQueuePortContextImpl* context; - ~CapabilityGuard() { context->Release(); } - } capabilityGuard{ pinnable }; - - std::lock_guard lock(m_attachedContextsLock); - - if (m_nextAttachedContextId == UINT64_MAX) - { - return E_OUTOFMEMORY; - } - - m_attachedContexts.emplace( - m_nextAttachedContextId, - AttachedContextRegistration{ portContext, pinnable }); - - ++m_nextAttachedContextId; - return S_OK; - } - - // Without safe pinning, invoking callbacks outside the lock is unsafe. - return E_NOINTERFACE; -} CATCH_RETURN(); - -void __stdcall TaskQueuePortImpl::Detach( - _In_ ITaskQueuePortContext* portContext) -{ - { - std::lock_guard lock(m_attachedContextsLock); - - for (auto it = m_attachedContexts.begin(); - it != m_attachedContexts.end(); ++it) - { - if (it->second.context == portContext) - { - m_attachedContexts.erase(it); - break; - } - } - } - - // Cancellation may release references and run reentrant teardown. - CancelPendingEntries(portContext, false); -} - -bool TaskQueuePortImpl::TryAcquireNextAttachedContext( - uint64_t& cursor, - uint64_t upperBound, - ITaskQueuePortContext** result) -{ - *result = nullptr; - - std::lock_guard lock(m_attachedContextsLock); - - auto it = m_attachedContexts.upper_bound(cursor); - - while (it != m_attachedContexts.end() && - it->first <= upperBound) - { - cursor = it->first; - - // A successful pin keeps the containing queue alive until - // the caller releases the context outside the registry lock. - if (it->second.pinnable->TryPin()) - { - *result = it->second.context; - return true; - } - - ++it; - } - - return false; -} - -bool __stdcall TaskQueuePortImpl::Dispatch( - _In_ ITaskQueuePortContext* portContext, - _In_ uint32_t timeoutInMs) -{ - bool found = false; - - while (!found) - { - found = DrainOneItem(); - - if (!found && !Wait(portContext, timeoutInMs)) - { - break; - } - } - - return found; -} - -bool TaskQueuePortImpl::DrainOneItem() -{ - struct DummyActionStatus : OS::ThreadPoolActionStatus - { - void Complete() override {} - void MayRunLong() override {} - } dummy; - - return DrainOneItem(dummy); -} - -bool TaskQueuePortImpl::DrainOneItem( - _In_ OS::ThreadPoolActionStatus& status) -{ - if (m_suspended && m_dispatchMode != XTaskQueueDispatchMode::Immediate) - { - return false; - } - - m_processingCallback++; - QueueEntry entry; - bool popped = false; - - while (m_queueList->pop_front(entry)) - { - referenced_ptr context; - -#ifdef _WIN32 - if (entry.waitRegistration) - { - if (!DispatchWaitEntry(entry, status, context)) continue; - } - else -#endif - { -#ifdef _WIN32 - --m_readyEntries; -#endif - *context.address_of() = entry.portContext; // Adopt the queue entry's reference. - if (entry.portContext->GetType() == XTaskQueuePort::Work) - { - status.MayRunLong(); - } - entry.callback(entry.callbackContext, IsCallCanceled(entry)); - } - - m_processingCallback--; - m_processingCallbackCv.notify_all(); - popped = true; - break; // context releases after the processing count falls. - } - if (!popped) - { - m_processingCallback--; - m_processingCallbackCv.notify_all(); - } - - if (ReadyQueueEmpty() && m_processingCallback.load() == 0) - { - SignalTerminations(); - SignalQueue(); - } - - return popped; -} - -// Waits up to timeout for something to arrive in the queue. -// Returns true if the wait succeeded. Returns false if it timed -// out or the port is terminated. -bool TaskQueuePortImpl::Wait( - _In_ ITaskQueuePortContext* portContext, - _In_ uint32_t timeout) -{ -#ifdef _WIN32 - const ULONGLONG start = GetTickCount64(); - bool attempted = false; - for (;;) - { - WaitSnapshot snapshot; - CaptureWaitSnapshot(snapshot); - // A mutation before capture is visible here. A later mutation signals - // the epoch in this snapshot, including before the kernel wait starts. - if (portContext->GetStatus() == TaskQueuePortStatus::Terminated) return false; - if (!m_suspended && ((!ReadyQueueEmpty() && !m_queueList->empty()) || !TerminationListEmpty())) return true; - - DWORD remaining = INFINITE; - if (timeout != INFINITE) - { - const auto elapsed = GetTickCount64() - start; - if (attempted && timeout != 0 && elapsed >= timeout) return false; - remaining = elapsed < timeout ? timeout - static_cast(elapsed) : 0; - } - // Retirement and termination cannot fail due to event allocation. - const DWORD interval = snapshot.epoch ? remaining : (std::min)(remaining, DWORD{16}); - attempted = true; - DWORD result = WaitForMultipleObjects(snapshot.events.count(), snapshot.events.data(), FALSE, interval); - if (result == WAIT_TIMEOUT) - { - if (interval == remaining) return false; - continue; - } - if (result >= WAIT_OBJECT_0 + snapshot.events.count()) - { - if (result == WAIT_FAILED) { FAIL_FAST_IF_FAILED(HRESULT_FROM_WIN32(GetLastError())); } - return false; - } - if (result > WAIT_OBJECT_0 && result <= WAIT_OBJECT_0 + snapshot.registrations.count()) - ProcessWaitCallback(snapshot.registrations[result - WAIT_OBJECT_0 - 1].get()); - } - -#else - while (m_suspended || (ReadyQueueEmpty() && TerminationListEmpty())) - { - if (portContext->GetStatus() == TaskQueuePortStatus::Terminated) - { - return false; - } - - std::unique_lock lock(m_lock); - - if (!m_signaled && - m_event.wait_for(lock, std::chrono::milliseconds(timeout)) == std::cv_status::timeout) - { - return false; - } - - m_signaled = false; - } -#endif - - return true; -} - -bool TaskQueuePortImpl::ReadyQueueEmpty() -{ -#ifdef _WIN32 - return m_readyEntries.load() == 0; -#else - return m_queueList->empty(); -#endif -} - -bool __stdcall TaskQueuePortImpl::IsEmpty() -{ - bool empty = - (ReadyQueueEmpty()) && - (m_pendingList->empty()) && - (m_processingCallback == 0); - - return empty; -} - -void __stdcall TaskQueuePortImpl::WaitForUnwind() -{ - DefaultUnnamedMutex mutex; - std::unique_lock lock(mutex); - - while(m_processingCallback.load() != 0) - { - // wait for 10 ms. We do not modify m_processingCallback under - // the protection of a mutex because we don't want the hit of - // taking a lock. Therefore, we can't wait forever for the - // cv here. We could miss it due to a race. This API is only - // called during task queue termination and therefore some polling - // is OK. - - std::chrono::milliseconds ms{10}; - auto when = std::chrono::steady_clock::time_point(ms); - m_processingCallbackCv.wait_until(lock, when); - } -} - -HRESULT __stdcall TaskQueuePortImpl::SuspendTermination( - _In_ ITaskQueuePortContext* portContext - ) -{ - // This is necessary to ensure there is no race. - portContext->AddSuspend(); - HRESULT hr = VerifyNotTerminated(portContext); - - if (FAILED(hr)) - { - ResumeTermination(portContext); - RETURN_HR(hr); - } - - return S_OK; -} - -void __stdcall TaskQueuePortImpl::ResumeTermination( - _In_ ITaskQueuePortContext* portContext) -{ - if (portContext->RemoveSuspend()) - { - // Removed the last external callback. Look for - // parked terminations and reschedule them. - // Use a temporary list sharing the same heap to avoid allocation - LocklessQueue entries_to_schedule(*m_pendingTerminationList.get()); - - { - std::lock_guard lock(m_terminationLock); - m_pendingTerminationList->remove_if([&](auto& entry, auto address) - { - if (entry->portContext == portContext) - { - entries_to_schedule.push_back(entry, address); - return true; - } - - return false; - }); - } - - // Schedule entries outside the lock - TerminationEntry* entry; - uint64_t address; - while (entries_to_schedule.pop_front(entry, address)) - { - entry->node = address; - ScheduleTermination(entry); - } - } -} - -void __stdcall TaskQueuePortImpl::SuspendPort() -{ -#ifdef _WIN32 - std::lock_guard lock(m_lock); -#endif - m_suspended = true; -#ifdef _WIN32 - InvalidateWaitEpochLocked(); -#endif -} - -void __stdcall TaskQueuePortImpl::ResumePort() -{ - // Before we resume the port iterate over both the - // pending list and the termination list and count - // how many notifies we need. Because of the lock - // free nature of the queue establishing a count - // takes some effort. - - uint64_t address; - size_t notifyCount = 0; -#ifndef _WIN32 - QueueEntry queueEntry; - LocklessQueue retainEntries(*(m_pendingList.get())); - - while (m_queueList->pop_front(queueEntry, address)) - { - notifyCount++; - retainEntries.push_back(std::move(queueEntry), address); - } - - while (retainEntries.pop_front(queueEntry, address)) - { - m_queueList->push_back(std::move(queueEntry), address); - } -#endif - - { - std::lock_guard lock(m_terminationLock); - TerminationEntry* terminationEntry; - LocklessQueue retainTerminations(*(m_terminationList.get())); - - while (m_terminationList->pop_front(terminationEntry, address)) - { - notifyCount++; - retainTerminations.push_back(std::move(terminationEntry), address); - } - - while (retainTerminations.pop_front(terminationEntry, address)) - { - m_terminationList->push_back(std::move(terminationEntry), address); - } - } - -#ifdef _WIN32 - { - std::lock_guard lock(m_lock); - m_suspended = false; - InvalidateWaitEpochLocked(); - notifyCount += m_readyEntries.load(); - } -#else - m_suspended = false; -#endif - - while (notifyCount) - { - SignalQueue(); - NotifyItemQueued(); - notifyCount--; - } -} - -HRESULT TaskQueuePortImpl::VerifyNotTerminated( - _In_ ITaskQueuePortContext* portContext) -{ - // N.B. This looks wrong but it's not. We only error adding new items - // if we are terminating or terminated. If we're just canceled we allow - // new items in but we invoke them with the canceled flag set to true. - RETURN_HR_IF(E_ABORT, portContext->GetStatus() > TaskQueuePortStatus::Canceled); - return S_OK; -} - -bool TaskQueuePortImpl::IsCallCanceled(_In_ const QueueEntry& entry) -{ - return entry.portContext->GetStatus() != TaskQueuePortStatus::Active; -} - -// Appends the given entry to the active queue. The entry should already -// be add-refd. This will return false on failure. -bool TaskQueuePortImpl::AppendEntry( - _In_ const QueueEntry& entry, - _In_opt_ uint64_t node) -{ -#ifdef _WIN32 - if (node == 0 && !m_queueList->reserve_node(node)) return false; - ++m_readyEntries; - m_queueList->push_back(entry, node); -#else - if (node != 0) - { - m_queueList->push_back(entry, node); - } - else if (!m_queueList->push_back(entry)) - { - return false; - } - -#endif - - SignalQueue(); - NotifyItemQueued(); - - return true; -} - -void TaskQueuePortImpl::CancelPendingEntries( - _In_ ITaskQueuePortContext* portContext, - _In_ bool appendToQueue) -{ - // Only move entries owned by the terminating queue. Sibling delegates - // share this port's delayed-callback timer state, so leave m_timer and - // m_timerDue alone; if we removed the armed earliest entry, the existing - // timer simply takes one blank fire and re-arms for the next real item. - // - // Lifetime: every caller holds its own reference on portContext (and so on - // its queue, which keeps this port alive), so the entry releases below are - // never the final release and this port and portContext stay valid for - // the rest of the function. Still free each node before releasing its - // reference so nothing touches the port after a release. - LocklessQueue entriesToAppend(*m_queueList.get()); - - m_pendingList->remove_if([&](auto& entry, auto address) - { - if (entry.portContext == portContext) - { - if (appendToQueue) - { - entriesToAppend.push_back(std::move(entry), address); - } - else - { - m_pendingList->free_node(address); - entry.portContext->Release(); - } - - return true; - } - - return false; - }); - - while (appendToQueue) - { - QueueEntry entry = {}; - uint64_t address = 0; - if (!entriesToAppend.pop_front(entry, address)) - { - break; - } - - if (!AppendEntry(entry, address)) - { - m_queueList->free_node(address); - entry.portContext->Release(); - } - } - - // Test hook: let unit tests enqueue a sibling delayed callback while this - // termination path still owns the interleaving window that used to race - // with SubmitPendingCallbacks(). - if (auto hooks = portContext->GetQueue()->GetTestHooks(); hooks != nullptr) - { - hooks->PendingEntriesRemovedDuringTermination(portContext->GetType()); - } - - // We may have just removed the pending entry that the shared delayed-callback - // timer was armed for (a composite that shares this port can terminate while - // it still owns the armed-earliest entry). Relying on a "blank fire" of the - // now-orphaned deadline to re-arm is fragile under the STL timer backend, so - // re-point the timer at the earliest surviving pending entry directly. - RearmTimerForEarliestPending(); - -#ifdef _WIN32 - - StaticArray, PORT_WAIT_MAX> retired; - referenced_ptr discarded[PORT_WAIT_MAX]; - uint32_t notifications = 0; - { - std::lock_guard lock(m_lock); - for (auto it = m_waits.begin(); it != m_waits.end();) - { - auto& reg = it->second; - if (reg->queueEntry.portContext != portContext || - reg->state != WaitRegistration::State::Active) - { - ++it; - continue; - } - - retired.append(reg); - if (appendToQueue && !reg->appended) - { - uint64_t node = reg->cancelNode; - reg->cancelNode = 0; - if (PublishWaitEntryLocked(reg.get(), node)) ++notifications; - } - RetireWaitLocked(reg.get(), appendToQueue ? - WaitRegistration::State::Canceled : WaitRegistration::State::Removed); - if (!appendToQueue && reg->queuedContext) - { - discarded[retired.count() - 1] = std::move(reg->queuedContext); - --m_readyEntries; - } - ++it; // Keep the token discoverable through native drainage. - } - } - - for (uint32_t i = 0; i < retired.count(); ++i) - DrainRetiredWait(retired[i]); - if (retired.count()) SignalQueue(); - for (uint32_t i = 0; i < notifications; ++i) NotifyItemQueued(); -#endif -} - -// After cancellation removed pending entries, re-point the shared timer at the -// earliest surviving pending entry instead of leaving it armed for a deadline -// whose entry was just removed. Without this, a composite that shares this -// port's timer can terminate while owning the armed-earliest entry, leaving the -// timer pointed at an orphaned deadline; if the orphaned fire is lost (STL timer -// backend), the remaining delayed callbacks never run and the queue starves. -// -// Only called from CancelPendingEntries, whose callers keep this port alive -// (see there), so releasing the temporary nextItem reference below can never -// destroy this port even if it is the last reference to a sibling queue. -void TaskQueuePortImpl::RearmTimerForEarliestPending() -{ - while (true) - { - // Snapshot before scanning so a concurrent QueueItem publish makes the - // compare-exchange below fail instead of being overwritten. - uint64_t currentDue = m_timerDue.load(); - QueueEntry nextItem = {}; - bool hasNextItem = false; - - // Read-only scan: keep every entry (return false), tracking the earliest. - m_pendingList->remove_if([&](auto& entry, auto /*address*/) - { - if (!hasNextItem || nextItem.enqueueTime > entry.enqueueTime) - { - if (hasNextItem) - { - nextItem.portContext->Release(); - } - - nextItem = entry; - nextItem.portContext->AddRef(); - hasNextItem = true; - } - - return false; - }); - - if (hasNextItem) - { - bool timerStable = true; - bool movedTimerLater = false; - if (nextItem.enqueueTime < currentDue) - { - // Surviving entry is earlier than the armed deadline: min-wins arm. - timerStable = ArmTimerIfEarlier(nextItem.enqueueTime); - } - else if (nextItem.enqueueTime > currentDue) - { - // The armed deadline belonged to a removed entry; advance the timer - // to the earliest surviving deadline using the same verified helper - // the fire path uses (handles a concurrent earlier publish safely). - timerStable = ArmTimerForNextPendingDueTime(currentDue, nextItem.enqueueTime); - movedTimerLater = timerStable; - } - - nextItem.portContext->Release(); - - if (!timerStable) - { - continue; - } - - // A submission can land after the scan while the old, earlier due - // time is still published. Once we move that due time later, scan - // again to catch the intermediate entry. Repeat after every actual - // deadline advance until a scan reaches a fixed point. - if (movedTimerLater) - { - continue; - } - - return; - } - - if (currentDue == UINT64_MAX) - { - return; - } - - // No pending entries remain on any attached context; let the timer go - // idle. Mirrors the no-next-item branch of PromoteReadyPendingCallbacks - // (CAS only, never Cancel(), to avoid racing concurrent Start calls). - if (!m_timerDue.compare_exchange_strong(currentDue, UINT64_MAX)) - { - continue; - } - - // A callback can be queued after the scan while currentDue still names - // the removed entry. Rescan once after publishing the idle sentinel so - // that callback is either found here or arms itself against UINT64_MAX. - continue; - } -} - -void TaskQueuePortImpl::EraseQueue( - _In_opt_ LocklessQueue* queue) -{ - if (queue != nullptr) - { - QueueEntry entry; - - while(queue->pop_front(entry)) - { -#ifdef _WIN32 - if (entry.waitRegistration) - { - entry.waitRegistration->Release(); - continue; - } -#endif - entry.portContext->Release(); - } - } -} - -// Arms the OS timer for dueTime using min-wins CAS with post-Start -// verification. If another thread publishes an earlier deadline between -// our CAS and Start, we detect the overwrite and re-arm. This closes the -// TOCTOU window that could strand a pending entry. -// -// Uses <= so callers needing to re-arm for an already-published deadline -// (e.g. SubmitPendingCallbacks on an early timer fire) go through the -// same verified path. -// -// Returns true when the timer is stable (armed at or before dueTime, or -// dueTime is UINT64_MAX). Returns false if m_timerDue moved later (entry -// was promoted), signaling the caller to re-evaluate. -bool TaskQueuePortImpl::ArmTimerIfEarlier(uint64_t dueTime) -{ - while (true) - { - uint64_t currentDue = m_timerDue.load(); - - if (dueTime <= currentDue) - { - if (dueTime == UINT64_MAX) - { - return true; // Nothing to arm. - } - - if (m_timerDue.compare_exchange_weak(currentDue, dueTime)) - { - m_timer.Start(dueTime); - - // Post-Start verification: did m_timerDue change between - // our CAS and Start? If not, the timer is correctly armed. - uint64_t afterDue = m_timerDue.load(); - if (afterDue == dueTime) - { - return true; // Unchanged — timer correctly armed. - } - - if (afterDue < dueTime) - { - // An earlier deadline was published. Our Start may - // have overwritten a concurrent arm. Fix it. - dueTime = afterDue; - continue; - } - - // m_timerDue moved later (e.g. UINT64_MAX from promotion). - // Our entry was already handled. Caller should re-evaluate. - return false; - } - // CAS failed (concurrent modification). Retry with fresh read. - continue; - } - - // An earlier deadline is already published; the timer is already - // armed for it or another thread is in the process of arming it - // (with their own post-Start verification). - return true; - } -} - -// Replaces the due time that just fired with the next surviving future -// deadline. Unlike ArmTimerIfEarlier, this helper is allowed to move the -// published due time later, but only while the caller's observed due time is -// still current. If another thread already published an earlier/equal -// deadline, leave it alone. Returns false when the published due time moved -// later after Start(), signaling the caller to rescan the pending list. -bool TaskQueuePortImpl::ArmTimerForNextPendingDueTime( - uint64_t previousDueTime, - uint64_t nextDueTime) -{ - while (true) - { - if (m_timerDue.compare_exchange_strong(previousDueTime, nextDueTime)) - { - m_timer.Start(nextDueTime); - - uint64_t afterDue = m_timerDue.load(); - if (afterDue == nextDueTime) - { - return true; - } - - if (afterDue < nextDueTime) - { - // Our Start may have overwritten the earlier publisher's Start. - // Re-arm the currently published deadline so the final OS timer - // programming always agrees with m_timerDue. - return ArmTimerIfEarlier(afterDue); - } - - return false; - } - - // CAS failed: compare_exchange loaded the current m_timerDue into - // previousDueTime. If that value is already <= nextDueTime, the - // timer is armed for an earlier-or-equal deadline and we're done. - if (previousDueTime <= nextDueTime) - { - return true; - } - } -} - -// Re-arms the exact due time observed by an early/stale timer callback. -// If another thread has already consumed that due time and moved m_timerDue -// later (including to UINT64_MAX), the observed due is stale and the caller -// must re-evaluate instead of resurrecting it. -bool TaskQueuePortImpl::RearmTimerIfDueTimeUnchanged(uint64_t dueTime) -{ - // UINT64_MAX is the "nothing armed" sentinel and must never be programmed - // as a real deadline (see SubmitPendingCallbacks). Mirrors the guard in - // ArmTimerIfEarlier. - if (dueTime == UINT64_MAX) - { - return true; - } - - while (true) - { - uint64_t currentDue = m_timerDue.load(); - - if (currentDue < dueTime) - { - return true; - } - - if (currentDue > dueTime) - { - return false; - } - - if (m_timerDue.compare_exchange_weak(currentDue, dueTime)) - { - m_timer.Start(dueTime); - - uint64_t afterDue = m_timerDue.load(); - if (afterDue == dueTime) - { - return true; - } - - if (afterDue < dueTime) - { - dueTime = afterDue; - continue; - } - - return false; - } - } -} - -// Promote every pending callback whose deadline has arrived, then arm the -// timer for the earliest remaining future deadline. Sweeping all -// enqueueTime <= now avoids treating timestamps as unique identities, so -// equal-deadline siblings and stale timer callbacks follow the same rule. -void TaskQueuePortImpl::PromoteReadyPendingCallbacks( - _In_ uint64_t dueTime, - _In_ uint64_t now) -{ - // Releasing a port context can drop the last reference to its queue, and the queue owns this - // port. On the STL WaitTimer that release happens right here on the timer thread, so the port - // (including m_queueList, which readyEntries below shares) would be destroyed while this - // function is still using it (AddressSanitizer heap-use-after-free). Hand every reference this - // function would release to this holder instead. Any held context keeps its queue, and so this - // port, alive; the holder is declared before the loop, so the last release happens after every - // other local (readyEntries) is gone and nothing touches the port afterwards. - struct DeferredPortContextRelease - { - ITaskQueuePortContext* held = nullptr; - - void Hold(_In_ ITaskQueuePortContext* portContext) noexcept - { - ITaskQueuePortContext* previous = held; - held = portContext; - if (previous != nullptr) - { - previous->Release(); // safe: 'held' keeps the port alive - } - } - - ~DeferredPortContextRelease() - { - if (held != nullptr) - { - held->Release(); - } - } - } deferredRelease; - - for (;;) - { - // Collect due entries locally first and only touch the active queue - // after remove_if completes. Keeping the sweep phase and the publish - // phase separate preserves the "promote all ready entries" behavior - // without asking remove_if to coexist with queue wakeups and - // cross-queue node reuse at the same time. - LocklessQueue readyEntries(*m_queueList.get()); - - QueueEntry nextItem = {}; - bool hasNextItem = false; - - m_pendingList->remove_if([&](auto& entry, auto address) - { - // Any entry whose deadline has passed is ready right now, - // regardless of whether its timestamp aliases another entry or - // whether this timer fire is the original notification or a - // stale callback that arrived late. - if (entry.enqueueTime <= now) - { - readyEntries.push_back(std::move(entry), address); - - return true; - } - - if (!hasNextItem || nextItem.enqueueTime > entry.enqueueTime) - { - // remove_if works by removing items from the list and - // re-adding them if this callback returns false. If we - // are going to keep an item beyond this callback we need - // to make sure fields we're using stay valid. Only the - // port context is a risk. - - if (hasNextItem) - { - nextItem.portContext->Release(); - } - - nextItem = entry; - nextItem.portContext->AddRef(); - hasNextItem = true; - } - - return false; - }); - - // Publish the ready entries after the pending-list walk finishes. - QueueEntry readyEntry = {}; - uint64_t readyEntryNode = 0; - while (readyEntries.pop_front(readyEntry, readyEntryNode)) - { - if (!AppendEntry(readyEntry, readyEntryNode)) - { - m_queueList->free_node(readyEntryNode); - deferredRelease.Hold(readyEntry.portContext); - } - } - - if (hasNextItem) - { - bool timerAdvanced = false; - if (nextItem.portContext->GetStatus() == TaskQueuePortStatus::Active) - { - if (nextItem.enqueueTime != dueTime) - { - VisitAttachedContexts([&](ITaskQueuePortContext* portContext) - { - auto hooks = portContext->GetQueue()->GetTestHooks(); - if (hooks != nullptr) - { - hooks->NextPendingCallbackFound( - portContext->GetType(), - dueTime, - nextItem.enqueueTime); - } - }); - } - - // A rescue scan that finds the deadline it just published has - // reached a fixed point. Otherwise replace the fired due time - // with the earliest future deadline that survived the sweep. - if (nextItem.enqueueTime != dueTime && - !ArmTimerForNextPendingDueTime(dueTime, nextItem.enqueueTime)) - { - deferredRelease.Hold(nextItem.portContext); - now = m_timer.GetCurrentTime(); - dueTime = m_timerDue.load(); - continue; - } - timerAdvanced = nextItem.enqueueTime != dueTime; - } - else - { - // The port is no longer active. Pending entries are canceled - // when the port is terminated, but if we were iterating above - // it's possible that we removed an item while the termination - // was being processed and it got missed. - CancelPendingEntries(nextItem.portContext, true); - } - - deferredRelease.Hold(nextItem.portContext); - - // A callback can be inserted after the scan while the fired due - // time is still published. It will not arm itself if its deadline - // falls between dueTime and nextItem.enqueueTime, so rescan after - // every successful advance until a scan reaches a fixed point. - // Later submissions see the advanced deadline and arm themselves. - if (timerAdvanced) - { - now = m_timer.GetCurrentTime(); - dueTime = m_timerDue.load(); - continue; - } - - return; - } - - // No future entries remain in the pending list. - uint64_t noDueTime = UINT64_MAX; - - VisitAttachedContexts([&](ITaskQueuePortContext* portContext) - { - auto hooks = portContext->GetQueue()->GetTestHooks(); - if (hooks != nullptr) - { - hooks->NoNextPendingCallbackFound( - portContext->GetType(), - dueTime); - } - }); - - if (m_timerDue.compare_exchange_strong(dueTime, noDueTime)) - { - // Bug fix: ScheduleNextPendingCallback timer race results - // in lost delayed task wakes. Don't cancel the timer here - // as another scheduled callback could have been added. - // The CAS above is sufficient: the timer has already fired - // (call site 1: SubmitPendingCallbacks) or was already - // canceled (call site 2: CancelPendingEntries). A Cancel() - // here raced with concurrent QueueItem/Start calls on other - // threads, permanently stranding entries in m_pendingList. - // See VerifyDelayedCallbackTimerRaceOnManualQueue for full - // analysis. The test hook here allows unit tests to verify - // there is no race. - VisitAttachedContexts([&](ITaskQueuePortContext* portContext) - { - auto hooks = portContext->GetQueue()->GetTestHooks(); - if (hooks != nullptr) { - hooks->NextPendingCallbackScheduled( - portContext->GetType(), - dueTime, - noDueTime); - } - }); - - // A concurrent QueueItem can append a future entry after our - // sweep has already concluded there is no next item, but before - // we publish UINT64_MAX here. Instead of recursing (which has - // no tail-call guarantee and risks stack growth under sustained - // contention), loop back for a rescue sweep. If nothing landed, - // the second pass is a cheap no-op. - if (dueTime != noDueTime) - { - now = m_timer.GetCurrentTime(); - dueTime = noDueTime; - continue; - } - } - - return; - } -} - -void TaskQueuePortImpl::SubmitPendingCallbacks() -{ - while (true) - { - uint64_t dueTime = m_timerDue.load(); - - // UINT64_MAX is the "nothing armed" sentinel. It must never be programmed - // as a real deadline: WaitTimer::Start(UINT64_MAX) converts to a duration - // of -1 (before the steady_clock epoch), a perpetually-past deadline that - // fires immediately and re-arms the sentinel in an infinite loop, starving - // every real pending callback. If the timer is disarmed there is nothing - // to sweep, so return. - if (dueTime == UINT64_MAX) - { - return; - } - - // Timer callbacks are advisory: a threadpool fire can arrive after - // retargeting, or slightly before the steady-clock deadline due to - // clock-source differences on Win32. If the deadline hasn't arrived, - // re-arm the same published due time rather than silently dropping the - // callback (which would strand the pending entry). - const uint64_t now = m_timer.GetCurrentTime(); - if (now < dueTime) - { - if (RearmTimerIfDueTimeUnchanged(dueTime)) - { - return; - } - continue; - } - - PromoteReadyPendingCallbacks(dueTime, now); - return; - } -} - -// Called from thread pool callback -void TaskQueuePortImpl::ProcessThreadPoolCallback(_In_ OS::ThreadPoolActionStatus& status) -{ - if (m_dispatchMode == XTaskQueueDispatchMode::SerializedThreadPool) - { - uint32_t wasProcessing = m_processingSerializedTbCallback++; - - if (wasProcessing == 0) - { - // Skipped workers leave their notifications counted for the owner. - // Short-circuiting decrements the count only after an empty drain. - // Decrementing to zero atomically releases ownership: a notification - // before release forces another drain; one after release acquires - // ownership. - while (DrainOneItem(status) || --m_processingSerializedTbCallback != 0); - } - } - else - { - DrainOneItem(status); - } - - // Important that this comes before Release; otherwise - // cleanup may deadlock. - status.Complete(); - - // When we submitted a request to the thread pool we - // added a reference to ourself. Balance it here. This - // may be the final release. - Release(); -} - -void TaskQueuePortImpl::SignalQueue() -{ - if (!m_suspended) - { -#ifdef _WIN32 - SetEvent(m_queueEvent); -#else - std::unique_lock lock(m_lock); - m_signaled = true; - m_event.notify_all(); -#endif - } -} - -void TaskQueuePortImpl::NotifyItemQueued() -{ - // If this is an immediate queue, ignore suspends as - // we need to dispatch synchronously as part of the call. - - if (!m_suspended || m_dispatchMode == XTaskQueueDispatchMode::Immediate) - { - switch (m_dispatchMode) - { - case XTaskQueueDispatchMode::Manual: - // nothing - break; - - case XTaskQueueDispatchMode::SerializedThreadPool: - case XTaskQueueDispatchMode::ThreadPool: - // Addref before submitting to the thread pool in case we - // are released while there there are outstanding threadpool - // items. The threadpool does not cancel outstanding callbacks - // on termination so we need to drain before releasing. - AddRef(); - m_threadPool.Submit(); - break; - - case XTaskQueueDispatchMode::Immediate: - // We will handle this after we invoke - // callback submitted. - break; - } - - VisitAttachedContexts([](ITaskQueuePortContext* portContext) - { - portContext->ItemQueued(); - }); - - // If the queue is immediate, drain the newly queued item - // now. - - if (m_dispatchMode == XTaskQueueDispatchMode::Immediate) - { - DrainOneItem(); - } - } -} - -void TaskQueuePortImpl::SignalTerminations() -{ - // Collect entries to process outside the iteration to avoid concurrent modification races - // when callbacks invoke nested Terminate() calls. - // Use a temporary list sharing the same heap to avoid allocation. - LocklessQueue entries_to_process(*m_terminationList.get()); - - { - std::lock_guard lock(m_terminationLock); - m_terminationList->remove_if([&entries_to_process](auto& entry, auto address) - { - if (entry->portContext->GetStatus() >= TaskQueuePortStatus::Terminating) - { - entry->portContext->SetStatus(TaskQueuePortStatus::Terminated); - entries_to_process.push_back(entry, address); - return true; - } - - return false; - }); - } - -#ifdef _WIN32 - if (!entries_to_process.empty()) - { - std::lock_guard lock(m_lock); - InvalidateWaitEpochLocked(); - } -#endif - - // Now process callbacks outside the remove_if iteration - // This prevents races when callbacks invoke nested operations like Terminate() - TerminationEntry* entry; - uint64_t address; - while (entries_to_process.pop_front(entry, address)) - { - // AddRef portContext to prevent UAF if callback releases the queue - auto context = entry->portContext; - context->AddRef(); - - entry->callback(entry->callbackContext); - - { - std::lock_guard lock(m_terminationLock); - m_terminationList->free_node(address); - } - - delete entry; - context->Release(); - } -} - -void TaskQueuePortImpl::ScheduleTermination( - _In_ TerminationEntry* term) -{ - // Insert the termination callback into the queue. Even if the - // main queue is empty, we still signal it and run through - // a cycle. This ensures we flush the queue out with no - // races and that the termination callback happens on the right - // thread. - - // This never fails because we preallocate the - // list node. - { - std::lock_guard lock(m_terminationLock); - m_terminationList->push_back(term, term->node); - term->node = 0; // now owned by the list - } - - // The port should have already been marked as terminated, so now - // we can signal it to wake up. This should drain pending calls and - // invoke the termination callback we just pushed. - - SignalQueue(); - NotifyItemQueued(); -} - -bool TaskQueuePortImpl::TerminationListEmpty() -{ - std::lock_guard lock(m_terminationLock); - return m_terminationList->empty(); -} - -#ifdef _WIN32 -void TaskQueuePortImpl::InvalidateWaitEpochLocked() -{ - // Never reset or reuse a signaled event. A late waiter on the previous - // snapshot still observes it even if a new epoch already exists. - if (m_waitEpoch) - { - SetEvent(m_waitEpoch->handle); - m_waitEpoch.reset(); - } -} - -void TaskQueuePortImpl::CaptureWaitSnapshot(WaitSnapshot& snapshot) -{ - snapshot.events.append(m_queueEvent); - std::lock_guard lock(m_lock); - static_assert(PORT_EVENT_MAX <= MAXIMUM_WAIT_OBJECTS); - if (!m_waitEpoch) - { - try - { - auto epoch = std::make_shared(); - epoch->handle = CreateEventW(nullptr, TRUE, FALSE, nullptr); - if (epoch->handle) m_waitEpoch = std::move(epoch); - } - catch (const std::bad_alloc&) - { - // Wait() uses bounded polling until an epoch can be allocated. - } - } - snapshot.epoch = m_waitEpoch; - for (const auto& item : m_waits) - { - if (!m_suspended && item.second->state == WaitRegistration::State::Active) - { - snapshot.registrations.append(item.second); - snapshot.owners.append(item.second->handleOwner); - snapshot.events.append(item.second->handleOwner->handle); - } - } - if (snapshot.epoch) snapshot.events.append(snapshot.epoch->handle); -} - -void CALLBACK TaskQueuePortImpl::WaitCallback( - _In_ PTP_CALLBACK_INSTANCE instance, - _Inout_opt_ void* context, - _Inout_ PTP_WAIT wait, - _In_ TP_WAIT_RESULT waitResult) -{ - UNREFERENCED_PARAMETER(wait); - if (waitResult != WAIT_OBJECT_0 || !context) return; - - // Retirement holds the registration through WaitForThreadpoolWaitCallbacks. - // Acquire independent owners before allowing a reentrant close to finish. - referenced_ptr port; - referenced_ptr reg(static_cast(context)); - if (!reg->port->TryAddRef()) return; - *port.address_of() = reg->port; - DisassociateCurrentThreadFromCallback(instance); - port->ProcessWaitCallback(reg.get()); -} - -TaskQueuePortImpl::WaitRegistration::~WaitRegistration() -{ - ASSERT(cancelNode == 0); - if (threadpoolWait) CloseThreadpoolWait(threadpoolWait); // Unarmed registration failure. -} - -DefaultUnnamedMutex TaskQueuePortImpl::WaitCallbackFrame::lock; -TaskQueuePortImpl::WaitCallbackFrame* TaskQueuePortImpl::WaitCallbackFrame::head = nullptr; - -TaskQueuePortImpl::WaitCallbackFrame::WaitCallbackFrame(WaitRegistration* registration) : reg(registration) -{ - std::lock_guard guard(lock); - link = &head; - next = head; - if (next) next->link = &next; - head = this; -} - -TaskQueuePortImpl::WaitCallbackFrame::~WaitCallbackFrame() -{ - std::lock_guard guard(lock); - *link = next; - if (next) next->link = link; -} - -bool TaskQueuePortImpl::WaitCallbackFrame::ConfirmEntry() -{ - // Only the indirect user call is inside a frame. Synchronous reentry from - // that call witnesses physical entry, including its enclosing callbacks. - ULONG_PTR low, high; - GetCurrentThreadStackLimits(&low, &high); - // A fiber can suspend its callback and resume on a different thread. - // Identify the currently executing stack rather than reusing a thread ID. - std::lock_guard guard(lock); - bool reentrant = false; - for (auto* frame = head; frame; frame = frame->next) - { - const auto address = reinterpret_cast(frame); - if (address < low || address >= high) continue; - reentrant = true; - auto* reg = frame->reg; - std::lock_guard lock(reg->port->m_lock); - reg->enteredUserCode = true; - reg->port->m_waitFinished.notify_all(); - } - return reentrant; -} - -void TaskQueuePortImpl::DrainRetiredWait(const referenced_ptr& reg) -{ - // Every participant owns a reference. The first caller drains outside the - // port lock; associated callbacks have no dependency on user code here. - std::call_once(reg->drainOnce, [&] { - WaitForThreadpoolWaitCallbacks(reg->threadpoolWait, TRUE); - CloseThreadpoolWait(reg->threadpoolWait); - std::lock_guard lock(m_lock); - reg->threadpoolWait = nullptr; - reg->handleOwner.reset(); - reg->drained = true; - FinishRetirementLocked(reg.get()); - m_waitFinished.notify_all(); - }); -} - -void TaskQueuePortImpl::FinishRetirementLocked(WaitRegistration* reg) -{ - if (!reg->drained || reg->queuedContext || reg->running) return; - // The registration owns the token table independently of the queue. - // Public lookup drops the table lock before entering the port. - if (reg->publicRegistry) - { - reg->publicRegistry->Remove(reg->publicToken); - reg->publicRegistry.reset(); - } - m_waits.erase(reg->token); -} - -void TaskQueuePortImpl::RetireWaitLocked(WaitRegistration* reg, WaitRegistration::State state) -{ - const bool wasActive = reg->state == WaitRegistration::State::Active; - reg->state = state; - if (wasActive) - { - SetThreadpoolWait(reg->threadpoolWait, nullptr, nullptr); - --m_activeWaits; - if (reg->cancelNode) - { - m_queueList->free_node(reg->cancelNode); - reg->cancelNode = 0; - } - InvalidateWaitEpochLocked(); - } -} - -bool TaskQueuePortImpl::PublishWaitEntryLocked(WaitRegistration* reg, uint64_t node) -{ - // The node is already reserved. Keep its context pin revocable until - // dispatch claims it, so unregister can release an undispatched queue. - ASSERT(node != 0); - if (!reg->pinnable->TryPin()) - { - m_queueList->free_node(node); - return false; - } - *reg->queuedContext.address_of() = reg->queueEntry.portContext; // Adopt TryPin. - reg->AddRef(); - reg->appended = true; - ++m_readyEntries; - m_queueList->push_back(reg->queueEntry, node); - return true; -} - -void TaskQueuePortImpl::ProcessWaitCallback(WaitRegistration* reg) -{ - { - std::lock_guard lock(m_lock); - if (reg->state != WaitRegistration::State::Active || reg->appended) return; - uint64_t node = 0; - if (!m_queueList->reserve_node(node)) - { - SetThreadpoolWait(reg->threadpoolWait, reg->handleOwner->handle, nullptr); - return; - } - if (!PublishWaitEntryLocked(reg, node)) return; - } - SignalQueue(); - NotifyItemQueued(); -} - -bool TaskQueuePortImpl::DispatchWaitEntry(const QueueEntry& entry, OS::ThreadPoolActionStatus& status, - referenced_ptr& context) -{ - referenced_ptr reg; - *reg.address_of() = entry.waitRegistration; // Adopt the popped entry's ref. - { - std::lock_guard lock(m_lock); - if (reg->state == WaitRegistration::State::Removed) return false; - context = std::move(reg->queuedContext); - --m_readyEntries; - reg->running = true; - reg->enteredUserCode = false; - } - - if (context->GetType() == XTaskQueuePort::Work) status.MayRunLong(); - const bool canceled = IsCallCanceled(entry); - { - WaitCallbackFrame frame(reg.get()); - entry.callback(entry.callbackContext, canceled); - } - - { - std::lock_guard lock(m_lock); - reg->running = false; - reg->appended = false; - if (reg->state == WaitRegistration::State::Active) - SetThreadpoolWait(reg->threadpoolWait, reg->handleOwner->handle, nullptr); - else - FinishRetirementLocked(reg.get()); - } - m_waitFinished.notify_all(); - return true; -} - -#endif - -// -// TaskQueuePortContextImpl -// - -TaskQueuePortContextImpl::TaskQueuePortContextImpl( - _In_ TaskQueueImpl* queue, - _In_ XTaskQueuePort type, - _In_ SubmitCallback* submitCallback) : - m_queue(queue), - m_type(type), - m_submitCallback(submitCallback) -{ -} - -bool TaskQueuePortContextImpl::TryPin() noexcept -{ - return m_queue->TryAddRef(); -} -uint32_t __stdcall TaskQueuePortContextImpl::AddRef() -{ - return m_queue->AddRef(); -} - -uint32_t __stdcall TaskQueuePortContextImpl::Release() -{ - return m_queue->Release(); -} - -HRESULT __stdcall TaskQueuePortContextImpl::QueryApi(_In_ ApiId id, _Out_ void** ptr) -{ - if (ptr == nullptr) - { - return E_POINTER; - } - - *ptr = nullptr; - - if (id == TaskQueueInternal::kPinnableContextApiId) - { - // This concrete implementation can safely identify itself. - // The caller owns one reference, just like other QueryApi results. - *ptr = static_cast(this); - AddRef(); - return S_OK; - } - - if (id == ApiId::Identity || id == ApiId::TaskQueuePortContext) - { - *ptr = static_cast(this); - AddRef(); - return S_OK; - } - - return E_NOINTERFACE; -} - -XTaskQueuePort __stdcall TaskQueuePortContextImpl::GetType() -{ - return m_type; -} - -TaskQueuePortStatus __stdcall TaskQueuePortContextImpl::GetStatus() -{ - return m_status; -} - -ITaskQueue* __stdcall TaskQueuePortContextImpl::GetQueue() -{ - return m_queue; -} - -ITaskQueuePort* __stdcall TaskQueuePortContextImpl::GetPort() -{ - return Port.get(); -} - -bool __stdcall TaskQueuePortContextImpl::TrySetStatus( - _In_ TaskQueuePortStatus expectedStatus, - _In_ TaskQueuePortStatus status) -{ - return m_status.compare_exchange_strong(expectedStatus, status); -} - -void __stdcall TaskQueuePortContextImpl::SetStatus( - _In_ TaskQueuePortStatus status) -{ - m_status = status; -} - -void __stdcall TaskQueuePortContextImpl::ItemQueued() -{ - m_submitCallback->Invoke(m_type); -} - -bool __stdcall TaskQueuePortContextImpl::AddSuspend() -{ - return (m_suspendCount.fetch_add(1) == 0); -} - -bool __stdcall TaskQueuePortContextImpl::RemoveSuspend() -{ - for(;;) - { - uint32_t current = m_suspendCount.load(); - - // These should always be balanced and there is no - // valid case where this should happen, even - // for multiple threads racing. - - if (current == 0) - { - ASSERT(false); - return true; - } - - if (m_suspendCount.compare_exchange_weak(current, current -1)) - { - return current == 1; - } - } -} - -// -// TaskQueueImpl -// - -TaskQueueImpl::TaskQueueImpl() : - Api(), - m_callbackSubmitted(&m_header), - m_work(this, XTaskQueuePort::Work, &m_callbackSubmitted), - m_completion(this, XTaskQueuePort::Completion, &m_callbackSubmitted) -{ - m_header.m_signature = TASK_QUEUE_SIGNATURE; - m_header.m_runtimeIteration = GetCurrentRuntimeIteration(); - m_header.m_queue = this; - m_termination.terminated = false; -} - -TaskQueueImpl::~TaskQueueImpl() -{ - // Zero the header so we get an early warning of using - // a released object. - m_header = {}; -} - -HRESULT TaskQueueImpl::Initialize( - _In_ XTaskQueueDispatchMode workMode, - _In_ XTaskQueueDispatchMode completionMode) -{ - RETURN_IF_NULL_ALLOC(m_waitRegistry.get()); - referenced_ptr work(new (std::nothrow) TaskQueuePortImpl); - RETURN_IF_NULL_ALLOC(work); - RETURN_IF_FAILED(work->Initialize(workMode)); - - referenced_ptr completion(new (std::nothrow) TaskQueuePortImpl); - RETURN_IF_NULL_ALLOC(completion); - RETURN_IF_FAILED(completion->Initialize(completionMode)); - - work->GetHandle()->m_queue = this; - completion->GetHandle()->m_queue = this; - - RETURN_IF_FAILED(work->QueryApi(ApiId::TaskQueuePort, (void**)&m_work.Port)); - RETURN_IF_FAILED(completion->QueryApi(ApiId::TaskQueuePort, (void**)&m_completion.Port)); - - RETURN_IF_FAILED(m_work.Port->Attach(&m_work)); - RETURN_IF_FAILED(m_completion.Port->Attach(&m_completion)); - -#ifdef SUSPEND_API - RETURN_IF_FAILED(m_suspendHandler.Initialize(ProcessGlobals::g_suspendState, this)); -#endif - - return S_OK; -} - -HRESULT TaskQueueImpl::Initialize( - _In_ XTaskQueuePortHandle workPort, - _In_ XTaskQueuePortHandle completionPort) -{ - RETURN_IF_NULL_ALLOC(m_waitRegistry.get()); - RETURN_HR_IF(E_GAMERUNTIME_INVALID_HANDLE, workPort== nullptr || workPort->m_signature != TASK_QUEUE_PORT_SIGNATURE || workPort->m_runtimeIteration != GetCurrentRuntimeIteration()); - RETURN_HR_IF(E_GAMERUNTIME_INVALID_HANDLE, completionPort == nullptr || completionPort->m_signature != TASK_QUEUE_PORT_SIGNATURE || completionPort->m_runtimeIteration != GetCurrentRuntimeIteration()); - - m_work.Port = referenced_ptr(workPort->m_port); - m_completion.Port = referenced_ptr(completionPort->m_port); - m_work.Source = referenced_ptr(workPort->m_queue); - m_completion.Source = referenced_ptr(completionPort->m_queue); - - RETURN_IF_FAILED(m_work.Port->Attach(&m_work)); - RETURN_IF_FAILED(m_completion.Port->Attach(&m_completion)); - -#ifdef SUSPEND_API - RETURN_IF_FAILED(m_suspendHandler.Initialize(ProcessGlobals::g_suspendState, this)); -#endif - - return S_OK; -} - -HRESULT __stdcall TaskQueueImpl::GetPortContext( - _In_ XTaskQueuePort port, - _Out_ ITaskQueuePortContext** portContext) -{ - RETURN_HR_IF(E_POINTER, portContext == nullptr); - - switch(port) - { - case XTaskQueuePort::Work: - *portContext = &m_work; - m_work.AddRef(); - break; - - case XTaskQueuePort::Completion: - *portContext = &m_completion; - m_completion.AddRef(); - break; - - default: - RETURN_HR(E_INVALIDARG); - } - - return S_OK; -} - -HRESULT __stdcall TaskQueueImpl::RegisterWaitHandle( - _In_ XTaskQueuePort port, - _In_ HANDLE waitHandle, - _In_opt_ void* callbackContext, - _In_ XTaskQueueCallback* callback, - _Out_ XTaskQueueRegistrationToken* token) -{ - RETURN_HR_IF(E_POINTER, callback == nullptr || token == nullptr); - - XTaskQueueRegistrationToken portToken; - referenced_ptr portContext; - - RETURN_IF_FAILED(GetPortContext(port, portContext.address_of())); - RETURN_HR_IF(E_OUTOFMEMORY, !m_waitRegistry->Reserve()); - HRESULT hr; - void* capability = nullptr; - if (SUCCEEDED(portContext->GetPort()->QueryApi(TaskQueueInternal::kWaitPublicationApiId, &capability))) - { - referenced_ptr localPort; - *localPort.address_of() = static_cast(capability); - hr = localPort->RegisterWaitWithToken(portContext.get(), waitHandle, callbackContext, - callback, token, m_waitRegistry.get()); - } - else - { - // Older port implementations use the original immutable interface. - hr = portContext->GetPort()->RegisterWaitHandle( - portContext.get(), waitHandle, callbackContext, callback, &portToken); - if (SUCCEEDED(hr)) m_waitRegistry->Publish(port, portToken, token, false); - } - if (FAILED(hr)) - { - m_waitRegistry->CancelReservation(); - return hr; - } - return S_OK; -} - -void __stdcall TaskQueueImpl::UnregisterWaitHandle( - _In_ XTaskQueueRegistrationToken token) -{ - const auto registration = m_waitRegistry->Lookup(token); - if (registration.PortToken != 0) - { - referenced_ptr portContext; - if (SUCCEEDED(GetPortContext(registration.Port, portContext.address_of()))) - { - portContext->GetPort()->UnregisterWaitHandle({registration.PortToken}); - if (!registration.retiredByPort) m_waitRegistry->Remove(token); - } - } -} - -HRESULT __stdcall TaskQueueImpl::RegisterSubmitCallback( - _In_opt_ void* context, - _In_ XTaskQueueMonitorCallback* callback, - _Out_ XTaskQueueRegistrationToken* token) -{ - return m_callbackSubmitted.Register(context, callback, token); -} - -void __stdcall TaskQueueImpl::UnregisterSubmitCallback( - _In_ XTaskQueueRegistrationToken token) -{ - m_callbackSubmitted.Unregister(token); -} - -HRESULT __stdcall TaskQueueImpl::Terminate( - _In_ bool wait, - _In_opt_ void* callbackContext, - _In_opt_ XTaskQueueTerminatedCallback* callback) -{ - std::unique_ptr entry(new (std::nothrow) TerminationEntry); - RETURN_IF_NULL_ALLOC(entry); - - entry->owner = this; - entry->level = TerminationLevel::Work; - entry->context = callbackContext; - entry->callback = callback; - - void* workToken; - - RETURN_IF_FAILED(m_work.Port->PrepareTerminate(&m_work, entry.get(), OnTerminationCallback, &workToken)); - - HRESULT hr = m_completion.Port->PrepareTerminate(&m_completion, entry.get(), OnTerminationCallback, &entry->completionPortToken); - if (FAILED(hr)) - { - m_work.Port->CancelTermination(workToken); - RETURN_HR(hr); - } - - // At this point both ports have been marked for termination and have pre-alocated any state they - // need, so we can proceed with the actual termination. - - entry.release(); - - // Addref ourself to ensure we don't lose the queue to a close - // while termination is in flight. This is released on OnTerminationCallback. - // If we are waiting we will take another reference and release it - // after the wait completes. - - AddRef(); - - if (wait) - { - AddRef(); - } - - m_work.Port->Terminate(workToken); - - if (wait) - { - std::unique_lock lock(m_termination.lock); - while(!m_termination.terminated) - { - m_termination.cv.wait(lock); - } - - // Termination notify happens through a callback and when the - // terminated flag gets set that callback and other frames - // are still on the stack. Wait for them to unwind here so - // if the caller wants to exit the process there isn't code - // on the stack in another thread. - - m_work.Port->WaitForUnwind(); - m_completion.Port->WaitForUnwind(); - - Release(); - } - - return S_OK; -} - -void TaskQueueImpl::RundownObject() -{ - m_work.SetStatus(TaskQueuePortStatus::Terminated); - m_completion.SetStatus(TaskQueuePortStatus::Terminated); - -#ifdef SUSPEND_API - m_suspendHandler.Shutdown(); -#endif - - // We can be asked to rundown a partially created - // task queue, so check for nulls here. - - if (m_work.Port != nullptr) - { - m_work.Port->Detach(&m_work); - } - - if (m_completion.Port != nullptr) - { - m_completion.Port->Detach(&m_completion); - } -} - -#ifdef SUSPEND_API -void TaskQueueImpl::OnSuspendResume(_In_ bool isSuspended) -{ - if (isSuspended) - { - m_completion.GetPort()->SuspendPort(); - m_work.GetPort()->SuspendPort(); - } - else - { - m_work.GetPort()->ResumePort(); - m_completion.GetPort()->ResumePort(); - } -} -#endif - -void TaskQueueImpl::OnTerminationCallback(_In_ void* context) -{ - TerminationEntry* entry = static_cast(context); - switch(entry->level) - { - case TerminationLevel::Work: - entry->level = TerminationLevel::Completion; - entry->owner->m_completion.Port->Terminate(entry->completionPortToken); - break; - - case TerminationLevel::Completion: - if (entry->callback != nullptr) - { - entry->callback(entry->context); - } - - { - std::unique_lock lock(entry->owner->m_termination.lock); - entry->owner->m_termination.terminated = true; - entry->owner->m_termination.cv.notify_all(); - } - - entry->owner->Release(); - delete entry; - break; - - default: - ASSERT(false); - } -} - -static HRESULT CreateTaskQueueHandle( - _In_ ITaskQueue* impl, - _Out_ XTaskQueueHandle* queue) -{ - *queue = nullptr; - - std::unique_ptr q(new (std::nothrow) XTaskQueueObject); - RETURN_IF_NULL_ALLOC(q); - - q->m_signature = TASK_QUEUE_SIGNATURE; - q->m_runtimeIteration = GetCurrentRuntimeIteration(); - q->m_queue = impl; - impl->AddRef(); - - *queue = q.release(); - - SystemHandleMarkCreated(*queue); - return S_OK; -} - -/////////////////// -// XTaskQueue.h APIs -/////////////////// - -// -// Creates a Task Queue, which can be used to queue -// different calls together. -// -STDAPI XTaskQueueCreate( - _In_ XTaskQueueDispatchMode workDispatchMode, - _In_ XTaskQueueDispatchMode completionDispatchMode, - _Out_ XTaskQueueHandle* queue - ) noexcept -{ - *queue = nullptr; - - referenced_ptr aq(new (std::nothrow) TaskQueueImpl); - RETURN_IF_NULL_ALLOC(aq); - - RETURN_IF_FAILED(aq->Initialize( - workDispatchMode, - completionDispatchMode)); - - RETURN_IF_FAILED(CreateTaskQueueHandle(aq.get(), queue)); - - return S_OK; -} - -/// -/// Returns the task queue port handle for the given -/// port. Task queue port handles are owned by the -/// task queue and do not have to be closed. They are -/// used when creating composite task queues. -/// -/// The task queue to get the port from. -/// The port to get. -STDAPI XTaskQueueGetPort( - _In_ XTaskQueueHandle queue, - _In_ XTaskQueuePort port, - _Out_ XTaskQueuePortHandle* portHandle - ) noexcept -{ - referenced_ptr aq(GetQueue(queue)); - RETURN_HR_IF(E_GAMERUNTIME_INVALID_HANDLE, aq == nullptr); - - referenced_ptr portContext; - RETURN_IF_FAILED(aq->GetPortContext(port, portContext.address_of())); - - *portHandle = portContext->GetPort()->GetHandle(); - - return S_OK; -} - -/// -/// Creates a task queue composed of ports of other -/// task queue ports. A composite task queue will duplicate -/// the handles of queues that own the provided ports. -/// -/// The port to use for queuing work callbacks. -/// The port to use for queuing completion callbacks. -STDAPI XTaskQueueCreateComposite( - _In_ XTaskQueuePortHandle workPort, - _In_ XTaskQueuePortHandle completionPort, - _Out_ XTaskQueueHandle* queue - ) noexcept -{ - *queue = nullptr; - - referenced_ptr aq(new (std::nothrow) TaskQueueImpl); - RETURN_IF_NULL_ALLOC(aq); - RETURN_IF_FAILED(aq->Initialize(workPort, completionPort)); - - RETURN_IF_FAILED(CreateTaskQueueHandle(aq.get(), queue)); - - return S_OK; -} - -// -// Processes items in the task queue of the given type. If an item -// is processed this will return TRUE. If there are no items to process -// this returns FALSE. You can pass a timeout, which will cause -// XTaskQueueDispatch to wait for something to arrive in the queue. -// -STDAPI_(bool) XTaskQueueDispatch( - _In_ XTaskQueueHandle queue, - _In_ XTaskQueuePort port, - _In_ uint32_t timeoutInMs - ) noexcept -{ - referenced_ptr aq(GetQueue(queue)); - if (aq == nullptr) - { - return false; - } - - referenced_ptr portContext; - if (FAILED(aq->GetPortContext(port, portContext.address_of()))) - { - return false; - } - - return portContext->GetPort()->Dispatch(portContext.get(), timeoutInMs); -} - -// -// Returns TRUE if there is no outstanding work in this -// queue. Note this API is only used for testing and -// is not exposed outside the library. -// -STDAPI_(bool) XTaskQueueIsEmpty( - _In_ XTaskQueueHandle queue, - _In_ XTaskQueuePort port - ) noexcept -{ - referenced_ptr aq(GetQueue(queue)); - if (aq == nullptr) - { - return false; - } - - referenced_ptr portContext; - if (FAILED(aq->GetPortContext(port, portContext.address_of()))) - { - return false; - } - - return portContext->GetPort()->IsEmpty(); -} - -// -// Closes the task queue. A queue can only be closed if it -// is not in use by a task or is empty. If not true, the queue -// will be marked for closure and closed when it can. -// -STDAPI_(void) XTaskQueueCloseHandle( - _In_ XTaskQueueHandle queue - ) noexcept -{ - ITaskQueue* aq = GetQueue(queue); - - if (aq != nullptr) - { - if (USE_UNIQUE_HANDLES() && queue != aq->GetHandle()) - { - SystemHandleMarkDestroyed(queue); - - queue->m_signature = 0; - queue->m_queue = nullptr; - delete queue; - } - - aq->Release(); - } -} - -// -// Terminates a task queue by canceling all pending items and -// preventing new items from being queued. Once a queue is terminated -// its handle can be closed. -// -STDAPI XTaskQueueTerminate( - _In_ XTaskQueueHandle queue, - _In_ bool wait, - _In_opt_ void* callbackContext, - _In_opt_ XTaskQueueTerminatedCallback* callback - ) noexcept -{ - referenced_ptr aq(GetQueue(queue)); - return aq->Terminate(wait, callbackContext, callback); -} - -// -// Submits either a work or completion callback immediately. -// -STDAPI XTaskQueueSubmitCallback( - _In_ XTaskQueueHandle queue, - _In_ XTaskQueuePort port, - _In_opt_ void* callbackContext, - _In_ XTaskQueueCallback* callback - ) noexcept -{ - return XTaskQueueSubmitDelayedCallback(queue, port, 0, callbackContext, callback); -} - -// -// Submits either a work or completion callback. -// -STDAPI XTaskQueueSubmitDelayedCallback( - _In_ XTaskQueueHandle queue, - _In_ XTaskQueuePort port, - _In_ uint32_t delayMs, - _In_opt_ void* callbackContext, - _In_ XTaskQueueCallback* callback - ) noexcept -{ - referenced_ptr aq(GetQueue(queue)); - RETURN_HR_IF(E_GAMERUNTIME_INVALID_HANDLE, aq == nullptr); - - referenced_ptr portContext; - RETURN_IF_FAILED(aq->GetPortContext(port, portContext.address_of())); - - RETURN_IF_FAILED(portContext->GetPort()->QueueItem(portContext.get(), delayMs, callbackContext, callback)); - return S_OK; -} - -// -// Registers a wait handle with the task queue. When the wait handle -// is satisfied the task queue will invoke the given callback. This -// provides an efficient way to add items to a task queue in -// response to handles becoming signaled. -// -STDAPI XTaskQueueRegisterWaiter( - _In_ XTaskQueueHandle queue, - _In_ XTaskQueuePort port, - _In_ HANDLE waitHandle, - _In_opt_ void* callbackContext, - _In_ XTaskQueueCallback* callback, - _Out_ XTaskQueueRegistrationToken* token - ) noexcept -{ - referenced_ptr aq(GetQueue(queue)); - RETURN_HR_IF(E_GAMERUNTIME_INVALID_HANDLE, aq == nullptr); - RETURN_IF_FAILED(aq->RegisterWaitHandle(port, waitHandle, callbackContext, callback, token)); - return S_OK; -} - -// -// Unregisters a previously registered task queue waiter. -// -STDAPI_(void) XTaskQueueUnregisterWaiter( - _In_ XTaskQueueHandle queue, - _In_ XTaskQueueRegistrationToken token - ) noexcept -{ - referenced_ptr aq(GetQueue(queue)); - if (aq != nullptr) - { - aq->UnregisterWaitHandle(token); - } -} - -// -// Increments the refcount on the queue and allows supplying -// options as to how the duplicate is performed. -// -STDAPI XTaskQueueDuplicateHandleWithOptions( - _In_ XTaskQueueHandle queueHandle, - _In_ XTaskQueueDuplicateOptions options, - _Out_ XTaskQueueHandle* duplicatedHandle - ) noexcept -{ - RETURN_HR_IF(E_POINTER, duplicatedHandle == nullptr); - - *duplicatedHandle = nullptr; - - auto queue = GetQueue(queueHandle); - RETURN_HR_IF(E_GAMERUNTIME_INVALID_HANDLE, queue == nullptr); - - if (USE_UNIQUE_HANDLES() && (options != XTaskQueueDuplicateOptions::Reference)) - { - RETURN_IF_FAILED(CreateTaskQueueHandle(queue, duplicatedHandle)); - } - else - { - queue->AddRef(); - *duplicatedHandle = queue->GetHandle(); - } - - return S_OK; -} - -// -// Increments the refcount on the queue -// -STDAPI XTaskQueueDuplicateHandle( - _In_ XTaskQueueHandle queueHandle, - _Out_ XTaskQueueHandle* duplicatedHandle - ) noexcept -{ - return XTaskQueueDuplicateHandleWithOptions( - queueHandle, - XTaskQueueDuplicateOptions::None, - duplicatedHandle); -} - -// -// Registers a callback that will be called when a new callback -// is submitted. The callback will be directly invoked when -// the call is submitted. -// -STDAPI XTaskQueueRegisterMonitor( - _In_ XTaskQueueHandle queue, - _In_opt_ void* callbackContext, - _In_ XTaskQueueMonitorCallback* callback, - _Out_ XTaskQueueRegistrationToken* token - ) noexcept -{ - referenced_ptr aq(GetQueue(queue)); - RETURN_HR_IF(E_GAMERUNTIME_INVALID_HANDLE, aq == nullptr); - RETURN_IF_FAILED(aq->RegisterSubmitCallback(callbackContext, callback, token)); - return S_OK; -} - -// -// Unregisters a previously added callback. -// -STDAPI_(void) XTaskQueueUnregisterMonitor( - _In_ XTaskQueueHandle queue, - _In_ XTaskQueueRegistrationToken token - ) noexcept -{ - referenced_ptr aq(GetQueue(queue)); - if (aq != nullptr) - { - aq->UnregisterSubmitCallback(token); - } -} - -// -// Returns a handle to the process task queue, or nullptr if there is no -// process task queue. By default, there is a default process task queue -// that uses the thread pool for both work and completion ports. This is an -// internal variant that takes duplicate options. -// -STDAPI_(bool) XTaskQueueGetCurrentProcessTaskQueueWithOptions( - _In_ XTaskQueueDuplicateOptions options, - _Out_ XTaskQueueHandle* queue - ) noexcept -{ - *queue = nullptr; - - XTaskQueueHandle processQueue = ProcessGlobals::g_processQueue; - if (processQueue == ProcessGlobals::g_invalidQueueHandle) - { - XTaskQueueHandle defaultProcessQueue = ProcessGlobals::g_defaultProcessQueue; - if (defaultProcessQueue == ProcessGlobals::g_invalidQueueHandle) - { - // The default process queue hasn't been created yet. Create it locally - // then swap it into the atomic. - - referenced_ptr aq(new (std::nothrow) TaskQueueImpl); - if (aq != nullptr && SUCCEEDED(aq->Initialize( - XTaskQueueDispatchMode::ThreadPool, - XTaskQueueDispatchMode::ThreadPool))) - { - XTaskQueueHandle expected = ProcessGlobals::g_invalidQueueHandle; - if (ProcessGlobals::g_defaultProcessQueue.compare_exchange_strong( - expected, - aq->GetHandle())) - { - // We successfully set the default handle. - aq.release(); - } - } - - defaultProcessQueue = ProcessGlobals::g_defaultProcessQueue; - } - - processQueue = defaultProcessQueue; - } - - if (processQueue == ProcessGlobals::g_invalidQueueHandle) - { - processQueue = nullptr; - } - - if (processQueue != nullptr) - { - (void)XTaskQueueDuplicateHandleWithOptions(processQueue, options, queue); - } - - return (*queue) != nullptr; -} - -// -// Returns a handle to the process task queue, or nullptr if there is no -// process task queue. By default, there is a default process task queue -// that uses the thread pool for both work and completion ports. -// -STDAPI_(bool) XTaskQueueGetCurrentProcessTaskQueue( - _Out_ XTaskQueueHandle* queue - ) noexcept -{ - return XTaskQueueGetCurrentProcessTaskQueueWithOptions(XTaskQueueDuplicateOptions::None, queue); -} - -// -// Sets the given task queue as the process wide task queue. The -// queue can be set to nullptr, in which case XTaskQueueGetCurrentProcessTaskQueue will -// also return nullptr. The provided queue will have its handle duplicated -// and any existing process task queue will have its handle closed. -// -STDAPI_(void) XTaskQueueSetCurrentProcessTaskQueue( - _In_opt_ XTaskQueueHandle queue - ) noexcept -{ - XTaskQueueHandle newQueue = nullptr; - - if (queue != nullptr) - { - FAIL_FAST_IF_FAILED(XTaskQueueDuplicateHandle(queue, &newQueue)); - } - - XTaskQueueHandle previous = ProcessGlobals::g_processQueue.exchange(newQueue); - if (previous != nullptr && previous != ProcessGlobals::g_invalidQueueHandle) - { - XTaskQueueCloseHandle(previous); - } -} - -// -// Submits a callback that will be invoked asynchronously via some external -// system. This is used to prevent queue termination while other work -// is happening. -// -STDAPI XTaskQueueSuspendTermination( - _In_ XTaskQueueHandle queue - ) noexcept -{ - referenced_ptr aq(GetQueue(queue)); - RETURN_HR_IF(E_GAMERUNTIME_INVALID_HANDLE, aq == nullptr); - - referenced_ptr portContext; - RETURN_IF_FAILED(aq->GetPortContext(XTaskQueuePort::Work, portContext.address_of())); - - RETURN_IF_FAILED(portContext->GetPort()->SuspendTermination(portContext.get())); - return S_OK; -} - -// -// Tells the queue that a previously submitted external callback -// has been dispatched. -// -STDAPI_(void) XTaskQueueResumeTermination( - _In_ XTaskQueueHandle queue - ) noexcept -{ - referenced_ptr aq(GetQueue(queue)); - if (aq == nullptr) - { - return; - } - - referenced_ptr portContext; - if (FAILED(aq->GetPortContext(XTaskQueuePort::Work, portContext.address_of()))) - { - return; - } - - portContext->GetPort()->ResumeTermination(portContext.get()); -} - -// -// Suspends the activity of all task queues in the process. When -// a task queue is suspended: -// -// 1. It will not signal when new items are added. -// 2. It will not return items from the dispatcher (it acts like it -// is empty). -// -#ifdef SUSPEND_API -STDAPI_(void) XTaskQueueGlobalSuspend( - ) noexcept -{ - ProcessGlobals::g_suspendState.Suspend(); - ProcessGlobals::g_suspendState.WaitForQueuesToSuspend(); -} -#endif - -// -// Resumes the activity of all task queues in the process. When -// a task queue is resumed: -// -// 1. Queues that are not empty will signal they have items. -// 2. The dispatcher will start returing items again. -// -#ifdef SUSPEND_API -STDAPI_(void) XTaskQueueGlobalResume( - ) noexcept -{ - ProcessGlobals::g_suspendState.Resume(); -} -#endif - -// -// Uninitializes global task queue state. This closes handles to per-process -// task queues and resets state back to defaults. If there is a per-process -// task queue, it will be closed but not terminated. Queue termination is -// up to the caller. This API returns true if all task queues have been -// cleaned up and deleted, or false if there are still outstanding references. -// A timeout may be provided to wait for outstanding queues to be cleaned up. -// The default is not to wait. The maximum timeout capped to 5000ms. -// -STDAPI_(bool) XTaskQueueUninitialize( - _In_ uint32_t timeoutMilliseconds - ) noexcept -{ - std::atomic* globals[] = - { - &ProcessGlobals::g_defaultProcessQueue, - &ProcessGlobals::g_processQueue - }; - - for (auto queue : globals) - { - auto handle = queue->exchange(ProcessGlobals::g_invalidQueueHandle); - if (handle != nullptr && handle != ProcessGlobals::g_invalidQueueHandle) - { - XTaskQueueCloseHandle(handle); - } - } - - constexpr uint32_t maxTimeout = 5000; - if (timeoutMilliseconds > maxTimeout) - { - timeoutMilliseconds = maxTimeout; - } - - return ApiRefs::WaitZeroRefs(timeoutMilliseconds); -} - -/// -/// Sets or clears test hooks on a task queue. -/// -STDAPI XTaskQueueSetTestHooks( - _In_ XTaskQueueHandle queue, - _In_ XTaskQueueTestHooks* hooks - ) noexcept -{ - referenced_ptr aq(GetQueue(queue)); - RETURN_HR_IF(E_GAMERUNTIME_INVALID_HANDLE, aq == nullptr); - aq->SetTestHooks(hooks); - return S_OK; -} - -/// -/// Submits any pending delayed callbacks that are due to run. This is -/// intended for use in unit tests. -/// -STDAPI XTaskQueueSubmitPendingCallbacks( - _In_ XTaskQueueHandle queue, - _In_ XTaskQueuePort port - ) noexcept -{ - referenced_ptr aq(GetQueue(queue)); - RETURN_HR_IF(E_GAMERUNTIME_INVALID_HANDLE, aq == nullptr); - - referenced_ptr portContext; - RETURN_IF_FAILED(aq->GetPortContext(port, portContext.address_of())); - - portContext->GetPort()->SubmitPendingCallbacks(); - return S_OK; -} diff --git a/third_party/xtaskqueue/Source/Task/TaskQueueImpl.h b/third_party/xtaskqueue/Source/Task/TaskQueueImpl.h deleted file mode 100644 index 3678b5ede..000000000 --- a/third_party/xtaskqueue/Source/Task/TaskQueueImpl.h +++ /dev/null @@ -1,688 +0,0 @@ -// Copyright (c) Microsoft Corporation -// Licensed under the MIT license. See LICENSE file in the project root for full license information. - -#pragma once - -#include "ApiRefState.h" -#include "referenced_ptr.h" -#include "AtomicVector.h" -#include -#include "LocklessQueue.h" -#include "StaticArray.h" -#include "ThreadPool.h" -#include "WaitTimer.h" - -#ifdef SUSPEND_API -#include "SuspendState.h" -#endif - -SYSTEM_HANDLE_DEFINE_HELPERS(XTaskQueueHandle, XSystemHandleType::TaskQueue); - -namespace TaskQueueInternal -{ - // Private capability identifier; keep the shared ApiId enum unchanged. - constexpr ApiId kPinnableContextApiId = - static_cast(0x50494E31); - constexpr ApiId kWaitPublicationApiId = static_cast(0x57505432); -} - -namespace ApiRefs -{ - void GlobalAddRef(); - void GlobalRelease(); - -#ifdef HC_UNITTEST_API - // Unit-test diagnostics: tracks live Api<> objects by type so a failed - // XTaskQueueUninitialize can report what leaked. - void TrackLiveObject(ApiId id, int32_t delta) noexcept; -#endif -} - -template -class Api : public TInterface -{ -public: - -#ifdef HC_UNITTEST_API - Api() noexcept - { - ApiRefs::TrackLiveObject(iid, 1); - } -#endif - - virtual ~Api() - { -#ifdef HC_UNITTEST_API - ApiRefs::TrackLiveObject(iid, -1); -#endif - } - - uint32_t __stdcall AddRef() - { - ApiRefs::GlobalAddRef(); - return m_refState.AddRef(); - } - - bool TryAddRef() noexcept - { - // Account globally before publishing the local reference. - ApiRefs::GlobalAddRef(); - - if (m_refState.TryAddRef()) - { - return true; - } - - ApiRefs::GlobalRelease(); - return false; - } - - uint32_t __stdcall Release() - { - const auto result = m_refState.Release(); - - if (result.startRundown) - { - // Keep the global reference count nonzero during teardown. - ApiRefs::GlobalAddRef(); - RundownObject(); - delete this; - ApiRefs::GlobalRelease(); - } - - ApiRefs::GlobalRelease(); - return result.remaining; - } - - HRESULT __stdcall QueryApi(ApiId id, void** ptr) - { - if (ptr == nullptr) - { - return E_POINTER; - } - - *ptr = QueryApiImpl(id); - - if ((*ptr) != nullptr) - { - AddRef(); - return S_OK; - } - - return E_NOINTERFACE; - } - -protected: - - virtual void* QueryApiImpl(ApiId id) - { - if (id == ApiId::Identity || id == iid) - { - return static_cast(this); - } - return nullptr; - } - - // Called when the object is about to be deleted. - virtual void RundownObject() - { - } - -private: - ApiRefState m_refState; -}; - -static uint32_t const SUBMIT_CALLBACK_MAX = 32; - -class SubmitCallback -{ -public: - - SubmitCallback(_In_ XTaskQueueHandle queue); - - HRESULT Register(_In_opt_ void* context, _In_ XTaskQueueMonitorCallback* callback, _Out_ XTaskQueueRegistrationToken* token); - void Unregister(_In_ XTaskQueueRegistrationToken token); - void Invoke(_In_ XTaskQueuePort port); - -private: - - struct CallbackRegistration - { - uint64_t Token; - void* Context; - XTaskQueueMonitorCallback* Callback; - }; - - std::atomic m_nextToken{ 0 }; - DefaultUnnamedMutex m_lock; - CallbackRegistration m_buffer1[SUBMIT_CALLBACK_MAX]; - CallbackRegistration m_buffer2[SUBMIT_CALLBACK_MAX]; - CallbackRegistration* m_buffers[2]= { m_buffer1, m_buffer2 }; - std::atomic m_indexAndRef { 0 }; - XTaskQueueHandle m_queue; -}; - -#define PORT_WAIT_MAX 60 -#define PORT_EVENT_MAX (PORT_WAIT_MAX + 2) -#define QUEUE_WAIT_MAX (PORT_WAIT_MAX * 2) - -class QueueWaitRegistry -{ -public: - - void AddRef() noexcept { ++m_refs; } - void Release() noexcept { if (--m_refs == 0) delete this; } - bool Reserve(); - void CancelReservation(); - void Publish(XTaskQueuePort port, XTaskQueueRegistrationToken portToken, - XTaskQueueRegistrationToken* token, bool retiredByPort); - struct WaitRegistration - { - uint64_t Token; - uint64_t PortToken; - XTaskQueuePort Port; - bool retiredByPort; - }; - - WaitRegistration Lookup(XTaskQueueRegistrationToken token); - void Remove(XTaskQueueRegistrationToken token); - -private: - std::atomic m_refs{0}; - std::atomic m_nextToken{ 0 }; - uint32_t m_reserved = 0; - StaticArray m_callbacks; - DefaultUnnamedMutex m_lock; -}; - -class TaskQueuePortContextImpl; - -class TaskQueuePortImpl: public Api -{ -public: - - TaskQueuePortImpl(); - virtual ~TaskQueuePortImpl(); - - HRESULT Initialize( - _In_ XTaskQueueDispatchMode mode); - - XTaskQueuePortHandle __stdcall GetHandle() { return &m_header; } - - HRESULT __stdcall QueueItem( - _In_ ITaskQueuePortContext* portContext, - _In_ uint32_t waitMs, - _In_opt_ void* callbackContext, - _In_ XTaskQueueCallback* callback); - - HRESULT __stdcall RegisterWaitHandle( - _In_ ITaskQueuePortContext* portContext, - _In_ HANDLE waitHandle, - _In_opt_ void* callbackContext, - _In_ XTaskQueueCallback* callback, - _Out_ XTaskQueueRegistrationToken* token); - - // Local capability for publishing the public token before the wait is armed. - HRESULT RegisterWaitWithToken(ITaskQueuePortContext* portContext, HANDLE waitHandle, - void* callbackContext, XTaskQueueCallback* callback, XTaskQueueRegistrationToken* token, - QueueWaitRegistry* registry); - - void __stdcall UnregisterWaitHandle( - _In_ XTaskQueueRegistrationToken token); - - HRESULT __stdcall PrepareTerminate( - _In_ ITaskQueuePortContext* portContext, - _In_ void* callbackContext, - _In_ XTaskQueueTerminatedCallback* callback, - _Out_ void** token); - - void __stdcall CancelTermination( - _In_ void* token); - - void __stdcall Terminate( - _In_ void* token); - - virtual HRESULT __stdcall Attach( - _In_ ITaskQueuePortContext* portContext); - - void __stdcall Detach( - _In_ ITaskQueuePortContext* portContext); - - bool __stdcall Dispatch( - _In_ ITaskQueuePortContext* portContext, - _In_ uint32_t timeoutInMs); - - bool __stdcall IsEmpty(); - - void __stdcall WaitForUnwind(); - - HRESULT __stdcall SuspendTermination( - _In_ ITaskQueuePortContext* portContext); - - void __stdcall ResumeTermination( - _In_ ITaskQueuePortContext* portContext); - - void __stdcall SuspendPort(); - void __stdcall ResumePort(); - - void __stdcall SubmitPendingCallbacks(); - -private: - - void* QueryApiImpl(ApiId id) override - { - if (id == TaskQueueInternal::kWaitPublicationApiId) return this; - return Api::QueryApiImpl(id); - } - - struct WaitRegistration; - - struct QueueEntry - { - ITaskQueuePortContext* portContext; - void* callbackContext; - XTaskQueueCallback* callback; - WaitRegistration* waitRegistration; - uint64_t enqueueTime; - uint64_t id; - }; - - struct TerminationEntry - { - ITaskQueuePortContext* portContext; - void* callbackContext; - XTaskQueueTerminatedCallback* callback; - std::uint64_t node; - }; - -#ifdef _WIN32 - struct WaitHandleOwner - { - HANDLE handle = nullptr; - ~WaitHandleOwner() { if (handle) CloseHandle(handle); } - }; - - struct WaitRegistration - { - enum class State { Active, Canceled, Removed }; - std::atomic refs{0}; - void AddRef() noexcept { ++refs; } - void Release() noexcept { if (--refs == 0) delete this; } - ~WaitRegistration(); - - uint64_t token = 0; - referenced_ptr publicRegistry; - XTaskQueueRegistrationToken publicToken{}; - std::shared_ptr handleOwner; - std::once_flag drainOnce; - PTP_WAIT threadpoolWait = nullptr; - TaskQueuePortImpl* port = nullptr; - TaskQueuePortContextImpl* pinnable = nullptr; - QueueEntry queueEntry{}; - - // Protected by port->m_lock. Detach retires Active registrations - // before the embedded context can disappear. - State state = State::Active; - referenced_ptr queuedContext; - bool appended = false; - bool running = false; - bool enteredUserCode = false; - bool drained = false; - uint64_t cancelNode = 0; - }; - struct WaitSnapshot - { - std::shared_ptr epoch; - StaticArray events; - StaticArray, PORT_WAIT_MAX> owners; - StaticArray, PORT_WAIT_MAX> registrations; - }; - void InvalidateWaitEpochLocked(); - void FinishRetirementLocked(WaitRegistration* reg); - void CaptureWaitSnapshot(WaitSnapshot& snapshot); - friend struct WaitRegistrationTestAccess; - - struct WaitCallbackFrame - { - explicit WaitCallbackFrame(WaitRegistration* registration); - ~WaitCallbackFrame(); - WaitRegistration* reg; - WaitCallbackFrame* next; - WaitCallbackFrame** link; - static DefaultUnnamedMutex lock; - static WaitCallbackFrame* head; - static bool ConfirmEntry(); - }; - - void DrainRetiredWait(const referenced_ptr& reg); -#endif - - XTaskQueuePortObject m_header = { }; - XTaskQueueDispatchMode m_dispatchMode = XTaskQueueDispatchMode::Manual; - struct AttachedContextRegistration - { - ITaskQueuePortContext* context; - TaskQueuePortContextImpl* pinnable; - }; - - DefaultUnnamedMutex m_attachedContextsLock; - std::map m_attachedContexts; - - uint64_t m_nextAttachedContextId = 1; - - bool TryAcquireNextAttachedContext( - uint64_t& cursor, - uint64_t upperBound, - ITaskQueuePortContext** result); - - template - void VisitAttachedContexts(Callback callback) - { - // Keep the port alive even if a callback closes its owning queue. - if (!TryAddRef()) - { - return; - } - - struct PortGuard - { - TaskQueuePortImpl* port; - ~PortGuard() { port->Release(); } - } portGuard{ this }; - - uint64_t upperBound; - { - std::lock_guard lock(m_attachedContextsLock); - upperBound = m_nextAttachedContextId - 1; - } - - uint64_t cursor = 0; - - for (;;) - { - ITaskQueuePortContext* context = nullptr; - - if (!TryAcquireNextAttachedContext( - cursor, upperBound, &context)) - { - break; - } - - struct ContextGuard - { - ITaskQueuePortContext* context; - ~ContextGuard() { context->Release(); } - } contextGuard{ context }; - - // Never invoke external code while holding the registry mutex. - callback(context); - } - - // Only safely pinnable contexts can be visited. - } - std::atomic m_processingSerializedTbCallback{ 0 }; - std::atomic m_processingCallback{ 0 }; - DefaultUnnamedConditionVariable m_processingCallbackCv; - DefaultUnnamedMutex m_lock; - std::unique_ptr> m_queueList; - std::unique_ptr> m_pendingList; - std::unique_ptr> m_terminationList; - std::unique_ptr> m_pendingTerminationList; - DefaultUnnamedMutex m_terminationLock; - OS::WaitTimer m_timer; - OS::ThreadPool m_threadPool; - std::atomic m_timerDue = { UINT64_MAX }; - std::atomic m_nextId = { 0 }; - std::atomic m_suspended = { false }; - -#ifdef _WIN32 - std::map> m_waits; - DefaultUnnamedConditionVariable m_waitFinished; - HANDLE m_queueEvent = nullptr; - std::shared_ptr m_waitEpoch; - std::atomic m_readyEntries{0}; - uint32_t m_activeWaits = 0; - uint64_t m_nextWaitToken = 0; -#else - bool m_signaled = false; - DefaultUnnamedConditionVariableAny m_event; -#endif - - bool ReadyQueueEmpty(); - HRESULT VerifyNotTerminated(_In_ ITaskQueuePortContext* portContext); - - bool IsCallCanceled(_In_ const QueueEntry& entry); - - // Appends the given entry to the active queue. The entry should already - // be add-refd. - bool AppendEntry( - _In_ const QueueEntry& entry, - _In_opt_ uint64_t node = 0); - - void CancelPendingEntries( - _In_ ITaskQueuePortContext* portContext, - _In_ bool appendToQueue); - - bool DrainOneItem(); - - bool DrainOneItem( - _In_ OS::ThreadPoolActionStatus& status); - - bool Wait( - _In_ ITaskQueuePortContext* portContext, - _In_ uint32_t timeout); - - static void EraseQueue( - _In_opt_ LocklessQueue* queue); - - bool ArmTimerIfEarlier(_In_ uint64_t dueTime); - - bool ArmTimerForNextPendingDueTime( - _In_ uint64_t previousDueTime, - _In_ uint64_t nextDueTime); - - bool RearmTimerIfDueTimeUnchanged(_In_ uint64_t dueTime); - - // After cancellation removed pending entries, re-point the shared timer at - // the earliest surviving pending entry instead of leaving it armed for a - // deadline that no longer has an owner. - void RearmTimerForEarliestPending(); - - void PromoteReadyPendingCallbacks( - _In_ uint64_t dueTime, - _In_ uint64_t now); - - void SignalTerminations(); - void ScheduleTermination(_In_ TerminationEntry* term); - bool TerminationListEmpty(); - - void SignalQueue(); - void NotifyItemQueued(); - - void ProcessThreadPoolCallback(_In_ OS::ThreadPoolActionStatus& status); - -#ifdef _WIN32 - bool PublishWaitEntryLocked(WaitRegistration* reg, uint64_t node); - void RetireWaitLocked(WaitRegistration* reg, WaitRegistration::State state); - bool DispatchWaitEntry(const QueueEntry& entry, OS::ThreadPoolActionStatus& status, - referenced_ptr& context); - void ProcessWaitCallback(WaitRegistration* reg); - - static void CALLBACK WaitCallback( - _In_ PTP_CALLBACK_INSTANCE instance, - _Inout_opt_ void* context, - _Inout_ PTP_WAIT wait, - _In_ TP_WAIT_RESULT waitResult); -#endif -}; - -class TaskQueueImpl; - -class TaskQueuePortContextImpl : public ITaskQueuePortContext -{ -public: - - TaskQueuePortContextImpl( - _In_ TaskQueueImpl* queue, - _In_ XTaskQueuePort type, - _In_ SubmitCallback* submitCallback); - - uint32_t __stdcall AddRef() override; - uint32_t __stdcall Release() override; - bool TryPin() noexcept; - HRESULT __stdcall QueryApi(_In_ ApiId id, _Out_ void** ptr) override; - - XTaskQueuePort __stdcall GetType() override; - TaskQueuePortStatus __stdcall GetStatus() override; - ITaskQueue* __stdcall GetQueue() override; - ITaskQueuePort* __stdcall GetPort() override; - - bool __stdcall TrySetStatus( - _In_ TaskQueuePortStatus expectedStatus, - _In_ TaskQueuePortStatus status) override; - - void __stdcall SetStatus( - _In_ TaskQueuePortStatus status) override; - - void __stdcall ItemQueued() override; - - bool __stdcall AddSuspend() override; - bool __stdcall RemoveSuspend() override; - - referenced_ptr Port; - referenced_ptr Source; - -private: - - TaskQueueImpl* m_queue = nullptr; - XTaskQueuePort m_type = XTaskQueuePort::Work; - SubmitCallback* m_submitCallback = nullptr; - std::atomic m_status = { TaskQueuePortStatus::Active }; - std::atomic m_suspendCount = { 0 }; -}; - -class TaskQueueImpl : public Api -#ifdef SUSPEND_API - , public ISuspendResumeCallback -#endif -{ -public: - - TaskQueueImpl(); - virtual ~TaskQueueImpl(); - - HRESULT Initialize( - _In_ XTaskQueueDispatchMode workMode, - _In_ XTaskQueueDispatchMode completionMode); - - HRESULT Initialize( - _In_ XTaskQueuePortHandle workPort, - _In_ XTaskQueuePortHandle completionPort); - - XTaskQueueHandle __stdcall GetHandle() override { return &m_header; } - XTaskQueueTestHooks* __stdcall GetTestHooks() override { return m_testHooks; } - void __stdcall SetTestHooks(_In_ XTaskQueueTestHooks* testHooks) override { m_testHooks = testHooks; } - - HRESULT __stdcall GetPortContext( - _In_ XTaskQueuePort port, - _Out_ ITaskQueuePortContext** portContext) override; - - HRESULT __stdcall RegisterWaitHandle( - _In_ XTaskQueuePort port, - _In_ HANDLE waitHandle, - _In_opt_ void* callbackContext, - _In_ XTaskQueueCallback* callback, - _Out_ XTaskQueueRegistrationToken* token) override; - - void __stdcall UnregisterWaitHandle( - _In_ XTaskQueueRegistrationToken token) override; - - HRESULT __stdcall RegisterSubmitCallback( - _In_opt_ void* context, - _In_ XTaskQueueMonitorCallback* callback, - _Out_ XTaskQueueRegistrationToken* token) override; - - void __stdcall UnregisterSubmitCallback( - _In_ XTaskQueueRegistrationToken token) override; - - HRESULT __stdcall Terminate( - _In_ bool wait, - _In_opt_ void* callbackContext, - _In_opt_ XTaskQueueTerminatedCallback* callback) override ; - -protected: - - void RundownObject() override; - -private: - -#ifdef SUSPEND_API - void OnSuspendResume(_In_ bool isSuspended) override; -#endif - - static void CALLBACK OnTerminationCallback(_In_ void* context); - -private: - - enum class TerminationLevel - { - None, - Work, - Completion - }; - - struct TerminationEntry - { - TaskQueueImpl* owner; - TerminationLevel level; - void* completionPortToken; - void* context; - XTaskQueueTerminatedCallback* callback; - }; - - struct TerminationData - { - bool terminated; - DefaultUnnamedMutex lock; - DefaultUnnamedConditionVariable cv; - }; - - XTaskQueueObject m_header = { }; - SubmitCallback m_callbackSubmitted; - referenced_ptr m_waitRegistry{new (std::nothrow) QueueWaitRegistry}; - TerminationData m_termination; - TaskQueuePortContextImpl m_work; - TaskQueuePortContextImpl m_completion; - XTaskQueueTestHooks* m_testHooks = nullptr; - -#ifdef SUSPEND_API - SuspendResumeHandler m_suspendHandler; -#endif -}; - -inline ITaskQueue* GetQueue(XTaskQueueHandle handle) -{ - if (handle->m_signature != TASK_QUEUE_SIGNATURE || - handle->m_runtimeIteration != GetCurrentRuntimeIteration()) - { - SystemHandleAssert(handle); - ASSERT("Invalid XTaskQueueHandle"); - return nullptr; - } - - ITaskQueue* queue = handle->m_queue; - - // Only SystemHandleAssert if the handle provided here is - // not the internal queue handle, which is never tracked - // by handle tracking. The internal queue handle is given out - // for the default process queue, when calling back into - // task queue monitors, and when async operations are created. - - if (handle != queue->GetHandle()) - { - SystemHandleAssert(handle); - } - - ASSERT(queue->GetHandle()->m_signature == TASK_QUEUE_SIGNATURE); - return queue; -} diff --git a/third_party/xtaskqueue/Source/Task/TaskQueueP.h b/third_party/xtaskqueue/Source/Task/TaskQueueP.h deleted file mode 100644 index b34be4d43..000000000 --- a/third_party/xtaskqueue/Source/Task/TaskQueueP.h +++ /dev/null @@ -1,178 +0,0 @@ -// Copyright (c) Microsoft Corporation -// Licensed under the MIT license. See LICENSE file in the project root for full license information. -// -// This is the "private" api for a task queue. It is an immutable definition used to help define -// the implementation of a queue so that multiple implementations can co-habitate and share the same -// flat public API. -#pragma once - -enum class ApiId -{ - Identity, - TaskQueuePort, - TaskQueue, - TaskQueuePortContext -}; - -// Lightweight version of IUnknown -struct IApi -{ - virtual uint32_t __stdcall AddRef() = 0; - virtual uint32_t __stdcall Release() = 0; - virtual HRESULT __stdcall QueryApi(_In_ ApiId id, _Out_ void** ptr) = 0; -}; - -struct ITaskQueue; -struct ITaskQueuePort; -struct ITaskQueuePortContext; - -// A queue port is either the work or completion component of -// a task queue -struct ITaskQueuePort: IApi -{ - virtual XTaskQueuePortHandle __stdcall GetHandle() = 0; - - virtual HRESULT __stdcall QueueItem( - _In_ ITaskQueuePortContext* portContext, - _In_ uint32_t waitMs, - _In_opt_ void* callbackContext, - _In_ XTaskQueueCallback* callback) = 0; - - virtual HRESULT __stdcall RegisterWaitHandle( - _In_ ITaskQueuePortContext* portContext, - _In_ HANDLE waitHandle, - _In_opt_ void* callbackContext, - _In_ XTaskQueueCallback* callback, - _Out_ XTaskQueueRegistrationToken* token) = 0; - - virtual void __stdcall UnregisterWaitHandle( - _In_ XTaskQueueRegistrationToken token) = 0; - - virtual HRESULT __stdcall PrepareTerminate( - _In_ ITaskQueuePortContext* portContext, - _In_ void* callbackContext, - _In_ XTaskQueueTerminatedCallback* callback, - _Out_ void** token) = 0; - - virtual void __stdcall CancelTermination( - _In_ void* token) = 0; - - virtual void __stdcall Terminate( - _In_ void* token) = 0; - - virtual HRESULT __stdcall Attach( - _In_ ITaskQueuePortContext* portContext) = 0; - - virtual void __stdcall Detach( - _In_ ITaskQueuePortContext* portContext) = 0; - - virtual bool __stdcall Dispatch( - _In_ ITaskQueuePortContext* portContext, - _In_ uint32_t timeoutInMs) = 0; - - virtual bool __stdcall IsEmpty() = 0; - - virtual void __stdcall WaitForUnwind() = 0; - - virtual HRESULT __stdcall SuspendTermination( - _In_ ITaskQueuePortContext* portContext) = 0; - - virtual void __stdcall ResumeTermination( - _In_ ITaskQueuePortContext* portContext) = 0; - - virtual void __stdcall SuspendPort() = 0; - virtual void __stdcall ResumePort() = 0; - - virtual void __stdcall SubmitPendingCallbacks() = 0; -}; - -// The status of a port on the queue. This status is used in -// comparisions, with later status values adopting the restrictions -// of earier values. For example, any status >= Canceled will -// prevent new requests from being submitted to the port. -enum class TaskQueuePortStatus -{ - Active, // Actively servicing requests - Canceled, // Rejecting requests on the road to being terminated - Terminating, // Termination actively in progress - Terminated // Termination is complete. -}; - -// A task queue port context contains queue-specific data about a port. -// Interface pointer return values from this interface are not -// add-ref'd. -struct ITaskQueuePortContext : IApi -{ - virtual XTaskQueuePort __stdcall GetType() = 0; - virtual TaskQueuePortStatus __stdcall GetStatus() = 0; - virtual ITaskQueue* __stdcall GetQueue() = 0; - virtual ITaskQueuePort* __stdcall GetPort() = 0; - - virtual bool __stdcall TrySetStatus( - _In_ TaskQueuePortStatus expectedStatus, - _In_ TaskQueuePortStatus status) = 0; - - virtual void __stdcall SetStatus( - _In_ TaskQueuePortStatus status) = 0; - - virtual void __stdcall ItemQueued() = 0; - - virtual bool __stdcall AddSuspend() = 0; - virtual bool __stdcall RemoveSuspend() = 0; -}; - -// The task queue. The public flat API is built entirely on -// this primitive. -struct ITaskQueue : IApi -{ - virtual XTaskQueueHandle __stdcall GetHandle() = 0; - virtual XTaskQueueTestHooks* __stdcall GetTestHooks() = 0; - virtual void __stdcall SetTestHooks(_In_ XTaskQueueTestHooks* testHooks) = 0; - - virtual HRESULT __stdcall GetPortContext( - _In_ XTaskQueuePort port, - _Out_ ITaskQueuePortContext** portContext) = 0; - - virtual HRESULT __stdcall RegisterWaitHandle( - _In_ XTaskQueuePort port, - _In_ HANDLE waitHandle, - _In_opt_ void* callbackContext, - _In_ XTaskQueueCallback* callback, - _Out_ XTaskQueueRegistrationToken* token) = 0; - - virtual void __stdcall UnregisterWaitHandle( - _In_ XTaskQueueRegistrationToken token) = 0; - - virtual HRESULT __stdcall RegisterSubmitCallback( - _In_opt_ void* context, - _In_ XTaskQueueMonitorCallback* callback, - _Out_ XTaskQueueRegistrationToken* token) = 0; - - virtual void __stdcall UnregisterSubmitCallback( - _In_ XTaskQueueRegistrationToken token) = 0; - - virtual HRESULT __stdcall Terminate( - _In_ bool wait, - _In_opt_ void* callbackContext, - _In_opt_ XTaskQueueTerminatedCallback* callback) = 0; -}; - -// Defines the structure that backs an XTaskQueueHandle. -struct XTaskQueueObject -{ - uint32_t m_signature; - uint32_t m_runtimeIteration; - ITaskQueue* m_queue; -}; - -// Defines the structure that backs an XTaskQueuePortObject -struct XTaskQueuePortObject -{ - uint32_t m_signature; - uint32_t m_runtimeIteration; - ITaskQueuePort* m_port; - ITaskQueue* m_queue; -}; - -static uint32_t const TASK_QUEUE_SIGNATURE = 0x41515545; -static uint32_t const TASK_QUEUE_PORT_SIGNATURE = 0x41515553; diff --git a/third_party/xtaskqueue/Source/Task/ThreadPool.h b/third_party/xtaskqueue/Source/Task/ThreadPool.h deleted file mode 100644 index f98817815..000000000 --- a/third_party/xtaskqueue/Source/Task/ThreadPool.h +++ /dev/null @@ -1,37 +0,0 @@ -#pragma once - -namespace OS -{ - struct ThreadPoolActionStatus - { - virtual void Complete() = 0; - virtual void MayRunLong() = 0; - }; - - using ThreadPoolCallback = void(_In_opt_ void*, _In_ ThreadPoolActionStatus& status); - - class ThreadPoolImpl; - - // A thread pool will invoke its callback on a pool of threads. - class ThreadPool - { - public: - ThreadPool() noexcept; - ~ThreadPool() noexcept; - - // Initializes the thread pool. - HRESULT Initialize(_In_opt_ void* context, _In_ ThreadPoolCallback* callback) noexcept; - - // Terminates the thread pool, waiting for any outstanding calls to drain - // and and canceling any pending calls. - void Terminate() noexcept; - - // Submits a new callback to the thread pool. The callback passed to Initialize will - // be invoked on a thread pool thread. May throw / crash if called after termination - // or before init. - void Submit(); - - private: - ThreadPoolImpl* m_impl; - }; -} diff --git a/third_party/xtaskqueue/Source/Task/ThreadPool_win32.cpp b/third_party/xtaskqueue/Source/Task/ThreadPool_win32.cpp deleted file mode 100644 index c8506ddb8..000000000 --- a/third_party/xtaskqueue/Source/Task/ThreadPool_win32.cpp +++ /dev/null @@ -1,206 +0,0 @@ -#include "pch.h" -#include "ThreadPool.h" - -namespace OS -{ - // This API is documented but not defined in the headers. Load it dynamcially - // so the world doesn't have to add linkage to ntdll. Ntdll is not unloadable, - // so safe to leak the module ref here. - static inline BOOLEAN __stdcall RtlDllShutdownInProgress() noexcept - { - static decltype(RtlDllShutdownInProgress)* s_pfnRtlDllShutdownInProgress = nullptr; - static HMODULE s_ntdllModuleHandle = nullptr; - - // No locking needed -- if these race the threads race to copy - // the same values, and worst case is we get an addl ref on - // a dll we'll never unload anyway. GetModuleHandle is not defined - // for UWP apps, so don't do this safety check for them. - -#ifdef GetModuleHandle - if (s_pfnRtlDllShutdownInProgress == nullptr) - { - if (s_ntdllModuleHandle == nullptr) - { - s_ntdllModuleHandle = GetModuleHandleW(L"ntdll.dll"); - } - - if (s_ntdllModuleHandle != nullptr) - { - s_pfnRtlDllShutdownInProgress = reinterpret_cast(GetProcAddress(s_ntdllModuleHandle, "RtlDllShutdownInProgress")); - } - } -#endif - - return s_pfnRtlDllShutdownInProgress ? s_pfnRtlDllShutdownInProgress() : FALSE; - } - - class ThreadPoolImpl - { - public: - - ~ThreadPoolImpl() noexcept - { - Terminate(); - } - - void AddRef() - { - m_refs++; - } - - void Release() - { - if (--m_refs == 0) - { - delete this; - } - } - - HRESULT Initialize( - _In_opt_ void* context, - _In_ ThreadPoolCallback* callback) noexcept - { - m_context = context; - m_callback = callback; - m_work = CreateThreadpoolWork(TPCallback, this, nullptr); - RETURN_LAST_ERROR_IF_NULL(m_work); - - return S_OK; - } - - void Terminate() noexcept - { - if (m_work != nullptr) - { - // Wait for callbacks to complete. We don't want to - // cancel existing callbacks because it's important they - // get a chance to drain. - WaitForThreadpoolWorkCallbacks(m_work, FALSE); - CloseThreadpoolWork(m_work); - m_work = nullptr; - } - } - - void Submit() noexcept - { - if (!RtlDllShutdownInProgress()) - { - SubmitThreadpoolWork(m_work); - } - } - - private: - - static void CALLBACK TPCallback( - _In_ PTP_CALLBACK_INSTANCE instance, - _In_ void* context, PTP_WORK) noexcept - { - ThreadPoolImpl* pthis = static_cast(context); - - // ActionStatus offers a way for the call to - // provide the threadpool of its status. It - // can mark the call complete to indicate - // all portions of the call have finished - // and it is safe to release the - // thread pool, even if the callback has - // not totally unwound. This is neccessary - // to allow users to close a task queue from - // within a callback. Task queue guards with an - // extra ref to ensure a safe point where - // member state is no longer accessed, but the - // final release does need to wait on outstanding - // calls. - // - // A call can also mark itself that it may run - // long, which is often the case for work callbacks - // in an async call. This guides the thread pool - // to allow more threads to be created if needed. - - ActionStatusImpl status(pthis, instance); - pthis->AddRef(); - pthis->m_callback(pthis->m_context, status); - - if (!status.IsComplete) - { - status.Complete(); - } - pthis->Release(); // May delete this - } - - struct ActionStatusImpl : ThreadPoolActionStatus - { - ActionStatusImpl(ThreadPoolImpl* owner, PTP_CALLBACK_INSTANCE instance) : - m_owner(owner), - m_instance(instance) - { - } - - bool IsComplete = false; - - void Complete() override - { - IsComplete = true; - DisassociateCurrentThreadFromCallback(m_instance); - } - - void MayRunLong() override - { - // Only allowed once per callback - if (!m_longRunning) - { - m_longRunning = true; - CallbackMayRunLong(m_instance); - } - } - - private: - ThreadPoolImpl* m_owner = nullptr; - PTP_CALLBACK_INSTANCE m_instance = nullptr; - bool m_longRunning = false; - }; - - std::atomic m_refs{ 1 }; - PTP_WORK m_work = nullptr; - void* m_context = nullptr; - ThreadPoolCallback* m_callback = nullptr; - }; - - ThreadPool::ThreadPool() noexcept : - m_impl(nullptr) - { - } - - ThreadPool::~ThreadPool() noexcept - { - Terminate(); - } - - HRESULT ThreadPool::Initialize(_In_opt_ void* context, _In_ ThreadPoolCallback* callback) noexcept - { - RETURN_HR_IF(E_UNEXPECTED, m_impl != nullptr); - - std::unique_ptr impl(new (std::nothrow) ThreadPoolImpl); - RETURN_IF_NULL_ALLOC(impl); - - RETURN_IF_FAILED(impl->Initialize(context, callback)); - - m_impl = impl.release(); - return S_OK; - } - - void ThreadPool::Terminate() noexcept - { - if (m_impl != nullptr) - { - m_impl->Terminate(); - m_impl->Release(); - m_impl = nullptr; - } - } - - void ThreadPool::Submit() - { - m_impl->Submit(); - } - -} // Namespace \ No newline at end of file diff --git a/third_party/xtaskqueue/Source/Task/WaitTimer.h b/third_party/xtaskqueue/Source/Task/WaitTimer.h deleted file mode 100644 index 342a08808..000000000 --- a/third_party/xtaskqueue/Source/Task/WaitTimer.h +++ /dev/null @@ -1,49 +0,0 @@ -#pragma once - -#include - -namespace OS -{ - using WaitTimerCallback = void(_In_opt_ void*); - - class WaitTimerImpl; - - // Source-internal test seam for deterministic STL WaitTimer lifetime - // regressions. It is not exported as part of the public libHttpClient API. - struct WaitTimerTestHooks - { - virtual void WaitTimerImplDestructionStarted() noexcept {} - virtual bool BeforeTimerInvoke() noexcept { return true; } - virtual void BeforeTimerQueueRetirement() noexcept {} - virtual bool WaitTimerOperationLoaded(bool) noexcept { return true; } - }; - - void WaitTimerSetTestHooks(_In_opt_ WaitTimerTestHooks* hooks) noexcept; - - // A wait timer holds a single timeout expressed as a monotonic due time. - // Calling Start will reset any pending timeout. - class WaitTimer - { - public: - WaitTimer() noexcept; - ~WaitTimer() noexcept; - - HRESULT Initialize(_In_opt_ void* context, _In_ WaitTimerCallback* callback) noexcept; - void Terminate() noexcept; - - // Arms the one-shot timer for the provided monotonic due time. - void Start(_In_ uint64_t dueTime) noexcept; - void Cancel() noexcept; - - // Returns the current monotonic time used for delayed-callback - // ordering and stale-timer validation. - uint64_t GetCurrentTime() noexcept; - - // Returns a monotonic due time msFromNow milliseconds in the future. - uint64_t GetDueTime(_In_ uint32_t msFromNow) noexcept; - - private: - DefaultUnnamedMutex m_mutex; - std::atomic m_impl; - }; -} diff --git a/third_party/xtaskqueue/Source/Task/WaitTimer_win32.cpp b/third_party/xtaskqueue/Source/Task/WaitTimer_win32.cpp deleted file mode 100644 index 33e240466..000000000 --- a/third_party/xtaskqueue/Source/Task/WaitTimer_win32.cpp +++ /dev/null @@ -1,215 +0,0 @@ -#include "pch.h" -#include "WaitTimer.h" - -using Clock = std::chrono::steady_clock; -using Deadline = Clock::time_point; -using TimerDuration = std::chrono::nanoseconds; - -namespace -{ - Deadline DeadlineFromDueTime(uint64_t dueTime) noexcept - { - return Deadline(std::chrono::duration_cast(TimerDuration(dueTime))); - } - - uint64_t DueTimeFromDeadline(Deadline deadline) noexcept - { - return static_cast( - std::chrono::duration_cast(deadline.time_since_epoch()).count()); - } - - // The timer whose callback is currently executing on this thread, if any, - // and the threadpool callback instance it is running under. Terminate uses - // this to detect a callback that tears down its own timer. - thread_local void* t_callbackTimer = nullptr; - thread_local PTP_CALLBACK_INSTANCE t_callbackInstance = nullptr; -} - -namespace OS -{ - class WaitTimerImpl - { - public: - WaitTimerImpl() - : m_timer(nullptr) - {} - - ~WaitTimerImpl() - { - Terminate(); - } - - HRESULT Initialize(_In_opt_ void* context, _In_ WaitTimerCallback* callback) - { - m_context = context; - m_callback = callback; - - m_timer = CreateThreadpoolTimer(WaitCallback, this, nullptr); - RETURN_LAST_ERROR_IF_NULL(m_timer); - - return S_OK; - } - - void Terminate() - { - if (m_timer != nullptr) - { - SetThreadpoolTimer(m_timer, nullptr, 0, 0); - - // A timer callback can tear down its own timer, e.g. when the - // task queue port that owns this timer is released for the last - // time from inside the callback. WaitForThreadpoolTimerCallbacks - // would then wait for the very callback that is calling it and - // deadlock. Disassociate the current callback first so we only - // wait for other in-flight callbacks; the calling callback must - // not touch this object after Terminate returns (WaitCallback - // doesn't). - if (t_callbackTimer == this) - { - DisassociateCurrentThreadFromCallback(t_callbackInstance); - t_callbackTimer = nullptr; - t_callbackInstance = nullptr; - } - - WaitForThreadpoolTimerCallbacks(m_timer, TRUE); - CloseThreadpoolTimer(m_timer); - m_timer = nullptr; - } - } - - void Start(_In_ uint64_t dueTime) - { - LARGE_INTEGER li; - FILETIME ft; - - // The threadpool timer can run on its existing one-shot mechanism, - // but the due time we store in TaskQueue is now a steady-clock - // deadline. Convert that deadline back into a relative wait here so - // queue correctness no longer depends on wall-clock precision. - Deadline now = Clock::now(); - Deadline dueDeadline = DeadlineFromDueTime(dueTime); - TimerDuration remaining = dueDeadline > now - ? std::chrono::duration_cast(dueDeadline - now) - : TimerDuration::zero(); - - constexpr int64_t nanosPerTick = 100; - int64_t relativeTicks = - (static_cast(remaining.count()) + nanosPerTick - 1) / - nanosPerTick; - - // SetThreadpoolTimer expects negative values for relative waits. - // Clamp zero-or-past deadlines to the smallest relative delay so an - // already-due timer is queued immediately without switching back to - // absolute wall-clock FILETIME semantics. - if (relativeTicks <= 0) - { - relativeTicks = 1; - } - - li.QuadPart = -relativeTicks; - ft.dwHighDateTime = li.HighPart; - ft.dwLowDateTime = li.LowPart; - - SetThreadpoolTimer(m_timer, &ft, 0, 0); - } - - void Cancel() - { - SetThreadpoolTimer(m_timer, nullptr, 0, 0); - } - - private: - - PTP_TIMER m_timer; - void* m_context; - WaitTimerCallback* m_callback; - - static VOID CALLBACK WaitCallback( - _Inout_ PTP_CALLBACK_INSTANCE instance, - _Inout_opt_ void* context, - _Inout_ PTP_TIMER) - { - if (context != nullptr) - { - WaitTimerImpl* pthis = static_cast(context); - t_callbackTimer = pthis; - t_callbackInstance = instance; - - pthis->m_callback(pthis->m_context); - - // pthis may have been destroyed by the callback; don't touch it. - t_callbackTimer = nullptr; - t_callbackInstance = nullptr; - } - } - }; - - WaitTimer::WaitTimer() noexcept - : m_impl(nullptr) - {} - - WaitTimer::~WaitTimer() noexcept - { - Terminate(); - } - - HRESULT WaitTimer::Initialize(_In_opt_ void* context, _In_ WaitTimerCallback* callback) noexcept - { - std::lock_guard lock{ m_mutex }; - if (m_impl.load() != nullptr || callback == nullptr) - { - ASSERT(FALSE); - return E_UNEXPECTED; - } - - std::unique_ptr timer(new (std::nothrow) WaitTimerImpl); - RETURN_IF_NULL_ALLOC(timer.get()); - RETURN_IF_FAILED(timer->Initialize(context, callback)); - - m_impl = timer.release(); - - return S_OK; - } - - void WaitTimer::Terminate() noexcept - { - std::unique_ptr timer; - { - std::lock_guard lock{ m_mutex }; - timer.reset(m_impl.exchange(nullptr)); - } - if (timer != nullptr) - { - timer->Terminate(); - } - } - - void WaitTimer::Start(_In_ uint64_t dueTime) noexcept - { - std::lock_guard lock{ m_mutex }; - if (WaitTimerImpl* timer = m_impl.load()) - { - timer->Start(dueTime); - } - } - - void WaitTimer::Cancel() noexcept - { - std::lock_guard lock{ m_mutex }; - if (WaitTimerImpl* timer = m_impl.load()) - { - timer->Cancel(); - } - } - - uint64_t WaitTimer::GetCurrentTime() noexcept - { - return DueTimeFromDeadline(Clock::now()); - } - - uint64_t WaitTimer::GetDueTime(_In_ uint32_t msFromNow) noexcept - { - Deadline deadline = Clock::now() + std::chrono::milliseconds(msFromNow); - return DueTimeFromDeadline(deadline); - } -} // Namespace diff --git a/third_party/xtaskqueue/Source/Task/XAsyncProviderPriv.h b/third_party/xtaskqueue/Source/Task/XAsyncProviderPriv.h deleted file mode 100644 index 21ba2c798..000000000 --- a/third_party/xtaskqueue/Source/Task/XAsyncProviderPriv.h +++ /dev/null @@ -1,39 +0,0 @@ -// Copyright(c) Microsoft Corporation. All rights reserved. -// -// These APIs should be reserved for driving unit test harnesses. - -#pragma once - -#include "XAsyncProvider.h" - -/// -/// Initializes an async block for use. Once begun calls such -/// as XAsyncGetStatus will provide meaningful data. It is assumed the -/// async work will begin on some system defined thread after this call -/// returns. The token and function parameters can be used to help identify -/// mismatched Begin/GetResult calls. The token is typically the function -/// pointer of the async API you are implementing, and the functionName parameter -/// is typically the __FUNCTION__ compiler macro. -/// -/// This variant of XAsyncBegin will allocate additional memory of size contextSize -/// and use this as the context pointer for async provider callbacks. The memory -/// pointer is returned in 'context'. The lifetime of this memory is managed -/// by the async library and will be freed automatically when the call -/// completes. -/// -/// A pointer to the XAsyncBlock that holds data for the call. -/// An optional arbitrary pointer that can be used to identify this call. -/// An optional string that names the async call. This is typically the __FUNCTION__ compiler macro. -/// The function callback to invoke to implement the async call. -/// The size, in bytes, of additional context memory to allocate. -/// The size of a parameter block to copy into the allocated context. -/// The parameter block to copy. This will be copied into the allocated context. -STDAPI XAsyncBeginAlloc( - _Inout_ XAsyncBlock* asyncBlock, - _In_opt_ const void* identity, - _In_opt_ const char* identityName, - _In_ XAsyncProvider* provider, - _In_ size_t contextSize, - _In_ size_t parameterBlockSize, - _In_opt_ void* parameterBlock - ) noexcept; diff --git a/third_party/xtaskqueue/Source/Task/XTaskQueueDiagnostics.h b/third_party/xtaskqueue/Source/Task/XTaskQueueDiagnostics.h deleted file mode 100644 index 09ed0e6b2..000000000 --- a/third_party/xtaskqueue/Source/Task/XTaskQueueDiagnostics.h +++ /dev/null @@ -1,50 +0,0 @@ -// Copyright(c) Microsoft Corporation. All rights reserved. -// - -#pragma once - -#include "XTaskQueue.h" - -#if defined(HC_ENABLE_UNNAMED_OBJECT_DIAGNOSTICS) -struct XTaskQueueSyncObjectCounts -{ - uint64_t constructed; - uint64_t destroyed; - uint64_t live; -}; - -struct XTaskQueueSyncObjectSnapshot -{ - XTaskQueueSyncObjectCounts mutex; - XTaskQueueSyncObjectCounts recursiveMutex; - XTaskQueueSyncObjectCounts conditionVariable; - XTaskQueueSyncObjectCounts conditionVariableAny; - bool usesUnnamedConstructors; -}; - -/// -/// Gets aggregate construction and destruction counts for the synchronization -/// wrappers used by this module. Available only in diagnostic test builds. -/// -STDAPI XTaskQueueGetSyncObjectDiagnosticSnapshot( - _Out_ XTaskQueueSyncObjectSnapshot* snapshot - ) noexcept; - -/// -/// Constructs and destroys one of each synchronization wrapper, including a -/// recursive re-entry, and returns snapshots at each test boundary. -/// -STDAPI XTaskQueueRunSyncObjectDiagnosticProbe( - _Out_ XTaskQueueSyncObjectSnapshot* before, - _Out_ XTaskQueueSyncObjectSnapshot* during, - _Out_ XTaskQueueSyncObjectSnapshot* after - ) noexcept; - -/// -/// Closes per-process queue handles and waits for outstanding TaskQueue -/// lifecycle references to drain. This is an existing private test API. -/// -STDAPI_(bool) XTaskQueueUninitialize( - _In_ uint32_t timeoutMilliseconds - ) noexcept; -#endif diff --git a/third_party/xtaskqueue/Source/Task/XTaskQueuePriv.h b/third_party/xtaskqueue/Source/Task/XTaskQueuePriv.h deleted file mode 100644 index 11baff38a..000000000 --- a/third_party/xtaskqueue/Source/Task/XTaskQueuePriv.h +++ /dev/null @@ -1,204 +0,0 @@ -// Copyright(c) Microsoft Corporation. All rights reserved. -// - -#pragma once - -#include "XTaskQueue.h" -#include "XTaskQueueDiagnostics.h" - -//----------------------------------------------------------------// -// -// These APIs should be reserved for driving unit test harnesses. -// -//----------------------------------------------------------------// - -/// -/// Returns TRUE if there is no outstanding work in this -/// queue for the given callback port. -/// -/// The queue to check. -/// The port to check. -STDAPI_(bool) XTaskQueueIsEmpty( - _In_ XTaskQueueHandle queue, - _In_ XTaskQueuePort port - ) noexcept; - -/// -/// Suspends terminations on the task queue. May return an error if -/// the queue is already terminated. -/// -/// The queue to suspend terminations. -STDAPI XTaskQueueSuspendTermination( - _In_ XTaskQueueHandle queue - ) noexcept; - -/// -/// Resumes the ability to terminate the task queue. If a termination was -/// attempted it will be continued. -/// -/// The queue resume terminations. -STDAPI_(void) XTaskQueueResumeTermination( - _In_ XTaskQueueHandle queue - ) noexcept; - -/// -/// This structure can be passed as a pointer to the task queue so unit tests -/// can hook into its behavior. Some race conditions are very difficult to get -/// to happen naturally so sometimes a hook is needed. A pointer to this -/// structure will be stored on the task queue. It is up to the test to ensure -/// the structure lifetime exceeds that of the task queue under test. -/// -struct XTaskQueueTestHooks -{ - virtual void PendingEntriesRemovedDuringTermination( - XTaskQueuePort port) - { - UNREFERENCED_PARAMETER(port); - } - - virtual void NoNextPendingCallbackFound( - XTaskQueuePort port, - uint64_t dueTime) - { - UNREFERENCED_PARAMETER(port); - UNREFERENCED_PARAMETER(dueTime); - } - - virtual void NextPendingCallbackScheduled( - XTaskQueuePort port, - uint64_t lastDueTime, - uint64_t nextDueTime) - { - UNREFERENCED_PARAMETER(port); - UNREFERENCED_PARAMETER(lastDueTime); - UNREFERENCED_PARAMETER(nextDueTime); - } - - // Called after a timer sweep found a future pending callback, before the - // timer is re-armed from the fired due time to that callback's deadline. - virtual void NextPendingCallbackFound( - XTaskQueuePort port, - uint64_t dueTime, - uint64_t nextDueTime) - { - UNREFERENCED_PARAMETER(port); - UNREFERENCED_PARAMETER(dueTime); - UNREFERENCED_PARAMETER(nextDueTime); - } -}; - -/// -/// Sets or clears test hooks on a task queue. -/// -STDAPI XTaskQueueSetTestHooks( - _In_ XTaskQueueHandle queue, - _In_ XTaskQueueTestHooks* hooks - ) noexcept; - -/// -/// Submits any pending delayed callbacks that are due to run. This is -/// intended for use in unit tests. -/// -STDAPI XTaskQueueSubmitPendingCallbacks( - _In_ XTaskQueueHandle queue, - _In_ XTaskQueuePort port - ) noexcept; - -//----------------------------------------------------------------// -// -// These APIs are internal to the runtime -// -//----------------------------------------------------------------// - -/// -/// Suspends the activity of all task queues in the process. When -/// a task queue is suspended: -/// -/// 1. It will not signal when new items are added. -/// 2. It will not return items from the dispatcher (it acts like it -/// is empty). -/// -STDAPI_(void) XTaskQueueGlobalSuspend( - ) noexcept; - -/// -/// Resumes the activity of all task queues in the process. When -/// a task queue is resumed: -/// -/// 1. Queues that are not empty will signal they have items. -/// 2. The dispatcher will start returing items again. -/// -STDAPI_(void) XTaskQueueGlobalResume( - ) noexcept; - -/// -/// Options when duplicating a task queue handle. -/// -enum class XTaskQueueDuplicateOptions -{ - /// - /// Default behavior. - /// - None, - - /// - /// The duplicated queue is a reference to the actual - /// queue object, not a duplicated queue handle. References - /// work just like fully duplicated handles but they are not - /// tracked by the handle tracking infrastructure and do not - /// cause an allocation for the handle. - /// - Reference -}; - -/// -/// Increments the refcount on the queue and allows supplying -/// options as to how the duplicate is performed. -/// -STDAPI XTaskQueueDuplicateHandleWithOptions( - _In_ XTaskQueueHandle queueHandle, - _In_ XTaskQueueDuplicateOptions options, - _Out_ XTaskQueueHandle *duplicatedHandle - ) noexcept; - -/// -/// Returns a handle to the process task queue, or nullptr if there is no -/// process task queue. By default, there is a default process task queue -/// that uses the thread pool for both work and completion ports. This is an -/// internal variant that takes duplicate options. -/// -STDAPI_(bool) XTaskQueueGetCurrentProcessTaskQueueWithOptions( - _In_ XTaskQueueDuplicateOptions options, - _Out_ XTaskQueueHandle *queue - ) noexcept; - -/// -/// Uninitializes global task queue state. This closes handles to per-process -/// task queues and resets state back to defaults. If there is a per-process -/// task queue, it will be closed but not terminated. Queue termination is -/// up to the caller. This API returns true if all task queues have been -/// cleaned up and deleted, or false if there are still outstanding references. -/// A timeout may be provided to wait for outstanding queues to be cleaned up. -/// The default is not to wait. The maximum timeout capped to 5000ms. -/// -STDAPI_(bool) XTaskQueueUninitialize( - _In_ uint32_t timeoutMilliseconds = 0 - ) noexcept; - -#ifdef HC_UNITTEST_API -/// -/// Unit-test diagnostics: the number of task queue / task queue port objects -/// still alive and the outstanding global task queue reference count. Used to -/// report what leaked when XTaskQueueUninitialize fails. -/// -struct XTaskQueueLiveObjectCounts -{ - uint32_t globalRefs; - uint32_t queues; - uint32_t ports; -}; - -STDAPI_(void) XTaskQueueGetLiveObjectCounts( - _Out_ XTaskQueueLiveObjectCounts* counts - ) noexcept; -#endif diff --git a/third_party/xtaskqueue/Source/Task/referenced_ptr.h b/third_party/xtaskqueue/Source/Task/referenced_ptr.h deleted file mode 100644 index 5a18325cd..000000000 --- a/third_party/xtaskqueue/Source/Task/referenced_ptr.h +++ /dev/null @@ -1,108 +0,0 @@ -// Copyright (c) Microsoft Corporation -// Licensed under the MIT license. See LICENSE file in the project root for full license information. - -#pragma once - -template -struct referenced_ptr -{ - referenced_ptr() noexcept - : _ptr(nullptr) - {} - - explicit referenced_ptr(TInterface* ptr) noexcept - : _ptr(ptr) - { - add_ref(); - } - - referenced_ptr(const referenced_ptr& other) noexcept - : _ptr(other.get()) - { - add_ref(); - } - - referenced_ptr(referenced_ptr&& other) noexcept - : _ptr(other.release()) - {} - - referenced_ptr& operator=(const referenced_ptr& other) noexcept - { - if (this == &other) { return *this; } - - reset(); - _ptr = other.get(); - add_ref(); - - return *this; - } - - referenced_ptr& operator=(referenced_ptr&& other) noexcept - { - if (this == &other) { return *this; } - - reset(); - _ptr = other.release(); - - return *this; - } - - ~referenced_ptr() noexcept - { - reset(); - } - - TInterface* get() const noexcept - { - return _ptr; - } - - TInterface* release() noexcept - { - TInterface* ptr = _ptr; - _ptr = nullptr; - return ptr; - } - - void reset() noexcept - { - if (_ptr) _ptr->Release(); - _ptr = nullptr; - } - - explicit operator bool() const noexcept - { - return _ptr != nullptr; - } - - TInterface* operator->() const noexcept - { - return _ptr; - } - - TInterface** address_of() noexcept - { - reset(); - return &_ptr; - } - -private: - void add_ref() noexcept - { - if (_ptr) _ptr->AddRef(); - } - - TInterface* _ptr = nullptr; -}; - -template -bool operator==(referenced_ptr& p, std::nullptr_t) -{ - return p.get() == nullptr; -} - -template -bool operator!=(referenced_ptr& p, std::nullptr_t) -{ - return p.get() != nullptr; -} diff --git a/tools/ab_control_flow.py b/tools/ab_control_flow.py deleted file mode 100644 index ddc67da22..000000000 --- a/tools/ab_control_flow.py +++ /dev/null @@ -1,400 +0,0 @@ -"""GPU A/B of control flow: render branchy pixel shaders translated both ways, as one loop around a switch -(--dispatch-loop) and as real loops and conditionals (the default), and compare the two images byte for byte. - - python -I tools/ab_control_flow.py /shaders [--count 150] [--loops only] [--runs 3] - -Needs a finished shaders stage (the disassembly and index.json in /shaders), spirv-as and spirv-val on PATH, -and runtime/build/vk_texture_test (or --harness). Shaders are picked from the corpus: pixel stage, at least two -branches, only the bindings and features the harness provides, and nothing that writes memory or images. - -What the comparison needs to mean anything, each learned from a run that looked like a translator bug: - - Every pixel input has to be defined. The vertex shader made here writes all 32 locations; with the game's - pass-through one, which writes location 0 only, a shader that uses another input as a buffer index reads - from wherever the driver's leftover value points, differently in each form. - - Without an MRT0 export, compare only the mask of MRT0 pixels differing from the clear value. - - Shaders with loops go to a software driver first (--harness with a Linux build under Mesa llvmpipe). One - that never ends is killed after --timeout there; on a real GPU it resets the driver. Feed the ones that - finish back with --names. -The heap is zeros. Equal MRT0 readbacks can result from different execution paths. By default the harness binds only -MRT0. The rows in /outcomes.tsv distinguish clear-only matches and list unobserved colour targets. -Pass --all-attachments to use vk_ps_sweep and compare each declared RGBA32F target separately. -Usage: `python -I tools/ab_control_flow.py --help` lists the options. -""" -import argparse -import collections -import os -import re -import struct -import subprocess -import sys - -# Left out: anything that writes memory or images, LDS, and the rare instructions the harness has no setup for. -# Loads are fine: with empty user data they read zeros from the start of the harness's heap, the same for both. -NEEDS = re.compile(r"^\t(image_store|image_atomic|buffer_(?:store|atomic)|tbuffer_|global_store|global_atomic|ds_|s_swappc|" - r"s_getpc|s_sendmsg|s_sleep)", re.M) -BRANCH = re.compile(r"^\ts_c?branch", re.M) -BACK = re.compile(r"^\ts_c?branch\S* (\d+)", re.M) -CLEAR = struct.pack("<4f", -1, -1, -1, -1) # what vk_texture_test clears the image to -READBACK_BYTES = 64 * 64 * len(CLEAR) # vk_texture_test writes a 64x64 RGBA32F image -LOCATIONS = 32 # every pixel-shader input location gets a defined value -SUPPORTED_BINDINGS = {0, 1, 2} -HOSTED_FEATURES = {"bufferDeviceAddress", "runtimeDescriptorArray", "shaderInt64", "shaderSampledImageArrayDynamicIndexing"} - - -def is_backward_branch(disassembly): - """Return whether the disassembly contains a branch to the backward half of the address space.""" - return any(int(target) >= 0x8000 for target in BACK.findall(disassembly)) - - -def valid_metadata(metadata): - """Whether one index entry is an object whose bindings and features, when present, are lists of scalars.""" - return isinstance(metadata, dict) and all( - isinstance(metadata.get(key, []), list) - and all(not isinstance(v, bool) and isinstance(v, (int, str)) for v in metadata.get(key, [])) - for key in ("bindings", "features")) - - -def supported_pixel_shaders(index): - """Return sorted pixel-shader names whose bindings and features are available in the harness.""" - return sorted(name for name, metadata in index.items() - if valid_metadata(metadata) - and metadata.get("stage") == "ps" - and set(metadata.get("bindings", [])) <= SUPPORTED_BINDINGS - and set(metadata.get("features", [])) <= HOSTED_FEATURES) - - -def select_candidates(index, disasm_dir, spirv_dir, count=150, loops="none", names_file=None): - """Select shaders from synthetic or real metadata/disassembly inputs. - - An explicit names file intentionally bypasses automatic metadata, disassembly, SPIR-V and loop filtering, - matching the CLI's documented "run exactly these shaders" behavior. - """ - if loops not in ("none", "only"): - raise ValueError("loops must be 'none' or 'only'") - if count < 1: # the check below runs after the first append, so 0 or less still picked one shader - raise ValueError("count must be at least 1") - if names_file: - with open(names_file, encoding="utf-8") as f: - return [name for name in f.read().split("\n") if name] - - picked = [] - for name in supported_pixel_shaders(index): - asm_path = os.path.join(disasm_dir, name + ".s") - spv_path = os.path.join(spirv_dir, name + ".spv") - if not os.path.isfile(spv_path) or not os.path.isfile(asm_path): - continue - with open(asm_path, encoding="utf-8", errors="replace") as f: - text = f.read() - if NEEDS.search(text) or len(BRANCH.findall(text)) < 2: - continue - if is_backward_branch(text) != (loops == "only"): - continue - picked.append(name) - if len(picked) >= count: - break - return picked - - -def classify_result(translation_valid, dispatch_runs, structured_runs): - """Classify one shader's A/B result from each form's repeated harness outcomes. - - A run is bytes on success, None when the harness failed, or the string "timeout". Every run of each form - must agree before the two forms are compared. - """ - if not translation_valid: - return "a translation is invalid" - - dispatch = dispatch_runs[0] if dispatch_runs else None - structured = structured_runs[0] if structured_runs else None - if (any(result != dispatch for result in dispatch_runs[1:]) - or any(result != structured for result in structured_runs[1:])): - return "unstable from run to run" - - if dispatch is None or structured is None: - return "dispatch form failed to run" if dispatch is None else "structured form failed to run" - if dispatch == "timeout" or structured == "timeout": - if dispatch == "timeout" and structured == "timeout": - return "neither terminates" - return "ONLY ONE FORM TERMINATES" - return "identical" if dispatch == structured else "DIFFERENT" - - -def write_outcomes(out_dir, outcomes): - """Write (shader name, outcome) pairs to the harness's tab-separated report.""" - os.makedirs(out_dir, exist_ok=True) - path = os.path.join(out_dir, "outcomes.tsv") - with open(path, "w", encoding="utf-8", newline="\n") as f: - f.write("".join(f"{name}\t{outcome}\n" for name, outcome in outcomes)) - return path - - -def test_vertex_shader(out_dir, runner=None): - """Generate a full-screen triangle vertex shader and assemble/validate it. - - runner is injectable so tests can exercise source generation without requiring SPIR-V Tools. - """ - if runner is None: - runner = subprocess.run - nl = "\n" - asm = f"""OpCapability Shader -OpMemoryModel Logical GLSL450 -OpEntryPoint Vertex %main "main" %pos %vid {" ".join(f"%o{i}" for i in range(LOCATIONS))} -OpDecorate %pos BuiltIn Position -OpDecorate %vid BuiltIn VertexIndex -{nl.join(f"OpDecorate %o{i} Location {i}" for i in range(LOCATIONS))} -%void = OpTypeVoid -%fn = OpTypeFunction %void -%float = OpTypeFloat 32 -%int = OpTypeInt 32 1 -%v4 = OpTypeVector %float 4 -%po = OpTypePointer Output %v4 -%pi = OpTypePointer Input %int -%pos = OpVariable %po Output -%vid = OpVariable %pi Input -{nl.join(f"%o{i} = OpVariable %po Output" for i in range(LOCATIONS))} -%f0 = OpConstant %float 0 -%f1 = OpConstant %float 1 -%f2 = OpConstant %float 2 -%fm1 = OpConstant %float -1 -%i1 = OpConstant %int 1 -%i2 = OpConstant %int 2 -%zero = OpConstantComposite %v4 %f0 %f0 %f0 %f0 -%main = OpFunction %void None %fn -%l = OpLabel -%i = OpLoad %int %vid -%a = OpShiftLeftLogical %int %i %i1 -%b = OpBitwiseAnd %int %a %i2 -%c = OpBitwiseAnd %int %i %i2 -%u = OpConvertSToF %float %b -%v = OpConvertSToF %float %c -%x = OpFMul %float %u %f2 -%x2 = OpFAdd %float %x %fm1 -%y = OpFMul %float %v %f2 -%y2 = OpFAdd %float %y %fm1 -%p = OpCompositeConstruct %v4 %x2 %y2 %f0 %f1 -OpStore %pos %p -%t = OpCompositeConstruct %v4 %u %v %f0 %f1 -OpStore %o0 %t -{nl.join(f"OpStore %o{i} %zero" for i in range(1, LOCATIONS))} -OpReturn -OpFunctionEnd -""" - src, dst = os.path.join(out_dir, "test_vs.spvasm"), os.path.join(out_dir, "test_vs.spv") - os.makedirs(out_dir, exist_ok=True) - with open(src, "w", encoding="utf-8", newline="\n") as f: - f.write(asm) - runner(["spirv-as", "--target-env", "vulkan1.2", src, "-o", dst], check=True) - runner(["spirv-val", "--target-env", "vulkan1.2", dst], check=True) - return dst - - -def positive_int(text): - """--count, --runs and --timeout: a whole number of at least 1. --runs 0 rendered nothing and reported every - shader as "dispatch form failed to run"; --count 0 still ran one shader.""" - try: - value = int(text) - except ValueError: - raise argparse.ArgumentTypeError(f"not a whole number: {text!r}") from None - if value < 1: - raise argparse.ArgumentTypeError("must be at least 1") - return value - - -def render_targets(forms, name, harness, vs, out, runs, timeout, observed, declared, all_attachments): - """Collect repeated readbacks by attachment, retaining only the mask for undeclared MRT0.""" - count = observed[-1] + 1 - size = count * READBACK_BYTES - images = {target: [[], []] for target in observed} - for form, (tag, directory) in enumerate(forms): - spirv = os.path.join(directory, name + ".spv") - raw = os.path.join(out, f"{tag}.raw") - args = ["64", "64", str(count)] if all_attachments else ["8", "92", "c00000", "14500000", "0"] - for _ in range(runs): - if os.path.isfile(raw): - os.remove(raw) - data = None - failure = None - try: - h = subprocess.run([harness, vs, spirv, raw, *args], capture_output=True, text=True, - timeout=timeout) - if all_attachments and h.returncode == 3: - failure = "timeout" - if h.returncode == 0 and os.path.isfile(raw): - with open(raw, "rb") as readback: - packed = readback.read(size + 1) - if len(packed) == size: - data = packed - except subprocess.TimeoutExpired: - failure = "timeout" - for target in observed: - image = failure - if data is not None: - image = data[target * READBACK_BYTES:(target + 1) * READBACK_BYTES] - if target not in declared: - image = bytes(image[i:i + 16] != CLEAR for i in range(0, len(image), 16)) - images[target][form].append(image) - if failure == "timeout": - break - return images - - -def main(argv=None): - ap = argparse.ArgumentParser() - ap.add_argument("repo") - ap.add_argument("shaders") - ap.add_argument("out") - ap.add_argument("--count", type=positive_int, default=150) - ap.add_argument("--all-attachments", action="store_true", help="compare each colour export using vk_ps_sweep") - ap.add_argument("--harness", help="override the executable for the selected harness") - ap.add_argument("--loops", choices=("none", "only"), default="none", - help="'only': shaders with backward branches. Use a software driver for those: one that never " - "terminates is killed after --timeout seconds, where a real GPU would reset its driver") - ap.add_argument("--timeout", type=positive_int, default=60) - ap.add_argument("--names", help="run exactly the shaders listed in this file (one per line), no selection") - ap.add_argument("--runs", type=positive_int, default=1, - help="render each form this many times; all must agree") - a = ap.parse_args(argv) - disasm = os.path.join(a.shaders, "dxbc", "disasm") - old = os.path.join(a.shaders, "spirv") - # Everything the run reads is checked before anything is created: a mistyped shaders folder or names file - # used to leave an empty output tree behind and end in a traceback. - import json - index_path = os.path.join(old, "index.json") - try: - with open(index_path, encoding="utf-8") as f: - index = json.load(f) - except (OSError, ValueError, RecursionError) as e: - ap.error(f"cannot read {index_path}: {getattr(e, 'strerror', None) or e}") - if a.names and not os.path.isfile(a.names): - ap.error(f"--names {a.names} is not a file") - if not isinstance(index, dict) or any(not valid_metadata(item) for item in index.values()): - ap.error(f"{index_path}: expected a JSON object mapping shader names to metadata " - "(an object whose bindings and features, when present, are lists of numbers or strings)") - names = supported_pixel_shaders(index) - print(f"{len(names)} pixel shaders use only the bindings and features the harness provides") - try: - picked = select_candidates(index, disasm, old, count=a.count, loops=a.loops, names_file=a.names) - branches = [] - for name in picked: - with open(os.path.join(disasm, name + ".s"), encoding="utf-8", errors="replace") as f: - branches.append(len(BRANCH.findall(f.read()))) - branches.sort() - except (OSError, UnicodeError) as e: - ap.error(f"cannot read selected shader inputs: {e}") - if not picked: - print("ERROR: no shader candidates for the control-flow comparison", file=sys.stderr) - return 1 - new = os.path.join(a.out, "new") - out_existed = os.path.isdir(a.out) - new_existed = os.path.isdir(new) - try: - if out_existed: - os.listdir(a.out) # an unreadable output folder is reported here, before anything is written - os.makedirs(new, exist_ok=True) - except OSError as e: - ap.error(f"cannot create {new}: {e.strerror or e}") - # The texture test's harness: it binds a heap, a descriptor table, a fallback texture and a sampler. - exe = "vk_ps_sweep" if a.all_attachments else "vk_texture_test" - if os.name == "nt": - exe += ".exe" - harness = a.harness or os.path.join(a.repo, "runtime", "build", exe) - try: - vs = test_vertex_shader(a.out) - except (OSError, subprocess.CalledProcessError) as e: - # Remove only what this run created: its own files and the folders it made, and only while they are - # empty, so output another process wrote beside them survives. - for path in (os.path.join(a.out, "test_vs.spvasm"), os.path.join(a.out, "test_vs.spv")): - try: - os.remove(path) - except OSError: - pass - for path, existed in ((new, new_existed), (a.out, out_existed)): - if not existed: - try: - os.rmdir(path) - except OSError: - pass - ap.error(f"cannot build the test vertex shader (needs spirv-as and spirv-val on PATH): {e}") - - print(f"{len(picked)} branchy pixel shaders picked ({'with loops' if a.loops == 'only' else 'loop-free'}); " - f"branches per shader: median {branches[len(branches) // 2]}, max {branches[-1]}") - - # Both forms from the current translator, so the control-flow arrangement is the only difference. - loopdir = os.path.join(a.out, "dispatch") - os.makedirs(loopdir, exist_ok=True) - res = collections.Counter() - differ = [] - outcomes = [] - - def note(name, what): - res[what] += 1 - outcomes.append((name, what)) - - tool = os.path.join(a.repo, "tools", "rdna2spirv.py") - for name in picked: - src = os.path.join(disasm, name + ".s") - r1 = subprocess.run([sys.executable, "-I", tool, src, "--out", new], capture_output=True, text=True) - r2 = subprocess.run([sys.executable, "-I", tool, src, "--out", loopdir, "--dispatch-loop"], - capture_output=True, text=True) - if "1 pass spirv-val" not in r1.stdout or "1 pass spirv-val" not in r2.stdout: - note(name, "a translation is invalid") - continue - targets = [] - for directory in (loopdir, new): - with open(os.path.join(directory, name + ".spvasm"), encoding="utf-8") as assembly: - targets.append(set(re.findall(r"%out_mrt(\d+)\b", assembly.read()))) - if targets[0] != targets[1]: - note(name, "DIFFERENT colour target declarations") - differ.append(name) - continue - declared = sorted(map(int, targets[0])) - observed = sorted({0, *declared}) if a.all_attachments else [0] - if a.all_attachments: - cached = index.get(name, {}).get("outputs") - if cached is not None and (not isinstance(cached, list) or - any(type(t) is not int for t in cached) or sorted(cached) != declared): - note(name, "cached outputs disagree with translated colour targets") - continue - if observed[-1] > 7: - note(name, "colour target outside MRT0..7") - continue - images = render_targets((("old", loopdir), ("new", new)), name, harness, vs, a.out, a.runs, - a.timeout, observed, declared, a.all_attachments) - labels = [] - for target, (old_runs, new_runs) in images.items(): - outcome = classify_result(True, old_runs, new_runs) - if outcome in ("DIFFERENT", "ONLY ONE FORM TERMINATES") and name not in differ: - differ.append(name) - if outcome == "identical": - image = new_runs[0] - if target in declared: - detail = "clear-only" if image == CLEAR * (READBACK_BYTES // len(CLEAR)) else "non-clear" - outcome = f"identical MRT{target}: {detail}" - else: - detail = "nonempty" if any(image) else "empty" - outcome = f"identical MRT0 clear-difference mask: {detail}" - if target == 0: - step = len(CLEAR) if target in declared else 1 - res["identical and not all one colour"] += len( - set(image[i:i + step] for i in range(0, len(image), step))) > 1 - elif a.all_attachments: - outcome = f"MRT{target}: {outcome}" - labels.append(outcome) - outcome = "; ".join(labels) - unbound = sorted(set(declared) - set(observed)) - if unbound: - outcome += "; unobserved " + ", ".join(f"MRT{n}" for n in unbound) - note(name, outcome) - print(dict(res)) - for name in differ[:8]: - print(" differs:", name[:70]) - write_outcomes(a.out, outcomes) - return 0 - - -if __name__ == "__main__": - try: # a redirected stdout is strict ANSI code page under -I; write '?' for what it cannot encode - sys.stdout.reconfigure(errors="replace") - except (AttributeError, ValueError, OSError): - pass - sys.exit(main()) diff --git a/tools/amd_swizzle.py b/tools/amd_swizzle.py deleted file mode 100644 index 14732b690..000000000 --- a/tools/amd_swizzle.py +++ /dev/null @@ -1,300 +0,0 @@ -"""AMD GFX10/RDNA2 texture detiling from addrlib's published swizzle patterns. - -Reads gfx10SwizzlePattern.h (Mesa's addrlib, MIT licence) and builds, for a swizzle mode and pipe/packer -configuration, the equation that maps an element's (x, y) to its byte offset. 64 KB macro blocks are laid out -row-major; inside a block every address bit is an XOR of x and y bits (including bits above the block, which is -how the XOR modes spread neighbouring blocks across pipes). - -As a tool: - python -I amd_swizzle.py --bpe 8 --width 2048 --height 2048 [--offset N] [--modes 64K] [--out best.png] -tries every pattern table whose name has the --modes part (64K by default; 4K, 256, S_X, ...) and configuration -for that element size, each with its own block size, scores each by image smoothness, and renders the best. As a -module, `detile(data, pattern, bpe, wb, hb, block_bytes)` returns linear blocks. -""" -import argparse -import os -import re -import sys - -import numpy as np - -HEADER = os.environ.get("AMD_SWIZZLE_HEADER", r"\mesa-addrlib\gfx10SwizzlePattern.h") -BPE_INDEX = {1: 0, 2: 1, 4: 2, 8: 3, 16: 4} -# Address bits of one block for each pattern table size, as tex_mode_probe.py uses them (12 for 4 KB, 16 for 64 KB). -BLOCK_BITS = {"256": 8, "4K": 12, "64K": 16} -# Unsigned/void dtype whose item size is the element size, so detile gathers whole elements in one take. -_ELEMENT_DTYPE = {1: "u1", 2: " 12), or None for another size.""" - parts = table_name.split("_") - return BLOCK_BITS.get(parts[2]) if len(parts) > 3 else None - - -def table_matches(table_name, modes): - """Whether --modes picks this table: whole name parts, so 4K does not also pick the 64K tables.""" - return f"_{modes.strip('_')}_" in f"{table_name}_" - - -def _symbols(): - env = {} - for i in range(16): - env[f"X{i}"] = 1 << i - env[f"Y{i}"] = 1 << (16 + i) - env[f"Z{i}"] = 1 << (32 + i) - env[f"S{i}"] = 1 << (48 + i) - return env - - -def _term(text, env): - """Value of one pattern cell: symbols and integers joined by ^, the only syntax addrlib's tables use.""" - value = 0 - for part in text.split("^"): - part = part.strip() - if part in env: - value ^= env[part] - elif re.fullmatch(r"\d+", part): - value ^= int(part) - else: - raise ValueError(f"unexpected swizzle pattern term: {text!r}") - return value - - -def load(path=HEADER): - with open(path, encoding="utf-8", errors="replace") as f: - text = f.read() - env = _symbols() - nibbles = {} - for name in ("NIBBLE01", "NIBBLE2", "NIBBLE3", "NIBBLE4"): - m = re.search(r"GFX10_SW_PATTERN_" + name + r"\[\]\[\d+\]\s*=\s*\{(.*?)\n\};", text, re.S) - rows = re.findall(r"\{([^{}]*)\}", m.group(1)) - nibbles[name] = [[_term(t, env) for t in r.split(",") if t.strip()] for r in rows] - tables = {} - for m in re.finditer(r"const ADDR_SW_PATINFO (GFX10_SW_\w+_PATINFO)\[\]\s*=\s*\{(.*?)\n\};", text, re.S): - entries = [] - for row in m.group(2).splitlines(): - mm = re.match(r"\s*\{\s*(\d+),\s*(\d+),\s*(\d+),\s*(\d+),\s*(\d+),\s*\}\s*,\s*//\s*(.*)", row) - if mm: - entries.append(tuple(int(v) for v in mm.groups()[:5]) + (mm.group(6).strip(),)) - tables[m.group(1)] = entries - return nibbles, tables - - -def equation(nibbles, entry, block_bits): - """Per address bit, (x mask, y mask) for the given pattern entry, for the first `block_bits` bits.""" - _, n01, n2, n3, n4, _ = entry - bits = list(nibbles["NIBBLE01"][n01]) + list(nibbles["NIBBLE2"][n2]) + list(nibbles["NIBBLE3"][n3]) + \ - list(nibbles["NIBBLE4"][n4]) - return [(v & 0xFFFF, (v >> 16) & 0xFFFF) for v in bits[:block_bits]] - - -def _parity(a): - a = a ^ (a >> 8) - a = a ^ (a >> 4) - a = a ^ (a >> 2) - a = a ^ (a >> 1) - return a & 1 - - -def _axis_offsets(eq, n, mask_of, shift): - """In-block address contribution of one axis: each address bit is an XOR of x bits and y bits, so the offset - of (x, y) is the XOR of a function of x alone and a function of y alone. Evaluating those two 1-D tables - (length wb and hb) replaces the per-bit parity over the whole wb x hb grid. `shift` drops the low address - bits (a right shift distributes over XOR) so detile gets element indices without a pass over the grid.""" - coord = np.arange(n, dtype=np.int64) - acc = np.zeros(n, dtype=np.int64) - for bit, masks in enumerate(eq): - m = masks[mask_of] - if m: - acc |= _parity(coord & m) << bit - return acc >> shift if shift else acc - - -def _grid(eq, wb, hb, bw, bh, block_bytes, shift): - """(hb, wb) int64 array of ((XOR of the address bits) + block * block_bytes) >> shift, built in place.""" - blocks_x = (wb + bw - 1) // bw - col = _axis_offsets(eq, wb, 0, shift) - row = _axis_offsets(eq, hb, 1, shift) - unit = block_bytes >> shift # block_bytes is a multiple of 1 << shift, so the shift splits over the sum - out = np.bitwise_xor(row[:, None], col[None, :]) - out += (np.arange(hb, dtype=np.int64) // bh * (blocks_x * unit))[:, None] - out += (np.arange(wb, dtype=np.int64) // bw * unit)[None, :] - return out - - -def _block_shape(bpe, block_bytes): - """Macro-block size in elements, from the element count. - - Deriving it from the x/y bits that appear alone in an address bit only works for the S modes; in the XOR modes - the high bits are almost always XORed, so the block came out too small (72/75 RDNA2 R_X entries). - tex_export.detile_offsets uses this same formula for 4 KB blocks and it matches every 64 KB entry.""" - elems = block_bytes // bpe - lb = elems.bit_length() - 1 - bw = 1 << ((lb + 1) // 2) - return bw, elems // bw - - -def offsets(eq, bpe, wb, hb, block_bytes=65536): - """Byte offset of every element (row-major y, x) for a wb x hb element grid.""" - xb = max((mx.bit_length() for mx, _ in eq if mx), default=0) - yb = max((my.bit_length() for _, my in eq if my), default=0) - bw, bh = _block_shape(bpe, block_bytes) - return _grid(eq, wb, hb, bw, bh, block_bytes, 0), (bw, bh, xb, yb) - - -def feature(linear, bpe): - """Per-element RGB for the smoothness score: raw RGB for uncompressed bpe, colour endpoint for BC.""" - if bpe == 4: - return linear.reshape(-1, 4)[:, :3].astype(np.float32) - if bpe == 2: - p = linear.reshape(-1, 2).astype(np.float32) - return np.stack([p[:, 0], p[:, 1], (p[:, 0] + p[:, 1]) * 0.5], axis=-1) - if bpe == 1: - return np.repeat(linear.reshape(-1, 1).astype(np.float32), 3, axis=1) - from tile_probe import block_feature - return block_feature(linear, bpe) - - -def detile(data, eq, bpe, wb, hb, block_bytes=65536): - raw = np.frombuffer(data[: len(data) // bpe * bpe], np.uint8).reshape(-1, bpe) - bw, bh = _block_shape(bpe, block_bytes) - shift = bpe.bit_length() - 1 - if bpe & (bpe - 1) == 0 and block_bytes % bpe == 0: - idx = _grid(eq, wb, hb, bw, bh, block_bytes, shift) - else: - idx = _grid(eq, wb, hb, bw, bh, block_bytes, 0) // bpe - if idx.size and idx.max() >= len(raw): - return None - flat = idx.reshape(-1) - if bpe in _ELEMENT_DTYPE: - # One gather of whole elements instead of bpe separate byte rows. - # Reading `data` as one wide element needs its length to be a multiple of bpe, which the slice above ensures. - wide = raw.reshape(-1).view(_ELEMENT_DTYPE[bpe]) - return wide.take(flat).view(np.uint8).reshape(-1, bpe) - return raw[flat] - - -def validate_out_path(out, blob, same_report_path): - """Return an error string if `out` cannot be used as an --out image path, or None.""" - if not out or not out.strip(): - return "--out path must not be empty" - if "\x00" in out: - return "--out path contains a NUL byte" - if out.endswith(os.sep) or (os.altsep and out.endswith(os.altsep)) or os.path.isdir(out): - return f"--out path is a directory: {out}" - cur = os.path.dirname(os.path.abspath(out)) - while cur: - if os.path.isdir(cur): - break - if os.path.lexists(cur): - return f"--out parent is not a directory: {cur}" - nxt = os.path.dirname(cur) - if nxt == cur: - break - cur = nxt - if same_report_path(out, blob) or (os.path.exists(out) and os.path.exists(blob) and os.path.samefile(out, blob)): - return f"--out must not overwrite the input {blob}" - return None - - -def main(argv=None): - sys.path.insert(0, os.path.dirname(__file__)) - from tile_probe import same_report_path, score - from swizzle_search import render # noqa: F401 - ap = argparse.ArgumentParser() - ap.add_argument("blob") - ap.add_argument("--bpe", type=int, choices=(1, 2, 4, 8, 16), default=8) - ap.add_argument("--width", type=int, required=True) - ap.add_argument("--height", type=int, required=True) - ap.add_argument("--offset", type=int, default=0) - ap.add_argument("--modes", default="_64K_") - ap.add_argument("--out") - a = ap.parse_args(argv) - if a.out is not None: - err = validate_out_path(a.out, a.blob, same_report_path) - if err: - print(f"ERROR: {err}", file=sys.stderr) - return 2 - try: - with open(a.blob, "rb") as f: - data = f.read()[a.offset:] - except OSError as e: - print(f"ERROR: {a.blob}: {e.strerror or e}", file=sys.stderr) - return 2 - nibbles, tables = load() - # BC formats cover 4x4 pixels per element; uncompressed 1/2/4 bpe formats have one pixel per element. - block = 4 if a.bpe in (8, 16) else 1 - wb = (a.width + block - 1) // block - hb = (a.height + block - 1) // block - res = [] - for tname, entries in tables.items(): - bits = block_bits(tname) - if bits is None or not table_matches(tname, a.modes): - continue - for e in entries: - if f" {a.bpe} bpe" not in e[5]: - continue - eq = equation(nibbles, e, bits) - lin = detile(data, eq, a.bpe, wb, hb, 1 << bits) - if lin is None: - continue - img = feature(lin, a.bpe).reshape(hb, wb, 3) - res.append((score(img), tname, e[5], e, bits)) - res.sort(key=lambda r: r[0]) - seen = set() - for s, t, c, _, _ in res: - if (t, c) in seen: - continue - seen.add((t, c)) - print(f"{s:8.2f} {t:40} {c}") - if len(seen) >= 10: - break - if a.out and res: - import io - import struct - from PIL import Image - bits = res[0][4] - lin = detile(data, equation(nibbles, res[0][3], bits), a.bpe, wb, hb, 1 << bits) - if a.bpe == 1: - preview = Image.fromarray(lin.reshape(hb, wb)).convert("RGB") - elif a.bpe == 2: - rgb = np.zeros((hb, wb, 3), dtype=np.uint8) - rgb[:, :, :2] = lin.reshape(hb, wb, 2) - preview = Image.fromarray(rgb) - else: - hdr = bytearray(128) - hdr[0:4] = b"DDS " - struct.pack_into("", a.out) - return 0 - - -if __name__ == "__main__": - try: # a redirected stdout is strict ANSI code page under -I; write '?' for what it cannot encode - sys.stdout.reconfigure(errors="replace") - except (AttributeError, ValueError, OSError): - pass - sys.exit(main()) diff --git a/tools/analyze_4240_full.py b/tools/analyze_4240_full.py deleted file mode 100644 index a12b1f46e..000000000 --- a/tools/analyze_4240_full.py +++ /dev/null @@ -1,344 +0,0 @@ -#!/usr/bin/env python3 -"""Analyze `42 40 00 00` vertex blocks in RPF9 archives (ASSET-57). - -These blocks use the same 0x60-byte slot-word header as `63 30 00 00` mesh blocks, -but with different vertex formats. This tool finds and measures their strides. -Usage: `python -I tools/analyze_4240_full.py --help` lists the options. -""" - -import argparse -import json -import mmap -import os -import re -import struct -import sys -import zlib - -# -I keeps the script directory off sys.path, so add it explicitly before importing the sibling module. -sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) -from report_paths import same_report_path # noqa: E402 - -# Constants from meshlet_page.py -BLOCK_MAGIC = 0x3063 # 63 30 00 00 -OTHER_BLOCK_MAGIC = 0x4042 # 42 40 00 00 -HEADER_SIZE = 0x60 -SLOT_COUNT = 23 -ZHDR = re.compile(rb"\x78[\x01\x5e\x9c\xda]") - -def _u32(data, at): - if at + 4 > len(data): - raise ValueError(f"truncated at +0x{at:x}") - return struct.unpack_from(" len(data): - return False - vbase = tbase = 0 - for m in range(meshlets): - w0, w1, _, _ = struct.unpack_from("<4I", data, rec_at + 16 * m) - vcount = (w0 & 0x7F) + 1 - tcount = ((w0 >> 7) & 0x7F) + 1 - if (w1 & 0xFFFF) != (vbase & 0xFFFF) or (w1 >> 16) != (tbase & 0xFFFF): - return False - if tbase + tcount > triangles or vbase + vcount > refs: - return False - vbase += vcount - tbase += tcount - return vbase == refs and tbase == triangles - except Exception: - return False - -def iter_archive_streams(path): - """Yield (stream_offset, decompressed_data) for every zlib stream that is a mesh page.""" - with open(path, "rb") as fh: - if not os.fstat(fh.fileno()).st_size: - return - m = mmap.mmap(fh.fileno(), 0, access=mmap.ACCESS_READ) - try: - size = len(m) - pos = struct.unpack_from("= 8 else size - if pos > size: - raise ValueError(f"{path}: header data offset {pos} is past the end of the file ({size} bytes)") - while pos < size: - match = ZHDR.search(m, pos) - if not match: - break - s = match.start() - try: - d = zlib.decompressobj() - chunks = [] - p = s - while not d.eof and p < size: - block = m[p:p + (1 << 20)] - chunks.append(d.decompress(block)) - p += len(block) - if d.unused_data or d.eof: - break - out = b"".join(chunks) + d.flush() - except zlib.error: - pos = s + 1 - continue - if not d.eof or len(out) < 64: - pos = s + 1 - continue - if is_mesh_page(out): - yield f"0x{s:x}", out - pos = p - len(d.unused_data) - finally: - m.close() - -def parse_4240_block(data, at, stream_end): - """Parse a `42 40 00 00` vertex block. Returns (record, end_offset).""" - if at + HEADER_SIZE > len(data): - raise ValueError(f"block header truncated at +0x{at:x}") - words = struct.unpack_from("<24I", data, at) - if words[0] != OTHER_BLOCK_MAGIC: - raise ValueError(f"no 4240 block magic at +0x{at:x} (got 0x{words[0]:08x})") - - # Parse slot words: low byte = tag, high 24 bits = offset/2 - slots = {i: (w & 0xFF, (w >> 8) * 2) for i, w in enumerate(words[:SLOT_COUNT]) if w} - - record = { - "kind": "4240_block", - "offset": at, - "flags": words[23], - "slots": [[i, tag, off] for i, (tag, off) in sorted(slots.items())], - "slot_count": len(slots), - "slot_tags": {i: tag for i, (tag, _) in slots.items()}, - "slot_offsets": {i: off for i, (_, off) in slots.items()}, - } - - # Compute strides from slot offsets - if slots: - ordered = sorted(slots.items(), key=lambda x: x[1][1]) - for j in range(len(ordered) - 1): - idx1, (tag1, off1) = ordered[j] - idx2, (tag2, off2) = ordered[j + 1] - stride = off2 - off1 - if stride > 0: - record.setdefault("strides", []).append({ - "from_slot": idx1, - "from_tag": tag1, - "from_offset": off1, - "to_slot": idx2, - "to_tag": tag2, - "to_offset": off2, - "stride": stride, - }) - - # Also compute stride from slot 0 (assumed position) to each subsequent slot - if 0 in slots and slots[0][1] == HEADER_SIZE: - base_off = HEADER_SIZE - for idx, (tag, off) in slots.items(): - if idx != 0 and off > base_off: - stride = off - base_off - record.setdefault("strides_from_slot0", []).append({ - "slot": idx, - "tag": tag, - "offset": off, - "stride": stride, - }) - - return record, at + HEADER_SIZE - -def process_archive(archive_path, limit=None): - """Process an RPF9 archive and return stats on 4240 blocks.""" - stats = { - "archive": archive_path, - "streams": 0, - "blocks_4240": 0, - "blocks_6330": 0, - "groups": 0, - "block_formats": {}, - "strides": {}, - "strides_from_slot0": {}, - "slot_tag_counts": {}, - "slot_offsets": {}, - "errors": 0, - } - - for stream_name, stream_data in iter_archive_streams(archive_path): - if limit and stats["streams"] >= limit: - break - stats["streams"] += 1 - - # Walk stream - pos = 0 - while pos < len(stream_data): - pos = (pos + 15) & ~15 - if pos >= len(stream_data): - break - while pos + 4 <= len(stream_data) and _u32(stream_data, pos) == 0: - pos += 4 - if pos >= len(stream_data): - break - pos &= ~15 - if pos + 4 > len(stream_data): - break - word = _u32(stream_data, pos) - - if word == OTHER_BLOCK_MAGIC: - try: - record, pos = parse_4240_block(stream_data, pos, len(stream_data)) - stats["blocks_4240"] += 1 - - # Record slot tags - for slot_idx, tag in record["slot_tags"].items(): - stats["slot_tag_counts"][(slot_idx, tag)] = stats["slot_tag_counts"].get((slot_idx, tag), 0) + 1 - - # Record strides between consecutive slots - if "strides" in record: - for s in record["strides"]: - key = (s["from_slot"], s["from_tag"], s["to_slot"], s["to_tag"], s["stride"]) - stats["strides"][key] = stats["strides"].get(key, 0) + 1 - - # Record strides from slot 0 - if "strides_from_slot0" in record: - for s in record["strides_from_slot0"]: - key = (s["slot"], s["tag"], s["stride"]) - stats["strides_from_slot0"][key] = stats["strides_from_slot0"].get(key, 0) + 1 - - # Format signature - fmt_sig = tuple(sorted(record["slot_tags"].items())) - stats["block_formats"][fmt_sig] = stats["block_formats"].get(fmt_sig, 0) + 1 - - except ValueError as e: - # Advance past the rejected block: staying on the same word parsed it again for ever. - stats["errors"] += 1 - stats.setdefault("first_error", str(e)) - pos += 4 - elif word == BLOCK_MAGIC: - stats["blocks_6330"] += 1 - pos += HEADER_SIZE - elif word & 0x80000000: - head = _u32(stream_data, pos) - meshlets = head & 0x7FFFFFFF - triangles = _u32(stream_data, pos + 4) - refs = _u32(stream_data, pos + 8) - rec_at = pos + 12 - tri_at = rec_at + 16 * meshlets - ref_at = tri_at + 4 * triangles - end = ref_at + 2 * refs - if end <= len(stream_data): - pos = end - else: - pos += 4 - stats["groups"] += 1 - else: - pos += 4 - - return stats - -def positive_int(text): - """--limit: 0 is falsy and scanned everything, and a negative number scanned one stream.""" - try: - value = int(text, 0) - except ValueError: - raise argparse.ArgumentTypeError(f"invalid int value: {text!r}") from None - if value < 1: - raise argparse.ArgumentTypeError("must be at least 1") - return value - - -def main() -> int: - parser = argparse.ArgumentParser(description="Analyze 42 40 00 00 vertex blocks in RPF9 archives") - parser.add_argument("inputs", nargs="+", help="RPF9 archive paths") - parser.add_argument("--json", help="Write results to JSON file") - parser.add_argument("--limit", type=positive_int, help="Limit streams per archive") - args = parser.parse_args() - # Checked before the scan: the report is written after every archive has been read, so a --json naming one of - # them replaced the archive with the report, and a folder only failed once the whole scan was done. - if args.json: - if os.path.isdir(args.json): - print(f"ERROR: --json {args.json} is a folder, not a file", file=sys.stderr) - return 2 - for path in args.inputs: - if same_report_path(args.json, path): - print(f"ERROR: --json {args.json} would overwrite the input archive {path}", file=sys.stderr) - return 2 - - all_stats, status = [], 0 - for path in args.inputs: - if not os.path.exists(path): - # A missing input is a usage error (2); a folder that exists but is not an archive is a read error (1). - print(f"ERROR: {path}: does not exist", file=sys.stderr) - status = max(status, 2) - continue - if not os.path.isfile(path): - # A folder passed for an archive used to reach open() and end the whole run with PermissionError. - print(f"ERROR: {path} is not a file", file=sys.stderr) - status = max(status, 1) - continue - print(f"Processing {path}...") - try: - stats = process_archive(path, limit=args.limit) - except ValueError as e: - # A truncated archive or a bad data offset otherwise looks like an empty successful scan. - print(f"ERROR: {e}", file=sys.stderr) - status = 1 - continue - except OSError as e: - print(f"ERROR: cannot read {path}: {e.strerror or e}", file=sys.stderr) - status = max(status, 1) - continue - all_stats.append(stats) - - print(f" Streams: {stats['streams']}") - print(f" 4240 blocks: {stats['blocks_4240']}") - print(f" 6330 blocks: {stats['blocks_6330']}") - print(f" Groups: {stats['groups']}") - print(f" Unique formats: {len(stats['block_formats'])}") - print(f" Slot tag counts: {sorted(stats['slot_tag_counts'].items())}") - print(f" Strides (consecutive): {sorted(stats['strides'].items())}") - print(f" Strides from slot 0: {sorted(stats['strides_from_slot0'].items())}") - - # Show top formats - for fmt, count in sorted(stats['block_formats'].items(), key=lambda x: -x[1])[:10]: - tags = [f"slot{i}:tag{tag}" for i, tag in fmt] - print(f" Format ({count}x): {', '.join(tags)}") - - if args.json: - output = [] - for s in all_stats: - s_copy = dict(s) - s_copy["block_formats"] = {str(k): v for k, v in s["block_formats"].items()} - s_copy["strides"] = {str(k): v for k, v in s["strides"].items()} - s_copy["strides_from_slot0"] = {str(k): v for k, v in s["strides_from_slot0"].items()} - s_copy["slot_tag_counts"] = {str(k): v for k, v in s["slot_tag_counts"].items()} - output.append(s_copy) - parent = os.path.dirname(os.path.abspath(args.json)) - try: - if parent: # every archive has been read by now; a missing folder used to lose the run - os.makedirs(parent, exist_ok=True) - with open(args.json, "w", encoding="utf-8", newline="\n") as f: - json.dump(output, f, indent=2) - except OSError as e: - print(f"ERROR: cannot write {args.json}: {e.strerror or e}", file=sys.stderr) - return 2 - return status - - -if __name__ == "__main__": - try: # a redirected stdout is strict ANSI code page under -I; write '?' for what it cannot encode - sys.stdout.reconfigure(errors="replace") - except (AttributeError, ValueError, OSError): - pass - sys.exit(main()) diff --git a/tools/anim_clips.py b/tools/anim_clips.py deleted file mode 100644 index 14783e0cb..000000000 --- a/tools/anim_clips.py +++ /dev/null @@ -1,1593 +0,0 @@ -"""Decode the clip dictionaries in anim.rpf: clips, animations and their keyframe channels. - -The table of contents is encrypted, so this starts from the same stream walk as anim_index.py: every zlib stream -that inflates cleanly to its end. A clip dictionary is a RAGE resource whose system pages are one or two of those -streams. Its root stream starts with 8 zero bytes, a 0x50xxxxxx page-map pointer at +8 and zeros up to +0x38. The -page map's byte at +8 gives the number of system pages, and the dictionary takes that many back-to-back streams. -A last page that anim_index does not list (a zlib stream inflating to fewer than 64 bytes, or a 16-byte raw page -right after the stream) is joined when the pages then parse. Pointers are then offsets into the joined pages -(pointer - 0x50000000). See docs/animation.md, "Keyframe decoding". - -Hash-only references are joined across the archive: a root pack reference with a null pointer is another -dictionary's joaat32(name), and each `.motion` child is {clip hash, dictionary hash}; the counts say how many of -them are found in the same archive. - -Every animation is decoded down to the per-frame values. The default output is counts only: the number of -dictionaries, clips, animations, sequences, channels by type and track types. The checks are also counted: channel -definitions ending at the frame data, type-10 chunk closure, sequence boundaries and quaternion norms. The local -JSON adds one row per dictionary (offset, hash, counts, and its name, read from your own copy). No values or -payloads are written. - -Usage: - python -I anim_clips.py [--start N] [--limit BYTES] [--jobs N] [--quiet] - python -I anim_clips.py --decode [--frames N] - -`--decode` prints one dictionary's clips and the decoded track values (first N frames, default 4) as JSON on -stdout, for local inspection. It writes no file. -Usage: `python -I tools/anim_clips.py --help` lists the options. -""" -import argparse -import collections -import json -import math -import mmap -import os -import struct -import sys -import time -import zlib - -# -I keeps the script directory off sys.path, so add it explicitly before importing the stream walk. -sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) - -import anim_index # noqa: E402 -from pool_workers import process_workers # noqa: E402 - -SYSTEM = 0x50000000 -CHANNEL_NAMES = ("static_quat", "static_vec3", "static_float", "raw_float", "quantize_float", - "indirect_quantize_float", "linear_float", "cached_quat", "quat_normalize", "type9", - "delta2_float") -# Track-type hashes are joaat32 of these names. -TRACK_TYPE_NAMES = ("bonerotation", "bonetranslation", "bonescale", "genericcontrol", "generictranslation", - "facialtranslation", "cameratranslation", "camerarotation") -TRACK_TYPES = {anim_index.joaat32(n): n for n in TRACK_TYPE_NAMES} -TRACK_FORMATS = {0: "quaternion", 2: "vector3", 4: "float"} - -# `.motion` axis names: joaat32 of the lower-case name, recovered by brute force over a word list -AXIS_NAMES = {anim_index.joaat32(n): n for n in ("yawangle", "rotationz", "facingdirection", "speed", "surfaceincline", - "roll", "verticalheight", "pitch", "pitchangle", "height")} - - -class DecodeError(ValueError): - pass - - -class NotClipDictionary(DecodeError): - """A root with the dictionary header whose +0x70 is not a pack array.""" - - -class System: - """Joined system pages of one resource. Non-null pointers must land inside the pages.""" - - def __init__(self, data): - self.d = data - - def u16(self, at): - return struct.unpack_from(" len(self.d): - raise DecodeError(f"field at 0x{at:x} is outside the pages") - q = self.u64(at) - if q == 0: - return None - if not SYSTEM <= q < SYSTEM + len(self.d): - raise DecodeError(f"pointer 0x{q:x} at 0x{at:x} is outside the pages") - return q - SYSTEM - - def string(self, at): - """16-byte atString: {char *ptr; u16 length; u16 capacity}, or a short string stored inline, in which - case byte 15 is 0x80 | length and the characters start at byte 0.""" - if at < 0 or at + 16 > len(self.d): - raise DecodeError(f"string at 0x{at:x} is outside the pages") - tag = self.d[at + 15] - if tag & 0x80: - n = tag & 0x7F - if n > 15: - raise DecodeError(f"inline string at 0x{at:x} is {n} bytes") - return self.d[at:at + n].decode("latin-1") - p = self.ptr(at) - if p is None: - return None - n = self.u16(at + 8) - if p + n > len(self.d): - raise DecodeError("string runs past the pages") - return self.d[p:p + n].decode("latin-1") - - def array(self, at): - """{T *ptr; u16 count; u16 capacity} -> (offset or None, count)""" - p = self.ptr(at) - return (p, self.u16(at + 8)) if p is not None else (None, 0) - - def atmap(self, at): - """atMap {Entry **buckets; u32 bucket count; ...}, Entry {u64 key; T *value; Entry *next}""" - buckets, n = self.ptr(at), self.u32(at + 8) - if buckets is None: - return [] - if n > 4096: - raise DecodeError(f"atMap at 0x{at:x} has {n} buckets") - out, seen = [], set() - for i in range(n): - e = self.ptr(buckets + 8 * i) - while e is not None: - if e in seen: - raise DecodeError("atMap chain loops") - seen.add(e) - out.append((self.u64(e), self.ptr(e + 8))) - e = self.ptr(e + 16) - return out - - -# ---------------------------------------------------------------- structure - - -def parse_animation(s, at): - seqs, nseq = s.array(at + 0x50) - tracks, ntr = s.array(at + 0x60) - return { - "offset": at, "frames": s.u16(at + 0x24), "duration": s.f32(at + 0x28), - "sequences": [s.ptr(seqs + 8 * i) for i in range(nseq)], - "tracks": [struct.unpack_from("<3I", s.d, tracks + 12 * i) for i in range(ntr)], - } - - -def motion_times(s, at): - """`.motion` +0x70: one 0x28-byte entry per child, {f32 child duration, f32 duration in the blend, - {ptr, u16 count} curve of (child time, blend time) f32 pairs, 16 zero bytes}. -> [(duration, blend, points)]""" - p, n = s.array(at + 0x70) - out = [] - for i in range(n if p is not None else 0): - e = p + 0x28 * i - cp, cn = s.array(e + 8) - points = [(s.f32(cp + 8 * j), s.f32(cp + 8 * j + 4)) for j in range(cn)] if cp is not None else [] - out.append((s.f32(e), s.f32(e + 4), points)) - return out - - -# Where a multi-axis node keeps its sample count (the number of +0x90 sample lists of a one-node `.motion`) -NODE_SAMPLE_COUNT_AT = {4: 0x90, 5: 0x90, 6: 0x50, 8: 0xA0} - - -def parameter_node(s, at, parameters): - """The node that places a `.motion`'s children in parameter space: the pointer at +0x138 when +0x58 is 1; - when +0x58 is 2, +0x120 points at a block whose +0x18 is the node. A node starts {u64 0, u32 type, u32 0}. - Types 3, 4, 5, 6 and 8 have 1, 2, 3, 4 and 5 axes: +0x10 is an array of 8-byte {u32 name hash, u16, u16}. - Type 3 is one sampled axis: then an array of (u32 sample index, f32 value) sorted by value, f32 min, f32 max. - Types 4, 5, 6 and 8 keep their sample count at NODE_SAMPLE_COUNT_AT, and +0x20 is a {ptr, count} array of - 16-byte items ("pairs": words 0 and 2; {u32, u32 0, u32, u32 0} on types 6 and 8, null on type 4, not decoded); - the rest of them is not decoded. - Type 1 has no axes and its sample count (1) at +0x20. - -> (type, axis or None) or None; axis = {names, slots, sample_count, and samples, min, max for type 3 or - pairs for types 4-8}""" - if parameters == 1: - node = s.ptr(at + 0x138) - elif parameters == 2: - block = s.ptr(at + 0x120) - node = s.ptr(block + 0x18) if block is not None else None - else: - return None - if node is None or s.u64(node) != 0 or s.u32(node + 12) != 0: - return None - kind, axis = s.u32(node + 8), None - if kind == 1: - axis = {"names": [], "slots": [], "sample_count": s.u32(node + 0x20)} - elif kind == 3 or kind in NODE_SAMPLE_COUNT_AT: - names, nn = s.array(node + 0x10) - if names is not None: - axis = {"names": [s.u32(names + 8 * i) for i in range(nn)], - "slots": [(s.u16(names + 8 * i + 4), s.u16(names + 8 * i + 6)) for i in range(nn)]} - if kind == 3: - samples, ns = s.array(node + 0x20) - if samples is None: - return kind, None - axis.update(samples=[(s.u32(samples + 8 * i), s.f32(samples + 8 * i + 4)) for i in range(ns)], - min=s.f32(node + 0x30), max=s.f32(node + 0x34), sample_count=ns) - else: - axis["sample_count"] = s.u32(node + NODE_SAMPLE_COUNT_AT[kind]) - pairs, npairs = s.array(node + 0x20) # null on type 4 and most type 5 - axis["pairs"] = None if pairs is None else [(s.u32(pairs + 16 * i), s.u32(pairs + 16 * i + 8)) - for i in range(npairs)] - return kind, axis - - -def matcher_array(s, field): - """A `.motionmatcher` array: the pointer at `field`, its u32 count at `field - 4`. -> (offset or None, count)""" - p, n = s.ptr(field), s.u32(field - 4) - if p is None and n: - raise DecodeError(f"array at 0x{field:x} has {n} items and no data") - return p, n - - -def matcher_values(s, field, fmt): - """The items of the `matcher_array` at `field`, each unpacked with the struct format `fmt` (one value per item - for a one-letter format). -> list""" - p, n = matcher_array(s, field) - size = struct.calcsize("<" + fmt) - if n and p + size * n > len(s.d): - raise DecodeError(f"array at 0x{field:x} runs past the pages") - items = [struct.unpack_from("<" + fmt, s.d, p + size * i) for i in range(n)] - return [x[0] for x in items] if len(fmt) == 1 else items - - -def hash_table(s, field, slot): - """An open-addressing table: u32 group count at `field`, u32 entry count at +4, pointer at +8. Each group is 16 - control bytes (0x80 empty, below 0x80 full) and then 16 slots of `slot` bytes. -> offsets of the full slots""" - groups, count, p = s.u32(field), s.u32(field + 4), s.ptr(field + 8) - if p is None: - if groups or count: - raise DecodeError(f"table at 0x{field:x} has no data") - return [] - if groups & (groups - 1) or p + groups * (16 + 16 * slot) > len(s.d): - raise DecodeError(f"table at 0x{field:x} has {groups} groups") - full = [] - for g in range(groups): - base = p + g * (16 + 16 * slot) - for i, b in enumerate(s.d[base:base + 16]): - if b < 0x80: - full.append(base + 16 + slot * i) - elif b != 0x80: - raise DecodeError(f"table at 0x{field:x}: control byte 0x{b:02x}") - if len(full) != count: - raise DecodeError(f"table at 0x{field:x}: {len(full)} full slots for {count} entries") - return full - - -def fmix64(k): - """MurmurHash3's 64-bit finaliser.""" - k = (k ^ k >> 33) * 0xFF51AFD7ED558CCD & 0xFFFFFFFFFFFFFFFF - k = (k ^ k >> 33) * 0xC4CEB9FE1A85EC53 & 0xFFFFFFFFFFFFFFFF - return k ^ k >> 33 - - -def clip_slot_hash(s, o): - """The clip table's hash of a slot: `fmix64` of its first two u32 as one u64 (clip hash low, second word high).""" - return fmix64(s.u32(o) | s.u32(o + 4) << 32) - - -def table_placed_by_key(s, field, slot, key=None): - """True when every full slot of the `hash_table` at `field` sits where its hash h puts it: control byte - h & 0x7F, in group (h >> 7) & (groups - 1) or, when that group is full, in a later one with every group - between full (linear probing, wrapping). h is `key(s, slot offset)`, by default the slot's first u32.""" - groups, p = s.u32(field), s.ptr(field + 8) - size = 16 + 16 * slot - full = lambda g: all(b < 0x80 for b in s.d[p + g * size:p + g * size + 16]) # noqa: E731 - for o in hash_table(s, field, slot): - g, i = divmod(o - p, size) - h = key(s, o) if key else s.u32(o) - home = (h >> 7) & (groups - 1) - if s.d[p + g * size + (i - 16) // slot] != h & 0x7F or not all( - full((home + d) % groups) for d in range((g - home) % groups)): - return False - return True - - -def parse_matcher(s, at): - """The measured part of a `.motionmatcher` after its name (docs/animation.md, "`.motion` and `.motionmatcher` - clips"). Arrays keep their u32 count just before the pointer. -> dict, values only for local inspection""" - rec, n = matcher_array(s, at + 0x58) - records = [(s.f32(rec + 24 * i), s.f32(rec + 24 * i + 4), s.f32(rec + 24 * i + 8), s.u32(rec + 24 * i + 12)) - for i in range(n)] - off, no = matcher_array(s, at + 0x68) - a78, ng = matcher_array(s, at + 0x78) - ab8, nf = matcher_array(s, at + 0xB8) - refs_at, nr = matcher_array(s, at + 0x98) - refs = [] - for i in range(nr): - if s.u64(refs_at + 16 * i) != 0: - raise DecodeError("motionmatcher clip reference does not start with 8 zero bytes") - refs.append((s.u32(refs_at + 16 * i + 8), s.u32(refs_at + 16 * i + 12))) - return { - "records": records, # {f32; f32; f32; u32 clip; u64 0} - "offsets": [s.u32(off + 4 * i) for i in range(no)], # +0x68: u32, one more than the records - "refs": refs, # +0x98: per clip {u64 0; clip; dictionary} - "clips": [(s.u32(o), s.u32(o + 4), s.u32(o + 8)) for o in hash_table(s, at + 0xA0, 16)], # (clip, ?, index) - "keys": [(s.u32(o), s.u32(o + 4)) for o in hash_table(s, at + 0x170, 8)], # (hash, index) - "self": (s.u32(at + 0x188), s.u32(at + 0x18C)), # own clip hash, joaat32(dictionary) - "u16_78": [s.u16(a78 + 2 * i) for i in range(ng)], # +0x78: first record of each clip, then n - "u8_b8": list(struct.unpack_from(f"<{nf}B", s.d, ab8)) if nf else [], # +0xB8: 0 or 1, one per clip - "items_48": matcher_values(s, at + 0x48, "10I"), # 40-byte items - "u32_118": matcher_values(s, at + 0x118, "I"), # the pose sample count - "u16_128": matcher_values(s, at + 0x128, "H"), - **matcher_features(s, at), # first: it refuses a null +0x20 - "tables_placed_by_key": (table_placed_by_key(s, at + 0xA0, 16, clip_slot_hash), - table_placed_by_key(s, at + 0x170, 8), - table_placed_by_key(s, s.ptr(at + 0x20) + 0x48, 8)), # clips, keys, feature names - } - - -def matcher_features(s, at): - """The `.motionmatcher`'s `+0x20` object: the features a pose is compared on. `+0x40` is an array of pointers to - 0x30-byte features {u32 column at +0x08; u16 width at +0x0C; u16 at +0x0E; u32 name hash at +0x18; u32 kind - bits at +0x1C}, and `+0x48` a hash table of (name hash, feature index) with 8-byte slots, hashed differently - from `+0x18`. With `+0x0E` = 1 the name hash is joaat32 of a skeleton bone's name and the width is 3 columns - for kind bit 0, 3 for bit 1 and 6 for bit 3. `+0x28` is the skeleton (`matcher_skeleton`); `+0x98` holds one - u32 per sample, a bit mask over the matcher's key table indices; `+0xB8` one f32 weight per pose column, in - chunks of 8 (count at `+0xB4`), zero after the last column.""" - obj = s.ptr(at + 0x20) - if obj is None: - raise DecodeError("motionmatcher without a feature object") - arr, n = matcher_array(s, obj + 0x40) - features = [] - for i in range(n): - f = s.ptr(arr + 8 * i) - if f is None: - raise DecodeError("motionmatcher feature pointer is null") - features.append((s.u32(f + 0x08), s.u16(f + 0x0C), s.u32(f + 0x18))) - kinds = [(s.u16(s.ptr(arr + 8 * i) + 0x0E), s.u32(s.ptr(arr + 8 * i) + 0x1C)) for i in range(n)] - names = [(s.u32(o), s.u32(o + 4)) for o in hash_table(s, obj + 0x48, 8)] - skel = s.ptr(obj + 0x28) - if skel is None: - raise DecodeError("motionmatcher feature object without its skeleton") - second = s.ptr(obj + 0x30) is not None - columns = features[-1][0] + features[-1][1] if features else 0 - poses = matcher_poses(s, obj, columns, second) - tags, nt = matcher_array(s, obj + 0x98) - if nt and tags + 4 * nt > len(s.d): - raise DecodeError("motionmatcher per-sample words run past the pages") - sample_u32 = list(struct.unpack_from(f"<{nt}I", s.d, tags)) if nt else [] - wp, nw = matcher_array(s, obj + 0xB8) - if nw and wp + 32 * nw > len(s.d): - raise DecodeError("motionmatcher column weights run past the pages") - weights = list(struct.unpack_from(f"<{8 * nw}f", s.d, wp)) if nw else [] - return {"features": features, "feature_names": names, # (column, width, name hash); (hash, index) - "feature_kinds": kinds, # (u16 +0x0E, u32 +0x1C) per feature - "feature_second": second, # +0x30 object present - "feature_b": matcher_object_b(s, s.ptr(obj + 0x30)) if second else None, - "column_weights": weights, # +0xB8: chunks of 8 f32, one per column - "c0": struct.unpack_from(" dict""" - if at + 0x70 > len(s.d): - raise DecodeError("motionmatcher +0x30 object runs past the pages") - form = s.u32(at + 8) - if form == 2: - return {"form": 2, "bones": [s.u32(at + 0x10), s.u32(at + 0x14)], - "weights": list(struct.unpack_from("<2f", s.d, at + 0x18)), - "feature": (s.u16(at + 0x3E), s.u32(at + 0x48)), "kind": s.u32(at + 0x4C), - "width": s.u32(at + 0x68), "flag": s.u16(at + 0x6C)} - if form != 1: - return {"form": form} - out = {"form": 1, "rotation": struct.unpack_from("<4f", s.d, at + 0x10), "flag": s.u32(at + 0x60)} - for name, field, fmt in (("bones", at + 0x40, "I"), ("weights", at + 0x50, "f")): - n, p = s.u32(field), s.ptr(field + 8) - if n and (p is None or p + 4 * n > len(s.d)): - raise DecodeError("motionmatcher +0x30 object array runs past the pages") - out[name] = list(struct.unpack_from(f"<{n}{fmt}", s.d, p)) if n else [] - return out - - -def matcher_skeleton(s, at): - """The feature object's `+0x28`: the skeleton the features are measured on. `+0x6C` u16 bone count; `+0x28` the - 80-byte bones {f32 rotation quaternion[4]; f32 translation[3]; f32 ?; f32 1.0[4]; char *name at +0x30; s16 - parent at +0x46; u16 index at +0x48 and +0x4C; u16 bone id at +0x4A}; `+0x38` each bone's 4x4 local matrix and - `+0x30` its inverse bind matrix (row-vector convention, translation in row 3); `+0x40` the parents as s16; and a - tag table at `+0x18` (u32 slots, u32 entries, pointer) of 8-byte {u32 tag; u32 bone} slots, empty tag 0xFFFFFFFF. - `+0x48` is a tree of the bone names (`skeleton_name_tree`). - -> {"bones": [(name, parent, id, rotation, translation)], "tags", "local", "inverse_bind", "name_tree"}""" - n, bones = s.u16(at + 0x6C), s.ptr(at + 0x28) - mats = [s.ptr(at + 0x38), s.ptr(at + 0x30), s.ptr(at + 0x40)] - if n and (bones is None or None in mats): - raise DecodeError("motionmatcher skeleton without its arrays") - if n and (bones + 80 * n > len(s.d) or max(mats[0], mats[1]) + 64 * n > len(s.d) or mats[2] + 2 * n > len(s.d)): - raise DecodeError("motionmatcher skeleton runs past the pages") - out = [] - for i in range(n): - b = bones + 80 * i - name_at = s.ptr(b + 0x30) - end = s.d.find(b"\0", name_at, name_at + 256) if name_at is not None else -1 - if end < 0: - raise DecodeError("motionmatcher bone without a name") - out.append((s.d[name_at:end].decode("latin-1"), struct.unpack_from(" len(s.d): - raise DecodeError("motionmatcher skeleton tag table runs past the pages") - tags = [struct.unpack_from(" [(name, bone index)] in tree order, or [] for a null pointer""" - if at is None: - return [] - if at + 4 > len(s.d): - raise DecodeError("motionmatcher bone name tree runs past the pages") - n, size = s.u16(at), s.u16(at + 2) - if at + size + 2 * n > len(s.d): - raise DecodeError("motionmatcher bone name tree runs past the pages") - out, stack, steps = [], [(4, "")] if size > 4 else [], 0 - while stack: - node, prefix = stack.pop() - steps += 1 - end = s.d.find(b"\0", at + node + 6, at + size) if 4 <= node and node + 6 < size else -1 - if end < 0 or steps > size: - raise DecodeError("motionmatcher bone name tree node outside its block") - sibling, child, value = struct.unpack_from(" {"poses": {...}, "pose_transforms": [...]}""" - chunks, data = s.u32(obj + 0xEC), s.ptr(obj + 0xF0) - if data is None: - raise DecodeError("motionmatcher without a pose matrix") - if rows_layout: - samples, cols, per_row = s.u32(obj + 0xF8), s.u32(obj + 0xFC), s.u32(obj + 0x100) - stride, layout = 16 * per_row, "rows" - if not samples or cols != columns or per_row != -(-cols // 16) or chunks != samples * per_row: - raise DecodeError("motionmatcher pose matrix size does not fit its rows") - else: - samples, cols = s.u32(obj + 0x128), s.u32(obj + 0xFC) - stride, layout = cols + (cols & 1), "blocks of 8" - if not samples or cols != columns or 16 * chunks != -(-samples // 8) * 8 * stride: - raise DecodeError("motionmatcher pose matrix size does not fit its blocks") - if data + 32 * chunks > len(s.d): - raise DecodeError("motionmatcher pose matrix runs past the pages") - h = struct.unpack_from(f"<{16 * chunks}e", s.d, data) - if layout == "rows": - padding = all(h[r * stride + c] == 0 for r in range(samples) for c in range(cols, stride)) - else: - last, base = samples - 1, (samples - 1) // 8 * stride * 8 - padding = all(h[base + c * 8 + lane] == h[base + c * 8 + last % 8] - for c in range(cols) for lane in range(last % 8 + 1, 8)) and all( - h[b * stride * 8 + c * 8 + lane] == 0 for b in range(-(-samples // 8)) for c in range(cols, stride) - for lane in range(8)) - transforms = [] - if rows_layout: - tr, nt = matcher_array(s, obj + 0xA8) - if nt and tr + 48 * nt > len(s.d): - raise DecodeError("motionmatcher pose transforms run past the pages") - transforms = [struct.unpack_from("<12f", s.d, tr + 48 * i) for i in range(nt)] - poses = {"layout": layout, "samples": samples, "columns": cols, "stride": stride, "at": data, - "finite": all(map(math.isfinite, h)), "padding": padding} - return {"poses": poses, "pose_transforms": transforms} - - -def matcher_pose(s, poses, sample): - """One row of the pose matrix (see `matcher_poses`): the f16 feature values of `sample`, as floats.""" - if not 0 <= sample < poses["samples"]: - raise IndexError(sample) - cols, stride, at = poses["columns"], poses["stride"], poses["at"] - if poses["layout"] == "rows": - return list(struct.unpack_from(f"<{cols}e", s.d, at + 2 * sample * stride)) - base = at + 2 * (sample // 8) * stride * 8 - return [struct.unpack_from("> 24 - h &= ~top & 0xFFFFFFFF - return h % 0xFE8F + 0x170 - - -def quaternion_rows(x, y, z, w): - """The rotation of a unit quaternion as a 3x3 matrix for row vectors (v' = v M).""" - return [[1 - 2 * (y * y + z * z), 2 * (x * y + z * w), 2 * (x * z - y * w)], - [2 * (x * y - z * w), 1 - 2 * (x * x + z * z), 2 * (y * z + x * w)], - [2 * (x * z + y * w), 2 * (y * z - x * w), 1 - 2 * (x * x + y * y)]] - - -def skeleton_checks(skel): - """-> (local matrices are the bones' rotation and translation, inverse binds undo the parent chain), each - to 2e-3, for the row-vector convention. A parent that isn't an earlier bone makes the chain check False.""" - local_ok, inverse_ok, world = True, True, [] - for i, (_name, parent, _id, q, t) in enumerate(skel["bones"]): - m = skel["local"][i] - r = quaternion_rows(*q) - local_ok &= all(abs(m[a][b] - r[a][b]) < 2e-3 for a in range(3) for b in range(3)) and all( - abs(m[3][a] - t[a]) < 2e-3 for a in range(3)) - lm = [list(m[a][:3]) + [0.0] for a in range(3)] + [list(t) + [1.0]] - if parent >= i: - inverse_ok, g = False, lm - else: - g = lm if parent < 0 else [[sum(lm[a][k] * world[parent][k][b] for k in range(4)) for b in range(4)] - for a in range(4)] - world.append(g) - ib = skel["inverse_bind"][i] - inv = [list(row[:3]) + [0.0] for row in ib[:3]] + [list(ib[3][:3]) + [1.0]] - inverse_ok &= all(abs(sum(g[a][k] * inv[k][b] for k in range(4)) - (a == b)) < 2e-3 - for a in range(4) for b in range(4)) - return local_ok, inverse_ok - - -def count_matcher(c, dictionary_hash, stats): - """Counts for a `.motionmatcher`'s decoded fields (no values).""" - m = c.get("matcher") - if m is None: - stats["matcher_unreadable"] += 1 - return - n = len(m["records"]) - stats["matcher_records"] += n - stats["matcher_record_index_is_position"] += [r[3] for r in m["records"]] == list(range(n)) - stats["matcher_record_third_is_minus_one"] += all(r[2] == -1.0 for r in m["records"]) - o = m["offsets"] - stats["matcher_offsets_one_more_than_records"] += len(o) == n + 1 - stats["matcher_offsets_from_0_nondecreasing"] += bool(o) and o[0] == 0 and all(a <= b for a, b in zip(o, o[1:])) - stats["matcher_clip_table_entries"] += len(m["clips"]) - stats["matcher_clip_table_indices_0_to_n"] += sorted(i for _c, _k, i in m["clips"]) == list(range(len(m["clips"]))) - stats["matcher_clip_table_one_per_record"] += sorted(i for _c, _k, i in m["clips"]) == list(range(n)) - nc = len(m["clips"]) - stats["matcher_with_refs"] += bool(m["refs"]) - stats["matcher_refs"] += len(m["refs"]) - if m["refs"]: - stats["matcher_refs_one_per_clip"] += len(m["refs"]) == nc - stats["matcher_refs_name_the_table_clip"] += all( - i < len(m["refs"]) and m["refs"][i][0] == ch for ch, _k, i in m["clips"]) - stats["matcher_key_table_entries"] += len(m["keys"]) - stats["matcher_key_table_indices_0_to_n"] += sorted(i for _h, i in m["keys"]) == list(range(len(m["keys"]))) - stats["matcher_self_is_own_key"] += m["self"] == (c["hash"], dictionary_hash) - g = m["u16_78"] - stats["matcher_u16_78_from_0_to_records"] += bool(g) and g[0] == 0 and g[-1] == n and all( - a <= b for a, b in zip(g, g[1:])) - stats["matcher_u16_78_one_more_than_clips"] += len(g) == nc + 1 - stats["matcher_record_clip_in_its_u16_78_range"] += len(g) == nc + 1 and all( - r[3] < nc and g[r[3]] <= i < g[r[3] + 1] for i, r in enumerate(m["records"])) - stats["matcher_u8_b8_one_per_clip"] += len(m["u8_b8"]) == nc - stats["matcher_u8_b8_set"] += sum(m["u8_b8"]) - stats["matcher_u8_b8_0_or_1"] += bool(m["u8_b8"]) and all(f in (0, 1) for f in m["u8_b8"]) - f = m["features"] - stats["matcher_features"] += len(f) - stats["matcher_feature_columns"] += f[-1][0] + f[-1][1] if f else 0 - stats["matcher_feature_columns_chain_from_0"] += bool(f) and f[0][0] == 0 and all( - a[0] + a[1] == b[0] for a, b in zip(f, f[1:])) - stats["matcher_feature_widths_multiple_of_3"] += bool(f) and all(w % 3 == 0 for _c, w, _h in f) - stats["matcher_feature_names_distinct"] += bool(f) and len({h for _c, _w, h in f}) == len(f) - stats["matcher_feature_name_table_indices_0_to_f"] += bool(f) and sorted( - i for _h, i in m["feature_names"]) == list(range(len(f))) - stats["matcher_feature_object_second_pointer"] += m["feature_second"] - stats["matcher_item_48_one_zero_item_with_u32_1_at_0x20"] += len(m["items_48"]) == 1 and m["items_48"][0] == ( - 0,) * 8 + (1, 0) - stats["matcher_u32_118_is_the_sample_count"] += m["u32_118"] == [m["poses"]["samples"]] - stats["matcher_u16_128_is_one_0"] += m["u16_128"] == [0] - cols, w = m["poses"]["columns"], m["column_weights"] - stats["matcher_column_weights_chunks_of_8"] += len(w) == 8 * -(-cols // 8) - stats["matcher_column_weights_positive_sum_1_then_0"] += len(w) >= cols and all(x > 0 for x in w[:cols]) and abs( - sum(w[:cols]) - 1) < 1e-4 and not any(w[cols:]) - stats["matcher_column_weights_same_within_each_vec3"] += len(w) >= cols and all( - abs(w[i] - w[i + 1]) <= 1e-6 * w[i] and abs(w[i] - w[i + 2]) <= 1e-6 * w[i] for i in range(0, cols - 2, 3)) - stats["matcher_c8_1_with_rows_3_with_blocks"] += m["c0"][1:] == (1.0, 1 if m["poses"]["layout"] == "rows" else 3) - names = {anim_index.joaat32(x[0]) for x in m["skeleton"]["bones"]} - b = m["feature_b"] - if b is not None: - stats[f"matcher_object_b_form_{b['form']}"] += 1 - if b["form"] == 2: - k = b["kind"] - stats["matcher_object_b_form_2_width_from_kind_bits"] += b["width"] == 3 * (k & 1) + 3 * ( - k >> 1 & 1) + 6 * (k >> 3 & 1) - stats["matcher_object_b_form_2_kind_is_a_feature_kind"] += k in {kk for _e, kk in m["feature_kinds"]} - stats["matcher_object_b_form_2_copies_the_first_feature"] += bool(f) and b["feature"] == ( - m["feature_kinds"][0][0], f[0][2]) and k == m["feature_kinds"][0][1] - stats["matcher_object_b_form_2_two_distinct_bones"] += len(set(b["bones"])) == 2 and set( - b["bones"]) <= names - if b["form"] == 1: - q = b["rotation"] - stats["matcher_object_b_form_1_rotation_unit"] += abs(sum(x * x for x in q) - 1) < 1e-4 - stats["matcher_object_b_form_1_bones_one_per_weight"] += len(b["bones"]) == len(b["weights"]) - stats["matcher_object_b_form_1_bones_name_skeleton_bones"] += bool(b["bones"]) and set( - b["bones"]) <= names - if b["form"] in (1, 2): - wb = b["weights"] - stats["matcher_object_b_weights_positive_sum_1"] += bool(wb) and all(x > 0 for x in wb) and abs( - sum(wb) - 1) < 1e-4 - stats[f"matcher_object_b_form_{b['form']}_flag_{b['flag']}"] += 1 - for name, placed in zip(("clip", "key", "feature_name"), m["tables_placed_by_key"]): - stats[f"matcher_{name}_table_placed_by_key"] += placed - sk = m["skeleton"] - bones = sk["bones"] - stats["matcher_skeleton_bones"] += len(bones) - parents = sk["parents"] - stats["matcher_skeleton_one_root_parents_first"] += bool(bones) and parents == [b[1] for b in bones] and sum( - p < 0 for p in parents) == 1 and all(0 <= p < i for i, p in enumerate(parents) if p >= 0) - stats["matcher_skeleton_tags_are_name_hash_and_id"] += bool(bones) and sorted(sk["tags"]) == sorted( - [(anim_index.joaat32(b[0]), i) for i, b in enumerate(bones)] + [(b[2], i) for i, b in enumerate(bones)]) - stats["matcher_skeleton_bone_ids_from_names_root_0"] += bool(bones) and all( - b[2] == (0 if b[1] < 0 else bone_id(b[0])) for b in bones) - stats["matcher_skeleton_name_tree_maps_each_name_to_its_bone"] += bool(bones) and sorted( - sk["name_tree"], key=lambda x: x[1]) == [(b[0], i) for i, b in enumerate(bones)] - local_ok, inverse_ok = skeleton_checks(sk) - stats["matcher_skeleton_local_is_bone_transform"] += bool(bones) and local_ok - stats["matcher_skeleton_inverse_bind_undoes_chain"] += bool(bones) and inverse_ok - simple = [(fw, k, h) for (_c, fw, h), (e, k) in zip(f, m["feature_kinds"]) if e == 1] - stats["matcher_features_with_0e_1"] += len(simple) - stats["matcher_features_0e_1_name_a_bone"] += sum(h in names for _w, _k, h in simple) - stats["matcher_features_0e_1_width_from_kind_bits"] += sum( - fw == 3 * (k & 1) + 3 * (k >> 1 & 1) + 6 * (k >> 3 & 1) for fw, k, _h in simple) - for (_c, fw, h), (e, k) in zip(f, m["feature_kinds"]): - if e == 5: # not a bone: one of +0x18 and +0x1C is 0 - stats["matcher_features_0e_5"] += 1 - stats["matcher_features_0e_5_name_a_bone"] += h in names - stats["matcher_features_0e_5_with_1c_0" if k == 0 else "matcher_features_0e_5_with_18_0" if h == 0 else - "matcher_features_0e_5_with_neither_0"] += 1 - u = m["sample_u32"] - if u: - stats["matcher_sample_u32_one_per_sample"] += len(u) == m["poses"]["samples"] - stats["matcher_sample_u32_same_within_a_record"] += all( - len(set(u[a:b])) <= 1 for a, b in zip(m["offsets"], m["offsets"][1:])) - used = 0 - for x in u: - used |= x - stats["matcher_sample_u32_bits_are_key_indices"] += used == (1 << len(m["keys"])) - 1 - p = m["poses"] - stats["matcher_pose_layout_rows" if p["layout"] == "rows" else "matcher_pose_layout_blocks_of_8"] += 1 - stats["matcher_pose_samples"] += p["samples"] - stats["matcher_pose_samples_are_offsets_end"] += bool(m["offsets"]) and p["samples"] == m["offsets"][-1] - stats["matcher_pose_values_finite"] += p["finite"] - stats["matcher_pose_padding_as_expected"] += p["padding"] - t = m["pose_transforms"] - if t: - stats["matcher_pose_transforms_one_per_sample"] += len(t) == p["samples"] - stats["matcher_pose_transforms_unit_quaternion_scale_1"] += all( - abs(sum(x * x for x in q[:4]) - 1) < 1e-3 and q[7] == 0 and q[8:11] == (1.0, 1.0, 1.0) and q[11] == 0 - for q in t) - - -def motion_samples(s, at): - """`.motion` +0x90: one {ptr, u16 count} list per sample of the parameter node, each item a 12-byte - {u32 child index, f32, f32}. A one-node `.motion` has as many lists as its node has samples, so type-3 sample - index k plays child list[k][0]. -> [[(child, f32, f32)]] ([] when +0x90 is null)""" - p, n = s.array(at + 0x90) - out = [] - for i in range(n if p is not None else 0): - items, count = s.array(p + 16 * i) - out.append([(s.u32(items + 12 * j), s.f32(items + 12 * j + 4), s.f32(items + 12 * j + 8)) - for j in range(count)] if items is not None else []) - return out - - -def parse_clip(s, at): - kind = s.u32(at + 0x20) - if kind >= 16: # +0x20 is a pointer: a parametric clip that refers to packs outside the dictionary - if at + 0x40 > len(s.d): - raise DecodeError(f"clip at 0x{at:x} is outside the pages") - name_at, tag = s.u64(at + 0x30), s.d[at + 0x3F] - # `.motion`: name at +0x30, a pointer or inline (+0x3F 0x80 | length). For a `.motionmatcher` +0x3F is - # byte 7 of its name at +0x38: a pointer's zero high byte or an inline character. - if SYSTEM <= name_at < SYSTEM + len(s.d) or tag & 0x80 and tag & 0x7F <= 15: - motion = {"kind": "motion", "name": s.string(at + 0x30), "animations": [], "children": None, - "parameters": None} - try: - # +0x58 u32 parameter count; +0x60 array of {u64 0; u32 clip hash; u32 dictionary hash} - children, n = s.array(at + 0x60) - if children is None: - motion["children"], motion["parameters"] = [], s.u32(at + 0x58) - elif children + 16 * n <= len(s.d) and all(s.u64(children + 16 * i) == 0 for i in range(n)): - motion["children"] = [(s.u32(children + 16 * i + 8), s.u32(children + 16 * i + 12)) - for i in range(n)] - motion["parameters"] = s.u32(at + 0x58) - except (DecodeError, struct.error): - pass - try: # read apart: a malformed node must not mark a readable time table unreadable - motion["times"] = motion_times(s, at) - except (DecodeError, struct.error): - motion["times"] = None - try: - motion["node"] = parameter_node(s, at, motion["parameters"]) - except (DecodeError, struct.error): - motion["node"] = None - try: - motion["samples"] = motion_samples(s, at) - except (DecodeError, struct.error): - motion["samples"] = None - return motion - # `.motionmatcher`: a 16-byte id at +0x28, name at +0x38 - matcher = {"kind": "motionmatcher", "name": s.string(at + 0x38), "animations": [], "matcher": None} - try: - matcher["matcher"] = parse_matcher(s, at) - except (DecodeError, struct.error): - pass - return matcher - clip = {"kind": "clip", "name": s.string(at + 0x28), "duration": s.f32(at + 0x78), "animations": []} - lst = s.ptr(at + 0x68) - if lst is not None: - entries, n = s.array(lst) - for i in range(n): - e = entries + 0x38 * i - clip["animations"].append({"animation": s.ptr(e), "hash": s.u32(e + 8), "start": s.f32(e + 0x28), - "end": s.f32(e + 0x2C), "rate": s.f32(e + 0x30)}) - return clip - - -def parse_dictionary(s): - """Root object at page offset 0: +0x38 name, +0x48 clip map, +0x68 joaat32(name), +0x70 pack references.""" - refs_word = s.u64(0x70) - if refs_word and not SYSTEM <= refs_word < SYSTEM + len(s.d): - # Same root layout, other content: "RIG" + version at +0x70 is a rig dictionary. - raise NotClipDictionary("rig" if s.d[0x70:0x73] == b"RIG" else "other") - d = {"name": s.string(0x38), "hash": s.u32(0x68), "clips": [], "packs": [], "external_packs": 0, - "external_hashes": []} - for key, value in s.atmap(0x48): - if value is not None: - clip = parse_clip(s, value) - clip["hash"] = key & 0xFFFFFFFF # the key is joaat32(dictionary) << 32 | clip hash - d["clips"].append(clip) - refs, n = s.array(0x70) - for i in range(n): - pack = s.ptr(refs + 16 * i) - if pack is None: - d["external_packs"] += 1 # only a hash: another clip dictionary's joaat32(name) - d["external_hashes"].append(s.u32(refs + 16 * i + 8)) - continue - anims = [parse_animation(s, v) for _k, v in s.atmap(pack + 0x48) if v is not None] - d["packs"].append({"name": s.string(pack + 0x38), "hash": s.u32(pack + 0x68), "animations": anims}) - return d - - -# ---------------------------------------------------------------- channels - - -def zigzag(u): - return (u >> 1) if not u & 1 else -((u + 1) >> 1) - - -def _bits(blob, pos, k): - if not k: - return 0 - o = pos >> 3 - v = int.from_bytes(blob[o:o + ((pos & 7) + k + 7 >> 3)], "little") - return (v >> (pos & 7)) & ((1 << k) - 1) - - -def decode_delta2(data, at, nf, stats=None): - """Channel type 10, second-order delta coded. Returns (values, byte length). - - u32 word count | u8 c1, c2, c3, 0 | f32 quantum | f32 offset | LSB-first bits: - nc = ceil(nf / 64) chunk payload positions (c1 bits each), nc chunk start values (c2 bits), - ceil((nf - 1) / 8) unary widths, one per 8 deltas (k zeros then a one), and at the end 8 lanes x c3 u32 words, - interleaved (word w * 8 + j is lane j). Lane j holds delta j of every 8-delta group, k bits each. - In a chunk: x = start, v = 0; for each frame v += zigzag(raw); x += v. Value = x * quantum + offset. - """ - words, packed, quantum, offset = struct.unpack_from("> 8) & 255, (packed >> 16) & 255 - size = 4 * words - if size < 16 or at + size > len(data): - raise DecodeError("type-10 channel runs past the sequence") - blob = bytes(data[at + 16:at + size]) - nbits = 8 * len(blob) - nc, ng = (nf + 63) // 64, (nf + 6) // 8 # nf - 1 deltas, 8 per width code - starts = [_bits(blob, nc * c1 + i * c2, c2) for i in range(nc)] - pos = nc * (c1 + c2) - widths = [] - for _ in range(ng): # unary: k zero bits, then a one - o, k = pos >> 3, 0 - byte = blob[o] >> (pos & 7) if o < len(blob) else 0 - if byte: - k = (byte & -byte).bit_length() - 1 - else: - k = 8 - (pos & 7) - o += 1 - while o < len(blob) and not blob[o]: - k += 8 - o += 1 - if o >= len(blob): - raise DecodeError("type-10 width code runs past the channel") - k += (blob[o] & -blob[o]).bit_length() - 1 - pos += k + 1 - widths.append(k) - lane_at = nbits - 256 * c3 - if lane_at < pos: - raise DecodeError("type-10 lanes overlap the width codes") - if sum(widths) > 32 * c3: - raise DecodeError("type-10 widths need more lane bits than the channel has") - lw = struct.unpack_from(f"<{8 * c3}I", blob, lane_at // 8) - lanes = [b"".join(struct.pack("= nf: - break - v += zigzag(raw[f0 + j]) - x += v - if j == 63: - if stats is not None: - stats["delta2_boundaries"] += 1 - stats["delta2_boundaries_closed"] += x == starts[ci + 1] - break - values[f] = x * quantum + offset - return values, size - - -def sequence_header(data, at): - h = struct.unpack_from("<5I5H2B", data, at) - return {"length": h[1], "frame_offset": h[3], "frames": h[6], "frame_bytes": h[7], "quantize_bits": h[9]} - - -def decode_sequence(s, at, stats=None): - """One sequence: 0x20-byte header, then channel definitions, frame bits, u16 counts[11] and the - (track << 2 | component) lists. Returns (frames, channels) with channels = [type, track, comp, values].""" - if at is None: - raise DecodeError("sequence pointer is null") - if at < 0 or at + 0x20 > len(s.d): - raise DecodeError(f"sequence at 0x{at:x} is outside the pages") - h = sequence_header(s.d, at) - if at + 0x20 + h["length"] > len(s.d): - raise DecodeError(f"sequence at 0x{at:x} runs past the pages") - data = memoryview(s.d)[at + 0x20:at + 0x20 + h["length"]] - nf, fo, fl = h["frames"], h["frame_offset"], h["frame_bytes"] - lists_at = fo + fl * nf - if lists_at + 22 > len(data): - raise DecodeError("sequence counts run past its data") - counts = struct.unpack_from("<11H", data, lists_at) - lists, p = [], lists_at + 22 - for c in counts: - lists.append([(x >> 2, x & 3) for x in struct.unpack_from(f"<{c}H", data, p)]) - p += 2 * ((c + 3) // 4 * 4) - p, channels, frame_fields = 0, [], [] - for t, c in enumerate(counts): - if c and t in (6, 9): - raise DecodeError(f"channel type {t} ({CHANNEL_NAMES[t]}) is not decoded") - for i in range(c): - track, comp = lists[t][i] - value = None - if t == 0 or t == 1: - value = struct.unpack_from("<3f", data, p) - p += 12 - elif t == 2: - value = struct.unpack_from(" fo: - raise DecodeError("type-5 value table runs past channel definitions") - table_bytes = bytes(data[p + 20:p + 20 + 4 * words]) - p += 20 + 4 * words - n = (32 * words) // vbits if vbits else 1 - table = [(_bits(table_bytes, i * vbits, vbits) if vbits else 0) * quantum + offset for i in range(n)] - frame_fields.append((len(channels), fbits, "table", table)) - elif t == 10: - value, size = decode_delta2(data[:fo], p, nf, stats) - p += size - channels.append([t, track, comp, value]) - if p != fo: - raise DecodeError(f"channel definitions end at 0x{p:x}, frame data starts at 0x{fo:x}") - if stats is not None: - stats["quantize_bits_match"] += sum(b for _i, b, q, _o in frame_fields if q not in ("raw", "table")) \ - == h["quantize_bits"] - if frame_fields: - need = sum(b for _i, b, _q, _o in frame_fields) - if need > 8 * fl: - raise DecodeError(f"frame fields need {need} bits, frames have {8 * fl}") - columns = {i: [] for i, *_ in frame_fields} - for f in range(nf): - row = int.from_bytes(data[fo + f * fl:fo + (f + 1) * fl], "little") - for i, bits, quantum, offset in frame_fields: - x = row & ((1 << bits) - 1) - row >>= bits - if quantum == "raw": - columns[i].append(struct.unpack("= len(offset): - raise DecodeError("indirect index past its value table") - columns[i].append(offset[x]) - else: - columns[i].append(x * quantum + offset) - for i, col in columns.items(): - channels[i][3] = col - return nf, channels - - -def assemble_tracks(nf, channels, ntracks, stats=None): - """Channels -> {track: [per-frame tuple]}. Quaternions are (x, y, z, w). - - Type 7 on a track with three stored components (comp 0..2): rebuild the missing component, placed at the - type-7 channel's comp position, as +sqrt(1 - sum of squares); the stored three fill the other positions in - order. Type 8 on a track with all four components stored: use them and normalise (nothing is rebuilt).""" - by = collections.defaultdict(list) - for t, track, comp, v in channels: - if track >= ntracks: - raise DecodeError("channel names a track past the track list") - by[track].append((t, comp, v)) - out = {} - for track, chs in by.items(): - whole = [c for c in chs if c[0] in (0, 1)] - if whole: - t, _comp, v = whole[0] - if t == 0: - x, y, z = v - r = 1.0 - x * x - y * y - z * z - if stats is not None: - stats["quaternion_static"] += 1 - stats["quaternion_static_xyz_over_unit"] += r < -1e-3 - v = (x, y, z, math.sqrt(max(0.0, r))) - out[track] = [tuple(v)] * nf - continue - comps, rebuild, normalise = {}, None, False - for t, comp, v in chs: - if t == 7: - rebuild = comp - elif t == 8: - normalise = True - else: - comps[comp] = v if isinstance(v, list) else [v] * nf - if rebuild is not None and sorted(comps) != [0, 1, 2]: - raise DecodeError("type-7 channel on a track without exactly three stored components") - if normalise and sorted(comps) != [0, 1, 2, 3]: - raise DecodeError("type-8 channel on a track without four stored components") - n = 3 if rebuild is not None else (max(comps) + 1 if comps else 0) - frames, worst = [], 0.0 - for f in range(nf): - vec = [comps[c][f] if c in comps else 0.0 for c in range(n)] - if rebuild is not None: - r = 1.0 - sum(a * a for a in vec) - worst = max(worst, -r) - vec.insert(rebuild, math.sqrt(max(0.0, r))) - elif n == 4: - worst = max(worst, abs(math.sqrt(sum(a * a for a in vec)) - 1.0)) - if rebuild is not None or normalise: - norm = math.sqrt(sum(a * a for a in vec)) or 1.0 - vec = [a / norm for a in vec] # quantisation leaves |q| slightly off 1 - frames.append(tuple(vec)) - if stats is not None and (rebuild is not None or n == 4): - kind = "rebuilt" if rebuild is not None else ("type8_four_stored" if normalise else "four_stored") - stats[f"quaternion_{kind}"] += 1 - stats[f"quaternion_{kind}_worst_1e6"] = max(stats[f"quaternion_{kind}_worst_1e6"], round(worst * 1e6)) - out[track] = frames - return out - - -def decode_animation(s, anim, stats=None): - """Concatenate the sequences. Consecutive sequences share one frame, so sum(frames) == total + n - 1 and the - first frame of every sequence after the first is dropped (and compared with the frame it repeats).""" - tracks, total, frames_sum = {}, 0, 0 - for si, at in enumerate(anim["sequences"]): - nf, channels = decode_sequence(s, at, stats) - if nf == 0 and len(anim["sequences"]) > 1: - raise DecodeError("multi-sequence animation has an empty sequence") - frames_sum += nf - if stats is not None: - for t, *_ in channels: - stats[f"channel:{t:02d}_{CHANNEL_NAMES[t]}"] += 1 - part = assemble_tracks(nf, channels, len(anim["tracks"]), stats) - for k, frames in part.items(): - if si and stats is not None and k in tracks and frames: - a, b = tracks[k][-1], frames[0] - if anim["tracks"][k][2] == 0 and len(a) == 4 == len(b): - stats["boundary_quaternions"] += 1 - stats["boundary_quaternions_same_rotation"] += abs(sum(x * y for x, y in zip(a, b))) > 0.9999 - else: - stats["boundary_values"] += 1 - stats["boundary_values_within_1e-3"] += ( - len(a) == len(b) and bool(a) and max(abs(x - y) for x, y in zip(a, b)) < 1e-3 - ) - have = tracks.setdefault(k, [frames[0]] * total if frames else []) - have.extend(frames[1:] if si else frames) - total += nf - (1 if si else 0) - for k, have in tracks.items(): - if len(have) < total: - have.extend([have[-1]] * (total - len(have))) - if stats is not None: - stats["frames_sum_matches"] += frames_sum == anim["frames"] + max(0, len(anim["sequences"]) - 1) - return tracks, total - - -# ---------------------------------------------------------------- resources - - -def is_root(head): - """A clip-dictionary root page: 8 zero bytes, a 0x50xxxxxx pointer at +8, zeros from +0x10 to +0x38.""" - return (len(head) >= 0x40 and head[:8] == bytes(8) and head[16:0x38] == bytes(0x28) - and struct.unpack_from("> 28 == 5) - - -def _named_root_hash(page): - """Return the verified page-local name hash shared by dictionary and pack headers.""" - if len(page) < 0x6C or not is_root(page): - return None - s = System(page) - try: - name = s.string(0x38) - except DecodeError: - return None - stored = s.u32(0x68) - return stored if name and anim_index.joaat32(name) == stored else None - - -def _local_packs(data): - """Referenced (system pointer, name hash) pairs, or None until the table is available.""" - if len(data) < 0x7a: - return None - refs, count = struct.unpack_from(" len(data): - return None - return {(ptr, name_hash) for ptr, name_hash in struct.iter_unpack(" segment dict or None.""" - d = zlib.decompressobj() - d.decompress(m[row["offset"]:row["offset"] + row["stored"]]) - end = row["offset"] + row["stored"] - len(d.unused_data) - at = (end + 15) & ~15 - if at >= len(m) or m[end:at] != bytes(at - end): - return None - if anim_index.ZHDR.match(m, at) and m[at:at + 3] != b"KB2": - z, chunk = zlib.decompressobj(), m[at:at + 4096] - try: - page = z.decompress(chunk) - except zlib.error: - page = None - if page and z.eof: - try: - parse_dictionary(System(first + page)) - except (DecodeError, struct.error, IndexError): - pass - else: - return {"offset": at, "stored": len(chunk) - len(z.unused_data), "raw": False, - "kind": "small zlib page"} - if at + 16 > len(m): - return None - page = bytes(m[at:at + 16]) - try: - parse_dictionary(System(first + page)) - except (DecodeError, struct.error, IndexError): - return None - return {"offset": at, "stored": 16, "raw": True, "kind": "raw 16-byte page"} - - -def segment(rows, k): - """(offset, stored, raw) for a stream index or a gap page.""" - if isinstance(k, dict): - return k["offset"], k["stored"], k["raw"] - return rows[k]["offset"], rows[k]["stored"], False - - -# A continuation can start with pack:/ paths or bone names inside the dictionary. -_MAP_BOUNDARIES = anim_index.STOP_SIGNATURES - {"name-table", "skeleton-names"} - - -def group(m, rows, *, first_row_only: bool = False, continuation_rows=None): - """-> ([(root index, [stream indices or gap pages])], unresolved count by reason, gap pages by kind). A - dictionary takes the page map's system page count of back-to-back streams. When the last page is not the next - listed stream, the bytes right after the stream are tried (`_gap_page`); otherwise the root is reported. - With first_row_only, later rows supply continuation pages but cannot start other dictionaries. - A selected-root caller can supply continuation_rows to discover rows on demand.""" - def has_next(k): - if k + 1 < len(rows): - return True - row = next(continuation_rows, None) if continuation_rows is not None else None - if row is None: - return False - rows.append(row) - return True - - out, unresolved, taken, gaps = [], collections.Counter(), set(), collections.Counter() - for i, row in enumerate(rows[:1] if first_row_only else rows): - if i in taken or row["signature"] != "zero-prefix": - continue - data = _inflate(m, row) - if not is_root(data): - continue - pm = struct.unpack_from(" 1: - prefix = data + b"".join(_inflate(m, rows[j]) for j in parts[1:]) - packs = _local_packs(prefix) - return packs is None or (SYSTEM + offset, name_hash) not in packs - - # Only the two count bytes are needed. Locate them by inflated size, - # including when they straddle a listed stream boundary. - count_at = pm + 8 - counts = data[count_at:count_at + 2] - end = len(data) - while len(counts) < 2 and len(parts) < 255 and has_next(k): - following = rows[k + 1] - if not _next_to(rows[k], following) or following["signature"] in _MAP_BOUNDARIES: - break - start, end = end, end + following["size"] - page = None - if following["signature"] == "zero-prefix": - page = _inflate(m, following) - # Short continuation pages can resemble an unnamed root. Within - # the original four-page window, check the root name or local map. - if is_root(page) and (len(parts) >= 4 or any(page[0x38:0x40]) - or struct.unpack_from(" count_at: - if page is None: - page = _inflate(m, following) - counts += page[max(0, count_at - start):count_at + 2 - start] - if len(counts) != 2: - unresolved["page map not in the next stream"] += 1 - continue - pages, graphics = counts - if graphics: - unresolved["graphics pages"] += 1 - continue - while len(parts) < pages and has_next(k) and _next_to(rows[k], rows[k + 1]): - following = rows[k + 1] - if following["signature"] == "zero-prefix" and separate_root(_inflate(m, following), end): - break - end += following["size"] - k += 1 - parts.append(k) - # A listed adjacent root cannot also be an unlisted gap page. - if len(parts) == pages - 1 and (k + 1 == len(rows) or not _next_to(rows[k], rows[k + 1])): - joined = b"".join(_inflate(m, rows[j]) for j in parts) - gap = _gap_page(m, rows[k], joined) - if gap is not None: - parts.append(gap) - if len(parts) != pages: - unresolved["system page not the next stream"] += 1 - continue - if isinstance(parts[-1], dict): - gaps[parts[-1]["kind"]] += 1 - taken.update(p for p in parts if not isinstance(p, dict)) - out.append((i, parts)) - return out, unresolved, gaps - - -def child_times(c): - """A `.motion`'s +0x70 entries lined up with its children (None where they don't line up).""" - times = c.get("times") - return times if times is not None and len(times) == len(c["children"]) else [None] * len(c["children"]) - - -def count_motion_blend(c, stats): - """Counts for a `.motion`'s +0x70 child times and its parameter node (no values).""" - times = c.get("times") - if times is None: - stats["motion_times_unreadable"] += 1 - else: - stats["motion_times_one_per_child"] += len(times) == len(c["children"]) - for duration, blend, points in times: - stats["motion_child_times"] += 1 - if len(points) == 2 and points == [(0.0, 0.0), (duration, blend)] and duration == blend: - stats["motion_child_times_identity"] += 1 - elif (len(points) > 2 and points[0] == (0.0, 0.0) and points[-1] == (duration, blend) and - all(a[0] <= b[0] and a[1] <= b[1] for a, b in zip(points, points[1:]))): - stats["motion_child_times_warped"] += 1 - else: - stats["motion_child_times_other"] += 1 - node = c.get("node") - if node is None: - stats["motion_node_unreadable"] += 1 - return - kind, axis = node - stats[f"motion_node_type:{kind}"] += 1 - if axis is None: - return - count_motion_samples(c, kind, axis, stats) - if kind != 3: - stats[f"motion_node_axes:{kind}:{len(axis['names'])}"] += 1 - if kind != 1: - pairs = axis["pairs"] - stats[f"motion_node_pairs:{kind}:" + ("null" if pairs is None else str(len(pairs)))] += 1 - for h in axis["names"]: - stats[f"motion_node_axis_name:{kind}:" + AXIS_NAMES.get(h, "unresolved")] += 1 - return - values = [v for _i, v in axis["samples"]] - stats["motion_axes"] += 1 - stats["motion_axis_samples"] += len(values) - stats["motion_axis_one_name"] += len(axis["names"]) == 1 - stats["motion_axis_sorted"] += all(a <= b for a, b in zip(values, values[1:])) - stats["motion_axis_range_is_first_last"] += bool(values) and (axis["min"], axis["max"]) == (values[0], values[-1]) - stats["motion_axis_indices_are_0_to_n"] += sorted(i for i, _v in axis["samples"]) == list(range(len(values))) - stats["motion_axis_samples_equal_children"] += len(values) == len(c["children"] or []) - stats[f"motion_axis_sample_count:{len(values)}"] += 1 - for h in axis["names"]: - stats["motion_axis_name:" + AXIS_NAMES.get(h, f"0x{h:08x}")] += 1 - - -def window_matches_duration(start, end, rate, duration): - """True when an animation entry's clip window covers the clip exactly: (end - start) / rate equals the clip's - +0x78 duration, to float32 precision (relative 1e-5, absolute 1e-6). False for a zero or non-finite rate.""" - if not rate or not all(math.isfinite(x) for x in (start, end, rate, duration)): - return False - return math.isclose((end - start) / rate, duration, rel_tol=1e-5, abs_tol=1e-6) - - -def count_clip_windows(clips, stats): - """docs/animation.md: a clip plays each animation over [start, end] at its rate, and (end - start) / rate is the - clip's duration. Count the animation entries of ordinary clips that hold to it, and the ones with rate 0.""" - for c in clips: - if c["kind"] != "clip": - continue - for e in c["animations"]: - stats["clip_windows"] += 1 - stats["clip_windows_rate_zero"] += e["rate"] == 0 - stats["clip_windows_match_duration"] += window_matches_duration(e["start"], e["end"], e["rate"], - c["duration"]) - - -def count_motion_samples(c, kind, axis, stats): - """Counts for the +0x90 sample lists of a one-node `.motion` (+0x58 == 1) against its node (no values).""" - lists = c.get("samples") - if c["parameters"] != 1 or lists is None: - return - children = len(c["children"]) - mapped = [items[0][0] for items in lists if items] - pre = f"motion_samples:{kind}:" - stats[pre + "motions"] += 1 - stats[pre + "lists_equal_node_samples"] += len(lists) == axis["sample_count"] - stats[pre + "lists_more_than_children"] += len(lists) > children - stats[pre + "every_list_one_item"] += all(len(items) == 1 for items in lists) - stats[pre + "children_in_range"] += all(ch < children for items in lists for ch, _a, _b in items) - stats[pre + "every_child_sampled"] += {ch for items in lists for ch, _a, _b in items} == set(range(children)) - stats[pre + "sample_k_is_child_k"] += (len(lists) == children and all(len(items) == 1 for items in lists) and - mapped == list(range(children))) - for items in lists: - for _ch, a, b in items: - stats[pre + "items"] += 1 - stats[pre + "items_first_float_1"] += a == 1.0 - stats[pre + "items_second_float_1"] += b == 1.0 - - -def new_stats(): - return collections.Counter() - - -def merge(total, part): - """Add counters; `*_worst_1e6` entries keep the maximum.""" - for k, v in part.items(): - total[k] = max(total[k], v) if k.endswith("_worst_1e6") else total[k] + v - - -def decode_resource(path, segments, budget=None): - """Worker: inflate and decode one dictionary. -> (row, stats). The row carries no values. - With `budget` (seconds), animations left when it runs out are counted as skipped and the row says so.""" - started = time.monotonic() - stats = new_stats() - with open(path, "rb") as fh: - data = b"" - for off, stored, raw in segments: - fh.seek(off) - data += fh.read(stored) if raw else zlib.decompressobj().decompress(fh.read(stored)) - s = System(data) - row = {"offset": segments[0][0], "streams": len(segments), "system_bytes": len(data)} - try: - d = parse_dictionary(s) - except NotClipDictionary as e: - stats["roots_not_clip_dictionary:" + str(e)] += 1 - row["kind"] = str(e) - return row, stats - except (DecodeError, struct.error) as e: - stats["dictionaries_unparsed"] += 1 - stats["dictionary_error:" + str(e).split(" at 0x")[0].split("pointer 0x")[0][:60]] += 1 - row["error"] = str(e)[:120] - return row, stats - stats["dictionaries"] += 1 - stats["dictionary_hash_matches_name"] += d["name"] is not None and anim_index.joaat32(d["name"]) == d["hash"] - stats["clips"] += len(d["clips"]) - stats["clips_motion"] += sum(c["kind"] == "motion" for c in d["clips"]) - stats["clips_motionmatcher"] += sum(c["kind"] == "motionmatcher" for c in d["clips"]) - for c in d["clips"]: - if c["kind"] == "motionmatcher": - count_matcher(c, d["hash"], stats) - external = set(d["external_hashes"]) - for c in d["clips"]: - if c["kind"] != "motion": - continue - if c["children"] is None: - stats["motion_children_unreadable"] += 1 - continue - stats[f"motion_parameters:{c['parameters']}"] += 1 - stats["motion_children"] += len(c["children"]) - stats["motion_children_in_external_refs"] += sum(dh in external for _ch, dh in c["children"]) - count_motion_blend(c, stats) - stats["clip_animation_refs"] += sum(len(c["animations"]) for c in d["clips"]) - count_clip_windows(d["clips"], stats) - stats["packs_local"] += len(d["packs"]) - stats["packs_external"] += d["external_packs"] - stats["dictionaries_without_local_pack"] += not d["packs"] - ok = failed = skipped = 0 - for pack in d["packs"]: - for anim in pack["animations"]: - stats["animations"] += 1 - if budget is not None and time.monotonic() - started >= budget: # >=: a coarse clock (Windows) reads 0.0 for short spans - skipped += 1 - continue - stats["sequences"] += len(anim["sequences"]) - for bone, ttype, fmt in anim["tracks"]: - stats["track_type:" + TRACK_TYPES.get(ttype, f"0x{ttype:08x}")] += 1 - stats["track_format:" + TRACK_FORMATS.get(fmt, str(fmt))] += 1 - try: - local = new_stats() - decode_animation(s, anim, local) - merge(stats, local) - ok += 1 - except (DecodeError, struct.error, IndexError) as e: - failed += 1 - stats["animation_error:" + str(e).split(" at 0x")[0][:60]] += 1 - stats["animations_decoded"] += ok - stats["animations_failed"] += failed - if skipped: - stats["animations_skipped_over_budget"] += skipped - stats["dictionaries_over_budget"] += 1 - row["over_budget"] = True - # for the archive-wide join in scan(); scan() removes these lists from the rows it returns - row["_clip_hashes"] = [c["hash"] for c in d["clips"] if c["kind"] == "clip"] - row["_clip_durations"] = [c["duration"] for c in d["clips"] if c["kind"] == "clip"] - row["_children"] = [ch for c in d["clips"] if c["kind"] == "motion" and c["children"] for ch in c["children"]] - row["_child_durations"] = [t[0] if t else None for c in d["clips"] if c["kind"] == "motion" and c["children"] - for t in child_times(c)] - row["_external"] = d["external_hashes"] - matchers = [c["matcher"] for c in d["clips"] if c["kind"] == "motionmatcher" and c.get("matcher")] - row["_matcher_clips"] = [ch for m in matchers for ch, _k, _i in m["clips"]] - row["_matcher_refs"] = [r for m in matchers for r in m["refs"]] - row["_matcher_keys"] = [h for m in matchers for h, _i in m["keys"]] - row.update(hash=f"0x{d['hash']:08x}", name=d["name"], clips=len(d["clips"]), packs=len(d["packs"]), - external_packs=d["external_packs"], animations=ok + failed + skipped, decoded=ok, - seconds=round(time.monotonic() - started, 3)) - return row, stats - - -def join_references(rows, stats): - """Resolve hash-only references across the archive: a root `+0x70` item with a null pointer names another - dictionary (its joaat32 name hash), and a `.motion` child is {clip hash, dictionary hash}.""" - clips_by_dict = collections.defaultdict(set) - duration = {} - for r in rows: - if "_clip_hashes" in r: - clips_by_dict[int(r["hash"], 16)].update(r["_clip_hashes"]) - for h, t in zip(r["_clip_hashes"], r.get("_clip_durations", [])): - duration[(int(r["hash"], 16), h)] = t - all_clips = set().union(*clips_by_dict.values()) if clips_by_dict else set() - ext_seen = set() - for r in rows: - for h in r.pop("_external", []): - stats["external_refs_to_a_dictionary_here"] += h in clips_by_dict - if h not in ext_seen: - ext_seen.add(h) - stats["external_hashes_distinct"] += 1 - stats["external_hashes_distinct_found_here"] += h in clips_by_dict - kids = r.pop("_children", []) - for (ch, dh), t in zip(kids, r.pop("_child_durations", [None] * len(kids))): - if dh in clips_by_dict: - stats["motion_children_dictionary_here"] += 1 - stats["motion_children_resolved_to_clip"] += ch in clips_by_dict[dh] - if ch in clips_by_dict[dh] and t is not None: - stats["motion_child_duration_equals_clip"] += duration.get((dh, ch)) == t - for ch in r.pop("_matcher_clips", []): - stats["matcher_table_clips_found_here"] += ch in all_clips - for h in r.pop("_matcher_keys", []): - stats["matcher_key_table_hashes_that_are_clips"] += h in all_clips - for ch, dh in r.pop("_matcher_refs", []): - stats["matcher_refs_resolved_to_clip"] += ch in clips_by_dict.get(dh, ()) - r.pop("_clip_hashes", None) - r.pop("_clip_durations", None) - - -def _decode_star(args): - return decode_resource(*args) - - -def scan(path, start=None, limit=None, jobs=1, progress=None, budget=None): - rows, walk = anim_index.scan_rpf(path, start, limit) - with open(path, "rb") as fh, mmap.mmap(fh.fileno(), 0, access=mmap.ACCESS_READ) as m: - groups, unresolved, gaps = group(m, rows) - work = [(path, [segment(rows, k) for k in parts], budget) for _i, parts in groups] - used = [k for _i, parts in groups for k in parts if not isinstance(k, dict)] - stats, out = new_stats(), [] - if jobs > 1 and len(work) > 1: - import multiprocessing - with multiprocessing.Pool(process_workers(jobs)) as pool: - for n, (row, st) in enumerate(pool.imap_unordered(_decode_star, work, chunksize=4), 1): - out.append(row) - merge(stats, st) - if progress and n % 5000 == 0: - progress(n, len(work)) - else: - for n, w in enumerate(work, 1): - row, st = decode_resource(*w) - out.append(row) - merge(stats, st) - if progress and n % 5000 == 0: - progress(n, len(work)) - out.sort(key=lambda r: r["offset"]) - join_references(out, stats) - summary = { - "streams": walk["files"], - "dictionary_roots": len(groups) + sum(unresolved.values()), - "dictionaries_grouped": len(groups), - "unresolved": dict(unresolved), - "gap_pages": dict(gaps), - "pages": {str(k): v for k, v in sorted(collections.Counter(len(p) for _i, p in groups).items())}, - "dictionary_streams": len(used), - "dictionary_stored_bytes": sum(rows[k]["stored"] for k in used), - "dictionary_inflated_bytes": sum(rows[k]["size"] for k in used), - "dictionary_stream_signatures": dict(collections.Counter( - rows[k]["signature"].split(":")[0] for k in used).most_common()), - "slowest_dictionary_seconds": max([r.get("seconds", 0) for r in out] or [0]), - "counts": dict(sorted(stats.items())), - } - return out, summary - - -def decode_one(path, offset, frames): - rows, _walk = anim_index.scan_rpf(path, offset, 64 << 20) - with open(path, "rb") as fh, mmap.mmap(fh.fileno(), 0, access=mmap.ACCESS_READ) as m: - groups, _unresolved, _gaps = group(m, rows, first_row_only=True) - if not groups or rows[groups[0][0]]["offset"] != offset: - raise ValueError(f"no clip dictionary starts at 0x{offset:x}") - with open(path, "rb") as fh: - data = b"" - for k in groups[0][1]: - off, stored, raw = segment(rows, k) - fh.seek(off) - data += fh.read(stored) if raw else zlib.decompressobj().decompress(fh.read(stored)) - s = System(data) - d = parse_dictionary(s) - for pack in d["packs"]: - for anim in pack["animations"]: - try: - tracks, total = decode_animation(s, anim) - anim["decoded"] = {str(k): [list(v) for v in vals[:frames]] for k, vals in tracks.items()} - anim["decoded_frames"] = total - except (DecodeError, struct.error, IndexError) as e: - anim["error"] = str(e) - anim["tracks"] = [{"bone": f"0x{b:08x}", "type": TRACK_TYPES.get(t, f"0x{t:08x}"), - "format": TRACK_FORMATS.get(f, f)} for b, t, f in anim["tracks"]] - anim.pop("sequences") - for clip in d["clips"]: - for a in clip["animations"]: - a.pop("animation") - return d - - -def same_output_path(first, second): - """True when writing ``second`` would truncate ``first`` (same file, path or hard link).""" - if os.path.normcase(os.path.realpath(first)) == os.path.normcase(os.path.realpath(second)): - return True - try: - return os.path.samefile(first, second) - except OSError: - return False - - -def main(): - ap = argparse.ArgumentParser(description=__doc__.splitlines()[0]) - ap.add_argument("archive", help="anim.rpf") - ap.add_argument("out", nargs="?", help="output .json (counts and one row per dictionary)") - ap.add_argument("--start", type=anim_index.offset, help="first byte to scan (default: the RPF data start)") - ap.add_argument("--limit", type=anim_index.byte_count, help="number of bytes to scan") - ap.add_argument("--jobs", type=int, default=1, help="worker processes for decoding (default 1)") - ap.add_argument("--budget", type=float, default=600.0, - help="seconds per dictionary; animations left after it are counted as skipped (default 600)") - ap.add_argument("--decode", type=anim_index.offset, metavar="OFFSET", - help="print one dictionary (root stream offset) with decoded values to stdout") - ap.add_argument("--frames", type=int, default=4, help="frames per track printed by --decode (default 4)") - ap.add_argument("--quiet", action="store_true") - a = ap.parse_args() - if a.jobs < 1: - ap.error("--jobs must be at least 1") - if a.frames < 0: - ap.error("--frames must be 0 or more") - if math.isnan(a.budget) or a.budget < 0: - ap.error("--budget must be 0 or a finite positive value (or infinite)") - if a.decode is None and not a.out: - ap.error("an output .json is required unless --decode is given") - if a.out: - if os.path.isdir(a.out): - ap.error(f"{a.out} is a directory, not a .json file") - if same_output_path(a.archive, a.out): - ap.error("output must not overwrite the input archive") - try: - if a.decode is not None: - json.dump(decode_one(a.archive, a.decode, a.frames), sys.stdout, indent=1) - print() - return 0 - - def progress(n, total): - if not a.quiet: - print(f"[{n / max(1, total):6.1%}] {n} dictionaries", flush=True) - rows, summary = scan(a.archive, a.start, a.limit, a.jobs, progress, a.budget) - except ValueError as e: - sys.exit(f"{a.archive}: {e}") - except OSError as e: - sys.exit(f"{e.filename or a.archive}: {e.strerror or e}") - try: - parent = os.path.dirname(os.path.abspath(a.out)) - if parent: - os.makedirs(parent, exist_ok=True) - with open(a.out, "w", encoding="utf-8", newline="\n") as f: - json.dump({"summary": summary, "dictionaries": rows}, f, indent=1) - except OSError as e: - sys.exit(f"{a.out}: cannot write: {e.strerror or e}") - c = summary["counts"] - print(json.dumps({k: summary[k] for k in ("streams", "dictionary_roots", "dictionaries_grouped", "unresolved")})) - print(json.dumps({k: c.get(k, 0) for k in ("dictionaries", "clips", "animations", "animations_decoded", - "animations_failed", "sequences")})) - return 0 - - -if __name__ == "__main__": - try: # a redirected stdout is strict ANSI code page under -I; write '?' for what it cannot encode - sys.stdout.reconfigure(errors="replace") - except (AttributeError, ValueError, OSError): - pass - sys.exit(main()) diff --git a/tools/anim_glb.py b/tools/anim_glb.py deleted file mode 100644 index d1dc1059b..000000000 --- a/tools/anim_glb.py +++ /dev/null @@ -1,819 +0,0 @@ -"""Export a skinned character part with its skeleton and decoded clips as an animated binary glTF (.glb). - -Three readers meet here: the skeleton that a character fragment carries at drawable + 0x18, the skin streams of -a part drawable (docs/character_skeleton.md, ASSET-12) and the clip dictionaries of anim.rpf (anim_clips.py). Each -part mesh is bound to the skeleton through its model's bone list, and each clip track to a skeleton joint through -its bone hash. Nothing is invented: a part whose weighted bones are not in the skeleton is refused, and clip tracks -that name no joint are counted and left out. - -Skeleton (measured on the 596-bone female and 560-bone male humanoid fragments of packs.rpf): - - header = drawable + 0x18 +0x28 bone records, +0x30 inverse bind matrices (64 bytes each), - +0x40 u16 parent indices (0xFFFF = root), +0x6C/+0x6E u16 bone count - bone record (0x50 bytes) +0x00 rotation quaternion (x, y, z, w), +0x10 translation (x, y, z), - +0x1C u32 joaat32(lowercase bone name), +0x20 scale (x, y, z), - +0x30 name pointer, +0x46 u16 parent, +0x48 u16 own index - -The default rotation, translation and scale are local to the parent. Composed down the hierarchy they give each -joint's model-space transform, and its inverse is the stored inverse bind matrix (the check is in `read_skeleton`). -The matrices are row-vector (D3D) matrices; stored row by row, they are glTF's column-major layout as is. - -Part meshes: grmModel + 0x14 u16 bone count, grmModel + 0x28 pointer to that many u32 bone hashes (joaat32 of the -bone names). A vertex's bone indices (FVF semantics 20/21) index this list; its weights are the UNORM bytes of -semantics 16/17 (they sum to 255). Positions and the clustered index buffer are read as rpf9-explorer reads them. - -Clips: a `.clip` lists animations, each played over its own [start, end] window at its rate. A track is -{joaat32(bone name), track type, format}: `bonerotation` (quaternion), `bonetranslation` (vec3) and `bonescale` -(vec3) drive the joint with that hash, and bone hash 0 is the mover (root motion), which drives an extra node -above the skeleton. Other track types (`genericcontrol`, facial, camera) are counted, not exported. - -The skeleton, meshes and clips stay in RAGE's Z-up space; one root node turns it into glTF's Y-up. - -Usage: - python -I anim_glb.py --skeleton --part [:] [--part ...] - [--anim --dictionary [--clip ...]] - [--lod N] [--max-influences 4|8] [--no-root-motion] [--report ] - python -I anim_glb.py --coverage --skeleton --anim --report - [--jobs N] - -Offsets are the resources' zlib stream offsets in the archive (the `0x...` offsets rpf9dump and skin_streams -report). `--part` takes a drawable, a fragment or a drawable dictionary; `:` picks a dictionary child. -`--coverage` writes counts only: how many clip-dictionary bone tracks name a joint of the skeleton. -Usage: `python -I tools/anim_glb.py --help` lists the options. -""" -import argparse -import collections -import json -import math -import mmap -import os -import struct -import sys -import tempfile -import time -import zlib - -# -I keeps the script directory off sys.path, so add it explicitly before importing the sibling readers. -sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) - -import anim_clips # noqa: E402 -import anim_index # noqa: E402 -from file_mode import published_mode # noqa: E402 -import glb_writer # noqa: E402 -from pool_workers import process_workers # noqa: E402 -import skin_streams # noqa: E402 - -SYSTEM = 0x50000000 -GRAPHICS = 0x60000000 -MAX_BONES = 4096 -BONE_STRIDE = 0x50 -WEIGHT_SLOTS = (16, 17) -INDEX_SLOTS = (20, 21) -# (element bytes, format byte) of the bone-index slots, as skin_streams measures them -INDEX_LAYOUTS = {(4, 30): "u8x4", (16, 3): "packed", (8, 12): "u16x4", (1, 62): "rigid-u8", (2, 57): "rigid-u16"} -TRACK_PATHS = {anim_index.joaat32("bonerotation"): "rotation", anim_index.joaat32("bonetranslation"): "translation", - anim_index.joaat32("bonescale"): "scale"} -PATH_FORMATS = {"rotation": 0, "translation": 2, "scale": 2} -Z_UP_TO_Y_UP = [-math.sqrt(0.5), 0.0, 0.0, math.sqrt(0.5)] # -90 degrees about X: (x, y, z) -> (x, z, -y) -COMPONENT_UNSIGNED_SHORT = 5123 -COMPONENT_FLOAT = 5126 - - -class ExportError(ValueError): - """The input is not what the exporter reads; the message says which check failed.""" - - -def require(condition, message): - if not condition: - raise ExportError(message) - - -def u16(b, o): - return struct.unpack_from("= len(b): - return None - at = p - SYSTEM - end = b.find(b"\0", at, at + 256) - if end < 0: - return None - return b[at:end].decode("latin-1") - - -# ---------------------------------------------------------------- resources - - -def load_resource(m, at): - """(system pages, graphics pages) of the resource whose first zlib stream starts at `at`.""" - size = len(m) - require(0 <= at < size, f"offset 0x{at:x} is outside the archive") - data, used = skin_streams.inflate_at(m, at, size) - require(data is not None and len(data) >= 192, f"no resource stream at 0x{at:x}") - directory = sys_at(data, 8, 16, "page directory") - system_pages, graphics_pages = data[directory + 8], data[directory + 9] - require(0 < system_pages <= 32 and graphics_pages <= 32, "page directory counts") - parts, fp = [data], at + used - for _ in range(system_pages - 1 + graphics_pages): - nxt = skin_streams.next_stream(m, fp, size) - require(nxt is not None, "a page stream of the resource is missing") - parts.append(nxt[0]) - fp = nxt[1] + nxt[2] - return b"".join(parts[:system_pages]), b"".join(parts[system_pages:]) - - -def drawable_at(sys, child): - """System offset of the drawable to read: a dictionary child, a fragment's drawable or the drawable itself.""" - kind = skin_streams.resource_kind(sys) - require(kind is not None, "not a drawable, fragment or drawable dictionary") - found = list(skin_streams.drawable_offsets(sys, kind)) - if child is None: - require(len(found) == 1, f"{kind} with {len(found)} drawables: pick one with :") - child = 0 - require(0 <= child < len(found), f"child {child} is not in 0..{len(found) - 1}") - return found[child] - - -# ---------------------------------------------------------------- skeleton - - -def quat_mul(a, b): - ax, ay, az, aw = a - bx, by, bz, bw = b - return (aw * bx + ax * bw + ay * bz - az * by, aw * by - ax * bz + ay * bw + az * bx, - aw * bz + ax * by - ay * bx + az * bw, aw * bw - ax * bx - ay * by - az * bz) - - -def quat_rotate(q, v): - x, y, z, w = q - vx, vy, vz = v - tx, ty, tz = 2 * (y * vz - z * vy), 2 * (z * vx - x * vz), 2 * (x * vy - y * vx) - return (vx + w * tx + y * tz - z * ty, vy + w * ty + z * tx - x * tz, vz + w * tz + x * ty - y * tx) - - -def read_skeleton(sys, drawable): - """-> list of joints {hash, name, parent, rotation, translation, scale, inverse_bind (16 floats)}. - - Also returns the largest distance between a joint's model-space position composed from the default - transforms and the one its inverse bind matrix gives; `export` refuses a skeleton where they disagree.""" - header = sys_at(sys, drawable + 0x18, 0x70, "skeleton") - count = u16(sys, header + 0x6C) - require(0 < count <= MAX_BONES and count == u16(sys, header + 0x6E), "skeleton bone count") - records = sys_at(sys, header + 0x28, count * BONE_STRIDE, "bone records") - inverse = sys_at(sys, header + 0x30, count * 64, "inverse bind matrices") - parents = sys_at(sys, header + 0x40, count * 2, "parent indices") - joints = [] - for i in range(count): - r = records + i * BONE_STRIDE - parent = u16(sys, parents + 2 * i) - require(u16(sys, r + 0x48) == i and u16(sys, r + 0x46) == parent, f"bone record {i} index/parent") - require(parent == 0xFFFF or parent < i, f"bone {i} parent {parent} is not an earlier bone") - m = struct.unpack_from("<16f", sys, inverse + 64 * i) - require(all(math.isfinite(v) for v in m) and m[3] == m[7] == m[11] == 0, f"inverse bind matrix {i}") - # RageSkeleton.cs:109 also refuses a degenerate matrix. The stored last column is (0, 0, 0, 1), - # so the 4x4 determinant is the determinant of the upper-left 3x3 linear part. As in the C#, - # abs() keeps mirrored binds; the epsilon rejects clearly non-invertible ones, not just float32 zero. - det = (m[0] * (m[5] * m[10] - m[6] * m[9]) - - m[1] * (m[4] * m[10] - m[6] * m[8]) - + m[2] * (m[4] * m[9] - m[5] * m[8])) - require(math.isfinite(det) and abs(det) >= 1e-12, f"inverse bind matrix {i} determinant") - joints.append({ - "hash": u32(sys, r + 0x1C), "name": c_string(sys, r + 0x30), "parent": None if parent == 0xFFFF else parent, - "rotation": struct.unpack_from("<4f", sys, r), "translation": struct.unpack_from("<3f", sys, r + 0x10), - "scale": struct.unpack_from("<3f", sys, r + 0x20), "inverse_bind": list(m[:15]) + [1.0], - }) - # Compose the default transforms; compare each joint's origin with the one its inverse bind matrix gives. - world, worst = [], 0.0 - for j in joints: - q, t = j["rotation"], j["translation"] - if j["parent"] is None: - world.append((q, t)) - else: - pq, pt = world[j["parent"]] - world.append((quat_mul(pq, q), tuple(a + b for a, b in zip(pt, quat_rotate(pq, t))))) - m = j["inverse_bind"] - rows, t_inv = (m[0:3], m[4:7], m[8:11]), m[12:15] - origin = tuple(-sum(t_inv[k] * rows[c][k] for k in range(3)) for c in range(3)) - worst = max(worst, max(abs(a - b) for a, b in zip(origin, world[-1][1]))) - return joints, worst - - -# ---------------------------------------------------------------- part meshes - - -def read_positions(sys, gfx, vb, fvf, vertices): - offset, size, fmt = u32(sys, fvf), sys[fvf + 0xD0], sys[fvf + 0x104] - length = u32(sys, vb + 8) * u16(sys, vb + 12) - require(length > 0 and 96 <= offset <= length and size * vertices <= length - offset, "position stream bounds") - at = gfx_at(sys, gfx, vb + 24, length, "vertex buffer") - data = gfx[at:at + length] - if (size, fmt) == (12, 6): - require(u32(data, 0) & 127 == 0x63, "float position descriptor") - return [struct.unpack_from("<3f", data, offset + 12 * i) for i in range(vertices)], data - if (size, fmt) == (8, 16): - require(offset >= 128 and u32(data, 0) & 127 == 0x42, "quantized position descriptor") - bias, scale = struct.unpack_from("<3f", data, 96), struct.unpack_from("<3f", data, 112) - axis = u32(data, 108) - require(axis <= 2 and min(scale) >= 0, "quantized position bias/scale") - out = [] - for i in range(vertices): - q = u64(data, offset + 8 * i) - p = (bias[0] + scale[0] * ((q >> 8) & 0xFFFFFF), bias[1] + scale[1] * ((((q >> 32) & 0xFFFF) << 8) | (q & 0xFF)), - bias[2] + scale[2] * (q >> 48)) - out.append((p[2], p[1], p[0]) if axis == 0 else (p[1], p[2], p[0]) if axis == 1 else p) - return out, data - raise ExportError(f"position encoding {size}/{fmt} is not read") - - -def read_triangles(sys, gfx, geometry, vertices): - """The clustered index buffer: cluster records, 7-bit corner triplets, then the vertex reference list.""" - descriptor = sys_at(sys, geometry + 64, 16, "index descriptor") - ib = sys_at(sys, descriptor, 64, "index buffer") - require(u16(sys, ib + 12) == 4, "index buffer stride") - length = u32(sys, ib + 8) * 4 - at = gfx_at(sys, gfx, ib + 24, length, "index data") - data = gfx[at:at + length] - count_flags = u32(data, 0) - palette = count_flags & 0x40000000 - clusters = count_flags & (0xFFFF if palette else 0x7FFFFFFF) - triangles, refs = u32(data, 4), u32(data, 8) - require(0 < clusters <= 2048 and 0 < triangles <= 65535 and 0 < refs <= 65535, "index buffer counts") - ref_size = 2 if count_flags & 0x80000000 else 4 - tri_at = 12 + clusters * 16 - refs_at = tri_at + triangles * 4 - require(refs_at + refs * ref_size <= length, "index buffer length") - fmt = "<%d%s" % (refs, "H" if ref_size == 2 else "I") - references = struct.unpack_from(fmt, data, refs_at) - require(max(references) < vertices, "vertex reference past the vertex count") - indices, seen_refs, seen_tris = [], 0, 0 - for c in range(clusters): - packed, offsets = u32(data, 12 + 16 * c), u32(data, 16 + 16 * c) - n_vertices, n_tris = (packed & 127) + 1, ((packed >> 7) & 255) + 1 - v_start, t_start = offsets & 0xFFFF, offsets >> 16 - require(v_start == seen_refs and t_start == seen_tris, "cluster starts (meshes over 65,535 are not read)") - for t in range(t_start, t_start + n_tris): - word = u32(data, tri_at + 4 * t) - require(word >> 21 == c, "triangle cluster tag") - for corner in range(3): - local = (word >> (7 * corner)) & 127 - require(local < n_vertices, "triangle corner past its cluster") - indices.append(references[v_start + local]) - seen_refs += n_vertices - seen_tris += n_tris - require(seen_refs == refs and seen_tris == triangles, "clusters do not cover the index buffer") - constant = count_flags & 0x20000000 - hint = (count_flags >> 16) & 0x1FFF - return indices, (hint // 2 if palette and constant else None) - - -def read_skin(sys, fvf, data, vertices, constant_bone): - """Per vertex: up to 8 (model bone index, weight 0..255) pairs with a non-zero weight.""" - slots = {} - for i in WEIGHT_SLOTS + INDEX_SLOTS: - size = sys[fvf + 0xD0 + i] - if size: - offset = u32(sys, fvf + 4 * i) - require(offset + size * vertices <= len(data), f"skin slot {i} bounds") - slots[i] = (size, sys[fvf + 0x104 + i], offset) - index_slots = [i for i in INDEX_SLOTS if i in slots] - if not index_slots: - require(constant_bone is not None, "mesh has no bone-index stream and no constant binding") - return [[(constant_bone, 255)] for _ in range(vertices)], "constant" - layout = INDEX_LAYOUTS.get(slots[index_slots[0]][:2]) - require(layout is not None and all(slots[i][:2] == slots[index_slots[0]][:2] for i in index_slots), - "bone-index stream format") - weight_slots = [i for i in WEIGHT_SLOTS if i in slots] - require(all(slots[i][:2] == (4, 28) for i in weight_slots), "weight stream format") - if layout.startswith("rigid"): - require(not weight_slots, "rigid index stream with weights") - size, _fmt, offset = slots[index_slots[0]] - code = "B" if size == 1 else "H" - return [[(v, 255)] for v in struct.unpack_from(f"<{vertices}{code}", data, offset)], layout - require(len(weight_slots) == len(index_slots), "weight and index stream counts differ") - out = [] - for v in range(vertices): - pairs = [] - for wi, ii in zip(weight_slots, index_slots): - weights = data[slots[wi][2] + 4 * v:slots[wi][2] + 4 * v + 4] - at = slots[ii][2] - if layout == "u8x4": - bones = data[at + 4 * v:at + 4 * v + 4] - elif layout == "u16x4": - bones = struct.unpack_from("<4H", data, at + 8 * v) - else: # packed: bits 0..11 of each u32 - bones = [w & 0xFFF for w in struct.unpack_from("<4I", data, at + 16 * v)] - pairs.extend((b, w) for b, w in zip(bones, weights) if w) - out.append(pairs) - return out, layout - - -def read_part(sys, gfx, drawable, lod=0): - """-> list of meshes {model, geometry, positions, indices, skin [(model bone, weight)], palette [hash], layout}.""" - lod_field = drawable + 80 + 8 * lod - require(0 <= lod < 4 and u64(sys, lod_field), f"LOD {lod} is empty") - lod_at = sys_at(sys, lod_field, 16, "LOD") - models = u16(sys, lod_at + 8) - require(0 < models <= 256 and models == u16(sys, lod_at + 10), "LOD model count") - model_list = sys_at(sys, lod_at, models * 8, "model list") - meshes = [] - for mi in range(models): - model = sys_at(sys, model_list + 8 * mi, 56, "model") - count, bones = u16(sys, model + 16), u16(sys, model + 20) - require(0 < count <= 256 and count == u16(sys, model + 18) == u16(sys, model + 54), "geometry count") - require(0 < bones <= MAX_BONES, f"model {mi} has no bone list (not skinned)") - palette_at = sys_at(sys, model + 0x28, bones * 4, "model bone list") - palette = list(struct.unpack_from(f"<{bones}I", sys, palette_at)) - geometries = sys_at(sys, model + 8, count * 8, "geometry list") - for gi in range(count): - geometry = sys_at(sys, geometries + 8 * gi, 160, "geometry") - vb = sys_at(sys, geometry + 8, 80, "vertex buffer header") - fvf = sys_at(sys, vb + 64, 0x13C, "FVF table") - flags = u32(sys, fvf + 0x138) - vertices = flags >> 10 - require(flags & 1 and 0 < vertices <= 1_000_000, "vertex count") - positions, data = read_positions(sys, gfx, vb, fvf, vertices) - indices, constant_bone = read_triangles(sys, gfx, geometry, vertices) - skin, layout = read_skin(sys, fvf, data, vertices, constant_bone) - for pairs in skin: - for b, _w in pairs: - require(b < bones, "weighted bone index past the model's bone list") - meshes.append({"model": mi, "geometry": gi, "positions": positions, "indices": indices, "skin": skin, - "palette": palette, "layout": layout}) - return meshes - - -def bind_part(meshes, joints, max_influences=8): - """Model bone index -> skeleton joint index through the bone hashes; -> per mesh JOINTS/WEIGHTS sets. - - With `max_influences` 4, a vertex keeps its four largest weights, renormalised, in one set (three.js and - other viewers read only JOINTS_0/WEIGHTS_0).""" - by_hash = {} - for i, j in enumerate(joints): - by_hash[j["hash"]] = i if j["hash"] not in by_hash else -1 - for mesh in meshes: - mapping = [by_hash.get(h) for h in mesh["palette"]] - missing = {mesh["palette"][b] for pairs in mesh["skin"] for b, _w in pairs if mapping[b] is None or mapping[b] < 0} - require(not missing, "weighted bones not in the skeleton: " + ", ".join(f"0x{h:08x}" for h in sorted(missing))) - sets = 2 if max_influences > 4 and max((len(p) for p in mesh["skin"]), default=0) > 4 else 1 - joint_rows, weight_rows = [], [] - for pairs in mesh["skin"]: - pairs = sorted(pairs, key=lambda p: -p[1])[:4 * sets] - total = float(sum(w for _b, w in pairs)) - require(total > 0, "vertex with no weight") - row_j = [mapping[b] for b, _w in pairs] + [0] * (4 * sets - len(pairs)) - row_w = [w / total for _b, w in pairs] + [0.0] * (4 * sets - len(pairs)) - joint_rows.append(row_j) - weight_rows.append(row_w) - mesh["joints"], mesh["weights"], mesh["sets"] = joint_rows, weight_rows, sets - return meshes - - -# ---------------------------------------------------------------- clips - - -def contiguous_rows(m, offset): - end = min(len(m), offset + (64 << 20)) - while 0 <= offset < end and anim_index.ZHDR.match(m, offset): - data, used = skin_streams.inflate_at(m, offset, end) - if data is None or len(data) < 64: - break - yield anim_index.classify(data, offset, used) - offset = (offset + used + 15) & ~15 - - -def load_dictionary(path, offset): - """Parse the clip dictionary whose root stream starts at `offset` -> (System, dictionary).""" - with open(path, "rb") as fh, mmap.mmap(fh.fileno(), 0, access=mmap.ACCESS_READ) as m: - streams = contiguous_rows(m, offset) - first = next(streams, None) - rows = [first] if first is not None else [] - groups, _unresolved, _gaps = anim_clips.group(m, rows, first_row_only=True, continuation_rows=streams) - require(groups and rows[groups[0][0]]["offset"] == offset, f"no clip dictionary starts at 0x{offset:x}") - data = b"" - with open(path, "rb") as fh: - for k in groups[0][1]: - off, stored, raw = anim_clips.segment(rows, k) - fh.seek(off) - data += fh.read(stored) if raw else zlib.decompressobj().decompress(fh.read(stored)) - s = anim_clips.System(data) - return s, anim_clips.parse_dictionary(s) - - -def clip_label(clip): - name = clip.get("name") or f"0x{clip['hash']:08x}" - if name.startswith("pack:/"): - name = name[6:] - return name[:-5] if name.endswith(".clip") else name - - -def select_clips(dictionary, wanted): - clips = [c for c in dictionary["clips"] if c["kind"] == "clip"] - if not wanted: - return clips - out = [] - for w in wanted: - wanted_hash = None - if w.lower().startswith("0x"): - try: - wanted_hash = int(w, 16) - except ValueError: - wanted_hash = None - hits = [c for c in clips if clip_label(c) == w or (wanted_hash is not None and c["hash"] == wanted_hash)] - require(hits, f"clip {w!r} is not in the dictionary") - out.extend(hits) - return out - - -def clip_channels(s, dictionary, clip, joint_by_hash, root_motion, tally): - """-> {(target, path): [(time, value)]} for one clip. target is a joint index or 'mover'.""" - animations = {a["offset"]: a for p in dictionary["packs"] for a in p["animations"]} - channels = {} - for entry in clip["animations"]: - anim = animations.get(entry["animation"]) - if anim is None: - tally["animations_not_local"] += 1 - continue - tracks, frames = anim_clips.decode_animation(s, anim) - rate = entry["rate"] if entry["rate"] and math.isfinite(entry["rate"]) and entry["rate"] > 0 else 1.0 - step = anim["duration"] / (frames - 1) if frames > 1 and anim["duration"] > 0 else 1.0 / 30 - start = entry["start"] if math.isfinite(entry["start"]) else 0.0 - end = entry["end"] if math.isfinite(entry["end"]) and entry["end"] >= start else anim["duration"] - if end == start: - keep = [min(range(frames), key=lambda k: abs(k * step - start))] if frames else [] - single_pose = True - else: - keep = [k for k in range(frames) if start - 1e-4 <= k * step <= end + 1e-4] - single_pose = not keep - if single_pose: - target_time = 0.5 * (start + end) - keep = [min(range(frames), key=lambda k: abs(k * step - target_time))] if frames else [] - if not keep: - continue - tally["animations"] += 1 - for t, (bone, ttype, fmt) in enumerate(anim["tracks"]): - path = TRACK_PATHS.get(ttype) - if path is None: - tally["tracks_other_type"] += 1 - continue - if fmt != PATH_FORMATS[path] or t not in tracks: - tally["tracks_unexpected_format"] += 1 - continue - if bone == 0: - if not root_motion: - tally["tracks_mover_skipped"] += 1 - continue - target = "mover" - else: - target = joint_by_hash.get(bone) - if target is None: - tally["tracks_bone_not_in_skeleton"] += 1 - continue - tally["tracks_exported"] += 1 - if (target, path) in channels: - tally["tracks_overridden"] += 1 - # a frame kept by the 1e-4 tolerance before `start` would get a slightly negative time - if single_pose: - channels[(target, path)] = [(0.0, tuple(tracks[t][k])) for k in keep] - else: - channels[(target, path)] = [(max(0.0, (k * step - start) / rate), tuple(tracks[t][k])) for k in keep] - return channels - - -# ---------------------------------------------------------------- glTF - - -def _view(buf, views, payload, target=None): - return glb_writer._append_buffer_view(buf, views, payload, target=target) - - -def _accessor(accessors, view, component, count, kind, **extra): - accessors.append(dict(bufferView=view, componentType=component, count=count, type=kind, **extra)) - return len(accessors) - 1 - - -def _floats(values): - return struct.pack(f"<{len(values)}f", *values) - - -def build(joints, meshes, clips, *, root_motion=True, generator="Leonida anim_glb"): - """glTF JSON + binary chunk for the skeleton, the bound meshes and the clip channels -> GLB bytes.""" - buf, views, accessors = bytearray(), [], [] - nodes = [{"name": "rage_z_up", "rotation": Z_UP_TO_Y_UP, "children": []}] - holder = nodes[0] - mover = None - if root_motion: - mover = len(nodes) - nodes.append({"name": "mover", "children": []}) - holder["children"].append(mover) - holder = nodes[mover] - first_joint = len(nodes) - for i, j in enumerate(joints): - node = {"name": j["name"] or f"bone_0x{j['hash']:08x}"} - node["rotation"] = [round(v, 7) for v in j["rotation"]] - node["translation"] = [round(v, 7) for v in j["translation"]] - if any(abs(s - 1.0) > 1e-6 for s in j["scale"]): - node["scale"] = [round(v, 7) for v in j["scale"]] - nodes.append(node) - for i, j in enumerate(joints): - if j["parent"] is None: - holder["children"].append(first_joint + i) - else: - nodes[first_joint + j["parent"]].setdefault("children", []).append(first_joint + i) - ibm_view = _view(buf, views, _floats([v for j in joints for v in j["inverse_bind"]])) - ibm = _accessor(accessors, ibm_view, COMPONENT_FLOAT, len(joints), "MAT4") - skin = {"joints": list(range(first_joint, first_joint + len(joints))), "inverseBindMatrices": ibm} - roots = [first_joint + i for i, j in enumerate(joints) if j["parent"] is None] - if len(roots) == 1: - skin["skeleton"] = roots[0] - gltf_meshes, scene_nodes = [], [0] - for mesh in meshes: - packed = glb_writer.pack_primitive({"positions": mesh["positions"], "indices": mesh["indices"]}) - attributes, index_accessor = glb_writer._append_packed(buf, views, accessors, packed) - for k in range(mesh["sets"]): - jv = _view(buf, views, struct.pack(f"<{4 * len(mesh['joints'])}H", - *[x for row in mesh["joints"] for x in row[4 * k:4 * k + 4]]), - target=glb_writer.TARGET_ARRAY_BUFFER) - attributes[f"JOINTS_{k}"] = _accessor(accessors, jv, COMPONENT_UNSIGNED_SHORT, len(mesh["joints"]), "VEC4") - wv = _view(buf, views, _floats([x for row in mesh["weights"] for x in row[4 * k:4 * k + 4]]), - target=glb_writer.TARGET_ARRAY_BUFFER) - attributes[f"WEIGHTS_{k}"] = _accessor(accessors, wv, COMPONENT_FLOAT, len(mesh["weights"]), "VEC4") - gltf_meshes.append({"name": mesh["name"], "primitives": [{"attributes": attributes, "indices": index_accessor, - "mode": glb_writer.MODE_TRIANGLES}]}) - scene_nodes.append(len(nodes)) - # A skinned mesh's own transform is ignored (glTF 2.0, 3.7.3), so its node sits at the scene root. - nodes.append({"name": mesh["name"], "mesh": len(gltf_meshes) - 1, "skin": 0}) - animations = [] - for name, channels in clips: - samplers, out_channels = [], [] - for (target, path), keys in sorted(channels.items(), key=lambda kv: (str(kv[0][0]), kv[0][1])): - time_bytes = _floats([t for t, _v in keys]) - times = struct.unpack(f"<{len(keys)}f", time_bytes) - require(all(b > a for a, b in zip(times, times[1:])), "key times are not increasing") - tv = _view(buf, views, time_bytes) - ta = _accessor(accessors, tv, COMPONENT_FLOAT, len(times), "SCALAR", min=[min(times)], max=[max(times)]) - values = [x for _t, v in keys for x in v] - vv = _view(buf, views, _floats(values)) - va = _accessor(accessors, vv, COMPONENT_FLOAT, len(keys), "VEC4" if path == "rotation" else "VEC3") - samplers.append({"input": ta, "output": va, "interpolation": "LINEAR"}) - node = mover if target == "mover" else first_joint + target - out_channels.append({"sampler": len(samplers) - 1, "target": {"node": node, "path": path}}) - if out_channels: - animations.append({"name": name, "samplers": samplers, "channels": out_channels}) - gltf = { - "asset": {"version": "2.0", "generator": generator}, - "scene": 0, "scenes": [{"nodes": scene_nodes}], "nodes": nodes, "skins": [skin], "meshes": gltf_meshes, - "accessors": accessors, "bufferViews": views, "buffers": [{"byteLength": len(buf)}], - } - if animations: - gltf["animations"] = animations - return pack_glb(gltf, buf), gltf - - -def pack_glb(gltf, buf): - buf = bytes(buf) + b"\0" * ((-len(buf)) % 4) - gltf["buffers"][0]["byteLength"] = len(buf) - text = json.dumps(gltf, separators=(",", ":"), allow_nan=False).encode("utf-8") - text += b" " * ((-len(text)) % 4) - total = 12 + 8 + len(text) + 8 + len(buf) - return b"".join((struct.pack("<4sII", glb_writer.GLB_MAGIC, glb_writer.GLB_VERSION, total), - struct.pack("= 0.9 - counts["dictionaries_no_bone_in_skeleton"] += not hit - return counts - - -def coverage(args): - started = time.monotonic() - with open(args.archive, "rb") as fh, mmap.mmap(fh.fileno(), 0, access=mmap.ACCESS_READ) as m: - sys_pages, _gfx = load_resource(m, args.skeleton[0]) - joints, worst = read_skeleton(sys_pages, drawable_at(sys_pages, args.skeleton[1])) - rows, _walk = anim_index.scan_rpf(args.anim) - with open(args.anim, "rb") as fh, mmap.mmap(fh.fileno(), 0, access=mmap.ACCESS_READ) as m: - groups, _unresolved, _gaps = anim_clips.group(m, rows) - segments = [[anim_clips.segment(rows, k) for k in parts] for _root, parts in groups] - hashes = sorted({j["hash"] for j in joints}) - jobs = process_workers(max(1, args.jobs)) # a pool takes at most 61 workers on Windows - slices = [(args.anim, segments[i::jobs], hashes) for i in range(jobs)] - total = collections.Counter() - if jobs == 1: - total.update(coverage_worker(slices[0])) - else: - from concurrent.futures import ProcessPoolExecutor - with ProcessPoolExecutor(jobs) as ex: - for part in ex.map(coverage_worker, slices): - total.update(part) - return {"skeleton": {"offset": f"0x{args.skeleton[0]:x}", "joints": len(joints), "bind_error": worst}, - "counts": dict(sorted(total.items())), "seconds": round(time.monotonic() - started, 1)} - - -def write_report(path, text): - """Stage the JSON report next to its destination and swap it in, so a write or replace failure keeps any - previous report intact and preserves its permission bits.""" - parent = os.path.dirname(os.path.abspath(path)) - tmp = None - try: - with tempfile.NamedTemporaryFile("w", encoding="utf-8", newline="\n", dir=parent, - prefix=".anim_glb-", suffix=".tmp", delete=False) as f: - tmp = f.name - f.write(text) - os.chmod(tmp, published_mode(path)) - os.replace(tmp, path) - except BaseException: - if tmp is not None: - try: - if os.path.lexists(tmp): - os.chmod(tmp, 0o600) - os.remove(tmp) - except OSError: - pass - raise - - -def main(argv=None): - ap = argparse.ArgumentParser(description=__doc__.split("\n")[0]) - ap.add_argument("archive", help="archive holding the skeleton and the parts (packs.rpf)") - ap.add_argument("out", nargs="?", help="output .glb (export mode)") - ap.add_argument("--skeleton", type=parse_offset, required=True, help="resource with the skeleton, [:]") - ap.add_argument("--part", type=parse_offset, action="append", default=[], help="part drawable, [:]") - ap.add_argument("--anim", help="anim.rpf") - ap.add_argument("--dictionary", type=lambda t: parse_offset(t)[0], help="export: clip dictionary offset in --anim") - ap.add_argument("--clip", action="append", default=[], - help="export: name (without pack:/ and .clip) or 0xhash in the selected --anim dictionary") - ap.add_argument("--lod", type=int, default=0, help="LOD level of the parts (0 = highest)") - ap.add_argument("--max-influences", type=int, choices=(4, 8), default=8, - help="bone influences per vertex; 4 keeps the largest four, renormalised (three.js reads four)") - ap.add_argument("--no-root-motion", action="store_true", help="leave out the mover (bone hash 0) tracks") - ap.add_argument("--coverage", action="store_true", help="count clip bone tracks that name a skeleton joint") - ap.add_argument("--jobs", type=int, default=1, help="worker processes for --coverage (at least 1)") - ap.add_argument("--report", help="write a JSON report (counts only)") - args = ap.parse_args(argv) - if args.jobs < 1: - ap.error("--jobs must be at least 1") - inputs = [args.archive] + ([args.anim] if args.anim else []) - outputs = [p for p in (args.out, args.report) if p] - for o in outputs: - for i in inputs: - if os.path.exists(o) and same_path(i, o): - ap.error(f"{o} is an input; refusing to overwrite it") - if args.report and os.path.isdir(args.report): - ap.error(f"--report is a directory: {args.report}") - if args.out and args.report and same_path(args.out, args.report): - ap.error("the GLB and the report are the same path") - if args.clip or args.dictionary is not None: - if args.coverage: - ap.error("--clip and --dictionary select clips for export, not --coverage") - if not args.anim: - ap.error("--clip and --dictionary require --anim") - if args.coverage: - if not args.anim or not args.report: - ap.error("--coverage needs --anim and --report") - if args.out: - ap.error("--coverage writes no GLB") - else: - if not args.out or not args.part: - ap.error("export needs and at least one --part") - if args.anim and args.dictionary is None: - ap.error("--anim needs --dictionary") - try: - report = coverage(args) if args.coverage else export(args) - except OSError as e: - print(f"ERROR: {e.filename or args.archive}: {e.strerror or e}", file=sys.stderr) - return 2 - except (ExportError, anim_clips.DecodeError, struct.error, ValueError) as e: - print(f"ERROR: {e}", file=sys.stderr) - return 2 - if args.report: - try: - write_report(args.report, json.dumps(report, indent=1, sort_keys=True) + "\n") - except OSError as e: - print(f"ERROR: cannot write report {args.report}: {e.strerror or e}", file=sys.stderr) - return 2 - print(json.dumps({k: v for k, v in report.items() if k in ("counts", "skeleton", "seconds")}, sort_keys=True)) - return 0 - - -if __name__ == "__main__": - try: # a redirected stdout is strict ANSI code page under -I; write '?' for what it cannot encode - sys.stdout.reconfigure(errors="replace") - except (AttributeError, ValueError, OSError): - pass - sys.exit(main()) diff --git a/tools/anim_index.py b/tools/anim_index.py deleted file mode 100644 index 069437c80..000000000 --- a/tools/anim_index.py +++ /dev/null @@ -1,637 +0,0 @@ -"""Index the animation containers in an RPF9 data area or a folder of carved streams. - -RPF9's table of contents is encrypted, so this walks the data area the same way rpf9_carve.py does: find every -zlib stream that inflates cleanly to its end, then classify the inflated bytes. It never decrypts, never writes -game data, and does not decode animation. - -Signatures are only the byte patterns measured in docs/animation.md. Anything else is reported as `raw:` -instead of being guessed. A `0DRP` page is reported with its version and page count; the tagged auxiliary table that starts a -`0DRP` second system page (historical label `clip-stream`) with its entry count, tags and payload end, and only -when its directory and payloads fit in the stream; `MoVE` with its version and size hint; `RBF0` with its first schema name; name tables with their first path and number of paths. - -Usage: - python -I anim_index.py [--start N] [--limit BYTES] [--quiet] - python -I anim_index.py [--quiet] - python -I anim_index.py --rigs - -`--rigs` additionally joins the RBF0 stream with its 64 KiB continuation blocks and writes the rig-set/rig entries -and plain `SKEL_` bone names to its own JSON. It stops at the next known container signature or a gap. -Usage: `python -I tools/anim_index.py --help` lists the options. -""" -import argparse -import bisect -import collections -import csv -import json -import mmap -import os -import re -import struct -import sys -import zlib - -ROOT = os.path.dirname(os.path.abspath(__file__)) -if ROOT not in sys.path: - sys.path.insert(0, ROOT) -from report_paths import same_report_path # noqa: E402 -from zero_span import gap_split # noqa: E402 - -# zlib stream start, or a Bink 2 video ('KB2' + revision letter). Kept in step with rpf9_carve.py. -ZHDR = re.compile(rb"\x78[\x01\x5e\x9c\xda]|KB2[a-z]") -PACK_NAMES = re.compile(rb"pack:/[^\x00]{1,200}") -SKEL_NAMES = re.compile(rb"(?:SKEL_|PH_)[A-Za-z0-9_]{1,100}") -COLUMNS = ["offset", "stored", "size", "signature", "version", "name", "count", "detail"] -RBF0_SOURCES = ("canonical@source", "generated@source", "pipelined@source", "canonical@legacy") -STOP_SIGNATURES = {"rbf0", "page-directory", "name-table", "move", "psin", "typehash", "clip-stream", - "skeleton-names", "bink2"} - - -def _u16(data, at): - return struct.unpack_from("= at + 2 else None - - -def _u32(data, at): - return struct.unpack_from("= at + 4 else None - - -def _u64(data, at): - return struct.unpack_from("= at + 8 else None - - -def _first_text(data, prefix): - start = data.find(prefix) - if start < 0: - return "" - end = data.find(b"\x00", start) - if end < 0: - end = min(len(data), start + 200) - return data[start:end].decode("ascii", "replace") - - -def _printable(data): - if not data: - return False - sample = data[:512] - good = sum(1 for b in sample if 32 <= b < 127 or b in (9, 10, 13)) - return len(sample) >= 64 and good / len(sample) > 0.9 - - -AUX_FIRST_TAG = 0x101 -AUX_COUNTS = (2, 3) - - -def aux_table(data): - """The tagged auxiliary table at the start of a `0DRP` resource's second system page (docs/animation.md): - a u32 count (2 or 3), then `count` pairs {u32 tag, u32 payloadBytes}, then the payloads in order; the first - tag is 0x101. Bytes after the payloads are legitimate (schema tables follow them). Returns - ([(tag, size), ...], payload_end) when the directory and every payload fit in `data`, else None, so a - matching prefix on truncated or unrelated bytes keeps its generic classification. Needs the whole - inflated stream, not a head slice.""" - count = _u32(data, 0) - if count not in AUX_COUNTS: - return None - directory_end = 4 + 8 * count - if len(data) < directory_end: - return None - entries = [struct.unpack_from(" len(data): - return None - return entries, payload_end - - -def classify(data, offset, stored): - """Return one record for an inflated stream. `offset` is its archive offset, `stored` its compressed size.""" - record = {"offset": offset, "stored": stored, "size": len(data), "signature": "raw", - "version": None, "name": "", "count": None, "detail": ""} - if data[:4] == b"MoVE": - record.update(signature="move", version=_u32(data, 4)) - hint = _u32(data, 0x14) - if hint is not None: - record["detail"] = f"size_hint={hint}" - elif data[:4] == b"PSIN": - record.update(signature="psin", detail="metadata container") - elif data[:4] == b"RBF0": - schema = re.search(rb"[\x20-\x7e]{4,120}", data[8:160]) - record.update(signature="rbf0", name=schema.group().decode("ascii", "replace") if schema else "", - detail="rig metadata") - elif data[:6] == b"pack:/": - names = PACK_NAMES.findall(data) - record.update(signature="name-table", name=_first_text(data, b"pack:/"), count=len(names), - detail="pack:/ paths") - elif data[:5] == b"SKEL_": - names = SKEL_NAMES.findall(data) - record.update(signature="skeleton-names", name=_first_text(data, b"SKEL_"), count=len(names), - detail="bone names") - elif len(data) >= 0x30 and data[16:20] == b"0DRP": - record.update(signature="page-directory", version=_u32(data, 0x14), count=_u64(data, 0x20), - detail="0DRP at +16") - elif (len(data) >= 16 and _u32(data, 4) == 8 and _u32(data, 12) == 0 - and 0 < (_u32(data, 8) or 0) <= 4096): - record.update(signature="typehash", version=8, count=_u32(data, 8), - detail=f"type=0x{_u32(data, 0):08x}") - elif (table := aux_table(data)) is not None: - # Historical label kept so existing consumers group these pages as before; the count is the measured - # entry count, not a version. - entries, payload_end = table - record.update(signature="clip-stream", count=len(entries), - detail=f"aux-table tags={','.join(f'0x{tag:x}' for tag, _ in entries)} " - f"payload_end={payload_end}") - elif data[:3] == b"KB2" and len(data) >= 0x20: - record.update(signature="bink2", version=chr(data[3]), count=_u32(data, 8)) - record["detail"] = f"{_u32(data, 0x14)}x{_u32(data, 0x18)}" - elif data[:8] == b"\x00" * 8: - record["signature"] = "zero-prefix" - elif _printable(data): - record["signature"] = "text" - else: - record["signature"] = "raw:" + data[:4].hex() - return record - - -def _u16_string(data, at): - """Short length-prefixed ASCII string, as used by RBF0 rig-set keys and schema names.""" - n = _u16(data, at) - if n is None or not 1 <= n <= 300: - return None - raw = data[at + 2:at + 2 + n] - if len(raw) != n or not raw or not all(32 <= c < 127 for c in raw): - return None - return raw.decode("ascii") - - -def _fd_string(data, at): - """`fd ff` + u32 length (including NUL) + ASCII value, as used by RBF0 rig fields.""" - if data[at:at + 2] != b"\xfd\xff": - return None - n = _u32(data, at + 2) - if n is None or not 1 <= n <= 300: - return None - raw = data[at + 6:at + 6 + n] - if raw.endswith(b"\x00"): - raw = raw[:-1] - if not raw or not all(32 <= c < 127 for c in raw): - return None - return raw.decode("ascii") - - -def joaat32(text): - """Jenkins one-at-a-time, lowercased, as used for animation path and bone name hashes.""" - h = 0 - for c in text.lower().encode("latin-1", "replace"): - h = (h + c) & 0xFFFFFFFF - h = (h + (h << 10)) & 0xFFFFFFFF - h ^= h >> 6 - h = (h + (h << 3)) & 0xFFFFFFFF - h ^= h >> 11 - return (h + (h << 15)) & 0xFFFFFFFF - - -def parse_skel_names(data, offset=0): - """Read the full bone names out of a plain `SKEL_` stream. Front-coded tables are not decoded.""" - names = [m.group().decode("ascii", "replace") for m in SKEL_NAMES.finditer(data)] - distinct = sorted(set(names)) - hashes = sum(1 for n in distinct if struct.pack("= len(rigs): - continue - rig_at, rig = rigs[j] - k = bisect.bisect_right(rigset_offsets, source_at) - 1 - if k < 0: - continue - end = sources[n + 1][0] if n + 1 < len(sources) else len(data) - group = "" - p = rig_at + 6 + len(rig) + 1 - while p < end: - candidate = _fd_string(data, p) - if candidate is not None: - if not candidate.startswith("anim/"): - group = candidate - break - p += 1 - rows[k]["entries"].append({"source": source, "rig": rig, "group": group, - "source_offset": source_at, "rig_offset": rig_at}) - for row in rows: - row["distinct_rigs"] = len({e["rig"] for e in row["entries"]}) - rig_names = {e["rig"] for row in rows for e in row["entries"]} - names = {row["key"] for row in rows} | rig_names - # Little-endian u32 at every byte offset (all four alignments), checked against the wanted hashes only. - wanted = {joaat32(n) for n in names} - found = set() - view = memoryview(data) - for a in range(4): - if found == wanted: - break - whole = a + (len(data) - a) // 4 * 4 - found.update(h for (h,) in struct.iter_unpack("= 8 * 1024 * 1024 or row["offset"] > previous_end + 16 or previous_size != MAX_CHUNK: - break - if row["signature"] in STOP_SIGNATURES or row["size"] > MAX_CHUNK: - break - blob += _inflate_row(archive, row) - previous_end = row["offset"] + row["stored"] - previous_size = row["size"] - return bytes(blob) - - -def collect_skeletons(archive, rows): - """Standalone `SKEL_` streams plus small resources (motion matchers) that embed bone tables.""" - out = [] - for row in rows: - if row["signature"] == "skeleton-names" or (row["size"] <= 16384 and row["signature"].startswith("raw:")): - data = _inflate_row(archive, row) - if b"SKEL_" in data or b"PH_" in data: - record = parse_skel_names(data, row["offset"]) - record["kind"] = ("plain-bone-table" if row["signature"] == "skeleton-names" - else ("motion-matcher" if b"motionmatcher" in data else "bone-table")) - if record["distinct"] or record["hashes_present"]: - out.append(record) - return out - - -def collect_skeletons_dir(path): - out = [] - for name in sorted(os.listdir(path)): - full = os.path.join(path, name) - if not os.path.isfile(full) or name.lower().endswith((".json", ".csv")): - continue - size = os.path.getsize(full) - with open(full, "rb") as f: - head = f.read(5) - if size > 16384 and head != b"SKEL_": - continue - data = head + f.read() - m = re.match(r"([0-9a-fA-F]{6,})", name) - offset = int(m.group(1), 16) if m else 0 - sig = classify(data, offset, len(data))["signature"] - if not (sig == "skeleton-names" or (size <= 16384 and sig.startswith("raw:"))): - continue - if b"SKEL_" in data or b"PH_" in data: - record = parse_skel_names(data, offset) - record["kind"] = ("plain-bone-table" if sig == "skeleton-names" - else ("motion-matcher" if b"motionmatcher" in data else "bone-table")) - if record["distinct"] or record["hashes_present"]: - out.append(record) - return out - - -def collect_rbf0_dir(path): - """The same continuation rule for a carved directory sorted by offset.""" - entries = [] - for name in sorted(os.listdir(path)): - full = os.path.join(path, name) - if not os.path.isfile(full) or name.lower().endswith((".json", ".csv")): - continue - m = re.match(r"([0-9a-fA-F]{6,})", name) - offset = int(m.group(1), 16) if m else len(entries) - with open(full, "rb") as f: - entries.append((offset, name, f.read())) - entries.sort(key=lambda e: e[0]) - first = next((i for i, (_, _, data) in enumerate(entries) if data[:4] == b"RBF0"), None) - if first is None: - return None - blob = bytearray(entries[first][2]) - previous_end = entries[first][0] + len(entries[first][2]) - previous_size = len(entries[first][2]) - for offset, _, data in entries[first + 1:]: - if previous_size != MAX_CHUNK: - break - sign = classify(data, offset, len(data))["signature"] - if len(blob) >= 8 * 1024 * 1024 or offset > previous_end + 16 or sign in STOP_SIGNATURES or len(data) > MAX_CHUNK: - break - blob += data - previous_end = offset + len(data) - previous_size = len(data) - return bytes(blob) - - - -def scan_rpf(path, start=None, limit=None, progress=None): - """Walk an RPF9 data area. Returns (records, summary). No tables of contents are read or decrypted.""" - rows = [] - if os.path.getsize(path) == 0: - raise ValueError("empty file") - with open(path, "rb") as fh, mmap.mmap(fh.fileno(), 0, access=mmap.ACCESS_READ) as m: - size = len(m) - if size < 8: - raise ValueError("truncated RPF9 header") - if m[:4] not in (b"9FPR", b"RPF9"): - raise ValueError("not an RPF9 archive") - first = struct.unpack_from("/index.json as the carve manifest. - if same_report_path(manifest, path): - ap.error(f"{flag} would overwrite the carve manifest: {path}") - if os.path.isfile(path): - for name in os.listdir(a.source): - inp = os.path.join(a.source, name) - if os.path.isfile(inp) and not name.lower().endswith((".json", ".csv")): - if same_report_path(inp, path): - ap.error(f"{flag} would overwrite an input file: {path}") - if os.path.splitext(a.out)[1].lower() not in (".json", ".csv"): - ap.error("output must end in .json or .csv") - if a.rigs and os.path.splitext(a.rigs)[1].lower() != ".json": - ap.error("--rigs must end in .json") - for flag, path in (("output", a.out), ("--rigs", a.rigs)): - if not path: - continue - folder = os.path.dirname(os.path.abspath(path)) - if not os.path.isdir(folder): - sys.exit(f"{path}: cannot write: folder does not exist: {folder}") - try: - if os.path.isdir(a.source): - if a.start is not None or a.limit is not None: - print("--start and --limit are only supported for archive files", file=sys.stderr) - return 2 - rows, summary = scan_dir(a.source) - else: - def progress(n, pos, end): - if not a.quiet: - print(f"[{pos / max(1, end):6.1%}] {n} streams", flush=True) - rows, summary = scan_rpf(a.source, a.start, a.limit, progress) - except ValueError as e: - sys.exit(f"{a.source}: {e}") - except OSError as e: # missing, a folder that can't be listed, a file that can't be read - sys.exit(f"{e.filename or a.source}: {e.strerror or e}") - try: - write_output(a.out, rows, summary) - except OSError as e: - sys.exit(f"{a.out}: cannot write: {e.strerror or e}") - if a.rigs: - if os.path.isdir(a.source): - blob = collect_rbf0_dir(a.source) - skeletons = collect_skeletons_dir(a.source) - else: - blob = collect_rbf0(a.source, rows) - skeletons = collect_skeletons(a.source, rows) - if blob is None: - print("no RBF0 stream found; --rigs needs the archive or carved folder that contains it", file=sys.stderr) - return 2 - try: - rbf0 = parse_rbf0(blob) - except ValueError as e: - # Parse before opening --rigs, so a failed parse leaves an existing file as it was. - print(f"{a.source}: RBF0 stream: {e}", file=sys.stderr) - return 2 - try: - with open(a.rigs, "w", encoding="utf-8", newline="\n") as f: - json.dump({"rbf0": rbf0, "skeletons": skeletons}, f, indent=1) - except OSError as e: - sys.exit(f"{a.rigs}: cannot write: {e.strerror or e}") - top = dict(sorted(summary["signatures"].items(), key=lambda kv: -kv[1]["files"])[:15]) - print(json.dumps({k: summary[k] for k in - ("files", "compressed_bytes", "inflated_bytes", "zero_padding", "unread_bytes", - "span", "readable_fraction", "bink2_files")}, indent=1)) - print(f"{len(summary['signatures'])} signature classes; top 15:") - for name, counts in top.items(): - print(f" {name:24} {counts['files']:6} files {counts['stored']:12} stored {counts['inflated']:12} inflated") - return 0 - - -if __name__ == "__main__": - try: # a redirected stdout is strict ANSI code page under -I; write '?' for what it cannot encode - sys.stdout.reconfigure(errors="replace") - except (AttributeError, ValueError, OSError): - pass - sys.exit(main()) diff --git a/tools/anim_move.py b/tools/anim_move.py deleted file mode 100644 index dea276b2d..000000000 --- a/tools/anim_move.py +++ /dev/null @@ -1,659 +0,0 @@ -"""Decode the MoVE (version 19) state-machine and motion-tree containers in anim.rpf (ASSET-86). - - python -I tools/anim_move.py \\anim.rpf \\anim-move.json - -Each MoVE resource has a fixed 32-byte header (`MoVE`, u32 version = 19, three zero u32s, u32 network hash at -+0x14, u32 body_size at +0x18, one zero u32 at +0x1C), followed at +0x20 by a variable preamble: - - u32 N_req + N_req × u32 request hashes - - u32 N_flag + N_flag × u32 flag hashes - - u32 preamble_mode (0, 1 or 2) - - u32 N_desc + N_desc × 5-byte `{u32 hash; u8 kind}` descriptors - - 10-byte tail `{u16 sub_flag; u32 ref_hash_0; u32 ref_hash_1}` (zero when preamble_mode is 0 or 1) - -`body_size` at +0x18 excludes the 46 fixed/count/tail preamble bytes outside it and the `5 * N_desc` descriptor -table, so every complete MoVE v19 resource satisfies: - - total_bytes == 46 + 5 * N_desc + body_size - -One resource in anim.rpf (at 0x105a7d000, 71,099 bytes) exceeds RPF9's 64 KiB stream ceiling and spans two -consecutive 16-byte-aligned zlib streams (65,536 + 5,563 bytes). After the 10-byte preamble tail sits the root -state container (`Type 1` = StateMachine, `Type 3` = InlinedStateMachine, `Type 22` = MotionTree), whose child -states, transitions and length-prefixed parameter blocks recurse through signed 32-bit self-relative offsets. -Usage: `python -I tools/anim_move.py --help` lists the options. -""" -import argparse -import collections -import json -import os -import re -import struct -import sys -import tempfile -import zlib - -sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) -import anim_index # noqa: E402 -from file_mode import published_mode # noqa: E402 -from replace_retry import replace as replace_retry # noqa: E402 -from report_paths import same_report_path # noqa: E402 - -MAGIC = b"MoVE" -VERSION = 19 -TYPE_STATE_MACHINE = 1 -TYPE_INLINED_STATE_MACHINE = 3 -TYPE_MOTION_TREE = 22 -CONTAINER_TYPES = { - TYPE_STATE_MACHINE: "state_machine", - TYPE_INLINED_STATE_MACHINE: "inlined_state_machine", - TYPE_MOTION_TREE: "motion_tree", -} -KNOWN_SCHEMA_HASHES = { - anim_index.joaat32("statemachine"): "statemachine", - anim_index.joaat32("motiontree"): "motiontree", -} -MAX_STANDALONE_FILE_BYTES = 128 * 1024 * 1024 - - -class DecodeError(ValueError): - pass - - -def is_move_container(data): - return len(data) >= 32 and data[:4] == MAGIC - - -def expected_total_size(data): - """Return `46 + 5 * N_desc + body_size` once the preamble up to `N_desc` is available, or None if truncated.""" - if not is_move_container(data) or len(data) < 48: - return None - body_size = struct.unpack_from(" len(data): - return None - n_flag = struct.unpack_from(" len(data): - return None - n_desc = struct.unpack_from("= 0x4C`).""" - if start < 0 or end < start or end > len(data): - raise DecodeError(f"transition span 0x{start:x}..0x{end:x} outside resource") - out, p = [], start - for _ in range(count): - if p + 0x4C > end: - raise DecodeError(f"truncated transition header at 0x{p:x}") - tr_size = struct.unpack_from(" end: - raise DecodeError(f"invalid transition size 0x{tr_size:x} at 0x{p:x}") - target_rel = struct.unpack_from("= 0x50 else 0 - out.append({ - "offset": p, - "size": tr_size, - "target": p + 0x48 + target_rel, - "condition_kind": cond_kind, - "condition_bytes": max(0, tr_size - 0x50), - }) - p += tr_size - if p != end: - raise DecodeError(f"transition block at 0x{start:x} ended at 0x{p:x}, expected 0x{end:x}") - return out - - -def _parse_default_transitions(data, start, end, count): - """Parse `count` default/any-state transitions in `data[start:end]`: `{u16 size; u16 cond_count; i32 target_rel}`.""" - if start < 0 or end < start or end > len(data): - raise DecodeError(f"default-transition span 0x{start:x}..0x{end:x} outside resource") - out, p = [], start - for _ in range(count): - if p + 16 > end: - raise DecodeError(f"truncated default transition at 0x{p:x}") - size, cond_count, target_rel = struct.unpack_from(" end: - raise DecodeError(f"invalid default-transition size {size} at 0x{p:x}") - out.append({ - "offset": p, - "size": size, - "conditions": cond_count, - "target": p + 4 + target_rel, - }) - p += size - if p != end: - raise DecodeError(f"default-transition block at 0x{start:x} ended at 0x{p:x}, expected 0x{end:x}") - return out - - -def _parse_param_blocks(data, start, end_limit, count): - """Parse `count` length-prefixed MotionTree parameter blocks starting at `start`. - - Every block satisfies: - block_size == 12 + 16 * (b1 + b2 + b3 + b4) + 8 * b5 + sum(sub_size for _ in range(b6)) - with `b7 == 0`. Returns `(blocks, end_offset)`. - """ - if start < 0 or start > end_limit: - raise DecodeError(f"parameter block start 0x{start:x} outside container") - blocks, p = [], start - for _ in range(count): - if p + 12 > end_limit: - raise DecodeError(f"truncated parameter block header at 0x{p:x}") - bsz = struct.unpack_from(" end_limit: - raise DecodeError(f"invalid parameter block size {bsz} at 0x{p:x}") - b0, b1, b2, b3, b4, b5, b6, b7 = data[p + 4:p + 12] - if b7 != 0: - raise DecodeError(f"non-zero parameter block reserved byte b7={b7} at 0x{p:x}") - n16 = b1 + b2 + b3 + b4 - q = p + 12 + 16 * n16 + 8 * b5 - if q > p + bsz: - raise DecodeError(f"parameter block table overflow at 0x{p:x}") - sub_sizes = [] - for _ in range(b6): - if q + 6 > p + bsz: - raise DecodeError(f"truncated curve sub-record at 0x{q:x}") - sub_sz = struct.unpack_from(" p + bsz: - raise DecodeError(f"invalid curve sub-record size {sub_sz} at 0x{q:x}") - sub_sizes.append(sub_sz) - q += sub_sz - if q != p + bsz: - raise DecodeError(f"parameter block size mismatch at 0x{p:x}: walked {q - p}, header {bsz}") - blocks.append({ - "offset": p, - "size": bsz, - "index": b0, - "bindings_16b": n16, - "binding_counts": (b1, b2, b3, b4), - "outputs_8b": b5, - "curves": b6, - "curve_bytes": sum(sub_sizes), - }) - p += bsz - return blocks, p - - -def _parse_container(data, off, end_limit, stats): - """Recursively decode a `Type 1` (`StateMachine`), `Type 3` (`InlinedStateMachine`), or `Type 22` (`MotionTree`).""" - if off + 0x24 > end_limit or end_limit > len(data): - raise DecodeError(f"truncated state container at 0x{off:x}") - (ntype, nidx, name_hash, init_rel, flags_0c, - b10, b11, n_children, n_transitions) = struct.unpack_from(" end_limit: - raise DecodeError(f"truncated {kind} header at 0x{off:x}") - tr_rel = struct.unpack_from(" end_limit: - raise DecodeError(f"truncated inlined_state_machine input table at 0x{off:x}") - for i in range(n_inputs): - ipos = off + 0x5C + 4 * i - inp_target = ipos + struct.unpack_from(" 0 else child_table_end - if n_transitions > 0 and tr_start != child_table_end: - raise DecodeError( - f"{kind} at 0x{off:x}: transition start 0x{tr_start:x} != child table end 0x{child_table_end:x}" - ) - child_entries = [] - for i in range(n_children): - epos = child_table_off + 8 * i - ch_hash, ch_rel = struct.unpack_from(" end_limit: - raise DecodeError(f"truncated motion_tree header at 0x{off:x}") - tr_rel, blk_rel, n_param_blocks = struct.unpack_from(" len(data): - raise DecodeError("truncated MoVE preamble at request count") - n_req = struct.unpack_from(" len(data): - raise DecodeError("truncated MoVE request table") - requests = list(struct.unpack_from(f"<{n_req}I", data, pos)) if n_req else [] - pos += 4 * n_req - n_flag = struct.unpack_from(" len(data): - raise DecodeError("truncated MoVE flag table") - flags = list(struct.unpack_from(f"<{n_flag}I", data, pos)) if n_flag else [] - pos += 4 * n_flag - preamble_mode, n_desc = struct.unpack_from("<2I", data, pos) - pos += 8 - if preamble_mode not in (0, 1, 2): - raise DecodeError(f"unexpected MoVE preamble_mode {preamble_mode}") - if pos + 5 * n_desc + 10 > len(data): - raise DecodeError("truncated MoVE 5-byte descriptor table or 10-byte preamble tail") - descriptors = [] - for _ in range(n_desc): - h, kind = struct.unpack_from(" MAX_STANDALONE_FILE_BYTES: - continue - m = re.search(r"0x([0-9a-fA-F]+)|([0-9a-fA-F]{6,})", name) - offset = int(m.group(1) or m.group(2), 16) if m else len(entries) - with open(full, "rb") as fh: - data = fh.read() - entries.append((offset, name, data)) - entries.sort(key=lambda e: (e[0], e[1])) - items = [] - i = 0 - while i < len(entries): - offset, _name, data = entries[i] - if not is_move_container(data): - i += 1 - continue - blob = bytearray(data) - stream_count = 1 - want = expected_total_size(blob) - j = i + 1 - while (want is not None and len(blob) < want and j < len(entries) - and len(entries[j - 1][2]) == anim_index.MAX_CHUNK - and not is_move_container(entries[j][2])): - blob += entries[j][2] - stream_count += 1 - j += 1 - items.append((offset, stream_count, len(blob), bytes(blob))) - i = j - return items, len(entries) - - -def scan(path, start=None, limit=None): - """Scan an RPF9 archive or a directory of carved streams and decode every MoVE v19 container.""" - if os.path.isdir(path): - if start is not None or limit is not None: - raise ValueError("--start and --limit apply only to an RPF archive") - raw_items, total_streams = _collect_move_streams_dir(path) - else: - raw_items, total_streams = _collect_move_streams_rpf(path, start, limit) - - stats = collections.Counter() - resources = [] - total_stored = 0 - total_inflated = 0 - total_move_streams = 0 - for offset, stream_count, stored_bytes, blob in raw_items: - total_stored += stored_bytes - total_inflated += len(blob) - total_move_streams += stream_count - try: - parsed = parse_move(blob) - except (DecodeError, struct.error) as e: - stats["move_resources_unparsed"] += 1 - resources.append({ - "offset": offset, - "streams": stream_count, - "stored_bytes": stored_bytes, - "bytes": len(blob), - "error": str(e)[:160], - }) - continue - parsed["offset"] = offset - parsed["streams"] = stream_count - parsed["stored_bytes"] = stored_bytes - resources.append(parsed) - - stats["move_resources"] += 1 - stats["move_streams"] += stream_count - if stream_count > 1: - stats["multi_stream_resources"] += 1 - stats[f"version:{parsed['version']}"] += 1 - p = parsed["preamble"] - stats[f"preamble_mode:{p['mode']}"] += 1 - if p["requests"]: - stats["resources_with_requests"] += 1 - stats["requests"] += len(p["requests"]) - if p["flags"]: - stats["resources_with_flags"] += 1 - stats["flags"] += len(p["flags"]) - if p["descriptors_5b"]: - stats["resources_with_descriptors_5b"] += 1 - stats["descriptors_5b"] += len(p["descriptors_5b"]) - for d in p["descriptors_5b"]: - stats[f"descriptor_5b_kind:{d['kind']}"] += 1 - root = parsed["root"] - stats[f"root_container:{root['kind']}"] += 1 - for k, v in parsed["counts"].items(): - stats[k] += v - - summary = { - "streams": total_streams, - "move_resources": len(raw_items), - "move_streams": total_move_streams, - "stored_bytes": total_stored, - "inflated_bytes": total_inflated, - "counts": dict(sorted(stats.items())), - } - return resources, summary - - -def _summary_row(r): - """Build a game-data-free summary row for JSON output (counts and structural metadata only, no raw hash arrays).""" - if "error" in r: - return r - p = r["preamble"] - root = r["root"] - c = r["counts"] - return { - "offset": r["offset"], - "streams": r["streams"], - "stored_bytes": r["stored_bytes"], - "bytes": r["bytes"], - "version": r["version"], - "body_size": r["body_size"], - "node_start": r["node_start"], - "graph_bytes": r["graph_bytes"], - "preamble_mode": p["mode"], - "requests": len(p["requests"]), - "flags": len(p["flags"]), - "descriptors_5b": len(p["descriptors_5b"]), - "root_type": root["type"], - "root_kind": root["kind"], - "containers": c.get("containers", 0), - "state_machines": c.get("container:state_machine", 0), - "inlined_state_machines": c.get("container:inlined_state_machine", 0), - "motion_trees": c.get("container:motion_tree", 0), - "transitions": c.get("transitions", 0), - "default_transitions": c.get("default_transitions", 0), - "param_blocks": c.get("param_blocks", 0), - } - - -def _write_json_atomic(path, doc): - """Publish complete JSON, or leave the previous report intact on replace failure.""" - destination = os.path.abspath(path) - parent = os.path.dirname(destination) or "." - os.makedirs(parent, exist_ok=True) - try: - mode = os.stat(destination).st_mode - except FileNotFoundError: - mode = None - except OSError: - # Non-regular destinations (pipes/devices) keep a direct write. - with open(destination, "w", encoding="utf-8", newline="\n") as f: - json.dump(doc, f, indent=1) - return - if mode is not None: - # Retain the direct writer's permission check without truncating the report. - os.close(os.open(destination, os.O_WRONLY)) - - staged = tempfile.NamedTemporaryFile( - mode="w", encoding="utf-8", newline="\n", delete=False, - dir=parent, prefix=".anim_move_", suffix=".tmp", - ) - try: - with staged: - json.dump(doc, staged, indent=1) - if os.name != "nt": - os.chmod(staged.name, published_mode(destination)) - replace_retry(staged.name, destination) - finally: - try: - os.unlink(staged.name) - except FileNotFoundError: - pass - - -def main(argv=None): - ap = argparse.ArgumentParser(description=__doc__.splitlines()[0]) - ap.add_argument("archive", help="anim.rpf or a directory of carved MoVE streams") - ap.add_argument("out", help="output .json (counts and one row per MoVE resource)") - ap.add_argument("--start", type=anim_index.offset, help="first byte to scan (default: the RPF data start)") - ap.add_argument("--limit", type=anim_index.byte_count, help="number of bytes to scan") - a = ap.parse_args(argv) - if not os.path.exists(a.archive): - sys.exit(f"{a.archive}: No such file or directory") - if os.path.isdir(a.archive) and (a.start is not None or a.limit is not None): - ap.error("--start and --limit cannot be used when the input is a directory") - if os.path.isdir(a.out): - sys.exit(f"{a.out}: cannot write: Is a directory") - inputs = [full for _name, full in _iter_dir_stream_paths(a.archive)] if os.path.isdir(a.archive) else [a.archive] - if any(same_report_path(path, a.out) for path in inputs): - sys.exit(f"{a.out}: refuses to overwrite the input archive") - try: - resources, summary = scan(a.archive, a.start, a.limit) - except ValueError as e: - sys.exit(f"{a.archive}: {e}") - except OSError as e: - sys.exit(f"{e.filename or a.archive}: {e.strerror or e}") - rows = [_summary_row(r) for r in resources] - try: - _write_json_atomic(a.out, {"summary": summary, "move_resources": rows}) - except OSError as e: - sys.exit(f"{a.out}: cannot write: {e.strerror or e}") - c = summary["counts"] - print(json.dumps({ - k: c.get(k, 0) - for k in ( - "move_resources", - "move_streams", - "multi_stream_resources", - "containers", - "container:state_machine", - "container:inlined_state_machine", - "container:motion_tree", - "transitions", - "default_transitions", - "param_blocks", - ) - })) - return 0 - - -if __name__ == "__main__": - try: # a redirected stdout is strict ANSI code page under -I; write '?' for what it cannot encode - sys.stdout.reconfigure(errors="replace") - except (AttributeError, ValueError, OSError): - pass - sys.exit(main()) diff --git a/tools/anim_rigs.py b/tools/anim_rigs.py deleted file mode 100644 index f48aa77fe..000000000 --- a/tools/anim_rigs.py +++ /dev/null @@ -1,194 +0,0 @@ -"""Read the rig dictionaries in anim.rpf and join the RBF0 rig-set manager's entries to them (ASSET-20). - - python -I tools/anim_rigs.py \\anim.rpf \\anim-rigs.json [--rigs \\rigs.json] - -A rig dictionary has the clip dictionary's root layout (docs/animation.md, "Clip dictionaries are RAGE -resources") with `RIG` + a version byte at +0x70 instead of the pack array. Its map is keyed by `joaat32` of a rig -path. Each value points at +0x20 to a `RIG` block, which holds tables of 8-byte `(hash, word)` items. `--rigs` -takes the JSON `anim_index.py --rigs` writes and resolves every rig-set entry (source = rig dictionary name, -rig = key). The output holds counts and one row per rig dictionary, no item values. -Usage: `python -I tools/anim_rigs.py --help` lists the options. -""" -import argparse -import collections -import json -import mmap -import os -import struct -import sys -import zlib - -# -I keeps the script directory off sys.path, so add it explicitly before importing the sibling module. -sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) -from report_paths import same_report_path # noqa: E402 - -sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) -import anim_clips # noqa: E402 -import anim_index # noqa: E402 - -SYSTEM = anim_clips.SYSTEM -MAGIC = b"RIG" - - -def is_rig_dictionary(data): - return len(data) >= 0x78 and data[0x70:0x73] == MAGIC - - -def block_tables(s, at): - """Tables of a `RIG` block at page offset `at`: `RIG` + u8 version, u32 length of what follows, then tables - `{u32 kind hash; u32 size = 0xC + 8 * count; u32 count; u32 word}` + count × `{u32 hash; u32 word}`, with other - bytes between them. Returns (version, length, [(kind, count)]).""" - if s.d[at:at + 3] != MAGIC: - raise anim_clips.DecodeError(f"no RIG block at 0x{at:x}") - if at + 8 > len(s.d): - raise anim_clips.DecodeError(f"truncated RIG block at 0x{at:x}") - version, length = s.d[at + 3], s.u32(at + 4) - end = min(len(s.d), at + 8 + length) - o, tables = at + 8, [] - while o + 16 <= end: - kind, size, count, _word = struct.unpack_from("<4I", s.d, o) - if 0 < count < 4096 and size == 0xC + 8 * count and o + 16 + 8 * count <= end: - tables.append((kind, count)) - o += 16 + 8 * count - else: - o += 4 - return version, length, tables - - -def parse_rig_dictionary(s): - """Root: +0x38 name, +0x48 map (key = joaat32(rig path), high half 0), +0x68 joaat32(name), +0x70 `RIG`.""" - d = {"name": s.string(0x38), "hash": s.u32(0x68), "version": s.d[0x73], "entries": []} - for key, value in s.atmap(0x48): - if value is None: - continue - block = s.ptr(value + 0x20) - e = {"key": key & 0xFFFFFFFF, "key_high": key >> 32, "block": block} - if block is not None: - e["block_version"], e["block_length"], e["tables"] = block_tables(s, block) - d["entries"].append(e) - return d - - -def _read(path, segments): - with open(path, "rb") as fh: - data = b"" - for off, stored, raw in segments: - fh.seek(off) - data += fh.read(stored) if raw else zlib.decompressobj().decompress(fh.read(stored)) - return data - - -def scan(path, start=None, limit=None): - rows, walk = anim_index.scan_rpf(path, start, limit) - with open(path, "rb") as fh, mmap.mmap(fh.fileno(), 0, access=mmap.ACCESS_READ) as m: - groups, _unresolved, _gaps = anim_clips.group(m, rows) - stats, dicts = collections.Counter(), [] - for _i, parts in groups: - segments = [anim_clips.segment(rows, k) for k in parts] - with open(path, "rb") as fh: - fh.seek(segments[0][0]) - head = fh.read(segments[0][1]) - first = head if segments[0][2] else zlib.decompressobj().decompress(head, 0x80) - if not is_rig_dictionary(first): - continue - s = anim_clips.System(_read(path, segments)) - try: - d = parse_rig_dictionary(s) - except (anim_clips.DecodeError, struct.error) as e: - stats["rig_dictionaries_unparsed"] += 1 - dicts.append({"offset": segments[0][0], "error": str(e)[:120]}) - continue - d["offset"], d["streams"], d["system_bytes"] = segments[0][0], len(segments), len(s.d) - dicts.append(d) - stats["rig_dictionaries"] += 1 - stats["rig_dictionary_hash_matches_name"] += d["name"] is not None and anim_index.joaat32(d["name"]) == d["hash"] - stats[f"rig_dictionary_version:{d['version']}"] += 1 - for e in d["entries"]: - stats["entries"] += 1 - stats["entries_key_high_zero"] += e["key_high"] == 0 - if e["block"] is None: - stats["entries_without_block"] += 1 - continue - stats["entries_with_block"] += 1 - stats[f"block_version:{e['block_version']}"] += 1 - stats["tables"] += len(e["tables"]) - for kind, count in e["tables"]: - stats[f"table_kind:0x{kind:08x}"] += 1 - stats[f"table_items:0x{kind:08x}"] += count - return dicts, {"streams": walk["files"], "dictionary_roots": len(groups), "counts": dict(sorted(stats.items()))} - - -def join_rbf0(dicts, rigs): - """Resolve the rig-set manager's entries: source = rig dictionary name, joaat32(rig) = a key there.""" - keys: collections.defaultdict[str, set[int]] = collections.defaultdict(set) - for dictionary in dicts: - if name := dictionary.get("name"): - keys[name].update(entry["key"] for entry in dictionary.get("entries", ())) - entries = [e for rs in rigs["rbf0"]["rigsets"] for e in rs["entries"]] - c = collections.Counter() - for e in entries: - h = anim_index.joaat32(e["rig"].lower()) - if h in keys.get(e["source"], ()): - c["resolved"] += 1 - elif any(h in k for k in keys.values()): - c["in_another_dictionary"] += 1 - elif e["source"] not in keys: - c["no_dictionary_named_source"] += 1 - else: - c["key_missing"] += 1 - distinct = {(e["source"], e["rig"].lower()) for e in entries} - used = {(src, anim_index.joaat32(r)) for src, r in distinct} - c["distinct_rigs"] = len(distinct) - c["keys"] = sum(len(k) for k in keys.values()) - c["keys_named_by_an_entry"] = sum(1 for name, k in keys.items() for h in k if (name, h) in used) - return dict(sorted(c.items())) - - -def main(): - ap = argparse.ArgumentParser(description=__doc__.splitlines()[0]) - ap.add_argument("archive", help="anim.rpf") - ap.add_argument("out", help="output .json (counts and one row per rig dictionary)") - ap.add_argument("--rigs", help="the JSON anim_index.py --rigs wrote, to resolve the RBF0 entries") - ap.add_argument("--start", type=anim_index.offset, help="first byte to scan (default: the RPF data start)") - ap.add_argument("--limit", type=anim_index.byte_count, help="number of bytes to scan") - a = ap.parse_args() - if os.path.isdir(a.out): - ap.error(f"{a.out} is a folder, not a file") - if same_report_path(a.out, a.archive): - ap.error(f"{a.out} would overwrite the input archive") - if a.rigs and same_report_path(a.out, a.rigs): - ap.error(f"{a.out} would overwrite the --rigs input") - try: - dicts, summary = scan(a.archive, a.start, a.limit) - except ValueError as e: - sys.exit(f"{a.archive}: {e}") - except OSError as e: - sys.exit(f"{e.filename or a.archive}: {e.strerror or e}") - if a.rigs: - try: - with open(a.rigs, encoding="utf-8-sig") as f: - summary["rbf0_join"] = join_rbf0(dicts, json.load(f)) - except (OSError, ValueError, KeyError, TypeError, AttributeError) as e: - print(f"ERROR: {a.rigs}: invalid rig report ({getattr(e, 'strerror', None) or e})", file=sys.stderr) - return 2 - rows = [{k: v for k, v in d.items() if k != "entries"} | {"entries": len(d.get("entries", ()))} for d in dicts] - try: - os.makedirs(os.path.dirname(os.path.abspath(a.out)), exist_ok=True) - with open(a.out, "w", encoding="utf-8", newline="\n") as f: - json.dump({"summary": summary, "rig_dictionaries": rows}, f, indent=1) - except OSError as e: - print(f"ERROR: cannot write {a.out}: {e.strerror or e}", file=sys.stderr) - return 2 - c = summary["counts"] - print(json.dumps({k: c.get(k, 0) for k in ("rig_dictionaries", "entries", "entries_with_block", "tables")})) - if "rbf0_join" in summary: - print(json.dumps(summary["rbf0_join"])) - return 0 - - -if __name__ == "__main__": - try: # a redirected stdout is strict ANSI code page under -I; write '?' for what it cannot encode - sys.stdout.reconfigure(errors="replace") - except (AttributeError, ValueError, OSError): - pass - sys.exit(main()) diff --git a/tools/anim_skel_match.py b/tools/anim_skel_match.py deleted file mode 100644 index 6800c3b8f..000000000 --- a/tools/anim_skel_match.py +++ /dev/null @@ -1,174 +0,0 @@ -"""Match the bone names in anim.rpf's bone-table streams against the skeletons of packs.rpf (ASSET-231). - -docs/animation.md ("Bone tables and motion matchers") lists four small anim.rpf streams that carry full `SKEL_*` / -`PH_*` bone names: a standalone 896-byte name list and three motion-matcher resources. Those pages carry no model -name, so which skeleton they belong to was not measured. A skeleton does carry its names: each bone record holds -`joaat32(lowercased name)` at +0x1C and a name pointer at +0x30 (docs/character_skeleton.md, read by -`anim_glb.read_skeleton`). This tool reads the names out of the four streams (`anim_index.parse_skel_names`), reads -every skeleton that `anim_glb` can read in packs.rpf (drawables, drawable-dictionary children and fragments, the -resource walk of `skin_streams`), and reports per stream and for their union: - -- how many names have their `joaat32` among the joints of some skeleton, and whether the joint's own name string - is the same spelling; -- how many distinct skeletons (by their ordered joint-hash list) and how many skeleton copies hold every name; -- the joint counts of the skeletons that hold every name of the union. - -Only counts and joint counts are printed; no bone list or game bytes are written. - -Usage: - python -I tools/anim_skel_match.py [--stream OFFSET ...] [--json out.json] - -The default streams are the four offsets in docs/animation.md (1.0.2.1 package). Exit 0 when the report was -written, 2 on a read error. Nothing here decrypts anything. -Usage: `python -I tools/anim_skel_match.py --help` lists the options. -""" -import argparse -import collections -import json -import mmap -import os -import sys - -HERE = os.path.dirname(os.path.abspath(__file__)) -sys.dont_write_bytecode = True -if HERE not in sys.path: - sys.path.insert(0, HERE) - -import anim_index # noqa: E402 -from report_paths import same_report_path # noqa: E402 - -DEFAULT_STREAMS = (0x101A32160, 0x101C379A0, 0x101C41D50, 0x101EA66C0) - - -def match(names_by_stream, skeletons): - """names_by_stream: {label: [bone name]}; skeletons: [{"hashes": [u32], "names": [str or None]}]. - - Returns the report described in the module docstring (a JSON-ready dict).""" - union = sorted(set().union(*names_by_stream.values())) if names_by_stream else [] - hashes = {n: anim_index.joaat32(n.lower()) for n in union} - distinct = collections.Counter(tuple(s["hashes"]) for s in skeletons) - spellings = collections.defaultdict(set) - for s in skeletons: - for h, name in zip(s["hashes"], s["names"]): - if name: - spellings[h].add(name) - every_hash = set(spellings) | {h for s in skeletons for h in s["hashes"]} - joint_sets = [(set(k), len(k), copies) for k, copies in distinct.items()] - - def holding(names): - want = {hashes[n] for n in names} - rows = [(size, copies) for joints, size, copies in joint_sets if want <= joints] - return {"distinct": len(rows), "copies": sum(c for _, c in rows), "joint_counts": sorted({s for s, _ in rows})} - - def summary(names): - found = [n for n in names if hashes[n] in every_hash] - return {"names": len(names), "in_a_skeleton": len(found), - "same_spelling": sum(1 for n in found if n in spellings[hashes[n]]), - "joint_unnamed": sum(1 for n in found if not spellings[hashes[n]]), - "held_by_skeletons": holding(names)} - - return {"skeletons": len(skeletons), "distinct_skeletons": len(distinct), - "streams": {label: summary(sorted(set(names))) for label, names in names_by_stream.items()}, - "union": summary(union), - "not_in_any_skeleton": sum(1 for n in union if hashes[n] not in every_hash)} - - -def stream_names(anim_path, offsets): - """{"0x...": [bone name]} for each stream offset of anim.rpf.""" - import skin_streams - out = {} - with open(anim_path, "rb") as fh, mmap.mmap(fh.fileno(), 0, access=mmap.ACCESS_READ) as m: - for off in offsets: - data, _used = skin_streams.inflate_at(m, off, len(m)) - if data is None: - raise ValueError(f"no zlib stream at 0x{off:x} in {anim_path}") - out[f"0x{off:x}"] = anim_index.parse_skel_names(data, off)["names"] - return out - - -def read_skeletons(packs_path, progress=None): - """Every skeleton anim_glb reads in the archive: [{"hashes": [...], "names": [...]}].""" - import anim_glb - import skin_streams as ss - found = [] - size = os.path.getsize(packs_path) - with open(packs_path, "rb") as fh, mmap.mmap(fh.fileno(), 0, access=mmap.ACCESS_READ) as m: - pos = 0 - while pos < size: - page = (pos + ss.PAGE - 1) & ~(ss.PAGE - 1) - at, pos = page + 16, page + ss.PAGE - if at + 2 > size: - break - if m[at - 16:at] != b"\0" * 16 or not ss.ZHDR.match(m, at): - continue - data, _used = ss.inflate_at(m, at, size) - if data is None or len(data) < 192: - continue - kind = ss.resource_kind(data) - if kind is None: - continue - try: - system, _graphics = anim_glb.load_resource(m, at) - drawables = list(ss.drawable_offsets(system, kind)) - except (anim_glb.ExportError, ss.Skip, IndexError, ValueError): - continue - for drawable in drawables: - try: - joints, _worst = anim_glb.read_skeleton(system, drawable) - except (anim_glb.ExportError, IndexError, ValueError): - continue - found.append({"hashes": [j["hash"] for j in joints], "names": [j["name"] for j in joints]}) - if progress and found and len(found) % 2000 == 0: - progress(f" {len(found)} skeletons by 0x{page:x}") - return found - - -def print_report(report): - print(f"{report['skeletons']} skeletons, {report['distinct_skeletons']} distinct") - rows = list(report["streams"].items()) + [("union", report["union"])] - for label, r in rows: - h = r["held_by_skeletons"] - print(f"{label}: {r['in_a_skeleton']} of {r['names']} names are joints ({r['same_spelling']} same spelling, " - f"{r['joint_unnamed']} unnamed); all held by {h['distinct']} distinct skeletons " - f"({h['copies']} copies), joint counts {h['joint_counts'][:6]}") - - -def parse_offset(text): - try: - return int(text, 0) - except ValueError: - raise argparse.ArgumentTypeError(f"not an offset: {text!r}") from None - - -def main(argv=None): - ap = argparse.ArgumentParser(description=__doc__.split("\n")[0]) - ap.add_argument("anim", help="anim.rpf") - ap.add_argument("packs", help="packs.rpf") - ap.add_argument("--stream", type=parse_offset, action="append", help="bone-table stream offset in anim.rpf") - ap.add_argument("--json", help="write the report here") - a = ap.parse_args(argv) - if a.json: - for source in (a.anim, a.packs): - if same_report_path(a.json, source): - print(f"anim_skel_match: --json must not overwrite input {source}", file=sys.stderr) - return 2 - try: - names = stream_names(a.anim, a.stream or DEFAULT_STREAMS) - skeletons = read_skeletons(a.packs, lambda t: print(t, file=sys.stderr, flush=True)) - except (OSError, ValueError) as e: - print(f"anim_skel_match: {e}", file=sys.stderr) - return 2 - report = match(names, skeletons) - print_report(report) - if a.json: - with open(a.json, "w", encoding="utf-8", newline="\n") as f: - json.dump(report, f, indent=1) - return 0 - - -if __name__ == "__main__": - try: # a redirected stdout is strict ANSI code page under -I; write '?' for what it cannot encode - sys.stdout.reconfigure(errors="replace") - except (AttributeError, ValueError, OSError): - pass - sys.exit(main()) diff --git a/tools/anim_skeleton_match.py b/tools/anim_skeleton_match.py deleted file mode 100644 index 2cab41339..000000000 --- a/tools/anim_skeleton_match.py +++ /dev/null @@ -1,188 +0,0 @@ -"""Match `anim.rpf` `SKEL_*` bone lists against decoded skeleton name tables in `packs.rpf` (ASSET-231). - - python -I tools/anim_skeleton_match.py [--out ] - -Reads both archives in place using `anim_index.scan_rpf`, extracts `SKEL_[A-Za-z0-9_]+` tokens from -inflated streams, and compares the animation bone set against the model skeletons (both exact and -case-insensitive, plus `joaat32` of lowercased ASCII). Writes counts only (no bone names, offsets -or archive bytes) when `--out` is given. Standard library only; no game data. -Usage: `python -I tools/anim_skeleton_match.py --help` lists the options. -""" -import argparse -import json -import mmap -import os -import re -import sys -import tempfile -import zlib - -HERE = os.path.dirname(os.path.abspath(__file__)) -if HERE not in sys.path: - sys.path.insert(0, HERE) - -import anim_index # noqa: E402 -from file_mode import published_mode # noqa: E402 -from replace_retry import replace as replace_retry # noqa: E402 -from report_paths import same_report_path # noqa: E402 - -SKEL_RE = re.compile(rb"SKEL_[A-Za-z0-9_]+") - - -def joaat32(name: str) -> int: - """RAGE joaat32 over the lowercased bone name, encoded as hashdict.joaat does (latin-1, '?' for the rest).""" - h = 0 - for b in name.lower().encode("latin-1", "replace"): - h = (h + b) & 0xFFFFFFFF - h = (h + (h << 10)) & 0xFFFFFFFF - h = (h ^ (h >> 6)) & 0xFFFFFFFF - h = (h + (h << 3)) & 0xFFFFFFFF - h = (h ^ (h >> 11)) & 0xFFFFFFFF - h = (h + (h << 15)) & 0xFFFFFFFF - return h - - -def extract_skel_tokens(data: bytes) -> set[str]: - """Return distinct `SKEL_[A-Za-z0-9_]+` tokens present in `data`.""" - if b"SKEL_" not in data: - return set() - return {m.decode("ascii") for m in SKEL_RE.findall(data)} - - -def scan_archive_skel(path: str) -> dict: - """Scan an RPF archive's zlib streams and return stream/token counts and the `SKEL_*` token sets.""" - rows, _ = anim_index.scan_rpf(path) - per_stream = [] - all_tokens = set() - with open(path, "rb") as fh, mmap.mmap(fh.fileno(), 0, access=mmap.ACCESS_READ) as m: - for row in rows: - off = row["offset"] - try: - data = zlib.decompress(m[off:off + row["stored"] + 16]) - except zlib.error: - continue - toks = extract_skel_tokens(data) - if toks: - per_stream.append(toks) - all_tokens |= toks - return {"streams": len(rows), "skel_streams": len(per_stream), "per_stream": per_stream, "tokens": all_tokens} - - -def compare_sets(skel_tokens: set[str], anim_per_stream: list[set[str]]) -> dict: - """Compare animation `SKEL_*` streams/tokens against a model skeleton token set (counts only).""" - anim_tokens = set().union(*anim_per_stream) if anim_per_stream else set() - skel_lower = {t.lower() for t in skel_tokens} - skel_hashes = {joaat32(t) for t in skel_tokens} - exact = anim_tokens & skel_tokens - ci = {t for t in anim_tokens if t.lower() in skel_lower} - hashed = {t for t in anim_tokens if joaat32(t) in skel_hashes} - all_exact_streams = sum(1 for s in anim_per_stream if s <= skel_tokens) - all_ci_streams = sum(1 for s in anim_per_stream if all(t.lower() in skel_lower for t in s)) - any_ci_streams = sum(1 for s in anim_per_stream if any(t.lower() in skel_lower for t in s)) - return { - "distinct_anim_tokens": len(anim_tokens), - "distinct_skeleton_tokens": len(skel_tokens), - "matched_exact": len(exact), - "matched_case_insensitive": len(ci), - "matched_joaat32": len(hashed), - "unmatched_case_insensitive": len(anim_tokens) - len(ci), - "anim_skel_streams": len(anim_per_stream), - "streams_all_matched_exact": all_exact_streams, - "streams_all_matched_ci": all_ci_streams, - "streams_any_matched_ci": any_ci_streams, - } - - -def _check_input(ap, label: str, path: str) -> None: - if not os.path.exists(path): - ap.error(f"{label} not found: {path}") - if os.path.isdir(path): - ap.error(f"{label} is a directory: {path}") - try: - if os.path.getsize(path) == 0: - ap.error(f"{label} is empty: {path}") - except OSError as exc: - ap.error(f"cannot read {label} ({path}): {exc}") - - -def _check_output(ap, out_path: str, inputs: tuple[str, ...]) -> None: - if any(same_report_path(out_path, inp) for inp in inputs): - ap.error("--out must not overwrite an input archive") - if os.path.isdir(out_path): - ap.error(f"--out is a directory: {out_path}") - parent = os.path.dirname(os.path.abspath(out_path)) - if not os.path.isdir(parent): - ap.error(f"--out parent directory does not exist: {parent}") - - -def _write_json_report(path: str, text: str) -> None: - """Publish complete JSON, or leave the previous report intact on replace failure.""" - destination = os.path.abspath(path) - parent = os.path.dirname(destination) - if parent: - os.makedirs(parent, exist_ok=True) - try: - mode = os.stat(destination).st_mode - except FileNotFoundError: - mode = None - except OSError: - # Non-regular destinations (pipes/devices) keep a direct write. - with open(destination, "w", encoding="utf-8", newline="\n") as fh: - fh.write(text if text.endswith("\n") else text + "\n") - return - if mode is not None: - # Retain the direct writer's permission check without truncating the report. - os.close(os.open(destination, os.O_WRONLY)) - - staged = tempfile.NamedTemporaryFile( - mode="w", encoding="utf-8", newline="\n", delete=False, - dir=parent, prefix=".anim_skeleton_match-", suffix=".tmp", - ) - try: - with staged: - staged.write(text if text.endswith("\n") else text + "\n") - if os.name != "nt": - os.chmod(staged.name, published_mode(destination)) - replace_retry(staged.name, destination) - finally: - try: - os.unlink(staged.name) - except FileNotFoundError: - pass - - -def main(argv=None): - ap = argparse.ArgumentParser(description="Match anim.rpf SKEL_* bone lists against packs.rpf skeletons (ASSET-231).") - ap.add_argument("packs", help="Path to packs.rpf") - ap.add_argument("anim", help="Path to anim.rpf") - ap.add_argument("--out", help="Optional JSON output path (counts only)") - a = ap.parse_args(argv) - _check_input(ap, "packs", a.packs) - _check_input(ap, "anim", a.anim) - if a.out: - _check_output(ap, a.out, (a.packs, a.anim)) - try: - packs = scan_archive_skel(a.packs) - anim = scan_archive_skel(a.anim) - except (OSError, ValueError) as exc: - ap.error(str(exc)) - summary = compare_sets(packs["tokens"], anim["per_stream"]) - summary["packs_streams"] = packs["streams"] - summary["packs_skel_streams"] = packs["skel_streams"] - summary["anim_streams"] = anim["streams"] - text = json.dumps(summary, indent=2) - print(text) - if a.out: - try: - _write_json_report(a.out, text) - except OSError as exc: - ap.error(f"cannot write --out ({a.out}): {exc}") - return 0 - - -if __name__ == "__main__": - try: # a redirected stdout is strict ANSI code page under -I; write '?' for what it cannot encode - sys.stdout.reconfigure(errors="replace") - except (AttributeError, ValueError, OSError): - pass - sys.exit(main()) diff --git a/tools/audio_config.py b/tools/audio_config.py deleted file mode 100644 index 8865818c2..000000000 --- a/tools/audio_config.py +++ /dev/null @@ -1,303 +0,0 @@ -"""Read the music/radio record table from the game's inflated audio-config blob. - -The audio config is the zlib-compressed section at the start of `audio.rpf`, before the first AWC bank. -It is not part of the table of contents and it is not a script resource. The music records sit in a -few streams inside it and share a fixed 46-byte layout, keyed by a marker that is stable across every -record: - - record - 4 u32 duration in milliseconds - record + 0 0c 01 marker - record + 2 u16 config id - record + 4 02 00 0c 00 - record + 8 u32 hash A (unresolved) - record + 12 u32 hash B joaat(normalized name) - record + 16 00 00 02 23 - record + 20 22 bytes fixed flags/parameters - -`hash B` is Jenkins one-at-a-time over the lowercase name with spaces and punctuation mapped to `_`. -The AWC stream id is `hash B & 0x1FFFFFFF`. The config and the current AWC manifest report -per-channel duration, which is the actual song/ad length. In the original comparison, all -1,589 records resolved to a stream id and 1,584 durations matched within 0.01 s after -halving the legacy manifest values to account for interleaved stereo samples. - -The config stores no per-track start offsets. It gives the station grouping as contiguous config-id -ranges and station-local content-id lists, but the mix order is not stored; a continuous radio mix -must be matched in the audio. This tool therefore outputs only the record table. - -Usage: - python -I audio_config.py [--json] [--names FILE] [--join] - [--min-ms N] [--max-ms N] - -`--names` is an optional NUL-separated string pool (the package's debug/name stream); each string is -hashed with the same function and used to fill `name` for the matching hash B. The pool is a local -game file and is never copied or committed. - -The input is the inflated output of `rpf9_carve.py`, either the per-stream `.bin` files or a single -concatenated config blob. Records are found by their marker and duration range, not by a hard-coded -stream offset, so an incomplete carve simply yields fewer records. - -`--join` streams the directory's `.bin` parts in name order as one input, so a record split across -a zlib block boundary is still found. JSON `offset` is then the joined byte position and -`file_offset` the position inside `file`, the part holding the record's `0c` marker byte; text -output prints `file:file_offset`. The joined scan holds at most two read blocks of input -(`JOIN_BLOCK_BYTES`, 1 MiB) plus a 24-byte carry, one name and start per part, and the records. -""" -import argparse -from bisect import bisect_right -import json -import os -import struct -import sys - -MARKER_1 = b"\x0c\x01" -MARKER_2 = b"\x02\x00\x0c\x00" -MARKER_3 = b"\x00\x00\x02\x23" -RECORD_BYTES = 46 -MIN_MS = 20_000 -MAX_MS = 2_000_000 -STREAM_MASK = 0x1FFFFFFF -JOIN_BLOCK_BYTES = 1 << 20 # --join read size; a typical carved part is one read - - -def joaat(text): - """Jenkins one-at-a-time over the lowercased latin-1 bytes, as the name hash is defined. - - The same rule as ``tools/hashdict.py`` (the pinned name dictionary) and ``tools/awc_names.py``, which - recovers stream names: a name has to hash alike in every tool or the id never matches. Lowercased - UTF-8 gave a different hash for any non-ASCII character (``é`` is one byte 0xE9, not 0xC3 0xA9), so a - title with an accent produced a stream id no bank stores. - """ - h = 0 - for c in text.lower().encode("latin-1", "replace"): - h = (h + c) & 0xFFFFFFFF - h = (h + (h << 10)) & 0xFFFFFFFF - h ^= h >> 6 - h = (h + (h << 3)) & 0xFFFFFFFF - h ^= h >> 11 - h = (h + (h << 15)) & 0xFFFFFFFF - return h & 0xFFFFFFFF - - -def title_stream_id(title: str) -> int: - """AWC stream id for a config title. - - The config's ``hash B`` is ``joaat(normalized_name(title))`` and the - stream id is its low 29 bits. This is the lookup used to resolve untitled - config records when the title is known from credits or a playlist. - """ - return joaat(normalized_name(title)) & STREAM_MASK - - -def normalized_name(text): - """Lowercase, and map every non-alphanumeric run to a single underscore.""" - out = [] - last = False - for ch in text.lower(): - ok = ch.isalnum() - if ok: - out.append(ch) - elif not last: - out.append("_") - last = not ok - return "".join(out).strip("_") - - -def _record_at(blob, i, offset, min_ms, max_ms): - """Return the record whose `0c 01` marker is at blob[i], reported at `offset`, or None.""" - if blob[i + 4:i + 8] != MARKER_2 or blob[i + 16:i + 20] != MARKER_3: - return None - duration = struct.unpack_from(" display string for a NUL-separated pool.""" - with open(path, "rb") as f: - pool = f.read() - names = {} - for item in pool.split(b"\x00"): - if not item: - continue - text = item.decode("latin-1") # a name's bytes, as hashdict.py and awc_names.py read them - key = joaat(normalized_name(text)) - if key not in names: - names[key] = text - return names - - -def collect(src, min_ms=MIN_MS, max_ms=MAX_MS, names=None, join=False): - """Scan `src` and add `file` and `file_offset`, the record's position inside `file`. - - Without `join`, `offset` equals `file_offset`. With `join`, the parts are streamed in name - order, `offset` is the joined position and `file` is the part holding the `0c` marker byte. - """ - records = [] - if join: - files, starts = [], [] - - def chunks(): - seen = 0 - for name, path in paths_in(src): - files.append(name) - starts.append(seen) - with open(path, "rb") as f: - while chunk := f.read(JOIN_BLOCK_BYTES): - seen += len(chunk) - yield chunk - - for record in scan_stream(chunks(), min_ms, max_ms): - index = bisect_right(starts, record["offset"]) - 1 - record["file"] = files[index] - record["file_offset"] = record["offset"] - starts[index] - records.append(record) - else: - for name, blob in files_in(src): - for record in scan(blob, min_ms, max_ms): - record["file"] = name - record["file_offset"] = record["offset"] - records.append(record) - if names: - for record in records: - record["name"] = names.get(record["hash_b"], "") - return records - - -def summarize(records): - ids = [r["id"] for r in records] - counts = {} - for i in ids: - counts[i] = counts.get(i, 0) + 1 - return { - "records": len(records), - "distinct_ids": len(counts), - "id_min": min(ids) if ids else None, - "id_max": max(ids) if ids else None, - "duration_s": round(sum(r["duration_ms"] for r in records) / 1000.0, 3), - "named": sum(1 for r in records if r.get("name")), - "duplicate_ids": sorted(i for i, n in counts.items() if n > 1), - } - - -def main(): - ap = argparse.ArgumentParser(description="Read the audio-config music/radio record table.") - ap.add_argument("src", help="inflated config blob or directory of carved .bin streams") - ap.add_argument("--json", action="store_true", help="write records and summary as JSON") - ap.add_argument("--names", help="optional NUL-separated name pool for hash B") - ap.add_argument("--join", action="store_true", - help="scan the directory's .bin streams in name order as one stream " - "(records can straddle a zlib block boundary); text shows the offset in " - "the file, JSON keeps the joined offset and adds file_offset") - ap.add_argument("--min-ms", type=int, default=MIN_MS, help="minimum duration (default 20000)") - ap.add_argument("--max-ms", type=int, default=MAX_MS, help="maximum duration (default 2000000)") - a = ap.parse_args() - if a.min_ms < 1 or a.max_ms < a.min_ms: - ap.error("require 1 <= min-ms <= max-ms") - - if not os.path.exists(a.src): - print(f"ERROR: {a.src}: does not exist", file=sys.stderr) - return 2 - if a.join and not os.path.isdir(a.src): - ap.error("--join applies to a directory, not a single file") - try: - names = load_names(a.names) if a.names else None - except OSError as e: - sys.exit(f"{a.names}: cannot read the name pool: {e.strerror or e}") - try: - records = collect(a.src, a.min_ms, a.max_ms, names, a.join) - except OSError as e: - sys.exit(f"{e.filename or a.src}: cannot read: {e.strerror or e}") - if not records: - sys.exit(f"{a.src}: no audio-config records found") - summary = summarize(records) - - if a.json: - json.dump({"records": records, "summary": summary}, sys.stdout, indent=1) - sys.stdout.write("\n") - return 0 - - for r in records: - label = r.get("name") or f"0x{r['hash_b']:08X}" - print(f"{r['file']}:{r['file_offset']:6d} id=0x{r['id']:04X} " - f"dur={r['duration_s']:9.3f}s stream=0x{r['stream_id']:08X} {label}") - print(f"{summary['records']} records, {summary['distinct_ids']} distinct ids, " - f"ids 0x{summary['id_min']:04X}-0x{summary['id_max']:04X}, " - f"{summary['duration_s']:.1f} s total" - + (f", {summary['named']} named" if names else "")) - return 0 - - -if __name__ == "__main__": - try: # a redirected stdout is strict ANSI code page under -I; write '?' for what it cannot encode - sys.stdout.reconfigure(errors="replace") - except (AttributeError, ValueError, OSError): - pass - sys.exit(main()) diff --git a/tools/audio_wav.py b/tools/audio_wav.py deleted file mode 100644 index c096b9da2..000000000 --- a/tools/audio_wav.py +++ /dev/null @@ -1,573 +0,0 @@ -"""Decode Ogg Opus audio to 16-bit PCM WAV with ffmpeg. - - python -I audio_wav.py [--out DIR] [--jobs N] [--ffmpeg PATH] - -Every .ogg/.opus file under the source is decoded to /.wav (the name keeps its directory, -the extension becomes .wav; files that would share a name, such as x.ogg and x.opus, keep their extension: -x.ogg.wav, x.opus.wav). Existing .wav files are skipped, so a stopped run continues where it left off, and -.wav inputs are never decoded. With no --out, a source directory writes to /wav and a single file writes -next to itself. Resuming assumes the same set of sources: an existing plain-named WAV is trusted by name. Only an -existing name shaped like a kept-extension one (x.ogg.wav, x.opus~2.wav) has its audio compared; if it differs, -that file is left alone and the input moves on to the next ~N name. - -The output is pcm_s16le at the stream's own sample rate and channel count (Opus is always 48 kHz). A single -stream is trimmed to its Ogg Opus end granule minus pre-skip, because ffmpeg can keep samples beyond its declared -end. For chained streams, ffmpeg handles each link's timing. ffmpeg must be on PATH or given with ---ffmpeg; without it the tool exits with an explanation instead of a traceback. -The decode queue holds at most one outstanding job per worker, even for a large input tree. - -For PCM copies of the AWC banks' Opus streams, first repackage the banks with awc_opus.py, then run this tool on -its output (make_game.py does both, the second only with --wav). -Usage: `python -I tools/audio_wav.py --help` lists the options. -""" -import argparse -import concurrent.futures -from contextlib import ExitStack -import errno -from functools import cache -import hashlib -import os -import shutil -import struct -import subprocess -import sys -import tempfile -import time -from typing import BinaryIO -import unicodedata - -EXTS = (".ogg", ".opus") - - -def error(msg: str) -> None: - print(f"ERROR: {msg}", file=sys.stderr) - - -def find_ffmpeg(explicit: str): - """The ffmpeg executable to run, or None (with the reason already printed).""" - if explicit: - candidate = os.path.expanduser(explicit) - if os.path.dirname(candidate): - if os.path.isfile(candidate): - return os.path.abspath(candidate) - else: - found = shutil.which(candidate) - if found: - return found - error(f"ffmpeg not found: {explicit}. Give --ffmpeg the path to ffmpeg.exe, or install ffmpeg and put it " - "on PATH: https://ffmpeg.org/download.html") - return None - found = shutil.which("ffmpeg") - if not found: - error("ffmpeg was not found on PATH (it decodes the Ogg Opus files to WAV). Install it from " - "https://ffmpeg.org/download.html and reopen the terminal, or pass --ffmpeg PATH.") - return found - - -def _read_opus_id(stream: BinaryIO) -> tuple[bytes, bytes] | None: - """Read the Opus ID packet and serial, leaving the stream at the next page.""" - header = stream.read(27) - if len(header) != 27 or header[:6] != b"OggS\x00\x02": - return None - lacing = stream.read(header[26]) - # An Opus identification packet completes on the BOS page and is its only packet (RFC 7845). - if len(lacing) != header[26] or not lacing or lacing[-1] == 255 or any(v != 255 for v in lacing[:-1]): - return None - size = sum(lacing) - packet = stream.read(size) - if len(packet) != size or size < 19 or not packet.startswith(b"OpusHead"): - return None - return packet, header[14:18] - - -def looks_like_opus(path: str) -> bool: - """True if the first Ogg page carries an OpusHead packet (so .ogg files that are Vorbis are left alone).""" - try: - with open(path, "rb") as f: - return _read_opus_id(f) is not None - except OSError: - return True # let ffmpeg report the real problem - - -def ogg_output_samples(path: str) -> int: - """End granule minus pre-skip for a single unchained Opus stream, or 0 to use ffmpeg's timing.""" - try: - size = os.path.getsize(path) - with open(path, "rb") as f: - identification = _read_opus_id(f) - if identification is None: - return 0 - head, serial = identification - if head[8] >= 16 or head[9] == 0: - return 0 - pre_skip, = struct.unpack_from(" size: - return 0 - if htype & 0x04: - if offset != size: - return 0 - granule, = struct.unpack_from(" pre_skip else 0 - return 0 - except (OSError, struct.error): - return 0 - - -def collect(src: str): - """([(input, relative output stem)], number of .ogg/.opus files that are not Ogg Opus).""" - def scan_failed(exc: OSError) -> None: - raise exc - - files, not_opus = [], 0 - for root, dirs, names in os.walk(src, onerror=scan_failed): - dirs.sort() - for name in sorted(names): - if not name.lower().endswith(EXTS): - continue - path = os.path.join(root, name) - rel = os.path.relpath(path, src) - if looks_like_opus(path): - files.append((path, os.path.splitext(rel)[0])) - else: - not_opus += 1 - return files, not_opus - - -def output_names(items, out=None): - """Give every input its own output stem, and count how many had to keep their extension. - - x.ogg and x.opus (or x.OPUS, which is the same name on Windows) both became x.wav: two jobs then decoded into - the same x.wav.part.wav at once and one result was lost, and with --jobs 1 the second silently replaced the - first. Inputs that share a stem now keep their extension (x.ogg.wav, x.opus.wav); a name that still clashes - gets ~2, ~3. With out supplied, resolve directory links on the destination before checking names. Keep the - original relative paths in the result so existing WAVs are still found and skipped.""" - @cache - def output_directory(relative): - return os.path.normcase(os.path.realpath(os.path.join(out, relative))) - - def destination(stem): - if out is None: - return os.path.normcase(stem) - directory, name = os.path.split(stem) - return output_directory(directory), os.path.normcase(name) - - count = {} - for _, rel in items: - key = destination(rel) - count[key] = count.get(key, 0) + 1 - if len(count) == len(items): - return list(items), 0 - named, used, renamed = [], set(), 0 - for path, rel in items: - name = rel - if count[destination(rel)] > 1: - name = rel + os.path.splitext(path)[1] - renamed += 1 - base, n = name, 2 - key = destination(name) - while key in used: - name, n = f"{base}~{n}", n + 1 - key = destination(name) - used.add(key) - named.append((path, name)) - return named, renamed - - -def fold_name(text): - # A broad, cheap filter. The output volume decides whether two candidate names are really aliases. - return unicodedata.normalize("NFD", unicodedata.normalize("NFD", os.path.normcase(text)).upper().casefold()) - - -def existing_entry(path, st): - if st.st_nlink == 1: - return st.st_dev, st.st_ino - # Two hard links have the same inode but can occupy separate directory entries, even on a read-only volume. - directory, leaf = os.path.split(path) - with os.scandir(directory) as entries: - matches = [e.name for e in entries if fold_name(e.name) == fold_name(leaf) and e.inode() == st.st_ino] - if leaf in matches or len(matches) == 1: - return st.st_dev, os.stat(directory).st_ino, leaf if leaf in matches else matches[0] - return None - - -def native_collisions(group, named, target, unprobed): - """Ask the destination volume which suspect names identify one file, without touching the real targets.""" - stems = {i: target(named[i][1]) for i in group} - collided = set() - - def record(indices, tokens): - owners, missing = {}, [] - for i, token in zip(indices, tokens): - if token is None: - missing.append(i) - else: - first = owners.setdefault(token, i) - if first != i: - collided.update((first, i)) - return missing - - def existing_tokens(indices, suffix): - entries = [] - for i in indices: - path = stems[i] + suffix - try: - st = os.lstat(path) - except OSError as e: - if e.errno not in (errno.ENOENT, errno.ENAMETOOLONG): - raise - entries.append(None) - continue - entry = existing_entry(path, st) - if not st.st_ino or entry is None: - return [] # an ambiguous hard link cannot partition this group - entries.append(entry) - return entries - - # Existing and missing spellings for a common suffix cannot be aliases. Classify the existing entries - # together, then apply another common witness to those still missing; never compare incompatible identities. - suffixes = [".wav"] + sorted({os.path.splitext(named[i][0])[1] + ".wav" for i in group}) - remaining = group - while len(remaining) > 1: - for suffix in suffixes: - entries = existing_tokens(remaining, suffix) - if any(entries): - remaining = record(remaining, entries) - break - else: - break - if len(remaining) < 2: - return collided - - probes, tokens = {}, [] - try: - with ExitStack() as stack: - for i in remaining: - stem = stems[i] - parent = os.path.dirname(stem) - while not os.path.isdir(parent) and os.path.dirname(parent) != parent: - parent = os.path.dirname(parent) - anchor = os.stat(parent) - volume_dir = anchor.st_dev, anchor.st_ino - if volume_dir not in probes: - probes[volume_dir] = stack.enter_context(tempfile.TemporaryDirectory(dir=parent)) - probe = os.path.join(probes[volume_dir], os.path.relpath(stem, parent) + ".wav") - os.makedirs(os.path.dirname(probe), exist_ok=True) - with open(probe, "ab"): - pass - st = os.stat(probe) - if not st.st_ino: - raise OSError(f"the filesystem did not report a file identity for {stem}") - tokens.append((st.st_dev, st.st_ino)) - except OSError as e: - if e.errno not in (errno.EACCES, errno.EPERM, errno.EROFS): - raise - unprobed.update(remaining) # only an existing PCM-verified repair may be reused - else: - record(remaining, tokens) - return collided - - -def repair_base(stem): - """The kept-extension base of a possible repair, including names that already have a ~N counter.""" - base, sep, counter = stem.rpartition("~") - if sep and counter.isascii() and counter.isdigit(): - stem = base - return stem if stem.lower().endswith(EXTS) else None - - -def plan_outputs(items, src, out, ffmpeg): - """Apply the existing naming rules first. Reserve their results before moving any residual native aliases.""" - @cache - def parent(directory): - return os.path.realpath(os.path.join(out, directory)) - - def target(stem): - directory, name = os.path.split(stem) - return os.path.join(parent(directory), name) - - folded_parent = cache(lambda directory: fold_name(parent(directory))) - - def key(stem): - directory, name = os.path.split(stem) - return folded_parent(directory), fold_name(name) - - def buckets(pairs): - reserved, groups, guarded = {}, {}, [] - for i, (_, stem) in enumerate(pairs): - bucket = key(stem) - first = reserved.setdefault(bucket, i) - if i != first: - groups.setdefault(bucket, [first]).append(i) - base = repair_base(stem) - if base is not None: - guarded.append((i, base)) - return reserved, groups, guarded - - reserved, groups, guarded = buckets(items) - if not groups and not guarded: - return items, 0, 0 - named, renamed, repaired, unprobed = list(items), 0, set(), set() - if groups: - named, renamed = output_names(items, out) - if renamed: - # Legacy assignments, including their counters, take precedence over all new names. - reserved, groups, guarded = buckets(named) - for group in groups.values(): - repaired.update(native_collisions(group, named, target, unprobed)) - repaired.update(unprobed) - counters, digests, dest_digests = {}, {}, {} - - def holds_own_audio(i, stem): - """True if stem.wav is free or already holds input i's decoded audio.""" - path = named[i][0] - dst = os.path.join(out, stem + ".wav") - if not os.path.lexists(dst): - return True - if i not in digests: - if not digests: - print("Checking audio in existing kept-extension WAVs...", flush=True) - elif len(digests) % 100 == 0: - print(f" Checked {len(digests)} input recordings...", flush=True) - digests[i] = audio_digest(ffmpeg, path, source=True) - if digests[i] and os.path.isfile(dst): - if dst not in dest_digests: - dest_digests[dst] = audio_digest(ffmpeg, dst, source=False) - if dest_digests[dst] == digests[i]: - return True - print(f" Keeping {dst}: its audio could not be verified for {path}.", file=sys.stderr) - return False - - def allocate(i, base): - """Give input i the first unreserved name of base, base~2, ... that is free or holds its audio.""" - base_key = key(base) - first = counters.get(base_key, 2) - stem, n = (base, 2) if first == 2 else (f"{base}~{first}", first + 1) - skipped_unreserved = False - while True: - candidate = key(stem) - if candidate not in reserved: - if i in unprobed and not os.path.lexists(os.path.join(out, stem + ".wav")): - raise OSError(f"cannot distinguish names in a read-only directory and verify {stem}.wav") - if holds_own_audio(i, stem): - break - skipped_unreserved = True - stem, n = f"{base}~{n}", n + 1 - if not skipped_unreserved: - counters[base_key] = n - reserved[candidate] = i - named[i] = (named[i][0], stem) - - for i in sorted(repaired): - directory, leaf = os.path.split(os.path.relpath(named[i][0], src)) - base, ext = os.path.splitext(leaf) - # Keep room for the source extension, a counter and ".wav" on a 255-byte filesystem. - while len(os.fsencode(base)) > 230: - base = base[:-1] - allocate(i, os.path.join(directory, base + ext)) - # An earlier run may have left a repair under this shape for different audio. Plain names stay name-only. - moved = 0 - for i, base in guarded: - if i not in repaired and not holds_own_audio(i, named[i][1]): - allocate(i, base) - moved += 1 - return named, renamed, len(repaired) + moved - - -def audio_digest(ffmpeg, path, *, source): - """Hash a metadata-free WAV stream, retaining its PCM, channel layout and sample rate.""" - cmd = [ffmpeg, "-v", "error"] - if not source: - # Preserve an unspecified layout (e.g. four mapping-family-255 channels) when reading a prior WAV. - cmd += ["-f", "wav", "-guess_layout_max", "0"] - cmd += ["-i", path] - if source: - samples = ogg_output_samples(path) - if samples: - cmd += ["-af", f"atrim=end_sample={samples}"] - cmd += ["-map_metadata", "-1", "-fflags", "+bitexact", "-c:a", "pcm_s16le" if source else "copy", "-f", "wav", "-"] - # No stdin for ffmpeg here or in decode(): it reads stdin for key commands, which stops a run started in the - # background of a terminal and swallows input piped to the caller (such as a shell loop's file list). - with subprocess.Popen(cmd, stdin=subprocess.DEVNULL, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL) as proc: - header = proc.stdout.read(12) - h = hashlib.sha256(header) - for block in iter(lambda: proc.stdout.read(1024 * 1024), b""): - h.update(block) - valid = header[:4] in (b"RIFF", b"RF64") and header[8:] == b"WAVE" - return h.digest() if proc.wait() == 0 and valid else None - - -def decode(ffmpeg: str, src: str, dst: str): - """Decode under the destination directory and rename the finished WAV into place.""" - try: - out_dir = os.path.dirname(dst) - os.makedirs(out_dir, exist_ok=True) - td_kwargs = {"dir": out_dir} - if sys.version_info >= (3, 10): - td_kwargs["ignore_cleanup_errors"] = True - with tempfile.TemporaryDirectory(**td_kwargs) as tmp_dir: - tmp = os.path.join(tmp_dir, "decoded.wav") - cmd = [ffmpeg, "-v", "error", "-y", "-i", src] - samples = ogg_output_samples(src) - if samples: - cmd += ["-af", f"atrim=end_sample={samples}"] - cmd += ["-c:a", "pcm_s16le", tmp] - r = subprocess.run(cmd, stdin=subprocess.DEVNULL, capture_output=True, text=True, errors="replace") - if r.returncode != 0: - return False, (r.stderr.strip() or f"ffmpeg exited with {r.returncode}") - os.replace(tmp, dst) - return True, "" - except OSError as e: - return False, str(e) - - -def _decode_jobs(pool, ffmpeg, todo, workers): - """Yield (relative name, completed future) without retaining a future for every input.""" - jobs = iter(todo) - pending = {} - while True: - while len(pending) < workers: - job = next(jobs, None) - if job is None: - break - path, rel, dst = job - pending[pool.submit(decode, ffmpeg, path, dst)] = rel - if not pending: - return - ready, _ = concurrent.futures.wait(pending, return_when=concurrent.futures.FIRST_COMPLETED) - for future in ready: - yield pending.pop(future), future - - -def main(argv=None) -> int: - ap = argparse.ArgumentParser(description="Decode Ogg Opus audio to 16-bit PCM WAV with ffmpeg.") - ap.add_argument("src", help="a directory to search recursively, or one .ogg/.opus file") - ap.add_argument("--out", help="output directory (default: /wav for a directory, next to a single file)") - ap.add_argument("--jobs", type=int, default=max(1, (os.cpu_count() or 2) // 2), - help="ffmpeg processes to run at once (default: half the CPU count)") - ap.add_argument("--ffmpeg", help="ffmpeg executable (default: ffmpeg on PATH)") - a = ap.parse_args(argv) - if a.jobs < 1: - ap.error("--jobs must be at least 1") - - src = os.path.abspath(a.src) - if os.path.isfile(src): - if not src.lower().endswith(EXTS): - error(f"{a.src} is not an .ogg/.opus file (already-WAV files are not decoded).") - return 2 - if not looks_like_opus(src): - error(f"{a.src} is not Ogg Opus.") - return 2 - items = [(src, os.path.splitext(os.path.basename(src))[0])] - not_opus = 0 - default_out = os.path.dirname(src) - elif os.path.isdir(src): - try: - items, not_opus = collect(src) - except OSError as exc: - error(f"cannot scan {exc.filename or src}: {exc.strerror or exc}") - return 2 - default_out = os.path.join(src, "wav") - else: - error(f"source not found: {a.src}") - return 2 - - out = os.path.abspath(a.out or default_out) - if a.out and os.path.isfile(out): - ap.error(f"{a.out} is a file, not a folder") - - print(f"{len(items)} Ogg Opus file(s) under {src} -> {out}") - if not items: - print(f"Nothing to do: no Ogg Opus files found" - + (f" ({not_opus} .ogg/.opus file(s) are not Ogg Opus)" if not_opus else "") + ".") - return 0 - - ffmpeg = find_ffmpeg(a.ffmpeg) - if not ffmpeg: - return 2 - - try: - items, renamed, repaired = plan_outputs(items, src, out, ffmpeg) - except OSError as e: - error(f"could not safely distinguish WAV output names under {out}: {e}") - return 2 - if renamed: - print(f"{renamed} file(s) share a name with another input (e.g. x.ogg and x.opus) and keep their extension " - f"in the WAV name (x.ogg.wav)") - if repaired: - print(f"{repaired} file(s) needed distinct names on the output filesystem or beside an unverified WAV.") - - t0 = time.time() - written = skipped = 0 - todo = [] - failed = 0 - failure_samples: list[tuple[str, str]] = [] - - def record_failure(rel: str, message: str) -> None: - nonlocal failed - failed += 1 - if len(failure_samples) < 10: - first = next((line.strip() for line in message.splitlines() if line.strip()), "unknown error") - failure_samples.append((rel, first)) - - for path, rel in items: - dst = os.path.join(out, rel + ".wav") - if os.path.isfile(dst): - skipped += 1 - elif os.path.exists(dst): - record_failure(rel, f"output path is not a file: {dst}") - else: - todo.append((path, rel, dst)) - - done = 0 - workers = min(a.jobs, len(todo)) if todo else 1 - if todo: - print(f"Decoding {len(todo)} file(s) with {workers} job(s)...") - with concurrent.futures.ThreadPoolExecutor(max_workers=workers) as pool: - for rel, future in _decode_jobs(pool, ffmpeg, todo, workers): - try: - ok, message = future.result() - except Exception as e: # never lose the summary to an unexpected worker error - ok, message = False, f"{type(e).__name__}: {e}" - done += 1 - if ok: - written += 1 - else: - record_failure(rel, message) - if done % 200 == 0: - print(f" {done}/{len(todo)} decoded", flush=True) - - seconds = time.time() - t0 - summary = f"{len(items)} Ogg Opus file(s): {written} WAV written, {skipped} already present" - if failed: - summary += f", {failed} failed" - print(summary + f" ({seconds:.1f}s)") - if not_opus: - print(f" {not_opus} .ogg/.opus file(s) skipped: not Ogg Opus") - for rel, first in failure_samples: - print(f" FAILED {rel}: {first}") - if failed > len(failure_samples): - print(f" ... and {failed - len(failure_samples)} more failures") - return 1 if failed else 0 - - -if __name__ == "__main__": - try: # a redirected stdout is strict ANSI code page under -I; write '?' for what it cannot encode - sys.stdout.reconfigure(errors="replace") - except (AttributeError, ValueError, OSError): - pass - sys.exit(main()) diff --git a/tools/awc_cue_labels.py b/tools/awc_cue_labels.py deleted file mode 100644 index f2735fde1..000000000 --- a/tools/awc_cue_labels.py +++ /dev/null @@ -1,60 +0,0 @@ -"""Convert one exported cue_regions.json to per-channel Audacity label tracks.""" - -import argparse -import json -from pathlib import Path -import re -import sys -from tempfile import TemporaryDirectory - - -def convert(sheet, output): - data = json.loads(sheet.read_text(encoding="utf-8")) - if (not isinstance(data, dict) or data.get("sample_rate") != 48000 - or not isinstance(data.get("regions"), list)): - raise ValueError("expected a 48 kHz cue sheet with a regions list") - - tracks = {} - for ordinal, row in enumerate(data["regions"], 1): - if not isinstance(row, dict): - raise ValueError(f"invalid cue at row {ordinal}") - channel = row.get("file") - cue = row.get("name_hash") - start = row.get("start_sample") - end = row.get("end_sample") - if (not isinstance(channel, str) or not re.fullmatch(r"[0-9A-F]{8}\.ogg", channel) - or not isinstance(cue, str) or not re.fullmatch(r"[0-9A-F]{8}", cue) - or type(start) is not int or type(end) is not int or not 0 <= start <= end <= 0xffffffff): - raise ValueError(f"invalid channel, cue hash or sample interval at row {ordinal}") - tracks.setdefault(channel, []).append( - f"{start / 48000:.9f}\t{end / 48000:.9f}\t{cue} #{ordinal}\n") - - # Publish a whole bank together, including an empty bank. - if output.exists(): - raise ValueError("choose a new output directory for this bank") - with TemporaryDirectory(dir=output.parent) as tmp: - staged = Path(tmp) / "labels" - staged.mkdir() - for channel, lines in tracks.items(): - (staged / Path(channel).with_suffix(".txt")).write_text( - "".join(lines), encoding="utf-8", newline="\n") - staged.rename(output) - - -def main(): - parser = argparse.ArgumentParser(description=__doc__) - parser.add_argument("sheet", type=Path, help="one bank's exported cue_regions.json") - parser.add_argument("output", type=Path, help="new directory for this bank's label tracks") - args = parser.parse_args() - try: - convert(args.sheet, args.output) - except (ValueError, OSError) as exc: - parser.exit(1, f"error: {exc}\n") - - -if __name__ == "__main__": - try: # a redirected stdout is strict ANSI code page under -I; write '?' for what it cannot encode - sys.stdout.reconfigure(errors="replace") - except (AttributeError, ValueError, OSError): - pass - main() diff --git a/tools/awc_manifest.py b/tools/awc_manifest.py deleted file mode 100644 index 89372f41f..000000000 --- a/tools/awc_manifest.py +++ /dev/null @@ -1,289 +0,0 @@ -"""Write a readable manifest of the streams in AWC audio banks, without decoding or exporting audio. - - python -I awc_manifest.py [--out FILE] [--format csv|json] - -The AWC layout is read by tools/awc_opus.py (parse_awc + music_channels), so this manifest and the -exporter agree on stream ids, codecs, sample rates and streamed-music descriptors. A directory is -scanned recursively for *.awc. CSV is the default on stdout; --out writes a file and a .json -extension selects JSON unless --format says otherwise. A report cannot replace an input bank, including one -found during a directory scan. Unreadable banks are reported on stderr, skipped, -and excluded from bank_count, but a single named file that holds no bank is an error (exit 2) instead of an -empty manifest, since then the path or the format is wrong. The bank column gives the path relative to the -scanned directory or the basename for a single file. - -CSV columns: bank, stream, codec, codec_name, channels, sample_rate, declared_samples, duration_s, -streamed_music, data_offset, data_size, bank_size, notes. JSON is an object with bank_count, -stream_count, streamed_music_channel_count and a streams list of the same fields (booleans and -numbers keep their types). duration_s is the decoded duration: a plain Opus stream counts 48 kHz -frames interleaved across channels, so it is `declared_samples / channels / 48000` regardless of -the tag's rate field; PCM and XMA use `declared_samples / sample_rate`. notes flags values that -look inconsistent (zero/odd rate, data-size mismatch, implausible duration). -A streamed-music descriptor contributes one row per channel group; `channels` is the packet channel count read -from the Opus TOC stereo bit, and `declared_samples`/`duration_s` are per channel (the descriptor stores the -interleaved count). `data_offset`/`size` is the shared data tag. -Usage: `python -I tools/awc_manifest.py --help` lists the options. -""" -import argparse -import csv -import json -import os -import struct -import sys -import tempfile - -# -I keeps the script directory off sys.path, so add it explicitly before importing the parser. -sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) -import awc_opus # noqa: E402 -from file_mode import published_mode # noqa: E402 -from replace_retry import replace as replace_retry # noqa: E402 -from report_paths import same_report_path # noqa: E402 - -FIELDS = ("bank", "stream", "codec", "codec_name", "channels", "sample_rate", "declared_samples", - "duration_s", "streamed_music", "data_offset", "data_size", "bank_size", "notes") -CODEC_NAMES = {0x00: "PCM16", 0x02: "PCM float32", 0x05: "XMA2", 0x0B: "Opus"} - - -def _seconds(codec: int, channels: int, rate: int, samples: int, streamed: bool): - """Decoded duration of one stream, or None when the header has no usable timing. - - A plain Opus format tag counts 48 kHz frames interleaved across the packet channels: over - 1,598,151 measured streams, packet samples - declared is 1920..2879 for every rate, which is - only possible if the count is already 48 kHz frames (and halved for stereo). PCM and XMA - count per-channel samples at the tag's rate. Streamed-music descriptors are already divided - to a per-channel count by awc_opus.music_channels().""" - if codec == 0x0B and not streamed: - return samples / channels / 48000 if channels > 0 else None - return samples / rate if rate > 0 else None - - -def _notes(codec: int, channels: int, rate: int, samples: int, data, bank_size: int, - streamed: bool = False) -> str: - """Human-readable warnings for metadata that does not look self-consistent.""" - offset, size = data - out = [] - if rate <= 0: - out.append("sample rate is zero") - elif rate < 1000 or rate > 192000: - out.append(f"sample rate {rate} Hz is outside 1-192 kHz") - if samples == 0: - out.append("no samples declared") - if size == 0: - out.append("data size is zero") - if offset < 0 or size < 0 or offset + size > bank_size: - out.append("data range is outside the bank") - seconds = _seconds(codec, channels, rate, samples, streamed) - if seconds is not None: - if samples and seconds < 0.001: - out.append(f"duration {seconds:.6f} s is under 1 ms") - if seconds > 24 * 3600: - out.append(f"duration {seconds:.1f} s is over 24 h") - if codec == 0x0B and rate != 48000: - out.append("Opus decodes at 48 kHz") - if codec == 0: - expected = samples * channels * 2 - if size != expected: - out.append(f"PCM16 data is {size} bytes, header implies {expected}") - elif codec == 2: - expected = samples * channels * 4 - if size != expected: - out.append(f"float32 data is {size} bytes, header implies {expected}") - return "; ".join(out) - - -def _row(bank: str, sid: int, codec: int, channels: int, rate: int, samples: int, data, - bank_size: int, streamed: bool) -> dict: - duration = _seconds(codec, channels, rate, samples, streamed) - return { - "bank": bank, - "stream": f"{sid:08X}", - "codec": f"0x{codec:02X}", - "codec_name": CODEC_NAMES.get(codec, "unknown"), - "channels": channels, - "sample_rate": rate, - "declared_samples": samples, - "duration_s": None if duration is None else round(duration, 6), - "streamed_music": streamed, - "data_offset": data[0], - "data_size": data[1], - "bank_size": bank_size, - "notes": _notes(codec, channels, rate, samples, data, bank_size, streamed), - } - - -def _bank_rows(path: str, bank: str) -> list: - with open(path, "rb") as f: - d = f.read() - parsed = awc_opus.parse_awc(d) - if isinstance(parsed, tuple) and len(parsed) == 2: # PR #19: (streams, music) - streams, music = parsed - else: # older parser: streams + attribute - streams = parsed - music = getattr(awc_opus.parse_awc, "music", []) - bank_size, rows = len(d), [] - # A bank can hold two streams with the same id: list both, and note the name awc_opus exports the later - # one under, instead of letting it replace the first row. - for s, stem in zip(streams, awc_opus.export_stems([s["id"] for s in streams])): - row = _row(bank, s["id"], s["codec"], s["channels"], s["rate"], s["samples"], s["data"], bank_size, - False) - if stem != row["stream"]: - note = f"same id as an earlier stream in this bank; awc_opus exports it as {stem}" - row["notes"] = "; ".join(x for x in (row["notes"], note) if x) - rows.append(row) - for mus, data in music or []: - try: - channels = awc_opus.music_channels(d, mus, data, collect_packets=False) - except (ValueError, struct.error, IndexError) as e: - print(f"awc_manifest: warning: {bank}: music descriptor: {e}", file=sys.stderr) - continue - if not channels: - print(f"awc_manifest: warning: {bank}: ignored malformed streamed-music descriptor", - file=sys.stderr) - continue - for cid, samples, rate, codec, _packets, packet_channels in channels: - row = _row(bank, cid, codec, packet_channels, rate, samples, data, bank_size, True) - same = next((i for i, r in enumerate(rows) if r["stream"] == row["stream"]), None) - if same is None: - rows.append(row) - else: # as before: a streamed-music channel replaces a row with its id - rows[same] = row - return rows - - -def collect(src: str, *, out: str | None = None): - """(parsed bank count, rows, streamed-music row count); one warning per skipped bank. - - Malformed banks are reported on stderr and excluded from the bank count. I/O errors propagate so an - incomplete scan cannot replace a previous manifest. If out is given, refuse a report that would replace - any input bank before reading even the first bank (including malformed ones). - """ - recursive = os.path.isdir(src) - if recursive: - def scan_failed(error): - raise error - - banks = [] - for root, dirs, files in os.walk(src, onerror=scan_failed): - dirs.sort() - banks += [os.path.join(root, f) for f in files if f.lower().endswith(".awc")] - banks.sort(key=lambda p: (os.path.basename(p).lower(), p.lower())) - else: - banks = [src] - if out: - for path in banks: - if same_report_path(out, path): - raise ValueError(f"--out would overwrite the input {path}") - rows = [] - parsed = 0 - for path in banks: - try: - bank = os.path.relpath(path, src).replace(os.sep, "/") if recursive else os.path.basename(path) - rows += _bank_rows(path, bank) - parsed += 1 - except (ValueError, struct.error, IndexError) as e: - print(f"awc_manifest: warning: skipping {path}: {e}", file=sys.stderr) - rows.sort(key=lambda r: (r["bank"].lower(), int(r["stream"], 16))) - return parsed, rows, sum(1 for r in rows if r["streamed_music"]) - - -def write_manifest(rows: list, banks: int, streamed: int, fmt: str, out: str) -> None: - """Write to stdout, or publish a complete file over `out` so a failed replace keeps the previous - manifest instead of truncating it.""" - doc = {"bank_count": banks, "stream_count": len(rows), - "streamed_music_channel_count": streamed, "streams": rows} - - def _emit(f): - if fmt == "json": - json.dump(doc, f, indent=2) - f.write("\n") - else: - w = csv.DictWriter(f, fieldnames=FIELDS, lineterminator="\n") - w.writeheader() - for r in rows: - row = dict(r) - row["duration_s"] = "" if r["duration_s"] is None else f"{r['duration_s']:.6f}" - row["streamed_music"] = "yes" if r["streamed_music"] else "no" - w.writerow(row) - - if not out: - _emit(sys.stdout) - return - - destination = os.path.abspath(out) - folder = os.path.dirname(destination) or "." - os.makedirs(folder, exist_ok=True) - try: - mode = os.stat(destination).st_mode - except FileNotFoundError: - mode = None - except OSError: - # Non-regular destinations (pipes/devices) keep a direct write. - with open(destination, "w", encoding="utf-8", newline="") as f: - _emit(f) - return - if mode is not None: - # Retain the direct writer's permission check without truncating the report. - os.close(os.open(destination, os.O_WRONLY)) - - staged = tempfile.NamedTemporaryFile( - mode="w", encoding="utf-8", newline="", delete=False, - dir=folder, prefix=".awc_manifest-", suffix=".tmp", - ) - try: - with staged: - _emit(staged) - if os.name != "nt": - os.chmod(staged.name, published_mode(destination)) - replace_retry(staged.name, destination) - finally: - # The staging file may have inherited a read-only destination's mode; make it deletable - # first, or Windows strands it beside the manifest when the replace fails. - try: - os.chmod(staged.name, 0o600) - except OSError: - pass - try: - os.unlink(staged.name) - except FileNotFoundError: - pass - - -def main(argv=None) -> int: - ap = argparse.ArgumentParser( - description="Write a readable manifest of AWC bank streams; never exports audio.") - ap.add_argument("src", help=".awc file, or a directory scanned recursively for *.awc") - ap.add_argument("--out", help="write the manifest to this file instead of stdout") - ap.add_argument("--format", choices=("csv", "json"), - help="output format (default: csv, or json when --out ends in .json)") - a = ap.parse_args(argv) - if not os.path.exists(a.src): - print(f"awc_manifest: error: {a.src}: no such file or directory", file=sys.stderr) - return 2 - fmt = a.format or ("json" if a.out and a.out.lower().endswith(".json") else "csv") - try: - banks, rows, streamed = collect(a.src, out=a.out) - except ValueError as e: - print(f"awc_manifest: error: {e}", file=sys.stderr) - return 2 - except OSError as e: - print(f"awc_manifest: error: cannot read {e.filename or a.src}: {e.strerror or e}", file=sys.stderr) - return 1 - if not banks and not os.path.isdir(a.src): - # A named file that parsed as no bank is a wrong path or format, not an empty result; a directory scan - # keeps reporting 0 banks because scanning a folder with no bank in it is a valid answer. - print(f"awc_manifest: error: {a.src}: holds no AWC bank", file=sys.stderr) - return 2 - try: - write_manifest(rows, banks, streamed, fmt, a.out) - except OSError as e: - print(f"awc_manifest: error: cannot write {a.out or 'stdout'}: {e}", file=sys.stderr) - return 1 - print(f"{banks} banks, {len(rows)} streams, {streamed} streamed-music channels", file=sys.stderr) - return 0 - - -if __name__ == "__main__": - try: # a redirected stdout is strict ANSI code page under -I; write '?' for what it cannot encode - sys.stdout.reconfigure(errors="replace") - except (AttributeError, ValueError, OSError): - pass - sys.exit(main()) diff --git a/tools/awc_markers.py b/tools/awc_markers.py deleted file mode 100644 index 2fd8f2f45..000000000 --- a/tools/awc_markers.py +++ /dev/null @@ -1,241 +0,0 @@ -"""Count the marker events (tag 0xBD) of AWC banks: layout checks, type hashes and counts, never audio or names. - - python -I awc_markers.py [--out FILE.json] - -A 0xBD tag is a headerless array of 16-byte events (docs/audio_config.md; the same records as -rsc8_audio.decode_marker_records, which checks one tag, where this tool reports per type and per kind of bank): - - +0 u32 type (a 32-bit name hash) - +4 f32 value (a number for most types; a few types store a second u32 name hash here) - +8 u32 time (48 kHz frames from the start of the stream) - +12 u32 flags - -An archive is walked for `ADAT` banks with rsc8_audio.parse_adat_at_file, the same header parser and the same bank -set as rsc8_audio.scan_rpf, but each parsed bank is jumped over, so only the headers, the gaps between banks and the -marker tags are read (under a minute for the 28.5 GB audio.rpf on an NVMe drive). A directory is scanned -recursively for *.awc. An unreadable bank or directory fails the scan without publishing partial counts. - -Banks are reported in two groups: `streamed_music` (the bank has a 0x48 descriptor) and `other`. A chunk is compared -with the length of its own stream in 48 kHz frames: for streamed music the descriptor channel with the stream's id -(interleaved samples divided by the packet channel count, read from the TOC stereo bit of the channel's first -packet), otherwise the Opus format tag (samples / channels). Streams with neither have no length and are counted. - -The report holds counts, sizes, 32-bit hashes and numeric ranges only. -Usage: `python -I tools/awc_markers.py --help` lists the options. -""" -import argparse -import json -import os -import statistics -import struct -import sys - -sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) -from rsc8_audio import parse_adat_at_file # noqa: E402 - -TAG_MUSIC, TAG_DATA, TAG_FORMAT, TAG_MARKER = 0x48, 0x55, 0x76, 0xBD -EVENT = struct.Struct(" list: - """[(type, value bits, time, flags)] for the whole 16-byte events of one 0xBD chunk.""" - return list(EVENT.iter_unpack(chunk[:len(chunk) - len(chunk) % EVENT.size])) - - -def iter_banks(fh, size: int): - """Every `ADAT` bank of an open file in offset order; bytes inside a parsed bank are not searched. - - The file is searched a window at a time, and a window is kept while the next search starts inside it, so a - run of small banks is read about once and not once per bank. - """ - base, buf, pos = 0, b"", 0 - while pos < size: - if not (buf and base <= pos < base + WINDOW): - fh.seek(pos) - base, buf = pos, fh.read(WINDOW + 3) # +3: a magic that starts in this window and ends in the next - bank, at = None, buf.find(b"ADAT", pos - base) - while 0 <= at < WINDOW: - bank = parse_adat_at_file(fh, base + at, size) - if bank is not None: - break - at = buf.find(b"ADAT", at + 4) - if bank is None: - pos = base + WINDOW - continue - yield bank - pos = max(bank["end"], bank["offset"] + 4) - - -def _read(fh, at: int, size: int) -> bytes: - fh.seek(at) - return fh.read(size) - - -def music_frames(fh, base: int, mus, data) -> dict: - """{channel id: 48 kHz frames per channel} for one 0x48 descriptor, or {} when it does not parse.""" - desc = _read(fh, base + mus[0], mus[1]) - if len(desc) < 12: - return {} - channels = struct.unpack_from("= 30: - fmt = _read(fh, base + tm[TAG_FORMAT][0], 30) - if len(fmt) == 30 and fmt[28] == 0x0B and fmt[29]: - length = struct.unpack_from(" dict: - return {"banks": 0, "banks_with_chunk": 0, "chunks": 0, "chunks_not_multiple_of_16": 0, "events": 0, - "per_chunk": [], "chunks_time_decreases": 0, "chunks_with_length": 0, "chunks_past_end": 0, - "flags": {}, "types": {}} - - -def _add(group: dict, evs: list, size: int, length) -> None: - group["chunks"] += 1 - group["chunks_not_multiple_of_16"] += size % EVENT.size != 0 - group["events"] += len(evs) - group["per_chunk"].append(len(evs)) - times = [e[2] for e in evs] - group["chunks_time_decreases"] += any(b < a for a, b in zip(times, times[1:])) - if length is not None: - group["chunks_with_length"] += 1 - group["chunks_past_end"] += bool(times) and max(times) > length - here = {} - for typ, value, time, flags in evs: - group["flags"][flags] = group["flags"].get(flags, 0) + 1 - t = group["types"].setdefault(typ, {"events": 0, "chunks": 0, "chunks_with_one": 0, "max_per_chunk": 0, - "at_time_0": 0, "values": set()}) - t["events"] += 1 - t["at_time_0"] += time == 0 - t["values"].add(value) - here[typ] = here.get(typ, 0) + 1 - for typ, n in here.items(): - t = group["types"][typ] - t["chunks"] += 1 - t["chunks_with_one"] += n == 1 - t["max_per_chunk"] = max(t["max_per_chunk"], n) - - -def _finish(group: dict) -> dict: - per = group.pop("per_chunk") - group["events_per_chunk"] = {"min": min(per), "median": statistics.median(per), "max": max(per)} if per else None - group["flags"] = {f"0x{k:08X}": v for k, v in sorted(group["flags"].items())} - types = {} - for typ, t in sorted(group["types"].items(), key=lambda kv: (-kv[1]["events"], kv[0])): - bits = sorted(t.pop("values")) - values = [struct.unpack(" dict: - """The report for an archive, one bank or a directory of banks.""" - if os.path.isdir(src): - def scan_failed(error): - raise error - - paths = sorted(os.path.join(root, f) for root, _dirs, files in os.walk(src, onerror=scan_failed) - for f in files if f.lower().endswith(".awc")) - else: - paths = [src] - groups = {"streamed_music": _new_group(), "other": _new_group()} - banks = streams = 0 - for path in paths: - size = os.path.getsize(path) - with open(path, "rb") as fh: - for bank in iter_banks(fh, size): - banks += 1 - streams += bank["count"] - music, chunks = bank_chunks(fh, bank) - group = groups["streamed_music" if music else "other"] - group["banks"] += 1 - group["banks_with_chunk"] += bool(chunks) - for evs, chunk_size, length in chunks: - _add(group, evs, chunk_size, length) - return {"banks": banks, "streams": streams, **{name: _finish(g) for name, g in groups.items()}} - - -def main(argv=None) -> int: - ap = argparse.ArgumentParser(description="Count AWC marker events (tag 0xBD); hashes and counts only.") - ap.add_argument("src", help="an RPF9 archive, an .awc bank, or a directory scanned recursively for *.awc") - ap.add_argument("--out", help="write the full report (every type hash) to this JSON file") - a = ap.parse_args(argv) - if not os.path.exists(a.src): - print(f"awc_markers: error: {a.src}: no such file or directory", file=sys.stderr) - return 2 - try: - report = scan(a.src) - except OSError as error: - print(f"awc_markers: error: cannot read {error.filename or a.src}: {error.strerror or error}", file=sys.stderr) - return 1 - if a.out: - with open(a.out, "w", encoding="utf-8", newline="\n") as f: - json.dump(report, f, indent=2) - f.write("\n") - print(f"{report['banks']} banks, {report['streams']} streams") - for name in ("streamed_music", "other"): - g = report[name] - print(f"{name}: {g['banks']} banks, {g['banks_with_chunk']} with a 0xBD chunk; {g['chunks']} chunks, " - f"{g['events']} events, {len(g['types'])} types; size not a multiple of 16: " - f"{g['chunks_not_multiple_of_16']}; time decreases: {g['chunks_time_decreases']}; " - f"past the stream end: {g['chunks_past_end']} of {g['chunks_with_length']} with a length; " - f"flags: {g['flags']}") - for typ, t in list(g["types"].items())[:20]: - print(f" {typ} events {t['events']:>7} chunks {t['chunks']:>7} one per chunk {t['chunks_with_one']:>7}" - f" max per chunk {t['max_per_chunk']:>5} at time 0 {t['at_time_0']:>7}" - f" distinct values {t['distinct_values']:>5} " - + (f"{t['value_min']:g} .. {t['value_max']:g}" if t["values_all_integers"] - else " ".join(t.get("value_bits", ["not integers"])))) - if len(g["types"]) > 20: - print(f" ... {len(g['types']) - 20} more types (use --out)") - return 0 - - -if __name__ == "__main__": - try: # a redirected stdout is strict ANSI code page under -I; write '?' for what it cannot encode - sys.stdout.reconfigure(errors="replace") - except (AttributeError, ValueError, OSError): - pass - sys.exit(main()) diff --git a/tools/awc_names.py b/tools/awc_names.py deleted file mode 100644 index d56389dca..000000000 --- a/tools/awc_names.py +++ /dev/null @@ -1,511 +0,0 @@ -"""Name AWC streams by matching dictionary words against their 29-bit joaat stream ids. - -An AWC stream table stores ``joaat(lowercase name) & 0x1FFFFFFF`` per stream (docs/audio.md). With over a million -distinct ids in a 2^29 space, about 0.3% of arbitrary words collide by chance, so a hit alone is not trusted. A -name is accepted under one of two rules: - -``dialogue`` an exact dictionary word shaped like a dialogue wave, ``au_<4 letters>_``. -``family`` a name without its trailing ``_`` (the base) that hits ids in the same bank with several - numbered suffixes (``''``, ``_00`` .. ``_40``, ``_1`` .. ``_9``): at least 3 members, or 2 with adjacent - numbers. The base must be made of common tokens (each in at least ``--min-token`` dictionary words), and - at least one member must be a dictionary word itself. - -Every run repeats the attack with a salt prepended to each word (``zq``): those names cannot be right, so their -accepted count estimates the false names. Per source, the dialogue rule is kept only if its control is under 2% of -its real count, and the family rule uses the smallest family size whose control is under 2%. - -Dictionary sources: - -``--words`` a text file with one word per line, or a ``hashdict.py`` JSON (its values are used); -``--conversations`` files or directories whose conversation data pairs a dialogue key with line labels - (``AU_\\0] -Usage: `python -I tools/batch_glb.py --help` lists the options. - -A matched texture is also reported as unembedded when none of its primitives has UV coordinates. -""" -from __future__ import annotations - -import argparse -import concurrent.futures -import os -import sys -import threading -import time - -sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) -import glb_writer -import dds_png - - -def _existing_texture_dir(value: str) -> str: - """--textures must name a directory: a typo otherwise silently embedded nothing and still exited 0.""" - if not os.path.isdir(value): - raise argparse.ArgumentTypeError(f"not a directory: {value}") - return value - - -def _build_texture_index(texture_dir: str | None) -> dict[str, str]: - """Index available texture files (.png and .dds) by lowercase basename without extension.""" - if not texture_dir: - return {} - index: dict[str, str] = {} - for entry in os.scandir(texture_dir): - if not entry.is_file(): - continue - lower = entry.name.lower() - if lower.endswith(".png") or lower.endswith(".dds"): - stem = os.path.splitext(lower)[0] - # Prefer png over dds if both exist - if stem not in index or lower.endswith(".png"): - index[stem] = entry.path - return index - - -def _load_png_bytes(tex_path: str, max_size: int = 0) -> tuple[bytes | None, str]: - """(PNG bytes from file or DDS decode, or None and why it cannot be embedded: a texture the model - can live without is skipped and reported, never a silent hole in the output).""" - lower = tex_path.lower() - if lower.endswith(".png"): - try: - with open(tex_path, "rb") as f: - data = f.read() - except OSError as exc: - return None, str(exc) - if not data: - return None, "the PNG file is empty" - return data, "" - elif lower.endswith(".dds"): - try: - data = dds_png.dds_file_to_png_bytes(tex_path, max_size=max_size) - except Exception as exc: - return None, f"DDS decode: {exc}" - if not data: - return None, "DDS decode produced no bytes" - return data, "" - return None, "not a .png or .dds" - - -class TextureCache: - """Thread-safe (bytes, reason) per texture path, so the batch decodes a broken DDS once even when two - worker threads reach the same file at the same time (the pool runs one model per thread).""" - - def __init__(self) -> None: - self._lock = threading.Lock() - self._entries: dict[str, tuple[bytes | None, str]] = {} - - def get_or_load(self, path: str, max_size: int = 0) -> tuple[bytes | None, str]: - with self._lock: - if path not in self._entries: - self._entries[path] = _load_png_bytes(path, max_size=max_size) - return self._entries[path] - - -def convert_single( - args_tuple: tuple[str, str, str, dict[str, str], int, TextureCache], -) -> tuple[bool, str, str, list[tuple[str, str]]]: - in_path, out_path, up_axis, tex_index, max_tex_size, tex_cache = args_tuple - dropped: list[tuple[str, str]] = [] - dropped_seen: set[str] = set() - try: - primitives = glb_writer.parse_obj(in_path, is_path=True, up_axis=up_axis) - materials: dict[str, dict] = {} - - if tex_index: - base_stem = os.path.splitext(os.path.basename(in_path))[0].lower() - # Clean possible hash suffix like 'ambient_femalebb._ft_at_...' -> 'ambient_femalebb' - clean_stem = base_stem.split(".")[0] - texture_has_uv: dict[str, bool] = {} - - for prim in primitives: - mat_name = prim.get("material", "") - lookup_keys = [] - if mat_name: - lookup_keys.extend([ - mat_name.lower(), - f"{mat_name.lower()}_d", - f"{mat_name.lower()}_diff", - ]) - lookup_keys.extend([ - base_stem, - clean_stem, - f"{clean_stem}_d", - f"{clean_stem}_diff", - ]) - - found_path = None - for key in lookup_keys: - if key in tex_index: - found_path = tex_index[key] - break - - if found_path: - png_bytes, why_not = tex_cache.get_or_load(found_path, max_size=max_tex_size) - if why_not and found_path not in dropped_seen: - dropped_seen.add(found_path) # one line per texture per model, not per primitive - dropped.append((found_path, why_not)) - if png_bytes: - texture_has_uv[found_path] = texture_has_uv.get(found_path, False) or bool(prim.get("uvs")) - materials[mat_name] = { - "name": mat_name or clean_stem, - "png_bytes": png_bytes, - } - dropped.extend((path, "matching primitives have no texture coordinates") - for path, has_uv in texture_has_uv.items() if not has_uv) - - glb_writer.write_glb(out_path, primitives, materials=materials if materials else None) - return True, in_path, "", dropped - except Exception as exc: - return False, in_path, str(exc), dropped - - -def batch_convert( - in_dir: str, - out_dir: str, - up_axis: str = "z", - jobs: int | None = None, - texture_dir: str | None = None, - max_tex_size: int = 0, -) -> dict[str, int]: - if not os.path.isdir(in_dir): - raise ValueError(f"Input directory does not exist: {in_dir}") - - os.makedirs(out_dir, exist_ok=True) - obj_files = [ - f for f in os.listdir(in_dir) if f.lower().endswith(".obj") and os.path.isfile(os.path.join(in_dir, f)) - ] - - tex_index = _build_texture_index(texture_dir) - tex_cache = TextureCache() - - tasks = [ - ( - os.path.join(in_dir, f), - os.path.join(out_dir, os.path.splitext(f)[0] + ".glb"), - up_axis, - tex_index, - max_tex_size, - tex_cache, - ) - for f in obj_files - ] - - total = len(tasks) - succeeded = 0 - failed = 0 - failures: list[tuple[str, str]] = [] # (model, error): counted and named - dropped_textures: list[tuple[str, str, str]] = [] - - max_workers = jobs if jobs and jobs > 0 else (os.cpu_count() or 4) - - with concurrent.futures.ThreadPoolExecutor(max_workers=max_workers) as executor: - for ok, path, err, dropped in executor.map(convert_single, tasks): - if ok: - succeeded += 1 - else: - failed += 1 - failures.append((path, err)) - dropped_textures.extend((path, tex, why) for tex, why in dropped) - - return { - "total": total, - "succeeded": succeeded, - "failed": failed, - "failures": failures, - "dropped_textures": dropped_textures, - } - - -def _positive_jobs(value: str) -> int: - jobs = int(value) - if jobs <= 0: - raise argparse.ArgumentTypeError(f"must be a positive integer (got {value!r})") - return jobs - - -def _non_negative_int(value: str) -> int: - num = int(value) - if num < 0: - raise argparse.ArgumentTypeError(f"must be >= 0 (got {value!r})") - return num - - -def main(argv: list[str] | None = None) -> int: - parser = argparse.ArgumentParser( - description="Batch convert Wavefront OBJ models to binary glTF 2.0 (.glb)." - ) - parser.add_argument("in_dir", help="Directory containing .obj files") - parser.add_argument("out_dir", help="Output directory for .glb files") - parser.add_argument( - "--jobs", - type=_positive_jobs, - default=None, - help="Number of parallel worker threads (default: CPU count)", - ) - parser.add_argument( - "--up", - choices=("z", "y"), - default="z", - help="Source up axis: 'z' converts RAGE Z-up to glTF Y-up (default), 'y' keeps Y-up", - ) - parser.add_argument( - "--textures", - type=_existing_texture_dir, - default=None, - help="Optional directory containing textures (.png or .dds) to link and embed", - ) - parser.add_argument( - "--max-tex-size", - type=_non_negative_int, - default=0, - help="Max texture dimension in pixels when decoding DDS (0 = unconstrained)", - ) - - args = parser.parse_args(argv) - t0 = time.monotonic() - try: - stats = batch_convert( - args.in_dir, - args.out_dir, - up_axis=args.up, - jobs=args.jobs, - texture_dir=args.textures, - max_tex_size=args.max_tex_size, - ) - except (ValueError, OSError) as exc: - print(f"ERROR: {exc}", file=sys.stderr) - return 1 - elapsed = time.monotonic() - t0 - - for path, err in stats["failures"]: - print(f"batch_glb: {path}: {err}") - for model, tex, why in stats["dropped_textures"]: - print(f"batch_glb: {os.path.basename(model)}: texture {tex} not embedded: {why}") - dropped = len(stats["dropped_textures"]) - note = f", {dropped} unembedded texture" + ("" if dropped == 1 else "s") if dropped else "" - print( - f"batch_glb: converted {stats['succeeded']}/{stats['total']} models " - f"({stats['failed']} failed{note}) in {elapsed:.2f}s" - ) - return 0 if stats["failed"] == 0 else 1 - - -if __name__ == "__main__": - sys.stdout.reconfigure(errors="replace") - sys.exit(main()) diff --git a/tools/bc_feature.py b/tools/bc_feature.py deleted file mode 100644 index 613d9678a..000000000 --- a/tools/bc_feature.py +++ /dev/null @@ -1,54 +0,0 @@ -"""Vectorised per-block average colour for BC1 and the colour half of BC3. - -Endpoints and palette colours are computed in floating point. The averages can differ from GPU readback -when the hardware quantizes the decoded RGB values. -""" -import numpy as np - - -def _565(c): - r = ((c >> 11) & 31).astype(np.float32) * (255 / 31) - g = ((c >> 5) & 63).astype(np.float32) * (255 / 63) - b = (c & 31).astype(np.float32) * (255 / 31) - return np.stack([r, g, b], -1) - - -def _color_average(blocks: np.ndarray, force_four_colors: bool = False) -> np.ndarray: - c0 = blocks[:, 0].astype(np.uint32) | (blocks[:, 1].astype(np.uint32) << 8) - c1 = blocks[:, 2].astype(np.uint32) | (blocks[:, 3].astype(np.uint32) << 8) - p0, p1 = _565(c0), _565(c1) - four = (force_four_colors | (c0 > c1))[:, None] - p2 = np.where(four, (2 * p0 + p1) / 3, (p0 + p1) / 2) - p3 = np.where(four, (p0 + 2 * p1) / 3, 0) - idx = blocks[:, 4:8].astype(np.uint32) - bits = idx[:, 0] | (idx[:, 1] << 8) | (idx[:, 2] << 16) | (idx[:, 3] << 24) - counts = np.zeros((len(blocks), 4), np.float32) - for k in range(16): - sel = (bits >> (2 * k)) & 3 - counts[np.arange(len(blocks)), sel] += 1 - pal = np.stack([p0, p1, p2, p3], 1) # (N, 4, 3) - return (pal * counts[:, :, None]).sum(1) / 16 - - -def bc1_average(blocks: np.ndarray) -> np.ndarray: - """blocks: (N, 8) uint8 -> (N, 3) float average colour of the 16 decoded pixels.""" - if blocks.ndim != 2 or blocks.shape[1] != 8: - raise ValueError(f"bc1_average expects shape (N, 8), got {blocks.shape}") - return _color_average(blocks) - - -def block_average(blocks: np.ndarray, bpe: int) -> np.ndarray: - if bpe not in (8, 16): - raise ValueError(f"unsupported block size bpe={bpe} (expected 8 or 16)") - if blocks.ndim != 2 or blocks.shape[1] != bpe: - raise ValueError(f"block_average(bpe={bpe}) expects shape (N, {bpe}), got {blocks.shape}") - if bpe == 8: - return bc1_average(blocks) - # BC3 colour uses four entries regardless of endpoint order (EXT_texture_compression_s3tc). - return _color_average(blocks[:, 8:16], force_four_colors=True) - - -def smoothness(img: np.ndarray) -> float: - """Neighbour difference relative to the image's own spread (lower = more coherent).""" - d = np.abs(np.diff(img, axis=0)).mean() + np.abs(np.diff(img, axis=1)).mean() - return float(d / (img.std() + 1e-6)) diff --git a/tools/bcpack.py b/tools/bcpack.py deleted file mode 100644 index af87bfb08..000000000 --- a/tools/bcpack.py +++ /dev/null @@ -1,1488 +0,0 @@ -"""Clean-room BCPack bitstream decoder (Python standard library only). - -Implements the Xbox Series DirectStorage BCPack entropy layer (interleaved -12/16-lane 16-bit rANS with 8-byte/cycle prefetch scheduling and exponential -frequency tables) and block rebuilders for all six active modes: BC1, BC3, -BC4, BC5, BC6H and BC7 (codecs 1, 3, 4, 5, 6 and 7). - -Codec identifiers follow `DSTORAGE_BCPACK_MODE` (matching `tools/ttpf_mips.py` -and `docs/textures.md`): - 1 = BC1, 3 = BC3, 4 = BC4, 5 = BC5, 6 = BC6H, 7 = BC7. - -Strict decoding (`decode(..., allow_provisional=False)`, the default) refuses -any chunk that depends on an unconfirmed built-in history entry or inferred BC7 -signature. Pass `allow_provisional=True` (or use `decode_with_info`) to allow -provisional entries and inspect which ones were used. - -See `docs/textures.md` for the bitstream specification and provenance. -""" -import os -import struct -import sys - -sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) -import bcpack_tables as _tables # noqa: E402 -import bcpack_tables_bptc as _bptc # noqa: E402 - -# rANS and lane-array constants -RANS_L = 1 << 24 -MAX_WIDTH = 10 -PREFETCH_BUDGET = 8 -MAX_VIRTUAL_ZEROS = 8 - -CODEC_NAMES = { - 1: "BC1", - 3: "BC3", - 4: "BC4", - 5: "BC5", - 6: "BC6H", - 7: "BC7", -} - -# Bytes represented by one lane symbol-tuple (BC3/BC5/BC6H/BC7 use 2 elements per 16-byte block). -ELEMENT_BYTES = 8 - -BLOCK_BYTES = { - 1: 8, - 3: 16, - 4: 8, - 5: 16, - 6: 16, - 7: 16, -} - -# Default per-lane symbol widths (bits) for each DSTORAGE_BCPACK_MODE. -LANE_WIDTHS = { - 1: (8, 8, 5, 6, 5, 5, 6, 5, 8, 8, 8, 8), - 3: (4, 4, 8, 6, 6, 6, 6, 5, 6, 5, 8, 8), - 4: (8, 8, 8, 8, 6, 6, 6, 6, 6, 6, 6, 6), - 5: (4, 4, 8, 8, 6, 6, 6, 6, 6, 6, 6, 6), - 6: (4, 4, 8, 8, 8, 5, 5, 5, 6, 6, 6, 8, 8, 8, 8, 5), - 7: (4, 4, 8, 8, 8, 8, 8, 7, 7, 5, 6, 8, 8, 8, 8, 5), -} - -ALL_CODECS = frozenset(CODEC_NAMES) -SUPPORTED_REBUILD_CODECS = frozenset({1, 3, 4, 5, 6, 7}) - - -class BcpackError(ValueError): - """Raised when a BCPack stream fails structural or rANS validation.""" - - -class BcpackProvisionalError(BcpackError): - """Raised when strict decoding encounters an unconfirmed or unknown history entry.""" - - -class BcpackUnsupportedCodec(NotImplementedError): - """Raised when a BCPack codec has no block rebuilder yet.""" - - -class _Model: - """16-bit rANS banded frequency model for one (symbol_width, q) pair.""" - - __slots__ = ("w", "freq", "base") - - def __init__(self, w, freq): - self.w = w - self.freq = freq - base = [] - acc = 0 - for p, f in enumerate(freq): - base.append(acc) - acc += f * (1 if p == 0 else 1 << (p - 1)) - if acc != 65536: - raise BcpackError(f"probability table ({w}) does not sum to 65536 (got {acc})") - self.base = tuple(base) - - def lookup(self, cf): - p = self.w - base = self.base - while p > 0 and cf < base[p]: - p -= 1 - return 0 if p == 0 else (1 << (p - 1)) + (cf - base[p]) // self.freq[p] - - def advance(self, s, x): - p = s.bit_length() - f = self.freq[p] - c = self.base[p] + f * (s - (0 if p == 0 else 1 << (p - 1))) - if c == 0: - f, c = f - 1, 1 - return f * (x >> 16) + (x & 0xFFFF) - c - - -_MODEL_CACHE = {} - - -def _get_model(w, q): - key = (w, q) - m = _MODEL_CACHE.get(key) - if m is None: - freq = _tables.PROB_TABLES.get(key) - if freq is None: - return None - m = _Model(w, freq) - _MODEL_CACHE[key] = m - return m - - -def _decode_lanes_raw(raw, widths, nsym): - """Decode the interleaved rANS lane array into one symbol list per lane. - - Returns `(lanes, bytes_used)`. Raises `BcpackError` if any fragment fails - to land at the exact rANS lower bound `RANS_L`, runs out of input, or - produces an out-of-range symbol. - """ - nl = len(widths) - HDR0, HDR1, HDR2, PROC = 0, 1, 2, 3 - L = RANS_L - ctrl = [HDR0] * nl - out_rem = [nsym] * nl - w = [0] * nl - q = [0] * nl - h3 = [0] * nl - flush = [0] * nl - done = [nsym <= 0] * nl - full = [False] * nl - held = [False] * nl - vz = [0] * nl - inbuf = [0] * nl - sym = [0] * nl - in_rem = [0] * nl - p0 = [0] * nl - p1 = [0] * nl - model = [None] * nl - slotfull = [False] * nl - slotval = [0] * nl - stall = [False] * nl - out = [[] for _ in range(nl)] - pos = 0 - nraw = len(raw) - - def fail(msg, lane): - raise BcpackError( - f"lane {lane} (width {w[lane]}, q {q[lane]}) at input byte {pos}: {msg}" - ) - - while True: - if all(done[i] and not slotfull[i] for i in range(nl)): - return out, pos - - # Phase 1: state update, prefetch arbitration (at most 8 bytes/cycle), - # and symbol release for non-stalled lanes. - left = PREFETCH_BUDGET - for i in range(nl): - if done[i]: - stall[i] = True - continue - if held[i] and slotfull[i]: - stall[i] = True - continue - stall[i] = False - if ctrl[i] == PROC: - p0[i] = model[i].advance(sym[i], p1[i]) if held[i] else p1[i] - if not full[i] and (ctrl[i] != PROC or in_rem[i] > 0): - if left == 0: - stall[i] = True - continue - if pos >= nraw: - fail("input ran out", i) - inbuf[i] = raw[pos] - pos += 1 - full[i] = True - left -= 1 - if held[i]: - slotfull[i] = True - slotval[i] = sym[i] - held[i] = False - - # Phase 2: header parsing, byte merge, virtual zero fill on flush, and symbol lookup. - for i in range(nl): - if done[i] or stall[i]: - continue - c = ctrl[i] - if c == HDR0: - if not full[i]: - continue - h = inbuf[i] - q[i] = h & 15 - flush[i] = (h >> 4) & 1 - h3[i] = (h >> 5) & 1 - w[i] = widths[i] - (h >> 6) - full[i] = False - ctrl[i] = HDR1 - vz[i] = 0 - elif c == HDR1: - if not full[i]: - continue - full[i] = False - wi = w[i] - if not 1 <= wi <= MAX_WIDTH: - fail("symbol width out of range", i) - m = _get_model(wi, q[i]) - if m is None: - fail("probability table for this width and q is not known", i) - model[i] = m - if h3[i]: - in_rem[i] = inbuf[i] - ctrl[i] = HDR2 - else: - in_rem[i] = inbuf[i] + 1 - ctrl[i] = PROC - elif c == HDR2: - if not full[i]: - continue - in_rem[i] = ((inbuf[i] << 8) | (in_rem[i] & 0xFF)) + 257 - ctrl[i] = PROC - full[i] = False - else: - st = p0[i] - if st < L: - if in_rem[i] > 0: - if full[i]: - st = (st << 8) | inbuf[i] - in_rem[i] -= 1 - full[i] = False - if in_rem[i] == 0 and flush[i]: - while st < L and st != 0 and vz[i] < MAX_VIRTUAL_ZEROS: - st <<= 8 - vz[i] += 1 - elif flush[i]: - if st == 0 or vz[i] >= MAX_VIRTUAL_ZEROS: - fail("fragment did not end at its home state", i) - while st < L and st != 0 and vz[i] < MAX_VIRTUAL_ZEROS: - st <<= 8 - vz[i] += 1 - else: - p1[i] = st - if out_rem[i] > 0: - ctrl[i] = HDR0 - else: - done[i] = True - continue - nxt = st > L and out_rem[i] > 0 - if nxt: - s = model[i].lookup(st & 0xFFFF) - sym[i] = s - out_rem[i] -= 1 - if s >> w[i]: - fail("symbol outside its width", i) - held[i] = nxt - p1[i] = st - if in_rem[i] == 0: - if flush[i]: - if st == L: - if out_rem[i] > 0: - ctrl[i] = HDR0 - p0[i] = 0 - p1[i] = 0 - else: - done[i] = True - elif st > L and not nxt: - fail("fragment did not end at its home state", i) - elif out_rem[i] == 0 and not nxt: - done[i] = True - elif st == L: - fail("fragment did not end at its home state", i) - elif st == L or (out_rem[i] == 0 and not nxt and st > L): - fail("fragment did not end at its home state", i) - - # Phase 3: emit one synchronized element when every active lane has filled its slot. - ready = True - anyfull = False - for i in range(nl): - if slotfull[i]: - anyfull = True - elif not (done[i] and not held[i]): - ready = False - break - if ready and anyfull: - for i in range(nl): - if slotfull[i]: - out[i].append(slotval[i]) - slotfull[i] = False - for i in range(nl): - if done[i] and held[i] and not slotfull[i]: - slotfull[i] = True - slotval[i] = sym[i] - held[i] = False - - -_NATIVE = [] - - -def _native_unpack(): - """`(unpack_model, tables)` of the optional Rust lane decoder, or None. - - `tools/bcpack_calibration` (built with Cargo, see its README.md) exports - `unpack_model`, a port of `_decode_lanes_raw` that is fed this module's - probability tables, so it accepts the same streams and gives the same - symbols. Set `LEONIDA_BCPACK_NATIVE=0` to use Python only. - """ - if not _NATIVE: - found = None - if os.environ.get("LEONIDA_BCPACK_NATIVE", "1") != "0": - import ctypes - name = {"win32": "bcpack_calibration.dll", - "darwin": "libbcpack_calibration.dylib"}.get(sys.platform, "libbcpack_calibration.so") - path = os.path.join(os.path.dirname(os.path.abspath(__file__)), - "bcpack_calibration", "target", "release", name) - if os.path.isfile(path): - try: - lib = ctypes.CDLL(path) - fn = lib.unpack_model - blocks = lib.decode_blocks - except (OSError, AttributeError): - fn = None - if fn is not None: - fn.argtypes = [ctypes.c_char_p, ctypes.c_size_t, ctypes.c_char_p, ctypes.c_size_t, - ctypes.c_size_t, ctypes.c_void_p, ctypes.c_size_t, ctypes.c_void_p] - fn.restype = ctypes.c_ssize_t - side = MAX_WIDTH + 1 - flat = [-1] * (side * 16 * side) - for (w, q), freq in _tables.PROB_TABLES.items(): - if 0 <= w <= MAX_WIDTH and 0 <= q < 16 and len(freq) == w + 1: - flat[(w * 16 + q) * side:(w * 16 + q) * side + w + 1] = freq - blocks.argtypes = [ctypes.c_char_p, ctypes.c_size_t, ctypes.c_uint32, ctypes.c_char_p, - ctypes.c_size_t, ctypes.c_size_t, ctypes.c_void_p, ctypes.c_size_t, - ctypes.c_char_p, ctypes.c_size_t, ctypes.c_void_p, ctypes.c_size_t, - ctypes.c_void_p, ctypes.c_size_t] - blocks.restype = ctypes.c_ssize_t - found = fn, (ctypes.c_int32 * len(flat))(*flat), blocks - _NATIVE.append(found) - return _NATIVE[0] - - -def _decode_lanes_native(raw, widths, nsym): - """`(lanes, bytes_used)` from the Rust port of `_decode_lanes_raw`, or None. - - None means the library is not built or the stream is refused (or is one - the port leaves to Python); `decode_lanes` then runs the Python model, - which raises its usual error. `tests/test_bcpack_native.py` checks that the - two agree. - """ - native = _native_unpack() - if native is None or nsym <= 0: - return None - import ctypes - fn, tables, _ = native - nl = len(widths) - data = bytes(raw) - out = (ctypes.c_uint16 * (nsym * nl))() - used = fn(data, len(data), bytes(widths), nl, nsym, tables, len(tables), out) - if used < 0: - return None - flat = memoryview(out).cast("B").cast("H") - return [flat[i * nsym:(i + 1) * nsym].tolist() for i in range(nl)], used - - -_NATIVE_BLOCKS = { - # codec: (lookup table bytes, confirmed defaults, provisional defaults, values per entry) - 1: (lambda: bytes(_tables.BC1_QUADRANT), "BC1_HISTORY_CONFIRMED", "BC1_HISTORY_PROVISIONAL", 6), - 3: (lambda: bytes(v for pair in _tables.BC3_ALPHA_PAIR for v in pair) + bytes(_tables.BC3_COLOUR_QUADRANT), - "BC3_HISTORY_CONFIRMED", "BC3_HISTORY_PROVISIONAL", 8), - 4: (lambda: bytes(v for pair in _tables.BC4_PAIR for v in pair), "BC4_HISTORY_CONFIRMED", - "BC4_HISTORY_PROVISIONAL", 2), - 5: (lambda: bytes(v for pair in _tables.BC5_PAIR for v in pair), "BC5_HISTORY_CONFIRMED", - "BC5_HISTORY_PROVISIONAL", 4), -} -_NATIVE_BUILTIN = {} - - -def _decode_blocks_native(raw, codec, out_size, history): - """BC1/BC3/BC4/BC5 bytes from the Rust lanes + strict rebuild, or None to decode in Python. - - Rust only takes the strict path: a stream it refuses, a non-zero lane 1 or - a history entry that is not confirmed returns None, and Python decodes the - chunk itself, so its errors and provisional entries are unchanged. - """ - native = _native_unpack() - spec = _NATIVE_BLOCKS.get(codec) - if native is None or spec is None or out_size <= 0 or out_size % BLOCK_BYTES[codec]: - return None - import ctypes - _, tables, blocks = native - lut, conf_name, prov_name, k = spec - cached = _NATIVE_BUILTIN.get(codec) if history is None else None - if cached is None: - try: - confirmed, _ = _resolve_bc_history( - codec, getattr(_tables, conf_name), getattr(_tables, prov_name), history) - except (ValueError, TypeError, OSError): - return None # Python reads the same history after the lanes, so its error order is unchanged - flat = [-1] * (256 * k) - for entry, values in confirmed.items(): - if 0 <= entry < 256 and len(values) == k: - flat[entry * k:entry * k + k] = values - cached = lut(), (ctypes.c_int32 * len(flat))(*flat) - if history is None: - _NATIVE_BUILTIN[codec] = cached - table, builtin = cached - widths = LANE_WIDTHS[codec] - data = bytes(raw) - out = ctypes.create_string_buffer(out_size) - used = blocks(data, len(data), codec, bytes(widths), len(widths), out_size // ELEMENT_BYTES, - tables, len(tables), table, len(table), builtin, len(builtin), out, out_size) - return out.raw if used >= 0 else None - - -def decode_lanes(raw, codec, out_size): - """Entropy layer: decode `raw` into per-lane symbol lists and bytes consumed. - - Works for all six active codecs (`1, 3, 4, 5, 6, 7`). Trailing non-zero - bytes after the last lane finishes are rejected. Uses the Rust decoder when - it is built (`_native_unpack`) and Python for the streams it refuses. - """ - if codec not in LANE_WIDTHS: - raise BcpackError(f"unsupported BCPack codec id: {codec}") - if out_size < 0 or out_size % BLOCK_BYTES[codec] != 0: - raise BcpackError( - f"decoded size {out_size} is not a whole number of {CODEC_NAMES[codec]} blocks" - ) - nsym = out_size // ELEMENT_BYTES - fast = _decode_lanes_native(raw, LANE_WIDTHS[codec], nsym) - if fast is not None: - return fast - data = memoryview(raw) - lanes, used = _decode_lanes_raw(data, LANE_WIDTHS[codec], nsym) - if any(data[used:]): - raise BcpackError("non-zero data left over after the last lane finished") - return lanes, used - - -def _unzig(v): - return -((v + 1) >> 1) if (v & 1) else (v >> 1) - - -def _inter(a, b, n): - d = 0 - for k in range(n): - d |= (((a >> k) & 1) << (2 * k)) | (((b >> k) & 1) << (2 * k + 1)) - return d - - -def _inter8(a, b): - return _inter(a, b, 4) - - -# 4-bit de-interleave lookup tables for 8-bit index-pair symbols (even / odd bits). -_DEINT = ( - tuple( - ((s >> 0) & 1) | (((s >> 2) & 1) << 1) | (((s >> 4) & 1) << 2) | (((s >> 6) & 1) << 3) - for s in range(256) - ), - tuple( - ((s >> 1) & 1) | (((s >> 3) & 1) << 1) | (((s >> 5) & 1) << 2) | (((s >> 7) & 1) << 3) - for s in range(256) - ), -) - - -def _loose_limit(nblocks): - """Maximum undetermined blocks permitted in provisional mode (1 in 1,024, min 2).""" - return max(2, nblocks // 1024) - - -def _unknown_blocks(e_roots, i_roots, unknown_e, unknown_i): - """Blocks whose endpoint or index history root is an unknown entry. A block can depend on one of each, and - it is one undetermined block, not two, against `_loose_limit`.""" - return sum(1 for e, i in zip(e_roots, i_roots) if e in unknown_e or i in unknown_i) - - -def _resolve_bc_history(codec, default_confirmed, default_provisional, history): - """Merge or replace BC1/BC3/BC4/BC5 history tables when external `history` is provided.""" - loaded = _bptc.load_bc_history(codec, history) - if loaded is None: - return default_confirmed, default_provisional - ext_conf, ext_prov, replace = loaded - if replace: - confirmed = dict(ext_conf) - loose = {k: v for k, v in ext_prov.items() if k not in confirmed} - return confirmed, loose - confirmed = dict(default_confirmed) - confirmed.update(ext_conf) - loose = {k: v for k, v in default_provisional.items() if k not in confirmed} - for k, v in ext_prov.items(): - if k not in confirmed: - loose[k] = v - return confirmed, loose - - -def _bc1_blocks(lanes, nblocks, provisional, *, history=None): - if any(lanes[1]): - raise BcpackError("BC1 lane 1 is non-zero (unexpected)") - quad = _tables.BC1_QUADRANT - confirmed, loose = _resolve_bc_history( - 1, _tables.BC1_HISTORY_CONFIRMED, _tables.BC1_HISTORY_PROVISIONAL, history - ) - out = bytearray(nblocks * 8) - hist = [None] * nblocks - mods = (32, 64, 32, 32, 64, 32) - l0 = lanes[0] - cols = lanes[2:8] - q0, q1, q2, q3 = lanes[8:12] - for i in range(nblocks): - v = l0[i] - d = 256 - ((v + 1) >> 1) if (v & 1) else (v >> 1) - if d == 0: - base = (0, 0, 0, 0, 0, 0) - elif i - d >= 0: - base = hist[i - d] - else: - entry = 256 + i - d - base = confirmed.get(entry) - if base is None: - if provisional is not None and entry in loose: - base = loose[entry] - provisional.add(f"BC1 history {entry}") - else: - state = "unconfirmed" if entry in loose else "unknown" - raise BcpackProvisionalError( - f"BC1 block {i} references {state} built-in history entry {entry}" - ) - e0 = (base[0] + _unzig(cols[0][i])) % mods[0] - e1 = (base[1] + _unzig(cols[1][i])) % mods[1] - e2 = (base[2] + _unzig(cols[2][i])) % mods[2] - e3 = (base[3] + _unzig(cols[3][i])) % mods[3] - e4 = (base[4] + _unzig(cols[4][i])) % mods[4] - e5 = (base[5] + _unzig(cols[5][i])) % mods[5] - hist[i] = (e0, e1, e2, e3, e4, e5) - c0 = (e0 << 11) | (e1 << 5) | e2 - c1 = (e3 << 11) | (e4 << 5) | e5 - a, b, c, dd = quad[q0[i]], quad[q1[i]], quad[q2[i]], quad[q3[i]] - # Quadrant byte: pixels TL, TR, BL, BR in bits 0-1, 2-3, 4-5, 6-7. - struct.pack_into( - "> 4) | ((b >> 4) << 4), - (c & 15) | ((dd & 15) << 4), - (c >> 4) | ((dd >> 4) << 4), - ) - return bytes(out) - - -_BC3_MODS = (256, 256, 32, 64, 32, 32, 64, 32) -_BC3_NONE = (128, 128, 0, 0, 0, 0, 0, 0) - - -def _bc3_blocks(lanes, nblocks, provisional, *, history=None): - if any(lanes[1]): - raise BcpackError("BC3 lane 1 is non-zero (unexpected)") - pairs = _tables.BC3_ALPHA_PAIR - quads = _tables.BC3_COLOUR_QUADRANT - confirmed, loose = _resolve_bc_history( - 3, _tables.BC3_HISTORY_CONFIRMED, _tables.BC3_HISTORY_PROVISIONAL, history - ) - out = bytearray(nblocks * 16) - hist = [None] * nblocks - lost = [False] * nblocks - l0, alpha = lanes[0], lanes[2] - rows = lanes[3:7] - lr, lg, lb = lanes[7], lanes[8], lanes[9] - top, bottom = lanes[10], lanes[11] - unknown = set() - mods = _BC3_MODS - for i in range(nblocks): - a, b = 2 * i, 2 * i + 1 - d = _unzig(_inter8(l0[a], l0[b])) & 255 - if d == 0: - base = _BC3_NONE - elif i - d >= 0: - base = hist[i - d] - lost[i] = lost[i - d] - else: - entry = 256 + i - d - base = confirmed.get(entry) - if base is None and entry in loose: - if provisional is None: - raise BcpackProvisionalError( - f"BC3 block {i} references unconfirmed built-in history entry {entry}" - ) - base = loose[entry] - provisional.add(f"BC3 history {entry}") - if base is None: - if provisional is None: - raise BcpackProvisionalError( - f"BC3 block {i} references unknown built-in history entry {entry}" - ) - base = _BC3_NONE - lost[i] = True - unknown.add(entry) - dz = (alpha[a], alpha[b], lr[a], lg[a], lb[a], lr[b], lg[b], lb[b]) - e = tuple((base[k] + _unzig(dz[k])) % mods[k] for k in range(8)) - hist[i] = e - bits = 0 - for r in range(4): - left, right = pairs[rows[r][a]], pairs[rows[r][b]] - bits |= (left[0] | (left[1] << 3) | (right[0] << 6) | (right[1] << 9)) << (12 * r) - at = i * 16 - out[at] = e[0] - out[at + 1] = e[1] - out[at + 2:at + 8] = bits.to_bytes(6, "little") - c0 = (e[2] << 11) | (e[3] << 5) | e[4] - c1 = (e[5] << 11) | (e[6] << 5) | e[7] - qa, qb = quads[top[a]], quads[top[b]] - qc, qd = quads[bottom[a]], quads[bottom[b]] - struct.pack_into( - "> 4) | ((qb >> 4) << 4), - (qc & 15) | ((qd & 15) << 4), - (qc >> 4) | ((qd >> 4) << 4), - ) - if unknown: - total = sum(lost) - if total > _loose_limit(nblocks): - raise BcpackProvisionalError( - f"BC3 chunk has {total}/{nblocks} blocks from unknown built-in history entries" - ) - provisional.add(f"BC3 unknown history {sorted(unknown)} ({total} blocks)") - return bytes(out) - - -def _bc4_blocks(lanes, nblocks, provisional, *, history=None): - if any(lanes[1]): - raise BcpackError("BC4 lane 1 is non-zero (unexpected)") - pairs = _tables.BC4_PAIR - confirmed, loose = _resolve_bc_history( - 4, _tables.BC4_HISTORY_CONFIRMED, _tables.BC4_HISTORY_PROVISIONAL, history - ) - out = bytearray(nblocks * 8) - hist = [None] * nblocks - l0, l2, l3 = lanes[0], lanes[2], lanes[3] - rows = lanes[4:12] - for i in range(nblocks): - v = l0[i] - d = 256 - ((v + 1) >> 1) if (v & 1) else (v >> 1) - if d == 0: - base = (128, 128) - elif i - d >= 0: - base = hist[i - d] - else: - entry = 256 + i - d - base = confirmed.get(entry) - if base is None: - if provisional is not None and entry in loose: - base = loose[entry] - provisional.add(f"BC4 history {entry}") - else: - state = "unconfirmed" if entry in loose else "unknown" - raise BcpackProvisionalError( - f"BC4 block {i} references {state} built-in history entry {entry}" - ) - a0 = (base[0] + _unzig(l2[i])) & 255 - a1 = (base[1] + _unzig(l3[i])) & 255 - hist[i] = (a0, a1) - bits = 0 - for r in range(4): - left, right = pairs[rows[2 * r][i]], pairs[rows[2 * r + 1][i]] - bits |= (left[0] | (left[1] << 3) | (right[0] << 6) | (right[1] << 9)) << (12 * r) - at = i * 8 - out[at] = a0 - out[at + 1] = a1 - out[at + 2:at + 8] = bits.to_bytes(6, "little") - return bytes(out) - - -def _bc5_blocks(lanes, nblocks, provisional, *, history=None): - if any(lanes[1]): - raise BcpackError("BC5 lane 1 is non-zero (unexpected)") - pairs = _tables.BC5_PAIR - confirmed, loose = _resolve_bc_history( - 5, _tables.BC5_HISTORY_CONFIRMED, _tables.BC5_HISTORY_PROVISIONAL, history - ) - out = bytearray(nblocks * 16) - hist = [None] * nblocks - lost = [False] * nblocks - l0, red, green = lanes[0], lanes[2], lanes[3] - rows = lanes[4:12] - unknown = set() - for i in range(nblocks): - a, b = 2 * i, 2 * i + 1 - d = _unzig(_inter8(l0[a], l0[b])) & 255 - if d == 0: - base = (128, 128, 128, 128) - elif i - d >= 0: - base = hist[i - d] - lost[i] = lost[i - d] - else: - entry = 256 + i - d - base = confirmed.get(entry) - if base is None and entry in loose: - if provisional is None: - raise BcpackProvisionalError( - f"BC5 block {i} references unconfirmed built-in history entry {entry}" - ) - base = loose[entry] - provisional.add(f"BC5 history {entry}") - if base is None: - if provisional is None: - raise BcpackProvisionalError( - f"BC5 block {i} references unknown built-in history entry {entry}" - ) - base = (128, 128, 128, 128) - lost[i] = True - unknown.add(entry) - e = ( - (base[0] + _unzig(red[a])) & 255, - (base[1] + _unzig(red[b])) & 255, - (base[2] + _unzig(green[a])) & 255, - (base[3] + _unzig(green[b])) & 255, - ) - hist[i] = e - at = i * 16 - for ch in range(2): - bits = 0 - for r in range(4): - left, right = pairs[rows[4 * ch + r][a]], pairs[rows[4 * ch + r][b]] - bits |= (left[0] | (left[1] << 3) | (right[0] << 6) | (right[1] << 9)) << (12 * r) - out[at + 8 * ch] = e[2 * ch] - out[at + 8 * ch + 1] = e[2 * ch + 1] - out[at + 8 * ch + 2:at + 8 * ch + 8] = bits.to_bytes(6, "little") - if unknown: - total = sum(lost) - if total > _loose_limit(nblocks): - raise BcpackProvisionalError( - f"BC5 chunk has {total}/{nblocks} blocks from unknown built-in history entries" - ) - provisional.add(f"BC5 unknown history {sorted(unknown)} ({total} blocks)") - return bytes(out) - - -# BC6H ------------------------------------------------------------------------ - -# Mode index (1..14, where mode = lane15[2*i] + 1) -> D3D11/Khronos mode bits. -_BC6H_CODE = ( - 0, 0x00, 0x01, 0x02, 0x06, 0x0A, 0x0E, 0x12, - 0x16, 0x1A, 0x1E, 0x03, 0x07, 0x0B, 0x0F, -) - -# Mode code -> (transformed, base_bits, (dr, dg, db), regions). -_BC6H_INFO = { - 0x00: (1, 10, (5, 5, 5), 2), - 0x01: (1, 7, (6, 6, 6), 2), - 0x02: (1, 11, (5, 4, 4), 2), - 0x06: (1, 11, (4, 5, 4), 2), - 0x0A: (1, 11, (4, 4, 5), 2), - 0x0E: (1, 9, (5, 5, 5), 2), - 0x12: (1, 8, (6, 5, 5), 2), - 0x16: (1, 8, (5, 6, 5), 2), - 0x1A: (1, 8, (5, 5, 6), 2), - 0x1E: (0, 6, (6, 6, 6), 2), - 0x03: (0, 10, (10, 10, 10), 1), - 0x07: (1, 11, (9, 9, 9), 1), - 0x0B: (1, 12, (8, 8, 8), 1), - 0x0F: (1, 16, (4, 4, 4), 1), -} - -# Standard D3D11/Khronos BC6H header bit layouts (LSB-first after the 2- or 5-bit mode). -_BC6H_LAYOUT = { - 0x00: "gy4 by4 bz4 rw10 gw10 bw10 rx5 gz4 gy4_ gx5 bz0 gz4_ bx5 bz1 by4_ ry5 bz2 rz5 bz3 d", - 0x01: "gy5 gz4 gz5 rw7 bz0 bz1 by4 gw7 by5 bz2 gy4 bw7 bz3 bz5 bz4 rx6 gy4_ gx6 gz4_ bx6 by4_ ry6 rz6 d", - 0x02: "rw10 gw10 bw10 rx5 rw:10 gy4_ gx4 gw:10 bz0 gz4_ bx4 bw:10 bz1 by4_ ry5 bz2 rz5 bz3 d", - 0x06: "rw10 gw10 bw10 rx4 rw:10 gz4 gy4_ gx5 gw:10 gz4_ bx4 bw:10 bz1 by4_ ry4 bz0 bz2 rz4 gy4 bz3 d", - 0x0A: "rw10 gw10 bw10 rx4 rw:10 by4 gy4_ gx4 gw:10 bz0 gz4_ bx5 bw:10 by4_ ry4 bz1 bz2 rz4 bz4 bz3 d", - 0x0E: "rw9 by4 gw9 gy4 bw9 bz4 rx5 gz4 gy4_ gx5 bz0 gz4_ bx5 bz1 by4_ ry5 bz2 rz5 bz3 d", - 0x12: "rw8 gz4 by4 gw8 bz2 gy4 bw8 bz3 bz4 rx6 gy4_ gx5 bz0 gz4_ bx5 bz1 by4_ ry6 rz6 d", - 0x16: "rw8 bz0 by4 gw8 gy5 gy4 bw8 gz5 bz4 rx5 gz4 gy4_ gx6 gz4_ bx5 bz1 by4_ ry5 bz2 rz5 bz3 d", - 0x1A: "rw8 bz1 by4 gw8 by5 gy4 bw8 bz5 bz4 rx5 gz4 gy4_ gx5 bz0 gz4_ bx6 by4_ ry5 bz2 rz5 bz3 d", - 0x1E: "rw6 gz4 bz0 bz1 by4 gw6 gy5 by5 bz2 gy4 bw6 gz5 bz3 bz5 bz4 rx6 gy4_ gx6 gz4_ bx6 by4_ ry6 rz6 d", - 0x03: "rw10 gw10 bw10 rx10 gx10 bx10", - 0x07: "rw10 gw10 bw10 rx9 rw:10 gx9 gw:10 bx9 bw:10", - 0x0B: "rw10 gw10 bw10 rx8 rw:11-10 gx8 gw:11-10 bx8 bw:11-10", - 0x0F: "rw10 gw10 bw10 rx4 rw:15-10 gx4 gw:15-10 bx4 bw:15-10", -} - -_BC6H_FIELD_MAP = { - "rw": (0, 0), "gw": (1, 0), "bw": (2, 0), - "rx": (0, 1), "gx": (1, 1), "bx": (2, 1), - "ry": (0, 2), "gy": (1, 2), "by": (2, 2), - "rz": (0, 3), "gz": (1, 3), "bz": (2, 3), -} - -_BC6H_NONE_E = ((0x8000, 0x200, 0x20, 0x20),) * 3 -_BC6H_NONE_I = (8,) * 16 -_BC6H_PLANS = {} - - -def _bc6h_plan(code): - """Cached `(plan, header_bits)` for a BC6H mode code. - - Each plan item is `(channel, endpoint_slot, bit_index, stream_pos)` with - `channel == -1` for the 5-bit partition field `d`. - """ - cached = _BC6H_PLANS.get(code) - if cached is not None: - return cached - pos = 2 if code < 2 else 5 - plan = [] - for token in _BC6H_LAYOUT[code].split(): - if token == "d": - for b in range(5): - plan.append((-1, -1, b, pos + b)) - pos += 5 - elif ":" in token: - name, span = token.split(":") - c, q = _BC6H_FIELD_MAP[name] - hi, lo = (int(x) for x in span.split("-")) if "-" in span else (int(span), int(span)) - for b in range(hi, lo - 1, -1): - plan.append((c, q, b, pos)) - pos += 1 - elif token.endswith("_"): - name, n = token[:2], int(token[2:-1]) - c, q = _BC6H_FIELD_MAP[name] - for b in range(n): - plan.append((c, q, b, pos + b)) - pos += n - else: - name, n = token[:2], int(token[2:]) - c, q = _BC6H_FIELD_MAP[name] - if name[1] in "wx" or name in ("ry", "rz"): - for b in range(n): - plan.append((c, q, b, pos + b)) - pos += n - else: - plan.append((c, q, n, pos)) - pos += 1 - res = (tuple(plan), pos) - _BC6H_PLANS[code] = res - return res - - -def _bc6h_stream_w(mode, w): - """Map BCPack's base endpoint `w` into the D3D11/Khronos BC6H bit order.""" - if mode == 13: - return (w & 0x3FF) | (((w >> 10) & 1) << 11) | (((w >> 11) & 1) << 10) - if mode == 14: - out = w & 0x3FF - for b in range(10, 16): - out |= ((w >> b) & 1) << (25 - b) - return out - return w - - -def _bc6h_blocks(lanes, nblocks, provisional, *, history=None): - """Rebuild `nblocks` 16-byte BC6H blocks from the 16 BCPack lanes. - - With `history=None`, no built-in BC6H initial history is loaded, so strict - mode (`provisional is None`) accepts only self-contained chunks whose delta - chains stay within the chunk (`d == 0` or `d <= i`). Pass a locally - generated `history` JSON file/directory to supply built-in history entries. - """ - if len(lanes[0]) != 2 * nblocks: - raise BcpackError("BC6H lane length does not match the block count") - eh_table, ih_table, eclass, iclass, ep_cb, ix_cb = _bptc.load_bc6h(history, with_confirmed_bits=True) - anchor2 = _bptc.BC7_ANCHOR2 - out = bytearray(nblocks * 16) - st_e = [None] * nblocks - st_i = [None] * nblocks - eroot = [-1] * nblocks - iroot = [-1] * nblocks - ends = {} - idxs = {} - weak_e = set() - weak_i = set() - violations = 0 - l0, l1, l15 = lanes[0], lanes[1], lanes[15] - deint0, deint1 = _DEINT - - for i in range(nblocks): - a, b = 2 * i, 2 * i + 1 - m_sym = l15[a] - if m_sym > 13: - raise BcpackError(f"BC6H block {i} mode symbol {m_sym} outside 0..13") - mode = m_sym + 1 - code = _BC6H_CODE[mode] - trans, base, deltas, reg = _BC6H_INFO[code] - part = l15[b] if l15[b] < 31 else 31 - - di = _inter8(l1[a], l1[b]) - de = (di + _unzig(_inter8(l0[a], l0[b]))) & 255 - if de == 0: - eref = _BC6H_NONE_E - elif i >= de: - eref = st_e[i - de] - eroot[i] = eroot[i - de] - else: - entry = 256 + i - de - eref = eh_table[entry] - eroot[i] = entry - # Only direct initial-history reads consume the calibrated bits. - # Later blocks read the reconstructed state, whose truncation and - # zero padding are determined by this block's mode and deltas. - for c in range(3): - dc = deltas[c] - need = (base, dc, dc, dc) if reg == 2 else (base, dc, 0, 0) - if any(ep_cb[entry][c][q] < n for q, n in enumerate(need)): - weak_e.add(entry) - if eroot[i] >= 0: - r = eroot[i] - ends[r] = ends.get(r, 0) + 1 - - if di == 0: - iref = _BC6H_NONE_I - elif i >= di: - iref = st_i[i - di] - iroot[i] = iroot[i - di] - else: - entry = 256 + i - di - iref = ih_table[entry] - iroot[i] = entry - if any(b < (3 if reg == 2 else 4) for b in ix_cb[entry]): - weak_i.add(entry) - if iroot[i] >= 0: - r = iroot[i] - idxs[r] = idxs.get(r, 0) + 1 - - mw = (1 << base) - 1 - w_shift = 16 - base - f_block = [None, None, None] - st_block = [None, None, None] - for c in range(3): - dc = deltas[c] - mD = (1 << dc) - 1 - sh = 6 - dc if dc < 6 else 0 - dz0 = _unzig(_inter(lanes[2 + c][a], lanes[2 + c][b], 8)) - dz1 = _unzig(_inter(lanes[5 + c][a], lanes[5 + c][b], 5)) - dz2 = _unzig(lanes[8 + c][a]) - dz3 = _unzig(lanes[8 + c][b]) - r0, r1, r2, r3 = eref[c] - w = ((r0 >> w_shift) + dz0) & mw - x = ((r1 >> (10 - dc)) + dz1) & mD - y = ((r2 >> sh) + dz2) & mD - z = ((r3 >> sh) + dz3) & mD - x10 = x << (10 - dc) - if reg == 2: - st_block[c] = (w << w_shift, x10, y << sh, z << sh) - f_block[c] = (_bc6h_stream_w(mode, w), x, y, z) - else: - v = (w & mD) ^ ((1 << (dc - 1)) if trans == 1 else 0) - low_y = (v >> (dc - 6)) if dc >= 6 else (v << sh) - st_block[c] = (w << w_shift, x10, low_y, x10 >> 4) - f_block[c] = (_bc6h_stream_w(mode, w), x, 0, 0) - st_e[i] = (st_block[0], st_block[1], st_block[2]) - - ibits = 3 if reg == 2 else 4 - imask = (1 << ibits) - 1 - ishift = 4 - ibits - ix_block = [0] * 16 - si_block = [0] * 16 - for yy in range(4): - sa = lanes[11 + yy][a] - sb = lanes[11 + yy][b] - row = yy * 4 - if yy < 3: - d0, d1 = deint1[sa], deint0[sa] - d2, d3 = deint1[sb], deint0[sb] - else: - d0, d1 = deint0[sa], deint1[sa] - d2, d3 = deint0[sb], deint1[sb] - for off, dv in ((0, d0), (1, d1), (2, d2), (3, d3)): - p = row + off - ix = ((iref[p] >> ishift) + _unzig(dv)) & imask - ix_block[p] = ix - si_block[p] = ix << ishift - st_i[i] = tuple(si_block) - - second = anchor2[part] if reg == 2 else -1 - if ix_block[0] & (4 if reg == 2 else 8): - violations += 1 - if reg == 2 and (ix_block[second] & 4): - violations += 1 - - plan, header = _bc6h_plan(code) - acc = code - for c, q, bit_idx, pos in plan: - if c < 0: - if (part >> bit_idx) & 1: - acc |= 1 << pos - elif (f_block[c][q] >> bit_idx) & 1: - acc |= 1 << pos - at = header - for p in range(16): - nb = (ibits - 1) if (p == 0 or p == second) else ibits - acc |= (ix_block[p] & ((1 << nb) - 1)) << at - at += nb - out[16 * i:16 * i + 16] = acc.to_bytes(16, "little") - - if provisional is None: - unconf_e = [k for k in ends if eclass[k] != 3 or k in weak_e] - unconf_i = [k for k in idxs if iclass[k] != 3 or k in weak_i] - if unconf_e or unconf_i: - k = unconf_e[0] if unconf_e else unconf_i[0] - kind = "endpoint" if unconf_e else "index" - cls = eclass[k] if unconf_e else iclass[k] - state = "unknown" if cls == 0 else "unconfirmed" - hint = " (pass --history )" if history is None else "" - raise BcpackProvisionalError( - f"BC6H chunk references {state} built-in {kind} history entry {k}{hint}" - ) - if violations: - raise BcpackError( - f"BC6H chunk has {violations} anchor pixel(s) with an inconsistent index" - ) - return bytes(out) - - lost = _unknown_blocks(eroot, iroot, {k for k in ends if eclass[k] == 0}, {k for k in idxs if iclass[k] == 0}) - missing = sorted( - {f"endpoint {k}" for k in ends if eclass[k] == 0} - | {f"index {k}" for k in idxs if iclass[k] == 0} - ) - if lost > _loose_limit(nblocks): - hint = " (pass --history )" if history is None else "" - raise BcpackProvisionalError( - f"BC6H chunk has {lost}/{nblocks} blocks from unknown built-in history entries " - f"({', '.join(missing[:6])}{', ...' if len(missing) > 6 else ''}){hint}" - ) - weak_labels = [ - f"BC6H {kind} history {k} (unconfirmed bits)" - for kind, entries, cls in (("endpoint", weak_e, eclass), ("index", weak_i, iclass)) - for k in sorted(entries) - if cls[k] == 3 - ] - hist_labels = [] - for name, entries, cls in (("endpoint", ends, eclass), ("index", idxs, iclass)): - fitted = sorted(k for k in entries if cls[k] == 1) - rough = sorted(k for k in entries if cls[k] == 2) - if fitted: - hist_labels.append(f"BC6H {name} history {', '.join(map(str, fitted))}") - if rough: - hist_labels.append(f"BC6H {name} history {', '.join(map(str, rough))} (last-resort)") - if violations: - if not (provisional or missing or weak_labels or hist_labels): - raise BcpackError( - f"BC6H chunk has {violations} anchor pixel(s) with an inconsistent index" - ) - if violations > _loose_limit(nblocks): - raise BcpackProvisionalError( - f"BC6H chunk has {violations} anchor pixels with an inconsistent index" - ) - if missing: - provisional.add(f"BC6H unknown history {', '.join(missing)} ({lost} blocks)") - if violations: - provisional.add(f"BC6H anchor index inconsistent in {violations} pixels") - provisional.update(weak_labels) - provisional.update(hist_labels) - return bytes(out) - - -# BC7 ------------------------------------------------------------------------- - -_B7_NS = (3, 2, 3, 2, 1, 1, 1, 2) -_B7_CB = (4, 6, 5, 7, 5, 7, 7, 5) -_B7_AB = (0, 0, 0, 0, 6, 8, 7, 5) -_B7_PK = (1, 2, 0, 1, 0, 0, 1, 1) # 0=none, 1=per-endpoint p-bit, 2=shared per subset -_B7_IB = (3, 3, 2, 2, 3, 2, 4, 2) # index bits of primary index set (lanes 11..14) -_B7_PB = (4, 6, 6, 6, 0, 0, 0, 6) # partition field bits -_B7_LANE = ((2, 3, 4, 5), (6, 7, 8, 9), (10, 5, 9, -1)) -_B7_ANCHOR = 8 -_B7_PBIT = 16 -_B7_SIGNATURE = 32 -_B7_MIN_DEPTH = 4 - - -def _bc7_field_bits(mode, rot): - """Leading bits read from a stored endpoint byte for channels (R, G, B, A).""" - w = [_B7_CB[mode], _B7_CB[mode], _B7_CB[mode], _B7_AB[mode]] - if rot: - w[rot - 1], w[3] = _B7_AB[mode], _B7_CB[mode] - pk = _B7_PK[mode] - return [w[c] + (1 if (pk and c == 0) else 0) if w[c] else 0 for c in range(4)] - - -def _bc7_check(lanes, nblocks, table, provisional, *, has_history=False): - """Validate signatures and built-in history coverage for a BC7 chunk. - - In strict mode (`provisional is None`), raises `BcpackError` for unknown - signatures and `BcpackProvisionalError` for inferred signatures or any - unconfirmed/unknown built-in history entry. In provisional mode, populates - `provisional` with descriptive labels and returns a list of `(kind, entry)` - pairs whose depth is below `_B7_MIN_DEPTH` (or missing for indices). - """ - cfg = table["config"] - rank_of = table["rank_of"] - l0, l1, l15 = lanes[0], lanes[1], lanes[15] - ranks = set() - for a, b in set(zip(l15[0::2], l15[1::2])): - rank = rank_of[a * 16 + b] if a < 32 and b < 16 else -1 - if rank < 0 or cfg[rank][0] > 7 or cfg[rank][1] == 255: - raise BcpackError(f"BC7 signature ({a}, {b}) is outside the signature table") - ranks.add(rank) - for rank in sorted(ranks & table["inferred"]): - if provisional is None: - raise BcpackProvisionalError( - f"BC7 signature rank {rank} is inferred-only (unconfirmed)" - ) - provisional.add(f"BC7 signature {rank}") - - need_e = {} - need_i = {} - for i in range(min(nblocks, 256)): - rank = rank_of[l15[2 * i] * 16 + l15[2 * i + 1]] - mode, _, rot, _ = cfg[rank] - di = _inter8(l1[2 * i], l1[2 * i + 1]) - de = (di + _unzig(_inter8(l0[2 * i], l0[2 * i + 1]))) & 255 - if de > i: - bits = _bc7_field_bits(mode, rot) - row = need_e.setdefault(256 + i - de, [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]) - for sub in range(_B7_NS[mode]): - for c in range(4): - if bits[c] > row[sub][c]: - row[sub][c] = bits[c] - if di > i: - row = need_i.setdefault(256 + i - di, [0, 0]) - if _B7_IB[mode] > row[0]: - row[0] = _B7_IB[mode] - if mode in (4, 5): - row[1] = 2 - - unknown = [] - last_resort = table["last_resort"] - checks = ( - ("endpoint", need_e, table["history_endpoint_bits"], table["history_endpoint_confirmed_bits"]), - ("index", need_i, table["history_index_bits"], table["history_index_confirmed_bits"]), - ) - for kinds, need, bits_t, conf_t in checks: - for k, want in sorted(need.items()): - if kinds == "endpoint": - slots = [ - (sub * 8 + e * 4 + c, want[sub][c]) - for sub in range(3) for e in range(2) for c in range(4) - if want[sub][c] - ] - else: - slots = [ - (st * 16 + p, want[st]) - for st in range(2) for p in range(16) - if want[st] - ] - weak = False - missing = False - shallow = 8 - bk = bits_t[k] - ck = conf_t[k] - for j, b in slots: - if bk[j] < b: - missing = True - if bk[j] < shallow: - shallow = bk[j] - if ck[j] < b: - weak = True - if missing: - if provisional is None: - hint = " (pass --history )" if not has_history else "" - raise BcpackProvisionalError( - f"BC7 chunk references unknown built-in {kinds} history entry {k}{hint}" - ) - if kinds == "endpoint" and shallow >= _B7_MIN_DEPTH: - provisional.add(f"BC7 endpoint history {k} (top {shallow} bits known)") - else: - unknown.append((kinds, k)) - elif weak: - if provisional is None: - raise BcpackProvisionalError( - f"BC7 chunk references unconfirmed built-in {kinds} history entry {k}" - ) - provisional.add(f"BC7 {kinds} history {k}") - if kinds == "endpoint" and provisional is not None: - if any((k, j) in last_resort for j, _ in slots): - provisional.add(f"BC7 endpoint history {k} (last-resort)") - return unknown - - -def _bc7_rebuild(lanes, nblocks, table): - """Rebuild `nblocks` 16-byte BC7 blocks and per-block consistency status flags.""" - cfg = table["config"] - rank_of = table["rank_of"] - p2 = table["partition2"] - p3 = table["partition3"] - a2 = table["anchor2"] - a3a = table["anchor3a"] - a3b = table["anchor3b"] - pre_e = table["history_endpoints"] - pre_i = table["history_indices"] - out = bytearray(16 * nblocks) - status = [0] * nblocks - eps = [None] * nblocks - ixs = [None] * nblocks - zero_e = (0,) * 24 - zero_i = (0,) * 32 - rows1 = (lanes[11], lanes[12], lanes[13], lanes[14]) - rows2 = (lanes[6], lanes[7], lanes[8], lanes[10]) - l0, l1, l15 = lanes[0], lanes[1], lanes[15] - deint0, deint1 = _DEINT - - for i in range(nblocks): - a, b = 2 * i, 2 * i + 1 - s15a, s15b = l15[a], l15[b] - rank = rank_of[s15a * 16 + s15b] if s15a < 32 and s15b < 16 else -1 - if rank < 0 or cfg[rank][0] > 7: - status[i] = _B7_SIGNATURE - eps[i] = zero_e - ixs[i] = zero_i - continue - mode, part, rot, isel = cfg[rank] - st = 0 - di = _inter8(l1[a], l1[b]) - de = (di + _unzig(_inter8(l0[a], l0[b]))) & 255 - rep = zero_e if de == 0 else (eps[i - de] if i >= de else pre_e[256 + i - de]) - rix = zero_i if di == 0 else (ixs[i - di] if i >= di else pre_i[256 + i - di]) - - ns = _B7_NS[mode] - cb = _B7_CB[mode] - ab = _B7_AB[mode] - pk = _B7_PK[mode] - w = [cb, cb, cb, ab] - if rot: - w[rot - 1], w[3] = ab, cb - - val = [[[0, 0, 0, 0], [0, 0, 0, 0]] for _ in range(3)] - sep = [0] * 24 - pb = [[0, 0], [0, 0], [0, 0]] - for sub in range(ns): - lane_row = _B7_LANE[sub] - base_sub = sub * 8 - for c in range(4): - lane_idx = lane_row[c] - wc = w[c] - if not wc or lane_idx < 0: - continue - bits = wc + (1 if (pk and c == 0) else 0) - shift = 8 - bits - mask = (1 << bits) - 1 - ln = lanes[lane_idx] - v0 = ((rep[base_sub + c] >> shift) + _unzig(ln[a])) & mask - v1 = ((rep[base_sub + 4 + c] >> shift) + _unzig(ln[b])) & mask - val[sub][0][c] = v0 - val[sub][1][c] = v1 - sep[base_sub + c] = v0 << shift - sep[base_sub + 4 + c] = v1 << shift - if pk == 1: - pb[sub][0] = val[sub][0][0] & 1 - pb[sub][1] = val[sub][1][0] & 1 - elif pk == 2: - p0 = val[sub][0][0] & 1 - pb[sub][0] = p0 - pb[sub][1] = p0 - if (val[sub][1][0] & 1) != p0: - st |= _B7_PBIT - for sub in range(ns, 3): - sep[sub * 8:sub * 8 + 8] = sep[0:8] - eps[i] = sep - - b1 = _B7_IB[mode] - b1_shift = 4 - b1 - b1_mask = (1 << b1) - 1 - two = mode in (4, 5) - s1 = [0] * 16 - s2 = [0] * 16 if two else None - six = [0] * 32 - for y in range(4): - r1 = rows1[y] - sa, sb = r1[a], r1[b] - row = y * 4 - if y < 3: - d0, d1, d2, d3 = deint1[sa], deint0[sa], deint1[sb], deint0[sb] - else: - d0, d1, d2, d3 = deint0[sa], deint1[sa], deint0[sb], deint1[sb] - for off, dv in ((0, d0), (1, d1), (2, d2), (3, d3)): - p = row + off - iv = ((rix[p] >> b1_shift) + _unzig(dv)) & b1_mask - s1[p] = iv - six[p] = iv << b1_shift - if two: - r2 = rows2[y] - s2a, s2b = r2[a], r2[b] - if y < 3: - e0, e1, e2, e3 = deint1[s2a], deint0[s2a], deint1[s2b], deint0[s2b] - else: - e0, e1, e2, e3 = deint0[s2a], deint1[s2a], deint0[s2b], deint1[s2b] - for off, dv in ((0, e0), (1, e1), (2, e2), (3, e3)): - p = row + off - iv2 = ((rix[16 + p] >> 2) + _unzig(dv)) & 3 - s2[p] = iv2 - six[16 + p] = iv2 << 2 - ixs[i] = six - - if mode == 0 and part == 0 and not any(sep) and not any(s1): - status[i] = st - continue - - sm = p2[part] if ns == 2 else (p3[part] if ns == 3 else None) - anchors = (0,) if ns == 1 else ((0, a2[part]) if ns == 2 else (0, a3a[part], a3b[part])) - if mode == 4: - pri, ib, sec, ib2 = s2, 2, s1, 3 - elif mode == 5: - pri, ib, sec, ib2 = s1, 2, s2, 2 - else: - pri, ib, sec, ib2 = s1, b1, None, 0 - - acc = 1 << mode - pos = mode + 1 - pbits = _B7_PB[mode] - if pbits: - acc |= (part & ((1 << pbits) - 1)) << pos - pos += pbits - if mode in (4, 5): - acc |= (rot & 3) << pos - pos += 2 - if mode == 4: - acc |= (isel & 1) << pos - pos += 1 - cb_mask = (1 << cb) - 1 - for c in range(3): - tc = 3 if (rot and c == rot - 1) else c - drop = bool(pk and tc == 0) - for sub in range(ns): - for e in range(2): - v = val[sub][e][tc] - acc |= ((v >> 1 if drop else v) & cb_mask) << pos - pos += cb - if ab: - ab_mask = (1 << ab) - 1 - tc = rot - 1 if rot else 3 - drop = bool(pk and tc == 0) - for sub in range(ns): - for e in range(2): - v = val[sub][e][tc] - acc |= ((v >> 1 if drop else v) & ab_mask) << pos - pos += ab - if pk == 1: - for sub in range(ns): - acc |= (pb[sub][0] & 1) << pos - pos += 1 - acc |= (pb[sub][1] & 1) << pos - pos += 1 - elif pk == 2: - for sub in range(ns): - acc |= (pb[sub][0] & 1) << pos - pos += 1 - - ib_mask = (1 << ib) - 1 - ib_amask = (1 << (ib - 1)) - 1 - for p in range(16): - anchor = p == anchors[sm[p] if sm is not None else 0] - pv = pri[p] - if anchor: - if pv >> (ib - 1): - st |= _B7_ANCHOR - acc |= (pv & ib_amask) << pos - pos += ib - 1 - else: - acc |= (pv & ib_mask) << pos - pos += ib - if sec is not None: - ib2_mask = (1 << ib2) - 1 - ib2_amask = (1 << (ib2 - 1)) - 1 - for p in range(16): - sv = sec[p] - if p == 0: - if sv >> (ib2 - 1): - st |= _B7_ANCHOR - acc |= (sv & ib2_amask) << pos - pos += ib2 - 1 - else: - acc |= (sv & ib2_mask) << pos - pos += ib2 - if pos != 128: - st |= _B7_SIGNATURE - out[16 * i:16 * i + 16] = acc.to_bytes(16, "little") - status[i] = st - return bytes(out), status - - -def _bc7_blocks(lanes, nblocks, provisional, *, history=None): - """Rebuild `nblocks` 16-byte BC7 blocks from the 16 BCPack lanes.""" - if len(lanes[0]) != 2 * nblocks: - raise BcpackError("BC7 lane length does not match the block count") - table = _bptc.load_bc7(history) - unknown = _bc7_check(lanes, nblocks, table, provisional, has_history=(history is not None)) - if unknown: - l0, l1 = lanes[0], lanes[1] - er = [0] * nblocks - ir = [0] * nblocks - for i in range(nblocks): - di = _inter8(l1[2 * i], l1[2 * i + 1]) - de = (di + _unzig(_inter8(l0[2 * i], l0[2 * i + 1]))) & 255 - er[i] = -1 if de == 0 else (256 + i - de if de > i else er[i - de]) - ir[i] = -1 if di == 0 else (256 + i - di if di > i else ir[i - di]) - counts = [(kinds, k, (er if kinds == "endpoint" else ir).count(k)) for kinds, k in unknown] - total = _unknown_blocks(er, ir, {k for kinds, k in unknown if kinds == "endpoint"}, - {k for kinds, k in unknown if kinds == "index"}) - if total > _loose_limit(nblocks): - names = ", ".join(f"{kinds} {k}" for kinds, k, _ in counts[:6]) - if len(counts) > 6: - names += ", ..." - hint = " (pass --history )" if history is None else "" - raise BcpackProvisionalError( - f"BC7 chunk has {total}/{nblocks} blocks from unknown built-in history entries ({names}){hint}" - ) - for kinds, k, count in counts: - provisional.add(f"BC7 unknown {kinds} history {k} ({count} blocks)") - data, status = _bc7_rebuild(lanes, nblocks, table) - bad = [i for i, st in enumerate(status) if st] - if bad: - sig_bad = [i for i in bad if status[i] & _B7_SIGNATURE] - if sig_bad: - raise BcpackError( - f"BC7 chunk failed signature check ({len(sig_bad)}/{nblocks} blocks; first: block {sig_bad[0]})" - ) - if provisional is None or not provisional: - raise BcpackError( - f"BC7 chunk failed anchor/p-bit consistency check " - f"({len(bad)}/{nblocks} blocks; first: block {bad[0]})" - ) - if len(bad) > _loose_limit(nblocks): - raise BcpackProvisionalError( - f"BC7 chunk failed anchor/p-bit consistency check in {len(bad)}/{nblocks} blocks" - ) - provisional.add(f"BC7 consistency check failed in {len(bad)} blocks") - return data - - -_REBUILDERS = { - 1: _bc1_blocks, - 3: _bc3_blocks, - 4: _bc4_blocks, - 5: _bc5_blocks, - 6: _bc6h_blocks, - 7: _bc7_blocks, -} - - -def decode_with_info(raw, codec, out_size, *, allow_provisional=False, history=None): - """Decode one BCPack chunk, returning `(decoded_bytes, provisional_labels)`. - - When `allow_provisional` is False (strict mode), any unconfirmed or unknown - built-in history reference raises `BcpackProvisionalError` and the returned - set is always empty. `history` may point to a locally generated JSON file, - directory, or dict supplying initial history tables for BC6H/BC7 (and - optional overrides for BC1-BC5). - """ - rebuilder = _REBUILDERS.get(codec) - if rebuilder is None: - name = CODEC_NAMES.get(codec, str(codec)) - raise BcpackUnsupportedCodec(f"BCPack block rebuilder for codec {codec} ({name}) is not implemented yet") - fast = _decode_blocks_native(raw, codec, out_size, history) - if fast is not None: - return fast, set() - lanes, _ = decode_lanes(raw, codec, out_size) - nblocks = out_size // BLOCK_BYTES[codec] - prov = set() if allow_provisional else None - data = rebuilder(lanes, nblocks, prov, history=history) - return data, (prov if prov is not None else set()) - - -def decode(raw, codec, out_size, *, allow_provisional=False, history=None): - """Decode one BCPack chunk into `out_size` bytes of standard BCn blocks.""" - data, _ = decode_with_info( - raw, codec, out_size, allow_provisional=allow_provisional, history=history - ) - return data diff --git a/tools/bcpack_calibration/.gitignore b/tools/bcpack_calibration/.gitignore deleted file mode 100644 index b83d22266..000000000 --- a/tools/bcpack_calibration/.gitignore +++ /dev/null @@ -1 +0,0 @@ -/target/ diff --git a/tools/bcpack_calibration/Cargo.lock b/tools/bcpack_calibration/Cargo.lock deleted file mode 100644 index aff9f4dfe..000000000 --- a/tools/bcpack_calibration/Cargo.lock +++ /dev/null @@ -1,14 +0,0 @@ -# This file is automatically @generated by Cargo. -# It is not intended for manual editing. -version = 4 - -[[package]] -name = "bcpack-rans" -version = "0.2.0" - -[[package]] -name = "bcpack_calibration" -version = "0.1.0" -dependencies = [ - "bcpack-rans", -] diff --git a/tools/bcpack_calibration/Cargo.toml b/tools/bcpack_calibration/Cargo.toml deleted file mode 100644 index 3b5e04024..000000000 --- a/tools/bcpack_calibration/Cargo.toml +++ /dev/null @@ -1,11 +0,0 @@ -[package] -name = "bcpack_calibration" -version = "0.1.0" -edition = "2021" -publish = false - -[lib] -crate-type = ["cdylib"] - -[dependencies] -bcpack-rans = { path = "../../third_party/bcpack-rs" } diff --git a/tools/bcpack_calibration/README.md b/tools/bcpack_calibration/README.md deleted file mode 100644 index 676418b1b..000000000 --- a/tools/bcpack_calibration/README.md +++ /dev/null @@ -1,41 +0,0 @@ -# Calibrated TTPF export - -The Python exporter can replay a locally measured reconstruction profile for 2D BC1, BC3, BC4, BC5, BC6H and BC7 textures and 2D arrays. A single-entry export accepts `--calibration PROFILE.json`. The assets stage discovers `/bcpack-calibration.json`. The profile is data. The compiled library is loaded from this crate's release build directory. - -From the repository root, build with Rust/Cargo and run in the Python environment where NumPy is installed: - -```text -python -m pip install numpy -cargo build --release --locked --offline --manifest-path tools/bcpack_calibration/Cargo.toml -python -IB tests/test_calibrated_texture.py -v -python -I tools/ttpf_mips.py export path/to/pool.ttpf 0 output.dds --calibration path/to/profile.json -``` - -The synthetic test constructs its own BC1 pool and profile, runs the CLI and compares the full mip payload with known blocks. A real profile requires the caller's calibrated tables. The exporter does not derive the tables automatically. A matching file hash verifies reproduction of a previous fitted export. Original pixel fidelity needs independent reference pixels. - -## Faster strict decoding - -Once built, the same library also speeds up the default strict path. Its `unpack_model` export (`src/model.rs`) is a line-by-line port of the lane-array model in `tools/bcpack.py` (`_decode_lanes_raw`, virtual zero bytes included), and `tools/bcpack.py` passes it its own probability tables. It therefore accepts exactly the streams the Python model accepts, with the same symbols. It is about 30 times faster than the Python model on synthetic chunks, and NumPy is not needed. When the library is not built, or a stream is refused, Python decodes the stream as before and raises its usual error. `python -I tests/test_bcpack_native.py` checks that the two agree, and `LEONIDA_BCPACK_NATIVE=0` turns the native path off. - -For BC1, BC3, BC4 and BC5 chunks, `decode_blocks` (`src/blocks.rs`) also rebuilds the blocks in the same call. It takes only the strict path: a chunk with a non-zero lane 1, or one that references a built-in history entry that is not confirmed, is decoded by Python, so errors and provisional entries do not change. On synthetic 16,384-block chunks, it is about 18 times faster than Python end to end for BC1, 38 times for BC4 and, measured the same way on a Windows PC, about 47 times for BC3 and 45 times for BC5. - -The `unpack` export above runs `third_party/bcpack-rs`, which follows the hardware RTL. It is faster but refuses some streams the model accepts, for example every `q = 0` fragment whose omitted trailing zero byte comes before a symbol. That is why the strict path does not use it. - -## Automatic asset export - -Run the ordinary build or `python -I make_game.py --game --work --stages assets`. The assets stage runs the C# exporter on each new pool and revisits existing pool manifests. It attempts full mip chains for missing and partial BCn entries whose allocation includes BCPack. With no profile, it uses the Python strict decoder. For calibrated 2D textures and arrays, install NumPy, build the library as above and place a matching profile at `/bcpack-calibration.json` before running the stage. - -The DDS files and their manifest are under `/assets/ttpf//` or `/assets/ttpf_pack///`. The manifest keeps the asset key for model lookup and records the new filename, mip count and decoder. A failed reconstruction keeps the previous file reference and records the reason in `BCPackLimitation`. The stage publishes each DDS before replacing the pool manifest. A completed pass skips decoding on the next build. Adding or changing the profile triggers another pass. - -## Version 1 profile - -The top-level JSON object contains `"version": 1` and the sections used by the requested texture: - -- `bc1.endpoints` holds 256 rows of six RGB565 components indexed by predictor age. Negative values mark unknown components. `bc1.selectors` contains four rows of 256 unsigned 32-bit masks in output bit order. The synthetic test generates both fields. -- `bc3.endpoints` maps negative history offsets to eight RGB-alpha components in endpoint order. Offset -512 is the zero-distance predictor. `color` and `alpha` map quadrant and pair ranks to packed selector bits. -- `bc4` maps profile names to dictionaries of history-slot numbers and two byte-valued endpoints. BC5 uses the decoder's built-in tables and the compatibility endpoint ordering. -- `bc6h` uses the existing external BC6H history section. -- `bc7.labels` has 1,024 rows of mode, partition, rotation and index selection indexed by the two signature symbols. `anchors` contains 128 unsigned 16-bit masks. Each entry of `seeds` is a 256 × 56 × 2 array indexed by age and field with left-aligned byte value and known-bit count. Tables are named `base`, `secondary`, `early` and `refined`. Optional fitted endpoint adjustments are keyed by SHA-256 of the contiguous lane-symbol matrix followed by little-endian signed 64-bit unresolved block indices. Each adjustment gives age, endpoint field and fitted byte value. -- Optional `entries` maps pool basename and zero-based index to a profile name (default `base`). Optional `compatibility` maps a compressed BC1 stream's SHA-256 to a list of flattened symbol positions. Rotate the symbols at those positions left once to reproduce a known historical feeder ordering. - -Cargo builds the entropy decoder from the two upstream modules included in `third_party/bcpack-rs`. With the Rust toolchain installed, this step works offline with an empty Cargo cache. The [source and license notes](../../third_party/bcpack-rs/README.md) identify the upstream revision. The Python reader handles streams for which that reader does not report full consumption. The fitted BC7 reconstruction tracks precision while decoding blocks in archive order. Visible blocks must resolve before the DDS is written. diff --git a/tools/bcpack_calibration/src/blocks.rs b/tools/bcpack_calibration/src/blocks.rs deleted file mode 100644 index 043673fd2..000000000 --- a/tools/bcpack_calibration/src/blocks.rs +++ /dev/null @@ -1,217 +0,0 @@ -// Strict BC1, BC3, BC4 and BC5 block rebuild, ported from `_bc1_blocks`, -// `_bc3_blocks`, `_bc4_blocks` and `_bc5_blocks` in tools/bcpack.py. Python passes the lookup table and the confirmed built-in -// history it would use. Anything the strict path would not decode on its own -// (a non-zero lane 1, a history entry that is not confirmed) returns None: -// Python then runs the whole chunk again, so its errors and its provisional -// entries are unchanged. - -fn dist(v: u16) -> i64 { - let v = v as i64; - if v & 1 != 0 { - 256 - ((v + 1) >> 1) - } else { - v >> 1 - } -} - -fn unzig(v: u16) -> i64 { - let v = v as i64; - if v & 1 != 0 { - -((v + 1) >> 1) - } else { - v >> 1 - } -} - -/// The base of block `i`: the zero state, an earlier block, or a confirmed built-in entry. -fn base( - i: usize, - d: i64, - zero: [i64; K], - hist: &[[i64; K]], - builtin: &[i32], -) -> Option<[i64; K]> { - if d == 0 { - return Some(zero); - } - if i as i64 - d >= 0 { - return Some(hist[i - d as usize]); - } - let entry = (256 + i as i64 - d) as usize; - let row = builtin.get(entry * K..entry * K + K)?; - if row[0] < 0 { - return None; - } - let mut b = [0i64; K]; - for k in 0..K { - b[k] = row[k] as i64; - } - Some(b) -} - -/// `lane(l)[i]` is symbol i of lane l (lane-major, `n` symbols per lane). -pub fn bc1(sym: &[u16], n: usize, quad: &[u8], builtin: &[i32], out: &mut [u8]) -> Option<()> { - let lane = |l: usize| &sym[l * n..(l + 1) * n]; - if quad.len() != 256 || builtin.len() != 256 * 6 || out.len() != n * 8 || lane(1).iter().any(|&s| s != 0) { - return None; - } - const MODS: [i64; 6] = [32, 64, 32, 32, 64, 32]; - let mut hist = vec![[0i64; 6]; n]; - for i in 0..n { - let b = base(i, dist(lane(0)[i]), [0; 6], &hist, builtin)?; - let mut e = [0i64; 6]; - for k in 0..6 { - e[k] = (b[k] + unzig(lane(2 + k)[i])).rem_euclid(MODS[k]); - } - hist[i] = e; - let c0 = ((e[0] << 11) | (e[1] << 5) | e[2]) as u16; - let c1 = ((e[3] << 11) | (e[4] << 5) | e[5]) as u16; - let q = |l: usize| *quad.get(lane(l)[i] as usize).unwrap_or(&0); - if (8..12).any(|l| lane(l)[i] > 255) { - return None; - } - let (a, bb, c, dd) = (q(8), q(9), q(10), q(11)); - let o = &mut out[i * 8..i * 8 + 8]; - o[0..2].copy_from_slice(&c0.to_le_bytes()); - o[2..4].copy_from_slice(&c1.to_le_bytes()); - o[4] = (a & 15) | ((bb & 15) << 4); - o[5] = (a >> 4) | ((bb >> 4) << 4); - o[6] = (c & 15) | ((dd & 15) << 4); - o[7] = (c >> 4) | ((dd >> 4) << 4); - } - Some(()) -} - -/// `pairs` is `BC4_PAIR` flattened: 64 rows of two 3-bit indices. -pub fn bc4(sym: &[u16], n: usize, pairs: &[u8], builtin: &[i32], out: &mut [u8]) -> Option<()> { - let lane = |l: usize| &sym[l * n..(l + 1) * n]; - if pairs.len() != 128 || builtin.len() != 256 * 2 || out.len() != n * 8 || lane(1).iter().any(|&s| s != 0) { - return None; - } - let mut hist = vec![[0i64; 2]; n]; - for i in 0..n { - let b = base(i, dist(lane(0)[i]), [128; 2], &hist, builtin)?; - let a0 = (b[0] + unzig(lane(2)[i])) & 255; - let a1 = (b[1] + unzig(lane(3)[i])) & 255; - hist[i] = [a0, a1]; - let mut bits = 0u64; - for r in 0..4 { - let (l, rr) = (lane(4 + 2 * r)[i] as usize, lane(5 + 2 * r)[i] as usize); - if l >= 64 || rr >= 64 { - return None; - } - let v = pairs[2 * l] as u64 - | (pairs[2 * l + 1] as u64) << 3 - | (pairs[2 * rr] as u64) << 6 - | (pairs[2 * rr + 1] as u64) << 9; - bits |= v << (12 * r); - } - let o = &mut out[i * 8..i * 8 + 8]; - o[0] = a0 as u8; - o[1] = a1 as u8; - o[2..8].copy_from_slice(&bits.to_le_bytes()[..6]); - } - Some(()) -} - -/// The 8-bit history distance of the two-element codecs: lane 0 carries the low -/// four bits of the distance code in element `a` and the high four in `b`, -/// interleaved bit by bit, then zigzag decoded modulo 256 (`_inter8`). -fn dist8(a: u16, b: u16) -> i64 { - let mut code = 0u16; - for k in 0..4 { - code |= (((a >> k) & 1) << (2 * k)) | (((b >> k) & 1) << (2 * k + 1)); - } - unzig(code) & 255 -} - -/// Three index bits of each element of a pair, from a symbol of `pairs` (64 rows of two 3-bit values). -fn pair_bits(pairs: &[u8], left: u16, right: u16) -> Option { - let (l, r) = (left as usize, right as usize); - if l >= 64 || r >= 64 { - return None; - } - Some( - pairs[2 * l] as u64 - | (pairs[2 * l + 1] as u64) << 3 - | (pairs[2 * r] as u64) << 6 - | (pairs[2 * r + 1] as u64) << 9, - ) -} - -/// `lut` is `BC3_ALPHA_PAIR` flattened (64 rows of two 3-bit indices) followed by `BC3_COLOUR_QUADRANT` (256 bytes). -/// BC3 and BC5 carry two symbols of every lane per block, so `n` is twice the block count. -pub fn bc3(sym: &[u16], n: usize, lut: &[u8], builtin: &[i32], out: &mut [u8]) -> Option<()> { - let lane = |l: usize| &sym[l * n..(l + 1) * n]; - if n % 2 != 0 || lut.len() != 128 + 256 || builtin.len() != 256 * 8 || out.len() != n * 8 || lane(1).iter().any(|&s| s != 0) { - return None; - } - const MODS: [i64; 8] = [256, 256, 32, 64, 32, 32, 64, 32]; - let (pairs, quads) = lut.split_at(128); - let mut hist = vec![[0i64; 8]; n / 2]; - for i in 0..n / 2 { - let (a, b) = (2 * i, 2 * i + 1); - let base = base(i, dist8(lane(0)[a], lane(0)[b]), [128, 128, 0, 0, 0, 0, 0, 0], &hist, builtin)?; - let dz = [ - lane(2)[a], lane(2)[b], lane(7)[a], lane(8)[a], lane(9)[a], lane(7)[b], lane(8)[b], lane(9)[b], - ]; - let mut e = [0i64; 8]; - for k in 0..8 { - e[k] = (base[k] + unzig(dz[k])).rem_euclid(MODS[k]); - } - hist[i] = e; - let mut bits = 0u64; - for r in 0..4 { - bits |= pair_bits(pairs, lane(3 + r)[a], lane(3 + r)[b])? << (12 * r); - } - if (10..12).any(|l| lane(l)[a] > 255 || lane(l)[b] > 255) { - return None; - } - let q = |l: usize, at: usize| quads[lane(l)[at] as usize]; - let (qa, qb, qc, qd) = (q(10, a), q(10, b), q(11, a), q(11, b)); - let c0 = ((e[2] << 11) | (e[3] << 5) | e[4]) as u16; - let c1 = ((e[5] << 11) | (e[6] << 5) | e[7]) as u16; - let o = &mut out[i * 16..i * 16 + 16]; - o[0] = e[0] as u8; - o[1] = e[1] as u8; - o[2..8].copy_from_slice(&bits.to_le_bytes()[..6]); - o[8..10].copy_from_slice(&c0.to_le_bytes()); - o[10..12].copy_from_slice(&c1.to_le_bytes()); - o[12] = (qa & 15) | ((qb & 15) << 4); - o[13] = (qa >> 4) | ((qb >> 4) << 4); - o[14] = (qc & 15) | ((qd & 15) << 4); - o[15] = (qc >> 4) | ((qd >> 4) << 4); - } - Some(()) -} - -/// `pairs` is `BC5_PAIR` flattened: 64 rows of two 3-bit indices. -pub fn bc5(sym: &[u16], n: usize, pairs: &[u8], builtin: &[i32], out: &mut [u8]) -> Option<()> { - let lane = |l: usize| &sym[l * n..(l + 1) * n]; - if n % 2 != 0 || pairs.len() != 128 || builtin.len() != 256 * 4 || out.len() != n * 8 || lane(1).iter().any(|&s| s != 0) { - return None; - } - let mut hist = vec![[0i64; 4]; n / 2]; - for i in 0..n / 2 { - let (a, b) = (2 * i, 2 * i + 1); - let base = base(i, dist8(lane(0)[a], lane(0)[b]), [128; 4], &hist, builtin)?; - let e = [ - (base[0] + unzig(lane(2)[a])) & 255, - (base[1] + unzig(lane(2)[b])) & 255, - (base[2] + unzig(lane(3)[a])) & 255, - (base[3] + unzig(lane(3)[b])) & 255, - ]; - hist[i] = e; - let o = &mut out[i * 16..i * 16 + 16]; - for ch in 0..2 { - let mut bits = 0u64; - for r in 0..4 { - bits |= pair_bits(pairs, lane(4 + 4 * ch + r)[a], lane(4 + 4 * ch + r)[b])? << (12 * r); - } - o[8 * ch] = e[2 * ch] as u8; - o[8 * ch + 1] = e[2 * ch + 1] as u8; - o[8 * ch + 2..8 * ch + 8].copy_from_slice(&bits.to_le_bytes()[..6]); - } - } - Some(()) -} diff --git a/tools/bcpack_calibration/src/lib.rs b/tools/bcpack_calibration/src/lib.rs deleted file mode 100644 index 636350434..000000000 --- a/tools/bcpack_calibration/src/lib.rs +++ /dev/null @@ -1,354 +0,0 @@ -// BCPack modes 4 through 7. A cell carries a left-aligned value and the number -// of bits established by an archive observation or an earlier decoded block. -use std::slice; - -mod blocks; -mod model; - -#[repr(C)] -#[derive(Copy, Clone, Default)] -struct Cell { - value: u8, - precision: u8, -} -type History = [Cell; 56]; - -fn spread(n: u8) -> usize { - (0..4).map(|k| ((n as usize >> k) & 1) << (2 * k)).sum() -} -fn zig(n: u8) -> i32 { - (n as i32 >> 1) ^ -((n as i32) & 1) -} -fn add(c: Cell, b: u8, delta: i32) -> Cell { - let shift = 8 - b; - let v = (((c.value as i32 >> shift) + delta) & ((1 << b) - 1)) as u8; - if c.precision >= b { - return Cell { - value: v << shift, - precision: 8, - }; - } - let range = (1u16 << (b - c.precision)) - 1; - let end = v as u16 + range; - if end >= (1u16 << b) { - return Cell::default(); - } - let last = (end as u8) << shift; - let first = v << shift; - let precision = (first ^ last).leading_zeros() as u8; - let mask = if precision == 0 { - 0 - } else { - 255u8 << (8 - precision) - }; - Cell { - value: first & mask, - precision, - } -} -fn part(code: u8, parity: u8, bits: u8) -> u8 { - (0..bits) - .map(|k| ((code >> (2 * k + parity)) & 1) << k) - .sum() -} -fn put(out: &mut u128, at: &mut u32, value: u8, bits: u8) -> bool { - if bits == 0 { - return value == 0; - } - if *at + bits as u32 > 128 { - return false; - } - *out |= (value as u128 & ((1u128 << bits) - 1)) << *at; - *at += bits as u32; - (value as u16) < (1u16 << bits) -} - -#[no_mangle] -pub unsafe extern "C" fn rebuild( - input: *const u8, - n: usize, - table: *const i16, - seed: *const u8, - anchor: *const u16, - bytes: *mut u8, - ready: *mut u8, -) { - let sy = slice::from_raw_parts(input, n * 32); - let labels = slice::from_raw_parts(table, 1024 * 4); - let seeds = slice::from_raw_parts(seed as *const History, 256); - let anchors = slice::from_raw_parts(anchor, 128); - let out = slice::from_raw_parts_mut(bytes, n * 16); - let known = slice::from_raw_parts_mut(ready, n); - let mut history = [[Cell::default(); 56]; 256]; - let zero = [Cell { - value: 0, - precision: 8, - }; 56]; - for i in 0..n { - let s = &sy[i * 32..i * 32 + 32]; - let label = &labels[4 * (32 * s[15] as usize + s[31] as usize)..]; - let mode = label[0]; - let mut cur = [Cell::default(); 56]; - known[i] = 0; - if !(0..=7).contains(&mode) || !(0..=3).contains(&label[2]) || !(0..64).contains(&label[1]) - { - history[i % 256] = cur; - continue; - } - if (label[2] != 0 && !matches!(mode, 4 | 5)) || (mode == 0 && label[1] >= 16) { - history[i % 256] = cur; - continue; - } - let rot = label[2] as usize; - let partition = label[1] as usize; - let di = spread(s[1]) + 2 * spread(s[17]); - let de = ((di as i32 + zig((spread(s[0]) + 2 * spread(s[16])) as u8)) & 255) as usize; - let reference = |d: usize| -> &History { - if d == 0 { - &zero - } else if d > i { - &seeds[d - i] - } else { - &history[(i - d) % 256] - } - }; - let e = reference(de); - let w = reference(di); - let (mut bits, planes): ([u8; 4], [u8; 2]) = match mode { - 0 => ([5, 4, 4, 0], [0, 3]), - 1 => ([7, 6, 6, 0], [0, 3]), - 2 => ([5, 5, 5, 0], [0, 2]), - 3 => ([8, 7, 7, 0], [0, 2]), - 4 => ([5, 5, 5, 6], [2, 3]), - 5 => ([7, 7, 7, 8], [2, 2]), - 6 => ([8, 7, 7, 7], [0, 4]), - _ => ([6, 5, 5, 5], [0, 2]), - }; - if rot > 0 { - bits.swap(rot - 1, 3) - } - let count = [6, 4, 6, 4, 2, 2, 2, 4][mode as usize]; - let mut ep = [[0u8; 4]; 6]; - let mut ok = true; - for j in 0..count { - for c in 0..4 { - let z = j * 4 + c; - let b = bits[c]; - if b == 0 { - cur[z] = zero[0]; - continue; - } - let lane = [[2, 3, 4, 5], [6, 7, 8, 9], [10, 5, 9, 0]][j / 2][c]; - cur[z] = add(e[z], b, zig(s[(j % 2) * 16 + lane])); - ok &= cur[z].precision >= b; - ep[j][c] = cur[z].value >> (8 - b); - } - if rot > 0 { - ep[j].swap(rot - 1, 3) - } - } - if count == 2 { - cur.copy_within(0..8, 8) - } - if count < 6 { - cur.copy_within(0..8, 16) - } - let mut indices = [[0u8; 16]; 2]; - for (plane, &b) in planes.iter().enumerate() { - if b == 0 { - for cell in &mut cur[24..40] { - *cell = zero[0] - } - continue; - } - let lanes = if plane == 0 { - [6, 7, 8, 10] - } else { - [11, 12, 13, 14] - }; - for (row, &lane) in lanes.iter().enumerate() { - for half in 0..2 { - let code = s[half * 16 + lane]; - for k in 0..2 { - let parity = if row == 3 { k } else { 1 - k }; - let p = row * 4 + half * 2 + k; - let at = 24 + 16 * plane + p; - cur[at] = add(w[at], b, zig(part(code, parity as u8, b))); - ok &= cur[at].precision >= b; - indices[plane][p] = cur[at].value >> (8 - b); - } - } - } - } - history[i % 256] = cur; - if !ok || label[1] < 0 { - continue; - } - let (mut data, mut at) = (1u128 << mode, (mode + 1) as u32); - if count > 2 { - put( - &mut data, - &mut at, - partition as u8, - if mode == 0 { 4 } else { 6 }, - ); - } - if mode == 4 || mode == 5 { - put(&mut data, &mut at, rot as u8, 2); - } - if mode == 4 { - put(&mut data, &mut at, label[3] as u8, 1); - } - if rot > 0 { - bits.swap(rot - 1, 3) - } - let has_p = matches!(mode, 0 | 1 | 3 | 6 | 7); - for c in 0..4 { - for e in &ep[..count] { - let drop = (has_p && c == 0) as u8; - put(&mut data, &mut at, e[c] >> drop, bits[c] - drop); - } - } - if has_p { - for j in 0..count { - if mode == 1 && j % 2 == 1 { - ok &= (ep[j][0] & 1) == (ep[j - 1][0] & 1); - continue; - } - put(&mut data, &mut at, ep[j][0] & 1, 1); - } - } - let mask = if count > 2 { - anchors[(count / 2 - 2) * 64 + partition] - } else { - 1 - }; - for wire in 0..2 { - let plane = if mode == 5 { 1 - wire } else { wire }; - let b = planes[plane]; - if b > 0 { - for p in 0..16 { - ok &= put( - &mut data, - &mut at, - indices[plane][p], - b - ((mask >> p) & 1) as u8, - ); - } - } - } - if ok && at == 128 { - known[i] = 1; - out[i * 16..i * 16 + 16].copy_from_slice(&data.to_le_bytes()); - } - } -} - -// Python owns the byte input and the target-by-lanes uint8 output buffer. -#[no_mangle] -pub unsafe extern "C" fn unpack( - data: *const u8, - size: usize, - widths: *const u8, - lanes: usize, - target: usize, - output: *mut u8, -) -> isize { - let stream = slice::from_raw_parts(data, size); - let bits = slice::from_raw_parts(widths, lanes); - if bits.iter().any(|&b| b > 7) { - return -1; - } - let Ok(decoded) = bcpack_rans::rans::decode_slice(stream, bits, target) else { - return -1; - }; - let out = slice::from_raw_parts_mut(output, target * lanes); - for lane in 0..lanes { - for (i, &v) in decoded.lane(lane).iter().enumerate() { - out[i * lanes + lane] = v as u8; - } - } - decoded.consumed as isize -} - -// The lane-array model of tools/bcpack.py: same streams accepted, same symbols. -// `tables` is the flat i32 table of `model::Tables::new`; `output` receives -// `lanes * target` u16 symbols, lane-major. Returns the bytes used, or -1. -#[no_mangle] -pub unsafe extern "C" fn unpack_model( - data: *const u8, - size: usize, - widths: *const u8, - lanes: usize, - target: usize, - tables: *const i32, - tables_len: usize, - output: *mut u16, -) -> isize { - let stream = slice::from_raw_parts(data, size); - let bits = slice::from_raw_parts(widths, lanes); - let Some(t) = model::Tables::new(slice::from_raw_parts(tables, tables_len)) else { - return -1; - }; - let Some((symbols, used)) = model::decode(stream, bits, target, &t) else { - return -1; - }; - if stream[used..].iter().any(|&b| b != 0) { - return -1; - } - slice::from_raw_parts_mut(output, lanes * target).copy_from_slice(&symbols); - used as isize -} - -// Lanes and the strict block rebuild of codec 1 (BC1), 3 (BC3), 4 (BC4) or 5 -// (BC5) in one call. `lut` is BC1_QUADRANT, the flattened BC3_ALPHA_PAIR then -// BC3_COLOUR_QUADRANT, the flattened BC4_PAIR or the flattened BC5_PAIR, -// `builtin` the confirmed built-in history (rows of 6, 8, 2 or 4 values, -1 where absent). Returns the bytes -// used, or -1: then Python decodes the chunk itself. -#[no_mangle] -pub unsafe extern "C" fn decode_blocks( - data: *const u8, - size: usize, - codec: u32, - widths: *const u8, - lanes: usize, - target: usize, - tables: *const i32, - tables_len: usize, - lut: *const u8, - lut_len: usize, - builtin: *const i32, - builtin_len: usize, - output: *mut u8, - output_len: usize, -) -> isize { - if lanes != 12 { - return -1; - } - let stream = slice::from_raw_parts(data, size); - let bits = slice::from_raw_parts(widths, lanes); - let Some(t) = model::Tables::new(slice::from_raw_parts(tables, tables_len)) else { - return -1; - }; - let Some((symbols, used)) = model::decode(stream, bits, target, &t) else { - return -1; - }; - if stream[used..].iter().any(|&b| b != 0) { - return -1; - } - let lut = slice::from_raw_parts(lut, lut_len); - let builtin = slice::from_raw_parts(builtin, builtin_len); - let out = slice::from_raw_parts_mut(output, output_len); - let done = match codec { - 1 => blocks::bc1(&symbols, target, lut, builtin, out), - 3 => blocks::bc3(&symbols, target, lut, builtin, out), - 4 => blocks::bc4(&symbols, target, lut, builtin, out), - 5 => blocks::bc5(&symbols, target, lut, builtin, out), - _ => None, - }; - if done.is_some() { - used as isize - } else { - -1 - } -} diff --git a/tools/bcpack_calibration/src/model.rs b/tools/bcpack_calibration/src/model.rs deleted file mode 100644 index 8826a9258..000000000 --- a/tools/bcpack_calibration/src/model.rs +++ /dev/null @@ -1,326 +0,0 @@ -// A line-by-line port of `_decode_lanes_raw` in tools/bcpack.py (the lane-array -// model of docs/textures.md, with its virtual zero bytes), so Python and Rust -// accept the same streams. Python passes its own probability tables in. The -// state is an i128 because the Python model works on unbounded integers: a -// fragment that lands below zero is shifted left and compared, never wrapped. -// Any refusal returns None; Python then decodes the stream again and raises its -// own message. -const RANS_L: i128 = 1 << 24; -const MAX_WIDTH: usize = 10; -const PREFETCH_BUDGET: u32 = 8; -const MAX_VIRTUAL_ZEROS: u32 = 8; -const HDR0: u8 = 0; -const HDR1: u8 = 1; -const HDR2: u8 = 2; -const PROC: u8 = 3; - -/// `freq[w][q]` (bands 0..=w) and its running `base`, or None where Python has no table. -pub struct Tables { - models: Vec>, -} - -impl Tables { - /// `flat[(w * 16 + q) * 11 + p]` for w in 0..=10; a table whose first entry is -1 is absent. - pub fn new(flat: &[i32]) -> Option { - if flat.len() != (MAX_WIDTH + 1) * 16 * (MAX_WIDTH + 1) { - return None; - } - let mut models = Vec::with_capacity((MAX_WIDTH + 1) * 16); - for w in 0..=MAX_WIDTH { - for q in 0..16 { - let row = &flat[(w * 16 + q) * (MAX_WIDTH + 1)..][..MAX_WIDTH + 1]; - if row[0] < 0 { - models.push(None); - continue; - } - let mut freq = [0i128; MAX_WIDTH + 1]; - let mut base = [0i128; MAX_WIDTH + 1]; - let mut acc = 0i128; - for p in 0..=w { - freq[p] = row[p] as i128; - base[p] = acc; - acc += freq[p] * if p == 0 { 1 } else { 1 << (p - 1) }; - } - if acc != 65536 { - return None; - } - models.push(Some((freq, base))); - } - } - Some(Tables { models }) - } - - fn get(&self, w: usize, q: usize) -> Option { - self.models[w * 16 + q].as_ref().map(|_| w * 16 + q) - } - - fn lookup(&self, m: usize, cf: i128) -> Option { - let (freq, base) = self.models[m].as_ref().unwrap(); - let mut p = m / 16; - while p > 0 && cf < base[p] { - p -= 1; - } - if p == 0 { - return Some(0); - } - if freq[p] == 0 { - return None; - } - Some((1i128 << (p - 1)) + (cf - base[p]).div_euclid(freq[p])) - } - - fn advance(&self, m: usize, s: i128, x: i128) -> i128 { - let (freq, base) = self.models[m].as_ref().unwrap(); - let p = (128 - s.leading_zeros()) as usize; - let mut f = freq[p]; - let mut c = base[p] + f * (s - if p == 0 { 0 } else { 1 << (p - 1) }); - if c == 0 { - f -= 1; - c = 1; - } - f * (x >> 16) + (x & 0xFFFF) - c - } -} - -/// `(symbols lane-major, bytes used)`, or None where the Python model raises. -pub fn decode(raw: &[u8], widths: &[u8], nsym: usize, t: &Tables) -> Option<(Vec, usize)> { - let nl = widths.len(); - let mut ctrl = vec![HDR0; nl]; - let mut out_rem = vec![nsym; nl]; - let mut w = vec![0usize; nl]; - let mut q = vec![0usize; nl]; - let mut h3 = vec![false; nl]; - let mut flush = vec![false; nl]; - let mut done = vec![nsym == 0; nl]; - let mut full = vec![false; nl]; - let mut held = vec![false; nl]; - let mut vz = vec![0u32; nl]; - let mut inbuf = vec![0i128; nl]; - let mut sym = vec![0i128; nl]; - let mut in_rem = vec![0i128; nl]; - let mut p0 = vec![0i128; nl]; - let mut p1 = vec![0i128; nl]; - let mut model = vec![usize::MAX; nl]; - let mut slotfull = vec![false; nl]; - let mut slotval = vec![0i128; nl]; - let mut stall = vec![false; nl]; - let mut out: Vec> = vec![Vec::with_capacity(nsym); nl]; - let mut pos = 0usize; - // The Python model has no cycle limit. A stream on which no lane changes - // for this many cycles is handed back to Python unchanged. - let mut idle = 0u32; - - loop { - if (0..nl).all(|i| done[i] && !slotfull[i]) { - let mut flat = Vec::with_capacity(nl * nsym); - for lane in &out { - if lane.len() != nsym { - return None; - } - flat.extend_from_slice(lane); - } - return Some((flat, pos)); - } - let before = (pos, out.iter().map(Vec::len).sum::()); - let mut moved = false; - - let mut left = PREFETCH_BUDGET; - for i in 0..nl { - if done[i] { - stall[i] = true; - continue; - } - if held[i] && slotfull[i] { - stall[i] = true; - continue; - } - stall[i] = false; - if ctrl[i] == PROC { - p0[i] = if held[i] { t.advance(model[i], sym[i], p1[i]) } else { p1[i] }; - } - if !full[i] && (ctrl[i] != PROC || in_rem[i] > 0) { - if left == 0 { - stall[i] = true; - continue; - } - if pos >= raw.len() { - return None; - } - inbuf[i] = raw[pos] as i128; - pos += 1; - full[i] = true; - left -= 1; - } - if held[i] { - slotfull[i] = true; - slotval[i] = sym[i]; - held[i] = false; - moved = true; - } - } - - for i in 0..nl { - if done[i] || stall[i] { - continue; - } - match ctrl[i] { - HDR0 => { - if !full[i] { - continue; - } - let h = inbuf[i]; - q[i] = (h & 15) as usize; - flush[i] = (h >> 4) & 1 != 0; - h3[i] = (h >> 5) & 1 != 0; - let wi = widths[i] as i128 - (h >> 6); - if !(1..=MAX_WIDTH as i128).contains(&wi) { - // Python checks the width at HDR1; it fails there either way. - w[i] = usize::MAX; - } else { - w[i] = wi as usize; - } - full[i] = false; - ctrl[i] = HDR1; - vz[i] = 0; - moved = true; - } - HDR1 => { - if !full[i] { - continue; - } - full[i] = false; - if w[i] == usize::MAX { - return None; - } - model[i] = t.get(w[i], q[i])?; - if h3[i] { - in_rem[i] = inbuf[i]; - ctrl[i] = HDR2; - } else { - in_rem[i] = inbuf[i] + 1; - ctrl[i] = PROC; - } - moved = true; - } - HDR2 => { - if !full[i] { - continue; - } - in_rem[i] = ((inbuf[i] << 8) | (in_rem[i] & 0xFF)) + 257; - ctrl[i] = PROC; - full[i] = false; - moved = true; - } - _ => { - let mut st = p0[i]; - if st < 0 { - // Only a corrupt stream gets here; leave it to Python. - return None; - } - if st < RANS_L { - if in_rem[i] > 0 { - if full[i] { - st = (st << 8) | inbuf[i]; - in_rem[i] -= 1; - full[i] = false; - if in_rem[i] == 0 && flush[i] { - while st < RANS_L && st != 0 && vz[i] < MAX_VIRTUAL_ZEROS { - st <<= 8; - vz[i] += 1; - } - } - } - } else if flush[i] { - if st == 0 || vz[i] >= MAX_VIRTUAL_ZEROS { - return None; - } - while st < RANS_L && st != 0 && vz[i] < MAX_VIRTUAL_ZEROS { - st <<= 8; - vz[i] += 1; - } - } else { - p1[i] = st; - if out_rem[i] > 0 { - ctrl[i] = HDR0; - } else { - done[i] = true; - } - moved = true; - continue; - } - } - let nxt = st > RANS_L && out_rem[i] > 0; - if nxt { - let s = t.lookup(model[i], st & 0xFFFF)?; - sym[i] = s; - out_rem[i] -= 1; - if s >> w[i] != 0 { - return None; - } - } - if nxt != held[i] || p1[i] != st { - moved = true; - } - held[i] = nxt; - p1[i] = st; - if in_rem[i] == 0 { - if flush[i] { - if st == RANS_L { - if out_rem[i] > 0 { - ctrl[i] = HDR0; - p0[i] = 0; - p1[i] = 0; - } else { - done[i] = true; - } - moved = true; - } else if st > RANS_L && !nxt { - return None; - } - } else if out_rem[i] == 0 && !nxt { - done[i] = true; - moved = true; - } - } else if st == RANS_L || (out_rem[i] == 0 && !nxt && st > RANS_L) { - return None; - } - } - } - } - - let mut ready = true; - let mut anyfull = false; - for i in 0..nl { - if slotfull[i] { - anyfull = true; - } else if !(done[i] && !held[i]) { - ready = false; - break; - } - } - if ready && anyfull { - for i in 0..nl { - if slotfull[i] { - out[i].push(slotval[i] as u16); - slotfull[i] = false; - } - } - } - for i in 0..nl { - if done[i] && held[i] && !slotfull[i] { - slotfull[i] = true; - slotval[i] = sym[i]; - held[i] = false; - moved = true; - } - } - if (pos, out.iter().map(Vec::len).sum::()) != before || moved { - idle = 0; - } else { - idle += 1; - if idle > 1 << 16 { - return None; - } - } - } -} diff --git a/tools/bcpack_history_calib.py b/tools/bcpack_history_calib.py deleted file mode 100644 index 4c8312b41..000000000 --- a/tools/bcpack_history_calib.py +++ /dev/null @@ -1,2791 +0,0 @@ -"""Local pure-Python BCPack initial-history calibration and validation tool. - -Derives, merges, and validates local `--history` JSON tables for `tools/bcpack.py` -and `tools/ttpf_mips.py` strictly from the player's own TTPF pools and/or -supplied reference DDS/block pairs. No game data is embedded in or written by -this repository. - -Two complementary calibration paths are supported (and may be combined): -1. Exact reference-pair inversion (`--ref-dds POOL:INDEX=REF.dds` or - `--ref-pairs PAIRS.json`): algebraically inverts built-in history references - against exact BCn reference blocks, producing **confirmed** entries - (`class 3` with per-field `ConfirmedBits` for BC6H, `ConfirmedBits` for BC7, - `confirmed` for BC1-BC5). -2. Pool self-calibration (from TTPF `.ttpf` files or directories): combines - exact algebraic bitstream constraints (BC6H/BC7 anchor MSB constraints and - BC7 Mode-1 shared p-bit parity), intra-block smoothness index voting, and - sibling raw/zlib mip endpoint fitting on mixed-codec textures to produce - **provisional** tables usable with `--history --allow-provisional`. -""" -import argparse -import json -import os -import struct -import sys - -_TOOLS_DIR = os.path.dirname(os.path.abspath(__file__)) -if _TOOLS_DIR not in sys.path: - sys.path.insert(0, _TOOLS_DIR) - -import bcpack # noqa: E402 -import bcpack_tables as _tables # noqa: E402 -import bcpack_tables_bptc as _bptc # noqa: E402 -import ttpf_mips as _ttpf # noqa: E402 - -if hasattr(sys.stdout, "reconfigure"): - try: - sys.stdout.reconfigure(errors="replace") - except Exception: - pass -if hasattr(sys.stderr, "reconfigure"): - try: - sys.stderr.reconfigure(errors="replace") - except Exception: - pass - - -class CliError(Exception): - """User-facing CLI error reported cleanly without a traceback.""" - - -ALL_CODECS = (1, 3, 4, 5, 6, 7) -DEFAULT_CODECS = (6, 7) -CODEC_KEYS = {1: "bc1", 3: "bc3", 4: "bc4", 5: "bc5", 6: "bc6h", 7: "bc7"} -CODEC_ALIASES = { - "1": 1, "bc1": 1, - "3": 3, "bc3": 3, - "4": 4, "bc4": 4, - "5": 5, "bc5": 5, - "6": 6, "bc6": 6, "bc6h": 6, - "7": 7, "bc7": 7, -} -CODEC_DXGI = { - 1: frozenset((70, 71, 72)), - 3: frozenset((76, 77, 78)), - 4: frozenset((79, 80, 81)), - 5: frozenset((82, 83, 84)), - 6: frozenset((94, 95, 96)), - 7: frozenset((97, 98, 99)), -} -BC_MODS = { - 1: (32, 64, 32, 32, 64, 32), - 3: (256, 256, 32, 64, 32, 32, 64, 32), - 4: (256, 256), - 5: (256, 256, 256, 256), -} -_BC6H_CODE_TO_MODE = {code: mode for mode, code in enumerate(bcpack._BC6H_CODE) if mode > 0} -_FOURCC_DXGI = { - b"DXT1": 71, - b"DXT5": 77, - b"ATI1": 80, - b"BC4U": 80, - b"BC4S": 81, - b"ATI2": 83, - b"BC5U": 83, - b"BC5S": 84, -} - - -def parse_codecs(spec): - """Parse a comma-separated codec list or `'all'` into a deduplicated tuple of IDs.""" - if not spec or not spec.strip(): - raise CliError("--codec must not be empty") - tokens = [tok.strip().lower() for tok in spec.split(",") if tok.strip()] - if not tokens: - raise CliError("--codec must not be empty") - out = [] - for tok in tokens: - if tok == "all": - for cid in ALL_CODECS: - if cid not in out: - out.append(cid) - continue - cid = CODEC_ALIASES.get(tok) - if cid is None: - valid = ", ".join(sorted(CODEC_KEYS.values()) + ["all"]) - raise CliError(f"unknown codec {tok!r} (expected one of: {valid})") - if cid not in out: - out.append(cid) - return tuple(out) - - -# --------------------------------------------------------------------------- -# Fast prefix rANS lane decoder -# --------------------------------------------------------------------------- - -def decode_lanes_prefix(raw, codec, out_size, max_sym): - """Decode up to `max_sym` symbols per lane from a BCPack chunk. - - Because direct built-in history references (`d > i`) can only occur in - blocks `0..255`, stopping the forward rANS scheduler after a short prefix - avoids decoding tens of thousands of trailing blocks per chunk. - """ - nsym = out_size // 8 - if max_sym <= 0 or max_sym >= nsym: - return bcpack.decode_lanes(raw, codec, out_size)[0] - widths = bcpack.LANE_WIDTHS[codec] - nl = len(widths) - HDR0, HDR1, HDR2, PROC = 0, 1, 2, 3 - L = bcpack.RANS_L - ctrl = [HDR0] * nl - out_rem = [nsym] * nl - w = [0] * nl - q = [0] * nl - h3 = [0] * nl - flush = [0] * nl - done = [False] * nl - full = [False] * nl - held = [False] * nl - vz = [0] * nl - inbuf = [0] * nl - sym = [0] * nl - in_rem = [0] * nl - p0 = [0] * nl - p1 = [0] * nl - model = [None] * nl - slotfull = [False] * nl - slotval = [0] * nl - stall = [False] * nl - out = [[] for _ in range(nl)] - pos = 0 - nraw = len(raw) - data = memoryview(raw) - emitted = 0 - while emitted < max_sym: - left = 8 - for i in range(nl): - if done[i] or (held[i] and slotfull[i]): - stall[i] = True - continue - stall[i] = False - if ctrl[i] == PROC: - p0[i] = model[i].advance(sym[i], p1[i]) if held[i] else p1[i] - if not full[i] and (ctrl[i] != PROC or in_rem[i] > 0): - if left == 0: - stall[i] = True - continue - if pos >= nraw: - raise bcpack.BcpackError("BCPack lane stream ended before prefix symbols finished") - inbuf[i] = data[pos] - pos += 1 - full[i] = True - left -= 1 - if held[i]: - slotfull[i] = True - slotval[i] = sym[i] - held[i] = False - for i in range(nl): - if done[i] or stall[i]: - continue - c = ctrl[i] - if c == HDR0: - if not full[i]: - continue - h = inbuf[i] - q[i] = h & 15 - flush[i] = (h >> 4) & 1 - h3[i] = (h >> 5) & 1 - w[i] = widths[i] - (h >> 6) - full[i] = False - ctrl[i] = HDR1 - vz[i] = 0 - elif c == HDR1: - if not full[i]: - continue - full[i] = False - model[i] = bcpack._get_model(w[i], q[i]) - if h3[i]: - in_rem[i] = inbuf[i] - ctrl[i] = HDR2 - else: - in_rem[i] = inbuf[i] + 1 - ctrl[i] = PROC - elif c == HDR2: - if not full[i]: - continue - in_rem[i] = ((inbuf[i] << 8) | (in_rem[i] & 0xFF)) + 257 - ctrl[i] = PROC - full[i] = False - else: - st = p0[i] - if st < L: - if in_rem[i] > 0: - if full[i]: - st = (st << 8) | inbuf[i] - in_rem[i] -= 1 - full[i] = False - if in_rem[i] == 0 and flush[i]: - while st < L and st != 0 and vz[i] < 8: - st <<= 8 - vz[i] += 1 - elif flush[i]: - while st < L and st != 0 and vz[i] < 8: - st <<= 8 - vz[i] += 1 - else: - p1[i] = st - if out_rem[i] > 0: - ctrl[i] = HDR0 - else: - done[i] = True - continue - nxt = st > L and out_rem[i] > 0 - if nxt: - sym[i] = model[i].lookup(st & 0xFFFF) - out_rem[i] -= 1 - held[i] = nxt - p1[i] = st - if in_rem[i] == 0: - if flush[i]: - if st == L: - if out_rem[i] > 0: - ctrl[i] = HDR0 - p0[i] = 0 - p1[i] = 0 - else: - done[i] = True - elif out_rem[i] == 0 and not nxt: - done[i] = True - ready = True - anyfull = False - for i in range(nl): - if slotfull[i]: - anyfull = True - elif not (done[i] and not held[i]): - ready = False - break - if ready and anyfull: - for i in range(nl): - if slotfull[i]: - out[i].append(slotval[i]) - slotfull[i] = False - emitted += 1 - for i in range(nl): - if done[i] and held[i] and not slotfull[i]: - slotfull[i] = True - slotval[i] = sym[i] - held[i] = False - return out - - -# --------------------------------------------------------------------------- -# RDNA2 tile coordinate helpers and DDS reader -# --------------------------------------------------------------------------- - -def _tile_pattern(layout): - eb = layout["element_bytes"] - pats = _ttpf.PATTERNS_4K if layout["tile"] == 4096 else _ttpf.PATTERNS_64K - return pats[{1: 0, 2: 1, 4: 2, 8: 3, 16: 4}[eb]] - - -def tiled_offset(layout, mip, bx, by): - """Return the byte offset of block `(bx, by)` inside `mip`'s tiled region.""" - pat = _tile_pattern(layout) - bw, bh = layout["block_w"], layout["block_h"] - off = ((by // bh) * (mip["padded_w"] // bw) + bx // bw) * layout["tile"] - tx, ty = bx + mip["tile_x"], by + mip["tile_y"] - for bit, s in enumerate(pat): - if s > 0: - off |= ((tx >> (s - 1)) & 1) << bit - elif s < 0: - off |= ((ty >> (-s - 1)) & 1) << bit - return off - - -def make_inverse_tile_lookup(layout, mip): - """Return a fast function mapping a mip-relative byte offset to `(bx, by)` or `None`.""" - pat = _tile_pattern(layout) - tile = layout["tile"] - bw, bh = layout["block_w"], layout["block_h"] - tiles_x = mip["padded_w"] // bw - tx0, ty0 = mip["tile_x"], mip["tile_y"] - w, h = mip["blocks_w"], mip["blocks_h"] - reg = mip["region"] - x_bits = tuple((bit, 1 << (s - 1)) for bit, s in enumerate(pat) if s > 0) - y_bits = tuple((bit, 1 << (-s - 1)) for bit, s in enumerate(pat) if s < 0) - - def lookup(rel_off): - if rel_off < 0 or rel_off >= reg: - return None - tile_idx = rel_off // tile - in_tile = rel_off % tile - lx = 0 - for bit, val in x_bits: - if (in_tile >> bit) & 1: - lx |= val - ly = 0 - for bit, val in y_bits: - if (in_tile >> bit) & 1: - ly |= val - bx = (tile_idx % tiles_x) * bw + lx - tx0 - by = (tile_idx // tiles_x) * bh + ly - ty0 - if 0 <= bx < w and 0 <= by < h: - return bx, by - return None - - return lookup - - -def retile_mip(linear, layout, mip): - """Place a linear DDS mip payload into its RDNA2 tiled byte buffer.""" - out = bytearray(mip["region"]) - _retile_mip_into(linear, layout, mip, out) - return bytes(out) - - -def _retile_mip_into(linear: bytes, layout: dict, mip: dict, out: bytearray, - known: bytearray | None = None) -> None: - """Write one mip's blocks into its region, which may also hold other tail mips.""" - eb = layout["element_bytes"] - bw, bh = mip["blocks_w"], mip["blocks_h"] - expected = bw * bh * eb - if len(linear) < expected: - raise ValueError(f"DDS mip payload truncated ({len(linear)} < {expected} bytes)") - mv = memoryview(linear) - row_stride = bw * eb - for by in range(bh): - row_at = by * row_stride - for bx in range(bw): - off = tiled_offset(layout, mip, bx, by) - src = row_at + bx * eb - out[off:off + eb] = mv[src:src + eb] - if known is not None: - known[off:off + eb] = b"\x01" * eb - - -def read_dds(path): - """Read a DX9 or DX10 2D BCn DDS file into `(dxgi, width, height, mips_list)`.""" - with open(path, "rb") as fh: - data = fh.read() - if len(data) < 128 or data[:4] != b"DDS ": - raise ValueError(f"{path}: not a valid DDS file") - hdr_size = struct.unpack_from(" len(data): - raise ValueError(f"{path}: truncated payload at mip {m}") - mips.append(data[off:off + sz]) - off += sz - mw = max(1, mw >> 1) - mh = max(1, mh >> 1) - return dxgi, width, height, mips - - -# --------------------------------------------------------------------------- -# Pure-Python BC1 / BC3 / BC4 / BC5 / BC6H / BC7 block decoders (for sibling mips) -# --------------------------------------------------------------------------- - -def _rgb565_channels(c): - r = ((c >> 11) & 31) * 255.0 / 31.0 - g = ((c >> 5) & 63) * 255.0 / 63.0 - b = (c & 31) * 255.0 / 31.0 - return r, g, b - - -def decode_bc1_block_rgba(data, at): - c0, c1, idx = struct.unpack_from(" c1: - pal = ( - (r0, g0, b0, 255.0), - (r1, g1, b1, 255.0), - ((2.0 * r0 + r1) / 3.0, (2.0 * g0 + g1) / 3.0, (2.0 * b0 + b1) / 3.0, 255.0), - ((r0 + 2.0 * r1) / 3.0, (g0 + 2.0 * g1) / 3.0, (b0 + 2.0 * b1) / 3.0, 255.0), - ) - else: - pal = ( - (r0, g0, b0, 255.0), - (r1, g1, b1, 255.0), - (0.5 * (r0 + r1), 0.5 * (g0 + g1), 0.5 * (b0 + b1), 255.0), - (0.0, 0.0, 0.0, 0.0), - ) - return [pal[(idx >> (2 * p)) & 3] for p in range(16)] - - -def decode_bc4_block_u8(data, at): - a0, a1 = data[at], data[at + 1] - bits = int.from_bytes(data[at + 2:at + 8], "little") - if a0 > a1: - pal = ( - float(a0), float(a1), - (6.0 * a0 + 1.0 * a1) / 7.0, (5.0 * a0 + 2.0 * a1) / 7.0, - (4.0 * a0 + 3.0 * a1) / 7.0, (3.0 * a0 + 4.0 * a1) / 7.0, - (2.0 * a0 + 5.0 * a1) / 7.0, (1.0 * a0 + 6.0 * a1) / 7.0, - ) - else: - pal = ( - float(a0), float(a1), - (4.0 * a0 + 1.0 * a1) / 5.0, (3.0 * a0 + 2.0 * a1) / 5.0, - (2.0 * a0 + 3.0 * a1) / 5.0, (1.0 * a0 + 4.0 * a1) / 5.0, - 0.0, 255.0, - ) - return [pal[(bits >> (3 * p)) & 7] for p in range(16)] - - -def decode_bc3_block_rgba(data, at): - al = decode_bc4_block_u8(data, at) - c0, c1, idx = struct.unpack_from("> (2 * p)) & 3] - out[p] = (r, g, b, al[p]) - return out - - -def decode_bc5_block_rg(data, at): - rs = decode_bc4_block_u8(data, at) - gs = decode_bc4_block_u8(data, at + 8) - return [(rs[p], gs[p]) for p in range(16)] - - -def _sign_extend(val, bits): - sign = 1 << (bits - 1) - return (val ^ sign) - sign - - -def _bc6h_unquantize(val, bits, signed=False): - if not signed: - if bits >= 15: - return val - if val == 0: - return 0 - if val == (1 << bits) - 1: - return 0xFFFF - return ((val << 16) + 0x8000) >> bits - neg = val < 0 - v = -val if neg else val - if bits >= 16: - out = v - elif v == 0: - out = 0 - elif v >= (1 << (bits - 1)) - 1: - out = 0x7FFF - else: - out = ((v << 15) + 0x4000) >> (bits - 1) - return -out if neg else out - - -def unpack_bc6h_block(data, at): - """Unpack a 16-byte BC6H block into `(mode, part, f_wxyz, ix_block)` or `None`.""" - acc = int.from_bytes(data[at:at + 16], "little") - m2 = acc & 3 - code = m2 if m2 < 2 else (acc & 0x1F) - mode = _BC6H_CODE_TO_MODE.get(code) - if mode is None: - return None - _trans, _base, _deltas, reg = bcpack._BC6H_INFO[code] - plan, header = bcpack._bc6h_plan(code) - f = [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]] - part = 0 - for c, q, bit_idx, pos in plan: - if (acc >> pos) & 1: - if c < 0: - part |= 1 << bit_idx - else: - f[c][q] |= 1 << bit_idx - for c in range(3): - f[c][0] = bcpack._bc6h_stream_w(mode, f[c][0]) - ibits = 3 if reg == 2 else 4 - second = _bptc.BC7_ANCHOR2[part] if reg == 2 else -1 - pos = header - ix = [0] * 16 - for p in range(16): - nb = (ibits - 1) if (p == 0 or p == second) else ibits - ix[p] = (acc >> pos) & ((1 << nb) - 1) - pos += nb - return mode, part, f, ix - - -def decode_bc6h_block_unq(data, at, signed=False): - """Decode one 16-byte BC6H block into 16 `(r, g, b)` tuples in 16-bit unquantized space.""" - parsed = unpack_bc6h_block(data, at) - if parsed is None: - return [(0.0, 0.0, 0.0)] * 16 - mode, part, f, ix = parsed - code = bcpack._BC6H_CODE[mode] - trans, base, deltas, reg = bcpack._BC6H_INFO[code] - mw = (1 << base) - 1 - ep = [[0.0, 0.0, 0.0, 0.0] for _ in range(3)] - for c in range(3): - w, x, y, z = f[c] - w = bcpack._bc6h_stream_w(mode, w) - dc = deltas[c] - if signed: - w = _sign_extend(w, base) - if trans: - e0 = w - e1 = (w + _sign_extend(x, dc)) & mw - if signed: - e1 = _sign_extend(e1, base) - ep[c][0] = float(_bc6h_unquantize(e0, base, signed)) - ep[c][1] = float(_bc6h_unquantize(e1, base, signed)) - if reg == 2: - e2 = (w + _sign_extend(y, dc)) & mw - e3 = (w + _sign_extend(z, dc)) & mw - if signed: - e2 = _sign_extend(e2, base) - e3 = _sign_extend(e3, base) - ep[c][2] = float(_bc6h_unquantize(e2, base, signed)) - ep[c][3] = float(_bc6h_unquantize(e3, base, signed)) - else: - if signed: - x = _sign_extend(x, dc) - y = _sign_extend(y, dc) - z = _sign_extend(z, dc) - ep[c][0] = float(_bc6h_unquantize(w, base, signed)) - ep[c][1] = float(_bc6h_unquantize(x, dc, signed)) - if reg == 2: - ep[c][2] = float(_bc6h_unquantize(y, dc, signed)) - ep[c][3] = float(_bc6h_unquantize(z, dc, signed)) - wt = _ttpf._BPTC_WEIGHTS[3 if reg == 2 else 4] - sm = _bptc.load_bc7()["partition2"][part] if reg == 2 else None - out = [None] * 16 - for p in range(16): - s2 = 0 if sm is None else (sm[p] * 2) - w1 = wt[ix[p]] - w0 = 64 - w1 - out[p] = ( - (w0 * ep[0][s2] + w1 * ep[0][s2 + 1]) / 64.0, - (w0 * ep[1][s2] + w1 * ep[1][s2 + 1]) / 64.0, - (w0 * ep[2][s2] + w1 * ep[2][s2 + 1]) / 64.0, - ) - return out - - -def unpack_bc7_block(data, at): - """Unpack one 16-byte BC7 block into `(mode, part, rot, isel, val_8bit, pri, sec)` or `None`. - - `val_8bit[sub][e][c]` is left-aligned 8-bit in display RGBA order (matching - `val` inside `bcpack._bc7_rebuild` before channel rotation is applied). - """ - b0 = data[at] - if b0 == 0: - return None - mode = (b0 & -b0).bit_length() - 1 - ns, pb, rb, isb, cb, ab, epb, spb, ib, ib2 = _ttpf._BC7_MODES[mode] - blk = int.from_bytes(data[at:at + 16], "little") - pos = mode + 1 - part = (blk >> pos) & ((1 << pb) - 1) if pb else 0 - pos += pb - rot = (blk >> pos) & ((1 << rb) - 1) if rb else 0 - pos += rb - isel = (blk >> pos) & 1 if isb else 0 - pos += isb - n_ep = 2 * ns - cb_mask = (1 << cb) - 1 - raw_c = [[0] * n_ep for _ in range(4)] - for ch in range(3): - row = raw_c[ch] - for k in range(n_ep): - row[k] = (blk >> pos) & cb_mask - pos += cb - if ab: - ab_mask = (1 << ab) - 1 - row = raw_c[3] - for k in range(n_ep): - row[k] = (blk >> pos) & ab_mask - pos += ab - pbits = None - if epb: - pbits = [(blk >> (pos + k)) & 1 for k in range(n_ep)] - pos += n_ep - elif spb: - sp = [(blk >> (pos + s)) & 1 for s in range(ns)] - pos += ns - pbits = [sp[k >> 1] for k in range(n_ep)] - - # Build left-aligned 8-bit values in pre-rotation stream order first. - val = [[[0, 0, 0, 0], [0, 0, 0, 0]] for _ in range(ns)] - for sub in range(ns): - for e in range(2): - k = sub * 2 + e - for ch in range(3): - if pbits is not None: - v = ((raw_c[ch][k] << 1) | pbits[k]) << (8 - cb - 1) - else: - v = raw_c[ch][k] << (8 - cb) - val[sub][e][ch] = v - if ab: - if pbits is not None and epb: - v = ((raw_c[3][k] << 1) | pbits[k]) << (8 - ab - 1) - else: - v = raw_c[3][k] << (8 - ab) - val[sub][e][3] = v - if rot: - # Undo channel rotation so val[sub][e][0..3] matches display RGBA - # (same channel order stored in BCPack's BC7 endpoint history). - val[sub][e][rot - 1], val[sub][e][3] = val[sub][e][3], val[sub][e][rot - 1] - - tab = _bptc.load_bc7() - if ns == 1: - sm = None - anchors = (0,) - elif ns == 2: - sm = tab["partition2"][part] - anchors = (0, tab["anchor2"][part]) - else: - sm = tab["partition3"][part] - anchors = (0, tab["anchor3a"][part], tab["anchor3b"][part]) - - ib_mask = (1 << ib) - 1 - ib_amask = (1 << (ib - 1)) - 1 - idx1 = [0] * 16 - for p in range(16): - sub = 0 if sm is None else sm[p] - if p == anchors[sub]: - idx1[p] = (blk >> pos) & ib_amask - pos += ib - 1 - else: - idx1[p] = (blk >> pos) & ib_mask - pos += ib - - idx2 = None - if ib2: - ib2_mask = (1 << ib2) - 1 - ib2_amask = (1 << (ib2 - 1)) - 1 - idx2 = [0] * 16 - for p in range(16): - if p == 0: - idx2[p] = (blk >> pos) & ib2_amask - pos += ib2 - 1 - else: - idx2[p] = (blk >> pos) & ib2_mask - pos += ib2 - - # Map D3D11 (idx1, idx2) to BCPack's (s1=rows1, s2=rows2): in Mode 4, - # D3D11 writes the 2-bit set (`s2`) first and the 3-bit set (`s1`) second. - s1, s2 = (idx2, idx1) if mode == 4 else (idx1, idx2) - return mode, part, rot, isel, val, s1, s2 - - -def decode_bc7_block_rgba(data, at): - """Decode one 16-byte BC7 block into 16 `(r, g, b, a)` floats in `0..255`.""" - b0 = data[at] - if b0 == 0: - return [(0.0, 0.0, 0.0, 0.0)] * 16 - mode = (b0 & -b0).bit_length() - 1 - ns, pb, rb, isb, cb, ab, epb, spb, ib, ib2 = _ttpf._BC7_MODES[mode] - blk = int.from_bytes(data[at:at + 16], "little") - pos = mode + 1 - part = (blk >> pos) & ((1 << pb) - 1) if pb else 0 - pos += pb - rot = (blk >> pos) & ((1 << rb) - 1) if rb else 0 - pos += rb - isel = (blk >> pos) & 1 if isb else 0 - pos += isb - n_ep = 2 * ns - cb_mask = (1 << cb) - 1 - raw_c = [[0] * n_ep for _ in range(4)] - for ch in range(3): - row = raw_c[ch] - for k in range(n_ep): - row[k] = (blk >> pos) & cb_mask - pos += cb - if ab: - ab_mask = (1 << ab) - 1 - row = raw_c[3] - for k in range(n_ep): - row[k] = (blk >> pos) & ab_mask - pos += ab - c_bits = cb - a_bits = ab - if epb: - pbits = [(blk >> (pos + k)) & 1 for k in range(n_ep)] - pos += n_ep - c_bits += 1 - if ab: - a_bits += 1 - elif spb: - sp = [(blk >> (pos + s)) & 1 for s in range(ns)] - pos += ns - pbits = [sp[k >> 1] for k in range(n_ep)] - c_bits += 1 - else: - pbits = None - c_sh = 8 - c_bits - c_rep = 2 * c_bits - 8 - ep = [[255] * n_ep for _ in range(4)] - for ch in range(3): - src = raw_c[ch] - dst = ep[ch] - for k in range(n_ep): - v = (src[k] << 1) | pbits[k] if pbits is not None else src[k] - dst[k] = (v << c_sh) | (v >> c_rep) - if ab: - a_sh = 8 - a_bits - a_rep = 2 * a_bits - 8 - src = raw_c[3] - dst = ep[3] - for k in range(n_ep): - v = (src[k] << 1) | pbits[k] if (pbits is not None and epb) else src[k] - dst[k] = (v << a_sh) | (v >> a_rep) - tab = _bptc.load_bc7() - if ns == 1: - sm = None - anchors = (0,) - elif ns == 2: - sm = tab["partition2"][part] - anchors = (0, tab["anchor2"][part]) - else: - sm = tab["partition3"][part] - anchors = (0, tab["anchor3a"][part], tab["anchor3b"][part]) - ib_mask = (1 << ib) - 1 - ib_amask = (1 << (ib - 1)) - 1 - idx1 = [0] * 16 - for p in range(16): - sub = 0 if sm is None else sm[p] - if p == anchors[sub]: - idx1[p] = (blk >> pos) & ib_amask - pos += ib - 1 - else: - idx1[p] = (blk >> pos) & ib_mask - pos += ib - if ib2: - ib2_mask = (1 << ib2) - 1 - ib2_amask = (1 << (ib2 - 1)) - 1 - idx2 = [0] * 16 - for p in range(16): - if p == 0: - idx2[p] = (blk >> pos) & ib2_amask - pos += ib2 - 1 - else: - idx2[p] = (blk >> pos) & ib2_mask - pos += ib2 - if isel: - c_idx, c_wt = idx2, _ttpf._BPTC_WEIGHTS[ib2] - a_idx, a_wt = idx1, _ttpf._BPTC_WEIGHTS[ib] - else: - c_idx, c_wt = idx1, _ttpf._BPTC_WEIGHTS[ib] - a_idx, a_wt = idx2, _ttpf._BPTC_WEIGHTS[ib2] - else: - c_idx = a_idx = idx1 - c_wt = a_wt = _ttpf._BPTC_WEIGHTS[ib] - er, eg, eb_, ea = ep - out = [None] * 16 - for p in range(16): - s2 = 0 if sm is None else sm[p] * 2 - wc = c_wt[c_idx[p]] - iwc = 64 - wc - r = (iwc * er[s2] + wc * er[s2 + 1] + 32) >> 6 - g = (iwc * eg[s2] + wc * eg[s2 + 1] + 32) >> 6 - b = (iwc * eb_[s2] + wc * eb_[s2 + 1] + 32) >> 6 - if ab: - wa = a_wt[a_idx[p]] - a = ((64 - wa) * ea[s2] + wa * ea[s2 + 1] + 32) >> 6 - else: - a = 255 - if rot == 1: - r, a = a, r - elif rot == 2: - g, a = a, g - elif rot == 3: - b, a = a, b - out[p] = (float(r), float(g), float(b), float(a)) - return out - - -# --------------------------------------------------------------------------- -# Bit-precision constraint helpers -# --------------------------------------------------------------------------- - -def _merge_top_bits(cur_bits, cur_val, new_bits, new_val, total_bits): - """Merge two left-aligned top-bit constraints, returning `(bits, val, conflict)`.""" - if cur_bits == 0: - return new_bits, new_val, False - overlap = min(cur_bits, new_bits) - shift = total_bits - overlap - if (cur_val >> shift) != (new_val >> shift): - return cur_bits, cur_val, True - if new_bits > cur_bits: - return new_bits, new_val, False - return cur_bits, cur_val, False - - -def _lead_bits_4(mask): - """Return `(left_aligned_val, exact_bits)` shared by all set bits in a 16-bit mask.""" - if mask == 0: - return 0, 0 - surv = [h for h in range(16) if (mask >> h) & 1] - diff = 0 - for h in surv[1:]: - diff |= h ^ surv[0] - bits = 4 - diff.bit_length() - val = surv[0] & (0xF << (4 - bits)) if bits else 0 - return val, bits - - -def _eval_bc7_ops(ops, h): - v = h - for bits, dz in ops: - sh = 8 - bits - m = (1 << bits) - 1 - v = (((v >> sh) + dz) & m) << sh - return v - - -# --------------------------------------------------------------------------- -# Per-codec calibrators -# --------------------------------------------------------------------------- - -class BcSimpleCalibrator: - """Calibrator for BC1 (1), BC3 (3), BC4 (4), and BC5 (5) endpoint history tables.""" - - def __init__(self, codec): - self.codec = codec - self.mods = BC_MODS[codec] - self.ncols = len(self.mods) - self.confirmed = {} - self.conflicts = 0 - self.ref_blocks = 0 - self.pool_chunks = 0 - self.pool_textures = 0 - # obs[(entry, pair_idx)] -> list of (dz0, dz1, q_targets_4, q_weights_4, weight) - self.obs = {} - - def _lane_step(self, lanes, i): - if self.codec == 1: - v = lanes[0][i] - d = 256 - ((v + 1) >> 1) if (v & 1) else (v >> 1) - dz = tuple(bcpack._unzig(lanes[2 + c][i]) for c in range(6)) - return d, dz - if self.codec == 3: - a, b = 2 * i, 2 * i + 1 - d = bcpack._unzig(bcpack._inter8(lanes[0][a], lanes[0][b])) & 255 - dz = ( - bcpack._unzig(lanes[2][a]), bcpack._unzig(lanes[2][b]), - bcpack._unzig(lanes[7][a]), bcpack._unzig(lanes[8][a]), bcpack._unzig(lanes[9][a]), - bcpack._unzig(lanes[7][b]), bcpack._unzig(lanes[8][b]), bcpack._unzig(lanes[9][b]), - ) - return d, dz - if self.codec == 4: - v = lanes[0][i] - d = 256 - ((v + 1) >> 1) if (v & 1) else (v >> 1) - dz = (bcpack._unzig(lanes[2][i]), bcpack._unzig(lanes[3][i])) - return d, dz - # codec 5 - a, b = 2 * i, 2 * i + 1 - d = bcpack._unzig(bcpack._inter8(lanes[0][a], lanes[0][b])) & 255 - dz = ( - bcpack._unzig(lanes[2][a]), bcpack._unzig(lanes[2][b]), - bcpack._unzig(lanes[3][a]), bcpack._unzig(lanes[3][b]), - ) - return d, dz - - def _extract_ref_endpoints(self, ref_blocks, i): - eb = bcpack.BLOCK_BYTES[self.codec] - at = i * eb - if self.codec == 1: - c0, c1 = struct.unpack_from("> 11) & 31, (c0 >> 5) & 63, c0 & 31, (c1 >> 11) & 31, (c1 >> 5) & 63, c1 & 31) - if self.codec == 3: - a0, a1 = ref_blocks[at], ref_blocks[at + 1] - c0, c1 = struct.unpack_from("> 11) & 31, (c0 >> 5) & 63, c0 & 31, (c1 >> 11) & 31, (c1 >> 5) & 63, c1 & 31) - if self.codec == 4: - return (ref_blocks[at], ref_blocks[at + 1]) - return (ref_blocks[at], ref_blocks[at + 1], ref_blocks[at + 8], ref_blocks[at + 9]) - - def add_reference_chunk(self, lanes, ref_blocks, nblocks, *, valid_blocks=None): - """Algebraically invert direct built-in references from exact BCn blocks.""" - mods = self.mods - for i in range(min(nblocks, 256)): - if valid_blocks is not None and not valid_blocks[i]: - continue - d, dz = self._lane_step(lanes, i) - if d == 0 or d <= i: - continue - entry = 256 + i - d - ep = self._extract_ref_endpoints(ref_blocks, i) - solved = tuple((ep[k] - dz[k]) % mods[k] for k in range(self.ncols)) - prev = self.confirmed.get(entry) - if prev is None: - self.confirmed[entry] = solved - elif prev != solved: - self.conflicts += 1 - self.ref_blocks += 1 - - def _quadrant_weights(self, lanes, i): - """Return per-channel 4-quadrant average interpolation weight in `[0, 1]`.""" - if self.codec == 1: - quad = _tables.BC1_QUADRANT - qvals = (quad[lanes[8][i]], quad[lanes[9][i]], quad[lanes[10][i]], quad[lanes[11][i]]) - w_lut = (0.0, 1.0, 1.0 / 3.0, 2.0 / 3.0) - qw = tuple( - sum(w_lut[(q >> (2 * p)) & 3] for p in range(4)) / 4.0 - for q in qvals - ) - return (qw, qw, qw) - if self.codec == 3: - a, b = 2 * i, 2 * i + 1 - pairs = _tables.BC3_ALPHA_PAIR - a_lut = (0.0, 1.0, 1.0 / 7.0, 2.0 / 7.0, 3.0 / 7.0, 4.0 / 7.0, 5.0 / 7.0, 6.0 / 7.0) - aq = [0.0, 0.0, 0.0, 0.0] - for r in range(4): - left = pairs[lanes[3 + r][a]] - right = pairs[lanes[3 + r][b]] - qi_l = (r // 2) * 2 - aq[qi_l] += a_lut[left[0]] + a_lut[left[1]] - aq[qi_l + 1] += a_lut[right[0]] + a_lut[right[1]] - aq_t = tuple(v / 4.0 for v in aq) - quads = _tables.BC3_COLOUR_QUADRANT - qvals = (quads[lanes[10][a]], quads[lanes[10][b]], quads[lanes[11][a]], quads[lanes[11][b]]) - w_lut = (0.0, 1.0, 1.0 / 3.0, 2.0 / 3.0) - cw = tuple( - sum(w_lut[(q >> (2 * p)) & 3] for p in range(4)) / 4.0 - for q in qvals - ) - return (aq_t, cw, cw, cw) - if self.codec == 4: - pairs = _tables.BC4_PAIR - a_lut = (0.0, 1.0, 1.0 / 7.0, 2.0 / 7.0, 3.0 / 7.0, 4.0 / 7.0, 5.0 / 7.0, 6.0 / 7.0) - aq = [0.0, 0.0, 0.0, 0.0] - for r in range(4): - left = pairs[lanes[4 + 2 * r][i]] - right = pairs[lanes[4 + 2 * r + 1][i]] - qi_l = (r // 2) * 2 - aq[qi_l] += a_lut[left[0]] + a_lut[left[1]] - aq[qi_l + 1] += a_lut[right[0]] + a_lut[right[1]] - return (tuple(v / 4.0 for v in aq),) - # codec 5 - a, b = 2 * i, 2 * i + 1 - pairs = _tables.BC5_PAIR - a_lut = (0.0, 1.0, 1.0 / 7.0, 2.0 / 7.0, 3.0 / 7.0, 4.0 / 7.0, 5.0 / 7.0, 6.0 / 7.0) - out = [] - for ch in range(2): - aq = [0.0, 0.0, 0.0, 0.0] - for r in range(4): - left = pairs[lanes[4 + 4 * ch + r][a]] - right = pairs[lanes[4 + 4 * ch + r][b]] - qi_l = (r // 2) * 2 - aq[qi_l] += a_lut[left[0]] + a_lut[left[1]] - aq[qi_l + 1] += a_lut[right[0]] + a_lut[right[1]] - out.append(tuple(v / 4.0 for v in aq)) - return tuple(out) - - def add_pool_chunk(self, lanes, nblocks, inv_lookup, chunk_rel_start, get_quads): - """Accumulate sibling-mip observations for built-in history chains.""" - self.pool_chunks += 1 - eb = bcpack.BLOCK_BYTES[self.codec] - mods = self.mods - roots = [-1] * nblocks - deltas = [None] * nblocks - for i in range(nblocks): - d, dz = self._lane_step(lanes, i) - if d == 0: - continue - if d > i: - root = 256 + i - d - acc = tuple(dz[k] % mods[k] for k in range(self.ncols)) - else: - root = roots[i - d] - if root < 0: - continue - prev = deltas[i - d] - acc = tuple((prev[k] + dz[k]) % mods[k] for k in range(self.ncols)) - roots[i] = root - deltas[i] = acc - if root in self.confirmed: - continue - xy = inv_lookup(chunk_rel_start + i * eb) - if xy is None: - continue - qpts = get_quads(xy[0], xy[1]) - qw = self._quadrant_weights(lanes, i) - if self.codec == 1: - spread = max(max(p[c] for p in qpts) - min(p[c] for p in qpts) for c in range(3)) - wt = 4.0 if spread <= 8.0 else (2.0 if spread <= 24.0 else 0.75) - scales = (31.0 / 255.0, 63.0 / 255.0, 31.0 / 255.0) - for c in range(3): - lst = self.obs.setdefault((root, c), []) - if len(lst) < 64: - tgts = tuple(p[c] * scales[c] for p in qpts) - lst.append((acc[c], acc[c + 3], tgts, qw[c], wt)) - elif self.codec == 3: - spread = max(max(p[c] for p in qpts) - min(p[c] for p in qpts) for c in range(4)) - wt = 4.0 if spread <= 8.0 else (2.0 if spread <= 24.0 else 0.75) - # pair 0 = alpha (p[3]), pairs 1..3 = RGB565 (p[0..2]) - lst_a = self.obs.setdefault((root, 0), []) - if len(lst_a) < 64: - lst_a.append((acc[0], acc[1], tuple(p[3] for p in qpts), qw[0], wt)) - scales = (31.0 / 255.0, 63.0 / 255.0, 31.0 / 255.0) - for c in range(3): - lst = self.obs.setdefault((root, 1 + c), []) - if len(lst) < 64: - tgts = tuple(p[c] * scales[c] for p in qpts) - lst.append((acc[2 + c], acc[5 + c], tgts, qw[1 + c], wt)) - elif self.codec == 4: - spread = max(qpts) - min(qpts) - wt = 4.0 if spread <= 8.0 else (2.0 if spread <= 24.0 else 0.75) - lst = self.obs.setdefault((root, 0), []) - if len(lst) < 64: - lst.append((acc[0], acc[1], qpts, qw[0], wt)) - else: - spread = max(max(p[c] for p in qpts) - min(p[c] for p in qpts) for c in range(2)) - wt = 4.0 if spread <= 8.0 else (2.0 if spread <= 24.0 else 0.75) - for c in range(2): - lst = self.obs.setdefault((root, c), []) - if len(lst) < 64: - lst.append((acc[2 * c], acc[2 * c + 1], tuple(p[c] for p in qpts), qw[c], wt)) - - @staticmethod - def _fit_pair(obs_list, mod): - cap = float(mod) * 0.25 - if mod <= 64: - best_err = 1e30 - best = (0, 0) - for h0 in range(mod): - for h1 in range(mod): - err = 0.0 - for d0, d1, tgts, qw, wt in obs_list: - e0 = (h0 + d0) % mod - e1 = (h1 + d1) % mod - de = e1 - e0 - for q in range(4): - d = abs((e0 + qw[q] * de) - tgts[q]) - err += wt * (d if d < cap else cap) - if err < best_err: - best_err = err - best = (h0, h1) - return best - # Coarse-to-fine search for 8-bit channels (0..255) - cands = [] - for h0 in range(0, mod, 16): - for h1 in range(0, mod, 16): - err = 0.0 - for d0, d1, tgts, qw, wt in obs_list: - e0 = (h0 + 8 + d0) & 255 - e1 = (h1 + 8 + d1) & 255 - de = e1 - e0 - for q in range(4): - d = abs((e0 + qw[q] * de) - tgts[q]) - err += wt * (d if d < cap else cap) - cands.append((err, h0, h1)) - cands.sort() - top = cands[:4] - for step in (8, 4, 2, 1): - nxt = {} - mid = step // 2 - for _, b0, b1 in top: - for o0 in (0, step): - for o1 in (0, step): - h0, h1 = (b0 + o0) & 255, (b1 + o1) & 255 - key = (h0, h1) - if key in nxt: - continue - err = 0.0 - for d0, d1, tgts, qw, wt in obs_list: - e0 = (h0 + mid + d0) & 255 - e1 = (h1 + mid + d1) & 255 - de = e1 - e0 - for q in range(4): - d = abs((e0 + qw[q] * de) - tgts[q]) - err += wt * (d if d < cap else cap) - nxt[key] = err - top = sorted((e, a, b) for (a, b), e in nxt.items())[:4] - return top[0][1], top[0][2] - - def build_document(self, replace=False): - provisional = {} - entries = sorted({k for (k, _) in self.obs} - set(self.confirmed)) - for k in entries: - if self.codec == 1: - if not all((k, c) in self.obs for c in range(3)): - continue - r0, r1 = self._fit_pair(self.obs[(k, 0)], 32) - g0, g1 = self._fit_pair(self.obs[(k, 1)], 64) - b0, b1 = self._fit_pair(self.obs[(k, 2)], 32) - provisional[k] = [r0, g0, b0, r1, g1, b1] - elif self.codec == 3: - if not all((k, c) in self.obs for c in range(4)): - continue - a0, a1 = self._fit_pair(self.obs[(k, 0)], 256) - r0, r1 = self._fit_pair(self.obs[(k, 1)], 32) - g0, g1 = self._fit_pair(self.obs[(k, 2)], 64) - b0, b1 = self._fit_pair(self.obs[(k, 3)], 32) - provisional[k] = [a0, a1, r0, g0, b0, r1, g1, b1] - elif self.codec == 4: - a0, a1 = self._fit_pair(self.obs[(k, 0)], 256) - provisional[k] = [a0, a1] - else: - if not all((k, c) in self.obs for c in range(2)): - continue - r0, r1 = self._fit_pair(self.obs[(k, 0)], 256) - g0, g1 = self._fit_pair(self.obs[(k, 1)], 256) - provisional[k] = [r0, r1, g0, g1] - - doc = { - "codec": CODEC_KEYS[self.codec], - "confirmed": {str(k): list(self.confirmed[k]) for k in sorted(self.confirmed)}, - "provisional": {str(k): list(provisional[k]) for k in sorted(provisional)}, - } - if replace: - doc["replace"] = True - stats = { - "confirmed_entries": len(self.confirmed), - "provisional_entries": len(provisional), - "reference_blocks": self.ref_blocks, - "reference_conflicts": self.conflicts, - "pool_chunks": self.pool_chunks, - "pool_textures": self.pool_textures, - } - return doc, stats - - -class Bc6hCalibrator: - """Calibrator for BC6H (`codec 6`) endpoint and index initial history tables.""" - - def __init__(self): - # Exact reference-pair constraints: - # ref_ep[k][c][q] = [bits, val] (left-aligned to (16, 10, 6, 6)) - self.ref_ep = [[[[0, 0] for _ in range(4)] for _ in range(3)] for _ in range(256)] - self.ref_ix = [[[0, 0] for _ in range(16)] for _ in range(256)] - self.ref_ep_seen = [False] * 256 - self.ref_ix_seen = [False] * 256 - self.conflicts = 0 - self.ref_blocks = 0 - self.pool_chunks = 0 - self.pool_textures = 0 - - # Algebraic constraints & pool observations: - self.valid_ix = [[0xFFFF] * 16 for _ in range(256)] - self.ix_obs = [[0] * 16 for _ in range(256)] - self.ix_rel_votes = {(k, p): [0] * 16 for k in range(256) for p in range(16)} - # Endpoint observations: - # w_obs[(k, c)] -> list of (ops_w, tgt_unq, wt) where ops_w is ((base, dz0), ...) - self.w_obs = {} - # d_obs[(k, c, q)] -> list of (dc, dz) for transformed-mode centering (q in 1, 2, 3) - self.d_obs = {} - self.ep_seen = [False] * 256 - - def add_reference_chunk(self, lanes, ref_blocks, nblocks, *, valid_blocks=None): - """Algebraically invert direct built-in BC6H history references from exact blocks.""" - l0, l1, l15 = lanes[0], lanes[1], lanes[15] - deint0, deint1 = bcpack._DEINT - slot_widths = (16, 10, 6, 6) - for i in range(min(nblocks, 256)): - if valid_blocks is not None and not valid_blocks[i]: - continue - a, b = 2 * i, 2 * i + 1 - m_sym = l15[a] - if m_sym > 13: - continue - parsed = unpack_bc6h_block(ref_blocks, i * 16) - if parsed is None: - continue - mode, part, f, ix = parsed - if mode != m_sym + 1: - self.conflicts += 1 - continue - code = bcpack._BC6H_CODE[mode] - _trans, base, deltas, reg = bcpack._BC6H_INFO[code] - di = bcpack._inter8(l1[a], l1[b]) - de = (di + bcpack._unzig(bcpack._inter8(l0[a], l0[b]))) & 255 - if de > i: - ke = 256 + i - de - self.ref_ep_seen[ke] = True - mw = (1 << base) - 1 - w_sh = 16 - base - for c in range(3): - dc = deltas[c] - mD = (1 << dc) - 1 - sh = 6 - dc if dc < 6 else 0 - dz0 = bcpack._unzig(bcpack._inter(lanes[2 + c][a], lanes[2 + c][b], 8)) - dz1 = bcpack._unzig(bcpack._inter(lanes[5 + c][a], lanes[5 + c][b], 5)) - dz2 = bcpack._unzig(lanes[8 + c][a]) - dz3 = bcpack._unzig(lanes[8 + c][b]) - w_val = ((f[c][0] - dz0) & mw) << w_sh - x_val = ((f[c][1] - dz1) & mD) << (10 - dc) - updates = [(0, base, w_val), (1, dc, x_val)] - if reg == 2: - y_val = ((f[c][2] - dz2) & mD) << sh - z_val = ((f[c][3] - dz3) & mD) << sh - updates.append((2, dc, y_val)) - updates.append((3, dc, z_val)) - for q, nb, val in updates: - cb, cv = self.ref_ep[ke][c][q] - nb2, nv2, conf = _merge_top_bits(cb, cv, nb, val, slot_widths[q]) - if conf: - self.conflicts += 1 - else: - self.ref_ep[ke][c][q][0] = nb2 - self.ref_ep[ke][c][q][1] = nv2 - self.ref_blocks += 1 - if di > i: - ki = 256 + i - di - self.ref_ix_seen[ki] = True - ibits = 3 if reg == 2 else 4 - imask = (1 << ibits) - 1 - ishift = 4 - ibits - for yy in range(4): - sa = lanes[11 + yy][a] - sb = lanes[11 + yy][b] - row = yy * 4 - if yy < 3: - ds = (deint1[sa], deint0[sa], deint1[sb], deint0[sb]) - else: - ds = (deint0[sa], deint1[sa], deint0[sb], deint1[sb]) - for off, dv in enumerate(ds): - p = row + off - v = ((ix[p] - bcpack._unzig(dv)) & imask) << ishift - cb, cv = self.ref_ix[ki][p] - nb2, nv2, conf = _merge_top_bits(cb, cv, ibits, v, 4) - if conf: - self.conflicts += 1 - else: - self.ref_ix[ki][p][0] = nb2 - self.ref_ix[ki][p][1] = nv2 - - def add_pool_chunk(self, lanes, nblocks, inv_lookup=None, chunk_rel_start=0, get_quads=None): - """Accumulate algebraic constraints and optional sibling-mip HDR endpoint targets.""" - self.pool_chunks += 1 - l0, l1, l15 = lanes[0], lanes[1], lanes[15] - deint0, deint1 = bcpack._DEINT - a2 = _bptc.BC7_ANCHOR2 - p2 = _bptc.load_bc7()["partition2"] - eroot = [-1] * nblocks - wchain = [None] * nblocks - iroot = [-1] * nblocks - imap = [None] * nblocks - - for i in range(nblocks): - a, b = 2 * i, 2 * i + 1 - m_sym = l15[a] - if m_sym > 13: - continue - mode = m_sym + 1 - code = bcpack._BC6H_CODE[mode] - trans, base, deltas, reg = bcpack._BC6H_INFO[code] - part = l15[b] if l15[b] < 31 else 31 - di = bcpack._inter8(l1[a], l1[b]) - de = (di + bcpack._unzig(bcpack._inter8(l0[a], l0[b]))) & 255 - ibits = 3 if reg == 2 else 4 - imask = (1 << ibits) - 1 - ishift = 4 - ibits - - # Index anchor constraints & intra-block smoothness - if di > 0: - if di > i: - ki = 256 + i - di - pmap = None - else: - ki = iroot[i - di] - pmap = imap[i - di] if ki >= 0 else None - if ki >= 0: - iroot[i] = ki - anchors = (0, a2[part]) if reg == 2 else (0,) - cur = {} - for p_idx in anchors: - if pmap is not None and p_idx not in pmap: - continue - yy, off = divmod(p_idx, 4) - s = lanes[11 + yy][a] if off < 2 else lanes[11 + yy][b] - dv = bcpack._unzig(deint1[s] if ((off % 2 == 0) if yy < 3 else (off % 2 == 1)) else deint0[s]) - if pmap is None: - mp = tuple((((h >> ishift) + dv) & imask) << ishift for h in range(16)) - else: - mp = tuple((((pmap[p_idx][h] >> ishift) + dv) & imask) << ishift for h in range(16)) - cur[p_idx] = mp - mask = 0 - for h in range(16): - if mp[h] < 8: - mask |= 1 << h - if self.valid_ix[ki][p_idx] & mask: - self.valid_ix[ki][p_idx] &= mask - self.ix_obs[ki][p_idx] += 1 - if pmap is None: - sm_i = p2[part] if reg == 2 else None - s0 = lanes[11][a] - dv0 = bcpack._unzig(deint1[s0]) - for p_idx in range(1, 16): - self.ix_obs[ki][p_idx] += 1 - if sm_i is None or sm_i[p_idx] == sm_i[0]: - yy, off = divmod(p_idx, 4) - sp = lanes[11 + yy][a] if off < 2 else lanes[11 + yy][b] - dvp = bcpack._unzig(deint1[sp] if ((off % 2 == 0) if yy < 3 else (off % 2 == 1)) else deint0[sp]) - diff_top = ((dv0 - dvp) & imask) << ishift - for lo in range(1 << ishift): - self.ix_rel_votes[(ki, p_idx)][(diff_top | lo) & 15] += 1 - imap[i] = cur - - # Endpoint chains and observations - if de == 0: - continue - if de > i: - ke = 256 + i - de - pchain = None - else: - ke = eroot[i - de] - pchain = wchain[i - de] if ke >= 0 else None - if ke < 0: - continue - eroot[i] = ke - self.ep_seen[ke] = True - mw = (1 << base) - 1 - cur_w = [None, None, None] - for c in range(3): - dc = deltas[c] - dz0 = bcpack._unzig(bcpack._inter(lanes[2 + c][a], lanes[2 + c][b], 8)) & mw - if pchain is None: - cur_w[c] = ((base, dz0),) - if trans: - dz1 = bcpack._unzig(bcpack._inter(lanes[5 + c][a], lanes[5 + c][b], 5)) - lst1 = self.d_obs.setdefault((ke, c, 1), []) - if len(lst1) < 96: - lst1.append((dc, dz1)) - if reg == 2: - dz2 = bcpack._unzig(lanes[8 + c][a]) - dz3 = bcpack._unzig(lanes[8 + c][b]) - lst2 = self.d_obs.setdefault((ke, c, 2), []) - if len(lst2) < 96: - lst2.append((dc, dz2)) - lst3 = self.d_obs.setdefault((ke, c, 3), []) - if len(lst3) < 96: - lst3.append((dc, dz3)) - elif pchain[c] is not None: - pops = pchain[c] - if pops[-1][0] == base: - cur_w[c] = pops[:-1] + ((base, (pops[-1][1] + dz0) & mw),) - elif len(pops) < 3: - cur_w[c] = pops + ((base, dz0),) - wchain[i] = cur_w - - if inv_lookup is None or get_quads is None: - continue - xy = inv_lookup(chunk_rel_start + i * 16) - if xy is None: - continue - qpts = get_quads(xy[0], xy[1]) - spread = max(max(p[c] for p in qpts) - min(p[c] for p in qpts) for c in range(3)) - wt = 4.0 if spread <= 512.0 else (2.0 if spread <= 2048.0 else 0.75) - mean_rgb = tuple(sum(p[c] for p in qpts) / 4.0 for c in range(3)) - for c in range(3): - if cur_w[c] is not None: - lst = self.w_obs.setdefault((ke, c), []) - if len(lst) < 64: - lst.append((cur_w[c], mode, max(0.0, min(65535.0, mean_rgb[c])), wt)) - - @staticmethod - def _eval_w_ops(ops, mode, r0): - v = r0 - last_base = 16 - for base, dz in ops: - sh = 16 - base - m = (1 << base) - 1 - v = (((v >> sh) + dz) & m) << sh - last_base = base - d3d_w = bcpack._bc6h_stream_w(mode, v >> (16 - last_base)) - return _bc6h_unquantize(d3d_w, last_base, signed=False) - - @classmethod - def _fit_w(cls, obs_list): - cap = 8192.0 - cands = [] - for h in range(0, 65536, 1024): - err = 0.0 - for ops, mode, tgt, wt in obs_list: - d = abs(cls._eval_w_ops(ops, mode, h | 512) - tgt) - err += wt * (d if d < cap else cap) - cands.append((err, h)) - cands.sort() - top = cands[:4] - for step in (512, 256, 128, 64, 32, 16, 8, 4, 2, 1): - nxt = {} - mid = step // 2 - for _, b in top: - for off in (0, step): - h = (b + off) & 65535 - if h in nxt: - continue - err = 0.0 - for ops, mode, tgt, wt in obs_list: - d = abs(cls._eval_w_ops(ops, mode, h | mid) - tgt) - err += wt * (d if d < cap else cap) - nxt[h] = err - top = sorted((e, h) for h, e in nxt.items())[:4] - return top[0][1] - - @staticmethod - def _fit_signed_delta(obs_list, total_bits): - if not obs_list: - return 1 << (total_bits - 1) - limit = 1 << total_bits - best_err = 1e30 - best_r = 0 - for r in range(limit): - err = 0.0 - for dc, dz in obs_list: - sh = total_bits - dc if dc < total_bits else 0 - mD = (1 << dc) - 1 - v = ((r >> sh) + dz) & mD - err += abs(_sign_extend(v, dc)) / float(1 << (dc - 1)) - if err < best_err: - best_err = err - best_r = r - return best_r - - def build_document(self): - eh = [[[0, 0, 0, 0] for _ in range(3)] for _ in range(256)] - ih = [[0] * 16 for _ in range(256)] - ep_cb = [[[self.ref_ep[k][c][q][0] for q in range(4)] for c in range(3)] for k in range(256)] - ix_cb = [[self.ref_ix[k][p][0] for p in range(16)] for k in range(256)] - ec = [0] * 256 - ic = [0] * 256 - - for k in range(256): - # Endpoints - if self.ref_ep_seen[k]: - defaults = (0x8000, 0x200, 0x20, 0x20) - for c in range(3): - for q in range(4): - rb, rv = self.ref_ep[k][c][q] - eh[k][c][q] = rv if rb > 0 else defaults[q] - ec[k] = 3 - elif self.ep_seen[k]: - has_w = 0 - has_d = 0 - for c in range(3): - wl = self.w_obs.get((k, c)) - if wl: - w_val = self._fit_w(wl) - has_w += 1 - else: - w_val = 0x8000 - x_obs = self.d_obs.get((k, c, 1)) - y_obs = self.d_obs.get((k, c, 2)) - z_obs = self.d_obs.get((k, c, 3)) - if x_obs or y_obs or z_obs: - has_d += 1 - x_val = self._fit_signed_delta(x_obs, 10) - y_val = self._fit_signed_delta(y_obs, 6) - z_val = self._fit_signed_delta(z_obs, 6) - eh[k][c] = [w_val, x_val, y_val, z_val] - if has_w == 3: - ec[k] = 1 - elif has_w > 0 or has_d > 0: - ec[k] = 2 - - # Indices - if self.ref_ix_seen[k] and all(self.ref_ix[k][p][0] > 0 for p in range(16)): - ih[k] = [self.ref_ix[k][p][1] for p in range(16)] - ic[k] = 3 - elif any(self.ix_obs[k]): - v0_lead, b0 = _lead_bits_4(self.valid_ix[k][0]) - surv0 = [h for h in range(16) if (self.valid_ix[k][0] >> h) & 1] - v0 = v0_lead if b0 == 4 else (surv0[len(surv0) // 2] if surv0 else 0) - row = [0] * 16 - total_votes = 0 - for p in range(16): - v, b = _lead_bits_4(self.valid_ix[k][p]) - if b == 4: - row[p] = v - continue - mask = self.valid_ix[k][p] - votes = self.ix_rel_votes[(k, p)] - sv = sum(votes) - total_votes += sv - if p == 0: - best_h = v0 - elif sv > 0: - best_h = max( - (h for h in range(16) if (mask >> h) & 1), - key=lambda h: votes[(h - v0) & 15], - default=v0, - ) - else: - surv = [h for h in range(16) if (mask >> h) & 1] - best_h = surv[len(surv) // 2] if surv else 0 - row[p] = best_h - ih[k] = row - ic[k] = 1 if (b0 >= 2 and total_votes > 0) else 2 - - doc = { - "endpointHistory": eh, - "indexHistory": ih, - "endpointClass": ec, - "indexClass": ic, - "endpointConfirmedBits": ep_cb, - "indexConfirmedBits": ix_cb, - } - stats = { - "endpoint_confirmed": sum(1 for c in ec if c == 3), - "endpoint_provisional": sum(1 for c in ec if c == 1), - "endpoint_last_resort": sum(1 for c in ec if c == 2), - "index_confirmed": sum(1 for c in ic if c == 3), - "index_provisional": sum(1 for c in ic if c == 1), - "index_last_resort": sum(1 for c in ic if c == 2), - "reference_blocks": self.ref_blocks, - "reference_conflicts": self.conflicts, - "pool_chunks": self.pool_chunks, - "pool_textures": self.pool_textures, - } - return doc, stats - - -class Bc7Calibrator: - """Calibrator for BC7 (`codec 7`) endpoint and index initial history tables.""" - - def __init__(self): - self.tab = _bptc.load_bc7() - # Exact reference-pair constraints - self.ref_ep = [[[0, 0] for _ in range(24)] for _ in range(256)] - self.ref_ix = [[[0, 0] for _ in range(32)] for _ in range(256)] - self.conflicts = 0 - self.ref_blocks = 0 - self.pool_chunks = 0 - self.pool_textures = 0 - - # Algebraic & pool self-calibration accumulators - self.valid_ix = [[0xFFFF] * 32 for _ in range(256)] - self.ix_obs = [[0] * 32 for _ in range(256)] - self.ix_rel_votes = {(k, p): [0] * 16 for k in range(256) for p in range(32)} - self.pbit_parity = {} - self.ep_obs = {} - - def add_reference_chunk(self, lanes, ref_blocks, nblocks, *, valid_blocks=None): - """Algebraically invert direct built-in BC7 history references from exact blocks.""" - cfg = self.tab["config"] - rank_of = self.tab["rank_of"] - l0, l1, l15 = lanes[0], lanes[1], lanes[15] - rows1 = (lanes[11], lanes[12], lanes[13], lanes[14]) - rows2 = (lanes[6], lanes[7], lanes[8], lanes[10]) - deint0, deint1 = bcpack._DEINT - - for i in range(min(nblocks, 256)): - if valid_blocks is not None and not valid_blocks[i]: - continue - aa, bb = 2 * i, 2 * i + 1 - s15a, s15b = l15[aa], l15[bb] - rank = rank_of[s15a * 16 + s15b] if s15a < 32 and s15b < 16 else -1 - if rank < 0 or cfg[rank][0] > 7: - continue - parsed = unpack_bc7_block(ref_blocks, i * 16) - if parsed is None: - continue - mode, part, rot, isel, val, idx1, idx2 = parsed - if (mode, part, rot, isel) != cfg[rank]: - self.conflicts += 1 - continue - di = bcpack._inter8(l1[aa], l1[bb]) - de = (di + bcpack._unzig(bcpack._inter8(l0[aa], l0[bb]))) & 255 - ns = bcpack._B7_NS[mode] - cb = bcpack._B7_CB[mode] - ab = bcpack._B7_AB[mode] - pk = bcpack._B7_PK[mode] - b1 = bcpack._B7_IB[mode] - - if de > i: - ke = 256 + i - de - w = [cb, cb, cb, ab] - if rot: - w[rot - 1], w[3] = ab, cb - for sub in range(ns): - lrow = bcpack._B7_LANE[sub] - bsub = sub * 8 - for c in range(4): - li = lrow[c] - wc = w[c] - if not wc or li < 0: - continue - bits = wc + (1 if (pk and c == 0) else 0) - sh = 8 - bits - mask_b = (1 << bits) - 1 - dz0 = bcpack._unzig(lanes[li][aa]) - dz1 = bcpack._unzig(lanes[li][bb]) - for e_idx, dz in ((0, dz0), (1, dz1)): - slot = bsub + e_idx * 4 + c - v = (((val[sub][e_idx][c] >> sh) - dz) & mask_b) << sh - cb0, cv0 = self.ref_ep[ke][slot] - nb2, nv2, conf = _merge_top_bits(cb0, cv0, bits, v, 8) - if conf: - self.conflicts += 1 - else: - self.ref_ep[ke][slot][0] = nb2 - self.ref_ep[ke][slot][1] = nv2 - self.ref_blocks += 1 - - if di > i: - ki = 256 + i - di - # `idx1` / `idx2` from `unpack_bc7_block` are already mapped to - # BCPack's `(s1=rows1, s2=rows2)` order; `rows2` is always 2 bits. - pri_bits = bcpack._B7_IB[mode] - pri_sh = 4 - pri_bits - pri_m = (1 << pri_bits) - 1 - for yy in range(4): - sa = rows1[yy][aa] - sb = rows1[yy][bb] - row = yy * 4 - if yy < 3: - ds = (deint1[sa], deint0[sa], deint1[sb], deint0[sb]) - else: - ds = (deint0[sa], deint1[sa], deint0[sb], deint1[sb]) - for off, dv in enumerate(ds): - p = row + off - v = ((idx1[p] - bcpack._unzig(dv)) & pri_m) << pri_sh - cb0, cv0 = self.ref_ix[ki][p] - nb2, nv2, conf = _merge_top_bits(cb0, cv0, pri_bits, v, 4) - if conf: - self.conflicts += 1 - else: - self.ref_ix[ki][p][0] = nb2 - self.ref_ix[ki][p][1] = nv2 - if mode in (4, 5) and idx2 is not None: - sec_bits = 2 - sec_sh = 2 - sec_m = 3 - for yy in range(4): - sa = rows2[yy][aa] - sb = rows2[yy][bb] - row = yy * 4 - if yy < 3: - ds = (deint1[sa], deint0[sa], deint1[sb], deint0[sb]) - else: - ds = (deint0[sa], deint1[sa], deint0[sb], deint1[sb]) - for off, dv in enumerate(ds): - p = row + off - v = ((idx2[p] - bcpack._unzig(dv)) & sec_m) << sec_sh - cb0, cv0 = self.ref_ix[ki][16 + p] - nb2, nv2, conf = _merge_top_bits(cb0, cv0, sec_bits, v, 4) - if conf: - self.conflicts += 1 - else: - self.ref_ix[ki][16 + p][0] = nb2 - self.ref_ix[ki][16 + p][1] = nv2 - - def add_pool_chunk(self, lanes, nblocks, inv_lookup=None, chunk_rel_start=0, get_quads=None): - """Accumulate BC7 anchor/p-bit constraints and optional sibling-mip RGBA endpoint fits.""" - self.pool_chunks += 1 - cfg = self.tab["config"] - rank_of = self.tab["rank_of"] - inferred = self.tab["inferred"] - a2, a3a, a3b = self.tab["anchor2"], self.tab["anchor3a"], self.tab["anchor3b"] - p2, p3 = self.tab["partition2"], self.tab["partition3"] - deint0, deint1 = bcpack._DEINT - l0, l1, l15 = lanes[0], lanes[1], lanes[15] - rows1 = (lanes[11], lanes[12], lanes[13], lanes[14]) - rows2 = (lanes[6], lanes[7], lanes[8], lanes[10]) - - eroot = [-1] * nblocks - echain = [None] * nblocks - iroot = [-1] * nblocks - imap = [None] * nblocks - - for i in range(nblocks): - aa, bb = 2 * i, 2 * i + 1 - s15a, s15b = l15[aa], l15[bb] - rank = rank_of[s15a * 16 + s15b] if s15a < 32 and s15b < 16 else -1 - if rank < 0 or rank in inferred: - continue - mode, part, rot, _isel = cfg[rank] - if mode > 7: - continue - di = bcpack._inter8(l1[aa], l1[bb]) - de = (di + bcpack._unzig(bcpack._inter8(l0[aa], l0[bb]))) & 255 - ns = bcpack._B7_NS[mode] - b1 = bcpack._B7_IB[mode] - b1_sh = 4 - b1 - b1_m = (1 << b1) - 1 - - # Index anchor constraints & intra-block smoothness - if di > 0: - if di > i: - ki = 256 + i - di - pmap = None - else: - ki = iroot[i - di] - pmap = imap[i - di] if ki >= 0 else None - if ki >= 0: - iroot[i] = ki - anchors = (0,) if ns == 1 else ((0, a2[part]) if ns == 2 else (0, a3a[part], a3b[part])) - pri_anc = (0,) if mode in (4, 5) else anchors - cur = {} - for p_idx in pri_anc: - if pmap is not None and p_idx not in pmap: - continue - yy, off = divmod(p_idx, 4) - s = rows1[yy][aa] if off < 2 else rows1[yy][bb] - dv = bcpack._unzig(deint1[s] if ((off % 2 == 0) if yy < 3 else (off % 2 == 1)) else deint0[s]) - if pmap is None: - mp = tuple((((h >> b1_sh) + dv) & b1_m) << b1_sh for h in range(16)) - else: - mp = tuple((((pmap[p_idx][h] >> b1_sh) + dv) & b1_m) << b1_sh for h in range(16)) - cur[p_idx] = mp - mask = 0 - for h in range(16): - if mp[h] < 8: - mask |= 1 << h - if self.valid_ix[ki][p_idx] & mask: - self.valid_ix[ki][p_idx] &= mask - self.ix_obs[ki][p_idx] += 1 - if pmap is None: - sm_i = None if ns == 1 else (p2[part] if ns == 2 else p3[part]) - s0 = rows1[0][aa] - dv0 = bcpack._unzig(deint1[s0]) - for p_idx in range(1, 16): - self.ix_obs[ki][p_idx] += 1 - if sm_i is None or sm_i[p_idx] == sm_i[0]: - yy, off = divmod(p_idx, 4) - sp = rows1[yy][aa] if off < 2 else rows1[yy][bb] - dvp = bcpack._unzig(deint1[sp] if ((off % 2 == 0) if yy < 3 else (off % 2 == 1)) else deint0[sp]) - diff_top = ((dv0 - dvp) & b1_m) << b1_sh - for lo in range(1 << b1_sh): - self.ix_rel_votes[(ki, p_idx)][(diff_top | lo) & 15] += 1 - if mode in (4, 5): - b2 = 2 - b2_sh = 2 - b2_m = 3 - s2a = rows2[0][aa] - dv2 = bcpack._unzig(deint1[s2a]) - if pmap is None: - m2 = tuple((((h >> b2_sh) + dv2) & b2_m) << b2_sh for h in range(16)) - elif 16 in pmap: - m2 = tuple((((pmap[16][h] >> b2_sh) + dv2) & b2_m) << b2_sh for h in range(16)) - else: - m2 = None - if m2 is not None: - cur[16] = m2 - mask = 0 - for h in range(16): - if m2[h] < 8: - mask |= 1 << h - if self.valid_ix[ki][16] & mask: - self.valid_ix[ki][16] &= mask - self.ix_obs[ki][16] += 1 - if pmap is None: - for p_idx in range(1, 16): - self.ix_obs[ki][16 + p_idx] += 1 - yy, off = divmod(p_idx, 4) - sp = rows2[yy][aa] if off < 2 else rows2[yy][bb] - dvp = bcpack._unzig(deint1[sp] if ((off % 2 == 0) if yy < 3 else (off % 2 == 1)) else deint0[sp]) - diff_top = ((dv2 - dvp) & b2_m) << b2_sh - for lo in range(1 << b2_sh): - self.ix_rel_votes[(ki, 16 + p_idx)][(diff_top | lo) & 15] += 1 - imap[i] = cur - - # Endpoint chains & observations - if de == 0: - continue - if de > i: - ke = 256 + i - de - pchain = None - else: - ke = eroot[i - de] - pchain = echain[i - de] if ke >= 0 else None - if ke < 0: - continue - eroot[i] = ke - cb = bcpack._B7_CB[mode] - ab = bcpack._B7_AB[mode] - pk = bcpack._B7_PK[mode] - w = [cb, cb, cb, ab] - if rot: - w[rot - 1], w[3] = ab, cb - cur_e = [None] * 24 - for sub in range(ns): - lrow = bcpack._B7_LANE[sub] - bsub = sub * 8 - for c in range(4): - li = lrow[c] - wc = w[c] - if not wc or li < 0: - continue - bits = wc + (1 if (pk and c == 0) else 0) - mask_b = (1 << bits) - 1 - dz0 = bcpack._unzig(lanes[li][aa]) & mask_b - dz1 = bcpack._unzig(lanes[li][bb]) & mask_b - for e_idx, dz in ((0, dz0), (1, dz1)): - slot = bsub + e_idx * 4 + c - if pchain is None: - cur_e[slot] = (slot, ((bits, dz),)) - else: - prev = pchain[slot] - if prev is not None: - ss, pops = prev - if pops[-1][0] == bits: - nops = pops[:-1] + ((bits, (pops[-1][1] + dz) & mask_b),) - elif len(pops) < 3: - nops = pops + ((bits, dz),) - else: - nops = None - if nops is not None: - cur_e[slot] = (ss, nops) - if pk == 2 and pchain is None: - par = (bcpack._unzig(lanes[lrow[0]][aa]) ^ bcpack._unzig(lanes[lrow[0]][bb])) & 1 - rec = self.pbit_parity.setdefault((ke, sub), [0, 0]) - rec[par] += 1 - for sub in range(ns, 3): - cur_e[sub * 8:sub * 8 + 8] = cur_e[0:8] - echain[i] = cur_e - - if inv_lookup is None or get_quads is None: - continue - xy = inv_lookup(chunk_rel_start + i * 16) - if xy is None: - continue - qpts = get_quads(xy[0], xy[1]) - spread = max(max(p[c] for p in qpts) - min(p[c] for p in qpts) for c in range(4)) - weight = 4.0 if spread <= 6.0 else (2.0 if spread <= 18.0 else 0.5) - sm = None if ns == 1 else (p2[part] if ns == 2 else p3[part]) - for sub in range(ns): - if sm is None: - sub_rgba = tuple(sum(p[c] for p in qpts) / 4.0 for c in range(4)) - else: - acc_c = [0.0, 0.0, 0.0, 0.0] - sc = 0 - for px_i in range(16): - if sm[px_i] == sub: - qi = ((px_i // 4) // 2) * 2 + ((px_i % 4) // 2) - qp = qpts[qi] - for cc in range(4): - acc_c[cc] += qp[cc] - sc += 1 - if not sc: - continue - sub_rgba = tuple(v / sc for v in acc_c) - for c in range(4): - s0 = cur_e[sub * 8 + c] - s1 = cur_e[sub * 8 + 4 + c] - if s0 is None or s1 is None: - continue - ss0, ops0 = s0 - ss1, ops1 = s1 - if ss0 // 8 != ss1 // 8 or (ss0 % 8) != c or (ss1 % 8) != (4 + c): - continue - orig_sub = ss0 // 8 - lst = self.ep_obs.setdefault((ke, orig_sub, c), []) - if len(lst) < 60: - lst.append((ops0, ops1, sub_rgba[c], weight)) - - @staticmethod - def _fit_ep_pair(obs_list): - cands = [] - for h0 in range(0, 256, 16): - for h1 in range(0, 256, 16): - err = 0.0 - for ops0, ops1, tgt, wt in obs_list: - e0 = _eval_bc7_ops(ops0, h0 | 8) - e1 = _eval_bc7_ops(ops1, h1 | 8) - d = abs(0.5 * (e0 + e1) - tgt) - err += wt * ((d if d < 40.0 else 40.0) + 0.01 * abs(e0 - e1)) - cands.append((err, h0, h1)) - cands.sort() - top = cands[:4] - for step in (8, 4, 2, 1): - nxt = {} - mid = step // 2 - for _, b0, b1 in top: - for d0 in (0, step): - for d1 in (0, step): - h0, h1 = (b0 + d0) & 255, (b1 + d1) & 255 - key = (h0, h1) - if key in nxt: - continue - err = 0.0 - for ops0, ops1, tgt, wt in obs_list: - e0 = _eval_bc7_ops(ops0, h0 | mid) - e1 = _eval_bc7_ops(ops1, h1 | mid) - d = abs(0.5 * (e0 + e1) - tgt) - err += wt * ((d if d < 40.0 else 40.0) + 0.01 * abs(e0 - e1)) - nxt[key] = err - top = sorted((e, a, b) for (a, b), e in nxt.items())[:4] - return top[0][1], top[0][2] - - def build_document(self): - hist_ep = [[0] * 24 for _ in range(256)] - hist_ep_b = [[0] * 24 for _ in range(256)] - hist_ep_cb = [[0] * 24 for _ in range(256)] - hist_ix = [[0] * 32 for _ in range(256)] - hist_ix_b = [[0] * 32 for _ in range(256)] - hist_ix_cb = [[0] * 32 for _ in range(256)] - last_resort = [] - - ep_conf_slots = 0 - ep_prov_slots = 0 - ix_conf_slots = 0 - ix_prov_slots = 0 - - for k in range(256): - # Indices: exact reference beats algebraic/smoothness - eff_masks = list(self.valid_ix[k]) - for p in range(32): - rb, rv = self.ref_ix[k][p] - if rb > 0: - sh = 4 - rb - rmask = 0 - for h in range(16): - if (h >> sh) == (rv >> sh): - rmask |= 1 << h - if eff_masks[p] & rmask: - eff_masks[p] &= rmask - else: - eff_masks[p] = rmask - hist_ix[k][p] = rv - hist_ix_b[k][p] = rb - hist_ix_cb[k][p] = rb - ix_conf_slots += 1 - continue - v, b = _lead_bits_4(eff_masks[p]) - if b > 0: - hist_ix[k][p] = v - hist_ix_b[k][p] = b - hist_ix_cb[k][p] = b - surv0 = [h for h in range(16) if (eff_masks[0] >> h) & 1] - v0 = hist_ix[k][0] if hist_ix_b[k][0] == 4 else (surv0[len(surv0) // 2] if surv0 else 0) - surv16 = [h for h in range(16) if (eff_masks[16] >> h) & 1] - v16 = hist_ix[k][16] if hist_ix_b[k][16] >= 2 else (surv16[len(surv16) // 2] if surv16 else 0) - if any(self.ix_obs[k][:16]): - for p in range(16): - if hist_ix_b[k][p] < 4: - mask = eff_masks[p] - votes = self.ix_rel_votes[(k, p)] - if p == 0: - best_h = v0 - elif sum(votes) > 0: - best_h = max( - (h for h in range(16) if (mask >> h) & 1), - key=lambda h: votes[(h - v0) & 15], - default=v0, - ) - else: - surv = [h for h in range(16) if (mask >> h) & 1] - best_h = surv[len(surv) // 2] if surv else 0 - hist_ix[k][p] = best_h - hist_ix_b[k][p] = 4 - if self.ref_ix[k][p][0] == 0: - ix_prov_slots += 1 - if any(self.ix_obs[k][16:]): - for p in range(16, 32): - if hist_ix_b[k][p] < 2: - mask = eff_masks[p] - votes = self.ix_rel_votes[(k, p)] - if p == 16: - best_h = v16 - elif sum(votes) > 0: - best_h = max( - (h for h in range(16) if (mask >> h) & 1), - key=lambda h: votes[(h - v16) & 15], - default=v16, - ) - else: - surv = [h for h in range(16) if (mask >> h) & 1] - best_h = surv[len(surv) // 2] if surv else 0 - hist_ix[k][p] = best_h - hist_ix_b[k][p] = 2 - if self.ref_ix[k][p][0] == 0: - ix_prov_slots += 1 - - # Endpoints: exact reference takes precedence per slot; otherwise sibling-mip fit - for sub in range(3): - for c in range(4): - s0 = sub * 8 + c - s1 = sub * 8 + 4 + c - rb0, rv0 = self.ref_ep[k][s0] - rb1, rv1 = self.ref_ep[k][s1] - if rb0 > 0: - hist_ep[k][s0] = rv0 - hist_ep_b[k][s0] = rb0 - hist_ep_cb[k][s0] = rb0 - ep_conf_slots += 1 - if rb1 > 0: - hist_ep[k][s1] = rv1 - hist_ep_b[k][s1] = rb1 - hist_ep_cb[k][s1] = rb1 - ep_conf_slots += 1 - if rb0 > 0 and rb1 > 0: - continue - obs_list = self.ep_obs.get((k, sub, c)) - if not obs_list: - continue - best0, best1 = self._fit_ep_pair(obs_list) - if c == 0 and (k, sub) in self.pbit_parity: - c0, c1 = self.pbit_parity[(k, sub)] - if (c0 > 0) != (c1 > 0): - req = 0 if c0 > 0 else 1 - if (((best0 >> 1) ^ (best1 >> 1)) & 1) != req: - best1 ^= 2 - depth = 8 if len(obs_list) >= 4 else 5 - if rb0 == 0: - hist_ep[k][s0] = best0 - hist_ep_b[k][s0] = depth - ep_prov_slots += 1 - if len(obs_list) < 3: - last_resort.append([k, sub, 0, c]) - if rb1 == 0: - hist_ep[k][s1] = best1 - hist_ep_b[k][s1] = depth - ep_prov_slots += 1 - if len(obs_list) < 3: - last_resort.append([k, sub, 1, c]) - - last_resort.sort() - doc = { - "historyEndpoints": hist_ep, - "historyEndpointBits": hist_ep_b, - "historyEndpointConfirmedBits": hist_ep_cb, - "historyIndices": hist_ix, - "historyIndexBits": hist_ix_b, - "historyIndexConfirmedBits": hist_ix_cb, - "historyEndpointLastResort": last_resort, - } - stats = { - "endpoint_confirmed_slots": ep_conf_slots, - "endpoint_provisional_slots": ep_prov_slots, - "endpoint_last_resort_slots": len(last_resort), - "index_confirmed_slots": ix_conf_slots, - "index_provisional_slots": ix_prov_slots, - "reference_blocks": self.ref_blocks, - "reference_conflicts": self.conflicts, - "pool_chunks": self.pool_chunks, - "pool_textures": self.pool_textures, - } - return doc, stats - - -# --------------------------------------------------------------------------- -# Reference-pair loaders (`--ref-dds` and `--ref-pairs`) -# --------------------------------------------------------------------------- - -def parse_ref_dds_spec(spec): - """Parse `POOL:INDEX=REF.dds`, preserving Windows drive letters.""" - if "=" not in spec: - raise CliError(f"invalid --ref-dds {spec!r}: expected POOL:INDEX=REF.dds") - left, dds_path = spec.split("=", 1) - if ":" not in left: - raise CliError(f"invalid --ref-dds {spec!r}: expected POOL:INDEX=REF.dds") - pool_path, idx_s = left.rsplit(":", 1) - if not pool_path or not dds_path: - raise CliError(f"invalid --ref-dds {spec!r}: expected POOL:INDEX=REF.dds") - try: - index = int(idx_s) - except ValueError: - raise CliError(f"invalid texture index in --ref-dds {spec!r}") - if index < 0: - raise CliError(f"texture index must be non-negative in --ref-dds {spec!r}") - return pool_path, index, dds_path - - -def apply_ref_dds(pool_path, index, dds_path, calibrators): - """Retile a reference DDS against a TTPF texture entry and invert all matching chunks.""" - if not os.path.isfile(pool_path): - raise CliError(f"reference pool not found: {pool_path}") - if not os.path.isfile(dds_path): - raise CliError(f"reference DDS not found: {dds_path}") - dxgi, width, height, mips = read_dds(dds_path) - pool = _ttpf.Pool(pool_path) - try: - if not 0 <= index < pool.textures: - raise CliError(f"texture index {index} out of range for {pool_path} ({pool.textures} entries)") - d = pool.descriptor(index) - a = _ttpf.analyze(pool, index, allow_bcpack=True) - if "layout" not in a or not a.get("available"): - raise CliError(f"{pool_path}:{index}: unsupported or unavailable layout for reference calibration") - if d["width"] != width or d["height"] != height: - raise CliError( - f"{pool_path}:{index}: DDS size {width}x{height} disagrees with pool {d['width']}x{d['height']}" - ) - lay = a["layout"] - seen_chunks = set() - # Build virtual-offset map of retiled DDS mip bytes. - tiled_ranges: dict[int, bytearray] = {} - known_ranges: dict[int, bytearray] = {} - for m, mip in enumerate(lay["mips"]): - if m >= len(mips): - break - start = d["base"] + mip["offset"] - if start not in tiled_ranges: - tiled_ranges[start] = bytearray(mip["region"]) - known_ranges[start] = bytearray(mip["region"]) - _retile_mip_into(mips[m], lay, mip, tiled_ranges[start], known_ranges[start]) - # Match every BCPack chunk touching those mips. - for m, mip in enumerate(lay["mips"]): - if m >= len(mips): - break - for virt, csize, src, packed, codec, _pad in pool.chunks_for(d["base"] + mip["offset"], mip["region"]): - if codec not in calibrators: - continue - if dxgi not in CODEC_DXGI[codec]: - raise CliError(f"{dds_path}: DXGI format {dxgi} does not match codec {CODEC_KEYS[codec]}") - key = (src, packed, codec) - if key in seen_chunks: - continue - # Assemble the chunk's reference tiled bytes from `tiled_ranges`. - ref_chunk = bytearray(csize) - known_chunk = bytearray(csize) - for mstart, mtiled in tiled_ranges.items(): - mend = mstart + len(mtiled) - lo = max(virt, mstart) - hi = min(virt + csize, mend) - if lo < hi: - ref_chunk[lo - virt:hi - virt] = mtiled[lo - mstart:hi - mstart] - known_chunk[lo - virt:hi - virt] = known_ranges[mstart][lo - mstart:hi - mstart] - eb = bcpack.BLOCK_BYTES[codec] - nblocks = csize // eb - max_b = min(nblocks, 256) - # DDS files contain visible blocks only. Tiled padding and - # bytes belonging to absent mips are not reference evidence. - valid_blocks = [all(known_chunk[i * eb:(i + 1) * eb]) for i in range(max_b)] - if not any(valid_blocks): - continue - raw = pool.data[src:src + packed] - sym_per_blk = 1 if codec in (1, 4) else 2 - lanes = decode_lanes_prefix(raw, codec, csize, max_b * sym_per_blk) - calibrators[codec].add_reference_chunk(lanes, bytes(ref_chunk), max_b, - valid_blocks=valid_blocks) - seen_chunks.add(key) - finally: - pool.close() - - -def apply_ref_pairs_file(pairs_path, calibrators): - """Apply a JSON file of raw `(codec, chunk, reference)` block pairs or DDS pairs.""" - if not os.path.isfile(pairs_path): - raise CliError(f"reference pairs file not found: {pairs_path}") - try: - with open(pairs_path, "r", encoding="utf-8-sig") as fh: - data = json.load(fh) - except (OSError, json.JSONDecodeError) as exc: - raise CliError(f"{pairs_path}: {exc}") - items = data.get("pairs") if isinstance(data, dict) else data - if not isinstance(items, list): - raise CliError(f"{pairs_path}: expected a JSON list or {{\"pairs\": [...]}}") - base_dir = os.path.dirname(os.path.abspath(pairs_path)) - for idx, item in enumerate(items): - if not isinstance(item, dict): - raise CliError(f"{pairs_path}: pair {idx} must be a JSON object") - if "pool" in item and "dds" in item: - p_path = item["pool"] - d_path = item["dds"] - if not os.path.isabs(p_path): - p_path = os.path.join(base_dir, p_path) - if not os.path.isabs(d_path): - d_path = os.path.join(base_dir, d_path) - apply_ref_dds(p_path, int(item["index"]), d_path, calibrators) - continue - cspec = str(item.get("codec", "")).strip().lower() - codec = CODEC_ALIASES.get(cspec) - if codec is None: - raise CliError(f"{pairs_path}: pair {idx} has invalid codec {item.get('codec')!r}") - if codec not in calibrators: - continue - if "chunk_hex" in item: - raw = bytes.fromhex(item["chunk_hex"]) - elif "chunk_file" in item: - cp = item["chunk_file"] - if not os.path.isabs(cp): - cp = os.path.join(base_dir, cp) - with open(cp, "rb") as fh: - raw = fh.read() - else: - raise CliError(f"{pairs_path}: pair {idx} missing chunk_hex or chunk_file") - if "ref_hex" in item: - ref_bytes = bytes.fromhex(item["ref_hex"]) - elif "ref_file" in item: - rp = item["ref_file"] - if not os.path.isabs(rp): - rp = os.path.join(base_dir, rp) - with open(rp, "rb") as fh: - ref_bytes = fh.read() - else: - raise CliError(f"{pairs_path}: pair {idx} missing ref_hex or ref_file") - eb = bcpack.BLOCK_BYTES[codec] - out_size = int(item.get("out_size", len(ref_bytes))) - if out_size <= 0 or out_size % eb != 0 or len(ref_bytes) < out_size: - raise CliError(f"{pairs_path}: pair {idx} out_size/ref length mismatch") - nblocks = out_size // eb - max_b = min(nblocks, 256) - sym_per_blk = 1 if codec in (1, 4) else 2 - lanes = decode_lanes_prefix(raw, codec, out_size, max_b * sym_per_blk) - calibrators[codec].add_reference_chunk(lanes, ref_bytes, max_b) - - -# --------------------------------------------------------------------------- -# Pool self-calibration runner -# --------------------------------------------------------------------------- - -def _make_sibling_quads_getter(codec, lay, mip_z, ztiled, kind, signed=False): - zblk_cache = {} - pw, ph = mip_z["pixels_w"], mip_z["pixels_h"] - - def _decode_block(bx_z, by_z): - key = (bx_z, by_z) - blk = zblk_cache.get(key) - if blk is None: - off = tiled_offset(lay, mip_z, bx_z, by_z) - if codec == 1: - blk = decode_bc1_block_rgba(ztiled, off) - elif codec == 3: - blk = decode_bc3_block_rgba(ztiled, off) - elif codec == 4: - blk = decode_bc4_block_u8(ztiled, off) - elif codec == 5: - blk = decode_bc5_block_rg(ztiled, off) - elif codec == 6: - blk = decode_bc6h_block_unq(ztiled, off, signed=signed) - else: - blk = decode_bc7_block_rgba(ztiled, off) - zblk_cache[key] = blk - return blk - - def _get_pixel(px, py): - px = min(pw - 1, max(0, px)) - py = min(ph - 1, max(0, py)) - blk = _decode_block(px >> 2, py >> 2) - return blk[((py & 3) << 2) | (px & 3)] - - def get_quads(bx, by): - if kind == "child": - return tuple(_get_pixel(2 * bx + dx, 2 * by + dy) for dy in (0, 1) for dx in (0, 1)) - out = [] - for qy in (0, 1): - for qx in (0, 1): - x0, y0 = 8 * bx + 4 * qx, 8 * by + 4 * qy - x1, y1 = min(pw, x0 + 4), min(ph, y0 + 4) - if codec == 4: - acc = 0.0 - cnt = 0 - for py in range(y0, y1): - for px in range(x0, x1): - acc += _get_pixel(px, py) - cnt += 1 - out.append(acc / cnt if cnt else 0.0) - else: - nch = 2 if codec == 5 else (3 if codec == 6 else 4) - acc = [0.0] * nch - cnt = 0 - for py in range(y0, y1): - for px in range(x0, x1): - pv = _get_pixel(px, py) - for c in range(nch): - acc[c] += pv[c] - cnt += 1 - out.append(tuple(v / cnt for v in acc) if cnt else (0.0,) * nch) - return tuple(out) - - return get_quads - - -def calibrate_from_pools(pools, calibrators, *, limit=0, max_blocks=256): - """Scan TTPF pools read-only to populate self-calibrated history tables.""" - target_codecs = set(calibrators.keys()) - dxgi_to_codec = {} - for cid in target_codecs: - for dfmt in CODEC_DXGI[cid]: - dxgi_to_codec[dfmt] = cid - - # When `limit > 0`, divide quota round-robin across pools so every pool - # contributes textures rather than exhausting `--limit` on the first pool. - n_pools = len(pools) - per_pool_cap = {} - if limit > 0 and n_pools > 0: - base_q = max(1, (limit + n_pools - 1) // n_pools) - for cid in target_codecs: - per_pool_cap[cid] = base_q - - tex_counts = {cid: 0 for cid in target_codecs} - alg_counts = {cid: 0 for cid in target_codecs} - alg_limit = max(limit * 4, 256) if limit > 0 else 0 - - for pool_path in pools: - if limit > 0 and all(tex_counts[c] >= limit for c in target_codecs): - break - pool = _ttpf.Pool(pool_path) - try: - cache = {} - pool_tex = {cid: 0 for cid in target_codecs} - seen_alg = set() - for ti in range(pool.textures): - if limit > 0 and all( - tex_counts[c] >= limit or pool_tex[c] >= per_pool_cap[c] - for c in target_codecs - ): - break - d = pool.descriptor(ti) - if d["base"] == 0 or d["dimension"] != 1 or d["depth"] != 1: - continue - cid = dxgi_to_codec.get(d["format"]) - if cid is None: - continue - need_mixed = (limit == 0) or ( - tex_counts[cid] < limit and pool_tex[cid] < per_pool_cap[cid] - ) - need_alg = cid in (6, 7) and (alg_limit == 0 or alg_counts[cid] < alg_limit) - if not need_mixed and not need_alg: - continue - a = _ttpf.analyze(pool, ti, allow_bcpack=True) - if "layout" not in a or not a.get("available"): - continue - mc = a["mip_codecs"] - lay = a["layout"] - nmips = len(lay["mips"]) - # Find mixed (BCPack mip, adjacent raw/zlib mip) pairs - pairs = [] - if need_mixed: - for m in range(nmips): - if cid not in mc[m]: - continue - if m + 1 < nmips and set(mc[m + 1]) <= {0, 8}: - pairs.append((m, m + 1, "child")) - elif m > 0 and set(mc[m - 1]) <= {0, 8} and lay["mips"][m - 1]["region"] <= 1048576: - pairs.append((m, m - 1, "parent")) - cal = calibrators[cid] - eb = bcpack.BLOCK_BYTES[cid] - sym_per_blk = 1 if cid in (1, 4) else 2 - signed = d["format"] in (81, 84, 96) - used_mixed = False - - for m, mz, kind in pairs: - mip_bc = lay["mips"][m] - mip_z = lay["mips"][mz] - mip_virt = d["base"] + mip_bc["offset"] - chunks = pool.chunks_for(mip_virt, mip_bc["region"]) - bc_chunks = [c for c in chunks if c[4] == cid] - if not bc_chunks: - continue - ztiled = pool.read_range(d["base"] + mip_z["offset"], mip_z["region"], cache, bcpack_mode="off") - inv_lookup = make_inverse_tile_lookup(lay, mip_bc) - get_quads = _make_sibling_quads_getter(cid, lay, mip_z, ztiled, kind, signed=signed) - for virt, csize, src, packed, codec, _pad in bc_chunks: - nb = min(csize // eb, max_blocks) - if nb <= 0: - continue - raw = pool.data[src:src + packed] - lanes = decode_lanes_prefix(raw, cid, csize, nb * sym_per_blk) - cal.add_pool_chunk(lanes, nb, inv_lookup, virt - mip_virt, get_quads) - seen_alg.add((src, packed, cid)) - used_mixed = True - - if used_mixed: - tex_counts[cid] += 1 - pool_tex[cid] += 1 - cal.pool_textures += 1 - elif need_alg: - # Pure-BCPack BC6H/BC7 chunks still yield exact anchor & p-bit constraints - for m in range(nmips): - if cid not in mc[m]: - continue - mip_bc = lay["mips"][m] - for virt, csize, src, packed, codec, _pad in pool.chunks_for( - d["base"] + mip_bc["offset"], mip_bc["region"] - ): - if codec != cid or (src, packed, cid) in seen_alg: - continue - nb = min(csize // eb, max_blocks) - if nb <= 0: - continue - raw = pool.data[src:src + packed] - lanes = decode_lanes_prefix(raw, cid, csize, nb * sym_per_blk) - cal.add_pool_chunk(lanes, nb) - seen_alg.add((src, packed, cid)) - alg_counts[cid] += 1 - break - break - finally: - pool.close() - - -# --------------------------------------------------------------------------- -# Schema validation & pool verification (`--verify` / `--check`) -# --------------------------------------------------------------------------- - -def validate_history_schema(history_path, codecs): - """Validate history JSON schema for `codecs` and return aggregate coverage counts.""" - if not os.path.exists(history_path): - raise CliError(f"history path not found: {history_path}") - summary = {} - for cid in codecs: - ckey = CODEC_KEYS[cid] - if cid == 6: - eh, ih, ec, ic = _bptc.load_bc6h(history_path) - for i in range(256): - if not 0 <= ec[i] <= 3: - raise ValueError(f"BC6H endpointClass[{i}]={ec[i]} outside 0..3") - if not 0 <= ic[i] <= 3: - raise ValueError(f"BC6H indexClass[{i}]={ic[i]} outside 0..3") - for c in range(3): - w, x, y, z = eh[i][c] - if not (0 <= w <= 65535 and 0 <= x <= 1023 and 0 <= y <= 63 and 0 <= z <= 63): - raise ValueError(f"BC6H endpointHistory[{i}][{c}] out of bounds") - if any(not 0 <= p <= 15 for p in ih[i]): - raise ValueError(f"BC6H indexHistory[{i}] pixel out of 0..15") - summary[ckey] = { - "endpoint_confirmed": sum(1 for v in ec if v == 3), - "endpoint_provisional": sum(1 for v in ec if v == 1), - "endpoint_last_resort": sum(1 for v in ec if v == 2), - "endpoint_unknown": sum(1 for v in ec if v == 0), - "index_confirmed": sum(1 for v in ic if v == 3), - "index_provisional": sum(1 for v in ic if v == 1), - "index_last_resort": sum(1 for v in ic if v == 2), - "index_unknown": sum(1 for v in ic if v == 0), - } - elif cid == 7: - tab = _bptc.load_bc7(history_path) - ep = tab["history_endpoints"] - ep_b = tab["history_endpoint_bits"] - ep_cb = tab["history_endpoint_confirmed_bits"] - ix = tab["history_indices"] - ix_b = tab["history_index_bits"] - ix_cb = tab["history_index_confirmed_bits"] - for i in range(256): - for j in range(24): - if not 0 <= ep[i][j] <= 255: - raise ValueError(f"BC7 historyEndpoints[{i}][{j}] out of 0..255") - if not 0 <= ep_cb[i][j] <= ep_b[i][j] <= 8: - raise ValueError(f"BC7 endpoint bit depth invalid at [{i}][{j}]") - for j in range(32): - if not 0 <= ix[i][j] <= 15: - raise ValueError(f"BC7 historyIndices[{i}][{j}] out of 0..15") - if not 0 <= ix_cb[i][j] <= ix_b[i][j] <= 4: - raise ValueError(f"BC7 index bit depth invalid at [{i}][{j}]") - summary[ckey] = { - "endpoint_confirmed_slots": sum(1 for row in ep_cb for v in row if v > 0), - "endpoint_known_slots": sum(1 for row in ep_b for v in row if v > 0), - "endpoint_last_resort_slots": len(tab["last_resort"]), - "index_confirmed_slots": sum(1 for row in ix_cb for v in row if v > 0), - "index_known_slots": sum(1 for row in ix_b for v in row if v > 0), - } - else: - loaded = _bptc.load_bc_history(cid, history_path) - if loaded is None: - summary[ckey] = {"present": False} - else: - conf, prov, rep = loaded - summary[ckey] = { - "present": True, - "confirmed_entries": len(conf), - "provisional_entries": len(prov), - "replace": rep, - } - return summary - - -def verify_against_pools(history_path, codecs, pools, *, limit=20): - """Test sampled BCPack chunks from `pools` with `history_path` (aggregate stats only).""" - target = set(codecs) - cap = limit if limit > 0 else 20 - results = { - CODEC_KEYS[c]: {"tested": 0, "strict_ok": 0, "provisional_ok": 0, "refused": 0, "errors": 0} - for c in codecs - } - tested = {c: 0 for c in codecs} - seen = set() - for pool_path in pools: - if all(tested[c] >= cap for c in codecs): - break - pool = _ttpf.Pool(pool_path) - try: - for virt, csize, src, packed, codec, _pad in pool.chunks: - if all(tested[c] >= cap for c in codecs): - break - if codec not in target or tested[codec] >= cap: - continue - key = (pool_path, src, packed, codec) - if key in seen: - continue - seen.add(key) - raw = pool.data[src:src + packed] - rec = results[CODEC_KEYS[codec]] - rec["tested"] += 1 - tested[codec] += 1 - try: - bcpack.decode_with_info(raw, codec, csize, allow_provisional=False, history=history_path) - rec["strict_ok"] += 1 - rec["provisional_ok"] += 1 - continue - except bcpack.BcpackProvisionalError: - pass - except bcpack.BcpackError: - rec["errors"] += 1 - continue - try: - bcpack.decode_with_info(raw, codec, csize, allow_provisional=True, history=history_path) - rec["provisional_ok"] += 1 - except bcpack.BcpackProvisionalError: - rec["refused"] += 1 - except bcpack.BcpackError: - rec["errors"] += 1 - finally: - pool.close() - return results - - -# --------------------------------------------------------------------------- -# Output writer & path guards -# --------------------------------------------------------------------------- - -def _resolve_pools(paths): - pools = [] - for p in paths: - found = _ttpf.find_pools(p) - if not found: - why = "no such file or folder" if not os.path.exists(p) else "no .ttpf pool in it" - raise CliError(f"{p}: {why}") - pools.extend(found) - # Deterministic sorted deduplicated order - seen = set() - unique = [] - for p in sorted(pools, key=lambda s: os.path.normcase(os.path.abspath(s))): - norm = os.path.normcase(os.path.abspath(p)) - if norm not in seen: - seen.add(norm) - unique.append(p) - return unique - - -def _write_json_deterministic(path, obj): - parent = os.path.dirname(os.path.abspath(path)) - if parent: - os.makedirs(parent, exist_ok=True) - text = json.dumps(obj, sort_keys=True, indent=2) + "\n" - with open(path, "w", encoding="utf-8", newline="\n") as fh: - fh.write(text) - - -def write_outputs(out_path, docs, pools): - """Write either a combined `.json` file or per-codec `.json` files into a directory.""" - is_json_file = out_path.lower().endswith(".json") - if is_json_file: - if os.path.isdir(out_path): - raise CliError(f"--out {out_path} is an existing directory") - for p in pools: - if _ttpf.same_output_path(out_path, p): - raise CliError(f"--out would overwrite input pool {p}") - _write_json_deterministic(out_path, docs) - return [out_path] - if os.path.isfile(out_path): - raise CliError(f"--out {out_path} is an existing file (use a directory or a .json path)") - os.makedirs(out_path, exist_ok=True) - written = [] - for ckey in sorted(docs.keys()): - target = os.path.join(out_path, f"{ckey}.json") - for p in pools: - if _ttpf.same_output_path(target, p): - raise CliError(f"--out would overwrite input pool {p}") - _write_json_deterministic(target, docs[ckey]) - written.append(target) - return written - - -# --------------------------------------------------------------------------- -# CLI entrypoint -# --------------------------------------------------------------------------- - -def build_arg_parser(): - ap = argparse.ArgumentParser( - prog="bcpack_history_calib.py", - description=( - "Locally calibrate and validate BCPack initial history JSON tables " - "for tools/bcpack.py and tools/ttpf_mips.py --history." - ), - ) - ap.add_argument( - "inputs", - nargs="*", - help="read-only .ttpf pool files or directories (e.g. game root or ttdb folder)", - ) - ap.add_argument( - "--out", - metavar="PATH", - help="output directory (writes bc6h.json, bc7.json, ...) or combined .json file", - ) - ap.add_argument( - "--codec", - default="bc6h,bc7", - help="comma-separated codecs (bc1,bc3,bc4,bc5,bc6h,bc7) or 'all' (default: bc6h,bc7)", - ) - ap.add_argument( - "--limit", - type=int, - default=0, - help="max mixed textures per codec to scan from pools (0 = scan all; also verify sample cap)", - ) - ap.add_argument( - "--max-blocks", - type=int, - default=256, - help="prefix blocks decoded per BCPack chunk during self-calibration (default: 256)", - ) - ap.add_argument( - "--ref-dds", - action="append", - default=[], - metavar="POOL:INDEX=REF.dds", - help="exact reference DDS paired with a pool texture (produces confirmed history entries)", - ) - ap.add_argument( - "--ref-pairs", - action="append", - default=[], - metavar="PAIRS.json", - help="JSON file of exact chunk/reference block pairs (produces confirmed history entries)", - ) - ap.add_argument( - "--verify", - nargs="?", - const="__OUT__", - default=None, - metavar="PATH", - help="validate history JSON schema (and test sampled chunks if pools are given)", - ) - ap.add_argument( - "--check", - action="store_true", - help="alias for --verify on the written --out path", - ) - ap.add_argument( - "--replace", - action="store_true", - help="set replace=true on generated BC1-BC5 JSON files instead of overlaying defaults", - ) - ap.add_argument( - "--json", - action="store_true", - help="print machine-readable aggregate JSON summary to stdout", - ) - return ap - - -def run(argv=None): - ap = build_arg_parser() - args = ap.parse_args(argv) - if args.limit < 0: - raise CliError("--limit must be non-negative") - if args.max_blocks <= 0: - raise CliError("--max-blocks must be positive") - codecs = parse_codecs(args.codec) - pools = _resolve_pools(args.inputs) if args.inputs else [] - - do_verify = args.check or (args.verify is not None) - verify_target = None - if args.verify == "__OUT__" or (args.check and args.verify is None): - verify_target = args.out - elif args.verify is not None: - verify_target = args.verify - - if not args.out and not do_verify: - raise CliError("specify --out to calibrate or --verify to validate") - if do_verify and not verify_target: - raise CliError("--verify / --check requires a history path or --out ") - - report = {"codecs": [CODEC_KEYS[c] for c in codecs]} - - if args.out: - if not pools and not args.ref_dds and not args.ref_pairs: - raise CliError("calibration requires TTPF inputs, --ref-dds, or --ref-pairs") - calibrators = {} - for cid in codecs: - if cid == 6: - calibrators[cid] = Bc6hCalibrator() - elif cid == 7: - calibrators[cid] = Bc7Calibrator() - else: - calibrators[cid] = BcSimpleCalibrator(cid) - - for spec in args.ref_dds: - pool_path, index, dds_path = parse_ref_dds_spec(spec) - apply_ref_dds(pool_path, index, dds_path, calibrators) - for pairs_path in args.ref_pairs: - apply_ref_pairs_file(pairs_path, calibrators) - if pools: - calibrate_from_pools( - pools, calibrators, limit=args.limit, max_blocks=args.max_blocks - ) - - docs = {} - cal_stats = {} - for cid in codecs: - ckey = CODEC_KEYS[cid] - cal = calibrators[cid] - if cid in (1, 3, 4, 5): - doc, st = cal.build_document(replace=args.replace) - else: - doc, st = cal.build_document() - docs[ckey] = doc - cal_stats[ckey] = st - - written = write_outputs(args.out, docs, pools) - report["out"] = args.out - report["files_written"] = len(written) - report["pools_scanned"] = len(pools) - report["calibration"] = cal_stats - - if do_verify: - schema = validate_history_schema(verify_target, codecs) - verify_info = {"path": verify_target, "schema_ok": True, "tables": schema} - if pools: - verify_info["pool_check"] = verify_against_pools( - verify_target, codecs, pools, limit=(args.limit or 20) - ) - report["verify"] = verify_info - - if args.json: - print(json.dumps(report, sort_keys=True, indent=2)) - else: - if "calibration" in report: - print(f"Calibrated {', '.join(report['codecs'])} -> {report['out']} ({report['files_written']} file(s))") - for ckey, st in report["calibration"].items(): - parts = ", ".join(f"{k}={v}" for k, v in st.items()) - print(f" {ckey}: {parts}") - if "verify" in report: - vi = report["verify"] - print(f"Verified history schema at {vi['path']}: OK") - for ckey, st in vi["tables"].items(): - parts = ", ".join(f"{k}={v}" for k, v in st.items()) - print(f" {ckey} table: {parts}") - if "pool_check" in vi: - for ckey, st in vi["pool_check"].items(): - print( - f" {ckey} pool check: tested={st['tested']} strict={st['strict_ok']} " - f"provisional={st['provisional_ok']} refused={st['refused']} errors={st['errors']}" - ) - return 0 - - -def main(argv=None): - try: - return run(argv) - except (CliError, ValueError, OSError, json.JSONDecodeError, bcpack.BcpackError) as exc: - print(f"ERROR: {exc}", file=sys.stderr) - return 2 - - -if __name__ == "__main__": - try: # a redirected stdout is strict ANSI code page under -I; write '?' for what it cannot encode - sys.stdout.reconfigure(errors="replace") - except (AttributeError, ValueError, OSError): - pass - raise SystemExit(main()) diff --git a/tools/bcpack_tables.py b/tools/bcpack_tables.py deleted file mode 100644 index b087d3bba..000000000 --- a/tools/bcpack_tables.py +++ /dev/null @@ -1,493 +0,0 @@ -"""Fixed codec constant tables for the clean-room BCPack decoder. - -All values here are codec-level constants (rANS exponential probability models, -symbol-rank tables, and built-in initial endpoint history entries), not game -texture assets. Recovered clean-room from public specifications (US patent -11,234,023 and BCn block formats) and statistical/algebraic fitting; confirmed -and provisional built-in history entries are kept strictly separate so callers -can refuse unconfirmed entries by default. -""" - -# (symbol_width, q) -> per-band rANS frequencies (band 0 is symbol 0; -# band p >= 1 covers symbols [2^(p-1), 2^p)); total weight is 65536. -PROB_TABLES = { - (1, 0): (32768, 32768), - (1, 1): (38761, 26775), - (1, 2): (44484, 21052), - (1, 3): (49818, 15718), - (1, 4): (54623, 10913), - (1, 5): (58721, 6815), - (1, 6): (61911, 3625), - (1, 7): (64036, 1500), - (1, 8): (65121, 415), - (1, 9): (65477, 59), - (1, 10): (65534, 2), - (1, 11): (65535, 1), - (1, 12): (65535, 1), - (1, 13): (65535, 1), - (1, 14): (65535, 1), - (1, 15): (65535, 1), - (2, 0): (16384, 16384, 16384), - (2, 1): (21168, 17592, 13388), - (2, 2): (26354, 18130, 10526), - (2, 3): (31900, 17918, 7859), - (2, 4): (37750, 16874, 5456), - (2, 5): (43800, 14920, 3408), - (2, 6): (49850, 12062, 1812), - (2, 7): (55537, 8499, 750), - (2, 8): (60308, 4812, 208), - (2, 9): (63575, 1901, 30), - (2, 10): (65132, 402, 1), - (2, 11): (65511, 23, 1), - (2, 12): (65533, 1, 1), - (2, 13): (65533, 1, 1), - (2, 14): (65533, 1, 1), - (2, 15): (65533, 1, 1), - (3, 0): (8192, 8192, 8192, 8192), - (3, 1): (11073, 10095, 8796, 6694), - (3, 2): (14406, 11948, 9065, 5263), - (3, 3): (18234, 13666, 8958, 3930), - (3, 4): (22624, 15126, 8437, 2728), - (3, 5): (27657, 16143, 7460, 1704), - (3, 6): (33414, 16436, 6031, 906), - (3, 7): (39920, 15616, 4250, 375), - (3, 8): (47024, 13284, 2406, 104), - (3, 9): (54201, 9375, 950, 15), - (3, 10): (60388, 4744, 200, 1), - (3, 11): (64250, 1262, 10, 1), - (3, 12): (65456, 74, 1, 1), - (3, 13): (65529, 1, 1, 1), - (3, 14): (65529, 1, 1, 1), - (3, 15): (65529, 1, 1, 1), - (4, 0): (4096, 4096, 4096, 4096, 4096), - (4, 1): (5665, 5407, 5048, 4398, 3347), - (4, 2): (7539, 6867, 5973, 4532, 2632), - (4, 3): (9773, 8461, 6833, 4479, 1965), - (4, 4): (12447, 10177, 7564, 4218, 1364), - (4, 5): (15679, 11977, 8072, 3730, 852), - (4, 6): (19640, 13774, 8217, 3016, 453), - (4, 7): (24559, 15361, 7808, 2124, 188), - (4, 8): (30704, 16320, 6642, 1203, 52), - (4, 9): (38280, 15920, 4688, 476, 7), - (4, 10): (47169, 13219, 2372, 99, 1), - (4, 11): (56354, 7896, 631, 4, 1), - (4, 12): (63248, 2208, 34, 1, 1), - (4, 13): (65465, 57, 1, 1, 1), - (4, 14): (65521, 1, 1, 1, 1), - (4, 15): (65521, 1, 1, 1, 1), - (5, 0): (2048, 2048, 2048, 2048, 2048, 2048), - (5, 1): (2865, 2799, 2704, 2524, 2200, 1673), - (5, 2): (3858, 3682, 3434, 2986, 2266, 1316), - (5, 3): (5063, 4709, 4230, 3418, 2240, 982), - (5, 4): (6536, 5912, 5088, 3782, 2109, 682), - (5, 5): (8366, 7314, 5988, 4036, 1865, 426), - (5, 6): (10688, 8952, 6888, 4108, 1507, 227), - (5, 7): (13713, 10847, 7680, 3904, 1062, 94), - (5, 8): (17758, 12946, 8160, 3320, 602, 26), - (5, 9): (23272, 15008, 7960, 2344, 237, 4), - (5, 10): (30841, 16327, 6610, 1187, 48, 1), - (5, 11): (41006, 15348, 3947, 316, 1, 1), - (5, 12): (53291, 9957, 1104, 14, 1, 1), - (5, 13): (63380, 2084, 22, 1, 1, 1), - (5, 14): (65505, 1, 1, 1, 1, 1), - (5, 15): (65505, 1, 1, 1, 1, 1), - (6, 0): (1024, 1024, 1024, 1024, 1024, 1024, 1024), - (6, 1): (1441, 1423, 1400, 1352, 1262, 1099, 837), - (6, 2): (1951, 1907, 1841, 1717, 1493, 1133, 658), - (6, 3): (2577, 2487, 2354, 2115, 1709, 1120, 491), - (6, 4): (3350, 3186, 2956, 2544, 1890, 1055, 341), - (6, 5): (4324, 4042, 3657, 2994, 2019, 932, 213), - (6, 6): (5581, 5107, 4476, 3444, 2055, 754, 113), - (6, 7): (7258, 6454, 5424, 3840, 1952, 531, 47), - (6, 8): (9579, 8179, 6473, 4080, 1660, 301, 13), - (6, 9): (12907, 10365, 7504, 3980, 1171, 119, 2), - (6, 10): (17852, 12988, 8164, 3304, 594, 23, 1), - (6, 11): (25441, 15565, 7673, 1974, 155, 1, 1), - (6, 12): (37208, 16084, 4978, 552, 4, 1, 1), - (6, 13): (53649, 9731, 1042, 4, 1, 1, 1), - (6, 14): (65147, 327, 1, 1, 1, 1, 1), - (6, 15): (65473, 1, 1, 1, 1, 1, 1), - (7, 0): (512, 512, 512, 512, 512, 512, 512, 512), - (7, 1): (722, 718, 712, 700, 676, 632, 550, 418), - (7, 2): (981, 971, 952, 920, 858, 748, 566, 329), - (7, 3): (1300, 1276, 1244, 1178, 1058, 854, 559, 246), - (7, 4): (1696, 1654, 1593, 1478, 1272, 946, 526, 171), - (7, 5): (2198, 2126, 2022, 1828, 1498, 1009, 467, 106), - (7, 6): (2852, 2728, 2554, 2238, 1721, 1028, 376, 57), - (7, 7): (3736, 3522, 3227, 2712, 1920, 977, 266, 23), - (7, 8): (4979, 4601, 4090, 3236, 2040, 831, 151, 6), - (7, 9): (6807, 6101, 5182, 3752, 1991, 586, 59, 1), - (7, 10): (9634, 8218, 6494, 4082, 1652, 296, 11, 1), - (7, 11): (14275, 11165, 7784, 3836, 988, 74, 1, 1), - (7, 12): (22449, 14759, 8042, 2489, 272, 1, 1, 1), - (7, 13): (37625, 16023, 4866, 509, 1, 1, 1, 1), - (7, 14): (60485, 4663, 132, 1, 1, 1, 1, 1), - (7, 15): (65409, 1, 1, 1, 1, 1, 1, 1), - (8, 0): (256, 256, 256, 256, 256, 256, 256, 256, 256), - (8, 1): (362, 360, 359, 356, 350, 338, 316, 275, 209), - (8, 2): (492, 488, 486, 476, 460, 429, 374, 284, 164), - (8, 3): (653, 647, 638, 622, 589, 529, 426, 280, 123), - (8, 4): (853, 843, 828, 796, 739, 636, 473, 264, 85), - (8, 5): (1108, 1090, 1063, 1011, 914, 748, 504, 234, 53), - (8, 6): (1442, 1410, 1364, 1277, 1120, 860, 514, 189, 28), - (8, 7): (1895, 1841, 1760, 1614, 1356, 961, 488, 132, 12), - (8, 8): (2538, 2442, 2300, 2045, 1618, 1021, 414, 76, 3), - (8, 9): (3497, 3311, 3050, 2591, 1875, 996, 292, 29, 1), - (8, 10): (5008, 4626, 4109, 3247, 2041, 826, 149, 4, 1), - (8, 11): (7575, 6701, 5582, 3892, 1918, 494, 34, 1, 1), - (8, 12): (12397, 10051, 7380, 4020, 1245, 129, 1, 1, 1), - (8, 13): (22767, 14857, 8012, 2432, 240, 1, 1, 1, 1), - (8, 14): (47343, 13141, 2332, 35, 1, 1, 1, 1, 1), - (8, 15): (65281, 1, 1, 1, 1, 1, 1, 1, 1), - (9, 0): (128, 128, 128, 128, 128, 128, 128, 128, 128, 128), - (9, 1): (181, 181, 179, 180, 178, 175, 169, 157, 137, 105), - (9, 2): (246, 246, 244, 243, 238, 231, 214, 187, 142, 82), - (9, 3): (327, 325, 324, 319, 310, 294, 265, 213, 141, 61), - (9, 4): (428, 424, 422, 414, 397, 370, 319, 236, 131, 43), - (9, 5): (557, 551, 546, 530, 506, 457, 374, 252, 116, 27), - (9, 6): (725, 717, 705, 683, 638, 560, 430, 256, 95, 14), - (9, 7): (955, 941, 920, 880, 807, 677, 481, 244, 66, 6), - (9, 8): (1282, 1256, 1219, 1150, 1023, 810, 510, 207, 37, 2), - (9, 9): (1772, 1724, 1656, 1524, 1295, 938, 498, 147, 13, 1), - (9, 10): (2554, 2454, 2312, 2054, 1625, 1020, 414, 74, 1, 1), - (9, 11): (3904, 3672, 3350, 2791, 1946, 959, 247, 14, 1, 1), - (9, 12): (6523, 5873, 5026, 3690, 2011, 621, 58, 1, 1, 1), - (9, 13): (12593, 10175, 7428, 4006, 1216, 105, 1, 1, 1, 1), - (9, 14): (31009, 16335, 6572, 1136, 1, 1, 1, 1, 1, 1), - (9, 15): (65025, 1, 1, 1, 1, 1, 1, 1, 1, 1), - (10, 0): (64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64), - (10, 1): (91, 89, 90, 90, 90, 90, 88, 85, 79, 69, 52), - (10, 2): (123, 123, 123, 123, 121, 120, 115, 108, 93, 71, 41), - (10, 3): (164, 164, 162, 161, 160, 155, 148, 131, 108, 69, 31), - (10, 4): (214, 214, 212, 211, 206, 199, 184, 160, 117, 67, 21), - (10, 5): (279, 277, 276, 273, 265, 252, 229, 187, 126, 59, 13), - (10, 6): (364, 360, 358, 352, 342, 319, 280, 215, 129, 47, 7), - (10, 7): (479, 477, 470, 460, 441, 404, 339, 240, 122, 33, 3), - (10, 8): (644, 638, 627, 610, 576, 511, 405, 254, 105, 18, 1), - (10, 9): (892, 880, 862, 828, 763, 647, 469, 248, 73, 6, 1), - (10, 10): (1290, 1264, 1227, 1156, 1028, 812, 510, 207, 34, 1, 1), - (10, 11): (1982, 1922, 1836, 1674, 1396, 972, 481, 123, 4, 1, 1), - (10, 12): (3347, 3177, 2936, 2513, 1846, 1004, 311, 22, 1, 1, 1), - (10, 13): (6632, 5962, 5087, 3714, 2003, 609, 37, 1, 1, 1, 1), - (10, 14): (17963, 13041, 8168, 3285, 506, 1, 1, 1, 1, 1, 1), - (10, 15): (64513, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1), -} - -# BC1 index lanes: symbol -> 2x2 quadrant byte (TL, TR, BL, BR in bits 0-1, 2-3, 4-5, 6-7). -BC1_QUADRANT = bytes([ - 0xaa, 0xff, 0x00, 0x55, 0xfa, 0xaf, 0xfb, 0xbf, 0xfe, 0xef, 0xbb, 0xee, 0xdf, 0xba, 0x5a, 0xae, - 0x7f, 0xea, 0xab, 0xf7, 0xfd, 0xa5, 0x5f, 0xf5, 0xdd, 0x77, 0x66, 0x99, 0x2a, 0x8a, 0xa2, 0x50, - 0x05, 0xa8, 0x11, 0x9a, 0x44, 0x3f, 0xa6, 0xa9, 0xcf, 0xbe, 0xfc, 0xf3, 0x6a, 0xeb, 0x7e, 0xe7, - 0xdb, 0xbd, 0x7a, 0xa7, 0xda, 0x0f, 0xad, 0x57, 0xd5, 0x0a, 0x5d, 0x75, 0x2f, 0x6e, 0xf0, 0x8f, - 0xf8, 0xe6, 0x3d, 0xf2, 0xb9, 0x25, 0x7c, 0x9b, 0x3b, 0x85, 0xce, 0xec, 0x58, 0xb3, 0xd3, 0xa0, - 0x52, 0xde, 0x7b, 0x2b, 0xb7, 0x5e, 0xc7, 0xed, 0x5b, 0xb2, 0x8e, 0xcc, 0x6f, 0x19, 0xf6, 0x9f, - 0x64, 0xe8, 0xe5, 0x29, 0xf9, 0x33, 0x46, 0x22, 0xb5, 0xd7, 0x2d, 0x78, 0x56, 0x86, 0x88, 0x68, - 0x91, 0x95, 0x92, 0xd2, 0x87, 0x7d, 0x76, 0x67, 0x9d, 0x59, 0x65, 0xd9, 0x15, 0x37, 0x93, 0x5c, - 0xc6, 0x35, 0x6c, 0xcd, 0x39, 0x45, 0xdc, 0x54, 0x73, 0x51, 0x53, 0xc5, 0x2e, 0x8b, 0x8d, 0x27, - 0xe2, 0x1f, 0xf4, 0x1d, 0xd8, 0xf1, 0x72, 0xa3, 0x4f, 0x74, 0xb8, 0xca, 0x3a, 0xac, 0xd1, 0x89, - 0x47, 0x26, 0x62, 0x98, 0x70, 0x0d, 0xa1, 0x1a, 0x4a, 0x6b, 0x1b, 0xd0, 0xa4, 0xe9, 0x07, 0xb1, - 0x9e, 0xb6, 0xe4, 0x4e, 0xbc, 0xe3, 0x3e, 0xcb, 0x82, 0x31, 0x02, 0x28, 0x4c, 0x13, 0xc4, 0x20, - 0x0e, 0x0b, 0x08, 0x96, 0x80, 0xe0, 0x09, 0xb0, 0x69, 0x60, 0x06, 0x90, 0x23, 0x97, 0x8c, 0xd6, - 0x21, 0x6d, 0x79, 0x32, 0xc8, 0x48, 0x84, 0x17, 0x12, 0xd4, 0x4d, 0x71, 0x01, 0x36, 0x63, 0x9c, - 0xc9, 0x40, 0x04, 0x10, 0xe1, 0x16, 0x94, 0x49, 0x4b, 0x1e, 0xb4, 0x61, 0x03, 0x0c, 0xc0, 0x42, - 0x81, 0x18, 0x30, 0x24, 0xc3, 0x3c, 0xc2, 0x41, 0x14, 0x83, 0x2c, 0x38, 0x43, 0x34, 0x1c, 0xc1, -]) - -# BC1 built-in 256-entry endpoint history: index -> (r0, g0, b0, r1, g1, b1). -BC1_HISTORY_CONFIRMED = { - 1: (7, 29, 6, 8, 30, 7), 2: (15, 29, 15, 16, 36, 17), 3: (20, 38, 14, 3, 5, 2), - 4: (12, 27, 13, 6, 12, 6), 5: (10, 22, 11, 6, 14, 7), 7: (12, 26, 12, 7, 14, 7), - 8: (22, 36, 15, 20, 32, 14), 9: (14, 23, 8, 1, 2, 1), 10: (23, 5, 30, 9, 5, 30), - 11: (11, 22, 11, 7, 15, 7), 12: (17, 22, 7, 10, 11, 3), 13: (12, 25, 12, 7, 16, 7), - 14: (13, 28, 8, 5, 11, 3), 15: (11, 20, 8, 16, 31, 14), 16: (23, 32, 30, 17, 12, 29), - 17: (8, 44, 30, 6, 26, 30), 18: (10, 24, 30, 6, 45, 30), 19: (10, 12, 4, 8, 8, 2), - 20: (16, 23, 30, 14, 6, 26), 21: (12, 25, 13, 10, 22, 12), 22: (19, 27, 10, 12, 15, 5), - 23: (11, 24, 12, 4, 11, 6), 24: (29, 60, 29, 6, 13, 6), 25: (17, 31, 11, 1, 2, 1), - 26: (26, 54, 24, 12, 24, 10), 27: (23, 49, 30, 20, 36, 30), 28: (16, 23, 10, 10, 14, 6), - 29: (11, 24, 10, 6, 13, 5), 30: (18, 52, 30, 14, 22, 30), 31: (14, 51, 30, 9, 34, 30), - 32: (2, 3, 1, 19, 37, 16), 33: (14, 15, 30, 9, 31, 30), 34: (29, 57, 27, 27, 52, 25), - 35: (13, 29, 15, 8, 20, 11), 36: (13, 17, 5, 9, 10, 3), 37: (18, 50, 29, 15, 10, 29), - 38: (11, 25, 13, 8, 19, 10), 39: (17, 32, 12, 6, 11, 4), 40: (22, 18, 30, 19, 41, 30), - 41: (10, 22, 11, 8, 18, 9), 42: (18, 30, 31, 10, 44, 30), 43: (25, 50, 24, 2, 4, 1), - 44: (11, 30, 31, 7, 15, 29), 45: (12, 19, 8, 11, 16, 7), 46: (19, 29, 30, 14, 55, 28), - 47: (9, 20, 10, 4, 10, 5), 48: (12, 24, 10, 7, 13, 5), 49: (26, 53, 25, 6, 13, 6), - 50: (19, 27, 31, 11, 19, 30), 51: (21, 31, 30, 22, 31, 30), 52: (10, 19, 5, 11, 21, 6), - 53: (30, 50, 3, 29, 46, 2), 54: (15, 9, 30, 7, 9, 30), 55: (14, 18, 6, 11, 14, 4), - 56: (28, 56, 26, 4, 7, 3), 57: (9, 20, 10, 5, 13, 7), 58: (28, 58, 26, 15, 32, 14), - 59: (11, 19, 8, 6, 9, 4), 60: (16, 22, 9, 13, 17, 7), 61: (1, 2, 1, 14, 28, 12), - 62: (22, 45, 30, 9, 15, 30), 63: (19, 22, 30, 16, 23, 31), 64: (25, 50, 24, 21, 43, 20), - 65: (6, 11, 4, 16, 31, 13), 66: (13, 25, 8, 3, 6, 1), 67: (5, 9, 3, 12, 24, 10), - 68: (16, 29, 13, 7, 13, 5), 69: (20, 38, 16, 13, 25, 10), 70: (18, 35, 15, 5, 9, 3), - 72: (11, 21, 7, 7, 13, 4), 73: (20, 39, 16, 11, 20, 8), 74: (16, 31, 12, 4, 8, 2), - 75: (22, 41, 30, 18, 23, 30), 76: (24, 50, 24, 9, 19, 8), 77: (3, 12, 7, 4, 16, 8), - 78: (18, 27, 12, 16, 22, 10), 79: (24, 49, 23, 13, 28, 12), 80: (24, 50, 24, 18, 37, 18), - 81: (17, 33, 12, 14, 27, 9), 82: (20, 10, 31, 13, 10, 31), 83: (7, 8, 2, 5, 5, 1), - 84: (1, 2, 1, 10, 21, 9), 85: (10, 18, 6, 1, 1, 0), 86: (22, 46, 21, 1, 3, 1), - 87: (11, 20, 8, 8, 14, 5), 88: (17, 35, 31, 14, 14, 29), 89: (16, 22, 31, 12, 40, 31), - 90: (12, 22, 9, 8, 15, 6), 91: (18, 15, 30, 15, 33, 31), 92: (19, 32, 30, 15, 43, 31), - 93: (18, 35, 15, 8, 15, 5), 94: (21, 43, 20, 18, 37, 17), 95: (10, 17, 6, 9, 15, 6), - 96: (14, 27, 12, 7, 13, 5), 97: (8, 16, 7, 12, 25, 11), 98: (18, 37, 17, 1, 1, 0), - 99: (17, 45, 30, 15, 33, 31), 100: (13, 25, 11, 8, 16, 7), 101: (23, 47, 22, 16, 32, 15), - 102: (18, 33, 13, 11, 21, 8), 103: (4, 10, 4, 8, 17, 7), 104: (1, 2, 1, 3, 7, 3), - 105: (11, 22, 9, 6, 11, 4), 106: (16, 29, 11, 13, 23, 9), 107: (12, 24, 12, 6, 12, 6), - 108: (23, 47, 22, 7, 14, 6), 109: (11, 32, 30, 11, 31, 30), 110: (14, 26, 11, 10, 18, 7), - 111: (20, 41, 19, 1, 3, 1), 112: (14, 28, 12, 8, 16, 6), 113: (11, 21, 9, 8, 15, 6), - 114: (1, 2, 1, 7, 13, 6), 115: (19, 35, 14, 16, 29, 12), 116: (13, 27, 13, 7, 15, 7), - 117: (15, 33, 16, 8, 18, 9), 118: (15, 42, 31, 11, 22, 30), 119: (23, 48, 23, 4, 9, 4), - 120: (22, 45, 21, 11, 22, 10), 121: (31, 62, 30, 31, 61, 29), 123: (19, 39, 19, 9, 20, 10), - 124: (7, 14, 2, 6, 12, 2), 125: (21, 42, 20, 3, 7, 3), 126: (10, 17, 7, 8, 13, 5), - 127: (11, 20, 8, 9, 17, 7), 128: (19, 33, 31, 12, 31, 31), 129: (21, 43, 20, 5, 11, 5), - 130: (10, 20, 9, 7, 13, 6), 131: (10, 21, 10, 6, 13, 6), 132: (15, 29, 12, 11, 20, 8), - 133: (21, 43, 20, 9, 18, 8), 134: (3, 8, 3, 5, 11, 5), 135: (16, 31, 13, 9, 17, 7), - 136: (11, 22, 11, 6, 12, 6), 137: (10, 21, 10, 7, 15, 7), 138: (27, 3, 1, 26, 1, 0), - 139: (18, 37, 18, 16, 32, 16), 140: (12, 23, 10, 9, 17, 7), 141: (12, 25, 12, 8, 17, 8), - 142: (11, 21, 9, 2, 4, 1), 143: (7, 15, 7, 8, 18, 9), 144: (17, 33, 15, 13, 24, 11), - 145: (9, 19, 9, 7, 15, 7), 146: (21, 43, 20, 13, 27, 12), 147: (17, 36, 17, 2, 4, 2), - 148: (10, 20, 9, 6, 12, 5), 149: (20, 41, 19, 7, 14, 7), 150: (3, 9, 6, 2, 8, 5), - 151: (13, 24, 10, 11, 20, 8), 152: (18, 38, 18, 4, 7, 3), 153: (19, 38, 18, 8, 17, 8), - 154: (16, 35, 17, 4, 10, 4), 155: (11, 23, 11, 10, 21, 10), 156: (17, 36, 17, 7, 14, 7), - 157: (13, 27, 13, 6, 12, 6), 158: (9, 15, 4, 8, 13, 4), 159: (10, 19, 7, 5, 9, 3), - 160: (19, 40, 19, 11, 24, 11), 161: (11, 23, 11, 8, 17, 8), 162: (14, 29, 14, 7, 15, 7), - 163: (12, 22, 9, 5, 8, 3), 164: (10, 20, 9, 8, 17, 8), 165: (21, 42, 19, 15, 31, 14), - 166: (14, 29, 13, 1, 1, 0), 167: (8, 16, 8, 7, 14, 7), 168: (9, 18, 8, 8, 16, 7), - 169: (10, 17, 7, 3, 4, 1), 170: (14, 28, 13, 2, 4, 1), 171: (14, 30, 14, 3, 6, 3), - 172: (19, 38, 18, 5, 11, 5), 173: (12, 26, 12, 1, 2, 1), 174: (9, 16, 6, 8, 13, 5), - 175: (8, 13, 4, 7, 11, 4), 176: (16, 34, 16, 3, 7, 3), 177: (13, 28, 13, 4, 9, 4), - 178: (15, 31, 15, 6, 13, 6), 179: (12, 24, 11, 9, 19, 9), 180: (9, 19, 8, 7, 14, 6), - 181: (14, 28, 13, 5, 10, 4), 182: (10, 20, 7, 4, 6, 2), 183: (16, 34, 17, 11, 25, 12), - 184: (15, 30, 15, 8, 16, 8), 185: (13, 27, 13, 10, 20, 10), 186: (9, 20, 9, 0, 1, 0), - 187: (16, 32, 15, 2, 4, 2), 188: (13, 27, 12, 3, 6, 3), 189: (13, 26, 12, 12, 23, 11), - 190: (12, 25, 12, 5, 10, 5), 191: (11, 23, 11, 5, 11, 5), 192: (16, 34, 16, 6, 12, 5), - 193: (16, 35, 31, 15, 25, 31), 194: (16, 33, 16, 7, 15, 7), 195: (13, 27, 13, 8, 18, 8), - 196: (18, 36, 17, 11, 22, 10), 197: (18, 37, 18, 13, 27, 13), 198: (12, 25, 12, 4, 8, 4), - 199: (9, 18, 7, 6, 11, 4), 200: (15, 30, 14, 9, 19, 9), 201: (17, 35, 16, 9, 18, 9), - 202: (11, 24, 11, 2, 4, 2), 203: (16, 33, 16, 0, 1, 0), 204: (15, 31, 15, 4, 9, 4), - 205: (16, 31, 15, 14, 27, 13), 206: (14, 29, 14, 13, 25, 12), 207: (11, 23, 11, 3, 6, 3), - 208: (16, 32, 16, 10, 21, 10), 209: (11, 22, 11, 4, 9, 4), 210: (11, 22, 10, 1, 2, 0), - 211: (8, 14, 5, 2, 4, 1), 212: (9, 16, 6, 6, 10, 4), 213: (10, 21, 10, 9, 19, 9), - 214: (14, 30, 14, 11, 22, 11), 215: (9, 18, 8, 6, 13, 6), 216: (6, 13, 6, 5, 11, 5), - 217: (7, 14, 6, 0, 1, 0), 218: (4, 7, 2, 3, 4, 1), 219: (10, 20, 9, 4, 8, 4), - 220: (9, 17, 7, 5, 9, 3), 221: (7, 14, 7, 1, 2, 1), 222: (10, 20, 10, 5, 10, 5), - 223: (8, 15, 5, 4, 6, 2), 224: (8, 17, 8, 1, 2, 1), 225: (10, 20, 10, 3, 6, 3), - 226: (7, 10, 3, 6, 8, 3), 227: (8, 15, 7, 6, 12, 6), 228: (9, 19, 9, 2, 4, 2), - 229: (6, 11, 4, 3, 4, 1), 230: (6, 11, 4, 0, 1, 0), 231: (8, 16, 7, 2, 4, 2), - 232: (16, 34, 16, 15, 29, 15), 233: (7, 16, 7, 5, 10, 5), 234: (8, 14, 5, 5, 9, 3), - 235: (9, 18, 8, 4, 8, 4), 236: (5, 9, 3, 4, 7, 2), 237: (9, 18, 8, 5, 10, 5), - 238: (6, 12, 6, 2, 4, 2), 239: (7, 12, 5, 4, 7, 3), 240: (5, 11, 5, 1, 2, 1), - 241: (8, 17, 8, 3, 6, 3), 242: (16, 31, 31, 16, 32, 31), 243: (7, 14, 7, 3, 6, 3), - 244: (5, 11, 6, 4, 9, 4), 245: (7, 15, 7, 4, 8, 4), 246: (2, 4, 2, 0, 0, 1), - 247: (5, 11, 5, 3, 6, 3), 248: (4, 8, 4, 1, 1, 1), 249: (3, 6, 3, 1, 2, 1), - 250: (2, 4, 1, 1, 2, 1), 251: (4, 8, 4, 3, 6, 3), 252: (3, 6, 3, 2, 4, 2), - 253: (4, 9, 4, 2, 4, 2), 254: (17, 27, 31, 15, 34, 31), 255: (0, 0, 1, 0, 0, 0), -} - -BC1_HISTORY_PROVISIONAL = { - 6: (12, 24, 11, 7, 14, 6), 71: (13, 25, 11, 6, 11, 4), 122: (13, 26, 11, 5, 8, 3), -} - -# BC3 3-bit alpha index pair rank table (64 entries) and colour quadrant rank table (256 entries). -BC3_ALPHA_PAIR = ( - (0, 0), (1, 1), (6, 6), (4, 4), (3, 3), (5, 5), (7, 7), (1, 6), - (6, 1), (0, 1), (1, 0), (7, 1), (1, 7), (0, 3), (3, 0), (0, 2), - (2, 0), (2, 2), (5, 4), (3, 4), (4, 3), (4, 5), (1, 5), (5, 1), - (0, 4), (4, 0), (2, 3), (3, 2), (5, 3), (3, 5), (6, 5), (5, 6), - (6, 7), (7, 6), (5, 7), (4, 6), (6, 4), (7, 5), (6, 0), (0, 6), - (4, 2), (2, 4), (4, 1), (1, 4), (5, 0), (0, 5), (6, 3), (3, 6), - (3, 1), (5, 2), (1, 3), (2, 5), (7, 4), (4, 7), (7, 3), (3, 7), - (2, 6), (6, 2), (2, 1), (1, 2), (0, 7), (7, 0), (2, 7), (7, 2), -) - -BC3_COLOUR_QUADRANT = bytes([ - 0x55, 0xaa, 0xff, 0x00, 0x50, 0x05, 0xaf, 0xfa, 0xae, 0xea, 0xab, 0xba, 0xee, 0xbb, 0xfe, 0xbf, - 0xef, 0xfb, 0xa5, 0x5a, 0xf0, 0x11, 0x0f, 0x44, 0xf5, 0x5f, 0xa0, 0x0a, 0x8a, 0xa2, 0xa8, 0x2a, - 0x7f, 0xf7, 0x77, 0xdf, 0xfd, 0xdd, 0x66, 0x99, 0x88, 0xbe, 0xeb, 0x22, 0xcc, 0x33, 0x8f, 0xf8, - 0x57, 0x75, 0xd5, 0x5d, 0x2f, 0xf2, 0x7a, 0x85, 0xa7, 0xda, 0x58, 0x25, 0xad, 0x52, 0x3f, 0xf3, - 0xcf, 0xe8, 0xfc, 0x8e, 0x2b, 0x7e, 0x6a, 0xa6, 0x9a, 0x70, 0x07, 0x0d, 0xa9, 0x78, 0x80, 0x08, - 0x02, 0xe7, 0xb2, 0x20, 0xdb, 0xd0, 0x87, 0x5e, 0xbd, 0x7c, 0x2d, 0xe5, 0xc7, 0xec, 0xce, 0x5b, - 0xb3, 0xd2, 0x2e, 0xb5, 0x3b, 0xe0, 0xe6, 0x6e, 0x68, 0x8b, 0x9b, 0xe2, 0xb9, 0x0e, 0xb8, 0x0b, - 0x3d, 0xd3, 0x51, 0x86, 0x27, 0x45, 0x15, 0xde, 0x54, 0x8d, 0xb7, 0xed, 0x7b, 0xb0, 0xd8, 0x29, - 0x72, 0x92, 0x7d, 0xd7, 0x35, 0xa3, 0xc5, 0x82, 0x37, 0x53, 0x28, 0x5c, 0x56, 0x65, 0x76, 0x95, - 0x59, 0xcd, 0x9f, 0x3a, 0x73, 0x89, 0xca, 0xac, 0x67, 0x9d, 0xf6, 0xd9, 0xf9, 0x91, 0x19, 0xdc, - 0x98, 0x6c, 0x46, 0x64, 0x6f, 0x26, 0x39, 0x62, 0xc6, 0x93, 0x09, 0x23, 0x06, 0x60, 0x8c, 0xc8, - 0x90, 0x32, 0x03, 0x3e, 0xc0, 0x13, 0x31, 0xe3, 0x4c, 0x9e, 0x0c, 0xc4, 0xcb, 0xbc, 0xb6, 0xe9, - 0x30, 0x6b, 0x1f, 0xf1, 0x1d, 0xd1, 0x47, 0x74, 0x4f, 0x10, 0x40, 0xf4, 0x01, 0x04, 0xa1, 0x1a, - 0xa4, 0x1b, 0x4a, 0xb1, 0xe4, 0x4e, 0x36, 0xc9, 0x9c, 0x63, 0x97, 0x71, 0x79, 0x17, 0x48, 0x69, - 0x21, 0x12, 0x3c, 0x84, 0x83, 0x6d, 0xd6, 0x96, 0xc3, 0x38, 0x1e, 0x4d, 0xe1, 0xd4, 0xc2, 0x2c, - 0x18, 0x81, 0xb4, 0x4b, 0x16, 0x61, 0xc1, 0x24, 0x1c, 0x49, 0x14, 0x42, 0x94, 0x41, 0x34, 0x43, -]) - -# BC3 built-in endpoint history: index -> (a0, a1, r0, g0, b0, r1, g1, b1). -BC3_HISTORY_CONFIRMED = {} - -BC3_HISTORY_PROVISIONAL = { - 2: (177, 134, 27, 55, 24, 14, 54, 24), 26: (255, 255, 21, 34, 8, 15, 22, 3), - 29: (220, 109, 17, 35, 17, 15, 30, 15), 30: (219, 96, 2, 53, 14, 2, 59, 16), - 35: (95, 65, 16, 31, 16, 15, 31, 15), 37: (136, 13, 16, 33, 16, 15, 32, 15), - 47: (146, 108, 18, 37, 18, 13, 26, 13), 52: (255, 255, 20, 38, 16, 3, 5, 2), - 71: (200, 51, 17, 34, 17, 15, 31, 15), 76: (170, 150, 2, 60, 20, 1, 61, 20), - 78: (248, 10, 3, 4, 2, 0, 1, 0), 95: (237, 229, 26, 51, 25, 1, 3, 1), - 98: (255, 0, 19, 38, 18, 14, 29, 13), 104: (255, 6, 13, 27, 13, 8, 17, 8), - 109: (254, 4, 15, 27, 11, 3, 4, 2), 112: (117, 39, 21, 41, 21, 1, 3, 1), - 126: (170, 119, 16, 31, 16, 15, 30, 15), 138: (122, 121, 14, 29, 14, 13, 27, 13), - 139: (247, 1, 15, 28, 13, 9, 16, 7), 153: (105, 126, 2, 7, 4, 1, 3, 2), - 154: (93, 100, 20, 40, 20, 15, 30, 15), 166: (91, 99, 17, 35, 17, 15, 30, 15), - 167: (155, 99, 16, 33, 16, 15, 31, 15), 177: (255, 255, 13, 24, 12, 11, 23, 10), - 185: (254, 255, 10, 17, 7, 2, 3, 1), 197: (253, 255, 11, 20, 9, 6, 11, 4), - 210: (254, 255, 5, 10, 5, 1, 2, 1), 220: (255, 255, 11, 20, 9, 9, 17, 7), - 225: (106, 113, 24, 39, 23, 0, 13, 0), 226: (1, 255, 8, 15, 7, 5, 10, 4), - 230: (1, 2, 0, 1, 1, 0, 0, 0), 232: (140, 131, 16, 31, 16, 15, 34, 16), - 237: (255, 254, 5, 11, 5, 4, 9, 3), 244: (255, 255, 1, 1, 1, 0, 0, 0), - 246: (253, 254, 3, 5, 2, 1, 2, 1), -} - -# BC4 3-bit index pair rank table (64 entries) and built-in endpoint history: index -> (a0, a1). -BC4_PAIR = ( - (1, 1), (0, 0), (3, 3), (6, 6), (4, 4), (5, 5), (3, 0), (0, 3), - (6, 1), (1, 6), (7, 7), (2, 2), (6, 3), (3, 6), (1, 0), (0, 1), - (4, 1), (1, 4), (3, 1), (1, 3), (6, 0), (0, 6), (4, 2), (7, 5), - (5, 7), (2, 4), (0, 5), (5, 0), (6, 4), (4, 6), (5, 3), (3, 5), - (4, 0), (0, 4), (1, 5), (5, 1), (3, 4), (4, 3), (2, 6), (6, 2), - (7, 3), (3, 7), (1, 2), (2, 1), (0, 7), (7, 0), (2, 5), (5, 2), - (7, 4), (4, 7), (4, 5), (5, 4), (3, 2), (2, 3), (0, 2), (2, 0), - (1, 7), (7, 1), (6, 5), (5, 6), (6, 7), (7, 6), (2, 7), (7, 2), -) - -BC4_HISTORY_CONFIRMED = { - 52: (217, 182), 190: (43, 25), -} - -BC4_HISTORY_PROVISIONAL = { - 3: (122, 77), 15: (67, 91), 25: (83, 49), 32: (114, 158), - 33: (58, 31), 34: (83, 58), 35: (103, 121), 40: (246, 65), - 41: (244, 137), 42: (101, 141), 43: (181, 141), 49: (224, 201), - 55: (227, 73), 57: (213, 205), 60: (125, 83), 62: (243, 91), - 63: (214, 190), 64: (226, 53), 66: (230, 227), 69: (156, 116), - 70: (250, 174), 71: (220, 86), 72: (238, 115), 73: (227, 42), - 74: (166, 80), 75: (200, 166), 77: (164, 124), 80: (74, 115), - 81: (83, 99), 82: (186, 74), 83: (140, 148), 84: (204, 141), - 85: (220, 103), 86: (208, 44), 87: (147, 108), 88: (190, 88), - 90: (203, 82), 91: (222, 142), 92: (218, 217), 93: (206, 63), - 94: (186, 189), 96: (197, 48), 98: (203, 203), 99: (147, 116), - 100: (196, 14), 101: (172, 137), 102: (214, 124), 103: (200, 174), - 104: (122, 83), 105: (152, 157), 106: (88, 51), 107: (178, 87), - 108: (169, 149), 109: (170, 98), 110: (171, 71), 111: (202, 183), - 112: (138, 100), 114: (153, 148), 116: (77, 34), 117: (140, 82), - 118: (171, 106), 119: (194, 127), 120: (197, 193), 121: (179, 118), - 123: (190, 161), 124: (179, 167), 125: (115, 126), 126: (139, 108), - 127: (132, 115), 128: (161, 89), 129: (182, 152), 130: (186, 61), - 131: (165, 56), 132: (170, 175), 133: (186, 177), 134: (167, 159), - 135: (153, 81), 137: (145, 140), 139: (151, 94), 140: (57, 74), - 141: (112, 107), 142: (132, 91), 145: (74, 16), 147: (177, 43), - 148: (151, 124), 149: (123, 107), 150: (145, 73), 151: (113, 75), - 152: (75, 71), 153: (107, 90), 154: (194, 106), 155: (158, 69), - 156: (159, 40), 157: (71, 51), 158: (144, 132), 159: (156, 15), - 160: (144, 62), 161: (81, 75), 162: (122, 91), 163: (55, 33), - 164: (76, 58), 165: (152, 53), 167: (89, 83), 168: (114, 83), - 169: (65, 74), 171: (152, 39), 172: (140, 119), 173: (42, 15), - 174: (65, 41), 175: (114, 91), 178: (90, 50), 179: (48, 8), - 180: (102, 102), 181: (132, 70), 182: (73, 56), 183: (123, 119), - 184: (72, 34), 185: (159, 136), 186: (131, 107), 187: (105, 12), - 188: (143, 40), 189: (113, 99), 192: (79, 85), 193: (126, 100), - 195: (98, 58), 196: (90, 74), 197: (133, 135), 198: (96, 90), - 200: (55, 17), 202: (82, 42), 203: (71, 66), 204: (133, 52), - 205: (89, 58), 206: (113, 6), 207: (132, 123), 208: (39, 9), - 209: (136, 27), 211: (39, 23), 212: (81, 50), 213: (19, 41), - 214: (39, 17), 215: (103, 82), 217: (115, 21), 218: (120, 60), - 219: (81, 58), 220: (73, 42), 221: (47, 17), 223: (64, 25), - 224: (119, 34), 226: (66, 58), 227: (33, 16), 228: (101, 67), - 229: (66, 49), 230: (101, 75), 232: (78, 5), 234: (33, 60), - 235: (57, 24), 236: (69, 2), 239: (105, 25), 240: (96, 35), - 241: (112, 46), 243: (47, 25), 244: (88, 22), 245: (85, 66), - 246: (49, 33), 247: (22, 17), 248: (55, 41), 250: (130, 129), - 252: (27, 8), 254: (12, 6), -} - -# BC5 3-bit index pair rank table (64 entries) and built-in endpoint history: index -> (r0, r1, g0, g1). -BC5_PAIR = ( - (0, 0), (1, 1), (4, 4), (3, 3), (6, 6), (7, 7), (4, 0), (0, 4), - (0, 1), (2, 2), (1, 0), (3, 0), (0, 3), (5, 5), (2, 0), (0, 2), - (1, 6), (6, 1), (4, 3), (1, 7), (3, 4), (1, 4), (7, 1), (6, 0), - (0, 6), (6, 3), (6, 4), (3, 6), (3, 2), (4, 6), (1, 5), (1, 3), - (2, 3), (5, 4), (5, 3), (5, 0), (4, 1), (7, 6), (4, 5), (4, 2), - (3, 1), (3, 5), (5, 1), (6, 7), (2, 4), (7, 5), (7, 4), (0, 5), - (6, 5), (4, 7), (5, 7), (7, 0), (5, 6), (0, 7), (7, 3), (3, 7), - (5, 2), (2, 5), (1, 2), (6, 2), (2, 1), (2, 6), (7, 2), (2, 7), -) - -BC5_HISTORY_CONFIRMED = { - 105: (219, 153, 195, 135), 182: (133, 126, 124, 55), 183: (128, 126, 116, 112), - 222: (131, 128, 123, 37), 255: (129, 127, 128, 126), -} - -BC5_HISTORY_PROVISIONAL = { - 3: (130, 218, 45, 192), 4: (172, 109, 158, 94), 5: (183, 136, 113, 69), - 6: (125, 129, 86, 34), 7: (171, 196, 33, 82), 9: (142, 149, 102, 118), - 14: (82, 62, 26, 23), 15: (100, 94, 32, 32), 16: (97, 123, 61, 97), - 19: (133, 140, 118, 123), 20: (206, 194, 128, 123), 22: (147, 145, 64, 66), - 24: (76, 189, 55, 171), 27: (94, 115, 86, 102), 28: (163, 38, 152, 29), - 29: (143, 133, 89, 80), 30: (197, 67, 172, 50), 31: (164, 218, 130, 127), - 32: (141, 145, 111, 132), 33: (177, 125, 131, 32), 34: (49, 113, 26, 94), - 36: (173, 169, 40, 28), 38: (117, 125, 43, 50), 39: (139, 111, 99, 72), - 40: (123, 93, 83, 49), 41: (189, 166, 135, 116), 42: (198, 97, 178, 73), - 43: (205, 201, 76, 86), 44: (172, 174, 73, 72), 46: (157, 210, 136, 188), - 47: (126, 149, 115, 129), 48: (158, 67, 137, 41), 49: (214, 120, 131, 80), - 51: (147, 150, 119, 119), 52: (169, 107, 135, 65), 54: (231, 168, 223, 154), - 55: (115, 144, 99, 120), 56: (74, 104, 50, 83), 57: (220, 132, 32, 123), - 58: (150, 136, 110, 96), 60: (139, 147, 124, 108), 61: (121, 124, 78, 94), - 63: (169, 151, 124, 103), 64: (120, 106, 103, 88), 65: (134, 147, 110, 109), - 67: (133, 125, 103, 107), 68: (160, 133, 118, 123), 69: (175, 78, 163, 68), - 70: (229, 133, 166, 121), 71: (233, 147, 224, 134), 72: (127, 142, 104, 121), - 73: (134, 150, 99, 121), 74: (110, 149, 83, 129), 75: (175, 187, 129, 141), - 77: (115, 124, 96, 104), 78: (164, 128, 141, 109), 79: (129, 85, 114, 22), - 80: (246, 131, 241, 125), 82: (168, 186, 145, 165), 83: (192, 133, 158, 100), - 84: (107, 143, 105, 133), 85: (201, 212, 172, 181), 86: (124, 138, 116, 121), - 87: (92, 60, 71, 40), 88: (203, 134, 149, 126), 90: (61, 123, 25, 114), - 91: (123, 160, 113, 145), 92: (150, 169, 135, 150), 93: (134, 139, 101, 109), - 94: (253, 94, 255, 63), 95: (123, 87, 106, 67), 96: (238, 133, 121, 121), - 98: (24, 18, 15, 10), 99: (117, 41, 97, 25), 100: (123, 121, 70, 67), - 101: (64, 59, 51, 49), 102: (11, 103, 12, 88), 103: (144, 133, 111, 123), - 104: (189, 200, 65, 52), 106: (150, 110, 138, 98), 107: (118, 142, 60, 117), - 108: (139, 145, 114, 118), 109: (216, 225, 191, 200), 110: (46, 46, 38, 33), - 111: (91, 132, 85, 126), 112: (154, 178, 115, 132), 114: (132, 126, 122, 15), - 115: (136, 134, 15, 123), 116: (131, 129, 105, 123), 119: (132, 215, 122, 149), - 120: (129, 138, 112, 111), 123: (136, 145, 119, 131), 124: (179, 196, 165, 183), - 125: (126, 125, 111, 92), 126: (136, 150, 122, 123), 127: (168, 158, 136, 126), - 128: (146, 153, 129, 134), 129: (127, 130, 85, 124), 130: (132, 241, 120, 126), - 131: (155, 124, 125, 85), 132: (121, 115, 115, 108), 133: (106, 72, 89, 51), - 134: (136, 155, 118, 137), 135: (121, 145, 106, 133), 136: (119, 220, 102, 209), - 137: (179, 136, 150, 122), 138: (120, 133, 102, 113), 139: (145, 142, 111, 112), - 140: (130, 108, 123, 62), 141: (121, 132, 37, 122), 142: (157, 142, 135, 119), - 143: (80, 201, 59, 191), 144: (130, 133, 122, 104), 145: (138, 136, 112, 120), - 146: (131, 107, 123, 37), 147: (122, 120, 107, 119), 148: (126, 181, 121, 146), - 149: (143, 141, 137, 135), 150: (134, 178, 121, 161), 151: (103, 135, 55, 126), - 152: (193, 132, 128, 123), 153: (141, 129, 111, 114), 154: (79, 77, 53, 51), - 155: (133, 72, 127, 64), 157: (102, 101, 83, 80), 159: (92, 137, 39, 125), - 160: (108, 136, 87, 122), 161: (102, 97, 65, 57), 162: (163, 149, 151, 134), - 163: (133, 17, 121, 15), 165: (179, 162, 153, 133), 166: (119, 132, 98, 125), - 167: (175, 132, 130, 124), 169: (132, 92, 124, 81), 170: (40, 31, 27, 19), - 171: (188, 211, 180, 202), 172: (139, 121, 117, 101), 173: (150, 125, 130, 106), - 174: (129, 184, 123, 131), 175: (132, 158, 126, 148), 176: (130, 155, 126, 129), - 177: (131, 167, 124, 127), 178: (155, 131, 132, 125), 179: (198, 139, 170, 124), - 180: (200, 196, 190, 186), 184: (173, 157, 163, 147), 185: (197, 175, 158, 137), - 186: (102, 129, 98, 126), 187: (131, 216, 121, 198), 188: (127, 135, 115, 130), - 189: (139, 196, 94, 111), 190: (132, 106, 123, 94), 191: (219, 130, 193, 116), - 192: (212, 133, 127, 124), 193: (196, 176, 173, 151), 194: (56, 192, 15, 27), - 195: (129, 198, 124, 131), 196: (131, 124, 125, 99), 197: (176, 130, 169, 126), - 198: (137, 127, 121, 111), 199: (144, 137, 131, 123), 200: (132, 130, 114, 120), - 201: (182, 165, 169, 153), 202: (138, 136, 113, 109), 203: (185, 172, 179, 164), - 204: (131, 127, 123, 81), 205: (124, 141, 121, 137), 206: (173, 131, 136, 92), - 208: (120, 133, 108, 123), 209: (147, 134, 123, 110), 210: (130, 142, 125, 129), - 211: (136, 137, 122, 131), 212: (130, 119, 127, 114), 214: (117, 136, 111, 131), - 215: (199, 181, 187, 167), 216: (132, 215, 124, 125), 217: (135, 138, 120, 114), - 218: (131, 85, 123, 45), 219: (197, 131, 193, 126), 221: (69, 206, 57, 195), - 223: (161, 156, 96, 92), 225: (130, 136, 123, 121), 226: (126, 60, 118, 46), - 227: (139, 137, 120, 124), 228: (140, 130, 124, 123), 229: (122, 127, 118, 123), - 231: (130, 141, 127, 138), 232: (54, 205, 50, 185), 233: (75, 74, 69, 68), - 234: (223, 130, 217, 125), 235: (111, 129, 108, 127), 236: (160, 129, 157, 126), - 237: (129, 217, 126, 217), 238: (148, 128, 146, 126), 239: (130, 129, 127, 118), - 241: (60, 200, 50, 200), 242: (131, 130, 120, 124), 243: (123, 132, 116, 127), - 244: (132, 135, 130, 132), 245: (129, 41, 126, 37), 246: (122, 133, 120, 133), - 247: (118, 128, 116, 126), 248: (136, 128, 133, 126), 249: (128, 133, 123, 131), - 250: (82, 81, 78, 77), 251: (124, 130, 122, 128), 252: (130, 130, 125, 124), - 253: (128, 128, 127, 127), 254: (127, 126, 126, 125), -} diff --git a/tools/bcpack_tables_bptc.py b/tools/bcpack_tables_bptc.py deleted file mode 100644 index 9e4500e75..000000000 --- a/tools/bcpack_tables_bptc.py +++ /dev/null @@ -1,418 +0,0 @@ -"""Public BPTC (BC6H and BC7) specification tables and runtime history loader. - -Everything embedded in this module is either standard public D3D11 / Khronos -BPTC specification data (2-subset and 3-subset partition masks and anchor pixel -indices) or the BC7 lane-15 bitstream signature permutation (`BC7_CONFIG`). - -BCPack's 256-entry initial endpoint/index history buffers for BC6H and BC7 are -**not** embedded in this repository because they are unpublished codec -constants that can only be recovered locally from the player's own texture -pools. Callers can decode self-contained BC6H/BC7 chunks (delta chains that -stay within the chunk) with `history=None`, or pass a locally generated JSON -file or directory (`--history `) at runtime. -""" -import json -import os - -# Standard D3D11 / Khronos BPTC 2-subset (64 x 16 pixels, 1 bit/pixel) and -# 3-subset (64 x 16 pixels, 2 bits/pixel) partition masks. -BC7_PART2_PACKED = ( - 0xcccc, 0x8888, 0xeeee, 0xecc8, 0xc880, 0xfeec, 0xfec8, 0xec80, - 0xc800, 0xffec, 0xfe80, 0xe800, 0xffe8, 0xff00, 0xfff0, 0xf000, - 0xf710, 0x008e, 0x7100, 0x08ce, 0x008c, 0x7310, 0x3100, 0x8cce, - 0x088c, 0x3110, 0x6666, 0x366c, 0x17e8, 0x0ff0, 0x718e, 0x399c, - 0xaaaa, 0xf0f0, 0x5a5a, 0x33cc, 0x3c3c, 0x55aa, 0x9696, 0xa55a, - 0x73ce, 0x13c8, 0x324c, 0x3bdc, 0x6996, 0xc33c, 0x9966, 0x0660, - 0x0272, 0x04e4, 0x4e40, 0x2720, 0xc936, 0x936c, 0x39c6, 0x639c, - 0x9336, 0x9cc6, 0x817e, 0xe718, 0xccf0, 0x0fcc, 0x7744, 0xee22, -) - -BC7_PART3_PACKED = ( - 0xaa685050, 0x6a5a5040, 0x5a5a4200, 0x5450a0a8, 0xa5a50000, 0xa0a05050, - 0x5555a0a0, 0x5a5a5050, 0xaa550000, 0xaa555500, 0xaaaa5500, 0x90909090, - 0x94949494, 0xa4a4a4a4, 0xa9a59450, 0x2a0a4250, 0xa5945040, 0x0a425054, - 0xa5a5a500, 0x55a0a0a0, 0xa8a85454, 0x6a6a4040, 0xa4a45000, 0x1a1a0500, - 0x0050a4a4, 0xaaa59090, 0x14696914, 0x69691400, 0xa08585a0, 0xaa821414, - 0x50a4a450, 0x6a5a0200, 0xa9a58000, 0x5090a0a8, 0xa8a09050, 0x24242424, - 0x00aa5500, 0x24924924, 0x24499224, 0x50a50a50, 0x500aa550, 0xaaaa4444, - 0x66660000, 0xa5a0a5a0, 0x50a050a0, 0x69286928, 0x44aaaa44, 0x66666600, - 0xaa444444, 0x54a854a8, 0x95809580, 0x96969600, 0xa85454a8, 0x80959580, - 0xaa141414, 0x96960000, 0xaaaa1414, 0xa05050a0, 0xa0a5a5a0, 0x96000000, - 0x40804080, 0xa9a8a9a8, 0xaaaaaa44, 0x2a4a5254, -) - -# Second and third subset anchor pixel indices (subset 0 anchor is always 0). -# BC6H two-region partitions use the first 32 entries of BC7_ANCHOR2. -BC7_ANCHOR2 = ( - 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, - 15, 2, 8, 2, 2, 8, 8, 15, 2, 8, 2, 2, 8, 8, 2, 2, - 15, 15, 6, 8, 2, 8, 15, 15, 2, 8, 2, 2, 2, 15, 15, 6, - 6, 2, 6, 8, 15, 15, 2, 2, 15, 15, 15, 15, 15, 2, 2, 15, -) - -BC7_ANCHOR3A = ( - 3, 3, 15, 15, 8, 3, 15, 15, 8, 8, 6, 6, 6, 5, 3, 3, - 3, 3, 8, 15, 3, 3, 6, 10, 5, 8, 8, 6, 8, 5, 15, 15, - 8, 15, 3, 5, 6, 10, 8, 15, 15, 3, 15, 5, 15, 15, 15, 15, - 3, 15, 5, 5, 5, 8, 5, 10, 5, 10, 8, 13, 15, 12, 3, 3, -) - -BC7_ANCHOR3B = ( - 15, 8, 8, 3, 15, 15, 3, 8, 15, 15, 15, 15, 15, 15, 15, 8, - 15, 8, 15, 3, 15, 8, 15, 8, 3, 15, 6, 10, 15, 15, 10, 8, - 15, 3, 15, 10, 10, 8, 9, 10, 6, 15, 8, 15, 3, 6, 6, 8, - 15, 3, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 3, 15, 15, 8, -) - -# BC7 lane-15 signature rank -> (mode, partition, rotation, index_selection). -# Lane-15 symbol pairs (a, b) on the 32 x 16 grid are ranked by -# `((a + 1) * (b + 1), a)` ascending. Modes 7, 6, 5, 4, 3 and 1 follow exact -# descending formulas; the 22 mode-2 partitions placed before mode 1 and the -# remaining 42 placed after mode 0 are both descending subsets of 0..63. -_BC7_MODE2_HEAD = ( - 63, 59, 58, 57, 54, 53, 52, 47, 43, 42, 40, - 38, 37, 35, 34, 32, 23, 21, 18, 17, 16, 11, -) - - -def _build_bc7_config(): - head_set = set(_BC7_MODE2_HEAD) - mode2_tail = tuple(p for p in range(63, -1, -1) if p not in head_set) - return ( - tuple((7, 63 - r, 0, 0) for r in range(64)) - + ((6, 0, 0, 0),) - + tuple((5, 0, 3 - r, 0) for r in range(4)) - + tuple((4, 0, (7 - r) >> 1, (7 - r) & 1) for r in range(8)) - + tuple((3, 63 - r, 0, 0) for r in range(64)) - + tuple((2, p, 0, 0) for p in _BC7_MODE2_HEAD) - + tuple((1, 63 - r, 0, 0) for r in range(64)) - + tuple((0, p, 0, 0) for p in (*range(15, 7, -1), *range(5, -1, -1))) - + tuple((2, p, 0, 0) for p in mode2_tail) - + ((0, 7, 0, 0), (0, 6, 0, 0), (255, 255, 0, 0)) - ) - - -BC7_CONFIG = _build_bc7_config() - -# Signature ranks whose mode-2 partition assignment is inferred from anchor -# positions and order only; strict mode refuses chunks that reference them. -BC7_CONFIG_INFERRED = frozenset((149, 151, 152, 153, 246, 248, 251, 252, 253, 254)) - -_EMPTY_BC6H_EH = tuple(((0, 0, 0, 0), (0, 0, 0, 0), (0, 0, 0, 0)) for _ in range(256)) -_EMPTY_BC6H_IH = tuple((0,) * 16 for _ in range(256)) -_EMPTY_BC6H_CLS = (0,) * 256 - -_EMPTY_BC7_EP = tuple((0,) * 24 for _ in range(256)) -_EMPTY_BC7_IX = tuple((0,) * 32 for _ in range(256)) - -_BC7_STATIC_CACHE = None -_FILE_CACHE = {} - - -def _bc7_static(): - """Return unpacked public D3D11/Khronos BC7 partition/anchor/signature tables.""" - global _BC7_STATIC_CACHE - if _BC7_STATIC_CACHE is None: - part2 = tuple( - tuple((mask >> p) & 1 for p in range(16)) for mask in BC7_PART2_PACKED - ) - part3 = tuple( - tuple((mask >> (2 * p)) & 3 for p in range(16)) for mask in BC7_PART3_PACKED - ) - cells = sorted( - ((a, b) for a in range(32) for b in range(16)), - key=lambda ab: ((ab[0] + 1) * (ab[1] + 1), ab[0]), - ) - rank_of = [-1] * 512 - for rank, (a, b) in enumerate(cells): - if rank < len(BC7_CONFIG): - rank_of[a * 16 + b] = rank - _BC7_STATIC_CACHE = { - "partition2": part2, - "partition3": part3, - "anchor2": BC7_ANCHOR2, - "anchor3a": BC7_ANCHOR3A, - "anchor3b": BC7_ANCHOR3B, - "config": BC7_CONFIG, - "inferred": BC7_CONFIG_INFERRED, - "rank_of": tuple(rank_of), - } - return _BC7_STATIC_CACHE - - -def _read_history_section(history, codec_key, marker_key): - """Resolve `history` (None, dict, JSON file, or directory) for one codec.""" - if history is None: - return None - if isinstance(history, dict): - if codec_key in history: - return history[codec_key] - return history if marker_key in history else None - path = os.fspath(history) - if os.path.isdir(path): - candidate = os.path.join(path, f"{codec_key}.json") - if not os.path.isfile(candidate): - return None - path = candidate - abspath = os.path.abspath(path) - st = os.stat(abspath) - cache_key = (st.st_mtime_ns, st.st_size) - cached = _FILE_CACHE.get(abspath) - if cached is not None and cached[0] == cache_key: - data = cached[1] - else: - with open(abspath, "r", encoding="utf-8-sig") as fh: - data = json.load(fh) - if not isinstance(data, dict): - raise ValueError(f"{path}: expected a JSON object") - _FILE_CACHE[abspath] = (cache_key, data) - if codec_key in data: - return data[codec_key] - return data if marker_key in data else None - - -def _iter_entries(obj, count=256): - """Yield `(index, value)` pairs from a 256-list or sparse `{index: value}` dict.""" - if obj is None: - return - if isinstance(obj, list): - if len(obj) != count: - raise ValueError(f"expected {count} entries, got {len(obj)}") - for i, v in enumerate(obj): - yield i, v - elif isinstance(obj, dict): - for k, v in obj.items(): - i = int(k) - if not 0 <= i < count: - raise ValueError(f"history entry index {i} outside 0..{count - 1}") - yield i, v - else: - raise ValueError("history table must be a 256-element list or index-keyed dict") - - -def _flatten_bc7_entry(val, expected_len): - """Flatten nested `[3][2][4]` / `[2][16]` or flat `24`/`32` BC7 entry to a tuple of ints.""" - out = [] - - def _walk(x): - if isinstance(x, (list, tuple)): - for item in x: - _walk(item) - else: - out.append(int(x)) - - _walk(val) - if len(out) != expected_len: - raise ValueError(f"expected {expected_len} integers in BC7 history entry, got {len(out)}") - return tuple(out) - - -def load_bc6h(history=None, *, with_confirmed_bits=False): - """Return `(endpoint_history, index_history, endpoint_class, index_class)`. - - With `history=None`, returns empty/unknown tables (class `0` for all 256 - entries) so self-contained BC6H chunks still decode strictly without any - external file. When `history` is a local JSON file, directory containing - `bc6h.json`, or dict, populates the BC6H initial history tables from it. - With `with_confirmed_bits=True`, append endpoint `[256][3][4]` and index - `[256][16]` leading-bit confirmation depths. Legacy documents without the - optional depth tables retain full precision for class-3 entries. - """ - sec = _read_history_section(history, "bc6h", "endpointHistory") - if sec is None: - result = (_EMPTY_BC6H_EH, _EMPTY_BC6H_IH, _EMPTY_BC6H_CLS, _EMPTY_BC6H_CLS) - return result + (_EMPTY_BC6H_EH, _EMPTY_BC6H_IH) if with_confirmed_bits else result - eh = list(_EMPTY_BC6H_EH) - ih = list(_EMPTY_BC6H_IH) - ec = list(_EMPTY_BC6H_CLS) - ic = list(_EMPTY_BC6H_CLS) - for i, channels in _iter_entries(sec.get("endpointHistory")): - if len(channels) != 3 or any(len(ch) != 4 for ch in channels): - raise ValueError(f"BC6H endpointHistory[{i}] must be 3x4 integers") - eh[i] = tuple(tuple(int(v) for v in ch) for ch in channels) - for i, pixels in _iter_entries(sec.get("indexHistory")): - if len(pixels) != 16: - raise ValueError(f"BC6H indexHistory[{i}] must have 16 integers") - ih[i] = tuple(int(v) for v in pixels) - for i, cls in _iter_entries(sec.get("endpointClass")): - ec[i] = int(cls) - for i, cls in _iter_entries(sec.get("indexClass")): - ic[i] = int(cls) - ep_cb = [tuple((16, 10, 6, 6) for _ in range(3)) if c == 3 else _EMPTY_BC6H_EH[0] for c in ec] - ix_cb = [(4,) * 16 if c == 3 else _EMPTY_BC6H_IH[0] for c in ic] - for key, target, empty, widths in ( - ("endpointConfirmedBits", ep_cb, _EMPTY_BC6H_EH, (16, 10, 6, 6)), - ("indexConfirmedBits", ix_cb, _EMPTY_BC6H_IH, (4,) * 16), - ): - if key not in sec: - continue - # In an explicit sparse depth table, omitted rows confirm no bits. - target[:] = empty - for i, row in _iter_entries(sec[key]): - if key == "endpointConfirmedBits": - if len(row) != 3 or any(len(ch) != 4 for ch in row): - raise ValueError(f"BC6H {key}[{i}] must be 3x4 integers") - value = tuple(tuple(int(v) for v in ch) for ch in row) - valid = all(0 <= v <= widths[q] for ch in value for q, v in enumerate(ch)) - else: - if len(row) != 16: - raise ValueError(f"BC6H {key}[{i}] must have 16 integers") - value = tuple(int(v) for v in row) - valid = all(0 <= v <= 4 for v in value) - if not valid: - raise ValueError(f"BC6H {key}[{i}] bit depth out of bounds") - target[i] = value - result = (tuple(eh), tuple(ih), tuple(ec), tuple(ic)) - return result + (tuple(ep_cb), tuple(ix_cb)) if with_confirmed_bits else result - - -def load_bc7(history=None): - """Return the BC7 partition, anchor, signature, and history tables. - - With `history=None`, built-in history slots have depth `0` (unknown) so - self-contained BC7 chunks decode strictly without external data while any - reference to built-in history cleanly refuses. When `history` is a local - JSON file, directory containing `bc7.json`, or dict, loads the BC7 initial - history tables from it. - """ - static = _bc7_static() - sec = _read_history_section(history, "bc7", "historyEndpoints") - if sec is None: - return { - **static, - "history_endpoints": _EMPTY_BC7_EP, - "history_endpoint_bits": _EMPTY_BC7_EP, - "history_endpoint_confirmed_bits": _EMPTY_BC7_EP, - "history_indices": _EMPTY_BC7_IX, - "history_index_bits": _EMPTY_BC7_IX, - "history_index_confirmed_bits": _EMPTY_BC7_IX, - "last_resort": frozenset(), - } - ep = list(_EMPTY_BC7_EP) - ep_b = list(_EMPTY_BC7_EP) - ep_cb = list(_EMPTY_BC7_EP) - ix = list(_EMPTY_BC7_IX) - ix_b = list(_EMPTY_BC7_IX) - ix_cb = list(_EMPTY_BC7_IX) - for i, v in _iter_entries(sec.get("historyEndpoints")): - ep[i] = _flatten_bc7_entry(v, 24) - for i, v in _iter_entries(sec.get("historyEndpointBits")): - ep_b[i] = _flatten_bc7_entry(v, 24) - for i, v in _iter_entries(sec.get("historyEndpointConfirmedBits")): - ep_cb[i] = _flatten_bc7_entry(v, 24) - for i, v in _iter_entries(sec.get("historyIndices")): - ix[i] = _flatten_bc7_entry(v, 32) - for i, v in _iter_entries(sec.get("historyIndexBits")): - ix_b[i] = _flatten_bc7_entry(v, 32) - for i, v in _iter_entries(sec.get("historyIndexConfirmedBits")): - ix_cb[i] = _flatten_bc7_entry(v, 32) - # Mid-range fill for endpoints known to 0 < d < 8 leading bits. - # Readers taking <= d bits shift the low bits away unchanged. - for i in range(256): - depth = ep_b[i] - if any(0 < d < 8 for d in depth): - row = ep[i] - ep[i] = tuple( - ((v >> (8 - d) << (8 - d)) | (1 << (7 - d))) if 0 < d < 8 else v - for v, d in zip(row, depth) - ) - last_resort = set() - for item in sec.get("historyEndpointLastResort") or (): - if len(item) == 4: - k, sub, e, c = (int(x) for x in item) - last_resort.add((k, sub * 8 + e * 4 + c)) - elif len(item) == 2: - last_resort.add((int(item[0]), int(item[1]))) - else: - raise ValueError("historyEndpointLastResort entries must have 2 or 4 integers") - return { - **static, - "history_endpoints": tuple(ep), - "history_endpoint_bits": tuple(ep_b), - "history_endpoint_confirmed_bits": tuple(ep_cb), - "history_indices": tuple(ix), - "history_index_bits": tuple(ix_b), - "history_index_confirmed_bits": tuple(ix_cb), - "last_resort": frozenset(last_resort), - } - - -_BC_HISTORY_SPEC = { - 1: ("bc1", (32, 64, 32, 32, 64, 32)), - 3: ("bc3", (256, 256, 32, 64, 32, 32, 64, 32)), - 4: ("bc4", (256, 256)), - 5: ("bc5", (256, 256, 256, 256)), -} - - -def load_bc_history(codec, history=None): - """Load optional BC1/BC3/BC4/BC5 initial history overrides from `history`. - - Returns `None` when `history` is `None` or does not contain a section for - `codec`. Otherwise returns `(confirmed, provisional, replace)` where - `confirmed` and `provisional` map `0..255` entry indices to validated - endpoint tuples and `replace` is a bool (default False: overlay onto the - built-in `bcpack_tables.py` defaults). - """ - if history is None: - return None - spec = _BC_HISTORY_SPEC.get(codec) - if spec is None: - raise ValueError(f"unsupported BC history codec: {codec}") - codec_key, mods = spec - if isinstance(history, dict): - if codec_key in history: - sec = history[codec_key] - elif history.get("codec") == codec_key: - sec = history - else: - return None - else: - path = os.fspath(history) - if os.path.isdir(path): - candidate = os.path.join(path, f"{codec_key}.json") - if not os.path.isfile(candidate): - return None - path = candidate - abspath = os.path.abspath(path) - st = os.stat(abspath) - cache_key = (st.st_mtime_ns, st.st_size) - cached = _FILE_CACHE.get(abspath) - if cached is not None and cached[0] == cache_key: - data = cached[1] - else: - with open(abspath, "r", encoding="utf-8-sig") as fh: - data = json.load(fh) - if not isinstance(data, dict): - raise ValueError(f"{path}: expected a JSON object") - _FILE_CACHE[abspath] = (cache_key, data) - if codec_key in data: - sec = data[codec_key] - elif data.get("codec") == codec_key: - sec = data - else: - return None - if not isinstance(sec, dict): - raise ValueError(f"{codec_key} history section must be a JSON object") - if "codec" in sec and sec["codec"] != codec_key: - raise ValueError(f"expected codec {codec_key!r}, got {sec['codec']!r}") - ncols = len(mods) - - def _parse_map(obj, label): - out = {} - for i, vals in _iter_entries(obj): - if not isinstance(vals, (list, tuple)) or len(vals) != ncols: - raise ValueError(f"{codec_key} {label}[{i}] must have {ncols} integers") - row = [] - for v, mod in zip(vals, mods): - iv = int(v) - if not 0 <= iv < mod: - raise ValueError(f"{codec_key} {label}[{i}] value {iv} outside 0..{mod - 1}") - row.append(iv) - out[i] = tuple(row) - return out - - confirmed = _parse_map(sec.get("confirmed"), "confirmed") - provisional = _parse_map(sec.get("provisional"), "provisional") - replace = bool(sec.get("replace", False)) - return confirmed, provisional, replace diff --git a/tools/bcpack_tool.py b/tools/bcpack_tool.py deleted file mode 100644 index d127250c4..000000000 --- a/tools/bcpack_tool.py +++ /dev/null @@ -1,271 +0,0 @@ -"""DirectStorage BCPack bitstream inspection, decoding and profiling tool. - -Provides CLI inspection, diagnostics, statistical frequency profiling and -decompression for Xbox Series BCPack streams (codecs BC1, BC3, BC4, BC5, BC6H, BC7). - -Usage: - python -I tools/bcpack_tool.py inspect --codec <1..7> --size [--json] - python -I tools/bcpack_tool.py decode --codec <1..7> --size [--provisional] - python -I tools/bcpack_tool.py profile --codec <1..7> --size -""" -from __future__ import annotations - -import argparse -import json -import os -import sys - -sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) -import bcpack -from report_paths import same_report_path - - -def inspect_stream(raw: bytes, codec: int, out_size: int) -> dict: - """Analyze stream structure, compression ratio and per-lane statistics.""" - if codec not in bcpack.ALL_CODECS: - raise ValueError(f"unsupported BCPack codec id: {codec}") - - block_size = bcpack.BLOCK_BYTES[codec] - if out_size <= 0 or out_size % block_size != 0: - raise ValueError( - f"output size {out_size} is not a valid multiple of {bcpack.CODEC_NAMES[codec]} block size ({block_size})" - ) - - nblocks = out_size // block_size - lanes, used = bcpack.decode_lanes(raw, codec, out_size) - - lane_widths = bcpack.LANE_WIDTHS[codec] - lane_reports = [] - total_symbols = 0 - - for idx, lane in enumerate(lanes): - count = len(lane) - total_symbols += count - w = lane_widths[idx] - zeros = lane.count(0) - min_val = min(lane) if count else 0 - max_val = max(lane) if count else 0 - avg_val = (sum(lane) / count) if count else 0.0 - - lane_reports.append({ - "lane": idx, - "bit_width": w, - "symbols": count, - "zeros": zeros, - "zero_percent": round(100.0 * zeros / count, 2) if count else 0.0, - "min": min_val, - "max": max_val, - "avg": round(avg_val, 2), - }) - - trailing_bytes = len(raw) - used - ratio = round(len(raw) / out_size, 4) if out_size else 0.0 - - return { - "codec": bcpack.CODEC_NAMES[codec], - "codec_id": codec, - "compressed_bytes": len(raw), - "bytes_used": used, - "trailing_zeros": trailing_bytes, - "uncompressed_bytes": out_size, - "blocks": nblocks, - "compression_ratio": ratio, - "total_symbols": total_symbols, - "lanes": lane_reports, - } - - -def profile_stream(raw: bytes, codec: int, out_size: int) -> dict: - """Generate symbol frequency distribution profile across all lanes.""" - info = inspect_stream(raw, codec, out_size) - lanes, _ = bcpack.decode_lanes(raw, codec, out_size) - - histograms = [] - for idx, lane in enumerate(lanes): - counts: dict[int, int] = {} - for sym in lane: - counts[sym] = counts.get(sym, 0) + 1 - sorted_top = sorted(counts.items(), key=lambda kv: (-kv[1], kv[0]))[:8] - histograms.append({ - "lane": idx, - "unique_symbols": len(counts), - "top_symbols": [{"sym": s, "count": c} for s, c in sorted_top], - }) - - info["histograms"] = histograms - return info - - -def decode_file( - in_path: str, - out_path: str, - codec: int, - out_size: int, - allow_provisional: bool = False, - history: str | None = None, -) -> int: - """Decode compressed file and write decompressed blocks to disk.""" - if same_report_path(in_path, out_path): - raise ValueError( - f"output path '{out_path}' names the compressed input '{in_path}'; " - f"refusing to overwrite it" - ) - - with open(in_path, "rb") as f: - raw = f.read() - - try: - data, prov = bcpack.decode_with_info( - raw, codec, out_size, allow_provisional=allow_provisional, history=history - ) - except bcpack.BcpackError: - raise # stream failures are already attributed to the stream, never to --history - except ValueError as e: - # json.JSONDecodeError from a --history file carries no filename; attribute it, - # but do not double-prefix messages that already name the history path. - if history is not None and os.path.basename(str(history)) not in str(e): - raise ValueError(f"{history}: {e}") from e - raise - - parent = os.path.dirname(os.path.abspath(out_path)) - if parent: - os.makedirs(parent, exist_ok=True) - - with open(out_path, "wb") as f: - f.write(data) - - return len(data) - - -def main(argv: list[str] | None = None) -> int: - parser = argparse.ArgumentParser( - description="DirectStorage BCPack bitstream inspection, decoding and profiling tool." - ) - sub = parser.add_subparsers(dest="command", required=True) - - # inspect - p_insp = sub.add_parser("inspect", help="Inspect BCPack stream structure and lane statistics") - p_insp.add_argument("file", help="Path to raw BCPack compressed file") - p_insp.add_argument( - "--codec", - type=int, - required=True, - choices=sorted(bcpack.ALL_CODECS), - help="BCPack codec ID (1=BC1, 3=BC3, 4=BC4, 5=BC5, 6=BC6H, 7=BC7)", - ) - p_insp.add_argument( - "--size", - type=int, - required=True, - help="Expected uncompressed size in bytes", - ) - p_insp.add_argument( - "--json", - action="store_true", - help="Print machine-readable JSON output", - ) - - # profile - p_prof = sub.add_parser("profile", help="Generate detailed symbol frequency distribution") - p_prof.add_argument("file", help="Path to raw BCPack compressed file") - p_prof.add_argument( - "--codec", - type=int, - required=True, - choices=sorted(bcpack.ALL_CODECS), - help="BCPack codec ID", - ) - p_prof.add_argument( - "--size", - type=int, - required=True, - help="Expected uncompressed size in bytes", - ) - - # decode - p_dec = sub.add_parser("decode", help="Decompress BCPack file to raw BCn blocks") - p_dec.add_argument("in_file", help="Path to input BCPack compressed file") - p_dec.add_argument("out_file", help="Path to output decompressed file") - p_dec.add_argument( - "--codec", - type=int, - required=True, - choices=sorted(bcpack.ALL_CODECS), - help="BCPack codec ID", - ) - p_dec.add_argument( - "--size", - type=int, - required=True, - help="Expected uncompressed size in bytes", - ) - p_dec.add_argument( - "--provisional", - action="store_true", - help="Allow provisional history and signatures", - ) - p_dec.add_argument( - "--history", - type=str, - default=None, - help="Path to optional BC6H/BC7 history JSON or directory", - ) - - args = parser.parse_args(argv) - - # CLI-level guard: a missing/unreadable input or history file (OSError), a stream that fails - # structural or rANS validation (bcpack.BcpackError, a ValueError), or a malformed --history - # JSON (ValueError) must be one named line on stderr with exit status 2, not a traceback. - # bcpack.py's library-level behavior is unchanged. - src = args.in_file if args.command == "decode" else args.file - try: - return _run(args) - except (ValueError, OSError) as e: - print(f"ERROR: {src}: {e}", file=sys.stderr) - return 2 - - -def _run(args: argparse.Namespace) -> int: - if args.command == "inspect": - with open(args.file, "rb") as f: - raw = f.read() - info = inspect_stream(raw, args.codec, args.size) - if args.json: - print(json.dumps(info, indent=2)) - else: - print( - f"BCPack {info['codec']} stream: {info['compressed_bytes']} bytes -> " - f"{info['uncompressed_bytes']} bytes ({info['blocks']} blocks, ratio {info['compression_ratio']:.3f})" - ) - print(f"Lanes ({len(info['lanes'])} active):") - for l in info['lanes']: - print( - f" lane {l['lane']:2d} (w={l['bit_width']:2d}b): {l['symbols']} syms, " - f"{l['zeros']} zeros ({l['zero_percent']}%), min {l['min']}, max {l['max']}, avg {l['avg']}" - ) - return 0 - - elif args.command == "profile": - with open(args.file, "rb") as f: - raw = f.read() - prof = profile_stream(raw, args.codec, args.size) - print(json.dumps(prof, indent=2)) - return 0 - - elif args.command == "decode": - written = decode_file( - args.in_file, - args.out_file, - args.codec, - args.size, - allow_provisional=args.provisional, - history=args.history, - ) - print(f"Successfully decoded {written} bytes to {args.out_file}") - return 0 - - return 1 - -if __name__ == "__main__": - sys.stdout.reconfigure(errors="replace") - sys.exit(main()) diff --git a/tools/bink_index.py b/tools/bink_index.py deleted file mode 100644 index db20ed5ec..000000000 --- a/tools/bink_index.py +++ /dev/null @@ -1,493 +0,0 @@ -"""Index Bink 2 streams in an RPF archive or a directory without extracting them. - -A Bink 2 stream starts with ``KB2`` and a lowercase revision letter. The first -44 (0x2C) bytes are the fixed header; audio-track metadata and the frame index -follow it, and their size depends on the revision and the track count. This -tool reads only the fixed header plus the audio descriptors, so a malformed -stream cannot make it read past the stored size. - -Usage: - python -I bink_index.py [--out index.csv|.json] - [--format csv|json] [--probe] - -With ``--probe`` each stream is written to a temporary file and passed to -``ffprobe``; the extra columns say only whether that ffprobe build can decode -the stream. A missing ffprobe leaves the base columns unchanged. -A single named file that is neither a Bink 2 stream nor an RPF archive is an -error (exit 2), not an empty index; a directory scan still reports 0 streams -when nothing matches. - -A single named file has to start with ``KB2`` or an RPF header; anything else -(an empty file, a text file, a carved chunk) cannot hold a stream and is one -error line with exit 2, which is how a wrong path shows up. - -In an RPF9 archive the last ``u32 +12`` bytes of the file are a block of their own -(``docs/rpf.md``), so when the gap after the last stream reaches EOF and is at least -that long, those bytes are counted as ``rpf_trailer`` and only the rest of the gap is -split into zero padding and unread bytes. -Usage: `python -I tools/bink_index.py --help` lists the options. -""" -import argparse -import csv -import json -import mmap -import os -import re -import shutil -import stat -import struct -import subprocess -import sys -import tempfile - -sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) -from file_mode import published_mode # noqa: E402 -from replace_retry import replace as replace_retry # noqa: E402 - -SIG = re.compile(rb"KB2[a-z]") -HDR = 0x2C -MAX_FRAMES = 1_000_000 -MAX_WIDTH = 7680 -MAX_HEIGHT = 4800 -MAX_AUDIO_TRACKS = 32 -# Bink Audio flags in the per-track descriptor. -AUD_16BITS = 0x4000 -AUD_STEREO = 0x2000 -AUD_USEDCT = 0x1000 -AUD_KNOWN = AUD_16BITS | AUD_STEREO | AUD_USEDCT - -BASE_FIELDS = [ - "source", "offset", "size", "revision", "frames", "width", "height", - "fps", "fps_num", "fps_den", "duration_s", "audio_tracks", - "audio_rates", "audio_flags", "audio_codecs", "audio_channels", -] -PROBE_FIELDS = ["decodes", "codec", "probe_duration_s"] - - -def _audio_layout(data, base, count, end): - """Decode one candidate audio layout, or return None if it is not plausible.""" - need = base + 12 * count - if need > end: - return None - rates, flags = [], [] - for i in range(count): - rate, flag = struct.unpack_from(" len(data): - return None - tag = bytes(data[offset:offset + 4]) - if tag[:3] != b"KB2" or not 0x61 <= tag[3] <= 0x7A: - return None - (size8, frames, largest, frames2, width, height, - fps_num, fps_den, _extra, audio) = struct.unpack_from("<10I", data, offset + 4) - stored = size8 + 8 - if size8 < 0x24 or stored < HDR + 4 or offset + stored > len(data): - return None - if not 1 <= frames <= MAX_FRAMES or frames2 != frames: - return None - if largest > size8: - return None - if not (16 <= width <= MAX_WIDTH and 16 <= height <= MAX_HEIGHT): - return None - if fps_den == 0 or not fps_den <= fps_num <= 240 * fps_den: - return None - fps = fps_num / fps_den - if audio > MAX_AUDIO_TRACKS: - return None - - revision = chr(tag[3]) - rates, flags = [], [] - if audio: - # Revisions i/j/k/n have one opaque word at 0x2C before the audio - # descriptors; older revisions start them at 0x2C. Try the expected - # layout first, then the other, and accept only plausible descriptors. - bases = [offset + 0x30, offset + 0x2C] if revision in "ijkn" else [offset + 0x2C] - for base in bases: - got = _audio_layout(data, base, audio, offset + stored) - if got: - rates, flags = got - break - - codecs = ["binkaudio_dct" if f & AUD_USEDCT else "binkaudio_rdft" for f in flags] - channels = [2 if f & AUD_STEREO else 1 for f in flags] - return { - "source": None, - "offset": offset, - "size": stored, - "revision": revision, - "frames": frames, - "width": width, - "height": height, - "fps": round(fps, 3), - "fps_num": fps_num, - "fps_den": fps_den, - "duration_s": round(frames * fps_den / fps_num, 3), - "audio_tracks": audio, - "audio_rates": rates, - "audio_flags": [f"0x{f:04x}" for f in flags], - "audio_codecs": codecs, - "audio_channels": channels, - } - - -def _gap(data, start, end): - """Split an unread range into all-zero padding and other bytes.""" - if end <= start: - return 0, 0 - for pos in range(start, end, 1 << 20): - chunk = data[pos:min(pos + (1 << 20), end)] - if chunk.count(0) != len(chunk): - return 0, end - start - return end - start, 0 - - -def scan_file(path, source): - """Index every Bink 2 stream in one file. Returns (rows, stats).""" - rows = [] - size = os.path.getsize(path) - if size == 0: - return rows, {"files_scanned": 1, "streams": 0, "bytes": 0, "zero_padding": 0, - "rpf_trailer": 0, "unread_bytes": 0, "span": 0} - with open(path, "rb") as fh: - with mmap.mmap(fh.fileno(), 0, access=mmap.ACCESS_READ) as data: - start = trailer_size = 0 - if size >= 16 and bytes(data[1:4]) == b"FPR": - hint, trailer_size = struct.unpack_from("= 16 and header[1:4] == b"FPR" - - -def same_output_path(first, second): - """True when writing ``second`` would truncate ``first`` (same file, path or hard link).""" - if os.path.normcase(os.path.realpath(first)) == os.path.normcase(os.path.realpath(second)): - return True - try: - return os.path.samefile(first, second) - except OSError: - return False - - -def target_problem(path): - """None when a single named file is something this tool indexes, else a one-line reason. - - The scan only searches the bytes for `KB2` headers, so a wrong path or a mislabelled file came back as a - successful scan of 0 streams. An RPF archive may hold no stream and is a real answer. - """ - with open(path, "rb") as fh: - head = fh.read(4) - if not head: - return "empty file" - if head[1:4] != b"FPR" and not SIG.match(head): - return "not a Bink 2 stream (KB2) or an RPF archive" - return None - - -def main(argv=None): - ap = argparse.ArgumentParser(description=__doc__.splitlines()[0]) - ap.add_argument("target", help="an .rpf archive, a .bk2 file, or a directory") - ap.add_argument("--out", help="index.csv or index.json; default is stdout") - ap.add_argument("--format", choices=["csv", "json"], help="inferred from --out if omitted") - ap.add_argument("--probe", action="store_true", help="run ffprobe on each stream") - a = ap.parse_args(argv) - if a.out and same_output_path(a.target, a.out): - ap.error("--out must not overwrite the source") - if a.out and os.path.isdir(a.out): - ap.error(f"--out is a folder, not a report file: {a.out}") - if a.out and os.path.isdir(a.target): - manifest = os.path.join(a.target, "index.json") - # Reserved even before the carve writes it: other tools read /index.json as the carve manifest. - if same_output_path(a.out, manifest): - ap.error(f"--out would overwrite the carve manifest: {a.out}") - if os.path.isfile(a.out): - for root, _dirs, names in os.walk(a.target): - for name in names: - if name.lower().endswith((".json", ".csv")): - continue - if same_output_path(os.path.join(root, name), a.out): - ap.error(f"--out would overwrite an input file: {a.out}") - if not os.path.exists(a.target): - print(f"bink_index: error: {a.target}: no such file or directory", file=sys.stderr) - return 2 - if not os.path.isdir(a.target): - try: - problem = target_problem(a.target) - except OSError as error: - print(f"bink_index: error: cannot read {a.target}: {error.strerror or error}", file=sys.stderr) - return 2 - if problem: - print(f"bink_index: error: {a.target}: {problem}", file=sys.stderr) - return 2 - - skip_report = None - if a.out and os.path.isfile(a.out): - skip_report = a.out - try: - rows, summary = scan_target(a.target, skip_report) - except OSError as error: - path = error.filename or a.target - print(f"bink_index: error: cannot read {path}: {error.strerror or error}", file=sys.stderr) - return 2 - if not rows and not os.path.isdir(a.target) and not is_rpf_archive(a.target): - # A named file with no Bink 2 stream and no RPF header is a wrong path or - # format, not an empty index; a directory scan still reports 0 streams. - print(f"bink_index: error: {a.target}: not a Bink 2 stream or an RPF archive", file=sys.stderr) - return 2 - probe = False - if a.probe: - ffprobe = shutil.which("ffprobe") - if ffprobe: - probe = True - for row in rows: - probe_row(row, ffprobe) - else: - print("ffprobe not found; --probe skipped", file=sys.stderr) - - fmt = a.format or ("json" if a.out and a.out.lower().endswith(".json") else "csv") - if a.out: - try: - if fmt == "json": - write_json(a.out, a.target, rows, summary, probe) - else: - write_csv(a.out, rows, probe) - except OSError as error: - print(f"bink_index: error: cannot write {a.out}: {error}", file=sys.stderr) - return 2 - print(f"{len(rows)} Bink 2 streams, {summary['bytes']} bytes, " - f"{summary['unread_bytes']} unread, {summary['zero_padding']} zero padding, " - f"{summary['rpf_trailer']} RPF trailer") - else: - if fmt == "json": - fields = BASE_FIELDS + (PROBE_FIELDS if probe else []) - print(json.dumps({"target": a.target, "summary": summary, - "streams": [_flat(r, fields) for r in rows]}, indent=1)) - else: - fields = BASE_FIELDS + (PROBE_FIELDS if probe else []) - # stdout is a text stream that already turns "\n" into the platform's line end; - # csv's default "\r\n" would come out as "\r\r\n" on Windows - writer = csv.DictWriter(sys.stdout, fieldnames=fields, lineterminator="\n") - writer.writeheader() - for row in rows: - writer.writerow(_flat(row, fields)) - print(f"{len(rows)} Bink 2 streams, {summary['bytes']} bytes, " - f"{summary['unread_bytes']} unread, {summary['zero_padding']} zero padding, " - f"{summary['rpf_trailer']} RPF trailer", - file=sys.stderr) - return 0 - - -if __name__ == "__main__": - try: # a redirected stdout is strict ANSI code page under -I; write '?' for what it cannot encode - sys.stdout.reconfigure(errors="replace") - except (AttributeError, ValueError, OSError): - pass - sys.exit(main()) diff --git a/tools/bink_names.py b/tools/bink_names.py deleted file mode 100644 index 9d1827978..000000000 --- a/tools/bink_names.py +++ /dev/null @@ -1,499 +0,0 @@ -"""Name the Bink 2 streams of an RPF archive from the game's own mount lists. - -The RPF9 table of contents is encrypted, so ``bink_index.py`` can only report offsets. The names are still in the -package: every pack registers its videos in a ``CDataFileMgr__ContentChangeSetDef`` mount list (``core_binks``, -``story000_binks``, ...) as ``$(common)/movies//.bk2``. The archive stores the -streams of a pack in the order of that list once it is sorted by lowercase path (folder, then file name without -the extension, in plain byte order). A list can name more files than its archive holds, because some entries live -in other packs, so the list and the streams are aligned rather than zipped. - -The alignment is a monotone dynamic programme over (list entry, stream in offset order) that may skip list -entries, never streams. It scores: - -* name hints against the header: ``_720``/``_1080``/``_1440``/``_4k`` against the height, ``snapmatic/`` against a - portrait frame, ``tv/sprt/`` against 1280x720; -* siblings: consecutive matches of one family (the name without trailing numbers or side/size words) should share - width, height and frame count, and unrelated neighbours get a small bonus when they do; -* optional pins: a CSV of ``offset,path`` from someone who watched the stream (``path`` may list alternatives - separated by ``|``). - -Each name gets a confidence: - -``verified`` a pin names exactly this path; -``anchored`` a family neighbour agrees on the header, a name hint matched, or a pin allows this path; -``bracketed`` between the nearest anchored matches (or the ends) the number of names equals the number of - streams, so no skipped entry can hide there; -``positional`` only the order supports it. - -Usage: - python -I bink_names.py --mount [...] - [--pins pins.csv] [--max-skip N] [--out names.csv|.json] - -The source is read with ``bink_index.py`` (an archive or directory is scanned; a CSV or JSON written by -``bink_index.py --out`` is reused). ``--mount`` takes list files, an archive (``common.rpf``), an ``rpf9_carve.py`` -directory, or any directory of files; only payloads that mention ``$(common)/movies/`` are used. A list longer than -one zlib stream is rebuilt whole by ``gamedata_index.py``. The output names game files: it is a local work product and must not be -committed or attached to an issue. The tests use synthetic headers and lists only. -Usage: `python -I tools/bink_names.py --help` lists the options. -""" -import argparse -import csv -import json -import os -import re -import sys -import tempfile - -ROOT = os.path.dirname(os.path.abspath(__file__)) -if ROOT not in sys.path: - sys.path.insert(0, ROOT) -import bink_index # noqa: E402 -import gamedata_index # noqa: E402 -from file_mode import published_mode # noqa: E402 -from replace_retry import replace as replace_retry # noqa: E402 -import gamedata_xml # noqa: E402 - -LIST_ENTRY = re.compile(r"\s*\$\(common\)/movies/([^<]+?\.bk2)\s*", re.I) -FAMILY_TAIL = re.compile(r"(_?\d+|_?(4k|left|right|top|topleft|topright|side|high|low|medium|light|dark|close|far))+$", - re.I) -LIST_MARKER = b"$(common)/movies/" -MAX_LIST_BYTES = 16 << 20 -HEIGHT_HINTS = (("_720", 720), ("_1080", 1080), ("_1440", 1440), ("_4k", 2160)) -CONFIDENCES = ("verified", "anchored", "bracketed", "positional") -FIELDS = ["source", "offset", "size", "path", "confidence", "width", "height", "frames"] -REPORT_FIELDS = ["source", "offset", "size", "width", "height", "frames"] - -PIN_SCORE = 50.0 -HINT_SCORE = 3.0 -SNAPMATIC_SCORE = 2.0 -TV_SCORE = 1.0 -FAMILY_SCORE = 2.0 -NEIGHBOUR_SCORE = 0.3 -SKIP_COST = 0.6 -MAX_SKIP = 30 - - -def sort_key(path): - """Archive order: folder, then file name without the extension, both lowercase and compared as bytes.""" - folder, _, name = path.lower().rpartition("/") - return folder.encode(), name.rsplit(".", 1)[0].encode() - - -def _archive_documents(archive): - """XML payloads of an archive, streams joined by gamedata_index (nothing written to disk).""" - source = gamedata_index.ArchiveSource(archive) - try: - by_offset = {row["off"]: k for k, row in enumerate(source.rows)} - for row in gamedata_index.build_rows(source.rows, source): - if row["type"] == "xml": - start = by_offset[row["offset"]] - yield b"".join(source.read(source.rows[k]) for k in range(start, start + row["chunks"])) - finally: - source.close() - - -def mount_documents(paths): - """Byte payloads that may hold mount lists. - - A carve directory (``index.json`` from rpf9_carve.py) and an ``.rpf`` are read as whole XML payloads, so a list - split over several zlib streams stays in one piece. Any other directory is searched file by file. - """ - def scan_failed(error): - raise error - - for path in paths: - if os.path.isdir(path) and os.path.isfile(os.path.join(path, "index.json")): - for doc in gamedata_xml.carve_documents(path): - yield doc["data"] - elif os.path.isfile(path) and path.lower().endswith(".rpf"): - yield from _archive_documents(path) - elif os.path.isdir(path): - for root, _dirs, files in os.walk(path, onerror=scan_failed): - for name in sorted(files): - full = os.path.join(root, name) - if os.path.getsize(full) <= MAX_LIST_BYTES: - with open(full, "rb") as fh: - yield fh.read() - else: - with open(path, "rb") as fh: - yield fh.read() - - -def read_mount_lists(paths): - """Every distinct movie path the lists mention, in archive order.""" - seen, names = set(), [] - for data in mount_documents(paths): - if LIST_MARKER not in data.lower(): - continue - text = data.decode("utf-8", errors="replace") - for name in LIST_ENTRY.findall(text): - name = name.strip().replace("\\", "/") - if name.lower() not in seen: - seen.add(name.lower()) - names.append(name) - return sorted(names, key=sort_key) - - -def _int(value): - if isinstance(value, bool) or not isinstance(value, (int, str)): - raise TypeError(f"expected an integer, got {type(value).__name__}") - return int(value, 0) if isinstance(value, str) else value - - -def load_streams(source, skip_report=None): - """Stream rows (source, offset, size, width, height, frames) in archive order.""" - lower = source.lower() - if os.path.isfile(source) and lower.endswith(".json"): - with open(source, encoding="utf-8") as fh: - doc = json.load(fh) - if not isinstance(doc, dict) or not isinstance(doc.get("streams"), list): - raise ValueError("expected a JSON object with a 'streams' list") - rows = doc["streams"] - label, start = "stream {i}", 1 - elif os.path.isfile(source) and lower.endswith(".csv"): - with open(source, encoding="utf-8", newline="") as fh: - reader = csv.DictReader(fh) - header = reader.fieldnames or [] - missing = [f for f in REPORT_FIELDS if f not in header] - if missing: - raise ValueError(f"CSV header is missing required fields: {', '.join(missing)}") - rows = list(reader) - label, start = "row {i}", 2 - else: - rows, _summary = bink_index.scan_target(source, skip_report=skip_report) - label, start = "stream {i}", 1 - out = [] - for j, row in enumerate(rows): - try: - if not isinstance(row, dict): - raise TypeError("row is not an object") - offset = _int(row["offset"]) - size = _int(row["size"]) - width = _int(row["width"]) - height = _int(row["height"]) - frames = _int(row["frames"]) - if offset < 0 or size <= 0 or width <= 0 or height <= 0 or frames <= 0: - raise ValueError("negative offset or non-positive stream field") - out.append({"source": row["source"], "offset": offset, "size": size, - "width": width, "height": height, "frames": frames}) - except (KeyError, ValueError, TypeError, OverflowError) as error: - raise ValueError(f"{label.format(i=start + j)} is missing or unusable: {error}") from None - if not isinstance(out[-1]["source"], str): - raise ValueError(f"{label.format(i=start + j)} has a non-string source") - out[-1]["source"] = out[-1]["source"].replace("\\", "/") # an older Windows index wrote "\" - # A directory of carved files sorts by file name; carves name files by archive offset. - out.sort(key=lambda r: (r["source"], r["offset"])) - return out - - -def _normalize_pin_path(raw): - path = raw.strip().replace("\\", "/").lower() - if path.startswith("$(common)/movies/"): - path = path[len("$(common)/movies/"):] - return path - - -def load_pins(path): - """{(source or "", offset): set of lowercase paths} from a CSV with offset,path[,source].""" - pins = {} - if not path: - return pins - with open(path, encoding="utf-8", newline="") as fh: - reader = csv.DictReader(fh) - header = reader.fieldnames or [] - missing = [f for f in ("offset", "path") if f not in header] - if missing: - raise ValueError(f"CSV header is missing required fields: {', '.join(missing)}") - for j, row in enumerate(reader, start=2): - try: - offset = _int(row["offset"]) - if offset < 0: - raise ValueError("offset must be non-negative") - key = ((row.get("source") or "").strip().replace("\\", "/"), offset) # pins from before "/" too - raw_path = row["path"] - if not isinstance(raw_path, str): - raise TypeError("path is missing") - parsed = [item for item in (_normalize_pin_path(p) for p in raw_path.split("|")) if item] - if not parsed: - raise ValueError("empty path") - except (KeyError, ValueError, TypeError, OverflowError) as error: - raise ValueError(f"row {j} is missing or unusable: {error}") from None - pins.setdefault(key, set()).update(parsed) - return pins - - -def family(name): - return FAMILY_TAIL.sub("", name.rsplit(".", 1)[0].lower()) - - -def _shape(stream): - return stream["width"], stream["height"], stream["frames"] - - -class Scorer: - def __init__(self, pins): - self.pins = pins - self.pinned = {next(iter(p)) for p in pins.values() if len(p) == 1} - - def pin(self, stream): - return self.pins.get((stream["source"], stream["offset"]), self.pins.get(("", stream["offset"]))) - - def unary(self, name, stream): - n = name.lower() - score = 0.0 - pin = self.pin(stream) - if pin is not None: - score += PIN_SCORE if n in pin else -PIN_SCORE - elif n in self.pinned: - score -= PIN_SCORE - for tag, height in HEIGHT_HINTS: - if tag in n: - score += HINT_SCORE if stream["height"] == height else -HINT_SCORE - if n.startswith("snapmatic/"): - score += SNAPMATIC_SCORE if stream["height"] > stream["width"] else -SNAPMATIC_SCORE - if n.startswith("tv/sprt/"): - score += TV_SCORE if (stream["width"], stream["height"]) == (1280, 720) else -TV_SCORE - return score - - -def pair(name_a, stream_a, name_b, stream_b): - same = _shape(stream_a) == _shape(stream_b) - if family(name_a) == family(name_b): - return FAMILY_SCORE if same else -FAMILY_SCORE - return NEIGHBOUR_SCORE if same else 0.0 - - -def align(names, streams, scorer, skip_cost=SKIP_COST, max_skip=MAX_SKIP): - """Best monotone assignment of one list entry per stream: [(name index, stream index)].""" - n_names, n_streams = len(names), len(streams) - if n_streams == 0: - return [] - if n_names < n_streams: - raise ValueError(f"the lists name {n_names} movies but the source has {n_streams} streams") - slack = n_names - n_streams # entries that can be skipped in total - neg = float("-inf") - score = [dict() for _ in range(n_streams)] - back = [dict() for _ in range(n_streams)] - for i in range(min(slack, max_skip) + 1): - score[0][i] = scorer.unary(names[i], streams[0]) - skip_cost * i - for j in range(1, n_streams): - prev = score[j - 1] - for i in range(j, j + slack + 1): - best, arg = neg, None - for p in range(max(j - 1, i - 1 - max_skip), i): - if p not in prev: - continue - v = prev[p] - skip_cost * (i - p - 1) + pair(names[p], streams[j - 1], names[i], streams[j]) - if v > best: - best, arg = v, p - if arg is not None: - score[j][i] = best + scorer.unary(names[i], streams[j]) - back[j][i] = arg - last = {i: value for i, value in score[-1].items() if n_names - 1 - i <= max_skip} - if not last: - raise ValueError("no alignment within --max-skip; the lists do not match this source") - i = max(last, key=lambda k: last[k] - skip_cost * (n_names - 1 - k)) - path = [] - for j in range(n_streams - 1, -1, -1): - path.append((i, j)) - i = back[j].get(i) - return path[::-1] - - -def classify(names, streams, path, scorer): - """Confidence per aligned pair, in path order.""" - unaries = [scorer.unary(names[i], streams[j]) for i, j in path] - anchored = [] - for k, (i, j) in enumerate(path): - neighbours = [(k + d, *path[k + d]) for d in (-1, 1) if 0 <= k + d < len(path)] - fam = any(unaries[k2] >= 0 and family(names[i2]) == family(names[i]) and _shape(streams[j2]) == _shape(streams[j]) - for k2, i2, j2 in neighbours) - anchored.append(unaries[k] > 0 or (fam and unaries[k] >= 0)) - out = [] - for k, (i, j) in enumerate(path): - pin = scorer.pin(streams[j]) or set() - name = names[i].lower() - if pin == {name}: - out.append("verified") - elif name in pin or anchored[k]: - out.append("anchored") - elif unaries[k] < 0: - out.append("positional") - else: - a = max((x for x in range(k) if anchored[x]), default=None) - b = min((x for x in range(k + 1, len(path)) if anchored[x]), default=None) - ia, ja = path[a] if a is not None else (-1, -1) - ib, jb = path[b] if b is not None else (len(names), len(streams)) - out.append("bracketed" if ib - ia == jb - ja else "positional") - return out - - -def name_streams(names, streams, pins=None, max_skip=MAX_SKIP): - """Rows (one per stream) and the list entries that matched no stream.""" - scorer = Scorer(pins or {}) - path = align(names, streams, scorer, max_skip=max_skip) - conf = classify(names, streams, path, scorer) - rows = [] - for (i, j), c in zip(path, conf): - s = streams[j] - rows.append({"source": s["source"], "offset": s["offset"], "size": s["size"], "path": names[i], - "confidence": c, "width": s["width"], "height": s["height"], "frames": s["frames"]}) - used = {i for i, _ in path} - unmatched = [n for k, n in enumerate(names) if k not in used] - return rows, unmatched - - -def write(out, rows, unmatched, summary): - """Publish a complete report, or leave the previous file intact on replace failure.""" - destination = os.path.abspath(out) - parent = os.path.dirname(destination) or "." - if parent: - os.makedirs(parent, exist_ok=True) - try: - mode = os.stat(destination).st_mode - except FileNotFoundError: - mode = None - except OSError: - # Non-regular destinations (pipes/devices) keep a direct write. - _write_report_body(destination, rows, unmatched, summary) - return - if mode is not None: - # Retain the direct writer's permission check without truncating the report. - os.close(os.open(destination, os.O_WRONLY)) - - staged = tempfile.NamedTemporaryFile( - mode="w", encoding="utf-8", newline="\n", delete=False, - dir=parent, prefix=".bink_names-", suffix=".tmp", - ) - try: - with staged: - _write_report_body(staged, rows, unmatched, summary, json_out=out.lower().endswith(".json")) - if os.name != "nt": - os.chmod(staged.name, published_mode(destination)) - replace_retry(staged.name, destination) - finally: - try: - os.unlink(staged.name) - except FileNotFoundError: - pass - - -def _write_report_body(fh_or_path, rows, unmatched, summary, json_out=None): - if isinstance(fh_or_path, str): - path = fh_or_path - if json_out is None: - json_out = path.lower().endswith(".json") - if json_out: - with open(path, "w", encoding="utf-8", newline="\n") as fh: - json.dump({"summary": summary, "streams": rows, "unmatched_list_entries": unmatched}, fh, indent=1) - else: - with open(path, "w", encoding="utf-8", newline="") as fh: - w = csv.DictWriter(fh, fieldnames=FIELDS, lineterminator="\n") - w.writeheader() - w.writerows(rows) - return - fh = fh_or_path - if json_out: - json.dump({"summary": summary, "streams": rows, "unmatched_list_entries": unmatched}, fh, indent=1) - else: - w = csv.DictWriter(fh, fieldnames=FIELDS, lineterminator="\n") - w.writeheader() - w.writerows(rows) - - -def main(argv=None): - ap = argparse.ArgumentParser(description=__doc__.splitlines()[0]) - ap.add_argument("source", help="an .rpf archive, a directory, or a bink_index.py CSV/JSON") - ap.add_argument("--mount", action="append", required=True, - help="a mount-list XML, an archive or carve directory holding the lists, or a directory to " - "search (repeatable)") - ap.add_argument("--pins", help="CSV with offset,path[,source] of streams identified by viewing them") - ap.add_argument("--max-skip", type=int, default=MAX_SKIP, - help="most list entries skipped before, between or after stream matches " - "(an empty source leaves all entries unmatched)") - ap.add_argument("--out", help="names.csv or names.json; index.json in a source or mount directory is reserved " - "for the carve manifest (default: a summary only)") - a = ap.parse_args(argv) - if a.max_skip < 0: - ap.error("--max-skip must be 0 or more") - inputs = [a.source, *a.mount] + ([a.pins] if a.pins else []) - for path in inputs: - if not os.path.exists(path): - print(f"bink_names: error: {path}: no such file or directory", file=sys.stderr) - return 2 - if a.out and any(bink_index.same_output_path(p, a.out) for p in inputs): - ap.error("--out must not overwrite an input") - if a.out and os.path.isdir(a.out): - ap.error(f"--out is a folder, not a report file: {a.out}") - if a.out: - def unlistable(error): - # os.walk skips a folder it cannot list unless onerror stops it. An --out inside that folder could then - # be an input this check never saw, so refuse it. Any other unlistable folder is left to the scan, - # which stops on it with exit 1 whether or not the report already exists. - locked = error.filename or folder - out_key = os.path.normcase(os.path.realpath(a.out)) - locked_key = os.path.normcase(os.path.realpath(locked)) - try: - inside = os.path.commonpath([out_key, locked_key]) == locked_key - except ValueError: # different drives on Windows - inside = False - if inside: - ap.error(f"--out cannot be checked against the inputs: cannot list {locked}: " - f"{error.strerror or error}") - - for folder in [p for p in [a.source, *a.mount] if os.path.isdir(p)]: - manifest = os.path.join(folder, "index.json") - if bink_index.same_output_path(a.out, manifest): - ap.error(f"--out is reserved for the carve manifest: {a.out}") - if os.path.isfile(a.out): - for root, _dirs, names in os.walk(folder, onerror=unlistable): - for name in names: - if name.lower().endswith((".json", ".csv")): - continue - if bink_index.same_output_path(os.path.join(root, name), a.out): - ap.error(f"--out would overwrite an input file: {a.out}") - - try: - names = read_mount_lists(a.mount) - except OSError as error: - print(f"bink_names: error: {error.filename or error}: {error.strerror or error}", file=sys.stderr) - return 1 - except ValueError as error: - print(f"bink_names: error: {error}", file=sys.stderr) - return 1 - try: - streams = load_streams(a.source, skip_report=a.out if a.out and os.path.isfile(a.out) else None) - except (OSError, csv.Error, ValueError) as error: - print(f"bink_names: error: {a.source}: {error}", file=sys.stderr) - return 1 - try: - pins = load_pins(a.pins) - except (OSError, csv.Error, ValueError) as error: - print(f"bink_names: error: {a.pins}: {error}", file=sys.stderr) - return 1 - try: - rows, unmatched = name_streams(names, streams, pins, a.max_skip) - except ValueError as error: - print(f"bink_names: error: {error}", file=sys.stderr) - return 1 - counts = {c: sum(r["confidence"] == c for r in rows) for c in CONFIDENCES} - summary = {"list_entries": len(names), "streams": len(streams), "named": len(rows), - "unmatched_list_entries": len(unmatched), **counts} - if a.out: - try: - write(a.out, rows, unmatched, summary) - except OSError as error: - print(f"bink_names: error: cannot write {a.out}: {error}", file=sys.stderr) - return 2 - print(f"{len(names)} list entries, {len(streams)} streams: " - + ", ".join(f"{counts[c]} {c}" for c in CONFIDENCES) - + f"; {len(unmatched)} list entries not in this source") - return 0 - - -if __name__ == "__main__": - try: # a redirected stdout is strict ANSI code page under -I; write '?' for what it cannot encode - sys.stdout.reconfigure(errors="replace") - except (AttributeError, ValueError, OSError): - pass - sys.exit(main()) diff --git a/tools/bink_play.py b/tools/bink_play.py deleted file mode 100644 index 0d2edf634..000000000 --- a/tools/bink_play.py +++ /dev/null @@ -1,174 +0,0 @@ -"""Play a game movie by name, straight from its archive, with runtime/test/bink_play. - -The movie is never extracted: this finds its offset in ``movies.rpf`` with ``bink_names.py`` (from the mount lists in -``common.rpf``) and starts ``bink_play @``, which hands the archive to the package's own -Bink2Scarlett.dll with ``BinkSetFileOffset``. - -Usage: - python tools/bink_play.py Stinger/RSG_STINGER.bk2 [--game-dir DIR] [--exe bink_play.exe] [-- bink_play args] - python tools/bink_play.py stinger # any unique part of the name, case-insensitive - python tools/bink_play.py --list [TEXT] # the names (and sizes) it knows, optionally filtered - -``--game-dir`` defaults to ``LEONIDA_GAME_DIR``. Naming the streams takes about half a minute, so the name table -(names, offsets and frame sizes only, no movie data) is kept in ``%LOCALAPPDATA%\\Leonida\\bink_names.csv`` and rebuilt -when the archive or mount source changes, or the cached table cannot be parsed. ``--no-cache`` skips it. -The names are a local work product: don't commit or post them. -""" -import argparse -import csv -import os -import subprocess -import sys -import tempfile -from pathlib import Path - -HERE = Path(__file__).resolve().parent -sys.path.insert(0, str(HERE)) - -import bink_names # noqa: E402 - -CACHE_FIELDS = ("path", "offset", "width", "height", "frames") - - -def cache_path(): - base = os.environ.get("LOCALAPPDATA") or str(Path.home() / ".cache") - return Path(base) / "Leonida" / "bink_names.csv" - - -def stamp(archive): - st = archive.stat() - return f"{archive.resolve()}|{st.st_size}|{st.st_mtime_ns}" - - -def _read_cache(cache, key): - """Return cached rows, or None for a stale or malformed cache. A valid empty table is a hit.""" - try: - with cache.open(encoding="utf-8", newline="") as f: - if f.readline().rstrip("\r\n") != "# " + key: - return None - reader = csv.reader(f, strict=True) - if tuple(next(reader, ())) != CACHE_FIELDS: - return None - rows = [] - for path, offset, width, height, frames in reader: - offset = int(offset) - if not path or offset < 0 or min(int(width), int(height), int(frames)) < 1: - return None - rows.append((path, offset, width, height, frames)) - return rows - except (ValueError, csv.Error): - return None - - -def load_names(archive, mount, use_cache=True): - """[(path, offset, width, height, frames)] for the streams of ``archive``, named from ``mount``.""" - cache = cache_path() - key = stamp(archive) + "|" + stamp(mount) # the names come from the mount lists too - if use_cache and cache.is_file(): - rows = _read_cache(cache, key) - if rows is not None: - return rows - cache.parent.mkdir(parents=True, exist_ok=True) - # Each lookup gets its own report and staging file: two runs at once must not remove or replace each other's. - fd, name = tempfile.mkstemp(prefix="bink_names.", suffix=".tmp.csv", dir=cache.parent) - os.close(fd) - tmp = Path(name) - try: - print(f"naming the movies in {archive.name} (about half a minute, once)...", file=sys.stderr) - rc = bink_names.main([str(archive), "--mount", str(mount), "--out", str(tmp)]) - if rc not in (0, None) or not tmp.is_file() or tmp.stat().st_size == 0: - raise SystemExit(f"bink_names.py failed on {archive}") - with tmp.open(encoding="utf-8", newline="") as f: - rows = [r for r in csv.DictReader(f) if r.get("path")] - finally: - tmp.unlink(missing_ok=True) - if use_cache: - fd, name = tempfile.mkstemp(prefix="bink_names.", suffix=".part", dir=cache.parent) - with open(fd, "w", encoding="utf-8", newline="") as f: - f.write("# " + key + "\n") - w = csv.writer(f, lineterminator="\n") - w.writerow(CACHE_FIELDS) - for r in rows: - w.writerow([r["path"], r["offset"], r["width"], r["height"], r["frames"]]) - os.replace(name, cache) - return [(r["path"], int(r["offset"]), r["width"], r["height"], r["frames"]) for r in rows] - - -def pick(names, wanted): - """Prefer exact paths to substring matches and return a hit only when unique.""" - w = wanted.replace("\\", "/").lower() - exact = [n for n in names if n[0].lower() == w] - if len(exact) == 1: - return exact[0], [] - if exact: - return None, exact - part = [n for n in names if w in n[0].lower()] - if len(part) == 1: - return part[0], [] - return None, part - - -def find_exe(explicit): - if explicit: - return Path(explicit) - root = HERE.parent - for c in (root / "runtime" / "build" / "bink_play.exe", root / "runtime" / "build" / "Release" / "bink_play.exe"): - if c.is_file(): - return c - raise SystemExit("bink_play.exe not found; build the runtime (runtime/build) or pass --exe") - - -def main(argv=None): - argv = list(sys.argv[1:] if argv is None else argv) - extra = [] - if "--" in argv: - i = argv.index("--") - argv, extra = argv[:i], argv[i + 1:] - ap = argparse.ArgumentParser(description="Play a game movie by name, straight from its archive.") - ap.add_argument("name", nargs="?", help="the movie's path (Stinger/RSG_STINGER.bk2) or a unique part of it") - ap.add_argument("--game-dir", default=os.environ.get("LEONIDA_GAME_DIR"), help="the package folder") - ap.add_argument("--archive", default="movies.rpf", help="the archive holding the movie (default movies.rpf)") - ap.add_argument("--mount", default="common.rpf", help="where the mount lists are (default common.rpf)") - ap.add_argument("--exe", help="bink_play.exe (default runtime/build/bink_play.exe)") - ap.add_argument("--list", action="store_true", help="list the names, filtered by NAME if given") - ap.add_argument("--no-cache", action="store_true", help="name the streams again and keep nothing") - a = ap.parse_args(argv) - if not a.game_dir: - ap.error("no game folder: pass --game-dir or set LEONIDA_GAME_DIR") - game = Path(a.game_dir) - archive = Path(a.archive) if Path(a.archive).is_absolute() else game / a.archive - mount = Path(a.mount) if Path(a.mount).is_absolute() else game / a.mount - for p in (archive, mount): - if not p.is_file(): - ap.error(f"{p} is not a file") - names = load_names(archive, mount, use_cache=not a.no_cache) - - if a.list: - w = (a.name or "").replace("\\", "/").lower() - for path, _, width, height, frames in names: - if w in path.lower(): - print(f"{path} {width}x{height}, {frames} frames") - return 0 - if not a.name: - ap.error("name a movie, or use --list") - hit, candidates = pick(names, a.name) - if hit is None: - if not candidates: - print(f"no movie named like {a.name!r} in {archive.name}; try --list", file=sys.stderr) - else: - print(f"{len(candidates)} movies match {a.name!r}; be more specific:", file=sys.stderr) - for c in candidates[:40]: - print(" " + c[0], file=sys.stderr) - return 1 - path, offset, width, height, frames = hit - print(f"{path}: {width}x{height}, {frames} frames, at {archive.name}@{offset}", flush=True) - cmd = [str(find_exe(a.exe)), f"{archive}@{offset}", "--game-dir", str(game)] + extra - return subprocess.call(cmd) - - -if __name__ == "__main__": - try: # a redirected stdout is strict ANSI code page under -I; write '?' for what it cannot encode - sys.stdout.reconfigure(errors="replace") - except (AttributeError, ValueError, OSError): - pass - sys.exit(main()) diff --git a/tools/boot_trace.py b/tools/boot_trace.py deleted file mode 100644 index 676ae2060..000000000 --- a/tools/boot_trace.py +++ /dev/null @@ -1,422 +0,0 @@ -"""Summarize `gta6rt`'s two first-boot traces: the startup JSONL and the `[d3d12-trace]` lines. - -The loader writes the startup trace with `gta6rt --trace FILE` (one JSON object per line, flushed per event so it -survives a crash; `runtime/README.md`, "Startup trace"), and the D3D12 proxy writes one `[d3d12-trace] # - ` line to stderr with `--trace-d3d12`. This tool turns both into the small report a first-boot -triage needs: modules, unimplemented calls and their callers, DllMain/TLS results, exceptions and the exit, then -the D3D12 calls by outcome and the first call per method. - -The method field can contain spaces (`SetMarker/BeginEvent with unknown metadata`), so the parser takes the -outcome as the last field instead of assuming a single-word method. PowerShell 5.1 wraps the first stderr line of -a native program in an error record (`program.exe : [d3d12-trace] #1 ...`), so a ` : ` prefix before the -tag is accepted too. The reader accepts UTF-8 and BOM-marked UTF-16, including PowerShell 5.1 stderr redirection. - -Usage: - python -I boot_trace.py boot.jsonl [--d3d12 d3d12.log] [--json] [--counts-only] [--limit N] - -Use --counts-only for an aggregate JSON report to share. The traces can quote what the game prints, so they -stay on the player's machine. The text report counts debug -strings instead of printing them, and only the tests' synthetic fixtures go into the repository. Share counts and -error classes from a real run, not its trace (AGENTS.md, "No game data"). - -Standard library only; reads files, never runs them. A truncated last line (the expected shape after a crash) is -counted, not fatal; a file with no valid event is an error (exit 2). When one of two requested traces fails to -parse, the report still includes the other trace. -""" - -from __future__ import annotations - -import argparse -import json -import re -import sys - -D3D12_LINE = re.compile(r"^(?:.+ : )?\[d3d12-trace\] #(\d+) (.+) (\S+)\s*$") -D3D12_PROBLEMS = ("failed", "unsupported", "refused", "partial") -D3D12_OUTCOMES = frozenset((*D3D12_PROBLEMS, "called", "ok", "ignored")) - - -class TraceError(ValueError): - """The file is unreadable or holds no valid trace event.""" - - -def _open_text(path: str): - """Read UTF-8 or use the byte-order mark to decode a UTF-16 trace.""" - try: - with open(path, "rb") as raw: - head = raw.read(2) - encoding = "utf-16" if head in (b"\xff\xfe", b"\xfe\xff") else "utf-8-sig" - return open(path, encoding=encoding, errors="replace") - except OSError as e: - raise TraceError(f"cannot read {path}: {e.strerror or e}") from e - - -def parse_startup(path: str, limit: int = 10) -> dict: - """Read the `--trace` JSONL into the units the first-boot triage uses.""" - trace = { - "path": path, - "pid": None, - "events": 0, - "bad_lines": 0, - "bad_line_numbers": [], - "kinds": {}, - "modules": [], - "tls_callbacks": 0, - "dllmain": {"ok": 0, "failed": 0, "failed_modules": []}, - "unimplemented": [], - "unimplemented_by_dll": {}, - "unimplemented_call_counts": {}, - "debug_strings": 0, - "file_open_failed": [], - "file_open_failed_count": 0, - "int3_skipped": [], - "exceptions": [], - "exception_count": 0, - "exit": None, - "error": None, - } - with _open_text(path) as fh: - for number, line in enumerate(fh, 1): - line = line.strip() - if not line: - continue - try: - event = json.loads(line) - if isinstance(event, dict) and event.get("kind") == "exit" and type(event.get("code")) is not int: - event = None - except json.JSONDecodeError: - trace["bad_lines"] += 1 - if len(trace["bad_line_numbers"]) < limit: - trace["bad_line_numbers"].append(number) - continue - if not isinstance(event, dict) or "kind" not in event: - trace["bad_lines"] += 1 - if len(trace["bad_line_numbers"]) < limit: - trace["bad_line_numbers"].append(number) - continue - trace["events"] += 1 - kind = str(event.get("kind")) - trace["kinds"][kind] = trace["kinds"].get(kind, 0) + 1 - if kind == "trace_open": - trace["pid"] = event.get("pid") - elif kind == "map": - trace["modules"].append( - { - "module": event.get("module"), - "base": event.get("base"), - "size": event.get("size"), - "relocated": event.get("relocated"), - } - ) - elif kind == "tls_callback": - trace["tls_callbacks"] += 1 - trace["last_tls_callback"] = { - "module": event.get("module"), - "at": event.get("at"), - "reason": event.get("reason"), - } - elif kind == "dllmain": - if event.get("result"): - trace["dllmain"]["ok"] += 1 - else: - trace["dllmain"]["failed"] += 1 - if len(trace["dllmain"]["failed_modules"]) < limit: - trace["dllmain"]["failed_modules"].append(event.get("module")) - elif kind == "unimplemented_call": - name = str(event.get("import", "?")) - calls = trace["unimplemented_call_counts"] - calls[name] = calls.get(name, 0) + 1 - if calls[name] == 1: - trace["unimplemented"].append( - {"import": name, "caller": event.get("caller")} - ) - dll = name.split("!", 1)[0] - trace["unimplemented_by_dll"][dll] = ( - trace["unimplemented_by_dll"].get(dll, 0) + 1 - ) - elif kind == "debug_string": - trace["debug_strings"] += 1 - elif kind == "file_open_failed": - trace["file_open_failed_count"] += 1 - if len(trace["file_open_failed"]) < limit: - trace["file_open_failed"].append( - { - "path": event.get("path"), - "error": event.get("error"), - "caller": event.get("caller"), - } - ) - elif kind == "int3_skipped": - trace["int3_skipped"].append(event.get("at")) - elif kind == "exception": - trace["exception_count"] += 1 - if limit <= 0: - continue - stack = event.get("stack") - detail = { - "code": event.get("code"), - "at": event.get("at"), - "cpp": event.get("cpp"), - "access": event.get("access"), - "address": event.get("address"), - "stack": stack[:8] if isinstance(stack, list) else [], - } - if len(trace["exceptions"]) < limit: - trace["exceptions"].append(detail) - else: - trace["exceptions"][-1] = detail - elif kind == "exit": - trace["exit"] = event.get("code") - elif kind == "error": - trace["error"] = event.get("what") - if trace["events"] == 0: - raise TraceError(f"{path} has no valid startup event") - return trace - - -def parse_d3d12(path: str, limit: int = 10) -> dict: - """Read the `--trace-d3d12` stderr lines, ignoring the runtime's ordinary diagnostics.""" - trace = { - "path": path, - "calls": 0, - "ignored_lines": 0, - "outcomes": {}, - "methods": [], - "first": {}, - "method_outcomes": {}, - "failed": [], - "unsupported": [], - "refused": [], - "partial": [], - "last_seq": 0, - "sequence_break_count": 0, - "sequence_breaks": [], - } - with _open_text(path) as fh: - for line in fh: - match = D3D12_LINE.match(line.rstrip("\n")) - # A crash can truncate the final outcome. A known complete outcome is - # still usable when the trace ends just before the newline. - if not match or (not line.endswith("\n") and match.group(3) not in D3D12_OUTCOMES): - if line.strip(): - trace["ignored_lines"] += 1 - continue - seq, method, outcome = int(match.group(1)), match.group(2), match.group(3) - trace["calls"] += 1 - expected = trace["last_seq"] + 1 - if seq != expected: - trace["sequence_break_count"] += 1 - if len(trace["sequence_breaks"]) < limit: - trace["sequence_breaks"].append({"expected": expected, "observed": seq}) - trace["last_seq"] = seq - trace["outcomes"][outcome] = trace["outcomes"].get(outcome, 0) + 1 - counts = trace["method_outcomes"].setdefault(method, {}) - counts[outcome] = counts.get(outcome, 0) + 1 - if method not in trace["first"]: - trace["methods"].append(method) - trace["first"][method] = {"seq": seq, "outcome": outcome} - if outcome in D3D12_PROBLEMS: - bucket = trace[outcome] - if len(bucket) < limit: - bucket.append({"seq": seq, "method": method}) - if trace["calls"] == 0: - raise TraceError( - f"{path} has no [d3d12-trace] line among {trace['ignored_lines']} line(s); " - "is it the stderr log of a --trace-d3d12 run, with the Vulkan device enabled?" - ) - trace["last_call"] = {"seq": seq, "method": method, "outcome": outcome} - return trace - - -def summarize(startup: dict | None, d3d12: dict | None) -> dict: - return {"startup": startup, "d3d12": d3d12} - - -def counts_only(summary: dict) -> dict: - """Project only fixed counters into the summary intended for sharing.""" - counters = summarize(None, None) - if startup := summary["startup"]: - counters["startup"] = { - name: startup[name] for name in ("events", "bad_lines", "tls_callbacks", "debug_strings", - "file_open_failed_count", "exception_count") - } - counters["startup"].update( - modules=len(startup["modules"]), - dllmain_failed=startup["dllmain"]["failed"], - unimplemented_imports=len(startup["unimplemented"]), - int3_skipped=len(startup["int3_skipped"]), - exit_observed=startup["exit"] is not None, - ) - if d3d12 := summary["d3d12"]: - outcomes = {} - for outcome, count in d3d12["outcomes"].items(): - key = outcome if outcome in ("failed", "unsupported", "refused", "partial", "ok", "called", "ignored") else "other" - outcomes[key] = outcomes.get(key, 0) + count - counters["d3d12"] = { - "calls": d3d12["calls"], - "ignored_lines": d3d12["ignored_lines"], - "sequence_break_count": d3d12["sequence_break_count"], - "outcomes": outcomes, - } - return counters - - -def _tail(items, limit: int) -> str: - shown = ", ".join(str(x) for x in items[:limit]) - return shown + (f", ... {len(items) - limit} more" if len(items) > limit else "") - - -def format_text(summary: dict, limit: int) -> str: - out = [] - startup = summary.get("startup") - if startup: - out.append(f"startup trace: {startup['path']}") - if startup["events"]: - out.append( - f" pid {startup['pid']}, {startup['events']} event(s), {startup['bad_lines']} bad line(s)" - ) - kinds = ", ".join(f"{k} {v}" for k, v in sorted(startup["kinds"].items())) - out.append(f" kinds: {kinds}") - if startup["modules"]: - names = [m["module"] for m in startup["modules"]] - out.append(f" modules ({len(names)}): {_tail(names, limit)}") - out.append(f" tls callbacks: {startup['tls_callbacks']}") - if callback := startup.get("last_tls_callback"): - reason = callback["reason"] - phase = "phase unknown" - if type(reason) is int: - phase = {0: "process detach", 1: "process attach"}.get(reason, phase) - at = callback["at"] or "address unknown" - out.append(f" last observed TLS callback: {at} ({phase})") - dm = startup["dllmain"] - line = f" dllmain: {dm['ok']} ok, {dm['failed']} failed" - if dm["failed_modules"]: - line += f" ({_tail(dm['failed_modules'], limit)})" - out.append(line) - if startup["unimplemented"]: - calls = startup["unimplemented_call_counts"] - out.append(f" unimplemented: {len(calls)} unique, {sum(calls.values())} calls") - for item in sorted(startup["unimplemented"], key=lambda item: -calls[item["import"]])[:limit]: - count = calls[item["import"]] - out.append(f" {item['import']} from {item['caller']} ({count} {'call' if count == 1 else 'calls'})") - if len(startup["unimplemented"]) > limit: - out.append(f" ... {len(startup['unimplemented']) - limit} more") - by_dll = ", ".join( - f"{dll} {count}" - for dll, count in sorted(startup["unimplemented_by_dll"].items()) - ) - out.append(f" by dll (unique imports): {by_dll}") - else: - out.append(" unimplemented: none") - if startup["debug_strings"]: - out.append(f" debug strings: {startup['debug_strings']} (text not shown)") - if startup["file_open_failed_count"]: - out.append(f" failed file opens: {startup['file_open_failed_count']}") - for item in startup["file_open_failed"][:limit]: - out.append(f" {item['path']} error {item['error']} from {item['caller']}") - if startup["file_open_failed_count"] > limit: - out.append(f" ... {startup['file_open_failed_count'] - limit} more") - if startup["int3_skipped"]: - out.append(f" int3 skipped (LEONIDA_SKIP_INT3, one per address): {_tail(startup['int3_skipped'], limit)}") - if startup["exception_count"]: - out.append(f" exceptions: {startup['exception_count']}") - for exc in startup["exceptions"][:limit]: - cpp = exc.get("cpp") - detail = " (C++ throw)" if cpp is True else f" ({cpp})" if cpp else "" - if exc.get("access"): - detail += f" ({exc['access']}" - if exc.get("address"): - detail += f" {exc['address']}" - detail += ")" - out.append(f" code {exc['code']} at {exc['at']}{detail}") - if exc.get("stack"): - out.append(f" stack: {_tail(exc['stack'], limit)}") - if startup["error"]: - out.append(f" error: {startup['error']}") - if startup["exit"] is not None: - out.append(f" exit: {startup['exit']}") - d3d12 = summary.get("d3d12") - if d3d12: - out.append(f"d3d12 trace: {d3d12['path']}") - outcomes = ", ".join(f"{k} {v}" for k, v in sorted(d3d12["outcomes"].items())) - out.append( - f" {d3d12['calls']} call(s), {d3d12['ignored_lines']} other line(s)" - " (the [rt] diagnostics are not summarized)" - + (f": {outcomes}" if outcomes else "") - ) - if last_call := d3d12.get("last_call"): - out.append(f" last recorded call: #{last_call['seq']} {last_call['method']} {last_call['outcome']}") - if d3d12["sequence_break_count"]: - out.append(f" sequence breaks: {d3d12['sequence_break_count']}") - for item in d3d12["sequence_breaks"][:limit]: - out.append(f" expected #{item['expected']}, observed #{item['observed']}") - if d3d12["methods"]: - out.append(f" first per method: {_tail(d3d12['methods'], limit)}") - problems = [] - for method, counts in d3d12["method_outcomes"].items(): - failures = {outcome: counts[outcome] for outcome in D3D12_PROBLEMS if outcome in counts} - if failures: - problems.append((sum(failures.values()), method, failures)) - if problems: - out.append(" methods by problem count:") - for _, method, counts in sorted(problems, key=lambda row: (-row[0], row[1]))[:limit]: - out.append(f" {method}: " + ", ".join(f"{outcome} {n}" for outcome, n in counts.items())) - if d3d12["unsupported"]: - unsupported = [f"#{c['seq']} {c['method']}" for c in d3d12["unsupported"]] - out.append(f" unsupported: {_tail(unsupported, limit)}") - if d3d12["failed"]: - failed = [f"#{c['seq']} {c['method']}" for c in d3d12["failed"]] - out.append(f" failed: {_tail(failed, limit)}") - if d3d12["refused"]: - refused = [f"#{c['seq']} {c['method']}" for c in d3d12["refused"]] - out.append(f" refused: {_tail(refused, limit)}") - if d3d12.get("partial"): - partial = [f"#{c['seq']} {c['method']}" for c in d3d12["partial"]] - out.append(f" partial: {_tail(partial, limit)}") - return "\n".join(out) - - -def main(argv=None) -> int: - ap = argparse.ArgumentParser( - description="Summarize gta6rt's startup and D3D12 first-boot traces." - ) - ap.add_argument("startup", nargs="?", help="the JSONL written by gta6rt --trace") - ap.add_argument("--d3d12", help="the stderr log written with --trace-d3d12") - ap.add_argument("--json", action="store_true", help="print the summary as JSON") - ap.add_argument("--counts-only", action="store_true", help="print aggregate JSON without paths or event details") - ap.add_argument( - "--limit", type=int, default=10, help="items listed per section (default 10)" - ) - a = ap.parse_args(argv) - if not a.startup and not a.d3d12: - print("error: give the startup trace, --d3d12, or both", file=sys.stderr) - return 2 - if a.limit < 1: - print("error: --limit must be at least 1", file=sys.stderr) - return 2 - summary = summarize(None, None) - exit_code = 0 - for section, path, parse in (("startup", a.startup, parse_startup), ("d3d12", a.d3d12, parse_d3d12)): - if path: - try: - summary[section] = parse(path, a.limit) - except TraceError as e: - print(f"error: {section} trace unavailable" if a.counts_only else f"error: {e}", file=sys.stderr) - exit_code = 2 - if not any(summary.values()): - return 2 - if a.counts_only: - print(json.dumps(counts_only(summary), indent=1)) - elif a.json: - print(json.dumps(summary, indent=1)) - else: - print(format_text(summary, a.limit)) - return exit_code - - -if __name__ == "__main__": - try: # a redirected stdout is strict ANSI code page under -I; write '?' for what it cannot encode - sys.stdout.reconfigure(errors="replace") - except (AttributeError, ValueError, OSError): - pass - sys.exit(main()) diff --git a/tools/buffer_bounds_probe.py b/tools/buffer_bounds_probe.py deleted file mode 100644 index 0769a08e5..000000000 --- a/tools/buffer_bounds_probe.py +++ /dev/null @@ -1,258 +0,0 @@ -r"""SHADER-341: native GFX10 MUBUF `OOB_SELECT` bounds probe. - -Runs hand-written one-lane raw kernels through `tools/hw_oracle` and compares a -4-byte `buffer_load_dword` against the two published bounds columns: - - * Mesa's GFX10 column (`.ac_descriptors.c`), which checks `offset >= stride` - in structured-with-offset mode and `offset >= NUM_RECORDS` in raw mode; - * the RDNA2 measurement in docs/buffer_bounds.md (Mesa's GFX11 column), which - checks the *end* of the dword and includes `soffset` in raw mode. - -No game data is involved: every V#, buffer and pattern is built by this file. - -Usage: - python -I tools/buffer_bounds_probe.py --self-test - python -I tools/buffer_bounds_probe.py [--waves 32,64] [--json report.json] - -Exit codes: - 0 every case matches the measured RDNA2/GFX11 column - 1 at least one case disagrees (or a wave32/wave64 result differs) - 2 bad arguments (including a --json path this tool cannot write) or harness error - 77 hardware oracle unavailable or not a GFX10 device -""" -import argparse -import json -import os -import sys - -HERE = os.path.dirname(os.path.abspath(__file__)) -ROOT = os.path.dirname(HERE) -if HERE not in sys.path: - sys.path.insert(0, HERE) - -# Raw output V# in s[0:3]; the probed data starts 0x100 bytes into the buffer. -OUT_V_W3 = 0x31016FAC -V_W3_BASE = 0x01000FAC -DATA_OFF = 0x100 -DATA_DWORDS = 64 -SEED_BASE = 0xA0000000 - -# name, mode, stride, num_records, index, offset, soffset, idxen, offen. -# The first four cases are the ones where the two columns disagree. -CASES = [ - ("mode0_stride16_off13", 0, 16, 18, 0, 13, 0, False, True), - ("mode0_stride16_off12", 0, 16, 18, 0, 12, 0, False, True), - ("mode0_index_at_nr", 0, 16, 2, 2, 0, 0, True, False), - ("mode1_index_at_nr", 1, 16, 2, 2, 0, 0, True, False), - ("mode1_index_off48", 1, 16, 18, 1, 48, 0, True, True), - ("mode2_nr0", 2, 16, 0, 0, 0, 0, False, False), - ("mode2_nr18", 2, 16, 18, 0, 0, 0, False, False), - ("mode3_nr18_off16", 3, 0, 18, 0, 16, 0, False, True), - ("mode3_nr18_off13", 3, 0, 18, 0, 13, 0, False, True), - ("mode3_nr3_off0", 3, 0, 3, 0, 0, 0, False, True), - ("mode3_soff8_off8_nr18", 3, 0, 18, 0, 8, 8, False, True), - ("mode3_stride16_index4", 3, 16, 18, 4, 0, 0, True, False), -] - - -def oob_gfx10(case): - """Out-of-range according to Mesa's GFX10 column (docs/buffer_bounds.md).""" - _name, mode, stride, nr, idx, off, _soff, _idxen, _offen = case - if mode == 0: - return idx >= nr or off >= stride - if mode == 1: - return idx >= nr - if mode == 2: - return nr == 0 - if mode == 3: - return off >= nr - raise ValueError(f"bad OOB_SELECT mode {mode}") - - -def oob_gfx11(case): - """Out-of-range according to the measured RDNA2 / Mesa GFX11 column.""" - _name, mode, stride, nr, idx, off, soff, _idxen, _offen = case - if mode == 0: - return idx >= nr or off + 4 > stride - if mode == 1: - return idx >= nr - if mode == 2: - return nr == 0 - if mode == 3: - return off + soff + 4 > nr - raise ValueError(f"bad OOB_SELECT mode {mode}") - - -def kernel_lines(case, wave): - """One self-contained raw kernel: seed the data, load once, store the word.""" - name, mode, stride, nr, idx, off, soff, idxen, offen = case - lbl, done = f".Lseed_{name}", f".Ldone_{name}" - if wave == 32: - save = ["s_mov_b32 s28, exec_lo", "v_cmpx_eq_u32_e32 0, v0"] - restore = ["s_mov_b32 exec_lo, s28"] - else: - save = ["s_mov_b64 s[28:29], exec", "v_cmpx_eq_u32_e32 0, v0"] - restore = ["s_mov_b64 exec, s[28:29]"] - return [ - "s_mov_b32 s0, s2", - "s_and_b32 s1, s3, 0xffff", - "s_mov_b32 s2, 0xffffffff", - f"s_mov_b32 s3, {OUT_V_W3:#x}", - f"s_add_u32 s16, s0, {DATA_OFF:#x}", - "s_addc_u32 s17, s1, 0", - "s_and_b32 s17, s17, 0xffff", - *save, - "s_mov_b32 s20, 0", - f"{lbl}:", - f"s_cmp_ge_u32 s20, {DATA_DWORDS * 4:#x}", - f"s_cbranch_scc1 {done}", - f"s_add_u32 s21, s20, {SEED_BASE:#x}", - "v_mov_b32 v30, s21", - f"s_add_u32 s22, s20, {DATA_OFF:#x}", - "buffer_store_dword v30, off, s[0:3], s22", - "s_add_u32 s20, s20, 4", - f"s_branch {lbl}", - f"{done}:", - "s_waitcnt vmcnt(0)", - *restore, - "s_mov_b32 s4, s16", - f"s_or_b32 s5, s17, {stride << 16:#x}", - f"s_mov_b32 s6, {nr:#x}", - f"s_mov_b32 s7, {V_W3_BASE | (22 << 12) | (mode << 28):#x}", - f"s_mov_b32 s10, {soff:#x}", - f"v_mov_b32 v1, {idx:#x}", - f"v_mov_b32 v2, {off:#x}", - f"buffer_load_dword v8, {_addr(case)}, s[4:7], {_soff(case)}{_mods(case)}", - "s_waitcnt vmcnt(0)", - "buffer_store_dword v8, off, s[0:3], 0", - "s_endpgm", - ] - - -def _addr(case): - _n, _m, _s, _nr, _i, _o, _so, idxen, offen = case - if idxen and offen: - return "v[1:2]" - if idxen: - return "v1" - if offen: - return "v2" - return "off" - - -def _soff(case): - return "s10" if case[6] else "0" - - -def _mods(case): - idxen, offen = case[7], case[8] - if idxen and offen: - return " idxen offen" - if idxen: - return " idxen" - if offen: - return " offen" - return "" - - -def self_test(): - assert len({c[0] for c in CASES}) == len(CASES), "duplicate case names" - for c in CASES: - assert 0 <= c[1] <= 3 and c[2] >= 0 and c[3] >= 0, c - oob_gfx10(c) - oob_gfx11(c) - for wave in (32, 64): - lines = kernel_lines(c, wave) - assert any("buffer_load_dword v8," in ln for ln in lines), c - assert lines[-1] == "s_endpgm", c - # The four witness cases must separate the two columns. - witnesses = [c for c in CASES if oob_gfx10(c) != oob_gfx11(c)] - assert len(witnesses) >= 4, len(witnesses) - assert oob_gfx10(CASES[10]) is False and oob_gfx11(CASES[10]) is True # soffset in raw mode - print("self-test OK") - - -def probe(oracle, asm, waves): - out = {"arch": oracle.arch, "device": str(oracle.device), "waves": {}} - for wave in waves: - kernels = [asm.Kernel(kernel_lines(c, wave), wave=wave, threads=1, - words=4, raw=True) for c in CASES] - results = oracle.run(kernels, words=4) - rows = [] - for case, result in zip(CASES, results): - word = result[0] if isinstance(result, list) else result - oob = word == 0 - rows.append({"name": case[0], "got": word & 0xFFFFFFFF, "oob": oob, - "gfx10_oob": oob_gfx10(case), "gfx11_oob": oob_gfx11(case)}) - out["waves"][str(wave)] = rows - return out - - -def main(): - if hasattr(sys.stdout, "reconfigure"): - sys.stdout.reconfigure(encoding="utf-8", errors="replace") - ap = argparse.ArgumentParser(description=__doc__.splitlines()[0]) - ap.add_argument("--waves", default="32,64", help="wave sizes to run (default: 32,64)") - ap.add_argument("--json", dest="json_out", help="write the full report to this path") - ap.add_argument("--self-test", action="store_true", help="check the models without a GPU") - args = ap.parse_args() - if args.self_test: - self_test() - return 0 - waves = [int(w) for w in args.waves.split(",") if w.strip()] - if not waves or any(w not in (32, 64) for w in waves): - print("--waves must be a non-empty list of 32 and/or 64", file=sys.stderr) - return 2 - if args.json_out: - # The report is written after the sweep, but a path that cannot be written must fail before the GPU work. - if os.path.isdir(args.json_out): - print(f"ERROR: --json {args.json_out} is a directory", file=sys.stderr) - return 2 - folder = os.path.dirname(os.path.abspath(args.json_out)) - if not os.path.isdir(folder): - print(f"ERROR: --json {args.json_out}: its folder {folder} does not exist", file=sys.stderr) - return 2 - from hw_oracle import asm, runner - try: - oracle = runner.open_oracle() - except runner.Unavailable as exc: - print(f"SKIP: {exc}", file=sys.stderr) - return 77 - try: - if asm.family(oracle.arch) != "gfx10": - print(f"SKIP: {oracle.arch} is not GFX10 (RDNA1/RDNA2)", file=sys.stderr) - return 77 - report = probe(oracle, asm, waves) - finally: - oracle.close() - gfx10_diff = gfx11_diff = wave_diff = 0 - for wave, rows in report["waves"].items(): - for row in rows: - gfx10_diff += row["oob"] != row["gfx10_oob"] - gfx11_diff += row["oob"] != row["gfx11_oob"] - print(f"wave{wave} {row['name']:24s} got={'OOB' if row['oob'] else 'data'} " - f"gfx10={'OOB' if row['gfx10_oob'] else 'data'} " - f"gfx11={'OOB' if row['gfx11_oob'] else 'data'} 0x{row['got']:08x}") - if "32" in report["waves"] and "64" in report["waves"]: - a = {r["name"]: r["oob"] for r in report["waves"]["32"]} - b = {r["name"]: r["oob"] for r in report["waves"]["64"]} - wave_diff = sum(a[k] != b.get(k) for k in a) - print(f"{oracle.arch}: {sum(len(v) for v in report['waves'].values())} cases, " - f"{gfx11_diff} disagree with the measured RDNA2/GFX11 column, " - f"{gfx10_diff} disagree with Mesa's GFX10 column, " - f"{wave_diff} wave32/wave64 differences") - if args.json_out: - try: - with open(args.json_out, "w", encoding="utf-8", newline="\n") as f: - json.dump(report, f, indent=2) - except OSError as exc: - print(f"ERROR: cannot write {args.json_out}: {getattr(exc, 'strerror', None) or exc}", - file=sys.stderr) - return 2 - return 1 if gfx11_diff or wave_diff else 0 - - -if __name__ == "__main__": - if hasattr(sys.stdout, "reconfigure"): - sys.stdout.reconfigure(errors="replace") - raise SystemExit(main()) diff --git a/tools/buffer_format_fuzz.py b/tools/buffer_format_fuzz.py deleted file mode 100644 index 2bee995d2..000000000 --- a/tools/buffer_format_fuzz.py +++ /dev/null @@ -1,666 +0,0 @@ -r"""Hardware oracle for the GFX10 buffer data formats a V# or MTBUF can name (standard library only). - -For every format code 1..77 (GFX10_FORMAT_*, tools/gfx10_formats.json) that the GPU also has, one raw kernel per batch -of 16-byte elements runs `buffer_load_format_xyzw` (the format comes from the V#) or `tbuffer_load_format_xyzw` (the -format comes from the instruction) over many bit patterns, or `buffer_store_format_xyzw` of many register values into -a buffer pre-filled with 0xDEAD0000, and every result word is compared with MODEL, the CPU decode / encode this file defines. The -translator's emission (Gen.decode_format / Gen.encode_format in tools/rdna2spirv.py) is held to the same MODEL by -tests/semantic/test_buffer_formats_all.py, so the chain is hardware -> MODEL -> translated SPIR-V. - -The Radeon 880M (gfx1150) is RDNA3.5, not RDNA2, and numbers its formats differently (GFX11 has 63; its 10_11_11 / 11_11_10 -families keep only FLOAT and it has no SCALED 10_10_10_2), so a format is mapped by NAME and the 14 GFX10-only codes -(30..35, 37..42, 46, 47) cannot be run there. On a GFX10 device (the Linux DRM backend, tools/hw_oracle/drm.py, native -GFX10 numbers) the default run covers all 77. The model was validated on the 880M and on a real RDNA2 (gfx1036, -@AwkGrep256, #2022: 1,330,469 elements on the 63 codes and 199,144 on the 14 others, 0 mismatches), with the same -two-component buffer_store_format_* routing (x, w) on both (docs/buffer_formats.md). - -Usage: - python -I tools/buffer_format_fuzz.py --self-test - python -I tools/buffer_format_fuzz.py --oracle hw [--mode load|store|all] [--path mubuf|mtbuf|both] - [--formats 56,36,...] [--seed S] [--negative-control] -Exit code: 0 all match, 1 a mismatch, 2 a usage or harness error, 77 no hardware oracle. Nothing here reads game files. -""" -import argparse -import json -import math -import os -import random -import struct -import sys -from fractions import Fraction - -HERE = os.path.dirname(os.path.abspath(__file__)) -sys.path.insert(0, HERE) - -PREFILL = 0xDEAD0000 # what the launcher writes into the output before a kernel runs (hw_oracle.c) - -# GFX11's unified format numbers by name, from the order the AMD assembler (LLVM 23.1.5, -mcpu=gfx1150) gives -# `format:N`; GFX11 has no code for the other GFX10 buffer formats (its names below are all it knows). -GFX11_CODES = { - "8_UNORM": 1, "8_SNORM": 2, "8_USCALED": 3, "8_SSCALED": 4, "8_UINT": 5, "8_SINT": 6, "16_UNORM": 7, - "16_SNORM": 8, "16_USCALED": 9, "16_SSCALED": 10, "16_UINT": 11, "16_SINT": 12, "16_FLOAT": 13, - "8_8_UNORM": 14, "8_8_SNORM": 15, "8_8_USCALED": 16, "8_8_SSCALED": 17, "8_8_UINT": 18, "8_8_SINT": 19, - "32_UINT": 20, "32_SINT": 21, "32_FLOAT": 22, "16_16_UNORM": 23, "16_16_SNORM": 24, "16_16_USCALED": 25, - "16_16_SSCALED": 26, "16_16_UINT": 27, "16_16_SINT": 28, "16_16_FLOAT": 29, "10_11_11_FLOAT": 30, - "11_11_10_FLOAT": 31, "10_10_10_2_UNORM": 32, "10_10_10_2_SNORM": 33, "10_10_10_2_UINT": 34, - "10_10_10_2_SINT": 35, "2_10_10_10_UNORM": 36, "2_10_10_10_SNORM": 37, "2_10_10_10_USCALED": 38, - "2_10_10_10_SSCALED": 39, "2_10_10_10_UINT": 40, "2_10_10_10_SINT": 41, "8_8_8_8_UNORM": 42, - "8_8_8_8_SNORM": 43, "8_8_8_8_USCALED": 44, "8_8_8_8_SSCALED": 45, "8_8_8_8_UINT": 46, "8_8_8_8_SINT": 47, - "32_32_UINT": 48, "32_32_SINT": 49, "32_32_FLOAT": 50, "16_16_16_16_UNORM": 51, "16_16_16_16_SNORM": 52, - "16_16_16_16_USCALED": 53, "16_16_16_16_SSCALED": 54, "16_16_16_16_UINT": 55, "16_16_16_16_SINT": 56, - "16_16_16_16_FLOAT": 57, "32_32_32_UINT": 58, "32_32_32_SINT": 59, "32_32_32_FLOAT": 60, - "32_32_32_32_UINT": 61, "32_32_32_32_SINT": 62, "32_32_32_32_FLOAT": 63, -} - - -def load_gfx10_names(): - with open(os.path.join(HERE, "gfx10_formats.json"), encoding="utf-8") as f: - raw = json.load(f) - return {int(k): v[len("GFX10_FORMAT_"):] for k, v in raw.items() if 1 <= int(k) <= 77} - - -GFX10_NAMES = load_gfx10_names() # code -> "8_8_8_8_UNORM" - - -def parse_name(name): - """(component widths from bit 0, numeric format). Names list the widths from the top bit down, so the last - number of 2_10_10_10 (50) is the x field in bits 9:0 and 10_10_10_2 (44) has a 2-bit x in bits 1:0.""" - *w, nfmt = name.split("_") - return tuple(int(x) for x in reversed(w)), nfmt - - -def f32_bits(x: float) -> int: - return struct.unpack(" int: - """f32 bits of a non-negative fraction, correctly rounded (ties to even).""" - if q == 0: - return 0 - num, den = q.numerator, q.denominator - e = num.bit_length() - den.bit_length() - if Fraction(num, den) < Fraction(2) ** e: - e -= 1 # 2^e <= q < 2^(e+1) - e = max(e, -126) - scaled = q / (Fraction(2) ** (e - 23)) # mantissa units of 2^(e-23) - m = scaled.numerator // scaled.denominator - rem = scaled - m - if rem > Fraction(1, 2) or (rem == Fraction(1, 2) and m & 1): - m += 1 - if e == -126 and m < (1 << 23): - return m # denormal range is never reached by these formats - if m >= 1 << 24: - m >>= 1 - e += 1 - return ((e + 127) << 23) | (m - (1 << 23)) - - -def sign_extend(v, w): - return v - (1 << w) if v >> (w - 1) & 1 else v - - -# ---- the model: what a load returns, what a store writes ---- - -# Small unsigned floats: 5 exponent bits, bias 15, no sign. 11 bits carry 6 mantissa bits, 10 bits carry 5. -def ufloat_decode(raw, w): - mbits = w - 5 - e, m = raw >> mbits, raw & ((1 << mbits) - 1) - if e == 31: - return 0x7F800000 | (m << (23 - mbits)) # infinity, or a NaN whose payload moves up unquieted (measured) - if e == 0: - return frac_to_f32(Fraction(m, 1 << mbits) * Fraction(2) ** -14) - return frac_to_f32((1 + Fraction(m, 1 << mbits)) * Fraction(2) ** (e - 15)) - - -def half_decode(raw): - h = struct.unpack("> bit) & ((1 << w) - 1))) - bit += w - n = len(out) - if path == "mtbuf": - return out + [0] * (4 - n) - return [out[c % n] for c in range(4)] - - -def element_size(name): - return sum(parse_name(name)[0]) // 8 - - -# ---- the data: patterns per format ---- - -def edge_values(w, rng): - vals = {0, 1, 2, (1 << w) - 1, (1 << w) - 2, 1 << (w - 1), (1 << (w - 1)) - 1, (1 << (w - 1)) + 1} - vals |= {rng.getrandbits(w) for _ in range(4)} - return sorted(v for v in vals if 0 <= v < 1 << w) - - -def pack(widths, comps, rng, size): - big, bit = 0, 0 - for w, v in zip(widths, comps): - big |= (v & ((1 << w) - 1)) << bit - bit += w - tail = rng.getrandbits(128 - bit) << bit # bytes past the element are random: they must not leak in - return (big | tail).to_bytes(16, "little") - - -def load_patterns(name, rng, budget): - """16-byte elements for one format: every value of each field (all of it up to 12 bits, a 16-bit float's 65536, - edges and random above that) with random other fields, then edge-value combinations and plain random bytes.""" - widths, nfmt = parse_name(name) - size = element_size(name) - elems = [bytes(16), b"\xff" * 16] - for c, w in enumerate(widths): - if w == 32: - values = edge_values(32, rng) + [0x7F800000, 0xFF800000, 0x7FC00000, 0x00000001, 0x80000000, 0x3F800000, - 0xBF800000] + [rng.getrandbits(32) for _ in range(256)] - elif w <= 12 or (w == 16 and nfmt == "FLOAT"): - values = range(1 << w) - else: - values = edge_values(w, rng) + [rng.getrandbits(w) for _ in range(512)] - for v in values: - comps = [rng.getrandbits(x) for x in widths] - comps[c] = v - elems.append(pack(widths, comps, rng, size)) - for _ in range(budget): - comps = [rng.choice(edge_values(w, rng)) for w in widths] - elems.append(pack(widths, comps, rng, size)) - elems.append(rng.getrandbits(128).to_bytes(16, "little")) - return elems - - -def f32_edges(rng): - base = [0.0, -0.0, 1.0, -1.0, 0.5, -0.5, 2.0, 255.0, 255.5, 256.0, 1e-8, -1e-8, 1e30, -1e30, 65504.0, 65505.0, - 65520.0, 65519.0, 131008.0, 1e-5, 6.1e-5, 5.9e-8, 3.0e-8, 1.5, 2.5, 0.49999997, 0.50000006, 100.5, 101.5, - 1023.0, 1023.5, 1024.0, -1023.0, -1024.0, -511.5, 511.5, 512.0, 511.0, 3.0, -3.0, 0.3, -0.3] - bits = [f32_bits(x) for x in base] + [0x7F800000, 0xFF800000, 0x7FC00000, 0xFFC00000, 0x7F800001, 0x00000001, - 0x80000001, 0x007FFFFF, 0x00800000, 0x7F7FFFFF, 0xFF7FFFFF] - return bits + [rng.getrandbits(32) for _ in range(40)] + [f32_bits(rng.uniform(-3, 3)) for _ in range(40)] + \ - [f32_bits(rng.uniform(-300, 300)) for _ in range(40)] + [f32_bits(math.ldexp(rng.uniform(1, 2), rng.randrange(-20, 18))) - for _ in range(60)] - - -def int_edges(rng): - base = [0, 1, 2, 3, 127, 128, 255, 256, 511, 512, 1023, 1024, 2047, 2048, 32767, 32768, 65535, 65536, 0x7FFFFFFF, - 0x80000000, 0xFFFFFFFF, 0xFFFFFFFE, 0xFFFFFF80, 0xFFFFFF7F, 0xFFFFFE00, 0xFFFFFC00, 0xFFFF8000, 0xFFFF7FFF, - 0xFFFFFFFF - 1023, 0xFFFFFFFF - 511, 0xFFFFFFFF - 4095] - return base + [rng.getrandbits(32) for _ in range(60)] + [rng.getrandbits(rng.randrange(1, 17)) for _ in range(60)] + \ - [(-rng.getrandbits(rng.randrange(1, 17))) & 0xFFFFFFFF for _ in range(60)] - - -def store_inputs(name, rng): - """Register values (4 dwords per element) for a store: every channel takes values from the right domain, so a - float format sees f32 edges, an integer format integer edges. Channel 0 sweeps while the others hold other values.""" - widths, nfmt = parse_name(name) - vals = int_edges(rng) if nfmt in ("UINT", "SINT") else f32_edges(rng) - if nfmt in ("UNORM", "SNORM"): - vals += [f32_bits(rng.uniform(-1.1, 1.1)) for _ in range(120)] - vals += [f32_bits(k / ((1 << w) - 1) + d) for w in set(widths) for k in (0, 1, 2, (1 << w) - 2, (1 << w) - 1) - for d in (0.0, 1e-9, -1e-9, 0.5 / ((1 << w) - 1), -0.5 / ((1 << w) - 1))] - elems = [] - for i, v in enumerate(vals): - row = [v] + [vals[(i * 7 + 13 * k + 5) % len(vals)] for k in (1, 2, 3)] - elems.append(row) - elems.append([row[1], v, row[3], row[2]]) - elems.append([row[2], row[3], v, row[1]]) - elems.append([row[3], row[2], row[1], v]) - return elems - - -# ---- the kernels ---- - -SEL_CODES = {"0": 0, "1": 1, "X": 4, "Y": 5, "Z": 6, "W": 7} - - -def v_sharp_word3(arch_family, code, sel="XYZW"): - w3 = sum(SEL_CODES[ch] << (3 * i) for i, ch in enumerate(sel)) | code << 12 | 3 << 28 # DST_SEL, FORMAT, OOB_SELECT = raw - if arch_family == "gfx10": - w3 |= 1 << 23 # RESOURCE_LEVEL - return w3 - - -def _longs(words): - return [f" .long {', '.join(f'0x{w:08x}' for w in words[i:i + 8])}" for i in range(0, len(words), 8)] - - -def vgpr_clear(): - return [f"v_mov_b32 v{8 + i}, 0x{PREFILL + 0x100 + i:08x}" for i in range(4)] - - -def load_lines(uid, family, ref, path, elems): - """Lane i loads element i of the table in the kernel's own code with `buffer_load_format_xyzw`/tbuffer and stores - the four result registers at i * 16. ref: the format code for the V# (mubuf) or the BUF_FMT_ name (mtbuf).""" - code = ref if path == "mubuf" else 22 - w3 = v_sharp_word3(family, code) - lines = ["s_getpc_b64 s[4:5]", f".Lpc{uid}:", f"s_add_u32 s4, s4, .Ldat{uid}-.Lpc{uid}", "s_addc_u32 s5, s5, 0", - "s_mov_b32 s8, s4", "s_and_b32 s9, s5, 0xffff", "s_mov_b32 s10, 0x100000", f"s_mov_b32 s11, 0x{w3:08x}", - "v_lshlrev_b32 v1, 4, v0"] + vgpr_clear() - if path == "mubuf": - lines.append("buffer_load_format_xyzw v[8:11], v1, s[8:11], 0 offen") - else: - lines.append(f"tbuffer_load_format_xyzw v[8:11], v1, s[8:11], 0 format:[BUF_FMT_{ref}] offen") - lines += ["s_waitcnt vmcnt(0)", "global_store_b128 v1, v[8:11], s[2:3]", "s_endpgm", ".p2align 4", f".Ldat{uid}:"] - words = [] - for e in elems: - words += list(struct.unpack("<4I", e)) - return lines + _longs(words) - - -def store_lines(uid, family, ref, path, rows, instr="xyzw", sel="XYZW"): - """Lane i reads its four register values from the table, stores them with `buffer_store_format_` / tbuffer - (instr xyzw or xy: the first two registers) into the output buffer at i * 16 (a V# whose base is the output pointer).""" - regs = "v[8:11]" if instr == "xyzw" else "v[8:9]" - code = ref if path == "mubuf" else 22 - w3 = v_sharp_word3(family, code, sel) - lines = ["s_getpc_b64 s[4:5]", f".Lpc{uid}:", f"s_add_u32 s4, s4, .Ldat{uid}-.Lpc{uid}", "s_addc_u32 s5, s5, 0", - "s_mov_b32 s12, s4", "s_and_b32 s13, s5, 0xffff", "s_mov_b32 s14, 0x100000", f"s_mov_b32 s15, 0x{v_sharp_word3(family, 22):08x}", - "s_mov_b32 s8, s2", "s_and_b32 s9, s3, 0xffff", "s_mov_b32 s10, 0x100000", f"s_mov_b32 s11, 0x{w3:08x}", - "v_lshlrev_b32 v1, 4, v0", "buffer_load_dwordx4 v[8:11], v1, s[12:15], 0 offen", "s_waitcnt vmcnt(0)"] - if path == "mubuf": - lines.append(f"buffer_store_format_{instr} {regs}, v1, s[8:11], 0 offen") - else: - lines.append(f"tbuffer_store_format_{instr} {regs}, v1, s[8:11], 0 format:[BUF_FMT_{ref}] offen") - lines += ["s_endpgm", ".p2align 4", f".Ldat{uid}:"] - words = [] - for r in rows: - words += r - return lines + _longs(words) - - -# ---- running ---- - -CHUNK = 1024 # elements (lanes) per kernel: one workgroup of 1024 threads, 4096 output words - - -def hw_code(family, code, name): - """The format number this GPU family uses for GFX10 format `name` (None: the family has no such format).""" - if family == "gfx10": - return code - return GFX11_CODES.get(name) - - -def run_loads(oracle, family, fmts, path, rng, budget, negative=None): - """-> {code: (cases, mismatches [(element bytes, want words, got words)])}""" - from hw_oracle import asm - jobs, kernels = [], [] - for code, name in fmts: - hc = hw_code(family, code, name) - elems = load_patterns(name, rng, budget) - ref = hc if path == "mubuf" else name - if negative is not None: - ref = negative(code, name, ref) - for lo in range(0, len(elems), CHUNK): - part = elems[lo:lo + CHUNK] - uid = len(kernels) - kernels.append(asm.Kernel(load_lines(uid, family, ref, path, part), 32, len(part), len(part) * 4, raw=True)) - jobs.append((code, name, part)) - results = oracle.run(kernels, words=CHUNK * 4) - out = {} - for (code, name, part), res in zip(jobs, results): - cases, bad = out.setdefault(code, [0, []]) - if isinstance(res, str): - bad.append((b"", [], [res])) - continue - for i, e in enumerate(part): - got = res[4 * i:4 * i + 4] - want = decode_element(name, e, path) - cases += 1 - if not words_equal(got, want, name): - bad.append((e, want, got)) - out[code][0] = cases - return out - - -def words_equal(got, want, name): - """Bit equality, NaN payloads included (the hardware keeps them).""" - return list(got) == list(want) - - -# ---- stores ---- - -def to_f32(bits): - return struct.unpack(" Fraction(1, 2) or (r == Fraction(1, 2) and f & 1): - f += 1 - return f - - -def rne_away(x): - """Round half away from zero of a non-negative Fraction.""" - return (x + Fraction(1, 2)).__floor__() - - -def small_float_encode(bits, mbits, signed): - """f32 bits -> a 5-exponent-bit float with `mbits` mantissa bits (and a sign bit when `signed`), truncating the - mantissa (round toward zero, measured). Overflow, NaN and the sign of an unsigned format: see the measurements.""" - x = to_f32(bits) - sign = (0x8000 if signed else 0) if bits >> 31 else 0 - if math.isnan(x): - return sign | (31 << mbits) | ((bits >> (23 - mbits) & ((1 << mbits) - 1)) or 1) # a payload that shifts out stays a NaN - if not signed and bits >> 31: - return 0 - if math.isinf(x): - return sign | (31 << mbits) - q = abs(Fraction(x)) - if q == 0: - return sign - e = q.numerator.bit_length() - q.denominator.bit_length() - if q < Fraction(2) ** e: - e -= 1 - if e < -14: # denormal: multiples of 2^(-14 - mbits) - return sign | (q / Fraction(2) ** (-14 - mbits)).__floor__() - m = ((q / Fraction(2) ** e - 1) * (1 << mbits)).__floor__() - if e > 15: - return sign | (30 << mbits) | ((1 << mbits) - 1) # too large for the format: the largest finite value - return sign | ((e + 15) << mbits) | m - - -def ufloat_encode(bits, w): - return small_float_encode(bits, w - 5, False) - - -def half_encode(bits): - return small_float_encode(bits, 10, True) - - -def encode_field(nfmt, w, reg): - if nfmt in ("UINT", "SINT"): - if nfmt == "UINT": - return min(reg, (1 << w) - 1) - s = reg - (1 << 32) if reg >> 31 else reg - return max(-(1 << (w - 1)), min((1 << (w - 1)) - 1, s)) & ((1 << w) - 1) - if nfmt == "FLOAT": - if w == 32: - return reg - if w == 16: - return half_encode(reg) - return ufloat_encode(reg, w) - if nfmt == "USCALED": # measured on gfx1150: a store converts a SCALED format as its NORM one - nfmt = "UNORM" - elif nfmt == "SSCALED": - nfmt = "SNORM" - x = to_f32(reg) - if math.isnan(x): - return 0 - fx = Fraction(x) if not math.isinf(x) else Fraction(1 << 40) * (1 if x > 0 else -1) - if nfmt == "UNORM": - return rne(max(Fraction(0), min(Fraction(1), fx)) * ((1 << w) - 1)) - if nfmt == "SNORM": - v = max(Fraction(-1), min(Fraction(1), fx)) * ((1 << (w - 1)) - 1) - return (-rne_away(-v) if v < 0 else rne_away(v)) & ((1 << w) - 1) - if nfmt == "USCALED": - return max(0, min((1 << w) - 1, rne(fx))) - if nfmt == "SSCALED": - return max(-(1 << (w - 1)), min((1 << (w - 1)) - 1, rne(fx))) & ((1 << w) - 1) - raise ValueError(nfmt) - - -def encode_element(name, regs, instr="xyzw", route="mubuf", sel="XYZW"): - """The bytes a store of registers x, y, z, w writes (the element's size; nothing else is touched). instr "xy" gives - only x and y (z and w are 0). route "mubuf" (`buffer_store_format_*`, the format from the V#): component c takes - channel c, except a two-component format, whose second component is channel y when the V#'s DST_SEL is Y in y and a - constant (0 or 1) in z (the runtime's XY01), channel w otherwise (identity XYZW: `_xy` then writes (x, 0)). Measured - on the Radeon 880M (gfx1150) for sixteen selector sets and on a real RDNA2, gfx1036 (@AwkGrep256, #2022: XYZW; the - narrow-integer fixtures: XY01). route "mtbuf" (`tbuffer_store_format_*`): component c takes channel c.""" - widths, nfmt = parse_name(name) - chan = list(regs[:4]) if instr == "xyzw" else list(regs[:2]) + [0, 0] - if route == "mubuf" and len(widths) == 2: - chan = [chan[0], chan[1] if sel[1] == "Y" and sel[2] in "01" else chan[3]] - big, bit = 0, 0 - for c, w in enumerate(widths): - big |= encode_field(nfmt, w, chan[c]) << bit - bit += w - return big.to_bytes(bit // 8, "little") - - -def run_stores(oracle, family, fmts, path, rng, instr="xyzw", sel="XYZW"): - """-> {code: [elements, mismatches, 0]}. A mismatch is a store that differs from the model of its route.""" - from hw_oracle import asm - jobs, kernels = [], [] - for code, name in fmts: - hc = hw_code(family, code, name) - rows = store_inputs(name, rng) - ref = hc if path == "mubuf" else name - for lo in range(0, len(rows), CHUNK): - part = rows[lo:lo + CHUNK] - uid = len(kernels) - kernels.append(asm.Kernel(store_lines(uid, family, ref, path, part, instr, sel), 32, len(part), len(part) * 4, raw=True)) - jobs.append((code, name, part)) - results = oracle.run(kernels, words=CHUNK * 4) - out = {} - for (code, name, part), res in zip(jobs, results): - rec = out.setdefault(code, [0, [], 0]) - if isinstance(res, str): - rec[1].append((b"", b"", res.encode())) - continue - size = element_size(name) - for i, row in enumerate(part): - got = struct.pack("<4I", *res[4 * i:4 * i + 4]) - want = bytearray(struct.pack("<4I", *([PREFILL] * 4))) - want[:size] = encode_element(name, row, instr, path, sel) - rec[0] += 1 - if bytes(want) != got: - rec[1].append((row, bytes(want), got)) - return out - - -# ---- the command line ---- - -GFX10_ONLY = tuple(c for c, n in GFX10_NAMES.items() if n not in GFX11_CODES) # 30..35, 37..42: no GFX11 spelling - - -def select_formats(spec, family="gfx11"): - """The formats to run: the ones in `spec`, else every code the GPU family has (GFX10: all 77, GFX11: the 63 that have a - GFX11 spelling).""" - codes = {n: c for c, n in GFX10_NAMES.items()} - if not spec: - return [(c, n) for c, n in GFX10_NAMES.items() if family == "gfx10" or n in GFX11_CODES] - out = [] - for tok in spec.split(","): - tok = tok.strip() - code = int(tok) if tok.isdigit() else codes.get(tok) - if code not in GFX10_NAMES: - raise ValueError(f"unknown format {tok!r}; give a GFX10 code (1..77) or name such as 8_8_8_8_UNORM") - out.append((code, GFX10_NAMES[code])) - return out - - -def self_test(): - """The MODEL on values worked out by hand, and round trips; no GPU.""" - problems = [] - - def check(cond, what): - if not cond: - problems.append(what) - - one11 = 15 << 6 - check(decode_element("8_8_8_8_UNORM", bytes([0, 255, 128, 51]))[:4] == [0, 0x3F800000, frac_to_f32(Fraction(128, 255)), - frac_to_f32(Fraction(51, 255))], "unorm8") - check(decode_element("8_SINT", bytes([0xFF]))[0] == 0xFFFFFFFF, "8_SINT -1") - check(decode_element("8_SSCALED", bytes([0x80]))[0] == 0xC3000000, "8_SSCALED -128.0") - check(decode_element("10_11_11_FLOAT", one11.to_bytes(4, "little"))[0] == 0x3F800000, "11 bit float 1.0") - check(decode_element("10_11_11_FLOAT", (0x7C1).to_bytes(4, "little"))[0] == 0x7F820000, "11 bit float NaN payload") - check(decode_element("10_11_11_FLOAT", b"\1\0\0\0")[0] == 0x35800000, "11 bit float denormal 2^-20") - check(decode_element("8_UNORM", b"\x33")[:4] == [frac_to_f32(Fraction(51, 255))] * 4, "missing channels repeat") - check(decode_element("8_UNORM", b"\x33", "mtbuf")[1:] == [0, 0, 0], "tbuffer: the rest is 0") - check(encode_element("10_11_11_FLOAT", [0x3F800000, 0, 0, 0])[:2] == one11.to_bytes(2, "little"), "encode 1.0") - check(encode_field("FLOAT", 11, 0xBF800000) == 0, "negative to an unsigned float is 0") - check(encode_field("FLOAT", 11, 0x47800000) == 0x7BF, "too large is the largest finite value") - check(encode_field("SNORM", 2, 0x3F000000) == 1 and encode_field("SNORM", 2, 0xBF000000) == 3, "2 bit SNORM ties away") - check(encode_field("USCALED", 8, 0x3F800000) == 255, "a SCALED store converts as NORM") - check(encode_field("SINT", 8, 0x80000000) == 0x80 and encode_field("UINT", 8, 0x1FF) == 0xFF, "integer stores saturate") - rng = random.Random(1) - for code, name in GFX10_NAMES.items(): # decode -> encode -> decode is stable for every format - widths, nfmt = parse_name(name) - if nfmt in ("USCALED", "SSCALED"): - continue - for e in load_patterns(name, rng, 2)[:200]: - d = decode_element(name, e) - if nfmt == "FLOAT" and any((x & 0x7F800000) == 0x7F800000 for x in d[:len(widths)]): - continue # inf and NaN do not round trip through RTZ and saturation - re_ = encode_element(name, d) - d2 = decode_element(name, re_ + bytes(16 - len(re_))) - if nfmt == "SNORM": - continue # -1.0 decodes from two codes; stored once as the symmetric one - check(d2 == d, f"round trip {name} {e[:len(re_)].hex()} -> {re_.hex()}") - if problems: - break - for p in problems: - print("SELF-TEST FAIL:", p) - print("self-test:", "FAILED" if problems else "ok") - return 1 if problems else 0 - - -def negative_control(oracle, family, rng): - """The hardware must disagree with a kernel whose V# names another format (a model that was never compared - with real words would pass this too).""" - fmts = select_formats("8_8_8_8_UNORM,16_16_SNORM,10_11_11_FLOAT,2_10_10_10_UINT,32_32_FLOAT") - swapped = run_loads(oracle, family, fmts, "mubuf", rng, 8, negative=lambda c, n, ref: 22 if ref != 22 else 21) - ok = True - for code, name in fmts: - cases, bad = swapped[code] - ok &= len(bad) > 0 - print(f" wrong V# format for {name}: {len(bad)} of {cases} elements differ ({'caught' if bad else 'NOT CAUGHT'})") - return 0 if ok else 1 - - -def report(title, results, fmts): - """Prints a line per format; returns (validated elements, mismatches, known-difference elements).""" - bad_total = cases_total = known_total = 0 - for code, name in fmts: - cases, bad, *rest = results[code] - known = rest[0] if rest else 0 - cases_total += cases - known - known_total += known - bad_total += len(bad) - note = f" (+{known} known difference)" if known else "" - print(f" {title:<14} {code:>3} {name:<22} {cases - known:>7} validated {'ok' if not bad else f'MISMATCH {len(bad)}'}{note}") - for first, want, got in bad[:3]: - shown = first.hex() if isinstance(first, bytes) else [f"{w:08x}" for w in first] - print(" ", shown, want if isinstance(want, bytes) else [f"{w:08x}" for w in want], - got if isinstance(got, bytes) else [f"{w:08x}" if isinstance(w, int) else w for w in got]) - return cases_total, bad_total, known_total - - -def main(): - ap = argparse.ArgumentParser(description="Buffer data formats on the GPU against the CPU model.") - ap.add_argument("--oracle", default="", help="hw: run the kernels on the AMD GPU through tools/hw_oracle/") - ap.add_argument("--mode", choices=("load", "store", "all"), default="all") - ap.add_argument("--path", choices=("mubuf", "mtbuf", "both"), default="both") - ap.add_argument("--formats", default="", help="GFX10 codes or names, comma separated (default: every GFX10 code " - "the GPU family has)") - ap.add_argument("--seed", type=int, default=1) - ap.add_argument("--budget", type=int, default=40, help="random elements per format on top of the sweeps") - ap.add_argument("--hw-arch", default=None) - ap.add_argument("--negative-control", action="store_true") - ap.add_argument("--self-test", action="store_true") - a = ap.parse_args() - if a.self_test: - return self_test() - if a.oracle != "hw": - ap.error("--oracle hw or --self-test") - # An explicit --formats needs no GPU to be parsed: a typo is a usage error here, before the oracle is opened - # (it used to be reported only after it, or masked by "hardware oracle unavailable" without one). - explicit = None - if a.formats: - try: - explicit = select_formats(a.formats) - except ValueError as e: - ap.error(str(e)) - from hw_oracle import runner, asm - try: - oracle = runner.open_oracle(arch=a.hw_arch) - except runner.Unavailable as e: - print(f"hardware oracle unavailable: {e}") - return 77 - try: - family = asm.family(oracle.arch) - fmts = explicit if explicit is not None else select_formats("", family) - if family == "gfx12": - print("GFX12 numbers its formats again; not built here") - return 77 - print(f"hardware oracle: {oracle.device} ({oracle.arch}, {family} format numbers)") - if family == "gfx11": - print("note: GFX11 is RDNA3 or newer, not RDNA2: a match supports the model and does not prove RDNA2; " - f"GFX10-only codes {', '.join(map(str, GFX10_ONLY))} cannot be run here") - fmts = [(c, n) for c, n in fmts if n in GFX11_CODES] - if not a.negative_control and not fmts: - print("no requested formats can run on GFX11 (all are GFX10-only)") - return 77 - rng = random.Random(a.seed) - if a.negative_control: - return negative_control(oracle, family, rng) - paths = ("mubuf", "mtbuf") if a.path == "both" else (a.path,) - total = bad = known = 0 - for path in paths: - if a.mode in ("load", "all"): - c, b_, k = report(f"load {path}", run_loads(oracle, family, fmts, path, rng, a.budget), fmts) - total, bad, known = total + c, bad + b_, known + k - if a.mode in ("store", "all"): - for instr in ("xyzw", "xy"): - c, b_, k = report(f"store {instr} {path}", run_stores(oracle, family, fmts, path, rng, instr), fmts) - total, bad, known = total + c, bad + b_, known + k - if path == "mubuf": # the runtime's selectors for a two-component format: X, Y, 0, 1 - two = [(c_, n_) for c_, n_ in fmts if len(parse_name(n_)[0]) == 2] - for instr in ("xyzw", "xy"): - c, b_, k = report(f"store {instr} XY01", run_stores(oracle, family, two, path, rng, instr, "XY01"), two) - total, bad, known = total + c, bad + b_, known + k - print(f"{total} validated elements, {bad} mismatches" + (f"; plus {known} known-difference elements" if known else "")) - return 1 if bad else 0 - finally: - oracle.close() - - -if __name__ == "__main__": - try: # a redirected stdout is strict ANSI code page under -I; write '?' for what it cannot encode - sys.stdout.reconfigure(errors="replace") - except (AttributeError, ValueError, OSError): - pass - sys.exit(main()) diff --git a/tools/buffer_store_probe.py b/tools/buffer_store_probe.py deleted file mode 100644 index 8505967f6..000000000 --- a/tools/buffer_store_probe.py +++ /dev/null @@ -1,405 +0,0 @@ -r"""Measure RDNA2 (GFX10) typed buffer store rounding and 2-component DST_SEL swizzling natively (SHADER-364). - -Two questions left open by #2022 (measured on RDNA3.5 gfx1150, needing RDNA2 gfx103x data): -1. UNORM/SNORM store rounding: does hardware round the exact product clamp(x) * scale once (0.3 * 65535 -> 19661) - with ties away from zero, or double-round through an intermediate f32 multiply (0.3 * 65535 -> 19660)? -2. 2-component buffer_store_format_xyzw channel mapping: why did gfx1150 write (x, w) instead of (x, y)? - This probe sweeps all 12 2-component formats in FORMATS with XY01 (runtime RG) and XYZW, plus all 216 valid - (DST_SEL_X, DST_SEL_Y, DST_SEL_Z) triples on 32_32_UINT, for both MUBUF (buffer_store_format_*) and MTBUF - (tbuffer_store_format_*), in wave32 and wave64. - -Usage: - python -I tools/buffer_store_probe.py [--waves 32,64] [--json out.json] - python -I tools/buffer_store_probe.py --self-test # pure-Python model checks, no GPU - -Exit 0 when the sweep ran and matched the model (or --self-test passed), 1 on a wave32/wave64, model, or -report-write error, 2 on a harness or CLI argument error, 77 when tools/hw_oracle is unavailable or the GPU is -not GFX10. Standard library only; nothing here reads game files. -""" -import argparse -import itertools -import json -import os -import struct -import sys -from fractions import Fraction - -HERE = os.path.dirname(os.path.abspath(__file__)) -sys.dont_write_bytecode = True -if HERE not in sys.path: - sys.path.insert(0, HERE) - -# (name, GFX10 format code, kind, x channel bits) -NORM_FORMATS = ( - ("unorm16", 7, "unorm", 16), - ("snorm16", 8, "snorm", 16), - ("unorm8", 1, "unorm", 8), - ("snorm8", 2, "snorm", 8), - ("unorm10", 50, "unorm", 10), -) - -# All 12 2-component formats in Gen.FORMATS: (name, code, kind, element_mask_or_None_for_64bit) -TWO_COMP_FORMATS = ( - ("8_8_UNORM", 14, "unorm", 0xFFFF), - ("8_8_SNORM", 15, "snorm", 0xFFFF), - ("8_8_UINT", 18, "uint", 0xFFFF), - ("8_8_SINT", 19, "sint", 0xFFFF), - ("16_16_UNORM", 23, "unorm", 0xFFFFFFFF), - ("16_16_SNORM", 24, "snorm", 0xFFFFFFFF), - ("16_16_UINT", 27, "uint", 0xFFFFFFFF), - ("16_16_SINT", 28, "sint", 0xFFFFFFFF), - ("16_16_FLOAT", 29, "f16", 0xFFFFFFFF), - ("32_32_UINT", 62, "u32", None), - ("32_32_SINT", 63, "i32", None), - ("32_32_FLOAT", 64, "f32", None), -) - -SEL_VALS = (0, 1, 4, 5, 6, 7) -SEL_XY01 = (4, 5, 0, 1) -SEL_XYZW = (4, 5, 6, 7) -SEL_X001 = (4, 0, 0, 1) - - -def f32_to_u32(val): - return struct.unpack("= 0: - return int(frac + Fraction(1, 2)) - return -int(-frac + Fraction(1, 2)) - - -def model_norm(u_bits, kind, bits): - """Exact single-rounded UNORM/SNORM encoding (ties away from zero, NaN -> 0).""" - f = u32_to_f32(u_bits) - if f != f: - return 0 - mask = (1 << bits) - 1 - if kind == "unorm": - if f <= 0.0: - return 0 - if f >= 1.0: - return mask - return round_half_away(Fraction(f) * mask) - scale = (1 << (bits - 1)) - 1 - if f <= -1.0: - return (-scale) & mask - if f >= 1.0: - return scale - return round_half_away(Fraction(f) * scale) & mask - - -def model_norm_double(u_bits, kind, bits): - """Double-rounded f32-multiply + RoundEven encoding (pre-SHADER-364 translator behaviour).""" - f = u32_to_f32(u_bits) - if f != f: - return 0 - mask = (1 << bits) - 1 - if kind == "unorm": - f = max(0.0, min(1.0, f)) - prod = u32_to_f32(f32_to_u32(f * float(mask))) - return int(round(prod)) - scale = (1 << (bits - 1)) - 1 - f = max(-1.0, min(1.0, f)) - prod = u32_to_f32(f32_to_u32(f * float(scale))) - return int(round(prod)) & mask - - -def model_2comp_channels(sel, comps): - """Hardware 2-component MUBUF store COMP_SWAP rule from V# DST_SEL (sx, sy, sz, sw). - - comps is the 4-tuple (x, y, z, w) padded with 0 for absent store components. - Returns (mem_ch0, mem_ch1). - """ - sx, sy, sz, _sw = sel - use_y = (sy >= 4) and (sz < 4) - rev = (sx != 4) and ((sy >= 4) or (sz >= 4)) - sec = comps[1] if use_y else comps[3] - return (sec, comps[0]) if rev else (comps[0], sec) - - -def norm_inputs(kind, bits): - """Specials + inputs near (k + 0.5) / scale that expose double rounding.""" - scale = (1 << bits) - 1 if kind == "unorm" else (1 << (bits - 1)) - 1 - out = [ - 0x00000000, 0x80000000, 0x00000001, 0x80000001, - 0x007FFFFF, 0x807FFFFF, 0x00800000, 0x80800000, - f32_to_u32(0.5), f32_to_u32(-0.5), - f32_to_u32(0.3), f32_to_u32(-0.3), - f32_to_u32(1.0), f32_to_u32(-1.0), - f32_to_u32(1.5), f32_to_u32(-1.5), - 0x7F800000, 0xFF800000, 0x7FC00000, 0xFFC00000, - 0x7F800001, 0xFF800001, - ] - step = max(1, scale // 100) - for k in range(0, scale, step): - base = f32_to_u32((k + 0.5) / scale) - for d in (-1, 0, 1): - out.append(base + d) - if kind == "snorm": - out.append((base + d) | 0x80000000) - return out - - -def _store_kernel(asm_mod, inst, code, sel, vals, wave): - n_comp = len(inst.rsplit("_", 1)[1]) - vreg = "v4" if n_comp == 1 else f"v[4:{3 + n_comp}]" - st = (f"{inst} {vreg}, v1, s[8:11], 0 offen glc" if inst.startswith("buffer_") - else f"{inst} {vreg}, v1, s[8:11], 0 format:{code} offen glc") - lines = [ - "v_mov_b32 v1, 0", - "s_mov_b32 s8, s2", - "s_and_b32 s9, s3, 0xffff", - "s_mov_b32 s10, 0x100", - f"s_mov_b32 s11, 0x{vsharp_d3(code, sel):x}", - ] - for i, v in enumerate(vals[:n_comp]): - lines.append(f"v_mov_b32 v{4 + i}, 0x{v:x}") - lines += [st, "s_waitcnt_vscnt null, 0x0", "s_endpgm"] - return asm_mod.Kernel(lines, wave, 1, 2, raw=True, vgprs=12, sgprs=16) - - -def probe_norm(oracle, asm_mod, wave): - """Run UNORM/SNORM rounding sweep + SNORM2 tie check in wave32 or wave64.""" - report = {} - for name, code, kind, bits in NORM_FORMATS: - inputs = norm_inputs(kind, bits) - mask = (1 << bits) - 1 - sel = SEL_XYZW if bits == 10 else SEL_X001 - fmt_res = {} - for inst in ("buffer_store_format_x", "tbuffer_store_format_x"): - ks = [_store_kernel(asm_mod, inst, code, sel, (u,), wave) for u in inputs] - got = oracle.run(ks, words=2) - exact_ok = double_diffs = 0 - first_bad = None - for u, words in zip(inputs, got): - if isinstance(words, str) or len(words) < 2: - raise RuntimeError(f"{name} {inst} wave{wave}: {words}") - hw = words[0] & mask - want = model_norm(u, kind, bits) - dbl = model_norm_double(u, kind, bits) - if want != dbl: - double_diffs += 1 - if hw == want: - exact_ok += 1 - elif first_bad is None: - first_bad = {"f32": f"{u:#010x}", "hw": hw, "want": want, "double": dbl} - fmt_res[inst] = {"inputs": len(inputs), "exact": exact_ok, "double_witnesses": double_diffs, - "first_mismatch": first_bad} - report[name] = fmt_res - # SNORM2 tie-breaking on code 45 (10_10_10_2_SNORM: 2-bit x at bits [1:0]) - tie_vals = (f32_to_u32(0.5), f32_to_u32(-0.5), f32_to_u32(0.5) - 1, f32_to_u32(-0.5) - 1) - ks = [_store_kernel(asm_mod, "buffer_store_format_xyzw", 45, SEL_XYZW, (u, 0, 0, 0), wave) for u in tie_vals] - got = oracle.run(ks, words=2) - tie_ok = sum((w[0] & 3) == model_norm(u, "snorm", 2) for u, w in zip(tie_vals, got)) - report["snorm2_ties"] = {"inputs": len(tie_vals), "exact": tie_ok, - "half_pos": got[0][0] & 3, "half_neg": got[1][0] & 3} - return report - - -def probe_two_comp(oracle, asm_mod, wave): - """Run all 12 2-component formats (XY01 vs XYZW, MUBUF vs MTBUF) + all 216 (sx,sy,sz) triples on 32_32_UINT.""" - int_vals = (0x11, 0x22, 0x33, 0x44) - flt_vals = (f32_to_u32(0.25), f32_to_u32(0.5), f32_to_u32(0.75), f32_to_u32(1.0)) - formats_ok = 0 - format_mismatches = [] - for fname, code, kind, mask in TWO_COMP_FORMATS: - vals = flt_vals if kind in ("unorm", "snorm", "f16", "f32") else int_vals - cases = ( - ("mubuf_xy_XY01", "buffer_store_format_xy", SEL_XY01), - ("mubuf_xyzw_XY01", "buffer_store_format_xyzw", SEL_XY01), - ("mubuf_xy_XYZW", "buffer_store_format_xy", SEL_XYZW), - ("mubuf_xyzw_XYZW", "buffer_store_format_xyzw", SEL_XYZW), - ("mtbuf_xyzw_XYZW", "tbuffer_store_format_xyzw", SEL_XYZW), - ) - ks = [_store_kernel(asm_mod, inst, code, sel, vals, wave) for _, inst, sel in cases] - got = oracle.run(ks, words=2) - if any(isinstance(w, str) or len(w) < 2 for w in got): - raise RuntimeError(f"{fname} wave{wave}: {got}") - # Reference: mubuf_xy_XY01 == mubuf_xyzw_XY01 == mtbuf_xyzw_XYZW == (x, y), - # mubuf_xy_XYZW == (x, 0), mubuf_xyzw_XYZW == (x, w) (distinct from (x, y) and (x, 0)) - def elem(w): - return (w[0] & mask,) if mask is not None else (w[0], w[1]) - xy_xy01, xyzw_xy01, xy_xyzw, xyzw_xyzw, mt_xyzw = (elem(w) for w in got) - if xy_xy01 == xyzw_xy01 == mt_xyzw and xy_xyzw != xy_xy01 and xyzw_xyzw != xy_xy01 and xyzw_xyzw != xy_xyzw: - formats_ok += 1 - else: - format_mismatches.append({"format": fname, "xy_xy01": xy_xy01, "xyzw_xy01": xyzw_xy01, - "xy_xyzw": xy_xyzw, "xyzw_xyzw": xyzw_xyzw, "mt_xyzw": mt_xyzw}) - # Exhaustive 216 (sx, sy, sz) triples on 32_32_UINT (code 62) - triples = list(itertools.product(SEL_VALS, repeat=3)) - ks = [_store_kernel(asm_mod, "buffer_store_format_xyzw", 62, (sx, sy, sz, 1), int_vals, wave) - for sx, sy, sz in triples] - got = oracle.run(ks, words=2) - triples_ok = 0 - triple_bad = [] - for (sx, sy, sz), w in zip(triples, got): - if isinstance(w, str) or len(w) < 2: - raise RuntimeError(f"32_32_UINT ({sx},{sy},{sz}) wave{wave}: {w}") - want = model_2comp_channels((sx, sy, sz, 1), int_vals) - if (w[0], w[1]) == want: - triples_ok += 1 - elif len(triple_bad) < 4: - triple_bad.append({"sel": [sx, sy, sz, 1], "hw": [w[0], w[1]], "want": list(want)}) - return { - "formats_total": len(TWO_COMP_FORMATS), - "formats_ok": formats_ok, - "format_mismatches": format_mismatches, - "triples_total": len(triples), - "triples_ok": triples_ok, - "triple_mismatches": triple_bad, - } - - -def self_test(): - # Double-rounding witness: UNORM16(0.3) -> exact 19661, double-rounded 19660 - u03 = f32_to_u32(0.3) - assert model_norm(u03, "unorm", 16) == 19661 - assert model_norm_double(u03, "unorm", 16) == 19660 - # SNORM2 ties away from zero - assert model_norm(f32_to_u32(0.5), "snorm", 2) == 1 - assert model_norm(f32_to_u32(-0.5), "snorm", 2) == 3 - assert model_norm(0x7FC00000, "unorm", 16) == 0 - assert model_norm(0xFFC00000, "snorm", 16) == 0 - # 2-component COMP_SWAP truth table - c = (0x11, 0x22, 0x33, 0x44) - assert model_2comp_channels(SEL_XY01, c) == (0x11, 0x22) - assert model_2comp_channels((5, 4, 0, 1), c) == (0x22, 0x11) - assert model_2comp_channels(SEL_XYZW, c) == (0x11, 0x44) - assert model_2comp_channels((5, 4, 6, 7), c) == (0x44, 0x11) - assert model_2comp_channels(SEL_XYZW, (0x11, 0x22, 0, 0)) == (0x11, 0) - # Every norm format must have at least one double-rounding witness - for name, _code, kind, bits in NORM_FORMATS: - w = sum(model_norm(u, kind, bits) != model_norm_double(u, kind, bits) for u in norm_inputs(kind, bits)) - assert w > 0, f"{name} has no double-rounding witness" - print("self-test OK") - - -def parse_waves(raw): - """Parse --waves into a list of supported wave sizes (32, 64), or return (None, err_msg).""" - tokens = [w.strip() for w in raw.split(",") if w.strip()] - if not tokens: - return None, "--waves must not be empty" - waves = [] - for tok in tokens: - try: - w = int(tok) - except ValueError: - return None, f"invalid wave size {tok!r} (expected 32 or 64)" - if w not in (32, 64): - return None, f"unsupported wave size {w} (expected 32 or 64)" - waves.append(w) - return waves, None - - -def validate_json_path(path): - """Return an error string if `path` cannot be used as a --json output file, or None.""" - if not path or not path.strip(): - return "--json path must not be empty" - if "\x00" in path: - return "--json path contains a NUL byte" - if path.endswith(os.sep) or (os.altsep and path.endswith(os.altsep)) or os.path.isdir(path): - return f"--json path is a directory: {path}" - cur = os.path.dirname(os.path.abspath(path)) - while cur: - if os.path.isdir(cur): - break - if os.path.lexists(cur): - return f"--json parent is not a directory: {cur}" - nxt = os.path.dirname(cur) - if nxt == cur: - break - cur = nxt - return None - - -def write_json_report(path, data): - """Create missing parent directories and write `data` as LF-terminated JSON, or return an error string.""" - parent = os.path.dirname(os.path.abspath(path)) - if parent: - try: - os.makedirs(parent, exist_ok=True) - except OSError as e: - return f"cannot create directory for --json {path}: {e.strerror or e}" - try: - with open(path, "w", encoding="utf-8", newline="\n") as f: - json.dump(data, f, indent=2) - except OSError as e: - return f"cannot write --json {path}: {e.strerror or e}" - return None - - -def main(argv=None): - if hasattr(sys.stdout, "reconfigure"): - sys.stdout.reconfigure(encoding="utf-8", errors="replace") - ap = argparse.ArgumentParser(description=__doc__.splitlines()[0]) - ap.add_argument("--waves", default="32,64", help="wave sizes to run (default: 32,64)") - ap.add_argument("--json", dest="json_out", help="write full JSON report to this path") - ap.add_argument("--self-test", action="store_true", help="check the Python models without a GPU") - args = ap.parse_args(argv) - if args.self_test: - self_test() - return 0 - waves, err = parse_waves(args.waves) - if err: - print(f"error: {err}", file=sys.stderr) - return 2 - if args.json_out is not None: - err = validate_json_path(args.json_out) - if err: - print(f"error: {err}", file=sys.stderr) - return 2 - from hw_oracle import asm, runner - try: - oracle = runner.open_oracle() - except runner.Unavailable as exc: - print(f"SKIP: {exc}", file=sys.stderr) - return 77 - if asm.family(oracle.arch) != "gfx10": - print(f"SKIP: {oracle.arch} is not GFX10 (RDNA1/RDNA2)", file=sys.stderr) - return 77 - out = {"arch": oracle.arch, "waves": {}} - mismatches = 0 - for wave in waves: - norm = probe_norm(oracle, asm, wave) - two = probe_two_comp(oracle, asm, wave) - out["waves"][str(wave)] = {"norm": norm, "two_comp": two} - sweeps = [(f"{name} {inst}", info) for name, *_ in NORM_FORMATS for inst, info in norm[name].items()] - bad_sweeps = [(label, info) for label, info in sweeps if info["exact"] != info["inputs"]] - mismatches += len(bad_sweeps) - ties = norm["snorm2_ties"] - if ties["exact"] != ties["inputs"]: - mismatches += 1 - if two["formats_ok"] != two["formats_total"] or two["triples_ok"] != two["triples_total"]: - mismatches += 1 - print(f"wave{wave} ({oracle.arch}): norm {len(sweeps) - len(bad_sweeps)}/{len(sweeps)} sweeps exact across " - f"{len(NORM_FORMATS)} formats, snorm2 ties {ties['exact']}/{ties['inputs']}, " - f"2-comp {two['formats_ok']}/{two['formats_total']} formats, " - f"{two['triples_ok']}/{two['triples_total']} DST_SEL triples") - for label, info in bad_sweeps: - first = info["first_mismatch"] - print(f" {label}: {info['exact']}/{info['inputs']} exact, first mismatch f32 {first['f32']} " - f"hw {first['hw']} want {first['want']} (double-rounded {first['double']})") - if args.json_out is not None: - err = write_json_report(args.json_out, out) - if err: - print(f"error: {err}", file=sys.stderr) - return 1 - return 1 if mismatches else 0 - - -if __name__ == "__main__": - if hasattr(sys.stdout, "reconfigure"): - sys.stdout.reconfigure(errors="replace") - raise SystemExit(main()) diff --git a/tools/buffer_swizzle_probe.py b/tools/buffer_swizzle_probe.py deleted file mode 100644 index 520fc5432..000000000 --- a/tools/buffer_swizzle_probe.py +++ /dev/null @@ -1,668 +0,0 @@ -r"""SHADER-343: Native RDNA2 hardware probe for swizzled buffer addressing (V# SWIZZLE_ENABLE, ADD_TID_ENABLE). - -Runs self-contained MUBUF/MTBUF buffer-swizzle kernels natively on an AMD GPU through tools/hw_oracle (wave32 and -wave64) and compares every output word with Leonida's live translator (tools/rdna2spirv.py -> -tests/semantic/spirv_mini_interp.py). Standard library only; no game files. - -Groups covered (docs/design.md, Swizzled buffer addressing): - swizzle_basic IS=8/16/32/64 formula, index >= IS, non-4-mult stride, inst_offset, mode 0 soffset, stride 0 - idxen_ignores_tid idxen=1 ignores ADD_TID_ENABLE (linear & swizzled, address & bounds, load/typed/atomic) - swizzle_activation SWIZZLE_ENABLE=1 with idxen=0 and ADD_TID_ENABLE=0 stays linear and RAW in mode 3 - multi_dword_stepping scratch swizzle (+4*IS) vs indexed swizzle (+4 linear, crossing IS), loads/stores & per-dword OOB - typed_and_atomic_x2 scratch swizzle suppresses typed >4B & atomic_*_x2 even in mode 2; indexed swizzle steps +4 - oob_mode3_soffset OOB_SELECT 3 with active swizzle and stride != 0 checks (index + soffset) >= num_records - offset_wrap uint32(voff + inst_offset) wraps at 32 bits; RAW mode 3 uint64(off) + uint64(soff) does not - add_tid_wave_lane 64-thread ADD_TID_ENABLE wraps at wave lane 32 on wave32 vs 64 on wave64 - -Usage: - python -I tools/buffer_swizzle_probe.py # translator side only (CPU) - python -I tools/buffer_swizzle_probe.py --oracle hw # native AMD GPU only (wave32 + wave64) - python -I tools/buffer_swizzle_probe.py --oracle both # compare hardware vs translator - python -I tools/buffer_swizzle_probe.py --oracle both --strict # fail on known divergences too - python -I tools/buffer_swizzle_probe.py --self-test - -Exit codes: - 0 all unexpected comparisons match (and wave32 == wave64 on wave-invariant cases) - 1 at least one unexpected mismatch, unexpected wave32/64 diff, or known divergence under --strict - 2 bad CLI arguments or harness error - 77 hardware oracle requested but unavailable on this machine -""" -import argparse -import json -import os -import struct -import sys -import tempfile -import warnings - -HERE = os.path.dirname(os.path.abspath(__file__)) -ROOT = os.path.dirname(HERE) -sys.dont_write_bytecode = True -for p in (HERE, os.path.join(ROOT, "tests", "semantic")): - if p not in sys.path: - sys.path.insert(0, p) - -import rdna2spirv # noqa: E402 -import spirv_mini_interp # noqa: E402 - -# Buffer layout in the allocated buffer (s[0:3] RAW V# at offset 0): -# 0x000..0x0FF (64 dwords): output words out[0..63] -# 0x100..0x7FF (448 dwords): data region DATA_BASE (s[16:17]), seeded with 0x5EED0000 + offset -OUT_WORDS = 512 -DATA_OFF = 0x100 -DATA_DWORDS = OUT_WORDS - (DATA_OFF // 4) -SEED_BASE = 0x5EED0000 -OUT_V_W3 = 0x31016FAC -V_W3_BASE = 0x01000FAC - -KNOWN_DIVERGENCES = {} - - -def _cs_fssm(threads): - header = bytearray(0x148) - struct.pack_into("<4I", header, 0x138, 0x8088, threads, 1, 1) - return bytes(header) - - -def _vsharp_lines(stride, nr, istride, mode, *, swz=True, tid=False, fmt=22): - """Build probed V# in s[4:7] anchored at DATA_BASE (s[16:17]).""" - w1_hi = (stride << 16) | (int(swz) << 31) - w3 = V_W3_BASE | (fmt << 12) | (istride << 21) | (int(tid) << 23) | (mode << 28) - return [ - "s_mov_b32 s4, s16", - f"s_or_b32 s5, s17, {w1_hi:#x}", - f"s_mov_b32 s6, {nr:#x}", - f"s_mov_b32 s7, {w3:#x}", - ] - - -class Case: - """One self-contained buffer-swizzle probe kernel. - - `body` runs after s[0:3] is the RAW output V# (base 0) and s[16:17] is DATA_BASE (base + 0x100), with the data - region seeded to `0x5EED0000 + byte_offset`. `body` stores `words` output dwords into out[0..words-1] via s[0:3]. - """ - - __slots__ = ("group", "name", "body", "note", "threads", "words", "wave_dependent") - - def __init__(self, group, name, body, note="", *, threads=1, words=4, wave_dependent=False): - self.group = group - self.name = name - self.body = tuple(body) - self.note = note - self.threads = threads - self.words = words - self.wave_dependent = wave_dependent - - -def _single_lane(lines): - return ["v_cmpx_eq_u32_e32 0, v0", *lines] - - -def build_cases(): - cases = [] - - # 1. Baseline swizzled addressing formula (IS=8/16/32/64, index>=IS, non-4-mult stride, inst_offset, mode 0 soffset) - cases += [ - Case("swizzle_basic", "is8_idx_off", _single_lane([ - *_vsharp_lines(8, 16, 0, 3), - "v_mov_b32 v1, 1", "v_mov_b32 v2, 4", - "buffer_load_dword v8, v[1:2], s[4:7], 0 idxen offen", # (0*8+4)*8 + 1*4 = 0x24 - "v_mov_b32 v1, 9", "v_mov_b32 v2, 0", - "buffer_load_dword v9, v[1:2], s[4:7], 0 idxen offen", # (1*8+0)*8 + 1*4 = 0x44 - "v_mov_b32 v1, 1", - "buffer_load_dword v10, v1, s[4:7], 0 idxen offset:4", # inst_offset=4 -> 0x24 - *_vsharp_lines(8, 4, 0, 1), - "v_mov_b32 v1, 3", "v_mov_b32 v2, 0x20", - "buffer_load_dword v11, v[1:2], s[4:7], 0 idxen offen", # mode 1: (0*8+0x20)*8 + 3*4 = 0x10c - "s_waitcnt vmcnt(0)", - "buffer_store_dwordx4 v[8:11], off, s[0:3], 0", - ]), "IS=8 idx/off, idx>=IS, inst_offset, and mode 1 large off"), - - Case("swizzle_basic", "is16_32_64_non4_stride", _single_lane([ - *_vsharp_lines(8, 8, 1, 0), # IS=16 - "v_mov_b32 v1, 3", "v_mov_b32 v2, 4", - "buffer_load_dword v8, v[1:2], s[4:7], 0 idxen offen", # (0*8+4)*16 + 3*4 = 0x4c - *_vsharp_lines(16, 64, 2, 1), # IS=32 - "v_mov_b32 v1, 35", "v_mov_b32 v2, 4", - "buffer_load_dword v9, v[1:2], s[4:7], 0 idxen offen", # (1*16+4)*32 + 3*4 = 0x28c - *_vsharp_lines(8, 100, 3, 1), # IS=64 - "v_mov_b32 v1, 65", - "buffer_load_dword v10, v1, s[4:7], 0 idxen", # (1*8)*64 + 1*4 = 0x204 - *_vsharp_lines(18, 16, 0, 0), # IS=8, non-4-multiple stride 18 - "v_mov_b32 v1, 9", "v_mov_b32 v2, 4", - "buffer_load_dword v11, v[1:2], s[4:7], 0 idxen offen", # (1*18+4)*8 + 1*4 = 0xb4 - "s_waitcnt vmcnt(0)", - "buffer_store_dwordx4 v[8:11], off, s[0:3], 0", - ]), "IS=16/32/64 and non-4-multiple stride 18"), - - Case("swizzle_basic", "stride0_and_mode0_soff", _single_lane([ - *_vsharp_lines(0, 0x40, 0, 3), # stride=0, idxen=1: swizzled addr + RAW check - "v_mov_b32 v1, 2", "v_mov_b32 v2, 0x30", - "buffer_load_dword v8, v[1:2], s[4:7], 0 idxen offen", # (0*0+0x30)*8 + 2*4 = 0x188 - *_vsharp_lines(8, 16, 0, 0), # mode 0: soffset added after swizzle, not checked - "s_mov_b32 s8, 0x100", - "v_mov_b32 v1, 1", "v_mov_b32 v2, 4", - "buffer_load_dword v9, v[1:2], s[4:7], s8 idxen offen", # 0x24 + 0x100 = 0x124 - *_vsharp_lines(8, 4, 0, 2), # mode 2: disabled bounds - "v_mov_b32 v1, 5", - "buffer_load_dword v10, v1, s[4:7], 0 idxen", # 5*4 = 0x14 - *_vsharp_lines(8, 16, 0, 0), # mode 0: idx 16 >= 16 -> OOB - "v_mov_b32 v1, 16", - "buffer_load_dword v11, v1, s[4:7], 0 idxen", # 0 - "s_waitcnt vmcnt(0)", - "buffer_store_dwordx4 v[8:11], off, s[0:3], 0", - ]), "stride=0 RAW with idxen, mode 0 soffset, mode 2, and mode 0 OOB"), - ] - - # 2. idxen == 1 ignores ADD_TID_ENABLE (linear & swizzled, address & bounds, load/typed/atomic) - cases += [ - Case("idxen_ignores_tid", "linear_idxen_tid", [ - *_vsharp_lines(4, 5, 0, 1, swz=False, tid=True), - "v_mov_b32 v1, 2", - "buffer_load_dword v8, v1, s[4:7], 0 idxen", # every lane reads idx=2 (< 5) -> 0x08 - "s_waitcnt vmcnt(0)", - "v_lshlrev_b32 v2, 2, v0", - "buffer_store_dword v8, v2, s[0:3], 0 offen", - ], "linear idxen=1 ignores ADD_TID_ENABLE for both address and bounds", threads=8, words=8), - - Case("idxen_ignores_tid", "swizzled_idxen_tid", [ - *_vsharp_lines(8, 16, 0, 3, swz=True, tid=True), - "v_mov_b32 v1, 4", - "buffer_load_dword v8, v1, s[4:7], 0 idxen", # every lane reads idx=4 -> 0x10 - "s_waitcnt vmcnt(0)", - "v_lshlrev_b32 v2, 2, v0", - "buffer_store_dword v8, v2, s[0:3], 0 offen", - ], "swizzled idxen=1 ignores ADD_TID_ENABLE across lanes", threads=8, words=8), - - Case("idxen_ignores_tid", "typed_and_atomic_idxen_tid", [ - "v_cmpx_eq_u32_e32 3, v0", # run on lane 3 so lane != 0 - *_vsharp_lines(8, 16, 0, 0, swz=True, tid=True, fmt=20), - "v_mov_b32 v1, 1", - "buffer_load_format_x v8, v1, s[4:7], 0 idxen", # idx=1 -> 0x04 - "v_mov_b32 v1, 2", - "tbuffer_load_format_x v9, v1, s[4:7], 0 format:[BUF_FMT_32_UINT] idxen", # idx=2 -> 0x08 - "v_mov_b32 v1, 3", "v_mov_b32 v10, 0x77777777", - "buffer_atomic_swap v10, v1, s[4:7], 0 idxen glc", # idx=3 -> old 0x0c - "s_waitcnt vmcnt(0)", - "buffer_load_dword v11, off, s[0:3], 0 offset:0x10c", # verify swap wrote 0x0c, not (3+3)*4=0x18 - "s_waitcnt vmcnt(0)", - "buffer_store_dwordx4 v[8:11], off, s[0:3], 0", - ], "lane 3 typed MUBUF, MTBUF, and atomic with idxen=1 ignore ADD_TID_ENABLE", threads=4, words=4), - ] - - # 3. SWIZZLE_ENABLE=1 with idxen=0 and ADD_TID_ENABLE=0 has zero effect (linear + mode 3 stays RAW) - cases += [ - Case("swizzle_activation", "no_idx_no_tid_linear", _single_lane([ - *_vsharp_lines(8, 4, 0, 1, swz=True, tid=False), - "v_mov_b32 v1, 0x10", - "buffer_load_dword v8, v1, s[4:7], 0 offen", # linear 0x10 (not 0x80) - *_vsharp_lines(8, 0x40, 0, 3, swz=True, tid=False), - "v_mov_b32 v1, 0x30", - "buffer_load_dword v9, v1, s[4:7], 0 offen", # stays RAW linear 0x30 despite stride 8 - *_vsharp_lines(0x40, 4, 0, 0, swz=True, tid=False), - "v_mov_b32 v1, 0x10", - "buffer_load_dword v10, v1, s[4:7], 0 offen", # mode 0 linear 0x10 - *_vsharp_lines(8, 4, 0, 2, swz=True, tid=False), - "v_mov_b32 v1, 0x10", - "buffer_load_dword v11, v1, s[4:7], 0 offen", # mode 2 linear 0x10 - "s_waitcnt vmcnt(0)", - "buffer_store_dwordx4 v[8:11], off, s[0:3], 0", - ]), "SWIZZLE_ENABLE=1 with idxen=0 and ADD_TID_ENABLE=0 stays linear across modes 0..3"), - ] - - # 4. Multi-dword stepping: scratch swizzle (+4*IS) vs indexed swizzle (+4 linear) - cases += [ - Case("multi_dword_stepping", "scratch_swz_load_x4", [ - "v_cmpx_eq_u32_e32 2, v0", - *_vsharp_lines(16, 4, 0, 0, swz=True, tid=True), # IS=8, lane=2 -> 0x08, 0x28, 0x48, 0x68 - "buffer_load_dwordx4 v[8:11], off, s[4:7], 0", - "s_waitcnt vmcnt(0)", - "buffer_store_dwordx4 v[8:11], off, s[0:3], 0", - ], "scratch swizzle (idxen=0, ADD_TID=1) x4 load steps by +4*IS", threads=4, words=4), - - Case("multi_dword_stepping", "scratch_swz_load_x4_oob", [ - "v_cmpx_eq_u32_e32 2, v0", - *_vsharp_lines(8, 4, 0, 0, swz=True, tid=True), # stride=8: dwords 0..1 IN, 2..3 OOB - "buffer_load_dwordx4 v[8:11], off, s[4:7], 0", - "s_waitcnt vmcnt(0)", - "buffer_store_dwordx4 v[8:11], off, s[0:3], 0", - ], "scratch swizzle x4 load per-dword OOB at stride=8", threads=4, words=4), - - Case("multi_dword_stepping", "scratch_swz_store_x2", [ - "v_cmpx_eq_u32_e32 5, v0", - *_vsharp_lines(8, 16, 1, 3, swz=True, tid=True), # IS=16, lane=5 -> writes 0x14 and 0x54 - "v_mov_b32 v1, 0xaaaa0001", "v_mov_b32 v2, 0xaaaa0002", - "buffer_store_dwordx2 v[1:2], off, s[4:7], 0", - "s_waitcnt vmcnt(0)", - "buffer_load_dword v8, off, s[0:3], 0 offset:0x114", - "buffer_load_dword v9, off, s[0:3], 0 offset:0x118", - "buffer_load_dword v10, off, s[0:3], 0 offset:0x154", - "buffer_load_dword v11, off, s[0:3], 0 offset:0x158", - "s_waitcnt vmcnt(0)", - "buffer_store_dwordx4 v[8:11], off, s[0:3], 0", - ], "scratch swizzle x2 store steps by +4*IS (IS=16 -> +0x40)", threads=8, words=4), - - Case("multi_dword_stepping", "indexed_swz_load_x4", _single_lane([ - *_vsharp_lines(16, 4, 0, 0, swz=True, tid=False), # IS=8, idx=2 -> 0x08, 0x0c, 0x10, 0x14 - "v_mov_b32 v1, 2", - "buffer_load_dwordx4 v[8:11], v1, s[4:7], 0 idxen", - "s_waitcnt vmcnt(0)", - "buffer_store_dwordx4 v[8:11], off, s[0:3], 0", - ]), "indexed swizzle (idxen=1) x4 load steps linearly by +4"), - - Case("multi_dword_stepping", "indexed_swz_load_x2_cross_is_and_oob", _single_lane([ - *_vsharp_lines(8, 16, 0, 3, swz=True, tid=True), # IS=8, idx=7 -> 0x1c, 0x20 (linear across IS) - "v_mov_b32 v1, 7", - "buffer_load_dwordx2 v[8:9], v1, s[4:7], 0 idxen", - *_vsharp_lines(8, 16, 1, 3, swz=True, tid=False), # IS=16, idx=5, off=4 -> 0x54, 0 (dword 1 OOB) - "v_mov_b32 v1, 5", "v_mov_b32 v2, 4", - "buffer_load_dwordx2 v[10:11], v[1:2], s[4:7], 0 idxen offen", - "s_waitcnt vmcnt(0)", - "buffer_store_dwordx4 v[8:11], off, s[0:3], 0", - ]), "indexed swizzle x2 crosses IS=8 linearly and enforces per-dword stride OOB"), - - Case("multi_dword_stepping", "indexed_swz_store_x2", _single_lane([ - *_vsharp_lines(8, 16, 0, 3, swz=True, tid=False), # IS=8, idx=2 -> writes 0x08 and 0x0c - "v_mov_b32 v1, 2", "v_mov_b32 v2, 0xbbbb0001", "v_mov_b32 v3, 0xbbbb0002", - "buffer_store_dwordx2 v[2:3], v1, s[4:7], 0 idxen", - "s_waitcnt vmcnt(0)", - "buffer_load_dword v8, off, s[0:3], 0 offset:0x108", - "buffer_load_dword v9, off, s[0:3], 0 offset:0x10c", - "buffer_load_dword v10, off, s[0:3], 0 offset:0x128", - "buffer_load_dword v11, off, s[0:3], 0 offset:0x12c", - "s_waitcnt vmcnt(0)", - "buffer_store_dwordx4 v[8:11], off, s[0:3], 0", - ]), "indexed swizzle x2 store steps linearly by +4 (leaves +4*IS untouched)"), - ] - - # 5. Typed formats and buffer_atomic_*_x2 in indexed vs scratch swizzle - cases += [ - Case("typed_and_atomic_x2", "indexed_swz_fmt16_load", _single_lane([ - *_vsharp_lines(16, 4, 0, 1, swz=True, tid=False, fmt=75), # 32_32_32_32_UINT, idx=1 -> 0x04..0x10 - "v_mov_b32 v1, 1", - "buffer_load_format_xyzw v[8:11], v1, s[4:7], 0 idxen", - "s_waitcnt vmcnt(0)", - "buffer_store_dwordx4 v[8:11], off, s[0:3], 0", - ]), "indexed swizzle 16B typed load steps linearly by +4"), - - Case("typed_and_atomic_x2", "indexed_swz_fmt16_store", _single_lane([ - *_vsharp_lines(16, 4, 0, 1, swz=True, tid=False, fmt=75), - "v_mov_b32 v1, 1", - "v_mov_b32 v2, 0xcccc0001", "v_mov_b32 v3, 0xcccc0002", - "v_mov_b32 v4, 0xcccc0003", "v_mov_b32 v5, 0xcccc0004", - "buffer_store_format_xyzw v[2:5], v1, s[4:7], 0 idxen", - "s_waitcnt vmcnt(0)", - "buffer_load_dword v8, off, s[0:3], 0 offset:0x104", - "buffer_load_dword v9, off, s[0:3], 0 offset:0x108", - "buffer_load_dword v10, off, s[0:3], 0 offset:0x124", - "buffer_load_dword v11, off, s[0:3], 0 offset:0x144", - "s_waitcnt vmcnt(0)", - "buffer_store_dwordx4 v[8:11], off, s[0:3], 0", - ]), "indexed swizzle 16B typed store writes contiguous dwords"), - - Case("typed_and_atomic_x2", "scratch_swz_fmt16_suppressed", [ - "v_cmpx_eq_u32_e32 5, v0", - *_vsharp_lines(16, 16, 0, 2, swz=True, tid=True, fmt=75), # mode 2 (DISABLED), yet suppressed -> all 0 - "buffer_load_format_xyzw v[8:11], off, s[4:7], 0", - "s_waitcnt vmcnt(0)", - "buffer_store_dwordx4 v[8:11], off, s[0:3], 0", - ], "scratch swizzle suppresses 16B typed MUBUF load even in OOB_SELECT 2", threads=8, words=4), - - Case("typed_and_atomic_x2", "scratch_swz_mtbuf_atomic_x2_and_4b_ctrl", [ - "v_cmpx_eq_u32_e32 4, v0", # lane 4 -> addr +0x10 (8-byte aligned) - *_vsharp_lines(16, 16, 0, 2, swz=True, tid=True, fmt=20), # mode 2, 32_UINT (4B) in V# - "tbuffer_load_format_xy v[2:3], off, s[4:7], 0 format:[BUF_FMT_32_32_UINT]", # 8B -> suppressed (0, 0) - "v_mov_b32 v4, 0xeeeeeeee", "v_mov_b32 v5, 0xffffffff", - "buffer_atomic_swap_x2 v[4:5], off, s[4:7], 0 glc", # 8B -> suppressed (0, 0, mem untouched) - "buffer_load_format_x v10, off, s[4:7], 0", # 4B control -> 0x5eed0010 - "s_waitcnt vmcnt(0)", - "v_or_b32 v8, v2, v3", # 0 - "v_or_b32 v9, v4, v5", # 0 - "buffer_load_dword v11, off, s[0:3], 0 offset:0x110", # mem untouched -> 0x5eed0010 - "s_waitcnt vmcnt(0)", - "buffer_store_dwordx4 v[8:11], off, s[0:3], 0", - ], "scratch swizzle suppresses 8B MTBUF & atomic_swap_x2 while 4B typed control succeeds", threads=8, words=4), - - Case("typed_and_atomic_x2", "indexed_swz_atomic_x2", _single_lane([ - *_vsharp_lines(16, 16, 0, 0, swz=True, tid=False), - "v_mov_b32 v1, 2", # addr +0x08 (8-byte aligned) - "v_mov_b32 v8, 0xdddd0001", "v_mov_b32 v9, 0xdddd0002", - "buffer_atomic_swap_x2 v[8:9], v1, s[4:7], 0 idxen glc", # old [0x5eed0008, 0x5eed000c] - "s_waitcnt vmcnt(0)", - "buffer_load_dword v10, off, s[0:3], 0 offset:0x108", # new 0xdddd0001 - "buffer_load_dword v11, off, s[0:3], 0 offset:0x10c", # new 0xdddd0002 - "s_waitcnt vmcnt(0)", - "buffer_store_dwordx4 v[8:11], off, s[0:3], 0", - ]), "indexed swizzle 8B buffer_atomic_swap_x2 executes linearly at aligned address"), - ] - - # 6. OOB_SELECT 3 with active swizzle and stride != 0 checks (index + soffset) >= num_records - cases += [ - Case("oob_mode3_soffset", "indexed_mode3_soff_edge", _single_lane([ - *_vsharp_lines(8, 16, 0, 3, swz=True, tid=False), - "s_mov_b32 s8, 0x100", - "v_mov_b32 v1, 1", "v_mov_b32 v2, 4", - "buffer_load_dword v8, v[1:2], s[4:7], s8 idxen offen", # 1 + 0x100 >= 16 -> 0 (OOB) - "s_mov_b32 s8, 12", - "v_mov_b32 v1, 3", "v_mov_b32 v2, 4", - "buffer_load_dword v9, v[1:2], s[4:7], s8 idxen offen", # 3 + 12 = 15 < 16 -> 0x38 - "v_mov_b32 v1, 4", "v_mov_b32 v2, 4", - "buffer_load_dword v10, v[1:2], s[4:7], s8 idxen offen", # 4 + 12 = 16 >= 16 -> 0 (OOB) - *_vsharp_lines(8, 14, 0, 3, swz=True, tid=False), - "s_mov_b32 s8, 8", - "v_mov_b32 v1, 5", - "buffer_load_dword v11, v1, s[4:7], s8 idxen", # 5 + 8 = 13 < 14 -> 0x14 + 8 = 0x1c - "s_waitcnt vmcnt(0)", - "buffer_store_dwordx4 v[8:11], off, s[0:3], 0", - ]), "mode 3 swizzled with stride != 0 checks (index + soffset) < num_records"), - - Case("oob_mode3_soffset", "scratch_mode3_soff_lanes", [ - *_vsharp_lines(8, 10, 0, 3, swz=True, tid=True), - "s_mov_b32 s8, 4", - "buffer_load_dword v8, off, s[4:7], s8", # lanes 0..5 IN (lane+4 < 10), 6..15 OOB - "s_waitcnt vmcnt(0)", - "v_lshlrev_b32 v2, 2, v0", - "buffer_store_dword v8, v2, s[0:3], 0 offen", - ], "scratch swizzle mode 3 with soffset=4 and NR=10: lanes 0..5 IN, 6..15 OOB", threads=16, words=16), - ] - - # 7. 32-bit wrap on uint32(voff + inst_offset) vs 64-bit no-wrap on RAW mode 3 (off + soffset) - cases += [ - Case("offset_wrap", "voff_inst_wrap_and_soff_nowrap", _single_lane([ - *_vsharp_lines(8, 16, 0, 3, swz=True, tid=False), - "v_mov_b32 v1, 1", "v_mov_b32 v2, 0xfffffffc", - "buffer_load_dword v8, v[1:2], s[4:7], 0 idxen offen offset:8", # off wraps to 4 -> 0x24 - *_vsharp_lines(0, 0x40, 0, 3, swz=False, tid=False), - "v_mov_b32 v1, 0xfffffffc", - "buffer_load_dword v9, v1, s[4:7], 0 offen offset:8", # linear off wraps to 4 -> 0x04 - *_vsharp_lines(0, 0xffffffff, 0, 3, swz=False, tid=False), - "s_mov_b32 s8, 0xfffffff0", - "v_mov_b32 v1, 0x20", - "buffer_load_dword v10, v1, s[4:7], s8 offen", # 0x20 + 0xfffffff0 = 0x100000010 -> OOB - *_vsharp_lines(0, 0xffffffff, 0, 3, swz=True, tid=False), - "v_mov_b32 v1, 1", "v_mov_b32 v2, 0x20", - "buffer_load_dword v11, v[1:2], s[4:7], s8 idxen offen", # swizzled stride=0 RAW -> OOB - "s_waitcnt vmcnt(0)", - "buffer_store_dwordx4 v[8:11], off, s[0:3], 0", - ]), "uint32(voff + inst_offset) wraps at 32 bits; RAW mode 3 off + soffset does not"), - ] - - # 8. 64-thread ADD_TID_ENABLE uses wave lane (0..31 in wave32, 0..63 in wave64), not workgroup thread ID - cases += [ - Case("add_tid_wave_lane", "tid_wave32_vs_wave64", [ - *_vsharp_lines(8, 64, 0, 1, swz=True, tid=True), - "buffer_load_dword v8, off, s[4:7], 0", - "s_waitcnt vmcnt(0)", - "v_lshlrev_b32 v2, 2, v0", - "buffer_store_dword v8, v2, s[0:3], 0 offen", - ], "64 threads with ADD_TID_ENABLE: wave32 wraps lanes 32..63 to 0..31, wave64 uses 0..63", - threads=64, words=64, wave_dependent=True), - ] - - return cases - - -def _hw_kernel_lines(case, idx, wave): - """Wrap `case.body` for hw_oracle (raw=True, s[2:3] = output buffer base address).""" - lbl = f".Lseed_{idx}" - lbl_done = f".Lseed_done_{idx}" - # Build RAW V# in s[0:3] from s[2:3], compute DATA_BASE = base + DATA_OFF in s[16:17], and seed DATA_BASE on - # lane 0 (preserving EXEC with wave-sized save/restore so all threads participate in the body afterwards). - if wave == 32: - save_exec = ["s_mov_b32 s28, exec_lo", "v_cmpx_eq_u32_e32 0, v0"] - restore_exec = ["s_mov_b32 exec_lo, s28"] - else: - save_exec = ["s_mov_b64 s[28:29], exec", "v_cmpx_eq_u32_e32 0, v0"] - restore_exec = ["s_mov_b64 exec, s[28:29]"] - lines = [ - "s_mov_b32 s0, s2", - "s_and_b32 s1, s3, 0xffff", - "s_mov_b32 s2, 0xffffffff", - f"s_mov_b32 s3, {OUT_V_W3:#x}", - f"s_add_u32 s16, s0, {DATA_OFF:#x}", - "s_addc_u32 s17, s1, 0", - "s_and_b32 s17, s17, 0xffff", - *save_exec, - "s_mov_b32 s20, 0", - f"{lbl}:", - f"s_cmp_ge_u32 s20, {DATA_DWORDS * 4:#x}", - f"s_cbranch_scc1 {lbl_done}", - f"s_add_u32 s21, s20, {SEED_BASE:#x}", - "v_mov_b32 v30, s21", - f"s_add_u32 s22, s20, {DATA_OFF:#x}", - "buffer_store_dword v30, off, s[0:3], s22", - "s_add_u32 s20, s20, 4", - f"s_branch {lbl}", - f"{lbl_done}:", - "s_waitcnt vmcnt(0)", - *restore_exec, - ] - if case.threads > 1: - lines.append("s_barrier") - lines.extend(case.body) - lines.append("s_endpgm") - return lines - - -def _translate_case(work, case, wave=32): - os.makedirs(os.path.join(work, "disasm"), exist_ok=True) - os.makedirs(os.path.join(work, "fssm"), exist_ok=True) - name = f"cs_swz_probe_{case.name}_w{wave}" - src = os.path.join(work, "disasm", name + ".s") - wave_tag = "s_mov_b64 s[28:29], exec" if wave == 64 else "s_mov_b32 s28, exec_lo" - body = [ - wave_tag, - f"s_add_u32 s16, s0, {DATA_OFF:#x}", - "s_addc_u32 s17, s1, 0", - "s_and_b32 s17, s17, 0xffff", - *case.body, - "s_endpgm", - ] - with open(src, "w", encoding="utf-8", newline="\n") as f: - f.write(f"; {name}\n" + "".join(f"\t{ln}\n" for ln in body)) - with open(os.path.join(work, "fssm", name + ".fssm"), "wb") as f: - f.write(_cs_fssm(case.threads)) - with warnings.catch_warnings(): - warnings.simplefilter("ignore", ResourceWarning) - spv = rdna2spirv.translate(src) - memory = {a: 0 for a in range(0, DATA_OFF, 4)} - for off in range(0, DATA_DWORDS * 4, 4): - memory[DATA_OFF + off] = SEED_BASE + off - spirv_mini_interp.run_workgroup( - spv, case.threads, wave, - inputs_for=lambda i: {"%wg_id": (0, 0, 0), "%local_id": (i, 0, 0), "%sg_lane": i % wave}, - push_constants=[0, 0, 0xFFFFFFFF, OUT_V_W3] + [0] * 28, - memory=memory, - ) - return [memory.get(4 * i, 0) for i in range(case.words)] - - -def run_translator(cases, waves=(32, 64)): - per_wave = {} - with tempfile.TemporaryDirectory(prefix="buf_swz_probe_") as work: - for wave in waves: - out = {} - for case in cases: - if wave != waves[0] and not case.wave_dependent: - out[case.name] = per_wave[waves[0]][case.name] - continue - try: - out[case.name] = _translate_case(work, case, wave=wave) - except Exception as e: - out[case.name] = f"error: {type(e).__name__}: {e}" - per_wave[wave] = out - return per_wave - - -def run_hw(cases, arch=None, waves=(32, 64)): - from hw_oracle import asm, runner # noqa: E402 - oracle = runner.open_oracle(arch=arch) - try: - device = oracle.device - per_wave = {} - for wave in waves: - kernels = [ - asm.Kernel(_hw_kernel_lines(case, idx, wave), wave=wave, threads=case.threads, - words=OUT_WORDS, raw=True) - for idx, case in enumerate(cases) - ] - res = oracle.run(kernels, words=OUT_WORDS) - per_wave[wave] = {case.name: (r[:case.words] if isinstance(r, list) else r) for case, r in zip(cases, res)} - return device, per_wave - finally: - oracle.close() - - -def _fmt_words(w): - if isinstance(w, list): - if len(w) <= 8: - return " ".join(f"0x{x:08x}" for x in w) - head = " ".join(f"0x{x:08x}" for x in w[:4]) - tail = " ".join(f"0x{x:08x}" for x in w[-4:]) - return f"[{len(w)} words: {head} ... {tail}]" - return str(w) - - -def self_test(): - cases = build_cases() - names = [c.name for c in cases] - assert len(names) == len(set(names)), "duplicate case names" - for name in KNOWN_DIVERGENCES: - assert name in names, f"unknown KNOWN_DIVERGENCES key: {name}" - res = run_translator(cases, waves=(32, 64)) - for w in (32, 64): - errors = {k: v for k, v in res[w].items() if not isinstance(v, list)} - assert not errors, f"translator wave{w} errors: {errors}" - assert res[32]["tid_wave32_vs_wave64"] != res[64]["tid_wave32_vs_wave64"], "wave32/64 ADD_TID must differ" - print(f"self-test: {len(cases)} cases across {len({c.group for c in cases})} groups translated and ran on CPU OK") - return 0 - - -def main(argv=None): - ap = argparse.ArgumentParser(description=__doc__.splitlines()[0]) - ap.add_argument("--oracle", choices=("translator", "hw", "both"), default="translator") - ap.add_argument("--wave", choices=("32", "64", "both"), default="both") - ap.add_argument("--group", action="append", default=[], help="run only named group(s)") - ap.add_argument("--hw-arch", default=None, help="override GPU architecture for hw_oracle") - ap.add_argument("--list-groups", action="store_true") - ap.add_argument("--strict", action="store_true", help="treat known translator divergences as failures") - ap.add_argument("--json", dest="json_out", default=None, help="write raw results to a JSON file") - ap.add_argument("--self-test", action="store_true") - args = ap.parse_args(argv) - - if args.self_test: - return self_test() - - cases = build_cases() - groups = [] - for c in cases: - if c.group not in groups: - groups.append(c.group) - if args.list_groups: - for g in groups: - n = sum(1 for c in cases if c.group == g) - print(f"{g:<22} ({n} cases)") - return 0 - - if args.group: - unknown = [g for g in args.group if g not in groups] - if unknown: - print(f"unknown group(s): {', '.join(unknown)}", file=sys.stderr) - return 2 - want = set(args.group) - cases = [c for c in cases if c.group in want] - - waves = (32, 64) if args.wave == "both" else (int(args.wave),) - tr_res = run_translator(cases, waves=waves) if args.oracle in ("translator", "both") else None - hw_device, hw_res = None, None - if args.oracle in ("hw", "both"): - from hw_oracle import runner # noqa: E402 - try: - hw_device, hw_res = run_hw(cases, arch=args.hw_arch, waves=waves) - except runner.Unavailable as e: - print(f"hardware oracle unavailable: {e}", file=sys.stderr) - return 77 - print(f"hardware oracle: {hw_device} (waves: {','.join(str(w) for w in waves)})") - - mismatches = 0 - known_diffs = 0 - wave_diffs = 0 - records = [] - for c in cases: - t32 = tr_res[32][c.name] if tr_res and 32 in tr_res else None - t64 = tr_res[64][c.name] if tr_res and 64 in tr_res else None - h32 = hw_res[32][c.name] if hw_res and 32 in hw_res else None - h64 = hw_res[64][c.name] if hw_res and 64 in hw_res else None - status = "OK" - tag = None - if not c.wave_dependent and h32 is not None and h64 is not None and h32 != h64: - status = "WAVE_DIFF" - wave_diffs += 1 - elif c.wave_dependent and h32 is not None and h64 is not None and h32 == h64: - status = "WAVE_SAME" - mismatches += 1 - elif any(v is not None and not isinstance(v, list) for v in (t32, t64, h32, h64)): - status = "ERROR" - mismatches += 1 - else: - bad = ((t32 is not None and h32 is not None and t32 != h32) - or (t64 is not None and h64 is not None and t64 != h64)) - if bad: - hw_ref = h32 if h32 is not None else h64 - known = KNOWN_DIVERGENCES.get(c.name) - if known and hw_ref == known[1]: - status = "KNOWN_DIFF" - tag = known[0] - known_diffs += 1 - else: - status = "MISMATCH" - mismatches += 1 - records.append({ - "group": c.group, "name": c.name, "note": c.note, "wave_dependent": c.wave_dependent, - "status": status, "known_tag": tag, - "translator_w32": t32, "translator_w64": t64, "hw_w32": h32, "hw_w64": h64, - }) - if status != "OK" or args.oracle != "both": - label = f"{status}:{tag}" if tag else status - print(f"[{label:<22}] {c.group}/{c.name}: {c.note}") - if h32 is not None: - print(f" hw_w32: {_fmt_words(h32)}") - if h64 is not None and h64 != h32: - print(f" hw_w64: {_fmt_words(h64)}") - if t32 is not None: - print(f" tr_w32: {_fmt_words(t32)}") - if t64 is not None and t64 != t32: - print(f" tr_w64: {_fmt_words(t64)}") - - total = len(cases) - matched = total - mismatches - known_diffs - wave_diffs - print(f"summary: {total} cases: {matched} match, {known_diffs} known divergence, " - f"{mismatches} unexpected mismatch, {wave_diffs} wave32/64 diff") - - if args.json_out: - out_path = os.path.abspath(args.json_out) - if os.path.isdir(out_path): - print(f"ERROR: --json path is a directory: {out_path}", file=sys.stderr) - return 2 - parent = os.path.dirname(out_path) - try: - os.makedirs(parent, exist_ok=True) - with open(out_path, "w", encoding="utf-8", newline="\n") as f: - json.dump({"device": hw_device, "waves": list(waves), "cases": records}, f, indent=2) - f.write("\n") - except OSError as exc: - print(f"ERROR: cannot write {out_path}: {exc.strerror or exc}", file=sys.stderr) - return 2 - - if mismatches or wave_diffs or (args.strict and known_diffs): - return 1 - return 0 - - -if __name__ == "__main__": - try: # a redirected stdout is strict ANSI code page under -I; write '?' for what it cannot encode - sys.stdout.reconfigure(errors="replace") - except (AttributeError, ValueError, OSError): - pass - sys.exit(main()) diff --git a/tools/bvh_geometry_check.py b/tools/bvh_geometry_check.py deleted file mode 100644 index ba9eee45f..000000000 --- a/tools/bvh_geometry_check.py +++ /dev/null @@ -1,211 +0,0 @@ -"""Check whether geometry given to a BLAS rehydration is the geometry the BLAS was built from. - -A rehydrated structure that matches `XboxBvhBuilder.dll` byte for byte proves the packing, not the geometry: the -library and `tools/bvh_rehydrate.py` agree on any input. The dehydrated BLAS, though, keeps things that were computed -from the true triangles, and this tool compares a rehydration against them (docs/bvh.md §4a): - -1. bounds: every rehydrated leaf lies inside `sceneBounds` mapped through the leaf frame, and the union of the leaves - equals it (the error is the largest gap over the largest extent; about 1e-7 or less for the right geometry); -2. overrides: each box component stored in the dehydrated groups lies inside the range of the rehydrated slot it - overrides and is no looser than it, within a few float32 ulps (the offline build rounds some one or two ulps away); -3. pairs: a leaf with two primitives joins triangles that share an edge, so in the right index buffer the two share - two vertex indices. This needs no positions and no transform, so it also checks one geometry on its own; -4. area: the summed surface area of the internal box slots, a tie-break between candidates (lower is tighter). - -Standard library only. - -Usage: - python -I tools/bvh_geometry_check.py --geom VB[,IB] [...] [--header-offset N] [--stride BYTES] - [--index16] [--transform 12 floats] [--json ] - -The geometry options are those of tools/bvh_rehydrate.py. It prints one line per check; exit status is 0 when bounds, -overrides and pairs are consistent, 1 when one is not, 2 on an input error. -""" -import argparse -import json -import math -import os -import struct -import sys - -sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) -import bvh_rehydrate as R # noqa: E402 -from bvh_index import _publish # noqa: E402 -from report_paths import same_report_path # noqa: E402 - -BOUNDS_TOLERANCE = 1e-4 # of the largest sceneBounds extent -OUTSIDE_TOLERANCE = 1e-3 -OVERRIDE_ULPS = 4 - - -def leaf_offsets(hdr): - for i in range(hdr.num_elements): - yield hdr.offset_to_elements + (i // R.LEAVES_PER_CHUNK) * R.CHUNK_STRIDE + (i % R.LEAVES_PER_CHUNK) * 64 - - -def check_bounds(hdr, out): - """(leaves outside, relative gap between the leaf union and sceneBounds in the leaf frame).""" - frame = R.LeafFrame(hdr) - lo, hi = hdr.bounds[:3], hdr.bounds[3:] - corners = [frame.apply((x, y, z)) for x in (lo[0], hi[0]) for y in (lo[1], hi[1]) for z in (lo[2], hi[2])] - box = [min(c[a] for c in corners) for a in range(3)] + [max(c[a] for c in corners) for a in range(3)] - extent = max(max(box[a + 3] - box[a] for a in range(3)), 1e-30) - union = [math.inf] * 3 + [-math.inf] * 3 - outside = 0 - for off in leaf_offsets(hdr): - b = R.node_bounds(out, (off >> 6) << 3 | R.TRI0) - if max([box[a] - b[a] for a in range(3)] + [b[a] - box[a] for a in range(3, 6)]) > OUTSIDE_TOLERANCE * extent: - outside += 1 - for a in range(3): - union[a], union[a + 3] = min(union[a], b[a]), max(union[a + 3], b[a + 3]) - gap = max(abs(union[a] - box[a]) for a in range(6)) / extent if hdr.num_elements else 0.0 - return outside, gap - - -def stored_overrides(src, hdr): - """Yield (child pointer, component, value) for every override the dehydrated box groups store.""" - if hdr.root & 7 not in (R.BOX16, R.BOX32): - return - for b32_start, b32_count, b16_start, b16_count in R.levels(src, hdr): - for start, count, wide in ((b32_start, b32_count, True), (b16_start, b16_count, False)): - for g in range((count + R.GROUP - 1) // R.GROUP): - n = min(R.GROUP, count - g * R.GROUP) - base = hdr.offset_to_nodes + start + g * ((1 << 13) if wide else (1 << 12)) - words = struct.unpack_from("<%dI" % n, src, base) - child_at, value_at = base + 4 * n, base + 4 * (n + sum(w >> 24 for w in words)) - for word in words: - kids = word >> 24 - children = struct.unpack_from("<%dI" % kids, src, child_at) - child_at += 4 * kids - for bit in range(24): - if word >> bit & 1: - if wide: - value = struct.unpack_from("= b[comp] - tol if comp < 3 else value <= b[comp] + tol - if tighter and lo - tol <= value <= hi + tol: - good += 1 - else: - bad += 1 - return good, bad - - -def check_pairs(src, hdr, geometries): - """{geometry index: (pairs sharing an edge, pairs)} from the leaves that hold two primitives.""" - out = {} - for _, gi, _, prim0, prim1, _ in R.leaf_records(src, hdr): - if prim1 is None or gi >= len(geometries): - continue - g = geometries[gi] - shared = len(set(g.triangle(prim0)) & set(g.triangle(prim1))) >= 2 - ok, total = out.get(gi, (0, 0)) - out[gi] = (ok + shared, total + 1) - return out - - -def internal_area(hdr, out): - area, stack, seen = 0.0, [hdr.root], set() - while stack: - p = stack.pop() - if p == R.INVALID or p in seen or p & 7 not in (R.BOX16, R.BOX32): - continue - seen.add(p) - for child in struct.unpack_from("<4I", out, (p >> 3) << 6): - if child == R.INVALID: - continue - b = R.node_bounds(out, child) - e = [b[a + 3] - b[a] if math.isfinite(b[a + 3] - b[a]) and b[a + 3] >= b[a] else 0.0 for a in range(3)] - area += 2.0 * (e[0] * e[1] + e[1] * e[2] + e[0] * e[2]) - stack.append(child) - return area - - -def check(dehydrated, geometries, header_offset=0): - """Rehydrate and run every check. Returns a report dict; report["consistent"] is the overall verdict.""" - hdr = R.Header(dehydrated, header_offset) - src = bytes(dehydrated[header_offset:header_offset + hdr.total_bytes]) - out = R.rehydrate(dehydrated, geometries, header_offset) - outside, gap = check_bounds(hdr, out) - good, bad = check_overrides(src, hdr, out) - pairs = check_pairs(src, hdr, list(geometries)) - pairs_ok = all(ok == total for ok, total in pairs.values()) - return {"leaves": hdr.num_elements, "leaves_outside": outside, "bounds_gap": gap, - "overrides_consistent": good, "overrides_inconsistent": bad, - "pairs": {str(k): list(v) for k, v in sorted(pairs.items())}, "internal_area": internal_area(hdr, out), - "consistent": outside == 0 and gap <= BOUNDS_TOLERANCE and bad == 0 and pairs_ok} - - -def main(argv=None): - ap = argparse.ArgumentParser(description="Check a BLAS rehydration's geometry against what the BLAS stores.") - ap.add_argument("dehydrated") - ap.add_argument("--geom", action="append", default=[], metavar="VB[,IB]") - ap.add_argument("--header-offset", type=int, default=0) - ap.add_argument("--stride", type=int, default=12) - ap.add_argument("--index16", action="store_true") - ap.add_argument("--transform") - ap.add_argument("--json") - a = ap.parse_args(argv) - geom_paths = [] - for spec in a.geom: - parts = spec.split(",") - geom_paths.append((parts[0], parts[1] if len(parts) > 1 else "")) - if a.json: - if same_report_path(a.json, a.dehydrated): - print("error: --json %s must not overwrite the dehydrated input" % a.json, file=sys.stderr) - return 2 - for vb_path, ib_path in geom_paths: - for path in (vb_path, ib_path): - if path and same_report_path(a.json, path): - print("error: --json %s must not overwrite a geometry buffer %s" % (a.json, path), file=sys.stderr) - return 2 - try: - transform = R.parse_transform(a.transform) if a.transform else None - geometries = [] - for vb_path, ib_path in geom_paths: - with open(vb_path, "rb") as f: - vb = f.read() - ib = None - if ib_path: - with open(ib_path, "rb") as f: - ib = f.read() - geometries.append(R.Geometry(vb, a.stride, ib, a.index16, transform)) - with open(a.dehydrated, "rb") as f: - report = check(f.read(), geometries, a.header_offset) - except (OSError, ValueError, struct.error) as e: - print("error: %s" % e, file=sys.stderr) - return 2 - pairs = report["pairs"] - print("bounds: %d of %d leaves outside, union gap %.2e" % (report["leaves_outside"], report["leaves"], report["bounds_gap"])) - print("overrides: %d consistent, %d not" % (report["overrides_consistent"], report["overrides_inconsistent"])) - print("pairs sharing an edge: %s" % (", ".join("geometry %s %d/%d" % (k, v[0], v[1]) for k, v in pairs.items()) or "no pairs")) - print("internal box area: %.6g" % report["internal_area"]) - print("consistent" if report["consistent"] else "NOT consistent") - if a.json: - try: - _publish(a.json, lambda f: json.dump(report, f, indent=1), "\n") - except OSError as e: - print("error: cannot write %s: %s" % (a.json, e.strerror or e), file=sys.stderr) - return 2 - return 0 if report["consistent"] else 1 - - -if __name__ == "__main__": - try: # a redirected stdout is strict ANSI code page under -I; write '?' for what it cannot encode - sys.stdout.reconfigure(errors="replace") - except (AttributeError, ValueError, OSError): - pass - sys.exit(main()) diff --git a/tools/bvh_gpu_smoke.py b/tools/bvh_gpu_smoke.py deleted file mode 100644 index b4b53f8de..000000000 --- a/tools/bvh_gpu_smoke.py +++ /dev/null @@ -1,320 +0,0 @@ -"""Run XboxBvhBuilder.dll's translated compute programs on the GPU with synthetic inputs (TEST-594). - -docs/embedded_shaders.md: the DLL carries 52 console compute programs, and the translator takes all but one; none had -been run on a GPU. This translates them from your own package and runs each one through vk_compute_test: - - python -I tools/bvh_gpu_smoke.py --game-dir [--work DIR] [--build runtime/build] - [--max-shared-memory 32768] [--table-qword 0x2000] [--include-rehydration] - [--json report.json] - -Each program reads its root arguments from a table at s[0:1], which in vk_compute_test is the heap base (Xbox VA 0). -The heap starts as that table, 64-bit words that all hold --table-qword, then zeros up to --heap-bytes (seeded with -VKC_HEAP_INIT). So every root descriptor points at a zeroed region past the table and every root constant reads ---table-qword or 0. That is enough to run each program, not to give it meaningful work: most leave early, and the -report says how many words each one changed. A run passes when it exits 0, the Khronos validation layer (when -installed) reports no error, and a second run writes the same heap bytes. - ---checked also runs the programs whose effect reads straight off their code with inputs chosen for them, and compares -every byte they write (CHECKED below). Five take a count and write that many 16- or 8-byte entries from thread index 0 -up; 32 threads per group, so one group with a count of 20 also shows that entries past the count are left alone. -PrefixSum64 scans 64 words in place into their exclusive prefix sum and stores the total. - -The three rehydration programs (Box16Rehydration, Box32Rehydration, LeafRehydration) belong to TEST-376, which checks -them against tools/bvh_rehydrate.py; --include-rehydration runs them too. - ---max-shared-memory is passed to rdna2spirv.py: set it to the device's maxComputeSharedMemorySize (32768 on AMD's -Windows driver; the translator's default is 65536). Over it, a program's LDS array shrinks to what the program uses, -which the wave64 bitonic sorts need on a 32 KiB device. - -Nothing from the package is written outside --work. The report holds module names, statuses and counts only. -""" -import argparse -import json -import math -import os -import struct -import subprocess -import sys -import tempfile -from pathlib import Path - -HERE = Path(__file__).resolve().parent -REHYDRATION = ("Box16Rehydration", "Box32Rehydration", "LeafRehydration") -TABLE_QWORDS = 512 # a 4 KiB root table - - -def heap_image(table_qword, heap_bytes): - """The initial heap: TABLE_QWORDS words of table_qword, then zeros up to heap_bytes.""" - table = struct.pack(f"<{TABLE_QWORDS}Q", *([table_qword] * TABLE_QWORDS)) - if heap_bytes < len(table): - raise ValueError(f"--heap-bytes must be at least {len(table)}") - return table + bytes(heap_bytes - len(table)) - - -def changed_words(initial, after): - """How many 32-bit words of the heap differ from the initial image.""" - n = min(len(initial), len(after)) // 4 - a = struct.unpack_from(f"<{n}I", initial) - b = struct.unpack_from(f"<{n}I", after) - return sum(1 for x, y in zip(a, b) if x != y) - - -def run_program(vkc, spv, init, dump, heap_words, validation, timeout): - """One dispatch of one workgroup. Returns (status, last line of output): ok, 'exit N', validation, timeout.""" - env = dict(os.environ, VKC_OUT_WORDS=str(heap_words), VKC_HEAP_INIT=str(init), VKC_DUMP=str(dump)) - if validation: - env["VK_INSTANCE_LAYERS"] = "VK_LAYER_KHRONOS_validation" - try: - p = subprocess.run([str(vkc), str(spv), "1", "dump"], capture_output=True, text=True, env=env, - timeout=timeout) - except subprocess.TimeoutExpired: - return "timeout", "" - out = (p.stdout or "") + (p.stderr or "") - last = (out.strip().splitlines() or [""])[-1][:160] - if p.returncode != 0: - return f"exit {p.returncode}", last - if "Validation Error" in out: - return "validation", next((line for line in out.splitlines() if "VUID" in line), last)[:160] - return "ok", last - - -def smoke(spirv_dir, vkc, *, table_qword, heap_bytes, validation, timeout, include_rehydration, runner=run_program): - """Run every program in spirv_dir twice. Returns [{name, status, words_changed, detail}] in name order.""" - image = heap_image(table_qword, heap_bytes) - results = [] - with tempfile.TemporaryDirectory(prefix="bvh_gpu_smoke_") as tmp: - tmp = Path(tmp) - init = tmp / "heap.bin" - init.write_bytes(image) - for spv in sorted(Path(spirv_dir).glob("*.spv")): - name = spv.stem - if name in REHYDRATION and not include_rehydration: - continue - first, second = tmp / (name + ".1.bin"), tmp / (name + ".2.bin") - status, detail = runner(vkc, spv, init, first, heap_bytes // 4, validation, timeout) - changed = None - if status == "ok": - again, detail2 = runner(vkc, spv, init, second, heap_bytes // 4, validation, timeout) - a = first.read_bytes() if first.is_file() else b"" - b = second.read_bytes() if second.is_file() else b"" - if again != "ok": - status, detail = again, detail2 - elif not a or a != b: - status, detail = "nondeterministic", "the two runs wrote different heap bytes" - else: - status = "pass" - changed = changed_words(image, a) if a else None - results.append({"name": name, "status": status, "words_changed": changed, "detail": detail}) - return results - - -# ---- checked runs ---- -# -# Root-table fields as each program reads them (offsets in the table at s[0:1]; addresses are 64-bit, counts and -# values 32-bit), and what it writes. FILL marks the bytes a program must leave alone. -DST, SRC, SUMS = 0x2000, 0x6000, 0x4000 # regions past the 4 KiB table -FILL = 0xAA -COUNT = 20 # within one 32-thread group - - -def _u32(heap, at): - return struct.unpack_from("8} {r['detail'] if r['status'] != 'pass' else ''}") - counts = {} - for r in results: - counts[r["status"]] = counts.get(r["status"], 0) + 1 - working = sum(1 for r in results if r["status"] == "pass" and r["words_changed"] and - r["words_changed"] > 0) - print(f"{counts.get('pass', 0)} of {len(results)} pass; {working} changed heap words beyond running; " - + ", ".join(f"{k} {v}" for k, v in sorted(counts.items()) if k != "pass")) - checked = [] - if a.checked: - checked = run_checked(spirv, vkc, heap_bytes=a.heap_bytes, validation=not a.no_validation, timeout=a.timeout) - for r in checked: - print(f"checked {r['name']:20} {r['status']:10} {r['detail']}") - print(f"checked: {sum(r['status'] == 'pass' for r in checked)} of {len(checked)} write exactly what they should") - if a.json: - Path(a.json).write_text(json.dumps({"max_shared_memory": a.max_shared_memory, "table_qword": a.table_qword, - "heap_bytes": a.heap_bytes, "results": results, "checked": checked}, - indent=1), encoding="utf-8", newline="\n") - ok = counts.get("pass", 0) == len(results) and all(r["status"] == "pass" for r in checked) - return 0 if ok else 1 - - -if __name__ == "__main__": - try: # a redirected stdout is strict ANSI code page under -I; write '?' for what it cannot encode - sys.stdout.reconfigure(errors="replace") - except (AttributeError, ValueError, OSError): - pass - sys.exit(main()) diff --git a/tools/bvh_groups.py b/tools/bvh_groups.py deleted file mode 100644 index e6f7d83ca..000000000 --- a/tools/bvh_groups.py +++ /dev/null @@ -1,350 +0,0 @@ -"""Decode the `0x5000xxxx` descriptor streams of a `*_bvh4.rpf` archive and tie them to their BVH buffers. - -docs/bvh.md §3.2 has the layouts this checks. Every descriptor stream starts with a zero u64 and a `0x5000xxxx` word at -0x08 that points at a 32-byte block whose u32 at +8 (the "page word") is 0x101 or 0x1. Two templates exist: - -* **instance** (page word 0x101, `0x60000000` at 0x20): u64 N at 0x10, then pointers to N u64 entries (0x18), two - N x u64 arrays (0x28, 0x30) and N 3x4 float matrices (0x38, always 0x50). The 208-byte `instance208` record is the - N = 1 case. The next stream is the BVH buffer: the BLAS of the non-zero entries back to back, each starting where - the previous non-zero entry's low 32 bits end, and each entry's low 32 bits are that BLAS's declared end rounded up - to 256 bytes. An entry of 0 has no BLAS. -* **table** (page word 0x1): u64 0 at 0x10, u64 1 at 0x18, a pointer to K u32 values (0x20) with `u16 count, - u16 capacity` at 0x28, and a pointer to K pointers (0x30) with the same count at 0x38. Each pointer addresses a - 32-byte item whose only non-zero bytes are a u64 at +0x10. The u32 values are sorted ascending and distinct. - -The tool walks the archive with bvh_index's own decompressor and classifier, parses every descriptor, checks an -instance descriptor against the stream that follows it, and prints counts. It writes no payload bytes, keys or -values: rows hold offsets, sizes, counts and check results. - -Usage: - python -I tools/bvh_groups.py [--json report.json] [--start N] [--limit BYTES] - -Exit status: 0 after a scan (whatever it found), 2 for a bad argument or an unreadable archive. -""" -import argparse -import collections -import json -import mmap -import os -import stat -import struct -import sys -import tempfile - -sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) -import bvh_index # noqa: E402 -from file_mode import published_mode # noqa: E402 -from replace_retry import replace as replace_retry # noqa: E402 - -VBASE = 0x50000000 -PBASE = 0x60000000 -ITEM = 32 -MAP = 32 - - -def _u32(b, o): - return struct.unpack_from(" len(b): - return None - lo, hi = struct.unpack_from(" size: - return None - page_word = _u32(buf, m + 8) - if _u32(buf, 0x20) == PBASE and _u32(buf, 0x24) == 0: - return _parse_instance(buf, m, page_word) - return _parse_table(buf, m, page_word) - - -def _parse_instance(buf, m, page_word): - size = len(buf) - n = _u64(buf, 0x10) - ptrs = [_vptr(buf, o) for o in (0x18, 0x28, 0x30, 0x38)] - if None in ptrs or not 1 <= n <= (size - 0x50) // 48 or size < 0x50: - return None - ent, a28, a30, xf = ptrs - if ent + 8 * n > size or a28 + 8 * n > size or a30 + 8 * n > size or xf + 48 * n > size: - return None - entries = [_u64(buf, ent + 8 * i) for i in range(n)] - sizes = [e & 0xFFFFFFFF for e in entries] - return { - "family": "instance", "size": size, "page_word": page_word, "count": n, - "entry_sizes": sizes, "zero_entries": sizes.count(0), - "entry_high_low16_mod64": all((e >> 32) & 0xFFFF == 0 or ((e >> 32) & 0xFFFF) % 64 == 0 - for e in entries if e & 0xFFFFFFFF), - "matrix_offset": xf, - "zero_0x48": _u64(buf, 0x48) == 0, - "arrays_zero": all(_u64(buf, a + 8 * i) == 0 for a in (a28, a30) for i in range(n)), - "tiles": _tiles([(xf, 48 * n), (ent, 8 * n), (a28, 8 * n), (a30, 8 * n), (m, MAP)], 0x50, size), - } - - -def _parse_table(buf, m, page_word): - size = len(buf) - if _u64(buf, 0x10) != 0 or _u64(buf, 0x18) != 1: - return None - keys_at, items_at = _vptr(buf, 0x20), _vptr(buf, 0x30) - if keys_at is None or items_at is None or _u32(buf, 0x2C) or _u32(buf, 0x3C): - return None - k, cap = _u32(buf, 0x28) & 0xFFFF, _u32(buf, 0x28) >> 16 - k2, cap2 = _u32(buf, 0x38) & 0xFFFF, _u32(buf, 0x38) >> 16 - if k == 0 or keys_at + 4 * k > size or items_at + 8 * k > size: - return None - values = [_u32(buf, keys_at + 4 * i) for i in range(k)] - items = [_vptr(buf, items_at + 8 * i) for i in range(k)] - items_ok = None not in items and all(p + ITEM <= size for p in items) - item_words_ok = items_ok and all( - _u64(buf, p) == 0 and _u64(buf, p + 8) == 0 and _u64(buf, p + 0x18) == 0 and _u64(buf, p + 0x10) != 0 - for p in items) - contiguous = items_ok and all(items[i + 1] - items[i] == ITEM for i in range(k - 1)) - regions = [(m, MAP), (keys_at, 4 * k), (items_at, 8 * k)] - if contiguous: - regions.append((items[0], ITEM * k)) - return { - "family": "table", "size": size, "page_word": page_word, "count": k, - "count_fields_equal": (k, cap) == (k2, cap2) and k == cap, - "values_sorted_distinct": all(values[i] < values[i + 1] for i in range(k - 1)), - "items_contiguous": bool(contiguous), "item_words": bool(item_words_ok), - "tiles": bool(contiguous) and _tiles(regions, 0x40, size), - } - - -def check_buffer(desc, payload): - """Check an instance descriptor against the stream that follows it. - - `payload` is the following stream (only its first 0x140 bytes are needed when the descriptor has one non-zero - entry). Returns {"ok": bool, "blas": [(offset, declared end), ...], "reason": str}. - """ - blas, off = [], 0 - nonzero = [s for s in desc["entry_sizes"] if s] - for i, s in enumerate(nonzero): - if off + bvh_index.HEAD > len(payload): - return {"ok": False, "blas": blas, "reason": "BLAS %d past the end of the kept bytes" % i} - head = payload[off:off + bvh_index.HEAD] - tag, n = struct.unpack_from("= 8 else size) - if not 0 <= pos <= size: - raise ValueError("start offset is outside the archive") - end = min(size, pos + limit) if limit else size - pending = None # the previous stream's descriptor row, waiting for its following stream - while pos < end: - mt = bvh_index.ZHDR.search(m, pos, end) - if not mt: - break - s = mt.start() - got = bvh_index.inflate_stream(m, s, end, max_inflate) - if got is None: - pos = s + 1 - continue - head, kept, total, used = got - kind = bvh_index.classify(head, total)["kind"] - if pending is not None: - pending["next_kind"] = kind - if pending["family"] == "instance": - if kind in ("bvh4", "bvh4-chunk"): - res = check_buffer(pending, kept) - pending["buffer_ok"], pending["blas_count"] = res["ok"], len(res["blas"]) - if not res["ok"]: - pending["reason"] = res["reason"] - else: - pending["buffer_ok"] = False - pending["reason"] = "followed by %s" % kind - pending = None - row = {"offset": s, "size": total, "kind": kind} - if kind in ("instance208", "descriptor"): - desc = parse_descriptor(bytes(kept)) if total == len(kept) else None - if desc is None: - row["family"] = "unparsed" - else: - row.update(desc) - pending = row - rows.append(row) - pos = s + used - if pending is not None: - pending["next_kind"] = None - if pending["family"] == "instance": - pending["buffer_ok"] = False - pending["reason"] = "last stream of the scan" - finally: - m.close() - return rows, summarize(rows) - - -def summarize(rows): - c = collections.Counter() - sizes = collections.defaultdict(collections.Counter) - counts = collections.defaultdict(collections.Counter) - bvh_after = collections.Counter() - for i, r in enumerate(rows): - if r["kind"] in ("bvh4", "bvh4-chunk") and i: - p = rows[i - 1] - bvh_after[p.get("family", p["kind"]) + ("/" + p["kind"] if "family" in p else "")] += 1 - fam = r.get("family") - if fam is None: - continue - key = "%s/%s" % (fam, r["kind"]) - c[key] += 1 - sizes[key][r["size"]] += 1 - if fam == "unparsed": - continue - counts[key][r["count"]] += 1 - c["%s page_word=0x%x" % (key, r["page_word"])] += 1 - c["%s next=%s" % (key, r.get("next_kind"))] += 1 - c["%s tiles=%s" % (key, r["tiles"])] += 1 - if fam == "instance": - c["%s buffer_ok=%s" % (key, r.get("buffer_ok"))] += 1 - c["%s arrays_zero=%s" % (key, r["arrays_zero"])] += 1 - c["%s zero_0x48=%s" % (key, r["zero_0x48"])] += 1 - c["%s entry_high_low16_mod64=%s" % (key, r["entry_high_low16_mod64"])] += 1 - c["%s matrix_offset=0x%x" % (key, r["matrix_offset"])] += 1 - if r["zero_entries"]: - c["%s with zero entries" % key] += 1 - c["%s zero entries" % key] += r["zero_entries"] - c["%s blas tied" % key] += r.get("blas_count", 0) if r.get("buffer_ok") else 0 - else: - for f in ("count_fields_equal", "values_sorted_distinct", "items_contiguous", "item_words"): - c["%s %s=%s" % (key, f, r[f])] += 1 - c["%s items" % key] += r["count"] - return {"streams": len(rows), "counts": dict(sorted(c.items())), - "bvh_preceded_by": dict(sorted(bvh_after.items())), - "sizes": {k: dict(sorted(v.items())) for k, v in sorted(sizes.items())}, - "entry_or_item_counts": {k: dict(sorted(v.items())) for k, v in sorted(counts.items())}} - - -def _nonneg(text): - v = int(text, 0) - if v < 0: - raise argparse.ArgumentTypeError("must be 0 or more") - return v - - -def _positive(text): - v = int(text, 0) - if v < 1: - raise argparse.ArgumentTypeError("must be at least 1") - return v - - -def write_json_report(path, report): - """Publish a complete regular file, or write directly to a non-regular destination.""" - destination = os.path.realpath(path) - parent = os.path.dirname(destination) or "." - try: - mode = os.stat(destination).st_mode - except FileNotFoundError: - mode = None - if mode is not None and not stat.S_ISREG(mode): - with open(path, "w", encoding="utf-8", newline="\n") as f: - json.dump(report, f, indent=1) - f.write("\n") - return - if mode is not None: - # Retain the direct writer's permission check without truncating the report. - os.close(os.open(destination, os.O_WRONLY)) - - staged = tempfile.NamedTemporaryFile( - mode="w", encoding="utf-8", newline="\n", delete=False, - dir=parent, prefix=".bvh_groups-", suffix=".tmp", - ) - try: - with staged: - json.dump(report, staged, indent=1) - staged.write("\n") - if os.name != "nt": - os.chmod(staged.name, published_mode(destination)) - replace_retry(staged.name, destination) - finally: - try: - os.unlink(staged.name) - except FileNotFoundError: - pass - - -def main(argv=None): - ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) - ap.add_argument("archive") - ap.add_argument("--json", help="write rows and summary here (offsets, sizes, counts and check results only)") - ap.add_argument("--start", type=_nonneg) - ap.add_argument("--limit", type=_positive) - a = ap.parse_args(argv) - if a.json and os.path.exists(a.json) and os.path.exists(a.archive) and os.path.samefile(a.json, a.archive): - print("bvh_groups: --json would replace the archive", file=sys.stderr) - return 2 - try: - rows, summary = scan(a.archive, a.start, a.limit) - except (OSError, ValueError) as e: - print("bvh_groups: %s" % e, file=sys.stderr) - return 2 - for k, v in summary["counts"].items(): - print("%8d %s" % (v, k)) - for k, v in summary["bvh_preceded_by"].items(): - print("%8d bvh stream preceded by %s" % (v, k)) - if a.json: - write_json_report(a.json, {"source": a.archive, "summary": summary, "rows": rows}) - return 0 - - -if __name__ == "__main__": - try: # a redirected stdout is strict ANSI code page under -I; write '?' for what it cannot encode - sys.stdout.reconfigure(errors="replace") - except (AttributeError, ValueError, OSError): - pass - sys.exit(main()) diff --git a/tools/bvh_index.py b/tools/bvh_index.py deleted file mode 100644 index 0cc363df7..000000000 --- a/tools/bvh_index.py +++ /dev/null @@ -1,601 +0,0 @@ -"""Index the payloads of an RPF9 archive (or a directory of payloads) for BVH4 data. - -The RPF9 table of contents in this package is encrypted, so file names cannot be recovered without keys; this tool -does not try. It walks the data area, decompresses every zlib stream that decodes cleanly to its end, and -classifies the inflated bytes from their headers. Nothing it writes contains game payload bytes: the rows hold -offsets, sizes, counts, a header tag and a bounding box. - -The one signature it relies on was measured over the whole `*_bvh4` pack: a BVH stream has `flags = 0x81020006` -at offset 0x100, `totalSizeIn64BNodes` at 0x104, and wrapper words at 0x20/0x28 such that - - 0x140 + 64 * totalSizeIn64BNodes == u32@0x20 and u32@0x28 == u32@0x20 - 0x100 - -A stream is reported as `bvh4` only when all of that holds. The row also carries the exact XboxBvh4Header fields: -`crc32`, `numElements`, scene bounds, `offsetToNodes`, `offsetToPrimRemap`, `rootNodePtr`, `offsetToElements`, -`offsetToParents`, `compressionParams`, and the decoded root node index/type. A 208-byte instance record is -reported separately: it has the constant descriptor words listed in INSTANCE_WORDS and a 3x4 float matrix at 0x50. - -Usage: - python -I tools/bvh_index.py [--out index.json] [--csv index.csv] - [--start N] [--limit BYTES] [--max-inflate BYTES] - python -I tools/bvh_index.py [--out index.json] [--csv index.csv] - [--max-inflate BYTES] - ---start and --limit apply to a single archive only; with a directory they are an error (exit 2). ---max-inflate applies to every .rpf in the directory. -Archive rows include a fill histogram only when the complete node range was kept. - -Exit status is 0 even when nothing is found; the summary says how many streams were read. -""" -import argparse -import csv -import fnmatch -import json -import mmap -import os -import re -import struct -import sys -import tempfile -import time -import unicodedata -import zlib -from contextlib import suppress - -sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) -from file_mode import published_mode # noqa: E402 - -ROOT = os.path.dirname(os.path.abspath(__file__)) -if ROOT not in sys.path: - sys.path.insert(0, ROOT) -from zero_span import gap_split # noqa: E402 - -ZHDR = re.compile(rb"\x78[\x01\x5e\x9c\xda]") -TAG = 0x81020006 -HEAD = 0x140 -TAG_OFF = 0x100 -N_OFF = 0x104 -END_OFF = 0x20 -TAIL_OFF = 0x28 -AABB_OFF = 0x110 -INVALID_NODE = 0xFFFFFFFF -NODE_TYPE_NAMES = {0: "tri0", 1: "tri1", 2: "tri2", 3: "tri3", - 4: "box16", 5: "box32", 6: "instance", 7: "aabb_geometry"} -INSTANCE_WORDS = ((0x08, 0x50000080), (0x10, 1), (0x18, 0x500000A0), (0x20, 0x60000000), - (0x28, 0x500000B0), (0x30, 0x500000C0), (0x38, 0x50000050)) -FILL_BYTES = (0x00, 0x81, 0x94, 0x29) - - -def below_normal(): - if os.name == "nt": - import ctypes - from ctypes import wintypes - - k = ctypes.windll.kernel32 - # GetCurrentProcess returns a pointer-sized pseudo-handle. - k.GetCurrentProcess.argtypes = () - k.GetCurrentProcess.restype = wintypes.HANDLE - k.SetPriorityClass.argtypes = (wintypes.HANDLE, wintypes.DWORD) - k.SetPriorityClass.restype = wintypes.BOOL - k.SetPriorityClass(k.GetCurrentProcess(), 0x00004000) - - -def decode_node_pointer(value): - """Decode the low three type bits and the high 29-bit 64-byte node index.""" - typ = value & 7 - invalid = value == INVALID_NODE - return {"ptr": value, "index": value >> 3, "type": typ, - "name": "invalid" if invalid else NODE_TYPE_NAMES[typ], "invalid": invalid} - - -def parse_header(head): - """Parse the 64-byte XboxBvh4Header at payload offset 0x100. - - The field names, types and offsets match the public XboxBvh4Header used by the Xbox DXR traversal - shaders. The offsets in the header are relative to 0x100, the start of this header. The source - declares offsetToPrimRemap as int32_t and offsetToParents as uint32_t, so they are unpacked differently. - """ - if len(head) < HEAD or struct.unpack_from("") - if close >= 0: - rest = rest[close + 2:] - start = rest.find(b"<") - end = rest.find(b">", start + 1) - if 0 <= start < end: - name = rest[start + 1:end].strip().split(b" ")[0].split(b"/")[0].lstrip(b"!-") - row["root_element"] = name.decode("ascii", "replace")[:64] - return row - probe = head[:256] - if size >= 64 and len(probe) >= 64: - printable = sum(1 for c in probe if c in (9, 10, 13) or 32 <= c < 127) - if printable >= len(probe) * 0.9 and b"<" in probe and b">" in probe: - row.update(kind="xml", signature="xml", fragment=True) - return row - if size == 208 and all(struct.unpack_from("> 16, lo16=w & 0xFFFF) - return row - if 0x60 <= size <= 0x100000 and len(head) >= 0x30 and head[:8] == bytes(8) \ - and struct.unpack_from("= HEAD and len(head) >= HEAD and struct.unpack_from("= 8 else size - if not 0 <= pos <= size: - raise ValueError("start offset is outside the archive") - end = min(size, pos + limit) if limit else size - span = end - pos - last, zero, unread = pos, 0, 0 - while pos < end: - mt = ZHDR.search(m, pos, end) - if not mt: - break - s = mt.start() - # Bounded by the scan window (the archive without --limit): a stream that runs past it is left out, - # so readable + zero + unread add up to the span, as in story_index (#712). - got = inflate_stream(m, s, end, max_inflate) - if got is None: - pos = s + 1 - continue - head, kept, total, used = got - gap_zero, gap_unread = gap_split(m, last, s) - zero += gap_zero - unread += gap_unread - row = classify(head, total, kept[-HEAD:] if len(kept) >= HEAD else kept) - row.update(source=path, offset=s, stored=used, size=total) - if row["kind"] in ("bvh4", "bvh4-chunk") and row["declared_bytes"] <= len(kept): - body = kept[HEAD:HEAD + row["node_count"] * 64] - row["fill"] = {("%02x" % b): body.count(bytes([b])) for b in FILL_BYTES if body.count(bytes([b]))} - row["fill"]["total"] = len(body) - rows.append(row) - last = pos = s + used - gap_zero, gap_unread = gap_split(m, last, end) - zero += gap_zero - unread += gap_unread - finally: - m.close() - return rows, [summarize(rows, path, span, zero, unread, time.time() - t0)] - - -def summarize(rows, source, span, zero, unread, elapsed): - kinds = {} - for r in rows: - kinds[r["kind"]] = kinds.get(r["kind"], 0) + 1 - stored = sum(r["stored"] for r in rows) - inflated = sum(r["size"] for r in rows) - bvh = [r for r in rows if r["kind"] in ("bvh4", "bvh4-chunk")] - total_nodes = sum(r["node_count"] for r in bvh) - return {"source": str(source), "streams": len(rows), "kinds": kinds, "stored": stored, - "inflated": inflated, "span": span, "zero_padding": zero, "unread": unread, - "readable_fraction": round(stored / span, 6) if span else None, - "bvh4_streams": len(bvh), "bvh4_complete": sum(1 for r in bvh if r["kind"] == "bvh4"), - "bvh4_chunked": sum(1 for r in bvh if r["kind"] == "bvh4-chunk"), - "bvh4_nodes": total_nodes, "bvh4_node_bytes": total_nodes * 64, - "elapsed_s": round(elapsed, 2)} - - -def find_payloads(root, patterns, skipped=None): - """The files under root matching each glob pattern, as a sorted list per pattern. Hidden names are left out and - links are followed, as glob.glob("**", recursive=True) did. Unlike glob, a folder that cannot be listed is not - dropped silently: it is named on stderr and added to skipped, so the run reports itself incomplete.""" - found = {p: [] for p in patterns} - - def unlistable(error): - print(f"{error.filename or root}: skipped ({error.strerror or error})", file=sys.stderr) - if skipped is not None: - skipped.append(error.filename or root) - - for folder, dirs, names in os.walk(root, onerror=unlistable, followlinks=True): - dirs[:] = [d for d in dirs if not d.startswith(".")] - for name in names: - if not name.startswith("."): - for p in patterns: - if fnmatch.fnmatch(name, p): - found[p].append(os.path.join(folder, name)) - return [sorted(found[p]) for p in patterns] - - -def scan_dir(path, max_inflate=1 << 28, skipped=None): - rpfs, bins = find_payloads(os.fspath(path), ("*.rpf", "*.bin"), skipped) - rows, summaries = [], [] - if rpfs: - for p in rpfs: - try: - r, s = scan_rpf(p, max_inflate=max_inflate) - except (OSError, ValueError) as e: # one unreadable archive should not lose the others - print(f"{p}: skipped ({e})", file=sys.stderr) - if skipped is not None: - skipped.append(p) # the caller still reports the run as incomplete - continue - rows += r - summaries.extend(s) - return rows, summaries - for p in bins: - size = os.path.getsize(p) - with open(p, "rb") as f: - head = f.read(HEAD) - if size > HEAD: - f.seek(-HEAD, os.SEEK_END) - tail = f.read(HEAD) - else: - tail = head - row = classify(head, size, tail) - row.update(source=p, offset=0, stored=size, size=size) - # A chunk exposes the header but has only a prefix of the declared node buffer. - if row["kind"] == "bvh4": - with open(p, "rb") as f: - body = f.read(HEAD + row["node_count"] * 64)[HEAD:] - row["fill"] = {("%02x" % b): body.count(bytes([b])) for b in FILL_BYTES} - row["fill"]["total"] = len(body) - rows.append(row) - summary = summarize(rows, path, 0, 0, 0, 0.0) - summary["span"] = None - summary["readable_fraction"] = None - return rows, [summary] - - -def _make_parent(path): - """Create the folder a report lives in: the scan is over by the time we write, so a missing - folder used to end the run in a FileNotFoundError and lose the result.""" - parent = os.path.dirname(os.path.abspath(path)) - if parent: - os.makedirs(parent, exist_ok=True) - - -def _publish(dest, write, newline): - """Write a report next to `dest` and swap it in, so a run that fails or is interrupted while writing (a - serialization error, a full disk, Ctrl+C) leaves the previous report as it was instead of a truncated one. - The result keeps the previous report's permission bits, or gets the usual ones for a new file.""" - _make_parent(dest) - directory = os.path.dirname(os.path.abspath(dest)) - temp = None - try: - with tempfile.NamedTemporaryFile(mode="w", encoding="utf-8", newline=newline, dir=directory, - prefix=".bvh_index-", suffix=".tmp", delete=False) as f: - temp = f.name - write(f) - os.chmod(temp, published_mode(dest)) - os.replace(temp, dest) - except BaseException: - if temp is not None: - with suppress(OSError): - # The staging file may have inherited a read-only destination's mode; make it deletable - # first, or Windows strands it beside the report when the replace fails. - os.chmod(temp, 0o600) - os.unlink(temp) - raise - - -def report_path_problem(path): - """Why a report can't be written at `path`, or None: its folder can't be created (a file in the way, a - missing drive) or can't be written to. Checked before the scan, so a mistyped destination doesn't cost a run.""" - parent = os.path.dirname(os.path.abspath(path)) - try: - os.makedirs(parent, exist_ok=True) - except OSError as e: - return f"cannot create its folder: {e}" - if not os.access(parent, os.W_OK): - return f"its folder is not writable: {parent}" - if os.path.exists(path) and not os.access(path, os.W_OK): - return "the existing report is read-only" - return None - - -def write_outputs(rows, summaries, out, csv_path): - if out: - payload = summaries if len(summaries) > 1 else (summaries[0] if summaries else {}) - _publish(out, lambda f: json.dump({"summary": payload, "streams": rows}, f, indent=0), "\n") - if csv_path: - cols = ["source", "offset", "stored", "size", "kind", "signature", "version", "node_count", - "node_bytes", "declared_bytes", "tail_offset", "flags", "crc32", "num_elements", - "offset_to_nodes", "offset_to_prim_remap", "root_node_ptr", "root_node_index", - "root_node_type", "root_node_type_name", "root_node_invalid", "offset_to_elements", - "offset_to_parents", - "compression_params", "dehydrated", "chunked", "bounds_min", "bounds_max", - "hash", "off_a0", "hi16", "lo16", "desc_word", "fragment"] - - def write_csv(f): - w = csv.DictWriter(f, fieldnames=cols, extrasaction="ignore", lineterminator="\n") - w.writeheader() - for r in rows: - r = dict(r) - for k in ("bounds_min", "bounds_max", "matrix"): - if k in r: - r[k] = " ".join(str(v) for v in r[k]) - w.writerow(r) - - _publish(csv_path, write_csv, "") - - -def byte_count(text): - """--limit: 0 or less used to scan nothing (negative) or everything (0 is falsy) without a word.""" - try: - value = int(text, 0) - except ValueError: - raise argparse.ArgumentTypeError(f"invalid int value: {text!r}") from None - if value < 1: - raise argparse.ArgumentTypeError("must be at least 1") - return value - - -def offset(text): - """--start: a negative offset would slice the archive from its end.""" - try: - value = int(text, 0) - except ValueError: - raise argparse.ArgumentTypeError(f"invalid int value: {text!r}") from None - if value < 0: - raise argparse.ArgumentTypeError("must be 0 or more") - return value - - -_PC_CASE_SENSITIVE = 11 # on macOS; os.pathconf_names doesn't list it - - -def _case_insensitive_volume(path): - """True when the volume that will hold `path` ignores letter case, as macOS's default APFS volume does. - os.path.normcase folds case only on Windows, so on macOS `R.json` and `r.json` would pass as two reports.""" - if sys.platform != "darwin": - return False - while not os.path.exists(path): - parent = os.path.dirname(path) - if parent == path: - break - path = parent - try: - return os.pathconf(path, _PC_CASE_SENSITIVE) == 0 - except (OSError, ValueError): - return True # the macOS default; folding can only refuse a pair, never overwrite one - - -def _path_key(path): - path = os.path.normcase(os.path.realpath(path)) - if _case_insensitive_volume(path): - # APFS and HFS+ also treat composed and decomposed accents as one name. - path = unicodedata.normalize("NFD", path.casefold()) - return path - - -def same_output_path(first, second): - if _path_key(first) == _path_key(second): - return True - try: - return os.path.samefile(first, second) - except OSError: - return False - - -def _inside(path, folder): - """True when `path` is `folder` or lies below it, compared as the report check compares paths.""" - path, folder = _path_key(path), _path_key(folder) - try: - return os.path.commonpath([path, folder]) == folder - except ValueError: # different drives on Windows - return False - - -def main(argv=None): - ap = argparse.ArgumentParser(description=__doc__.splitlines()[0]) - ap.add_argument("target", help="RPF9 archive or a directory of .rpf/.bin payloads") - ap.add_argument("--out", help="write JSON (summary + per-stream rows)") - ap.add_argument("--csv", help="write CSV (offset, size, signature, readable fields)") - ap.add_argument("--start", type=offset, help="data-area start (default: u32 at file offset 4)") - ap.add_argument("--limit", type=byte_count, help="stop after this many bytes of the data area") - ap.add_argument("--max-inflate", type=byte_count, default=1 << 28, - help="keep at most this many bytes of one stream") - a = ap.parse_args(argv) - if a.out and a.csv and same_output_path(a.out, a.csv): - ap.error("--out and --csv must use different paths") - if a.out and same_output_path(a.target, a.out): - ap.error("--out must not overwrite the source") - if a.csv and same_output_path(a.target, a.csv): - ap.error("--csv must not overwrite the source") - for flag, path in (("--out", a.out), ("--csv", a.csv)): - if path and os.path.isdir(path): - ap.error(f"{flag} is a folder, not a report file: {path}") - if os.path.isdir(a.target): - manifest = os.path.join(a.target, "index.json") - - def unlistable(error): - # os.walk skips a folder it cannot list unless onerror stops it. A report path inside that folder could - # then be an input this check never saw, so refuse it. Any other unlistable folder is left to the scan, - # which names it and reports the run as incomplete (exit 1). - folder = error.filename or a.target - if _inside(path, folder): - ap.error(f"{flag} cannot be checked against the inputs: cannot list {folder}: " - f"{error.strerror or error}") - - for flag, path in (("--out", a.out), ("--csv", a.csv)): - if not path: - continue - if os.path.isfile(manifest) and same_output_path(path, manifest): - ap.error(f"{flag} would overwrite the carve manifest: {path}") - if os.path.isfile(path): - for root, _dirs, names in os.walk(a.target, onerror=unlistable): - for name in names: - if name.lower().endswith((".json", ".csv")): - continue - if same_output_path(os.path.join(root, name), path): - ap.error(f"{flag} would overwrite an input file: {path}") - if os.path.isdir(a.target) and (a.start is not None or a.limit is not None): - ap.error("--start and --limit apply to a single archive, not a directory") - for flag, path in (("--out", a.out), ("--csv", a.csv)): - problem = report_path_problem(path) if path else None - if problem: - ap.error(f"{flag} cannot be written to {path}: {problem}") - below_normal() - if os.path.isdir(a.target): - skipped = [] - rows, summaries = scan_dir(a.target, a.max_inflate, skipped) - else: - skipped = [] - try: - rows, summaries = scan_rpf(a.target, a.start, a.limit, a.max_inflate) - except (OSError, ValueError) as e: - # An OSError repeats the target we already print, and reprs it: name the reason once. - reason = e.strerror if isinstance(e, OSError) and e.filename and e.strerror else e - print(f"{a.target}: {reason}", file=sys.stderr) - return 2 - for s in summaries: - print(json.dumps(s, indent=1)) - try: - write_outputs(rows, summaries, a.out, a.csv) - except OSError as e: # a full disk, a folder removed or locked since the preflight: a line, not a traceback - print(f"cannot write the report: {e}", file=sys.stderr) - return 2 - if not rows: - print("no zlib streams found", file=sys.stderr) - if skipped: - print(f"{len(skipped)} archive(s) or folder(s) could not be scanned; the report is incomplete", file=sys.stderr) - return 1 - return 0 - - -if __name__ == "__main__": - try: # a redirected stdout is strict ANSI code page under -I; write '?' for what it cannot encode - sys.stdout.reconfigure(errors="replace") - except (AttributeError, ValueError, OSError): - pass - sys.exit(main()) diff --git a/tools/bvh_match.py b/tools/bvh_match.py deleted file mode 100644 index d156c2444..000000000 --- a/tools/bvh_match.py +++ /dev/null @@ -1,455 +0,0 @@ -"""Find the drawable geometry a dehydrated BLAS was built from, over `rpf9dump`'s model export. - -A dehydrated BLAS (docs/bvh.md §3.1, §4a) keeps, for every leaf, the index of the geometry it came from and the -primitive it uses. That index counts the geometries of one model in the drawable's primary LOD, leaving out the -geometries whose shader the BVH does not keep. So a BLAS is a triangle count per geometry index, and the drawable it -came from has exactly those counts among the geometries of one of its models: - -1. read that signature from the BLAS leaves (a leaf holding two primitives counts twice); -2. keep every (drawable, model) of a `rpf9dump models` manifest whose per-geometry triangle counts contain the - signature as an ordered subsequence - the geometries a model uses are `MeshTris`, grouped by `MeshModels`; -3. for each survivor, read the geometries it points at from the model's OBJ (positions are the decoder's exact - float32, faces are in primitive order) and check the rehydration against what the BLAS stores with - tools/bvh_geometry_check.py (bounds, overrides, paired-leaf edges, internal area). - -Which geometries the BVH leaves out follows from their material's render bucket (docs/bvh.md §4a, ASSET-349): the -byte at +57 of the shader record, which `rpf9dump models` writes as `RenderBucket`. A geometry is kept when the low 7 -bits of that byte are 0 or 3 and left out otherwise (KEPT_BUCKETS; bit 7 is ignored). When a geometry of a -model has no bucket in the manifest (its shader index is not in the material list, or an older export without the -field) the rule cannot be applied to that model and every geometry is a candidate; the checks then decide. ---no-bucket-rule turns it off. --skip-shaders (or BVH_SKIP_SHADERS) still leaves out geometries by shader name hash -on top of it; the hashes are game data, for local use only. - -The instance transform is the 3x4 at +0x50 of the BLAS's 208-byte instance descriptor (docs/bvh.md §3.2). Without -it, every leaf of a rotated structure falls outside the header bounds and a correct geometry is rejected. - -The manifest is one window of an archive: `rpf9dump models ` exports every drawable it recovers from -that slice, and a slice holds one region's. A BLAS whose drawable sits elsewhere in the archive therefore finds no -candidate in it, which is not the same as a geometry that fails the checks; the tool says which case it is. - -Standard library only. Reads the user's own package and writes nothing by default. Exit status is 0 when a -candidate is consistent, 1 when none is, and 2 on an input error. - -Usage: - python -I tools/bvh_match.py --descriptor - [--models DIR] [--header-offset N] [--descriptor-offset N] - [--transform 12 floats] [--skip-shaders HEX,HEX] [--no-bucket-rule] [--unordered] - [--embeddings N] [--top N] [--names] [--write DIR] [--json FILE] - ---write DIR writes the matched geometries as float3/uint32 buffers plus an export.json, the shape -tools/bvh_rehydrate.py takes: the transform is recorded in it rather than applied to the vertices. -""" -import argparse -import json -import os -import stat -import struct -import sys -import tempfile -from collections import Counter - -sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) -import bvh_geometry_check as C # noqa: E402 -import bvh_rehydrate as R # noqa: E402 -from file_mode import published_mode # noqa: E402 -from replace_retry import replace as replace_retry # noqa: E402 -from report_paths import same_report_path # noqa: E402 - -INSTANCE_TRANSFORM_OFFSET = 0x50 -SKIP_SHADERS_ENV = "BVH_SKIP_SHADERS" -# Render buckets (low 7 bits of the byte at shader record +57, `RenderBucket` in the manifest) whose geometries the -# BVH keeps; every other bucket (1, 2, 4, 5, 6) is left out. Bit 7 does not change the choice (docs/bvh.md §4a, -# ASSET-349). -KEPT_BUCKETS = frozenset((0, 3)) -BUCKET_MASK = 0x7F - - -def bucket_kept(bucket): - """True when the BVH keeps a geometry whose material has this render bucket, None when the bucket is unknown.""" - return None if bucket is None else (bucket & BUCKET_MASK) in KEPT_BUCKETS - - -def leaf_signature(src, header_offset=0): - """Triangles per leaf geometry index; a leaf that holds two primitives counts as two triangles.""" - hdr = R.Header(src, header_offset) - body = bytes(src[header_offset:header_offset + hdr.total_bytes]) # the leaf arrays count from the header - per = {} - for _, geometry, _, _, prim1, _ in R.leaf_records(body, hdr): - per[geometry] = per.get(geometry, 0) + (1 if prim1 is None else 2) - return [per.get(i, 0) for i in range(max(per) + 1)] if per else [] - - -def parse_shader_hashes(text): - """'0x1234abcd,89abcdef' -> frozenset of ints; empty or None -> empty set (the rule is not applied).""" - return frozenset(int(x, 16) for x in (text or "").replace(" ", "").split(",") if x) - - -def read_transform(path, at=0): - """The 3x4 at +0x50 of a 208-byte instance descriptor, as three rows of four floats.""" - with open(path, "rb") as f: - f.seek(at + INSTANCE_TRANSFORM_OFFSET) - raw = f.read(48) - if len(raw) != 48: - raise ValueError("%s is shorter than a 208-byte instance descriptor at %d" % (path, at)) - values = struct.unpack("<12f", raw) - return tuple(values[4 * row:4 * row + 4] for row in range(3)) - - -def embeddings(signature, counts, cap, ordered=True): - """Every way to pick distinct geometries of `counts` matching `signature` (index lists), at most `cap` of them. - - ordered: the picked indices must increase (a prefix is the common case); otherwise any order is allowed. - """ - if cap <= 0 or len(signature) > len(counts): - return [] - - latest = [len(counts) - 1] * len(signature) - if ordered: - # Match the signature backwards once. An index later than latest[i] leaves - # too few matching geometries for the rest of the signature. - k = len(counts) - 1 - for i in reversed(range(len(signature))): - while k >= 0 and counts[k] != signature[i]: - k -= 1 - if k < 0: - return [] - latest[i] = k - k -= 1 - elif Counter(signature) - Counter(counts): - # In any order, each triangle count just needs enough distinct geometries. - return [] - - out = [] - - def walk(i, j, acc): - if i == len(signature): - out.append(list(acc)) - return - for k in range(j, latest[i] + 1): - if counts[k] == signature[i] and (ordered or k not in acc): - acc.append(k) - walk(i + 1, k + 1 if ordered else 0, acc) - acc.pop() - if len(out) == cap: - return - - walk(0, 0, []) - return out - - -def model_geometries(item): - """[(mesh index, model, geometry, triangles, shader hash or None, render bucket or None)] for one manifest item, - in mesh order. - - The mesh index is the geometry's `o` group in the item's OBJ: the manifest arrays and the OBJ groups are - written in the same order. - """ - tris = item.get("MeshTris") - if tris is None: - raise ValueError("the manifest has no MeshTris: re-export with an rpf9dump that writes per-geometry counts") - models = item.get("MeshModels") or [0] * len(tris) - geometries = item.get("MeshGeoms") or list(range(len(tris))) - shaders = item.get("MeshShaders") or [None] * len(tris) - materials = item.get("Materials") or [] - hashes, buckets = [], [] - for index in shaders: - material = materials[index] if index is not None and 0 <= index < len(materials) else {} - hashes.append(int(material["Shader"], 16) if "Shader" in material else None) - bucket = material.get("RenderBucket") - buckets.append(bucket if isinstance(bucket, int) and not isinstance(bucket, bool) else None) - return list(zip(range(len(tris)), models, geometries, tris, hashes, buckets)) - - -def match_candidates(items, signature, skip, cap, ordered=True, buckets=True): - """Every (item, model, used geometry indices, kept geometries) whose triangle counts contain the signature. - - buckets: leave out the geometries whose render bucket the BVH does not keep (bucket_kept), in every model whose - geometries all have a bucket. skip: shader hashes left out as well, in every model whose geometries all have one. - """ - out = [] - for item in items: - meshes = model_geometries(item) - for model in sorted({mesh[1] for mesh in meshes}): - group = [mesh for mesh in meshes if mesh[1] == model] - # A geometry the BVH leaves out is not in the BLAS, so it takes no index in the signature. Without the - # bucket (or, for --skip-shaders, the hash) of every geometry of the group a rule cannot be applied to - # it: keep all of them and let the checks decide. - by_bucket = buckets and all(mesh[5] is not None for mesh in group) - rule = bool(skip) and all(mesh[4] is not None for mesh in group) - kept = [mesh for mesh in group - if (not by_bucket or bucket_kept(mesh[5])) and (not rule or mesh[4] not in skip)] - for used in embeddings(signature, [mesh[3] for mesh in kept], cap, ordered): - out.append({"item": item, "model": model, "used": used, "kept": kept, - "rule": rule, "skipped": bool(skip), "by_bucket": by_bucket, "buckets": buckets}) - return out - - -def read_groups(path): - """[(positions, faces)] per `o` group of an OBJ, in file order; faces are 0-based indices into that group. - - tools/rpf9dump reads `RageModelDecoder.CreateObj` output: one group per geometry, its vertices in buffer order - and its faces in primitive order (docs/bvh.md §4a: the leaves address triangles in primitive order). - """ - groups, positions, faces, base, started = [], [], [], 0, False - - def flush(): - nonlocal positions, faces, base, started - if started or positions or faces: - groups.append((positions, faces)) - base += len(positions) - positions, faces, started = [], [], False - - with open(path, "rb") as f: - for raw in f: - line = raw.decode("ascii", "replace").strip() - if len(line) < 2: - continue - tag, _, rest = line.partition(" ") - if tag == "o": - flush() - started = True - elif tag == "v": - x, y, z = rest.split()[:3] - positions.append((float(x), float(y), float(z))) - elif tag == "f": - corners = rest.split() - if len(corners) != 3: - raise ValueError("%s: a face with %d corners; only triangles are expected" % (path, len(corners))) - faces.append(tuple(int(corner.split("/")[0]) - 1 - base for corner in corners)) - flush() - return groups - - -def build_geometry(group, transform=None): - """A bvh_rehydrate.Geometry from one OBJ group: float3 vertices, uint32 triangles, the instance transform.""" - positions, faces = group - if not faces: - raise ValueError("a geometry without triangles cannot be an index of a BLAS leaf") - for face in faces: - if min(face) < 0 or max(face) >= len(positions): - raise ValueError("an OBJ face refers to a vertex outside its group") - vb = b"".join(struct.pack("<3f", *p) for p in positions) - ib = b"".join(struct.pack("<3I", *face) for face in faces) - return R.Geometry(vb, 12, ib, False, transform) - - -def score(src, candidate, groups, transform, header_offset=0): - """Rehydrate the candidate's geometries and run bvh_geometry_check over them.""" - used = [candidate["kept"][k] for k in candidate["used"]] - for mesh in used: - if mesh[0] >= len(groups): - raise ValueError("the manifest lists %d geometries but its OBJ holds %d: re-export the window" - % (max(m[0] for m in used) + 1, len(groups))) - geometries = [build_geometry(groups[mesh[0]], transform) for mesh in used] - return C.check(src, geometries, header_offset) - - -def export_buffer_names(count): - """The (vertex, index) buffer names write_export gives each of `count` matched geometries.""" - return [("g%d_f3.bin" % i, "g%d_tri.bin" % i) for i in range(count)] - - -def write_export(directory, candidate, groups, transform): - """Write the matched geometries as float3/uint32 buffers plus the export.json tools/bvh_rehydrate.py is given. - - The vertices are the OBJ's float32 as they are, so the instance transform is recorded rather than applied: pass - it to bvh_rehydrate.py with --transform, exactly as the descriptor gave it here. - """ - os.makedirs(directory, exist_ok=True) - rows = [] - names = export_buffer_names(len(candidate["used"])) - for k in candidate["used"]: - mesh = candidate["kept"][k] - geometry = build_geometry(groups[mesh[0]]) - vb, ib = names[len(rows)] - with open(os.path.join(directory, vb), "wb") as f: - f.write(geometry.vertices) - with open(os.path.join(directory, ib), "wb") as f: - f.write(geometry.indices) - rows.append({"index": len(rows), "model": candidate["model"], "drawable_geometry": mesh[2], - "vertices": len(geometry.vertices) // 12, "triangles": len(geometry.indices) // 12, - "vertex_format": 6, "index_format": 42, "stride": 12, "vb": vb, "ib": ib, - "instance_transform": False, - "transform": None if transform is None else [v for row in transform for v in row]}) - with open(os.path.join(directory, "export.json"), "w", encoding="utf-8", newline="\n") as f: - json.dump(rows, f, indent=1) - return rows - - -def describe(candidate, names): - item = candidate["item"] - used = [candidate["kept"][k][2] for k in candidate["used"]] - label = ("%-40s " % item["Name"]) if names else "" - note = " (shader rule not applied)" if candidate["skipped"] and not candidate["rule"] else "" - if candidate.get("buckets") and not candidate.get("by_bucket"): - note += " (bucket rule not applied: a geometry has no render bucket)" - return "%sstream 0x%-10x model %d geometry %s%s" % (label, item["Offset"], candidate["model"], used, note) - - -def write_json_report(path, report): - """Publish a complete regular file, or write directly to a non-regular destination.""" - destination = os.path.realpath(path) - parent = os.path.dirname(destination) or "." - try: - mode = os.stat(destination).st_mode - except FileNotFoundError: - mode = None - if mode is not None and not stat.S_ISREG(mode): - with open(path, "w", encoding="utf-8", newline="\n") as f: - json.dump(report, f, indent=1) - return - if mode is not None: - # Retain the direct writer's permission check without truncating the report. - os.close(os.open(destination, os.O_WRONLY)) - - staged = tempfile.NamedTemporaryFile( - mode="w", encoding="utf-8", newline="\n", delete=False, - dir=parent, prefix=".bvh_match-", suffix=".tmp", - ) - try: - with staged: - json.dump(report, staged, indent=1) - if os.name != "nt": - os.chmod(staged.name, published_mode(destination)) - replace_retry(staged.name, destination) - finally: - try: - os.unlink(staged.name) - except FileNotFoundError: - pass - - -def main(argv=None): - ap = argparse.ArgumentParser(description="Find the drawable geometry a dehydrated BLAS was built from.") - ap.add_argument("dehydrated") - ap.add_argument("manifest") - ap.add_argument("--models", help="directory of the OBJs (default: the manifest's directory)") - ap.add_argument("--descriptor", help="208-byte instance descriptor; its 3x4 at +0x50 is the geometry transform") - ap.add_argument("--descriptor-offset", type=int, default=0) - ap.add_argument("--transform", help="the same 3x4 as 12 comma-separated floats, instead of --descriptor") - ap.add_argument("--header-offset", type=int, default=0, help="the 64-byte header's offset in the file") - ap.add_argument("--skip-shaders", default=os.environ.get(SKIP_SHADERS_ENV, ""), - help="shader name hashes of the geometries the BVH leaves out (game data; local use only)") - ap.add_argument("--no-bucket-rule", action="store_true", - help="do not leave out geometries by render bucket (by default only buckets 0 and 3 are kept)") - ap.add_argument("--unordered", action="store_true", help="also try the geometries in any order") - ap.add_argument("--embeddings", type=int, default=64, help="at most this many index choices per model") - ap.add_argument("--top", type=int, default=8, help="how many scored candidates to print") - ap.add_argument("--names", action="store_true", help="print drawable names (game data: local use only)") - ap.add_argument("--write", metavar="DIR", help="write the matched geometries here as float3/uint32 buffers " - "and an export.json for tools/bvh_rehydrate.py") - ap.add_argument("--json", help="write the report here") - a = ap.parse_args(argv) - if a.json: - if os.path.isdir(a.json): - print("error: --json is a directory: %s" % a.json, file=sys.stderr) - return 2 - # The report is written last, after the inputs have been read, so an aliased input would silently - # be replaced by it. Refuse the alias before any input is opened, as the other report tools do. - for what, other in (("the dehydrated input", a.dehydrated), ("the manifest", a.manifest), - ("the --descriptor input", a.descriptor)): - if other and same_report_path(a.json, other): - print("error: --json would overwrite %s: %s" % (what, other), file=sys.stderr) - return 2 - if a.write and same_report_path(a.json, os.path.join(a.write, "export.json")): - print("error: --json would overwrite --write's export.json: %s" % a.json, file=sys.stderr) - return 2 - try: - with open(a.dehydrated, "rb") as f: - src = f.read() - with open(a.manifest, encoding="utf-8") as f: - manifest = json.load(f) - if not isinstance(manifest, dict): - raise ValueError("%s is not a JSON object (got %s)" % (a.manifest, type(manifest).__name__)) - items = manifest.get("Items") or [] - if not items: - raise ValueError("%s has no Items: the export found no model in its window, so there is nothing to match " - "the BLAS against" % a.manifest) - models_dir = a.models or os.path.dirname(os.path.abspath(a.manifest)) - transform = None - if a.transform: - transform = R.parse_transform(a.transform) - elif a.descriptor: - transform = read_transform(a.descriptor, a.descriptor_offset) - signature = leaf_signature(src, a.header_offset) - if not signature: - raise ValueError("the BLAS has no leaves") - candidates = match_candidates(items, signature, parse_shader_hashes(a.skip_shaders), a.embeddings, - not a.unordered, not a.no_bucket_rule) - except (OSError, ValueError, KeyError, IndexError, TypeError, struct.error) as e: - print("error: %s" % e, file=sys.stderr) - return 2 - if transform is None: - print("no --descriptor or --transform: the geometry is checked without the instance transform", file=sys.stderr) - print("triangles per geometry index: %s" % signature) - print("%d candidates from %d models in the manifest" % (len(candidates), len(items))) - if not candidates: - # Distinguishing "the geometry is not in this export" from "the rule does not fit" saves the confusion of an - # empty run: a window holds one region's drawables, and a BLAS whose drawable lives elsewhere cannot match. - print("nothing to score: no model in this manifest has those triangle counts per geometry. Either the drawable " - "is outside the exported window (the manifest's Scan.Start/Scan.Length, when present, says which window " - "it is), or its geometry list does not follow the rule (docs/bvh.md §4a)") - results, groups, errors = [], {}, 0 - for candidate in candidates: - item = candidate["item"] - path = os.path.join(models_dir, item["File"]) - try: - if path not in groups: - groups[path] = read_groups(path) - report = score(src, candidate, groups[path], transform, a.header_offset) - except (OSError, ValueError, KeyError, IndexError, TypeError, struct.error) as e: - errors += 1 - print(" %s: %s" % (describe(candidate, a.names), e)) - continue - results.append((not report["consistent"], report["internal_area"], report, candidate)) - results.sort(key=lambda r: (r[0], r[1])) - best = next((r[1] for r in results if not r[0]), None) - for bad, area, report, candidate in results[:max(1, a.top)]: - ratio = "" if best is None or not best else " (x%.3f)" % (area / best) - print(" %-10s %s | outside %d of %d, gap %.1e, overrides %d/%d, area %.6g%s" % ( - "consistent" if not bad else "rejected", describe(candidate, a.names), report["leaves_outside"], report["leaves"], - report["bounds_gap"], report["overrides_consistent"], report["overrides_inconsistent"], area, ratio)) - consistent = [r for r in results if not r[0]] - print("%d of %d scored candidates are consistent%s" % (len(consistent), len(results), "" if not errors else " (%d could not be read)" % errors)) - if len(consistent) > 1: - print("more than one candidate is consistent: the signature and the checks do not decide between them; " - "the internal box area (the smallest one) is the tie-break") - if a.write: - if not consistent: - print("nothing written: no candidate is consistent") - else: - match = consistent[0][3] - if a.json: - # The report is written after the export, so it must not land on one of the buffers the - # export is about to write either. Their names depend on the match, hence the check here. - for vb, ib in export_buffer_names(len(match["used"])): - for name in (vb, ib): - if same_report_path(a.json, os.path.join(a.write, name)): - print("error: --json would overwrite --write's %s: %s" % (name, a.json), file=sys.stderr) - return 2 - rows = write_export(a.write, match, groups[os.path.join(models_dir, match["item"]["File"])], transform) - print("wrote %d geometries to %s%s" % (len(rows), a.write, - "; pass the transform in export.json to bvh_rehydrate.py with --transform" if transform else "")) - if a.json: - match = consistent[0][3] if consistent else None - try: - write_json_report(a.json, { - "signature": signature, "consistent": bool(consistent), "scored": len(results), - "matched": None if match is None else { - "offset": match["item"]["Offset"], "model": match["model"], - "geometry": [match["kept"][k][2] for k in match["used"]], - "triangles": [match["kept"][k][3] for k in match["used"]], - "name": match["item"]["Name"] if a.names else None}, - }) - except OSError as e: - print("error: cannot write %s: %s" % (a.json, e.strerror or e), file=sys.stderr) - return 2 - return 0 if consistent else 1 - - -if __name__ == "__main__": - try: # a redirected stdout is strict ANSI code page under -I; write '?' for what it cannot encode - sys.stdout.reconfigure(errors="replace") - except (AttributeError, ValueError, OSError): - pass - sys.exit(main()) diff --git a/tools/bvh_packing_check.py b/tools/bvh_packing_check.py deleted file mode 100644 index e5b662722..000000000 --- a/tools/bvh_packing_check.py +++ /dev/null @@ -1,549 +0,0 @@ -"""Check the dehydrated BVH4 packing of docs/bvh.md §4a on every stream of a pack, without geometry. - -`tools/bvh_rehydrate.py` reads a dehydrated BLAS with the packing recorded in docs/bvh.md §4a, and it matches -`XboxBvhBuilder.dll` byte for byte on 8 samples. This tool tests the same reading on every stream of a pack. A -stream passes when its bytes form exactly one tree under that reading: - -* header: the dehydrated flag is set, and the leaf records and the box groups fit in the declared structure; -* level table: the last word is the level count; before it, the level ends are in order, a multiple of the node - size apart, and end before the table; -* groups: every group's node words, child pointers and stored values fit in the bytes its nodes occupy; -* nodes: 1 to 4 children, and no override bit for a slot past the child count; -* child pointers: a box pointer names a box node of its own width (BOX16 or BOX32) at a lower level; a TRI0 pointer - names a leaf slot, `offsetToElements + 64 * k` with `k < numElements`; -* tree: the root is a box node and nothing points to it, every other box node has exactly one parent, and every - leaf is named by exactly one pointer; -* leaves: every vertex-order byte puts the three vertices in three different slots; -* stored values: each override lies inside `sceneBounds` mapped through the leaf frame (BOX16 widened to the half - grid; an infinite BOX16 value only where the bound is outside the half range). Where every slot of the root stores - a component, the root's union of that component must equal the bound. - -None of this reads geometry, so it runs on the whole pack. Output holds offsets and counts only. - -Standard library only. - -Usage: - python -I tools/bvh_packing_check.py [--workers N] [--window BYTES] [--start N] [--limit BYTES] - [--json report.json] - python -I tools/bvh_packing_check.py [ ...] [--header-offset N] [--json report.json] - -An .rpf is scanned the way tools/bvh_index.py scans it (every zlib stream that inflates to its end), split into -windows that run in parallel; a stream belongs to the window it starts in. A `bvh4-chunk` is joined with the streams -after it up to its declared end (docs/bvh.md §6). A .bin is one stream; --header-offset is where its header is (256 -for a whole `bvh4` payload, 0 for a buffer that starts at the header). - -Exit status 0 when every checked stream passes, 1 when one fails, 2 on an input error. -""" -import argparse -import json -import math -import mmap -import multiprocessing -import os -import struct -import sys -import time -import zlib -from collections import Counter - -sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) -import bvh_index as I # noqa: E402 -import bvh_rehydrate as R # noqa: E402 -from report_paths import same_report_path # noqa: E402 - -BOX_TYPES = (R.BOX16, R.BOX32) -HALF_MAX = 65504.0 -FLOAT_TOL = 4 * 2.0 ** -23 # relative, as tools/bvh_geometry_check.py allows for stored overrides -HALF_TOL = 2.0 ** -10 # one half ulp, relative -EXAMPLES = 20 # offsets kept per failure reason - - -def _valid_order_table(): - table = bytearray(256) - for order in range(256): - a, b = order & 3, (order >> 2) & 3 - c = (a ^ 3) - b - table[order] = 1 if sorted((a, b, c)) == [0, 1, 2] else 0 - return bytes(table) - - -VALID_ORDER = _valid_order_table() - - -def mapped_bounds(hdr): - """sceneBounds mapped through the leaf frame, as tools/bvh_geometry_check.py maps it: (lo xyz, hi xyz).""" - frame = R.LeafFrame(hdr) - lo, hi = hdr.bounds[:3], hdr.bounds[3:] - corners = [frame.apply((x, y, z)) for x in (lo[0], hi[0]) for y in (lo[1], hi[1]) for z in (lo[2], hi[2])] - return [min(c[a] for c in corners) for a in range(3)] + [max(c[a] for c in corners) for a in range(3)] - - -def _inside(value, comp, box, wide): - """True when a stored override lies inside the mapped bounds on its axis.""" - lo, hi = box[comp % 3], box[comp % 3 + 3] - if value != value: - return False - if math.isinf(value): - if wide: - return False - return (value < 0 and lo < -HALF_MAX) or (value > 0 and hi > HALF_MAX) - tol = (FLOAT_TOL if wide else HALF_TOL) * max(abs(lo), abs(hi), 1.0) - if not wide: - tol += 2.0 ** -14 - return lo - tol <= value <= hi + tol - - -def _root_equal(value, bound, comp, wide): - if wide: - return abs(value - bound) <= FLOAT_TOL * max(abs(bound), 1e-30) - want = R.half_down(bound) if comp < 3 else R.half_up(bound) - return R.float_to_half(value) == want - - -class Result: - """Per-stream outcome: failure reasons (counted once each) and summed statistics.""" - - def __init__(self): - self.fails = Counter() - self.stats = Counter() - - def fail(self, reason, n=1): - self.fails[reason] += n - - -def check_stream(buf, at=0): - """Check one dehydrated BVH4 structure whose 64-byte header starts at buf[at]. Returns a Result.""" - res = Result() - st = res.stats - hdr = R.Header(buf, at) - total = hdr.total_bytes - src = bytes(buf[at:at + total]) - if len(src) < total: - res.fail("short_input") - return res - if not hdr.flags & R.FLAG_DEHYDRATED: - res.fail("not_dehydrated") - return res - n = hdr.num_elements - elements = hdr.offset_to_elements - nodes = hdr.offset_to_nodes - st["leaves"] += n - - # Leaf records: chunks of 2,048 every 128 KiB; in the rehydrated layout leaf k sits at elements + 64 k. - if elements + 64 * n > total: - res.fail("leaves_past_end") - return res - if n and elements + 64 * n > nodes: - res.fail("leaves_overlap_nodes") - remaining, chunk = n, 0 - while remaining > 0: - c = min(R.LEAVES_PER_CHUNK, remaining) - base = elements + chunk * R.CHUNK_STRIDE - orders = src[base + 10 * c:base + 11 * c] - bad = orders.translate(VALID_ORDER).count(0) - if bad: - res.fail("leaf_vertex_order", bad) - remaining -= c - chunk += 1 - - if hdr.root == R.INVALID: - st["root_invalid"] += 1 - if n: - res.fail("invalid_root_with_leaves") - return res - root_type = hdr.root & 7 - st["root_type_%d" % root_type] += 1 - if root_type not in BOX_TYPES: - # A structure whose root is a single leaf has no box groups or level table to check. - if root_type == R.TRI0 and n == 1 and ((hdr.root >> 3) << 6) == elements: - st["root_leaf"] += 1 - else: - res.fail("root_not_a_box") - return res - - try: - lv = R.levels(src, hdr) - except (ValueError, struct.error): - res.fail("level_table") - return res - table_start = total - 4 - 8 * len(lv) - st["levels"] += len(lv) - st["levels_%d" % len(lv)] += 1 - if lv and nodes + lv[-1][2] + 64 * lv[-1][3] > table_start: - res.fail("levels_past_table") - return res - - # Every box node: pointer (unit << 3 | type) -> (node id, level). - node_of = {} - runs = [] # (level, wide, start offset from header, count, first id) - nid = 0 - for level, (b32_start, b32_count, b16_start, b16_count) in enumerate(lv): - for start, count, wide in ((b32_start, b32_count, True), (b16_start, b16_count, False)): - size = 128 if wide else 64 - typ = R.BOX32 if wide else R.BOX16 - first = nodes + start - for j in range(count): - node_of[((first + j * size) >> 6) << 3 | typ] = (nid + j, level) - runs.append((level, wide, first, count, nid)) - nid += count - st["box_nodes"] += nid - if hdr.root not in node_of: - res.fail("root_not_a_node") - return res - root_id, root_level = node_of[hdr.root] - if root_level == len(lv) - 1: - st["root_in_top_level"] += 1 - if root_id == nid - 1: - st["root_is_last_node"] += 1 - top = lv[-1] - if top[1] + top[3] == 1: - st["top_level_single_node"] += 1 - - box_refs = bytearray(nid) - leaf_refs = bytearray(n) - box = mapped_bounds(hdr) - root_comps = None - for level, wide, first, count, first_id in runs: - size = 128 if wide else 64 - group_bytes = size * R.GROUP - for g in range((count + R.GROUP - 1) // R.GROUP): - k = min(R.GROUP, count - g * R.GROUP) - base = first + g * group_bytes - words = struct.unpack_from("<%dI" % k, src, base) - kids_total = sum(w >> 24 for w in words) - n_values = sum(bin(w & 0xFFFFFF).count("1") for w in words) - used = 4 * (k + kids_total) + (4 if wide else 2) * n_values - if used > k * size: - res.fail("group_overflow") - continue - tail = src[base + used:base + k * size] - if tail.count(0) != len(tail): - st["group_tail_nonzero_bytes"] += len(tail) - tail.count(0) - children = struct.unpack_from("<%dI" % kids_total, src, base + 4 * k) - values = struct.unpack_from(("<%df" if wide else "<%dH") % n_values, src, base + 4 * (k + kids_total)) - if not wide: - values = [R.half_to_float(h) for h in values] - ci = vi = 0 - for t, word in enumerate(words): - kids, mask = word >> 24, word & 0xFFFFFF - this_id = first_id + g * R.GROUP + t - st["children_%d" % kids] += 1 - if kids == 0: - res.fail("no_children") - elif kids > 4: - res.fail("too_many_children") - if mask >> (6 * min(kids, 4)): - res.fail("mask_past_children") - for ptr in children[ci:ci + kids]: - typ = ptr & 7 - st["child_type_%d" % typ] += 1 - if ptr == R.INVALID: - res.fail("invalid_child") - elif typ in BOX_TYPES: - hit = node_of.get(ptr) - if hit is None: - other = ptr ^ (R.BOX16 ^ R.BOX32) - res.fail("child_wrong_width" if other in node_of else "child_not_a_node") - else: - if hit[1] >= level: - res.fail("child_not_below") - if box_refs[hit[0]] < 255: - box_refs[hit[0]] += 1 - elif typ == R.TRI0: - off = ((ptr >> 3) << 6) - elements - if off < 0 or off % 64 or off // 64 >= n: - res.fail("child_not_a_leaf") - elif leaf_refs[off // 64] < 255: - leaf_refs[off // 64] += 1 - else: - res.fail("child_type_%d" % typ) - ci += kids - comps = {} if this_id == root_id else None - for bit in range(24): - if mask >> bit & 1: - v = values[vi] - vi += 1 - st["overrides"] += 1 - if not _inside(v, bit % 6, box, wide): - res.fail("override_outside_bounds") - if comps is not None and bit // 6 < kids: - comps.setdefault(bit % 6, []).append((bit // 6, v)) - if comps is not None: - root_comps = (kids, comps, wide) - - if root_comps is not None: - kids, comps, wide = root_comps - for comp in range(6): - got = comps.get(comp, []) - if len(got) == kids and kids: - vals = [v for _, v in got] - union = min(vals) if comp < 3 else max(vals) - st["root_components_stored"] += 1 - if _root_equal(union, box[comp], comp, wide): - st["root_components_equal"] += 1 - else: - res.fail("root_union_not_bounds") - - if box_refs[root_id]: - res.fail("root_referenced") - unreferenced = sum(1 for i, r in enumerate(box_refs) if r == 0 and i != root_id) - shared = sum(1 for r in box_refs if r > 1) - if unreferenced: - res.fail("node_unreferenced", unreferenced) - if shared: - res.fail("node_shared", shared) - leaf_missing = leaf_refs.count(0) - leaf_shared = n - leaf_missing - leaf_refs.count(1) - if leaf_missing: - res.fail("leaf_unreferenced", leaf_missing) - if leaf_shared: - res.fail("leaf_shared", leaf_shared) - return res - - -# --- archive scan ----------------------------------------------------------------------------------------------- - -def _inflate(m, s, end): - """Inflate the zlib stream at s (reading at most up to end). Returns (data, used) or None.""" - d = zlib.decompressobj() - out, p = [], s - try: - while not d.eof and p < end: - chunk = m[p:min(p + (1 << 20), end)] - if not chunk: - break - out.append(d.decompress(chunk)) - p += len(chunk) - if d.unused_data: - break - out.append(d.flush()) - except zlib.error: - return None - if not d.eof: - return None - data = b"".join(out) - if len(data) < 64: - return None - return data, p - s - len(d.unused_data) - - -class Tally: - def __init__(self): - self.kinds = Counter() - self.checked = self.passed = 0 - self.fail_streams = Counter() # reason -> streams - self.fail_items = Counter() # reason -> occurrences - self.stats = Counter() - self.examples = {} - self.raw = set() # offsets of streams no classifier recognised - self.consumed = set() # offsets of continuation streams joined to a bvh4-chunk - - def add(self, offset, res): - self.checked += 1 - self.stats.update(res.stats) - if not res.fails: - self.passed += 1 - for reason, k in res.fails.items(): - self.fail_streams[reason] += 1 - self.fail_items[reason] += k - ex = self.examples.setdefault(reason, []) - if len(ex) < EXAMPLES: - ex.append(offset) - - def merge(self, other): - self.kinds.update(other.kinds) - self.checked += other.checked - self.passed += other.passed - self.fail_streams.update(other.fail_streams) - self.fail_items.update(other.fail_items) - self.stats.update(other.stats) - self.raw |= other.raw - self.consumed |= other.consumed - for reason, ex in other.examples.items(): - mine = self.examples.setdefault(reason, []) - mine.extend(ex) - mine.sort() - del mine[EXAMPLES:] - - def report(self): - # A continuation that starts in a later window is seen there as an unrecognised stream; count it once. - kinds = Counter(self.kinds) - raw = len(self.raw - self.consumed) - if raw: - kinds["raw"] = raw - return {"kinds": dict(sorted(kinds.items())), "checked": self.checked, "passed": self.passed, - "failed": self.checked - self.passed, - "fail_streams": dict(sorted(self.fail_streams.items())), - "fail_items": dict(sorted(self.fail_items.items())), - "stats": dict(sorted(self.stats.items())), - "fail_examples": {k: sorted(v) for k, v in sorted(self.examples.items())}} - - -def scan_window(args): - """Check every stream that starts in [start, end) of the archive; reads past end to finish a stream.""" - path, start, end = args - tally = Tally() - with open(path, "rb") as fh: - m = mmap.mmap(fh.fileno(), 0, access=mmap.ACCESS_READ) - try: - size = len(m) - pos = start - while pos < end: - # ZHDR is 2 bytes; end + 1 lets a header starting at end - 1 match without entering [end, ...). - mt = I.ZHDR.search(m, pos, min(end + 1, size)) - if not mt: - break - s = mt.start() - got = _inflate(m, s, size) - if got is None: - pos = s + 1 - continue - data, used = got - pos = s + used - row = I.classify(data[:I.HEAD], len(data)) - kind = row["kind"] - if kind == "raw": - tally.raw.add(s) - else: - tally.kinds[kind] += 1 - if kind == "bvh4-chunk": - # Join the continuation streams that follow, up to the declared end. - parts, have, q = [data], len(data), pos - while have < row["declared_bytes"]: - nxt = I.ZHDR.search(m, q, size) - more = _inflate(m, nxt.start(), size) if nxt else None - if more is None: - break - parts.append(more[0]) - have += len(more[0]) - tally.kinds["continuation"] += 1 - tally.consumed.add(nxt.start()) - q = nxt.start() + more[1] - data = b"".join(parts) - if have < row["declared_bytes"]: - tally.add(s, _short()) - continue - tally.kinds["bvh4-chunk-joined"] += 1 - pos = q - kind = "bvh4" - if kind == "bvh4": - try: - res = check_stream(data, I.TAG_OFF) - except (ValueError, struct.error) as e: - res = Result() - res.fail("error:" + type(e).__name__) - tally.add(s, res) - finally: - m.close() - return tally - - -def _short(): - r = Result() - r.fail("short_input") - return r - - -def scan_archive(path, workers, window, start=None, limit=None, progress=True): - size = os.path.getsize(path) - with open(path, "rb") as fh: - first = struct.unpack("= 8 else size - lo = first if start is None else start - if not 0 <= lo <= size: - raise ValueError("start offset is outside the archive") - hi = min(size, lo + limit) if limit else size - jobs = [(path, a, min(a + window, hi)) for a in range(lo, hi, window)] - total = Tally() - t0 = time.time() - if workers <= 1 or len(jobs) <= 1: - results = map(scan_window, jobs) - pool = None - else: - pool = multiprocessing.Pool(workers, initializer=I.below_normal) - results = pool.imap_unordered(scan_window, jobs) - try: - for done, t in enumerate(results, 1): - total.merge(t) - if progress: - print(" %d/%d windows, %d streams checked, %d failed (%.0fs)" - % (done, len(jobs), total.checked, total.checked - total.passed, time.time() - t0), - file=sys.stderr, flush=True) - finally: - if pool is not None: - pool.close() - pool.join() - return total, round(time.time() - t0, 1) - - -def main(argv=None): - ap = argparse.ArgumentParser(description="Check the dehydrated BVH4 packing (docs/bvh.md §4a) without geometry.") - ap.add_argument("inputs", nargs="+") - ap.add_argument("--workers", type=int, default=max(1, (os.cpu_count() or 2) - 2)) - ap.add_argument("--window", type=int, default=64 << 20, help="archive bytes per parallel job (default 64 MiB)") - ap.add_argument("--start", type=int) - ap.add_argument("--limit", type=int) - ap.add_argument("--header-offset", type=int, default=0) - ap.add_argument("--json") - a = ap.parse_args(argv) - if a.header_offset < 0: - ap.error("--header-offset must be non-negative") - if a.header_offset and any(p.lower().endswith(".rpf") for p in a.inputs): - ap.error("--header-offset only applies to a stream file") - bad_limit = a.limit is not None and a.limit <= 0 - if a.window <= 0 or a.workers <= 0 or bad_limit or (a.start is not None and a.start < 0): - print("error: --window, --workers and --limit must be positive, --start not negative", file=sys.stderr) - return 2 - if a.json: - if os.path.isdir(a.json): - print("error: --json is a directory: %s" % a.json, file=sys.stderr) - return 2 - parent = os.path.dirname(os.path.abspath(a.json)) - if not os.path.isdir(parent): - print("error: --json parent folder does not exist: %s" % parent, file=sys.stderr) - return 2 - for p in a.inputs: - if same_report_path(a.json, p): - print("error: --json must not overwrite the input %s" % p, file=sys.stderr) - return 2 - rpfs = [p for p in a.inputs if p.lower().endswith(".rpf")] - if rpfs and len(a.inputs) > 1: - print("error: give one .rpf, or one or more stream files", file=sys.stderr) - return 2 - try: - if rpfs: - tally, elapsed = scan_archive(rpfs[0], a.workers, a.window, a.start, a.limit) - else: - if a.start is not None or a.limit is not None: - print("error: --start and --limit apply to an .rpf only", file=sys.stderr) - return 2 - t0 = time.time() - tally = Tally() - for p in a.inputs: - with open(p, "rb") as f: - data = f.read() - tally.kinds["file"] += 1 - tally.add(p, check_stream(data, a.header_offset)) - elapsed = round(time.time() - t0, 1) - except (OSError, ValueError, struct.error) as e: - print("error: %s" % e, file=sys.stderr) - return 2 - rep = tally.report() - rep["elapsed_s"] = elapsed - print("checked %d streams: %d passed, %d failed (%.1fs)" % (rep["checked"], rep["passed"], rep["failed"], elapsed)) - for reason, k in rep["fail_streams"].items(): - print(" %s: %d streams, %d items" % (reason, k, rep["fail_items"][reason])) - if a.json: - try: - I._publish(a.json, lambda f: json.dump(rep, f, indent=1), "\n") - except OSError as e: - print("error: cannot write %s: %s" % (a.json, e.strerror or e), file=sys.stderr) - return 2 - return 0 if rep["failed"] == 0 else 1 - - -if __name__ == "__main__": - try: # a redirected stdout is strict ANSI code page under -I; write '?' for what it cannot encode - sys.stdout.reconfigure(errors="replace") - except (AttributeError, ValueError, OSError): - pass - sys.exit(main()) diff --git a/tools/bvh_rehydrate.py b/tools/bvh_rehydrate.py deleted file mode 100644 index a7b4bf4a3..000000000 --- a/tools/bvh_rehydrate.py +++ /dev/null @@ -1,543 +0,0 @@ -"""Rehydrate a dehydrated XDXR BVH4 bottom-level acceleration structure on the CPU. - -The `*_bvh4.rpf` packs hold offline-built BLASes in the builder's dehydrated form: the header and the box -hierarchy are there, but the leaves name primitives instead of holding vertices, and most box bounds are left -to be recomputed. `XboxBvhBuilder.dll` turns such a buffer back into the runtime XDXR layout (docs/bvh.md §3.1) -with its geometry. This tool does the same on the CPU, following the packing recorded in docs/bvh.md §4a, so a -rehydrated structure can be produced without the DLL and the builder's own rehydration programs can be checked -against it on a GPU. Standard library only; nothing is read from the package. - -Input layout. The buffer starts at the 64-byte header (pass --header-offset 256 for a whole `bvh4` stream, whose -header sits at payload 0x100). Every offset in the header counts from the header. The output is the rehydrated -structure only, `64 * (totalSizeIn64BNodes + 1)` bytes from the header on. - -What is done, in order (docs/bvh.md §4a): - -* Header. The header is copied together with the bytes after it that the builder keeps: up to `offsetToParents` - when the word at +0x2c is non-zero, else `16 * (9 * k * k + 4)` bytes with `k = flags >> 20 & 15`, rounded up to - 16. The dehydrated flag (0x01000000) is cleared and the root's parent entry is set to 0xffffffff. -* Leaves. `numElements` leaves sit at `offsetToElements` in chunks of 2,048 every 128 KiB. A chunk of `c` leaves is - five arrays: geometry index (3 bytes each), flags (1), base primitive (3), second primitive (3; 0xffffff = none) - and a vertex-order byte (1). Each leaf becomes a 64-byte `Leaf`: the base triangle's three vertices in the slots - the vertex-order byte selects, a fourth vertex for a second primitive (NaN when there is none), then - `geometryIndex << 8 | flags`, the two primitive indices and the remap word. -* Boxes. The level table at the end of the input (last word: level count, before it one (BOX32 end, BOX16 end) - pair per level, offsets from `offsetToNodes`) lists the levels bottom-up. In each level the BOX32 nodes come - first, in groups of up to 64 per 8 KiB, then the BOX16 nodes, 64 per 4 KiB. A group starts with one word per node - (`children << 24 | 24-bit override mask`), then all the child pointers, then one stored value per mask bit - (float for BOX32, half for BOX16). A slot's box is the bounds of the already rehydrated child; the stored values - replace the masked components (bit `6 * slot + c`, min xyz then max xyz). BOX16 rounds min down and max up and - overflows to +-inf. Each node writes itself as the parent of its box children (and of TRI0 leaves when the - structure is updatable, flag 0x00040000). -* Leaf frame. Vertices are mapped `(R * v - t) * s` per `compressionParams` (+0x3c): bit 31 turns on the scale - `2^(e - 127)` with `e` the bytes 0, 1, 2; bit 30 the translation, the centre of `sceneBounds` on an axis whose - bounds do not straddle zero; bits 24-29 pick one of 64 rotations in steps of pi/8 about x, y and z. The value - 0x007f7f7f means none of it. Only rotation index 0 occurs in the measured samples. - -Float arithmetic is rounded to float32 after every operation, as the GPU does, so the output is meant to be -byte-exact. Geometry is float3 vertices (any stride) with uint32, uint16 or no indices, plus an optional 3x4 -geometry transform (the instance descriptor's matrix at +0x50, docs/bvh.md §3.2), applied as `x' = M * x`. - -Usage: - python -I tools/bvh_rehydrate.py --geom VB[,IB] [--geom VB[,IB] ...] --out - [--header-offset N] [--stride BYTES] [--index16] [--transform 12 floats] - [--compare ] - -One --geom per geometry index, in order: VB is a file of vertices (three float32 at the start of each --stride -record, default 12), IB a file of uint32 (or, with --index16, uint16) triangle indices; without IB the vertices are -a triangle list. --transform takes the 3x4 row-major matrix as 12 comma-separated floats and applies to every -geometry. --compare prints how many bytes differ from a reference structure. Exit status 0 on success, 2 on an -input error. -""" -import argparse -import contextlib -import math -import os -import struct -import sys -import tempfile - -FLAG_DEHYDRATED = 0x01000000 -FLAG_UPDATABLE = 0x00040000 -NO_TRANSFORM = 0x007F7F7F -INVALID = 0xFFFFFFFF -TRI0, TRI1, BOX16, BOX32 = 0, 1, 4, 5 -FLT_MAX = struct.unpack(" leaf vertex slot -M32 = 0xFFFFFFFF - - -# --- float32 / half helpers ------------------------------------------------------------------------------------- - -def f32(x): - return struct.unpack("= b else b - - -def half_down(x): - """Largest half not above x (a box16 minimum).""" - if x != x: - return float_to_half(x) - b = bits32(x) - if x < 0.0: - y = min_num(from_bits32((b + 0x1FFF) & ~0x1FFF), -HALF_MIN_NORMAL) - else: - y = from_bits32(b & ~0x1FFF) - y = 0.0 if y < HALF_MIN_NORMAL else y - return float_to_half(y) - - -def half_up(x): - """Smallest half not below x (a box16 maximum).""" - if x != x: - return float_to_half(x) - b = bits32(x) - if x > 0.0: - y = max_num(from_bits32((b + 0x1FFF) & ~0x1FFF), HALF_MIN_NORMAL) - else: - y = from_bits32(b & ~0x1FFF) - y = 0.0 if y > -HALF_MIN_NORMAL else y - return float_to_half(y) - - -# --- header and frames ------------------------------------------------------------------------------------------ - -class Header: - """The XboxBvh4Header fields this tool needs (docs/bvh.md §3.1); offsets are from the header.""" - - def __init__(self, buf, at=0): - if at < 0 or at + 64 > len(buf): - raise ValueError("no 64-byte header at offset %d" % at) - (self.flags, self.size_units, self.crc32, self.num_elements) = struct.unpack_from("<4I", buf, at) - self.bounds = struct.unpack_from("<6f", buf, at + 16) - (self.offset_to_nodes, self.prim_remap_word, self.root, self.offset_to_elements, self.offset_to_parents, - self.compression) = struct.unpack_from("<6I", buf, at + 40) - - @property - def total_bytes(self): - return (self.size_units + 1) * 64 - - def kept_header_bytes(self): - if self.prim_remap_word: - n = self.offset_to_parents - else: - k = (self.flags >> 20) & 15 - n = 16 * (9 * k * k + 4) - return (n + 15) & ~15 - - def parent_entry(self, node_offset): - """Address of the parent-table entry for the node at node_offset (all arithmetic is 32-bit).""" - unit = ((node_offset - self.offset_to_elements) & M32) >> 6 - return (self.offset_to_parents + 4 * unit) & M32 - - def stored_parent_entry(self, node_offset, size): - """The entry's address when the structure stores it, else None: only the entries from the header end to - offsetToElements are kept (docs/bvh.md §3.1), so a console structure's low units have none.""" - entry = self.parent_entry(node_offset) - if 64 <= entry and entry + 4 <= min(self.offset_to_elements, size): - return entry - return None - - -def rotation(index): - """Rotation index -> 3x3 matrix Rz * Ry * Rx, each angle a multiple of pi/8, products rounded to float32.""" - c = (1.0, math.cos(math.pi / 8), math.cos(math.pi / 4), math.cos(3 * math.pi / 8), 0.0) - ix, iy, iz = index & 3, (index >> 2) & 3, (index >> 4) & 3 - cx, sx, cy, sy, cz, sz = (f32(c[ix]), f32(c[4 - ix]), f32(c[iy]), f32(c[4 - iy]), f32(c[iz]), f32(c[4 - iz])) - rx = ((1.0, 0.0, 0.0), (0.0, cx, sx), (0.0, -sx, cx)) - ry = ((cy, 0.0, -sy), (0.0, 1.0, 0.0), (sy, 0.0, cy)) - rz = ((cz, sz, 0.0), (-sz, cz, 0.0), (0.0, 0.0, 1.0)) - - def mul(a, b): - out = [] - for r in range(3): - row = [] - for col in range(3): - acc = 0.0 - for m in range(3): - acc = f32(acc + f32(a[r][m] * b[m][col])) - row.append(acc) - out.append(tuple(row)) - return tuple(out) - - return mul(rz, mul(ry, rx)) - - -class LeafFrame: - """The compressionParams mapping (R * v - t) * s, or the identity.""" - - def __init__(self, hdr): - word = hdr.compression - self.on = word != NO_TRANSFORM - self.r = rotation((word >> 24) & 0x3F) - self.t = [0.0, 0.0, 0.0] - self.s = [1.0, 1.0, 1.0] - if word >> 30 & 1: - for a in range(3): - lo, hi = hdr.bounds[a], hdr.bounds[a + 3] - if lo > 0.0 or hi < 0.0: - self.t[a] = f32(f32(lo + hi) * 0.5) - if word >> 31 & 1: - self.s = [from_bits32(((word >> (8 * a)) & 0xFF) << 23) for a in range(3)] - - def apply(self, v): - if not self.on: - return v - out = [] - for row in range(3): - acc = f32(self.r[row][0] * v[0]) - acc = f32(self.r[row][1] * v[1] + acc) - acc = f32(self.r[row][2] * v[2] + acc) - out.append(f32(f32(acc - self.t[row]) * self.s[row])) - return tuple(out) - - -# --- geometry --------------------------------------------------------------------------------------------------- - -class Geometry: - """float3 vertices (the first 12 bytes of each `stride` record) with optional uint32/uint16 triangle indices and - an optional 3x4 row-major transform applied as x' = M * x.""" - - def __init__(self, vertices, stride=12, indices=None, index16=False, transform=None): - if stride < 12: - raise ValueError("vertex stride %d is below 12" % stride) - self.vertices, self.stride, self.indices, self.index16 = bytes(vertices), stride, indices, index16 - self.transform = transform - - def triangle(self, prim): - if self.indices is None: - return 3 * prim, 3 * prim + 1, 3 * prim + 2 - if self.index16: - return struct.unpack_from("<3H", self.indices, 6 * prim) - return struct.unpack_from("<3I", self.indices, 12 * prim) - - def vertex(self, i): - v = struct.unpack_from("<3f", self.vertices, i * self.stride) - m = self.transform - if m is None: - return v - out = [] - for row in range(3): - acc = f32(m[row][0] * v[0]) - acc = f32(m[row][1] * v[1] + acc) - acc = f32(m[row][2] * v[2] + acc) - out.append(f32(acc + m[row][3])) - return tuple(out) - - -# --- rehydration ------------------------------------------------------------------------------------------------ - -def read_u24(buf, at): - return buf[at] | buf[at + 1] << 8 | buf[at + 2] << 16 - - -def leaf_records(src, hdr): - """Yield (leaf output offset, geometry, flags, prim0, prim1 or None, vertex order) for every leaf.""" - remaining, chunk = hdr.num_elements, 0 - while remaining > 0: - c = min(LEAVES_PER_CHUNK, remaining) - base = hdr.offset_to_elements + chunk * CHUNK_STRIDE - if base + 11 * c > len(src): - raise ValueError("leaf chunk %d runs past the input" % chunk) - for i in range(c): - prim1 = read_u24(src, base + 7 * c + 3 * i) - yield (base + 64 * i, read_u24(src, base + 3 * i), src[base + 3 * c + i], read_u24(src, base + 4 * c + 3 * i), - None if prim1 == 0xFFFFFF else prim1, src[base + 10 * c + i]) - remaining -= c - chunk += 1 - - -def write_leaves(src, dst, hdr, geometries, frame): - for out, gi, flags, prim0, prim1, order in leaf_records(src, hdr): - if gi >= len(geometries): - raise ValueError("a leaf uses geometry index %d but %d geometries were given" % (gi, len(geometries))) - g = geometries[gi] - tri = [frame.apply(g.vertex(i)) for i in g.triangle(prim0)] - if prim1 is None: - fourth = (NAN32, NAN32, NAN32) - else: - j = g.triangle(prim1) - fourth = frame.apply(g.vertex(j[0] if order & 0x20 else j[1] if order & 0x80 else j[2])) - a, b = order & 3, (order >> 2) & 3 - slots = [None, None, None, fourth] - for which, value in zip((a, b, (a ^ 3) - b), tri): - slots[SLOT_OF_ORDER[which]] = value - struct.pack_into("<12f4I", dst, out, *slots[0], *slots[1], *slots[2], *slots[3], - (gi << 8 | flags) & M32, prim0, INVALID if prim1 is None else prim1, - (order & 0xF) | ((order << 4) & 0xF00)) - - -def node_bounds(dst, ptr): - """(min xyz, max xyz) of the rehydrated node a child pointer names.""" - kind, at = ptr & 7, (ptr >> 3) << 6 - if kind == TRI0: - v = struct.unpack_from("<12f", dst, at) - pts = [v[0:3], v[3:6], v[6:9]] + ([v[9:12]] if struct.unpack_from(" x))): - best = cand - out.append(half_to_float(best)) - return tuple(out) - else: - return (FLT_MAX,) * 3 + (-FLT_MAX,) * 3 - lo, hi = list(pts[0]), list(pts[0]) - for p in pts[1:]: - for a in range(3): - lo[a] = min_num(lo[a], p[a]) - hi[a] = max_num(hi[a], p[a]) - return tuple(lo) + tuple(hi) - - -def levels(src, hdr): - """[(box32 start, box32 count, box16 start, box16 count)] bottom-up, offsets from offsetToNodes.""" - end = hdr.total_bytes - count = struct.unpack_from("> 24 for w in words) - child_at = base + 4 * n - value_at = base + 4 * (n + total_children) - for t, word in enumerate(words): - kids, mask = word >> 24, word & 0xFFFFFF - children = list(struct.unpack_from("<%dI" % kids, src, child_at)) + [INVALID] * (4 - kids) - child_at += 4 * kids - comps = [] - for slot in range(4): - if slot < kids: - b = node_bounds(dst, children[slot]) - comps += list(b) if wide else [half_down(b[0]), half_down(b[1]), half_down(b[2]), - half_up(b[3]), half_up(b[4]), half_up(b[5])] - else: - comps += [FLT_MAX] * 3 + [-FLT_MAX] * 3 if wide else [HALF_POS_INF] * 3 + [HALF_NEG_INF] * 3 - for bit in range(24): - if mask >> bit & 1: - if wide: - comps[bit] = struct.unpack_from("> 6) << 3 | (BOX32 if wide else BOX16) - for child in children: - if (child & 6) == 4 or ((child & 7) == TRI0 and hdr.flags & FLAG_UPDATABLE): - entry = hdr.stored_parent_entry(((child >> 3) << 6) & M32, len(dst)) - if entry is not None: - struct.pack_into(" len(src): - raise ValueError("the kept header bytes (%d) run past the input" % kept) - dst[:kept] = src[:kept] - struct.pack_into("> 3) << 6) & M32, len(dst)) - if root_entry is not None: - struct.pack_into(" 1 and parts[1]: - with open(parts[1], "rb") as f: - ib = f.read() - geometries.append(Geometry(vb, a.stride, ib, a.index16, transform)) - with open(a.dehydrated, "rb") as f: - data = f.read() - out = rehydrate(data, geometries, a.header_offset) - except (OSError, ValueError, struct.error) as e: - print("error: %s" % e, file=sys.stderr) - return 2 - try: - _publish(a.out, out) - except OSError as e: - print("error: cannot write %s: %s" % (a.out, e), file=sys.stderr) - return 2 - print("rehydrated %d bytes, %d leaves, %d geometries -> %s" % (len(out), Header(data, a.header_offset).num_elements, - len(geometries), a.out)) - if a.compare: - try: - with open(a.compare, "rb") as f: - ref = f.read() - except OSError as e: - print("error: cannot read %s: %s" % (a.compare, e), file=sys.stderr) - return 2 - diff = sum(x != y for x, y in zip(out, ref)) + abs(len(out) - len(ref)) - print("differs from %s in %d bytes" % (a.compare, diff)) - return 0 - - -if __name__ == "__main__": - try: # a redirected stdout is strict ANSI code page under -I; write '?' for what it cannot encode - sys.stdout.reconfigure(errors="replace") - except (AttributeError, ValueError, OSError): - pass - sys.exit(main()) diff --git a/tools/bvh_slot_check.py b/tools/bvh_slot_check.py deleted file mode 100644 index 610ddf4be..000000000 --- a/tools/bvh_slot_check.py +++ /dev/null @@ -1,345 +0,0 @@ -"""Compare multi-slot BVH transforms against drawable groups selected by topology. - -Inputs are the core BVH archive, its generic archive index (files[].off/stored/size/head), -and one or more primary-LOD levels model manifests with their exported OBJs. -Use --save-evidence and --prior to combine private window scans without reopening earlier OBJs. -Only BLAS with at least 30 paired primitives enter the topology screen. -The candidate universe is the supplied exports. Stdout contains aggregate counts only. -Usage: `python -I tools/bvh_slot_check.py --help` lists the options. -""" -import argparse -import hashlib -import json -import math -import os -import struct -import sys -import tempfile -import zlib -from bisect import bisect_left -from collections import Counter, defaultdict -from pathlib import Path - -sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) -import bvh_geometry_check as C -import bvh_index as I -import bvh_match as M -import bvh_rehydrate as R - - -# Bump when signature ordering, source matching or matrix verdict semantics change. -EVIDENCE_FORMAT = "bvh-slot-evidence-v1" -PAIR = struct.Struct(" len(descriptor): - raise ValueError("invalid instance slot table") - matrices = [] - bodies = [] - pos = 0 - for i in range(count): - matrix = tuple(struct.unpack_from("<4f", descriptor, 80 + 48 * i + 16 * r) for r in range(3)) - if not all(math.isfinite(value) for row in matrix for value in row): - raise ValueError("non-finite matrix") - matrices.append(matrix) - size, = struct.unpack_from(" 1 or matrices.count(passed[0]) > 1: - return "non_discriminating" - return "own_only" - - -def topology_matches(faces, pairs): - """Require both the common edge and the encoded fourth vertex of every pair.""" - for first, second, fourth in pairs: - a, b = faces[first], faces[second] - if b[fourth] in a or len(set(a).intersection(b)) != 2: - return False - return True - - -def read_stream(f, row): - f.seek(row["off"]) - data = zlib.decompress(f.read(row["stored"])) - if len(data) != row["size"] or not data.startswith(bytes.fromhex(row["head"])): - raise ValueError("index disagrees with archive") - return data - - -def signature(records): - counts = Counter() - pairs = defaultdict(bytearray) - largest = {} - for _, gi, _, a, b, order in records: - counts[gi] += 1 - largest[gi] = max(largest.get(gi, 0), a) - if b is not None: - counts[gi] += 1 - fourth = 0 if order & 0x20 else 1 if order & 0x80 else 2 - largest[gi] = max(largest[gi], b) - pairs[gi].extend(PAIR.pack(a, b, fourth)) - if not counts or max(counts) >= len(counts): - return None - if any(largest[k] >= counts[k] for k in counts) or sum(map(len, pairs.values())) < 30 * PAIR.size: - return None - return tuple((counts[k], bytes(pairs[k])) for k in range(len(counts))) - - -def source_candidates(sig, meshes, groups): - """Ordered embeddings in one drawable model, retaining only topology matches.""" - choices = [] - for n, pairs in sig: - choices.append([mesh for mesh in meshes if len(groups[mesh][1]) == n - and topology_matches(groups[mesh][1], PAIR.iter_unpack(pairs))]) - - # Remove choices that cannot be followed by a complete ordered suffix. - for i in reversed(range(len(choices))): - if not choices[i]: - return - if i: - end = bisect_left(choices[i - 1], choices[i][-1]) - choices[i - 1] = choices[i - 1][:end] - - def walk(prefix): - if len(prefix) == len(sig): - yield prefix - return - for mesh in choices[len(prefix)]: - if not prefix or mesh > prefix[-1]: - yield from walk(prefix + (mesh,)) - - yield from walk(()) - - -def match_exports(queries, manifests, stats): - # Only inspect signatures for which the model has the largest required geometry. - by_count = defaultdict(list) - for sig in queries: - by_count[max(n for n, _ in sig)].append(sig) - matches = {} - for manifest in manifests: - items = json.loads(manifest.read_bytes())["Items"] - stats["manifest_items"] += len(items) - for item in items: - models = defaultdict(list) - for mesh, model, *_ in M.model_geometries(item): - models[model].append(mesh) - groups = None - buffers = {} - for meshes in models.values(): - counts = Counter(item["MeshTris"][mesh] for mesh in meshes) - for count in counts: - for sig in by_count[count]: - if sig in matches and matches[sig] is None: - continue - if Counter(n for n, _ in sig) - counts: - continue - if groups is None: - groups = M.read_groups(manifest.parent / item["File"]) - if [len(faces) for _, faces in groups] != item["MeshTris"]: - raise ValueError("OBJ and manifest disagree on mesh triangle counts") - for selected in source_candidates(sig, meshes, groups): - for mesh in selected: - if mesh not in buffers: - if not all(math.isfinite(x) for vertex in groups[mesh][0] for x in vertex): - raise ValueError("non-finite source vertex") - buffers[mesh] = M.build_geometry(groups[mesh]) - geometry = tuple(buffers[mesh] for mesh in selected) - previous = matches.get(sig) - if previous and any(a.indices != b.indices or a.vertices != b.vertices - for a, b in zip(previous, geometry)): - matches[sig] = None - break - matches[sig] = geometry - return matches - - -def buffer_digest(geometries): - digest = hashlib.sha256() - for geometry in geometries: - for buffer in (geometry.vertices, geometry.indices): - digest.update(struct.pack("/... (through a subclass of the runner, not through this tool): - clang-21 --target=amdgcn-amd-amdhsa -mcpu=gfx1030 [-mwavefrontsize64] -mcode-object-version=5 -c k.s -o k.o - ld.lld-21 -shared k.o -o k.co -amdhip64_6.dll refuses code object v6 (HIP error 209; the runner's probe falls back to v5 by itself). Doing the same -with this tool needs LEONIDA_AMD_CLANG to name a wrapper that runs the clang line that way, an ld.lld wrapper next to -it or on PATH, and LEONIDA_HW_ARCH=gfx1030, since no amdgpu-arch sits beside such a wrapper; that route was not tried -with this tool. The DRM launcher on Linux reads back at most 4096 dwords, so the two lane kernels (8192) are skipped -there. - -Exit codes: 0 every compared word matched (and the two forms agreed); 1 a mismatch; 2 a CLI or harness error; 77 the -hardware oracle was asked for but is unavailable, or the GPU is not GFX10. -""" -import argparse -import gc -import hashlib -import json -import math -import os -import struct -import sys -import tempfile -import warnings -import zlib -from fractions import Fraction as Fr - -HERE = os.path.dirname(os.path.abspath(__file__)) -ROOT = os.path.dirname(HERE) -sys.dont_write_bytecode = True -for _p in (HERE, os.path.join(ROOT, "tests", "semantic")): - if _p not in sys.path: - sys.path.insert(0, _p) - -INF, NAN = float("inf"), float("nan") -QNAN = 0x7FC00000 -MISS = 0xFFFFFFFF -POISON = 0xBAADF00D -DONE = 0x600D0000 -SENT = 0xBEEF0000 -PREFILL = 0xDEAD0000 -STUB_DXBC = b"DXBC" + bytes(24) + struct.pack(" 0 else 0xFFC00000 - try: - return struct.unpack(" 0 else 0xFF800000 - - -def u2f(w): - return struct.unpack(" 0 else -INF) if c == 0 else 1.0 / c for c in d] - return [v & 0xFFFFFFFF if isinstance(v, int) else f2u(v) for v in (tmax, *org, *d, *inv)] - - -class Kernel: - """The nodes and cases of one kernel (one dispatch), and its lines.""" - - def __init__(self, label, threads=1, wave=32, nsa=False, lane_offsets=None): - if threads not in LAYOUT: - raise ValueError("threads must be 1 or 64") - self.uid = zlib.crc32(label.encode("utf-8")) & 0xFFFF - self.label, self.threads, self.wave, self.nsa = label, threads, wave, nsa - self.L = LAYOUT[threads] - self.lane_offsets = lane_offsets # (dx, dy): org.x += (lane & 15) dx, org.y += (lane >> 4) dy - self.slots = {} # slot -> 16 u32 words - self.cases = [] - self.max_cases = 7 if threads == 64 else 32 - - def add_node(self, words): - """Place a 16-word node in the next free 64-byte slot of the node region; returns the slot.""" - if len(words) != 16: - raise ValueError("a triangle node is 16 words") - for s in range(NSLOTS): - if s not in self.slots: - self.slots[s] = [w & 0xFFFFFFFF for w in words] - return s - raise ValueError(f"kernel {self.label}: no free node slot") - - def add_case(self, label, slot, ntype, ray, meta=None): - if not 0 <= ntype <= 3: - raise ValueError(f"case {label}: node type {ntype}; this probe runs triangle nodes (0..3) only") - if slot not in self.slots: - raise ValueError(f"case {label}: slot {slot} holds no node") - if len(self.cases) >= self.max_cases: - raise ValueError(f"kernel {self.label}: more than {self.max_cases} cases") - if len(ray) != 10: - raise ValueError("ray is 10 words") - self.cases.append(dict(label=label, slot=slot, type=ntype, ray=[w & 0xFFFFFFFF for w in ray], meta=meta or {})) - return len(self.cases) - 1 - - def node_off(self, slot): - return self.L["node"] + SLOT * slot - - def node32(self, case): - return (SLOT * case["slot"]) >> 3 | case["type"] - - def lines(self): - L, u = self.L, self.uid - w1 = DESC["w1"] - out = [f"; kernel {u}: {self.label}", - f"s_add_u32 s20, s2, 0x{L['node']:x}", "s_addc_u32 s21, s3, 0", # node region VA - f"s_add_u32 s24, s2, 0x{L['ctl']:x}", "s_addc_u32 s25, s3, 0", # control block VA - "v_mov_b32 v1, 0"] - if self.threads == 64: - out += ["v_lshlrev_b32 v1, 8, v0"] # lane l -> 256 * l - out += ["v_mov_b32 v16, s20", "v_mov_b32 v17, s21", "v_mov_b32 v18, 0", "v_mov_b32 v19, 0", - "v_mov_b32 v13, 0", - "global_store_dwordx4 v13, v[16:19], s[24:25]", - "s_and_b32 s22, s20, 0xff", "s_cmp_lg_u32 s22, 0", f"s_cbranch_scc1 .Lbad{u}"] - for s in sorted(self.slots): - ws = self.slots[s] - out.append(f"; node slot {s} at +0x{self.node_off(s):x}, {len(ws) * 4} bytes") - for q in range(0, len(ws), 4): - out += [f"v_mov_b32 v{16 + j}, 0x{ws[q + j]:08x}" for j in range(4)] - out.append(f"global_store_dwordx4 v13, v[16:19], s[20:21] offset:{SLOT * s + 4 * q}") - out += ["s_waitcnt_vscnt null, 0x0", "buffer_gl0_inv", "buffer_gl1_inv"] - # descriptors: 32-bit form base = node region VA >> 8; 64-bit form base 0 - out += ["s_lshr_b64 s[14:15], s[20:21], 8", "s_mov_b32 s4, s14", "s_and_b32 s5, s15, 0xff", - f"s_or_b32 s5, s5, 0x{w1:08x}", f"s_mov_b32 s6, 0x{DESC['w2']:08x}", - f"s_mov_b32 s7, 0x{DESC['w3']:08x}", - "s_mov_b32 s8, 0", f"s_mov_b32 s9, 0x{w1:08x}", f"s_mov_b32 s10, 0x{DESC['w2']:08x}", - f"s_mov_b32 s11, 0x{DESC['w3']:08x}"] - if self.threads == 64: - out += ["v_mbcnt_lo_u32_b32 v14, -1, 0"] # lane id as the wave sees it - if self.wave == 64: - out += ["v_mbcnt_hi_u32_b32 v14, -1, v14"] - for i, c in enumerate(self.cases): - out += self._case_lines(i, c) - if self.threads == 64: - out += ["v_mov_b32 v16, v14", "v_mov_b32 v17, v0", f"v_mov_b32 v18, 0x{DONE | u:08x}", - "v_mov_b32 v19, 0", "global_store_dwordx4 v1, v[16:19], s[2:3] offset:224"] - out += ["v_mov_b32 v13, 0", f"v_mov_b32 v16, 0x{DONE | u:08x}", - "global_store_dword v13, v16, s[24:25] offset:8", - f"s_branch .Lend{u}", - f".Lbad{u}:", - "v_mov_b32 v13, 0", f"v_mov_b32 v16, 0x{POISON:08x}", - "global_store_dword v13, v16, s[24:25] offset:12", - f".Lend{u}:", - "s_waitcnt_vscnt null, 0x0", - "s_endpgm"] - return out - - def _case_lines(self, i, c): - out = [f"; case {i}: {c['label']} (slot {c['slot']}, type {c['type']})"] - out += [f"v_mov_b32 v{40 + j}, 0x{SENT | (i << 4) | j:08x}" for j in range(8)] - r = c["ray"] - out.append(f"v_mov_b32 v2, 0x{self.node32(c):x}") - out += [f"v_mov_b32 v{3 + j}, 0x{r[j]:08x}" for j in range(10)] - if self.lane_offsets: - dx, dy = self.lane_offsets - out += ["v_and_b32 v13, 15, v0", "v_cvt_f32_u32 v13, v13", f"v_fmac_f32 v4, 0x{f2u(dx):08x}, v13", - "v_lshrrev_b32 v13, 4, v0", "v_cvt_f32_u32 v13, v13", f"v_fmac_f32 v5, 0x{f2u(dy):08x}, v13"] - a = "[" + ", ".join(f"v{2 + j}" for j in range(11)) + "]" if self.nsa else "v[2:12]" - out.append(f"image_bvh_intersect_ray v[40:43], {a}, s[4:7]") - off = SLOT * c["slot"] - out += [f"s_add_u32 s12, s20, 0x{off:x}", "s_addc_u32 s13, s21, 0", "s_lshr_b64 s[12:13], s[12:13], 3", - f"s_or_b32 s12, s12, 0x{c['type']:x}", "v_mov_b32 v24, s12", "v_mov_b32 v25, s13"] - out += [f"v_mov_b32 v{26 + j}, v{3 + j}" for j in range(10)] - a = "[" + ", ".join(f"v{24 + j}" for j in range(12)) + "]" if self.nsa else "v[24:35]" - out.append(f"image_bvh64_intersect_ray v[44:47], {a}, s[8:11]") - out += ["s_waitcnt vmcnt(0)", - f"global_store_dwordx4 v1, v[40:43], s[2:3] offset:{32 * i}", - f"global_store_dwordx4 v1, v[44:47], s[2:3] offset:{32 * i + 16}"] - return out - - def program(self, asm): - """The hw_oracle program (asm is tools/hw_oracle/asm.py).""" - return asm.Kernel(self.lines(), wave=self.wave, threads=self.threads, words=self.L["words"], raw=True, - vgprs=48, sgprs=40) - - def lane_ray(self, case, lane): - """The ray lane `lane` traces: the kernel's v_fmac_f32 of the lane offsets (exact for these values).""" - r = list(case["ray"]) - if self.lane_offsets: - dx, dy = self.lane_offsets - r[1] = f2u(u2f(r[1]) + dx * (lane & 15)) - r[2] = f2u(u2f(r[2]) + dy * (lane >> 4)) - return r - - -def check_kernel(k): - """The memory rules above, from the kernel's bookkeeping and its lines; raises ValueError on a violation.""" - L = k.L - if not (L["node_end"] - L["node"] == NSLOTS * SLOT and L["node_end"] < 4 * L["words"] and L["node"] % 256 == 0): - raise ValueError(f"{k.label}: layout") - for s, ws in k.slots.items(): - if not (0 <= s < NSLOTS and len(ws) * 4 == NODE_BYTES): - raise ValueError(f"{k.label}: node slot {s}") - for c in k.cases: - if c["slot"] not in k.slots or not 0 <= c["type"] <= 3: - raise ValueError(f"{k.label}: case {c['label']}") - # results: case i at 32 i (+16 for the 64-bit form); lane kernels give each lane 256 bytes, its control at +224 - end = 256 * k.threads if k.threads == 64 else 32 * len(k.cases) - if end > L["ctl"] - L["res"] or (k.threads == 64 and 32 * len(k.cases) > 224): - raise ValueError(f"{k.label}: results overlap the control block") - lines = k.lines() - bvh = [ln for ln in lines if ln.startswith("image_bvh")] - if len(bvh) != 2 * len(k.cases): - raise ValueError(f"{k.label}: {len(bvh)} BVH instructions for {len(k.cases)} cases") - guard = lines.index(f"s_cbranch_scc1 .Lbad{k.uid}") - if lines[guard - 2:guard] != ["s_and_b32 s22, s20, 0xff", "s_cmp_lg_u32 s22, 0"] or \ - guard > lines.index(next(ln for ln in lines if ln.startswith("image_bvh"))): - raise ValueError(f"{k.label}: no alignment guard before the first BVH instruction") - for ln in lines: - if ln.startswith(("s_mov_b32 s6", "s_mov_b32 s10")) and not ln.endswith(f"0x{DESC['w2']:08x}"): - raise ValueError(f"{k.label}: descriptor w2 `{ln}`") - if ln.startswith(("s_mov_b32 s7", "s_mov_b32 s11")) and not ln.endswith(f"0x{DESC['w3']:08x}"): - raise ValueError(f"{k.label}: descriptor w3 `{ln}`") - if ln.startswith("global_store") and ln.split()[-1].startswith("offset:"): - off = int(ln.split(":")[-1]) - base = ln.split(", ")[2].split()[0] - hi = {"s[20:21]": L["node"] + off + 16, "s[24:25]": L["ctl"] + off + 4, - "s[2:3]": L["res"] + off + 16 + (k.threads - 1) * 256 * (k.threads == 64)}[base] - limit = {"s[20:21]": L["node_end"], "s[24:25]": L["ctl"] + 16, "s[2:3]": L["ctl"]}[base] - if hi > limit: - raise ValueError(f"{k.label}: store past its region `{ln}`") - return True - - -def results(k, output): - """Per case {hw32, hw64} (lane kernels: a list of 64), and the control words.""" - L = k.L - res = [] - for i, c in enumerate(k.cases): - if k.threads == 1: - b = (L["res"] + 32 * i) // 4 - res.append(dict(hw32=output[b:b + 4], hw64=output[b + 4:b + 8])) - else: - lanes = [] - for lane in range(k.threads): - b = (L["res"] + 256 * lane + 32 * i) // 4 - lanes.append(dict(hw32=output[b:b + 4], hw64=output[b + 4:b + 8])) - res.append(dict(lanes=lanes)) - return res, output[L["ctl"] // 4:L["ctl"] // 4 + 4] - - -def output_problem(k, output): - """Why an output cannot be trusted, or None.""" - if not isinstance(output, list) or len(output) < k.L["words"]: - return f"no output ({output!r:.200})" - if all(w == PREFILL for w in output): - return "the output is all prefill: the kernel did not run" - res, ctl = results(k, output) - if ctl[3] == POISON: - return "the node region was not 256-byte aligned: no BVH instruction ran" - if ctl[2] != DONE | k.uid: - return f"control word 2 is 0x{ctl[2]:08x}, not 0x{DONE | k.uid:08x}: the kernel did not reach its end" - for r in res: - for x in r.get("lanes", [r]): - if any(w & 0xFFFF0000 == SENT for w in x["hw32"] + x["hw64"]): - return "a destination register was never written" - return None - - -# --------------------------------------------------------------------------------------------------------------------- -# the cases (port of the measurement's tri/gen.py, the kernels that ran) -# --------------------------------------------------------------------------------------------------------------------- -# A closed fan of the four triangle node types around slot 2, all wound the same way, in the plane z = 3 -FAN = [(0, 0, 3), (4, 0, 3), (0, 2, 3), (4, 2, 3), (-2, 3, 3)] -VSLOTS = {0: (0, 1, 2), 1: (1, 3, 2), 2: (2, 3, 4), 3: (2, 4, 0)} -REMAP = 0x09090909 # every type: (V, W), what a builder writes -INSIDE = {0: (1, 0.25), 1: (3.5, 1.25), 2: (1.75, 2.125), 3: (-0.5, 2.0)} # interior points, distinct weights -OUTSIDE = {0: (-0.25, 0.75, 0.5), 1: (0.75, -0.25, 0.5), 2: (0.75, 0.5, -0.25)} # beyond the edge opposite vertex i -D_POS, D_NEG = (0.0, 0.0, 0.5), (0.0, 0.0, -0.5) -D_OBL, D_OBLN = (0.125, 0.0625, 0.5), (0.125, 0.0625, -0.5) -PX, PY = (2, 0, 1), (1, 2, 0) # cyclic: the dominant axis becomes x / y, orientation kept - - -def leaf(slots=FAN, remap=REMAP): - """16 node words: vertex slots 0..3, slot 4 in words 12..14, the remap bytes in word 15.""" - w = [f2u(float(c)) for s in slots for c in s] - if len(w) != 15: - raise ValueError("five vertex slots") - return w + [remap] - - -def bary(tri, p): - (ax, ay), (bx, by), (cx, cy) = [(Fr(v[0]), Fr(v[1])) for v in tri] - x, y = Fr(p[0]), Fr(p[1]) - det = (bx - ax) * (cy - ay) - (cx - ax) * (by - ay) - b1 = ((x - ax) * (cy - ay) - (cx - ax) * (y - ay)) / det - b2 = ((bx - ax) * (y - ay) - (x - ax) * (by - ay)) / det - return (1 - b1 - b2, b1, b2) - - -def ray_at(p, d, z=3.0, t=8.0, tmax=100.0, perm=None, inv=None): - """A ray that reaches (p, z) at parameter t along d. perm: cyclic axis permutation applied to the ray.""" - o = [p[0] - t * d[0], p[1] - t * d[1], z - t * d[2]] - dd = list(d) - if perm: - o, dd = [o[i] for i in perm], [dd[i] for i in perm] - return ray_words(tmax, o, dd, inv) - - -def permuted(slots, perm): - return [tuple(s[i] for i in perm) for s in slots] - - -def mirror(slots): - return [(-s[0], s[1], s[2]) for s in slots] - - -def outside_point(t, i, slots=FAN): - P = [slots[s][:2] for s in VSLOTS[t]] - b = OUTSIDE[i] - return (sum(b[j] * P[j][0] for j in range(3)), sum(b[j] * P[j][1] for j in range(3))) - - -def prev_f(x): - return u2f(f2u(x) - 1) - - -def next_f(x): - return u2f(f2u(x) + 1) - - -def g1(variant="", **kw): - """Slots and node types, both facings, axis and oblique rays, the cs_bvh triangle.""" - k = Kernel("tri_g1a" + variant, **kw) - s_fan = k.add_node(leaf()) - s_mir = k.add_node(leaf(mirror(FAN))) - for t in range(4): - k.add_case(f"TRI{t} hit +z", s_fan, t, ray_at(INSIDE[t], D_POS)) - k.add_case(f"TRI{t} hit -z (back)", s_fan, t, ray_at(INSIDE[t], D_NEG)) - for t in range(4): - k.add_case(f"TRI{t} miss (+z at TRI{(t + 1) % 4}'s point)", s_fan, t, ray_at(INSIDE[(t + 1) % 4], D_POS)) - for t in range(4): - p = INSIDE[t] - k.add_case(f"TRI{t} mirrored leaf hit +z", s_mir, t, ray_at((-p[0], p[1]), D_POS)) - for t in range(4): - k.add_case(f"TRI{t} hit oblique +z", s_fan, t, ray_at(INSIDE[t], D_OBL)) - k.add_case(f"TRI{t} hit oblique -z", s_fan, t, ray_at(INSIDE[t], D_OBLN)) - # runtime/test/vk_compute_test.cpp "bvh" scene, triangle node 0x40: z = 10 triangle, the heap's 0xEE fill elsewhere - cs = [f2u(c) for c in (0, 0, 10, 1, 0, 10, 0, 1, 10)] + [0xEEEEEEEE] * 6 + [0x09] - k.add_case("cs_bvh scene triangle node 0x40", k.add_node(cs), 0, - ray_words(100.0, (0.25, 0.25, 0.0), (0.0, 0.0, 1.0), (INF, INF, 1.0))) - return k - - -def g1b(): - """Dominant axis x and y, kz ties, mirrored leaf along -z.""" - k = Kernel("tri_g1b") - for perm, nm in ((PX, "x"), (PY, "y")): - s = k.add_node(leaf(permuted(FAN, perm))) - for t in (0, 2): - k.add_case(f"TRI{t} dominant +{nm}", s, t, ray_at(INSIDE[t], D_POS, perm=perm)) - k.add_case(f"TRI{t} dominant -{nm}", s, t, ray_at(INSIDE[t], D_NEG, perm=perm)) - s = k.add_node(leaf()) - p = INSIDE[0] - for d, nm in (((0.5, 0.0, 0.5), "|dx|=|dz|"), ((0.0, 0.5, 0.5), "|dy|=|dz|"), ((0.5, 0.5, 0.5), "|dx|=|dy|=|dz|")): - k.add_case(f"TRI0 kz tie {nm}", s, 0, ray_at(p, d)) - k.add_case("TRI0 kz tie |dx|=|dy|>|dz|", s, 0, ray_at(p, (0.5, 0.5, 0.25), t=16.0)) - s_m = k.add_node(leaf(mirror(FAN))) - for t in range(4): - q = INSIDE[t] - k.add_case(f"TRI{t} mirrored leaf hit -z", s_m, t, ray_at((-q[0], q[1]), D_NEG)) - return k - - -def g1c(): - """Misses with det < 0 and det > 0 for every type, outside by each of the three edges.""" - k = Kernel("tri_g1c") - s_fan = k.add_node(leaf()) - s_mir = k.add_node(leaf(mirror(FAN))) - k.add_case("control: TRI0 hit +z", s_fan, 0, ray_at(INSIDE[0], D_POS)) - k.add_case("control: TRI0 hit -z (back)", s_fan, 0, ray_at(INSIDE[0], D_NEG)) - for t in range(4): - for i in range(3): - p = outside_point(t, i) - for d, nm in ((D_POS, "+z (det<0)"), (D_NEG, "-z (det>0)")): - k.add_case(f"TRI{t} miss beyond edge opposite v{i} {nm}", s_fan, t, ray_at(p, d)) - p = outside_point(t, 0, mirror(FAN)) - k.add_case(f"TRI{t} mirrored leaf miss beyond edge opposite v0 +z (det>0)", s_mir, t, ray_at(p, D_POS)) - return k - - -def g2(): - """Remap byte: all 16 low nibbles per node type (the other three bytes 0x06), high nibbles on TRI0 both facings.""" - ks = [] - for half in (0, 1): - k = Kernel(f"tri_g2{'ab'[half]}") - for t in (2 * half, 2 * half + 1): - for n in range(16): - rm = sum((n if b == t else 0x06) << (8 * b) for b in range(4)) - k.add_case(f"TRI{t} byte{t}=0x{n:02x} others 0x06", k.add_node(leaf(remap=rm)), t, - ray_at(INSIDE[t], D_POS), meta=dict(byte=n)) - ks.append(k) - k = Kernel("tri_g2c") - for h in range(16): - rm = ((h << 4) | 0x09) | (0x06 << 8) | (0x06 << 16) | (0x06 << 24) - s = k.add_node(leaf(remap=rm)) - k.add_case(f"TRI0 byte0=0x{(h << 4) | 9:02x} +z", s, 0, ray_at(INSIDE[0], D_POS), meta=dict(byte=(h << 4) | 9)) - k.add_case(f"TRI0 byte0=0x{(h << 4) | 9:02x} -z (back)", s, 0, ray_at(INSIDE[0], D_NEG), - meta=dict(byte=(h << 4) | 9)) - ks.append(k) - return ks - - -def g3(): - """t max, the sign of t, zero area, NaN and inf in the node (tri_g3a); the ray's own NaN, inf, zero and - inconsistent inverse direction (tri_g3b).""" - p = INSIDE[0] - k = Kernel("tri_g3a") - s = k.add_node(leaf()) - for tm, nm in ((100.0, "100 (control)"), (8.0, "8 = t"), (prev_f(8.0), "prev(8)"), (next_f(8.0), "next(8)"), - (7.0, "7"), (0.0, "0"), (-1.0, "-1"), (INF, "+inf")): - k.add_case(f"TRI0 t=8 tmax={nm}", s, 0, ray_at(p, D_POS, tmax=tm)) - r = ray_at(p, D_POS) - r[0] = QNAN - k.add_case("TRI0 t=8 tmax=NaN", s, 0, r) - k.add_case("TRI0 behind origin +z (t=-4)", s, 0, ray_at(p, D_POS, t=-4.0)) - k.add_case("TRI0 behind origin -z (t=-4, back)", s, 0, ray_at(p, D_NEG, t=-4.0)) - k.add_case("TRI0 origin on the plane (t=0)", s, 0, ray_at(p, D_POS, t=0.0)) - k.add_case("TRI0 t=2^-19", s, 0, ray_at(p, D_POS, t=2.0 ** -19)) - z = 3 - one = k.add_node(leaf([(1, 0.25, z)] * 3 + [FAN[3], FAN[4]])) - k.add_case("zero area: three equal vertices, ray through them", one, 0, ray_at(p, D_POS)) - col = k.add_node(leaf([(0, 0.25, z), (2, 0.25, z), (4, 0.25, z), FAN[3], FAN[4]])) - k.add_case("zero area: collinear, ray through the segment", col, 0, ray_at(p, D_POS)) - k.add_case("zero area: collinear, ray off the line", col, 0, ray_at((1, 1), D_POS)) - eon = k.add_node(leaf([(0, 0.25, 0), (4, 0.25, 0), (0, 0.25, 6), FAN[3], FAN[4]])) - k.add_case("edge-on: ray in the triangle's plane, through it", eon, 0, ray_at(p, D_POS)) - for nm, vi, ci, val in (("v0.x NaN", 0, 0, QNAN), ("v0.z NaN", 0, 2, QNAN), ("v1.y NaN", 1, 1, QNAN), - ("v2.x +inf", 2, 0, 0x7F800000), ("v0.x -inf", 0, 0, 0xFF800000)): - w = leaf() - w[3 * vi + ci] = val - k.add_case(f"TRI0 vertex {nm}", k.add_node(w), 0, ray_at(p, D_POS)) - w = leaf() - w[9] = QNAN - k.add_case("TRI0 NaN in slot 3 (not read by TRI0): control", k.add_node(w), 0, ray_at(p, D_POS)) - w = leaf() - w[12] = QNAN - k.add_case("TRI0 NaN in slot 4 word 12 (not read by TRI0): control", k.add_node(w), 0, ray_at(p, D_POS)) - - k2 = Kernel("tri_g3b") - s = k2.add_node(leaf()) - base = ray_at(p, D_POS) - k2.add_case("TRI0 control", s, 0, base) - - def var(nm, idx, val): - r = list(base) - r[idx] = val & 0xFFFFFFFF - k2.add_case(f"TRI0 ray {nm}", s, 0, r) - var("o.x NaN", 1, QNAN) - var("o.z NaN", 3, QNAN) - var("o.x +inf", 1, 0x7F800000) - var("d.x NaN", 4, QNAN) - var("d.z NaN", 6, QNAN) - var("inv.z NaN", 9, QNAN) - var("inv.x NaN (axis the translator does not read)", 7, QNAN) - var("inv.z = 4 (not 1/d.z = 2)", 9, f2u(4.0)) - var("inv.z = 1 (not 1/d.z)", 9, f2u(1.0)) - var("inv.x = 3 (not 1/d.x = inf)", 7, f2u(3.0)) - var("d.x = -0.0", 4, 0x80000000) - r = list(base) - r[4], r[7] = 0x80000000, 0xFF800000 - k2.add_case("TRI0 ray d.x = -0.0, inv.x = -inf", s, 0, r) - r = list(base) - r[4:10] = [0, 0, 0, 0x7F800000, 0x7F800000, 0x7F800000] - k2.add_case("TRI0 ray d = 0, inv = +inf", s, 0, r) - r = list(base) - r[6], r[9] = 0x7F800000, 0 - k2.add_case("TRI0 ray d.z = +inf, inv.z = 0", s, 0, r) - k2.add_case("TRI0 ray d.z = 1024 (t = 2^-8)", s, 0, ray_at(p, (0.0, 0.0, 1024.0), t=4.0 / 1024)) - k2.add_case("TRI0 ray d.z = 2^-20 (t = 2^22)", s, 0, ray_at(p, (0.0, 0.0, 2.0 ** -20), t=4.0 * 2 ** 20, tmax=INF)) - k2.add_case("TRI0 ray oblique, inv.z = 4 (not 1/d.z)", s, 0, ray_at(p, D_OBL, inv=(8.0, 16.0, 4.0))) - k2.add_case("TRI0 ray oblique, inv.x = inv.y = 1 (not 1/d)", s, 0, ray_at(p, D_OBL, inv=(1.0, 1.0, 2.0))) - return [k, k2] - - -def g4(): - """Shared-edge and shared-vertex tie-breaks on the closed fan.""" - k = Kernel("tri_g4a") - s = k.add_node(leaf()) - for d, nm in ((D_POS, "+z"), (D_NEG, "-z"), (D_OBL, "oblique +z"), (D_OBLN, "oblique -z")): - for t in range(4): - k.add_case(f"fan vertex s2 (0,2), TRI{t}, {nm}", s, t, ray_at((0, 2), d)) - k2 = Kernel("tri_g4b") - s = k2.add_node(leaf()) - edges = (("E01 (2,1)", (2, 1), (0, 1)), ("E03 (0,1)", (0, 1), (0, 3)), ("E12 (2,2)", (2, 2), (1, 2)), - ("E23 (-1,2.5)", (-1, 2.5), (2, 3))) - for d, nm in ((D_POS, "+z"), (D_NEG, "-z"), (D_OBL, "oblique +z")): - for en, p, ts in edges: - for t in ts: - k2.add_case(f"shared edge {en}, TRI{t}, {nm}", s, t, ray_at(p, d)) - for nm, p, ts in (("outer vertex s0 (0,0)", (0, 0), (0, 3)), ("outer edge (2,0)", (2, 0), (0,)), - ("outer vertex s1 (4,0)", (4, 0), (0, 1)), ("outer vertex s3 (4,2)", (4, 2), (1, 2)), - ("outer vertex s4 (-2,3)", (-2, 3), (2,))): - for t in ts: - k2.add_case(f"{nm}, TRI{t}, +z", s, t, ray_at(p, D_POS)) - return [k, k2] - - -def g5_lanes(wave): - """64 threads (two waves of 32, or one of 64), each lane its own origin.""" - k = Kernel(f"tri_lanes_w{wave}", threads=64, wave=wave, lane_offsets=(2.0 ** -6, 2.0 ** -6)) - s = k.add_node(leaf()) - for t in range(4): - k.add_case(f"TRI{t} hit +z, origin + lane offset", s, t, ray_at(INSIDE[t], D_POS)) - k.add_case("TRI0 hit -z, origin + lane offset", s, 0, ray_at(INSIDE[0], D_NEG)) - k.add_case("TRI0 miss, origin + lane offset", s, 0, ray_at(INSIDE[1], D_POS)) - k.add_case("TRI1 hit oblique +z, origin + lane offset", s, 1, ray_at(INSIDE[1], D_OBL)) - return k - - -# --------------------------------------------------------------------------------------------------------------------- -# the tie cases (port of the measurement's ties/gen_ties.py and gen_bridge.py, the kernels tri_t1..t8 that ran): rays -# exactly on an edge or a vertex with x, y or z dominant, both windings, both signs of d[kz], and equal |d| -# components. Every kernel holds 32 cases, case i on its own slot i. -# --------------------------------------------------------------------------------------------------------------------- -TIE_SHARED = [("E01 (2,1)", (2, 1), (0, 1)), ("E03 (0,1)", (0, 1), (0, 3)), ("E12 (2,2)", (2, 2), (1, 2)), - ("E23 (-1,2.5)", (-1, 2.5), (2, 3))] -TIE_VERTEX = [("fan vertex s2 (0,2)", (0, 2), (0, 1, 2, 3))] -TIE_OUTER = [("outer edge s0-s1 (2,0)", (2, 0), (0,)), ("outer vertex s0 (0,0)", (0, 0), (0,)), - ("outer vertex s1 (4,0)", (4, 0), (0,))] -EQ_CLASSES = {"|dx|=|dy|>|dz|": ((0, 1), 2, 0.25), "|dx|=|dz|>|dy|": ((0, 2), 1, 0.125), - "|dy|=|dz|>|dx|": ((1, 2), 0, 0.125), "|dx|=|dy|=|dz|": ((0, 1, 2), None, None)} -# the equal-|d| tie rows that ran (class, d, mirrored leaf, tie point), chosen by gen_ties.group_t4 so that every two -# possible dominant axes give different words on some row under the two registered rules -EQ_TIES = [("|dx|=|dy|>|dz|", (0.5, 0.5, 0.25), False, "E01 (2,1)"), - ("|dx|=|dy|>|dz|", (0.5, -0.5, 0.25), False, "E12 (2,2)"), - ("|dx|=|dy|>|dz|", (-0.5, 0.5, 0.25), True, "E03 (0,1)"), - ("|dx|=|dy|>|dz|", (-0.5, -0.5, 0.25), False, "fan vertex s2 (0,2)"), - ("|dx|=|dz|>|dy|", (0.5, 0.125, 0.5), False, "E12 (2,2)"), - ("|dx|=|dz|>|dy|", (0.5, 0.125, -0.5), False, "E01 (2,1)"), - ("|dx|=|dz|>|dy|", (-0.5, 0.125, 0.5), True, "E12 (2,2)"), - ("|dx|=|dz|>|dy|", (-0.5, 0.125, -0.5), False, "E03 (0,1)"), - ("|dy|=|dz|>|dx|", (0.125, 0.5, 0.5), False, "E01 (2,1)"), - ("|dy|=|dz|>|dx|", (0.125, 0.5, -0.5), True, "E03 (0,1)"), - ("|dy|=|dz|>|dx|", (0.125, -0.5, 0.5), False, "E01 (2,1)"), - ("|dy|=|dz|>|dx|", (0.125, -0.5, -0.5), False, "E12 (2,2)"), - ("|dx|=|dy|=|dz|", (0.5, 0.5, 0.5), False, "fan vertex s2 (0,2)"), - ("|dx|=|dy|=|dz|", (0.5, 0.5, -0.5), True, "E03 (0,1)"), - ("|dx|=|dy|=|dz|", (0.5, 0.5, -0.5), False, "E01 (2,1)"), - ("|dx|=|dy|=|dz|", (0.5, -0.5, 0.5), False, "fan vertex s2 (0,2)"), - ("|dx|=|dy|=|dz|", (-0.5, 0.5, 0.5), False, "E01 (2,1)"), - ("|dx|=|dy|=|dz|", (-0.5, 0.5, 0.5), True, "E03 (0,1)")] -# measured rows of the kernels above, repeated as controls (kernel, case label) -TIE_CONTROLS = [("tri_g1a", "TRI0 hit +z"), ("tri_g4b", "shared edge E01 (2,1), TRI1, +z"), - ("tri_g4b", "shared edge E01 (2,1), TRI0, +z"), ("tri_g4a", "fan vertex s2 (0,2), TRI2, -z"), - ("tri_g4b", "shared edge E12 (2,2), TRI2, -z"), ("tri_g1b", "TRI0 dominant +x"), - ("tri_g4b", "shared edge E23 (-1,2.5), TRI3, oblique +z"), ("tri_g1b", "TRI2 dominant -y"), - ("tri_g4a", "fan vertex s2 (0,2), TRI1, oblique +z"), - ("tri_g1c", "TRI1 miss beyond edge opposite v2 -z (det>0)"), - ("tri_g4b", "outer vertex s0 (0,0), TRI0, +z"), ("tri_g1b", "TRI0 kz tie |dx|=|dy|=|dz|"), - ("tri_g4b", "shared edge E03 (0,1), TRI0, -z"), ("tri_g1a", "TRI1 mirrored leaf hit +z"), - ("tri_g4b", "shared edge E12 (2,2), TRI1, oblique +z"), ("tri_g1b", "TRI2 dominant +x")] -BRIDGE_CONTROLS = [("tri_g1a", "TRI1 mirrored leaf hit +z"), ("tri_g4b", "shared edge E03 (0,1), TRI0, -z"), - ("tri_g4a", "fan vertex s2 (0,2), TRI2, -z"), ("tri_g4b", "shared edge E12 (2,2), TRI1, oblique +z")] - - -def tie_rows(points, d, a=0.0, b=0.0, mirrored=False, rot=False, perm=None, tag=""): - """[(label, node, type, ray)]: the fan turned 90 degrees in its plane ((x, y) -> (-y, x)) if rot, then mirrored - (x -> -x, the other winding) if mirrored, lifted onto z = 3 + a x + b y, then axis-permuted (perm); a ray that - reaches each tie point at t = 8.""" - def xy(p): - x, y = (-p[1], p[0]) if rot else p - return (-x, y) if mirrored else (x, y) - pz = lambda x, y: 3 + a * x + b * y - slots = [(*xy((x, y)), pz(*xy((x, y)))) for x, y, _ in FAN] - node = leaf(permuted(slots, perm) if perm else slots) - nm = ("rotated " if rot else "") + ("mirrored fan" if mirrored else "fan") - if a or b: - nm += f" on z=3{a:+g}x{b:+g}y" - if perm: - nm += f", axes cycled ({ {PX: 'z->x', PY: 'z->y'}[perm] })" - out = [] - for pn, p, ts in points: - q = xy(p) - for t in ts: - ray = ray_at(q, d, z=pz(*q), perm=perm) - dd = [u2f(x) for x in ray[4:7]] - out.append((f"{tag}{pn}, TRI{t}, {nm}, d=({dd[0]:g},{dd[1]:g},{dd[2]:g})", node, t, ray)) - return out - - -def eq_dirs(cls): - tied, other, mag = EQ_CLASSES[cls] - signs = [(1, 1, 1), (1, 1, -1), (1, -1, 1), (-1, 1, 1)] if len(tied) == 3 else \ - [(1, 1), (1, -1), (-1, 1), (-1, -1)] - out = [] - for sg in signs: - d = [0.0, 0.0, 0.0] - for ax, s in zip(tied, sg): - d[ax] = 0.5 * s - if other is not None: - d[other] = mag - out.append(tuple(d)) - return out - - -def tie_kernels(measured): - """tri_t1..t7 (x / y dominant and equal |d|) and the z bridge tri_t8. measured: the kernels above, by label.""" - def ctl(kn, lab): - k = measured[kn] - c = next(c for c in k.cases if c["label"] == lab) - return (f"control {kn}: {lab}", k.slots[c["slot"]], c["type"], c["ray"]) - body = [] - for perm, ax in ((PX, "x"), (PY, "y")): # T1: perpendicular fan, x / y dominant - for mirrored in (False, True): - for d, sn in ((D_POS, "+"), (D_NEG, "-")): - pts = TIE_SHARED + TIE_VERTEX + ([] if (not mirrored and d == D_POS) else TIE_OUTER) - body += tie_rows(pts, d, mirrored=mirrored, perm=perm, tag=f"T1 {sn}{ax}: ") - body += tie_rows(TIE_SHARED[:1], d, mirrored=mirrored, rot=True, perm=perm, tag=f"T1 {sn}{ax}: ") - for ax, a, b, mirrored, d in (("x", 1.0, 0.0, False, (0.125, -0.25, 0.5)), # T2: tilted fans, oblique rays - ("y", 1.0, 1.0, True, (-0.125, -0.25, -0.5))): - body += tie_rows(TIE_SHARED + TIE_VERTEX, d, a=a, b=b, mirrored=mirrored, perm={"x": PX, "y": PY}[ax], - tag=f"T2 {ax}-dominant: ") - i = 0 # T3: equal |d|, no tie - for cls in EQ_CLASSES: - tied = EQ_CLASSES[cls][0] - for d in eq_dirs(cls)[1::2]: - t = i % 4 - i += 1 - body.append((f"T3 {cls}: TRI{t} interior hit, fan, d=({d[0]:g},{d[1]:g},{d[2]:g})", leaf(), t, - ray_at(INSIDE[t], d))) - if len(tied) == 2 and tied != (0, 1): - continue - d = eq_dirs(cls)[3] - body.append((f"T3 {cls}: TRI0 miss (at TRI1's point), fan, d=({d[0]:g},{d[1]:g},{d[2]:g})", leaf(), 0, - ray_at(INSIDE[1], d))) - by_name = {p[0]: p for p in TIE_SHARED + TIE_VERTEX} # T4: ties under equal |d| - for cls, d, mirrored, pn in EQ_TIES: - body += tie_rows([by_name[pn]], d, mirrored=mirrored, tag=f"T4 {cls}: ") - ctls = [ctl(*c) for c in TIE_CONTROLS] - ks, ci = [], 0 - for n in range(-(-len(body) // 31)): - chunk = body[31 * n:31 * (n + 1)] - cs = [] - while len(chunk) + len(cs) < 32: - cs.append(ctls[ci % len(ctls)]) - ci += 1 - ks.append((f"tri_t{n + 1}", cs[:1] + chunk + cs[1:])) - bridge = [] # tri_t8: z dominant, the cells #4202 never measured - for d, sn in ((D_POS, "+z"), (D_NEG, "-z")): - bridge += tie_rows(TIE_SHARED[:3] + TIE_VERTEX, d, mirrored=True, tag=f"T5 {sn}: ") - bridge += tie_rows(TIE_SHARED[:1], d, mirrored=True, rot=True, tag=f"T5 {sn}: ") - bridge += tie_rows(TIE_SHARED[:1], d, rot=True, tag=f"T5 {sn}: ") - bctl = [ctl(*c) for c in BRIDGE_CONTROLS] - ks.append(("tri_t8", bctl[:1] + bridge + bctl[1:])) - out = [] - for label, rows in ks: - k = Kernel(label) - for lab, node, t, ray in rows: - k.add_case(lab, k.add_node(node), t, ray) - out.append(k) - return out - - -def build_kernels(): - """The 22 kernels of the two measurements (14 of #4202, then the tie cases tri_t1..t8), in the order of - tests/semantic/test_image_bvh_tri_hw.py.""" - for t, p in INSIDE.items(): # each interior point is inside its own triangle only - w = bary([FAN[s][:2] for s in VSLOTS[t]], p) - assert all(x > 0 for x in w) and len(set(w)) == 3, (t, w) - for u in range(4): - if u != t: - assert min(bary([FAN[s][:2] for s in VSLOTS[u]], p)) < 0, (t, u) - ks = [g1(), g1("_nsa", nsa=True), g1("_w64", wave=64), g1b(), g1c(), *g2(), *g3(), *g4(), g5_lanes(32), - g5_lanes(64)] - ks += tie_kernels({k.label: k for k in ks}) - for k in ks: - check_kernel(k) - return ks - - -# --------------------------------------------------------------------------------------------------------------------- -# the measured rule (docs/design.md, Ray tracing row), binary32 rounding after every operation -# --------------------------------------------------------------------------------------------------------------------- -def f32(x): - if math.isnan(x) or math.isinf(x): - return x - try: - return struct.unpack(" Q whose edge function is exactly 0 counts as inside when, with (tx, ty) = Q - P in the sheared frame with the - d[kz] < 0 swap undone, ty == 0 ? sign(det) tx > 0 : sign(d[kz]) sign(det) ty > 0.""" - tmax = u2f(ray[0]) - o, d, inv = ([u2f(x) for x in ray[a:a + 3]] for a in (1, 4, 7)) - if any(math.isnan(x) for x in [tmax] + o + d + inv) or any(math.isinf(x) for x in o): - return [0x7F800000, 0x3F800000, 0, 0] - V = [[u2f(node[3 * s + c]) for c in range(3)] for s in VSLOTS[ntype]] - ad = [abs(c) for c in d] - if ad[0] >= ad[1]: - kz, ky, kx = (0, 2, 1) if ad[0] >= ad[2] else (2, 1, 0) - else: - kz, ky, kx = (1, 0, 2) if ad[1] >= ad[2] else (2, 1, 0) - s = -1.0 if d[kz] < 0 else 1.0 - if s < 0: - kx, ky = ky, kx - adz = abs(d[kz]) - px, py = _mul(s, d[kx]), _mul(s, d[ky]) - rel = [[_sub(V[j][c], o[c]) for c in range(3)] for j in range(3)] - sh = [(_sub(_mul(r[kx], adz), _mul(px, r[kz])), _sub(_mul(r[ky], adz), _mul(py, r[kz])), r[kz]) for r in rel] - (ax, ay, az), (bx, by, bz), (cx, cy, cz) = sh - U = _sub(_mul(cx, by), _mul(cy, bx)) - Vv = _sub(_mul(ax, cy), _mul(ay, cx)) - W = _sub(_mul(bx, ay), _mul(by, ax)) - det = _add(U, _add(Vv, W)) - byte = (node[15] >> (8 * ntype)) & 0xFF - pick = (U, Vv, W, U) # selector 3 reads U; bits 7:4 of the byte are ignored - w = [_mul(s, _add(_add(_mul(U, az), _mul(Vv, bz)), _mul(W, cz)))] - w += [_mul(adz, x) for x in (det, pick[byte & 3], pick[(byte >> 2) & 3])] - hit = False - if det == det and det != 0: - sg = 1.0 if det > 0 else -1.0 - - def passes(x, p, q): # a zero edge function: RDNA2's tie rule on the edge from p to q - if x != 0: - return x * sg > 0 # False for a NaN - tx, ty = q[0] - p[0], q[1] - p[1] - if s < 0: # in the frame with the kx/ky swap of d[kz] < 0 undone - tx, ty = ty, tx - return sg * tx > 0 if ty == 0 else s * sg * ty > 0 - a2, b2, c2 = (ax, ay), (bx, by), (cx, cy) - hit = passes(U, b2, c2) and passes(Vv, c2, a2) and passes(W, a2, b2) and sg * w[0] >= 0 - out = [0xFFC00000 if x != x else 0 if x == 0 else f2u(x) for x in w] - if not hit: - out[0] = 0x7F800000 | (out[1] & 0x80000000) - return out - - -# --------------------------------------------------------------------------------------------------------------------- -# the translator (tools/rdna2spirv.py on tests/semantic/spirv_mini_interp.py) -# --------------------------------------------------------------------------------------------------------------------- -T_RAY, T_NODE = 0x1000, 0x2000 - - -def _translate(work, form, nsa): - import rdna2spirv - lines = ["s_buffer_load_dwordx16 s[8:23], s[0:3], 0", "s_waitcnt lgkmcnt(0)"] - if form == "64": - lines += [f"v_mov_b32_e32 v{1 + i}, s{8 + i}" for i in range(12)] + ["s_mov_b32 s4, 0"] - regs, op = [f"v{1 + i}" for i in range(12)], "image_bvh64_intersect_ray" - else: - lines += ["v_mov_b32_e32 v1, s8"] + [f"v_mov_b32_e32 v{2 + i}, s{10 + i}" for i in range(10)] - lines += [f"s_mov_b32 s4, 0x{T_NODE >> 8:x}"] - regs, op = [f"v{1 + i}" for i in range(11)], "image_bvh_intersect_ray" - addr = "[" + ", ".join(regs) + "]" if nsa else f"v[1:{len(regs)}]" - lines += [f"s_mov_b32 s5, 0x{DESC['w1']:08x}", f"s_mov_b32 s6, 0x{DESC['w2']:08x}", - f"s_mov_b32 s7, 0x{DESC['w3']:08x}", f"{op} v[20:23], {addr}, s[4:7]", - "exp mrt0 v20, v21, v22, v23 done vm", "s_endpgm"] - name = f"ps_bvh_tri_probe_{form}{'_nsa' if nsa else ''}" - os.makedirs(os.path.join(work, "disasm"), exist_ok=True) - src = os.path.join(work, "disasm", name + ".s") - with open(src, "w", encoding="utf-8", newline="\n") as f: - f.write(f"; {name}\n" + "".join(f"\t{ln}\n" for ln in lines)) - with open(os.path.join(work, name + ".dxbc"), "wb") as f: - f.write(STUB_DXBC) - with warnings.catch_warnings(): - warnings.simplefilter("ignore", ResourceWarning) - spv = rdna2spirv.translate(src) - gc.collect() - return spv - - -def run_translator(kernels): - """{kernel: [per case {"tr32", "tr64"} or {"lanes": [...]}]}; a case the interpreter refuses is a string.""" - import spirv_mini_interp - out = {} - with tempfile.TemporaryDirectory(prefix="bvh_tri_probe_") as work: - spv = {(f, n): _translate(work, f, n) for f in ("32", "64") for n in (False, True)} - - def one(k, c, ray): - r = {} - for form in ("32", "64"): - nid = (T_NODE >> 3 | c["type"]) if form == "64" else c["type"] - mem = {T_RAY + 4 * i: w for i, w in enumerate([nid, 0, *ray, 0, 0, 0, 0])} - mem.update({T_NODE + 4 * i: w for i, w in enumerate(k.slots[c["slot"]])}) - try: - r["tr" + form] = list(spirv_mini_interp.run_fragment( - spv[(form, k.nsa)], push_constants=[T_RAY, 0, 0x100, 0] + [0] * 28, - memory=mem)["%out_mrt0"]) - except Exception as e: # noqa: BLE001 (UnsupportedConstruct: undefined in SPIR-V) - r["tr" + form] = f"{type(e).__name__}: {e}" - return r - for k in kernels: - out[k.label] = [dict(lanes=[one(k, c, k.lane_ray(c, ln)) for ln in range(64)]) if k.threads == 64 - else one(k, c, c["ray"]) for c in k.cases] - return out - - -# --------------------------------------------------------------------------------------------------------------------- -# the GPU -# --------------------------------------------------------------------------------------------------------------------- -def run_hw(kernels, oracle, asm): - """{kernel: [per case {"hw32", "hw64"} or {"lanes": [...]}], or a string saying why it was not run}. One - oracle.run call (one dispatch) per kernel; the first untrustworthy output stops the run.""" - out = {} - limit = getattr(oracle, "max_words", None) or (4096 if type(oracle).__name__ == "DrmOracle" else 16384) - # the runner checks isinstance(program, asm.Kernel) against the asm module it imported itself (one loaded by file - # path is another module object): build the programs with that one - asm = getattr(sys.modules.get(type(oracle).__module__), "asm", None) or asm - for k in kernels: - check_kernel(k) - if k.L["words"] > limit: - out[k.label] = f"skipped: the launcher reads back at most {limit} dwords, this kernel {k.L['words']}" - continue - output = oracle.run([k.program(asm)], words=k.L["words"])[0] - why = output_problem(k, output) - if why: - raise RuntimeError(f"{k.label}: {why}") - out[k.label] = results(k, output)[0] - return out - - -# --------------------------------------------------------------------------------------------------------------------- -# comparison and the command line -# --------------------------------------------------------------------------------------------------------------------- -def hx(ws): - return " ".join(f"{w:08x}" for w in ws) if isinstance(ws, list) else str(ws) - - -def compare(kernels, tr, hw): - """Rows of {kernel, case, lane, rule, tr32/tr64, hw32/hw64, status} and the number of failed rows.""" - rows, bad = [], 0 - for k in kernels: - trk = tr.get(k.label) if tr else None - hwk = hw.get(k.label) if hw else None - if isinstance(hwk, str): - print(f"{k.label}: {hwk}") - hwk = None - for i, c in enumerate(k.cases): - lanes = range(64) if k.threads == 64 else [None] - for ln in lanes: - ray = k.lane_ray(c, ln) if ln is not None else c["ray"] - want = rule_words(k.slots[c["slot"]], c["type"], ray) - row = dict(kernel=k.label, case=c["label"], lane=ln, rule=want) - for src, got in (("tr", trk), ("hw", hwk)): - if got is not None: - x = got[i]["lanes"][ln] if ln is not None else got[i] - row.update(x) - vals = [row[x] for x in ("tr32", "tr64", "hw32", "hw64") if x in row] - row["status"] = "OK" if all(v == want for v in vals) else "MISMATCH" - if row["status"] != "OK": - bad += 1 - print(f"[MISMATCH] {k.label}: {c['label']}" + (f", lane {ln}" if ln is not None else "")) - for x in ("rule", "tr32", "tr64", "hw32", "hw64"): - if x in row: - print(f" {x:5} {hx(row[x])}") - rows.append(row) - return rows, bad - - -def self_test(): - ks = build_kernels() - single = sum(len(k.cases) for k in ks if k.threads == 1) - assert single == 564 and [len(k.cases) for k in ks if k.threads == 64] == [7, 7], single - assert len({k.uid for k in ks}) == len(ks) - for k in ks: # a box node, type 6/7 or a free node id cannot be added - for bad in (lambda: k.add_case("x", 0, 5, [0] * 10), lambda: k.add_case("x", 31, 0, [0] * 10)): - n = len(k.cases) - try: - bad() - except ValueError: - pass - else: - raise AssertionError(f"{k.label}: an illegal case was accepted") - del k.cases[n:] - by = {k.label: k for k in ks} - # hand-derived words of five measured rows (docs/design.md, Ray tracing row) - g1a, g3b = by["tri_g1a"], by["tri_g3b"] - for k, label, want in ( - (g1a, "TRI0 hit +z", [0xC1000000, 0xBF800000, 0xBE800000, 0xBE000000]), # k = 1/8: -64/8, -8/8, ... - (g1a, "TRI2 hit +z", [0xC0800000, 0xBF000000, 0xBE800000, 0xBD800000]), # |det| 4: half of TRI0's - (g3b, "TRI0 ray inv.x NaN (axis the translator does not read)", [0x7F800000, 0x3F800000, 0, 0]), - (g3b, "TRI0 ray d.z = 1024 (t = 2^-8)", [0xCC000000, 0xD0000000, 0xCF000000, 0xCE800000]), # k = 2^30 - (g3b, "TRI0 ray d = 0, inv = +inf", [0x7F800000, 0, 0, 0])): - c = next(c for c in k.cases if c["label"] == label) - got = rule_words(k.slots[c["slot"]], c["type"], c["ray"]) - assert got == want, (label, hx(got), hx(want)) - print(f"self-test OK: {len(ks)} kernels, {single} single-lane cases, 2 x 7 lane cases; rule checked on 5 rows") - return 0 - - -def write_kernels(kernels, out_dir): - os.makedirs(out_dir, exist_ok=True) - for k in kernels: - with open(os.path.join(out_dir, k.label + ".s"), "w", encoding="utf-8", newline="\n") as f: - f.write("\n".join(k.lines()) + "\n") - tab = dict(label=k.label, uid=k.uid, threads=k.threads, wave=k.wave, nsa=k.nsa, layout=k.L, - lane_offsets=k.lane_offsets, desc={x: f"0x{v:08x}" for x, v in DESC.items()}, - nodes={str(s): [f"0x{w:08x}" for w in ws] for s, ws in sorted(k.slots.items())}, - cases=[dict(c, ray=[f"0x{w:08x}" for w in c["ray"]], node32=f"0x{k.node32(c):x}", - rule=[f"0x{w:08x}" for w in rule_words(k.slots[c["slot"]], c["type"], c["ray"])]) - for c in k.cases]) - with open(os.path.join(out_dir, k.label + ".json"), "w", encoding="utf-8", newline="\n") as f: - json.dump(tab, f, indent=1) - print(f"{k.label}: {len(k.cases)} cases, lines sha256 " - f"{hashlib.sha256(chr(10).join(k.lines()).encode('utf-8')).hexdigest()[:16]}") - return 0 - - -def main(argv=None): - ap = argparse.ArgumentParser(description=__doc__.splitlines()[0]) - ap.add_argument("--oracle", default="translator", help="translator (default), hw, or translator,hw") - ap.add_argument("--kernel", action="append", default=[], help="run only this kernel (repeatable)") - ap.add_argument("--list", action="store_true", help="list the kernels and their cases") - ap.add_argument("--write-kernels", metavar="DIR", help="write every kernel's lines and cases; no GPU") - ap.add_argument("--json", dest="json_out", help="write every case's words to this file") - ap.add_argument("--self-test", action="store_true") - args = ap.parse_args(argv) - if args.self_test: - return self_test() - backends = tuple(dict.fromkeys(t.strip() for t in args.oracle.split(","))) - if not backends or any(t not in ("translator", "hw") for t in backends): - print("error: --oracle takes translator, hw or translator,hw", file=sys.stderr) - return 2 - kernels = build_kernels() - if args.kernel: - names = [k.label for k in kernels] - unknown = [n for n in args.kernel if n not in names] - if unknown: - print(f"error: unknown kernel(s) {', '.join(unknown)} (known: {', '.join(names)})", file=sys.stderr) - return 2 - kernels = [k for k in kernels if k.label in args.kernel] - if args.json_out is not None and (not args.json_out.strip() or os.path.isdir(args.json_out)): - print(f"error: --json {args.json_out.strip() or '(empty)'} is not a file path", file=sys.stderr) - return 2 - if args.list: - for k in kernels: - print(f"{k.label:15} threads={k.threads:2} wave={k.wave} nsa={str(k.nsa):5} cases={len(k.cases)}") - for c in k.cases: - print(f" {c['label']}") - return 0 - if args.write_kernels: - return write_kernels(kernels, args.write_kernels) - tr = run_translator(kernels) if "translator" in backends else None - hw, device = None, None - if "hw" in backends: - from hw_oracle import asm, runner - try: - oracle = runner.open_oracle() - except runner.Unavailable as e: - print(f"hardware oracle unavailable: {e}", file=sys.stderr) - return 77 - try: - if asm.family(oracle.arch) != "gfx10": - print(f"SKIP: {oracle.arch} is not GFX10 (RDNA1/RDNA2)", file=sys.stderr) - return 77 - device = getattr(oracle, "device", oracle.arch) - print(f"hardware oracle: {device}") - try: - hw = run_hw(kernels, oracle, asm) - except RuntimeError as e: - print(f"error: {e}", file=sys.stderr) - return 2 - finally: - oracle.close() - rows, bad = compare(kernels, tr, hw) - srcs = [x for x, v in (("translator", tr), ("hardware", hw)) if v is not None] - print(f"summary: {len(rows)} results ({sum(r['lane'] is None for r in rows)} single-lane) of {len(kernels)} " - f"kernels, {' and '.join(srcs)} against the rule, both forms: {len(rows) - bad} match, {bad} mismatch") - if args.json_out is not None: - parent = os.path.dirname(os.path.abspath(args.json_out)) - try: - os.makedirs(parent, exist_ok=True) - with open(args.json_out, "w", encoding="utf-8", newline="\n") as f: - json.dump({"device": device, "rows": rows}, f, indent=1) - f.write("\n") - except OSError as e: - print(f"error: cannot write --json {args.json_out}: {e}", file=sys.stderr) - return 2 - return 1 if bad else 0 - - -if __name__ == "__main__": - try: # a redirected stdout is strict ANSI code page under -I; write '?' for what it cannot encode - sys.stdout.reconfigure(errors="replace") - except (AttributeError, ValueError, OSError): - pass - sys.exit(main()) diff --git a/tools/calibrated_texture.py b/tools/calibrated_texture.py deleted file mode 100644 index 1168fae03..000000000 --- a/tools/calibrated_texture.py +++ /dev/null @@ -1,443 +0,0 @@ -"""Numerical reconstruction with an explicitly supplied local calibration profile.""" - -from functools import lru_cache -import ctypes -import hashlib -import json -import os -from pathlib import Path -import sys -import tempfile -import zlib - -# `python -I` implies `-P`, so the script's directory is not on sys.path; the sibling modules are next to it. -sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) - -import numpy as np -import bcpack -import bcpack_tables -import ttpf_mips as ttpf - - -@lru_cache(maxsize=1) -def native(): - name = { - "win32": "bcpack_calibration.dll", - "darwin": "libbcpack_calibration.dylib", - }.get(sys.platform, "libbcpack_calibration.so") - path = Path(__file__).with_name("bcpack_calibration") / "target/release" / name - lib = ctypes.CDLL(str(path)) - lib.unpack.argtypes = [ - ctypes.c_char_p, - ctypes.c_size_t, - ctypes.c_char_p, - ctypes.c_size_t, - ctypes.c_size_t, - ctypes.c_void_p, - ] - lib.unpack.restype = ctypes.c_ssize_t - lib.rebuild.argtypes = [ctypes.c_void_p, ctypes.c_size_t] + [ctypes.c_void_p] * 5 - lib.rebuild.restype = None - return lib - - -def array(values, shape, dtype, lo, hi): - data = np.asarray(values) - if ( - data.shape != shape - or data.dtype.kind not in "iu" - or np.any(data < lo) - or np.any(data > hi) - ): - raise ValueError(f"Invalid calibration field (expected integer array {shape})") - return np.ascontiguousarray(data, dtype=dtype) - - -def unzig(a): - return (a >> 1) ^ -(a & 1) - - -def distance(symbols, lane): - spread = np.array( - [sum(((v >> k) & 1) << (2 * k) for k in range(4)) for v in range(16)] - ) - return spread[symbols[:, 0, lane]] + 2 * spread[symbols[:, 1, lane]] - - -def accumulate(distances, residuals): - roots = np.arange(len(distances)) - distances - roots[distances == 0] = -512 - while (mask := roots >= 0).any(): - parents = roots[mask] - residuals[mask] += residuals[parents] - roots[mask] = roots[parents] - return roots - - -def bc1_blocks(s, params): - seeds, selectors = params - ep = unzig(s[:, 2:8].astype("int32")) - roots = accumulate(unzig(s[:, 0].astype("int32")) % 256, ep) - external = roots != -512 - base = seeds[-roots[external]] - if np.any(base < 0): - raise ValueError("Missing BC1 endpoint history") - ep[external] += base - ep %= (32, 64, 32, 32, 64, 32) - rgb = (ep[:, ::3] << 11) | (ep[:, 1::3] << 5) | ep[:, 2::3] - indices = np.bitwise_or.reduce(selectors[np.arange(4), s[:, 8:12]], axis=1) - words = ( - rgb[:, 0].astype("uint64") - | (rgb[:, 1].astype("uint64") << 16) - | (indices.astype("uint64") << 32) - ) - return words.astype(" 8): - raise ValueError("Invalid history precision") - self.seeds[name] = data - return self.seeds[name] - - def symbols(self, c): - _, size, offset, packed, codec, _ = self.pool.chunks[c] - raw = self.pool.data[offset : offset + packed] - widths = bcpack.LANE_WIDTHS[codec] - sy = np.empty((size // 8, len(widths)), "uint8") - used = native().unpack( - raw, - packed, - bytes(w - 1 for w in widths), - len(widths), - len(sy), - sy.ctypes.data, - ) - if used != packed: - lanes, consumed = bcpack.decode_lanes(raw, codec, size) - if consumed != packed: - raise ValueError(f"Entropy decode failed for chunk {c}") - sy = np.ascontiguousarray(np.asarray(lanes, dtype="uint8").T) - # Historical feeder interpretations may release a short group of symbols - # in a different order. The profile identifies the exact compressed input. - if codec == 1 and self.cal.get("compatibility"): - cycle = self.cal["compatibility"].get(hashlib.sha256(raw).hexdigest()) - if cycle: - if any(type(v) != int or not 0 <= v < sy.size for v in cycle) or len( - set(cycle) - ) != len(cycle): - raise ValueError("Invalid symbol rotation") - sy.flat[cycle] = np.roll(sy.ravel()[cycle], -1) - return sy - - def _read_chunk(self, c, bs, profile): - _, size, start, length, codec, _ = self.pool.chunks[c] - if size % bs or (codec not in (0, 8) and bcpack.BLOCK_BYTES.get(codec) != bs): - raise ValueError("Block size and codec disagree") - if codec in (0, 8): - raw = self.pool.data[start : start + length] - if codec: - raw = zlib.decompress(raw) - if len(raw) != size: - raise ValueError("Invalid raw chunk length") - return np.frombuffer(raw, f"V{bs}"), None - sy = self.symbols(c) - if codec == 7: - if self.config is None: - cfg = self.cal["bc7"] - self.config = ( - array(cfg["labels"], (1024, 4), "int16", -1, 255), - array(cfg["anchors"], (128,), "uint16", 0, 65535), - ) - names = ["early"] if profile == "early" else ["base", "secondary"] - if profile == "refined": - names.append("refined") - blocks, valid = bc7_blocks(sy, self.config, self.seed(names[0])) - for name in names[1:]: - if valid.all(): - break - alternative, known = bc7_blocks(sy, self.config, self.seed(name)) - blocks[~valid] = alternative[~valid] - valid |= known - return blocks, valid - if codec == 1: - if self.bc1 is None: - cfg = self.cal["bc1"] - self.bc1 = ( - array(cfg["endpoints"], (256, 6), "int32", -1, 63), - array(cfg["selectors"], (4, 256), "uint32", 0, 0xFFFFFFFF), - ) - raw = bc1_blocks(sy, self.bc1) - elif codec == 6: - raw = bcpack._bc6h_blocks( - [l.tobytes() for l in sy.T], size // bs, set(), history=self.cal["bc6h"] - ) - elif codec == 4: - table = {int(k): v for k, v in self.cal["bc4"][profile].items()} - raw = scalar_bc4(sy, table) - elif codec == 3: - raw = local_bc3(sy, self.cal["bc3"]) - elif codec == 5: - raw = local_bc5(sy) - return np.frombuffer(raw, f"V{bs}"), None - - def surface(self, at, bs, profile): - chunks = np.searchsorted(self.edges, at, side="right") - 1 - if np.any(chunks < 0) or np.any(chunks >= len(self.pool.chunks)): - raise ValueError("Texture exceeds virtual pool") - result = np.empty(len(at), f"V{bs}") - for c in np.unique(chunks): - mask = chunks == c - ix = (at[mask] - self.edges[c]) // bs - blocks, ok = self.read_chunk(int(c), bs, profile) - chosen = blocks[ix] - if ok is not None and not ok[ix].all(): - missing = ~ok[ix] - if profile != "refined": - raise ValueError("Missing calibrated blocks") - sy = self.symbols(c) - key = hashlib.sha256( - sy.tobytes() + ix[missing].astype("> i) + 3) // 4) * ((max(1, height >> i) + 3) // 4) * bs - for i in range(count) - ) - if expected > ttpf.MAX_OUTPUT: - raise ValueError("DDS exceeds output limit") - grids = [ - ((max(1, width >> i) + 3) // 4, (max(1, height >> i) + 3) // 4) - for i in range(levels) - ] - if faces > 1 and d["mode"] == 1: - # Mode-1 arrays group source slices by mip. DDS groups mips by slice. - layout = ttpf.array_surface_layout(width, height, faces, levels, bs, 4, tile) - bw, bh = layout["block_w"], layout["block_h"] - offsets = { - mip["index"]: (mip["offset"], mip["tile_x"], mip["tile_y"], mip["slice_stride"]) - for mip in layout["mips"] - } - else: - # ASSET-568: the compact mip chain is computed in tools/tex_headers.py. Re-deriving - # first_tail here got NPOT chains and single-mip sub-tiles wrong; consume the layout. - bw, bh, grids, offsets = compact_dds_layout(width, height, fmt, levels, tile) - profile = ( - self.cal.get("entries", {}) - .get(Path(self.pool.path).name, {}) - .get(str(index), "base") - ) - span = self.pool.span(index, d["base"]) - if not span or d["base"] < self.edges[0]: - raise ValueError("Texture has no mapped allocation") - payload = bytearray() - for face in range(faces): - for i, (w, h) in enumerate(grids[:count]): - offset, x, y, slice_stride = offsets[i] - at = ( - addresses(tile, bs, bw, bh, w, h, x, y) - + d["base"] - + face * slice_stride - + offset - ) - if at.max() + bs > d["base"] + span: - raise ValueError("Texture crosses its allocation boundary") - payload.extend(self.surface(at, bs, profile)) - return ttpf.dds_bytes( - width, height, fmt, count, linear, bytes(payload), array_size=faces - ) - - -def compact_dds_layout(width, height, fmt, levels, tile): - """Block dimensions and per-mip (offset, x, y, slice_stride) from the measured compact layout. - - ASSET-568: the packed-tail boundary and standalone subresource offsets belong to - ``tools/tex_headers.py``; callers that re-derived them used the wrong grid on NPOT - chains and treated a single mip as a packed tail. - """ - layout = ttpf.surface_layout(width, height, fmt, levels, tile) - first_tail = layout["first_tail"] - stride = tile if first_tail < levels else 0 - offsets, dims = {}, [] - for mip in layout["mips"]: - i = mip["index"] - dims.append((mip["blocks_w"], mip["blocks_h"])) - if i < first_tail: - offsets[i] = (mip["offset"], 0, 0, stride) - else: - offsets[i] = (0, mip["tile_x"], mip["tile_y"], stride) - return layout["block_w"], layout["block_h"], dims, offsets - - -@lru_cache(maxsize=64) -def addresses(tile, bs, bw, bh, w, h, x0, y0): - x = np.arange(x0, x0 + w, dtype="int64")[None, :] - y = np.arange(y0, y0 + h, dtype="int64")[:, None] - off = ((y // bh) * ((w + bw - 1) // bw) + x // bw) * tile - patterns = ttpf.PATTERNS_64K if tile == 65536 else ttpf.PATTERNS_4K - for bit, axis in enumerate(patterns[bs.bit_length() - 1]): - if axis: - off |= (((x if axis > 0 else y) >> (abs(axis) - 1)) & 1) << bit - return off.ravel() - - -def scalar_bc4(symbols, table): - v = symbols.astype("int32") - d = unzig(v[:, 0]) % 256 - anc = np.arange(len(d)) - d - anc[d == 0] = -512 - delta = unzig(v[:, 2:4]) - while (mask := anc >= 0).any(): - parent = anc[mask] - delta[mask] += delta[parent] - anc[mask] = anc[parent] - for slot in np.unique(anc): - delta[anc == slot] += (128, 128) if slot == -512 else table[int(slot) + 256] - pairs = np.asarray(bcpack_tables.BC4_PAIR, dtype="uint64") - ranks = (pairs[:, 0] | (pairs[:, 1] << 3))[v[:, 4:]] - selectors = np.bitwise_or.reduce( - ranks << (6 * np.arange(8, dtype="uint64")), axis=1 - ) - ep = (delta % 256).astype("uint64") - return ((selectors << 16) | (ep[:, 1] << 8) | ep[:, 0]).astype("= 0).any(): - parent = ancestors[mask] - endpoints[mask] += endpoints[parent] - ancestors[mask] = ancestors[parent] - table = bcpack_tables.BC5_HISTORY_PROVISIONAL | bcpack_tables.BC5_HISTORY_CONFIRMED - for slot in np.unique(ancestors): - seed = (128,) * 4 if slot == -512 else table[int(slot) + 256] - endpoints[ancestors == slot] += np.asarray(seed).reshape(2, 2) - ep = (endpoints % 256).astype("uint64") - pairs = np.asarray(bcpack_tables.BC5_PAIR, dtype="uint64") - ranks = s[:, :, 4:].reshape(-1, 2, 2, 4).transpose(0, 2, 3, 1).reshape(-1, 2, 8) - values = (pairs[:, 0] | (pairs[:, 1] << 3))[ranks] - selectors = np.bitwise_or.reduce( - values << (6 * np.arange(8, dtype="uint64")), axis=2 - ) - return ( - ((selectors << 16) | (ep[:, :, 1] << 8) | ep[:, :, 0]).astype("= 0).any(): - parents = ancestors[mask] - ep[mask] += ep[parents] - ancestors[mask] = ancestors[parents] - for slot in np.unique(ancestors): - ep[ancestors == slot] += profile["endpoints"][str(slot)] - ep %= CAP - colors = np.asarray(profile["color"])[s[:, :, 10:12].reshape(-1, 4)] - quadrants = (colors[:, [0, 2, 1, 3], None] >> (2 * np.arange(4))) & 3 - ci = quadrants.reshape(-1, 2, 2, 2, 2).transpose(0, 1, 3, 2, 4).reshape(-1, 16) - alpha = np.asarray(profile["alpha"])[s[:, :, 3:7].reshape(-1, 8)] - pairs = (alpha[:, :, None] >> (3 * np.arange(2))) & 7 - ai = pairs.reshape(-1, 16)[ - :, [0, 1, 8, 9, 2, 3, 10, 11, 4, 5, 12, 13, 6, 7, 14, 15] - ] - rgb = (ep[:, ::4] << 11) | (ep[:, 1::4] << 5) | ep[:, 2::4] - cw = ci.astype("uint64") @ (1 << (2 * np.arange(16, dtype="uint64"))) - aw = ai.astype("uint64") @ (1 << (3 * np.arange(16, dtype="uint64"))) - low = (aw << 16) | ep[:, 3].astype("uint64") | (ep[:, 7].astype("uint64") << 8) - high = (cw << 32) | rgb[:, 0].astype("uint64") | (rgb[:, 1].astype("uint64") << 16) - return np.column_stack((low, high)).astype(" s_and_saveexec -> [s_cbranch_execz] -> body -> s_or exec (LLVM SI_IF / SI_END_CF) - ifelse ... s_xor saveexec mask, s_or_saveexec + s_xor exec for the else side (LLVM SI_ELSE) - cmpx s_mov save, exec -> v_cmpx -> [s_cbranch_execz] -> body -> s_mov exec, save - vccz v_cmp -> s_cbranch_vccz/vccnz over a body that every active lane runs (wave-uniform branch) - sif s_cmp -> s_cbranch_scc0/1 [-> s_branch over an else] (uniform branch) - sloop uniform counter loop closed by s_cbranch_scc1 (natural loop) - vloop per-lane trip counts: break mask, s_andn2 exec, s_cbranch_execnz (LLVM SI_LOOP) - irr two-entry cycle on uniform SCC branches (irreducible graph) - sccmask s_and/andn2/or/xor of VCC and EXEC -> s_cbranch_scc0/1 (SCC = whole mask != 0) - csel the same SCC read by s_cselect_b32 into a uniform SGPR -(vloop also closes some loops with s_cbranch_scc1 on the SCC of its s_andn2 exec.) -Bodies mix integer VALU and SALU ops with "probes": v11 = v11 * 33 + K at each site, so v11 records which sites -each lane ran, in which order and how often. v8/v9 carry data, v10 the uniform SGPRs. Immediates stay in the -inline-constant range so every instruction has a known size, and the listing carries `; encoding:` bytes of -those sizes (zeros: the translator reads only their length), which places the branch targets. - -Usage: - python -I tools/cf_diff.py [--programs N] [--seed S] [--wave 32|64|both] [--dispatch-loop] [--depth D] - python -I tools/cf_diff.py --self-test - python -I tools/cf_diff.py --spirv-val ... # also spirv-as + spirv-val each module - python -I tools/cf_diff.py --seed S --program K --show [--minimize] # print (and shrink) one program - -Exit code 0 when every program matches, 1 on a mismatch (case, seed, lane, the expected and actual words and the -listing; with --minimize also a reduced listing), 2 on harness errors or when every program was skipped (nothing was -compared). Skips are counted with reasons. -""" -import argparse -import gc -import os -import random -import shutil -import struct -import subprocess -import sys -import tempfile -import warnings - -HERE = os.path.dirname(os.path.abspath(__file__)) -sys.dont_write_bytecode = True -if HERE not in sys.path: - sys.path.insert(0, HERE) -SEM_DIR = os.path.join(os.path.dirname(HERE), "tests", "semantic") -if SEM_DIR not in sys.path: - sys.path.insert(0, SEM_DIR) - -import cf_ref # noqa: E402 -import cpu_ref # noqa: E402 -# The translator is imported where it is used (run_case), not here: rdna2spirv.py takes seconds to compile, and -# with dont_write_bytecode the compiled code is never cached, so --help and a usage error would wait for it on -# every run. -from spirv_wave_interp import UnsupportedConstruct, run_wave # noqa: E402 - -STUB_DXBC = b"DXBC" + bytes(24) + struct.pack(" 0: - body.extend(g.block(0)) - body.append(g.probe()) - return body - - -class Emitter: - """Expands a program tree into tab-less instruction lines with sizes, labels and symbolic branches.""" - - def __init__(self, wave): - self.wave = wave - self.items = [] # ("ins", text) | ("label", name) | ("br", mnemonic, label) - self.n_labels = 0 - self.depth = 0 - - # register names ------------------------------------------------------------------------------------------- - def exec_(self): - return "exec" if self.wave == 64 else "exec_lo" - - def vcc(self): - return "vcc" if self.wave == 64 else "vcc_lo" - - def b(self): - return "b64" if self.wave == 64 else "b32" - - def sreg(self, base): - """A mask SGPR for the current nesting depth (an aligned pair in wave64).""" - n = base + 2 * self.depth - return f"s[{n}:{n + 1}]" if self.wave == 64 else f"s{n}" - - def label(self): - self.n_labels += 1 - return f"L{self.n_labels}" - - def ins(self, text): - self.items.append(("ins", text)) - - def br(self, mnemonic, label): - self.items.append(("br", mnemonic, label)) - - def place(self, label): - self.items.append(("label", label)) - - def vcmp(self, c, dst=None): - cc, ty, k, v = c - self.ins(f"v_cmp_{cc}_{ty}_e32 {dst or self.vcc()}, {k}, v{v}") - - # program ------------------------------------------------------------------------------------------------------ - def program(self, body): - if self.wave == 64: - self.ins("v_mbcnt_lo_u32_b32 v0, -1, 0") - self.ins("v_mbcnt_hi_u32_b32 v0, -1, v0") - else: - self.ins("v_mbcnt_lo_u32_b32 v0, -1, 0") - self.ins("v_and_b32 v1, 7, v0") - self.ins("v_lshrrev_b32 v2, 2, v0") - self.ins("v_mul_lo_u32 v3, v0, 5") - self.ins("v_and_b32 v3, 15, v3") - self.ins("v_xor_b32 v8, 9, v0") - self.ins("v_mov_b32 v9, 0") - self.ins("v_mov_b32 v11, 1") - for i, s in enumerate(SREGS): - self.ins(f"s_mov_b32 s{s}, {(3, 5, 0, 12)[i]}") - self.nodes(body) - self.ins(f"v_mov_b32 v10, s{SREGS[0]}") - for s in SREGS[1:]: - self.ins("v_lshlrev_b32 v10, 3, v10") - self.ins(f"v_xor_b32 v10, s{s}, v10") - self.ins("exp mrt0 v8, v9, v10, v11 done vm") - self.ins("s_endpgm") - - def nodes(self, nodes): - for n in nodes: - self.node(n) - - def node(self, n): - kind = n[0] - w = self.b() - ex = self.exec_() - if kind == "op": - self.ins(n[1]) - elif kind == "probe": - self.ins("v_mul_lo_u32 v11, v11, 33") - self.ins(f"v_add_nc_u32 v11, {n[1]}, v11") - elif kind == "cnd": - _, d, s, c = n - self.vcmp(c) - self.ins(f"v_cndmask_b32_e32 v{d}, 7, v{s}, {self.vcc()}") - elif kind == "if": - _, c, skip, body = n - save, end = self.sreg(20), self.label() - self.vcmp(c) - self.ins(f"s_and_saveexec_{w} {save}, {self.vcc()}") - if skip: - self.br("s_cbranch_execz", end) - self.depth += 1 - self.nodes(body) - self.depth -= 1 - self.place(end) - self.ins(f"s_or_{w} {ex}, {ex}, {save}") - elif kind == "ifelse": - _, c, then, other = n - save, els, end = self.sreg(20), self.label(), self.label() - self.vcmp(c) - self.ins(f"s_and_saveexec_{w} {save}, {self.vcc()}") - self.ins(f"s_xor_{w} {save}, {ex}, {save}") - self.br("s_cbranch_execz", els) - self.depth += 1 - self.nodes(then) - self.depth -= 1 - self.place(els) - self.ins(f"s_or_saveexec_{w} {save}, {save}") - self.ins(f"s_xor_{w} {ex}, {ex}, {save}") - self.br("s_cbranch_execz", end) - self.depth += 1 - self.nodes(other) - self.depth -= 1 - self.place(end) - self.ins(f"s_or_{w} {ex}, {ex}, {save}") - elif kind == "cmpx": - _, (cc, ty, k, v), skip, body = n - save, end = self.sreg(20), self.label() - self.ins(f"s_mov_{w} {save}, {ex}") - self.ins(f"v_cmpx_{cc}_{ty}_e32 {k}, v{v}") - if skip: - self.br("s_cbranch_execz", end) - self.depth += 1 - self.nodes(body) - self.depth -= 1 - self.place(end) - self.ins(f"s_mov_{w} {ex}, {save}") - elif kind == "saveexec": - _, c, op_name, skip_br, body = n - save, end = self.sreg(20), self.label() - self.vcmp(c) - self.ins(f"s_{op_name}_saveexec_{w} {save}, {self.vcc()}") - if skip_br is not None: - self.br(skip_br, end) - self.depth += 1 - self.nodes(body) - self.depth -= 1 - self.place(end) - self.ins(f"s_mov_{w} {ex}, {save}") - elif kind == "vccz": - _, c, mnemonic, body = n - end = self.label() - self.vcmp(c) - self.br(mnemonic, end) - self.nodes(body) - self.place(end) - elif kind == "sif": - _, (cc, sr, k), on_one, then, other = n - els, end = self.label(), self.label() - self.ins(f"s_cmp_{SCALAR_CC.get(cc, cc)}_u32 s{sr}, {k}") - self.br("s_cbranch_scc0" if on_one else "s_cbranch_scc1", els if other else end) - self.nodes(then) - if other: - self.br("s_branch", end) - self.place(els) - self.nodes(other) - self.place(end) - elif kind == "sloop": - _, trips, body = n - ctr, head = 14 + self.depth, self.label() - self.ins(f"s_mov_b32 s{ctr}, 0") - self.place(head) - self.depth += 1 - self.nodes(body) - self.depth -= 1 - self.ins(f"s_add_u32 s{ctr}, s{ctr}, 1") - self.ins(f"s_cmp_lt_u32 s{ctr}, {trips}") - self.br("s_cbranch_scc1", head) - elif kind == "sccmask": - # SCC of a mask op is (whole result != 0): one value for the wave, like a vote. - _, c, logic, mnemonic, body = n - tmp, end = self.sreg(50), self.label() - self.vcmp(c) - self.ins(f"s_{logic}_{w} {tmp}, {self.vcc()}, {ex}") - self.br(mnemonic, end) - self.nodes(body) - self.place(end) - elif kind == "csel": - _, c, logic, sr = n - self.vcmp(c) - self.ins(f"s_{logic}_{w} {self.sreg(50)}, {self.vcc()}, {ex}") - self.ins(f"s_cselect_b32 s{sr}, s{sr}, 17") - elif kind == "vloop": - _, (src, mask, scc_exit), brk, body = n - it, lim, brk_mask, head = 4 + self.depth, 30 + self.depth, self.sreg(40), self.label() - self.ins(f"v_and_b32 v{lim}, {mask}, v{src}") - self.ins(f"v_add_nc_u32 v{lim}, 1, v{lim}") - self.ins(f"v_mov_b32 v{it}, 0") - self.ins(f"s_mov_{w} {brk_mask}, 0") - self.place(head) - self.depth += 1 - self.nodes(body) - self.depth -= 1 - if brk is not None: - # An early exit (SI_IF_BREAK): lanes meeting `brk` join the break mask for this iteration. - self.vcmp(brk) - self.ins(f"s_or_{w} {brk_mask}, {self.vcc()}, {brk_mask}") - self.ins(f"v_add_nc_u32 v{it}, 1, v{it}") - self.ins(f"v_cmp_ge_u32_e32 {self.vcc()}, v{it}, v{lim}") - self.ins(f"s_or_{w} {brk_mask}, {self.vcc()}, {brk_mask}") - self.ins(f"s_andn2_{w} {ex}, {ex}, {brk_mask}") - # Loop again while any lane is left: EXECNZ, or SCC of the s_andn2 (= new EXEC != 0). - self.br("s_cbranch_scc1" if scc_exit else "s_cbranch_execnz", head) - self.ins(f"s_or_{w} {ex}, {ex}, {brk_mask}") - elif kind == "irr": - _, (sr, k), part_a, part_b = n - ctr, a_lbl, b_lbl, end = 14 + self.depth, self.label(), self.label(), self.label() - self.ins(f"s_mov_b32 s{ctr}, 0") - self.ins(f"s_cmp_lt_u32 s{sr}, {k}") - self.br("s_cbranch_scc0", b_lbl) - self.place(a_lbl) - self.depth += 1 - self.nodes(part_a) - self.ins(f"s_add_u32 s{ctr}, s{ctr}, 1") - self.ins(f"s_cmp_lt_u32 s{ctr}, 4") - self.br("s_cbranch_scc0", end) - self.place(b_lbl) - self.nodes(part_b) - self.depth -= 1 - self.ins(f"s_add_u32 s{ctr}, s{ctr}, 2") - self.ins(f"s_cmp_lt_u32 s{ctr}, 7") - self.br("s_cbranch_scc1", a_lbl) - self.place(end) - else: - raise ValueError(f"unknown node {kind}") - - def assemble(self): - """Lines with real branch offsets: [(text, size_in_bytes)].""" - pc, where, sized = 0, {}, [] - for it in self.items: - if it[0] == "label": - where[it[1]] = pc - continue - size = 4 if it[0] == "br" else _size(it[1]) - sized.append((it, pc, size)) - pc += size - out = [] - for it, at, size in sized: - if it[0] == "br": - off = (where[it[2]] - (at + 4)) // 4 - out.append((f"{it[1]} {off}", size)) - else: - out.append((it[1], size)) - return out - - -def _size(text): - op = text.split()[0] - if op == "exp" or op.endswith("_e64") or op in VOP3: - return 8 - return 4 - - -def listing_text(lines, name): - out = [f"; {name} code 0x0..0x{sum(s for _, s in lines):x}"] - for text, size in lines: - out.append("\t" + text + " ; encoding: [" + ",".join(["0x00"] * size) + "]") - return "\n".join(out) + "\n" - - -def build(body, wave): - e = Emitter(wave) - e.program(body) - return e.assemble() - - -# ---- one comparison ------------------------------------------------------------------------------------------ - -def run_case(name, body, wave, structured=True): - """Returns (status, detail): status in {"match", "mismatch", "skip"}.""" - import rdna2spirv # here, not at the top of the file: see the note above the imports - lines = build(body, wave) - text = listing_text(lines, name) - with tempfile.TemporaryDirectory(prefix="cf-diff-") as tmp: - dis = os.path.join(tmp, "disasm") - os.mkdir(dis) - path = os.path.join(dis, name + ".s") - with open(path, "w", encoding="utf-8", newline="\n") as f: - f.write(text) - with open(os.path.join(tmp, name + ".dxbc"), "wb") as f: - f.write(STUB_DXBC) - try: - ref = cf_ref.run(path, wave=wave) - except cpu_ref.CpuRefError as e: - return ("skip", f"cf_ref: {e}") - old = rdna2spirv.STRUCTURED - rdna2spirv.STRUCTURED = structured - try: - with warnings.catch_warnings(): - warnings.simplefilter("ignore", ResourceWarning) - spv = rdna2spirv.translate(path) - gen = rdna2spirv.translate.last_gen - gc.collect() - except rdna2spirv.Unsupported as e: - return ("skip", f"translator unsupported: {e}") - finally: - rdna2spirv.STRUCTURED = old - if SPIRV_VAL: - bad = _spirv_val(spv, tmp) - if bad: - return ("mismatch", f"spirv-val: {bad}") - if bool(getattr(gen, "wave64", False)) != (wave == 64): - return ("mismatch", f"translator detected wave{64 if gen.wave64 else 32}, the program is wave{wave}") - try: - got = run_wave(spv, wave=wave)["outputs"] - except UnsupportedConstruct as e: - return ("skip", f"wave interp: {e}") - for lane in range(wave): - want = ref["exports"].get(lane) - have = (got[lane] or {}).get("%out_mrt0") if got[lane] is not None else None - if want == have: - continue - if want is None or have is None: - return ("mismatch", f"lane {lane}: export {'missing' if have is None else 'unexpected'} in the " - f"translation (reference {_words(want)}, translation {_words(have)})") - bad = [i for i in range(4) if want[i] != have[i]] - what = {0: "v8 (data)", 1: "v9 (data)", 2: "v10 (uniform SGPRs)", 3: "v11 (path probes)"} - return ("mismatch", f"lane {lane}: {', '.join(what[i] for i in bad)} differ: reference {_words(want)}, " - f"translation {_words(have)}") - return ("match", "") - - -SPIRV_VAL = False # --spirv-val: also assemble and validate every translation (spirv-as/spirv-val on PATH) - - -def _spirv_val(spv, tmp): - """First spirv-as/spirv-val error for the module (Vulkan 1.2, as tests/conftest.py), or None.""" - sa, sv = os.path.join(tmp, "m.spvasm"), os.path.join(tmp, "m.spv") - with open(sa, "w", encoding="utf-8", newline="\n") as f: - f.write(spv) - for cmd in (["spirv-as", sa, "-o", sv, "--target-env", "vulkan1.2"], - ["spirv-val", "--target-env", "vulkan1.2", sv]): - r = subprocess.run(cmd, capture_output=True, text=True) - if r.returncode: - return (cmd[0] + ": " + (r.stderr or r.stdout).strip().splitlines()[0]) if (r.stderr or r.stdout) \ - else f"{cmd[0]} exited with {r.returncode}" - return None - - -def _words(w): - return "none" if w is None else "(" + ", ".join(f"0x{x:08x}" for x in w) + ")" - - -# ---- reduction ----------------------------------------------------------------------------------------------- - -def _variants(body): - """Smaller programs: each node deleted, and each compound node replaced by one of its child lists.""" - for i, n in enumerate(body): - yield body[:i] + body[i + 1:] - kids = [x for x in n[1:] if isinstance(x, list)] - for k in kids: - yield body[:i] + k + body[i + 1:] - for j, x in enumerate(n): - if isinstance(x, list): - for v in _variants(x): - m = list(n) - m[j] = v - yield body[:i] + [tuple(m)] + body[i + 1:] - - -def minimize(body, wave, structured=True): - """Greedy reduction that keeps a mismatch.""" - changed = True - while changed: - changed = False - for cand in _variants(body): - status, _ = run_case("ps_cf_min", cand, wave, structured) - if status == "mismatch": - body, changed = cand, True - break - return body - - -# ---- suite --------------------------------------------------------------------------------------------------- - -def program_for(seed, index, wave, depth): - rng = random.Random(f"{seed}:{index}:{wave}") - return generate(rng, wave, max_depth=depth, budget=rng.randrange(4, 13)) - - -def run_suite(programs, seed, waves, structured=True, depth=3, limit=None): - counts = {"pass": 0, "mismatch": 0, "skip": {}, "harness-error": 0} - failures = [] - total = programs if limit is None else min(programs, limit) - for i in range(total): - for wave in waves: - name = f"ps_cf_{i:04d}_w{wave}" - body = program_for(seed, i, wave, depth) - try: - status, detail = run_case(name, body, wave, structured) - except Exception as e: # noqa: BLE001 - harness bugs must be loud - counts["harness-error"] += 1 - failures.append((i, wave, f"harness error {type(e).__name__}: {e}")) - continue - if status == "match": - counts["pass"] += 1 - elif status == "mismatch": - counts["mismatch"] += 1 - failures.append((i, wave, detail)) - else: - counts["skip"][detail] = counts["skip"].get(detail, 0) + 1 - return counts, failures - - -def self_test(): - """Harness canaries: a program must match, a sabotaged reference must be caught, the interpreter must - reconverge after a divergent branch.""" - ok = True - body = [("if", ("gt", "u32", 4, 0), True, [("probe", 5), ("op", "v_add_nc_u32 v9, 1, v9")]), ("probe", 6)] - for wave in (32, 64): - status, detail = run_case("ps_canary_ok", body, wave) - if status != "match": - print(f"canary FAILED (wave{wave}): hand-written if did not match ({status}: {detail})") - ok = False - # The reference must be able to disagree: drop the s_or that restores EXEC and the lanes > 4 never export. - e = Emitter(32) - e.program(body) - e.items = [it for it in e.items if not (it[0] == "ins" and it[1].startswith("s_or_b32 exec_lo"))] - with tempfile.TemporaryDirectory(prefix="cf-diff-") as tmp: - p = os.path.join(tmp, "c.s") - with open(p, "w", encoding="utf-8", newline="\n") as f: - f.write(listing_text(e.assemble(), "ps_canary_bad")) - if len(cf_ref.run(p, wave=32)["exports"]) != 4: # 4 > lane: lanes 0-3 stay on - print("canary FAILED: the reference did not drop lanes whose EXEC was never restored") - ok = False - # Divergent loop + vote: every lane must leave the loop with its own trip count. - body = [("vloop", (0, 3, False), None, [("probe", 9), ("vccz", ("eq", "u32", 0, 1), "s_cbranch_vccz", - [("op", "s_add_u32 s10, s10, 1")])])] - for wave in (32, 64): - status, detail = run_case("ps_canary_loop", body, wave) - if status != "match": - print(f"canary FAILED (wave{wave}): divergent loop did not match ({status}: {detail})") - ok = False - if ok: - print("canaries: match ok, sabotaged reference detected, divergent loop reconverges") - return ok - - -def main(argv=None): - ap = argparse.ArgumentParser(description="FUZZ-8: control-flow/EXEC differential fuzzer.") - ap.add_argument("--programs", type=int, default=200) - ap.add_argument("--seed", type=int, default=1) - ap.add_argument("--wave", choices=("32", "64", "both"), default="both") - ap.add_argument("--depth", type=int, default=3, help="maximum nesting depth") - ap.add_argument("--dispatch-loop", action="store_true", help="translate in the dispatch-loop form") - ap.add_argument("--program", type=int, help="only this program index (with --show / --minimize)") - ap.add_argument("--show", action="store_true", help="print the listing of --program") - ap.add_argument("--minimize", action="store_true", help="reduce a mismatching program before printing it") - ap.add_argument("--spirv-val", action="store_true", - help="also run spirv-as and spirv-val on every translation (a failure counts as a mismatch)") - ap.add_argument("--self-test", action="store_true") - if argv is None: - argv = sys.argv[1:] - if not argv: - ap.error("no arguments given; pass --help for the available options") - a = ap.parse_args(argv) - if a.show and a.program is None: - ap.error("--show requires --program") - if a.programs < 1: - ap.error("--programs must be at least 1") - if a.spirv_val: - missing = [t for t in ("spirv-as", "spirv-val") if not shutil.which(t)] - if missing: - print(f"--spirv-val needs {' and '.join(missing)} on PATH") - return 2 - global SPIRV_VAL - SPIRV_VAL = True - if a.self_test: - return 0 if self_test() else 1 - waves = (32, 64) if a.wave == "both" else (int(a.wave),) - structured = not a.dispatch_loop - if a.program is not None: - rc = 0 - matched = 0 - for wave in waves: - body = program_for(a.seed, a.program, wave, a.depth) - status, detail = run_case(f"ps_cf_{a.program:04d}_w{wave}", body, wave, structured) - print(f"program {a.program} wave{wave}: {status} {detail}") - matched += status == "match" - if status == "mismatch": - rc = 1 - if a.minimize: - body = minimize(body, wave, structured) - print("reduced:", run_case("ps_cf_min", body, wave, structured)[1]) - if a.show or a.minimize: - print(listing_text(build(body, wave), f"ps_cf_{a.program:04d}_w{wave}")) - if not rc and not matched: # same order as the suite: a mismatch (1) outranks "nothing was compared" (2) - print("no program ran: every one was skipped") - return 2 - return rc - counts, failures = run_suite(a.programs, a.seed, waves, structured, a.depth) - skips = sum(counts["skip"].values()) - form = "dispatch loop" if a.dispatch_loop else "structured" - print(f"{a.programs} programs x wave {'/'.join(map(str, waves))} (seed {a.seed}, {form}): " - f"{counts['pass']} pass, {counts['mismatch']} mismatch, {skips} skipped, " - f"{counts['harness-error']} harness errors") - for reason, n in sorted(counts["skip"].items(), key=lambda kv: -kv[1]): - print(f" skip x{n}: {reason}") - for i, wave, detail in failures[:10]: - print(f" program {i} wave{wave}: {detail}") - if len(failures) > 10: - print(f" ... {len(failures) - 10} more") - if counts["harness-error"]: - return 2 - if counts["mismatch"]: - return 1 - if not counts["pass"]: - print("no program ran: every one was skipped") - return 2 - return 0 - - -if __name__ == "__main__": - try: # a redirected stdout is strict ANSI code page under -I; write '?' for what it cannot encode - sys.stdout.reconfigure(errors="replace") - except (AttributeError, ValueError, OSError): - pass - sys.exit(main()) diff --git a/tools/cf_ref.py b/tools/cf_ref.py deleted file mode 100644 index c7d593df0..000000000 --- a/tools/cf_ref.py +++ /dev/null @@ -1,377 +0,0 @@ -"""Wave-level CPU reference for RDNA2 control flow (standard library only). - -tools/cpu_ref.py executes straight-line code. This module extends its Machine with what control flow needs and -nothing else: branches, vector and scalar compares, `v_cmpx`, the saveexec family, 64-bit mask moves and the -export. It is the reference side of tools/cf_diff.py and, like cpu_ref, is a model written from the ISA document -(AMD "RDNA 2" Instruction Set Architecture, sections 3 (program flow), 4.4 (EXEC), 6 (SOP*), 8 (VOPC)), not -from the translator. - -Model: - * One wave of 32 or 64 lanes, all in one Machine (cpu_ref's 64-lane mode). A wave32 program runs with - EXEC[63:32] = 0, so lanes 32-63 never execute, and its masks (VCC, EXEC, compare results) are 32 bits. - * PC is a byte offset. A branch target is next_pc + 4 * simm16 (sign-extended), as the hardware computes it. - The listing must carry `; encoding:` bytes so instruction sizes (and so branch targets) are known. - * Compares write 0 for inactive lanes (VOPC behaviour). On RDNA2 `v_cmpx_*` writes EXEC only, never VCC or - an SGPR; EXEC = EXEC & compare. - * SCC: s_cmp_* set it to the comparison; s_and/or/xor/andn2/orn2/nand/nor/xnor set it to result != 0; - s_*_saveexec set it to (new EXEC != 0); s_add_u32/s_sub_u32 to the carry/borrow; s_add_i32/s_sub_i32 to - signed overflow; s_cselect reads it and leaves it alone. - * In wave32 mode VCCZ and EXECZ test the low 32 bits. - * `exp` records, for every lane whose EXEC bit is set, the four source VGPRs. Lanes that are off at the export - write nothing, which is the hardware's per-lane valid mask for an `exp ... done vm`. - -Everything else (memory, LDS, images, cross-lane ops, 16-bit and float ops beyond cpu_ref's) raises -cpu_ref.Unsupported with the mnemonic and PC. - -API: - run(listing_path, wave=32 | 64, max_steps=...) -> { - "wave": 32 | 64, - "exports": {lane: (w0, w1, w2, w3)}, # lanes that were active at the export - "exec": final EXEC, "vcc": final VCC, "scc": final SCC, - "sgpr": {index: u32}, "steps": int, - } -""" -import os -import sys - -HERE = os.path.dirname(os.path.abspath(__file__)) -if HERE not in sys.path: - sys.path.insert(0, HERE) - -import cpu_ref # noqa: E402 -from shader_ir import parse_file # noqa: E402 - -MASK32 = 0xFFFFFFFF -MASK64 = 0xFFFFFFFFFFFFFFFF -Unsupported = cpu_ref.Unsupported -ProgramError = cpu_ref.ProgramError - -_CMP = { - "eq": lambda a, b: a == b, "ne": lambda a, b: a != b, "lg": lambda a, b: a != b, - "lt": lambda a, b: a < b, "le": lambda a, b: a <= b, "gt": lambda a, b: a > b, "ge": lambda a, b: a >= b, -} -_SOP2_LOGIC = { - "and": lambda a, b, m: a & b, "or": lambda a, b, m: a | b, "xor": lambda a, b, m: a ^ b, - "andn2": lambda a, b, m: a & ~b & m, "orn2": lambda a, b, m: (a | ~b) & m, - "nand": lambda a, b, m: ~(a & b) & m, "nor": lambda a, b, m: ~(a | b) & m, "xnor": lambda a, b, m: ~(a ^ b) & m, -} -# s__saveexec_b32/b64: D = EXEC; EXEC = f(S0, EXEC). (ISA section 6.4, SOP1.) -_SAVEEXEC = { - "and": lambda s, e, m: s & e, "or": lambda s, e, m: s | e, "xor": lambda s, e, m: s ^ e, - "andn2": lambda s, e, m: s & ~e & m, "orn2": lambda s, e, m: (s | ~e) & m, - "nand": lambda s, e, m: ~(s & e) & m, "nor": lambda s, e, m: ~(s | e) & m, "xnor": lambda s, e, m: ~(s ^ e) & m, - "andn1": lambda s, e, m: ~s & e & m, "orn1": lambda s, e, m: (~s | e) & m, -} -_BRANCHES = {"s_branch", "s_cbranch_scc0", "s_cbranch_scc1", "s_cbranch_vccz", "s_cbranch_vccnz", - "s_cbranch_execz", "s_cbranch_execnz"} - - -def _signed(v, bits=32): - v &= (1 << bits) - 1 - return v - (1 << bits) if v >> (bits - 1) else v - - -class WaveMachine(cpu_ref.Machine): - def __init__(self, info, wave=32, max_steps=200000): - if wave not in (32, 64): - raise ValueError("wave must be 32 or 64") - super().__init__(info, {"lanes": 64, "exec": (1 << wave) - 1, "max_steps": max_steps}) - self.wave = wave - self.wmask = (1 << wave) - 1 - self.exports = {} - self.by_pc = {} - for i, ins in enumerate(self.insns): - if not ins.get("enc"): - raise ProgramError(f"instruction at index {i} ({ins['op']}) has no encoding bytes; " - "branch targets need instruction sizes") - self.by_pc[ins["pc"]] = i - - # -- masks --------------------------------------------------------------------------------------------------- - def _read_mask(self, arg): - """A wave-sized lane mask from an SGPR (pair), VCC, EXEC or an inline constant.""" - k = arg["k"] - if k == "sgpr": - lo = self.sgpr.get(arg["r"], 0) - if arg.get("n", 1) >= 2: - return ((self.sgpr.get(arg["r"] + 1, 0) << 32) | lo) & self.wmask - return lo & self.wmask if self.wave == 32 else lo - if k == "special": - t = arg["t"] - if t == "vcc": - return self.vcc & self.wmask - if t == "vcc_lo": - return self.vcc & MASK32 - if t == "vcc_hi": - return (self.vcc >> 32) & MASK32 - if t == "exec": - return self.exec & self.wmask - if t == "exec_lo": - return self.exec & MASK32 - if t == "exec_hi": - return 0 if self.wave == 32 else (self.exec >> 32) & MASK32 - if t == "null": - return 0 - if k == "imm": - return arg["v"] & self.wmask - raise Unsupported(arg.get("t", k), self.pc, "mask operand is not modelled") - - def _write_mask(self, dst, value): - k = dst["k"] - if k == "sgpr": - self.sgpr[dst["r"]] = value & MASK32 - if dst.get("n", 1) >= 2: - self.sgpr[dst["r"] + 1] = (value >> 32) & MASK32 - return - if k == "special": - t = dst["t"] - if t == "vcc": - self.vcc = (value & MASK64) if self.wave == 64 else ((self.vcc & ~MASK32 & MASK64) | (value & MASK32)) - return - if t == "vcc_lo": - self.vcc = (self.vcc & ~MASK32 & MASK64) | (value & MASK32) - return - if t == "vcc_hi": - self.vcc = (self.vcc & MASK32) | ((value & MASK32) << 32) - return - if t == "exec": - self.exec = value & MASK64 - return - if t == "exec_lo": - self.exec = (self.exec & ~MASK32 & MASK64) | (value & MASK32) - return - if t == "exec_hi": - if self.wave == 64: - self.exec = (self.exec & MASK32) | ((value & MASK32) << 32) - return - if t == "null": - return - raise Unsupported(dst.get("t", k), self.pc, "mask destination is not modelled") - - def _wide(self, base): - return base.endswith("_b64") - - def _check_width(self, base, op): - if self._wide(base) != (self.wave == 64): - raise Unsupported(op, self.pc, f"{'64' if self._wide(base) else '32'}-bit mask op in a wave{self.wave} " - "program is not modelled") - - def _active_lanes(self): - m = self.exec & self.wmask - return [i for i in range(self.wave) if (m >> i) & 1] - - def _read_special(self, name): - if name == "exec_hi" and self.wave == 32: - return 0 - return super()._read_special(name) - - def _write_scalar_dst(self, dst, value): - if dst.get("k") == "special" and dst.get("t") == "exec_hi" and self.wave == 32: - return - super()._write_scalar_dst(dst, value) - - # -- execution ----------------------------------------------------------------------------------------------- - def run(self): - if not self.insns: - raise ProgramError("listing has no instructions") - i = 0 - while not self.halted: - if i >= len(self.insns): - raise ProgramError("execution ran past the last instruction without s_endpgm") - if self.steps >= self.max_steps: - raise ProgramError(f"step limit {self.max_steps} reached at pc 0x{self.insns[i]['pc']:x}") - ins = self.insns[i] - self.steps += 1 - self.pc = ins["pc"] - self.next_pc = ins["pc"] + len(ins["enc"]) // 2 - target = self.step(ins) - nxt = self.next_pc if target is None else target - if not self.halted: - if nxt not in self.by_pc: - raise ProgramError(f"branch from pc 0x{self.pc:x} to 0x{nxt:x}, which is not an instruction") - i = self.by_pc[nxt] - return { - "wave": self.wave, - "exports": dict(self.exports), - "exec": self.exec & self.wmask, "vcc": self.vcc & self.wmask, "scc": self.scc, - "sgpr": dict(sorted(self.sgpr.items())), "steps": self.steps, - } - - def step(self, ins): - op = ins["op"] - base = cpu_ref.base_op(op) - a = ins["args"] - if op == "exp": - return self._export(ins) - mods = ins.get("mods") or [] - if mods and base not in cpu_ref.FLOAT_OPS: - raise Unsupported(op, self.pc, f"modifier(s) {', '.join(mods)} are not modelled") - if base in _BRANCHES: - return self._branch(base, a) - if base in ("v_add_nc_u32", "v_sub_nc_u32", "v_subrev_nc_u32", "v_mul_lo_u32"): - self._expect(ins, 3) - for lane in self._active_lanes(): - x, y = self._int_src(a[1], lane), self._int_src(a[2], lane) - r = {"v_add_nc_u32": x + y, "v_sub_nc_u32": x - y, "v_subrev_nc_u32": y - x, - "v_mul_lo_u32": x * y}[base] - self._write_vgpr(a[0], lane, r) - return None - if base in ("v_mbcnt_lo_u32_b32", "v_mbcnt_hi_u32_b32"): - self._expect(ins, 3) - for lane in self._active_lanes(): - m = self._int_src(a[1], lane) - if base == "v_mbcnt_lo_u32_b32": - below = m & ((1 << min(lane, 32)) - 1) - else: - below = m & ((1 << max(lane - 32, 0)) - 1) - self._write_vgpr(a[0], lane, below.bit_count() + self._int_src(a[2], lane)) - return None - if base.startswith(("v_cmp_", "v_cmpx_")): - return self._vcmp(ins, base) - if base.startswith("s_cmp_"): - self._expect(ins, 2) - cc, _, ty = base[len("s_cmp_"):].partition("_") - if cc not in _CMP or ty not in ("u32", "i32"): - raise Unsupported(op, self.pc, "compare is not modelled") - x, y = self._int_src(a[0], 0, scalar=True), self._int_src(a[1], 0, scalar=True) - if ty == "i32": - x, y = _signed(x), _signed(y) - self.scc = 1 if _CMP[cc](x, y) else 0 - return None - if base.endswith("_saveexec_b32") or base.endswith("_saveexec_b64"): - self._check_width(base, op) - self._expect(ins, 2) - kind = base[2:].split("_saveexec")[0] - if kind not in _SAVEEXEC: - raise Unsupported(op, self.pc, "saveexec variant is not modelled") - s0 = self._read_mask(a[1]) - old = self.exec & self.wmask - self._write_mask(a[0], old) - new = _SAVEEXEC[kind](s0, old, self.wmask) & self.wmask - self.exec = new if self.wave == 64 else (self.exec & ~MASK32) | new - self.scc = 1 if new else 0 - return None - parts = base.split("_") - if len(parts) == 3 and parts[0] == "s" and parts[1] in _SOP2_LOGIC and parts[2] in ("b32", "b64"): - self._expect(ins, 3) - mask_op = self._touches_mask(a) - if parts[2] == "b64" or mask_op: - if parts[2] == "b64" or any(x["k"] == "special" and x["t"] in ("exec", "vcc") for x in a): - self._check_width(base, op) - mask = MASK64 if parts[2] == "b64" else MASK32 - x, y = self._read_mask(a[1]) & mask, self._read_mask(a[2]) & mask - r = _SOP2_LOGIC[parts[1]](x, y, mask) & mask - self._write_mask(a[0], r) - else: - x, y = self._int_src(a[1], 0, scalar=True), self._int_src(a[2], 0, scalar=True) - r = _SOP2_LOGIC[parts[1]](x, y, MASK32) & MASK32 - self._write_scalar_dst(a[0], r) - self.scc = 1 if r else 0 - return None - if base == "s_mov_b64": - if self.wave != 64: - raise Unsupported(op, self.pc, "s_mov_b64 in a wave32 program is not modelled") - self._expect(ins, 2) - src = a[1] - v = (src["v"] & MASK64) if src["k"] == "imm" else self._read_mask(src) - self._write_mask(a[0], v) - return None - if base == "s_mov_b32" and self._touches_mask(a): - if any(x["k"] == "special" and x["t"] in ("exec", "vcc") for x in a): - self._check_width(base, op) - self._expect(ins, 2) - v = a[1]["v"] & MASK32 if a[1]["k"] == "imm" else self._read_mask(a[1]) & MASK32 - self._write_mask(a[0], v) - return None - if base in ("s_sub_u32", "s_add_i32", "s_sub_i32"): - self._expect(ins, 3) - x, y = self._int_src(a[1], 0, scalar=True), self._int_src(a[2], 0, scalar=True) - if base == "s_sub_u32": - r, self.scc = (x - y) & MASK32, 1 if y > x else 0 - else: - r = (x + y if base == "s_add_i32" else x - y) & MASK32 - sx, sy, sr = _signed(x), _signed(y), _signed(r) - if base == "s_add_i32": - self.scc = 1 if (sx >= 0) == (sy >= 0) and (sr >= 0) != (sx >= 0) else 0 - else: - self.scc = 1 if (sx >= 0) != (sy >= 0) and (sr >= 0) != (sx >= 0) else 0 - self._write_scalar_dst(a[0], r) - return None - if base == "s_cselect_b32": - self._expect(ins, 3) - x, y = self._int_src(a[1], 0, scalar=True), self._int_src(a[2], 0, scalar=True) - self._write_scalar_dst(a[0], x if self.scc else y) - return None - if base == "v_cndmask_b32" and self.wave == 32 and len(a) == 3: - # VOP2 form: the implicit condition is VCC_LO in wave32 (cpu_ref models a wave64 VCC). - for lane in self._active_lanes(): - bit = (self.vcc >> lane) & 1 - self._write_vgpr(a[0], lane, self._int_src(a[2], lane) if bit else self._int_src(a[1], lane)) - return None - super().step(ins) - return None - - @staticmethod - def _touches_mask(args): - return any(x["k"] == "special" and x["t"] in ("exec", "exec_lo", "exec_hi", "vcc", "vcc_lo", "vcc_hi") - for x in args) - - def _branch(self, base, a): - if len(a) != 1 or a[0]["k"] not in ("imm", "label"): - raise Unsupported(base, self.pc, "branch operand is not an immediate offset") - off = a[0]["v"] if a[0]["k"] == "imm" else None - if off is None: - raise Unsupported(base, self.pc, "symbolic branch labels are not modelled") - target = self.next_pc + 4 * _signed(off, 16) - cond = { - "s_branch": True, - "s_cbranch_scc0": self.scc == 0, "s_cbranch_scc1": self.scc == 1, - "s_cbranch_vccz": (self.vcc & self.wmask) == 0, "s_cbranch_vccnz": (self.vcc & self.wmask) != 0, - "s_cbranch_execz": (self.exec & self.wmask) == 0, "s_cbranch_execnz": (self.exec & self.wmask) != 0, - }[base] - return target if cond else None - - def _export(self, ins): - a = ins["args"] - bad_mods = [m for m in (ins.get("mods") or []) if m not in ("done", "vm")] - if bad_mods: - raise Unsupported("exp", self.pc, f"modifier(s) {', '.join(bad_mods)} are not modelled") - if len(a) != 5 or a[0].get("t") != "mrt0" or any(x["k"] != "vgpr" for x in a[1:]): - raise Unsupported("exp", self.pc, "only `exp mrt0 vA, vB, vC, vD` is modelled") - for lane in self._active_lanes(): - self.exports[lane] = tuple(self._vgpr(x["r"], lane) for x in a[1:]) - return None - - def _vcmp(self, ins, base): - op, a = ins["op"], ins["args"] - cmpx = base.startswith("v_cmpx_") - body = base[len("v_cmpx_"):] if cmpx else base[len("v_cmp_"):] - cc, _, ty = body.partition("_") - if cc not in _CMP or ty not in ("u32", "i32"): - raise Unsupported(op, self.pc, "compare is not modelled") - srcs = a if cmpx else a[1:] - if cmpx and len(a) == 3: - raise Unsupported(op, self.pc, "an RDNA2 v_cmpx has no scalar destination") - if len(srcs) != 2: - raise Unsupported(op, self.pc, f"expected 2 compare sources, got {len(srcs)}") - mask = 0 - for lane in self._active_lanes(): - x, y = self._int_src(srcs[0], lane), self._int_src(srcs[1], lane) - if ty == "i32": - x, y = _signed(x), _signed(y) - if _CMP[cc](x, y): - mask |= 1 << lane - if cmpx: - self.exec = mask if self.wave == 64 else (self.exec & ~MASK32) | mask - return None - dst = a[0] - if self.wave == 32 and dst["k"] == "special" and dst["t"] == "vcc": - dst = {"k": "special", "t": "vcc_lo"} - if self.wave == 64 and dst["k"] == "sgpr" and dst.get("n", 1) < 2: - raise Unsupported(op, self.pc, "a wave64 compare needs an SGPR pair destination") - self._write_mask(dst, mask) - return None - - -def run(listing_path, wave=32, max_steps=200000): - cpu_ref._require_header(listing_path) - return WaveMachine(parse_file(listing_path), wave=wave, max_steps=max_steps).run() diff --git a/tools/cfg_structure.py b/tools/cfg_structure.py deleted file mode 100644 index 3409d4dbf..000000000 --- a/tools/cfg_structure.py +++ /dev/null @@ -1,349 +0,0 @@ -"""Arrange a control-flow graph as nested loops and conditionals driven by a block-number variable. - - structure(succ) -> tree, or None when the graph is irreducible - -`succ[b]` lists the blocks that block b can go to next (none = the program ends there); block 0 is the entry. -Every block ends by storing its successor's number in a variable `pc` (END when it has none). The tree says where -each block's code goes: - - ("block", b) run block b - ("guard", b, [items]) if pc == b: run the items (they start with block b, or with the loop headed by b) - ("loop", b, [items]) repeat the items, which start with block b, for as long as pc == b afterwards - -Why this instead of one loop around a switch: a shader compiler has to rediscover the real control flow from a -switch on a variable that every block writes, which takes it minutes on shaders with a thousand blocks. Here the -loops are loops, and the guards are tests against a value that was just assigned, which fold at once. - -How it is built (reducible graphs only, i.e. every loop has a single entry): - - Each natural loop becomes a "loop" item. Leaving it needs no break: pc simply no longer names the header. - - Inside a loop (and at the top level) the members are nested by dominance: after a member come the members it - immediately dominates, each behind a guard, in an order where every forward edge points later. A jump to a - member that isn't below the current one falls out of the guards it is in, to the level where a later guard - matches. A jump out of the loop falls out of all of them. -A block is never skipped or run twice in one pass, so any path through the graph is followed exactly. -""" -import collections - -END = -1 - - -def _order(succ): - """Reverse postorder from block 0, the retreating edges of that walk, and the predecessors of each block.""" - state, order, back = {0: 1}, [], [] - stack = [(0, iter(succ[0]))] - while stack: - v, it = stack[-1] - for w in it: - if w not in state: - state[w] = 1 - stack.append((w, iter(succ[w]))) - break - if state[w] == 1: - back.append((v, w)) - else: - state[v] = 2 - order.append(v) - stack.pop() - rpo = order[::-1] - preds = collections.defaultdict(list) - for v in rpo: - for w in succ[v]: - preds[w].append(v) - return rpo, back, preds - - -def _dominators(rpo, preds): - """Immediate dominator of each reachable block (Cooper, Harvey and Kennedy).""" - pos = {v: i for i, v in enumerate(rpo)} - idom = {rpo[0]: rpo[0]} - changed = True - while changed: - changed = False - for v in rpo[1:]: - new = None - for p in preds[v]: - if p not in idom: - continue - if new is None: - new = p - continue - a, b = p, new - while a != b: - while pos[a] > pos[b]: - a = idom[a] - while pos[b] > pos[a]: - b = idom[b] - new = a - if idom.get(v) != new: - idom[v] = new - changed = True - return idom, pos - - -def structure(succ): - rpo, back, preds = _order(succ) - idom, pos = _dominators(rpo, preds) - - def dominates(a, b): - while pos[b] > pos[a]: - b = idom[b] - return a == b - - if not all(dominates(w, v) for v, w in back): - return None # a loop with two entries: no nesting expresses it - - # Natural loops, and the innermost loop each block is in (named by its header; None = not in a loop). - bodies = {} - for v, h in back: - body = bodies.setdefault(h, {h}) - work = [v] - while work: - x = work.pop() - if x not in body: - body.add(x) - work.extend(preds[x]) - inner = {} - for h in sorted(bodies, key=lambda h: len(bodies[h])): - for x in bodies[h]: - inner.setdefault(x, h) - outer = {} # loop -> the loop around it - for h in bodies: - around = [g for g in bodies if g != h and h in bodies[g]] - outer[h] = min(around, key=lambda g: len(bodies[g])) if around else None - - def member(x, region): - """The member of `region` that block x belongs to: x itself, or the loop inside the region holding it. - Members are ("b", block) and ("l", header).""" - loop = inner.get(x) - if loop == region: - return ("b", x) - while outer[loop] != region: - loop = outer[loop] - return ("l", loop) - - # Dominance among the members of each region. A member's parent is the member holding the immediate - # dominator of its first block; that dominator is always inside the same region. - children = collections.defaultdict(list) - for x in rpo[1:]: - region = inner.get(x) - if region == x: # a loop header: it is placed as its loop, in the outer region - children[member(idom[x], outer[x])].append(("l", x)) - else: - children[member(idom[x], region)].append(("b", x)) - - # Flatten dominated tail continuations out of enclosing guards and build iteratively so long sequential - # diamond/loop chains stay O(1) deep instead of nesting O(N) OpSelectionMerge constructs (and never hit - # Python's recursion limit on multi-thousand-block shaders). - # Hoisting the last child c_last of a guarded member m into m's enclosing list is exact: m's head strictly - # dominates c_last's head, so no block outside m's subtree can jump to c_last's head. When m's guard is skipped - # (pc != m_head), pc cannot equal c_last_head either, so c_last's guard is skipped too; when m's guard runs, - # c_last runs right after m's earlier children, in the same order as before. - max_guard_depth = 16 - root = [] - start = ("l", 0) if 0 in bodies else ("b", 0) - stack = [("emit", root, None, start, 0)] - while stack: - task = stack.pop() - if task[0] == "open_guard": - _, parent_list, m, depth = task - gbody = [] - parent_list.append(("guard", m[1], gbody)) - stack.append(("emit", gbody, parent_list, m, depth)) - continue - _, out_list, parent_list, m, depth = task - kind, x = m - below = sorted(children[m], key=lambda c: pos[c[1]]) - if kind == "l": - lbody = [] - out_list.append(("loop", x, lbody)) - else: - out_list.append(("block", x)) - if kind == "b" and len(below) == 1 and list(succ[x]) == [below[0][1]]: - stack.append(("emit", out_list, parent_list, below[0], depth)) - else: - hoist = (parent_list is not None and below - and (len(below) >= 2 or kind == "l" or depth >= max_guard_depth)) - if hoist: - stack.append(("open_guard", parent_list, below[-1], depth)) - inner = below[:-1] - else: - inner = below - for c in reversed(inner): - stack.append(("open_guard", out_list, c, depth + 1)) - if kind == "l": - stack.append(("emit", lbody, None, ("b", x), 0)) - return root - - - -def depth(tree): - """Nesting depth of a tree from structure(): a block is depth 0 and each guard or loop adds one.""" - best = 0 - stack = [(tree, 0)] - while stack: - items, d = stack.pop() - for it in items: - if it[0] == "block": - best = max(best, d) - else: - best = max(best, d + 1) - stack.append((it[2], d + 1)) - return best - - -def _sccs(nodes, adj): - """Iterative Tarjan's algorithm over `nodes` with adjacency `adj`; returns SCCs with >= 2 nodes.""" - index, low, on_stack, stack, out = {}, {}, set(), [], [] - nxt = 0 - for start in nodes: - if start in index: - continue - index[start] = low[start] = nxt - nxt += 1 - stack.append(start) - on_stack.add(start) - call = [(start, iter(adj[start]))] - while call: - v, it = call[-1] - for w in it: - if w not in index: - index[w] = low[w] = nxt - nxt += 1 - stack.append(w) - on_stack.add(w) - call.append((w, iter(adj[w]))) - break - if w in on_stack and index[w] < low[v]: - low[v] = index[w] - else: - if low[v] == index[v]: - comp = [] - while True: - x = stack.pop() - on_stack.remove(x) - comp.append(x) - if x == v: - break - if len(comp) >= 2: - out.append(set(comp)) - call.pop() - if call: - p = call[-1][0] - if low[v] < low[p]: - low[p] = low[v] - return out - - -def split_irreducible(succ, max_factor=2, max_splits=64): - """Make an irreducible CFG reducible by controlled node splitting (cloning the closed region R reachable from a secondary entry e without passing through primary entry h - in an irreducible SCC, and redirecting e's external predecessors to clone[e]). - - Returns `(new_succ, orig_of)` where `orig_of[b]` is the original block index that block `b` executes - and `new_succ[b]` preserves the exact positional successor order of `succ[orig_of[b]]`. - Returns `(succ, list(range(len(succ))))` unchanged if `succ` is already reducible, or `None` if - splitting would exceed `max_factor` * len(succ) blocks or `max_splits` duplications. - """ - n0 = len(succ) - if n0 == 0: - return succ, [] - max_blocks = min(int(n0 * max_factor), n0 + max_splits) - g = None - orig = None - while True: - cur = succ if g is None else g - rpo, back, preds = _order(cur) - idom, pos = _dominators(rpo, preds) - - def dominates(a, b): - while pos[b] > pos[a]: - b = idom[b] - return a == b - - if all(dominates(w, v) for v, w in back): - if g is None: - return succ, list(range(n0)) - return g, orig - if g is None: - g = [list(s) for s in succ] - orig = list(range(n0)) - if len(g) >= max_blocks: - return None - - # Strip dominating back-edges so nested irreducible cycles inside reducible loops surface as SCCs. - adj = {v: [w for w in g[v] if not dominates(w, v)] for v in rpo} - sccs = _sccs(rpo, adj) - if not sccs: - return None - # Pick the smallest irreducible SCC (tie-break by earliest RPO position). - scc = min(sccs, key=lambda c: (len(c), min(pos[x] for x in c))) - entries = [x for x in scc if x == 0 or any(p not in scc for p in preds[x])] - # Choose a pair (h, e) of SCC entries (e != h, e != 0) minimizing |R|, where R is the closed region of - # SCC nodes reachable from e without passing through h. Cloning all of R at once keeps internal cycles - # inside the clone instead of re-entering the original SCC and unrolling infinitely. - best = None - for h in entries: - for e in entries: - if e == h or e == 0: - continue - region = {e} - work = [e] - while work: - u = work.pop() - for w in g[u]: - if w in scc and w != h and w not in region: - region.add(w) - work.append(w) - key = (len(region), pos[h], -pos[e]) - if best is None or key < best[0]: - best = (key, h, e, region) - if best is None: - return None - _, h, e, region = best - if len(g) + len(region) > max_blocks: - return None - # Order cloned nodes deterministically by RPO position. - reg_ordered = sorted(region, key=lambda x: pos[x]) - clone_of = {} - for u in reg_ordered: - clone_of[u] = len(g) - orig.append(orig[u]) - g.append([]) - for u in reg_ordered: - g[clone_of[u]] = [clone_of[w] if w in clone_of else w for w in g[u]] - ext_preds = {p for p in preds[e] if p not in scc} - ce = clone_of[e] - for p in ext_preds: - g[p] = [ce if w == e else w for w in g[p]] - -def run(tree, choose, limit): - """Interpret a tree: the blocks it executes, in order, stopping after `limit`. `choose(b)` gives the block - that b goes to next (END to finish) and stands for whatever b stores in pc.""" - trace, pc = [], [0] - stack = [("items", tree, 0)] - while stack: - frame = stack[-1] - if frame[0] == "items": - _, items, idx = frame - if idx >= len(items): - stack.pop() - continue - stack[-1] = ("items", items, idx + 1) - it = items[idx] - if it[0] == "block": - if len(trace) >= limit: - break - trace.append(it[1]) - pc[0] = choose(it[1]) - elif it[0] == "guard": - if pc[0] == it[1]: - stack.append(("items", it[2], 0)) - else: - stack.append(("loop", it[1], it[2])) - stack.append(("items", it[2], 0)) - else: - _, head, body = frame - if pc[0] == head: - stack.append(("items", body, 0)) - else: - stack.pop() - return trace diff --git a/tools/character_census.py b/tools/character_census.py deleted file mode 100644 index 7b949b2c4..000000000 --- a/tools/character_census.py +++ /dev/null @@ -1,937 +0,0 @@ -"""Census decoded character models: counts, materials, textures, bones and skin layout. - -Usage:: - - python -I tools/character_census.py [--json FILE] [--csv FILE] - -The input is either a directory tree of decoded pack models (every nested ``model.json`` is read) or a -manifest. The decoded ``model.json`` layout written by the local pack exporter is:: - - type "dr" drawable, "ft" fragment, ... - vertex_count total over all meshes - triangle_count total over all meshes - materials[] shader_name_hash, textures[] (hash64/hash32) - drawable.skeleton[] fragment skeleton - drawable.models[] bone_palette[] (local bone count) - meshes[] vertex_count, triangle_count, skinned, skin_influences, bones - -The local exporter does not write an index count, so the index column and total normally stay -unknown. An input that supplies ``index_count`` (or ``indices``/``IndexCount``) is counted; the -field is optional, not part of the decoded layout above. -When a model total is absent, every mesh must supply its contribution for that total to be known. -A mesh without a triangle count can contribute its own index count divided by three. - -An ``rpf9dump models`` manifest (``Items[]`` with ``Verts``, ``Tris``, ``IsFragment``, -``HasBoneBindings`` and ``Materials[]``) and a simple ``models[]`` list of model paths or inline -model objects are also accepted. An ``rpf9dump models`` manifest has only ``HasBoneBindings``, not -a bone count or influence width, so those cells are reported as unknown rather than guessed. - -Every model is reported independently. A missing field, a wrong type or an unreadable JSON file -adds an issue to that row and never stops the run. Only model names, hashes, counts and issue text -are emitted; no vertex, texture or package bytes are copied. - -The report paths are refused when they alias an input (the manifest, a nested ``model.json`` or a -model referenced by the manifest), so the census cannot overwrite its own source. -""" -from __future__ import annotations - -import argparse -import csv -import json -import os -import sys - -HERE = os.path.dirname(os.path.abspath(__file__)) -if HERE not in sys.path: # -I does not put the script's directory on sys.path - sys.path.insert(0, HERE) -from report_paths import same_report_path # noqa: E402 - -MODEL_JSON = "model.json" -SHADER_DIGITS = 8 -TEXTURE_DIGITS = 16 - -KINDS = { - "dr": "drawable", - "ydr": "drawable", - "drawable": "drawable", - "d": "drawable", - "ft": "fragment", - "yft": "fragment", - "fragment": "fragment", - "f": "fragment", - "dd": "dictionary", - "ydd": "dictionary", - "dictionary": "dictionary", - "component": "component", - "cmp": "component", -} - -VERTEX_KEYS = ("vertex_count", "vertices", "Verts", "Vertices", "VertexCount") -TRIANGLE_KEYS = ("triangle_count", "triangles", "Tris", "Triangles", "TriangleCount") -INDEX_KEYS = ("index_count", "indices", "Indices", "IndexCount") -BONE_KEYS = ("bone_count", "BoneCount", "Bones", "bones") -SHADER_KEYS = ("shader_name_hash", "shader_hash", "Shader", "name_hash", "hash") -TEXTURE_KEYS = ("hash64", "Id64", "Key", "asset_key", "hash", "hash32", "Name") - -CSV_FIELDS = ["source", "name", "kind", "vertices", "triangles", "indices", "bones", "skin_8", - "shaders", "textures", "issues"] - - -# --------------------------------------------------------------------- hashes -def _hash(value, digits: int): - """Canonical ``0x`` + uppercase hex hash, or None when the value is not hex.""" - if isinstance(value, bool): - return None - if isinstance(value, int): - if value < 0 or value >= 1 << (4 * digits): - return None - return f"0x{value:0{digits}X}" - if not isinstance(value, str): - return None - text = value.strip() - if text[:2].lower() == "0x": - text = text[2:] - if not text or len(text) > digits: - return None - if any(ch not in "0123456789abcdefABCDEF" for ch in text): - return None - try: - number = int(text, 16) - except ValueError: - return None - return f"0x{number:0{digits}X}" - - -def shader_hash(value): - """An 8-digit material shader hash; zero and malformed values are not hashes.""" - result = _hash(value, SHADER_DIGITS) - return None if result in (None, "0x00000000") else result - - -def texture_hash(value): - """A texture key: 16 digits for 64-bit values, 8 for 32-bit values.""" - if isinstance(value, str): - text = value.strip() - digits = TEXTURE_DIGITS if len(text.removeprefix("0x").removeprefix("0X")) > 8 else 8 - elif isinstance(value, int) and not isinstance(value, bool): - digits = TEXTURE_DIGITS if value > 0xFFFFFFFF else 8 - else: - digits = 8 - result = _hash(value, digits) - return None if result in (None, "0x" + "0" * digits) else result - - -def count(value): - """A non-negative integer, or None for bools, floats, negatives and non-numbers.""" - if isinstance(value, bool) or not isinstance(value, int) or value < 0: - return None - return value - - -# -------------------------------------------------------------------- reading -def _walk_error(exc: OSError): - # os.walk skips a directory it cannot list unless onerror raises; a census must not report an - # incomplete scan as complete. main() turns the OSError into one ERROR line and exit 2. - raise exc - - -def model_json_files(directory: str): - """Every nested model.json, in a stable order. An unlistable sub-folder raises OSError.""" - for base, dirs, files in os.walk(directory, onerror=_walk_error): - dirs.sort() - for name in sorted(files): - if name.lower() == MODEL_JSON: - yield os.path.join(base, name) - - -def _read_json(path: str): - # utf-8-sig: a model.json or manifest saved by a Windows editor starts with a BOM, which json.load refuses. - with open(path, encoding="utf-8-sig") as handle: - return json.load(handle) - - -def _manifest_entries(data): - """Return (entries, label) for a manifest object/list, or (None, None) for a model.""" - if isinstance(data, list): - return data, "models" - if not isinstance(data, dict): - return None, None - for key in ("Items", "items"): - if isinstance(data.get(key), list): - return data[key], key - if isinstance(data.get("models"), list): - return data["models"], "models" - return None, None - - -def _looks_like_model(data) -> bool: - if not isinstance(data, dict): - return False - return any(key in data for key in ("drawable", "meshes", "vertex_count", "triangle_count", - "materials", "buffer_files", "glb")) - - -def _entry_path(entry): - if isinstance(entry, str): - return entry - if isinstance(entry, dict): - for key in ("model_json", "model_path", "path", "json"): - value = entry.get(key) - if isinstance(value, str) and value.strip(): - return value - return None - - -def _resolve_path(path: str, base: str) -> str: - path = path if os.path.isabs(path) else os.path.join(base, path) - if os.path.isdir(path): - path = os.path.join(path, MODEL_JSON) - return os.path.abspath(path) - - -def input_files(target: str): - """Every file the census may read, so a report path cannot overwrite one.""" - if os.path.isdir(target): - yield from model_json_files(target) - return - if not os.path.isfile(target): - return - yield target - try: - data = _read_json(target) - except (OSError, UnicodeDecodeError, ValueError, RecursionError): - return - entries, _ = _manifest_entries(data) - if entries is None: - return - base = os.path.dirname(os.path.abspath(target)) - for entry in entries: - path = _entry_path(entry) - if path: - try: - yield _resolve_path(path, base) - except (OSError, ValueError): - continue - - -def _fallback_name(source: str) -> str: - source = os.path.normpath(source) - if os.path.basename(source).lower() == MODEL_JSON: - return os.path.basename(os.path.dirname(source)) or MODEL_JSON - return os.path.splitext(os.path.basename(source))[0] or "model" - - -def _blank_row(source: str, name: str) -> dict: - return { - "source": source, - "name": name, - "kind": "unknown", - "vertices": None, - "triangles": None, - "indices": None, - "bones": None, - "skin_8": None, - "shaders": [], - "textures": [], - "issues": [], - } - - -def _text_field(obj, keys, label: str, issues: list) -> str | None: - for key in keys: - if key not in obj: - continue - value = obj[key] - if isinstance(value, str) and value.strip(): - return value.strip() - if value is not None: - issues.append(f"{label} is not a non-empty string") - return None - - -def _count_field(obj, keys, label: str, issues: list, *, list_len: bool = False) -> int | None: - for key in keys: - if key not in obj: - continue - value = obj[key] - if value is None: - return None - if list_len and isinstance(value, list): - return len(value) - result = count(value) - if result is None: - issues.append(f"{label} is not a non-negative integer") - return result - return None - - -def _mesh_count(meshes: list, keys, label: str, issues: list, *, list_len: bool = False): - total = 0 - complete = True - for index, mesh in enumerate(meshes): - if not isinstance(mesh, dict): - issues.append(f"mesh {index} is not an object") - complete = False - continue - value = _count_field(mesh, keys, f"mesh {index} {label}", issues, list_len=list_len) - if value is None and keys == TRIANGLE_KEYS: - indices = _count_field(mesh, INDEX_KEYS, f"mesh {index} index count", issues, list_len=True) - if indices is not None: - value = indices // 3 - if value is None: - complete = False - else: - total += value - return total if complete else None - - -def _kind(model: dict, row: dict, issues: list) -> str: - if "type" in model: - raw = model.get("type") - if not isinstance(raw, str) or not raw.strip(): - issues.append("type is not a non-empty string") - else: - text = raw.strip().lower() - return KINDS.get(text, text) - elif "kind" in model: - raw = model.get("kind") - if not isinstance(raw, str) or not raw.strip(): - issues.append("kind is not a non-empty string") - else: - text = raw.strip().lower() - return KINDS.get(text, text) - if row.get("IsFragment") is True: - return "fragment" - if row.get("IsFragment") is False: - return "drawable" - if "drawable" in model: - return "drawable" - if "meshes" in model: - return "component" - return "unknown" - - -def _collect_shaders(materials, drawable, issues: list) -> list: - found = set() - material_rows = materials if isinstance(materials, list) else [] - for index, material in enumerate(material_rows): - if not isinstance(material, dict): - issues.append(f"material {index} is not an object") - continue - for key in SHADER_KEYS: - if key not in material or material[key] is None: - continue - value = shader_hash(material[key]) - if value is None: - issues.append(f"material {index} {key} is not an 8-digit shader hash") - else: - found.add(value) - shader_rows = drawable.get("shaders") if isinstance(drawable, dict) else None - for index, shader in enumerate(shader_rows if isinstance(shader_rows, list) else []): - if not isinstance(shader, dict): - issues.append(f"drawable shader {index} is not an object") - continue - for key in SHADER_KEYS: - if key not in shader or shader[key] is None: - continue - value = shader_hash(shader[key]) - if value is None: - issues.append(f"drawable shader {index} {key} is not an 8-digit shader hash") - else: - found.add(value) - if material_rows and not found: - issues.append("no shader hash on any material") - return sorted(found) - - -def _texture_rows(textures, where: str, issues: list): - if isinstance(textures, list): - return textures - if isinstance(textures, dict): - return list(textures.values()) - if textures is not None: - issues.append(f"{where} is not a list or object") - return [] - - -def _collect_textures(materials, drawable, issues: list) -> list: - found = set() - - def add(value, where: str): - if value is None: - return - key = texture_hash(value) - if key is None: - issues.append(f"{where} is not a hexadecimal texture key") - else: - found.add(key) - - def add_rows(rows, where: str): - for index, texture in enumerate(rows): - if isinstance(texture, dict): - for key in TEXTURE_KEYS: - if key in texture and texture[key] is not None: - add(texture[key], f"{where} {index} {key}") - break - else: - add(texture, f"{where} {index}") - - material_rows = materials if isinstance(materials, list) else [] - for index, material in enumerate(material_rows): - if isinstance(material, dict): - for key in ("textures", "Textures"): - if key in material: - add_rows(_texture_rows(material[key], f"material {index} textures", issues), - f"material {index} texture") - break - - shader_rows = drawable.get("shaders") if isinstance(drawable, dict) else None - for index, shader in enumerate(shader_rows if isinstance(shader_rows, list) else []): - if isinstance(shader, dict) and "textures" in shader: - add_rows(_texture_rows(shader["textures"], f"drawable shader {index} textures", issues), - f"drawable shader {index} texture") - return sorted(found) - - -def _bones(model, drawable, meshes, row, issues: list): - for source, where in ((row, "manifest"), (model, "model")): - if not isinstance(source, dict): - continue - for key in BONE_KEYS: - if key not in source: - continue - value = source[key] - if isinstance(value, list): - if value: - return len(value) - continue - result = count(value) - if result is not None: - return result - if value is not None: - issues.append(f"{where} {key} is not a non-negative integer or a list") - if isinstance(drawable, dict): - skeleton = drawable.get("skeleton") - if isinstance(skeleton, list) and skeleton: - return len(skeleton) - models = drawable.get("models") - palettes = [len(m["bone_palette"]) for m in models if isinstance(m, dict) - and isinstance(m.get("bone_palette"), list)] if isinstance(models, list) else [] - if any(palettes): - return max(palettes) - mesh_bones = [] - for mesh in meshes: - if not isinstance(mesh, dict): - continue - value = mesh.get("bones") - if isinstance(value, list) and value: - mesh_bones.append(len(value)) - elif count(value) is not None: - mesh_bones.append(count(value)) - if mesh_bones: - return max(mesh_bones) - if row.get("HasBoneBindings") is False: - return 0 - if any(isinstance(mesh, dict) and mesh.get("skinned") is True for mesh in meshes): - issues.append("no bone count for a skinned model") - return None - if row.get("HasBoneBindings") is True: - return None - return 0 - - -def _eight_influence_sections(drawable) -> bool: - """True when a vertex buffer's measured section table has all four skin slots. - - The decoded layout writes ``mesh_blob.sections`` as ``[semantic, offset, format]``; 6/7 are - the WEIGHTS_0/1 streams and 8/9 the JOINTS_0/1 streams. This is a fallback for a model.json - that omits ``meshes[].skin_influences``. - """ - if not isinstance(drawable, dict): - return False - buffers = drawable.get("buffers") - if not isinstance(buffers, list): - return False - for buffer in buffers: - if not isinstance(buffer, dict): - continue - blob = buffer.get("mesh_blob") - if not isinstance(blob, dict) or not isinstance(blob.get("sections"), list): - continue - semantics = set() - for section in blob["sections"]: - if isinstance(section, (list, tuple)) and section: - value = count(section[0]) - if value is not None: - semantics.add(value) - if {6, 7, 8, 9} <= semantics: - return True - return False - - -def _skin_8(meshes, row, issues: list, drawable=None): - for key in ("skin_8", "Skin8", "skin_influences_8", "SkinInfluences8"): - if key in row: - value = row[key] - if isinstance(value, bool): - return value - if value is not None: - issues.append(f"{key} is not a boolean") - for key in ("skin_influences", "SkinInfluences", "Influences"): - if key not in row or row[key] is None: - continue - influences = count(row[key]) - if influences is None: - issues.append(f"{key} is not a non-negative integer") - else: - return influences >= 8 - states = [] - for index, mesh in enumerate(meshes): - if not isinstance(mesh, dict): - continue - attributes = mesh.get("attributes") - if isinstance(attributes, dict): - names = {str(key) for key in attributes} - elif isinstance(attributes, list): - names = {str(value) for value in attributes} - else: - names = set() - if {"JOINTS_0", "JOINTS_1", "WEIGHTS_0", "WEIGHTS_1"} <= names: - states.append(True) - continue - value = mesh.get("skin_influences") - if value is not None: - influences = count(value) - if influences is None: - issues.append(f"mesh {index} skin_influences is not a non-negative integer") - states.append(None) - else: - states.append(influences >= 8) - elif mesh.get("skinned") is True: - states.append(None) - if True in states: - return True - if _eight_influence_sections(drawable): - return True - if None in states: - return None - if states: - return False - if row.get("HasBoneBindings") is True: - return None - if row.get("HasBoneBindings") is False: - return False - return False - - -def model_row(model: dict, source: str, issues: list | None = None) -> dict: - """Build one census row from a decoded model.json object.""" - issues = [] if issues is None else issues - row = _blank_row(source, "") - row["issues"] = issues - - drawable = model.get("drawable") - if drawable is not None and not isinstance(drawable, dict): - issues.append("drawable is not an object") - drawable = None - meshes = model.get("meshes") - if meshes is not None and not isinstance(meshes, list): - issues.append("meshes is not a list") - meshes = [] - meshes = meshes or [] - materials = model.get("materials") - if materials is not None and not isinstance(materials, list): - issues.append("materials is not a list") - materials = [] - - name = _text_field(model, ("name", "Name"), "name", issues) - if name is None and isinstance(drawable, dict): - name = _text_field(drawable, ("name", "Name"), "drawable name", issues) - if name is None: - name = _fallback_name(source) - issues.append("missing name") - row["name"] = name - row["kind"] = _kind(model, row, issues) - - vertices = _count_field(model, VERTEX_KEYS, "vertex count", issues) - if vertices is None and meshes: - vertices = _mesh_count(meshes, VERTEX_KEYS, "vertex count", issues) - triangles = _count_field(model, TRIANGLE_KEYS, "triangle count", issues) - if triangles is None and meshes: - triangles = _mesh_count(meshes, TRIANGLE_KEYS, "triangle count", issues) - indices = _count_field(model, INDEX_KEYS, "index count", issues, list_len=True) - if indices is None and meshes: - indices = _mesh_count(meshes, INDEX_KEYS, "index count", issues, list_len=True) - if vertices is None: - issues.append("missing vertex count") - if triangles is None: - issues.append("missing triangle count") - row["vertices"] = vertices - row["triangles"] = triangles - row["indices"] = indices - - row["shaders"] = _collect_shaders(materials, drawable, issues) - row["textures"] = _collect_textures(materials, drawable, issues) - row["bones"] = _bones(model, drawable, meshes, row, issues) - row["skin_8"] = _skin_8(meshes, row, issues, drawable) - return row - - -def manifest_row(entry: dict, source: str) -> dict: - """Build one census row from an rpf9dump models manifest item.""" - issues = [] - row = _blank_row(source, "") - name = _text_field(entry, ("Name", "name"), "name", issues) - if name is None: - file_name = entry.get("File") - name = (os.path.splitext(os.path.basename(file_name))[0] - if isinstance(file_name, str) and file_name else source) - issues.append("missing name") - row["name"] = name - row["kind"] = _kind(entry, entry, issues) - if "IsFragment" in entry and not isinstance(entry["IsFragment"], bool): - issues.append("IsFragment is not a boolean") - row["vertices"] = _count_field(entry, VERTEX_KEYS, "vertex count", issues) - row["triangles"] = _count_field(entry, TRIANGLE_KEYS, "triangle count", issues) - row["indices"] = _count_field(entry, INDEX_KEYS, "index count", issues, list_len=True) - if row["vertices"] is None: - issues.append("missing vertex count") - if row["triangles"] is None: - issues.append("missing triangle count") - - materials = entry.get("Materials") - if materials is not None and not isinstance(materials, list): - issues.append("Materials is not a list") - materials = [] - row["shaders"] = _collect_shaders(materials, None, issues) - row["textures"] = _collect_textures(materials, None, issues) - row["bones"] = _bones(entry, None, [], entry, issues) - row["skin_8"] = _skin_8([], entry, issues) - if "HasBoneBindings" not in entry: - explicit_bones = any(key in entry for key in BONE_KEYS) - explicit_skin = any(key in entry for key in - ("skin_8", "Skin8", "skin_influences", "SkinInfluences", "Influences")) - if not explicit_bones: - row["bones"] = None - if not explicit_skin: - row["skin_8"] = None - issues.append("HasBoneBindings is missing") - elif not isinstance(entry["HasBoneBindings"], bool): - issues.append("HasBoneBindings is not a boolean") - row["bones"] = None - row["skin_8"] = None - row["issues"] = issues - return row - - -def _read_model(path: str, source: str) -> dict: - try: - data = _read_json(path) - except (OSError, UnicodeDecodeError, ValueError, RecursionError) as exc: - row = _blank_row(source, _fallback_name(path)) - detail = getattr(exc, "strerror", None) or str(exc) - row["issues"].append(f"cannot read model.json: {detail}") - return row - if not isinstance(data, dict): - row = _blank_row(source, _fallback_name(path)) - row["issues"].append("model.json root is not an object") - return row - return model_row(data, source) - - -def load_rows(target: str): - """Yield one row per model. Per-model failures become rows with an issue.""" - if os.path.isdir(target): - root = os.path.abspath(target) - for path in model_json_files(target): - source = os.path.relpath(path, root) - yield _read_model(path, source) - return - - source = os.path.basename(target) - try: - data = _read_json(target) - except (OSError, UnicodeDecodeError, ValueError, RecursionError) as exc: - row = _blank_row(source, _fallback_name(target)) - detail = getattr(exc, "strerror", None) or str(exc) - row["issues"].append(f"cannot read manifest: {detail}") - yield row - return - - if _looks_like_model(data): - yield model_row(data, source) - return - - entries, label = _manifest_entries(data) - if entries is None: - row = _blank_row(source, _fallback_name(target)) - row["issues"].append("manifest has no Items[] or models[] list") - yield row - return - - base = os.path.dirname(os.path.abspath(target)) - for index, entry in enumerate(entries): - where = f"{source}#{label}[{index}]" - path = _entry_path(entry) - if path: - try: - resolved = _resolve_path(path, base) - except (OSError, ValueError) as exc: - row = _blank_row(where, _fallback_name(where)) - row["issues"].append(f"cannot resolve model path: {exc}") - yield row - continue - try: - relative = os.path.relpath(resolved, base) - except ValueError: # another drive on Windows - relative = resolved - yield _read_model(resolved, f"{source}#{relative}") - elif isinstance(entry, dict) and _looks_like_model(entry): - yield model_row(entry, where) - elif isinstance(entry, dict): - source_name = entry.get("File") or entry.get("Name") or where - yield manifest_row(entry, str(source_name)) - else: - row = _blank_row(where, _fallback_name(where)) - row["issues"].append("manifest entry is neither a model object nor a path") - yield row - - -# ----------------------------------------------------------------- aggregates -def _known_total(rows, key): - values = [row[key] for row in rows if row[key] is not None] - return sum(values), len(rows) - len(values) - - -def summarize(rows: list) -> dict: - vertices, unknown_vertices = _known_total(rows, "vertices") - triangles, unknown_triangles = _known_total(rows, "triangles") - indices, unknown_indices = _known_total(rows, "indices") - summary = { - "models": len(rows), - "vertices": vertices, - "triangles": triangles, - "indices": indices, - "unknown_vertices": unknown_vertices, - "unknown_triangles": unknown_triangles, - "unknown_indices": unknown_indices, - "skin_8": sum(1 for row in rows if row["skin_8"] is True), - "skin_unknown": sum(1 for row in rows if row["skin_8"] is None), - "malformed": sum(1 for row in rows if row["issues"]), - "shader_hashes": len({value for row in rows for value in row["shaders"]}), - "texture_keys": len({value for row in rows for value in row["textures"]}), - "by_kind": {}, - "by_shader": {}, - } - kinds, shaders = summary["by_kind"], summary["by_shader"] - for row in rows: - group = kinds.setdefault(row["kind"], { - "models": 0, "vertices": 0, "triangles": 0, "indices": 0, - "skin_8": 0, "skin_unknown": 0, "malformed": 0, - "unknown_vertices": 0, "unknown_triangles": 0, "unknown_indices": 0, - }) - group["models"] += 1 - for key in ("vertices", "triangles", "indices"): - if row[key] is None: - group[f"unknown_{key}"] += 1 - else: - group[key] += row[key] - if row["skin_8"] is True: - group["skin_8"] += 1 - elif row["skin_8"] is None: - group["skin_unknown"] += 1 - if row["issues"]: - group["malformed"] += 1 - for value in row["shaders"]: - shader = shaders.setdefault(value, {"models": 0, "vertices": 0, "triangles": 0}) - shader["models"] += 1 - if row["vertices"] is not None: - shader["vertices"] += row["vertices"] - if row["triangles"] is not None: - shader["triangles"] += row["triangles"] - summary["by_kind"] = dict(sorted(kinds.items())) - summary["by_shader"] = dict(sorted(shaders.items())) - return summary - - -# --------------------------------------------------------------------- output -def _fmt(value, *, missing: str = "?") -> str: - if value is None: - return missing - return f"{value:,}" if isinstance(value, int) else str(value) - - -def _fmt_flag(value) -> str: - if value is None: - return "?" - return "yes" if value else "no" - - -def _table(headers, rows, right=()) -> list: - widths = [len(header) for header in headers] - for row in rows: - for index, cell in enumerate(row): - widths[index] = max(widths[index], len(cell)) - lines = [] - for cells in [headers] + rows: - parts = [] - for index, cell in enumerate(cells): - parts.append(cell.rjust(widths[index]) if index in right else cell.ljust(widths[index])) - lines.append(" ".join(parts).rstrip()) - return lines - - -def _plural(number: int, singular: str, plural: str | None = None) -> str: - word = singular if number == 1 else (plural or singular + "s") - return f"{number:,} {word}" - - -def _total_text(total: int, unknown: int, models: int, noun: str) -> str: - if models and unknown == models: - return f"? {noun}" - text = f"{_fmt(total)} {noun}" - if unknown: - text += f" ({unknown} without)" - return text - - -def print_report(summary: dict, rows: list) -> None: - verts = _total_text(summary["vertices"], summary["unknown_vertices"], - summary["models"], "vertices") - tris = _total_text(summary["triangles"], summary["unknown_triangles"], - summary["models"], "triangles") - indices = _total_text(summary["indices"], summary["unknown_indices"], - summary["models"], "indices") - print(f'character census: {_plural(summary["models"], "model")}, {verts}, {tris}, {indices}') - print(f' 8-influence skin: {summary["skin_8"]} yes, ' - f'{summary["models"] - summary["skin_8"] - summary["skin_unknown"]} no, ' - f'{summary["skin_unknown"]} unknown; ' - f'{_plural(summary["shader_hashes"], "shader hash", "shader hashes")}, ' - f'{_plural(summary["texture_keys"], "texture key")}') - print(f' {_plural(summary["malformed"], "model")} with issues') - - print("by kind:") - kind_rows = [] - for kind, group in summary["by_kind"].items(): - kind_rows.append([kind, _fmt(group["models"]), _fmt(group["vertices"]), - _fmt(group["triangles"]), _fmt(group["skin_8"]), _fmt(group["malformed"])]) - for line in _table(["KIND", "MODELS", "VERTICES", "TRIANGLES", "8-INFLUENCE", "ISSUES"], - kind_rows, right={1, 2, 3, 4, 5}): - print(" " + line) - - print("by shader (a model with several materials counts under each):") - shader_rows = [] - for value, group in summary["by_shader"].items(): - shader_rows.append([value, _fmt(group["models"]), _fmt(group["vertices"]), - _fmt(group["triangles"])]) - for line in _table(["SHADER", "MODELS", "VERTICES", "TRIANGLES"], shader_rows, right={1, 2, 3}): - print(" " + line) - - print("models:") - model_rows = [] - for row in rows: - model_rows.append([ - row["name"], row["kind"], _fmt(row["vertices"]), _fmt(row["triangles"]), - _fmt(row["indices"], missing="-"), _fmt(row["bones"]), _fmt_flag(row["skin_8"]), - ",".join(row["shaders"]) or "-", ",".join(row["textures"]) or "-", - ]) - for line in _table(["NAME", "KIND", "VERTS", "TRIS", "INDICES", "BONES", "8-INFL", - "SHADERS", "TEXTURES"], model_rows, right={2, 3, 4, 5}): - print(" " + line) - - problems = [(row["source"], issue) for row in rows for issue in row["issues"]] - if problems: - print("problems:") - for source, issue in problems: - print(f" {source}: {issue}") - - -def _make_parent(path: str) -> None: - parent = os.path.dirname(os.path.abspath(path)) - if parent: - os.makedirs(parent, exist_ok=True) - - -def write_csv(path: str, rows: list) -> None: - _make_parent(path) - with open(path, "w", newline="", encoding="utf-8") as handle: - writer = csv.DictWriter(handle, fieldnames=CSV_FIELDS, lineterminator="\n") - writer.writeheader() - for row in rows: - out = {key: row[key] for key in CSV_FIELDS} - out["shaders"] = ";".join(row["shaders"]) - out["textures"] = ";".join(row["textures"]) - out["issues"] = ";".join(row["issues"]) - out["skin_8"] = "" if row["skin_8"] is None else str(row["skin_8"]).lower() - for key in ("vertices", "triangles", "indices", "bones"): - out[key] = "" if row[key] is None else row[key] - writer.writerow(out) - - -def write_json(path: str, summary: dict, rows: list) -> None: - _make_parent(path) - with open(path, "w", encoding="utf-8", newline="\n") as handle: - json.dump({"summary": summary, "models": rows}, handle, indent=1, ensure_ascii=False) - handle.write("\n") - - -def main(argv=None) -> int: - parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) - parser.add_argument("target", help="directory of decoded model.json files or a manifest path") - parser.add_argument("--json", metavar="FILE", help="write the summary and per-model rows as JSON") - parser.add_argument("--csv", metavar="FILE", help="write one row per model as CSV") - args = parser.parse_args(argv) - - if args.csv and args.json and same_report_path(args.csv, args.json): - parser.error("--csv and --json must use different paths") - try: - sources = list(input_files(args.target)) - except (OSError, ValueError) as exc: - print(f"ERROR: cannot read {getattr(exc, 'filename', None) or args.target}: " - f"{getattr(exc, 'strerror', None) or exc}", - file=sys.stderr) - return 2 - for flag, path in (("--json", args.json), ("--csv", args.csv)): - if not path: - continue - if os.path.isdir(path): - parser.error(f"{flag} is a directory: {path}") - for source in sources: - if same_report_path(path, source): - parser.error(f"{flag} would overwrite the input {source}") - - if not os.path.exists(args.target): - print(f"not found: {args.target}", file=sys.stderr) - return 2 - try: - rows = list(load_rows(args.target)) - except OSError as exc: - print(f"ERROR: cannot read {getattr(exc, 'filename', None) or args.target}: " - f"{getattr(exc, 'strerror', None) or exc}", - file=sys.stderr) - return 2 - rows.sort(key=lambda row: (row["name"].lower(), row["source"].lower())) - - summary = summarize(rows) - reports = [] - for path, writer, values in ((args.csv, write_csv, (rows,)), - (args.json, write_json, (summary, rows))): - if path: - try: - writer(path, *values) - except OSError as exc: - print(f"ERROR: cannot write {path}: {exc.strerror or exc}", file=sys.stderr) - return 2 - reports.append(path) - print_report(summary, rows) - for path in reports: - print("wrote", path) - return 0 - - -if __name__ == "__main__": - try: # a redirected stdout is strict ANSI code page under -I; write '?' for what it cannot encode - sys.stdout.reconfigure(errors="replace") - except (AttributeError, ValueError, OSError): - pass - sys.exit(main()) diff --git a/tools/character_textures.py b/tools/character_textures.py deleted file mode 100644 index 31bbff006..000000000 --- a/tools/character_textures.py +++ /dev/null @@ -1,406 +0,0 @@ -"""Classify the texture bindings of decoded character ``model.json`` materials. - -The five slot hashes below were measured on the retail package and named by the -case-sensitive joaat of the parameter name. They are the only slots this tool -resolves; anything else is reported as ``unknown 0x...`` rather than guessed: - - | slot | role | meaning | - | 0xC8E8C282 | diffusetex | sRGB albedo (the only albedo slot) | - | 0xC6F46E79 | speculartex | specular/gloss pack, not colour | - | 0x1E77BF4C | bumptex | tangent-space normal/detail normal | - | 0x739E3D0D | speculartex2 | packed ORM/mask | - | 0x8ADB8480 | materialid | ID/palette map | - -The garment shaders ``d5ed50f4``, ``ea8d09d0`` and ``39ddb9ca`` declare no -``0xC8E8C282`` slot at all. A material on one of those shaders with no albedo -binding is flagged ``garment-no-albedo``: a renderer must keep it clay instead -of treating ``speculartex`` as colour. - -Input is one or more decoded model JSON files, or a directory searched -recursively for ``model.json``. The decoder's capitalised keys are read, with -lowercase equivalents accepted for hand-written files: - - {"Name": "player_head", "Materials": [ - {"Name": "head", "Shader": "a1b2c3d4", "Textures": [ - {"Param": "C8E8C282", "Name": "face_diffusetex"}, - {"Param": "1E77BF4C", "Name": "face_bumptex"}]}]} - -A top-level ``Items``/``Models`` list is also accepted, so a model manifest can -be passed directly. When the model has no name, the ``File`` stem accepts either -slash convention regardless of the reporting host. The texture column keeps its -display name or hash. A separate ``asset_key`` column carries the 16-digit -resource identity from ``Id64`` or ``AssetKey``. - - python -I tools/character_textures.py [...] [--json FILE] [--csv FILE] - -``--json`` writes the full per-material report and ``--csv`` one row per -binding; neither may overwrite an input. Standard library only. -""" -import argparse -import csv -import json -import ntpath -import os -import sys - -# -I keeps the script directory off sys.path, so add it explicitly before importing the sibling module. -sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) -from report_paths import path_key, same_report_path # noqa: E402 - -SLOT_ROLES = { - "C8E8C282": "diffusetex", - "C6F46E79": "speculartex", - "1E77BF4C": "bumptex", - "739E3D0D": "speculartex2", - "8ADB8480": "materialid", -} -ALBEDO_SLOT = "C8E8C282" -GARMENT_SHADERS = ("d5ed50f4", "ea8d09d0", "39ddb9ca") - -MODEL_LISTS = ("Items", "items", "Models", "models") -MATERIAL_LISTS = ("Materials", "materials") -TEXTURE_LISTS = ("Textures", "textures", "Bindings", "bindings", "TextureBindings", "texture_bindings") -MODEL_NAME_KEYS = ("Name", "name", "ModelName", "model_name", "Model", "model") -MODEL_FILE_KEYS = ("File", "file") -MATERIAL_NAME_KEYS = ("Name", "name", "MaterialName", "material_name") -SHADER_KEYS = ("Shader", "shader", "ShaderName", "shader_name", "ShaderHash", "shader_hash") -PARAM_KEYS = ("Param", "param", "Slot", "slot", "Parameter", "parameter", "Hash", "hash") -ASSET_KEY_FIELDS = ("Id64", "id64", "AssetKey", "asset_key") -TEXTURE_NAME_KEYS = ("Name", "name", "Texture", "texture", "Key", "key") + ASSET_KEY_FIELDS - -CSV_FIELDS = ("source", "model", "material", "shader", "slot", "role", "texture", "flags", "asset_key") - - -def _first(mapping: dict, keys: tuple): - """The first present, non-empty value for `keys`; 0 and False are values, not gaps.""" - for key in keys: - if key not in mapping: - continue - value = mapping[key] - if value is None: - continue - if isinstance(value, str) and not value.strip(): - continue - return value - return None - - -def _one_line(text: object) -> str: - return " ".join(str(text).split()) - - -def _hex_field(value: object, digits: int) -> str | None: - """Normalise an unsigned field to its declared width, or None if malformed.""" - if isinstance(value, bool): - return None - if isinstance(value, int): - return f"{value:0{digits}X}" if 0 <= value < 16 ** digits else None - if not isinstance(value, str): - return None - text = value.strip() - if text[:2].lower() == "0x": - text = text[2:] - if len(text) == digits and all(ch in "0123456789abcdefABCDEF" for ch in text): - return text.upper() - return None - - -def _shader_id(value: object) -> str | None: - """Shader hash as lowercase text for display and garment matching.""" - if isinstance(value, bool) or value is None: - return None - if isinstance(value, int): - return f"{value:08x}" if 0 <= value <= 0xFFFFFFFF else str(value) - text = str(value).strip() - return text.lower() if text else None - - -def _texture_name(value: object) -> str: - text = _one_line(value) - return text or "-" - - -def model_name(model: dict, path: str) -> str: - """Name from the model, else its File stem, else the containing folder for a plain model.json.""" - explicit = _first(model, MODEL_NAME_KEYS) - if explicit is not None: - return _one_line(explicit) - file_name = _first(model, MODEL_FILE_KEYS) - if isinstance(file_name, str) and file_name.strip(): - return _one_line(ntpath.splitext(ntpath.basename(file_name.strip()))[0]) - stem = os.path.splitext(os.path.basename(path))[0] - if stem.lower() == "model": - parent = os.path.basename(os.path.dirname(os.path.abspath(path))) - if parent: - return parent - return stem or "-" - - -def models_in(document: object) -> list[dict]: - """The model objects in a decoded file, accepting a single model, a list, or a manifest.""" - if isinstance(document, list): - return [item for item in document if isinstance(item, dict)] - if not isinstance(document, dict): - raise ValueError("top level is not a JSON object or list") - for key in MODEL_LISTS: - value = document.get(key) - if isinstance(value, list): - return [item for item in value if isinstance(item, dict)] - if any(isinstance(document.get(key), list) for key in MATERIAL_LISTS): - return [document] - raise ValueError("no Materials or Items list") - - -def texture_bindings(material: dict) -> list: - """The material's binding list, also accepting a {slot: name} mapping.""" - for key in TEXTURE_LISTS: - value = material.get(key) - if isinstance(value, list): - return value - if isinstance(value, dict): - bindings = [] - for slot, entry in value.items(): - if isinstance(entry, dict): - binding = dict(entry) - binding.setdefault("Param", slot) - else: - binding = {"Param": slot, "Name": entry} - bindings.append(binding) - return bindings - return [] - - -def classify_material(material: dict, index: int) -> dict: - """Classify one decoded material.""" - name = _one_line(_first(material, MATERIAL_NAME_KEYS) or f"material[{index}]") - shader = _shader_id(_first(material, SHADER_KEYS)) - bindings = [] - for reference in texture_bindings(material): - if isinstance(reference, dict): - slot = _hex_field(_first(reference, PARAM_KEYS), 8) - texture = _texture_name(_first(reference, TEXTURE_NAME_KEYS)) - asset_key = _hex_field(_first(reference, ASSET_KEY_FIELDS), 16) - else: - slot, texture, asset_key = None, _texture_name(reference), None - if slot is None: - label, role = "-", "unknown" - else: - label = f"0x{slot}" - role = SLOT_ROLES.get(slot, f"unknown {label}") - bindings.append({"slot": label, "role": role, "texture": texture, "asset_key": asset_key}) - - missing_albedo = not any(binding["slot"] == f"0x{ALBEDO_SLOT}" for binding in bindings) - garment = shader is not None and (shader[2:] if shader.startswith("0x") else shader) in GARMENT_SHADERS - flags = ["garment-no-albedo"] if garment and missing_albedo else [] - return { - "name": name, - "shader": shader or "-", - "garment": garment, - "missing_albedo": missing_albedo, - "flags": flags, - "bindings": bindings, - } - - -def classify_file(path: str) -> dict: - """Read one model file and classify every material in it.""" - try: - with open(path, encoding="utf-8-sig") as f: - document = json.load(f) - except json.JSONDecodeError as exc: - raise ValueError(f"{path}: {exc.msg} at line {exc.lineno} column {exc.colno}") from None - return classify_document(path, document) - - -def classify_document(path: str, document: object) -> dict: - models = models_in(document) - if not models: - raise ValueError(f"{path}: no models") - report_models = [] - for model in models: - materials = [] - material_list = [] - for key in MATERIAL_LISTS: - if isinstance(model.get(key), list): - material_list = model[key] - break - for index, material in enumerate(material_list): - if not isinstance(material, dict): - continue - materials.append(classify_material(material, index)) - report_models.append({"name": model_name(model, path), "source": path, "materials": materials}) - return {"models": report_models} - - -def model_files(targets: list) -> list[str]: - """Resolve explicit files and recurse into directories for model.json, de-duplicated.""" - def scan_failed(exc: OSError) -> None: - raise exc - - found = [] - for target in targets: - if os.path.isdir(target): - matches = sorted(os.path.join(root, name) - for root, _, names in os.walk(target, onerror=scan_failed) for name in names - if name.lower() == "model.json") - if not matches: - raise ValueError(f"no model.json under {target}") - found.extend(matches) - elif os.path.isfile(target): - found.append(target) - else: - raise FileNotFoundError(target) - unique = [] - seen = set() - for path in found: - key = path_key(path) - if key not in seen: - seen.add(key) - unique.append(path) - return unique - - -def build_report(sources: list) -> dict: - """Classify every source and add the summary and warning lines.""" - report = {"models": []} - warnings = [] - material_count = 0 - binding_count = 0 - unknown_count = 0 - flagged = 0 - for path in sources: - file_report = classify_file(path) - for model in file_report["models"]: - for material in model["materials"]: - material_count += 1 - binding_count += len(material["bindings"]) - unknown_count += sum(1 for b in material["bindings"] if b["role"].startswith("unknown 0x")) - if material["flags"]: - flagged += 1 - warnings.append( - f"garment-no-albedo {model['name']} / {material['name']} ({material['shader']}): " - f"no 0x{ALBEDO_SLOT} binding; speculartex is not colour") - report["models"].extend(file_report["models"]) - report["summary"] = { - "models": len(report["models"]), - "materials": material_count, - "bindings": binding_count, - "unknown_slots": unknown_count, - "garment_without_albedo": flagged, - } - report["warnings"] = warnings - return report - - -def report_rows(report: dict) -> list[dict]: - """Flatten the report to one row per binding (or one placeholder row per empty material).""" - rows = [] - for model in report["models"]: - for material in model["materials"]: - bindings = material["bindings"] or [{"slot": "-", "role": "no-bindings", "texture": "-"}] - for binding in bindings: - rows.append({ - "source": model["source"], - "model": model["name"], - "material": material["name"], - "shader": material["shader"], - "slot": binding["slot"], - "role": binding["role"], - "texture": binding["texture"], - "flags": ";".join(material["flags"]), - "asset_key": binding.get("asset_key"), - }) - return rows - - -def print_report(report: dict) -> None: - print("model\tmaterial\tslot\trole\ttexture\tasset_key") - for row in report_rows(report): - print(*(_one_line(row[key]) for key in ("model", "material", "slot", "role", "texture")), - row["asset_key"] or "-", sep="\t") - for warning in report["warnings"]: - print(f"FLAG {warning}") - summary = report["summary"] - print(f'{summary["models"]} models, {summary["materials"]} materials, ' - f'{summary["bindings"]} bindings, {summary["unknown_slots"]} unknown slots, ' - f'{summary["garment_without_albedo"]} garment materials without albedo') - - -def _make_parent(path: str) -> None: - parent = os.path.dirname(os.path.abspath(path)) - if parent: - os.makedirs(parent, exist_ok=True) - - -def write_csv(path: str, rows: list) -> None: - _make_parent(path) - with open(path, "w", newline="", encoding="utf-8") as f: - writer = csv.DictWriter(f, fieldnames=CSV_FIELDS, lineterminator="\n", extrasaction="ignore") - writer.writeheader() - writer.writerows(rows) - - -def write_json(path: str, report: dict, rows: list) -> None: - _make_parent(path) - public = {"summary": report["summary"], "warnings": report["warnings"], - "models": report["models"], "rows": rows} - with open(path, "w", encoding="utf-8", newline="\n") as f: - json.dump(public, f, indent=2) - f.write("\n") - - -def check_report_path(parser: argparse.ArgumentParser, flag: str, path: str, sources: list) -> None: - if os.path.isdir(path): - parser.error(f"{flag} is a directory: {path}") - for source in sources: - if same_report_path(path, source): - parser.error(f"{flag} would overwrite the input {source}") - - -def main() -> int: - parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) - parser.add_argument("targets", nargs="+", help="decoded model.json file(s), or a directory searched recursively") - parser.add_argument("--json", metavar="FILE", help="write the full per-material report as JSON") - parser.add_argument("--csv", metavar="FILE", help="write one row per texture binding as CSV") - args = parser.parse_args() - - if args.json and args.csv and same_report_path(args.json, args.csv): - parser.error("--json and --csv must use different paths") - try: - sources = model_files(args.targets) - except FileNotFoundError as exc: - print(f"not found: {exc}", file=sys.stderr) - return 2 - except (OSError, ValueError) as exc: - print(f"ERROR: {exc}", file=sys.stderr) - return 2 - for flag, path in (("--json", args.json), ("--csv", args.csv)): - if path: - check_report_path(parser, flag, path, sources) - - try: - report = build_report(sources) - except (OSError, ValueError, KeyError, TypeError) as exc: - print(f"ERROR: {exc}", file=sys.stderr) - return 2 - - rows = report_rows(report) - print_report(report) - for path, writer, values in ((args.json, write_json, (report, rows)), - (args.csv, write_csv, (rows,))): - if path: - try: - writer(path, *values) - except OSError as exc: - print(f"ERROR: cannot write {path}: {exc.strerror or exc}", file=sys.stderr) - return 2 - print("wrote", path) - return 0 - - -if __name__ == "__main__": - try: # a redirected stdout is strict ANSI code page under -I; write '?' for what it cannot encode - sys.stdout.reconfigure(errors="replace") - except (AttributeError, ValueError, OSError): - pass - sys.exit(main()) diff --git a/tools/classify_carve.py b/tools/classify_carve.py deleted file mode 100644 index 88e09fcc3..000000000 --- a/tools/classify_carve.py +++ /dev/null @@ -1,140 +0,0 @@ -"""Group every carved file by signature, using only the per-archive index.json (no file reads). - -Classes: - bink2 Bink 2 video (KB2x) - rbf0 Rockstar binary metadata ('RBF0', carries its own field names) - respage resource page ('42 40 00 00': tagged-pointer structures for textures/meshes/etc.) - gpu-zerohdr starts with 16+ zero bytes (GPU data: textures, vertex/index buffers) - other: anything else, keyed by its first 4 bytes - -Usage: - python -I tools/classify_carve.py \\carve -Writes types.json (per archive and overall counts/bytes per class, plus size stats) and prints a summary. -Every per-class entry, overall and per archive, is {"files": N, "bytes": B, "min": ..., "max": ..., "median": ...}: -min, max and median are the smallest, largest and median file size in bytes among the files of that class in that -scope. For an even count the median is the lower of the two middle sizes (statistics.median_low), so every value -in the report is an integer. A class only appears when it has at least one file, so the stats keys are never null. -The tool keeps one size (a plain Python int) per file per class to compute these. -""" -import json -import os -import sys -import tempfile -from collections import defaultdict -from statistics import median_low - -sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) -from file_mode import published_mode # noqa: E402 - - -def classify(r): - if r.get("type") == "bink2": - return "bink2" - h = r["head"] - if h.startswith("52424630"): - return "rbf0" - if h.startswith("42400000"): - return "respage" - if h.startswith("00000000000000000000000000000000"): - return "gpu-zerohdr" - return "other:" + h[:8] - - -def index_rows(path): - with open(path, encoding="utf-8-sig") as f: - try: - document = json.load(f) - except (ValueError, RecursionError): - raise ValueError("invalid JSON") from None - rows = document.get("files") if isinstance(document, dict) else None - if not isinstance(rows, list): - raise ValueError('expected a "files" list') - - for number, row in enumerate(rows, 1): - if not isinstance(row, dict) or type(row.get("size")) is not int or row["size"] < 0: - raise ValueError(f"row {number} needs a nonnegative integer size") - if row.get("type") != "bink2" and not isinstance(row.get("head"), str): - raise ValueError(f"row {number} needs a string head") - yield row - - -def entry(v): - sizes = v[2] - return {"files": v[0], "bytes": v[1], "min": min(sizes), "max": max(sizes), "median": median_low(sizes)} - - -USAGE = "usage: python -I tools/classify_carve.py \\carve" - - -def main(): - if sys.argv[1:] in (["-h"], ["--help"]): - print(USAGE) - return 0 - if len(sys.argv) != 2: - print(USAGE, file=sys.stderr) - return 2 - root = sys.argv[1] - if not os.path.isdir(root): - what = "is not a folder" if os.path.exists(root) else "does not exist" - print(f"{root}: {what}; give the carve folder (the one with an index.json per archive)", file=sys.stderr) - return 2 - report = os.path.join(root, "types.json") - if os.path.isdir(report): - print(f"{report}: is a directory; remove or rename that directory before rerun", file=sys.stderr) - return 2 - per = {} - total = defaultdict(lambda: [0, 0, []]) - try: - entries = sorted(os.listdir(root)) - except OSError as error: - print(f"{root}: {error}", file=sys.stderr) - return 2 - for name in entries: - p = os.path.join(root, name, "index.json") - if not os.path.isfile(p): - continue - c = defaultdict(lambda: [0, 0, []]) - try: - for r in index_rows(p): - k = classify(r) - c[k][0] += 1 - c[k][1] += r["size"] - c[k][2].append(r["size"]) - total[k][0] += 1 - total[k][1] += r["size"] - total[k][2].append(r["size"]) - except (OSError, ValueError) as error: - print(f"{p}: {error}", file=sys.stderr) - return 2 - per[name] = {k: entry(v) for k, v in sorted(c.items(), key=lambda kv: -kv[1][1])} - top = sorted(total.items(), key=lambda kv: -kv[1][1]) - out = {"overall": {k: entry(v) for k, v in top}, "per_archive": per} - dest = os.path.realpath(report) - dest_dir = os.path.dirname(dest) or root - fd, temp = tempfile.mkstemp(dir=dest_dir, prefix=".types-", suffix=".tmp") - try: - with os.fdopen(fd, "w", encoding="utf-8", newline="\n") as f: - json.dump(out, f, indent=1) - f.flush() - os.fsync(f.fileno()) - os.chmod(temp, published_mode(dest)) # mkstemp creates 0600 - os.replace(temp, dest) - except BaseException: - try: - os.unlink(temp) - except OSError: - pass - raise - print(f"{'class':24} {'files':>10} {'GiB':>8}") - for k, v in top[:25]: - print(f"{k:24} {v[0]:>10} {v[1] / 2**30:8.2f}") - print(f"{len(top)} classes in total") - return 0 - - -if __name__ == "__main__": - try: # a redirected stdout is strict ANSI code page under -I; write '?' for what it cannot encode - sys.stdout.reconfigure(errors="replace") - except (AttributeError, ValueError, OSError): - pass - sys.exit(main()) diff --git a/tools/conformance/COMPARE.md b/tools/conformance/COMPARE.md deleted file mode 100644 index 30c2b3b84..000000000 --- a/tools/conformance/COMPARE.md +++ /dev/null @@ -1,408 +0,0 @@ -# compare.py - pixel conformance checker and renderer diff - -`compare.py` verifies rendered PNGs against the pixel checks a renderer's -`manifest.json` declares, and measures how far one renderer's scenes are from -another's. It reads PNG and JSON only: it never parses C++ or `scenes.h`. Every -expectation comes from the manifest, so the same tool works for the native -D3D12 renderer, the Vulkan-backed shim and any future scene. - -Standard library only. Tested with Python 3.12.10 on Windows (the conformance -box). Python 3.8 or newer is needed for the language features used. - -``` -D:\conform\tools\ - compare.py the tool - README.md this file -``` - -On the conformance box: - -```powershell -& "$env:LOCALAPPDATA\Programs\Python\Python312\python.exe" D:\conform\tools\compare.py --help -``` - -Elsewhere, `python compare.py --help` is enough. - -## Manifest contract - -The tool consumes exactly the shape the renderers write: - -```json -{ - "renderer": "native", - "adapter": "NVIDIA GeForce RTX ...", - "scenes": [ - { - "name": "clear", - "png": "clear.png", - "checks": [ - {"x": 0, "y": 0, "r": 10, "g": 20, "b": 30, "a": 255, - "why": "top-left is the clear colour"} - ] - } - ] -} -``` - -The manifest must be UTF-8; a UTF-8 BOM (which PowerShell may add) is accepted. -Each JSON object must have unique keys. A repeated field, including a channel in a pixel check, -is an input error rather than a last-value-wins override. - -Validation rules, all reported with the manifest path and the exact scene/check -position: - -- `renderer` and `adapter` are required strings (`adapter` may be empty). -- `scenes` is a non-empty list. Each scene needs a unique `name`, a unique `png` - file name beside the manifest (no directories), and a non-empty `checks` list. - A scene with no checks is rejected: it would prove nothing. -- A check needs integer `x`, `y` (0 or more) and `r`, `g`, `b`, `a` (0-255). - `why` is optional; when present it is quoted in a failure line. -- The number of checks is not assumed. The current scene contract uses 2 to 5 - per scene; `expect` evaluates however many are declared. -- Unknown extra keys are ignored so a newer renderer can add metadata without - breaking this tool. - -The scene `name` is also used for the heatmap file `.diff.png`, so names -that are Windows-illegal or contain a path separator are rejected at load with -an explanation rather than failing later during a write. - -## Orientation and channel order - -These are contract conventions and the reader follows them literally: - -- Image row 0 is the **top** of the image and corresponds to NDC y = +1. The - reader does not flip rows, and the writer does not flip them either. -- Channels are stored and interpreted in **R, G, B, A** order, 8 bits each. The - reader does not reorder channels. -- **A vertical flip is the single most common reason a GPU diff looks like a - total mismatch.** `inspect` always prints labelled top-left and bottom-right - values so a flip is obvious at a glance, and `selftest` includes an image whose - top and bottom halves differ so the tool's own orientation is proven. - -## expect - verify declared pixels - -```powershell -python compare.py expect --manifest D:\conform\native\manifest.json -python compare.py expect --manifest D:\conform\shim\manifest.json --dir D:\conform\shim\renders -``` - -`--dir` is optional; without it, PNGs are read from the manifest's directory. - -Output is one line per declared check, then a summary. This is an excerpt from a -shim run against an 18-check manifest: - -``` -PASS fullscreen (128,128) expected 200,30,60,255 got 200,30,60 -FAIL fullscreen (8,8) expected 200,30,60,255 got 10,20,30 (top-left corner is covered) -FAIL blend (128,128) expected 105,25,45,255 got 200,30,60 (0.5*(200,30,60) + 0.5*(10,20,30) = (105,25,45)) - -6 scenes, 18 checks: 8 passed, 10 failed -``` - -- `got` prints the channels actually stored: three for an RGB file, four for - RGBA. An RGB file has no alpha channel, so it is compared as if alpha were 255. - A check that declares any other alpha against an RGB file fails and says why. -- A pixel outside the image is a failure that names the coordinate and the - image's size. The scene's other checks still run. -- A missing, truncated or corrupt image is one scene-level FAIL carrying the - reader's message (path, byte offset or CRC), and the scene's declared checks - are counted as failed in the summary. -- Exit code is 0 only when every check passed. - -`expect` does not verify that the manifest's checks are the right expectations. -That is the scene contract's job; this tool checks the pixels against whatever -the manifest declares. - -## diff - compare two renderers - -```powershell -python compare.py diff --reference D:\conform\native\manifest.json --candidate D:\conform\shim\manifest.json -``` - -Both manifests must declare the same scene names; each manifest's own `png` -field is used to find its image, so the two renderers may name files -differently. Images must have equal dimensions. - -Per scene the row reports: - -- **differing**: number of pixels where any R, G, B or A channel differs, and - that count as a percentage of width x height. -- **mean**: mean absolute channel delta over every channel of every pixel. The - denominator is `width * height * 4`, so an RGB image contributes zero alpha - deltas and a small area failing hard is distinguishable from a large area - failing softly. -- **max**: largest single-channel delta in the scene. -- **first**: first differing pixel in row-major order (top row first, left to - right within a row), or `-` when identical. - -Thresholds are strict `>` comparisons and both default to `0.0`, so any -difference fails: - -``` ---max-differing-percent FLOAT fail above this percent of differing pixels ---max-mean-delta FLOAT fail above this mean absolute channel delta -``` - -NaN, infinity and negative values are rejected by the argument parser rather -than silently passing everything. - -Example (the native and shim fixture run, shortened): - -``` -PASS clear differing 0/65536 (0.000%) mean 0.0000 max 0 first - -FAIL fullscreen differing 256/65536 (0.391%) mean 0.2246 max 190 first (8,8) (differing pixels 0.391% exceed --max-differing-percent 0.000%) -FAIL depth_order differing 34648/65536 (52.869%) mean 46.2601 max 180 first (6,6) (differing pixels 52.869% exceed --max-differing-percent 0.000%) -FAIL scissor differing 57344/65536 (87.500%) mean 78.7500 max 180 first (0,0) (differing pixels 87.500% exceed --max-differing-percent 0.000%) -FAIL blend differing 65536/65536 (100.000%) mean 28.7500 max 95 first (0,0) (differing pixels 100.000% exceed --max-differing-percent 0.000%) - scene 'blend': every pixel differs - usually the scene's tint (constant buffer b0) or clear colour, before chasing rasterisation -FAIL indexed differing 10230/65536 (15.610%) mean 18.7317 max 200 first (51,51) (differing pixels 15.610% exceed --max-differing-percent 0.000%) - -6 scenes compared, 5 exceed the thresholds. Heatmaps written beside the candidate images as .diff.png -``` - -When **every** pixel differs, the tool prints a second, indented line naming the -scene and pointing at the most likely cause: - -``` - scene 'fullscreen': every pixel differs - usually the scene's tint (constant buffer b0) or clear colour, before chasing rasterisation -``` - -Each scene's tint is distinct in the current contract, so a whole frame of the -wrong colour is usually a constant-buffer value, not rasterisation. The scene -name is already at the start of the row; the extra line makes that diagnosis -impossible to miss. - -### Heatmap - -For every scene, `diff` writes `.diff.png` beside the candidate image, -same size as the candidate: - -- unchanged pixels: dark grey `(48, 48, 48)`, not black, so a black render pixel - cannot hide in the background; -- differing pixels: `delta` is the largest absolute channel difference at that - pixel. Red is `round(255 * (delta - 1) / 254)`, green is 0, blue is - `255 - red`. Delta 1 is pure blue `(0, 0, 255)`, delta 255 is pure red - `(255, 0, 0)`, and the ramp passes through purple. Alpha differences count. - -Heatmaps are written for passing scenes too, so a clean run leaves a complete -visual record. Existing files are overwritten. The tool is deterministic: the -same inputs produce byte-identical heatmaps (verified with SHA-256 over two -runs). - -### diff failures that are not pixel differences - -- Missing or extra scene names in the candidate manifest: error names them and - exits 2. There is nothing meaningful to compare. -- Different image sizes: error names both paths and their sizes and exits 2. -- Unreadable or unsupported image: error names the file and exits 2. - -A pixel comparison that ran and exceeded a threshold exits 1. - -## inspect - look at one image - -```powershell -python compare.py inspect --image D:\conform\shim\clear.png -python compare.py inspect --image D:\conform\shim\clear.png --pixel 0,0 --pixel 128,128 -``` - -Top-left and bottom-right are always printed with explicit coordinates. Without -`--pixel`, top-right, bottom-left and the centre are printed too. With -`--pixel X,Y` (repeatable), the requested pixels follow the two labelled corners. - -``` -fixtures/native/clear.png - 256 x 256, RGB, 8 bits per channel, non-interlaced - top-left (0,0) = 10,20,30 - bottom-right (255,255) = 10,20,30 - no --pixel given; also showing top-right, bottom-left and centre - top-right (255,0) = 10,20,30 - bottom-left (0,255) = 10,20,30 - centre (128,128) = 10,20,30 -``` - -RGB prints three values, RGBA four. A pixel outside the image is an error naming -the coordinate and the image size; exit code 2. - -## selftest - prove the tool without external files - -```powershell -python compare.py selftest -``` - -It creates a temporary directory, writes fixture PNGs, asserts the behaviours -below, removes the directory, and exits 1 on the first mismatch (naming the -assertion, expected value and actual value). - -``` -selftest: fixtures in C:\Users\Hussain\AppData\Local\Temp\compare-selftest-wf7w_kkg -ok PNG round-trip: RGB pixels and alpha-free pixel reads -ok PNG round-trip: RGBA rectangle at (2,1)-(5,4), alpha 200 preserved -ok PNG writer is deterministic: two writes of one raster match byte for byte -ok failure path: unwritable output directory names the path -ok failure path: corrupt IDAT reports the CRC and byte offset -ok failure path: truncated file reports the byte offset -ok PNG filters 0-4 decode: hand-computed streams for a 3x2 RGB fixture -ok failure path: short filter data and undefined filter type are rejected -ok arguments: thresholds reject negative, NaN, inf and text; pixels need x,y -ok orientation: top and bottom halves survive; inspect labels both corners -ok expect: a five-check manifest exits 0 and prints five PASS rows -ok manifest reader accepts a UTF-8 BOM, as PowerShell writes -ok expect: wrong pixel and out-of-range coordinate fail with explanations -ok expect: a missing image fails once for the scene and names the path -ok failure path: a scene with no checks is rejected, not silently passed -ok diff metrics: 2 known pixels give exact count, percent, mean, max and first -ok heatmap: grey unchanged, red at delta 255, blue at delta 1 -ok diff edge cases: row-major first difference, alpha-only delta, tint hint -ok failure path: mismatched image sizes refuse to compare and say so -ok diff: changed scene exits 1 and writes clear.diff.png beside the candidate -ok diff: generous thresholds pass the same scene without hiding its delta -selftest passed -``` - -### What selftest proves - -- **PNG writer and reader**: an 8x6 RGB image round-trips byte for byte; an 8x6 - RGBA image round-trips with a known rectangle at x 2..5, y 1..4 and alpha 200 - preserved at its corners and clear outside it. A second write of the same - raster is byte-identical. -- **PNG filters**: all five filter types decode a 3x2 RGB fixture whose filtered - streams were computed independently from the filter definitions; filter 0, 1, - 2, 3 and 4 each reconstruct the same pixels. Short filtered data and a filter - type of 5 are rejected with the reason (and the row for an undefined type). -- **PNG failure paths**: writing into a missing directory fails with the path; - a flipped byte inside IDAT fails with a CRC mismatch and byte offset; a - truncated file fails naming the truncation. None of these crash or write a - zero-byte file. -- **Arguments**: thresholds accept 0 and 1.5 and reject negative, NaN, infinity - and text; `--pixel` requires x,y and rejects malformed values. -- **Orientation and channel order**: a 4x4 image with a red top half and a blue - bottom half round-trips with row 0 still red and row 3 still blue, channels - still R,G,B, and `inspect` labels both corners with those values. A row flip - or a BGR swap would fail this step. -- **expect**: a manifest with five checks (one per corner plus the centre) - passes, prints five PASS rows and exits 0; a wrong expectation and an - out-of-range coordinate both fail with explanations and exit 1; a missing - image produces one scene-level failure naming the path; a scene with an empty - check list is rejected at load. A manifest with a UTF-8 BOM still loads. -- **diff metrics**: a known two-pixel change in a 4x3 image produces exact - differing count, total pixels, percent, mean absolute delta, maximum delta and - first coordinate. Identical images report zero. A 100%-different frame gets - the wrong-tint hint naming the scene; a partial difference gets none. -- **diff edge cases**: first difference follows row-major order (a change at - (3,0) wins over (0,1)); an alpha-only change against an RGB reference is - counted with delta 1; mismatched image sizes refuse to compare with both sizes - in the message. -- **diff command**: a changed scene exits 1, writes `clear.diff.png` beside the - candidate, and the written heatmap marks a delta-255 pixel pure red. The same - scene passes with generous thresholds while still printing its pixel count. -- **heatmap colours**: unchanged is dark grey, delta 255 is red, delta 1 is blue - in the built raster before it is written. - -### What selftest does not prove - -- **Independent PNG encoders.** Selftest's PNGs come from the tool's own writer, - and the filter fixtures are hand-built byte streams. Separately, during - development, the reader was cross-checked on macOS against Pillow 13.0.0: 16 - images (RGB and RGBA; 1x1, 2x3, 17x9, 256x256; `optimize` on and off) decoded - byte for byte, and their IDAT streams were observed to use filter types 0, 1, - 2, 3 and 4. Pillow is not installed on the conformance box and is not a - dependency of this tool, so that check is not part of `selftest`. -- **The full command-line parser.** Selftest calls the command functions and the - two argument type functions directly. The transcripts in this README exercise - the real `argparse` wiring on Windows. -- **Unsupported PNG variants.** 16-bit, palette, grayscale and interlaced files - are rejected by the reader with specific messages, but selftest does not - construct each one. -- **Huge or hostile inputs.** There is no decompressed-size cap beyond the - expected length check; a deliberately enormous or adversarial PNG is not - tested. -- **Performance.** 256x256 is fast; a multi-megapixel image is not benchmarked. -- **That the manifest's checks are correct.** It proves the tool, not the scene - contract. - -## Exit codes - -| Code | Meaning | -| --- | --- | -| 0 | Everything the mode checked passed. | -| 1 | The mode ran and found a mismatch: a failed check, a threshold exceeded, or a selftest assertion failed. | -| 2 | The mode could not run: bad arguments, missing/unreadable/invalid manifest, unreadable image, mismatched sizes, or an unwritable heatmap path. | - -`argparse` also exits 2 for malformed command lines, which matches the table. - -## Known limits and deliberate omissions - -- **No enforced 256x256.** The manifest has no size field, so `expect` only - fails when a declared coordinate falls outside the image. A wrong-size image - whose checks all happen to be in range passes. `diff` does refuse to compare - images of different sizes. If a size gate is wanted, add width/height to the - manifest rather than hard-coding 256 in the tool. -- **PNG support is exactly the contract**: 8-bit RGB (type 2) or RGBA (type 6), - non-interlaced, filter types 0-4. Everything else is rejected with a message. - RGB must be opaque: `tRNS` transparency is rejected rather than silently treated - as opaque. Re-export such images as RGBA with an explicit alpha channel. -- **No colour management.** Ancillary chunks such as gAMA, sRGB and iCCP are - ignored; pixels are compared exactly as stored. This matches the scene - contract's "no sRGB conversion". -- **APNG** is read as its default image; animation chunks are ancillary and - ignored. -- **Exact matching in expect.** No per-channel tolerance. Use `diff` thresholds - when measuring drift. -- **A global diff threshold**, not per-scene or per-channel limits. -- **Mean is always over four channels.** For RGB files the alpha term is zero, - which is deliberate and consistent. -- **Heatmap is RGB** and encodes the per-pixel maximum channel delta, not the - sum, and not a perceptual metric (no SSIM or Delta-E). -- **Manifest names are file-name constrained** because they become - `.diff.png`; `png` must be a base name beside the manifest. Unknown - extra JSON keys are ignored. -- **No batch/report output**: no recursive directory scan, no JSON or JUnit - output, no parallelism. Run it once per manifest pair. -- **Stale heatmaps are not removed.** Scenes deleted from a manifest leave their - old `.diff.png` beside the candidate until deleted by hand. -- **The writer always uses filter 0.** The reader handles all five, which is the - part that matters for reading other encoders. -- **Python speed.** Plain nested loops are used for clarity; 256x256 is - immediate, very large images will be slower than a vectorised decoder. - -## What changed in review - -The review standard asks for findings, fixes, evidence. These are the real -changes made after the first working version. - -| Finding | Fix | Evidence | -| --- | --- | --- | -| `build_argument_parser` grew to 92 lines, past the one-screen rule. | Split into `add_expect_command`, `add_diff_command`, `add_inspect_command`, `add_selftest_command`; the builder is now 29 lines. | AST check reports no function over 60 lines. | -| 57 functions had no summary of what they do. | Added one-line docstrings to every function, plus fuller docstrings where a decision needs explanation. | AST check reports no function without a docstring. | -| `step_png_error_paths` read `solid.png` created by an earlier selftest step, an invisible ordering dependency. | The step now writes its own `error-fixture.png`. | Selftest passes; no step reads a file another step was assumed to have left. | -| Two paeth fixture bytes were wrong, so selftest failed on its own fixture rather than on the decoder. | Recomputed all five filtered streams with a separate throwaway encoder and corrected the fixture bytes (251 -> 30, 85 -> 30). | Filter step passes; reader cross-checked against Pillow on adaptive-filter PNGs using all five filters. | -| The heatmap endpoint test asserted pure red at deltas of 245 and 190, so the red end of the ramp was never tested. | Fixtures changed to reference red 0, candidate red 255, giving delta 255. | "heatmap delta 255 pixel is red" and the written-file check both pass. | -| Manifests written by PowerShell with a UTF-8 BOM failed to parse. | Decode with `utf-8-sig`; selftest writes and loads a BOM manifest. | Selftest line "manifest reader accepts a UTF-8 BOM". | -| `Raster.colour_name` would have called any unknown colour type "RGBA". | It now asks `channels_for_colour_type`, which validates. | Code path is shared with the reader; invalid types are rejected before a Raster exists. | -| `diff` used the reference manifest's PNG file name to locate the candidate image, so different file names in the two manifests were ignored. | `diff` now looks up the candidate scene by name and uses the candidate manifest's own `png` field. | Selftest's candidate file is `shim-clear.png` while the reference is `clear.png`, and diff passes. | -| `--max-mean-delta nan` parsed as a float; every `>` comparison against NaN is false, so all scenes would pass. | Threshold parser rejects non-finite values; selftest rejects NaN and infinity. | Selftest line "arguments: thresholds reject negative, NaN, inf and text". | -| The revised scene contract allows 2-5 checks and makes `expect` handle any count. | No code assumption existed; selftest now uses five checks and asserts five PASS rows. | Selftest line "expect: a five-check manifest exits 0". | -| The revised contract makes row order and channel order explicit. | Added an orientation selftest and labelled corner output in `inspect`; README states the flip failure mode. | Selftest line "orientation: top and bottom halves survive". | -| The revised contract wants whole-frame colour failures blamed on the tint. | `diff` prints a scene-named hint whenever every pixel differs. | Selftest asserts the hint names the scene and mentions the tint; manual wrong-tint transcript shows one line per scene. | -| A diff that failed after printing its header showed the stderr error above the header when output was captured. | `diff` and `inspect` flush stdout after the header, before a later read can fail. | The Windows wrong-size transcript now shows the header and then the error. | - -## Review pass 2 — corrections - -The legibility review found three claims in this README that the code did not support. They are corrected -here rather than silently rewritten above: - -- **Exit codes are not identical in every mode.** `expect` treats an unreadable or missing image as a failed - scene and exits **1**; `diff` exits **2** when it cannot compare (missing manifest, size mismatch). Both - mean "the run did not complete", but only `diff` returns 2 for them. A crash that the tool did not - anticipate now exits **2** with a traceback, never 1, so a calling script can tell "the pixels differ" - from "this program failed". -- **The whole-frame mean does not separate "small area failing hard" from "large area failing softly".** - One pixel off by 255 and 255 pixels off by 1 give the same mean. Read the mean together with - `differing` and `max`. -- **The whole-frame hint names pixel values now.** It previously blamed the tint. An unblended draw of the - correct colour also differs everywhere, and so does a scene that was never drawn; the first differing - pixel's reference and candidate RGBA values are printed so a reader can tell those apart. - -Also fixed: a failing `selftest` keeps its fixture directory and prints the path instead of deleting the -evidence, and a `ToolError` raised inside selftest is reported as a selftest failure (exit 1) rather than a -usage error. diff --git a/tools/conformance/README.md b/tools/conformance/README.md deleted file mode 100644 index d39104bbe..000000000 --- a/tools/conformance/README.md +++ /dev/null @@ -1,107 +0,0 @@ -# Conformance harness: does the Vulkan-backed D3D12 device render what D3D12 renders? - -The shim in `runtime/` reimplements D3D12 on Vulkan. Its device, resource, view, sampler, -copy, clear and barrier paths are covered by `runtime/test/`, but nothing today checks the -thing that matters most: **that a draw produces the same pixels as the host's D3D12.** - -This harness defines a small set of deterministic scenes, renders them with native D3D12 on -the same machine, and checks every pixel that the scene claims. When the shim's draw path -lands, the same scenes go through it and the two image sets are diffed. - -## Layout - -``` -tools/conformance/ - spec/scenes.h the contract: scene kinds, geometry, state, expected pixels - spec/shaders/*.hlsl the two shader pairs, compiled by dxc - native/ native D3D12 reference renderer (Windows, D3D12 + WIC) - compare.py check a render against the contract, diff two renders - COMPARE.md compare.py's modes, exit codes and limits -``` - -## The scenes - -Seven scenes, each chosen to make one failure visible at an exact coordinate: - -| scene | proves | -|---|---| -| `clear` | render target creation, clear value, readback | -| `fullscreen` | vertex shader runs, pipeline binds, one triangle covers the target | -| `depth_order` | depth test rejects a later draw that is behind (green survives over red only because of it) | -| `scissor` | scissor clips at `{48,32,176,96}`, right/bottom exclusive | -| `blend` | 50% source over the clear colour, `SRC_ALPHA`/`INV_SRC_ALPHA` | -| `indexed` | the index buffer is read; vertices are stored out of draw order | - -The contract states the baseline pipeline state every scene inherits (cull NONE, -`TRIANGLELIST`, sample mask, viewport, clip-space z in 0..1 with `w = 1`, row 0 is the top). -Anything an implementer would otherwise have to guess is written down, because two guesses -that disagree produce two different images and neither is wrong on its own terms. - -## Run it - -```powershell -# 1. build and render the reference images -powershell -NoProfile -ExecutionPolicy Bypass -File tools\conformance\native\scripts\build.ps1 -powershell -NoProfile -ExecutionPolicy Bypass -File tools\conformance\native\scripts\run.ps1 - -# 2. check every declared pixel -python tools\conformance\compare.py expect --manifest tools\conformance\native\out\run1\manifest.json - -# 3. prove the scenes are not vacuous: corrupt three pieces of state and require three failures -powershell -NoProfile -ExecutionPolicy Bypass -File tools\conformance\native\scripts\negative-control.ps1 -``` - -Requirements: Windows with the D3D12 runtime, Visual Studio 2022 (C++ x64), Windows SDK -10.0.26100 (`dxc.exe`), Python 3.10+ for `compare.py` (standard library only; no pip -installs). The renderer needs a D3D12 device with feature level 11_0 — it runs on the -Microsoft Basic Render Driver as well as on hardware. - -## Status today - -Against the shim as of `2e5c0f2`, the driver in the pull request reports: - -``` -clear OK 3/3 pixel checks matched (row pitch 1024, readback 262144 bytes) -fullscreen BLOCKED ID3D12Device::CreateRootSignature (E_NOTIMPL 0x80004001) -depth_order BLOCKED ID3D12Device::CreateRootSignature (E_NOTIMPL 0x80004001) -scissor BLOCKED ID3D12Device::CreateRootSignature (E_NOTIMPL 0x80004001) -blend BLOCKED ID3D12Device::CreateRootSignature (E_NOTIMPL 0x80004001) -indexed BLOCKED ID3D12Device::CreateRootSignature (E_NOTIMPL 0x80004001) -``` - -`clear` already proves the whole resource → clear → barrier → copy → readback chain through -the Vulkan device. The five drawn scenes stop at the first call the shim genuinely lacks, so -each one becomes a progress marker as the draw path lands: `CreateRootSignature` → -`CreateGraphicsPipelineState` → the `SetPipelineState` / root-binding group → viewport and -scissor → vertex/index buffers → `OMSetRenderTargets` → `DrawInstanced` / -`DrawIndexedInstanced`. - -## The shader format question - -The reference renderer compiles HLSL to **DXIL** because native D3D12 requires it. The -shim's documented contract is **SPIR-V**, because the game's shaders reach it from the RDNA2 -translator. A PSO implementation that understands only one of them cannot serve both. - -The cheapest resolution, when the draw path lands: compile each conformance shader twice -(`dxc -T vs_6_6` and `dxc -spirv -T vs_6_6`) and let each renderer take the blob it wants. -One workload, one set of expected pixels, no DXIL translator in the shim. - -## Why the scenes are trustworthy - -Three independent checks, all reproducible: - -1. **The renderer verifies itself.** It reads every declared pixel back from the GPU *and* - from the PNG decoded off disk, prints one line per check, and exits non-zero on any - mismatch. 18 checks, 18 passes, on both the NVIDIA and AMD adapters. -2. **The negative control asserts its own result.** It disables the depth test, the blend - state and the scissor rect in a throwaway copy, then requires exactly `depth_order`, - `blend` and `scissor` to fail — each at the pixel that names the state. If a - `String.Replace` silently stops matching, the script throws instead of reporting success. -3. **Determinism is measured**, not assumed: two runs produce byte-identical PNGs. - -## Extending it - -Add a `Scene` to `spec/scenes.h` with its expected pixels. The renderer picks it up through -`SceneKind`; `/we4062` makes an unhandled enumerator a build error, so a new kind cannot -silently render as a clear-only scene. Add a matching row to the shim driver's switch when -the draw path exists. diff --git a/tools/conformance/compare.py b/tools/conformance/compare.py deleted file mode 100644 index 78454e0f4..000000000 --- a/tools/conformance/compare.py +++ /dev/null @@ -1,1874 +0,0 @@ -#!/usr/bin/env python3 -"""Verify rendered PNGs against declared pixel checks, and diff two renderers. - -Every expectation comes from a manifest.json written by a renderer. This tool -never reads C++ or scene definitions: the images and the manifest are the whole -contract. PNG support is deliberately small and complete for that contract: -8-bit RGB or RGBA, non-interlaced, with all five filter types (0-4), because any -encoder that writes those formats may use any of them. -RGB must be opaque; tRNS transparency is rejected. Use RGBA for explicit alpha. - -Exit codes, identical in every mode: - 0 everything the mode checked passed - 1 the mode ran and found a mismatch (pixels, thresholds or selftest) - 2 the mode could not run (bad arguments, unreadable or invalid input) -""" - -import argparse -import contextlib -import io -import json -import math -import os -import shutil -import sys -import tempfile -import zlib -from dataclasses import dataclass - -EXIT_PASSED = 0 -EXIT_FAILED = 1 -EXIT_ERROR = 2 - -PNG_SIGNATURE = b"\x89PNG\r\n\x1a\n" -PNG_COLOUR_TYPE_RGB = 2 -PNG_COLOUR_TYPE_RGBA = 6 -PNG_BIT_DEPTH_8 = 8 -PNG_COMPRESSION_DEFLATE = 0 -PNG_FILTER_ADAPTIVE = 0 -PNG_INTERLACE_NONE = 0 -OPAQUE_ALPHA = 255 -MAX_CHANNEL_VALUE = 255 - -# Diff arithmetic always works on RGBA so an RGB reference and an RGBA candidate -# are comparable; RGB images supply an implicit alpha of 255. -RGBA_CHANNEL_COUNT = 4 - -FILTER_NONE = 0 -FILTER_SUB = 1 -FILTER_UP = 2 -FILTER_AVERAGE = 3 -FILTER_PAETH = 4 - -# Dark grey rather than black so that a black pixel in a near-black render does -# not vanish into the "unchanged" background of a heatmap. -HEATMAP_UNCHANGED = (48, 48, 48) - -# Coordinates beyond this are certainly a manifest bug, not a big render. -MAX_SANE_COORDINATE = 1_000_000 - -# Heatmaps are written as ".diff.png", so a scene name must be usable as -# a file name. These are Windows' forbidden characters; the tool runs on Windows. -UNSAFE_FILE_NAME_CHARACTERS = '<>:"/\\|?*' - - -class ToolError(Exception): - """A problem the operator can act on: bad input, or a comparison that cannot run.""" - - -class SelftestMismatch(Exception): - """A selftest expectation did not hold; the message names the expectation.""" - - -# --------------------------------------------------------------------------- -# PNG reading and writing -# --------------------------------------------------------------------------- - - -@dataclass -class Raster: - """Decoded pixels plus the metadata a caller needs to interpret them.""" - - width: int - height: int - colour_type: int - pixels: bytearray - source_path: str - - def channels(self): - """Return 3 or 4, matching the stored PNG colour type.""" - return channels_for_colour_type(self.colour_type, self.source_path) - - def colour_name(self): - """Return the PNG colour type as a short display name.""" - return "RGB" if self.channels() == 3 else "RGBA" - - def stored_pixel(self, x, y): - """Return the channels actually stored at (x, y), three or four values.""" - if x < 0 or y < 0 or x >= self.width or y >= self.height: - raise ToolError( - f"pixel ({x},{y}) is outside the {self.width}x{self.height} image " - f"'{self.source_path}'; check the requested coordinate or the render size" - ) - channels = self.channels() - offset = (y * self.width + x) * channels - return tuple(self.pixels[offset:offset + channels]) - - def pixel_rgba(self, x, y): - """Return (r, g, b, a); RGB images are opaque, because they store no alpha.""" - stored = self.stored_pixel(x, y) - if self.colour_type == PNG_COLOUR_TYPE_RGB: - return stored + (OPAQUE_ALPHA,) - return stored - - -def channels_for_colour_type(colour_type, source_path): - """Return 3 channels for RGB and 4 for RGBA; reject every other PNG colour type.""" - if colour_type == PNG_COLOUR_TYPE_RGB: - return 3 - if colour_type == PNG_COLOUR_TYPE_RGBA: - return 4 - raise ToolError( - f"'{source_path}': PNG colour type {colour_type} is not supported; " - f"only 2 (RGB) and 6 (RGBA) are. Re-export without a palette or grayscale mode" - ) - - -def read_file_bytes(path, description): - """Read a file whole, naming the path and the OS error when it cannot.""" - try: - with open(path, "rb") as file_handle: - return file_handle.read() - except OSError as error: - raise ToolError( - f"cannot read {description} '{path}': {error.strerror or error}. " - f"Check that the file exists and is readable" - ) - - -def read_text_file(path, description): - """Read UTF-8 text, accepting an optional BOM, naming the bad byte on failure.""" - raw_bytes = read_file_bytes(path, description) - try: - # utf-8-sig accepts a BOM, which PowerShell-written manifests may carry. - return raw_bytes.decode("utf-8-sig") - except UnicodeDecodeError as error: - raise ToolError( - f"'{path}' is not valid UTF-8 text: byte {error.start} is invalid. " - f"Check that the file was not saved in a legacy code page" - ) - - -def write_file_bytes(path, data, description): - """Write bytes into an existing directory; never creates one.""" - try: - with open(path, "wb") as file_handle: - file_handle.write(data) - except OSError as error: - raise ToolError( - f"cannot write {description} '{path}': {error.strerror or error}. " - f"Check that the directory exists and is writable" - ) - - -def split_png_chunks(file_bytes, source_path): - """Split a PNG into (type, data) chunks, verifying every length and CRC. - - IEND ends the chunk list; bytes after it are rejected rather than ignored so a - concatenated or padded file is reported instead of silently half-read. - """ - if not file_bytes.startswith(PNG_SIGNATURE): - raise ToolError( - f"'{source_path}' is not a PNG: the 8-byte signature is missing. " - f"Check that the renderer wrote a PNG and not a raw or JPEG dump" - ) - - chunks = [] - offset = len(PNG_SIGNATURE) - while True: - header_end = offset + 8 - if header_end > len(file_bytes): - raise ToolError( - f"'{source_path}': truncated chunk header at byte offset {offset}; " - f"the file ends before the chunk length and type. Check for a partial write" - ) - chunk_length = int.from_bytes(file_bytes[offset:offset + 4], "big") - chunk_type = file_bytes[offset + 4:header_end] - data_end = header_end + chunk_length - crc_end = data_end + 4 - if crc_end > len(file_bytes): - raise ToolError( - f"'{source_path}': truncated {chunk_type.decode('ascii', 'replace')} chunk " - f"at byte offset {offset}: declared length {chunk_length} runs past the end " - f"of the file. Check for a partial write" - ) - chunk_data = file_bytes[header_end:data_end] - stored_crc = int.from_bytes(file_bytes[data_end:crc_end], "big") - computed_crc = png_chunk_crc(chunk_type, chunk_data) - if stored_crc != computed_crc: - raise ToolError( - f"'{source_path}': CRC mismatch in {chunk_type.decode('ascii', 'replace')} " - f"chunk at byte offset {offset}: stored {stored_crc:08x}, computed " - f"{computed_crc:08x}. The file is corrupt; re-render it" - ) - chunks.append((chunk_type, chunk_data)) - offset = crc_end - if chunk_type == b"IEND": - break - - if offset != len(file_bytes): - raise ToolError( - f"'{source_path}': {len(file_bytes) - offset} byte(s) follow IEND at offset " - f"{offset}. Check that two files were not concatenated" - ) - return chunks - - -def parse_image_header(chunks, source_path): - """Validate IHDR and return (width, height, colour_type).""" - first_type, first_data = chunks[0] - if first_type != b"IHDR": - raise ToolError( - f"'{source_path}': first chunk is " - f"{first_type.decode('ascii', 'replace')}, not IHDR; the file is not a valid PNG" - ) - if len(first_data) != 13: - raise ToolError( - f"'{source_path}': IHDR is {len(first_data)} bytes, expected 13. " - f"The file is corrupt; re-render it" - ) - - width = int.from_bytes(first_data[0:4], "big") - height = int.from_bytes(first_data[4:8], "big") - bit_depth = first_data[8] - colour_type = first_data[9] - compression_method = first_data[10] - filter_method = first_data[11] - interlace_method = first_data[12] - - if width == 0 or height == 0: - raise ToolError( - f"'{source_path}': IHDR declares {width}x{height}; a PNG must have at " - f"least one pixel in each direction" - ) - if bit_depth != PNG_BIT_DEPTH_8: - raise ToolError( - f"'{source_path}': bit depth {bit_depth} is not supported; only 8 is. " - f"Re-export from the renderer without 16-bit or packed formats" - ) - if colour_type not in (PNG_COLOUR_TYPE_RGB, PNG_COLOUR_TYPE_RGBA): - raise ToolError( - f"'{source_path}': colour type {colour_type} is not supported; only 2 (RGB) " - f"and 6 (RGBA) are. Re-export without palette or grayscale mode" - ) - if compression_method != PNG_COMPRESSION_DEFLATE: - raise ToolError( - f"'{source_path}': compression method {compression_method} is not deflate(0); " - f"the file is not a PNG this tool can read" - ) - if filter_method != PNG_FILTER_ADAPTIVE: - raise ToolError( - f"'{source_path}': filter method {filter_method} is not adaptive(0); " - f"the file is not a PNG this tool can read" - ) - if interlace_method != PNG_INTERLACE_NONE: - raise ToolError( - f"'{source_path}': interlace method {interlace_method}; only non-interlaced(0) " - f"is supported. Re-export as non-interlaced" - ) - return width, height, colour_type - - -def png_chunk_crc(chunk_type, chunk_data): - """CRC-32 over a PNG chunk's type and data, as the format defines it.""" - return zlib.crc32(chunk_type + chunk_data) & 0xFFFFFFFF - - -def read_png(path): - """Read a supported PNG from disk. Raises ToolError naming the file on any defect.""" - file_bytes = read_file_bytes(path, "PNG image") - chunks = split_png_chunks(file_bytes, path) - width, height, colour_type = parse_image_header(chunks, path) - if any(chunk_type == b"tRNS" for chunk_type, _ in chunks): - if colour_type == PNG_COLOUR_TYPE_RGBA: - raise ToolError(f"'{path}': tRNS is forbidden in an RGBA PNG; re-export a valid RGBA image") - raise ToolError( - f"'{path}': PNG tRNS transparency is not supported; re-export as RGBA " - f"with an explicit alpha channel. Ignoring tRNS would compare transparent pixels as opaque" - ) - - compressed_data = b"".join( - chunk_data for chunk_type, chunk_data in chunks if chunk_type == b"IDAT" - ) - if not compressed_data: - raise ToolError( - f"'{path}': no IDAT chunk, so there are no pixels. The file is incomplete; " - f"re-render it" - ) - try: - decompressed_data = zlib.decompress(compressed_data) - except zlib.error as error: - raise ToolError( - f"'{path}': IDAT does not decompress as zlib: {error}. " - f"Check that the file is complete and not a partial write" - ) - - channels = channels_for_colour_type(colour_type, path) - pixels = unfilter_image(decompressed_data, width, height, channels, path) - return Raster(width, height, colour_type, pixels, path) - - -def unfilter_image(filtered_bytes, width, height, channels, source_path): - """Turn filtered scanlines into packed pixels, one filter type per row. - - PNG filters each row against the row above, so decoding must proceed top to - bottom, feeding each reconstructed row into the next row's predictor. - """ - row_byte_count = width * channels - row_stride = row_byte_count + 1 # filter-type byte plus the row - expected_length = row_stride * height - if len(filtered_bytes) != expected_length: - raise ToolError( - f"'{source_path}': decompressed pixel data is {len(filtered_bytes)} bytes, " - f"expected {expected_length} for {width}x{height} with {channels} channels " - f"(rows include one filter-type byte). Check the render size and bit depth" - ) - - pixels = bytearray(row_byte_count * height) - # The specification defines the row above the first row as zeroes, so the - # first row's Up, Average and Paeth predictors have a defined input. - previous_row = bytes(row_byte_count) - for row_index in range(height): - row_start = row_index * row_stride - filter_type = filtered_bytes[row_start] - filtered_row = filtered_bytes[row_start + 1:row_start + row_stride] - reconstructed_row = unfilter_row( - filter_type, filtered_row, previous_row, channels, row_index, source_path - ) - row_offset = row_index * row_byte_count - pixels[row_offset:row_offset + row_byte_count] = reconstructed_row - previous_row = reconstructed_row - return pixels - - -def unfilter_row(filter_type, filtered_row, previous_row, bytes_per_pixel, - row_index, source_path): - """Dispatch one scanline to its filter decoder; reject undefined filter types.""" - if filter_type == FILTER_NONE: - return unfilter_none(filtered_row) - if filter_type == FILTER_SUB: - return unfilter_sub(filtered_row, bytes_per_pixel) - if filter_type == FILTER_UP: - return unfilter_up(filtered_row, previous_row) - if filter_type == FILTER_AVERAGE: - return unfilter_average(filtered_row, previous_row, bytes_per_pixel) - if filter_type == FILTER_PAETH: - return unfilter_paeth(filtered_row, previous_row, bytes_per_pixel) - raise ToolError( - f"'{source_path}': row {row_index} uses PNG filter type {filter_type}; " - f"only 0-4 are defined. The file is corrupt; re-render it" - ) - - -def unfilter_none(filtered_row): - """Return the scanline unchanged (filter 0).""" - return bytes(filtered_row) - - -def unfilter_sub(filtered_row, bytes_per_pixel): - """Add the byte one pixel to the left in the same row (filter 1).""" - reconstructed = bytearray(len(filtered_row)) - for index in range(len(filtered_row)): - left = reconstructed[index - bytes_per_pixel] if index >= bytes_per_pixel else 0 - # PNG filter arithmetic is modulo 256; masking keeps the byte in range. - reconstructed[index] = (filtered_row[index] + left) & 0xFF - return bytes(reconstructed) - - -def unfilter_up(filtered_row, previous_row): - """Add the byte directly above in the previous row (filter 2).""" - reconstructed = bytearray(len(filtered_row)) - for index in range(len(filtered_row)): - reconstructed[index] = (filtered_row[index] + previous_row[index]) & 0xFF - return bytes(reconstructed) - - -def unfilter_average(filtered_row, previous_row, bytes_per_pixel): - """Add the floor of the left and above average (filter 3).""" - reconstructed = bytearray(len(filtered_row)) - for index in range(len(filtered_row)): - left = reconstructed[index - bytes_per_pixel] if index >= bytes_per_pixel else 0 - above = previous_row[index] - reconstructed[index] = (filtered_row[index] + ((left + above) // 2)) & 0xFF - return bytes(reconstructed) - - -def unfilter_paeth(filtered_row, previous_row, bytes_per_pixel): - """Add the Paeth predictor of left, above and upper-left (filter 4).""" - reconstructed = bytearray(len(filtered_row)) - for index in range(len(filtered_row)): - left = reconstructed[index - bytes_per_pixel] if index >= bytes_per_pixel else 0 - above = previous_row[index] - upper_left = previous_row[index - bytes_per_pixel] if index >= bytes_per_pixel else 0 - predictor = paeth_predictor(left, above, upper_left) - reconstructed[index] = (filtered_row[index] + predictor) & 0xFF - return bytes(reconstructed) - - -def paeth_predictor(left, above, upper_left): - """Return PNG's Paeth predictor for one byte. - - The predictor is whichever neighbour is closest to left + above - upper_left. - Ties go left, then above, then upper-left; that order is part of the PNG - specification and swapping it silently corrupts smooth gradients. - """ - estimate = left + above - upper_left - distance_left = abs(estimate - left) - distance_above = abs(estimate - above) - distance_upper_left = abs(estimate - upper_left) - if distance_left <= distance_above and distance_left <= distance_upper_left: - return left - if distance_above <= distance_upper_left: - return above - return upper_left - - -def make_chunk(chunk_type, chunk_data): - """Wrap chunk data as length, type, data and CRC, as PNG requires.""" - length_prefix = len(chunk_data).to_bytes(4, "big") - crc = png_chunk_crc(chunk_type, chunk_data) - return length_prefix + chunk_type + chunk_data + crc.to_bytes(4, "big") - - -def write_png(path, raster): - """Write an 8-bit RGB or RGBA PNG, filter type 0 on every row.""" - channels = channels_for_colour_type(raster.colour_type, path) - row_byte_count = raster.width * channels - if len(raster.pixels) != row_byte_count * raster.height: - raise ToolError( - f"cannot write '{path}': raster holds {len(raster.pixels)} bytes, expected " - f"{row_byte_count * raster.height} for {raster.width}x{raster.height} " - f"{raster.colour_name()}" - ) - - filtered_rows = bytearray() - for row_index in range(raster.height): - filtered_rows.append(FILTER_NONE) - row_offset = row_index * row_byte_count - filtered_rows.extend(raster.pixels[row_offset:row_offset + row_byte_count]) - - header = ( - raster.width.to_bytes(4, "big") - + raster.height.to_bytes(4, "big") - + bytes((PNG_BIT_DEPTH_8, raster.colour_type, PNG_COMPRESSION_DEFLATE, - PNG_FILTER_ADAPTIVE, PNG_INTERLACE_NONE)) - ) - file_bytes = ( - PNG_SIGNATURE - + make_chunk(b"IHDR", header) - + make_chunk(b"IDAT", zlib.compress(bytes(filtered_rows), 9)) - + make_chunk(b"IEND", b"") - ) - write_file_bytes(path, file_bytes, "PNG image") - - -# --------------------------------------------------------------------------- -# Manifest loading -# --------------------------------------------------------------------------- - - -@dataclass(frozen=True) -class ManifestCheck: - x: int - y: int - expected_red: int - expected_green: int - expected_blue: int - expected_alpha: int - reason: str - - -@dataclass(frozen=True) -class ManifestScene: - name: str - png_name: str - checks: tuple - - -@dataclass(frozen=True) -class Manifest: - manifest_path: str - renderer: str - adapter: str - scenes: tuple - - -def require_key(mapping, key, context): - """Return a required mapping key, or fail naming the context and key.""" - if key not in mapping: - raise ToolError(f'{context}: required key "{key}" is missing') - return mapping[key] - - -def require_string(mapping, key, context): - """Return a required string value and reject other JSON types.""" - value = require_key(mapping, key, context) - if not isinstance(value, str): - raise ToolError(f'{context}: "{key}" must be a string, got {value!r}') - return value - - -def require_list(mapping, key, context): - """Return a required JSON list and reject other JSON types.""" - value = require_key(mapping, key, context) - if not isinstance(value, list): - raise ToolError(f'{context}: "{key}" must be a list, got {value!r}') - return value - - -def require_int(mapping, key, minimum, maximum, context): - """Return a required integer in range, rejecting booleans and floats.""" - value = require_key(mapping, key, context) - # bool is an int subclass; true would otherwise pass as coordinate 1. - if isinstance(value, bool) or not isinstance(value, int): - raise ToolError(f'{context}: "{key}" must be an integer, got {value!r}') - if value < minimum or value > maximum: - raise ToolError( - f'{context}: "{key}" must be between {minimum} and {maximum}, got {value}' - ) - return value - - -def parse_manifest_check(raw_check, check_index, scene_context): - """Validate one declared pixel into a ManifestCheck.""" - context = f"{scene_context}, check {check_index + 1}" - if not isinstance(raw_check, dict): - raise ToolError(f"{context}: must be an object, got {raw_check!r}") - reason = raw_check.get("why", "") - if not isinstance(reason, str): - raise ToolError(f'{context}: "why" must be a string when present, got {reason!r}') - return ManifestCheck( - x=require_int(raw_check, "x", 0, MAX_SANE_COORDINATE, context), - y=require_int(raw_check, "y", 0, MAX_SANE_COORDINATE, context), - expected_red=require_int(raw_check, "r", 0, MAX_CHANNEL_VALUE, context), - expected_green=require_int(raw_check, "g", 0, MAX_CHANNEL_VALUE, context), - expected_blue=require_int(raw_check, "b", 0, MAX_CHANNEL_VALUE, context), - expected_alpha=require_int(raw_check, "a", 0, MAX_CHANNEL_VALUE, context), - reason=reason, - ) - - -def require_safe_file_name(value, key, context, reason): - """Reject a manifest string that would escape its directory or break a path.""" - has_control_character = any(ord(character) < 32 for character in value) - has_unsafe_character = any( - character in UNSAFE_FILE_NAME_CHARACTERS for character in value - ) - if (os.path.basename(value) != value or value in (".", "..") - or has_control_character or has_unsafe_character): - raise ToolError( - f'{context}: "{key}" must be a plain file name; got {value!r}. {reason}' - ) - return value - - -def parse_manifest_scene(raw_scene, scene_index, manifest_path): - """Validate one scene entry, including a non-empty check list.""" - context = f"manifest '{manifest_path}': scene {scene_index + 1}" - if not isinstance(raw_scene, dict): - raise ToolError(f"{context}: must be an object, got {raw_scene!r}") - name = require_string(raw_scene, "name", context) - if not name.strip(): - raise ToolError(f"{context}: \"name\" is empty; it identifies the scene and the diff row") - name = require_safe_file_name( - name, "name", context, "It is also used as the .diff.png file name" - ) - context = f"manifest '{manifest_path}': scene {scene_index + 1} ('{name}')" - - png_name = require_string(raw_scene, "png", context) - png_name = require_safe_file_name( - png_name, "png", context, "It must name an image beside the manifest" - ) - raw_checks = require_list(raw_scene, "checks", context) - if not raw_checks: - raise ToolError( - f"{context}: \"checks\" is empty; a scene with no pixel checks proves " - f"nothing. Add at least one check or remove the scene" - ) - checks = tuple( - parse_manifest_check(raw_check, check_index, context) - for check_index, raw_check in enumerate(raw_checks) - ) - return ManifestScene(name=name, png_name=png_name, checks=checks) - - -def parse_manifest_scenes(raw_scenes, manifest_path): - """Validate all scenes and reject duplicate scene or PNG names.""" - scenes = [] - scene_number_by_name = {} - png_number_by_name = {} - for scene_index, raw_scene in enumerate(raw_scenes): - scene = parse_manifest_scene(raw_scene, scene_index, manifest_path) - if scene.name in scene_number_by_name: - raise ToolError( - f"manifest '{manifest_path}': scene {scene_index + 1} repeats name " - f"'{scene.name}' from scene {scene_number_by_name[scene.name] + 1}; " - f"diff matches scenes by name, so duplicates are ambiguous" - ) - if scene.png_name in png_number_by_name: - raise ToolError( - f"manifest '{manifest_path}': scene {scene_index + 1} repeats png " - f"'{scene.png_name}' from scene {png_number_by_name[scene.png_name] + 1}; " - f"diff would write the same .diff.png twice" - ) - scene_number_by_name[scene.name] = scene_index - png_number_by_name[scene.png_name] = scene_index - scenes.append(scene) - return tuple(scenes) - - -def load_manifest(path): - """Load and validate a renderer manifest. Unknown extra keys are ignored.""" - manifest_path = os.path.abspath(path) - text = read_text_file(manifest_path, "scene manifest") - - def unique_keys(pairs): - obj = {} - for key, value in pairs: - if key in obj: - raise ToolError(f"manifest '{manifest_path}': duplicate key {key!r}") - obj[key] = value - return obj - - try: - document = json.loads(text, object_pairs_hook=unique_keys) - except json.JSONDecodeError as error: - raise ToolError( - f"manifest '{manifest_path}' is not valid JSON: {error.msg} at line " - f"{error.lineno} column {error.colno}. Check for a missing comma or " - f"trailing text" - ) - if not isinstance(document, dict): - raise ToolError( - f"manifest '{manifest_path}': top level must be an object, got " - f"{type(document).__name__}" - ) - - context = f"manifest '{manifest_path}'" - renderer = require_string(document, "renderer", context) - adapter = require_string(document, "adapter", context) - raw_scenes = require_list(document, "scenes", context) - if not raw_scenes: - raise ToolError( - f"manifest '{manifest_path}': \"scenes\" is empty; there is nothing to " - f"check. Point --manifest at the renderer's manifest.json" - ) - return Manifest( - manifest_path=manifest_path, - renderer=renderer, - adapter=adapter, - scenes=parse_manifest_scenes(raw_scenes, manifest_path), - ) - - -def resolve_image_directory(manifest, override): - """Return the absolute image directory, checking that an explicit --dir exists.""" - if override: - if not os.path.isdir(override): - raise ToolError( - f"image directory '{override}' does not exist or is not a directory. " - f"Check the --dir argument" - ) - return os.path.abspath(override) - return os.path.dirname(manifest.manifest_path) - - -def scene_image_path(image_directory, png_name): - """Join an image directory with a manifest's PNG file name.""" - return os.path.join(image_directory, png_name) - - -# --------------------------------------------------------------------------- -# expect -# --------------------------------------------------------------------------- - - -@dataclass(frozen=True) -class CheckOutcome: - scene_name: str - check: ManifestCheck - actual: tuple - failure_note: str - # Decided from the comparison itself. Deriving it from failure_note made the verdict - # depend on whether a "why" string happened to be present. - passed_check: bool - - @property - def passed(self): - """True when the pixel matched; failure_note is display text only.""" - return self.passed_check - - -@dataclass(frozen=True) -class SceneOutcome: - scene: ManifestScene - checks: tuple - image_problem: str = "" - - -def evaluate_check(scene_name, image, check): - """Compare one declared pixel; bounds and absent alpha are explained, not raised.""" - if check.x >= image.width or check.y >= image.height: - note = ( - f"coordinate is outside the {image.width}x{image.height} image " - f"'{image.source_path}'; check the manifest coordinate and the render size" - ) - return CheckOutcome(scene_name, check, (), note, False) - - stored = image.stored_pixel(check.x, check.y) - declared = (check.expected_red, check.expected_green, check.expected_blue, - check.expected_alpha) - if image.pixel_rgba(check.x, check.y) == declared: - return CheckOutcome(scene_name, check, stored, "", True) - - if image.colour_type == PNG_COLOUR_TYPE_RGB and check.expected_alpha != OPAQUE_ALPHA: - note = ( - f"image stores no alpha channel, so declared alpha {check.expected_alpha} " - f"cannot match; {check.reason or 'fix the check or render RGBA'}" - ) - else: - note = check.reason or "pixel does not match the declared value" - return CheckOutcome(scene_name, check, stored, note, False) - - -def verify_scene(scene, image_directory): - """Read one scene's image and evaluate every check; image errors stay scene-local.""" - image_path = scene_image_path(image_directory, scene.png_name) - try: - image = read_png(image_path) - except ToolError as error: - return SceneOutcome(scene, (), str(error)) - checks = tuple( - evaluate_check(scene.name, image, check) for check in scene.checks - ) - return SceneOutcome(scene, checks) - - -def format_channel_values(values): - """Render channel values as comma-separated decimals for the report.""" - return ",".join(str(value) for value in values) - - -def plural(count, singular): - """Return the singular or plural noun for a count, for readable summaries.""" - return singular if count == 1 else singular + "s" - - -def format_check_line(outcome, scene_column_width): - """Format one PASS or FAIL row with expected, actual and failure reason.""" - status = "PASS" if outcome.passed else "FAIL" - coordinate = f"({outcome.check.x},{outcome.check.y})" - expected = format_channel_values(( - outcome.check.expected_red, - outcome.check.expected_green, - outcome.check.expected_blue, - outcome.check.expected_alpha, - )) - got = format_channel_values(outcome.actual) if outcome.actual else "not read" - line = ( - f"{status} {outcome.scene_name:<{scene_column_width}} {coordinate:<12} " - f"expected {expected:<17} got {got}" - ) - if not outcome.passed: - line += f" ({outcome.failure_note})" - return line - - -def print_expect_report(scene_outcomes): - """Print every check row and the summary; return True when all passed.""" - scene_column_width = max(len(outcome.scene.name) for outcome in scene_outcomes) - passed_count = 0 - failed_count = 0 - unreadable_count = 0 - for scene_outcome in scene_outcomes: - if scene_outcome.image_problem: - unreadable_count += 1 - failed_count += len(scene_outcome.scene.checks) - print( - f"FAIL {scene_outcome.scene.name:<{scene_column_width}} " - f"image problem: {scene_outcome.image_problem}" - ) - continue - for check_outcome in scene_outcome.checks: - print(format_check_line(check_outcome, scene_column_width)) - if check_outcome.passed: - passed_count += 1 - else: - failed_count += 1 - - check_count = passed_count + failed_count - summary = ( - f"{len(scene_outcomes)} {plural(len(scene_outcomes), 'scene')}, " - f"{check_count} {plural(check_count, 'check')}: " - f"{passed_count} passed, {failed_count} failed" - ) - if unreadable_count: - summary += ( - f", {unreadable_count} {plural(unreadable_count, 'image')} " - f"could not be read" - ) - print() - print(summary) - return failed_count == 0 - - -def command_expect(arguments): - """Run the expect mode and return its exit code.""" - manifest = load_manifest(arguments.manifest) - image_directory = resolve_image_directory(manifest, arguments.dir) - scene_outcomes = [ - verify_scene(scene, image_directory) for scene in manifest.scenes - ] - return EXIT_PASSED if print_expect_report(scene_outcomes) else EXIT_FAILED - - -# --------------------------------------------------------------------------- -# diff -# --------------------------------------------------------------------------- - - -@dataclass(frozen=True) -class DiffStats: - differing_pixels: int - total_pixels: int - differing_percent: float - mean_absolute_delta: float - max_channel_delta: int - first_difference: tuple - # The RGBA values at first_difference, so a failure line can show what actually - # differed instead of only how much. - first_reference_pixel: tuple - first_candidate_pixel: tuple - - -def compare_rasters(reference, candidate): - """Compare two same-size images using RGBA; RGB images count as opaque.""" - if (reference.width, reference.height) != (candidate.width, candidate.height): - raise ToolError( - f"cannot compare '{reference.source_path}' " - f"({reference.width}x{reference.height}) with '{candidate.source_path}' " - f"({candidate.width}x{candidate.height}); re-render at the same size" - ) - - total_pixels = reference.width * reference.height - # Every RGBA sample compared, so this is 4x the pixel count, not the pixel count. - channel_sample_count = total_pixels * RGBA_CHANNEL_COUNT - differing_pixels = 0 - total_absolute_delta = 0 - max_channel_delta = 0 - first_difference = None - first_reference_pixel = () - first_candidate_pixel = () - - for y in range(reference.height): - for x in range(reference.width): - reference_pixel = reference.pixel_rgba(x, y) - candidate_pixel = candidate.pixel_rgba(x, y) - pixel_delta = 0 - for channel_index in range(RGBA_CHANNEL_COUNT): - channel_delta = abs(reference_pixel[channel_index] - - candidate_pixel[channel_index]) - total_absolute_delta += channel_delta - pixel_delta = max(pixel_delta, channel_delta) - if pixel_delta == 0: - continue - differing_pixels += 1 - max_channel_delta = max(max_channel_delta, pixel_delta) - if first_difference is None: - first_difference = (x, y) - first_reference_pixel = reference_pixel - first_candidate_pixel = candidate_pixel - - return DiffStats( - differing_pixels=differing_pixels, - total_pixels=total_pixels, - differing_percent=100.0 * differing_pixels / total_pixels, - # Mean over every channel sample of every pixel. Read it together with - # differing_pixels and max_channel_delta: on its own, one pixel off by 255 and 255 - # pixels off by 1 give the same mean, so the mean alone cannot rank a failure. - mean_absolute_delta=total_absolute_delta / channel_sample_count, - max_channel_delta=max_channel_delta, - first_difference=first_difference, - first_reference_pixel=first_reference_pixel, - first_candidate_pixel=first_candidate_pixel, - ) - - -def heatmap_colour(channel_delta): - """Map delta 1 to pure blue and delta 255 to pure red, on a linear ramp.""" - if channel_delta <= 0: - return HEATMAP_UNCHANGED - red = round(MAX_CHANNEL_VALUE * (channel_delta - 1) / (MAX_CHANNEL_VALUE - 1)) - return (red, 0, MAX_CHANNEL_VALUE - red) - - -def build_heatmap(reference, candidate): - """Build an RGB image: unchanged grey, differences ramped blue to red.""" - if (reference.width, reference.height) != (candidate.width, candidate.height): - raise ToolError( - f"cannot build a heatmap from {reference.width}x{reference.height} and " - f"{candidate.width}x{candidate.height} images; sizes must match" - ) - pixels = bytearray(reference.width * reference.height * 3) - for y in range(reference.height): - for x in range(reference.width): - reference_pixel = reference.pixel_rgba(x, y) - candidate_pixel = candidate.pixel_rgba(x, y) - pixel_delta = max( - abs(reference_pixel[channel] - candidate_pixel[channel]) - for channel in range(RGBA_CHANNEL_COUNT) - ) - offset = (y * reference.width + x) * 3 - pixels[offset:offset + 3] = bytes(heatmap_colour(pixel_delta)) - return Raster( - width=reference.width, - height=reference.height, - colour_type=PNG_COLOUR_TYPE_RGB, - pixels=pixels, - source_path=os.path.join( - os.path.dirname(candidate.source_path), - "difference heatmap for " + os.path.basename(candidate.source_path), - ), - ) - - -def format_rgba(pixel): - """Format an RGBA tuple for a failure line; empty reads as a dash.""" - if not pixel: - return "-" - return ",".join(str(channel) for channel in pixel) - - -def threshold_violation(stats, max_differing_percent, max_mean_delta): - """Return why the scene fails the thresholds, or "" when it passes.""" - if stats.differing_percent > max_differing_percent: - return ( - f"differing pixels {stats.differing_percent:.3f}% exceed " - f"--max-differing-percent {max_differing_percent:.3f}%" - ) - if stats.mean_absolute_delta > max_mean_delta: - return ( - f"mean absolute channel delta {stats.mean_absolute_delta:.4f} exceeds " - f"--max-mean-delta {max_mean_delta:.4f}" - ) - return "" - - -def whole_frame_difference_note(scene_name, stats): - """Explain a whole-frame difference, with the values that identify the cause. - - A whole-frame difference is not automatically the tint: an unblended draw of the - correct colour also differs everywhere, and so does a scene that was never drawn. - The pixel values are what tell those apart, so they are printed. - """ - if stats.total_pixels == 0 or stats.differing_pixels != stats.total_pixels: - return "" - reference_text = format_rgba(stats.first_reference_pixel) - candidate_text = format_rgba(stats.first_candidate_pixel) - return ( - f"scene '{scene_name}': every pixel differs - at the first difference the " - f"reference is {reference_text} and the candidate is {candidate_text}. " - f"Suspects, in order: the constant buffer tint, the clear colour, blend state, " - f"or a draw that never happened" - ) - - -def format_diff_line(scene_name, stats, scene_column_width, violation): - """Format one scene's diff metrics as a single table row.""" - status = "FAIL" if violation else "PASS" - if stats.first_difference: - first = f"({stats.first_difference[0]},{stats.first_difference[1]})" - else: - first = "-" - line = ( - f"{status} {scene_name:<{scene_column_width}} " - f"differing {stats.differing_pixels}/{stats.total_pixels} " - f"({stats.differing_percent:.3f}%) mean {stats.mean_absolute_delta:.4f} " - f"max {stats.max_channel_delta} first {first}" - ) - if violation: - line += f" ({violation})" - return line - - -def match_manifest_scenes(reference, candidate): - """Require both manifests to declare exactly the same scene names.""" - reference_names = {scene.name for scene in reference.scenes} - candidate_names = {scene.name for scene in candidate.scenes} - missing_names = sorted(reference_names - candidate_names) - extra_names = sorted(candidate_names - reference_names) - if missing_names: - raise ToolError( - f"candidate manifest '{candidate.manifest_path}' is missing scene(s) the " - f"reference declares: {', '.join(missing_names)}. Re-render them" - ) - if extra_names: - raise ToolError( - f"candidate manifest '{candidate.manifest_path}' has scenes the reference " - f"does not declare: {', '.join(extra_names)}. Remove them or update the reference" - ) - - -def command_diff(arguments): - """Run the diff mode: metrics, heatmaps, thresholds and exit code.""" - reference = load_manifest(arguments.reference) - candidate = load_manifest(arguments.candidate) - reference_directory = resolve_image_directory(reference, arguments.reference_dir) - candidate_directory = resolve_image_directory(candidate, arguments.candidate_dir) - match_manifest_scenes(reference, candidate) - - print(f"reference: {reference.manifest_path}") - print(f" renderer '{reference.renderer}', adapter '{reference.adapter}'") - print(f"candidate: {candidate.manifest_path}") - print(f" renderer '{candidate.renderer}', adapter '{candidate.adapter}'") - print() - # Flush before a later read can fail onto stderr, so the error is not - # printed above the header it belongs to when output is redirected. - sys.stdout.flush() - - # Each manifest names its own files, so look up the candidate scene itself - # rather than assuming both renderers wrote the same PNG file name. - candidate_scenes_by_name = {scene.name: scene for scene in candidate.scenes} - scene_column_width = max(len(scene.name) for scene in reference.scenes) - failing_scenes = [] - for scene in reference.scenes: - candidate_scene = candidate_scenes_by_name[scene.name] - reference_image = read_png(scene_image_path(reference_directory, scene.png_name)) - candidate_image = read_png( - scene_image_path(candidate_directory, candidate_scene.png_name) - ) - stats = compare_rasters(reference_image, candidate_image) - heatmap = build_heatmap(reference_image, candidate_image) - heatmap_path = os.path.join(candidate_directory, f"{scene.name}.diff.png") - write_png(heatmap_path, heatmap) - - violation = threshold_violation( - stats, arguments.max_differing_percent, arguments.max_mean_delta - ) - print(format_diff_line(scene.name, stats, scene_column_width, violation)) - whole_frame_note = whole_frame_difference_note(scene.name, stats) - if whole_frame_note: - print(f" {whole_frame_note}") - if violation: - failing_scenes.append(scene.name) - - print() - scene_count = len(reference.scenes) - print( - f"{scene_count} {plural(scene_count, 'scene')} compared, " - f"{len(failing_scenes)} exceed the thresholds. Heatmaps written beside the " - f"candidate images as .diff.png" - ) - return EXIT_FAILED if failing_scenes else EXIT_PASSED - - -# --------------------------------------------------------------------------- -# inspect -# --------------------------------------------------------------------------- - - -def pixel_coordinate_argument(text): - """Parse an argparse X,Y pixel argument into an (x, y) tuple.""" - parts = text.split(",") - if len(parts) != 2: - raise argparse.ArgumentTypeError( - f"'{text}' is not x,y; use for example --pixel 12,34" - ) - try: - x = int(parts[0]) - y = int(parts[1]) - except ValueError: - raise argparse.ArgumentTypeError( - f"'{text}' has a non-integer part; use for example --pixel 12,34" - ) - return (x, y) - - -def format_inspection_line(label, x, y, channel_values): - """Format one labelled pixel row for inspect output.""" - coordinate = f"({x},{y})" - return ( - f" {label:<12} {coordinate:<11}= " - f"{format_channel_values(channel_values)}" - ) - - -def command_inspect(arguments): - """Run the inspect mode and return its exit code. - - Top-left and bottom-right are always printed so a vertical flip is visible: - the corners are labelled and their coordinates are explicit. - """ - image = read_png(arguments.image) - print(arguments.image) - print( - f" {image.width} x {image.height}, {image.colour_name()}, 8 bits per channel, " - f"non-interlaced" - ) - sys.stdout.flush() - bottom_right_x = image.width - 1 - bottom_right_y = image.height - 1 - print(format_inspection_line("top-left", 0, 0, image.stored_pixel(0, 0))) - print( - format_inspection_line( - "bottom-right", bottom_right_x, bottom_right_y, - image.stored_pixel(bottom_right_x, bottom_right_y), - ) - ) - if arguments.pixel: - for x, y in arguments.pixel: - print(format_inspection_line("pixel", x, y, image.stored_pixel(x, y))) - else: - print(" no --pixel given; also showing top-right, bottom-left and centre") - for label, x, y in ( - ("top-right", bottom_right_x, 0), - ("bottom-left", 0, bottom_right_y), - ("centre", image.width // 2, image.height // 2), - ): - print(format_inspection_line(label, x, y, image.stored_pixel(x, y))) - return EXIT_PASSED - - -# --------------------------------------------------------------------------- -# selftest -# --------------------------------------------------------------------------- - - -def require_equal(description, actual, expected): - """Fail the selftest unless actual equals expected.""" - if actual != expected: - raise SelftestMismatch( - f"{description}: expected {expected!r}, got {actual!r}" - ) - - -def require_true(description, condition): - """Fail the selftest unless the condition holds.""" - if not condition: - raise SelftestMismatch(description) - - -def assert_tool_error(action, expected_fragment, description): - """Require the action to raise ToolError containing an expected fragment.""" - try: - action() - except ToolError as error: - require_true( - f"{description}: message should contain {expected_fragment!r}, got '{error}'", - expected_fragment in str(error), - ) - return - raise SelftestMismatch(f"{description}: expected a ToolError, but the call succeeded") - - -def assert_argument_error(action, description): - """Require the action to raise argparse.ArgumentTypeError.""" - try: - action() - except argparse.ArgumentTypeError: - return - raise SelftestMismatch( - f"{description}: expected an ArgumentTypeError, but the call succeeded" - ) - - -def make_solid_raster(width, height, colour_type, colour, source_path): - """Build an in-memory raster filled with one colour.""" - return Raster( - width=width, - height=height, - colour_type=colour_type, - pixels=bytearray(bytes(colour) * (width * height)), - source_path=source_path, - ) - - -def write_selftest_manifest(path, renderer, adapter, scenes): - """Write a manifest in the renderer's shape for selftest fixtures.""" - document = {"renderer": renderer, "adapter": adapter, "scenes": scenes} - write_file_bytes( - path, json.dumps(document, indent=2).encode("utf-8"), "selftest manifest" - ) - - -def run_and_capture(command, arguments): - """Run a command with stdout captured; return its exit code and text.""" - output_buffer = io.StringIO() - with contextlib.redirect_stdout(output_buffer): - exit_code = command(arguments) - return exit_code, output_buffer.getvalue() - - -def make_selftest_directory(path): - """Create one selftest fixture directory, reporting failure as a mismatch.""" - try: - os.makedirs(path) - except OSError as error: - raise SelftestMismatch( - f"cannot create selftest fixture directory '{path}': {error}" - ) - - -def step_png_roundtrip(directory): - """Assert RGB and RGBA round-trip, rectangle pixels and write determinism.""" - solid = make_solid_raster(8, 6, PNG_COLOUR_TYPE_RGB, (10, 20, 30), "selftest solid") - solid_path = os.path.join(directory, "solid.png") - write_png(solid_path, solid) - decoded = read_png(solid_path) - require_equal("solid PNG width", decoded.width, 8) - require_equal("solid PNG height", decoded.height, 6) - require_equal("solid PNG colour type", decoded.colour_type, PNG_COLOUR_TYPE_RGB) - require_equal("solid PNG pixels", bytes(decoded.pixels), bytes(solid.pixels)) - require_equal("solid PNG pixel (0,0)", decoded.stored_pixel(0, 0), (10, 20, 30)) - print("ok PNG round-trip: RGB pixels and alpha-free pixel reads") - - rectangle = make_solid_raster( - 8, 6, PNG_COLOUR_TYPE_RGBA, (10, 20, 30, 255), "selftest rectangle" - ) - for y in range(1, 5): - for x in range(2, 6): - offset = (y * 8 + x) * 4 - rectangle.pixels[offset:offset + 4] = bytes((200, 30, 60, 200)) - rectangle_path = os.path.join(directory, "rectangle.png") - write_png(rectangle_path, rectangle) - decoded_rectangle = read_png(rectangle_path) - require_equal( - "rectangle PNG pixel inside the rectangle", - decoded_rectangle.stored_pixel(2, 1), - (200, 30, 60, 200), - ) - require_equal( - "rectangle PNG pixel at its bottom-right corner", - decoded_rectangle.stored_pixel(5, 4), - (200, 30, 60, 200), - ) - require_equal( - "rectangle PNG pixel left of the rectangle", - decoded_rectangle.pixel_rgba(1, 1), - (10, 20, 30, 255), - ) - require_equal( - "rectangle PNG pixel right of the rectangle", - decoded_rectangle.stored_pixel(6, 1), - (10, 20, 30, 255), - ) - print("ok PNG round-trip: RGBA rectangle at (2,1)-(5,4), alpha 200 preserved") - - second_path = os.path.join(directory, "solid-again.png") - write_png(second_path, solid) - require_equal( - "two writes of the same raster are byte-identical", - read_file_bytes(second_path, "selftest PNG"), - read_file_bytes(solid_path, "selftest PNG"), - ) - print("ok PNG writer is deterministic: two writes of one raster match byte for byte") - - -def step_png_error_paths(directory): - """Assert unwritable directory, corrupt CRC and truncation are reported.""" - solid = make_solid_raster(8, 6, PNG_COLOUR_TYPE_RGB, (10, 20, 30), "selftest solid") - solid_path = os.path.join(directory, "error-fixture.png") - write_png(solid_path, solid) - - missing_directory_path = os.path.join(directory, "missing-subdirectory", "image.png") - assert_tool_error( - lambda: write_png(missing_directory_path, solid), - "cannot write", - "writing into a missing directory", - ) - print("ok failure path: unwritable output directory names the path") - - crc_path = os.path.join(directory, "bad-crc.png") - write_png(crc_path, solid) - corrupt_bytes = bytearray(read_file_bytes(crc_path, "selftest PNG")) - corrupt_bytes[45] ^= 0xFF # inside IDAT data: offset 33 starts IDAT, 8 bytes of header - write_file_bytes(crc_path, bytes(corrupt_bytes), "selftest PNG") - assert_tool_error( - lambda: read_png(crc_path), - "CRC mismatch", - "reading a PNG with a corrupted IDAT", - ) - print("ok failure path: corrupt IDAT reports the CRC and byte offset") - - truncated_path = os.path.join(directory, "truncated.png") - truncated_bytes = read_file_bytes(solid_path, "selftest PNG")[:60] - write_file_bytes(truncated_path, truncated_bytes, "selftest PNG") - assert_tool_error( - lambda: read_png(truncated_path), - "truncated", - "reading a truncated PNG", - ) - print("ok failure path: truncated file reports the byte offset") - - -def step_filter_decoders(): - """Assert filters 0-4 decode hand-computed streams and bad streams fail.""" - # 3x2 RGB fixture: row 0 is (10,20,30) (200,30,60) (105,25,45); - # row 1 is (40,50,60) (70,80,90) (100,110,120). The five filtered streams - # were computed by hand from the PNG filter definitions, independently of - # the decoder, so a mirrored encoder bug cannot hide here. - expected_pixels = bytes(( - 10, 20, 30, 200, 30, 60, 105, 25, 45, - 40, 50, 60, 70, 80, 90, 100, 110, 120, - )) - filtered_streams = { - FILTER_NONE: bytes(( - FILTER_NONE, 10, 20, 30, 200, 30, 60, 105, 25, 45, - FILTER_NONE, 40, 50, 60, 70, 80, 90, 100, 110, 120, - )), - FILTER_SUB: bytes(( - FILTER_SUB, 10, 20, 30, 190, 10, 30, 161, 251, 241, - FILTER_SUB, 40, 50, 60, 30, 30, 30, 30, 30, 30, - )), - FILTER_UP: bytes(( - FILTER_UP, 10, 20, 30, 200, 30, 60, 105, 25, 45, - FILTER_UP, 30, 30, 30, 126, 50, 30, 251, 85, 75, - )), - FILTER_AVERAGE: bytes(( - FILTER_AVERAGE, 10, 20, 30, 195, 20, 45, 5, 10, 15, - FILTER_AVERAGE, 35, 40, 45, 206, 40, 30, 13, 58, 53, - )), - FILTER_PAETH: bytes(( - FILTER_PAETH, 10, 20, 30, 190, 10, 30, 161, 251, 241, - FILTER_PAETH, 30, 30, 30, 126, 30, 30, 30, 30, 30, - )), - } - for filter_type in sorted(filtered_streams): - decoded = unfilter_image(filtered_streams[filter_type], 3, 2, 3, - "selftest filter fixture") - require_equal( - f"filter {filter_type} reconstructs the fixture", - bytes(decoded), - expected_pixels, - ) - print("ok PNG filters 0-4 decode: hand-computed streams for a 3x2 RGB fixture") - - truncated_stream = filtered_streams[FILTER_NONE][:-1] - assert_tool_error( - lambda: unfilter_image(truncated_stream, 3, 2, 3, "selftest filter fixture"), - "decompressed pixel data", - "filter data one byte short", - ) - unknown_filter_stream = bytearray(filtered_streams[FILTER_NONE]) - unknown_filter_stream[0] = 5 - assert_tool_error( - lambda: unfilter_image(bytes(unknown_filter_stream), 3, 2, 3, "selftest fixture"), - "filter type 5", - "undefined filter type", - ) - print("ok failure path: short filter data and undefined filter type are rejected") - - -def step_orientation_and_channel_order(directory): - """Assert row 0 is the top, channels stay R,G,B, and inspect labels both corners.""" - top_colour = (200, 30, 60) - bottom_colour = (10, 20, 30) - image = make_solid_raster( - 4, 4, PNG_COLOUR_TYPE_RGB, bottom_colour, "selftest orientation" - ) - for y in range(2): - for x in range(4): - offset = (y * 4 + x) * 3 - image.pixels[offset:offset + 3] = bytes(top_colour) - - image_path = os.path.join(directory, "orientation.png") - write_png(image_path, image) - decoded = read_png(image_path) - require_equal("row 0 keeps the top colour", decoded.stored_pixel(0, 0), top_colour) - require_equal("last row keeps the bottom colour", decoded.stored_pixel(3, 3), - bottom_colour) - require_equal("channels stay in R,G,B order", decoded.stored_pixel(0, 0), - (200, 30, 60)) - - exit_code, output = run_and_capture( - command_inspect, argparse.Namespace(image=image_path, pixel=None) - ) - require_equal("inspect exit code", exit_code, EXIT_PASSED) - require_true("inspect labels top-left with its value", - "top-left" in output and "(0,0)" in output and "200,30,60" in output) - require_true("inspect labels bottom-right with its value", - "bottom-right" in output and "(3,3)" in output and "10,20,30" in output) - print("ok orientation: top and bottom halves survive; inspect labels both corners") - - -def step_expect_matching(directory): - """Assert expect passes checks that match the fixture image.""" - image_path = os.path.join(directory, "clear.png") - write_png( - image_path, - make_solid_raster(8, 6, PNG_COLOUR_TYPE_RGB, (10, 20, 30), "selftest clear"), - ) - manifest_path = os.path.join(directory, "manifest-good.json") - write_selftest_manifest(manifest_path, "selftest", "fixture", [{ - "name": "clear", - "png": "clear.png", - "checks": [ - {"x": 0, "y": 0, "r": 10, "g": 20, "b": 30, "a": 255, - "why": "top-left is the clear colour"}, - {"x": 7, "y": 0, "r": 10, "g": 20, "b": 30, "a": 255, - "why": "top-right is the clear colour"}, - {"x": 0, "y": 5, "r": 10, "g": 20, "b": 30, "a": 255, - "why": "bottom-left is the clear colour"}, - {"x": 7, "y": 5, "r": 10, "g": 20, "b": 30, "a": 255, - "why": "bottom-right is the clear colour"}, - {"x": 4, "y": 3, "r": 10, "g": 20, "b": 30, "a": 255, - "why": "centre-ish pixel is the clear colour"}, - ], - }]) - exit_code, output = run_and_capture( - command_expect, argparse.Namespace(manifest=manifest_path, dir=None) - ) - require_equal("expect exit code for matching pixels", exit_code, EXIT_PASSED) - require_true("expect reports all five checks", output.count("PASS clear") == 5) - require_true("expect output has no FAIL row", "FAIL" not in output) - require_equal("expect evaluates checks in any count", len( - load_manifest(manifest_path).scenes[0].checks - ), 5) - print("ok expect: a five-check manifest exits 0 and prints five PASS rows") - - bom_path = os.path.join(directory, "manifest-bom.json") - bom_bytes = b"\xef\xbb\xbf" + read_file_bytes(manifest_path, "selftest manifest") - write_file_bytes(bom_path, bom_bytes, "selftest manifest") - require_equal("manifest with a UTF-8 BOM still loads", - len(load_manifest(bom_path).scenes), 1) - print("ok manifest reader accepts a UTF-8 BOM, as PowerShell writes") - - -def step_expect_failures(directory): - """Assert a wrong pixel and an out-of-range coordinate both fail.""" - image_path = os.path.join(directory, "clear.png") - write_png( - image_path, - make_solid_raster(8, 6, PNG_COLOUR_TYPE_RGB, (10, 20, 30), "selftest clear"), - ) - bad_manifest_path = os.path.join(directory, "manifest-bad.json") - write_selftest_manifest(bad_manifest_path, "selftest", "fixture", [{ - "name": "clear", - "png": "clear.png", - "checks": [ - {"x": 0, "y": 0, "r": 1, "g": 2, "b": 3, "a": 255, - "why": "deliberate wrong expectation"}, - {"x": 8, "y": 0, "r": 10, "g": 20, "b": 30, "a": 255, - "why": "coordinate one past the right edge"}, - ], - }]) - exit_code, output = run_and_capture( - command_expect, argparse.Namespace(manifest=bad_manifest_path, dir=None) - ) - require_equal("expect exit code for a wrong pixel", exit_code, EXIT_FAILED) - require_true("wrong pixel failure quotes its why", "deliberate wrong expectation" in output) - require_true("out-of-range pixel names the image size", "outside the 8x6 image" in output) - print("ok expect: wrong pixel and out-of-range coordinate fail with explanations") - - manifest = load_manifest(bad_manifest_path) - scene_outcome = verify_scene(manifest.scenes[0], directory) - require_equal("declared checks are all evaluated", len(scene_outcome.checks), 2) - require_true("first check fails", not scene_outcome.checks[0].passed) - require_equal("failed check records the stored pixel", scene_outcome.checks[0].actual, - (10, 20, 30)) - require_true("second check fails on bounds", not scene_outcome.checks[1].passed) - - -def step_expect_missing_and_invalid(directory): - """Assert a missing image fails the scene and an empty check list is rejected.""" - missing_manifest_path = os.path.join(directory, "manifest-missing.json") - write_selftest_manifest(missing_manifest_path, "selftest", "fixture", [{ - "name": "clear", - "png": "absent.png", - "checks": [{"x": 0, "y": 0, "r": 10, "g": 20, "b": 30, "a": 255}], - }]) - exit_code, output = run_and_capture( - command_expect, argparse.Namespace(manifest=missing_manifest_path, dir=None) - ) - require_equal("expect exit code for a missing image", exit_code, EXIT_FAILED) - require_true("missing image message names the file", "absent.png" in output) - require_true( - "missing image message says what to check", - "Check that the file exists" in output, - ) - print("ok expect: a missing image fails once for the scene and names the path") - - empty_checks_manifest_path = os.path.join(directory, "manifest-empty.json") - write_selftest_manifest(empty_checks_manifest_path, "selftest", "fixture", [{ - "name": "clear", "png": "clear.png", "checks": [], - }]) - assert_tool_error( - lambda: load_manifest(empty_checks_manifest_path), - "proves nothing", - "manifest scene with no checks", - ) - print("ok failure path: a scene with no checks is rejected, not silently passed") - - duplicate_path = os.path.join(directory, "manifest-duplicate.json") - for key, document in ( - ("renderer", b'{"renderer":"first","renderer":"second"}'), - ("r", b'{"scenes":[{"checks":[{"r":255,"r":0}]}]}'), - ): - write_file_bytes(duplicate_path, document, "duplicate key fixture") - assert_tool_error(lambda: load_manifest(duplicate_path), - f"manifest '{duplicate_path}': duplicate key {key!r}", - f"duplicate manifest key {key}") - print("ok manifest: duplicate top-level and nested keys cannot hide declarations") - - -def step_diff_metrics(): - """Assert diff metrics and heatmap colours for one known two-pixel change.""" - reference = make_solid_raster(4, 3, PNG_COLOUR_TYPE_RGB, (0, 20, 30), "selftest reference") - candidate = Raster( - width=4, height=3, colour_type=PNG_COLOUR_TYPE_RGB, - pixels=bytearray(reference.pixels), source_path="selftest candidate", - ) - candidate.pixels[(1 * 4 + 1) * 3:(1 * 4 + 1) * 3 + 3] = bytes((255, 20, 30)) - candidate.pixels[(2 * 4 + 2) * 3:(2 * 4 + 2) * 3 + 3] = bytes((0, 20, 31)) - - stats = compare_rasters(reference, candidate) - require_equal("differing pixel count", stats.differing_pixels, 2) - require_equal("total pixel count", stats.total_pixels, 12) - require_equal("first differing coordinate", stats.first_difference, (1, 1)) - require_equal("max channel delta", stats.max_channel_delta, 255) - require_equal("differing percent", round(stats.differing_percent, 6), - round(100.0 * 2 / 12, 6)) - require_equal("mean absolute channel delta", round(stats.mean_absolute_delta, 6), - round(256 / 48, 6)) - require_equal("identical rasters report no difference", - compare_rasters(reference, reference).differing_pixels, 0) - - heatmap = build_heatmap(reference, candidate) - require_equal("heatmap unchanged pixel is dark grey", heatmap.stored_pixel(0, 0), - HEATMAP_UNCHANGED) - require_equal("heatmap delta 255 pixel is red", heatmap.stored_pixel(1, 1), (255, 0, 0)) - require_equal("heatmap delta 1 pixel is blue", heatmap.stored_pixel(2, 2), (0, 0, 255)) - print("ok diff metrics: 2 known pixels give exact count, percent, mean, max and first") - print("ok heatmap: grey unchanged, red at delta 255, blue at delta 1") - - -def step_diff_edge_cases(): - """Assert scan order, alpha-only differences and size-mismatch refusal.""" - reference = make_solid_raster( - 4, 3, PNG_COLOUR_TYPE_RGB, (0, 20, 30), "selftest reference" - ) - row_order_candidate = Raster( - width=4, height=3, colour_type=PNG_COLOUR_TYPE_RGB, - pixels=bytearray(reference.pixels), source_path="selftest row order", - ) - row_order_candidate.pixels[3 * 3:3 * 3 + 3] = bytes((1, 20, 30)) - row_order_candidate.pixels[(1 * 4) * 3:(1 * 4) * 3 + 3] = bytes((2, 20, 30)) - require_equal( - "first difference follows row-major order, not column order", - compare_rasters(reference, row_order_candidate).first_difference, - (3, 0), - ) - - alpha_pixels = bytearray() - for offset in range(0, len(reference.pixels), 3): - alpha_pixels.extend(reference.pixels[offset:offset + 3]) - alpha_pixels.append(OPAQUE_ALPHA) - alpha_candidate = Raster( - width=4, height=3, colour_type=PNG_COLOUR_TYPE_RGBA, - pixels=alpha_pixels, source_path="selftest alpha", - ) - alpha_candidate.pixels[3] = OPAQUE_ALPHA - 1 - alpha_stats = compare_rasters(reference, alpha_candidate) - require_equal("alpha-only difference is counted", alpha_stats.differing_pixels, 1) - require_equal("alpha-only difference has delta 1", alpha_stats.max_channel_delta, 1) - require_equal("alpha-only difference coordinate", alpha_stats.first_difference, (0, 0)) - - wrong_tint = make_solid_raster( - 4, 3, PNG_COLOUR_TYPE_RGB, (200, 30, 60), "selftest wrong tint" - ) - wrong_tint_stats = compare_rasters(reference, wrong_tint) - whole_frame_note = whole_frame_difference_note("fullscreen", wrong_tint_stats) - require_true("whole-frame hint names the scene", "'fullscreen'" in whole_frame_note) - require_true("whole-frame hint points at the tint", "tint" in whole_frame_note) - require_equal("partial difference gets no whole-frame hint", - whole_frame_difference_note("clear", alpha_stats), "") - print("ok diff edge cases: row-major first difference, alpha-only delta, tint hint") - - larger = make_solid_raster(5, 3, PNG_COLOUR_TYPE_RGB, (0, 20, 30), "selftest wider") - assert_tool_error( - lambda: compare_rasters(reference, larger), - "re-render at the same size", - "comparing images of different sizes", - ) - print("ok failure path: mismatched image sizes refuse to compare and say so") - - -def step_diff_command(directory): - """Assert diff exit codes and the heatmap file it writes.""" - reference_directory = os.path.join(directory, "reference-images") - candidate_directory = os.path.join(directory, "candidate-images") - make_selftest_directory(reference_directory) - make_selftest_directory(candidate_directory) - - reference_image = make_solid_raster( - 4, 3, PNG_COLOUR_TYPE_RGB, (0, 20, 30), "selftest reference image" - ) - candidate_image = Raster( - width=4, height=3, colour_type=PNG_COLOUR_TYPE_RGB, - pixels=bytearray(reference_image.pixels), source_path="selftest candidate image", - ) - candidate_image.pixels[(0 * 4 + 3) * 3:(0 * 4 + 3) * 3 + 3] = bytes((255, 20, 30)) - write_png(os.path.join(reference_directory, "clear.png"), reference_image) - # Different file names prove diff reads each manifest's own png field. - write_png(os.path.join(candidate_directory, "shim-clear.png"), candidate_image) - - reference_manifest_path = os.path.join(reference_directory, "manifest.json") - candidate_manifest_path = os.path.join(candidate_directory, "manifest.json") - common = { - "name": "clear", - "checks": [{"x": 0, "y": 0, "r": 10, "g": 20, "b": 30, "a": 255}], - } - write_selftest_manifest( - reference_manifest_path, "native", "fixture", - [dict(common, png="clear.png")], - ) - write_selftest_manifest( - candidate_manifest_path, "shim", "fixture", - [dict(common, png="shim-clear.png")], - ) - - arguments = argparse.Namespace( - reference=reference_manifest_path, - candidate=candidate_manifest_path, - reference_dir=None, - candidate_dir=None, - max_differing_percent=0.0, - max_mean_delta=0.0, - ) - exit_code, output = run_and_capture(command_diff, arguments) - require_equal("diff exit code for a changed pixel", exit_code, EXIT_FAILED) - require_true("diff row names the scene", "FAIL clear" in output) - diff_path = os.path.join(candidate_directory, "clear.diff.png") - require_true("diff wrote the heatmap beside the candidate", os.path.isfile(diff_path)) - require_equal("written heatmap marks the changed pixel red", - read_png(diff_path).stored_pixel(3, 0), (255, 0, 0)) - print("ok diff: changed scene exits 1 and writes clear.diff.png beside the candidate") - - arguments.max_differing_percent = 100.0 - arguments.max_mean_delta = 1000.0 - exit_code, output = run_and_capture(command_diff, arguments) - require_equal("diff exit code inside generous thresholds", exit_code, EXIT_PASSED) - require_true("relaxed thresholds still report the pixel count", - "differing 1/12" in output) - print("ok diff: generous thresholds pass the same scene without hiding its delta") - - -def step_argument_parsing(): - """Assert threshold and pixel arguments accept good text and reject the rest.""" - require_equal("zero threshold", non_negative_float("0"), 0.0) - require_equal("fractional threshold", non_negative_float("1.5"), 1.5) - require_equal("pixel coordinate", pixel_coordinate_argument("12,34"), (12, 34)) - for bad_threshold in ("-1", "nan", "inf", "abc"): - assert_argument_error( - lambda text=bad_threshold: non_negative_float(text), - f"threshold {bad_threshold!r}", - ) - for bad_pixel in ("12", "1,2,3", "a,b"): - assert_argument_error( - lambda text=bad_pixel: pixel_coordinate_argument(text), - f"pixel {bad_pixel!r}", - ) - print("ok arguments: thresholds reject negative, NaN, inf and text; pixels need x,y") - - -def run_selftest_steps(directory): - """Run every selftest step in order; each step prints its own ok line.""" - step_png_roundtrip(directory) - step_png_error_paths(directory) - step_filter_decoders() - step_argument_parsing() - step_orientation_and_channel_order(directory) - step_expect_matching(directory) - step_expect_failures(directory) - step_expect_missing_and_invalid(directory) - step_diff_metrics() - step_diff_edge_cases() - step_diff_command(directory) - - -def command_selftest(arguments): - """Run the selftest in a temporary directory and return its exit code.""" - try: - working_directory = tempfile.mkdtemp(prefix="compare-selftest-") - except OSError as error: - raise ToolError( - f"selftest cannot create a temporary directory: {error}. " - f"Check that %TEMP% is writable" - ) - print(f"selftest: fixtures in {working_directory}") - try: - run_selftest_steps(working_directory) - except SelftestMismatch as mismatch: - print(f"FAIL {mismatch}") - print(f"fixtures kept for inspection: {working_directory}") - return EXIT_FAILED - except ToolError as error: - # A broken fixture is a failed selftest, not a usage error: the tool ran. - print(f"FAIL selftest could not complete: {error}") - print(f"fixtures kept for inspection: {working_directory}") - return EXIT_FAILED - shutil.rmtree(working_directory, ignore_errors=True) - print("selftest passed") - return EXIT_PASSED - - -# --------------------------------------------------------------------------- -# Command line -# --------------------------------------------------------------------------- - - -def non_negative_float(text): - """argparse type for a finite threshold that may be zero but never negative.""" - try: - value = float(text) - except ValueError: - raise argparse.ArgumentTypeError(f"'{text}' is not a number") - # NaN would compare false against every threshold and silently pass all scenes. - if not math.isfinite(value): - raise argparse.ArgumentTypeError(f"'{text}' is not a finite number") - if value < 0: - raise argparse.ArgumentTypeError(f"'{text}' is negative; use 0 or more") - return value - - -def add_expect_command(subparsers): - """Register the expect subcommand and its arguments.""" - expect_parser = subparsers.add_parser( - "expect", - help="verify every pixel declared in a manifest", - description=( - "Read each scene's PNG, compare every declared check, and print one PASS " - "or FAIL line per check with expected and actual values. A missing or " - "unreadable image fails its whole scene with the path and what to check." - ), - ) - expect_parser.add_argument("--manifest", required=True, - help="manifest.json written by the renderer") - expect_parser.add_argument( - "--dir", default=None, - help="directory holding the PNGs (default: the manifest's directory)", - ) - expect_parser.set_defaults(handler=command_expect) - - -def add_diff_command(subparsers): - """Register the diff subcommand and its arguments.""" - diff_parser = subparsers.add_parser( - "diff", - help="compare two renderers' images scene by scene", - description=( - "For every scene the reference manifest declares, compare its PNG against " - "the candidate's. Prints differing pixel count, percent, mean absolute " - "channel delta, maximum channel delta and the first differing coordinate. " - "Writes .diff.png beside the candidate image: unchanged pixels are " - "dark grey, differing pixels ramp from blue (delta 1) to red (delta 255)." - ), - ) - diff_parser.add_argument("--reference", required=True, - help="manifest.json for the reference renderer") - diff_parser.add_argument("--candidate", required=True, - help="manifest.json for the renderer under test") - diff_parser.add_argument( - "--reference-dir", default=None, - help="reference image directory (default: that manifest's directory)", - ) - diff_parser.add_argument( - "--candidate-dir", default=None, - help="candidate image directory (default: that manifest's directory)", - ) - diff_parser.add_argument( - "--max-differing-percent", type=non_negative_float, default=0.0, - help="fail a scene above this percent of differing pixels (default 0.0)", - ) - diff_parser.add_argument( - "--max-mean-delta", type=non_negative_float, default=0.0, - help="fail a scene above this mean absolute channel delta (default 0.0)", - ) - diff_parser.set_defaults(handler=command_diff) - - -def add_inspect_command(subparsers): - """Register the inspect subcommand and its arguments.""" - inspect_parser = subparsers.add_parser( - "inspect", - help="print an image's size, colour type and pixel values", - description=( - "Decode one PNG and print its dimensions, colour type and the requested " - "pixels. Without --pixel it prints the four corners and the centre." - ), - ) - inspect_parser.add_argument("--image", required=True, help="PNG file to read") - inspect_parser.add_argument( - "--pixel", type=pixel_coordinate_argument, action="append", default=None, - metavar="X,Y", help="pixel to print, for example --pixel 12,34 (repeatable)", - ) - inspect_parser.set_defaults(handler=command_inspect) - - -def add_selftest_command(subparsers): - """Register the selftest subcommand.""" - selftest_parser = subparsers.add_parser( - "selftest", - help="prove the reader, writer, expect, diff and heatmap on built-in fixtures", - description=( - "Write fixture PNGs into a temporary directory, then assert known pixel " - "reads, all five PNG filters, expectation matching, diff metrics, heatmap " - "colours and the failure paths. Leaves nothing behind; exits 1 on a mismatch." - ), - ) - selftest_parser.set_defaults(handler=command_selftest) - - -def build_argument_parser(): - """Build the full CLI: shared help text plus four subcommands.""" - parser = argparse.ArgumentParser( - prog="compare.py", - description=( - "Check rendered PNGs against the pixel checks a manifest declares, or " - "measure how far two renderers' images differ. The tool reads only " - "manifest.json and PNG files; it never parses C++." - ), - formatter_class=argparse.RawDescriptionHelpFormatter, - epilog=( - "examples:\n" - " python compare.py expect --manifest D:\\conform\\native\\manifest.json\n" - " python compare.py diff --reference native\\manifest.json " - "--candidate shim\\manifest.json\n" - " python compare.py inspect --image shim\\clear.png --pixel 0,0\n" - " python compare.py selftest\n" - "\n" - "exit codes: 0 passed, 1 mismatch found, 2 could not run (bad input).\n" - ), - ) - subparsers = parser.add_subparsers( - dest="mode", required=True, metavar="{expect,diff,inspect,selftest}" - ) - add_expect_command(subparsers) - add_diff_command(subparsers) - add_inspect_command(subparsers) - add_selftest_command(subparsers) - return parser - - -def main(argv=None): - """Parse arguments, run one mode and translate failures into exit codes. - - 0 passed, 1 the run completed and found a mismatch, 2 the tool could not run. - An exception the tool did not anticipate is a 2, never a 1: a calling script must be - able to tell "the pixels differ" from "this program crashed". - """ - arguments = build_argument_parser().parse_args(argv) - try: - return arguments.handler(arguments) - except ToolError as error: - print(f"error: {error}", file=sys.stderr) - return EXIT_ERROR - except Exception: # noqa: BLE001 - deliberate: report and exit 2, never mask as a mismatch - traceback.print_exc() - print("error: unexpected failure; this is a bug in compare.py, not a pixel mismatch", - file=sys.stderr) - return EXIT_ERROR - - -if __name__ == "__main__": - sys.exit(main()) diff --git a/tools/conformance/native/CMakeLists.txt b/tools/conformance/native/CMakeLists.txt deleted file mode 100644 index 599080cca..000000000 --- a/tools/conformance/native/CMakeLists.txt +++ /dev/null @@ -1,108 +0,0 @@ -cmake_minimum_required(VERSION 3.21) -project(conform_native LANGUAGES CXX) - -# The scene contract and the HLSL are the shared spec; this project only reads them. -set(CONFORM_SPEC_DIR "${CMAKE_CURRENT_SOURCE_DIR}/../spec" CACHE PATH - "Directory holding scenes.h and shaders/") -set(DXC_EXECUTABLE - "C:/Program Files (x86)/Windows Kits/10/bin/10.0.26100.0/x64/dxc.exe" - CACHE FILEPATH "DirectX Shader Compiler") - -if(NOT EXISTS "${CONFORM_SPEC_DIR}/scenes.h") - message(FATAL_ERROR - "scenes.h not found at ${CONFORM_SPEC_DIR}/scenes.h. Point -DCONFORM_SPEC_DIR at the " - "directory that holds scenes.h and shaders/.") -endif() -if(NOT EXISTS "${DXC_EXECUTABLE}") - message(FATAL_ERROR - "dxc.exe not found at ${DXC_EXECUTABLE}. Install the Windows SDK or pass " - "-DDXC_EXECUTABLE=.") -endif() - -if(NOT MSVC) - message(FATAL_ERROR "This project targets the Visual Studio toolchain; use -G \"Visual Studio 17 2022\" -A x64.") -endif() -set(CMAKE_CXX_STANDARD 20) -set(CMAKE_CXX_STANDARD_REQUIRED ON) -set(CMAKE_CXX_EXTENSIONS OFF) - -set(SHADER_OUTPUT_DIR "${CMAKE_CURRENT_BINARY_DIR}/shaders") -file(MAKE_DIRECTORY "${SHADER_OUTPUT_DIR}") - -set(FULLSCREEN_HLSL "${CONFORM_SPEC_DIR}/shaders/fullscreen_color.hlsl") -set(VERTEX_COLOR_HLSL "${CONFORM_SPEC_DIR}/shaders/vertex_color.hlsl") - -set(FULLSCREEN_VS_CSO "${SHADER_OUTPUT_DIR}/fullscreen_color.vs.cso") -set(FULLSCREEN_PS_CSO "${SHADER_OUTPUT_DIR}/fullscreen_color.ps.cso") -set(VERTEX_COLOR_VS_CSO "${SHADER_OUTPUT_DIR}/vertex_color.vs.cso") -set(VERTEX_COLOR_PS_CSO "${SHADER_OUTPUT_DIR}/vertex_color.ps.cso") - -# -Qstrip_debug and -Qstrip_reflect keep the .cso small and deterministic: nothing in the -# file depends on the build directory or the machine. -WX makes a shader warning a build -# failure rather than a silent behaviour change in the reference images. -set(DXC_COMMON_ARGS -nologo -O3 -WX -Qstrip_debug -Qstrip_reflect) - -add_custom_command( - OUTPUT "${FULLSCREEN_VS_CSO}" - COMMAND "${DXC_EXECUTABLE}" -T vs_6_6 -E VSMain ${DXC_COMMON_ARGS} - "-Fo${FULLSCREEN_VS_CSO}" "${FULLSCREEN_HLSL}" - DEPENDS "${FULLSCREEN_HLSL}" "${DXC_EXECUTABLE}" - COMMENT "Compiling fullscreen_color.hlsl VSMain as vs_6_6" - VERBATIM) - -add_custom_command( - OUTPUT "${FULLSCREEN_PS_CSO}" - COMMAND "${DXC_EXECUTABLE}" -T ps_6_6 -E PSMain ${DXC_COMMON_ARGS} - "-Fo${FULLSCREEN_PS_CSO}" "${FULLSCREEN_HLSL}" - DEPENDS "${FULLSCREEN_HLSL}" "${DXC_EXECUTABLE}" - COMMENT "Compiling fullscreen_color.hlsl PSMain as ps_6_6" - VERBATIM) - -add_custom_command( - OUTPUT "${VERTEX_COLOR_VS_CSO}" - COMMAND "${DXC_EXECUTABLE}" -T vs_6_6 -E VSMain ${DXC_COMMON_ARGS} - "-Fo${VERTEX_COLOR_VS_CSO}" "${VERTEX_COLOR_HLSL}" - DEPENDS "${VERTEX_COLOR_HLSL}" "${DXC_EXECUTABLE}" - COMMENT "Compiling vertex_color.hlsl VSMain as vs_6_6" - VERBATIM) - -add_custom_command( - OUTPUT "${VERTEX_COLOR_PS_CSO}" - COMMAND "${DXC_EXECUTABLE}" -T ps_6_6 -E PSMain ${DXC_COMMON_ARGS} - "-Fo${VERTEX_COLOR_PS_CSO}" "${VERTEX_COLOR_HLSL}" - DEPENDS "${VERTEX_COLOR_HLSL}" "${DXC_EXECUTABLE}" - COMMENT "Compiling vertex_color.hlsl PSMain as ps_6_6" - VERBATIM) - -add_custom_target(conform_shaders DEPENDS - "${FULLSCREEN_VS_CSO}" "${FULLSCREEN_PS_CSO}" - "${VERTEX_COLOR_VS_CSO}" "${VERTEX_COLOR_PS_CSO}") - -add_executable(conform_native - src/main.cpp - src/diagnostics.cpp - src/gpu.cpp - src/renderer.cpp - src/scene_plan.cpp - src/png_io.cpp - src/verify.cpp - src/manifest.cpp) - -target_include_directories(conform_native PRIVATE "${CONFORM_SPEC_DIR}") -target_compile_definitions(conform_native PRIVATE NOMINMAX WIN32_LEAN_AND_MEAN) -# /we4062 is separate from /W4 because C4062 (enumerator not handled in a switch that has -# no default) is off by default, so /W4 /WX would let a new SceneKind render as a clear. -target_compile_options(conform_native PRIVATE /W4 /WX /we4062 /permissive- /utf-8 /EHsc) -target_link_libraries(conform_native PRIVATE d3d12 dxgi windowscodecs ole32) -add_dependencies(conform_native conform_shaders) - -add_custom_command(TARGET conform_native POST_BUILD - COMMAND "${CMAKE_COMMAND}" -E make_directory "$/shaders" - COMMAND "${CMAKE_COMMAND}" -E copy_if_different - "${FULLSCREEN_VS_CSO}" "${FULLSCREEN_PS_CSO}" - "${VERTEX_COLOR_VS_CSO}" "${VERTEX_COLOR_PS_CSO}" - "$/shaders/" - COMMENT "Copying compiled shaders next to conform_native.exe" - VERBATIM) - -set_property(DIRECTORY "${CMAKE_CURRENT_SOURCE_DIR}" PROPERTY VS_STARTUP_PROJECT conform_native) diff --git a/tools/conformance/native/README.md b/tools/conformance/native/README.md deleted file mode 100644 index be56a16c7..000000000 --- a/tools/conformance/native/README.md +++ /dev/null @@ -1,363 +0,0 @@ -# conform_native - -Native D3D12 golden-image renderer for the conformance suite. It renders every scene in -`../spec/scenes.h` into an offscreen 256x256 `R8G8B8A8_UNORM` colour target, reads the -colour back through a readback heap, checks every `conform::PixelCheck` against the -pixels, and writes `.png` plus `manifest.json`. - -No swapchain, no window, no present. One process run produces one complete set of images. - -The contract lives in `../spec` and is read, never modified: - -| Input | Used for | -| --- | --- | -| `../spec/scenes.h` | scene list, per-scene tint, clear values, scissor rect, geometry, PixelChecks | -| `../spec/shaders/fullscreen_color.hlsl` | `vs_6_6`/`ps_6_6`, entries `VSMain`/`PSMain` | -| `../spec/shaders/vertex_color.hlsl` | `vs_6_6`/`ps_6_6`, entries `VSMain`/`PSMain` | - -## Build - -```bat -cd tools/conformance/native -"C:\Program Files\CMake\bin\cmake.exe" -S . -B build -G "Visual Studio 17 2022" -A x64 -"C:\Program Files\CMake\bin\cmake.exe" --build build --config Release --parallel -``` - -Equivalently: `powershell -NoProfile -ExecutionPolicy Bypass -File scripts\build.ps1`. - -Requirements, all already present on this machine: - -* Visual Studio 2022 x64 toolset (`C:\Program Files (x86)\Microsoft Visual Studio\2022\BuildTools`). -* Windows SDK 10.0.26100 (`d3d12`, `dxgi`, `windowscodecs`; no d3dx12 helpers, no third-party code). -* `dxc.exe` at `C:\Program Files (x86)\Windows Kits\10\bin\10.0.26100.0\x64\dxc.exe`. - Override with `-DDXC_EXECUTABLE=` if the SDK moves. - -The build compiles the four shader entry points into `build/shaders/*.cso` -(`-T vs_6_6` / `-T ps_6_6`, `-O3 -WX -Qstrip_debug -Qstrip_reflect`) and copies them next -to the executable. The program loads those `.cso` files at startup; if they are missing it -stops with the filename and the target that produces them rather than falling back to -anything. - -## Run - -```bat -tools/conformance/native\build\Release\conform_native.exe tools/conformance/native\out\run1 -``` - -``` -usage: conform_native [options] - --shaders where the .cso files live (default: \shaders) - --adapter adapter from the printed list (default: most dedicated - memory, non-software) - --debug-layer enable D3D12 validation and fail on validation errors - --help print this text -``` - -Exit codes: `0` every check passed, `1` a check failed or the run could not complete, -`2` bad command line. The output directory is created if absent. - -Each run prints one line per check: - -``` -PASS readback scene=blend (128,128) expected 105,25,45,255 actual 105,25,45,255 0.5*(200,30,60) + 0.5*(10,20,30) = (105,25,45) -``` - -`readback` verifies the pixels copied out of the render target. `png` re-decodes the PNG -that was just written with WIC and runs the same checks against it, so a channel swap or a -truncated file in the encoder path fails the run instead of silently shipping. - -## Baseline state conformance - -The header's baseline table is not documentation in this renderer; it is the state that is -set. Where each row lives: - -| Baseline row | Set in | -| --- | --- | -| topology `TRIANGLELIST` | `BindPipelineAndDraw` — `IASetPrimitiveTopology` | -| cull `NONE`, fill `SOLID`, `FrontCounterClockwise FALSE` | `MakeBasePipelineDescription` | -| sample count 1, sample mask `0xFFFFFFFF`, no MSAA | `MakeBasePipelineDescription` | -| `RenderTargetWriteMask = ALL` | `MakeBasePipelineDescription` | -| viewport `(0,0,256,256)`, depth 0..1 | `Renderer::Initialize` | -| scissor full target unless the scene says otherwise | `MakeDrawPlan` | -| root signature: one root CBV at b0, visibility ALL, space 0, `ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT` | `CreateSceneRootSignature` | -| constant buffer: one float4 at offset 0, `tint/255.0f` | `CreateTintConstants` (one 256-byte slot per scene), bound in `BindPipelineAndDraw` | -| depth only for `depth_order`: `D32_FLOAT`, clear 1.0, LESS, write ALL, stencil off | `ClearAndDrawScene` (DSV bound only there) + `CreateVertexColorPipeline` | -| vertex format `ClipVertex`, stride 16 | `kVertexColorInputLayout` plus two `static_assert`s on size and offset | -| index format `R16_UINT` | `CreateGeometryBuffers` | - -The vertex-colour shaders do not read b0; the constant buffer is bound for those draws -anyway so all three pipelines share the single signature the header names. - -## Output - -Six PNGs, 8-bit RGBA (`colour type 6`), 256x256, top-left origin, plus `manifest.json`: - -```json -{ - "renderer": "native", - "adapter": "NVIDIA GeForce RTX 5070 Ti", - "scenes": [ - { - "name": "clear", - "png": "clear.png", - "checks": [ - {"x": 0, "y": 0, "r": 10, "g": 20, "b": 30, "a": 255, "why": "top-left is the clear colour"} - ] - } - ] -} -``` - -Every check is copied from `scenes.h` (`checkCount`, up to the header's five); the diff -tool never parses C++. The manifest carries no timestamp, run counter or build path, so it -is byte-comparable between runs. - -## Verified - -Transcripts from this machine: RTX 5070 Ti (default pick) and AMD Radeon iGPU -(`--adapter 0`), one Windows install. - -**All checks pass, both adapters.** `scripts\verify.ps1` prints `VERIFY: PASS` and exits 0: - -``` -ok run A exits 0 (all PixelChecks pass) -ok run A wrote 7 files (6 PNGs + manifest.json), found 7 -ok identical bytes: blend.png 75AD77065361FAF4951974525D00B1AB92154E04EB375FD87DB883BC10E2217F -ok identical bytes: clear.png 28DDD65A36CF858D64E12F07D3BD910AC06B7EA9C45C20E8EB8C6F22FF5857DC -ok identical bytes: depth_order.png B01EA5355093A8AEDF4B625422A46EE3647214C51371E4B04D6ECC4630C97C5F -ok identical bytes: fullscreen.png 7AFB53BFBBF7FE54D59B9BFA12D46F118E81D25C1DD951596CA466D8B2A5FFEC -ok identical bytes: indexed.png 52043F2B0F9C79DCFF1A85873642FE6DA11E3357B17D2471E8F726AAD85DFD04 -ok identical bytes: manifest.json 8029372FD2147D99F965F1C0AE31E8E051ADA1C897F7ED0D3E6C90310AC51420 -ok identical bytes: scissor.png 394DAD5B4BF2D8AF0B79132A79750A8AE40305DBA443BFACA5D84DF332028E48 -ok render on adapter 0 exits 0 -ok adapter 0 passes all 18 readback checks -ok adapter 0 passes all 18 PNG checks -... -VERIFY: PASS -``` - -| Scene | Checks | Readback | PNG | -| --- | --- | --- | --- | -| clear | 3 | pass | pass | -| fullscreen | 3 | pass | pass | -| depth_order | 2 | pass | pass | -| scissor | 5 | pass | pass | -| blend | 2 | pass | pass | -| indexed | 3 | pass | pass | -| **total** | **18** | **18/18** | **18/18** | - -Rendered identically on `NVIDIA GeForce RTX 5070 Ti` (default) and `AMD Radeon(TM) -Graphics` (`--adapter 0`). Same PNG hashes on the NVIDIA adapter across two runs. - -**The scenes are not vacuous.** A throwaway copy with three pieces of state disabled -(`scripts/negative-control.ps1`, build discarded afterwards) produced exactly the failures -each scene claims to catch, and nothing else: - -``` -FAIL readback scene=depth_order (128,128) expected 40,160,90,255 actual 220,40,40,255 -FAIL readback scene=scissor (40,64) expected 10,20,30,255 actual 70,140,210,255 -FAIL readback scene=scissor (180,64) expected 10,20,30,255 actual 70,140,210,255 -FAIL readback scene=scissor (112,24) expected 10,20,30,255 actual 70,140,210,255 -FAIL readback scene=scissor (112,104) expected 10,20,30,255 actual 70,140,210,255 -FAIL readback scene=blend (128,128) expected 105,25,45,255 actual 200,30,60,128 -FAIL readback scene=blend (8,8) expected 105,25,45,255 actual 200,30,60,128 -readback checks: 11 passed, 7 failed -``` - -That is: with `DepthEnable = FALSE` the far red quad drawn second wins (proving the depth -test is what keeps green); with the scissor widened to the full target the four outside -checks see the tint; with `BlendEnable = FALSE` the source colour lands unchanged, alpha -128 included. Clear, fullscreen and indexed still passed, so the failures are attributable. - -**The images are the expected shapes.** Read the PNGs back and looked at them: -`depth_order.png` is a full-height red rectangle with a green rectangle over its left two -thirds and a clear border where the quads stop at ±0.95; `scissor.png` is a filled blue -rectangle inset from every edge (the 48..176 × 32..96 rect); `indexed.png` is two right -triangles, yellow and blue, with clear space between and below them. - -**PNG structure.** IHDR of all six files: `width 256 height 256 bitdepth 8 colortype 6`. - -**Shader bytecode.** `dxc -dumpbin` on the four `.cso` files reports -`EntryFunctionName: VSMain` / `PSMain`, `Vertex Shader` / `Pixel Shader`, and the input -signatures the code assumes: `SV_VertexID` for the fullscreen VS, `POSITION`/`COLOR` for -the vertex-colour VS, `SV_Position`/`COLOR` for its PS, and a `cbuffer` in the fullscreen -PS. - -**Failure paths exercised** (`scripts/failure-log.cmd`, merged stdout+stderr, all exit -non-zero, all naming the file and the next thing to check): - -``` -=== output path is an existing file -FAIL tools/conformance/native\src\main.cpp:154 std::filesystem::create_directories -> could not create tools/conformance/native\out\failures\blocked: Cannot create a file when that file already exists. Check: the path is a directory the process can write to, not an existing file and not a read-only volume -EXITCODE 1 - -=== shader directory with no .cso files -FAIL tools/conformance/native\src\renderer.cpp:420 std::ifstream::open -> could not open tools/conformance/native\out\failures\no-shaders\fullscreen_color.vs.cso. Check: the build ran the conform_shaders target and the shaders directory sits next to conform_native.exe; use --shaders to point elsewhere -EXITCODE 1 - -=== PNG path occupied by a directory -PASS readback scene=clear (0,0) expected 10,20,30,255 actual 10,20,30,255 top-left is the clear colour -FAIL tools/conformance/native\src\png_io.cpp:61 IWICStream::InitializeFromFilename -> HRESULT 0x80070005. Check: the output directory is writable and nothing else holds tools/conformance/native\out\failures\png-blocked\clear.png open -readback checks: 3 passed, 0 failed -png checks: 0 passed, 0 failed -RESULT: FAIL (run did not complete) -EXITCODE 1 -``` - -The third case is an unwritable output path (a directory occupies `clear.png`): rendering -and readback verification still ran and passed for that scene; the run exits non-zero -because no PNG was written. Command-line errors exit 2 and print usage (no arguments, -unknown flag, missing option value, bad `--adapter` value, two positional directories). - -## Decisions a reviewer should agree with, or overrule - -1. **Three pipeline states, not two.** D3D12 bakes blend state into a PSO and has no - `OMSetBlendState`, so the blend scene needs its own. Fullscreen and blend share the root - signature and shaders and differ only in `D3D12_BLEND_DESC`, so the split isolates blend - rather than duplicating anything. -2. **Scissor is per-scene state, not pipeline state.** `D3D12_RASTERIZER_DESC` has no - `ScissorEnable` (that is D3D11). D3D12 applies the scissor rect whenever one is set, so - the scissor scene is the fullscreen pipeline plus `RSSetScissorRects(48,32,176,96)`. - The negative control above shows the rect is load-bearing: widen it and four checks fail. -3. **One DSV binding, for `depth_order` only.** The header's baseline says every other - scene binds no DSV, so `OMSetRenderTargets` passes `nullptr` for them. The indexed scene - uses the depth-enabled vertex-colour PSO with no DSV bound, which leaves depth testing - inert; that is the same PSO the contract asks for, not a fourth state. -4. **One 256-byte constant-buffer slot per scene.** A root CBV must be 256-byte aligned and - each scene now carries its own tint. Each slot's float4 sits at byte offset 0 of its - slot, so the shader sees exactly "a single float4 at offset 0". Slots are filled once - before any draw and never rewritten, so no CPU write can race a GPU read. -5. **No sRGB anywhere.** Target format is `R8G8B8A8_UNORM` (not `_SRGB`), clears are - `byte/255.0f`, and WIC writes the bytes it is given. Nothing converts. - -## Not covered - -* **D3D12 validation was not available on this machine.** `--debug-layer` reports - `the D3D12 debug layer is not installed (HRESULT 0x887A002D)` and continues without it. - The plumbing (`ID3D12InfoQueue` drain, failure on validation errors) is implemented but - has never validated anything here. Install the Graphics Tools optional feature to - exercise it. This is the largest gap in the verification. -* Only two adapters were tried, both on one Windows install. The software adapter - `Microsoft Basic Render Driver` (index 2) was listed but not rendered on. -* Device-removed and GPU-hang paths (`GetDeviceRemovedReason`, 60 s fence timeout) are - coded but never triggered; forcing a TDR needs a debugger or a fault-injection build. -* PNG determinism is verified on this WIC build only. WIC's zlib output is stable here, but - that is an observation about this machine, not a documented Windows guarantee. The - pixels are deterministic; the compressed bytes are a WIC implementation detail. -* The depth buffer is never read back, so depth correctness is inferred from colour. The - negative control closes that gap for this scene (colour changes when depth is disabled), - but there is no direct depth-value check. -* 16-bit indices are configured (`DXGI_FORMAT_R16_UINT`) and the shuffled index buffer - draws the expected triangles, but no scene has more than 8 vertices, so nothing proves - behaviour past 65 535 indices. -* `scenes.h` allows at most 5 checks per scene (`PixelCheck checks[5]`); the manifest and - verifier iterate `checkCount` and would read past the array if the contract raised it - without changing the struct. -* No swapchain, present, resize or multi-frame path is implemented or tested; out of scope - for a golden-image tool. -* Nothing here validates the Vulkan shim's output. That comparison needs the diff tool. - -## Contract revision (05:07) - -The shared header was replaced mid-work. Changes and how they landed: - -| Header change | What the renderer does now | -| --- | --- | -| baseline pipeline table | one root signature (CBV b0, visibility ALL, `ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT`); see the conformance table above | -| `depth_order` draw order reversed | unchanged code path: indices are drawn in header order, so the near green quad is now first and depth rejects the later red one | -| `indexed` vertices/indices shuffled, third check | unchanged code path: the vertex and index arrays are uploaded as declared | -| scissor rect `{48,32,176,96}`, five checks | `MakeDrawPlan` reads `kScissor*`; checks at all four outside edges now run | -| per-scene tint (`tintR/G/B/A`) | one CB slot per scene, filled from each `Scene` | -| `checks[5]`, 2..5 per scene | verifier and manifest already iterate `checkCount` | -| blend alpha `ONE/INV_SRC_ALPHA` | PSO updated from the previous `ZERO/ONE`; `SrcBlendAlpha = ONE`, `DestBlendAlpha = INV_SRC_ALPHA` | - -After the revision: 18/18 readback and 18/18 PNG on both adapters, and determinism holds -(`verify.ps1`: `VERIFY: PASS`). Only `scissor.png` and `manifest.json` changed bytes -relative to the pre-revision run; the other five PNGs are byte-identical, which is what the -contract predicts — the reversed depth order and shuffled indices produce the same image -when implemented correctly, and 128/255 with `ONE/INV_SRC_ALPHA` resolves to the same -8-bit blend result the header says it should. - -## What changed in review - -Three passes in the order `REVIEW.md` asks for. Every fix was re-verified by the build and -`scripts\verify.ps1` after the change. - -**Pass 1 — functional.** - -* Finding: first build failed with `C2065: 'D3D12_COMMAND_QUEUE_TYPE_DIRECT'` and - `C2039: 'ScissorEnable' is not a member of 'D3D12_RASTERIZER_DESC'`. - Fix: queue type is `D3D12_COMMAND_LIST_TYPE_DIRECT`; the scissor PSO was deleted because - D3D12 has no scissor enable bit, and the scissor rect became per-scene state. - Evidence: `BUILD EXIT 0`; scissor checks pass and fail correctly in the negative control. -* Finding: the first run passed everything, which is not evidence by itself. - Checked the blend arithmetic by hand and changed the alpha channel to the header's - `ONE/INV_SRC_ALPHA`; then built the negative control to prove the passing scenes react to - their state. Evidence: negative-control transcript above. -* Finding: a stray closing brace after `CreatePipelines` (bad edit) broke the build with - `C2059`. - Fix: removed. Evidence: `BUILD EXIT 0`. - -**Pass 2 — legibility.** - -* Finding: FAIL diagnostics appeared above the program banner because stdout was buffered - and stderr was not. Fix: `setvbuf(stdout, nullptr, _IONBF, 0)` in `main`. Evidence: the - merged failure transcript now reads banner → `FAIL …` → `RESULT: FAIL`. -* Finding: `Check: could not create ` read as a broken sentence under the - `FAIL file:line call -> detail. Check:` shape. Fix: the hint is now a testable claim - ("the output directory is writable and nothing else holds `` open"). -* Finding: a doubled period from concatenating a Win32 message that already ends in `.` - with the `. Check:` separator. Fix: `TrimTrailingPeriod`. Evidence: `… already exists. - Check: …`. -* Finding: `Renderer::full_frame_scissor` and `GpuContext::adapter_index` were written and - never read. Fix: both removed. Evidence: clean rebuild under `/W4 /WX`. -* Finding: `#include ` in `gpu.cpp` with no use. Fix: removed. -* Finding: the marker `TintKind` and two hard-coded tint addresses became dead state when - the header moved to per-scene tints. Fix: replaced by the scene's tint slot; `grep` for - `TintKind`/`kTint*` now returns nothing. - -**Pass 3 — verify and fix.** Clean rebuild from an empty `build\`, then -`scripts\verify.ps1`: 30 claims, `VERIFY: PASS`, exit 0, plus the negative control and the -failure-path log above. - -## Layout - -``` -CMakeLists.txt build, shader compilation, shader copy -scripts/build.ps1 configure + build -scripts/run.ps1 run one output directory with extra arguments; empties it first only - when it holds just a run's PNGs and manifest.json, else exits 2 -scripts/verify.ps1 re-checks every claim in this README, exits 0 only if all hold -scripts/failure-log.cmd exercises the three failure paths and prints one merged log -scripts/negative-control.ps1 throwaway build with depth/blend/scissor disabled, then deleted -src/main.cpp arguments, COM, run loop, tally, exit code -src/gpu.h/.cpp adapter choice, device, queue, fence, validation drain -src/renderer.h/.cpp targets, buffers, root signature, PSOs, recording, readback -src/scene_plan.h/.cpp Scene -> pipeline/geometry/tint slot/depth binding/scissor -src/png_io.h/.cpp WIC encode and decode -src/verify.h/.cpp PixelCheck comparison and PASS/FAIL output -src/manifest.h/.cpp manifest.json with JSON escaping -src/pixel_surface.h R8G8B8A8 pixel buffer shared by readback and decode -src/diagnostics.h/.cpp failure lines: file, call, HRESULT/error in hex, what to check -``` - -## Review pass 2 — legibility fixes applied - -A second review pass read every file against the review notes in the pull request. These were fixed and re-verified; -each line names the failure it prevents. - -| fix | file | the failure it prevents | -|---|---|---| -| Severity comparisons inverted | `gpu.cpp` `ReportValidationMessages` | `D3D12_MESSAGE_SEVERITY` counts **down** as severity rises (CORRUPTION 0 … MESSAGE 4), so `>= WARNING` printed only INFO/MESSAGE and `>= ERROR` counted everything except corruption. Real errors were printed as nothing and corruption was ignored. | -| `--debug-layer` now fails when the layer is absent | `main.cpp`, `gpu.cpp`, `gpu.h` | It printed `validation errors: 0` and could end `RESULT: PASS` on a machine where validation never ran. It now prints `validation: NOT RUN` and exits 1. | -| Enum switches can no longer fall through | `CMakeLists.txt` (`/we4062`), `scene_plan.cpp` | `DrawPlan` defaults to `{Fullscreen, None}`, so a new `SceneKind` would have rendered as a clear-only scene with no message. C4062 is off under `/W4`, so `/WX` never caught it. | -| Renderer released before the device | `gpu.h`, `gpu.cpp`, `main.cpp` | `DestroyGpuContext` ran while `Renderer` still held resources, PSOs and command lists. A `GpuContext` destructor now runs after the renderer's, and the manual teardown calls are gone. | -| Readback pitch derived, padding stripped | `renderer.cpp` | `kReadbackRowPitch` was hard-coded to `width*4` and the copy used the pitch as the row length, so any width whose pitch is padded would have produced sheared rows. | -| Index type pinned at compile time | `renderer.cpp` | The format (`R16_UINT`) and `sizeof/sizeof` counts were independent of the array types; a switch to `uint32_t` would have doubled every count with no build error. | -| Check counts validated at compile time | `verify.cpp` | A scene with `checkCount == 0` passed with nothing checked; a count above 5 read past `checks[5]`. Now a `static_assert`. | -| Validation messages that cannot be read are counted | `gpu.cpp` | `GetMessage` failures were skipped silently, hiding queue entries. | -| Negative control asserts its own result | `scripts/negative-control.ps1` | The script printed and hoped. `Replace` calls that silently did nothing produced no evidence, and the README quoted output that did not match what the current code prints. It now throws when a replacement does not match exactly once, and fails unless exactly `blend`, `depth_order` and `scissor` fail. | - -Deferred, and why: `HrSucceeded` still carries the `__FILE__`/`__LINE__` pairs instead of taking a -`std::source_location`, because renaming it touches 69 call sites and the functional pass would have to be -re-run entirely; the name is misleading but the behaviour is correct. diff --git a/tools/conformance/native/scripts/build.ps1 b/tools/conformance/native/scripts/build.ps1 deleted file mode 100644 index f665d93e8..000000000 --- a/tools/conformance/native/scripts/build.ps1 +++ /dev/null @@ -1,16 +0,0 @@ -# Builds conform_native. Run from anywhere: -# powershell -NoProfile -ExecutionPolicy Bypass -File tools\conformance\native\scripts\build.ps1 -$ErrorActionPreference = 'Stop' -$root = Split-Path -Parent $PSScriptRoot -$cmake = (Get-Command cmake -ErrorAction SilentlyContinue) -if ($cmake) { $cmake = $cmake.Path } else { $cmake = 'C:\Program Files\CMake\bin\cmake.exe' } -$source = $root -$build = Join-Path $root 'build' - -& $cmake -S $source -B $build -G 'Visual Studio 17 2022' -A x64 -if ($LASTEXITCODE -ne 0) { Write-Output "CONFIGURE EXIT $LASTEXITCODE"; exit $LASTEXITCODE } - -& $cmake --build $build --config Release --parallel -$buildExit = $LASTEXITCODE -Write-Output "BUILD EXIT $buildExit" -exit $buildExit diff --git a/tools/conformance/native/scripts/failure-log.cmd b/tools/conformance/native/scripts/failure-log.cmd deleted file mode 100644 index fde2c21cf..000000000 --- a/tools/conformance/native/scripts/failure-log.cmd +++ /dev/null @@ -1,28 +0,0 @@ -@echo off -setlocal -set EXE=%~dp0..\build\Release\conform_native.exe -set ROOT=%~dp0..\out\failures -set LOG=%~dp0..\out\failures.log -if exist "%ROOT%" rmdir /s /q "%ROOT%" -mkdir "%ROOT%" - -> "%LOG%" echo === output path is an existing file -echo not a directory> "%ROOT%\blocked" -"%EXE%" "%ROOT%\blocked">> "%LOG%" 2>&1 ->> "%LOG%" echo EXITCODE %errorlevel% -del "%ROOT%\blocked" - ->> "%LOG%" echo. ->> "%LOG%" echo === shader directory with no .cso files -mkdir "%ROOT%\no-shaders" -"%EXE%" "%ROOT%\shader-failure" --shaders "%ROOT%\no-shaders">> "%LOG%" 2>&1 ->> "%LOG%" echo EXITCODE %errorlevel% - ->> "%LOG%" echo. ->> "%LOG%" echo === PNG path occupied by a directory -mkdir "%ROOT%\png-blocked" -mkdir "%ROOT%\png-blocked\clear.png" -"%EXE%" "%ROOT%\png-blocked">> "%LOG%" 2>&1 ->> "%LOG%" echo EXITCODE %errorlevel% - -type "%LOG%" diff --git a/tools/conformance/native/scripts/negative-control.ps1 b/tools/conformance/native/scripts/negative-control.ps1 deleted file mode 100644 index 712efe2a1..000000000 --- a/tools/conformance/native/scripts/negative-control.ps1 +++ /dev/null @@ -1,65 +0,0 @@ -$ErrorActionPreference = 'Stop' -$source = Split-Path -Parent $PSScriptRoot -$scratch = Join-Path $source 'negative-control' -$cmake = (Get-Command cmake -ErrorAction SilentlyContinue) -if ($cmake) { $cmake = $cmake.Path } else { $cmake = 'C:\Program Files\CMake\bin\cmake.exe' } - -# This script exists to prove the scenes are not vacuous: it disables three pieces of -# pipeline state and requires the suite to notice exactly those three scenes. It asserts -# its own result, so a silent no-op edit cannot be mistaken for evidence. - -function Replace-ExactlyOnce { - param([string] $Text, [string] $Search, [string] $Replacement, [string] $What) - $count = ([regex]::Matches($Text, [regex]::Escape($Search))).Count - if ($count -ne 1) { - throw "expected exactly one occurrence of '$Search' while disabling $What, found $count. The source moved; update negative-control.ps1 before trusting this test." - } - return $Text.Replace($Search, $Replacement) -} - -Write-Output '=== building a throwaway copy with depth, blend and scissor state disabled ===' -if (Test-Path $scratch) { Remove-Item $scratch -Recurse -Force } -New-Item -ItemType Directory "$scratch\src" | Out-Null -Copy-Item "$source\CMakeLists.txt" $scratch -Copy-Item "$source\src\*" "$scratch\src" - -# 1. depth test off in the vertex-colour pipeline -$renderer = Get-Content "$scratch\src\renderer.cpp" -Raw -$renderer = Replace-ExactlyOnce $renderer 'description.DepthStencilState.DepthEnable = TRUE;' 'description.DepthStencilState.DepthEnable = FALSE;' 'the depth test' -# 2. blending off -$renderer = Replace-ExactlyOnce $renderer 'description.BlendState.RenderTarget[0].BlendEnable = TRUE;' 'description.BlendState.RenderTarget[0].BlendEnable = FALSE;' 'blending' -Set-Content -Path "$scratch\src\renderer.cpp" -Value $renderer -NoNewline - -# 3. scissor rect widened to the whole target -$plan = Get-Content "$scratch\src\scene_plan.cpp" -Raw -$plan = Replace-ExactlyOnce $plan 'plan.scissor = {conform::kScissorLeft, conform::kScissorTop, conform::kScissorRight,' 'plan.scissor = {0, 0, conform::kSceneWidth,' 'the scissor rectangle' -$plan = Replace-ExactlyOnce $plan 'conform::kScissorBottom};' 'conform::kSceneHeight};' 'the scissor rectangle bottom edge' -Set-Content -Path "$scratch\src\scene_plan.cpp" -Value $plan -NoNewline - -& $cmake -S $scratch -B "$scratch\build" -G 'Visual Studio 17 2022' -A x64 | Out-Null -& $cmake --build "$scratch\build" --config Release --parallel | Select-Object -Last 2 -if ($LASTEXITCODE -ne 0) { Write-Output "BUILD FAILED $LASTEXITCODE"; exit 1 } - -Write-Output '=== run: which scenes notice? ===' -$output = & "$scratch\build\Release\conform_native.exe" (Join-Path $source 'out/negative-control') 2>&1 -$exit = $LASTEXITCODE -$output | Select-String -Pattern '^FAIL|^readback checks|^RESULT' -Write-Output "EXITCODE $exit" - -# Assert, rather than print and hope. -$failedScenes = $output | - Select-String -Pattern '^FAIL (?:readback|png) scene=(\w+)' | - ForEach-Object { $_.Matches[0].Groups[1].Value } | - Sort-Object -Unique -$expected = @('blend', 'depth_order', 'scissor') -if (Compare-Object $failedScenes $expected) { - Write-Output "NEGATIVE CONTROL FAILED: scenes that noticed = $($failedScenes -join ', '); expected $($expected -join ', ')" - exit 1 -} -if ($exit -eq 0) { - Write-Output 'NEGATIVE CONTROL FAILED: the corrupted build still exited 0' - exit 1 -} -Write-Output "NEGATIVE CONTROL PASSED: exactly $($expected -join ', ') failed" -Remove-Item $scratch -Recurse -Force -exit 0 diff --git a/tools/conformance/native/scripts/run.ps1 b/tools/conformance/native/scripts/run.ps1 deleted file mode 100644 index d8d3c190e..000000000 --- a/tools/conformance/native/scripts/run.ps1 +++ /dev/null @@ -1,41 +0,0 @@ -param( - [string]$Output = '', - [string[]]$Extra = @() -) -# Renders every scene into $Output (default: /tools/conformance/native/out/run1). -# A folder already at $Output is emptied first, so no PNG from an earlier run is left behind, but only when it holds -# nothing except what a run writes (.png and manifest.json). A mistyped -Output (a drive, the repository, a -# home folder, a folder of anything else) is refused with exit 2 instead of deleted, and nothing is touched at all -# when the renderer has not been built. -$ErrorActionPreference = 'Continue' -$root = Split-Path -Parent $PSScriptRoot -if ([string]::IsNullOrEmpty($Output)) { $Output = Join-Path $root 'out/run1' } -$exe = Join-Path $root 'build/Release/conform_native.exe' -if (-not (Test-Path -LiteralPath $exe -PathType Leaf)) { - Write-Output "$exe does not exist; build first (scripts\build.ps1)" - Write-Output 'EXITCODE 1' - exit 1 -} - -function Refuse-Output([string]$Why) { - Write-Output "-Output $Output $Why; not deleting it. Pass an empty folder or a previous run's output folder." - Write-Output 'EXITCODE 2' - exit 2 -} - -if (Test-Path -LiteralPath $Output) { - $item = Get-Item -LiteralPath $Output -Force - if (-not $item.PSIsContainer) { Refuse-Output 'is a file' } - # A junction or symbolic link: a recursive Remove-Item on it can delete the contents of the folder it points to. - if ($item.Attributes -band [IO.FileAttributes]::ReparsePoint) { Refuse-Output 'is a link or junction' } - if ($null -eq $item.Parent) { Refuse-Output 'is a drive root' } - $foreign = @(Get-ChildItem -LiteralPath $item.FullName -Force | - Where-Object { $_.PSIsContainer -or -not ($_.Name -eq 'manifest.json' -or $_.Extension -eq '.png') }) - if ($foreign.Count -gt 0) { - $names = ($foreign | Select-Object -First 3 | ForEach-Object { $_.Name }) -join ', ' - Refuse-Output "holds files a run does not write ($names)" - } - Remove-Item -LiteralPath $item.FullName -Recurse -Force -} -& $exe $Output @Extra -Write-Output "EXITCODE $LASTEXITCODE" diff --git a/tools/conformance/native/scripts/verify.ps1 b/tools/conformance/native/scripts/verify.ps1 deleted file mode 100644 index 26a4af6f2..000000000 --- a/tools/conformance/native/scripts/verify.ps1 +++ /dev/null @@ -1,88 +0,0 @@ -# Re-checks every claim the README makes about the native renderer. -# Run: powershell -NoProfile -ExecutionPolicy Bypass -File verify.ps1 -# Exit code 0 means every claim held. - -$ErrorActionPreference = 'Continue' -$root_dir = Split-Path -Parent $PSScriptRoot -$exe = Join-Path $root_dir 'build/Release/conform_native.exe' -$root = Join-Path $root_dir 'out' -$script:broken = 0 - -function Check([bool]$condition, [string]$label) { - if ($condition) { - Write-Output "ok $label" - } else { - Write-Output "BROKEN $label" - $script:broken += 1 - } -} - -if (-not (Test-Path $exe)) { Write-Output "BROKEN $exe does not exist; build first"; exit 1 } -if (Test-Path $root) { Remove-Item $root -Recurse -Force } - -Write-Output '--- contract checks on the primary adapter ---' -& $exe "$root\a" | Out-Null -Check ($LASTEXITCODE -eq 0) 'run A exits 0 (all PixelChecks pass)' - -Write-Output '--- determinism: two runs, byte compare ---' -& $exe "$root\b" | Out-Null -Check ($LASTEXITCODE -eq 0) 'run B exits 0' -$names = Get-ChildItem "$root\a" | Select-Object -ExpandProperty Name | Sort-Object -Check ($names.Count -eq 7) "run A wrote 7 files (6 PNGs + manifest.json), found $($names.Count)" -foreach ($name in $names) { - $hashA = (Get-FileHash "$root\a\$name" -Algorithm SHA256).Hash - $hashB = (Get-FileHash "$root\b\$name" -Algorithm SHA256).Hash - Check ($hashA -eq $hashB) "identical bytes: $name $hashA" -} - -Write-Output '--- second adapter (index 0 = AMD Radeon iGPU on this machine) ---' -$amdText = (& $exe "$root\amd" --adapter 0 2>&1 | Out-String) -Check ($LASTEXITCODE -eq 0) 'render on adapter 0 exits 0' -Check ($amdText -match 'adapter: AMD Radeon') 'adapter 0 is reported as the AMD Radeon' -Check ($amdText -match 'readback checks: 18 passed, 0 failed') 'adapter 0 passes all 18 readback checks' -Check ($amdText -match 'png checks: 18 passed, 0 failed') 'adapter 0 passes all 18 PNG checks' - -Write-Output '--- failure paths ---' -Set-Content -Path "$root\blocked-by-file" -Value 'not a directory' -$fileText = (& $exe "$root\blocked-by-file" 2>&1 | Out-String) -Check ($LASTEXITCODE -eq 1) 'output path that is a file exits 1' -Check ($fileText -match 'create_directories') 'that failure names create_directories' -Check ($fileText -match 'blocked-by-file') 'that failure names the path' -Remove-Item "$root\blocked-by-file" -Force - -New-Item -ItemType Directory "$root\no-shaders" | Out-Null -$shaderText = (& $exe "$root\shader-failure" --shaders "$root\no-shaders" 2>&1 | Out-String) -Check ($LASTEXITCODE -eq 1) 'missing .cso files exit 1' -Check ($shaderText -match 'fullscreen_color.vs.cso') 'that failure names the missing file' -Check ($shaderText -match 'conform_shaders') 'that failure says which build target produces it' - -New-Item -ItemType Directory "$root\png-blocked" | Out-Null -New-Item -ItemType Directory "$root\png-blocked\clear.png" | Out-Null -$pngText = (& $exe "$root\png-blocked" 2>&1 | Out-String) -Check ($LASTEXITCODE -eq 1) 'unwritable PNG path exits 1' -Check ($pngText -match 'clear\.png') 'that failure names the PNG' -Check ($pngText -match 'RESULT: FAIL \(run did not complete\)') 'that run reports it did not complete' - -$noArgText = (& $exe 2>&1 | Out-String) -Check ($LASTEXITCODE -eq 2) 'no arguments exits 2' -Check ($noArgText -match 'usage: conform_native') 'no arguments prints usage' - -$badFlagText = (& $exe "$root\x" --nonsense 2>&1 | Out-String) -Check ($LASTEXITCODE -eq 2) 'unknown flag exits 2' - -Write-Output '--- manifest ---' -$manifest = Get-Content "$root\a\manifest.json" -Raw | ConvertFrom-Json -Check ($manifest.renderer -eq 'native') 'manifest renderer is native' -Check ($manifest.adapter -match 'RTX 5070 Ti') 'manifest records the chosen adapter' -Check ($manifest.scenes.Count -eq 6) 'manifest lists 6 scenes' -$checkCount = 0 -foreach ($scene in $manifest.scenes) { $checkCount += $scene.checks.Count } -Check ($checkCount -eq 18) 'manifest lists all 18 checks from scenes.h' - -Write-Output '' -if ($script:broken -eq 0) { - Write-Output 'VERIFY: PASS' - exit 0 -} -Write-Output "VERIFY: FAIL ($script:broken broken claim(s))" -exit 1 diff --git a/tools/conformance/native/src/diagnostics.cpp b/tools/conformance/native/src/diagnostics.cpp deleted file mode 100644 index 03283b818..000000000 --- a/tools/conformance/native/src/diagnostics.cpp +++ /dev/null @@ -1,60 +0,0 @@ -#include "diagnostics.h" - -#include -#include - -namespace { - -// One line shape for every failure so a log grep for "FAIL " finds all of them. -void PrintDiagnostic(const char* file, int line, const char* call, const std::string& detail, - const char* what_to_check) { - std::fprintf(stderr, "FAIL %s:%d %s -> %s. Check: %s\n", file, line, call, detail.c_str(), - what_to_check); - std::fflush(stderr); -} - -// Hex is how HRESULTs are looked up in the SDK headers and in Event Viewer. -std::string FormatHex32(unsigned long value, const char* prefix) { - char text[32]; - std::snprintf(text, sizeof text, "%s0x%08lX", prefix, value); - return std::string(text); -} - -} // namespace - -bool HrSucceeded(HRESULT result, const char* file, int line, const char* call, - const char* what_to_check) { - if (SUCCEEDED(result)) { - return true; - } - PrintDiagnostic(file, line, call, FormatHex32(static_cast(result), "HRESULT "), - what_to_check); - return false; -} - -bool Win32Succeeded(BOOL result, const char* file, int line, const char* call, - const char* what_to_check) { - if (result != FALSE) { - return true; - } - const unsigned long last_error = static_cast(GetLastError()); - char detail[64]; - std::snprintf(detail, sizeof detail, "Win32 error %lu (0x%08lX)", last_error, last_error); - PrintDiagnostic(file, line, call, detail, what_to_check); - return false; -} - -void ReportFailure(const char* file, int line, const char* call, const std::string& message, - const char* what_to_check) { - PrintDiagnostic(file, line, call, message, what_to_check); -} - -std::string TextFromWide(const std::wstring& wide) { - const int wide_count = static_cast(wide.size()); - const int byte_count = - WideCharToMultiByte(CP_UTF8, 0, wide.data(), wide_count, nullptr, 0, nullptr, nullptr); - std::string text(static_cast(byte_count), '\0'); - WideCharToMultiByte(CP_UTF8, 0, wide.data(), wide_count, text.data(), byte_count, nullptr, - nullptr); - return text; -} diff --git a/tools/conformance/native/src/diagnostics.h b/tools/conformance/native/src/diagnostics.h deleted file mode 100644 index edb78456d..000000000 --- a/tools/conformance/native/src/diagnostics.h +++ /dev/null @@ -1,30 +0,0 @@ -#pragma once - -#include - -#include - -// Failure reporting for this tool. Every fallible call goes through one of these so a -// failed run always names the file, the call, the numeric error and the next thing to -// check. Each function returns true only when the call succeeded, so call sites branch -// on a single boolean and never need a nested if. - -// Reports a failed HRESULT. Use for anything that returns HRESULT, including -// GetDeviceRemovedReason, where the value is the reason rather than a call failure. -bool HrSucceeded(HRESULT result, const char* file, int line, const char* call, - const char* what_to_check); - -// Reports a failed Win32 call using GetLastError. Use for CreateEventW and friends. -bool Win32Succeeded(BOOL result, const char* file, int line, const char* call, - const char* what_to_check); - -// Reports a failure that carries no error code (missing file, bad argument, a check the -// tool itself does not implement). message states what went wrong and may name a path. -void ReportFailure(const char* file, int line, const char* call, const std::string& message, - const char* what_to_check); - -// UTF-8 text of an argument or of path.native(), for messages. path.string() converts to -// the ANSI code page and throws for a character that page does not have, so printing a -// valid path could end the run. An unpaired surrogate, which a Windows file name may hold, -// becomes U+FFFD here. -std::string TextFromWide(const std::wstring& wide); diff --git a/tools/conformance/native/src/gpu.cpp b/tools/conformance/native/src/gpu.cpp deleted file mode 100644 index d607a340a..000000000 --- a/tools/conformance/native/src/gpu.cpp +++ /dev/null @@ -1,299 +0,0 @@ -#include "gpu.h" - -#include -#include - -#include "diagnostics.h" - -namespace { - -// One enumerated adapter. The index is kept so `--adapter N` matches the printed list -// even after software adapters are filtered out of automatic selection. -struct AdapterCandidate { - int index = -1; - bool software = false; - SIZE_T dedicated_video_memory = 0; - std::string description; - ComPtr adapter; -}; - -// Converts a driver-supplied UTF-16 name to UTF-8. Returns false rather than storing a -// truncated name, so a broken name shows up as a reported failure, not a blank field. -bool Utf8FromWide(const wchar_t* wide, std::string& text_out) { - const int byte_count = WideCharToMultiByte(CP_UTF8, 0, wide, -1, nullptr, 0, nullptr, nullptr); - if (byte_count <= 1) { - return false; - } - std::vector buffer(static_cast(byte_count)); - const int written = - WideCharToMultiByte(CP_UTF8, 0, wide, -1, buffer.data(), byte_count, nullptr, nullptr); - if (written != byte_count) { - return false; - } - text_out.assign(buffer.data()); - return true; -} - -// Enumerates every DXGI adapter. DXGI_ERROR_NOT_FOUND ends the list; any other failure -// on a later index would silently truncate the list, so it is reported. -bool EnumerateAdapters(IDXGIFactory4& factory, std::vector& candidates) { - for (int index = 0;; ++index) { - ComPtr adapter; - const HRESULT result = factory.EnumAdapters1(static_cast(index), adapter.GetAddressOf()); - if (result == DXGI_ERROR_NOT_FOUND) { - return true; - } - if (!HrSucceeded(result, __FILE__, __LINE__, "IDXGIFactory4::EnumAdapters1", - "a broken display driver; try another adapter with --adapter")) { - return false; - } - - DXGI_ADAPTER_DESC1 description{}; - if (!HrSucceeded(adapter->GetDesc1(&description), __FILE__, __LINE__, - "IDXGIAdapter1::GetDesc1", "a display driver that does not expose a " - "description; try another adapter with --adapter")) { - return false; - } - - AdapterCandidate candidate; - candidate.index = index; - candidate.software = (description.Flags & DXGI_ADAPTER_FLAG_SOFTWARE) != 0; - candidate.dedicated_video_memory = description.DedicatedVideoMemory; - if (!Utf8FromWide(description.Description, candidate.description)) { - ReportFailure(__FILE__, __LINE__, "WideCharToMultiByte", - "the adapter description could not be converted to UTF-8", - "the driver reports an empty adapter name"); - return false; - } - candidate.adapter = adapter; - candidates.push_back(candidate); - } -} - -// Prints the candidate list so a surprising choice can be diagnosed from the log alone. -void PrintAdapterCandidates(const std::vector& candidates) { - for (const AdapterCandidate& candidate : candidates) { - std::printf("adapter[%d] %s (%llu MB dedicated)%s\n", candidate.index, - candidate.description.c_str(), - static_cast(candidate.dedicated_video_memory / - (1024ull * 1024ull)), - candidate.software ? " [software]" : ""); - } -} - -// Chooses the adapter: an explicit index wins verbatim, otherwise the non-software -// adapter with the most dedicated memory (the discrete GPU on a hybrid machine). -bool SelectAdapter(const std::vector& candidates, int requested_index, - const AdapterCandidate*& selected_out) { - if (candidates.empty()) { - ReportFailure(__FILE__, __LINE__, "SelectAdapter", "DXGI enumerated no adapters", - "the GPU driver is installed and the machine has a display adapter"); - return false; - } - if (requested_index >= 0) { - for (const AdapterCandidate& candidate : candidates) { - if (candidate.index == requested_index) { - selected_out = &candidate; - return true; - } - } - ReportFailure(__FILE__, __LINE__, "SelectAdapter", "--adapter names an adapter that does " - "not exist", "pick an index from the adapter list printed above"); - return false; - } - - const AdapterCandidate* best = nullptr; - for (const AdapterCandidate& candidate : candidates) { - if (candidate.software) { - continue; - } - if (best == nullptr || candidate.dedicated_video_memory > best->dedicated_video_memory) { - best = &candidate; - } - } - if (best == nullptr) { - ReportFailure(__FILE__, __LINE__, "SelectAdapter", - "every enumerated adapter is software-only", - "install a GPU driver, or pass --adapter with the WARP index if WARP is " - "acceptable for a reference image"); - return false; - } - selected_out = best; - return true; -} - -// Turns on the D3D12 debug layer. Reports success only when the layer was actually -// enabled: the caller must not claim validation ran when this returns false. -bool EnableDebugLayer() { - ComPtr debug_controller; - const HRESULT result = D3D12GetDebugInterface(IID_PPV_ARGS(debug_controller.GetAddressOf())); - if (FAILED(result)) { - std::fprintf(stderr, - "note: --debug-layer requested but the D3D12 debug layer is not installed " - "(HRESULT 0x%08lX); continuing without validation\n", - static_cast(result)); - return false; - } - debug_controller->EnableDebugLayer(); - // GPU-based validation is left at its default (off): it changes nothing about the - // output but makes a 256x256 reference render take minutes on some drivers. Nothing - // else is changed here; the layer is used exactly as Microsoft configured it. - return true; -} - -} // namespace - -GpuContext::~GpuContext() { DestroyGpuContext(*this); } - -bool CreateGpuContext(GpuContext& gpu, int requested_adapter_index, bool enable_debug_layer) { - const bool debug_layer_active = enable_debug_layer ? EnableDebugLayer() : false; - // Recorded on the context so the caller can tell "validation ran and found nothing" - // from "validation was asked for and never ran". - gpu.validation_active = debug_layer_active; - const UINT factory_flags = debug_layer_active ? DXGI_CREATE_FACTORY_DEBUG : 0; - - if (!HrSucceeded(CreateDXGIFactory2(factory_flags, IID_PPV_ARGS(gpu.dxgi_factory.GetAddressOf())), - __FILE__, __LINE__, "CreateDXGIFactory2", - "dxgi.dll is present and, with --debug-layer, the DXGI debug layer is " - "installed")) { - return false; - } - - std::vector candidates; - if (!EnumerateAdapters(*gpu.dxgi_factory.Get(), candidates)) { - return false; - } - PrintAdapterCandidates(candidates); - - const AdapterCandidate* selected = nullptr; - if (!SelectAdapter(candidates, requested_adapter_index, selected)) { - return false; - } - gpu.adapter_description = selected->description; - gpu.adapter_is_software = selected->software; - - // Feature level 11_0 is the floor the scene contract needs; the shaders are SM 6.6, - // which the PSO creation below validates against the actual device. - if (!HrSucceeded(D3D12CreateDevice(selected->adapter.Get(), D3D_FEATURE_LEVEL_11_0, - IID_PPV_ARGS(gpu.device.GetAddressOf())), - __FILE__, __LINE__, "D3D12CreateDevice", - "the adapter supports D3D12; an adapter listed as [software] or an old " - "driver is the usual cause")) { - return false; - } - - D3D12_COMMAND_QUEUE_DESC queue_description{}; - queue_description.Type = D3D12_COMMAND_LIST_TYPE_DIRECT; - queue_description.Priority = D3D12_COMMAND_QUEUE_PRIORITY_NORMAL; - queue_description.Flags = D3D12_COMMAND_QUEUE_FLAG_NONE; - if (!HrSucceeded(gpu.device->CreateCommandQueue(&queue_description, IID_PPV_ARGS( - gpu.command_queue.GetAddressOf())), - __FILE__, __LINE__, "ID3D12Device::CreateCommandQueue", - "a direct queue is available; a device lost at creation is the usual cause")) { - return false; - } - - if (!HrSucceeded(gpu.device->CreateFence(0, D3D12_FENCE_FLAG_NONE, - IID_PPV_ARGS(gpu.fence.GetAddressOf())), - __FILE__, __LINE__, "ID3D12Device::CreateFence", - "the device is still present after queue creation")) { - return false; - } - - gpu.fence_event = CreateEventW(nullptr, FALSE, FALSE, nullptr); - if (!Win32Succeeded(gpu.fence_event != nullptr, __FILE__, __LINE__, "CreateEventW", - "the process can create kernel events; a restricted job object is the " - "usual cause")) { - return false; - } - return true; -} - -void DestroyGpuContext(GpuContext& gpu) { - if (gpu.fence_event != nullptr) { - CloseHandle(gpu.fence_event); - gpu.fence_event = nullptr; - } - gpu.fence.Reset(); - gpu.command_queue.Reset(); - gpu.device.Reset(); - gpu.dxgi_factory.Reset(); -} - -bool WaitForFenceValue(GpuContext& gpu, uint64_t fence_value) { - if (gpu.fence->GetCompletedValue() >= fence_value) { - return true; - } - if (!HrSucceeded(gpu.fence->SetEventOnCompletion(fence_value, gpu.fence_event), __FILE__, - __LINE__, "ID3D12Fence::SetEventOnCompletion", - "the fence event handle is valid and the queue has not been destroyed")) { - return false; - } - const DWORD wait_result = WaitForSingleObject(gpu.fence_event, 60000); - if (wait_result != WAIT_OBJECT_0) { - ReportFailure(__FILE__, __LINE__, "WaitForSingleObject", - wait_result == WAIT_TIMEOUT ? "the GPU did not finish within 60 s" - : "waiting for the fence failed", - "Event Viewer for a display driver reset (TDR) on the adapter named above; " - "a hung draw or an unbound resource is the usual cause"); - return false; - } - return true; -} - -bool SignalAndWaitForGpu(GpuContext& gpu) { - const uint64_t fence_value = gpu.next_fence_value; - gpu.next_fence_value += 1; - if (!HrSucceeded(gpu.command_queue->Signal(gpu.fence.Get(), fence_value), __FILE__, __LINE__, - "ID3D12CommandQueue::Signal", "the queue is still open and the fence valid")) { - return false; - } - return WaitForFenceValue(gpu, fence_value); -} - -bool DeviceStillPresent(GpuContext& gpu) { - const HRESULT reason = gpu.device->GetDeviceRemovedReason(); - if (SUCCEEDED(reason)) { - return true; - } - return HrSucceeded(reason, __FILE__, __LINE__, "ID3D12Device::GetDeviceRemovedReason", - "Event Viewer for a TDR on the adapter named above; the HRESULT names " - "the removal reason (DEVICE_HUNG, DEVICE_RESET, OUT_OF_MEMORY)"); -} - -int ReportValidationMessages(ID3D12Device& device) { - ComPtr info_queue; - if (FAILED(device.QueryInterface(IID_PPV_ARGS(info_queue.GetAddressOf())))) { - return 0; - } - const UINT64 message_count = info_queue->GetNumStoredMessages(); - int error_count = 0; - int unreadable_count = 0; - for (UINT64 index = 0; index < message_count; ++index) { - SIZE_T message_size = 0; - if (FAILED(info_queue->GetMessage(index, nullptr, &message_size)) || message_size == 0) { - ++unreadable_count; - continue; - } - std::vector storage(message_size); - D3D12_MESSAGE* message = reinterpret_cast(storage.data()); - if (FAILED(info_queue->GetMessage(index, message, &message_size))) { - ++unreadable_count; - continue; - } - // Severity counts down as severity rises (CORRUPTION 0 ... MESSAGE 4). - if (message->Severity <= D3D12_MESSAGE_SEVERITY_WARNING) { - std::fprintf(stderr, "validation: %.*s\n", static_cast(message->DescriptionByteLength), - message->pDescription); - } - if (message->Severity <= D3D12_MESSAGE_SEVERITY_ERROR) { - ++error_count; - } - } - if (unreadable_count > 0) { - std::fprintf(stderr, "validation: %d message(s) could not be retrieved from the info queue\n", - unreadable_count); - } - std::fflush(stderr); - return error_count; -} diff --git a/tools/conformance/native/src/gpu.h b/tools/conformance/native/src/gpu.h deleted file mode 100644 index 9caf17828..000000000 --- a/tools/conformance/native/src/gpu.h +++ /dev/null @@ -1,60 +0,0 @@ -#pragma once - -#include -#include -#include - -#include -#include - -using Microsoft::WRL::ComPtr; - -// Everything the renderer needs from the GPU: a device, a direct queue, and the fence -// used to know when readback is safe. Adapter selection happens here and the chosen -// adapter's description is kept for the manifest. -struct GpuContext { - ComPtr dxgi_factory; - ComPtr device; - ComPtr command_queue; - ComPtr fence; - HANDLE fence_event = nullptr; - uint64_t next_fence_value = 1; - std::string adapter_description; // UTF-8 copy of DXGI_ADAPTER_DESC1::Description - bool adapter_is_software = false; - // True only when --debug-layer was requested AND the layer actually came up. A run - // that asked for validation but did not get it must never report "0 errors". - bool validation_active = false; - - // Releases the COM objects in the right order when the context goes out of scope, so - // a caller cannot forget DestroyGpuContext on an early return. - ~GpuContext(); -}; - -// Creates the DXGI factory, picks an adapter, creates the device, queue and fence. -// Does not create any command lists or resources; that is the renderer's job. -// adapter_index < 0 selects the non-software adapter with the most dedicated memory. -bool CreateGpuContext(GpuContext& gpu, int requested_adapter_index, bool enable_debug_layer); - -// Releases the COM objects and closes the fence event. Safe on a partially built -// context, which is why failure paths call it before returning. -void DestroyGpuContext(GpuContext& gpu); - -// Blocks until the GPU has finished the given fence value, or 60 s pass. A timeout is -// reported as a failure rather than waited out forever. -bool WaitForFenceValue(GpuContext& gpu, uint64_t fence_value); - -// Signals the queue's fence and waits for it. Call after ExecuteCommandLists whenever -// the next step touches the result on the CPU. -bool SignalAndWaitForGpu(GpuContext& gpu); - -// True when the device has not been removed. A removed device silently produces zeroed -// or stale readback, so this is checked after every wait. -bool DeviceStillPresent(GpuContext& gpu); - -// Prints validation-layer messages of WARNING severity or worse and returns the number -// of ERROR or CORRUPTION messages. Zero when the debug layer was not enabled. -// -// D3D12_MESSAGE_SEVERITY counts DOWN as severity goes up: CORRUPTION is 0, ERROR 1, -// WARNING 2, INFO 3, MESSAGE 4. So "severity <= WARNING" means "warning or worse", and -// "severity <= ERROR" means "error or corruption". -int ReportValidationMessages(ID3D12Device& device); diff --git a/tools/conformance/native/src/main.cpp b/tools/conformance/native/src/main.cpp deleted file mode 100644 index 59d98ac8b..000000000 --- a/tools/conformance/native/src/main.cpp +++ /dev/null @@ -1,320 +0,0 @@ -#include - -#include -#include -#include -#include - -#include "diagnostics.h" -#include "gpu.h" -#include "manifest.h" -#include "png_io.h" -#include "renderer.h" -#include "scene_plan.h" -#include "scenes.h" -#include "verify.h" - -namespace { - -// Balances CoInitializeEx for the lifetime of main. One owner, no copy: a second -// initialisation would change the apartment model under WIC. -struct ComScope { - HRESULT result = E_FAIL; - - ComScope() { result = CoInitializeEx(nullptr, COINIT_MULTITHREADED); } - ~ComScope() { - if (SUCCEEDED(result)) { - CoUninitialize(); - } - } - ComScope(const ComScope&) = delete; - ComScope& operator=(const ComScope&) = delete; -}; - -struct CommandLineOptions { - std::filesystem::path output_directory; - std::filesystem::path shader_directory; // empty: \shaders - int adapter_index = -1; // -1: the non-software adapter with most memory - bool enable_debug_layer = false; - bool show_help = false; -}; - -// Totals for the run. Readback and PNG are counted separately so a failure says which -// path broke: rendering, or the file the diff tool will read. -struct RunTally { - int readback_passed = 0; - int readback_failed = 0; - int png_passed = 0; - int png_failed = 0; -}; - -void PrintUsage() { - std::printf( - "usage: conform_native [options]\n" - " --shaders where the .cso files live (default: \\shaders)\n" - " --adapter adapter from the printed list (default: most dedicated\n" - " memory, non-software)\n" - " --debug-layer enable D3D12 validation and fail on validation errors\n" - " --help print this text\n"); -} - -// Parses argv into options. Returns false on any malformed argument; the caller prints -// usage, so this function prints only the reason. -bool ParseCommandLine(int argument_count, wchar_t** arguments, CommandLineOptions& options) { - for (int index = 1; index < argument_count; ++index) { - const std::wstring argument = arguments[index]; - if (argument == L"--help" || argument == L"-h") { - options.show_help = true; - continue; - } - if (argument == L"--debug-layer") { - options.enable_debug_layer = true; - continue; - } - if (argument == L"--adapter" || argument == L"--shaders") { - if (index + 1 >= argument_count) { - ReportFailure(__FILE__, __LINE__, "ParseCommandLine", - TextFromWide(argument) + " needs a value", - "see --help for the argument list"); - return false; - } - const std::wstring value = arguments[++index]; - if (argument == L"--shaders") { - options.shader_directory = std::filesystem::path(value); - continue; - } - wchar_t* end_of_number = nullptr; - const long parsed = std::wcstol(value.c_str(), &end_of_number, 10); - if (end_of_number == value.c_str() || *end_of_number != L'\0' || parsed < 0) { - ReportFailure(__FILE__, __LINE__, "ParseCommandLine", - "--adapter expects a non-negative index, got \"" + - TextFromWide(value) + "\"", - "the adapter list printed at startup numbers the adapters"); - return false; - } - options.adapter_index = static_cast(parsed); - continue; - } - if (!argument.empty() && argument[0] == L'-') { - ReportFailure(__FILE__, __LINE__, "ParseCommandLine", - "unknown option " + TextFromWide(argument), - "see --help for the argument list"); - return false; - } - if (!options.output_directory.empty()) { - ReportFailure(__FILE__, __LINE__, "ParseCommandLine", - "more than one output directory: " + TextFromWide(argument), - "pass exactly one output directory"); - return false; - } - options.output_directory = std::filesystem::path(argument); - } - - if (options.show_help) { - return true; - } - if (options.output_directory.empty()) { - ReportFailure(__FILE__, __LINE__, "ParseCommandLine", "no output directory given", - "pass the directory the PNGs and manifest.json should be written to"); - return false; - } - return true; -} - -// The directory holding the running executable. Shaders are copied next to the exe at -// build time, so this keeps the tool runnable from any working directory. -bool ExecutableDirectory(std::filesystem::path& directory_out) { - std::wstring buffer(32768, L'\0'); - const DWORD length = - GetModuleFileNameW(nullptr, buffer.data(), static_cast(buffer.size())); - if (length == 0 || length >= buffer.size()) { - ReportFailure(__FILE__, __LINE__, "GetModuleFileNameW", - "could not read the executable path", - "the process image is still on disk and the path is shorter than 32768 " - "characters"); - return false; - } - buffer.resize(length); - directory_out = std::filesystem::path(buffer).parent_path(); - return true; -} - -// Trims the trailing period Windows appends to system messages so the "Check:" clause -// that follows does not produce "...exists.. Check:". -std::string TrimTrailingPeriod(std::string text) { - while (!text.empty() && text.back() == '.') { - text.pop_back(); - } - return text; -} - -// Creates the output directory if needed. Reports the filesystem's own message, which -// distinguishes "it is a file" from "access denied" from "the drive is gone". -bool EnsureOutputDirectory(const std::filesystem::path& directory) { - std::error_code error; - std::filesystem::create_directories(directory, error); - if (error) { - ReportFailure(__FILE__, __LINE__, "std::filesystem::create_directories", - TrimTrailingPeriod("could not create " + TextFromWide(directory.native()) + - ": " + error.message()), - "the path is a directory the process can write to, not an existing file and " - "not a read-only volume"); - return false; - } - return true; -} - -// Renders, verifies and writes one scene. Returns false only when the pipeline itself -// broke; a wrong pixel is recorded in the tally and the run keeps going so one log -// shows every failing scene. -bool RunOneScene(GpuContext& gpu, Renderer& renderer, - const std::filesystem::path& output_directory, int scene_index, - const conform::Scene& scene, RunTally& tally) { - const DrawPlan plan = MakeDrawPlan(scene, scene_index); - PixelSurface rendered; - if (!renderer.RenderScene(gpu, plan, rendered)) { - ReportFailure(__FILE__, __LINE__, "Renderer::RenderScene", - std::string("scene ") + scene.name + " did not render", - "the failure printed above this line names the call that broke"); - return false; - } - if (rendered.width != conform::kSceneWidth || rendered.height != conform::kSceneHeight) { - ReportFailure(__FILE__, __LINE__, "Renderer::RenderScene", - std::string("scene ") + scene.name + " produced a " + - std::to_string(rendered.width) + "x" + std::to_string(rendered.height) + - " image", - "the readback footprint matches the contract's 256x256 target"); - return false; - } - - std::printf("\nscene %s: %d checks -- %s\n", scene.name, scene.checkCount, scene.proves); - const CheckTally readback_tally = VerifyChecks(scene, rendered, "readback"); - tally.readback_passed += readback_tally.passed; - tally.readback_failed += readback_tally.failed; - - const std::filesystem::path png_path = - output_directory / (std::string(scene.name) + ".png"); - if (!WritePngFile(png_path, rendered)) { - return false; - } - - // Decode what landed on disk. A WIC channel swap or a truncated file passes the - // readback checks and fails here, which is the point of the second comparison. - PixelSurface decoded; - if (!ReadPngFile(png_path, decoded)) { - return false; - } - if (decoded.width != rendered.width || decoded.height != rendered.height) { - ReportFailure(__FILE__, __LINE__, "ReadPngFile", - TextFromWide(png_path.native()) + " decoded to " + - std::to_string(decoded.width) + "x" + std::to_string(decoded.height), - "the encoder wrote a full 256x256 image"); - return false; - } - const CheckTally png_tally = VerifyChecks(scene, decoded, "png"); - tally.png_passed += png_tally.passed; - tally.png_failed += png_tally.failed; - return true; -} - -// Every scene in the contract, in declaration order, then the manifest. Scene order is -// fixed so two runs do the same GPU work in the same order. -bool RunAllScenes(GpuContext& gpu, Renderer& renderer, - const std::filesystem::path& output_directory, RunTally& tally) { - for (int index = 0; index < conform::kSceneCount; ++index) { - if (!RunOneScene(gpu, renderer, output_directory, index, conform::kScenes[index], tally)) { - return false; - } - } - // After the images: a manifest must never describe PNGs that do not exist. - return WriteManifest(output_directory / "manifest.json", gpu.adapter_description, - conform::kScenes, conform::kSceneCount); -} - -} // namespace - -// wmain, because main() receives the command line converted to the ANSI code page, where a -// folder name outside that page has already become question marks. -int wmain(int argument_count, wchar_t** arguments) { - // stdout unbuffered so PASS/FAIL lines stay in order with FAIL diagnostics, which - // stderr prints immediately. A reordered transcript invites a wrong conclusion. - std::setvbuf(stdout, nullptr, _IONBF, 0); - - CommandLineOptions options; - if (!ParseCommandLine(argument_count, arguments, options)) { - PrintUsage(); - return 2; - } - if (options.show_help) { - PrintUsage(); - return 0; - } - - std::printf("conform native renderer (D3D12, 256x256 R8G8B8A8_UNORM, offscreen)\n"); - ComScope com; - if (FAILED(com.result)) { - HrSucceeded(com.result, __FILE__, __LINE__, "CoInitializeEx", - "COM can be initialised on this thread; RPC_E_CHANGED_MODE means another " - "part of the process already picked a different apartment"); - return 1; - } - - std::filesystem::path shader_directory = options.shader_directory; - if (shader_directory.empty()) { - std::filesystem::path executable_directory; - if (!ExecutableDirectory(executable_directory)) { - return 1; - } - shader_directory = executable_directory / "shaders"; - } - if (!EnsureOutputDirectory(options.output_directory)) { - return 1; - } - std::printf("output: %s\n", TextFromWide(options.output_directory.native()).c_str()); - std::printf("shaders: %s\n", TextFromWide(shader_directory.native()).c_str()); - - GpuContext gpu; - if (!CreateGpuContext(gpu, options.adapter_index, options.enable_debug_layer)) { - return 1; - } - std::printf("adapter: %s%s\n\n", gpu.adapter_description.c_str(), - gpu.adapter_is_software ? " (software)" : ""); - - // A run that asked for validation and did not get it must stop here. Reporting - // "0 validation errors" after the layer failed to load is an invented result. - if (options.enable_debug_layer && !gpu.validation_active) { - std::fprintf(stderr, - "validation: NOT RUN - --debug-layer was requested but the D3D12 debug " - "layer is not installed on this machine. Install the Graphics Tools " - "optional feature, or drop --debug-layer to run unvalidated.\n"); - return 1; - } - - Renderer renderer; - if (!renderer.Initialize(gpu, shader_directory)) { - return 1; - } - - RunTally tally; - const bool run_completed = RunAllScenes(gpu, renderer, options.output_directory, tally); - - bool validation_errors_present = false; - if (options.enable_debug_layer) { - const int validation_error_count = ReportValidationMessages(*gpu.device.Get()); - validation_errors_present = validation_error_count > 0; - std::printf("\nvalidation errors: %d\n", validation_error_count); - } - - std::printf("\nreadback checks: %d passed, %d failed\n", tally.readback_passed, - tally.readback_failed); - std::printf("png checks: %d passed, %d failed\n", tally.png_passed, tally.png_failed); - - if (!run_completed) { - std::printf("RESULT: FAIL (run did not complete)\n"); - return 1; - } - const bool all_checks_passed = - tally.readback_failed == 0 && tally.png_failed == 0 && !validation_errors_present; - std::printf("RESULT: %s\n", all_checks_passed ? "PASS" : "FAIL"); - return all_checks_passed ? 0 : 1; -} diff --git a/tools/conformance/native/src/manifest.cpp b/tools/conformance/native/src/manifest.cpp deleted file mode 100644 index afd789ab5..000000000 --- a/tools/conformance/native/src/manifest.cpp +++ /dev/null @@ -1,98 +0,0 @@ -#include "manifest.h" - -#include -#include -#include - -#include "diagnostics.h" - -namespace { - -// Escapes the bytes JSON requires escaped. UTF-8 passes through unchanged, which JSON -// allows and keeps the adapter name readable. -void WriteJsonString(std::ostream& output, const char* text) { - output << '"'; - for (const char* cursor = text; *cursor != '\0'; ++cursor) { - const unsigned char byte = static_cast(*cursor); - switch (byte) { - case '"': - output << "\\\""; - break; - case '\\': - output << "\\\\"; - break; - case '\n': - output << "\\n"; - break; - case '\r': - output << "\\r"; - break; - case '\t': - output << "\\t"; - break; - default: - if (byte < 0x20) { - char escape[8]; - std::snprintf(escape, sizeof escape, "\\u%04X", byte); - output << escape; - } else { - output << static_cast(byte); - } - break; - } - } - output << '"'; -} - -void WriteCheck(std::ostream& output, const conform::PixelCheck& check) { - output << "{\"x\": " << check.x << ", \"y\": " << check.y - << ", \"r\": " << static_cast(check.r) << ", \"g\": " << static_cast(check.g) - << ", \"b\": " << static_cast(check.b) << ", \"a\": " << static_cast(check.a) - << ", \"why\": "; - WriteJsonString(output, check.why); - output << '}'; -} - -void WriteScene(std::ostream& output, const conform::Scene& scene, bool is_last_scene) { - const std::string png_name = std::string(scene.name) + ".png"; - output << " {\n \"name\": "; - WriteJsonString(output, scene.name); - output << ",\n \"png\": "; - WriteJsonString(output, png_name.c_str()); - output << ",\n \"checks\": [\n"; - for (int index = 0; index < scene.checkCount; ++index) { - output << " "; - WriteCheck(output, scene.checks[index]); - output << (index + 1 < scene.checkCount ? ",\n" : "\n"); - } - output << " ]\n }" << (is_last_scene ? "\n" : ",\n"); -} - -} // namespace - -bool WriteManifest(const std::filesystem::path& path, const std::string& adapter_description, - const conform::Scene* scenes, int scene_count) { - std::ofstream output(path, std::ios::binary | std::ios::trunc); - if (!output.is_open()) { - ReportFailure(__FILE__, __LINE__, "std::ofstream::open", - "could not create " + TextFromWide(path.native()), - "the output directory is writable and not on a read-only volume"); - return false; - } - - output << "{\n \"renderer\": \"native\",\n \"adapter\": "; - WriteJsonString(output, adapter_description.c_str()); - output << ",\n \"scenes\": [\n"; - for (int index = 0; index < scene_count; ++index) { - WriteScene(output, scenes[index], index + 1 == scene_count); - } - output << " ]\n}\n"; - output.close(); - if (output.fail()) { - ReportFailure(__FILE__, __LINE__, "std::ofstream::close", - "could not write " + TextFromWide(path.native()), - "the disk has free space; a full volume fails on close, not on open"); - return false; - } - return true; -} diff --git a/tools/conformance/native/src/manifest.h b/tools/conformance/native/src/manifest.h deleted file mode 100644 index 28f1e42bf..000000000 --- a/tools/conformance/native/src/manifest.h +++ /dev/null @@ -1,12 +0,0 @@ -#pragma once - -#include -#include - -#include "scenes.h" - -// Writes manifest.json in the schema the diff tool consumes. Every check comes from -// scenes.h so the tool never parses C++. Holds no timestamps or run counts: two runs -// against the same adapter must produce identical bytes. -bool WriteManifest(const std::filesystem::path& path, const std::string& adapter_description, - const conform::Scene* scenes, int scene_count); diff --git a/tools/conformance/native/src/pixel_surface.h b/tools/conformance/native/src/pixel_surface.h deleted file mode 100644 index 87b40afbd..000000000 --- a/tools/conformance/native/src/pixel_surface.h +++ /dev/null @@ -1,20 +0,0 @@ -#pragma once - -#include -#include - -// Pixels in the form both the readback path and the PNG decode path produce: four -// bytes per pixel in R,G,B,A order, top-left origin, tightly packed. Keeping one shape -// for both means a single comparison function covers rendering and file output. -struct PixelSurface { - int width = 0; - int height = 0; - std::vector rgba; - - // Points at the RGBA bytes of one pixel. The caller owns the bounds check; sizing - // is validated once when the surface is filled. - const uint8_t* At(int x, int y) const { - return rgba.data() + (static_cast(y) * static_cast(width) + - static_cast(x)) * 4; - } -}; diff --git a/tools/conformance/native/src/png_io.cpp b/tools/conformance/native/src/png_io.cpp deleted file mode 100644 index c5942dfb1..000000000 --- a/tools/conformance/native/src/png_io.cpp +++ /dev/null @@ -1,178 +0,0 @@ -#include "png_io.h" - -#include -#include - -#include -#include - -#include "diagnostics.h" - -using Microsoft::WRL::ComPtr; - -namespace { - -// One WIC factory per call. It is a few thousand bytes of COM state, and keeping it -// local means no object outlives the function that needed it. -bool CreateWicFactory(ComPtr& factory_out) { - return HrSucceeded( - CoCreateInstance(CLSID_WICImagingFactory, nullptr, CLSCTX_INPROC_SERVER, - IID_PPV_ARGS(factory_out.GetAddressOf())), - __FILE__, __LINE__, "CoCreateInstance(CLSID_WICImagingFactory)", - "the Windows Imaging Component is registered; a stripped Windows image without " - "the WIC feature is the usual cause"); -} - -// WIC's PNG encoder takes 32bppBGRA. Swapping here, once, keeps the channel order -// correct on disk without a format converter. -std::vector ConvertRgbaToBgra(const PixelSurface& surface) { - std::vector bgra(surface.rgba.size()); - for (size_t offset = 0; offset + 3 < surface.rgba.size(); offset += 4) { - bgra[offset + 0] = surface.rgba[offset + 2]; - bgra[offset + 1] = surface.rgba[offset + 1]; - bgra[offset + 2] = surface.rgba[offset + 0]; - bgra[offset + 3] = surface.rgba[offset + 3]; - } - return bgra; -} - -} // namespace - -bool WritePngFile(const std::filesystem::path& path, const PixelSurface& surface) { - ComPtr factory; - if (!CreateWicFactory(factory)) { - return false; - } - if (surface.width <= 0 || surface.height <= 0 || - surface.rgba.size() != static_cast(surface.width) * surface.height * 4) { - ReportFailure(__FILE__, __LINE__, "WritePngFile", - "the pixel surface is empty or its size does not match its dimensions", - "the readback path produced a full 256x256 image before this ran"); - return false; - } - - ComPtr stream; - if (!HrSucceeded(factory->CreateStream(stream.GetAddressOf()), __FILE__, __LINE__, - "IWICImagingFactory::CreateStream", "WIC is initialised on this thread")) { - return false; - } - const std::string write_hint = - "the output directory is writable and nothing else holds " + - TextFromWide(path.native()) + " open"; - if (!HrSucceeded(stream->InitializeFromFilename(path.c_str(), GENERIC_WRITE), __FILE__, __LINE__, - "IWICStream::InitializeFromFilename", write_hint.c_str())) { - return false; - } - - ComPtr encoder; - if (!HrSucceeded(factory->CreateEncoder(GUID_ContainerFormatPng, nullptr, - encoder.GetAddressOf()), - __FILE__, __LINE__, "IWICImagingFactory::CreateEncoder(PNG)", - "the PNG codec is installed with Windows")) { - return false; - } - if (!HrSucceeded(encoder->Initialize(stream.Get(), WICBitmapEncoderNoCache), __FILE__, __LINE__, - "IWICBitmapEncoder::Initialize", "the output stream is writable")) { - return false; - } - - ComPtr frame; - ComPtr frame_properties; - if (!HrSucceeded(encoder->CreateNewFrame(frame.GetAddressOf(), frame_properties.GetAddressOf()), - __FILE__, __LINE__, "IWICBitmapEncoder::CreateNewFrame", - "the encoder was initialised")) { - return false; - } - if (!HrSucceeded(frame->Initialize(frame_properties.Get()), __FILE__, __LINE__, - "IWICBitmapFrameEncode::Initialize", "the frame property bag is valid")) { - return false; - } - if (!HrSucceeded(frame->SetSize(static_cast(surface.width), - static_cast(surface.height)), - __FILE__, __LINE__, "IWICBitmapFrameEncode::SetSize", - "the dimensions are non-zero and fit in UINT")) { - return false; - } - - WICPixelFormatGUID pixel_format = GUID_WICPixelFormat32bppBGRA; - if (!HrSucceeded(frame->SetPixelFormat(&pixel_format), __FILE__, __LINE__, - "IWICBitmapFrameEncode::SetPixelFormat", "the PNG codec accepts 32bppBGRA")) { - return false; - } - if (!IsEqualGUID(pixel_format, GUID_WICPixelFormat32bppBGRA)) { - ReportFailure(__FILE__, __LINE__, "IWICBitmapFrameEncode::SetPixelFormat", - "the PNG codec silently changed the requested pixel format", - "a channel order assumption in this tool no longer holds; the written " - "file would not be comparable"); - return false; - } - - std::vector bgra = ConvertRgbaToBgra(surface); - const UINT stride = static_cast(surface.width) * 4; - if (!HrSucceeded(frame->WritePixels(static_cast(surface.height), stride, - static_cast(bgra.size()), bgra.data()), - __FILE__, __LINE__, "IWICBitmapFrameEncode::WritePixels", - "the disk has space and the surface buffer is as large as its dimensions")) { - return false; - } - if (!HrSucceeded(frame->Commit(), __FILE__, __LINE__, "IWICBitmapFrameEncode::Commit", - "the frame was fully written before commit")) { - return false; - } - // Commit is where the PNG chunks are flushed; the stream closes when the local COM - // pointers are released as this function returns. - return HrSucceeded(encoder->Commit(), __FILE__, __LINE__, "IWICBitmapEncoder::Commit", - "the stream accepted every byte; a full disk shows up here"); -} - -bool ReadPngFile(const std::filesystem::path& path, PixelSurface& surface_out) { - ComPtr factory; - if (!CreateWicFactory(factory)) { - return false; - } - - ComPtr decoder; - const std::string read_hint = - TextFromWide(path.native()) + " exists and is not locked by another process"; - if (!HrSucceeded(factory->CreateDecoderFromFilename(path.c_str(), nullptr, GENERIC_READ, - WICDecodeMetadataCacheOnDemand, - decoder.GetAddressOf()), - __FILE__, __LINE__, "IWICImagingFactory::CreateDecoderFromFilename", - read_hint.c_str())) { - return false; - } - - ComPtr frame; - if (!HrSucceeded(decoder->GetFrame(0, frame.GetAddressOf()), __FILE__, __LINE__, - "IWICBitmapDecoder::GetFrame(0)", "the PNG has at least one frame")) { - return false; - } - - ComPtr converter; - if (!HrSucceeded(factory->CreateFormatConverter(converter.GetAddressOf()), __FILE__, __LINE__, - "IWICImagingFactory::CreateFormatConverter", "WIC is initialised")) { - return false; - } - if (!HrSucceeded(converter->Initialize(frame.Get(), GUID_WICPixelFormat32bppRGBA, - WICBitmapDitherTypeNone, nullptr, 0.0, - WICBitmapPaletteTypeCustom), - __FILE__, __LINE__, "IWICFormatConverter::Initialize", - "the decoded frame can be converted to 32bppRGBA without a palette")) { - return false; - } - - UINT width = 0; - UINT height = 0; - if (!HrSucceeded(converter->GetSize(&width, &height), __FILE__, __LINE__, - "IWICFormatConverter::GetSize", "the frame header is intact")) { - return false; - } - surface_out.width = static_cast(width); - surface_out.height = static_cast(height); - surface_out.rgba.resize(static_cast(width) * height * 4); - return HrSucceeded(converter->CopyPixels(nullptr, width * 4, - static_cast(surface_out.rgba.size()), - surface_out.rgba.data()), - __FILE__, __LINE__, "IWICFormatConverter::CopyPixels", - "the file holds a complete image; a truncated PNG fails here"); -} diff --git a/tools/conformance/native/src/png_io.h b/tools/conformance/native/src/png_io.h deleted file mode 100644 index 674ab34d4..000000000 --- a/tools/conformance/native/src/png_io.h +++ /dev/null @@ -1,13 +0,0 @@ -#pragma once - -#include - -#include "pixel_surface.h" - -// Writes the surface as an 8-bit RGBA PNG. The WIC encoder is handed BGRA, the byte -// order it stores natively, so the file's R, G and B channels match the surface exactly. -bool WritePngFile(const std::filesystem::path& path, const PixelSurface& surface); - -// Decodes the first frame of a PNG back into R,G,B,A bytes. Used to prove the file on -// disk, not just the readback buffer, matches the contract. -bool ReadPngFile(const std::filesystem::path& path, PixelSurface& surface_out); diff --git a/tools/conformance/native/src/renderer.cpp b/tools/conformance/native/src/renderer.cpp deleted file mode 100644 index 30258ccbc..000000000 --- a/tools/conformance/native/src/renderer.cpp +++ /dev/null @@ -1,713 +0,0 @@ -#include "renderer.h" - -#include - -#include -#include -#include -#include -#include -#include - -#include "diagnostics.h" - -namespace { - -constexpr UINT kTintConstantStride = 256; // D3D12 requires 256-byte alignment for a root CBV -// D3D12_TEXTURE_DATA_PITCH_ALIGNMENT is 256 bytes: the readback buffer's rows are padded -// to that boundary, which happens to equal width*4 at 256 pixels wide. Deriving it keeps -// the copy loop honest if the scene size ever changes. -constexpr UINT kReadbackRowPitch = - (conform::kSceneWidth * 4 + D3D12_TEXTURE_DATA_PITCH_ALIGNMENT - 1) / - D3D12_TEXTURE_DATA_PITCH_ALIGNMENT * D3D12_TEXTURE_DATA_PITCH_ALIGNMENT; -constexpr UINT kReadbackRowBytes = conform::kSceneWidth * 4; -constexpr SIZE_T kUploadAlignment = 256; -constexpr UINT kFullscreenTriangleVertices = 3; - -// The index buffers are declared uint16_t in the contract and bound as R16_UINT. If the -// contract ever switches to 32-bit indices these fail at compile time instead of every -// index being read as two. -static_assert(std::is_same_v>, uint16_t>); -static_assert(std::is_same_v>, uint16_t>); - -// A .cso held in ordinary memory. D3D12_SHADER_BYTECODE copies nothing, so the vector -// must stay alive until the pipeline state is created. -struct ShaderFile { - std::vector bytes; - - D3D12_SHADER_BYTECODE Bytecode() const { - return D3D12_SHADER_BYTECODE{bytes.data(), bytes.size()}; - } -}; - -// The input layout for conform::ClipVertex. The offsets mirror scenes.h: three floats, -// then four UNORM bytes, so the colour arrives in the shader as straight 0..1 RGBA. -// The asserts make a future edit to the struct a build failure instead of a scene that -// renders the wrong shade. -static_assert(sizeof(conform::ClipVertex) == 16, - "ClipVertex must stay 3 floats + 4 bytes; the input layout assumes 16"); -static_assert(offsetof(conform::ClipVertex, r) == 12, - "COLOR must start at byte 12; the input layout hard-codes that offset"); - -const D3D12_INPUT_ELEMENT_DESC kVertexColorInputLayout[] = { - {"POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, - 0}, - {"COLOR", 0, DXGI_FORMAT_R8G8B8A8_UNORM, 0, 12, D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0}, -}; - -SIZE_T AlignToUploadBoundary(SIZE_T size) { - return (size + (kUploadAlignment - 1)) & ~(kUploadAlignment - 1); -} - -// Creates one committed resource and names it for the debug layer. Reports its own -// failure because every resource in this file is created the same way. -bool CreateCommittedResourceAt(ID3D12Device& device, D3D12_HEAP_TYPE heap_type, - D3D12_RESOURCE_STATES initial_state, - const D3D12_RESOURCE_DESC& description, const wchar_t* debug_name, - ComPtr& resource_out) { - D3D12_HEAP_PROPERTIES heap_properties{}; - heap_properties.Type = heap_type; - heap_properties.CPUPageProperty = D3D12_CPU_PAGE_PROPERTY_UNKNOWN; - heap_properties.MemoryPoolPreference = D3D12_MEMORY_POOL_UNKNOWN; - heap_properties.CreationNodeMask = 0; - heap_properties.VisibleNodeMask = 0; - - const HRESULT result = device.CreateCommittedResource( - &heap_properties, D3D12_HEAP_FLAG_NONE, &description, initial_state, nullptr, - IID_PPV_ARGS(resource_out.GetAddressOf())); - if (!HrSucceeded(result, __FILE__, __LINE__, "ID3D12Device::CreateCommittedResource", - "GPU memory is available and the heap type matches the resource; " - "OUT_OF_MEMORY means the adapter is full or the limit is set too low")) { - return false; - } - resource_out->SetName(debug_name); - return true; -} - -// Upload-heap buffer holding a CPU-side copy of geometry or constants. The size is -// rounded up because D3D12 wants buffer widths aligned and the slack costs nothing. -bool CreateUploadBuffer(ID3D12Device& device, const void* data, SIZE_T data_size, - const wchar_t* debug_name, ComPtr& resource_out) { - D3D12_RESOURCE_DESC description{}; - description.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER; - description.Width = AlignToUploadBoundary(data_size); - description.Height = 1; - description.DepthOrArraySize = 1; - description.MipLevels = 1; - description.Format = DXGI_FORMAT_UNKNOWN; - description.SampleDesc.Count = 1; - description.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; - description.Flags = D3D12_RESOURCE_FLAG_NONE; - - if (!CreateCommittedResourceAt(device, D3D12_HEAP_TYPE_UPLOAD, D3D12_RESOURCE_STATE_GENERIC_READ, - description, debug_name, resource_out)) { - return false; - } - - void* mapped = nullptr; - if (!HrSucceeded(resource_out->Map(0, nullptr, &mapped), __FILE__, __LINE__, - "ID3D12Resource::Map(upload)", "the upload heap is not exhausted")) { - return false; - } - std::memcpy(mapped, data, data_size); - resource_out->Unmap(0, nullptr); - return true; -} - -D3D12_RESOURCE_DESC MakeTextureDescription(DXGI_FORMAT format, D3D12_RESOURCE_FLAGS flags) { - D3D12_RESOURCE_DESC description{}; - description.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D; - description.Width = static_cast(conform::kSceneWidth); - description.Height = static_cast(conform::kSceneHeight); - description.DepthOrArraySize = 1; - description.MipLevels = 1; - description.Format = format; - description.SampleDesc.Count = 1; - description.SampleDesc.Quality = 0; - description.Layout = D3D12_TEXTURE_LAYOUT_UNKNOWN; - description.Flags = flags; - return description; -} - -bool CreateDescriptorHeaps(Renderer& renderer, ID3D12Device& device) { - D3D12_DESCRIPTOR_HEAP_DESC render_target_heap{}; - render_target_heap.Type = D3D12_DESCRIPTOR_HEAP_TYPE_RTV; - render_target_heap.NumDescriptors = 1; - if (!HrSucceeded(device.CreateDescriptorHeap(&render_target_heap, IID_PPV_ARGS( - renderer.render_target_view_heap.GetAddressOf())), - __FILE__, __LINE__, "ID3D12Device::CreateDescriptorHeap(RTV)", - "the RTV heap limit is not exhausted and the heap type is supported")) { - return false; - } - renderer.color_render_target_view = - renderer.render_target_view_heap->GetCPUDescriptorHandleForHeapStart(); - - D3D12_DESCRIPTOR_HEAP_DESC depth_stencil_heap{}; - depth_stencil_heap.Type = D3D12_DESCRIPTOR_HEAP_TYPE_DSV; - depth_stencil_heap.NumDescriptors = 1; - if (!HrSucceeded(device.CreateDescriptorHeap(&depth_stencil_heap, IID_PPV_ARGS( - renderer.depth_stencil_view_heap.GetAddressOf())), - __FILE__, __LINE__, "ID3D12Device::CreateDescriptorHeap(DSV)", - "the DSV heap limit is not exhausted and the heap type is supported")) { - return false; - } - renderer.depth_stencil_view = - renderer.depth_stencil_view_heap->GetCPUDescriptorHandleForHeapStart(); - return true; -} - -bool CreateTargets(Renderer& renderer, ID3D12Device& device) { - if (!CreateCommittedResourceAt(device, D3D12_HEAP_TYPE_DEFAULT, D3D12_RESOURCE_STATE_COMMON, - MakeTextureDescription(DXGI_FORMAT_R8G8B8A8_UNORM, - D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET), - L"color_target", renderer.color_target)) { - return false; - } - if (!CreateCommittedResourceAt(device, D3D12_HEAP_TYPE_DEFAULT, D3D12_RESOURCE_STATE_DEPTH_WRITE, - MakeTextureDescription(DXGI_FORMAT_D32_FLOAT, - D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL), - L"depth_target", renderer.depth_target)) { - return false; - } - - D3D12_RESOURCE_DESC readback_description{}; - readback_description.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER; - readback_description.Width = static_cast(kReadbackRowPitch) * conform::kSceneHeight; - readback_description.Height = 1; - readback_description.DepthOrArraySize = 1; - readback_description.MipLevels = 1; - readback_description.Format = DXGI_FORMAT_UNKNOWN; - readback_description.SampleDesc.Count = 1; - readback_description.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; - if (!CreateCommittedResourceAt(device, D3D12_HEAP_TYPE_READBACK, D3D12_RESOURCE_STATE_COPY_DEST, - readback_description, L"readback_buffer", - renderer.readback_buffer)) { - return false; - } - - // Null descriptions inherit the resource format, which is what the pipelines expect. - device.CreateRenderTargetView(renderer.color_target.Get(), nullptr, - renderer.color_render_target_view); - device.CreateDepthStencilView(renderer.depth_target.Get(), nullptr, - renderer.depth_stencil_view); - return true; -} - -bool CreateGeometryBuffers(Renderer& renderer, ID3D12Device& device) { - if (!CreateUploadBuffer(device, conform::kDepthOrderVertices, - sizeof(conform::kDepthOrderVertices), L"depth_order_vertex_buffer", - renderer.depth_order_vertex_buffer)) { - return false; - } - if (!CreateUploadBuffer(device, conform::kDepthOrderIndices, - sizeof(conform::kDepthOrderIndices), L"depth_order_index_buffer", - renderer.depth_order_index_buffer)) { - return false; - } - if (!CreateUploadBuffer(device, conform::kIndexedVertices, sizeof(conform::kIndexedVertices), - L"indexed_vertex_buffer", renderer.indexed_vertex_buffer)) { - return false; - } - if (!CreateUploadBuffer(device, conform::kIndexedIndices, sizeof(conform::kIndexedIndices), - L"indexed_index_buffer", renderer.indexed_index_buffer)) { - return false; - } - - renderer.depth_order_vertex_view.BufferLocation = - renderer.depth_order_vertex_buffer->GetGPUVirtualAddress(); - renderer.depth_order_vertex_view.SizeInBytes = - static_cast(sizeof(conform::kDepthOrderVertices)); - renderer.depth_order_vertex_view.StrideInBytes = - static_cast(sizeof(conform::ClipVertex)); - - renderer.depth_order_index_view.BufferLocation = - renderer.depth_order_index_buffer->GetGPUVirtualAddress(); - renderer.depth_order_index_view.SizeInBytes = - static_cast(sizeof(conform::kDepthOrderIndices)); - renderer.depth_order_index_view.Format = DXGI_FORMAT_R16_UINT; - - renderer.indexed_vertex_view.BufferLocation = - renderer.indexed_vertex_buffer->GetGPUVirtualAddress(); - renderer.indexed_vertex_view.SizeInBytes = static_cast(sizeof(conform::kIndexedVertices)); - renderer.indexed_vertex_view.StrideInBytes = static_cast(sizeof(conform::ClipVertex)); - - renderer.indexed_index_view.BufferLocation = - renderer.indexed_index_buffer->GetGPUVirtualAddress(); - renderer.indexed_index_view.SizeInBytes = static_cast(sizeof(conform::kIndexedIndices)); - renderer.indexed_index_view.Format = DXGI_FORMAT_R16_UINT; - return true; -} - -bool CreateTintConstants(Renderer& renderer, ID3D12Device& device) { - // One 256-byte slot per scene. Each slot holds exactly the single float4 the contract - // specifies at byte offset 0, already divided by 255 so the UNORM bytes come back - // exact. Slots are filled before any draw and never rewritten. - std::vector slot_bytes( - static_cast(conform::kSceneCount) * kTintConstantStride, 0); - for (int index = 0; index < conform::kSceneCount; ++index) { - const conform::Scene& scene = conform::kScenes[index]; - const float tint[4] = {scene.tintR / 255.0f, scene.tintG / 255.0f, - scene.tintB / 255.0f, scene.tintA / 255.0f}; - std::memcpy(slot_bytes.data() + static_cast(index) * kTintConstantStride, tint, - sizeof tint); - } - return CreateUploadBuffer(device, slot_bytes.data(), slot_bytes.size(), L"tint_constants", - renderer.tint_constants); -} - -// Address of one scene's float4. Callers validate the slot; this only converts. -D3D12_GPU_VIRTUAL_ADDRESS TintAddress(const Renderer& renderer, int tint_slot) { - return renderer.tint_constants->GetGPUVirtualAddress() + - static_cast(tint_slot) * kTintConstantStride; -} - -// Serialises and creates a root signature. On a serialisation failure the compiler's -// own message is printed, because that text names the offending parameter. -bool CreateRootSignatureFromDescription(ID3D12Device& device, - const D3D12_ROOT_SIGNATURE_DESC& description, - const wchar_t* debug_name, - ComPtr& signature_out) { - ComPtr serialized; - ComPtr error_text; - const HRESULT serialize_result = D3D12SerializeRootSignature( - &description, D3D_ROOT_SIGNATURE_VERSION_1, serialized.GetAddressOf(), - error_text.GetAddressOf()); - if (FAILED(serialize_result)) { - if (error_text != nullptr) { - std::fprintf(stderr, "root signature error: %.*s\n", - static_cast(error_text->GetBufferSize()), - static_cast(error_text->GetBufferPointer())); - } - HrSucceeded(serialize_result, __FILE__, __LINE__, "D3D12SerializeRootSignature", - "the root signature description is valid; the printed text names the " - "offending field"); - return false; - } - if (!HrSucceeded(device.CreateRootSignature(0, serialized->GetBufferPointer(), - serialized->GetBufferSize(), - IID_PPV_ARGS(signature_out.GetAddressOf())), - __FILE__, __LINE__, "ID3D12Device::CreateRootSignature", - "the device is still present and the serialised blob is intact")) { - return false; - } - signature_out->SetName(debug_name); - return true; -} - -bool CreateSceneRootSignature(Renderer& renderer, ID3D12Device& device) { - // The contract's baseline: one root CBV at b0, shader visibility ALL, space 0, and - // ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT so the vertex-colour pipeline can declare an - // input layout. The vertex-colour shaders never read b0; every draw binds it anyway so - // all three pipelines share one signature, exactly as the header specifies. - D3D12_ROOT_PARAMETER tint_parameter{}; - tint_parameter.ParameterType = D3D12_ROOT_PARAMETER_TYPE_CBV; - tint_parameter.Descriptor.ShaderRegister = 0; - tint_parameter.Descriptor.RegisterSpace = 0; - tint_parameter.ShaderVisibility = D3D12_SHADER_VISIBILITY_ALL; - - D3D12_ROOT_SIGNATURE_DESC description{}; - description.NumParameters = 1; - description.pParameters = &tint_parameter; - description.Flags = D3D12_ROOT_SIGNATURE_FLAG_ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT; - return CreateRootSignatureFromDescription(device, description, L"scene_root_signature", - renderer.root_signature); -} - -// The state every pipeline shares. Callers override blend and depth; the three pipelines -// share everything else. Scissor is not pipeline state in D3D12: it is per-draw state set -// in ClearAndDrawScene, which is why no pipeline mentions it. -D3D12_GRAPHICS_PIPELINE_STATE_DESC MakeBasePipelineDescription( - ID3D12RootSignature& root_signature, const D3D12_SHADER_BYTECODE& vertex_shader, - const D3D12_SHADER_BYTECODE& pixel_shader, const D3D12_INPUT_LAYOUT_DESC& input_layout) { - D3D12_GRAPHICS_PIPELINE_STATE_DESC description{}; - description.pRootSignature = &root_signature; - description.VS = vertex_shader; - description.PS = pixel_shader; - description.IBStripCutValue = D3D12_INDEX_BUFFER_STRIP_CUT_VALUE_DISABLED; - description.PrimitiveTopologyType = D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE; - description.NumRenderTargets = 1; - description.RTVFormats[0] = DXGI_FORMAT_R8G8B8A8_UNORM; - description.DSVFormat = DXGI_FORMAT_D32_FLOAT; - description.SampleDesc.Count = 1; - description.SampleMask = UINT_MAX; - description.Flags = D3D12_PIPELINE_STATE_FLAG_NONE; - description.InputLayout = input_layout; - - // Winding is irrelevant for these axis-aligned quads and a fullscreen triangle, so - // culling is off; a cull setting must never be what makes a scene pass or fail. - description.RasterizerState.FillMode = D3D12_FILL_MODE_SOLID; - description.RasterizerState.CullMode = D3D12_CULL_MODE_NONE; - description.RasterizerState.FrontCounterClockwise = FALSE; - description.RasterizerState.DepthBias = 0; - description.RasterizerState.DepthBiasClamp = 0.0f; - description.RasterizerState.SlopeScaledDepthBias = 0.0f; - description.RasterizerState.DepthClipEnable = TRUE; - description.RasterizerState.MultisampleEnable = FALSE; - description.RasterizerState.AntialiasedLineEnable = FALSE; - description.RasterizerState.ForcedSampleCount = 0; - description.RasterizerState.ConservativeRaster = D3D12_CONSERVATIVE_RASTERIZATION_MODE_OFF; - - description.BlendState.AlphaToCoverageEnable = FALSE; - description.BlendState.IndependentBlendEnable = FALSE; - description.BlendState.RenderTarget[0].BlendEnable = FALSE; - description.BlendState.RenderTarget[0].RenderTargetWriteMask = D3D12_COLOR_WRITE_ENABLE_ALL; - - description.DepthStencilState.DepthEnable = FALSE; - description.DepthStencilState.DepthWriteMask = D3D12_DEPTH_WRITE_MASK_ZERO; - description.DepthStencilState.DepthFunc = D3D12_COMPARISON_FUNC_LESS; - description.DepthStencilState.StencilEnable = FALSE; - return description; -} - -bool CreateFullscreenPipeline(Renderer& renderer, ID3D12Device& device, - const ShaderFile& vertex_shader, const ShaderFile& pixel_shader) { - const D3D12_INPUT_LAYOUT_DESC no_input_layout{nullptr, 0}; - D3D12_GRAPHICS_PIPELINE_STATE_DESC description = MakeBasePipelineDescription( - *renderer.root_signature.Get(), vertex_shader.Bytecode(), - pixel_shader.Bytecode(), no_input_layout); - if (!HrSucceeded(device.CreateGraphicsPipelineState(&description, IID_PPV_ARGS( - renderer.fullscreen_pipeline.GetAddressOf())), - __FILE__, __LINE__, "ID3D12Device::CreateGraphicsPipelineState(fullscreen)", - "the shader bytecode matches the declared formats and the shader model is " - "supported by this adapter")) { - return false; - } - renderer.fullscreen_pipeline->SetName(L"fullscreen_pipeline"); - return true; -} - -bool CreateBlendPipeline(Renderer& renderer, ID3D12Device& device, - const ShaderFile& vertex_shader, const ShaderFile& pixel_shader) { - const D3D12_INPUT_LAYOUT_DESC no_input_layout{nullptr, 0}; - D3D12_GRAPHICS_PIPELINE_STATE_DESC description = MakeBasePipelineDescription( - *renderer.root_signature.Get(), vertex_shader.Bytecode(), - pixel_shader.Bytecode(), no_input_layout); - description.BlendState.RenderTarget[0].BlendEnable = TRUE; - description.BlendState.RenderTarget[0].SrcBlend = D3D12_BLEND_SRC_ALPHA; - description.BlendState.RenderTarget[0].DestBlend = D3D12_BLEND_INV_SRC_ALPHA; - description.BlendState.RenderTarget[0].BlendOp = D3D12_BLEND_OP_ADD; - // The contract states the alpha channel explicitly: ONE, INV_SRC_ALPHA, ADD, which - // evaluates to 1.0*0.5 + 0.5*1.0 = 1.0 and stores 255. SRC_ALPHA here would store - // 191 and fail the scene's checks. - description.BlendState.RenderTarget[0].SrcBlendAlpha = D3D12_BLEND_ONE; - description.BlendState.RenderTarget[0].DestBlendAlpha = D3D12_BLEND_INV_SRC_ALPHA; - description.BlendState.RenderTarget[0].BlendOpAlpha = D3D12_BLEND_OP_ADD; - if (!HrSucceeded(device.CreateGraphicsPipelineState(&description, IID_PPV_ARGS( - renderer.blend_pipeline.GetAddressOf())), - __FILE__, __LINE__, "ID3D12Device::CreateGraphicsPipelineState(blend)", - "the render target format supports blending; R8G8B8A8_UNORM always does")) { - return false; - } - renderer.blend_pipeline->SetName(L"blend_pipeline"); - return true; -} - -bool CreateVertexColorPipeline(Renderer& renderer, ID3D12Device& device, - const ShaderFile& vertex_shader, const ShaderFile& pixel_shader) { - D3D12_INPUT_LAYOUT_DESC input_layout{}; - input_layout.pInputElementDescs = kVertexColorInputLayout; - input_layout.NumElements = static_cast( - sizeof(kVertexColorInputLayout) / sizeof(kVertexColorInputLayout[0])); - D3D12_GRAPHICS_PIPELINE_STATE_DESC description = MakeBasePipelineDescription( - *renderer.root_signature.Get(), vertex_shader.Bytecode(), pixel_shader.Bytecode(), - input_layout); - // The only pipeline with depth: the contract asks for LESS with writes enabled so the - // nearer green quad wins regardless of draw order. - description.DepthStencilState.DepthEnable = TRUE; - description.DepthStencilState.DepthWriteMask = D3D12_DEPTH_WRITE_MASK_ALL; - description.DepthStencilState.DepthFunc = D3D12_COMPARISON_FUNC_LESS; - if (!HrSucceeded(device.CreateGraphicsPipelineState(&description, IID_PPV_ARGS( - renderer.vertex_color_pipeline.GetAddressOf())), - __FILE__, __LINE__, "ID3D12Device::CreateGraphicsPipelineState(vertex_color)", - "the input layout matches the shader's semantics and the depth format is " - "supported")) { - return false; - } - renderer.vertex_color_pipeline->SetName(L"vertex_color_pipeline"); - return true; -} - -bool LoadShaderFile(const std::filesystem::path& path, ShaderFile& shader_out) { - std::ifstream input(path, std::ios::binary | std::ios::ate); - if (!input.is_open()) { - ReportFailure(__FILE__, __LINE__, "std::ifstream::open", - "could not open " + TextFromWide(path.native()), - "the build ran the conform_shaders target and the shaders directory sits " - "next to conform_native.exe; use --shaders to point elsewhere"); - return false; - } - const std::streamoff size = input.tellg(); - if (size <= 0) { - ReportFailure(__FILE__, __LINE__, "std::ifstream::tellg", - TextFromWide(path.native()) + " is empty", - "rebuild with the conform_shaders target so dxc writes a real .cso"); - return false; - } - shader_out.bytes.resize(static_cast(size)); - input.seekg(0, std::ios::beg); - input.read(reinterpret_cast(shader_out.bytes.data()), size); - if (!input) { - ReportFailure(__FILE__, __LINE__, "std::ifstream::read", - "could not read all of " + TextFromWide(path.native()), - "the file is not locked by another process and the disk is readable"); - return false; - } - return true; -} - -bool CreatePipelines(Renderer& renderer, ID3D12Device& device, - const std::filesystem::path& shader_directory) { - ShaderFile fullscreen_vertex_shader; - ShaderFile fullscreen_pixel_shader; - ShaderFile vertex_color_vertex_shader; - ShaderFile vertex_color_pixel_shader; - if (!LoadShaderFile(shader_directory / "fullscreen_color.vs.cso", fullscreen_vertex_shader) || - !LoadShaderFile(shader_directory / "fullscreen_color.ps.cso", fullscreen_pixel_shader) || - !LoadShaderFile(shader_directory / "vertex_color.vs.cso", vertex_color_vertex_shader) || - !LoadShaderFile(shader_directory / "vertex_color.ps.cso", vertex_color_pixel_shader)) { - return false; - } - - if (!CreateSceneRootSignature(renderer, device) || - !CreateFullscreenPipeline(renderer, device, fullscreen_vertex_shader, - fullscreen_pixel_shader) || - !CreateBlendPipeline(renderer, device, fullscreen_vertex_shader, - fullscreen_pixel_shader) || - !CreateVertexColorPipeline(renderer, device, vertex_color_vertex_shader, - vertex_color_pixel_shader)) { - return false; - } - return true; -} - -bool CreateCommandObjects(Renderer& renderer, ID3D12Device& device) { - if (!HrSucceeded(device.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS( - renderer.command_allocator.GetAddressOf())), - __FILE__, __LINE__, "ID3D12Device::CreateCommandAllocator", - "the direct queue was created successfully")) { - return false; - } - if (!HrSucceeded(device.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, - renderer.command_allocator.Get(), nullptr, - IID_PPV_ARGS(renderer.command_list.GetAddressOf())), - __FILE__, __LINE__, "ID3D12Device::CreateCommandList", - "the allocator is valid and no list of this type is already recording")) { - return false; - } - // A newly created list is open; close it so the first scene starts from a clean reset. - return HrSucceeded(renderer.command_list->Close(), __FILE__, __LINE__, - "ID3D12GraphicsCommandList::Close", - "the list was created in a recordable state"); -} - -// Inserts one transition for every subresource. All barriers in this file go through it -// so the before-state is always the state the previous barrier left behind. -bool TransitionColorTarget(Renderer& renderer, D3D12_RESOURCE_STATES state_before, - D3D12_RESOURCE_STATES state_after) { - if (state_before == state_after) { - ReportFailure(__FILE__, __LINE__, "TransitionColorTarget", - "the barrier would have identical before and after states", - "this is a renderer bug in the scene state machine, not a driver issue"); - return false; - } - D3D12_RESOURCE_BARRIER barrier{}; - barrier.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION; - barrier.Flags = D3D12_RESOURCE_BARRIER_FLAG_NONE; - barrier.Transition.pResource = renderer.color_target.Get(); - barrier.Transition.Subresource = D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES; - barrier.Transition.StateBefore = state_before; - barrier.Transition.StateAfter = state_after; - renderer.command_list->ResourceBarrier(1, &barrier); - return true; -} - -// Binds the pipeline named by the plan and issues exactly one draw. Split from the -// recording function so that function stays short and the draw geometry is in one place. -void BindPipelineAndDraw(Renderer& renderer, const DrawPlan& plan) { - ID3D12PipelineState* pipeline = nullptr; - switch (plan.pipeline) { - case PipelineKind::Fullscreen: - pipeline = renderer.fullscreen_pipeline.Get(); - break; - case PipelineKind::Blend: - pipeline = renderer.blend_pipeline.Get(); - break; - case PipelineKind::VertexColor: - pipeline = renderer.vertex_color_pipeline.Get(); - break; - } - ID3D12GraphicsCommandList* list = renderer.command_list.Get(); - list->SetPipelineState(pipeline); - // Bound for every draw, including vertex-colour draws whose shaders ignore it: the - // contract's baseline names one root CBV at b0 for every scene. - list->SetGraphicsRootSignature(renderer.root_signature.Get()); - list->SetGraphicsRootConstantBufferView(0, TintAddress(renderer, plan.tint_slot)); - list->IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST); - - switch (plan.geometry) { - case GeometryKind::None: - return; - case GeometryKind::FullscreenTriangle: - list->DrawInstanced(kFullscreenTriangleVertices, 1, 0, 0); - return; - case GeometryKind::DepthOrderQuads: - list->IASetVertexBuffers(0, 1, &renderer.depth_order_vertex_view); - list->IASetIndexBuffer(&renderer.depth_order_index_view); - // The index buffer carries the contract's draw order: near green first, far - // red second. A renderer that ignores depth paints red over green. - list->DrawIndexedInstanced( - static_cast(sizeof(conform::kDepthOrderIndices) / sizeof(uint16_t)), 1, 0, 0, 0); - return; - case GeometryKind::IndexedTriangles: - list->IASetVertexBuffers(0, 1, &renderer.indexed_vertex_view); - list->IASetIndexBuffer(&renderer.indexed_index_view); - list->DrawIndexedInstanced( - static_cast(sizeof(conform::kIndexedIndices) / sizeof(uint16_t)), 1, 0, 0, 0); - return; - } -} - -// Clears the colour target (and the depth target for depth_order only), then draws when -// the plan asks for geometry. The clear always happens, which is what the clear scene -// alone tests. -void ClearAndDrawScene(Renderer& renderer, const DrawPlan& plan) { - ID3D12GraphicsCommandList* list = renderer.command_list.Get(); - // The contract's baseline binds a DSV only for depth_order; every other scene passes - // a null DSV, which leaves depth testing inert. - const D3D12_CPU_DESCRIPTOR_HANDLE* depth_view = - plan.binds_depth_target ? &renderer.depth_stencil_view : nullptr; - list->OMSetRenderTargets(1, &renderer.color_render_target_view, FALSE, depth_view); - - const float clear_color[4] = {conform::kClearR / 255.0f, conform::kClearG / 255.0f, - conform::kClearB / 255.0f, conform::kClearA / 255.0f}; - list->ClearRenderTargetView(renderer.color_render_target_view, clear_color, 0, nullptr); - if (plan.binds_depth_target) { - list->ClearDepthStencilView(renderer.depth_stencil_view, D3D12_CLEAR_FLAG_DEPTH, 1.0f, 0, 0, - nullptr); - } - list->RSSetViewports(1, &renderer.viewport); - list->RSSetScissorRects(1, &plan.scissor); - if (plan.geometry != GeometryKind::None) { - BindPipelineAndDraw(renderer, plan); - } -} - -// Copies the rendered target into the readback buffer at the contract's row pitch. -void CopyColorTargetToReadback(Renderer& renderer) { - D3D12_TEXTURE_COPY_LOCATION destination{}; - destination.pResource = renderer.readback_buffer.Get(); - destination.Type = D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT; - destination.PlacedFootprint.Offset = 0; // 512-byte aligned, as placed footprints require - destination.PlacedFootprint.Footprint.Format = DXGI_FORMAT_R8G8B8A8_UNORM; - destination.PlacedFootprint.Footprint.Width = static_cast(conform::kSceneWidth); - destination.PlacedFootprint.Footprint.Height = static_cast(conform::kSceneHeight); - destination.PlacedFootprint.Footprint.Depth = 1; - destination.PlacedFootprint.Footprint.RowPitch = kReadbackRowPitch; - - D3D12_TEXTURE_COPY_LOCATION source{}; - source.pResource = renderer.color_target.Get(); - source.Type = D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX; - source.SubresourceIndex = 0; - - const D3D12_BOX source_box{0, 0, 0, static_cast(conform::kSceneWidth), - static_cast(conform::kSceneHeight), 1}; - renderer.command_list->CopyTextureRegion(&destination, 0, 0, 0, &source, &source_box); -} - -// Records one scene's whole pass: reset, clear, optional draw, copy out, back to COMMON -// so the next scene always starts from the same state. -bool RecordSceneCommands(Renderer& renderer, const DrawPlan& plan) { - if (!HrSucceeded(renderer.command_allocator->Reset(), __FILE__, __LINE__, - "ID3D12CommandAllocator::Reset", - "the GPU finished the previous scene; RenderScene waits on a fence before " - "the next reset")) { - return false; - } - if (!HrSucceeded(renderer.command_list->Reset(renderer.command_allocator.Get(), nullptr), - __FILE__, __LINE__, "ID3D12GraphicsCommandList::Reset", - "the list is closed and its allocator was just reset")) { - return false; - } - - if (!TransitionColorTarget(renderer, D3D12_RESOURCE_STATE_COMMON, - D3D12_RESOURCE_STATE_RENDER_TARGET)) { - return false; - } - ClearAndDrawScene(renderer, plan); - if (!TransitionColorTarget(renderer, D3D12_RESOURCE_STATE_RENDER_TARGET, - D3D12_RESOURCE_STATE_COPY_SOURCE)) { - return false; - } - CopyColorTargetToReadback(renderer); - if (!TransitionColorTarget(renderer, D3D12_RESOURCE_STATE_COPY_SOURCE, - D3D12_RESOURCE_STATE_COMMON)) { - return false; - } - return HrSucceeded(renderer.command_list->Close(), __FILE__, __LINE__, - "ID3D12GraphicsCommandList::Close", - "every recording call above succeeded on a list that was open"); -} - -// Maps the readback buffer and copies it row by row; the row pitch is explicit because -// a buffer's mapped layout follows the placed footprint, not the image width alone. -bool CopyReadbackToSurface(Renderer& renderer, PixelSurface& surface_out) { - void* mapped = nullptr; - if (!HrSucceeded(renderer.readback_buffer->Map(0, nullptr, &mapped), __FILE__, __LINE__, - "ID3D12Resource::Map(readback)", - "the GPU finished the copy and the resource is a readback heap buffer")) { - return false; - } - surface_out.width = conform::kSceneWidth; - surface_out.height = conform::kSceneHeight; - // The surface is tightly packed; the mapped buffer is not. Copy row bytes, not pitch. - const SIZE_T image_size = static_cast(kReadbackRowBytes) * conform::kSceneHeight; - surface_out.rgba.resize(image_size); - for (int row = 0; row < conform::kSceneHeight; ++row) { - std::memcpy(surface_out.rgba.data() + static_cast(row) * kReadbackRowBytes, - static_cast(mapped) + static_cast(row) * kReadbackRowPitch, - kReadbackRowBytes); - } - renderer.readback_buffer->Unmap(0, nullptr); - return true; -} - -} // namespace - -bool Renderer::Initialize(GpuContext& gpu, const std::filesystem::path& shader_directory) { - if (!CreateDescriptorHeaps(*this, *gpu.device.Get()) || !CreateTargets(*this, *gpu.device.Get()) || - !CreateGeometryBuffers(*this, *gpu.device.Get()) || - !CreateTintConstants(*this, *gpu.device.Get()) || !CreatePipelines(*this, *gpu.device.Get(), - shader_directory) || - !CreateCommandObjects(*this, *gpu.device.Get())) { - return false; - } - - viewport.TopLeftX = 0.0f; - viewport.TopLeftY = 0.0f; - viewport.Width = static_cast(conform::kSceneWidth); - viewport.Height = static_cast(conform::kSceneHeight); - viewport.MinDepth = 0.0f; // the clip-space z values in scenes.h map straight to 0..1 - viewport.MaxDepth = 1.0f; - return true; -} - -bool Renderer::RenderScene(GpuContext& gpu, const DrawPlan& plan, PixelSurface& surface_out) { - if (plan.tint_slot < 0 || plan.tint_slot >= conform::kSceneCount) { - ReportFailure(__FILE__, __LINE__, "Renderer::RenderScene", - "tint slot " + std::to_string(plan.tint_slot) + - " is outside the constant buffer", - "MakeDrawPlan is given an index inside conform::kScenes"); - return false; - } - if (!RecordSceneCommands(*this, plan)) { - return false; - } - ID3D12CommandList* command_lists[] = {command_list.Get()}; - gpu.command_queue->ExecuteCommandLists(1, command_lists); - if (!SignalAndWaitForGpu(gpu) || !DeviceStillPresent(gpu)) { - return false; - } - return CopyReadbackToSurface(*this, surface_out); -} diff --git a/tools/conformance/native/src/renderer.h b/tools/conformance/native/src/renderer.h deleted file mode 100644 index 198f252c0..000000000 --- a/tools/conformance/native/src/renderer.h +++ /dev/null @@ -1,65 +0,0 @@ -#pragma once - -#include - -#include - -#include "gpu.h" -#include "pixel_surface.h" -#include "scene_plan.h" - -// A D3D12 renderer fixed to the contract's 256x256 R8G8B8A8_UNORM target with a -// D32_FLOAT depth buffer, no swapchain. Owns every GPU object it needs; the only state -// that lives outside is the device and queue in GpuContext. -// -// It does not create a window, pump messages, present, or touch D:\conform\spec; the -// shaders are loaded from disk as compiled by the build. -struct Renderer { - // Descriptor heaps. One RTV and one DSV is all the contract needs. - ComPtr render_target_view_heap; - ComPtr depth_stencil_view_heap; - D3D12_CPU_DESCRIPTOR_HANDLE color_render_target_view{}; - D3D12_CPU_DESCRIPTOR_HANDLE depth_stencil_view{}; - - // Render and readback targets. - ComPtr color_target; - ComPtr depth_target; - ComPtr readback_buffer; - - // Geometry, one upload buffer per array in scenes.h. - ComPtr depth_order_vertex_buffer; - ComPtr depth_order_index_buffer; - ComPtr indexed_vertex_buffer; - ComPtr indexed_index_buffer; - D3D12_VERTEX_BUFFER_VIEW depth_order_vertex_view{}; - D3D12_INDEX_BUFFER_VIEW depth_order_index_view{}; - D3D12_VERTEX_BUFFER_VIEW indexed_vertex_view{}; - D3D12_INDEX_BUFFER_VIEW indexed_index_view{}; - - // One constant-buffer slot per scene: the contract now gives each scene its own - // tint, and a root CBV must sit on a 256-byte boundary. Filled once before any draw, - // so no CPU write can race a GPU read. - ComPtr tint_constants; - - // Pipelines and the one root signature they share. - ComPtr root_signature; - ComPtr fullscreen_pipeline; - ComPtr blend_pipeline; - ComPtr vertex_color_pipeline; - - // Command recording objects. One list is enough because every scene waits for the - // GPU before the next reset. - ComPtr command_allocator; - ComPtr command_list; - - // Fixed state shared by every scene. - D3D12_VIEWPORT viewport{}; - - // Creates every resource, pipeline and command object. Does not render anything and - // does not verify output; RenderScene does both of those. - bool Initialize(GpuContext& gpu, const std::filesystem::path& shader_directory); - - // Renders one scene, waits for the GPU, and fills surface_out with the readback - // pixels. Does not compare them against the contract; VerifyChecks does that. - bool RenderScene(GpuContext& gpu, const DrawPlan& plan, PixelSurface& surface_out); -}; diff --git a/tools/conformance/native/src/scene_plan.cpp b/tools/conformance/native/src/scene_plan.cpp deleted file mode 100644 index 6effaeac8..000000000 --- a/tools/conformance/native/src/scene_plan.cpp +++ /dev/null @@ -1,52 +0,0 @@ -#include "scene_plan.h" - -#include -#include - -DrawPlan MakeDrawPlan(const conform::Scene& scene, int scene_index) { - DrawPlan plan{}; - plan.tint_slot = scene_index; - // The baseline scissor is the full target; only the scissor scene narrows it. - plan.scissor = {0, 0, conform::kSceneWidth, conform::kSceneHeight}; - - switch (scene.kind) { - case conform::SceneKind::Clear: - // No draw at all: the contract tests the clear and the readback path. - plan.geometry = GeometryKind::None; - break; - case conform::SceneKind::Fullscreen: - plan.geometry = GeometryKind::FullscreenTriangle; - break; - case conform::SceneKind::DepthOrder: - plan.pipeline = PipelineKind::VertexColor; - plan.geometry = GeometryKind::DepthOrderQuads; - // The only scene that binds a depth target; every other scene passes a null - // DSV, which is what the contract's baseline table says. - plan.binds_depth_target = true; - break; - case conform::SceneKind::Scissor: - // Same pipeline as fullscreen. D3D12 applies the scissor test whenever a rect - // is set, with no enable flag in the pipeline state, so this scene proves - // RSSetScissorRects. Right and bottom are exclusive. - plan.geometry = GeometryKind::FullscreenTriangle; - plan.scissor = {conform::kScissorLeft, conform::kScissorTop, conform::kScissorRight, - conform::kScissorBottom}; - break; - case conform::SceneKind::Blend: - plan.pipeline = PipelineKind::Blend; - plan.geometry = GeometryKind::FullscreenTriangle; - break; - case conform::SceneKind::Indexed: - plan.pipeline = PipelineKind::VertexColor; - plan.geometry = GeometryKind::IndexedTriangles; - break; - default: - // Unreachable while every SceneKind has a case above. If scenes.h gains a kind - // and this switch is forgotten, /we4062 turns the missing case into a build - // error; this line is the belt for a compiler that does not implement it. - std::fprintf(stderr, "internal: scene kind %d has no draw plan\n", - static_cast(scene.kind)); - std::abort(); - } - return plan; -} diff --git a/tools/conformance/native/src/scene_plan.h b/tools/conformance/native/src/scene_plan.h deleted file mode 100644 index 4328b44df..000000000 --- a/tools/conformance/native/src/scene_plan.h +++ /dev/null @@ -1,36 +0,0 @@ -#pragma once - -#include - -#include "scenes.h" - -// Which of the three pipeline states the draw needs. The PSO carries blend and depth -// state, so this choice fixes both at once; the scissor rect and the depth-target binding -// are per-scene state, because D3D12 always applies the scissor and allows a null DSV. -enum class PipelineKind { - Fullscreen, // oversized triangle, no depth, no blend - Blend, // identical but with the contract's blend state - VertexColor, // vertex buffer + 16-bit indices, depth LESS with write -}; - -enum class GeometryKind { - None, // clear only - FullscreenTriangle, // SV_VertexID, three vertices, no buffers - DepthOrderQuads, // conform::kDepthOrderVertices / kDepthOrderIndices - IndexedTriangles, // conform::kIndexedVertices / kIndexedIndices -}; - -// Everything one scene needs bound, resolved from the contract before any GPU call so -// the render loop contains no per-scene branching. -struct DrawPlan { - PipelineKind pipeline = PipelineKind::Fullscreen; - GeometryKind geometry = GeometryKind::None; - int tint_slot = 0; // which 256-byte slot holds this scene's float4 - bool binds_depth_target = false; // true only for depth_order, per the baseline state - D3D12_RECT scissor{}; -}; - -// Maps a contract scene to pipeline, geometry, constant-buffer slot, depth binding and -// scissor. scene_index is the scene's position in conform::kScenes and selects its tint. -// Pure function: reads only scenes.h values and touches no device state. -DrawPlan MakeDrawPlan(const conform::Scene& scene, int scene_index); diff --git a/tools/conformance/native/src/verify.cpp b/tools/conformance/native/src/verify.cpp deleted file mode 100644 index 3c37f2d68..000000000 --- a/tools/conformance/native/src/verify.cpp +++ /dev/null @@ -1,50 +0,0 @@ -#include "verify.h" - -#include -#include - -namespace { - -// A scene with zero checks proves nothing, and a count above the array size reads past -// the end. Both are contract errors, so they are build errors rather than runtime ones. -constexpr bool CheckCountsAreSane() { - for (const conform::Scene& scene : conform::kScenes) { - if (scene.checkCount < 1 || scene.checkCount > static_cast(std::size(scene.checks))) { - return false; - } - } - return true; -} -static_assert(CheckCountsAreSane(), "every scene needs 1..N pixel checks; see conform::Scene"); - -} // namespace - -CheckTally VerifyChecks(const conform::Scene& scene, const PixelSurface& surface, - const char* source_label) { - CheckTally tally; - for (int index = 0; index < scene.checkCount; ++index) { - const conform::PixelCheck& check = scene.checks[index]; - if (check.x < 0 || check.y < 0 || check.x >= surface.width || check.y >= surface.height) { - std::printf("FAIL %s scene=%s (%d,%d) lies outside the %dx%d image %s\n", source_label, - scene.name, check.x, check.y, surface.width, surface.height, check.why); - ++tally.failed; - continue; - } - - const uint8_t* actual = surface.At(check.x, check.y); - const bool matches = actual[0] == check.r && actual[1] == check.g && - actual[2] == check.b && actual[3] == check.a; - std::printf("%s %s scene=%s (%d,%d) expected %u,%u,%u,%u actual %u,%u,%u,%u %s\n", - matches ? "PASS" : "FAIL", source_label, scene.name, check.x, check.y, - static_cast(check.r), static_cast(check.g), - static_cast(check.b), static_cast(check.a), - static_cast(actual[0]), static_cast(actual[1]), - static_cast(actual[2]), static_cast(actual[3]), check.why); - if (matches) { - ++tally.passed; - } else { - ++tally.failed; - } - } - return tally; -} diff --git a/tools/conformance/native/src/verify.h b/tools/conformance/native/src/verify.h deleted file mode 100644 index 7fa8e9e18..000000000 --- a/tools/conformance/native/src/verify.h +++ /dev/null @@ -1,17 +0,0 @@ -#pragma once - -#include "pixel_surface.h" -#include "scenes.h" - -// How many of a scene's contract checks matched one pixel surface. Kept per source so -// the summary can say which path failed: rendering or PNG encoding. -struct CheckTally { - int passed = 0; - int failed = 0; -}; - -// Compares every conform::PixelCheck of one scene against the surface and prints one -// PASS/FAIL line per check with the scene, coordinate, expected and actual pixel. Does -// not stop at the first failure, and does not modify the surface. -CheckTally VerifyChecks(const conform::Scene& scene, const PixelSurface& surface, - const char* source_label); diff --git a/tools/conformance/spec/scenes.h b/tools/conformance/spec/scenes.h deleted file mode 100644 index c392b1fcd..000000000 --- a/tools/conformance/spec/scenes.h +++ /dev/null @@ -1,245 +0,0 @@ -// Conformance scene contract — the single source of truth shared by the native D3D12 -// reference renderer, the Vulkan-shim renderer, and the image diff tool. -// -// Every scene is deterministic and analytically checkable: it names the exact pixels -// that must come out, so a mismatch is a bug with a coordinate, not a vague "the -// picture looks off". Where a value could be read two ways, this header states the -// reading; if an implementer has to guess, that is a defect in this header. -// -// Conventions, stated once and assumed everywhere below: -// * clip space is D3D style: x and y in -1..1, z in 0..1, w = 1.0. Depth == z. -// There is no GL-style (z+1)/2 remap anywhere in this suite. -// * image row 0 is the TOP of the image and corresponds to NDC y = +1. -// Byte order in memory is R, G, B, A. -// * the render target is R8G8B8A8_UNORM, so writing v in 0..1 stores round(v * 255) -// and reading gives the same 8-bit value back. No sRGB conversion, no dithering. -#pragma once - -#include - -namespace conform { - -constexpr int kSceneWidth = 256; -constexpr int kSceneHeight = 256; - -// Clear colour, in 8-bit UNORM, shared by every scene. -constexpr uint8_t kClearR = 10; -constexpr uint8_t kClearG = 20; -constexpr uint8_t kClearB = 30; -constexpr uint8_t kClearA = 255; - -// Pixel value that the clear colour writes, restated for checks and comments. -inline constexpr uint8_t kClearBytes[4] = {kClearR, kClearG, kClearB, kClearA}; - -// --------------------------------------------------------------------------------- -// Baseline pipeline state. Every scene starts from this and only the listed scene -// differences change. A zero-initialised D3D12_RASTERIZER_DESC is invalid, and a zero -// sample mask draws nothing, so this table is not optional documentation: it is the -// state an implementer must set. -// --------------------------------------------------------------------------------- -// -// topology D3D12_PRIMITIVE_TOPOLOGY_TRIANGLELIST (never a strip: a strip -// would bridge the depth-order quads with phantom triangles) -// cull mode D3D12_CULL_MODE_NONE, fill SOLID, FrontCounterClockwise FALSE -// sample count 1, sample mask 0xFFFFFFFF, no MSAA -// render target R8G8B8A8_UNORM, RenderTargetWriteMask = ALL (0x0F) -// viewport (0, 0, 256, 256), depth 0..1 -// scissor the full 256x256 target unless the scene says otherwise; -// scissor is always enabled in D3D12, so it must be set explicitly -// root signature one root CBV at b0, shader visibility ALL, space 0, -// flags = ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT (vertex-colour scenes -// also bind a vertex buffer and use the same signature unused) -// constant buffer a single float4 at byte offset 0, set to tint/255.0f -// depth only the depth_order scene binds a depth target, and it binds -// D32_FLOAT, clears to 1.0, DepthFunc LESS, DepthWriteMask ALL, -// stencil disabled. Every other scene binds no DSV. -// vertex format ClipVertex as declared below, stride sizeof(ClipVertex) -// index format R16_UINT for every indexed draw -// -// Each scene clears the render target to the clear colour before it draws, so state -// left behind by a previous scene can never explain a pass. - -// A vertex in clip space with a straight (non-premultiplied) colour. -// w is 1.0 everywhere, so z is the depth value written to SV_Position. -struct ClipVertex { - float x; - float y; - float z; - uint8_t r; - uint8_t g; - uint8_t b; - uint8_t a; -}; - -// depth_order: the NEAR green quad is drawn FIRST, the FAR red quad SECOND. -// -// This order is deliberate and load-bearing. At the overlap, the red quad is drawn -// after the green one, so the only reason green survives is that the depth test rejects -// red (0.75 vs 0.25, LESS). A shim that ignores the depth target paints red over green -// and fails the check at (128,128). -// -// Green spans x -0.95..0.15, red spans x -0.95..0.95, so the right-hand side of the -// image shows red with nothing over it. -inline constexpr ClipVertex kDepthOrderVertices[] = { - // near quad: green, z = 0.25, drawn first - {-0.95f, -0.95f, 0.25f, 40, 160, 90, 255}, - {-0.95f, 0.95f, 0.25f, 40, 160, 90, 255}, - { 0.15f, 0.95f, 0.25f, 40, 160, 90, 255}, - { 0.15f, -0.95f, 0.25f, 40, 160, 90, 255}, - // far quad: red, z = 0.75, drawn second - {-0.95f, -0.95f, 0.75f, 220, 40, 40, 255}, - {-0.95f, 0.95f, 0.75f, 220, 40, 40, 255}, - { 0.95f, 0.95f, 0.75f, 220, 40, 40, 255}, - { 0.95f, -0.95f, 0.75f, 220, 40, 40, 255}, -}; -// Two triangles per quad, both wound counter-clockwise in NDC, which is irrelevant -// while culling is NONE but stated so the geometry has one meaning. -inline constexpr uint16_t kDepthOrderIndices[] = { - 0, 1, 2, 0, 2, 3, // near green quad - 4, 5, 6, 4, 6, 7, // far red quad -}; - -// indexed: six vertices stored in an order that is NOT the draw order, addressed by a -// non-identity index list. A program that ignores the index buffer and draws the vertex -// buffer in order produces the wrong triangles, which is the failure this scene exists -// to catch. -// -// Vertex layout in memory (deliberately shuffled): -// slot 0 = left-bottom, slot 1 = right-top, slot 2 = left-top, -// slot 3 = right-bottom, slot 4 = right-top, slot 5 = left-bottom -inline constexpr ClipVertex kIndexedVertices[] = { - {-0.60f, -0.60f, 0.50f, 240, 200, 40, 255}, // slot 0: left triangle, bottom left - { 0.60f, -0.60f, 0.50f, 40, 120, 240, 255}, // slot 1: right triangle, bottom right - {-0.60f, 0.60f, 0.50f, 240, 200, 40, 255}, // slot 2: left triangle, top left - { 0.10f, 0.60f, 0.50f, 40, 120, 240, 255}, // slot 3: right triangle, top left - { 0.10f, -0.60f, 0.50f, 40, 120, 240, 255}, // slot 4: right triangle, bottom left - {-0.10f, -0.60f, 0.50f, 240, 200, 40, 255}, // slot 5: left triangle, bottom right -}; -inline constexpr uint16_t kIndexedIndices[] = { - 0, 2, 5, // left triangle (slots 0, 2, 5) - 1, 3, 4, // right triangle (slots 1, 3, 4) -}; - -// Scissor rectangle for the scissor scene: D3D12_RECT{left, top, right, bottom} with -// right and bottom EXCLUSIVE. Deliberately asymmetric in both axes so that reading the -// rectangle as (x, y, width, height) - the usual mistake - fails the checks. -constexpr int kScissorLeft = 48; -constexpr int kScissorTop = 32; -constexpr int kScissorRight = 176; -constexpr int kScissorBottom = 96; - -struct PixelCheck { - int x; - int y; - uint8_t r; - uint8_t g; - uint8_t b; - uint8_t a; - const char* why; // what this pixel proves, phrased as a claim -}; - -enum class SceneKind { - Clear, // clear only, no draw - Fullscreen, // one oversized triangle, colour from the constant buffer at b0 - DepthOrder, // kDepthOrderVertices / kDepthOrderIndices, depth target bound - Scissor, // oversized triangle restricted to the scissor rectangle - Blend, // oversized triangle, source alpha 0.5, SRC_ALPHA / INV_SRC_ALPHA - Indexed, // kIndexedVertices / kIndexedIndices -}; - -struct Scene { - const char* name; // also the PNG name, without extension - SceneKind kind; - const char* proves; // one sentence: the failure this scene would catch - - // Constant-buffer value for the scenes that read it, in 8-bit UNORM. - // Each scene uses a distinct colour so that state leaking from a previous scene - // changes the image instead of hiding behind an identical tint. - uint8_t tintR; - uint8_t tintG; - uint8_t tintB; - uint8_t tintA; - - int checkCount; - PixelCheck checks[5]; -}; - -// Blend arithmetic, stated so there is nothing to guess: -// source colour (200, 30, 60) with source alpha 0.5, over the clear colour: -// colour: SRC_ALPHA, INV_SRC_ALPHA, ADD -// alpha: ONE, INV_SRC_ALPHA, ADD -> 1.0*0.5 + 0.5*1.0 = 1.0 -> 255 -// 0.5*200 + 0.5*10 = 105, 0.5*30 + 0.5*20 = 25, 0.5*60 + 0.5*30 = 45 -// With the source alpha quantised to either 127 or 128 the result is still 105/25/45, -// so no tolerance is needed. -inline constexpr Scene kScenes[] = { - { - "clear", SceneKind::Clear, - "render target creation, the clear value and the readback path are wired up", - 10, 20, 30, 255, // tint unused - 3, - { - {0, 0, kClearR, kClearG, kClearB, kClearA, "top-left is the clear colour"}, - {128, 128, kClearR, kClearG, kClearB, kClearA, "centre is the clear colour"}, - {255, 255, kClearR, kClearG, kClearB, kClearA, "bottom-right is the clear colour"}, - }, - }, - { - "fullscreen", SceneKind::Fullscreen, - "vertex shader runs, a pipeline binds, and one triangle covers every pixel", - 200, 30, 60, 255, - 3, - { - {128, 128, 200, 30, 60, 255, "centre is the constant-buffer colour"}, - {8, 8, 200, 30, 60, 255, "top-left corner is covered: the triangle is oversized"}, - {247, 247, 200, 30, 60, 255, "bottom-right corner is covered too"}, - }, - }, - { - "depth_order", SceneKind::DepthOrder, - "the depth test rejects a later draw that is behind: without it this scene is red", - 0, 0, 0, 255, // tint unused - 2, - { - {128, 128, 40, 160, 90, 255, "overlap keeps the near quad drawn first (green, z=0.25) although red (z=0.75) was drawn after it"}, - {224, 128, 220, 40, 40, 255, "uncovered right side shows the far quad (red)"}, - }, - }, - { - "scissor", SceneKind::Scissor, - "scissor state is honoured: draws are clipped at the rectangle, not merely darkened", - 70, 140, 210, 255, - 5, - { - {112, 64, 70, 140, 210, 255, "inside the rectangle the draw lands"}, - {40, 64, kClearR, kClearG, kClearB, kClearA, "left of the rectangle stays clear"}, - {180, 64, kClearR, kClearG, kClearB, kClearA, "right of the rectangle stays clear"}, - {112, 24, kClearR, kClearG, kClearB, kClearA, "above the rectangle stays clear"}, - {112, 104, kClearR, kClearG, kClearB, kClearA, "below the rectangle stays clear"}, - }, - }, - { - "blend", SceneKind::Blend, - "blend state is applied: 50% source over the clear colour, not a replacement", - 200, 30, 60, 128, // 128/255 ~= 0.5, which rounds to the same result as 127 - 2, - { - {128, 128, 105, 25, 45, 255, "0.5*(200,30,60) + 0.5*(10,20,30) = (105,25,45)"}, - {8, 8, 105, 25, 45, 255, "blending applies everywhere the triangle covers"}, - }, - }, - { - "indexed", SceneKind::Indexed, - "the index buffer is read: a program that ignores it draws different triangles", - 0, 0, 0, 255, // tint unused - 3, - { - {80, 200, 240, 200, 40, 255, "left triangle, from index triple 0,2,5"}, - {176, 200, 40, 120, 240, 255, "right triangle, from index triple 1,3,4"}, - {128, 240, kClearR, kClearG, kClearB, kClearA, "the gap between the two triangles stays clear"}, - }, - }, -}; - -inline constexpr int kSceneCount = static_cast(sizeof(kScenes) / sizeof(kScenes[0])); - -} // namespace conform diff --git a/tools/conformance/spec/shaders/fullscreen_color.hlsl b/tools/conformance/spec/shaders/fullscreen_color.hlsl deleted file mode 100644 index ff6a1381e..000000000 --- a/tools/conformance/spec/shaders/fullscreen_color.hlsl +++ /dev/null @@ -1,35 +0,0 @@ -// Fullscreen triangle, one colour from a constant buffer. -// Used by the clear, fullscreen, scissor, blend and constant-buffer scenes: they -// differ only in pipeline state and the value in the CB, so one shader pair covers -// them and a failure points at state, not at shader compilation. - -cbuffer SceneConstants : register(b0) -{ - float4 tint; // straight (non-premultiplied) RGBA in 0..1 -}; - -struct VsOut -{ - float4 position : SV_Position; -}; - -VsOut VSMain(uint vertexId : SV_VertexID) -{ - // One oversized triangle covering clip space; no vertex buffer needed. - // id 0 -> (-1,-1) id 1 -> (-1, 3) id 2 -> (3,-1) - float2 corners[3] = - { - float2(-1.0, -1.0), - float2(-1.0, 3.0), - float2( 3.0, -1.0), - }; - - VsOut output; - output.position = float4(corners[vertexId], 0.0, 1.0); - return output; -} - -float4 PSMain(VsOut input) : SV_Target -{ - return tint; -} diff --git a/tools/conformance/spec/shaders/vertex_color.hlsl b/tools/conformance/spec/shaders/vertex_color.hlsl deleted file mode 100644 index 64be2a6af..000000000 --- a/tools/conformance/spec/shaders/vertex_color.hlsl +++ /dev/null @@ -1,29 +0,0 @@ -// Clip-space position with a per-vertex colour. -// Used by the depth-order and indexed scenes: the two quads/triangles differ in -// depth or index order, and the colour comes from the vertex data so a wrong draw -// is visible as the wrong colour rather than the wrong shade. - -struct VsIn -{ - float3 position : POSITION; // already in clip space: xy in -1..1, z in 0..1 - float4 color : COLOR; -}; - -struct VsOut -{ - float4 position : SV_Position; - float4 color : COLOR; -}; - -VsOut VSMain(VsIn input) -{ - VsOut output; - output.position = float4(input.position, 1.0); - output.color = input.color; - return output; -} - -float4 PSMain(VsOut input) : SV_Target -{ - return input.color; -} diff --git a/tools/content_definitions.py b/tools/content_definitions.py deleted file mode 100644 index 10070157d..000000000 --- a/tools/content_definitions.py +++ /dev/null @@ -1,242 +0,0 @@ -"""Read local content-definition XML (ASSET-149), without resolving references. - -Accepts XML files or rpf9_carve directories. The CLI prints aggregate counts only. -The Python API returns ordered records containing local game data: never publish -those records. Archive offsets identify recovered spans, not named RPF entries. -Usage: `python -I tools/content_definitions.py --help` lists the options. -""" -from __future__ import annotations - -import argparse -from dataclasses import dataclass -import json -import os -import sys -import xml.etree.ElementTree as ET - -ROOTS = { - "CDataFileMgr__ContentChangeSetDef": "change_set", - "CDataFileMgr__ContentDef": "content", - "SSetupData": "setup", -} - - -class ContentError(ValueError): - """Invalid content XML; messages never include input values or paths.""" - - -class _OtherRoot(ContentError): - """Well-formed XML outside the supported content schemas.""" - - -@dataclass(frozen=True) -class Record: - tag: str - attributes: tuple[tuple[str, str], ...] - text: str - tail: str - children: tuple[Record, ...] - - def select(self, *path: str) -> tuple[Record, ...]: - """Select ordered direct-child paths; duplicates are not collapsed.""" - nodes = (self,) - for tag in path: - nodes = tuple(child for node in nodes for child in node.children if child.tag == tag) - return nodes - - def scalar(self, tag: str) -> str | None: - """One text/value field, untyped; absent is None, explicitly empty is ''.""" - fields = self.select(tag) - if not fields: - return None - if len(fields) != 1 or fields[0].children: - raise ContentError("ambiguous scalar field") - field = fields[0] - text = field.text.strip() - attrs = dict(field.attributes) - if "value" in attrs: - if text: - raise ContentError("scalar has both text and value attribute") - return attrs["value"] - return text - - -@dataclass(frozen=True) -class FileEntry: - filename: str | None - file_type: str | None - record: Record - - -@dataclass(frozen=True) -class ContentDocument: - kind: str - root: Record - - @property - def files(self) -> tuple[FileEntry, ...]: - if self.kind != "change_set": - return () - return tuple(FileEntry(item.scalar("filename"), item.scalar("fileType"), item) - for item in self.root.select("fileList", "Item")) - - @property - def included_changesets(self) -> tuple[Record, ...]: - return self.root.select("includedChangesets", "Item") if self.kind == "content" else () - - @property - def included_sets(self) -> tuple[Record, ...]: - return self.root.select("includedSets", "Item") if self.kind == "content" else () - - @property - def change_set_groups(self) -> tuple[Record, ...]: - return self.root.select("contentChangeSetGroups", "Item") if self.kind == "setup" else () - - -class _Builder(ET.TreeBuilder): - def __init__(self): - super().__init__() - self.depth = 0 - - def start(self, tag, attrs): - self.depth += 1 - if self.depth > 128: - raise ContentError("XML nesting exceeds 128 elements") - return super().start(tag, attrs) - - def end(self, tag): - self.depth -= 1 - return super().end(tag) - - def doctype(self, name, pubid, system): - raise ContentError("DTD declarations are unsupported") - - -def parse_content(chunks, *, max_bytes: int = 64 << 20) -> ContentDocument: - """Parse one document from byte chunks. No partially parsed result escapes. - - Preserves all elements, attributes, text and tails (after XML normalization), - including unknown fields. Comments/PIs are not configuration fields. This - reader retains a whole document, with a configurable byte limit, not a whole - archive. No path, macro, hash or include is resolved and no numeric conversion - is inferred. Namespaced roots are not silently treated as the known schema. - """ - if max_bytes < 1: - raise ValueError("max_bytes must be positive") - parser = ET.XMLParser(target=_Builder()) - total = 0 - try: - for chunk in chunks: - if not isinstance(chunk, bytes): - raise TypeError("content input must contain byte chunks") - total += len(chunk) - if total > max_bytes: - raise ContentError("XML exceeds byte limit") - parser.feed(chunk) - element = parser.close() - except ContentError: - raise - except (ET.ParseError, LookupError, ValueError): - raise ContentError("malformed or unsupported XML") from None - if element.tag not in ROOTS: - raise _OtherRoot("unsupported content root") - - def record(el): - return Record(el.tag, tuple(el.attrib.items()), el.text or "", el.tail or "", - tuple(record(child) for child in el)) - - result = ContentDocument(ROOTS[element.tag], record(element)) - # Validate the known scalar fields exposed by the file-entry convenience API. - result.files - for item in result.included_changesets: - item.scalar("loadPath") - return result - - -def file_chunks(stream): - while chunk := stream.read(65536): - yield chunk - - -def carve_documents(directory): - """Yield (offset, stored size, document) for XML payloads in an existing carve. - - Existing grouping determines spans; it does not recover encrypted TOC names. - Strict reads prevent missing .bin files falling back to index header bytes. - Non-content XML yields None; malformed content raises ContentError. - """ - tools_dir = os.path.dirname(os.path.abspath(__file__)) - if tools_dir not in sys.path: - sys.path.insert(0, tools_dir) - import gamedata_index as gi - - class Source(gi.DirectorySource): - def read(self, row): - ext = ".bk2" if row.get("type") == "bink2" else ".bin" - with open(os.path.join(self.directory, f'{row["off"]:012x}{ext}'), "rb") as stream: - # Grouping only needs the Bink signature, not the video payload. - return stream.read(64) if ext == ".bk2" else stream.read() - - source = Source(directory) - positions = {r["off"]: i for i, r in enumerate(source.rows)} - for row in gi.build_rows(source.rows, source): - if row["type"] != "xml": - continue - if row["root"] not in ROOTS: - yield row["offset"], row["stored"], None - continue - first = positions[row["offset"]] - group = source.rows[first:first + row["chunks"]] - yield row["offset"], row["stored"], parse_content(source.read(r) for r in group) - - -def main() -> int: - cli = argparse.ArgumentParser(description=__doc__) - cli.add_argument("inputs", nargs="+", help="local XML files or carve directories") - args = cli.parse_args() - counts = dict(documents=0, change_sets=0, contents=0, setups=0, files=0, - included_changesets=0, included_sets=0, groups=0, - other_xml=0, failed_inputs=0) - - def add(doc): - if doc is None: - counts["other_xml"] += 1 - return - counts["documents"] += 1 - counts[{"change_set": "change_sets", "content": "contents", "setup": "setups"}[doc.kind]] += 1 - counts["files"] += len(doc.files) - counts["included_changesets"] += len(doc.included_changesets) - counts["included_sets"] += len(doc.included_sets) - counts["groups"] += len(doc.change_set_groups) - - status = 0 - for path in args.inputs: - if not os.path.exists(path): - print(f"ERROR: {path}: does not exist", file=sys.stderr) - counts["failed_inputs"] += 1 - status = 2 - continue - try: - if os.path.isdir(path): - for _, _, doc in carve_documents(path): - add(doc) - else: - with open(path, "rb") as stream: - try: - doc = parse_content(file_chunks(stream)) - except _OtherRoot: - doc = None - add(doc) - except (OSError, ContentError, ValueError, KeyError, TypeError): - counts["failed_inputs"] += 1 - status = max(status, 1) - print(json.dumps(counts, sort_keys=True)) - return status - - -if __name__ == "__main__": - try: # a redirected stdout is strict ANSI code page under -I; write '?' for what it cannot encode - sys.stdout.reconfigure(errors="replace") - except (AttributeError, ValueError, OSError): - pass - raise SystemExit(main()) diff --git a/tools/cpu_feature_scan.py b/tools/cpu_feature_scan.py deleted file mode 100644 index 432f68cdc..000000000 --- a/tools/cpu_feature_scan.py +++ /dev/null @@ -1,331 +0,0 @@ -"""Which CPU instructions an x64 image needs, and which of them a desktop CPU may not run. - -Usage: - python -I tools/cpu_feature_scan.py [--sites] [--json] - python -I tools/cpu_feature_scan.py [--image ] [--base 0x140000000] [--sites] [--json] - -The Xbox Series CPU is an AMD Zen 2. The runtime maps the game's code and runs it as-is (docs/design.md, "Why a -loader before a recompiler"), so an instruction the host CPU lacks raises #UD (STATUS_ILLEGAL_INSTRUCTION) where it -is reached, and a privileged one faults. This tool lists those instructions: it streams MSVC -`dumpbin /disasm:nobytes` (as tools/inline_scan.py does), names the CPUID feature or privilege class of each -instruction, and counts them per feature. Each feature has one of these classes: - - amd-only no Intel CPU has it (SSE4a, CLZERO, MONITORX/MWAITX, RDPRU, XOP, FMA4, TBM): #UD on every - Intel host - newer-intel Zen 2 has it, but Intel CPUs only from a later generation on (CLWB, SHA, RDPID): #UD on older - Intel hosts, such as the client Skylake to Comet Lake parts - not-zen2 the console CPU does not have it (AVX-512, VAES, VPCLMULQDQ, WAITPKG, ...): a hit is most likely - data that the linear disassembly read as code - privileged ring 0 only (port I/O, CLI/HLT, MSRs, control registers, XSETBV, MONITOR/MWAIT, ...): faults in user - mode on every PC - kernel-call SYSCALL, SYSENTER and INT n other than the debug/assert/fast-fail vectors: a direct call into the - console kernel - host-query CPUID, XGETBV, RDTSC(P), RDPID: run on every host but answer with the host's values - baseline a feature every x86-64 PC the runtime targets has (AVX2, FMA, BMI, AES, ...): counted, not flagged - -The image's `.pdata` table (read from the PE, or from `--image` for a listing) splits each count into hits inside -a function's range and hits elsewhere. A linear disassembly also decodes padding, jump tables and other data in the -code sections, so a hit outside every `.pdata` range is often not code; but a leaf function that does not touch the -stack has no `.pdata` entry either, so read those sites by hand (`--sites` prints their RVAs). - -Nothing is executed. The output is counts, feature names and RVAs, no code bytes. An input with no instructions in -it exits 2 instead of reporting zero hits. Standard library only. -""" -from __future__ import annotations - -import argparse -import bisect -import json -import os -import re -import struct -import sys -from collections import Counter, defaultdict -from pathlib import Path - -sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) -import inline_scan # noqa: E402 -from pe_inspect import DIR_EXCEPTION, PeFormatError, PeImage # noqa: E402 - -FLAGGED = ("amd-only", "newer-intel", "not-zen2", "privileged", "kernel-call") -CLASSES = FLAGGED + ("host-query", "baseline") - -# feature -> (class, what a host without it does) -FEATURES = { - "SSE4A": ("amd-only", "#UD on every Intel CPU"), - "CLZERO": ("amd-only", "#UD on every Intel CPU"), - "MONITORX": ("amd-only", "#UD on every Intel CPU"), - "RDPRU": ("amd-only", "#UD on every Intel CPU; Zen 2 and later"), - "XOP": ("amd-only", "#UD on every Intel CPU and on Zen"), - "FMA4": ("amd-only", "#UD on every Intel CPU; not reported by Zen"), - "TBM": ("amd-only", "#UD on every Intel CPU and on Zen"), - "3DNOW": ("amd-only", "#UD on every Intel CPU and on Zen"), - "CLWB": ("newer-intel", "#UD on Intel client CPUs before Ice Lake / Tiger Lake"), - "SHA": ("newer-intel", "#UD on Intel client CPUs before Ice Lake (Goldmont Atoms have it)"), - "RDPID": ("newer-intel", "#UD on Intel CPUs before Ice Lake"), - "AVX512": ("not-zen2", "not on the console CPU"), - "VAES": ("not-zen2", "not on the console CPU (Zen 3 and later)"), - "VPCLMULQDQ": ("not-zen2", "not on the console CPU (Zen 3 and later)"), - "WAITPKG": ("not-zen2", "Intel only"), - "MOVDIR": ("not-zen2", "Intel only"), - "SERIALIZE": ("not-zen2", "Intel only"), - "RTM": ("not-zen2", "Intel only"), - "GFNI": ("not-zen2", "not on the console CPU"), - "PKU": ("not-zen2", "not on the console CPU (Zen 3 and later)"), - "PORT-IO": ("privileged", "faults in user mode"), - "SYSTEM": ("privileged", "faults in user mode"), - "MONITOR": ("privileged", "faults in user mode on Windows"), - "XSETBV": ("privileged", "faults in user mode"), - "SYSCALL": ("kernel-call", "enters the host kernel with a console service number"), - "INT": ("kernel-call", "a software interrupt Windows does not serve for the title"), - "CPUID": ("host-query", "answers with the host CPU's vendor, family and features"), - "XGETBV": ("host-query", "answers with the host OS's enabled state"), - "RDTSC": ("host-query", "counts at the host's TSC rate"), - "AVX": ("baseline", ""), "AVX2": ("baseline", ""), "FMA": ("baseline", ""), "F16C": ("baseline", ""), - "BMI1": ("baseline", ""), "BMI2": ("baseline", ""), "LZCNT": ("baseline", ""), "POPCNT": ("baseline", ""), - "ADX": ("baseline", ""), "MOVBE": ("baseline", ""), "AES": ("baseline", ""), "PCLMULQDQ": ("baseline", ""), - "RDRAND": ("baseline", ""), "RDSEED": ("baseline", ""), "CLFLUSHOPT": ("baseline", ""), - "XSAVE": ("baseline", ""), "FSGSBASE": ("baseline", ""), "CX16": ("baseline", ""), - "PREFETCHW": ("baseline", ""), "SSE4.2": ("baseline", ""), -} - -# Exact mnemonics (dumpbin spelling, lower case) -> feature. -MNEMONICS: dict[str, str] = {} - - -def _names(feature: str, *names: str): - for name in names: - MNEMONICS[name] = feature - - -_names("SSE4A", "extrq", "insertq", "movntsd", "movntss") -_names("CLZERO", "clzero") -_names("MONITORX", "monitorx", "mwaitx") -_names("RDPRU", "rdpru") -_names("XOP", "vpperm", "vpcmov", "vprotb", "vprotw", "vprotd", "vprotq", "vpshab", "vpshaw", "vpshad", "vpshaq", - "vpshlb", "vpshlw", "vpshld", "vpshlq", "vfrczps", "vfrczpd", "vfrczss", "vfrczsd", "vpermil2ps", "vpermil2pd", - "vphaddbw", "vphaddbd", "vphaddbq", "vphaddwd", "vphaddwq", "vphadddq", "vphaddubw", "vphaddubd", - "vphaddubq", "vphadduwd", "vphadduwq", "vphaddudq", "vphsubbw", "vphsubwd", "vphsubdq", "vpmacssww", - "vpmacsww", "vpmacsswd", "vpmacswd", "vpmacssdd", "vpmacsdd", "vpmacssdql", "vpmacsdql", "vpmacssdqh", - "vpmacsdqh", "vpmadcsswd", "vpmadcswd", "vpcomb", "vpcomw", "vpcomd", "vpcomq", "vpcomub", "vpcomuw", - "vpcomud", "vpcomuq") -_names("FMA4", *(f"{op}{t}" for op in ("vfmadd", "vfmsub", "vfnmadd", "vfnmsub") for t in ("ps", "pd", "ss", "sd")), - "vfmaddsubps", "vfmaddsubpd", "vfmsubaddps", "vfmsubaddpd") -_names("TBM", "blcfill", "blci", "blcic", "blcmsk", "blcs", "blsfill", "blsic", "t1mskc", "tzmsk") -_names("3DNOW", "femms", "pavgusb", "pf2id", "pfacc", "pfadd", "pfcmpeq", "pfcmpge", "pfcmpgt", "pfmax", "pfmin", - "pfmul", "pfrcp", "pfrcpit1", "pfrcpit2", "pfrsqit1", "pfrsqrt", "pfsub", "pfsubr", "pi2fd", "pmulhrw", - "pf2iw", "pfnacc", "pfpnacc", "pi2fw", "pswapd") -_names("CLWB", "clwb") -_names("SHA", "sha1rnds4", "sha1nexte", "sha1msg1", "sha1msg2", "sha256rnds2", "sha256msg1", "sha256msg2") -_names("RDPID", "rdpid") -_names("WAITPKG", "umonitor", "umwait", "tpause") -_names("MOVDIR", "movdiri", "movdir64b", "enqcmd", "enqcmds") -_names("SERIALIZE", "serialize") -_names("RTM", "xbegin", "xend", "xabort", "xtest") -_names("GFNI", "gf2p8affineqb", "gf2p8affineinvqb", "gf2p8mulb", "vgf2p8affineqb", "vgf2p8affineinvqb", - "vgf2p8mulb") -_names("PKU", "rdpkru", "wrpkru") -_names("AVX512", "kmovb", "kmovw", "kmovd", "kmovq", "kandw", "korw", "kxorw", "knotw", "kortestw", "kshiftlw", - "kshiftrw", "vpternlogd", "vpternlogq", "vpcompressd", "vpcompressq", "vpexpandd", "vpexpandq", - "vpermi2d", "vpermi2q", "vpermi2ps", "vpermi2pd", "vpermt2d", "vpermt2q", "vpermt2ps", "vpermt2pd") -_names("PORT-IO", "in", "out", "ins", "insb", "insw", "insd", "outs", "outsb", "outsw", "outsd") -_names("SYSTEM", "cli", "sti", "hlt", "rdmsr", "wrmsr", "rdpmc", "invd", "wbinvd", "wbnoinvd", "invlpg", "invpcid", - "lgdt", "lidt", "lldt", "ltr", "clts", "swapgs", "sysret", "sysretq", "sysexit", "lmsw", - "invlpga", "vmrun", "vmload", "vmsave", "stgi", "clgi", "skinit", "vmcall", "vmmcall", "rsm") -_names("MONITOR", "monitor", "mwait") -_names("XSETBV", "xsetbv") -_names("SYSCALL", "syscall", "sysenter") -_names("AVX", "vzeroupper", "vzeroall") -_names("CPUID", "cpuid") -_names("XGETBV", "xgetbv") -_names("RDTSC", "rdtsc", "rdtscp") -_names("F16C", "vcvtph2ps", "vcvtps2ph") -_names("BMI1", "andn", "bextr", "blsi", "blsmsk", "blsr", "tzcnt") -_names("BMI2", "bzhi", "mulx", "pdep", "pext", "rorx", "sarx", "shlx", "shrx") -_names("LZCNT", "lzcnt") -_names("POPCNT", "popcnt") -_names("ADX", "adcx", "adox") -_names("MOVBE", "movbe") -_names("RDRAND", "rdrand") -_names("RDSEED", "rdseed") -_names("CLFLUSHOPT", "clflushopt") -_names("XSAVE", "xsave", "xsave64", "xsaveopt", "xsaveopt64", "xsavec", "xsavec64", "xsaves", "xsaves64", - "xrstor", "xrstor64", "xrstors", "xrstors64") -_names("FSGSBASE", "rdfsbase", "rdgsbase", "wrfsbase", "wrgsbase") -_names("CX16", "cmpxchg16b") -_names("PREFETCHW", "prefetchw") -_names("SSE4.2", "crc32", "pcmpestri", "pcmpestrm", "pcmpistri", "pcmpistrm", "vpcmpestri", "vpcmpestrm", - "vpcmpistri", "vpcmpistrm") -_names("AVX2", "vpbroadcastb", "vpbroadcastw", "vpbroadcastd", "vpbroadcastq", "vbroadcasti128", "vextracti128", - "vinserti128", "vperm2i128", "vpermd", "vpermq", "vpermps", "vpermpd", "vpmaskmovd", "vpmaskmovq", - "vpsllvd", "vpsllvq", "vpsrlvd", "vpsrlvq", "vpsravd", "vpgatherdd", "vpgatherdq", "vpgatherqd", - "vpgatherqq", "vgatherdps", "vgatherdpd", "vgatherqps", "vgatherqpd", "vpblendd") - -PREFIXES = {"lock", "rep", "repe", "repz", "repne", "repnz", "xacquire", "xrelease", "bnd", "notrack"} -ALLOWED_INT = {3, 0x29, 0x2C, 0x2D} # breakpoint, __fastfail, __assert, debug service: Windows serves them -FMA3 = re.compile(r"^vf(?:n?m(?:add|sub)|maddsub|msubadd)(?:132|213|231)(?:ps|pd|ss|sd)$") -AES = {"aesenc", "aesenclast", "aesdec", "aesdeclast", "aesimc", "aeskeygenassist"} -CONTROL_REG = re.compile(r"\b[cd]r\d+\b") -IMMEDIATE = re.compile(r"^([0-9A-F]+)h?$") -ZMM = re.compile(r"\bzmm\d+\b|\{k\d\}") -YMM = re.compile(r"\bymm\d+\b") - - -def classify(mnem: str, ops: str) -> str | None: - """The feature (a FEATURES key) one dumpbin instruction needs, or None for the plain x86-64 baseline.""" - while mnem in PREFIXES and ops: - mnem, _, ops = ops.partition(" ") - ops = ops.strip() - if mnem == "int": - m = IMMEDIATE.match(ops.strip()) - return None if m and int(m.group(1), 16) in ALLOWED_INT else "INT" - if mnem == "int1" or mnem == "into": - return "INT" - if mnem == "mov" and CONTROL_REG.search(ops): - return "SYSTEM" - if ZMM.search(ops): - return "AVX512" - base = mnem[1:] if mnem.startswith("v") else mnem - if base in AES: - return "VAES" if mnem.startswith("v") and YMM.search(ops) else "AES" - if base == "pclmulqdq": - return "VPCLMULQDQ" if mnem.startswith("v") and YMM.search(ops) else "PCLMULQDQ" - if mnem in MNEMONICS: - return MNEMONICS[mnem] - if FMA3.match(mnem): - return "FMA" - if mnem.startswith("vp") and YMM.search(ops): - return "AVX2" # a 256-bit integer operation - if mnem.startswith("v") and (YMM.search(ops) or "xmm" in ops): - return "AVX" - return None - - -class Functions: - """The image's .pdata ranges, as sorted, merged [begin, end) RVA pairs.""" - - def __init__(self, ranges): - merged = [] - for begin, end in sorted(r for r in ranges if r[1] > r[0]): - if merged and begin <= merged[-1][1]: - merged[-1][1] = max(merged[-1][1], end) - else: - merged.append([begin, end]) - self.begins = [b for b, _ in merged] - self.ends = [e for _, e in merged] - self.count = len(ranges) - - @classmethod - def from_image(cls, img: PeImage) -> "Functions": - rva, size = img.directory(DIR_EXCEPTION) - at = img.offset(rva, size) if rva and size else None - if at is None: - return cls([]) - return cls([struct.unpack_from(" bool: - i = bisect.bisect_right(self.begins, rva) - 1 - return i >= 0 and rva < self.ends[i] - - -def scan(lines, functions: Functions | None, base: int | None, stats: dict | None = None): - """Yield (feature, rva, in_function) for every instruction that needs a feature. `stats` gets the counts.""" - stats = {} if stats is None else stats - stats.update(instructions=0, in_functions=0) - for addr, mnem, ops in inline_scan.instructions(lines): - if base is None: - base = addr & ~0xFFFFFFF - rva = addr - base - inside = functions.contains(rva) if functions else None - stats["instructions"] += 1 - stats["in_functions"] += bool(inside) - feature = classify(mnem, ops) - if feature: - yield feature, rva, inside - - -def summarize(hits, stats: dict, functions: Functions | None) -> dict: - counts = defaultdict(Counter) - sites = defaultdict(list) - for feature, rva, inside in hits: - where = "unknown" if inside is None else "in_functions" if inside else "elsewhere" - counts[feature][where] += 1 - if FEATURES[feature][0] in FLAGGED: - sites[feature].append({"rva": rva, "in_function": inside}) - report = {"instructions": stats["instructions"], - "pdata_entries": functions.count if functions else None, - "instructions_in_functions": stats["in_functions"] if functions else None, - "features": {}} - order = {c: i for i, c in enumerate(CLASSES)} - for feature in sorted(counts, key=lambda f: (order[FEATURES[f][0]], f)): - cls, note = FEATURES[feature] - c = counts[feature] - report["features"][feature] = {"class": cls, "note": note, "total": sum(c.values()), - "in_functions": c["in_functions"], "elsewhere": c["elsewhere"], - "sites": sites.get(feature, [])} - return report - - -def to_text(report: dict, show_sites: bool) -> str: - out = [f"instructions scanned: {report['instructions']}"] - if report["pdata_entries"] is not None: - out.append(f".pdata entries: {report['pdata_entries']}, instructions inside them: " - f"{report['instructions_in_functions']}") - else: - out.append("no .pdata read (pass --image for a listing): hits are not split by function") - flagged = [f for f, r in report["features"].items() if r["class"] in FLAGGED] - out.append(f"flagged features: {len(flagged)}" + (f" ({', '.join(flagged)})" if flagged else "")) - out.append(f"{'feature':<12} {'class':<12} {'total':>9} {'in .pdata':>9} {'elsewhere':>9} note") - for feature, r in report["features"].items(): - known = report["pdata_entries"] is not None - inside = r["in_functions"] if known else "-" - elsewhere = r["elsewhere"] if known else "-" - out.append(f"{feature:<12} {r['class']:<12} {r['total']:>9} {inside:>9} {elsewhere:>9} {r['note']}") - if show_sites: - for feature, r in report["features"].items(): - for s in r["sites"]: - where = {True: "in .pdata", False: "outside .pdata", None: "?"}[s["in_function"]] - out.append(f" {feature} +0x{s['rva']:x} {where}") - return "\n".join(out) - - -def main(argv=None) -> int: - p = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) - p.add_argument("source", type=Path, help="an x64 PE (disassembled with dumpbin) or a saved dumpbin listing") - p.add_argument("--image", type=Path, help="for a listing: the PE it came from, to read .pdata and the base") - p.add_argument("--base", type=lambda s: int(s, 16), help="image base (default: the PE's, else inferred)") - p.add_argument("--sites", action="store_true", help="print the RVA of every flagged instruction") - p.add_argument("--json", action="store_true", help="print the report as JSON") - args = p.parse_args(argv) - if not args.source.is_file(): - print(f"{args.source} not found", file=sys.stderr) - return 2 - is_image = args.source.suffix.lower() in (".exe", ".dll") - image_path = args.source if is_image else args.image - functions, base = None, args.base - if image_path is not None: - try: - img = PeImage(image_path.read_bytes()) - except (OSError, PeFormatError) as e: - print(f"{image_path}: {e}", file=sys.stderr) - return 2 - functions = Functions.from_image(img) - if base is None: - base = img.image_base - stats = {} - report = summarize(scan(inline_scan.read_lines(args.source), functions, base, stats), stats, functions) - if not stats["instructions"]: - print(f"{args.source}: no instructions found (not a dumpbin listing, or an image without code)", - file=sys.stderr) - return 2 - print(json.dumps(report, indent=1) if args.json else to_text(report, args.sites)) - return 0 - - -if __name__ == "__main__": - try: # a redirected stdout is strict ANSI code page under -I; write '?' for what it cannot encode - sys.stdout.reconfigure(errors="replace") - except (AttributeError, ValueError, OSError): - pass - sys.exit(main()) diff --git a/tools/cpu_ref.py b/tools/cpu_ref.py deleted file mode 100644 index 8a5474c2f..000000000 --- a/tools/cpu_ref.py +++ /dev/null @@ -1,872 +0,0 @@ -"""CPU reference for a small, straight-line RDNA2 subset. - -This is a reference model for differential shader validation, not a recompiler. It executes the -instructions listed below from a listing produced by tools/shader_disasm.py (the same ``.s`` format -that tools/rdna2spirv.py consumes). Anything outside the subset raises Unsupported with the mnemonic -and PC; it is never guessed. - -Model: - * SGPRs are 32-bit wave-uniform values. - * VGPRs are one 32-bit value per lane. - * VCC, EXEC and SCC are modelled; vector writes are masked by EXEC. - * One lane or 64 lanes. One-lane mode is a view of one hardware lane: scalar reads of - exec_lo/exec_hi and writes of the full masks still use the 64-bit wave state. - * Float registers keep raw bits. f32 add/sub/mul use IEEE binary32. FMA is evaluated exactly with - rational arithmetic and rounded once, so it does not inherit a host double-rounding error. - * NaNs are canonicalized to 0x7fc00000. Denormals are preserved. - -Implemented: s_mov_b32, v_mov_b32, v_add_f32, v_sub_f32, v_mul_f32, v_fma_f32, v_cndmask_b32, -v_and_b32, v_or_b32, v_xor_b32, v_lshlrev_b32, v_lshrrev_b32, v_ashrrev_i32, s_add_u32, -s_lshl_b32, s_lshr_b32, s_endpgm. Also the integer/bit VALU block: v_add_nc_u32, v_sub_nc_u32, -v_subrev_nc_u32, v_mul_u32_u24, v_mul_i32_i24, v_mul_lo_u32, v_mul_hi_u32/v_mul_hi_i32, -v_mad_u32_u24/v_mad_i32_i24, v_min_u32/v_max_u32, v_min_i32/v_max_i32, -v_bfe_u32/v_bfe_i32, v_bfi_b32, v_alignbit_b32, v_alignbyte_b32, v_perm_b32 and -v_med3_i32/v_med3_u32. Inline constants and literals for those operands are handled. -``clamp`` is accepted on the f32 ops (NaN -> 0). Registers not initialized by the caller read as -zero, matching the translator's deterministic register arrays. - -Not modelled: branches and loops, memory/LDS/images, wave operations, 16-bit arithmetic, SDWA/DPP, -and any modifier except ``clamp``. An explicit 32-bit SGPR condition on v_cndmask is a 32-bit lane -mask, so lanes 32-63 read zero; VOP2's implicit VCC uses the full 64-bit mask. - -A listing must start with the usual header line (``; name ...``): shader_ir.parse_file treats the -first line as a header and parses tab-indented instruction lines after it. - -API: - run(listing_path, inputs) -> { - "lanes": 1 | 64, - "lane": , - "active": , - "registers": { - "sgpr": {index: u32, ...}, - "vgpr": {index: u32} or {index: [u32, ...]}, # 64-lane mode: one list per VGPR - "vcc": u64, "exec": u64, "scc": 0 | 1, - }, - "steps": int, "pc": int, "halted": bool, - "source": listing name, - } - -inputs: - lanes 1 (default) or 64 - lane hardware lane for one-lane mode (default 0) - sgpr {index: u32} - vgpr {index: u32} or {index: [u32, ...]}; a list must have one entry per lane - vcc u64 lane mask (default 0) - exec u64 lane mask (default all ones) - scc 0 or 1 (default 0) - max_steps instruction issue limit (default 100000) - -The result's register maps contain the registers that were initialized or written. In one-lane mode -a VGPR value is the selected lane's value; VCC/EXEC remain full 64-bit masks. - -CLI: - python -I tools/cpu_ref.py [--lanes 64] [--parse-only] [--json] - python -I tools/cpu_ref.py --sgpr 0=0x3f800000 --vgpr 1=0x40000000 -Usage: `python -I tools/cpu_ref.py --help` lists the options. -""" -import argparse -import json -import math -import os -import struct -import sys -from fractions import Fraction - -sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) -from shader_ir import parse_file # noqa: E402 - -MASK32 = 0xFFFFFFFF -MASK64 = (1 << 64) - 1 -SIGN32 = 0x80000000 -QNAN = 0x7FC00000 -INF = 0x7F800000 - -FLOAT_OPS = {"v_add_f32", "v_sub_f32", "v_mul_f32", "v_fma_f32"} -SUPPORTED_OPS = { - "s_mov_b32", "s_add_u32", "s_lshl_b32", "s_lshr_b32", - "v_mov_b32", "v_cndmask_b32", "v_and_b32", "v_or_b32", "v_xor_b32", - "v_lshlrev_b32", "v_lshrrev_b32", "v_ashrrev_i32", - "v_add_nc_u32", "v_sub_nc_u32", "v_subrev_nc_u32", "v_mul_u32_u24", "v_mul_i32_i24", - "v_mul_lo_u32", "v_mul_hi_u32", "v_mul_hi_i32", "v_mad_u32_u24", "v_mad_i32_i24", - "v_min_u32", "v_max_u32", "v_min_i32", "v_max_i32", - "v_bfe_u32", "v_bfe_i32", "v_bfi_b32", "v_alignbit_b32", "v_alignbyte_b32", - "v_perm_b32", "v_med3_i32", "v_med3_u32", - "v_not_b32", "v_bfrev_b32", "v_ffbl_b32", "v_ffbh_u32", "v_ffbh_i32", - "v_xnor_b32", "v_bcnt_u32_b32", - "v_add3_u32", "v_lshl_add_u32", "v_add_lshl_u32", "v_lshl_or_b32", "v_and_or_b32", "v_or3_b32", "v_xad_u32", - "v_add_f32", "v_sub_f32", "v_mul_f32", "v_fma_f32", - "s_endpgm", -} -SPECIAL_WRITE = {"vcc", "vcc_lo", "vcc_hi", "exec", "exec_lo", "exec_hi", "scc", "null"} - - -def _ffbh_i32(a): - if a in (0, MASK32): - return MASK32 - return 32 - (~a & MASK32).bit_length() if a & SIGN32 else 32 - a.bit_length() - - -_INT_VOP = { - "v_not_b32": (1, lambda a: ~a), - "v_bfrev_b32": (1, lambda a: int(f"{a:032b}"[::-1], 2)), - "v_ffbl_b32": (1, lambda a: MASK32 if a == 0 else (a & -a).bit_length() - 1), - "v_ffbh_u32": (1, lambda a: MASK32 if a == 0 else 32 - a.bit_length()), - "v_ffbh_i32": (1, _ffbh_i32), - "v_xnor_b32": (2, lambda a, b: ~(a ^ b)), - "v_bcnt_u32_b32": (2, lambda a, b: a.bit_count() + b), - "v_add3_u32": (3, lambda a, b, c: a + b + c), - "v_lshl_add_u32": (3, lambda a, b, c: (a << (b & 31)) + c), - "v_add_lshl_u32": (3, lambda a, b, c: ((a + b) & MASK32) << (c & 31)), - "v_lshl_or_b32": (3, lambda a, b, c: (a << (b & 31)) | c), - "v_and_or_b32": (3, lambda a, b, c: (a & b) | c), - "v_or3_b32": (3, lambda a, b, c: a | b | c), - "v_xad_u32": (3, lambda a, b, c: (a ^ b) + c), -} - - -class CpuRefError(Exception): - """Base class for a program the model cannot execute as written.""" - - -class Unsupported(CpuRefError): - def __init__(self, op, pc=None, reason=""): - self.op, self.pc, self.reason = op, pc, reason - where = f" at pc 0x{pc:x}" if pc is not None else "" - why = f": {reason}" if reason else "" - super().__init__(f"unsupported instruction {op}{where}{why}") - - -class ProgramError(CpuRefError): - pass - - -# ---- float helpers --------------------------------------------------------------------------- - -def bits_to_float(bits): - return struct.unpack("= Fraction(2) ** (e + 1): - e += 1 - - if e >= -126: - scaled = a / (Fraction(2) ** (e - 23)) - m = _round_half_even(scaled) - if m >= 1 << 24: - m >>= 1 - e += 1 - if e > 127: - return (sign << 31) | INF - return (sign << 31) | ((e + 127) << 23) | (m & 0x7FFFFF) - - # Subnormal: units of 2**-149. - m = _round_half_even(a * (Fraction(2) ** 149)) - if m == 0: - return sign << 31 - if m >= 1 << 23: - return (sign << 31) | (1 << 23) # rounded up to the smallest normal - return (sign << 31) | m - - -def _round_half_even(value): - """Round a non-negative Fraction to the nearest integer, ties to even.""" - q, r = divmod(value.numerator, value.denominator) - twice = 2 * r - if twice > value.denominator or (twice == value.denominator and (q & 1)): - q += 1 - return q - - -def add_f32_bits(a, b): - return float_to_bits(bits_to_float(a) + bits_to_float(b)) - - -def sub_f32_bits(a, b): - return float_to_bits(bits_to_float(a) - bits_to_float(b)) - - -def mul_f32_bits(a, b): - return float_to_bits(bits_to_float(a) * bits_to_float(b)) - - -def fma_f32_bits(a, b, c): - """Exact fused multiply-add, rounded once to binary32. - - The product of two binary32 values always fits in the exact rational. Adding the third operand - and rounding once is the ISA's FMA; rounding a host double first can lose a tie-breaking addend. - """ - if _is_nan_bits(a) or _is_nan_bits(b) or _is_nan_bits(c): - return QNAN - a_inf, b_inf, c_inf = _is_inf_bits(a), _is_inf_bits(b), _is_inf_bits(c) - a_zero, b_zero = _is_zero_bits(a), _is_zero_bits(b) - - if (a_inf and b_zero) or (b_inf and a_zero): - return QNAN - product_inf = a_inf or b_inf - product_sign = (a >> 31) ^ (b >> 31) - if product_inf: - if c_inf and (c >> 31) != product_sign: - return QNAN - return (product_sign << 31) | INF - if c_inf: - return c - - exact = Fraction(*bits_to_float(a).as_integer_ratio()) * \ - Fraction(*bits_to_float(b).as_integer_ratio()) + \ - Fraction(*bits_to_float(c).as_integer_ratio()) - if exact == 0: - # IEEE FMA zero sign: the product's sign when both terms are zero with that sign, otherwise - # +0 for cancellation under round-to-nearest. - if a_zero or b_zero: - psign = product_sign - if _is_zero_bits(c) and (c >> 31) == psign: - return psign << 31 - return 0 - return _fraction_to_f32(exact) - - -def clamp_f32_bits(bits): - """AMD clamp: min(max(x, 0), 1); a NaN clamps to 0.""" - if _is_nan_bits(bits): - return 0 - value = bits_to_float(bits) - if value < 0.0: - return 0 - if value > 1.0: - return float_to_bits(1.0) - return bits - - -# ---- listing helpers ------------------------------------------------------------------------- - -def base_op(op): - """Drop the VOP encoding suffix. Only _e32/_e64 are transparent here; SDWA/DPP are not modelled.""" - for suffix in ("_e32", "_e64"): - if op.endswith(suffix): - return op[: -len(suffix)] - return op - - -def check_supported(ins): - """Return None if the mnemonic and modifiers are in the modelled subset, else a printable reason. - - Operand kinds and arity are checked when the instruction executes, not here. - """ - op = ins["op"] - if op == "s_endpgm": - return None - base = base_op(op) - if base not in SUPPORTED_OPS: - return f"{op} is not modelled" - mods = ins.get("mods") or [] - allowed = {"clamp"} if base in FLOAT_OPS else set() - bad = [m for m in mods if m not in allowed] - if bad: - return f"modifier(s) {', '.join(bad)} are not modelled" - return None - - -# ---- machine --------------------------------------------------------------------------------- - -class Machine: - def __init__(self, info, inputs=None): - inputs = {} if inputs is None else dict(inputs) - allowed = {"lanes", "lane", "sgpr", "vgpr", "vcc", "exec", "scc", "max_steps"} - unknown = sorted(set(inputs) - allowed) - if unknown: - raise ValueError("unknown input key(s): " + ", ".join(unknown)) - - self.info = info - self.insns = info["insns"] - self.lanes = int(inputs.get("lanes", 1)) - if self.lanes not in (1, 64): - raise ValueError("lanes must be 1 or 64") - self.lane = int(inputs.get("lane", 0)) - if self.lanes == 64 and "lane" in inputs: - raise ValueError("lane is only valid in one-lane mode") - if not 0 <= self.lane < 64: - raise ValueError("lane must be in 0..63") - - self.sgpr = {} - for k, v in (inputs.get("sgpr") or {}).items(): - self.sgpr[int(k)] = int(v) & MASK32 - self.vgpr = {} - for k, v in (inputs.get("vgpr") or {}).items(): - k = int(k) - if isinstance(v, (list, tuple)): - if len(v) != self.lanes: - raise ValueError(f"vgpr[{k}] has {len(v)} values, expected {self.lanes}") - self.vgpr[k] = [int(x) & MASK32 for x in v] - else: - self.vgpr[k] = [int(v) & MASK32] * self.lanes - - self.vcc = int(inputs.get("vcc", 0)) & MASK64 - self.exec = int(inputs.get("exec", MASK64)) & MASK64 - self.scc = 1 if inputs.get("scc", 0) else 0 - self.max_steps = int(inputs.get("max_steps", 100000)) - if self.max_steps <= 0: - raise ValueError("max_steps must be positive") - - self.steps = 0 - self.pc = info.get("code_start", 0) - self.next_pc = self.pc - self.halted = False - - # -- register access -- - def _hw_lane(self, lane): - return self.lane if self.lanes == 1 else lane - - def _vgpr(self, index, lane): - values = self.vgpr.get(index) - return 0 if values is None else values[lane] - - def _write_vgpr(self, dst, lane, value): - if dst["k"] != "vgpr": - raise Unsupported(dst.get("t", "destination"), self.pc, "expected a VGPR destination") - if dst.get("n", 1) != 1: - raise Unsupported("v[%d:%d]" % (dst["r"], dst["r"] + dst.get("n", 1) - 1), self.pc, - "multi-dword VGPR destination is not modelled") - self.vgpr.setdefault(dst["r"], [0] * self.lanes)[lane] = value & MASK32 - - def _read_special(self, name): - if name == "scc": - return self.scc - if name in ("vcc", "vcc_lo"): - return self.vcc & MASK32 - if name == "vcc_hi": - return (self.vcc >> 32) & MASK32 - if name in ("exec", "exec_lo"): - return self.exec & MASK32 - if name == "exec_hi": - return (self.exec >> 32) & MASK32 - if name == "null": - return 0 - raise Unsupported(name, self.pc, "special register is not modelled") - - def _write_scalar_dst(self, dst, value): - value &= MASK32 - if dst["k"] == "sgpr": - if dst.get("n", 1) != 1: - raise Unsupported("s[%d:%d]" % (dst["r"], dst["r"] + dst.get("n", 1) - 1), self.pc, - "multi-dword SGPR destination is not modelled") - self.sgpr[dst["r"]] = value - return - if dst["k"] != "special" or dst["t"] not in SPECIAL_WRITE: - raise Unsupported(dst.get("t", "destination"), self.pc, "expected an SGPR or special destination") - name = dst["t"] - if name == "scc": - self.scc = 1 if value else 0 - elif name == "null": - return - elif name in ("vcc", "vcc_lo"): - self.vcc = (self.vcc & ~MASK32) | value - elif name == "vcc_hi": - self.vcc = (self.vcc & MASK32) | (value << 32) - elif name in ("exec", "exec_lo"): - self.exec = (self.exec & ~MASK32) | value - elif name == "exec_hi": - self.exec = (self.exec & MASK32) | (value << 32) - - def _int_src(self, arg, lane, scalar=False): - kind = arg["k"] - if kind == "vgpr": - if scalar: - raise Unsupported("vgpr source", self.pc, "a scalar instruction cannot read a VGPR directly") - value = self._vgpr(arg["r"], lane) - elif kind == "sgpr": - if arg.get("n", 1) != 1: - raise Unsupported("s[%d:%d]" % (arg["r"], arg["r"] + arg.get("n", 1) - 1), self.pc, - "multi-dword SGPR source is not modelled") - value = self.sgpr.get(arg["r"], 0) - elif kind == "imm": - value = arg["v"] & MASK32 - elif kind == "fimm": - value = float_to_bits(arg["v"]) - elif kind == "special": - value = self._read_special(arg["t"]) - else: - raise Unsupported(arg.get("t", kind), self.pc, "operand kind is not modelled") - if arg.get("abs"): - value &= 0x7FFFFFFF - if arg.get("neg"): - value ^= SIGN32 - return value & MASK32 - - def _float_src(self, arg, lane): - kind = arg["k"] - if kind == "vgpr": - bits = self._vgpr(arg["r"], lane) - elif kind == "sgpr": - if arg.get("n", 1) != 1: - raise Unsupported("s[%d:%d]" % (arg["r"], arg["r"] + arg.get("n", 1) - 1), self.pc, - "multi-dword SGPR source is not modelled") - bits = self.sgpr.get(arg["r"], 0) - elif kind == "imm": - bits = arg["v"] & MASK32 # integer inline constants are bit patterns; float ones parse as "fimm" - elif kind == "fimm": - bits = float_to_bits(arg["v"]) - elif kind == "special": - bits = self._read_special(arg["t"]) - else: - raise Unsupported(arg.get("t", kind), self.pc, "operand kind is not modelled") - if arg.get("abs"): - bits &= 0x7FFFFFFF - if arg.get("neg"): - bits ^= SIGN32 - return bits - - def _mask_bit(self, arg, lane): - kind = arg["k"] - if kind == "sgpr": - low = self.sgpr.get(arg["r"], 0) - if arg.get("n", 1) >= 2: - mask = (self.sgpr.get(arg["r"] + 1, 0) << 32) | low - else: - mask = low - elif kind == "special": - name = arg["t"] - if name in ("vcc", "vcc_lo"): - mask = self.vcc if name == "vcc" else self.vcc & MASK32 - elif name == "vcc_hi": - mask = self.vcc >> 32 - elif name == "exec": - mask = self.exec - elif name == "exec_lo": - mask = self.exec & MASK32 - elif name == "exec_hi": - mask = self.exec >> 32 - elif name == "scc": - mask = self.scc - elif name == "null": - mask = 0 - else: - raise Unsupported(name, self.pc, "condition register is not modelled") - elif kind == "imm": - mask = arg["v"] & MASK32 - if arg["v"] < 0: - mask |= MASK32 << 32 - elif kind == "fimm": - mask = float_to_bits(arg["v"]) - else: - raise Unsupported(arg.get("t", kind), self.pc, "condition operand is not modelled") - return (mask >> lane) & 1 - - def _active_lanes(self): - if self.lanes == 1: - lanes = [0] - else: - lanes = range(64) - return [lane for lane in lanes if (self.exec >> self._hw_lane(lane)) & 1] - - # -- execution -- - def run(self): - if not self.insns: - raise ProgramError("listing has no instructions") - for ins in self.insns: - if self.halted: - break - if self.steps >= self.max_steps: - raise ProgramError(f"step limit {self.max_steps} reached at pc 0x{ins['pc']:x}") - self.steps += 1 - self.step(ins) - enc = ins.get("enc") - self.next_pc = ins["pc"] + (len(enc) // 2 if enc else 0) - self.pc = self.next_pc - if not self.halted: - raise ProgramError("listing ended without s_endpgm") - return self.result() - - def step(self, ins): - op = ins["op"] - reason = check_supported(ins) - if reason: - raise Unsupported(op, ins["pc"], reason) - if op == "s_endpgm": - self.halted = True - return - base = base_op(op) - args = ins["args"] - clamp = "clamp" in (ins.get("mods") or []) - - if base == "v_mov_b32": - self._expect(ins, 2) - for lane in self._active_lanes(): - self._write_vgpr(args[0], lane, self._int_src(args[1], lane)) - elif base in FLOAT_OPS: - self._expect(ins, 4 if base == "v_fma_f32" else 3) - for lane in self._active_lanes(): - a = self._float_src(args[1], lane) - b = self._float_src(args[2], lane) - if base == "v_add_f32": - r = add_f32_bits(a, b) - elif base == "v_sub_f32": - r = sub_f32_bits(a, b) - elif base == "v_mul_f32": - r = mul_f32_bits(a, b) - else: - r = fma_f32_bits(a, b, self._float_src(args[3], lane)) - if clamp: - r = clamp_f32_bits(r) - self._write_vgpr(args[0], lane, r) - elif base == "v_cndmask_b32": - if len(args) not in (3, 4): - raise Unsupported(op, ins["pc"], f"expected 3 or 4 operands, got {len(args)}") - cond = args[3] if len(args) == 4 else None - # VOP2 cndmask has an implicit VCC condition; LLVM prints it as vcc_lo, but on a wave64 - # the hardware operand is the full VCC. VOP3 (_e64) names a 32-bit half explicitly. - implicit = cond is None or (cond["k"] == "special" and cond["t"] in ("vcc", "vcc_lo") - and not op.endswith("_e64")) - for lane in self._active_lanes(): - if implicit: - bit = (self.vcc >> self._hw_lane(lane)) & 1 - else: - bit = self._mask_bit(cond, self._hw_lane(lane)) - src0 = self._int_src(args[1], lane) - src1 = self._int_src(args[2], lane) - self._write_vgpr(args[0], lane, src1 if bit else src0) - elif base in ("v_and_b32", "v_or_b32", "v_xor_b32"): - self._expect(ins, 3) - for lane in self._active_lanes(): - a = self._int_src(args[1], lane) - b = self._int_src(args[2], lane) - r = a & b if base == "v_and_b32" else (a | b if base == "v_or_b32" else a ^ b) - self._write_vgpr(args[0], lane, r) - elif base in ("v_lshlrev_b32", "v_lshrrev_b32", "v_ashrrev_i32"): - self._expect(ins, 3) - for lane in self._active_lanes(): - shift = self._int_src(args[1], lane) & 31 - value = self._int_src(args[2], lane) - if base == "v_lshlrev_b32": - r = (value << shift) & MASK32 - elif base == "v_lshrrev_b32": - r = value >> shift - else: - signed = value - (1 << 32) if value & SIGN32 else value - r = (signed >> shift) & MASK32 - self._write_vgpr(args[0], lane, r) - elif base in ("v_add_nc_u32", "v_sub_nc_u32", "v_mul_u32_u24", "v_mul_lo_u32", - "v_min_u32", "v_max_u32", "v_min_i32", "v_max_i32"): - self._expect(ins, 3) - for lane in self._active_lanes(): - a = self._int_src(args[1], lane) - b = self._int_src(args[2], lane) - if base == "v_add_nc_u32": - r = (a + b) & MASK32 - elif base == "v_sub_nc_u32": - r = (a - b) & MASK32 - elif base == "v_mul_u32_u24": - r = ((a & 0xFFFFFF) * (b & 0xFFFFFF)) & MASK32 - elif base == "v_mul_lo_u32": - r = (a * b) & MASK32 - elif base in ("v_min_u32", "v_max_u32"): - r = (max if base == "v_max_u32" else min)(a, b) - else: - sa = a - (1 << 32) if a & SIGN32 else a - sb = b - (1 << 32) if b & SIGN32 else b - r = (max if base == "v_max_i32" else min)(sa, sb) & MASK32 - self._write_vgpr(args[0], lane, r) - elif base == "v_subrev_nc_u32": - self._expect(ins, 3) - for lane in self._active_lanes(): - a = self._int_src(args[1], lane) - b = self._int_src(args[2], lane) - self._write_vgpr(args[0], lane, (b - a) & MASK32) - elif base in ("v_mul_hi_u32", "v_mul_hi_i32"): - self._expect(ins, 3) - for lane in self._active_lanes(): - a = self._int_src(args[1], lane) - b = self._int_src(args[2], lane) - if base == "v_mul_hi_i32": - a = a - (1 << 32) if a & SIGN32 else a - b = b - (1 << 32) if b & SIGN32 else b - self._write_vgpr(args[0], lane, ((a * b) >> 32) & MASK32) - elif base in ("v_mad_u32_u24", "v_mad_i32_i24"): - self._expect(ins, 4) - for lane in self._active_lanes(): - x = self._int_src(args[1], lane) & 0xFFFFFF - y = self._int_src(args[2], lane) & 0xFFFFFF - if base == "v_mad_i32_i24": - x = x - (1 << 24) if x & 0x800000 else x - y = y - (1 << 24) if y & 0x800000 else y - z = self._int_src(args[3], lane) - self._write_vgpr(args[0], lane, (x * y + z) & MASK32) - elif base == "v_mul_i32_i24": - self._expect(ins, 3) - for lane in self._active_lanes(): - x = self._int_src(args[1], lane) & 0xFFFFFF - y = self._int_src(args[2], lane) & 0xFFFFFF - sx = x - (1 << 24) if x & 0x800000 else x - sy = y - (1 << 24) if y & 0x800000 else y - self._write_vgpr(args[0], lane, (sx * sy) & MASK32) - elif base in ("v_bfe_u32", "v_bfe_i32"): - self._expect(ins, 4) - for lane in self._active_lanes(): - value = self._int_src(args[1], lane) - off = self._int_src(args[2], lane) & 31 - width = min(self._int_src(args[3], lane) & 31, 32 - off) - if width == 0: - r = 0 - else: - r = (value >> off) & ((1 << width) - 1) - if base == "v_bfe_i32" and r & (1 << (width - 1)): - r = (r - (1 << width)) & MASK32 - self._write_vgpr(args[0], lane, r) - elif base == "v_bfi_b32": - self._expect(ins, 4) - for lane in self._active_lanes(): - x = self._int_src(args[1], lane) - y = self._int_src(args[2], lane) - z = self._int_src(args[3], lane) - self._write_vgpr(args[0], lane, (x & y) | (~x & z)) - elif base in ("v_alignbit_b32", "v_alignbyte_b32"): - self._expect(ins, 4) - for lane in self._active_lanes(): - hi = self._int_src(args[1], lane) - lo = self._int_src(args[2], lane) - shift = self._int_src(args[3], lane) - shift = (shift & 31) if base == "v_alignbit_b32" else (shift & 3) * 8 - self._write_vgpr(args[0], lane, (((hi << 32) | lo) >> shift) & MASK32) - elif base == "v_perm_b32": - self._expect(ins, 4) - for lane in self._active_lanes(): - hi = self._int_src(args[1], lane) - lo = self._int_src(args[2], lane) - sel = self._int_src(args[3], lane) - packed = (hi << 32) | lo - r = 0 - for i in range(4): - sb = (sel >> (8 * i)) & 0xFF - if sb < 8: - val = (packed >> (8 * (sb & 7))) & 0xFF - elif sb < 12: - k = sb & 3 - src = lo if k < 2 else hi - # Selector 8/9 pick bit 7 of bytes 1/3 of src1 (bits 15/31); - # 10/11 the same bytes of src0 (bits 47/63, i.e. 15/31 again). - val = 0xFF if (src >> (15 + 16 * (k & 1))) & 1 else 0 - else: - val = 0 if sb == 12 else 0xFF - r |= val << (8 * i) - self._write_vgpr(args[0], lane, r) - elif base in ("v_med3_i32", "v_med3_u32"): - self._expect(ins, 4) - for lane in self._active_lanes(): - vals = [self._int_src(args[i], lane) for i in (1, 2, 3)] - if base == "v_med3_i32": - vals = [v - (1 << 32) if v & SIGN32 else v for v in vals] - x, y, z = vals - self._write_vgpr(args[0], lane, max(min(x, y), min(max(x, y), z)) & MASK32) - elif base in _INT_VOP: - arity, fn = _INT_VOP[base] - self._expect(ins, 1 + arity) - for lane in self._active_lanes(): - vals = [self._int_src(args[i], lane) for i in range(1, 1 + arity)] - self._write_vgpr(args[0], lane, fn(*vals) & MASK32) - elif base == "s_mov_b32": - self._expect(ins, 2) - self._write_scalar_dst(args[0], self._int_src(args[1], 0, scalar=True)) - elif base == "s_add_u32": - self._expect(ins, 3) - a = self._int_src(args[1], 0, scalar=True) - b = self._int_src(args[2], 0, scalar=True) - total = a + b - self.scc = 1 if total >> 32 else 0 - self._write_scalar_dst(args[0], total & MASK32) - elif base in ("s_lshl_b32", "s_lshr_b32"): - self._expect(ins, 3) - value = self._int_src(args[1], 0, scalar=True) - shift = self._int_src(args[2], 0, scalar=True) & 31 - r = ((value << shift) & MASK32) if base == "s_lshl_b32" else (value >> shift) - self.scc = 1 if r else 0 - self._write_scalar_dst(args[0], r) - else: # check_supported should have caught this - raise Unsupported(op, ins["pc"], "not modelled") - - @staticmethod - def _expect(ins, n): - if len(ins["args"]) != n: - raise Unsupported(ins["op"], ins["pc"], f"expected {n} operands, got {len(ins['args'])}") - - def result(self): - regs = { - "sgpr": {k: self.sgpr[k] for k in sorted(self.sgpr)}, - "vgpr": {k: (self.vgpr[k][0] if self.lanes == 1 else list(self.vgpr[k])) - for k in sorted(self.vgpr)}, - "vcc": self.vcc, - "exec": self.exec, - "scc": self.scc, - } - out = { - "lanes": self.lanes, - "registers": regs, - "steps": self.steps, - "pc": self.pc, - "halted": self.halted, - "source": self.info.get("name"), - } - if self.lanes == 1: - out["lane"] = self.lane - out["active"] = bool((self.exec >> self.lane) & 1) - return out - - -def _require_header(listing_path): - """shader_ir.parse_file treats line 1 as the header; a raw llvm-mc dump would lose an instruction.""" - with open(listing_path, encoding="utf-8", errors="replace") as f: - first = f.readline() - if first.startswith("\t"): - raise ProgramError("listing has no header line; its first instruction would be skipped") - - -def run(listing_path, inputs=None): - """Parse a .s listing and execute the modelled subset. Raises CpuRefError on anything else.""" - _require_header(listing_path) - info = parse_file(listing_path) - return Machine(info, inputs).run() - - -# ---- CLI ------------------------------------------------------------------------------------- - -def _value(text): - return int(text, 0) - - -def _vgpr_value(text, lanes): - if "," in text: - values = [int(x, 0) for x in text.split(",")] - if len(values) != lanes: - raise argparse.ArgumentTypeError(f"expected {lanes} comma-separated values") - return values - return int(text, 0) - - -def _print_parse_report(path): - _require_header(path) - info = parse_file(path) - print(f"{path}: {len(info['insns'])} instructions parsed (code_start=0x{info['code_start']:x}, " - f"{info['invalid']} invalid words)") - supported = 0 - first_bad = None - for ins in info["insns"]: - reason = check_supported(ins) - if reason is None: - supported += 1 - state = "supported mnemonic" - else: - state = "UNSUPPORTED: " + reason - if first_bad is None: - first_bad = (ins, reason) - print(f" 0x{ins['pc']:04x} {ins['op']:<24} {state}") - print(f"{supported}/{len(info['insns'])} instructions have a modelled mnemonic and modifiers") - if first_bad: - ins, reason = first_bad - print(f"first unsupported: {ins['op']} at pc 0x{ins['pc']:x} ({reason})") - return 0 - - -def main(argv=None): - ap = argparse.ArgumentParser(description="Execute a small RDNA2 subset from a shader_ir listing.") - ap.add_argument("listing", help=".s listing (tools/shader_disasm.py or runtime/test/shaders/build.py)") - ap.add_argument("--lanes", type=int, choices=(1, 64), default=1) - ap.add_argument("--lane", type=int, default=0, help="hardware lane for one-lane mode") - ap.add_argument("--sgpr", action="append", default=[], metavar="N=VALUE") - ap.add_argument("--vgpr", action="append", default=[], metavar="N=VALUE[,VALUE...]") - ap.add_argument("--vcc", type=_value, default=0) - ap.add_argument("--exec", type=_value, default=None) - ap.add_argument("--parse-only", action="store_true", help="report parsed and modelled instructions only") - ap.add_argument("--json", action="store_true", help="print the result as JSON") - args = ap.parse_args(argv) - if not os.path.exists(args.listing): - print(f"ERROR: {args.listing}: does not exist", file=sys.stderr) - return 2 - - inputs = {"lanes": args.lanes, "vcc": args.vcc} - if args.lanes == 1: - if not 0 <= args.lane < 64: - ap.error("--lane must be in 0..63") - inputs["lane"] = args.lane - if args.exec is not None: - inputs["exec"] = args.exec - for kind, assignments, syntax in ( - ("sgpr", args.sgpr, "N=VALUE"), - ("vgpr", args.vgpr, "N=VALUE[,VALUE...]"), - ): - for item in assignments: - try: - register, text = item.split("=", 1) - index = _value(register) - value = _value(text) if kind == "sgpr" else _vgpr_value(text, args.lanes) - except (ValueError, argparse.ArgumentTypeError): - ap.exit(2, f"error: --{kind} expects {syntax}, got {item!r}\n") - inputs.setdefault(kind, {})[index] = value - - if args.parse_only: - try: - return _print_parse_report(args.listing) - except (CpuRefError, OSError) as e: - print(f"error: {e}", file=sys.stderr) - return 1 - - try: - result = run(args.listing, inputs) - except (CpuRefError, OSError) as e: - print(f"error: {e}", file=sys.stderr) - return 1 - - if args.json: - print(json.dumps(result, indent=2)) - return 0 - print(f"{args.listing}: {result['steps']} instructions, halted={result['halted']}") - if result["lanes"] == 1: - print(f"lane {result['lane']} active={result['active']}") - for name, value in result["registers"]["sgpr"].items(): - print(f" s{name} = 0x{value:08x}") - for name, value in result["registers"]["vgpr"].items(): - if isinstance(value, list): - print(f" v{name} = [" + ", ".join(f"0x{x:08x}" for x in value) + "]") - else: - print(f" v{name} = 0x{value:08x}") - print(f" vcc = 0x{result['registers']['vcc']:016x} exec = 0x{result['registers']['exec']:016x} " - f"scc = {result['registers']['scc']}") - return 0 - - -if __name__ == "__main__": - try: # a redirected stdout is strict ANSI code page under -I; write '?' for what it cannot encode - sys.stdout.reconfigure(errors="replace") - except (AttributeError, ValueError, OSError): - pass - sys.exit(main()) diff --git a/tools/crosslane_fuzz.py b/tools/crosslane_fuzz.py deleted file mode 100644 index 6be446180..000000000 --- a/tools/crosslane_fuzz.py +++ /dev/null @@ -1,1759 +0,0 @@ -r"""Differential fuzzer for the translator's wave and cross-lane operations (FUZZ-7 in #156 / #374). - -Generates seeded random compute programs built from cross-lane RDNA2 instructions (v_readlane, v_writelane, -v_readfirstlane, ballots through v_cmp / v_cmpx, s_bcnt1 / s_ff1 of masks, v_mbcnt, v_cndmask on a mask, masks -read as data, v_permlane16 / v_permlanex16, forward s_cbranch_execz / vccz / vccnz around them, and with --dpp -DPP16 / DPP8 sources) under random EXEC masks: constants per half, v_cmpx, nested s_and_saveexec and its -restore, partial waves (a group size that isn't a multiple of the wave size) and groups of two or more waves. -Each program runs through a Python model of the ISA (the reference, below) and through the translator on the -local GPU: llvm-mc assembles it, tools/rdna2spirv.py translates it (wave32 natively; wave64 with ---wave64-emulate, and natively with --w64-native), runtime/build/vk_compute_test runs it with VKC_OUT_WORDS / -VKC_DUMP, and every word every thread stores is compared. docs/shader_validation.md has the details. - - python -I tools/crosslane_fuzz.py --programs 200 --seed 1 [--wave 32|64|both] [--modes native,emulate] - python -I tools/crosslane_fuzz.py --ext --wave 64 # more wave64 ops (below); wave32 programs are unchanged - python -I tools/crosslane_fuzz.py --self-test # the model against hand-computed values, no GPU - python -I tools/crosslane_fuzz.py --oracle hw # model vs the AMD GPU natively (wave32 and wave64); exit 77 - # when tools/hw_oracle's tools are missing. --oracle translator,hw - # does both. No llvm-mc, Vulkan or vk_compute_test for hw alone. - python -I tools/crosslane_fuzz.py --dpp-sweep --oracle hw # one program per DPP case instead of random ones: - # every DPP16 control x bound_ctrl x fi x EXEC pattern, all - # row_mask / bank_mask pairs, DPP8 selects (7,206 per wave size) - -Exit code: 0 when every program that ran matches (or differs only in a program with a hypothesis op), 1 on a -mismatch or an untranslated program, 2 when the only failures are harness errors: vk_compute_test timed out or -gave no dump for a program. Such a program is listed with the others (and kept with --keep) and the run goes on. -A missing vk_compute_test for the translator oracle is one line and exit 1, before any program is generated. -A wave32 program is skipped where vk_compute_test can't pin 32-lane subgroups ("compute subgroup size: 32 not -available", e.g. Mesa llvmpipe at 8 lanes), and a run where every program was skipped exits 2. Wave64 programs -translated with --wave64-emulate use no subgroup operations, so they are compared at any subgroup size. - -Needs LLVM_MC (llvm-mc with AMDGPU, as for the shaders stage), the Vulkan SDK and a built vk_compute_test -(cmake --build runtime/build --target vk_compute_test). No game files. - -Reference semantics (AMD "RDNA 2" ISA reference guide; Mesa ACO and LLVM where the guide is terse): - * v_readlane_b32 sD, vS, lane: sD = vS of lane (lane & 63 in wave64, & 31 in wave32), EXEC ignored. - * v_writelane_b32 vD, s, lane: vD of that lane = s, EXEC ignored. - * v_readfirstlane_b32: vS of the lowest lane on in EXEC, lane 0 if EXEC is 0. - * VOPC v_cmp: bit l = condition for active lanes, 0 for inactive ones (sD / VCC is written as a whole). - v_cmpx: EXEC = EXEC & condition (inactive lanes stay off). - * s_and_saveexec_bN sD, s: sD = EXEC; EXEC = s & EXEC. - * v_mbcnt_lo_u32_b32 vD, s, acc: popcount(s & ((1 << lane) - 1)) + acc (all 32 bits for lane >= 32); - v_mbcnt_hi_u32_b32: popcount(s & ((1 << (lane - 32)) - 1)) + acc for lane >= 32, acc for lane < 32. - * v_permlane16_b32 vD, vS, s1, s2: lane l reads lane (l & ~15) | sel[l & 15], sel = nibbles of {s2, s1}; - v_permlanex16_b32 reads lane (l & ~31) | ((l & 16) ^ 16) | sel[l & 15]. Only written in active lanes. - A source lane that is off in EXEC (op_sel FI = 0) is the DPP "invalid source" case: with BOUND_CTRL = 0 the - lane keeps its old vD. That was measured on RDNA2 and RDNA3.5 (docs/shader_validation.md, #374), but the - translator models it only with #580, so programs that reach it are still reported apart. - * VALU results are written only in active lanes; SALU is wave-uniform. - ---ext adds these to wave64 programs (the model of each was checked against an RDNA2 GPU, gfx1036, with --oracle hw): - * v_add_co / v_sub_co / v_subrev_co_u32 and the _ci forms, carries in SGPR pairs or VCC: the carry-out mask has - the lane's carry (borrow) for an active lane and 0 for an inactive one. - * ds_bpermute_b32: lane l reads vData of lane ((vAddr + offset) >> 2) & 31 of its own 32-lane half; a source - lane that is off in EXEC reads 0. ds_permute_b32: every active lane sends vData to that lane; a lane nobody - sends to gets 0, and with several senders the highest lane wins. ds_swizzle_b32 (QUAD_PERM, BITMASK_PERM, SWAP, - REVERSE, BROADCAST) works inside each group of 32 lanes; an EXEC-off source lane reads 0, which the - translator models only with #2780, so programs that reach it are reported apart like the permlane case. - On hardware the three need `s_waitcnt lgkmcnt(0)` before the result is used; the generator emits it. - * v_readlane / v_writelane with an SGPR lane select of 64 or more (S1[5:0]). - * s_bcnt0/1 and s_ff0/1 of a mask, s_and/or/xor/andn2_b64 of masks, the ten s_*_saveexec_b64 forms and - s_andn1/andn2_wrexec_b64, s_wqm_b64, s_cmp_eq/lg_u64 and s_bitcmp0/1_b64 of masks, each followed by an - s_cselect_b32 so its SCC reaches a stored SGPR; s_cselect_b64 between masks; s_mov_b64 exec, mask; - s_bfm_b64 (D = ((1 << S0[5:0]) - 1) << S1[5:0]) into a mask or EXEC. - * A loop in LLVM's SI_LOOP shape: per-lane trip counts, a break mask, s_andn2_b64 exec and s_cbranch_execnz - back to the head, so lanes of both halves leave on different iterations while the rest keep running. -Usage: `python -I tools/crosslane_fuzz.py --help` lists the options. -""" -import argparse -import os -import random -import re -import struct -import subprocess -import sys -import tempfile - -HERE = os.path.dirname(os.path.abspath(__file__)) -ROOT = os.path.dirname(HERE) -sys.path.insert(0, HERE) -sys.path.insert(0, os.path.join(ROOT, "runtime", "test", "shaders")) -import mc_command # noqa: E402 - -M32 = 0xFFFFFFFF -M64 = (1 << 64) - 1 -DATA_V = (2, 3, 4, 5, 6, 7) # data VGPRs, stored at the end -DATA_S = (8, 9, 10, 11, 12, 13, 14, 15) # data SGPRs, stored at the end -OUT_REGS = [("v", r) for r in DATA_V] + [("s", r) for r in DATA_S] -SAVE = (22, 24, 26) # saveexec destinations (pairs in wave64) -ENTRY = 30 # entry EXEC (pair in wave64) -SEL = 28 # scratch SGPRs for lane selects / permlane selectors (28, 29) -PERM_V = 23 # --ext: scratch VGPR for ds_permute addresses -LOOP_V = (24, 25) # --ext: a loop's per-lane trip limit and counter -LOOP_S = (32, 34) # --ext: a loop's break mask and "done this iteration" mask (pairs) -DS_WAIT = "\n\ts_waitcnt lgkmcnt(0)" # after ds_bpermute / ds_permute / ds_swizzle: the result comes back late -PERMLANE_FETCH_INACTIVE = False -TRANSLATOR = [os.path.join(HERE, "rdna2spirv.py")] # --translator # --permlane-fetch-inactive: model FI = 1 (read inactive sources) - - -class Wave: - def __init__(self, size, exists): - self.size = size - self.exists = exists # bit mask of lanes that exist (partial last wave) - self.v = {} # vgpr -> [lane values] - self.s = {} # sgpr -> value - self.exec = exists - self.vcc = 0 - - def vr(self, r): - return self.v.setdefault(r, [0] * self.size) - - def sr(self, r): - return self.s.get(r, 0) - - def active(self, lane): - return self.exec >> lane & 1 - - def mask(self, name): - """A mask operand: 'vcc', 'exec' or an SGPR number (pair in wave64).""" - if name == "vcc": - return self.vcc - if name == "exec": - return self.exec - lo = self.sr(name) - return lo | (self.sr(name + 1) << 32 if self.size == 64 else 0) - - def set_mask(self, name, m): - m &= (1 << self.size) - 1 - if name == "vcc": - self.vcc = m - elif name == "exec": - self.exec = m - else: - self.s[name] = m & M32 - if self.size == 64: - self.s[name + 1] = m >> 32 - - def vwrite(self, r, vals): - dst = self.vr(r) - for lane in range(self.size): - if self.active(lane) and self.exists >> lane & 1: - dst[lane] = vals[lane] & M32 - - -def popcount(x): - return bin(x).count("1") - - -def mreg(wave, name): - """Assembler name of a mask operand.""" - if name == "vcc": - return "vcc" if wave == 64 else "vcc_lo" - if name == "exec": - return "exec" if wave == 64 else "exec_lo" - return f"s[{name}:{name + 1}]" if wave == 64 else f"s{name}" - - -class Op: - """One instruction (or a short fixed group) with its assembly and its effect on the model.""" - hyp = False # depends on a hypothesis about the ISA (reported apart) - - def __init__(self, text, fn, tag, hyp=False): - self.text, self.fn, self.tag, self.hyp = text, fn, tag, hyp - - def apply(self, waves): - hyp = False - for w in waves: - hyp |= bool(self.fn(w)) - return hyp - - -DPP16_CONTROLS = ("quad_perm", "row_shl", "row_shr", "row_ror", "row_mirror", "row_half_mirror", "row_share", - "row_xmask") -DPP_OPS = {"mov": "v_mov_b32", "not": "v_not_b32", "add": "v_add_nc_u32", "xor": "v_xor_b32"} - - -def dpp16_select(control, arg=None): - """(modifier text, f) for one DPP16 control; f(x) gives (source lane in the 16-lane row, whether it is in the - row) for row lane x. arg: the four quad_perm selects, or the shift / rotate / share / xmask amount.""" - if control == "quad_perm": - q = list(arg) - return f"quad_perm:[{','.join(map(str, q))}]", (lambda x: ((x & ~3) | q[x & 3], True)) - if control == "row_shl": - return f"row_shl:{arg}", (lambda x: (x + arg, x + arg < 16)) - if control == "row_shr": - return f"row_shr:{arg}", (lambda x: (x - arg, x >= arg)) - if control == "row_ror": - return f"row_ror:{arg}", (lambda x: ((x - arg) & 15, True)) - if control == "row_mirror": - return "row_mirror", (lambda x: (15 - x, True)) - if control == "row_half_mirror": - return "row_half_mirror", (lambda x: ((x & 8) | (7 - (x & 7)), True)) - if control == "row_share": - return f"row_share:{arg}", (lambda x: (arg, True)) - if control == "row_xmask": - return f"row_xmask:{arg}", (lambda x: (x ^ arg, True)) - raise ValueError(f"unknown DPP16 control {control!r}") - - -def dpp_op(d, a, b, kind, control=None, dpp8=None, fi=False, bound=False, row_mask=0xF, bank_mask=0xF): - """A VOP1/VOP2 op with a DPP16 (control = (name, arg)) or DPP8 (dpp8 = the eight selects) src0, and its - effect on the model. From the RDNA 2 ISA guide's DPP section: DPP16 picks the source lane inside the 16-lane - row; a source out of the row, or one that is off in EXEC while fi = 0, is invalid: bound_ctrl 1 uses 0 as - src0, bound_ctrl 0 leaves the lane unwritten. Lanes in a row or bank that row_mask / bank_mask turn off are - not written. DPP8 picks a lane in the 8-lane group; an inactive source with fi = 0 reads 0 (as #238 - implements it; reported apart as a hypothesis). Every source is read before vD is written, so d may be a.""" - if dpp8 is not None: - sel = list(dpp8) - ctl = f"dpp8:[{','.join(map(str, sel))}]" + (" fi:1" if fi else "") - pick = lambda l: ((l & ~7) | sel[l & 7], True) - else: - ctl, f = dpp16_select(*control) - - def pick(l, f=f): - s_, ok = f(l & 15) - return (l & ~15) | (s_ & 15), ok - ctl += f" row_mask:0x{row_mask:x} bank_mask:0x{bank_mask:x}" + (" bound_ctrl:1" if bound else "") + \ - (" fi:1" if fi else "") - name = DPP_OPS[kind] - if kind in ("mov", "not"): - text = f"{name}_dpp v{d}, v{a} {ctl}" - else: - text = f"{name}_dpp v{d}, v{a}, v{b} {ctl}" - alu = {"mov": lambda x, y: x, "not": lambda x, y: ~x, "add": lambda x, y: x + y, - "xor": lambda x, y: x ^ y}[kind] - - def fn(w): - src, other = w.vr(a), w.vr(b) - vals, hyp = list(w.vr(d)), False - for lane in range(w.size): - if not w.active(lane): - continue - sl, ok = pick(lane) - if dpp8 is not None: - if w.active(sl) or fi: - x = src[sl] - else: - x, hyp = 0, True - else: - if not (row_mask >> (lane >> 4) & 1 and bank_mask >> ((lane >> 2) & 3) & 1): - continue - if ok and (w.active(sl) or fi): - x = src[sl] - elif bound: - x = 0 - else: - continue - vals[lane] = alu(x, other[lane]) & M32 - w.vwrite(d, vals) - return hyp - return Op(text, fn, "dpp") - - -def exec_op(wave, mask): - """EXEC = mask (a constant), as op_exec_const writes it.""" - if wave == 32: - text = f"s_mov_b32 exec_lo, 0x{mask & M32:x}" - else: - text = f"s_mov_b32 exec_lo, 0x{mask & M32:x}\n\ts_mov_b32 exec_hi, 0x{mask >> 32:x}" - - def fn(w): - w.exec = mask & ((1 << w.size) - 1) - return Op(text, fn, "exec") - - -# --dpp-sweep: EXEC patterns. "all" has no inactive source; "odd" turns off every other lane, so every source a -# lane reads one or three lanes away is off; "banks" turns off the first lane of each 4-lane bank and the whole -# second row, so inactive sources sit next to active ones and one row (row 1) runs nothing. -SWEEP_EXEC = { - 32: (("all", M32), ("odd", 0x55555555), ("banks", 0x0000EEEE)), - 64: (("all", M64), ("odd", 0x5555555555555555), ("banks", 0xEEEEEEEE0000EEEE)), -} -SWEEP_DPP8 = ((0, 1, 2, 3, 4, 5, 6, 7), (7, 6, 5, 4, 3, 2, 1, 0), (1, 0, 3, 2, 5, 4, 7, 6), (4, 5, 6, 7, 0, 1, 2, 3)) + \ - tuple((k,) * 8 for k in range(8)) + tuple(tuple((i + k) & 7 for i in range(8)) for k in range(1, 8)) -SWEEP_MASK_CONTROLS = (("row_shr", 1), ("quad_perm", (1, 0, 3, 2)), ("row_share", 5)) - - -def dpp16_sweep_controls(): - """Every DPP16 control the RDNA2 assembler takes: 256 quad_perms, row_shl/shr/ror 1-15, both mirrors, - row_share and row_xmask 0-15 (335).""" - out = [("quad_perm", tuple(q >> s & 3 for s in (0, 2, 4, 6))) for q in range(256)] - out += [(c, n) for c in ("row_shl", "row_shr", "row_ror") for n in range(1, 16)] - out += [("row_mirror", None), ("row_half_mirror", None)] - out += [(c, n) for c in ("row_share", "row_xmask") for n in range(16)] - return out - - -def dpp_sweep_cases(wave): - """The --dpp-sweep cases for one wave size, as (family, exec name, exec mask, op kwargs). Three parts: - every DPP16 control x bound_ctrl x fi x EXEC pattern with both masks on; all 256 row_mask / bank_mask pairs - for three controls, with and without bound_ctrl, under the full and the odd EXEC; every DPP8 select set - x fi x EXEC pattern. The op (mov, not, add, xor) and whether vD is also src0 (in place, as a reduction - writes it) rotate through the cases, so each control meets all four ops and both register layouts.""" - cases = [] - execs = SWEEP_EXEC[wave] - for control in dpp16_sweep_controls(): - for bound in (False, True): - for fi in (False, True): - for ename, emask in execs: - cases.append((control[0], ename, emask, - dict(control=control, fi=fi, bound=bound))) - for control in SWEEP_MASK_CONTROLS: - for row_mask in range(16): - for bank_mask in range(16): - for bound in (False, True): - for ename, emask in execs[:2]: - cases.append(("masks", ename, emask, dict(control=control, bound=bound, row_mask=row_mask, - bank_mask=bank_mask))) - for sel in SWEEP_DPP8: - for fi in (False, True): - for ename, emask in execs: - cases.append(("dpp8", ename, emask, dict(dpp8=sel, fi=fi))) - return cases - - -def dpp_sweep_programs(wave): - """One program per --dpp-sweep case: the usual prologue (data in v2-v7), EXEC set to the case's pattern, one - DPP op, and the usual epilogue (EXEC restored, every word stored). One full wave, so no source lane is missing.""" - progs = [] - kinds = tuple(DPP_OPS) - for i, (family, ename, emask, kw) in enumerate(dpp_sweep_cases(wave)): - rng = random.Random(wave * 1000003 + i) - pro, init = prologue(rng, wave) - kind = kinds[i % 4] - d, a, b = (2, 2, 4) if (i // 4) % 2 else (2, 3, 4) - op = dpp_op(d, a, b, kind, **kw) - p = Program(f"cs_dpp{wave}_{i}", wave, wave, pro, init, [exec_op(wave, emask), op]) - p.label = f"{family}, EXEC {ename}: {op.text}" - p.family = family - progs.append(p) - return progs - - -class Gen: - def __init__(self, rng, wave, group, allow_maskdata=True, wave32_hi_lanes=True, dpp=False, ext=False): - self.rng, self.W, self.L = rng, wave, group - self.nwaves = (group + wave - 1) // wave - last = group - (self.nwaves - 1) * wave - self.min_exist = last # lanes every wave has - self.full = last == wave - self.allow_maskdata, self.hi_lanes = allow_maskdata, wave32_hi_lanes - self.dpp = dpp - self.ext = ext and wave == 64 # --ext: the wave64 extension ops - self.masks = [] # mask registers written so far - self.depth = 0 - self.in_branch, self.branch_id = False, 0 - - def r(self, seq): - return self.rng.choice(seq) - - def lane(self): - return self.rng.randrange(self.min_exist) - - def vsrc(self): - return self.r(DATA_V + (1,)) - - def mask_name(self, write=False): - pool = ["vcc", 16, 18, 20] - if write: - return self.r(pool) - return self.r(self.masks) if self.masks else None - - # ---- op builders ------------------------------------------------------------------------------------ - def op_cmp(self): - d = self.mask_name(write=True) - a, cond = self.vsrc(), self.r(("lt", "gt", "eq", "ne", "le", "ge")) - f = {"lt": lambda x, y: x < y, "gt": lambda x, y: x > y, "eq": lambda x, y: x == y, - "ne": lambda x, y: x != y, "le": lambda x, y: x <= y, "ge": lambda x, y: x >= y}[cond] - if d == "vcc" and self.rng.random() < 0.5: - k = self.rng.randrange(65) - text = f"v_cmp_{cond}_u32_e32 {mreg(self.W, 'vcc')}, {k}, v{a}" - - def fn(w): - m = 0 - for lane in range(w.size): - if w.active(lane) and f(k, w.vr(a)[lane]): - m |= 1 << lane - w.set_mask("vcc", m) - else: - b = self.vsrc() - text = f"v_cmp_{cond}_u32_e64 {mreg(self.W, d)}, v{a}, v{b}" - - def fn(w): - m = 0 - for lane in range(w.size): - if w.active(lane) and f(w.vr(a)[lane], w.vr(b)[lane]): - m |= 1 << lane - w.set_mask(d, m) - if d not in self.masks: - self.masks.append(d) - return Op(text, fn, "cmp") - - def op_cmpx(self): - a, k = self.vsrc(), self.rng.randrange(65) - cond = self.r(("gt", "lt", "ne")) - f = {"gt": lambda x, y: x > y, "lt": lambda x, y: x < y, "ne": lambda x, y: x != y}[cond] - text = f"v_cmpx_{cond}_u32_e32 {k}, v{a}" - - def fn(w): - m = 0 - for lane in range(w.size): - if w.active(lane) and f(k, w.vr(a)[lane]): - m |= 1 << lane - w.exec = m - return Op(text, fn, "exec") - - def op_exec_const(self): - ex = (1 << self.min_exist) - 1 - lo = self.rng.getrandbits(32) & ex - if self.rng.random() < 0.15: - lo = 0 - if self.W == 32: - text = f"s_mov_b32 exec_lo, 0x{lo:x}" - - def fn(w): - w.exec = lo - return Op(text, fn, "exec") - hi = self.rng.getrandbits(32) & (ex >> 32) - if self.rng.random() < 0.15: - hi = 0 - text = f"s_mov_b32 exec_lo, 0x{lo:x}\n\ts_mov_b32 exec_hi, 0x{hi:x}" - - def fn(w): - w.exec = lo | hi << 32 - return Op(text, fn, "exec") - - def op_saveexec(self): - m = self.mask_name() - if m is None or self.depth >= len(SAVE): - return None - d = SAVE[self.depth] - self.depth += 1 - op = "s_and_saveexec_b64" if self.W == 64 else "s_and_saveexec_b32" - text = f"{op} {mreg(self.W, d)}, {mreg(self.W, m)}" - - def fn(w): - old = w.exec - w.exec = w.mask(m) & old - w.set_mask(d, old) - return Op(text, fn, "exec") - - def op_restore(self): - if self.depth == 0: - return None - self.depth -= 1 - d = SAVE[self.depth] - op = "s_mov_b64 exec," if self.W == 64 else "s_mov_b32 exec_lo," - text = f"{op} {mreg(self.W, d)}" - - def fn(w): - w.exec = w.mask(d) & w.exists - return Op(text, fn, "exec") - - def op_readlane(self): - d, v = self.r(DATA_S), self.vsrc() - lane = self.lane() - enc = lane - if self.W == 32 and self.hi_lanes and self.rng.random() < 0.3: - enc = lane + 32 * self.rng.randrange(1, 8) # wave32 uses lane select bits [4:0] - if self.rng.random() < 0.5: - text = f"v_readlane_b32 s{d}, v{v}, {enc}" if enc <= 64 else \ - f"s_mov_b32 s{SEL}, {enc}\n\tv_readlane_b32 s{d}, v{v}, s{SEL}" - else: - text = f"s_mov_b32 s{SEL}, {enc}\n\tv_readlane_b32 s{d}, v{v}, s{SEL}" - tag = "readlane" if enc == lane else "readlane_w32hi" - - def fn(w): - w.s[d] = w.vr(v)[lane] - if "s_mov_b32" in text: - w.s[SEL] = enc - return Op(text, fn, tag) - - def op_writelane(self): - d = self.r(DATA_V) - lane = self.lane() if self.rng.random() < 0.7 else self.rng.randrange(self.W) - enc = lane - if self.W == 32 and self.hi_lanes and self.rng.random() < 0.3: - enc = lane + 32 * self.rng.randrange(1, 8) - if self.rng.random() < 0.5: - src = f"s{self.r(DATA_S)}" - else: - src = str(self.rng.randrange(-16, 65)) - if self.rng.random() < 0.5 and enc <= 64: - text = f"v_writelane_b32 v{d}, {src}, {enc}" - else: - text = f"s_mov_b32 s{SEL}, {enc}\n\tv_writelane_b32 v{d}, {src}, s{SEL}" - tag = "writelane" if enc == lane else "writelane_w32hi" - - def fn(w): - val = w.sr(int(src[1:])) if src.startswith("s") else int(src) & M32 - if lane < w.size and w.exists >> lane & 1: - w.vr(d)[lane] = val - if "s_mov_b32" in text: - w.s[SEL] = enc - return Op(text, fn, tag) - - def op_readfirstlane(self): - d, v = self.r(DATA_S), self.vsrc() - text = f"v_readfirstlane_b32 s{d}, v{v}" - - def fn(w): - e = w.exec - first = (e & -e).bit_length() - 1 if e else 0 - w.s[d] = w.vr(v)[first] - return Op(text, fn, "readfirstlane") - - def op_bcnt(self): - m = self.mask_name() if self.rng.random() < 0.7 else "exec" - if m is None: - m = "exec" - d = self.r(DATA_S) - kind = self.r(("bcnt1", "ff1", "bcnt0")) - sfx = "b64" if self.W == 64 else "b32" - text = f"s_{kind}_i32_{sfx} s{d}, {mreg(self.W, m)}" - - def fn(w): - x = w.mask(m) - if kind == "bcnt1": - w.s[d] = popcount(x) - elif kind == "bcnt0": - w.s[d] = self.W - popcount(x) - else: - w.s[d] = ((x & -x).bit_length() - 1) & M32 if x else M32 - return Op(text, fn, "bcnt") - - def op_mbcnt(self): - d, acc = self.r(DATA_V), self.vsrc() - m = self.mask_name() if self.rng.random() < 0.6 else "exec" - if m is None: - m = "exec" - if self.W == 32: - text = f"v_mbcnt_lo_u32_b32 v{d}, {mreg(32, m)}, v{acc}" - elif m in ("exec", "vcc"): - text = (f"v_mbcnt_lo_u32_b32 v{d}, {m}_lo, v{acc}\n\t" - f"v_mbcnt_hi_u32_b32 v{d}, {m}_hi, v{d}") - else: - text = f"v_mbcnt_lo_u32_b32 v{d}, s{m}, v{acc}\n\tv_mbcnt_hi_u32_b32 v{d}, s{m + 1}, v{d}" - - def fn(w): - x = w.mask(m) - vals = [] - for lane in range(w.size): - vals.append(popcount(x & ((1 << lane) - 1)) + w.vr(acc)[lane]) - w.vwrite(d, vals) - return Op(text, fn, "mbcnt") - - def op_mbcnt_data(self): - """v_mbcnt with an ordinary SGPR (data, not a mask) as its mask operand.""" - d, acc, s = self.r(DATA_V), self.vsrc(), self.r(DATA_S) - hi = self.W == 64 and self.rng.random() < 0.5 - name = "v_mbcnt_hi_u32_b32" if hi else "v_mbcnt_lo_u32_b32" - text = f"{name} v{d}, s{s}, v{acc}" - - def fn(w): - x = w.sr(s) - vals = [] - for lane in range(w.size): - if hi: - below = 0 if lane < 32 else popcount(x & ((1 << (lane - 32)) - 1)) - else: - below = popcount(x & ((1 << min(lane, 32)) - 1)) - vals.append(below + w.vr(acc)[lane]) - w.vwrite(d, vals) - return Op(text, fn, "mbcnt_data") - - def op_cndmask(self): - m = self.mask_name() - if m is None: - return None - d, a, b = self.r(DATA_V), self.vsrc(), self.vsrc() - text = f"v_cndmask_b32_e64 v{d}, v{a}, v{b}, {mreg(self.W, m)}" - - def fn(w): - x = w.mask(m) - w.vwrite(d, [w.vr(b)[l] if x >> l & 1 else w.vr(a)[l] for l in range(w.size)]) - return Op(text, fn, "cndmask") - - def op_maskdata(self): - m = self.mask_name() - if m is None or not self.allow_maskdata: - return None - d = self.r(DATA_V) - half = self.rng.randrange(2) if self.W == 64 else 0 - if m == "vcc": - src = "vcc_hi" if half else "vcc_lo" - else: - src = f"s{m + half}" - text = f"v_mov_b32_e32 v{d}, {src}" - - def fn(w): - x = w.mask(m) >> (32 * half) & M32 - w.vwrite(d, [x] * w.size) - return Op(text, fn, "maskdata") - - def op_mask_salu(self): - if len(self.masks) < 1: - return None - a, b = self.r(self.masks), self.r(self.masks) - d = self.r([16, 18, 20]) - kind = self.r(("and", "or", "xor", "andn2")) - sfx = "b64" if self.W == 64 else "b32" - text = f"s_{kind}_{sfx} {mreg(self.W, d)}, {mreg(self.W, a)}, {mreg(self.W, b)}" - if d not in self.masks: - self.masks.append(d) - - def fn(w): - x, y = w.mask(a), w.mask(b) - r = {"and": x & y, "or": x | y, "xor": x ^ y, "andn2": x & ~y}[kind] - w.set_mask(d, r) - return Op(text, fn, "mask_salu") - - def op_permlane(self): - if not self.full: - return None - d, v = self.r(DATA_V), self.vsrc() - x16 = self.rng.random() < 0.5 - s1, s2 = self.rng.getrandbits(32), self.rng.getrandbits(32) - name = "v_permlanex16_b32" if x16 else "v_permlane16_b32" - if self.rng.random() < 0.5: # VOP3 takes one literal: s1 as a literal, s2 from an SGPR - text = f"s_mov_b32 s{SEL + 1}, 0x{s2:x}\n\t{name} v{d}, v{v}, 0x{s1:x}, s{SEL + 1}" - else: - text = (f"s_mov_b32 s{SEL}, 0x{s1:x}\n\ts_mov_b32 s{SEL + 1}, 0x{s2:x}\n\t" - f"{name} v{d}, v{v}, s{SEL}, s{SEL + 1}") - sel = s1 | s2 << 32 - - def fn(w): - if text.count("s_mov_b32") == 2: - w.s[SEL] = s1 - w.s[SEL + 1] = s2 - src = w.vr(v) - old = list(w.vr(d)) - vals, hyp = list(old), False - for lane in range(w.size): - n = sel >> (4 * (lane & 15)) & 15 - sl = (lane & ~31) | ((lane & 16) ^ 16) | n if x16 else (lane & ~15) | n - if not w.active(lane): - continue - if w.active(sl) or PERMLANE_FETCH_INACTIVE: - vals[lane] = src[sl] - if not w.active(sl): - hyp = not PERMLANE_FETCH_INACTIVE # FI = 0, BOUND_CTRL = 0: keeps vD (measured; translator: #580) - w.vwrite(d, vals) - return hyp - return Op(text, fn, "permlane") - - def op_dpp(self): - """A VOP1/VOP2 op with a DPP16 or DPP8 src0 (--dpp). Model, from the RDNA 2 ISA guide's DPP section: - DPP16 picks the source lane inside the 16-lane row (quad_perm, row_shl/shr/ror, row_mirror, - row_half_mirror, row_share, row_xmask); a source out of the row, or one that is off in EXEC while fi = 0, - is invalid: bound_ctrl 1 uses 0 as src0, bound_ctrl 0 leaves the lane unwritten. Lanes in a row or bank - that row_mask / bank_mask turn off are not written. DPP8 picks a lane in the 8-lane group; an inactive - source with fi = 0 reads 0 (as #238 implements it; reported apart as a hypothesis).""" - if not self.dpp or not self.full: # a source lane in the missing part of a wave is undefined - return None - d, a, b = self.r(DATA_V), self.vsrc(), self.vsrc() - kind = self.r(("mov", "mov", "not", "add", "xor")) - r = self.rng - # The draws stay in this order, so a seed gives the same programs as before dpp_op was split out. - dpp8 = r.random() < 0.25 - fi = r.random() < 0.3 - bound = r.random() < 0.5 - row_mask = 0xF if r.random() < 0.6 else r.randrange(16) - bank_mask = 0xF if r.random() < 0.6 else r.randrange(16) - if dpp8: - return dpp_op(d, a, b, kind, fi=fi, dpp8=[r.randrange(8) for _ in range(8)]) - c = r.choice(DPP16_CONTROLS) - if c == "quad_perm": - arg = [r.randrange(4) for _ in range(4)] - elif c in ("row_shl", "row_shr", "row_ror"): - arg = r.randrange(1, 16) - elif c in ("row_share", "row_xmask"): - arg = r.randrange(16) - else: - arg = None - return dpp_op(d, a, b, kind, control=(c, arg), fi=fi, bound=bound, row_mask=row_mask, bank_mask=bank_mask) - - def op_valu(self): - d, a, b = self.r(DATA_V), self.vsrc(), self.vsrc() - kind = self.r(("add", "xor", "movs", "lshr")) - if kind == "add": - text, f = f"v_add_nc_u32_e32 v{d}, v{a}, v{b}", lambda w, l: w.vr(a)[l] + w.vr(b)[l] - elif kind == "xor": - text, f = f"v_xor_b32_e32 v{d}, v{a}, v{b}", lambda w, l: w.vr(a)[l] ^ w.vr(b)[l] - elif kind == "lshr": - k = self.rng.randrange(1, 17) - text, f = f"v_lshrrev_b32_e32 v{d}, {k}, v{a}", lambda w, l: w.vr(a)[l] >> k - else: - s = self.r(DATA_S) - text, f = f"v_mov_b32_e32 v{d}, s{s}", lambda w, l: w.sr(s) - return Op(text, lambda w: w.vwrite(d, [f(w, l) for l in range(w.size)]), "valu") - - def op_salu(self): - d, a, b = self.r(DATA_S), self.r(DATA_S), self.r(DATA_S) - if self.rng.random() < 0.5: - text = f"s_add_u32 s{d}, s{a}, s{b}" - - def fn(w): - w.s[d] = (w.sr(a) + w.sr(b)) & M32 - else: - text = f"s_xor_b32 s{d}, s{a}, s{b}" - - def fn(w): - w.s[d] = w.sr(a) ^ w.sr(b) - return Op(text, fn, "salu") - - def op_branch(self): - """A forward branch over a few ops: s_cbranch_execz / vccz / vccnz (taken per wave, as on hardware).""" - if self.in_branch: - return None - kind = self.r(("execz", "execz", "vccz", "vccnz")) - if kind != "execz" and "vcc" not in self.masks: - kind = "execz" - self.in_branch = True - body = self.program(self.rng.randrange(1, 5)) - self.in_branch = False - k = self.branch_id - self.branch_id += 1 - text = "\n\t".join([f"s_cbranch_{kind} @{k}"] + [o.text for o in body] + [f";@END{k}"]) - - def fn(w): - taken = {"execz": w.exec == 0, "vccz": w.vcc == 0, "vccnz": w.vcc != 0}[kind] - hyp = False - if not taken: - for o in body: - hyp |= bool(o.fn(w)) - return hyp - op = Op(text, fn, "branch") - op.tags = {"branch"} | {t for o in body for t in getattr(o, "tags", {o.tag})} - return op - - # ---- --ext: more wave64 ops (all return None in a wave32 program) ----------------------------------- - def scc_probe(self): - """(text, fn) of an s_cselect_b32 right after an op, so the op's SCC reaches a stored SGPR.""" - d, a, b = self.r(DATA_S), self.r(DATA_S), self.r(DATA_S) - - def fn(w, scc): - w.s[d] = w.sr(a) if scc else w.sr(b) - return f"\n\ts_cselect_b32 s{d}, s{a}, s{b}", fn - - def ext_mask(self): - """A mask that has been written, or EXEC.""" - return self.r(self.masks + ["exec"]) - - def op_scan64(self): - """s_bcnt1 / s_bcnt0 / s_ff1 / s_ff0 of a 64-bit mask; the counts also show their SCC (result != 0).""" - if self.W != 64: - return None - m, d = self.ext_mask(), self.r(DATA_S) - kind = self.r(("bcnt1", "bcnt0", "ff1", "ff0")) - ptext, pfn = self.scc_probe() - probe = kind.startswith("bcnt") - text = f"s_{kind}_i32_b64 s{d}, {mreg(64, m)}" + (ptext if probe else "") - - def fn(w): - x = w.mask(m) - if kind == "bcnt1": - r = popcount(x) - elif kind == "bcnt0": - r = 64 - popcount(x) - else: - y = x if kind == "ff1" else ~x & M64 - r = ((y & -y).bit_length() - 1) & M32 if y else M32 - w.s[d] = r - if probe: - pfn(w, r != 0) - return Op(text, fn, "scan64") - - def op_mask_scc(self): - """s_and/or/xor/andn2_b64 of two masks into a mask or VCC, and its SCC (result != 0).""" - if self.W != 64 or not self.masks: - return None - a, b = self.r(self.masks), self.r(self.masks) - d = self.r([16, 18, 20, "vcc"]) - kind = self.r(("and", "or", "xor", "andn2")) - ptext, pfn = self.scc_probe() - text = f"s_{kind}_b64 {mreg(64, d)}, {mreg(64, a)}, {mreg(64, b)}" + ptext - if d not in self.masks: - self.masks.append(d) - - def fn(w): - x, y = w.mask(a), w.mask(b) - r = {"and": x & y, "or": x | y, "xor": x ^ y, "andn2": x & ~y}[kind] & M64 - w.set_mask(d, r) - pfn(w, r != 0) - return Op(text, fn, "mask_scc") - - def op_exec_logic(self): - """The saveexec / wrexec family (RDNA2 ISA SOP1): saveexec D = EXEC, EXEC = f(S0, EXEC); wrexec - EXEC = f(S0, EXEC), D = EXEC; SCC = (EXEC != 0). D is one of the mask registers, not the saveexec stack of - op_saveexec. The forms that complement a whole mask stay out of a partial wave: they would turn on lanes - that do not exist.""" - if self.W != 64 or not self.masks: - return None - m, d = self.r(self.masks), self.r([16, 18, 20]) - kinds = ["and", "or", "xor", "andn1", "andn2"] - if self.full: - kinds += ["orn1", "orn2", "nand", "nor", "xnor"] - kind = self.r(kinds) - wr = kind in ("andn1", "andn2") and self.rng.random() < 0.4 - ptext, pfn = self.scc_probe() - text = f"s_{kind}_{'wrexec' if wr else 'saveexec'}_b64 {mreg(64, d)}, {mreg(64, m)}" + ptext - if d not in self.masks: - self.masks.append(d) - - def fn(w): - s, e = w.mask(m), w.exec - r = {"and": s & e, "or": s | e, "xor": s ^ e, "andn1": ~s & e, "andn2": s & ~e, "orn1": ~s | e, - "orn2": s | ~e, "nand": ~(s & e), "nor": ~(s | e), "xnor": ~(s ^ e)}[kind] & M64 - w.exec = r - w.set_mask(d, r if wr else e) - pfn(w, r != 0) - return Op(text, fn, "exec") - - def op_exec_mask(self): - """EXEC = a mask (s_mov_b64), not only the restore of a saved EXEC.""" - if self.W != 64 or not self.masks: - return None - m = self.r(self.masks) - - def fn(w): - w.exec = w.mask(m) - return Op(f"s_mov_b64 exec, {mreg(64, m)}", fn, "exec") - - def op_cselect64(self): - """s_cselect_b64 between two masks on the SCC of a scalar compare.""" - if self.W != 64 or not self.masks: - return None - a, b = self.ext_mask(), self.r(self.masks) - d = self.r([16, 18, 20, "vcc"]) - sa, sb = self.r(DATA_S), self.r(DATA_S) - text = f"s_cmp_lt_u32 s{sa}, s{sb}\n\ts_cselect_b64 {mreg(64, d)}, {mreg(64, a)}, {mreg(64, b)}" - if d not in self.masks: - self.masks.append(d) - - def fn(w): - w.set_mask(d, w.mask(a) if w.sr(sa) < w.sr(sb) else w.mask(b)) - return Op(text, fn, "cselect64") - - def op_mask_test(self): - """s_cmp_eq_u64 / s_cmp_lg_u64 of two masks, or s_bitcmp0/1_b64 of one lane's bit, seen through SCC.""" - if self.W != 64 or not self.masks: - return None - ptext, pfn = self.scc_probe() - if self.rng.random() < 0.5: - a, b = self.ext_mask(), self.ext_mask() - kind = self.r(("eq", "lg")) - text = f"s_cmp_{kind}_u64 {mreg(64, a)}, {mreg(64, b)}" + ptext - - def fn(w): - pfn(w, (w.mask(a) == w.mask(b)) == (kind == "eq")) - else: - m, one, lane = self.ext_mask(), self.rng.randrange(2), self.rng.randrange(64) - text = f"s_bitcmp{one}_b64 {mreg(64, m)}, {lane}" + ptext - - def fn(w): - pfn(w, (w.mask(m) >> lane & 1) == one) - return Op(text, fn, "mask_test") - - def op_bfm(self): - """s_bfm_b64 D, S0, S1: D = ((1 << S0[5:0]) - 1) << S1[5:0], into a mask, VCC or EXEC (full waves only).""" - if self.W != 64 or not self.full: - return None - d = self.r([16, 18, 20, "vcc", "exec"]) - form = self.r(("cc", "sc", "cs", "ss")) - sa, sb = self.r(DATA_S), self.r(DATA_S) - ka, kb = self.rng.randrange(65), self.rng.randrange(65) - text = (f"s_bfm_b64 {mreg(64, d)}, " + (f"s{sa}" if form[0] == "s" else str(ka)) + ", " + - (f"s{sb}" if form[1] == "s" else str(kb))) - if d not in self.masks and d != "exec": - self.masks.append(d) - - def fn(w): - size = (w.sr(sa) if form[0] == "s" else ka) & 63 - off = (w.sr(sb) if form[1] == "s" else kb) & 63 - w.set_mask(d, (((1 << size) - 1) << off) & M64) - return Op(text, fn, "exec" if d == "exec" else "bfm") - - def op_wqm(self): - """s_wqm_b64: every group of four bits with a bit set becomes 1111; SCC = (D != 0). Full waves only.""" - if self.W != 64 or not self.full or not self.masks: - return None - m, d = self.ext_mask(), self.r([16, 18, 20, "vcc"]) - ptext, pfn = self.scc_probe() - text = f"s_wqm_b64 {mreg(64, d)}, {mreg(64, m)}" + ptext - if d not in self.masks: - self.masks.append(d) - - def fn(w): - x, r = w.mask(m), 0 - for q in range(16): - if x >> (4 * q) & 15: - r |= 15 << (4 * q) - w.set_mask(d, r) - pfn(w, r != 0) - return Op(text, fn, "wqm") - - def op_carry(self): - """v_add_co / v_sub_co / v_subrev_co (and the _ci forms) with the carry in and out in SGPR pairs or VCC. - Carry out: bit l for an active lane, 0 for an inactive one; the carry in is read before it is written.""" - if self.W != 64: - return None - d, a, b = self.r(DATA_V), self.vsrc(), self.vsrc() - kind = self.r(("add_co", "sub_co", "subrev_co", "add_co_ci", "sub_co_ci", "subrev_co_ci")) - ci = kind.endswith("_ci") - if ci and not self.masks: - return None - mo = self.mask_name(write=True) - mi = self.r(self.masks) if ci else None - sfx = "e32" if mo == "vcc" and mi == "vcc" and self.rng.random() < 0.5 else "e64" # VOP2 only has VCC - text = f"v_{kind}_u32_{sfx} v{d}, {mreg(64, mo)}, v{a}, v{b}" + (f", {mreg(64, mi)}" if ci else "") - if mo not in self.masks: - self.masks.append(mo) - - def fn(w): - cin = w.mask(mi) if ci else 0 - vals, m = [], 0 - for l in range(w.size): - x, y, c = w.vr(a)[l], w.vr(b)[l], cin >> l & 1 - if kind.startswith("add"): - t = x + y + c - co = t >> 32 - else: - t = (y - x - c) if kind.startswith("subrev") else (x - y - c) - co = int(t < 0) - vals.append(t & M32) - if w.active(l) and co: - m |= 1 << l - w.vwrite(d, vals) - w.set_mask(mo, m) - return Op(text, fn, "carry") - - def op_bpermute(self): - """ds_bpermute_b32 vD, vAddr, vData: lane l reads vData of lane ((vAddr + offset) >> 2) & 31 of its own - 32-lane half; a source lane that is off in EXEC (or missing from a partial wave) reads 0.""" - if self.W != 64: - return None - d, ad, dat = self.r(DATA_V), self.vsrc(), self.vsrc() - off = self.r((0, 0, 4, 60, 128, 252, 65532)) - text = f"ds_bpermute_b32 v{d}, v{ad}, v{dat}" + (f" offset:{off}" if off else "") + DS_WAIT - - def fn(w): - vals = [] - for l in range(w.size): - sl = (l & 32) | (((w.vr(ad)[l] + off) >> 2) & 31) - vals.append(w.vr(dat)[sl] if w.active(sl) else 0) - w.vwrite(d, vals) - return Op(text, fn, "bpermute") - - def op_permute(self): - """ds_permute_b32 vD, vAddr, vData: every lane on in EXEC sends vData to lane ((vAddr + offset) >> 2) & 31 - of its own half; a lane nobody sends to gets 0; several senders: the highest lane wins (measured). Half of - the time the addresses are a permutation (lane * odd + c), else any data VGPR.""" - if self.W != 64: - return None - d, dat = self.r(DATA_V), self.vsrc() - if self.rng.random() < 0.5: - k, c = self.r((1, 3, 5, 7, 9, 11, 13, 15, 17, 31)), self.rng.randrange(64) - ad, off = PERM_V, self.r((0, 0, 4, 124)) - pre = f"v_mad_u32_u24 v{ad}, v1, {k}, {c}\n\tv_lshlrev_b32_e32 v{ad}, 2, v{ad}\n\t" - else: - k = c = None - ad, off, pre = self.vsrc(), 0, "" - text = pre + f"ds_permute_b32 v{d}, v{ad}, v{dat}" + (f" offset:{off}" if off else "") + DS_WAIT - - def fn(w): - if k is not None: - w.vwrite(ad, [((l * k + c) << 2) & M32 for l in range(w.size)]) - vals = [0] * w.size - for l in range(w.size): - if w.active(l): - vals[(l & 32) | (((w.vr(ad)[l] + off) >> 2) & 31)] = w.vr(dat)[l] - w.vwrite(d, vals) - return Op(text, fn, "permute") - - def op_swizzle(self): - """ds_swizzle_b32 vD, vS offset:swizzle(...): QUAD_PERM inside each group of four lanes; the other modes - are source lane = ((lane & and) | or) ^ xor inside each group of 32. A source lane that is off in EXEC - reads 0 (measured; the translator does that with #2780, so a program that reaches it is reported apart).""" - if self.W != 64: - return None - d, v = self.r(DATA_V), self.vsrc() - mode = self.r(("quad", "bits", "bits", "swap", "reverse", "broadcast")) - and_m, or_m, xor_m = 31, 0, 0 - if mode == "quad": - q = [self.rng.randrange(4) for _ in range(4)] - sw = f"swizzle(QUAD_PERM, {', '.join(map(str, q))})" - elif mode == "bits": - chars = [self.r("01pi") for _ in range(5)] - and_m = 0 - for i, ch in enumerate(chars): # bit 4 first: p = keep, i = invert, 0 / 1 = force - bit = 1 << (4 - i) - and_m |= bit if ch in "pi" else 0 - xor_m |= bit if ch == "i" else 0 - or_m |= bit if ch == "1" else 0 - sw = f'swizzle(BITMASK_PERM, "{"".join(chars)}")' - elif mode == "swap": - xor_m = self.r((1, 2, 4, 8, 16)) - sw = f"swizzle(SWAP,{xor_m})" - elif mode == "reverse": - n = self.r((2, 4, 8, 16, 32)) - xor_m = n - 1 - sw = f"swizzle(REVERSE,{n})" - else: - n = self.r((2, 4, 8, 16, 32)) - or_m = self.rng.randrange(n) - and_m = ~(n - 1) & 31 - sw = f"swizzle(BROADCAST,{n},{or_m})" - text = f"ds_swizzle_b32 v{d}, v{v} offset:{sw}" + DS_WAIT - - def fn(w): - vals, hyp = [], False - for l in range(w.size): - sl = (l & ~3) | q[l & 3] if mode == "quad" else (l & ~31) | (((l & 31 & and_m) | or_m) ^ xor_m) - if w.active(sl): - vals.append(w.vr(v)[sl]) - else: - vals.append(0) - hyp |= bool(w.active(l)) - w.vwrite(d, vals) - return hyp - return Op(text, fn, "swizzle") - - def op_lane_wrap(self): - """v_readlane / v_writelane with an SGPR lane select of 64 or more: wave64 uses S1[5:0].""" - if self.W != 64: - return None - lane = self.lane() - enc = lane + 64 * self.rng.randrange(1, 1 << 20) - if self.rng.random() < 0.5: - d, v = self.r(DATA_S), self.vsrc() - text = f"s_mov_b32 s{SEL}, {enc}\n\tv_readlane_b32 s{d}, v{v}, s{SEL}" - - def fn(w): - w.s[SEL] = enc - w.s[d] = w.vr(v)[lane] - else: - d, s = self.r(DATA_V), self.r(DATA_S) - text = f"s_mov_b32 s{SEL}, {enc}\n\tv_writelane_b32 v{d}, s{s}, s{SEL}" - - def fn(w): - w.s[SEL] = enc - if w.exists >> lane & 1: - w.vr(d)[lane] = w.sr(s) - return Op(text, fn, "lane_wrap") - - LOOP_BODY = ("op_readfirstlane", "op_bcnt", "op_mbcnt", "op_valu", "op_valu", "op_readlane", "op_writelane", - "op_cmp", "op_cndmask", "op_bpermute", "op_permute", "op_carry", "op_salu", "op_mask_salu", - "op_scan64", "op_cselect64", "op_mask_test") - - def op_loop(self): - """A loop in the shape LLVM's SI_LOOP gives: every lane has its own trip count (1 to 8), a lane that is - done joins the break mask, s_andn2_b64 takes it out of EXEC and s_cbranch_execnz closes the loop while a - lane is left; EXEC comes back from the break mask after it. The body is one to four ops that do not write - EXEC, then the count of the lanes still running added to a data VGPR, so every iteration shows.""" - if self.W != 64 or self.in_branch: - return None - src, trips = self.vsrc(), self.r((1, 3, 3, 7)) - self.in_branch = True # no branch and no second loop inside - body, n = [], self.rng.randrange(1, 5) - while len(body) < n: - o = getattr(self, self.r(self.LOOP_BODY))() - if o is not None: - body.append(o) - sd, vx = self.r(DATA_S), self.r(DATA_V) - self.in_branch = False - k = self.branch_id - self.branch_id += 1 - lim, it = LOOP_V - brk, done = LOOP_S - lines = [f"v_and_b32_e32 v{lim}, {trips}, v{src}", f"v_mov_b32_e32 v{it}, 0", - f"s_mov_b64 {mreg(64, brk)}, 0", f";@LOOP{k}"] - lines += [o.text for o in body] - lines += [f"s_bcnt1_i32_b64 s{sd}, exec", f"v_add_nc_u32_e32 v{vx}, s{sd}, v{vx}", - f"v_cmp_ge_u32_e64 {mreg(64, done)}, v{it}, v{lim}", f"v_add_nc_u32_e32 v{it}, 1, v{it}", - f"s_or_b64 {mreg(64, brk)}, {mreg(64, done)}, {mreg(64, brk)}", - f"s_andn2_b64 exec, exec, {mreg(64, brk)}", f"s_cbranch_execnz @-{k}", - f"s_or_b64 exec, exec, {mreg(64, brk)}"] - - def fn(w): - hyp = False - w.vwrite(lim, [x & trips for x in w.vr(src)]) - w.vwrite(it, [0] * w.size) - broke = 0 - for _ in range(trips + 2): - for o in body: - hyp |= bool(o.fn(w)) - w.s[sd] = popcount(w.exec) - w.vwrite(vx, [w.sr(sd) + x for x in w.vr(vx)]) - m = 0 - for l in range(w.size): - if w.active(l) and w.vr(it)[l] >= w.vr(lim)[l]: - m |= 1 << l - w.vwrite(it, [x + 1 for x in w.vr(it)]) - broke |= m - w.exec &= ~broke - if not w.exec: - break - else: - raise AssertionError("loop model did not end") - w.set_mask(brk, broke) - w.set_mask(done, m) - w.exec |= broke - return hyp - op = Op("\n\t".join(lines), fn, "loop") - op.tags = {"loop"} | {t for o in body for t in getattr(o, "tags", {o.tag})} - return op - - EXT_WEIGHTS = (("op_scan64", 3), ("op_mask_scc", 3), ("op_exec_logic", 3), ("op_exec_mask", 1), - ("op_cselect64", 2), ("op_mask_test", 3), ("op_bfm", 2), ("op_wqm", 2), ("op_carry", 4), - ("op_bpermute", 3), ("op_permute", 4), ("op_swizzle", 3), ("op_lane_wrap", 2), ("op_loop", 3)) - - WEIGHTS = (("op_branch", 3), ("op_cmp", 5), ("op_cmpx", 2), ("op_exec_const", 2), ("op_saveexec", 2), ("op_restore", 2), - ("op_readlane", 4), ("op_writelane", 3), ("op_readfirstlane", 3), ("op_bcnt", 3), ("op_mbcnt", 3), - ("op_mbcnt_data", 1), ("op_cndmask", 2), ("op_maskdata", 1), ("op_mask_salu", 2), - ("op_permlane", 3), ("op_valu", 3), ("op_salu", 1), ("op_dpp", 6)) - - def program(self, n): - table = [kw for kw in self.WEIGHTS if kw[0] != "op_dpp" or self.dpp] # seeds stay stable without --dpp - if self.ext: # and without --ext - table += self.EXT_WEIGHTS - names = [k for k, _ in table] - weights = [w for _, w in table] - ops = [] - while len(ops) < n: - op = getattr(self, self.rng.choices(names, weights)[0])() - if op is not None: - ops.append(op) - return ops - - -def prologue(rng, wave): - """Lane id in v1, data in v2-v7 and s8-s15, entry EXEC saved. Returns (text lines, init fn).""" - lines = ["v_mbcnt_lo_u32_b32 v1, -1, 0"] - if wave == 64: - lines.append("v_mbcnt_hi_u32_b32 v1, -1, v1") - lines.append(f"s_mov_b64 s[{ENTRY}:{ENTRY + 1}], exec") - else: - lines.append(f"s_mov_b32 s{ENTRY}, exec_lo") - coef = [] - for r in DATA_V: - a, b = rng.randrange(1, 65), rng.getrandbits(32) - coef.append((r, a, b)) - lines.append(f"v_mad_u32_u24 v{r}, v0, {a}, 0x{b:x}") - svals = [(r, rng.getrandbits(32)) for r in DATA_S] - lines += [f"s_mov_b32 s{r}, 0x{v:x}" for r, v in svals] - # Every mask register holds a mask on every path, as in compiled code: a branch may skip the v_cmp that - # writes one, and a register that is undefined on one path has no defined value after the join. - mov, ex = ("s_mov_b64", "exec") if wave == 64 else ("s_mov_b32", "exec_lo") - lines += [f"{mov} {mreg(wave, m)}, 0" for m in ("vcc", 16, 18, 20)] - lines += [f"{mov} {mreg(wave, m)}, {ex}" for m in SAVE] - - def init(waves): - for wi, w in enumerate(waves): - tid = [wi * w.size + l for l in range(w.size)] - w.v[0] = tid - w.v[1] = list(range(w.size)) - for r, a, b in coef: - w.v[r] = [((t & 0xFFFFFF) * a + b) & M32 for t in tid] - for r, v in svals: - w.s[r] = v - w.set_mask(ENTRY, w.exists) - for m in ("vcc", 16, 18, 20): - w.set_mask(m, 0) - for m in SAVE: - w.set_mask(m, w.exists) - return lines, init - - -def epilogue(wave, hw=False): - """hw=True stores with global_store_b32 through the output pointer in s[2:3] (hw_oracle) instead of a buffer.""" - k = len(OUT_REGS) - lines = [f"s_mov_b64 exec, s[{ENTRY}:{ENTRY + 1}]" if wave == 64 else f"s_mov_b32 exec_lo, s{ENTRY}", - f"v_mul_u32_u24_e32 v22, {4 * k}, v0"] - for j, (kind, r) in enumerate(OUT_REGS): - lines.append(f"v_mov_b32_e32 v20, {kind}{r}") - lines.append(f"global_store_b32 v22, v20, s[2:3] offset:{4 * j}" if hw else - f"buffer_store_dword v20, v22, s[0:3], 0 offen offset:{4 * j}") - lines.append("s_endpgm") - return lines - - -class Program: - label = None # --dpp-sweep: what the case tests, printed with a failure - family = None # --dpp-sweep: the control family, for the per-family summary - - def __init__(self, name, wave, group, pro, init, ops): - self.name, self.wave, self.group, self.pro, self.init, self.ops = name, wave, group, pro, init, ops - - def source(self, ops=None): - ops = self.ops if ops is None else ops - mattr = "+wavefrontsize64,-wavefrontsize32" if self.wave == 64 else "+wavefrontsize32,-wavefrontsize64" - head = [f"; {self.name}: crosslane_fuzz, wave{self.wave}, group {self.group}", - f"; group: {self.group},1,1", f"; mattr: {mattr}"] - body = self.pro + [o.text for o in ops] + epilogue(self.wave) - return "\n".join(head + body) + "\n" - - def hw_lines(self, ops=None, guard=True): - """The program as a native kernel body for tools/hw_oracle: branch placeholders become labels, the stores go - through the output pointer, and with guard each instruction is followed by s_nop 7. The ISA model has no - hazards; the real unit needs wait states after some VALU writes of SGPRs, VCC and EXEC (GFX10 and GFX11 - both), and compiled code gets them from the compiler.""" - ops = self.ops if ops is None else ops - out = [] - for text in self.pro + [o.text for o in ops] + epilogue(self.wave, hw=True): - for ln in (x.strip() for x in text.split("\n")): - m = re.fullmatch(r";@(END|LOOP)(\d+)", ln) - if m: - out.append(f".L{self.name}_{'B' if m.group(1) == 'LOOP' else ''}{m.group(2)}:") - continue - ln = re.sub(r"^(s_cbranch_\w+) @(-?)(\d+)$", - lambda b: f"{b.group(1)} .L{self.name}_{'B' if b.group(2) else ''}{b.group(3)}", ln) - out.append(ln) - if guard and ln != "s_endpgm": - out.append("s_nop 7") - return out - - def expected(self, ops=None): - """{(thread, word): value}, plus the set of ops whose result depends on a hypothesis.""" - ops = self.ops if ops is None else ops - n = (self.group + self.wave - 1) // self.wave - waves = [] - for wi in range(n): - cnt = min(self.wave, self.group - wi * self.wave) - waves.append(Wave(self.wave, (1 << cnt) - 1)) - self.init(waves) - hyp = set() - for i, o in enumerate(ops): - if o.apply(waves): - hyp.add(i) - out = {} - for wi, w in enumerate(waves): - for lane in range(w.size): - if not w.exists >> lane & 1: - continue - tid = wi * w.size + lane - for j, (kind, r) in enumerate(OUT_REGS): - out[(tid, j)] = w.vr(r)[lane] if kind == "v" else w.sr(r) - return out, hyp - - -def make_program(seed, wave, n_ops, **kw): - rng = random.Random(seed) - if wave == 64: - group = rng.choice((64, 64, 128, 40, 100, 192)) - else: - group = rng.choice((32, 32, 64, 20, 50, 96)) - g = Gen(rng, wave, group, **kw) - pro, init = prologue(rng, wave) - ops = g.program(n_ops) - return Program(f"cs_xl{wave}_{seed}", wave, group, pro, init, ops) - - -# ---- running on the GPU --------------------------------------------------------------------------------- -def assemble(mc, prog, src, disasm, fssm): - import compute_fixture - mattr = "+wavefrontsize64,-wavefrontsize32" if prog.wave == 64 else "+wavefrontsize32,-wavefrontsize64" - cmd = mc + ["-triple=amdgcn--amdpal", "-mcpu=gfx1013", f"-mattr={mattr}", "-show-encoding"] - if "@" in src: - src = resolve_branches(cmd, prog, src) - r = mc_command.run(cmd, input=src, capture_output=True, text=True) - if r.returncode or "error:" in r.stderr: - raise RuntimeError(f"{prog.name} did not assemble:\n{r.stderr}\n{src}") - code = "".join(ln for ln in r.stdout.splitlines(keepends=True) if not ln.lstrip().startswith(".")) - with open(os.path.join(disasm, prog.name + ".s"), "w", encoding="utf-8", newline="\n") as f: - f.write(f"; {prog.name} crosslane_fuzz\n{code}") - asm_path = os.path.join(fssm, prog.name + ".asm") - with open(asm_path, "w", encoding="utf-8", newline="\n") as f: - f.write(src) - with open(os.path.join(fssm, prog.name + ".fssm"), "wb") as f: - f.write(compute_fixture.compute_header(asm_path)) - os.remove(asm_path) - - -def branch_offsets(lines, size_at): - """lines with every `s_cbranch_* @k` replaced by the dword offset to its `;@ENDk` line below it, and every - `@-k` (--ext loops) by the negative offset back to its `;@LOOPk` line above it. size_at: line index -> the - instruction's size in dwords. A branch offset counts from the instruction after the branch.""" - out = list(lines) - for i, ln in enumerate(lines): - m = re.search(r"@(-?)(\d+)$", ln.strip()) - if not m: - continue - if m.group(1): - head = next(j for j in range(i - 1, -1, -1) if lines[j].strip() == f";@LOOP{m.group(2)}") - off = -sum(size_at.get(j, 0) for j in range(head + 1, i + 1)) - else: - end = next(j for j in range(i + 1, len(lines)) if lines[j].strip() == f";@END{m.group(2)}") - off = sum(size_at.get(j, 0) for j in range(i + 1, end)) - out[i] = ln[:ln.rindex("@")] + str(off) - return out - - -def resolve_branches(cmd, prog, src): - """Replace each `s_cbranch_* @k` with the dword offset to its `;@ENDk` line (and `@-k` with the offset back - to `;@LOOPk`): assemble once with offset 0, take each instruction's size from its encoding, and sum the - sizes in between (branch_offsets).""" - lines = src.splitlines() - insns = [i for i, ln in enumerate(lines) if ln.strip() and not ln.strip().startswith(";")] - first = "\n".join(re.sub(r"@-?\d+$", "0", ln) for ln in lines) + "\n" - r = mc_command.run(cmd, input=first, capture_output=True, text=True) - if r.returncode or "error:" in r.stderr: - raise RuntimeError(f"{prog.name} did not assemble:\n{r.stderr}\n{first}") - sizes = [len(re.findall(r"0x[0-9a-f]{2}", m)) // 4 for m in re.findall(r"encoding: \[([^\]]*)\]", r.stdout)] - if len(sizes) != len(insns): - raise RuntimeError(f"{prog.name}: {len(sizes)} encodings for {len(insns)} instructions") - return "\n".join(branch_offsets(lines, dict(zip(insns, sizes)))) + "\n" - - -def translate(work, emulate): - out = os.path.join(work, "spirv_emu" if emulate else "spirv_nat") - cmd = [sys.executable, "-I", TRANSLATOR[0], os.path.join(work, "disasm"), "--out", out] - if emulate: - cmd.append("--wave64-emulate") - r = subprocess.run(cmd, capture_output=True, text=True) - return out, r.stdout + r.stderr - - -def gpu_env(prog, emulate, dump, base=None): - """vk_compute_test's environment (FUZZ-6, tools/lds_fuzz.py): VKC_OUT_WORDS sizes the buffer, VKC_DUMP gets its - raw bytes. A wave32 program, or a wave64 one translated with --wave64-emulate, is written for 32-wide subgroups, - so it asks for them with VKC_SUBGROUP_SIZE=32, as lds_fuzz.py and valu_fuzz.py do (FUZZ-13): on AMD, whose - compute default is 64, a group over 32 would otherwise run as one 64-wide subgroup and mismatch in wave 1. - A native wave64 program keeps the device default (--w64-native runs it on whatever the GPU has).""" - env = dict(os.environ if base is None else base, VKC_OUT_WORDS=str(max(prog.group * len(OUT_REGS), 64)), - VKC_DUMP=dump) - if prog.wave == 32 or emulate: - env["VKC_SUBGROUP_SIZE"] = "32" - return env - - -class HarnessError(RuntimeError): - """vk_compute_test did not give a result for one program: it hung, crashed or wrote no dump.""" - - -class Unpinned(RuntimeError): - """vk_compute_test ran a wave32 program but couldn't pin the 32-lane subgroups it needs, so its words came from - another wave size (Mesa llvmpipe: 8 lanes) and are no evidence either way: the program is skipped. Programs - translated with --wave64-emulate use no subgroup operations, so they are judged at any size.""" - - -GPU_TIMEOUT = 60 # seconds for one program; a translated program that never ends shows up as this - - -def run_gpu(exe, spv, prog, work, emulate): - dump = os.path.join(work, "dump.bin") - if os.path.exists(dump): - os.remove(dump) # never compare a stale dump - env = gpu_env(prog, emulate, dump) - try: - r = subprocess.run([exe, spv, "1", "dump"], capture_output=True, text=True, env=env, timeout=GPU_TIMEOUT) - except subprocess.TimeoutExpired: - raise HarnessError(f"vk_compute_test timed out after {GPU_TIMEOUT} s") from None - import compute_fixture - lanes = compute_fixture.unpinned_subgroup(r.stdout + r.stderr) if prog.wave == 32 else None - if lanes: - raise Unpinned(f"the device can't run it at {lanes} lanes (vk_compute_test: compute subgroup size: {lanes} " - "not available)") - if not os.path.exists(dump): - detail = " ".join(f"{r.stdout}{r.stderr}".split()) - raise HarnessError(f"vk_compute_test gave no dump (exit {r.returncode}){': ' + detail if detail else ''}") - with open(dump, "rb") as f: - data = f.read() - return list(struct.unpack(f"<{len(data) // 4}I", data)) - - -def compare(prog, got, ops=None): - exp, hyp = prog.expected(ops) - bad = [] - for (tid, j), v in sorted(exp.items()): - g = got[tid * len(OUT_REGS) + j] - if g != v: - bad.append((tid, j, v, g)) - return bad, hyp - - -def describe(prog, bad, limit=6): - lines = [] - for tid, j, v, g in bad[:limit]: - kind, r = OUT_REGS[j] - lines.append(f" thread {tid} (wave {tid // prog.wave}, lane {tid % prog.wave}) {kind}{r}: " - f"expected 0x{v:08x}, got 0x{g:08x}") - if len(bad) > limit: - lines.append(f" ... {len(bad) - limit} more") - return "\n".join(lines) - - -def minimize(prog, mode, ctx): - """Greedy: drop ops while the program still mismatches (same mode). Returns the reduced op list.""" - ops = list(prog.ops) - i = len(ops) - 1 - while i >= 0: - trial = ops[:i] + ops[i + 1:] - if still_fails(prog, trial, mode, ctx): - ops = trial - i -= 1 - return ops - - -def still_fails(prog, ops, mode, ctx): - mc, exe = ctx - with tempfile.TemporaryDirectory(prefix="xlmin-") as work: - for d in ("disasm", "fssm"): - os.mkdir(os.path.join(work, d)) - try: - assemble(mc, prog, prog.source(ops), os.path.join(work, "disasm"), os.path.join(work, "fssm")) - except RuntimeError: - return False - spdir, _ = translate(work, mode == "emulate") - spv = os.path.join(spdir, prog.name + ".spv") - if not os.path.exists(spv): - return False - try: - bad, hyp = compare(prog, run_gpu(exe, spv, prog, work, mode == "emulate"), ops) - except (HarnessError, Unpinned): - return False # a reduction that hangs or crashes is not the mismatch being reduced - return bool(bad) and not hyp - - -MODES = ("native", "emulate") - - -def parse_modes(text): - """--modes: a comma list of native and emulate, or both. Any other word is an error: the run loop only knows - these two, and an unknown one used to run every program natively, wave64 included.""" - modes = [] - for word in (w.strip() for w in text.split(",")): - if not word: - continue - for mode in MODES if word == "both" else (word,): - if mode not in MODES: - raise argparse.ArgumentTypeError(f"unknown mode {word!r} (use native, emulate or both)") - if mode not in modes: - modes.append(mode) - if not modes: - raise argparse.ArgumentTypeError("no mode given (use native, emulate or both)") - return modes - - -def _at_least_one(text): - """--programs and --ops: a count below 1 ran nothing (or a program of no ops) and still printed a summary, which - reads as a clean pass. Refuse it as a usage error instead, as the other fuzzers do.""" - value = int(text) - if value < 1: - raise argparse.ArgumentTypeError(f"must be at least 1 (got {value})") - return value - - -def main(): - ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) - ap.add_argument("--programs", type=_at_least_one, default=100, - help="programs per wave (at least 1; default 100)") - ap.add_argument("--seed", type=int, default=1) - ap.add_argument("--ops", type=_at_least_one, default=24, help="ops per program (at least 1; default 24)") - ap.add_argument("--wave", choices=("32", "64", "both"), default="both") - ap.add_argument("--modes", type=parse_modes, default="native,emulate", - help="native, emulate (wave64 only), or both (the default)") - ap.add_argument("--w64-native", action="store_true", - help="also run wave64 programs without --wave64-emulate (on a 32-wide subgroup that is the " - "documented cross-half approximation, so mismatches are expected there)") - ap.add_argument("--no-maskdata", action="store_true", help="leave out masks read as data (#293)") - ap.add_argument("--no-w32-hi-lanes", action="store_true", help="wave32 lane selects stay below 32") - ap.add_argument("--exe", default=os.path.join(ROOT, "runtime", "build", "vk_compute_test" + - (".exe" if os.name == "nt" else ""))) - ap.add_argument("--keep", help="copy failing programs (.asm) here") - ap.add_argument("--minimize", action="store_true", help="reduce each failing program") - ap.add_argument("--permlane-fetch-inactive", action="store_true", - help="model an inactive permlane source as read (FI = 1) instead of the hypothesis") - ap.add_argument("--dpp", action="store_true", help="also generate DPP16 / DPP8 ops") - ap.add_argument("--ext", action="store_true", - help="wave64 programs also get carries, ds_bpermute/ds_permute/ds_swizzle, lane selects of 64 " - "and up, b64 mask SALU with SCC probes, the saveexec/wrexec family, s_bfm_b64, s_wqm_b64 " - "and SI_LOOP-shaped loops (wave32 programs and seeds without the flag are unchanged)") - ap.add_argument("--dpp-sweep", action="store_true", - help="instead of random programs, one program per DPP case: every DPP16 control x bound_ctrl x " - "fi x EXEC pattern, all row_mask / bank_mask pairs, and a set of DPP8 selects " - "(--programs, --seed, --ops and --dpp are ignored; --wave applies)") - ap.add_argument("--oracle", default="translator", - help="comma-separated: translator (default; needs llvm-mc, the Vulkan SDK and vk_compute_test), hw " - "(natively on the AMD GPU, wave32 and native wave64; tools/hw_oracle/), or translator,hw") - ap.add_argument("--hw-arch", default=None, help="GPU architecture to assemble for (default: detected)") - ap.add_argument("--no-hw-guard", action="store_true", - help="no s_nop 7 after each instruction in the native kernels (hazards then show up as mismatches)") - ap.add_argument("--translator", help="rdna2spirv.py to test (default: the one next to this file)") - ap.add_argument("--self-test", action="store_true") - args = ap.parse_args() - if not os.path.isfile(args.exe): # a Visual Studio build puts it in a configuration subfolder - folder, name = os.path.split(args.exe) - for config in ("RelWithDebInfo", "Release"): - if os.path.isfile(os.path.join(folder, config, name)): - args.exe = os.path.join(folder, config, name) - break - # Windows' CreateProcess searches for a relative path written with "/" that doesn't start with "./" or "../" - # (runtime/build/x.exe) instead of taking it from the working directory, though os.path.isfile does, so such an - # --exe passed the check below and the first GPU run ended in a FileNotFoundError traceback. An absolute path - # (abspath also turns "/" into "\" there) runs from anywhere. - args.exe = os.path.abspath(args.exe) - global PERMLANE_FETCH_INACTIVE - PERMLANE_FETCH_INACTIVE = args.permlane_fetch_inactive - if args.translator: - TRANSLATOR[0] = os.path.abspath(args.translator) - if args.self_test: - return self_test() - backends = tuple(dict.fromkeys(t.strip() for t in args.oracle.split(","))) - if not backends or any(t not in ("translator", "hw") for t in backends): - ap.error("--oracle takes translator, hw or translator,hw") - if args.wave == "32" and "native" not in args.modes: - # emulate runs a wave64 program as two 32-lane halves, so a wave32-only selection has nothing to run: the run - # used to end after a bare `summary:` with exit 0, the same false pass #1452 fixed for a count below 1. - # Only when emulate is the sole mode: with the default (native,emulate) native runs every wave32 program. - ap.error("--modes emulate needs wave64 programs: with --wave 32 nothing runs (use --wave 64 or both)") - if args.wave == "64" and "emulate" not in args.modes and not args.w64_native: - # A wave64 program only runs natively when --w64-native asks for the documented cross-half approximation, so - # this combination was empty in the same silent way. With the default modes emulate runs them. - ap.error("--wave 64 --modes native runs nothing without --w64-native; pass it to run the documented " - "cross-half approximation, or use --modes emulate") - if "translator" in backends and not os.path.isfile(args.exe): # before any program is generated or run - sys.exit(f"vk_compute_test not found at {args.exe} or in its RelWithDebInfo/Release folder; build it first " - "(cmake --build --target vk_compute_test) or give its path with --exe") - oracle = None - if "hw" in backends: - from hw_oracle import runner - try: - oracle = runner.open_oracle(arch=args.hw_arch) - except runner.Unavailable as e: - print(f"hardware oracle unavailable: {e}") - return 77 - print(f"hardware oracle: {oracle.device}") - waves = (32, 64) if args.wave == "both" else (int(args.wave),) - modes = args.modes - progs = [] - if args.dpp_sweep: - for wave in waves: - progs += dpp_sweep_programs(wave) - print(f"dpp sweep: {len(progs)} cases") - for i in range(0 if args.dpp_sweep else args.programs): - wave = waves[i % len(waves)] - progs.append(make_program(args.seed * 100003 + i, wave, args.ops, allow_maskdata=not args.no_maskdata, - wave32_hi_lanes=not args.no_w32_hi_lanes, dpp=args.dpp, ext=args.ext)) - stats = {} - fails = [] - try: - if oracle: - run_hw(oracle, progs, stats, fails, guard=not args.no_hw_guard) - mc = None - if "translator" in backends: - import mc_command - mc = mc_command.mc_command() - run_translator(args, mc, progs, waves, modes, stats, fails) - tr_status = {} - for p, mode, what, bad in fails: - if mode != "hw": - tr_status.setdefault(p.name, []).append(f"{mode}: {what}") - for p, mode, what, bad in fails: - if mode == "hw" and bad and "translator" in backends: - print(f"{p.name}: hardware and reference differ; translator: " + - ("; ".join(tr_status.get(p.name, [])) or "matches the reference")) - for p, mode, what, bad in fails: - tags = sorted({t for o in p.ops for t in getattr(o, 'tags', {o.tag})}) - print(f"{p.name} [{mode}] {what}; group {p.group}; ops: {', '.join(tags)}") - if p.label: - print(f" case: {p.label}") - if bad: - print(describe(p, bad)) - if args.keep: - os.makedirs(args.keep, exist_ok=True) - with open(os.path.join(args.keep, f"{p.name}_{mode}.asm"), "w", encoding="utf-8", newline="\n") as f: - f.write(kept_source(p, mode, None, not args.no_hw_guard)) - if args.minimize and bad and what.startswith("mismatch"): - if mode == "hw": - ops = minimize_hw(p, oracle, not args.no_hw_guard) - elif mc is not None: - ops = minimize(p, mode, (mc, args.exe)) - else: - continue - hyp_ops = p.expected(ops)[1] - print(" minimized:\n\t" + "\n\t".join(o.text + (" ; hypothesis op" if i in hyp_ops else "") - for i, o in enumerate(ops))) - if args.keep: - with open(os.path.join(args.keep, f"{p.name}_{mode}_min.asm"), "w", encoding="utf-8", newline="\n") as f: - f.write(kept_source(p, mode, ops, not args.no_hw_guard)) - finally: - if oracle: - oracle.close() - print("summary:") - for key, st in sorted(stats.items()): - print(f" {key}: " + ", ".join(f"{k} {v}" for k, v in st.items())) - if args.dpp_sweep: - print("dpp sweep by family (cases, failing per oracle mode):") - failing = {} - for p, mode, what, bad in fails: - failing.setdefault((p.wave, p.family, mode), set()).add(p.name) - for wave in waves: - for family in dict.fromkeys(p.family for p in progs if p.wave == wave): - n = sum(p.wave == wave and p.family == family for p in progs) - bad = ", ".join(f"{m} {len(s)}" for (w, f, m), s in sorted(failing.items()) - if w == wave and f == family) or "none" - print(f" wave{wave} {family}: {n} cases; failing: {bad}") - if any(st["mismatch"] or st["rejected"] for st in stats.values()): - return 1 - if any(st.get("harness_errors") for st in stats.values()): - return 2 - if stats and not any(st["match"] or st["hyp_only"] for st in stats.values()): - print("no program ran: every one was skipped") - return 2 - return 0 - - -def kept_source(prog, mode, ops, guard): - """What --keep writes: for a hardware failure the kernel body that actually ran, else the translator input.""" - if mode == "hw": - return "\n".join(prog.hw_lines(ops, guard)) + "\n" - return prog.source(ops) - - -def hw_skip_reason(prog, arch): - """Why a program cannot be compared on this GPU, or None. Nothing the generator emits differs between GFX10 and - GFX11 in a way that changes a result (checked by running it; docs/shader_validation.md lists what was looked - at), so the only skips are assembler rejections, which the runner reports.""" - return None - - -def run_hw(oracle, progs, stats, fails, guard=True): - """Run every program natively (wave32 or wave64 as the program is, its real group size, one thread per lane) - and compare all stored words with the model.""" - from hw_oracle import asm - kernels, which = [], [] - for p in progs: - st = stats.setdefault(f"wave{p.wave} hw", {"programs": 0, "match": 0, "mismatch": 0, "hyp_only": 0, - "hyp_confirmed": 0, "rejected": 0}) - st["programs"] += 1 - why = hw_skip_reason(p, oracle.arch) - if why: - st["rejected"] += 1 - fails.append((p, "hw", f"skipped: {why}", None)) - continue - kernels.append(asm.Kernel(p.hw_lines(guard=guard), p.wave, p.group, p.group * len(OUT_REGS), raw=True)) - which.append(p) - for p, got in zip(which, oracle.run(kernels)): - st = stats[f"wave{p.wave} hw"] - if isinstance(got, str): - st["rejected"] += 1 - fails.append((p, "hw", got, None)) - continue - bad, hyp = compare(p, got) - if not bad: - st["match"] += 1 - st["hyp_confirmed"] += bool(hyp) - for kind in sorted({t for i in hyp for t in getattr(p.ops[i], "tags", {p.ops[i].tag}) - if t in ("permlane", "dpp", "swizzle")}): - st["hyp_" + kind] = st.get("hyp_" + kind, 0) + 1 - else: - # On the hardware a failing hypothesis is a falsified claim, and it could hide a model bug elsewhere in - # the program, so it is a mismatch like any other (hyp_only counts the ones that had a hypothesis op). - st["mismatch"] += 1 - if hyp: - st["hyp_only"] += 1 - fails.append((p, "hw", "mismatch" + (" (program has a hypothesis op)" if hyp else ""), bad)) - - -def minimize_hw(prog, oracle, guard=True): - """Drop ops while the program still differs on the hardware.""" - from hw_oracle import asm - - def fails_with(ops): - got = oracle.run([asm.Kernel(prog.hw_lines(ops, guard), prog.wave, prog.group, - prog.group * len(OUT_REGS), raw=True)])[0] - if isinstance(got, str): - return False - return bool(compare(prog, got, ops)[0]) - ops = list(prog.ops) - for i in range(len(ops) - 1, -1, -1): - trial = ops[:i] + ops[i + 1:] - if fails_with(trial): - ops = trial - return ops - - -def run_translator(args, mc, progs, waves, modes, stats, fails): - with tempfile.TemporaryDirectory(prefix="crosslane-") as work: - disasm, fssm = os.path.join(work, "disasm"), os.path.join(work, "fssm") - os.mkdir(disasm) - os.mkdir(fssm) - for p in progs: - assemble(mc, p, p.source(), disasm, fssm) - for mode in modes: - if mode == "emulate" and 64 not in waves: - continue - spdir, log = translate(work, mode == "emulate") - for p in progs: - if mode == "emulate" and p.wave != 64: - continue - if mode == "native" and p.wave == 64 and not args.w64_native: - continue - key = f"wave{p.wave} {mode}" - st = stats.setdefault(key, {"programs": 0, "match": 0, "mismatch": 0, "hyp_only": 0, - "rejected": 0, "harness_errors": 0, "skipped": 0}) - st["programs"] += 1 - spv = os.path.join(spdir, p.name + ".spv") - if not os.path.exists(spv): - st["rejected"] += 1 - fails.append((p, mode, "not translated", None)) - continue - try: - bad, hyp = compare(p, run_gpu(args.exe, spv, p, work, mode == "emulate")) - except HarnessError as e: - # One program that hangs or crashes the harness used to end the run with a traceback and - # lose every result before it. It is reported like the other failures and the run goes on. - st["harness_errors"] += 1 - fails.append((p, mode, f"harness error: {e}", None)) - continue - except Unpinned as e: - st["skipped"] += 1 - print(f"SKIP {p.name} [{mode}]: {e}") - continue - if not bad: - st["match"] += 1 - elif hyp: - st["hyp_only"] += 1 - fails.append((p, mode, "mismatch (program has a hypothesis op)", bad)) - else: - st["mismatch"] += 1 - fails.append((p, mode, "mismatch", bad)) - - -def self_test(): - """The model against values worked out by hand (no GPU, no llvm-mc).""" - w = Wave(64, M64) - w.v[2] = [3 * l + 1 for l in range(64)] - g = Gen(random.Random(0), 64, 64) - # readlane: lane 40 of 3l+1 = 121, independent of EXEC. - w.exec = 1 << 63 - Op("", lambda x: x.s.__setitem__(8, x.vr(2)[40]), "t").apply([w]) - assert w.s[8] == 121 - # readfirstlane with only lane 63 on: 190; with EXEC 0: lane 0 = 1. - rf = g.op_readfirstlane() - w.exec = 1 << 63 - rf.apply([w]) - d = int(rf.text.split()[1].strip(",")[1:]) - v = int(rf.text.split()[2][1:]) - assert w.s[d] == w.vr(v)[63] - w.exec = 0 - rf.apply([w]) - assert w.s[d] == w.vr(v)[0] - # mbcnt of EXEC = all ones gives the lane. - w.exec = M64 - vals = [popcount(M64 & ((1 << l) - 1)) for l in range(64)] - assert vals[0] == 0 and vals[40] == 40 and vals[63] == 63 - # permlanex16 with selectors 0: lane 5 reads lane 16, lane 20 reads lane 0, lane 40 reads lane 48. - x16 = [((l & ~31) | ((l & 16) ^ 16)) for l in range(64)] - assert x16[5] == 16 and x16[20] == 0 and x16[40] == 48 - print("self-test OK") - return 0 - - -if __name__ == "__main__": - try: # a redirected stdout is strict ANSI code page under -I; write '?' for what it cannot encode - sys.stdout.reconfigure(errors="replace") - except (AttributeError, ValueError, OSError): - pass - sys.exit(main()) diff --git a/tools/cvt_diff.py b/tools/cvt_diff.py deleted file mode 100644 index b3a345a99..000000000 --- a/tools/cvt_diff.py +++ /dev/null @@ -1,902 +0,0 @@ -r"""Differential fuzzer for the RDNA2 rounding and normalizing conversions (standard library only). - -Covers eight opcodes that no other fuzzer generates (the `v_cvt_flr_i32_f32`/`v_cvt_rpi_i32_f32`, -`v_cvt_norm_*_f16`, `v_cvt_pknorm_*_f32` and `v_cvt_pknorm_*_f16` rows of docs/design.md's contract table): - - v_cvt_flr_i32_f32 v_cvt_rpi_i32_f32 VOP1 (_e32, _e64), f32 -> i32 - v_cvt_norm_i16_f16 v_cvt_norm_u16_f16 VOP1 (_e32, _e64), f16 -> snorm16 / unorm16 - v_cvt_pknorm_i16_f32 v_cvt_pknorm_u16_f32 VOP3, two f32 -> packed snorm16 / unorm16 - v_cvt_pknorm_i16_f16 v_cvt_pknorm_u16_f16 VOP3, two f16 -> packed snorm16 / unorm16 - -Seeded straight-line programs run through two independent oracles, and the four exported mrt0 words are compared -bit for bit: - - * the reference below, written from the rules docs/design.md records as measured on RDNA2, with exact rationals - (fractions.Fraction), so no step of it rounds in binary32. It shares no code with the translator: - - flr: sat_i32(floor(S0)); rpi: sat_i32(floor(S0 + 1/2)), the + 1/2 exact. |S0| >= 2^31, +-inf and NaN - saturate by the operand's sign bit (+ -> 0x7FFFFFFF, - -> 0x80000000). An f32 denormal reads as zero - (gfx1036 gives flr(-1e-45) = 0). - - norm and pknorm: round_even(clamp(x, -1, 1) * 32767) (i16) or round_even(clamp(x, 0, 1) * 65535) (u16), - rounded once from the exact product, NaN -> 0. f16 denormals are values (the MODE inferred for the game - keeps them); an f32 denormal is too small to round to anything but 0 either way. - - norm writes D[15:0] and keeps D[31:16]. pknorm writes S0's result to D[15:0] and S1's to D[31:16]; with - the destination op_sel bit of the f16 forms, S0's result to D[31:16] and 0 to D[15:0]. - tests/test_cvt_diff.py pins it to the words measured on RDNA2 that tests/semantic records, and - * tools/rdna2spirv.py, executing the SPIR-V with tests/semantic/spirv_mini_interp.py. - -Program shape: seeds in v8..v15 and s4..s7, then the family ops, then `exp mrt0 v8, v9, v10, v11` so every result -is observed. Every destination is v8..v11, so later ops read earlier results (as floats) and norm keeps whatever -an earlier op left in the high half. - -Sources: VGPR v8..v15, SGPR s4..s7, a hex literal, an integer inline constant (-16..64, the 32-bit two's complement -word) and a float inline constant (0.5, 1.0, 2.0, 4.0, their negatives, 0.15915494). A 16-bit float operand reads -the low half of a register or literal, and a float inline constant as its f16 value (docs/design.md, "f16 inline -constants"); an integer inline constant as the low half of its word. VOP3 programs stay encodable on GFX10: at most -one literal and two constant-bus reads. - -Modifiers: source `neg`/`abs` on register operands of every _e64/VOP3 form (applied to the f32 word, or to the -selected f16 half); `op_sel:[a,b,c]` on v_cvt_pknorm_*_f16, where a and b pick the high half of a register source -and c = 1 writes S0's result to D[31:16] and 0 to D[15:0], dropping S1's (measured on gfx1036, docs/design.md); -and the measured hardware no-ops: VOP3 `clamp`, `mul:2`, `mul:4`, `div:2` on v_cvt_norm_*, and `clamp` on -v_cvt_pknorm_* (both widths). - -Not generated, on purpose: SDWA and DPP forms (tools/sdwa_diff.py's domain), output modifiers on flr/rpi, -`mul:2`/`mul:4`/`div:2` on pknorm (the translator refuses them, and llvm-mc does for the f16 forms), `op_sel` on -norm (GFX10 has no encoding for it), and modifiers on constants. --self-test pins the forms the translator -refuses. - -Three stages run one after the other: - * a sweep: every op with every source kind and every modifier setting it takes, values from the edge lists; - * an edge grid: every op on every edge input (zeros, denormals, the normal minimum, +-0.5 and its neighbours, - the scale steps 1/32767 and 1/65535, near ties of x * 32767 and x * 65535, +-1, 2^23 and 2^31 neighbours, the - largest finite values, +-inf, quiet and signalling NaNs of both signs), four results per program; - * random programs (--programs), which widen the value coverage over the same space. - ---exhaustive-f16 adds every one of the 65,536 f16 inputs through the four f16 ops (49,152 programs). - -Usage: - python -I tools/cvt_diff.py [--programs N] [--seed S] [--max-ops N] [--no-sweep] [--exhaustive-f16] - python -I tools/cvt_diff.py --ops v_cvt_rpi_i32_f32,v_cvt_pknorm_i16_f32 - python -I tools/cvt_diff.py --list-ops - python -I tools/cvt_diff.py --self-test - -Exit code 0 when every program matches, 1 on a mismatch (the first one is printed with its listing) or a skip, 2 on -a harness error. Every generated form is one the translator takes, so a skip is a finding too: a translation the -interpreter calls undefined (an FClamp of a NaN, say) is reported with its reason, not passed. Nothing here reads game -files. -""" -import argparse -import gc -import math -import os -import random -import re -import struct -import sys -import tempfile -import warnings -from collections import Counter -from fractions import Fraction - -HERE = os.path.dirname(os.path.abspath(__file__)) -TOOLS_DIR = os.environ.get("LEONIDA_TOOLS_DIR") or HERE -sys.dont_write_bytecode = True -if TOOLS_DIR not in sys.path: - sys.path.insert(0, TOOLS_DIR) -SEM_DIR = os.path.join(os.path.dirname(HERE), "tests", "semantic") -if SEM_DIR not in sys.path: - sys.path.insert(0, SEM_DIR) - -import rdna2spirv # noqa: E402 -from spirv_mini_interp import UnsupportedConstruct, run_fragment # noqa: E402 - -M32 = 0xFFFFFFFF -M16 = 0xFFFF -STUB_DXBC = b"DXBC" + bytes(24) + struct.pack(" (kind, snorm); kind: "flr"/"rpi" (f32 -> i32), "norm" (f16 -> 16 bits), "pk32", "pk16" -FAMILY = { - "v_cvt_flr_i32_f32": ("flr", None), "v_cvt_rpi_i32_f32": ("rpi", None), - "v_cvt_norm_i16_f16": ("norm", True), "v_cvt_norm_u16_f16": ("norm", False), - "v_cvt_pknorm_i16_f32": ("pk32", True), "v_cvt_pknorm_u16_f32": ("pk32", False), - "v_cvt_pknorm_i16_f16": ("pk16", True), "v_cvt_pknorm_u16_f16": ("pk16", False), -} -VOP1_OPS = tuple(op for op, (k, _) in FAMILY.items() if k in ("flr", "rpi", "norm")) -OMOD_OPS = tuple(op for op, (k, _) in FAMILY.items() if k == "norm") # clamp, mul:2, mul:4, div:2 are no-ops -CLAMP_OPS = OMOD_OPS + tuple(op for op, (k, _) in FAMILY.items() if k in ("pk32", "pk16")) -OMODS = ("clamp", "mul:2", "mul:4", "div:2", "clamp mul:2", "clamp div:2") -OP_FORMS = { - **{op: f"{op}_e32 d, s0 | {op}_e64 d, [-][|]s0[|]" for op in VOP1_OPS}, - **{op: f"{op} d, [-][|]s0[|], [-][|]s1[|]" for op, (k, _) in FAMILY.items() if k == "pk32"}, - **{op: f"{op} d, [-][|]s0[|], [-][|]s1[|] [op_sel:[a,b,c]]" for op, (k, _) in FAMILY.items() if k == "pk16"}, -} -for _op in OMOD_OPS: - OP_FORMS[_op] += " [clamp] [mul:2|mul:4|div:2]" -for _op in CLAMP_OPS[len(OMOD_OPS):]: - OP_FORMS[_op] += " [clamp]" - -KINDS = ("vgpr", "sgpr", "lit", "int", "float") -MODS = ("", "-", "|", "-|") # source modifiers on a register: none, neg, abs, neg(abs) -FLOAT_INLINE = { # token -> (f32 word, f16 half) - "0.5": (0x3F000000, 0x3800), "-0.5": (0xBF000000, 0xB800), "1.0": (0x3F800000, 0x3C00), - "-1.0": (0xBF800000, 0xBC00), "2.0": (0x40000000, 0x4000), "-2.0": (0xC0000000, 0xC000), - "4.0": (0x40800000, 0x4400), "-4.0": (0xC0800000, 0xC400), "0.15915494": (0x3E22F983, 0x3118), -} -INT_INLINE = tuple(range(0, 65)) + tuple(range(-16, 0)) - - -class HarnessError(Exception): - """The generator or the reference met something outside the modelled forms.""" - - -# ---- the reference ---- - -def f32_value(w): - """An f32 word as ("nan", sign), ("inf", sign) or ("num", Fraction). Denormals are values here; the ops decide - whether they flush.""" - sign = w >> 31 - e, m = (w >> 23) & 0xFF, w & 0x7FFFFF - if e == 0xFF: - return ("nan", sign) if m else ("inf", sign) - v = Fraction(m, 1 << 149) if e == 0 else Fraction((1 << 23) | m) * Fraction(2) ** (e - 150) - return ("num", -v if sign else v) - - -def f16_value(h): - sign = h >> 15 - e, m = (h >> 10) & 0x1F, h & 0x3FF - if e == 0x1F: - return ("nan", sign) if m else ("inf", sign) - v = Fraction(m, 1 << 24) if e == 0 else Fraction((1 << 10) | m) * Fraction(2) ** (e - 25) - return ("num", -v if sign else v) - - -def round_even(q): - """Round a Fraction to the nearest integer, ties to even.""" - fl = math.floor(q) - d = q - fl - if d > Fraction(1, 2) or (d == Fraction(1, 2) and fl % 2): - return fl + 1 - return fl - - -def to_i32(w, half_up): - """v_cvt_flr_i32_f32 (half_up False) and v_cvt_rpi_i32_f32 (True) on an f32 word, modifiers already applied.""" - sign = w >> 31 - if w & 0x7FFFFFFF >= 0x4F000000: # |x| >= 2^31, inf, NaN: by the sign bit - return 0x80000000 if sign else 0x7FFFFFFF - if w & 0x7F800000 == 0: # zero or denormal: flushed - return 0 - v = f32_value(w)[1] - return math.floor(v + Fraction(1, 2) if half_up else v) & M32 - - -def normalize(kind_value, snorm): - """round_even(clamp(x, lo, 1) * scale) & 0xFFFF for an f32_value/f16_value result; NaN gives 0.""" - kind, v = kind_value - if kind == "nan": - return 0 - lo = Fraction(-1) if snorm else Fraction(0) - if kind == "inf": - v = lo if v else Fraction(1) - v = min(max(v, lo), Fraction(1)) - return round_even(v * (32767 if snorm else 65535)) & M16 - - -def modify(word, mod, bits): - """Source abs/neg on a `bits`-wide float: abs clears the sign, neg flips it (abs first for -|x|).""" - sbit = 1 << (bits - 1) - if "|" in mod: - word &= ~sbit - if mod.startswith("-"): - word ^= sbit - return word - - -_REG = re.compile(r"([sv])(\d+)$") -_SRC = re.compile(r"(-?)(\|?)([sv]\d+)\|?$") -_MOD = re.compile(r"\s+(op_sel:\[[01],[01],[01]\]|clamp|mul:[24]|div:2)$") - - -def source(tok, vgpr, sgpr, f16): - """(word or half, modifier string, is_register) for a source token. A 16-bit operand is the low half of a register - or literal, the f16 value of a float inline constant, or the low half of an integer inline constant's word.""" - tok = tok.strip() - m = _SRC.fullmatch(tok) - if m: - neg, bar, reg = m.groups() - if bar and not tok.endswith("|"): - raise HarnessError(f"unbalanced abs bars in {tok!r}") - r = _REG.fullmatch(reg) - regs = vgpr if r.group(1) == "v" else sgpr - return regs.get(int(r.group(2)), 0), neg + bar, True - if tok in FLOAT_INLINE: - return FLOAT_INLINE[tok][1 if f16 else 0], "", False - if tok.lower().startswith("0x"): - return int(tok, 16) & M32, "", False - if tok.lstrip("-").isdigit(): - return int(tok, 10) & M32, "", False - raise HarnessError(f"unknown source {tok!r}") - - -def split_line(line): - """(opcode, raw opcode, operand tokens, modifier list) for one generated line.""" - mods = [] - body = line.rstrip() - while True: - m = _MOD.search(body) - if not m: - break - mods.insert(0, m.group(1)) - body = body[:m.start()] - raw, _, rest = body.partition(" ") - op = raw[:-4] if raw.endswith(("_e32", "_e64")) else raw - return op, raw, [t.strip() for t in rest.split(",")], mods - - -def _dst_index(dst): - m = _REG.fullmatch(dst.strip()) - if not m or m.group(1) != "v": - raise HarnessError(f"unknown destination {dst!r}") - return int(m.group(2)) - - -def _opsel(mods): - for m in mods: - if m.startswith("op_sel:"): - return tuple(int(b) for b in m[len("op_sel:"):].strip("[]").split(",")) - return (0, 0, 0) - - -def step(line, vgpr, sgpr, events=None): - """Execute one generated listing line on the reference's registers. `events` (a Counter), when given, counts what - each op's inputs were: (op, "nan"), (op, "inf"), (op, "saturated") for an out-of-range or clamped input, and - (op, "tie") for a product within TIE_WINDOW of k + 1/2 (an exact x.5 for rpi).""" - op, raw, args, mods = split_line(line) - if op == "v_mov_b32": - vgpr[_dst_index(args[0])] = source(args[1], vgpr, sgpr, False)[0] - return - if op == "s_mov_b32": - if not args[0].startswith("s"): - raise HarnessError(line) - sgpr[int(args[0][1:])] = source(args[1], vgpr, sgpr, False)[0] - return - if op not in FAMILY: - raise HarnessError(line) - kind, snorm = FAMILY[op] - d = _dst_index(args[0]) - sel = _opsel(mods) - if sel != (0, 0, 0) and kind != "pk16": - raise HarnessError(f"op_sel outside the modelled forms: {line}") - if kind in ("flr", "rpi"): - w, mod, _ = source(args[1], vgpr, sgpr, False) - w = modify(w, mod, 32) - if events is not None: - _count(events, op, f32_value(w), 1, half_up=kind == "rpi") - vgpr[d] = to_i32(w, kind == "rpi") - return - if kind == "norm": - w, mod, _ = source(args[1], vgpr, sgpr, True) - h = modify(w & M16, mod, 16) - if events is not None: - _count(events, op, f16_value(h), 32767 if snorm else 65535) - vgpr[d] = (vgpr.get(d, 0) & 0xFFFF0000) | normalize(f16_value(h), snorm) - return - halves = [] - for k in (0, 1): - w, mod, is_reg = source(args[1 + k], vgpr, sgpr, kind == "pk16") - if kind == "pk32": - val = f32_value(modify(w, mod, 32)) - else: - if sel[k] and not is_reg: - raise HarnessError(f"op_sel high half of a constant: {line}") - val = f16_value(modify((w >> 16 if sel[k] else w) & M16, mod, 16)) - if events is not None: - _count(events, op, val, 32767 if snorm else 65535) - halves.append(normalize(val, snorm)) - # op_sel[2] (f16 forms): S0's result in D[31:16], D[15:0] = 0, S1's result dropped (gfx1036, docs/design.md) - vgpr[d] = halves[0] << 16 if sel[2] else halves[0] | (halves[1] << 16) - - -TIE_WINDOW = Fraction(1, 256) - - -def _count(events, op, val, scale, half_up=False): - kind, v = val - if kind != "num": - events[(op, kind)] += 1 - return - if scale == 1: - if abs(v) >= 1 << 31: - events[(op, "saturated")] += 1 - elif half_up and (v - Fraction(1, 2)) == math.floor(v - Fraction(1, 2)): - events[(op, "tie")] += 1 - return - lo = -1 if scale == 32767 else 0 - if v < lo or v > 1: - events[(op, "saturated")] += 1 - return - p = v * scale - if abs(p - math.floor(p) - Fraction(1, 2)) <= TIE_WINDOW: - events[(op, "tie")] += 1 - - -def reference(lines, events=None): - """The four exported mrt0 words the ISA gives for a program (seeds and ops; exp and s_endpgm are ignored).""" - vgpr, sgpr = {}, {} - for line in lines: - if line.split()[0] in ("exp", "s_endpgm"): - continue - step(line, vgpr, sgpr, events) - return [vgpr.get(r, 0) for r in EXPORT_REGS] - - -# ---- edge values ---- - -def _f32(x): - return struct.unpack(" 2 else 0}]" - if omod: - line += " " + omod - return line - - -def _random_op(rng, op): - kind = FAMILY[op][0] - n = 2 if kind.startswith("pk") else 1 - form = "e32" if op in VOP1_OPS and rng.random() < 0.4 else "e64" - while True: - kinds = tuple(rng.choices(KINDS, weights=(5, 2, 1, 1, 1), k=n)) - if encodable(op, kinds, form): - break - mods = tuple(rng.choice(MODS) if form == "e64" else "" for _ in kinds) - sel = (0, 0) - if kind == "pk16": - sel = tuple(rng.randrange(2) if k in ("vgpr", "sgpr") else 0 for k in kinds) + (int(rng.random() < 0.25),) - omod = "" - if form == "e64" and op in CLAMP_OPS and rng.random() < 0.25: - omod = rng.choice(OMODS) if op in OMOD_OPS else "clamp" - return op_line(rng, op, kinds, form, mods, sel, omod) - - -def seeds(rng): - lines = [f"v_mov_b32_e32 v{r}, 0x{_seed_word(rng):x}" for r in range(8, 16)] - lines += [f"s_mov_b32 s{r}, 0x{_seed_word(rng):x}" for r in range(4, 8)] - return lines - - -def program(rng, n_ops, ops=None): - """Seeds, then n_ops family ops. Returns (lines, ops used).""" - ops = ops or tuple(FAMILY) - lines = seeds(rng) - used = [] - for _ in range(n_ops): - op = rng.choice(ops) - used.append(op) - lines.append(_random_op(rng, op)) - return lines, used - - -def sweep_ops(ops=None): - """(op, form, kinds, mods, sel, omod) for every source kind and every modifier setting each op takes.""" - out = [] - for op in ops or FAMILY: - kind = FAMILY[op][0] - n = 2 if kind.startswith("pk") else 1 - forms = ("e32", "e64") if op in VOP1_OPS else ("e64",) - for form in forms: - for kinds in _product(KINDS, n): - if not encodable(op, kinds, form): - continue - reg = [k in ("vgpr", "sgpr") for k in kinds] - mod_sets = [("",) * n] if form == "e32" else \ - [m for m in _product(MODS, n) if all(r or not x for r, x in zip(reg, m))] - sel_sets = [(0, 0)] - if kind == "pk16": - sel_sets = [s + (dhi,) for dhi in (0, 1) for s in _product((0, 1), n) - if all(r or not x for r, x in zip(reg, s))] - omods = [""] - if form == "e64" and op in CLAMP_OPS: - omods += list(OMODS) if op in OMOD_OPS else ["clamp"] - for mods in mod_sets: - for sel in sel_sets: - for omod in omods: - if omod and (any(mods) or any(sel[:2])): - continue # output modifiers once per source kind and destination half - out.append((op, form, kinds, mods, sel, omod)) - return out - - -def _product(items, n): - if n == 0: - return [()] - return [(x,) + rest for x in items for rest in _product(items, n - 1)] - - -def sweep_program(case, rng): - op, form, kinds, mods, sel, omod = case - return seeds(rng) + [op_line(rng, op, kinds, form, mods, sel, omod) for _ in range(3)] - - -GRID_PER_PROGRAM = 4 - - -def grid_cases(ops=None): - """(op, input word, second input word) for every op and every edge input. The f32 ops read F32_EDGES and - F32_TIES; the f16 ops F16_EDGES and F16_TIES. A pk op pairs each input with the next one as S1.""" - out = [] - for op in ops or FAMILY: - kind = FAMILY[op][0] - vals = list(F32_EDGES + F32_TIES) if kind in ("flr", "rpi", "pk32") else list(F16_EDGES + F16_TIES) - for i, v in enumerate(vals): - out.append((op, v, vals[(i + 1) % len(vals)])) - return out - - -def grid_program(chunk, rng): - """Inputs in v12..v15 (an f16 input in the low half, with a different f16 edge in the high half), then one op per - case writing v8..v11. A pk16 case reads its two inputs from the halves op_sel picks.""" - lines = [f"v_mov_b32_e32 v{8 + i}, 0x{0xA5A50000 | i:x}" for i in range(4)] - body = [] - for i, (op, a, b) in enumerate(chunk): - kind = FAMILY[op][0] - if kind in ("flr", "rpi"): - lines.append(f"v_mov_b32_e32 v{12 + i}, 0x{a:x}") - body.append(f"{op}_e32 v{8 + i}, v{12 + i}") - elif kind == "norm": - lines.append(f"v_mov_b32_e32 v{12 + i}, 0x{a | (rng.choice(F16_EDGES) << 16):x}") - body.append(f"{op}_e32 v{8 + i}, v{12 + i}") - elif kind == "pk32": - lines.append(f"v_mov_b32_e32 v{12 + i}, 0x{a:x}") - lines.append(f"s_mov_b32 s{4 + i}, 0x{b:x}") - body.append(f"{op} v{8 + i}, v{12 + i}, s{4 + i}") - else: - hi = i & 1 - lines.append(f"v_mov_b32_e32 v{12 + i}, 0x{(a << 16 | b) if hi else (b << 16 | a):x}") - body.append(f"{op} v{8 + i}, v{12 + i}, v{12 + i}" + (" op_sel:[1,0,0]" if hi else " op_sel:[0,1,0]")) - return lines + body - - -def exhaustive_programs(ops=None): - """Every f16 input through each f16 op: four per program for norm (VOP1, low half), eight per program for pknorm - (S0 and S1 from the two halves of one register). Yields (op, lines).""" - for op in ops or FAMILY: - kind = FAMILY[op][0] - if kind == "norm": - for base in range(0, 1 << 16, 4): - lines = [f"v_mov_b32_e32 v{8 + i}, 0x{0x5A5A0000 | i:x}" for i in range(4)] - lines += [f"v_mov_b32_e32 v{12 + i}, 0x{base + i:x}" for i in range(4)] - lines += [f"{op}_e32 v{8 + i}, v{12 + i}" for i in range(4)] - yield op, lines - elif kind == "pk16": - for base in range(0, 1 << 16, 8): - lines = [f"v_mov_b32_e32 v{12 + i}, 0x{(base + 2 * i + 1) << 16 | (base + 2 * i):x}" - for i in range(4)] - lines += [f"{op} v{8 + i}, v{12 + i}, v{12 + i} op_sel:[0,1,0]" for i in range(4)] - yield op, lines - - -# ---- the translator oracle ---- - -def write_listing(path, lines, name): - with open(path, "w", encoding="utf-8", newline="\n") as f: - f.write(f"; {name} code 0x0..0x1000\n") - for line in lines: - f.write("\t" + line + "\n") - f.write("\t" + EXPORT + "\n") - f.write("\ts_endpgm\n") - - -def translate_listing(lines, name, tmpdir): - """The four mrt0 words the translator path produces. Raises rdna2spirv.Unsupported (and the mini interp's - UnsupportedConstruct) for anything outside the oracles' model.""" - dis = os.path.join(tmpdir, "disasm") - os.makedirs(dis, exist_ok=True) - path = os.path.join(dis, name + ".s") - write_listing(path, lines, name) - with open(os.path.join(tmpdir, name + ".dxbc"), "wb") as f: - f.write(STUB_DXBC) - with warnings.catch_warnings(): - warnings.simplefilter("ignore", ResourceWarning) - spvasm = rdna2spirv.translate(path) - gc.collect() - out = run_fragment(spvasm) - if list(out) != ["%out_mrt0"]: - raise HarnessError(f"outputs {sorted(out)}, want %out_mrt0") - return [w & M32 for w in out["%out_mrt0"]] - - -def check(lines, name="ps_cvt_case"): - """None when both oracles agree, else the first differing word with both values.""" - with tempfile.TemporaryDirectory(prefix="cvt-diff-") as tmp: - want = reference(lines) - got = translate_listing(lines, name, tmp) - return compare(want, got) - - -def compare(want, got): - """None when the translator exported the same words as the reference, else what differs. A short export is a - difference too: zip alone would compare only the words both sides have.""" - if len(got) != len(want): - return f"exported {len(got)} words, want {len(want)}" - for i, (w, g) in enumerate(zip(want, got)): - if w != (g & M32): - return f"word {i} (v{EXPORT_REGS[i]}): expected 0x{w:08x}, actual 0x{g:08x}" - return None - - -def run_one(lines, name, tmpdir, events=None): - """(status, detail) with status in {"match", "mismatch", "skip"}.""" - try: - want = reference(lines, events) - except HarnessError as e: - return ("skip", f"reference cannot run the program: {e}") - try: - got = translate_listing(lines, name, tmpdir) - except (rdna2spirv.Unsupported, UnsupportedConstruct) as e: - return ("skip", f"{type(e).__name__}: {e}") - except (IndexError, KeyError, ValueError) as e: - return ("skip", f"translator error {type(e).__name__}: {e}") - detail = compare(want, got) - return ("mismatch", detail) if detail else ("match", "") - - -# ---- the suites ---- - -def _new_counts(): - return {"pass": 0, "mismatch": 0, "skip": Counter(), "ops": Counter(), "events": Counter()} - - -def _tally(counts, status, detail): - if status == "match": - counts["pass"] += 1 - elif status == "skip": - counts["skip"][detail] += 1 - else: - counts["mismatch"] += 1 - - -def run_sweep(seed, ops=None): - """Every case of sweep_ops, one program each. Returns (counts, failure).""" - counts = _new_counts() - failure = None - with tempfile.TemporaryDirectory(prefix="cvt-diff-sweep-") as tmp: - for i, case in enumerate(sweep_ops(ops)): - op, form, kinds, mods, sel, omod = case - tag = f"{op}:{form}:{'/'.join(kinds)}:{'/'.join(m or '.' for m in mods)}:{sel}:{omod}" - lines = sweep_program(case, random.Random(f"{seed}:{tag}")) - counts["ops"][op] += 1 - status, detail = run_one(lines, f"ps_cvt_sw{i:04d}", tmp, counts["events"]) - _tally(counts, status, detail) - if status == "mismatch" and failure is None: - failure = (f"sweep {tag} (case {i}, seed {seed})", lines, detail) - return counts, failure - - -def run_grid(ops=None): - """The edge grid, GRID_PER_PROGRAM cases per program. Returns (counts, failure); counts["ops"] counts cases.""" - counts = _new_counts() - failure = None - cases = grid_cases(ops) - rng = random.Random("cvt_diff:grid") - with tempfile.TemporaryDirectory(prefix="cvt-diff-grid-") as tmp: - for i in range(0, len(cases), GRID_PER_PROGRAM): - chunk = cases[i:i + GRID_PER_PROGRAM] - lines = grid_program(chunk, rng) - counts["ops"].update(op for op, *_ in chunk) - status, detail = run_one(lines, f"ps_cvt_gr{i // GRID_PER_PROGRAM:04d}", tmp, counts["events"]) - _tally(counts, status, detail) - if status == "mismatch" and failure is None: - failure = (f"edge grid program {i // GRID_PER_PROGRAM}", lines, detail) - return counts, failure - - -def run_exhaustive(ops=None): - """Every f16 input through the f16 ops. Returns (counts, failure); counts["ops"] counts op lines (four per - program).""" - counts = _new_counts() - failure = None - with tempfile.TemporaryDirectory(prefix="cvt-diff-ex-") as tmp: - for i, (op, lines) in enumerate(exhaustive_programs(ops)): - counts["ops"][op] += GRID_PER_PROGRAM - status, detail = run_one(lines, f"ps_cvt_ex{i:05d}", tmp, counts["events"]) - _tally(counts, status, detail) - if status == "mismatch" and failure is None: - failure = (f"exhaustive f16 program {i} ({op})", lines, detail) - return counts, failure - - -def run_suite(programs, seed, max_ops=6, ops=None): - """Random seeded programs. Returns (counts, failure).""" - counts = _new_counts() - failure = None - rng = random.Random(f"suite:{seed}") - with tempfile.TemporaryDirectory(prefix="cvt-diff-run-") as tmp: - for i in range(programs): - lines, used = program(rng, rng.randint(1, max_ops), ops) - counts["ops"].update(used) - status, detail = run_one(lines, f"ps_cvt_{i:04d}", tmp, counts["events"]) - _tally(counts, status, detail) - if status == "mismatch" and failure is None: - failure = (f"program {i} (seed {seed})", lines, detail) - return counts, failure - - -REJECTED = ( - ("mul:2 on v_cvt_pknorm_u16_f16", "v_cvt_pknorm_u16_f16 v8, v9, v10 mul:2"), - ("mul:2 on v_cvt_pknorm_i16_f32", "v_cvt_pknorm_i16_f32 v8, v9, v10 mul:2"), - ("div:2 on v_cvt_pknorm_u16_f32", "v_cvt_pknorm_u16_f32 v8, v9, v10 div:2"), -) - - -def self_test(): - """True when the reference's hand-pinned words, the rejected forms and the harness canaries all hold.""" - ok = True - - def expect(cond, what): - nonlocal ok - print(("ok " if cond else "FAIL ") + what) - ok = ok and cond - - # Hand-pinned reference words: the docs/design.md rows and tests/semantic/test_alu_cvt_flr_rpi.py. - expect(to_i32(0x3EFFFFFF, True) == 0, "rpi(0.49999997) = 0: the + 1/2 is exact, not rounded in binary32") - expect(to_i32(0x4B000001, True) == 0x00800001, "rpi(8388609.0) = 8388609") - expect(to_i32(0x4B7FFFFF, True) == 0x00FFFFFF, "rpi(16777215.0) = 16777215") - expect(to_i32(0xBF000000, True) == 0 and to_i32(0xBFC00000, True) == M32, - "rpi(-0.5) = 0 and rpi(-1.5) = -1 (floor(x + 1/2))") - expect(to_i32(0xCF000001, False) == 0x80000000, "flr below -2^31 saturates to INT_MIN") - expect(to_i32(0x7FC00000, False) == 0x7FFFFFFF and to_i32(0xFFC00000, False) == 0x80000000, - "flr of a NaN saturates by its sign bit") - expect(to_i32(0x80000001, False) == 0, "flr(-1e-45) = 0: an f32 denormal reads as zero (gfx1036)") - expect(normalize(f16_value(0x3C00), True) == 0x7FFF and normalize(f16_value(0xBC00), True) == 0x8001, - "norm_i16(+-1.0) = 0x7fff / 0x8001") - expect(normalize(f16_value(0xFC00), True) == 0x8001 and normalize(f16_value(0xFC00), False) == 0, - "-inf clamps to -1 (i16) and to 0 (u16)") - expect(normalize(f16_value(0x7E00), True) == 0 and normalize(f32_value(0xFFC00000), False) == 0, "NaN gives 0") - expect(normalize(f16_value(0x3801), True) == 16399, "norm_i16(0.5 + 2^-11): 16399.499... rounds down once") - expect(normalize(f32_value(0x3F000000), True) == 0x4000 and normalize(f32_value(0xBF000000), True) == 0xC000 - and normalize(f32_value(0x3F000000), False) == 0x8000, - "x = +-0.5 is an exact tie (16383.5, 32767.5) and goes to even: 0x4000, 0xc000, 0x8000") - expect(normalize(f16_value(0x03FF), True) == 2, "an f16 denormal is a value: (2^-14 - 2^-24) * 32767 = 1.99") - # norm keeps the destination's high half; pknorm reads op_sel halves. - expect(reference(["v_mov_b32 v8, 0x12340000", "v_mov_b32 v9, 0x3c00", "v_cvt_norm_u16_f16_e32 v8, v9"])[0] - == 0x1234FFFF, "v_cvt_norm_u16_f16 writes D[15:0] and keeps D[31:16]") - expect(reference(["v_mov_b32 v9, 0xbc003c00", "v_cvt_pknorm_i16_f16 v8, v9, v9 op_sel:[1,0,0]"])[0] - == 0x7FFF8001, "v_cvt_pknorm_i16_f16 op_sel:[1,0,0]: S0 from the high half") - # The destination op_sel and clamp of the f16 forms, as measured on gfx1036 (tests/semantic/ - # test_cvt_pknorm_f16_mods.py): clamp changes nothing, op_sel[2] moves S0's result up and zeroes D[15:0]. - pk = ["v_mov_b32 v8, 0xdeadbeef", "v_mov_b32 v9, 0x3c003400", "v_mov_b32 v10, 0xbc003801"] - expect(reference(pk + ["v_cvt_pknorm_i16_f16 v8, v9, v10 clamp"])[0] == 0x400F2000, - "v_cvt_pknorm_i16_f16 clamp: a no-op (0.25 -> 0x2000, 0.5 + 2^-11 -> 0x400f)") - expect(reference(pk + ["v_cvt_pknorm_i16_f16 v8, v9, v10 op_sel:[0,0,1] clamp"])[0] == 0x20000000, - "v_cvt_pknorm_i16_f16 op_sel:[0,0,1]: S0's result in D[31:16], D[15:0] = 0, S1 dropped") - expect(reference(pk + ["v_cvt_pknorm_u16_f16 v8, v9, v10 op_sel:[0,1,1]"])[0] == 0x40000000, - "v_cvt_pknorm_u16_f16 op_sel:[0,1,1]: the high-half S1 is read but dropped") - expect(reference(["v_cvt_pknorm_u16_f16 v8, 1.0, 0.5"])[0] == 0x8000FFFF, - "float inline constants read as f16 values in a 16-bit operand (1.0 -> 0xffff, 0.5 -> 0x8000)") - - # The two-oracle path agrees on a fixed program, and a sabotaged word is caught. - lines = ["v_mov_b32 v9, 0x3effffff", "v_mov_b32 v10, 0xbc003801", - "v_cvt_rpi_i32_f32_e32 v8, v9", "v_cvt_norm_i16_f16_e64 v11, -v10"] - expect(check(lines) is None, "a hand-pinned program matches on both oracles") - real = translate_listing - try: - globals()["translate_listing"] = lambda l, n, t: real(l, n, t)[:3] + [1] - expect(check(lines) is not None, "a sabotaged export word is reported") - finally: - globals()["translate_listing"] = real - - # Forms the contract rows say are refused, not guessed. - with tempfile.TemporaryDirectory(prefix="cvt-diff-neg-") as tmp: - for what, bad in REJECTED: - try: - translate_listing(["v_mov_b32 v9, 1", "v_mov_b32 v10, 2", bad], "ps_cvt_neg", tmp) - expect(False, f"{what}: the translator rejected it") - except (rdna2spirv.Unsupported, UnsupportedConstruct): - expect(True, f"{what}: the translator rejected it") - - # Determinism: the same seed gives the same program stream. - expect(program(random.Random(9), 4) == program(random.Random(9), 4), "generation is deterministic for a seed") - counts, failure = run_suite(8, 3, 3) - expect(failure is None and counts["pass"] == 8 and not counts["skip"], - f"a short seeded run matches ({counts['pass']} programs, skips {dict(counts['skip'])})") - return ok - - -def main(): - ap = argparse.ArgumentParser(description=__doc__.splitlines()[0], - formatter_class=argparse.RawDescriptionHelpFormatter) - ap.add_argument("--programs", type=int, default=300, help="random programs after the sweep") - ap.add_argument("--seed", type=int, default=1) - ap.add_argument("--max-ops", type=int, default=6, help="ops per random program") - ap.add_argument("--ops", default=None, help="comma-separated opcodes to cover (default: all eight)") - ap.add_argument("--no-sweep", action="store_true", help="skip the source-kind sweep and the edge grid") - ap.add_argument("--exhaustive-f16", action="store_true", help="also run every f16 input through the f16 ops") - ap.add_argument("--list-ops", action="store_true") - ap.add_argument("--self-test", action="store_true") - args = ap.parse_args() - - if args.list_ops: - for op, form in OP_FORMS.items(): - print(f"{op:22s} {form}") - return 0 - if args.self_test: - return 0 if self_test() else 1 - - ops = [o.strip() for o in args.ops.split(",")] if args.ops else None - bad = [o for o in (ops or []) if o not in FAMILY] - if bad: - print(f"unknown op(s) {bad}; --list-ops shows the family", file=sys.stderr) - return 2 - - total_pass = total_run = total_mismatch = total_skip = 0 - per_op, events = Counter(), Counter() - failure = None - try: - for label, enabled, runner in ( - ("sweep", not args.no_sweep, lambda: run_sweep(args.seed, ops)), - ("edge grid", not args.no_sweep, lambda: run_grid(ops)), - ("exhaustive f16", args.exhaustive_f16, lambda: run_exhaustive(ops)), - ("random", args.programs > 0, lambda: run_suite(args.programs, args.seed, args.max_ops, ops)), - ): - if not enabled: - continue - counts, first = runner() - ran = counts["pass"] + counts["mismatch"] + sum(counts["skip"].values()) - total_pass += counts["pass"] - total_mismatch += counts["mismatch"] - total_skip += sum(counts["skip"].values()) - total_run += ran - per_op.update(counts["ops"]) - events.update(counts["events"]) - print(f"{label}: {counts['pass']}/{ran} programs match, {counts['mismatch']} mismatch; " - f"skips: {dict(counts['skip'])}") - failure = failure or first - except HarnessError as e: - print(f"harness error: {e}", file=sys.stderr) - return 2 - print("cases per op: " + ", ".join(f"{op} {per_op[op]}" for op in sorted(per_op))) - print("inputs per op (NaN / inf / saturated / near tie): " + ", ".join( - f"{op} {events[(op, 'nan')]}/{events[(op, 'inf')]}/{events[(op, 'saturated')]}/{events[(op, 'tie')]}" - for op in sorted(per_op))) - print(f"cvt family: {total_pass}/{total_run} programs match, {total_mismatch} mismatch " - f"({len(per_op)} of {len(FAMILY)} ops)") - if failure: - _report(failure) - return 1 - if total_skip: - print(f"SKIPPED {total_skip} program(s): every generated form should translate (reasons above)") - return 1 - return 0 - - -def _report(failure): - name, lines, detail = failure - print(f"MISMATCH {name}: {detail}") - print("program:") - for line in lines: - print(" " + line) - - -if __name__ == "__main__": - try: # a redirected stdout is strict ANSI code page under -I; write '?' for what it cannot encode - sys.stdout.reconfigure(errors="replace") - except (AttributeError, ValueError, OSError): - pass - sys.exit(main()) diff --git a/tools/cvt_f16_omod_probe.py b/tools/cvt_f16_omod_probe.py deleted file mode 100644 index db65bcf8f..000000000 --- a/tools/cvt_f16_omod_probe.py +++ /dev/null @@ -1,495 +0,0 @@ -r"""Measure RDNA2 v_cvt_f16_f32 VOP3 output modifiers (mul:2, mul:4, div:2, clamp) across MODE settings. Standard library only. - -docs/design.md records the RX 6800 (RNE) order for v_cvt_f16_f32 output modifiers — convert to f16, apply omod when -IEEE=0 and f16 denormals are flushed, then apply clamp — and marks finite overflow under MODE toward-zero (FP_ROUND=3) -as unmeasured. Running this probe natively on RDNA2 (gfx1036) via tools/hw_oracle/ across wave32 and wave64 confirms -RTZ overflow saturation (+-65504 for mul:2/mul:4, +-65520 div:2 -> +-32752) and catches an edge-case bug: when div:2 -underflows a negative smallest normal (exponent 1, -2^-14 .. -(2 - 2^-10) * 2^-14), hardware produces -0.0 (0x8000) -rather than +0.0 (0x0000), while pre-omod zero/denormals (exponent 0, including -0.0 and -2^-15) give +0.0. - -Usage: - python -I tools/cvt_f16_omod_probe.py [--waves 32,64] [--modes ...] [--json out.json] - python -I tools/cvt_f16_omod_probe.py --self-test - -Exit 0 when all hardware results match the model across requested modes (with wave32 and wave64 agreeing bit-for-bit), -1 on a model mismatch or wave32/wave64 difference, 2 on a harness/CLI error, and 77 when the hardware oracle is -unavailable or the GPU is not GFX10. Nothing here reads game files. -""" -import argparse -import json -import os -import struct -import sys - -HERE = os.path.dirname(os.path.abspath(__file__)) -sys.dont_write_bytecode = True -if HERE not in sys.path: - sys.path.insert(0, HERE) - -HI_SEED = 0xAAAA -LO_SEED = 0x5555 -SEED_WORD = (HI_SEED << 16) | LO_SEED - - -def _f32_bits(x: float) -> int: - return struct.unpack(" f16 0x87FF in both RNE and RTZ - ("-rne_to_exp2", 0xB8FFFE00), # f16 0x8800 (-2^-13) in RNE, 0x87FF in RTZ - ("-2^-13", _f32_bits(-(2.0 ** -13))), - ("0.375", _f32_bits(0.375)), - ("0.75", _f32_bits(0.75)), - ("-0.5", _f32_bits(-0.5)), - ("1.5", _f32_bits(1.5)), - ("2.0", _f32_bits(2.0)), - ("+16384.0", _f32_bits(16384.0)), - ("-16384.0", _f32_bits(-16384.0)), - ("+32752.0", _f32_bits(32752.0)), - ("-32752.0", _f32_bits(-32752.0)), - ("+32768.0", _f32_bits(32768.0)), - ("-32768.0", _f32_bits(-32768.0)), - ("+65504.0", _f32_bits(65504.0)), - ("-65504.0", _f32_bits(-65504.0)), - ("+65520.0", _f32_bits(65520.0)), - ("-65520.0", _f32_bits(-65520.0)), - ("+FLT_MAX", 0x7F7FFFFF), - ("-FLT_MAX", 0xFF7FFFFF), - ("+inf", 0x7F800000), - ("-inf", 0xFF800000), - ("+qNaN", 0x7FC01234), - ("-qNaN", 0xFFC01234), - ("+sNaN", 0x7F801234), - ("-sNaN", 0xFF801234), -) - -# In LLVM AMDGPU syntax for v_cvt_f16_f32_e64, clamp precedes mul:2/mul:4/div:2. -MODS: tuple[str, ...] = ( - "", - "mul:2", - "mul:4", - "div:2", - "clamp", - "clamp mul:2", - "clamp mul:4", - "clamp div:2", -) - -# name -> (kernel-descriptor MODE dict, runtime s_setreg RTZ flag, model parameters) -MODES: dict[str, dict] = { - "rne_d0_i0": { - "descriptor": {"round16_64": 0, "denorm16_64": 0, "dx10_clamp": 1, "ieee": 0}, - "setreg_rtz": False, - "rtz": False, - "denorm_keep": False, - "ieee": False, - "dx10_clamp": True, - }, - "rtz_d0_i0": { - "descriptor": {"round16_64": 3, "denorm16_64": 0, "dx10_clamp": 1, "ieee": 0}, - "setreg_rtz": False, - "rtz": True, - "denorm_keep": False, - "ieee": False, - "dx10_clamp": True, - }, - "rtz_d3_i0": { - "descriptor": {"round16_64": 3, "denorm16_64": 3, "dx10_clamp": 1, "ieee": 0}, - "setreg_rtz": False, - "rtz": True, - "denorm_keep": True, - "ieee": False, - "dx10_clamp": True, - }, - "rtz_d0_i1": { - "descriptor": {"round16_64": 3, "denorm16_64": 0, "dx10_clamp": 1, "ieee": 1}, - "setreg_rtz": False, - "rtz": True, - "denorm_keep": False, - "ieee": True, - "dx10_clamp": True, - }, - "dyn_rtz_d0_i0": { - "descriptor": {"round16_64": 0, "denorm16_64": 0, "dx10_clamp": 1, "ieee": 0}, - "setreg_rtz": True, - "rtz": True, - "denorm_keep": False, - "ieee": False, - "dx10_clamp": True, - }, -} - - -def f32_to_f16_bits(f32_bits: int, *, rtz: bool, denorm_keep: bool) -> int: - """Exact binary32 -> binary16 conversion with f32 denormals flushed to signed zero.""" - sg16 = ((f32_bits >> 31) & 1) << 15 - exp = (f32_bits >> 23) & 0xFF - frac = f32_bits & 0x7FFFFF - - if exp == 0xFF: - if frac: - return sg16 | 0x7E00 | ((frac >> 13) & 0x3FF) - return sg16 | 0x7C00 - if exp == 0: - return sg16 - - e = exp - 127 - if e > 15: - return sg16 | (0x7BFF if rtz else 0x7C00) - - m = 0x800000 | frac - if e >= -14: - q = m >> 13 - rem = m & 0x1FFF - if not rtz and (rem > 0x1000 or (rem == 0x1000 and (q & 1))): - q += 1 - if q == 0x800: - q = 0x400 - e += 1 - if e > 15: - return sg16 | (0x7BFF if rtz else 0x7C00) - return sg16 | ((e + 15) << 10) | (q & 0x3FF) - - if not denorm_keep: - return sg16 - - sh = -1 - e - if sh > 25: - return sg16 - q = m >> sh - rem = m & ((1 << sh) - 1) - half = 1 << (sh - 1) - if not rtz and (rem > half or (rem == half and (q & 1))): - q += 1 - return sg16 | q - - -def _clamp_f16(h: int, *, dx10_clamp: bool) -> int: - e = (h >> 10) & 31 - if e == 31 and (h & 0x3FF) != 0: - return 0x0000 if dx10_clamp else h - if h & 0x8000: - return 0x0000 - if h > 0x3C00: - return 0x3C00 - return h - - -def expected_cvt_f16_omod( - f32_bits: int, - mod: str, - *, - rtz: bool, - denorm_keep: bool, - ieee: bool, - dx10_clamp: bool = True, - hi_seed: int = HI_SEED, -) -> int: - """Expected 32-bit VGPR word after `v_cvt_f16_f32_e64 vD, src [clamp] [mul:2|mul:4|div:2]`.""" - tokens = mod.split() - omod = next((tok for tok in tokens if tok in ("mul:2", "mul:4", "div:2")), None) - has_clamp = "clamp" in tokens - - h = f32_to_f16_bits(f32_bits, rtz=rtz, denorm_keep=denorm_keep) - - if omod is not None and not denorm_keep and not ieee: - e = (h >> 10) & 31 - sign = h & 0x8000 - if e == 31: - pass - elif e == 0: - h = 0x0000 - elif omod == "div:2": - if e == 1: - h = sign - else: - h = (h - (1 << 10)) & 0xFFFF - else: - shift = 1 if omod == "mul:2" else 2 - if e >= 31 - shift: - h = sign | (0x7BFF if rtz else 0x7C00) - else: - h = (h + (shift << 10)) & 0xFFFF - - if has_clamp: - h = _clamp_f16(h, dx10_clamp=dx10_clamp) - - return ((hi_seed & 0xFFFF) << 16) | (h & 0xFFFF) - - -def kernel_lines(mode_name: str, mod: str) -> list[str]: - """Raw GFX10 kernel lines running every input in INPUTS sequentially on lane 0.""" - cfg = MODES[mode_name] - lines: list[str] = [] - if cfg["setreg_rtz"]: - lines.append("s_setreg_imm32_b32 hwreg(HW_REG_MODE, 2, 2), 3") - lines.append("s_nop 2") - suffix = f" {mod}" if mod else "" - for idx, (_, bits) in enumerate(INPUTS): - lines.append(f"v_mov_b32_e32 v1, {bits:#010x}") - lines.append(f"v_mov_b32_e32 v2, {SEED_WORD:#010x}") - lines.append(f"v_cvt_f16_f32_e64 v2, v1{suffix}") - lines.append(f"v_mov_b32_e32 v3, {idx * 4}") - lines.append("global_store_dword v3, v2, s[2:3]") - lines.append("s_waitcnt vmcnt(0)") - lines.append("s_endpgm") - return lines - - -def build_jobs(modes: list[str], waves: list[int]): - """Build (kernels, metadata) pairs for oracle.run().""" - from hw_oracle import asm - - kernels, meta = [], [] - for wave in waves: - for mode_name in modes: - mdict = dict(MODES[mode_name]["descriptor"]) - for mod in MODS: - lines = kernel_lines(mode_name, mod) - kernels.append( - asm.Kernel(lines, wave=wave, threads=1, words=len(INPUTS), raw=True, mode=mdict) - ) - meta.append((wave, mode_name, mod)) - return kernels, meta - - -def evaluate_results(modes: list[str], waves: list[int], meta, raw_results) -> dict: - """Compare hardware outputs against expected_cvt_f16_omod and check wave32 vs wave64 parity.""" - by_key: dict[tuple[int, str, str], list[int]] = {} - harness_errors: list[dict] = [] - for (wave, mode_name, mod), res in zip(meta, raw_results): - if isinstance(res, str): - harness_errors.append({"wave": wave, "mode": mode_name, "mod": mod, "error": res}) - continue - if len(res) != len(INPUTS): - harness_errors.append({ - "wave": wave, - "mode": mode_name, - "mod": mod, - "error": f"expected {len(INPUTS)} words, got {len(res)}", - }) - continue - by_key[(wave, mode_name, mod)] = [w & 0xFFFFFFFF for w in res] - - if harness_errors: - return { - "total_cases": len(meta) * len(INPUTS), - "lo_mismatches": 0, - "hi_mismatches": 0, - "wave_diffs": 0, - "dyn_rtz_diffs": 0, - "harness_errors": harness_errors, - "first_mismatches": [], - "first_wave_diffs": [], - } - - lo_mismatches = 0 - hi_mismatches = 0 - first_mismatches: list[dict] = [] - for wave in waves: - for mode_name in modes: - cfg = MODES[mode_name] - for mod in MODS: - got_words = by_key[(wave, mode_name, mod)] - for (iname, bits), got in zip(INPUTS, got_words): - want = expected_cvt_f16_omod( - bits, - mod, - rtz=cfg["rtz"], - denorm_keep=cfg["denorm_keep"], - ieee=cfg["ieee"], - dx10_clamp=cfg["dx10_clamp"], - ) - if (got >> 16) != HI_SEED: - hi_mismatches += 1 - if (got & 0xFFFF) != (want & 0xFFFF): - lo_mismatches += 1 - if got != want and len(first_mismatches) < 16: - first_mismatches.append({ - "wave": wave, - "mode": mode_name, - "mod": mod, - "input": iname, - "f32": f"0x{bits:08x}", - "got": f"0x{got:08x}", - "want": f"0x{want:08x}", - }) - - wave_diffs = 0 - first_wave_diffs: list[dict] = [] - if len(waves) > 1: - w0 = waves[0] - for w in waves[1:]: - for mode_name in modes: - for mod in MODS: - for (iname, _), a_w, b_w in zip(INPUTS, by_key[(w0, mode_name, mod)], by_key[(w, mode_name, mod)]): - if a_w != b_w: - wave_diffs += 1 - if len(first_wave_diffs) < 16: - first_wave_diffs.append({ - "mode": mode_name, - "mod": mod, - "input": iname, - f"w{w0}": f"0x{a_w:08x}", - f"w{w}": f"0x{b_w:08x}", - }) - - dyn_rtz_diffs = 0 - if "rtz_d0_i0" in modes and "dyn_rtz_d0_i0" in modes: - for wave in waves: - for mod in MODS: - for a_w, b_w in zip(by_key[(wave, "rtz_d0_i0", mod)], by_key[(wave, "dyn_rtz_d0_i0", mod)]): - if a_w != b_w: - dyn_rtz_diffs += 1 - - return { - "total_cases": len(waves) * len(modes) * len(MODS) * len(INPUTS), - "lo_mismatches": lo_mismatches, - "hi_mismatches": hi_mismatches, - "wave_diffs": wave_diffs, - "dyn_rtz_diffs": dyn_rtz_diffs, - "harness_errors": [], - "first_mismatches": first_mismatches, - "first_wave_diffs": first_wave_diffs, - } - - -def write_report(path: str, doc: dict) -> bool: - """Write JSON report with LF line endings, creating parent folders.""" - try: - os.makedirs(os.path.dirname(os.path.abspath(path)), exist_ok=True) - with open(path, "w", encoding="utf-8", newline="\n") as f: - json.dump(doc, f, indent=1) - f.write("\n") - except OSError as e: - print(f"ERROR: cannot write {path}: {e}", file=sys.stderr) - return False - return True - - -def self_test() -> int: - """Verify the reference model and kernel generator against hand-checked values without GPU or clang.""" - # RNE vs RTZ conversion and omod overflow - assert expected_cvt_f16_omod(_f32_bits(32768.0), "mul:2", rtz=False, denorm_keep=False, ieee=False) == 0xAAAA7C00 - assert expected_cvt_f16_omod(_f32_bits(32768.0), "mul:2", rtz=True, denorm_keep=False, ieee=False) == 0xAAAA7BFF - assert expected_cvt_f16_omod(_f32_bits(-32768.0), "mul:2", rtz=True, denorm_keep=False, ieee=False) == 0xAAAAFBFF - assert expected_cvt_f16_omod(_f32_bits(16384.0), "mul:4", rtz=True, denorm_keep=False, ieee=False) == 0xAAAA7BFF - assert expected_cvt_f16_omod(_f32_bits(65520.0), "div:2", rtz=False, denorm_keep=False, ieee=False) == 0xAAAA7C00 - assert expected_cvt_f16_omod(_f32_bits(65520.0), "div:2", rtz=True, denorm_keep=False, ieee=False) == 0xAAAA77FF - assert expected_cvt_f16_omod(_f32_bits(-65520.0), "div:2", rtz=True, denorm_keep=False, ieee=False) == 0xAAAAF7FF - assert expected_cvt_f16_omod(0x7F800000, "mul:2", rtz=True, denorm_keep=False, ieee=False) == 0xAAAA7C00 - # div:2 underflow from exponent 1 preserves sign; exponent 0 flushes to +0 - assert expected_cvt_f16_omod(_f32_bits(-(2.0 ** -14)), "div:2", rtz=False, denorm_keep=False, ieee=False) == 0xAAAA8000 - assert expected_cvt_f16_omod(_f32_bits(-1.5 * (2.0 ** -14)), "div:2", rtz=True, denorm_keep=False, ieee=False) == 0xAAAA8000 - assert expected_cvt_f16_omod(0xB8FFE000, "div:2", rtz=False, denorm_keep=False, ieee=False) == 0xAAAA8000 - assert expected_cvt_f16_omod(0xB8FFFE00, "div:2", rtz=False, denorm_keep=False, ieee=False) == 0xAAAA8400 - assert expected_cvt_f16_omod(0xB8FFFE00, "div:2", rtz=True, denorm_keep=False, ieee=False) == 0xAAAA8000 - assert expected_cvt_f16_omod(0x80000000, "div:2", rtz=False, denorm_keep=False, ieee=False) == 0xAAAA0000 - assert expected_cvt_f16_omod(_f32_bits(-(2.0 ** -15)), "div:2", rtz=False, denorm_keep=False, ieee=False) == 0xAAAA0000 - assert expected_cvt_f16_omod(_f32_bits(-(2.0 ** -14)), "clamp div:2", rtz=False, denorm_keep=False, ieee=False) == 0xAAAA0000 - # denorm_keep=True or ieee=True ignores omod while keeping clamp - assert expected_cvt_f16_omod(_f32_bits(0.75), "mul:2", rtz=True, denorm_keep=True, ieee=False) == 0xAAAA3A00 - assert expected_cvt_f16_omod(_f32_bits(0.75), "clamp mul:2", rtz=True, denorm_keep=False, ieee=False) == 0xAAAA3C00 - assert expected_cvt_f16_omod(_f32_bits(0.75), "clamp mul:2", rtz=True, denorm_keep=False, ieee=True) == 0xAAAA3A00 - assert expected_cvt_f16_omod(0x7FC01234, "clamp mul:2", rtz=True, denorm_keep=False, ieee=False) == 0xAAAA0000 - # Kernel assembly sanity - kl = kernel_lines("dyn_rtz_d0_i0", "clamp mul:2") - assert kl[0] == "s_setreg_imm32_b32 hwreg(HW_REG_MODE, 2, 2), 3" - assert kl[-2:] == ["s_waitcnt vmcnt(0)", "s_endpgm"] - assert any("v_cvt_f16_f32_e64 v2, v1 clamp mul:2" == ln for ln in kl) - print(f"self-test ok ({len(INPUTS)} inputs, {len(MODES) * len(MODS) * len(INPUTS)} cases/wave)") - return 0 - - -def main(argv=None) -> int: - ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) - ap.add_argument("--modes", default=",".join(MODES)) - ap.add_argument("--waves", default="32,64") - ap.add_argument("--json", help="write measurement summary JSON here") - ap.add_argument("--hw-arch") - ap.add_argument("--self-test", action="store_true") - a = ap.parse_args(argv) - if a.self_test: - return self_test() - - modes = [m.strip() for m in a.modes.split(",") if m.strip()] - wave_tokens = [w.strip() for w in a.waves.split(",") if w.strip()] - bad_modes = [m for m in modes if m not in MODES] - bad_waves = [w for w in wave_tokens if w not in ("32", "64")] - if bad_modes or bad_waves or not modes or not wave_tokens: - ap.error("unknown or empty: " + ", ".join(bad_modes + bad_waves or ["--modes/--waves"])) - waves = [int(w) for w in wave_tokens] - if a.json and os.path.isdir(a.json): - ap.error(f"--json {a.json} is a folder, not a file") - - from hw_oracle import asm, runner - - try: - oracle = runner.open_oracle(arch=a.hw_arch) - except runner.Unavailable as e: - print(f"hardware oracle unavailable: {e}") - return 77 - - try: - if asm.family(oracle.arch) != "gfx10": - print(f"hardware oracle unavailable: {oracle.arch} is not GFX10") - return 77 - print(f"hardware oracle: {oracle.device} ({oracle.arch})") - kernels, meta = build_jobs(modes, waves) - raw_results = oracle.run(kernels) - summary = evaluate_results(modes, waves, meta, raw_results) - except RuntimeError as e: - print(f"harness error: {e}") - return 2 - finally: - oracle.close() - - report = { - "device": str(oracle.device), - "arch": oracle.arch, - "waves": waves, - "modes": modes, - "mods": list(MODS), - "inputs": len(INPUTS), - **summary, - } - if a.json and not write_report(a.json, report): - return 2 - - if summary["harness_errors"]: - for err in summary["harness_errors"][:5]: - print(f"harness error: wave{err['wave']} {err['mode']} {err['mod']!r}: {err['error']}") - return 2 - - print( - f"{summary['total_cases']} evaluations across {len(waves)} wave(s) x {len(modes)} mode(s) x " - f"{len(MODS)} mod(s): lo_mismatches={summary['lo_mismatches']}, hi_mismatches={summary['hi_mismatches']}, " - f"wave_diffs={summary['wave_diffs']}, dyn_rtz_diffs={summary['dyn_rtz_diffs']}" - ) - for m in summary["first_mismatches"]: - print(f" MISMATCH wave{m['wave']} {m['mode']} {m['mod']!r} {m['input']} ({m['f32']}): got {m['got']}, want {m['want']}") - for d in summary["first_wave_diffs"]: - print(f" WAVE DIFF {d['mode']} {d['mod']!r} {d['input']}: {d}") - - if summary["lo_mismatches"] or summary["hi_mismatches"] or summary["wave_diffs"] or summary["dyn_rtz_diffs"]: - return 1 - return 0 - - -if __name__ == "__main__": - try: - sys.stdout.reconfigure(errors="replace") - except (AttributeError, ValueError, OSError): - pass - sys.exit(main()) diff --git a/tools/cvt_norm_mods_probe.py b/tools/cvt_norm_mods_probe.py deleted file mode 100644 index b8fdeb6c1..000000000 --- a/tools/cvt_norm_mods_probe.py +++ /dev/null @@ -1,667 +0,0 @@ -r"""Measure RDNA2 VOP3/SDWA output modifiers on v_cvt_norm_{i16,u16}_f16 and v_cvt_pknorm_{i16,u16}_f32. - -Standard library only. Uses `tools/hw_oracle` to run native RDNA2 ISA kernels on AMD GFX10 hardware: -- `v_cvt_norm_i16_f16`, `v_cvt_norm_u16_f16`: exhaustive 65,536-input f16 sweeps across VOP3 `_e64` - (`plain`, `clamp`, `mul:2`, `mul:4`, `div:2`, `clamp mul:2`, `clamp div:2`) in wave32 and wave64, - plus `HW_REG_MODE` (`RTZ`, `IEEE=1`), `_e64` high-half preservation / `abs` / `neg`, and `_sdwa` `clamp` - (`WORD_0`/`WORD_1`, `UNUSED_PRESERVE`/`UNUSED_SEXT`/`UNUSED_PAD`). -- `v_cvt_pknorm_i16_f32`, `v_cvt_pknorm_u16_f32`: 40 edge, NaN, inf, subnormal, out-of-range, and single-rounding - near-tie pairs across `plain` vs VOP3 `clamp`, 6 `HW_REG_MODE` states, source modifiers, and wave32/wave64. - -Usage: - python -I tools/cvt_norm_mods_probe.py [--waves 32,64] [--ops ...] [--hw-arch gfx1036] [--json out.json] - python -I tools/cvt_norm_mods_probe.py --self-test - -Exit codes: - 0 all hardware outputs match the reference model across requested waves (with wave32 == wave64) - 1 at least one word mismatch or wave32/wave64 difference - 2 bad CLI arguments, unwritable --json path, or harness error - 77 hardware oracle unavailable or GPU is not GFX10 -""" -from __future__ import annotations - -import argparse -from fractions import Fraction -import json -import os -import sys - -HERE = os.path.dirname(os.path.abspath(__file__)) -sys.dont_write_bytecode = True -if HERE not in sys.path: - sys.path.insert(0, HERE) - -M16 = 0xFFFF -M32 = 0xFFFFFFFF - -NORM_F16_OPS = ("v_cvt_norm_i16_f16", "v_cvt_norm_u16_f16") -PKNORM_F32_OPS = ("v_cvt_pknorm_i16_f32", "v_cvt_pknorm_u16_f32") -OPS: tuple[str, ...] = NORM_F16_OPS + PKNORM_F32_OPS - -VOP3_NORM_MODS: tuple[str, ...] = ( - "", - "clamp", - "mul:2", - "mul:4", - "div:2", - "clamp mul:2", - "clamp div:2", -) - -NORM_MODE_VARIANTS: tuple[tuple[str, int], ...] = ( - ("rtz16", 0x000000CC), # round16_64=3 (RTZ), denorm16_64=3 - ("ieee1", 0x000002C0), # IEEE=1, denorm16_64=3 -) - -PKNORM_MODES: tuple[tuple[str, int], ...] = ( - ("game", 0x000001C0), # IEEE=0, DX10_CLAMP=1, denorm32=0, denorm16_64=3, RNE - ("ieee0_dx0", 0x000000C0), # IEEE=0, DX10_CLAMP=0, denorm32=0, denorm16_64=3, RNE - ("ieee1_dx0", 0x000002C0), # IEEE=1, DX10_CLAMP=0, denorm32=0, denorm16_64=3, RNE - ("ieee1_dx1", 0x000003C0), # IEEE=1, DX10_CLAMP=1, denorm32=0, denorm16_64=3, RNE - ("rtz", 0x000001CF), # FP_ROUND32=RTZ, FP_ROUND16_64=RTZ, DX10_CLAMP=1 - ("den32_keep", 0x000001F0), # denorm32=3, denorm16_64=3, DX10_CLAMP=1, RNE -) - -# 40 f32 bit patterns: +-0, subnormals, near-ties from pknorm_probe.py, scale steps, +-0.25/0.5/1/2, huge, +-inf, NaNs. -PKNORM_F32_VALUES: tuple[int, ...] = ( - 0x00000000, 0x80000000, # +0, -0 - 0x00000001, 0x80000001, # min subnormal - 0x007FFFFF, 0x807FFFFF, # max subnormal - 0x37800000, 0xB7800000, # +-2^-16 - 0x37800080, 0xB7800080, # just above 0.5 / 32767 - 0x37000040, 0x37000080, # near 0.5 / 65535 - 0x38400180, 0x38E001C0, # pknorm_probe.py near-ties (i16) - 0x39300160, 0x3C004101, - 0x3C014103, 0x3C024105, - 0x37C000C0, 0x386000E0, # pknorm_probe.py near-ties (u16) - 0x38B000B0, 0x3B008081, - 0x3B028083, 0x3B048085, - 0x3E800000, 0xBE800000, # +-0.25 - 0x3F000000, 0xBF000000, # +-0.5 (exact halfway ties) - 0x3F000100, 0xBF000100, # near +-0.5 - 0x3F7FFFFF, 0xBF7FFFFF, # just below +-1.0 - 0x3F800000, 0xBF800000, # +-1.0 - 0x3FC00000, 0xBFC00000, # +-1.5 - 0x40000000, 0xC0000000, # +-2.0 - 0x60000000, 0xE0000000, # huge finite - 0x7F800000, 0xFF800000, # +inf, -inf - 0x7FC00000, 0xFFC00000, # +qNaN, -qNaN - 0x7F800001, 0xFF800001, # +sNaN, -sNaN - 0x7FC01234, 0xFFC01234, # payload qNaN -) - -PKNORM_PAIRS: tuple[tuple[int, int], ...] = tuple( - (PKNORM_F32_VALUES[i], PKNORM_F32_VALUES[(i * 7 + 3) % len(PKNORM_F32_VALUES)]) - for i in range(40) -) - -# SDWA cases for v_cvt_norm_{i16,u16}_f16. Input register v1 = 0x3800B800 (hi=+0.5, lo=-0.5), v0 seeded with 0xCAFE1234. -SDWA_CASES: tuple[tuple[str, int, int, str, str, str], ...] = ( - # (label, seed_v0, src_v1, mod_prefix, src_expr, tail) - ("w1_preserve", 0xCAFE1234, 0x3800B800, "", "v1", "dst_sel:WORD_1 dst_unused:UNUSED_PRESERVE src0_sel:WORD_1"), - ("w0_preserve", 0xCAFE1234, 0x3800B800, "", "v1", "dst_sel:WORD_0 dst_unused:UNUSED_PRESERVE src0_sel:WORD_0"), - ("w0_sext", 0xCAFE1234, 0x3800B800, "", "v1", "dst_sel:WORD_0 dst_unused:UNUSED_SEXT src0_sel:WORD_0"), - ("w0_pad", 0xCAFE1234, 0x3800B800, "", "v1", "dst_sel:WORD_0 dst_unused:UNUSED_PAD src0_sel:WORD_0"), - ("w1_abs", 0xCAFE1234, 0xB8003800, "", "|v1|", "dst_sel:WORD_1 dst_unused:UNUSED_PRESERVE src0_sel:WORD_1"), - ("w0_neg", 0xCAFE1234, 0x38003800, "", "-v1", "dst_sel:WORD_0 dst_unused:UNUSED_PRESERVE src0_sel:WORD_0"), -) - - -def _f16_to_frac(h: int) -> Fraction | str: - h &= M16 - sign = (h >> 15) & 1 - exp = (h >> 10) & 0x1F - mant = h & 0x3FF - if exp == 31: - return "nan" if mant else ("-inf" if sign else "+inf") - if exp == 0: - val = Fraction(mant, 1 << 24) - elif exp <= 25: - val = Fraction(1024 + mant, 1 << (25 - exp)) - else: - val = Fraction((1024 + mant) << (exp - 25), 1) - return -val if sign else val - - -def expected_norm_f16(h: int, snorm: bool) -> int: - """Exact rational result for v_cvt_norm_i16_f16 (snorm=True) or v_cvt_norm_u16_f16 (snorm=False).""" - v = _f16_to_frac(h) - if v == "nan": - return 0 - if v == "-inf": - return (-32767) & M16 if snorm else 0 - if v == "+inf": - return 32767 if snorm else 65535 - lo = Fraction(-1, 1) if snorm else Fraction(0, 1) - if v < lo: - v = lo - elif v > 1: - v = Fraction(1, 1) - return round(v * (32767 if snorm else 65535)) & M16 - - -def _f32_to_frac(u: int) -> Fraction | str: - u &= M32 - sign = (u >> 31) & 1 - exp = (u >> 23) & 0xFF - mant = u & 0x7FFFFF - if exp == 255: - return "nan" if mant else ("-inf" if sign else "+inf") - if exp == 0: - val = Fraction(mant, 1 << 149) - elif exp <= 150: - val = Fraction((1 << 23) + mant, 1 << (150 - exp)) - else: - val = Fraction(((1 << 23) + mant) << (exp - 150), 1) - return -val if sign else val - - -def expected_pknorm_f32_lane(u: int, snorm: bool, *, flush_denorm: bool = True) -> int: - """Exact single-rounded 16-bit result for one lane of v_cvt_pknorm_{i16,u16}_f32.""" - u &= M32 - if flush_denorm and ((u >> 23) & 0xFF) == 0: - return 0 - v = _f32_to_frac(u) - if v == "nan": - return 0 - if v == "-inf": - return (-32767) & M16 if snorm else 0 - if v == "+inf": - return 32767 if snorm else 65535 - lo = Fraction(-1, 1) if snorm else Fraction(0, 1) - if v < lo: - v = lo - elif v > 1: - v = Fraction(1, 1) - return round(v * (32767 if snorm else 65535)) & M16 - - -def expected_pknorm_f32(op: str, s0: int, s1: int, *, flush_denorm: bool = True) -> int: - """Expected packed 32-bit dword for v_cvt_pknorm_i16_f32 or v_cvt_pknorm_u16_f32.""" - if op not in PKNORM_F32_OPS: - raise ValueError(f"unknown pknorm op: {op}") - snorm = op == "v_cvt_pknorm_i16_f32" - lo = expected_pknorm_f32_lane(s0, snorm, flush_denorm=flush_denorm) - hi = expected_pknorm_f32_lane(s1, snorm, flush_denorm=flush_denorm) - return lo | (hi << 16) - - -def _apply_f16_src_mod(h: int, src_expr: str) -> int: - h &= M16 - if "|" in src_expr: - h &= 0x7FFF - if src_expr.startswith("-"): - h ^= 0x8000 - return h - - -def expected_sdwa_words(op: str) -> list[int]: - """Expected 32-bit words for SDWA_CASES on op (plain or clamp).""" - snorm = op == "v_cvt_norm_i16_f16" - out: list[int] = [] - for _, seed_v0, src_v1, _, src_expr, tail in SDWA_CASES: - src_hi = "src0_sel:WORD_1" in tail - h = (src_v1 >> 16) & M16 if src_hi else (src_v1 & M16) - h = _apply_f16_src_mod(h, src_expr) - val16 = expected_norm_f16(h, snorm) - if "dst_sel:WORD_1" in tail: - word = (val16 << 16) | (seed_v0 & M16) - elif "UNUSED_PRESERVE" in tail: - word = (seed_v0 & 0xFFFF0000) | val16 - elif "UNUSED_SEXT" in tail: - word = (0xFFFF0000 | val16) if (val16 & 0x8000) else val16 - else: - word = val16 - out.append(word & M32) - return out - - -def expected_sweep_words(op: str) -> list[int]: - """All 32,768 packed dwords (65,536 f16 inputs) for v_cvt_norm_{i16,u16}_f16.""" - snorm = op == "v_cvt_norm_i16_f16" - return [ - expected_norm_f16(2 * wi, snorm) | (expected_norm_f16(2 * wi + 1, snorm) << 16) - for wi in range(32768) - ] - - -def sweep_kernel_lines(op: str, mod_str: str, base_word: int, label: str, mode_val: int | None = None) -> list[str]: - """GFX10 kernel evaluating 32,768 sequential f16 inputs as 16,384 packed dwords.""" - mod_suf = (" " + mod_str) if mod_str else "" - lines: list[str] = [] - if mode_val is not None: - lines.append(f"s_setreg_imm32_b32 hwreg(HW_REG_MODE), {mode_val:#010x}") - lines += [ - "v_mov_b32_e32 v2, 0", - "v_mov_b32_e32 v3, 0", - "v_lshlrev_b32_e32 v10, 4, v0", - f"v_add_nc_u32_e32 v11, {base_word}, v10", - "v_lshlrev_b32_e32 v12, 1, v11", - "v_lshlrev_b32_e32 v13, 2, v10", - "s_mov_b32 s4, 16", - f"{label}:", - f"{op}_e64 v2, v12{mod_suf}", - "v_add_nc_u32_e32 v14, 1, v12", - f"{op}_e64 v3, v14{mod_suf}", - "v_lshl_or_b32 v4, v3, 16, v2", - "global_store_dword v13, v4, s[2:3]", - "v_add_nc_u32_e32 v12, 2, v12", - "v_add_nc_u32_e32 v13, 4, v13", - "s_sub_u32 s4, s4, 1", - "s_cmp_lg_u32 s4, 0", - f"s_cbranch_scc1 {label}", - "s_waitcnt vmcnt(0)", - "s_endpgm", - ] - return lines - - -def sdwa_kernel_lines(op: str, clamp: bool) -> list[str]: - """GFX10 kernel testing SDWA plain vs clamp, dst_unused forms, and VOP3 preservation.""" - c_mod = " clamp" if clamp else "" - lines: list[str] = [] - for idx, (_, seed_v0, src_v1, _, src_expr, tail) in enumerate(SDWA_CASES): - lines += [ - f"v_mov_b32_e32 v0, {seed_v0:#010x}", - f"v_mov_b32_e32 v1, {src_v1:#010x}", - f"{op}_sdwa v0, {src_expr}{c_mod} {tail}", - f"v_mov_b32_e32 v12, {idx * 4}", - "global_store_dword v12, v0, s[2:3]", - ] - # Also verify VOP3 _e64 preserves the high half of v0 under clamp and omod. - vop3_mods = ("clamp", "mul:2", "mul:4", "div:2") if clamp else ("",) - base_idx = len(SDWA_CASES) - for k, mod in enumerate(vop3_mods): - suf = (" " + mod) if mod else "" - lines += [ - "v_mov_b32_e32 v0, 0xCAFE1234", - "v_mov_b32_e32 v1, 0xB8003800", # lo=+0.5, hi=-0.5 - f"{op}_e64 v0, -|v1|{suf}", - f"v_mov_b32_e32 v12, {(base_idx + k) * 4}", - "global_store_dword v12, v0, s[2:3]", - ] - lines += ["s_waitcnt vmcnt(0)", "s_endpgm"] - return lines - - -def expected_sdwa_and_pres_words(op: str, clamp: bool) -> list[int]: - words = expected_sdwa_words(op) - snorm = op == "v_cvt_norm_i16_f16" - # -|0x3800| = -0.5 -> 0xB800 - val16 = expected_norm_f16(0xB800, snorm) - pres_word = 0xCAFE0000 | val16 - count = 4 if clamp else 1 - return words + [pres_word] * count - - -def pknorm_kernel_lines(op: str, clamp: bool, mode_val: int) -> list[str]: - """GFX10 kernel running PKNORM_PAIRS + source modifier checks under one HW_REG_MODE.""" - suf = " clamp" if clamp else "" - lines: list[str] = [f"s_setreg_imm32_b32 hwreg(HW_REG_MODE), {mode_val:#010x}"] - for idx, (a, b) in enumerate(PKNORM_PAIRS): - lines += [ - f"v_mov_b32_e32 v1, {a:#010x}", - f"v_mov_b32_e32 v2, {b:#010x}", - f"{op} v0, v1, v2{suf}", - f"v_mov_b32_e32 v12, {idx * 4}", - "global_store_dword v12, v0, s[2:3]", - ] - # Also check VOP3 source modifiers (-v1, |v2|, -|v1|) with clamp. - mod_cases = ( - (0x3F000000, 0xBF000000, "-v1, |v2|"), - (0xBF000000, 0x3F000000, "|v1|, -v2"), - (0x3F800000, 0x3F000000, "-|v1|, -|v2|"), - ) - base_idx = len(PKNORM_PAIRS) - for k, (a, b, expr) in enumerate(mod_cases): - lines += [ - f"v_mov_b32_e32 v1, {a:#010x}", - f"v_mov_b32_e32 v2, {b:#010x}", - f"{op} v0, {expr}{suf}", - f"v_mov_b32_e32 v12, {(base_idx + k) * 4}", - "global_store_dword v12, v0, s[2:3]", - ] - lines += ["s_waitcnt vmcnt(0)", "s_endpgm"] - return lines - - -def expected_pknorm_words(op: str) -> list[int]: - words = [expected_pknorm_f32(op, a, b) for a, b in PKNORM_PAIRS] - # (-0.5, |-0.5|), (|-0.5|, -0.5), (-|1.0|, -|0.5|) - mod_inputs = ( - (0xBF000000, 0x3F000000), - (0x3F000000, 0xBF000000), - (0xBF800000, 0xBF000000), - ) - words.extend(expected_pknorm_f32(op, a, b) for a, b in mod_inputs) - return words - - -def build_jobs(ops: list[str], waves: list[int]): - """Build (kernels, metadata) pairs for oracle.run().""" - from hw_oracle import asm - - kernels = [] - meta = [] - label_id = 0 - - for op in ops: - if op in NORM_F16_OPS: - exp_full = expected_sweep_words(op) - for wave in waves: - for mod_str in VOP3_NORM_MODS: - mod_key = mod_str or "plain" - for part, base_word in enumerate((0, 16384)): - lbl = f".L_cvt_loop_{label_id}" - label_id += 1 - lines = sweep_kernel_lines(op, mod_str, base_word, lbl) - kernels.append(asm.Kernel(lines, wave=wave, threads=1024, words=16384, raw=True)) - exp_slice = exp_full[base_word : base_word + 16384] - meta.append(("sweep", op, wave, f"{mod_key}_p{part}", bool(mod_str), exp_slice)) - for clamp in (False, True): - lines = sdwa_kernel_lines(op, clamp) - exp = expected_sdwa_and_pres_words(op, clamp) - kernels.append(asm.Kernel(lines, wave=wave, threads=1, words=len(exp), raw=True)) - meta.append(("sdwa", op, wave, "clamp" if clamp else "plain", clamp, exp)) - # MODE tests (RTZ and IEEE=1) on the first requested wave. - mode_wave = waves[0] - for mode_name, mode_val in NORM_MODE_VARIANTS: - for part, base_word in enumerate((0, 16384)): - lbl = f".L_cvt_loop_{label_id}" - label_id += 1 - lines = sweep_kernel_lines(op, "", base_word, lbl, mode_val=mode_val) - kernels.append(asm.Kernel(lines, wave=mode_wave, threads=1024, words=16384, raw=True)) - exp_slice = exp_full[base_word : base_word + 16384] - meta.append(("mode", op, mode_wave, f"{mode_name}_p{part}", False, exp_slice)) - elif op in PKNORM_F32_OPS: - exp_pk = expected_pknorm_words(op) - for wave in waves: - for mode_name, mode_val in PKNORM_MODES: - for clamp in (False, True): - lines = pknorm_kernel_lines(op, clamp, mode_val) - kernels.append(asm.Kernel(lines, wave=wave, threads=1, words=len(exp_pk), raw=True)) - meta.append(("pknorm", op, wave, mode_name, clamp, exp_pk)) - else: - raise ValueError(f"unknown op: {op}") - - return kernels, meta - - -def evaluate_results(waves: list[int], meta, raw_results) -> dict: - """Compare hardware outputs against expected words and check wave32 == wave64.""" - by_key: dict[tuple[str, str, int, str, bool], list[int]] = {} - harness_errors: list[dict] = [] - total_words = 0 - - for (kind, op, wave, variant, clamp, expected), res in zip(meta, raw_results): - total_words += len(expected) - if isinstance(res, str): - harness_errors.append({"kind": kind, "op": op, "wave": wave, "variant": variant, "error": res}) - continue - if len(res) != len(expected): - harness_errors.append({ - "kind": kind, - "op": op, - "wave": wave, - "variant": variant, - "error": f"expected {len(expected)} words, got {len(res)}", - }) - continue - by_key[(kind, op, wave, variant, clamp)] = [w & M32 for w in res] - - if harness_errors: - return { - "total_words": total_words, - "mismatches": 0, - "wave_diffs": 0, - "harness_errors": harness_errors, - "mismatch_details": [], - "wave_diff_details": [], - } - - mismatches = 0 - mismatch_details: list[dict] = [] - for (kind, op, wave, variant, clamp, expected), res in zip(meta, raw_results): - words = [w & M32 for w in res] - for idx, (got_w, exp_w) in enumerate(zip(words, expected)): - if got_w != exp_w: - mismatches += 1 - if len(mismatch_details) < 32: - mismatch_details.append({ - "kind": kind, - "op": op, - "wave": wave, - "variant": variant, - "clamp": clamp, - "word_idx": idx, - "expected": f"0x{exp_w:08x}", - "actual": f"0x{got_w:08x}", - }) - - wave_diffs = 0 - wave_diff_details: list[dict] = [] - if 32 in waves and 64 in waves: - seen_pairs: set[tuple[str, str, str, bool]] = set() - for kind, op, wave, variant, clamp, _ in meta: - if kind == "mode": - continue - pkey = (kind, op, variant, clamp) - if pkey in seen_pairs: - continue - seen_pairs.add(pkey) - k32 = (kind, op, 32, variant, clamp) - k64 = (kind, op, 64, variant, clamp) - if k32 not in by_key or k64 not in by_key: - continue - for idx, (w32, w64) in enumerate(zip(by_key[k32], by_key[k64])): - if w32 != w64: - wave_diffs += 1 - if len(wave_diff_details) < 32: - wave_diff_details.append({ - "kind": kind, - "op": op, - "variant": variant, - "clamp": clamp, - "word_idx": idx, - "wave32": f"0x{w32:08x}", - "wave64": f"0x{w64:08x}", - }) - - return { - "total_words": total_words, - "mismatches": mismatches, - "wave_diffs": wave_diffs, - "harness_errors": [], - "mismatch_details": mismatch_details, - "wave_diff_details": wave_diff_details, - } - - -def self_test() -> int: - """Verify reference model, kernel construction, and evaluation logic without a GPU.""" - # 1. Exact v_cvt_norm_{i16,u16}_f16 edges & single-rounding ties near +-0.5. - assert expected_norm_f16(0x0000, True) == 0 - assert expected_norm_f16(0x8000, True) == 0 - assert expected_norm_f16(0x3C00, True) == 0x7FFF - assert expected_norm_f16(0xBC00, True) == 0x8001 - assert expected_norm_f16(0xFC00, True) == 0x8001 - assert expected_norm_f16(0x7E00, True) == 0 - assert expected_norm_f16(0x7C01, False) == 0 - assert expected_norm_f16(0x3800, True) == 16384 # 0.5 * 32767 = 16383.5 -> 16384 (even) - assert expected_norm_f16(0x3801, True) == 16399 # single rounding near +0.5 (double-rounding gives 16400) - assert expected_norm_f16(0x37FF, True) == 16376 # single rounding near +0.5 (double-rounding gives 16375) - assert expected_norm_f16(0x3800, False) == 32768 # 0.5 * 65535 = 32767.5 -> 32768 (even) - assert expected_norm_f16(0x3801, False) == 32799 - assert expected_norm_f16(0x37FF, False) == 32752 - - # 2. Exact v_cvt_pknorm_{i16,u16}_f32 near-ties & saturation. - assert expected_pknorm_f32("v_cvt_pknorm_i16_f32", 0x38400180, 0x00000000) == 0x00000001 - assert expected_pknorm_f32("v_cvt_pknorm_i16_f32", 0x3C004101, 0xBF800000) == 0x80010101 - assert expected_pknorm_f32("v_cvt_pknorm_u16_f32", 0x37C000C0, 0x40000000) == 0xFFFF0001 - assert expected_pknorm_f32("v_cvt_pknorm_u16_f32", 0x7FC00000, 0xFF800000) == 0x00000000 - - # 3. Exhaustive sweep builders produce 32,768 packed dwords, valid labels, and proper endpgm. - for op in NORM_F16_OPS: - assert len(expected_sweep_words(op)) == 32768 - l0 = sweep_kernel_lines(op, "clamp mul:2", 0, ".L_test_0") - l1 = sdwa_kernel_lines(op, True) - assert l0[-2:] == ["s_waitcnt vmcnt(0)", "s_endpgm"] - assert l1[-2:] == ["s_waitcnt vmcnt(0)", "s_endpgm"] - assert len(expected_sdwa_and_pres_words(op, True)) == len(SDWA_CASES) + 4 - for op in PKNORM_F32_OPS: - lp = pknorm_kernel_lines(op, True, 0x000001C0) - assert lp[-2:] == ["s_waitcnt vmcnt(0)", "s_endpgm"] - assert len(expected_pknorm_words(op)) == len(PKNORM_PAIRS) + 3 - - # 4. Synthetic evaluation checks pass, mismatch, and wave diff detection. - meta = [ - ("sdwa", "v_cvt_norm_i16_f16", 32, "clamp", True, expected_sdwa_and_pres_words("v_cvt_norm_i16_f16", True)), - ("sdwa", "v_cvt_norm_i16_f16", 64, "clamp", True, expected_sdwa_and_pres_words("v_cvt_norm_i16_f16", True)), - ("pknorm", "v_cvt_pknorm_u16_f32", 32, "game", True, expected_pknorm_words("v_cvt_pknorm_u16_f32")), - ("pknorm", "v_cvt_pknorm_u16_f32", 64, "game", True, expected_pknorm_words("v_cvt_pknorm_u16_f32")), - ] - raw_ok = [list(m[5]) for m in meta] - rep_ok = evaluate_results([32, 64], meta, raw_ok) - assert rep_ok["mismatches"] == 0 and rep_ok["wave_diffs"] == 0 and not rep_ok["harness_errors"], rep_ok - - raw_bad = [list(w) for w in raw_ok] - raw_bad[0][0] ^= 1 - rep_bad = evaluate_results([32, 64], meta, raw_bad) - assert rep_bad["mismatches"] == 1 and rep_bad["wave_diffs"] == 1, rep_bad - - print( - f"self-test ok ({len(OPS)} ops, {len(VOP3_NORM_MODS)} VOP3 norm mods, " - f"{len(SDWA_CASES)} SDWA cases, {len(PKNORM_PAIRS)} pknorm pairs)" - ) - return 0 - - -def _parse_waves(spec: str) -> list[int] | None: - parts = [p.strip() for p in spec.split(",")] - if not parts or any(not p for p in parts): - return None - try: - waves = [int(p) for p in parts] - except ValueError: - return None - if any(w not in (32, 64) for w in waves): - return None - return list(dict.fromkeys(waves)) - - -def _parse_ops(spec: str) -> list[str] | None: - parts = [p.strip() for p in spec.split(",")] - if not parts or any(not p for p in parts): - return None - if any(p not in OPS for p in parts): - return None - return list(dict.fromkeys(parts)) - - -def main(argv: list[str] | None = None) -> int: - ap = argparse.ArgumentParser(description=__doc__.splitlines()[0]) - ap.add_argument("--waves", default="32,64", help="comma-separated wave sizes (default: 32,64)") - ap.add_argument("--ops", default=",".join(OPS), help="comma-separated conversion opcodes to probe") - ap.add_argument("--hw-arch", default=None, help="override GPU architecture for hw_oracle") - ap.add_argument("--json", dest="json_out", default=None, help="write JSON report to this path") - ap.add_argument("--self-test", action="store_true", help="verify reference model and kernel generator without GPU") - args = ap.parse_args(argv) - - if args.self_test: - return self_test() - - waves = _parse_waves(args.waves) - if waves is None: - print(f"ERROR: --waves must list 32 and/or 64, got {args.waves!r}", file=sys.stderr) - return 2 - - ops = _parse_ops(args.ops) - if ops is None: - print(f"ERROR: unknown or malformed --ops {args.ops!r} (valid: {', '.join(OPS)})", file=sys.stderr) - return 2 - - if args.json_out is not None: - out_check = os.path.abspath(args.json_out) - if os.path.isdir(out_check): - print(f"ERROR: --json path is a directory: {out_check}", file=sys.stderr) - return 2 - - from hw_oracle import asm, runner - - try: - oracle = runner.open_oracle(arch=args.hw_arch) - except runner.Unavailable as e: - print(f"hardware oracle unavailable: {e}") - return 77 - - try: - try: - fam = asm.family(oracle.arch) - except ValueError: - fam = None - if fam != "gfx10": - print(f"skipping: requires GFX10 RDNA2 hardware, found {oracle.arch}") - return 77 - - kernels, meta = build_jobs(ops, waves) - raw_results = oracle.run(kernels, words=16384) - summary = evaluate_results(waves, meta, raw_results) - device = oracle.device - arch = oracle.arch - finally: - oracle.close() - - total_words = summary["total_words"] - print(f"cvt_norm_mods_probe on {device} ({arch}):") - if summary["harness_errors"]: - for err in summary["harness_errors"][:8]: - print(f" harness error ({err['kind']} wave{err['wave']} {err['op']} {err['variant']}): {err['error']}") - return 2 - - print( - f" {total_words} word evaluations across {len(waves)} wave(s) x {len(ops)} op(s): " - f"mismatches={summary['mismatches']}, wave_diffs={summary['wave_diffs']}" - ) - for d in summary["mismatch_details"]: - print( - f" MISMATCH {d['kind']} wave{d['wave']} {d['op']} {d['variant']} clamp={d['clamp']} " - f"w[{d['word_idx']}]: expected={d['expected']} actual={d['actual']}" - ) - for d in summary["wave_diff_details"]: - print( - f" WAVE DIFF {d['kind']} {d['op']} {d['variant']} clamp={d['clamp']} " - f"w[{d['word_idx']}]: wave32={d['wave32']} wave64={d['wave64']}" - ) - - if args.json_out is not None: - out_path = os.path.abspath(args.json_out) - if os.path.isdir(out_path): - print(f"ERROR: cannot write {out_path}: path is a directory", file=sys.stderr) - return 2 - payload = { - "device": device, - "arch": arch, - "waves": waves, - "ops": ops, - **summary, - } - try: - parent = os.path.dirname(out_path) - if parent: - os.makedirs(parent, exist_ok=True) - with open(out_path, "w", encoding="utf-8", newline="\n") as f: - json.dump(payload, f, indent=2) - f.write("\n") - except OSError as e: - print(f"ERROR: cannot write {out_path}: {e}", file=sys.stderr) - return 2 - - return 1 if (summary["mismatches"] or summary["wave_diffs"]) else 0 - - -if __name__ == "__main__": - try: - sys.stdout.reconfigure(errors="replace") - except (AttributeError, ValueError, OSError): - pass - sys.exit(main()) diff --git a/tools/cvt_pknorm_f16_probe.py b/tools/cvt_pknorm_f16_probe.py deleted file mode 100644 index b5afda03f..000000000 --- a/tools/cvt_pknorm_f16_probe.py +++ /dev/null @@ -1,685 +0,0 @@ -r"""Measure RDNA2 v_cvt_pknorm_i16_f16 and v_cvt_pknorm_u16_f16 on native hardware. Standard library only. - -Runs an exhaustive 65,536-input binary16 sweep across plain, VOP3 `clamp`, `op_sel:[0,0,1]`, and -`op_sel:[0,0,1] clamp` plus targeted edge cases (all 8 `op_sel:[s0,s1,d]` permutations, prior `vdst` -overwrite checks, double-rounding traps, `abs`/`neg`, inline f16/int constants, 16-bit literal, SGPR source, -destination aliasing, and raw `.long` VOP3 `omod=0..3` encodings) across wave32 and wave64 on GFX10 (`gfx1036`). - -Usage: - python -I tools/cvt_pknorm_f16_probe.py [--waves 32,64] [--ops ...] [--hw-arch gfx1036] [--json out.json] - python -I tools/cvt_pknorm_f16_probe.py --self-test - -Exit 0 when all hardware results match the exact Fraction reference across requested ops/waves with zero wave32/wave64 -diffs, zero clamp diffs, and zero raw-omod diffs; 1 on a mismatch or parity failure; 2 on a harness/CLI error; -77 when the hardware oracle is unavailable or the GPU is not GFX10. Nothing here reads game files. -""" -import argparse -from dataclasses import dataclass -from fractions import Fraction -import json -import math -import os -import struct -import sys - -HERE = os.path.dirname(os.path.abspath(__file__)) -sys.dont_write_bytecode = True -if HERE not in sys.path: - sys.path.insert(0, HERE) - -OPS: tuple[str, ...] = ("v_cvt_pknorm_i16_f16", "v_cvt_pknorm_u16_f16") -_OPCODES: dict[str, int] = {"v_cvt_pknorm_i16_f16": 0x12, "v_cvt_pknorm_u16_f16": 0x13} -SWEEP_MODES: tuple[tuple[str, bool, bool], ...] = ( - ("", False, False), - ("clamp", True, False), - ("op_sel:[0,0,1]", False, True), - ("op_sel:[0,0,1] clamp", True, True), -) -CLAMP_MODES: tuple[bool, ...] = (False, True) -SWEEP_WORDS_PER_HALF = 16384 - - -@dataclass(frozen=True) -class Case: - name: str - src0: int - src1: int - src0_asm: str | None = None - src1_asm: str | None = None - src0_abs: bool = False - src0_neg: bool = False - src1_abs: bool = False - src1_neg: bool = False - sel: tuple[int, int] = (0, 0) - dhi: int = 0 - emit_opsel: bool = False - init_dst: int = 0xDEADBEEF - alias: str | None = None # "src0" | "src1" | None - sgpr0: bool = False - raw_omod: int | None = None - - -CASES: tuple[Case, ...] = ( - # All 8 op_sel:[s0,s1,d] combinations on distinct lo/hi halves (hi0=1.0, lo0=0.25; hi1=-1.0, lo1=0.5+2^-11) - Case("opsel_000", 0x3C003400, 0xBC003801, sel=(0, 0), dhi=0, emit_opsel=True), - Case("opsel_001", 0x3C003400, 0xBC003801, sel=(0, 0), dhi=1, emit_opsel=True), - Case("opsel_010", 0x3C003400, 0xBC003801, sel=(0, 1), dhi=0, emit_opsel=True), - Case("opsel_011", 0x3C003400, 0xBC003801, sel=(0, 1), dhi=1, emit_opsel=True), - Case("opsel_100", 0x3C003400, 0xBC003801, sel=(1, 0), dhi=0, emit_opsel=True), - Case("opsel_101", 0x3C003400, 0xBC003801, sel=(1, 0), dhi=1, emit_opsel=True), - Case("opsel_110", 0x3C003400, 0xBC003801, sel=(1, 1), dhi=0, emit_opsel=True), - Case("opsel_111", 0x3C003400, 0xBC003801, sel=(1, 1), dhi=1, emit_opsel=True), - # Destination overwrite checks: op_sel[2]=1 zeroes D[15:0] regardless of prior vdst bits - Case("dst_zero_12345678", 0x3C003400, 0xBC003801, dhi=1, emit_opsel=True, init_dst=0x12345678), - Case("dst_zero_ffffffff", 0x3C003400, 0xBC003801, dhi=1, emit_opsel=True, init_dst=0xFFFFFFFF), - # Double-rounding traps and inf/NaN/denormal/zero boundaries - Case("trap_pos_neg_0p5_ulp", 0x7E003801, 0x3C00B801), - Case("trap_below_0p5_ulp", 0x000137FF, 0x8001B7FF), - Case("inf_pos_neg", 0x38007C00, 0x3800FC00), - Case("nan_q_and_s", 0x3C007E00, 0xBC007C01), - Case("signed_zeros_and_subnorm", 0x00018000, 0x80010000), - # Source abs/neg modifiers with op_sel - Case("abs_neg_opsel_110", 0x3C003400, 0xBC003801, src0_abs=True, src1_neg=True, sel=(1, 1), dhi=0, emit_opsel=True), - Case("negabs_abs_opsel_010", 0x3C003400, 0xBC003801, src0_abs=True, src0_neg=True, src1_abs=True, sel=(0, 1), dhi=0, emit_opsel=True), - Case("abs_neg_opsel_111", 0x3C003400, 0xBC003801, src0_abs=True, src1_neg=True, sel=(1, 1), dhi=1, emit_opsel=True), - # Inline f16 / integer constants (op_sel=1 on inline f16 reads high half 0x0000) - Case("inline_f16_pair", 0x00003800, 0x0000B800, src0_asm="0.5", src1_asm="-0.5"), - Case("inline_f16_sel100", 0x00003800, 0xBC003801, src0_asm="0.5", sel=(1, 0), dhi=0, emit_opsel=True), - Case("inline_1_0_sel100", 0x00003C00, 0xBC003801, src0_asm="1.0", sel=(1, 0), dhi=0, emit_opsel=True), - Case("inline_neg_f16_src", 0x00003800, 0xBC003801, src0_asm="0.5", src0_neg=True), - Case("inline_int_1_neg1", 0x00000001, 0xFFFFFFFF, src0_asm="1", src1_asm="-1"), - # 16-bit literal & SGPR source - Case("lit16_3800_sel000", 0x00003800, 0xBC003801, src0_asm="0x3800"), - Case("lit16_3800_sel100", 0x00003800, 0xBC003801, src0_asm="0x3800", sel=(1, 0), dhi=0, emit_opsel=True), - Case("sgpr0_opsel_100", 0x3C003400, 0xBC003801, sel=(1, 0), dhi=0, emit_opsel=True, sgpr0=True), - Case("sgpr0_opsel_101", 0x3C003400, 0xBC003801, sel=(1, 0), dhi=1, emit_opsel=True, sgpr0=True), - # Destination aliasing under op_sel[2]=1 - Case("dst_alias_src0_dhi", 0x3C003400, 0xBC003801, dhi=1, emit_opsel=True, alias="src0"), - Case("dst_alias_src1_dhi", 0x3C003400, 0xBC003801, dhi=1, emit_opsel=True, alias="src1"), - # Raw VOP3 omod bits [60:59] (llvm-mc rejects textual mul:*/div:* on this op; silicon ignores them) - Case("raw_omod_0", 0x3C003400, 0xBC003801, raw_omod=0), - Case("raw_omod_1", 0x3C003400, 0xBC003801, raw_omod=1), - Case("raw_omod_2", 0x3C003400, 0xBC003801, raw_omod=2), - Case("raw_omod_3", 0x3C003400, 0xBC003801, raw_omod=3), -) - - -def ref_norm16_f16(bits16: int, snorm: bool) -> int: - """Exact single-rounded normalized f16 -> snorm16/unorm16 word (NaN -> 0, +-inf saturate).""" - x = struct.unpack("= 1.0: - cl = Fraction(1) - else: - cl = Fraction(x) - scale = 32767 if snorm else 65535 - return round(cl * scale) & 0xFFFF - - -def _build_ref_table(snorm: bool) -> list[int]: - return [ref_norm16_f16(b, snorm) for b in range(65536)] - - -_REF_TABLES: dict[bool, list[int]] = {True: _build_ref_table(True), False: _build_ref_table(False)} - - -def expected_pknorm_f16( - op: str, - src0: int, - src1: int, - *, - sel: tuple[int, int] = (0, 0), - dhi: bool | int = False, - clamp: bool = False, - src0_abs: bool = False, - src0_neg: bool = False, - src1_abs: bool = False, - src1_neg: bool = False, -) -> int: - """Reference 32-bit packed result for v_cvt_pknorm_{i,u}16_f16; clamp is a no-op, dhi shifts << 16.""" - if op not in OPS: - raise ValueError(f"unsupported op: {op}") - del clamp # measured hardware no-op - snorm = op == "v_cvt_pknorm_i16_f16" - tab = _REF_TABLES[snorm] - halves = [] - for raw, hi, is_abs, is_neg in ( - (src0, sel[0], src0_abs, src0_neg), - (src1, sel[1], src1_abs, src1_neg), - ): - b = (raw >> (16 * hi)) & 0xFFFF - if is_abs: - b &= 0x7FFF - if is_neg: - b ^= 0x8000 - halves.append(tab[b]) - packed = halves[0] | (halves[1] << 16) - if dhi: - return (packed << 16) & 0xFFFFFFFF - return packed - - -def sweep_kernel_lines(op: str, mod: str, half: int, tag: int) -> list[str]: - """Raw GFX10 kernel sweeping 16,384 consecutive f16 pairs (32,768 values) using unique loop label.""" - if half not in (0, 1): - raise ValueError(f"half must be 0 or 1, got {half}") - lbl = f".L_pknorm_sweep_{tag}" - base_val = half * 32768 - inst = f"{op} v8, v1, v2" + (f" {mod}" if mod else "") - lines = [ - "s_mov_b32 s4, 0", - f"{lbl}:", - "v_lshlrev_b32 v3, 6, s4", - "v_add_nc_u32 v3, v3, v0", - "v_lshlrev_b32 v1, 1, v3", - ] - if base_val: - lines.append(f"v_add_nc_u32 v1, {base_val:#x}, v1") - lines += [ - "v_add_nc_u32 v2, 1, v1", - "v_or_b32 v1, 0x3c000000, v1", - "v_or_b32 v2, 0xbc000000, v2", - "v_mov_b32_e32 v8, 0xdeadbeef", - inst, - "v_lshlrev_b32 v4, 2, v3", - "global_store_dword v4, v8, s[2:3]", - "s_add_u32 s4, s4, 1", - "s_cmp_lt_u32 s4, 256", - f"s_cbranch_scc1 {lbl}", - "s_waitcnt vmcnt(0)", - "s_endpgm", - ] - return lines - - -def _format_src(reg_or_asm: str, is_abs: bool, is_neg: bool) -> str: - s = f"|{reg_or_asm}|" if is_abs else reg_or_asm - return f"-{s}" if is_neg else s - - -def case_instruction(op: str, c: Case, clamp: bool) -> list[str]: - """Emit raw GFX10 setup + VOP3 instruction lines storing result in v8.""" - lines: list[str] = [] - if c.raw_omod is not None: - lines.append(f"v_mov_b32_e32 v1, {c.src0:#010x}") - lines.append(f"v_mov_b32_e32 v2, {c.src1:#010x}") - lines.append(f"v_mov_b32_e32 v8, {c.init_dst:#010x}") - dw0 = 0xD7000008 | (_OPCODES[op] << 16) | (0x8000 if clamp else 0) - dw1 = 0x00020501 | ((c.raw_omod & 3) << 27) - lines.append(f".long {dw0:#010x}, {dw1:#010x}") - return lines - - if c.alias == "src0": - lines.append(f"v_mov_b32_e32 v8, {c.src0:#010x}") - lines.append(f"v_mov_b32_e32 v2, {c.src1:#010x}") - s0_base, s1_base = "v8", "v2" - elif c.alias == "src1": - lines.append(f"v_mov_b32_e32 v1, {c.src0:#010x}") - lines.append(f"v_mov_b32_e32 v8, {c.src1:#010x}") - s0_base, s1_base = "v1", "v8" - else: - if c.sgpr0: - lines.append(f"s_mov_b32 s4, {c.src0:#010x}") - s0_base = "s4" - elif c.src0_asm is not None: - s0_base = c.src0_asm - else: - lines.append(f"v_mov_b32_e32 v1, {c.src0:#010x}") - s0_base = "v1" - if c.src1_asm is not None: - s1_base = c.src1_asm - else: - lines.append(f"v_mov_b32_e32 v2, {c.src1:#010x}") - s1_base = "v2" - lines.append(f"v_mov_b32_e32 v8, {c.init_dst:#010x}") - - s0_op = _format_src(s0_base, c.src0_abs, c.src0_neg) - s1_op = _format_src(s1_base, c.src1_abs, c.src1_neg) - mods: list[str] = [] - if c.emit_opsel or c.sel != (0, 0) or c.dhi: - mods.append(f"op_sel:[{c.sel[0]},{c.sel[1]},{int(bool(c.dhi))}]") - if clamp: - mods.append("clamp") - suffix = (" " + " ".join(mods)) if mods else "" - lines.append(f"{op} v8, {s0_op}, {s1_op}{suffix}") - return lines - - -def cases_kernel_lines(op: str, clamp: bool) -> list[str]: - """Raw GFX10 kernel running all targeted CASES sequentially on lane 0.""" - lines: list[str] = [] - for idx, c in enumerate(CASES): - lines.extend(case_instruction(op, c, clamp)) - lines.append(f"v_mov_b32_e32 v3, {idx * 4}") - lines.append("global_store_dword v3, v8, s[2:3]") - lines.append("s_waitcnt vmcnt(0)") - lines.append("s_endpgm") - return lines - - -def build_jobs(ops: list[str], waves: list[int], *, exhaustive: bool = True): - """Build (kernels, metadata) pairs for oracle.run().""" - from hw_oracle import asm - - kernels, meta = [], [] - tag = 0 - for wave in waves: - for op in ops: - if exhaustive: - for mod, clamp, dhi in SWEEP_MODES: - for half in (0, 1): - kernels.append( - asm.Kernel( - sweep_kernel_lines(op, mod, half, tag), - wave=wave, - threads=64, - words=SWEEP_WORDS_PER_HALF, - raw=True, - ) - ) - meta.append(("sweep", wave, op, clamp, dhi, half)) - tag += 1 - for clamp in CLAMP_MODES: - kernels.append( - asm.Kernel( - cases_kernel_lines(op, clamp), - wave=wave, - threads=1, - words=len(CASES), - raw=True, - ) - ) - meta.append(("cases", wave, op, clamp, False, 0)) - return kernels, meta - - -def evaluate_results(ops: list[str], waves: list[int], meta, raw_results, *, exhaustive: bool = True) -> dict: - """Compare hardware outputs against exact Fraction reference and check wave/clamp/omod parity.""" - sweep_halves: dict[tuple[int, str, bool, bool, int], list[int]] = {} - case_words: dict[tuple[int, str, bool], list[int]] = {} - harness_errors: list[dict] = [] - - for entry, res in zip(meta, raw_results): - kind, wave, op, clamp, dhi, half = entry - want_words = SWEEP_WORDS_PER_HALF if kind == "sweep" else len(CASES) - if isinstance(res, str): - harness_errors.append({"kind": kind, "wave": wave, "op": op, "clamp": clamp, "dhi": dhi, "half": half, "error": res}) - continue - if len(res) != want_words: - harness_errors.append({ - "kind": kind, - "wave": wave, - "op": op, - "clamp": clamp, - "dhi": dhi, - "half": half, - "error": f"expected {want_words} words, got {len(res)}", - }) - continue - words = [w & 0xFFFFFFFF for w in res] - if kind == "sweep": - sweep_halves[(wave, op, clamp, dhi, half)] = words - else: - case_words[(wave, op, clamp)] = words - - if harness_errors: - return { - "exhaustive": exhaustive, - "sweep_words": 0, - "sweep_halves": 0, - "case_words": 0, - "total_words": 0, - "mismatches": 0, - "wave_diffs": 0, - "clamp_diffs": 0, - "raw_omod_diffs": 0, - "harness_errors": harness_errors, - "first_mismatches": [], - "first_wave_diffs": [], - "first_clamp_diffs": [], - "first_raw_omod_diffs": [], - } - - mismatches = 0 - first_mismatches: list[dict] = [] - sweep_by_key: dict[tuple[int, str, bool, bool], list[int]] = {} - sweep_word_count = 0 - - if exhaustive: - for wave in waves: - for op in ops: - tab = _REF_TABLES[op == "v_cvt_pknorm_i16_f16"] - for _, clamp, dhi in SWEEP_MODES: - words = sweep_halves[(wave, op, clamp, dhi, 0)] + sweep_halves[(wave, op, clamp, dhi, 1)] - sweep_by_key[(wave, op, clamp, dhi)] = words - sweep_word_count += len(words) - for idx, got in enumerate(words): - lo = tab[2 * idx] - hi = tab[2 * idx + 1] - want = ((lo << 16) if dhi else (lo | (hi << 16))) & 0xFFFFFFFF - if got != want: - mismatches += 1 - if len(first_mismatches) < 16: - first_mismatches.append({ - "kind": "sweep", - "wave": wave, - "op": op, - "clamp": clamp, - "dhi": dhi, - "case": f"f16({2 * idx:#06x},{2 * idx + 1:#06x})", - "got": f"0x{got:08x}", - "want": f"0x{want:08x}", - }) - - case_word_count = 0 - for wave in waves: - for op in ops: - got_list = case_words[(wave, op, False)] + case_words[(wave, op, True)] - case_word_count += len(got_list) - for clamp in CLAMP_MODES: - for c, got in zip(CASES, case_words[(wave, op, clamp)]): - want = expected_pknorm_f16( - op, - c.src0, - c.src1, - sel=c.sel, - dhi=bool(c.dhi), - clamp=clamp, - src0_abs=c.src0_abs, - src0_neg=c.src0_neg, - src1_abs=c.src1_abs, - src1_neg=c.src1_neg, - ) - if got != want: - mismatches += 1 - if len(first_mismatches) < 16: - first_mismatches.append({ - "kind": "case", - "wave": wave, - "op": op, - "clamp": clamp, - "dhi": bool(c.dhi), - "case": c.name, - "got": f"0x{got:08x}", - "want": f"0x{want:08x}", - }) - - wave_diffs = 0 - first_wave_diffs: list[dict] = [] - if len(waves) > 1: - w0 = waves[0] - for w in waves[1:]: - for op in ops: - if exhaustive: - for _, clamp, dhi in SWEEP_MODES: - for idx, (a_w, b_w) in enumerate( - zip(sweep_by_key[(w0, op, clamp, dhi)], sweep_by_key[(w, op, clamp, dhi)]) - ): - if a_w != b_w: - wave_diffs += 1 - if len(first_wave_diffs) < 16: - first_wave_diffs.append({ - "kind": "sweep", - "op": op, - "clamp": clamp, - "dhi": dhi, - "case": f"f16({2 * idx:#06x},{2 * idx + 1:#06x})", - f"w{w0}": f"0x{a_w:08x}", - f"w{w}": f"0x{b_w:08x}", - }) - for clamp in CLAMP_MODES: - for c, a_w, b_w in zip(CASES, case_words[(w0, op, clamp)], case_words[(w, op, clamp)]): - if a_w != b_w: - wave_diffs += 1 - if len(first_wave_diffs) < 16: - first_wave_diffs.append({ - "kind": "case", - "op": op, - "clamp": clamp, - "dhi": bool(c.dhi), - "case": c.name, - f"w{w0}": f"0x{a_w:08x}", - f"w{w}": f"0x{b_w:08x}", - }) - - clamp_diffs = 0 - first_clamp_diffs: list[dict] = [] - for wave in waves: - for op in ops: - if exhaustive: - for dhi in (False, True): - for idx, (pw, cw) in enumerate( - zip(sweep_by_key[(wave, op, False, dhi)], sweep_by_key[(wave, op, True, dhi)]) - ): - if pw != cw: - clamp_diffs += 1 - if len(first_clamp_diffs) < 16: - first_clamp_diffs.append({ - "kind": "sweep", - "wave": wave, - "op": op, - "dhi": dhi, - "case": f"f16({2 * idx:#06x},{2 * idx + 1:#06x})", - "plain": f"0x{pw:08x}", - "clamp": f"0x{cw:08x}", - }) - for c, pw, cw in zip(CASES, case_words[(wave, op, False)], case_words[(wave, op, True)]): - if pw != cw: - clamp_diffs += 1 - if len(first_clamp_diffs) < 16: - first_clamp_diffs.append({ - "kind": "case", - "wave": wave, - "op": op, - "dhi": bool(c.dhi), - "case": c.name, - "plain": f"0x{pw:08x}", - "clamp": f"0x{cw:08x}", - }) - - raw_omod_diffs = 0 - first_raw_omod_diffs: list[dict] = [] - raw_indices = [idx for idx, c in enumerate(CASES) if c.raw_omod is not None] - if raw_indices: - base_idx = next(idx for idx in raw_indices if CASES[idx].raw_omod == 0) - for wave in waves: - for op in ops: - for clamp in CLAMP_MODES: - words = case_words[(wave, op, clamp)] - base_w = words[base_idx] - for idx in raw_indices: - if idx == base_idx: - continue - w = words[idx] - if w != base_w: - raw_omod_diffs += 1 - if len(first_raw_omod_diffs) < 16: - first_raw_omod_diffs.append({ - "wave": wave, - "op": op, - "clamp": clamp, - "case": CASES[idx].name, - "omod0": f"0x{base_w:08x}", - "got": f"0x{w:08x}", - }) - - return { - "exhaustive": exhaustive, - "sweep_words": sweep_word_count, - "sweep_halves": sweep_word_count * 2, - "case_words": case_word_count, - "total_words": sweep_word_count + case_word_count, - "mismatches": mismatches, - "wave_diffs": wave_diffs, - "clamp_diffs": clamp_diffs, - "raw_omod_diffs": raw_omod_diffs, - "harness_errors": [], - "first_mismatches": first_mismatches, - "first_wave_diffs": first_wave_diffs, - "first_clamp_diffs": first_clamp_diffs, - "first_raw_omod_diffs": first_raw_omod_diffs, - } - - -def write_report(path: str, doc: dict) -> bool: - """Write JSON report with LF line endings, creating parent folders.""" - try: - os.makedirs(os.path.dirname(os.path.abspath(path)), exist_ok=True) - with open(path, "w", encoding="utf-8", newline="\n") as f: - json.dump(doc, f, indent=1) - f.write("\n") - except OSError as e: - print(f"ERROR: cannot write {path}: {e}", file=sys.stderr) - return False - return True - - -def self_test() -> int: - """Verify the reference model, kernel assembly, and synthetic evaluator without GPU or clang.""" - # Exact single-rounding double-rounding traps (0x3801 = 0.5 + 2^-11) - assert ref_norm16_f16(0x3801, True) == 16399 - assert ref_norm16_f16(0xB801, True) == (-16399) & 0xFFFF - assert ref_norm16_f16(0x3801, False) == 32799 - assert ref_norm16_f16(0x37FF, True) == 16376 - assert ref_norm16_f16(0x37FF, False) == 32752 - # NaNs, +-inf, +-0, subnormals - for nan in (0x7E00, 0xFE00, 0x7C01, 0xFC01): - assert ref_norm16_f16(nan, True) == 0 - assert ref_norm16_f16(nan, False) == 0 - assert ref_norm16_f16(0x7C00, True) == 32767 - assert ref_norm16_f16(0xFC00, True) == (-32767) & 0xFFFF - assert ref_norm16_f16(0x7C00, False) == 65535 - assert ref_norm16_f16(0xFC00, False) == 0 - assert ref_norm16_f16(0x8000, True) == 0 - assert ref_norm16_f16(0x0001, True) == 0 - # clamp is no-op; dhi shifts left by 16 zeroing D[15:0] - assert expected_pknorm_f16("v_cvt_pknorm_i16_f16", 0x3C003400, 0xBC003801, clamp=False) == 0x400F2000 - assert expected_pknorm_f16("v_cvt_pknorm_i16_f16", 0x3C003400, 0xBC003801, clamp=True) == 0x400F2000 - assert expected_pknorm_f16("v_cvt_pknorm_i16_f16", 0x3C003400, 0xBC003801, dhi=True) == 0x20000000 - assert expected_pknorm_f16("v_cvt_pknorm_i16_f16", 0x3C003400, 0xBC003801, sel=(1, 0), dhi=True, clamp=True) == 0x7FFF0000 - assert expected_pknorm_f16("v_cvt_pknorm_u16_f16", 0x3C003400, 0xBC003801, sel=(1, 1), dhi=True) == 0xFFFF0000 - # Kernel assembly sanity - sk = sweep_kernel_lines("v_cvt_pknorm_i16_f16", "op_sel:[0,0,1] clamp", 1, 7) - assert sk[-2:] == ["s_waitcnt vmcnt(0)", "s_endpgm"] - assert "v_cvt_pknorm_i16_f16 v8, v1, v2 op_sel:[0,0,1] clamp" in sk - assert ".L_pknorm_sweep_7:" in sk - ck = cases_kernel_lines("v_cvt_pknorm_u16_f16", True) - assert "v_cvt_pknorm_u16_f16 v8, v1, v2 op_sel:[1,0,1] clamp" in ck - assert "v_cvt_pknorm_u16_f16 v8, 0.5, -0.5 clamp" in ck - assert ".long 0xd7138008, 0x18020501" in ck - # Synthetic evaluator pass check - meta = [ - ("cases", 32, "v_cvt_pknorm_i16_f16", False, False, 0), - ("cases", 32, "v_cvt_pknorm_i16_f16", True, False, 0), - ] - fake_words = [ - expected_pknorm_f16( - "v_cvt_pknorm_i16_f16", c.src0, c.src1, - sel=c.sel, dhi=bool(c.dhi), clamp=False, - src0_abs=c.src0_abs, src0_neg=c.src0_neg, src1_abs=c.src1_abs, src1_neg=c.src1_neg, - ) - for c in CASES - ] - ev = evaluate_results(["v_cvt_pknorm_i16_f16"], [32], meta, [fake_words, fake_words], exhaustive=False) - assert ev["mismatches"] == 0 and ev["clamp_diffs"] == 0 and ev["raw_omod_diffs"] == 0 - print(f"self-test ok ({len(CASES)} cases, 65,536 f16 ref entries)") - return 0 - - -def main(argv=None) -> int: - ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) - ap.add_argument("--ops", default=",".join(OPS)) - ap.add_argument("--waves", default="32,64") - ap.add_argument("--no-exhaustive", action="store_true", help="run targeted CASES only without 65,536-input sweep") - ap.add_argument("--json", help="write measurement summary JSON here") - ap.add_argument("--hw-arch") - ap.add_argument("--self-test", action="store_true") - a = ap.parse_args(argv) - if a.self_test: - return self_test() - - ops = [o.strip() for o in a.ops.split(",") if o.strip()] - wave_tokens = [w.strip() for w in a.waves.split(",") if w.strip()] - bad_ops = [o for o in ops if o not in OPS] - bad_waves = [w for w in wave_tokens if w not in ("32", "64")] - if bad_ops or bad_waves or not ops or not wave_tokens: - ap.error("unknown or empty: " + ", ".join(bad_ops + bad_waves or ["--ops/--waves"])) - waves = [int(w) for w in wave_tokens] - if a.json and os.path.isdir(a.json): - ap.error(f"--json {a.json} is a folder, not a file") - exhaustive = not a.no_exhaustive - - from hw_oracle import asm, runner - - try: - oracle = runner.open_oracle(arch=a.hw_arch) - except runner.Unavailable as e: - print(f"hardware oracle unavailable: {e}") - return 77 - - try: - if asm.family(oracle.arch) != "gfx10": - print(f"hardware oracle unavailable: {oracle.arch} is not GFX10") - return 77 - print(f"hardware oracle: {oracle.device} ({oracle.arch})") - kernels, meta = build_jobs(ops, waves, exhaustive=exhaustive) - raw_results = oracle.run(kernels) - summary = evaluate_results(ops, waves, meta, raw_results, exhaustive=exhaustive) - except RuntimeError as e: - print(f"harness error: {e}") - return 2 - finally: - oracle.close() - - report = { - "device": str(oracle.device), - "arch": oracle.arch, - "waves": waves, - "ops": ops, - "sweep_modes": [m[0] or "plain" for m in SWEEP_MODES] if exhaustive else [], - "cases": len(CASES), - **summary, - } - if a.json and not write_report(a.json, report): - return 2 - - if summary["harness_errors"]: - for err in summary["harness_errors"][:5]: - print(f"harness error: {err['kind']} wave{err['wave']} {err['op']} clamp={err['clamp']}: {err['error']}") - return 2 - - print( - f"sweep_halves={summary['sweep_halves']} ({summary['sweep_words']} words), " - f"case_words={summary['case_words']} across {len(waves)} wave(s) x {len(ops)} op(s): " - f"mismatches={summary['mismatches']}, wave_diffs={summary['wave_diffs']}, " - f"clamp_diffs={summary['clamp_diffs']}, raw_omod_diffs={summary['raw_omod_diffs']}" - ) - for m in summary["first_mismatches"]: - print(f" MISMATCH {m['kind']} wave{m['wave']} {m['op']} clamp={m['clamp']} {m['case']}: got {m['got']}, want {m['want']}") - for d in summary["first_wave_diffs"]: - print(f" WAVE DIFF {d['kind']} {d['op']} clamp={d['clamp']} {d['case']}: {d}") - for d in summary["first_clamp_diffs"]: - print(f" CLAMP DIFF {d['kind']} wave{d['wave']} {d['op']} {d['case']}: plain={d['plain']} clamp={d['clamp']}") - for d in summary["first_raw_omod_diffs"]: - print(f" RAW OMOD DIFF wave{d['wave']} {d['op']} clamp={d['clamp']} {d['case']}: omod0={d['omod0']} got={d['got']}") - - if ( - summary["mismatches"] - or summary["wave_diffs"] - or summary["clamp_diffs"] - or summary["raw_omod_diffs"] - ): - return 1 - return 0 - - -if __name__ == "__main__": - try: - sys.stdout.reconfigure(errors="replace") - except (AttributeError, ValueError, OSError): - pass - sys.exit(main()) diff --git a/tools/d16_format_probe.py b/tools/d16_format_probe.py deleted file mode 100644 index d19754e03..000000000 --- a/tools/d16_format_probe.py +++ /dev/null @@ -1,360 +0,0 @@ -r"""How an RDNA2 GPU rounds UNORM/SNORM buffer loads to f16 with d16 (BUILD-161). Standard library only. - -docs/design.md ("d16 and f16 format narrowing") narrows every d16 result with integer round to nearest even, but -for typed buffer loads that rounding was inferred (#489, #711), not measured. This sweep measures it: every value of -each format below goes through buffer_load_format_d16_x and tbuffer_load_format_d16_x natively on the GPU (through -tools/hw_oracle/), in wave32 and wave64. Every result is compared with several candidate rules computed from the -exact quotient (Fraction arithmetic): - - f32_rte x / (2^n - 1) (SNORM: max(s / (2^(n-1) - 1), -1)) rounded to f32 (nearest even), then to f16 - nearest even: the translator's rule before BUILD-161 (the exact binary32 decode, then Gen.f16_bits) - f32_rtz rounded to f32, then to f16 toward zero (v_cvt_pkrtz_f16_f32 of the f32 value; PackHalf2x16 on AMD - drivers, the #489 bug) - rte the exact quotient rounded once to f16, nearest even (no f32 step): what an RX 6700 does, and the - translator's rule since BUILD-161 (Gen.d16_norm_f16) - rtz the exact quotient rounded once to f16, toward zero - mul_rte the f32 product v * f32(1 / (2^n - 1)) (a reciprocal multiply, not a division), then f16 nearest even - -and each rule again with f16 denormal results flushed to zero (UNORM16 and SNORM16 have quotients under 2^-14). -Only the 16-bit formats tell the f32 step apart: rte and f32_rte differ on UNORM16 0xffaf and 0xffef and on SNORM16 -0x7ff7 and 0x8009, and a flush shows on the smallest UNORM16 / SNORM16 values. On UNORM8, SNORM8 and UNORM10 every -rule but the rtz ones gives the same bits. -buffer_load_format_x (an f32 result, no d16) runs on the same values against the f32 rules, so the two stages can be -told apart. Controls that must hold for the sweep to count: every staged input word reads back as written, a -16_FLOAT d16 load returns its own bits, and d16_x leaves the high half of its VGPR as it was. - -The kernels write their own inputs: thread t stores the format's bits for value base + t at dword t of the output -buffer, waits for the store, builds a GFX10 buffer descriptor (V#) over that buffer and loads its element with glc dlc -(past the L0 and GL1 caches), then stores the loaded VGPR at dword 1024 + t. GFX10 only (RDNA1 and RDNA2: the -V# layout, RESOURCE_LEVEL = 1), which is what BUILD-161 asks for; another architecture exits 77. - -Usage: - python -I tools/d16_format_probe.py [--formats unorm8,snorm16] [--waves 32,64] [--json out.json] - python -I tools/d16_format_probe.py --self-test # the models against known counts, no GPU - -Exit 0 when the sweep ran (which rule the hardware follows is a finding, not a failure), 1 when wave32 and wave64 -or MUBUF and MTBUF disagree, 2 on a harness error (a control failed, a kernel without its words), 77 when the -hardware oracle is unavailable or the GPU is not GFX10. Nothing here reads game files. -""" -import argparse -import json -import os -import struct -import sys -from fractions import Fraction - -HERE = os.path.dirname(os.path.abspath(__file__)) -sys.dont_write_bytecode = True -if HERE not in sys.path: - sys.path.insert(0, HERE) - -# name: (GFX10 unified buffer format code, kind, bits of the x channel). The codes are the translator's FORMATS -# table (tools/rdna2spirv.py); 10_10_10_2 (50) holds x in its low 10 bits. -FORMATS = { - "unorm8": (1, "unorm", 8), - "snorm8": (2, "snorm", 8), - "unorm16": (7, "unorm", 16), - "snorm16": (8, "snorm", 16), - "unorm10": (50, "unorm", 10), - "float16": (13, "f16", 16), # control: d16 of an f16 element is its own bits -} -INSTS = ("buffer_d16", "tbuffer_d16", "buffer_f32") -THREADS = 1024 -WORDS = 2 * THREADS -HI_SEED = 0xBEEF0000 # the d16_x destination starts as this | 0x1234; the high half must stay -LO_SEED = 0x1234 -RULES16 = ("f32_rte", "f32_rtz", "rte", "rtz", "mul_rte") -RULES32 = ("f32_rte", "f32_rtz", "mul_f32") - - -# ---- exact arithmetic ---- - -def round_frac(x, prec, emin, rtz=False): - """x rounded to a binary float with prec significand bits (implicit bit included) and minimum normal exponent - emin, denormals kept; nearest even, or toward zero. No overflow: every value here is in [-1, 1]. - Exact, in integers: x = p/q, 2^e <= p/q < 2^(e+1), ulp = 2^k; the significand is p/q / 2^k rounded. Building - Fractions for 2^e and the quotient instead gave the same bits about 4x slower (minutes for a 16-bit sweep).""" - p, q = x.numerator, x.denominator - if p == 0: - return Fraction(0) - sign, p = (-1, -p) if p < 0 else (1, p) - e = p.bit_length() - q.bit_length() # floor(log2(p/q)) is e or e - 1 - if (p << -e if e < 0 else p) < (q << e if e > 0 else q): - e -= 1 - k = max(e, emin) - prec + 1 - num, den = (p, q << k) if k >= 0 else (p << -k, q) - n, r = divmod(num, den) - if not rtz and (2 * r > den or (2 * r == den and n & 1)): # half to even - n += 1 - return Fraction(sign * n << k) if k >= 0 else Fraction(sign * n, 1 << -k) - - -def f16_bits(v): - return struct.unpack("> (n - 1) else v - return max(Fraction(s, (1 << (n - 1)) - 1), Fraction(-1)) - - -def is_denorm16(h): - return (h & 0x7C00) == 0 and (h & 0x3FF) != 0 - - -def models16(kind, n, v): - """{rule: f16 bits} for one input, plus each rule with a denormal result flushed (rule + '_flush').""" - x = quotient(kind, n, v) - rcp = to_f32(Fraction(1, (1 << n) - 1) if kind == "unorm" else Fraction(1, (1 << (n - 1)) - 1)) - s = (v - (1 << n) if v >> (n - 1) else v) if kind == "snorm" else v - prod = max(to_f32(s * rcp), Fraction(-1)) - out = {"rte": f16_bits(to_f16(x)), "rtz": f16_bits(to_f16(x, True)), "f32_rte": f16_bits(to_f16(to_f32(x))), - "f32_rtz": f16_bits(to_f16(to_f32(x), True)), "mul_rte": f16_bits(to_f16(prod))} - for r in RULES16: - out[r + "_flush"] = (out[r] & 0x8000) if is_denorm16(out[r]) else out[r] - return out - - -def models32(kind, n, v): - x = quotient(kind, n, v) - rcp = to_f32(Fraction(1, (1 << n) - 1) if kind == "unorm" else Fraction(1, (1 << (n - 1)) - 1)) - s = (v - (1 << n) if v >> (n - 1) else v) if kind == "snorm" else v - return {"f32_rte": f32_bits(to_f32(x)), "f32_rtz": f32_bits(to_f32(x, True)), - "mul_f32": f32_bits(max(to_f32(s * rcp), Fraction(-1)))} - - -# ---- kernels ---- - -def descriptor_word3(code): - """GFX10 V# dword 3: DST_SEL x/y/z/w = X/Y/Z/W (4, 5, 6, 7), FORMAT [18:12], RESOURCE_LEVEL [24] = 1, - OOB_SELECT [29:28] = 3 (raw: in bounds while offset < NUM_RECORDS), TYPE [31:30] = 0 (buffer).""" - return 4 | 5 << 3 | 6 << 6 | 7 << 9 | code << 12 | 1 << 24 | 3 << 28 - - -def kernel_lines(inst, fmt, base): - """Thread t: stage format bits (base + t) & mask at dword t, load the element, store the VGPR at dword 1024 + t.""" - code, kind, n = FORMATS[fmt] - mask = (1 << n) - 1 - load = {"buffer_d16": "buffer_load_format_d16_x v3, v2, s[8:11], 0 offen glc dlc", - "tbuffer_d16": f"tbuffer_load_format_d16_x v3, v2, s[8:11], 0 format:{code} offen glc dlc", - "buffer_f32": "buffer_load_format_x v3, v2, s[8:11], 0 offen glc dlc"}[inst] - return [ - f"v_add_nc_u32 v1, 0x{base:x}, v0", - f"v_and_b32 v1, 0x{mask:x}, v1", - "v_lshlrev_b32 v2, 2, v0", - "global_store_b32 v2, v1, s[2:3]", - "s_waitcnt_vscnt null, 0x0", - "s_mov_b32 s8, s2", - "s_and_b32 s9, s3, 0xffff", # BASE_ADDRESS[47:32]; STRIDE 0, no swizzle - f"s_mov_b32 s10, 0x{4 * THREADS:x}", # NUM_RECORDS: the staged inputs, in bytes - f"s_mov_b32 s11, 0x{descriptor_word3(code):x}", - f"v_mov_b32 v3, 0x{HI_SEED | LO_SEED:x}", - load, - "s_waitcnt vmcnt(0)", - f"v_add_nc_u32 v4, 0x{4 * THREADS:x}, v2", - "global_store_b32 v4, v3, s[2:3]", - "s_endpgm", - ] - - -def jobs(fmt): - """(inst, base) for every kernel a format needs: one per 1024 values.""" - n = FORMATS[fmt][2] - insts = ("buffer_d16", "tbuffer_d16") if FORMATS[fmt][1] == "f16" else INSTS - return [(inst, base) for inst in insts for base in range(0, 1 << n, THREADS)] - - -def sweep(oracle, fmt, wave): - """{inst: [loaded VGPR word per value]} for every value of the format, or raise RuntimeError.""" - from hw_oracle import asm - n = FORMATS[fmt][2] - todo = jobs(fmt) - kernels = [asm.Kernel(kernel_lines(inst, fmt, base), wave, THREADS, WORDS, raw=True, vgprs=8, sgprs=16) - for inst, base in todo] - got = oracle.run(kernels, words=WORDS) - # Every kernel must answer: zip() over a shorter list would drop the values of the missing ones and still - # succeed. hw_oracle's Oracle.run() returns one entry per kernel; this keeps that contract checked (BUILD-733). - if len(got) != len(todo): - raise RuntimeError(f"{fmt} wave{wave}: the oracle returned {len(got)} results for {len(todo)} kernels") - out = {} - for (inst, base), words in zip(todo, got): - if words is None or isinstance(words, str) or len(words) != WORDS: - why = "no result" if words is None else words if isinstance(words, str) else f"{len(words)} words" - raise RuntimeError(f"{fmt} {inst} wave{wave} base {base}: {why}") - count = min(THREADS, (1 << n) - base) - staged = words[:count] - want = [(base + t) & ((1 << n) - 1) for t in range(count)] - if staged != want: - bad = next(t for t in range(count) if staged[t] != want[t]) - raise RuntimeError(f"{fmt} {inst} wave{wave}: staged input {want[bad]:#x} read back as {staged[bad]:#x}") - out.setdefault(inst, []).extend(words[THREADS:THREADS + count]) - return out - - -# ---- comparison ---- - -def classify(fmt, hw): - """Counts of inputs each rule predicts exactly, the inputs where the translator's rule (rte for d16, f32_rte for f32) is wrong, and the - control failures. hw: {inst: [VGPR word per value]}.""" - _, kind, n = FORMATS[fmt] - res = {"inputs": 1 << n, "insts": {}, "control": []} - for inst, words in hw.items(): - d16 = inst.endswith("d16") - if d16: - hi_bad = [v for v, w in enumerate(words) if w >> 16 != HI_SEED >> 16] - if hi_bad: - res["control"].append(f"{inst}: d16_x changed the high half for {len(hi_bad)} values " - f"(first {hi_bad[0]:#x}: {words[hi_bad[0]]:#010x})") - if kind == "f16": - wrong = [v for v, w in enumerate(words) if (w & 0xFFFF) != v and not ( - (v & 0x7C00) == 0x7C00 and v & 0x3FF and (w & 0x7C00) == 0x7C00 and w & 0x3FF)] - if wrong: - res["control"].append(f"{inst}: 16_FLOAT came back changed for {len(wrong)} values " - f"(first {wrong[0]:#06x} -> {words[wrong[0]] & 0xFFFF:#06x})") - res["insts"][inst] = {"own_bits": (1 << n) - len(wrong)} - continue - rules = (tuple(RULES16) + tuple(r + "_flush" for r in RULES16)) if d16 else RULES32 - match = dict.fromkeys(rules, 0) - off = [] - for v, w in enumerate(words): - got = w & 0xFFFF if d16 else w - m = models16(kind, n, v) if d16 else models32(kind, n, v) - for r in rules: - match[r] += got == m[r] - rule = "rte" if d16 else "f32_rte" # the translator's rule (Gen.d16_norm_f16, norm_bits) - if got != m[rule]: - off.append((v, got, m[rule], m)) - res["insts"][inst] = {"match": match, "off_rule": len(off), - "first_off": [{"value": f"{v:#x}", "hw": f"{g:#x}", "rule": f"{r:#x}", - "fits": [k for k in rules if m[k] == g]} for v, g, r, m in off[:8]]} - return res - - -def rte_rtz_disagreements(kind, n): - """How many inputs the translator's rule and the #489 bug (f32 then RTZ) narrow differently (docs/design.md: - 123 of 256 UNORM8 and 110 of 256 SNORM8 loaded 1 ulp low).""" - return sum(models16(kind, n, v)["f32_rte"] != models16(kind, n, v)["f32_rtz"] for v in range(1 << n)) - - -def self_test(): - assert round_frac(Fraction(1, 3), 11, -14) == Fraction(1365, 4096) # 0x3555 - assert f16_bits(to_f16(Fraction(1, 255))) == 0x1C04 # 2^-8 * 1.00390625 - assert f16_bits(to_f16(Fraction(9, 255))) == 0x2885 and f16_bits(to_f16(Fraction(9, 255), True)) == 0x2884 - assert f16_bits(to_f16(Fraction(1, 65535))) == 0x0100 and is_denorm16(0x0100) # under 2^-14 - assert f16_bits(to_f16(Fraction(1, 2) + Fraction(1, 4096))) == 0x3800 # a tie: to even - assert quotient("snorm", 8, 0x80) == -1 and quotient("snorm", 8, 0x81) == -1 and quotient("snorm", 8, 0x7F) == 1 - assert models16("unorm", 8, 255)["rte"] == 0x3C00 and models16("snorm", 16, 0x8000)["rte"] == 0xBC00 - assert models32("unorm", 8, 1)["f32_rte"] == 0x3B808081 # 1/255 in f32 - assert models16("unorm", 16, 1)["f32_rte_flush"] == 0 - assert models16("unorm", 16, 0xFFEF)["rte"] == 0x3BFF and models16("unorm", 16, 0xFFEF)["f32_rte"] == 0x3C00 - assert models16("snorm", 16, 0x8009)["rte"] == 0xBBFF and models16("snorm", 16, 0x8009)["f32_rte"] == 0xBC00 - assert rte_rtz_disagreements("unorm", 8) == 123 - assert rte_rtz_disagreements("snorm", 8) == 110 - w3 = descriptor_word3(7) - assert w3 & 0xFFF == 0xFAC and (w3 >> 12) & 0x7F == 7 and (w3 >> 24) & 1 and (w3 >> 28) & 3 == 3 - lines = kernel_lines("tbuffer_d16", "unorm16", 0x400) - assert lines[0] == "v_add_nc_u32 v1, 0x400, v0" and "format:7 offen glc dlc" in lines[10] - assert len(jobs("unorm16")) == 3 * 64 and len(jobs("unorm8")) == 3 and len(jobs("float16")) == 2 * 64 - print("self-test ok") - return 0 - - -def write_report(path, doc): - """Write the JSON report, creating its folder; one ERROR line instead of a traceback on failure.""" - try: - os.makedirs(os.path.dirname(os.path.abspath(path)), exist_ok=True) - with open(path, "w", encoding="utf-8", newline="\n") as f: - json.dump(doc, f, indent=1) - except OSError as e: - print(f"ERROR: cannot write {path}: {e}", file=sys.stderr) - return False - return True - - -def main(argv=None): - ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) - ap.add_argument("--formats", default=",".join(FORMATS)) - ap.add_argument("--waves", default="32,64") - ap.add_argument("--json", help="write the counts and the first differences here") - ap.add_argument("--hw-arch") - ap.add_argument("--self-test", action="store_true") - a = ap.parse_args(argv) - if a.self_test: - return self_test() - fmts = [f for f in a.formats.split(",") if f] - waves = [int(w) for w in a.waves.split(",") if w.strip().isdigit()] - bad = [f for f in fmts if f not in FORMATS] + [w for w in a.waves.split(",") if w and w not in ("32", "64")] - if bad or not fmts or not waves: - ap.error("unknown or empty: " + ", ".join(bad or ["--formats/--waves"])) - if a.json and os.path.isdir(a.json): - ap.error(f"--json {a.json} is a folder, not a file") - from hw_oracle import asm, runner - try: - oracle = runner.open_oracle(arch=a.hw_arch) - except runner.Unavailable as e: - print(f"hardware oracle unavailable: {e}") - return 77 - try: - if asm.family(oracle.arch) != "gfx10": - print(f"hardware oracle unavailable: {oracle.arch} is not GFX10; the descriptor here is GFX10's (RDNA2)") - return 77 - print(f"hardware oracle: {oracle.device}") - report = {"device": str(oracle.device), "arch": oracle.arch, "formats": {}} - rc = 0 - for fmt in fmts: - hw = {w: sweep(oracle, fmt, w) for w in waves} - first = hw[waves[0]] - entry = classify(fmt, first) - entry["waves_differ"] = {inst: sum(a_ != b_ for a_, b_ in zip(first[inst], hw[w][inst])) - for w in waves[1:] for inst in first} - if "tbuffer_d16" in first: - entry["mubuf_mtbuf_differ"] = sum((x ^ y) & 0xFFFF != 0 - for x, y in zip(first["buffer_d16"], first["tbuffer_d16"])) - report["formats"][fmt] = entry - if entry["control"]: - for c in entry["control"]: - print(f"harness error: {fmt} {c}") - rc = 2 - if any(entry["waves_differ"].values()) or entry.get("mubuf_mtbuf_differ"): - rc = max(rc, 1) if rc != 2 else 2 - print(f"{fmt} ({entry['inputs']} values): wave32/64 differ {entry['waves_differ'] or 'n/a'}; " - f"MUBUF/MTBUF d16 differ {entry.get('mubuf_mtbuf_differ', 'n/a')}") - for inst, s in entry["insts"].items(): - if "own_bits" in s: - print(f" {inst}: own bits {s['own_bits']}/{entry['inputs']}") - continue - print(f" {inst}: " + ", ".join(f"{r} {k}" for r, k in s["match"].items()) + - f"; off the rule {s['off_rule']}") - for o in s["first_off"][:3]: - print(f" value {o['value']}: hw {o['hw']}, rule {o['rule']}, fits {','.join(o['fits']) or '-'}") - except RuntimeError as e: - print(f"harness error: {e}") - return 2 - finally: - oracle.close() - if a.json and not write_report(a.json, report): - return 2 - return rc - - -if __name__ == "__main__": - try: - sys.stdout.reconfigure(errors="replace") - except (AttributeError, ValueError, OSError): - pass - sys.exit(main()) diff --git a/tools/d16_image_probe.py b/tools/d16_image_probe.py deleted file mode 100644 index 92c0d3eb2..000000000 --- a/tools/d16_image_probe.py +++ /dev/null @@ -1,422 +0,0 @@ -r"""How an RDNA2 GPU rounds d16 image results to f16 (point loads, point samples and bilinear samples). Standard library. - -docs/design.md ("d16 and f16 format narrowing") narrows the f16 of every d16 image result from its f32 with integer -round to nearest even. For images that is inferred, not measured. BUILD-161 (tools/d16_format_probe.py) found that a -typed d16 buffer load rounds the exact UNORM/SNORM quotient once, straight to f16, and that the f32-first rule is -1 ulp high on four 16-bit values. This sweep asks the same of the image path. Every value of each format below sits -in a texture, and every texel is read in one kernel lane with: - - image_load f32 and d16, at the texel (unnormalized integer coordinates) - image_sample_lz f32 and d16, point filter, at the texel centre (unnormalized coordinates) - image_sample_lz f32 and d16, bilinear filter, `--frac` texels to the right of the centre, so the result mixes the - texel with its right neighbour (the last texel of a row clamps to itself) - -natively on the GPU through tools/hw_oracle, in wave32 and wave64. The loads and point samples are compared with -the candidate rules of d16_format_probe (rte: the exact quotient rounded once; f32_rte: the translator's f32 first, -then f16; their toward-zero and denormal-flushing variants). A bilinear d16 result has no exact quotient, so it is -compared with the hardware's own f32 result for the same sample: rounded to nearest even (what the translator does -with the f32 a Vulkan driver returns), toward zero, or neither. - -The float32 set holds f32 bit patterns that sit exactly on f16 halfway points (0x3f7ff000 and 0x3f7fb000, the two -UNORM/SNORM quotients that land there, their negatives, and other ties), plus values next to them. It answers -whether a correction for the two quotients could be applied to every float-class image or only to normalized ones: -a 32_FLOAT texel on a halfway point is a real tie. - -The texture is in the kernel's own code after s_endpgm, 256-byte aligned and linear, found with s_getpc_b64 (the -layout of tools/hw_oracle/tsharp.py, #1566). The T# is tsharp.image_words with the FORMAT field set to the format -here; the samplers are GFX10 S#s with FORCE_UNNORMALIZED, CLAMP_LAST_TEXEL on every axis and MIP_FILTER none: - - S# WORD0 CLAMP_X/Y/Z [8:0] = 2, FORCE_UNNORMALIZED [15] = 1 - S# WORD1 MIN_LOD = MAX_LOD = 0 - S# WORD2 XY_MAG_FILTER [21:20] and XY_MIN_FILTER [23:22]: 0 point, 1 bilinear; MIP_FILTER [27:26] = 0 - S# WORD3 BORDER_COLOR_TYPE 0 (never read: every coordinate is inside the image) - -(Mesa src/amd/registers gfx10.json, SQ_IMG_SAMP_WORD0..3.) GFX10 only (RDNA1/RDNA2); another architecture exits 77. - -Controls that must hold for the sweep to count: the f32 image_load of every UNORM/SNORM texel equals the correctly -rounded f32 quotient (what the RX 6700 returns for buffer loads, so a wrong T# or texture layout shows here), a point -sample equals the load, a 16_FLOAT texel comes back with its own bits, and no lane reports a misaligned texture. - -Usage: - python -I tools/d16_image_probe.py [--formats unorm8,unorm16] [--waves 32,64] [--frac 0.5] [--json out.json] - python -I tools/d16_image_probe.py --self-test - -Exit 0 when the sweep ran (which rule the hardware follows is a finding), 1 when wave32 and wave64 disagree, 2 on a -harness error (a control failed, a kernel without its words), 77 when the oracle is unavailable or the GPU is not -GFX10. Nothing here reads game files. -""" -import argparse -import json -import os -import random -import struct -import sys - -HERE = os.path.dirname(os.path.abspath(__file__)) -sys.dont_write_bytecode = True -if HERE not in sys.path: - sys.path.insert(0, HERE) - -import d16_format_probe as fp # noqa: E402 - -# name: (GFX10 FORMAT, kind, bits per texel, texture width). Width x rows = 1024 texels; rows are 256 bytes, so the -# 256-byte pitch of a linear image adds no padding. -FORMATS = { - "unorm8": (1, "unorm", 8, 256), - "snorm8": (2, "snorm", 8, 256), - "unorm16": (7, "unorm", 16, 128), - "snorm16": (8, "snorm", 16, 128), - "float16": (13, "f16", 16, 128), # control: its own bits - "float32": (22, "f32", 32, 64), # halfway points of f16, as f32 texels -} -TEXELS = 1024 -WORDS_PER_LANE = 8 -SEED = 0xBEEF1234 # the d16 destinations start as this -POISON = 0xBAADF00D - -# f32 patterns on an f16 halfway point (the low 13 mantissa bits are exactly 0x1000) and their neighbours -HALFWAY_UNORM = (0x3F7FF000, 0x3F7FB000) - - -def float32_texels(): - """1024 f32 bit patterns, in this order: the two UNORM/SNORM halfway quotients and their negatives; more f16 - halfway points, chosen so that for half of them the f16 below is the even one and for the other half the f16 - above is (the two readings of a tie are then told apart); the f32 just below and just above each of those; and - a fixed random fill in [-1, 1]. HALFWAY_COUNT counts the exact ties, which come first.""" - ties = [] - for b in HALFWAY_UNORM: - ties += [b, b | 0x80000000] - for exp in (0x3F800000, 0x3F000000, 0x3E800000, 0x3C000000, 0x38800000, 0x3F700000): - for step in range(1, 5): # mantissa 0x1000, 0x3000, 0x5000, 0x7000: even and odd below - b = exp | (2 * step - 1) << 12 - ties += [b, b | 0x80000000] - out = list(ties) - for b in ties: - out += [b - 1, b + 1] - rng = random.Random(161) - while len(out) < TEXELS: - out.append(fp.f32_bits(rng.uniform(-1.0, 1.0))) - return out[:TEXELS], len(ties) - - -def block_values(fmt, block): - """The raw texel values (ints, the format's bits) of one 1024-texel texture.""" - _, kind, n, _ = FORMATS[fmt] - if kind == "f32": - return float32_texels()[0] - return [(block * TEXELS + t) & ((1 << n) - 1) for t in range(TEXELS)] - - -def blocks(fmt): - _, kind, n, _ = FORMATS[fmt] - return 1 if kind == "f32" else max(1, (1 << n) // TEXELS) - - -def texture_bytes(fmt, values): - n = FORMATS[fmt][2] - return b"".join(v.to_bytes(n // 8, "little") for v in values) - - -def sampler_words(bilinear): - word0 = 2 | 2 << 3 | 2 << 6 | 1 << 15 - word2 = (1 << 20 | 1 << 22) if bilinear else 0 - return [word0, 0, word2, 0] - - -def t_words(arch, fmt): - """The T#: tsharp's 2D linear descriptor with this format's FORMAT ([28:20] on GFX10).""" - from hw_oracle import tsharp - code, _, n, width = FORMATS[fmt] - words = tsharp.image_words(arch, "R32_SFLOAT", width, TEXELS // width, n // 8, - (tsharp.SEL_X, tsharp.SEL_0, tsharp.SEL_0, tsharp.SEL_1)) - words[1] = (words[1] & ~(0x1FF << 20)) | code << 20 - return words - - -def _f32(x): - return f"0x{fp.f32_bits(x):08x}" - - -def kernel_lines(arch, uid, fmt, values, frac): - """A raw kernel body (asm.Kernel(..., raw=True)): lane t reads texel t six ways and stores 8 words at 32 t.""" - from hw_oracle import tsharp - _, _, n, width = FORMATS[fmt] - t = t_words(arch, fmt) - pt, bl = sampler_words(False), sampler_words(True) - img = "dmask:0x1 dim:SQ_RSRC_IMG_2D unorm" - out = ["s_getpc_b64 s[4:5]", - f".Lpc{uid}:", - f"s_add_u32 s4, s4, .Ltex{uid}-.Lpc{uid}", - "s_addc_u32 s5, s5, 0", - "s_and_b32 s6, s4, 255", - "s_lshr_b64 s[4:5], s[4:5], 8", - "s_mov_b32 s8, s4", - "s_and_b32 s9, s5, 255", - f"s_or_b32 s9, s9, 0x{t[1]:08x}"] - out += [f"s_mov_b32 s{8 + i}, 0x{t[i]:08x}" for i in range(2, 8)] - out += [f"s_mov_b32 s{16 + i}, 0x{w:08x}" for i, w in enumerate(pt)] - out += [f"s_mov_b32 s{20 + i}, 0x{w:08x}" for i, w in enumerate(bl)] - out += [f"v_and_b32 v2, {width - 1}, v0", - f"v_lshrrev_b32 v3, {width.bit_length() - 1}, v0", - "v_cvt_f32_u32 v5, v2", - "v_cvt_f32_u32 v6, v3", - "v_add_f32 v5, 0.5, v5", - "v_add_f32 v6, 0.5, v6", - f"v_add_f32 v16, {_f32(frac)}, v5", - "v_mov_b32 v17, v6"] - out += [f"v_mov_b32 v{r}, 0x{SEED:08x}" for r in (9, 11, 13)] - out += ["v_mov_b32 v14, v0", "v_mov_b32 v15, 0", - "s_cmp_lg_u32 s6, 0", - f"s_cbranch_scc1 .Lbad{uid}", - f"image_load v8, v[2:3], s[8:15] {img}", - f"image_load v9, v[2:3], s[8:15] {img} d16", - f"image_sample_lz v10, v[5:6], s[8:15], s[16:19] {img}", - f"image_sample_lz v11, v[5:6], s[8:15], s[16:19] {img} d16", - f"image_sample_lz v12, v[16:17], s[8:15], s[20:23] {img}", - f"image_sample_lz v13, v[16:17], s[8:15], s[20:23] {img} d16", - "s_waitcnt vmcnt(0)", - f"s_branch .Lst{uid}", - f".Lbad{uid}:"] - out += [f"v_mov_b32 v{8 + i}, 0x{POISON:08x}" for i in range(8)] - out += [f".Lst{uid}:", - "v_lshlrev_b32 v4, 5, v0", - "global_store_b128 v4, v[8:11], s[2:3]", - "global_store_b128 v4, v[12:15], s[2:3] offset:16", - "s_endpgm", ".p2align 8", f".Ltex{uid}:"] - return out + tsharp._longs(tsharp.lay_out(texture_bytes(fmt, values), width, TEXELS // width, n // 8)) - - -def sweep(oracle, fmt, wave, frac): - """{field: [word per texel value]} over every block of the format, or raise RuntimeError.""" - from hw_oracle import asm - todo = [(b, block_values(fmt, b)) for b in range(blocks(fmt))] - kernels = [asm.Kernel(kernel_lines(oracle.arch, f"{fmt}_{b}", fmt, vals, frac), wave, TEXELS, - TEXELS * WORDS_PER_LANE, raw=True, vgprs=24, sgprs=32) for b, vals in todo] - out = {k: [] for k in ("value", "load", "load_d16", "point", "point_d16", "bilin", "bilin_d16", "right")} - width = FORMATS[fmt][3] - got = oracle.run(kernels, words=TEXELS * WORDS_PER_LANE) - if len(got) != len(todo): # zip would drop the tail and the counts would quietly cover fewer texels - raise RuntimeError(f"{fmt} wave{wave}: the hardware runner returned {len(got)} results for {len(todo)} kernels") - for (b, vals), words in zip(todo, got): - if isinstance(words, str) or len(words) != TEXELS * WORDS_PER_LANE: - raise RuntimeError(f"{fmt} wave{wave} block {b}: " - f"{words if isinstance(words, str) else f'{len(words)} words'}") - for lane in range(TEXELS): - w = words[WORDS_PER_LANE * lane:WORDS_PER_LANE * (lane + 1)] - if POISON in w[:6]: - raise RuntimeError(f"{fmt} wave{wave} block {b}: the texture is not 256-byte aligned") - if w[6] != lane: - raise RuntimeError(f"{fmt} wave{wave} block {b}: lane {lane} stored {w[6]:#x} as its index") - x = lane % width - out["value"].append(vals[lane]) - out["right"].append(vals[lane + 1] if x + 1 < width else vals[lane]) - for k, v in zip(("load", "load_d16", "point", "point_d16", "bilin", "bilin_d16"), w): - out[k].append(v) - return out - - -def classify(fmt, hw, frac): - """Counts per field and rule, the first inputs off the translator's rule, and the control failures.""" - _, kind, n, _ = FORMATS[fmt] - res = {"inputs": len(hw["value"]), "fields": {}, "control": []} - vals = hw["value"] - - def note(msg): - res["control"].append(msg) - - if kind in ("unorm", "snorm"): - want32 = [fp.models32(kind, n, v)["f32_rte"] for v in vals] - exact = sum(g == w for g, w in zip(hw["load"], want32)) - res["f32_load_is_rounded_quotient"] = exact - far = [i for i, (g, w) in enumerate(zip(hw["load"], want32)) if abs(_ord32(g) - _ord32(w)) > 1] - if far: - i = far[0] - note(f"f32 image_load is more than 1 ulp from the quotient on {len(far)} texels " - f"(first {vals[i]:#x}: {hw['load'][i]:#010x}, want {want32[i]:#010x}): wrong T# or layout?") - if kind == "f32": - bad = [i for i, v in enumerate(vals) if hw["load"][i] != v and not _both_nan32(hw["load"][i], v)] - res["f32_load_is_the_texel"] = len(vals) - len(bad) - if bad: - note(f"the f32 image_load of a 32_FLOAT texel is not the texel for {len(bad)} of them " - f"(first {vals[bad[0]]:#010x} -> {hw['load'][bad[0]]:#010x}): wrong T# or layout?") - if kind == "f16": - bad = [i for i, v in enumerate(vals) if (hw["load_d16"][i] & 0xFFFF) != v and not ( - (v & 0x7C00) == 0x7C00 and v & 0x3FF and (hw["load_d16"][i] & 0x7C00) == 0x7C00)] - if bad: - note(f"16_FLOAT d16 image_load changed {len(bad)} texels (first {vals[bad[0]]:#06x} -> " - f"{hw['load_d16'][bad[0]] & 0xFFFF:#06x})") - bad = [i for i in range(len(vals)) if hw["point"][i] != hw["load"][i] and not _both_nan32(hw["point"][i], - hw["load"][i])] - if bad: - i = bad[0] - note(f"point sample differs from image_load on {len(bad)} texels (first {vals[i]:#x}: " - f"{hw['point'][i]:#010x} vs {hw['load'][i]:#010x}): wrong S# or coordinates?") - - hi = {f: sum(w >> 16 == SEED >> 16 for w in hw[f]) for f in ("load_d16", "point_d16", "bilin_d16")} - res["d16_high_half_kept"] = hi - - if kind in ("unorm", "snorm"): - rules = tuple(fp.RULES16) + tuple(r + "_flush" for r in fp.RULES16) - for field in ("load_d16", "point_d16"): - match = dict.fromkeys(rules, 0) - off = [] - for v, w in zip(vals, hw[field]): - m = fp.models16(kind, n, v) - g = w & 0xFFFF - for r in rules: - match[r] += g == m[r] - if g != m["f32_rte"]: # the translator's image rule: f32 first (f16_bits) - off.append({"value": f"{v:#x}", "hw": f"{g:#06x}", "f32_rte": f"{m['f32_rte']:#06x}", - "fits": [r for r in rules if m[r] == g]}) - res["fields"][field] = {"match": match, "off_f32_rte": len(off), "first_off": off[:8]} - if kind == "f32": - # "either": the even neighbour is the one toward zero, so the two readings give the same word - ties = {"inputs": 0, "to_even": 0, "toward_zero": 0, "either": 0, "other": 0} - rest = {"inputs": 0, "rte": 0, "rtz": 0, "both": 0, "other": 0} - words = [] - for v, w in zip(vals, hw["load_d16"]): - g = w & 0xFFFF - x = fp.Fraction(struct.unpack("= 0x38800000: # on a normal f16 halfway point - ties["inputs"] += 1 - ties["other" if g not in (rte, rtz) else "either" if rte == rtz else - "to_even" if g == rte else "toward_zero"] += 1 - words.append({"f32": f"{v:#010x}", "hw": f"{g:#06x}", "to_even": f"{rte:#06x}"}) - else: - rest["inputs"] += 1 - rest["both" if g == rte == rtz else "rte" if g == rte else "rtz" if g == rtz else "other"] += 1 - res["fields"]["load_d16"] = {"halfway": ties, "others": rest, "halfway_words": words} - - # bilinear: d16 against the hardware's own f32 for the same sample, and (UNORM/SNORM) against the exact mix - rte_own = rtz_own = other = nan = rtz_any = 0 - first = [] - exact32 = once16 = 0 - for i, (w32, w16) in enumerate(zip(hw["bilin"], hw["bilin_d16"])): - g = w16 & 0xFFFF - if (w32 & 0x7F800000) == 0x7F800000: # inf or NaN: compare the class only - nan += (g & 0x7C00) == 0x7C00 - other += (g & 0x7C00) != 0x7C00 - continue - f = fp.Fraction(struct.unpack("> 12) & 1 for b in v[:ties]) - # half the ties have the f16 below as the even one (nearest-even and toward-zero agree there), half above - pairs = [(fp.f16_bits(fp.to_f16(x)), fp.f16_bits(fp.to_f16(x, True))) - for x in (fp.Fraction(struct.unpack("= 20 and sum(a == b for a, b in pairs) >= 20 - assert sampler_words(True)[2] == 0x500000 and sampler_words(False)[0] == 0x8092 - assert block_values("unorm16", 3)[:2] == [3072, 3073] and blocks("unorm16") == 64 and blocks("unorm8") == 1 - assert blocks("float32") == 1 and len(texture_bytes("float32", v)) == 4096 - assert fp.models16("unorm", 16, 0xFFEF)["f32_rte"] == 0x3C00 and fp.models16("unorm", 16, 0xFFEF)["rte"] == 0x3BFF - print("self-test ok") - return 0 - - -def main(argv=None): - ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) - ap.add_argument("--formats", default=",".join(FORMATS)) - ap.add_argument("--waves", default="32,64") - ap.add_argument("--frac", type=float, default=0.5, help="bilinear offset from the texel centre, in texels") - ap.add_argument("--json") - ap.add_argument("--hw-arch") - ap.add_argument("--self-test", action="store_true") - a = ap.parse_args(argv) - if a.self_test: - return self_test() - fmts = [f for f in a.formats.split(",") if f] - bad = [f for f in fmts if f not in FORMATS] + [w for w in a.waves.split(",") if w not in ("32", "64")] - if bad or not fmts or not 0 < a.frac < 1: - ap.error("unknown or out of range: " + ", ".join(bad or ["--frac must be in (0, 1)"])) - waves = [int(w) for w in a.waves.split(",")] - from hw_oracle import asm, runner - try: - oracle = runner.open_oracle(arch=a.hw_arch) - except runner.Unavailable as e: - print(f"hardware oracle unavailable: {e}") - return 77 - rc = 0 - try: - if asm.family(oracle.arch) != "gfx10": - print(f"hardware oracle unavailable: {oracle.arch} is not GFX10; the T# and S# here are GFX10's") - return 77 - print(f"hardware oracle: {oracle.device}") - report = {"device": str(oracle.device), "arch": oracle.arch, "frac": a.frac, "formats": {}} - for fmt in fmts: - hw = {w: sweep(oracle, fmt, w, a.frac) for w in waves} - first = hw[waves[0]] - entry = classify(fmt, first, a.frac) - entry["waves_differ"] = {k: sum(x != y for x, y in zip(first[k], hw[w][k])) - for w in waves[1:] for k in first if k not in ("value", "right")} - report["formats"][fmt] = entry - for c in entry["control"]: - print(f"harness error: {fmt}: {c}") - rc = 2 - if any(entry["waves_differ"].values()) and rc != 2: - rc = 1 - print(f"{fmt} ({entry['inputs']} texels): wave32/64 differ {entry['waves_differ'] or 'n/a'}; " - f"d16 high half kept {entry['d16_high_half_kept']}") - for field, s in entry["fields"].items(): - print(f" {field}: " + json.dumps({k: v for k, v in s.items() if not k.startswith("first") - and k != "halfway_words"})) - for o in (s.get("first_off") or s.get("first_other") or [])[:3]: - print(f" {o}") - for o in s.get("halfway_words", [])[:6]: - print(f" {o}") - except RuntimeError as e: - print(f"harness error: {e}") - return 2 - finally: - oracle.close() - if a.json: - with open(a.json, "w", encoding="utf-8", newline="\n") as f: - json.dump(report, f, indent=1) - return rc - - -if __name__ == "__main__": - try: - sys.stdout.reconfigure(errors="replace") - except (AttributeError, ValueError, OSError): - pass - sys.exit(main()) diff --git a/tools/d3d12_guid_sites.py b/tools/d3d12_guid_sites.py deleted file mode 100644 index d20162a28..000000000 --- a/tools/d3d12_guid_sites.py +++ /dev/null @@ -1,423 +0,0 @@ -r"""Which GUID constants does a PE image's code pass at its call sites? (D3D-441, stdlib only) - -A console client that queries or creates a D3D12 object names the interface with a GUID: either a -16-byte constant in its own data (IID_PPV_ARGS, QueryInterface), a GUID imported as data, or an -unknown console IID that no PC header lists. tools/d3d12_iid_scan.py answers "are these *known* -IIDs present anywhere in the image"; this tool answers the call-site question: *which* 16-byte -constants does the image's code take the address of, so an unknown GUID (a console-only IID) cannot -hide among them. - -It scans executable sections for RIP-relative `lea reg, [rip+disp32]` (the way MSVC materialises -`&GUID` for x64 argument passing), maps each target into the image, and keeps the targets in -non-executable initialized sections whose 16 bytes are GUID-shaped (version nibble 1-5, RFC-4122 -variant). It also scans data sections for absolute 8-byte pointers to GUID-shaped constants (a GUID -address stored in a struct), and lists `mov reg, [rip+...]` loads that go through an import slot, -because a GUID imported as data would otherwise be invisible. Every kept candidate is matched -against the IIDs of the installed d3d12.h plus `--known NAME=GUID` values; the rest are printed as -unknown, with the referencing count and the constant's own RVA, for call-site triage. - -It also reports data windows referenced by code that parse as a `D3D12_COMMAND_QUEUE_DESC` -{Type, Priority, Flags, NodeMask}: a static queue description with a console list type is where the -DMA type's numeric value would appear if a shipped module created such a queue. - -It prints names, counts and GUID values only, no bytes of the image. - -Usage: - python -I tools/d3d12_guid_sites.py [ ...] [--header PATH/d3d12.h] - [--known NAME=GUID ...] [--json OUT] - -Without --header it takes d3d12.h from the newest Windows SDK under "Windows Kits\\10\\Include". -The --json output must name a file separate from the images and the header. -""" -from __future__ import annotations - -import argparse -import glob -import json -import os -import re -import struct -import sys -import uuid - -sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) -from report_paths import same_report_path # noqa: E402 - -MIDL = re.compile(r'MIDL_INTERFACE\("([0-9a-fA-F-]{36})"\)\s*\n\s*(ID3D12\w+)') - -# RIP-relative operand: REX.W(le) 0x8D/0x8B, modrm mod=00 rm=101; instruction length 7 (disp32). -_LEA, _MOV = 0x8D, 0x8B -REXES = (0x48, 0x49, 0x4C, 0x4D) # REX.W with optional R/B; mod=00 rm=101 stays RIP-relative - - -def default_header() -> str | None: - root = os.path.join(os.environ.get("ProgramFiles(x86)", r"C:\Program Files (x86)"), - "Windows Kits", "10", "Include") - found = glob.glob(os.path.join(root, "*", "um", "d3d12.h")) - - def version(path: str) -> tuple[int, ...]: - name = os.path.basename(os.path.dirname(os.path.dirname(path))) - return tuple(int(p) for p in name.split(".") if p.isdigit()) - - return max(found, key=version) if found else None - - -def read_iids(header: str) -> dict[str, uuid.UUID]: - with open(header, encoding="utf-8", errors="replace") as f: - text = f.read() - return {name: uuid.UUID(guid) for guid, name in MIDL.findall(text)} - - -class Image: - """A parsed PE32/PE32+ image: sections, the image base and the import directory.""" - - def __init__(self, data: bytes): - self.data = data - if data[:2] != b"MZ": - raise ValueError("not an MZ image") - pe = struct.unpack_from(" len(data): - raise ValueError("optional header too small or truncated") - opt_magic = struct.unpack_from(" int | None: - for s in self.sections: - if s["va"] <= rva < s["va"] + max(s["vsize"], s["rsize"]): - off = s["raw"] + rva - s["va"] - return off if off < len(self.data) else None - return None - - def read(self, rva: int, size: int) -> bytes | None: - off = self.rva_to_offset(rva) - return self.data[off:off + size] if off is not None else None - - def initialized(self) -> list[dict]: - return [s for s in self.sections if s["rsize"] > 0] - - def section_of(self, rva: int) -> dict | None: - for s in self.initialized(): - if s["va"] <= rva < s["va"] + max(s["vsize"], s["rsize"]): - return s - return None - - def imports(self) -> list[tuple[str, list[str]]]: - """(dll, imported names or "#ordinal") from the import directory.""" - out: list[tuple[str, list[str]]] = [] - imp_rva = self.dirs[1][0] - if not imp_rva: - return out - pos = self.rva_to_offset(imp_rva) - width, flag = (8, 1 << 63) if self.pe32plus else (4, 1 << 31) - while pos is not None and pos + 20 <= len(self.data): - lookup_rva, _, _, name_rva, iat_rva = struct.unpack_from(" dict[int, tuple[str, str]]: - """RVA of every IAT slot -> (dll, import name); targets of `mov reg, [rip+...]` are matched here.""" - slots: dict[int, tuple[str, str]] = {} - imp_rva = self.dirs[1][0] - if not imp_rva: - return slots - pos = self.rva_to_offset(imp_rva) - width = 8 if self.pe32plus else 4 - while pos is not None and pos + 20 <= len(self.data): - lookup_rva, _, _, name_rva, iat_rva = struct.unpack_from(" bool: - """A plausible RFC-4122 GUID: version nibble 1-5, variant 10xx, and not all-zero/constant.""" - if len(blob) < 16 or blob[:4] == b"\0\0\0\0": - return False - if blob[:4] == b"DXBC": # an embedded shader container, whose header hashes parse as GUID-shaped - return False - version = blob[7] >> 4 - variant = blob[8] >> 6 - if version not in (1, 2, 3, 4, 5) or variant != 0b10: - return False - return len(set(blob)) > 6 # random data, not a fill pattern - - -def rip_refs(img: Image) -> list[tuple[int, int, int]]: - """(instruction RVA, target RVA, opcode) for every RIP-relative lea/mov in executable sections.""" - out: list[tuple[int, int, int]] = [] - for s in img.initialized(): - if not s["chars"] & 0x20000000: # IMAGE_SCN_MEM_EXECUTE - continue - blob = img.data[s["raw"]:s["raw"] + s["rsize"]] - for i in range(len(blob) - 6): # a 7-byte RIP-relative instruction must fit entirely - if blob[i] not in REXES or blob[i + 1] not in (_LEA, _MOV): - continue - modrm = blob[i + 2] - if (modrm & 0xC7) != 0x05: # mod=00, rm=101 - continue - disp = struct.unpack_from(" list[tuple[int, bytes]]: - """(first instruction RVA, 16 bytes) of adjacent `movabs reg, imm64` pairs that inline a GUID. - - A compiler that materialises an IID without a constant pool writes its two halves as two 10-byte - `REX.W B8+r imm64` moves; the concatenation is the GUID a lea would otherwise point at. - """ - out: list[tuple[int, bytes]] = [] - for s in img.initialized(): - if not s["chars"] & 0x20000000: - continue - blob = img.data[s["raw"]:s["raw"] + s["rsize"]] - imm: list[tuple[int, bytes]] = [] - for i in range(len(blob) - 10): - if blob[i] == 0x48 and 0xB8 <= blob[i + 1] <= 0xBF: - imm.append((s["va"] + i, blob[i + 2:i + 10])) - for (rva1, first), (rva2, second) in zip(imm, imm[1:]): - if rva2 - rva1 > 32: # the two halves are written together - continue - joined = first + second - if guid_shaped(joined): - out.append((rva1, joined)) - return out - -def absolute_refs(img: Image) -> list[tuple[int, int]]: - """(location RVA, target RVA) for 8-byte aligned absolute pointers into the image's own data.""" - out: list[tuple[int, int]] = [] - if not img.pe32plus: - return out - lo = img.image_base - for s in img.initialized(): - blob = img.data[s["raw"]:s["raw"] + s["rsize"]] - for i in range(0, len(blob) - 8, 8): - value = struct.unpack_from(" bool: - """A plausible `D3D12_COMMAND_QUEUE_DESC` {Type, Priority, Flags, NodeMask}.""" - if blob == b"\0" * 16: # a referenced zero block is padding, not a description - return False - t, p, flags, node = struct.unpack_from(" 15 or node > 1: # console list types stay small; a title queues on one node - return False - if p not in (0, 1, 2, 0xFFFFFFFF, 0x80000000): # NORMAL/HIGH/GLOBAL_REALTIME/"-1"/OR-ed - return False - return flags <= 0x3 # D3D12_COMMAND_QUEUE_FLAG_NONE/ALLOW_GPU_TIMEOUT/DISABLE_GPU_TIMEOUT - - -def scan(path: str, known: dict[str, uuid.UUID]) -> dict: - with open(path, "rb") as f: - data = f.read() - img = Image(data) - by_value = {} - for name, guid in known.items(): - by_value.setdefault(guid.bytes_le, []).append(name) - - def constant_at(rva: int) -> tuple[bytes, str] | None: - """The 16 bytes at `rva` when it sits in an initialized, non-executable section (a constant pool).""" - s = img.section_of(rva) - if s is None or s["chars"] & 0x20000000: - return None - blob = img.read(rva, 16) - return (blob, s["name"]) if blob is not None else None - - candidates: dict[bytes, dict] = {} - leas = 0 - iat_loads: list[tuple[int, str, str]] = [] - slots = img.iat_slots() - for insn_rva, target, opcode in rip_refs(img): - if opcode == _MOV: - if target in slots: - dll, name = slots[target] - iat_loads.append((insn_rva, dll, name)) - continue - leas += 1 - at = constant_at(target) - if at is None or not guid_shaped(at[0]): - continue - entry = candidates.setdefault(at[0], {"refs": [], "known": None, "section": at[1], "rva": target}) - entry["refs"].append(insn_rva) - if at[0] in by_value: - entry["known"] = by_value[at[0]] - for loc_rva, target in absolute_refs(img): - at = constant_at(target) - if at is None or not guid_shaped(at[0]): - continue - entry = candidates.setdefault(at[0], {"refs": [], "known": None, "section": at[1], "rva": target}) - entry["refs"].append(loc_rva) - if at[0] in by_value: - entry["known"] = by_value[at[0]] - for rva, joined in movabs_pairs(img): - entry = candidates.setdefault(joined, {"refs": [], "known": None, "section": "movabs", "rva": rva}) - entry["refs"].append(rva) - if joined in by_value: - entry["known"] = by_value[joined] - lea_targets = {t for _, t, op in rip_refs(img) if op == _LEA} - descs = [] - for s in img.initialized(): - if s["chars"] & 0x20000000: # code sections are not queue descriptions - continue - blob = img.data[s["raw"]:s["raw"] + s["rsize"]] - for i in range(0, len(blob) - 16, 4): - if s["va"] + i in lea_targets and queue_desc_shaped(blob[i:i + 16]): - t, p, flags, node = struct.unpack_from(" int: - ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) - ap.add_argument("images", nargs="+") - ap.add_argument("--header", help="d3d12.h to read the known IIDs from (default: newest Windows SDK)") - ap.add_argument("--known", action="append", default=[], metavar="NAME=GUID", - help="a known GUID the header does not list, e.g. a console IID (repeatable)") - ap.add_argument("--json", help="also write the result here") - args = ap.parse_args(argv) - - header = args.header - if header is None: - header = default_header() - if args.json: - for source in (*args.images, header): - if source and same_report_path(args.json, source): - ap.error(f"--json {args.json} would overwrite the input {source}") - - known: dict[str, uuid.UUID] = {} - if header and os.path.isfile(header): - known.update(read_iids(header)) - for pair in args.known: - name, _, value = pair.partition("=") - try: - known[name] = uuid.UUID(value) - except ValueError: - print(f"ERROR: --known expects NAME=GUID, got {pair!r}", file=sys.stderr) - return 2 - print(f"{len(known)} known GUIDs" + (f" from {header}" if header else "")) - - results = [] - for path in args.images: - if not os.path.isfile(path): - print(f"ERROR: cannot read {path}: no such file", file=sys.stderr) - return 2 - try: - r = scan(path, known) - except (ValueError, struct.error) as e: - print(f"== {os.path.basename(path)}: skipped ({e})") - continue - results.append(r) - print(f"== {r['image']}: {r['lea_count']} RIP-relative lea, " - f"{len(r['guid_candidates'])} GUID-shaped referenced constants, " - f"{len(r['queue_descs'])} referenced queue-desc-shaped windows") - for c in r["guid_candidates"]: - names = ", ".join(c["known"]) if c["known"] else "UNKNOWN" - print(f" {c['value']} x{c['refs']} at {c['section']} rva 0x{c['rva']:x} {names}") - for w in r["iat_guid_loads"]: - print(f" IAT GUID load at rva 0x{w['rva']:x}: {w['dll']}!{w['name']}") - for d in r["queue_descs"]: - print(f" queue-desc-shaped window at rva 0x{d['rva']:x}: Type={d['type']} " - f"Priority={d['priority']} Flags={d['flags']} NodeMask={d['node']}") - for line in r["imports_of_note"]: - print(f" GUID-named imports: {line}") - if args.json: - with open(args.json, "w", encoding="utf-8", newline="\n") as f: - json.dump({"known": len(known), "images": results}, f, indent=2) - f.write("\n") - return 0 - - -if __name__ == "__main__": - try: # a redirected stdout is strict ANSI code page under -I; write '?' for what it cannot encode - sys.stdout.reconfigure(errors="replace") - except (AttributeError, ValueError, OSError): - pass - sys.exit(main()) diff --git a/tools/d3d12_iid_scan.py b/tools/d3d12_iid_scan.py deleted file mode 100644 index f9ea4b40b..000000000 --- a/tools/d3d12_iid_scan.py +++ /dev/null @@ -1,200 +0,0 @@ -r"""Which D3D12 interfaces can a PE image ask for? (D3D-350, stdlib only) - -A client that creates a D3D12 object passes the interface's IID (`IID_PPV_ARGS`), so the 16 GUID bytes are in the -caller's image unless it imports them as data (`d3d12_xs.dll` exports IIDs; see docs/d3d12_xs_surface.md section -2). This tool reads every `MIDL_INTERFACE("...") ID3D12...` declaration from the Windows SDK's d3d12.h and reports -which of those IIDs occur, little-endian as in memory, anywhere in each image. An interface that is absent was -never created or queried by that image through a constant of its own. - -docs/d3d12_command_objects.md section 2.1 uses it to show that no DLL in the package can call the device's queue, -allocator, command-list or fence creators (slots 8, 9, 12 and 36). The interfaces that are found act as the -positive control: they match the objects the image is known to create. - -It prints interface names and counts only, no bytes of the image. - -Usage: - python -I tools/d3d12_iid_scan.py [ ...] [--header PATH/d3d12.h] [--json OUT] - -Without --header it takes d3d12.h from the newest Windows SDK under "Windows Kits\10\Include". -It also lists what each image imports from d3d12_xs.dll and warns when one of those imports could be IID data (an -IID_* name, or an ordinal in the GUID range 23-115), because an IID taken from there would not show up here. -""" -from __future__ import annotations - -import argparse -import glob -import json -import os -import re -import struct -import sys -import uuid - -sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) -from report_paths import same_report_path # noqa: E402 - -MIDL = re.compile(r'MIDL_INTERFACE\("([0-9a-fA-F-]{36})"\)\s*\n\s*(ID3D12\w+)') - -# The creators whose result interfaces docs/d3d12_command_objects.md section 2.1 asks about. -FOCUS = ("ID3D12CommandQueue", "ID3D12CommandAllocator", "ID3D12CommandList", "ID3D12GraphicsCommandList", - "ID3D12Fence", "ID3D12Fence1") - - -def default_header() -> str | None: - root = os.path.join(os.environ.get("ProgramFiles(x86)", r"C:\Program Files (x86)"), - "Windows Kits", "10", "Include") - found = glob.glob(os.path.join(root, "*", "um", "d3d12.h")) - - def version(path: str) -> tuple[int, ...]: - name = os.path.basename(os.path.dirname(os.path.dirname(path))) - return tuple(int(p) for p in name.split(".") if p.isdigit()) - - return max(found, key=version) if found else None - - -def read_iids(header: str) -> dict[str, uuid.UUID]: - with open(header, encoding="utf-8", errors="replace") as f: - text = f.read() - return {name: uuid.UUID(guid) for guid, name in MIDL.findall(text)} - - -def d3d12_xs_imports(data: bytes) -> list[str] | None: - """What the PE image imports from d3d12_xs.dll: names, or "#N" for an import by ordinal (ordinals 23-115 are - GUID data, docs/d3d12_xs_surface.md section 2). None when the image does not import d3d12_xs.dll at all.""" - try: - if data[:2] != b"MZ": - return None - pe = struct.unpack_from(" int | None: - for i in range(sections): - s = table + 40 * i - vsize, va, rsize, raw = struct.unpack_from(" bytes: - return data[at:data.index(b"\0", at)] - - names: list[str] | None = None - pos = offset(imp_rva) if imp_rva else None - while pos is not None and pos + 20 <= len(data): - lookup_rva, _, _, name_rva, iat_rva = struct.unpack_from(" list[str]: - """The d3d12_xs.dll imports that could be IID data: IID_* names and ordinals in the GUID range 23-115.""" - out = [] - for n in names or []: - if n.startswith("IID_") or (n.startswith("#") and n[1:].isdigit() and 23 <= int(n[1:]) <= 115): - out.append(n) - return out - - -def scan(path: str, iids: dict[str, uuid.UUID]) -> dict: - with open(path, "rb") as f: - data = f.read() - found = sorted(name for name, guid in iids.items() if guid.bytes_le in data) - imports = d3d12_xs_imports(data) - return { - "image": os.path.basename(path), - "found": found, - "focus": {name: name in found for name in FOCUS if name in iids}, - "d3d12_xs_imports": imports, - "possible_iid_imports": possible_iid_imports(imports), - } - - -def main(argv: list[str] | None = None) -> int: - ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) - ap.add_argument("images", nargs="+") - ap.add_argument("--header", help="d3d12.h to read the IIDs from (default: newest Windows SDK)") - ap.add_argument("--json", help="also write the result here") - args = ap.parse_args(argv) - if args.json: - # The report is written last, after every input has been read, so an aliased input would - # silently be replaced by it. Refuse the alias before anything is opened. - for what, other in (("--header", args.header), *(("an input image", p) for p in args.images)): - if other and same_report_path(args.json, other): - print(f"ERROR: --json would overwrite {what}: {other}", file=sys.stderr) - return 2 - header = args.header or default_header() - if not header or not os.path.isfile(header): - print("ERROR: d3d12.h not found; pass --header", file=sys.stderr) - return 2 - try: - iids = read_iids(header) - except OSError as e: - print(f"ERROR: cannot read {header}: {e.strerror or e}", file=sys.stderr) - return 2 - if not iids: - print(f"ERROR: no ID3D12 MIDL_INTERFACE declarations in {header}", file=sys.stderr) - return 2 - print(f"{len(iids)} ID3D12 IIDs from {header}") - results = [] - for path in args.images: - try: - r = scan(path, iids) - except OSError as e: # a missing, locked or folder image used to end the run in a traceback - print(f"ERROR: cannot read {path}: {e.strerror or e}", file=sys.stderr) - return 2 - results.append(r) - absent = [n for n, present in r["focus"].items() if not present] - print(f"== {r['image']}: {len(r['found'])} found") - print(" found: " + (", ".join(r["found"]) or "none")) - print(" absent from the queue/allocator/list/fence set: " + (", ".join(absent) or "none")) - if r["d3d12_xs_imports"] is not None: - print(" imports from d3d12_xs.dll: " + (", ".join(r["d3d12_xs_imports"]) or "none")) - if r["possible_iid_imports"]: - print(" WARNING: these d3d12_xs.dll imports may be IID data, so an absent IID proves nothing for " - "this image: " + ", ".join(r["possible_iid_imports"])) - if args.json: - try: - with open(args.json, "w", encoding="utf-8", newline="\n") as f: - json.dump({"header": os.path.basename(header), "iids": len(iids), "images": results}, f, indent=2) - f.write("\n") - except OSError as e: - print(f"ERROR: cannot write {args.json}: {e.strerror or e}", file=sys.stderr) - return 2 - return 0 - - -if __name__ == "__main__": - try: # a redirected stdout is strict ANSI code page under -I; write '?' for what it cannot encode - sys.stdout.reconfigure(errors="replace") - except (AttributeError, ValueError, OSError): - pass - sys.exit(main()) diff --git a/tools/d3d12_xs_surface.py b/tools/d3d12_xs_surface.py deleted file mode 100644 index 72d7d86cb..000000000 --- a/tools/d3d12_xs_surface.py +++ /dev/null @@ -1,629 +0,0 @@ -#!/usr/bin/env python3 -"""The measured Xbox Series ``d3d12_xs.dll`` export surface, with provenance. - -This is the machine-checkable half of ``docs/d3d12_xs_surface.md``. It does not talk to a game, a -vendor DLL or the network. The data is the surface SCARAB measured from the console runtime -(``p-portela/SCARAB`` @ d304fa2, GPL-3.0-only), plus the 28 D3D12 IIDs, which are also Windows SDK -facts. See the doc for the per-item evidence and for the claims that did not hold up. - -Checks that always run: - * 116 slots, ordinals 1..116 exactly once, 23 functions + 93 GUID data; - * every standard GUID in the table is byte-identical to the Windows SDK, when the SDK is found; - * GUIDs are valid RFC 4122 version 4, unique, and the 10 console GUIDs are not in the SDK set; - * the 88 IID ordinals 28..115 are alphabetical, except IID_ID3D12ConsDmaCommandList pinned at 100; - * the four unresolved console command-list IIDs are not assigned values or ordinals in the local tables. - -Optional checks: - * ``--scarab PATH`` cross-checks the table against a SCARAB checkout (values, ordinals, catalogue). - * ``--require-sdk`` turns a missing SDK into a failure instead of a skip. - -Usage: - python tools/d3d12_xs_surface.py --check - python tools/d3d12_xs_surface.py --check --sdk - python tools/d3d12_xs_surface.py --check --scarab C:\\path\\to\\scarab-ref - python tools/d3d12_xs_surface.py --markdown -""" -# SPDX-License-Identifier: GPL-3.0-or-later -# Original code. Facts sourced from SCARAB (GPL-3.0-only) and the Windows SDK; no SCARAB code copied. -from __future__ import annotations - -import argparse -import glob -import os -import re -import sys - -SCARAB_COMMIT = "d304fa26c0292e2f3ba76f23b15c9f30734bec02" - -# (ordinal, export, kind). Kind: standard | console. Names are SCARAB's published spellings; the -# five D3D12Cons* names are internal aliases, not verified wire names (doc section 2.3). -FUNCTION_EXPORTS = [ - (1, "D3D12ZeroMemoryX", "console"), - (2, "PixGetPixieEntryPoints", "console"), - (3, "D3D10CreateBlob", "console"), - (4, "D3D12ConfigureVirtualMemoryX", "console"), - (5, "D3D12CreateDevice", "standard"), - (6, "D3D12CreateRootSignatureDeserializer", "standard"), - (7, "D3D12CreateVersionedRootSignatureDeserializer", "standard"), - (8, "D3D12EnableExperimentalFeatures", "standard"), - (9, "D3D12GetDebugInterface", "standard"), - (10, "D3D12SerializeRootSignature", "standard"), - (11, "D3D12SerializeVersionedRootSignature", "standard"), - (12, "D3D12UploadCustomMicrocodeX", "console"), - (13, "D3D12ConsCreateDevice", "console"), - (14, "D3D12ConsEnableMemoryProfiling", "console"), - (15, "D3D12ConsGetProcessDebugFlags", "console"), - (16, "D3D12ConsSetProcessDebugFlags", "console"), - (17, "D3D12ConsUnloadDriverModule", "console"), - (18, "D3DFlushEntireCpuCache", "console"), - (19, "DXGIXGetFrameStatistics", "console"), - (20, "DXGIXPresentArray", "console"), - (21, "DXGIXSetFrameNotification", "console"), - (22, "DXGIXSetVLineNotification", "console"), - (116, "InternalDriverCallX", "console"), -] - -# Ordinals 23..115: 93 GUID data exports. Evidence is "documented" when iid_console.inc carries the -# ordinal, "derived" when it comes from the alphabetical rule anchored by IID_ID3D12Debug @76. -# Kind is debug | blob | d3d11 | d3d12 | console. The 10 console GUIDs are listed in CONSOLE_IIDS. -DATA_EXPORTS = [ - (23, "DXGI_DEBUG_ALL", "debug", "derived"), - (24, "DXGI_DEBUG_APP", "debug", "derived"), - (25, "DXGI_DEBUG_D3D11", "debug", "derived"), - (26, "DXGI_DEBUG_DX", "debug", "derived"), - (27, "DXGI_DEBUG_DXGI", "debug", "derived"), - (28, "IID_ID3D10Blob", "blob", "derived"), - (29, "IID_ID3D11Asynchronous", "d3d11", "documented"), - (30, "IID_ID3D11BlendState", "d3d11", "documented"), - (31, "IID_ID3D11BlendState1", "d3d11", "documented"), - (32, "IID_ID3D11Buffer", "d3d11", "documented"), - (33, "IID_ID3D11ClassInstance", "d3d11", "documented"), - (34, "IID_ID3D11ClassLinkage", "d3d11", "documented"), - (35, "IID_ID3D11CommandList", "d3d11", "documented"), - (36, "IID_ID3D11ComputeShader", "d3d11", "documented"), - (37, "IID_ID3D11Counter", "d3d11", "documented"), - (38, "IID_ID3D11CounterSampleX", "console", "documented"), - (39, "IID_ID3D11CounterSetX", "console", "documented"), - (40, "IID_ID3D11DepthStencilState", "d3d11", "documented"), - (41, "IID_ID3D11DepthStencilView", "d3d11", "documented"), - (42, "IID_ID3D11Device", "d3d11", "documented"), - (43, "IID_ID3D11Device1", "d3d11", "documented"), - (44, "IID_ID3D11DeviceChild", "d3d11", "documented"), - (45, "IID_ID3D11DeviceContext", "d3d11", "documented"), - (46, "IID_ID3D11DeviceContext1", "d3d11", "documented"), - (47, "IID_ID3D11DeviceContextX", "console", "documented"), - (48, "IID_ID3D11DeviceX", "console", "documented"), - (49, "IID_ID3D11DmaEngineContextX", "console", "documented"), - (50, "IID_ID3D11DomainShader", "d3d11", "documented"), - (51, "IID_ID3D11GeometryShader", "d3d11", "documented"), - (52, "IID_ID3D11HullShader", "d3d11", "documented"), - (53, "IID_ID3D11InputLayout", "d3d11", "documented"), - (54, "IID_ID3D11PerformanceContextX", "console", "documented"), - (55, "IID_ID3D11PerformanceDeviceX", "console", "documented"), - (56, "IID_ID3D11PixelShader", "d3d11", "documented"), - (57, "IID_ID3D11Predicate", "d3d11", "documented"), - (58, "IID_ID3D11Query", "d3d11", "documented"), - (59, "IID_ID3D11RasterizerState", "d3d11", "documented"), - (60, "IID_ID3D11RasterizerState1", "d3d11", "documented"), - (61, "IID_ID3D11RenderTargetView", "d3d11", "documented"), - (62, "IID_ID3D11Resource", "d3d11", "documented"), - (63, "IID_ID3D11SamplerState", "d3d11", "documented"), - (64, "IID_ID3D11ShaderResourceView", "d3d11", "documented"), - (65, "IID_ID3D11Texture1D", "d3d11", "documented"), - (66, "IID_ID3D11Texture2D", "d3d11", "documented"), - (67, "IID_ID3D11Texture3D", "d3d11", "documented"), - (68, "IID_ID3D11UnorderedAccessView", "d3d11", "documented"), - (69, "IID_ID3D11UserDefinedAnnotationX", "console", "documented"), - (70, "IID_ID3D11VertexShader", "d3d11", "documented"), - (71, "IID_ID3D11View", "d3d11", "documented"), - (72, "IID_ID3D12CommandAllocator", "d3d12", "derived"), - (73, "IID_ID3D12CommandList", "d3d12", "derived"), - (74, "IID_ID3D12CommandQueue", "d3d12", "derived"), - (75, "IID_ID3D12CommandSignature", "d3d12", "derived"), - (76, "IID_ID3D12Debug", "d3d12", "derived"), - (77, "IID_ID3D12DescriptorHeap", "d3d12", "derived"), - (78, "IID_ID3D12Device", "d3d12", "derived"), - (79, "IID_ID3D12Device1", "d3d12", "derived"), - (80, "IID_ID3D12Device2", "d3d12", "derived"), - (81, "IID_ID3D12Device3", "d3d12", "derived"), - (82, "IID_ID3D12Device4", "d3d12", "derived"), - (83, "IID_ID3D12DeviceChild", "d3d12", "derived"), - (84, "IID_ID3D12Fence", "d3d12", "derived"), - (85, "IID_ID3D12Fence1", "d3d12", "derived"), - (86, "IID_ID3D12GraphicsCommandList", "d3d12", "derived"), - (87, "IID_ID3D12GraphicsCommandList1", "d3d12", "derived"), - (88, "IID_ID3D12GraphicsCommandList2", "d3d12", "derived"), - (89, "IID_ID3D12Heap", "d3d12", "derived"), - (90, "IID_ID3D12Object", "d3d12", "derived"), - (91, "IID_ID3D12Pageable", "d3d12", "derived"), - (92, "IID_ID3D12PipelineLibrary", "d3d12", "derived"), - (93, "IID_ID3D12PipelineLibrary1", "d3d12", "derived"), - (94, "IID_ID3D12PipelineState", "d3d12", "derived"), - (95, "IID_ID3D12Resource", "d3d12", "derived"), - (96, "IID_ID3D12RootSignature", "d3d12", "derived"), - (97, "IID_ID3D12RootSignatureDeserializer", "d3d12", "derived"), - (98, "IID_ID3D12Tools", "d3d12", "derived"), - (99, "IID_ID3D12VersionedRootSignatureDeserializer", "d3d12", "derived"), - (100, "IID_ID3D12ConsDmaCommandList", "console", "documented"), - (101, "IID_ID3DDeviceContextState", "d3d11", "documented"), - (102, "IID_IDXGIAdapter", "d3d11", "documented"), - (103, "IID_IDXGIAdapter1", "d3d11", "documented"), - (104, "IID_IDXGIAdapter2", "d3d11", "documented"), - (105, "IID_IDXGIDevice", "d3d11", "documented"), - (106, "IID_IDXGIDevice1", "d3d11", "documented"), - (107, "IID_IDXGIDevice2", "d3d11", "documented"), - (108, "IID_IDXGIDeviceSubObject", "d3d11", "documented"), - (109, "IID_IDXGIFactory", "d3d11", "documented"), - (110, "IID_IDXGIFactory1", "d3d11", "documented"), - (111, "IID_IDXGIFactory2", "d3d11", "documented"), - (112, "IID_IDXGIObject", "d3d11", "documented"), - (113, "IID_IDXGISwapChain", "d3d11", "documented"), - (114, "IID_IDXGISwapChain1", "d3d11", "documented"), - (115, "IID_IGraphicsUnknown", "console", "documented"), -] - -# The 83 standard GUIDs. Values match the Windows SDK 10.0.26100.0 headers (doc section 3). -STANDARD_GUIDS = { - "DXGI_DEBUG_ALL": (0xE48AE283, 0xDA80, 0x490B, 0x87, 0xE6, 0x43, 0xE9, 0xA9, 0xCF, 0xDA, 0x08), - "DXGI_DEBUG_APP": (0x06CD6E01, 0x4219, 0x4EBD, 0x87, 0x09, 0x27, 0xED, 0x23, 0x36, 0x0C, 0x62), - "DXGI_DEBUG_D3D11": (0x4B99317B, 0xAC39, 0x4AA6, 0xBB, 0x0B, 0xBA, 0xA0, 0x47, 0x84, 0x79, 0x8F), - "DXGI_DEBUG_DX": (0x35CDD7FC, 0x13B2, 0x421D, 0xA5, 0xD7, 0x7E, 0x44, 0x51, 0x28, 0x7D, 0x64), - "DXGI_DEBUG_DXGI": (0x25CDDAA4, 0xB1C6, 0x47E1, 0xAC, 0x3E, 0x98, 0x87, 0x5B, 0x5A, 0x2E, 0x2A), - "IID_ID3D10Blob": (0x8BA5FB08, 0x5195, 0x40E2, 0xAC, 0x58, 0x0D, 0x98, 0x9C, 0x3A, 0x01, 0x02), - "IID_ID3D11Asynchronous": (0x4B35D0CD, 0x1E15, 0x4258, 0x9C, 0x98, 0x1B, 0x13, 0x33, 0xF6, 0xDD, 0x3B), - "IID_ID3D11BlendState": (0x75B68FAA, 0x347D, 0x4159, 0x8F, 0x45, 0xA0, 0x64, 0x0F, 0x01, 0xCD, 0x9A), - "IID_ID3D11BlendState1": (0xCC86FABE, 0xDA55, 0x401D, 0x85, 0xE7, 0xE3, 0xC9, 0xDE, 0x28, 0x77, 0xE9), - "IID_ID3D11Buffer": (0x48570B85, 0xD1EE, 0x4FCD, 0xA2, 0x50, 0xEB, 0x35, 0x07, 0x22, 0xB0, 0x37), - "IID_ID3D11ClassInstance": (0xA6CD7FAA, 0xB0B7, 0x4A2F, 0x94, 0x36, 0x86, 0x62, 0xA6, 0x57, 0x97, 0xCB), - "IID_ID3D11ClassLinkage": (0xDDF57CBA, 0x9543, 0x46E4, 0xA1, 0x2B, 0xF2, 0x07, 0xA0, 0xFE, 0x7F, 0xED), - "IID_ID3D11CommandList": (0xA24BC4D1, 0x769E, 0x43F7, 0x80, 0x13, 0x98, 0xFF, 0x56, 0x6C, 0x18, 0xE2), - "IID_ID3D11ComputeShader": (0x4F5B196E, 0xC2BD, 0x495E, 0xBD, 0x01, 0x1F, 0xDE, 0xD3, 0x8E, 0x49, 0x69), - "IID_ID3D11Counter": (0x6E8C49FB, 0xA371, 0x4770, 0xB4, 0x40, 0x29, 0x08, 0x60, 0x22, 0xB7, 0x41), - "IID_ID3D11DepthStencilState": (0x03823EFB, 0x8D8F, 0x4E1C, 0x9A, 0xA2, 0xF6, 0x4B, 0xB2, 0xCB, 0xFD, 0xF1), - "IID_ID3D11DepthStencilView": (0x9FDAC92A, 0x1876, 0x48C3, 0xAF, 0xAD, 0x25, 0xB9, 0x4F, 0x84, 0xA9, 0xB6), - "IID_ID3D11Device": (0xDB6F6DDB, 0xAC77, 0x4E88, 0x82, 0x53, 0x81, 0x9D, 0xF9, 0xBB, 0xF1, 0x40), - "IID_ID3D11Device1": (0xA04BFB29, 0x08EF, 0x43D6, 0xA4, 0x9C, 0xA9, 0xBD, 0xBD, 0xCB, 0xE6, 0x86), - "IID_ID3D11DeviceChild": (0x1841E5C8, 0x16B0, 0x489B, 0xBC, 0xC8, 0x44, 0xCF, 0xB0, 0xD5, 0xDE, 0xAE), - "IID_ID3D11DeviceContext": (0xC0BFA96C, 0xE089, 0x44FB, 0x8E, 0xAF, 0x26, 0xF8, 0x79, 0x61, 0x90, 0xDA), - "IID_ID3D11DeviceContext1": (0xBB2C6FAA, 0xB5FB, 0x4082, 0x8E, 0x6B, 0x38, 0x8B, 0x8C, 0xFA, 0x90, 0xE1), - "IID_ID3D11DomainShader": (0xF582C508, 0x0F36, 0x490C, 0x99, 0x77, 0x31, 0xEE, 0xCE, 0x26, 0x8C, 0xFA), - "IID_ID3D11GeometryShader": (0x38325B96, 0xEFFB, 0x4022, 0xBA, 0x02, 0x2E, 0x79, 0x5B, 0x70, 0x27, 0x5C), - "IID_ID3D11HullShader": (0x8E5C6061, 0x628A, 0x4C8E, 0x82, 0x64, 0xBB, 0xE4, 0x5C, 0xB3, 0xD5, 0xDD), - "IID_ID3D11InputLayout": (0xE4819DDC, 0x4CF0, 0x4025, 0xBD, 0x26, 0x5D, 0xE8, 0x2A, 0x3E, 0x07, 0xB7), - "IID_ID3D11PixelShader": (0xEA82E40D, 0x51DC, 0x4F33, 0x93, 0xD4, 0xDB, 0x7C, 0x91, 0x25, 0xAE, 0x8C), - "IID_ID3D11Predicate": (0x9EB576DD, 0x9F77, 0x4D86, 0x81, 0xAA, 0x8B, 0xAB, 0x5F, 0xE4, 0x90, 0xE2), - "IID_ID3D11Query": (0xD6C00747, 0x87B7, 0x425E, 0xB8, 0x4D, 0x44, 0xD1, 0x08, 0x56, 0x0A, 0xFD), - "IID_ID3D11RasterizerState": (0x9BB4AB81, 0xAB1A, 0x4D8F, 0xB5, 0x06, 0xFC, 0x04, 0x20, 0x0B, 0x6E, 0xE7), - "IID_ID3D11RasterizerState1": (0x1217D7A6, 0x5039, 0x418C, 0xB0, 0x42, 0x9C, 0xBE, 0x25, 0x6A, 0xFD, 0x6E), - "IID_ID3D11RenderTargetView": (0xDFDBA067, 0x0B8D, 0x4865, 0x87, 0x5B, 0xD7, 0xB4, 0x51, 0x6C, 0xC1, 0x64), - "IID_ID3D11Resource": (0xDC8E63F3, 0xD12B, 0x4952, 0xB4, 0x7B, 0x5E, 0x45, 0x02, 0x6A, 0x86, 0x2D), - "IID_ID3D11SamplerState": (0xDA6FEA51, 0x564C, 0x4487, 0x98, 0x10, 0xF0, 0xD0, 0xF9, 0xB4, 0xE3, 0xA5), - "IID_ID3D11ShaderResourceView": (0xB0E06FE0, 0x8192, 0x4E1A, 0xB1, 0xCA, 0x36, 0xD7, 0x41, 0x47, 0x10, 0xB2), - "IID_ID3D11Texture1D": (0xF8FB5C27, 0xC6B3, 0x4F75, 0xA4, 0xC8, 0x43, 0x9A, 0xF2, 0xEF, 0x56, 0x4C), - "IID_ID3D11Texture2D": (0x6F15AAF2, 0xD208, 0x4E89, 0x9A, 0xB4, 0x48, 0x95, 0x35, 0xD3, 0x4F, 0x9C), - "IID_ID3D11Texture3D": (0x037E866E, 0xF56D, 0x4357, 0xA8, 0xAF, 0x9D, 0xAB, 0xBE, 0x6E, 0x25, 0x0E), - "IID_ID3D11UnorderedAccessView": (0x28ACF509, 0x7F5C, 0x48F6, 0x86, 0x11, 0xF3, 0x16, 0x01, 0x0A, 0x63, 0x80), - "IID_ID3D11VertexShader": (0x3B301D64, 0xD678, 0x4289, 0x88, 0x97, 0x22, 0xF8, 0x92, 0x8B, 0x72, 0xF3), - "IID_ID3D11View": (0x839D1216, 0xBB2E, 0x412B, 0xB7, 0xF4, 0xA9, 0xDB, 0xEB, 0xE0, 0x8E, 0xD1), - "IID_ID3D12CommandAllocator": (0x6102DEE4, 0xAF59, 0x4B09, 0xB9, 0x99, 0xB4, 0x4D, 0x73, 0xF0, 0x9B, 0x24), - "IID_ID3D12CommandList": (0x7116D91C, 0xE7E4, 0x47CE, 0xB8, 0xC6, 0xEC, 0x81, 0x68, 0xF4, 0x37, 0xE5), - "IID_ID3D12CommandQueue": (0x0EC870A6, 0x5D7E, 0x4C22, 0x8C, 0xFC, 0x5B, 0xAA, 0xE0, 0x76, 0x16, 0xED), - "IID_ID3D12CommandSignature": (0xC36A797C, 0xEC80, 0x4F0A, 0x89, 0x85, 0xA7, 0xB2, 0x47, 0x50, 0x82, 0xD1), - "IID_ID3D12Debug": (0x344488B7, 0x6846, 0x474B, 0xB9, 0x89, 0xF0, 0x27, 0x44, 0x82, 0x45, 0xE0), - "IID_ID3D12DescriptorHeap": (0x8EFB471D, 0x616C, 0x4F49, 0x90, 0xF7, 0x12, 0x7B, 0xB7, 0x63, 0xFA, 0x51), - "IID_ID3D12Device": (0x189819F1, 0x1DB6, 0x4B57, 0xBE, 0x54, 0x18, 0x21, 0x33, 0x9B, 0x85, 0xF7), - "IID_ID3D12Device1": (0x77ACCE80, 0x638E, 0x4E65, 0x88, 0x95, 0xC1, 0xF2, 0x33, 0x86, 0x86, 0x3E), - "IID_ID3D12Device2": (0x30BAA41E, 0xB15B, 0x475C, 0xA0, 0xBB, 0x1A, 0xF5, 0xC5, 0xB6, 0x43, 0x28), - "IID_ID3D12Device3": (0x81DADC15, 0x2BAD, 0x4392, 0x93, 0xC5, 0x10, 0x13, 0x45, 0xC4, 0xAA, 0x98), - "IID_ID3D12Device4": (0xE865DF17, 0xA9EE, 0x46F9, 0xA4, 0x63, 0x30, 0x98, 0x31, 0x5A, 0xA2, 0xE5), - "IID_ID3D12DeviceChild": (0x905DB94B, 0xA00C, 0x4140, 0x9D, 0xF5, 0x2B, 0x64, 0xCA, 0x9E, 0xA3, 0x57), - "IID_ID3D12Fence": (0x0A753DCF, 0xC4D8, 0x4B91, 0xAD, 0xF6, 0xBE, 0x5A, 0x60, 0xD9, 0x5A, 0x76), - "IID_ID3D12Fence1": (0x433685FE, 0xE22B, 0x4CA0, 0xA8, 0xDB, 0xB5, 0xB4, 0xF4, 0xDD, 0x0E, 0x4A), - "IID_ID3D12GraphicsCommandList": (0x5B160D0F, 0xAC1B, 0x4185, 0x8B, 0xA8, 0xB3, 0xAE, 0x42, 0xA5, 0xA4, 0x55), - "IID_ID3D12GraphicsCommandList1": (0x553103FB, 0x1FE7, 0x4557, 0xBB, 0x38, 0x94, 0x6D, 0x7D, 0x0E, 0x7C, 0xA7), - "IID_ID3D12GraphicsCommandList2": (0x38C3E585, 0xFF17, 0x412C, 0x91, 0x50, 0x4F, 0xC6, 0xF9, 0xD7, 0x2A, 0x28), - "IID_ID3D12Heap": (0x6B3B2502, 0x6E51, 0x45B3, 0x90, 0xEE, 0x98, 0x84, 0x26, 0x5E, 0x8D, 0xF3), - "IID_ID3D12Object": (0xC4FEC28F, 0x7966, 0x4E95, 0x9F, 0x94, 0xF4, 0x31, 0xCB, 0x56, 0xC3, 0xB8), - "IID_ID3D12Pageable": (0x63EE58FB, 0x1268, 0x4835, 0x86, 0xDA, 0xF0, 0x08, 0xCE, 0x62, 0xF0, 0xD6), - "IID_ID3D12PipelineLibrary": (0xC64226A8, 0x9201, 0x46AF, 0xB4, 0xCC, 0x53, 0xFB, 0x9F, 0xF7, 0x41, 0x4F), - "IID_ID3D12PipelineLibrary1": (0x80EABF42, 0x2568, 0x4E5E, 0xBD, 0x82, 0xC3, 0x7F, 0x86, 0x96, 0x1D, 0xC3), - "IID_ID3D12PipelineState": (0x765A30F3, 0xF624, 0x4C6F, 0xA8, 0x28, 0xAC, 0xE9, 0x48, 0x62, 0x24, 0x45), - "IID_ID3D12Resource": (0x696442BE, 0xA72E, 0x4059, 0xBC, 0x79, 0x5B, 0x5C, 0x98, 0x04, 0x0F, 0xAD), - "IID_ID3D12RootSignature": (0xC54A6B66, 0x72DF, 0x4EE8, 0x8B, 0xE5, 0xA9, 0x46, 0xA1, 0x42, 0x92, 0x14), - "IID_ID3D12RootSignatureDeserializer": (0x34AB647B, 0x3CC8, 0x46AC, 0x84, 0x1B, 0xC0, 0x96, 0x56, 0x45, 0xC0, 0x46), - "IID_ID3D12Tools": (0x7071E1F0, 0xE84B, 0x4B33, 0x97, 0x4F, 0x12, 0xFA, 0x49, 0xDE, 0x65, 0xC5), - "IID_ID3D12VersionedRootSignatureDeserializer": (0x7F91CE67, 0x090C, 0x4BB7, 0xB7, 0x8E, 0xED, 0x8F, 0xF2, 0xE3, 0x1D, 0xA0), - "IID_ID3DDeviceContextState": (0x5C1E0D8A, 0x7C23, 0x48F9, 0x8C, 0x59, 0xA9, 0x29, 0x58, 0xCE, 0xFF, 0x11), - "IID_IDXGIAdapter": (0x2411E7E1, 0x12AC, 0x4CCF, 0xBD, 0x14, 0x97, 0x98, 0xE8, 0x53, 0x4D, 0xC0), - "IID_IDXGIAdapter1": (0x29038F61, 0x3839, 0x4626, 0x91, 0xFD, 0x08, 0x68, 0x79, 0x01, 0x1A, 0x05), - "IID_IDXGIAdapter2": (0x0AA1AE0A, 0xFA0E, 0x4B84, 0x86, 0x44, 0xE0, 0x5F, 0xF8, 0xE5, 0xAC, 0xB5), - "IID_IDXGIDevice": (0x54EC77FA, 0x1377, 0x44E6, 0x8C, 0x32, 0x88, 0xFD, 0x5F, 0x44, 0xC8, 0x4C), - "IID_IDXGIDevice1": (0x77DB970F, 0x6276, 0x48BA, 0xBA, 0x28, 0x07, 0x01, 0x43, 0xB4, 0x39, 0x2C), - "IID_IDXGIDevice2": (0x05008617, 0xFBFD, 0x4051, 0xA7, 0x90, 0x14, 0x48, 0x84, 0xB4, 0xF6, 0xA9), - "IID_IDXGIDeviceSubObject": (0x3D3E0379, 0xF9DE, 0x4D58, 0xBB, 0x6C, 0x18, 0xD6, 0x29, 0x92, 0xF1, 0xA6), - "IID_IDXGIFactory": (0x7B7166EC, 0x21C7, 0x44AE, 0xB2, 0x1A, 0xC9, 0xAE, 0x32, 0x1A, 0xE3, 0x69), - "IID_IDXGIFactory1": (0x770AAE78, 0xF26F, 0x4DBA, 0xA8, 0x29, 0x25, 0x3C, 0x83, 0xD1, 0xB3, 0x87), - "IID_IDXGIFactory2": (0x50C83A1C, 0xE072, 0x4C48, 0x87, 0xB0, 0x36, 0x30, 0xFA, 0x36, 0xA6, 0xD0), - "IID_IDXGIObject": (0xAEC22FB8, 0x76F3, 0x4639, 0x9B, 0xE0, 0x28, 0xEB, 0x43, 0xA6, 0x7A, 0x2E), - "IID_IDXGISwapChain": (0x310D36A0, 0xD2E7, 0x4C0A, 0xAA, 0x04, 0x6A, 0x9D, 0x23, 0xB8, 0x88, 0x6A), - "IID_IDXGISwapChain1": (0x790A45F7, 0x0D42, 0x4876, 0x98, 0x3A, 0x0A, 0x55, 0xCF, 0xE6, 0xF4, 0xAA), -} - -# The 10 console-only GUIDs, reported by SCARAB from the runtime's export table (doc section 4). -CONSOLE_IIDS = { - "IID_ID3D11CounterSampleX": (0x806CEEE4, 0x280B, 0x43D9, 0x90, 0x08, 0xB4, 0xFD, 0xF7, 0xFE, 0xBE, 0xE2), - "IID_ID3D11CounterSetX": (0xF9F6A732, 0xC5F8, 0x4A57, 0xBA, 0x36, 0xEA, 0xE7, 0xC2, 0x7B, 0xA7, 0x4A), - "IID_ID3D11DeviceContextX": (0x48800095, 0x7134, 0x4BE7, 0x91, 0x86, 0xB8, 0x6B, 0xEC, 0xB2, 0x64, 0x77), - "IID_ID3D11DeviceX": (0x177700F9, 0x876A, 0x4436, 0xB3, 0x68, 0x36, 0xA6, 0x04, 0xF8, 0x2C, 0xEF), - "IID_ID3D11DmaEngineContextX": (0xA6332DDB, 0x8E02, 0x427D, 0xB0, 0xB7, 0x34, 0xA1, 0xE6, 0x1A, 0x64, 0x88), - "IID_ID3D11PerformanceContextX": (0x9458FE06, 0xC78D, 0x47F7, 0x96, 0xA0, 0xEC, 0x7B, 0x72, 0x7B, 0xE1, 0xE9), - "IID_ID3D11PerformanceDeviceX": (0x88671610, 0x712E, 0x4F1E, 0x84, 0xAB, 0x01, 0xB5, 0x94, 0x8B, 0xD3, 0x73), - "IID_ID3D11UserDefinedAnnotationX": (0xB2DAAD8B, 0x03D4, 0x4DBF, 0x95, 0xEB, 0x32, 0xAB, 0x4B, 0x63, 0xD0, 0xAB), - "IID_ID3D12ConsDmaCommandList": (0x30BC77B9, 0x8379, 0x4B25, 0x95, 0xDE, 0xB8, 0x58, 0x8C, 0x42, 0x27, 0x5D), - "IID_IGraphicsUnknown": (0xACEEEA63, 0xE0A9, 0x4A1C, 0xBB, 0xEC, 0x71, 0xB2, 0xF4, 0x85, 0xF7, 0x58), -} - -# The four console command-list interfaces whose IIDs SCARAB reports as not exported and not -# recovered (doc section 4). The local tables must not assign a value; a title trace is one -# possible future source. They must stay out of DATA_EXPORTS and CONSOLE_IIDS. -UNRECOVERED_CONSOLE_IIDS = ( - "ID3D12ConsComputeCommandList", - "ID3D12ConsComputeCommandList6", - "ID3D12ConsComputeCommandList8", - "ID3D12ConsCopyCommandList6", -) - -# The 11 catalogue rows labelled "method" that are not interface methods (doc section 5). -CATALOGUE_NON_METHODS = { - "UINT_MAX", - "UINT64_MAX", - "DXGI_DEBUG_DX", - "D3D12_MESSAGE_ID_INVALID_NODE_INDEX", - "D3D12CONS_PRESENT_PLANES_MAX", - "D3D12CONS_PRESENT_VIEWS_MAX", - "UMDInternalDriverCallX", - "WorldRayOriginX", - "WorldRayDirectionX", - "DispatchRaysDimensionsX", - "TopLeftX", -} - -SDK_NOTE = "Windows SDK 10.0.26100.0" - - -def guid_text(g): - """RFC 4122 text form, for messages and the markdown table.""" - return "%08x-%04x-%04x-%02x%02x-%02x%02x%02x%02x%02x%02x" % g - - -def guid_version(g): - return (g[2] >> 12) & 0xF - - -def all_slots(): - """The 116 (ordinal, name, kind) rows, functions first.""" - return [(n, name, kind) for n, name, kind in FUNCTION_EXPORTS] + [ - (n, name, kind) for n, name, kind, _ev in DATA_EXPORTS - ] - - -def check_slots(): - errors = [] - slots = all_slots() - if len(slots) != 116: - errors.append("expected 116 slots, got %d" % len(slots)) - if len(FUNCTION_EXPORTS) != 23: - errors.append("expected 23 function exports, got %d" % len(FUNCTION_EXPORTS)) - if len(DATA_EXPORTS) != 93: - errors.append("expected 93 data exports, got %d" % len(DATA_EXPORTS)) - ordinals = sorted(n for n, _name, _kind in slots) - if ordinals != list(range(1, 117)): - missing = sorted(set(range(1, 117)) - set(ordinals)) - dupes = sorted({n for n in ordinals if ordinals.count(n) > 1}) - errors.append("ordinals are not 1..116 (missing=%s duplicates=%s)" % (missing, dupes)) - names = [name for _n, name, _kind in slots] - if len(names) != len(set(names)): - errors.append("duplicate export names") - # Exactly the function ordinals are 1..22 and 116; the data block is 23..115. - func_ord = {n for n, _name, _kind in FUNCTION_EXPORTS} - if func_ord != set(range(1, 23)) | {116}: - errors.append("function ordinals are not 1..22 plus 116") - if sum(1 for _n, _name, kind in FUNCTION_EXPORTS if kind == "standard") != 7: - errors.append("expected 7 standard (PC-shared) function exports, got %d" - % sum(1 for _n, _name, kind in FUNCTION_EXPORTS if kind == "standard")) - if sum(1 for _n, _name, kind in FUNCTION_EXPORTS if kind == "console") != 16: - errors.append("expected 16 console-only function exports, got %d" - % sum(1 for _n, _name, kind in FUNCTION_EXPORTS if kind == "console")) - return errors - - -def check_data_classes(): - errors = [] - standard = {name for _n, name, kind, _ev in DATA_EXPORTS if kind != "console"} - console = {name for _n, name, kind, _ev in DATA_EXPORTS if kind == "console"} - if standard != set(STANDARD_GUIDS): - errors.append("standard data names do not equal STANDARD_GUIDS (%d vs %d)" - % (len(standard), len(STANDARD_GUIDS))) - if console != set(CONSOLE_IIDS): - errors.append("console data names do not equal CONSOLE_IIDS (%d vs %d)" - % (len(console), len(CONSOLE_IIDS))) - if len(STANDARD_GUIDS) != 83: - errors.append("expected 83 standard GUIDs, got %d" % len(STANDARD_GUIDS)) - if len(CONSOLE_IIDS) != 10: - errors.append("expected 10 console GUIDs, got %d" % len(CONSOLE_IIDS)) - # IID ordinals are 28..115 and exactly the 88 names in the block. - iid_ord = {n for n, name, _kind, _ev in DATA_EXPORTS if name.startswith("IID_")} - if iid_ord != set(range(28, 116)): - errors.append("IID ordinals are not 28..115") - return errors - - -def check_guid_values(): - errors = [] - values = list(STANDARD_GUIDS.values()) + list(CONSOLE_IIDS.values()) - if len(values) != len({tuple(v) for v in values}): - errors.append("duplicate GUID value across the standard and console tables") - if set(STANDARD_GUIDS) & set(CONSOLE_IIDS): - errors.append("a GUID name is in both the standard and console tables") - for name, g in list(STANDARD_GUIDS.items()) + list(CONSOLE_IIDS.items()): - if len(g) != 11: - errors.append("%s: expected 11 components, got %d" % (name, len(g))) - continue - if g[0] > 0xFFFFFFFF or g[1] > 0xFFFF or g[2] > 0xFFFF or any(x > 0xFF for x in g[3:]): - errors.append("%s: component out of range" % name) - if guid_version(g) != 4: - errors.append("%s: not an RFC 4122 version 4 UUID" % name) - return errors - - -def check_unrecovered_console_iids(): - """The four unresolved command-list IIDs are absent from the local export table and CONSOLE_IIDS; the - vendor-runtime observation is SCARAB's.""" - errors = [] - export_names = {name for _n, name, _kind, _ev in DATA_EXPORTS} - for interface in UNRECOVERED_CONSOLE_IIDS: - for name in (interface, "IID_" + interface): - if name in export_names: - errors.append("%s must not be assigned to the 93-GUID export table" % name) - if name in CONSOLE_IIDS: - errors.append("%s must not be assigned a local GUID value" % name) - return errors - - -def check_iid_order(): - """The 88 IID names at 28..115 are alphabetical, except the DMA IID pinned at 100.""" - errors = [] - iids = [(n, name) for n, name, _kind, _ev in DATA_EXPORTS if name.startswith("IID_")] - pinned = [x for x in iids if x[1] == "IID_ID3D12ConsDmaCommandList"] - if len(pinned) != 1 or pinned[0][0] != 100: - errors.append("IID_ID3D12ConsDmaCommandList is not pinned at 100") - rest = [name for n, name in iids if name != "IID_ID3D12ConsDmaCommandList"] - if rest != sorted(rest): - errors.append("the IID block (excluding the DMA IID) is not alphabetical") - return errors - - -def find_sdk_include(): - """Return (um_dir, shared_dir) for the newest installed Windows SDK, or (None, None).""" - env = os.environ.get("WINDOWS_SDK_INCLUDE") or os.environ.get("SDK_INCLUDE") - if env: - candidates = [env] - else: - candidates = [] - for var in ("ProgramFiles(x86)", "ProgramFiles"): - root = os.environ.get(var) - if root: - candidates += glob.glob(os.path.join(root, "Windows Kits", "10", "Include", "*")) - - best = None - for path in candidates: - path = os.path.normpath(path) # "...\um\" has an empty basename - um = path if os.path.basename(path).lower() == "um" else os.path.join(path, "um") - shared = os.path.join(os.path.dirname(um), "shared") - if os.path.isdir(um): - name = os.path.basename(os.path.dirname(um)) - try: - key = (1, tuple(map(int, name.split(".")))) - except ValueError: - key = (0, name) - if best is None or key > best[0]: - best = (key, um, shared) - if not best: - return None, None - return best[1], best[2] - - -def parse_sdk_guids(um_dir, shared_dir): - """name -> 11-tuple for every DEFINE_GUID in the SDK's um/ and shared/ headers.""" - found = {} - for d in (um_dir, shared_dir): - if not d or not os.path.isdir(d): - continue - for path in glob.glob(os.path.join(d, "*.h")): - try: - with open(path, encoding="utf-8", errors="replace") as f: - text = f.read() - except OSError: - continue - for m in re.finditer(r"DEFINE_GUID\(\s*((?:IID|DXGI_DEBUG)_[A-Za-z0-9_]+)\s*,\s*([^)]*)\)", text): - nums = [] - for part in m.group(2).split(","): - part = part.strip().rstrip("LlUu") - try: - nums.append(int(part, 16)) - except ValueError: - nums = None - break - if nums and len(nums) == 11: - found.setdefault(m.group(1), tuple(nums)) - return found - - -def check_sdk(): - """Return (errors, checked_count, um_dir). checked_count is 0 when the SDK is missing.""" - um, shared = find_sdk_include() - if not um: - return [], 0, None - sdk = parse_sdk_guids(um, shared) - errors = [] - checked = 0 - for name, g in STANDARD_GUIDS.items(): - if name not in sdk: - errors.append("%s: not found in the SDK headers" % name) - continue - checked += 1 - if sdk[name] != g: - errors.append("%s: table %s != SDK %s" % (name, guid_text(g), guid_text(sdk[name]))) - for name in CONSOLE_IIDS: - if name in sdk: - errors.append("%s: expected a console-only IID, but the SDK defines it" % name) - return errors, checked, um - - -def parse_scarab_iid_table(path): - with open(path, encoding="utf-8") as f: - text = f.read() - out = {} - for name, body in re.findall(r"GUID\s+((?:IID|DXGI_DEBUG)_[A-Za-z0-9_]+)\s*=\s*\{([^;]*)\};", text): - nums = tuple(int(x, 16) for x in re.findall(r"0x([0-9A-Fa-f]+)", body)) - if len(nums) == 11: - out[name] = nums - return out - - -def parse_scarab_iid_console(path): - with open(path, encoding="utf-8") as f: - text = f.read() - out = {} - for m in re.finditer(r"GUID\s+(IID_[A-Za-z0-9_]+).*?ordinal\s+(\d+)", text): - out[m.group(1)] = int(m.group(2)) - return out - - -def parse_scarab_catalogue(path): - rows = [] - with open(path, encoding="utf-8") as fh: - header = fh.readline() - for line in fh: - parts = line.rstrip("\n").split("\t") - if len(parts) >= 3: - rows.append(tuple(parts[:3])) - return rows - - -def check_scarab(root): - """Cross-check the table against a SCARAB checkout. Returns (errors, notes).""" - errors = [] - notes = [] - iid_table = os.path.join(root, "components", "runtime-bridge", "src", "iid_table.cpp") - iid_console = os.path.join(root, "components", "extension-wrapper", "src", "iid_console.inc") - catalogue = os.path.join(root, "components", "extension-wrapper", "docs", - "console-extension-catalogue.tsv") - if os.path.exists(iid_table): - theirs = parse_scarab_iid_table(iid_table) - mine = dict(STANDARD_GUIDS) - mine.update(CONSOLE_IIDS) - if set(theirs) != set(mine): - errors.append("SCARAB iid_table names differ from this table") - for name in sorted(set(theirs) & set(mine)): - if theirs[name] != mine[name]: - errors.append("%s: SCARAB %s != table %s" - % (name, guid_text(theirs[name]), guid_text(mine[name]))) - notes.append("iid_table.cpp: %d GUID values compared" % len(theirs)) - else: - errors.append("missing %s" % iid_table) - if os.path.exists(iid_console): - theirs = parse_scarab_iid_console(iid_console) - known = {name for _n, name, _kind, _ev in DATA_EXPORTS} - unexpected = set(theirs) - known - if unexpected: - errors.append("iid_console.inc has names not in the table: %s" % sorted(unexpected)) - mine = {name: n for n, name, _kind, _ev in DATA_EXPORTS - if name in theirs} - for name in sorted(set(theirs) & set(mine)): - if theirs[name] != mine[name]: - errors.append("%s: SCARAB ordinal %d != table %d" - % (name, theirs[name], mine[name])) - notes.append("iid_console.inc: %d documented ordinals compared" % len(set(theirs) & set(mine))) - else: - errors.append("missing %s" % iid_console) - if os.path.exists(catalogue): - rows = parse_scarab_catalogue(catalogue) - methods = [r for r in rows if r[0] == "method"] - enums = [r for r in rows if r[0] == "enum"] - notes.append("catalogue: %d method rows, %d enum rows" % (len(methods), len(enums))) - if (len(methods), len(enums)) != (105, 106): - notes.append("catalogue counts changed since the pin (expected 105/106)") - present = {r[1] for r in methods} - missing = sorted(CATALOGUE_NON_METHODS - present) - if missing: - errors.append("catalogue non-method rows missing: %s" % missing) - else: - errors.append("missing %s" % catalogue) - return errors, notes - - -def markdown_table(): - """The 116-row table used in the doc, for maintenance.""" - lines = ["| # | export | kind | evidence |", "|---:|---|---|---|"] - for n, name, kind in FUNCTION_EXPORTS: - lines.append("| %d | `%s` | %s | documented |" % (n, name, kind)) - for n, name, kind, ev in DATA_EXPORTS: - lines.append("| %d | `%s` | %s | %s |" % (n, name, kind, ev)) - return "\n".join(lines) - - -def main(argv=None): - ap = argparse.ArgumentParser(description=__doc__.splitlines()[0]) - ap.add_argument("--check", action="store_true", help="run the invariant checks") - ap.add_argument("--sdk", action="store_true", help="also check the 83 standard GUIDs against the SDK") - ap.add_argument("--require-sdk", action="store_true", help="fail if the SDK is not found") - ap.add_argument("--scarab", metavar="PATH", help="also cross-check a SCARAB checkout") - ap.add_argument("--markdown", action="store_true", help="print the 116-row table") - args = ap.parse_args(argv) - - if args.markdown: - print(markdown_table()) - return 0 - - errors = [] - errors += check_slots() - errors += check_data_classes() - errors += check_guid_values() - errors += check_iid_order() - errors += check_unrecovered_console_iids() - - sdk_checked = 0 - if args.sdk or args.require_sdk: - sdk_errors, sdk_checked, um = check_sdk() - errors += sdk_errors - if sdk_checked: - print("sdk: %d/%d standard GUIDs match %s" % (sdk_checked, len(STANDARD_GUIDS), um)) - elif args.require_sdk: - errors.append("Windows SDK headers not found") - else: - print("sdk: SKIP (Windows SDK headers not found)") - - if args.scarab: - scarab_errors, notes = check_scarab(args.scarab) - errors += scarab_errors - for note in notes: - print("scarab: " + note) - - if errors: - for e in errors: - print("FAIL: " + e) - return 1 - if args.check or args.sdk or args.scarab: - print("PASS: 116 slots (23 functions + 93 GUID data), %d standard + %d console GUIDs, " - "%d unresolved command-list IIDs absent from local tables" - % (len(STANDARD_GUIDS), len(CONSOLE_IIDS), len(UNRECOVERED_CONSOLE_IIDS))) - return 0 - - -if __name__ == "__main__": - try: # a redirected stdout is strict ANSI code page under -I; write '?' for what it cannot encode - sys.stdout.reconfigure(errors="replace") - except (AttributeError, ValueError, OSError): - pass - sys.exit(main()) diff --git a/tools/dds_png.py b/tools/dds_png.py deleted file mode 100644 index dd59d7545..000000000 --- a/tools/dds_png.py +++ /dev/null @@ -1,1553 +0,0 @@ -"""Pure standard-library DDS to PNG decoder and 2x box-filter downscaler. - -Supports legacy and DX10 DDS headers across uncompressed 32-bit formats -(BGRA8, RGBA8, BGRX8, RGBX8, R10G10B10A2_UNORM, and arbitrary 32-bit RGB/RGBA bitmasks), the -legacy 24-bit RGB layouts (BGR8/RGB8, e.g. the D3DFMT_R8G8B8 byte order), -and block-compressed formats (BC1, BC2, BC3, BC4, BC5, BC7). - -BC7 covers all eight modes. Decoding DXGI 97/98/99 (typeless, UNORM, UNORM_SRGB) -preserves the stored RGBA8 values. The reserved mode (no mode bit in the first -byte) decodes as transparent black. BC6H is not supported. -DXT2, DXT4 and premultiplied DX10 images are converted to straight alpha for PNG. -For tagged sRGB images, unpremultiplication and downscaling use linear light. The PNG stores sRGB bytes. - -DX10 R16_FLOAT (54), R32_FLOAT (41) and R16G16B16A16_FLOAT (10) are read as linear values and -written like the UNORM formats, with no tone mapping or sRGB transfer: clamp to -[0, 1], then round(v * 255) half up. +inf saturates to 255; -inf, negative values -and NaN map to 0. The single-channel formats fill red, with green and blue 0 and alpha 255; -R16G16B16A16_FLOAT keeps its own alpha. -R11G11B10_FLOAT previews clamp RGB to [0, 1], map NaN to zero and use opaque alpha. - -Usage: - python -I tools/dds_png.py --info - python -I tools/dds_png.py [--mip N] [--layer N] [--face px] [--z N] [--max-size N] -""" -from __future__ import annotations - -import argparse -from bisect import bisect_right -from functools import cache -import json -import math -import os -import shutil -import struct -import sys -import tempfile -from typing import BinaryIO, NamedTuple, TypedDict -import zlib - -_TOOLS_DIR = os.path.dirname(os.path.abspath(__file__)) -if _TOOLS_DIR not in sys.path: - sys.path.insert(0, _TOOLS_DIR) -import bcpack_tables_bptc as _bptc # noqa: E402 - -DDS_MAGIC = b"DDS " -DDS_HEADER_SIZE = 128 -DDS_DX10_HEADER_SIZE = 148 -DDSD_PITCH = 0x8 -DDSD_DEPTH = 0x800000 -DDSCAPS2_CUBEMAP = 0x200 -DDSCAPS2_VOLUME = 0x200000 -_CUBE_FACES = ("px", "nx", "py", "ny", "pz", "nz") -DDS_ALPHA_MODE_MASK = 0x7 -DDS_ALPHA_MODE_PREMULTIPLIED = 2 -DDS_ALPHA_MODE_OPAQUE = 3 - -DDPF_ALPHAPIXELS = 0x1 -DDPF_FOURCC = 0x4 -DDPF_RGB = 0x40 - -PNG_SIGNATURE = b"\x89PNG\r\n\x1a\n" - -_FOURCC_MAP: dict[bytes, str] = { - b"DXT1": "BC1", - b"DXT2": "BC2", - b"DXT3": "BC2", - b"DXT4": "BC3", - b"DXT5": "BC3", - b"ATI1": "BC4", - b"BC4U": "BC4", - b"BC4S": "BC4_SNORM", - b"ATI2": "BC5", - b"BC5U": "BC5", - b"BC5S": "BC5_SNORM", -} - -_DXGI_MAP: dict[int, str] = { - # Typeless byte formats use the same channel layout as their UNORM variants. - 27: "RGBA8", - 28: "RGBA8", - 29: "RGBA8", - 87: "BGRA8", - 90: "BGRA8", - 91: "BGRA8", - 88: "BGRX8", - 92: "BGRX8", - 93: "BGRX8", - 26: "R11G11B10_FLOAT", - 41: "R32_FLOAT", - 56: "R16_UNORM", - 65: "A8_UNORM", - 70: "BC1", - 71: "BC1", - 72: "BC1", - 73: "BC2", - 74: "BC2", - 75: "BC2", - 76: "BC3", - 77: "BC3", - 78: "BC3", - 79: "BC4", - 80: "BC4", - 81: "BC4_SNORM", - 82: "BC5", - 83: "BC5", - 84: "BC5_SNORM", - 97: "BC7", - 98: "BC7", - 99: "BC7", - 10: "RGBA16_FLOAT", - 54: "R16_FLOAT", -} - -# Bytes per texel and channels per texel of the half-float formats. -_HALF_FLOAT_LAYOUT = {"RGBA16_FLOAT": (8, 4), "R16_FLOAT": (2, 1)} -_HALF_TO_U8: bytes | None = None - -_SRGB_DXGI_FORMATS = frozenset((29, 72, 75, 78, 91, 93, 99)) - - -def _srgb_byte_to_linear(value: float) -> float: - # Use the intensity of sRGB byte 1 as the unit so half-byte ties on the linear segment are exact. - if value <= 0.04045 * 255: - return value - return ((value / 255.0 + 0.055) / 1.055) ** 2.4 * (255 * 12.92) - - -_SRGB_TO_LINEAR = tuple(_srgb_byte_to_linear(v) for v in range(256)) -# Crossing the linear intensity of encoded value n + 0.5 rounds the output up to byte n + 1. -_SRGB_HALF_STEPS = tuple(_srgb_byte_to_linear(v + 0.5) for v in range(255)) - -_CANONICAL_MASKS: dict[tuple[int, int, int, int], str] = { - (0x00FF0000, 0x0000FF00, 0x000000FF, 0xFF000000): "BGRA8", - (0x00FF0000, 0x0000FF00, 0x000000FF, 0x00000000): "BGRX8", - (0x000000FF, 0x0000FF00, 0x00FF0000, 0xFF000000): "RGBA8", - (0x000000FF, 0x0000FF00, 0x00FF0000, 0x00000000): "RGBX8", -} - -# Legacy 24-bit RGB layouts: channel letters in stored byte order (D3DFMT_R8G8B8 -# stores B, G, R; alpha is absent, so decoded pixels are opaque). -_RGB24_LAYOUTS: dict[tuple[int, int, int, int], str] = { - (0x00FF0000, 0x0000FF00, 0x000000FF, 0x00000000): "BGR8", - (0x000000FF, 0x0000FF00, 0x00FF0000, 0x00000000): "RGB8", -} - -_R5_TO_8 = tuple((i << 3) | (i >> 2) for i in range(32)) -_G6_TO_8 = tuple((i << 2) | (i >> 4) for i in range(64)) - -_UNPACK_BC1 = struct.Struct(" 8-bit value by MSB replication. -_BC7_UNQUANTIZE = { - prec: bytes((v << (8 - prec)) | (v >> (2 * prec - 8)) for v in range(1 << prec)) - for prec in range(5, 9) -} -# Output byte for interpolated R, G, B, A under rotation 0-3 (A swaps with R, G or B). -_BC7_ROTATIONS = ((0, 1, 2, 3), (3, 1, 2, 0), (0, 3, 2, 1), (0, 1, 3, 2)) -_BC7_RESERVED_BLOCK = bytes(64) -_BC7_BLOCK_CACHE_LIMIT = 4096 - - -def _bc7_partition_layouts() -> tuple: - """Per subset count, each partition's (subset of pixel, pixel is anchor) tuples.""" - - def layout(subset_of, anchors): - return tuple(subset_of), tuple(int(p in anchors) for p in range(16)) - - two = tuple( - layout(((mask >> p) & 1 for p in range(16)), (0, anchor)) - for mask, anchor in zip(_bptc.BC7_PART2_PACKED, _bptc.BC7_ANCHOR2) - ) - three = tuple( - layout(((mask >> (2 * p)) & 3 for p in range(16)), (0, anchor_a, anchor_b)) - for mask, anchor_a, anchor_b in zip( - _bptc.BC7_PART3_PACKED, _bptc.BC7_ANCHOR3A, _bptc.BC7_ANCHOR3B - ) - ) - return (None, (layout((0,) * 16, (0,)),), two, three) - - -_BC7_LAYOUTS = _bc7_partition_layouts() - - -class DdsError(ValueError): - """Raised when DDS header or payload data is invalid or unsupported.""" - - -def _validate_mask(mask: int) -> tuple[int, int]: - """Return (shift, max_value) for a contiguous 32-bit bitmask, or (0, 0) if zero.""" - if mask == 0: - return 0, 0 - shift = (mask & -mask).bit_length() - 1 - max_val = mask >> shift - if (max_val & (max_val + 1)) != 0: - raise DdsError(f"Non-contiguous channel bitmask: 0x{mask:08X}") - return shift, max_val - - -class _DdsHeader(TypedDict): - width: int - height: int - depth: int - dimension: str - array_size: int - faces: tuple[str, ...] - format: str - dxgi_format: int | None - mip_count: int - pitch: int - data_offset: int - - -def _parse_header_internal( - data: bytes | bytearray | memoryview, -) -> tuple[_DdsHeader, tuple[int, int, int, int] | None, int]: - if not isinstance(data, (bytes, bytearray, memoryview)): - raise DdsError(f"Expected bytes-like object, got {type(data).__name__}") - if len(data) < DDS_HEADER_SIZE: - raise DdsError(f"DDS header too short: {len(data)} bytes (need at least {DDS_HEADER_SIZE})") - if bytes(data[:4]) != DDS_MAGIC: - raise DdsError(f"Invalid DDS magic: {bytes(data[:4])!r}") - - flags, height, width, pitch, raw_depth, raw_mips = struct.unpack_from("<6I", data, 8) - if width <= 0 or height <= 0: - raise DdsError(f"Invalid DDS dimensions: {width}x{height}") - - mip_count = raw_mips if raw_mips > 0 else 1 - - pf_flags, fourcc, rgb_bit_count, r_mask, g_mask, b_mask, a_mask = struct.unpack_from( - " max(width, height, depth).bit_length(): - raise DdsError(f"Too many DDS mip levels ({mip_count}) for {width}x{height}x{depth}") - - info: _DdsHeader = { - "width": width, - "height": height, - "depth": depth, - "dimension": dimension, - "array_size": array_size, - "faces": faces, - "format": fmt, - "dxgi_format": dxgi_format, - "mip_count": mip_count, - "data_offset": data_offset, - "pitch": pitch if flags & DDSD_PITCH else 0, - } - return info, masks, alpha_mode - - -def parse_dds_header(data: bytes) -> _DdsHeader: - """Return format and shape metadata from a legacy or DX10 DDS header.""" - info, _, _ = _parse_header_internal(data) - return info - - -class _Plane(NamedTuple): - offset: int - width: int - height: int - row_pitch: int - byte_length: int - - -_TEXEL_BYTES = { - "RGBA8": 4, "BGRA8": 4, "BGRX8": 4, "RGBX8": 4, "R11G11B10_FLOAT": 4, - "BGR8": 3, "RGB8": 3, "R16_UNORM": 2, "A8_UNORM": 1, - "R32_FLOAT": 4, - **{fmt: layout[0] for fmt, layout in _HALF_FLOAT_LAYOUT.items()}, -} - - -def _locate_plane(info: _DdsHeader, *, mip: int = 0, layer: int = 0, - face: str | None = None, z: int = 0) -> _Plane: - """Locate one stored 2D plane without walking individual layers or depth slices.""" - for name, value, count in (("mip", mip, info["mip_count"]), ("layer", layer, info["array_size"])): - if type(value) is not int or not 0 <= value < count: - raise DdsError(f"DDS {name} must be in 0..{count - 1}, got {value!r}") - mip_depth = max(1, info["depth"] >> mip) - if type(z) is not int or not 0 <= z < mip_depth: - raise DdsError(f"DDS z must be in 0..{mip_depth - 1} at mip {mip}, got {z!r}") - - faces = info["faces"] - if face is not None and face not in faces: - raise DdsError(f"DDS does not contain face {face!r}") - image_index = layer - if faces: - image_index = layer * len(faces) + (faces.index(face) if face is not None else 0) - - fmt = info["format"] - if fmt.startswith("BC"): - block = 4 - unit_bytes = 8 if fmt in ("BC1", "BC4", "BC4_SNORM") else 16 - else: - block = 1 - unit_bytes = _TEXEL_BYTES[fmt] - - # Arrays and cubemaps store one complete mip chain per image. A volume - # instead stores all depth slices of each mip together. A header has at - # most 32 mip levels, irrespective of its declared array size or depth. - chain_bytes = 0 - for level in range(info["mip_count"]): - width = max(1, info["width"] >> level) - height = max(1, info["height"] >> level) - rows = (height + block - 1) // block - row_bytes = (width + block - 1) // block * unit_bytes - row_pitch = row_bytes - if level == 0 and block == 1 and info["pitch"]: - row_pitch = info["pitch"] - if row_pitch < row_bytes: - raise DdsError(f"Invalid {fmt} row pitch: {row_pitch} bytes (need at least {row_bytes})") - slice_bytes = rows * row_pitch - if level == mip: - # The next plane starts after full rows including padding. Decoding - # this plane only needs the visible bytes of its last row. - plane = _Plane(chain_bytes + z * slice_bytes, width, height, row_pitch, - slice_bytes - row_pitch + row_bytes) - chain_bytes += slice_bytes * max(1, info["depth"] >> level) - return plane._replace(offset=info["data_offset"] + image_index * chain_bytes + plane.offset) - - -def _decode_uncompressed_32( - payload: memoryview, - width: int, - height: int, - fmt: str, - masks: tuple[int, int, int, int] | None, - pitch: int, -) -> bytes: - pixel_count = width * height - row_bytes = width * 4 - pitch = pitch or row_bytes - if pitch < row_bytes: - raise DdsError(f"Invalid {fmt} row pitch: {pitch} bytes (need at least {row_bytes})") - expected = (height - 1) * pitch + row_bytes - if len(payload) < expected: - raise DdsError(f"Truncated {fmt} payload: {len(payload)} bytes (need {expected})") - - if pitch == row_bytes: - src = bytes(payload[:expected]) - else: - src = b"".join(payload[start : start + row_bytes] for start in range(0, height * pitch, pitch)) - - if masks is None or masks in _CANONICAL_MASKS: - if fmt == "RGBA8": - return src - if fmt == "RGBX8": - out = bytearray(src) - out[3::4] = b"\xff" * pixel_count - return bytes(out) - if fmt == "BGRA8": - out = bytearray(src) - out[0::4], out[2::4] = out[2::4], out[0::4] - return bytes(out) - if fmt == "BGRX8": - out = bytearray(src) - out[0::4], out[2::4] = out[2::4], out[0::4] - out[3::4] = b"\xff" * pixel_count - return bytes(out) - - assert masks is not None - r_shift, r_max = _validate_mask(masks[0]) - g_shift, g_max = _validate_mask(masks[1]) - b_shift, b_max = _validate_mask(masks[2]) - a_shift, a_max = _validate_mask(masks[3]) - - out = bytearray(len(src)) - # Fast path when all non-zero masks are byte-aligned 8-bit lanes. - if ( - (r_max in (0, 255) and (r_shift & 7) == 0) - and (g_max in (0, 255) and (g_shift & 7) == 0) - and (b_max in (0, 255) and (b_shift & 7) == 0) - and (a_max in (0, 255) and (a_shift & 7) == 0) - ): - if r_max: - out[0::4] = src[r_shift >> 3 :: 4] - if g_max: - out[1::4] = src[g_shift >> 3 :: 4] - if b_max: - out[2::4] = src[b_shift >> 3 :: 4] - if a_max: - out[3::4] = src[a_shift >> 3 :: 4] - else: - out[3::4] = b"\xff" * pixel_count - return bytes(out) - - # General bitmask fallback (e.g. R10G10B10A2). - r_half = r_max >> 1 - g_half = g_max >> 1 - b_half = b_max >> 1 - a_half = a_max >> 1 - dst = 0 - for (px,) in struct.iter_unpack("> r_shift) & r_max) * 255 + r_half) // r_max if r_max else 0 - out[dst + 1] = (((px >> g_shift) & g_max) * 255 + g_half) // g_max if g_max else 0 - out[dst + 2] = (((px >> b_shift) & b_max) * 255 + b_half) // b_max if b_max else 0 - out[dst + 3] = (((px >> a_shift) & a_max) * 255 + a_half) // a_max if a_max else 255 - dst += 4 - return bytes(out) - - -def _half_to_u8_lut() -> bytes: - """Byte for every IEEE 754 binary16 code: clamp to [0, 1], round half up; NaN -> 0, +inf -> 255.""" - global _HALF_TO_U8 - if _HALF_TO_U8 is None: - lut = bytearray(65536) - for code, (v,) in enumerate(struct.iter_unpack("= 1.0 else int(v * 255.0 + 0.5) # v * 255 is exact in a double - _HALF_TO_U8 = bytes(lut) - return _HALF_TO_U8 - - -def _decode_half_float(payload: memoryview, width: int, height: int, fmt: str, pitch: int) -> bytes: - texel_bytes, channels = _HALF_FLOAT_LAYOUT[fmt] - row_bytes = width * texel_bytes - pitch = pitch or row_bytes - if pitch < row_bytes: - raise DdsError(f"Invalid {fmt} row pitch: {pitch} bytes (need at least {row_bytes})") - expected = (height - 1) * pitch + row_bytes - if len(payload) < expected: - raise DdsError(f"Truncated {fmt} payload: {len(payload)} bytes (need {expected})") - - lut = _half_to_u8_lut() - row_count = width * channels - unpack_row = struct.Struct(f"<{row_count}H").unpack_from - out = bytearray(width * height * 4) - if channels == 1: - out[3::4] = b"\xff" * (width * height) - for y in range(height): - values = bytes(map(lut.__getitem__, unpack_row(payload, y * pitch))) - start = y * width * 4 - if channels == 4: - out[start : start + row_bytes // 2] = values - else: - out[start : start + width * 4 : 4] = values - return bytes(out) - - -def _decode_uncompressed_24( - payload: memoryview, - width: int, - height: int, - fmt: str, - masks: tuple[int, int, int, int], - pitch: int, -) -> bytes: - """Decode a legacy 24-bit RGB payload (one byte per channel, no alpha) to RGBA8.""" - pixel_count = width * height - row_bytes = width * 3 - pitch = pitch or row_bytes - if pitch < row_bytes: - raise DdsError(f"Invalid {fmt} row pitch: {pitch} bytes (need at least {row_bytes})") - expected = (height - 1) * pitch + row_bytes - if len(payload) < expected: - raise DdsError(f"Truncated {fmt} payload: {len(payload)} bytes (need {expected})") - - if pitch == row_bytes: - src = bytes(payload[:expected]) - else: - src = b"".join(payload[start : start + row_bytes] for start in range(0, height * pitch, pitch)) - - # The header validation pinned each mask to a byte-aligned 8-bit lane. - r_byte = _validate_mask(masks[0])[0] >> 3 - g_byte = _validate_mask(masks[1])[0] >> 3 - b_byte = _validate_mask(masks[2])[0] >> 3 - out = bytearray(pixel_count * 4) - out[0::4] = src[r_byte::3] - out[1::4] = src[g_byte::3] - out[2::4] = src[b_byte::3] - out[3::4] = b"\xff" * pixel_count - return bytes(out) - - -def _bc_interp_lut(v0: int, v1: int) -> tuple[int, int, int, int, int, int, int, int]: - """Build the 8-entry BC3-alpha / BC4 / BC5 unsigned interpolation table.""" - if v0 > v1: - return ( - v0, - v1, - (6 * v0 + v1 + 3) // 7, - (5 * v0 + 2 * v1 + 3) // 7, - (4 * v0 + 3 * v1 + 3) // 7, - (3 * v0 + 4 * v1 + 3) // 7, - (2 * v0 + 5 * v1 + 3) // 7, - (v0 + 6 * v1 + 3) // 7, - ) - return ( - v0, - v1, - (4 * v0 + v1 + 2) // 5, - (3 * v0 + 2 * v1 + 2) // 5, - (2 * v0 + 3 * v1 + 2) // 5, - (v0 + 4 * v1 + 2) // 5, - 0, - 255, - ) - - -def _bc_interp_lut_snorm(b0: int, b1: int) -> tuple[int, int, int, int, int, int, int, int]: - """Build the 8-entry BC4_SNORM / BC5_SNORM table mapped from [-1, 1] to [0, 255].""" - s0 = b0 - 256 if b0 >= 128 else b0 - s1 = b1 - 256 if b1 >= 128 else b1 - if s0 == -128: - s0 = -127 - if s1 == -128: - s1 = -127 - - def to_u8(v: float) -> int: - # Map [-127.0, 127.0] -> [0, 255] - return int(round((v / 127.0 * 0.5 + 0.5) * 255.0)) - - if s0 > s1: - return ( - to_u8(s0), - to_u8(s1), - to_u8((6 * s0 + s1) / 7.0), - to_u8((5 * s0 + 2 * s1) / 7.0), - to_u8((4 * s0 + 3 * s1) / 7.0), - to_u8((3 * s0 + 4 * s1) / 7.0), - to_u8((2 * s0 + 5 * s1) / 7.0), - to_u8((s0 + 6 * s1) / 7.0), - ) - return ( - to_u8(s0), - to_u8(s1), - to_u8((4 * s0 + s1) / 5.0), - to_u8((3 * s0 + 2 * s1) / 5.0), - to_u8((2 * s0 + 3 * s1) / 5.0), - to_u8((s0 + 4 * s1) / 5.0), - 0, - 255, - ) - - -def _bc5_z_direct(r: int, g: int) -> int: - nx = r / 127.5 - 1.0 - ny = g / 127.5 - 1.0 - return int(round((math.sqrt(max(0.0, 1.0 - nx * nx - ny * ny)) * 0.5 + 0.5) * 255)) - - -def _get_bc5_z_lut() -> bytes: - global _BC5_Z_LUT - if _BC5_Z_LUT is None: - norm = [i / 127.5 - 1.0 for i in range(256)] - norm_sq = [x * x for x in norm] - lut = bytearray(65536) - idx = 0 - for r in range(256): - rem_r = 1.0 - norm_sq[r] - for g in range(256): - rem = rem_r - norm_sq[g] - z = math.sqrt(rem) if rem > 0.0 else 0.0 - lut[idx] = int(round((z * 0.5 + 0.5) * 255)) - idx += 1 - _BC5_Z_LUT = bytes(lut) - return _BC5_Z_LUT - - -def _decode_bc1(data: bytes | bytearray | memoryview, offset: int, width: int, height: int) -> bytes: - blocks_x = (width + 3) // 4 - blocks_y = (height + 3) // 4 - expected = blocks_x * blocks_y * 8 - if len(data) - offset < expected: - raise DdsError(f"Truncated BC1 payload: {len(data) - offset} bytes (need {expected})") - - out = bytearray(width * height * 4) - row_stride = width * 4 - r5_tab = _R5_TO_8 - g6_tab = _G6_TO_8 - unpack = _UNPACK_BC1 - pos = offset - - for by in range(blocks_y): - py0 = by * 4 - max_y = height - py0 - if max_y > 4: - max_y = 4 - row_base = py0 * row_stride - - for bx in range(blocks_x): - c0, c1, bits = unpack(data, pos) - pos += 8 - - r0 = r5_tab[c0 >> 11] - g0 = g6_tab[(c0 >> 5) & 0x3F] - b0 = r5_tab[c0 & 0x1F] - r1 = r5_tab[c1 >> 11] - g1 = g6_tab[(c1 >> 5) & 0x3F] - b1 = r5_tab[c1 & 0x1F] - - if c0 > c1: - pal = ( - bytes((r0, g0, b0, 255)), - bytes((r1, g1, b1, 255)), - bytes(((2 * r0 + r1 + 1) // 3, (2 * g0 + g1 + 1) // 3, (2 * b0 + b1 + 1) // 3, 255)), - bytes(((r0 + 2 * r1 + 1) // 3, (g0 + 2 * g1 + 1) // 3, (b0 + 2 * b1 + 1) // 3, 255)), - ) - else: - pal = ( - bytes((r0, g0, b0, 255)), - bytes((r1, g1, b1, 255)), - bytes(((r0 + r1) >> 1, (g0 + g1) >> 1, (b0 + b1) >> 1, 255)), - b"\x00\x00\x00\x00", - ) - - px0 = bx * 4 - max_x = width - px0 - dst = row_base + px0 * 4 - if max_x >= 4: - for ty in range(max_y): - rb = (bits >> (ty * 8)) & 0xFF - out[dst : dst + 16] = ( - pal[rb & 3] + pal[(rb >> 2) & 3] + pal[(rb >> 4) & 3] + pal[rb >> 6] - ) - dst += row_stride - else: - for ty in range(max_y): - rb = (bits >> (ty * 8)) & 0xFF - d = dst - for tx in range(max_x): - out[d : d + 4] = pal[(rb >> (tx * 2)) & 3] - d += 4 - dst += row_stride - - return bytes(out) - - -def _decode_bc2(data: bytes | bytearray | memoryview, offset: int, width: int, height: int) -> bytes: - blocks_x = (width + 3) // 4 - blocks_y = (height + 3) // 4 - expected = blocks_x * blocks_y * 16 - if len(data) - offset < expected: - raise DdsError(f"Truncated BC2 payload: {len(data) - offset} bytes (need {expected})") - - out = bytearray(width * height * 4) - row_stride = width * 4 - r5_tab = _R5_TO_8 - g6_tab = _G6_TO_8 - unpack = _UNPACK_BC23 - pos = offset - - for by in range(blocks_y): - py0 = by * 4 - max_y = height - py0 - if max_y > 4: - max_y = 4 - row_base = py0 * row_stride - - for bx in range(blocks_x): - alpha_q, c0, c1, bits = unpack(data, pos) - pos += 16 - - r0 = r5_tab[c0 >> 11] - g0 = g6_tab[(c0 >> 5) & 0x3F] - b0 = r5_tab[c0 & 0x1F] - r1 = r5_tab[c1 >> 11] - g1 = g6_tab[(c1 >> 5) & 0x3F] - b1 = r5_tab[c1 & 0x1F] - rgb = ( - (r0, g0, b0), - (r1, g1, b1), - ((2 * r0 + r1 + 1) // 3, (2 * g0 + g1 + 1) // 3, (2 * b0 + b1 + 1) // 3), - ((r0 + 2 * r1 + 1) // 3, (g0 + 2 * g1 + 1) // 3, (b0 + 2 * b1 + 1) // 3), - ) - - px0 = bx * 4 - max_x = width - px0 - dst = row_base + px0 * 4 - if max_x >= 4: - for ty in range(max_y): - ar = (alpha_q >> (ty * 16)) & 0xFFFF - rb = (bits >> (ty * 8)) & 0xFF - p0 = rgb[rb & 3] - p1 = rgb[(rb >> 2) & 3] - p2 = rgb[(rb >> 4) & 3] - p3 = rgb[rb >> 6] - out[dst : dst + 16] = bytes(( - p0[0], p0[1], p0[2], (ar & 0xF) * 17, - p1[0], p1[1], p1[2], ((ar >> 4) & 0xF) * 17, - p2[0], p2[1], p2[2], ((ar >> 8) & 0xF) * 17, - p3[0], p3[1], p3[2], (ar >> 12) * 17, - )) - dst += row_stride - else: - for ty in range(max_y): - ar = (alpha_q >> (ty * 16)) & 0xFFFF - rb = (bits >> (ty * 8)) & 0xFF - d = dst - for tx in range(max_x): - p = rgb[(rb >> (tx * 2)) & 3] - out[d] = p[0] - out[d + 1] = p[1] - out[d + 2] = p[2] - out[d + 3] = ((ar >> (tx * 4)) & 0xF) * 17 - d += 4 - dst += row_stride - - return bytes(out) - - -def _decode_bc3(data: bytes | bytearray | memoryview, offset: int, width: int, height: int) -> bytes: - blocks_x = (width + 3) // 4 - blocks_y = (height + 3) // 4 - expected = blocks_x * blocks_y * 16 - if len(data) - offset < expected: - raise DdsError(f"Truncated BC3 payload: {len(data) - offset} bytes (need {expected})") - - out = bytearray(width * height * 4) - row_stride = width * 4 - r5_tab = _R5_TO_8 - g6_tab = _G6_TO_8 - unpack = _UNPACK_BC23 - pos = offset - - for by in range(blocks_y): - py0 = by * 4 - max_y = height - py0 - if max_y > 4: - max_y = 4 - row_base = py0 * row_stride - - for bx in range(blocks_x): - alpha_q, c0, c1, bits = unpack(data, pos) - pos += 16 - - a_lut = _bc_interp_lut(alpha_q & 0xFF, (alpha_q >> 8) & 0xFF) - a_idx = alpha_q >> 16 - - r0 = r5_tab[c0 >> 11] - g0 = g6_tab[(c0 >> 5) & 0x3F] - b0 = r5_tab[c0 & 0x1F] - r1 = r5_tab[c1 >> 11] - g1 = g6_tab[(c1 >> 5) & 0x3F] - b1 = r5_tab[c1 & 0x1F] - rgb = ( - (r0, g0, b0), - (r1, g1, b1), - ((2 * r0 + r1 + 1) // 3, (2 * g0 + g1 + 1) // 3, (2 * b0 + b1 + 1) // 3), - ((r0 + 2 * r1 + 1) // 3, (g0 + 2 * g1 + 1) // 3, (b0 + 2 * b1 + 1) // 3), - ) - - px0 = bx * 4 - max_x = width - px0 - dst = row_base + px0 * 4 - if max_x >= 4: - for ty in range(max_y): - ar = (a_idx >> (ty * 12)) & 0xFFF - rb = (bits >> (ty * 8)) & 0xFF - p0 = rgb[rb & 3] - p1 = rgb[(rb >> 2) & 3] - p2 = rgb[(rb >> 4) & 3] - p3 = rgb[rb >> 6] - out[dst : dst + 16] = bytes(( - p0[0], p0[1], p0[2], a_lut[ar & 7], - p1[0], p1[1], p1[2], a_lut[(ar >> 3) & 7], - p2[0], p2[1], p2[2], a_lut[(ar >> 6) & 7], - p3[0], p3[1], p3[2], a_lut[ar >> 9], - )) - dst += row_stride - else: - for ty in range(max_y): - ar = (a_idx >> (ty * 12)) & 0xFFF - rb = (bits >> (ty * 8)) & 0xFF - d = dst - for tx in range(max_x): - p = rgb[(rb >> (tx * 2)) & 3] - out[d] = p[0] - out[d + 1] = p[1] - out[d + 2] = p[2] - out[d + 3] = a_lut[(ar >> (tx * 3)) & 7] - d += 4 - dst += row_stride - - return bytes(out) - - -def _decode_bc4( - data: bytes | bytearray | memoryview, - offset: int, - width: int, - height: int, - *, - signed: bool = False, -) -> bytes: - blocks_x = (width + 3) // 4 - blocks_y = (height + 3) // 4 - expected = blocks_x * blocks_y * 8 - if len(data) - offset < expected: - raise DdsError(f"Truncated BC4 payload: {len(data) - offset} bytes (need {expected})") - - out = bytearray(width * height * 4) - row_stride = width * 4 - unpack = _UNPACK_BC4 - lut_fn = _bc_interp_lut_snorm if signed else _bc_interp_lut - pos = offset - - for by in range(blocks_y): - py0 = by * 4 - max_y = height - py0 - if max_y > 4: - max_y = 4 - row_base = py0 * row_stride - - for bx in range(blocks_x): - (rq,) = unpack(data, pos) - pos += 8 - - r_lut = lut_fn(rq & 0xFF, (rq >> 8) & 0xFF) - px = tuple(bytes((v, v, v, 255)) for v in r_lut) - r_idx = rq >> 16 - - px0 = bx * 4 - max_x = width - px0 - dst = row_base + px0 * 4 - if max_x >= 4: - for ty in range(max_y): - rr = (r_idx >> (ty * 12)) & 0xFFF - out[dst : dst + 16] = ( - px[rr & 7] + px[(rr >> 3) & 7] + px[(rr >> 6) & 7] + px[rr >> 9] - ) - dst += row_stride - else: - for ty in range(max_y): - rr = (r_idx >> (ty * 12)) & 0xFFF - d = dst - for tx in range(max_x): - out[d : d + 4] = px[(rr >> (tx * 3)) & 7] - d += 4 - dst += row_stride - - return bytes(out) - - -def _decode_bc5( - data: bytes | bytearray | memoryview, - offset: int, - width: int, - height: int, - *, - signed: bool = False, -) -> bytes: - blocks_x = (width + 3) // 4 - blocks_y = (height + 3) // 4 - expected = blocks_x * blocks_y * 16 - if len(data) - offset < expected: - raise DdsError(f"Truncated BC5 payload: {len(data) - offset} bytes (need {expected})") - - out = bytearray(width * height * 4) - row_stride = width * 4 - unpack = _UNPACK_BC5 - lut_fn = _bc_interp_lut_snorm if signed else _bc_interp_lut - use_lut = width * height >= 4096 or _BC5_Z_LUT is not None - z_lut = _get_bc5_z_lut() if use_lut else None - pos = offset - - for by in range(blocks_y): - py0 = by * 4 - max_y = height - py0 - if max_y > 4: - max_y = 4 - row_base = py0 * row_stride - - for bx in range(blocks_x): - rq, gq = unpack(data, pos) - pos += 16 - - r_lut = lut_fn(rq & 0xFF, (rq >> 8) & 0xFF) - g_lut = lut_fn(gq & 0xFF, (gq >> 8) & 0xFF) - r_idx = rq >> 16 - g_idx = gq >> 16 - - px0 = bx * 4 - max_x = width - px0 - dst = row_base + px0 * 4 - if z_lut is not None and max_x >= 4: - for ty in range(max_y): - rr = (r_idx >> (ty * 12)) & 0xFFF - gr = (g_idx >> (ty * 12)) & 0xFFF - r0 = r_lut[rr & 7] - g0 = g_lut[gr & 7] - r1 = r_lut[(rr >> 3) & 7] - g1 = g_lut[(gr >> 3) & 7] - r2 = r_lut[(rr >> 6) & 7] - g2 = g_lut[(gr >> 6) & 7] - r3 = r_lut[rr >> 9] - g3 = g_lut[gr >> 9] - out[dst : dst + 16] = bytes(( - r0, g0, z_lut[(r0 << 8) | g0], 255, - r1, g1, z_lut[(r1 << 8) | g1], 255, - r2, g2, z_lut[(r2 << 8) | g2], 255, - r3, g3, z_lut[(r3 << 8) | g3], 255, - )) - dst += row_stride - else: - for ty in range(max_y): - rr = (r_idx >> (ty * 12)) & 0xFFF - gr = (g_idx >> (ty * 12)) & 0xFFF - d = dst - for tx in range(max_x): - r = r_lut[(rr >> (tx * 3)) & 7] - g = g_lut[(gr >> (tx * 3)) & 7] - z = z_lut[(r << 8) | g] if z_lut is not None else _bc5_z_direct(r, g) - out[d] = r - out[d + 1] = g - out[d + 2] = z - out[d + 3] = 255 - d += 4 - dst += row_stride - - return bytes(out) - - -@cache -def _unsigned_float_to_u8(mantissa_bits: int) -> bytes: - """Map a five-bit-exponent unsigned float channel to preview bytes.""" - table = bytearray(1 << (5 + mantissa_bits)) - fraction_mask = (1 << mantissa_bits) - 1 - for code in range(len(table)): - exponent = code >> mantissa_bits - fraction = code & fraction_mask - if exponent == 31: - table[code] = 0 if fraction else 255 - continue - significand = fraction + ((1 << mantissa_bits) if exponent else 0) - value = math.ldexp(significand, max(1, exponent) - 15 - mantissa_bits) - table[code] = int(min(1.0, value) * 255 + 0.5) - return bytes(table) - - -def _decode_r11g11b10(payload: memoryview, width: int, height: int, pitch: int) -> bytes: - row_bytes = width * 4 - pitch = pitch or row_bytes - if pitch < row_bytes: - raise DdsError(f"Invalid R11G11B10_FLOAT row pitch: {pitch} bytes (need at least {row_bytes})") - expected = (height - 1) * pitch + row_bytes - if len(payload) < expected: - raise DdsError(f"Truncated R11G11B10_FLOAT payload: {len(payload)} bytes (need {expected})") - - rg_table = _unsigned_float_to_u8(6) - b_table = _unsigned_float_to_u8(5) - rgba = bytearray(width * height * 4) - rgba[3::4] = b"\xff" * (width * height) - dst = 0 - for start in range(0, height * pitch, pitch): - for (pixel,) in struct.iter_unpack("> 11) & 0x7FF] - rgba[dst + 2] = b_table[pixel >> 22] - dst += 4 - return bytes(rgba) - - -def _decode_single_channel(payload: memoryview, width: int, height: int, pitch: int, fmt: str) -> bytes: - """Red-only R16_UNORM/R32_FLOAT and alpha-only A8_UNORM.""" - bpp = _TEXEL_BYTES[fmt] - row_bytes = width * bpp - pitch = pitch or row_bytes - if pitch < row_bytes: - raise DdsError(f"Invalid {fmt} row pitch: {pitch} bytes (need at least {row_bytes})") - expected = (height - 1) * pitch + row_bytes - if len(payload) < expected: - raise DdsError(f"Truncated {fmt} payload: {len(payload)} bytes (need {expected})") - - rgba = bytearray(width * height * 4) - if fmt != "A8_UNORM": - rgba[3::4] = b"\xff" * (width * height) - dst = 0 - for start in range(0, height * pitch, pitch): - row = payload[start:start + row_bytes] - if fmt == "R16_UNORM": - for (v,) in struct.iter_unpack("= 1: - rgba[dst] = 255 - elif v > 0: # Negative values and NaN leave red at zero. - rgba[dst] = int(v * 255 + 0.5) - dst += 4 - else: - rgba[dst + 3:dst + 4 * width:4] = row - dst += 4 * width - return bytes(rgba) - - -def _bc7_read_indices(bits: int, index_bits: int, is_anchor: tuple[int, ...]) -> tuple[list[int], int]: - """Read 16 LSB-first pixel indices; anchor pixels omit their implicit zero MSB.""" - indices = [] - for anchor in is_anchor: - width = index_bits - anchor - indices.append(bits & ((1 << width) - 1)) - bits >>= width - return indices, bits - - -def _decode_bc7_block(block: int) -> bytes: - """Decode one little-endian 128-bit BC7 block to 64 bytes of row-major RGBA8.""" - if not block & 0xFF: - return _BC7_RESERVED_BLOCK - mode = (block & -block).bit_length() - 1 - (subsets, partition_bits, rotation_bits, selector_bits, color_bits, alpha_bits, - endpoint_pbits, shared_pbits, index_bits, index2_bits) = _BC7_MODES[mode] - - # Fields are LSB-first: mode, partition, rotation, index selector, endpoints, - # p-bits, then the index set(s). - bits = block >> (mode + 1) - partition = bits & ((1 << partition_bits) - 1) - bits >>= partition_bits - rotation = bits & ((1 << rotation_bits) - 1) - bits >>= rotation_bits - selector = bits & ((1 << selector_bits) - 1) - bits >>= selector_bits - - # All R endpoints, then all G, B and A, each ordered subset 0 end 0, subset 0 end 1, ... - endpoint_count = 2 * subsets - channel_bits = (color_bits,) * 3 + ((alpha_bits,) if alpha_bits else ()) - raw_channels = [] - for width in channel_bits: - mask = (1 << width) - 1 - values = [] - for _ in range(endpoint_count): - values.append(bits & mask) - bits >>= width - raw_channels.append(values) - - if endpoint_pbits: - pbits = [(bits >> e) & 1 for e in range(endpoint_count)] - bits >>= endpoint_count - elif shared_pbits: - pbits = [(bits >> (e >> 1)) & 1 for e in range(endpoint_count)] - bits >>= subsets - else: - pbits = None - - endpoints = [] - for width, values in zip(channel_bits, raw_channels): - if pbits is not None: - values = [(v << 1) | p for v, p in zip(values, pbits)] - width += 1 - unquantize = _BC7_UNQUANTIZE[width] - endpoints.append([unquantize[v] for v in values]) - - subset_of, is_anchor = _BC7_LAYOUTS[subsets][partition] - color_indices, bits = _bc7_read_indices(bits, index_bits, is_anchor) - color_weights = alpha_weights = _BC7_WEIGHTS[index_bits] - if index2_bits: - # Modes 4 and 5: the selector swaps which index set drives colour and alpha. - alpha_indices, _ = _bc7_read_indices(bits, index2_bits, is_anchor) - alpha_weights = _BC7_WEIGHTS[index2_bits] - if selector: - color_indices, alpha_indices = alpha_indices, color_indices - color_weights, alpha_weights = alpha_weights, color_weights - else: - if subsets > 1: - # Address the per-subset palettes concatenated below. - stride = len(color_weights) - color_indices = [s * stride + i for s, i in zip(subset_of, color_indices)] - alpha_indices = color_indices - - # Alpha stays 255 in modes 0-3; rotation is applied after interpolation. - out = bytearray(b"\xff" * 64) - order = _BC7_ROTATIONS[rotation] - for channel, ends in enumerate(endpoints): - if channel == 3: - weights, indices = alpha_weights, alpha_indices - else: - weights, indices = color_weights, color_indices - palette = [] - for e0, e1 in zip(ends[0::2], ends[1::2]): - palette += [(e0 * (64 - w) + e1 * w + 32) >> 6 for w in weights] - out[order[channel]::4] = bytes(map(palette.__getitem__, indices)) - return bytes(out) - - -def _decode_bc7(data: bytes | bytearray | memoryview, offset: int, width: int, height: int) -> bytes: - blocks_x = (width + 3) // 4 - blocks_y = (height + 3) // 4 - expected = blocks_x * blocks_y * 16 - if len(data) - offset < expected: - raise DdsError(f"Truncated BC7 payload: {len(data) - offset} bytes (need {expected})") - - out = bytearray(width * height * 4) - row_stride = width * 4 - cache: dict[bytes, bytes] = {} - from_bytes = int.from_bytes - pos = offset - - for by in range(blocks_y): - py0 = by * 4 - max_y = height - py0 - if max_y > 4: - max_y = 4 - row_base = py0 * row_stride - - for bx in range(blocks_x): - key = bytes(data[pos : pos + 16]) - pos += 16 - block_rgba = cache.get(key) - if block_rgba is None: - block_rgba = _decode_bc7_block(from_bytes(key, "little")) - if len(cache) < _BC7_BLOCK_CACHE_LIMIT: - cache[key] = block_rgba - - px0 = bx * 4 - span = min(width - px0, 4) * 4 - dst = row_base + px0 * 4 - for ty in range(max_y): - src = ty * 16 - out[dst : dst + span] = block_rgba[src : src + span] - dst += row_stride - - return bytes(out) - - -def _linear_to_srgb_byte(linear: float) -> int: - return bisect_right(_SRGB_HALF_STEPS, linear) - - -def _unpremultiply_rgba(rgba: bytes, srgb: bool) -> bytes: - """Straight RGBA8, rounding color channels to the nearest byte and keeping alpha unchanged.""" - out = bytearray(rgba) - for p in range(0, len(out), 4): - alpha = rgba[p + 3] - if alpha == 0: - out[p:p + 3] = b"\x00\x00\x00" - elif alpha < 255: - for c in range(p, p + 3): - if srgb: - out[c] = _linear_to_srgb_byte(_SRGB_TO_LINEAR[rgba[c]] * 255.0 / alpha) - else: - out[c] = min(255, (rgba[c] * 255 + alpha // 2) // alpha) - return bytes(out) - - -def _decode_plane(data: bytes | bytearray | memoryview, plane: _Plane, info: _DdsHeader, - masks: tuple[int, int, int, int] | None, alpha_mode: int) -> tuple[int, int, bytes, bool]: - """Decode data starting at the selected plane, in its source color space.""" - payload = memoryview(data) - srgb = info["dxgi_format"] in _SRGB_DXGI_FORMATS - width, height, pitch = plane.width, plane.height, plane.row_pitch - fmt = info["format"] - - if fmt in ("RGBA8", "BGRA8", "BGRX8", "RGBX8"): - rgba = _decode_uncompressed_32(payload, width, height, fmt, masks, pitch) - elif fmt in _HALF_FLOAT_LAYOUT: - rgba = _decode_half_float(payload, width, height, fmt, pitch) - elif fmt in _RGB24_LAYOUTS.values(): - assert masks is not None - rgba = _decode_uncompressed_24(payload, width, height, fmt, masks, pitch) - elif fmt == "BC1": - rgba = _decode_bc1(payload, 0, width, height) - elif fmt == "BC2": - rgba = _decode_bc2(payload, 0, width, height) - elif fmt == "BC3": - rgba = _decode_bc3(payload, 0, width, height) - elif fmt == "BC4": - rgba = _decode_bc4(payload, 0, width, height, signed=False) - elif fmt == "BC4_SNORM": - rgba = _decode_bc4(payload, 0, width, height, signed=True) - elif fmt == "BC5": - rgba = _decode_bc5(payload, 0, width, height, signed=False) - elif fmt == "BC5_SNORM": - rgba = _decode_bc5(payload, 0, width, height, signed=True) - elif fmt == "R11G11B10_FLOAT": - rgba = _decode_r11g11b10(payload, width, height, pitch) - elif fmt in ("R16_UNORM", "R32_FLOAT", "A8_UNORM"): - rgba = _decode_single_channel(payload, width, height, pitch, fmt) - elif fmt == "BC7": - rgba = _decode_bc7(payload, 0, width, height) - else: - raise DdsError(f"Unsupported DDS format: {fmt}") - - if alpha_mode == DDS_ALPHA_MODE_PREMULTIPLIED: - rgba = _unpremultiply_rgba(rgba, srgb) - elif alpha_mode == DDS_ALPHA_MODE_OPAQUE: - opaque = bytearray(rgba) - opaque[3::4] = b"\xff" * (width * height) - rgba = bytes(opaque) - - return width, height, rgba, srgb - - -def _decode_dds(data: bytes, *, mip: int = 0, layer: int = 0, face: str | None = None, - z: int = 0) -> tuple[int, int, bytes, bool]: - info, masks, alpha_mode = _parse_header_internal(data) - plane = _locate_plane(info, mip=mip, layer=layer, face=face, z=z) - payload = memoryview(data)[plane.offset:plane.offset + plane.byte_length] - return _decode_plane(payload, plane, info, masks, alpha_mode) - - -def decode_dds(data: bytes, *, mip: int = 0, layer: int = 0, face: str | None = None, - z: int = 0) -> tuple[int, int, bytes]: - """Decode one DDS image plane into top-down row-major RGBA8 with straight alpha.""" - width, height, rgba, _ = _decode_dds(data, mip=mip, layer=layer, face=face, z=z) - return width, height, rgba - - -def _box_spans(source: int, target: int) -> list: - """Source pixel indices and integer overlap weights for each output pixel.""" - spans = [] - for i in range(target): - # In these units a source pixel is target units wide, and an output pixel is source units wide. - left, right = i * source, (i + 1) * source - span = [] - for j in range(left // target, (right - 1) // target + 1): - weight = min(right, (j + 1) * target) - max(left, j * target) - span.append((j, weight)) - spans.append(span) - return spans - - -def _resample_box(width: int, height: int, rgba: bytes, nw: int, nh: int, srgb: bool = False) -> bytes: - x_spans = _box_spans(width, nw) - y_spans = _box_spans(height, nh) - area = width * height - out = bytearray(nw * nh * 4) - for y, rows in enumerate(y_spans): - for x, cols in enumerate(x_spans): - samples = [] - for sy, wy in rows: - for sx, wx in cols: - offset = 4 * (sy * width + sx) - samples.append((offset, rgba[offset + 3] * wx * wy)) - coverage = sum(weight for _, weight in samples) - dst = 4 * (y * nw + x) - out[dst + 3] = (coverage + area // 2) // area - if coverage: - for channel in range(3): - if srgb: - light = sum(_SRGB_TO_LINEAR[rgba[offset + channel]] * weight for offset, weight in samples) - out[dst + channel] = _linear_to_srgb_byte(light / coverage) - else: - total = sum(rgba[offset + channel] * weight for offset, weight in samples) - out[dst + channel] = (total + coverage // 2) // coverage - return bytes(out) - - -def _halve_rgba(width: int, height: int, rgba: bytes, srgb: bool = False) -> tuple[int, int, bytes]: - nw = max(1, width // 2) - nh = max(1, height // 2) - if (width > 1 and width % 2) or (height > 1 and height % 2) or rgba[3::4].count(255) != width * height: - return nw, nh, _resample_box(width, height, rgba, nw, nh, srgb) - row_bytes = width * 4 - out_row_bytes = nw * 4 - out = bytearray(nw * nh * 4) - out[3::4] = b"\xff" * (nw * nh) - # A column has the same contiguous pixel pairs as a single row. - if width == 1: - if height == 1: - return nw, nh, rgba - row_bytes, out_row_bytes = height * 4, nh * 4 - linear = _SRGB_TO_LINEAR - for oy, s0 in enumerate(range(0, len(rgba), 2 * row_bytes)): - r0 = rgba[s0 : s0 + row_bytes] - r1 = rgba[s0 + row_bytes : s0 + 2 * row_bytes] or r0 - dst = oy * out_row_bytes - dst_end = dst + out_row_bytes - for c in range(3): - samples = zip(r0[c::8], r0[c + 4 :: 8], r1[c::8], r1[c + 4 :: 8]) - if srgb: - values = (_linear_to_srgb_byte((linear[a] + linear[b] + linear[d] + linear[e]) * 0.25) - for a, b, d, e in samples) - else: - values = ((a + b + d + e + 2) >> 2 for a, b, d, e in samples) - out[dst + c : dst_end : 4] = bytes(values) - - return nw, nh, bytes(out) - - -def downscale_rgba( - width: int, height: int, rgba: bytes, max_size: int, *, srgb: bool = False, -) -> tuple[int, int, bytes]: - """Halve straight-alpha RGBA8 with an alpha-weighted box filter. Tagged sRGB uses linear light.""" - if width <= 0 or height <= 0: - raise DdsError(f"Invalid image dimensions: {width}x{height}") - expected = width * height * 4 - if len(rgba) != expected: - raise DdsError(f"Invalid RGBA buffer length: {len(rgba)} (expected {expected})") - - if max_size < 0: - raise DdsError(f"Invalid max_size: {max_size}") - if max_size == 0 or max(width, height) <= max_size: - return width, height, bytes(rgba) if not isinstance(rgba, bytes) else rgba - - w, h = width, height - cur = bytes(rgba) if not isinstance(rgba, bytes) else rgba - while max(w, h) > max_size: - w, h, cur = _halve_rgba(w, h, cur, srgb) - return w, h, cur - - -def _png_chunk(chunk_type: bytes, payload: bytes) -> bytes: - crc = zlib.crc32(payload, zlib.crc32(chunk_type)) & 0xFFFFFFFF - return struct.pack(">I", len(payload)) + chunk_type + payload + struct.pack(">I", crc) - - -def encode_png(width: int, height: int, rgba: bytes) -> bytes: - """Encode top-down row-major RGBA8 bytes as a spec-compliant PNG.""" - if width <= 0 or height <= 0: - raise ValueError(f"Invalid PNG dimensions: {width}x{height}") - stride = width * 4 - expected = stride * height - if len(rgba) != expected: - raise ValueError(f"Invalid RGBA buffer length: {len(rgba)} (expected {expected})") - - ihdr = _png_chunk(b"IHDR", struct.pack(">IIBBBBB", width, height, 8, 6, 0, 0, 0)) - - raw = bytearray(height * (stride + 1)) - mv = memoryview(rgba) - dst = 1 - src = 0 - dst_step = stride + 1 - for _ in range(height): - raw[dst : dst + stride] = mv[src : src + stride] - dst += dst_step - src += stride - - idat = _png_chunk(b"IDAT", zlib.compress(raw)) - iend = _png_chunk(b"IEND", b"") - return PNG_SIGNATURE + ihdr + idat + iend - - -def _preview_png(image: tuple[int, int, bytes, bool], max_size: int) -> bytes: - w, h, rgba, srgb = image - if max_size > 0: - w, h, rgba = downscale_rgba(w, h, rgba, max_size, srgb=srgb) - return encode_png(w, h, rgba) - - -def _read_header(source: BinaryIO) -> bytes: - header = source.read(DDS_HEADER_SIZE) - if header[84:88] == b"DX10": - header += source.read(DDS_DX10_HEADER_SIZE - DDS_HEADER_SIZE) - return header - - -def dds_to_png_bytes( - data: bytes, max_size: int = 0, *, mip: int = 0, layer: int = 0, face: str | None = None, z: int = 0, -) -> bytes: - """Encode one DDS plane as PNG, optionally downscaling the selected mip.""" - if max_size < 0: - raise DdsError(f"Invalid max_size: {max_size}") - return _preview_png(_decode_dds(data, mip=mip, layer=layer, face=face, z=z), max_size) - - -def read_half_texel(path: str, *, x: int, y: int, mip: int = 0, layer: int = 0, - z: int = 0) -> dict[str, str]: - """Return exact stored channel values as text, including signed zero and nonfinite values.""" - with open(path, "rb") as source: - info = parse_dds_header(_read_header(source)) - fmt = info["format"] - if fmt not in _HALF_FLOAT_LAYOUT: - raise DdsError(f"Expected a half-float DDS, got {fmt}") - stride, channels = _HALF_FLOAT_LAYOUT[fmt] - plane = _locate_plane(info, mip=mip, layer=layer, z=z) - if (type(x) is not int or not 0 <= x < plane.width or - type(y) is not int or not 0 <= y < plane.height): - raise DdsError("Texel outside the selected mip") - if plane.offset + plane.byte_length > source.seek(0, os.SEEK_END): - raise DdsError("Truncated DDS plane") - source.seek(plane.offset + y * plane.row_pitch + x * stride) - raw = source.read(stride) - if len(raw) != stride: - raise DdsError("Truncated DDS texel") - return dict(zip("RGBA", map(str, struct.unpack(f"<{channels}e", raw)))) - - -def dds_file_to_png_bytes( - path: str, max_size: int = 0, *, mip: int = 0, layer: int = 0, face: str | None = None, z: int = 0, -) -> bytes: - """Seek directly to a mip, array layer, cube face or volume slice and encode it as PNG.""" - if max_size < 0: - raise DdsError(f"Invalid max_size: {max_size}") - with open(path, "rb") as f: - if not f.seekable(): - return dds_to_png_bytes(f.read(), max_size, mip=mip, layer=layer, face=face, z=z) - info, masks, alpha_mode = _parse_header_internal(_read_header(f)) - plane = _locate_plane(info, mip=mip, layer=layer, face=face, z=z) - # Check before seek/read: an invalid header may describe an offset larger than off_t. - if plane.offset + plane.byte_length > f.seek(0, os.SEEK_END): - raise DdsError(f"Truncated {info['format']} payload for the selected plane") - f.seek(plane.offset) - payload = f.read(plane.byte_length) - return _preview_png(_decode_plane(payload, plane, info, masks, alpha_mode), max_size) - - -def main(argv: list[str] | None = None) -> int: - ap = argparse.ArgumentParser(description="Decode a DDS texture to PNG (pure Python stdlib).") - ap.add_argument("input", help="Input .dds file path") - ap.add_argument("output", nargs="?", help="Output .png file path") - ap.add_argument("--info", action="store_true", help="Print DDS header metadata as JSON") - ap.add_argument("--mip", type=int, help="Mip level (0 is full resolution)") - ap.add_argument("--layer", type=int, help="Zero-based array element or cube index") - ap.add_argument("--face", choices=_CUBE_FACES, help="Cubemap face (default: first face present)") - ap.add_argument("--z", type=int, help="Zero-based volume slice within the selected mip") - ap.add_argument( - "--max-size", - type=int, - help="Downscale the selected plane to a maximum side length of N (0 = disabled)", - ) - args = ap.parse_args(argv) - if args.max_size is not None and args.max_size < 0: - ap.error("--max-size must be 0 or more") - export_options = (args.output, args.mip, args.layer, args.face, args.z, args.max_size) - if args.info and any(value is not None for value in export_options): - ap.error("--info takes only an input DDS") - if not args.info and args.output is None: - ap.error("an output PNG is required unless --info is used") - - try: - if args.info: - with open(args.input, "rb") as f: - print(json.dumps(parse_dds_header(_read_header(f)), indent=2)) - return 0 - try: - overwrites_input = os.path.samefile(args.input, args.output) - except FileNotFoundError: - overwrites_input = False - if overwrites_input: - raise DdsError("output must not overwrite the input DDS") - png = dds_file_to_png_bytes( - args.input, args.max_size or 0, mip=args.mip or 0, layer=args.layer or 0, - face=args.face, z=args.z or 0, - ) - # Resolve an existing symlink as the old direct write did, and stage on the same filesystem. - output = os.path.realpath(args.output) - parent = os.path.dirname(output) - os.makedirs(parent, exist_ok=True) - with tempfile.TemporaryDirectory(prefix=".dds-preview-", dir=parent) as staging: - pending = os.path.join(staging, "preview.png") - with open(pending, "wb") as f: - f.write(png) - if os.path.isfile(output): - shutil.copymode(output, pending) - os.replace(pending, output) - except (DdsError, OSError) as exc: - print(f"ERROR: {exc}", file=sys.stderr) - return 1 - return 0 - - -if __name__ == "__main__": - try: # a redirected stdout is strict ANSI code page under -I; write '?' for what it cannot encode - sys.stdout.reconfigure(errors="replace") - except (AttributeError, ValueError, OSError): - pass - sys.exit(main()) diff --git a/tools/div_fixup_diff.py b/tools/div_fixup_diff.py deleted file mode 100644 index 813920ab9..000000000 --- a/tools/div_fixup_diff.py +++ /dev/null @@ -1,1039 +0,0 @@ -r"""Differential fuzzer for v_div_fixup_f16, v_div_fixup_f32 and v_div_fixup_f64 (standard library only). - -No other fuzzer generates these three ops: they are on no `--list-ops` list and in no generator. - - v_div_fixup_f16 VOP3 d, s0, s1, s2 [op_sel:[a,b,c,d]] [clamp] [mul:2 | mul:4 | div:2] - v_div_fixup_f32 VOP3 d, s0, s1, s2 [clamp] [mul:2 | mul:4 | div:2] - v_div_fixup_f64 VOP3 d[2], s0[2], s1[2], s2[2] [mul:2 | mul:4 | div:2] - s0 quotient, s1 denominator, s2 numerator - -Seeded straight-line programs run through two independent oracles, and the four exported mrt0 words are compared: - - * the reference below, written from the docs/design.md rows "v_div_fixup_f32" (measured on gfx1036) and - "v_div_fixup_f16, v_div_fixup_f64" (the gfx1036 measurements in it). It works on the operand bits and shares no - code with the translator: - - abs clears and neg then flips the sign bit of a source, NaNs included; - - f32 reads an S1 or S2 denormal as a zero of its sign (denorm32 = 0) and keeps an S0 denormal; f16 and f64 - keep every denormal (denorm16_64 = 3); - - the first rule that holds gives the result, with sign = sign(S1) ^ sign(S2): - 1. NaN(S2) -> S2, unchanged (a signalling NaN is not quieted under IEEE = 0) - 2. NaN(S1) -> S1, unchanged - 3. 0/0 or inf/inf -> the negative quiet NaN (0xfe00, 0xffc00000, 0xfff8000000000000) - 4. a zero numerator or an inf denominator -> a zero with the sign - 5. a zero denominator or an inf numerator -> inf with the sign - 6. exp(S2) - exp(S1) <= -151 on f32 or <= -1076 on f64 (biased exponents) -> a zero with the sign; - f16 has no such cutoff - 7. NaN(S0) -> inf with the sign - 8. S0's magnitude with the sign. - The f16/f64 row lists rule 6 with rule 4 and NaN(S0) with rule 5; the order is the same, because rule 6 needs - exp(S1) >= 1076 and a finite S2, so it never meets rule 5. - - f32 output modifiers: mul:2, mul:4 or div:2, then clamp to [0, 1], where a NaN gives +0 (DX10_CLAMP = 1). - f16 clamp: to [0, 1]. - - f16 and f64 output multipliers (mul:2, mul:4, div:2) change nothing: the hardware ignores them on a 16-bit or - binary64 result while denorm_mode_16_64 = 3, the game's MODE (docs/design.md, measured on gfx1036 with - tools/f64_omod_probe.py, #6314). An f16 clamp still applies. - - an f16 result goes to the half op_sel's last bit names, and the other half is kept. - tests/test_div_fixup_diff.py pins it to the gfx1036 words that tests/semantic records, and - * tools/rdna2spirv.py, executing the SPIR-V with tests/semantic/spirv_mini_interp.py. - -Comparison: bit for bit. Only an f32 NaN that went through an output multiplier matches any NaN (payloads are not -modelled there). A program is not judged (counted with the reason, not a failure) when: - - f64 rule 6 depends on how a denormal's exponent counts (its field 0, 1, or its normalized exponent): the rows - say "exp(S2) - exp(S1)" and only normal operands were measured; - - an output multiplier without clamp meets -0 (the hardware gives +0, which docs/design.md lists as not - modelled), or an output multiplier meets an f32 denormal or makes one (whether it flushes is the MODE - question, SHADER-35); - - clamp meets a positive f32 denormal, an f16 -0 (measured on f32 only, where it gives +0) or an f16 NaN (the - translator's FClamp of it is undefined in SPIR-V); - - an op reads part of an f32 NaN whose payload the reference does not model. - -Program shape: seeds in v8..v15 and s4..s7, then the ops, then `exp mrt0 v8, v9, v10, v11` so every result is -observed. Every destination is in v8..v11 (an f64 one is v[8:9], v[9:10] or v[10:11]), so later ops read earlier -results, f64 halves as f32 or f16 values included. - -Sources: VGPRs, SGPRs (f64: a VGPR pair from v[8:9] to v[14:15], s[4:5] or s[6:7]), a hex literal (not on f64), -an integer inline constant (-16..64) and a float inline constant (0.5, 1.0, 2.0, 4.0, their negatives and 1/(2 pi), -printed 0.15915494, and 0.15915494309189532 for an f64 operand). An f16 operand reads the low half of a register or -literal (the high half with its op_sel bit), a float inline constant as its f16 value and an integer inline constant -as the low half of its word (docs/design.md, "f16 inline constants"). An f64 operand reads an integer inline constant -sign-extended. Every program is encodable on GFX10: at most one literal and at most two constant-bus reads. - -Modifiers: neg/abs on the register sources, op_sel on f16 register sources and the destination bit, clamp on f16 -and f32, and mul:2 / mul:4 / div:2 on all three. Not generated, on purpose: a literal on f64 (the translator puts it -in bits 31:0; #3791 moves it to bits 63:32), clamp on f64 (the translation needs Float64, which spirv_mini_interp -does not run), op_sel on a constant, and the forms the translator refuses (--self-test pins those as expected -rejections). - -Stages: - 1. a sweep: every encodable source-kind combination of every op, twice, with random modifiers; - 2. an edge grid: zeros, denormals, the normal bounds, 1, the largest finite value, inf and quiet and signalling - NaNs as S1 and S2 under five S0 values; the rule 6 boundaries (one exponent above, at and below the cutoff, also - against a NaN or inf S0, and on f64 with a denormal S2); abs/neg on every kind of source; the output - modifiers on every rule's result (f32), f16 op_sel, clamp and output multipliers, f64 output multipliers; - 3. random seeded programs. - -Exit code 0 when every judged program matches, 1 on a mismatch (the first one is printed with its listing) or a -translator skip (every generated form is one the translator takes), 2 on a harness error. - -Usage: - python -I tools/div_fixup_diff.py [--programs N] [--seed S] [--max-ops N] [--ops v_div_fixup_f64] - python -I tools/div_fixup_diff.py --list-ops - python -I tools/div_fixup_diff.py --self-test -""" -import argparse -import gc -import os -import random -import re -import struct -import sys -import tempfile -import warnings -from collections import Counter - -HERE = os.path.dirname(os.path.abspath(__file__)) -TOOLS_DIR = os.environ.get("LEONIDA_TOOLS_DIR") or HERE -sys.dont_write_bytecode = True -if TOOLS_DIR not in sys.path: - sys.path.insert(0, TOOLS_DIR) -SEM_DIR = os.path.join(os.path.dirname(HERE), "tests", "semantic") -if SEM_DIR not in sys.path: - sys.path.insert(0, SEM_DIR) - -import rdna2spirv # noqa: E402 -from spirv_mini_interp import UnsupportedConstruct, run_fragment # noqa: E402 - -M16 = 0xFFFF -M32 = 0xFFFFFFFF -M64 = (1 << 64) - 1 -STUB_DXBC = b"DXBC" + bytes(24) + struct.pack(" (f32 word, f16 half) - "0.5": (0x3F000000, 0x3800), "-0.5": (0xBF000000, 0xB800), "1.0": (0x3F800000, 0x3C00), - "-1.0": (0xBF800000, 0xBC00), "2.0": (0x40000000, 0x4000), "-2.0": (0xC0000000, 0xC000), - "4.0": (0x40800000, 0x4400), "-4.0": (0xC0800000, 0xC400), "0.15915494": (0x3E22F983, 0x3118), -} -FLOAT_INLINE64 = { - "0.5": 0x3FE0000000000000, "-0.5": 0xBFE0000000000000, "1.0": 0x3FF0000000000000, - "-1.0": 0xBFF0000000000000, "2.0": 0x4000000000000000, "-2.0": 0xC000000000000000, - "4.0": 0x4010000000000000, "-4.0": 0xC010000000000000, "0.15915494309189532": 0x3FC45F306DC9C882, -} -INT_INLINE = tuple(range(0, 65)) + tuple(range(-16, 0)) - - -class HarnessError(Exception): - """The generator or the reference met something outside the modelled forms.""" - - -class NotJudged(Exception): - """The reference does not judge this program (the reason is counted).""" - - -# ---- the reference ---- - -class Fmt: - def __init__(self, name, width, ebits, cutoff, canon): - self.name = name - self.width = width - self.sign = 1 << (width - 1) - self.mag = self.sign - 1 - self.mbits = width - 1 - ebits - self.inf = ((1 << ebits) - 1) << self.mbits - self.min_norm = 1 << self.mbits - self.cutoff = cutoff - self.canon = canon - - -FMT = { - "v_div_fixup_f16": Fmt("f16", 16, 5, None, 0xFE00), - "v_div_fixup_f32": Fmt("f32", 32, 8, -151, 0xFFC00000), - "v_div_fixup_f64": Fmt("f64", 64, 11, -1076, 0xFFF8000000000000), -} - - -def _exponents(fmt, a): - """The readings of the biased exponent of a finite nonzero magnitude: its field, and for a denormal also 1 and - its normalized exponent (rule 6 was measured on normal operands only).""" - e = a >> fmt.mbits - if e: - return {e} - return {0, 1, a.bit_length() - fmt.mbits} - - -def _cutoff(fmt, a1, a2): - hits = {e2 - e1 <= fmt.cutoff for e1 in _exponents(fmt, a1) for e2 in _exponents(fmt, a2)} - if len(hits) > 1: - raise NotJudged(f"{fmt.name} exponent cutoff on a denormal: how its exponent counts is not measured") - return hits.pop() - - -def fixup(fmt, s0, s1, s2): - """(rule index, result bits) of div_fixup on the modified source bits, by the order in the module docstring.""" - a0, a1, a2 = s0 & fmt.mag, s1 & fmt.mag, s2 & fmt.mag - sign = (s1 ^ s2) & fmt.sign - if a2 > fmt.inf: - return 0, s2 - if a1 > fmt.inf: - return 1, s1 - if fmt.name == "f32": - z1, z2 = a1 < fmt.min_norm, a2 < fmt.min_norm # denorm32 = 0: S1 and S2 denormals are zeros - else: - z1, z2 = a1 == 0, a2 == 0 - i1, i2 = a1 == fmt.inf, a2 == fmt.inf - if (z1 and z2) or (i1 and i2): - return 2, fmt.canon - if z2 or i1: - return 3, sign - if z1 or i2: - return 4, sign | fmt.inf - if fmt.cutoff is not None and _cutoff(fmt, a1, a2): - return 5, sign - if a0 > fmt.inf: - return 6, sign | fmt.inf - return 7, sign | a0 - - -def _f32_value(w): - """The f32 word as an exact (numerator, power of two) of its magnitude, for a normal or zero word.""" - e, m = (w >> 23) & 0xFF, w & 0x7FFFFF - return (1 << 23) | m, e - 150 - - -def out_f32(w, mods): - """The f32 output modifiers on result word ``w``: (word, state), state "w32" for a NaN of unmodelled payload.""" - k = next((m for m in mods if m in ("mul:2", "mul:4", "div:2")), None) - clamp = "clamp" in mods - a = w & 0x7FFFFFFF - if a > 0x7F800000: - if clamp: - return 0, None # DX10_CLAMP: a NaN gives +0 - return (w, None) if k is None else (0x7FC00000, "w32") - if clamp and w >> 31: - return 0, None # any negative value, -0 included (measured), clamps to +0 - if k is not None and a != 0x7F800000: - if a == 0: - if w >> 31: - raise NotJudged("an output multiplier on -0 (the hardware gives +0, not modelled)") - elif a < 0x00800000: - raise NotJudged("an output multiplier on an f32 denormal") - else: - e = (a >> 23) + {"mul:2": 1, "mul:4": 2, "div:2": -1}[k] - if e >= 0xFF: - a = 0x7F800000 - elif e <= 0: - raise NotJudged("an output multiplier gives an f32 denormal") - else: - a = (e << 23) | (a & 0x7FFFFF) - w = (w & 0x80000000) | a - if clamp: - if 0 < a < 0x00800000: - raise NotJudged("clamp of an f32 denormal") - if a >= 0x3F800000: # above 1, or +inf - return 0x3F800000, None - return w, None - - -def clamp_f16(h): - a = h & 0x7FFF - if a > 0x7C00: - raise NotJudged("clamp of an f16 NaN (FClamp of a NaN is undefined in SPIR-V)") - if a == 0 and h & 0x8000: - raise NotJudged("clamp of -0") - if h & 0x8000: - return 0 - return min(h, 0x3C00) - - -# ---- the program text ---- - -_REG = re.compile(r"([sv])(\d+)$") -_PAIR = re.compile(r"([sv])\[(\d+):(\d+)\]$") -_SRC = re.compile(r"(-?)(\|?)([sv]\d+|[sv]\[\d+:\d+\])\|?$") -_MOD = re.compile(r"\s+(op_sel:\[[01](?:,[01])*\]|clamp|mul:2|mul:4|div:2)$") - - -def split_line(line): - """'op d, a, b mods' -> (op, [operands], [mods]).""" - mods = [] - while True: - m = _MOD.search(line) - if not m: - break - mods.insert(0, m.group(1)) - line = line[:m.start()] - op, _, rest = line.partition(" ") - return op, [t.strip() for t in rest.split(",")], mods - - -def _opsel(mods): - m = next((x for x in mods if x.startswith("op_sel:")), None) - if m is None: - return [0, 0, 0, 0] - b = [int(x) for x in m.split("[")[1].rstrip("]").split(",")] - if len(b) != 4: - raise HarnessError(f"{m}: want 4 bits") - return b - - -class Machine: - """The reference's register file: words, and per-half states: None (known bits) or "w32" (half of an f32 NaN - whose payload the reference does not model).""" - - def __init__(self): - self.v = {} - self.s = {} - self.st = {} - - def state(self, r): - return self.st.setdefault(r, [None, None]) - - def reg(self, k, i): - if k == "v": - if i not in self.v: - raise HarnessError(f"v{i} read before it is written") - return self.v[i], list(self.state(i)) - if i not in self.s: - raise HarnessError(f"s{i} read before it is written") - return self.s[i], [None, None] - - def source(self, tok, fmt, hi=0): - """(modified source bits, unknown) of an operand of width fmt.width; ``unknown`` marks an f32 NaN whose - payload is not modelled.""" - m = _SRC.match(tok) - mod = (m.group(1) + m.group(2)) if m else "" - base = m.group(3) if m else tok - unknown = False - pm, rm = _PAIR.match(base), _REG.match(base) - if fmt.width == 64: - if pm: - k, lo, top = pm.group(1), int(pm.group(2)), int(pm.group(3)) - if top != lo + 1: - raise HarnessError(f"bad pair {base}") - (wl, sl), (wh, sh) = self.reg(k, lo), self.reg(k, lo + 1) - if "w32" in sl + sh: - raise NotJudged("an f32 NaN of unmodelled payload read as half of an f64") - bits = wl | (wh << 32) - elif base in FLOAT_INLINE64: - bits = FLOAT_INLINE64[base] - else: - bits = self._int(base) & M64 - elif rm: - w, sts = self.reg(rm.group(1), int(rm.group(2))) - if fmt.width == 16: - if sts[hi] == "w32": - raise NotJudged("half of an f32 NaN of unmodelled payload read as an f16") - bits = (w >> 16) & M16 if hi else w & M16 - else: - if sts == ["w32", "w32"]: - unknown = True - elif "w32" in sts: - raise NotJudged("an f32 NaN of unmodelled payload read in part") - bits = w - elif base in FLOAT_INLINE: - if hi: - raise HarnessError("op_sel on a constant") - bits = FLOAT_INLINE[base][1 if fmt.width == 16 else 0] - elif base.startswith("0x"): - if hi: - raise HarnessError("op_sel on a constant") - bits = int(base, 16) & (M16 if fmt.width == 16 else M32) - else: - if hi: - raise HarnessError("op_sel on a constant") - bits = self._int(base) & (M16 if fmt.width == 16 else M32) - if "|" in mod: - bits &= fmt.mag - if mod.startswith("-"): - bits ^= fmt.sign - if unknown: - bits = (bits & fmt.sign) | 0x7FC00000 - return bits, unknown - - @staticmethod - def _int(tok): - try: - n = int(tok) - except ValueError: - raise HarnessError(f"unknown source {tok!r}") from None - if n not in INT_INLINE: - raise HarnessError(f"{n} is not an inline constant") - return n - - def dst(self, tok, width): - if width == 64: - m = _PAIR.match(tok) - if not m or m.group(1) != "v" or int(m.group(3)) != int(m.group(2)) + 1: - raise HarnessError(f"destination {tok!r}") - return int(m.group(2)) - m = _REG.match(tok) - if not m or m.group(1) != "v": - raise HarnessError(f"destination {tok!r}") - return int(m.group(2)) - - def write_half(self, r, hi, h): - old = self.v.get(r, 0) - self.v[r] = (old & M16) | (h << 16) if hi else (old & 0xFFFF0000) | h - self.state(r)[hi] = None - - def write_word(self, r, w, st=None): - self.v[r] = w & M32 - self.st[r] = [st, st] - - -def _count(events, op, fmt, rule, bits): - if events is None: - return - ev = events.setdefault(op, Counter()) - ev[RULES[rule]] += 1 - for b in bits: - a = b & fmt.mag - if a > fmt.inf: - ev["NaN in"] += 1 - elif a == fmt.inf: - ev["inf in"] += 1 - elif 0 < a < fmt.min_norm: - ev["denormal in"] += 1 - - -def step(line, mc, events=None): - """Run one op line on the Machine.""" - op, args, mods = split_line(line) - fmt = FMT.get(op) - if fmt is None: - raise HarnessError(f"op {op!r} is not in the family") - if len(args) != 4: - raise HarnessError(f"{op}: want 4 operands") - sel = _opsel(mods) - if fmt.width != 16 and any(sel): - raise HarnessError(f"op_sel on {op}") - if sum(m in ("mul:2", "mul:4", "div:2") for m in mods) > 1: - raise HarnessError(f"two output multipliers on {op}") - if fmt.width == 64 and "clamp" in mods: - raise HarnessError("clamp on v_div_fixup_f64") - d = mc.dst(args[0], fmt.width) - srcs = [mc.source(t, fmt, sel[i]) for i, t in enumerate(args[1:])] - bits = [b for b, _ in srcs] - rule, r = fixup(fmt, *bits) - _count(events, op, fmt, rule, bits) - # an output multiplier on an f16 or f64 result is ignored under denorm_mode_16_64 = 3 (#6314): nothing to do - if fmt.width == 16: - if "clamp" in mods: - r = clamp_f16(r) - mc.write_half(d, sel[3], r) - elif fmt.width == 32: - unknown = rule in (0, 1) and srcs[2 - rule][1] - if unknown and "clamp" not in mods: - mc.write_word(d, 0x7FC00000, "w32") - else: - w, st = out_f32(r, mods) - mc.write_word(d, w, st) - else: - mc.write_word(d, r & M32) - mc.write_word(d + 1, r >> 32) - - -def reference(lines, events=None): - """Run the program; returns (four exported words, per-word half states). Raises NotJudged.""" - mc = Machine() - for line in lines: - op, args, _ = split_line(line) - if op == "v_mov_b32": - mc.write_word(mc.dst(args[0], 32), int(args[1], 16)) - elif op == "s_mov_b32": - mc.s[int(args[0][1:])] = int(args[1], 16) & M32 - else: - step(line, mc, events) - return [mc.v[r] for r in EXPORT_REGS], [list(mc.state(r)) for r in EXPORT_REGS] - - -def compare(want, states, got): - """None when every judged bit agrees, else a description of the first difference.""" - for i, (w, sts, g) in enumerate(zip(want, states, got)): - g &= M32 - if sts == ["w32", "w32"]: - if not ((g >> 23) & 0xFF == 0xFF and g & 0x7FFFFF): - return f"word {i} (v{EXPORT_REGS[i]}): expected an f32 NaN, actual 0x{g:08x}" - continue - mask = (0 if sts[0] else M16) | (0 if sts[1] else M16 << 16) - if (w ^ g) & mask: - return f"word {i} (v{EXPORT_REGS[i]}): expected 0x{w:08x}, actual 0x{g:08x}" - return None - - -# ---- the generator ---- - -F16_EDGES = (0x0000, 0x8000, 0x0001, 0x83FF, 0x0400, 0x3C00, 0xBC00, 0x7BFF, 0x7C00, 0xFC00, 0x7C01, 0xFE00) -F32_EDGES = (0x00000000, 0x80000000, 0x00000001, 0x807FFFFF, 0x00800000, 0x3F800000, 0xBF800000, 0x7F7FFFFF, - 0x7F800000, 0xFF800000, 0x7F800001, 0xFFC00000) -F64_EDGES = (0, 1 << 63, 1, (1 << 63) | ((1 << 52) - 1), 1 << 52, 0x3FF0000000000000, 0xBFF0000000000000, - 0x7FEFFFFFFFFFFFFF, 0x7FF0000000000000, 0xFFF0000000000000, 0x7FF0000000000001, 0xFFF8000000000000) -EDGES = {16: F16_EDGES, 32: F32_EDGES, 64: F64_EDGES} -# S0 under the edge grid: 1.5, a denormal, -0, -inf and a NaN with a payload -S0_EDGES = {16: (0x3E00, 0x0003, 0x8000, 0xFC00, 0x7D11), - 32: (0x3FC00000, 0x00000003, 0x80000000, 0xFF800000, 0x7FA00011), - 64: (0x3FF8000000000000, 3, 1 << 63, 0xFFF0000000000000, 0x7FF4000000000011)} - - -def _rand_f16(rng): - r = rng.random() - if r < 0.3: - return rng.choice(F16_EDGES) - if r < 0.4: - return (rng.getrandbits(1) << 15) | rng.randrange(1, 0x400) - if r < 0.5: - return rng.getrandbits(16) - return (rng.getrandbits(1) << 15) | (rng.randrange(1, 31) << 10) | rng.getrandbits(10) - - -def _rand_f32(rng): - r = rng.random() - if r < 0.3: - return rng.choice(F32_EDGES) - if r < 0.4: - return rng.getrandbits(32) - if r < 0.5: - return (rng.getrandbits(1) << 31) | rng.randrange(1, 0x800000) - e = rng.randrange(1, 255) if rng.random() < 0.6 else rng.choice((1, 2, 3, 100, 127, 150, 151, 152, 153, 254)) - return (rng.getrandbits(1) << 31) | (e << 23) | rng.getrandbits(23) - - -def _f64_high(rng): - """The high word of a binary64: sign, an exponent (often an extreme one), 20 mantissa bits.""" - r = rng.random() - if r < 0.15: - return rng.choice(F64_EDGES) >> 32 - if r < 0.4: - e = rng.choice((0, 0, 1, 2, 3, 52, 1022, 1023, 1024, 1076, 1077, 1078, 2045, 2046, 2047)) - else: - e = rng.randrange(0, 2048) - return (rng.getrandbits(1) << 31) | (e << 20) | (rng.getrandbits(20) if rng.random() < 0.7 else 0) - - -def _rand_f64(rng): - r = rng.random() - if r < 0.3: - return rng.choice(F64_EDGES) - lo = 0 if rng.random() < 0.4 else rng.getrandbits(32) - return (_f64_high(rng) << 32) | lo - - -def _seed_word(rng): - r = rng.random() - if r < 0.3: - return _rand_f16(rng) | (_rand_f16(rng) << 16) - if r < 0.6: - return _rand_f32(rng) - if r < 0.85: - return _f64_high(rng) - return 0 if rng.random() < 0.5 else rng.getrandbits(32) - - -def _source(rng, kind, width): - """A source token of ``kind`` (no modifier) for an operand of ``width`` bits.""" - if width == 64: - if kind == "vgpr": - n = rng.randrange(8, 15) - return f"v[{n}:{n + 1}]" - if kind == "sgpr": - n = rng.choice(SGPR_PAIRS) - return f"s[{n}:{n + 1}]" - if kind == "int": - return str(rng.choice(INT_INLINE)) - if kind == "float": - return rng.choice(tuple(FLOAT_INLINE64)) - raise HarnessError(f"{kind} source on f64") - if kind == "vgpr": - return f"v{rng.choice(VGPRS)}" - if kind == "sgpr": - return f"s{rng.choice(SGPRS)}" - if kind == "lit": - w = (_rand_f16(rng) | (rng.getrandbits(16) << 16)) if width == 16 else _rand_f32(rng) - return f"0x{w:08x}" - if kind == "int": - return str(rng.choice(INT_INLINE)) - return rng.choice(tuple(FLOAT_INLINE)) - - -def encodable(kinds): - """GFX10 VOP3: at most one literal, at most two constant-bus reads (SGPRs and the literal).""" - return sum(k == "lit" for k in kinds) <= 1 and sum(k in ("sgpr", "lit") for k in kinds) <= 2 - - -def _reg_mod(rng, tok, kind): - if kind not in ("vgpr", "sgpr"): - return tok - m = rng.choice(MODS) - return f"{'-' if m.startswith('-') else ''}{'|' if '|' in m else ''}{tok}{'|' if '|' in m else ''}" - - -def _out_mods(rng, width): - """The output modifiers of a random line: clamp on f16 and f32, an output multiplier on all three.""" - extra = "" - if width in (16, 32) and rng.random() < 0.25: - extra += " clamp" - k = rng.choice(OMODS) - if k: - extra += " " + k - return extra - - -def op_line(rng, op, kinds=None, mods=True): - """One line of ``op``; ``kinds`` fixes the three source kinds (else random).""" - width = FMT[op].width - allowed = KINDS64 if width == 64 else KINDS - while True: - ks = list(kinds) if kinds else [rng.choice(allowed) for _ in range(3)] - if encodable(ks) and all(k in allowed for k in ks): - break - if kinds: - raise HarnessError(f"{op}: {kinds} not encodable") - toks = [_source(rng, k, width) for k in ks] - srcs = [_reg_mod(rng, t, k) if mods else t for t, k in zip(toks, ks)] - if width == 64: - n = rng.choice(DSTS64) - return f"{op} v[{n}:{n + 1}], {', '.join(srcs)}{_out_mods(rng, width) if mods else ''}", ks - extra = "" - if width == 16: - sel = [rng.getrandbits(1) if k in ("vgpr", "sgpr") else 0 for k in ks] + [rng.getrandbits(1)] - if any(sel) or rng.random() < 0.2: - extra = f" op_sel:[{','.join(map(str, sel))}]" - if mods: - extra += _out_mods(rng, width) - return f"{op} v{rng.choice(DSTS)}, {', '.join(srcs)}{extra}", ks - - -def seeds(rng): - lines = [f"v_mov_b32 v{r}, 0x{_seed_word(rng):08x}" for r in VGPRS] - lines += [f"s_mov_b32 s{r}, 0x{_seed_word(rng):08x}" for r in SGPRS] - return lines - - -def program(rng, n_ops, ops=None): - """A random program: seeds, n_ops family ops, the export. Returns (lines, the ops used).""" - ops = list(ops or OPS) - lines = seeds(rng) - used = [] - for _ in range(n_ops): - op = rng.choice(ops) - lines.append(op_line(rng, op)[0]) - used.append(op) - return lines, used - - -def sweep_cases(ops=None): - """(op, kinds) for every encodable source-kind combination of every op.""" - cases = [] - for op in ops or OPS: - allowed = KINDS64 if FMT[op].width == 64 else KINDS - for a in allowed: - for b in allowed: - for c in allowed: - if encodable([a, b, c]): - cases.append((op, (a, b, c))) - return cases - - -SWEEP_REPEAT = 2 - - -def sweep_program(case, rng): - op, kinds = case - return seeds(rng) + [op_line(rng, op, kinds)[0]] - - -# ---- the edge grid ---- - -GRID_PER_PROGRAM = 4 -_GRID_RNG_SEED = "div_fixup_diff:grid" - - -def _with_exp(width, sign, e, rng): - """A value of ``width`` with biased exponent ``e`` (0: a nonzero denormal) and a random mantissa.""" - f = FMT[{16: "v_div_fixup_f16", 32: "v_div_fixup_f32", 64: "v_div_fixup_f64"}[width]] - m = rng.randrange(1, f.min_norm) if e == 0 else rng.getrandbits(f.mbits) - return (sign << (width - 1)) | (e << f.mbits) | m - - -def grid_cases(ops=None): - """(op, (s0, s1, s2) words, (three source modifiers), op_sel bits, output modifiers) cases.""" - rng = random.Random(_GRID_RNG_SEED) - cases = [] - for op in ops or OPS: - f = FMT[op] - w = f.width - plain = ("", "", "") - # 1. every edge pair as S1 and S2, under five S0 values - for s0 in S0_EDGES[w]: - for s1 in EDGES[w]: - for s2 in EDGES[w]: - cases.append((op, (s0, s1, s2), plain, (0, 0, 0, 0), "")) - # 2. the exponent cutoff: one above, at, and one below it, also against a NaN and an inf S0 - if f.cutoff is not None: - top = (1 << (w - 1 - f.mbits)) - 2 # the largest finite biased exponent - for diff in (f.cutoff + 1, f.cutoff, f.cutoff - 1): - for e1 in (top, top - 1, -diff + 1, -diff + 2, -diff + 40): - e2 = e1 + diff - if not (1 <= e1 <= top and 1 <= e2 <= top): - continue - for s0 in (S0_EDGES[w][0], S0_EDGES[w][4], f.inf): - sg = rng.getrandbits(2) - cases.append((op, (s0, _with_exp(w, sg & 1, e1, rng), _with_exp(w, sg >> 1, e2, rng)), - plain, (0, 0, 0, 0), "")) - if w == 64: - # a denormal numerator against large denominators: the readings of its exponent agree below and - # above the band where they differ, and disagree (not judged) inside it - for e1 in (1000, 1024, 1025, 1050, 1075, 1076, 1077, 1100, 2046): - for m2 in (1, 1 << 20, (1 << 52) - 1): - cases.append((op, (S0_EDGES[w][0], _with_exp(w, 0, e1, rng), m2), plain, (0, 0, 0, 0), "")) - # 3. abs/neg on every kind of source, NaNs included - for _ in range(240): - words = (rng.choice(S0_EDGES[w] + EDGES[w]), rng.choice(EDGES[w]), rng.choice(EDGES[w])) - cases.append((op, words, tuple(rng.choice(MODS) for _ in range(3)), (0, 0, 0, 0), "")) - # 4. the output modifiers on each rule's result (f32), clamp and op_sel (f16) - one, neg_one = {16: (0x3C00, 0xBC00), 32: (0x3F800000, 0xBF800000), 64: (F64_EDGES[5], F64_EDGES[6])}[w] - nan = EDGES[w][10] - zero = 0 - outcomes = ((one, one), (zero, zero), (one, zero), (zero, one), (one, nan), (neg_one, one), (nan, one)) - if w == 64: - # the multipliers change nothing on a binary64 result (#6314); clamp is not generated on f64 - for s0 in S0_EDGES[w] + (F64_EDGES[7], F64_EDGES[4]): - for s1, s2 in outcomes: - for om in F16_F64_OMODS[w]: - cases.append((op, (s0, s1, s2), plain, (0, 0, 0, 0), om)) - continue - if w == 32: - s0s = (0x3F000000, 0x3FC00000, 0xBF000000, 0x7F7FFFFF, 0x00800000, 0x00000001, 0x7FC00001, 0x3E800000) - omods = ("clamp", "mul:2", "mul:4", "div:2", "clamp mul:2", "clamp mul:4", "clamp div:2") - for s0 in s0s: - for s1, s2 in outcomes: - for om in omods: - cases.append((op, (s0, s1, s2), plain, (0, 0, 0, 0), om)) - else: - s0s = (0x3800, 0x3E00, 0xB800, 0x7BFF, 0x0001, 0x7D00, 0x3C00) - for s0 in s0s: - for s1, s2 in outcomes: - for clamp in ("", "clamp"): - for _ in range(2): - sel = tuple(rng.getrandbits(1) for _ in range(4)) - cases.append((op, (s0, s1, s2), plain, sel, clamp)) - # the multipliers change nothing on an f16 result (#6314), with or without clamp, in either half - for i, (s0, (s1, s2)) in enumerate((s0, o) for s0 in s0s for o in outcomes): - for om in F16_F64_OMODS[w]: - cases.append((op, (s0, s1, s2), plain, (0, 0, 0, i & 1), om)) - return cases - - -def _mod(tok, m): - return f"{'-' if m.startswith('-') else ''}{'|' if '|' in m else ''}{tok}{'|' if '|' in m else ''}" - - -def grid_program(chunk, rng): - """A program for a chunk of grid cases of one op. Case i reads its own registers from v16 + 6i on and writes - v{8 + i} (f64: v[8 + 2i : 9 + 2i]).""" - lines = [f"v_mov_b32 v{r}, 0x{rng.getrandbits(32):08x}" for r in VGPRS] - lines += [f"s_mov_b32 s{r}, 0x{rng.getrandbits(32):08x}" for r in SGPRS] - body = [] - for i, (op, words, mods, sel, om) in enumerate(chunk): - w = FMT[op].width - base = 16 + 6 * i - if w == 64: - for j, x in enumerate(words): - lines.append(f"v_mov_b32 v{base + 2 * j}, 0x{x & M32:08x}") - lines.append(f"v_mov_b32 v{base + 2 * j + 1}, 0x{x >> 32:08x}") - srcs = [_mod(f"v[{base + 2 * j}:{base + 2 * j + 1}]", m) for j, m in enumerate(mods)] - body.append(f"{op} v[{8 + 2 * i}:{9 + 2 * i}], {', '.join(srcs)}{' ' + om if om else ''}") - continue - for j, x in enumerate(words): - if w == 16: - other = rng.getrandbits(16) - x = (x << 16) | other if sel[j] else x | (other << 16) - lines.append(f"v_mov_b32 v{base + j}, 0x{x:08x}") - srcs = [_mod(f"v{base + j}", m) for j, m in enumerate(mods)] - extra = f" op_sel:[{','.join(map(str, sel))}]" if any(sel) else "" - body.append(f"{op} v{8 + i}, {', '.join(srcs)}{extra}{' ' + om if om else ''}") - return lines + body - - -# ---- the oracles ---- - -def write_listing(path, lines, name): - with open(path, "w", encoding="utf-8", newline="\n") as f: - f.write(f"; {name} code 0x0..0x1000\n") - for line in lines: - f.write("\t" + line + "\n") - f.write("\t" + EXPORT + "\n") - f.write("\ts_endpgm\n") - - -def translate_listing(lines, name, tmpdir): - """The four mrt0 words the translator path produces. Raises rdna2spirv.Unsupported (and the mini interp's - UnsupportedConstruct) for anything outside the oracles' model.""" - dis = os.path.join(tmpdir, "disasm") - os.makedirs(dis, exist_ok=True) - path = os.path.join(dis, name + ".s") - write_listing(path, lines, name) - with open(os.path.join(tmpdir, name + ".dxbc"), "wb") as f: - f.write(STUB_DXBC) - with warnings.catch_warnings(): - warnings.simplefilter("ignore", ResourceWarning) - spvasm = rdna2spirv.translate(path) - gc.collect() - out = run_fragment(spvasm) - if list(out) != ["%out_mrt0"]: - raise HarnessError(f"outputs {sorted(out)}, want %out_mrt0") - return [w & M32 for w in out["%out_mrt0"]] - - -def check(lines, name="ps_dfx_case"): - """None when both oracles agree, else the first difference.""" - with tempfile.TemporaryDirectory(prefix="dfx-diff-") as tmp: - want, states = reference(lines) - got = translate_listing(lines, name, tmp) - return compare(want, states, got) - - -def run_one(lines, name, tmpdir, events=None): - """(status, detail) with status in {"match", "mismatch", "skip", "unjudged"}.""" - try: - want, states = reference(lines, events) - except NotJudged as e: - return ("unjudged", str(e)) - try: - got = translate_listing(lines, name, tmpdir) - except (rdna2spirv.Unsupported, UnsupportedConstruct) as e: - return ("skip", f"{type(e).__name__}: {e}") - except (IndexError, KeyError, ValueError) as e: - return ("skip", f"translator error {type(e).__name__}: {e}") - diff = compare(want, states, got) - if diff: - return ("mismatch", diff) - return ("match", "") - - -# ---- the suites ---- - -def _new_counts(): - return {"pass": 0, "mismatch": 0, "skip": Counter(), "unjudged": Counter(), "ops": Counter(), "events": {}} - - -def _tally(counts, status, detail): - if status == "match": - counts["pass"] += 1 - elif status in ("skip", "unjudged"): - counts[status][detail] += 1 - else: - counts["mismatch"] += 1 - - -def _run(counts, items, tag): - failure = None - with tempfile.TemporaryDirectory(prefix=f"dfx-diff-{tag}-") as tmp: - for i, (label, lines, used) in enumerate(items): - counts["ops"].update(used) - status, detail = run_one(lines, f"ps_dfx_{tag}{i:05d}", tmp, counts["events"]) - _tally(counts, status, detail) - if status == "mismatch" and failure is None: - failure = (label, lines, detail) - return failure - - -def sweep_items(seed, ops=None): - """(label, lines, ops) of the sweep, yielded one at a time so a run holds one program's text.""" - for case in sweep_cases(ops): - op, kinds = case - for rep in range(SWEEP_REPEAT): - tag = f"{op}:{'/'.join(kinds)}:{rep}" - rng = random.Random(f"{seed}:{tag}") - yield f"sweep {tag} (seed {seed})", sweep_program(case, rng), [op] - - -def run_sweep(seed, ops=None): - counts = _new_counts() - return counts, _run(counts, sweep_items(seed, ops), "sw") - - -def grid_items(ops=None): - """(label, lines, ops) of the edge grid: four cases per program, two for f64, yielded one at a time.""" - rng = random.Random("div_fixup_diff:grid-programs") - cases = grid_cases(ops) - for op in ops or OPS: - mine = [c for c in cases if c[0] == op] - n = 2 if FMT[op].width == 64 else GRID_PER_PROGRAM - for i in range(0, len(mine), n): - chunk = mine[i:i + n] - yield f"edge grid {op} program {i // n}", grid_program(chunk, rng), [op] * len(chunk) - - -def run_grid(ops=None): - counts = _new_counts() - return counts, _run(counts, grid_items(ops), "gr") - - -def suite_items(programs, seed, max_ops=6, ops=None): - """(label, lines, ops) of the random programs, yielded one at a time.""" - rng = random.Random(f"suite:{seed}") - for i in range(programs): - lines, used = program(rng, rng.randint(1, max_ops), ops) - yield f"program {i} (seed {seed})", lines, used - - -def run_suite(programs, seed, max_ops=6, ops=None): - counts = _new_counts() - return counts, _run(counts, suite_items(programs, seed, max_ops, ops), "rn") - - -REJECTED = ( - ("op_sel on v_div_fixup_f32", "v_div_fixup_f32 v8, v9, v10, v11 op_sel:[1,0,0,0]"), - ("a single-VGPR destination of v_div_fixup_f64", "v_div_fixup_f64 v8, v[10:11], v[12:13], v[14:15]"), -) - - -def self_test(): - ok = True - - def report(good, what): - nonlocal ok - ok &= good - print(("ok " if good else "FAIL ") + what) - - # reference spot checks, from the docs/design.md rows - f16, f32, f64 = (FMT[op] for op in OPS) - for fmt, words, want, what in ( - (f32, (0x3F800000, 0x7FC00011, 0x7F800005), 0x7F800005, "f32: NaN(S2) beats NaN(S1), unchanged"), - (f32, (0x3F800000, 0x00000001, 0x807FFFFF), 0xFFC00000, "f32: denormal S1 and S2 read as 0/0"), - (f32, (0x7FC00000, 0x4C000000, 0x00800000), 0x00000000, "f32: e2 - e1 = -151 gives 0, beats NaN(S0)"), - (f32, (0x7FC00000, 0x4B800000, 0x00800000), 0x7F800000, "f32: e2 - e1 = -150 keeps NaN(S0) -> inf"), - (f32, (0x00000003, 0xBF800000, 0x3F800000), 0x80000003, "f32: an S0 denormal is kept"), - (f16, (0x3C00, 0x7800, 0x0400), 0x3C00, "f16: no exponent cutoff (e2 - e1 = -29)"), - (f16, (0x7E35, 0xC000, 0x3C00), 0xFC00, "f16: NaN(S0) gives -inf"), - (f64, (0x3FF0000000000000, 2046 << 52, 971 << 52), 0x3FF0000000000000, "f64: e2 - e1 = -1075 keeps S0"), - (f64, (0x3FF0000000000000, 2046 << 52, 970 << 52), 0, "f64: e2 - e1 = -1076 gives +0"), - (f64, (0x3FF0000000000000, 0, 1 << 63), 0xFFF8000000000000, "f64: 0/0 gives 0xfff8000000000000")): - report(fixup(fmt, *words)[1] == want, what) - report(out_f32(0x3FC00000, ["clamp", "mul:2"]) == (0x3F800000, None), "f32: mul:2 then clamp of 1.5 is 1.0") - report(out_f32(0xFFC00000, ["clamp"]) == (0, None), "f32: clamp of a NaN is +0") - zeros = [f"v_mov_b32 v{r}, 0x0" for r in EXPORT_REGS] - words = reference(zeros + ["v_mov_b32 v12, 0x3e00", "v_mov_b32 v13, 0x3c00", "v_mov_b32 v14, 0x3c00", - "v_div_fixup_f16 v8, v12, v13, v14 clamp div:2"])[0] - report(words[0] & 0xFFFF == 0x3C00, "f16: div:2 is ignored and clamp still applies (1.5 gives 1.0, not 0.75)") - words = reference(zeros + ["v_mov_b32 v12, 0x0", "v_mov_b32 v13, 0x3ff80000", "v_mov_b32 v14, 0x0", - "v_mov_b32 v15, 0x3ff00000", "v_div_fixup_f64 v[8:9], v[12:13], v[14:15], v[14:15] mul:4"])[0] - report(words[:2] == [0, 0x3FF80000], "f64: mul:4 is ignored (1.5 stays 1.5)") - for what, line in REJECTED: - try: - with tempfile.TemporaryDirectory(prefix="dfx-diff-st-") as tmp: - translate_listing(seeds(random.Random(1)) + [line], "ps_dfx_rej", tmp) - report(False, f"{what}: the translator accepted it") - except (rdna2spirv.Unsupported, UnsupportedConstruct): - report(True, f"{what}: the translator rejected it") - a = program(random.Random("st"), 5)[0] - b = program(random.Random("st"), 5)[0] - report(a == b, "generation is deterministic for a seed") - counts, failure = run_suite(8, 1) - report(failure is None and not counts["skip"], - f"a short seeded run matches ({counts['pass']} programs, skips {dict(counts['skip'])})") - return ok - - -def main(): - ap = argparse.ArgumentParser(description=__doc__.split("\n")[0]) - ap.add_argument("--programs", type=int, default=300, help="random programs after the sweep and the grid") - ap.add_argument("--seed", type=int, default=1) - ap.add_argument("--max-ops", type=int, default=6, help="ops per random program") - ap.add_argument("--ops", default=None, help="comma-separated opcodes to cover (default: all three)") - ap.add_argument("--no-sweep", action="store_true", help="skip the source-kind sweep and the edge grid") - ap.add_argument("--list-ops", action="store_true") - ap.add_argument("--self-test", action="store_true") - args = ap.parse_args() - if args.list_ops: - for op in OPS: - print(f"{op:16s} {OP_FORMS[op]}") - return 0 - if args.self_test: - return 0 if self_test() else 1 - ops = None - if args.ops: - ops = [o.strip() for o in args.ops.split(",") if o.strip()] - bad = [o for o in ops if o not in OPS] - if bad: - print(f"unknown op(s): {', '.join(bad)} (see --list-ops)", file=sys.stderr) - return 2 - stages = [] - if not args.no_sweep: - stages += [("sweep", lambda: run_sweep(args.seed, ops)), ("edge grid", lambda: run_grid(ops))] - if args.programs > 0: - stages.append(("random", lambda: run_suite(args.programs, args.seed, args.max_ops, ops))) - total = {"pass": 0, "mismatch": 0, "skip": 0, "unjudged": Counter(), "ops": Counter(), "events": {}} - first = None - try: - for name, fn in stages: - counts, failure = fn() - n = counts["pass"] + counts["mismatch"] + sum(counts["skip"].values()) + sum(counts["unjudged"].values()) - print(f"{name}: {counts['pass']}/{n} programs match, {counts['mismatch']} mismatch; " - f"skips: {dict(counts['skip'])}; not judged: {sum(counts['unjudged'].values())}") - total["pass"] += counts["pass"] - total["mismatch"] += counts["mismatch"] - total["skip"] += sum(counts["skip"].values()) - total["unjudged"].update(counts["unjudged"]) - total["ops"].update(counts["ops"]) - for op, ev in counts["events"].items(): - total["events"].setdefault(op, Counter()).update(ev) - if failure and first is None: - first = failure - except HarnessError as e: - print(f"harness error: {e}", file=sys.stderr) - return 2 - print("op lines per op: " + ", ".join(f"{op} {n}" for op, n in sorted(total["ops"].items()))) - for op, ev in sorted(total["events"].items()): - print(f"rules taken by {op}: " + ", ".join(f"{r} {ev[r]}" for r in RULES) - + f"; NaN / inf / denormal inputs {ev['NaN in']}/{ev['inf in']}/{ev['denormal in']}") - if total["unjudged"]: - print("not judged: " + ", ".join(f"{why} {n}" for why, n in total["unjudged"].most_common())) - judged = total["pass"] + total["mismatch"] + total["skip"] - print(f"div_fixup family: {total['pass']}/{judged} judged programs match, {total['mismatch']} mismatch " - f"({len(total['ops'])} of {len(OPS)} ops)") - if first: - _report(first) - return 1 - if total["skip"]: - print(f"SKIPPED {total['skip']} program(s): every generated form should translate (reasons above)") - return 1 - return 0 - - -def _report(failure): - label, lines, detail = failure - print(f"\nFIRST MISMATCH: {label}: {detail}") - for line in lines: - print(" " + line) - - -if __name__ == "__main__": - try: # a redirected stdout is strict ANSI code page under -I; write '?' for what it cannot encode - sys.stdout.reconfigure(errors="replace") - except (AttributeError, ValueError, OSError): - pass - sys.exit(main()) diff --git a/tools/dot_diff.py b/tools/dot_diff.py deleted file mode 100644 index 442689b34..000000000 --- a/tools/dot_diff.py +++ /dev/null @@ -1,700 +0,0 @@ -r"""Differential fuzzer for the RDNA2 packed integer dot products (standard library only). - -Covers twelve opcodes, one family (the "Packed integer dot products", "Signed-byte dot products" and -`v_dot2c_i32_i16`, `v_dot8c_i32_i4` rows of docs/design.md's contract table): - - v_dot2_i32_i16 v_dot2_u32_u16 v_dot4_i32_i8 v_dot4_u32_u8 v_dot8_i32_i4 v_dot8_u32_u4 VOP3P, acc = S2 - v_dot4c_i32_i8 VOP2, acc = old D - v_dot2c_i32_i16 v_dot2c_u32_u16 v_dot4c_u32_u8 v_dot8c_i32_i4 v_dot8c_u32_u4 VOP2/VOP3, acc = old D - -The first seven are the gfx103x encodings (docs/design.md, the GFX10.1/GFX10.3 opcode row). The last five are the -gfx908 `VOP2Instructions.td` forms the translator also accepts (not in the gfx1013/gfx103x feature sets); they run -by default because the translator ships them, and `--ops` can leave them out. - -Seeded straight-line programs run through two independent oracles, and the four exported mrt0 words are compared -bit for bit (all integer, so a mismatch is never a rounding convention): - - * the reference below, written from the RDNA2 ISA with Python integers: D = sum(S0.elem[k] * S1.elem[k]) + acc, - the exact sum taken modulo 2^32, or with `clamp` saturated to [-2^31, 2^31-1] (signed ops) or [0, 2^32-1] - (unsigned ops). It shares no code with the translator. tests/test_dot_diff.py checks it against the words - measured on RDNA2 hardware (gfx1036) in tests/semantic/test_alu_dot4_i8.py, and - * tools/rdna2spirv.py, executing the SPIR-V with tests/semantic/spirv_mini_interp.py. - -Program shape: seeds in v8..v15 and s4..s7, then the family ops, then `exp mrt0 v8, v9, v10, v11` so every result -is observed. Every op's destination is v8..v11, so later ops chain on earlier results, and an accumulating op reads -whatever an earlier op left in its destination. - -Sources, in every position the encoding allows: VGPR v8..v15, SGPR s4..s7, a hex literal (32 bits) and an integer -inline constant (-16..64), read as the 32-bit dword (positive values zero-extend, negative values sign-extend: the -rule docs/design.md measured for VOP3P integer constants). VOP3P programs stay encodable on GFX10: at most one -literal and at most two constant-bus reads (SGPRs plus the literal). VOP2 S1 is a VGPR; the gfx908 VOP3 (`_e64 ... -clamp`) forms take no literal. - -Modifiers: `clamp` on the VOP3P ops and on the gfx908 accumulating forms; `op_sel`/`op_sel_hi` on the S0 and S1 -halves of v_dot4_i32_i8 (measured on gfx1036: op_sel[k] picks the 16-bit half of source k for bytes 0..1, op_sel_hi[k] -for bytes 2..3); and the explicit default `op_sel:[0,0,0] op_sel_hi:[1,1,1]` on the other VOP3P ops, which the -translator must take as the plain instruction. - -Not generated, on purpose: `neg_lo`/`neg_hi` and source `neg`/`abs`, non-default op_sel outside v_dot4_i32_i8's S0/S1, -`clamp` on v_dot4c_i32_i8, and DPP/SDWA. The translator refuses each one; --self-test pins those rejections. Float -inline constants are left out too: no rule for them in a packed integer operand is recorded. - -Three stages run one after the other: - * a sweep: every op with every encodable source-kind combination, with and without clamp where the op takes it, - and all 16 op_sel/op_sel_hi settings of v_dot4_i32_i8, values drawn from element-edge words; - * an edge grid: every op with S0 and S1 from four words built of one lane width's extremes (all lanes the signed - minimum, all the signed maximum, all ones, minimum/maximum alternating) and eight accumulators on and next to - the saturation bounds, with and without clamp, four cases per program. It reaches the one point where the two - products of v_dot2_i32_i16 alone overflow, (-32768)^2 + (-32768)^2 = 2^31, which random values almost never hit; - * random programs (--programs), which widen the value coverage over the same space. - -The report counts, per op, how many clamped results actually saturated and how many unclamped ones wrapped, so a -run shows that it reached the edges. - -Usage: - python -I tools/dot_diff.py [--programs N] [--seed S] [--max-ops N] [--no-sweep] - python -I tools/dot_diff.py --ops v_dot4_i32_i8,v_dot4c_i32_i8 - python -I tools/dot_diff.py --list-ops - python -I tools/dot_diff.py --self-test - -Exit code 0 when every program matches, 1 on a mismatch (the first one is printed with its listing), 2 on a -harness error. Skips are counted with reasons and never silent. Nothing here reads game files. -""" -import argparse -import gc -import os -import random -import re -import struct -import sys -import tempfile -import warnings -from collections import Counter - -HERE = os.path.dirname(os.path.abspath(__file__)) -TOOLS_DIR = os.environ.get("LEONIDA_TOOLS_DIR") or HERE -sys.dont_write_bytecode = True -if TOOLS_DIR not in sys.path: - sys.path.insert(0, TOOLS_DIR) -SEM_DIR = os.path.join(os.path.dirname(HERE), "tests", "semantic") -if SEM_DIR not in sys.path: - sys.path.insert(0, SEM_DIR) - -import rdna2spirv # noqa: E402 -from spirv_mini_interp import UnsupportedConstruct, run_fragment # noqa: E402 - -M32 = 0xFFFFFFFF -STUB_DXBC = b"DXBC" + bytes(24) + struct.pack(" (element width, signed) -VOP3P_OPS = { - "v_dot2_i32_i16": (16, True), "v_dot2_u32_u16": (16, False), - "v_dot4_i32_i8": (8, True), "v_dot4_u32_u8": (8, False), - "v_dot8_i32_i4": (4, True), "v_dot8_u32_u4": (4, False), -} -ACC_OPS = { - "v_dot4c_i32_i8": (8, True), - "v_dot2c_i32_i16": (16, True), "v_dot2c_u32_u16": (16, False), "v_dot4c_u32_u8": (8, False), - "v_dot8c_i32_i4": (4, True), "v_dot8c_u32_u4": (4, False), -} -GFX103X_OPS = tuple(VOP3P_OPS) + ("v_dot4c_i32_i8",) -CLAMP_ACC_OPS = tuple(op for op in ACC_OPS if op != "v_dot4c_i32_i8") # the gfx908 VOP3 `_e64 ... clamp` forms -OPSEL_OPS = ("v_dot4_i32_i8",) -FAMILY = {**VOP3P_OPS, **ACC_OPS} -OP_FORMS = {op: f"{op} d, s0, s1, s2 [op_sel] [clamp]" for op in VOP3P_OPS} -OP_FORMS.update({op: f"{op}_e32 d, s0, v1 (acc = d)" for op in ACC_OPS}) -OP_FORMS.update({op: f"{op}_e32 d, s0, v1 | {op}_e64 d, s0, v1 clamp (acc = d)" for op in CLAMP_ACC_OPS}) -OP_FORMS = {op: OP_FORMS[op] for op in FAMILY} - -KINDS = ("vgpr", "sgpr", "lit", "inline") - -# Element-edge words: the extremes of each lane width (i16 -32768/32767, i8 -128/127, i4 -8/7, their unsigned -# maxima) and accumulators next to the signed and unsigned saturation bounds. -EDGE = (0x00000000, 0x00000001, 0xFFFFFFFF, 0x7FFFFFFF, 0x80000000, 0x7FFFFFFE, 0x80000001, 0xFFFFFFFE, - 0x80008000, 0x7FFF7FFF, 0x80007FFF, 0xFFFF0001, 0x0000FFFF, 0x00010001, 0x7FFF8000, 0x80010000, - 0x80808080, 0x7F7F7F7F, 0x807F807F, 0x01010101, 0xFF00FF00, 0x00FF00FF, - 0x88888888, 0x77777777, 0x87878787, 0x11111111, 0xF0F0F0F0, 0x0F0F0F0F, - 0x55555555, 0xAAAAAAAA, 0x01234567, 0x89ABCDEF) -INLINE = tuple(range(0, 65)) + tuple(range(-16, 0)) - - -class HarnessError(Exception): - pass - - -# ---- the reference, from the RDNA2 ISA ---- - -def elements(word, width, signed): - """The 32 // width lanes of a dword, lowest first, sign-extended for the signed ops.""" - out = [] - for off in range(0, 32, width): - e = (word >> off) & ((1 << width) - 1) - if signed and e >> (width - 1): - e -= 1 << width - out.append(e) - return out - - -def exact_dot(op, x, y, acc): - """The exact (unbounded) value of sum(S0.elem[k] * S1.elem[k]) + acc; acc is signed for the signed ops.""" - width, signed = FAMILY[op] - total = sum(p * q for p, q in zip(elements(x & M32, width, signed), elements(y & M32, width, signed))) - acc &= M32 - if signed and acc >> 31: - acc -= 1 << 32 - return total + acc - - -def dot(op, x, y, acc, clamp=False): - """The destination dword: the exact sum modulo 2^32, or saturated to the op's 32-bit range under clamp.""" - v = exact_dot(op, x, y, acc) - if clamp: - lo, hi = (-(1 << 31), (1 << 31) - 1) if FAMILY[op][1] else (0, M32) - v = max(lo, min(hi, v)) - return v & M32 - - -def select_halves(word, sel_lo, sel_hi): - """op_sel/op_sel_hi on a v_dot4_i32_i8 source: bytes 0..1 come from the half sel_lo picks, bytes 2..3 from the - half sel_hi picks.""" - half = lambda h: (word >> (16 * h)) & 0xFFFF # noqa: E731 - return half(sel_lo) | (half(sel_hi) << 16) - - -_REG = re.compile(r"([sv])(\d+)$") -_MOD = re.compile(r"\s+(op_sel_hi:\[[01],[01],[01]\]|op_sel:\[[01],[01],[01]\]|clamp)$") - - -def _word(tok, vgpr, sgpr): - """The 32-bit word a source token reads: a register, a hex literal, or an integer inline constant (two's - complement at 32 bits).""" - tok = tok.strip() - m = _REG.fullmatch(tok) - if m: - regs = vgpr if m.group(1) == "v" else sgpr - return regs.get(int(m.group(2)), 0) - if tok.lower().startswith("0x"): - return int(tok, 16) & M32 - if tok.lstrip("+-").isdigit(): - return int(tok, 10) & M32 - raise HarnessError(f"unknown source {tok!r}") - - -def _dst_index(dst): - m = _REG.fullmatch(dst.strip()) - if not m or m.group(1) != "v": - raise HarnessError(f"unknown destination {dst!r}") - return int(m.group(2)) - - -def split_line(line): - """(opcode without _e32/_e64, operand tokens, modifier dict) for one generated line.""" - mods = {} - body = line.rstrip() - while True: - m = _MOD.search(body) - if not m: - break - tok = m.group(1) - if tok == "clamp": - mods["clamp"] = True - else: - name, bits = tok.split(":") - mods[name] = tuple(int(b) for b in bits.strip("[]").split(",")) - body = body[:m.start()] - op, _, rest = body.partition(" ") - if op.endswith(("_e32", "_e64")): - op = op[:-4] - return op, [t.strip() for t in rest.split(",")], mods - - -def step(line, vgpr, sgpr, events=None): - """Execute one generated listing line on the reference's registers. `events` (a Counter), when given, counts - (op, "saturated") for a clamped result outside the 32-bit range and (op, "wrapped") for an unclamped one.""" - op, args, mods = split_line(line) - if op == "v_mov_b32": - vgpr[_dst_index(args[0])] = _word(args[1], vgpr, sgpr) - return - if op == "s_mov_b32": - if not args[0].startswith("s"): - raise HarnessError(line) - sgpr[int(args[0][1:])] = _word(args[1], vgpr, sgpr) - return - if op not in FAMILY: - raise HarnessError(line) - d = _dst_index(args[0]) - if op in VOP3P_OPS: - if len(args) != 4: - raise HarnessError(line) - x, y, acc = (_word(a, vgpr, sgpr) for a in args[1:]) - sel, selhi = mods.get("op_sel", (0, 0, 0)), mods.get("op_sel_hi", (1, 1, 1)) - if (sel, selhi) != ((0, 0, 0), (1, 1, 1)): - if op not in OPSEL_OPS or sel[2] != 0 or selhi[2] != 1: - raise HarnessError(f"op_sel outside the modelled forms: {line}") - x, y = select_halves(x, sel[0], selhi[0]), select_halves(y, sel[1], selhi[1]) - else: - if len(args) != 3: - raise HarnessError(line) - x, y = _word(args[1], vgpr, sgpr), _word(args[2], vgpr, sgpr) - acc = vgpr.get(d, 0) - clamp = mods.get("clamp", False) - if events is not None: - v = exact_dot(op, x, y, acc) - lo, hi = (-(1 << 31), (1 << 31) - 1) if FAMILY[op][1] else (0, M32) - if not lo <= v <= hi: - events[(op, "saturated" if clamp else "wrapped")] += 1 - vgpr[d] = dot(op, x, y, acc, clamp) - - -def reference(lines, events=None): - """The four exported mrt0 words the ISA gives for a program (seeds and ops; exp and s_endpgm are ignored).""" - vgpr, sgpr = {}, {} - for line in lines: - first = line.split()[0] - if first in ("exp", "s_endpgm"): - continue - step(line, vgpr, sgpr, events) - return [vgpr.get(r, 0) for r in EXPORT_REGS] - - -# ---- program generation ---- - -def _near_bound(rng): - """A word within a dot product's reach of a saturation bound (INT32_MAX, INT32_MIN, UINT32_MAX), so an - accumulator or a chained result can cross it: a 4-bit dot spans less than 2^9, an 8-bit one 2^18.""" - delta = rng.randrange(1 << rng.choice((4, 9, 13, 18, 31))) - bound = rng.choice((0x7FFFFFFF, 0x80000000, M32)) - return (bound + delta) & M32 if bound == 0x80000000 else (bound - delta) & M32 - - -def _seed_word(rng): - r = rng.random() - if r < 0.45: - return rng.choice(EDGE) - return _near_bound(rng) if r < 0.7 else rng.getrandbits(32) - - -def _source(rng, kind): - if kind == "vgpr": - return f"v{rng.randrange(8, 16)}" - if kind == "sgpr": - return f"s{rng.randrange(4, 8)}" - if kind == "lit": - return f"0x{_seed_word(rng):08x}" - return str(rng.choice(INLINE)) - - -def encodable(op, kinds, clamp=False): - """GFX10 VOP3P: at most one literal and two constant-bus reads. VOP2: S1 is a VGPR. The gfx908 VOP3 forms - (clamp on an accumulating op) take no literal.""" - if op in VOP3P_OPS: - return kinds.count("lit") <= 1 and kinds.count("lit") + kinds.count("sgpr") <= 2 - if kinds[1] != "vgpr": - return False - return not (clamp and kinds[0] == "lit") - - -def op_line(rng, op, kinds, clamp=False, sel=None): - """One family line with the given source kinds; sel = (op_sel, op_sel_hi) tuples or None.""" - srcs = [_source(rng, k) for k in kinds] - dst = f"v{rng.choice(EXPORT_REGS)}" - if op in VOP3P_OPS: - line = f"{op} {dst}, {', '.join(srcs)}" - if sel is not None: - line += " op_sel:[{},{},{}] op_sel_hi:[{},{},{}]".format(*sel[0], *sel[1]) - return line + (" clamp" if clamp else "") - if clamp: - return f"{op}_e64 {dst}, {srcs[0]}, {srcs[1]} clamp" - return f"{op}_e32 {dst}, {srcs[0]}, {srcs[1]}" - - -def _random_op(rng, op): - """(line) for one random use of op: encodable kinds, clamp where the op takes it, op_sel where measured.""" - clamp = (op in VOP3P_OPS or op in CLAMP_ACC_OPS) and rng.random() < 0.5 - n = 3 if op in VOP3P_OPS else 2 - while True: - kinds = tuple(rng.choice(KINDS) for _ in range(n)) - if encodable(op, kinds, clamp): - break - sel = None - if op in OPSEL_OPS and rng.random() < 0.4: - sel = ((rng.randrange(2), rng.randrange(2), 0), (rng.randrange(2), rng.randrange(2), 1)) - elif op in VOP3P_OPS and rng.random() < 0.1: - sel = ((0, 0, 0), (1, 1, 1)) - return op_line(rng, op, kinds, clamp, sel) - - -def seeds(rng): - lines = [f"v_mov_b32 v{r}, 0x{_seed_word(rng):08x}" for r in range(8, 16)] - lines += [f"s_mov_b32 s{r}, 0x{_seed_word(rng):08x}" for r in range(4, 8)] - return lines - - -def program(rng, n_ops, ops=None): - """One straight-line program: (lines, ops_used). Ops drawn from `ops` (default: the whole family).""" - ops = list(ops) if ops else list(FAMILY) - lines = seeds(rng) - used = Counter() - for _ in range(n_ops): - op = rng.choice(ops) - used[op] += 1 - lines.append(_random_op(rng, op)) - return lines, used - - -def sweep_ops(ops=None): - """Every op with every encodable source-kind combination, with and without clamp where the op takes it, plus - the 16 op_sel/op_sel_hi settings of v_dot4_i32_i8 (VGPR sources, with and without clamp). Returns a list of - (op, kinds, clamp, sel).""" - ops = list(ops) if ops else list(FAMILY) - cases = [] - for op in ops: - n = 3 if op in VOP3P_OPS else 2 - combos = [()] - for _ in range(n): - combos = [c + (k,) for c in combos for k in KINDS] - clamps = (False, True) if (op in VOP3P_OPS or op in CLAMP_ACC_OPS) else (False,) - for clamp in clamps: - for kinds in combos: - if encodable(op, kinds, clamp): - cases.append((op, kinds, clamp, None)) - if op in OPSEL_OPS: - for bits in range(16): - sel = ((bits & 1, (bits >> 1) & 1, 0), ((bits >> 2) & 1, (bits >> 3) & 1, 1)) - for clamp in (False, True): - cases.append((op, ("vgpr", "vgpr", "vgpr"), clamp, sel)) - return cases - - -def sweep_program(op, kinds, clamp, sel, rng): - """One sweep program: seeds, then the op once.""" - return seeds(rng) + [op_line(rng, op, kinds, clamp, sel)] - - -def lane_edges(width): - """Four dwords made of one lane width's extremes: every lane the signed minimum (0x8000, 0x80, 0x8), every lane - the signed maximum, every lane all ones, and minimum/maximum alternating.""" - smin, smax = 1 << (width - 1), (1 << (width - 1)) - 1 - rep = lambda lane: sum(lane << off for off in range(0, 32, width)) # noqa: E731 - alt = sum((smin if (off // width) % 2 == 0 else smax) << off for off in range(0, 32, width)) - return (rep(smin), rep(smax), rep((1 << width) - 1), alt) - - -# Accumulators on and next to the saturation bounds; 256 is inside every lane width's reach (a 4-bit dot spans 512). -ACC_EDGES = (0, 1, M32, 0x7FFFFFFF, 0x80000000, 0x7FFFFF00, 0x80000100, 0xFFFFFF00) -GRID_PER_PROGRAM = 4 - - -def grid_cases(ops=None): - """The edge grid: every op with every pair of lane_edges words as S0/S1, every ACC_EDGES accumulator, with and - without clamp where the op takes it. Returns a list of (op, x, y, acc, clamp).""" - ops = list(ops) if ops else list(FAMILY) - cases = [] - for op in ops: - words = lane_edges(FAMILY[op][0]) - clamps = (False, True) if (op in VOP3P_OPS or op in CLAMP_ACC_OPS) else (False,) - cases += [(op, x, y, acc, clamp) for clamp in clamps for x in words for y in words for acc in ACC_EDGES] - return cases - - -def grid_program(chunk): - """Up to four grid cases in one program: each loads its operands into v12..v14 (the accumulating forms load the - accumulator into their destination) and writes its own exported register v8..v11.""" - lines = [] - for (op, x, y, acc, clamp), dst in zip(chunk, EXPORT_REGS): - lines += [f"v_mov_b32 v12, 0x{x:08x}", f"v_mov_b32 v13, 0x{y:08x}"] - if op in VOP3P_OPS: - lines += [f"v_mov_b32 v14, 0x{acc:08x}", f"{op} v{dst}, v12, v13, v14" + (" clamp" if clamp else "")] - else: - suffix = "_e64" if clamp else "_e32" - lines += [f"v_mov_b32 v{dst}, 0x{acc:08x}", f"{op}{suffix} v{dst}, v12, v13" + (" clamp" if clamp else "")] - return lines - - -# ---- the translator oracle ---- - -def write_listing(path, lines, name): - with open(path, "w", encoding="utf-8", newline="\n") as f: - f.write(f"; {name} code 0x0..0x1000\n") - for line in lines: - f.write("\t" + line + "\n") - f.write("\t" + EXPORT + "\n") - f.write("\ts_endpgm\n") - - -def translate_listing(lines, name, tmpdir): - """The four mrt0 words the translator path produces. Raises rdna2spirv.Unsupported (and the mini interp's - UnsupportedConstruct) for anything outside the oracles' model.""" - dis = os.path.join(tmpdir, "disasm") - os.makedirs(dis, exist_ok=True) - path = os.path.join(dis, name + ".s") - write_listing(path, lines, name) - with open(os.path.join(tmpdir, name + ".dxbc"), "wb") as f: - f.write(STUB_DXBC) - with warnings.catch_warnings(): - warnings.simplefilter("ignore", ResourceWarning) - spvasm = rdna2spirv.translate(path) - gc.collect() - out = run_fragment(spvasm) - if list(out) != ["%out_mrt0"]: - raise HarnessError(f"outputs {sorted(out)}, want %out_mrt0") - return [w & M32 for w in out["%out_mrt0"]] - - -def check(lines, name="ps_dot_case"): - """None when both oracles agree, else the first differing word with both values.""" - with tempfile.TemporaryDirectory(prefix="dot-diff-") as tmp: - want = reference(lines) - got = translate_listing(lines, name, tmp) - for i, (w, g) in enumerate(zip(want, got)): - if w != (g & M32): - return f"word {i} (v{EXPORT_REGS[i]}): expected 0x{w:08x}, actual 0x{g:08x}" - return None - - -def run_one(lines, name, tmpdir, events=None): - """(status, detail) with status in {"match", "mismatch", "skip"}.""" - try: - want = reference(lines, events) - except HarnessError as e: - return ("skip", f"reference cannot run the program: {e}") - try: - got = translate_listing(lines, name, tmpdir) - except (rdna2spirv.Unsupported, UnsupportedConstruct) as e: - return ("skip", f"{type(e).__name__}: {e}") - except (IndexError, KeyError, ValueError) as e: - return ("skip", f"translator error {type(e).__name__}: {e}") - for i, (w, g) in enumerate(zip(want, got)): - if w != (g & M32): - return ("mismatch", f"word {i} (v{EXPORT_REGS[i]}): expected 0x{w:08x}, actual 0x{g:08x}") - return ("match", "") - - -# ---- the suites ---- - -def _new_counts(): - return {"pass": 0, "mismatch": 0, "skip": Counter(), "ops": Counter(), "events": Counter()} - - -def _tally(counts, status, detail): - if status == "match": - counts["pass"] += 1 - elif status == "skip": - counts["skip"][detail] += 1 - else: - counts["mismatch"] += 1 - - -def run_sweep(seed, ops=None): - """Every case of sweep_ops, one program each. Returns (counts, failure).""" - counts = _new_counts() - failure = None - with tempfile.TemporaryDirectory(prefix="dot-diff-sweep-") as tmp: - for i, (op, kinds, clamp, sel) in enumerate(sweep_ops(ops)): - tag = f"{op}:{'/'.join(kinds)}:{int(clamp)}:{sel}" - lines = sweep_program(op, kinds, clamp, sel, random.Random(f"{seed}:{tag}")) - counts["ops"][op] += 1 - status, detail = run_one(lines, f"ps_dot_sw{i:04d}", tmp, counts["events"]) - _tally(counts, status, detail) - if status == "mismatch" and failure is None: - failure = (f"sweep {tag} (case {i}, seed {seed})", lines, detail) - return counts, failure - - -def run_grid(ops=None): - """The edge grid, GRID_PER_PROGRAM cases per program. Returns (counts, failure); counts["ops"] counts cases.""" - counts = _new_counts() - failure = None - cases = grid_cases(ops) - with tempfile.TemporaryDirectory(prefix="dot-diff-grid-") as tmp: - for i in range(0, len(cases), GRID_PER_PROGRAM): - chunk = cases[i:i + GRID_PER_PROGRAM] - lines = grid_program(chunk) - counts["ops"].update(op for op, *_ in chunk) - status, detail = run_one(lines, f"ps_dot_gr{i // GRID_PER_PROGRAM:04d}", tmp, counts["events"]) - _tally(counts, status, detail) - if status == "mismatch" and failure is None: - failure = (f"edge grid program {i // GRID_PER_PROGRAM}", lines, detail) - return counts, failure - - -def run_suite(programs, seed, max_ops=6, ops=None): - """Random seeded programs. Returns (counts, failure).""" - counts = _new_counts() - failure = None - rng = random.Random(f"suite:{seed}") - with tempfile.TemporaryDirectory(prefix="dot-diff-run-") as tmp: - for i in range(programs): - lines, used = program(rng, rng.randint(1, max_ops), ops) - counts["ops"].update(used) - status, detail = run_one(lines, f"ps_dot_{i:04d}", tmp, counts["events"]) - _tally(counts, status, detail) - if status == "mismatch" and failure is None: - failure = (f"program {i} (seed {seed})", lines, detail) - return counts, failure - - -REJECTED = ( - ("non-default op_sel on v_dot2_i32_i16", "v_dot2_i32_i16 v8, v9, v10, v11 op_sel:[1,0,0] op_sel_hi:[1,1,1]"), - ("op_sel_hi:[0,0,0] on v_dot2_u32_u16", "v_dot2_u32_u16 v8, v9, v10, v11 op_sel:[0,0,0] op_sel_hi:[0,0,0]"), - ("an S2 half select on v_dot4_i32_i8", "v_dot4_i32_i8 v8, v9, v10, v11 op_sel:[0,0,1] op_sel_hi:[1,1,1]"), - ("neg_lo on v_dot4_i32_i8", "v_dot4_i32_i8 v8, v9, v10, v11 neg_lo:[1,0,0]"), - ("neg_hi on v_dot8_i32_i4", "v_dot8_i32_i4 v8, v9, v10, v11 neg_hi:[0,1,0]"), - ("source neg on v_dot4_u32_u8", "v_dot4_u32_u8 v8, -v9, v10, v11"), - ("clamp on v_dot4c_i32_i8", "v_dot4c_i32_i8_e64 v8, v9, v10 clamp"), - ("source abs on v_dot2c_i32_i16", "v_dot2c_i32_i16_e64 v8, |v9|, v10"), - ("op_sel on v_dot8c_u32_u4", "v_dot8c_u32_u4_e64 v8, v9, v10 op_sel:[0,0,0]"), -) - - -def self_test(): - """True when the reference's hand-pinned words, the rejected forms and the harness canaries all hold.""" - ok = True - - def expect(cond, what): - nonlocal ok - print(("ok " if cond else "FAIL ") + what) - ok = ok and cond - - # Hand-pinned reference words, each derived from the ISA rule in the docstring. - expect(dot("v_dot2_i32_i16", 0x80008000, 0x80008000, 0) == 0x80000000, - "v_dot2_i32_i16: (-32768)^2 * 2 = 2^31 wraps to 0x80000000") - expect(dot("v_dot2_i32_i16", 0x80008000, 0x80008000, 0, clamp=True) == 0x7FFFFFFF, - "v_dot2_i32_i16 clamp: 2^31 saturates to 0x7fffffff") - expect(dot("v_dot2_i32_i16", 0x80008000, 0x80008000, 0x80000000, clamp=True) == 0, - "v_dot2_i32_i16 clamp: 2^31 + INT32_MIN = 0, the products' overflow cancels (no early saturation)") - expect(dot("v_dot2_u32_u16", M32, M32, 0) == 0xFFFC0002, - "v_dot2_u32_u16: 2 * 65535^2 = 0x1fffc0002 wraps to 0xfffc0002") - expect(dot("v_dot2_u32_u16", M32, M32, 0, clamp=True) == M32, "v_dot2_u32_u16 clamp saturates to 0xffffffff") - expect(dot("v_dot4_u32_u8", M32, M32, 5) == 4 * 255 * 255 + 5, "v_dot4_u32_u8: 4 * 255^2 + 5") - expect(dot("v_dot4_i32_i8", 0x7F7F7F7F, 0x7F7F7F7F, 0x7FFFFFFF) == 0x8000FC03, - "v_dot4_i32_i8 wraps upward without clamp (the gfx1036 word 0x8000fc03)") - expect(dot("v_dot4_i32_i8", 0x7F7F7F7F, 0x7F7F7F7F, 0x7FFFFFFF, clamp=True) == 0x7FFFFFFF, - "v_dot4_i32_i8 clamp saturates the same sum") - expect(dot("v_dot8_i32_i4", 0x88888888, 0x88888888, 0) == 8 * 64, "v_dot8_i32_i4: 8 * (-8)^2 = 512") - expect(dot("v_dot8_u32_u4", M32, M32, 0) == 8 * 225, "v_dot8_u32_u4: 8 * 15^2 = 1800") - expect(dot("v_dot8_i32_i4", 0x77777777, 0x88888888, 0x80000000, clamp=True) == 0x80000000, - "v_dot8_i32_i4 clamp: INT32_MIN - 448 saturates to 0x80000000") - # op_sel 2 / op_sel_hi 5 exchanges S1's halves (the gfx1036-measured form): 0x00050000 reads as 5. - expect(reference(["v_mov_b32 v9, 1", "v_mov_b32 v10, 0x00050000", - "v_dot4_i32_i8 v8, v9, v10, 0 op_sel:[0,1,0] op_sel_hi:[1,0,1]"])[0] == 5, - "v_dot4_i32_i8 op_sel:[0,1,0] op_sel_hi:[1,0,1] swaps S1's 16-bit halves") - # The accumulating form reads its old destination. - expect(reference(["v_mov_b32 v8, 100", "v_mov_b32 v9, 0x01020304", "v_mov_b32 v10, 0x05060708", - "v_dot4c_i32_i8_e32 v8, v9, v10"])[0] == 170, "v_dot4c_i32_i8: 70 + old D 100") - # A negative inline constant is the sign-extended dword (four -1 bytes), a positive one zero-extends. - expect(reference(["v_mov_b32 v9, 0x01010101", "v_dot4_i32_i8 v8, v9, -1, 0"])[0] == M32 - 3, - "the inline constant -1 reads as 0xffffffff (four -1 bytes: -4)") - expect(reference(["v_mov_b32 v9, 0x01010101", "v_dot4_i32_i8 v8, v9, 5, 0"])[0] == 5, - "the inline constant 5 reads as 0x00000005") - - # The two-oracle path agrees on a fixed program, and a sabotaged word is caught. - lines = ["v_mov_b32 v8, 0x80008000", "v_mov_b32 v9, 0x80008000", "v_mov_b32 v10, 0x80000000", - "v_dot2_i32_i16 v11, v8, v9, v10 clamp"] - expect(check(lines) is None, "a hand-pinned clamp program matches on both oracles") - real = translate_listing - try: - globals()["translate_listing"] = lambda l, n, t: real(l, n, t)[:3] + [1] - expect(check(lines) is not None, "a sabotaged export word is reported") - finally: - globals()["translate_listing"] = real - - # Forms the contract rows say are refused, not guessed. - with tempfile.TemporaryDirectory(prefix="dot-diff-neg-") as tmp: - for what, bad in REJECTED: - try: - translate_listing(["v_mov_b32 v9, 1", "v_mov_b32 v10, 2", bad], "ps_dot_neg", tmp) - expect(False, f"{what}: the translator rejected it") - except (rdna2spirv.Unsupported, UnsupportedConstruct): - expect(True, f"{what}: the translator rejected it") - - # Determinism: the same seed gives the same program stream. - expect(program(random.Random(9), 4) == program(random.Random(9), 4), "generation is deterministic for a seed") - counts, failure = run_suite(8, 3, 3) - expect(failure is None and counts["pass"] == 8 and not counts["skip"], - f"a short seeded run matches ({counts['pass']} programs, skips {dict(counts['skip'])})") - return ok - - -def main(): - ap = argparse.ArgumentParser(description=__doc__.splitlines()[0], - formatter_class=argparse.RawDescriptionHelpFormatter) - ap.add_argument("--programs", type=int, default=300, help="random programs after the sweep") - ap.add_argument("--seed", type=int, default=1) - ap.add_argument("--max-ops", type=int, default=6, help="ops per random program") - ap.add_argument("--ops", default=None, help="comma-separated opcodes to cover (default: all twelve; " - "'gfx103x' selects the seven gfx103x encodings)") - ap.add_argument("--no-sweep", action="store_true", help="skip the source-kind sweep and the edge grid") - ap.add_argument("--list-ops", action="store_true") - ap.add_argument("--self-test", action="store_true") - args = ap.parse_args() - - if args.list_ops: - for op, form in OP_FORMS.items(): - tag = "gfx103x" if op in GFX103X_OPS else "gfx908 syntax" - print(f"{op:18s} {tag:14s} {form}") - return 0 - if args.self_test: - return 0 if self_test() else 1 - - if args.ops == "gfx103x": - ops = list(GFX103X_OPS) - else: - ops = [o.strip() for o in args.ops.split(",")] if args.ops else None - bad = [o for o in (ops or []) if o not in FAMILY] - if bad: - print(f"unknown op(s) {bad}; --list-ops shows the family", file=sys.stderr) - return 2 - - total_pass = total_run = total_mismatch = 0 - per_op, events = Counter(), Counter() - failure = None - try: - for label, enabled, runner in ( - ("sweep", not args.no_sweep, lambda: run_sweep(args.seed, ops)), - ("edge grid", not args.no_sweep, lambda: run_grid(ops)), - ("random", True, lambda: run_suite(args.programs, args.seed, args.max_ops, ops)), - ): - if not enabled: - continue - counts, first = runner() - ran = counts["pass"] + counts["mismatch"] + sum(counts["skip"].values()) - total_pass += counts["pass"] - total_mismatch += counts["mismatch"] - total_run += ran - per_op.update(counts["ops"]) - events.update(counts["events"]) - print(f"{label}: {counts['pass']}/{ran} programs match, {counts['mismatch']} mismatch; " - f"skips: {dict(counts['skip'])}") - failure = failure or first - except HarnessError as e: - print(f"harness error: {e}", file=sys.stderr) - return 2 - print("cases per op: " + ", ".join(f"{op} {per_op[op]}" for op in sorted(per_op))) - print("results outside the 32-bit range (saturated under clamp / wrapped without): " + ", ".join( - f"{op} {events[(op, 'saturated')]}/{events[(op, 'wrapped')]}" for op in sorted(per_op))) - print(f"dot family: {total_pass}/{total_run} programs match, {total_mismatch} mismatch " - f"({len(per_op)} of {len(FAMILY)} ops)") - if failure: - _report(failure) - return 1 - return 0 - - -def _report(failure): - name, lines, detail = failure - print(f"MISMATCH {name}: {detail}") - print("program:") - for line in lines: - print(" " + line) - - -if __name__ == "__main__": - try: # a redirected stdout is strict ANSI code page under -I; write '?' for what it cannot encode - sys.stdout.reconfigure(errors="replace") - except (AttributeError, ValueError, OSError): - pass - sys.exit(main()) diff --git a/tools/draw_ownership.py b/tools/draw_ownership.py deleted file mode 100644 index dbb224174..000000000 --- a/tools/draw_ownership.py +++ /dev/null @@ -1,261 +0,0 @@ -"""ASSET-70 draw-ownership tool: system-segment pointer layers, synthetically tested. - -ASSET-70 tooling; used by the draw-ownership measurement campaign. - -The pointer schema follows `tools/meshlet_page.py`'s `drawable_geometries()` and -`draw_binding()` with unchanged semantics (system pointers are 0x50000000-based, -graphics pointers are 0x60000000-based): - - drawable+80 -> LOD record (16B) - LOD+8 -> used/capacity u16 pair; used == capacity, 1..256 - LOD+0 -> 8B model-pointer table (8 * used bytes) - model+16 -> used/capacity u16 pair (geometry count) - model+54 -> u16; must match the model+16 number - model+8 -> 8B geometry-pointer entries table - geometry -> 160B record: +8 -> vertex-buffer record (80B: +8 count u32 / - stride u16, +24 -> GRAPHICS pointer), vb+64 -> vertex-layout - (320B), geometry+64 -> meshlet descriptor (16B: +0 -> 64B - index-buffer record; +8 meshlets u16 / triangles u16 / binding u32) - -Layers: - walk_chain / walk_drawable walk the regular drawable -> LOD -> model -> geometry - chain; a schema violation raises a WalkError subclass - carrying the concrete reason (used != capacity, a - model+54 contradiction, a pointer outside the segment). - reverse_pointers read a u64 at every 8-byte-aligned position; every value - that is 0x50000000-based and points into the segment - becomes an edge, and the edges build a reverse index - (target -> source positions). - classify_parent classify the source records that point at one - geometry-entries table by the shape of the record - ("model-compatible" / "unknown parent"), with a 32-byte - hex dump of each source. - geometry_shape_check the system-side half of the geometry record (the part of - draw_binding that needs no graphics segment). - -Tested on synthetic bytes only (tests/test_draw_ownership.py); it reads no real game data. -""" - -import struct - -PTR_BASE = 0x50000000 -GRAPHICS_BASE = 0x60000000 - - -class WalkError(Exception): - """A schema violation in the drawable chain or the geometry shape; the message gives the concrete reason.""" - - -class OutOfSegmentError(WalkError): - """A pointer field, pointer target or record does not fit in the system segment.""" - - -class CountError(WalkError): - """A used/capacity u16 pair violates the schema (used != capacity, or used not in 1..256).""" - - -class ModelCountMismatchError(WalkError): - """The model+16 used/capacity pair and the model+54 u16 contradict each other.""" - - -def _u16(system, at): - if not 0 <= at <= len(system) - 2: - raise OutOfSegmentError(f"u16 field outside the segment: +0x{at:x}") - return struct.unpack_from(" LOD -> model -> geometry chain. - - Returns the whole chain: {"drawable": ..., "lod": ..., - "models": [{"model": ..., "entries": ..., "geometries": [...]}, ...]}. - A schema violation raises a WalkError subclass with the concrete reason. - """ - if not 0 <= drawable_off <= len(system) - 176: - raise OutOfSegmentError( - f"drawable +0x{drawable_off:x} falls outside the {len(system)}-byte system segment (176 B needed)") - lod = _system_pointer(system, drawable_off + 80, 16, "LOD") - models_n = _count(system, lod + 8, f"LOD +0x{lod:x}") - table = _system_pointer(system, lod, 8 * models_n, "model-pointer table") - models = [] - for i in range(models_n): - model = _system_pointer(system, table + 8 * i, 56, "model record") - geo_n = _count(system, model + 16, f"model +0x{model:x}") - at54 = _u16(system, model + 54) - if at54 != geo_n: - raise ModelCountMismatchError( - f"model +0x{model:x}: the geometry count in the +16 used/capacity pair is {geo_n}, " - f"but the +54 u16 is {at54}") - entries = _system_pointer(system, model + 8, 8 * geo_n, "geometry-entries table") - geometries = [_system_pointer(system, entries + 8 * j, 160, "geometry record") - for j in range(geo_n)] - models.append({"model": model, "entries": entries, "geometries": geometries}) - return {"drawable": drawable_off, "lod": lod, "models": models} - - -def walk_drawable(system, drawable_off): - """Enumerate the geometry offsets of the drawable's primary LOD (a generator). - - Exactly the schema of meshlet_page.drawable_geometries(); on a violation it raises - a WalkError subclass (used != capacity, a model+54 contradiction, a pointer outside - the segment). - """ - for model in walk_chain(system, drawable_off)["models"]: - yield from model["geometries"] - - -def reverse_pointers(system): - """Reverse pointer analysis: read a u64 at every 8-byte-aligned position. - - Every value that is 0x50000000-based and points into the segment - (0x50000000 <= value < 0x50000000 + len(system)) becomes an edge (source position -> - target offset). Graphics pointers (0x60000000-based) and zeroes give no edge. - Returns the reverse index: {target offset: [source positions, in ascending order]}. - """ - index = {} - low, high = PTR_BASE, PTR_BASE + len(system) - unpack = struct.Struct(" sources) this finds the source positions that - point at the table, and classifies each by the shape of the source record: - - "model-compatible": the source corresponds to a model+8 field — the record at - source-8 has a schema-shaped +16 used/capacity pair (used == capacity, 1..256) - and its +54 u16 gives the same number; - - "unknown parent": every other source-record shape. - Each candidate gets a 32-byte hex dump from its surroundings. - - A reverse_pointers() index can be passed as `index`; when it is missing the tool - builds one itself. Returns a list of {source, target, classification, ...} records, - in ascending order of source position. - """ - if index is None: - index = reverse_pointers(system) - out = [] - for src in index.get(entries_table_off, []): - rec = {"source": src, "target": entries_table_off} - model = src - 8 - if model >= 0 and model + 56 <= len(system): - used, capacity = struct.unpack_from(">10 from the +0x138), meshlet descriptor (16B: - meshlets/triangles/refs non-zero, the binding's top bit zero) and index buffer - (64B, stride 4, at least 12 bytes). It only reports the +24 graphics pointers by - their base (whether they are 0x60000000-based); the 0x4042 / group header magics - cannot be checked without the graphics segment. A schema violation raises WalkError. - """ - if not 0 <= geometry_off <= len(system) - 160: - raise OutOfSegmentError( - f"geometry +0x{geometry_off:x} falls outside the {len(system)}-byte segment (160 B needed)") - vb = _system_pointer(system, geometry_off + 8, 80, "vertex-buffer record") - layout = _system_pointer(system, vb + 64, 320, "vertex-layout") - descriptor = _system_pointer(system, geometry_off + 64, 16, "meshlet descriptor") - ib = _system_pointer(system, descriptor, 64, "index-buffer record") - for field_at, what in ((vb + 24, "vertex-buffer"), (ib + 24, "index-buffer")): - if struct.unpack_from("> 10 - if (not flags & 1 or not vertices or _u32(system, layout) != 128 - or system[layout + 0xD0] != 8 or system[layout + 0x104] != 16 - or vcount * vstride < 128 + vertices * 8): - raise WalkError(f"vertex-layout +0x{layout:x}: unsupported format or position extent " - f"(flags=0x{flags:x})") - meshlets, triangles, binding = struct.unpack_from("> 8) & 0x7FFFFF - icount, istride = struct.unpack_from("> 31 or not (meshlets and triangles and refs): - raise WalkError(f"meshlet descriptor +0x{descriptor:x}: invalid or unsupported binding " - f"(meshlets={meshlets}, triangles={triangles}, " - f"refs={refs}, index-buffer stride={istride})") - return {"geometry": geometry_off, "vertex_buffer": vb, "vertex_layout": layout, - "descriptor": descriptor, "index_buffer": ib, "vertices": vertices, - "vertex_count": vcount, "vertex_stride": vstride, - "meshlets": meshlets, "triangles": triangles, "refs": refs} diff --git a/tools/ds_permute_probe.py b/tools/ds_permute_probe.py deleted file mode 100644 index 9d1d460e7..000000000 --- a/tools/ds_permute_probe.py +++ /dev/null @@ -1,258 +0,0 @@ -r"""Measure RDNA2 (GFX10) `ds_permute_b32` natively via `tools/hw_oracle` (SHADER-133). - -Covers collisions (2-way, 4-way, 32-way, and with the highest lane masked off in EXEC), unaddressed active -destination lanes, EXEC off on source and destination, `offset:` addition and low-bit carry (`((vAddr + offset) ->> 2) mod 32`), wave64 independent 32-lane halves, and partial waves (20 threads in wave32, 40 in wave64). - -Usage: - python -I tools/ds_permute_probe.py [--waves 32,64] [--json out.json] - python -I tools/ds_permute_probe.py --self-test # pure-Python model checks, no GPU - -Exit 0 when every case matches the RDNA2 model (or --self-test passed), 1 on a mismatch or report write error, -2 on a harness or CLI error, 77 when tools/hw_oracle is unavailable or the GPU is not GFX10. Standard library only; -nothing here reads game files. -""" -import argparse -import json -import os -import sys - -HERE = os.path.dirname(os.path.abspath(__file__)) -sys.dont_write_bytecode = True -if HERE not in sys.path: - sys.path.insert(0, HERE) - -SENTINEL = 0xCAFE0000 -PAYLOAD_BASE = 0x1000 - - -def model_ds_permute(wave, addrs, exec_mask, offset=0, threads=None): - """RDNA2 hardware model for ds_permute_b32 (wave32 or wave64). - - Wave64 runs as two independent 32-lane halves. Within each half: - - active source lane i sends (PAYLOAD_BASE + lane) to target ((addrs[lane] + offset) >> 2) % 32 - - on a collision, the highest-numbered active lane in the half wins - - unaddressed active destination lanes receive 0 - - inactive destination lanes keep SENTINEL | lane - - lanes >= threads do not execute (initial EXEC bit is 0) - """ - if threads is None: - threads = wave - live_mask = ((1 << threads) - 1) & exec_mask - out = [SENTINEL | l for l in range(wave)] - for base in range(0, wave, 32): - tmp = [0] * 32 - for i in range(32): - lane = base + i - if (live_mask >> lane) & 1: - dst = ((addrs[lane] + offset) >> 2) & 31 - tmp[dst] = PAYLOAD_BASE + lane - for i in range(32): - lane = base + i - if (live_mask >> lane) & 1: - out[lane] = tmp[i] - return out - - -def _make_kernel(asm_mod, body_lines, wave, threads=None): - if threads is None: - threads = wave - restore = "s_mov_b32 exec_lo, 0xffffffff" if wave == 32 else "s_mov_b64 exec, -1" - lines = [ - f"v_or_b32 v10, 0x{SENTINEL:x}, v0", - f"v_add_nc_u32 v2, 0x{PAYLOAD_BASE:x}, v0", - ] + body_lines + [ - restore, - "v_lshlrev_b32 v11, 2, v0", - "global_store_b32 v11, v10, s[2:3]", - "s_waitcnt_vscnt null, 0x0", - "s_endpgm", - ] - return asm_mod.Kernel(lines, wave, threads, wave, raw=True, vgprs=16, sgprs=16) - - -def build_cases(wave): - """List of (name, body_lines, addrs, exec_mask, offset, threads) for wave32 or wave64.""" - full_mask = (1 << wave) - 1 - mask_no_lo8 = 0xFFFFFF00 if wave == 32 else ((0xFFFFFF00 << 32) | 0xFFFFFF00) - mask_no_top = 0x7FFFFFFF if wave == 32 else ((0x7FFFFFFF << 32) | 0x7FFFFFFF) - exec_no_lo8 = (["s_mov_b32 exec_lo, 0xffffff00"] if wave == 32 - else ["s_mov_b32 exec_lo, 0xffffff00", "s_mov_b32 exec_hi, 0xffffff00"]) - exec_no_top = (["s_mov_b32 exec_lo, 0x7fffffff"] if wave == 32 - else ["s_mov_b32 exec_lo, 0x7fffffff", "s_mov_b32 exec_hi, 0x7fffffff"]) - part_threads = 20 if wave == 32 else 40 - return [ - ("rot_plus1_offset4_lowbits", - ["v_lshlrev_b32 v3, 2, v0", "v_and_b32 v4, 3, v0", "v_or_b32 v3, v3, v4", - "ds_permute_b32 v10, v3, v2 offset:4", "s_waitcnt lgkmcnt(0)"], - [(l << 2) | (l & 3) for l in range(wave)], full_mask, 4, wave), - ("offset_lowbit_carry", - ["v_mov_b32 v3, 3", "ds_permute_b32 v10, v3, v2 offset:1", "s_waitcnt lgkmcnt(0)"], - [3] * wave, full_mask, 1, wave), - ("unaddressed_odd_and_2way_collision", - ["v_and_b32 v3, 0xfffffffe, v0", "v_lshlrev_b32 v3, 2, v3", - "ds_permute_b32 v10, v3, v2", "s_waitcnt lgkmcnt(0)"], - [(l & ~1) << 2 for l in range(wave)], full_mask, 0, wave), - ("collision_4way", - ["v_and_b32 v3, 0xfffffffc, v0", "v_lshlrev_b32 v3, 2, v3", - "ds_permute_b32 v10, v3, v2", "s_waitcnt lgkmcnt(0)"], - [(l & ~3) << 2 for l in range(wave)], full_mask, 0, wave), - ("collision_all_to_0", - ["v_mov_b32 v3, 0", "ds_permute_b32 v10, v3, v2", "s_waitcnt lgkmcnt(0)"], - [0] * wave, full_mask, 0, wave), - ("collision_all_to_0_top_off", - exec_no_top + ["v_mov_b32 v3, 0", "ds_permute_b32 v10, v3, v2", "s_waitcnt lgkmcnt(0)"], - [0] * wave, mask_no_top, 0, wave), - ("exec_off_src_and_dst", - exec_no_lo8 + ["v_lshlrev_b32 v3, 2, v0", "ds_permute_b32 v10, v3, v2 offset:4", "s_waitcnt lgkmcnt(0)"], - [l << 2 for l in range(wave)], mask_no_lo8, 4, wave), - ("addr_plus32_wrap_halves", - ["v_add_nc_u32 v3, 32, v0", "v_lshlrev_b32 v3, 2, v3", - "ds_permute_b32 v10, v3, v2", "s_waitcnt lgkmcnt(0)"], - [(l + 32) << 2 for l in range(wave)], full_mask, 0, wave), - ("partial_wave", - ["v_lshlrev_b32 v3, 2, v0", "ds_permute_b32 v10, v3, v2 offset:4", "s_waitcnt lgkmcnt(0)"], - [l << 2 for l in range(wave)], full_mask, 4, part_threads), - ] - - -def probe_wave(oracle, asm_mod, wave): - cases = build_cases(wave) - kernels = [_make_kernel(asm_mod, body, wave, threads) for _, body, _, _, _, threads in cases] - results = oracle.run(kernels, words=wave) - report = {} - ok = 0 - for (name, _, addrs, exec_mask, offset, threads), got in zip(cases, results): - if isinstance(got, str) or len(got) < threads: - raise RuntimeError(f"{name} wave{wave}: {got}") - want = model_ds_permute(wave, addrs, exec_mask, offset, threads) - # Only check running lanes 0..threads-1 (lanes >= threads did not execute global_store_b32). - diffs = [{"lane": i, "hw": f"{got[i]:#x}", "want": f"{want[i]:#x}"} - for i in range(threads) if got[i] != want[i]] - if not diffs: - ok += 1 - report[name] = {"lanes_checked": threads, "mismatches": len(diffs), "first_diffs": diffs[:4]} - return {"cases_total": len(cases), "cases_ok": ok, "cases": report} - - -def self_test(): - # Wave32: all-to-0 collision -> highest lane 31 wins; lane 1..31 unaddressed -> 0 - w32 = model_ds_permute(32, [0] * 32, 0xFFFFFFFF) - assert w32[0] == PAYLOAD_BASE + 31 and all(w == 0 for w in w32[1:]) - # Wave64: two independent halves, +32 wrap keeps each lane in its own half - w64 = model_ds_permute(64, [(l + 32) << 2 for l in range(64)], (1 << 64) - 1) - assert w64 == [PAYLOAD_BASE + l for l in range(64)] - # EXEC off on destination keeps SENTINEL|lane, off source leaves target 0 - w32_e = model_ds_permute(32, [l << 2 for l in range(32)], 0xFFFFFF00, offset=4) - assert w32_e[0] == (SENTINEL | 0) and w32_e[8] == 0 and w32_e[9] == PAYLOAD_BASE + 8 - # Low-bit carry: (3 + 1) >> 2 == 1 - w32_c = model_ds_permute(32, [3] * 32, 0xFFFFFFFF, offset=1) - assert w32_c[1] == PAYLOAD_BASE + 31 and w32_c[0] == 0 - # Partial wave64 (40 threads): low half wraps, high half lane 32 gets 0 - w64_p = model_ds_permute(64, [l << 2 for l in range(64)], (1 << 64) - 1, offset=4, threads=40) - assert w64_p[0] == PAYLOAD_BASE + 31 and w64_p[32] == 0 and w64_p[33] == PAYLOAD_BASE + 32 - print("self-test OK") - - -def parse_waves(text): - """Parse --waves comma-separated list into [32|64, ...], or raise ValueError.""" - tokens = [t.strip() for t in text.split(",") if t.strip()] - if not tokens: - raise ValueError("--waves must not be empty") - waves = [] - for tok in tokens: - try: - w = int(tok) - except ValueError: - raise ValueError(f"invalid wave size {tok!r}; expected 32 or 64") from None - if w not in (32, 64): - raise ValueError(f"unsupported wave size {w}; expected 32 or 64") - waves.append(w) - return waves - - -def validate_json_path(path): - """Return an error string if `path` cannot be used as a --json output file, or None.""" - if not path or not path.strip(): - return "--json path must not be empty" - if "\x00" in path: - return "--json path contains a NUL byte" - if path.endswith(os.sep) or (os.altsep and path.endswith(os.altsep)) or os.path.isdir(path): - return f"--json path is a directory: {path}" - cur = os.path.dirname(os.path.abspath(path)) - while cur: - if os.path.isdir(cur): - break - if os.path.lexists(cur): - return f"--json parent is not a directory: {cur}" - nxt = os.path.dirname(cur) - if nxt == cur: - break - cur = nxt - return None - - -def write_json_report(path, data): - """Create missing parent directories and write `data` as LF-terminated JSON, or return an error string.""" - parent = os.path.dirname(os.path.abspath(path)) - if parent: - try: - os.makedirs(parent, exist_ok=True) - except OSError as e: - return f"cannot create directory for --json {path}: {e.strerror or e}" - try: - with open(path, "w", encoding="utf-8", newline="\n") as f: - json.dump(data, f, indent=2) - except OSError as e: - return f"cannot write --json {path}: {e.strerror or e}" - return None - - -def main(argv=None): - ap = argparse.ArgumentParser(description=__doc__.splitlines()[0]) - ap.add_argument("--waves", default="32,64", help="wave sizes to run (default: 32,64)") - ap.add_argument("--json", dest="json_out", help="write full JSON report to this path") - ap.add_argument("--self-test", action="store_true", help="check the Python model without a GPU") - args = ap.parse_args(argv) - if args.self_test: - self_test() - return 0 - try: - waves = parse_waves(args.waves) - except ValueError as exc: - print(f"error: {exc}", file=sys.stderr) - return 2 - if args.json_out is not None: - err = validate_json_path(args.json_out) - if err: - print(f"error: {err}", file=sys.stderr) - return 2 - from hw_oracle import asm, runner - try: - oracle = runner.open_oracle() - except runner.Unavailable as exc: - print(f"SKIP: {exc}", file=sys.stderr) - return 77 - if asm.family(oracle.arch) != "gfx10": - print(f"SKIP: {oracle.arch} is not GFX10 (RDNA1/RDNA2)", file=sys.stderr) - return 77 - out = {"arch": oracle.arch, "waves": {}} - mismatches = 0 - for wave in waves: - res = probe_wave(oracle, asm, wave) - out["waves"][str(wave)] = res - if res["cases_ok"] != res["cases_total"]: - mismatches += 1 - print(f"wave{wave} ({oracle.arch}): {res['cases_ok']}/{res['cases_total']} ds_permute_b32 cases exact") - if args.json_out is not None: - err = write_json_report(args.json_out, out) - if err: - print(f"error: {err}", file=sys.stderr) - return 1 - return 1 if mismatches else 0 - - -if __name__ == "__main__": - if hasattr(sys.stdout, "reconfigure"): - sys.stdout.reconfigure(errors="replace") - raise SystemExit(main()) diff --git a/tools/exe_checklist.py b/tools/exe_checklist.py deleted file mode 100644 index 1e49418fa..000000000 --- a/tools/exe_checklist.py +++ /dev/null @@ -1,220 +0,0 @@ -"""The things to confirm against the game executable: every ASSUMPTION, UNVERIFIED and VERIFY note, in one list. - - python -I tools/exe_checklist.py [--gdk-calls REPORT.json]... [--out checklist.md] [--root DIR] - -The runtime and the docs mark what was written without the executable: `// ASSUMPTION ...` or `// ... UNVERIFIED` -comments in runtime/src and runtime/shims (C++), and `**VERIFY:**`, `**ASSUMPTION:**` or `**UNVERIFIED:**` notes in -docs/*.md, in any case (the prose spelling `**Assumption**`, `**Unverified:**` counts too; a bold term followed by -a dash defines it and is not a note, and a marker that does not start its line or that sits in a table row is prose, -not a note). This collects them with their file and line, the whole comment block or list item each starts, so the -first look at the executable (scripts/first_look.ps1) has one list to work through. - ---gdk-calls takes gdk_runtime_calls.py's JSON for the executable (its --out file or its --json output, one image or -several). A shim note then says whether the executable calls a runtime class that file serves: "called" items are -the ones a boot can reach, so they come first; "not called" ones can wait. The classes of a file are its -`constexpr GUID k...Class` ids, as gdk_runtime_calls reads them. - -Output: Markdown, to stdout or --out (LF). Exit status 0 on success; 1 when a --gdk-calls file can't be read or -the checklist cannot be written to --out; 2 when --out refers to an input report. -Standard library only. -Usage: `python -I tools/exe_checklist.py --help` lists the options. -""" -from __future__ import annotations - -import argparse -import json -import os -import re -import sys - -sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) -from gdk_runtime_calls import served_classes # noqa: E402 -from report_paths import same_report_path # noqa: E402 - -HERE = os.path.dirname(os.path.abspath(__file__)) -DEFAULT_ROOT = os.path.normpath(os.path.join(HERE, "..")) -SOURCE_DIRS = ("runtime/src", "runtime/shims") -SOURCE_EXTS = (".cpp", ".h", ".hpp", ".inl") -CODE_MARK = re.compile(r"\b(ASSUMPTION|UNVERIFIED|VERIFY)\b") -# The docs spell the marker in caps (`**VERIFY:**`) and in prose (`**Assumption**`, `**Unverified:**`, `**Assumptions -# to confirm:**`); all of them are notes. -DOC_MARK = re.compile(r"\*\*(VERIFY|ASSUMPTION|UNVERIFIED)S?\b[^*]*:?\*\*", re.IGNORECASE) -# A bold marker followed by a dash defines the term (`- **Assumption** — a design choice ...`), it is not a note. -DEFINITION = re.compile(r"[\u2014\u2013-]\s") -# A note is what a list item starts, so the marker after this prefix is at the item's start. -LIST_ITEM = re.compile(r"^(?:[-*+]|\d+[.)])\s+") - - -def comment_text(line: str) -> str | None: - """The text of a whole-line `//` comment, or None (code, or code with a trailing comment).""" - stripped = line.lstrip() - return stripped[2:].strip() if stripped.startswith("//") else None - - -def without_marker(text: str) -> str: - """The note without its leading marker word ("ASSUMPTION: x" -> "x"), which the list already shows.""" - return re.sub(r"^\**\s*(ASSUMPTION|UNVERIFIED|VERIFY)S?\b[^:]*:\**\s*", "", text, count=1, flags=re.IGNORECASE) - - -def code_notes(path: str, rel: str) -> list[dict]: - """Each whole-line comment run holding a marker, as one note from the run's first line to its last. Trailing - comments (`x = 18; // UNVERIFIED, see the header`) point at such a run and are not notes of their own.""" - with open(path, encoding="utf-8", errors="replace") as f: - lines = f.read().split("\n") - notes, i = [], 0 - while i < len(lines): - if comment_text(lines[i]) is None: - i += 1 - continue - start = i - parts = [] - while i < len(lines) and comment_text(lines[i]) is not None: - parts.append(comment_text(lines[i])) - i += 1 - # A run can hold several notes, and a note starts at its marker (a file's header describes the file first): - # each one runs from its marker to the next marker or the end of the run. - marks = [k for k, p in enumerate(parts) if CODE_MARK.search(p)] - for n, at in enumerate(marks): - stop = marks[n + 1] if n + 1 < len(marks) else len(parts) - first = parts[at][CODE_MARK.search(parts[at]).start():] - text = " ".join(p for p in [first] + parts[at + 1:stop] if p) - notes.append({"file": rel, "line": start + at + 1, "kind": CODE_MARK.search(first).group(1), - "text": without_marker(text)}) - return notes - - -def doc_notes(path: str, rel: str) -> list[dict]: - """Each note whose bold marker starts its line (after the indentation and an optional list marker), from the line - it starts on to the next blank line or item. A marker further into a sentence (`... work (**Assumption**);`) or a - table row (`| ... |`) is prose: the note does not start there, so it is not a note.""" - with open(path, encoding="utf-8", errors="replace") as f: - lines = f.read().split("\n") - notes = [] - for i, line in enumerate(lines): - stripped = line.lstrip() - if stripped.startswith("|"): - continue - body = LIST_ITEM.sub("", stripped) - m = DOC_MARK.match(body) - if not m: - continue - if DEFINITION.match(body[m.end():].lstrip()): - continue - end = i + 1 - while end < len(lines) and lines[end].strip() and not lines[end].lstrip().startswith(("- ", "* ", "#", "|")): - end += 1 - text = " ".join(re.sub(r"^[-*] ", "", l.strip()) for l in lines[i:end]) - notes.append({"file": rel, "line": i + 1, "kind": m.group(1).upper(), "text": without_marker(text)}) - return notes - - -def collect(root: str) -> list[dict]: - notes = [] - for d in SOURCE_DIRS: - base = os.path.join(root, d) - for dirpath, _dirs, files in sorted(os.walk(base)): - for name in sorted(files): - if name.endswith(SOURCE_EXTS): - path = os.path.join(dirpath, name) - rel = os.path.relpath(path, root).replace(os.sep, "/") - found = code_notes(path, rel) - if not found: - continue - # The classes belong to the file, so parse them once and give every note from it the same list. - with open(path, encoding="utf-8", errors="replace") as f: - classes = sorted(served_classes(f.read())) - for n in found: - n["classes"] = classes - notes += found - docs = os.path.join(root, "docs") - if os.path.isdir(docs): - for name in sorted(os.listdir(docs)): - if name.endswith(".md"): - notes += doc_notes(os.path.join(docs, name), f"docs/{name}") - return notes - - -def called_classes(paths: list[str]) -> set[str]: - """The class ids the executable's gdk_runtime_calls reports list (any image in them).""" - ids = set() - for p in paths: - with open(p, encoding="utf-8") as f: - doc = json.load(f) - for image in doc.get("images", [doc]): - for c in image.get("classes", []): - if c.get("class_id"): - ids.add(str(c["class_id"]).lower()) - return ids - - -def render(notes: list[dict], called: set[str] | None) -> str: - def status(n): - if called is None or not n.get("classes"): - return None - return any(c in called for c in n["classes"]) - - out = ["# Checklist: what to confirm against the executable", ""] - out.append(f"{len(notes)} notes from the runtime sources and the docs (tools/exe_checklist.py).") - if called is not None: - out.append("Runtime notes are marked by whether the executable calls a class their file serves " - "(gdk_runtime_calls); the called ones come first.") - out.append("") - groups = [("Runtime", [n for n in notes if not n["file"].startswith("docs/")]), - ("Docs", [n for n in notes if n["file"].startswith("docs/")])] - for title, group in groups: - if not group: - continue - out.append(f"## {title}") - out.append("") - order = {True: 0, None: 1, False: 2} - for n in sorted(group, key=lambda n: (order[status(n)], n["file"], n["line"])): - s = status(n) - tag = "" if s is None else (" **called**" if s else " (not called)") - out.append(f"- [ ] `{n['file']}:{n['line']}` {n['kind']}{tag}: {n['text']}") - out.append("") - return "\n".join(out) - - -def main(argv: list[str] | None = None) -> int: - ap = argparse.ArgumentParser(description=__doc__.split("\n\n", 1)[0]) - ap.add_argument("--gdk-calls", action="append", default=[], help="gdk_runtime_calls.py JSON for the executable") - ap.add_argument("--out", help="write the checklist here instead of stdout") - ap.add_argument("--root", default=DEFAULT_ROOT, help="the repository (default: %(default)s)") - a = ap.parse_args(argv) - if not os.path.isdir(a.root): - print(f"error: --root is not a directory: {a.root}", file=sys.stderr) - return 2 - if a.out and os.path.isdir(a.out): - print(f"error: --out path is a directory: {a.out}", file=sys.stderr) - return 2 - if a.out: - for report in a.gdk_calls: - if same_report_path(a.out, report): - ap.error(f"--out {a.out} would overwrite the --gdk-calls report {report}") - called = None - if a.gdk_calls: - try: - called = called_classes(a.gdk_calls) - except (OSError, ValueError, AttributeError) as e: - print(f"cannot read the gdk_runtime_calls report: {e}", file=sys.stderr) - return 1 - text = render(collect(a.root), called) - if a.out: - try: - with open(a.out, "w", encoding="utf-8", newline="\n") as f: - f.write(text) - except OSError as e: - print(f"cannot write the checklist to {a.out}: {e.strerror or e}", file=sys.stderr) - return 1 - print(f"wrote {a.out}") - else: - print(text, end="") - return 0 - - -if __name__ == "__main__": - try: # a redirected stdout is strict ANSI code page under -I; write '?' for what it cannot encode - sys.stdout.reconfigure(errors="replace") - except (AttributeError, ValueError, OSError): - pass - sys.exit(main()) diff --git a/tools/f16_trans_sweep.py b/tools/f16_trans_sweep.py deleted file mode 100644 index 50b8bcd8e..000000000 --- a/tools/f16_trans_sweep.py +++ /dev/null @@ -1,517 +0,0 @@ -r"""Every f16 input through the f16 transcendentals on an AMD GPU (FUZZ-29). Standard library only. - -v_exp_f16, v_log_f16, v_rcp_f16, v_rsq_f16, v_sqrt_f16, v_sin_f16 and v_cos_f16 run natively through the hardware -oracle (tools/hw_oracle/) on all 65,536 f16 bit patterns, in wave32 and wave64 and under several float MODEs, and -each result is compared with the rule the translator implements (tools/rdna2spirv.py: widen to f32, the GLSL.std.450 -function, round to nearest even back to f16, f16 denormals kept): - - * v_exp_f16 = Exp2, v_log_f16 = Log2, v_rcp_f16 = 1 / x, v_rsq_f16 = InverseSqrt, v_sqrt_f16 = Sqrt. The - reference is the exact value, correctly rounded to f16 (decimal arithmetic, 60 digits), which is the best a - Vulkan driver can return for the translated SPIR-V. - * v_sin_f16 / v_cos_f16 take turns: the reference is sin / cos of 2 pi x, reduced in turns, correctly rounded. A - second table compares the hardware with Sin / Cos of the f32 product 6.2831855 * x, which is what the translator - computed before reducing in turns (#594). - * Where the rule's SPIR-V is undefined (Log2 / Sqrt / InverseSqrt of a negative, Log2 / InverseSqrt of 0, a - division by 0), the hardware result is tabulated instead of judged. - -Nothing is assumed about how close the hardware is: the tables count bit-exact results, 1 ulp, more than 1 ulp, -denormal operands read as zero, denormal results flushed, and NaN, and list the hardware word for each special -input. Each MODE is read back inside a kernel first, so a launcher that ignored the descriptor fails instead of -producing plausible tables. - -Usage: - python -I tools/f16_trans_sweep.py [--ops v_exp_f16,v_log_f16] [--modes keep16,flush16] [--json out.json] - python -I tools/f16_trans_sweep.py --self-test - -Exit 0 when the sweep ran (differences from the rule are findings, not failures), 1 when wave32 and wave64 -disagree or --json cannot be written, 2 on a harness error (a MODE that did not apply, a kernel without its -words), 77 when the hardware oracle is unavailable. On Linux the -oracle needs LEONIDA_HW_DRM_NODE (docs/shader_validation.md). Nothing here reads game files. -""" -import argparse -import functools -import json -import os -import struct -import sys -from decimal import ROUND_HALF_EVEN, Decimal, localcontext - -HERE = os.path.dirname(os.path.abspath(__file__)) -sys.dont_write_bytecode = True -if HERE not in sys.path: - sys.path.insert(0, HERE) - -OPS = ("v_exp_f16", "v_log_f16", "v_rcp_f16", "v_rsq_f16", "v_sqrt_f16", "v_sin_f16", "v_cos_f16") - -# f32 denormals flushed and IEEE off is the state docs/design.md infers for the game's shaders; the f16 denormal -# field is the open question, so both settings are run, then IEEE on, then f16 rounding toward zero. -MODES = { - "keep16": {"ieee": 0, "dx10_clamp": 1, "denorm32": 0, "denorm16_64": 3}, - "flush16": {"ieee": 0, "dx10_clamp": 1, "denorm32": 0, "denorm16_64": 0}, - "ieee_keep16": {"ieee": 1, "dx10_clamp": 1, "denorm32": 0, "denorm16_64": 3}, - "ieee_flush16": {"ieee": 1, "dx10_clamp": 1, "denorm32": 0, "denorm16_64": 0}, - "keep16_rtz": {"ieee": 0, "dx10_clamp": 1, "denorm32": 0, "denorm16_64": 3, "round16_64": 3}, -} - -THREADS = 1024 -PER_THREAD = 8 # inputs per thread, packed two to a dword -PER_KERNEL = THREADS * PER_THREAD # 8192 inputs, 4096 words per kernel: 8 kernels cover every input -QNAN = 0x7E00 -TWO_PI_F32 = struct.unpack("= Decimal(2) ** (e + 1) and e < 15: - e += 1 - ulp = Decimal(2) ** (e - 10) - with localcontext() as c: - c.prec = 80 - n = int((a / ulp).to_integral_value(rounding="ROUND_DOWN" if rtz else ROUND_HALF_EVEN)) - val = n * ulp - if val > 65504: - return sign | (0x7BFF if rtz else 0x7C00) - return sign | struct.unpack("= 1: - f -= 1 - q = f * 4 - if q == q.to_integral_value(): - return [Decimal(0), Decimal(1), Decimal(0), Decimal(-1)][int(q)] - if f > Decimal("0.5"): - f -= 1 # (-0.5, 0.5] - return _sin(2 * _pi() * f) - - -def exact(op, h): - """The exact real result of the op on f16 h as a Decimal, or a str for a result that is not a finite real: - 'nan', '+inf', '-inf', '+0', '-0', or 'undef' where the translated SPIR-V is undefined.""" - if is_nan(h): - return "nan" - s = neg(h) - if is_inf(h): - return {"v_exp_f16": "+0" if s else "+inf", "v_log_f16": "undef" if s else "+inf", - "v_rcp_f16": "-0" if s else "+0", "v_rsq_f16": "undef" if s else "+0", - "v_sqrt_f16": "undef" if s else "+inf", "v_sin_f16": "undef", "v_cos_f16": "undef"}[op] - if is_zero(h): - return {"v_exp_f16": Decimal(1), "v_log_f16": "undef", "v_rcp_f16": "undef", "v_rsq_f16": "undef", - "v_sqrt_f16": "-0" if s else "+0", "v_sin_f16": "-0" if s else "+0", "v_cos_f16": Decimal(1)}[op] - x = to_dec(h) - if s and op in ("v_log_f16", "v_rsq_f16", "v_sqrt_f16"): - return "undef" - with localcontext() as c: - c.prec = 60 - if op == "v_exp_f16": - return Decimal(2) ** x if x != x.to_integral_value() else (Decimal(2) ** int(x) if abs(x) < 64 else - (Decimal(0) if x < 0 else Decimal(10) ** 30)) - if op == "v_log_f16": - return x.ln() / Decimal(2).ln() - if op == "v_rcp_f16": - return 1 / x - if op == "v_rsq_f16": - return 1 / x.sqrt() - if op == "v_sqrt_f16": - return x.sqrt() - return sin_turns(x, op == "v_cos_f16") - - -def product_turns(op, h): - """sin / cos of the f32 product 6.2831855 * x for finite h (the translator before #594 was fixed).""" - with localcontext() as c: - c.prec = 60 - t = Decimal(struct.unpack("> 16] - return out - - -def classify(op, hw, ref): - """Counts for one op and mode. A denormal operand whose word equals the hardware's own word for a zero of the - same sign counts as read as zero (the rule is undefined at 0 for log, rcp and rsq, so the rule can't say).""" - zero_hw = {False: hw[0x0000], True: hw[0x8000]} - c = {"inputs": 0, "exact": 0, "ulp1": 0, "ulp_more": 0, "max_ulp": 0, "nan_ok": 0, "zero_sign": 0, - "denorm_in_as_zero": 0, "denorm_out_flushed": 0, "undefined": 0, "nan_payload_kept": 0, "snan_kept": 0, - "snan_quieted": 0, "snan_other": 0, "other": 0} - worst = [] - for h in range(65536): - r, g = ref[h], hw[h] - c["inputs"] += 1 - if r is None: - c["undefined"] += 1 - continue - if is_nan(r): - if is_nan(g): - c["nan_ok"] += 1 - if is_nan(h) and (g & 0x1FF) == (h & 0x1FF): - c["nan_payload_kept"] += 1 - if is_nan(h) and not h & 0x200: - c["snan_kept" if g == h else "snan_quieted" if g == h | 0x200 else "snan_other"] += 1 - else: - c["other"] += 1 - worst.append((h, g, r)) - continue - if g == r: - c["exact"] += 1 - elif is_denorm(h) and g == zero_hw[neg(h)]: - c["denorm_in_as_zero"] += 1 - elif is_denorm(r) and is_zero(g) and (g & 0x8000) == (r & 0x8000): - c["denorm_out_flushed"] += 1 - elif is_zero(g) and is_zero(r): - c["zero_sign"] += 1 - elif is_nan(g): - c["other"] += 1 - worst.append((h, g, r)) - else: - d = ulps(g, r) - c["max_ulp"] = max(c["max_ulp"], d) - if d == 1: - c["ulp1"] += 1 - else: - c["ulp_more"] += 1 - worst.append((h, g, r)) - worst.sort(key=lambda t: -ulps(t[1], t[2]) if not (is_nan(t[1]) or is_nan(t[2])) else -1 << 20) - return c, worst[:8] - - -def product_reference(op, rtz=False): - return [None if is_nan(h) or is_inf(h) else to_bits(product_turns(op, h), rtz) for h in range(65536)] - - -def range_stats(hw, turns): - """sin / cos only: ulps against sin / cos of the f32 product, by |x| band.""" - bands = {"|x|<=1": (0, 1), "1<|x|<=256": (1, 256), "|x|>256": (256, 1e9)} - out = {} - for name, (lo, hi) in bands.items(): - n = ex = u1 = more = 0 - worst = 0 - for h in range(65536): - if is_nan(h) or is_inf(h): - continue - a = abs(float(to_dec(h))) - if not (lo < a <= hi or (lo == 0 and a == 0)): - continue - r = turns[h] - g = hw[h] - n += 1 - if is_nan(g): - more += 1 - continue - d = 0 if (g == r or (is_zero(g) and is_zero(r))) else ulps(g, r) - worst = max(worst, d) - ex += d == 0 - u1 += d == 1 - more += d > 1 - out[name] = {"inputs": n, "exact": ex, "ulp1": u1, "ulp_more": more, "max_ulp": worst} - return out - - -def fmt(h): - if h is None: - return "undef" - v = struct.unpack(" {v}" for h, v in report["ops"][op][modes[0]]["specials"].items())) - except RuntimeError as e: - print(f"harness error: {e}") - return 2 - finally: - oracle.close() - if a.json is not None: - err = write_json_report(a.json, report) - if err: - print(f"error: {err}", file=sys.stderr) - return 1 - return rc - - -if __name__ == "__main__": - try: # a redirected stdout is strict ANSI code page under -I; write '?' for what it cannot encode - sys.stdout.reconfigure(errors="replace") - except (AttributeError, ValueError, OSError): - pass - sys.exit(main()) diff --git a/tools/f16_widen_probe.py b/tools/f16_widen_probe.py deleted file mode 100644 index 0807ceeeb..000000000 --- a/tools/f16_widen_probe.py +++ /dev/null @@ -1,355 +0,0 @@ -r"""Measure how RDNA2 (GFX10) widens a half-precision NaN in a typed buffer load (FUZZ-5 follow-up). - -`tools/mem_diff.py` reported one class of mismatch: a typed buffer load of a half NaN. Its Python reference decodes -16_FLOAT through `struct.unpack(' f32 bits keeping sign and NaN payload (the 'widen by shifting' rule, and Python 3.14's '> 15) << 31 - exp = (h >> 10) & 0x1F - frac = h & 0x03FF - if exp == 0x1F: - return sign | 0x7F800000 | (frac << 13) - if exp == 0 and frac: - b = frac.bit_length() - return sign | ((b + 102) << 23) | ((frac << (24 - b)) & 0x7FFFFF) - if exp == 0: - return sign - return sign | ((exp + 112) << 23) | (frac << 13) - - -def h2f_canonical(h): - """f16 -> f32 bits with every NaN collapsed to the canonical quiet NaN, sign kept (mini interpreter rule).""" - h &= 0xFFFF - if (h >> 10) & 0x1F == 0x1F and h & 0x03FF: - return ((h >> 15) << 31) | 0x7FC00000 - return h2f_payload(h) - - -def h2f_quiet(h): - """f16 -> f32 bits keeping sign and payload with the quiet bit forced (a sNaN quieted, payload kept).""" - bits = h2f_payload(h) - if (h >> 10) & 0x1F == 0x1F and h & 0x03FF: - bits |= 1 << 22 - return bits - - -def classify(bits, half): - """How an observed f32 word relates to the half it came from.""" - payload = h2f_payload(half) - canonical = h2f_canonical(half) - quiet = h2f_quiet(half) - if bits == payload: - return "payload" - if bits == quiet and quiet != payload: - return "payload_quiet" - if bits == canonical and canonical != payload: - return "canonical" - if bits == 0: - return "zero" - return "other" - - -def _kernel(asm_mod, inst, code, half, wave): - ncomp = len(inst.rsplit("_", 1)[1]) - vreg = "v4" if ncomp == 1 else f"v[4:{3 + ncomp}]" - load = ( - f"{inst} {vreg}, off, s[8:11], 0 offset:32" - if inst.startswith("buffer_") - else f"{inst} {vreg}, off, s[8:11], 0 format:{code} offset:32" - ) - lines = [ - "s_mov_b32 s8, s2", - "s_and_b32 s9, s3, 0xffff", - "s_mov_b32 s10, 0x100", - f"s_mov_b32 s11, 0x{vsharp_d3(code):x}", - "v_mov_b32 v4, 0", - "buffer_store_dword v4, off, s[8:11], 0 offset:36", - f"v_mov_b32 v4, 0x{half:x}", - "buffer_store_dword v4, off, s[8:11], 0 offset:32 glc", - "s_waitcnt_vscnt null, 0x0", - load, - "s_waitcnt vmcnt(0)", - ] - for i in range(ncomp): - lines.append(f"buffer_store_dword v{4 + i}, off, s[8:11], 0 offset:{4 * i}") - lines += ["s_waitcnt_vscnt null, 0x0", "s_endpgm"] - return asm_mod.Kernel(lines, wave, 1, 16, raw=True, vgprs=12, sgprs=16) - - -def _alu_kernel(asm_mod, half, wave): - """The half word through v_cvt_f32_f16: what a driver lowers UnpackHalf2x16 to.""" - lines = [ - "s_mov_b32 s8, s2", - "s_and_b32 s9, s3, 0xffff", - "s_mov_b32 s10, 0x100", - f"s_mov_b32 s11, 0x{vsharp_d3(13):x}", - f"v_mov_b32 v4, 0x{half:x}", - "buffer_store_dword v4, off, s[8:11], 0 offset:32 glc", - "s_waitcnt_vscnt null, 0x0", - "buffer_load_dword v4, off, s[8:11], 0 offset:32", - "s_waitcnt vmcnt(0)", - "v_cvt_f32_f16 v5, v4", - "buffer_store_dword v5, off, s[8:11], 0 offset:0", - "s_waitcnt_vscnt null, 0x0", - "s_endpgm", - ] - return asm_mod.Kernel(lines, wave, 1, 16, raw=True, vgprs=12, sgprs=16) - - -def cases(): - """(case name, format code, form, instruction, lane count) for every sweep entry.""" - for code, name, widths in FLOAT_FORMATS: - for form in FORMS: - for suffix in INSTRUCTIONS: - ncomp = len(suffix) - yield f"fmt{code}/{name}/{form}_{suffix}", code, form, suffix, ncomp - - -def sweep(oracle, asm_mod, wave): - out = {} - order, kernels = [], [] - for case, code, form, suffix, n in cases(): - for label, half in HALVES: - order.append((case, code, form, suffix, n, label, half)) - kernels.append( - _kernel(asm_mod, f"{form}_load_format_{suffix}", code, half, wave) - ) - got = oracle.run(kernels, words=16) - for (case, code, form, suffix, n, label, half), words in zip(order, got): - if isinstance(words, str): - raise RuntimeError(f"{case} {label} wave{wave}: {words}") - lanes = words[:n] - case_out = out.setdefault(case, {}) - case_out[label] = { - "half": f"0x{half:04x}", - "words": [f"0x{w:08x}" for w in lanes], - "classes": [classify(w, half) for w in lanes], - } - order, kernels = [], [] - for label, half in HALVES: - order.append(("alu/v_cvt_f32_f16", label, half)) - kernels.append(_alu_kernel(asm_mod, half, wave)) - got = oracle.run(kernels, words=16) - for (case, label, half), words in zip(order, got): - if isinstance(words, str): - raise RuntimeError(f"{case} {label} wave{wave}: {words}") - out.setdefault(case, {})[label] = { - "half": f"0x{half:04x}", - "words": [f"0x{words[0]:08x}"], - "classes": [classify(words[0], half)], - } - return out - - -def self_test(): - # Payload rule, bit for bit. - assert h2f_payload(0x3C00) == 0x3F800000 - assert h2f_payload(0xC000) == 0xC0000000 - assert h2f_payload(0x7DDB) == 0x7FBB6000 # sNaN, payload kept, quiet bit not forced - assert h2f_payload(0x7FE6) == 0x7FFCC000 - assert h2f_payload(0xFFB2) == 0xFFF64000 - assert h2f_payload(0x7C01) == 0x7F802000 - assert h2f_payload(0x0001) == 0x33800000 # smallest subnormal half - # Canonical rule, and the quiet-bit variant. - assert h2f_canonical(0x7DDB) == 0x7FC00000 - assert h2f_canonical(0xFFB2) == 0xFFC00000 - assert h2f_canonical(0x7FE6) == 0x7FC00000 - assert h2f_canonical(0x3C00) == 0x3F800000 - assert h2f_quiet(0x7DDB) == 0x7FFB6000 - assert h2f_quiet(0x7FE6) == 0x7FFCC000 - assert h2f_quiet(0x3C00) == 0x3F800000 - # classify() names the three outcomes apart. - assert classify(0x7FBB6000, 0x7DDB) == "payload" - assert classify(0x7FC00000, 0x7DDB) == "canonical" - assert classify(0x7FFB6000, 0x7DDB) == "payload_quiet" - assert classify(0x7FBB6001, 0x7DDB) == "other" - assert classify(0x00000000, 0x7DDB) == "zero" - # Every control widens exactly in all three models. - for h in (0x3C00, 0xC000): - assert h2f_payload(h) == h2f_canonical(h) == h2f_quiet(h) - assert struct.unpack( - " {' '.join(e['words'])} [{' '.join(e['classes'])}]" - ) - - -def main(argv=None): - if hasattr(sys.stdout, "reconfigure"): - sys.stdout.reconfigure(encoding="utf-8", errors="replace") - ap = argparse.ArgumentParser(description=__doc__.splitlines()[0]) - ap.add_argument( - "--waves", default="32,64", help="wave sizes to run (default: 32,64)" - ) - ap.add_argument( - "--json", dest="json_out", help="write the full JSON report to this path" - ) - ap.add_argument( - "--self-test", action="store_true", help="check the Python model without a GPU" - ) - args = ap.parse_args(argv) - if args.self_test: - self_test() - return 0 - waves, err = parse_waves(args.waves) - if err: - print(f"error: {err}", file=sys.stderr) - return 2 - if args.json_out is not None: - err = validate_json_path(args.json_out) - if err: - print(f"error: {err}", file=sys.stderr) - return 2 - from hw_oracle import asm, runner - - try: - oracle = runner.open_oracle() - except runner.Unavailable as exc: - print(f"SKIP: {exc}", file=sys.stderr) - return 77 - if asm.family(oracle.arch) != "gfx10": - print(f"SKIP: {oracle.arch} is not GFX10 (RDNA1/RDNA2)", file=sys.stderr) - return 77 - out = {"arch": oracle.arch, "waves": {}} - for wave in waves: - report = sweep(oracle, asm, wave) - out["waves"][str(wave)] = report - print_table(report, wave) - if args.json_out is not None: - err = write_json_report(args.json_out, out) - if err: - print(f"error: {err}", file=sys.stderr) - return 1 - return 0 - - -if __name__ == "__main__": - if hasattr(sys.stdout, "reconfigure"): - sys.stdout.reconfigure(errors="replace") - raise SystemExit(main()) diff --git a/tools/f16misc_diff.py b/tools/f16misc_diff.py deleted file mode 100644 index 942b9587f..000000000 --- a/tools/f16misc_diff.py +++ /dev/null @@ -1,1273 +0,0 @@ -r"""Differential fuzzer for the RDNA2 f16 VALU ops no other fuzzer generates (standard library only). - -Covers eleven opcodes that are on no `--list-ops` list and in no generator of the other fuzzers: - - v_min3_f16 v_max3_f16 VOP3, three f16 -> f16, op_sel:[a,b,c,d], clamp - v_frexp_mant_f16 v_frexp_exp_i16_f16 VOP1 (_e32, _e64), f16 -> f16 / i16, op_sel:[a,d] - v_ldexp_f16 VOP2 (_e32, _e64), f16 * 2^i16 -> f16, op_sel:[a,b,d] - v_fmamk_f16 v_fmaak_f16 VOP2 with a literal K, f16 fma - v_pk_fmac_f16 VOP2, two f16 fmas into the packed accumulator - v_fma_mix_f32 v_fma_mixlo_f16 v_fma_mixhi_f16 VOP3P, f32 fma of f32 or f16 sources (op_sel_hi), clamp - -Seeded straight-line programs run through two independent oracles, and the four exported mrt0 words are compared: - - * the reference below, written from the rules docs/design.md records for these ops, with exact rationals - (fractions.Fraction) and one round-to-nearest-even per result. It shares no code with the translator: - - f16 operands and results keep denormals (the MODE inferred for the game, denorm_mode_16_64 = 3); an f32 - operand of v_fma_mix_* reads as a zero of its sign when it is denormal (denorm_mode_32 = 0, SHADER-298). - - fma: x * y + z exact, then rounded once (to f16, or to f32 for v_fma_mix_f32); |x| at or past the - rounding boundary of the largest finite value gives +-inf. An exact zero sum is -0 only when both the - product and the addend are -0. - - min3 / max3: a NaN operand is ignored, -0 orders below +0; the result is the chosen operand. - - frexp_mant: the input with its exponent set to 14 (mantissa in [0.5, 1), sign kept); frexp_exp: the - exponent that goes with it, as an i16. ldexp: S0 * 2^clamp(S1.i16, -64, 64), rounded to nearest even. - Zero gives a signed zero (exponent 0); inf and NaN pass through unchanged (exponent 0). - - clamp: to [0, 1] after the operation, before the rounding. On frexp_mant / ldexp a negative result and a - NaN give +0 (measured on gfx1036). - - output multipliers (mul:2, mul:4, div:2) change nothing: the hardware ignores them on an f16 result with - f16 denormals kept, and clamp still acts; on frexp_exp's integer result clamp changes nothing either - (measured on gfx1036, docs/design.md's f16 output modifier and v_frexp/ldexp_f16 rows). - - destinations: an f16 result goes to the half op_sel's last bit names (the low half for VOP1/VOP2 and - v_fma_mixlo_f16, the high half for v_fma_mixhi_f16) and the other half is kept; v_pk_fmac_f16 writes both - halves; v_fma_mix_f32 writes the word. - tests/test_f16misc_diff.py pins it to the words measured on RDNA2 that tests/semantic records, and - * tools/rdna2spirv.py, executing the SPIR-V with tests/semantic/spirv_mini_interp.py. - -Comparison: bit for bit, except that a NaN the reference computed (an fma or a min3/max3 of all-NaN operands) -matches any NaN: payloads are not modelled. A NaN that only passes through (frexp_mant, ldexp, a min3 operand) -is compared exactly. A program is not judged (counted with the reason, not a failure) when it reads such a NaN as -bits (an f32 operand made of an f16 NaN half, an i16 exponent, half of an f32 NaN), clamps a NaN or a -0 through -min3/max3/fma_mix (the translator's FClamp of a NaN is undefined in SPIR-V; docs/design.md does not pin -0), or -when v_fma_mix_f32 returns an f32 denormal (whether f32 denormal results flush is the MODE question, SHADER-35). - -Program shape: seeds in v8..v15 and s4..s7, then the family ops, then `exp mrt0 v8, v9, v10, v11` so every result -is observed. Every destination is v8..v11, so later ops read earlier results. - -Sources: VGPR v8..v15, SGPR s4..s7, a hex literal, an integer inline constant (-16..64) and a float inline -constant (0.5, 1.0, 2.0, 4.0, their negatives, 0.15915494). A 16-bit float operand reads the low half of a -register or literal, a float inline constant as its f16 value, and an integer inline constant as the low half of -its word (docs/design.md, "f16 inline constants"). An f32 operand of v_fma_mix_* reads a float inline constant as -its f32 value. Every program is encodable on GFX10: at most one literal, at most two constant-bus reads in a VOP3 -or VOP3P op, and a VOP2 literal or SGPR only in src0. - -Modifiers: neg/abs on the register sources of the VOP3/VOP3P forms (not on ldexp's exponent); op_sel on register -sources and the destination bit; clamp on min3/max3, frexp_mant, frexp_exp, ldexp and the fma_mix ops; an output -multiplier on the VOP3 forms of min3/max3, frexp_mant, frexp_exp and ldexp. Not generated, on purpose: the -modifiers the translator refuses (--self-test pins those as expected rejections), SDWA and DPP forms -(tools/sdwa_diff.py's domain), and op_sel on a constant (only measured for some ops). - -Stages: - 1. a sweep: every encodable source-kind combination of every op and form, twice, with random modifiers; - 2. an edge grid: special values (zeros, denormals, the normal bounds, 1, the largest finite, inf, quiet and - signalling NaNs) through every op, frexp_mant and ldexp also with clamp, and fma near ties and cancellations, - four cases per program. Some near ties are off the tie by less than half an f32 ulp (NEAR_ONE), so an fma - rounded first to f32 and then to f16 gives a different word there; - 3. random seeded programs. ---exhaustive-f16 adds every f16 input through v_frexp_mant_f16, v_frexp_exp_i16_f16 and v_ldexp_f16 (eight -exponents in turn). - -Exit code 0 when every judged program matches, 1 on a mismatch (the first one is printed with its listing) or a -translator skip (every generated form is one the translator takes), 2 on a harness error. - -Usage: - python -I tools/f16misc_diff.py [--programs N] [--seed S] [--max-ops N] [--ops v_ldexp_f16,v_fma_mix_f32] - python -I tools/f16misc_diff.py --exhaustive-f16 --programs 0 --no-sweep - python -I tools/f16misc_diff.py --list-ops - python -I tools/f16misc_diff.py --self-test -""" -import argparse -import gc -import os -import random -import re -import struct -import sys -import tempfile -import warnings -from collections import Counter -from fractions import Fraction - -HERE = os.path.dirname(os.path.abspath(__file__)) -TOOLS_DIR = os.environ.get("LEONIDA_TOOLS_DIR") or HERE -sys.dont_write_bytecode = True -if TOOLS_DIR not in sys.path: - sys.path.insert(0, TOOLS_DIR) -SEM_DIR = os.path.join(os.path.dirname(HERE), "tests", "semantic") -if SEM_DIR not in sys.path: - sys.path.insert(0, SEM_DIR) - -import rdna2spirv # noqa: E402 -from spirv_mini_interp import UnsupportedConstruct, run_fragment # noqa: E402 - -M32 = 0xFFFFFFFF -M16 = 0xFFFF -STUB_DXBC = b"DXBC" + bytes(24) + struct.pack(" kind -FAMILY = { - "v_min3_f16": "min3", "v_max3_f16": "max3", - "v_frexp_mant_f16": "mant", "v_frexp_exp_i16_f16": "exp", "v_ldexp_f16": "ldexp", - "v_fmamk_f16": "fmamk", "v_fmaak_f16": "fmaak", - "v_pk_fmac_f16": "pkfmac", - "v_fma_mix_f32": "mix32", "v_fma_mixlo_f16": "mixlo", "v_fma_mixhi_f16": "mixhi", -} -MIX = ("v_fma_mix_f32", "v_fma_mixlo_f16", "v_fma_mixhi_f16") -OP_FORMS = { - "v_min3_f16": "d, [-][|]s0[|], [-][|]s1[|], [-][|]s2[|] [op_sel:[a,b,c,d]] [clamp]", - "v_max3_f16": "d, [-][|]s0[|], [-][|]s1[|], [-][|]s2[|] [op_sel:[a,b,c,d]] [clamp]", - "v_frexp_mant_f16": "_e32 d, s0 | _e64 d, [-][|]s0[|] [op_sel:[a,d]] [clamp]", - "v_frexp_exp_i16_f16": "_e32 d, s0 | _e64 d, [-][|]s0[|] [op_sel:[a,d]]", - "v_ldexp_f16": "_e32 d, s0, vs1 | _e64 d, [-][|]s0[|], s1 [op_sel:[a,b,d]] [clamp]", - "v_fmamk_f16": "d, s0, K, vs1", - "v_fmaak_f16": "d, s0, vs1, K", - "v_pk_fmac_f16": "d, s0, vs1 (d is the accumulator)", - "v_fma_mix_f32": "d, [-][|]s0[|], [-][|]s1[|], [-][|]s2[|] op_sel:[a,b,c] op_sel_hi:[x,y,z] [clamp]", - "v_fma_mixlo_f16": "d, [-][|]s0[|], [-][|]s1[|], [-][|]s2[|] op_sel:[a,b,c] op_sel_hi:[x,y,z] [clamp]", - "v_fma_mixhi_f16": "d, [-][|]s0[|], [-][|]s1[|], [-][|]s2[|] op_sel:[a,b,c] op_sel_hi:[x,y,z] [clamp]", -} - -KINDS = ("vgpr", "sgpr", "lit", "int", "float") -MODS = ("", "-", "|", "-|") # source modifiers on a register: none, neg, abs, neg(abs) -FLOAT_INLINE = { # token -> (f32 word, f16 half) - "0.5": (0x3F000000, 0x3800), "-0.5": (0xBF000000, 0xB800), "1.0": (0x3F800000, 0x3C00), - "-1.0": (0xBF800000, 0xBC00), "2.0": (0x40000000, 0x4000), "-2.0": (0xC0000000, 0xC000), - "4.0": (0x40800000, 0x4400), "-4.0": (0xC0800000, 0xC400), "0.15915494": (0x3E22F983, 0x3118), -} -INT_INLINE = tuple(range(0, 65)) + tuple(range(-16, 0)) -OMODS = ("mul:2", "mul:4", "div:2") -OMOD_KINDS = ("min3", "max3", "mant", "exp", "ldexp") # the VOP3 forms that have an omod field - -# Half states in the reference's register file: None (known bits), "nan" (an f16 NaN whose payload the reference -# does not model) and "w32" (half of an f32 NaN whose payload it does not model). -NAN16 = 0x7E00 -NAN32 = 0x7FC00000 - - -class HarnessError(Exception): - """The generator or the reference met something outside the modelled forms.""" - - -class NotJudged(Exception): - """The reference does not judge this program (the reason is counted).""" - - -# ---- numbers: (kind, sign, magnitude), kind "num" / "inf" / "nan", magnitude a Fraction ---- - -F16 = (11, -14, 15) # precision, smallest normal exponent, largest exponent -F32 = (24, -126, 127) - - -def _ilog2(q): - """floor(log2(q)) of a positive Fraction.""" - e = q.numerator.bit_length() - q.denominator.bit_length() - if Fraction(2) ** e > q: - e -= 1 - elif Fraction(2) ** (e + 1) <= q: - e += 1 - return e - - -def _round_even(q): - n = q.numerator // q.denominator - d = q - n - if d > Fraction(1, 2) or (d == Fraction(1, 2) and n % 2): - n += 1 - return n - - -def decode16(h): - sign = h >> 15 - e, m = (h >> 10) & 0x1F, h & 0x3FF - if e == 0x1F: - return ("nan" if m else "inf", sign, None) - mag = Fraction(m, 1 << 24) if e == 0 else Fraction((1 << 10) | m) * Fraction(2) ** (e - 25) - return ("num", sign, mag) - - -def decode32(w, flush=True): - """An f32 word; a denormal reads as a zero of its sign when ``flush``.""" - sign = w >> 31 - e, m = (w >> 23) & 0xFF, w & 0x7FFFFF - if e == 0xFF: - return ("nan" if m else "inf", sign, None) - if e == 0: - return ("num", sign, Fraction(0) if flush else Fraction(m, 1 << 149)) - return ("num", sign, Fraction((1 << 23) | m) * Fraction(2) ** (e - 150)) - - -def round_to(value, fmt, events=None): - """Round a ("num", sign, exact magnitude) to the format, nearest even; past the largest finite gives inf.""" - kind, sign, mag = value - if kind != "num" or mag == 0: - return value - p, emin, emax = fmt - e = max(_ilog2(mag), emin) - ulp = Fraction(2) ** (e - p + 1) - q = mag / ulp - if events is not None and q.denominator == 2: - events["tie"] += 1 - r = _round_even(q) * ulp - if r > (Fraction(2) ** p - 1) * Fraction(2) ** (emax - p + 1): - if events is not None: - events["overflow"] += 1 - return ("inf", sign, None) - if events is not None and 0 < r < Fraction(2) ** emin: - events["denormal result"] += 1 - return ("num", sign, r) - - -def encode16(value): - kind, sign, mag = value - if kind == "nan": - return (sign << 15) | NAN16 - if kind == "inf": - return (sign << 15) | 0x7C00 - if mag == 0: - return sign << 15 - e = _ilog2(mag) - if e < -14: - m = mag * (1 << 24) - assert m.denominator == 1 and m < 1024, value - return (sign << 15) | int(m) - m = mag / Fraction(2) ** (e - 10) - 1024 - assert m.denominator == 1 and 0 <= m < 1024 and e <= 15, value - return (sign << 15) | ((e + 15) << 10) | int(m) - - -def encode32(value): - kind, sign, mag = value - if kind == "nan": - return (sign << 31) | NAN32 - if kind == "inf": - return (sign << 31) | 0x7F800000 - if mag == 0: - return sign << 31 - e = _ilog2(mag) - if e < -126: - raise NotJudged("v_fma_mix_f32 gives an f32 denormal") - m = mag / Fraction(2) ** (e - 23) - (1 << 23) - assert m.denominator == 1 and 0 <= m < (1 << 23) and e <= 127, value - return (sign << 31) | ((e + 127) << 23) | int(m) - - -def fma(x, y, z): - """x * y + z, exact (not rounded). Any NaN, inf * 0 and inf - inf give ("nan", 0, None).""" - if "nan" in (x[0], y[0], z[0]): - return ("nan", 0, None) - ps = x[1] ^ y[1] - if x[0] == "inf" or y[0] == "inf": - if (x[0] == "num" and x[2] == 0) or (y[0] == "num" and y[2] == 0): - return ("nan", 0, None) - if z[0] == "inf" and z[1] != ps: - return ("nan", 0, None) - return ("inf", ps, None) - if z[0] == "inf": - return z - pm = x[2] * y[2] - total = (-pm if ps else pm) + (-z[2] if z[1] else z[2]) - if total == 0: - return ("num", 1 if (pm == 0 and z[2] == 0 and ps and z[1]) else 0, Fraction(0)) - return ("num", 1 if total < 0 else 0, abs(total)) - - -def _key(v): - """Order for min/max: -inf < negative < -0 < +0 < positive < +inf.""" - kind, sign, mag = v - if kind == "inf": - return (2 if not sign else 0, 0, 0) - return (1, -mag if sign else mag, 0 if sign else 1) - - -def clamp01(v, nan_to_zero=False): - """Clamp to [0, 1]. A NaN gives +0 when ``nan_to_zero`` (frexp_mant, ldexp), else it is not judged; a -0 - through FClamp is not judged either.""" - kind, sign, mag = v - if kind == "nan": - if nan_to_zero: - return ("num", 0, Fraction(0)) - raise NotJudged("clamp of a NaN") - if sign: - if kind == "num" and mag == 0 and not nan_to_zero: - raise NotJudged("clamp of -0") - return ("num", 0, Fraction(0)) - if kind == "inf" or mag > 1: - return ("num", 0, Fraction(1)) - return v - - -# ---- the program text ---- - -_REG = re.compile(r"([sv])(\d+)$") -_SRC = re.compile(r"(-?)(\|?)([sv]\d+)\|?$") -_MOD = re.compile(r"\s+(op_sel:\[[01](?:,[01])*\]|op_sel_hi:\[[01],[01],[01]\]|clamp|mul:[24]|div:2)$") - - -def split_line(line): - """'op d, a, b mods' -> (op, [operands], [mods]).""" - mods = [] - while True: - m = _MOD.search(line) - if not m: - break - mods.insert(0, m.group(1)) - line = line[:m.start()] - op, _, rest = line.partition(" ") - return op, [t.strip() for t in rest.split(",")], mods - - -def _bits(mods, name, n): - m = next((x for x in mods if x.startswith(name + ":")), None) - if m is None: - return [0] * n - b = [int(x) for x in m.split("[")[1].rstrip("]").split(",")] - if len(b) != n: - raise HarnessError(f"{m}: want {n} bits") - return b - - -class Machine: - """The reference's register file: words plus per-half NaN states (see NAN16 above).""" - - def __init__(self): - self.v = {} - self.s = {} - self.st = {} # vgpr -> [lo state, hi state] - - def state(self, r): - return self.st.setdefault(r, [None, None]) - - def raw(self, tok): - """(32-bit word, [lo state, hi state], kind) of a source token, modifiers stripped.""" - m = _SRC.match(tok) - if m: - reg = m.group(3) - k, i = reg[0], int(reg[1:]) - if k == "v": - if i not in self.v: - raise HarnessError(f"v{i} read before it is written") - return self.v[i], list(self.state(i)), "vgpr" - if i not in self.s: - raise HarnessError(f"s{i} read before it is written") - return self.s[i], [None, None], "sgpr" - if tok in FLOAT_INLINE: - return None, [None, None], "float" - if tok.startswith("0x"): - return int(tok, 16), [None, None], "lit" - try: - n = int(tok) - except ValueError: - raise HarnessError(f"unknown source {tok!r}") from None - if n not in INT_INLINE: - raise HarnessError(f"{n} is not an inline constant") - return n & M32, [None, None], "int" - - def f16(self, tok, hi=0): - """An f16 operand: (value, known bits or None). neg/abs applied.""" - m = _SRC.match(tok) - mod = (m.group(1) + m.group(2)) if m else "" - base = m.group(3) if m else tok - if base in FLOAT_INLINE: - h = 0 if hi else FLOAT_INLINE[base][1] - st = None - else: - w, sts, _ = self.raw(base) - h = (w >> 16) & M16 if hi else w & M16 - st = sts[1 if hi else 0] - if st == "w32": - raise NotJudged("half of an f32 NaN read as an f16") - if "|" in mod: - h &= 0x7FFF - if mod.startswith("-"): - h ^= 0x8000 - if st == "nan": - return ("nan", h >> 15, None), None - return decode16(h), h - - def f32(self, tok): - """An f32 operand of v_fma_mix_*: (value, None); a denormal reads as a signed zero.""" - m = _SRC.match(tok) - mod = (m.group(1) + m.group(2)) if m else "" - base = m.group(3) if m else tok - if base in FLOAT_INLINE: - w, sts = FLOAT_INLINE[base][0], [None, None] - else: - w, sts, _ = self.raw(base) - if sts == ["w32", "w32"]: - return ("nan", 0, None) - if sts != [None, None]: - raise NotJudged("an f16 NaN of unmodelled payload read as f32 bits") - if "|" in mod: - w &= 0x7FFFFFFF - if mod.startswith("-"): - w ^= 0x80000000 - return decode32(w, flush=True) - - def i16(self, tok, hi=0): - if _SRC.match(tok) and tok[0] in "-|": - raise HarnessError("modifier on an integer operand") - w, sts, kind = self.raw(tok) - if kind == "float": - raise HarnessError("float constant as an i16") - if sts[1 if hi else 0] is not None: - raise NotJudged("an unmodelled NaN payload read as an i16") - h = (w >> 16) & M16 if hi else w & M16 - return h - 0x10000 if h & 0x8000 else h - - def dst(self, tok): - m = _REG.match(tok) - if not m or m.group(1) != "v": - raise HarnessError(f"destination {tok!r}") - return int(m.group(2)) - - def write_half(self, r, hi, h, st=None): - old = self.v.get(r, 0) - sts = self.state(r) - if hi: - self.v[r] = (old & M16) | ((h & M16) << 16) - else: - self.v[r] = (old & 0xFFFF0000) | (h & M16) - sts[1 if hi else 0] = st - - def write_word(self, r, w, st=None): - self.v[r] = w & M32 - self.st[r] = [st, st] - - -def _out16(value): - """(bits, state) of an f16 result; a NaN the reference computed has no modelled payload.""" - if value[0] == "nan": - return NAN16, "nan" - return encode16(value), None - - -def _count_in(events, op, *vals): - if events is None: - return - ev = events.setdefault(op, Counter()) - for v in vals: - if v[0] == "nan": - ev["NaN"] += 1 - elif v[0] == "inf": - ev["inf"] += 1 - elif v[2] != 0 and v[2] < Fraction(1, 1 << 14): - ev["denormal"] += 1 - - -def step(line, mc, events=None): - """Run one op line on the Machine.""" - op_full, args, mods = split_line(line) - op = op_full - for suf in ("_e32", "_e64"): - if op.endswith(suf): - op = op[:-len(suf)] - kind = FAMILY.get(op) - if kind is None: - raise HarnessError(f"op {op_full!r} is not in the family") - ev = None if events is None else events.setdefault(op, Counter()) - d = mc.dst(args[0]) - clamp = "clamp" in mods - # An output multiplier is a no-op on these f16 (and i16) results in the game's MODE (gfx1036): nothing to apply. - if any(m in OMODS for m in mods) and (kind not in OMOD_KINDS or op_full.endswith("_e32")): - raise HarnessError(f"output modifier on a form without one: {line}") - if kind in ("min3", "max3"): - sel = _bits(mods, "op_sel", 4) - vals = [mc.f16(t, sel[i])[0] for i, t in enumerate(args[1:4])] - _count_in(events, op, *vals) - live = [v for v in vals if v[0] != "nan"] - if not live: - r = ("nan", 0, None) # the hardware returns src0's bits, the translator a quiet NaN: any NaN - else: - r = (min if kind == "min3" else max)(live, key=_key) - if clamp: - r = clamp01(r) - h, st = _out16(r) - mc.write_half(d, sel[3], h, st) - elif kind in ("mant", "exp"): - sel = _bits(mods, "op_sel", 2) - v, h = mc.f16(args[1], sel[0]) - _count_in(events, op, v) - if kind == "exp": # clamp (and an omod) leave the integer result as it is (gfx1036) - e = _ilog2(v[2]) + 1 if v[0] == "num" and v[2] != 0 else 0 - mc.write_half(d, sel[1], e & M16) - return - if v[0] == "num" and v[2] != 0: - r = ("num", v[1], v[2] / Fraction(2) ** (_ilog2(v[2]) + 1)) - else: - r = v - if clamp: - r = clamp01(r, nan_to_zero=True) - if r[0] == "nan": - mc.write_half(d, sel[1], NAN16 if h is None else h, "nan" if h is None else None) - else: - mc.write_half(d, sel[1], encode16(r)) - elif kind == "ldexp": - sel = _bits(mods, "op_sel", 3) - v, h = mc.f16(args[1], sel[0]) - n = max(-64, min(64, mc.i16(args[2], sel[1]))) - _count_in(events, op, v) - if v[0] == "num" and v[2] != 0: - r = round_to(("num", v[1], v[2] * Fraction(2) ** n), F16, ev) - else: - r = v - if clamp: - r = clamp01(r, nan_to_zero=True) - if r[0] == "nan": - mc.write_half(d, sel[2], NAN16 if h is None else h, "nan" if h is None else None) - else: - mc.write_half(d, sel[2], encode16(r)) - elif kind in ("fmamk", "fmaak"): - a = mc.f16(args[1])[0] - b = mc.f16(args[2])[0] - c = mc.f16(args[3])[0] - _count_in(events, op, a, b, c) - h, st = _out16(round_to(fma(a, b, c), F16, ev)) - mc.write_half(d, 0, h, st) - elif kind == "pkfmac": - acc = [] - for hi in (0, 1): - a = mc.f16(args[1], hi)[0] - b = mc.f16(args[2], hi)[0] - c = mc.f16(args[0], hi)[0] - _count_in(events, op, a, b, c) - acc.append(_out16(round_to(fma(a, b, c), F16, ev))) - for hi in (0, 1): - mc.write_half(d, hi, acc[hi][0], acc[hi][1]) - else: # v_fma_mix_* - sel = _bits(mods, "op_sel", 3) - shi = _bits(mods, "op_sel_hi", 3) - vals = [mc.f16(t, sel[i])[0] if shi[i] else mc.f32(t) for i, t in enumerate(args[1:4])] - _count_in(events, op, *vals) - r = fma(*vals) - if clamp: - r = clamp01(r) - if kind == "mix32": - r = round_to(r, F32, ev) - if r[0] == "nan": - mc.write_word(d, NAN32, "w32") - else: - mc.write_word(d, encode32(r)) - else: - h, st = _out16(round_to(r, F16, ev)) - mc.write_half(d, 1 if kind == "mixhi" else 0, h, st) - - -def reference(lines, events=None): - """Run the program; returns (four exported words, per-word half states). Raises NotJudged.""" - mc = Machine() - for line in lines: - op, args, _ = split_line(line) - if op == "v_mov_b32": - mc.write_word(mc.dst(args[0]), int(args[1], 16)) - elif op == "s_mov_b32": - mc.s[int(args[0][1:])] = int(args[1], 16) & M32 - else: - step(line, mc, events) - return [mc.v[r] for r in EXPORT_REGS], [list(mc.state(r)) for r in EXPORT_REGS] - - -def compare(want, states, got): - """None when every judged bit agrees, else a description of the first difference.""" - for i, (w, sts, g) in enumerate(zip(want, states, got)): - g &= M32 - if sts == ["w32", "w32"]: - if not ((g >> 23) & 0xFF == 0xFF and g & 0x7FFFFF): - return f"word {i} (v{EXPORT_REGS[i]}): expected an f32 NaN, actual 0x{g:08x}" - continue - for hi in (0, 1): - st = sts[hi] - wh, gh = (w >> (16 * hi)) & M16, (g >> (16 * hi)) & M16 - if st == "w32": - continue - if st == "nan": - if not ((gh >> 10) & 0x1F == 0x1F and gh & 0x3FF): - return (f"word {i} (v{EXPORT_REGS[i]}) {'high' if hi else 'low'} half: expected an f16 NaN, " - f"actual 0x{g:08x}") - elif wh != gh: - return f"word {i} (v{EXPORT_REGS[i]}): expected 0x{w:08x}, actual 0x{g:08x}" - return None - - -# ---- the generator ---- - -F16_EDGES = (0x0000, 0x8000, 0x0001, 0x8001, 0x0200, 0x03FF, 0x83FF, 0x0400, 0x8400, 0x0401, 0x3555, 0x3800, - 0xB800, 0x3BFF, 0x3C00, 0xBC00, 0x3C01, 0x4000, 0xC000, 0x5640, 0x7800, 0x7BFF, 0xFBFF, 0x7C00, - 0xFC00, 0x7C01, 0xFC01, 0x7D00, 0x7E00, 0xFE00, 0x7FFF) -F32_EDGES = (0x00000000, 0x80000000, 0x00000001, 0x807FFFFF, 0x00800000, 0x3F800000, 0xBF800000, 0x3F000000, - 0x477FE000, 0x477FF000, 0x477FEFFF, 0x387FC000, 0x33800000, 0x33000000, 0x7F7FFFFF, 0x7F800000, - 0xFF800000, 0x7FC00000, 0xFFC00000, 0x7FA00000, 0x40490FDB) -I16_EDGES = (0, 1, -1, 2, -2, 10, -10, 14, -14, 15, -15, 16, -16, 24, -24, 25, -25, 29, 30, -30, 31, 40, -40, - 63, -63, 64, -64, 65, -65, 100, -100, 32767, -32768) - - -def _rand_f16(rng): - r = rng.random() - if r < 0.3: - return rng.choice(F16_EDGES) - if r < 0.4: - return (rng.getrandbits(1) << 15) | rng.randrange(1, 0x400) # denormal - if r < 0.5: - return rng.getrandbits(16) - e = rng.randrange(1, 31) if rng.random() < 0.3 else rng.randrange(11, 20) # mostly near 1 - return (rng.getrandbits(1) << 15) | (e << 10) | rng.getrandbits(10) - - -def _rand_f32(rng): - r = rng.random() - if r < 0.3: - return rng.choice(F32_EDGES) - if r < 0.4: - return rng.getrandbits(32) - e = rng.randrange(1, 255) if rng.random() < 0.3 else rng.randrange(100, 145) - return (rng.getrandbits(1) << 31) | (e << 23) | rng.getrandbits(23) - - -def _seed_word(rng): - r = rng.random() - if r < 0.6: - return _rand_f16(rng) | (_rand_f16(rng) << 16) - if r < 0.8: - return _rand_f32(rng) - return (rng.choice(I16_EDGES) & M16) | (_rand_f16(rng) << 16) - - -def _source(rng, kind): - """A source token of ``kind`` (no modifier).""" - if kind == "vgpr": - return f"v{rng.choice(VGPRS)}" - if kind == "sgpr": - return f"s{rng.choice(SGPRS)}" - if kind == "lit": - r = rng.random() - if r < 0.5: - return f"0x{_rand_f16(rng) | (_rand_f16(rng) << 16):08x}" - if r < 0.8: - return f"0x{_rand_f32(rng):08x}" - return f"0x{(rng.choice(I16_EDGES) & M16) | (rng.getrandbits(16) << 16):08x}" - if kind == "int": - return str(rng.choice(INT_INLINE)) - return rng.choice(tuple(FLOAT_INLINE)) - - -def encodable(kinds, form): - """GFX10: one literal, VOP3/VOP3P at most two constant-bus reads (SGPRs and the literal); VOP1/VOP2 e32 take a - literal or SGPR only in src0 (and VOP2 vsrc1 is a VGPR).""" - lits = sum(k == "lit" for k in kinds) - bus = sum(k in ("sgpr", "lit") for k in kinds) - if lits > 1: - return False - if form == "vop3": - return bus <= 2 - return all(k == "vgpr" for k in kinds[1:]) - - -def _reg_mod(rng, tok, kind): - if kind not in ("vgpr", "sgpr"): - return tok - m = rng.choice(MODS) - return f"{'-' if m.startswith('-') else ''}{'|' if '|' in m else ''}{tok}{'|' if '|' in m else ''}" - - -def op_line(rng, op, kinds=None, form=None, mods=True, values=None): - """One line of ``op``. ``kinds`` fixes the source kinds (else random), ``form`` the encoding ("e32"/"e64" for - VOP1/VOP2 ops), ``values`` optional exact source tokens.""" - kind = FAMILY[op] - d = f"v{rng.choice(DSTS)}" - - def pick(n, allowed=KINDS, vop3=True): - while True: - ks = list(kinds) if kinds else [rng.choice(allowed) for _ in range(n)] - if encodable(ks, "vop3" if vop3 else "vop2"): - return ks - if kinds: - raise HarnessError(f"{op}: {kinds} not encodable") - - if kind in ("min3", "max3") or kind in ("mix32", "mixlo", "mixhi"): - ks = pick(3) - toks = values or [_source(rng, k) for k in ks] - srcs = [_reg_mod(rng, t, k) if mods else t for t, k in zip(toks, ks)] - if kind in ("min3", "max3"): - sel = [rng.getrandbits(1) if k in ("vgpr", "sgpr") else 0 for k in ks] + [rng.getrandbits(1)] - extra = f" op_sel:[{','.join(map(str, sel))}]" if any(sel) or rng.random() < 0.2 else "" - else: - shi = [rng.getrandbits(1) for _ in ks] - sel = [rng.getrandbits(1) if (k in ("vgpr", "sgpr") and h) else 0 for k, h in zip(ks, shi)] - extra = f" op_sel:[{','.join(map(str, sel))}] op_sel_hi:[{','.join(map(str, shi))}]" - if mods and rng.random() < 0.25: - extra += " clamp" - if kind in ("min3", "max3") and mods and rng.random() < 0.2: - extra += " " + rng.choice(OMODS) - return f"{op} {d}, {', '.join(srcs)}{extra}", ks - if kind in ("mant", "exp"): - form = form or rng.choice(("e32", "e64")) - ks = pick(1) - tok = values[0] if values else _source(rng, ks[0]) - if form == "e32": - return f"{op}_e32 {d}, {tok}", ks - src = _reg_mod(rng, tok, ks[0]) if mods else tok - sel = [rng.getrandbits(1) if ks[0] in ("vgpr", "sgpr") else 0, rng.getrandbits(1)] - extra = f" op_sel:[{sel[0]},{sel[1]}]" if any(sel) or rng.random() < 0.2 else "" - if mods and rng.random() < 0.25: - extra += " clamp" - if mods and rng.random() < 0.2: - extra += " " + rng.choice(OMODS) - return f"{op}_e64 {d}, {src}{extra}", ks - if kind == "ldexp": - form = form or rng.choice(("e32", "e64")) - if form == "e32": - ks = pick(2, vop3=False) if kinds else [rng.choice(KINDS), "vgpr"] - toks = values or [_source(rng, ks[0]), _source(rng, "vgpr")] - return f"{op}_e32 {d}, {toks[0]}, {toks[1]}", ks - while True: - ks = list(kinds) if kinds else [rng.choice(KINDS), rng.choice(("vgpr", "sgpr", "lit", "int"))] - if ks[1] == "float": - raise HarnessError("float constant as ldexp's exponent") - if encodable(ks, "vop3"): - break - if kinds: - raise HarnessError(f"{op}: {kinds} not encodable") - toks = values or [_source(rng, k) for k in ks] - src0 = _reg_mod(rng, toks[0], ks[0]) if mods else toks[0] - sel = [rng.getrandbits(1) if ks[0] in ("vgpr", "sgpr") else 0, - rng.getrandbits(1) if ks[1] in ("vgpr", "sgpr") else 0, rng.getrandbits(1)] - extra = f" op_sel:[{','.join(map(str, sel))}]" if any(sel) or rng.random() < 0.2 else "" - if mods and rng.random() < 0.25: - extra += " clamp" - if mods and rng.random() < 0.2: - extra += " " + rng.choice(OMODS) - return f"{op}_e64 {d}, {src0}, {toks[1]}{extra}", ks - if kind in ("fmamk", "fmaak"): - k0 = kinds[0] if kinds else rng.choice(("vgpr", "sgpr", "int", "float")) - ks = [k0, "vgpr"] - toks = values or [_source(rng, k0), _source(rng, "vgpr"), f"0x{_rand_f16(rng):04x}"] - if kind == "fmamk": - return f"{op} {d}, {toks[0]}, {toks[2]}, {toks[1]}", ks - return f"{op} {d}, {toks[0]}, {toks[1]}, {toks[2]}", ks - # v_pk_fmac_f16 - k0 = kinds[0] if kinds else rng.choice(KINDS) - ks = [k0, "vgpr"] - toks = values or [_source(rng, k0), _source(rng, "vgpr")] - return f"{op} {d}, {toks[0]}, {toks[1]}", ks - - -def seeds(rng): - lines = [f"v_mov_b32 v{r}, 0x{_seed_word(rng):08x}" for r in VGPRS] - lines += [f"s_mov_b32 s{r}, 0x{_seed_word(rng):08x}" for r in SGPRS] - return lines - - -def program(rng, n_ops, ops=None): - """A random program: seeds, n_ops family ops, the export. Returns (lines, the ops used).""" - ops = list(ops or FAMILY) - lines = seeds(rng) - used = [] - for _ in range(n_ops): - op = rng.choice(ops) - lines.append(op_line(rng, op)[0]) - used.append(op) - return lines, used - - -def sweep_cases(ops=None): - """(op, form, kinds) for every encodable source-kind combination of every op and form.""" - cases = [] - for op in ops or FAMILY: - kind = FAMILY[op] - if kind in ("min3", "max3", "mix32", "mixlo", "mixhi"): - for a in KINDS: - for b in KINDS: - for c in KINDS: - if encodable([a, b, c], "vop3"): - cases.append((op, None, (a, b, c))) - elif kind in ("mant", "exp"): - for form in ("e32", "e64"): - for a in KINDS: - cases.append((op, form, (a,))) - elif kind == "ldexp": - for a in KINDS: - cases.append((op, "e32", (a, "vgpr"))) - for b in ("vgpr", "sgpr", "lit", "int"): - if encodable([a, b], "vop3"): - cases.append((op, "e64", (a, b))) - elif kind in ("fmamk", "fmaak"): - for a in ("vgpr", "sgpr", "int", "float"): - cases.append((op, None, (a, "vgpr"))) - else: - for a in KINDS: - cases.append((op, None, (a, "vgpr"))) - return cases - - -SWEEP_REPEAT = 2 - - -def sweep_program(case, rng): - op, form, kinds = case - return seeds(rng) + [op_line(rng, op, kinds, form)[0]] - - -GRID_PER_PROGRAM = 4 -_GRID_RNG_SEED = "f16misc_diff:grid" - - -def grid_cases(ops=None): - """(op, source words[, "clamp"]) cases: special values through every op. Each case is one op line reading - v12..v15; frexp_mant and ldexp also run the edges with clamp (a NaN gives +0).""" - rng = random.Random(_GRID_RNG_SEED) - ops = list(ops or FAMILY) - cases = [] - edges = F16_EDGES - for op in ops: - kind = FAMILY[op] - if kind in ("mant", "exp"): - for h in edges: - cases.append((op, (h | (rng.getrandbits(16) << 16),))) - if kind == "mant": - for h in edges: - cases.append((op, (h | (rng.getrandbits(16) << 16),), "clamp")) - elif kind == "ldexp": - for h in edges: - for n in (-64, -25, -24, -15, -1, 0, 1, 15, 29, 30, 64, 100): - cases.append((op, (h, n & M16))) - for h in edges: - for n in (-1, 0, 1): - cases.append((op, (h, n & M16), "clamp")) - elif kind in ("min3", "max3"): - pick = (0x0000, 0x8000, 0x0001, 0x3C00, 0xBC00, 0x7C00, 0xFC00, 0x7E00, 0x7D00, 0x4000) - for a in pick: - for b in pick: - for c in pick: - if (a, b, c).count(0x7E00) + (a, b, c).count(0x7D00) == 3: - continue # every operand NaN: payload not modelled, see the docstring - cases.append((op, (a, b, c))) - else: - for _ in range(240): - cases.append((op, _fma_case(rng, kind))) - return cases - - -def _pow2_16(e, mant=0): - """The f16 2^e * (1 + mant/1024), e in [-14, 15].""" - return ((e + 15) << 10) | mant - - -# (a, c, d): the f16 mantissas 1 + a/1024 and (2048 - c)/2048 multiply to 1 + d/2^21 with 0 < |d| < 256. Added to -# half an ulp of an f16 z, that product is off the tie by less than half an f32 ulp of the sum: an f32 fma rounds -# it onto the tie and the f16 rounding then goes to even, so an fma rounded twice is wrong in about half the cases. -NEAR_ONE = tuple((a, c, (1024 + a) * (2048 - c) - (1 << 21)) - for a in range(1, 64) for c in range(max(1, 2 * a - 3), 2 * a + 4) - if 0 < abs((1024 + a) * (2048 - c) - (1 << 21)) < 256) - - -def _tie_case(rng, f32_addend): - """x * y + z with x * y = +-half an ulp of z, or a hair above or below it: z + x*y is a rounding tie (or the - nearest non-tie) of the result format (f16, or f32 when ``f32_addend``). x and y are f16 powers of two times - 1, 1 + 2^-10 or 1 - 2^-11, or a NEAR_ONE pair (x * y = 2^k (1 + d/2^21)).""" - if f32_addend: - ez = rng.randrange(125, 170) # biased f32 exponent of z; half its ulp is 2^(ez - 151) - z = (rng.getrandbits(1) << 31) | (ez << 23) | rng.getrandbits(23) - k = ez - 151 - else: - ez = rng.randrange(5, 31) # biased f16 exponent; half an ulp is 2^(ez - 26) - z = (rng.getrandbits(1) << 15) | (ez << 10) | rng.getrandbits(10) - k = ez - 26 - a = max(-14, min(15, k // 2)) - b = k - a - if not -14 <= b <= 15: - return (0x3C00, 0x3C00, z) - sx = rng.getrandbits(1) << 15 - if rng.random() < 0.4 and b - 1 >= -14: - am, c, _ = rng.choice(NEAR_ONE) - return (_pow2_16(a, am) | sx, _pow2_16(b - 1, 1024 - c), z) - mant, eb = rng.choice(((0, b), (0, b), (1, b), (0x3FF, b - 1))) # 1, 1 + 2^-10, (2 - 2^-10) / 2 - if not -14 <= eb <= 15: - mant, eb = 0, b - return (_pow2_16(a) | sx, _pow2_16(eb, mant), z) - - -def _fma_case(rng, kind): - """Three source words for an fma op, aimed at ties, cancellation, overflow and the denormal range.""" - r = rng.random() - if kind == "mix32" or (kind in ("mixlo", "mixhi") and rng.random() < 0.5): - f = _rand_f32 - else: - f = _rand_f16 - x, y = f(rng), f(rng) - if r < 0.3: - return _tie_case(rng, kind == "mix32") - if r < 0.45: - z = f(rng) - elif r < 0.6: - # z = -(x*y) rounded: the sum cancels to the product's rounding error - z = _neg_product(x, y, f is _rand_f16) - elif r < 0.8: - z = rng.choice(F16_EDGES if f is _rand_f16 else F32_EDGES) - else: - z = 0 if rng.random() < 0.5 else (0x8000 if f is _rand_f16 else 0x80000000) - return (x, y, z) - - -def _neg_product(x, y, half): - a = decode16(x) if half else decode32(x, flush=False) - b = decode16(y) if half else decode32(y, flush=False) - p = fma(a, b, ("num", 0, Fraction(0))) - if p[0] != "num": - return x - r = round_to(("num", p[1] ^ 1, p[2]), F16 if half else F32) - if r[0] != "num": - return x - try: - return encode16(r) if half else encode32(r) - except NotJudged: - return 0 - - -def grid_program(chunk, rng): - """A program for up to GRID_PER_PROGRAM grid cases. Case i reads only its own registers and writes v{8+i}.""" - lines = [f"v_mov_b32 v{r}, 0x{rng.getrandbits(32):08x}" for r in VGPRS] - lines += [f"s_mov_b32 s{r}, 0x{rng.getrandbits(32):08x}" for r in SGPRS] - body = [] - for i, (op, words, *flags) in enumerate(chunk): - kind = FAMILY[op] - d = f"v{DSTS[i]}" - clamp = " clamp" if "clamp" in flags else "" - if kind in ("mant", "exp"): - lines.append(f"v_mov_b32 v{12 + i}, 0x{words[0]:08x}") - body.append(f"{op}_e64 {d}, v{12 + i}{clamp}") - elif kind == "ldexp": - lines.append(f"v_mov_b32 v{12 + i}, 0x{words[0] | (words[1] << 16):08x}") - body.append(f"{op}_e64 {d}, v{12 + i}, v{12 + i} op_sel:[0,1,0]{clamp}") - elif kind in ("min3", "max3"): - # the three halves: v{12+i} lo, v{12+i} hi and d's own high half (read before it is written) - lines.append(f"v_mov_b32 v{12 + i}, 0x{words[0] | (words[1] << 16):08x}") - lines.append(f"v_mov_b32 {d}, 0x{(words[2] << 16) | 0x1234:08x}") - body.append(f"{op} {d}, v{12 + i}, v{12 + i}, {d} op_sel:[0,1,1,0]") - elif kind in ("fmamk", "fmaak"): - # words are (x, y, z) of x * y + z: fmamk D = S0 * K + S1 takes y as K, fmaak D = S0 * S1 + K takes z - kw, dw = (words[1], words[2]) if kind == "fmamk" else (words[2], words[1]) - lines.append(f"v_mov_b32 v{12 + i}, 0x{words[0] | (rng.getrandbits(16) << 16):08x}") - lines.append(f"v_mov_b32 {d}, 0x{dw | (rng.getrandbits(16) << 16):08x}") - k = f"0x{kw:04x}" - if kind == "fmamk": - body.append(f"{op} {d}, v{12 + i}, {k}, {d}") - else: - body.append(f"{op} {d}, v{12 + i}, {d}, {k}") - elif kind == "pkfmac": - # lane 0: words, lane 1: the same values negated - lines.append(f"v_mov_b32 v{12 + i}, 0x{words[0] | ((words[0] ^ 0x8000) << 16):08x}") - lines.append(f"v_mov_b32 {d}, 0x{words[2] | ((words[2] ^ 0x8000) << 16):08x}") - lines.append(f"s_mov_b32 s{4 + i}, 0x{words[1] | (words[1] << 16):08x}") - body.append(f"{op} {d}, s{4 + i}, v{12 + i}") - else: - # f32 words are read whole (op_sel_hi 0), f16 values from the low half (op_sel_hi 1) - regs = [f"v{12 + i}", f"s{4 + i}", d] - lines.append(f"v_mov_b32 v{12 + i}, 0x{words[0]:08x}") - lines.append(f"s_mov_b32 s{4 + i}, 0x{words[1]:08x}") - lines.append(f"v_mov_b32 {d}, 0x{words[2]:08x}") - shi = [0 if w > M16 else 1 for w in words] - body.append(f"{op} {d}, {', '.join(regs)} op_sel:[0,0,0] op_sel_hi:[{','.join(map(str, shi))}]") - return lines + body - - -def exhaustive_programs(ops=None): - """(op, lines) programs: every f16 input through the frexp ops and ldexp, four inputs per program, yielded one at - a time.""" - exps = (-64, -25, -15, -1, 1, 15, 30, 64) - for op in ("v_frexp_mant_f16", "v_frexp_exp_i16_f16", "v_ldexp_f16"): - if ops and op not in ops: - continue - for base in range(0, 0x10000, GRID_PER_PROGRAM): - lines, body = [], [] - for i in range(GRID_PER_PROGRAM): - h = base + i - d = f"v{DSTS[i]}" - if op == "v_ldexp_f16": - n = exps[(h >> 2) % len(exps)] & M16 - lines.append(f"v_mov_b32 v{12 + i}, 0x{h | (n << 16):08x}") - body.append(f"{op}_e64 {d}, v{12 + i}, v{12 + i} op_sel:[0,1,0]") - else: - lines.append(f"v_mov_b32 v{12 + i}, 0x{h | 0xabcd0000:08x}") - body.append(f"{op}_e32 {d}, v{12 + i}") - yield op, [f"v_mov_b32 v{r}, 0x5a5a5a5a" for r in DSTS] + lines + body - - -# ---- the oracles ---- - -def write_listing(path, lines, name): - with open(path, "w", encoding="utf-8", newline="\n") as f: - f.write(f"; {name} code 0x0..0x1000\n") - for line in lines: - f.write("\t" + line + "\n") - f.write("\t" + EXPORT + "\n") - f.write("\ts_endpgm\n") - - -def translate_listing(lines, name, tmpdir): - """The four mrt0 words the translator path produces. Raises rdna2spirv.Unsupported (and the mini interp's - UnsupportedConstruct) for anything outside the oracles' model.""" - dis = os.path.join(tmpdir, "disasm") - os.makedirs(dis, exist_ok=True) - path = os.path.join(dis, name + ".s") - write_listing(path, lines, name) - with open(os.path.join(tmpdir, name + ".dxbc"), "wb") as f: - f.write(STUB_DXBC) - with warnings.catch_warnings(): - warnings.simplefilter("ignore", ResourceWarning) - spvasm = rdna2spirv.translate(path) - gc.collect() - out = run_fragment(spvasm) - if list(out) != ["%out_mrt0"]: - raise HarnessError(f"outputs {sorted(out)}, want %out_mrt0") - return [w & M32 for w in out["%out_mrt0"]] - - -def check(lines, name="ps_f16m_case"): - """None when both oracles agree, else the first difference.""" - with tempfile.TemporaryDirectory(prefix="f16m-diff-") as tmp: - want, states = reference(lines) - got = translate_listing(lines, name, tmp) - return compare(want, states, got) - - -def run_one(lines, name, tmpdir, events=None): - """(status, detail) with status in {"match", "mismatch", "skip", "unjudged"}.""" - try: - want, states = reference(lines, events) - except NotJudged as e: - return ("unjudged", str(e)) - try: - got = translate_listing(lines, name, tmpdir) - except (rdna2spirv.Unsupported, UnsupportedConstruct) as e: - return ("skip", f"{type(e).__name__}: {e}") - except (IndexError, KeyError, ValueError) as e: - return ("skip", f"translator error {type(e).__name__}: {e}") - diff = compare(want, states, got) - if diff: - return ("mismatch", diff) - return ("match", "") - - -# ---- the suites ---- - -def _new_counts(): - return {"pass": 0, "mismatch": 0, "skip": Counter(), "unjudged": Counter(), "ops": Counter(), "events": {}} - - -def _tally(counts, status, detail): - if status == "match": - counts["pass"] += 1 - elif status in ("skip", "unjudged"): - counts[status][detail] += 1 - else: - counts["mismatch"] += 1 - - -def _run(counts, items, tag): - failure = None - with tempfile.TemporaryDirectory(prefix=f"f16m-diff-{tag}-") as tmp: - for i, (label, lines, used) in enumerate(items): - counts["ops"].update(used) - status, detail = run_one(lines, f"ps_f16m_{tag}{i:05d}", tmp, counts["events"]) - _tally(counts, status, detail) - if status == "mismatch" and failure is None: - failure = (label, lines, detail) - return failure - - -# Each stage yields its (label, lines, ops) items one at a time, so a run holds one program's text, not the whole list. -def sweep_items(seed, ops=None): - for case in sweep_cases(ops): - op, form, kinds = case - for rep in range(SWEEP_REPEAT): - tag = f"{op}:{form}:{'/'.join(kinds)}:{rep}" - rng = random.Random(f"{seed}:{tag}") - yield f"sweep {tag} (seed {seed})", sweep_program(case, rng), [op] - - -def grid_items(ops=None): - cases = grid_cases(ops) - rng = random.Random("f16misc_diff:grid-programs") - for i in range(0, len(cases), GRID_PER_PROGRAM): - chunk = cases[i:i + GRID_PER_PROGRAM] - yield f"edge grid program {i // GRID_PER_PROGRAM}", grid_program(chunk, rng), [c[0] for c in chunk] - - -def suite_items(programs, seed, max_ops=6, ops=None): - rng = random.Random(f"suite:{seed}") - for i in range(programs): - lines, used = program(rng, rng.randint(1, max_ops), ops) - yield f"program {i} (seed {seed})", lines, used - - -def run_sweep(seed, ops=None): - counts = _new_counts() - return counts, _run(counts, sweep_items(seed, ops), "sw") - - -def run_grid(ops=None): - counts = _new_counts() - return counts, _run(counts, grid_items(ops), "gr") - - -def run_exhaustive(ops=None): - counts = _new_counts() - items = ((f"exhaustive f16 program {i} ({op})", lines, [op] * GRID_PER_PROGRAM) - for i, (op, lines) in enumerate(exhaustive_programs(ops))) - return counts, _run(counts, items, "ex") - - -def run_suite(programs, seed, max_ops=6, ops=None): - counts = _new_counts() - return counts, _run(counts, suite_items(programs, seed, max_ops, ops), "rn") - - -REJECTED = ( - ("neg on v_pk_fmac_f16", "v_pk_fmac_f16 v8, -v9, v10"), - ("clamp on v_pk_fmac_f16", "v_pk_fmac_f16 v8, v9, v10 clamp"), -) - - -def self_test(): - ok = True - - def report(good, what): - nonlocal ok - ok &= good - print(("ok " if good else "FAIL ") + what) - - # reference spot checks, from docs/design.md and tests/semantic - mc = Machine() - mc.write_word(9, 0x00010001) - step("v_frexp_mant_f16_e32 v8, v9", mc) - report(mc.v[8] & M16 == 0x3800, "frexp_mant(0x0001) = 0.5 (0x3800)") - step("v_frexp_exp_i16_f16_e32 v8, v9", mc) - report(mc.v[8] & M16 == (-23) & M16, "frexp_exp(0x0001) = -23") - mc.write_word(9, 0x000003FF) - step("v_frexp_mant_f16_e32 v8, v9", mc) - report(mc.v[8] & M16 == 0x3BFE, "frexp_mant(0x03ff) = 0x3bfe") - for h, n, want in ((0x3C00, -15, 0x0200), (0x3E00, -24, 0x0002), (0x3C00, -25, 0x0000), (0x7BFF, -30, 0x0400)): - mc.write_word(9, h | ((n & M16) << 16)) - step("v_ldexp_f16_e64 v8, v9, v9 op_sel:[0,1,0]", mc) - report(mc.v[8] & M16 == want, f"ldexp(0x{h:04x}, {n}) = 0x{want:04x}") - for words, want in (((0x3C00, 0x0000, 0x3C00), 0x0000), ((0x0000, 0x8000, 0x0000), 0x8000), - ((0xBC00, 0x7C01, 0x0000), 0xBC00), ((0x0001, 0x4000, 0x8000), 0x8000)): - mc.write_word(9, words[0]) - mc.write_word(10, words[1]) - mc.write_word(11, words[2]) - mc.write_word(8, 0xDEADBEEF) - step("v_min3_f16 v8, v9, v10, v11", mc) - report(mc.v[8] == 0xDEAD0000 | want, f"min3{tuple(hex(w) for w in words)} = 0xdead{want:04x}") - # output multipliers are no-ops on f16 results and clamp still acts; frexp_exp ignores both (gfx1036) - mc.write_word(9, 0x12343A00) - mc.write_word(11, 0x9ABC4100) - mc.write_word(12, 3) - for line, want in (("v_frexp_mant_f16_e64 v8, v11 mul:4", 0x3900), - ("v_frexp_exp_i16_f16_e64 v8, v11 clamp mul:2", 2), - ("v_ldexp_f16_e64 v8, v9, v12 div:2", 0x4600), - ("v_ldexp_f16_e64 v8, v11, v12 clamp mul:2", 0x3C00)): - step(line, mc) - report(mc.v[8] & M16 == want, f"{line} = 0x{want:04x}") - # the translator rejects the forms the generator leaves out - for what, line in REJECTED: - try: - with tempfile.TemporaryDirectory(prefix="f16m-diff-st-") as tmp: - translate_listing(seeds(random.Random(1)) + [line], "ps_f16m_rej", tmp) - report(False, f"{what}: the translator accepted it") - except (rdna2spirv.Unsupported, UnsupportedConstruct): - report(True, f"{what}: the translator rejected it") - a = program(random.Random("st"), 5)[0] - b = program(random.Random("st"), 5)[0] - report(a == b, "generation is deterministic for a seed") - counts, failure = run_suite(8, 1) - report(failure is None and not counts["skip"], - f"a short seeded run matches ({counts['pass']} programs, skips {dict(counts['skip'])})") - return ok - - -def main(): - ap = argparse.ArgumentParser(description=__doc__.split("\n")[0]) - ap.add_argument("--programs", type=int, default=300, help="random programs after the sweep") - ap.add_argument("--seed", type=int, default=1) - ap.add_argument("--max-ops", type=int, default=6, help="ops per random program") - ap.add_argument("--ops", default=None, help="comma-separated opcodes to cover (default: all eleven)") - ap.add_argument("--no-sweep", action="store_true", help="skip the source-kind sweep and the edge grid") - ap.add_argument("--exhaustive-f16", action="store_true", help="also run every f16 input through frexp/ldexp") - ap.add_argument("--list-ops", action="store_true") - ap.add_argument("--self-test", action="store_true") - args = ap.parse_args() - if args.list_ops: - for op in FAMILY: - print(f"{op:22s} {OP_FORMS[op]}") - return 0 - if args.self_test: - return 0 if self_test() else 1 - ops = None - if args.ops: - ops = [o.strip() for o in args.ops.split(",") if o.strip()] - bad = [o for o in ops if o not in FAMILY] - if bad: - print(f"unknown op(s): {', '.join(bad)} (see --list-ops)", file=sys.stderr) - return 2 - stages = [] - if not args.no_sweep: - stages += [("sweep", lambda: run_sweep(args.seed, ops)), ("edge grid", lambda: run_grid(ops))] - if args.exhaustive_f16: - stages.append(("exhaustive f16", lambda: run_exhaustive(ops))) - if args.programs > 0: - stages.append(("random", lambda: run_suite(args.programs, args.seed, args.max_ops, ops))) - total = {"pass": 0, "mismatch": 0, "skip": 0, "unjudged": Counter(), "ops": Counter(), "events": {}} - first = None - try: - for name, fn in stages: - counts, failure = fn() - n = counts["pass"] + counts["mismatch"] + sum(counts["skip"].values()) + sum(counts["unjudged"].values()) - print(f"{name}: {counts['pass']}/{n} programs match, {counts['mismatch']} mismatch; " - f"skips: {dict(counts['skip'])}; not judged: {sum(counts['unjudged'].values())}") - total["pass"] += counts["pass"] - total["mismatch"] += counts["mismatch"] - total["skip"] += sum(counts["skip"].values()) - total["unjudged"].update(counts["unjudged"]) - total["ops"].update(counts["ops"]) - for op, ev in counts["events"].items(): - total["events"].setdefault(op, Counter()).update(ev) - if failure and first is None: - first = failure - except HarnessError as e: - print(f"harness error: {e}", file=sys.stderr) - return 2 - print("op lines per op: " + ", ".join(f"{op} {n}" for op, n in sorted(total["ops"].items()))) - print("inputs/results per op (NaN / inf / denormal / tie / overflow): " + ", ".join( - f"{op} {ev['NaN']}/{ev['inf']}/{ev['denormal'] + ev['denormal result']}/{ev['tie']}/{ev['overflow']}" - for op, ev in sorted(total["events"].items()))) - if total["unjudged"]: - print("not judged: " + ", ".join(f"{why} {n}" for why, n in total["unjudged"].most_common())) - judged = total["pass"] + total["mismatch"] + total["skip"] - print(f"f16 misc family: {total['pass']}/{judged} judged programs match, {total['mismatch']} mismatch " - f"({len(total['ops'])} of {len(FAMILY)} ops)") - if first: - _report(first) - return 1 - if total["skip"]: - print(f"SKIPPED {total['skip']} program(s): every generated form should translate (reasons above)") - return 1 - return 0 - - -def _report(failure): - label, lines, detail = failure - print(f"\nFIRST MISMATCH: {label}: {detail}") - for line in lines: - print(" " + line) - - -if __name__ == "__main__": - try: # a redirected stdout is strict ANSI code page under -I; write '?' for what it cannot encode - sys.stdout.reconfigure(errors="replace") - except (AttributeError, ValueError, OSError): - pass - sys.exit(main()) diff --git a/tools/f32_fuzz.py b/tools/f32_fuzz.py deleted file mode 100644 index 1c0fe63d4..000000000 --- a/tools/f32_fuzz.py +++ /dev/null @@ -1,1770 +0,0 @@ -r"""Differential fuzzer for the translator's 32-bit float VALU (FUZZ-3; standard library only). - -Seeded programs of VOP1 / VOP2 / VOP3 float instructions (with neg/abs source modifiers, clamp and omod) run -through two independent sides and are compared bit-exact: - - * F32Model below: the RDNA2 ISA definitions ("RDNA 2" Instruction Set Architecture reference guide, chapter - 6 "Vector ALU Operations" and the VOP1/VOP2/VOP3/VOPC opcode tables), with exact rational arithmetic and one - round-to-nearest-even per operation. It shares no code with tools/rdna2spirv.py. - * tools/rdna2spirv.py -> tests/semantic/spirv_mini_interp.py (the translated SPIR-V, executed). - -What a comparison can and cannot say: - * NaN results match any NaN: payloads are not modelled (the interpreter passes floats through Python). - * Denormal f32 operands or results are skipped with a reason: whether the game's shaders flush f32 - denormals is the MODE register question (SHADER-35), not a property of these instructions. - * v_rcp/v_rsq/v_sqrt/v_exp/v_log are only fed inputs whose results are exact (0, inf, NaN, negatives, powers - of two); the hardware's 1-ULP approximations are out of scope. - * An input for which the translated SPIR-V is undefined (GLSL.std.450 FMax of NaN, OpFDiv by zero, Log2 of - 0, ...) while the ISA defines the result is reported as its own class, "undefined in SPIR-V": the - interpreter refuses to guess, and so does this tool. - -With --oracle hw (or translator,hw) the same programs also run natively on an AMD GPU (tools/hw_oracle/, wave32) and -the hardware is judged against F32Model: match / mismatch where the model has an answer, "known deviation" where the -hardware equals an analysed alternative (omod turns -0 into +0), and informational tables where the model declines -(denormals under four MODE settings, NaN payloads, clamp of NaN, omod under IEEE/denormal modes). GFX10.1-only opcodes -(v_mad_f32, v_mac_f32, v_madak_f32, v_madmk_f32, v_mad_legacy_f32) are skipped on gfx1030/GFX11 with a reason, never substituted. -v_min/max/min3/max3/med3_f32 are hardware-only ops. Exit 77 when the hardware tools are missing. See -docs/shader_validation.md ("32-bit float VALU on the GPU"). - -Usage: - python -I tools/f32_fuzz.py [--programs N] [--seed S] [--ops v_add_f32,...] [--show N] - python -I tools/f32_fuzz.py --oracle hw [--probes N] [--negative-control | --perturb NAME] [--no-info] - python -I tools/f32_fuzz.py --list-ops - python -I tools/f32_fuzz.py --self-test - -Exit code: 0 when every program matches, 1 when any mismatches, 2 on a harness error. Nothing here reads game -files. -""" -import argparse -import gc -import math -import os -import random -import struct -import sys -import tempfile -import warnings -from fractions import Fraction - -HERE = os.path.dirname(os.path.abspath(__file__)) -sys.dont_write_bytecode = True -TOOLS_DIR = os.environ.get("LEONIDA_TOOLS_DIR") or HERE -if TOOLS_DIR not in sys.path: - sys.path.insert(0, TOOLS_DIR) -SEM_DIR = os.path.join(os.path.dirname(HERE), "tests", "semantic") -if SEM_DIR not in sys.path: - sys.path.insert(0, SEM_DIR) - -# The translator is imported where it is used (run_translated, main), not here: rdna2spirv.py takes seconds to -# compile, and with dont_write_bytecode the compiled code is never cached, so --help and a usage error would wait -# for it on every run. -from spirv_mini_interp import run_fragment # noqa: E402 - -M32 = 0xFFFFFFFF -STUB_DXBC = b"DXBC" + bytes(24) + struct.pack("> 23) & 0xFF == 0xFF and b & 0x7FFFFF != 0 - - -def is_inf(b): - return b & 0x7FFFFFFF == PINF - - -def is_zero(b): - return b & 0x7FFFFFFF == 0 - - -def is_denorm(b): - return (b >> 23) & 0xFF == 0 and b & 0x7FFFFF != 0 - - -def sign(b): - return b >> 31 - - -def to_frac(b): - """Exact value of a finite f32.""" - e, m = (b >> 23) & 0xFF, b & 0x7FFFFF - v = Fraction(m, 1 << 23) * Fraction(2) ** -126 if e == 0 else Fraction((1 << 23) | m, 1 << 23) * Fraction(2) ** (e - 127) - return -v if sign(b) else v - - -def round_f32(v, neg_zero=False): - """Fraction -> f32 bits, round to nearest even, overflow to inf. `neg_zero`: the sign of an exact zero.""" - if v == 0: - return 0x80000000 if neg_zero else 0 - s = 0x80000000 if v < 0 else 0 - a = -v if v < 0 else v - e = a.numerator.bit_length() - a.denominator.bit_length() - if Fraction(2) ** e > a: - e -= 1 - if e < -126: - q = a / (Fraction(2) ** -149) # denormal: units of 2^-149 - n = _rne(q) - if n == 0: - return s - if n < (1 << 23): - return s | n - return s | (1 << 23) # rounded up to the smallest normal - q = a / (Fraction(2) ** (e - 23)) # [2^23, 2^24) - n = _rne(q) - if n == 1 << 24: - n >>= 1 - e += 1 - if e > 127: - return s | PINF - return s | ((e + 127) << 23) | (n & 0x7FFFFF) - - -def _rne(q): - n = q.numerator // q.denominator - rem = q - n - if rem > Fraction(1, 2) or (rem == Fraction(1, 2) and n & 1): - n += 1 - return n - - -def round_rtz_f16(b): - """f32 bits -> f16 bits, round toward zero; finite overflow gives +-65504, inf stays inf, NaN stays NaN.""" - s = (b >> 16) & 0x8000 - if is_nan(b): - return 0x7E00 | s - if is_inf(b): - return 0x7C00 | s - a = abs(to_frac(b)) - if a >= 65504: - return s | 0x7BFF - if a < Fraction(2) ** -14: - return s | int(a / Fraction(2) ** -24) # f16 denormal (truncated) - e = a.numerator.bit_length() - a.denominator.bit_length() - if Fraction(2) ** e > a: - e -= 1 - n = int(a / Fraction(2) ** (e - 10)) - return s | ((e + 15) << 10) | (n & 0x3FF) - - -def round_rne_f16(b): - s = (b >> 16) & 0x8000 - if is_nan(b): - return 0x7E00 | s - if is_inf(b): - return 0x7C00 | s - a = abs(to_frac(b)) - if a == 0: - return s - if a < Fraction(2) ** -14: - n = _rne(a / Fraction(2) ** -24) - return s | n # n == 0x400 is the smallest normal, same encoding - e = a.numerator.bit_length() - a.denominator.bit_length() - if Fraction(2) ** e > a: - e -= 1 - n = _rne(a / Fraction(2) ** (e - 10)) - if n == 1 << 11: - n >>= 1 - e += 1 - if e > 15: - return s | 0x7C00 - return s | ((e + 15) << 10) | (n & 0x3FF) - - -def f16_to_f32(h): - s = (h & 0x8000) << 16 - e, m = (h >> 10) & 0x1F, h & 0x3FF - if e == 0x1F: - return s | PINF | (m << 13) - if e == 0: - return round_f32(Fraction(m, 1 << 24) * (-1 if s else 1), neg_zero=bool(s)) - return s | ((e - 15 + 127) << 23) | (m << 13) - - -def bits(x): - return struct.unpack("= 0 else -_rne(-v) - - -def cvt_pk_u8(x, byte, base): - """flt32_to_uint8: round to nearest even, clamp to [0, 255], NaN -> 0.""" - if is_nan(x): - u = 0 - elif sign(x) or is_zero(x): - u = 0 - elif is_inf(x): - u = 255 - else: - u = min(255, _rne(to_frac(x))) - sh = 8 * (byte & 3) - return (base & ~(0xFF << sh) & M32) | (u << sh) - - -def cube(op, x, y, z): - """V_CUBEID/SC/TC/MA_F32 (ISA pseudocode; comparisons are float compares, so -0 < 0 is false).""" - if is_nan(x) or is_nan(y) or is_nan(z): - raise NotModelled("cube of NaN") - ax, ay, az = (abs(to_frac(v)) if not is_inf(v) else math.inf for v in (x, y, z)) - lt0 = lambda v: sign(v) and not is_zero(v) # noqa: E731 - if az >= ax and az >= ay: - major = "z" - elif ay >= ax: - major = "y" - else: - major = "x" - if op == "v_cubeid_f32": - face = {"z": 5 if lt0(z) else 4, "y": 3 if lt0(y) else 2, "x": 1 if lt0(x) else 0}[major] - return bits(float(face)) - if op == "v_cubesc_f32": - return {"z": neg(x) if lt0(z) else x, "y": x, "x": z if lt0(x) else neg(z)}[major] - if op == "v_cubetc_f32": - return {"z": neg(y), "y": neg(z) if lt0(y) else z, "x": neg(y)}[major] - m = {"z": z, "y": y, "x": x}[major] - return 0 if is_zero(m) else mul(bits(2.0), m) - - -def cmp_class(x, mask): - if is_nan(x): - c = 1 if x & 0x400000 else 0 - elif is_inf(x): - c = 2 if sign(x) else 9 - elif is_zero(x): - c = 5 if sign(x) else 6 - elif is_denorm(x): - c = 4 if sign(x) else 7 - else: - c = 3 if sign(x) else 8 - return (mask >> c) & 1 - - -def transcendental(op, x): - """Exact-result inputs only (see gen): special values and powers of two.""" - if is_nan(x): - return QNAN - if op == "v_rcp_f32": - if is_zero(x): - return (x & 0x80000000) | PINF - if is_inf(x): - return x & 0x80000000 - return round_f32(1 / to_frac(x)) - if op == "v_sqrt_f32": - if is_zero(x): - return x - if sign(x): - return QNAN - if is_inf(x): - return x - return _exact_pow2_op(x, lambda e: Fraction(2) ** (e // 2)) - if op == "v_rsq_f32": - if is_zero(x): - return (x & 0x80000000) | PINF - if sign(x): - return QNAN - if is_inf(x): - return 0 - return _exact_pow2_op(x, lambda e: Fraction(2) ** (-(e // 2))) - if op == "v_exp_f32": - if is_inf(x): - return 0 if sign(x) else PINF - v = to_frac(x) - if v.denominator != 1: - raise ValueError("v_exp_f32 of a non-integer") - n = int(v) - if n >= 128: - return PINF - if n < -126: - raise Denormal("v_exp_f32 result") - return round_f32(Fraction(2) ** n) - if op == "v_log_f32": - if is_zero(x): - return NINF - if sign(x): - return QNAN - if is_inf(x): - return PINF - return _exact_pow2_op(x, lambda e: Fraction(e)) - raise ValueError(op) - - -def _exact_pow2_op(x, f): - v = to_frac(x) - e = v.numerator.bit_length() - 1 if v.denominator == 1 else -(v.denominator.bit_length() - 1) - if Fraction(2) ** e != v: - raise ValueError("not a power of two") - return round_f32(f(e)) - - -OMOD = {"mul:2": 2, "mul:4": 4, "div:2": Fraction(1, 2)} - - -def apply_out_mods(r, mods): - """VOP3 output modifiers: omod scales the rounded result, then clamp to [0, 1] (NaN -> 0).""" - for m in mods: - if m in OMOD: - if not is_nan(r): - r = mul(r, round_f32(Fraction(OMOD[m]))) - if "clamp" in mods: - if is_nan(r) or r == 0x80000000: - raise NotModelled("clamp of NaN or -0 (@shelbykb2's claim)") - if sign(r): - r = 0 - elif not is_zero(r) and (is_inf(r) or to_frac(r) > 1): - r = bits(1.0) - return r - - -# ---- op table: name -> (sources, kind, model) ---- -# kinds: "f" float source (takes neg/abs), "u" integer source, "k" literal float constant (fmaak/fmamk/madak/madmk). - -def _op(srcs, fn, mods=True, sel="any", hw_only=False): - return {"srcs": srcs, "fn": fn, "mods": mods, "sel": sel, "hw_only": hw_only} - - -def _fval(b): - return struct.unpack(" _fval(y) else y - - -def fmed3(x, y, z): - """With any NaN operand: min3(s0, s1, s2); otherwise the median, -0 < +0.""" - if is_nan(x) or is_nan(y) or is_nan(z): - return fmin(fmin(x, y), z) - return sorted((x, y, z), key=lambda b: (_fval(b), 0 if sign(b) else 1))[1] - - -ALL_OPS = { - "v_add_f32": _op("ff", lambda x, y: add(x, y)), - "v_sub_f32": _op("ff", lambda x, y: add(x, neg(y))), - "v_subrev_f32": _op("ff", lambda x, y: add(y, neg(x))), - "v_mul_f32": _op("ff", mul), - "v_mul_legacy_f32": _op("ff", legacy_mul), - "v_mad_legacy_f32": _op("fff", lambda x, y, z: add(legacy_mul(x, y), z)), - "v_mad_f32": _op("fff", lambda x, y, z: add(mul(x, y), z)), - "v_fma_f32": _op("fff", fma), - "v_fmac_f32": _op("ffd", fma), # D = S0 * S1 + D - "v_mac_f32": _op("ffd", lambda x, y, z: add(mul(x, y), z)), - "v_fmaak_f32": _op("ffk", fma, mods=False), - "v_fmamk_f32": _op("fkf", fma, mods=False), - "v_madak_f32": _op("ffk", lambda x, y, z: add(mul(x, y), z), mods=False), - "v_madmk_f32": _op("fkf", lambda x, y, z: add(mul(x, y), z), mods=False), - "v_cvt_f32_i32": _op("u", lambda x: cvt_int_to_f32(x - (1 << 32) if x >> 31 else x)), - "v_cvt_f32_u32": _op("u", lambda x: cvt_int_to_f32(x)), - "v_cvt_f32_ubyte0": _op("u", lambda x: cvt_int_to_f32(x & 0xFF)), - "v_cvt_f32_ubyte1": _op("u", lambda x: cvt_int_to_f32((x >> 8) & 0xFF)), - "v_cvt_f32_ubyte2": _op("u", lambda x: cvt_int_to_f32((x >> 16) & 0xFF)), - "v_cvt_f32_ubyte3": _op("u", lambda x: cvt_int_to_f32(x >> 24)), - "v_cvt_f32_f16": _op("h", lambda x: f16_to_f32(x & 0xFFFF)), - "v_cvt_f16_f32": _op("f", None, mods=False), # partial write, handled in step() - "v_cvt_pkrtz_f16_f32": _op("ff", lambda x, y: round_rtz_f16(x) | (round_rtz_f16(y) << 16), mods=False), - "v_cvt_pk_u8_f32": _op("fuu", cvt_pk_u8, mods=False), - "v_floor_f32": _op("f", lambda x: rounding(x, "floor")), - "v_ceil_f32": _op("f", lambda x: rounding(x, "ceil")), - "v_trunc_f32": _op("f", lambda x: rounding(x, "trunc")), - "v_rndne_f32": _op("f", lambda x: rounding(x, "rne")), - "v_rcp_f32": _op("t", lambda x: transcendental("v_rcp_f32", x)), - # v_rcp_iflag_f32 is v_rcp_f32 without the FP exception flags: bit-identical on gfx1030 (design.md, "Denormal - # flush and special results"), so it shares the model; clamp and omod are what is new here (SHADER-136). - "v_rcp_iflag_f32": _op("t", lambda x: transcendental("v_rcp_f32", x)), - "v_rsq_f32": _op("t", lambda x: transcendental("v_rsq_f32", x)), - "v_sqrt_f32": _op("t", lambda x: transcendental("v_sqrt_f32", x)), - "v_exp_f32": _op("e", lambda x: transcendental("v_exp_f32", x)), - "v_log_f32": _op("t", lambda x: transcendental("v_log_f32", x)), - "v_cubeid_f32": _op("fff", lambda x, y, z: cube("v_cubeid_f32", x, y, z)), - "v_cubesc_f32": _op("fff", lambda x, y, z: cube("v_cubesc_f32", x, y, z)), - "v_cubetc_f32": _op("fff", lambda x, y, z: cube("v_cubetc_f32", x, y, z)), - "v_cubema_f32": _op("fff", lambda x, y, z: cube("v_cubema_f32", x, y, z)), - "v_cmp_class_f32": _op("fu", None, mods=False), # writes VCC, handled in step() - # Hardware-only: the RDNA2 NaN / signed-zero rules measured by #634 (docs/design.md), which the translator - # emits as NMin / NMax. They are in the table so --oracle hw can say whether gfx1150 follows the same rules; the - # translator comparison leaves them out (the SPIR-V interpreter has no defined result for every case). - "v_min_f32": _op("ff", fmin, hw_only=True), - "v_max_f32": _op("ff", fmax, hw_only=True), - "v_min3_f32": _op("fff", lambda x, y, z: fmin(fmin(x, y), z), hw_only=True), - "v_max3_f32": _op("fff", lambda x, y, z: fmax(fmax(x, y), z), hw_only=True), - "v_med3_f32": _op("fff", fmed3, hw_only=True), -} -VOP3_ONLY = {"v_mad_legacy_f32", "v_mad_f32", "v_fma_f32", "v_cubeid_f32", "v_cubesc_f32", "v_cubetc_f32", - "v_cubema_f32", "v_cvt_pk_u8_f32", "v_cvt_pkrtz_f16_f32", "v_min3_f32", "v_max3_f32", "v_med3_f32"} -OPS = {k: v for k, v in ALL_OPS.items() if not v["hw_only"]} # what the translator comparison covers -HW_ONLY_OPS = tuple(k for k, v in ALL_OPS.items() if v["hw_only"]) -LITERAL_CONST_OPS = {"v_fmaak_f32", "v_fmamk_f32", "v_madak_f32", "v_madmk_f32"} - -# Ops the hardware gives an output modifier in their VOP3 form but whose float output is an integer or packed -# value: no omod/clamp generated for them. -NO_OUT_MODS = {"v_cvt_f16_f32", "v_cvt_pkrtz_f16_f32", "v_cvt_pk_u8_f32", "v_cmp_class_f32"} | LITERAL_CONST_OPS - -# ---- operand values ---- - -SPECIAL = [0, 0x80000000, bits(1.0), bits(-1.0), bits(0.5), bits(-0.5), bits(2.0), bits(-2.0), PINF, NINF, - QNAN, 0xFFC00000, 0x7F800001, bits(1.5), bits(2.5), bits(-2.5), bits(0.49999997), bits(254.5), - bits(255.5), bits(256.0), bits(-1e30), bits(1e30), 0x7F7FFFFF, 0xFF7FFFFF, 0x00800000, 0x80800000, - bits(65504.0), bits(65519.996), bits(65520.0), bits(3.0), bits(1.0000001), bits(0.75), bits(-0.75), - bits(16777216.0), bits(8388608.5), bits(1e-30)] -INTS = [0, 1, 0xFFFFFFFF, 0x7FFFFFFF, 0x80000000, 0x01000001, 0x00FFFFFF, 0xFFFFFF7F, 255, 0x12345678, - 16777217, 0xFFFFFFFE, 0x40000001] -TRANS = [0, 0x80000000, PINF, NINF, QNAN, bits(1.0), bits(4.0), bits(0.25), bits(16.0), bits(2.0 ** -20), - bits(2.0 ** 40), bits(-4.0), bits(-1.0), bits(-(2.0 ** -14)), bits(2.0 ** 126), bits(2.0 ** -126)] -EXPS = [NINF, PINF, QNAN, 0, 0x80000000, bits(1.0), bits(3.0), bits(-3.0), bits(127.0), bits(128.0), - bits(-126.0), bits(-20.0), bits(10.0)] - - -def rand_float(rng): - r = rng.random() - if r < 0.4: - return rng.choice(SPECIAL) - if r < 0.7: # a normal number with a modest exponent: arithmetic stays normal - e = rng.randrange(127 - 20, 127 + 21) - return (rng.getrandbits(1) << 31) | (e << 23) | rng.getrandbits(23) - if r < 0.85: # small integers and halves: exact cases, ties - return bits(rng.randrange(-300, 301) / rng.choice((1, 2, 4))) - e = rng.randrange(1, 255) - return (rng.getrandbits(1) << 31) | (e << 23) | rng.getrandbits(23) - - -# ---- programs ---- -# A program: seeds (v0..v7 = values, by v_mov_b32 of a literal) and one instruction writing v8 (v8 is seeded -# too, so accumulating ops read it). Observed: v8, the first two sources' registers, and v9 (VCC as 0/1). - -SEED_REGS = tuple(range(0, 9)) - - -def fmt_src(reg, m): - s = f"v{reg}" - if m.get("abs"): - s = f"|{s}|" - if m.get("neg"): - s = "-" + s - return s - - -def gen(rng, op): - spec = ALL_OPS[op] - vals = [rand_float(rng) for _ in SEED_REGS] - srcs, mods_src, text_srcs = [], [], [] - e64 = op in VOP3_ONLY or (spec["mods"] and rng.random() < 0.5) - k_lit = None - regs = list(range(8)) - rng.shuffle(regs) - for i, kind in enumerate(spec["srcs"]): - if kind == "d": - continue - r = regs[i] - if kind == "u": - vals[r] = rng.choice(INTS) if rng.random() < 0.6 else rng.getrandbits(32) - if op == "v_cvt_pk_u8_f32" and i == 1: - vals[r] = rng.randrange(0, 8) - elif kind == "h": - vals[r] = rng.getrandbits(32) if rng.random() < 0.5 else rng.choice( - (0x3C00, 0xBC00, 0x7C00, 0xFC00, 0x7E00, 0x0001, 0x8001, 0x03FF, 0x7BFF, 0x0400, 0x8000)) - elif kind == "t": - vals[r] = rng.choice(TRANS) - elif kind == "e": - vals[r] = rng.choice(EXPS) - elif kind == "k": - k_lit = rand_float(rng) - srcs.append(("k", k_lit)) - continue - m = {} - if e64 and kind in "fte" and spec["mods"]: - m = {"neg": rng.random() < 0.25, "abs": rng.random() < 0.2} - srcs.append((r, m)) - text_srcs.append(fmt_src(r, m)) - out_mods = [] - if e64 and spec["mods"] and op not in NO_OUT_MODS: - if rng.random() < 0.3: - out_mods.append(rng.choice(tuple(OMOD))) - if rng.random() < 0.3: - out_mods.append("clamp") - return vals, srcs, e64, out_mods - - -def source_value(vals, s): - r, m = s - v = vals[r] - if m.get("abs"): - v = fabs(v) - if m.get("neg"): - v = neg(v) - return v - - -def flush(b): - """A denormal read or written as a zero of its sign (what a flush-to-zero f32 unit does).""" - return b & 0x80000000 if is_denorm(b) else b - - -# model(..., denorm=): what happens to f32 denormals. -# "skip" raise Denormal (the default: this tool does not claim to know) -# "keep" exact IEEE behaviour, denormals read and written as they are -# "ftz" inputs read as signed zero and denormal results written as signed zero -# "ftz_in", "ftz_out" only one of the two -DENORM_MODES = ("skip", "keep", "ftz", "ftz_in", "ftz_out") - - -def model(op, vals, srcs, out_mods, denorm="skip", translator=True): - """Words of v8 (result) and v9 (VCC as 0/1). `translator`: refuse inputs the SPIR-V interpreter cannot carry - (they are fine on a GPU).""" - spec = ALL_OPS[op] - ins = [] - for s in srcs: - ins.append(s[1] if s[0] == "k" else source_value(vals, s)) - if "d" in spec["srcs"]: - ins.append(vals[8]) - kinds = spec["srcs"].replace("d", "f") - fpos = [i for i, k in enumerate(kinds) if k in "fktde"] - if denorm == "skip": - if any(is_denorm(ins[i]) for i in fpos): - raise Denormal("operand") - elif denorm in ("ftz", "ftz_in"): - for i in fpos: - ins[i] = flush(ins[i]) - out_flush = denorm in ("ftz", "ftz_out") - vcc = 0 - if op == "v_cvt_f16_f32": - r = (vals[8] & 0xFFFF0000) | round_rne_f16(ins[0]) - elif op == "v_cmp_class_f32": - if translator and is_nan(ins[0]) and not ins[0] & 0x400000: - # The translator reads the class from the bits after an OpBitcast to float and back, exact on a - # GPU; the interpreter holds floats as Python floats, which quiets a signalling NaN on the way. - raise NotModelled("signalling NaN through the interpreter's float bitcast") - r, vcc = vals[8], cmp_class(ins[0], ins[1]) - else: - r = spec["fn"](*ins) - floaty = spec["mods"] or op in LITERAL_CONST_OPS - if floaty and is_denorm(r): - if denorm == "skip": - raise Denormal("result") - if out_flush: - r = flush(r) - if op in ("v_mad_f32", "v_mac_f32", "v_madak_f32", "v_madmk_f32", "v_mad_legacy_f32"): - prod = legacy_mul(ins[0], ins[1]) if op == "v_mad_legacy_f32" else mul(ins[0], ins[1]) - if is_denorm(prod) and denorm == "skip": - raise Denormal("intermediate product") - r = apply_out_mods(r, out_mods) - if is_denorm(r): - if denorm == "skip": - raise Denormal("result") - if out_flush: - r = flush(r) - return [r & M32, vcc] - - -def line(op, vals, srcs, e64, out_mods): - spec = ALL_OPS[op] - parts = [] - for s in srcs: - parts.append(f"0x{s[1]:x}" if s[0] == "k" else fmt_src(*s)) - name = op - if op == "v_cmp_class_f32": - name += "_e64" if e64 else "_e32" - return f"{name} vcc_lo, " + ", ".join(parts) if e64 else f"{name} vcc_lo, " + ", ".join(parts) - if op not in VOP3_ONLY and op not in LITERAL_CONST_OPS: - name += "_e64" if e64 else "_e32" - if not e64 and op not in LITERAL_CONST_OPS: - # VOP1/VOP2: src1 must be a VGPR, already true; no modifiers - pass - del spec - return f"{name} v8, " + ", ".join(parts) + ("" if not out_mods else " " + " ".join(out_mods)) - - -def listing(op, vals, srcs, e64, out_mods): - out = ["; f32_fuzz case code 0x0..0x1000"] - for r in SEED_REGS: - out.append(f"\tv_mov_b32_e32 v{r}, 0x{vals[r]:x}") - out.append("\ts_mov_b32 vcc_lo, 0") - out.append("\t" + line(op, vals, srcs, e64, out_mods)) - out.append("\tv_cndmask_b32_e64 v9, 0, 1, vcc_lo") - obs = [s[0] for s in srcs if s[0] != "k"][:2] + [0, 1] - out.append(f"\texp mrt0 v8, v9, v{obs[0]}, v{obs[1]} done vm") - out.append("\ts_endpgm") - return "\n".join(out) + "\n", obs[:2] - - -def run_translated(text, name="ps_f32_fuzz"): - import rdna2spirv # here, not at the top of the file: see the note above the imports - with tempfile.TemporaryDirectory(prefix="f32-fuzz-") as tmp: - dis = os.path.join(tmp, "disasm") - os.mkdir(dis) - path = os.path.join(dis, name + ".s") - with open(path, "w", encoding="utf-8", newline="\n") as f: - f.write(text) - with open(os.path.join(tmp, name + ".dxbc"), "wb") as f: - f.write(STUB_DXBC) - try: - with warnings.catch_warnings(): - warnings.simplefilter("ignore", ResourceWarning) - spv = rdna2spirv.translate(path) - gc.collect() - except rdna2spirv.Unsupported as e: - return "skip", f"translator unsupported: {e}" - try: - out = run_fragment(spv) - except Exception as e: # noqa: BLE001 - the interpreter is half of the comparison - msg = str(e) - if "undefined" in msg: - return "undefined", msg[:90] - return "skip", f"interpreter: {type(e).__name__}: {msg[:90]}" - if list(out) != ["%out_mrt0"]: - return "skip", f"outputs {sorted(out)}" - return "ok", [w & M32 for w in out["%out_mrt0"]] - - -def same(want, got): - if is_nan(want) and is_nan(got): - return True - return want == got - - -def check(op, vals, srcs, e64, out_mods): - try: - want = model(op, vals, srcs, out_mods) - except Denormal as e: - return "skip", f"denormal {e}" - except NotModelled as e: - return "skip", str(e) - text, obs = listing(op, vals, srcs, e64, out_mods) - status, got = run_translated(text) - if status != "ok": - return status, got - want_words = [want[0], want[1], vals[obs[0]], vals[obs[1]]] - if all(same(w, g) or (k >= 2 and same(w | 0x400000 if is_nan(w) else w, g)) for k, (w, g) in - enumerate(zip(want_words, got))): - return "match", None - return "mismatch", (want_words, got, text) - - -def fdesc(b): - if is_nan(b): - return f"0x{b:08x}(NaN)" - try: - return f"0x{b:08x}({struct.unpack('> 16 * h) & 0xFFFF, (got[0] >> 16 * h) & 0xFFFF - if not (w == g or (h in halves and is_nan16(w) and is_nan16(g))): - return False - return True - - -# ---- known deviations: hardware behaviour measured on gfx1150 that the ISA-text model does not have ---- -# Each maps (case, want) to the words the hardware gives instead, or None when it does not apply. A hardware result -# that equals the deviation's words is filed under "known deviation", not "match"; anything else stays a mismatch. - -def dev_omod_neg_zero(case, want, mode=None): - """VOP3 omod (mul:2, mul:4, div:2) turns a -0 result into +0, on gfx1150 and on RDNA2 (gfx1031, gfx1036). LLVM - notes that omod mishandles signed zeros (SIFoldOperands.cpp) and D30209 describes -0 being forced to +0 before the - modifier. Only where the omod was active: not with MODE.IEEE = 1, not for ALU ops with f32 denormals kept - (omod_active).""" - if mode is None: - mode = HW_PRIMARY - if want[0] == 0x80000000 and any(m in OMOD for m in case.out_mods) and omod_active(mode, case.op): - return [0, want[1]] - return None - - -KNOWN_DEVIATIONS = {"omod_neg_zero": dev_omod_neg_zero} - - -def hw_verdict(case, got, model_fn=model): - """('match' | 'mismatch', want) when the model has an answer, ('skip', reason) when it declines.""" - try: - want = model_fn(case.op, case.vals, case.srcs, case.out_mods, translator=False) - except Denormal as e: - return "skip", f"denormal {e}" - except NotModelled as e: - return "skip", str(e) - if hw_same(want, got, case.op): - return "match", want - for name, fn in KNOWN_DEVIATIONS.items(): - alt = fn(case, want) - if alt is not None and hw_same(alt, got, case.op): - return "deviation:" + name, want - return "mismatch", want - - -# What the model gets wrong on purpose, to prove the comparison can fail (--perturb, --negative-control). Each -# entry: op -> replacement for ALL_OPS[op]["fn"]; none of them shares code with the real model's result path. -def _mul_rtz(x, y): - r = mul(x, y) - if is_nan(r) or is_inf(r) or is_zero(r): - return r - exact = to_frac(x) * to_frac(y) - return r - 1 if abs(to_frac(r)) > abs(exact) else r - - -PERTURBATIONS = { - "add_lsb": ("v_add_f32", lambda x, y: add(x, y) ^ 1), - "mul_rtz": ("v_mul_f32", _mul_rtz), - "fma_unfused": ("v_fma_f32", lambda x, y, z: add(mul(x, y), z)), - "legacy_is_ieee": ("v_mul_legacy_f32", mul), - "rndne_floor": ("v_rndne_f32", lambda x: rounding(x, "floor")), - "min_ieee_nan": ("v_min_f32", lambda x, y: QNAN if is_nan(x) or is_nan(y) else fmin(x, y)), -} - - -class perturbed: - """Context manager: swap one op's model function.""" - - def __init__(self, name): - self.op, self.fn = PERTURBATIONS[name] - self.old = None - - def __enter__(self): - self.old = ALL_OPS[self.op]["fn"] - ALL_OPS[self.op]["fn"] = self.fn - return self - - def __exit__(self, *exc): - ALL_OPS[self.op]["fn"] = self.old - - -# ---- informational classification: what the hardware did where the model declines ---- - -DENORM_LABELS = {"keep": "kept", "ftz": "flushed in+out", "ftz_in": "inputs flushed only", "ftz_out": "results flushed only"} - - -def denorm_label(case, got): - """Which denormal variants of the model the hardware's words equal: 'where' ('operand' / 'result') and the - matching variant names ('none' when no variant does).""" - op, vals, srcs, e64, out_mods = case.args() - spec = ALL_OPS[op] - ins = [s[1] if s[0] == "k" else source_value(vals, s) for s in srcs] + ([vals[8]] if "d" in spec["srcs"] else []) - kinds = spec["srcs"].replace("d", "f") - operand = any(is_denorm(ins[i]) for i, k in enumerate(kinds) if k in "fktde") - hit = [] - for d in ("keep", "ftz", "ftz_in", "ftz_out"): - try: - w = model(op, vals, srcs, out_mods, denorm=d, translator=False) - except (NotModelled, ValueError): - continue - alt = dev_omod_neg_zero(case, w) # a flushed zero is -0 too, and omod turns that into +0 - if hw_same(w, got, op) or (alt is not None and hw_same(alt, got, op)): - hit.append(d) - return ("operand" if operand else "result"), "|".join(hit) or "none" - - -def has_denorm_in(case): - op, vals, srcs, e64, out_mods = case.args() - spec = ALL_OPS[op] - ins = [s[1] if s[0] == "k" else source_value(vals, s) for s in srcs] + ([vals[8]] if "d" in spec["srcs"] else []) - kinds = spec["srcs"].replace("d", "f") - return any(is_denorm(ins[i]) for i, k in enumerate(kinds) if k in "fktde") - - -def float_inputs(case): - """[(position, value after neg/abs)] for the float sources, in instruction order.""" - spec = ALL_OPS[case.op] - ins = [s[1] if s[0] == "k" else source_value(case.vals, s) for s in case.srcs] - if "d" in spec["srcs"]: - ins.append(case.vals[8]) - kinds = spec["srcs"].replace("d", "f") - return [(i, v) for i, (v, k) in enumerate(zip(ins, kinds)) if k in "fktde"] - - -CUBE_OPS = ("v_cubeid_f32", "v_cubesc_f32", "v_cubetc_f32", "v_cubema_f32") -NAN_NOT_F32 = ("v_cmp_class_f32", "v_cvt_pk_u8_f32", "v_cvt_f16_f32", "v_cvt_pkrtz_f16_f32") - - -def nan_facts(case, result): - """What the hardware did with NaNs, as short strings (one case can give several). Source n is src n of the - instruction after neg/abs. 'quieted' = the same payload with bit 22 set. Not for ops whose result is not an f32.""" - if case.op in NAN_NOT_F32: - return nan_facts_f16(case, result) if case.op.startswith("v_cvt_") and "f16" in case.op else [] - nans = [(i, v) for i, v in float_inputs(case) if is_nan(v)] - facts = [] - if not is_nan(result): - return ["NaN in, no NaN out"] if nans else [] - if not nans: - return [f"no NaN in, NaN out: 0x{result:08x}"] - first_i, first = nans[0] - if case.op in CUBE_OPS: - pass # the result is a selected source: no 'first' rule - elif result in (first, first | 0x400000, first ^ 0x80000000, (first ^ 0x80000000) | 0x400000): - facts.append("result = first NaN source" + (" (a signalling one)" if not first & 0x400000 else "")) - elif any(result in (v, v | 0x400000) for _, v in nans[1:]): - facts.append("result = a later NaN source") - elif result in (0xFFC00000, 0x7FC00000): - facts.append(f"result = default NaN 0x{result:08x}") - else: - facts.append(f"result = other 0x{result:08x}") - for i, v in nans: - if not v & 0x400000 and result == v: - facts.append("signalling NaN passes unchanged") - break - if not v & 0x400000 and result in (v | 0x400000, (v ^ 0x80000000) | 0x400000): - facts.append("signalling NaN quieted") - break - if any(result == (v ^ 0x80000000) | 0x400000 or result == v ^ 0x80000000 for _, v in nans): - facts.append("sign of the NaN flipped") - return facts - - -def nan_facts_f16(case, result): - """v_cvt_f16_f32 (low half) and v_cvt_pkrtz_f16_f32 (both halves): the f16 NaN against the f32 NaN it came from.""" - ins = [v for _, v in float_inputs(case)] - facts = [] - for h in F16_HALVES[case.op]: - x, half = ins[h], (result >> 16 * h) & 0xFFFF - if not is_nan(x): - continue - trunc = ((x >> 16) & 0x8000) | 0x7C00 | ((x >> 13) & 0x3FF) | 0x200 - facts.append("f16 NaN = f32 payload truncated to 10 bits, quiet bit set" if half == trunc else - "f16 NaN = canonical 0x7e00" if half & 0x7FFF == 0x7E00 else f"f16 NaN other 0x{half:04x}") - return facts - - -def omod_label(case, got): - """What an omod (mul:2, mul:4, div:2) did, judged where it changes the result and nothing is denormal.""" - if not any(m in OMOD for m in case.out_mods): - return None - try: - with_ = model(case.op, case.vals, case.srcs, case.out_mods, translator=False) - without = model(case.op, case.vals, case.srcs, [m for m in case.out_mods if m not in OMOD], - translator=False) - except (NotModelled, ValueError): - return None - if hw_same(with_, without, case.op) and with_[0] != 0x80000000: - return None - if hw_same(with_, without, case.op) and hw_same(with_, got, case.op): - return "-0 result kept (applied or ignored, same word)" # neither applied nor ignored is shown - if hw_same(with_, got, case.op): - return "applied" - alt = dev_omod_neg_zero(case, with_) - if alt is not None and hw_same(alt, got, case.op): - return "applied, but a -0 result becomes +0" - if hw_same(without, got, case.op): - return "ignored" - return "other" - - -def clamp_label(case, got): - """What a clamp bit did to a NaN or -0 result (the model declines): measured against the unclamped result.""" - op, vals, srcs, e64, out_mods = case.args() - try: - raw = model(op, vals, srcs, [m for m in out_mods if m != "clamp"], denorm="keep", translator=False)[0] - except (NotModelled, ValueError): - return "n/a" - r = got[0] - if is_nan(raw): - if r == 0: - return "NaN -> +0" - if is_nan(r): - return "NaN passes through" + (" (quieted)" if raw & 0x400000 == 0 and r & 0x400000 else "") - return f"NaN -> 0x{r:08x}" - if raw == 0x80000000: - return {0: "-0 -> +0", 0x80000000: "-0 stays -0"}.get(r, f"-0 -> 0x{r:08x}") - return "other" - - -FAMILIES = [ - ("add / sub / mul", ("v_add_f32", "v_sub_f32", "v_subrev_f32", "v_mul_f32")), - ("DX9 legacy mul / mad", ("v_mul_legacy_f32", "v_mad_legacy_f32")), - ("mad / mac / madak / madmk", ("v_mad_f32", "v_mac_f32", "v_madak_f32", "v_madmk_f32")), - ("fma / fmac / fmaak / fmamk", ("v_fma_f32", "v_fmac_f32", "v_fmaak_f32", "v_fmamk_f32")), - ("int -> f32 convert", ("v_cvt_f32_i32", "v_cvt_f32_u32", "v_cvt_f32_ubyte0", "v_cvt_f32_ubyte1", - "v_cvt_f32_ubyte2", "v_cvt_f32_ubyte3")), - ("f16 convert", ("v_cvt_f32_f16", "v_cvt_f16_f32", "v_cvt_pkrtz_f16_f32")), - ("v_cvt_pk_u8_f32", ("v_cvt_pk_u8_f32",)), - ("floor / ceil / trunc / rndne", ("v_floor_f32", "v_ceil_f32", "v_trunc_f32", "v_rndne_f32")), - ("rcp / rsq / sqrt / exp / log (exact inputs)", ("v_rcp_f32", "v_rcp_iflag_f32", "v_rsq_f32", "v_sqrt_f32", - "v_exp_f32", "v_log_f32")), - ("cube", ("v_cubeid_f32", "v_cubesc_f32", "v_cubetc_f32", "v_cubema_f32")), - ("v_cmp_class_f32", ("v_cmp_class_f32",)), - ("min / max / med3 (hardware only)", HW_ONLY_OPS), -] - - -def family_of(op): - return next(name for name, ops in FAMILIES if op in ops) - - -# ---- generated probes: structured inputs the random generator never produces ---- - -DENORMS = [0x00000001, 0x00000002, 0x007FFFFF, 0x00400000, 0x00000100, 0x00123456, 0x80000001, 0x807FFFFF, - 0x80400000] -POW2_DENORMS = [0x00400000, 0x00200000, 0x00000001, 0x00080000] # 2^-127, 2^-128, 2^-149, 2^-130 -NANS = [0x7FC00000, 0xFFC00000, 0x7FC00001, 0xFFC12345, 0x7FA00000, 0xFFA00000, 0x7F800001, 0xFF800001, - 0x7FFFFFFF, 0xFFFFFFFF, 0x7FC0DEAD, 0x7FBFFFFF] -NEAR_MIN = [bits(2.0 ** -126), bits(1.5 * 2.0 ** -126), bits(2.0 ** -125), bits(-(2.0 ** -126)), - bits(-1.5 * 2.0 ** -126), bits(2.0 ** -126 * 1.0000001)] -SMALLS = [bits(0.5), bits(0.25), bits(-0.5), bits(1.0), bits(-1.0), bits(1.5), bits(0.75), bits(2.0 ** -10)] - - -def _float_slots(case): - """Registers (or the literal) holding float operands: [(srcs index, kind char)].""" - kinds = ALL_OPS[case.op]["srcs"].replace("d", "") - return [(i, k) for i, k in enumerate(kinds) if k in "fkte"] - - -def _set(case, i, v): - s = case.srcs[i] - if s[0] == "k": - case.srcs[i] = ("k", v) - else: - case.vals[s[0]] = v - - -def gen_probe(rng, op, kind): - """A Case of the given probe kind, or None when the op has no such probe.""" - vals, srcs, e64, out_mods = gen(rng, op) - case = Case(op, vals, list(srcs), e64, out_mods, group=kind) - slots = _float_slots(case) - spec = ALL_OPS[op] - if kind == "denorm_in": - pos = [(i, k) for i, k in slots if k in "ftk"] - if not pos: - return None - for i, k in rng.sample(pos, rng.randrange(1, min(2, len(pos)) + 1)): - _set(case, i, rng.choice(POW2_DENORMS if k == "t" else DENORMS)) - if "d" in spec["srcs"] and rng.random() < 0.3: - case.vals[8] = rng.choice(DENORMS) - return case - if kind == "denorm_out": - for _ in range(80): - for i, k in slots: - if k == "t": - _set(case, i, rng.choice(TRANS + [bits(2.0 ** 127)])) - elif k == "e": - _set(case, i, rng.choice(EXPS + [bits(-127.0), bits(-140.0), bits(-149.0), bits(-150.0)])) - elif k == "f": - _set(case, i, rng.choice(NEAR_MIN + SMALLS) if rng.random() < 0.7 else rand_float(rng)) - else: - _set(case, i, rng.choice(NEAR_MIN + SMALLS)) - if "d" in spec["srcs"]: - case.vals[8] = rng.choice(NEAR_MIN + [0] + SMALLS) - try: - if not is_denorm(model(op, case.vals, case.srcs, case.out_mods, denorm="keep", - translator=False)[0]): - continue - except (NotModelled, ValueError): - continue - return case - return None - if kind == "nan": - pos = [(i, k) for i, k in slots if k in "fkt"] - if not pos: - return None - picked = [p for p in pos if rng.random() < 0.6] or [rng.choice(pos)] - for i, k in picked: - _set(case, i, rng.choice(NANS)) - return case - if kind == "zero_inf": - # the DX9 rule: a zero times anything (inf, NaN included) is +0; small samples need these to see a plain multiply - if op not in ("v_mul_legacy_f32", "v_mad_legacy_f32"): - return None - _set(case, 0, rng.choice([0, 0x80000000])) - _set(case, 1, rng.choice([PINF, NINF, QNAN, 0x7F800001, bits(3.0)])) - if rng.random() < 0.5: - x, y = case.srcs[0], case.srcs[1] - case.srcs[0], case.srcs[1] = y, x - return case - if kind == "cancel": - # z = -round(x * y): a fused multiply-add keeps the rounding residue of the product, an unfused one gives 0 - if op not in ("v_fma_f32", "v_fmac_f32", "v_fmaak_f32", "v_fmamk_f32"): - return None - x = (rng.getrandbits(1) << 31) | (rng.randrange(120, 135) << 23) | rng.getrandbits(23) - y = (rng.getrandbits(1) << 31) | (rng.randrange(120, 135) << 23) | rng.getrandbits(23) - z = neg(mul(x, y)) - _set(case, 0, x) - _set(case, 1, y) - if op == "v_fmac_f32": - case.vals[8] = z - else: - _set(case, 2, z) - return case - if kind == "invalid": - pool = [0, 0x80000000, PINF, NINF, bits(1.0), bits(-1.0), bits(2.0), bits(0.5), bits(-4.0)] - for _ in range(80): - for i, k in slots: - _set(case, i, rng.choice(pool)) - if "d" in spec["srcs"]: - case.vals[8] = rng.choice(pool) - try: - r = model(op, case.vals, case.srcs, case.out_mods, denorm="keep", translator=False)[0] - except (NotModelled, ValueError): - continue - if is_nan(r) and not any(is_nan(v) for _, v in float_inputs(case)): - return case - return None - if kind == "clamp": - if not spec["mods"] or op in NO_OUT_MODS: - return None - case.e64 = True - case.out_mods = ["clamp"] + ([rng.choice(tuple(OMOD))] if rng.random() < 0.3 else []) - for _ in range(80): - for i, k in slots: - if k in "ft": - _set(case, i, rng.choice([QNAN, 0xFFC00000, 0x80000000, 0, bits(-1.0), bits(2.0), PINF, NINF, - bits(0.5), bits(-0.0)])) - if "d" in spec["srcs"]: - case.vals[8] = rng.choice([0, 0x80000000, QNAN]) - try: - model(op, case.vals, case.srcs, case.out_mods, denorm="keep", translator=False) - except NotModelled: - return case - except ValueError: - continue - return None - raise ValueError(kind) - - -PROBE_KINDS = ("denorm_in", "denorm_out", "nan", "clamp", "invalid", "cancel", "zero_inf") - - -def gen_cases(programs, seed, ops): - """The seeded random programs, in the order run_suite draws them.""" - rng = random.Random(seed) - cases = [] - for i in range(programs): - op = rng.choice(ops) - vals, srcs, e64, out_mods = gen(rng, op) - cases.append(Case(op, vals, srcs, e64, out_mods, "random", i)) - return cases - - -def gen_probes(per_kind, seed, ops): - rng = random.Random(seed * 7919 + 13) - cases = [] - for op in ops: - for kind in PROBE_KINDS: - for j in range(per_kind): - c = gen_probe(rng, op, kind) - if c is not None: - c.index = j - cases.append(c) - return cases - - -class HwReport: - """Everything one hardware run learned.""" - - def __init__(self): - self.per_op = {} # op -> counters - self.mismatches = [] # (case, want, got) - self.denorm = {} # (mode, family, where, label) -> n - self.nan = {} # (mode, op, label) -> n - self.clamp = {} # (mode, label) -> n - self.skips = {} # reason -> n - self.minmax = {} # (mode, label) -> n - self.results = [] # (case, primary-mode words) for every case that ran - self.groups = {} # group -> counters - self.deviations = [] # (name, case, want, got): hardware = the known deviation's words - self.omod = {} # (mode, label) -> n - - def row(self, op): - return self.per_op.setdefault(op, {"programs": 0, "match": 0, "mismatch": 0, "dev": 0, "gfx11": 0, - "denorm": 0, "other": 0, "asm": 0}) - - def bump(self, table, key): - table[key] = table.get(key, 0) + 1 - - -def hw_suite(oracle, cases, guard=True, info_modes=("keep", "no_dx10", "ieee"), translator=False, model_fn=model): - """Run every case in the primary mode and compare with the model; then rerun the cases the model declines (and - those with NaNs) in the other modes for the informational tables. Returns an HwReport.""" - from hw_oracle import asm - rep = HwReport() - runnable = [] - for c in cases: - row = rep.row(c.op) - row["programs"] += 1 - why = asm.valu_skip_reason(c.op, oracle.arch) - if why: - row["gfx11"] += 1 - rep.bump(rep.skips, why) - continue - runnable.append(c) - primary = hw_run(oracle, runnable, HW_PRIMARY, guard) - info = [] - for c, got in zip(runnable, primary): - row = rep.row(c.op) - if isinstance(got, str): - row["asm"] += 1 - rep.bump(rep.skips, got) - continue - rep.results.append((c, got)) - verdict, want = hw_verdict(c, got, model_fn) - grp = rep.groups.setdefault(c.group, {"programs": 0, "match": 0, "mismatch": 0, "dev": 0, - "skip": 0}) - grp["programs"] += 1 - if verdict == "match": - row["match"] += 1 - grp["match"] += 1 - elif verdict.startswith("deviation:"): - row["dev"] += 1 - grp["dev"] += 1 - rep.deviations.append((verdict.split(":", 1)[1], c, want, got)) - elif verdict == "mismatch": - row["mismatch"] += 1 - grp["mismatch"] += 1 - rep.mismatches.append((c, want, got)) - else: - row["denorm" if want.startswith("denormal") else "other"] += 1 - grp["skip"] += 1 - rep.bump(rep.skips, want) - interesting = verdict == "skip" or has_denorm_in(c) or any(is_nan(v) for _, v in float_inputs(c)) \ - or is_nan(got[0]) or c.op in HW_ONLY_OPS or "clamp" in c.out_mods or any(m in OMOD for m in c.out_mods) - if interesting: - info.append(c) - classify(rep, HW_PRIMARY, c, got, verdict, want) - for mode in info_modes: - for c, got in zip(info, hw_run(oracle, info, mode, guard)): - if isinstance(got, str): - continue - ce = c if omod_active(mode, c.op) else strip_omod(c) # the model has no omod to judge there - verdict, want = hw_verdict(ce, got, model_fn) - classify(rep, mode, ce, got, verdict, want, orig=c) - return rep - - -def classify(rep, mode, c, got, verdict, want, orig=None): - fam = family_of(c.op) - if has_denorm_in(c) or (verdict == "skip" and want.startswith("denormal")): - rep.bump(rep.denorm, (mode, fam, *denorm_label(c, got))) - src = orig or c - if "clamp" not in src.out_mods and not any(m in OMOD for m in src.out_mods): - for fact in nan_facts(c, got[0]): - rep.bump(rep.nan, (mode, c.op, fact)) - if "clamp" in c.out_mods and verdict == "skip" and not want.startswith("denormal"): - rep.bump(rep.clamp, (mode, fam, clamp_label(c, got))) - if c.op in HW_ONLY_OPS and not any(m in OMOD for m in c.out_mods): - rep.bump(rep.minmax, (mode, "model matches" if verdict in ("match",) or verdict.startswith("deviation") else - "model differs" if verdict == "mismatch" else f"model declines ({want})")) - lab = omod_label(orig or c, got) - if lab: - rep.bump(rep.omod, (mode, lab)) - - -def negative_control(rep): - """Re-judge the hardware words already collected with each deliberately wrong model. Returns {name: (cases of - that op, mismatches the perturbation caused)}; every entry with cases must show mismatches.""" - out = {} - for name, (op, _) in PERTURBATIONS.items(): - n = bad = 0 - with perturbed(name): - for c, got in rep.results: - if c.op != op: - continue - n += 1 - if hw_verdict(c, got)[0] == "mismatch": - bad += 1 - out[name] = (n, bad) - return out - - -def hw_print(rep, show=2, translator_check=None, quiet=False): - """Tables and mismatch details. Returns the number of mismatches.""" - n_mis = len(rep.mismatches) - if quiet: - return n_mis - for g, r in sorted(rep.groups.items()): - print(f" group {g:10s} {r['programs']:6d} ran: {r['match']} match, {r['mismatch']} mismatch, " - f"{r['dev']} known deviation, {r['skip']} not judged") - fam_rows = {} - for op, r in rep.per_op.items(): - f = fam_rows.setdefault(family_of(op), dict.fromkeys(r, 0)) - for k, v in r.items(): - f[k] += v - head = (f"{'family':46s} {'programs':>8s} {'match':>7s} {'mismatch':>8s} {'known dev':>9s} {'GFX11 skip':>10s} " - f"{'denormal':>8s} {'other':>6s} {'asm rej':>7s}") - print(head) - tot = dict.fromkeys(("programs", "match", "mismatch", "dev", "gfx11", "denorm", "other", "asm"), 0) - for name, _ in FAMILIES: - r = fam_rows.get(name) - if not r: - continue - print(f"{name:46s} {r['programs']:8d} {r['match']:7d} {r['mismatch']:8d} {r['dev']:9d} {r['gfx11']:10d} " - f"{r['denorm']:8d} {r['other']:6d} {r['asm']:7d}") - for k in tot: - tot[k] += r[k] - print(f"{'total':46s} {tot['programs']:8d} {tot['match']:7d} {tot['mismatch']:8d} {tot['dev']:9d} " - f"{tot['gfx11']:10d} {tot['denorm']:8d} {tot['other']:6d} {tot['asm']:7d}") - if tot["asm"]: - print(f"WARNING: the assembler rejected {tot['asm']} program(s) the GFX11 table did not list; this is a harness " - "problem, not a skip, and the run fails (exit 2)") - for reason, n in sorted(rep.skips.items(), key=lambda t: -t[1]): - if reason.startswith("assembler rejected"): - print(f" {n} x {reason}") - by_dev = {} - for name, c, _, _ in rep.deviations: - by_dev.setdefault(name, {}).setdefault(c.op, 0) - by_dev[name][c.op] += 1 - for name, ops in sorted(by_dev.items()): - print(f" known deviation {name} x{sum(ops.values())}: " + ", ".join(f"{o} {n}" for o, n in sorted(ops.items()))) - for reason, n in sorted(rep.skips.items(), key=lambda t: -t[1]): - print(f" skip x{n}: {reason}") - shown = {} - for c, want, got in rep.mismatches: - if shown.get(c.op, 0) >= show: - continue - shown[c.op] = shown.get(c.op, 0) + 1 - print(f"--- {c.group} program {c.index}: {line(*c.args())}") - used = sorted({s[0] for s in c.srcs if s[0] != "k"} | ({8} if "d" in ALL_OPS[c.op]["srcs"] else set())) - print(" inputs: " + " ".join(f"v{r}={fdesc(c.vals[r])}" for r in used) + - "".join(f" literal={fdesc(s[1])}" for s in c.srcs if s[0] == "k")) - print(" model v8/vcc: " + " ".join(fdesc(w) for w in want)) - print(" hardware v8/vcc: " + " ".join(fdesc(w) for w in got)) - if translator_check: - print(" translator: " + translator_check(c, want, got)) - return n_mis - - -def info_print(rep): - """The informational tables: what the hardware does where the model does not judge.""" - print("\nhardware behaviour (informational; not counted as match or mismatch)") - modes = list(HW_MODES) - if rep.denorm: - print("\n f32 denormals (label = which model variants the hardware equals: kept = exact denormals, " - "flushed in+out = operands read as zero and denormal results written as zero)") - tab = {} - for (mode, fam, where, label), n in rep.denorm.items(): - tab.setdefault((fam, where, label), {})[mode] = n - for (fam, where, label), by in sorted(tab.items()): - print(f" {fam:44s} {where:8s} {label:28s} " + " ".join(f"{m}={by.get(m, 0)}" for m in modes)) - if rep.clamp: - print("\n clamp bit on a NaN or -0 result (DX10_CLAMP on = 'flush' and the other modes, off = 'no_dx10')") - tab = {} - for (mode, fam, label), n in rep.clamp.items(): - tab.setdefault(label, {})[mode] = tab.get(label, {}).get(mode, 0) + n - for label, by in sorted(tab.items()): - print(f" {label:34s} " + " ".join(f"{m}={by.get(m, 0)}" for m in modes)) - if rep.omod: - print("\n output modifier (mul:2, mul:4, div:2) where it changes the result; IEEE on = 'ieee'") - tab = {} - for (mode, label), n in rep.omod.items(): - tab.setdefault(label, {})[mode] = n - for label, by in sorted(tab.items()): - print(f" {label:47s} " + " ".join(f"{m}={by.get(m, 0)}" for m in modes)) - if rep.nan: - print("\n NaN handling (programs without clamp or omod; same program counts in every mode, so a column that " - "differs is a mode effect)") - tab = {} - for (mode, op, fact), n in rep.nan.items(): - tab.setdefault((op, fact), {})[mode] = n - for (op, fact), by in sorted(tab.items()): - print(f" {op:20s} {fact:62s} " + " ".join(f"{m}={by.get(m, 0)}" for m in modes)) - if rep.minmax: - print("\n min / max / med3 against the RDNA2 rules measured in #634") - tab = {} - for (mode, label), n in rep.minmax.items(): - tab.setdefault(label, {})[mode] = n - for label, by in sorted(tab.items()): - print(f" {label:60s} " + " ".join(f"{m}={by.get(m, 0)}" for m in modes)) - - -def self_test(): - """The model and the harness must both be able to pass and to fail.""" - ok = True - # Model spot checks with known answers. - checks = [ - (add(bits(1.0), bits(2.0)), bits(3.0)), - (add(0x80000000, 0x80000000), 0x80000000), - (add(0x80000000, 0), 0), - (mul(bits(-2.0), 0), 0x80000000), - (legacy_mul(PINF, 0x80000000), 0), - (fma(bits(1.0 + 2 ** -23), bits(1.0 - 2 ** -23), bits(-1.0)), bits(-(2.0 ** -46))), - (round_rtz_f16(bits(70000.0)), 0x7BFF), - (round_rtz_f16(bits(1.0 + 2 ** -11)), 0x3C00), - (round_rne_f16(bits(65520.0)), 0x7C00), - (rounding(bits(-0.5), "rne"), 0x80000000), - (rounding(bits(2.5), "rne"), bits(2.0)), - (cube("v_cubeid_f32", bits(1.0), bits(-3.0), bits(2.0)), bits(3.0)), - (cmp_class(0xFFC00000, 1 << 1), 1), - (apply_out_mods(bits(0.75), ["mul:2", "clamp"]), bits(1.0)), - (round_f32(Fraction(1, 3)), 0x3EAAAAAB), - ] - for i, (got, want) in enumerate(checks): - if got != want: - print(f"model check {i} FAILED: 0x{got:08x} != 0x{want:08x}") - ok = False - vals = [bits(1.0), bits(2.0)] + [0] * 7 - status, d = check("v_add_f32", vals, [(0, {}), (1, {})], False, []) - if status != "match": - print(f"canary FAILED: v_add_f32 1+2 gave {status}: {d}") - ok = False - real = OPS["v_add_f32"]["fn"] - OPS["v_add_f32"]["fn"] = lambda x, y: real(x, y) ^ 1 - try: - status, _ = check("v_add_f32", vals, [(0, {}), (1, {})], False, []) - finally: - OPS["v_add_f32"]["fn"] = real - if status != "mismatch": - print("canary FAILED: a corrupted model result was not flagged") - ok = False - ok &= hw_self_test() - if ok: - print("canaries: model checks ok, match ok, mismatch detected") - return ok - - -def hw_self_test(): - """The hardware side without hardware: kernel text, the verdicts, the classifiers and the negative control.""" - ok = True - cases = gen_cases(300, 5, tuple(ALL_OPS)) - for op, _ in PERTURBATIONS.values(): - cases += gen_cases(150, 6, (op,)) - fake = [] - for c in cases: - try: - w = model(c.op, c.vals, c.srcs, c.out_mods, denorm="ftz", translator=False) - except (NotModelled, ValueError): - continue - fake.append((c, w)) - rep = HwReport() - rep.results = list(fake) - bad = [c.op for c, w in fake if hw_verdict(c, w)[0] == "mismatch"] - if bad or len(fake) < 100: - print(f"canary FAILED: the model disagrees with itself on {bad[:3]} ({len(fake)} cases)") - ok = False - nc = negative_control(rep) - silent = [n for n, (cases_n, bad_n) in nc.items() if cases_n >= 5 and not bad_n] - if silent: - print(f"canary FAILED: perturbations not detected: {silent}") - ok = False - for c, _ in fake[:40]: - text = "\n".join(hw_lines(c, "gfx1150")) - if "global_store_b64 v20, v[8:9], s[2:3]" not in text or not text.endswith("s_endpgm") or "@" in text: - print(f"canary FAILED: malformed kernel body for {c.op}") - ok = False - break - a = Case("v_add_f32", [bits(1.0), bits(2.0)] + [0] * 7, [(0, {}), (1, {})], False, []) - if hw_verdict(a, [bits(3.0), 0])[0] != "match" or hw_verdict(a, [bits(3.0) ^ 1, 0])[0] != "mismatch": - print("canary FAILED: hw_verdict") - ok = False - if hw_verdict(a, [QNAN, 0])[0] != "mismatch" or hw_verdict(a, [bits(3.0), 1])[0] != "mismatch": - print("canary FAILED: hw_verdict value/vcc") - ok = False - d = Case("v_add_f32", [0x00000001, bits(1.0)] + [0] * 7, [(0, {}), (1, {})], False, []) - if hw_verdict(d, [bits(1.0), 0])[0] != "skip": - print("canary FAILED: a denormal operand is not skipped") - ok = False - m = Case("v_mul_f32", [0x00000001, bits(1048576.0)] + [0] * 7, [(0, {}), (1, {})], False, []) - if denorm_label(m, [0, 0]) != ("operand", "ftz|ftz_in|ftz_out") or \ - denorm_label(m, [bits(2.0 ** -129), 0]) != ("operand", "keep"): - print("canary FAILED: denorm_label") - ok = False - n = Case("v_add_f32", [0x7FA00000, bits(1.0)] + [0] * 7, [(0, {}), (1, {})], False, []) - if nan_facts(n, 0x7FE00000) != ["result = first NaN source (a signalling one)", "signalling NaN quieted"] or \ - nan_facts(n, 0x7FA00000)[1:] != ["signalling NaN passes unchanged"]: - print("canary FAILED: nan_facts") - ok = False - return ok - - -def main(argv=None): - ap = argparse.ArgumentParser(description="32-bit float VALU differential fuzzer: the model against the translator " - "and/or the AMD GPU.") - ap.add_argument("--programs", type=int, default=1000) - ap.add_argument("--seed", type=int, default=1) - ap.add_argument("--ops", default=None, help="comma-separated op names (default: all the oracle covers)") - ap.add_argument("--show", type=int, default=2, help="failures to print per op") - ap.add_argument("--list-ops", action="store_true") - ap.add_argument("--self-test", action="store_true") - ap.add_argument("--oracle", default="translator", - help="comma-separated: translator (default; needs llvm-mc for gfx1013) or hw (natively on the AMD " - "GPU, wave32; tools/hw_oracle/), or translator,hw. Exit 77 when the hardware tools are missing") - ap.add_argument("--hw-arch", default=None, help="GPU architecture to assemble for (default: detected)") - ap.add_argument("--probes", type=int, default=12, - help="with hw: structured probes per op and kind (denormal operand, denormal result, NaN payloads, " - "clamp of NaN); they are judged where the model has an answer and recorded where it has not") - ap.add_argument("--no-hw-guard", action="store_true", help="no s_nop 7 after the instruction in the native kernels") - ap.add_argument("--no-info", action="store_true", help="leave out the informational hardware tables") - ap.add_argument("--perturb", choices=sorted(PERTURBATIONS), help="judge the hardware against a deliberately wrong " - "model (mismatches must appear)") - ap.add_argument("--negative-control", action="store_true", - help="after the hardware run, re-judge its words with every perturbed model; exit 1 if one is not caught") - ap.add_argument("--fma", choices=("glsl", "khr"), default="glsl", - help="with the translator oracle: emit the fused multiply-adds as GLSL Fma (default) or OpFmaKHR") - ap.add_argument("--keep", help="write the kernel body of every hardware mismatch to this folder") - if argv is None: - argv = sys.argv[1:] - if not argv: - ap.error("no arguments given; pass --help for the available options") - a = ap.parse_args(argv) - import rdna2spirv # after the arguments are parsed, so --help and usage errors don't wait for it to compile - rdna2spirv.FMA_KHR = a.fma == "khr" - if a.programs < 1: - ap.error("--programs must be at least 1") - if a.probes < 0: - ap.error("--probes cannot be negative") - if a.list_ops: - print("\n".join(ALL_OPS)) - return 0 - if a.self_test: - return 0 if self_test() else 1 - backends = tuple(dict.fromkeys(t.strip() for t in a.oracle.split(","))) - if not backends or any(t not in ("translator", "hw") for t in backends): - ap.error("--oracle takes translator, hw or translator,hw") - if (a.perturb or a.negative_control or a.keep) and "hw" not in backends: - ap.error("--perturb, --negative-control and --keep need --oracle hw") - ops = tuple(ALL_OPS if "hw" in backends else OPS) - if a.ops: - ops = tuple(o.strip() for o in a.ops.split(",") if o.strip()) - unknown = [o for o in ops if o not in ALL_OPS] - if unknown: - ap.error(f"unknown ops: {', '.join(unknown)} (see --list-ops)") - if "hw" not in backends and any(o in HW_ONLY_OPS for o in ops): - ap.error(f"{', '.join(o for o in ops if o in HW_ONLY_OPS)} can only be run with --oracle hw") - oracle = None - if "hw" in backends: - from hw_oracle import runner - try: - oracle = runner.open_oracle(arch=a.hw_arch) - except runner.Unavailable as e: - print(f"hardware oracle unavailable: {e}") - return 77 - print(f"hardware oracle: {oracle.device}") - rc = 0 - harness = False - try: - cases = gen_cases(a.programs, a.seed, ops) - if "translator" in backends: - counts, _, _ = translate_cases(cases, a.seed, show=a.show) - rc |= bool(counts["mismatch"]) - if oracle: - words = hw_probe_modes(oracle) - print("MODE read back in the kernels: " + ", ".join(f"{n} 0x{w:x}" for n, w in words.items())) - if a.probes: - cases += gen_probes(a.probes, a.seed, ops) - model_ctx = perturbed(a.perturb) if a.perturb else None - if model_ctx: - model_ctx.__enter__() - try: - rep = hw_suite(oracle, cases, guard=not a.no_hw_guard, - info_modes=() if a.no_info else tuple(m for m in HW_MODES if m != HW_PRIMARY)) - finally: - if model_ctx: - model_ctx.__exit__(None, None, None) - print(f"\nhardware vs F32Model{' (perturbed: ' + a.perturb + ')' if a.perturb else ''}, " - f"{len(cases)} programs, mode {HW_PRIMARY} (MODE 0x{words[HW_PRIMARY]:x}), seed {a.seed}:") - tr = translator_verdict if "translator" in backends else None - n_mis = hw_print(rep, show=a.show, translator_check=tr) - if any(r["asm"] for r in rep.per_op.values()): - harness = True - if tr and rep.deviations: - tally = {} - for name, c, want, got in rep.deviations: - if c.op in HW_ONLY_OPS: - continue - verdict = tr(c, want, got).split(" (")[0] - tally[(name, verdict)] = tally.get((name, verdict), 0) + 1 - for (name, verdict), n in sorted(tally.items()): - print(f" translator on known deviation {name} x{n}: {verdict}") - if not a.no_info: - info_print(rep) - if a.keep and rep.mismatches: - os.makedirs(a.keep, exist_ok=True) - for k, (c, _, _) in enumerate(rep.mismatches): - with open(os.path.join(a.keep, f"{c.group}_{c.index}_{c.op}_{k}.asm"), "w", encoding="utf-8", newline="\n") as f: - f.write("\n".join(hw_lines(c, oracle.arch, not a.no_hw_guard)) + "\n") - if a.perturb: - print(f"perturbed model '{a.perturb}': {n_mis} mismatches" + ("" if n_mis else " -- NOT DETECTED")) - rc |= not n_mis - return 2 if harness else int(bool(rc)) - if a.negative_control: - print("\nnegative control (wrong models judged against the same hardware words):") - for name, (n, bad) in negative_control(rep).items(): - status = "caught" if bad else ("no programs of that op ran" if not n else "NOT CAUGHT") - print(f" {name:16s} {n:5d} programs of {PERTURBATIONS[name][0]}: {bad} mismatches ({status})") - rc |= bool(n and not bad) - rc |= bool(n_mis) - finally: - if oracle: - oracle.close() - return 2 if harness else int(bool(rc)) - - -if __name__ == "__main__": - try: # a redirected stdout is strict ANSI code page under -I; write '?' for what it cannot encode - sys.stdout.reconfigure(errors="replace") - except (AttributeError, ValueError, OSError): - pass - sys.exit(main()) diff --git a/tools/f64_diff.py b/tools/f64_diff.py deleted file mode 100644 index ef1f8a807..000000000 --- a/tools/f64_diff.py +++ /dev/null @@ -1,812 +0,0 @@ -"""Differential checks for the 47 binary64 VALU instruction forms translated by main. - -The reference below decodes IEEE-754 words itself. Finite arithmetic is performed with -Fractions and rounded to binary64; it shares no implementation with the translator, its -CPU interpreter, cpu_ref, or another fuzzer. The second path translates generated listings -and executes their SPIR-V with the semantic one-lane interpreter. Only synthetic programs -are created; no game files are read. - -The GPU path is deliberately optional. It translates the same fragment shader, runs it -through vk_harness, and reads back RGBA32F words. ``--oracle hw`` runs the programs natively -on an AMD GPU through tools/hw_oracle (``--hw-arch`` selects the architecture) and compares -them with the reference; it returns 77 only when that oracle is unavailable. ``--known`` runs -known divergence probes; a reproduced mismatch intentionally returns 1. -Usage: `python -I tools/f64_diff.py --help` lists the options. -""" -import argparse -import gc -import math -import os -import random -import re -import shutil -import struct -import subprocess -import sys -import tempfile -import warnings -from collections import Counter -from fractions import Fraction - -HERE = os.path.dirname(os.path.abspath(__file__)) -ROOT = os.path.dirname(HERE) -SEM = os.path.join(ROOT, "tests", "semantic") -for path in (HERE, SEM, os.path.join(ROOT, "tests")): - if path not in sys.path: - sys.path.insert(0, path) -sys.dont_write_bytecode = True - -import rdna2spirv # noqa: E402 -from spirv_mini_interp import UnsupportedConstruct, run_fragment # noqa: E402 -import spirv_interp # noqa: E402 - -M32 = 0xFFFFFFFF -M64 = 0xFFFFFFFFFFFFFFFF -EXP = 0x7FF0000000000000 -FRAC = 0x000FFFFFFFFFFFFF -QNAN = 0x7FF8000000000000 -STUB_DXBC = b"DXBC" + bytes(24) + struct.pack("> 32) & M32 - - -def is_nan(x): - return (x & EXP) == EXP and (x & FRAC) != 0 - - -def is_inf(x): - return x & 0x7FFFFFFFFFFFFFFF == EXP - - -def is_zero(x): - return x & 0x7FFFFFFFFFFFFFFF == 0 - - -def is_subnormal(x): - return (x & EXP) == 0 and (x & FRAC) != 0 - - -def is_f32_subnormal(x): - return (x & 0x7F800000) == 0 and (x & 0x7FFFFF) != 0 - - -def to_float(bits): - return struct.unpack("> 52) & 0x7FF, bits & FRAC - if e == 0: - n, p = m, -1074 - else: - n, p = m | (1 << 52), e - 1075 - f = Fraction(n) * (Fraction(2) ** p) - return -f if bits >> 63 else f - - -def round_fraction(value, mode=0, negative_zero=False): - """Round a finite rational to binary64: nearest-even, +inf, -inf, or toward zero.""" - if not value: - return 0x8000000000000000 if negative_zero else 0 - sign = 0x8000000000000000 if value < 0 else 0 - a = abs(value) - e = a.numerator.bit_length() - a.denominator.bit_length() - while Fraction(2) ** e > a: - e -= 1 - while Fraction(2) ** (e + 1) <= a: - e += 1 - def overflow(): - negative = bool(sign) - if mode == 3 or (mode == 1 and negative) or (mode == 2 and not negative): - return sign | 0x7FEFFFFFFFFFFFFF - return sign | EXP - - if e > 1023: return overflow() - if e < -1022: - scaled = a * Fraction(2 ** 1074) - q, r = divmod(scaled.numerator, scaled.denominator) - increment = (2 * r > scaled.denominator or (2 * r == scaled.denominator and q & 1)) if mode == 0 else bool(r) and ((mode == 1 and not sign) or (mode == 2 and bool(sign))) - if increment: - q += 1 - return sign | q - scaled = a / Fraction(2) ** (e - 52) - q, r = divmod(scaled.numerator, scaled.denominator) - increment = (2 * r > scaled.denominator or (2 * r == scaled.denominator and q & 1)) if mode == 0 else bool(r) and ((mode == 1 and not sign) or (mode == 2 and bool(sign))) - if increment: - q += 1 - if q == 1 << 53: - q >>= 1 - e += 1 - if e > 1023: - return overflow() - return sign | ((e + 1023) << 52) | (q & FRAC) - - -def add_bits(a, b, mode=0): - """IEEE sum; MODE 3 (toward zero) steps back if nearest-even rounded away from zero.""" - if is_nan(a) or is_nan(b): - return QNAN - if is_inf(a) or is_inf(b): - af, bf = to_float(a), to_float(b) - return from_float(af + bf) - exact = to_fraction(a) + to_fraction(b) - # IEEE 754-2019 6.3: an exact zero sum of two zeros of the same sign keeps that sign in every mode; any other - # exact zero (opposite-signed zeros, or x + (-x)) is -0 only when rounding toward negative, +0 otherwise. - if is_zero(a) and is_zero(b) and (a ^ b) >> 63 == 0: - negzero = bool(a >> 63) - else: - negzero = mode == 2 - return round_fraction(exact, mode, negzero) - - -def class_index(bits): - sign, e, m = bits >> 63, (bits >> 52) & 0x7FF, bits & FRAC - if e == 0x7FF: - if m: - return 0 if not (m & (1 << 51)) else 1 - return 2 if sign else 9 - if e == 0: - if not m: - return 5 if sign else 6 - return 4 if sign else 7 - return 3 if sign else 8 - - -def compare(cond, a, b): - unordered = is_nan(a) or is_nan(b) - if cond == "f": return 0 - if cond == "tru": return 1 - if cond == "o": return int(not unordered) - if cond == "u": return int(unordered) - if unordered: - return int({"nge": 0, "nlg": 1, "ngt": 2, "nle": 3, "neq": 4, "nlt": 5}.get(cond, -1) >= 0) - x, y = to_float(a), to_float(b) - result = {"lt": x < y, "eq": x == y, "le": x <= y, "gt": x > y, "lg": x != y, - "ge": x >= y, "nge": x < y, "nlg": x == y, "ngt": x <= y, - "nle": x > y, "neq": x != y, "nlt": x >= y} - return int(result[cond]) - - -def fixup(s0, s1, s2): - sign = (s1 ^ s2) & 0x8000000000000000 - if is_nan(s2): return s2 | (1 << 51) - if is_nan(s1): return s1 | (1 << 51) - z1, z2, i1, i2 = is_zero(s1), is_zero(s2), is_inf(s1), is_inf(s2) - if (z1 and z2) or (i1 and i2): return 0xFFF8000000000000 - e1, e2 = (s1 >> 52) & 0x7FF, (s2 >> 52) & 0x7FF - ediff = e2 - e1 - if i1 or z2 or ediff < -1074: return sign - if z1 or i2 or ediff >= 1024 or is_nan(s0): return sign | EXP - return (s0 & 0x7FFFFFFFFFFFFFFF) | sign - - -def frexp(bits): - sign = bits & 0x8000000000000000 - e, m = (bits >> 52) & 0x7FF, bits & FRAC - if e == 0x7FF or (e == 0 and m == 0): return bits, 0 - if e: - return sign | (0x3FE << 52) | m, e - 1022 - top = m.bit_length() - 1 - exp = top - 1073 - mantissa = m << (52 - top) - return sign | (0x3FE << 52) | (mantissa & FRAC), exp - - -def rounded_unary(op, bits): - if is_nan(bits) or is_inf(bits) or is_zero(bits): return bits - x = to_float(bits) - value = {"v_trunc_f64": math.trunc, "v_ceil_f64": math.ceil, - "v_rndne_f64": round, "v_floor_f64": math.floor}[op](x) - if value == 0 and bits >> 63: return 0x8000000000000000 - return from_float(float(value)) - - -def read_source(tok, vgpr, sgpr): - tok = tok.strip() - neg = tok.startswith("neg(") or tok.startswith("-|") or (tok.startswith("-") and tok[1:].startswith(("v[", "s[", "v", "s", "|"))) - absmod = "|" in tok - tok = tok.replace("|", "").replace("neg(", "").replace(")", "").strip() - if neg and tok.startswith("-"): - tok = tok[1:].strip() - m = re.fullmatch(r"([sv])\[(\d+):(\d+)\]", tok) - if m: - regs = vgpr if m.group(1) == "v" else sgpr - lo, hi = int(m.group(2)), int(m.group(3)) - value = words_to_bits(regs.get(lo, 0), regs.get(hi, 0)) - elif tok.startswith(("v", "s")) and tok[1:].isdigit(): - raise HarnessError("binary64 source must be an even register pair") - elif tok.startswith("0x"): - # A printed 32-bit ISA literal occupies bits 63:32; a spelling of more than 8 hex digits is - # the whole binary64 value (the full-width form gen_source writes), as in the translator. - value = int(tok, 16) - if len(tok) - 2 <= 8: value <<= 32 - value &= M64 - elif re.fullmatch(r"[-+]?\d+", tok): - n = int(tok) - value = n & M64 - else: - try: value = from_float(float(tok)) - except (ValueError, OverflowError) as exc: raise HarnessError(f"bad source {tok!r}") from exc - if absmod: value &= 0x7FFFFFFFFFFFFFFF - if neg: value ^= 0x8000000000000000 - return value - - -def parse_source_args(line): - head, *args = line.split(",") - bits = head.split() - return bits[0], bits[1].rstrip(","), [x.strip() for x in args] - - -def ref_program(lines, include_known=False, exec_lo=M32): - vgpr, sgpr, mode, vcc, active = {}, {}, 0, 0, exec_lo - for line in lines: - s = line.strip() - if not s or s.startswith((";", "exp ", "s_endpgm")): continue - if s.startswith("v_mov_b32") or s.startswith("s_mov_b32"): - op, dst, srcs = parse_source_args(s) - src = srcs[0] - if dst == "exec_lo": active = sgpr.get(int(src[1:]), 0) & M32 - elif src == "exec_lo": sgpr[int(dst[1:])] = active - else: - if re.fullmatch(r"[sv]\d+", src): - regs = vgpr if src.startswith("v") else sgpr - word = regs.get(int(src[1:]), 0) - else: word = int(src, 0) - (vgpr if dst.startswith("v") else sgpr)[int(dst[1:])] = word & M32 - continue - if s.startswith("s_round_mode "): - mode = (int(s.split(None, 1)[1], 0) >> 2) & 3 - continue - if "s_setreg_imm32_b32" in s: - mode = (int(s.rsplit(",", 1)[1], 0) >> 2) & 3 - continue - if s.startswith("v_cmp_eq_i32_e32 vcc_lo,"): - vcc = int(s.rsplit(",", 2)[1].strip(), 0) == int(s.rsplit(",", 1)[1].strip(), 0) - continue - op, dst, a = parse_source_args(s) - if op in ROUND: - out = rounded_unary(op, read_source(a[0], vgpr, sgpr)) - lo, hi = bits_to_words(out); vgpr[int(dst[2:-1].split(":")[0])] = lo - vgpr[int(dst[2:-1].split(":")[0]) + 1] = hi - elif op == "v_add_f64": - modifiers = re.findall(r"(?> 63 else 0x7F800000 - elif op == "v_rcp_f64": out = from_float(1.0 / to_float(x)) if not is_zero(x) else ((x ^ 0x3FF0000000000000) & 0x8000000000000000) | EXP - elif op == "v_sqrt_f64": - if is_zero(x): out = x - elif x >> 63: out = QNAN - else: out = from_float(math.sqrt(to_float(x))) - elif is_zero(x): out = (x & 0x8000000000000000) | EXP - else: out = QNAN if x >> 63 else from_float(1.0 / math.sqrt(to_float(x))) - if op in ("v_rcp_f64", "v_rsq_f64", "v_sqrt_f64") and (is_subnormal(x) or is_subnormal(out)): - raise SkipCase(f"{op} subnormal operand/result is driver-dependent (FTZ)") - if op == "v_cvt_f32_f64" and is_f32_subnormal(out): - raise SkipCase("v_cvt_f32_f64 subnormal f32 result is driver-dependent (FTZ)") - if op == "v_cvt_f32_f64": vgpr[int(dst[1:])] = out - else: - d = int(dst[2:-1].split(":")[0]); vgpr[d], vgpr[d + 1] = bits_to_words(out) - elif op == "v_div_fixup_f64": - args = [read_source(t, vgpr, sgpr) for t in a[:3]] - s0, s1, s2 = args - ediff = ((s2 >> 52) & 0x7FF) - ((s1 >> 52) & 0x7FF) - normal_division = (not is_nan(s1) and not is_inf(s1) and not is_zero(s1) - and not is_nan(s2) and not is_inf(s2) and not is_zero(s2) - and -1074 <= ediff < 1024) - if not include_known and is_nan(s0) and normal_division: - raise SkipCase(f"KNOWN_DIVERGENCE div-fixup-nan-s0: {KNOWN_DIVERGENCES['div-fixup-nan-s0']}") - d = int(dst[2:-1].split(":")[0]); vgpr[d], vgpr[d + 1] = bits_to_words(fixup(*args)) - elif op == "v_frexp_mant_f64": - d = int(dst[2:-1].split(":")[0]); vgpr[d], vgpr[d + 1] = bits_to_words(frexp(read_source(a[0], vgpr, sgpr))[0]) - elif op == "v_frexp_exp_i32_f64": - vgpr[int(dst[1:])] = frexp(read_source(a[0], vgpr, sgpr))[1] & M32 - elif "class" in op: - operands = [dst] + a if op.startswith("v_cmpx") else a - src = read_source(operands[-2], vgpr, sgpr); mask = int(operands[-1], 0) & 0x3FF - hit = int(bool(mask & (1 << class_index(src)))) - sgpr[20] = hit - if op.startswith("v_cmpx"): active &= M32 if hit else 0 - elif op.startswith("v_cmp_") or op.startswith("v_cmpx_"): - cond = op.split("_")[2] - operands = [dst] + a if op.startswith("v_cmpx") else a - hit = compare(cond, read_source(operands[-2], vgpr, sgpr), read_source(operands[-1], vgpr, sgpr)) - sgpr[20] = hit - if op.startswith("v_cmpx"): active &= M32 if hit else 0 - elif op == "v_cndmask_b32_e64": - _, dst, a = parse_source_args(s) - vgpr[int(dst[1:])] = int(a[1], 0) & M32 if sgpr.get(20, 0) else int(a[0], 0) & M32 - elif op == "v_div_fmas_f64": - x, y, z = (read_source(t, vgpr, sgpr) for t in a) - if any(is_nan(t) or is_inf(t) for t in (x, y, z)): - raise SkipCase("non-finite v_div_fmas_f64 operands are not judged") - exact = to_fraction(x) * to_fraction(y) + to_fraction(z) - if vcc: exact *= 1 << 64 - d = int(dst[2:-1].split(":")[0]); vgpr[d], vgpr[d + 1] = bits_to_words(round_fraction(exact)) - else: - raise HarnessError(f"reference does not implement {op}") - return [vgpr.get(r, 0) & M32 for r in range(8, 12)] - - -def write_listing(path, lines, name): - with open(path, "w", encoding="utf-8", newline="\n") as f: - f.write(f"; {name} code 0x0..0x1000\n") - for line in lines: f.write("\t" + line + "\n") - f.write("\t" + EXPORT + "\n\ts_endpgm\n") - - -def translate_assembly(lines, name, tmpdir): - dis = os.path.join(tmpdir, "disasm"); os.makedirs(dis, exist_ok=True) - src = os.path.join(dis, name + ".s") - write_listing(src, lines, name) - with open(os.path.join(tmpdir, name + ".dxbc"), "wb") as f: f.write(STUB_DXBC) - with warnings.catch_warnings(): - warnings.simplefilter("ignore", ResourceWarning) - return rdna2spirv.translate(src) - - -def translate(lines, name, tmpdir): - asm = translate_assembly(lines, name, tmpdir) - gc.collect() - if "OpCapability Float64" in asm: - if "OpFDiv %double" in asm: - raise SkipCase("the available SPIR-V CPU interpreters do not model binary64 OpFDiv") - if "OpFConvert" in asm: - raise SkipCase("the available SPIR-V CPU interpreters do not model binary64 OpFConvert") - try: return [int(x) & M32 for x in spirv_interp.run(asm).vgpr[8:12]] - except (NotImplementedError, ZeroDivisionError, OverflowError, ValueError) as exc: - raise SkipCase(f"binary64 SPIR-V interpreter limitation: {type(exc).__name__}: {exc}") from exc - try: out = run_fragment(asm) - except UnsupportedConstruct as exc: raise SkipCase(str(exc)) from exc - if list(out) != ["%out_mrt0"]: raise HarnessError(f"unexpected outputs: {list(out)}") - return [int(x) & M32 for x in out["%out_mrt0"]] - - -def sdk_tool(name): - exe = name + (".exe" if os.name == "nt" else "") - found = shutil.which(exe) or shutil.which(name) - if found: return found - sdk = os.environ.get("VULKAN_SDK") - candidate = os.path.join(sdk, "Bin", exe) if sdk else "" - return candidate if candidate and os.path.isfile(candidate) else None - - -def prepare_gpu(exe, tmpdir): - if not os.path.isfile(exe): raise GPUUnavailable(f"vk_harness not found: {exe}") - glslc, spirv_as = sdk_tool("glslc"), sdk_tool("spirv-as") - if not glslc or not spirv_as: raise GPUUnavailable("Vulkan SDK glslc and spirv-as are required for --oracle gpu") - vertex = os.path.join(ROOT, "runtime", "test", "glsl", "vs_fullscreen.vert") - if not os.path.isfile(vertex): raise HarnessError(f"full-screen vertex shader is missing: {vertex}") - vs_spv = os.path.join(tmpdir, "f64_diff_vs.spv") - try: - r = subprocess.run([glslc, vertex, "-o", vs_spv], capture_output=True, text=True, timeout=30) - except subprocess.TimeoutExpired: raise HarnessError("glslc timed out while compiling the full-screen vertex shader") from None - if r.returncode: raise HarnessError(f"glslc failed: {(r.stdout + r.stderr).strip()}") - return {"exe": exe, "glslc": glslc, "spirv_as": spirv_as, "vs_spv": vs_spv} - - -def run_gpu(lines, name, tmpdir, gpu): - asm = translate_assembly(lines, name, tmpdir) - asm_path = os.path.join(tmpdir, name + ".spvasm") - fs_spv = os.path.join(tmpdir, name + ".spv") - raw = os.path.join(tmpdir, name + ".raw") - with open(asm_path, "w", encoding="utf-8", newline="\n") as f: f.write(asm) - try: - r = subprocess.run([gpu["spirv_as"], "--target-env", "vulkan1.2", asm_path, "-o", fs_spv], - capture_output=True, text=True, timeout=30) - except subprocess.TimeoutExpired: raise HarnessError("spirv-as timed out while assembling the translated shader") from None - if r.returncode: raise HarnessError(f"spirv-as failed: {(r.stdout + r.stderr).strip()}") - try: - r = subprocess.run([gpu["exe"], gpu["vs_spv"], fs_spv, raw, "1", "1"], - capture_output=True, text=True, timeout=60) - except subprocess.TimeoutExpired: raise HarnessError("vk_harness timed out after 60 s") from None - detail = " ".join((r.stdout + r.stderr).split()) - if r.returncode == 77: raise GPUUnavailable(detail or "vk_harness reports that the Vulkan device cannot run this shader") - if r.returncode: raise HarnessError(f"vk_harness exited {r.returncode}: {detail}") - if not os.path.isfile(raw) or os.path.getsize(raw) != 16: - raise HarnessError("vk_harness did not write exactly four RGBA32F dwords") - with open(raw, "rb") as f: return list(struct.unpack("<4I", f.read())) - - -# The float MODE the hardware kernels start with: the one docs/design.md infers for the game's shaders (the same as -# tools/fmisc_diff.py): IEEE off so output modifiers apply, DX10_CLAMP on. Directives an architecture cannot set make -# the program a counted skip (runner.Oracle.run returns the reason). -HW_MODE = {"ieee": 0, "dx10_clamp": 1, "denorm32": 0} - - -def hw_kernel(lines): - """A raw tools/hw_oracle kernel: the program on one lane, then v8..v11 stored at the output pointer.""" - from hw_oracle import asm - return asm.Kernel(list(lines) + ["v_mov_b32 v0, 0", "global_store_b128 v0, v[8:11], s[2:3]", "s_endpgm"], - wave=32, threads=1, words=4, raw=True, mode=HW_MODE) - - -def open_hw_oracle(arch=None): - """The AMD hardware oracle, or HWUnavailable when its tools or device are missing.""" - try: - from hw_oracle import runner - except ImportError as exc: - raise HWUnavailable(f"tools/hw_oracle cannot be imported: {exc}") from exc - try: - return runner.open_oracle(arch=arch) - except runner.Unavailable as exc: - raise HWUnavailable(str(exc)) from exc - - -def rand_bits(rng): - # Mostly finite normals, with signed zeros, infinities and NaNs for predicate/class coverage. - if rng.random() < .2: - return rng.choice((0, 0x8000000000000000, EXP, 0xFFF0000000000000, QNAN, 0xFFF0000000000001, 1, 0x8000000000000001)) - return rng.getrandbits(64) & 0xFFEFFFFFFFFFFFFF | (rng.getrandbits(1) << 63) | (rng.randrange(1, 2047) << 52) - - -def gen_source(rng, idx, allow_literal=True, bus=None): - choices = ("v", "s", "fimm", "inline", "literal") if allow_literal else ("v", "s", "fimm", "inline") - kind = rng.choice(choices) - if bus is not None: - if kind == "s" and len(bus[0]) >= 2: kind = "v" - if kind == "literal" and bus[1]: kind = "v" - if kind == "s": bus[0].add(idx) - if kind == "literal": bus[1] = True - if kind == "v": return f"v[{8 + 2*idx}:{9 + 2*idx}]" - if kind == "s": return f"s[{4 + 2*(idx % 2)}:{5 + 2*(idx % 2)}]" - if kind == "fimm": return rng.choice(("0.0", "-0.0", "1.0", "-1.0", "1.5", "2.0", "0.5", "3.25")) - if kind == "inline": return str(rng.choice((-16, -1, 0, 1, 2, 16, 64))) - if bus is not None and bus[2] == 64: - return f"0x{rng.getrandbits(64):016x}" - return f"0x{rng.getrandbits(32):08x}" - - -def maybe_word_modifier(rng, src): - """Only add modifiers to integer-word paths (round, compare and class), not %double math.""" - if not src.startswith(("v[", "s[")) or rng.random() >= 0.25: return src - choice = rng.randrange(3) - return f"|{src}|" if choice == 0 else f"-{src}" if choice == 1 else f"-|{src}|" - - -def make_case(rng, op, allow_literal=True, known_case=None): - setup_lines, body_lines = [], [] - vg, sg = {}, {} - for r in range(4, 8): - word = rng.getrandbits(32); sg[r] = word; setup_lines.append(f"s_mov_b32 s{r}, 0x{word:08x}") - # Replace both data lanes with selected edge cases for interpretable differential coverage. - for d in range(4): - bits = rand_bits(rng); lo, hi = bits_to_words(bits); r = 8 + 2*d - vg[r], vg[r + 1] = lo, hi - setup_lines += [f"v_mov_b32 v{r}, 0x{lo:08x}", f"v_mov_b32 v{r+1}, 0x{hi:08x}"] - if op == "v_add_f64": body_lines.append(f"s_round_mode {0 if known_case else rng.choice((0, 4, 8, 12))}") - high_literal = op in ROUND or op in ("v_add_f64", "v_cvt_f32_f64") or "cmp" in op or "class" in op - bus = [set(), False, 32 if high_literal else 64] - if op in ROUND: - src = maybe_word_modifier(rng, gen_source(rng, 0, allow_literal, bus)) - body_lines.append(f"{op} v[8:9], {src}") - elif op in ("v_cvt_f32_f64", "v_rcp_f64", "v_rsq_f64", "v_sqrt_f64", "v_frexp_mant_f64", "v_frexp_exp_i32_f64"): - src = gen_source(rng, 0, allow_literal, bus) - dst = "v8" if op in ("v_cvt_f32_f64", "v_frexp_exp_i32_f64") else "v[8:9]" - body_lines.append(f"{op} {dst}, {src}") - elif op == "v_add_f64": - left, right = gen_source(rng, 0, allow_literal, bus), gen_source(rng, 1, allow_literal, bus) - if known_case == "double-neg-abs": left = "-|v[8:9]|" - suffix = " mul:2" if known_case == "f64-omod" else " clamp" if known_case == "fclamp-nan-zero" else "" - if known_case == "fclamp-nan-zero": left, right = "0x7ff80001", "1.0" - body_lines.append(f"{op} v[8:9], {left}, {right}{suffix}") - elif op == "v_div_fixup_f64": - if known_case == "div-fixup-nan-s0": - setup_lines += ["v_mov_b32 v12, 0x00000000", "v_mov_b32 v13, 0x7ff80000"] - body_lines.append(f"{op} v[8:9], v[12:13], 1.0, 2.0") - else: - body_lines.append(f"{op} v[8:9], {gen_source(rng, 0, allow_literal, bus)}, {gen_source(rng, 1, allow_literal, bus)}, {gen_source(rng, 2, allow_literal, bus)}") - elif op == "v_div_fmas_f64": - # VCC is initialized true so the f64 scaled FMA path is exercised deterministically. - body_lines += ["v_cmp_eq_i32_e32 vcc_lo, 0, 0", f"{op} v[8:9], {gen_source(rng, 0, allow_literal, bus)}, {gen_source(rng, 1, allow_literal, bus)}, {gen_source(rng, 2, allow_literal, bus)}"] - elif "class" in op: - src, mask = maybe_word_modifier(rng, gen_source(rng, 2 if op.startswith("v_cmpx") else 0, allow_literal, bus)), f"0x{rng.randrange(1024):x}" - if op.startswith("v_cmpx"): - body_lines += ["s_mov_b32 s10, exec_lo", f"{op}_e64 {src}, {mask}", "s_mov_b32 s22, exec_lo", "s_mov_b32 exec_lo, s10", "v_mov_b32 v9, s22"] - body_lines += [f"v_cmp_class_f64_e64 s20, {src}, {mask}"] - else: body_lines.append(f"{op}_e64 s20, {src}, {mask}") - body_lines.append("v_cndmask_b32_e64 v8, 0, 1, s20") - else: - cond = op.split("_")[2] - source_index = 2 if op.startswith("v_cmpx") else 0 - s0 = maybe_word_modifier(rng, gen_source(rng, source_index, allow_literal, bus)) - s1 = maybe_word_modifier(rng, gen_source(rng, 3 if op.startswith("v_cmpx") else 1, allow_literal, bus)) - if op.startswith("v_cmpx"): - body_lines += ["s_mov_b32 s10, exec_lo", f"{op}_e64 {s0}, {s1}", "s_mov_b32 s22, exec_lo", "s_mov_b32 exec_lo, s10", "v_mov_b32 v9, s22"] - body_lines += [f"v_cmp_{cond}_f64_e64 s20, {s0}, {s1}", "v_cndmask_b32_e64 v8, 0, 1, s20"] - return setup_lines, body_lines, vg, sg - - -def output_kind(lines): - low, high = "int", "int" - for line in lines: - s = line.strip() - if s.startswith(("v_cndmask_b32_e64 v8,", "v_mov_b32 v8,")): low = "int" - elif s.startswith("v_mov_b32 v9,"): high = "int" - elif s.startswith("v_cvt_f32_f64 v8,"): low = "f32" - elif s.startswith("v_frexp_exp_i32_f64 v8,"): low = "int" - elif any(s.startswith(op + " v[8:9],") for op in (*ROUND, "v_add_f64", "v_rcp_f64", "v_rsq_f64", "v_sqrt_f64", "v_div_fixup_f64", "v_div_fmas_f64", "v_frexp_mant_f64")): - low, high = "f64", "f64" - return low, high - - -def equivalent(a, b, kind="int"): - if len(a) != len(b): return False - if kind == "f64": - x, y = words_to_bits(a[0], a[1]), words_to_bits(b[0], b[1]) - if x != y and not (is_nan(x) and is_nan(y)): return False - return a[2:] == b[2:] - if kind == "f32": - x, y = a[0], b[0] - if x != y and not (((x & 0x7F800000) == 0x7F800000 and x & 0x7FFFFF) and - ((y & 0x7F800000) == 0x7F800000 and y & 0x7FFFFF)): return False - return a[1:] == b[1:] - if isinstance(kind, tuple): - low, high = kind - if low == "f64": - x, y = words_to_bits(a[0], a[1]), words_to_bits(b[0], b[1]) - if x != y and not (is_nan(x) and is_nan(y)): return False - elif low == "f32": - x, y = a[0], b[0] - if x != y and not (((x & 0x7F800000) == 0x7F800000 and x & 0x7FFFFF) and - ((y & 0x7F800000) == 0x7F800000 and y & 0x7FFFFF)): return False - elif a[0] != b[0]: return False - if high == "f64" and low != "f64": - x, y = words_to_bits(a[0], a[1]), words_to_bits(b[0], b[1]) - if not (is_nan(x) and is_nan(y)) and a[1] != b[1]: return False - elif high != "f64" and a[1] != b[1]: return False - return a[2:] == b[2:] - return a == b - - -def run_one(lines, name, tmp, oracle="translator", gpu=None, include_known=False, hw_words=None): - """Compare one program with the reference. ``gpu`` is the prepared Vulkan context for --oracle gpu, or the open - hw_oracle for --oracle hw (whose result may be passed in as ``hw_words``: four words or a skip reason).""" - if oracle == "hw": - # The hardware runs every form natively, so the translator-only exclusions do not apply: compare it with the - # whole reference, the known cases included. - include_known = True - if not include_known: - for line in lines: - if " mul:" in line or " div:" in line: - return "skip", f"KNOWN_DIVERGENCE f64-omod: {KNOWN_DIVERGENCES['f64-omod']}", None, None - if " clamp" in line and "f64" in line: - return "skip", f"KNOWN_DIVERGENCE fclamp-nan-zero: {KNOWN_DIVERGENCES['fclamp-nan-zero']}", None, None - if line.split() and line.split()[0] in ("v_add_f64", "v_cvt_f32_f64", "v_rcp_f64", "v_rsq_f64", "v_sqrt_f64", "v_div_fmas_f64") and ("|" in line or "-v[" in line or "-s[" in line): - return "skip", f"KNOWN_DIVERGENCE double-neg-abs: {KNOWN_DIVERGENCES['double-neg-abs']}", None, None - # The hardware kernel is one lane, so EXEC is 1 there and a program that reads exec_lo back sees 1. - try: expected = ref_program(lines, include_known, 1 if oracle == "hw" else M32) - except SkipCase as exc: return "skip", str(exc), None, None - except (ArithmeticError, IndexError, KeyError, ValueError) as exc: - return "skip", f"reference limitation: {type(exc).__name__}: {exc}", None, None - if oracle == "gpu" and any(line.lstrip().startswith(("v_rsq_f64 ", "v_sqrt_f64 ")) for line in lines): - return "skip", "GLSL.std.450 InverseSqrt/Sqrt double-precision result precision is implementation-defined", expected, None - if oracle == "hw": - if any(line.lstrip().startswith(("v_rcp_f64 ", "v_rsq_f64 ", "v_sqrt_f64 ")) for line in lines): - return "skip", ("native v_rcp_f64/v_rsq_f64/v_sqrt_f64 are approximations (about 26 bits, PROC-216) and " - "the reference is exact, so their result is not judged"), expected, None - actual = hw_words if hw_words is not None else gpu.run([hw_kernel(lines)])[0] - if isinstance(actual, str): return "skip", f"hardware: {actual}", expected, None - actual = [int(x) & M32 for x in actual] - return ("match", "", expected, actual) if equivalent(expected, actual, output_kind(lines)) else ("mismatch", "word comparison", expected, actual) - try: actual = run_gpu(lines, name, tmp, gpu) if oracle == "gpu" else translate(lines, name, tmp) - except (rdna2spirv.Unsupported, UnsupportedConstruct, SkipCase) as exc: return "skip", f"{type(exc).__name__}: {exc}", expected, None - except (IndexError, KeyError, ValueError, OverflowError) as exc: return "skip", f"translator/interpreter limitation: {type(exc).__name__}: {exc}", expected, None - return ("match", "", expected, actual) if equivalent(expected, actual, output_kind(lines)) else ("mismatch", "word comparison", expected, actual) - - -def shrink(lines, expected, oracle="translator", gpu=None, gpu_ctx=None, tmpdir=None, include_known=False): - """Greedy instruction deletion minimizer, retaining only instructions needed for the mismatch.""" - current = list(lines) - def reduce(tmp, context): - i = 0 - while i < len(current): - trial = current[:i] + current[i + 1:] - try: - status, _, _, _ = run_one(trial, "ps_f64_shrink", tmp, oracle, context, include_known) - if status == "mismatch": - current[:] = trial - continue - except GPUUnavailable: - raise - except Exception: - pass - i += 1 - return current - if tmpdir is not None: - context = gpu_ctx if gpu_ctx is not None else prepare_gpu(gpu, tmpdir) if oracle == "gpu" else None - return reduce(tmpdir, context) - with tempfile.TemporaryDirectory(prefix="f64-shrink-") as tmp: - context = gpu_ctx if gpu_ctx is not None else prepare_gpu(gpu, tmp) if oracle == "gpu" else None - return reduce(tmp, context) - - -def run_batch(ops, programs, seed, max_ops=1, sweep=True, allow_literal=True, known=False, all_failures=False, - oracle="translator", gpu=None, hw=None): - counts = Counter(); skips = Counter(); failures = [] - rng = random.Random(seed) - sequence = [(op, True, None) for op in ops] if sweep else [] - sequence += [(rng.choice(ops), False, None) for _ in range(programs)] - if known: - sequence += [("v_div_fixup_f64" if label == "div-fixup-nan-s0" else "v_add_f64", True, label) - for label in KNOWN_DIVERGENCES] - cases = [] - for idx, (op, is_sweep, known_case) in enumerate(sequence): - setup_lines, body_lines, _, _ = make_case(rng, op, allow_literal, known_case) - lines = setup_lines + body_lines - if not is_sweep and not known_case: - n_ops = rng.randint(1, max_ops) - for _ in range(n_ops - 1): - _, extra_body, _, _ = make_case(rng, rng.choice(ops), allow_literal) - lines.extend(extra_body) - cases.append((idx, lines, known_case)) - # One launch for the whole campaign; a failing program is re-run alone while it is shrunk. - hw_results = hw.run([hw_kernel(lines) for _, lines, _ in cases]) if oracle == "hw" else None - with tempfile.TemporaryDirectory(prefix="f64-diff-") as tmp: - gpu_ctx = prepare_gpu(gpu, tmp) if oracle == "gpu" else hw if oracle == "hw" else None - for idx, lines, known_case in cases: - status, reason, want, got = run_one(lines, f"ps_f64_{idx:05d}", tmp, oracle, gpu_ctx, - include_known=bool(known_case), - hw_words=hw_results[idx] if hw_results is not None else None) - if status == "skip": skips[reason] += 1 - else: counts[status] += 1 - if status == "mismatch": - reduced = shrink(lines, want, oracle, gpu, gpu_ctx, tmp, bool(known_case)) - failures.append((reduced, want, got, reason)) - if status == "mismatch" and not all_failures: break - return counts, skips, failures - - -def self_test(): - tests = [round_fraction(Fraction(1, 3) + Fraction(2, 3)) == 0x3FF0000000000000, - round_fraction(Fraction(1, 1 << 1075)) == 0, - add_bits(0x3FF0000000000000, 0x3CA0000000000000) == 0x3FF0000000000000, - class_index(0x7FF0000000000001) == 0, - class_index(0xFFF8000000000000) == 1, - compare("nlt", 0x7FF8000000000000, 0) == 1, - round_fraction(Fraction(1) + Fraction(1, 1 << 53), 1) == 0x3FF0000000000001, - round_fraction(-(Fraction(1) + Fraction(1, 1 << 53)), 2) == 0xBFF0000000000001, - round_fraction(Fraction(1 << 1024), 3) == 0x7FEFFFFFFFFFFFFF, - len(BASE) == 47] - for i, ok in enumerate(tests, 1): print(f"{'ok' if ok else 'FAIL'} reference invariant {i}") - # A planted output error must be reported and remain observable after shrinking. - lines = ["v_mov_b32 v12, 0x00000000", "v_mov_b32 v13, 0x3ff80000", - "v_trunc_f64 v[8:9], v[12:13]"] - original = translate - def planted_bug(listing, name, tmp): - out = original(listing, name, tmp) - if any(line.startswith("v_trunc_f64 ") for line in listing): out[0] ^= 1 - return out - try: - globals()["translate"] = planted_bug - with tempfile.TemporaryDirectory(prefix="f64-self-test-") as tmp: - status, _, expected, actual = run_one(lines, "ps_f64_self_test_negative", tmp) - reduced = shrink(lines, expected) - caught = (status == "mismatch" and not equivalent(expected, actual, output_kind(lines)) and len(reduced) == 1 - and reduced[0].startswith("v_trunc_f64 ")) - print(f"{'ok' if caught else 'FAIL'} planted translator mismatch is caught and shrinkable") - finally: - globals()["translate"] = original - return all(tests) and caught - - -def main(argv=None): - ap = argparse.ArgumentParser(description=__doc__.splitlines()[0]) - ap.add_argument("--sweep", dest="sweep", action="store_true", default=True) - ap.add_argument("--no-sweep", dest="sweep", action="store_false") - ap.add_argument("--programs", type=int, default=300) - ap.add_argument("--seed", type=int, default=1) - ap.add_argument("--max-ops", type=int, default=1) - ap.add_argument("--ops") - ap.add_argument("--list-ops", action="store_true") - ap.add_argument("--no-literals", action="store_true") - ap.add_argument("--known", action="store_true") - ap.add_argument("--self-test", action="store_true") - ap.add_argument("--all-failures", action="store_true") - ap.add_argument("--oracle", choices=("translator", "gpu", "hw"), default="translator", - help="translator (default), Vulkan GPU via vk_harness, or AMD hardware oracle") - ap.add_argument("--exe", help="vk_harness executable for --oracle gpu") - ap.add_argument("--hw-arch", help="GPU architecture hw_oracle assembles for (default: detected)") - args = ap.parse_args(argv) - if args.programs < 0 or args.max_ops < 1: print("programs must be nonnegative and max-ops positive", file=sys.stderr); return 2 - ops = [x.strip() for x in args.ops.split(",")] if args.ops else list(BASE) - bad = sorted(set(ops) - set(BASE)) - if bad: print(f"unknown opcode(s): {','.join(bad)}", file=sys.stderr); return 2 - if args.list_ops: - for op in BASE: print(op) - print("Excluded (not translated by main): v_mul_f64, v_min_f64, v_max_f64, v_fract_f64, v_cvt_f64_f32, v_ldexp_f64, v_mad_f64, v_cvt_i32_f64, v_cvt_u32_f64, v_div_scale_f64") - return 0 - if args.self_test: return 0 if self_test() else 1 - gpu = hw = None - if args.oracle == "hw": - try: hw = open_hw_oracle(args.hw_arch) - except HWUnavailable as exc: - print(f"hardware oracle unavailable: {exc}", file=sys.stderr); return 77 - print(f"hardware oracle: {getattr(hw, 'device', 'AMD GPU')}") - if args.oracle == "gpu": - ext = ".exe" if os.name == "nt" else "" - gpu = args.exe or os.path.join(ROOT, "runtime", "build", "vk_harness" + ext) - try: - counts, skips, failures = run_batch(ops, args.programs, args.seed, args.max_ops, args.sweep, - not args.no_literals, args.known, args.all_failures, - args.oracle, gpu, hw) - except GPUUnavailable as exc: - print(f"GPU oracle unavailable: {exc}", file=sys.stderr); return 77 - except (HarnessError, RuntimeError) as exc: - print(f"harness error: {exc}", file=sys.stderr); return 2 - finally: - if hw is not None: hw.close() - total = sum(counts.values()) + sum(skips.values()) - print(f"{args.oracle}: {counts['match']} match, {counts['mismatch']} mismatch; {total} total, {dict(skips)} skips") - if failures: - for lines, want, got, reason in failures: - print(f"MISMATCH: {reason}\nminimal program:") - print("\n".join(" " + x for x in lines)) - if want is not None and got is not None: - print("expected: " + " ".join(f"{x:08x}" for x in want)) - print("actual: " + " ".join(f"{x:08x}" for x in got)) - return 1 - return 0 - - -if __name__ == "__main__": - try: # a redirected stdout is strict ANSI code page under -I; write '?' for what it cannot encode - sys.stdout.reconfigure(errors="replace") - except (AttributeError, ValueError, OSError): - pass - sys.exit(main()) diff --git a/tools/f64_omod_probe.py b/tools/f64_omod_probe.py deleted file mode 100644 index 1180d33ba..000000000 --- a/tools/f64_omod_probe.py +++ /dev/null @@ -1,340 +0,0 @@ -r"""Measure the VOP3 output modifiers of the binary64 conversion, frexp and div_fixup VALU ops across MODE settings. Standard library only. - -docs/design.md records for the f32 VALU ops that `mul:2`/`mul:4`/`div:2` are applied only when MODE.IEEE = 0 and the -output denormals of the destination precision are flushed, and `clamp` in every mode. Running this probe natively on -RDNA2 (gfx1036) through tools/hw_oracle extends that gate to the remaining binary64 and 16-bit results: -`v_cvt_f64_i32`, `v_cvt_f64_u32`, `v_frexp_mant_f64`, `v_div_fixup_f64` and `v_div_fixup_f16` ignore the scaling -while `denorm_mode_16_64 = 3` — which is the mode the translator assumes — and apply it only with IEEE = 0 and -`denorm_mode_16_64 = 0`, while `clamp` still applies in every mode. `v_cvt_f32_f64` writes an f32 result and follows -the f32 gate: it scales whenever `denorm32 = 0`, including under `denorm_mode_16_64 = 3`, and stops scaling when -`denorm32 = 3`. The gate is therefore per result precision, not per instruction family. wave32 and wave64 agree on -every word written; for the 16-bit form only the low half of the destination is written, as the ISA defines. - -Every expectation is derived from the plain (no-modifier) result measured in the same mode on the same device, so the -probe compares the effect of the modifier and not the semantics of the operation. - -Usage: - python -I tools/f64_omod_probe.py [--waves 32,64] [--modes ...] [--json out.json] - python -I tools/f64_omod_probe.py --self-test - -Exit 0 when every measured result matches the model (with wave32 and wave64 agreeing bit-for-bit), 1 on a model -mismatch or a wave32/wave64 difference, 2 on a harness or CLI error, and 77 when the hardware oracle is unavailable or -the GPU is not GFX10. Nothing here reads game files. -""" -import argparse -import json -import math -import os -import struct -import sys - -HERE = os.path.dirname(os.path.abspath(__file__)) -sys.dont_write_bytecode = True -if HERE not in sys.path: - sys.path.insert(0, HERE) - -MODES = { - # The mode the translator emits and the game runs with: scaling ignored, clamp applied. - "game_i0_d3": {"round16_64": 0, "denorm16_64": 3, "denorm32": 0, "dx10_clamp": 1, "ieee": 0}, - # 16/64-bit denormals flushed, IEEE off: the scaling applies to the f16 and binary64 results. - "i0_d0": {"round16_64": 0, "denorm16_64": 0, "denorm32": 0, "dx10_clamp": 1, "ieee": 0}, - # IEEE on: the scaling is ignored in both denormal settings. - "i1_d3": {"round16_64": 0, "denorm16_64": 3, "denorm32": 0, "dx10_clamp": 1, "ieee": 1}, - "i1_d0": {"round16_64": 0, "denorm16_64": 0, "denorm32": 0, "dx10_clamp": 1, "ieee": 1}, - # f32 denormals kept while 16/64-bit ones are flushed: the discriminator for the f32 result of v_cvt_f32_f64. - "i0_d3_f32keep": {"round16_64": 0, "denorm16_64": 3, "denorm32": 3, "dx10_clamp": 1, "ieee": 0}, -} - -MODS = ("", "mul:2", "mul:4", "div:2", "clamp") -SCALE = {"mul:2": 2.0, "mul:4": 4.0, "div:2": 0.5} - -INT_SOURCES = [("0", 0x00000000), ("1", 0x00000001), ("-1", 0xFFFFFFFF), ("2^24+1", 0x01000001), - ("2^31-1", 0x7FFFFFFF), ("-2^31", 0x80000000)] -F64_TO_F32 = [("1.0", 1.0), ("2.0", 2.0), ("1.5", 1.5), ("3.25", 3.25), ("-1.0", -1.0), - ("2^-1074 min sub", 2.0 ** -1074), ("2^-1050 sub", 2.0 ** -1050), ("2^-130", 2.0 ** -130)] -FREXP_INPUTS = [("3.0", 3.0), ("1.0", 1.0), ("0.5", 0.5), ("-1.75", -1.75), ("8.0", 8.0), - ("2^-1074 min sub", 2.0 ** -1074), ("1.5*2^-1050 sub", 1.5 * 2.0 ** -1050)] - - -def _f64_bits(x: float) -> int: - return struct.unpack(" int: - try: - return struct.unpack("> 32:#010x}") - return lines - - -# (op, e64 form, result kind, [(case name, setup lines)]) -OPS = [ - ("v_cvt_f64_i32", "v_cvt_f64_i32_e64 v[8:9], v1", "f64", - [(name, [f"v_mov_b32_e32 v1, {bits:#010x}"]) for name, bits in INT_SOURCES]), - ("v_cvt_f64_u32", "v_cvt_f64_u32_e64 v[8:9], v1", "f64", - [(name, [f"v_mov_b32_e32 v1, {bits:#010x}"]) for name, bits in INT_SOURCES]), - ("v_cvt_f32_f64", "v_cvt_f32_f64_e64 v8, v[1:2]", "f32", - [(name, load([value])) for name, value in F64_TO_F32]), - ("v_frexp_mant_f64", "v_frexp_mant_f64_e64 v[8:9], v[1:2]", "f64", - [(name, load([value])) for name, value in FREXP_INPUTS]), - ("v_div_fixup_f64", "v_div_fixup_f64_e64 v[8:9], v[1:2], v[3:4], v[5:6]", "f64", - [(name, load(values)) for name, values in - [("q=2 d=1.5 n=3", (2.0, 1.5, 3.0)), ("q=-2 d=1.5 n=3", (-2.0, 1.5, 3.0)), - ("q=2 d=-1.5 n=3", (2.0, -1.5, 3.0)), ("q=0.75 d=2 n=1.5", (0.75, 2.0, 1.5))]]), - ("v_div_fixup_f16", "v_div_fixup_f16_e64 v8, v1, v2, v3", "f16", - [(name, [f"v_mov_b32_e32 v1, {h:#010x}", f"v_mov_b32_e32 v2, {d:#010x}", f"v_mov_b32_e32 v3, {n:#010x}"]) - for name, h, d, n in [("q=2h d=1.5h n=3h", _f16_bits(2.0), _f16_bits(1.5), _f16_bits(3.0)), - ("q=-2h d=1.5h n=3h", _f16_bits(-2.0), _f16_bits(1.5), _f16_bits(3.0)), - ("q=0.75h d=2h n=1.5h", _f16_bits(0.75), _f16_bits(2.0), _f16_bits(1.5)), - ("q=1h d=1h n=1h", _f16_bits(1.0), _f16_bits(1.0), _f16_bits(1.0))]]), -] - - -def word_count(kind: str) -> int: - return 2 if kind == "f64" else 1 - - -def build_kernels(asm, modes, waves): - kernels, meta = [], [] - for wave in waves: - for mode_name in modes: - for op, form, kind, cases in OPS: - lines, words = [], 0 - for _, setup in cases: - for mod in MODS: - lines.extend(setup) - lines.append(form + (f" {mod}" if mod else "")) - lines.append(f"v_mov_b32_e32 v7, {words * 4}") - lines.append("global_store_dword v7, v8, s[2:3]") - words += 1 - if kind == "f64": - lines.append("v_lshrrev_b64 v[10:11], 32, v[8:9]") - lines.append(f"v_mov_b32_e32 v7, {words * 4}") - lines.append("global_store_dword v7, v10, s[2:3]") - words += 1 - lines.append("s_waitcnt vmcnt(0)") - lines.append("s_endpgm") - kernels.append(asm.Kernel(lines, wave=wave, threads=1, words=words, raw=True, - mode=dict(MODES[mode_name]))) - meta.append((wave, mode_name, op, kind, [name for name, _ in cases])) - return kernels, meta - - -def scalar_value(lo, hi, kind): - if kind == "f64": - return struct.unpack("> 32) & 0xFFFFFFFF) - if kind == "f32": - return (struct.unpack(" int: - ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) - ap.add_argument("--modes", default=",".join(MODES)) - ap.add_argument("--waves", default="32,64") - ap.add_argument("--json", help="write the measurement report here") - ap.add_argument("--hw-arch") - ap.add_argument("--self-test", action="store_true") - args = ap.parse_args(argv) - if args.self_test: - return self_test() - - modes = [m.strip() for m in args.modes.split(",") if m.strip()] - wave_tokens = [w.strip() for w in args.waves.split(",") if w.strip()] - bad = [m for m in modes if m not in MODES] + [w for w in wave_tokens if w not in ("32", "64")] - if bad or not modes or not wave_tokens: - ap.error("unknown or empty --modes/--waves entry: " + ", ".join(bad or ["--modes/--waves"])) - waves = [int(w) for w in wave_tokens] - if args.json and os.path.isdir(args.json): - ap.error(f"--json {args.json} is a folder, not a file") - - from hw_oracle import asm, runner - - try: - oracle = runner.open_oracle(arch=args.hw_arch) - except runner.Unavailable as exc: - print(f"hardware oracle unavailable: {exc}") - return 77 - try: - if asm.family(oracle.arch) != "gfx10": - print(f"hardware oracle unavailable: {oracle.arch} is not GFX10") - return 77 - print(f"hardware oracle: {oracle.device} ({oracle.arch})") - kernels, meta = build_kernels(asm, modes, waves) - summary = evaluate(modes, waves, meta, oracle.run(kernels)) - except (RuntimeError, KeyError, TypeError) as exc: - print(f"harness error: {exc}") - return 2 - finally: - oracle.close() - - if args.json and not write_report(args.json, { - "device": str(oracle.device), "arch": oracle.arch, "modes": modes, "waves": waves, - "mods": list(MODS), "ops": [op for op, *_ in OPS], **summary}): - return 2 - - print(f"{summary['total_cases']} cases across {len(modes)} mode(s) x {len(MODS)} modifier forms " - f"x {len(waves)} wave(s): scaling_gated_on={summary['scaling_gated_on']}, " - f"scaling_gated_off={summary['scaling_gated_off']}, " - f"scaling_changed_value={summary['scaling_changed_value']}, " - f"clamp_changed_value={summary['clamp_changed_value']}, " - f"mismatches={summary['mismatches']}, wave_diffs={summary['wave_diffs']}") - for m in summary["first_mismatches"]: - print(f" MISMATCH {m['mode']} {m['op']} {m['case']} {m['mod']}: plain {m['plain']} " - f"got {m['got']} want {m['want']}") - for d in summary["first_wave_diffs"]: - print(f" WAVE DIFF {d['mode']} {d['op']} {d['mod']!r} wave{d['wave']}") - return 1 if (summary["mismatches"] or summary["wave_diffs"]) else 0 - - -if __name__ == "__main__": - try: - sys.stdout.reconfigure(errors="replace") - except (AttributeError, ValueError, OSError): - pass - sys.exit(main()) diff --git a/tools/feature_scan.py b/tools/feature_scan.py deleted file mode 100644 index 21385f63f..000000000 --- a/tools/feature_scan.py +++ /dev/null @@ -1,666 +0,0 @@ -"""Scan the shader corpus for features the D3D12 -> Vulkan layer may need (docs/d3d12_vulkan.md §8.2 #10, #14, #16). - - python -I tools/feature_scan.py /shaders [--out feature_scan.json] - -Reads what the shaders stage of make_game.py leaves in /shaders, and prints counts only: - -- dxbc/index.json and the .dxbc files: the DXIL program kind of every shader (hull, domain and amplification - stages would show up here), the SFI0 feature flags (D3D_SHADER_REQUIRES_* from the Windows SDK's d3d12shader.h, - among them WAVE_MMA and SHADING_RATE), and the output-signature (OSG1) stream index of every element: stream - output to a stream other than 0 needs a geometry shader writing that stream. The PSV0 resource bindings: structured - UAVs with a counter (append/consume buffers) and typed buffer SRVs/UAVs (#16). -- dxbc/disasm/*.s (shader_disasm.py): the native RDNA2 instructions that mean wave MMA (v_mfma*, v_wmma*, - v_smfmac*) or GDS / ordered-count traffic (the hardware path NGG stream output uses on RDNA2). Typed buffer - accesses (#16): the MTBUF instruction formats, and for MUBUF where V# word 3 (the format) comes from, each checked - against the translator's typed-buffer table (rdna2spirv.Gen.FORMATS). -- spirv/index.json (rdna2spirv.py): uses_code_base per stage. A graphics PSO can only need two code bases - (§5.2) if two of its stages use one; this gives the per-stage counts. Which stages are paired in one PSO is in - the executable, not in shaders.rpf. - -InnerCoverage metadata is cross-tabulated by stage: SFI0 set/clear/unknown versus ISG1 -present/absent/unknown. Unknown includes missing or truncated parts; unreadable containers -remain in the existing unreadable count. DXIL permits InnerCoverage outside the signature, -so ISG1 absence is not evidence of non-use. These counts do not identify an Xbox input VGPR. - -Standard library only. Nothing from the game is printed or written: names, code and data stay in the work folder. -Usage: `python -I tools/feature_scan.py --help` lists the options. -""" -import argparse -import json -import os -import re -import struct -import sys -from collections import Counter, defaultdict - -sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) -from shader_carve import parts as dxbc_part_ranges # noqa: E402 - -# d3d12shader.h (Windows SDK 10.0.26100.0), D3D_SHADER_REQUIRES_*: the SFI0 part is this 64-bit mask. -SFI0_FLAGS = { - 0x1: "DOUBLES", 0x2: "EARLY_DEPTH_STENCIL", 0x4: "UAVS_AT_EVERY_STAGE", 0x8: "64_UAVS", - 0x10: "MINIMUM_PRECISION", 0x20: "11_1_DOUBLE_EXTENSIONS", 0x40: "11_1_SHADER_EXTENSIONS", - 0x80: "LEVEL_9_COMPARISON_FILTERING", 0x100: "TILED_RESOURCES", 0x200: "STENCIL_REF", 0x400: "INNER_COVERAGE", - 0x800: "TYPED_UAV_LOAD_ADDITIONAL_FORMATS", 0x1000: "ROVS", - 0x2000: "VIEWPORT_AND_RT_ARRAY_INDEX_FROM_ANY_SHADER_FEEDING_RASTERIZER", 0x4000: "WAVE_OPS", - 0x8000: "INT64_OPS", 0x10000: "VIEW_ID", 0x20000: "BARYCENTRICS", 0x40000: "NATIVE_16BIT_OPS", - 0x80000: "SHADING_RATE", 0x100000: "RAYTRACING_TIER_1_1", 0x200000: "SAMPLER_FEEDBACK", - 0x400000: "ATOMIC_INT64_ON_TYPED_RESOURCE", 0x800000: "ATOMIC_INT64_ON_GROUP_SHARED", - 0x1000000: "DERIVATIVES_IN_MESH_AND_AMPLIFICATION_SHADERS", 0x2000000: "RESOURCE_DESCRIPTOR_HEAP_INDEXING", - 0x4000000: "SAMPLER_DESCRIPTOR_HEAP_INDEXING", 0x8000000: "WAVE_MMA", - 0x10000000: "ATOMIC_INT64_ON_DESCRIPTOR_HEAP_RESOURCE", 0x20000000: "ADVANCED_TEXTURE_OPS", - 0x40000000: "WRITEABLE_MSAA_TEXTURES", 0x80000000: "SAMPLE_CMP_GRADIENT_OR_BIAS", - 0x100000000: "EXTENDED_COMMAND_INFO", -} -# The ones §8.2 #10 asks about; always printed, also when zero. -WATCHED = ("WAVE_MMA", "SHADING_RATE", "VIEW_ID", "ROVS", "STENCIL_REF", "INNER_COVERAGE", "SAMPLER_FEEDBACK", - "RAYTRACING_TIER_1_1") -ALL_STAGES = ("vs", "ps", "gs", "hs", "ds", "cs", "ms", "as", "lib") - -MMA = re.compile(r"^\s*(v_mfma\w*|v_wmma\w*|v_smfmac\w*)\b") -# Ordered count, GWS and the GS-register adds are the GDS-side instructions NGG stream output relies on. ds_append / -# ds_consume are included as the other counter-style DS ops (LDS unless they carry `gds`, which GDS below catches). -ORDERED = re.compile(r"^\s*(ds_ordered_count|ds_gws_\w+|ds_append|ds_consume|ds_add_gs_reg\w*|ds_sub_gs_reg\w*)\b") -GDS = re.compile(r"^\s*ds_\w+\b[^;]*\bgds\b") -REG_SINGLE = re.compile(r"^([sv])(\d+)$") -REG_RANGE = re.compile(r"^([sv])\[(\d+):(\d+)\]$") -CONST_MOV_OPS = frozenset(("s_mov_b32", "s_mov_b32_e32", "v_mov_b32", "v_mov_b32_e32", "v_mov_b32_e64")) - - -def parts(d: bytes) -> dict: - """DXBC part fourcc -> payload.""" - if not d.startswith(b"DXBC"): - raise ValueError("missing DXBC magic") - return {tag: d[off:off + size] for tag, (off, size) in dxbc_part_ranges(d).items()} - - -def signature_offsets(sig: bytes) -> range: - """Offsets of the 32-byte elements in a complete ISG1 or OSG1 table.""" - if len(sig) < 8: - raise ValueError("truncated signature header") - count, first = struct.unpack_from(" len(sig): - raise ValueError("invalid signature table") - return range(first, end, 32) - - -def streams(sig: bytes) -> set: - """Stream indices from a complete signature, or an empty set for an unusable table.""" - try: - offsets = signature_offsets(sig) - except ValueError: - return set() - return {struct.unpack_from(" list: - """(resource type, resource kind) of every PSV0 resource binding record. - - The part is: u32 runtime-info size, the runtime info, u32 resource count and, when that is not 0, u32 record - size and the records. A record is PSVResourceBindInfo0 (type, space, lower and upper bound: 16 bytes) or - PSVResourceBindInfo1 (plus resource kind and flags: 24 bytes); a 16-byte record has kind "?". Raises ValueError - when the table does not fit in the part.""" - if len(psv) < 4: - raise ValueError("PSV0 shorter than its runtime-info size") - pos = 4 + struct.unpack_from(" len(psv): - raise ValueError("PSV0 truncated before the resource count") - count = struct.unpack_from(" len(psv): - raise ValueError("PSV0 truncated before the record size") - size = struct.unpack_from(" len(psv): - raise ValueError("PSV0 resource records do not fit") - out = [] - for i in range(count): - at = pos + i * size - t = struct.unpack_from("= 20 else None - out.append((PSV_RES_TYPES[t] if t < len(PSV_RES_TYPES) else f"type{t}", - "?" if k is None else PSV_RES_KINDS[k] if k < len(PSV_RES_KINDS) else f"kind{k}")) - return out - - -# §8.2 #16: append/consume buffers are the structured UAVs with a counter; typed buffers are typed SRVs/UAVs of -# kind TypedBuffer (a typed SRV/UAV of a texture kind is an image, not a buffer). -WATCHED_BINDINGS = ("uav_with_counter", "typed_buffer_srv", "typed_buffer_uav") - - -def watched_binding(res_type: str, kind: str): - if res_type == "UAVStructuredWithCounter": - return "uav_with_counter" - if kind == "TypedBuffer" and res_type in ("SRVTyped", "UAVTyped"): - return "typed_buffer_srv" if res_type == "SRVTyped" else "typed_buffer_uav" - return None - - -def stage_name(row: dict) -> str: - stage = row.get("stage") - return stage if isinstance(stage, str) and stage else "?" - - -def inner_coverage_metadata(p: dict) -> tuple[str, str]: - """Independent SFI0/ISG1 observations, not an Xbox VGPR mapping. - - DXC DxilConstants.h defines ShaderFeatureInfo_InnerCoverage as 0x400; - DxilContainer.h defines the signature system value as 70. DXIL.rst marks - InnerCoverage NotInSig: an absent signature entry does not disprove use. - Missing/truncated metadata must not become evidence of absence. - """ - sfi = p.get("SFI0", b"") - feature = "unknown" - if len(sfi) >= 8: - feature = "set" if struct.unpack_from("= 8: - count, first = struct.unpack_from(" dict: - stages = Counter() - flags = defaultdict(Counter) # flag -> stage -> shaders - inner = defaultdict(Counter) # stage -> independent metadata observations, counts only - gs_streams = Counter() - non_zero_stream = Counter() # stage -> shaders with an output element on a stream other than 0 - records, shaders_with = Counter(), Counter() # PSV0: (type, kind) -> records; watched class -> shaders - psv_bad = 0 - missing = 0 - for e in index: - if not isinstance(e, dict): - missing += 1 - continue - stage = stage_name(e) - stages[stage] += 1 - filename = e.get("file") - if not isinstance(filename, str) or not filename: - missing += 1 - continue - path = os.path.join(dxbc_dir, filename) - try: - with open(path, "rb") as f: - p = parts(f.read()) - except (OSError, ValueError): - missing += 1 - continue - feature, signature = inner_coverage_metadata(p) - inner[stage][f"sfi0_{feature}__isg1_{signature}"] += 1 - if len(p.get("SFI0", b"")) >= 8: - mask = struct.unpack_from(" bool: - """s_getpc_b64 not followed within three instructions by s_setpc_b64: the address is used to read data - embedded in the code (a code base), not for a far branch (getpc; add/sub; addc/subb; setpc).""" - return any(op == "s_getpc_b64" and "s_setpc_b64" not in ops[i + 1:i + 4] for i, op in enumerate(ops)) - - -def _parse_imm(tok: str): - """Parse a decimal or 0x-hex integer immediate, or return None.""" - try: - return int(tok, 0) & 0xFFFFFFFF - except ValueError: - return None - - -def _written_regs(tok: str) -> list: - """Return individual sN/vN register names covered by a destination operand token.""" - m = REG_SINGLE.match(tok) - if m: - return [tok] - m = REG_RANGE.match(tok) - if m: - prefix, lo, hi = m.group(1), int(m.group(2)), int(m.group(3)) - if lo <= hi <= lo + 32: - return [f"{prefix}{i}" for i in range(lo, hi + 1)] - return [] - - -def _has_secondary_sgpr_destination(op: str) -> bool: - return op.startswith("v_") and ("_co_" in op or op.startswith("v_div_scale")) - - -def _update_const_regs(const_reg: dict, op: str, operands: list) -> None: - """Track single-register immediate loads and invalidate any destination register written.""" - if not operands: - return - dst = operands[0].split()[0] if operands[0].split() else "" - if op in CONST_MOV_OPS and len(operands) >= 2 and REG_SINGLE.match(dst): - src_tok = operands[1].split()[0] if operands[1].split() else "" - imm = _parse_imm(src_tok) - if imm is not None: - const_reg[dst] = imm - return - destination_count = 2 if _has_secondary_sgpr_destination(op) else 1 - for operand in operands[:destination_count]: - tokens = operand.split() - if tokens: - for register in _written_regs(tokens[0]): - const_reg.pop(register, None) - - -def scan_disasm(disasm_dir: str, stage_of: dict) -> dict: - mma, ordered, gds, code_data = Counter(), Counter(), Counter(), Counter() - mma_ops, ordered_ops = Counter(), Counter() - vperm_shaders = Counter() - vperm_insns = vperm_imm = vperm_creg = vperm_unres = 0 - vperm_sext_shaders = vperm_sext_insns = 0 - vperm_classes = {"0_7": 0, "8_11": 0, "12": 0, "13_plus": 0} - files = 0 - for fn in sorted(os.listdir(disasm_dir)): - if not fn.endswith(".s"): - continue - files += 1 - stage = stage_of.get(fn[:-2], "?") - seen_mma = seen_ord = seen_gds = seen_vperm = seen_vperm_sext = False - ops = [] - const_reg = {} - with open(os.path.join(disasm_dir, fn), encoding="utf-8", errors="replace") as f: - for line in f: - code = line.split(";", 1)[0].strip() - head = code.split(None, 1) - if head and not head[0].startswith("."): - op = head[0] - ops.append(op) - operands = [x.strip() for x in head[1].split(",")] if len(head) > 1 else [] - if op in ("v_perm_b32", "v_perm_b32_e64") and len(operands) >= 4: - seen_vperm = True - vperm_insns += 1 - sel_tok = operands[3].split()[0] if operands[3].split() else "" - sel_val = _parse_imm(sel_tok) - if sel_val is not None: - vperm_imm += 1 - elif sel_tok in const_reg: - sel_val = const_reg[sel_tok] - vperm_creg += 1 - else: - vperm_unres += 1 - if sel_val is not None: - has_sext = False - for shift in (0, 8, 16, 24): - b = (sel_val >> shift) & 0xFF - if b <= 7: - vperm_classes["0_7"] += 1 - elif b <= 11: - vperm_classes["8_11"] += 1 - has_sext = True - elif b == 12: - vperm_classes["12"] += 1 - else: - vperm_classes["13_plus"] += 1 - if has_sext: - vperm_sext_insns += 1 - seen_vperm_sext = True - _update_const_regs(const_reg, op, operands) - m = MMA.match(line) - if m: - mma_ops[m.group(1)] += 1 - seen_mma = True - m = ORDERED.match(line) - if m: - ordered_ops[m.group(1)] += 1 - seen_ord = True - if GDS.match(line): - seen_gds = True - mma[stage] += seen_mma - ordered[stage] += seen_ord - gds[stage] += seen_gds - vperm_shaders[stage] += seen_vperm - vperm_sext_shaders += int(seen_vperm_sext) - code_data[stage] += getpc_for_data(ops) - nz = lambda c: {k: v for k, v in c.items() if v} - return {"files": files, "wave_mma_shaders": nz(mma), "wave_mma_ops": dict(mma_ops), - "ordered_or_gws_shaders": nz(ordered), "ordered_or_gws_ops": dict(ordered_ops), "gds_shaders": nz(gds), - "getpc_for_data_shaders": nz(code_data), - "v_perm_b32": { - "shaders": nz(vperm_shaders), - "insns": vperm_insns, - "immediate": vperm_imm, - "const_reg": vperm_creg, - "unresolved": vperm_unres, - "sign_extend_8_11_shaders": vperm_sext_shaders, - "sign_extend_8_11_insns": vperm_sext_insns, - "selector_classes": vperm_classes, - }} - - -# Scalar ops whose first operand is a source, not an SGPR they write. -NO_SDST = ("s_cmp", "s_bitcmp", "s_cbranch", "s_branch", "s_waitcnt", "s_endpgm", "s_store", "s_buffer_store", - "s_scratch_store", "s_setpc", "s_sendmsg", "s_nop", "s_barrier", "s_dcache", "s_icache", "s_gl1_inv", - "s_setprio", "s_sleep", "s_ttrace", "s_set_gpr_idx", "s_setreg", "s_inst_prefetch", "s_round_mode", - "s_denorm_mode", "s_clause", "s_trap", "s_wakeup", "s_code_end", "s_atc_probe", "s_setkill", "s_incperflevel", - "s_decperflevel", "s_version") -BRANCH_OPS = frozenset(("s_branch", "s_cbranch_scc0", "s_cbranch_scc1", "s_cbranch_vccz", "s_cbranch_vccnz", - "s_cbranch_execz", "s_cbranch_execnz")) -TYPED_MUBUF = re.compile(r"^buffer_(load|store)_format_(d16_)?(x|xy|xyz|xyzw)$") -TYPED_MTBUF = re.compile(r"^tbuffer_(load|store)_format_(d16_)?(x|xy|xyz|xyzw)$") - - -def translator_formats(): - """(codes the translator models, GFX10 code -> format name), read from rdna2spirv itself so the scan follows the - table as it changes. Modelled: the typed-buffer table and INVALID (0), an unbound descriptor, which reads 0 on the - hardware and in the translator.""" - import rdna2spirv - return frozenset(rdna2spirv.Gen.FORMATS) | {0}, {c: n.replace("GFX10_FORMAT_", "") for c, n in - rdna2spirv.GFX10_FORMATS.items()} - - -def sgpr_writes(ins: dict) -> range: - """The SGPRs an instruction writes (as far as a V# word can be written: scalar destinations, v_readlane and - v_readfirstlane, the SGPR mask of a VOP3 compare and the carry of a VOP3b add).""" - op, args = ins["op"], ins["args"] - dst = None - if op.startswith("s_") and not op.startswith(NO_SDST): - dst = args[0] if args else None - elif op.startswith(("v_readlane", "v_readfirstlane")) or (op.startswith("v_cmp") and not op.startswith("v_cmpx") - and op.endswith("_e64")): - dst = args[0] if args else None - elif len(args) > 1 and _has_secondary_sgpr_destination(op): - dst = args[1] - if dst and dst.get("k") == "sgpr": - return range(dst["r"], dst["r"] + dst.get("n", 1)) - return range(0) - - -def branch_target(ins: dict): - """Byte pc a branch goes to (simm16 dwords after the branch), or None without an encoding.""" - imm = next((x for x in ins["args"] if x.get("k") == "imm"), None) - if imm is None or not ins.get("enc"): - return None - v = imm["v"] & 0xFFFF - return ins["pc"] + len(ins["enc"]) // 2 + 4 * (v - 0x10000 if v & 0x8000 else v) - - -def typed_buffer_ops(insns: list, table: frozenset, names: dict) -> Counter: - """Count the typed buffer accesses of one listing (§8.2 #16). - - MTBUF (tbuffer_*) carries its format in the instruction; LLVM leaves `format:` out for GFX10's default, 8_UNORM. - MUBUF (buffer_*_format_*) takes it from V# word 3 bits 18:12, and the result says where that word comes from in the - basic block of the access (blocks start at branch targets and after branches, as rdna2spirv.translate splits - them): an s_mov_b32 literal (the only form the translator folds, so the format is known when translating), a - scalar load (a descriptor from memory), or any other instruction (computed). A word 3 not written in the block is - "earlier_" + the class of the last write before it in listing order, or "shader_input" when nothing before it - writes the register (a user or system SGPR: the root signature's descriptor). - - Keys: ("mtbuf", load|store, format), ("mubuf", load|store, class) and, for a literal word 3 (in the block or - earlier), ("mubuf_literal", load|store, format). A format the translator's table lacks gets a "!" in front.""" - leaders = {insns[0]["pc"]} if insns else set() - for ins in insns: - if ins["op"] in BRANCH_OPS: - t = branch_target(ins) - if t is not None: - leaders.add(t) - if ins.get("enc"): - leaders.add(ins["pc"] + len(ins["enc"]) // 2) - out = Counter() - block, last = {}, {} # SGPR -> (class, literal or None): written in this block / last write so far - for ins in insns: - if ins["pc"] in leaders: - block = {} - op = ins["op"] - m = TYPED_MTBUF.match(op) or TYPED_MUBUF.match(op) - if m: - kind = m.group(1) - if op.startswith("t"): - fm = next((x for x in ins["mods"] if x.startswith("format:")), "format:[BUF_FMT_8_UNORM]") - name = fm.split("BUF_FMT_")[-1].rstrip("]") - code = next((c for c, n in names.items() if n == name), None) - out[("mtbuf", kind, ("" if code in table else "!") + name)] += 1 - elif len(ins["args"]) > 2 and ins["args"][2].get("k") == "sgpr": - w3 = ins["args"][2]["r"] + 3 - if w3 in block: - cls, lit = block[w3] - elif w3 in last: - cls, lit = "earlier_" + last[w3][0], last[w3][1] - else: - cls, lit = "shader_input", None - out[("mubuf", kind, cls)] += 1 - if lit is not None: - code = (lit >> 12) & 0x7F - out[("mubuf_literal", kind, ("" if code in table else "!") + names.get(code, f"code{code}"))] += 1 - regs = sgpr_writes(ins) - if regs: - if op == "s_mov_b32" and len(ins["args"]) > 1 and ins["args"][1].get("k") == "imm": - state = ("literal", ins["args"][1]["v"] & 0xFFFFFFFF) - elif op.startswith(("s_load", "s_buffer_load")): - state = ("memory", None) - else: - state = ("computed", None) - for r in regs: - block[r] = last[r] = state - return out - - -def scan_typed_buffers(disasm_dir: str, stage_of: dict) -> dict: - """§8.2 #16 over every listing: typed buffer access counts (typed_buffer_ops) summed, and shaders per stage.""" - import shader_ir - table, names = translator_formats() - total, shaders = Counter(), defaultdict(Counter) - for fn in sorted(os.listdir(disasm_dir)): - if not fn.endswith(".s"): - continue - path = os.path.join(disasm_dir, fn) - with open(path, encoding="utf-8", errors="replace") as f: - if "_format_" not in f.read(): # no typed buffer op: skip the slower full parse - continue - stage = stage_of.get(fn[:-2], "?") - c = typed_buffer_ops(shader_ir.parse_file(path)["insns"], table, names) - total.update(c) - for what in {k[0] for k in c}: - shaders[what][stage] += 1 - if any(k[0] == "mubuf" and k[2] not in ("literal", "earlier_literal") for k in c): - shaders["mubuf_runtime_format"][stage] += 1 - group = lambda what: {f"{k[1]} {k[2].lstrip('!')}": n for k, n in sorted(total.items()) if k[0] == what} - return {"mtbuf": group("mtbuf"), "mubuf_word3": group("mubuf"), "mubuf_literal_formats": group("mubuf_literal"), - "not_in_translator": {f"{k[0]} {k[1]} {k[2][1:]}": n for k, n in sorted(total.items()) - if k[0] != "mubuf" and k[2].startswith("!")}, - "shaders": {w: dict(s) for w, s in sorted(shaders.items())}} - - -def scan_spirv(spirv_index: str) -> dict: - with open(spirv_index, encoding="utf-8-sig") as f: - idx = json.load(f) - # An object maps shader names to rows; a list is the other accepted shape. A scalar is a - # broken index, not something to iterate -- report no translated shaders for it. - if isinstance(idx, dict): - entries = idx.values() - elif isinstance(idx, list): - entries = idx - else: - entries = () - total, code_base = Counter(), Counter() - for m in entries: - if not isinstance(m, dict): - continue - stage = stage_name(m) - total[stage] += 1 - code_base[stage] += (m.get("uses_code_base") is True) - return {"translated": dict(total), "uses_code_base": {k: v for k, v in code_base.items() if v}} - - -def same_path(first: str, second: str) -> bool: - """True when two paths name the same file, including through a link or a case difference on Windows.""" - a = os.path.normcase(os.path.abspath(first)) - b = os.path.normcase(os.path.abspath(second)) - if a == b: - return True - try: - return os.path.samefile(first, second) - except OSError: - return False - - -def inside_dir(path: str, folder: str) -> bool: - """True when the path itself or its symlink target is in the folder.""" - for resolve in (os.path.abspath, os.path.realpath): - root = os.path.normcase(resolve(folder)) - target = os.path.normcase(resolve(path)) - if target == root or target.startswith(os.path.join(root, "")): - return True - return False - - -def main() -> int: - ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) - ap.add_argument("shaders", help="/shaders from make_game.py") - ap.add_argument("--out", help="also write the counts as JSON") - a = ap.parse_args() - - dxbc_dir = os.path.join(a.shaders, "dxbc") - index_path = os.path.join(dxbc_dir, "index.json") - if not os.path.isdir(a.shaders): - what = "is not a folder" if os.path.exists(a.shaders) else "does not exist" - print(f"ERROR: {a.shaders} {what}. Give the /shaders folder make_game.py writes.", file=sys.stderr) - return 2 - if a.out: # a report is not an input: one written over the corpus index leaves the next run unable to scan - spirv_index = os.path.join(a.shaders, "spirv", "index.json") - if inside_dir(a.out, dxbc_dir): - print(f"ERROR: --out {a.out} is inside the scanned corpus {dxbc_dir}. Writing the report there would " - "replace index.json or a .dxbc the scan reads. Give a report path outside it.", file=sys.stderr) - return 2 - for input_index in (index_path, spirv_index): - if same_path(a.out, input_index): - print(f"ERROR: --out {a.out} is {input_index}, which the scan reads. Give another report path.", - file=sys.stderr) - return 2 - if not os.path.isfile(index_path): - print(f"ERROR: {index_path} is missing. Run the shaders stage of make_game.py first.", file=sys.stderr) - return 2 - try: - with open(index_path, encoding="utf-8-sig") as f: - index = json.load(f) - except (OSError, ValueError) as e: - print(f"ERROR: cannot read {index_path}: {getattr(e, 'strerror', None) or e}", file=sys.stderr) - return 2 - if not isinstance(index, list): - print(f"ERROR: {index_path} is not a shader list. Run the shaders stage of make_game.py again.", - file=sys.stderr) - return 2 - result = {"shaders": len(index), "dxbc": scan_dxbc(dxbc_dir, index)} - # Original names can be shared by variants, so indexed filenames take precedence. - # Non-object rows are already counted as unreadable by scan_dxbc; skip them here too. - rows = [e for e in index if isinstance(e, dict)] - stage_of = {e["name"]: stage_name(e) for e in rows if isinstance(e.get("name"), str)} - stage_of |= {os.path.splitext(e["file"])[0]: stage_name(e) - for e in rows if isinstance(e.get("file"), str)} - disasm = os.path.join(dxbc_dir, "disasm") - if os.path.isdir(disasm): - result["disasm"] = scan_disasm(disasm, stage_of) - result["typed_buffers"] = scan_typed_buffers(disasm, stage_of) - spirv = os.path.join(a.shaders, "spirv", "index.json") - if os.path.isfile(spirv): - try: - result["spirv"] = scan_spirv(spirv) - except (OSError, ValueError) as e: - print(f"ERROR: cannot read {spirv}: {getattr(e, 'strerror', None) or e}", file=sys.stderr) - return 2 - - d = result["dxbc"] - print(f"{result['shaders']} shaders") - print("DXIL stages:", ", ".join(f"{s} {n}" for s, n in d["stages"].items())) - for name in WATCHED: - print(f"SFI0 {name}: {sum(d['sfi0'].get(name, {}).values())} {d['sfi0'].get(name, {})}") - print("SFI0, every flag set anywhere:", {n: sum(v.values()) for n, v in d["sfi0"].items()}) - print("InnerCoverage metadata (ISG1 absence does not disprove use; no Xbox VGPR mapping):", - d["inner_coverage_metadata"]) - print("GS output-signature stream counts:", d["gs_output_stream_count"], - "| shaders with an output on a stream other than 0:", d["output_on_stream_other_than_0"] or 0) - pv = d["psv0"] - print(f"PSV0 bindings: {pv['records']} records | shaders with " - + ", ".join(f"{c} {pv['shaders'][c]} ({pv['records_of'][c]} records)" for c in WATCHED_BINDINGS) - + (f" | {pv['unreadable']} unreadable PSV0" if pv["unreadable"] else "")) - if "disasm" in result: - s = result["disasm"] - print(f"disasm: {s['files']} files | wave MMA shaders {s['wave_mma_shaders'] or 0} | ordered-count/GWS shaders " - f"{s['ordered_or_gws_shaders'] or 0} {s['ordered_or_gws_ops'] or ''} | GDS shaders {s['gds_shaders'] or 0}") - print("s_getpc_b64 used for code-embedded data (not a far branch), by stage:", s["getpc_for_data_shaders"] or 0) - vp = s["v_perm_b32"] - print(f"v_perm_b32: {sum(vp['shaders'].values())} shaders {vp['shaders'] or 0} | {vp['insns']} insns " - f"(imm {vp['immediate']}, const_reg {vp['const_reg']}, unresolved {vp['unresolved']}) | " - f"selectors 8-11: {vp['sign_extend_8_11_shaders']} shaders / {vp['sign_extend_8_11_insns']} insns | " - f"bytes {vp['selector_classes']}") - tb = result["typed_buffers"] - print("typed buffers, MTBUF formats (instruction):", tb["mtbuf"] or 0) - print("typed buffers, MUBUF V# word 3 source:", tb["mubuf_word3"] or 0, "| literal formats:", - tb["mubuf_literal_formats"] or 0) - print("typed buffers, formats the translator's table lacks:", tb["not_in_translator"] or 0, - "| shaders:", tb["shaders"] or 0) - else: - print("disasm: not there yet (run the shaders stage)") - if "spirv" in result: - s = result["spirv"] - print("uses_code_base by stage:", s["uses_code_base"], "of", s["translated"]) - else: - print("spirv/index.json: not there yet (run the shaders stage)") - if d["unreadable"]: - print(f"{d['unreadable']} .dxbc files could not be read") - if a.out: - folder = os.path.dirname(a.out) # --out into a folder that does not exist yet, as awc_manifest.py does - try: - if folder: - os.makedirs(folder, exist_ok=True) - with open(a.out, "w", encoding="utf-8", newline="\n") as f: - json.dump(result, f, indent=1) - except OSError as e: - print(f"ERROR: cannot write {a.out}: {e.strerror or e}", file=sys.stderr) - return 2 - return 0 - - -if __name__ == "__main__": - try: # a redirected stdout is strict ANSI code page under -I; write '?' for what it cannot encode - sys.stdout.reconfigure(errors="replace") - except (AttributeError, ValueError, OSError): - pass - sys.exit(main()) diff --git a/tools/file_mode.py b/tools/file_mode.py deleted file mode 100644 index 7c7f49812..000000000 --- a/tools/file_mode.py +++ /dev/null @@ -1,41 +0,0 @@ -"""Permission bits for a file published through a private staging file. - -tempfile.NamedTemporaryFile creates its file 0600, so a writer that stages next to the destination and then -os.replace()s it has to give the staged file the bits the destination would have had. Those are the bits of the -file it replaces, or, for a new file, what open() would give one in that directory. - -The umask is not read with os.umask(0) / os.umask(mask): that sets process-wide state, so a thread creating a -file between the two calls gets mask 0 (#750 and #728 review). Instead a probe file is created with mode 0666 and -its bits are read back, which applies the current umask (and a directory's default ACL) without changing anything. -""" -import os -import secrets -import stat - - -def new_file_mode(directory): - """The permission bits open() would give a new file in `directory`, found without touching the umask.""" - flags = os.O_WRONLY | os.O_CREAT | os.O_EXCL | getattr(os, "O_BINARY", 0) - for _ in range(100): - probe = os.path.join(directory, f".mode-{secrets.token_hex(8)}.probe") - try: - fd = os.open(probe, flags, 0o666) - except FileExistsError: - continue - try: - return stat.S_IMODE(os.fstat(fd).st_mode) - finally: - os.close(fd) - try: - os.remove(probe) - except OSError: - pass - raise FileExistsError(f"no free probe name in {directory}") - - -def published_mode(path): - """The permission bits a file published at `path` should get: those of the file it replaces, or a new file's.""" - try: - return stat.S_IMODE(os.stat(path).st_mode) - except FileNotFoundError: - return new_file_mode(os.path.dirname(os.path.abspath(path))) diff --git a/tools/find_hash_lookup.py b/tools/find_hash_lookup.py deleted file mode 100644 index 2757339f5..000000000 --- a/tools/find_hash_lookup.py +++ /dev/null @@ -1,168 +0,0 @@ -"""Rank candidate hash-lookup functions in a PE image (docs/modding.md, "Day one: finding the hook"). - - python -I tools/find_hash_lookup.py game_scarlett_master.exe [--hash player_story000_00 ...] [--window 48] - [--top 15] [--json out.json] - -Reads the file only; nothing runs. For each --hash (a model name, hashed with joaat as the game does, or 0x...; -default: Lucia's player model and cs_mandy), it finds every place the executable sections hold that 32-bit value -(an immediate such as `mov ecx, 0xE472B687`) and the direct calls (E8 rel32) in the next --window bytes. Each call -target is a candidate; candidates are ranked by how many of the hashes lead to them, then by how many direct calls -the whole image makes to them. RAGE's archetype lookup by hash takes the hash and is called from hundreds of places, -so it should rank first; pass its RVA to `gta6rt --archetype-lookup`. - -Standard library only. No game data is written: the report holds RVAs and counts. The report destination must not -name the scanned executable, which it would truncate. -""" -import argparse -import json -import os -import struct -import sys -from collections import Counter, defaultdict - -# -I keeps the script directory off sys.path, so add it explicitly before importing the sibling module. -sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) -from report_paths import same_report_path # noqa: E402 - -IMAGE_SCN_MEM_EXECUTE = 0x20000000 - - -def joaat(name): - """RAGE's joaat: Jenkins one-at-a-time over the lower-cased name (joaat('cs_mandy') == 0xD7C0CDFF). - - Over the Latin-1 bytes, as hashdict.joaat (the pinned dictionary) does; tests/test_joaat_agreement.py checks it.""" - h = 0 - for c in name.lower().encode("latin-1", "replace"): - h = (h + c) & 0xFFFFFFFF - h = (h + (h << 10)) & 0xFFFFFFFF - h ^= h >> 6 - h = (h + (h << 3)) & 0xFFFFFFFF - h ^= h >> 11 - return (h + (h << 15)) & 0xFFFFFFFF - - -def parse_hash(text): - if text.lower().startswith("0x"): - value = int(text, 16) - if value > 0xFFFFFFFF: - raise ValueError(f"{text} is wider than 32 bits") - return value - return joaat(text) - - -def sections(data): - """[(name, rva, raw offset, size, executable)] of a PE file (32- or 64-bit).""" - if data[:2] != b"MZ": - raise ValueError("not a PE file (no MZ header): an encrypted or packed executable can't be scanned") - pe = struct.unpack_from(" hashes that lead to it - hits = Counter() # hash -> occurrences found - for name, value in hashes: - needle = struct.pack("= 0: - hits[name] += 1 - tail = code[at + 4:at + 4 + window] - j = tail.find(b"\xE8") - while 0 <= j <= len(tail) - 5: - rel = struct.unpack_from("12} callers {c['direct_callers']:>6} led by {', '.join(c['led_by'])}") - if a.json: - try: - with open(a.json, "w", encoding="utf-8", newline="\n") as f: - json.dump(report, f, indent=1) - f.write("\n") - except OSError as e: - print(f"ERROR: cannot write {a.json}: {e.strerror or e}", file=sys.stderr) - return 2 - return 0 - - -if __name__ == "__main__": - try: # a redirected stdout is strict ANSI code page under -I; write '?' for what it cannot encode - sys.stdout.reconfigure(errors="replace") - except (AttributeError, ValueError, OSError): - pass - sys.exit(main()) diff --git a/tools/first_light.py b/tools/first_light.py deleted file mode 100644 index 75d14d7af..000000000 --- a/tools/first_light.py +++ /dev/null @@ -1,1186 +0,0 @@ -"""First light: draw an exported game model with a selected pair of translated game shaders. - -This assembles the smallest end-to-end path from the user's package to a Vulkan image: carve the game's -`shaders.rpf`, translate one real VS/PS pair with the repository's translator, convert one exported model to the -mesh the GPU harness reads, and run it on the device. Nothing is written outside `--work`, and no game data is -committed: the tool is the recipe, the user's copy is the input. - -Without a DDS texture, the vertex shader forwards clip-space POSITION and TEXCOORD. The default pixel shader -writes the interpolated TEXCOORD, so the first image is the model's own UV map. Both are ordinary game shaders; -`--vs` and `--ps` take other names from the carve index. - -Usage: - python -I first_light.py --game "" --obj --work [--out ] [--run] - python -I first_light.py --game "" --obj --work --camera [--yaw 30 --pitch 25] --run - python -I first_light.py --game "" --work --list # show VS/PS candidates - -The mesh file the harness reads is: u32 vertex_count, u32 index_count, vertex_count x (x,y,z,u,v) f32, then -index_count u32 indices. By default the draw is orthographic: the model is centred and scaled to NDC on X/Y and -flattened to z = 0.5, because the chosen VS does not apply a matrix (see docs/first_light.md). - -`--camera` draws in perspective instead, with a game VS that reads a world matrix and a view-projection matrix -from two constant buffers (CAMERA_VS). The mesh keeps the model's own coordinates; the tool builds a camera, writes -the matrices, the two V#s and the descriptor table into the harness heap (VKH_HEAP, VKH_SGPRS) and predicts the -image with the same matrices, interpolating UV perspective-correctly as the rasterizer does. Its output goes to -/first_light/camera, so the orthographic folder that d3d12_first_light_test reads is left alone. - -The model is an OBJ from `rpf9dump models` (tools/rpf9dump). Building that tool and exporting an archive is the -only step outside this script: - - git submodule update --init - dotnet build tools/rpf9dump/rpf9dump.csproj -c Release - DOTNET_ROLL_FORWARD=Major tools/rpf9dump/bin/Release/net8.0/rpf9dump models "/data.rpf" /assets - -Standard library only; the project's tools run with `python -I`. -""" - -from __future__ import annotations - -import argparse -import hashlib -import json -import math -import os -import shutil -import struct -import subprocess -import sys - -TOOLS = os.path.dirname(os.path.abspath(__file__)) -ROOT = os.path.dirname(TOOLS) -sys.path.insert(0, os.path.join(ROOT, "runtime", "test", "shaders")) -from compute_fixture import find_test_program # noqa: E402 -sys.path.insert(0, TOOLS) # python -I leaves the script's own folder off sys.path -from stale_build import newer_sources # noqa: E402 - -DEFAULT_VS = "VS_main_170e32e6_Wrapped" -DEFAULT_PS = "$PS_Rage_Untextured_14f8529b_Wrapped" -DEFAULT_TEXTURED_PS = "PS_Copy_3ea4b38a_Wrapped" -DEFAULT_TSHARP_VA = 0x100 -DEFAULT_PTR_SGPR = 9 -DEFAULT_SSHARP = [0x92, 0xC00000, 0x14500000, 0] -MESH_HEADER = struct.Struct(" str: - """Remove /first_light/dxbc and spirv as an earlier run left them; return a new, empty dxbc. - - The unpacker, the disassembler and the translator each take every file in the folder they are given, and the - translator merges into an index.json it finds, so a container staged by an earlier run would be translated - again beside this run's pair. Both folders hold only copies from /shaders and files derived from them, - so they are removed whole; first_light/out, another --out and /shaders are not touched. A folder that - is a symlink or a junction, or is reached through one at first_light, is refused: nothing outside the work - folder is removed. shutil.rmtree unlinks a link inside a folder without entering it. - """ - base = os.path.join(work, "first_light") - real_base = os.path.join(os.path.realpath(work), "first_light") - # first_light itself is checked first: when it is a link to a folder with no dxbc or spirv in it, there is - # nothing stale to judge below, and the new dxbc would be created on the far side of the link. - if os.path.lexists(base) and ( - not os.path.isdir(base) or os.path.normcase(os.path.realpath(base)) != os.path.normcase(real_base) - ): - raise SystemExit( - f"{base} is a symlink, a junction or a file: each run removes and creates folders under it and does " - "not follow a link to do it; remove it and run again" - ) - stale = [os.path.join(base, name) for name in ("dxbc", "spirv") if os.path.lexists(os.path.join(base, name))] - for folder in stale: # both are checked before either is removed - real = os.path.join(real_base, os.path.basename(folder)) - if not os.path.isdir(folder) or os.path.normcase(os.path.realpath(folder)) != os.path.normcase(real): - raise SystemExit( - f"{folder} is a symlink, a junction or a file, or first_light above it is a link: each run " - "removes this folder and does not follow a link to do it; remove it and run again" - ) - for folder in stale: - try: - shutil.rmtree(folder) - except OSError as e: - raise SystemExit( - f"cannot remove {e.filename or folder} left by an earlier run ({e.strerror or e}); " - f"close what holds it or delete {folder}, then run again" - ) from e - dxbc = os.path.join(base, "dxbc") - try: - os.makedirs(dxbc) - except OSError as e: - raise SystemExit(f"cannot create {dxbc}: {e.strerror or e}") from e - return dxbc - - -def carve_index(work: str) -> str: - return os.path.join(work, "shaders", "dxbc", "index.json") - - -def ensure_carve(game: str, work: str) -> str: - index = carve_index(work) - if not os.path.isfile(index): - run( - [ - os.path.join(TOOLS, "shader_carve.py"), - os.path.join(game, "shaders.rpf"), - os.path.join(work, "shaders", "dxbc"), - ] - ) - return index - - -def choose(index_path: str, vs: str, ps: str) -> list[dict]: - entries = load_json(index_path, "carve index", list, entry_keys=("stage", "name", "file")) - by_stage_and_name = {(entry["stage"], entry["name"]): entry for entry in entries} - requested = (("vs", vs), ("ps", ps)) - missing = [f"{stage} {name}" for stage, name in requested if (stage, name) not in by_stage_and_name] - if missing: - raise SystemExit( - f"shader not in the carve index: {', '.join(missing)} (use --list)" - ) - return [by_stage_and_name[key] for key in requested] - - -def translate(work: str, picked: list[dict]) -> dict: - """Translate just the two chosen containers, in the layout rdna2spirv.py reads.""" - base = os.path.join(work, "first_light") - dxbc = reset_run_folders(work) - index = [] - for entry in picked: - shutil.copy( - os.path.join(work, "shaders", "dxbc", entry["file"]), - os.path.join(dxbc, entry["file"]), - ) - index.append( - {"name": entry["name"], "file": entry["file"], "stage": entry["stage"]} - ) - with open(os.path.join(dxbc, "index.json"), "w", encoding="utf-8", newline="\n") as f: - json.dump(index, f, indent=0) - run([os.path.join(TOOLS, "fssm_unpack.py"), dxbc]) - run( - [ - os.path.join(TOOLS, "shader_disasm.py"), - os.path.join(dxbc, "fssm"), - "--out", - os.path.join(dxbc, "disasm"), - "--mcpu", - "gfx1013", - ] - ) - spirv = os.path.join(base, "spirv") - run( - [ - os.path.join(TOOLS, "rdna2spirv.py"), - os.path.join(dxbc, "disasm"), - "--out", - spirv, - ] - ) - with open(os.path.join(spirv, "index.json"), encoding="utf-8") as f: - meta = json.load(f) - result = {} - for entry in picked: - stem = os.path.splitext(entry["file"])[0] - item = meta.get(stem) - if item is None or item.get("stage") != entry["stage"]: - raise SystemExit(f"translator has no {entry['stage']} result for {stem}") - result[entry["stage"]] = item - return result - - -def _obj_lines(handle): - """Yield logical OBJ lines with trailing-backslash continuations joined and # comments stripped.""" - pending = "" - for raw_line in handle: - stripped = raw_line.rstrip("\r\n") - if stripped.endswith("\\"): - pending += stripped[:-1] - continue - yield (pending + stripped).split("#", 1)[0] - pending = "" - if pending: - yield pending.split("#", 1)[0] - - -def _parse_obj_int(token: str, path: str, kind: str) -> int: - try: - return int(token) - except ValueError: - raise SystemExit(f"{path}: invalid {kind} index {token!r}") from None - - -def read_obj( - path: str, -) -> tuple[list[tuple[float, float, float, float, float]], list[int]]: - """Positions, UVs and triangles as (x, y, z, u, v) vertices plus a u32 index list.""" - positions, uvs, faces = [], [], [] - with open(path, encoding="utf-8", errors="replace") as f: - for line in _obj_lines(f): - p = line.split() - if not p: - continue - if p[0] == "v": - if len(p) < 4: - raise SystemExit(f"{path}: short vertex line: {line.strip()!r}") - try: - position = tuple(float(x) for x in p[1:4]) - except ValueError: - raise SystemExit(f"{path}: invalid vertex coordinates: {line.strip()!r}") from None - if not all(math.isfinite(value) for value in position): - raise SystemExit(f"{path}: non-finite vertex coordinates: {line.strip()!r}") - positions.append(position) - elif p[0] == "vt": - if len(p) < 3: - raise SystemExit(f"{path}: short texture-coordinate line: {line.strip()!r}") - try: - u, v = map(float, p[1:3]) - except ValueError: - raise SystemExit(f"{path}: invalid texture coordinates: {line.strip()!r}") from None - if not (math.isfinite(u) and math.isfinite(v)): - raise SystemExit(f"{path}: non-finite texture coordinates: {line.strip()!r}") - try: - struct.pack("<2f", u, v) # Validate the mesh encoding before opening the output. - except OverflowError: - raise SystemExit(f"{path}: texture coordinates exceed the binary32 range: {line.strip()!r}") from None - uvs.append((u, v)) - elif p[0] == "f": - face = [] - for word in p[1:]: - parts = word.split("/") - raw_vi = _parse_obj_int(parts[0], path, "vertex") - if raw_vi == 0: - raise SystemExit(f"{path}: vertex index 0 is out of range (OBJ indices are 1-based)") - vi = len(positions) + raw_vi if raw_vi < 0 else raw_vi - 1 - if raw_vi < 0 and vi < 0: - raise SystemExit(f"{path}: vertex index {raw_vi} is out of range for {len(positions)} vertex(es)") - if len(parts) > 1 and parts[1]: - raw_ti = _parse_obj_int(parts[1], path, "texture-coordinate") - if raw_ti == 0: - ti = -1 - else: - ti = len(uvs) + raw_ti if raw_ti < 0 else raw_ti - 1 - if raw_ti < 0 and ti < 0: - ti = -1 - else: - ti = -1 - face.append((vi, ti)) - for k in range(1, len(face) - 1): - faces.extend((face[0], face[k], face[k + 1])) - if not positions or not faces: - raise SystemExit(f"no vertices or faces in {path}") - unique, vertices, indices = {}, [], [] - for vi, ti in faces: - if not 0 <= vi < len(positions): - raise SystemExit(f"{path}: vertex index {vi + 1} is out of range for {len(positions)} vertex(es)") - key = (vi, ti) - if key not in unique: - unique[key] = len(vertices) - x, y, z = positions[vi] - u, v = uvs[ti] if 0 <= ti < len(uvs) else (0.0, 0.0) - vertices.append((x, y, z, u, v)) - indices.append(unique[key]) - return vertices, indices - - -def fit(vertices, width: int, height: int, fit_xy: bool, flatten_z: bool): - xs = [v[0] for v in vertices] - ys = [v[1] for v in vertices] - zs = [v[2] for v in vertices] - cx, cy = (min(xs) + max(xs)) / 2, (min(ys) + max(ys)) / 2 - span = max(max(xs) - min(xs), max(ys) - min(ys)) or 1.0 - scale = 1.8 / span - cz = (min(zs) + max(zs)) / 2 if not flatten_z else 0.0 - aspect = width / height if height else 1.0 - out = [] - for x, y, z, u, v in vertices: - nx = (x - cx) * scale * (1.0 / aspect if aspect > 1 else 1.0) - ny = (y - cy) * scale * (aspect if aspect < 1 else 1.0) - nz = 0.5 if flatten_z else (z - cz) * scale + 0.5 - out.append((nx, ny, nz, u, v)) - return out - - -def f32(x: float) -> float: - """x rounded to float32, so the predicted image uses the matrices the GPU reads.""" - return struct.unpack(" list[int]: - """A raw buffer V#: 32-bit base address (the heap is below 4 GiB), stride 0, size in bytes, word 3 zero.""" - return [base, 0, size, 0] - - -def camera_constants(world, viewproj) -> tuple[str, str]: - """VKH_SGPRS and VKH_HEAP for CAMERA_VS: the table address in s9, the two V#s in the table, the two matrices.""" - sgprs = [0] * (CAMERA_TABLE_SGPR + 1) - sgprs[CAMERA_TABLE_SGPR] = TABLE_VA - heap = {} - - def put(addr, words): - for i, word in enumerate(words): - heap[addr + 4 * i] = word - - def f32_words(m): - return [struct.unpack(" None: - with open(path, "wb") as f: - f.write(MESH_HEADER.pack(len(vertices), len(indices))) - f.writelines(struct.pack("<5f", *v) for v in vertices) - f.write(struct.pack(f"<{len(indices)}I", *indices)) - - -def decode_dds_to_rgba(path: str) -> tuple[int, int, bytes, str]: - """Decode a DDS texture (BC1/BC3/BC7/RGBA8/etc.) via tools/dds_png.py.""" - if TOOLS not in sys.path: - sys.path.insert(0, TOOLS) - import dds_png - - with open(path, "rb") as f: - raw = f.read() - width, height, rgba = dds_png.decode_dds(raw) - return width, height, rgba, hashlib.sha256(raw).hexdigest() - - -def write_texture_rgba(path: str, width: int, height: int, rgba: bytes) -> None: - if len(rgba) != width * height * 4: - raise ValueError(f"expected {width * height * 4} RGBA bytes, got {len(rgba)}") - with open(path, "wb") as f: - f.write(TEX_HEADER.pack(width, height)) - f.write(rgba) - - -def sample_rgba_bilinear( - width: int, height: int, rgba: bytes, u: float, v: float -) -> list[float]: - """Bilinear sample of an R8G8B8A8_UNORM texture with clamp-to-edge addressing.""" - u = max(0.0, min(1.0, u)) - v = max(0.0, min(1.0, v)) - fx = u * width - 0.5 - fy = v * height - 0.5 - x0 = max(0, min(width - 1, int(fx) if fx >= 0 else 0)) - y0 = max(0, min(height - 1, int(fy) if fy >= 0 else 0)) - x1 = min(width - 1, x0 + 1) - y1 = min(height - 1, y0 + 1) - tx = max(0.0, min(1.0, fx - x0)) - ty = max(0.0, min(1.0, fy - y0)) - - def texel(x: int, y: int) -> tuple[float, float, float, float]: - off = (y * width + x) * 4 - return ( - rgba[off] / 255.0, - rgba[off + 1] / 255.0, - rgba[off + 2] / 255.0, - rgba[off + 3] / 255.0, - ) - - c00, c10 = texel(x0, y0), texel(x1, y0) - c01, c11 = texel(x0, y1), texel(x1, y1) - out = [] - for c in range(4): - top = c00[c] * (1.0 - tx) + c10[c] * tx - bot = c01[c] * (1.0 - tx) + c11[c] * tx - out.append(round(top * (1.0 - ty) + bot * ty, 6)) - return out - - -def harness_env(manifest: dict, out_dir: str, base_env: dict | None = None) -> dict: - """The environment vk_harness draws a first_light manifest with: the mesh and its layout, plus the constants of a - --camera draw (VKH_SGPRS and VKH_HEAP) or of a --dds draw (the texture, T#, S# and its pointer SGPR). - - tests/test_first_light.py uses it too. VKH_SGPRS and VKH_HEAP from the caller are dropped first, so a stale value - cannot change an orthographic draw. - """ - env = dict(os.environ if base_env is None else base_env) - env["VKH_DRAW_MESH"] = os.path.join(out_dir, manifest["files"]["mesh"]) - env["VKH_VERTEX_LAYOUT"] = "0:3f,1:2f" - env.pop("VKH_SGPRS", None) - env.pop("VKH_HEAP", None) - camera = manifest.get("camera") - if camera: - env["VKH_SGPRS"] = camera["sgprs"] - env["VKH_HEAP"] = camera["heap"] - tex = manifest.get("texture") - if tex: - tex_file = manifest["files"]["texture"] - ptr_sgpr = int(tex["ptr_sgpr"]) - tsharp_va = int(tex["tsharp_va"]) - ssharp = tex["ssharp"] - sgprs = ["0"] * (ptr_sgpr + 1) - sgprs[ptr_sgpr] = hex(tsharp_va) - env["VKH_TEX_RGBA"] = os.path.join(out_dir, tex_file) - env["VKH_TSHARP_VA"] = hex(tsharp_va) - env["VKH_SSHARP"] = ",".join(hex(int(w)) for w in ssharp) - env["VKH_SGPRS"] = ",".join(sgprs) - ps_sg = manifest.get("ps", {}).get("subgroup_size") - if ps_sg: - env["VKH_SUBGROUP_SIZE"] = str(int(ps_sg)) - return env - - -def pixel_ndc(px: int, py: int, width: int, height: int) -> tuple[float, float]: - """The NDC of a pixel centre under the harness's viewport (y grows down, like Vulkan).""" - return (px + 0.5) / width * 2.0 - 1.0, (py + 0.5) / height * 2.0 - 1.0 - - -def barycentric(px, py, ax, ay, bx, by, cx, cy): - """The three barycentric weights of (px, py) in the triangle, or None outside it (either winding).""" - det = (by - cy) * (ax - cx) + (cx - bx) * (ay - cy) - if abs(det) < 1e-12: - return None - w0 = ((by - cy) * (px - cx) + (cx - bx) * (py - cy)) / det - w1 = ((cy - ay) * (px - cx) + (ax - cx) * (py - cy)) / det - w2 = 1.0 - w0 - w1 - if min(w0, w1, w2) < -1e-6 or max(w0, w1, w2) > 1.0 + 1e-6: - return None - return w0, w1, w2 - - -def uv_at(vertices, indices, px: int, py: int, width: int, height: int): - """The UV the last triangle covering this pixel centre writes (no depth test: the last primitive wins). - - Vertices from project() carry clip w as a sixth item; their UV is interpolated perspective-correctly (each - screen-space weight divided by its vertex's w, renormalized), as the rasterizer does for a perspective varying. - """ - x, y = pixel_ndc(px, py, width, height) - found = None - for i in range(0, len(indices), 3): - a, b, c = (vertices[indices[i + k]] for k in range(3)) - weights = barycentric(x, y, a[0], a[1], b[0], b[1], c[0], c[1]) - if weights and len(a) > 5: - q = (weights[0] / a[5], weights[1] / b[5], weights[2] / c[5]) - weights = tuple(w / sum(q) for w in q) - if weights: - if not (0 <= a[2] <= 1 and 0 <= b[2] <= 1 and 0 <= c[2] <= 1): - # The passthrough VS has w=1. Use the float32 depths written to mesh.bin. - za, zb, zc = struct.unpack("<3f", struct.pack("<3f", a[2], b[2], c[2])) - z = za + weights[1] * (zb - za) + weights[2] * (zc - za) - if not 0 <= z <= 1: - continue - found = ( - weights[0] * a[3] + weights[1] * b[3] + weights[2] * c[3], - weights[0] * a[4] + weights[1] * b[4] + weights[2] * c[4], - ) - return found - - -def clear_pixel(vertices, indices, width: int, height: int): - """A corner the mesh does not cover, which must keep the harness clear value.""" - for px, py in ((0, 0), (width - 1, 0), (0, height - 1), (width - 1, height - 1)): - if uv_at(vertices, indices, px, py, width, height) is None: - return [px, py] - return None - - -def uv_probes(vertices, indices, width: int, height: int, limit: int = 4) -> list[dict]: - """Pixels whose predicted UV has U and V far apart, so a swapped-U/V image cannot pass. - - The centre alone is not enough: a symmetric model can have U ~= V there. The scan is coarse (16 x 16 at - 128 px) and uses the same last-triangle rule as the centre. - """ - step = max(1, min(width, height) // 16) - found = [] - for py in range(step // 2, height, step): - for px in range(step // 2, width, step): - uv = uv_at(vertices, indices, px, py, width, height) - if uv and abs(uv[0] - uv[1]) > 0.15: - found.append( - {"pixel": [px, py], "uv": [round(uv[0], 6), round(uv[1], 6)]} - ) - if len(found) > limit: - found = [found[int(i * len(found) / limit)] for i in range(limit)] - return found - - -def warn_if_stale(harness: str) -> str: - """`harness`, after a warning when it is a build in this checkout's runtime/build older than vk_harness's sources - (a pull since it was built): it would draw with the old harness and say nothing. A harness outside runtime/build - (--harness or LEONIDA_VK_HARNESS naming another folder) isn't compared.""" - build = os.path.abspath(os.path.join(ROOT, "runtime", "build")) - try: - ours = os.path.commonpath([build, os.path.abspath(harness)]) == build - except ValueError: # another drive - ours = False - newer = newer_sources(harness, ROOT, "vk_harness") if ours else [] - if newer: - more = f" and {len(newer) - 3} more" if len(newer) > 3 else "" - print(f"WARNING: {harness} is older than {', '.join(newer[:3])}{more}; rebuild it " - f"(cmake --build --target vk_harness) to draw with this checkout's harness", - file=sys.stderr) - return harness - - -def find_harness(explicit: str | None) -> str: - executable = "vk_harness.exe" if os.name == "nt" else "vk_harness" - build = os.path.join(ROOT, "runtime", "build") - build_dirs = (os.path.join(build, "linux"), os.path.join(build, "windows"), build) - for candidate in ( - explicit, - os.environ.get("LEONIDA_VK_HARNESS"), - *(os.path.join(folder, executable) for folder in build_dirs), - ): - if candidate and os.path.isfile(candidate): - return warn_if_stale(candidate) - for folder in build_dirs: - configured = find_test_program(folder, "vk_harness") - if configured: - return warn_if_stale(os.path.join(configured, executable)) - raise SystemExit( - "vk_harness not found: build runtime/build/linux or runtime/build/windows (target vk_harness), " - "or set --harness/LEONIDA_VK_HARNESS" - ) - - -CLEAR = -1.0 -FALLBACK_RGBA = (1.0, 0.0, 1.0, 1.0) - - -def _close(got: float, want: float, tol: float) -> bool: - return math.isfinite(got) and abs(got - want) <= tol - - -def _distinguishable_from_fallback(rgba: list[float] | tuple[float, ...], tol: float) -> bool: - return any(abs(c - m) > tol for c, m in zip(rgba, FALLBACK_RGBA)) - - -def rgba_probes_for_mesh( - vertices, - indices, - width: int, - height: int, - tw: int, - th: int, - rgba: bytes, - uv_probe_list: list[dict] | None = None, - tol: float = 0.02, - limit: int = 4, -) -> list[dict]: - """Select covered RGBA probes for textured verification. - - Starts from ``uv_probe_list`` when available; if that is empty (e.g. an off-centre mesh with - default (0, 0) UVs), scans covered pixels so textured draws always have at least one covered - RGBA probe. Prefers samples whose expected colour differs from the harness's magenta fallback. - """ - candidates = list(uv_probe_list) if uv_probe_list else [] - if not candidates and vertices: - step = max(1, min(width, height) // 16) - for py in range(step // 2, height, step): - for px in range(step // 2, width, step): - uv = uv_at(vertices, indices, px, py, width, height) - if uv is not None: - candidates.append( - {"pixel": [px, py], "uv": [round(uv[0], 6), round(uv[1], 6)]} - ) - if not candidates: - for py in range(height): - for px in range(width): - uv = uv_at(vertices, indices, px, py, width, height) - if uv is not None: - candidates.append( - {"pixel": [px, py], "uv": [round(uv[0], 6), round(uv[1], 6)]} - ) - if len(candidates) >= limit * 4: - break - if len(candidates) >= limit * 4: - break - sampled = [ - { - "pixel": p["pixel"], - "uv": p["uv"], - "rgba": sample_rgba_bilinear(tw, th, rgba, p["uv"][0], p["uv"][1]), - } - for p in candidates - ] - distinct = [p for p in sampled if _distinguishable_from_fallback(p["rgba"], tol)] - pool = distinct if distinct else sampled - if len(pool) > limit: - pool = [pool[int(i * len(pool) / limit)] for i in range(limit)] - return pool - - -def check_image(data: bytes, manifest: dict) -> dict: - """The readback oracle: exact shape, coverage window, a clear corner and the centre UV. - - tests/test_first_light.py imports this function, so the test and ``--check`` agree. - """ - def check_rgba_shape(values: object, field: str) -> None: - if not isinstance(values, (list, tuple)) or len(values) != 4: - raise AssertionError(f"{field} must contain exactly four RGBA values") - - width, height = manifest["width"], manifest["height"] - - def pixel_offset(point, field: str) -> int: - if ( - not isinstance(point, (list, tuple)) or len(point) != 2 - or any(type(coord) is not int for coord in point) - or not (0 <= point[0] < width and 0 <= point[1] < height) - ): - raise AssertionError(f"invalid {field} coordinates {point!r} for {width}x{height} image") - x, y = point - return (y * width + x) * 4 - - if len(data) != width * height * 16: - raise AssertionError( - f"raw is {len(data)} bytes, expected {width * height * 16}" - ) - pixels = struct.unpack(f"<{len(data) // 4}f", data) - clear_val = manifest.get("clear", CLEAR) - textured = ( - manifest.get("texture") is not None - or manifest.get("centre_rgba") is not None - or manifest.get("rgba_probes") is not None - ) - if textured: - # UNORM texels can have any alpha in [0, 1] (including 0.0), so distinguish covered fragments - # from the harness clear sentinel (-1.0) instead of testing alpha > 0.5. - covered = sum( - 1 - for i in range(0, len(pixels), 4) - if not all(_close(pixels[i + c], clear_val, 1e-5) for c in range(4)) - ) - else: - covered = sum(1 for i in range(3, len(pixels), 4) if pixels[i] > 0.5) - ratio = covered / (width * height) - if ( - not manifest.get("min_coverage", 0.0) - <= ratio - <= manifest.get("max_coverage", 1.0) - ): - raise AssertionError( - f"coverage {ratio:.4f} outside " - f"[{manifest.get('min_coverage', 0.0)}, {manifest.get('max_coverage', 1.0)}]" - ) - if (clear := manifest.get("clear_pixel")) is not None: - i = pixel_offset(clear, "clear_pixel") - if any(not _close(pixels[i + c], clear_val, 1e-5) for c in range(4)): - raise AssertionError( - f"clear pixel {clear} is {pixels[i : i + 4]}, expected {clear_val}" - ) - if textured: - tol = manifest.get("rgba_tolerance", 0.02) - expected_rgbas = [] - if (rgba := manifest.get("centre_rgba")) is not None: - expected_rgbas.append(rgba) - for probe in manifest.get("rgba_probes") or []: - expected_rgbas.append(probe["rgba"]) - if not expected_rgbas: - raise AssertionError( - "textured manifest has no covered RGBA samples (centre_rgba or rgba_probes)" - ) - if not any(_distinguishable_from_fallback(r, tol) for r in expected_rgbas): - raise AssertionError( - f"textured manifest has no expected colour distinguishable from fallback {FALLBACK_RGBA} (tol {tol})" - ) - centre = manifest.get("centre_pixel") - if centre is None or centre == []: - centre = [width // 2, height // 2] - if (rgba := manifest.get("centre_rgba")) is not None: - i = pixel_offset(centre, "centre_pixel") - tol = manifest.get("rgba_tolerance", 0.02) - check_rgba_shape(rgba, "centre_rgba") - for c, want in enumerate(rgba): - if not _close(pixels[i + c], want, tol): - raise AssertionError( - f"centre {centre} is {pixels[i : i + 4]}, expected {rgba} (tol {tol})" - ) - elif (uv := manifest.get("centre_uv")) is not None: - i = pixel_offset(centre, "centre_pixel") - for c, want in enumerate((uv[0], uv[1], 0.0, 1.0)): - if not _close(pixels[i + c], want, 2e-3): - raise AssertionError( - f"centre {centre} is {pixels[i : i + 4]}, expected {want} at {c}" - ) - if (rgba_probes := manifest.get("rgba_probes")) is not None: - tol = manifest.get("rgba_tolerance", 0.02) - for probe in rgba_probes: - i = pixel_offset(probe.get("pixel"), "rgba_probes pixel") - want_rgba = probe["rgba"] - check_rgba_shape(want_rgba, "rgba_probes[].rgba") - for c, want in enumerate(want_rgba): - if not _close(pixels[i + c], want, tol): - raise AssertionError( - f"RGBA probe {probe['pixel']} is {pixels[i : i + 4]}, expected {want_rgba} (tol {tol})" - ) - uv_probes = manifest.get("uv_probes") - if uv_probes is None: - uv_probes = [] - for probe in uv_probes: - i = pixel_offset(probe.get("pixel"), "uv_probes pixel") - if rgba_probes is not None: - continue - u, v = probe["uv"] - for c, want in enumerate((u, v, 0.0, 1.0)): - if not _close(pixels[i + c], want, 2e-3): - raise AssertionError( - f"UV probe {probe['pixel']} is {pixels[i : i + 4]}, expected {want} at {c}" - ) - return {"covered": covered, "ratio": ratio, "pixels": pixels} - - -def write_ppm(path: str, pixels, width: int, height: int) -> None: - """Write RGB bytes, saturating infinities and rendering NaN as zero.""" - def channel_byte(value: float) -> int: - return round(min(1.0, value) * 255) if value > 0.0 else 0 - - with open(path, "wb") as f: - f.write(f"P6\n{width} {height}\n255\n".encode()) - f.writelines( - bytes(channel_byte(pixels[i + c]) for c in range(3)) - for i in range(0, len(pixels), 4) - ) - - -def run_draw(args, manifest: dict, out_dir: str) -> dict: - if manifest.get("vertex_count") == 0 or manifest.get("index_count") == 0: - raise SystemExit("first-light draw requires an OBJ with faces. Prepare this output with --obj before drawing.") - harness = find_harness(args.harness) - raw = os.path.join(out_dir, "image.raw") - ppm = os.path.join(out_dir, "image.ppm") - manifest_path = os.path.join(out_dir, "manifest.json") - env = harness_env(manifest, out_dir) - cmd = [ - harness, - os.path.join(out_dir, "vs.spv"), - os.path.join(out_dir, "ps.spv"), - raw, - str(manifest["width"]), - str(manifest["height"]), - ] - # A new draw must not reuse an old readback or leave an old success report on failure. - for path in (raw, ppm): - if os.path.exists(path): - os.unlink(path) - if "result" in manifest: - del manifest["result"] - with open(manifest_path, "w", encoding="utf-8", newline="\n") as f: - json.dump(manifest, f, indent=1) - subprocess.run(cmd, check=True, env=env) - if not os.path.isfile(raw): - raise SystemExit(f"the harness exited successfully but did not write {raw}") - with open(raw, "rb") as f: - data = f.read() - try: - result = check_image(data, manifest) - except AssertionError as e: - raise SystemExit(str(e)) from e - write_ppm(ppm, result["pixels"], manifest["width"], manifest["height"]) - print( - f"covered {result['covered']}/{manifest['width'] * manifest['height']} " - f"({result['ratio']:.3f}); {ppm}" - ) - manifest["result"] = { - "covered": result["covered"], - "total": manifest["width"] * manifest["height"], - "ratio": result["ratio"], - "ppm": ppm, - } - with open(manifest_path, "w", encoding="utf-8", newline="\n") as f: - json.dump(manifest, f, indent=1) - return result - - -def load_json( - path: str, - kind: str, - expect: type, - keys: tuple[str, ...] = (), - entry_keys: tuple[str, ...] = (), -): - """Read a JSON file from the user's folders; a bad read exits naming it, never a traceback. - - Invalid or truncated JSON, non-UTF-8 bytes, the wrong top-level shape, a missing required - key, and an array entry that is not an object or lacks one are the user's broken files, so - they fail like the tool's other errors: one SystemExit line with the path and the reason. - """ - wanted = "an object" if expect is dict else "an array" - try: - with open(path, encoding="utf-8") as f: - data = json.load(f) - except UnicodeDecodeError as e: - raise SystemExit(f"the {kind} {path} is not valid UTF-8 ({e.reason})") from e - except json.JSONDecodeError as e: - raise SystemExit( - f"the {kind} {path} is not valid JSON ({e.msg} at line {e.lineno} column {e.colno})" - ) from e - if not isinstance(data, expect): - raise SystemExit(f"the {kind} {path} is a {type(data).__name__}, expected {wanted}") - if expect is dict: - if gaps := [k for k in keys if k not in data]: - raise SystemExit(f"the {kind} {path} has no key {', '.join(repr(k) for k in gaps)}") - else: - for i, entry in enumerate(data): - if not isinstance(entry, dict): - raise SystemExit( - f"the {kind} {path} entry {i} is a {type(entry).__name__}, expected an object" - ) - if gaps := [k for k in entry_keys if k not in entry]: - raise SystemExit( - f"the {kind} {path} entry {i} has no key {', '.join(repr(k) for k in gaps)}" - ) - return data - - -def main(argv=None) -> int: - ap = argparse.ArgumentParser( - description="Draw an exported model with translated game shaders. Display its UVs or supply a texture with --dds." - ) - ap.add_argument("--game", help="the package folder") - ap.add_argument("--obj", help="an OBJ exported by rpf9dump models, with finite vertex positions and UVs") - ap.add_argument( - "--work", - default=os.path.expanduser("~/leonida-work"), - help="the work folder make_game.py uses (default ~/leonida-work)", - ) - ap.add_argument("--out", help="output folder (default /first_light/out)") - ap.add_argument( - "--vs", - help=f"vertex shader name in the carve index (default {DEFAULT_VS}, or {CAMERA_VS} with --camera)", - ) - ap.add_argument( - "--ps", default=None, help="pixel shader name in the carve index (default untextured, or PS_Copy with --dds)" - ) - ap.add_argument( - "--dds", - help="an exported DDS texture (e.g. BCPack-decoded TTPF albedo) to bind via set-0 T# and sampler S#", - ) - ap.add_argument("--width", type=int, default=128) - ap.add_argument("--height", type=int, default=128) - ap.add_argument( - "--min-coverage", - type=float, - help="the oracle's lowest covered fraction (default 0.5, or 0.2 with --camera: a model in perspective " - "fills less of the image)", - ) - ap.add_argument( - "--no-fit", - action="store_true", - help="keep the model's coordinates (must already be in NDC)", - ) - ap.add_argument("--keep-z", action="store_true", help="do not flatten z to 0.5") - ap.add_argument( - "--camera", - action="store_true", - help="draw in perspective with CAMERA_VS and a camera's world/view-projection constants", - ) - ap.add_argument("--yaw", type=float, default=30.0, help="--camera: degrees around Z from -Y (default 30)") - ap.add_argument( - "--pitch", type=float, default=25.0, help="--camera: degrees above the XY plane, -80..80 (default 25)" - ) - ap.add_argument("--fov", type=float, default=50.0, help="--camera: vertical field of view, degrees (default 50)") - ap.add_argument( - "--harness", - help="vk_harness binary (default LEONIDA_VK_HARNESS or runtime/build/linux)", - ) - ap.add_argument( - "--run", action="store_true", help="run the draw and write image.raw/image.ppm" - ) - ap.add_argument( - "--check", - action="store_true", - help="run the draw and fail if the coverage is too low", - ) - ap.add_argument( - "--list", - action="store_true", - help="list VS/PS names in the carve index and exit", - ) - a = ap.parse_args(argv) - if a.width < 1 or a.height < 1: - ap.error("--width and --height must be at least 1") - if a.min_coverage is not None and not 0.0 <= a.min_coverage <= 1.0: - ap.error("--min-coverage must be between 0 and 1") - if a.camera: - if not math.isfinite(a.yaw): - ap.error("--yaw must be finite") - if a.vs not in (None, CAMERA_VS): - ap.error(f"--camera writes the constant layout of {CAMERA_VS} only") - if a.no_fit or a.keep_z: - ap.error("--camera keeps the model's coordinates; --no-fit and --keep-z do not apply") - if not -80.0 <= a.pitch <= 80.0 or not 1.0 <= a.fov <= 150.0: - ap.error("--pitch must be within -80..80 and --fov within 1..150 degrees") - if a.dds: - ap.error("--camera and --dds both put a pointer in s9 and data at heap VA 0x100; draw the camera untextured") - a.vs = a.vs or (CAMERA_VS if a.camera else DEFAULT_VS) - if a.min_coverage is None: - a.min_coverage = 0.2 if a.camera else 0.5 - work = os.path.abspath(os.path.expanduser(a.work)) - out_dir = ( - os.path.abspath(os.path.expanduser(a.out)) - if a.out - else os.path.join(work, "first_light", "camera" if a.camera else "out") - ) - - if a.list: - if not a.game: - raise SystemExit("--list needs --game") - index = ensure_carve(os.path.abspath(a.game), work) - for e in load_json(index, "carve index", list, entry_keys=("stage", "name")): - if e["stage"] in ("vs", "ps"): - print(f"{e['stage']} {e['name']}") - return 0 - existing = os.path.join(out_dir, "manifest.json") - if a.check and not a.game and os.path.isfile(existing): - manifest = load_json(existing, "first-light manifest", dict, keys=("width", "height")) - run_draw(a, manifest, out_dir) - return 0 - if not a.game: - raise SystemExit("--game is required") - game = os.path.abspath(os.path.expanduser(a.game)) - if not a.no_fit and not a.obj: - raise SystemExit("--obj is required unless --no-fit") - if a.dds and not a.obj: - raise SystemExit("--dds requires --obj so textured probes can be checked") - - index = ensure_carve(game, work) - ps_name = a.ps if a.ps is not None else (DEFAULT_TEXTURED_PS if a.dds else DEFAULT_PS) - picked = choose(index, a.vs, ps_name) - meta = translate(work, picked) - os.makedirs(out_dir, exist_ok=True) - for entry in picked: - stem = os.path.splitext(entry["file"])[0] - stage = entry["stage"] - shutil.copy( - os.path.join(work, "first_light", "spirv", f"{stem}.spv"), - os.path.join(out_dir, f"{stage}.spv"), - ) - # For d3d12_first_light_test: the game's containers (the PSO finds each stage by the FSSM hash inside) and - # the translator's index entries, keyed vs/ps so the runtime's shader library reads vs.spv and ps.spv here. - for entry in picked: - shutil.copy( - os.path.join(work, "shaders", "dxbc", entry["file"]), - os.path.join(out_dir, f"{entry['stage']}.dxbc"), - ) - with open(os.path.join(out_dir, "index.json"), "w", encoding="utf-8", newline="\n") as f: - json.dump({"vs": meta["vs"], "ps": meta["ps"]}, f, indent=1) - vertices, indices = read_obj(a.obj) if a.obj else ([], []) - obj_sha256 = None - if a.obj: - with open(a.obj, "rb") as f: - obj_sha256 = hashlib.sha256(f.read()).hexdigest() - camera = None - if vertices and a.camera: - # The mesh keeps the model's coordinates (CAMERA_VS applies the matrices); the prediction below works on - # the same vertices projected on the CPU. - write_mesh(os.path.join(out_dir, "mesh.bin"), vertices, indices) - world, viewproj = camera_matrices(vertices, a.width, a.height, a.yaw, a.pitch, a.fov) - sgprs, heap = camera_constants(world, viewproj) - camera = { - "yaw": a.yaw, - "pitch": a.pitch, - "fov": a.fov, - "world": world, - "viewproj": viewproj, - "sgprs": sgprs, - "heap": heap, - } - vertices = project(vertices, world, viewproj) - elif vertices: - if not a.no_fit: - vertices = fit(vertices, a.width, a.height, True, not a.keep_z) - write_mesh(os.path.join(out_dir, "mesh.bin"), vertices, indices) - else: # a run without a model must not draw the mesh an earlier run left in the folder - try: - os.unlink(os.path.join(out_dir, "mesh.bin")) - except FileNotFoundError: - pass - centre_pixel = [a.width // 2, a.height // 2] - centre_uv = ( - uv_at(vertices, indices, centre_pixel[0], centre_pixel[1], a.width, a.height) - if vertices - else None - ) - clear = clear_pixel(vertices, indices, a.width, a.height) if vertices else None - probes = uv_probes(vertices, indices, a.width, a.height) if vertices else [] - manifest = { - "vs": { - "name": picked[0]["name"], - "fssm_sha256": meta["vs"].get("fssm_sha256"), - "verified": True, - }, - "ps": { - "name": picked[1]["name"], - "fssm_sha256": meta["ps"].get("fssm_sha256"), - "subgroup_size": meta["ps"].get("subgroup_size"), - "verified": True, - }, - "vertex_count": len(vertices), - "index_count": len(indices), - "triangle_count": len(indices) // 3, - "obj_sha256": obj_sha256, - "width": a.width, - "height": a.height, - "min_coverage": a.min_coverage, - "max_coverage": 0.99, - "centre_pixel": centre_pixel, - "centre_uv": list(centre_uv) if centre_uv else None, - "clear_pixel": clear, - "uv_probes": probes, - "clear": -1.0, - "camera": camera, - "files": { - "vs": "vs.spv", - "ps": "ps.spv", - "mesh": "mesh.bin", - "vs_dxbc": "vs.dxbc", - "ps_dxbc": "ps.dxbc", - "index": "index.json", - }, - } - if a.dds: - tw, th, rgba, dds_sha = decode_dds_to_rgba(a.dds) - write_texture_rgba(os.path.join(out_dir, "texture.rgba"), tw, th, rgba) - ps_meta = meta["ps"] - ptr_sgpr = next( - ( - int(r["sgpr"]) - for r in (ps_meta.get("user_sgpr_reads") or []) - if r.get("kind") in ("ptr32_lo", "ptr64_lo") - ), - DEFAULT_PTR_SGPR, - ) - lit_samplers = ps_meta.get("literal_samplers") or [] - ssharp = list(lit_samplers[0]) if lit_samplers else list(DEFAULT_SSHARP) - manifest["texture"] = { - "width": tw, - "height": th, - "dds_sha256": dds_sha, - "ptr_sgpr": ptr_sgpr, - "tsharp_va": DEFAULT_TSHARP_VA, - "ssharp": ssharp, - } - manifest["files"]["texture"] = "texture.rgba" - manifest["rgba_tolerance"] = 0.02 - if centre_uv is not None: - manifest["centre_rgba"] = sample_rgba_bilinear( - tw, th, rgba, centre_uv[0], centre_uv[1] - ) - tex_probes = rgba_probes_for_mesh( - vertices, - indices, - a.width, - a.height, - tw, - th, - rgba, - uv_probe_list=probes, - tol=manifest["rgba_tolerance"], - ) - if tex_probes: - manifest["rgba_probes"] = tex_probes - with open(os.path.join(out_dir, "manifest.json"), "w", encoding="utf-8", newline="\n") as f: - json.dump(manifest, f, indent=1) - print(f"{len(vertices)} vertices, {len(indices) // 3} triangles -> {out_dir}") - if not (a.run or a.check): - env_preview = harness_env(manifest, out_dir, base_env={}) - env_str = " ".join(f"{k}={v}" for k, v in env_preview.items()) - print( - f"run: {env_str} " - f" {os.path.join(out_dir, 'vs.spv')} {os.path.join(out_dir, 'ps.spv')} " - f"{os.path.join(out_dir, 'image.raw')} {a.width} {a.height}" - + (" (with VKH_SGPRS and VKH_HEAP from manifest.json's camera)" if camera else "") - ) - return 0 - run_draw(a, manifest, out_dir) - return 0 - - -if __name__ == "__main__": - try: # a redirected stdout is strict ANSI code page under -I; write '?' for what it cannot encode - sys.stdout.reconfigure(errors="replace") - except (AttributeError, ValueError, OSError): - pass - sys.exit(main()) diff --git a/tools/fma_mix_literal_probe.py b/tools/fma_mix_literal_probe.py deleted file mode 100644 index b1bd6e4ea..000000000 --- a/tools/fma_mix_literal_probe.py +++ /dev/null @@ -1,280 +0,0 @@ -r"""Does a v_fma_mix source with op_sel_hi and op_sel set read the high half of a 32-bit literal? A probe, standard -library only. - -A v_fma_mix* source read as f16 (op_sel_hi[i] = 1) takes the half op_sel[i] names. When two sources share one 32-bit -literal, the console compiler (in the FidelityFX DLL's FSPX code) and Mesa's ACO (`optimize_constants()` in -src/amd/compiler/aco_optimizer.cpp) both put two f16 values in it and give one source the high half. llvm-mc prints -such a literal as its low 16 bits, so the translator takes it from the blob (docs/design.md, "Printed encodings"). -That the hardware reads the high half that way is the part no one has measured. Two readings: - - halves op_sel picks the half of the 32-bit literal (what the translator does with the blob) - low the literal is 16 bits, its high half reads +0.0 (what llvm-mc's text says) - -CASES (values made up for the probe; f16 halves written hi:lo): - - A src0 = literal.lo, src2 = literal.hi op_sel:[0,0,1] op_sel_hi:[1,0,1] the shape seen in FSPX code - B src0 = literal.hi, src2 = literal.hi op_sel:[1,0,1] op_sel_hi:[1,0,1] - E src0 = v (f32), src2 = literal.hi op_sel:[0,0,1] op_sel_hi:[0,0,1] - C src0 = literal.lo, src2 = literal.lo control: both readings agree - D src0 = literal as f32, src2 = v (f32) control: an f32 literal is the whole 32 bits - -src1 is always a VGPR holding 2.0 (f32). Each case computes fma(src0, src1, src2) with values that are exact in f32, -so rounding plays no part. - -Sides: - translator tools/rdna2spirv.py on a listing whose printed encodings are llvm-mc's (the literal cut to 16 bits) - with the real bytes next to it, run in tests/semantic/spirv_mini_interp.py on the CPU. Always runs. - The text and encodings are what llvm-mc 23.1.5 prints for these bytes, except D's text: it prints - that f32 literal as lit(0x40400000), which the translator does not parse, so D's listing says - 0x40400000. - hw the instruction's exact bytes (`.long`, since LLVM's assembler can't encode the literal either) on an - AMD GPU through tools/hw_oracle (HIP on Windows, libdrm on Linux), one wave32 lane. The measurement. - - python -I tools/fma_mix_literal_probe.py # translator side only - python -I tools/fma_mix_literal_probe.py --oracle hw # + the AMD GPU in this machine - -Exit code: 0 when every side that ran follows the same reading, 1 when they differ or a side follows neither (or a -control is wrong), 2 on a harness error, 77 when the hardware side is unavailable. Nothing here reads game files. -Usage: `python -I tools/fma_mix_literal_probe.py --help` lists the options. -""" -import argparse -import os -import struct -import subprocess -import sys -import tempfile -import warnings - -HERE = os.path.dirname(os.path.abspath(__file__)) -ROOT = os.path.dirname(HERE) -sys.dont_write_bytecode = True -TOOLS_DIR = os.environ.get("LEONIDA_TOOLS_DIR") or HERE -for p in (TOOLS_DIR, os.path.join(ROOT, "tests", "semantic")): - if p not in sys.path: - sys.path.insert(0, p) - -import rdna2spirv # noqa: E402 -import spirv_mini_interp # noqa: E402 - -STUB_DXBC = b"DXBC" + bytes(24) + struct.pack("> 16) if reading == HALVES else 0.0 - - def expected(self, reading): - return f2u(self.operand(0, reading) * V2_VALUE + self.operand(2, reading)) - - def printed_literal(self): - """What llvm-mc re-encodes: the literal's low 16 bits. llvm-mc 23.1.5 does that for every v_fma_mix literal, - one that a source reads as f32 (D) too.""" - return self.literal & 0xFFFF - - def words(self, vdst, vsrc1, literal): - """The instruction's three dwords: VOP3P word 0, word 1, literal.""" - src = [LITERAL if self.srcs[0] == "lit" else 256 + vsrc1, 256 + vsrc1, - LITERAL if self.srcs[2] == "lit" else 256 + vsrc1] - w0 = (0xCC000000 | OP_FMA_MIX_F32 << 16 | self.op_sel_hi[2] << 14 | self.op_sel[2] << 13 | - self.op_sel[1] << 12 | self.op_sel[0] << 11 | vdst) - w1 = self.op_sel_hi[1] << 28 | self.op_sel_hi[0] << 27 | src[2] << 18 | src[1] << 9 | src[0] - return w0, w1, literal - - def text(self, vdst, vsrc1): - f16 = any(self.srcs[i] == "lit" and self.op_sel_hi[i] for i in (0, 2)) - lit = f"0x{self.printed_literal() if f16 else self.literal:x}" # D: hand-written, see the docstring - reg = f"v{vsrc1}" - ops = [lit if self.srcs[0] == "lit" else reg, reg, lit if self.srcs[2] == "lit" else reg] - mods = [f"{name}:[{','.join(map(str, bits))}]" for name, bits in (("op_sel", self.op_sel), - ("op_sel_hi", self.op_sel_hi)) if any(bits)] - return " ".join([f"v_fma_mix_f32 v{vdst}, {ops[0]}, {ops[1]}, {ops[2]}"] + mods) # llvm-mc omits [0,0,0] - - -CASES = ( - Case("A", ("lit", "v", "lit"), (0, 0, 1), (1, 0, 1), 0x40004200, "src0 = lo, src2 = hi (the FSPX shape)"), - Case("B", ("lit", "v", "lit"), (1, 0, 1), (1, 0, 1), 0x42004500, "src0 = hi, src2 = hi"), - Case("E", ("v", "v", "lit"), (0, 0, 1), (0, 0, 1), 0xBC004200, "src0 = v (f32), src2 = hi"), - Case("C", ("lit", "v", "lit"), (0, 0, 0), (1, 0, 1), 0x40004200, "control: src0 = src2 = lo"), - Case("D", ("lit", "v", "v"), (0, 0, 0), (0, 0, 0), 0x40400000, "control: src0 = the f32 literal"), -) - - -def is_control(case): - return case.expected(HALVES) == case.expected(LOW) - - -def verdict(results): - """(reading or None, report lines) for [(case, word or None)].""" - readings, lines = set(), [] - for case, word in results: - want = {r: case.expected(r) for r in (HALVES, LOW)} - if word is None: - got, tag = "no result", "missing" - else: - got = f"{f(word):g}" - tag = [r for r in (HALVES, LOW) if want[r] == word] - tag = ("both (control)" if is_control(case) else tag[0]) if tag else "neither" - if tag in (HALVES, LOW): - readings.add(tag) - elif tag != "both (control)": - readings.add(None) - lines.append(f" {case.name} {got:<10} halves {f(want[HALVES]):g} low {f(want[LOW]):g} -> {tag:<16} " - f"{case.what}") - reading = readings.pop() if len(readings) == 1 else None - return reading, lines - - -# ---- the translator, on the CPU ---- - -VOP1_MOV = 0x7E000200 # v_mov_b32 (VOP1 opcode 1); | vdst << 17 | src0 -EXP_MRT0_V0 = "0f 18 00 f8 00 00 00 00" -S_ENDPGM = "00 00 81 bf" -CODE_START = 0x100 - - -def hexs(*dwords): - return " ".join(f"{b:02x}" for w in dwords for b in struct.pack(" 0x3fff) can't tell them apart in nearest -mode: there both give 0x4000, and toward zero, two truncations equal one. - -The two rules differ only when the f32 rounding lands exactly on an f16 tie (or moves the value off one). CASES holds -seven such inputs, each one f16 ulp apart under the two rules, and one control where both agree: - - A 1 * 2^-40 + (1 + 2^-11) just above a tie, f32 rounds onto it, ties-to-even goes down - B 1 * -2^-40 + (1 + 3 * 2^-11) just below a tie with an odd lower neighbour: double goes up - C -1 * 2^-40 - (1 + 2^-11) A negated - D 2^-30 * 2^-30 + 2^-25 the tie between 0 and the smallest f16 subnormal (needs f16 denormals) - E 1 * -2^-20 + 65520 the overflow tie: double gives inf, single 65504 - F (1 + 2^-12) * (1 + 2^-12) + 0 the tie comes from the product (1 + 2^-11 + 2^-24), not from z - G f16 operands: (1 + 2^-7) * (2^-11 - 2^-18) + (1 + 2^-10) as B, through op_sel_hi:[1,1,1] - H 1 * 2 + 0.5 = 2.5 control - -Sides (each prints the f16 word per case and the rule its words follow): - - translator tools/rdna2spirv.py -> tests/semantic/spirv_mini_interp.py, on the CPU. Always runs. - hw the native instruction on an AMD GPU (tools/hw_oracle: HIP on Windows, libdrm on Linux), one wave32 - lane, MODE as inferred for the game (IEEE 0, DX10_CLAMP 1, f32 denormals flushed, f16 kept, nearest). - This is the measurement the docs lack. - vulkan the translated compute shader on this machine's Vulkan GPU through vk_compute_test (--build DIR, - needs spirv-as). The operands come in user SGPRs (VKC_SGPRS), so the driver can't fold them. It checks - that the driver runs the translator's sequence as written; it says nothing about RDNA2 itself. - - python -I tools/fma_mix_probe.py # translator side only - python -I tools/fma_mix_probe.py --oracle hw # + the AMD GPU in this machine - python -I tools/fma_mix_probe.py --oracle vulkan --build runtime/build - -Exit code: 0 when every side that ran follows the same rule, 1 when they differ or a side follows neither rule (or -its control is wrong), 2 on a harness error, 77 when a requested side is unavailable. Nothing here reads game files. -Usage: `python -I tools/fma_mix_probe.py --help` lists the options. -""" -import argparse -import os -import re -import struct -import subprocess -import sys -import tempfile -import warnings -from fractions import Fraction - -HERE = os.path.dirname(os.path.abspath(__file__)) -ROOT = os.path.dirname(HERE) -sys.dont_write_bytecode = True -TOOLS_DIR = os.environ.get("LEONIDA_TOOLS_DIR") or HERE -for p in (TOOLS_DIR, os.path.join(ROOT, "tests", "semantic")): - if p not in sys.path: - sys.path.insert(0, p) - -import rdna2spirv # noqa: E402 -import spirv_mini_interp # noqa: E402 - -STUB_DXBC = b"DXBC" + bytes(24) + struct.pack("> 10) & 0x1F, word & 0x3FF, -1 if word & 0x8000 else 1 - if e == 0x1F: - raise ValueError(f"f16 0x{word:04x} is not finite") - return s * (Fraction(m, 1 << 24) if e == 0 else Fraction(0x400 | m, 1 << 10) * Fraction(2) ** (e - 15)) - e, m, s = (word >> 23) & 0xFF, word & 0x7FFFFF, -1 if word >> 31 else 1 - if e == 0xFF or (e == 0 and m): - raise ValueError(f"f32 0x{word:08x} is not a finite normal or zero") - return Fraction(0) if e == 0 else s * Fraction(0x800000 | m, 1 << 23) * Fraction(2) ** (e - 127) - - -def round_rne(x, bits, emin): - """x rounded to nearest even with `bits` significand bits and subnormals below 2^emin (no overflow).""" - if x == 0: - return x - a, e = abs(x), emin - while a >= Fraction(2) ** (e + 1): - e += 1 - q = Fraction(2) ** (e - bits + 1) # the ulp at a's binade (or the subnormal ulp) - n = a / q - k, rem = n.numerator // n.denominator, n - n.numerator // n.denominator - if rem > Fraction(1, 2) or (rem == Fraction(1, 2) and k % 2): - k += 1 - return (k * q) if x > 0 else -(k * q) - - -def f16_word(x): - """f16 bits of x rounded to nearest even; |x| >= 65520 is inf.""" - r = round_rne(x, 11, -14) - s = 0x8000 if x < 0 else 0 - a = abs(r) - if a > 65504: - return s | 0x7C00 - if a < Fraction(1, 1 << 14): - return s | int(a * (1 << 24)) - e = 0 - while a >= Fraction(2) ** (e + 1): - e += 1 - while a < Fraction(2) ** e: - e -= 1 - return s | (e + 15) << 10 | int((a / Fraction(2) ** e - 1) * 1024) - - -def expected(case): - """{"single": word, "double": word}: the f16 result under each rule.""" - x, y, z = (operand(w, case.f16) for w in case.words) - exact = x * y + z - return {SINGLE: f16_word(exact), DOUBLE: f16_word(round_rne(exact, 24, -126))} - - -def half(case, word): - """The f16 a case wrote, or None when the other half of the destination lost the sentinel.""" - keep, mine = (word & 0xFFFF, word >> 16) if case.hi else (word >> 16, word & 0xFFFF) - other = SENTINEL & 0xFFFF - return mine if keep == other else None - - -def verdict(results): - """results: [(case, word or None)]. Returns (rule or None, one line per case). The rule is the one every - discriminating case follows, with the control right; None when the words follow neither or a mix.""" - rules, lines = set(), [] - for case, word in results: - want = expected(case) - h = None if word is None else half(case, word) - if word is None: - got, tag = "no result", "missing" - elif h is None: - got, tag = f"0x{word:08x}", "other half not kept" - else: - got = f"0x{h:04x}" - tag = [r for r in (SINGLE, DOUBLE) if want[r] == h] - tag = ("both (control)" if want[SINGLE] == want[DOUBLE] else tag[0]) if tag else "neither" - if tag in (SINGLE, DOUBLE): - rules.add(tag) - elif tag != "both (control)": - rules.add(None) - lines.append(f" {case.name} {case.op:<16} {got:<12} single 0x{want[SINGLE]:04x} double 0x{want[DOUBLE]:04x}" - f" -> {tag:<16} {case.what}") - rule = rules.pop() if len(rules) == 1 else None - return rule, lines - - -# ---- the translator, on the CPU ---- - -def _translate(work, name, text, fssm=None): - os.makedirs(os.path.join(work, "disasm"), exist_ok=True) - src = os.path.join(work, "disasm", name + ".s") - with open(src, "w", encoding="utf-8", newline="\n") as f: - f.write(text) - with open(os.path.join(work, name + ".dxbc"), "wb") as f: - f.write(STUB_DXBC) - if fssm is not None: - os.makedirs(os.path.join(work, "fssm"), exist_ok=True) - with open(os.path.join(work, "fssm", name + ".fssm"), "wb") as f: - f.write(fssm) - with warnings.catch_warnings(): - warnings.simplefilter("ignore", ResourceWarning) - return rdna2spirv.translate(src) - - -def ps_listing(case): - """A pixel shader that runs one case and exports the destination word as mrt0.x.""" - x, y, z = case.words - body = [f"v_mov_b32 v1, 0x{x:x}", f"v_mov_b32 v2, 0x{y:x}", f"v_mov_b32 v3, 0x{z:x}", - f"v_mov_b32 v0, 0x{SENTINEL:x}", f"{case.op} v0, v1, v2, v3{case.mods}", "exp mrt0 v0, v0, v0, v0 done vm", - "s_endpgm"] - return "; fma_mix_probe\n" + "".join(f"\t{ln}\n" for ln in body) - - -def run_translator(cases=CASES): - out = [] - with tempfile.TemporaryDirectory(prefix="fma_mix_probe_") as work: - for case in cases: - spv = _translate(work, f"ps_fma_mix_{case.name}", ps_listing(case)) - out.append(spirv_mini_interp.run_fragment(spv)["%out_mrt0"][0]) - return out - - -# ---- the translated compute shader on a Vulkan GPU ---- -# s[0:3] is the output V#, then three operand words per case in s4.. (VKC_SGPRS), the workgroup id after them. - -FIRST_RESULT = 10 - - -def cs_rsrc2(cases): - user = 4 + 3 * len(cases) - if user > 32: - raise ValueError("too many cases for the user SGPRs") - return 0x8080 | user << 1 # USER_SGPR [5:1], TGID_X_EN, 512 bytes of LDS (as build.py's default) - - -def cs_listing(cases=CASES): - """One thread runs every case from its SGPR operands and stores the destination words at offset 0, 4, ...""" - body = [] - for k, case in enumerate(cases): - s = 4 + 3 * k - d = FIRST_RESULT + k - body += [f"v_mov_b32 v1, s{s}", f"v_mov_b32 v2, s{s + 1}", f"v_mov_b32 v3, s{s + 2}", - f"v_mov_b32 v{d}, 0x{SENTINEL:x}", f"{case.op} v{d}, v1, v2, v3{case.mods}"] - for k in range(len(cases)): - body += [f"v_mov_b32 v4, {4 * k}", f"buffer_store_dword v{FIRST_RESULT + k}, v4, s[0:3], 0 offen"] - body.append("s_endpgm") - return "; fma_mix_probe\n" + "".join(f"\t{ln}\n" for ln in body) - - -def cs_fssm(cases=CASES): - header = bytearray(0x148) - struct.pack_into("<4I", header, 0x138, cs_rsrc2(cases), 1, 1, 1) - return bytes(header) - - -def sgpr_words(cases=CASES): - return [w for case in cases for w in case.words] - - -def translate_cs(work, cases=CASES): - return _translate(work, "cs_fma_mix_probe", cs_listing(cases), cs_fssm(cases)) - - -def run_vulkan(build, cases=CASES): - """[word per case] from vk_compute_test, or raise RuntimeError with the reason (Unavailable-like: FileNotFound).""" - sys.path.insert(0, os.path.join(ROOT, "runtime", "test", "shaders")) - from compute_fixture import find_test_program - folder = find_test_program(build, "vk_compute_test") - if folder is None: - raise FileNotFoundError(f"vk_compute_test is not built in {build}") - exe = os.path.join(folder, "vk_compute_test" + (".exe" if os.name == "nt" else "")) - if len(cases) > 8: - raise ValueError("vk_compute_test prints eight words") - with tempfile.TemporaryDirectory(prefix="fma_mix_probe_") as work: - text = translate_cs(work, cases) - sa, sv = os.path.join(work, "cs.spvasm"), os.path.join(work, "cs.spv") - with open(sa, "w", encoding="utf-8", newline="\n") as f: - f.write(text) - try: - r = subprocess.run(["spirv-as", sa, "-o", sv, "--target-env", "vulkan1.2"], capture_output=True, text=True) - except FileNotFoundError: - raise FileNotFoundError("spirv-as is not on PATH (SPIRV-Tools)") from None - if r.returncode: - raise RuntimeError("spirv-as failed: " + (r.stderr or r.stdout).strip()[:300]) - env = dict(os.environ, VKC_SGPRS=",".join(f"0x{w:x}" for w in sgpr_words(cases))) - r = subprocess.run([exe, sv, "1", "dump"], capture_output=True, text=True, env=env, timeout=120) - msg = r.stdout + r.stderr - m = re.search(r"^out\[0\.\.7\] = ((?:[0-9]+ ){7}[0-9]+)$", msg, re.MULTILINE) - if r.returncode == 77: - raise FileNotFoundError("vk_compute_test: no usable Vulkan device (exit 77)") - if r.returncode or not m: - raise RuntimeError(f"vk_compute_test exited {r.returncode}: {msg.strip()[-300:]}") - return [int(x) for x in m.group(1).split()][:len(cases)] - - -# ---- the native instruction on an AMD GPU ---- - -HW_MODE = {"ieee": 0, "dx10_clamp": 1, "denorm32": 0, "denorm16_64": 3, "round16_64": 0} - - -def hw_lines(case): - x, y, z = case.words - return [f"v_mov_b32 v1, 0x{x:x}", f"v_mov_b32 v2, 0x{y:x}", f"v_mov_b32 v3, 0x{z:x}", - f"v_mov_b32 v8, 0x{SENTINEL:x}", f"{case.op} v8, v1, v2, v3{case.mods}", "v_mov_b32 v20, 0", - "global_store_b32 v20, v8, s[2:3]", "s_endpgm"] - - -def run_hw(oracle, cases=CASES): - from hw_oracle import asm - got = oracle.run([asm.Kernel(hw_lines(c), 32, 1, 1, raw=True, mode=HW_MODE) for c in cases], words=1) - return [None if isinstance(w, str) else w[0] for w in got], [w for w in got if isinstance(w, str)] - - -# ---- driver ---- - -def report(side, results): - rule, lines = verdict(results) - print(f"{side}: {'follows ' + rule + ' rounding' if rule else 'follows neither rule'}") - for ln in lines: - print(ln) - return rule - - -def main(argv=None): - ap = argparse.ArgumentParser(description=__doc__.split("\n", 1)[0]) - ap.add_argument("--oracle", default="translator", - help="comma-separated sides besides the translator, which always runs: hw, vulkan") - ap.add_argument("--build", help="the runtime build folder holding vk_compute_test (for --oracle vulkan)") - ap.add_argument("--hw-arch", help="GPU architecture to assemble for (default: detected; LEONIDA_HW_ARCH)") - a = ap.parse_args(argv) - sides = {s.strip() for s in a.oracle.split(",") if s.strip()} - {"translator"} - if sides - {"hw", "vulkan"}: - ap.error(f"unknown --oracle side(s): {', '.join(sorted(sides - {'hw', 'vulkan'}))}") - if "vulkan" in sides and not a.build: - ap.error("--oracle vulkan needs --build DIR") - for case in CASES: # the table itself: seven inputs that tell the rules apart, one that doesn't - want = expected(case) - if (want[SINGLE] == want[DOUBLE]) != case.what.startswith("control"): - print(f"harness error: case {case.name} does not discriminate as described") - return 2 - rules = [] - try: - rules.append(report("translator", list(zip(CASES, run_translator())))) - if "vulkan" in sides: - try: - words = run_vulkan(a.build) - except FileNotFoundError as e: - print(f"vulkan side unavailable: {e}") - return 77 - rules.append(report("vulkan (translated, this GPU)", list(zip(CASES, words)))) - if "hw" in sides: - from hw_oracle import runner - try: - oracle = runner.open_oracle(arch=a.hw_arch) - except runner.Unavailable as e: - print(f"hardware oracle unavailable: {e}") - return 77 - try: - print(f"hardware oracle: {oracle.device}") - words, rejected = run_hw(oracle) - finally: - oracle.close() - for why in rejected: - print(f" {why}") - rules.append(report(f"hw (native, {oracle.arch})", list(zip(CASES, words)))) - except (RuntimeError, OSError, subprocess.SubprocessError, spirv_mini_interp.UnsupportedConstruct) as e: - print(f"harness error: {e}") - return 2 - if None in rules or len(set(rules)) != 1: - print("sides disagree" if None not in rules else "a side follows neither rule") - return 1 - print(f"all sides follow {rules[0]} rounding") - return 0 - - -if __name__ == "__main__": - try: # a redirected stdout is strict ANSI code page under -I; write '?' for what it cannot encode - sys.stdout.reconfigure(errors="replace") - except (AttributeError, ValueError, OSError): - pass - sys.exit(main()) diff --git a/tools/fmisc_diff.py b/tools/fmisc_diff.py deleted file mode 100644 index b5196ae62..000000000 --- a/tools/fmisc_diff.py +++ /dev/null @@ -1,878 +0,0 @@ -r"""Differential fuzzing of the 32-bit float VALU ops no other fuzzer generates, and of float compares. Standard -library only. - -Generates seeded straight-line programs, one lane, runs them through - - * the reference below, written from the RDNA2 ISA guide's pseudocode for each opcode with exact rational - arithmetic and one round-to-nearest-even per operation, and - * tools/rdna2spirv.py, executing the SPIR-V with tests/semantic/spirv_mini_interp.py (lane 0 of a wave32), - -and compares four exported words bit for bit (v8..v11), except that any NaN matches any NaN. The reference does -not share code with the translator, with tools/cpu_ref.py or with the other fuzzers. tools/f32_fuzz.py covers the -float arithmetic (add, mul, fma, floor, the transcendentals, v_cmp_class_f32 without modifiers, ...); this tool -covers the ops it does not generate. - -What is modelled, per instruction (OPS, --list-ops): - * v_fract_f32: S0 - floor(S0), at most 0x3f7fffff (a tiny negative S0 would round to 1.0); +-inf gives - 0xffc00000, a NaN comes back unchanged (a signalling one too); an integer gives +0. - * v_frexp_mant_f32 / v_frexp_exp_i32_f32: S0 = mant * 2^exp, mant in [0.5, 1) with S0's sign. +-0 gives +-0 and - 0; +-inf and NaN give S0 (mant) and 0 (exp). - * v_ldexp_f32 (VOP3 only): S0 * 2^S1, S1 a signed integer; overflow is +-inf, +-inf / +-0 / NaN pass through. - * v_cvt_u32_f32 / v_cvt_i32_f32: truncate toward zero, saturate; NaN gives 0. - * v_cvt_off_f32_i4: the signed 4-bit S0[3:0] / 16. - * v_fmamk_f32: S0 * K + S1 with one rounding, K the literal. - * v_cmp__f32 for all 16 conditions (VOPC e32 into vcc_lo; e64 into s20, s21 or vcc_lo) and - v_cmp_class_f32 e64, each followed by v_cndmask_b32_e64 on the mask (one lane: the mask is that lane's bit). - The class bits are 0 signalling NaN, 1 quiet NaN, 2 -inf, 3 -normal, 4 -denormal, 5 -0, 6 +0, 7 +denormal, - 8 +normal, 9 +inf. - * VOP3 neg and abs on float sources (abs first), and on float results mul:2 / mul:4 / div:2 then clamp to [0, 1]. - * sources: VGPRs v0..v7 and v12..v19, SGPRs s4..s19, integer and float inline constants and literals, at most one - literal and two scalar values per VOP3 instruction (the GFX10 constant bus); an e32 VOPC or VOP1 takes a literal - only in src0. -Every rule was checked against an RDNA2 GPU (AMD Radeon iGPU, gfx1036, Windows driver 26.10.1) with --oracle hw. - -Not judged (the program is skipped with the reason, counted): a denormal operand or result (whether f32 denormals -are flushed is the MODE question, SHADER-35), a NaN whose payload is later read as an integer (payloads are not -modelled), the clamp of a NaN and an output modifier whose result is a zero (tools/f32_fuzz.py measures both), and -an output modifier on a signalling-NaN result (the translator's multiply quiets it, which a later v_cmp_class sees; -whether the hardware does is not measured). - -Known divergences (KNOWN_DIVERGENCES): by default the generator leaves out the forms where the translator is known to -differ from the hardware, so that a run shows new problems only; --known puts them back (a hardware-only run always -has them): - * class-snan-mods: v_cmp_class_f32 with neg or abs on its float source. The hardware flips or clears the sign bit - of a signalling NaN and still reports it as signalling (class bit 0). The translator applies the modifier with - OpFNegate / FAbs, so the result depends on whether the float operation keeps the NaN signalling; in - tests/semantic/spirv_mini_interp.py it does not, and the NaN tests as quiet (bit 1). Posted as a finding in the - coordination issue (#2300). - -With --oracle hw the same programs also run natively on an AMD GPU (tools/hw_oracle/), one lane of a wave32 compute -dispatch under the MODE inferred for the game's shaders (HW_MODE: IEEE off, f32 denormals flushed; with IEEE on the -hardware ignores omod), and the four words are compared with the reference: that validates the reference itself. -Without the oracle tools the run exits 77. - -Usage: - python -I tools/fmisc_diff.py [--programs N] [--seed S] [--max-ops N] [--ops v_ldexp_f32,cmp,class] - python -I tools/fmisc_diff.py --no-literals # sources without literals - python -I tools/fmisc_diff.py --known # also the forms in KNOWN_DIVERGENCES - python -I tools/fmisc_diff.py --oracle hw # hardware vs reference only - python -I tools/fmisc_diff.py --oracle translator,hw - python -I tools/fmisc_diff.py --list-ops - python -I tools/fmisc_diff.py --self-test - -Exit 0 when every program matches, 1 on a mismatch (the shortest failing program is printed after removing -instructions that do not matter), 2 on a harness error or when every program was skipped (nothing was compared), 77 when the requested hardware oracle is unavailable. -Skips are counted with their reasons. -""" -import argparse -import gc -import math -import os -import random -import re -import struct -import sys -import tempfile -import warnings -from fractions import Fraction - -HERE = os.path.dirname(os.path.abspath(__file__)) -sys.dont_write_bytecode = True -if HERE not in sys.path: - sys.path.insert(0, HERE) -SEM_DIR = os.path.join(os.path.dirname(HERE), "tests", "semantic") -if SEM_DIR not in sys.path: - sys.path.insert(0, SEM_DIR) - -M32 = 0xFFFFFFFF -STUB_DXBC = b"DXBC" + bytes(24) + struct.pack("> 31 else x - - -# ---- f32 helpers (exact) -------------------------------------------------------------------------------------- - -def is_nan(w): - return (w & 0x7F800000) == 0x7F800000 and (w & 0x7FFFFF) != 0 - - -def is_inf(w): - return (w & 0x7FFFFFFF) == PINF - - -def is_zero(w): - return w & 0x7FFFFFFF == 0 - - -def is_denorm(w): - return (w & 0x7F800000) == 0 and (w & 0x7FFFFF) != 0 - - -def to_frac(w): - """The exact value of a finite f32 bit pattern.""" - e, m = (w >> 23) & 0xFF, w & 0x7FFFFF - v = Fraction(m, 1 << 149) if e == 0 else Fraction(m | 0x800000) * Fraction(2) ** (e - 150) - return -v if w >> 31 else v - - -def round_f32(fr, neg_zero=False): - """An exact rational rounded to f32 (nearest even), overflow to inf. A result below 2^-150 in magnitude is a - zero in every denormal mode; one between that and the smallest normal raises Uncertain.""" - if fr == 0: - return 0x80000000 if neg_zero else 0 - sign = 0x80000000 if fr < 0 else 0 - a = abs(fr) - if a < Fraction(1, 1 << 150): - return sign - e = a.numerator.bit_length() - a.denominator.bit_length() - while Fraction(2) ** e > a: - e -= 1 - while Fraction(2) ** (e + 1) <= a: - e += 1 - if e < -126: - raise Uncertain("denormal result") - scaled = a / Fraction(2) ** (e - 23) # in [2^23, 2^24) - q, r = divmod(scaled.numerator, scaled.denominator) - if 2 * r > scaled.denominator or (2 * r == scaled.denominator and q & 1): - q += 1 - if q == 1 << 24: - q, e = q >> 1, e + 1 - if e > 127: - return sign | PINF - return sign | ((e + 127) << 23) | (q & 0x7FFFFF) - - -def fract(w): - # Measured on gfx1036 (docs/design.md, "Float min/max/med3 with NaN, v_fract"): a NaN comes back unchanged, a - # signalling one too (v_cmp_class_f32 still reports class bit 0), and +-inf gives exactly 0xffc00000. - if is_nan(w): - return w - if is_inf(w): - return 0xFFC00000 - fr = to_frac(w) - r = fr - math.floor(fr) - if r == 0: - return 0 # S0 + -floor(S0): x + -x is +0, so is -0 + +0 - return min(round_f32(r), 0x3F7FFFFF) - - -def frexp_mant(w): - if is_nan(w) or is_inf(w) or is_zero(w): - return w - return (w & 0x807FFFFF) | (126 << 23) - - -def frexp_exp(w): - if is_nan(w) or is_inf(w) or is_zero(w): - return 0 - return (((w >> 23) & 0xFF) - 126) & M32 - - -def ldexp(w, n): - if is_nan(w) or is_inf(w) or is_zero(w): - return w - n = max(-400, min(400, s32(n))) # past +-400 every finite f32 overflows or vanishes - return round_f32(to_frac(w) * Fraction(2) ** n, bool(w >> 31)) - - -def cvt_u32(w): - if is_nan(w): - return 0 - if is_inf(w): - return 0 if w >> 31 else M32 - return max(0, min(M32, math.trunc(to_frac(w)))) - - -def cvt_i32(w): - if is_nan(w): - return 0 - if is_inf(w): - return 0x80000000 if w >> 31 else 0x7FFFFFFF - return max(-(1 << 31), min((1 << 31) - 1, math.trunc(to_frac(w)))) & M32 - - -def cvt_off(w): - n = w & 0xF - return round_f32(Fraction(n - 16 if n & 8 else n, 16)) - - -def fmamk(a, k, b): - if is_nan(a) or is_nan(k) or is_nan(b): - return QNAN - if is_inf(a) or is_inf(k): - if is_zero(a) or is_zero(k): - return QNAN - p = PINF | ((a ^ k) & 0x80000000) - if is_inf(b) and b != p: - return QNAN - return p - if is_inf(b): - return b - prod = to_frac(a) * to_frac(k) - fr = prod + to_frac(b) - neg_zero = prod == 0 and bool((a ^ k) >> 31) and bool(b >> 31) # -0 + -0; any other exact zero is +0 - return round_f32(fr, neg_zero) - - -def class_bits(w): - if is_nan(w): - return 1 << (1 if (w >> 22) & 1 else 0) - neg = w >> 31 - if is_inf(w): - return 1 << (2 if neg else 9) - if is_zero(w): - return 1 << (5 if neg else 6) - if is_denorm(w): - return 1 << (4 if neg else 7) - return 1 << (3 if neg else 8) - - -def fcmp(c, a, b): - if is_nan(a) or is_nan(b): - lt = eq = gt = False - un = True - else: - fa = math.inf if a == PINF else -math.inf if a == NINF else to_frac(a) - fb = math.inf if b == PINF else -math.inf if b == NINF else to_frac(b) - lt, eq, gt, un = fa < fb, fa == fb, fa > fb, False - return {"f": False, "lt": lt, "eq": eq, "le": lt or eq, "gt": gt, "lg": lt or gt, "ge": gt or eq, - "o": not un, "u": un, "nge": not (gt or eq), "nlg": not (lt or gt), "ngt": not gt, - "nle": not (lt or eq), "neq": not eq, "nlt": not lt, "tru": True}[c] - - -# name -> (form, float source mask, float result, fn). form: vop1 (e32 and e64), vop3 (VOP3 only), fmamk. -OPS = { - "v_fract_f32": ("vop1", (1,), True, fract), - "v_frexp_mant_f32": ("vop1", (1,), True, frexp_mant), - "v_frexp_exp_i32_f32": ("vop1", (1,), False, frexp_exp), - "v_cvt_u32_f32": ("vop1", (1,), False, cvt_u32), - "v_cvt_i32_f32": ("vop1", (1,), False, cvt_i32), - "v_cvt_off_f32_i4": ("vop1", (0,), True, cvt_off), - "v_ldexp_f32": ("vop3", (1, 0), True, ldexp), - "v_fmamk_f32": ("fmamk", (1, 1, 1), True, fmamk), -} -ALL_OPS = sorted(OPS) + ["class", "cmp"] # cmp / class: a VOPC compare into a mask, then v_cndmask_b32_e64 on it - -VK_CONSTANTS = False # --vk-constants: leave the seeds as literals in the vk programs -KNOWN = False # also generate the forms in KNOWN_DIVERGENCES (--known; always on for a hardware-only run) -LITERALS = True -KNOWN_DIVERGENCES = { - "class-snan-mods": "v_cmp_class_f32 with neg/abs on a signalling NaN: the hardware reports it as signalling, the " - "translator's OpFNegate / FAbs can quiet it (it does in spirv_mini_interp)", -} - - -# ---- program generation ------------------------------------------------------------------------------------- - -def fval(rng): - r = rng.random() - if r < 0.55: - return rng.choice(FVALS) - if r < 0.8: - return round_f32(Fraction(rng.randint(-2000, 2000), rng.choice((1, 2, 3, 4, 7, 8, 1024)))) - return (rng.getrandbits(1) << 31) | (rng.randint(1, 254) << 23) | rng.getrandbits(23) - - -def ival(rng): - return (rng.choice(NVALS) if rng.random() < 0.7 else rng.randint(-300, 300)) & M32 - - -def fconst(rng): - """An inline constant for a float source: a float one, or an integer one whose bits are not a denormal.""" - return rng.choice(tuple(INLINE_F)) if rng.random() < 0.7 else str(rng.choice((0, -1, -2, -16))) - - -class Gen: - def __init__(self, rng): - self.r = rng - - def vreg(self, flt=True): - """A VGPR; mostly one seeded with the kind of value the source reads (an integer read as a float is mostly - a denormal, which the reference does not judge).""" - return f"v{self.r.choice(VREGS if self.r.random() < 0.15 else FLT_V if flt else INT_V)}" - - def src(self, st, flt, vop3, lit_ok=True, mods=True): - """One source; st = [scalar values used, literal used]. VOP3 float sources may get neg / abs (mods).""" - r = self.r - k = r.random() - if k < 0.5: - t = self.vreg(flt) - elif k < 0.75: - s = f"s{r.choice(SREGS if r.random() < 0.15 else FLT_S if flt else INT_S)}" - if s not in st[0] and len(st[0]) >= (2 if vop3 else 1): - t = self.vreg(flt) - else: - st[0].add(s) - t = s - elif k < 0.9 or not (LITERALS and lit_ok and not st[1] and len(st[0]) < (2 if vop3 else 1)): - t = fconst(r) if flt else str(r.randint(-16, 64)) - else: - v = fval(r) if flt else ival(r) - if -16 <= s32(v) <= 64 or v in INLINE_F.values(): - v = 0x7FC00001 if flt else 0x12345 - t = f"0x{v:x}" - st[0].add("lit") - st[1] = True - if vop3 and flt and mods and t[0] in "vs": - if r.random() < 0.3: - t = f"|{t}|" - if r.random() < 0.3: - t = f"-{t}" - return t - - def outmods(self): - r = self.r - m = " clamp" if r.random() < 0.2 else "" # GFX10's assembler wants clamp before the omod - if r.random() < 0.25: - m += " " + r.choice(("mul:2", "mul:4", "div:2")) - return m - - def op(self, ops): - r = self.r - name = r.choice(ops) - d = r.choice(INT_V if name in OPS and not OPS[name][2] else FLT_V) - st = [set(), False] - if name in ("cmp", "class"): - m = r.choice(MASKS) - sel = f"v_cndmask_b32_e64 v{d}, 0, 1.0, {m}" - if name == "class": - a = self.src(st, True, True, mods=KNOWN) - mask = self.src(st, False, True) - return [f"v_cmp_class_f32_e64 {m}, {a}, {mask}", sel] - c = r.choice(FCMP) - if r.random() < 0.4: - a = self.src(st, True, False) - return [f"v_cmp_{c}_f32_e32 vcc_lo, {a}, {self.vreg()}", sel.replace(f", {m}", ", vcc_lo")] - a, b = self.src(st, True, True), self.src(st, True, True) - return [f"v_cmp_{c}_f32_e64 {m}, {a}, {b}", sel] - form, fin, fout, _ = OPS[name] - if form == "vop1": - if r.random() < 0.4: - return [f"{name}_e32 v{d}, {self.src(st, fin[0], False)}"] - return [f"{name}_e64 v{d}, {self.src(st, fin[0], True)}{self.outmods() if fout else ''}"] - if form == "vop3": - a = self.src(st, True, True) - return [f"{name} v{d}, {a}, {self.src(st, False, True)}{self.outmods()}"] - # fmamk: src0 any (an SGPR or inline constant next to the literal K), K, then a VGPR - st = [set(), True] # K is the literal: one more scalar value fits - return [f"v_fmamk_f32 v{d}, {self.src(st, True, False)}, 0x{fval(r):x}, {self.vreg()}"] - - -def seeds(rng): - return ([f"v_mov_b32_e32 v{v}, 0x{(ival if v in INT_V else fval)(rng):x}" for v in VREGS] - + [f"s_mov_b32 s{s}, 0x{(ival if s in INT_S else fval)(rng):x}" for s in SREGS]) - - -def observe(regs): - return [f"v_mov_b32_e32 v{8 + i}, v{r}" for i, r in enumerate(regs)] - - -def generate(rng, n_ops, ops): - gen = Gen(rng) - body = [] - for _ in range(n_ops): - body += gen.op(ops) - written = [] - for line in reversed(body): - if line.startswith("v_cmp"): - continue - dst = int(line.split()[1].rstrip(",")[1:]) - if dst not in written: - written.append(dst) - regs = written[:4] - regs += [rng.choice(VREGS) for _ in range(4 - len(regs))] - return seeds(rng) + body + observe(regs) - - -# ---- the reference interpreter -------------------------------------------------------------------------------- - -_OMOD = {"mul:2": Fraction(2), "mul:4": Fraction(4), "div:2": Fraction(1, 2)} - - -def parse(rest): - mods = {} - keep = [] - for t in rest.split(" "): - if t in _OMOD: - mods["omod"] = t - elif t == "clamp": - mods["clamp"] = True - else: - keep.append(t) - return [a.strip() for a in " ".join(keep).split(",")], mods - - -def raw(tok, st): - if re.fullmatch(r"v\d+", tok): - return st["v"].get(int(tok[1:]), 0) - if re.fullmatch(r"s\d+|vcc_lo", tok): - if tok not in st["s"]: - raise RefError(f"{tok} read before it is written") - return st["s"][tok] - if tok in INLINE_F: - return INLINE_F[tok] - return int(tok, 0) & M32 - - -def ivalue(tok, st): - if re.fullmatch(r"v\d+", tok) and int(tok[1:]) in st["nan"]: - raise Uncertain("a computed NaN read as an integer") - return raw(tok, st) - - -def fvalue(tok, st): - neg = tok.startswith("-") and not tok[1:2].isdigit() - if neg: - tok = tok[1:] - ab = tok.startswith("|") - w = raw(tok.strip("|"), st) - if ab: - w &= 0x7FFFFFFF - if neg: - w ^= 0x80000000 - if is_denorm(w): - raise Uncertain("denormal operand") - return w - - -def out_mods(w, mods): - om = mods.get("omod") - if om and is_nan(w) and not w & 0x400000: - raise Uncertain("output modifier on a signalling NaN") - if om and not (is_nan(w) or is_inf(w)): - v = to_frac(w) * _OMOD[om] - if v == 0: - raise Uncertain("output modifier on a zero") - w = round_f32(v) - if mods.get("clamp"): - if is_nan(w): - raise Uncertain("clamp of a NaN") - w = 0 if w >> 31 else min(w, 0x3F800000) - return w - - -def reference(lines): - """Run the program; returns the four exported words. Raises Uncertain for what it does not judge.""" - st = {"v": {}, "s": {}, "nan": set()} # nan: VGPRs holding a computed NaN (payload not modelled) - for line in lines: - op, _, rest = line.partition(" ") - args, mods = parse(rest) - if op == "s_mov_b32": - st["s"][args[0]] = raw(args[1], st) - continue - if op.startswith("v_cmp_"): - a = fvalue(args[1], st) - if op.startswith("v_cmp_class_f32"): - bit = class_bits(a) & ivalue(args[2], st) - else: - bit = fcmp(op[len("v_cmp_"):].split("_f32")[0], a, fvalue(args[2], st)) - st["s"][args[0]] = int(bool(bit)) - continue - d = int(args[0][1:]) - if op in ("v_mov_b32_e32", "v_cndmask_b32_e64"): - src = args[1] if op == "v_mov_b32_e32" else args[2 if raw(args[3], st) & 1 else 1] - st["v"][d] = raw(src, st) - nan = re.fullmatch(r"v\d+", src) and int(src[1:]) in st["nan"] - (st["nan"].add if nan else st["nan"].discard)(d) - continue - base = op[:-4] if op.endswith(("_e32", "_e64")) else op - if base not in OPS: - raise RefError(f"{op} is not modelled") - form, fin, fout, fn = OPS[base] - if form == "fmamk": - vals = [fvalue(args[1], st), fvalue(args[2], st), fvalue(args[3], st)] - else: - vals = [fvalue(t, st) if fin[i] else ivalue(t, st) for i, t in enumerate(args[1:])] - w = fn(*vals) & M32 - if fout: - if is_denorm(w): - raise Uncertain("denormal result") - w = out_mods(w, mods) - (st["nan"].add if fout and is_nan(w) else st["nan"].discard)(d) - st["v"][d] = w - return [st["v"].get(8 + i, 0) for i in range(4)] - - -# ---- the translator side ----------------------------------------------------------------------------------- - -def translated(lines, name="ps_fmisc"): - """Translate and execute; returns the four exported words, or raises Skip.""" - import rdna2spirv - from spirv_mini_interp import run_fragment - with tempfile.TemporaryDirectory(prefix="fmisc-diff-") as tmp: - dis = os.path.join(tmp, "disasm") - os.mkdir(dis) - path = os.path.join(dis, name + ".s") - with open(path, "w", encoding="utf-8", newline="\n") as f: - f.write(f"; {name} fmisc_diff case\n") - for line in lines: - f.write("\t" + line + "\n") - f.write("\texp mrt0 v8, v9, v10, v11 done vm\n\ts_endpgm\n") - with open(os.path.join(tmp, name + ".dxbc"), "wb") as f: - f.write(STUB_DXBC) - try: - with warnings.catch_warnings(): - warnings.simplefilter("ignore", ResourceWarning) - spvasm = rdna2spirv.translate(path) - gc.collect() - except rdna2spirv.Unsupported as e: - raise Skip(f"translator unsupported: {e}") from None - try: - out = run_fragment(spvasm) - except Exception as e: # noqa: BLE001 - an interpreter gap is a counted skip, never a pass - raise Skip(f"mini_interp: {type(e).__name__}: {str(e)[:80]}") from None - return [w & M32 for w in out["%out_mrt0"]] - - -# The float MODE the hardware kernels start with: the one docs/design.md infers for the game's shaders (IEEE off, -# DX10_CLAMP on, f32 denormals flushed; tools/f32_fuzz.py's "flush"). The assembler's compute default has IEEE on, -# under which the hardware ignores omod (measured: v_fract_f32_e64 v4, -v16 mul:2 with v16 = 0.5 gives 0.5). -HW_MODE = {"ieee": 0, "dx10_clamp": 1, "denorm32": 0} - - -def hw_kernel(lines, wave=32): - """A raw kernel for tools/hw_oracle: the program on one lane, then v8..v11 stored at the output pointer. wave 64 - runs it in a wave64 wave with the lane masks as 64-bit pairs.""" - from hw_oracle import asm - if wave == 64: - import vk_fuzz_run - lines = [vk_fuzz_run.wave64_text(ln) for ln in lines] - return asm.Kernel(list(lines) + ["v_mov_b32 v0, 0", "global_store_b128 v0, v[8:11], s[2:3]", "s_endpgm"], - wave=wave, threads=1, words=4, raw=True, mode=HW_MODE) - - -# ---- comparison, shrinking, the run -------------------------------------------------------------------------- - -def _diff(lines, want, got, label): - bad = [k for k in range(4) if want[k] != got[k] and not (is_nan(want[k]) and is_nan(got[k]))] - if not bad: - return None - i = bad[0] - return f"word {i} ({lines[-N_OBS + i].split(', ')[1]}): reference 0x{want[i]:08x}, {label} 0x{got[i]:08x}" - - -def check(lines, backends=("translator",), hw=None): - """None on a match, else a description. Raises Skip (every backend skipped, or Uncertain) / RefError. - hw is the hardware result for this program (four words or a str reason), or a callable lines -> that.""" - want = reference(lines) - problems, skips = [], [] - if "translator" in backends: - try: - problems.append(_diff(lines, want, translated(lines), "translated")) - except Skip as e: - skips.append(e) - if "hw" in backends: - got = hw(lines) if callable(hw) else hw - if got is None: - raise RuntimeError("no result from the hardware runner") - if isinstance(got, str): - skips.append(Skip(f"hardware: {got}")) - elif len(got) < 4: - raise RuntimeError(f"the hardware runner returned {len(got)} words (expected 4)") - else: - problems.append(_diff(lines, want, got, "hardware")) - if skips and len(skips) == len(backends): - raise skips[0] - return "; ".join(p for p in problems if p) or None - - -def shrink(lines, check_fn=check): - """Observe one register if that still fails, drop instructions (a compare and its v_cndmask together) while the - program still mismatches, then the seeds of registers nothing reads.""" - def fails(trial): - try: - return bool(check_fn(trial)) - except (Skip, RefError): - return False - seed, body, obs = lines[:N_SEED], lines[N_SEED:-N_OBS], lines[-N_OBS:] - for line in obs: - one = [line.replace(line.split()[1], f"v{8 + i},") for i in range(4)] - if fails(seed + body + one): - obs = one - break - changed = True - while changed: - changed = False - i = len(body) - 1 - while i >= 0: - n = 2 if body[i].startswith("v_cndmask") and i and body[i - 1].startswith("v_cmp") else 1 - trial = body[:i + 1 - n] + body[i + 1:] - if fails(seed + trial + obs): - body, changed = trial, True - i -= n - used = set() - for line in body + obs: - used |= set(re.findall(r"\b[vs]\d+\b", line.partition(" ")[2])) - seed = [line for line in seed if line.split()[1].rstrip(",") in used] - return seed + body + obs - - -def omod_writer(lines, k): - """Whether the last instruction that wrote the register observed as word k carries an output modifier.""" - reg = lines[-N_OBS + k].split(", ")[1] - for line in reversed(lines[:-N_OBS]): - op, _, rest = line.partition(" ") - if rest.split(",")[0].strip() == reg and not op.startswith("v_cmp"): - return "mul:" in line or "div:" in line - return False - - -def vk_verdict(lines, hw, got): - """(class, detail) for a program translated and run on a Vulkan GPU against the hardware's four words: - match (a NaN matches any NaN), denormal (the words differ and the reference declines the program for a denormal: - RDNA2 in the game's MODE flushes f32 denormals, the translator leaves them to the driver), omod_neg_zero (an output - modifier turned the hardware's -0 into +0 and the translated -0 stayed: the translator does not model it, #1281) - or mismatch.""" - bad = [k for k in range(4) if hw[k] != got[k] and not (is_nan(hw[k]) and is_nan(got[k]))] - if not bad: - return "match", "" - try: - reference(lines) - except Skip as e: - if "denormal" in str(e): - return "denormal", str(e) - except RefError: - pass - if all(hw[k] == 0 and got[k] == 0x80000000 and omod_writer(lines, k) for k in bad): - return "omod_neg_zero", "omod made the hardware's -0 a +0" - i = bad[0] - return "mismatch", f"word {i} ({lines[-N_OBS + i].split(', ')[1]}): hardware 0x{hw[i]:08x}, translated on the GPU 0x{got[i]:08x}" - - -def check_hw_rows(hw, count): - """Refuse a hardware batch that can't be compared: no list, the wrong number of results, or a result that is None - or has fewer than 4 words. A str result (why the program was skipped) is kept. Runs before both comparison paths, - so vk_verdict never sees a row check() would have refused.""" - if hw is None: - raise RuntimeError("no result from the hardware runner") - if len(hw) != count: - raise RuntimeError(f"the hardware runner returned {len(hw)} results for {count} programs") - for i, row in enumerate(hw): - if row is None: - raise RuntimeError(f"no result from the hardware runner for program {i}") - if not isinstance(row, str) and len(row) < 4: - raise RuntimeError(f"the hardware runner returned {len(row)} words for program {i} (expected 4)") - - -def run_suite(programs, seed, max_ops, ops, backends=("translator",), oracle=None, wave=32, build=None, work=None): - counts = {"pass": 0, "mismatch": 0, "skip": {}, "vk": {}} - failures = [] - rng = random.Random(seed) - progs = [generate(rng, rng.randrange(1, max_ops + 1), ops) for _ in range(programs)] - if "hw" in backends: - hw = oracle.run([hw_kernel(p, wave) for p in progs]) - check_hw_rows(hw, len(progs)) - else: - hw = [None] * programs - vk_failures = [] - if "vk" in backends: - import vk_fuzz_run - vk = vk_fuzz_run.run_programs(progs, 4, wave, build, work, opaque=not VK_CONSTANTS) - for i, lines in enumerate(progs): - if isinstance(hw[i], str) or isinstance(vk[i], str): - why = ("hardware: " + hw[i]) if isinstance(hw[i], str) else vk[i] - counts["vk"]["skip: " + why] = counts["vk"].get("skip: " + why, 0) + 1 - continue - klass, detail = vk_verdict(lines, hw[i], vk[i]) - counts["vk"][klass] = counts["vk"].get(klass, 0) + 1 - if klass == "mismatch": - vk_failures.append((i, detail, lines)) - counts["vk_failures"] = vk_failures - backends = tuple(b for b in backends if b != "vk") - for i, lines in enumerate(progs): - try: - problem = check(lines, backends, hw[i]) - except Skip as e: - reason = ("uncertain: " if isinstance(e, Uncertain) else "") + str(e) - counts["skip"][reason] = counts["skip"].get(reason, 0) + 1 - continue - if problem is None: - counts["pass"] += 1 - continue - counts["mismatch"] += 1 - failures.append((i, problem, lines)) - return counts, failures - - -def self_test(): - """Harness canaries: a hand program matches, the reference gives hand-worked values, a bad form is a skip.""" - base = ([f"v_mov_b32_e32 v{v}, 0x{0x3F800000 + (v << 20):x}" for v in VREGS] # v1 1.125, v2 1.25, ... - + [f"s_mov_b32 s{s}, {s}" for s in SREGS]) - body = ["v_ldexp_f32 v1, -v2, s4", # -1.25 * 16 - "v_fract_f32_e64 v3, v3 mul:2", # 1.375 -> 0.375 -> 0.75 - "v_cmp_nge_f32_e64 s20, |v1|, 0x7fc00001", # unordered: true - "v_cndmask_b32_e64 v4, 0, 1, s20"] - lines = base + body + observe([1, 3, 4, 2]) - ok = check(lines) is None - worked = reference(lines) == [0xC1A00000, 0x3F400000, 1, 0x3FA00000] - try: - translated(base + ["v_fract_f32_sdwa_dpp v1, v2"] + observe([1, 2, 3, 4])) - skipped = False - except Skip: - skipped = True - print(f"self-test: match {ok}, hand values {worked}, unsupported form skipped {skipped}") - return ok and worked and skipped - - -def main(argv=None): - ap = argparse.ArgumentParser(description="f32 misc ops and float compares: differential fuzzing.") - ap.add_argument("--programs", type=int, default=300) - ap.add_argument("--seed", type=int, default=1) - ap.add_argument("--max-ops", type=int, default=5) - ap.add_argument("--ops", default=None, help="comma-separated opcodes (--list-ops; cmp and class = compare + " - "v_cndmask)") - ap.add_argument("--no-literals", action="store_true", help="no literal sources (v_fmamk_f32 keeps its K)") - ap.add_argument("--list-ops", action="store_true") - ap.add_argument("--self-test", action="store_true") - ap.add_argument("--all-failures", action="store_true", help="print every failing program, not just the first") - ap.add_argument("--known", action="store_true", - help="also generate the forms where the translator is known to differ (KNOWN_DIVERGENCES; " - "always on with --oracle hw alone)") - ap.add_argument("--oracle", default="translator", - help="comma-separated comparison targets: translator (default), hw (natively on an AMD GPU; see " - "tools/hw_oracle/) and vk (with hw: the translated programs on a Vulkan GPU through " - "vk_compute_test, judged against the hardware's words). 'hw' alone compares the hardware " - "with the reference only") - ap.add_argument("--hw-arch", default=None, help="GPU architecture to assemble for (default: detected)") - ap.add_argument("--wave", type=int, choices=(32, 64), default=32, - help="the wave size of the hardware kernels and of the vk programs (64 needs native 64-wide " - "subgroups; lane 0 is judged)") - ap.add_argument("--build", default=os.path.join(os.path.dirname(HERE), "runtime", "build"), - help="with vk: the folder with vk_compute_test") - ap.add_argument("--vk-constants", action="store_true", - help="with vk: keep the seeds as literal v_mov_b32 constants (the driver may fold them)") - ap.add_argument("--work", default=None, help="with vk: a folder for the temporary files (VK_FUZZ_KEEP=1 keeps them)") - a = ap.parse_args(argv) - if a.programs < 1 or a.max_ops < 1: - ap.error("--programs and --max-ops must be at least 1") - backends = tuple(dict.fromkeys(t.strip() for t in a.oracle.split(","))) - if not backends or any(t not in ("translator", "hw", "vk") for t in backends): - ap.error("--oracle takes translator, hw, vk (with hw) or a comma-separated mix") - if "vk" in backends and "hw" not in backends: - ap.error("--oracle vk judges the translated programs against the hardware's words: use --oracle hw,vk") - global KNOWN, LITERALS, VK_CONSTANTS - VK_CONSTANTS = a.vk_constants - KNOWN = a.known or backends == ("hw",) - LITERALS = not a.no_literals - if a.list_ops: - for name in ALL_OPS: - if name == "cmp": - print(f"{'cmp':20} v_cmp__f32 e32 / e64 + v_cndmask_b32_e64: {', '.join(FCMP)}") - elif name == "class": - print(f"{'class':20} v_cmp_class_f32_e64 + v_cndmask_b32_e64") - else: - form, _, fout, _ = OPS[name] - kind = {"vop1": "VOP1 e32/e64", "vop3": "VOP3 only", "fmamk": "VOP2 with literal K"}[form] - print(f"{name:20} {kind}{', omod/clamp' if fout and form != 'fmamk' else ''}") - return 0 - if a.self_test: - return 0 if self_test() else 1 - if a.ops is not None: - tokens = [t.strip() for t in a.ops.split(",")] - if not any(tokens) or any(not t for t in tokens): - ap.error("--ops must be a comma-separated list of opcodes") - ops = sorted(set(tokens)) - else: - ops = list(ALL_OPS) - unknown = [o for o in ops if o not in ALL_OPS] - if unknown: - ap.error("unknown ops: " + ", ".join(unknown)) - oracle = None - if "hw" in backends: - from hw_oracle import runner - try: - oracle = runner.open_oracle(arch=a.hw_arch) - except runner.Unavailable as e: - print(f"hardware oracle unavailable: {e}") - return 77 - print(f"hardware oracle: {oracle.device}") - try: - counts, failures = run_suite(a.programs, a.seed, a.max_ops, ops, backends, oracle, a.wave, a.build, a.work) - vk_bad = counts.pop("vk_failures") - skips = sum(counts["skip"].values()) - print(f"{a.programs} programs (seed {a.seed}, {'+'.join(backends)}{', known' if KNOWN else ''}): " - f"{counts['pass']} pass, {counts['mismatch']} mismatch, {skips} skipped") - for reason, n in sorted(counts["skip"].items(), key=lambda kv: -kv[1]): - print(f" skip x{n}: {reason}") - - want_vk = "vk" in backends - if want_vk: - print(f"translated on the Vulkan GPU (wave{a.wave}) against the hardware: " - + ", ".join(f"{k} {n}" for k, n in sorted(counts["vk"].items(), key=lambda kv: kv[0].startswith("skip")))) - for i, detail, lines in vk_bad[: None if a.all_failures else 3]: - print(f"VK MISMATCH program {i}: {detail}") - print("\n".join("\t" + line for line in lines)) - backends = tuple(b for b in backends if b != "vk") - - def check_fn(lines): - def run_hw_one(l): - res = oracle.run([hw_kernel(l, a.wave)]) - if not res: - raise RuntimeError("the hardware runner returned no result for shrunk program") - return res[0] - return check(lines, backends, run_hw_one if oracle else None) - for i, problem, lines in failures[: None if a.all_failures else 1]: - small = shrink(lines, check_fn) - print(f"MISMATCH program {i}: {check_fn(small) or problem}") - print("\n".join("\t" + line for line in small)) - except (RefError, RuntimeError) as e: - print(f"harness error: {e}") - return 2 - finally: - if oracle: - oracle.close() - if failures or vk_bad: - return 1 - if not counts["pass"]: - print("no program ran: every one was skipped") - return 2 - if want_vk: - import vk_fuzz_run - if vk_fuzz_run.all_skipped(counts["vk"]): - print("no Vulkan program ran: every one was skipped") - return 2 - return 0 - - -if __name__ == "__main__": - try: # a redirected stdout is strict ANSI code page under -I; write '?' for what it cannot encode - sys.stdout.reconfigure(errors="replace") - except (AttributeError, ValueError, OSError): - pass - sys.exit(main()) diff --git a/tools/fog_volumes.py b/tools/fog_volumes.py deleted file mode 100644 index 9033f283f..000000000 --- a/tools/fog_volumes.py +++ /dev/null @@ -1,456 +0,0 @@ -"""Scan RPF9 archives or carved 0x7a files for CScatteringTransmittance__FogVolumeListData resources. - -Reports only counts, offsets, schema hashes, and aggregate numeric/flag distributions (no game strings or names). -See docs/gamedata.md, "Fog volumes" (ASSET-308). - -Usage: - python -I fog_volumes.py [--out FILE] [--jobs N] -""" -from __future__ import annotations - -import argparse -import collections -import concurrent.futures -import hashlib -import json -import mmap -import os -import re -import struct -import sys -import tempfile -import zlib - -_TOOLS_DIR = os.path.dirname(os.path.abspath(__file__)) -if _TOOLS_DIR not in sys.path: - sys.path.insert(0, _TOOLS_DIR) - -import pool_workers # noqa: E402 -import world_census as WC # noqa: E402 -import world_index as WI # noqa: E402 -from report_paths import same_report_path # noqa: E402 - -ZHDR = re.compile(rb"\x78[\x01\x5e\x9c\xda]") - - -def joaat_cs(s: str) -> int: - """Case-sensitive joaat32 used by 0x7a schema struct and member tables.""" - h = 0 - for c in s.encode("latin-1"): - h = (h + c) & 0xFFFFFFFF - h = (h + (h << 10)) & 0xFFFFFFFF - h ^= h >> 6 - h = (h + (h << 3)) & 0xFFFFFFFF - h ^= h >> 11 - return (h + (h << 15)) & 0xFFFFFFFF - - -STRUCT_LIST = joaat_cs("CScatteringTransmittance__FogVolumeListData") # 0x03073767 -STRUCT_VOLUME = joaat_cs("CScatteringTransmittance__FogVolume") # 0x81907918 - -FIELDS = { - name: joaat_cs(name) - for name in ( - "IsBox", - "Position", - "PositionOffset", - "Scale", - "Rotation", - "Shear", - "RotationMtx", - "TransformMtx", - "BlendMode", - "IntExtMode", - "Type", - "SortKey", - "ProfileIndex", - "SecondaryProfileIndex", - "ProfileInterpolation", - ) -} - -_IDENT3 = (1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0) - - -def _ptr(val: int, size: int) -> int | None: - if val >> 28 != 5: - return None - off = val & 0x0FFFFFFF - return off if off < size else None - - -def parse_schema(b: bytes) -> tuple[dict[int, tuple[int, dict]], list[tuple[int, int, int | None]]]: - """Return ({struct_hash: (struct_size, members)}, [(block_struct_hash, block_size, offset_or_None)]).""" - n = len(b) - if n < 0x50 or b[0x10:0x14] != b"0DRP" or b[0x14] != 0x7A: - return {}, [] - nst, nbl = WI._u16(b, 0x48), WI._u16(b, 0x4C) - st = _ptr(WI._u64(b, 0x28), n) - it = _ptr(WI._u64(b, 0x38), n) - if not (1 <= nst <= 4096 and 1 <= nbl <= 4096) or st is None or it is None: - return {}, [] - if st + 32 * nst > n or it + 16 * nbl > n: - return {}, [] - structs: dict[int, tuple[int, dict]] = {} - for i in range(nst): - o = st + 32 * i - sh = WI._u32(b, o) - sz = WI._u32(b, o + 0x18) - cnt = WI._u16(b, o + 0x1E) - tbl = _ptr(WI._u64(b, o + 0x10), n) - members = WI._members(b, tbl, cnt, n) or {} - structs.setdefault(sh, (sz, members)) - blocks = [] - for i in range(nbl): - o = it + 16 * i - blocks.append((WI._u32(b, o), WI._u32(b, o + 4), _ptr(WI._u64(b, o + 8), n))) - return structs, blocks - - -def _read_field(b: bytes, base: int, member): - if member is None: - return None - off, ty = member[0], member[1] - p = base + off - if ty == 0x01: # bool / u8 - return b[p] if p < len(b) else None - if ty == 0x35: # Mat34V / 3x vec4f (48 bytes) - if p + 48 > len(b): - return None - m = struct.unpack_from("<12f", b, p) - return (m[0], m[1], m[2], m[4], m[5], m[6], m[8], m[9], m[10]) - if ty == 0x62: # enum u32 - return struct.unpack_from(" list[dict]: - """Decode all CScatteringTransmittance__FogVolume instances in a 0x7a resource.""" - structs, blocks = parse_schema(b) - if STRUCT_VOLUME not in structs: - return [] - vsz, vmems = structs[STRUCT_VOLUME] - if not vsz: - return [] - fields = {} - for name, field_hash in FIELDS.items(): - member = vmems.get(field_hash) - if member is not None: - width = FIELD_WIDTHS.get(member[1]) - if width is not None and member[0] + width <= vsz: - fields[name] = member - out: list[dict] = [] - for bsh, bsz, boff in blocks: - if bsh != STRUCT_VOLUME or boff is None or bsz % vsz or boff + bsz > len(b): - continue - for k in range(bsz // vsz): - base = boff + k * vsz - row = {name: _read_field(b, base, member) for name, member in fields.items()} - cleaned = {k_: v for k_, v in row.items() if v is not None} - if include_digest: - cleaned["_sha256"] = hashlib.sha256(b[base:base + vsz]).digest() - out.append(cleaned) - return out - - -def _is_identity3(m) -> bool: - return m is not None and len(m) == 9 and all(abs(a - c) < 1e-4 for a, c in zip(m, _IDENT3)) - - -def _scan_rpf_chunk(args: tuple[str, int, int]) -> tuple[list[int], int, int]: - """Scan [start, end) of an RPF9 archive for complete 0x7a FogVolume resources without a 256 KiB cap. - - Returns (matching_offsets, complete_0x7a_count, incomplete_0x7a_count). - """ - path, start, end = args - offs: list[int] = [] - complete_0x7a = 0 - incomplete_0x7a = 0 - with open(path, "rb") as f, mmap.mmap(f.fileno(), 0, access=mmap.ACCESS_READ) as m: - size = len(m) - pos = start - while pos < end: - mt = ZHDR.search(m, pos, end) - if not mt: - break - off = mt.start() - if ((m[off] << 8) | m[off + 1]) % 31 != 0: - pos = off + 1 - continue - d = zlib.decompressobj() - try: - head = d.decompress(m[off:min(size, off + 256)], 24) - except zlib.error: - pos = off + 1 - continue - if len(head) < 21 or head[0x10:0x14] != b"0DRP" or head[0x14] != 0x7A: - pos = off + 2 - continue - try: - res = WC.assemble(m, off, size) - except zlib.error: - incomplete_0x7a += 1 - pos = off + 2 - continue - if not res: - incomplete_0x7a += 1 - pos = off + 2 - continue - pos = max(off + 2, res.get("end", off + 2)) - if not res.get("complete"): - incomplete_0x7a += 1 - continue - complete_0x7a += 1 - data = res["data"] - nst = struct.unpack_from(" len(data): - continue - for i in range(nst): - if struct.unpack_from(" tuple[list[int], int, int]: - size = os.path.getsize(path) - if size < 16: - return [], 0, 0 - workers = pool_workers.process_workers(max(1, jobs)) - chunk_sz = max(4 * 1024 * 1024, min(64 * 1024 * 1024, (size + workers - 1) // workers)) - ranges = [(path, s, min(size, s + chunk_sz)) for s in range(0, size, chunk_sz)] - offs: list[int] = [] - complete_0x7a = 0 - incomplete_0x7a = 0 - if len(ranges) == 1 or workers == 1: - for r in ranges: - part_offs, c7a, i7a = _scan_rpf_chunk(r) - offs.extend(part_offs) - complete_0x7a += c7a - incomplete_0x7a += i7a - else: - with concurrent.futures.ProcessPoolExecutor(max_workers=workers) as ex: - for part_offs, c7a, i7a in ex.map(_scan_rpf_chunk, ranges): - offs.extend(part_offs) - complete_0x7a += c7a - incomplete_0x7a += i7a - offs.sort() - return offs, complete_0x7a, incomplete_0x7a - - -def iter_fog_resources(path: str, jobs: int = 1, stats: dict | None = None): - """Yield (source_id, raw_0x7a_bytes) for every complete 0x7a fog-volume resource in `path`.""" - if os.path.isdir(path): - for name in sorted(os.listdir(path)): - p = os.path.join(path, name) - if not os.path.isfile(p): - continue - with open(p, "rb") as f: - data = f.read(WC.CAP + 1) - if len(data) >= 0x50 and data[0x10:0x14] == b"0DRP" and data[0x14] == 0x7A: - if STRUCT_VOLUME in parse_schema(data)[0]: - yield name, data - return - - with open(path, "rb") as f: - magic = f.read(4) - if magic != b"9FPR": - with open(path, "rb") as f: - data = f.read(WC.CAP + 1) - if STRUCT_VOLUME in parse_schema(data)[0]: - yield os.path.basename(path), data - return - - size = os.path.getsize(path) - offs, complete_0x7a, incomplete_0x7a = _scan_rpf_offsets(path, jobs=jobs) - if stats is not None: - stats["scanned_0x7a_complete"] = complete_0x7a - stats["scanned_0x7a_incomplete"] = incomplete_0x7a - with open(path, "rb") as f, mmap.mmap(f.fileno(), 0, access=mmap.ACCESS_READ) as m: - for off in offs: - try: - res = WC.assemble(m, off, size) - except zlib.error: - continue - if res and res.get("complete"): - yield off, res["data"] - - -def summarize(path: str, jobs: int = 1) -> dict: - """Aggregate counts and numeric distributions (no game strings or names).""" - resources = 0 - volumes = 0 - distinct_digests: set[bytes] = set() - per_res: list[int] = [] - by_vol_count: collections.Counter[str] = collections.Counter() - offsets: list[int] = [] - scan_stats: dict[str, int] = {} - is_box: collections.Counter[str] = collections.Counter() - blend_mode: collections.Counter[str] = collections.Counter() - int_ext: collections.Counter[str] = collections.Counter() - vol_type: collections.Counter[str] = collections.Counter() - prof_idx: collections.Counter[str] = collections.Counter() - sec_prof_idx: collections.Counter[str] = collections.Counter() - prof_interp_nz = 0 - at_origin = 0 - pos_offset_nz = 0 - rot_nz = 0 - shear_nz = 0 - rot_mtx_id = 0 - tr_mtx_id = 0 - pos_axes: list[list[float]] = [[], [], []] - po_axes: list[list[float]] = [[], [], []] - sc_axes: list[list[float]] = [[], [], []] - - for src, data in iter_fog_resources(path, jobs=jobs, stats=scan_stats): - vols = parse_fog_volumes(data, include_digest=True) - resources += 1 - if isinstance(src, int): - offsets.append(src) - per_res.append(len(vols)) - by_vol_count[str(len(vols))] += 1 - for v in vols: - volumes += 1 - distinct_digests.add(v["_sha256"]) - if "IsBox" in v: - is_box[str(v["IsBox"])] += 1 - if "BlendMode" in v: - blend_mode[str(v["BlendMode"])] += 1 - if "IntExtMode" in v: - int_ext[str(v["IntExtMode"])] += 1 - if "Type" in v: - vol_type[str(v["Type"])] += 1 - if "ProfileIndex" in v: - prof_idx[str(v["ProfileIndex"])] += 1 - if "SecondaryProfileIndex" in v: - sec_prof_idx[str(v["SecondaryProfileIndex"])] += 1 - if v.get("ProfileInterpolation") and abs(v["ProfileInterpolation"]) > 1e-6: - prof_interp_nz += 1 - pos = v.get("Position") - if pos: - for i in range(3): - pos_axes[i].append(pos[i]) - if pos[0] == 0.0 and pos[1] == 0.0 and pos[2] == 0.0: - at_origin += 1 - po = v.get("PositionOffset") - if po: - for i in range(3): - po_axes[i].append(po[i]) - if any(abs(c) > 1e-6 for c in po): - pos_offset_nz += 1 - sc = v.get("Scale") - if sc: - for i in range(3): - sc_axes[i].append(sc[i]) - rot = v.get("Rotation") - if rot and any(abs(c) > 1e-6 for c in rot): - rot_nz += 1 - sh = v.get("Shear") - if sh and any(abs(c) > 1e-6 for c in sh): - shear_nz += 1 - if _is_identity3(v.get("RotationMtx")): - rot_mtx_id += 1 - if _is_identity3(v.get("TransformMtx")): - tr_mtx_id += 1 - - def _rng(axes): - if not axes[0]: - return None - return { - "x": [round(min(axes[0]), 4), round(max(axes[0]), 4)], - "y": [round(min(axes[1]), 4), round(max(axes[1]), 4)], - "z": [round(min(axes[2]), 4), round(max(axes[2]), 4)], - } - - out = { - "resources": resources, - "volumes": volumes, - "distinct_serialized_volumes": len(distinct_digests), - "volumes_per_resource": { - "min": min(per_res) if per_res else 0, - "max": max(per_res) if per_res else 0, - "median": sorted(per_res)[len(per_res) // 2] if per_res else 0, - }, - "resources_by_volume_count": dict(sorted(by_vol_count.items(), key=lambda kv: int(kv[0]))), - "offset_range": [hex(min(offsets)), hex(max(offsets))] if offsets else None, - "is_box": dict(sorted(is_box.items())), - "blend_mode": dict(sorted(blend_mode.items())), - "int_ext_mode": dict(sorted(int_ext.items())), - "type": dict(sorted(vol_type.items())), - "profile_index": dict(sorted(prof_idx.items(), key=lambda kv: int(kv[0]))), - "secondary_profile_index": dict(sorted(sec_prof_idx.items(), key=lambda kv: int(kv[0]))), - "profile_interpolation_nonzero": prof_interp_nz, - "position_at_origin": at_origin, - "position_offset_nonzero": pos_offset_nz, - "rotation_nonzero": rot_nz, - "shear_nonzero": shear_nz, - "rotation_mtx_identity": rot_mtx_id, - "transform_mtx_identity": tr_mtx_id, - "position_range": _rng(pos_axes), - "position_offset_range": _rng(po_axes), - "scale_range": _rng(sc_axes), - } - out.update(scan_stats) - return out - - -def _write_json_atomic(path: str, doc: dict) -> None: - out_abs = os.path.abspath(path) - parent = os.path.dirname(out_abs) - os.makedirs(parent, exist_ok=True) - fd, tmp = tempfile.mkstemp(prefix=".fog-volumes-", suffix=".tmp", dir=parent) - try: - with os.fdopen(fd, "w", encoding="utf-8", newline="\n") as f: - json.dump(doc, f, indent=1, sort_keys=True) - f.write("\n") - f.flush() - os.fsync(f.fileno()) - os.replace(tmp, out_abs) - except Exception: - try: - os.unlink(tmp) - except OSError: - pass - raise - - -def main(argv=None) -> int: - ap = argparse.ArgumentParser(description=__doc__.splitlines()[0]) - ap.add_argument("path", help="RPF9 archive, carved 0x7a file, or folder of carved files") - ap.add_argument("--out", help="optional JSON summary output path") - ap.add_argument("--jobs", type=WC.job_count, default=min(16, os.cpu_count() or 4), - help="worker processes for RPF9 scanning (at least 1)") - a = ap.parse_args(argv) - if not os.path.exists(a.path): - ap.error(f"no such file or folder: {a.path}") - if a.out: - if os.path.isdir(a.out): - ap.error(f"--out is a directory: {a.out}") - if os.path.isfile(a.path) and same_report_path(a.path, a.out): - ap.error(f"--out would overwrite input: {a.out}") - try: - doc = summarize(a.path, jobs=a.jobs) - if a.out: - _write_json_atomic(a.out, doc) - except OSError as exc: - print(f"ERROR: {exc}", file=sys.stderr) - return 2 - print(json.dumps(doc, indent=1, sort_keys=True)) - return 0 - - -if __name__ == "__main__": - try: # a redirected stdout is strict ANSI code page under -I; write '?' for what it cannot encode - sys.stdout.reconfigure(errors="replace") - except (AttributeError, ValueError, OSError): - pass - sys.exit(main()) diff --git a/tools/fragment_children.py b/tools/fragment_children.py deleted file mode 100644 index 23fee0277..000000000 --- a/tools/fragment_children.py +++ /dev/null @@ -1,413 +0,0 @@ -"""Census the child drawables of the fragments in an RPF9 archive (ASSET-261). - -docs/character_models.md records that every one of the 2,865 `packs.rpf` fragments has a single drawable and -no child arrays. This tool measures the same thing for any archive, `levels.rpf` included, from the raw -system pages: no manifest, no table of contents and no decoder is needed. Only archives whose resources are -plain page-aligned zlib streams are read, the way tools/skin_streams.py reads them. - -A fragment is the resource shape rpf9-explorer's `RageModelDecoder` calls one: not a drawable, not a drawable -dictionary, and a header whose `+0x08`, `+0x18` and `+0xA8` fields are system pointers, whose `+0x10`, `+0x20` -and `+0x28` fields are null or system pointers, and whose u16 fields at `+0x30..+0x36` read (a, b, c, d) with -0 < a <= 4096, b <= 4096 and c <= d <= 4096. `+0x18` points at the fragment's main drawable. - -Layout measured here (counts only; nothing the archive holds is written out): - - drawable array `a` (u16 at `+0x30`) is the number of drawables. They are 0x110-byte records at a fixed - stride starting at the main drawable `+0x18` points at, so record i is at main + 0x110 * i. - Records 1..a-1 are the child drawables; their `+0x00` and `+0x08` fields are zero. - drawable body what the tool accepts as a drawable at an offset: `+0x00` and `+0x08` zero, `+0x10` (shader - group) and `+0xA8` (name) null or system pointers, finite ordered bounds, a finite - radius in [0, 1e6), and a LOD list behind `+0x50` (u16 model count 1..256 at +0x08, - repeated at +0x0A, an array of system pointers to models whose geometry count at - +0x10 equals the copies at +0x12 and +0x36). - child drawable a body at main + 0x110 * i for 1 <= i < a (the declared children). - stray drawable a body at any other 16-byte-aligned offset of the system pages outside the main record, - found by scanning; a count of what the array walk would miss. - child array a fragment whose array holds at least one child drawable. - part element the 0x50-byte records of the array `+0x28` points at (c of them, c = u16 at `+0x34`); - the fragments with more than one are counted too. - -A fragment with no child drawable and no stray drawable has nothing the main-drawable export misses. - -Usage: - python -I tools/fragment_children.py [--jobs N] [--start BYTES] [--end BYTES] - [--records out.jsonl] [--json out.json] - -`--start`/`--end` bound the byte range scanned (resume a long run, or split it); `--jobs` splits the range -over worker processes. `--records` writes one JSON line per fragment with its stream offset and the measured -numbers, for a re-count without a re-scan; it is a local working file, not something to publish. -""" -import argparse -import array as array_module -import json -import mmap -import multiprocessing -import os -import stat -import struct -import sys -import tempfile -import time -import zlib - -sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) # -I keeps the script directory off sys.path -from file_mode import published_mode # noqa: E402 -from replace_retry import replace as replace_retry # noqa: E402 -import skin_streams as ss # noqa: E402 - -SYSTEM = 0x50000000 -PAGE = 4096 -MAX_SYSTEM_BYTES = 64 * 1024 * 1024 -MAX_PAGES = 32 -MAX_ELEMENTS = 4096 -ELEMENT_STRIDE = 0x50 -RECORD = 0x110 # stride of the drawable records -HEADER = 192 # a fragment header; nothing embedded starts inside it -ZHDR = ss.ZHDR - - -def u16(b, o): - return struct.unpack_from(" len(b) or u64(b, at) != 0: - return False - pages, shader, high, name = u64(b, at + 8), u64(b, at + 16), u64(b, at + 80), u64(b, at + 168) - if (pages != 0) if embedded else (not system_pointer(pages)): - return False - if not (system_pointer(shader) and system_pointer(high)): - return False - if not (system_pointer(name) or (embedded and name == 0)): - return False - radius = struct.unpack_from(" n or u64(b, at) != 0 or u64(b, at + 8) != 0: - return False - shader, name, lod = u64(b, at + 16), u64(b, at + 168), u64(b, at + 80) - if (shader and not system_pointer(shader)) or (name and not system_pointer(name)): - return False - radius = struct.unpack_from(" total or pages < 1: - nxt = ss.next_stream(m, fp, size) - if nxt is None or pages >= MAX_PAGES: - return None - parts.append(nxt[0]) - total += len(nxt[0]) - fp = nxt[1] + nxt[2] - pages += 1 - joined = b"".join(parts) - system_pages = joined[directory + 8] - if not 0 < system_pages <= MAX_PAGES: - return None - while pages < system_pages: - nxt = ss.next_stream(m, fp, size) - if nxt is None: - return None - parts.append(nxt[0]) - fp = nxt[1] + nxt[2] - pages += 1 - joined = b"".join(parts) - return joined, fp - - -def stray_bodies(system, array): - """Offsets of drawable bodies outside the record array: `array` is the (start, end) the records span.""" - n = len(system) - words = array_module.array("Q") - words.frombytes(system[:n // 8 * 8]) - if sys.byteorder != "little": - words.byteswap() - found, low, high = [], SYSTEM, SYSTEM + n - for at in range(HEADER, n - 176 + 1, 16): - if array[0] <= at < array[1]: - continue - i = at >> 3 - if words[i] or words[i + 1] or not low <= words[i + 10] < high: # +0x00, +0x08, the LOD pointer - continue - if drawable_body(system, at): - found.append(at) - return found - - -def walk(system): - """Measure one fragment's system pages; returns a dict of counts, or None if the header is unusable.""" - if not fragment_header(system): - return None - main = u64(system, 24) - SYSTEM - a, b, c, d = struct.unpack_from("<4H", system, 48) - rec = {"main": main, "abcd": [a, b, c, d], - "optional_null": sum(1 << i for i, at in enumerate((16, 32, 40)) if u64(system, at) == 0)} - rec["main_ok"] = 0 <= main <= len(system) - 176 and drawable_header(system, main, True) - found = [i for i in range(1, a) if drawable_body(system, main + RECORD * i)] - rec["children"] = len(found) - rec["declared"] = a - 1 - # the main record is excluded from the scan through the array span, so a missing child stays "stray" - rec["stray"] = len(stray_bodies(system, (main, main + RECORD * a))) if main >= HEADER else -1 - elements = 0 - table = u64(system, 40) - SYSTEM - if c and u64(system, 40) and 0 <= table <= len(system) - c * ELEMENT_STRIDE and c <= MAX_ELEMENTS: - elements = c - rec["elements"] = elements - return rec - - -def empty_stats(): - return {"fragments": 0, "unreadable": 0, "main_drawable_invalid": 0, "optional_pointers_null": 0, - "multi_drawable_fragments": 0, "declared_child_drawables": 0, "child_drawables": 0, - "child_arrays": 0, "stray_drawables": 0, "fragments_with_stray": 0, "max_children": 0, - "multi_part_fragments": 0, "part_elements": 0} - - -def count(stats, rec): - stats["fragments"] += 1 - if not rec["main_ok"]: - stats["main_drawable_invalid"] += 1 - if rec["optional_null"]: - stats["optional_pointers_null"] += 1 - if rec["declared"]: - stats["multi_drawable_fragments"] += 1 - stats["declared_child_drawables"] += rec["declared"] - if rec["children"]: - stats["child_arrays"] += 1 - stats["child_drawables"] += rec["children"] - stats["max_children"] = max(stats["max_children"], rec["children"]) - if rec["stray"] > 0: - stats["fragments_with_stray"] += 1 - stats["stray_drawables"] += rec["stray"] - stats["part_elements"] += rec["elements"] - if rec["elements"] > 1: - stats["multi_part_fragments"] += 1 - - -def merge(into, other): - for key, value in other.items(): - into[key] = max(into[key], value) if key == "max_children" else into[key] + value - - -def scan_range(path, start, end, records, log=None): - """Scan [start, end) of one archive; returns the stats. `records` is a writable handle or None.""" - stats = empty_stats() - size = os.path.getsize(path) - end = min(end, size) - if size == 0 or start >= end: - return stats - t0 = time.time() - with open(path, "rb") as fh: - m = mmap.mmap(fh.fileno(), 0, access=mmap.ACCESS_READ) - pos = start - while pos < end: - page = (pos + PAGE - 1) & ~(PAGE - 1) - at = page + 16 - if at + 2 > size or page >= end: - break - pos = page + PAGE - if m[at - 16:at] != b"\0" * 16 or not ZHDR.match(m, at): - continue - try: - prefix = zlib.decompressobj().decompress(m[at:at + 4 * PAGE], 192) - except zlib.error: - continue - if classify(prefix) is None: - continue - got = read_system(m, at, size) - rec = None - if got is not None: - rec = walk(got[0]) - if rec is None: - stats["unreadable"] += 1 - continue - count(stats, rec) - pos = max(pos, got[1]) # resume after the pages this resource consumed - if records is not None: - records.write(json.dumps(dict(rec, at=at), separators=(",", ":")) + "\n") - records.flush() - if log and stats["fragments"] % 5000 == 0: - log(f" {os.path.basename(path)} @{page:#x}: {stats['fragments']} fragments, " - f"{time.time() - t0:.0f}s") - return stats - - -def worker(args): - path, start, end, records_path = args - handle = open(records_path, "w", encoding="utf-8", newline="\n") if records_path else None - try: - return scan_range(path, start, end, handle) - finally: - if handle: - handle.close() - - -def split_ranges(start, end, jobs): - step = max(PAGE, ((end - start) // jobs + PAGE - 1) // PAGE * PAGE) - return [(lo, min(lo + step, end)) for lo in range(start, end, step)] - - -def scan_archive(path, start=0, end=None, jobs=1, records=None, log=None): - size = os.path.getsize(path) - end = size if end is None else min(end, size) - total = empty_stats() - if jobs <= 1 or end - start < 2 * PAGE: - handle = open(records, "w", encoding="utf-8", newline="\n") if records else None - try: - merge(total, scan_range(path, start, end, handle, log)) - finally: - if handle: - handle.close() - return total - ranges = split_ranges(start, end, jobs) - work = [(path, lo, hi, f"{records}.{i}" if records else None) for i, (lo, hi) in enumerate(ranges)] - with multiprocessing.Pool(len(work)) as pool: - for part in pool.imap_unordered(worker, work): - merge(total, part) - if records: # join the per-range files in range order - with open(records, "w", encoding="utf-8", newline="\n") as out: - for i in range(len(work)): - part = f"{records}.{i}" - with open(part, encoding="utf-8") as fh: - out.write(fh.read()) - os.remove(part) - return total - - -def write_json_report(path, report): - """Publish a complete regular file, or write directly to a non-regular destination.""" - destination = os.path.realpath(path) - parent = os.path.dirname(destination) or "." - try: - mode = os.stat(destination).st_mode - except FileNotFoundError: - mode = None - if mode is not None and not stat.S_ISREG(mode): - with open(path, "w", encoding="utf-8", newline="\n") as fh: - json.dump(report, fh, indent=1) - return - if mode is not None: - # Retain the direct writer's permission check without truncating the report. - os.close(os.open(destination, os.O_WRONLY)) - - staged = tempfile.NamedTemporaryFile( - mode="w", encoding="utf-8", newline="\n", delete=False, - dir=parent, prefix=".fragment_children-", suffix=".tmp", - ) - try: - with staged: - json.dump(report, staged, indent=1) - if os.name != "nt": - os.chmod(staged.name, published_mode(destination)) - replace_retry(staged.name, destination) - finally: - try: - os.unlink(staged.name) - except FileNotFoundError: - pass - - -def main(argv=None): - ap = argparse.ArgumentParser(description=__doc__.splitlines()[0]) - ap.add_argument("archive", help="RPF9 archive to scan") - ap.add_argument("--start", type=int, default=0, help="first byte offset to scan") - ap.add_argument("--end", type=int, help="byte offset to stop at (default: end of file)") - ap.add_argument("--jobs", type=int, default=1, help="worker processes (the range is split evenly)") - ap.add_argument("--records", help="write one JSON line per fragment here (a local working file)") - ap.add_argument("--json", help="write the totals to this file") - a = ap.parse_args(argv) - if a.jobs < 1 or a.start < 0 or (a.end is not None and a.end < a.start): - print("error: bad --jobs, --start or --end", file=sys.stderr) - return 2 - if not os.path.isfile(a.archive): - print(f"error: {a.archive} is not a file", file=sys.stderr) - return 2 - for out in (a.records, a.json): - if not out: - continue - if os.path.isdir(out) or ss.same_output_path(out, a.archive): - print(f"error: {out} is a directory or the input", file=sys.stderr) - return 2 - parent = os.path.dirname(os.path.abspath(out)) - if not os.path.isdir(parent): - # checked before the scan: the scan can run for hours and would raise only at write time - print(f"error: {out} is in a folder that does not exist: {parent}", file=sys.stderr) - return 2 - t0 = time.time() - stats = scan_archive(a.archive, a.start, a.end, a.jobs, a.records, lambda text: print(text, flush=True)) - print(f"{os.path.basename(a.archive)}: {time.time() - t0:.0f}s") - for key, value in stats.items(): - print(f" {key:26s} {value:10d}") - if a.json: - write_json_report(a.json, stats) - return 0 - - -if __name__ == "__main__": - try: - sys.stdout.reconfigure(errors="replace") - except (AttributeError, ValueError, OSError): - pass - sys.exit(main()) diff --git a/tools/frexp_ldexp_f16_mods_probe.py b/tools/frexp_ldexp_f16_mods_probe.py deleted file mode 100644 index ce41dc39d..000000000 --- a/tools/frexp_ldexp_f16_mods_probe.py +++ /dev/null @@ -1,606 +0,0 @@ -r"""Measure RDNA2 VOP3 output modifiers on v_frexp_mant_f16, v_frexp_exp_i16_f16, and v_ldexp_f16. Standard library only. - -Probes VOP3 ``clamp``, ``mul:2``, ``mul:4``, ``div:2``, and ``clamp`` combined with ``mul:*``/``div:*`` across -curated binary16 edge inputs (``+-0``, ``+-min_sub``, ``+-max_sub``, ``+-min_norm``, ``+-0.25``, ``+-0.5``, -``+-(1-2^-11)``, ``+-1.0``, ``+-(1+2^-10)``, ``+-2.0``, ``+-max_finite``, ``+-inf``, ``+-sNaN``, ``+-qNaN``), -source ``abs``/``neg`` modifiers, dirty upper-16-bit source halves, and destination high-half preservation across -wave32 and wave64 on GFX10 (``gfx1036``) under: -- Console MODE (``0x1c0``: ``IEEE=0``, ``DX10_CLAMP=1``, ``denorm32=0``, ``denorm16_64=3``); -- Flush control MODE (``0x100``: ``denorm16_64=0``); -- IEEE control MODE (``0x3c0``: ``IEEE=1``, ``denorm16_64=3``). - -Usage: - python -I tools/frexp_ldexp_f16_mods_probe.py [--waves 32,64] [--ops ...] [--hw-arch gfx1036] [--json out.json] - python -I tools/frexp_ldexp_f16_mods_probe.py --self-test - -Exit 0 when all hardware results match the expected RDNA2 model with zero wave32/wave64 diffs and zero console-MODE -omod diffs; 1 on a mismatch or parity failure; 2 on a harness/CLI error; 77 when the hardware oracle is unavailable or -the GPU is not GFX10. Nothing here reads game files. -""" -from dataclasses import dataclass -import json -import math -import os -import struct -import sys -import argparse - -HERE = os.path.dirname(os.path.abspath(__file__)) -sys.dont_write_bytecode = True -if HERE not in sys.path: - sys.path.insert(0, HERE) - -OPS: tuple[str, ...] = ("v_frexp_mant_f16", "v_frexp_exp_i16_f16", "v_ldexp_f16") -MODS: tuple[str, ...] = ("", "clamp", "mul:2", "mul:4", "div:2", "clamp mul:2", "clamp mul:4", "clamp div:2") - -EDGE_F16: tuple[int, ...] = ( - 0x0000, 0x8000, # +-0.0 - 0x0001, 0x8001, # +-min_sub - 0x03FF, 0x83FF, # +-max_sub - 0x0400, 0x8400, # +-min_norm - 0x3400, 0xB400, # +-0.25 - 0x3800, 0xB800, # +-0.5 - 0x3BFF, 0xBBFF, # +-(1 - 2^-11) - 0x3C00, 0xBC00, # +-1.0 - 0x3C01, 0xBC01, # +-(1 + 2^-10) - 0x4000, 0xC000, # +-2.0 - 0x7BFF, 0xFBFF, # +-max_finite - 0x7C00, 0xFC00, # +-inf - 0x7C01, 0xFC01, # +-sNaN - 0x7E00, 0xFE00, # +-qNaN - 0x7E55, 0xFE55, # +-qNaN with payload -) -LDEXP_EXPS: tuple[int, ...] = (-25, -1, 0, 1, 16) - -MODE_CONSOLE = 0x1C0 # IEEE=0, DX10_CLAMP=1, denorm32=0, denorm16_64=3 -MODE_FLUSH16 = 0x100 # IEEE=0, DX10_CLAMP=1, denorm32=0, denorm16_64=0 -MODE_IEEE = 0x3C0 # IEEE=1, DX10_CLAMP=1, denorm32=0, denorm16_64=3 -DEFAULT_INIT_DST = 0xDEADBEEF - - -@dataclass(frozen=True) -class SrcModCase: - name: str - op: str - h: int - n: int - mod: str - src0_abs: bool = False - src0_neg: bool = False - init_dst: int = DEFAULT_INIT_DST - - -SRC_MOD_CASES: tuple[SrcModCase, ...] = ( - SrcModCase("mant_neg_clamp", "v_frexp_mant_f16", 0xBC00, 0, "clamp", src0_neg=True), - SrcModCase("mant_abs_clamp_mul2", "v_frexp_mant_f16", 0xC000, 0, "clamp mul:2", src0_abs=True), - SrcModCase("mant_negabs_div2", "v_frexp_mant_f16", 0x3C00, 0, "div:2", src0_abs=True, src0_neg=True), - SrcModCase("mant_neg_qnan_clamp", "v_frexp_mant_f16", 0xFE55, 0, "clamp", src0_neg=True), - SrcModCase("exp_neg_clamp", "v_frexp_exp_i16_f16", 0xC800, 0, "clamp", src0_neg=True), - SrcModCase("exp_abs_mul2", "v_frexp_exp_i16_f16", 0xC800, 0, "mul:2", src0_abs=True), - SrcModCase("exp_negabs_clamp_div2", "v_frexp_exp_i16_f16", 0x4800, 0, "clamp div:2", src0_abs=True, src0_neg=True), - SrcModCase("ldexp_neg_clamp", "v_ldexp_f16", 0xBC00, 1, "clamp", src0_neg=True), - SrcModCase("ldexp_abs_clamp_mul2", "v_ldexp_f16", 0xBC00, 1, "clamp mul:2", src0_abs=True), - SrcModCase("ldexp_negabs_div2", "v_ldexp_f16", 0x3C00, 1, "div:2", src0_abs=True, src0_neg=True), - SrcModCase("ldexp_neg_inf_clamp", "v_ldexp_f16", 0xFC00, 0, "clamp", src0_neg=True), -) - - -@dataclass(frozen=True) -class ControlCase: - name: str - op: str - h: int - n: int - mod: str - want_lo: int - init_dst: int = DEFAULT_INIT_DST - - -FLUSH_CONTROL_CASES: tuple[ControlCase, ...] = ( - ControlCase("mant_plain", "v_frexp_mant_f16", 0x3C00, 0, "", 0x3800), - ControlCase("mant_mul2", "v_frexp_mant_f16", 0x3C00, 0, "mul:2", 0x3C00), - ControlCase("mant_mul4", "v_frexp_mant_f16", 0x3C00, 0, "mul:4", 0x4000), - ControlCase("mant_div2", "v_frexp_mant_f16", 0x3C00, 0, "div:2", 0x3400), - ControlCase("mant_clamp_mul4", "v_frexp_mant_f16", 0x3C00, 0, "clamp mul:4", 0x3C00), - ControlCase("ldexp_plain", "v_ldexp_f16", 0x3800, 1, "", 0x3C00), - ControlCase("ldexp_mul2", "v_ldexp_f16", 0x3800, 1, "mul:2", 0x4000), - ControlCase("ldexp_mul4", "v_ldexp_f16", 0x3800, 1, "mul:4", 0x4400), - ControlCase("ldexp_div2", "v_ldexp_f16", 0x3800, 1, "div:2", 0x3800), - ControlCase("ldexp_clamp_mul4", "v_ldexp_f16", 0x3800, 1, "clamp mul:4", 0x3C00), - # 16-bit integer result ignores clamp and omod even when denorm_mode_16_64=0. - *(ControlCase(f"exp_{m or 'plain'}", "v_frexp_exp_i16_f16", 0x4800, 0, m, 0x0004) for m in MODS), -) - - -def _h2f(h: int) -> float: - return struct.unpack(" int: - return struct.unpack(" bool: - return ((h >> 10) & 0x1F) != 31 and (h & 0x7FFF) != 0 - - -def ref_clamp_f16(h: int) -> int: - """DX10_CLAMP [0.0, 1.0] saturation on a binary16 word: negative (including -0.0) and NaN -> +0.0.""" - h &= 0xFFFF - if (h & 0x8000) or (((h >> 10) & 0x1F) == 31 and (h & 0x3FF) != 0): - return 0x0000 - return 0x3C00 if h > 0x3C00 else h - - -def expected_word( - op: str, - h: int, - n: int = 0, - *, - mod: str = "", - init_dst: int = DEFAULT_INIT_DST, - src0_abs: bool = False, - src0_neg: bool = False, -) -> int: - """Expected 32-bit vdst value under console MODE (0x1c0: IEEE=0, DX10_CLAMP=1, denorm16_64=3).""" - if op not in OPS: - raise ValueError(f"unsupported op: {op}") - b = h & 0xFFFF - if src0_abs: - b &= 0x7FFF - if src0_neg: - b ^= 0x8000 - - if op == "v_frexp_mant_f16": - lo = _f2h(math.frexp(_h2f(b))[0]) if _is_finite_nonzero(b) else b - elif op == "v_frexp_exp_i16_f16": - lo = (math.frexp(_h2f(b))[1] & 0xFFFF) if _is_finite_nonzero(b) else 0 - else: - if _is_finite_nonzero(b): - n16 = n & 0xFFFF - if n16 & 0x8000: - n16 -= 0x10000 - try: - lo = _f2h(math.ldexp(_h2f(b), max(-64, min(64, n16)))) - except OverflowError: - lo = (b & 0x8000) | 0x7C00 - else: - lo = b - - if "clamp" in mod.split() and op != "v_frexp_exp_i16_f16": - lo = ref_clamp_f16(lo) - return (init_dst & 0xFFFF0000) | (lo & 0xFFFF) - - -def _format_src(reg: str, is_abs: bool, is_neg: bool) -> str: - s = f"|{reg}|" if is_abs else reg - return f"-{s}" if is_neg else s - - -def _emit_inst(op: str, mod: str, *, src0_abs: bool = False, src0_neg: bool = False) -> str: - s0 = _format_src("v1", src0_abs, src0_neg) - suffix = f" {mod}" if mod else "" - if op == "v_ldexp_f16": - return f"v_ldexp_f16 v8, {s0}, v2{suffix}" - return f"{op}_e64 v8, {s0}{suffix}" - - -def mode_grid_kernel_lines(op: str, mod: str, mode_val: int) -> tuple[list[str], list[tuple[int, int]]]: - """Emit raw GFX10 kernel sweeping EDGE_F16 (or EDGE_F16 x LDEXP_EXPS) under ``mode_val``.""" - pairs = [(h, n) for h in EDGE_F16 for n in LDEXP_EXPS] if op == "v_ldexp_f16" else [(h, 0) for h in EDGE_F16] - lines = [f"s_setreg_imm32_b32 hwreg(HW_REG_MODE, 0, 10), {mode_val:#x}"] - for idx, (h, n) in enumerate(pairs): - lines.append(f"v_mov_b32_e32 v1, {0xABCD0000 | (h & 0xFFFF):#010x}") - if op == "v_ldexp_f16": - lines.append(f"v_mov_b32_e32 v2, {0x12340000 | (n & 0xFFFF):#010x}") - lines.append(f"v_mov_b32_e32 v8, {DEFAULT_INIT_DST:#010x}") - lines.append(_emit_inst(op, mod)) - lines.append(f"v_mov_b32_e32 v3, {idx * 4}") - lines.append("global_store_dword v3, v8, s[2:3]") - lines += ["s_waitcnt vmcnt(0)", "s_endpgm"] - return lines, pairs - - -def src_mod_kernel_lines(cases: tuple[SrcModCase, ...], mode_val: int) -> list[str]: - """Emit raw GFX10 kernel running ``cases`` sequentially on lane 0 under ``mode_val``.""" - lines = [f"s_setreg_imm32_b32 hwreg(HW_REG_MODE, 0, 10), {mode_val:#x}"] - for idx, c in enumerate(cases): - lines.append(f"v_mov_b32_e32 v1, {0xABCD0000 | (c.h & 0xFFFF):#010x}") - if c.op == "v_ldexp_f16": - lines.append(f"v_mov_b32_e32 v2, {0x12340000 | (c.n & 0xFFFF):#010x}") - lines.append(f"v_mov_b32_e32 v8, {c.init_dst:#010x}") - lines.append(_emit_inst(c.op, c.mod, src0_abs=c.src0_abs, src0_neg=c.src0_neg)) - lines.append(f"v_mov_b32_e32 v3, {idx * 4}") - lines.append("global_store_dword v3, v8, s[2:3]") - lines += ["s_waitcnt vmcnt(0)", "s_endpgm"] - return lines - - -def control_kernel_lines(cases: tuple[ControlCase, ...], mode_val: int) -> list[str]: - """Emit raw GFX10 kernel running ``cases`` sequentially under ``mode_val``.""" - lines = [f"s_setreg_imm32_b32 hwreg(HW_REG_MODE, 0, 10), {mode_val:#x}"] - for idx, c in enumerate(cases): - lines.append(f"v_mov_b32_e32 v1, {0xABCD0000 | (c.h & 0xFFFF):#010x}") - if c.op == "v_ldexp_f16": - lines.append(f"v_mov_b32_e32 v2, {0x12340000 | (c.n & 0xFFFF):#010x}") - lines.append(f"v_mov_b32_e32 v8, {c.init_dst:#010x}") - lines.append(_emit_inst(c.op, c.mod)) - lines.append(f"v_mov_b32_e32 v3, {idx * 4}") - lines.append("global_store_dword v3, v8, s[2:3]") - lines += ["s_waitcnt vmcnt(0)", "s_endpgm"] - return lines - - -def ieee_control_cases(ops: list[str]) -> list[ControlCase]: - """Selected control cases verified under MODE_IEEE (0x3c0).""" - out = [] - for op in ops: - if op == "v_frexp_mant_f16": - h, n = 0xBC00, 0 - elif op == "v_frexp_exp_i16_f16": - h, n = 0x4800, 0 - else: - h, n = 0xBC00, 1 - for mod in MODS: - want = expected_word(op, h, n, mod=mod) & 0xFFFF - out.append(ControlCase(f"ieee_{op}_{mod or 'plain'}", op, h, n, mod, want)) - return out - - -def build_jobs(ops: list[str], waves: list[int]): - """Build (kernels, metadata) pairs for oracle.run().""" - from hw_oracle import asm - - kernels, meta = [], [] - src_cases = tuple(c for c in SRC_MOD_CASES if c.op in ops) - flush_cases = tuple(c for c in FLUSH_CONTROL_CASES if c.op in ops) - ieee_cases = tuple(ieee_control_cases(ops)) - for wave in waves: - for op in ops: - for mod in MODS: - lines, pairs = mode_grid_kernel_lines(op, mod, MODE_CONSOLE) - kernels.append(asm.Kernel(lines, wave=wave, threads=1, words=len(pairs), raw=True)) - meta.append(("grid", wave, op, mod, pairs)) - if src_cases: - kernels.append(asm.Kernel(src_mod_kernel_lines(src_cases, MODE_CONSOLE), wave=wave, threads=1, - words=len(src_cases), raw=True)) - meta.append(("src_mods", wave, "all", "src_mods", src_cases)) - if flush_cases: - kernels.append(asm.Kernel(control_kernel_lines(flush_cases, MODE_FLUSH16), wave=wave, threads=1, - words=len(flush_cases), raw=True)) - meta.append(("flush_ctrl", wave, "all", "flush_ctrl", flush_cases)) - if ieee_cases: - kernels.append(asm.Kernel(control_kernel_lines(ieee_cases, MODE_IEEE), wave=wave, threads=1, - words=len(ieee_cases), raw=True)) - meta.append(("ieee_ctrl", wave, "all", "ieee_ctrl", ieee_cases)) - return kernels, meta - - -def evaluate_results(ops: list[str], waves: list[int], meta, raw_results) -> dict: - """Compare hardware outputs against expected RDNA2 semantics and check wave and omod parity.""" - grid_words: dict[tuple[int, str, str], list[int]] = {} - src_words: dict[int, list[int]] = {} - flush_words: dict[int, list[int]] = {} - ieee_words: dict[int, list[int]] = {} - harness_errors: list[dict] = [] - - for (kind, wave, op, mod, items), res in zip(meta, raw_results): - want_words = len(items) - if isinstance(res, str): - harness_errors.append({"kind": kind, "wave": wave, "op": op, "mod": mod, "error": res}) - continue - if len(res) != want_words: - harness_errors.append({ - "kind": kind, - "wave": wave, - "op": op, - "mod": mod, - "error": f"expected {want_words} words, got {len(res)}", - }) - continue - words = [w & 0xFFFFFFFF for w in res] - if kind == "grid": - grid_words[(wave, op, mod)] = words - elif kind == "src_mods": - src_words[wave] = words - elif kind == "flush_ctrl": - flush_words[wave] = words - elif kind == "ieee_ctrl": - ieee_words[wave] = words - - if harness_errors: - return { - "total_words": 0, - "grid_words": 0, - "src_mod_words": 0, - "control_words": 0, - "mismatches": 0, - "wave_diffs": 0, - "omod_diffs": 0, - "harness_errors": harness_errors, - "first_mismatches": [], - "first_wave_diffs": [], - "first_omod_diffs": [], - } - - mismatches = 0 - first_mismatches: list[dict] = [] - grid_word_count = 0 - src_word_count = 0 - control_word_count = 0 - - def record_mismatch(entry: dict): - nonlocal mismatches - mismatches += 1 - if len(first_mismatches) < 16: - first_mismatches.append(entry) - - src_cases = tuple(c for c in SRC_MOD_CASES if c.op in ops) - flush_cases = tuple(c for c in FLUSH_CONTROL_CASES if c.op in ops) - ieee_cases = tuple(ieee_control_cases(ops)) - - for wave in waves: - for op in ops: - pairs = [(h, n) for h in EDGE_F16 for n in LDEXP_EXPS] if op == "v_ldexp_f16" else [(h, 0) for h in EDGE_F16] - for mod in MODS: - words = grid_words[(wave, op, mod)] - grid_word_count += len(words) - for (h, n), got in zip(pairs, words): - want = expected_word(op, h, n, mod=mod) - if got != want: - record_mismatch({ - "kind": "grid", "wave": wave, "op": op, "mod": mod, - "case": f"h={h:#06x},n={n}", "got": f"0x{got:08x}", "want": f"0x{want:08x}", - }) - if src_cases: - words = src_words[wave] - src_word_count += len(words) - for c, got in zip(src_cases, words): - want = expected_word(c.op, c.h, c.n, mod=c.mod, init_dst=c.init_dst, - src0_abs=c.src0_abs, src0_neg=c.src0_neg) - if got != want: - record_mismatch({ - "kind": "src_mods", "wave": wave, "op": c.op, "mod": c.mod, - "case": c.name, "got": f"0x{got:08x}", "want": f"0x{want:08x}", - }) - if flush_cases: - words = flush_words[wave] - control_word_count += len(words) - for c, got in zip(flush_cases, words): - want = (c.init_dst & 0xFFFF0000) | (c.want_lo & 0xFFFF) - if got != want: - record_mismatch({ - "kind": "flush_ctrl", "wave": wave, "op": c.op, "mod": c.mod, - "case": c.name, "got": f"0x{got:08x}", "want": f"0x{want:08x}", - }) - if ieee_cases: - words = ieee_words[wave] - control_word_count += len(words) - for c, got in zip(ieee_cases, words): - want = (c.init_dst & 0xFFFF0000) | (c.want_lo & 0xFFFF) - if got != want: - record_mismatch({ - "kind": "ieee_ctrl", "wave": wave, "op": c.op, "mod": c.mod, - "case": c.name, "got": f"0x{got:08x}", "want": f"0x{want:08x}", - }) - - wave_diffs = 0 - first_wave_diffs: list[dict] = [] - if len(waves) > 1: - w0 = waves[0] - for w in waves[1:]: - for op in ops: - for mod in MODS: - for idx, (a_w, b_w) in enumerate(zip(grid_words[(w0, op, mod)], grid_words[(w, op, mod)])): - if a_w != b_w: - wave_diffs += 1 - if len(first_wave_diffs) < 16: - first_wave_diffs.append({ - "kind": "grid", "op": op, "mod": mod, "index": idx, - f"w{w0}": f"0x{a_w:08x}", f"w{w}": f"0x{b_w:08x}", - }) - for kind, table in (("src_mods", src_words), ("flush_ctrl", flush_words), ("ieee_ctrl", ieee_words)): - if w0 in table and w in table: - for idx, (a_w, b_w) in enumerate(zip(table[w0], table[w])): - if a_w != b_w: - wave_diffs += 1 - if len(first_wave_diffs) < 16: - first_wave_diffs.append({ - "kind": kind, "index": idx, - f"w{w0}": f"0x{a_w:08x}", f"w{w}": f"0x{b_w:08x}", - }) - - omod_diffs = 0 - first_omod_diffs: list[dict] = [] - for wave in waves: - for op in ops: - for base_mod, omods in (("", ("mul:2", "mul:4", "div:2")), - ("clamp", ("clamp mul:2", "clamp mul:4", "clamp div:2"))): - base = grid_words[(wave, op, base_mod)] - for mod in omods: - for idx, (bw, mw) in enumerate(zip(base, grid_words[(wave, op, mod)])): - if bw != mw: - omod_diffs += 1 - if len(first_omod_diffs) < 16: - first_omod_diffs.append({ - "wave": wave, "op": op, "base": base_mod or "plain", "mod": mod, - "index": idx, "want": f"0x{bw:08x}", "got": f"0x{mw:08x}", - }) - if op == "v_frexp_exp_i16_f16": - base = grid_words[(wave, op, "")] - for idx, (bw, cw) in enumerate(zip(base, grid_words[(wave, op, "clamp")])): - if bw != cw: - omod_diffs += 1 - if len(first_omod_diffs) < 16: - first_omod_diffs.append({ - "wave": wave, "op": op, "base": "plain", "mod": "clamp", - "index": idx, "want": f"0x{bw:08x}", "got": f"0x{cw:08x}", - }) - - return { - "total_words": grid_word_count + src_word_count + control_word_count, - "grid_words": grid_word_count, - "src_mod_words": src_word_count, - "control_words": control_word_count, - "mismatches": mismatches, - "wave_diffs": wave_diffs, - "omod_diffs": omod_diffs, - "harness_errors": [], - "first_mismatches": first_mismatches, - "first_wave_diffs": first_wave_diffs, - "first_omod_diffs": first_omod_diffs, - } - - -def write_report(path: str, doc: dict) -> bool: - """Write JSON report with LF line endings, creating parent folders.""" - try: - os.makedirs(os.path.dirname(os.path.abspath(path)), exist_ok=True) - with open(path, "w", encoding="utf-8", newline="\n") as f: - json.dump(doc, f, indent=1) - f.write("\n") - except OSError as e: - print(f"ERROR: cannot write {path}: {e}", file=sys.stderr) - return False - return True - - -def self_test() -> int: - """Verify reference model, assembly emission, and evaluator without GPU or clang.""" - assert ref_clamp_f16(0x8000) == 0x0000 - assert ref_clamp_f16(0xFC00) == 0x0000 - assert ref_clamp_f16(0x7E00) == 0x0000 - assert ref_clamp_f16(0x7C01) == 0x0000 - assert ref_clamp_f16(0x7C00) == 0x3C00 - assert ref_clamp_f16(0x3800) == 0x3800 - - # Console MODE expectations: omod is a no-op on all 3 ops; clamp applies only to frexp_mant and ldexp. - assert expected_word("v_frexp_mant_f16", 0x3C00, mod="") == 0xDEAD3800 - assert expected_word("v_frexp_mant_f16", 0x3C00, mod="mul:2") == 0xDEAD3800 - assert expected_word("v_frexp_mant_f16", 0xBC00, mod="clamp") == 0xDEAD0000 - assert expected_word("v_frexp_mant_f16", 0x7C00, mod="clamp mul:4") == 0xDEAD3C00 - assert expected_word("v_frexp_exp_i16_f16", 0x4800, mod="") == 0xDEAD0004 - assert expected_word("v_frexp_exp_i16_f16", 0x4800, mod="clamp mul:2") == 0xDEAD0004 - assert expected_word("v_ldexp_f16", 0x3800, 1, mod="") == 0xDEAD3C00 - assert expected_word("v_ldexp_f16", 0x3800, 1, mod="mul:2") == 0xDEAD3C00 - assert expected_word("v_ldexp_f16", 0x3C00, 1, mod="clamp div:2") == 0xDEAD3C00 - assert expected_word("v_frexp_mant_f16", 0xBC00, mod="clamp", src0_neg=True) == 0xDEAD3800 - - gl, pairs = mode_grid_kernel_lines("v_ldexp_f16", "clamp mul:2", MODE_CONSOLE) - assert len(pairs) == len(EDGE_F16) * len(LDEXP_EXPS) - assert "s_setreg_imm32_b32 hwreg(HW_REG_MODE, 0, 10), 0x1c0" in gl - assert "v_ldexp_f16 v8, v1, v2 clamp mul:2" in gl - assert gl[-2:] == ["s_waitcnt vmcnt(0)", "s_endpgm"] - - sl = src_mod_kernel_lines(SRC_MOD_CASES, MODE_CONSOLE) - assert "v_frexp_mant_f16_e64 v8, -|v1| div:2" in sl - assert "v_ldexp_f16 v8, |v1|, v2 clamp mul:2" in sl - - # Synthetic evaluator pass check across all 3 ops and wave 32 - ops = list(OPS) - meta, raw = [], [] - for op in ops: - op_pairs = [(h, n) for h in EDGE_F16 for n in LDEXP_EXPS] if op == "v_ldexp_f16" else [(h, 0) for h in EDGE_F16] - for mod in MODS: - meta.append(("grid", 32, op, mod, op_pairs)) - raw.append([expected_word(op, h, n, mod=mod) for h, n in op_pairs]) - meta.append(("src_mods", 32, "all", "src_mods", SRC_MOD_CASES)) - raw.append([ - expected_word(c.op, c.h, c.n, mod=c.mod, init_dst=c.init_dst, src0_abs=c.src0_abs, src0_neg=c.src0_neg) - for c in SRC_MOD_CASES - ]) - meta.append(("flush_ctrl", 32, "all", "flush_ctrl", FLUSH_CONTROL_CASES)) - raw.append([(c.init_dst & 0xFFFF0000) | (c.want_lo & 0xFFFF) for c in FLUSH_CONTROL_CASES]) - ieee_cases = tuple(ieee_control_cases(ops)) - meta.append(("ieee_ctrl", 32, "all", "ieee_ctrl", ieee_cases)) - raw.append([(c.init_dst & 0xFFFF0000) | (c.want_lo & 0xFFFF) for c in ieee_cases]) - - ev = evaluate_results(ops, [32], meta, raw) - assert ev["mismatches"] == 0 and ev["wave_diffs"] == 0 and ev["omod_diffs"] == 0, ev - print(f"self-test ok ({ev['total_words']} synthetic words checked)") - return 0 - - -def main(argv=None) -> int: - ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) - ap.add_argument("--ops", default=",".join(OPS)) - ap.add_argument("--waves", default="32,64") - ap.add_argument("--json", help="write measurement summary JSON here") - ap.add_argument("--hw-arch") - ap.add_argument("--self-test", action="store_true") - a = ap.parse_args(argv) - if a.self_test: - return self_test() - - ops = [o.strip() for o in a.ops.split(",") if o.strip()] - wave_tokens = [w.strip() for w in a.waves.split(",") if w.strip()] - bad_ops = [o for o in ops if o not in OPS] - bad_waves = [w for w in wave_tokens if w not in ("32", "64")] - if bad_ops or bad_waves or not ops or not wave_tokens: - ap.error("unknown or empty: " + ", ".join(bad_ops + bad_waves or ["--ops/--waves"])) - waves = [int(w) for w in wave_tokens] - if a.json and os.path.isdir(a.json): - ap.error(f"--json {a.json} is a folder, not a file") - - from hw_oracle import asm, runner - - try: - oracle = runner.open_oracle(arch=a.hw_arch) - except runner.Unavailable as e: - print(f"hardware oracle unavailable: {e}") - return 77 - - try: - if asm.family(oracle.arch) != "gfx10": - print(f"hardware oracle unavailable: {oracle.arch} is not GFX10") - return 77 - print(f"hardware oracle: {oracle.device} ({oracle.arch})") - kernels, meta = build_jobs(ops, waves) - raw_results = oracle.run(kernels) - summary = evaluate_results(ops, waves, meta, raw_results) - except RuntimeError as e: - print(f"harness error: {e}") - return 2 - finally: - oracle.close() - - report = { - "device": str(oracle.device), - "arch": oracle.arch, - "waves": waves, - "ops": ops, - "mods": list(MODS), - **summary, - } - if a.json and not write_report(a.json, report): - return 2 - - if summary["harness_errors"]: - for err in summary["harness_errors"][:5]: - print(f"harness error: {err['kind']} wave{err['wave']} {err['op']} {err['mod']}: {err['error']}") - return 2 - - print( - f"total_words={summary['total_words']} (grid={summary['grid_words']}, " - f"src_mods={summary['src_mod_words']}, controls={summary['control_words']}) " - f"across {len(waves)} wave(s) x {len(ops)} op(s): " - f"mismatches={summary['mismatches']}, wave_diffs={summary['wave_diffs']}, omod_diffs={summary['omod_diffs']}" - ) - for m in summary["first_mismatches"]: - print(f" MISMATCH {m['kind']} wave{m['wave']} {m['op']} {m['mod']!r} {m['case']}: got {m['got']}, want {m['want']}") - for d in summary["first_wave_diffs"]: - print(f" WAVE DIFF {d['kind']} {d}") - for d in summary["first_omod_diffs"]: - print(f" OMOD DIFF wave{d['wave']} {d['op']} {d['base']} vs {d['mod']} idx={d['index']}: got {d['got']}, want {d['want']}") - - if summary["mismatches"] or summary["wave_diffs"] or summary["omod_diffs"]: - return 1 - return 0 - - -if __name__ == "__main__": - try: - sys.stdout.reconfigure(errors="replace") - except (AttributeError, ValueError, OSError): - pass - sys.exit(main()) diff --git a/tools/fspx_prologue_probe.py b/tools/fspx_prologue_probe.py deleted file mode 100644 index ca6bf3b40..000000000 --- a/tools/fspx_prologue_probe.py +++ /dev/null @@ -1,319 +0,0 @@ -r"""TEST-849: RDNA2 hardware probe for the 36-byte FSPX shader prologue. - -FSPX compute payloads (docs/fspx.md) start with a 36-byte (9 x u32) prologue of three 12-byte VOP3 words with opcode -0x180 (bits 31..16 = 0xD580) plus literals. llvm-mc rejects them, so docs/fspx.md inferred that they are no-ops. - -This tool tests synthetic 36-byte prologues of that form directly on an AMD GPU through tools/hw_oracle (wave32 and -wave64) and checks that VGPRs, SGPRs, M0, VCC, EXEC, SCC, multi-lane state under a partial EXEC mask, and PC -advancement (+36 bytes) are unaffected, with negative controls that prove the harness catches state changes. - -Usage: - python -I tools/fspx_prologue_probe.py # run on AMD GPU (wave32 + wave64) - python -I tools/fspx_prologue_probe.py --oracle hw # same - python -I tools/fspx_prologue_probe.py --self-test # offline check (no GPU needed) - -Exit codes: - 0 all prologue checks passed and all negative controls detected their clobbers - 1 a prologue modified state, failed to assemble/run, or a negative control went undetected - 2 bad CLI arguments - 77 hardware oracle unavailable on this machine -""" -import argparse -import os -import sys - -HERE = os.path.dirname(os.path.abspath(__file__)) -sys.dont_write_bytecode = True -if HERE not in sys.path: - sys.path.insert(0, HERE) - -from hw_oracle import asm, runner # noqa: E402 - -WORD0_FIXED_MASK = 0xFFFF0000 -WORD0_FIXED_VAL = 0xD5800000 -WORD1_FIXED_MASK = 0xFFFE0100 -WORD1_FIXED_VAL = 0x03FE0100 -TAIL_WORDS = (0xD5800000, 0x03FE0100, 0x00000AC0) - -VGPR_SENTINELS = ( - 0xA5A5A5A5, # v8 - 0x5A5A5A5A, # v9 - 0x13572468, # v10 - 0xDEADBEEF, # v11 - 0xCAFEBABE, # v12 - 0x01020304, # v13 - 0xFEDCBA98, # v14 - 0x778899AA, # v15 (toggled by 1 after the prologue to prove execution continues at +36) -) -V0_SENTINEL = 0xF00D0000 -V1_SENTINEL = 0x11223344 -SGPR_SENTINELS = tuple(0x40010000 + r for r in range(4, 16)) # s4..s15 -M0_SENTINEL = 0x76543210 -VCC_LO_SENTINEL = 0xA5A55A5A -VCC_HI_SENTINEL = 0x3C3CC3C3 -EXEC_LO_SENTINEL = 0x0F0F0F0F # bit 0 is set so lane 0 remains active -EXEC_HI_SENTINEL = 0xF0F0F0F1 -ML_TAG = 0xA5A5A500 -ML_EXEC_LO = 0x55555555 -ML_EXEC_HI = 0xAAAAAAAA - - -def build_prologue(w0_lo, s1_0, s0_0, lit0, w3_lo, s1_1, s0_1, lit1): - """Build a synthetic 9-dword FSPX prologue matching the VOP3 opcode-0x180 structural masks.""" - return ( - WORD0_FIXED_VAL | (w0_lo & 0xFFFF), - WORD1_FIXED_VAL | ((s1_0 & 0xFF) << 9) | (s0_0 & 0xFF), - lit0 & 0xFFFFFFFF, - WORD0_FIXED_VAL | (w3_lo & 0xFFFF), - WORD1_FIXED_VAL | ((s1_1 & 0xFF) << 9) | (s0_1 & 0xFF), - lit1 & 0xFFFFFFFF, - *TAIL_WORDS, - ) - - -def prologue_asm_lines(words): - """Render 9 u32 prologue words as raw assembler `.long` directives.""" - if len(words) != 9: - raise ValueError(f"expected 9 prologue dwords, got {len(words)}") - return [f".long 0x{w & 0xFFFFFFFF:08x}" for w in words] - - -# Synthetic-only patterns covering all zero, all high, targeted tested VGPRs/SGPRs, and alternating bit patterns. -PROLOGUES = { - "zero": build_prologue(0x0000, 0x00, 0x00, 0x00000000, 0x0000, 0x00, 0x00, 0x00000000), - "all_ones": build_prologue(0xFFFF, 0xFF, 0xFF, 0xFFFFFFFF, 0xFFFF, 0xFF, 0xFF, 0xFFFFFFFF), - "target_vgpr_ctrl": build_prologue(0x8008, 0x88, 0x09, 0x12345678, 0x810A, 0x6A, 0x7C, 0x9ABCDEF0), - "target_v1_v12": build_prologue(0x0001, 0x0C, 0x0B, 0xCAFEBABE, 0x000C, 0x01, 0x0F, 0x01020304), - "alt_bits": build_prologue(0xA55A, 0xAA, 0x55, 0x55AA55AA, 0x5AA5, 0x55, 0xAA, 0xA5A55A5A), -} - - -def make_vgpr_kernel(mid_lines, wave): - """Check v0, v1, v8..v15 preservation and post-prologue execution at +36 bytes.""" - lines = [ - f"v_mov_b32 v0, 0x{V0_SENTINEL:08x}", - f"v_mov_b32 v1, 0x{V1_SENTINEL:08x}", - *(f"v_mov_b32 v{8 + i}, 0x{val:08x}" for i, val in enumerate(VGPR_SENTINELS)), - *mid_lines, - "v_xor_b32 v15, v15, 1", - "v_mov_b32 v2, v0", - "v_mov_b32 v0, 0", - "global_store_b128 v0, v[8:11], s[2:3]", - "v_mov_b32 v8, v12", - "v_mov_b32 v9, v13", - "v_mov_b32 v10, v14", - "v_mov_b32 v11, v15", - "global_store_b128 v0, v[8:11], s[2:3] offset:16", - "v_mov_b32 v8, v2", - "v_mov_b32 v9, v1", - "global_store_b32 v0, v8, s[2:3] offset:32", - "global_store_b32 v0, v9, s[2:3] offset:36", - "s_waitcnt vmcnt(0)", - "s_endpgm", - ] - expected = [*VGPR_SENTINELS[:-1], VGPR_SENTINELS[-1] ^ 1, V0_SENTINEL, V1_SENTINEL] - return asm.Kernel(lines, wave=wave, threads=1, words=10, raw=True), expected - - -def make_sgpr_scc_kernel(mid_lines, wave, scc_init): - """Check s4..s15, s[0:1] equality, and SCC (0 or 1) preservation across mid_lines.""" - cmp_line = "s_cmp_eq_u32 1, 1" if scc_init else "s_cmp_eq_u32 0, 1" - lines = [ - *(f"s_mov_b32 s{4 + i}, 0x{val:08x}" for i, val in enumerate(SGPR_SENTINELS)), - "s_mov_b64 s[18:19], s[0:1]", - cmp_line, - *mid_lines, - "s_cselect_b32 s16, 1, 0", - "s_xor_b32 s20, s0, s18", - "s_xor_b32 s21, s1, s19", - "v_mov_b32 v0, 0", - "v_mov_b32 v8, s4", "v_mov_b32 v9, s5", "v_mov_b32 v10, s6", "v_mov_b32 v11, s7", - "global_store_b128 v0, v[8:11], s[2:3]", - "v_mov_b32 v8, s8", "v_mov_b32 v9, s9", "v_mov_b32 v10, s10", "v_mov_b32 v11, s11", - "global_store_b128 v0, v[8:11], s[2:3] offset:16", - "v_mov_b32 v8, s12", "v_mov_b32 v9, s13", "v_mov_b32 v10, s14", "v_mov_b32 v11, s15", - "global_store_b128 v0, v[8:11], s[2:3] offset:32", - "v_mov_b32 v8, s16", "v_mov_b32 v9, s20", "v_mov_b32 v10, s21", "v_mov_b32 v11, 0", - "global_store_b128 v0, v[8:11], s[2:3] offset:48", - "s_waitcnt vmcnt(0)", - "s_endpgm", - ] - expected = [*SGPR_SENTINELS, 1 if scc_init else 0, 0, 0] - return asm.Kernel(lines, wave=wave, threads=1, words=15, raw=True), expected - - -def make_ctrl_kernel(mid_lines, wave): - """Check M0, VCC (lo/hi), and EXEC (lo/hi) preservation across mid_lines.""" - lines = [ - f"s_mov_b32 m0, 0x{M0_SENTINEL:08x}", - f"s_mov_b32 vcc_lo, 0x{VCC_LO_SENTINEL:08x}", - f"s_mov_b32 vcc_hi, 0x{VCC_HI_SENTINEL:08x}", - f"s_mov_b32 exec_lo, 0x{EXEC_LO_SENTINEL:08x}", - f"s_mov_b32 exec_hi, 0x{EXEC_HI_SENTINEL:08x}", - *mid_lines, - "s_mov_b32 s4, m0", - "s_mov_b32 s5, vcc_lo", - "s_mov_b32 s6, vcc_hi", - "s_mov_b32 s7, exec_lo", - "s_mov_b32 s8, exec_hi", - "s_mov_b32 exec_lo, -1", - "s_mov_b32 exec_hi, -1", - "v_mov_b32 v0, 0", - "v_mov_b32 v8, s4", "v_mov_b32 v9, s5", "v_mov_b32 v10, s6", "v_mov_b32 v11, s7", - "global_store_b128 v0, v[8:11], s[2:3]", - "v_mov_b32 v8, s8", - "global_store_b32 v0, v8, s[2:3] offset:16", - "s_waitcnt vmcnt(0)", - "s_endpgm", - ] - expected = [M0_SENTINEL, VCC_LO_SENTINEL, VCC_HI_SENTINEL, EXEC_LO_SENTINEL, EXEC_HI_SENTINEL] - return asm.Kernel(lines, wave=wave, threads=1, words=5, raw=True), expected - - -def make_multilane_kernel(mid_lines, wave): - """Check all 64 lanes under a split active/inactive EXEC mask.""" - lines = [ - "v_mov_b32 v1, v0", - f"v_xor_b32 v8, v0, 0x{ML_TAG:08x}", - f"s_mov_b32 exec_lo, 0x{ML_EXEC_LO:08x}", - f"s_mov_b32 exec_hi, 0x{ML_EXEC_HI:08x}", - *mid_lines, - "s_mov_b32 exec_lo, -1", - "s_mov_b32 exec_hi, -1", - "v_xor_b32 v9, v8, v1", - "v_lshlrev_b32 v2, 2, v1", - "global_store_b32 v2, v9, s[2:3]", - "s_waitcnt vmcnt(0)", - "s_endpgm", - ] - return asm.Kernel(lines, wave=wave, threads=64, words=64, raw=True), [ML_TAG] * 64 - - -def _negative_control_specs(): - """Return (name, builder, mid_lines, check_diff_fn) tuples for known clobbers.""" - return ( - ("neg_vgpr", make_vgpr_kernel, ("v_xor_b32 v8, v8, 1",), lambda got, exp: got[0] != exp[0]), - ("neg_sgpr_scc", lambda mid, w: make_sgpr_scc_kernel(mid, w, 0), ("s_xor_b32 s8, s8, 1",), - lambda got, exp: got[4] != exp[4] and got[12] != exp[12]), - ("neg_ctrl", make_ctrl_kernel, - ("s_mov_b32 m0, 0x11111111", "s_xor_b32 vcc_lo, vcc_lo, 1", "s_xor_b32 exec_lo, exec_lo, 2"), - lambda got, exp: got[0] != exp[0] and got[1] != exp[1] and got[3] != exp[3]), - ("neg_multilane", make_multilane_kernel, ("v_xor_b32 v8, v8, 1",), - lambda got, exp: sum(a != b for a, b in zip(got, exp)) == 32), - ) - - -def build_probe_plan(waves=(32, 64)): - """Return (positive_specs, negative_specs) with (tag, kernel, expected_or_checker).""" - positives = [] - for name, words in PROLOGUES.items(): - mid = prologue_asm_lines(words) - for wave in waves: - k_vgpr, exp_vgpr = make_vgpr_kernel(mid, wave) - positives.append((f"vgpr/{name}/w{wave}", k_vgpr, exp_vgpr)) - for scc in (0, 1): - k_scc, exp_scc = make_sgpr_scc_kernel(mid, wave, scc) - positives.append((f"sgpr_scc{scc}/{name}/w{wave}", k_scc, exp_scc)) - k_ctrl, exp_ctrl = make_ctrl_kernel(mid, wave) - positives.append((f"ctrl/{name}/w{wave}", k_ctrl, exp_ctrl)) - k_ml, exp_ml = make_multilane_kernel(mid, wave) - positives.append((f"multilane/{name}/w{wave}", k_ml, exp_ml)) - - negatives = [] - for name, builder, mid, check_diff in _negative_control_specs(): - for wave in waves: - k, exp = builder(mid, wave) - negatives.append((f"{name}/w{wave}", k, exp, check_diff)) - return positives, negatives - - -def self_test(): - """Offline verification of prologue layout invariants, .long emission, and kernel generation.""" - for name, words in PROLOGUES.items(): - assert len(words) == 9, name - assert (words[0] & WORD0_FIXED_MASK) == WORD0_FIXED_VAL, name - assert (words[1] & WORD1_FIXED_MASK) == WORD1_FIXED_VAL, name - assert (words[3] & WORD0_FIXED_MASK) == WORD0_FIXED_VAL, name - assert (words[4] & WORD1_FIXED_MASK) == WORD1_FIXED_VAL, name - assert tuple(words[6:]) == TAIL_WORDS, name - lines = prologue_asm_lines(words) - assert len(lines) == 9 and all(ln.startswith(".long 0x") for ln in lines), name - - positives, negatives = build_probe_plan() - assert len(positives) == len(PROLOGUES) * 5 * 2 - assert len(negatives) == 8 - text32, names32, _ = asm.module_text([k for _, k, _ in positives if k.wave == 32], "gfx1030", wave=32) - text64, names64, _ = asm.module_text([k for _, k, _ in positives if k.wave == 64], "gfx1030", wave=64) - assert len(names32) == len(positives) // 2 and len(names64) == len(positives) // 2 - assert ".long 0xd580" in text32 and ".long 0x00000ac0" in text64 - print(f"self-test: {len(positives)} prologue cases and {len(negatives)} negative controls built cleanly") - return 0 - - -def run_hw(waves=(32, 64), arch=None): - """Run all positive prologue checks and negative controls on the AMD GPU.""" - try: - oracle = runner.open_oracle(arch=arch) - except runner.Unavailable as e: - print(f"hardware oracle unavailable: {e}", file=sys.stderr) - return 77 - - positives, negatives = build_probe_plan(waves=waves) - all_kernels = [k for _, k, _ in positives] + [k for _, k, _, _ in negatives] - try: - raw_results = oracle.run(all_kernels, words=64) - device = oracle.device - finally: - oracle.close() - - pos_results = raw_results[:len(positives)] - neg_results = raw_results[len(positives):] - - failures = [] - for (tag, k, exp), got in zip(positives, pos_results): - if isinstance(got, str): - failures.append(f"{tag}: {got}") - elif got[:k.words] != exp: - failures.append(f"{tag}: mismatch (first diff at word " - f"{next(i for i, (a, b) in enumerate(zip(got[:k.words], exp)) if a != b)})") - - for (tag, k, exp, check_diff), got in zip(negatives, neg_results): - if isinstance(got, str): - failures.append(f"{tag}: {got}") - elif not check_diff(got[:k.words], exp): - failures.append(f"{tag}: negative control failed to detect injected change") - - print(device) - if failures: - for f in failures: - print(f"FAIL {f}", file=sys.stderr) - print(f"FAIL: {len(failures)} failure(s) across {len(positives)} prologue checks and " - f"{len(negatives)} negative controls") - return 1 - - print(f"PASS: {len(positives)}/{len(positives)} prologue checks preserved all state " - f"(VGPRs, SGPRs, s[0:1], M0, VCC, EXEC, SCC=0/1, 64-lane masked EXEC, +36 PC); " - f"{len(negatives)}/{len(negatives)} negative controls detected clobbers") - return 0 - - -def main(argv=None): - ap = argparse.ArgumentParser(description=__doc__.splitlines()[0]) - ap.add_argument("--oracle", choices=("hw",), default="hw") - ap.add_argument("--wave", choices=("32", "64", "both"), default="both") - ap.add_argument("--hw-arch", default=None, help="override GPU architecture for hw_oracle") - ap.add_argument("--self-test", action="store_true") - args = ap.parse_args(argv) - - if args.self_test: - return self_test() - waves = (32, 64) if args.wave == "both" else (int(args.wave),) - return run_hw(waves=waves, arch=args.hw_arch) - - -if __name__ == "__main__": - try: # a redirected stdout is strict ANSI code page under -I; write '?' for what it cannot encode - sys.stdout.reconfigure(errors="replace") - except (AttributeError, ValueError, OSError): - pass - sys.exit(main()) diff --git a/tools/fspx_unpack.py b/tools/fspx_unpack.py deleted file mode 100644 index 5cb94813e..000000000 --- a/tools/fspx_unpack.py +++ /dev/null @@ -1,291 +0,0 @@ -"""Unpack the native compute programs in FSPX payloads: the ACCC part of the shader containers that the package's -FidelityFX upscaler DLL (amd_fidelityfx_upscaler_xbox.dll) carries instead of DXIL. Layout and meaning in -docs/fspx.md. - - DXBC container (SFI0 ISG1 OSG1 PSV0 RTS0 HASH ACCC, no DXIL) - ACCC part = FSPX payload - u32 'FSPX', u32 version, u32 entry count, u32 total size - count x {u32 kind, u32 offset, u32 size, u32 0} offsets from the start of the payload - kind 0 dispatch state (thread-group size, wave size, COMPUTE_PGM_RSRC1/2) - kind 1 20 bytes, meaning unknown (optional) - kind 6 the RDNA2 program - kind 7 resource words and the container's shader hash (optional) - -`parse_fspx` follows the DLL's own reader (RVA 0x1a20), including its status codes: 1 too short, 2 not FSPX, -4 directory longer than the payload, 5 kind 0 or kind 6 missing or empty. An entry outside the payload is skipped, -as the DLL skips it. The DLL does not check the version word. - -Usage: - python -I fspx_unpack.py [ ...] --out DIR [--disasm] [--mcpu gfx1030] - is the DLL, a .dxbc container or a bare FSPX payload. Writes, per shader, the same layout the game's shader -corpus uses, so tools/rdna2spirv.py can read it: - DIR/.dxbc the container (absent for a bare payload) - DIR/index.json [{"file": ".dxbc", "stage": "cs", ...}] - DIR/fspx/.json the decoded kind-0 entry, the directory and the code range - DIR/fspx/.code the kind-6 program - DIR/fspx/.state the kind-0 entry as it is (its SHA-256 is the index's fspx_state_sha256) - DIR/disasm/.s with --disasm: tools/shader_disasm.py output for the code after the prologue -""" -import argparse -import json -import os -import struct -import sys - -# -I keeps the script directory off sys.path, so add it explicitly before importing the sibling module. -sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) -from report_paths import path_key, same_report_path # noqa: E402 - -MAGIC = b"FSPX" -DXBC = b"DXBC" -ENDPGM = struct.pack(" bool: - """True when path is folder or below it, by the resolved and normcased name report_paths compares.""" - key, root = path_key(path), path_key(folder) - try: - return os.path.commonpath((key, root)) == root - except ValueError: # different drives - return False - - -def parse_fspx(data: bytes): - """(status, {kind: (offset, size)}) with the DLL's status codes; 0 means usable.""" - if len(data) < HEADER_SIZE: - return 1, {} - if data[:4] != MAGIC: - return 2, {} - count, total = struct.unpack_from(" total: - continue # outside the payload: the DLL ignores the entry - if kind in KINDS: - entries[kind] = (off, size) - if not entries.get(0, (0, 0))[1] or not entries.get(6, (0, 0))[1]: - return 5, entries - return 0, entries - - -def dxbc_parts(c: bytes) -> dict: - """Part tag -> payload of a DXBC container, or {} when the header doesn't fit.""" - if len(c) < 32 or c[:4] != DXBC: - return {} - total, nparts = struct.unpack_from(" len(c) or 32 + 4 * nparts > len(c): - return {} - out = {} - for k in range(nparts): - po = struct.unpack_from(" len(c): - return {} - size = struct.unpack_from(" len(c): - return {} - out[c[po:po + 4]] = c[po + 8:po + 8 + size] - return out - - -def find_containers(data: bytes): - """Every DXBC container in `data` that has an ACCC part holding an FSPX payload, as (offset, bytes).""" - found, i = [], 0 - while True: - i = data.find(DXBC, i) - if i < 0 or i + 32 > len(data): - return found - total, nparts = struct.unpack_from(" dict: - """The kind-0 words and the fields docs/fspx.md describes. `threads` is measured against PSV0; the rest is the - reading that fits the code (wave size, RSRC1/RSRC2), see docs/fspx.md for how far each one was checked.""" - w = struct.unpack_from("<7I", b) if len(b) >= 28 else () - if not w: - return {"words": list(struct.unpack_from(f"<{len(b) // 4}I", b))} - rsrc1, rsrc2 = w[5], w[6] - wave32 = bool((w[4] >> 20) & 1) - return { - "words": list(w), - "threads": [w[3] & 0xFFFF, w[3] >> 16, w[4] & 0xFFFF], - "wave32": wave32, - "rsrc1": rsrc1, - "rsrc2": rsrc2, - "vgprs": ((rsrc1 & 63) + 1) * (8 if wave32 else 4), - "user_sgprs": (rsrc2 >> 1) & 31, - "tgid_enable": [(rsrc2 >> b) & 1 for b in (7, 8, 9)], - "tidig_comp_cnt": (rsrc2 >> 11) & 3, - "lds_bytes": ((rsrc2 >> 15) & 0x1FF) * 512, - } - - -def code_range(code: bytes): - """(start, end) of the instructions in a kind-6 program: after the 36-byte prologue when it is there, through - the first s_endpgm. end is None when the program has no s_endpgm.""" - words = struct.unpack_from(f"<{len(code) // 4}I", code) - start = PROLOGUE_SIZE if len(words) > 8 and all(words[k] >> 16 == 0xD580 for k in PROLOGUE_WORDS) else 0 - pos = code.find(ENDPGM, start) - while pos >= 0 and pos % 4: - pos = code.find(ENDPGM, pos + 1) - return start, (pos + 4 if pos >= 0 else None) - - -def psv_stage(container_parts: dict): - """PSVRuntimeInfo1 ShaderStage, or None (PSV0 = u32 size of the runtime info, then the info).""" - psv = container_parts.get(b"PSV0", b"") - if len(psv) < 4: - return None - size = struct.unpack_from(" 24 and len(psv) > 4 + 24 else None - - -def unpack_payload(payload: bytes): - status, entries = parse_fspx(payload) - if status: - return None, status - blob = {k: payload[o:o + s] for k, (o, s) in entries.items()} - start, end = code_range(blob[6]) - meta = { - "version": struct.unpack_from(" int: - ap = argparse.ArgumentParser(description="Unpack the FSPX compute programs in FidelityFX shader containers.") - ap.add_argument("files", nargs="+", help="the DLL, .dxbc containers or bare FSPX payloads") - ap.add_argument("--out", required=True) - ap.add_argument("--disasm", action="store_true", help="also write disasm/.s (needs llvm-mc, see LLVM_MC)") - ap.add_argument("--mcpu", default="gfx1030", - help="llvm-mc CPU for --disasm (default gfx1030: the programs use v_dot4 instructions, which " - "gfx1010 and gfx1013 do not decode)") - a = ap.parse_args(argv) - # An output in the input folder can replace a .dxbc input and, when the input is the folder itself, - # os.makedirs writes there before open() tries to read the folder as a file. Refuse before either. - for path in a.files: - folder = path if os.path.isdir(path) else os.path.dirname(os.path.abspath(path)) - if (same_report_path(a.out, path) or same_report_path(a.out, folder) - or (os.path.isdir(path) and inside_folder(a.out, folder))): - print(f"ERROR: --out {a.out} collides with the input folder {folder}; give another output folder", - file=sys.stderr) - return 2 - fspx_dir = os.path.join(a.out, "fspx") - try: - os.makedirs(fspx_dir, exist_ok=True) - except OSError as error: - print(f"cannot create output directory {fspx_dir}: {error}", file=sys.stderr) - return 2 - disasm = None - if a.disasm: - sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) - import shader_disasm # noqa: E402 (resolves LLVM_MC at import) - disasm = shader_disasm - disasm_dir = os.path.join(a.out, "disasm") - try: - os.makedirs(disasm_dir, exist_ok=True) - except OSError as error: - print(f"cannot create output directory {disasm_dir}: {error}", file=sys.stderr) - return 2 - index, bad = [], 0 - used_names = set() - for path in a.files: - try: - with open(path, "rb") as f: - data = f.read() - except OSError as error: - print(f"{path}: cannot read input: {error}", file=sys.stderr) - bad += 1 - continue - stem = os.path.splitext(os.path.basename(path))[0] - if data[:4] == MAGIC: - items = [(0, None, data)] - else: - items = [(off, c, dxbc_parts(c)[b"ACCC"]) for off, c in find_containers(data)] - if not items: - print(f"{path}: no FSPX payload found", file=sys.stderr) - bad += 1 - continue - for n, (off, container, payload) in enumerate(items): - name = f"{stem}_{n:02d}" if len(items) > 1 else stem - got, status = unpack_payload(payload) - if not got: - print(f"{name}: FSPX status {status}", file=sys.stderr) - bad += 1 - continue - base_name = name - number = 1 - while name.casefold() in used_names: - number += 1 - name = f"{base_name}_{number}" - used_names.add(name.casefold()) - meta, blob = got - stage = psv_stage(dxbc_parts(container)) if container else None - meta["source"] = {"file": os.path.basename(path), "offset": off} - entry = {"file": name + ".dxbc", "stage": "cs" if stage in (None, STAGE_COMPUTE) else f"psv{stage}", - "source_offset": off} - if "threads" in meta: - entry["threads"] = meta["threads"] - if "wave32" in meta: - entry["wave32"] = meta["wave32"] - listing = None - if disasm and meta["code"]["end"]: - start, end = meta["code"]["start"], meta["code"]["end"] - asm, invalid, err = disasm.disasm(blob[6][start:end], a.mcpu) - if not asm.strip(): - reason = (err.strip().splitlines() or ["no output"])[0] - print(f"{name}: {reason}", file=sys.stderr) - bad += 1 - continue - entry["invalid_words"] = invalid - listing = f"; {name} code 0x{start:x}..0x{end:x} (fspx), {a.mcpu}, {invalid} invalid words\n" + asm - if err.strip(): - listing += "\n; --- llvm-mc messages ---\n; " + err.strip().replace("\n", "\n; ") + "\n" - if container: - with open(os.path.join(a.out, name + ".dxbc"), "wb") as f: - f.write(container) - with open(os.path.join(a.out, "fspx", name + ".code"), "wb") as f: - f.write(blob[6]) - with open(os.path.join(a.out, "fspx", name + ".state"), "wb") as f: - f.write(blob[0]) - with open(os.path.join(a.out, "fspx", name + ".json"), "w", encoding="utf-8", newline="\n") as f: - json.dump(meta, f, indent=1) - if listing is not None: - with open(os.path.join(a.out, "disasm", name + ".s"), "w", encoding="utf-8", newline="\n") as f: - f.write(listing) - index.append(entry) - with open(os.path.join(a.out, "index.json"), "w", encoding="utf-8", newline="\n") as f: - json.dump(index, f, indent=1) - print(f"{len(index)} FSPX program(s) unpacked to {a.out}" + (f", {bad} input(s) failed" if bad else "")) - return 1 if bad else 0 - - -if __name__ == "__main__": - try: # a redirected stdout is strict ANSI code page under -I; write '?' for what it cannot encode - sys.stdout.reconfigure(errors="replace") - except (AttributeError, ValueError, OSError): - pass - sys.exit(main()) diff --git a/tools/fssm_header.py b/tools/fssm_header.py deleted file mode 100644 index 56570fc6e..000000000 --- a/tools/fssm_header.py +++ /dev/null @@ -1,406 +0,0 @@ -"""Read the pixel-shader input table from an FSSM blob. - -FSSM is the precompiled RDNA2 program that the Xbox shader container carries. For pixel shaders a -table of 8-byte input records starts at offset 0x138. A record is present while its first byte is 6: - - byte 0 record kind (6 for an input) - byte 1 semantic id - byte 2 component mask (bit 0 = x, bit 3 = w) - byte 3 running index (same semantic id, next index) - bytes 4-5 unused here - byte 6 parameter slot - byte 7 flags, the read method: bit 0 (0x01) read through v_interp_mov_f32 (flat), - bit 1 (0x02) through v_interp_p1/p2 or the f16 forms (interpolated), bit 3 - (0x08) a Float16-typed parameter (#1256), bit 4 (0x10) a 16-bit interpolant - -The record's position in the table is the `v_interp attr` number the code uses, not byte 6 - 1. - -`directory_ok` checks the section-directory identity that most blobs follow: - - u32 at 0x120 (offset) + u32 at 0x12C (size) == u32 at 0x130 (next offset) - -All facts above are from the format description supplied with this tool. The optional stage lookup -reads the carve index (`/../index.json`) only to report how many *pixel* shaders have a -table; the decoder itself needs no index. - -On the local 26,503-blob corpus the directory identity held for 25,643 blobs (the 860 failures all -carry 0xDEADBEEF at 0x130), and 12,101 blobs were pixel shaders, 10,307 of them with a non-empty -table (55,791 records, 11,199 of them 16-bit). The table count equals the number of distinct -`v_interp attr` numbers in 11,316/12,101 shaders (93.5%); 300 more declare exactly one unread input, -475 declare two or more, and the 10 shaders whose table starts with a non-6 record are the only ones -that undercount. A 200-PS spot check agreed on 187/200. Flag bit 4 matched the 16-bit interpolant -opcodes in 12,067/12,101 (99.7%). `rdna2spirv.py` consumes it in the PS input path (pixel_interpolants: -every table position declared as a fragment input, 16-bit-flagged positions -rounded f32->f16->f32 on 32-bit reads). - -Read method (SHADER-181). Bits 0-1 say how the compiled code reads each input, not the D3D -interpolation mode (that is PSV0's, decoded by `tools/ps_interp_modes.py`, #1256). On the same -corpus exactly one of the two is set: bit 1 in 51,191 records, bit 0 in 4,600, neither or both in -none. They agree with the code in all 12,101 PS: every bit-0 position the code reads is read only -by `v_interp_mov_f32` (4,295 read positions), every bit-1 position only by `v_interp_p1/p2` or the -f16 forms (49,594), and no position is read both ways. The FSSM stores no SPI_PS_INPUT_ENA/ADDR -word. Bit 3 (0x08) is set in 11,619 records. - -The header flags word at offset 0xD4 records the compiled wave size: bit 5 (0x20) is 1 for wave32 -and 0 for wave64 (`wave_size()`). On the local 26,503-blob corpus every blob starts with `FSSM` -and is at least 0xD8 bytes long: 2,662 are wave32 (1,535 CS, 1,127 PS) and 23,841 are wave64 -(1,154 CS, 195 GS, 9,282 MS, 10,974 PS, 2,236 VS), with zero contradictions against GFX10 -code-proven wave32/wave64 instructions across all five stages. - -The post-`code_end` tail carries a binding table. After 16 bytes of `0xBF9F0000` filler and an -8-byte header, 20-byte records run until a `0xFFFFFFFF` sentinel; then `u32 0`, `u16 0`, `u16` -name length and the name. `binding_table()` returns those records. On the local 26,503-blob -corpus every blob parses (5,640,704 records), and the tail name is a substring of the container -name in all 26,503 cases, exactly equal in 691. - -Usage: - python -I fssm_header.py [--json] [--limit N] [--bindings] - -Prints one line per blob and a corpus tally: - N files, directory_ok X, PS with table Y, entries Z -""" -import argparse -import json -import os -import struct -import sys -from collections import Counter - -MAGIC = b"FSSM" -TABLE_OFFSET = 0x138 -RECORD_SIZE = 8 -RECORD_KIND = 6 -FLAG_FP16 = 0x10 -READ_MASK = 0x03 -READ_MOV = 0x01 # v_interp_mov_f32: flat -READ_INTERP = 0x02 # v_interp_p1/p2 and the f16 forms: interpolated with the v0/v1 pair -READ_NAMES = {READ_MOV: "mov", READ_INTERP: "interp"} -DIRECTORY_OFFSET = 0x120 -DIRECTORY_SIZE = 0x12C -DIRECTORY_NEXT = 0x130 -CODE_OFFSET = 0xC0 -CODE_SIZE = 0xC8 -WAVE_FLAGS_OFFSET = 0xD4 -FLAG_WAVE32 = 0x20 -CODE_END = 0xE8 -CODE_END_UNSET = 0xDEADBEEFDEADBEEF -TAIL_FILLER = 0xBF9F0000 -TAIL_PAD = 16 -TAIL_HEADER = 8 -BINDING_SIZE = 20 -BINDING_SENTINEL = 0xFFFFFFFF -MAX_BINDINGS = 100_000 - - -def _u32(blob: bytes, offset: int): - return struct.unpack_from(" len(blob) or start + TAIL_HEADER > len(blob): - return None - if blob[code_end:start] != struct.pack("= MAX_BINDINGS: - return None - records.append(struct.unpack_from("<5I", blob, offset)) - offset += BINDING_SIZE - if offset + 12 > len(blob) or _u32(blob, offset) != BINDING_SENTINEL: - return None - zero, pad, length = struct.unpack_from(" len(blob): - return None - raw_name = blob[offset + 12:offset + 12 + length] - if not all(0x20 <= byte < 0x7F for byte in raw_name): - return None - name = raw_name.decode("latin-1") - return { - "code_end": code_end, - "header": header, - "records": records, - "name": name, - "trailing": len(blob) - (offset + 12 + length), - } - - -def stage_index(path): - """Map shader stems to stages from the carve index, or {} when it is not next to the corpus. - - The index is the one `make_game.py` writes next to the carved `.dxbc` files. Both the `fssm` - directory (parent holds index.json) and a directory that contains index.json are accepted. - Prefer the local index when it has stage rows. - """ - base = path if os.path.isdir(path) else (os.path.dirname(path) or ".") - for candidate in (os.path.join(base, "index.json"), os.path.join(base, "..", "index.json")): - if os.path.isfile(candidate): - try: - with open(candidate, encoding="utf-8") as f: - rows = json.load(f) - except (OSError, ValueError): - continue - if not isinstance(rows, list): - continue - stages = {} - ambiguous = set() - for row in rows: - if not ( - isinstance(row, dict) - and isinstance(file := row.get("file"), str) - and (stem := os.path.splitext(os.path.basename(file.replace("\\", "/")))[0]) - and isinstance(stage := row.get("stage"), str) - and stage - ): - continue - if stem in ambiguous: - continue - prev = stages.get(stem) - if prev is not None and prev != stage: - del stages[stem] - ambiguous.add(stem) - else: - stages[stem] = stage - if stages: - return stages - return {} - - -def files_of(path): - if os.path.isfile(path): - return [path] - return [ - full - for name in sorted(os.listdir(path)) - if name.endswith(".fssm") and os.path.isfile(full := os.path.join(path, name)) - ] - - -def summarize(path, stages, bindings=False): - """Decode one blob and return the row used by the text and JSON output.""" - with open(path, "rb") as f: - blob = f.read() - stem = os.path.splitext(os.path.basename(path))[0] - count, fp16 = interpolants(blob) - row = { - "name": os.path.basename(path), - "stage": stages.get(stem), - "directory_ok": directory_ok(blob), - "wave_size": wave_size(blob), - "entries": count, - "fp16_mask": fp16, - "inputs": pixel_inputs(blob), - } - if bindings: - table = binding_table(blob) - row["bindings"] = None if table is None else { - "header": table["header"], - "records": len(table["records"]), - "name": table["name"], - "trailing": table["trailing"], - } - return row - - -def tally(rows, stages_known): - if stages_known: - ps = [row for row in rows if row["stage"] == "ps"] - counts = Counter(row["entries"] for row in ps) - scope = "ps" - else: - # Without a stage index, a non-empty table is the only PS signal the blob carries. - ps = [row for row in rows if row["entries"]] - # Keep the histogram in the same scope as ps_with_table/entries: non-PS blobs have no table - # and must not show up as a 0:N bucket in the reported corpus counts. - counts = Counter(row["entries"] for row in ps) - scope = "all" - methods = Counter(read_name(entry["flags"] & READ_MASK) for row in ps for entry in row["inputs"]) - waves = Counter(f"wave{ws}" for row in rows if (ws := row.get("wave_size")) is not None) - return { - "files": len(rows), - "directory_ok": sum(row["directory_ok"] for row in rows), - "ps_with_table": sum(1 for row in ps if row["entries"]), - "entries": sum(row["entries"] for row in ps), - "entry_counts": dict(sorted(counts.items())), - "entry_counts_scope": scope, - "read_methods": dict(sorted(methods.items())), - "wave_sizes": dict(sorted(waves.items())), - "stage_source": "index.json" if stages_known else "table-only", - } - - -def non_negative(text): - """--limit: a count of blobs. A negative one would slice from the end (paths[:-1] drops the last blob).""" - try: - value = int(text, 0) - except ValueError: - raise argparse.ArgumentTypeError(f"invalid int value: {text!r}") from None - if value < 0: - raise argparse.ArgumentTypeError("must be 0 or more") - return value - - -def main(argv=None): - ap = argparse.ArgumentParser(description="Read the FSSM pixel-shader input table.") - ap.add_argument("path", help="an .fssm file or a directory of them") - ap.add_argument("--json", action="store_true", help="print one JSON document instead of lines") - ap.add_argument("--limit", type=non_negative, help="stop after this many blobs") - ap.add_argument("--bindings", action="store_true", help="also parse the post-code binding table") - args = ap.parse_args(argv) - - if not os.path.exists(args.path): - print(f"ERROR: {args.path} does not exist", file=sys.stderr) - return 2 - try: - paths = files_of(args.path) - except OSError as e: - print(f"ERROR: cannot list {args.path}: {e.strerror or e}", file=sys.stderr) - return 2 - if args.limit is not None: - paths = paths[:args.limit] - stages = stage_index(args.path) - try: - rows = [summarize(path, stages, args.bindings) for path in paths] - except OSError as e: - print(f"ERROR: cannot read {e.filename or args.path}: {e.strerror or e}", file=sys.stderr) - return 2 - stages_known = any(row.get("stage") for row in rows) if rows else bool(stages) - summary = tally(rows, stages_known) - - if args.json: - json.dump({"files": rows, "tally": summary}, sys.stdout, indent=1) - sys.stdout.write("\n") - return 0 - - for row in rows: - stage = row["stage"] or "?" - wave = row["wave_size"] if row["wave_size"] is not None else "?" - print(f"{row['name']}: stage={stage} directory_ok={row['directory_ok']} " - f"entries={row['entries']} fp16=0x{row['fp16_mask']:x} wave={wave}") - if args.bindings: - table = row["bindings"] - if table is None: - print(" bindings unparsed") - else: - print(f" bindings header={table['header']} records={table['records']} " - f"name_len={len(table['name'])} trailing={table['trailing']}") - total = summary - print(f"{total['files']} files, directory_ok {total['directory_ok']}, " - f"PS with table {total['ps_with_table']}, entries {total['entries']}") - if total["wave_sizes"]: - print("wave sizes: " + ", ".join(f"{k}:{v}" for k, v in total["wave_sizes"].items())) - if total["read_methods"]: - print("read methods: " + ", ".join(f"{k}:{v}" for k, v in total["read_methods"].items())) - label = "PS entry counts" if total["entry_counts_scope"] == "ps" else "entry counts" - print(label + ": " + ", ".join(f"{k}:{v}" for k, v in total["entry_counts"].items())) - if total["stage_source"] == "table-only": - why = "no inspected blob in index.json" if stages else "no index.json found" - print(f"({why}: counted every blob with a non-empty table as a PS)") - if args.bindings: - parsed = [row for row in rows if row["bindings"]] - records = sum(row["bindings"]["records"] for row in parsed) - exact = sum(1 for row in parsed - if os.path.splitext(row["name"])[0].casefold() == row["bindings"]["name"].casefold()) - print(f"binding tables {len(parsed)}, records {records}, tail name equals file stem {exact}") - return 0 - - -if __name__ == "__main__": - try: # a redirected stdout is strict ANSI code page under -I; write '?' for what it cannot encode - sys.stdout.reconfigure(errors="replace") - except (AttributeError, ValueError, OSError): - pass - sys.exit(main()) diff --git a/tools/fssm_unpack.py b/tools/fssm_unpack.py deleted file mode 100644 index 42d3658a8..000000000 --- a/tools/fssm_unpack.py +++ /dev/null @@ -1,238 +0,0 @@ -"""Unpack the native GPU program from each carved shader container. - -Layout found in GTA VI's Xbox shaders (shader model 6.6 containers): - - DXBC - DXIL part = DxilProgramHeader (stub) + XDAT - XDAT = 'XDAT' u32 count, u32 header_size, then count x {u32 tag, u32 offset, u32 size} - (offsets are relative to the DXIL part) - tag 0x12 16-byte hash - tag 0x0d 'XBCH' u32 ?, u32 stored, u32 0, u32 unpacked, u32 0, then zlib -> 'FSSM' blob - tag 0x07 DxilProgramHeader with 'NOBC' (no LLVM bitcode is shipped) - -Some containers carry **two distinct tag-0x0D payloads** (195 of 26,503 measured). Both decompress to -valid FSSM blobs with the same code offset but different code sizes; the first is 64 or 128 bytes -longer. `xdat_entries_all` preserves their order, `xdat_entries` keeps the previous last-wins mapping -for compatibility, and `unpack()` defaults to the last payload (the one the existing corpus used) with -`payload="first"` available for the XDAT-order/SCARAB choice. The CLI exposes `--payload`. -`unpack_all()` returns every tag-0x0D payload in directory order, for callers that need both (a -two-payload VS container holds its ES and VS hardware variants; `tools/pal_stages.py` reads them). - PRIV part = Xbox private metadata - -The FSSM blob is the precompiled RDNA2 program plus its metadata. It contains the s_endpgm (0xBF810000) that ends -the code. - -Usage: - python -I fssm_unpack.py [--carve-index FILE] [--payload first|last] - (writes /fssm/.fssm and fssm_index.json) -""" -import argparse -import json -import os -import struct -import sys -import tempfile -import zlib -from collections import Counter - -# `python -I` leaves the script's directory off sys.path. -sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) -from shader_stage_manifest import shader_stems # noqa: E402 -from replace_retry import replace as replace_retry # noqa: E402 - -# Defensive per-blob ceiling, not a maximum defined by the XBCH format. -# 64 MiB matches the repository's existing per-resource cap in tools/world_index.py. -MAX_FSSM_BYTES = 64 << 20 - - -def parts(d: bytes) -> dict: - if len(d) < 32: - raise ValueError("truncated DXBC header") - count = struct.unpack_from(" len(d): - raise ValueError("truncated DXBC offset table") - out = {} - for k in range(count): - off = struct.unpack_from(" len(d): - raise ValueError(f"invalid DXBC part {k} header offset {off}") - size = struct.unpack_from(" len(d): - raise ValueError(f"truncated DXBC part {k} payload") - out[d[off:off + 4]] = d[off + 8:end] - return out - - -def xdat_entries_all(dxil: bytes) -> list: - """All XDAT entries in directory order, as (tag, payload) pairs.""" - x = dxil.find(b"XDAT") - if x < 0: - return [] - if x + 12 > len(dxil): - raise ValueError("truncated XDAT header") - count = struct.unpack_from(" len(dxil): - raise ValueError("truncated XDAT entry table") - out = [] - for k in range(count): - tag, off, size = struct.unpack_from(" len(dxil): - raise ValueError(f"XDAT entry {k} extends past the DXIL part") - if size and off < table_end and end > x: - raise ValueError(f"XDAT entry {k} overlaps its directory") - out.append((tag, dxil[off:end])) - return out - - -def xdat_entries(dxil: bytes) -> dict: - """Last payload per tag, kept for callers that want the old single-value view.""" - return {tag: payload for tag, payload in xdat_entries_all(dxil)} - - -def _inflate_xbch(blob: bytes): - """Decompress one XBCH entry payload to its FSSM blob, or None when it is not XBCH.""" - if not blob or blob[:4] != b"XBCH": - return None - stored = struct.unpack_from(" MAX_FSSM_BYTES: - raise ValueError(f"XBCH declared size {unpacked} exceeds limit {MAX_FSSM_BYTES}") - compressed = blob[24:] - if stored != len(compressed): - raise ValueError(f"XBCH stored size {stored} does not match payload size {len(compressed)}") - decompressor = zlib.decompressobj() - # The extra byte detects a stream that expands past the declared size without inflating it all. - data = decompressor.decompress(compressed, unpacked + 1) - if len(data) > unpacked: - raise ValueError(f"decompressed XBCH exceeds declared size {unpacked}") - if not decompressor.eof: - raise ValueError("truncated XBCH zlib stream") - if decompressor.unused_data: - raise ValueError("trailing data after XBCH zlib stream") - if len(data) != unpacked: - raise ValueError(f"size mismatch {len(data)} != {unpacked}") - if len(data) < 6: - raise ValueError("truncated FSSM magic or version") - if data[:4] != b"FSSM": - raise ValueError(f"invalid FSSM magic {data[:4]!r}") - return data - - -def unpack_all(dxbc: bytes): - """Every tag-0x0D payload in directory order, decompressed to its FSSM blob.""" - dxil = parts(dxbc).get(b"DXIL", b"") - out = [] - for tag, value in xdat_entries_all(dxil): - if tag == 0x0D: - data = _inflate_xbch(value) - if data is None: - raise ValueError("a tag-0x0D XDAT entry is not an XBCH payload") - out.append(data) - return out - - -def unpack(dxbc: bytes, payload: str = "last"): - p = parts(dxbc) - dxil = p.get(b"DXIL", b"") - all_entries = xdat_entries_all(dxil) - ents = {tag: value for tag, value in all_entries} - blobs = [value for tag, value in all_entries if tag == 0x0D] - if not blobs: - return None, ents - if payload == "first": - blob = blobs[0] - elif payload == "last": - blob = blobs[-1] - else: - raise ValueError(f"payload must be 'first' or 'last', not {payload!r}") - return _inflate_xbch(blob), ents - - -def main(argv=None) -> int: - ap = argparse.ArgumentParser(description="Unpack the FSSM program from each carved shader container.") - ap.add_argument("src", help="carved shader directory") - ap.add_argument("--carve-index", help="unpack only the DXBC files listed in this carve index") - ap.add_argument("--payload", choices=("first", "last"), default="last", - help="tag-0x0D payload when a container has more than one (default: last)") - a = ap.parse_args(argv) - src = a.src - # Check before anything is created: makedirs below would otherwise make a mistyped source folder. - if not os.path.isdir(src): - what = "is not a folder" if os.path.exists(src) else "does not exist" - print(f"ERROR: {src} {what}. Give the folder with the carved .dxbc files.", file=sys.stderr) - return 2 - try: - if a.carve_index: - names = shader_stems(a.carve_index, "file", ".dxbc") - shaders = sorted(os.path.join(src, name + ".dxbc") for name in names) - for path in shaders: - if not os.path.isfile(path): - raise ValueError(f"{a.carve_index}: declared shader file is missing: {path}") - else: - with os.scandir(src) as entries: - shaders = sorted(entry.path for entry in entries - if entry.name.endswith(".dxbc") and entry.is_file()) - except (OSError, ValueError) as e: - print(f"ERROR: cannot list shaders in {src}: {e}", file=sys.stderr) - return 2 - out = os.path.join(src, "fssm") - try: - os.makedirs(out, exist_ok=True) - except OSError as e: - print(f"ERROR: cannot create output directory {out}: {e.strerror or e}", file=sys.stderr) - return 2 - rows, problems = [], Counter() - for shader in shaders: - try: - with open(shader, "rb") as f: - d = f.read() - except OSError as e: - print(f"ERROR: cannot read {shader}: {e.strerror or e}", file=sys.stderr) - return 2 - try: - fssm, ents = unpack(d, payload=a.payload) - except Exception as e: # noqa: BLE001 - problems[type(e).__name__] += 1 - continue - if fssm is None: - problems["no XBCH"] += 1 - continue - stem = os.path.basename(shader)[:-5] - with open(os.path.join(out, stem + ".fssm"), "wb") as f: - f.write(fssm) - ends = [i for i in range(0, len(fssm) - 3, 4) if fssm[i:i + 4] == b"\x00\x00\x81\xbf"] - payloads = sum(1 for tag, _ in xdat_entries_all(parts(d).get(b"DXIL", b"")) if tag == 0x0D) - rows.append({"name": stem, "size": len(fssm), "magic": fssm[:4].decode("latin-1"), - "version": struct.unpack_from("] [--textures-dir ] -""" -from __future__ import annotations - -import argparse -import http.server -import json -import mimetypes -import os -import socketserver -import sys -import urllib.parse -import webbrowser - -sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) -try: - import dds_png -except ImportError: - dds_png = None - - -TEXTURE_FORMATS = { - ".dds": "DirectDraw Surface (DDS)", - ".png": "PNG Image", - ".jpg": "JPEG Image", - ".jpeg": "JPEG Image", - ".webp": "WebP Image", -} - - -def categorize_model(name: str, folder: str = "") -> str: - combined = f"{folder}/{name}".lower() - if any(k in combined for k in ("veh", "car", "truck", "bike", "wheel", "heli", "boat", "chassis", "motor", "engine")): - return "Транспорт (Vehicles)" - elif any(k in combined for k in ("weapon", "gun", "pistol", "rifle", "knife", "ammo", "shotgun", "smg")): - return "Оружие (Weapons)" - elif any(k in combined for k in ("light", "lamp", "sign", "box", "chair", "table", "prop", "debris", "anm", "amb", "core")): - return "Объекты и Пропы (Props)" - elif any(k in combined for k in ("tree", "grass", "plant", "bush", "flower", "water", "palm")): - return "Растительность (Nature)" - elif any(k in combined for k in ("build", "structure", "house", "bridge", "farlod", "station", "shop", "wall", "interior", "level", "road", "terrain")): - return "Карта и Здания (World)" - elif any(k in combined for k in ("ped", "female", "male", "head", "body", "lucia", "jason", "jacket", "face", "cloth", "skin", "_hair", "hair_")): - return "Персонажи (Characters)" - return "Прочее (Miscellaneous)" - - -_WINDOWS_RESERVED_DEVICES = frozenset({ - "CON", "PRN", "AUX", "NUL", "CONIN$", "CONOUT$", - # Windows also treats superscript 1/2/3 as device numbers; keep this fallback - # complete for Python 3.12, which has no os.path.isreserved. - *(f"COM{i}" for i in "123456789\u00b9\u00b2\u00b3"), - *(f"LPT{i}" for i in "123456789\u00b9\u00b2\u00b3"), -}) - - -def _is_reserved_segment(seg: str) -> bool: - stem = seg.split(".", 1)[0].rstrip(" ").upper() - if stem in _WINDOWS_RESERVED_DEVICES: - return True - isreserved = getattr(os.path, "isreserved", None) - if callable(isreserved) and isreserved(seg): - return True - return False - - -# Binding to 127.0.0.1 keeps other machines out, but not other web pages: a page on any site can point its own -# domain at 127.0.0.1 (DNS rebinding) and read local assets through this server as same-origin. -_LOOPBACK_HOSTS = frozenset({"127.0.0.1", "localhost", "[::1]"}) - - -def host_allowed(host: str | None) -> bool: - """True when a request's Host header names the loopback address. Browsers always send Host; a request without - one comes from a local tool, not a web page, and is allowed.""" - if host is None: - return True - host = host.strip(" \t").lower() - if host.startswith("["): # [::1] or [::1]:8080 - end = host.find("]") - if end < 0: - return False - name, rest = host[:end + 1], host[end + 1:] - if rest and not rest.startswith(":"): - return False # [::1]junk, [::1]. - port = rest[1:] if rest else None - else: - name, colon, port = host.partition(":") - if not colon: - port = None - elif ":" in port: - return False # a bare IPv6 address, or name:port:more - if name.endswith("."): # one trailing dot: the fully qualified form - name = name[:-1] - if port is not None and not (0 < len(port) <= 5 and port.isascii() and port.isdigit() and int(port) <= 65535): - return False - return name in _LOOPBACK_HOSTS - - -def safe_subpath(base_dir: str, rel: str) -> str | None: - """Resolve a relative URL path safely inside base_dir, or return None.""" - if not base_dir or not isinstance(rel, str) or not rel or "\x00" in rel: - return None - if rel.startswith(("/", "\\")) or rel.endswith(("/", "\\")): - return None - norm = rel.replace("\\", "/") - if os.path.isabs(rel) or os.path.isabs(norm): - return None - parts = norm.split("/") - for seg in parts: - if not seg or seg in (".", "..") or ":" in seg or _is_reserved_segment(seg): - return None - real_base = os.path.realpath(base_dir) - real_target = os.path.realpath(os.path.join(real_base, *parts)) - try: - common = os.path.commonpath([real_base, real_target]) - except ValueError: - return None - if os.path.normcase(common) != os.path.normcase(real_base): - return None - if os.path.normcase(real_target) == os.path.normcase(real_base): - return None - if os.path.isdir(real_target): - return None - return real_target - - -class StudioHandler(http.server.BaseHTTPRequestHandler): - models_dir: str = "" - textures_dir: str = "" - viewer_dir: str = "" - - def log_message(self, format: str, *args: object) -> None: - pass # Quiet logging - - def _check_host(self) -> bool: - hosts = self.headers.get_all("Host", []) - if len(hosts) > 1: - self.send_error(400, "Duplicate Host header") - return False - if not host_allowed(hosts[0] if hosts else None): - self.send_error(403, "Forbidden: open the gallery at http://127.0.0.1 or http://localhost") - return False - return True - - def do_GET(self) -> None: - if not self._check_host(): - return - - clean = self.path.split("#", 1)[0].split("?", 1)[0] - - if clean in ("/", "/index.html", "/studio.html"): - studio_path = os.path.join(self.viewer_dir, "studio.html") - index_path = os.path.join(self.viewer_dir, "index.html") - target = studio_path if os.path.isfile(studio_path) else index_path - if os.path.isfile(target): - self._send_file(target, "text/html; charset=utf-8") - else: - self.send_error(404, "Viewer page not found") - return - - if clean == "/api/models": - self._serve_models_json() - return - - if clean == "/api/textures": - self._serve_textures_json() - return - - if clean.startswith("/api/dds/"): - rel = urllib.parse.unquote(clean[len("/api/dds/"):]) - self._serve_dds(rel, self.path.partition("?")[2]) - return - - if clean.startswith("/vendor/"): - rel = urllib.parse.unquote(clean[len("/vendor/"):]) - vpath = safe_subpath(os.path.join(self.viewer_dir, "vendor"), rel) - if vpath is None: - self.send_error(403, "Forbidden") - return - if os.path.isfile(vpath): - mime = mimetypes.guess_type(vpath)[0] or "application/javascript" - self._send_file(vpath, mime) - else: - self.send_error(404, "Vendor file not found") - return - - if clean.startswith("/models/"): - rel = urllib.parse.unquote(clean[len("/models/"):]) - mpath = safe_subpath(self.models_dir, rel) - if mpath is None: - self.send_error(403, "Forbidden") - return - if os.path.isfile(mpath): - self._send_file(mpath, "model/gltf-binary") - else: - self.send_error(404, "Model not found") - return - - if clean.startswith("/textures/"): - rel = urllib.parse.unquote(clean[len("/textures/"):]) - tpath = safe_subpath(self.textures_dir, rel) - if tpath is None: - self.send_error(403, "Forbidden") - return - - if not os.path.isfile(tpath) and rel.lower().endswith(".png"): - # Try matching .dds file if png requested - stem = os.path.splitext(rel)[0] - dds_cand = safe_subpath(self.textures_dir, stem + ".dds") - if dds_cand is None: - self.send_error(403, "Forbidden") - return - if os.path.isfile(dds_cand) and dds_png: - try: - png_bytes = dds_png.dds_file_to_png_bytes(dds_cand, max_size=1024) - self.send_response(200) - self.send_header("Content-Type", "image/png") - self.send_header("Content-Length", str(len(png_bytes))) - self.send_header("Cache-Control", "max-age=86400") - self.end_headers() - self.wfile.write(png_bytes) - return - except Exception: - pass - - if os.path.isfile(tpath): - mime = mimetypes.guess_type(tpath)[0] or "application/octet-stream" - self._send_file(tpath, mime) - else: - self.send_error(404, "Texture not found") - return - - # Serve static assets from viewer directory (e.g. style.css, app.js) - if not clean.startswith("/"): - self.send_error(403, "Forbidden") - return - rel_viewer = urllib.parse.unquote(clean[1:]) - vfile = safe_subpath(self.viewer_dir, rel_viewer) - if vfile is None: - self.send_error(403, "Forbidden") - return - if os.path.isfile(vfile): - mime = mimetypes.guess_type(vfile)[0] or "application/octet-stream" - if mime.startswith("text/"): - mime += "; charset=utf-8" - self._send_file(vfile, mime) - return - - self.send_error(404, "Not Found") - - def _serve_dds(self, rel: str, query: str) -> None: - path = safe_subpath(self.textures_dir, rel) - if path is None: - self.send_error(403, "Forbidden") - return - if not rel.lower().endswith(".dds") or not os.path.isfile(path): - self.send_error(404, "DDS texture not found") - return - if dds_png is None: - self.send_error(503, "DDS decoder unavailable") - return - try: - if query == "info": - with open(path, "rb") as source: - info = dds_png.parse_dds_header(source.read(148)) - payload = json.dumps(info).encode("utf-8") - mime = "application/json" - else: - pairs = urllib.parse.parse_qsl(query, keep_blank_values=True, strict_parsing=True, - max_num_fields=5) - selection = {} - for key, value in pairs: - if (key not in ("mip", "layer", "z", "x", "y") or key in selection or - not value.isascii() or not value.isdecimal()): - raise ValueError("Expected a single unsigned index per selector") - selection[key] = int(value) - if "x" in selection or "y" in selection: - if "x" not in selection or "y" not in selection: - raise ValueError("Expected both texel coordinates") - payload = json.dumps(dds_png.read_half_texel(path, **selection)).encode("utf-8") - mime = "application/json" - else: - payload = dds_png.dds_file_to_png_bytes(path, max_size=1024, **selection) - mime = "image/png" - except ValueError: - self.send_error(400, "Invalid DDS texture or subresource selection") - return - except OSError: - self.send_error(500, "Could not read DDS texture") - return - self.send_response(200) - self.send_header("Content-Type", mime) - self.send_header("Content-Length", str(len(payload))) - self.send_header("Cache-Control", "no-cache") - self.end_headers() - self.wfile.write(payload) - - def _send_file(self, file_path: str, content_type: str) -> None: - # Open the file and take its size before the status line goes out. Once 200 and Content-Length are sent, - # an error can no longer become a 500: send_error would write a second response into this one's body. - try: - f = open(file_path, "rb") - except OSError as exc: - self.send_error(500, f"Could not open the file: {exc.strerror or exc}") - return - with f: - try: - size = os.fstat(f.fileno()).st_size - except OSError as exc: - self.send_error(500, f"Could not read the file: {exc.strerror or exc}") - return - self.send_response(200) - self.send_header("Content-Type", content_type) - self.send_header("Content-Length", str(size)) - self.send_header("Cache-Control", "no-cache") - self.end_headers() - remaining = size - try: - while remaining > 0 and (chunk := f.read(min(65536, remaining))): - self.wfile.write(chunk) - remaining -= len(chunk) - except OSError: - # A read error, or the client went away: the headers are out, so end the connection with a short - # body instead of appending an error page to it. - remaining = -1 - if remaining: - self.close_connection = True - - def _serve_models_json(self) -> None: - items = [] - if os.path.isdir(self.models_dir): - for root, dirs, files in os.walk(self.models_dir): - dirs.sort() - for fn in sorted(files): - if fn.lower().endswith((".glb", ".gltf")): - full_path = os.path.join(root, fn) - rel_path = os.path.relpath(full_path, self.models_dir).replace("\\", "/") - rel_dir = os.path.relpath(root, self.models_dir).replace("\\", "/") - folder_name = "Корневая папка" if rel_dir == "." else rel_dir - try: - fsize = os.path.getsize(full_path) - except OSError: - fsize = 0 - items.append({ - "name": fn, - "path": rel_path, - "folder": folder_name, - "category": categorize_model(fn, folder_name), - "size": fsize, - "url": f"/models/{urllib.parse.quote(rel_path)}", - }) - - # Group by category and folders for the UI - categories = {} - folders = {} - for item in items: - cat = item["category"] - fld = item["folder"] - categories.setdefault(cat, []).append(item) - folders.setdefault(fld, []).append(item) - - payload = json.dumps({ - "count": len(items), - "models": items, - "categories": {k: len(v) for k, v in categories.items()}, - "folders": {k: len(v) for k, v in folders.items()}, - }, ensure_ascii=False).encode("utf-8") - - self.send_response(200) - self.send_header("Content-Type", "application/json; charset=utf-8") - self.send_header("Content-Length", str(len(payload))) - self.end_headers() - self.wfile.write(payload) - - def _serve_textures_json(self) -> None: - items = [] - if os.path.isdir(self.textures_dir): - for root, dirs, files in os.walk(self.textures_dir): - dirs.sort() - for fn in sorted(files): - ext = os.path.splitext(fn)[1].lower() - if ext in TEXTURE_FORMATS: - full_path = os.path.join(root, fn) - rel_path = os.path.relpath(full_path, self.textures_dir).replace("\\", "/") - try: - fsize = os.path.getsize(full_path) - except OSError: - fsize = 0 - preview_rel = os.path.splitext(rel_path)[0] + ".png" if ext == ".dds" else rel_path - item = { - "name": fn, - "path": rel_path, - "size": fsize, - "format": TEXTURE_FORMATS[ext], - "url": f"/textures/{urllib.parse.quote(rel_path)}", - "preview": f"/textures/{urllib.parse.quote(preview_rel)}", - } - if ext == ".dds": - item["ddsPreview"] = f"/api/dds/{urllib.parse.quote(rel_path)}" - items.append(item) - - items.sort(key=lambda x: x["name"]) - payload = json.dumps({ - "count": len(items), - "textures": items, - "textures_dir": self.textures_dir, - }, ensure_ascii=False).encode("utf-8") - - self.send_response(200) - self.send_header("Content-Type", "application/json; charset=utf-8") - self.send_header("Content-Length", str(len(payload))) - self.end_headers() - self.wfile.write(payload) - - -class GalleryListenError(OSError): - """The gallery could not listen on a local port.""" - - -def start_server( - port: int = 8080, - models_dir: str | None = None, - textures_dir: str | None = None, - open_browser: bool = True, - *, - retry_next_port: bool = True, -) -> None: - here = os.path.dirname(os.path.abspath(__file__)) - root = os.path.dirname(here) - viewer_dir = os.path.join(root, "viewer") - - # Auto-locate candidate directories - if not models_dir or not os.path.isdir(models_dir): - candidates = [ - os.path.join(root, "models"), - os.path.join(root, "..", "batch_converted_glb"), - os.path.join(root, "..", "extracted_models"), - ] - best_cand = None - max_count = 0 - for cand in candidates: - if os.path.isdir(cand): - c = sum(1 for _, _, files in os.walk(cand) for f in files if f.lower().endswith(('.glb', '.gltf'))) - if c > max_count: - max_count = c - best_cand = cand - if best_cand: - models_dir = best_cand - if not models_dir or not os.path.isdir(models_dir): - models_dir = os.path.join(root, "models") - os.makedirs(models_dir, exist_ok=True) - - if not textures_dir or not os.path.isdir(textures_dir): - candidates = [ - os.path.join(root, "textures"), - os.path.join(root, "..", "clean_vehicles", "ttdb_vehicles"), - os.path.join(root, "..", "viewable_pngs"), - os.path.join(root, "..", "real_vehicle_pngs"), - ] - best_cand = None - max_count = 0 - for cand in candidates: - if os.path.isdir(cand): - c = sum(1 for f in os.listdir(cand) if os.path.splitext(f)[1].lower() in TEXTURE_FORMATS) - if c > max_count: - max_count = c - best_cand = cand - if best_cand: - textures_dir = best_cand - if not textures_dir or not os.path.isdir(textures_dir): - textures_dir = os.path.join(root, "textures") - os.makedirs(textures_dir, exist_ok=True) - - StudioHandler.models_dir = os.path.abspath(models_dir) - StudioHandler.textures_dir = os.path.abspath(textures_dir) - StudioHandler.viewer_dir = viewer_dir - - addr = ("127.0.0.1", port) - class ThreadingServer(socketserver.ThreadingMixIn, http.server.HTTPServer): - daemon_threads = True - - try: - try: - httpd = ThreadingServer(addr, StudioHandler) - except OSError: - if not retry_next_port or not 0 < port < 65535: - raise - addr = ("127.0.0.1", port + 1) - httpd = ThreadingServer(addr, StudioHandler) - except OSError as error: - raise GalleryListenError(f"can't listen on port {addr[1]}: {error}") from error - - url = f"http://localhost:{addr[1]}" - print(f"======================================================") - print(f" LEONIDA 3D ASSET STUDIO (VICE CITY EDITION) ") - print(f"======================================================") - print(f"Web Studio URL: {url}") - print(f"Models Directory: {StudioHandler.models_dir}") - print(f"Textures Directory: {StudioHandler.textures_dir}") - print(f"Viewer Directory: {StudioHandler.viewer_dir}") - print(f"Press Ctrl+C to stop.") - - if open_browser: - webbrowser.open(url) - - try: - httpd.serve_forever() - except KeyboardInterrupt: - print("\nStopping server...") - httpd.server_close() - - -def main(argv: list[str] | None = None) -> int: - parser = argparse.ArgumentParser(description="Leonida 3D Asset Studio local web gallery.") - parser.add_argument("--port", type=int, - help="HTTP port from 0 to 65535 (default 8080, or 8081 if unavailable)") - parser.add_argument("--models-dir", type=str, default=None, help="Directory containing .glb models") - parser.add_argument("--textures-dir", type=str, default=None, help="Directory containing textures") - parser.add_argument("--no-browser", action="store_true", help="Do not open browser automatically") - - args = parser.parse_args(argv) - port = 8080 if args.port is None else args.port - if not 0 <= port <= 65535: - parser.error("--port must be between 0 and 65535") - try: - start_server( - port=port, - models_dir=args.models_dir, - textures_dir=args.textures_dir, - open_browser=not args.no_browser, - retry_next_port=args.port is None, - ) - except GalleryListenError as error: - parser.error(str(error)) - return 0 - - -if __name__ == "__main__": - sys.stdout.reconfigure(errors="replace") - sys.exit(main()) diff --git a/tools/gamedata_blobs.py b/tools/gamedata_blobs.py deleted file mode 100644 index 62a0ec076..000000000 --- a/tools/gamedata_blobs.py +++ /dev/null @@ -1,427 +0,0 @@ -"""Decode the non-XML text and binary payloads of common.rpf and join to shaders.rpf. - -Targets the 3 plain-text payloads (0x640000 VFX_SETTINGS_FILE, 0x64e000 and -0x64f1c0 .fx shader preload lists) and the 2 fixed/grid binary tables -(0xad000 801x1296 B table and 0x23c000 3-region spatial grid / record table): - - python -I tools/gamedata_blobs.py [--shaders PATH/TO/shaders.rpf] [--json FILE] - -Only payload types, offsets, byte sizes, structural counts and SGD5 match counts -are printed or written; shader/setting names and raw bytes stay local. Standard -library only. -Usage: `python -I tools/gamedata_blobs.py --help` lists the options. -""" -from __future__ import annotations - -import argparse -from collections import Counter -import json -import os -import posixpath -import struct -import sys - -# -I keeps the script directory off sys.path, so add it explicitly before importing sibling helpers. -TOOLS = os.path.dirname(os.path.abspath(__file__)) -if TOOLS not in sys.path: - sys.path.insert(0, TOOLS) - -import gamedata_index as gi # noqa: E402 -import gamedata_maps as gm # noqa: E402 -from report_paths import same_report_path # noqa: E402 -import sgd5_effects as se # noqa: E402 - -COMMENT_PREFIXES = ("#", "//", ";") -CELL_SENTINEL = 0xC0000000 -CELL_OFFSET_MASK = 0x7FFFFF - - -def _is_fx_preload_lines(lines: list[str]) -> bool: - data_lines = [l.strip() for l in lines if l.strip() and not l.strip().startswith(COMMENT_PREFIXES)] - if not data_lines: - return False - return all(len(l.split()) == 1 and l.lower().endswith(".fx") for l in data_lines) - - -def parse_fx_preload_list(text: str) -> dict: - """Parse a plain-text .fx shader preload list (one filename or path per line).""" - raw_lines = text.splitlines() - entries: list[str] = [] - comment_lines = blank_lines = root_entries = subfolder_entries = 0 - for line in raw_lines: - s = line.strip() - if not s: - blank_lines += 1 - elif s.startswith(COMMENT_PREFIXES): - comment_lines += 1 - else: - toks = s.split() - if len(toks) != 1 or not toks[0].lower().endswith(".fx"): - raise ValueError(f"invalid .fx preload entry: {len(toks)} tokens") - norm = toks[0].replace("\\", "/") - if "/" in norm: - subfolder_entries += 1 - else: - root_entries += 1 - entries.append(os.path.splitext(posixpath.basename(norm))[0].lower()) - return { - "kind": "fx_preload_list", - "lines": len(raw_lines), - "entries": len(entries), - "distinct_entries": len(set(entries)), - "root_entries": root_entries, - "subfolder_entries": subfolder_entries, - "comment_lines": comment_lines, - "blank_lines": blank_lines, - "_stems": entries, - } - - -def parse_vfx_settings_dat(text: str) -> dict: - """Parse the plain-text VFX_SETTINGS_FILE ( ) table.""" - raw_lines = text.splitlines() - comment_lines = blank_lines = data_lines = scalar_pairs = equation_lines = tuple_lines = 0 - token_hist: Counter[int] = Counter() - keys: set[str] = set() - prefixes: list[str] = [] - for line in raw_lines: - s = line.strip() - if not s: - blank_lines += 1 - continue - if s.startswith(COMMENT_PREFIXES): - comment_lines += 1 - continue - data_lines += 1 - toks = s.split() - token_hist[len(toks)] += 1 - key = toks[0].lower() - keys.add(key) - prefixes.append(key.split(".", 1)[0]) - if "=" in s: - equation_lines += 1 - elif len(toks) == 2: - scalar_pairs += 1 - else: - tuple_lines += 1 - return { - "kind": "vfx_settings_dat", - "lines": len(raw_lines), - "data_lines": data_lines, - "comment_lines": comment_lines, - "blank_lines": blank_lines, - "scalar_pairs": scalar_pairs, - "equation_lines": equation_lines, - "tuple_lines": tuple_lines, - "distinct_keys": len(keys), - "distinct_prefixes": len(set(prefixes)), - "token_counts": {str(k): token_hist[k] for k in sorted(token_hist)}, - "_prefixes": sorted(set(prefixes)), - "_prefix_counts": dict(Counter(prefixes)), - } - - -def parse_fixed_table_1296(blob: bytes) -> dict: - """Decode the u32 record_count + N x 1,296-byte fixed record table (0xad000).""" - if len(blob) < 4: - raise ValueError("fixed table payload is shorter than 4-byte count") - count = struct.unpack_from(" dict: - """Decode the 3-region spatial grid / record / pointer-list blob (0x23c000).""" - if len(blob) < 16 or len(blob) % 4 != 0: - raise ValueError("spatial grid blob length must be at least 16 and 4-byte aligned") - words = struct.unpack_from(f"<{len(blob) // 4}I", blob, 0) - total_words = len(words) - - # Region 3 at the tail consists strictly of 4-byte-aligned u32 offsets into Region 2. - k = total_words - while k > 0 and 4 <= words[k - 1] < len(blob) and words[k - 1] % 4 == 0: - k -= 1 - if k == total_words or k == 0: - raise ValueError("missing trailing Region 3 offset table") - region3_start = k * 4 - region3 = words[k:] - - # Region 2 starts at the lowest target offset referenced by Region 3. - region2_start = min(region3) - if region2_start == 0 or region2_start >= region3_start or region2_start % 4 != 0: - raise ValueError(f"invalid Region 2 start {region2_start:#x} vs Region 3 {region3_start:#x}") - if any(w < region2_start or w >= region3_start or w % 4 != 0 for w in region3): - raise ValueError("Region 3 offset leaves Region 2 bounds") - - grid = words[:region2_start // 4] - empty_cells = sum(1 for w in grid if w == CELL_SENTINEL) - populated = [w for w in grid if w != CELL_SENTINEL] - cell_offs = [w & CELL_OFFSET_MASK for w in populated] - if not populated or any(o < region3_start or o >= len(blob) or o % 4 != 0 for o in cell_offs): - raise ValueError("Region 1 cell offset leaves Region 3 bounds") - - r2_targets = sorted(set(region3)) - if r2_targets[0] != region2_start: - raise ValueError("Region 2 does not start at first referenced record") - r2_bounds = r2_targets + [region3_start] - r2_word_hist = Counter((r2_bounds[i + 1] - r2_bounds[i]) // 4 for i in range(len(r2_targets))) - - r3_targets = sorted(set(cell_offs)) - if r3_targets[0] != region3_start: - raise ValueError(f"Region 3 start {region3_start:#x} does not match lowest cell offset {r3_targets[0]:#x}") - r3_bounds = r3_targets + [len(blob)] - r3_span_lens = [(r3_bounds[i + 1] - r3_bounds[i]) // 4 for i in range(len(r3_targets))] - - return { - "kind": "spatial_grid_table", - "grid_cells": len(grid), - "empty_cells": empty_cells, - "populated_cells": len(populated), - "distinct_cell_offsets": len(r3_targets), - "cells_in_region3": len(populated), - "region2_offset": region2_start, - "region2_bytes": region3_start - region2_start, - "region2_records": len(r2_targets), - "region2_record_words_hist": {str(sz): r2_word_hist[sz] for sz in sorted(r2_word_hist)}, - "region3_offset": region3_start, - "region3_bytes": len(blob) - region3_start, - "region3_end_inclusive": len(blob) - 1, - "region3_words": len(region3), - "region3_words_in_region2": len(region3), - "region3_spans": len(r3_targets), - "region3_span_words_min": min(r3_span_lens), - "region3_span_words_max": max(r3_span_lens), - } - - -def _read_group_bytes(source, rows: list[dict], start: int, chunks: int) -> bytes: - return b"".join(source.read(rows[start + idx]) for idx in range(chunks)) - - -def _analyze_from_source(source) -> list[dict]: - grouped = gi.build_rows(source.rows, source) - off_to_idx = {r["off"]: idx for idx, r in enumerate(source.rows)} - out = [] - for row in grouped: - if row["type"] not in ("text", "binary"): - continue - blob = _read_group_bytes(source, source.rows, off_to_idx[row["offset"]], row["chunks"]) - item = { - "offset": row["offset"], - "offset_hex": row["offset_hex"], - "stored": row["stored"], - "size": row["size"], - "chunks": row["chunks"], - "archive_type": row["type"], - } - if row["type"] == "text": - text = blob.decode("utf-8", "replace") - if _is_fx_preload_lines(text.splitlines()): - item.update(parse_fx_preload_list(text)) - else: - item.update(parse_vfx_settings_dat(text)) - else: - count0 = struct.unpack_from("= 4 else 0 - if count0 > 0 and len(blob) == 4 + count0 * 1296: - item.update(parse_fixed_table_1296(blob)) - else: - item.update(parse_spatial_grid_blob(blob)) - out.append(item) - return out - - -def check_carve_index(directory: str) -> list[dict]: - """Name the index and the bad row of a folder that is not an rpf9_carve.py carve, before the scan. - - DirectorySource reads `index['files']` and each row's `off` and `stored` straight through, so a hand-edited - or half-written index fails as `error: 'files'` and names nothing. - """ - index_path = os.path.join(directory, "index.json") - if not os.path.isfile(index_path): - raise ValueError(f"{directory} is not an rpf9_carve.py folder (no index.json)") - try: - with open(index_path, encoding="utf-8-sig") as f: - index = json.load(f) - except OSError as e: - raise ValueError(f"cannot read {index_path}: {e.strerror or e}") from e - except ValueError as e: - raise ValueError(f"{index_path} is not valid JSON: {e}") from e - rows = index.get("files") if isinstance(index, dict) else None - if not isinstance(rows, list): - raise ValueError(f"{index_path} has no 'files' list") - for i, row in enumerate(rows): - if not isinstance(row, dict) or "off" not in row or "stored" not in row: - raise ValueError(f"{index_path}: row {i} needs an 'off' and a 'stored'") - return sorted(rows, key=lambda r: r["off"]) - - -def read_payloads(target: str) -> list[dict]: - """Decode all text and binary payloads from an rpf9_carve.py dir or .rpf archive.""" - if os.path.isdir(target): - check_carve_index(target) - source = gi.DirectorySource(target) - return _analyze_from_source(source) - if not os.path.isfile(target): - raise ValueError(f"{target}: no such file or folder") - source = gi.ArchiveSource(target) - try: - return _analyze_from_source(source) - finally: - source.close() - - -def _is_subsequence(subseq: list[str], target_seq: list[str]) -> bool: - it = iter(target_seq) - return all(item in it for item in subseq) - - -def cross_reference_sgd5(payloads: list[dict], shaders_rpf: str) -> dict: - """Compare .fx preload lists and vfx prefixes against shaders.rpf SGD5 DB0/DB1.""" - with open(shaders_rpf, "rb") as stream: - db0_list = [m["effect"].lower() for m in se.read_database(stream, se.DATABASES[0], list_effects=True)["matches"]] - db1_list = [m["effect"].lower() for m in se.read_database(stream, se.DATABASES[1], list_effects=True)["matches"]] - - db0_set = set(db0_list) - db1_set = set(db1_list) - preload_checks = [] - vfx_prefix_matches = [] - - for p in payloads: - if p["kind"] == "fx_preload_list": - stems = p["_stems"] - in_db0 = [s for s in stems if s in db0_set] - in_db1 = [s for s in stems if s in db1_set] - preload_checks.append({ - "offset_hex": p["offset_hex"], - "entries": p["entries"], - "in_db0": len(in_db0), - "in_db1": len(in_db1), - "unshipped": p["entries"] - len(in_db0) - len(in_db1), - "exact_order_db0": in_db0 == db0_list and _is_subsequence(db0_list, stems), - "exact_order_db1": in_db1 == db1_list and _is_subsequence(db1_list, stems), - }) - elif p["kind"] == "vfx_settings_dat": - prefixes = set(p["_prefixes"]) - pfx_counts = p["_prefix_counts"] - vfx_prefix_matches.append({ - "offset_hex": p["offset_hex"], - "data_lines": p["data_lines"], - "distinct_prefixes": p["distinct_prefixes"], - "prefixes_in_db0": len(prefixes & db0_set), - "prefixes_in_db1": len(prefixes & db1_set), - "data_lines_in_db0": sum(c for k, c in pfx_counts.items() if k in db0_set), - "data_lines_in_db1": sum(c for k, c in pfx_counts.items() if k in db1_set), - }) - - return { - "sgd5_db0_effects": len(db0_list), - "sgd5_db1_effects": len(db1_list), - "preload_lists": preload_checks, - "vfx_settings": vfx_prefix_matches, - } - - -def check_report_path(out_path: str, target: str, shaders_rpf: str | None = None, - rows: list[dict] | None = None) -> None: - """Refuse a --json destination that is a directory or aliases any input file.""" - if os.path.isdir(out_path): - raise ValueError(f"--json is a directory: {out_path}") - if shaders_rpf and same_report_path(out_path, shaders_rpf): - raise ValueError(f"--json would overwrite the input {shaders_rpf}") - if os.path.isdir(target): - gm.check_report_path(out_path, target, rows=rows) - elif same_report_path(out_path, target): - raise ValueError(f"--json would overwrite the input {target}") - - -def _public(payload: dict) -> dict: - return {k: v for k, v in payload.items() if not k.startswith("_")} - - -def main(argv=None) -> int: - ap = argparse.ArgumentParser(description=__doc__.splitlines()[0]) - ap.add_argument("target", help="rpf9_carve.py directory or common.rpf archive") - ap.add_argument("--shaders", help="shaders.rpf archive to verify preload lists against SGD5 DB0/DB1") - ap.add_argument("--json", help="write aggregate decoded counts to this JSON") - a = ap.parse_args(argv) - - if not os.path.exists(a.target): - print(f"ERROR: cannot read {a.target}: no such file or folder", file=sys.stderr) - return 2 - try: - if a.json: - check_report_path(a.json, a.target, a.shaders) - if os.path.isdir(a.target): - rows = check_carve_index(a.target) - if a.json: - check_report_path(a.json, a.target, a.shaders, rows=rows) - payloads = read_payloads(a.target) - xref = cross_reference_sgd5(payloads, a.shaders) if a.shaders else None - except (OSError, ValueError, KeyError, TypeError, struct.error, RuntimeError) as e: - print("error:", e, file=sys.stderr) - return 1 - - for p in payloads: - k = p["kind"] - if k == "fx_preload_list": - print(f'text {p["offset_hex"]}: fx_preload_list, {p["entries"]} entries ({p["root_entries"]} root)') - elif k == "vfx_settings_dat": - print(f'text {p["offset_hex"]}: vfx_settings_dat, {p["lines"]} lines ' - f'({p["data_lines"]} data, {p["scalar_pairs"]} pairs, {p["distinct_prefixes"]} prefixes)') - elif k == "fixed_table_1296": - print(f'binary {p["offset_hex"]}: fixed_table_1296, {p["record_count"]} x {p["record_bytes"]} B ' - f'({p["duplicated_header_pairs"]}/{p["record_count"]} paired headers)') - else: - print(f'binary {p["offset_hex"]}: spatial_grid_table, {p["grid_cells"]} cells ' - f'({p["empty_cells"]} empty), {p["region2_records"]} records, {p["region3_words"]} ptrs') - if not payloads: - print("no text or binary payloads") - if xref is not None: - for row in xref["preload_lists"]: - print(f'SGD5 xref {row["offset_hex"]}: in_db0={row["in_db0"]} (order={row["exact_order_db0"]}), ' - f'in_db1={row["in_db1"]} (order={row["exact_order_db1"]}), unshipped={row["unshipped"]}') - for row in xref["vfx_settings"]: - print( - f'VFX xref {row["offset_hex"]}: {row["prefixes_in_db0"]}/{row["distinct_prefixes"]} prefixes ' - f'({row["data_lines_in_db0"]}/{row["data_lines"]} data lines) in DB0' - ) - - if a.json: - out: dict = {"payloads": [_public(p) for p in payloads]} - if xref is not None: - out["sgd5_xref"] = xref - try: - gm._make_parent(a.json) - with open(a.json, "w", encoding="utf-8", newline="\n") as f: - json.dump(out, f, indent=1) - except OSError as e: - print(f"error: cannot write {a.json}: {e.strerror or e}", file=sys.stderr) - return 1 - print("wrote", a.json) - return 0 - - -if __name__ == "__main__": - try: # a redirected stdout is strict ANSI code page under -I; write '?' for what it cannot encode - sys.stdout.reconfigure(errors="replace") - except (AttributeError, ValueError, OSError): - pass - sys.exit(main()) diff --git a/tools/gamedata_graph.py b/tools/gamedata_graph.py deleted file mode 100644 index 3938627b6..000000000 --- a/tools/gamedata_graph.py +++ /dev/null @@ -1,646 +0,0 @@ -"""Build a content-set and reference graph for the ``common.rpf`` XML catalog. - -``gamedata_xml.py`` catalogs the XML documents recovered from an RPF9 carve and counts reference -tokens, but it drops the target strings. This tool keeps them long enough to build and measure a -directed graph: - - python -I gamedata_graph.py [--json FILE] - python -I gamedata_graph.py [ ...] [--json FILE] - -A carve directory is read through ``gamedata_xml.load_documents``, so multi-stream documents are -rebuilt the same way as the index and catalog. For each parsed document the graph has: - -* a document node; -* a content-set node for every ```` (a top-level id or an id inside ````); -* a target node for every ````, ``parentPath`` and ``parentFile`` value and every - ```` value in ````. - -Edges are ``defines`` (document to its sets), ``includes`` (document to an ```` id), -``contains_file`` (set or document to a filename target), ``loads_changeset`` (document to a -```` target), and ``parent_path`` / ``parent_file`` for the two attributes. An include is -joined to a document only when its text equals a set id exactly. Missing ids become dangling -content-set nodes. They are never guessed from a similar spelling. - -The four documented prefix rules are measured: ``$(common)``, ``$(root)``, ``$(target)``, and -``platform:/`` split into ``levels`` and everything else. ``common:/`` occurs in the corpus but is -not one of those rules, so it is reported as an unrecognized scheme and is not normalized to -``$(common)``. ``parentPath`` values are XPath-like locators, not archive paths. Those of the form -``../Tag[@attr='value']`` are also followed inside their own document (exact match on a sibling of -the element) and reported under ``parent_path_inheritance``: resolved, ambiguous and unresolved -sites, inheritance chain depths and cycles. They never become document edges. - -The output is aggregate and schema-only: counts, root names, category names and reference prefixes. -Target strings, ids, offsets, source names and element values are never written. This keeps the JSON reviewable without copying game data, and the tests are -synthetic. The encrypted RPF9 table of contents is still the reason an archive path cannot be -mapped to a carved document; those targets remain target nodes rather than invented document -edges. This is a mount/reference graph, not a full runtime schema: the catalog carries names and -categories, not field types. -Usage: `python -I tools/gamedata_graph.py --help` lists the options. -""" -import argparse -import json -import os -import re -import sys -import xml.etree.ElementTree as ET -from collections import Counter, defaultdict, deque - -ROOT = os.path.dirname(os.path.abspath(__file__)) -if ROOT not in sys.path: - sys.path.insert(0, ROOT) -import gamedata_xml as gx # noqa: E402 - -MANIFEST_ROOTS = ("CDataFileMgr__ContentChangeSetDef", "CDataFileMgr__ContentDef") -MANIFEST_ROOT_SET = frozenset(MANIFEST_ROOTS) -KNOWN_MACROS = frozenset(("common", "target", "root")) -PARENT_ATTRIBUTES = ("parentPath", "parentFile") - -MACRO_REF = re.compile(r"^\$\(([A-Za-z_][\w.-]*)\)(.*)$", re.S) -PLATFORM_REF = re.compile(r"^platform:/([^/]*)(.*)$", re.I | re.S) -SCHEME_REF = re.compile(r"^([A-Za-z][\w.-]*):/(.*)$", re.S) -PARENT_SIBLING = re.compile(r"\.\./([A-Za-z_][\w.-]*)\[@([A-Za-z_][\w.-]*)=(['\"])(.*?)\3\]", re.S) -RELATIVE = "relative/locator" - - -def classify_target(text: str) -> tuple: - """Return (namespace, remainder, resolution reason) for one reference string.""" - value = text.strip() - match = MACRO_REF.match(value) - if match: - name = match.group(1) - namespace = "$(" + name + ")" - remainder = match.group(2).lstrip("/") - if name.lower() in KNOWN_MACROS: - return namespace, remainder, "document_unmapped" - return namespace, remainder, "unknown_macro" - match = PLATFORM_REF.match(value) - if match: - first = (match.group(1) or "").lower() - namespace = "platform:/levels" if first == "levels" else "platform:/other" - return namespace, (match.group(1) or "") + match.group(2), "document_unmapped" - match = SCHEME_REF.match(value) - if match: - return match.group(1).lower() + ":/", match.group(2), "unrecognized_prefix" - return RELATIVE, value, "relative_locator" - - -def _text(element) -> str: - return (element.text or "").strip() if element is not None else "" - - -def _direct_id(element) -> str: - for child in element: - if child.tag == "id": - value = _text(child) - if value: - return value - return "" - - -def _add_filename_refs(report: dict, scope, owner: str, seen: set) -> None: - if scope is None: - return - for filename in scope.iter("filename"): - if filename in seen: - continue - seen.add(filename) - value = _text(filename) - if value: - report["refs"].append({"kind": "filename", "target": value, "owner": owner}) - - -def scan_document(doc: dict) -> dict: - """Parse one payload and keep only the graph-relevant names and reference strings.""" - report = { - "root": "", - "parsed": False, - "complete": bool(doc.get("complete", False)), - "sets": [], - "refs": [], - "includes": [], - } - data = doc["data"] - try: - root = ET.fromstring(data) - except (ET.ParseError, ValueError, LookupError): - # A truncated tail can still carry a closing-root hint from the index. It is a named but - # unparsed document, not a rootless fragment; only an empty hint is rootless. - report["root"] = doc.get("root_hint") or "" - return report - report["parsed"] = True - report["root"] = root.tag - report["complete"] = bool(doc.get("complete", True)) - - own = _direct_id(root) - if own: - report["sets"].append(own) - - content_sets = root.find("contentSets") - if content_sets is not None: - for item in content_sets: - set_id = _direct_id(item) - if set_id: - report["sets"].append(set_id) - - seen = set() - report["sets"] = [set_id for set_id in report["sets"] - if not (set_id in seen or seen.add(set_id))] - - filenames = set() - _add_filename_refs(report, root.find("fileList"), own, filenames) - - if content_sets is not None: - for item in content_sets: - set_id = _direct_id(item) - if set_id: - _add_filename_refs(report, item.find("fileList"), set_id, filenames) - - _add_filename_refs(report, root, "", filenames) - - changesets = root.find("includedChangesets") - if changesets is not None: - for load_path in changesets.iter("loadPath"): - value = _text(load_path) - if value: - report["refs"].append({"kind": "loadPath", "target": value, "owner": ""}) - - included = root.find("includedSets") - if included is not None: - for item in included: - value = "".join(item.itertext()).strip() - if value: - report["includes"].append(value) - - for element in root.iter(): - for attribute in PARENT_ATTRIBUTES: - value = (element.attrib.get(attribute) or "").strip() - if value: - report["refs"].append({"kind": attribute, "target": value, "owner": ""}) - report["parent_links"] = resolve_parent_paths(root) - return report - - -def resolve_parent_paths(root) -> dict: - """Follow ``parentPath`` locators of the form ``../Tag[@attr='value']`` inside one document. - - ``..`` is the element's parent and the predicate selects the sibling with that exact attribute - value. Returns counts plus the inheritance links as element positions (no strings), so chain - depth and cycles can be measured without keeping any value. - """ - parent_of = {child: parent for parent in root.iter() for child in parent} - position = {element: index for index, element in enumerate(root.iter())} - result = {"sites": 0, "xpath_sibling": 0, "resolved": 0, "ambiguous": 0, "links": []} - for element in root.iter(): - value = (element.attrib.get("parentPath") or "").strip() - if not value: - continue - result["sites"] += 1 - match = PARENT_SIBLING.fullmatch(value) - container = parent_of.get(element) - if not match or container is None: - continue - result["xpath_sibling"] += 1 - tag, attribute, wanted = match.group(1), match.group(2), match.group(4) - hits = [sibling for sibling in container - if sibling.tag == tag and sibling.attrib.get(attribute) == wanted] - if len(hits) == 1: - result["resolved"] += 1 - result["links"].append((position[element], position[hits[0]])) - elif hits: - result["ambiguous"] += 1 - return result - - -def parent_chains(links: list) -> tuple: - """Return (depth histogram over the linked children, cycle count) for one document's links.""" - parent = dict(links) - depths = Counter() - cycles = 0 - for child in parent: - seen = {child} - node, depth = child, 0 - while node in parent: - node = parent[node] - depth += 1 - if node in seen: - cycles += 1 - break - seen.add(node) - else: - depths[depth] += 1 - return depths, cycles - - -def _strongly_connected(nodes: list, adjacency: dict) -> list: - """Tarjan's algorithm with an explicit stack for deep include chains.""" - index = {} - low = {} - stack = [] - on_stack = set() - components = [] - pending = [] - - def enter(node): - index[node] = low[node] = len(index) - stack.append(node) - on_stack.add(node) - pending.append((node, iter(adjacency.get(node, ())))) - - for root in nodes: - if root in index: - continue - enter(root) - while pending: - node, neighbours = pending[-1] - neighbour = next(neighbours, None) - if neighbour is not None: - if neighbour not in index: - enter(neighbour) - elif neighbour in on_stack: - low[node] = min(low[node], index[neighbour]) - continue - - pending.pop() - if low[node] == index[node]: - component = [] - while True: - member = stack.pop() - on_stack.remove(member) - component.append(member) - if member == node: - break - components.append(component) - if pending: - parent = pending[-1][0] - low[parent] = min(low[parent], low[node]) - return components - - -def build_graph(documents: list) -> dict: - """Build nodes, edges, unresolved buckets and aggregates from scanned documents.""" - reports = [scan_document(doc) for doc in documents] - set_docs = defaultdict(list) - all_set_ids = set() - for index, report in enumerate(reports): - for set_id in report["sets"]: - set_docs[set_id].append(index) - all_set_ids.add(set_id) - for set_id in report["includes"]: - all_set_ids.add(set_id) - - target_ids = {} - for report in reports: - for ref in report["refs"]: - namespace, remainder, _ = classify_target(ref["target"]) - key = (namespace, remainder) - if key not in target_ids: - target_ids[key] = len(target_ids) - - edges = Counter() - references = Counter() - prefixes = Counter() - resolution = Counter() - unresolved_sites = Counter() - unresolved_namespaces = defaultdict(Counter) - unique_resolution = defaultdict(set) - target_edges = [] - include_edges = [] - dangling_sets = set() - - for index, report in enumerate(reports): - for set_id in report["sets"]: - edges["defines"] += 1 - for set_id in report["includes"]: - references["includedSets"] += 1 - edges["includes"] += 1 - if set_id in set_docs: - resolution["document"] += 1 - for target_doc in set_docs[set_id]: - include_edges.append((index, target_doc)) - else: - resolution["include_id_missing"] += 1 - unresolved_sites["include_id_missing"] += 1 - dangling_sets.add(set_id) - - for ref in report["refs"]: - kind = ref["kind"] - namespace, remainder, reason = classify_target(ref["target"]) - references[kind] += 1 - prefixes[namespace] += 1 - resolution[reason] += 1 - unique_resolution[reason].add((namespace, remainder)) - if reason == "document_unmapped": - unresolved_sites["document_unmapped"] += 1 - unresolved_namespaces["document_unmapped"][namespace] += 1 - elif reason == "unrecognized_prefix": - unresolved_sites["unrecognized_prefix"] += 1 - unresolved_namespaces["unrecognized_prefix"][namespace] += 1 - elif reason == "unknown_macro": - unresolved_sites["unknown_macro"] += 1 - unresolved_namespaces["unknown_macro"][namespace] += 1 - elif reason == "relative_locator": - unresolved_sites["relative_locator"] += 1 - if kind == "filename": - edges["contains_file"] += 1 - edge_kind = "contains_file" - elif kind == "loadPath": - edges["loads_changeset"] += 1 - edge_kind = "loads_changeset" - elif kind == "parentPath": - edges["parent_path"] += 1 - edge_kind = "parent_path" - else: - edges["parent_file"] += 1 - edge_kind = "parent_file" - target_edges.append((index, ref["owner"], edge_kind, (namespace, remainder))) - - include_edges = sorted(set(include_edges)) - adjacency = defaultdict(set) - for source, target in include_edges: - adjacency[source].add(target) - in_degree = Counter() - for _, target in include_edges: - in_degree[target] += 1 - - manifest_documents = [index for index, report in enumerate(reports) - if report["parsed"] and report["root"] in MANIFEST_ROOT_SET] - roots = [index for index in manifest_documents if in_degree[index] == 0] - root_fallback = False - if not roots and manifest_documents: - roots = list(manifest_documents) - root_fallback = True - - depth = {index: 0 for index in roots} - queue = deque(roots) - reachable_docs = set() - while queue: - source = queue.popleft() - if source in reachable_docs: - continue - reachable_docs.add(source) - for target in adjacency.get(source, ()): - if target not in depth: - depth[target] = depth[source] + 1 - queue.append(target) - - components = _strongly_connected(list(range(len(reports))), adjacency) - cycle_components = [component for component in components - if len(component) > 1 or component[0] in adjacency.get(component[0], ())] - cycle_nodes = sum(len(component) for component in cycle_components) - - reachable_sets = set() - reachable_targets = set() - reachable_target_sites = 0 - for index in reachable_docs: - report = reports[index] - reachable_sets.update(report["sets"]) - reachable_sets.update(report["includes"]) - for index, owner, _, key in target_edges: - if index in reachable_docs and (not owner or owner in reachable_sets): - reachable_target_sites += 1 - reachable_targets.add(key) - - category_stats = defaultdict(Counter) - root_stats = defaultdict(Counter) - for report in reports: - root = report["root"] - category = gx.category_for(root) if root else gx.UNCATALOGUED - for stats in (category_stats[category], root_stats[root]): - stats["documents"] += 1 - stats["parsed"] += int(report["parsed"]) - stats["complete"] += int(report["complete"]) - stats["content_sets"] += len(report["sets"]) - stats["include_references"] += len(report["includes"]) - stats["target_references"] += len(report["refs"]) - stats["references"] += len(report["refs"]) + len(report["includes"]) - if root in MANIFEST_ROOT_SET: - category_stats[category]["manifest_documents"] += 1 - root_stats[root]["manifest_documents"] += 1 - - # Root names are stable schema names; category is the only derived label. - for root, stats in root_stats.items(): - stats["category"] = gx.category_for(root) if root else gx.UNCATALOGUED - - unique_by_namespace = Counter() - for namespace, _ in target_ids: - unique_by_namespace[namespace] += 1 - - # parentPath locators followed inside their own document (no archive path is involved). - inherit = Counter() - inherit_depths = Counter() - inherit_documents = 0 - for report in reports: - links = report.get("parent_links") - if not links or not links["sites"]: - continue - inherit_documents += 1 - for name in ("sites", "xpath_sibling", "resolved", "ambiguous"): - inherit[name] += links[name] - depths, cycles = parent_chains(links["links"]) - inherit_depths.update(depths) - inherit["cycles"] += cycles - - summary = { - "mode": "", - "payloads": len(reports), - "documents": sum(1 for report in reports if report["complete"]), - "parsed": sum(1 for report in reports if report["parsed"]), - "unparsed": sum(1 for report in reports if not report["parsed"]), - "root_count": len([root for root in root_stats if root]), - "rootless": sum(1 for report in reports if not report["root"]), - "manifest_documents": len(manifest_documents), - "manifest_roots": len(MANIFEST_ROOTS), - "content_sets": len(all_set_ids), - "defined_content_sets": len(set_docs), - "dangling_content_sets": len(dangling_sets), - "duplicate_set_ids": sum(1 for indexes in set_docs.values() if len(indexes) > 1), - "reference_sites": sum(references.values()), - "target_sites": sum(references[kind] for kind in - ("filename", "loadPath", "parentPath", "parentFile")), - "include_sites": references["includedSets"], - "references": dict(sorted(references.items())), - "prefixes": dict(sorted(prefixes.items())), - "resolution": dict(sorted(resolution.items())), - "unique": { - "targets": len(target_ids), - "targets_by_namespace": dict(sorted(unique_by_namespace.items())), - "document_unmapped": len(unique_resolution["document_unmapped"]), - "unknown_macro": len(unique_resolution["unknown_macro"]), - "unrecognized_prefix": len(unique_resolution["unrecognized_prefix"]), - "relative_locator": len(unique_resolution["relative_locator"]), - "content_set_ids": len(all_set_ids), - "include_ids": len({set_id for report in reports for set_id in report["includes"]}), - }, - "nodes": { - "documents": len(reports), - "content_sets": len(all_set_ids), - "targets": len(target_ids), - "total": len(reports) + len(all_set_ids) + len(target_ids), - }, - "edges": { - "total": sum(edges.values()), - "defines": edges["defines"], - "includes": edges["includes"], - "contains_file": edges["contains_file"], - "loads_changeset": edges["loads_changeset"], - "parent_path": edges["parent_path"], - "parent_file": edges["parent_file"], - "document_edges": edges["defines"] + edges["includes"], - "target_edges": (edges["contains_file"] + edges["loads_changeset"] + - edges["parent_path"] + edges["parent_file"]), - }, - "content_graph": { - "include_edges": len(include_edges), - "documents_with_incoming_includes": len(in_degree), - "documents_with_outgoing_includes": sum(1 for report in reports - if report["includes"]), - "root_documents": len(roots), - "root_fallback": root_fallback, - "reachable_documents": len(reachable_docs), - "max_depth": max(depth.values(), default=0), - "cycles": len(cycle_components), - "cycle_nodes": cycle_nodes, - }, - "reachable": { - "documents": len(reachable_docs), - "content_sets": len(reachable_sets), - "targets": len(reachable_targets), - "target_sites": reachable_target_sites, - }, - "parent_path_inheritance": { - "documents": inherit_documents, - "sites": inherit["sites"], - "xpath_sibling_form": inherit["xpath_sibling"], - "resolved_in_document": inherit["resolved"], - "ambiguous": inherit["ambiguous"], - "unresolved": inherit["sites"] - inherit["resolved"] - inherit["ambiguous"], - "chain_depths": {str(depth): count for depth, count in sorted(inherit_depths.items())}, - "cycles": inherit["cycles"], - }, - "categories": dict(sorted(category_stats.items(), key=lambda kv: (-kv[1]["documents"], - kv[0]))), - "roots": dict(sorted(root_stats.items(), key=lambda kv: (-kv[1]["documents"], kv[0]))), - } - # Count roots per category from the root table, not from documents. A root belongs to exactly - # one category, so this also checks that the category totals line up with the 118 named roots. - for category, stats in summary["categories"].items(): - stats["roots"] = sum(1 for root in summary["roots"] - if (gx.category_for(root) if root else gx.UNCATALOGUED) == category) - stats.setdefault("manifest_documents", 0) - for stats in summary["roots"].values(): - stats.setdefault("manifest_documents", 0) - stats.setdefault("category", gx.UNCATALOGUED) - - return { - "summary": summary, - "unresolved": { - "document_unmapped": dict(sorted(unresolved_namespaces["document_unmapped"].items())), - "unknown_macro": dict(sorted(unresolved_namespaces["unknown_macro"].items())), - "unrecognized_prefix": dict(sorted(unresolved_namespaces["unrecognized_prefix"].items())), - "relative_locator": unresolved_sites["relative_locator"], - "include_id_missing": unresolved_sites["include_id_missing"], - "total_sites": sum(unresolved_sites.values()), - }, - } - - -def print_summary(graph: dict) -> None: - summary = graph["summary"] - print(f'{summary["payloads"]} payloads ({summary["documents"]} complete, ' - f'{summary["parsed"]} parsed), {summary["manifest_documents"]} manifest documents') - print(f'{summary["content_sets"]} content-set ids ' - f'({summary["defined_content_sets"]} defined, ' - f'{summary["dangling_content_sets"]} dangling, ' - f'{summary["duplicate_set_ids"]} duplicate)') - print(f'{summary["reference_sites"]:,} reference sites: ' - f'{summary["references"].get("filename", 0):,} filename, ' - f'{summary["references"].get("loadPath", 0)} loadPath, ' - f'{summary["references"].get("parentPath", 0)} parentPath, ' - f'{summary["references"].get("parentFile", 0)} parentFile, ' - f'{summary["include_sites"]} includedSets') - prefixes = ", ".join(f"{name} {count:,}" for name, count in summary["prefixes"].items()) - print(f'prefixes: {prefixes}') - print(f'resolution: {summary["resolution"]}') - print(f'graph: {summary["nodes"]["total"]:,} nodes, {summary["edges"]["total"]:,} edges ' - f'({summary["edges"]["defines"]} defines, {summary["edges"]["includes"]} includes, ' - f'{summary["edges"]["contains_file"]:,} file, ' - f'{summary["edges"]["loads_changeset"]} changeset, ' - f'{summary["edges"]["parent_path"]} parentPath, ' - f'{summary["edges"]["parent_file"]} parentFile)') - content = summary["content_graph"] - print(f'content graph: {content["root_documents"]} roots, ' - f'{content["reachable_documents"]} reachable documents, ' - f'{summary["reachable"]["content_sets"]} sets, depth {content["max_depth"]}, ' - f'{content["cycles"]} cycles') - print(f'reachable: {summary["reachable"]["targets"]:,} unique targets ' - f'({summary["reachable"]["target_sites"]:,} sites)') - inherit = summary["parent_path_inheritance"] - depths = ", ".join(f"{depth}: {count}" for depth, count in inherit["chain_depths"].items()) - print(f'parentPath in-document: {inherit["resolved_in_document"]} of {inherit["sites"]} resolved ' - f'in {inherit["documents"]} document(s), {inherit["ambiguous"]} ambiguous, ' - f'{inherit["unresolved"]} unresolved; chain depths {{{depths}}}, {inherit["cycles"]} cycles') - unresolved = graph["unresolved"] - print(f'unresolved: {unresolved["total_sites"]:,} sites ' - f'({len(unresolved["document_unmapped"])} archive namespaces, ' - f'{sum(unresolved["unrecognized_prefix"].values())} unknown scheme, ' - f'{unresolved["relative_locator"]} relative, ' - f'{unresolved["include_id_missing"]} missing include id)') - - -def main() -> int: - parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) - parser.add_argument("targets", nargs="+", help="carve directory or XML file(s)") - parser.add_argument("--json", help="write the aggregate graph summary to this JSON") - args = parser.parse_args() - - try: - if args.json: - if os.path.isdir(args.json): - parser.error(f"--json is a directory: {args.json}") - for target in args.targets: - is_dir = os.path.isdir(target) - source = os.path.join(target, "index.json") if is_dir else target - if gx.same_report_path(args.json, source): - parser.error(f"--json would overwrite the input {source}") - if is_dir and os.path.isfile(args.json): - root = os.path.normcase(os.path.abspath(target)) - dest = os.path.normcase(os.path.abspath(args.json)) - if dest.endswith(".bin") and dest.startswith(root + os.sep): - parser.error(f"--json would overwrite an input file: {args.json}") - for path in gx.input_files([target]): - if gx.same_report_path(args.json, path): - parser.error(f"--json would overwrite the input {path}") - - documents = list(gx.load_documents(args.targets)) - except FileNotFoundError as exc: - print(f"not found: {exc}", file=sys.stderr) - return 2 - except RuntimeError as exc: - print(f"ERROR: {exc}", file=sys.stderr) - return 2 - except (OSError, ValueError, KeyError, TypeError) as exc: - # Same one-line contract as gamedata_xml.py and gamedata_index.py: a bad carve index is an error, - # not a traceback. - where = getattr(exc, "filename", None) or args.targets[0] - print(f"ERROR: cannot read {where}: {getattr(exc, 'strerror', None) or exc!r}", file=sys.stderr) - return 2 - graph = build_graph(documents) - graph["summary"]["mode"] = gx.document_mode(args.targets) - print_summary(graph) - if args.json: - try: - with open(args.json, "w", encoding="utf-8", newline="\n") as f: - json.dump(graph, f, indent=1) - except OSError as exc: - print(f"cannot write {args.json}: {exc.strerror or exc}", file=sys.stderr) - return 2 - print("wrote", args.json) - return 0 - - -if __name__ == "__main__": - try: # a redirected stdout is strict ANSI code page under -I; write '?' for what it cannot encode - sys.stdout.reconfigure(errors="replace") - except (AttributeError, ValueError, OSError): - pass - sys.exit(main()) diff --git a/tools/gamedata_index.py b/tools/gamedata_index.py deleted file mode 100644 index d333b6435..000000000 --- a/tools/gamedata_index.py +++ /dev/null @@ -1,508 +0,0 @@ -"""Index a carved RPF9 archive by payload type and XML root. - -RPF9 stores files as one or more zlib streams, usually 64 KiB of inflated data per stream. The table of -contents is encrypted, so a carve has offsets and sizes but no names. This tool turns that stream list into -a compact payload index: - - python -I gamedata_index.py [--csv FILE] [--json FILE] - python -I gamedata_index.py [--csv FILE] [--json FILE] [--carve-dir DIR] - - is an rpf9_carve.py output directory (index.json plus .bin files). For an .rpf, the -carver is run with --index-only in a temporary directory and the streams are inflated on demand, so no -carved files are written. Pass --carve-dir to reuse an existing index.json. - -The rows contain offsets, sizes, a coarse type and an XML root element (a schema/class name). They do not -contain element values, entry names or payload bytes, so the CSV/JSON can be reviewed without copying the -game data. Non-XML payloads follow the 64 KiB block rule; a file whose inflated size is an exact multiple of -64 KiB can merge with the next stream. XML documents close on their root element, so their grouping is exact. -The tool is standard library only and never writes outside the requested output files. -Usage: `python -I tools/gamedata_index.py --help` lists the options. -""" -from __future__ import annotations - -import argparse -import codecs -import csv -import json -import mmap -import os -import re -import subprocess -import sys -import tempfile -import zlib -from collections import defaultdict - -# -I keeps the script directory off sys.path, so add it explicitly before importing the sibling module. -sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) -from report_paths import same_report_path # noqa: E402 - -ROOT = os.path.dirname(os.path.abspath(__file__)) -CARVER = os.path.join(ROOT, "rpf9_carve.py") -BOM = b"\xef\xbb\xbf" -XML_DECL = re.compile(rb"<\?xml[^>]*\?>") -# Require a name delimiter so an unsupported character cannot turn a longer root into an ASCII prefix. -XML_OPEN = re.compile(rb"<([A-Za-z_][\w.:-]*)(?=[ \t\r\n/>])") -XML_CLOSE_TAIL = re.compile(rb"\s*$") -# Tag-like text inside these cannot open or close an element. -XML_NON_TAG = re.compile(rb"||<\?.*?\?>", re.S) -MAGIC = {b"MHIU": "MHIU", b"PAMH": "PAMH", b"SPS1": "SPS1", b"RBF0": "RBF0", b"PSIN": "PSIN"} -# A resource whose page directory starts the stream carries "0DRP" at +16 (docs/animation.md, "0DRP page marker"). -# Its first 4 KiB can be over 95% printable, so without this check such a stream reads as text, and as XML when it -# holds a "<": data.rpf has 337 of them and no XML at all (docs/gamedata.md, "Relationship to data.rpf"). -PAGE_MARKER, PAGE_MARKER_AT = b"0DRP", 16 - - -def printable(data: bytes) -> float: - sample = data[:4096] - if not sample: - return 0.0 - good = sum(1 for c in sample if c in (9, 10, 13) or 32 <= c < 127) - return good / len(sample) - - -def _utf8_text(data: bytes) -> bool: - """True when the leading 4 KiB decodes as printable UTF-8 text (tolerating a split multibyte boundary).""" - sample = data[:4096] - if not sample or b"\x00" in sample: - return False - start = 0 - while start < min(3, len(sample)) and 0x80 <= sample[start] <= 0xBF: - start += 1 - sample = sample[start:] - if not sample: - return False - try: - text = codecs.getincrementaldecoder("utf-8")("strict").decode(sample, final=False) - except UnicodeDecodeError: - return False - if not text: - return False - good = sum(1 for ch in text if ch in "\t\r\n" or (ord(ch) >= 0x20 and ord(ch) != 0x7F and ch.isprintable())) - return good / len(text) >= 0.95 - - -def has_xml_decl(data: bytes) -> bool: - # xml_root() drops the BOM before looking for the declaration; do the same here, or a BOM followed by - # whitespace makes the two disagree and the stream is grouped by the 64 KiB binary rule instead. - text = data[3:] if data.startswith(BOM) else data - return bool(XML_DECL.match(text) or XML_DECL.match(text.lstrip(b" \t\r\n"))) - - -def xml_root(data: bytes) -> str: - """First element name after the XML declaration/comments/PIs, or "".""" - text = data[3:] if data.startswith(BOM) else data - text = text.lstrip(b" \t\r\n") - while True: - m = XML_DECL.match(text) - if m: - text = text[m.end():].lstrip(b" \t\r\n") - continue - if text.startswith(b"") - text = text[end + 3:].lstrip(b" \t\r\n") if end >= 0 else b"" - continue - if text.startswith(b"") - text = text[end + 2:].lstrip(b" \t\r\n") if end >= 0 else b"" - continue - break - m = XML_OPEN.match(text) - return m.group(1).decode("ascii", "replace") if m else "" - - -def tail_root(data: bytes) -> str: - m = XML_CLOSE_TAIL.search(data[-512:]) - return m.group(1).decode("ascii", "replace") if m else "" - - -def xml_complete(root: str, data: bytes) -> bool: - """True when every in data is closed, not merely when a occurs somewhere in the tail. - - A nested element with the same name as the root used to satisfy the old substring test, so a truncated - document was reported complete and its continuation streams were not absorbed into the payload. - """ - if not root: - return False - text = XML_NON_TAG.sub(b"", data) - name = re.escape(root.encode("ascii", "replace")) - # A quoted attribute value may contain '>'; consume quoted strings as one unit or a self-closing - # tag with such a value is mistaken for an unclosed element. - opens = re.findall(rb"<" + name + rb"(?=[\s/>])(?:\"[^\"]*\"|'[^']*'|[^'\">])*>", text) - closes = re.findall(rb"", text) - self_closed = sum(1 for tag in opens if tag.rstrip().endswith(b"/>")) - if len(opens) - self_closed > len(closes): - return False - return bool(closes or self_closed) - - -def _self_closing_root(root: str, data: bytes) -> bool: - text = data[3:] if data.startswith(BOM) else data - text = XML_NON_TAG.sub(b"", text).strip() - name = re.escape(root.encode("ascii", "replace")) - return bool(re.fullmatch(rb"<" + name + rb"(?=[\s/])(?:\"[^\"]*\"|'[^']*'|[^'\">])*/>", text)) - - -def standalone_xml(data: bytes) -> bool: - """A complete document in one stream, with or without a declaration.""" - root = xml_root(data) - return bool(root) and xml_complete(root, data) and (tail_root(data) == root or _self_closing_root(root, data)) - - -def stream_kind(data: bytes, row: dict) -> str: - if row.get("type") == "bink2" or data.startswith(b"KB2"): - return "bink2" - if has_xml_decl(data): - return "decl" - if data.startswith(b"RBF0"): - return "rbf0" - if data.startswith(b"PSIN"): - return "psin" - for magic in MAGIC: - if data.startswith(magic): - return "other" - if data[PAGE_MARKER_AT:PAGE_MARKER_AT + len(PAGE_MARKER)] == PAGE_MARKER: - return "other" - if printable(data) > 0.95: - return "text" - return "binary" - - -def magic_name(data: bytes) -> str: - for magic, name in MAGIC.items(): - if data.startswith(magic): - return name - if data[PAGE_MARKER_AT:PAGE_MARKER_AT + len(PAGE_MARKER)] == PAGE_MARKER: - return PAGE_MARKER.decode() - return "" - - -CARVED_STREAM = re.compile(r"[0-9a-f]{12}\.(?:bin|bk2)") - - -def carved_stream(address: str, directory: str): - """The carved stream a report at `address` would overwrite in `directory`, or None. - - rpf9_carve.py writes one `.bin` (or `.bk2`) per stream beside its index.json, so it is an input, - not a place for a report; guarding only index.json left `--json`/`--csv` free to replace a carved stream. - """ - if not CARVED_STREAM.fullmatch(os.path.basename(address)): - return None - candidate = os.path.join(directory, os.path.basename(address)) - return candidate if os.path.isfile(candidate) and same_report_path(address, candidate) else None - - -class DirectorySource: - """Reads .bin/.bk2 files next to an rpf9_carve.py index.json.""" - - def __init__(self, directory: str): - self.directory = directory - with open(os.path.join(directory, "index.json"), encoding="utf-8-sig") as f: - self.index = json.load(f) - self.rows = sorted(self.index["files"], key=lambda r: r["off"]) - - def read(self, row: dict) -> bytes: - ext = ".bk2" if row.get("type") == "bink2" else ".bin" - path = os.path.join(self.directory, f'{row["off"]:012x}{ext}') - try: - with open(path, "rb") as f: - return f.read() - except OSError: - return bytes.fromhex(row.get("head", "")) - - @property - def summary(self) -> dict: - return self.index.get("summary", {}) - - -class ArchiveSource: - """Reads streams on demand from the archive, using an index-only carve.""" - - def __init__(self, archive: str, index_dir: str | None = None): - self.archive = archive - self._tmp = None - if index_dir is None: - self._tmp = tempfile.TemporaryDirectory(prefix="gamedata-index-") - index_dir = self._tmp.name - r = subprocess.run([sys.executable, "-I", CARVER, archive, index_dir, "--index-only"], - capture_output=True, text=True, encoding="utf-8", errors="replace") - if r.returncode != 0: - raise RuntimeError((r.stdout + r.stderr).strip() or "rpf9_carve.py failed") - with open(os.path.join(index_dir, "index.json"), encoding="utf-8-sig") as f: - self.index = json.load(f) - self.rows = sorted(self.index["files"], key=lambda r: r["off"]) - self._fh = open(archive, "rb") - self._map = mmap.mmap(self._fh.fileno(), 0, access=mmap.ACCESS_READ) - - def read(self, row: dict) -> bytes: - if row.get("type") == "bink2": - return self._map[row["off"]:row["off"] + min(row["stored"], 64)] - try: - d = zlib.decompressobj() - out = d.decompress(self._map[row["off"]:row["off"] + row["stored"]]) - return out + d.flush() - except zlib.error: - return bytes.fromhex(row.get("head", "")) - - @property - def summary(self) -> dict: - return self.index.get("summary", {}) - - def close(self) -> None: - self._map.close() - self._fh.close() - if self._tmp is not None: - self._tmp.cleanup() - - -def build_rows(rows: list, source) -> list: - """Group streams into payloads; XML documents are closed by their root element.""" - out = [] - n = len(rows) - i = 0 - while i < n: - data = source.read(rows[i]) - kind = stream_kind(data, rows[i]) - - if kind == "decl": - root = xml_root(data) - group = [i] - blob = data - j = i + 1 - while j < n and not xml_complete(root, blob): - nxt = source.read(rows[j]) - nk = stream_kind(nxt, rows[j]) - if nk in ("decl", "bink2", "rbf0", "psin", "other", "binary"): - break - blob += nxt - if not root: # the opening name or its delimiter may span streams - root = xml_root(blob) - group.append(j) - j += 1 - out.append(row_for("xml", rows, group, root=root, header=True, - complete=xml_complete(root, blob))) - i = j - continue - - if kind == "other" or kind == "bink2": - group = [i] - detail = magic_name(data) - j = i + 1 - # A resource's first stream may be any whole number of 64 KiB blocks (docs/page_directory.md: 128 and - # 192 KiB first streams continue in the next one). Only these headed kinds take that rule: a binary, - # text or XML run has no header proving a continuation, so it keeps the exact 64 KiB rule below. - while j < n and rows[j - 1]["size"] and rows[j - 1]["size"] % 65536 == 0: - nxt = source.read(rows[j]) - nk = stream_kind(nxt, rows[j]) - if nk in ("decl", "bink2", "rbf0", "psin", "other"): - break - group.append(j) - j += 1 - typ = "bink2" if kind == "bink2" else "other" - out.append(row_for(typ, rows, group, detail=detail)) - i = j - continue - - if kind in ("rbf0", "psin", "text", "binary"): - group = [i] - chunks = [data] if kind == "text" and b"<" in data else None - start_root = xml_root(data) if chunks is not None else "" - j = i + 1 - if not (chunks is not None and standalone_xml(data)): - while j < n and rows[j - 1]["size"] == 65536: - nxt = source.read(rows[j]) - if standalone_xml(nxt): - break - nk = stream_kind(nxt, rows[j]) - if nk in ("decl", "bink2", "rbf0", "psin", "other") or ( - chunks is not None and nk == "binary" and not _utf8_text(nxt) - ): - break - if chunks is not None: - chunks.append(nxt) - if not start_root: - start_root = xml_root(b"".join(chunks)) - group.append(j) - j += 1 - if chunks is not None and start_root and tail_root(nxt) == start_root and xml_complete(start_root, b"".join(chunks)): - break - if chunks is not None: - blob = b"".join(chunks) - root = tail_root(blob) or (xml_root(blob) if standalone_xml(blob) else "") - out.append(row_for("xml", rows, group, root=root, header=False, complete=bool(root))) - else: - out.append(row_for(kind, rows, group)) - i = j - continue - - # An XML continuation stream with no declaration: a tail-only document if it closes a root. - group = [i] - blob = data - j = i + 1 - while j < n and rows[j - 1]["size"] == 65536: - nxt = source.read(rows[j]) - if stream_kind(nxt, rows[j]) in ("decl", "bink2", "rbf0", "psin", "other", "binary"): - break - blob += nxt - group.append(j) - j += 1 - root = tail_root(blob) - out.append(row_for("xml", rows, group, root=root, header=False, - complete=bool(root) and xml_complete(root, blob))) - i = j - return out - - -def row_for(typ: str, rows: list, group: list, root: str = "", detail: str = "", - header: bool = False, complete: bool = True) -> dict: - first = rows[group[0]] - return { - "offset": first["off"], - "offset_hex": f'{first["off"]:x}', - "stored": sum(rows[x]["stored"] for x in group), - "size": sum(rows[x]["size"] for x in group), - "type": typ, - "root": root, - "detail": detail, - "chunks": len(group), - "complete": complete, - "header": header, - } - - -def summarize(rows: list, source_summary: dict, target: str) -> dict: - by_type = defaultdict(lambda: {"files": 0, "streams": 0, "stored": 0, "inflated": 0}) - by_root = defaultdict(lambda: {"files": 0, "inflated": 0}) - for r in rows: - t = by_type[r["type"]] - t["files"] += 1 - t["streams"] += r["chunks"] - t["stored"] += r["stored"] - t["inflated"] += r["size"] - if r["root"]: - by_root[r["root"]]["files"] += 1 - by_root[r["root"]]["inflated"] += r["size"] - xml = [r for r in rows if r["type"] == "xml"] - streams = source_summary.get("files", 0) - if isinstance(streams, list): - streams = len(streams) - return { - "target": target, - "streams": streams, - "stored": sum(r["stored"] for r in rows), - "inflated": sum(r["size"] for r in rows), - "zero_padding": source_summary.get("zero_padding"), - "unread_bytes": source_summary.get("unread_bytes"), - "types": {k: dict(v) for k, v in sorted(by_type.items(), key=lambda kv: -kv[1]["inflated"])}, - "xml_documents": sum(1 for r in xml if r["complete"]), - "xml_with_header": sum(1 for r in xml if r["header"]), - "xml_tail_only": sum(1 for r in xml if r["complete"] and not r["header"]), - "xml_incomplete": sum(1 for r in xml if not r["complete"]), - "roots": {k: dict(v) for k, v in sorted(by_root.items(), key=lambda kv: (-kv[1]["files"], kv[0]))}, - } - - -def _make_parent(path: str) -> None: - """Create the folder an output path lives in: the scan is over by the time we write, so a missing - folder used to end the run in a FileNotFoundError and lose the result.""" - parent = os.path.dirname(os.path.abspath(path)) - if parent: - os.makedirs(parent, exist_ok=True) - - -def write_csv(path: str, rows: list) -> None: - _make_parent(path) - fields = ["offset", "offset_hex", "stored", "size", "type", "root", "detail", "chunks", - "complete", "header"] - with open(path, "w", newline="", encoding="utf-8") as f: - w = csv.DictWriter(f, fieldnames=fields, lineterminator="\n") - w.writeheader() - w.writerows(rows) - - -def main() -> int: - ap = argparse.ArgumentParser(description=__doc__.splitlines()[0]) - ap.add_argument("target", help="carve directory or .rpf archive") - ap.add_argument("--carve-dir", help="existing rpf9_carve.py index.json directory for an .rpf") - ap.add_argument("--csv", help="write one row per payload to this CSV") - ap.add_argument("--json", help="write the summary and rows to this JSON") - a = ap.parse_args() - if a.csv and a.json and same_report_path(a.csv, a.json): - ap.error("--csv and --json must use different paths") - - if not os.path.exists(a.target): - print(f"ERROR: {a.target} does not exist", file=sys.stderr) - return 2 - protected = [a.target] if os.path.isfile(a.target) else [os.path.join(a.target, "index.json")] - if a.carve_dir: - protected.append(os.path.join(a.carve_dir, "index.json")) - for flag, path in (("--json", a.json), ("--csv", a.csv)): - if path: - if os.path.isdir(path): - ap.error(f"{flag} is a directory: {path}") - for input_path in protected: - if same_report_path(path, input_path): - ap.error(f"{flag} would overwrite the input {input_path}") - for directory in (a.target, a.carve_dir): - stream = directory and os.path.isdir(directory) and carved_stream(path, directory) - if stream: - ap.error(f"{flag} would overwrite the carved stream {stream}") - source = None - try: - if os.path.isdir(a.target): - source = DirectorySource(a.target) - else: - source = ArchiveSource(a.target, a.carve_dir) - rows = build_rows(source.rows, source) - summary = summarize(rows, source.summary, a.target) - except RuntimeError as e: # rpf9_carve.py refused the archive; its own message says why - print(f"ERROR: {e}", file=sys.stderr) - return 2 - except FileNotFoundError as e: - print(f"ERROR: {e.filename} is missing. Give a carve folder from rpf9_carve.py or an .rpf archive.", - file=sys.stderr) - return 2 - except (OSError, ValueError, KeyError, TypeError) as e: - where = getattr(e, "filename", None) or a.target - print(f"ERROR: cannot read {where}: {getattr(e, 'strerror', None) or e!r}", file=sys.stderr) - return 2 - finally: - if isinstance(source, ArchiveSource): - source.close() - - if a.csv: - try: - write_csv(a.csv, rows) - except OSError as e: - print(f"ERROR: cannot write {a.csv}: {e.strerror or e}", file=sys.stderr) - return 2 - if a.json: - try: - _make_parent(a.json) - with open(a.json, "w", encoding="utf-8", newline="\n") as f: - json.dump({"summary": summary, "rows": rows}, f, indent=1) - except OSError as e: - print(f"ERROR: cannot write {a.json}: {e.strerror or e}", file=sys.stderr) - return 2 - - print(f'{summary["streams"]} streams, {summary["stored"]:,} stored, ' - f'{summary["inflated"]:,} inflated') - for name, t in summary["types"].items(): - print(f' {name:8} {t["files"]:4} payloads {t["streams"]:5} streams ' - f'{t["stored"]:10,} stored {t["inflated"]:12,} inflated') - print(f'XML: {summary["xml_documents"]} complete documents ' - f'({summary["xml_with_header"]} with a declaration, {summary["xml_tail_only"]} tail-only), ' - f'{summary["xml_incomplete"]} incomplete, {len(summary["roots"])} roots') - if a.csv: - print("wrote", a.csv) - if a.json: - print("wrote", a.json) - return 0 - - -if __name__ == "__main__": - try: # a redirected stdout is strict ANSI code page under -I; write '?' for what it cannot encode - sys.stdout.reconfigure(errors="replace") - except (AttributeError, ValueError, OSError): - pass - sys.exit(main()) diff --git a/tools/gamedata_maps.py b/tools/gamedata_maps.py deleted file mode 100644 index c4d1f33a7..000000000 --- a/tools/gamedata_maps.py +++ /dev/null @@ -1,567 +0,0 @@ -"""Decode the MHIU and PAMH (HMAP) heightmaps in a carved RPF9 archive. - -Both payloads start with a 44-byte header and then use a row table plus packed -u8 heights. The layouts were measured on the Xbox Series 1.0.2.1 package and -match the published GTA V `heightmap.dat` (`HMAP`) layout: - -`MHIU` - 0x00 "MHIU" - 0x04 u16 version - 0x06 u16 width (2048 in both measured payloads) - 0x08 u16 height (2048) - 0x0A u16 pad - 0x0C six f32 bounds (min xyz, max xyz) - 0x24 u32 data size (bytes after this 44-byte header) - 0x28 u8 default height (23 in both measured payloads, 0 m quantised) - 0x29 3 bytes differ per file; not a checksum (padding?) - 0x2C height x 8-byte row headers `{u16 start, u16 count, i32 offset}` - then the packed u8 heights. A cell not covered by a row keeps the - default from 0x28. The source index is `offset + start + i`. The - encoder crops each row to its first and last non-default cell, so - no measured span starts or ends on the default. - The old "zero prefix + square grid" reading was an artifact: the prefix is - the zeroed row headers of the map's empty (default) rows. - -`PAMH` (`HMAP` read little-endian) - 0x00 "PAMH" (the `HMAP` magic stored little-endian) - 0x04 u8 version major, u8 version minor (1.2 in `common.rpf`) - 0x05 start of the coordinate label in the `levels.rpf` tiles (see below) - 0x06 u16 pad - 0x08 u32 at GTA V's `compressed` offset. In level tiles bit 0 is set. - 0x0C u16 width - 0x0E u16 height - 0x10 six f32 bounds (min xyz, max xyz) - 0x28 u32 data size (bytes after this 44-byte header) - 0x2C height x 8-byte row headers - then `width * height` u8 max rows and `width * height` u8 min rows. - On the measured file the first array is a flat 110 (2.5 m) sea-surface - layer and the second is the ground; min <= max in all 23,616 cells. - -In the 1,476 level tiles, derive column and row from the 512 m bounding boxes. -Write their one-based ASCII `column_row` and NUL over the right-aligned `height` -tail at 0x05..0x0B, then set bit 0 at 0x08. All seven bytes match on every tile. -Only 819 match before setting the bit. The stored label can represent two -different coordinates. The `common.rpf` payload holds 0x1BBC8CED at 0x08. - -Both formats scale a u8 value into the header's Z box: - - z = min.z + value / 255 * (max.z - min.z) - - python -I gamedata_maps.py [--json FILE] - - is an rpf9_carve.py output directory (index.json plus .bin -files). Only header fields, dimensions, row counts and value ranges are -printed or written; the height bytes are not. Standard library only. -Usage: `python -I tools/gamedata_maps.py --help` lists the options. -""" -from __future__ import annotations - -import argparse -import json -import math -import os -import struct -import sys -import unicodedata - -# -I keeps the script directory off sys.path, so add it explicitly before importing the sibling module. -sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) -from report_paths import same_report_path # noqa: E402 - -MAGIC = (b"MHIU", b"PAMH") -HEADER = 44 - - -def _u16(blob: bytes, offset: int) -> int: - return struct.unpack_from(" int: - return struct.unpack_from(" dict: - lo = list(struct.unpack_from("<3f", blob, offset)) - hi = list(struct.unpack_from("<3f", blob, offset + 12)) - for value in lo + hi: - if not math.isfinite(value): - raise ValueError(f"non-finite bound {value!r} at offset {offset:#x}") - return {"min": lo, "max": hi} - - -def _z(value: int, bounds: dict) -> float: - lo, hi = bounds["min"][2], bounds["max"][2] - return lo + value / 255.0 * (hi - lo) - - -def _rows(blob: bytes, height: int) -> bytes: - end = HEADER + height * 8 - if end > len(blob): - raise ValueError("row table is truncated") - return blob[HEADER:end] - - -def parse_mhiu(blob: bytes) -> dict: - if len(blob) < HEADER or blob[:4] != b"MHIU": - raise ValueError("not an MHIU payload") - width = _u16(blob, 0x06) - height = _u16(blob, 0x08) - if not width or not height: - raise ValueError("MHIU has a zero grid dimension") - if width > 4096 or height > 4096: - raise ValueError(f"MHIU grid {width}x{height} is out of range") - bounds = _bounds(blob, 0x0C) - size = _u32(blob, 0x24) - if size != len(blob) - HEADER: - raise ValueError(f"MHIU data size {size} does not match {len(blob) - HEADER} bytes") - - rows = _rows(blob, height) - pixels = blob[HEADER + height * 8:] - default = blob[0x28] - heights = bytearray([default]) * (width * height) - empty = filled_rows = filled_cells = ends_at_default = 0 - spans = [] - for y in range(height): - start, count = struct.unpack_from(" width: - raise ValueError(f"MHIU row {y} leaves the {width}-cell width") - source = offset + start - if source < 0 or source + count > len(pixels): - raise ValueError(f"MHIU row {y} leaves the {len(pixels)}-byte pixel data") - heights[y * width + start:y * width + start + count] = \ - pixels[source:source + count] - ends_at_default += (pixels[source] == default) + \ - (pixels[source + count - 1] == default) - filled_rows += 1 - filled_cells += count - spans.append((source, source + count)) - - spans.sort() - for (_, end), (start, _) in zip(spans, spans[1:]): - if start < end: - raise ValueError("MHIU row data overlaps") - - return { - "type": "MHIU", - "header": { - "version": _u16(blob, 0x04), - "width": width, - "height": height, - "bounds": bounds, - "data_size": size, - "default_height": default, - "pad_29": blob[0x29:0x2C].hex(), - "z_mapping": "min.z + value/255 * (max.z - min.z)", - }, - "grid": { - "dtype": "u8", - "width": width, - "height": height, - "cells": width * height, - "default": default, - "row_records": height, - "filled_rows": filled_rows, - "empty_rows": empty, - "filled_cells": filled_cells, - "data_bytes": len(pixels), - "span_ends_at_default": ends_at_default, - "z_at_default": round(_z(default, bounds), 2), - }, - "_grid": bytes(heights), - } - - -def parse_pamh(blob: bytes) -> dict: - if len(blob) < HEADER or blob[:4] != b"PAMH": - raise ValueError("not a PAMH payload") - width = _u16(blob, 0x0C) - height = _u16(blob, 0x0E) - if not width or not height: - raise ValueError("PAMH has a zero grid dimension") - bounds = _bounds(blob, 0x10) - size = _u32(blob, 0x28) - if size != len(blob) - HEADER: - raise ValueError(f"PAMH data size {size} does not match {len(blob) - HEADER} bytes") - - rows = _rows(blob, height) - data = blob[HEADER + height * 8:] - body = size - height * 8 - if body != width * height * 2: - raise ValueError( - f"PAMH data is {body} bytes; {width}x{height} needs " - f"{width * height * 2} for max and min rows") - half = width * height - maximum = bytearray(half) - minimum = bytearray(half) - full_width = 0 - for y in range(height): - start, count = struct.unpack_from(" width: - raise ValueError(f"PAMH row {y} leaves the {width}-cell width") - if start == 0 and count == width: - full_width += 1 - for i in range(count): - x = start + i - at = offset + x - if at < 0 or at >= half: - raise ValueError(f"PAMH row {y} leaves the {half}-cell row data") - maximum[y * width + x] = data[at] - minimum[y * width + x] = data[half + at] - - inversions = sum(1 for hi, lo in zip(maximum, minimum) if lo > hi) - return { - "type": "PAMH", - "header": { - "version_major": blob[0x04], - "version_minor": blob[0x05], - "padding08": _u32(blob, 0x08), - "width": width, - "height": height, - "bounds": bounds, - "data_size": size, - "z_mapping": "min.z + value/255 * (max.z - min.z)", - }, - "grid": { - "dtype": "u8 max + u8 min", - "width": width, - "height": height, - "cells": width * height, - "row_records": height, - "full_width_rows": full_width, - "max_min": min(maximum), - "max_max": max(maximum), - "min_min": min(minimum), - "min_max": max(minimum), - "min_above_max": inversions, - }, - "_max": bytes(maximum), - "_min": bytes(minimum), - } - - -def pamh_census(payloads: list[dict]) -> list[dict]: - """Group decoded PAMH payloads by grid size and count what varies inside a group. - - The 0x08 word overlaps the coordinate label in level tiles. Byte 0x05 holds the HMAP - version minor in the common.rpf payload and the first digit of the column in the tiles. - The census counts the 0x05 values and distinct 0x08 words within each grid size.""" - groups = {} - for p in payloads: - if p["type"] != "PAMH": - continue - h, g = p["header"], p["grid"] - grp = groups.get((g["width"], g["height"])) - if grp is None: - grp = groups[(g["width"], g["height"])] = { - "width": g["width"], - "height": g["height"], - "tiles": 0, - "cells": 0, - "bounds_min": list(h["bounds"]["min"]), - "bounds_max": list(h["bounds"]["max"]), - "full_width_row_tiles": 0, - "min_above_max": 0, - "version_minor": {}, - "padding08_zero": 0, - "_padding": set(), - } - grp["tiles"] += 1 - grp["cells"] += g["cells"] - for i in range(3): - grp["bounds_min"][i] = min(grp["bounds_min"][i], h["bounds"]["min"][i]) - grp["bounds_max"][i] = max(grp["bounds_max"][i], h["bounds"]["max"][i]) - if g["full_width_rows"] == g["height"]: - grp["full_width_row_tiles"] += 1 - grp["min_above_max"] += g["min_above_max"] - minor = str(h["version_minor"]) - grp["version_minor"][minor] = grp["version_minor"].get(minor, 0) + 1 - if h["padding08"] == 0: - grp["padding08_zero"] += 1 - grp["_padding"].add(h["padding08"]) - out = list(groups.values()) - for grp in out: - grp["padding08_distinct"] = len(grp.pop("_padding")) - out.sort(key=lambda x: (-x["tiles"], x["width"], x["height"])) - return out - - -def parse_payload(blob: bytes) -> dict: - if blob[:4] == b"MHIU": - return parse_mhiu(blob) - if blob[:4] == b"PAMH": - return parse_pamh(blob) - raise ValueError(f"unsupported payload magic {blob[:4]!r}") - - -def _read_row(directory: str, row: dict) -> bytes: - path = os.path.join(directory, f'{row["off"]:012x}.bin') - try: - with open(path, "rb") as f: - return f.read() - except OSError: - return bytes.fromhex(row.get("head", "")) - - -def _join(row: dict, data: bytes) -> dict: - out = { - "offset": row["off"], - "offset_hex": f'{row["off"]:x}', - "stored": row.get("stored", len(data)), - "size": len(data), - "chunks": 1, - } - out.update(parse_payload(data)) - return out - - -def _read_index_rows(directory: str) -> list[dict]: - index_path = os.path.join(directory, "index.json") - with open(index_path, encoding="utf-8") as f: - index = json.load(f) - # A hand-edited or half-written index used to fail as `error: 'files'`, naming neither the folder nor the - # file. Name the index and the malformed row like gamedata_blobs.check_carve_index does. - rows = index.get("files") if isinstance(index, dict) else None - if not isinstance(rows, list): - raise ValueError(f"{index_path} has no 'files' list") - for i, row in enumerate(rows): - if not isinstance(row, dict) or "off" not in row: - raise ValueError(f"{index_path}: row {i} needs an 'off'") - return sorted(rows, key=lambda r: r["off"]) - - -def read_payloads(directory: str, rows: list[dict] | None = None) -> list[dict]: - if rows is None: - rows = _read_index_rows(directory) - out = [] - i = 0 - while i < len(rows): - data = _read_row(directory, rows[i]) - if data[:4] not in MAGIC: - i += 1 - continue - if len(data) < HEADER: - raise ValueError(f"truncated {data[:4].decode('ascii')} header at {rows[i]['off']:#x}") - target_size = HEADER + _u32(data, 0x24 if data[:4] == b"MHIU" else 0x28) - size = len(data) - parts = [data] - j = i - # The header's size bounds the join, so any whole number of 64 KiB blocks may continue (as in gamedata_index). - while size < target_size and rows[j].get("size", 0) and rows[j]["size"] % 65536 == 0 and j + 1 < len(rows): - nxt = _read_row(directory, rows[j + 1]) - if nxt[:4] in MAGIC or nxt.startswith((b" dict: - return {k: v for k, v in payload.items() if not k.startswith("_")} - - -_PC_CASE_SENSITIVE = 11 # on macOS; os.pathconf_names doesn't list it - - -def _resolve_report_path(path: str) -> str: - if os.name != "nt": - return os.path.realpath(path) - if not path.startswith("\\\\?\\"): - # GetFullPathName normalizes ordinary Windows paths the same way opening them does. - return os.path.realpath(os.path.abspath(path)) - # realpath can trim literal trailing dots and spaces from missing verbatim components. - # Resolve the existing ancestor and append the missing components as written. - missing = [] - while not os.path.lexists(path): - parent, name = os.path.split(path) - if not name: - break - missing.append(name) - path = parent - return os.path.join(os.path.realpath(path), *reversed(missing)) - - -def _case_insensitive_volume(path: str) -> bool: - """True when the volume that will hold `path` ignores letter case, as macOS's default APFS volume does. - os.path.normcase folds case only on Windows, so on macOS `INDEX.JSON` and `index.json` would otherwise - look like two different paths.""" - if sys.platform != "darwin": - return False - while not os.path.exists(path): - parent = os.path.dirname(path) - if parent == path: - break - path = parent - try: - return os.pathconf(path, _PC_CASE_SENSITIVE) == 0 - except (OSError, ValueError): - return True # the macOS default; folding can only refuse a collision, never overwrite an input - - -def _path_key(path: str) -> str: - path = os.path.normcase(_resolve_report_path(path)) - if os.name != "nt": - if _case_insensitive_volume(path): - # APFS and HFS+ also treat composed and decomposed accents as one name. - path = unicodedata.normalize("NFD", path.casefold()) - return path - # Drive and UNC paths can also be spelled using the extended-length prefix. - extended_prefix = "\\\\?\\" - unc_prefix = extended_prefix + "unc\\" - if path.startswith(unc_prefix): - return "\\\\" + path[len(unc_prefix):] - drive, _ = os.path.splitdrive(path) - if drive.startswith(extended_prefix) and len(drive) == len(extended_prefix) + 2 and drive.endswith(":"): - return path[len(extended_prefix):] - return path - - -def _file_identity(path: str): - try: - st = os.stat(path) - except OSError: - return None - return st.st_dev, st.st_ino - - -def _matches_candidate(out_key: str, out_id, out_in_carve: bool, out_name_folded: str, - candidate: str, name: str, is_symlink: bool | None = None) -> bool: - if out_id is not None: - cand_id = _file_identity(candidate) - if cand_id is not None and cand_id == out_id: - return True - if is_symlink is None: - is_symlink = os.path.islink(candidate) - if is_symlink: - return _path_key(candidate) == out_key - if out_in_carve and unicodedata.normalize("NFD", name.casefold()) == out_name_folded: - return _path_key(candidate) == out_key - return False - - -def check_report_path(out_path: str, carve_dir: str, rows: list[dict] | None = None) -> None: - """Refuse a --json path that points to an existing directory or collides with any carve input.""" - if same_report_path(out_path, carve_dir): - raise ValueError(f"--json would overwrite the input {carve_dir}") - if os.path.isdir(out_path): - raise ValueError(f"--json is a directory: {out_path}") - index_path = os.path.join(carve_dir, "index.json") - if same_report_path(out_path, index_path): - raise ValueError(f"--json would overwrite the input {index_path}") - - out_key = _path_key(out_path) - out_id = _file_identity(out_path) - carve_key = _path_key(carve_dir) - out_in_carve = os.path.dirname(out_key) == carve_key - out_name_folded = unicodedata.normalize("NFD", os.path.basename(out_key).casefold()) - - if rows is None: - if not os.path.isdir(carve_dir): - return - try: - entries = os.scandir(carve_dir) - except OSError: - return - with entries: - for entry in entries: - if not entry.name.lower().endswith(".bin"): - continue - try: - if entry.is_dir(): - continue - is_link = entry.is_symlink() - except OSError: - continue - if _matches_candidate(out_key, out_id, out_in_carve, out_name_folded, - entry.path, entry.name, is_link): - raise ValueError(f"--json would overwrite the input {entry.path}") - else: - for row in rows: - name = f'{row["off"]:012x}.bin' - candidate = os.path.join(carve_dir, name) - if _matches_candidate(out_key, out_id, out_in_carve, out_name_folded, - candidate, name): - raise ValueError(f"--json would overwrite the input {candidate}") - - -def _make_parent(path: str) -> None: - """Create the folder an output path lives in so a missing folder does not lose a finished scan.""" - parent = os.path.dirname(os.path.abspath(path)) - if parent: - os.makedirs(parent, exist_ok=True) - - -def main() -> int: - ap = argparse.ArgumentParser(description=__doc__.splitlines()[0]) - ap.add_argument("carve_dir", help="rpf9_carve.py output directory") - ap.add_argument("--json", help="write the decoded header and grid summary to this JSON") - a = ap.parse_args() - if not os.path.exists(a.carve_dir): - print(f"ERROR: {a.carve_dir}: does not exist", file=sys.stderr) - return 2 - if not os.path.isfile(os.path.join(a.carve_dir, "index.json")): - # A file, or a folder without the carve's index, otherwise fails below as a raw - # FileNotFoundError naming "\index.json", which the user never typed. - print(f"ERROR: {a.carve_dir}: not an rpf9_carve.py folder (no index.json)", file=sys.stderr) - return 2 - - try: - if a.json: - check_report_path(a.json, a.carve_dir) - rows = _read_index_rows(a.carve_dir) - if a.json: - check_report_path(a.json, a.carve_dir, rows=rows) - payloads = read_payloads(a.carve_dir, rows=rows) - except (OSError, ValueError, KeyError, TypeError, struct.error) as e: - print("error:", e, file=sys.stderr) - return 1 - - for p in payloads: - g = p["grid"] - if p["type"] == "MHIU": - print(f'MHIU {p["offset_hex"]}: {p["size"]:,} B, ' - f'{g["width"]}x{g["height"]} u8, {g["filled_rows"]} filled rows, ' - f'{g["empty_rows"]} empty (default {g["default"]})') - else: - print(f'PAMH {p["offset_hex"]}: {p["size"]:,} B, ' - f'{g["width"]}x{g["height"]} u8 max+min, {g["row_records"]} row records, ' - f'{g["min_above_max"]} cells min>max') - if not payloads: - print("no MHIU or PAMH payloads") - census = pamh_census(payloads) - for grp in census: - print(f'PAMH census {grp["width"]}x{grp["height"]}: {grp["tiles"]} tiles, ' - f'{grp["full_width_row_tiles"]} with full-width rows, ' - f'{grp["min_above_max"]} cells min>max, padding 08 zero {grp["padding08_zero"]}, ' - f'{grp["padding08_distinct"]} distinct') - if a.json: - out = {"payloads": [_public(p) for p in payloads]} - if census: - out["pamh_census"] = census - try: - _make_parent(a.json) - with open(a.json, "w", encoding="utf-8", newline="\n") as f: - json.dump(out, f, indent=1) - except OSError as e: - print(f"error: cannot write {a.json}: {e.strerror or e}", file=sys.stderr) - return 1 - print("wrote", a.json) - return 0 - - -if __name__ == "__main__": - try: # a redirected stdout is strict ANSI code page under -I; write '?' for what it cannot encode - sys.stdout.reconfigure(errors="replace") - except (AttributeError, ValueError, OSError): - pass - sys.exit(main()) diff --git a/tools/gamedata_reader.py b/tools/gamedata_reader.py deleted file mode 100644 index c9d4ae40f..000000000 --- a/tools/gamedata_reader.py +++ /dev/null @@ -1,339 +0,0 @@ -"""Stream the game-data XML of a carved RPF9 archive into Python values, dispatching on root tag and ``type``. - -The XML in ``common.rpf`` is RAGE parser metadata (docs/gamedata.md): 118 root tags and 5,293 element tags, written -with a handful of conventions. This reader turns any of it into plain values without a schema per tag, and lets a -caller plug in a schema where one is known: - -- ````: a scalar (bool for ``true``/``false``, int for decimal or ``0x`` hex, float, else the text); -- ````: a vector, as a tuple of floats; -- ``..``: the - whitespace-separated numbers of the body (pairs, triples or matrix rows where the content says so); -- ``..``: a polymorphic object, ``{"$type": "CSomeClass", ...}``; ``type="NULL"`` is - ``None``; -- ````: ``{"$ref": "name"}``; -- children that are all ````: a list; children that all carry ``key``: a dict by key; repeated tags: a list; -- an element with only text: the text. - -Dispatch: ``register_root(tag)`` registers a handler for a whole document's root element, ``register_type(name)`` -one for every element with ``type="name"`` (both called as ``handler(element, reader)``; ``reader.convert`` gives the -generic value of a sub-element). Everything else takes the generic conversion. The documents are read with -``iterparse`` and each top-level field is converted and dropped as soon as it ends, so memory is bounded by the largest -field, not the document. - - python -I tools/gamedata_reader.py [...] [--root TAG] [--out DIR] - -prints counts only: documents read, roots, the elements each convention covered, ``type`` classes seen, and -documents that are not well-formed XML (tail-only or truncated carves), with the reason. ``--out DIR`` writes one JSON -file per document: those files hold the game's data and stay on the local machine (CONTRIBUTING.md). Standard -library only. -Usage: `python -I tools/gamedata_reader.py --help` lists the options. -""" -import argparse -import io -import json -import os -import re -import sys -import xml.etree.ElementTree as ET -from collections import Counter - -HERE = os.path.dirname(os.path.abspath(__file__)) -if HERE not in sys.path: - sys.path.insert(0, HERE) - -BOM = b"\xef\xbb\xbf" -VECTOR_KEYS = ("x", "y", "z", "w") -BASE_CONVENTION_KEYS = frozenset(("type", "content", "value", "ref", "key")) -CONVENTION_KEYS = BASE_CONVENTION_KEYS | frozenset(VECTOR_KEYS) -GROUPS = {"vector2_array": 2, "vec3v_array": 3, "matrix33": 3, "matrix34": 3} -INT = re.compile(r"[-+]?\d+") -HEX = re.compile(r"0x[0-9A-Fa-f]+") -FLOAT = re.compile(r"[-+]?(\d+\.?\d*|\.\d+)([eE][-+]?\d+)?f?|[-+]?(inf|nan)", re.I) - -ROOT_HANDLERS = {} -TYPE_HANDLERS = {} - - -def _is_vector(attrib): - """True when ``attrib`` carries ``x`` and every present ``x``/``y``/``z``/``w`` attribute is a float.""" - return "x" in attrib and all(FLOAT.fullmatch(attrib[k]) for k in VECTOR_KEYS if k in attrib) - - -def _uses_vector_keys(attrib): - """True when ``attrib`` resolves via the vector convention rather than another attribute convention.""" - return (attrib.get("type") != "NULL" - and "content" not in attrib - and "value" not in attrib - and _is_vector(attrib)) - - -def register_root(tag): - """Decorator: ``handler(element, reader)`` for every document whose root element is ``tag``.""" - def wrap(fn): - ROOT_HANDLERS[tag] = fn - return fn - return wrap - - -def register_type(name): - """Decorator: ``handler(element, reader)`` for every element with ``type="name"``.""" - def wrap(fn): - TYPE_HANDLERS[name] = fn - return fn - return wrap - - -def parse_scalar(text): - """A ``value`` attribute or array token: bool, int (decimal or 0x hex), float, else the text unchanged.""" - if text in ("true", "false"): - return text == "true" - if HEX.fullmatch(text): - return int(text, 16) - if INT.fullmatch(text): - return int(text) - if FLOAT.fullmatch(text): - return _float(text) - return text - - -def _float(text): - """A float with an optional C-style ``f`` suffix ("1.5f"); "inf" keeps its f.""" - try: - return float(text) - except ValueError: - return float(text[:-1]) - - -def parse_content(kind, text): - """The numbers of a ``content=`` body, grouped into tuples for vector arrays and matrices.""" - nums = [parse_scalar(t) for t in (text or "").split()] - width = GROUPS.get(kind) - if not width: - return nums - if len(nums) % width: - raise ValueError(f"{kind}: {len(nums)} numbers is not a multiple of {width}") - return [tuple(nums[i:i + width]) for i in range(0, len(nums), width)] - - -class Reader: - """Converts elements, counting which convention each one took (``stats``) and the ``type`` classes seen.""" - - def __init__(self, root_handlers=None, type_handlers=None): - self.root_handlers = ROOT_HANDLERS if root_handlers is None else root_handlers - self.type_handlers = TYPE_HANDLERS if type_handlers is None else type_handlers - self.stats = Counter() - self.types = Counter() - self._active_type_elements = set() - - def convert(self, el, use_type_handler=True): - """The generic value of element ``el`` (a registered ``type`` handler first, unless told not to). Attributes - no convention uses (``name``, ``userFlags``, ...) are kept as ``"@name"`` entries.""" - in_handler = id(el) in self._active_type_elements - value = self._convert(el, use_type_handler) - return self.with_attributes(el.attrib, value, count_stats=not in_handler) - - def with_attributes(self, attrib, value, count_stats=True): - consumed = CONVENTION_KEYS if _uses_vector_keys(attrib) else BASE_CONVENTION_KEYS - extra = {f"@{k}": parse_scalar(v) for k, v in attrib.items() if k not in consumed} - if not extra: - return value - if count_stats: - self.stats["extra attributes"] += 1 - if isinstance(value, dict): - return {**value, **extra} - return {"$value": value, **extra} if value not in ("", None) else extra - - def _convert(self, el, use_type_handler=True): - a = el.attrib - t = a.get("type") - if t == "NULL": - self.stats["null"] += 1 - return None - if t is not None: - if id(el) not in self._active_type_elements: - self.types[t] += 1 - handler = self.type_handlers.get(t) if use_type_handler else None - if handler: - self.stats["type handler"] += 1 - self._active_type_elements.add(id(el)) - try: - return handler(el, self) - finally: - self._active_type_elements.discard(id(el)) - if "content" in a: - self.stats["array"] += 1 - return parse_content(a["content"], el.text) - if "value" in a: - self.stats["scalar"] += 1 - return parse_scalar(a["value"]) - if _is_vector(a): - self.stats["vector"] += 1 - return tuple(_float(a[k]) for k in VECTOR_KEYS if k in a) - if "ref" in a: - self.stats["reference"] += 1 - return {"$ref": a["ref"]} - kids = list(el) - if not kids: - self.stats["text"] += 1 - return (el.text or "").strip() - return self._typed_object(t, self.children(kids)) - - def _typed_object(self, t, value): - """Wrap an assembled child container in a polymorphic ``$type`` dict when ``t`` is set.""" - if t is None: - return value - self.stats["object"] += 1 - if not isinstance(value, dict): - value = {"$items": value} - return {"$type": t, **value} - - def _streams_children(self, root): - """True when top-level children can be converted and dropped piecemeal instead of keeping the whole root.""" - if root.tag in self.root_handlers: - return False - a = root.attrib - t = a.get("type") - if t == "NULL" or (t is not None and t in self.type_handlers): - return False - return not ("content" in a or "value" in a or _is_vector(a) or "ref" in a) - - def children(self, kids): - """Child elements as a list (all ``Item``), a dict by ``key`` (all keyed) or a dict by tag.""" - return self.assemble([(k.tag, k.attrib.get("key"), self.convert(k)) for k in kids]) - - def assemble(self, parts): - """``(tag, key or None, value)`` of each child, in order -> list, dict by key or dict by tag (a tag that occurs - more than once becomes the list of its values).""" - if all(tag == "Item" for tag, _, _ in parts): - if all(key is not None for _, key, _ in parts): - self.stats["map"] += 1 - return {key: value for _, key, value in parts} - self.stats["list"] += 1 - return [value for _, _, value in parts] - self.stats["struct"] += 1 - out, repeated = {}, set() - for tag, _, value in parts: - if tag in out: - if tag not in repeated: - out[tag], repeated = [out[tag]], repeated | {tag} - out[tag].append(value) - else: - out[tag] = value - return out - - def read(self, data): - """One document (bytes) -> ``(root tag, root type, value)``. Fields are converted as their end tag arrives - and then dropped from the tree. Raises ``ET.ParseError`` for a document that is not well-formed.""" - stream = io.BytesIO(data[len(BOM):] if data.startswith(BOM) else data) - depth, root, parts, stream_kids = 0, None, [], False - for event, el in ET.iterparse(stream, events=("start", "end")): - if event == "start": - depth += 1 - if root is None: - root = el - stream_kids = self._streams_children(root) - continue - depth -= 1 - if depth == 1 and stream_kids: - # a top-level field is complete: convert it now and drop its sub-tree and root reference - parts.append((el.tag, el.attrib.get("key"), self.convert(el))) - el.clear() - del root[:] - handler = self.root_handlers.get(root.tag) - if handler: - self.stats["root handler"] += 1 - return root.tag, root.attrib.get("type"), handler(root, self) - if not parts: - return root.tag, root.attrib.get("type"), self.convert(root) - attrib = dict(root.attrib) - value = self.assemble(parts) - t = attrib.get("type") - if t is not None: - self.types[t] += 1 - value = self._typed_object(t, value) - return root.tag, t, self.with_attributes(attrib, value) - - -def documents(targets): - """XML payloads of carve directories (index.json) or .xml files, as gamedata_xml.load_documents yields them.""" - import gamedata_xml as gx - return gx.load_documents(targets) - - -def run(targets, root_filter=None, out_dir=None, reader=None): - """Read every document; returns a summary of counts (no names of entries, no values).""" - reader = reader or Reader() - roots, failed, read = Counter(), Counter(), 0 - written_names = set() - for n, doc in enumerate(documents(targets)): - hint = doc.get("root_hint") - if root_filter and hint != root_filter: - continue - try: - tag, _, value = reader.read(doc["data"]) - except (ET.ParseError, LookupError, ValueError) as e: - # Unsupported encodings and malformed content arrays fail outside ET.ParseError too. - failed[str(e).split(":")[0]] += 1 - continue - read += 1 - roots[tag] += 1 - if out_dir: - os.makedirs(out_dir, exist_ok=True) - name = doc.get("offset_hex") or doc.get("name") or str(n) - stem = f"{tag}_{name}" - filename = f"{stem}.json" - suffix = 2 - # Another input can have the same basename or carve offset. Keep existing names on ordinary reruns. - while filename.casefold() in written_names: - filename = f"{stem}_{suffix}.json" - suffix += 1 - written_names.add(filename.casefold()) - with open(os.path.join(out_dir, filename), "w", encoding="utf-8", newline="\n") as f: - json.dump(value, f, indent=1, default=str) - return {"documents": read, "roots": len(roots), "per_root_documents": dict(roots), - "not_well_formed": sum(failed.values()), "parse_errors": dict(failed), - "elements_by_convention": dict(reader.stats), "type_classes": len(reader.types), - "typed_elements": sum(reader.types.values()), - "registered": {"roots": len(reader.root_handlers), "types": len(reader.type_handlers)}} - - -def main(argv=None): - ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) - ap.add_argument("targets", nargs="+", help="rpf9_carve.py directories (with index.json) or .xml files") - ap.add_argument("--root", help="only documents with this root tag") - ap.add_argument("--out", help="write one JSON file per document here (game data: keep it local)") - a = ap.parse_args(argv) - if a.out and os.path.exists(a.out) and not os.path.isdir(a.out): - print(f"ERROR: --out {a.out} exists and is not a directory", file=sys.stderr) - return 2 - try: - s = run(a.targets, a.root, a.out) - except FileNotFoundError as e: - print(f"ERROR: {e} does not exist", file=sys.stderr) - return 2 - except (OSError, ValueError, KeyError, TypeError) as e: - # an unreadable file, or a carve folder whose index.json is not JSON or not the rpf9_carve.py shape - where = getattr(e, "filename", None) or ", ".join(a.targets) - print(f"ERROR: cannot read {where}: {getattr(e, 'strerror', None) or e!r}", file=sys.stderr) - return 2 - print(f"{s['documents']} documents read, {s['roots']} roots, {s['not_well_formed']} not well-formed " - f"{s['parse_errors'] or ''}".rstrip()) - print("elements by convention:", ", ".join(f"{k} {v}" for k, v in sorted(s["elements_by_convention"].items()))) - print(f"type classes: {s['type_classes']} ({s['typed_elements']} typed elements); registered handlers: " - f"{s['registered']['roots']} roots, {s['registered']['types']} types") - if a.out: - print(f"wrote {s['documents']} JSON files to {a.out} (game data: keep them local)") - if not s["documents"] and s["not_well_formed"]: - # Nothing parsed. A corpus with some truncated tails still reads the rest and stays 0; a run that read - # nothing at all cannot tell "no documents here" from "every document was broken", so the exit code says it. - print(f"ERROR: no document could be read; {s['not_well_formed']} not well-formed", file=sys.stderr) - return 1 - return 0 - - -if __name__ == "__main__": - try: # a redirected stdout is strict ANSI code page under -I; write '?' for what it cannot encode - sys.stdout.reconfigure(errors="replace") - except (AttributeError, ValueError, OSError): - pass - sys.exit(main()) diff --git a/tools/gamedata_sps1.py b/tools/gamedata_sps1.py deleted file mode 100644 index b8aa70187..000000000 --- a/tools/gamedata_sps1.py +++ /dev/null @@ -1,405 +0,0 @@ -"""Decode the SPS1 shader-preset table in common.rpf and cross-check with shaders.rpf. - -Format measured on the Xbox Series 1.0.2.1 common.rpf (offset 0x650000, 43,791 B): - - 0x00 "SPS1" 4-byte magic - 0x04 u32 entry_count number of records (858 = 0x0000035A; low byte 0x5A - is ASCII 'Z', which earlier notes misread as "SPS1Z") - 0x08 entry_count records of: - u8 preset_len byte length of NUL-terminated ASCII preset path - char preset[preset_len] - u8 effect_len byte length of NUL-terminated target SGD5 effect name - char effect[effect_len] - u8 render_bucket default RAGE render bucket (0..7) - - python -I tools/gamedata_sps1.py [--shaders PATH/TO/shaders.rpf] [--preset-hash HEX] [--json FILE] - -Only header fields, aggregate counts, bucket distributions and hashed queries are -printed or written; preset and effect names stay on the local machine. Standard -library only. -Usage: `python -I tools/gamedata_sps1.py --help` lists the options. -""" -from __future__ import annotations - -import argparse -from collections import Counter, defaultdict -import json -import os -import posixpath -import re -import struct -import sys - -# -I keeps the script directory off sys.path, so add it explicitly before importing sibling helpers. -TOOLS = os.path.dirname(os.path.abspath(__file__)) -if TOOLS not in sys.path: - sys.path.insert(0, TOOLS) - -import gamedata_index as gi # noqa: E402 -import gamedata_maps as gm # noqa: E402 -from hashdict import joaat # noqa: E402 -from report_paths import same_report_path # noqa: E402 -import sgd5_effects as se # noqa: E402 - -SPS1_MAGIC = b"SPS1" -HEADER = 8 -BOUNDARY_MAGICS = (b"MHIU", b"PAMH", b"SPS1", b"RBF0", b"PSIN") -XML_PREFIXES = (b" tuple[str, int]: - """Read one u8-length-prefixed, NUL-terminated printable ASCII string.""" - if pos >= len(blob): - raise ValueError(f"truncated {label} length at {pos:#x}") - length = blob[pos] - pos += 1 - if length < 2: - raise ValueError(f"invalid {label} string length at {pos - 1:#x}") - if pos + length > len(blob): - raise ValueError(f"truncated {label} string at {pos - 1:#x}") - raw = blob[pos:pos + length] - if raw[-1] != 0 or 0 in raw[:-1]: - raise ValueError(f"{label} string at {pos - 1:#x} must end with a single NUL") - body = raw[:-1] - if any(b < 0x20 or b > 0x7E for b in body): - raise ValueError(f"non-printable byte in {label} string at {pos - 1:#x}") - return body.decode("ascii"), pos + length - - -def _preset_stem(preset_path: str) -> str: - """Basename of a .sps preset path without its .sps suffix.""" - base = posixpath.basename(preset_path.replace("\\", "/")) - if base.lower().endswith(".sps"): - return base[:-4] - return base - - -def parse_sps1(blob: bytes) -> dict: - """Decode an SPS1 binary blob into aggregate statistics plus private _entries.""" - if len(blob) < HEADER or blob[:4] != SPS1_MAGIC: - raise ValueError("not an SPS1 payload") - entry_count = struct.unpack_from("= len(blob): - raise ValueError(f"truncated render_bucket[{index}] at {pos:#x}") - bucket = blob[pos] - pos += 1 - entries.append((preset, effect, bucket)) - if pos != len(blob): - raise ValueError(f"SPS1 trailing bytes: consumed {pos} of {len(blob)} bytes") - - buckets_counter: Counter[int] = Counter() - buckets_by_effect: dict[str, set[int]] = defaultdict(set) - distinct_presets: set[str] = set() - distinct_stems: set[str] = set() - root_stems: set[str] = set() - subfolder_stems: list[str] = [] - preset_lengths: list[int] = [] - effect_lengths: list[int] = [] - sps_ext = root_presets = subfolder_presets = identity = 0 - - for preset, effect, bucket in entries: - low_preset = preset.lower() - low_effect = effect.lower() - stem = _preset_stem(preset).lower() - distinct_presets.add(low_preset) - distinct_stems.add(stem) - preset_lengths.append(len(preset)) - effect_lengths.append(len(effect)) - buckets_counter[bucket] += 1 - buckets_by_effect[low_effect].add(bucket) - if low_preset.endswith(".sps"): - sps_ext += 1 - if "/" in preset or "\\" in preset: - subfolder_presets += 1 - subfolder_stems.append(stem) - else: - root_presets += 1 - root_stems.add(stem) - if stem == low_effect: - identity += 1 - - multi_combos = Counter( - ",".join(str(b) for b in sorted(bset)) - for bset in buckets_by_effect.values() - if len(bset) > 1 - ) - low_byte = entry_count & 0xFF - return { - "type": "SPS1", - "header": { - "magic": "SPS1", - "entry_count": entry_count, - "low_count_byte_ascii": chr(low_byte) if 0x20 <= low_byte <= 0x7E else None, - }, - "table": { - "records": len(entries), - "data_bytes": len(blob) - HEADER, - "distinct_presets": len(distinct_presets), - "distinct_preset_stems": len(distinct_stems), - "distinct_effects": len(buckets_by_effect), - "sps_extension_count": sps_ext, - "root_presets": root_presets, - "subfolder_presets": subfolder_presets, - "subfolder_stem_collisions": sum(1 for s in subfolder_stems if s in root_stems), - "identity_presets": identity, - "aliased_presets": len(entries) - identity, - "preset_length_min": min(preset_lengths) if preset_lengths else 0, - "preset_length_max": max(preset_lengths) if preset_lengths else 0, - "effect_length_min": min(effect_lengths) if effect_lengths else 0, - "effect_length_max": max(effect_lengths) if effect_lengths else 0, - "render_buckets": {str(k): buckets_counter[k] for k in sorted(buckets_counter)}, - "multi_bucket_effects": sum(1 for bset in buckets_by_effect.values() if len(bset) > 1), - "multi_bucket_combinations": { - k: multi_combos[k] for k in sorted(multi_combos, key=lambda s: (-multi_combos[s], s)) - }, - }, - "_entries": entries, - } - - -def _load_from_source(rows: list[dict], read_row) -> list[dict]: - """Extract and parse all SPS1 payloads from sorted index rows.""" - out = [] - i = 0 - while i < len(rows): - row = rows[i] - head_hex = row.get("head", "") - if len(head_hex) >= 8 and not head_hex.lower().startswith("53505331"): - i += 1 - continue - data = read_row(row) - if data[:4] != SPS1_MAGIC: - i += 1 - continue - parts = [data] - j = i - blob = data - while True: - try: - parsed = parse_sps1(blob) - break - except ValueError as err: - if ( - "truncated" not in str(err) - or not (len(parts[-1]) > 0 and len(parts[-1]) % 65536 == 0) - or j + 1 >= len(rows) - ): - raise - nxt = read_row(rows[j + 1]) - if nxt[:4] in BOUNDARY_MAGICS or nxt.startswith(XML_PREFIXES): - raise - parts.append(nxt) - j += 1 - blob = b"".join(parts) - parsed.update({ - "offset": row["off"], - "offset_hex": f'{row["off"]:x}', - "stored": sum(rows[x].get("stored", 0) for x in range(i, j + 1)), - "size": len(blob), - "chunks": j - i + 1, - }) - out.append(parsed) - i = j + 1 - return out - - -def read_payloads(target: str) -> list[dict]: - """Load SPS1 payloads from a carve directory, a raw .bin file, or an .rpf archive.""" - if os.path.isdir(target): - rows = gm._read_index_rows(target) - return _load_from_source(rows, lambda r: gm._read_row(target, r)) - if not os.path.isfile(target): - raise FileNotFoundError(target) - with open(target, "rb") as f: - head = f.read(4) - if head == SPS1_MAGIC: - with open(target, "rb") as f: - blob = f.read() - parsed = parse_sps1(blob) - parsed.update({ - "offset": 0, - "offset_hex": "0", - "stored": len(blob), - "size": len(blob), - "chunks": 1, - }) - return [parsed] - if head != b"9FPR": - raise ValueError(f"{target} is neither an SPS1 payload nor an RPF9 archive") - source = gi.ArchiveSource(target) - try: - return _load_from_source(source.rows, source.read) - finally: - source.close() - - -def cross_reference_sgd5(payloads: list[dict], shaders_rpf: str) -> dict: - """Resolve SPS1 target effect names and preset stems against shaders.rpf SGD5 databases.""" - with open(shaders_rpf, "rb") as stream: - db0_res = se.read_database(stream, se.DATABASES[0], list_effects=True) - db1_res = se.read_database(stream, se.DATABASES[1], list_effects=True) - - db0_names = {m["effect"].lower() for m in db0_res["matches"]} - db1_names = {m["effect"].lower() for m in db1_res["matches"]} - all_sgd5 = db0_names | db1_names - - resolved_db0 = resolved_db1 = unresolved = 0 - matched_effects_db0: set[str] = set() - matched_effects_db1: set[str] = set() - distinct_stems: set[str] = set() - stems_in_sgd5: set[str] = set() - - for payload in payloads: - for preset, effect, _ in payload["_entries"]: - low_effect = effect.lower() - stem = _preset_stem(preset).lower() - distinct_stems.add(stem) - if stem in all_sgd5: - stems_in_sgd5.add(stem) - if low_effect in db0_names: - resolved_db0 += 1 - matched_effects_db0.add(low_effect) - elif low_effect in db1_names: - resolved_db1 += 1 - matched_effects_db1.add(low_effect) - else: - unresolved += 1 - - return { - "sgd5_db0_effects": len(db0_names), - "sgd5_db1_effects": len(db1_names), - "sgd5_total_effects": len(all_sgd5), - "records_resolved_db0": resolved_db0, - "records_resolved_db1": resolved_db1, - "records_unresolved": unresolved, - "distinct_effects_resolved_db0": len(matched_effects_db0), - "distinct_effects_resolved_db1": len(matched_effects_db1), - "preset_stems_in_sgd5": len(stems_in_sgd5), - "sps1_only_preset_stems": len(distinct_stems - stems_in_sgd5), - } - - -def lookup_preset_hash(payloads: list[dict], target_hash: int) -> list[dict]: - """Match a joaat hash against preset stems, preset paths, or effect names (hashes only returned).""" - matches = [] - for payload in payloads: - for idx, (preset, effect, bucket) in enumerate(payload["_entries"]): - stem = _preset_stem(preset) - stem_h = joaat(stem) - path_h = joaat(preset) - eff_h = joaat(effect) - if target_hash in (stem_h, path_h, eff_h): - matches.append({ - "record_index": idx, - "preset_stem_hash": f"{stem_h:08X}", - "preset_path_hash": f"{path_h:08X}", - "effect_hash": f"{eff_h:08X}", - "render_bucket": bucket, - "aliased": stem.lower() != effect.lower(), - }) - return matches - - -def check_report_path(out_path: str, target: str, shaders_rpf: str | None = None, - rows: list[dict] | None = None) -> None: - """Refuse a --json destination that is a directory or aliases any input file.""" - if os.path.isdir(out_path): - raise ValueError(f"--json is a directory: {out_path}") - if shaders_rpf and same_report_path(out_path, shaders_rpf): - raise ValueError(f"--json would overwrite the input {shaders_rpf}") - if os.path.isdir(target): - gm.check_report_path(out_path, target, rows=rows) - elif same_report_path(out_path, target): - raise ValueError(f"--json would overwrite the input {target}") - - -def _public(payload: dict) -> dict: - return {k: v for k, v in payload.items() if not k.startswith("_")} - - -def main(argv=None) -> int: - ap = argparse.ArgumentParser(description=__doc__.splitlines()[0]) - ap.add_argument("target", help="rpf9_carve.py directory, common.rpf archive, or SPS1 .bin file") - ap.add_argument("--shaders", help="shaders.rpf archive to cross-reference target effects against SGD5") - ap.add_argument("--preset-hash", metavar="HEX", - help="match a joaat32 hash against preset stem, path, or effect (prints hashes only)") - ap.add_argument("--json", help="write the aggregate summary and lookup hashes to this JSON") - a = ap.parse_args(argv) - - target_hash = None - if a.preset_hash is not None: - if not re.fullmatch(r"(?:0[xX])?[0-9a-fA-F]{1,8}", a.preset_hash): - ap.error("--preset-hash expects up to eight hexadecimal digits") - target_hash = int(a.preset_hash, 16) - - # A missing input path is a usage error (exit 2), not a failed run, as in BUILD-1046. - for path in (a.target, a.shaders): - if path is not None and not os.path.exists(path): - print(f"ERROR: {path} does not exist", file=sys.stderr) - return 2 - - try: - if a.json: - check_report_path(a.json, a.target, a.shaders) - if os.path.isdir(a.target): - rows = gm._read_index_rows(a.target) - if a.json: - check_report_path(a.json, a.target, a.shaders, rows=rows) - payloads = read_payloads(a.target) - xref = cross_reference_sgd5(payloads, a.shaders) if a.shaders else None - matches = lookup_preset_hash(payloads, target_hash) if target_hash is not None else None - except (OSError, ValueError, KeyError, TypeError, struct.error, RuntimeError) as e: - print("error:", e, file=sys.stderr) - return 1 - - for p in payloads: - t = p["table"] - print( - f'SPS1 {p["offset_hex"]}: {p["size"]:,} B, {t["records"]} presets -> ' - f'{t["distinct_effects"]} effects ({t["identity_presets"]} identity, {t["aliased_presets"]} aliased), ' - f'buckets {t["render_buckets"]}' - ) - if not payloads: - print("no SPS1 payloads") - if xref is not None: - print( - f'SGD5 xref: {xref["records_resolved_db0"]}/{sum(p["table"]["records"] for p in payloads)} ' - f'records in DB0 ({xref["distinct_effects_resolved_db0"]} distinct effects), ' - f'{xref["preset_stems_in_sgd5"]} stems in SGD5, {xref["sps1_only_preset_stems"]} SPS1-only' - ) - if matches is not None: - print(f"hash matches: {len(matches)}") - for m in matches: - print( - f' [{m["record_index"]}] stem={m["preset_stem_hash"]} ' - f'effect={m["effect_hash"]} bucket={m["render_bucket"]} aliased={m["aliased"]}' - ) - - if a.json: - out: dict = {"payloads": [_public(p) for p in payloads]} - if xref is not None: - out["sgd5_xref"] = xref - if matches is not None: - out["hash_matches"] = matches - try: - gm._make_parent(a.json) - with open(a.json, "w", encoding="utf-8", newline="\n") as f: - json.dump(out, f, indent=1) - except OSError as e: - print(f"error: cannot write {a.json}: {e.strerror or e}", file=sys.stderr) - return 1 - print("wrote", a.json) - return 0 - - -if __name__ == "__main__": - try: # a redirected stdout is strict ANSI code page under -I; write '?' for what it cannot encode - sys.stdout.reconfigure(errors="replace") - except (AttributeError, ValueError, OSError): - pass - sys.exit(main()) diff --git a/tools/gamedata_xml.py b/tools/gamedata_xml.py deleted file mode 100644 index a8b395177..000000000 --- a/tools/gamedata_xml.py +++ /dev/null @@ -1,748 +0,0 @@ -"""Catalog the XML documents recovered from a carved RPF9 archive. - -RPF9 stores a logical XML document as one or more zlib streams. A carve from ``rpf9_carve.py`` has an -``index.json`` plus one inflated ``.bin`` per stream, so ``gamedata_index.py`` can group the streams -back into payloads. This tool parses those payloads and writes an aggregate catalog: - - python -I gamedata_xml.py [--csv FILE] [--json FILE] [--check] - python -I gamedata_xml.py [ ...] [--csv FILE] [--json FILE] [--check] - -For every file it records the root element, element count, maximum depth, attribute names, ``$(name)`` and -``platform:/`` references, and include-like structures. For every root it records the file count, category, -element-name histogram, attribute histogram and reference targets. ``--check`` validates well-formedness and -separates rootless fragments, tail-only documents and malformed documents. -Well-formed documents use the parser's expanded root name (including its XML namespace), just as -the element histogram does. A raw tag hint is only needed when recovering incomplete documents. - -Only schema names, element/attribute names and reference tokens are written. Element text, attribute values, -``type``/``content`` values and entry paths are not. For a carve directory a row is identified by offset; an -individual file is identified by the basename that was passed. The output is a local work product: it must not -be committed or attached to an issue. Report paths are refused before the scan when they alias an input: a -nested XML in directory mode, or a carve ``index.json`` or stream. The test fixtures are synthetic and contain -no game data. -Usage: `python -I tools/gamedata_xml.py --help` lists the options. -""" -import argparse -import csv -import io -import json -import os -import re -import stat -import statistics -import sys -import xml.etree.ElementTree as ET -from collections import Counter, defaultdict -from xml.parsers.expat import errors - -ROOT = os.path.dirname(os.path.abspath(__file__)) -if ROOT not in sys.path: - sys.path.insert(0, ROOT) -import gamedata_index as gi # noqa: E402 -from report_paths import same_report_path # noqa: E402 - -BOM = b"\xef\xbb\xbf" -MACRO_REF = re.compile(r"\$\(([A-Za-z_][\w.-]*)\)") -PLATFORM_REF = re.compile(r"platform:/([A-Za-z0-9_.-]+)?") -XI_INCLUDE = "{http://www.w3.org/2001/XInclude}include" -INCLUDE_ELEMENTS = ("fileList", "filename", "includedSets", "includedChangesets", - "changesetIncludeFlags", "loadPath") - -# Category names and root membership follow the functional table in docs/gamedata.md. A category is a -# dispatch hint: the same root always belongs to one bucket, but a bucket is not a complete schema. Where a -# document straddles two labels, the table's bucket is kept so the file and root counts line up. -CATEGORY_ROOTS = { - "time, weather, sky, water": """ - timecycle_modifier_data timecycle_keyframe_data CContentsOfWeatherXmlFile STS_Config CustomClouds - CScatteringTransmittance__FogVolumeListData FogVolumeProfileList OceanSimPresets - OceanWaveCalmingCurves EnvironmentalWaterDisturbManager ShoreWavePlacementData time_data - RegionTintMap - """, - "vehicles, tyres, handling data": """ - CVehiclePoints CVehicleBoneOffsetsArray CVehiclePerformanceMaps CVehicleBaseRatingsAndEstimatesMap - CVehicleComponentSetManager CVehicleDistantLightData CVehiclePointsMeta CTyreDataSet CParkingSplines - CSnowTrackData CBreakableVehicleDoorLockManagerData CPaletteIndexedRecipeTintsArray - """, - "peds, schedules, appearance": """ - CPedAccuracyManager CPedComponentSetManager CPedFormationInfoManager CPedHeadbobSettingsManager - CPedInventoryLoadOutManager CPedMoodConditionTreesManager CPedMoodSettingsManager - CPedMotivationInfoManager CPedScheduleInfoManager CPedSpeedDataBlock CPedTimeWarpSettingsManager - CPedVariationBodyTypeManager CPairedPedDataBlock CEnergyConfigInfos CIdlePreferenceManager - CUpperBodyIdleConditionManager CUpperBodyIdleSettingsManager CHeadbobConditionManager - CHealthConfigInfo sPedDamageModifiers sPedDistractionModifiers WalkAndTalkProfileData - STPedMotionPredictionSetContainer STPedNavigationPredictiontPresetContainer CBaitingInfo - CAnimalAnimationContexts CAnimalAttackBehaviours Relationships__GroupsData CMoodConditionManager - """, - "tuning, parameters, effects": """ - CTuningFile CCoverProcessorTuning GridAtlasInfo PatchConstants CClimbTuneMgr CoverShadowTunables - LostTargetSearch__Tunables sCollisionEventScannerTuning hrsSimTuneMgr rage__fragTuneStruct - DiffractionProfiles GlintsProfiles LightAnimationPresets CGraphicsDefinitionsData - """, - "mount / content manifests": """ - CDataFileMgr__ContentChangeSetDef CDataFileMgr__ContentDef - """, - "world, navigation, map": """ - GameShape__Data__LocationNameLoopkup PathingStyleData CTrainConfigs CHazardNodes - MapState__Data__Templates aiNavIMapGroupData CLadderMetadataManager CLadderRailsMetadataManager - CDoorInteractionDataList CEntityComponentLodManagerData CGarageInitDataList - CSceneTerrainAnalyzerMgrDataInstance CScenicViewManager MaterialDataList TextureGridInfo - Sprinklers__RootData CProceduralInfo CFluidVesselManager CObjectComponentSetManager - """, - "combat and AI behaviour": """ - CCombatInfoMgr CFiringPatternInfoManager CFleeDecisionMakerData Combat__GoalData__Store - CSearchPointOfInterestRuleSet CTacticalAnalysisDistributionStore - Modular__SM__AIBehaviour__LockControllerConfig Witnesses__Informations CTaskDataInfoManager - CDrivingStyleCollection CLassoDataManager CAimUpperBodyDataBlock SSetupData - """, - "animation, poses, weapons": """ - WeaponAnimations__FullbodyControllerData WeaponAnimations__ConfigData CStandardPosesManager - CAnimSceneAttachSlotSetManager StudioConfigurationData rage__fwRetargetCoordinatorConfig - """, - "damage": "CDamageDataManager", - "audio, video, speech": """ - LandingPageVideos CTVPlaylistContainer naSpeechEventTypeBatchRequestParams rage__MediaDecoderSettings - """, - "missions, scenarios, respawn": "CDynamicScenarioManager CMissions Respawn__MetaData", - "conversation": "CConversationList CConversationDictionary", -} -CATEGORY_BY_ROOT = {} -for _category, _roots in CATEGORY_ROOTS.items(): - for _root in _roots.split(): - CATEGORY_BY_ROOT[_root] = _category -UNCATALOGUED = "uncatalogued" - - -def category_for(root: str) -> str: - return CATEGORY_BY_ROOT.get(root, UNCATALOGUED) - - -def scan_refs(text: str, report: dict) -> None: - """Count symbolic macros and platform prefixes in one text or attribute value.""" - if not text: - return - if "$(" in text: - for match in MACRO_REF.finditer(text): - report["refs"]["$(" + match.group(1) + ")"] += 1 - if "platform:/" in text: - for match in PLATFORM_REF.finditer(text): - # Keep the bucket coarse: the first segment after a platform prefix can be a directory or a - # file-like archive name, and only levels/other is needed to route a mount. - report["platform"]["levels" if (match.group(1) or "").lower() == "levels" else "other"] += 1 - report["platform_total"] += 1 - - -def scan_xml(data: bytes) -> dict: - """Parse one document and return aggregate facts. Never keeps element text or values.""" - report = { - "root": "", - "well_formed": False, - "mismatched_tag": False, - "error": "", - "element_count": 0, - "max_depth": 0, - "attributes": [], - "comments": 0, - "elements": Counter(), - "attrs": Counter(), - "refs": Counter(), - "platform": Counter(), - "platform_total": 0, - "filename": 0, - "parent_path": 0, - "parent_file": 0, - "xi_include": 0, - "type_attrs": 0, - "type_values": set(), - "content_values": set(), - } - depth = 0 - ended = None - try: - parser = ET.iterparse(io.BytesIO(data), events=("start", "end", "comment")) - for event, elem in parser: - if event == "comment": - report["comments"] += 1 - continue - # A closing tag can be read before its tail. The next start or end event finalizes it. - if ended is not None: - scan_refs(ended.tail, report) - ended.clear() - ended = None - if event == "start": - depth += 1 - report["max_depth"] = max(report["max_depth"], depth) - if not report["root"]: - report["root"] = elem.tag - report["element_count"] += 1 - report["elements"][elem.tag] += 1 - for name, value in elem.attrib.items(): - report["attrs"][name] += 1 - if name == "type": - report["type_attrs"] += 1 - report["type_values"].add(value) - elif name == "content": - report["content_values"].add(value) - elif name == "parentPath": - report["parent_path"] += 1 - elif name == "parentFile": - report["parent_file"] += 1 - scan_refs(value, report) - if elem.tag == "filename": - report["filename"] += 1 - if elem.tag == XI_INCLUDE or elem.tag == "xi:include": - report["xi_include"] += 1 - else: - scan_refs(elem.text, report) - depth -= 1 - ended = elem - report["well_formed"] = True - except (ET.ParseError, LookupError, ValueError) as exc: - # The parser also raises LookupError or ValueError for unsupported encoding declarations. - report["error"] = str(exc) - report["mismatched_tag"] = (isinstance(exc, ET.ParseError) - and exc.code == errors.codes[errors.XML_ERROR_TAG_MISMATCH]) - # The parser stops at the error, so the comments after it would go uncounted (a truncated or tail-only - # document): count them in the bytes instead, respecting the surrounding markup. - report["comments"] = raw_comment_count(data) - if ended is not None: - scan_refs(ended.tail, report) - report["attributes"] = sorted(report["attrs"]) - return report - - -COMMENT_MARKUP = re.compile( - rb"(?P|\Z)" - rb"||\Z)" - rb"|<\?.*?(?:\?>|\Z)", - re.S, -) - - -def raw_comment_count(data: bytes) -> int: - """Count comment starts in malformed XML, consuming comments, CDATA and PIs through their terminator or EOF.""" - return sum(match.lastgroup == "comment" for match in COMMENT_MARKUP.finditer(data)) - - -def looks_truncated(data: bytes, root: str) -> bool: - """True when the bytes start inside a document instead of at its root element.""" - if not root: - return False - body = data[3:] if data.startswith(BOM) else data - body = body.lstrip(b" \t\r\n") - if body.startswith(b" dict: - # A truncated tail can begin with an inner element, so the index's closing-root hint wins. - root = doc.get("root_hint") or scan["root"] - header = doc.get("header") - if header is None: - header = gi.has_xml_decl(doc["data"]) - well_formed = scan["well_formed"] - if well_formed: - root = scan["root"] # the parsed name includes its namespace; a recovery hint need not - tail_only = fragment = False - elif doc.get("from_carve"): - tail_only = not header - fragment = not root or not doc.get("complete", True) - elif scan["mismatched_tag"]: - # A cut inside a comment or CDATA changes the lexical meaning of the - # retained tags. Accept that explanation only if restoring the opener - # produces a complete document; a terminator alone is not evidence. - repaired_root = "" - data = doc["data"] - closing_root = gi.tail_root(data) - if not header and closing_root: - body = data[3:] if data.startswith(BOM) else data - for opener, terminator in ((b""), (b"")): - if terminator not in body: - continue - try: - ET.fromstring(b"<" + closing_root.encode("ascii") + b">" + opener + body) - except (ET.ParseError, LookupError, ValueError): - continue - repaired_root = closing_root - break - root = repaired_root or gi.xml_root(data) or scan["root"] - tail_only, fragment = bool(repaired_root), False - else: - tail_only = looks_truncated(doc["data"], root) - fragment = not root - malformed = not well_formed and not tail_only and not fragment - row = { - "source": doc.get("name", ""), - "offset": doc.get("offset"), - "offset_hex": doc.get("offset_hex", ""), - "bytes": len(doc["data"]), - "chunks": doc.get("chunks", 1), - "root": root, - "category": category_for(root) if root else UNCATALOGUED, - "header": bool(header), - "complete": well_formed or doc.get("complete", False), - "well_formed": well_formed, - "fragment": fragment, - "tail_only": tail_only and not fragment, - "truncated": tail_only and not fragment and not scan["well_formed"], - "malformed": malformed, - "error": scan["error"], - "element_count": scan["element_count"] if scan["well_formed"] else None, - "max_depth": scan["max_depth"] if scan["well_formed"] else None, - "comments": scan["comments"], - "attributes": scan["attributes"], - "refs": dict(sorted(scan["refs"].items())), - "platform": dict(sorted(scan["platform"].items())), - "platform_total": scan["platform_total"], - "filename": scan["filename"], - "parent_path": scan["parent_path"], - "parent_file": scan["parent_file"], - "xi_include": scan["xi_include"], - "type_attrs": scan["type_attrs"], - "type_values": len(scan["type_values"]), - "content_values": len(scan["content_values"]), - } - row["_scan"] = scan - return row - - -def new_root_stats(root: str) -> dict: - return { - "root": root, - "category": category_for(root) if root else UNCATALOGUED, - "files": 0, - "well_formed": 0, - "fragments": 0, - "tail_only": 0, - "truncated": 0, - "malformed": 0, - "bytes": 0, - "elements": 0, - "max_depth": 0, - "element_names": Counter(), - "attributes": Counter(), - "refs": Counter(), - "platform": Counter(), - "platform_total": 0, - "filename": 0, - "parent_path": 0, - "parent_file": 0, - "xi_include": 0, - "type_attrs": 0, - "type_values": set(), - "content_values": set(), - } - - -def aggregate(rows: list) -> dict: - roots = {} - for row in rows: - stats = roots.setdefault(row["root"], new_root_stats(row["root"])) - stats["files"] += 1 - stats["bytes"] += row["bytes"] - stats["fragments"] += int(row["fragment"]) - stats["tail_only"] += int(row["tail_only"]) - stats["truncated"] += int(row["truncated"]) - stats["malformed"] += int(row["malformed"]) - if not row["well_formed"]: - continue - scan = row["_scan"] - stats["well_formed"] += 1 - stats["elements"] += scan["element_count"] - stats["max_depth"] = max(stats["max_depth"], scan["max_depth"]) - stats["element_names"].update(scan["elements"]) - stats["attributes"].update(scan["attrs"]) - stats["refs"].update(scan["refs"]) - stats["platform"].update(scan["platform"]) - stats["platform_total"] += scan["platform_total"] - stats["filename"] += scan["filename"] - stats["parent_path"] += scan["parent_path"] - stats["parent_file"] += scan["parent_file"] - stats["xi_include"] += scan["xi_include"] - stats["type_attrs"] += scan["type_attrs"] - stats["type_values"].update(scan["type_values"]) - stats["content_values"].update(scan["content_values"]) - - total_elements = Counter() - total_attributes = Counter() - total_refs = Counter() - total_platform = Counter() - all_type_values = set() - all_content_values = set() - by_category = defaultdict(lambda: {"files": 0, "roots": 0, "elements": 0, "bytes": 0}) - for root, stats in roots.items(): - total_elements.update(stats["element_names"]) - total_attributes.update(stats["attributes"]) - total_refs.update(stats["refs"]) - total_platform.update(stats["platform"]) - all_type_values.update(stats["type_values"]) - all_content_values.update(stats["content_values"]) - cat = by_category[stats["category"]] - cat["files"] += stats["files"] - cat["roots"] += 1 - cat["elements"] += stats["elements"] - cat["bytes"] += stats["bytes"] - - for stats in roots.values(): - stats["element_names"] = dict(sorted(stats["element_names"].items(), key=lambda kv: (-kv[1], kv[0]))) - stats["attributes"] = dict(sorted(stats["attributes"].items(), key=lambda kv: (-kv[1], kv[0]))) - stats["refs"] = dict(sorted(stats["refs"].items())) - stats["platform"] = dict(sorted(stats["platform"].items())) - stats["type_values"] = len(stats["type_values"]) - stats["content_values"] = len(stats["content_values"]) - - ordered_roots = dict(sorted(roots.items(), key=lambda kv: (-kv[1]["files"], kv[0]))) - return { - "roots": ordered_roots, - "elements": total_elements, - "attributes": total_attributes, - "refs": total_refs, - "platform": total_platform, - "type_values": len(all_type_values), - "content_kinds": len(all_content_values), - "categories": dict(sorted(by_category.items())), - } - - -def summarize(rows: list, agg: dict, mode: str) -> dict: - sizes = sorted(row["bytes"] for row in rows) - header_sizes = sorted(row["bytes"] for row in rows if row["header"]) - return { - "mode": mode, - "documents": len(rows), - "well_formed": sum(1 for row in rows if row["well_formed"]), - "fragments": sum(1 for row in rows if row["fragment"]), - "tail_only": sum(1 for row in rows if row["tail_only"]), - "truncated": sum(1 for row in rows if row["truncated"]), - "malformed": sum(1 for row in rows if row["malformed"]), - "root_count": sum(1 for root in agg["roots"] if root), - "unattributed": int("" in agg["roots"]), - "catalog_roots": sum(1 for root in agg["roots"] if root in CATEGORY_BY_ROOT), - "elements": sum(agg["elements"].values()), - "element_names": len(agg["elements"]), - "attributes": len(agg["attributes"]), - "max_depth": max((stats["max_depth"] for stats in agg["roots"].values()), default=0), - "comments": sum(row["comments"] for row in rows), - "comments_header": sum(row["comments"] for row in rows if row["header"]), - "header_documents": len(header_sizes), - "type_values": agg["type_values"], - "content_kinds": agg["content_kinds"], - "bytes": sum(sizes), - "min_bytes": sizes[0] if sizes else 0, - "median_bytes": int(statistics.median(sizes)) if sizes else 0, - "max_bytes": sizes[-1] if sizes else 0, - "header_bytes": { - "min": header_sizes[0] if header_sizes else 0, - "median": int(statistics.median(header_sizes)) if header_sizes else 0, - "max": header_sizes[-1] if header_sizes else 0, - }, - "references": dict(sorted(agg["refs"].items())), - "platform": dict(sorted(agg["platform"].items())), - "platform_total": sum(agg["platform"].values()), - "filename": sum(stats["filename"] for stats in agg["roots"].values()), - "parent_path": sum(stats["parent_path"] for stats in agg["roots"].values()), - "parent_file": sum(stats["parent_file"] for stats in agg["roots"].values()), - "xi_include": sum(stats["xi_include"] for stats in agg["roots"].values()), - "include_like": {name: agg["elements"].get(name, 0) for name in INCLUDE_ELEMENTS}, - "categories": agg["categories"], - "catalog": { - "roots": len(CATEGORY_BY_ROOT), - "categories": len(CATEGORY_ROOTS), - }, - } - - -def carve_documents(directory: str): - """Yield the XML payloads of an rpf9_carve.py directory, rebuilt by gamedata_index.""" - source = gi.DirectorySource(directory) - rows = gi.build_rows(source.rows, source) - by_offset = {row["off"]: index for index, row in enumerate(source.rows)} - for row in rows: - if row["type"] != "xml": - continue - start = by_offset[row["offset"]] - data = b"".join(source.read(source.rows[index]) for index in range(start, start + row["chunks"])) - yield { - "data": data, - "from_carve": True, - "offset": row["offset"], - "offset_hex": row["offset_hex"], - "chunks": row["chunks"], - "header": row["header"], - "complete": row["complete"], - "root_hint": row["root"], - } - - -def xml_files(directory: str): - def scan_failed(exc: OSError) -> None: - raise exc - - for base, _, names in os.walk(directory, onerror=scan_failed): - for name in sorted(names): - if name.lower().endswith(".xml"): - yield os.path.join(base, name) - - -def input_files(targets: list): - """Yield every file the scan will read, so a report path cannot overwrite one. - - Directory mode reads every nested ``*.xml``; carve mode reads ``index.json`` and the - ``.bin``/``.bk2`` stream files next to it. A report path only has to match - one of these, not the target argument itself. - """ - for target in targets: - if os.path.isdir(target): - if os.path.isfile(os.path.join(target, "index.json")): - yield os.path.join(target, "index.json") - with os.scandir(target) as entries: - for entry in entries: - if entry.is_file() and entry.name.lower().endswith((".bin", ".bk2")): - yield entry.path - else: - yield from xml_files(target) - elif os.path.isfile(target): - yield target - - -def input_name_matches(name: str, target: str) -> bool: - """Whether a report basename could be a name the scan reads from this directory target.""" - name = name.lower() - if os.path.isdir(target): - if os.path.isfile(os.path.join(target, "index.json")): - return name == "index.json" or name.endswith((".bin", ".bk2")) - return name.endswith(".xml") - return False - - -def has_symlinked_input(target: str) -> bool: - """Whether the scan can read a symlink to the report from this target.""" - if os.path.isdir(target): - if os.path.isfile(os.path.join(target, "index.json")): - with os.scandir(target) as entries: - for entry in entries: - if entry.is_symlink(): - leaf = entry.name.lower() - if leaf == "index.json" or leaf.endswith((".bin", ".bk2")): - return True - else: - for base, _, names in os.walk(target): - for name in names: - if name.lower().endswith(".xml") and os.path.islink(os.path.join(base, name)): - return True - return False - - -def report_needs_input_check(path: str, targets: list) -> bool: - """Whether a report path has to be compared with every scanned input. - - A report that already exists as a regular file, is not a symlink and has one link is reachable - only through its own name. When that name cannot be an input read from a directory target, and - no scanned input is a symlink to it, the per-file ``same_report_path`` checks can be skipped. - Missing reports, links, explicit file targets and input-like names are always compared. - """ - try: - st = os.lstat(path) - except OSError: - return True - if not stat.S_ISREG(st.st_mode) or st.st_nlink != 1: - return True - name = os.path.basename(os.path.realpath(path)) - for target in targets: - if os.path.isdir(target): - if input_name_matches(name, target) or has_symlinked_input(target): - return True - elif os.path.isfile(target): - return True # an explicit file target can have any name - return False - - -def document_mode(targets: list) -> str: - for target in targets: - if os.path.isdir(target) and os.path.isfile(os.path.join(target, "index.json")): - return "carve" - return "files" - - -def load_documents(targets: list): - """Yield one document per XML payload. Directories with index.json use the carve path.""" - for target in targets: - if os.path.isdir(target): - if os.path.isfile(os.path.join(target, "index.json")): - for doc in carve_documents(target): - yield doc - else: - for path in xml_files(target): - yield file_document(path) - elif os.path.isfile(target): - yield file_document(target) - else: - raise FileNotFoundError(target) - - -def file_document(path: str) -> dict: - with open(path, "rb") as f: - data = f.read() - head, tail = gi.xml_root(data), gi.tail_root(data) - root = head if (head and (gi.has_xml_decl(data) or not gi.xml_complete(head, data))) else (tail or head) - return { - "data": data, - "from_carve": False, - "name": os.path.basename(path), - "root_hint": root, - } - - -def _make_parent(path: str) -> None: - """Create the folder an output path lives in: the scan is over by the time we write, so a missing - folder used to end the run in a FileNotFoundError and lose the result.""" - parent = os.path.dirname(os.path.abspath(path)) - if parent: - os.makedirs(parent, exist_ok=True) - - -def write_csv(path: str, rows: list) -> None: - _make_parent(path) - fields = ["source", "offset_hex", "bytes", "chunks", "root", "category", "header", "complete", - "well_formed", "fragment", "tail_only", "truncated", "malformed", "element_count", - "max_depth", "comments", "attributes", "refs", "platform", "platform_total", "filename", - "parent_path", "parent_file", "xi_include", "type_attrs", "type_values", "content_values", - "error"] - with open(path, "w", newline="", encoding="utf-8") as f: - writer = csv.DictWriter(f, fieldnames=fields, extrasaction="ignore", lineterminator="\n") - writer.writeheader() - for row in rows: - out = dict(row) - out["attributes"] = " ".join(row["attributes"]) - out["refs"] = ";".join(f"{key}={value}" for key, value in row["refs"].items()) - out["platform"] = ";".join(f"{key}={value}" for key, value in row["platform"].items()) - for flag in ("header", "complete", "well_formed", "fragment", "tail_only", "truncated", - "malformed"): - out[flag] = str(row[flag]).lower() - writer.writerow(out) - - -def plural(count: int, word: str) -> str: - return f"{count} {word}" if count == 1 else f"{count} {word}s" - - -def check_report(rows: list) -> bool: - """Print the validation split. Return True when no complete document is malformed.""" - fragments = sum(1 for row in rows if row["fragment"]) - print(f"check: {sum(1 for row in rows if row['well_formed'])} well-formed, " - f"{sum(1 for row in rows if row['truncated'])} truncated at the start, " - f"{plural(fragments, 'rootless fragment')}, " - f"{sum(1 for row in rows if row['malformed'])} malformed") - for row in rows: - if not (row["truncated"] or row["fragment"] or row["malformed"]): - continue - where = row["offset_hex"] or row["source"] or "?" - if row["malformed"]: - print(f" malformed {row['root'] or '?'} @ {where}: {row['error']}") - elif row["truncated"]: - print(f" truncated {row['root']} @ {where}: starts mid-document") - else: - print(f" fragment @ {where}: no root element") - return not any(row["malformed"] for row in rows) - - -def print_summary(summary: dict, agg: dict) -> None: - docs = summary["documents"] - print(f'{docs} XML payloads, {summary["bytes"]:,} bytes ' - f'(min {summary["min_bytes"]:,}, median {summary["median_bytes"]:,}, ' - f'max {summary["max_bytes"]:,})') - print(f'{summary["well_formed"]} well-formed, {summary["tail_only"]} tail-only ' - f'({summary["truncated"]} truncated), {plural(summary["fragments"], "rootless fragment")}, ' - f'{summary["malformed"]} malformed') - print(f'{summary["root_count"]} named roots (+{summary["unattributed"]} unattributed), ' - f'{summary["elements"]:,} elements, {summary["element_names"]:,} element names, ' - f'{summary["attributes"]} attributes, max depth {summary["max_depth"]}, ' - f'{summary["type_values"]} type values, {summary["content_kinds"]} content kinds') - print(f'{summary["comments"]} comment starts ' - f'({summary["comments_header"]} in {summary["header_documents"]} declaration-bearing documents)') - refs = ", ".join(f"{key} {value:,}" for key, value in summary["references"].items()) - platforms = ", ".join(f"{key} {value:,}" for key, value in summary["platform"].items()) - print(f"references: {summary['platform_total']:,} platform:/ ({platforms}); {refs}") - print(f'include-like: {summary["filename"]:,} filename, {summary["parent_path"]} parentPath, ' - f'{summary["parent_file"]} parentFile, {summary["xi_include"]} xi:include') - print("categories:") - for name, stats in summary["categories"].items(): - print(f' {plural(stats["files"], "file"):8} {plural(stats["roots"], "root"):8} ' - f'{stats["elements"]:7,} elements {name}') - print("roots:") - for root, stats in list(agg["roots"].items())[:10]: - if not root: - continue - print(f' {plural(stats["files"], "file"):8} {stats["elements"]:7,} elements ' - f'{root} [{stats["category"]}]') - - -def main() -> int: - parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) - parser.add_argument("targets", nargs="+", help="carve directory or XML file(s)") - parser.add_argument("--csv", help="write one row per XML document to this CSV") - parser.add_argument("--json", help="write the summary, per-root catalog and rows to this JSON") - parser.add_argument("--check", action="store_true", help="validate well-formedness and report fragments") - args = parser.parse_args() - - if args.csv and args.json and same_report_path(args.csv, args.json): - parser.error("--csv and --json must use different paths") - for flag, path in (("--csv", args.csv), ("--json", args.json)): - if not path: - continue - if os.path.isdir(path): - parser.error(f"{flag} is a directory: {path}") - if report_needs_input_check(path, args.targets): - for source in input_files(args.targets): - if same_report_path(path, source): - parser.error(f"{flag} would overwrite the input {source}") - - rows = [] - mode = document_mode(args.targets) - try: - for doc in load_documents(args.targets): - rows.append(file_row(doc, scan_xml(doc["data"]))) - except FileNotFoundError as exc: - print(f"not found: {exc}", file=sys.stderr) - return 2 - except RuntimeError as exc: - print(f"ERROR: {exc}", file=sys.stderr) - return 2 - except (OSError, ValueError, KeyError, TypeError) as exc: - # Same one-line contract as gamedata_index.py: a bad carve index is an error, not a traceback. - where = getattr(exc, "filename", None) or args.targets[0] - print(f"ERROR: cannot read {where}: {getattr(exc, 'strerror', None) or exc!r}", file=sys.stderr) - return 2 - - agg = aggregate(rows) - summary = summarize(rows, agg, mode) - clean = True - if args.check: - clean = check_report(rows) - print_summary(summary, agg) - if args.csv: - try: - write_csv(args.csv, rows) - except OSError as exc: - print(f"ERROR: cannot write {args.csv}: {exc.strerror or exc}", file=sys.stderr) - return 2 - print("wrote", args.csv) - if args.json: - public_rows = [{key: value for key, value in row.items() if key != "_scan"} for row in rows] - try: - _make_parent(args.json) - with open(args.json, "w", encoding="utf-8", newline="\n") as f: - json.dump({"summary": summary, "roots": agg["roots"], "rows": public_rows}, f, indent=1) - except OSError as exc: - print(f"ERROR: cannot write {args.json}: {exc.strerror or exc}", file=sys.stderr) - return 2 - print("wrote", args.json) - return 0 if clean else 1 - - -if __name__ == "__main__": - try: # a redirected stdout is strict ANSI code page under -I; write '?' for what it cannot encode - sys.stdout.reconfigure(errors="replace") - except (AttributeError, ValueError, OSError): - pass - sys.exit(main()) diff --git a/tools/gbuffer_census.py b/tools/gbuffer_census.py deleted file mode 100644 index d89ecd225..000000000 --- a/tools/gbuffer_census.py +++ /dev/null @@ -1,150 +0,0 @@ -"""Count declared G-buffer signatures and static exports in an indexed shader carve.""" -import argparse -from collections import Counter -import hashlib -import json -from pathlib import Path -import re -import struct -import sys -import zlib - -sys.path.insert(0, str(Path(__file__).resolve().parent)) -from feature_scan import parts, signature_offsets -from fssm_unpack import unpack_all -from shader_ir import ENC, HDR, parse_line - - -def signature(path): - return signature_bytes(path.read_bytes()) - - -def signature_bytes(data): - sig = parts(data)["OSG1"] - rows = [] - for offset in signature_offsets(sig): - index, system, ctype, register, mask, _, precision = struct.unpack_from( - "<4IBB2xI", sig, offset + 8) - kind = {64: "target", 65: "depth", 67: "depth_ge", 68: "depth_le"}.get(system, f"system{system}") - rows.append((kind, index, register, mask, ctype, precision)) - shape = Counter(row[0] for row in rows) - colour = shape["target"] - depth = sum(shape[key] for key in ("depth", "depth_ge", "depth_le")) - layout = " | ".join(f"{k}{i} reg={r} mask={m:#x} type={t} precision={p}" - for k, i, r, m, t, p in sorted(rows)) or "(empty)" - return f"{len(rows)} rows, {colour} colour, {depth} depth", layout - - -def exports(path): - counts = Counter() - encoded_bytes = 0 - with path.open(encoding="utf-8") as listing: - header = listing.readline() - span = HDR.match(header) - for line in listing: - if line.startswith("; ---"): - break - encoding = ENC.search(line) - if encoding and encoding[1].strip(): - encoded_bytes += encoding[1].count(",") + 1 - if line.split(maxsplit=1)[:1] != ["exp"]: - continue - ins = parse_line(line) - target = ins["args"][0].get("t", "") - if re.fullmatch(r"mrt[0-7z]", target): - mode = "compr" if "compr" in ins["mods"] else "uncompressed" - counts[f"{target} {mode}"] += 1 - complete = (span and encoded_bytes > 0 and encoded_bytes == int(span[3], 16) - int(span[2], 16) - and not re.search(r"\b[1-9]\d* invalid words", header)) - return counts, bool(complete) - - -def payload_identity(data): - """Only assign an entry when its container identifies one whole FSSM.""" - try: - if data is None or not data.startswith(b"DXBC"): - return "unavailable", None - identities = {hashlib.sha256(blob).digest() for blob in unpack_all(data)} - except (ValueError, struct.error, zlib.error): - return "unavailable", None - if not identities: - return "unavailable", None - if len(identities) > 1: - return "ambiguous", None - return "identified", identities.pop() - - -def census(directory, listings, *, payload_coverage=False): - predicates = ("all indexed ps", "entry contains deferred (casefold)", - "stem contains Deferred (case-sensitive)", "stem contains PS_DeferredTextured (case-sensitive)") - report = {key: {"coverage": Counter(), "declared_counts": Counter(), "signatures": Counter(), "observed_exports": Counter()} - for key in predicates} - identities = {key: Counter() for key in predicates} - if payload_coverage: - for group in report.values(): - group["payload_coverage"] = dict(identified=0, ambiguous=0, unavailable=0) - for row in json.loads((directory / "index.json").read_text(encoding="utf-8")): - if row["stage"] != "ps": - continue - path = directory / row["file"] - stem = path.stem - selected = (True, "deferred" in row["name"].casefold(), "Deferred" in stem, "PS_DeferredTextured" in stem) - coverage = Counter(indexed=1) - sig = None - observed = Counter() - data = None - try: - data = path.read_bytes() - sig = signature_bytes(data) - coverage["signature_read"] += 1 - except FileNotFoundError: - coverage["container_missing"] += 1 - except (KeyError, ValueError, struct.error, OSError): - coverage["signature_unreadable"] += 1 - try: - observed, complete = exports(listings / (stem + ".s")) - coverage["listing_complete" if complete else "listing_incomplete"] += 1 - except FileNotFoundError: - coverage["listing_missing"] += 1 - except (OSError, IndexError, ValueError): - coverage["listing_unreadable"] += 1 - if payload_coverage: - status, digest = payload_identity(data) - for key, include in zip(predicates, selected): - if include: - group = report[key] - if payload_coverage: - group["payload_coverage"][status] += 1 - if digest is not None: - identities[key][digest] += 1 - group["coverage"].update(coverage) - group["observed_exports"].update(observed) - if sig is not None: - shape, layout = sig - group["declared_counts"][shape] += 1 - group["signatures"][layout] += 1 - if payload_coverage: - for key, counts in identities.items(): - summary = report[key]["payload_coverage"] - summary["distinct_payloads"] = len(counts) - summary["payloads_by_indexed_entry_count"] = Counter(counts.values()) - return report - - -def main(): - parser = argparse.ArgumentParser(description=__doc__) - parser.add_argument("dxbc", type=Path, help="shader_carve directory containing index.json") - parser.add_argument("--disasm", type=Path, help="listing directory (default: DXBC/disasm)") - parser.add_argument("--payload-coverage", action="store_true", - help="count distinct whole FSSM payloads per cohort and histogram their indexed entry counts") - args = parser.parse_args() - print(json.dumps(census(args.dxbc, args.disasm or args.dxbc / "disasm", - payload_coverage=args.payload_coverage), indent=2, sort_keys=True)) - - -if __name__ == "__main__": - try: # a redirected stdout is strict ANSI code page under -I; write '?' for what it cannot encode - sys.stdout.reconfigure(errors="replace") - except (AttributeError, ValueError, OSError): - pass - main() diff --git a/tools/gdk_runtime_calls.py b/tools/gdk_runtime_calls.py deleted file mode 100644 index a6ab6bfec..000000000 --- a/tools/gdk_runtime_calls.py +++ /dev/null @@ -1,1076 +0,0 @@ -"""List the GDK runtime classes, interfaces and vtable slots a PE image calls through xgameruntime.lib's thunks. - -Usage: - python -I tools/gdk_runtime_calls.py [ ...] [--json] [--out DIR] - [--table FILE] [--runtime-source FILE] - -A title linked with xgameruntime.lib imports no GDK function. Each function of the library is a thunk that calls a -helper with a class id and an interface id (the helper initializes the runtime once and calls QueryApiImpl), then -calls one slot of the returned object's vtable with the function's own arguments after `this`, then Release (slot 2) -(docs/runtime_imports.md, "Class layouts, measured"). This finds those thunks in the image's code without running -it, and names each slot from tools/gdk_runtime_classes.json (tools/gen_gdk_runtime_classes.py makes it from -xgameruntime-docs). Run on the game executable, the classes and slots it prints are the runtime surface to serve -before the first boot. - -How it finds them (x86-64 images only): -1. Every 16-byte in-memory copy of a class or interface id the table knows, in the data sections (in the code - sections when the data sections have none). -2. Every RIP-relative `lea reg,[id]` in executable sections; the first call after it is a helper candidate. A - candidate is a helper when, after it returns, one or more vtable slots past IUnknown are called (`mov r,[obj]`, - `mov r,[r+disp]` and a call through it, the CFG `call __guard_dispatch_icall` form or `call [r+disp]`, followed - through register copies). -3. Every call to a helper is a thunk, whatever ids it passes: an id the table doesn't know is reported as unknown. - The ids are the RIP-relative addresses loaded into the helper's first two argument registers (followed through - register copies): rcx holds the class id, rdx the interface id (the class id when rdx holds none). A helper call - whose rcx holds no address is listed as not followed, with the calls after which no slot call is found. -4. After the helper call, each slot call up to Release, the next helper call or the end of the function is - recorded. Function bounds come from the exception directory (.pdata), or a byte window without one. -5. Whether anything in the image reaches each thunk function: a call, tail jump, RIP-relative address load or - 8-byte pointer in data, directly or through an incremental-link `jmp` stub, from code that is itself reached - when it is another thunk. An incremental link doesn't remove unreferenced functions, so an image can carry - thunks nothing calls (libHttpClient.GDK.dll calls 15 of its 404). - -The interface's slot table is the methods of its inheritance chain, base first, from slot 3. An id that is a class -id but not an interface id is read as the class's implemented interface. The argument count is an estimate: the -highest of rdx/r8/r9 (xmm1-3) written, or [rsp+20h+8k] stored, between the previous call and the slot call. - -Output: per image and class, the class and interface ids, the slots called with their method names and whether -their thunks are referenced, the thunk count, and whether the runtime serves the class (a `constexpr GUID -k...Class` with its id in one of runtime/shims/xgameruntime*.cpp: xgameruntime.cpp and the classes it hands on to -xgameruntime_user.cpp, _gamesave.cpp, _store.cpp, _offline.cpp; the class only, not each slot); then the known ids present in the image that -no thunk reaches. Text by default, --json for JSON. --out DIR writes both, as .gdk_calls.txt and -.json (x.dll-2.gdk_calls.txt for a second input named x.dll), and prints one summary line per image instead. - -Exit status 1 when an image (or the class table) can't be read, or an image is cut off before the end of its -sections (the report of what is there is still written); 0 otherwise. Reads the files only; never runs them. -Standard library only. -""" -from __future__ import annotations - -import argparse -import bisect -import json -import os -import re -import struct -import sys -import uuid - -sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) -from pe_inspect import DIR_EXCEPTION, MACHINES, PeFormatError, PeImage # noqa: E402 -from report_paths import same_report_path # noqa: E402 - -HERE = os.path.dirname(os.path.abspath(__file__)) -DEFAULT_TABLE = os.path.join(HERE, "gdk_runtime_classes.json") -DEFAULT_RUNTIME_SOURCE = os.path.join(HERE, "..", "runtime", "shims") # every xgameruntime*.cpp in it - -IUNKNOWN_SLOTS = 3 # QueryInterface, AddRef, Release -RELEASE = 2 -NO_PDATA_WINDOW = 256 # bytes scanned after a helper call when no .pdata entry covers it -BACK_WINDOW = 64 # bytes searched before a helper call for the instructions that load its arguments -LEA_TO_CALL = 8 # instructions from an id's lea to the helper call it feeds - -# ---- A small x86-64 instruction decoder: lengths, ModRM operands and branch targets ---- - -RIP = 16 # base register value of a RIP-relative operand -XMM = 32 # register number of xmm0 in writes() -RAX, RCX, RDX, RSP, R8, R9 = 0, 1, 2, 4, 8, 9 -VOLATILE = frozenset((0, 1, 2, 8, 9, 10, 11)) -ARG_INDEX = {RDX: 1, R8: 2, R9: 3, XMM + 1: 1, XMM + 2: 2, XMM + 3: 3} - -_PREFIXES = frozenset((0x26, 0x2E, 0x36, 0x3E, 0x64, 0x65, 0x66, 0x67, 0xF0, 0xF2, 0xF3)) -_ALU = [b + i for b in range(0, 0x40, 8) for i in range(4)] -_M1_MODRM = frozenset(_ALU + [0x63, 0x69, 0x6B, *range(0x80, 0x90), 0xC0, 0xC1, 0xC6, 0xC7, *range(0xD0, 0xD4), - *range(0xD8, 0xE0), 0xF6, 0xF7, 0xFE, 0xFF]) -_M1_INVALID = frozenset((0x06, 0x07, 0x0E, 0x16, 0x17, 0x1E, 0x1F, 0x27, 0x2F, 0x37, 0x3F, 0x60, 0x61, 0x82, 0x9A, - 0xCE, 0xD4, 0xD5, 0xD6, 0xEA)) -_M1_IMM8 = frozenset([b + 4 for b in range(0, 0x40, 8)] + [0x6A, 0x6B, 0x80, 0x83, 0xA8, *range(0xB0, 0xB8), 0xC0, - 0xC1, 0xC6, 0xCD, 0xE4, 0xE5, 0xE6, 0xE7]) -_M1_IMMZ = frozenset([b + 5 for b in range(0, 0x40, 8)] + [0x68, 0x69, 0x81, 0xA9, 0xC7]) -_M1_REL8 = frozenset([*range(0x70, 0x80), 0xE0, 0xE1, 0xE2, 0xE3, 0xEB]) -_M2_NO_MODRM = frozenset((0x05, 0x06, 0x07, 0x08, 0x09, 0x0B, 0x0E, *range(0x30, 0x38), 0x77, 0xA0, 0xA1, 0xA2, - 0xA8, 0xA9, 0xAA, *range(0xC8, 0xD0))) -_M2_IMM8 = frozenset((0x0F, 0x70, 0x71, 0x72, 0x73, 0xA4, 0xAC, 0xBA, 0xC2, 0xC4, 0xC5, 0xC6)) -_M2_INVALID = frozenset((0x04, 0x0A, 0x0C, 0x24, 0x25, 0x26, 0x27, 0x36, 0x39, 0x3B, 0x3C, 0x3D, 0x3E, 0x3F)) -_VEX_IMM8 = frozenset((0x70, 0x71, 0x72, 0x73, 0xC2, 0xC4, 0xC5, 0xC6)) - -# Opcodes (0x1xx = 0F xx) that write their ModRM reg operand, or their r/m operand when it is a register. -_WRITE_REG = frozenset((0x02, 0x03, 0x0A, 0x0B, 0x12, 0x13, 0x1A, 0x1B, 0x22, 0x23, 0x2A, 0x2B, 0x32, 0x33, 0x63, - 0x69, 0x6B, 0x86, 0x87, 0x8A, 0x8B, 0x8D, *range(0x140, 0x150), 0x1AF, 0x1B6, 0x1B7, 0x1B8, - 0x1BC, 0x1BD, 0x1BE, 0x1BF, 0x1C0, 0x1C1)) -_WRITE_RM = frozenset((0x00, 0x01, 0x08, 0x09, 0x10, 0x11, 0x18, 0x19, 0x20, 0x21, 0x28, 0x29, 0x30, 0x31, 0x86, - 0x87, 0x88, 0x89, 0x8F, 0xC0, 0xC1, 0xD0, 0xD1, 0xD2, 0xD3, *range(0x190, 0x1A0), 0x1C0, - 0x1C1)) -_WRITE_XMM = frozenset((0x110, 0x112, 0x114, 0x115, 0x116, 0x128, 0x12A, *range(0x151, 0x160), 0x16E, 0x16F)) -_STORE = frozenset((0x88, 0x89, 0xC6, 0xC7, 0x111, 0x129, 0x17F, 0x1D6)) - - -class Insn: - """One decoded instruction. `op` is the opcode byte, 0x100|b for 0F b, 0x200|b / 0x300|b for 0F 38 / 0F 3A - and 0x1000|map<<8|b under VEX/EVEX. `reg`/`rm` carry their REX bits; `base` is RIP for a RIP-relative operand - and None for a register operand; `target` is a branch target or a RIP-relative operand's RVA.""" - __slots__ = ("rva", "size", "op", "rex", "reg", "mod", "rm", "base", "index", "disp", "target") - - def __init__(self, rva, size, op, rex, reg, mod, rm, base, index, disp, target): - self.rva, self.size, self.op, self.rex = rva, size, op, rex - self.reg, self.mod, self.rm, self.base, self.index, self.disp, self.target = ( - reg, mod, rm, base, index, disp, target) - - @property - def end(self) -> int: - return self.rva + self.size - - @property - def wide(self) -> bool: - return bool(self.rex & 8) - - def is_call(self) -> bool: - return self.op == 0xE8 or (self.op == 0xFF and self.mod is not None and self.reg & 7 == 2) - - def ends_flow(self) -> bool: - """ret, or an unconditional jump.""" - return (self.op in (0xC3, 0xC2, 0xE9, 0xEB) - or (self.op == 0xFF and self.mod is not None and self.reg & 7 in (4, 5))) - - def call_key(self): - """What a direct call reaches: ("rel", rva) for call rel32, ("mem", rva) for call [rip+x].""" - if self.op == 0xE8: - return ("rel", self.target) - if self.op == 0xFF and self.base == RIP and self.reg & 7 == 2: - return ("mem", self.target) - return None - - def memory_at(self, base: int) -> bool: - """A memory operand [base+disp] with no index register.""" - return self.mod is not None and self.mod != 3 and self.base == base and self.index is None - - -def decode(buf, off: int, base_rva: int) -> Insn | None: - """Decode the instruction at buf[off] (buf starts at base_rva). None for an invalid or cut-off instruction.""" - n = len(buf) - p = off - p66 = p67 = False - while p < n and buf[p] in _PREFIXES: - p66 |= buf[p] == 0x66 - p67 |= buf[p] == 0x67 - p += 1 - if p >= n or p - off > 14: - return None - rex = 0 - b = buf[p] - if 0x40 <= b <= 0x4F: - rex = b - p += 1 - if p >= n: - return None - b = buf[p] - p += 1 - modrm = False - imm = rel = 0 - if b in (0xC4, 0xC5, 0x62): # VEX / EVEX: always so in 64-bit mode - if b == 0xC5: - if p >= n: - return None - rex, vmap = 0x40 | (0 if buf[p] & 0x80 else 4), 1 - p += 1 - else: - if p + (2 if b == 0x62 else 1) >= n: - return None - b1, b2 = buf[p], buf[p + 1] - vmap = b1 & (0x07 if b == 0x62 else 0x1F) - rex = (0x40 | (0 if b1 & 0x80 else 4) | (0 if b1 & 0x40 else 2) | (0 if b1 & 0x20 else 1) - | (8 if b2 & 0x80 else 0)) - p += 3 if b == 0x62 else 2 - if p >= n: - return None - b = buf[p] - p += 1 - op = 0x1000 | (vmap << 8) | b - modrm = not (vmap == 1 and b == 0x77) - imm = 1 if vmap == 3 or (vmap == 1 and b in _VEX_IMM8) else 0 - elif b == 0x0F: - if p >= n: - return None - b = buf[p] - p += 1 - if b in (0x38, 0x3A): - if p >= n: - return None - op = (0x200 if b == 0x38 else 0x300) | buf[p] - p += 1 - modrm = True - imm = 1 if b == 0x3A else 0 - else: - if b in _M2_INVALID: - return None - op = 0x100 | b - if 0x80 <= b <= 0x8F: - rel = 4 - elif b not in _M2_NO_MODRM: - modrm = True - imm = 1 if b in _M2_IMM8 else 0 - else: - if b in _M1_INVALID: - return None - op = b - modrm = b in _M1_MODRM - if b in _M1_IMM8: - imm = 1 - elif b in _M1_IMMZ: - imm = 2 if (p66 and not (rex & 8)) else 4 - elif b in _M1_REL8: - rel = 1 - elif b in (0xE8, 0xE9): - rel = 4 - elif 0xB8 <= b <= 0xBF: - imm = 8 if rex & 8 else (2 if p66 else 4) - elif b in (0xC2, 0xCA): - imm = 2 - elif b == 0xC8: - imm = 3 - elif 0xA0 <= b <= 0xA3: - imm = 4 if p67 else 8 - - reg = mod = rm = mbase = index = None - disp = 0 - rip = False - if modrm: - if p >= n: - return None - m = buf[p] - p += 1 - mod, reg, low = m >> 6, ((m >> 3) & 7) | ((rex & 4) << 1), m & 7 - dsize = 1 if mod == 1 else 4 if mod == 2 else 0 - if mod == 3: - rm = low | ((rex & 1) << 3) - elif low == 4: - if p >= n: - return None - s = buf[p] - p += 1 - idx = ((s >> 3) & 7) | ((rex & 2) << 2) - index = None if idx == 4 else idx - if s & 7 == 5 and mod == 0: - dsize = 4 # [index*scale + disp32], no base - else: - mbase = (s & 7) | ((rex & 1) << 3) - elif low == 5 and mod == 0: - mbase, dsize, rip = RIP, 4, True - else: - mbase = low | ((rex & 1) << 3) - if p + dsize > n: - return None - if dsize == 1: - disp = struct.unpack_from(" n: - return None - delta = struct.unpack_from(" n or p - off > 15: - return None - if rip: - target = base_rva + p + disp - return Insn(base_rva + off, p - off, op, rex, reg, mod, rm, mbase, index, disp, target) - - -def writes(i: Insn) -> list[int]: - """Registers the instruction writes (general registers 0-15, xmm n as XMM+n), for the forms that matter here.""" - op = i.op - if i.mod is None: - low = (op & 7) | ((i.rex & 1) << 3) - if 0xB0 <= op <= 0xBF or 0x58 <= op <= 0x5F: - return [low] - if 0x91 <= op <= 0x97: - return [RAX, low] - if op == 0x99: - return [RDX] - if op == 0x98: - return [RAX] - return [] - out = [] - if op in _WRITE_REG: - out.append(i.reg) - elif op in _WRITE_XMM: - out.append(XMM + i.reg) - if i.mod == 3: - sub = i.reg & 7 - if (op in _WRITE_RM or (op in (0x80, 0x81, 0x83) and sub != 7) or (op in (0xC6, 0xC7) and sub == 0) - or (op in (0xF6, 0xF7) and sub in (2, 3)) or (op in (0xFE, 0xFF) and sub in (0, 1))): - out.append(i.rm) - if op in (0xF6, 0xF7) and i.reg & 7 >= 4: # mul/imul/div/idiv - out += [RAX, RDX] - return out - - -def stack_argument(i: Insn) -> int | None: - """The argument number (5th = 4 after `this`) of a store to the outgoing stack area [rsp+20h+8k], else None.""" - if (i.op in _STORE and i.memory_at(RSP) and i.disp >= 0x20 and i.disp % 8 == 0 - and not (i.op in (0xC6, 0xC7) and i.reg & 7)): - return 4 + (i.disp - 0x20) // 8 - return None - - -# ---- The class table and the runtime shim ---- - -def guid_bytes(guid: str) -> bytes: - return uuid.UUID(guid).bytes_le - - -class RuntimeTable: - """tools/gdk_runtime_classes.json: class and interface ids, inheritance and method order.""" - - def __init__(self, doc: dict): - self.source = doc.get("source", "") - self.classes: dict = doc["classes"] - self.interfaces: dict = doc["interfaces"] - self.class_by_id = {c["id"]: name for name, c in self.classes.items()} - self.interface_by_id = {i["id"]: name for name, i in self.interfaces.items()} - - @classmethod - def load(cls, path: str) -> "RuntimeTable": - with open(path, encoding="utf-8-sig") as f: - return cls(json.load(f)) - - def ids(self) -> set[str]: - return set(self.class_by_id) | set(self.interface_by_id) - - def label(self, guid: str) -> str: - """What an id names: 'XUserImpl', 'IXUserImpl5', 'XThreadingImpl/IXThreadingImpl', or 'unknown'.""" - names = [n for n in (self.class_by_id.get(guid), self.interface_by_id.get(guid)) if n] - return "/".join(names) or "unknown" - - def class_of(self, guid: str) -> str | None: - if guid in self.class_by_id: - return self.class_by_id[guid] - iface = self.interface_by_id.get(guid) - return self.interfaces[iface]["class"] if iface else None - - def interface_for(self, guid: str) -> str | None: - """The interface whose slot table names the slots called through this id.""" - if guid in self.interface_by_id: - return self.interface_by_id[guid] - cls = self.class_by_id.get(guid) - if cls and self.classes[cls]["implements"]: - return self.classes[cls]["implements"][0] - return None - - def chain(self, iface: str) -> list[str]: - out, seen = [], set() - while iface and iface in self.interfaces and iface not in seen: - seen.add(iface) - out.append(iface) - iface = self.interfaces[iface]["inherits"] - return out[::-1] - - def slot_table(self, iface: str) -> tuple[list, list[str]]: - """(method names from slot 3 on, None where unknown), and the chain's interfaces without a layout.""" - names, no_layout = [], [] - for name in self.chain(iface): - methods = self.interfaces[name]["methods"] - if methods is None: - no_layout.append(name) - else: - names.extend(methods) - return names, no_layout - - def method(self, iface: str | None, slot: int) -> tuple[str | None, str | None]: - """(method name or None, the interface it was read from when that is not `iface`).""" - if not iface: - return None, None - names, _ = self.slot_table(iface) - k = slot - IUNKNOWN_SLOTS - if 0 <= k < len(names): - return names[k], None - # Past the requested interface: the object is the class's, so its implemented interface may name the slot - # when the requested one is on that interface's chain (an id that is both the class's and its base's). - cls = self.interfaces[iface]["class"] - for impl in self.classes.get(cls, {}).get("implements", []): - if impl != iface and iface in self.chain(impl): - more, _ = self.slot_table(impl) - if 0 <= k < len(more): - return more[k], impl - return None, None - - -GUID_CONSTANT = re.compile( - r"constexpr\s+GUID\s+k(\w*?)Class\s*=\s*\{\s*(0x[0-9a-fA-F]+)\s*,\s*(0x[0-9a-fA-F]+)\s*,\s*(0x[0-9a-fA-F]+)\s*," - r"\s*\{([^}]*)\}\s*\}") - - -def read_runtime_source(path: str) -> str: - """The text of a shim source file, or of every xgameruntime*.cpp in a folder (OSError when there is none).""" - if os.path.isdir(path): - names = sorted(n for n in os.listdir(path) if n.startswith("xgameruntime") and n.endswith(".cpp")) - if not names: - raise FileNotFoundError(2, "no xgameruntime*.cpp in the folder", path) - texts = [] - for n in names: - with open(os.path.join(path, n), encoding="utf-8", errors="replace") as f: - texts.append(f.read()) - return "\n".join(texts) - with open(path, encoding="utf-8", errors="replace") as f: - return f.read() - - -def served_classes(source: str) -> dict[str, str]: - """{class id: constant name} for each `constexpr GUID kClass = {...}` in the runtime shim's source.""" - out = {} - for m in GUID_CONSTANT.finditer(source): - try: - tail = [int(x, 16) for x in m.group(5).split(",") if x.strip()] - if len(tail) != 8: - continue - guid = uuid.UUID(fields=(int(m.group(2), 16), int(m.group(3), 16), int(m.group(4), 16), tail[0], - tail[1], int.from_bytes(bytes(tail[2:]), "big"))) - except ValueError: # not a GUID after all (a value out of range, a non-hex byte) - continue - out[str(guid)] = f"k{m.group(1)}Class" - return out - - -# ---- Scanning an image ---- - -class Code: - """The image's executable sections and .pdata function bounds.""" - - def __init__(self, img: PeImage): - self.img = img - self.sections = [] # (rva, bytes): file bytes of each executable section, mapped span only - for s in img.sections: - if s["exec"]: - data = img.section_data(s) - span = s["vsize"] or s["rawsize"] - self.sections.append((s["rva"], data[:span])) - self.begins, self.ends = [], [] - rva, size = img.directory(DIR_EXCEPTION) - at = img.offset(rva) if rva and size >= 12 else None - if at is not None: - count = min(size, len(img.data) - at) // 12 - entries = sorted((b, e) for b, e, _ in struct.iter_unpack(" b) - self.begins = [b for b, _ in entries] - self.ends = [e for _, e in entries] - - def view(self, rva: int): - """(bytes, section rva) of the executable section holding rva, or (None, 0).""" - for base, data in self.sections: - if base <= rva < base + len(data): - return data, base - return None, 0 - - def decode(self, rva: int) -> Insn | None: - data, base = self.view(rva) - return None if data is None else decode(data, rva - base, base) - - def function(self, rva: int) -> tuple[int, int] | None: - k = bisect.bisect_right(self.begins, rva) - 1 - if k >= 0 and self.begins[k] <= rva < self.ends[k]: - return self.begins[k], self.ends[k] - return None - - def run(self, start: int, stop: int) -> list[Insn] | None: - """The instructions from start up to stop, or None when decoding doesn't land on stop exactly.""" - out = [] - rva = start - while rva < stop: - i = self.decode(rva) - if i is None: - return None - out.append(i) - rva = i.end - return out if rva == stop else None - - -def guid_at(img: PeImage, rva: int) -> str | None: - at = img.offset(rva) - if at is None or at + 16 > len(img.data): - return None - return str(uuid.UUID(bytes_le=bytes(img.data[at:at + 16]))) - - -def find_ids(img: PeImage, ids: set[str]) -> dict[int, str]: - """{rva: id} for every in-memory copy of a known id in the data sections, or in the code sections when the data - sections have none (a linker can merge .rdata into .text).""" - found = {} - patterns = {guid_bytes(g): g for g in ids} - for code in (False, True): - for s in img.sections: - if s["exec"] != code: - continue - data = img.section_data(s)[:s["vsize"] or s["rawsize"]] - for pattern, guid in patterns.items(): - at = data.find(pattern) - while at >= 0: - found[s["rva"] + at] = guid - at = data.find(pattern, at + 1) - if found: - break - return found - - -LEA_RIP = re.compile(rb"[\x48\x4c]\x8d[\x05\x0d\x15\x1d\x25\x2d\x35\x3d]") - - -def lea_sites(code: Code, targets: dict[int, str]): - """RVAs of `lea r64,[rip+x]` instructions whose x is one of targets.""" - for base, data in code.sections: - for m in LEA_RIP.finditer(data): - at = m.start() - if at + 7 > len(data): - break - if base + at + 7 + struct.unpack_from(" dict[int, int]: - """{function start: references} for the thunk functions at `starts`: calls, tail jumps, RIP-relative address - loads and 8-byte pointers in data, each also through an incremental-link `jmp` stub (a jmp to the function from - outside every .pdata function). A reference from inside another of these functions counts only when that one - is referenced itself (every thunk calls the XThreadAssertNotTimeSensitive thunk, live or not). 0 means nothing - that is reached reaches it.""" - def source_function(source: int) -> int | None: - func = code.function(source) - return func[0] if func else None - - stubs: dict[int, int] = {} - outside = dict.fromkeys(starts, 0) - inside: dict[int, set[int]] = {s: set() for s in starts} - - def add(func: int, source: int | None) -> None: - if source in inside and source != func: - inside[func].add(source) - elif source not in inside: - outside[func] += 1 - - for source, target in branches(code, b"\xe9"): - if target in outside: - func = source_function(source) - if func is None: - stubs[source] = target # not inside any function: an incremental-link stub - else: - add(target, func) # a tail call - owner = {s: s for s in starts} | stubs - for source, target in branches(code, b"\xe8"): - if target in owner: - add(owner[target], source_function(source)) - for base, data in code.sections: - for m in LEA_RIP.finditer(data): - at = m.start() - if at + 7 <= len(data): - func = owner.get(base + at + 7 + struct.unpack_from(" 0) - if outside[func] + live != count[func]: - count[func] = outside[func] + live - changed = True - return count - - -def call_after(code: Code, lea_rva: int) -> Insn | None: - """The first call within LEA_TO_CALL instructions of an id's lea, unless control flow leaves first.""" - rva = lea_rva - for _ in range(LEA_TO_CALL): - i = code.decode(rva) - if i is None or i.ends_flow(): - return None - if i.is_call(): - return i - rva = i.end - return None - - -def call_arguments(code: Code, call: int) -> list[int | None]: - """The RIP-relative addresses passed in rcx, rdx, r8 and r9 to the call at `call`, in that order (None for a - register that holds none). The instructions before it are decoded from its function's start when .pdata covers - it and the start is near; else (or when that finds none) from each byte in BACK_WINDOW from which decoding lands - on the call, the first run that loads an address into rcx or rdx winning.""" - func = code.function(call) - starts = [func[0]] if func and call - func[0] <= 4096 else [] - starts += range(max(func[0] if func else 0, call - BACK_WINDOW), call) - for start in starts: - run = code.run(start, call) - if run is not None: - found = argument_addresses(run) - if found[0] is not None or found[1] is not None: - return found - return [None] * 4 - - -def argument_addresses(run: list[Insn]) -> list[int | None]: - """The RIP-relative addresses in rcx, rdx, r8 and r9 at the end of `run` (None where there isn't one).""" - state: dict[int, int] = {} - for i in run: - if i.is_call(): - for r in VOLATILE: - state.pop(r, None) - continue - if i.ends_flow(): - state.clear() - continue - if i.op == 0x8D and i.wide and i.base == RIP: - state[i.reg] = i.target - continue - if i.wide and i.mod == 3 and i.op in (0x8B, 0x89): # mov r64, r64 - dst, src = (i.reg, i.rm) if i.op == 0x8B else (i.rm, i.reg) - if src in state: - state[dst] = state[src] - else: - state.pop(dst, None) - continue - for r in writes(i): - state.pop(r, None) - return [state.get(r) for r in (RCX, RDX, R8, R9)] - - -def slot_calls(code: Code, start: int, helpers: set) -> tuple[list[tuple[int, int, int]], set]: - """[(slot, estimated argument count, call rva)] of the vtable calls after a helper call returns at `start`, and - the keys of the direct calls that dispatched them (the CFG dispatch routine).""" - func = code.function(start) - stop = func[1] if func else start + NO_PDATA_WINDOW - vtables: set[int] = set() # registers holding a vtable pointer - methods: dict[int, int] = {} # register -> slot of the method pointer it holds - written: set[int] = set() # argument registers written since the last call - stack: set[int] = set() # stack arguments stored since the last call - found, dispatchers = [], set() - rva = start - while rva < stop: - i = code.decode(rva) - if i is None: - break - rva = i.end - if i.is_call(): - slot = None - if i.op == 0xFF and i.mod != 3 and i.base in vtables and i.index is None and i.disp % 8 == 0: - slot = i.disp // 8 # call [vtable+disp] - elif i.op == 0xFF and i.mod == 3: - slot = methods.get(i.rm) # call reg - elif i.call_key() is not None and RAX in methods: - slot = methods[RAX] # CFG: call __guard_dispatch_icall (target in rax) - dispatchers.add(i.call_key()) - if slot is None and i.call_key() in helpers: - break # the next thunk's helper call - if slot is not None: - args = max([ARG_INDEX[r] for r in written if r in ARG_INDEX] + list(stack) + [0]) - found.append((slot, args, i.rva)) - if slot == RELEASE: - break - for r in VOLATILE: - vtables.discard(r) - methods.pop(r, None) - written.clear() - stack.clear() - continue - if i.ends_flow(): - if not func: - break - vtables.clear() - methods.clear() - continue - k = stack_argument(i) - if k is not None: - stack.add(k) - dests = writes(i) - written.update(dests) - load = (i.op == 0x8B and i.wide and i.mod != 3 and i.index is None - and i.base is not None and i.base not in (RIP, RSP)) - from_vtable = load and i.base in vtables and i.disp >= 0 and i.disp % 8 == 0 - copy = i.wide and i.mod == 3 and i.op in (0x8B, 0x89) # mov r64, r64 carries what its source held - if copy: - src = i.rm if i.op == 0x8B else i.reg - src_vtable, src_method = src in vtables, methods.get(src) - for r in dests: - vtables.discard(r) - methods.pop(r, None) - if copy: - if src_vtable: - vtables.add(dests[0]) - if src_method is not None: - methods[dests[0]] = src_method - elif from_vtable: - methods[i.reg] = i.disp // 8 # mov r, [vtable+disp] - elif load and i.disp == 0: - vtables.add(i.reg) # mov r, [object] - return found, dispatchers - - -def scan(img: PeImage, table: RuntimeTable) -> dict: - """Thunk sites of the image: {"helpers": [...], "sites": [...], "ids_present": {id: [rva, ...]}}.""" - known = find_ids(img, table.ids()) - present: dict[str, list[int]] = {} - for rva, guid in sorted(known.items()): - present.setdefault(guid, []).append(rva) - result = {"helpers": [], "sites": [], "unmatched": [], "ids_present": present, "pdata_functions": 0} - if img.machine != 0x8664: - result["skipped"] = f"{MACHINES.get(img.machine, hex(img.machine))} code is not scanned (x86-64 only)" - return result - code = Code(img) - result["pdata_functions"] = len(code.begins) - - # A helper: a call fed by a known id's lea and followed by a vtable call past IUnknown. - candidates: dict[int, Insn] = {} - for lea in lea_sites(code, known): - call = call_after(code, lea) - key = call.call_key() if call else None - if key is not None: - candidates.setdefault(call.rva, call) - helpers, dispatchers = set(), set() - for call in candidates.values(): - calls, used = slot_calls(code, call.end, set()) - dispatchers |= used - if any(slot >= IUNKNOWN_SLOTS for slot, _, _ in calls): - helpers.add(call.call_key()) - helpers -= dispatchers # a CFG dispatch routine is never the helper - result["helpers"] = sorted(helpers) - - near = {t for kind, t in helpers if kind == "rel"} - helper_calls = {source for source, target in branches(code, b"\xe8") if target in near} if near else set() - far = {t for kind, t in helpers if kind == "mem"} - if far: - helper_calls.update(source for source, target in branches(code, b"\xff\x15") if target in far) - - for call_rva in sorted(helper_calls): - call = code.decode(call_rva) - if call is None or call.call_key() not in helpers: - continue - # The class id is the one in rcx, the interface id the one in rdx (the class id when rdx holds none). - rcx, rdx = (None if a is None else guid_at(img, a) for a in call_arguments(code, call_rva)[:2]) - class_id, interface_id = rcx, rdx or rcx - slots = [c for c in slot_calls(code, call.end, helpers)[0] if c[0] >= IUNKNOWN_SLOTS] if rcx else [] - func = code.function(call_rva) - site = {"call": call_rva, "function": func[0] if func else None, "class_id": class_id, - "interface_id": interface_id, "slots": slots} - result["sites" if slots else "unmatched"].append(site) - - starts = {s["function"] for s in result["sites"] if s["function"] is not None} - refs = references(img, code, starts) if starts else {} - for s in result["sites"]: - s["references"] = refs.get(s["function"]) if s["function"] is not None else None - return result - - -def ranges(numbers) -> str: - """'3-7, 9, 12-14' for [3, 4, 5, 6, 7, 9, 12, 13, 14].""" - out, run = [], [] - for n in sorted(set(numbers)): - if run and n == run[-1] + 1: - run.append(n) - continue - if run: - out.append(f"{run[0]}-{run[-1]}" if len(run) > 1 else str(run[0])) - run = [n] - if run: - out.append(f"{run[0]}-{run[-1]}" if len(run) > 1 else str(run[0])) - return ", ".join(out) - - -def report(path: str, table: RuntimeTable, served: dict[str, str] | None) -> dict: - """The JSON report of one image. Raises PeFormatError or OSError when it can't be read.""" - with open(path, "rb") as f: - data = f.read() - try: - img = PeImage(data) - found = scan(img, table) - except struct.error as e: - raise PeFormatError(f"truncated or corrupt table: {e}") from None - cut = [s["name"] for s in img.sections if s["rawsize"] and s["rawptr"] + s["rawsize"] > len(data)] - - classes: dict[str, dict] = {} - for site in found["sites"]: - cid, iid = site["class_id"], site["interface_id"] - refs = site["references"] - cls = classes.setdefault(cid, { - "class": table.class_of(cid), "class_id": cid, - "served": None if served is None else cid in served, - "thunks": 0, "referenced_thunks": 0, "interfaces": {}}) - cls["thunks"] += 1 - if cls["referenced_thunks"] is not None: - cls["referenced_thunks"] = None if refs is None else cls["referenced_thunks"] + (refs > 0) - names_from = table.interface_for(iid) - iface = cls["interfaces"].setdefault(iid, { - "interface": table.label(iid), "interface_id": iid, "slots_named_from": names_from, - "without_layout": table.slot_table(names_from)[1] if names_from else [], "thunks": 0, "slots": {}}) - iface["thunks"] += 1 - where = f"{site['function'] if site['function'] is not None else site['call']:#x}" - for slot, args, _ in site["slots"]: - method, via = table.method(names_from, slot) - entry = iface["slots"].setdefault(slot, {"slot": slot, "method": method, "named_from": via, - "args_estimate": set(), "thunk_rvas": {}}) - entry["args_estimate"].add(args) - entry["thunk_rvas"][where] = refs - - out_classes = [] - for cid, cls in sorted(classes.items(), key=lambda kv: (kv[1]["class"] or "~", kv[0])): - ifaces = [] - for iface in sorted(cls["interfaces"].values(), key=lambda i: i["interface"]): - slots = [] - for _, s in sorted(iface["slots"].items()): - refs = list(s["thunk_rvas"].values()) - slots.append(dict(s, args_estimate=sorted(s["args_estimate"]), thunk_rvas=sorted(s["thunk_rvas"]), - referenced=None if None in refs else sum(r > 0 for r in refs))) - known = all(s["referenced"] is not None for s in slots) - ifaces.append(dict(iface, slots=slots, slot_list=ranges(s["slot"] for s in slots), - referenced_slot_list=ranges(s["slot"] for s in slots if s["referenced"]) - if known else None)) - out_classes.append(dict(cls, interfaces=ifaces)) - - reached = {table.class_of(c) for c in classes} | set(classes) - unreached = [] - for name, cls in sorted(table.classes.items()): - if name in reached: - continue - ids = [cls["id"]] + [i["id"] for i in table.interfaces.values() if i["class"] == name] - hits = [{"id": g, "names": table.label(g), "copies": len(found["ids_present"][g])} - for g in dict.fromkeys(ids) if g in found["ids_present"]] - if hits: - unreached.append({"class": name, "class_id": cls["id"], "ids": hits}) - - unmatched = [{"call": f"{s['call']:#x}", "class": table.class_of(s["class_id"]) if s["class_id"] else None, - "class_id": s["class_id"], "interface_id": s["interface_id"]} for s in found["unmatched"]] - refs = [s["references"] for s in found["sites"]] - return { - "file": os.path.basename(path), - "size": len(data), - "machine": MACHINES.get(img.machine, hex(img.machine)), - "is_dll": bool(img.characteristics & 0x2000), - "pdata_functions": found["pdata_functions"], - "cut_off_sections": cut, - "skipped": found.get("skipped"), - "helpers": [f"{kind} {rva:#x}" for kind, rva in found["helpers"]], - "thunks": len(found["sites"]), - "referenced_thunks": None if None in refs else sum(r > 0 for r in refs), - "classes": out_classes, - "helper_calls_without_slot_call": unmatched, - "unreached_classes": unreached, - } - - -def served_text(flag) -> str: - return {True: "served by the runtime", False: "NOT served by the runtime", None: "served: unknown"}[flag] - - -def referenced_text(count, total) -> str: - if count is None: - return "references unknown" - if count == total: - return "referenced" - return "unreferenced" if count == 0 else f"{count} referenced" - - -def to_text(r: dict) -> str: - kind = "DLL" if r["is_dll"] else "EXE" - out = [f"== {r['file']} ({r['machine']} {kind}, {r['size']:,} bytes, {r['pdata_functions']:,} .pdata functions)"] - if r["cut_off_sections"]: - out.append(f"WARNING: cut off inside {', '.join(r['cut_off_sections'])}: the file ends before the section " - "data, so this report is incomplete") - if r["skipped"]: - out.append(r["skipped"]) - out.append(f"QueryApiImpl helper(s): {', '.join(r['helpers']) or 'none found'}; {r['thunks']} thunk(s) reach " - f"{len(r['classes'])} runtime class(es)") - if r["thunks"]: - if r["referenced_thunks"] is None: - out.append("References to the thunks are unknown (no .pdata function bounds).") - else: - out.append(f"{r['referenced_thunks']} of the {r['thunks']} thunks are referenced (called, jumped to, " - "address taken or stored) in this image; an unreferenced one is present but nothing in the " - "image reaches it (an incremental link does not remove unreferenced functions).") - out.append("args~N: the argument count after `this`, estimated from the registers and stack slots written " - "before the call.") - width = max([len(s["method"] or "unknown") + (len(s["named_from"]) + 7 if s["named_from"] else 0) - for c in r["classes"] for i in c["interfaces"] for s in i["slots"]] + [40]) - for cls in r["classes"]: - out.append("") - out.append(f"{cls['class'] or 'unknown class'} {cls['class_id']} {served_text(cls['served'])} " - f"{cls['thunks']} thunk(s), {referenced_text(cls['referenced_thunks'], cls['thunks'])}") - for iface in cls["interfaces"]: - names = iface["slots_named_from"] - source = "" if names is None or names in iface["interface"].split("/") else f", slots named from {names}" - out.append(f" interface {iface['interface']} {iface['interface_id']}{source}: " - f"slots {iface['slot_list']}") - if iface["without_layout"]: - out.append(f" (no documented layout for {', '.join(iface['without_layout'])}: its own methods, " - "if any, are named in its base's list; slots past the list are unknown)") - if iface["interface_id"] != cls["class_id"]: - out.append(" (requested with an interface id other than the class id)") - for s in iface["slots"]: - name = s["method"] or "unknown" - if s["named_from"]: - name += f" (from {s['named_from']})" - args = "/".join(str(a) for a in s["args_estimate"]) - out.append(f" slot {s['slot']:>3} {name:<{width}} args~{args:<4} {len(s['thunk_rvas'])} thunk(s), " - f"{referenced_text(s['referenced'], len(s['thunk_rvas']))}") - todo = [c for c in r["classes"] if c["served"] is not True] - if todo: - out.append("") - out.append("Not served by the runtime (class as interface: slots called; the referenced ones):" - if all(c["served"] is False for c in todo) else - "Served status unknown (class as interface: slots called; the referenced ones):") - for c in todo: - for iface in c["interfaces"]: - ref = iface["referenced_slot_list"] - ref = "unknown" if ref is None else (ref or "none") - out.append(f" {c['class'] or c['class_id']} as {iface['interface']}: {iface['slot_list']}; " - f"referenced: {ref}") - if r["helper_calls_without_slot_call"]: - out.append("") - out.append("Helper calls not followed to a slot (no class id read from rcx, or no slot call found after " - f"them): {len(r['helper_calls_without_slot_call'])}") - for u in r["helper_calls_without_slot_call"]: - if u["class_id"] is None: - out.append(f" {u['call']} class id not read; interface {u['interface_id'] or 'not read'}") - else: - out.append(f" {u['call']} {u['class'] or 'unknown class'} {u['class_id']} / {u['interface_id']}") - if r["unreached_classes"]: - out.append("") - out.append(f"Known runtime ids present but reached by no thunk ({len(r['unreached_classes'])} classes):") - for u in r["unreached_classes"]: - ids = ", ".join(f"{h['names']} {h['id']}" for h in u["ids"]) - out.append(f" {u['class']}: {ids}") - return "\n".join(out) + "\n" - - -def summary(r: dict) -> str: - todo = [c["class"] or c["class_id"] for c in r["classes"] if c["served"] is False] - live = [c["class"] or c["class_id"] for c in r["classes"] if c["served"] is False and c["referenced_thunks"]] - ref = "?" if r["referenced_thunks"] is None else r["referenced_thunks"] - text = (f"{r['file']:<32} thunks={r['thunks']} referenced={ref} classes={len(r['classes'])} " - f"not-served={','.join(todo) or '-'} not-served-referenced={','.join(live) or '-'}") - if r["cut_off_sections"]: - text += " CUT OFF" - return text - - -def main(argv: list[str] | None = None) -> int: - ap = argparse.ArgumentParser(description=__doc__.split("\n\n", 1)[0]) - ap.add_argument("image", nargs="+") - ap.add_argument("--json", action="store_true", help="print JSON instead of text") - ap.add_argument("--out", help="write .gdk_calls.txt and .json here and print a summary line per image") - ap.add_argument("--table", default=DEFAULT_TABLE, help="the class table (default: %(default)s)") - ap.add_argument("--runtime-source", default=DEFAULT_RUNTIME_SOURCE, - help="a shim source, or a folder of xgameruntime*.cpp, whose `constexpr GUID k...Class` ids count " - "as served (default: %(default)s)") - a = ap.parse_args(argv) - - try: - table = RuntimeTable.load(a.table) - except (OSError, ValueError, KeyError, TypeError) as e: - print(f"cannot read the class table {a.table}: {e}", file=sys.stderr) - return 1 - try: - served = served_classes(read_runtime_source(a.runtime_source)) - except OSError as e: - print(f"warning: cannot read {a.runtime_source} ({e.strerror or e}); 'served' is unknown", file=sys.stderr) - served = None - if a.out: - if os.path.isfile(a.out): - print(f"cannot create output directory {a.out}: path is a file, not a directory", file=sys.stderr) - return 1 - try: - os.makedirs(a.out, exist_ok=True) - except OSError as e: - print(f"cannot create output directory {a.out}: {e.strerror or e}", file=sys.stderr) - return 1 - - rc = 0 - reports, used = [], set() - for path in a.image: - try: - r = report(path, table, served) - except (PeFormatError, OSError) as e: - print(f"{path}: not a readable PE image ({e})", file=sys.stderr) - rc = 1 - continue - if r["cut_off_sections"]: - print(f"{path}: the file ends inside {', '.join(r['cut_off_sections'])}; the report is incomplete", - file=sys.stderr) - rc = 1 - reports.append(r) - if not a.out: - continue - name, n = r["file"], 1 - while name.lower() in used: - n += 1 - name = f"{r['file']}-{n}" - used.add(name.lower()) - if n > 1: - print(f"{path}: another input is also named {r['file']}; report written as {name}.gdk_calls.txt/.json", - file=sys.stderr) - stem = os.path.join(a.out, name + ".gdk_calls") - json_path = stem + ".json" - txt_path = stem + ".txt" - inputs = list(a.image) + [a.table] - if os.path.isfile(a.runtime_source): - inputs.append(a.runtime_source) - collision = next( - (out_path for out_path in (json_path, txt_path) - if any(same_report_path(inp, out_path) for inp in inputs)), - None, - ) - if collision: - print(f"{path}: report {collision} would overwrite input file", file=sys.stderr) - rc = 1 - continue - try: - with open(json_path, "w", encoding="utf-8", newline="\n") as f: - json.dump({"table": table.source, **r}, f, indent=1) - f.write("\n") - with open(txt_path, "w", encoding="utf-8", newline="\n") as f: - f.write(to_text(r)) - except OSError as e: - print(f"{path}: cannot write report ({e.strerror or e})", file=sys.stderr) - rc = 1 - continue - print(summary(r)) - - if not a.out: - if a.json: - print(json.dumps({"table": table.source, "images": reports}, indent=1)) - else: - print(f"(class table: {table.source})") - for r in reports: - print() - print(to_text(r), end="") - return rc - - -if __name__ == "__main__": - try: # a redirected stdout is strict ANSI code page under -I; write '?' for what it cannot encode - sys.stdout.reconfigure(errors="replace") - except (AttributeError, ValueError, OSError): - pass - sys.exit(main()) diff --git a/tools/gdk_runtime_classes.json b/tools/gdk_runtime_classes.json deleted file mode 100644 index 16bb0a68e..000000000 --- a/tools/gdk_runtime_classes.json +++ /dev/null @@ -1,986 +0,0 @@ -{ - "classes": { - "XAccessibilityImpl": { - "id": "3e241977-6237-41e9-8559-102c2d9983f1", - "implements": [ - "IXAccessibilityImpl2" - ] - }, - "XAppCaptureImpl": { - "id": "a4f1aee2-4bf1-4485-b008-a7c26d52ac27", - "implements": [ - "IXAppCaptureImpl4" - ] - }, - "XAppCaptureMetadataImpl": { - "id": "186d5592-a72d-45fb-9560-11aed0e6647a", - "implements": [ - "IXAppCaptureMetadataImpl" - ] - }, - "XDisplayImpl": { - "id": "03f0fe74-fdd9-4e5c-b630-f9339c47acc5", - "implements": [ - "IXDisplayImpl" - ] - }, - "XErrorImpl": { - "id": "8ca467f7-22e8-4096-8456-bb8aa13f79d8", - "implements": [ - "IXErrorImpl" - ] - }, - "XGameActivationImpl": { - "id": "7f0fe8b8-e075-49ab-9aa7-a1e065489a9e", - "implements": [ - "IXGameActivationImpl" - ] - }, - "XGameEventImpl": { - "id": "bbfbdcc7-bfe7-409b-a5ca-edf054960b4d", - "implements": [ - "IXGameEventImpl" - ] - }, - "XGameImpl": { - "id": "973a344e-24bf-4d0f-8457-56c534892b29", - "implements": [ - "IXGameImpl3" - ] - }, - "XGameInviteImpl": { - "id": "0651aae2-4012-4077-bf84-8b9097090e2c", - "implements": [ - "IXGameInviteImpl2" - ] - }, - "XGameProtocolImpl": { - "id": "95fd18d2-74dd-4d7c-aa1b-0b51827665d6", - "implements": [ - "IXGameProtocolImpl" - ] - }, - "XGameRuntimeFeatureImpl": { - "id": "8836fe87-edb9-4fe3-8dad-05f0d2cd5b40", - "implements": [ - "IXGameRuntimeFeatureImpl" - ] - }, - "XGameSaveImpl": { - "id": "704c3f58-e629-4cc2-b197-30511b996fe2", - "implements": [ - "IXGameSaveImpl3" - ] - }, - "XGameStreamingImpl": { - "id": "0a2192aa-b2d5-4d58-83be-383b6d80799e", - "implements": [ - "IXGameStreamingImpl3" - ] - }, - "XGameUiImpl": { - "id": "dfcd4649-4ff8-4043-ba07-35d607df98b0", - "implements": [ - "IXGameUiImpl4" - ] - }, - "XLauncherImpl": { - "id": "1b339674-328d-4283-a200-3171f18d3639", - "implements": [ - "IXLauncherImpl" - ] - }, - "XNetworkingImpl": { - "id": "37e56907-2f10-41e8-b72f-36edb185331a", - "implements": [ - "IXNetworkingImpl2" - ] - }, - "XPackageImpl": { - "id": "af406016-e850-4aa8-a88d-2f3dcb9dac7e", - "implements": [ - "IXPackageImpl4" - ] - }, - "XPersistentLocalStorageImpl": { - "id": "f4faf4d4-2d04-4fce-b3e0-474a713a3e84", - "implements": [ - "IXPersistentLocalStorageImpl3" - ] - }, - "XStoreImpl": { - "id": "0dd112ac-7c24-448c-b92b-3960fb5bd30c", - "implements": [ - "IXStoreImpl6" - ] - }, - "XSystemAnalyticsImpl": { - "id": "b884675d-b738-4a9c-815d-9a9a1e0c6c9b", - "implements": [ - "IXSystemAnalyticsImpl" - ] - }, - "XSystemImpl": { - "id": "e349bd1a-fc20-4e40-b99c-4178cc6b409f", - "implements": [ - "IXSystemImpl5" - ] - }, - "XThreadingImpl": { - "id": "073b7dcb-1fcf-4030-94be-e3c9eb623428", - "implements": [ - "IXThreadingImpl" - ] - }, - "XUserDeviceImpl": { - "id": "7d824997-10dc-45ab-86b7-2737767c0bf1", - "implements": [ - "IXUserDeviceImpl2" - ] - }, - "XUserImpl": { - "id": "01acd177-91f9-4763-a38e-ccbb55ce32e0", - "implements": [ - "IXUserImpl6", - "IXUserGamertagImpl" - ] - } - }, - "interfaces": { - "IXAccessibilityImpl": { - "class": "XAccessibilityImpl", - "id": "3e241977-6237-41e9-8559-102c2d9983f1", - "inherits": null, - "methods": [ - "XClosedCaptionGetProperties", - "XClosedCaptionSetEnabled", - "XHighContrastGetMode", - "XSpeechToTextSetPositionHint", - "XSpeechToTextSendString", - "XSpeechSynthesizerEnumerateInstalledVoices", - "XSpeechSynthesizerCreate", - "XSpeechSynthesizerCloseHandle", - "XSpeechSynthesizerSetDefaultVoice", - "XSpeechSynthesizerSetCustomVoice", - "XSpeechSynthesizerCreateStreamFromText", - "XSpeechSynthesizerCloseStreamHandle", - "XSpeechSynthesizerGetStreamDataSize", - "XSpeechSynthesizerGetStreamData", - "XSpeechToTextBeginHypothesisString", - "XSpeechToTextUpdateHypothesisString", - "XSpeechToTextFinalizeHypothesisString", - "XSpeechToTextCancelHypothesisString", - "XSpeechSynthesizerCreateStreamFromSsml" - ] - }, - "IXAccessibilityImpl2": { - "class": "XAccessibilityImpl", - "id": "d722b373-8c4d-4692-9e51-d6ad9b37aa7d", - "inherits": "IXAccessibilityImpl", - "methods": null - }, - "IXAppCaptureImpl": { - "class": "XAppCaptureImpl", - "id": "a4f1aee2-4bf1-4485-b008-a7c26d52ac27", - "inherits": null, - "methods": [ - "XAppCaptureTakeDiagnosticScreenshot", - "XAppCaptureRecordDiagnosticClip", - "XAppCaptureTakeScreenshot", - "XAppCaptureOpenScreenshotStream", - "XAppCaptureReadScreenshotStream", - "XAppCaptureCloseScreenshotStream", - "XAppCaptureEnableRecord", - "XAppCaptureDisableRecord" - ] - }, - "IXAppCaptureImpl2": { - "class": "XAppCaptureImpl", - "id": "3a949778-772e-4799-bdea-0a6639e96baa", - "inherits": "IXAppCaptureImpl", - "methods": [ - "XAppCaptureGetVideoCaptureSettings", - "XAppCaptureRecordTimespan", - "XAppCaptureReadLocalStream", - "XAppCaptureCloseLocalStream" - ] - }, - "IXAppCaptureImpl3": { - "class": "XAppCaptureImpl", - "id": "2bbca60a-619c-4fe1-812e-fb5c1dbdcf51", - "inherits": "IXAppCaptureImpl2", - "methods": [ - "XAppCaptureStartUserRecord", - "XAppCaptureStopUserRecord" - ] - }, - "IXAppCaptureImpl4": { - "class": "XAppCaptureImpl", - "id": "22e672d7-b4e3-406c-bd50-8f0d25236f9e", - "inherits": "IXAppCaptureImpl3", - "methods": [ - "XAppCaptureCancelUserRecord" - ] - }, - "IXAppCaptureMetadataImpl": { - "class": "XAppCaptureMetadataImpl", - "id": "186d5592-a72d-45fb-9560-11aed0e6647a", - "inherits": null, - "methods": [ - "XAppBroadcastIsAppBroadcasting", - "XAppBroadcastShowUI", - "XAppBroadcastGetStatus", - "XAppBroadcastRegisterIsAppBroadcastingChanged", - "XAppBroadcastUnregisterIsAppBroadcastingChanged", - "XAppCaptureMetadataAddStringEvent", - "XAppCaptureMetadataAddInt32Event", - "XAppCaptureMetadataAddDoubleEvent", - "XAppCaptureMetadataStartStringState", - "XAppCaptureMetadataStartInt32State", - "XAppCaptureMetadataStartDoubleState", - "XAppCaptureMetadataStopState", - "XAppCaptureMetadataStopAllStates", - "XAppCaptureMetadataRemainingStorageBytesAvailable", - "XAppCaptureRegisterMetadataPurged", - "XAppCaptureUnRegisterMetadataPurged" - ] - }, - "IXDisplayImpl": { - "class": "XDisplayImpl", - "id": "35f07670-706e-4bfb-9476-090798c5ebf3", - "inherits": null, - "methods": [ - null, - "XDisplayTryEnableHdrMode" - ] - }, - "IXErrorImpl": { - "class": "XErrorImpl", - "id": "8ca467f7-22e8-4096-8456-bb8aa13f79d8", - "inherits": null, - "methods": [ - null, - "XErrorSetCallback", - "XErrorSetOptions" - ] - }, - "IXGameActivationImpl": { - "class": "XGameActivationImpl", - "id": "2e4f76fe-0fc7-461e-ab4d-a4499434c3cf", - "inherits": null, - "methods": [ - "XGameActivationRegisterForEvent", - "XGameActivationUnregisterForEvent", - "XGameActivationAcceptPendingInvite" - ] - }, - "IXGameEventImpl": { - "class": "XGameEventImpl", - "id": "bbfbdcc7-bfe7-409b-a5ca-edf054960b4d", - "inherits": null, - "methods": [ - "XGameEventWrite" - ] - }, - "IXGameImpl": { - "class": "XGameImpl", - "id": "973a344e-24bf-4d0f-8457-56c534892b29", - "inherits": null, - "methods": [ - "XGameGetXboxTitleId" - ] - }, - "IXGameImpl2": { - "class": "XGameImpl", - "id": "50849859-0ad8-4f81-80e4-5bc78626f852", - "inherits": "IXGameImpl", - "methods": [ - "XLaunchNewGame" - ] - }, - "IXGameImpl3": { - "class": "XGameImpl", - "id": "2549f142-6419-4a06-97b5-931aab7c2f34", - "inherits": "IXGameImpl2", - "methods": [ - "XLaunchRestartOnCrash" - ] - }, - "IXGameInviteImpl": { - "class": "XGameInviteImpl", - "id": "0651aae2-4012-4077-bf84-8b9097090e2c", - "inherits": null, - "methods": [ - "XGameInviteRegisterForEvent", - "XGameInviteUnregisterForEvent" - ] - }, - "IXGameInviteImpl2": { - "class": "XGameInviteImpl", - "id": "014d1cc3-bcfe-41ff-b2f0-e1ef07155828", - "inherits": "IXGameInviteImpl", - "methods": [ - "XGameInviteRegisterForPendingEvent", - "XGameInviteUnregisterForPendingEvent", - "XGameInviteAcceptPendingInvite" - ] - }, - "IXGameProtocolImpl": { - "class": "XGameProtocolImpl", - "id": "026b010c-06c3-4cdd-bbcb-43f229db1cff", - "inherits": null, - "methods": [ - "XGameProtocolRegisterForActivation", - "XGameProtocolUnregisterForActivation" - ] - }, - "IXGameRuntimeFeatureImpl": { - "class": "XGameRuntimeFeatureImpl", - "id": "8836fe87-edb9-4fe3-8dad-05f0d2cd5b40", - "inherits": null, - "methods": [ - "XGameRuntimeIsFeatureAvailable" - ] - }, - "IXGameSaveImpl": { - "class": "XGameSaveImpl", - "id": "704c3f58-e629-4cc2-b197-30511b996fe2", - "inherits": null, - "methods": [ - "XGameSaveInitializeProvider", - "XGameSaveInitializeProviderAsync", - "XGameSaveInitializeProviderResult", - "XGameSaveCloseProvider", - "XGameSaveGetRemainingQuota", - "XGameSaveGetRemainingQuotaAsync", - "XGameSaveGetRemainingQuotaResult", - "XGameSaveDeleteContainer", - "XGameSaveDeleteContainerAsync", - "XGameSaveDeleteContainerResult", - "XGameSaveGetContainerInfo", - "XGameSaveEnumerateContainerInfo", - "XGameSaveEnumerateContainerInfoByName", - "XGameSaveCreateContainer", - "XGameSaveCloseContainer", - "XGameSaveEnumerateBlobInfo", - "XGameSaveEnumerateBlobInfoByName", - "XGameSaveReadBlobData", - "XGameSaveReadBlobDataAsync", - "XGameSaveReadBlobDataResult", - "XGameSaveCreateUpdate", - "XGameSaveCloseUpdate", - "XGameSaveSubmitBlobWrite", - "XGameSaveSubmitBlobDelete", - "XGameSaveSubmitUpdate", - "XGameSaveSubmitUpdateAsync", - "XGameSaveSubmitUpdateResult" - ] - }, - "IXGameSaveImpl2": { - "class": "XGameSaveImpl", - "id": "704c3f58-e629-4cc2-b197-30511b996ee2", - "inherits": "IXGameSaveImpl", - "methods": [ - "XGameSaveFilesGetFolderWithUiAsync", - "XGameSaveFilesGetFolderWithUiResult", - "XGameSaveFilesGetRemainingQuota" - ] - }, - "IXGameSaveImpl3": { - "class": "XGameSaveImpl", - "id": "1bfff3af-f14a-40a3-8e35-9ada906593f9", - "inherits": "IXGameSaveImpl2", - "methods": null - }, - "IXGameStreamingImpl": { - "class": "XGameStreamingImpl", - "id": "8aff07f5-a1bf-4db8-80a5-31cca0de51b7", - "inherits": null, - "methods": [ - "XGameStreamingInitialize", - "XGameStreamingUninitialize", - "XGameStreamingIsStreaming", - "XGameStreamingRegisterClientPropertiesChanged", - "XGameStreamingUnregisterClientPropertiesChanged", - "XGameStreamingGetStreamPhysicalDimensions", - "XGameStreamingGetClientCount", - "XGameStreamingGetClients", - "XGameStreamingGetConnectionState", - "XGameStreamingRegisterConnectionStateChanged", - "XGameStreamingUnregisterConnectionStateChanged", - "XGameStreamingGetStreamAddedLatency", - "XGameStreamingGetServerLocationNameSize", - "XGameStreamingGetServerLocationName", - "XGameStreamingHideTouchControls", - "XGameStreamingShowTouchControlLayout", - "XGameStreamingHideTouchControlsOnClient", - "XGameStreamingShowTouchControlLayoutOnClient", - "XGameStreamingIsTouchInputEnabled", - "XGameStreamingGetLastFrameDisplayed", - "XGameStreamingGetAssociatedFrame", - "XGameStreamingGetGamepadPhysicality", - "XGameStreamingUpdateTouchControlsState", - "XGameStreamingUpdateTouchControlsStateOnClient", - "XGameStreamingShowTouchControlsWithStateUpdate", - "XGameStreamingShowTouchControlsWithStateUpdateOnClient", - "XGameStreamingGetTouchBundleVersionNameSize", - "XGameStreamingGetTouchBundleVersion", - "XGameStreamingGetClientIPAddress" - ] - }, - "IXGameStreamingImpl2": { - "class": "XGameStreamingImpl", - "id": "5f5e5169-746c-4001-ad1c-da728d01c9eb", - "inherits": "IXGameStreamingImpl", - "methods": [ - "XGameStreamingGetSessionId" - ] - }, - "IXGameStreamingImpl3": { - "class": "XGameStreamingImpl", - "id": "57786622-6605-46d0-b917-0f22bbcd9c52", - "inherits": "IXGameStreamingImpl2", - "methods": [ - "XGameStreamingGetDisplayDetails", - "XGameStreamingSetResolution" - ] - }, - "IXGameUiImpl": { - "class": "XGameUiImpl", - "id": "6eeaa73e-9669-43ad-a2c7-d0da4e1f50a1", - "inherits": null, - "methods": [ - "XGameUiShowMessageDialogAsync", - "XGameUiShowMessageDialogResult", - "XGameUiShowSendGameInviteAsync", - "XGameUiShowSendGameInviteResult", - "XGameUiShowPlayerProfileCardAsync", - "XGameUiShowPlayerProfileCardResult", - "XGameUiShowAchievementsAsync", - "XGameUiShowAchievementsResult", - "XGameUiShowPlayerPickerAsync", - "XGameUiShowPlayerPickerResultCount", - "XGameUiShowPlayerPickerResult", - "XGameUiShowErrorDialogAsync", - "XGameUiShowErrorDialogResult", - "XGameUiSetNotificationPositionHint", - "XGameUiShowTextEntryAsync", - "XGameUiShowTextEntryResultSize", - "XGameUiShowTextEntryResult", - null, - null, - null, - null, - "XGameUiShowWebAuthenticationAsync", - "XGameUiShowWebAuthenticationResultSize", - "XGameUiShowWebAuthenticationResult", - "XGameUiShowWebAuthenticationWithOptionsAsync", - null, - null - ] - }, - "IXGameUiImpl2": { - "class": "XGameUiImpl", - "id": "36a03122-9ea3-4a3a-a8a4-899cfd85d7db", - "inherits": "IXGameUiImpl", - "methods": [ - "XGameUiShowMultiplayerActivityGameInviteAsync", - "XGameUiShowMultiplayerActivityGameInviteResult", - null, - null, - "XGameUiTextEntryOpen", - "XGameUiTextEntryClose", - "XGameUiTextEntryGetState", - "XGameUiTextEntryGetExtents", - "XGameUiTextEntryUpdatePositionHint", - "XGameUiTextEntryUpdateVisibility" - ] - }, - "IXGameUiImpl3": { - "class": "XGameUiImpl", - "id": "ade7eba1-2093-42ce-a544-a523a66790e0", - "inherits": "IXGameUiImpl2", - "methods": [ - "XGameUiShowStateShareAsync", - "XGameUiShowStateShareResult" - ] - }, - "IXGameUiImpl4": { - "class": "XGameUiImpl", - "id": "eaf669df-5542-4590-99a3-8dc061f837cc", - "inherits": "IXGameUiImpl3", - "methods": [ - "XGameUiSetUiCallbacks", - "XGameUiSetMessageDialogUiResponse", - "XGameUiSetPlayerPickerUiResponse", - "XGameUiSetTextEntryUiResponse", - "XGameUiSetPlayerProfileCardUiResponse", - "XGameUiSetSendGameInviteUiResponse", - "XGameUiSetAchievementsUiResponse", - "XGameUiSetMultiplayerActivityGameInviteUiResponse", - "XGameUiSetErrorDialogUiResponse" - ] - }, - "IXLauncherImpl": { - "class": "XLauncherImpl", - "id": "1b339674-328d-4283-a200-3171f18d3639", - "inherits": null, - "methods": [ - "XLaunchUri", - "XDisplayAcquireTimeoutDeferral", - "XDisplayCloseTimeoutDeferralHandle" - ] - }, - "IXNetworkingImpl": { - "class": "XNetworkingImpl", - "id": "37e56907-2f10-41e8-b72f-36edb185331a", - "inherits": null, - "methods": [ - "XNetworkingQueryPreferredLocalUdpMultiplayerPort", - "XNetworkingQueryPreferredLocalUdpMultiplayerPortAsync", - "XNetworkingQueryPreferredLocalUdpMultiplayerPortAsyncResult", - "XNetworkingRegisterPreferredLocalUdpMultiplayerPortChanged", - "XNetworkingUnregisterPreferredLocalUdpMultiplayerPortChanged", - "XNetworkingQuerySecurityInformationForUrlAsync", - "XNetworkingQuerySecurityInformationForUrlAsyncResultSize", - "XNetworkingQuerySecurityInformationForUrlAsyncResult", - "XNetworkingQuerySecurityInformationForUrlUtf16Async", - "XNetworkingQuerySecurityInformationForUrlUtf16AsyncResultSize", - "XNetworkingQuerySecurityInformationForUrlUtf16AsyncResult", - "XNetworkingVerifyServerCertificate", - "XNetworkingGetConnectivityHint", - "XNetworkingRegisterConnectivityHintChanged", - "XNetworkingUnregisterConnectivityHintChanged" - ] - }, - "IXNetworkingImpl2": { - "class": "XNetworkingImpl", - "id": "bf2346b2-39af-4658-b5ea-44713c7e83b3", - "inherits": "IXNetworkingImpl", - "methods": [ - "XNetworkingQueryConfigurationSetting", - "XNetworkingSetConfigurationSetting", - "XNetworkingQueryStatistics" - ] - }, - "IXPackageImpl": { - "class": "XPackageImpl", - "id": "3720de07-e8e4-44a3-ad32-b359e8adbe55", - "inherits": null, - "methods": [ - "XPackageGetCurrentProcessPackageIdentifier", - "XPackageIsPackagedProcess", - "XPackageCreateInstallationMonitor", - "XPackageCloseInstallationMonitorHandle", - "XPackageGetInstallationProgress", - "XPackageUpdateInstallationMonitor", - "XPackageRegisterInstallationProgressChanged", - "XPackageUnregisterInstallationProgressChanged", - "XPackageGetUserLocale", - "XPackageFindChunkAvailability", - "XPackageEnumerateChunkAvailability", - "XPackageChangeChunkInstallOrder", - "XPackageInstallChunks", - "XPackageInstallChunksAsync", - "XPackageInstallChunksResult", - "XPackageEstimateDownloadSize", - "XPackageUninstallChunks", - null, - null, - "XPackageUnregisterPackageInstalled", - "XPackageMount", - "XPackageGetMountPathSize", - "XPackageGetMountPath", - "XPackageCloseMountHandle", - null, - "XPackageEnumeratePackages", - "XPackageRegisterPackageInstalled", - "XPackageGetWriteStats", - null, - "XPackageUninstallUWPInstance", - "XPackageEnumerateFeatures", - "XPackageUninstallPackage" - ] - }, - "IXPackageImpl2": { - "class": "XPackageImpl", - "id": "f92d8712-2b27-4d8a-bf01-11a6f8e3eb42", - "inherits": "IXPackageImpl", - "methods": [ - "XPackageEnumeratePackages", - "XPackageRegisterPackageInstalled", - "XPackageMountWithUiAsync", - "XPackageMountWithUiResult" - ] - }, - "IXPackageImpl3": { - "class": "XPackageImpl", - "id": "e2a4734b-2f4a-456d-aa8f-d065e04fb209", - "inherits": "IXPackageImpl2", - "methods": [ - "XPackageEnumeratePackages", - "XPackageRegisterPackageInstalled" - ] - }, - "IXPackageImpl4": { - "class": "XPackageImpl", - "id": "0b9d556e-ab70-43f4-baa0-9999ac4cb040", - "inherits": "IXPackageImpl3", - "methods": [ - "XPackageGetPackageKind" - ] - }, - "IXPersistentLocalStorageImpl": { - "class": "XPersistentLocalStorageImpl", - "id": "f4faf4d4-2d04-4fce-b3e0-474a713a3e84", - "inherits": null, - "methods": [ - "XPersistentLocalStorageGetPathSize", - "XPersistentLocalStorageGetPath", - "XPersistentLocalStorageGetSpaceInfo", - "XPersistentLocalStoragePromptUserForSpaceAsync", - "XPersistentLocalStoragePromptUserForSpaceResult" - ] - }, - "IXPersistentLocalStorageImpl2": { - "class": "XPersistentLocalStorageImpl", - "id": "d29411df-0794-4553-8b27-95fc02d0f75d", - "inherits": "IXPersistentLocalStorageImpl", - "methods": null - }, - "IXPersistentLocalStorageImpl3": { - "class": "XPersistentLocalStorageImpl", - "id": "41a4e10c-5a7e-41d9-8c37-37bde62a07d6", - "inherits": "IXPersistentLocalStorageImpl2", - "methods": [ - "XPersistentLocalStorageMountForPackage" - ] - }, - "IXStoreImpl": { - "class": "XStoreImpl", - "id": "0dd112ac-7c24-448c-b92b-3960fb5bd30c", - "inherits": null, - "methods": [ - "XStoreCreateContext", - "XStoreCloseContextHandle", - "XStoreQueryAssociatedProductsAsync", - "XStoreQueryAssociatedProductsResult", - "XStoreQueryProductsAsync", - "XStoreQueryProductsResult", - "XStoreQueryEntitledProductsAsync", - "XStoreQueryEntitledProductsResult", - "XStoreQueryProductForCurrentGameAsync", - "XStoreQueryProductForCurrentGameResult", - "XStoreQueryProductForPackageAsync", - "XStoreQueryProductForPackageResult", - "XStoreEnumerateProductsQuery", - "XStoreProductsQueryHasMorePages", - "XStoreProductsQueryNextPageAsync", - "XStoreProductsQueryNextPageResult", - "XStoreCloseProductsQueryHandle", - "XStoreAcquireLicenseForPackageAsync", - "XStoreAcquireLicenseForPackageResult", - "XStoreIsLicenseValid", - "XStoreCloseLicenseHandle", - "XStoreCanAcquireLicenseForStoreIdAsync", - "XStoreCanAcquireLicenseForStoreIdResult", - "XStoreCanAcquireLicenseForPackageAsync", - "XStoreCanAcquireLicenseForPackageResult", - "XStoreQueryGameLicenseAsync", - "XStoreQueryGameLicenseResult", - "XStoreQueryAddOnLicensesAsync", - "XStoreQueryAddOnLicensesResultCount", - "XStoreQueryAddOnLicensesResult", - "XStoreQueryConsumableBalanceRemainingAsync", - "XStoreQueryConsumableBalanceRemainingResult", - "XStoreReportConsumableFulfillmentAsync", - "XStoreReportConsumableFulfillmentResult", - "XStoreGetUserCollectionsIdAsync", - "XStoreGetUserCollectionsIdResultSize", - "XStoreGetUserCollectionsIdResult", - "XStoreGetUserPurchaseIdAsync", - "XStoreGetUserPurchaseIdResultSize", - "XStoreGetUserPurchaseIdResult", - "XStoreQueryLicenseTokenAsync", - "XStoreQueryLicenseTokenResultSize", - "XStoreQueryLicenseTokenResult", - null, - null, - null, - "XStoreShowPurchaseUIAsync", - "XStoreShowPurchaseUIResult", - "XStoreShowRateAndReviewUIAsync", - "XStoreShowRateAndReviewUIResult", - "XStoreShowRedeemTokenUIAsync", - "XStoreShowRedeemTokenUIResult", - "XStoreQueryGameAndDlcPackageUpdatesAsync", - "XStoreQueryGameAndDlcPackageUpdatesResultCount", - "XStoreQueryGameAndDlcPackageUpdatesResult", - "XStoreDownloadPackageUpdatesAsync", - "XStoreDownloadPackageUpdatesResult", - "XStoreDownloadAndInstallPackageUpdatesAsync", - "XStoreDownloadAndInstallPackageUpdatesResult", - "XStoreDownloadAndInstallPackagesAsync", - "XStoreDownloadAndInstallPackagesResultCount", - "XStoreDownloadAndInstallPackagesResult", - "XStoreQueryPackageIdentifier", - "XStoreRegisterGameLicenseChanged", - "XStoreUnregisterGameLicenseChanged", - "XStoreRegisterPackageLicenseLost", - "XStoreUnregisterPackageLicenseLost" - ] - }, - "IXStoreImpl2": { - "class": "XStoreImpl", - "id": "60b09f4e-1b85-45b1-826c-169118e230e1", - "inherits": "IXStoreImpl", - "methods": [ - "XStoreIsAvailabilityPurchasable" - ] - }, - "IXStoreImpl3": { - "class": "XStoreImpl", - "id": "2d42fea5-e71d-4b76-97cd-c50afbb3ae5d", - "inherits": "IXStoreImpl2", - "methods": [ - "XStoreAcquireLicenseForDurablesAsync", - "XStoreAcquireLicenseForDurablesResult" - ] - }, - "IXStoreImpl4": { - "class": "XStoreImpl", - "id": "de3dbdd4-0b37-4bdb-a10e-acf3a354d06a", - "inherits": "IXStoreImpl3", - "methods": [ - "XStoreShowAssociatedProductsUIAsync", - "XStoreShowAssociatedProductsUIResult", - "XStoreShowProductPageUIAsync", - "XStoreShowProductPageUIResult" - ] - }, - "IXStoreImpl5": { - "class": "XStoreImpl", - "id": "5c48dedf-0b67-4492-a4b5-6829b8e796e1", - "inherits": "IXStoreImpl4", - "methods": [ - "XStoreQueryAssociatedProductsForStoreIdAsync", - "XStoreQueryAssociatedProductsForStoreIdResult", - "XStoreQueryPackageUpdatesAsync", - "XStoreQueryPackageUpdatesResultCount", - "XStoreQueryPackageUpdatesResult" - ] - }, - "IXStoreImpl6": { - "class": "XStoreImpl", - "id": "b09d803c-2414-4a05-82c6-66dfdc9e9a44", - "inherits": "IXStoreImpl5", - "methods": [ - "XStoreShowGiftingUIAsync", - "XStoreShowGiftingUIResult" - ] - }, - "IXSystemAnalyticsImpl": { - "class": "XSystemAnalyticsImpl", - "id": "b884675d-b738-4a9c-815d-9a9a1e0c6c9b", - "inherits": null, - "methods": [ - "XSystemGetAnalyticsInfo" - ] - }, - "IXSystemImpl": { - "class": "XSystemImpl", - "id": "e349bd1a-fc20-4e40-b99c-4178cc6b409f", - "inherits": null, - "methods": [ - "XSystemGetConsoleId", - "XSystemGetXboxLiveSandboxId", - "XSystemGetAppSpecificDeviceId" - ] - }, - "IXSystemImpl2": { - "class": "XSystemImpl", - "id": "6fd71f09-7513-49f0-89bc-bfaf5df6f852", - "inherits": "IXSystemImpl", - "methods": null - }, - "IXSystemImpl3": { - "class": "XSystemImpl", - "id": "67ce4bfc-b1d1-4ac7-bc3a-cb9219a97a85", - "inherits": "IXSystemImpl2", - "methods": [ - "XSystemHandleTrack", - "XSystemIsHandleValid" - ] - }, - "IXSystemImpl4": { - "class": "XSystemImpl", - "id": "dadc2895-34b0-4ef5-a83e-45114d629b80", - "inherits": "IXSystemImpl3", - "methods": [ - "XSystemAllowFullDownloadBandwidth" - ] - }, - "IXSystemImpl5": { - "class": "XSystemImpl", - "id": "1861cf2e-e18b-4834-a9f5-b4a4e6efb4cf", - "inherits": "IXSystemImpl4", - "methods": null - }, - "IXThreadingImpl": { - "class": "XThreadingImpl", - "id": "073b7dcb-1fcf-4030-94be-e3c9eb623428", - "inherits": null, - "methods": [ - "XAsyncGetStatus", - "XAsyncGetResultSize", - "XAsyncCancel", - "XAsyncRun", - "XAsyncBegin", - "XAsyncBeginAlloc", - "XAsyncSchedule", - "XAsyncComplete", - "XAsyncGetResult", - "XTaskQueueCreate", - "XTaskQueueCreateComposite", - "XTaskQueueGetPort", - "XTaskQueueDuplicateHandle", - "XTaskQueueDispatch", - "XTaskQueueCloseHandle", - "XTaskQueueSubmitCallback", - "XTaskQueueSubmitDelayedCallback", - "XTaskQueueRegisterWaiter", - "XTaskQueueUnregisterWaiter", - "XTaskQueueTerminate", - "XTaskQueueRegisterMonitor", - "XTaskQueueUnregisterMonitor", - "XTaskQueueGetCurrentProcessTaskQueue", - "XTaskQueueSetCurrentProcessTaskQueue", - "XThreadSetTimeSensitive", - "XTaskQueueIsEmpty", - "XThreadAssertNotTimeSensitive", - "XThreadIsTimeSensitive" - ] - }, - "IXUserDeviceImpl": { - "class": "XUserDeviceImpl", - "id": "7d824997-10dc-45ab-86b7-2737767c0bf1", - "inherits": null, - "methods": [ - "XUserFindForDevice", - "XUserRegisterForDeviceAssociationChanged", - "XUserUnregisterForDeviceAssociationChanged", - "XUserGetDefaultAudioEndpointUtf16", - "XUserRegisterForDefaultAudioEndpointUtf16Changed", - "XUserUnregisterForDefaultAudioEndpointUtf16Changed", - "XUserFindControllerForUserWithUiAsync", - "XUserFindControllerForUserWithUiResult" - ] - }, - "IXUserDeviceImpl2": { - "class": "XUserDeviceImpl", - "id": "0cc6a956-e7e1-4fdf-9341-9d5da649ebc8", - "inherits": "IXUserDeviceImpl", - "methods": null - }, - "IXUserGamertagImpl": { - "class": "XUserImpl", - "id": "cef4fac0-7676-4a94-a119-4c43f9eb5b74", - "inherits": null, - "methods": [ - "XUserGetGamertag" - ] - }, - "IXUserImpl": { - "class": "XUserImpl", - "id": "01acd177-91f9-4763-a38e-ccbb55ce32e0", - "inherits": null, - "methods": [ - "XUserDuplicateHandle", - "XUserCloseHandle", - "XUserCompare", - "XUserGetMaxUsers", - "XUserAddAsync", - "XUserAddResult", - "XUserGetLocalId", - "XUserFindUserByLocalId", - "XUserGetId", - "XUserFindUserById", - "XUserGetIsGuest", - "XUserGetState", - null, - "XUserGetGamerPictureAsync", - "XUserGetGamerPictureResultSize", - "XUserGetGamerPictureResult", - "XUserGetAgeGroup", - "XUserCheckPrivilege", - "XUserResolvePrivilegeWithUiAsync", - "XUserResolvePrivilegeWithUiResult", - "XUserGetTokenAndSignatureAsync", - "XUserGetTokenAndSignatureResultSize", - "XUserGetTokenAndSignatureResult", - "XUserGetTokenAndSignatureUtf16Async", - "XUserGetTokenAndSignatureUtf16ResultSize", - "XUserGetTokenAndSignatureUtf16Result", - "XUserResolveIssueWithUiAsync", - "XUserResolveIssueWithUiResult", - "XUserResolveIssueWithUiUtf16Async", - "XUserResolveIssueWithUiUtf16Result", - "XUserRegisterForChangeEvent", - "XUserUnregisterForChangeEvent", - "XUserGetSignOutDeferral", - "XUserCloseSignOutDeferralHandle" - ] - }, - "IXUserImpl2": { - "class": "XUserImpl", - "id": "eb9bf948-18dc-4d82-bbcc-40e0a809c4c0", - "inherits": "IXUserImpl", - "methods": [ - "XUserAddByIdWithUiAsync", - "XUserAddByIdWithUiResult" - ] - }, - "IXUserImpl3": { - "class": "XUserImpl", - "id": "1bf2f8c5-d507-4e52-bb05-f726d0e71161", - "inherits": "IXUserImpl2", - "methods": [ - "XUserGetMsaTokenSilentlyAsync", - "XUserGetMsaTokenSilentlyResult", - "XUserGetMsaTokenSilentlyResultSize" - ] - }, - "IXUserImpl4": { - "class": "XUserImpl", - "id": "079415e3-6727-437f-8e9d-8f8f9b2439f7", - "inherits": "IXUserImpl3", - "methods": [ - "XUserIsStoreUser" - ] - }, - "IXUserImpl5": { - "class": "XUserImpl", - "id": "26f3c674-a2fe-44fa-b6c4-a323bc94ff53", - "inherits": "IXUserImpl4", - "methods": [ - "XUserPlatformRemoteConnectSetEventHandlers", - "XUserPlatformRemoteConnectCancelPrompt", - "XUserPlatformSpopPromptSetEventHandlers", - "XUserPlatformSpopPromptComplete" - ] - }, - "IXUserImpl6": { - "class": "XUserImpl", - "id": "5131d685-4394-4ee6-8c18-bfb5d4aef1ff", - "inherits": "IXUserImpl5", - "methods": [ - "XUserIsSignOutPresent", - "XUserSignOutAsync", - "XUserSignOutResult" - ] - } - }, - "licence": "The source is GPL-3.0. Facts only: ids, inheritance and method order; no text is copied.", - "note": "The runtime classes QueryApiImpl hands out. An interface's vtable is IUnknown's three slots, then the methods of its inheritance chain, base first. A null method is one the docs list as unknown; null 'methods' means the docs give no layout for that interface (its methods, if any, are listed under its base). Made by tools/gen_gdk_runtime_classes.py.", - "source": "https://github.com/xodus-gaming/xgameruntime-docs at 7090008692569aa6081e30dfdd9de58237741e24" -} diff --git a/tools/gen_d3d12_stubs.py b/tools/gen_d3d12_stubs.py deleted file mode 100644 index fccdf4510..000000000 --- a/tools/gen_d3d12_stubs.py +++ /dev/null @@ -1,227 +0,0 @@ -"""Generate logging stubs for D3D12 COM interfaces from the Windows SDK's d3d12.h. - -For each requested interface, writes a class `Stubs` deriving from it that overrides every method of -its chain (except IUnknown's) with a body that reports the call once through rt::d3d12::stub() and returns -E_NOTIMPL, nothing or a value-initialised result. The runtime's COM objects derive from these and override the -methods they implement, so their vtables have exactly the SDK's method order and the compiler rejects a missing -method. Run at build time (runtime/cmake/d3d12_vulkan.cmake); the output is not checked in. - - python -I tools/gen_d3d12_stubs.py --out [--header ] Interface [Interface ...] - python -I tools/gen_d3d12_stubs.py --report --source ... [--header ] Interface ... - -Without --header, d3d12.h is looked up in the directories of the INCLUDE environment variable (set by vcvars). -The report mode lists each interface's methods and which names are not overridden as `STDMETHODCALLTYPE` in the -given sources; it is a name-based coverage aid for the D3D12 layer, not a compiler check. -""" -import argparse -import json -import os -import re -import sys - -sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) -from report_paths import same_report_path # noqa: E402 one spelling comparison for every report pair - -INTERFACE = re.compile( - r'MIDL_INTERFACE\("[0-9a-fA-F-]+"\)\s*\n\s*(\w+)\s*:\s*public\s+(\w+)\s*\{\s*public:(.*?)\n\s*\};', re.S) -METHOD = re.compile(r'virtual\s+(.*?)\s*STDMETHODCALLTYPE\s+(\w+)\s*\((.*)\)\s*(const)?\s*=\s*0\s*;\s*$', re.S) -COMMENTS_OR_LITERALS = re.compile(r"""("(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*')|/\*.*?\*/|//[^\r\n]*""", re.S) - - -def find_header(): - for directory in os.environ.get("INCLUDE", "").split(os.pathsep): - path = os.path.join(directory, "d3d12.h") - if directory and os.path.isfile(path): - return path - return None - - -def parse_interfaces(text): - """name -> (base, [lines]) where a line is ('#', text) or ('m', return, name, params, const).""" - text = COMMENTS_OR_LITERALS.sub(lambda match: match.group(1) or " ", text) - out = {} - for match in INTERFACE.finditer(text): - name, base, body = match.groups() - items, pending = [], [] - for line in body.splitlines(): - stripped = line.strip() - if not stripped: - continue - if stripped.startswith("#") and not pending: - items.append(("#", stripped)) - continue - pending.append(stripped) - if re.search(r"=\s*0\s*;\s*$", stripped): - declaration = " ".join(pending) - pending = [] - method = METHOD.match(declaration) - if not method: - raise SystemExit(f"{name}: cannot parse {declaration!r}") - ret, method_name, params, const = method.groups() - items.append(("m", " ".join(ret.split()), method_name, " ".join(params.split()), const or "")) - if pending: - raise SystemExit(f"{name}: unterminated declaration {' '.join(pending)!r}") - out[name] = (base, items) - return out - - -def chain(interfaces, leaf): - names = [] - seen = set() - name = leaf - while name != "IUnknown": - if name not in interfaces: - raise SystemExit(f"interface {name} not found in d3d12.h") - if name in seen: - raise SystemExit(f"circular inheritance in d3d12.h: {' -> '.join([*names, name])}") - seen.add(name) - names.append(name) - name = interfaces[name][0] - return list(reversed(names)) - - -def emit_class(interfaces, leaf): - lines = [f"class {leaf}Stubs : public {leaf} {{", "public:"] - for name in chain(interfaces, leaf): - lines.append(f" // {name}") - for item in interfaces[name][1]: - if item[0] == "#": - lines.append(item[1]) - continue - _, ret, method, params, const = item - if ret == "void": - result = "" - elif ret == "HRESULT": - result = " return E_NOTIMPL;" - else: - result = " return {};" - signature = f"{ret} STDMETHODCALLTYPE {method}({params}){' const' if const else ''}" - lines.append(f' {signature} override {{ ::rt::d3d12::stub("{name}::{method}");{result} }}') - lines.append("};") - return "\n".join(lines) - - -OVERRIDE = re.compile(r"\bSTDMETHODCALLTYPE\s+(\w+)\s*\(") - - -def implemented_names(paths): - """Method names overridden as STDMETHODCALLTYPE in the given sources.""" - names = set() - for path in paths: - with open(path, encoding="utf-8", errors="replace") as f: - source = COMMENTS_OR_LITERALS.sub(" ", f.read()) - names.update(OVERRIDE.findall(source)) - return names - - -def coverage(interfaces, leaves, sources): - """A JSON-serialisable method-coverage report for the requested leaf interfaces.""" - implemented = implemented_names(sources) - report = [] - for leaf in dict.fromkeys(leaves): - methods = [] - for name in chain(interfaces, leaf): - methods.extend((name, item[2]) for item in interfaces[name][1] if item[0] == "m") - # d3d12.h declares a struct-returning method twice, once in each branch of - # `#if defined(_MSC_VER) || !defined(_WIN32)` / `#else`; it is one vtable slot, so count it once. - methods = list(dict.fromkeys(methods)) - open_methods = [f"{owner}::{method}" for owner, method in methods if method not in implemented] - report.append({ - "interface": leaf, - "methods": len(methods), - "implemented": len(methods) - len(open_methods), - "open": open_methods, - }) - return report - - -def write_if_changed(path, text): - os.makedirs(os.path.dirname(os.path.abspath(path)), exist_ok=True) - try: - with open(path, encoding="utf-8") as f: - if f.read() == text: - return - except OSError: - pass - with open(path, "w", encoding="utf-8", newline="\n") as f: - f.write(text) - - -def same_path(first, second): - """True when writing first would replace second (same file, or a case/symlink alias of it). The comparison is - report_paths.same_report_path, which also folds case on a case-insensitive volume: os.path.normcase does that - only on Windows, and macOS's default APFS volume would let `R.json` and `r.json` pass as two artifacts.""" - return same_report_path(first, second) - - -def write_report(path, text): - """write_if_changed with a one-line ERROR instead of a traceback; False when it could not write.""" - try: - write_if_changed(path, text) - except OSError as e: - print(f"ERROR: cannot write {path}: {e}", file=sys.stderr) - return False - return True - - -def main(): - parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) - parser.add_argument("--out", help="generated stub header (required unless --report is given)") - parser.add_argument("--report", help="write a JSON method-coverage report here") - parser.add_argument("--source", action="append", default=[], metavar="CPP", - help="source file with overrides, repeatable (for --report)") - parser.add_argument("--header") - parser.add_argument("interfaces", nargs="+") - args = parser.parse_args() - if not args.out and not args.report: - parser.error("--out is required unless --report is given") - if args.report and not args.source: - parser.error("--report needs at least one --source") - for path in args.source: - if not os.path.isfile(path): - parser.error(f"--source {path}: no such file") - for path in (args.out, args.report): - if path and os.path.isdir(path): - parser.error(f"{path} is a folder, not a file") - if args.out and args.report and same_path(args.out, args.report): - parser.error("--out and --report must use different paths") - header = args.header or find_header() - if not header: - raise SystemExit("d3d12.h not found: pass --header or run from a vcvars environment") - if not os.path.isfile(header): - parser.error(f"--header {header}: no such file") - for path in [header] + list(args.source): - for flag, target in (("--out", args.out), ("--report", args.report)): - if target and same_path(target, path): - parser.error(f"{flag} {target} would overwrite the input {path}") - with open(header, encoding="utf-8", errors="replace") as f: - interfaces = parse_interfaces(f.read()) - - if args.report: - report = coverage(interfaces, args.interfaces, args.source) - if not write_report(args.report, json.dumps(report, indent=2) + "\n"): - return 2 - if not args.out: - return 0 - - parts = [ - "// Generated by tools/gen_d3d12_stubs.py from " + os.path.basename(header) + ". Do not edit.", - "#pragma once", - "#include ", - "namespace rt::d3d12 { void stub(const char* method); }", - "#pragma warning(push)", - "#pragma warning(disable : 4100) // unreferenced parameters", - ] - parts += [emit_class(interfaces, leaf) for leaf in dict.fromkeys(args.interfaces)] - parts.append("#pragma warning(pop)") - if not write_report(args.out, "\n".join(parts) + "\n"): - return 2 - return 0 - - -if __name__ == "__main__": - try: # a redirected stdout is strict ANSI code page under -I; write '?' for what it cannot encode - sys.stdout.reconfigure(errors="replace") - except (AttributeError, ValueError, OSError): - pass - sys.exit(main()) diff --git a/tools/gen_gdk_runtime_classes.py b/tools/gen_gdk_runtime_classes.py deleted file mode 100644 index 83ddefe0c..000000000 --- a/tools/gen_gdk_runtime_classes.py +++ /dev/null @@ -1,148 +0,0 @@ -"""Build tools/gdk_runtime_classes.json from a clone of xodus-gaming/xgameruntime-docs. - -Usage: - python -I tools/gen_gdk_runtime_classes.py [--out FILE] - -The docs (GPL-3.0) describe the COM classes the GDK runtime's QueryApiImpl hands out: one folder per class under -COM/, a README.md with the class id and the interfaces it implements, and one page per interface with its id, the -interface it inherits from and its "Layout" (the method order after IUnknown's three slots). This keeps the facts -only: ids, inheritance and method names in order. No text is copied. - -- A method the docs list as *unknown* stays in the list as null, so the methods after it keep their slot. -- An interface whose page has no "Layout" ("Layout changes unknown, all methods listed under ...", "No known - methods") gets "methods": null; its own methods, if any, are in its base's list. -- A class can implement more than one interface with its own vtable (XUserImpl: IXUserImpl6 and - IXUserGamertagImpl); each interface lists its own chain, so each starts at slot 3. - -tools/gdk_runtime_calls.py reads the output. Standard library only. -""" -from __future__ import annotations - -import argparse -import json -import os -import re -import subprocess -import sys - -ID = re.compile(r"(?:Interface|Class) Id: `([0-9a-fA-F-]{36})`") -INHERITS = re.compile(r"Inherits: (?:\[(I\w+)\]|IUnknown\b)") -LINKED_INTERFACE = re.compile(r"\[(I\w+)\]\(\w+\.md\)") -METHOD = re.compile(r"\[(\w+)\]|(\w+)") - - -def read_utf8(path: str) -> str: - with open(path, encoding="utf-8") as f: - return f.read() - - -def parse_layout(text: str) -> list[str | None] | None: - """The method names of a "Layout:" list in order (None for an *unknown* entry), or None without a list.""" - if "Layout:" not in text: - return None - methods: list[str | None] = [] - for line in text.split("Layout:", 1)[1].splitlines(): - line = line.strip() - if not line.startswith("- "): - if methods and line: - break # the paragraph after the list - continue - item = line[2:].strip() - m = METHOD.match(item) - methods.append(None if item.startswith("*unknown*") or not m else (m.group(1) or m.group(2))) - return methods - - -def parse_docs(root: str) -> tuple[dict, dict]: - com = os.path.join(root, "COM") - if not os.path.isdir(com): - raise FileNotFoundError(f"{root} has no COM folder; is it a clone of xgameruntime-docs?") - classes, interfaces = {}, {} - for cls in sorted(os.listdir(com)): - folder = os.path.join(com, cls) - if not os.path.isdir(folder): - continue - for name in sorted(os.listdir(folder)): - if not name.endswith(".md"): - continue - text = read_utf8(os.path.join(folder, name)) - m = ID.search(text) - if not m: - continue - guid = m.group(1).lower() - if name == "README.md": - implements = text.split("Implements:", 1)[1].splitlines()[0] if "Implements:" in text else "" - classes[cls] = {"id": guid, "implements": LINKED_INTERFACE.findall(implements)} - continue - inherits = INHERITS.search(text) - interfaces[name[:-3]] = { - "id": guid, - "class": cls, - "inherits": inherits.group(1) if inherits and inherits.group(1) else None, - "methods": parse_layout(text), - } - return classes, interfaces - - -def check(classes: dict, interfaces: dict) -> list[str]: - """Links the docs make that the table cannot follow.""" - problems = [] - for name, cls in classes.items(): - for iface in cls["implements"]: - if iface not in interfaces: - problems.append(f"{name} implements {iface}, which has no page") - for name, iface in interfaces.items(): - if iface["inherits"] and iface["inherits"] not in interfaces: - problems.append(f"{name} inherits {iface['inherits']}, which has no page") - return problems - - -def revision(root: str) -> str: - try: - out = subprocess.run(["git", "-C", root, "rev-parse", "HEAD"], capture_output=True, text=True, check=True) - return out.stdout.strip() or "unknown revision" - except (OSError, subprocess.CalledProcessError): - return "unknown revision" - - -def build(root: str) -> dict: - classes, interfaces = parse_docs(root) - return { - "source": f"https://github.com/xodus-gaming/xgameruntime-docs at {revision(root)}", - "licence": "The source is GPL-3.0. Facts only: ids, inheritance and method order; no text is copied.", - "note": ("The runtime classes QueryApiImpl hands out. An interface's vtable is IUnknown's three slots, then " - "the methods of its inheritance chain, base first. A null method is one the docs list as unknown; " - "null 'methods' means the docs give no layout for that interface (its methods, if any, are listed " - "under its base). Made by tools/gen_gdk_runtime_classes.py."), - "classes": classes, - "interfaces": interfaces, - } - - -def main(argv: list[str] | None = None) -> int: - ap = argparse.ArgumentParser(description=__doc__.split("\n\n", 1)[0]) - ap.add_argument("docs", help="a clone of xodus-gaming/xgameruntime-docs") - ap.add_argument("--out", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), - "gdk_runtime_classes.json")) - a = ap.parse_args(argv) - try: - table = build(a.docs) - except OSError as e: - print(f"cannot read the docs: {e}", file=sys.stderr) - return 1 - problems = check(table["classes"], table["interfaces"]) - for p in problems: - print(f"warning: {p}", file=sys.stderr) - with open(a.out, "w", encoding="utf-8", newline="\n") as f: - json.dump(table, f, indent=1, sort_keys=True) - f.write("\n") - print(f"{len(table['classes'])} classes, {len(table['interfaces'])} interfaces -> {a.out}") - return 0 - - -if __name__ == "__main__": - try: # a redirected stdout is strict ANSI code page under -I; write '?' for what it cannot encode - sys.stdout.reconfigure(errors="replace") - except (AttributeError, ValueError, OSError): - pass - sys.exit(main()) diff --git a/tools/gfx10_formats.json b/tools/gfx10_formats.json deleted file mode 100644 index 0f2063d02..000000000 --- a/tools/gfx10_formats.json +++ /dev/null @@ -1,162 +0,0 @@ -{ -"0": "GFX10_FORMAT_INVALID", -"1": "GFX10_FORMAT_8_UNORM", -"2": "GFX10_FORMAT_8_SNORM", -"3": "GFX10_FORMAT_8_USCALED", -"4": "GFX10_FORMAT_8_SSCALED", -"5": "GFX10_FORMAT_8_UINT", -"6": "GFX10_FORMAT_8_SINT", -"7": "GFX10_FORMAT_16_UNORM", -"8": "GFX10_FORMAT_16_SNORM", -"9": "GFX10_FORMAT_16_USCALED", -"10": "GFX10_FORMAT_16_SSCALED", -"11": "GFX10_FORMAT_16_UINT", -"12": "GFX10_FORMAT_16_SINT", -"13": "GFX10_FORMAT_16_FLOAT", -"14": "GFX10_FORMAT_8_8_UNORM", -"15": "GFX10_FORMAT_8_8_SNORM", -"16": "GFX10_FORMAT_8_8_USCALED", -"17": "GFX10_FORMAT_8_8_SSCALED", -"18": "GFX10_FORMAT_8_8_UINT", -"19": "GFX10_FORMAT_8_8_SINT", -"20": "GFX10_FORMAT_32_UINT", -"21": "GFX10_FORMAT_32_SINT", -"22": "GFX10_FORMAT_32_FLOAT", -"23": "GFX10_FORMAT_16_16_UNORM", -"24": "GFX10_FORMAT_16_16_SNORM", -"25": "GFX10_FORMAT_16_16_USCALED", -"26": "GFX10_FORMAT_16_16_SSCALED", -"27": "GFX10_FORMAT_16_16_UINT", -"28": "GFX10_FORMAT_16_16_SINT", -"29": "GFX10_FORMAT_16_16_FLOAT", -"30": "GFX10_FORMAT_10_11_11_UNORM", -"31": "GFX10_FORMAT_10_11_11_SNORM", -"32": "GFX10_FORMAT_10_11_11_USCALED", -"33": "GFX10_FORMAT_10_11_11_SSCALED", -"34": "GFX10_FORMAT_10_11_11_UINT", -"35": "GFX10_FORMAT_10_11_11_SINT", -"36": "GFX10_FORMAT_10_11_11_FLOAT", -"37": "GFX10_FORMAT_11_11_10_UNORM", -"38": "GFX10_FORMAT_11_11_10_SNORM", -"39": "GFX10_FORMAT_11_11_10_USCALED", -"40": "GFX10_FORMAT_11_11_10_SSCALED", -"41": "GFX10_FORMAT_11_11_10_UINT", -"42": "GFX10_FORMAT_11_11_10_SINT", -"43": "GFX10_FORMAT_11_11_10_FLOAT", -"44": "GFX10_FORMAT_10_10_10_2_UNORM", -"45": "GFX10_FORMAT_10_10_10_2_SNORM", -"46": "GFX10_FORMAT_10_10_10_2_USCALED", -"47": "GFX10_FORMAT_10_10_10_2_SSCALED", -"48": "GFX10_FORMAT_10_10_10_2_UINT", -"49": "GFX10_FORMAT_10_10_10_2_SINT", -"50": "GFX10_FORMAT_2_10_10_10_UNORM", -"51": "GFX10_FORMAT_2_10_10_10_SNORM", -"52": "GFX10_FORMAT_2_10_10_10_USCALED", -"53": "GFX10_FORMAT_2_10_10_10_SSCALED", -"54": "GFX10_FORMAT_2_10_10_10_UINT", -"55": "GFX10_FORMAT_2_10_10_10_SINT", -"56": "GFX10_FORMAT_8_8_8_8_UNORM", -"57": "GFX10_FORMAT_8_8_8_8_SNORM", -"58": "GFX10_FORMAT_8_8_8_8_USCALED", -"59": "GFX10_FORMAT_8_8_8_8_SSCALED", -"60": "GFX10_FORMAT_8_8_8_8_UINT", -"61": "GFX10_FORMAT_8_8_8_8_SINT", -"62": "GFX10_FORMAT_32_32_UINT", -"63": "GFX10_FORMAT_32_32_SINT", -"64": "GFX10_FORMAT_32_32_FLOAT", -"65": "GFX10_FORMAT_16_16_16_16_UNORM", -"66": "GFX10_FORMAT_16_16_16_16_SNORM", -"67": "GFX10_FORMAT_16_16_16_16_USCALED", -"68": "GFX10_FORMAT_16_16_16_16_SSCALED", -"69": "GFX10_FORMAT_16_16_16_16_UINT", -"70": "GFX10_FORMAT_16_16_16_16_SINT", -"71": "GFX10_FORMAT_16_16_16_16_FLOAT", -"72": "GFX10_FORMAT_32_32_32_UINT", -"73": "GFX10_FORMAT_32_32_32_SINT", -"74": "GFX10_FORMAT_32_32_32_FLOAT", -"75": "GFX10_FORMAT_32_32_32_32_UINT", -"76": "GFX10_FORMAT_32_32_32_32_SINT", -"77": "GFX10_FORMAT_32_32_32_32_FLOAT", -"128": "GFX10_FORMAT_8_SRGB", -"129": "GFX10_FORMAT_8_8_SRGB", -"130": "GFX10_FORMAT_8_8_8_8_SRGB", -"131": "GFX10_FORMAT_6E4_FLOAT", -"132": "GFX10_FORMAT_5_9_9_9_FLOAT", -"133": "GFX10_FORMAT_5_6_5_UNORM", -"134": "GFX10_FORMAT_1_5_5_5_UNORM", -"135": "GFX10_FORMAT_5_5_5_1_UNORM", -"136": "GFX10_FORMAT_4_4_4_4_UNORM", -"137": "GFX10_FORMAT_4_4_UNORM", -"138": "GFX10_FORMAT_1_UNORM", -"139": "GFX10_FORMAT_1_REVERSED_UNORM", -"140": "GFX10_FORMAT_32_FLOAT_CLAMP", -"141": "GFX10_FORMAT_8_24_UNORM", -"142": "GFX10_FORMAT_8_24_UINT", -"143": "GFX10_FORMAT_24_8_UNORM", -"144": "GFX10_FORMAT_24_8_UINT", -"145": "GFX10_FORMAT_X24_8_32_UINT", -"146": "GFX10_FORMAT_X24_8_32_FLOAT", -"147": "GFX10_FORMAT_GB_GR_UNORM", -"148": "GFX10_FORMAT_GB_GR_SNORM", -"149": "GFX10_FORMAT_GB_GR_UINT", -"150": "GFX10_FORMAT_GB_GR_SRGB", -"151": "GFX10_FORMAT_BG_RG_UNORM", -"152": "GFX10_FORMAT_BG_RG_SNORM", -"153": "GFX10_FORMAT_BG_RG_UINT", -"154": "GFX10_FORMAT_BG_RG_SRGB", -"156": "GFX10_FORMAT_FMASK8_S2_F1", -"157": "GFX10_FORMAT_FMASK8_S4_F1", -"158": "GFX10_FORMAT_FMASK8_S8_F1", -"159": "GFX10_FORMAT_FMASK8_S2_F2", -"160": "GFX10_FORMAT_FMASK8_S4_F2", -"161": "GFX10_FORMAT_FMASK8_S4_F4", -"162": "GFX10_FORMAT_FMASK16_S16_F1", -"163": "GFX10_FORMAT_FMASK16_S8_F2", -"164": "GFX10_FORMAT_FMASK32_S16_F2", -"165": "GFX10_FORMAT_FMASK32_S8_F4", -"166": "GFX10_FORMAT_FMASK32_S8_F8", -"167": "GFX10_FORMAT_FMASK64_S16_F4", -"168": "GFX10_FORMAT_FMASK64_S16_F8", -"169": "GFX10_FORMAT_BC1_UNORM", -"170": "GFX10_FORMAT_BC1_SRGB", -"171": "GFX10_FORMAT_BC2_UNORM", -"172": "GFX10_FORMAT_BC2_SRGB", -"173": "GFX10_FORMAT_BC3_UNORM", -"174": "GFX10_FORMAT_BC3_SRGB", -"175": "GFX10_FORMAT_BC4_UNORM", -"176": "GFX10_FORMAT_BC4_SNORM", -"177": "GFX10_FORMAT_BC5_UNORM", -"178": "GFX10_FORMAT_BC5_SNORM", -"179": "GFX10_FORMAT_BC6_UFLOAT", -"180": "GFX10_FORMAT_BC6_SFLOAT", -"181": "GFX10_FORMAT_BC7_UNORM", -"182": "GFX10_FORMAT_BC7_SRGB", -"265": "GFX10_FORMAT_MM_8_UNORM", -"266": "GFX10_FORMAT_MM_8_UINT", -"267": "GFX10_FORMAT_MM_8_8_UNORM", -"268": "GFX10_FORMAT_MM_8_8_UINT", -"269": "GFX10_FORMAT_MM_8_8_8_8_UNORM", -"270": "GFX10_FORMAT_MM_8_8_8_8_UINT", -"271": "GFX10_FORMAT_MM_VYUY8_UNORM", -"272": "GFX10_FORMAT_MM_VYUY8_UINT", -"273": "GFX10_FORMAT_MM_10_11_11_UNORM", -"274": "GFX10_FORMAT_MM_10_11_11_UINT", -"275": "GFX10_FORMAT_MM_2_10_10_10_UNORM", -"276": "GFX10_FORMAT_MM_2_10_10_10_UINT", -"277": "GFX10_FORMAT_MM_16_16_16_16_UNORM", -"278": "GFX10_FORMAT_MM_16_16_16_16_UINT", -"279": "GFX10_FORMAT_MM_10_IN_16_UNORM", -"280": "GFX10_FORMAT_MM_10_IN_16_UINT", -"281": "GFX10_FORMAT_MM_10_IN_16_16_UNORM", -"282": "GFX10_FORMAT_MM_10_IN_16_16_UINT", -"283": "GFX10_FORMAT_MM_10_IN_16_16_16_16_UNORM ", -"284": "GFX10_FORMAT_MM_10_IN_16_16_16_16_UINT", -"285": "GFX10_FORMAT_7E3_FLOAT", -"286": "GFX10_FORMAT_YCBCR_UNORM", -"287": "GFX10_FORMAT_YCBCR_SNORM", -"288": "GFX10_FORMAT_YCBCR_USCALED", -"289": "GFX10_FORMAT_YCBCR_SSCALED", -"290": "GFX10_FORMAT_YCBCR_UINT", -"291": "GFX10_FORMAT_YCBCR_SINT", -"292": "GFX10_FORMAT_YCBCR_SRGB" -} \ No newline at end of file diff --git a/tools/glb_inspect.py b/tools/glb_inspect.py deleted file mode 100644 index 293e8bba6..000000000 --- a/tools/glb_inspect.py +++ /dev/null @@ -1,732 +0,0 @@ -"""Inspect a glTF 2.0 binary (.glb): meshes, materials, skins, animations and POSITION bounds. - -Usage: - python -I tools/glb_inspect.py [--json FILE] - -Reads the GLB container (12-byte header, JSON chunk, optional BIN chunk and -chunk padding), then reports what the JSON actually contains. Missing fields are -reported as missing; nothing is inferred from the binary buffers. -For base-color textures without a core source, the inspector checks the declared -KHR_texture_basisu and EXT_texture_webp image sources without loading either format. - -All geometry, names and paths come from the inspected file. No game data is -needed or bundled. -""" -from __future__ import annotations - -import argparse -from contextlib import suppress -import errno -import json -import os -import struct -import sys -import tempfile - -TOOLS_DIR = os.path.dirname(os.path.abspath(__file__)) -if TOOLS_DIR not in sys.path: - sys.path.insert(0, TOOLS_DIR) - -from file_mode import published_mode # noqa: E402 -from report_paths import same_report_path # noqa: E402 - -GLB_MAGIC = b"glTF" -GLB_VERSION = 2 -GLB_HEADER_SIZE = 12 -CHUNK_HEADER_SIZE = 8 -CHUNK_TYPE_JSON = 0x4E4F534A # b"JSON" -CHUNK_TYPE_BIN = 0x004E4942 # b"BIN\x00" - -MODE_NAMES = { - 0: "POINTS", - 1: "LINES", - 2: "LINE_LOOP", - 3: "LINE_STRIP", - 4: "TRIANGLES", - 5: "TRIANGLE_STRIP", - 6: "TRIANGLE_FAN", -} - - -class GlbError(ValueError): - """A malformed GLB container or JSON document.""" - - -def _is_int(value: object) -> bool: - return isinstance(value, int) and not isinstance(value, bool) - - -def _index(value: object) -> int | None: - """A non-negative integer index, or None.""" - return value if _is_int(value) and value >= 0 else None - - -def _chunk_type_name(chunk_type: int) -> str: - if chunk_type == CHUNK_TYPE_JSON: - return "JSON" - if chunk_type == CHUNK_TYPE_BIN: - return "BIN" - return f"0x{chunk_type:08X}" - - -def _object(value: object) -> dict: - return value if isinstance(value, dict) else {} - - -def _array(value: object) -> list: - return value if isinstance(value, list) else [] - - -def _count(gltf: dict, key: str) -> int: - return len(_array(gltf.get(key))) - - -ARRAY_FIELDS = ("scenes", "nodes", "meshes", "materials", "images", "skins", - "animations", "accessors") - - -def _invalid_types(gltf: dict) -> dict[str, str]: - """Known array fields that are present but hold a non-array value.""" - return {key: type(gltf[key]).__name__ for key in ARRAY_FIELDS - if key in gltf and not isinstance(gltf[key], list)} - - -def _entry(gltf: dict, key: str, index: object) -> dict | None: - """The object at ``gltf[key][index]``, or None for a missing/invalid index.""" - if not _is_int(index) or index < 0: - return None - entries = gltf.get(key) - if not isinstance(entries, list) or index >= len(entries): - return None - entry = entries[index] - return entry if isinstance(entry, dict) else None - - -def _text(value: object) -> str | None: - return value if isinstance(value, str) and value else None - - -def _reject_json_constant(value: str) -> None: - raise GlbError(f"malformed JSON chunk: {value} is not a JSON number") - - -def parse_glb(data: bytes) -> dict: - """Validate the GLB container and return the parsed JSON and chunk table.""" - size = len(data) - if size < GLB_HEADER_SIZE: - raise GlbError(f"truncated GLB header: {size} bytes, need at least {GLB_HEADER_SIZE}") - - magic, version, declared_length = struct.unpack_from("<4sII", data, 0) - if magic != GLB_MAGIC: - raise GlbError(f"bad GLB magic {magic!r}, expected {GLB_MAGIC!r}") - if version != GLB_VERSION: - raise GlbError(f"unsupported GLB version {version}, expected {GLB_VERSION}") - if declared_length != size: - detail = "file is truncated" if declared_length > size else "file has trailing bytes" - raise GlbError(f"declared GLB length {declared_length} does not match file size {size} ({detail})") - if declared_length % 4: - raise GlbError(f"declared GLB length {declared_length} is not 4-byte aligned") - if size < GLB_HEADER_SIZE + CHUNK_HEADER_SIZE: - raise GlbError("missing JSON chunk") - - offset = GLB_HEADER_SIZE - chunks: list[dict] = [] - while offset < size: - if offset + CHUNK_HEADER_SIZE > size: - raise GlbError(f"truncated chunk header at offset {offset}") - chunk_length, chunk_type = struct.unpack_from(" remaining: - raise GlbError( - f"truncated {label} chunk at offset {offset}: " - f"declared {chunk_length} bytes, {remaining} available" - ) - if chunk_length % 4: - raise GlbError(f"{label} chunk at offset {offset} has length {chunk_length}, not a multiple of 4") - chunks.append({"type": chunk_type, "length": chunk_length}) - offset += CHUNK_HEADER_SIZE + chunk_length - - if not chunks or chunks[0]["type"] != CHUNK_TYPE_JSON: - kind = _chunk_type_name(chunks[0]["type"]) if chunks else "none" - raise GlbError(f"missing JSON chunk: first chunk is {kind}") - - json_offset = GLB_HEADER_SIZE + CHUNK_HEADER_SIZE - json_payload = data[json_offset:json_offset + chunks[0]["length"]] - pad_start = len(json_payload.rstrip(b" \x00")) - padding = len(json_payload) - pad_start - nul_padding = json_payload[pad_start:].count(b"\x00") - # Some writers pad with NUL although the spec requires spaces; accept it for - # parsing, while still reporting exactly how many bytes were padding. - try: - json_text = json_payload[:pad_start].decode("utf-8", errors="strict") - gltf = json.loads(json_text, parse_constant=_reject_json_constant) - except json.JSONDecodeError as exc: - raise GlbError(f"malformed JSON chunk: {exc.msg} at line {exc.lineno} column {exc.colno}") from exc - except UnicodeDecodeError as exc: - raise GlbError(f"malformed JSON chunk: not UTF-8 ({exc.reason} at byte {exc.start})") from exc - except RecursionError as exc: - raise GlbError("malformed JSON chunk: nesting is too deep") from exc - if not isinstance(gltf, dict): - raise GlbError("malformed JSON chunk: root is not a JSON object") - - bin_padding = None - seen_bin = False - for chunk_index, chunk in enumerate(chunks[1:], 1): - if chunk["type"] == CHUNK_TYPE_JSON: - raise GlbError(f"duplicate JSON chunk at chunk index {chunk_index}") - if chunk["type"] != CHUNK_TYPE_BIN: - continue # extension chunks are allowed and ignored, per glTF 2.0 section 4.4 - if seen_bin: - raise GlbError("duplicate BIN chunk") - if chunk_index != 1: - raise GlbError("BIN chunk must immediately follow the JSON chunk") - seen_bin = True - bin_length = chunk["length"] - buffers = _array(gltf.get("buffers")) - buffer0 = _object(buffers[0]) if buffers else {} - declared = buffer0.get("byteLength") - if "uri" not in buffer0 and _is_int(declared) and 0 <= declared <= bin_length: - bin_padding = bin_length - declared - - chunk_table = [] - for chunk_index, chunk in enumerate(chunks): - entry = {"type": _chunk_type_name(chunk["type"]), "byte_length": chunk["length"]} - if chunk_index == 0: - entry["padding"] = padding - if nul_padding: - entry["nul_padding"] = nul_padding - elif chunk["type"] == CHUNK_TYPE_BIN: - entry["padding"] = bin_padding - chunk_table.append(entry) - return { - "version": version, - "json": gltf, - "chunks": chunk_table, - } - - -def _accessor(gltf: dict, index: object) -> dict | None: - return _entry(gltf, "accessors", index) - - -def _accessor_count(gltf: dict, index: object) -> int | None: - accessor = _accessor(gltf, index) - if accessor is None: - return None - count = accessor.get("count") - return count if _is_int(count) and count >= 0 else None - - -def _accessor_max(accessor: dict | None) -> float | None: - """An accessor's declared max[0], or None when it is missing or not a number.""" - if accessor is None: - return None - upper = accessor.get("max") - if (isinstance(upper, list) and upper - and isinstance(upper[0], (int, float)) and not isinstance(upper[0], bool)): - try: - return float(upper[0]) - except (OverflowError, ValueError): - return None # an integer too large to be a float has no usable bound - return None - - -def _accessor_type(gltf: dict, index: object) -> str | None: - accessor = _accessor(gltf, index) - return _text(accessor.get("type")) if accessor is not None else None - - -def _animation_report(gltf: dict, index: int, animation: dict) -> dict: - """Summarize an animation and flag references that cannot be resolved.""" - issues: list[str] = [] - raw_samplers_value = animation.get("samplers") - if raw_samplers_value is not None and not isinstance(raw_samplers_value, list): - issues.append("animation samplers is not an array") - raw_samplers = _array(raw_samplers_value) - raw_channels_value = animation.get("channels") - if raw_channels_value is not None and not isinstance(raw_channels_value, list): - issues.append("animation channels is not an array") - raw_channels = _array(raw_channels_value) - samplers: list[dict] = [] - for sampler_index, sampler in enumerate(raw_samplers): - if not isinstance(sampler, dict): - issues.append(f"sampler[{sampler_index}] is not an object") - samplers.append({"index": sampler_index, "input_accessor": None, "input_count": None, - "output_accessor": None, "output_count": None, - "output_type": None, "interpolation": None, "duration": None}) - continue - input_index = _index(sampler.get("input")) - output_index = _index(sampler.get("output")) - input_accessor = _accessor(gltf, input_index) - output_accessor = _accessor(gltf, output_index) - input_count = _accessor_count(gltf, input_index) - output_count = _accessor_count(gltf, output_index) - input_type = _accessor_type(gltf, input_index) - output_type = _accessor_type(gltf, output_index) - raw_interpolation = sampler.get("interpolation") - interpolation = _text(raw_interpolation) - if raw_interpolation is None: - interpolation = "LINEAR" - elif interpolation is None: - issues.append(f"sampler[{sampler_index}] has unknown interpolation {raw_interpolation!r}") - duration = _accessor_max(input_accessor) if input_count else None - if input_accessor is None: - issues.append(f"sampler[{sampler_index}] input accessor is missing") - elif input_count is None or input_count == 0: - issues.append(f"sampler[{sampler_index}] input accessor has no keyframes") - if input_type is not None and input_type != "SCALAR": - issues.append(f"sampler[{sampler_index}] input accessor type is {input_type}, expected SCALAR") - if output_accessor is None: - issues.append(f"sampler[{sampler_index}] output accessor is missing") - if input_count is not None and output_count is not None: - expected = input_count * 3 if interpolation == "CUBICSPLINE" else input_count - if output_count != expected: - issues.append( - f"sampler[{sampler_index}] has {output_count} output values for {input_count} " - f"keys with {interpolation} interpolation" - ) - if interpolation is not None and interpolation not in ("LINEAR", "STEP", "CUBICSPLINE"): - issues.append(f"sampler[{sampler_index}] has unknown interpolation {interpolation!r}") - samplers.append({ - "index": sampler_index, - "input_accessor": input_index, - "input_count": input_count, - "input_type": input_type, - "output_accessor": output_index, - "output_count": output_count, - "output_type": output_type, - "interpolation": interpolation, - "duration": duration, - }) - - channels: list[dict] = [] - paths: dict[str, int] = {} - target_nodes: set[int] = set() - for channel_index, channel in enumerate(raw_channels): - if not isinstance(channel, dict): - issues.append(f"channel[{channel_index}] is not an object") - channels.append({"index": channel_index, "sampler": None, "node": None, - "node_name": None, "path": None}) - continue - sampler_index = _index(channel.get("sampler")) - target = _object(channel.get("target")) - node_index = _index(target.get("node")) - path = _text(target.get("path")) - node = _entry(gltf, "nodes", node_index) - if sampler_index is None or sampler_index >= len(raw_samplers): - issues.append(f"channel[{channel_index}] has no valid sampler") - if node_index is None: - issues.append(f"channel[{channel_index}] has no target node") - elif node is None: - issues.append(f"channel[{channel_index}] targets missing node {node_index}") - else: - target_nodes.add(node_index) - if path is None: - issues.append(f"channel[{channel_index}] has no target path") - elif path not in ("translation", "rotation", "scale", "weights"): - issues.append(f"channel[{channel_index}] has unknown target path {path!r}") - else: - paths[path] = paths.get(path, 0) + 1 - expected_type = {"translation": "VEC3", "rotation": "VEC4", - "scale": "VEC3", "weights": "SCALAR"}[path] - sampler = samplers[sampler_index] if sampler_index is not None and sampler_index < len(samplers) else None - output_type = sampler["output_type"] if sampler is not None else None - if output_type is not None and output_type != expected_type: - issues.append( - f"channel[{channel_index}] path {path!r} expects {expected_type} output, " - f"got {output_type}" - ) - channels.append({ - "index": channel_index, - "sampler": sampler_index, - "node": node_index, - "node_name": _text(node.get("name")) if node is not None else None, - "path": path, - }) - - known_durations = [sampler["duration"] for sampler in samplers if sampler["duration"] is not None] - return { - "index": index, - "name": _text(animation.get("name")), - "channel_count": len(raw_channels), - "sampler_count": len(raw_samplers), - "duration": max(known_durations) if known_durations else None, - "target_node_count": len(target_nodes), - "paths": dict(sorted(paths.items())), - "interpolations": sorted({sampler["interpolation"] for sampler in samplers - if sampler["interpolation"] is not None}), - "channels": channels, - "samplers": samplers, - "issues": issues, - } - - - -def _bbox(accessor: dict | None) -> dict | None: - """An accessor's declared POSITION min/max, or None when either is missing.""" - if accessor is None: - return None - lower = accessor.get("min") - upper = accessor.get("max") - if not (isinstance(lower, list) and isinstance(upper, list) and len(lower) >= 3 and len(upper) >= 3): - return None - if not all(isinstance(value, (int, float)) and not isinstance(value, bool) for value in lower[:3] + upper[:3]): - return None - return {"min": lower[:3], "max": upper[:3]} - - -def _merge_bbox(boxes: list[dict]) -> dict | None: - if not boxes: - return None - return { - "min": [min(box["min"][axis] for box in boxes) for axis in range(3)], - "max": [max(box["max"][axis] for box in boxes) for axis in range(3)], - } - - -def _material_name(gltf: dict, index: object) -> str | None: - material = _entry(gltf, "materials", index) - return _text(material.get("name")) if material is not None else None - - -def _texture_name(gltf: dict, texture_index: object) -> str | None: - """The baseColor texture's image name, falling back to its URI then the texture name.""" - texture = _entry(gltf, "textures", texture_index) - if texture is None: - return None - image = _entry(gltf, "images", texture.get("source")) - if "source" not in texture: - extensions = _object(texture.get("extensions")) - for extension in ("KHR_texture_basisu", "EXT_texture_webp"): - source = _object(extensions.get(extension)).get("source") - image = _entry(gltf, "images", source) - if image is not None: - break - if image is not None: - name = _text(image.get("name")) - if name is not None: - return name - uri = _text(image.get("uri")) - if uri is not None: - return uri - return _text(texture.get("name")) - - -def _material_report(gltf: dict, index: int, material: dict) -> dict: - pbr = _object(material.get("pbrMetallicRoughness")) - base_color_texture = _object(pbr.get("baseColorTexture")) - texture_index = _index(base_color_texture.get("index")) - return { - "index": index, - "name": _text(material.get("name")), - "base_color_factor": pbr.get("baseColorFactor"), - "base_color_texture": _texture_name(gltf, texture_index), - "base_color_texture_index": texture_index, - "alpha_mode": material.get("alphaMode"), - "double_sided": material.get("doubleSided"), - } - - -def _primitive_mode(primitive: dict) -> tuple[int | None, str | None, bool]: - """The effective mode for counts, its name, and whether the spec default filled it in.""" - if "mode" not in primitive: - return 4, MODE_NAMES[4], True - value = primitive["mode"] - if not _is_int(value): - return None, None, False - return value, MODE_NAMES.get(value, f"MODE_{value}"), False - - -def _triangle_count(mode: int | None, count: int | None) -> int | None: - if mode is None or count is None: - return None - if mode == 4: - return count // 3 - if mode in (5, 6): - return max(0, count - 2) - if 0 <= mode <= 3: - return 0 - return None - - -def _primitive_report(gltf: dict, primitive_index: int, primitive: dict) -> dict: - attributes = _object(primitive.get("attributes")) - position_index = attributes.get("POSITION") - position_accessor = _accessor(gltf, position_index) - vertices = _accessor_count(gltf, position_index) - mode, mode_name, mode_defaulted = _primitive_mode(primitive) - indices_index = primitive.get("indices") - element_count = _accessor_count(gltf, indices_index) if indices_index is not None else vertices - material_index = _index(primitive.get("material")) - return { - "index": primitive_index, - "mode": primitive.get("mode") if _is_int(primitive.get("mode")) else None, - "mode_name": mode_name, - "mode_defaulted": mode_defaulted, - "vertices": vertices, - "triangles": _triangle_count(mode, element_count), - "material_index": material_index, - "material": _material_name(gltf, material_index), - "position_accessor": _index(position_index), - "bbox": _bbox(position_accessor), - } - - -def _mesh_report(gltf: dict, index: int, mesh: dict) -> dict: - primitives = [_primitive_report(gltf, i, primitive) - for i, primitive in enumerate(_array(mesh.get("primitives"))) - if isinstance(primitive, dict)] - material_names: list[str | None] = [] - for primitive in primitives: - if primitive["material_index"] is not None and primitive["material"] not in material_names: - material_names.append(primitive["material"]) - vertices = [primitive["vertices"] for primitive in primitives] - triangles = [primitive["triangles"] for primitive in primitives] - return { - "index": index, - "name": _text(mesh.get("name")), - "primitive_count": len(primitives), - "vertices": sum(vertices) if vertices and all(value is not None for value in vertices) else None, - "triangles": sum(triangles) if triangles and all(value is not None for value in triangles) else None, - "materials": material_names, - "primitives": primitives, - } - - -def build_report(glb: dict, file_bytes: int) -> dict: - """Turn the parsed GLB JSON into the inspection report.""" - gltf = glb["json"] - asset = _object(gltf.get("asset")) - meshes = [_mesh_report(gltf, i, mesh) - for i, mesh in enumerate(_array(gltf.get("meshes"))) - if isinstance(mesh, dict)] - materials = [_material_report(gltf, i, material) - for i, material in enumerate(_array(gltf.get("materials"))) - if isinstance(material, dict)] - skins = [] - for i, skin in enumerate(_array(gltf.get("skins"))): - if not isinstance(skin, dict): - continue - joints = skin.get("joints") - skins.append({ - "index": i, - "name": _text(skin.get("name")), - "joint_count": len(joints) if isinstance(joints, list) else None, - }) - animations = [_animation_report(gltf, i, animation) - for i, animation in enumerate(_array(gltf.get("animations"))) - if isinstance(animation, dict)] - - boxes = [primitive["bbox"] for mesh in meshes for primitive in mesh["primitives"] - if primitive["bbox"] is not None] - position_primitives = sum(1 for mesh in meshes for primitive in mesh["primitives"] - if primitive["position_accessor"] is not None) - invalid_counts = {} - for key in ("meshes", "materials", "skins", "animations"): - count = sum(1 for entry in _array(gltf.get(key)) if not isinstance(entry, dict)) - if count: - invalid_counts[key] = count - invalid_types = _invalid_types(gltf) - report = { - "bytes": file_bytes, - "asset": { - "version": asset.get("version"), - "generator": asset.get("generator"), - }, - "counts": { - "scenes": _count(gltf, "scenes"), - "nodes": _count(gltf, "nodes"), - "meshes": _count(gltf, "meshes"), - "materials": _count(gltf, "materials"), - "images": _count(gltf, "images"), - "skins": _count(gltf, "skins"), - "animations": _count(gltf, "animations"), - }, - "chunks": glb["chunks"], - "position_bbox": _merge_bbox(boxes), - "position_bbox_complete": bool(boxes) and len(boxes) == position_primitives, - "meshes": meshes, - "materials": materials, - "skins": skins, - "animations": animations, - } - if any(invalid_counts.values()): - report["invalid_counts"] = invalid_counts - if invalid_types: - report["invalid_types"] = invalid_types - return report - - -def _show(value: object) -> str: - if value is None: - return "(missing)" - if isinstance(value, list): - return "[" + ", ".join(_show(item) for item in value) + "]" - if isinstance(value, str): - return json.dumps(value, ensure_ascii=False) - if isinstance(value, bool): - return "true" if value else "false" - return str(value) - - -def _bbox_text(box: dict | None) -> str: - if box is None: - return "(missing)" - return f"min {_show(box['min'])} max {_show(box['max'])}" - - -def _padding_text(value: object) -> str: - return "n/a" if value is None else _show(value) - - -def format_report(report: dict) -> str: - """Render the human-readable report.""" - lines = [f"bytes: {report['bytes']:,}"] - asset = report["asset"] - lines.append(f"asset: version={_show(asset['version'])} generator={_show(asset['generator'])}") - counts = report["counts"] - lines.append("counts: " + " ".join(f"{key}={counts[key]}" for key in - ("scenes", "nodes", "meshes", "materials", "images", "skins", "animations"))) - invalid = report.get("invalid_counts") - if invalid: - lines.append("invalid entries: " + " ".join(f"{key}={value}" for key, value in invalid.items() if value)) - invalid_types = report.get("invalid_types") - if invalid_types: - lines.append("invalid types: " + " ".join(f"{key}={value}" for key, value in invalid_types.items())) - lines.append("chunks: " + ", ".join( - f"{chunk['type']} {chunk['byte_length']} bytes (padding {_padding_text(chunk.get('padding'))})" - for chunk in report["chunks"])) - bbox = report["position_bbox"] - suffix = (" (partial: some POSITION accessors have no min/max)" - if bbox is not None and not report["position_bbox_complete"] else "") - lines.append(f"POSITION bbox: {_bbox_text(bbox)}{suffix}") - - lines.append("meshes:") - if not report["meshes"]: - lines.append(" (none)") - for mesh in report["meshes"]: - names = "[" + ", ".join(_show(name) for name in mesh["materials"]) + "]" if mesh["materials"] else "none" - lines.append(f" [{mesh['index']}] name={_show(mesh['name'])} primitives={mesh['primitive_count']} " - f"vertices={_show(mesh['vertices'])} triangles={_show(mesh['triangles'])} " - f"materials={names}") - for primitive in mesh["primitives"]: - material = ("none" if primitive["material_index"] is None else - f"{_show(primitive['material'])} (index {primitive['material_index']})") - mode = _show(primitive["mode_name"]) - if primitive["mode_defaulted"]: - mode += " (default)" - lines.append( - f" primitive {primitive['index']}: mode={mode} " - f"vertices={_show(primitive['vertices'])} triangles={_show(primitive['triangles'])} " - f"material={material} bbox {_bbox_text(primitive['bbox'])}") - - lines.append("materials:") - if not report["materials"]: - lines.append(" (none)") - for material in report["materials"]: - lines.append( - f" [{material['index']}] name={_show(material['name'])} " - f"baseColorFactor={_show(material['base_color_factor'])} " - f"baseColorTexture={_show(material['base_color_texture'])} " - f"(index {_show(material['base_color_texture_index'])}) " - f"alphaMode={_show(material['alpha_mode'])} doubleSided={_show(material['double_sided'])}") - - lines.append("skins:") - if not report["skins"]: - lines.append(" (none)") - for skin in report["skins"]: - lines.append(f" [{skin['index']}] name={_show(skin['name'])} joints={_show(skin['joint_count'])}") - - lines.append("animations:") - if not report["animations"]: - lines.append(" (none)") - for animation in report["animations"]: - paths = ", ".join(f"{name}={count}" for name, count in animation["paths"].items()) or "none" - interpolation = ", ".join(animation["interpolations"]) or "none" - lines.append( - f" [{animation['index']}] name={_show(animation['name'])} " - f"channels={animation['channel_count']} samplers={animation['sampler_count']} " - f"duration={_show(animation['duration'])} targets={animation['target_node_count']}") - lines.append(f" paths: {paths}; interpolation: {interpolation}") - for issue in animation["issues"]: - lines.append(f" issue: {issue}") - return "\n".join(lines) - - -def inspect_file(path: str) -> dict: - with open(path, "rb") as handle: - data = handle.read() - return build_report(parse_glb(data), len(data)) - - -def main(argv: list[str] | None = None) -> int: - parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) - parser.add_argument("input", help="binary glTF 2.0 (.glb) file") - parser.add_argument("--json", dest="json_path", metavar="FILE", help="also write the report as JSON to FILE") - args = parser.parse_args(argv) - - if args.json_path: - # A trailing separator marks a directory-style destination; realpath would strip it and publish - # over a same-named file, which open(..., "w") never did. - separators = tuple(separator for separator in (os.sep, os.altsep) if separator) - if os.path.isdir(args.json_path) or args.json_path.endswith(separators): - print(f"error: --json {args.json_path} is a directory", file=sys.stderr) - return 2 - if same_report_path(args.json_path, args.input): - print(f"error: --json {args.json_path} must not overwrite the input {args.input}", file=sys.stderr) - return 2 - - try: - report = inspect_file(args.input) - except GlbError as exc: - print(f"error: {args.input}: {exc}", file=sys.stderr) - return 2 - except OSError as exc: - print(f"error: cannot read {args.input}: {exc.strerror or exc}", file=sys.stderr) - return 2 - - if args.json_path: - try: - text = json.dumps(report, indent=2, allow_nan=False) + "\n" - except (TypeError, ValueError) as exc: - print(f"error: cannot write {args.json_path}: {exc}", file=sys.stderr) - return 2 - # Publish at the symlink's target, as open(..., "w") did before the report was staged, without - # replacing the link. os.replace unlinks only at the destination name, so another hard link to - # the previous report keeps its bytes (the report-writer rule story_index.write_output documents). - staged = None - try: - destination = os.path.realpath(args.json_path) - if os.path.islink(destination): - # realpath leaves an unresolved link in place for a cycle (or past the depth limit); replacing it - # would break the promise above. open(..., "w") failed with ELOOP there. - raise OSError(errno.ELOOP, "Too many levels of symbolic links", args.json_path) - directory = os.path.dirname(os.path.abspath(destination)) - with tempfile.NamedTemporaryFile(mode="w", encoding="utf-8", newline="\n", dir=directory, - prefix=".glb_inspect-", delete=False) as handle: - staged = handle.name - handle.write(text) - os.chmod(staged, published_mode(destination)) - os.replace(staged, destination) - staged = None - except OSError as exc: - print(f"error: cannot write {args.json_path}: {getattr(exc, 'strerror', None) or exc}", file=sys.stderr) - return 2 - finally: - if staged is not None: - with suppress(OSError): - os.chmod(staged, 0o600) - os.unlink(staged) - print(format_report(report)) - if args.json_path: - print(f"wrote: {args.json_path}") - return 0 - - -if __name__ == "__main__": - try: # a redirected stdout is strict ANSI code page under -I; write '?' for what it cannot encode - sys.stdout.reconfigure(errors="replace") - except (AttributeError, ValueError, OSError): - pass - sys.exit(main()) diff --git a/tools/glb_skinning.py b/tools/glb_skinning.py deleted file mode 100644 index 17dc6336b..000000000 --- a/tools/glb_skinning.py +++ /dev/null @@ -1,1160 +0,0 @@ -"""Validate the skinning data in a binary glTF 2.0 (.glb) file. - -Usage: - python -I tools/glb_skinning.py [--json report.json] - -The tool parses the GLB container itself (12-byte header, JSON chunk, optional -BIN chunk, 4-byte padding), then checks every skin and every mesh primitive: - -* skin names, unique joint nodes, joint counts and inverseBindMatrices counts, -* the inverseBindMatrices accessor type and finite values, -* which mesh primitives carry skinning data and which are static, -* consecutive JOINTS_n/WEIGHTS_n pairs starting at 0, accessor types and vertex counts, -* per-vertex weight sums, handled as FLOAT, normalized UNSIGNED_BYTE or - normalized UNSIGNED_SHORT (exact integer sums for all-quantized sets), -* joint-index ranges and out-of-range counts, -* non-finite POSITION, weight and inverseBindMatrices values, -* the POSITION bounding box, computed from the accessor data. - -Missing optional fields are reported as null; they are never filled in with a -guess. A malformed container, a file with no skin, or a skin whose -inverseBindMatrices count differs from its joint count exits nonzero. Structural -problems also exit nonzero with a one-line ``ERROR:`` message. - -Each joint's inverse bind matrix must have the affine fourth row (0, 0, 0, 1). - -Only the standard library is used, and the input is read, never modified. -""" -from __future__ import annotations - -import argparse -import json -import math -import os -import re -import struct -import sys - -TOOLS_DIR = os.path.dirname(os.path.abspath(__file__)) -if TOOLS_DIR not in sys.path: - sys.path.insert(0, TOOLS_DIR) - -from report_paths import same_report_path # noqa: E402 - -GLB_MAGIC = b"glTF" -GLB_VERSION = 2 -CHUNK_TYPE_JSON = 0x4E4F534A -CHUNK_TYPE_BIN = 0x004E4942 - -WEIGHT_SUM_TOLERANCE = 1e-4 -WEIGHT_RANGE_TOLERANCE = 1e-6 - -TYPE_COMPONENTS = { - "SCALAR": 1, - "VEC2": 2, - "VEC3": 3, - "VEC4": 4, - "MAT2": 4, - "MAT3": 9, - "MAT4": 16, -} - -COMPONENT_TYPES = { - 5120: ("b", 1, "BYTE"), - 5121: ("B", 1, "UNSIGNED_BYTE"), - 5122: ("h", 2, "SHORT"), - 5123: ("H", 2, "UNSIGNED_SHORT"), - 5125: ("I", 4, "UNSIGNED_INT"), - 5126: ("f", 4, "FLOAT"), -} - -MODE_NAMES = { - 0: "POINTS", - 1: "LINES", - 2: "LINE_LOOP", - 3: "LINE_STRIP", - 4: "TRIANGLES", - 5: "TRIANGLE_STRIP", - 6: "TRIANGLE_FAN", -} - -ATTRIBUTE_RE = re.compile(r"^(JOINTS|WEIGHTS)_(\d+)$") -_MISSING = object() - - -class GlbSkinError(ValueError): - """Raised when the GLB container or a required skin field is malformed.""" - - -def _is_int(value): - return isinstance(value, int) and not isinstance(value, bool) - - -def _int_field(obj, key, path, default=_MISSING, minimum=0): - value = obj.get(key, default) - if value is _MISSING: - raise GlbSkinError(f"{path}.{key} is missing") - if not _is_int(value): - raise GlbSkinError(f"{path}.{key} must be an integer") - if minimum is not None and value < minimum: - raise GlbSkinError(f"{path}.{key} must be >= {minimum}") - return value - - -def _list_field(obj, key, path): - value = obj.get(key) - if value is None: - return [] - if not isinstance(value, list): - raise GlbSkinError(f"{path}.{key} must be an array") - return value - - -def _name_field(obj, path, warnings): - value = obj.get("name") - if value is None: - return None - if not isinstance(value, str): - warnings.append(f"{path}.name is not a string") - return None - return value - - -def _number(value): - return _is_int(value) or isinstance(value, float) - - -def _finite_number(value): - """True for a finite JSON number; an integer too large for float is not one.""" - if not _number(value): - return False - try: - return math.isfinite(value) - except OverflowError: - return False - - -def _reject_json_constant(token): - raise ValueError(f"non-finite JSON number {token}") - - -def parse_glb(data): - """Return ``(gltf, bin_chunk, container)`` for a binary glTF 2.0 container.""" - if not isinstance(data, (bytes, bytearray, memoryview)): - raise GlbSkinError("GLB data must be bytes-like") - raw = bytes(data) - if len(raw) < 12: - raise GlbSkinError(f"GLB too short for a header: {len(raw)} bytes") - - magic, version, total_length = struct.unpack_from("<4sII", raw, 0) - if magic != GLB_MAGIC: - raise GlbSkinError(f"not a GLB: magic is {magic!r}, expected {GLB_MAGIC!r}") - if version != GLB_VERSION: - raise GlbSkinError(f"unsupported GLB version {version}, expected {GLB_VERSION}") - if total_length != len(raw): - raise GlbSkinError(f"GLB length field says {total_length} bytes, file has {len(raw)}") - if total_length % 4: - raise GlbSkinError(f"GLB total length {total_length} is not 4-byte aligned") - - offset = 12 - json_chunk = None - bin_chunk = None - trailing_chunks = 0 - chunk_index = 0 - while offset < total_length: - if offset + 8 > total_length: - raise GlbSkinError("truncated GLB chunk header") - chunk_length, chunk_type = struct.unpack_from(" total_length: - raise GlbSkinError( - f"GLB chunk at {offset} declares {chunk_length} bytes, past the end of the file" - ) - payload = raw[start:end] - if chunk_index == 0: - if chunk_type != CHUNK_TYPE_JSON: - raise GlbSkinError( - f"first GLB chunk must be JSON (0x{CHUNK_TYPE_JSON:08X}), " - f"got 0x{chunk_type:08X}" - ) - json_chunk = payload - elif chunk_index == 1 and chunk_type == CHUNK_TYPE_BIN: - bin_chunk = payload - else: - if chunk_type == CHUNK_TYPE_JSON: - raise GlbSkinError("repeated JSON chunk in GLB") - if chunk_type == CHUNK_TYPE_BIN: - raise GlbSkinError("repeated BIN chunk in GLB") - trailing_chunks += 1 - offset = end - chunk_index += 1 - - if json_chunk is None: - raise GlbSkinError("GLB has no JSON chunk") - try: - text = json_chunk.decode("utf-8") - gltf = json.loads(text, parse_constant=_reject_json_constant) - except RecursionError as exc: - raise GlbSkinError("invalid GLB JSON chunk: nesting is too deep") from exc - except (UnicodeDecodeError, ValueError) as exc: - raise GlbSkinError(f"invalid GLB JSON chunk: {exc}") from exc - if not isinstance(gltf, dict): - raise GlbSkinError("GLB JSON root must be an object") - - asset = gltf.get("asset") - asset_version = asset.get("version") if isinstance(asset, dict) else None - if isinstance(asset_version, str): - if not asset_version.startswith("2."): - raise GlbSkinError(f"unsupported glTF version {asset_version!r}") - else: - asset_version = None - - container = { - "version": version, - "asset_version": asset_version, - "bytes": total_length, - "json_bytes": len(json_chunk), - "bin_bytes": len(bin_chunk) if bin_chunk is not None else 0, - "bin_present": bin_chunk is not None, - "trailing_chunks": trailing_chunks, - } - return gltf, bin_chunk, container - - -class _Reader: - """Read accessor rows from the single embedded buffer of a GLB.""" - - def __init__(self, gltf, bin_chunk): - self.gltf = gltf - self.bin_chunk = bin_chunk - self.buffers = _list_field(gltf, "buffers", "glTF") - self.buffer_views = _list_field(gltf, "bufferViews", "glTF") - self.accessors = _list_field(gltf, "accessors", "glTF") - self.buffer_limit = self._buffer_limit() - - def _buffer_limit(self): - if not self.buffers: - return 0 - buffer0 = self.buffers[0] - if not isinstance(buffer0, dict): - raise GlbSkinError("buffers[0] is not an object") - if "uri" in buffer0: - raise GlbSkinError("external buffer URIs are not supported; expected an embedded GLB") - declared = _int_field(buffer0, "byteLength", "buffers[0]") - if self.bin_chunk is None: - raise GlbSkinError("buffer 0 is embedded but the GLB has no BIN chunk") - if declared > len(self.bin_chunk): - raise GlbSkinError( - f"buffers[0].byteLength {declared} exceeds the BIN chunk ({len(self.bin_chunk)} bytes)" - ) - return declared - - def accessor(self, index, path): - if not _is_int(index): - raise GlbSkinError(f"{path} must be an accessor index") - if index < 0 or index >= len(self.accessors): - raise GlbSkinError( - f"{path} references accessor {index}, but the GLB has {len(self.accessors)} accessors" - ) - accessor = self.accessors[index] - if not isinstance(accessor, dict): - raise GlbSkinError(f"accessors[{index}] is not an object") - return accessor - - def read(self, index, path): - accessor = self.accessor(index, path) - component_type = _int_field(accessor, "componentType", f"accessors[{index}]") - type_name = accessor.get("type") - if not isinstance(type_name, str): - raise GlbSkinError(f"accessors[{index}].type is missing") - if type_name not in TYPE_COMPONENTS: - raise GlbSkinError(f"accessors[{index}].type {type_name!r} is not a glTF accessor type") - count = _int_field(accessor, "count", f"accessors[{index}]") - normalized = accessor.get("normalized", False) - if not isinstance(normalized, bool): - raise GlbSkinError(f"accessors[{index}].normalized must be a boolean") - if "sparse" in accessor: - raise GlbSkinError(f"{path}: sparse accessor {index} is not supported") - if component_type not in COMPONENT_TYPES: - raise GlbSkinError(f"accessors[{index}].componentType {component_type} is not supported") - - fmt_char, component_size, component_name = COMPONENT_TYPES[component_type] - components = TYPE_COMPONENTS[type_name] - element_size = component_size * components - meta = { - "accessor": index, - "count": count, - "type": type_name, - "component_type": component_type, - "component_type_name": component_name, - "components": components, - "normalized": normalized, - "buffer_view": None, - "declared_min": None, - "declared_max": None, - } - for key, label in (("min", "declared_min"), ("max", "declared_max")): - if key not in accessor: - continue - value = accessor[key] - if ( - not isinstance(value, list) - or len(value) != components - or not all(_finite_number(v) for v in value) - ): - raise GlbSkinError( - f"accessors[{index}].{key} must be {components} finite number(s)" - ) - meta[label] = [float(v) for v in value] - - if "bufferView" not in accessor: - zero = 0.0 if component_type == 5126 else 0 - values = [tuple(zero for _ in range(components)) for _ in range(count)] - return values, meta - - view_index = _int_field(accessor, "bufferView", f"accessors[{index}]") - if view_index >= len(self.buffer_views): - raise GlbSkinError( - f"accessors[{index}].bufferView {view_index} is out of range " - f"({len(self.buffer_views)} bufferViews)" - ) - view = self.buffer_views[view_index] - if not isinstance(view, dict): - raise GlbSkinError(f"bufferViews[{view_index}] is not an object") - buffer_index = _int_field(view, "buffer", f"bufferViews[{view_index}]", default=0) - if buffer_index != 0: - raise GlbSkinError( - f"bufferViews[{view_index}].buffer {buffer_index} is not supported; " - "only embedded buffer 0 is read" - ) - view_offset = _int_field(view, "byteOffset", f"bufferViews[{view_index}]", default=0) - view_length = _int_field(view, "byteLength", f"bufferViews[{view_index}]") - if view_offset + view_length > self.buffer_limit: - raise GlbSkinError( - f"bufferViews[{view_index}] exceeds buffer 0 " - f"({view_offset}+{view_length} > {self.buffer_limit})" - ) - accessor_offset = _int_field(accessor, "byteOffset", f"accessors[{index}]", default=0) - stride = view.get("byteStride") - if stride is None: - stride = element_size - else: - if not _is_int(stride) or stride < element_size: - raise GlbSkinError( - f"bufferViews[{view_index}].byteStride must be an integer >= {element_size}" - ) - if stride % component_size: - raise GlbSkinError( - f"bufferViews[{view_index}].byteStride {stride} is not a multiple " - f"of the component size {component_size}" - ) - if count: - last_end = accessor_offset + (count - 1) * stride + element_size - if last_end > view_length: - raise GlbSkinError( - f"accessors[{index}] needs {last_end} bytes of bufferViews[{view_index}], " - f"which has {view_length}" - ) - - if self.buffer_limit == 0: - raise GlbSkinError(f"accessors[{index}] needs buffer 0, but the GLB has no embedded buffer") - data = self.bin_chunk[: self.buffer_limit] - unpacker = struct.Struct("<" + fmt_char * components) - base = view_offset + accessor_offset - values = [] - for i in range(count): - values.append(unpacker.unpack_from(data, base + i * stride)) - meta["buffer_view"] = view_index - return values, meta - - -def _normalized(value, component_type): - if component_type == 5121: - return value / 255.0 - if component_type == 5123: - return value / 65535.0 - if component_type == 5120: - return max(value / 127.0, -1.0) - if component_type == 5122: - return max(value / 32767.0, -1.0) - return float(value) - - -def _mesh_label(mesh_index, mesh_name): - suffix = f" {json.dumps(mesh_name)}" if mesh_name is not None else "" - return f"mesh[{mesh_index}]{suffix}" - - -def _primitive_label(mesh_index, mesh_name, primitive_index): - return f"{_mesh_label(mesh_index, mesh_name)} primitive[{primitive_index}]" - - -def _skin_label(skin_index, skin_name): - suffix = f" {json.dumps(skin_name)}" if skin_name is not None else "" - return f"skin[{skin_index}]{suffix}" - - -def _bbox(values): - minimum = [math.inf, math.inf, math.inf] - maximum = [-math.inf, -math.inf, -math.inf] - non_finite = 0 - finite = 0 - for row in values: - for axis in range(3): - value = row[axis] - if not math.isfinite(value): - non_finite += 1 - continue - finite += 1 - if value < minimum[axis]: - minimum[axis] = value - if value > maximum[axis]: - maximum[axis] = value - if not finite: - return None, None, non_finite - return minimum, maximum, non_finite - - -def _validate_skins(gltf, reader, warnings, errors): - nodes = _list_field(gltf, "nodes", "glTF") - skins = _list_field(gltf, "skins", "glTF") - reports = [] - if not skins: - errors.append("no skin found in GLB") - return reports - - for skin_index, skin in enumerate(skins): - path = f"skins[{skin_index}]" - if not isinstance(skin, dict): - raise GlbSkinError(f"{path} is not an object") - name = _name_field(skin, path, warnings) - joints_present = "joints" in skin - joints = _list_field(skin, "joints", path) - if not joints: - errors.append( - f"{_skin_label(skin_index, name)} has " - f"{'no joints' if joints_present else 'no joints field'}" - ) - seen_joints = set() - for joint_offset, joint in enumerate(joints): - if not _is_int(joint): - raise GlbSkinError(f"{path}.joints[{joint_offset}] must be an integer") - if joint in seen_joints: - errors.append(f"{path}.joints[{joint_offset}]: duplicate joint node {joint}") - seen_joints.add(joint) - if joint < 0 or joint >= len(nodes): - errors.append( - f"{_skin_label(skin_index, name)} joint {joint_offset} references " - f"node {joint}, but the GLB has {len(nodes)} nodes" - ) - - skeleton = skin.get("skeleton") - if skeleton is not None: - if not _is_int(skeleton): - raise GlbSkinError(f"{path}.skeleton must be an integer") - if skeleton < 0 or skeleton >= len(nodes): - errors.append( - f"{_skin_label(skin_index, name)} skeleton references node {skeleton}, " - f"but the GLB has {len(nodes)} nodes" - ) - - inverse = { - "present": False, - "accessor": None, - "count": None, - "type": None, - "component_type": None, - "normalized": None, - "non_finite_count": 0, - } - inverse_index = skin.get("inverseBindMatrices") - if inverse_index is None: - warnings.append( - f"{_skin_label(skin_index, name)} has no inverseBindMatrices; " - "the glTF default is identity and was not assumed here" - ) - else: - if not _is_int(inverse_index): - raise GlbSkinError(f"{path}.inverseBindMatrices must be an accessor index") - values, meta = reader.read(inverse_index, f"skin[{skin_index}].inverseBindMatrices") - inverse.update({ - "present": True, - "accessor": meta["accessor"], - "count": meta["count"], - "type": meta["type"], - "component_type": meta["component_type"], - "normalized": meta["normalized"], - }) - if meta["count"] != len(joints): - errors.append( - f"{_skin_label(skin_index, name)}: inverseBindMatrices count " - f"{meta['count']} != joint count {len(joints)}" - ) - if meta["type"] != "MAT4": - errors.append( - f"{_skin_label(skin_index, name)}: inverseBindMatrices accessor type " - f"{meta['type']!r} is not MAT4" - ) - if meta["component_type"] != 5126: - errors.append( - f"{_skin_label(skin_index, name)}: inverseBindMatrices component type " - f"{meta['component_type_name']} is not FLOAT" - ) - bad = 0 - first_non_affine = None - for index, row in enumerate(values): - bad += sum(1 for value in row if not math.isfinite(value)) - # glTF stores MAT4 columns consecutively; translation is in the last column. - if (first_non_affine is None and index < len(joints) and meta["type"] == "MAT4" - and row[3::4] != (0.0, 0.0, 0.0, 1.0)): - first_non_affine = index - if first_non_affine is not None: - errors.append( - f"{_skin_label(skin_index, name)}: inverseBindMatrices[{first_non_affine}] " - "fourth row must be [0, 0, 0, 1]" - ) - inverse["non_finite_count"] = bad - if bad: - errors.append( - f"{_skin_label(skin_index, name)}: inverseBindMatrices has " - f"{bad} non-finite value(s)" - ) - - reports.append({ - "index": skin_index, - "name": name, - "joints_present": joints_present, - "joint_count": len(joints), - "joints": [int(joint) if _is_int(joint) else joint for joint in joints], - "skeleton": skeleton, - "inverse_bind_matrices": inverse, - }) - return reports - - -def _node_bindings(gltf, skin_count, mesh_count, warnings, errors): - nodes = _list_field(gltf, "nodes", "glTF") - bindings = {} - for node_index, node in enumerate(nodes): - path = f"nodes[{node_index}]" - if not isinstance(node, dict): - raise GlbSkinError(f"{path} is not an object") - mesh_index = node.get("mesh") - skin_index = node.get("skin") - if mesh_index is not None: - if not _is_int(mesh_index): - raise GlbSkinError(f"{path}.mesh must be an integer") - if mesh_index < 0 or mesh_index >= mesh_count: - errors.append( - f"{path} references mesh {mesh_index}, but the GLB has {mesh_count} meshes" - ) - mesh_index = None - if skin_index is not None: - if not _is_int(skin_index): - raise GlbSkinError(f"{path}.skin must be an integer") - if skin_index < 0 or skin_index >= skin_count: - if skin_count: - errors.append( - f"{path} references skin {skin_index}, " - f"but the GLB has {skin_count} skins" - ) - # With no skins at all the single "no skin found" error is enough. - skin_index = None - if mesh_index is None: - if skin_index is not None: - warnings.append(f"{path} has a skin but no mesh") - continue - bindings.setdefault(mesh_index, []).append({ - "node": node_index, - "skin": skin_index, - }) - return bindings - - -def _read_weight_set(reader, accessor_index, primitive_path, set_index, errors): - values, meta = reader.read(accessor_index, f"{primitive_path}.WEIGHTS_{set_index}") - if meta["type"] != "VEC4": - raise GlbSkinError( - f"{primitive_path}.WEIGHTS_{set_index} accessor type is {meta['type']!r}, expected VEC4" - ) - component_type = meta["component_type"] - if component_type not in (5126, 5121, 5123): - errors.append( - f"{primitive_path}.WEIGHTS_{set_index}: component type " - f"{meta['component_type_name']} is not FLOAT, UNSIGNED_BYTE or UNSIGNED_SHORT" - ) - if component_type in (5121, 5123) and not meta["normalized"]: - errors.append( - f"{primitive_path}.WEIGHTS_{set_index}: integer weights are not normalized" - ) - if component_type == 5126 and meta["normalized"]: - errors.append( - f"{primitive_path}.WEIGHTS_{set_index}: FLOAT weights must not be normalized" - ) - rows = [] - for row in values: - if meta["normalized"] and component_type in (5121, 5123): - rows.append([_normalized(value, component_type) for value in row]) - else: - rows.append([float(value) for value in row]) - finite = [value for row in rows for value in row if math.isfinite(value)] - non_finite = sum(1 for row in rows for value in row if not math.isfinite(value)) - report = { - "set": set_index, - "accessor": meta["accessor"], - "count": meta["count"], - "component_type": meta["component_type"], - "component_type_name": meta["component_type_name"], - "normalized": meta["normalized"], - "min": min(finite) if finite else None, - "max": max(finite) if finite else None, - "non_finite_count": non_finite, - } - # Preserve integer sums before dequantization: u8 * 257 and u16 share denominator 65535. - units = None - if meta["normalized"] and component_type in (5121, 5123): - factor = 257 if component_type == 5121 else 1 - units = [sum(row) * factor for row in values] - return rows, meta, report, units - - -def _read_joint_set(reader, accessor_index, primitive_path, set_index, errors): - values, meta = reader.read(accessor_index, f"{primitive_path}.JOINTS_{set_index}") - if meta["type"] != "VEC4": - raise GlbSkinError( - f"{primitive_path}.JOINTS_{set_index} accessor type is {meta['type']!r}, expected VEC4" - ) - if meta["component_type"] not in (5121, 5123): - raise GlbSkinError( - f"{primitive_path}.JOINTS_{set_index}: component type " - f"{meta['component_type_name']} is not UNSIGNED_BYTE or UNSIGNED_SHORT" - ) - if meta["normalized"]: - errors.append(f"{primitive_path}.JOINTS_{set_index}: joint indices must not be normalized") - indices = [[int(value) for value in row] for row in values] - flat = [value for row in indices for value in row] - report = { - "set": set_index, - "accessor": meta["accessor"], - "count": meta["count"], - "component_type": meta["component_type"], - "component_type_name": meta["component_type_name"], - "min": min(flat) if flat else None, - "max": max(flat) if flat else None, - "out_of_range": None, - "bindings": [], - } - return indices, meta, report - - -def _validate_primitive(reader, primitive, mesh_index, mesh_name, primitive_index, - bindings, skins, warnings, errors): - path = _primitive_label(mesh_index, mesh_name, primitive_index) - if not isinstance(primitive, dict): - raise GlbSkinError(f"{path} is not an object") - attributes = primitive.get("attributes") - if not isinstance(attributes, dict): - warnings.append(f"{path} has no attributes object") - attributes = {} - - mode = primitive.get("mode") - if mode is not None and not _is_int(mode): - raise GlbSkinError(f"{path}.mode must be an integer") - mode_name = MODE_NAMES.get(mode) if mode is not None else None - - position_report = { - "accessor": None, - "count": None, - "type": None, - "component_type": None, - "bbox_min": None, - "bbox_max": None, - "declared_min": None, - "declared_max": None, - "non_finite_count": 0, - } - position_count = None - non_finite_positions = 0 - if "POSITION" not in attributes: - warnings.append(f"{path} has no POSITION accessor; its bounding box is unknown") - else: - values, meta = reader.read(attributes["POSITION"], f"{path}.POSITION") - if meta["type"] != "VEC3": - raise GlbSkinError( - f"{path}.POSITION accessor type is {meta['type']!r}, expected VEC3" - ) - minimum, maximum, non_finite_positions = _bbox(values) - position_count = meta["count"] - position_report.update({ - "accessor": meta["accessor"], - "count": meta["count"], - "type": meta["type"], - "component_type": meta["component_type_name"], - "bbox_min": minimum, - "bbox_max": maximum, - "declared_min": meta["declared_min"], - "declared_max": meta["declared_max"], - "non_finite_count": non_finite_positions, - }) - if non_finite_positions: - errors.append( - f"{path}.POSITION has {non_finite_positions} non-finite component(s)" - ) - - set_numbers = sorted({ - int(match.group(2)) - for key in attributes - for match in [ATTRIBUTE_RE.match(key)] - if match - }) - if any(number != expected for expected, number in enumerate(set_numbers)): - errors.append(f"{path}: JOINTS/WEIGHTS sets must be consecutive starting at 0") - joint_reports = [] - weight_reports = [] - weight_rows_by_set = {} - quantized_units_by_set = {} - joint_rows_by_set = {} - first_set_count = None - for set_number in set_numbers: - joint_key = f"JOINTS_{set_number}" - weight_key = f"WEIGHTS_{set_number}" - if joint_key not in attributes: - errors.append(f"{path} has {weight_key} but no {joint_key}") - if weight_key not in attributes: - errors.append(f"{path} has {joint_key} but no {weight_key}") - if joint_key in attributes: - joint_rows, meta, joint_report = _read_joint_set( - reader, attributes[joint_key], path, set_number, errors - ) - joint_rows_by_set[set_number] = joint_rows - first_set_count = meta["count"] if first_set_count is None else first_set_count - joint_reports.append(joint_report) - if weight_key in attributes: - weight_rows, meta, weight_report, units = _read_weight_set( - reader, attributes[weight_key], path, set_number, errors - ) - weight_rows_by_set[set_number] = weight_rows - if units is not None: - quantized_units_by_set[set_number] = units - first_set_count = meta["count"] if first_set_count is None else first_set_count - weight_reports.append(weight_report) - - if position_count is None: - vertex_count = first_set_count - else: - vertex_count = position_count - for set_number, rows in weight_rows_by_set.items(): - if vertex_count is not None and len(rows) != vertex_count: - errors.append( - f"{path}.WEIGHTS_{set_number} has {len(rows)} vertices, " - f"expected {vertex_count}" - ) - for set_number, rows in joint_rows_by_set.items(): - if vertex_count is not None and len(rows) != vertex_count: - errors.append( - f"{path}.JOINTS_{set_number} has {len(rows)} vertices, " - f"expected {vertex_count}" - ) - - node_skins = sorted({binding["skin"] for binding in bindings - if binding["skin"] is not None}) - has_skin_attributes = bool(set_numbers) - skinned = has_skin_attributes or bool(node_skins) - if skinned and not has_skin_attributes: - errors.append(f"{path} is bound to a skin but has no JOINTS_0/WEIGHTS_0") - if has_skin_attributes and not node_skins and skins: - warnings.append( - f"{path} has JOINTS_0/WEIGHTS_0 but no node binds it to a skin; " - f"checked against the {len(skins)} skin(s) in the file" - ) - if node_skins: - checked_skins = node_skins - skin_source = "node" - elif has_skin_attributes: - checked_skins = list(range(len(skins))) - skin_source = "file" if skins else None - else: - checked_skins = [] - skin_source = None - - binding_limits = [] - for skin_index in checked_skins: - skin = skins[skin_index] - binding_limits.append({ - "skin": skin_index, - "name": skin["name"], - "joint_count": skin["joint_count"], - }) - - joint_min = None - joint_max = None - out_of_range_total = 0 - for joint_report in joint_reports: - rows = joint_rows_by_set[joint_report["set"]] - flat = [value for row in rows for value in row] - if flat: - report_min = min(flat) - report_max = max(flat) - joint_min = report_min if joint_min is None else min(joint_min, report_min) - joint_max = report_max if joint_max is None else max(joint_max, report_max) - joint_report["min"] = report_min - joint_report["max"] = report_max - for binding in binding_limits: - count = binding["joint_count"] - bad_count = 0 - first_bad = None - for vertex, row in enumerate(rows): - for component, value in enumerate(row): - if value < 0 or value >= count: - bad_count += 1 - if first_bad is None: - first_bad = (vertex, component, value) - binding_report = { - "skin": binding["skin"], - "name": binding["name"], - "joint_count": count, - "out_of_range": bad_count, - } - joint_report["bindings"].append(binding_report) - if first_bad is not None: - vertex, component, value = first_bad - errors.append( - f"{path} vertex {vertex} joint component {component}: joint index " - f"{value} is outside {_skin_label(binding['skin'], binding['name'])} " - f"({count} joints)" - ) - if binding_limits: - tightest = min(binding["joint_count"] for binding in binding_limits) - joint_report["out_of_range"] = sum( - 1 for row in rows for value in row if value < 0 or value >= tightest - ) - out_of_range_total += joint_report["out_of_range"] - else: - joint_report["out_of_range"] = None - - weight_min = None - weight_max = None - bad_weight_sums = 0 - first_bad_sum = None - non_finite_weights = 0 - out_of_range_weights = 0 - first_bad_weight = None - max_influences = 0 - for set_number in sorted(weight_rows_by_set): - for vertex, row in enumerate(weight_rows_by_set[set_number]): - for value in row: - if not math.isfinite(value): - non_finite_weights += 1 - elif value < -WEIGHT_RANGE_TOLERANCE or value > 1.0 + WEIGHT_RANGE_TOLERANCE: - out_of_range_weights += 1 - if first_bad_weight is None: - first_bad_weight = (set_number, vertex, value) - common_weight_count = min( - (len(rows) for rows in weight_rows_by_set.values()), default=0 - ) - all_quantized = bool(weight_rows_by_set) and len(quantized_units_by_set) == len(weight_rows_by_set) - sum_tolerance = 0.0 if all_quantized else WEIGHT_SUM_TOLERANCE - for vertex in range(common_weight_count): - values = [] - for set_number in sorted(weight_rows_by_set): - values.extend(weight_rows_by_set[set_number][vertex]) - influences = sum(1 for value in values if math.isfinite(value) and value != 0.0) - max_influences = max(max_influences, influences) - if values and all(math.isfinite(value) for value in values): - total = sum(values) - weight_min = total if weight_min is None else min(weight_min, total) - weight_max = total if weight_max is None else max(weight_max, total) - bad_sum = (sum(units[vertex] for units in quantized_units_by_set.values()) != 65535 - if all_quantized else abs(total - 1.0) > sum_tolerance) - if bad_sum: - bad_weight_sums += 1 - if first_bad_sum is None: - first_bad_sum = (vertex, total) - if first_bad_sum is not None: - vertex, total = first_bad_sum - suffix = f"; {bad_weight_sums} vertices bad" if bad_weight_sums > 1 else "" - errors.append( - f"{path} vertex {vertex}: weight sum {total:.7g} != 1 " - f"(tolerance {sum_tolerance:g}){suffix}" - ) - if non_finite_weights: - errors.append(f"{path} has {non_finite_weights} non-finite weight value(s)") - if out_of_range_weights: - set_number, vertex, value = first_bad_weight - errors.append( - f"{path} WEIGHTS_{set_number} vertex {vertex}: weight {value:.7g} is outside [0, 1] " - f"({out_of_range_weights} value(s) bad)" - ) - return { - "index": primitive_index, - "mode": mode, - "mode_name": mode_name, - "skinned": skinned, - "skins": checked_skins, - "skin_source": skin_source, - "vertex_count": vertex_count, - "position": position_report, - "joint_sets": joint_reports, - "weight_sets": weight_reports, - "max_influences": max_influences, - "weight_sum": { - "min": weight_min, - "max": weight_max, - "bad_count": bad_weight_sums, - "tolerance": sum_tolerance, - }, - "non_finite": { - "positions": non_finite_positions, - "weights": non_finite_weights, - "total": non_finite_positions + non_finite_weights, - }, - "_joint_min": joint_min, - "_joint_max": joint_max, - "_out_of_range_joints": out_of_range_total, - } - - -def analyze_glb(data): - """Validate a GLB and return a JSON-serializable report.""" - gltf, bin_chunk, container = parse_glb(data) - reader = _Reader(gltf, bin_chunk) - warnings = [] - errors = [] - if container["asset_version"] is None: - warnings.append("asset.version is missing; the GLB header still says version 2") - skins = _validate_skins(gltf, reader, warnings, errors) - meshes = _list_field(gltf, "meshes", "glTF") - mesh_bindings = _node_bindings(gltf, len(skins), len(meshes), warnings, errors) - if not meshes: - warnings.append("GLB has no meshes") - mesh_reports = [] - summary = { - "skin_count": len(skins), - "skin_names": [skin["name"] for skin in skins], - "mesh_count": len(meshes), - "primitive_count": 0, - "skinned_primitive_count": 0, - "static_primitive_count": 0, - "max_influences": None, - "weight_sum_min": None, - "weight_sum_max": None, - "bad_weight_sum_count": 0, - "joint_index_min": None, - "joint_index_max": None, - "out_of_range_joint_count": 0, - "non_finite_value_count": sum( - skin["inverse_bind_matrices"]["non_finite_count"] for skin in skins - ), - } - for mesh_index, mesh in enumerate(meshes): - path = f"meshes[{mesh_index}]" - if not isinstance(mesh, dict): - raise GlbSkinError(f"{path} is not an object") - name = _name_field(mesh, path, warnings) - primitives = _list_field(mesh, "primitives", path) - if not primitives: - warnings.append(f"{_mesh_label(mesh_index, name)} has no primitives") - bindings = mesh_bindings.get(mesh_index, []) - if not bindings: - warnings.append(f"{_mesh_label(mesh_index, name)} is not referenced by any node") - primitive_reports = [] - for primitive_index, primitive in enumerate(primitives): - report = _validate_primitive( - reader, primitive, mesh_index, name, primitive_index, - bindings, skins, warnings, errors, - ) - primitive_reports.append(report) - summary["primitive_count"] += 1 - if report["skinned"]: - summary["skinned_primitive_count"] += 1 - else: - summary["static_primitive_count"] += 1 - if summary["max_influences"] is None: - summary["max_influences"] = report["max_influences"] - else: - summary["max_influences"] = max( - summary["max_influences"], report["max_influences"] - ) - weight_sum = report["weight_sum"] - if weight_sum["min"] is not None: - if summary["weight_sum_min"] is None: - summary["weight_sum_min"] = weight_sum["min"] - summary["weight_sum_max"] = weight_sum["max"] - else: - summary["weight_sum_min"] = min(summary["weight_sum_min"], weight_sum["min"]) - summary["weight_sum_max"] = max(summary["weight_sum_max"], weight_sum["max"]) - summary["bad_weight_sum_count"] += weight_sum["bad_count"] - joint_min = report["_joint_min"] - joint_max = report["_joint_max"] - if joint_min is not None: - summary["joint_index_min"] = ( - joint_min if summary["joint_index_min"] is None - else min(summary["joint_index_min"], joint_min) - ) - summary["joint_index_max"] = ( - joint_max if summary["joint_index_max"] is None - else max(summary["joint_index_max"], joint_max) - ) - summary["out_of_range_joint_count"] += report["_out_of_range_joints"] - summary["non_finite_value_count"] += report["non_finite"]["total"] - for key in ("_joint_min", "_joint_max", "_out_of_range_joints"): - report.pop(key, None) - mesh_reports.append({ - "index": mesh_index, - "name": name, - "primitives_present": "primitives" in mesh, - "primitive_count": len(primitives), - "node_references": bindings, - "primitives": primitive_reports, - }) - - return { - "ok": not errors, - "container": container, - "skins": skins, - "meshes": mesh_reports, - "summary": summary, - "warnings": warnings, - "errors": errors, - } - - -def _fmt(value): - if value is None: - return "null" - if isinstance(value, float): - return f"{value:.7g}" - return str(value) - - -def _fmt_list(values): - if values is None: - return "null" - return "[" + ", ".join(_fmt(value) for value in values) + "]" - - -def format_report(report): - """Render the report as short human-readable lines.""" - container = report["container"] - lines = [ - f"GLB: {container['bytes']} bytes, glTF {container['version']}, " - f"JSON {container['json_bytes']} bytes, BIN {container['bin_bytes']} bytes" - ] - summary = report["summary"] - lines.append(f"skins: {summary['skin_count']}") - for skin in report["skins"]: - name = json.dumps(skin["name"]) if skin["name"] is not None else "(unnamed)" - inverse = skin["inverse_bind_matrices"] - inverse_text = "missing" if not inverse["present"] else _fmt(inverse["count"]) - lines.append( - f" skin[{skin['index']}] {name}: {skin['joint_count']} joint(s), " - f"inverseBindMatrices {inverse_text}" - ) - lines.append(f"meshes: {summary['mesh_count']}") - for mesh in report["meshes"]: - name = json.dumps(mesh["name"]) if mesh["name"] is not None else "(unnamed)" - lines.append(f" mesh[{mesh['index']}] {name}: {mesh['primitive_count']} primitive(s)") - for primitive in mesh["primitives"]: - kind = "skinned" if primitive["skinned"] else "static" - if primitive["skins"]: - kind += " via skin " + ", ".join( - str(index) for index in primitive["skins"] - ) - lines.append(f" primitive[{primitive['index']}]: {kind}, " - f"{_fmt(primitive['vertex_count'])} vertices, " - f"max {primitive['max_influences']} influence(s)") - weight_sum = primitive["weight_sum"] - lines.append( - f" weight sums: {_fmt(weight_sum['min'])}..{_fmt(weight_sum['max'])}, " - f"bad {weight_sum['bad_count']}" - ) - if primitive["joint_sets"]: - joint_min = min( - (joint_set["min"] for joint_set in primitive["joint_sets"] - if joint_set["min"] is not None), - default=None, - ) - joint_max = max( - (joint_set["max"] for joint_set in primitive["joint_sets"] - if joint_set["max"] is not None), - default=None, - ) - out_of_range = sum( - joint_set["out_of_range"] or 0 for joint_set in primitive["joint_sets"] - ) - lines.append( - f" joint indices: {_fmt(joint_min)}..{_fmt(joint_max)}, " - f"out of range {out_of_range}" - ) - lines.append( - f" POSITION bbox: {_fmt_list(primitive['position']['bbox_min'])} .. " - f"{_fmt_list(primitive['position']['bbox_max'])}, " - f"non-finite {primitive['non_finite']['total']}" - ) - lines.append( - "summary: " - f"{summary['skinned_primitive_count']} skinned, " - f"{summary['static_primitive_count']} static primitive(s); " - f"max influences {_fmt(summary['max_influences'])}; " - f"weight sums {_fmt(summary['weight_sum_min'])}..{_fmt(summary['weight_sum_max'])} " - f"({summary['bad_weight_sum_count']} bad); " - f"joints {_fmt(summary['joint_index_min'])}..{_fmt(summary['joint_index_max'])} " - f"({summary['out_of_range_joint_count']} out of range); " - f"non-finite {summary['non_finite_value_count']}" - ) - return "\n".join(lines) - - -def write_json(path, report): - """Write LF-only JSON without ever guessing values that JSON cannot hold.""" - payload = json.dumps(report, indent=2, ensure_ascii=False, allow_nan=False) + "\n" - with open(path, "wb") as handle: - handle.write(payload.encode("utf-8")) - - -def main(argv=None): - parser = argparse.ArgumentParser( - description="Validate the skinning data in a binary glTF 2.0 (.glb) file." - ) - parser.add_argument("glb", metavar="input.glb", help="input binary glTF file") - parser.add_argument("--json", metavar="FILE", help="write the report as LF-only JSON") - args = parser.parse_args(argv) - - if args.json and same_report_path(args.glb, args.json): - print("ERROR: --json must not overwrite the input GLB", file=sys.stderr) - return 2 - try: - with open(args.glb, "rb") as handle: - data = handle.read() - except OSError as exc: - detail = exc.strerror or str(exc) - print(f"ERROR: cannot read {args.glb}: {detail}", file=sys.stderr) - return 1 - try: - report = analyze_glb(data) - except (ValueError, TypeError, struct.error) as exc: - # Malformed JSON types and bad offsets must not escape as a traceback. - print(f"ERROR: {exc}", file=sys.stderr) - return 1 - - print(format_report(report)) - if args.json: - try: - write_json(args.json, report) - except (OSError, ValueError) as exc: - print(f"ERROR: cannot write report {args.json}: {exc}", file=sys.stderr) - return 2 - for message in report["errors"]: - print(f"ERROR: {message}", file=sys.stderr) - return 0 if report["ok"] else 1 - - -if __name__ == "__main__": - try: # a redirected stdout is strict ANSI code page under -I; write '?' for what it cannot encode - sys.stdout.reconfigure(errors="replace") - except (AttributeError, ValueError, OSError): - pass - sys.exit(main()) diff --git a/tools/glb_writer.py b/tools/glb_writer.py deleted file mode 100644 index ded546fea..000000000 --- a/tools/glb_writer.py +++ /dev/null @@ -1,1409 +0,0 @@ -"""Pure standard-library Wavefront OBJ parser and binary glTF 2.0 (.glb) writer. - -Usage: - python -I tools/glb_writer.py [--up z|y] - -Reads a Wavefront OBJ file (positions, UVs, normals, faces, groups, objects, materials), -converts coordinates from RAGE Z-up to glTF Y-up (or keeps Y-up), computes smooth -area-weighted vertex normals when explicit normals are absent, and serializes a strict -glTF 2.0 binary (.glb) container with optional deduplicated embedded PNG textures. -Simple planar polygon faces may be convex or concave. -""" -from __future__ import annotations - -import argparse -import array -import hashlib -import itertools -import json -import math -import os -import struct -import sys -import tempfile -import time -from collections.abc import Iterable, Iterator - -sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) -from file_mode import published_mode # noqa: E402 - -GLB_MAGIC = b"glTF" -GLB_VERSION = 2 -CHUNK_TYPE_JSON = 0x4E4F534A # b"JSON" -CHUNK_TYPE_BIN = 0x004E4942 # b"BIN\x00" - -TARGET_ARRAY_BUFFER = 34962 -TARGET_ELEMENT_ARRAY_BUFFER = 34963 - -COMPONENT_UNSIGNED_SHORT = 5123 -COMPONENT_UNSIGNED_INT = 5125 -COMPONENT_FLOAT = 5126 - -MODE_TRIANGLES = 4 - -DEFAULT_CLAY_COLOR = [0.75, 0.75, 0.75, 1.0] -DEFAULT_TEXTURED_COLOR = [1.0, 1.0, 1.0, 1.0] -DEFAULT_METALLIC = 0.0 -DEFAULT_ROUGHNESS = 0.85 - -ALPHA_MODES = ("OPAQUE", "MASK", "BLEND") - -DEFAULT_SAMPLER = { - "magFilter": 9729, # LINEAR - "minFilter": 9987, # LINEAR_MIPMAP_LINEAR - "wrapS": 10497, # REPEAT - "wrapT": 10497, # REPEAT -} - -_NEEDS_BYTESWAP = sys.byteorder != "little" -_UINT16_CODE = "H" if array.array("H").itemsize == 2 else None -_UINT32_CODE = "I" if array.array("I").itemsize == 4 else ("L" if array.array("L").itemsize == 4 else None) -_FLOAT32_CODE = "f" if array.array("f").itemsize == 4 else None - - -class GlbError(ValueError): - """Raised when OBJ/primitive data or GLB binary validation fails.""" - - -def _clean_zero(v: float) -> float: - return 0.0 if v == 0.0 else v - - -def _normalize3(nx: float, ny: float, nz: float) -> tuple[float, float, float]: - if not (math.isfinite(nx) and math.isfinite(ny) and math.isfinite(nz)): - return (0.0, 1.0, 0.0) - length = math.hypot(nx, ny, nz) - if length == 0.0: - return (0.0, 1.0, 0.0) - if length < sys.float_info.min or not math.isfinite(length): - # Scaling first keeps an unrepresentable or subnormal length from changing the direction. - scale = max(abs(nx), abs(ny), abs(nz)) - nx, ny, nz = nx / scale, ny / scale, nz / scale - length = math.hypot(nx, ny, nz) - return (_clean_zero(nx / length), _clean_zero(ny / length), _clean_zero(nz / length)) - - -def _compute_smooth_normals( - positions: list[tuple[float, float, float]], - indices: Iterable[int], -) -> list[tuple[float, float, float]]: - """Compute area-weighted smooth vertex normals with (0, 1, 0) fallback.""" - n = len(positions) - ax = [0.0] * n - ay = [0.0] * n - az = [0.0] * n - - index_iter = iter(indices) - for i0, i1, i2 in zip(index_iter, index_iter, index_iter): - p0 = positions[i0] - p1 = positions[i1] - p2 = positions[i2] - e1x = p1[0] - p0[0] - e1y = p1[1] - p0[1] - e1z = p1[2] - p0[2] - e2x = p2[0] - p0[0] - e2y = p2[1] - p0[1] - e2z = p2[2] - p0[2] - # Cross product magnitude equals 2 * triangle area -> exact area weighting. - cx = e1y * e2z - e1z * e2y - cy = e1z * e2x - e1x * e2z - cz = e1x * e2y - e1y * e2x - if not (math.isfinite(cx) and math.isfinite(cy) and math.isfinite(cz)): - continue - ax[i0] += cx - ay[i0] += cy - az[i0] += cz - ax[i1] += cx - ay[i1] += cy - az[i1] += cz - ax[i2] += cx - ay[i2] += cy - az[i2] += cz - - normals: list[tuple[float, float, float]] = [] - append = normals.append - for i in range(n): - append(_normalize3(ax[i], ay[i], az[i])) - return normals - - -def _resolve_obj_index(token: str, count: int) -> int | None: - if not token: - return None - try: - idx = int(token) - except ValueError: - return None - if idx > 0: - resolved = idx - 1 - elif idx < 0: - resolved = count + idx - else: - return None - if 0 <= resolved < count: - return resolved - return None - - -def _triangulate_face(points: list[tuple[float, float, float]]) -> list[tuple[int, int, int]] | None: - """Return corner triples when the first-corner fan folds over or emits a zero-area triangle. - - None keeps an already valid fan or falls back to it if ear clipping cannot complete. - """ - # Project onto the plane with the largest signed area. Work relative to one - # corner so translating the mesh far from the origin does not affect the sum. - origin = points[0] - rel = [(x - origin[0], y - origin[1], z - origin[2]) for x, y, z in points] - edges = list(zip(rel, rel[1:] + rel[:1])) - planes = ((1, 2), (2, 0), (0, 1)) - areas = [sum(a[u] * b[v] - a[v] * b[u] for a, b in edges) for u, v in planes] - axis = max(range(3), key=lambda i: abs(areas[i])) - area = areas[axis] - if not area or not math.isfinite(area): - return None - u, v = planes[axis] - winding = 1 if area > 0 else -1 - xy = [(p[u], p[v]) for p in rel] - - def turn(a, b, c): - ax, ay = xy[a] - bx, by = xy[b] - cx, cy = xy[c] - return winding * ((bx - ax) * (cy - ay) - (by - ay) * (cx - ax)) - - if all(turn(0, i, i + 1) > 0 for i in range(1, len(points) - 1)): - return None - - # Clip ears in boundary order. A point on the ear's edge blocks it too: - # that corner may carry its own UV or normal and still needs a triangle. - ring = list(range(len(points))) - triangles = [] - while len(ring) > 3: - for i, b in enumerate(ring): - a, c = ring[i - 1], ring[(i + 1) % len(ring)] - if turn(a, b, c) <= 0: - continue - if any(turn(a, b, p) >= 0 and turn(b, c, p) >= 0 and turn(c, a, p) >= 0 - for p in ring if p not in (a, b, c)): - continue - triangles.append((a, b, c)) - del ring[i] - break - else: - return None - triangles.append(tuple(ring)) - return triangles - - -def _logical_obj_lines(text: str) -> Iterator[str]: - """Yield OBJ logical lines, joining trailing-backslash continuations with a space. - - A '#' starts an inline comment. A backslash inside that comment does not continue the line; - a backslash in the code before the comment does. - """ - pending = "" - for raw_line in text.splitlines(): - line = raw_line.rstrip() - if not line or line.lstrip().startswith("#"): - continue - code, _, _comment = line.partition("#") - code = code.rstrip() - if code.endswith("\\"): - pending += code[:-1].rstrip() + " " - continue - yield pending + code - pending = "" - if pending: - yield pending - - -def parse_obj( - text_or_path: str, - *, - is_path: bool = True, - up_axis: str = "z", - offset: tuple[float, float, float] = (0.0, 0.0, 0.0), - scale: float = 1.0, -) -> list[dict]: - """Parse Wavefront OBJ geometry into glTF-ready primitives. - - Groups primitives in order of appearance by (group_index, material_name), - converts coordinates to glTF Y-up, flips V for top-left UV origin, - deduplicates vertices per primitive, and synthesizes smooth area-weighted - normals within the primitive and OBJ smoothing group when explicit normals are missing. - """ - up = up_axis.lower() - if up not in ("z", "y"): - raise GlbError(f"unsupported up_axis: {up_axis!r} (expected 'z' or 'y')") - if len(offset) != 3: - raise GlbError(f"offset must have 3 components, got {len(offset)}") - ox, oy, oz = float(offset[0]), float(offset[1]), float(offset[2]) - sc = float(scale) - if not (math.isfinite(sc) and math.isfinite(ox) and math.isfinite(oy) and math.isfinite(oz)): - raise GlbError("scale and offset must be finite numbers") - - if is_path: - with open(text_or_path, "r", encoding="utf-8", errors="replace") as f: - text = f.read() - else: - text = text_or_path - - z_up = up == "z" - mirrored = sc < 0 - raw_v: list[tuple[float, float, float] | None] = [] - raw_vt: list[tuple[float, float]] = [] - raw_vn: list[tuple[float, float, float]] = [] - - raw_v_append = raw_v.append - raw_vt_append = raw_vt.append - raw_vn_append = raw_vn.append - - group_index = 0 - group_name = "" - saw_g = False - group_has_faces = False - material_name = "" - smoothing_group: int | None = None - flat_face_id = 0 - - # Preserve order of appearance for (group_index, material_name) primitives. - builders: dict[tuple[int, str], dict] = {} - - for raw_line in _logical_obj_lines(text.removeprefix("\ufeff")): - line = raw_line.strip() - if not line or line[0] == "#": - continue - - # Fast dispatch on the leading keyword. - parts = line.split() - cmd = parts[0] - - if cmd == "v": - if "#" in line: - parts = line.split("#", 1)[0].split() - if len(parts) < 4: - raw_v_append(None) - continue - try: - x = float(parts[1]) - y = float(parts[2]) - z = float(parts[3]) - except ValueError: - raw_v_append(None) - continue - if z_up: - px = x * sc + ox - py = z * sc + oy - pz = (-y) * sc + oz - else: - px = x * sc + ox - py = y * sc + oy - pz = z * sc + oz - if math.isfinite(px) and math.isfinite(py) and math.isfinite(pz): - raw_v_append((_clean_zero(px), _clean_zero(py), _clean_zero(pz))) - else: - raw_v_append(None) - - elif cmd == "vt": - if "#" in line: - parts = line.split("#", 1)[0].split() - if len(parts) < 2: - raw_vt_append((0.0, 0.0)) - continue - try: - u = float(parts[1]) - v = float(parts[2]) if len(parts) >= 3 else 0.0 - except ValueError: - raw_vt_append((0.0, 0.0)) - continue - v_gltf = 1.0 - v - if not math.isfinite(u): - u = 0.0 - if not math.isfinite(v_gltf): - v_gltf = 0.0 - raw_vt_append((_clean_zero(u), _clean_zero(v_gltf))) - - elif cmd == "vn": - if "#" in line: - parts = line.split("#", 1)[0].split() - if len(parts) < 4: - raw_vn_append((0.0, 1.0, 0.0)) - continue - try: - nx = float(parts[1]) - ny = float(parts[2]) - nz = float(parts[3]) - except ValueError: - raw_vn_append((0.0, 1.0, 0.0)) - continue - if z_up: - nx, ny, nz = nx, nz, -ny - if mirrored: - nx, ny, nz = -nx, -ny, -nz - raw_vn_append(_normalize3(nx, ny, nz)) - - elif cmd == "g": - if saw_g or group_has_faces: - group_index += 1 - saw_g = True - group_has_faces = False - group_name = line[len(cmd):].split("#", 1)[0].strip() - - elif cmd == "o": - if group_has_faces: - group_index += 1 - saw_g = False - group_has_faces = False - group_name = line[len(cmd):].split("#", 1)[0].strip() - - elif cmd == "usemtl": - material_name = line[len(cmd):].split("#", 1)[0].strip() - - elif cmd == "s" and len(parts) > 1: - value = parts[1].split("#", 1)[0] - try: - group = 0 if value == "off" else int(value) - except ValueError: - continue - if group >= 0: - smoothing_group = group - - elif cmd == "f": - if "#" in line: - parts = line.split("#", 1)[0].split() - if len(parts) < 4: - continue - - nv = len(raw_v) - nvt = len(raw_vt) - nvn = len(raw_vn) - corners: list[tuple[int, int | None, int | None]] = [] - valid_face = True - - for tok in parts[1:]: - slashes = tok.split("/") - ns = len(slashes) - if ns > 3: - valid_face = False - break - - vi = _resolve_obj_index(slashes[0], nv) - if vi is None or raw_v[vi] is None: - valid_face = False - break - - vti: int | None = None - if ns >= 2 and slashes[1]: - vti = _resolve_obj_index(slashes[1], nvt) - if vti is None: - valid_face = False - break - - vni: int | None = None - if ns == 3 and slashes[2]: - vni = _resolve_obj_index(slashes[2], nvn) - if vni is None: - valid_face = False - break - - corners.append((vi, vti, vni)) - - if not valid_face or len(corners) < 3: - continue - - indices = ((0, 1, 2),) - if len(corners) > 3: - indices = None - if len({c[0] for c in corners}) == len(corners): - indices = _triangulate_face([raw_v[c[0]] for c in corners]) - if indices is None: - indices = ((0, i, i + 1) for i in range(1, len(corners) - 1)) - tris = [] - for a, b, c in indices: - c0, c1, c2 = corners[a], corners[b], corners[c] - if c0[0] == c1[0] or c1[0] == c2[0] or c0[0] == c2[0]: - continue - tris.append((c0, c2, c1) if mirrored else (c0, c1, c2)) - - if not tris: - continue - - group_has_faces = True - key = (group_index, material_name) - builder = builders.get(key) - if builder is None: - builder = { - "name": group_name, - "material": material_name, - "group_index": group_index, - "vert_map": {}, - "positions": [], - "normals": [], - "uvs": [], - "indices": [], - "has_any_uv": False, - "has_missing_normal": False, - } - builders[key] = builder - - normal_group = None - if smoothing_group is not None and any(vni is None for _, _, vni in corners): - normal_group = smoothing_group - if smoothing_group == 0: - flat_face_id -= 1 - normal_group = flat_face_id - - vert_map: dict[tuple[int, int | None, int | None, int | None], int] = builder["vert_map"] - b_pos: list[tuple[float, float, float]] = builder["positions"] - b_nrm: list[tuple[float, float, float] | None] = builder["normals"] - b_uv: list[tuple[float, float] | None] = builder["uvs"] - b_idx: list[int] = builder["indices"] - - for tri in tris: - for corner in tri: - vertex_key = (*corner, normal_group) - local_idx = vert_map.get(vertex_key) - if local_idx is None: - local_idx = len(b_pos) - vert_map[vertex_key] = local_idx - vi, vti, vni = corner - pos = raw_v[vi] - assert pos is not None - b_pos.append(pos) - if vti is not None: - builder["has_any_uv"] = True - b_uv.append(raw_vt[vti]) - else: - b_uv.append(None) - if vni is not None: - b_nrm.append(raw_vn[vni]) - else: - builder["has_missing_normal"] = True - b_nrm.append(None) - b_idx.append(local_idx) - - primitives: list[dict] = [] - for builder in builders.values(): - indices = builder["indices"] - positions = builder["positions"] - if not indices or not positions: - continue - - if builder["has_missing_normal"]: - # UVs and explicit normals split render vertices. Generated normals - # share an accumulator for each position within the same smoothing group. - first_vertex: dict[tuple[int, int | None], int] = {} - normal_vertices = [ - first_vertex.setdefault((vi, normal_group), vertex) - for (vi, _, _, normal_group), vertex in builder["vert_map"].items() - ] - raw_normals = builder["normals"] - index_iter = iter(indices) - # Fully explicit triangles should not smooth neighboring generated normals. - normal_indices = ( - normal_vertices[i] - for a, b, c in zip(index_iter, index_iter, index_iter) - if None in (raw_normals[a], raw_normals[b], raw_normals[c]) - for i in (a, b, c) - ) - computed = _compute_smooth_normals(positions, normal_indices) - normals = [ - normal if normal is not None else computed[normal_vertex] - for normal, normal_vertex in zip(raw_normals, normal_vertices) - ] - else: - normals = builder["normals"] - - if builder["has_any_uv"]: - uvs = [uv if uv is not None else (0.0, 0.0) for uv in builder["uvs"]] - else: - uvs = [] - - primitives.append({ - "name": builder["name"], - "material": builder["material"], - "group_index": builder["group_index"], - "positions": positions, - "normals": normals, - "uvs": uvs, - "indices": indices, - }) - - return primitives - - -def compute_bounds(primitives: list[dict]) -> list[float] | None: - """Return [minx, miny, minz, maxx, maxy, maxz] over all finite positions, or None.""" - minx = math.inf - miny = math.inf - minz = math.inf - maxx = -math.inf - maxy = -math.inf - maxz = -math.inf - found = False - - for prim in primitives: - for pos in prim.get("positions") or (): - if len(pos) < 3: - continue - x, y, z = float(pos[0]), float(pos[1]), float(pos[2]) - if not (math.isfinite(x) and math.isfinite(y) and math.isfinite(z)): - continue - found = True - if x < minx: - minx = x - if y < miny: - miny = y - if z < minz: - minz = z - if x > maxx: - maxx = x - if y > maxy: - maxy = y - if z > maxz: - maxz = z - - if not found: - return None - return [ - _clean_zero(minx), - _clean_zero(miny), - _clean_zero(minz), - _clean_zero(maxx), - _clean_zero(maxy), - _clean_zero(maxz), - ] - - -def _pack_f32(values: list[tuple[float, ...]], components: int) -> tuple[bytes, array.array]: - if any(len(item) != components for item in values): - raise GlbError(f"expected {components} floats per vertex") - if _FLOAT32_CODE is not None: - arr = array.array(_FLOAT32_CODE, itertools.chain.from_iterable(values)) - if not all(map(math.isfinite, arr)): - raise GlbError("non-finite float32 vertex attribute") - raw = arr - if _NEEDS_BYTESWAP: - swapped = array.array(_FLOAT32_CODE, arr) - swapped.byteswap() - return swapped.tobytes(), raw - return raw.tobytes(), raw - - flat: list[float] = [] - for item in values: - for c in item: - v = float(c) - if not math.isfinite(v): - raise GlbError("non-finite float32 vertex attribute") - flat.append(v) - packed = struct.pack(f"<{len(flat)}f", *flat) - unpacked = struct.unpack(f"<{len(flat)}f", packed) - if not all(map(math.isfinite, unpacked)): - raise GlbError("non-finite float32 vertex attribute") - return packed, array.array("d", unpacked) - - -def _pack_indices(indices: list[int], vert_count: int) -> tuple[bytes, int]: - if len(indices) % 3 != 0: - raise GlbError(f"triangle index count must be a multiple of 3, got {len(indices)}") - lo = min(indices) - hi = max(indices) - if lo < 0 or hi >= vert_count: - raise GlbError(f"index out of range [0, {vert_count - 1}]: min={lo}, max={hi}") - - if vert_count <= 65535: - comp_type = COMPONENT_UNSIGNED_SHORT - if _UINT16_CODE is not None: - arr = array.array(_UINT16_CODE, indices) - if _NEEDS_BYTESWAP: - arr.byteswap() - return arr.tobytes(), comp_type - return struct.pack(f"<{len(indices)}H", *indices), comp_type - - comp_type = COMPONENT_UNSIGNED_INT - if _UINT32_CODE is not None: - arr = array.array(_UINT32_CODE, indices) - if _NEEDS_BYTESWAP: - arr.byteswap() - return arr.tobytes(), comp_type - return struct.pack(f"<{len(indices)}I", *indices), comp_type - - -def _append_buffer_view( - bin_buf: bytearray, - buffer_views: list[dict], - payload: bytes, - *, - target: int | None = None, -) -> int: - pad = (-len(bin_buf)) % 4 - if pad: - bin_buf.extend(b"\x00" * pad) - offset = len(bin_buf) - bin_buf.extend(payload) - end_pad = (-len(bin_buf)) % 4 - if end_pad: - bin_buf.extend(b"\x00" * end_pad) - - bv: dict = { - "buffer": 0, - "byteOffset": offset, - "byteLength": len(payload), - } - if target is not None: - bv["target"] = target - bv_idx = len(buffer_views) - buffer_views.append(bv) - return bv_idx - - -def pack_primitive(prim: dict) -> dict: - """Packed little-endian glTF buffers for one primitive from ``parse_obj``. - - Returns ``positions``/``normals``/``uvs``/``indices`` as bytes (``uvs`` is b"" without UVs), the index - component type, the vertex and index counts, the POSITION ``min``/``max``, and the primitive's - ``material`` key and optional ``material_index``. The same packed primitive can be written into - a GLB once and drawn by many instances. - """ - positions = list(prim["positions"]) - indices = list(prim["indices"]) - vert_count = len(positions) - pos_bytes, pos_f32 = _pack_f32(positions, 3) - idx_bytes, idx_comp_type = _pack_indices(indices, vert_count) - normals_in = prim.get("normals") - if normals_in is None or len(normals_in) == 0: - normals = _compute_smooth_normals(positions, indices) - elif len(normals_in) == vert_count: - normals = [ - _normalize3(float(n[0]), float(n[1]), float(n[2])) - for n in normals_in - ] - else: - raise GlbError( - f"normals length ({len(normals_in)}) does not match positions length ({vert_count})" - ) - xs = pos_f32[0::3] - ys = pos_f32[1::3] - zs = pos_f32[2::3] - nrm_bytes, _ = _pack_f32(normals, 3) - uv_bytes = b"" - uvs_in = prim.get("uvs") - if uvs_in is not None and len(uvs_in) > 0: - if len(uvs_in) != vert_count: - raise GlbError( - f"uvs length ({len(uvs_in)}) does not match positions length ({vert_count})" - ) - clean_uvs = [ - ( - _clean_zero(float(uv[0])) if math.isfinite(float(uv[0])) else 0.0, - _clean_zero(float(uv[1])) if math.isfinite(float(uv[1])) else 0.0, - ) - for uv in uvs_in - ] - uv_bytes, _ = _pack_f32(clean_uvs, 2) - material = prim.get("material", "") - return { - "positions": pos_bytes, - "normals": nrm_bytes, - "uvs": uv_bytes, - "indices": idx_bytes, - "index_type": idx_comp_type, - "vertices": vert_count, - "index_count": len(indices), - "min": [_clean_zero(min(xs)), _clean_zero(min(ys)), _clean_zero(min(zs))], - "max": [_clean_zero(max(xs)), _clean_zero(max(ys)), _clean_zero(max(zs))], - "material": material if isinstance(material, (str, int)) and not isinstance(material, bool) else "", - "material_index": prim.get("material_index"), - } - - -def _append_packed(bin_buf: bytearray, buffer_views: list[dict], accessors: list[dict], packed: dict) -> tuple[dict, int]: - """Write one packed primitive's views and accessors; returns (attributes, indices accessor).""" - vert_count = packed["vertices"] - pos_bv = _append_buffer_view(bin_buf, buffer_views, packed["positions"], target=TARGET_ARRAY_BUFFER) - pos_acc = len(accessors) - accessors.append({ - "bufferView": pos_bv, - "componentType": COMPONENT_FLOAT, - "count": vert_count, - "type": "VEC3", - "min": list(packed["min"]), - "max": list(packed["max"]), - }) - nrm_bv = _append_buffer_view(bin_buf, buffer_views, packed["normals"], target=TARGET_ARRAY_BUFFER) - nrm_acc = len(accessors) - accessors.append({ - "bufferView": nrm_bv, - "componentType": COMPONENT_FLOAT, - "count": vert_count, - "type": "VEC3", - }) - attributes: dict[str, int] = {"POSITION": pos_acc, "NORMAL": nrm_acc} - if packed["uvs"]: - uv_bv = _append_buffer_view(bin_buf, buffer_views, packed["uvs"], target=TARGET_ARRAY_BUFFER) - uv_acc = len(accessors) - accessors.append({ - "bufferView": uv_bv, - "componentType": COMPONENT_FLOAT, - "count": vert_count, - "type": "VEC2", - }) - attributes["TEXCOORD_0"] = uv_acc - idx_bv = _append_buffer_view(bin_buf, buffer_views, packed["indices"], target=TARGET_ELEMENT_ARRAY_BUFFER) - idx_acc = len(accessors) - accessors.append({ - "bufferView": idx_bv, - "componentType": packed["index_type"], - "count": packed["index_count"], - "type": "SCALAR", - }) - return attributes, idx_acc - - -def _parse_base_color_factor(value: object, default: list[float]) -> list[float]: - if value is None: - return list(default) - if not isinstance(value, (list, tuple)) or len(value) not in (3, 4): - raise GlbError("base_color_factor must be a 3- or 4-element float sequence") - out = [float(c) for c in value] - if len(out) == 3: - out.append(1.0) - if not all(math.isfinite(c) and 0.0 <= c <= 1.0 for c in out): - raise GlbError("base_color_factor values must be finite numbers in [0.0, 1.0]") - return [_clean_zero(c) for c in out] - - -def _parse_alpha_mode(mode: object, cutoff: object, factor_alpha: float) -> dict: - """glTF alphaMode/alphaCutoff fields for a material spec; OPAQUE is the glTF default and is omitted.""" - if mode is None: - mode = "BLEND" if factor_alpha < 1.0 else "OPAQUE" - if not isinstance(mode, str) or mode not in ALPHA_MODES: - raise GlbError("alpha_mode must be one of 'OPAQUE', 'MASK', 'BLEND'") - if cutoff is not None and mode != "MASK": - raise GlbError("alpha_cutoff is only valid with alpha_mode 'MASK'") - if mode == "OPAQUE": - return {} - out: dict = {"alphaMode": mode} - if cutoff is not None: - if isinstance(cutoff, bool) or not isinstance(cutoff, (int, float)) or not math.isfinite(cutoff) or cutoff < 0.0: - raise GlbError("alpha_cutoff must be a finite number >= 0.0") - out["alphaCutoff"] = _clean_zero(float(cutoff)) - return out - - -class _MaterialTable: - """glTF materials, images and textures for one GLB, shared by every primitive that uses them.""" - - def __init__(self, materials, bin_buf: bytearray, buffer_views: list[dict]) -> None: - self.materials = materials - self.bin_buf = bin_buf - self.buffer_views = buffer_views - self.gltf_materials: list[dict] = [] - self.images: list[dict] = [] - self.textures: list[dict] = [] - self.mat_index_by_key: dict[tuple[str | int, bool], int] = {} - self.default_mat_index: int | None = None - self.tex_index_by_sha256: dict[bytes, int] = {} - - def get_texture_index(self, png_bytes: bytes) -> int: - digest = hashlib.sha256(png_bytes).digest() - existing = self.tex_index_by_sha256.get(digest) - if existing is not None: - return existing - bv_idx = _append_buffer_view(self.bin_buf, self.buffer_views, png_bytes, target=None) - img_idx = len(self.images) - self.images.append({ - "bufferView": bv_idx, - "mimeType": "image/png", - }) - tex_idx = len(self.textures) - self.textures.append({ - "sampler": 0, - "source": img_idx, - }) - self.tex_index_by_sha256[digest] = tex_idx - return tex_idx - - def _lookup_material_spec(self, prim: dict) -> tuple[str | int, dict] | None: - materials = self.materials - if materials is None: - return None - mat_key = prim.get("material", "") - if mat_key is None: - mat_key = "" - if isinstance(materials, dict): - if mat_key in materials: - return mat_key, materials[mat_key] or {} - if "material_index" in prim: - midx = prim["material_index"] - if isinstance(midx, int) and not isinstance(midx, bool) and midx in materials: - return midx, materials[midx] or {} - elif isinstance(materials, (list, tuple)): - midx = prim.get("material_index") - if isinstance(midx, int) and not isinstance(midx, bool) and 0 <= midx < len(materials): - return midx, materials[midx] or {} - return None - - def get_material_index(self, prim: dict, *, has_uv: bool) -> int: - found = self._lookup_material_spec(prim) - if found is not None: - resolved_key, spec = found - raw_png = spec.get("png_bytes") - has_png = has_uv and isinstance(raw_png, (bytes, bytearray, memoryview)) and len(raw_png) > 0 - cache_key = (resolved_key, has_png) - existing = self.mat_index_by_key.get(cache_key) - if existing is not None: - return existing - default_color = DEFAULT_TEXTURED_COLOR if has_png else DEFAULT_CLAY_COLOR - base_color = _parse_base_color_factor(spec.get("base_color_factor"), default_color) - alpha_fields = _parse_alpha_mode(spec.get("alpha_mode"), spec.get("alpha_cutoff"), base_color[3]) - - pbr: dict = { - "baseColorFactor": base_color, - "metallicFactor": DEFAULT_METALLIC, - "roughnessFactor": DEFAULT_ROUGHNESS, - } - if has_png: - tex_idx = self.get_texture_index(bytes(raw_png)) - pbr["baseColorTexture"] = {"index": tex_idx} - - mat_obj: dict = {"pbrMetallicRoughness": pbr} - mat_name = spec.get("name") - if mat_name is None and isinstance(resolved_key, str): - mat_name = resolved_key - if isinstance(mat_name, str) and mat_name: - mat_obj["name"] = mat_name - if spec.get("double_sided"): - mat_obj["doubleSided"] = True - mat_obj.update(alpha_fields) - - mat_idx = len(self.gltf_materials) - self.gltf_materials.append(mat_obj) - self.mat_index_by_key[cache_key] = mat_idx - return mat_idx - - if self.default_mat_index is None: - self.default_mat_index = len(self.gltf_materials) - self.gltf_materials.append({ - "name": "default_clay", - "pbrMetallicRoughness": { - "baseColorFactor": list(DEFAULT_CLAY_COLOR), - "metallicFactor": DEFAULT_METALLIC, - "roughnessFactor": DEFAULT_ROUGHNESS, - }, - }) - return self.default_mat_index - - def apply(self, gltf: dict) -> None: - gltf["materials"] = self.gltf_materials - if self.textures: - gltf["samplers"] = [dict(DEFAULT_SAMPLER)] - gltf["images"] = self.images - gltf["textures"] = self.textures - - -def _build_glb_with_stats( - primitives: list[dict], - materials: dict[str, dict] | None = None, - *, - generator: str = "Leonida glb_writer", -) -> tuple[bytes, dict]: - non_empty: list[dict] = [] - for prim in primitives: - positions = prim.get("positions") or () - indices = prim.get("indices") or () - if len(positions) > 0 and len(indices) > 0: - non_empty.append(prim) - - if not non_empty: - raise GlbError("cannot build GLB: no non-empty primitives") - - bin_buf = bytearray() - buffer_views: list[dict] = [] - accessors: list[dict] = [] - table = _MaterialTable(materials, bin_buf, buffer_views) - get_material_index = table.get_material_index - - gltf_primitives: list[dict] = [] - total_verts = 0 - total_tris = 0 - - for prim in non_empty: - packed = pack_primitive(prim) - total_verts += packed["vertices"] - total_tris += packed["index_count"] // 3 - attributes, idx_acc = _append_packed(bin_buf, buffer_views, accessors, packed) - mat_idx = get_material_index(prim, has_uv="TEXCOORD_0" in attributes) - - gltf_primitives.append({ - "attributes": attributes, - "indices": idx_acc, - "material": mat_idx, - "mode": MODE_TRIANGLES, - }) - - # Ensure BIN buffer is 4-byte aligned. - bin_pad = (-len(bin_buf)) % 4 - if bin_pad: - bin_buf.extend(b"\x00" * bin_pad) - - mesh_obj: dict = {"primitives": gltf_primitives} - if len(non_empty) == 1: - sole_name = non_empty[0].get("name") - if isinstance(sole_name, str) and sole_name: - mesh_obj["name"] = sole_name - - gltf: dict = { - "asset": { - "version": "2.0", - "generator": generator, - }, - "scene": 0, - "scenes": [{"nodes": [0]}], - "nodes": [{"mesh": 0}], - "meshes": [mesh_obj], - "materials": table.gltf_materials, - "accessors": accessors, - "bufferViews": buffer_views, - "buffers": [{"byteLength": len(bin_buf)}], - } - - if table.textures: - gltf["samplers"] = [dict(DEFAULT_SAMPLER)] - gltf["images"] = table.images - gltf["textures"] = table.textures - - json_bytes = json.dumps(gltf, separators=(",", ":"), ensure_ascii=False, allow_nan=False).encode("utf-8") - json_pad = (-len(json_bytes)) % 4 - if json_pad: - json_bytes += b" " * json_pad - - total_length = 12 + 8 + len(json_bytes) + 8 + len(bin_buf) - header = struct.pack("<4sII", GLB_MAGIC, GLB_VERSION, total_length) - json_hdr = struct.pack(" bytes: - """Serialize glTF-ready primitives and optional PNG materials into binary .glb bytes. - - ``materials`` maps a primitive's ``material`` name (or ``material_index``) to a - spec dict. Each spec becomes one glTF material shared by every primitive that - resolves to it; primitives without a matching spec share an opaque - ``default_clay`` material. Recognised spec keys: - - - ``name``: material name (defaults to the string key). - - ``png_bytes``: PNG embedded as ``baseColorTexture`` for primitives with UVs. - - ``base_color_factor``: 3 or 4 finite floats in [0, 1]; alpha defaults to 1. - - ``double_sided``: emit ``doubleSided: true`` when truthy. - - ``alpha_mode``: ``"OPAQUE"``, ``"MASK"`` or ``"BLEND"``. When omitted, a - ``base_color_factor`` alpha below 1 gives ``BLEND``; otherwise no ``alphaMode`` - is written (glTF default ``OPAQUE``). Texture alpha is never inspected. - - ``alpha_cutoff``: finite number >= 0, only with ``MASK`` (glTF default 0.5). - - Invalid specs raise GlbError. - """ - glb_bytes, _ = _build_glb_with_stats(primitives, materials, generator=generator) - return glb_bytes - - -# On Windows, MoveFileEx fails with a sharing violation (PermissionError) while -# another writer is replacing the same destination or a reader holds it open -# without FILE_SHARE_DELETE. Those holds last milliseconds, so the replace is -# retried with a short backoff (about 1.3 s in total) before the error is raised. -_REPLACE_RETRY = os.name == "nt" -_REPLACE_DELAYS = (0.001, 0.002, 0.005, 0.01, 0.02, 0.05, 0.1, 0.1, 0.2, 0.3, 0.5) - - -def _replace(source: str, destination: str) -> None: - for delay in _REPLACE_DELAYS if _REPLACE_RETRY else (): - try: - os.replace(source, destination) - return - except PermissionError: - time.sleep(delay) - os.replace(source, destination) - - -def write_glb( - path: str, - primitives: list[dict], - materials: dict[str, dict] | None = None, -) -> dict: - """Atomically publish a GLB using a private staging file in its destination directory. - - Overlapping writers publish complete files (the last replacement wins), and - existing sibling files are never used as staging files. On Windows a replace - that hits a sharing violation is retried briefly (see ``_replace``); one held - longer than that still raises PermissionError and leaves the old file in place. - ``materials`` takes the spec keys documented on ``build_glb``. - """ - glb_bytes, stats = _build_glb_with_stats(primitives, materials) - _write_bytes_atomic(path, glb_bytes) - return stats - - -def _write_bytes_atomic(path: str, glb_bytes: bytes) -> None: - """Publish ``glb_bytes`` at ``path`` through a private staging file in the same directory.""" - out_path = os.fspath(path) - parent = os.path.dirname(os.path.abspath(out_path)) - if parent: - os.makedirs(parent, exist_ok=True) - tmp_path = None - try: - with tempfile.NamedTemporaryFile( - mode="wb", dir=parent, prefix=".glb-", suffix=".tmp", delete=False, - ) as f: - tmp_path = f.name - f.write(glb_bytes) - # NamedTemporaryFile creates 0600; give the GLB the mode of the file it replaces, or a new file's. - os.chmod(tmp_path, published_mode(out_path)) - # Close before replacement: Windows cannot rename an open staging file. - _replace(tmp_path, out_path) - except BaseException: - try: - if tmp_path is not None: - os.remove(tmp_path) - except OSError: - pass - raise - - -INSTANCING_EXTENSION = "EXT_mesh_gpu_instancing" -INSTANCING_MODES = ("gpu", "nodes") - - -def _quat_matrix(q) -> list[list[float]]: - x, y, z, w = (float(v) for v in q) - return [ - [1 - 2 * (y * y + z * z), 2 * (x * y - z * w), 2 * (x * z + y * w)], - [2 * (x * y + z * w), 1 - 2 * (x * x + z * z), 2 * (y * z - x * w)], - [2 * (x * z - y * w), 2 * (y * z + x * w), 1 - 2 * (x * x + y * y)], - ] - - -def instance_bounds(box_min, box_max, translation, rotation, scale) -> list[float]: - """Exact axis-aligned bounds of the box [box_min, box_max] after scale, rotation (unit x, y, z, w) and - translation, the order glTF applies a node's TRS in.""" - r = _quat_matrix(rotation) - m = [[r[i][j] * float(scale[j]) for j in range(3)] for i in range(3)] - c = [(float(box_min[j]) + float(box_max[j])) * 0.5 for j in range(3)] - h = [(float(box_max[j]) - float(box_min[j])) * 0.5 for j in range(3)] - out_min, out_max = [], [] - for i in range(3): - ci = m[i][0] * c[0] + m[i][1] * c[1] + m[i][2] * c[2] + float(translation[i]) - hi = abs(m[i][0]) * h[0] + abs(m[i][1]) * h[1] + abs(m[i][2]) * h[2] - out_min.append(ci - hi) - out_max.append(ci + hi) - return out_min + out_max - - -def build_instanced_glb( - meshes: list[dict], - materials: dict[str | int, dict] | None = None, - *, - mode: str = "gpu", - generator: str = "Leonida glb_writer", -) -> tuple[bytes, dict]: - """One GLB in which each mesh is stored once and drawn by many instances. - - ``meshes`` is a list of ``{"name": str or None, "primitives": [pack_primitive(...)], "instances": - [(translation xyz, rotation xyzw, scale xyz), ...]}``. Every instance transform must have a positive - determinant (no mirroring scale); give mirrored instances their own mirrored mesh instead, so the winding is - right in every loader. ``mode`` "gpu" writes one node per mesh with ``EXT_mesh_gpu_instancing`` (listed in - extensionsUsed and extensionsRequired); "nodes" writes one plain glTF node per instance, which every loader - reads but which costs a draw call per instance. ``materials`` uses the same lookup and spec keys as - ``build_glb``. Returns (GLB bytes, stats), including rendered triangles (each mesh's triangles times its - instances) and the bounds of every instance. - """ - if mode not in INSTANCING_MODES: - raise GlbError(f"instancing mode must be one of {INSTANCING_MODES}, got {mode!r}") - bin_buf = bytearray() - buffer_views: list[dict] = [] - accessors: list[dict] = [] - table = _MaterialTable(materials, bin_buf, buffer_views) - gltf_meshes: list[dict] = [] - nodes: list[dict] = [] - stored_verts = stored_tris = drawn_tris = primitives = instances_total = 0 - lo = [math.inf] * 3 - hi = [-math.inf] * 3 - for mesh in meshes: - prims = [p for p in mesh.get("primitives") or () if p.get("vertices") and p.get("index_count")] - insts = list(mesh.get("instances") or ()) - if not prims or not insts: - continue - gltf_prims = [] - box_min = [math.inf] * 3 - box_max = [-math.inf] * 3 - mesh_tris = 0 - for packed in prims: - attributes, idx_acc = _append_packed(bin_buf, buffer_views, accessors, packed) - gltf_prims.append({ - "attributes": attributes, - "indices": idx_acc, - "material": table.get_material_index(packed, has_uv="TEXCOORD_0" in attributes), - "mode": MODE_TRIANGLES, - }) - stored_verts += packed["vertices"] - mesh_tris += packed["index_count"] // 3 - for k in range(3): - box_min[k] = min(box_min[k], packed["min"][k]) - box_max[k] = max(box_max[k], packed["max"][k]) - primitives += len(prims) - stored_tris += mesh_tris - mesh_obj: dict = {"primitives": gltf_prims} - if isinstance(mesh.get("name"), str) and mesh["name"]: - mesh_obj["name"] = mesh["name"] - mesh_idx = len(gltf_meshes) - gltf_meshes.append(mesh_obj) - ts, rs, ss = [], [], [] - for t, q, sc in insts: - t = [float(v) for v in t] - sc = [float(v) for v in sc] - q = [float(v) for v in q] - n = math.sqrt(sum(v * v for v in q)) - if not n or not math.isfinite(n): - raise GlbError("instance rotation must be a finite non-zero quaternion") - q = [v / n for v in q] - if sc[0] * sc[1] * sc[2] <= 0: - raise GlbError("instance scale must have a positive determinant; mirror the mesh instead") - if not all(math.isfinite(v) for v in t + sc): - raise GlbError("instance translation and scale must be finite") - ts.append(t) - rs.append(q) - ss.append(sc) - instances_total += len(insts) - drawn_tris += mesh_tris * len(insts) - bounds_transforms = zip(ts, rs, ss) - if mode == "gpu": - attrs = {} - stored_transforms: list[Iterable[tuple[float, ...]]] = [] - for key, values, kind in (("TRANSLATION", ts, "VEC3"), ("ROTATION", rs, "VEC4"), ("SCALE", ss, "VEC3")): - components = 4 if kind == "VEC4" else 3 - data, _ = _pack_f32(values, components) - stored_transforms.append(struct.iter_unpack(f"<{components}f", data)) - bv = _append_buffer_view(bin_buf, buffer_views, data, target=None) - attrs[key] = len(accessors) - accessors.append({"bufferView": bv, "componentType": COMPONENT_FLOAT, "count": len(values), "type": kind}) - nodes.append({"mesh": mesh_idx, "extensions": {INSTANCING_EXTENSION: {"attributes": attrs}}}) - bounds_transforms = zip(*stored_transforms) - else: - for t, q, sc in zip(ts, rs, ss): - node: dict = {"mesh": mesh_idx} - if any(t): - node["translation"] = [_clean_zero(v) for v in t] - if q != [0.0, 0.0, 0.0, 1.0]: - node["rotation"] = [_clean_zero(v) for v in q] - if sc != [1.0, 1.0, 1.0]: - node["scale"] = [_clean_zero(v) for v in sc] - nodes.append(node) - for t, q, sc in bounds_transforms: - b = instance_bounds(box_min, box_max, t, q, sc) - for k in range(3): - lo[k] = min(lo[k], b[k]) - hi[k] = max(hi[k], b[k + 3]) - if not nodes: - raise GlbError("cannot build GLB: no mesh with primitives and instances") - bin_pad = (-len(bin_buf)) % 4 - if bin_pad: - bin_buf.extend(b"\x00" * bin_pad) - gltf: dict = { - "asset": {"version": "2.0", "generator": generator}, - "scene": 0, - "scenes": [{"nodes": list(range(len(nodes)))}], - "nodes": nodes, - "meshes": gltf_meshes, - "accessors": accessors, - "bufferViews": buffer_views, - "buffers": [{"byteLength": len(bin_buf)}], - } - table.apply(gltf) - if mode == "gpu": - gltf["extensionsUsed"] = [INSTANCING_EXTENSION] - gltf["extensionsRequired"] = [INSTANCING_EXTENSION] - json_bytes = json.dumps(gltf, separators=(",", ":"), ensure_ascii=False, allow_nan=False).encode("utf-8") - json_bytes += b" " * ((-len(json_bytes)) % 4) - total_length = 12 + 8 + len(json_bytes) + 8 + len(bin_buf) - glb_bytes = b"".join(( - struct.pack("<4sII", GLB_MAGIC, GLB_VERSION, total_length), - struct.pack(" dict: - """``build_instanced_glb`` published atomically at ``path`` (same staging rules as ``write_glb``).""" - glb_bytes, stats = build_instanced_glb(meshes, materials, mode=mode) - _write_bytes_atomic(path, glb_bytes) - return stats - - -def read_glb_summary(data: bytes) -> dict: - """Validate binary glTF 2.0 container headers/chunks and return parsed summary.""" - if not isinstance(data, (bytes, bytearray, memoryview)): - raise GlbError("GLB data must be bytes-like") - buf = memoryview(data) - actual_len = len(buf) - if actual_len < 20: - raise GlbError(f"GLB data too short: {actual_len} bytes") - - magic, version, total_length = struct.unpack_from("<4sII", buf, 0) - if magic != GLB_MAGIC: - raise GlbError(f"invalid GLB magic: {magic!r}") - if version != GLB_VERSION: - raise GlbError(f"unsupported GLB version: {version}") - if total_length != actual_len: - raise GlbError(f"GLB total length mismatch: header={total_length}, actual={actual_len}") - if total_length % 4 != 0: - raise GlbError(f"GLB total length not 4-byte aligned: {total_length}") - - json_len, json_type = struct.unpack_from(" total_length: - raise GlbError(f"JSON chunk length {json_len} exceeds total length {total_length}") - - json_raw = bytes(buf[20:20 + json_len]) - try: - gltf = json.loads(json_raw.decode("utf-8")) - except (UnicodeDecodeError, json.JSONDecodeError) as exc: - raise GlbError(f"invalid JSON chunk: {exc}") from exc - if not isinstance(gltf, dict): - raise GlbError("GLB JSON root must be a JSON object") - - after_json = 20 + json_len - offset = after_json - bin_bytes = 0 - while offset < total_length: - if offset + 8 > total_length: - raise GlbError("truncated GLB chunk header") - chunk_len, chunk_type = struct.unpack_from(" total_length: - raise GlbError(f"GLB chunk length {chunk_len} exceeds GLB total length {total_length}") - if chunk_type == CHUNK_TYPE_JSON: - raise GlbError("duplicate GLB JSON chunk") - if chunk_type == CHUNK_TYPE_BIN: - if offset != after_json: - raise GlbError("GLB BIN chunk must be second") - bin_bytes = chunk_len - # Extension chunks are ignored after checking their framing. - offset = chunk_end - - buf0_limit = bin_bytes - buffers = gltf.get("buffers") - if isinstance(buffers, list) and buffers: - buf0 = buffers[0] - if isinstance(buf0, dict): - embedded = "uri" not in buf0 - declared = buf0.get("byteLength", 0 if embedded else None) - invalid_length = isinstance(declared, bool) or not isinstance(declared, int) or declared < 0 - if embedded and (invalid_length or declared > bin_bytes): - raise GlbError(f"buffers[0].byteLength ({declared}) exceeds BIN chunk ({bin_bytes})") - if invalid_length: - raise GlbError("invalid buffers[0].byteLength") - buf0_limit = declared - - buffer_views = gltf.get("bufferViews") - if isinstance(buffer_views, list): - for i, bv in enumerate(buffer_views): - if not isinstance(bv, dict): - raise GlbError(f"bufferViews[{i}] is not an object") - if bv.get("buffer", 0) == 0: - bv_off = bv.get("byteOffset", 0) - bv_len = bv.get("byteLength", -1) - if ( - isinstance(bv_off, bool) - or isinstance(bv_len, bool) - or not isinstance(bv_off, int) - or not isinstance(bv_len, int) - or bv_off < 0 - or bv_len < 0 - ): - raise GlbError(f"invalid byteOffset/byteLength in bufferViews[{i}]") - if bv_off + bv_len > buf0_limit: - raise GlbError( - f"bufferViews[{i}] exceeds buffer 0 ({bv_off}+{bv_len} > {buf0_limit})" - ) - - return { - "version": version, - "total_bytes": total_length, - "json": gltf, - "bin_bytes": bin_bytes, - } - - -def main(argv: list[str] | None = None) -> int: - parser = argparse.ArgumentParser( - description="Convert a Wavefront OBJ file to binary glTF 2.0 (.glb)." - ) - parser.add_argument("in_obj", help="Input Wavefront .obj file path") - parser.add_argument("out_glb", help="Output binary .glb file path") - parser.add_argument( - "--up", - choices=("z", "y"), - default="z", - help="Source up axis: 'z' converts RAGE Z-up to glTF Y-up (default), 'y' keeps Y-up", - ) - args = parser.parse_args(argv) - - try: - # write_glb replaces its target, so naming the OBJ as the output would silently destroy the model. - if os.path.exists(args.out_glb) and os.path.exists(args.in_obj) and os.path.samefile( - args.in_obj, args.out_glb): - raise GlbError(f"output must not overwrite the input OBJ: {args.in_obj}") - primitives = parse_obj(args.in_obj, is_path=True, up_axis=args.up) - stats = write_glb(args.out_glb, primitives) - except (GlbError, OSError) as exc: - print(f"ERROR: {exc}", file=sys.stderr) - return 1 - - print( - f"wrote {args.out_glb}: {stats['bytes']} bytes, " - f"{stats['primitives']} primitives, {stats['vertices']} verts, " - f"{stats['triangles']} tris" - ) - return 0 - - -if __name__ == "__main__": - try: # a redirected stdout is strict ANSI code page under -I; write '?' for what it cannot encode - sys.stdout.reconfigure(errors="replace") - except (AttributeError, ValueError, OSError): - pass - raise SystemExit(main()) diff --git a/tools/hashdict.py b/tools/hashdict.py deleted file mode 100644 index fc0887e96..000000000 --- a/tools/hashdict.py +++ /dev/null @@ -1,245 +0,0 @@ -"""Build a joaat (Jenkins one-at-a-time, lowercased) hash -> string dictionary from every string we can find. - -Sources: printable runs in carved blobs (selected archives fully; PSO/RBF blobs everywhere), shader names, and -any extra text/binary files given (e.g. the exe once it arrives: run with --extra path\\to\\exe). -A carved stream that inflates to a whole number of 64 KiB blocks continues in the next one (docs/page_directory.md), -so a blob is harvested together with its continuation streams: a name across the boundary stays whole, and a PSO or -RBF blob in an archive that is not harvested fully is read past its first stream. -When multiple names share a hash, the dictionary keeps the lexicographically first spelling. -The output cannot overwrite an input index, extra file, or harvested blob (including hard-link aliases). -An index.json saved with a UTF-8 BOM (Windows PowerShell 5.1, old Notepad) is read, not refused. - -Usage: - python -I hashdict.py --out hashes.json [--archives a,b] [--extra f1 f2 ...] [--min 3] - holds one folder per archive (/carve), or is one archive's folder (/carve/common). - python -I hashdict.py --lookup 0x28cca8df ... -""" -import argparse -import json -import os -import re -import sys - -# A whole printable run, however long (one linear scan: a single character class, no nested quantifiers). -STR = re.compile(rb"[A-Za-z_][A-Za-z0-9_./:\\-]{2,}") -# For --min below 3 the run matcher must also accept one- and two-character identifiers, so the same -# identifier syntax (first byte [A-Za-z_], the rest of the run [A-Za-z0-9_./:\\-]) is used with no minimum tail. -SHORT_STR = re.compile(rb"[A-Za-z_][A-Za-z0-9_./:\\-]*") -# A name (a whole run or one piece of it) longer than this is not added: it is a blob of text, not a name. -# The old pattern cut every run at 201 characters, so no entry was ever longer than this. -MAX_NAME_LEN = 201 -# The pieces of a path or dotted name, found one at a time (a run can be megabytes: no list of all its parts). -PART = re.compile(r"[^./:\\]+") -# Where re.split would yield an empty piece; only matters for --min 0 or less, which keeps "" as a name. -EMPTY_PART = re.compile(r"[./:\\]{2}|[./:\\]$") -# Carved stream heads (hex, as index.json has them) of the PSO and RBF blobs harvested in every archive. -META_HEADS = ("5053494e", "52424630") # PSIN, RBF0 -# Heads that start a stream of their own, never the continuation of the stream before (an XML declaration with or -# without a UTF-8 BOM, besides the blob heads above). -NEW_STREAM_HEADS = META_HEADS + ("3c3f786d6c", "efbbbf3c3f786d6c") -# A stream whose inflated size is a non-zero multiple of this continues in the next one (docs/page_directory.md). -CONTINUATION_BLOCK = 65536 -# Archives harvested fully when --archives is not given. A partial carve may lack some of them: that is not an error. -DEFAULT_ARCHIVES = "common,data,script,pack_story000_story000_script,textures" - - -def joaat(s: str) -> int: - h = 0 - for c in s.lower().encode("latin-1", "replace"): - h = (h + c) & 0xFFFFFFFF - h = (h + (h << 10)) & 0xFFFFFFFF - h ^= h >> 6 - h = (h + (h << 3)) & 0xFFFFFFFF - h ^= h >> 11 - return (h + (h << 15)) & 0xFFFFFFFF - - -def harvest(data: bytes, out: set, minlen: int): - run = STR if minlen >= 3 else SHORT_STR - for m in run.finditer(data): - s = m.group(0).decode("latin-1") - if len(s) >= minlen: - if len(s) <= MAX_NAME_LEN: - out.add(s) - # also the pieces of paths and dotted names, which are hashed on their own - for pm in PART.finditer(s): - if minlen <= pm.end() - pm.start() <= MAX_NAME_LEN: - out.add(pm.group(0)) - if minlen <= 0 and EMPTY_PART.search(s): - out.add("") - - -def _raise_scan_error(error): - raise error - - -def main(): - ap = argparse.ArgumentParser() - ap.add_argument("carve", nargs="?") - ap.add_argument("--out", default="hashes.json") - ap.add_argument("--archives", help=f"comma-separated archives to harvest fully (default: {DEFAULT_ARCHIVES})") - ap.add_argument("--extra", nargs="*", default=[]) - ap.add_argument("--min", type=int, default=3) - ap.add_argument("--lookup", nargs="+", metavar="VALUE", help="dictionary path followed by one or more hashes") - a = ap.parse_args() - if a.lookup: - if len(a.lookup) < 2: - ap.error("--lookup requires a dictionary and at least one hash") - values = [] - for h in a.lookup[1:]: - try: - values.append((h, int(h, 16))) - except ValueError: - ap.error(f"--lookup: {h!r} is not a hexadecimal hash") - try: - with open(a.lookup[0], encoding="utf-8") as f: - d = json.load(f) - except (OSError, ValueError) as e: - print(f"ERROR: cannot read the dictionary {a.lookup[0]}: {getattr(e, 'strerror', None) or e}", - file=sys.stderr) - return 2 - if not isinstance(d, dict): - print(f"ERROR: the dictionary {a.lookup[0]} is not a JSON object of hash -> name", file=sys.stderr) - return 2 - for h, v in values: - print(h, d.get(f"{v:08x}", "?")) - return 0 - if a.carve is None: - ap.error("a carve directory is required to build a dictionary") - if not os.path.isdir(a.carve): - what = "is not a folder" if os.path.exists(a.carve) else "does not exist" - print(f"ERROR: the carve folder {a.carve} {what}", file=sys.stderr) - return 2 - for extra in a.extra: - if not os.path.exists(extra): - print(f"ERROR: --extra input does not exist: {extra}", file=sys.stderr) - return 2 - # A folder with its own index.json is one archive's carve (\carve\common, the folder the gamedata_* - # tools take): harvest it as that archive. Otherwise each subfolder with an index.json is one archive. - if os.path.isfile(os.path.join(a.carve, "index.json")): - archives = [(os.path.basename(os.path.normpath(os.path.abspath(a.carve))), a.carve)] - else: - archives = [(d, os.path.join(a.carve, d)) for d in sorted(os.listdir(a.carve))] - # "common, data" names "common" and "data". An archive named on the command line that is not in the carve is - # a typo or the wrong folder, not a partial carve: refuse it rather than harvest without it. The default list - # may name archives a partial carve lacks. - full = {x.strip() for x in (DEFAULT_ARCHIVES if a.archives is None else a.archives).split(",")} - {""} - if a.archives is not None: - found = [arch for arch, d in archives if os.path.isfile(os.path.join(d, "index.json"))] - unknown = sorted(full.difference(found)) - if unknown: - ap.error(f"--archives: {', '.join(unknown)} not found in {a.carve} " - f"(archives there: {', '.join(found) or 'none'})") - # The dictionary is written after the harvest: an --out naming one of the inputs would replace it. - # samefile also catches a case-only difference on Windows and macOS's default volume. - if os.path.exists(a.out): - inputs = [x for x in a.extra if os.path.isfile(x)] - inputs += [os.path.join(d, "index.json") for _, d in archives] - for x in inputs: - try: - same = os.path.isfile(x) and os.path.samefile(a.out, x) - except OSError: - same = False - if same: - print(f"ERROR: --out {a.out} is one of the inputs ({x}); choose another output file", - file=sys.stderr) - return 2 - # A report can also alias a harvested .bin, including through a hard link. - # Snapshot its file identity once; compare against the input's already-open handle - # rather than statting every carve path (there may be millions of entries). - try: - output_stat = os.stat(a.out) - except OSError: - output_stat = None - strings = set() - missing = [] # carved blobs an index.json lists that can't be read: skipped, reported - for arch, arch_dir in archives: - p = os.path.join(arch_dir, "index.json") - if not os.path.isfile(p): - continue - try: - # utf-8-sig: PowerShell 5.1 and old Notepad write JSON with a UTF-8 BOM, as the other readers here accept. - with open(p, encoding="utf-8-sig") as f: - rows = json.load(f)["files"] - if not isinstance(rows, list) or not all(isinstance(r, dict) for r in rows): - raise ValueError('"files" is not a list of entries') - except (OSError, ValueError, KeyError, TypeError) as e: - reason = getattr(e, "strerror", None) or (f"no {e} key" if isinstance(e, KeyError) else e) - print(f"ERROR: cannot read {p}: {reason}", file=sys.stderr) - return 2 - chain = [] # the streams of the blob being read: its first stream and those that continue it - for row_idx, r in enumerate(rows): - if r.get("type") == "bink2": - harvest(b"".join(chain), strings, a.min) - chain = [] - continue - head = r.get("head") - off = r.get("off") - err = None - if not isinstance(head, str): - err = f"row {row_idx} has a non-string head" - elif not isinstance(off, int) or isinstance(off, bool) or off < 0: - err = f"row {row_idx} has an invalid offset" - if err is not None: - print(f"ERROR: cannot read {p}: {err}", file=sys.stderr) - return 2 - # A row continues the blob before it when that stream filled whole 64 KiB blocks and this one does - # not start a stream of its own; it is read with that blob, whatever its own head says. - last = len(chain[-1]) if chain else 0 - if not (last and last % CONTINUATION_BLOCK == 0 and not head.startswith(NEW_STREAM_HEADS)): - harvest(b"".join(chain), strings, a.min) - chain = [] - if not (arch in full or head.startswith(META_HEADS)): - continue - blob = os.path.join(arch_dir, f"{off:012x}.bin") - try: - with open(blob, "rb") as f: - if output_stat is not None and os.path.samestat(os.fstat(f.fileno()), output_stat): - print(f"ERROR: --out {a.out} is one of the inputs ({blob}); choose another output file", - file=sys.stderr) - return 2 - data = f.read() - except OSError: - missing.append(blob) - harvest(b"".join(chain), strings, a.min) - chain = [] - continue - chain.append(data) - harvest(b"".join(chain), strings, a.min) - print(f"{arch}: {len(strings)} strings so far", flush=True) - if missing: - print(f"WARNING: {len(missing)} carved blobs listed in an index.json could not be read and were skipped " - f"(first: {missing[0]}). Re-run the carve to get their strings.", file=sys.stderr) - for x in a.extra: - if os.path.isdir(x): - try: - for _, _, files in os.walk(x, onerror=_raise_scan_error): - for fn in files: - strings.add(os.path.splitext(fn)[0]) - except OSError as e: - print(f"ERROR: cannot scan --extra directory {e.filename or x}: {e.strerror or e}", file=sys.stderr) - return 2 - elif os.path.isfile(x): - with open(x, "rb") as f: - harvest(f.read(), strings, a.min) - d = {} - for s in sorted(strings): - d.setdefault(f"{joaat(s):08x}", s) - # Other tools create the output parent too: a long harvest must not be lost to a missing folder. - try: - os.makedirs(os.path.dirname(os.path.abspath(a.out)), exist_ok=True) - with open(a.out, "w", encoding="utf-8", newline="\n") as f: - json.dump(d, f) - except OSError as e: - print(f"ERROR: cannot write {a.out}: {e}", file=sys.stderr) - return 2 - print(f"{len(strings)} strings -> {len(d)} hashes -> {a.out}") - return 0 - - -if __name__ == "__main__": - try: # a redirected stdout is strict ANSI code page under -I; write '?' for what it cannot encode - sys.stdout.reconfigure(errors="replace") - except (AttributeError, ValueError, OSError): - pass - sys.exit(main()) diff --git a/tools/heap_index_census.py b/tools/heap_index_census.py deleted file mode 100644 index b8dd8e6e7..000000000 --- a/tools/heap_index_census.py +++ /dev/null @@ -1,466 +0,0 @@ -r"""Where does a directly heap-indexing shader get the descriptor-heap base? (D3D-329, stdlib only) - -docs/d3d12_vulkan.md section 3.4 leaves open where the console driver passes the bound CBV/SRV/UAV and sampler heap -base (and stride) to a shader that indexes `ResourceDescriptorHeap` / `SamplerDescriptorHeap`: user SGPRs, which the -layer fills from the root signature, or system SGPRs, which the translator would have to expose as a new runtime -constant. This tool measures it over a disassembly folder. - -For every shader it reads the DXBC `SFI0` heap-indexing bits (tools/shader_meta.read_dxbc_meta) and follows a forward -dataflow over the reachable basic blocks, tagging every SGPR with where its value came from: - - * ("in", n) the value SGPR n held at entry (user data below the stage's user count, system above it; the - count is COMPUTE_PGM_RSRC2's USER_SGPR for CS, and for the graphics stages the translator's 32, - with the NGG s3 as system in MS/GS: no graphics count is measured yet); - * ("const", v) a 32-bit constant; - * ("ld", pc, i) dword i of an s_load / s_buffer_load at code offset pc; - * ("off", t, d) tag t plus an offset, d = True when the offset is not a constant. - -Each descriptor-width scalar load (s_load_dwordx4/x8/x16 from an SGPR pair) is then classified by its base: a -64-bit pointer from an input pair, a 32-bit pointer from one input SGPR with the high word a constant 0, a pointer -that was itself loaded from memory, or something else. Its offset is static (immediate or a known constant) or -dynamic, and the result's role (T#, S#, V#) comes from the instruction that consumes it. The census groups the -loads per stage and SFI0 class, so the heap base shows up as the input SGPR the loads of heap-indexing shaders -start from, and as the difference to the shaders that use only descriptor tables. - -It reads only the listings, the DXBC containers next to them (`/../.dxbc`), the carve index -(`/../index.json`, for the stage) and, for compute shaders, COMPUTE_PGM_RSRC2 at FSSM header word 0x138 -(`/../fssm/.fssm`, as tools/rdna2spirv.py does). It prints counts only, no shader bytes. - -Usage: - python -I tools/heap_index_census.py /shaders/dxbc/disasm [--json OUT] [--limit N] - -A missing folder, an unreadable carve index and an unwritable --json each give one ERROR line and exit 2. -""" -import argparse -import json -import os -import struct -import sys -from collections import Counter, defaultdict - -sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) -import shader_ir # noqa: E402 -import shader_meta # noqa: E402 -from report_paths import same_report_path # noqa: E402 - -USER_SGPRS = 32 # graphics stages: user data s0..s31 (tools/rdna2spirv.py USER_SGPRS) -SYSTEM_SGPRS = {"ms": (3,), "gs": (3,)} # NGG wave info in s3 (tools/rdna2spirv.py sys_sgprs) -DESC_LOADS = {"s_load_dwordx4": 4, "s_load_dwordx8": 8, "s_load_dwordx16": 16} -BRANCHES = {"s_branch", "s_cbranch_scc0", "s_cbranch_scc1", "s_cbranch_vccz", "s_cbranch_vccnz", - "s_cbranch_execz", "s_cbranch_execnz"} -ADDS = {"s_add_u32", "s_add_i32", "s_sub_u32", "s_sub_i32", "s_addc_u32", "s_subb_u32"} - - -class Skip(Exception): - """A listing the census cannot follow; the reason is counted, not fatal.""" - - -# ---- inputs ------------------------------------------------------------------------------------------------- - -def stage_index(disasm_dir): - path = os.path.join(os.path.dirname(os.path.abspath(disasm_dir)), "index.json") - with open(path, encoding="utf-8") as f: - rows = json.load(f) - return {e["file"][:-5]: e["stage"] for e in rows} - - -def sfi0_class(disasm_dir, name): - """'res+smp', 'res', 'smp', 'none', or None when the container is missing.""" - path = os.path.join(os.path.dirname(os.path.abspath(disasm_dir)), name + ".dxbc") - try: - with open(path, "rb") as f: - meta = shader_meta.read_dxbc_meta(f.read()) - except OSError: - return None - if "sfi0_resource_heap_directly_indexed" not in meta: - return None - res = meta["sfi0_resource_heap_directly_indexed"] - smp = meta["sfi0_sampler_heap_directly_indexed"] - return "res+smp" if res and smp else "res" if res else "smp" if smp else "none" - - -def cs_user_count(disasm_dir, name): - """USER_SGPR [5:1] of COMPUTE_PGM_RSRC2 (FSSM header word 0x138), or None.""" - path = os.path.join(os.path.dirname(os.path.abspath(disasm_dir)), "fssm", name + ".fssm") - try: - with open(path, "rb") as f: - hdr = f.read(0x13C) - except OSError: - return None - if len(hdr) < 0x13C: - return None - return (struct.unpack_from("> 1) & 31 - - -# ---- control flow ------------------------------------------------------------------------------------------- - -def blocks_of(insns): - """Basic blocks and successor lists, split at branches as tools/rdna2spirv.py does.""" - def next_pc(ins): - return ins["pc"] + len(ins["enc"]) // 2 - - def target(ins): - imm = next((x for x in ins["args"] if x["k"] == "imm"), None) - if imm is None: - raise Skip("branch without offset") - v = imm["v"] & 0xFFFF - return next_pc(ins) + 4 * (v - 0x10000 if v & 0x8000 else v) - - if any(shader_meta.base_op(i["op"]) in BRANCHES and not i.get("enc") for i in insns): - raise Skip("branch without encoding") - leaders = {insns[0]["pc"]} - for ins in insns: - if shader_meta.base_op(ins["op"]) in BRANCHES: - leaders.add(target(ins)) - leaders.add(next_pc(ins)) - pcs = {i["pc"] for i in insns} - if any(p not in pcs for p in leaders if p != next_pc(insns[-1])): - raise Skip("branch target outside code") - starts = sorted(p for p in leaders if p in pcs) - index = {p: n for n, p in enumerate(starts)} - if any(target(i) not in index for i in insns if shader_meta.base_op(i["op"]) in BRANCHES): - raise Skip("branch target outside code") - blocks = [[] for _ in starts] - cur = -1 - for ins in insns: - cur = index.get(ins["pc"], cur) - blocks[cur].append(ins) - succ = [] - for n, blk in enumerate(blocks): - last = next((i for i in blk if shader_meta.base_op(i["op"]) == "s_endpgm" or - shader_meta.base_op(i["op"]) in BRANCHES), None) - fall = [n + 1] if n + 1 < len(blocks) else [] - if last is None: - succ.append(fall) - elif shader_meta.base_op(last["op"]) == "s_endpgm": - succ.append([]) - elif shader_meta.base_op(last["op"]) == "s_branch": - succ.append([index[target(last)]]) - else: - succ.append(list(dict.fromkeys([index[target(last)]] + fall))) - return blocks, succ - - -# ---- dataflow ----------------------------------------------------------------------------------------------- - -def root(tag): - """(underlying tag, dynamic offset?) with the ("off", ...) wrappers removed.""" - dyn = False - while tag is not None and tag[0] == "off": - dyn = dyn or tag[2] - tag = tag[1] - return tag, dyn - - -def _src(sym, a): - """Tag of a one-dword source operand, or None.""" - c = shader_meta._imm_u32(a) - if c is not None: - return ("const", c) - if a["k"] == "sgpr" and a.get("n", 1) == 1: - return sym.get(a["r"]) - if a["k"] == "special" and a.get("t") == "null": - return ("const", 0) - return None - - -def _pointerish(tag): - t, _ = root(tag) - return t is not None and t[0] in ("in", "ld") - - -def step(sym, ins, on_load=None, on_use=None): - """Advance the SGPR tags over one instruction; report descriptor loads and their consumers.""" - op = shader_meta.base_op(ins["op"]) - a = ins["args"] - if not a: - return - if on_use is not None: - if op.startswith("image_") and len(a) >= 3 and a[2]["k"] == "sgpr": - on_use(sym.get(a[2]["r"]), "T#") - if op.startswith(shader_meta.SAMPLER_IMAGE_OPS) and len(a) >= 4 and a[3]["k"] == "sgpr": - on_use(sym.get(a[3]["r"]), "S#") - elif op.startswith(("buffer_", "tbuffer_")) and len(a) >= 3 and a[2]["k"] == "sgpr": - on_use(sym.get(a[2]["r"]), "V#") - elif op.startswith("s_buffer_") and len(a) >= 2 and a[1]["k"] == "sgpr": - on_use(sym.get(a[1]["r"]), "V#") - if on_load is not None and op in DESC_LOADS and len(a) >= 2 and a[1]["k"] == "sgpr" and a[1].get("n") == 2: - b = a[1]["r"] - off = _src(sym, a[2]) if len(a) >= 3 else ("const", 0) - on_load(ins["pc"], op, sym.get(b), sym.get(b + 1), off) - - _, writes = shader_meta._split_operands(ins) - if not writes: - return - new = {} - if op.startswith(("s_load_dword", "s_buffer_load_dword")) and a[0]["k"] == "sgpr": - for i in range(a[0].get("n", 1)): - new[a[0]["r"] + i] = ("ld", ins["pc"], i) - elif op in ("s_mov_b32", "s_movk_i32") and len(a) >= 2 and a[0]["k"] == "sgpr" and a[0].get("n", 1) == 1: - if op == "s_movk_i32": - v = a[1]["v"] & 0xFFFF - new[a[0]["r"]] = ("const", (v - 0x10000 if v & 0x8000 else v) & 0xFFFFFFFF) - else: - t = _src(sym, a[1]) - if t is not None: - new[a[0]["r"]] = t - elif op == "s_mov_b64" and len(a) >= 2 and a[0]["k"] == "sgpr" and a[0].get("n") == 2: - d = a[0]["r"] - if a[1]["k"] == "imm": - v = a[1]["v"] & 0xFFFFFFFFFFFFFFFF - new[d], new[d + 1] = ("const", v & 0xFFFFFFFF), ("const", v >> 32) - elif a[1]["k"] == "sgpr" and a[1].get("n") == 2: - for i in (0, 1): - if a[1]["r"] + i in sym: - new[d + i] = sym[a[1]["r"] + i] - elif (op in ADDS or op in shader_meta.LSHL_ADD_SHIFT) and len(a) >= 3 and a[0]["k"] == "sgpr": - tx, ty = _src(sym, a[1]), _src(sym, a[2]) - if op in shader_meta.LSHL_ADD_SHIFT: - tx, ty = ty, tx # s_lshlK_add_u32 d, idx, base: the base is the second source - cx = tx[1] if tx is not None and tx[0] == "const" else None - cy = ty[1] if ty is not None and ty[0] == "const" else None - if cx is not None and cy is not None and op not in ("s_addc_u32", "s_subb_u32"): - if op in shader_meta.LSHL_ADD_SHIFT: - new[a[0]["r"]] = ("const", ((cy << shader_meta.LSHL_ADD_SHIFT[op]) + cx) & 0xFFFFFFFF) - else: - new[a[0]["r"]] = ("const", shader_meta._fold_scalar_alu(op, cx, cy)) - elif cx == 0 and cy == 0: - new[a[0]["r"]] = ("const", 0) # high word of a pointer below 4 GB plus a carry of 0 - elif _pointerish(tx) and not _pointerish(ty): - new[a[0]["r"]] = ("off", tx, cy is None) - elif _pointerish(ty) and not _pointerish(tx) and not op.startswith(("s_sub", "s_subb")): - new[a[0]["r"]] = ("off", ty, cx is None) - elif op == "s_addk_i32" and a[0]["k"] == "sgpr": - old = sym.get(a[0]["r"]) - if old is not None and old[0] == "const": - v = a[1]["v"] & 0xFFFF - new[a[0]["r"]] = ("const", (old[1] + (v - 0x10000 if v & 0x8000 else v)) & 0xFFFFFFFF) - elif _pointerish(old): - new[a[0]["r"]] = ("off", old, False) - elif op in ("s_and_b32", "s_or_b32", "s_lshl_b32", "s_lshr_b32", "s_mul_i32", "s_xor_b32") and len(a) >= 3: - tx, ty = _src(sym, a[1]), _src(sym, a[2]) - if tx is not None and ty is not None and tx[0] == ty[0] == "const": - new[a[0]["r"]] = ("const", shader_meta._fold_scalar_alu(op, tx[1], ty[1])) - for r in writes: - if r in new: - sym[r] = new[r] - else: - sym.pop(r, None) - - -def analyse(insns, stage, user_count): - """Descriptor loads of one shader: [{"op", "base", "ptr", "offset", "roles"}], in code order.""" - blocks, succ = blocks_of(insns) - system = set(SYSTEM_SGPRS.get(stage, ())) - entry = [None] * len(blocks) - entry[0] = {r: ("in", r) for r in range(106)} - work = [0] - while work: - b = work.pop() - sym = dict(entry[b]) - for ins in blocks[b]: - if shader_meta.base_op(ins["op"]) == "s_endpgm": - break - step(sym, ins) - for s in succ[b]: - merged = sym if entry[s] is None else {k: v for k, v in entry[s].items() if sym.get(k) == v} - if merged != entry[s]: - entry[s] = dict(merged) - work.append(s) - - loads = {} - - def on_load(pc, op, lo, hi, off): - rlo, dyn_lo = root(lo) - rhi, _ = root(hi) - if rlo is not None and rlo[0] == "in": - n = rlo[1] - where = "system" if (n in system or n >= user_count) else "user" - if rhi == ("in", n + 1): - base, ptr = f"s[{n}:{n + 1}]", "ptr64" - elif hi == ("const", 0): - base, ptr = f"s{n}", "ptr32" - else: - base, ptr = f"s{n}", "ptr64_lo_only" - base = f"{where} {base}" - elif rlo is not None and rlo[0] == "ld": - base, ptr = "loaded pointer", "ptr32" if hi == ("const", 0) else "ptr64" - elif rlo is not None and rlo[0] == "const": - base, ptr = "constant", "const" - else: - base, ptr = "unknown", "unknown" - if off is not None and off[0] == "const" and not dyn_lo: - offset = ("static", off[1]) - else: - offset = ("dynamic", None) - loads[pc] = {"op": op, "base": base, "ptr": ptr, "offset": offset, "roles": set()} - - def on_use(tag, role): - if tag is not None and tag[0] == "ld" and tag[2] == 0 and tag[1] in loads: - loads[tag[1]]["roles"].add(role) - - for b in range(len(blocks)): - if entry[b] is None: - continue - sym = dict(entry[b]) - for ins in blocks[b]: - if shader_meta.base_op(ins["op"]) == "s_endpgm": - break - step(sym, ins, on_load, on_use) - return [loads[pc] for pc in sorted(loads)] - - -# ---- census ------------------------------------------------------------------------------------------------- - -def role_of(load): - if len(load["roles"]) == 1: - return next(iter(load["roles"])) - if not load["roles"]: - return "unused" if load["op"] != "s_load_dwordx16" else "x16" - return "mixed" - - -def census(disasm_dir, limit=None, progress=None, stages=None): - if stages is None: - stages = stage_index(disasm_dir) - names = sorted(n[:-2] for n in os.listdir(disasm_dir) if n.endswith(".s")) - if limit: - names = names[:limit] - skipped = Counter() - shaders = Counter() # (stage, sfi0) -> shaders - with_loads = Counter() # (stage, sfi0) -> shaders with a descriptor load - base_shaders = defaultdict(Counter) # (stage, sfi0) -> base -> shaders loading from it - load_rows = defaultdict(Counter) # (stage, sfi0) -> (base, ptr, role, offset kind) -> loads - static_align = defaultdict(Counter) # (stage, sfi0, role) -> "aligned32"/"aligned16"/"other" - static_max = defaultdict(int) # (stage, sfi0, role) -> largest static offset - for k, name in enumerate(names): - if progress and k % 2000 == 0: - progress(k, len(names)) - stage = stages.get(name) - sfi0 = sfi0_class(disasm_dir, name) - if stage is None or sfi0 is None: - skipped["no stage or SFI0"] += 1 - continue - info = shader_ir.parse_file(os.path.join(disasm_dir, name + ".s")) - if not info["insns"]: - skipped["no instructions"] += 1 - continue - if info["invalid"]: - skipped["embedded data words"] += 1 - continue - user = USER_SGPRS - if stage == "cs": - user = cs_user_count(disasm_dir, name) - if user is None: - skipped["no FSSM header"] += 1 - continue - try: - loads = analyse(info["insns"], stage, user) - except Skip as e: - skipped[str(e)] += 1 - continue - key = (stage, sfi0) - shaders[key] += 1 - if loads: - with_loads[key] += 1 - for base in {ld["base"] for ld in loads}: - base_shaders[key][base] += 1 - for ld in loads: - role = role_of(ld) - load_rows[key][(ld["base"], ld["ptr"], role, ld["offset"][0])] += 1 - if ld["offset"][0] == "static": - v = ld["offset"][1] - static_align[(stage, sfi0, role)]["aligned32" if v % 32 == 0 else - "aligned16" if v % 16 == 0 else "other"] += 1 - static_max[(stage, sfi0, role)] = max(static_max[(stage, sfi0, role)], v) - out = {"shaders_read": len(names), "skipped": dict(skipped), "groups": {}} - for key in sorted(shaders): - stage, sfi0 = key - g = { - "shaders": shaders[key], - "shaders_with_descriptor_loads": with_loads[key], - "shaders_per_base": dict(base_shaders[key].most_common()), - "loads": [{"base": b, "ptr": p, "role": r, "offset": o, "count": c} - for (b, p, r, o), c in load_rows[key].most_common()], - "static_offsets": {role: {**dict(static_align[(s, f, role)]), "max": static_max[(s, f, role)]} - for (s, f, role) in sorted(static_align) if (s, f) == key}, - } - out["groups"][f"{stage} sfi0={sfi0}"] = g - return out - - -def print_report(out, top=6): - print(f"shaders read: {out['shaders_read']}; skipped: {out['skipped'] or 'none'}") - for name, g in out["groups"].items(): - print(f"\n{name}: {g['shaders']} shaders, {g['shaders_with_descriptor_loads']} with descriptor loads") - for base, n in list(g["shaders_per_base"].items())[:top]: - print(f" base {base:<22} {n:>6} shaders") - for row in g["loads"][:top]: - print(f" load {row['base']:<22} {row['ptr']:<14} {row['role']:<6} {row['offset']:<8} {row['count']:>7}") - for role, st in g["static_offsets"].items(): - print(f" static {role:<6} " + ", ".join(f"{k} {v}" for k, v in st.items())) - - -def main(argv=None): - ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) - ap.add_argument("disasm", help="/shaders/dxbc/disasm") - ap.add_argument("--json", help="write the full census here") - ap.add_argument("--limit", type=shader_ir.positive_int, help="only the first N listings (sorted by name)") - args = ap.parse_args(argv) - if not os.path.isdir(args.disasm): - print(f"ERROR: {args.disasm} is not a folder", file=sys.stderr) - return 2 - if args.json: - # The census is written last, after every listing has been read, so a report replacing one of - # them or the carve index would silently destroy what the run just used. - index_path = os.path.join(os.path.dirname(os.path.abspath(args.disasm)), "index.json") - if same_report_path(args.json, index_path): - print(f"ERROR: --json would overwrite the carve index: {args.json}", file=sys.stderr) - return 2 - disasm = os.path.realpath(args.disasm) - target = os.path.realpath(os.path.abspath(args.json)) - try: - inside = os.path.commonpath([disasm, target]) == disasm - except ValueError: # paths on different Windows drives - inside = False - if inside: - print(f"ERROR: --json must not write inside the disasm folder it reads: {args.json}", file=sys.stderr) - return 2 - try: - stages = stage_index(args.disasm) - except (OSError, ValueError, KeyError, TypeError) as e: - print(f"ERROR: cannot read the carve index next to {args.disasm}: {e}", file=sys.stderr) - return 2 - if args.json: - # Besides the listings and the carve index, the census reads each shader's DXBC container and - # FSSM header next to the disasm folder. A report landing on one of those (or a hard link to it) - # would destroy an input the run just used, so refuse those names too. - parent = os.path.dirname(os.path.abspath(args.disasm)) - for name in stages: - for path in (os.path.join(parent, name + ".dxbc"), - os.path.join(parent, "fssm", name + ".fssm")): - if same_report_path(args.json, path): - print(f"ERROR: --json would overwrite an input the census reads: {path}", file=sys.stderr) - return 2 - out = census(args.disasm, args.limit, stages=stages, - progress=lambda k, n: print(f" {k}/{n}", file=sys.stderr, flush=True)) - print_report(out) - if args.json: - try: - d = os.path.dirname(os.path.abspath(args.json)) - os.makedirs(d, exist_ok=True) - with open(args.json, "w", encoding="utf-8", newline="\n") as f: - json.dump(out, f, indent=1, sort_keys=True) - f.write("\n") - except OSError as e: - print(f"ERROR: cannot write {args.json}: {e}", file=sys.stderr) - return 2 - return 0 - - -if __name__ == "__main__": - try: # a redirected stdout is strict ANSI code page under -I; write '?' for what it cannot encode - sys.stdout.reconfigure(errors="replace") - except (AttributeError, ValueError, OSError): - pass - sys.exit(main()) diff --git a/tools/hw_oracle/__init__.py b/tools/hw_oracle/__init__.py deleted file mode 100644 index cf839a83a..000000000 --- a/tools/hw_oracle/__init__.py +++ /dev/null @@ -1,10 +0,0 @@ -"""Optional hardware oracle: run small hand-written AMD GPU programs natively and read the result back. - -asm.py program text -> GFX10/GFX11 kernels, HSA metadata, the SALU opcodes that differ (no hardware needed) -runner.py finds AMD clang, the HIP runtime DLL and a host C compiler, builds hw_oracle.c, runs kernels -tsharp.py image T# words per family (gfx10, gfx11) and the raw kernel that image_loads a texture (tools/image_fuzz.py) -hw_oracle.c the launcher: loads a code object through the driver's HIP runtime and dumps each kernel's output words - -Everything here is optional. When a tool is missing, runner.Unavailable is raised and callers exit 77. -See docs/shader_validation.md ("Hardware oracle"). -""" diff --git a/tools/hw_oracle/asm.py b/tools/hw_oracle/asm.py deleted file mode 100644 index 5aee6e9ce..000000000 --- a/tools/hw_oracle/asm.py +++ /dev/null @@ -1,465 +0,0 @@ -"""Wrap a scalar-ALU test program in a kernel prologue/epilogue and HSA metadata. Pure text, no hardware. - -A program is the list of lines tools/salu_diff.py generates: s_mov_b32 seeds, scalar ops, and an observation tail -that leaves four words in v8..v11. The kernel loads its output pointer from the kernarg segment, runs the program -on one lane (the launcher starts a single thread, so exec = lane 0) and stores v[8:11] as four dwords. - -Registers: s[0:1] kernarg pointer, s[2:3] output pointer; the programs use s4..s19 and s30, v8..v11. -""" -import re - -# SALU opcodes salu_diff models that GFX11 no longer has. Spellings that were only renamed (s_andn2_b32 -> -# s_and_not1_b32, s_ff1_i32_b32 -> s_ctz_i32_b32, s_flbit_i32_b32 -> s_clz_i32_u32, ...) are accepted by LLVM as -# aliases with the same semantics, so they are not listed here. -GFX11_REMOVED = { - "s_ff0_i32_b32": "removed in GFX11 (no find-first-zero; the ISA has only s_ctz = ff1)", - "s_ff0_i32_b64": "removed in GFX11 (no find-first-zero; the ISA has only s_ctz = ff1)", -} -# GFX12 also drops the SOPK compares: AMD clang (rocm-sdk-core 10.0.0) assembles all twelve for gfx1150 and rejects -# every one for gfx1201 ("instruction not supported on this GPU"). -GFX12_REMOVED = dict(GFX11_REMOVED, **{ - f"s_cmpk_{cond}_{ty}": "removed in GFX12 (no SOPK compares; s_cmp with a literal is the replacement)" - for cond in ("eq", "lg", "gt", "ge", "lt", "le") for ty in ("i32", "u32") -}) - -_LITERAL_FREE = ("s_movk_i32", "s_addk_i32", "s_mulk_i32") - - -def family(arch): - """'gfx10', 'gfx11' or 'gfx12' for gfx10xx, gfx11xx and gfx12xx. GFX12 uses GFX11's spellings for everything - the kernels here emit; it differs only in which SALU opcodes exist (GFX12_REMOVED).""" - m = re.fullmatch(r"gfx(\d+?)[0-9a-f]{2}", arch) - if not m or m.group(1) not in ("10", "11", "12"): - raise ValueError(f"unsupported GPU architecture {arch!r} (expected gfx10xx, gfx11xx or gfx12xx)") - return "gfx" + m.group(1) - - -def _is_inline(tok): - try: - return -16 <= int(tok, 0) <= 64 - except ValueError: - return True # registers and symbols are not literals - - -def literals(line): - """The distinct 32-bit literal values an instruction needs (SOPK immediates are not literals).""" - op, _, rest = line.partition(" ") - if not op.startswith("s_") or op.rstrip("_") in _LITERAL_FREE or re.match(r"s_cmpk_", op): - return set() - toks = [t.strip() for t in rest.split(",")] if rest else [] - # -1 and 0xffffffff are the same 32-bit value, so they share one literal slot - return {int(t, 0) & 0xFFFFFFFF for t in toks if not t.startswith("s") and not _is_inline(t)} - - -def skip_reason(lines, arch): - """Why a program cannot be run on this architecture, or None. Hardware allows one literal per instruction.""" - removed = {"gfx10": {}, "gfx11": GFX11_REMOVED, "gfx12": GFX12_REMOVED}[family(arch)] - for line in lines: - op = line.partition(" ")[0] - if op in removed: - return f"{op}: {removed[op]}" - if len(literals(line)) > 1: - return "two different literals in one instruction (not encodable)" - return None - - -class ModeUnavailable(Exception): - """A requested float MODE field cannot be encoded on this architecture.""" - - -class Kernel: - """One program to run. lines: the instructions. raw=False wraps them (output pointer load, v[8:11] store); - raw=True means the lines already end with their own stores and s_endpgm and only get the output pointer in - s[2:3]. threads: workgroup size; words: dwords read back; wave: 32 or 64. mode: the float MODE the kernel - starts with (raw kernels only), a dict of MODE_FIELDS names to values; None keeps the assembler's defaults. - On gfx1170+ the assembler rejects the ieee and dx10_clamp directives, so requesting those fields raises - ModeUnavailable while the denormal and rounding fields still work. - lds: bytes of LDS the kernel allocates (.amdhsa_group_segment_fixed_size and the metadata's - .group_segment_fixed_size; without it the hardware gives the group no LDS); vgprs, sgprs: registers the kernel uses - (default 32 and 40).""" - - def __init__(self, lines, wave=32, threads=1, words=4, raw=False, mode=None, lds=0, vgprs=32, sgprs=40): - self.lines, self.wave, self.threads, self.words, self.raw = list(lines), wave, threads, words, raw - self.lds, self.vgprs, self.sgprs = lds, vgprs, sgprs - if not 0 <= lds <= 65536 or lds % 4: - raise ValueError(f"LDS size {lds} is not a multiple of 4 in 0..65536") - if not 1 <= vgprs <= 256: - raise ValueError(f"vgprs {vgprs} is not in 1..256") - if not 1 <= sgprs <= 104: - raise ValueError(f"sgprs {sgprs} is not in 1..104") - self.mode = dict(mode or {}) - unknown = set(self.mode) - set(MODE_FIELDS) - if unknown: - raise ValueError(f"unknown MODE fields {sorted(unknown)} (known: {sorted(MODE_FIELDS)})") - - -# Float MODE the kernel descriptor starts a wave with, as .amdhsa_* directives. The assembler's defaults (checked on -# gfx1150 by reading the register back, see docs/shader_validation.md): IEEE 1, DX10_CLAMP 1, f32 denormals -# flushed (denorm_mode_32 = 0), f16/f64 denormals kept (3), all rounding to nearest even (0). -MODE_FIELDS = { - "ieee": ".amdhsa_ieee_mode", - "dx10_clamp": ".amdhsa_dx10_clamp", - "denorm32": ".amdhsa_float_denorm_mode_32", - "denorm16_64": ".amdhsa_float_denorm_mode_16_64", - "round32": ".amdhsa_float_round_mode_32", - "round16_64": ".amdhsa_float_round_mode_16_64", -} -# AMD clang (rocm-sdk-core 10.0.0) rejects these two directives on gfx1170 and later; the hardware keeps its -# fixed IEEE/DX10_CLAMP behaviour there, so a run that asks for either field is a skip, not an assembler failure. -_MODE_FIELDS_GONE_ON_GFX1170 = ("ieee", "dx10_clamp") - - -# MODE fields a kernel descriptor can no longer set: GFX11.7 and GFX12 have fixed IEEE / DX10_CLAMP behaviour, and AMD -# clang (rocm-sdk-core 10.0.0) rejects .amdhsa_ieee_mode and .amdhsa_dx10_clamp for gfx1201 with "directive -# unsupported on gfx1170+" (FUZZ-43, found by @Dom-in in #1548). The four denormal and rounding fields still assemble. -_MODE_FIXED = ("ieee", "dx10_clamp") - - -def is_gfx1170_or_later(arch): - """True for GFX11.7 and GFX12 (gfx1170 and later), which RDNA2 and RDNA3 code does not assemble for as is.""" - fam = family(arch) - return fam == "gfx12" or (fam == "gfx11" and int(arch[5], 16) >= 7) - - -def rdna23_skip_reason(arch): - """Why a hardware suite whose kernels set the MODE fields gfx1170+ cannot encode cannot run on this GPU, or - None. Remaining users: the OnHardware guards of f32_fuzz and f16_trans_sweep, whose MODE probes set IEEE and - DX10_CLAMP, which AMD clang (rocm-sdk-core 10.0.0) rejects for gfx1170+ (FUZZ-43) so the probe cannot run there. - The fuzzers whose kernels do assemble there gate per family (valu_fuzz.hw_family_skip_reason) or per program - (lds_fuzz.hw_skip_reason) instead of taking this blanket reason.""" - if not is_gfx1170_or_later(arch): - return None - return f"{arch} (GFX11.7 or GFX12) is not RDNA2 or RDNA3: the kernels here do not assemble for it" - - -def mode_skip_reason(mode, arch): - """Why a kernel's starting MODE cannot be set on this architecture, or None. A kernel that asks for one of - _MODE_FIXED on gfx1170+ (GFX11.7 and GFX12) is reported as not runnable there, rather than reaching the assembler, - which rejects the directive and, when every kernel of a chunk sets it, the whole chunk.""" - if not is_gfx1170_or_later(arch): - return None - fixed = sorted(k for k in (mode or {}) if k in _MODE_FIXED) - if not fixed: - return None - return (f"MODE {', '.join(fixed)} cannot be set on {arch}: {', '.join(MODE_FIELDS[k] for k in fixed)} " - "is unsupported on gfx1170+ (the behaviour is fixed there)") - - -# The global memory instructions GFX11 renamed, under their GFX10 names. A raw kernel body is written with the -# GFX11 ones (crosslane_fuzz stores with global_store_b32); a GFX10 assembler only takes the old spelling. -_GFX10_NAMES = {f"global_{kind}_b{bits}": f"global_{kind}_dword{suffix}" - for kind in ("load", "store") for bits, suffix in ((32, ""), (64, "x2"), (96, "x3"), (128, "x4"))} - - -def gfx10_spelling(line): - """A raw kernel line with a renamed memory mnemonic put back to its GFX10 name (the same instruction).""" - op, sep, rest = line.partition(" ") - return _GFX10_NAMES.get(op, op) + sep + rest - - -_REG = re.compile(r"(? / v[a:b] and s / s[a:b], 0 when there are none.""" - top = {"v": 0, "s": 0} - for line in lines: - for kind, single, last in _REG.findall(line.split(";", 1)[0]): - top[kind] = max(top[kind], int(last or single) + 1) - return top["v"], top["s"] - - -def register_counts(lines, vgprs, sgprs): - """The .amdhsa_next_free_vgpr / _sgpr a kernel gets: what was asked for, raised to cover every register the lines - name (at most 256 VGPRs and 104 SGPRs; a program past that is the assembler's to reject). A descriptor that - allocates fewer leaves the program registers that read back 0: measured on gfx1036, v16 and up under the wrapped - kernels' old fixed `.amdhsa_next_free_vgpr 16`.""" - v, s = regs_used(lines) - return min(max(vgprs, v), 256), min(max(sgprs, s), 104) - - -def raw_kernel_text(name, lines, arch, wave=32, mode=None, lds=0, vgprs=32, sgprs=40): - """A kernel whose body does its own stores. s[0:1] is the kernarg pointer, s[2:3] gets the output pointer.""" - fam = family(arch) - vgprs, sgprs = register_counts(lines, vgprs, sgprs) - if int(arch[3:], 16) >= 0x1170: - unsupported = sorted(set(mode or {}) & set(_MODE_FIELDS_GONE_ON_GFX1170)) - if unsupported: - fields = ", ".join(unsupported) - raise ModeUnavailable( - f"{fields} cannot be set on {arch}: AMD clang rejects .amdhsa_ieee_mode and .amdhsa_dx10_clamp " - "on gfx1170+, and the hardware keeps its fixed behaviour there; only denormal and rounding " - "mode fields are available") - modes = "".join(f"\n {MODE_FIELDS[k]} {int(v)}" for k, v in sorted((mode or {}).items())) - load = "s_load_b64" if fam == "gfx11" else "s_load_dwordx2" - if fam == "gfx10": - lines = [gfx10_spelling(ln) for ln in lines] - body = "\n".join(" " + ln for ln in lines) - return f""".globl {name} -.p2align 8 -.type {name},@function -{name}: - {load} s[2:3], s[0:1], 0x0 - s_waitcnt lgkmcnt(0) -{body} -.rodata -.p2align 6 -.amdhsa_kernel {name} - .amdhsa_user_sgpr_kernarg_segment_ptr 1 - .amdhsa_next_free_vgpr {vgprs} - .amdhsa_next_free_sgpr {sgprs} - .amdhsa_group_segment_fixed_size {lds} - .amdhsa_wavefront_size32 {1 if wave == 32 else 0} - .amdhsa_system_vgpr_workitem_id 0{modes} -.end_amdhsa_kernel -.text -""" - - -def kernel_text(name, lines, arch, wave=32, vgprs=16, sgprs=32, lds=0): - """Assembly for one kernel. The descriptor takes the wave size, the register counts (raised to the registers - the lines name, register_counts) and the LDS size (the group segment: without it a Linux launcher has nothing - to program COMPUTE_PGM_RSRC2.LDS_SIZE from). It used to be fixed at wave32, 16 VGPRs and 32 SGPRs: on gfx1036 - v16 and up read back 0 and a Kernel(wave=64) ran as wave32 (the lane ids of a full EXEC had 32 lanes).""" - fam = family(arch) - vgprs, sgprs = register_counts(lines, vgprs, sgprs) - load = "s_load_dwordx2" if fam == "gfx10" else "s_load_b64" - store = "global_store_dwordx4" if fam == "gfx10" else "global_store_b128" - body = "\n".join(" " + line for line in lines) - return f""".globl {name} -.p2align 8 -.type {name},@function -{name}: - {load} s[2:3], s[0:1], 0x0 - s_waitcnt lgkmcnt(0) - v_mov_b32 v0, 0 -{body} - {store} v0, v[8:11], s[2:3] - s_nop 0 - s_endpgm -.rodata -.p2align 6 -.amdhsa_kernel {name} - .amdhsa_user_sgpr_kernarg_segment_ptr 1 - .amdhsa_next_free_vgpr {vgprs} - .amdhsa_next_free_sgpr {sgprs} - .amdhsa_group_segment_fixed_size {lds} - .amdhsa_wavefront_size32 {1 if wave == 32 else 0} - .amdhsa_system_vgpr_workitem_id 0 -.end_amdhsa_kernel -.text -""" - - -def metadata(names, wave=32, lds=None, vgprs=None, sgprs=None): - """The HSA metadata block. Without it the HIP runtime fails the load with hipErrorNoBinaryForGpu (209). - lds / vgprs / sgprs: per kernel (lists as long as names); default 0 bytes of LDS, 32 VGPRs and 40 SGPRs.""" - out = [".amdgpu_metadata", "---", "amdhsa.version: [1, 2]", "amdhsa.kernels:"] - for i, n in enumerate(names): - out += [f" - .name: {n}", f" .symbol: {n}.kd", " .args:", - " - {.offset: 0, .size: 8, .value_kind: global_buffer, .address_space: global}", - f" .group_segment_fixed_size: {lds[i] if lds else 0}", " .private_segment_fixed_size: 0", - " .kernarg_segment_align: 8", " .kernarg_segment_size: 8", " .max_flat_workgroup_size: 1024", - f" .sgpr_count: {sgprs[i] if sgprs else 40}", f" .vgpr_count: {vgprs[i] if vgprs else 32}", f" .wavefront_size: {wave}"] - out.append(".end_amdgpu_metadata") - return "\n".join(out) + "\n" - - -def module_text(programs, arch, prefix="k", wave=32): - """(assembly text, kernel names, first source line of each kernel) for a list of programs. A program is a list - of lines (wrapped as a scalar test) or a Kernel.""" - parts = [f'.amdgcn_target "amdgcn-amd-amdhsa--{arch}"', ".text"] - names, starts, line_no, lds, vgprs, sgprs = [], [], 2, [], [], [] - for i, prog in enumerate(programs): - name = f"{prefix}{i}" - lds.append(prog.lds if isinstance(prog, Kernel) else 0) - if isinstance(prog, Kernel): - vg, sg = register_counts(prog.lines, prog.vgprs, prog.sgprs) - text = (raw_kernel_text(name, prog.lines, arch, prog.wave, prog.mode, prog.lds, vg, sg) if prog.raw - else kernel_text(name, prog.lines, arch, prog.wave, vg, sg, prog.lds)) - else: - vg, sg = register_counts(prog, 16, 32) - text = kernel_text(name, prog, arch, wave, vg, sg) - vgprs.append(vg) - sgprs.append(sg) - names.append(name) - starts.append(line_no + 1) - parts.append(text.rstrip("\n")) - line_no += text.count("\n") + 0 - parts.append(metadata(names, wave, lds, vgprs, sgprs).rstrip("\n")) - return "\n".join(parts) + "\n", names, starts - - -# ---- f32 vector ALU: what GFX11 does not have, or has under another name (tools/f32_fuzz.py --oracle hw) ---- -# Checked by assembling every f32_fuzz opcode with llvm-mc for gfx1013 (the console), gfx1010, gfx1030, gfx1100, -# gfx1150 and gfx1200. The four mad opcodes exist on GFX10.1 only (gfx1010, gfx1011, gfx1013): gfx1030 (RDNA2 -# desktop) and every GFX11 part reject them. They are not "renamed": v_fma_f32, v_fmac_f32, v_fmaak_f32 and -# v_fma_dx9_zero_f32 round once where the mad opcodes round the product first, so substituting one would compare a -# different instruction. -_MAD_GONE = "exists on GFX10.1 only (gfx1010/1011/1013), not on gfx1030 or GFX11; {} is fused, a different instruction" -VALU_REMOVED = { - "v_mad_f32": _MAD_GONE.format("v_fma_f32"), - "v_mac_f32": _MAD_GONE.format("v_fmac_f32"), - "v_madak_f32": _MAD_GONE.format("v_fmaak_f32"), - "v_madmk_f32": _MAD_GONE.format("v_fmamk_f32"), - "v_mad_legacy_f32": _MAD_GONE.format("v_fma_dx9_zero_f32"), -} -# Same instruction, new mnemonic: the assembler takes the GFX10 spelling for GFX11 and encodes the GFX11 name. -GFX11_VALU_RENAMED = { - "v_mul_legacy_f32": "v_mul_dx9_zero_f32", # DX9 rule: 0 * anything = 0 (the oracle itself checks it) - "v_cvt_pkrtz_f16_f32": "v_cvt_pk_rtz_f16_f32", -} - - -# ---- LDS (ds_*): GFX11 renamed the loads, stores and two atomics (tools/lds_fuzz.py --oracle hw) ---- -# Checked by assembling every ds_* mnemonic lds_fuzz emits with AMD clang for gfx1030 and gfx1150: the assembler takes -# the GFX10 spelling of all of them on gfx1150 except ds_cmpst_rtn_b32 ("instruction not supported on this GPU"), and -# takes the GFX11 spelling on gfx1030 for none. The new spelling is used on GFX11/GFX12 so the program text is what -# the target names, not what an alias happens to accept. ds_cmpstore_rtn_b32 also takes its two data operands in the -# other order (ds_line), and GFX12 spells the barrier and the LDS wait differently (sync_lines). -DS_RENAMED_GFX11 = { - "ds_wrxchg_rtn_b32": "ds_storexchg_rtn_b32", - "ds_cmpst_rtn_b32": "ds_cmpstore_rtn_b32", -} -_DS_STEMS_GFX11 = (("ds_read2st64_", "ds_load_2addr_stride64_"), ("ds_read2_", "ds_load_2addr_"), - ("ds_write2st64_", "ds_store_2addr_stride64_"), ("ds_write2_", "ds_store_2addr_"), - ("ds_read_", "ds_load_"), ("ds_write_", "ds_store_")) - - -def ds_mnemonic(op, arch): - """The spelling of a ds_* mnemonic for this architecture (GFX10 spellings in, as lds_fuzz writes them).""" - if family(arch) == "gfx10" or not op.startswith("ds_"): - return op - if op in DS_RENAMED_GFX11: - return DS_RENAMED_GFX11[op] - for old, new in _DS_STEMS_GFX11: - if op.startswith(old): - return new + op[len(old):] - return op - - -def ds_line(line, arch): - """A whole instruction line (GFX10 spelling and operand order in) respelled for the architecture. On GFX11 and - GFX12 ds_cmpstore_rtn_b32 takes the value to store first and the compare value second, the reverse of GFX10's - ds_cmpst_rtn_b32 vdst, vaddr, cmp, store (measured on gfx1150: tools/lds_fuzz.py --oracle hw, and it is what LLVM's - cmpxchg selection does for GFX11; measured on gfx1201, an RX 9070 XT: with M = 7 at the address, data v1 = 9 and - v2 = 7 the dword becomes 9 and with v1 = 7, v2 = 9 it stays 7, for the rtn and the non-returning form, while - gfx1036's ds_cmpst does the opposite); llvm-mc encodes both spellings of the same text identically, so only the - operand order tells them apart.""" - op, sep, rest = line.partition(" ") - if op == "ds_cmpst_rtn_b32" and family(arch) in ("gfx11", "gfx12"): - m = re.fullmatch(r"(v\d+),\s*(v\d+),\s*(v\d+),\s*(v\d+)(.*)", rest) - if not m: - raise ValueError(f"cannot swap the operands of {line!r}") - dst, addr, cmp_, store, tail = m.groups() - rest = f"{dst}, {addr}, {store}, {cmp_}{tail}" - elif op == "ds_cmpst_b32" and family(arch) in ("gfx11", "gfx12"): - # The non-returning form is renamed as well, and its two data operands swap the same way: GFX10's - # ds_cmpst_b32 vaddr, cmp, store is GFX11's ds_cmpstore_b32 vaddr, store, cmp (measured on gfx1100: with - # M = 7, vaddr = 0 and data v1 = 9, v2 = 7 the dword becomes 9, so the store operand is v1; the same on - # gfx1201). The rename is done here rather than in DS_RENAMED_GFX11 so that it never happens without the - # swap, which would silently compare and store the wrong way round. - m = re.fullmatch(r"(v\d+),\s*(v\d+),\s*(v\d+)(.*)", rest) - if not m: - raise ValueError(f"cannot swap the operands of {line!r}") - addr, cmp_, store, tail = m.groups() - return f"ds_cmpstore_b32 {addr}, {store}, {cmp_}{tail}" - return ds_mnemonic(op, arch) + sep + rest - - -def sync_lines(line, arch): - """A wait or barrier line (GFX10/GFX11 spelling in) as the instructions that do it on this architecture. GFX12 has - no s_barrier (AMD LLVM 23: "instruction not supported on this GPU (gfx1201)"); a workgroup barrier there is - s_barrier_signal -1 then s_barrier_wait -1. It also split lgkmcnt into dscnt (LDS) and kmcnt (scalar memory), so - a wait for the LDS is s_wait_dscnt 0 rather than the legacy s_waitcnt encoding the assembler still takes.""" - if family(arch) == "gfx12": - text = line.strip() - if text == "s_barrier": - return ["s_barrier_signal -1", "s_barrier_wait -1"] - if text == "s_waitcnt lgkmcnt(0)": - return ["s_wait_dscnt 0"] - return [line] - - -def valu_skip_reason(op, arch): - """Why an f32 VALU opcode cannot be run on this architecture, or None.""" - if op in VALU_REMOVED and arch not in ("gfx1010", "gfx1011", "gfx1012", "gfx1013"): - return f"{op}: {VALU_REMOVED[op]}" - return None - - -# ---- true16: LLVM 23 makes GFX11's 16-bit operands half registers (v8.l) and rejects a bare v8 there ---- -# The one-source f16 ops the fuzzers and sweeps run here: the two conversions and f16_trans_sweep's seven. -_F16_UNARY = "|".join(f"v_{op}_f16" for op in ("exp", "log", "rcp", "rsq", "sqrt", "sin", "cos")) -_F16_DST = re.compile(rf"^([ \t]*(?:v_cvt_f16_f32|{_F16_UNARY})(?:_e32|_e64)?[ \t]+v\d+)(?=[ \t]*,)", re.M) -_F16_SRC = re.compile(rf"^([ \t]*(?:v_cvt_f32_f16|{_F16_UNARY})(?:_e32|_e64)?[ \t]+v\d+(?:\.[lh])?[ \t]*," - r"[-| \ta-z(]*\bv\d+)\b(?!\.[lh])", re.M) -# These binary instructions use 16-bit VGPRs for all three operands. Packed operations and the VOP3 instructions the -# fuzzers emit with op_sel keep their existing operand spelling. -_TRUE16_BINARY = re.compile( - r"^([ \t]*v_(?:(?:add|sub|mul|max|min)_f16|mul_lo_u16|lshlrev_b16|lshrrev_b16|ashrrev_i16|" - r"(?:max|min)_[ui]16)(?:_e32|_e64)?[ \t]+)([^/;\r\n]+)", re.M) -_BARE_VGPR = re.compile(r"\bv\d+\b(?!\.[lh])") - - -def true16_spelling(text): - """The 16-bit operands of those ops written as the low half, which is what a bare register means there on GFX10 - and to older assemblers. Line numbers don't change, so error lines still map to kernels.""" - def binary(match): - prefix, operands = match.groups() - if re.search(r"\bop_sel\s*:", operands): - return match[0] - return prefix + _BARE_VGPR.sub(r"\g<0>.l", operands) - - text = _F16_SRC.sub(r"\1.l", _F16_DST.sub(r"\1.l", text)) - return _TRUE16_BINARY.sub(binary, text) - - -def needs_true16(assembles): - """Probe fixed input so a failed generated instruction never changes the chosen spelling.""" - bare = "v_cvt_f16_f32 v8, v1\n" - return not assembles(bare) and assembles(true16_spelling(bare)) - - -# ---- op_sel on GFX11+: the two-source 16-bit integer VOP3 ops want it on the registers too ---- -# This is separate from true16_spelling: AMD LLVM 23 (rocm-sdk-core 10.0.0) still takes a bare `v_cvt_f16_f32 v8, v1` -# on gfx1100, gfx1150 and gfx1201, so the runner's true16 probe says no, yet it rejects -# `v_max_u16_e64 v14, s12, v5 op_sel:[1,0,0]` on all three ("operands are not valid for this GPU or mode") and takes -# `v_max_u16_e64 v14.l, s12, v5.l op_sel:[1,0,0]`, which encodes to the same op_sel bits and operands as gfx1036's -# bare form. v_add_nc/v_sub_nc_*16 and the three-source 16-bit ops still take the bare form there. -_OPSEL16_OPS = ("v_ashrrev_i16", "v_lshlrev_b16", "v_lshrrev_b16", "v_max_i16", "v_max_u16", "v_min_i16", - "v_min_u16", "v_mul_lo_u16") -_OPSEL16 = re.compile(rf"^([ \t]*(?:{'|'.join(_OPSEL16_OPS)})(?:_e64)?[ \t]+)([^\n]*?)([ \t]+op_sel:\[([01,]+)\])" - r"([^\n]*)$", re.M) - - -def _opsel16_halves(m): - """One _OPSEL16 line with each bare VGPR operand named by the half its op_sel bit picks: bit i for source i, - the last bit for the destination. The op_sel list itself is kept, since SGPR and constant sources still - take their half from it.""" - head, operands, opsel, bits, tail = m.groups() - ops = [o.strip() for o in operands.split(",")] - bits = [b == "1" for b in bits.split(",")] - if len(bits) != len(ops): # not the dst + sources shape this respells; leave it to the assembler to judge - return m.group(0) - for i, o in enumerate(ops): - if re.fullmatch(r"v\d+", o): - ops[i] = o + (".h" if bits[i - 1] else ".l") # i - 1: the destination (operand 0) is the last bit - return head + ", ".join(ops) + opsel + tail - - -def opsel16_spelling(text): - """The VGPRs of the _OPSEL16_OPS lines that have op_sel, written as the half it selects, for GFX11 and later. - Lines without op_sel and every other op are left as they are. Line numbers don't change.""" - return _OPSEL16.sub(_opsel16_halves, text) - - -def failing_kernels(stderr, starts): - """Indices of the kernels an assembler error message points into (error lines are 'file:LINE:COL: error').""" - bad = set() - for m in re.finditer(r":(\d+):\d+: error", stderr): - ln = int(m.group(1)) - k = max((i for i, s in enumerate(starts) if s <= ln), default=None) - if k is not None: - bad.add(k) - return bad diff --git a/tools/hw_oracle/drm.py b/tools/hw_oracle/drm.py deleted file mode 100644 index 701bbcb84..000000000 --- a/tools/hw_oracle/drm.py +++ /dev/null @@ -1,225 +0,0 @@ -"""The Linux backend of the hardware oracle: the same kernels, run as raw compute dispatches through the kernel -driver (libdrm_amdgpu) by hw_oracle_drm.c. Standard library only. No ROCm: an assembler with the amdgcn target -(clang from the distribution's LLVM), gcc and the libdrm headers are enough. - - LEONIDA_HW_DRM_NODE the render node of the GPU to use, for example /dev/dri/renderD129. Required: there - is no default, so that a raw command stream never goes to a GPU by accident. - `ls -l /dev/dri/by-path` shows which node belongs to which PCI device. - LEONIDA_HW_DRM_ALLOW_DISPLAY set to 1 to use a GPU that has a display connected. A kernel that hangs makes the - kernel driver reset the GPU, and with it everything shown on that display. - LEONIDA_AMD_CLANG, LEONIDA_HOST_CC, LEONIDA_HW_ARCH as in runner.py - -The launcher supports compute engine versions 10, 11 and 12: GFX10 (RDNA1 and RDNA2), GFX11 (RDNA3) and -GFX12 (RDNA4). The registers the launcher writes sit at the same offsets on all three; only the preamble and -the cu-mask writes differ, as hw_oracle_drm.c documents. -""" -import glob -import hashlib -import os -import shutil -import struct -import subprocess -import tempfile - -try: - from . import asm, runner -except ImportError: # run as a script, or imported by runner.py run as a script - import asm - import runner - -HERE = os.path.dirname(os.path.abspath(__file__)) -SOURCE = os.path.join(HERE, "hw_oracle_drm.c") -Unavailable = runner.Unavailable - - -def connected_displays(node, sysfs="/sys/class/drm"): - """The connectors of the GPU behind a render node that have a display attached, as sysfs names them.""" - found = [] - for status in sorted(glob.glob(os.path.join(sysfs, os.path.basename(node), "device", "drm", "card*", "card*-*", - "status"))): - try: - with open(status, encoding="ascii") as f: - if f.read().strip() == "connected": - found.append(os.path.basename(os.path.dirname(status))) - except OSError: - pass - return found - - -def find_node(environ=None, sysfs="/sys/class/drm"): - """The render node to use, or raise Unavailable.""" - environ = os.environ if environ is None else environ - node = environ.get("LEONIDA_HW_DRM_NODE") - if not node: - raise Unavailable("set LEONIDA_HW_DRM_NODE to the render node of a GFX10, GFX11 or GFX12 AMD GPU that " - "drives no display (`ls -l /dev/dri/by-path` lists them)") - if not os.path.exists(node): - raise Unavailable(f"LEONIDA_HW_DRM_NODE={node} does not exist") - displays = connected_displays(node, sysfs) - if displays and environ.get("LEONIDA_HW_DRM_ALLOW_DISPLAY") != "1": - raise Unavailable(f"{node} drives a display ({', '.join(displays)}): a kernel that hangs resets that GPU. " - "Use a GPU without one, or set LEONIDA_HW_DRM_ALLOW_DISPLAY=1") - return node - - -def _symbols(elf): - """([(section name, address, file offset, size)], [(symbol, section number, value)]) of a little-endian ELF64.""" - if elf[:6] != b"\x7fELF\x02\x01": - raise ValueError("not a little-endian ELF64 file") - shoff, = struct.unpack_from(".kd - symbols) of an assembled module. - - The descriptor is where the assembler puts what a runtime must program before it starts the kernel: the - register counts and the float mode (rounding, denormals, IEEE, DX10 clamp) in RSRC1, the user and system SGPRs - and the workgroup's LDS in RSRC2, the wave size in the code properties. The HIP runtime follows it, and so does - the launcher. What the launcher does not provide is refused here instead of being run differently.""" - sections, symbols = _symbols(elf) - out = {} - for name, shndx, value in symbols: - if not name.endswith(".kd"): - continue - _section, address, offset, size = sections[shndx] - if value - address + 64 > size: - raise ValueError(f"{name}: the kernel descriptor runs past its section") - at = offset + value - address - group, private = struct.unpack_from(" 65536: - raise RuntimeError(f"{kernel}: {group} bytes of LDS; a workgroup gets at most 65536") - rsrc2 = (rsrc2 & ~(0x1FF << 15)) | (((group + 511) // 512) << 15) - if (rsrc2 >> 1) & 0x1F != 2: - raise RuntimeError(f"{kernel}: {(rsrc2 >> 1) & 0x1F} user SGPRs; the launcher fills two") - out[kernel] = (rsrc1, rsrc2, 32 if properties & 0x0400 else 64) - return out - - -def launcher_tokens(tokens, offsets, registers): - """name[:threads[:words]] -> name@offset/rsrc1/rsrc2/wave[:threads[:words]], the form hw_oracle_drm takes.""" - out = [] - for token in tokens: - name, sep, rest = token.partition(":") - if name not in offsets or name not in registers: - raise RuntimeError(f"kernel {name} is not in the assembled module") - rsrc1, rsrc2, wave = registers[name] - out.append(f"{name}@{offsets[name]}/{rsrc1:#x}/{rsrc2:#x}/{wave}{sep}{rest}") - return out - - -class DrmOracle(runner.Oracle): - """runner.Oracle with the assembling and launching done for the kernel driver instead of the HIP runtime.""" - - def __init__(self, arch=None, workdir=None, chunk=500): - if not os.path.isfile(SOURCE): - raise Unavailable("hw_oracle_drm.c is missing") - self.node = find_node() - self.clang = runner.find_clang() - self.chunk = chunk - self.workdir = workdir or tempfile.mkdtemp(prefix="leonida-hw-oracle-") - self._offsets, self._registers = {}, {} - self.exe = self._build_launcher() - self.arch = arch or os.environ.get("LEONIDA_HW_ARCH") or self._device_arch() - try: - asm.family(self.arch) - except ValueError as e: # as in runner.Oracle: an architecture without spellings is a skip - raise Unavailable(f"{e} (set LEONIDA_HW_ARCH)") from None - self.device = self._probe() - if hasattr(self, "_probe_waves"): # runner.Oracle has it once it runs kernels of both wave sizes - self._probe_waves() - - def _build_launcher(self): - with open(SOURCE, "rb") as f: - tag = hashlib.sha1(f.read()).hexdigest()[:10] - exe = os.path.join(tempfile.gettempdir(), f"leonida_hw_oracle_drm_{tag}") - if not os.path.isfile(exe): - flags = ["-I/usr/include/libdrm", "-ldrm_amdgpu"] - pkg_config = shutil.which("pkg-config") - if pkg_config: - r = subprocess.run([pkg_config, "--cflags", "--libs", "libdrm_amdgpu"], capture_output=True, text=True) - if r.returncode == 0 and r.stdout.strip(): - flags = r.stdout.split() - tmp = exe + f".{os.getpid()}" - kind, cc = runner.find_cc() - if kind != "gcc": # only an override named cl gives anything else on Linux - raise Unavailable(f"hw_oracle_drm.c needs gcc or a compiler that takes its options, not {cc}") - r = subprocess.run([cc, "-O1", SOURCE, "-o", tmp, *flags], capture_output=True, text=True) - if r.returncode: - raise Unavailable("hw_oracle_drm.c did not build (it needs the libdrm headers): " + r.stderr.strip()[:300]) - os.replace(tmp, exe) - return exe - - def _device_arch(self): - """What the launcher says the GPU is; it prints its device line before it reads any code.""" - r = subprocess.run([self.exe, os.devnull, "4", self.node], input="", capture_output=True, text=True) - head = r.stdout.splitlines()[0] if r.stdout else "" - if not head.startswith("#"): - raise Unavailable((r.stderr.strip() or "the launcher printed no device line")[:300]) - arch = next((field[5:] for field in head.split() if field.startswith("arch=")), "") - # A chip the launcher could only label by generation (an unannounced revision): any member takes the - # same encodings, so a representative assembles for it. asm.family() groups the names the same way. - return {"": "gfx1030", "gfx10xx": "gfx1030", "gfx11xx": "gfx1100", "gfx12xx": "gfx1201"}.get(arch, arch) - - def _assemble(self, text, wave=32): - s = os.path.join(self.workdir, "k.s") - o = os.path.join(self.workdir, "k.o") - code = os.path.join(self.workdir, "k.bin") - with open(s, "w", encoding="utf-8", newline="\n") as f: - f.write(text) - r = subprocess.run([self.clang, "--target=amdgcn-amd-amdhsa", f"-mcpu={self.arch}", - *(["-mwavefrontsize64"] if wave == 64 else []), "-c", s, "-o", o], - capture_output=True, text=True) - if r.returncode: - return None, r.stderr - with open(o, "rb") as f: - elf = f.read() - binary, self._offsets = text_section(elf) - self._registers = kernel_registers(elf) - with open(code, "wb") as f: - f.write(binary) - return code, "" - - def _launch(self, code, tokens, words=4): - r = subprocess.run([self.exe, code, str(words), self.node], - input="\n".join(launcher_tokens(tokens, self._offsets, self._registers)) + "\n", - capture_output=True, text=True) - return r.returncode, r.stdout, r.stderr diff --git a/tools/hw_oracle/hw_oracle.c b/tools/hw_oracle/hw_oracle.c deleted file mode 100644 index 3b6b1ed7f..000000000 --- a/tools/hw_oracle/hw_oracle.c +++ /dev/null @@ -1,96 +0,0 @@ -/* Hardware oracle launcher. Loads a code object with the HIP runtime that ships inside the AMD Windows driver - * (amdhip64_7.dll; no SDK, headers or import library) and runs kernels one at a time. - * - * hw_oracle [hip.dll] kernel names on stdin, whitespace separated; the DLL defaults to - * amdhip64_7.dll (then _6) from the normal search path - * - * Each kernel gets one 8-byte kernarg (a pointer to a dword buffer pre-filled with 0xDEAD0000) and is - * launched as one workgroup of one thread. A stdin token may be name:threads:words to launch a bigger workgroup - * and read back fewer words (threads 1..1024, words <= ). Output, one line per kernel: ... - * The first line is "# device= arch=". Exit 0 ok, 77 no runtime or no device, 2 usage, 3 failure. - * Build: gcc -O1 hw_oracle.c -o hw_oracle.exe - */ -#include -#include -#include -#include -#include -#define LOAD(n) n##_t n = (n##_t)GetProcAddress(h, #n); if (!n) { fprintf(stderr, "missing " #n "\n"); return 77; } -typedef int (*hipInit_t)(unsigned); -typedef int (*hipGetDeviceCount_t)(int *); -typedef int (*hipDeviceGetName_t)(char *, int, int); -typedef int (*hipGetDevicePropertiesR0600_t)(void *, int); -typedef int (*hipModuleLoadData_t)(void **, const void *); -typedef int (*hipModuleGetFunction_t)(void **, void *, const char *); -typedef int (*hipMalloc_t)(void **, size_t); -typedef int (*hipMemcpy_t)(void *, const void *, size_t, int); -typedef int (*hipDeviceSynchronize_t)(void); -typedef int (*hipModuleLaunchKernel_t)(void *, unsigned, unsigned, unsigned, unsigned, unsigned, unsigned, unsigned, - void *, void **, void **); -#define CK(x) do { int e_ = (x); if (e_) { fprintf(stderr, "%s -> hip error %d\n", #x, e_); return 3; } } while (0) - -int main(int argc, char **argv) { - if (argc < 3) { fprintf(stderr, "usage: hw_oracle code.co words < kernel-names\n"); return 2; } - unsigned words = (unsigned)strtoul(argv[2], NULL, 0); - if (words < 1 || words > 16384) { fprintf(stderr, "words must be 1..16384\n"); return 2; } - HMODULE h = NULL; - if (argc > 3) { - h = LoadLibraryA(argv[3]); - if (!h) { fprintf(stderr, "cannot load %s\n", argv[3]); return 77; } - } else { - h = LoadLibraryA("amdhip64_7.dll"); - if (!h) h = LoadLibraryA("amdhip64_6.dll"); - } - if (!h) { fprintf(stderr, "no amdhip64 DLL (AMD driver not installed)\n"); return 77; } - LOAD(hipInit) LOAD(hipGetDeviceCount) LOAD(hipDeviceGetName) LOAD(hipGetDevicePropertiesR0600) LOAD(hipModuleLoadData) - LOAD(hipModuleGetFunction) LOAD(hipMalloc) LOAD(hipMemcpy) LOAD(hipDeviceSynchronize) LOAD(hipModuleLaunchKernel) - int n = 0; - if (hipInit(0) || hipGetDeviceCount(&n) || n < 1) { fprintf(stderr, "no AMD device\n"); return 77; } - char name[256] = {0}; - CK(hipDeviceGetName(name, 256, 0)); - static char prop[16384]; - memset(prop, 0, sizeof prop); - hipGetDevicePropertiesR0600(prop, 0); - const char *arch = "?"; - for (int i = 0; i < (int)sizeof prop - 8; i++) if (!memcmp(prop + i, "gfx", 3)) { arch = prop + i; break; } - printf("# device=%s arch=%s\n", name, arch); - fflush(stdout); - FILE *f = fopen(argv[1], "rb"); - if (!f) { perror("code object"); return 2; } - fseek(f, 0, SEEK_END); long sz = ftell(f); fseek(f, 0, SEEK_SET); - void *img = malloc(sz); - if (fread(img, 1, sz, f) != (size_t)sz) { fprintf(stderr, "short read\n"); return 2; } - fclose(f); - void *mod; - CK(hipModuleLoadData(&mod, img)); /* 209 = no binary for this GPU: wrong -mcpu, or no .amdgpu_metadata */ - void *d; - CK(hipMalloc(&d, words * 4)); - uint32_t *buf = malloc(words * 4); - char kn[256]; - while (scanf("%255s", kn) == 1) { - /* token: name[:threads[:words]] */ - unsigned threads = 1, w = words; - char *c = strchr(kn, ':'); - if (c) { - *c++ = 0; - threads = (unsigned)strtoul(c, &c, 10); - if (*c == ':') w = (unsigned)strtoul(c + 1, NULL, 10); - if (threads < 1 || threads > 1024 || w < 1 || w > words) { fprintf(stderr, "bad kernel token\n"); return 2; } - } - for (unsigned i = 0; i < w; i++) buf[i] = 0xDEAD0000u; - CK(hipMemcpy(d, buf, w * 4, 1)); - void *fn; - CK(hipModuleGetFunction(&fn, mod, kn)); - void *arg = d; - size_t asz = sizeof arg; - void *extra[] = {(void *)1, &arg, (void *)2, &asz, (void *)3}; - CK(hipModuleLaunchKernel(fn, 1, 1, 1, threads, 1, 1, 0, NULL, NULL, extra)); - CK(hipDeviceSynchronize()); - CK(hipMemcpy(buf, d, w * 4, 2)); - printf("%s", kn); - for (unsigned i = 0; i < w; i++) printf(" %08x", buf[i]); - printf("\n"); - } - fflush(stdout); - return 0; -} diff --git a/tools/hw_oracle/hw_oracle_drm.c b/tools/hw_oracle/hw_oracle_drm.c deleted file mode 100644 index 8e60dd041..000000000 --- a/tools/hw_oracle/hw_oracle_drm.c +++ /dev/null @@ -1,367 +0,0 @@ -/* Hardware oracle launcher for Linux. Runs kernels as raw compute dispatches through the kernel driver - * (libdrm_amdgpu): no ROCm, no Vulkan, nothing between the instructions and the GPU. - * - * hw_oracle_drm - * - * is the .text section of the assembled module. Kernel tokens come on stdin, whitespace separated: - * name@offset/rsrc1/rsrc2/wave[:threads[:words]] - * offset where the kernel starts in code.bin, a multiple of 256 - * rsrc1, rsrc2 COMPUTE_PGM_RSRC1 and COMPUTE_PGM_RSRC2 from the kernel's descriptor: its register counts and - * float mode, and its user and system SGPRs. drm.py reads them out of the assembled object and - * puts the descriptor's group segment into RSRC2's LDS_SIZE field, which the assembler leaves 0 - * wave 32 or 64, from the descriptor too - * Each kernel gets what the Windows launcher (hw_oracle.c) gives it: s[0:1] points at an 8-byte kernarg holding - * the address of a dword buffer pre-filled with 0xDEAD0000 (1..16384 words), and it runs as one workgroup - * of `threads` threads (1..1024), started the way its descriptor says. - * Output, one line per kernel: ... The first line is "# device= arch= ...". - * Exit 0 ok, 77 no usable device, 2 usage, 3 failure (a kernel that does not finish within five seconds is one: - * the kernel driver then resets the GPU). - * - * The command stream is libdrm's own compute dispatch test for this GPU generation (libdrm 2.4.115, - * tests/amdgpu/shader_test_util.c, amdgpu_test_dispatch_memset, the gfx10 path), register for register. What - * differs is what belongs to the kernel: its entry point, COMPUTE_PGM_RSRC1 and COMPUTE_PGM_RSRC2 as its - * descriptor has them, the kernarg pointer as its two user SGPRs, the group size, and CS_W32_EN in the dispatch - * for 32-lane waves. - * That sequence is the one for compute engine version 10 (GFX10: RDNA1 and RDNA2). Engines 11 (GFX11, RDNA3) - * and 12 (GFX12, RDNA4) keep every register this stream writes at the same SH offsets — Mesa's register JSON - * and AMD's PAL headers (gfx9_plus_merged_offset.h, gfx12_merged_offset.h) agree on them — and take the preamble - * of the gfx11 path of the same libdrm test, so only the init and the cu-mask writes branch below. GFX12 takes - * that preamble unchanged: AMD's own driver stack still writes its registers with plain SET_SH_REG (PAL, - * gfx12CmdUtil.cpp, BuildSetSeqShRegs) and leaves COMPUTE_STATIC_THREAD_MGMT_SE* at their reset value - * 0xffffffff (gfx12_merged_default.h), so the indexed cu-mask writes stop at engine 11. - * A raw stream bypasses the Vulkan driver: run it on a GPU that drives no display (runner.py checks). - * - * Every submission gets command buffer memory of its own, never rewritten. Measured on a Ryzen 9 7950X3D's - * integrated GPU: when one buffer was rewritten in place right after its fence, the second dispatch of a process - * ran the first one's commands in 200 of 200 runs; with a fresh place for each, 24,500 distinct kernels (both - * wave sizes) each returned their own words. - * - * Build: gcc -O1 hw_oracle_drm.c -o hw_oracle_drm $(pkg-config --cflags --libs libdrm_amdgpu) - */ -#include -#include - -#include -#include -#include -#include -#include -#include - -#define PACKET3(op, n) ((3u << 30) | (((op) & 0xFF) << 8) | ((n) & 0x3FFF) << 16) -#define PACKET3_COMPUTE(op, n) (PACKET3(op, n) | (1 << 1)) -#define PACKET3_DISPATCH_DIRECT 0x15 -#define PACKET3_SET_SH_REG 0x76 -#define PACKET3_SET_UCONFIG_REG 0x79 -#define PACKET3_SET_SH_REG_INDEX 0x9B - -#define SENTINEL 0xDEAD0000u -#define IB_BYTES 1024u /* one submission's commands; about 80 dwords are used */ -#define IB_BLOCK (1u << 20) /* command memory is allocated a block at a time */ - -struct buffer { - amdgpu_bo_handle bo; - amdgpu_va_handle va; - uint64_t address; - void *cpu; - unsigned size; -}; - -static int allocate(amdgpu_device_handle dev, struct buffer *b, unsigned size, unsigned heap) { - struct amdgpu_bo_alloc_request request = {0}; - size = (size + 4095u) & ~4095u; - request.alloc_size = size; - request.phys_alignment = 4096; - request.preferred_heap = heap; - b->size = size; - if (amdgpu_bo_alloc(dev, &request, &b->bo)) return -1; - if (amdgpu_va_range_alloc(dev, amdgpu_gpu_va_range_general, size, 4096, 0, &b->address, &b->va, 0)) return -1; - if (amdgpu_bo_va_op_raw(dev, b->bo, 0, size, b->address, - AMDGPU_VM_PAGE_READABLE | AMDGPU_VM_PAGE_WRITEABLE | AMDGPU_VM_PAGE_EXECUTABLE, - AMDGPU_VA_OP_MAP)) - return -1; - return amdgpu_bo_cpu_map(b->bo, &b->cpu); -} - -/* The LLVM processor name of the chip, from the kernel's family id and revision. The ranges are the ones Mesa's - * ac_gpu_info.c and amdgpu_asic_addr.h use; GC 12 also needs the IP minor, as Mesa's NV4 case does. Every chip of - * one compute-engine generation takes the same encodings, so this only labels the result. */ -static const char *arch_name(const struct amdgpu_gpu_info *gpu, const struct drm_amdgpu_info_hw_ip *ip) { - const unsigned rev = gpu->chip_external_rev; - switch (gpu->family_id) { - case 143: /* AMDGPU_FAMILY_NV */ - if (rev < 0x0A) return "gfx1010"; - if (rev < 0x14) return "gfx1011"; - if (rev < 0x28) return "gfx1012"; - if (rev < 0x32) return "gfx1030"; - if (rev < 0x3C) return "gfx1031"; - if (rev < 0x46) return "gfx1032"; - return "gfx1034"; - case 144: return "gfx1033"; /* AMDGPU_FAMILY_VGH */ - case 146: return "gfx1035"; /* AMDGPU_FAMILY_YC */ - case 149: return "gfx1036"; /* AMDGPU_FAMILY_GC_10_3_6 */ - case 151: return "gfx1037"; /* AMDGPU_FAMILY_GC_10_3_7 */ - case 145: /* AMDGPU_FAMILY_GC_11_0_0: Navi31, Navi33, Navi32 */ - if (rev < 0x10) return "gfx1100"; - if (rev < 0x20) return "gfx1102"; - return "gfx1101"; - case 148: return "gfx1103"; /* AMDGPU_FAMILY_GC_11_0_1: Phoenix, Phoenix2, Hawk Point */ - case 150: /* AMDGPU_FAMILY_GC_11_5_0. The ranges are Mesa's amdgpu_asic_addr.h (STRIX1 0x01..0x3f, - * KRACKAN1 0x40..0x4f, GFX1153 0x50..0xbf, STRIX_HALO 0xc0..0xcf, GFX1156 0xd0..0xfe), and Mesa's - * amd_family.c names GFX1156 gfx1153 too (ac_get_llvm_processor_name), hence the two gfx1153 returns. */ - if (rev < 0x40) return "gfx1150"; /* STRIX1 */ - if (rev < 0x50) return "gfx1152"; /* KRACKAN1 */ - if (rev < 0xC0) return "gfx1153"; - if (rev < 0xD0) return "gfx1151"; /* STRIX_HALO */ - return "gfx1153"; /* GFX1156, which assembles as gfx1153 */ - case 154: /* AMDGPU_FAMILY_GC_11_5_4 */ - if (rev < 0x40) return "gfx1170"; - if (rev < 0x80) return "gfx1171"; - return "gfx11xx"; - case 152: /* AMDGPU_FAMILY_GC_12_0_0 */ - if (ip->hw_ip_version_minor == 1) return "gfx1210"; - if (rev < 0x40) return "gfx12xx"; - if (rev < 0x50) return "gfx1200"; - return "gfx1201"; /* the RX 9000 series */ - default: - return ip->hw_ip_version_major == 11 ? "gfx11xx" : ip->hw_ip_version_major == 12 ? "gfx12xx" : "gfx10xx"; - } -} - -int main(int argc, char **argv) { - if (argc < 4) { - fprintf(stderr, "usage: hw_oracle_drm code.bin words /dev/dri/renderD < kernel-tokens\n"); - return 2; - } - const unsigned words = (unsigned)strtoul(argv[2], NULL, 0); - if (words < 1 || words > 16384) { fprintf(stderr, "words must be 1..16384\n"); return 2; } - - const int fd = open(argv[3], O_RDWR); - if (fd < 0) { perror(argv[3]); return 77; } - uint32_t major = 0, minor = 0; - amdgpu_device_handle dev; - if (amdgpu_device_initialize(fd, &major, &minor, &dev)) { - fprintf(stderr, "%s is not an AMD GPU the amdgpu kernel driver runs\n", argv[3]); - return 77; - } - struct amdgpu_gpu_info gpu = {0}; - struct drm_amdgpu_info_hw_ip ip = {0}; - if (amdgpu_query_gpu_info(dev, &gpu) || amdgpu_query_hw_ip_info(dev, AMDGPU_HW_IP_COMPUTE, 0, &ip)) { - fprintf(stderr, "device queries failed\n"); - return 77; - } - if ((ip.hw_ip_version_major != 10 && ip.hw_ip_version_major != 11 && ip.hw_ip_version_major != 12) || - !(ip.available_rings & 1)) { - fprintf(stderr, "compute engine %u.%u: only versions 10 (GFX10, RDNA1 and RDNA2), 11 (GFX11, RDNA3) and " - "12 (GFX12, RDNA4) are supported\n", - ip.hw_ip_version_major, ip.hw_ip_version_minor); - return 77; - } - const unsigned engine = ip.hw_ip_version_major; - const char *name = amdgpu_get_marketing_name(dev); - printf("# device=%s (0x%04x) arch=%s engine=%u.%u\n", name ? name : "AMD GPU", gpu.asic_id, - arch_name(&gpu, &ip), ip.hw_ip_version_major, ip.hw_ip_version_minor); - fflush(stdout); - - FILE *file = fopen(argv[1], "rb"); - if (!file) { perror(argv[1]); return 2; } - fseek(file, 0, SEEK_END); - const long code_bytes = ftell(file); - fseek(file, 0, SEEK_SET); - if (code_bytes < 4 || code_bytes % 4 || code_bytes > (64 << 20)) { - fprintf(stderr, "%s: %ld bytes; expected whole dwords, at most 64 MiB\n", argv[1], code_bytes); - return 2; - } - - amdgpu_context_handle context; - struct buffer cmd = {0}, code = {0}, kernarg = {0}, out = {0}; - /* The code gets a page of zeros behind it: the GPU fetches instructions ahead, past a kernel's s_endpgm. */ - if (amdgpu_cs_ctx_create(dev, &context) || - allocate(dev, &code, (unsigned)code_bytes + 4096, AMDGPU_GEM_DOMAIN_VRAM) || - allocate(dev, &kernarg, 4096, AMDGPU_GEM_DOMAIN_VRAM) || allocate(dev, &out, words * 4, AMDGPU_GEM_DOMAIN_VRAM)) { - fprintf(stderr, "context or buffer creation failed\n"); - return 3; - } - memset(code.cpu, 0, code.size); - if (fread(code.cpu, 1, (size_t)code_bytes, file) != (size_t)code_bytes) { fprintf(stderr, "short read\n"); return 2; } - fclose(file); - memset(kernarg.cpu, 0, kernarg.size); - memcpy(kernarg.cpu, &out.address, 8); /* the kernel's one argument: where its output goes */ - - amdgpu_bo_list_handle list = NULL; - unsigned ib_used = IB_BLOCK; /* no block yet */ - - char token[512]; - while (scanf("%511s", token) == 1) { - /* name@offset/rsrc1/rsrc2/wave[:threads[:words]] */ - char *at = strchr(token, '@'); - if (!at) { fprintf(stderr, "bad kernel token %s (no @offset)\n", token); return 2; } - *at++ = 0; - char *rest = NULL; - const unsigned long offset = strtoul(at, &rest, 0); - uint32_t rsrc1 = 0, rsrc2 = 0; - unsigned wave = 0, threads = 1, w = words; - if (*rest == '/') rsrc1 = (uint32_t)strtoul(rest + 1, &rest, 0); - if (*rest == '/') rsrc2 = (uint32_t)strtoul(rest + 1, &rest, 0); - if (*rest == '/') wave = (unsigned)strtoul(rest + 1, &rest, 10); - if (*rest == ':') { - threads = (unsigned)strtoul(rest + 1, &rest, 10); - if (*rest == ':') w = (unsigned)strtoul(rest + 1, &rest, 10); - } - if (*rest || offset % 256 || offset >= (unsigned long)code_bytes || (wave != 32 && wave != 64) || threads < 1 || - threads > 1024 || w < 1 || w > words) { - fprintf(stderr, "bad kernel token for %s\n", token); - return 2; - } - uint32_t *result = out.cpu; - for (unsigned i = 0; i < w; i++) result[i] = SENTINEL; - - if (ib_used + IB_BYTES > IB_BLOCK) { - /* A new block of command memory. The old one stays mapped: nothing may reuse it. */ - if (list) amdgpu_bo_list_destroy(list); - memset(&cmd, 0, sizeof cmd); - if (allocate(dev, &cmd, IB_BLOCK, AMDGPU_GEM_DOMAIN_GTT)) { fprintf(stderr, "command buffer allocation failed\n"); return 3; } - amdgpu_bo_handle resources[4] = {out.bo, kernarg.bo, code.bo, cmd.bo}; - if (amdgpu_bo_list_create(dev, 4, resources, NULL, &list)) { fprintf(stderr, "bo list creation failed\n"); return 3; } - ib_used = 0; - } - const uint64_t entry = code.address + offset; - const uint64_t ib_address = cmd.address + ib_used; - uint32_t *p = (uint32_t *)((char *)cmd.cpu + ib_used); - ib_used += IB_BYTES; - int i = 0; - if (engine == 10) { - /* amdgpu_dispatch_init_gfx9 (no context control on the compute engine): COMPUTE_START_X..Z, TMPRING_SIZE. */ - p[i++] = PACKET3_COMPUTE(PACKET3_SET_SH_REG, 3); - p[i++] = 0x204; - p[i++] = 0; - p[i++] = 0; - p[i++] = 0; - p[i++] = PACKET3_COMPUTE(PACKET3_SET_SH_REG, 1); - p[i++] = 0x218; - p[i++] = 0; - /* amdgpu_dispatch_init_gfx10: COMPUTE_SHADER_CHKSUM, COMPUTE_REQ_CTRL (6 registers), CP_COHER_START_DELAY. */ - p[i++] = PACKET3_COMPUTE(PACKET3_SET_SH_REG, 1); - p[i++] = 0x22a; - p[i++] = 0; - p[i++] = PACKET3_COMPUTE(PACKET3_SET_SH_REG, 6); - p[i++] = 0x222; - for (int k = 0; k < 6; k++) p[i++] = 0; - p[i++] = PACKET3(PACKET3_SET_UCONFIG_REG, 1); - p[i++] = 0x7b; - p[i++] = 0x20; - } else { - /* amdgpu_dispatch_init_gfx11: COMPUTE_START_X..Z, TMPRING_SIZE, then REQ_CTRL on its own, the four - * COMPUTE_USER_ACCUM registers and the checksum. The checksum stays in the SH space, as AMD's PAL - * writes it on GFX11 (gfx9PipelineChunkCs.cpp, WriteSetOneShReg of mmCOMPUTE_SHADER_CHKSUM): the - * libdrm gfx11 path sends it as UCONFIG 0x22a, which does not reach this register. CP_COHER_START_DELAY - * is gone. GFX12 takes the same preamble: PAL writes these registers the same way (gfx12CmdUtil.cpp - * still builds plain SET_SH_REG). */ - p[i++] = PACKET3_COMPUTE(PACKET3_SET_SH_REG, 3); - p[i++] = 0x204; - p[i++] = 0; - p[i++] = 0; - p[i++] = 0; - p[i++] = PACKET3_COMPUTE(PACKET3_SET_SH_REG, 1); - p[i++] = 0x218; - p[i++] = 0; - p[i++] = PACKET3_COMPUTE(PACKET3_SET_SH_REG, 1); - p[i++] = 0x222; - p[i++] = 0; - p[i++] = PACKET3_COMPUTE(PACKET3_SET_SH_REG, 4); - p[i++] = 0x224; - for (int k = 0; k < 4; k++) p[i++] = 0; - p[i++] = PACKET3_COMPUTE(PACKET3_SET_SH_REG, 1); - p[i++] = 0x22a; - p[i++] = 0; - } - if (engine <= 11) { - /* amdgpu_dispatch_write_cumask (gfx10 and gfx11): COMPUTE_STATIC_THREAD_MGMT_SE0..3. GFX11's SE4..SE7 - * keep their reset value. */ - p[i++] = PACKET3_COMPUTE(PACKET3_SET_SH_REG_INDEX, 2); - p[i++] = 0x30000216; - p[i++] = 0xffffffff; - p[i++] = 0xffffffff; - p[i++] = PACKET3_COMPUTE(PACKET3_SET_SH_REG_INDEX, 2); - p[i++] = 0x30000219; - p[i++] = 0xffffffff; - p[i++] = 0xffffffff; - } - /* GFX12 writes none of the COMPUTE_STATIC_THREAD_MGMT registers: every SE's mask resets to 0xffffffff - * (AMD's gfx12_merged_default.h), and neither PAL nor RADV touches them, so an indexed write would only - * repeat what the queue already has. */ - /* amdgpu_dispatch_write2hw_gfx10/gfx11: COMPUTE_PGM_LO/HI (the entry point, in 256-byte units), the shader's - * registers, COMPUTE_PGM_RSRC3. RSRC3 stays 0 on every generation the launcher takes: its kernels carry - * none of its fields (drm.py refuses scratch memory and shared VGPRs), and RADV and PAL likewise program - * what the descriptor has. INST_PREF_SIZE (GFX11's 0x3f0 in the libdrm test) buys nothing here: the code - * buffer already has a page of zeros behind it against the prefetch. */ - p[i++] = PACKET3_COMPUTE(PACKET3_SET_SH_REG, 2); - p[i++] = 0x20c; - p[i++] = (uint32_t)(entry >> 8); - p[i++] = (uint32_t)(entry >> 40); - const uint32_t registers[][2] = { - {0x2e12, rsrc1}, /* COMPUTE_PGM_RSRC1, from the kernel's descriptor (0x000C0041 in the reference) */ - {0x2e13, rsrc2}, /* COMPUTE_PGM_RSRC2, from the kernel's descriptor (0x00000090 in the reference) */ - {0x2e07, threads}, /* COMPUTE_NUM_THREAD_X */ - {0x2e08, 1}, /* COMPUTE_NUM_THREAD_Y */ - {0x2e09, 1}, /* COMPUTE_NUM_THREAD_Z */ - }; - for (unsigned r = 0; r < sizeof(registers) / sizeof(registers[0]); ++r) { - p[i++] = PACKET3_COMPUTE(PACKET3_SET_SH_REG, 1); - p[i++] = registers[r][0] - 0x2c00; - p[i++] = registers[r][1]; - } - p[i++] = PACKET3_COMPUTE(PACKET3_SET_SH_REG, 1); - p[i++] = 0x228; - p[i++] = 0; - /* COMPUTE_USER_DATA_0..1: the kernarg pointer. */ - p[i++] = PACKET3_COMPUTE(PACKET3_SET_SH_REG, 2); - p[i++] = 0x240; - p[i++] = (uint32_t)kernarg.address; - p[i++] = (uint32_t)(kernarg.address >> 32); - /* amdgpu_dispatch_write_dispatch_cmd: COMPUTE_RESOURCE_LIMITS, then one group. The initiator is - * COMPUTE_SHADER_EN, with CS_W32_EN (bit 15) for 32-lane waves. */ - p[i++] = PACKET3_COMPUTE(PACKET3_SET_SH_REG, 1); - p[i++] = 0x215; - p[i++] = 0; - p[i++] = PACKET3_COMPUTE(PACKET3_DISPATCH_DIRECT, 3); - p[i++] = 1; - p[i++] = 1; - p[i++] = 1; - p[i++] = 1u | (wave == 32 ? 1u << 15 : 0); - while (i & 7) p[i++] = 0xffff1000; /* type-3 nop */ - - struct amdgpu_cs_ib_info ib = {0}; - ib.ib_mc_address = ib_address; - ib.size = (uint32_t)i; - struct amdgpu_cs_request request = {0}; - request.ip_type = AMDGPU_HW_IP_COMPUTE; - request.ring = 0; - request.resources = list; - request.number_of_ibs = 1; - request.ibs = &ib; - const int submitted = amdgpu_cs_submit(context, 0, &request, 1); - if (submitted) { fprintf(stderr, "%s: amdgpu_cs_submit failed: %d\n", token, submitted); return 3; } - struct amdgpu_cs_fence fence = {0}; - fence.context = context; - fence.ip_type = AMDGPU_HW_IP_COMPUTE; - fence.ring = 0; - fence.fence = request.seq_no; - uint32_t expired = 0; - const int waited = amdgpu_cs_query_fence_status(&fence, 5000000000ull, 0, &expired); /* five seconds */ - if (waited || !expired) { - fprintf(stderr, "%s did not finish within 5 s (wait returned %d): the kernel driver will time the job out " - "and reset this GPU\n", token, waited); - return 3; - } - printf("%s", token); - for (unsigned k = 0; k < w; k++) printf(" %08x", result[k]); - printf("\n"); - } - fflush(stdout); - if (list) amdgpu_bo_list_destroy(list); - amdgpu_cs_ctx_free(context); - amdgpu_device_deinitialize(dev); - close(fd); - return 0; -} diff --git a/tools/hw_oracle/runner.py b/tools/hw_oracle/runner.py deleted file mode 100644 index fc9b274f9..000000000 --- a/tools/hw_oracle/runner.py +++ /dev/null @@ -1,399 +0,0 @@ -"""Find the tools, build the launcher, assemble kernels and run them on the GPU. Standard library only. - -Two launchers: on Windows the HIP runtime that ships in the AMD driver (hw_oracle.c, this file), on Linux raw -dispatches through the kernel driver (hw_oracle_drm.c, drm.py, which also lists its own variables). open_oracle() -picks the one for the platform. - -Tools are located through environment variables first, then by looking in the usual places: - LEONIDA_AMD_CLANG AMD clang (its folder must also hold ld.lld); default: amdclang / clang on PATH that lists - the amdgcn target (a launcher without ld.lld beside it is followed to the clang it is - installed as), %HIP_PATH% / %ROCM_PATH%, a .venv holding the `rocm-sdk-core` wheel - LEONIDA_HIP_DLL the HIP runtime (amdhip64_7.dll); default: the one in System32 (it ships with the driver) - LEONIDA_HOST_CC a C compiler for hw_oracle.c (MinGW gcc, or cl.exe from a Developer shell); default: gcc on - PATH, C:\\msys64\\ucrt64\\bin, then on Windows a cl on PATH or Visual Studio's (vswhere) - LEONIDA_HW_ARCH the GPU architecture to assemble for; default: what amdgpu-arch reports, else gfx1150 -Anything missing raises Unavailable, which callers turn into exit 77 ("skipped"). -""" -import hashlib -import os -import shutil -import subprocess -import sys -import tempfile - -try: - from . import asm -except ImportError: # run as a script - sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) - import asm - -HERE = os.path.dirname(os.path.abspath(__file__)) -REPO = os.path.dirname(os.path.dirname(HERE)) -SENTINEL = 0xDEAD0000 - - -class Unavailable(Exception): - """A required tool or the GPU is not there.""" - - -def _exe(name): - return name + (".exe" if os.name == "nt" else "") - - -def _has_amdgcn(clang): - try: - out = subprocess.run([clang, "--print-targets"], capture_output=True, text=True, timeout=60).stdout - except (OSError, subprocess.SubprocessError): - return False - return "amdgcn" in out - - -def _installed_clang(clang): - """The clang a launcher stands for. The rocm-sdk wheels put `amdclang` in the Python environment's Scripts (bin) - folder: it has the amdgcn target, but ld.lld and amdgpu-arch sit beside the real clang, in the folder `--version` - names as InstalledDir. A clang with its ld.lld beside it, or one that names no such folder, is returned as it is.""" - if os.path.isfile(os.path.join(os.path.dirname(clang), _exe("ld.lld"))): - return clang - try: - out = subprocess.run([clang, "--version"], capture_output=True, text=True, timeout=60).stdout - except (OSError, subprocess.SubprocessError): - return clang - for line in out.splitlines(): - if line.startswith("InstalledDir:"): - real = os.path.join(line.split(":", 1)[1].strip(), _exe("clang")) - if os.path.isfile(real): - return real - return clang - - -def find_clang(): - env = os.environ.get("LEONIDA_AMD_CLANG") - if env: - if not os.path.isfile(env): - raise Unavailable(f"LEONIDA_AMD_CLANG={env} does not exist") - return env - cands = [shutil.which(n) for n in ("amdclang", "clang")] - for var in ("HIP_PATH", "ROCM_PATH"): - root = os.environ.get(var) - if root: - cands += [os.path.join(root, "lib", "llvm", "bin", _exe("clang")), os.path.join(root, "bin", _exe("clang"))] - tail = os.path.join("Lib", "site-packages", "_rocm_sdk_core", "lib", "llvm", "bin", _exe("clang")) - cands.append(os.path.join(REPO, ".venv", tail)) # only the repo root's venv, never a glob under the cwd - for c in cands: - if c and os.path.isfile(c) and _has_amdgcn(c): - return _installed_clang(c) - raise Unavailable("no AMD clang (set LEONIDA_AMD_CLANG; `pip install rocm-sdk-core` from " - "https://stable.repo.amd.com/rocm/whl-next/ provides one)") - - -def find_hip_dll(): - env = os.environ.get("LEONIDA_HIP_DLL") - if env: - if not os.path.isfile(env): - raise Unavailable(f"LEONIDA_HIP_DLL={env} does not exist") - return env - if os.name != "nt": - raise Unavailable("the launcher targets the Windows AMD driver (amdhip64_7.dll)") - for n in ("amdhip64_7.dll", "amdhip64_6.dll"): # the launcher loads whatever path this returns - p = os.path.join(os.environ.get("SystemRoot", r"C:\Windows"), "System32", n) - if os.path.isfile(p): - return p - raise Unavailable("no amdhip64_7.dll in System32 (the AMD Windows driver provides it)") - - -def _is_msvc(cc): - """cl.exe (MSVC or clang-cl) takes /Fe, not -o.""" - return os.path.basename(cc).lower() in ("cl.exe", "cl", "clang-cl.exe", "clang-cl") - - -def find_vcvars(): - """vcvars64.bat of the newest Visual Studio with the x64 C++ tools, as scripts/build_runtime.ps1 finds it.""" - pf86 = os.environ.get("ProgramFiles(x86)", r"C:\Program Files (x86)") - vswhere = os.path.join(pf86, "Microsoft Visual Studio", "Installer", "vswhere.exe") - if not os.path.isfile(vswhere): - return None - try: - out = subprocess.run([vswhere, "-latest", "-products", "*", "-requires", - "Microsoft.VisualStudio.Component.VC.Tools.x86.x64", "-property", "installationPath"], - capture_output=True, text=True, timeout=60).stdout.strip().splitlines() - except (OSError, subprocess.SubprocessError): - return None - bat = os.path.join(out[0].strip(), "VC", "Auxiliary", "Build", "vcvars64.bat") if out else "" - return bat if os.path.isfile(bat) else None - - -def find_cc(): - """The host compiler for hw_oracle.c: ('gcc', path), ('msvc', cl path) or ('vcvars', vcvars64.bat path).""" - env = os.environ.get("LEONIDA_HOST_CC") - if env: - if not os.path.isfile(env): - raise Unavailable(f"LEONIDA_HOST_CC={env} does not exist") - return ("msvc" if _is_msvc(env) else "gcc"), env - for c in (shutil.which("gcc"), r"C:\msys64\ucrt64\bin\gcc.exe", r"C:\msys64\mingw64\bin\gcc.exe"): - if c and os.path.isfile(c): - return "gcc", c - if os.name == "nt": - # A cl already on PATH (a Developer shell) has its environment; otherwise set it up from vcvars64.bat. - cl = shutil.which("cl") - if cl: - return "msvc", cl - bat = find_vcvars() - if bat: - return "vcvars", bat - raise Unavailable("no C compiler for hw_oracle.c: MinGW gcc or Visual Studio's C++ tools (set LEONIDA_HOST_CC)") - - -def build_command(kind, cc, src, out, workdir): - """argv that compiles src into out; MSVC's objects and the vcvars script go to workdir, the cwd to run it in.""" - if kind == "gcc": - return [cc, "-O1", src, "-o", out] - cl = [cc if kind == "msvc" else "cl", "/nologo", "/O1", src, f"/Fe{out}", f"/Fo{os.path.join(workdir, '')}"] - if kind == "msvc": - return cl - # cmd.exe strips the outer quotes of /c's argument, so the call goes through a script file. - # vcvars64.bat runs vswhere itself, so its folder goes on PATH first (as scripts/build_llvm_mc.ps1 does). - installer = os.path.join(os.environ.get("ProgramFiles(x86)", r"C:\Program Files (x86)"), - "Microsoft Visual Studio", "Installer") - name = "build_hw_oracle.cmd" - script = os.path.join(workdir, name) - # Written as UTF-8, with chcp 65001 so cmd.exe reads it as UTF-8 on any console code page: the checkout, %TEMP% - # and Visual Studio paths in here reach cl intact when one has a character outside ASCII (a user name, say). - with open(script, "w", encoding="utf-8", newline="\n") as f: - f.write(f'@echo off\r\nchcp 65001 >nul\r\nset "PATH={installer};%PATH%"\r\ncall "{cc}" >nul || exit /b 1\r\n' - + subprocess.list2cmdline(cl) + "\r\n") - # Relative to workdir, not the full path: cmd.exe /c loses a full path's quotes when it holds & or ^ (and - # list2cmdline adds none without a space), and `.\` is still found with NoDefaultCurrentDirectoryInExePath set. - return ["cmd.exe", "/d", "/c", "." + os.sep + name] - - -def detect_arch(clang): - env = os.environ.get("LEONIDA_HW_ARCH") - if env: - return env - tool = os.path.join(os.path.dirname(clang), _exe("amdgpu-arch")) - if os.path.isfile(tool): - try: - out = subprocess.run([tool], capture_output=True, text=True, timeout=60).stdout.split() - if out: - return out[0].split(":")[0] # amdgpu-arch prints 'gfx1010:xnack-': the kernels want the bare name - except (OSError, subprocess.SubprocessError): - pass - return "gfx1150" - - -def _find_lld(clang): - p = os.path.join(os.path.dirname(clang), _exe("ld.lld")) - if os.path.isfile(p): - return p - found = shutil.which("ld.lld") - if found: - return found - raise Unavailable("no ld.lld next to the AMD clang") - - -class Oracle: - """Assembles batches of scalar programs for one architecture and runs them on device 0.""" - - code_object = None # None: the assembler's default version; 5 after an older HIP runtime refused that - true16 = False # True: this assembler wants v8.l for a 16-bit operand - - def __init__(self, arch=None, workdir=None, chunk=500): - if not os.path.isfile(os.path.join(HERE, "hw_oracle.c")): - raise Unavailable("hw_oracle.c is missing") - self.clang = find_clang() - self.lld = _find_lld(self.clang) - self.dll = find_hip_dll() - self.arch = arch or detect_arch(self.clang) - try: - asm.family(self.arch) - except ValueError as e: # a GPU the kernels have no spellings for is a skip, like a missing tool - raise Unavailable(f"{e} (set LEONIDA_HW_ARCH)") from None - self.chunk = chunk - self.workdir = workdir or tempfile.mkdtemp(prefix="leonida-hw-oracle-") - self.exe = self._build_launcher() - self.device = self._probe() - self.true16 = self._needs_true16() - self._probe_waves() - - def _build_launcher(self): - src = os.path.join(HERE, "hw_oracle.c") - with open(src, "rb") as f: - tag = hashlib.sha1(f.read()).hexdigest()[:10] - exe = os.path.join(tempfile.gettempdir(), f"leonida_hw_oracle_{tag}{'.exe' if os.name == 'nt' else ''}") - if not os.path.isfile(exe): - # cl appends .exe to an /Fe name without one, so the temporary name keeps the extension last - tmp = exe[:-4] + f".{os.getpid()}.exe" if os.name == "nt" else exe + f".{os.getpid()}" - kind, cc = find_cc() - # The compiler's messages are only quoted in the error below; one in another code page must not raise. - r = subprocess.run(build_command(kind, cc, src, tmp, self.workdir), capture_output=True, text=True, - encoding="utf-8", errors="replace", cwd=self.workdir) - if r.returncode: - # cl reports compile errors on stdout - raise Unavailable("hw_oracle.c did not build: " + (r.stderr.strip() or r.stdout.strip())[:300]) - os.replace(tmp, exe) - return exe - - def _probe(self): - """Run an empty kernel list: confirms the DLL loads and a device exists.""" - text, names, _ = asm.module_text([["v_mov_b32 v8, 0", "v_mov_b32 v9, 0", "v_mov_b32 v10, 0", "v_mov_b32 v11, 0"]], - self.arch, prefix="probe") - co, err = self._assemble(text) - if co is None: - raise Unavailable("probe kernel did not assemble: " + err[:300]) - rc, out, err = self._launch(co, names) - if rc == 3 and any(e in err for e in ("hip error 209", "hip error 303")) and self.code_object is None: - # LLVM 23 writes code object v6, which HIP runtimes from 2024 (amdhip64_6.dll) refuse as "no binary for - # this GPU" (209) or "shared object init failed" (303). Ask for v5; an error that stays has another cause - # and is reported below. - self.code_object = 5 - co, why = self._assemble(text) - if co is None: - raise Unavailable("the HIP runtime refused the code object and v5 did not assemble: " + why[:300]) - rc, out, err = self._launch(co, names) - if rc == 77: - raise Unavailable(err.strip() or "no AMD device") - if rc: - raise Unavailable(f"probe launch failed (exit {rc}): {err.strip()[:300]}") - head = out.splitlines()[0] if out else "" - if "arch=" in head and self.arch not in head: - raise Unavailable(f"device reports {head!r} but assembling for {self.arch} (set LEONIDA_HW_ARCH)") - return head.lstrip("# ") - - def _needs_true16(self): - """Whether this assembler rejects `v_cvt_f16_f32 v8, v1` and takes `v8.l` (LLVM 23 on GFX11).""" - return asm.family(self.arch) != "gfx10" and asm.needs_true16(lambda text: self._assemble(text)[0] is not None) - - def _probe_waves(self): - """Each wave size really runs as that size: a 64-thread group stores v_mbcnt lane ids. In a wave64 kernel - thread 32 is lane 32 (mbcnt_hi adds 32); in a wave32 kernel it is lane 0 of the second wave. A runtime that - ignored the wave size in the code object would fail here instead of producing plausible-looking data.""" - store = "global_store_b32" if asm.family(self.arch) == "gfx11" else "global_store_dword" - tail = ["v_lshlrev_b32 v2, 2, v0", f"{store} v2, v1, s[2:3]", "s_endpgm"] - lo = ["v_mbcnt_lo_u32_b32 v1, -1, 0"] - k64 = asm.Kernel(lo + ["v_mbcnt_hi_u32_b32 v1, -1, v1"] + tail, 64, 64, 64, raw=True) - k32 = asm.Kernel(lo + tail, 32, 64, 64, raw=True) - w64, w32 = self.run([k64, k32], words=64) - if w64 != list(range(64)): - raise RuntimeError(f"wave64 probe: lane ids {w64!r}; the runtime did not run the kernel as wave64") - if w32 != list(range(32)) * 2: - raise RuntimeError(f"wave32 probe: lane ids {w32!r}; the runtime did not run the kernel as wave32") - - def _assemble(self, text, wave=32): - s = os.path.join(self.workdir, "k.s") - o = os.path.join(self.workdir, "k.o") - co = os.path.join(self.workdir, "k.co") - with open(s, "w", encoding="utf-8", newline="\n") as f: - f.write(text) - flags = ["-mwavefrontsize64"] if wave == 64 else [] - if self.code_object: - flags.append(f"-mcode-object-version={self.code_object}") - r = subprocess.run([self.clang, "--target=amdgcn-amd-amdhsa", f"-mcpu={self.arch}", *flags, "-c", s, "-o", o], - capture_output=True, text=True) - if r.returncode: - return None, r.stderr - # Some Windows LLD builds default to PE even when the input object is AMDGPU ELF. - r = subprocess.run([self.lld, "-m", "elf64_amdgpu", "-shared", o, "-o", co], - capture_output=True, text=True) - if r.returncode: - return None, r.stderr - return co, "" - - def _launch(self, co, names, words=4): - try: - r = subprocess.run([self.exe, co, str(words), self.dll], input="\n".join(names) + "\n", capture_output=True, text=True) - except OSError as e: - if getattr(e, "winerror", None) != 225: - raise - # Defender quarantined the launcher just built (a small unsigned exe that loads a DLL): not a crash - raise Unavailable(f"Windows Defender blocked the launcher {self.exe} (WinError 225); add an exclusion for " - f"{os.path.dirname(self.exe)} (Windows Security, Virus & threat protection) and rerun") from None - return r.returncode, r.stdout, r.stderr - - def run(self, programs, words=4): - """Run each program (a list of lines). Returns one entry per program: a list of `words` ints, or a str - explaining why it could not run (assembler rejection, or a MODE field this architecture cannot set).""" - results = [None] * len(programs) - for i, p in enumerate(programs): - why = asm.mode_skip_reason(p.mode, self.arch) if isinstance(p, asm.Kernel) else None - if why: - results[i] = why # never assembled: the directive would fail its whole chunk - for wave in (32, 64): - todo = [i for i, p in enumerate(programs) if results[i] is None and - (p.wave if isinstance(p, asm.Kernel) else 32) == wave] - for lo in range(0, len(todo), self.chunk): - try: - self._run_chunk(programs, todo[lo:lo + self.chunk], results, words, wave) - except asm.ModeUnavailable as e: - raise Unavailable(str(e)) from None - return results - - def _run_chunk(self, programs, idx, results, words, wave=32): - live = list(idx) - while live: - text, names, starts = asm.module_text([programs[i] for i in live], self.arch, wave=wave) - if self.true16: - text = asm.true16_spelling(text) - if asm.family(self.arch) != "gfx10": - text = asm.opsel16_spelling(text) # needed even where the true16 probe says no (asm.py) - co, err = self._assemble(text, wave) - if co is not None: - break - bad = asm.failing_kernels(err, starts) - if not bad: - raise RuntimeError("assembler failed with no kernel to blame:\n" + err[:600]) - first = err.strip().splitlines()[0] if err.strip() else "?" - for k in bad: - results[live[k]] = "assembler rejected: " + first.split("error:", 1)[-1].strip() - live = [i for k, i in enumerate(live) if k not in bad] - else: - # every program in the chunk was rejected: that is a broken harness (a bad prologue, the wrong - # architecture), not a thousand skips - raise RuntimeError("the assembler rejected every program in a chunk: " + - (str(results[idx[0]]) if idx else "empty chunk")) - tokens = [] - for n, i in zip(names, live): - p = programs[i] - tokens.append(f"{n}:{p.threads}:{p.words}" if isinstance(p, asm.Kernel) else n) - top = max([4] + [programs[i].words for i in live if isinstance(programs[i], asm.Kernel)]) - rc, out, err = self._launch(co, tokens, top if top > 4 else words) - if rc: - raise RuntimeError(f"hw_oracle exited {rc}: {err.strip()[:300]}") - got = {} - for line in out.splitlines(): - if line.startswith("#") or not line.strip(): - continue - name, *w = line.split() - got[name] = [int(x, 16) for x in w] - for n, i in zip(names, live): - results[i] = got.get(n, "kernel produced no output") - - def close(self): - shutil.rmtree(self.workdir, ignore_errors=True) - - -def open_oracle(**kw): - """An Oracle for this platform, or raise Unavailable.""" - if sys.platform.startswith("linux"): - try: - from . import drm - except ImportError: # run as a script - import drm - return drm.DrmOracle(**kw) - return Oracle(**kw) - - -def main(): - try: - o = open_oracle() - except Unavailable as e: - print(f"hardware oracle unavailable: {e}") - return 77 - print(f"hardware oracle ready: {o.device}; clang {o.clang}") - o.close() - return 0 - - -if __name__ == "__main__": - # Through the importable module: drm.py imports runner, and both must share one Unavailable and one Oracle. - import runner as _runner - sys.exit(_runner.main()) diff --git a/tools/hw_oracle/tsharp.py b/tools/hw_oracle/tsharp.py deleted file mode 100644 index 8976c51e7..000000000 --- a/tools/hw_oracle/tsharp.py +++ /dev/null @@ -1,147 +0,0 @@ -"""T# (image resource descriptor) words per GPU family, and the raw kernel that reads a texture through one. No hardware -needed to build either; tools/image_fuzz.py --oracle hw runs the kernels. - -The kernel carries its own texture: the texel rows sit in the kernel's code after s_endpgm, 256-byte aligned, and -the kernel finds them with s_getpc_b64, so the launcher (hw_oracle.c, hw_oracle_drm.c) needs no input buffer. The -texture is therefore in device memory the GPU already maps, linear (SW_MODE 0). The kernel writes the T# into -s[8:15] with the base address filled in at run time and runs - image_load v[8:11], v[x:y], s[8:15] dmask:.. dim:SQ_RSRC_IMG_2D unorm -for one texel per lane (every texel is read once, 1024 lanes at most with a short loop beyond that) and stores the -four result registers of each texel as four dwords at texel_index * 16 in the output buffer. - -Where the layout comes from (facts only; Mesa is MIT-licensed, the code here is this repository's own): -- field positions: Mesa src/amd/registers gfx10-rsrc.json (SQ_IMG_RSRC_WORD0..7 and the gfx103 variants of WORD4/5) - and gfx11-rsrc.json; -- which value goes into which field: Mesa src/amd/common ac_descriptors.c (ac_build_gfx10_texture_descriptor, - ac_set_mutable_tex_desc_fields: linear images on GFX10.3+ and GFX11 carry their pitch in WORD4 DEPTH and PITCH_MSB); -- format numbers: Mesa's GFX10_FORMAT enum (tools/gfx10_formats.json holds it too) and, for GFX11, the order of - LLVM's AMDGPU::UfmtGFX11::UnifiedFormat (SIDefines.h), which Mesa's GFX11_FORMAT follows. -GFX11 renumbers the formats (8_8_8_8_UNORM is 56 on GFX10 and 42 on GFX11), narrows FORMAT to [27:20], moves MAX_MIP -into WORD1 and drops WORD2's RESOURCE_LEVEL bit (GFX10 needs it set). A GFX11 part (the Radeon 880M is gfx1150, RDNA3.5) -runs these descriptors; RDNA2 (gfx1030) takes the GFX10 ones; a gfx1036 (RDNA2) ran them for tools/texoff_probe.py (2D and 3D, R32_SFLOAT). -""" -import re - -try: - from . import asm -except ImportError: # run as a script - import asm - -# Vulkan format name -> FORMAT field value, per family. GFX12 renumbers again and is not built here. -IMG_FORMATS = { - "gfx10": {"R8G8B8A8_UNORM": 56, "R16G16B16A16_SFLOAT": 71, "R32G32B32A32_SFLOAT": 77, "R32_SFLOAT": 22, - "R8G8B8A8_UINT": 60, "R8G8B8A8_SINT": 61}, - "gfx11": {"R8G8B8A8_UNORM": 42, "R16G16B16A16_SFLOAT": 57, "R32G32B32A32_SFLOAT": 63, "R32_SFLOAT": 22, - "R8G8B8A8_UINT": 46, "R8G8B8A8_SINT": 47}, -} -SQ_RSRC_IMG_2D = 9 -SEL_0, SEL_1, SEL_X, SEL_Y, SEL_Z, SEL_W = 0, 1, 4, 5, 6, 7 # SQ_SEL_*: DST_SEL values -PERF_MOD = 4 # what Mesa writes into WORD5 [22:20] -SENTINEL_BITS = (0x3F800000, 0x40000000, 0x40400000, 0x40800000) # 1.0 2.0 3.0 4.0, as image_fuzz.SENTINELS -POISON = 0xBAADF00D # what a kernel stores when its texture is misaligned - - -def check_arch(arch): - """The family whose T# layout is built, or ValueError (GFX12 has its own, not written here).""" - fam = asm.family(arch) - if fam not in IMG_FORMATS: - raise ValueError(f"no T# layout for {fam} ({arch}); this builder knows {', '.join(IMG_FORMATS)}") - return fam - - -def has_custom_pitch(arch): - """Whether WORD4 can carry a linear image's pitch: GFX10.3 (gfx1030..gfx1036) and GFX11. GFX10.1 has no such - field and takes the default pitch (width rounded up to 256 bytes), which pitch_texels also produces.""" - fam = check_arch(arch) - return fam == "gfx11" or re.fullmatch(r"gfx103[0-9a-f]", arch) is not None - - -def pitch_texels(width, bytes_per_texel): - """Row pitch in texels: the row size rounded up to 256 bytes (a linear image's pitch must be a multiple of it).""" - row = -(-width * bytes_per_texel // 256) * 256 - return row // bytes_per_texel - - -def image_words(arch, fmt, width, height, bytes_per_texel, swizzle=(SEL_X, SEL_Y, SEL_Z, SEL_W)): - """The 8 words of a 2D, one-mip, linear T# for gfx10/gfx11, with the base address (WORD0 and WORD1 [7:0]) left - zero: the kernel adds them once it knows where its texture landed.""" - fam = check_arch(arch) - if not (1 <= width <= 16384 and 1 <= height <= 16384): - raise ValueError(f"size {width}x{height} is outside 1..16384") - code = IMG_FORMATS[fam][fmt] - w, h = width - 1, height - 1 - word1 = (code << 20) | ((w & 3) << 30) - word2 = ((w >> 2) & 0xFFF) | (h << 14) - if fam == "gfx10": - word2 |= 1 << 31 # RESOURCE_LEVEL, "must be 1" on GFX10 and 0 on GFX11 - word3 = sum(s << (3 * i) for i, s in enumerate(swizzle)) | (SQ_RSRC_IMG_2D << 28) # levels 0, SW_MODE 0 = linear - word4 = 0 - if has_custom_pitch(arch): - pitch = pitch_texels(width, bytes_per_texel) - 1 - word4 = (pitch & 0x1FFF) | (((pitch >> 13) & 1) << 13) # DEPTH holds the low bits, PITCH_MSB bit 13 - word5 = PERF_MOD << 20 - return [0, word1, word2, word3, word4, word5, 0, 0] - - -def lay_out(texels, width, height, bytes_per_texel): - """Tight row-major texel bytes -> rows padded to pitch_texels (the padding is a pattern that is wrong to read).""" - row = width * bytes_per_texel - stride = pitch_texels(width, bytes_per_texel) * bytes_per_texel - out = bytearray() - for y in range(height): - out += texels[y * row:(y + 1) * row] + b"\xcd" * (stride - row) - return bytes(out) - - -def lanes(width, height): - """(threads, iterations): one lane per texel up to a 1024-lane group, then each lane takes several.""" - count = width * height - threads = min(count, 1024) - return threads, count // threads - - -def _longs(data): - data += b"\0" * (-len(data) % 4) - words = [int.from_bytes(data[i:i + 4], "little") for i in range(0, len(data), 4)] - return [f" .long {', '.join(f'0x{w:08x}' for w in words[i:i + 8])}" for i in range(0, len(words), 8)] - - -def kernel_lines(arch, uid, fmt, width, height, bytes_per_texel, dmask, texture, swizzle=(SEL_X, SEL_Y, SEL_Z, SEL_W)): - """The body of a raw kernel (asm.Kernel(..., raw=True): s[2:3] is the output pointer, v0 the lane). uid keeps the - labels of kernels in one module apart. `texture` is the padded texel bytes from lay_out. GFX11 spellings; asm.py - puts the GFX10 ones back for a gfx10 target. A texture that did not land 256-byte aligned makes every word of the - output POISON instead of reading from a wrong base.""" - t = image_words(arch, fmt, width, height, bytes_per_texel, swizzle) - threads, iterations = lanes(width, height) - n = dmask.bit_count() - dst = "v8" if n == 1 else f"v[8:{7 + n}]" - log2w = width.bit_length() - 1 - if width & (width - 1): - raise ValueError("the width must be a power of two") - out = ["s_getpc_b64 s[4:5]", - f".Lpc{uid}:", - f"s_add_u32 s4, s4, .Ltex{uid}-.Lpc{uid}", - "s_addc_u32 s5, s5, 0", - "s_and_b32 s6, s4, 255", - "s_lshr_b64 s[4:5], s[4:5], 8", - "s_mov_b32 s8, s4", - "s_and_b32 s9, s5, 255", - f"s_or_b32 s9, s9, 0x{t[1]:08x}"] - out += [f"s_mov_b32 s{8 + i}, 0x{t[i]:08x}" for i in range(2, 8)] - for k in range(iterations): - out += [f"v_add_nc_u32 v1, {k * threads}, v0", - f"v_and_b32 v2, {width - 1}, v1", - f"v_lshrrev_b32 v3, {log2w}, v1"] - out += [f"v_mov_b32 v{8 + i}, 0x{SENTINEL_BITS[i]:08x}" for i in range(4)] - out += ["s_cmp_lg_u32 s6, 0", - f"s_cbranch_scc0 .Lok{uid}_{k}"] - out += [f"v_mov_b32 v{8 + i}, 0x{POISON:08x}" for i in range(4)] - out += [f"s_branch .Lst{uid}_{k}", - f".Lok{uid}_{k}:", - f"image_load {dst}, v[2:3], s[8:15] dmask:0x{dmask:x} dim:SQ_RSRC_IMG_2D unorm", - "s_waitcnt vmcnt(0)", - f".Lst{uid}_{k}:", - "v_lshlrev_b32 v4, 4, v1", - "global_store_b128 v4, v[8:11], s[2:3]"] - out += ["s_endpgm", ".p2align 8", f".Ltex{uid}:"] - return out + _longs(texture) diff --git a/tools/image_bvh_census.py b/tools/image_bvh_census.py deleted file mode 100644 index 1204e8f8d..000000000 --- a/tools/image_bvh_census.py +++ /dev/null @@ -1,951 +0,0 @@ -r"""Census of the image_bvh_intersect_ray / image_bvh64_intersect_ray call sites (counts only, standard library). - - python -I tools/image_bvh_census.py /shaders/dxbc/disasm [--out image_bvh_census.json] - -docs/design.md's Ray tracing row describes one traversal step of AMD's BVH format, and the translator emulates it; -this tool counts how the game's shaders call it. For every listing that holds an `image_bvh*` instruction it reports: - -* the sites per form (`image_bvh_intersect_ray`, the 32-bit node id, against `image_bvh64_intersect_ray`); -* the ray-tracing resource descriptor (the four SGPRs of the call's third operand) decoded into the fields of PAL's - `sq_bvh_rsrc_t`: box_grow (bits 55..62), box_sort_en (63), size (64..105), triangle_return_mode (120), - llc_noalloc (121..122), big_page (123) and type (124..127). Word 0 holds base bits [31:0] and is reported only as - a literal or not; base itself is not decoded. A word counts as known when every path to the call sets its SGPR - from a literal (`s_mov_b32`, `s_movk_i32`, `s_brev_b32`, an inline `s_mov_b64`, or copies of those); -* how each of the four result words is read. - -How a read is found: the listing is loaded as `tools/rdna2spirv.py`'s `translate()` loads it (encodings re-anchored -when the listing holds data words, far branches folded, reachable code only) and split into basic blocks at -branches. The descriptor words come from a pass over the blocks from the entry. The result words come from one -forward walk per call, which starts at the call and asks, for the lanes that ran it, which definitions each VGPR can -hold. The call's k-th destination register holds word k. A plain `v_mov_b32` copies a register's definitions, and -any other write replaces them with a definition that is not a word. Partial writes (an SDWA byte or word insert with -UNUSED_PRESERVE, `v_writelane_b32`, a d16 load) keep the old definitions as well. Joins take the union. The walk -does not follow an edge back to the call or to code before it. The next pass of a loop around the call is a new -call, and a site whose words are still live on such an edge is counted under limits. An edge back to code that lies -inside the walk (an inner loop) is followed, and it drops every lane proof below. - -EXEC decides how much of a register a write replaces. The walk names each EXEC value. The root is the call's lanes. -Under it come a narrowing made by one instruction (`v_cmpx_*`, `s_and_saveexec_*`, `s_and_*` or `s_andn2_*` of EXEC) -and the else-half of a saved mask (`s_andn2_* exec, saved, exec`, `s_andn2_wrexec_*`). A mask saved with -`s_mov_b32 sX, exec` or a saveexec is restored by `s_mov_b32 exec, sX`. Any other EXEC write starts a value the walk -cannot place. A write under the root replaces the register. A write under a narrower value adds its definition for -those lanes and keeps the old one for every other lane. A read does not see a definition in only two cases: every lane -of the read ran an overwrite since (the read runs inside the same narrowing as the write), or the definition was made -only in lanes the read cannot run (the read is under the else-half of a mask whose then-half made it). A join whose two -paths have different EXEC values starts a new value, which lies within their nearest common one. Both proofs are -about one run of the instructions involved. Where the walk cannot give one (an EXEC write it cannot place, two values -with no complement relation, an inner back edge), both definitions stay visible, so the lane rule can only move a -read from "some paths" to "every path" by proving it. - -An instruction that reads a register holding a word is one read of that word. The read is on "every path" when -nothing but words can reach the register (and, for the ratio, the reciprocal operand holds only the reciprocal), and -on "some paths" otherwise: a lane merge the rule above cannot resolve, a register that one path overwrites, or a path -the program never takes. Each read gets exactly one category: - -* ratio: the word divided by word 1 of the same call, as the hardware's numerator/denominator pairs are meant to be - used: word 1 into `v_rcp_f32`, or a word times that reciprocal in `v_mul_f32` / `v_mul_legacy_f32`, with no - abs/neg modifier on either operand; -* high_half: word 1 read as its sign-extended high half, `sext(w1[31:16])`, the SDWA `src0_sel:WORD_1` operand of a - `v_mul_i32_i24`. This is the claim's "sign only" form. The category records that shape and does not prove that only - the sign survives: `high_half_product_readers` lists what reads the product (a signed compare against 0 or -1 - depends on the sign and on the high half being 0); -* raw_integer: read as integer bits by a VALU op, without the ratio: bitwise, shift, integer arithmetic, an integer - compare, a conversion from integer, or an SDWA field that is not the high-half product; -* raw_float: read as a float operand (the opcode's source type is f16/f32/f64), without the ratio; -* raw_other: any other read: a load/store/atomic address or data, a lane move (`v_readlane_b32`, - `v_readfirstlane_b32`, DPP, permlane), another `image_bvh*` operand; -* select (unclassified): the word is a data operand of `v_cndmask_b32`. The selected value is not followed. - -Each category is counted as [sites with a read of it on every path, sites with reads of it on some paths only]. -`site_partition` puts each site into one bucket: its every-path categories, then any category it reads on some paths -only. The buckets add up to the site total, and "none" means no every-path read. The words are followed through -registers only. A store counts as raw_other, and a value reloaded after it does not count as a word. Every count is -of static candidates: a read on a path the program never takes counts the same as one on a path it always takes. - -Standard library only. Nothing from the game is printed or written: counts, mnemonics and descriptor field values. -Usage: `python -I tools/image_bvh_census.py --help` lists the options. -""" -import argparse -import json -import os -import sys -from collections import Counter, defaultdict - -sys.path.insert(0, os.path.dirname(os.path.realpath(__file__))) -import rdna2spirv # noqa: E402 (base_op, BRANCHES, fold_far_branches, reachable_code, native_blob, stage_of) -from shader_ir import parse_file # noqa: E402 -from wave64_graphics_scan import scanned_paths # noqa: E402 - -FORMS = ("image_bvh_intersect_ray", "image_bvh64_intersect_ray") -CATEGORIES = ("ratio", "high_half", "raw_integer", "raw_float", "raw_other", "select") -OTHER = ("o",) # a definition that is not a result word (or the shader's entry) -OTHER_ENTRIES = frozenset({(OTHER, frozenset())}) -R1 = ("r1",) # v_rcp_f32 of word 1 -H = ("h",) # v_mul_i32_i24 of sext(word 1 [31:16]) -FIELDS = ( # (name, first bit, width) in the 128-bit descriptor, PAL sq_bvh_rsrc_t - ("box_grow", 55, 8), ("box_sort_en", 63, 1), ("size", 64, 42), ("triangle_return_mode", 120, 1), - ("llc_noalloc", 121, 2), ("big_page", 123, 1), ("type", 124, 4)) -RATIO_MULS = ("v_mul_f32", "v_mul_legacy_f32") -MEMORY = ("buffer_", "tbuffer_", "global_", "flat_", "scratch_", "ds_", "image_", "s_buffer_", "s_load") -LANE_OPS = ("v_readlane_b32", "v_readfirstlane_b32", "v_writelane_b32", "v_permlane16_b32", "v_permlanex16_b32") -ACC_DST = ("v_fmac_f32", "v_mac_f32", "v_mac_legacy_f32", "v_fmac_f16", "v_dot4c_i32_i8", "v_dot2c_i32_i16", - "v_dot8c_i32_i4", "v_pk_fmac_f16", "v_fmac_legacy_f32") -NO_VGPR_DST = ("exp", "buffer_store", "tbuffer_store", "image_store", "v_cmp", "ds_write", "global_store", - "scratch_store", "flat_store") -LDS_RETURNING = ("ds_read", "ds_swizzle", "ds_permute", "ds_bpermute", "ds_append", "ds_consume", "ds_wrxchg") -SALU_NO_DST = ("s_cmp", "s_bitcmp", "s_cbranch", "s_branch", "s_store", "s_buffer_store", "s_waitcnt", "s_nop", - "s_endpgm", "s_setpc", "s_barrier", "s_sendmsg", "s_dcache", "s_icache", "s_set", "s_sleep", - "s_ttrace", "s_inst_prefetch", "s_clause", "s_setprio", "s_trap", "s_wakeup", "s_round_mode", - "s_denorm_mode") -FLOAT_TYPES = ("f16", "f32", "f64") -LIMITS = ("sites the entry does not reach", "sites with a word in a v_cndmask_b32 (not followed)", - "sites with a category read on some paths only", "sites with a word live on a back edge to the call " - "(not followed)", "sites with no classified read on every path", "sites whose words are never read", - "shaders with s_setpc_b64 or s_swappc_b64 left", "shaders with relative VGPR addressing") - - -class Skip(Exception): - """A listing the census cannot follow; the reason is counted, not fatal.""" - - -# ---- loading -------------------------------------------------------------------------------------------------- - -def load_program(path): - """The reachable instructions of a listing, as rdna2spirv.translate() takes them (no SPIR-V is built).""" - info = parse_file(path) - insns = info["insns"] - if not insns: - raise Skip("no instructions") - if any(not i.get("enc") for i in insns): - raise Skip("instruction without encoding bytes") # pcs (and so branch targets) are unknown - if info["invalid"]: - try: - blob = rdna2spirv.native_blob(path, info["name"]) - except OSError: - raise Skip("data words without the native blob to re-anchor them") from None - pos = info["code_start"] - for ins in insns: - enc = bytes.fromhex(ins["enc"]) - at, skipped = pos, 0 - while not rdna2spirv.same_encoding(blob[at:at + len(enc)], enc, ins["op"], len(ins["args"])): - at += 4 - skipped += 4 - if skipped > 4096 or at >= len(blob): - at = None - break - if at is None: - if pos + len(enc) > len(blob): - raise Skip("undecodable words (cannot re-anchor)") - at = pos - ins["normalized"] = True - ins["pc"] = at - pos = at + len(enc) - insns = rdna2spirv.fold_far_branches(insns) - try: - insns = rdna2spirv.reachable_code(insns) - except rdna2spirv.Unsupported: - raise Skip("branch into data") from None - if any(i.get("normalized") for i in insns): - raise Skip("reachable instruction with normalized encoding") - else: - insns = rdna2spirv.fold_far_branches(insns) - return info["name"], insns - - -def blocks_of(insns): - """Basic blocks and successors: leaders at branch targets and after branches, s_endpgm and s_setpc_b64.""" - def next_pc(ins): - return ins["pc"] + len(ins["enc"]) // 2 - - def target(ins): - if "target" in ins: - return ins["target"] - imm = next((x for x in ins["args"] if x["k"] == "imm"), None) - if imm is None or not ins.get("enc"): - raise Skip("branch without offset or encoding") - v = imm["v"] & 0xFFFF - return next_pc(ins) + 4 * (v - 0x10000 if v & 0x8000 else v) - - pcs = {i["pc"] for i in insns} - leaders = {insns[0]["pc"]} - for ins in insns: - op = rdna2spirv.base_op(ins["op"]) - if op in rdna2spirv.BRANCHES: - if target(ins) not in pcs: - raise Skip("branch target outside code") - leaders.update((target(ins), next_pc(ins))) - elif op in ("s_endpgm", "s_setpc_b64"): - leaders.add(next_pc(ins)) - starts = sorted(p for p in leaders if p in pcs) - index = {p: n for n, p in enumerate(starts)} - blocks = [[] for _ in starts] - cur = 0 - for ins in insns: - cur = index.get(ins["pc"], cur) - blocks[cur].append(ins) - succ = [] - for n, blk in enumerate(blocks): - last = blk[-1] - op = rdna2spirv.base_op(last["op"]) - fall = [n + 1] if n + 1 < len(blocks) else [] - if op in ("s_endpgm", "s_setpc_b64"): - succ.append([]) - elif op == "s_branch": - succ.append([index[target(last)]]) - elif op in rdna2spirv.BRANCHES: - succ.append(list(dict.fromkeys([index[target(last)]] + fall))) - else: - succ.append(fall) - return blocks, succ - - -# ---- operands ------------------------------------------------------------------------------------------------- - -def vregs(a): - if a["k"] == "vgpr": - return list(range(a["r"], a["r"] + a.get("n", 1))) - if a["k"] == "vlist": - return list(a["r"]) - return [] - - -def vgpr_access(ins): - """(read operands as [(argument index, registers)], written registers, partial write?) by the conventions of - rdna2spirv.reg_reads_writes, plus atomics and LDS ops that return nothing and the partial writes.""" - op, a, mods = ins["op"], ins["args"], ins.get("mods", []) - if not a: - return [], [], False - bop = rdna2spirv.base_op(op) - no_dst = op.startswith(NO_VGPR_DST) or op.startswith("v_cmpx") - if bop.startswith(("global_atomic_", "flat_atomic_", "buffer_atomic_", "image_atomic_")) and "glc" not in mods: - no_dst = True - if bop.startswith("ds_") and not (bop.startswith(LDS_RETURNING) or "_rtn_" in bop): - no_dst = True - if op.startswith("s_"): - return [], [], False - sources = [n for n in range(len(a)) if no_dst or n > 0] - reads = [(n, vregs(a[n])) for n in sources if vregs(a[n])] - partial = rdna2spirv.sdwa_reads_dst(op, mods) or bop == "v_writelane_b32" or \ - ("_d16" in bop and bop.startswith(MEMORY)) - if (partial or bop in ACC_DST) and not no_dst and vregs(a[0]): - reads.append((0, vregs(a[0]))) - writes = [] if no_dst else vregs(a[0]) - if bop == "v_swap_b32" and len(a) > 1: - writes = vregs(a[0]) + vregs(a[1]) - return reads, writes, partial - - -def source_args(ins): - """Indexes of the source operands (everything after the destination, or every operand of a store/compare).""" - op, a = ins["op"], ins["args"] - if op.startswith("v_cmpx"): - return list(range(len(a))) - if op.startswith(NO_VGPR_DST) and not op.startswith("v_cmp"): - return list(range(len(a))) - return list(range(1, len(a))) # a v_cmp writes VCC or an SGPR pair first - - -def source_is_float(bop): - """Whether the opcode reads its sources as floats: the last type in v_cvt_*, else any type in the name.""" - parts = bop.split("_") - if bop.startswith("v_cvt_"): - return parts[-1] in FLOAT_TYPES - return any(p in FLOAT_TYPES for p in parts[1:]) - - -def plain(a): - return not a.get("neg") and not a.get("abs") and not a.get("sext") - - -def is_copy(ins): - """A v_mov_b32 / v_swap_b32 that moves the bits unchanged: no modifier, no SDWA select, no DPP.""" - bop = rdna2spirv.base_op(ins["op"]) - a = ins["args"] - if bop not in ("v_mov_b32", "v_swap_b32") or ins["op"].endswith(("_sdwa", "_dpp")) or len(a) < 2: - return False - return not ins.get("mods") and plain(a[1]) and bool(vregs(a[1])) - - -def high_half_operand(ins, n): - """Operand n of a v_mul_i32_i24 is sext(src[31:16]) (SDWA src_sel:WORD_1 with sext).""" - if rdna2spirv.base_op(ins["op"]) != "v_mul_i32_i24" or not ins["op"].endswith("_sdwa") or n not in (1, 2): - return False - return ins["args"][n].get("sext") and f"src{n - 1}_sel:WORD_1" in ins.get("mods", []) - - -def kind_of(ins, n): - """raw_* category of a read of operand n that is neither ratio nor high_half.""" - op = ins["op"] - bop = rdna2spirv.base_op(op) - if bop.startswith(MEMORY) or bop.startswith("image_bvh") or bop in LANE_OPS or op.endswith("_dpp") or \ - any(m.startswith(("quad_perm:", "row_", "dpp8:")) for m in ins.get("mods", [])) or \ - not bop.startswith("v_"): - return "raw_other" - return "raw_float" if source_is_float(bop) else "raw_integer" - - -# ---- SGPR constants (descriptor words) ---------------------------------------------------------------------- - -def sregs(a): - return list(range(a["r"], a["r"] + a.get("n", 1))) if a["k"] == "sgpr" else [] - - -def imm32(a): - if a["k"] == "imm" and not a.get("neg") and not a.get("abs"): - return a["v"] & 0xFFFFFFFF - if a["k"] == "fimm" and not a.get("neg") and not a.get("abs"): - import struct - return struct.unpack(" 1 and ("_co_" in bop or bop.startswith("v_div_scale")): - written += sregs(a[1]) # the carry / scale SGPR of a VOP3b op - value = {} - if bop in ("s_mov_b32", "s_movk_i32", "s_brev_b32") and len(a) == 2 and len(sregs(a[0])) == 1: - v = imm32(a[1]) - if v is not None: - if bop == "s_movk_i32": - v = (v & 0xFFFF) - (0x10000 if v & 0x8000 else 0) & 0xFFFFFFFF - elif bop == "s_brev_b32": - v = int(f"{v:032b}"[::-1], 2) - value[a[0]["r"]] = v - elif bop == "s_mov_b32" and len(sregs(a[1])) == 1 and a[1]["r"] in sg and plain(a[1]): - value[a[0]["r"]] = sg[a[1]["r"]] - elif bop == "s_mov_b64" and len(a) == 2 and len(sregs(a[0])) == 2: - r = a[0]["r"] - if a[1]["k"] == "imm" and -16 <= a[1]["v"] <= 64: # inline constant, sign-extended - v = a[1]["v"] & 0xFFFFFFFFFFFFFFFF - value = {r: v & 0xFFFFFFFF, r + 1: v >> 32} - elif len(sregs(a[1])) == 2: - value = {r + i: sg[a[1]["r"] + i] for i in (0, 1) if a[1]["r"] + i in sg} - for r in written: - sg.pop(r, None) - sg.update(value) - - -def decode_descriptor(words): - """{field: value or None} for the descriptor words [w0, w1, w2, w3] (None = not a literal).""" - out = {} - for name, lo, width in FIELDS: - need = range(lo // 32, (lo + width - 1) // 32 + 1) - if any(words[i] is None for i in need): - out[name] = None - continue - bits = sum(words[i] << (32 * (i - need[0])) for i in need) - out[name] = (bits >> (lo - 32 * need[0])) & ((1 << width) - 1) - return out - - -# ---- the dataflow ----------------------------------------------------------------------------------------------- - -def join_sgprs(old, inc, at=None): - """The SGPR literals both maps agree on; None when old is unchanged.""" - if old is None: - return dict(inc) - out = {r: v for r, v in old.items() if inc.get(r) == v} - return out if len(out) != len(old) else None - - -# ---- EXEC: which lanes a write covers --------------------------------------------------------------------------- -# -# A walk starts at one call, so its lanes are the call's (ROOT). An EXEC value is a node: ROOT, a narrowing of a node -# at one instruction (("n", pc, parent): a subset of the parent), the else-half of a saved mask (("e", pc, parent, -# then): the parent's lanes outside `then`), the value after a join of two paths with different EXEC (("j", block, -# parent): within their nearest common node, or its own root without one), or an EXEC value the walk cannot place -# (("u", pc), its own root). A node stands for one run of its instruction or join: the walk follows no back edge to -# the call, and an inner back edge drops every proof (see strip()). - -ROOT = ("root",) - - -def parent(node): - return node[2] if node[0] in ("n", "e", "j") else None - - -def within(node, outer): - """node's lanes are a subset of outer's: outer is node or one of its ancestors.""" - while node is not None: - if node == outer: - return True - node = parent(node) - return False - - -def disjoint(a, b): - """No lane in both: one of them sits under the else-half of a mask whose then-half holds the other.""" - for x, y in ((a, b), (b, a)): - node = x - while node is not None: - if node[0] == "e" and within(y, node[3]): - return True - node = parent(node) - return False - - -def common(a, b): - """The nearest node both lie within, or None.""" - up = set() - while a is not None: - up.add(a) - a = parent(a) - while b is not None and b not in up: - b = parent(b) - return b - - -def visible(guard, node): - """Whether a definition with this guard can be what a lane under EXEC `node` reads.""" - for kind, at in guard: - if kind == "in" and disjoint(at, node): # defined only in lanes this read does not run - return False - if kind == "out" and within(node, at): # every lane of this read was overwritten at `at` - return False - return True - - -def live(guard): - """A guard some lane can satisfy (no "in" a set and "out" a superset, no "in" two disjoint sets).""" - ins = [at for kind, at in guard if kind == "in"] - outs = [at for kind, at in guard if kind == "out"] - return not any(within(i, o) for i in ins for o in outs) and \ - not any(disjoint(i, j) for n, i in enumerate(ins) for j in ins[n + 1:]) - - -def entries_union(a, b): - """Union of two definition sets, dropping an entry whose guard has a subset with the same label.""" - if b <= a: - return a - if a <= b: - return b - by_label = defaultdict(set) - for lab, guard in a | b: - by_label[lab].add(guard) - out = [] - for lab, guards in by_label.items(): - if len(guards) == 1: - out.append((lab, next(iter(guards)))) - continue - out += [(lab, g) for g in guards if not any(h < g for h in guards)] - return frozenset(out) - - -def labels(entries, node): - """The labels a read under `node` can see.""" - return {lab for lab, guard in entries if visible(guard, node)} - - -def mask_writes(ins): - """SGPRs an instruction writes (destinations, VOP3b carry/scale outputs).""" - a, op = ins["args"], ins["op"] - out = [] - if a and not op.startswith(SALU_NO_DST): - out += sregs(a[0]) - if len(a) > 1 and ("_co_" in rdna2spirv.base_op(op) or rdna2spirv.base_op(op).startswith("v_div_scale")): - out += sregs(a[1]) - return out - - -def is_exec(a): - return a["k"] == "special" and a.get("t", "").startswith("exec") - - -def exec_step(st, ins): - """Apply one instruction to the EXEC node and the saved-mask SGPRs (st.masks: SGPR -> node).""" - op, a, pc = ins["op"], ins["args"], ins["pc"] - bop = rdna2spirv.base_op(op) - cur = st.exec - saved = lambda x: st.masks.get(x["r"]) if x["k"] == "sgpr" else None # noqa: E731 - new_masks = {} - if bop.startswith("v_cmpx"): - new = ("n", pc, cur) - elif "saveexec" in bop and a: - new_masks = {r: cur for r in sregs(a[0])} - if bop.startswith(("s_and_saveexec", "s_andn1_saveexec")): - new = ("n", pc, cur) - elif bop.startswith("s_or_saveexec") and len(a) > 1 and imm32(a[1]) == 0xFFFFFFFF: - new = ROOT # every lane, so every lane of the call - else: - new = ("u", pc) - elif bop.startswith("s_andn2_wrexec") and len(a) > 1 and saved(a[1]): - new = ("e", pc, saved(a[1]), cur) # EXEC = saved & ~EXEC: the else-half - new_masks = {r: new for r in sregs(a[0])} - elif not rdna2spirv.writes_exec(ins): - new = None - elif bop in ("s_mov_b32", "s_mov_b64") and len(a) == 2: - new = saved(a[1]) or (ROOT if imm32(a[1]) == 0xFFFFFFFF else ("u", pc)) - elif bop in ("s_and_b32", "s_and_b64") and len(a) == 3: - if is_exec(a[1]) or is_exec(a[2]): - new = ("n", pc, cur) - elif saved(a[1]) or saved(a[2]): - new = ("n", pc, saved(a[1]) or saved(a[2])) - else: - new = ("u", pc) - elif bop in ("s_andn2_b32", "s_andn2_b64") and len(a) == 3: - if is_exec(a[1]): - new = ("n", pc, cur) # EXEC & ~x - elif is_exec(a[2]) and saved(a[1]): - new = ("e", pc, saved(a[1]), cur) - else: - new = ("u", pc) - else: - new = ("u", pc) - for r in mask_writes(ins): - st.masks.pop(r, None) - if bop in ("s_mov_b32", "s_mov_b64") and len(a) == 2 and is_exec(a[1]) and not is_exec(a[0]): - new_masks = {r: cur for r in sregs(a[0])} - st.masks.update(new_masks) - if new is not None: - st.exec = new - - -class SiteState: - """One walk's state: VGPR -> definitions [(label, guard)], saved-mask SGPRs, EXEC node.""" - __slots__ = ("vg", "masks", "exec") - - def __init__(self, vg=None, masks=None, ex=ROOT): - self.vg, self.masks, self.exec = vg or {}, masks or {}, ex - - def copy(self): - return SiteState(dict(self.vg), dict(self.masks), self.exec) - - def idle(self): - """No register can hold a word, its reciprocal or its high-half product any more.""" - return all(lab == OTHER for s in self.vg.values() for lab, _ in s) - - def read(self, r): - return labels(self.vg.get(r, OTHER_ENTRIES), self.exec) - - def write(self, r, new, partial=False): - """new: definitions [(label, guard)] the active lanes now hold.""" - node = self.exec - old = self.vg.get(r, OTHER_ENTRIES) - if node == ROOT and not partial: - out = frozenset(new) - else: - mine = frozenset((lab, guard | {("in", node)}) for lab, guard in new) - rest = old if partial else frozenset((lab, guard | {("out", node)}) for lab, guard in old) - out = entries_union(frozenset(e for e in mine if live(e[1])), frozenset(e for e in rest if live(e[1]))) - if out == OTHER_ENTRIES: - self.vg.pop(r, None) - else: - self.vg[r] = out - - -def join_site(old, inc, at=None): - """Join of two walk states at the block starting at pc `at`: definitions united, masks kept where equal, and - two different EXEC values replaced by a new one, ("j", at, nearest common value), that lies within both - paths' common value.""" - if old is None: - return inc.copy() - vg, changed = dict(old.vg), False - for r in set(old.vg) | set(inc.vg): - a, b = old.vg.get(r, OTHER_ENTRIES), inc.vg.get(r, OTHER_ENTRIES) - u = entries_union(a, b) - if u != a: - vg[r], changed = u, True - masks = {r: v for r, v in old.masks.items() if inc.masks.get(r) == v} - changed = changed or len(masks) != len(old.masks) - ex = old.exec - if inc.exec != old.exec: - ex = ("j", at, common(old.exec, inc.exec)) - changed = changed or ex != old.exec - return SiteState(vg, masks, ex) if changed else None - - -def strip(st): - """Taken an inner back edge: the next pass of an instruction narrows to other lanes, so drop every guard.""" - out = st.copy() - out.masks = {} # a mask saved in this pass must not place a read in the next one - out.vg = {r: frozenset((lab, frozenset()) for lab, _ in s) for r, s in st.vg.items()} - out.vg = {r: s for r, s in out.vg.items() if s != OTHER_ENTRIES} - return out - - -def flow(blocks, succ, start, transfer, join, initial, copy=dict, cut=None, on_back=None, idle=None): - """Forward dataflow from (block, instruction index) `start` to a fixpoint. transfer(state, ins) updates a state - in place; join(old, new) returns the joined state or None when old already covers new. An edge to a block that - starts at or before pc `cut` is not followed, and the states that reach one are returned. Any other edge to a - block at or before the end of the one it leaves (an inner back edge) passes its state through on_back first. - A state for which idle(state) holds is not sent on (nothing it could reach would record anything).""" - b0, i0 = start - state_in = [None] * len(blocks) - work, at_cut = set(), [] - - def send(b, state): - if idle is not None and idle(state): - return - for s in succ[b]: - if cut is not None and blocks[s][0]["pc"] <= cut: - at_cut.append(state) - continue - out = on_back(state) if on_back and blocks[s][0]["pc"] <= blocks[b][-1]["pc"] else state - merged = join(state_in[s], out, blocks[s][0]["pc"]) - if merged is not None: - state_in[s] = merged - work.add(s) - if i0 == 0 and cut is None: - state_in[b0] = join(None, initial, blocks[b0][0]["pc"]) - work.add(b0) - else: # the rest of the start block; a later visit runs all of it - state = copy(initial) - for ins in blocks[b0][i0:]: - transfer(state, ins) - send(b0, state) - while work: - b = min(work) # program order converges in fewer passes than LIFO - work.discard(b) - state = copy(state_in[b]) - for ins in blocks[b]: - transfer(state, ins) - send(b, state) - return at_cut - - -def ratio_partner(st, other): - """"all" when the other multiplicand holds the reciprocal of word 1 on every path, "some" when only on some, - "none" otherwise.""" - regs = vregs(other) - s = st.read(regs[0]) if len(regs) == 1 else {OTHER} - if R1 not in s: - return "none" - return "all" if s == {R1} else "some" - - -def derived(s, label): - """The labels of a value computed from word 1: `label` when word 1 can reach, plus OTHER when anything else - can.""" - out = {label} if ("w", 1) in s else set() - if s - {("w", 1)}: - out.add(OTHER) - return out - - -def product_reader(ins, n): - """How a high-half product is read: the mnemonic and what the other source is (0, -1, a register...).""" - others = [m for m in source_args(ins) if m != n] - if len(others) != 1: - what = f"{len(others)} other operands" - else: - const = imm32(ins["args"][others[0]]) - what = {0: "0", 0xFFFFFFFF: "-1"}.get(const, "a register" if const is None else "a constant") - return f"{rdna2spirv.base_op(ins['op'])} with {what}" - - -def classify(st, ins, n, words): - """(category, reach) of a read of `words` (labels one register can hold) through operand n.""" - bop = rdna2spirv.base_op(ins["op"]) - a = ins["args"] - only_w1 = all(w[1] == 1 for w in words) - if bop.startswith("v_cndmask_b32") and n in (1, 2): - return "select", "all" - if bop == "v_rcp_f32" and n == 1 and only_w1 and plain(a[1]) and not ins.get("mods"): - return "ratio", "all" - if bop in RATIO_MULS and n in (1, 2) and len(a) == 3 and plain(a[1]) and plain(a[2]) and not ins.get("mods"): - partner = ratio_partner(st, a[3 - n]) - if partner != "none": - return "ratio", partner - if high_half_operand(ins, n) and only_w1: - return "high_half", "all" - return kind_of(ins, n), "all" - - -def site_transfer(call_pc, events, product_reads): - """The transfer function of one call's walk: record the reads of its words, then apply the writes.""" - def transfer(st, ins): - a = ins["args"] - bop = rdna2spirv.base_op(ins["op"]) - pc = ins["pc"] - reads, writes, partial = vgpr_access(ins) - copy = is_copy(ins) - ev, pr = [], [] - for n, regs in reads if not copy else (): - for r in regs: - s = st.read(r) - if H in s: - pr.append((product_reader(ins, n), "all" if s == {H} else "some")) - words = sorted(x for x in s if x[0] == "w") - if not words: - continue - cat, reach = classify(st, ins, n, words) - if len(words) != len(s): - reach = "some" - ev += [(w[1], cat, reach, bop) for w in words] - events[pc] = ev - product_reads[pc] = pr - if pc == call_pc: - new = {r: {("w", k)} for k, r in enumerate(writes[:4])} - elif copy: - new = {r: st.read(a[1]["r"]) for r in writes[:1]} - if bop == "v_swap_b32": - new[a[1]["r"]] = st.read(a[0]["r"]) - elif bop == "v_rcp_f32" and writes and len(a) > 1 and len(vregs(a[1])) == 1: - new = {writes[0]: derived(st.read(a[1]["r"]), R1)} - elif writes and any(high_half_operand(ins, n) for n in (1, 2)): - n = 1 if high_half_operand(ins, 1) else 2 - new = {writes[0]: derived(st.read(a[n]["r"]), H)} - else: - new = {r: {OTHER} for r in writes} - for r, labs in new.items(): - st.write(r, [(lab, frozenset()) for lab in labs], partial) - exec_step(st, ins) - return transfer - - -def descriptor_words(blocks, succ, calls): - """{call pc: [w0..w3 or None]}: the SGPR literals in force at each call, from the entry.""" - found = {} - - def transfer(sg, ins): - if ins["pc"] in calls: - a = ins["args"] - r = a[2]["r"] if len(a) > 2 and a[2]["k"] == "sgpr" else None - old = found.get(ins["pc"]) - now = [sg.get(r + i) if r is not None else None for i in range(4)] - found[ins["pc"]] = now if old is None else [x if x == y else None for x, y in zip(old, now)] - sgpr_step(sg, ins) - flow(blocks, succ, (0, 0), transfer, join_sgprs, {}) - return found - - -def analyse(insns): - """Per-site records of one program: form, descriptor words, and the reads of its words with their pcs. - - Returns [{"form", "pc", "reached", "desc": [w0..w3 or None], - "reads": [(pc, word, category, reach, mnemonic, past a later call)], "product_reads": [(pc, reader, reach)]}] in - program order; reach is "all" or "some" (paths), and the last field says whether the read lies after another - call in program order. The pcs are for local inspection; summarise() drops them.""" - blocks, succ = blocks_of(insns) - where = {i["pc"]: (b, n) for b, blk in enumerate(blocks) for n, i in enumerate(blk)} - calls = [i for i in insns if rdna2spirv.base_op(i["op"]) in FORMS] - desc = descriptor_words(blocks, succ, {c["pc"] for c in calls}) - sites = [] - for c in calls: - events, product_reads = {}, {} - at_cut = flow(blocks, succ, where[c["pc"]], site_transfer(c["pc"], events, product_reads), join_site, - SiteState(), copy=SiteState.copy, cut=c["pc"], on_back=strip, idle=SiteState.idle) - sites.append({"form": rdna2spirv.base_op(c["op"]), "pc": c["pc"], "reached": c["pc"] in desc, - "loop_carried": any(lab[0] == "w" for st in at_cut for s in st.vg.values() for lab, _ in s), - "desc": desc.get(c["pc"], [None] * 4), - "reads": [(pc,) + e + (any(c["pc"] < x["pc"] < pc for x in calls),) - for pc in sorted(events) for e in events[pc]], - "product_reads": [(pc,) + e for pc in sorted(product_reads) for e in product_reads[pc]]}) - return sites - - -# ---- corpus ----------------------------------------------------------------------------------------------------- - -def scan_listing(path): - """{"stage", "sites"} for a listing with an image_bvh* instruction, None without one; raises Skip.""" - with open(path, encoding="utf-8", errors="replace") as f: - if "image_bvh" not in f.read(): - return None - name, insns = load_program(path) - if not any(rdna2spirv.base_op(i["op"]) in FORMS for i in insns): - return None - return {"stage": rdna2spirv.stage_of(name, path), "sites": analyse(insns), - "setpc": any(rdna2spirv.base_op(i["op"]) in ("s_setpc_b64", "s_swappc_b64") for i in insns), - "movrel": any(rdna2spirv.base_op(i["op"]).startswith(("v_movrel", "s_set_gpr_idx")) for i in insns)} - - -def scan_directory(disasm): - """(listings scanned, per-listing records for those with sites, Counter of skip reasons).""" - paths = scanned_paths(disasm) - records, skipped = [], Counter() - for path in paths: - try: - r = scan_listing(path) - except Skip as e: - skipped[str(e)] += 1 - continue - if r is not None: - records.append(r) - return len(paths), records, skipped - - -def hexs(v): - return str(v) if v < 10 else hex(v) - - -def site_view(s): - """(categories read on every path, categories read only on some paths) of one site record.""" - every = {e[2] for e in s["reads"] if e[3] == "all"} - return every, {e[2] for e in s["reads"]} - every - - -def split_count(counter, items, every_items): - """Add 1 to counter[x][0] for x read on every path, to counter[x][1] for x read on some paths only.""" - for x in every_items: - counter[x][0] += 1 - for x in set(items) - set(every_items): - counter[x][1] += 1 - - -def pairs(): - return defaultdict(lambda: [0, 0]) - - -def ordered(d): - def weight(v): - return -sum(v) if isinstance(v, list) else -v - return {k: v for k, v in sorted(d.items(), key=lambda kv: (weight(kv[1]), kv[0]))} - - -def summarise(listings, records, skipped): - """Counts only, no names: the JSON report.""" - forms, stages, word0 = Counter(), Counter(), Counter() - limits = Counter({k: 0 for k in LIMITS}) - fields = {name: Counter() for name, _, _ in FIELDS} - cat_sites, cat_shaders, cat_reads, some_reads = pairs(), Counter(), Counter(), Counter() - per_word = {str(k): pairs() for k in range(4)} - partition, partition_shaders = Counter(), defaultdict(set) - mnemonics = {c: pairs() for c in CATEGORIES} - products = pairs() - position = pairs() - total = 0 - for n, r in enumerate(records): - stages[r["stage"]] += 1 - in_shader = set() - for s in r["sites"]: - total += 1 - forms[s["form"]] += 1 - if not s["reached"]: - limits["sites the entry does not reach"] += 1 - w = s["desc"] - word0["literal" if w[0] is not None else "not a literal"] += 1 - for name, v in decode_descriptor(w).items(): - fields[name]["not a literal" if v is None else hexs(v)] += 1 - reads = s["reads"] - every, some = site_view(s) - split_count(cat_sites, every | some, every) - in_shader |= every | some - for e in reads: - cat_reads[e[2]] += 1 - some_reads[e[2]] += e[3] == "some" - for word in range(4): - mine = [e for e in reads if e[1] == word] - split_count(per_word[str(word)], {e[2] for e in mine}, {e[2] for e in mine if e[3] == "all"}) - for c in CATEGORIES: - mine = [e for e in reads if e[2] == c] - split_count(mnemonics[c], {e[4] for e in mine}, {e[4] for e in mine if e[3] == "all"}) - partial = [e for e in reads if e[3] == "some"] - for c in {e[2] for e in partial}: - position[c][0 if any(not e[5] for e in partial if e[2] == c) else 1] += 1 - split_count(products, {p[1] for p in s["product_reads"]}, - {p[1] for p in s["product_reads"] if p[2] == "all"}) - key = "+".join(c for c in CATEGORIES if c in every) or "none" - if some: - key += " (some paths only: " + "+".join(c for c in CATEGORIES if c in some) + ")" - partition[key] += 1 - partition_shaders[key].add(n) - if "select" in every | some: - limits["sites with a word in a v_cndmask_b32 (not followed)"] += 1 - if some: - limits["sites with a category read on some paths only"] += 1 - if s["loop_carried"]: - limits["sites with a word live on a back edge to the call (not followed)"] += 1 - if reads and not every - {"select"}: - limits["sites with no classified read on every path"] += 1 - if not reads: - limits["sites whose words are never read"] += 1 - for c in in_shader: - cat_shaders[c] += 1 - limits["shaders with s_setpc_b64 or s_swappc_b64 left"] = sum(1 for r in records if r["setpc"]) - limits["shaders with relative VGPR addressing"] = sum(1 for r in records if r["movrel"]) - return { - "listings": listings, - "not_analysed": dict(sorted(skipped.items())), - "shaders": dict(sorted(stages.items())), - "sites": {"total": total, **{f: forms[f] for f in FORMS}}, - "descriptor": {"word0": dict(sorted(word0.items())), - "fields": {k: dict(sorted(v.items())) for k, v in fields.items()}}, - "word_reads": {"pairs": "[sites read on every path, sites read on some paths only]", - "sites": {c: cat_sites[c] for c in CATEGORIES}, - "shaders": {c: cat_shaders[c] for c in CATEGORIES}, - "reads": {c: cat_reads[c] for c in CATEGORIES}, - "reads_some_paths": {c: some_reads[c] for c in CATEGORIES}, - "per_word_sites": {k: {c: v[c] for c in CATEGORIES if c in v} for k, v in per_word.items()}}, - "site_partition": {k: [v, len(partition_shaders[k])] for k, v in ordered(partition).items()}, - "mnemonic_sites": {c: ordered(m) for c, m in mnemonics.items() if m}, - "high_half_product_readers": ordered(products), - "some_paths_position": {"pairs": "[sites with a some-paths read before the next call in program order, " - "sites whose some-paths reads all lie after a later call]", - **{c: position[c] for c in CATEGORIES if c in position}}, - "limits": dict(sorted(limits.items())), - } - - -def print_summary(s, out=None): - out = out or sys.stdout - w = lambda text="": print(text, file=out) # noqa: E731 - st = s["sites"] - w(f"{st['total']} image_bvh sites in {sum(s['shaders'].values())} shaders (" - + ", ".join(f"{k} {v}" for k, v in s["shaders"].items()) + f"); {s['listings']} listings scanned" - + (f"; not analysed {s['not_analysed']}" if s["not_analysed"] else "")) - w(" " + ", ".join(f"{f} {st[f]}" for f in FORMS)) - d = s["descriptor"] - w("descriptor word 0: " + ", ".join(f"{k} {v}" for k, v in d["word0"].items())) - for name, row in d["fields"].items(): - w(f" {name}: " + ", ".join(f"{k} at {v}" for k, v in row.items())) - wr = s["word_reads"] - w("word reads: sites read on every path / on some paths only, shaders, reads") - for c in CATEGORIES: - a, b = wr["sites"][c] - w(f" {c:<12} {a:5d} / {b:5d} {wr['shaders'][c]:3d} {wr['reads'][c]:6d}" - + (" (unclassified)" if c == "select" else "")) - for k, row in wr["per_word_sites"].items(): - w(f" w{k}: " + ", ".join(f"{c} {v[0]}/{v[1]}" for c, v in row.items())) - w("site partition (sites, shaders):") - for k, (v, n) in s["site_partition"].items(): - w(f" {k}: {v}, {n}") - for c, m in s["mnemonic_sites"].items(): - w(f"{c} mnemonics (sites every/some): " + ", ".join(f"{k} {v[0]}/{v[1]}" for k, v in m.items())) - if s["high_half_product_readers"]: - w("high-half product read by (sites every/some): " - + ", ".join(f"{k} {v[0]}/{v[1]}" for k, v in s["high_half_product_readers"].items())) - w("some-paths reads (sites with one before the next call / sites with all after a later call): " - + ", ".join(f"{c} {v[0]}/{v[1]}" for c, v in s["some_paths_position"].items() if c != "pairs")) - w("limits: " + "; ".join(f"{k} {v}" for k, v in s["limits"].items())) - - -def main(argv=None) -> int: - ap = argparse.ArgumentParser(description="Count image_bvh*_intersect_ray sites, their descriptor fields and how " - "their result words are read (counts only, no names)") - ap.add_argument("src", help="/shaders/dxbc/disasm from the shaders stage") - ap.add_argument("--out", help="write the same counts to a JSON file") - args = ap.parse_args(argv) - if not os.path.isdir(args.src): - ap.error(f"not a directory: {args.src}") - if args.out: - if os.path.isdir(args.out): - ap.error(f"{args.out} is a directory, not a JSON file") - if not os.path.isdir(os.path.dirname(os.path.abspath(args.out))): - ap.error(f"output directory does not exist: {os.path.dirname(os.path.abspath(args.out))}") - if os.path.exists(args.out) and any(os.path.samefile(args.out, p) for p in scanned_paths(args.src)): - ap.error("output must not overwrite a listing it scans") - summary = summarise(*scan_directory(args.src)) - print_summary(summary) - if args.out: - try: - with open(args.out, "w", encoding="utf-8", newline="\n") as f: - json.dump(summary, f, indent=1) - except OSError as e: - print(f"ERROR: cannot write {args.out}: {e.strerror or e}", file=sys.stderr) - return 2 - print(f"wrote {args.out}") - return 0 - - -if __name__ == "__main__": - try: # a redirected stdout is strict ANSI code page under -I; write '?' for what it cannot encode - sys.stdout.reconfigure(errors="replace") - except (AttributeError, ValueError, OSError): - pass - sys.exit(main()) diff --git a/tools/image_d16_probe.py b/tools/image_d16_probe.py deleted file mode 100644 index dc29771b2..000000000 --- a/tools/image_d16_probe.py +++ /dev/null @@ -1,359 +0,0 @@ -r"""How an RDNA2 GPU narrows 32-bit integer texels in d16 image loads, per image dimension (SHADER-387). Standard -library only. - -docs/design.md ("Typed image loads") has native gfx1036 saturating 32-bit UINT/SINT texels to the 16-bit range in -2D d16 loads, and lists 1D, 2D-array and 3D d16 loads as unchecked. Mesa sets `integer_dest_saturates` for AMD, -the translator saturates (`saturate_int16`). This probe measures it natively (through tools/hw_oracle/) on every -dimension the translator handles: SQ_RSRC_IMG_1D, 2D, 2D_ARRAY and 3D, for the formats 32_UINT and 32_SINT (dmask -0x1) and 32_32_UINT and 32_32_SINT (dmask 0x3, two results packed into one VGPR), with `image_load` and -`image_load_mip` (mip 0). - -Each lane reads one texel. Per texel the kernel stores four words: - 0 image_load without d16, x channel the control: must be the staged word, or the texture is laid out wrong - 1 image_load d16 the destination VGPR seeded with 0x5a5a5a5a first - 2 image_load_mip d16, mip 0 the same, through the other form - 3 image_load without d16, y channel (two-channel formats; the control for y, else the seed) -Every d16 result is compared with three rules for each 32-bit input w: - trunc the low 16 bits of w (what the translator did before it saturated) - sat_u min(w, 0xffff), w unsigned - sat_s w as a signed int clamped to [-32768, 32767], its low 16 bits -and, for one-channel formats, the high half: kept (0x5a5a, as docs/design.md records for 2D) or something else. - -The texture rides in the kernel's code after s_endpgm, as tools/hw_oracle/tsharp.py does for 2D, in a linear -layout whose rows are 256 bytes (64 R32 texels, 32 R32G32 texels), so the layout does not depend on how the T# -states the pitch. GFX10 only (RDNA1 and RDNA2: the T# layout); another family -exits 77. - -Usage: - python -I tools/image_d16_probe.py [--dims 1d,2d,2d_array,3d] [--formats r32_uint,...] [--json out.json] - python -I tools/image_d16_probe.py --self-test # the rules, T# words and kernels, no GPU - -Exit 0 when the sweep ran (which rule the hardware follows is a finding, not a failure), 1 when image_load and -image_load_mip disagree, 2 on a harness, CLI, or report write error (a control word did not read back), 77 when the -hardware oracle is unavailable or the GPU is not GFX10. Nothing here reads game files. -""" -import argparse -import json -import os -import sys - -sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) - -SEED = 0x5A5A5A5A -SENTINEL = 0xDEAD0000 -POISON = 0xBAADF00D -ROW_BYTES = 256 - -# Dimension -> (T# TYPE, MIMG dim name, coordinate count, texture extent as (height, depth or layers)). -DIMS = { - "1d": (8, "SQ_RSRC_IMG_1D", 1, (1, 1)), - "2d": (9, "SQ_RSRC_IMG_2D", 2, (2, 1)), - "2d_array": (13, "SQ_RSRC_IMG_2D_ARRAY", 3, (2, 3)), - "3d": (10, "SQ_RSRC_IMG_3D", 3, (2, 3)), -} -# Format -> (GFX10 FORMAT code, channels, signed). Codes from tools/gfx10_formats.json. -FORMATS = { - "r32_uint": (20, 1, False), - "r32_sint": (21, 1, True), - "r32g32_uint": (62, 2, False), - "r32g32_sint": (63, 2, True), -} -# Values that tell the rules apart, then a few that every rule maps alike. -EDGES = [0x00000000, 0x00000001, 0x00007FFE, 0x00007FFF, 0x00008000, 0x00008001, 0x0000FFFE, 0x0000FFFF, - 0x00010000, 0x00010001, 0x00012345, 0x0001FFFF, 0x7FFFFFFF, 0x80000000, 0x80000001, 0xFFFF7FFF, - 0xFFFF8000, 0xFFFF8001, 0xFFFFFFFE, 0xFFFFFFFF, 0x12348765, 0xDEAD5A5A, 0x00004321, 0xFFFFC000] - - -def rules(w): - """The 16-bit result of each candidate rule for the 32-bit input w.""" - s = w - (1 << 32) if w & 0x80000000 else w - return {"trunc": w & 0xFFFF, "sat_u": min(w, 0xFFFF), "sat_s": max(-32768, min(32767, s)) & 0xFFFF} - - -def texel_values(fmt, count): - """The staged 32-bit words, `channels` per texel: EDGES first, then a fixed mixing sequence.""" - channels = FORMATS[fmt][1] - out, x = [], 0x9E3779B9 - for i in range(count * channels): - if i < len(EDGES): - out.append(EDGES[i]) - else: - x = (x * 1103515245 + 12345) & 0xFFFFFFFF - out.append(x ^ (x >> 7) if i % 3 else EDGES[i % len(EDGES)]) - return [tuple(out[t * channels:(t + 1) * channels]) for t in range(count)] - - -def geometry(dim, fmt): - """(width, height, depth or layers, texel count) of the probe's texture.""" - channels = FORMATS[fmt][1] - width = ROW_BYTES // (4 * channels) - height, depth = DIMS[dim][3] - return width, height, depth, width * height * depth - - -def image_words(dim, fmt): - """The 8 words of a linear, one-mip GFX10.3 T# with the base address left zero (the kernel adds it). - Field positions as runtime/src/gfx10_descriptors.h lists them; a 1D or 2D image carries its pitch - 1 in WORD4 - DEPTH (GFX10.3 linear), an array its last layer and a 3D image its depth - 1.""" - kind, _, _, _ = DIMS[dim] - code = FORMATS[fmt][0] - width, height, depth, _ = geometry(dim, fmt) - w, h = width - 1, height - 1 - word1 = (code << 20) | ((w & 3) << 30) - word2 = ((w >> 2) & 0xFFF) | (h << 14) | (1 << 31) # RESOURCE_LEVEL, 1 on GFX10 - word3 = (4 | 5 << 3 | 6 << 6 | 7 << 9) | (kind << 28) # X Y Z W, levels 0..0, linear - word4 = (width - 1) if dim in ("1d", "2d") else (depth - 1) # pitch is width: rows are exactly 256 bytes - word5 = 4 << 20 # PERF_MOD, as Mesa writes it - return [0, word1, word2, word3, word4, word5, 0, 0] - - -def texture_bytes(dim, fmt): - data = bytearray() - for texel in texel_values(fmt, geometry(dim, fmt)[3]): - for word in texel: - data += word.to_bytes(4, "little") - return bytes(data) - - -def _longs(data): - words = [int.from_bytes(data[i:i + 4], "little") for i in range(0, len(data), 4)] - return [f" .long {', '.join(f'0x{w:08x}' for w in words[i:i + 8])}" for i in range(0, len(words), 8)] - - -def kernel_lines(dim, fmt, uid=0): - """A raw kernel (asm.Kernel(..., raw=True): s[2:3] the output, v0 the lane), one texel per lane.""" - _, dim_name, ncoord, _ = DIMS[dim] - width, height, _, count = geometry(dim, fmt) - channels = FORMATS[fmt][1] - t = image_words(dim, fmt) - log2w, log2wh = width.bit_length() - 1, (width * height).bit_length() - 1 - addr = "v2" if ncoord == 1 else f"v[2:{1 + ncoord}]" - mip = f"v[2:{2 + ncoord}]" - d16_mask = "0x1" if channels == 1 else "0x3" - out = ["s_getpc_b64 s[4:5]", f".Lpc{uid}:", f"s_add_u32 s4, s4, .Ltex{uid}-.Lpc{uid}", "s_addc_u32 s5, s5, 0", - "s_and_b32 s6, s4, 255", "s_lshr_b64 s[4:5], s[4:5], 8", "s_mov_b32 s8, s4", "s_and_b32 s9, s5, 255", - f"s_or_b32 s9, s9, 0x{t[1]:08x}"] - out += [f"s_mov_b32 s{8 + i}, 0x{t[i]:08x}" for i in range(2, 8)] - out += [f"v_and_b32 v2, {width - 1}, v0", - f"v_lshrrev_b32 v3, {log2w}, v0", - f"v_and_b32 v3, {height - 1}, v3", - f"v_lshrrev_b32 v4, {log2wh}, v0", - f"v_mov_b32 v{2 + ncoord}, 0"] # the mip of image_load_mip (or unused) - if ncoord == 1: - out.append("v_mov_b32 v4, 0") - out += [f"v_mov_b32 v8, 0x{SENTINEL:08x}", f"v_mov_b32 v9, 0x{SEED:08x}", f"v_mov_b32 v10, 0x{SEED:08x}", - f"v_mov_b32 v11, 0x{SEED:08x}", - "s_cmp_lg_u32 s6, 0", f"s_cbranch_scc0 .Lok{uid}"] - out += [f"v_mov_b32 v{8 + i}, 0x{POISON:08x}" for i in range(4)] - out += [f"s_branch .Lst{uid}", f".Lok{uid}:", - f"image_load v8, {addr}, s[8:15] dmask:0x1 dim:{dim_name} unorm", - f"image_load v9, {addr}, s[8:15] dmask:{d16_mask} dim:{dim_name} unorm d16", - f"image_load_mip v10, {mip}, s[8:15] dmask:{d16_mask} dim:{dim_name} unorm d16"] - if channels == 2: - out.append(f"image_load v11, {addr}, s[8:15] dmask:0x2 dim:{dim_name} unorm") - out += ["s_waitcnt vmcnt(0)", f".Lst{uid}:", "v_lshlrev_b32 v6, 4, v0", "global_store_b128 v6, v[8:11], s[2:3]", - "s_endpgm", ".p2align 8", f".Ltex{uid}:"] - if count > 1024: - raise ValueError("one lane per texel needs at most 1024 texels") - return out + _longs(texture_bytes(dim, fmt)) - - -def classify(dim, fmt, words): - """Compare one kernel's output (4 words per texel) with the rules.""" - channels = FORMATS[fmt][1] - staged = texel_values(fmt, geometry(dim, fmt)[3]) - entry = {"texels": len(staged), "control": [], "forms": {}} - forms = {"image_load": 1, "image_load_mip": 2} - agree = {f: {r: 0 for r in ("trunc", "sat_u", "sat_s")} for f in forms} - high = {f: {} for f in forms} - first_off = {f: [] for f in forms} - for i, texel in enumerate(staged): - got = words[4 * i:4 * i + 4] - if got[0] != texel[0]: - entry["control"].append(f"texel {i}: x read back 0x{got[0]:08x}, staged 0x{texel[0]:08x}") - if channels == 2 and got[3] != texel[1]: - entry["control"].append(f"texel {i}: y read back 0x{got[3]:08x}, staged 0x{texel[1]:08x}") - for form, k in forms.items(): - lo, hi = got[k] & 0xFFFF, got[k] >> 16 - for r in agree[form]: - want = rules(texel[0])[r] - ok = lo == want - if channels == 2: - ok = ok and hi == rules(texel[1])[r] - agree[form][r] += ok - if channels == 1: - key = "kept" if hi == SEED >> 16 else f"0x{hi:04x}" - high[form][key] = high[form].get(key, 0) + 1 - if len(first_off[form]) < 4 and not any( - (lo == rules(texel[0])[r]) for r in ("sat_u", "sat_s")): - first_off[form].append({"in": [f"0x{v:08x}" for v in texel], "got": f"0x{got[k]:08x}"}) - for form in forms: - entry["forms"][form] = {"match": agree[form], "high_half": high[form] or "n/a (two channels)", - "first_off": first_off[form]} - entry["forms_differ"] = sum(words[4 * i + 1] != words[4 * i + 2] for i in range(len(staged))) - return entry - - -def self_test(): - """The rules on the edge values, the T# fields and the kernels, without a GPU.""" - fails = [] - - def check(cond, what): - if not cond: - fails.append(what) - - check(rules(0x00012345) == {"trunc": 0x2345, "sat_u": 0xFFFF, "sat_s": 0x7FFF}, "rules of 0x12345") - check(rules(0xFFFF8000) == {"trunc": 0x8000, "sat_u": 0xFFFF, "sat_s": 0x8000}, "rules of -32768") - check(rules(0x80000000) == {"trunc": 0x0000, "sat_u": 0xFFFF, "sat_s": 0x8000}, "rules of INT_MIN") - check(rules(0x00007FFF) == {"trunc": 0x7FFF, "sat_u": 0x7FFF, "sat_s": 0x7FFF}, "rules of 0x7fff") - # the edges tell every pair of rules apart, so a match count says which rule the hardware follows - for a in ("trunc", "sat_u", "sat_s"): - for b in ("trunc", "sat_u", "sat_s"): - if a < b: - check(any(rules(w)[a] != rules(w)[b] for w in EDGES), f"no edge separates {a} from {b}") - for dim in DIMS: - for fmt in FORMATS: - width, height, depth, count = geometry(dim, fmt) - check(width * 4 * FORMATS[fmt][1] == ROW_BYTES, f"{dim} {fmt}: a row is not 256 bytes") - t = image_words(dim, fmt) - check(t[3] >> 28 == DIMS[dim][0], f"{dim} {fmt}: TYPE") - check((t[1] >> 20) & 0x1FF == FORMATS[fmt][0], f"{dim} {fmt}: FORMAT") - check(((t[1] >> 30) | ((t[2] & 0xFFF) << 2)) + 1 == width, f"{dim} {fmt}: WIDTH") - check(((t[2] >> 14) & 0x3FFF) + 1 == height, f"{dim} {fmt}: HEIGHT") - lines = kernel_lines(dim, fmt) - check(sum(ln.startswith("image_load") for ln in lines) == 2 + FORMATS[fmt][1], f"{dim} {fmt}: loads") - check(all(DIMS[dim][1] in ln for ln in lines if ln.startswith("image_load")), f"{dim} {fmt}: dim") - check(len(texture_bytes(dim, fmt)) == count * 4 * FORMATS[fmt][1], f"{dim} {fmt}: texture size") - # a fake GPU that saturates: every texel matches sat_s or sat_u, and the controls hold - signed = FORMATS[fmt][2] - fake = [] - for texel in texel_values(fmt, count): - r = [rules(v)["sat_s" if signed else "sat_u"] for v in texel] - d16 = r[0] | ((r[1] << 16) if len(r) == 2 else SEED & 0xFFFF0000) - fake += [texel[0], d16, d16, texel[1] if len(texel) == 2 else SEED] - e = classify(dim, fmt, fake) - rule = "sat_s" if signed else "sat_u" - check(not e["control"] and e["forms"]["image_load"]["match"][rule] == count and e["forms_differ"] == 0, - f"{dim} {fmt}: the saturating fake does not match {rule}") - check(e["forms"]["image_load"]["match"]["trunc"] < count, f"{dim} {fmt}: trunc not told apart") - for f in fails: - print("FAIL:", f) - print(f"self-test: {'ok' if not fails else f'{len(fails)} failure(s)'}") - return 1 if fails else 0 - - -def validate_json_path(path): - """Return an error string if `path` cannot be used as a --json output file, or None.""" - if not path or not path.strip(): - return "--json path must not be empty" - if "\x00" in path: - return "--json path contains a NUL byte" - if path.endswith(os.sep) or (os.altsep and path.endswith(os.altsep)) or os.path.isdir(path): - return f"--json path is a directory: {path}" - cur = os.path.dirname(os.path.abspath(path)) - while cur: - if os.path.isdir(cur): - break - if os.path.lexists(cur): - return f"--json parent is not a directory: {cur}" - nxt = os.path.dirname(cur) - if nxt == cur: - break - cur = nxt - return None - - -def write_json_report(path, report): - """Create missing parent directories and write `report` as LF-terminated JSON, or return an error string.""" - parent = os.path.dirname(os.path.abspath(path)) - if parent: - try: - os.makedirs(parent, exist_ok=True) - except OSError as e: - return f"cannot create directory for --json {path}: {e.strerror or e}" - try: - with open(path, "w", encoding="utf-8", newline="\n") as f: - json.dump(report, f, indent=1) - except OSError as e: - return f"cannot write --json {path}: {e.strerror or e}" - return None - - -def main(argv=None): - ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) - ap.add_argument("--dims", default=",".join(DIMS)) - ap.add_argument("--formats", default=",".join(FORMATS)) - ap.add_argument("--json", help="write the per-case counts here") - ap.add_argument("--hw-arch") - ap.add_argument("--self-test", action="store_true") - a = ap.parse_args(argv) - if a.self_test: - return self_test() - dims = [d for d in a.dims.split(",") if d] - fmts = [f for f in a.formats.split(",") if f] - bad = [d for d in dims if d not in DIMS] + [f for f in fmts if f not in FORMATS] - if bad or not dims or not fmts: - ap.error("unknown or empty: " + ", ".join(bad or ["--dims/--formats"])) - if a.json is not None: - err = validate_json_path(a.json) - if err: - print(f"error: {err}", file=sys.stderr) - return 2 - from hw_oracle import asm, runner - try: - oracle = runner.open_oracle(arch=a.hw_arch) - except runner.Unavailable as e: - print(f"hardware oracle unavailable: {e}") - return 77 - rc = 0 - try: - if asm.family(oracle.arch) != "gfx10": - print(f"hardware oracle unavailable: {oracle.arch} is not GFX10; the T# here is GFX10's (RDNA2)") - return 77 - print(f"hardware oracle: {oracle.device}") - report = {"device": str(oracle.device), "arch": oracle.arch, "cases": {}} - cases = [(d, f) for d in dims for f in fmts] - kernels = [] - for uid, (d, f) in enumerate(cases): - count = geometry(d, f)[3] - kernels.append(asm.Kernel(kernel_lines(d, f, uid), 32, count, count * 4, raw=True)) - for (d, f), got in zip(cases, oracle.run(kernels)): - name = f"{d} {f}" - if isinstance(got, str): - print(f"harness error: {name}: {got}") - rc = 2 - continue - e = classify(d, f, got) - report["cases"][name] = e - if e["control"]: - rc = 2 - for c in e["control"][:4]: - print(f"harness error: {name}: {c}") - if e["forms_differ"] and rc != 2: - rc = 1 - for form, s in e["forms"].items(): - m = ", ".join(f"{r} {k}/{e['texels']}" for r, k in s["match"].items()) - hh = s["high_half"] if isinstance(s["high_half"], str) else \ - ", ".join(f"{k} {v}" for k, v in s["high_half"].items()) - print(f"{name:<18} {form:<15} {m}; high half: {hh}") - if e["forms_differ"]: - print(f"{name}: image_load and image_load_mip differ on {e['forms_differ']} texels") - except RuntimeError as e: - print(f"harness error: {e}") - return 2 - finally: - oracle.close() - if a.json is not None: - err = write_json_report(a.json, report) - if err: - print(f"error: {err}", file=sys.stderr) - return 2 - return rc - - -if __name__ == "__main__": - try: - sys.stdout.reconfigure(errors="replace") - except (AttributeError, ValueError, OSError): - pass - sys.exit(main()) diff --git a/tools/image_fuzz.py b/tools/image_fuzz.py deleted file mode 100644 index a4379fa50..000000000 --- a/tools/image_fuzz.py +++ /dev/null @@ -1,703 +0,0 @@ -r"""Differential fuzzer for the translator's image path, starting with `image_load` (standard library only). - -Each case is a hand-written RDNA2 pixel shader that reads one texel with `image_load` and exports it to -`mrt0`. It runs on the GPU through `runtime/test/vk_image_fuzz.cpp` against a synthetic texture of a chosen -format, and every RGBA32F pixel is compared with an independent CPU oracle that models the RDNA2 texel fetch -for that T# format. A texel fetch is a memory read: no filtering, no borders, no LOD selection. - -What this covers today: 2D `image_load`, nonzero `dmask` values, `R8G8B8A8_UNORM`, `R16G16B16A16_SFLOAT`, -`R32G32B32A32_SFLOAT` and `R32_SFLOAT`, at sizes that divide the 64x64 draw (8/16/32/64), every texel read -at least once. - -Integer coverage uses 8-bit UINT/SINT sampled images (the translator reads them through uint/sint aliases of the -sampled array) and converts loaded integers to exactly representable floats. -Not covered yet: wider integer formats, mips, 1D/2D-array/3D/cube, `image_sample`/`gather` with filters and borders, and texel -offsets with `VK_KHR_maintenance8`. - -Oracles (--oracle translator|hw|translator,hw): translator (default) is the path above. hw runs the same fetches as raw -compute kernels natively on the AMD GPU through tools/hw_oracle/ (docs/shader_validation.md, "Hardware oracle for the -image fetches"): a linear texture in device memory, a T# built for the GPU's family (hw_oracle/tsharp.py: GFX11 on -gfx11xx, GFX10 on gfx103x), `image_load ... dmask:.. dim:SQ_RSRC_IMG_2D unorm` for every texel, every result register -stored and compared word for word with this file's CPU model. It tests the MODEL (and, with translator,hw, shows what -the translator did on a case the hardware disagrees with). A local gfx1150 is RDNA3.5, not RDNA2: a match supports the -model, it does not prove RDNA2. --negative-control checks that deliberately wrong models and a wrong T# FORMAT are caught. - -Usage: - python -I tools/image_fuzz.py [--programs N] [--seed S] [--build DIR] [--work DIR] [--show] - python -I tools/image_fuzz.py --oracle hw [--programs N] [--seed S] [--negative-control] - python -I tools/image_fuzz.py --self-test - -Exit code: 0 when every case matches, 1 on a mismatch, 2 on a setup or harness error, 77 when --oracle hw was asked -for and the hardware oracle's tools or GPU are missing. Nothing here reads game files. -""" -import argparse -import os -import random -import re -import signal -import struct -import subprocess -import sys -import tempfile - -ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) -TOOLS = os.path.join(ROOT, "tools") -SHADERS = os.path.join(ROOT, "runtime", "test", "shaders") -TRANSLATOR = os.path.join(TOOLS, "rdna2spirv.py") - -sys.path.insert(0, TOOLS) -sys.path.insert(0, SHADERS) -import mc_command # noqa: E402 -from compute_fixture import find_test_program # noqa: E402 -from hw_oracle import asm as hw_asm, tsharp # noqa: E402 - -HARNESS = "vk_image_fuzz" -DRAW = 64 # the harness draws a 64x64 full-screen triangle - -# name -> (Vulkan format for the spec and the image, GFX10 FORMAT code for T# word 1, bytes per texel, model) -FORMATS = { - "R8G8B8A8_UNORM": ("R8G8B8A8_UNORM", 56, 4, "unorm8"), - "R16G16B16A16_SFLOAT": ("R16G16B16A16_SFLOAT", 71, 8, "half4"), - "R32G32B32A32_SFLOAT": ("R32G32B32A32_SFLOAT", 77, 16, "float4"), - "R32_SFLOAT": ("R32_SFLOAT", 22, 4, "float1"), - "R8G8B8A8_UINT": ("R8G8B8A8_UINT", 60, 4, "uint8"), - "R8G8B8A8_SINT": ("R8G8B8A8_SINT", 61, 4, "sint8"), -} -SIZES = (8, 16, 32, 64) -# The default run reaches only the first two masks. Use a gap to check that selected components pack down. -DMASKS = (0xf, 0x5, *range(1, 0x5), *range(0x6, 0xf)) -STDERR_TAIL = 20 # lines of the harness's output a failure prints - -# Windows reports a crash as an NTSTATUS exit code (unsigned); the ones a driver crash tends to end with -NTSTATUS = { - 0xC0000005: "access violation", - 0xC000001D: "illegal instruction", - 0xC0000094: "integer divide by zero", - 0xC00000FD: "stack overflow", - 0xC0000374: "heap corruption", - 0xC0000409: "stack buffer overrun", -} - - -def assemble(asm: str, name: str, work: str) -> None: - """Assemble with llvm-mc like runtime/test/shaders/build.py, into work/disasm/.s.""" - cmd = mc_command.mc_command() + ["-triple=amdgcn--amdpal", "-mcpu=gfx1013", "-show-encoding"] - r = mc_command.run(cmd, input=asm, capture_output=True, text=True) - if r.returncode or "error:" in r.stderr: - raise SystemExit(f"llvm-mc rejected {name}:\n{r.stderr}") - code = "".join(line for line in r.stdout.splitlines(keepends=True) - if not line.lstrip().startswith(".")) - disasm = os.path.join(work, "disasm") - os.makedirs(disasm, exist_ok=True) - with open(os.path.join(disasm, name + ".s"), "w", encoding="utf-8", newline="\n") as f: - f.write(f"; {name} generated by tools/image_fuzz.py\n{code}") - with open(os.path.join(work, name + ".dxbc"), "wb") as f: - f.write(bytes(32)) # chunk count 0: no signatures, the stage comes from the name - - -def pc_tail_env() -> bool: - """True when LEONIDA_PC_TAIL_UBO asks for rdna2spirv.py --pc-tail-ubo (128-byte push constants).""" - return (os.environ.get("LEONIDA_PC_TAIL_UBO") or "").strip().lower() in ("1", "true", "yes", "on") - - -def translate(work: str, pc_tail: bool = False) -> str: - """Translate work/disasm into work/spirv and return that directory.""" - spirv = os.path.join(work, "spirv") - cmd = [sys.executable, "-I", TRANSLATOR, os.path.join(work, "disasm"), "--out", spirv] - if pc_tail: - cmd.append("--pc-tail-ubo") - r = subprocess.run(cmd, capture_output=True, text=True) - if r.returncode: - raise SystemExit(f"translator failed:\n{r.stdout}\n{r.stderr}") - # The batch translator can exit successfully even when an individual shader is rejected. - missing = [name for name in ("vs_ids.spv", "ps_image_load.spv") if not os.path.isfile(os.path.join(spirv, name))] - if missing: - raise SystemExit(f"translator did not emit {', '.join(missing)}:\n{r.stdout}\n{r.stderr}") - return spirv - - -SENTINELS = (1.0, 2.0, 3.0, 4.0) - - -def masked_components(rgba, dmask): - """Selected R/G/B/A components occupy consecutive VGPRs; remaining VGPRs keep their sentinels.""" - selected = [rgba[c] for c in range(4) if dmask & (1 << c)] - return selected + list(SENTINELS[len(selected):]) - - -def pixel_shader(width: int, height: int, dmask: int = 0xf, model: str = "") -> str: - """image_load of a 2D texture at the texel under each pixel, exported to mrt0.""" - count = dmask.bit_count() - dst = "v4" if count == 1 else f"v[4:{3 + count}]" - init = "".join(f"\tv_mov_b32_e32 v{reg}, {value}\n" for reg, value in enumerate(SENTINELS, 4)) - convert = "" - if model in ("uint8", "sint8"): - kind = "u32" if model == "uint8" else "i32" - convert = "".join(f"\tv_cvt_f32_{kind}_e32 v{r}, v{r}\n" for r in range(4, 4 + count)) - return ( - "; image_load probe generated by tools/image_fuzz.py\n" - "\tv_interp_p1_f32_e32 v2, v0, attr0.x\n" - "\tv_interp_p2_f32_e32 v2, v1, attr0.x\n" - "\tv_interp_p1_f32_e32 v3, v0, attr0.y\n" - "\tv_interp_p2_f32_e32 v3, v1, attr0.y\n" - f"\tv_mul_f32_e32 v2, {float(width)}, v2\n" - f"\tv_mul_f32_e32 v3, {float(height)}, v3\n" - "\tv_cvt_u32_f32_e32 v2, v2\n" - "\tv_cvt_u32_f32_e32 v3, v3\n" - f"{init}" - f"\timage_load {dst}, v[2:3], s[8:15] dmask:0x{dmask:x} dim:SQ_RSRC_IMG_2D\n" - "\ts_waitcnt vmcnt(0)\n" - f"{convert}" - "\texp mrt0 v4, v5, v6, v7 done vm\n" - "\ts_endpgm\n" - ) - - -def make_texels(fmt_name: str, width: int, height: int, rng: random.Random): - """Raw texel bytes and the T# words (the key; word 1 carries FORMAT for the translator).""" - vk_format, code, bpp, model = FORMATS[fmt_name] - # A fifth of the values are specials: a fetch is a memory read, so NaN/inf/+-0/denormal payloads must - # survive it unchanged (the comparison treats every NaN as equal to every NaN). - specials = [0.0, -0.0, float("inf"), float("-inf"), float("nan"), 1e-40, -1e-40] - raw = bytearray() - for _ in range(width * height): - if model in ("unorm8", "uint8", "sint8"): - raw += bytes([rng.randrange(256), rng.randrange(256), rng.randrange(256), rng.randrange(256)]) - elif model == "half4": - for _ in range(4): - value = rng.choice([struct.unpack(" float: - """The float32 the GPU gets; the UNORM divide happens in float, not in Python's double.""" - return struct.unpack(" list: - """Every texel as RGBA floats, the way an RDNA2 image_load of that format reads it.""" - _, _, bpp, model = FORMATS[fmt_name] - texel = [] - for i in range(width * height): - chunk = texels[i * bpp:(i + 1) * bpp] - if model == "unorm8": - texel.append([f32(chunk[c] / 255.0) for c in range(4)]) - elif model in ("uint8", "sint8"): - texel.append(list(struct.unpack("<4B" if model == "uint8" else "<4b", chunk))) - elif model == "half4": - texel.append([struct.unpack_from(" tuple: - """The texel the generated shader reads for pixel (x, y): floor(uv * size) with uv = (pixel + 0.5) / 64.""" - return (x * width) // DRAW, (y * height) // DRAW - - -def read_rgba(path: str) -> list: - with open(path, "rb") as f: - data = f.read() - want = DRAW * DRAW * 16 - if len(data) != want: - raise SystemExit(f"{path}: {len(data)} bytes, expected {want}") - return list(struct.unpack(f"<{DRAW * DRAW * 4}f", data)) - - -def same_component(a: float, b: float) -> bool: - """Bit equality of two f32 values, except that any NaN matches any NaN. - - Ordinary float equality would hide a wrong binding that returns -0 where +0 is expected (and the reverse): - +0.0 == -0.0 is true in Python, but the 32-bit words differ and a texture fetch must preserve the sign. - """ - packed_a, packed_b = struct.pack(" float conversion is the -# driver's, not the translated code's. RDNA2 returns the correctly rounded c / 255 (--oracle hw checks that bit for -# bit); llvmpipe multiplies by an f32 1/255 instead, one ulp above it for 126 of the 256 values (27: 0x3dd8d8da, not -# 0x3dd8d8d9), and a run stops at its first mismatch, so on llvmpipe no case after the first R8G8B8A8_UNORM one ran. -# A wrong format, swizzle, binding or dmask is never that close (c / 256 is ~0.4% off), so the translator oracle -# accepts one ulp on a UNORM8 texel component and counts how often it needed to. -UNORM8_ULPS = 1 -unorm8_near = 0 # UNORM8 components accepted one ulp from the exact quotient, for the summary - - -def near_component(a: float, b: float, ulps: int) -> bool: - """Finite f32 values of the same sign at most `ulps` units in the last place apart.""" - bits_a = struct.unpack(" list: - global unorm8_near - expected = oracle(fmt_name, texels, width, height) - # Only the components the texel supplies; the registers dmask leaves unwritten must keep their sentinels exactly. - near_ok = dmask.bit_count() if FORMATS[fmt_name][3] == "unorm8" else 0 - problems = [] - for y in range(DRAW): - for x in range(DRAW): - tx, ty = texel_of_pixel(x, y, width, height) - want = masked_components(expected[ty * width + tx], dmask) - base = (y * DRAW + x) * 4 - have = got[base:base + 4] - exact = [same_component(have[c], want[c]) for c in range(4)] - if all(exact): - continue - if all(exact[c] or (c < near_ok and near_component(have[c], want[c], UNORM8_ULPS)) for c in range(4)): - unorm8_near += exact.count(False) - continue - problems.append((x, y, want, have)) - if len(problems) >= 6: - return problems - return problems - - -def exit_status(returncode: int) -> str: - """How the harness ended, for a failure line: "exit 1", "killed by SIGSEGV", "exit 0xc0000005 (access violation)".""" - if returncode < 0: # POSIX: subprocess reports a fatal signal as its negative number - try: - name = signal.Signals(-returncode).name - except ValueError: - name = f"signal {-returncode}" - return f"killed by {name}" - status = returncode & 0xFFFFFFFF - if status >= 0xC0000000: - return f"exit 0x{status:08x}" + (f" ({NTSTATUS[status]})" if status in NTSTATUS else "") - return f"exit {returncode}" - - -def run_case(fmt_name, width, height, rng, work, build, keep, show, dmask=0xf, data=None, pc_tail=False) -> bool: - """data: the (texel bytes, T# words) to use instead of drawing them from rng (main draws all cases up front, so - the translator and the hardware oracle see the same textures).""" - vk_format, _, _, model = FORMATS[fmt_name] - asm = pixel_shader(width, height, dmask, model) - assemble(asm, "ps_image_load", work) - if not os.path.exists(os.path.join(work, "disasm", "vs_ids.s")): - with open(os.path.join(SHADERS, "vs_ids.asm"), encoding="utf-8") as f: - assemble(f.read(), "vs_ids", work) - spirv = translate(work, pc_tail=True) if pc_tail else translate(work) - texels, tsharp = data if data is not None else make_texels(fmt_name, width, height, rng) - texels_path = os.path.join(work, "texels.bin") - with open(texels_path, "wb") as f: - f.write(texels) - spec_path = os.path.join(work, "spec.txt") - with open(spec_path, "w", encoding="utf-8", newline="\n") as f: - f.write(f"width={width}\nheight={height}\nformat={vk_format}\ntexels={texels_path}\n" - f"tsharp={','.join(hex(w) for w in tsharp)}\n") - out_path = os.path.join(work, "out.raw") - harness = os.path.join(build, HARNESS + (".exe" if os.name == "nt" else "")) - if not os.path.exists(harness): - raise SystemExit(f"{harness} not found: build the runtime first " - f"(cmake --build --target {HARNESS})") - run_kw = {"capture_output": True, "text": True} - if pc_tail: - run_kw["env"] = dict(os.environ, LEONIDA_PC_TAIL_UBO="1") - r = subprocess.run([harness, os.path.join(spirv, "vs_ids.spv"), os.path.join(spirv, "ps_image_load.spv"), - out_path, spec_path], **run_kw) - if r.returncode == 77: # a device limit or missing feature, named on the harness's "unsupported:" line - why = next((ln for ln in f"{r.stdout}\n{r.stderr}".splitlines() if ln.startswith("unsupported:")), - "the device does not support the set") - print(f"{fmt_name} {width}x{height} dmask:0x{dmask:x}: SKIP ({why})") - return None - if r.returncode != 0: - status = exit_status(r.returncode) - stream, lines = "stderr", (r.stderr or "").strip().splitlines() - if not lines: - stream, lines = "stdout", (r.stdout or "").strip().splitlines() - reason = f"{HARNESS} {status}" + (f": {lines[-1]}" if lines else ", no output") - print(f"{fmt_name} {width}x{height} dmask:0x{dmask:x}: FAIL ({reason})") - if len(lines) > 1: - shown = lines[-STDERR_TAIL:] - print(f" {HARNESS} {stream}" + (f" (last {len(shown)} of {len(lines)} lines)" - if len(shown) < len(lines) else "") + ":") - for line in shown: - print(f" {line}") - return False - got = read_rgba(out_path) - problems = compare(fmt_name, texels, width, height, got, dmask) - if not problems: - if show: - print(f"{fmt_name} {width}x{height} dmask:0x{dmask:x}: pass (every pixel matches)") - return True - print(f"{fmt_name} {width}x{height} dmask:0x{dmask:x}: {len(problems)}+ mismatched pixels") - for x, y, want, have in problems: - print(f" pixel ({x}, {y}) texel ({texel_of_pixel(x, y, width, height)}): " - f"want {want} got {have}") - if keep: - print(f" case kept in {work} (spec.txt, ps_image_load.s, texels.bin, out.raw)") - return False - - -# ---- the hardware oracle ---- - -HW_CHUNK = 24 # kernels per assembled module: each carries its texture, up to 64 KB of data -WAVES = (32, 64) # alternated from case to case: a texel fetch must not depend on the wave size -FORMAT_ORDER = list(FORMATS) -_X, _Y, _Z, _W, _0, _1 = (tsharp.SEL_X, tsharp.SEL_Y, tsharp.SEL_Z, tsharp.SEL_W, tsharp.SEL_0, tsharp.SEL_1) -# DST_SEL per model. A one-channel format reads (r, 0, 0, 1): what the translator's image view gives it -# (format_swizzle in runtime/src/gfx10_descriptors.h) and what the CPU model says. -FORMAT_SWIZZLE = {"unorm8": (_X, _Y, _Z, _W), "half4": (_X, _Y, _Z, _W), "float4": (_X, _Y, _Z, _W), - "float1": (_X, _0, _0, _1), "uint8": (_X, _Y, _Z, _W), "sint8": (_X, _Y, _Z, _W)} - - -class Case: - """One fetch: a format, a texture size, a dmask and the texture bytes (drawn once, shared by every oracle).""" - - def __init__(self, index, fmt, width, height, dmask, data, wave): - self.index, self.fmt, self.width, self.height = index, fmt, width, height - self.dmask, self.data, self.wave = dmask, data, wave - - @property - def name(self): - return f"#{self.index} {self.fmt} {self.width}x{self.height} dmask:0x{self.dmask:x} wave{self.wave}" - - -def make_cases(programs, seed, formats): - """The cases of a run, drawn in the order main always used (width, height, then the texels of each case), so a - seed names the same textures whichever oracle runs them.""" - rng = random.Random(seed) - cases = [] - for i in range(programs): - fmt = formats[i % len(formats)] - width, height = rng.choice(SIZES), rng.choice(SIZES) - dmask = DMASKS[(i // len(formats)) % len(DMASKS)] - cases.append(Case(i, fmt, width, height, dmask, make_texels(fmt, width, height, rng), - WAVES[(i // len(formats)) % 2])) - return cases - - -# What the model gets wrong on purpose (--negative-control): each name switches one deliberate error on in -# expected_words, and the hardware words must then disagree with it somewhere. -PERTURB = set() -PERTURBATIONS = { - "unorm_256": "UNORM8 divides by 256 instead of 255", - "swap_rb": "red and blue swapped", - "sint_unsigned": "SINT8 read as unsigned", - "alpha_zero": "R32_SFLOAT missing alpha is 0, not 1", - "dmask_in_place": "dmask components stay in their own register instead of packing downwards", - "no_sentinels": "registers dmask does not write read as 0 instead of keeping their value", - "transpose": "texel (x, y) read as (y, x)", -} - - -def f32_bits(value: float) -> int: - return struct.unpack(" bool: - """Bit equality; for the float formats any NaN equals any NaN (payloads are not modelled).""" - if have == want: - return True - if model in ("uint8", "sint8"): - return False - return all((x & 0x7F800000) == 0x7F800000 and x & 0x007FFFFF for x in (have, want)) - - -def compare_hw(case, got): - """Mismatches (texel x, y, register, want, have) of one case's output words against the model.""" - want = expected_words(case.fmt, case.data[0], case.width, case.height, case.dmask) - model = FORMATS[case.fmt][3] - problems = [] - if len(got) != len(want): - return [(-1, -1, -1, len(want), len(got))] - for i, (h, w) in enumerate(zip(got, want)): - if not word_equal(h, w, model): - texel = i // 4 - problems.append((texel % case.width, texel // case.width, i % 4, w, h)) - return problems - - -def hw_kernel(arch, case, fmt_override=None): - """The native kernel of a case (fmt_override: build the T# with another format's code, for the negative control).""" - bpp = FORMATS[case.fmt][2] - texture = tsharp.lay_out(case.data[0], case.width, case.height, bpp) - lines = tsharp.kernel_lines(arch, case.index, fmt_override or case.fmt, case.width, case.height, bpp, - case.dmask, texture, FORMAT_SWIZZLE[FORMATS[case.fmt][3]]) - threads, _ = tsharp.lanes(case.width, case.height) - return hw_asm.Kernel(lines, case.wave, threads, case.width * case.height * 4, raw=True) - - -def run_hw(oracle, cases, a, quiet=False, fmt_override=None): - """Run every case natively and judge it against the model. Returns (stats, mismatching cases, {index: words}).""" - kernels = [hw_kernel(oracle.arch, c, fmt_override(c) if fmt_override else None) for c in cases] - stats = {} - failed, words = [], {} - for c, got in zip(cases, oracle.run(kernels)): - st = stats.setdefault(c.wave, {"cases": 0, "match": 0, "mismatch": 0, "rejected": 0}) - st["cases"] += 1 - if isinstance(got, str): - st["rejected"] += 1 - print(f"REJECTED {c.name} [hw]: {got}") - continue - if got and all(w == tsharp.POISON for w in got): - st["rejected"] += 1 - print(f"ERROR {c.name} [hw]: the texture in the kernel is not 256-byte aligned (every word is the poison)") - continue - words[c.index] = got - problems = compare_hw(c, got) - if not problems: - st["match"] += 1 - continue - st["mismatch"] += 1 - failed.append(c) - if quiet: - continue - print(f"MISMATCH {c.name} [hw]: {len(problems)} words; reproduce with --oracle hw --seed {a.seed} " - f"--programs {c.index + 1}") - for x, y, reg, want, have in problems[:a.max_report]: - print(f" texel ({x}, {y}) register {reg}: want 0x{want:08x} have 0x{have:08x}") - return stats, failed, words - - -def negative_control(oracle, cases, a): - """Every deliberately wrong model, and a kernel with the wrong T# FORMAT, must be caught by the hardware words: - the real model passes, each perturbed one has to mismatch on at least one case. Exit 0 when all are caught.""" - _, failed, words = run_hw(oracle, cases, a) - ran = [c for c in cases if c.index in words] - code = 1 if failed or not ran else 0 - print(f"unperturbed model: {len(failed)} of {len(ran)} cases mismatch") - for name, what in PERTURBATIONS.items(): - PERTURB.add(name) - try: - n = sum(bool(compare_hw(c, words[c.index])) for c in ran) - finally: - PERTURB.discard(name) - print(f"perturbation {name} ({what}): caught by {n} of {len(ran)} cases" + ("" if n else " <-- NOT CAUGHT")) - code = code or (0 if n else 1) - - def wrong_of(fmt): - return FORMAT_ORDER[(FORMAT_ORDER.index(fmt) + 1) % len(FORMAT_ORDER)] - _, bad, _ = run_hw(oracle, cases, a, quiet=True, fmt_override=lambda c: wrong_of(c.fmt)) - for fmt in dict.fromkeys(c.fmt for c in cases): - n_all = sum(c.fmt == fmt for c in cases) - n_bad = sum(c.fmt == fmt for c in bad) - print(f"wrong T# FORMAT ({fmt} built as {wrong_of(fmt)}): caught by {n_bad} of {n_all} cases" - + ("" if n_bad else " <-- NOT CAUGHT")) - code = code or (0 if n_bad else 1) - return code - - -def self_test() -> int: - """CPU-only: the oracle, the texel mapping and the generated shader without a GPU.""" - rng = random.Random(7) - for name, (vk, code, bpp, model) in FORMATS.items(): - width, height = 8, 8 - texels, tsharp = make_texels(name, width, height, rng) - assert len(texels) == width * height * bpp, name - assert tsharp[1] == code << 20, name - values = oracle(name, texels, width, height) - assert len(values) == width * height, name - assert all(len(v) == 4 for v in values), name - assert texel_of_pixel(0, 0, 8, 8) == (0, 0) - assert texel_of_pixel(63, 63, 8, 8) == (7, 7) - assert texel_of_pixel(63, 63, 64, 64) == (63, 63) - asm = pixel_shader(16, 8) - assert "\timage_load" in asm and "16.0" in asm and "8.0" in asm - print(f"image_fuzz self-test: ok ({len(FORMATS)} formats, {DRAW}x{DRAW} draw)") - return 0 - - - - -def run_translator(cases, a, work) -> tuple: - """The translator oracle over the cases. Returns (passed, failed, skipped, {case index: True/False/None}).""" - passed = failed = skipped = 0 - verdicts = {} - pc_tail = bool(getattr(a, "pc_tail_ubo", False)) - for c in cases: - if a.show: - print(f"[{c.index + 1}/{len(cases)}] {c.fmt} {c.width}x{c.height} (work {work})") - result = run_case(c.fmt, c.width, c.height, None, work, a.build, False, a.show, c.dmask, c.data, - pc_tail=pc_tail) - verdicts[c.index] = result - if result is None: - skipped += 1 - elif result: - passed += 1 - else: - failed += 1 - print(f" work dir kept: {work}") - break - return passed, failed, skipped, verdicts - - -def main() -> int: - ap = argparse.ArgumentParser(description="Differential fuzzer for the translator's image_load path") - ap.add_argument("--programs", type=int, default=8) - ap.add_argument("--seed", type=int, default=1) - # runtime/build, as docs/shader_validation.md builds it and lds_fuzz/valu_fuzz default to; a Visual Studio build's - # RelWithDebInfo/Release subfolder is found below. - ap.add_argument("--build", default=os.path.join(ROOT, "runtime", "build")) - ap.add_argument("--work", help="keep each run's generated files in a new subfolder here") - ap.add_argument("--show", action="store_true") - ap.add_argument("--formats", default=",".join(FORMATS)) - ap.add_argument("--oracle", default="translator", - help="comma-separated: translator (default; the shader through the translator and Vulkan), hw (the same " - "fetches as native kernels on the AMD GPU through tools/hw_oracle/; exit 77 when it is not " - "there) or translator,hw") - ap.add_argument("--hw-arch", default=None, help="GPU architecture to assemble for (default: detected)") - ap.add_argument("--negative-control", action="store_true", - help="hw: check that deliberately wrong models and a wrong T# FORMAT are caught by the hardware words") - ap.add_argument("--max-report", type=int, default=6, help="hw: mismatching words to print per case") - ap.add_argument("--pc-tail-ubo", action="store_true", - help="translate with rdna2spirv.py --pc-tail-ubo and run vk_image_fuzz with 128-byte push " - "constants (also set by LEONIDA_PC_TAIL_UBO=1)") - ap.add_argument("--self-test", action="store_true") - a = ap.parse_args() - a.pc_tail_ubo = a.pc_tail_ubo or pc_tail_env() - if a.self_test: - return self_test() - backends = tuple(dict.fromkeys(t.strip() for t in a.oracle.split(","))) - if not backends or any(t not in ("translator", "hw") for t in backends): - ap.error("--oracle takes translator, hw or translator,hw") - if a.negative_control and "hw" not in backends: - ap.error("--negative-control needs --oracle hw") - formats = [f.strip() for f in a.formats.split(",") if f.strip()] - if not formats: - ap.error("--formats must select at least one format") - unknown = [f for f in formats if f not in FORMATS] - if unknown: - print(f"unknown format(s): {', '.join(unknown)}; known: {', '.join(FORMATS)}", file=sys.stderr) - return 2 - if a.programs < 1: - print("--programs must be at least 1", file=sys.stderr) - return 2 - if a.max_report < 1: - print("--max-report must be at least 1", file=sys.stderr) - return 2 - if a.work: - # Reject a --work that is a file, or sits under one, before any fuzz work: os.makedirs would raise a - # FileExistsError traceback after the cases were built, and nothing here is retryable anyway. - probe = os.path.abspath(a.work) - while not os.path.lexists(probe): - parent = os.path.dirname(probe) - if parent == probe: - break - probe = parent - if os.path.lexists(probe) and not os.path.isdir(probe): - print(f"ERROR: --work is not a folder: {a.work}", file=sys.stderr) - return 2 - hw_oracle = None - if "hw" in backends: - from hw_oracle import runner - try: - hw_oracle = runner.open_oracle(arch=a.hw_arch) - fam = tsharp.check_arch(hw_oracle.arch) - except runner.Unavailable as e: - print(f"hardware oracle unavailable: {e}") - return 77 - except ValueError as e: - print(f"hardware oracle unavailable: {e}") - hw_oracle.close() - return 77 - hw_oracle.chunk = HW_CHUNK - print(f"hardware oracle: {hw_oracle.device} ({hw_oracle.arch}, {fam} T# layout)") - if fam == "gfx11": - print("note: GFX11 is RDNA3 or newer, not RDNA2: a match supports the model and does not prove RDNA2") - a.build = find_test_program(a.build, HARNESS) or a.build - cases = make_cases(a.programs, a.seed, formats) - code = 0 - verdicts = {} - try: - try: - parent = os.path.abspath(a.work) if a.work else None - if parent is not None: - os.makedirs(parent, exist_ok=True) - work = tempfile.mkdtemp(prefix="image_fuzz_", dir=parent) - except OSError as e: - print(f"ERROR: cannot create work directory: {e}", file=sys.stderr) - return 2 - print(f"work dir {work}") - if "translator" in backends: - passed, failed, skipped, verdicts = run_translator(cases, a, work) - summary = f"{passed}/{passed + failed} programs that ran match" - if failed: - summary += f"; {failed} mismatched" - if skipped: - summary += f"; {skipped} skipped" - if unorm8_near: - summary += (f"; {unorm8_near} R8G8B8A8_UNORM components one ulp from the exact c / 255 " - "(the driver's conversion)") - print("translator: " + summary) - code = 1 if failed else 0 - if hw_oracle: - if a.negative_control: - return max(code, negative_control(hw_oracle, cases, a)) - stats, failed_cases, _ = run_hw(hw_oracle, cases, a) - for wave, st in sorted(stats.items()): - print(f"image_load wave{wave} hw: " + ", ".join(f"{k} {v}" for k, v in st.items())) - if "translator" in backends: - for c in failed_cases: - seen = verdicts.get(c.index, "not run") - seen = {True: "matches the model", False: "mismatches the model", None: "was skipped"}.get(seen, seen) - print(f" {c.name}: hardware disagrees with the model; the translator {seen}") - if any(st["mismatch"] or st["rejected"] for st in stats.values()): - code = 1 - if sum(st["match"] for st in stats.values()) == 0: - code = max(code, 2) - finally: - if hw_oracle: - hw_oracle.close() - return code - - -if __name__ == "__main__": - try: # a redirected stdout is strict ANSI code page under -I; write '?' for what it cannot encode - sys.stdout.reconfigure(errors="replace") - except (AttributeError, ValueError, OSError): - pass - sys.exit(main()) diff --git a/tools/image_query_probe.py b/tools/image_query_probe.py deleted file mode 100644 index 29828f293..000000000 --- a/tools/image_query_probe.py +++ /dev/null @@ -1,370 +0,0 @@ -r"""What `image_get_resinfo` and `image_get_lod` return on an RDNA2 GPU (SHADER-388). Standard library only. - -docs/design.md ("Image atomics, size and LOD queries") left three answers unverified: resinfo's depth word for a 2D -image, the clamped LOD `image_get_lod` returns under a linear mip filter, and the order of u and v in the LOD query. -This probe runs both instructions natively (through tools/hw_oracle/) on hand-built descriptors and compares every -result word with the rules below. Neither instruction reads memory, so the T# has no texture behind it. - -image_get_resinfo, dmask 0xf, address VGPR = mip level (unsigned), T# with BASE_LEVEL b and LAST_LEVEL l: - n = l - b + 1 levels; past the last level (level >= n) width, height and depth are 0; otherwise - width = max(1, WIDTH >> (b + level)), height likewise, and the depth word is - 2D: 0, whatever T# WORD4 DEPTH holds (a linear GFX10.3 T# keeps its pitch there) - 2D array: max(1, (DEPTH + 1) >> (b + level)): the layer count is minified like a 3D depth - and the fourth word is n. -image_get_lod, dmask 0x3, 2D, S# MIN_LOD lo, MAX_LOD hi, LOD_BIAS s, n levels; one 2x2 quad of lanes whose u steps -by du across x and v by dv across y (so the LOD is log2(max(du * width, dv * height))): - VGPR 1 (raw) = that LOD + s - VGPR 0 (clamped) = 0 with MIP_FILTER none; else c = min(max(min(raw, hi), lo), n - 1) (lo wins over hi when - lo > hi, and the level count caps both), then floor(c + 0.5) with MIP_FILTER point (the level it would read, - ties up) and c with MIP_FILTER linear. -That is the definition of OpImageQueryLod / textureQueryLod (the level read, or a fraction between the two read). - -Every case runs in wave32 and wave64; every lane of a quad must agree. - -Usage: - python -I tools/image_query_probe.py [--waves 32,64] [--json out.json] - python -I tools/image_query_probe.py --self-test # the rules against values measured on gfx1036, no GPU - -Exit 0 when every word matches the rules, 1 on a mismatch (a finding: the rules above are wrong on this GPU), 2 on a -harness error or a --json report that cannot be written (the summary line still gives the result), 77 when the -hardware oracle is unavailable or the GPU is not GFX10 (the T# layout is GFX10's). -Nothing here reads game files. -""" -import argparse -import json -import math -import os -import stat -import struct -import sys -import tempfile - -HERE = os.path.dirname(os.path.abspath(__file__)) -if HERE not in sys.path: - sys.path.insert(0, HERE) -from file_mode import published_mode # noqa: E402 -from replace_retry import replace as replace_retry # noqa: E402 - -TYPE_2D, TYPE_2D_ARRAY = 9, 10 # SQ_RSRC_IMG_* in T# WORD3 [31:28] -DIMS = {TYPE_2D: "SQ_RSRC_IMG_2D", TYPE_2D_ARRAY: "SQ_RSRC_IMG_2D_ARRAY"} -MIP_NONE, MIP_POINT, MIP_LINEAR = 0, 1, 2 # SQ_TEX_MIP_FILTER in S# WORD2 [27:26] -SENTINEL = 0xDEAD0000 - - -def f2u(f): - return struct.unpack("= n: - return [0, 0, 0, n] - shift = base + level - w, h = max(1, width >> shift), max(1, height >> shift) - depth = 0 if typ == TYPE_2D else max(1, (depth_field + 1) >> shift) - return [w, h, depth, n] - - -def lod_model(lod, mip, lo, hi, bias, levels): - """(clamped, raw) that image_get_lod dmask:0x3 returns for a quad whose computed LOD is `lod`.""" - raw = lod + bias - if mip == MIP_NONE: - return 0.0, raw - c = min(max(min(raw, hi), lo), levels - 1) - return (math.floor(c + 0.5) if mip == MIP_POINT else c), raw - - -# ---- descriptors ---- - -def tsharp_words(arch, width, height, typ=TYPE_2D, depth_field=None, base=0, last=0): - """A GFX10 T# (tools/hw_oracle/tsharp.py's linear 2D one) with the type, levels and WORD4 DEPTH set. - depth_field None keeps what tsharp writes there (the pitch on GFX10.3).""" - from hw_oracle import tsharp - t = tsharp.image_words(arch, "R8G8B8A8_UNORM", width, height, 4) - t[3] = (t[3] & ~(0xF << 28) & ~(0xFF << 12)) | (typ << 28) | (base << 12) | (last << 16) - if depth_field is not None: - t[4] = (t[4] & ~0x1FFF) | depth_field - return t - - -def ssharp_words(mip, lo, hi, bias=0.0): - """A GFX10 S#: wrap, bilinear min/mag, MIP_FILTER mip, MIN_LOD/MAX_LOD (unsigned 4.8), LOD_BIAS (signed 5.8) - (runtime/src/gfx10_descriptors.h encode() has the same layout).""" - word1 = int(lo * 256) | int(hi * 256) << 12 - word2 = (int(bias * 256) & 0x3FFF) | 1 << 20 | 1 << 22 | mip << 26 - return [0, word1, word2, 0] - - -# ---- kernels ---- - -def resinfo_kernel(t, level, typ, wave): - from hw_oracle import asm - lines = [f"s_mov_b32 s{8 + i}, 0x{w:08x}" for i, w in enumerate(t)] - lines += [f"v_mov_b32 v{8 + i}, 0x{SENTINEL + i:08x}" for i in range(4)] - lines += [f"v_mov_b32 v2, {level}", - f"image_get_resinfo v[8:11], v2, s[8:15] dmask:0xf dim:{DIMS[typ]}", - "s_waitcnt vmcnt(0)", - "v_lshlrev_b32 v4, 4, v0", - "global_store_b128 v4, v[8:11], s[2:3]", - "s_endpgm"] - return asm.Kernel(lines, wave=wave, threads=1, words=4, raw=True) - - -def lod_kernel(t, s, du, dv, wave): - """One quad: lane i reads u = 0.5 + (i & 1) * du, v = 0.5 + (i >> 1) * dv. Each lane stores clamped, raw, u, v.""" - from hw_oracle import asm - lines = [f"s_mov_b32 s{8 + i}, 0x{w:08x}" for i, w in enumerate(t)] - lines += [f"s_mov_b32 s{16 + i}, 0x{w:08x}" for i, w in enumerate(s)] - lines += ["v_and_b32 v5, 1, v0", "v_lshrrev_b32 v6, 1, v0", "v_cvt_f32_u32 v5, v5", "v_cvt_f32_u32 v6, v6", - f"v_mul_f32 v2, 0x{f2u(du):08x}, v5", f"v_mul_f32 v3, 0x{f2u(dv):08x}, v6", - "v_add_f32 v2, 0.5, v2", "v_add_f32 v3, 0.5, v3", - f"v_mov_b32 v8, 0x{SENTINEL:08x}", f"v_mov_b32 v9, 0x{SENTINEL + 1:08x}", - "image_get_lod v[8:9], v[2:3], s[8:15], s[16:19] dmask:0x3 dim:SQ_RSRC_IMG_2D", - "s_waitcnt vmcnt(0)", - "v_mov_b32 v10, v2", "v_mov_b32 v11, v3", - "v_lshlrev_b32 v4, 4, v0", - "global_store_b128 v4, v[8:11], s[2:3]", - "s_endpgm"] - return asm.Kernel(lines, wave=wave, threads=4, words=16, raw=True) - - -# ---- cases ---- - -def resinfo_cases(): - """(name, width, height, type, DEPTH field or None, base, last, level).""" - out = [] - for w, h in ((16, 4), (64, 64)): - for depth in (None, 0, 5, 0x1FFF): - for level in (0, 1, 4, 5, 20): - out.append((f"2D {w}x{h} depth={depth} level={level}", w, h, TYPE_2D, depth, 0, 4, level)) - for base, last in ((1, 4), (2, 3)): - for level in (0, 1, 2, 3): - out.append((f"2D 16x4 base={base} last={last} level={level}", 16, 4, TYPE_2D, 0, base, last, level)) - for layers in (1, 6, 7, 16, 100): - for base in (0, 1): - for level in (0, 1, 2, 3, 5, 9): - out.append((f"2D array 256x256x{layers} base={base} level={level}", - 256, 256, TYPE_2D_ARRAY, layers - 1, base, 8, level)) - return out - - -LODS = (-1.0, 0.0, 0.25, 0.5, 1.25, 2.75, 3.5, 7.0) -SAMPLERS = [(mip, lo, hi, bias) for mip in (MIP_NONE, MIP_POINT, MIP_LINEAR) - for lo, hi, bias in ((0, 15, 0), (0, 0.25, 0), (0.5, 2.25, 0), (1, 1, 0), (5.5, 15, 0), (3, 2, 0), - (0, 15, 1.0), (0, 15, -0.5))] - - -def lod_cases(): - """(name, width, height, last, du, dv, sampler, expected LOD before bias). A 16x16 five-level image steps both - axes by the same texel count; the 64x4 seven-level image steps one axis only, which tells u from v.""" - out = [] - for samp in SAMPLERS: - for lod in LODS: - d = 2.0 ** lod / 16 - out.append((f"16x16 mip={samp[0]} lod=[{samp[1]},{samp[2]}] bias={samp[3]} L={lod}", 16, 16, 4, d, d, - samp, lod)) - for tx, ty, lod in ((1, 0, 0.0), (0, 1, 0.0), (4, 0, 2.0), (0, 4, 2.0), (4, 1, 2.0), (1, 4, 2.0), (8, 2, 3.0)): - out.append((f"64x4 du={tx} texels dv={ty} texels", 64, 4, 6, tx / 64, ty / 4, (MIP_LINEAR, 0, 15, 0), lod)) - return out - - -# ---- comparison ---- - -def compare_resinfo(case, got): - name, w, h, typ, depth, base, last, level = case - want = resinfo_model(w, h, typ, depth if depth is not None else 0, base, last, level) - if typ == TYPE_2D_ARRAY and depth is None: - raise ValueError("a 2D array case needs its DEPTH field") - return want == list(got[:4]), want - - -def compare_lod(case, got): - name, w, h, last, du, dv, (mip, lo, hi, bias), lod = case - want = lod_model(lod, mip, lo, hi, bias, last + 1) - lanes = [(u2f(got[4 * i]), u2f(got[4 * i + 1])) for i in range(4)] - return all(lane == want for lane in lanes), want, lanes - - -def run(oracle, waves): - arch = oracle.arch - rcases, lcases = resinfo_cases(), lod_cases() - report = {"arch": arch, "resinfo": [], "lod": []} - bad = 0 - for wave in waves: - kernels = [resinfo_kernel(tsharp_words(arch, w, h, typ, d, b, l), lv, typ, wave) - for _, w, h, typ, d, b, l, lv in rcases] - for case, got in zip(rcases, oracle.run(kernels)): - if isinstance(got, str) or len(got) < 4: - raise RuntimeError(f"{case[0]} wave{wave}: {got}") - ok, want = compare_resinfo(case, got) - bad += not ok - report["resinfo"].append({"case": case[0], "wave": wave, "got": got[:4], "rule": want, "match": ok}) - if not ok: - print(f"MISMATCH resinfo wave{wave} {case[0]}: got {got[:4]}, rule {want}") - kernels = [lod_kernel(tsharp_words(arch, w, h, last=l), ssharp_words(*s), du, dv, wave) - for _, w, h, l, du, dv, s, _ in lcases] - for case, got in zip(lcases, oracle.run(kernels, words=16)): - if isinstance(got, str) or len(got) < 16: - raise RuntimeError(f"{case[0]} wave{wave}: {got}") - ok, want, lanes = compare_lod(case, got) - bad += not ok - report["lod"].append({"case": case[0], "wave": wave, "got": lanes, "rule": want, "match": ok}) - if not ok: - print(f"MISMATCH get_lod wave{wave} {case[0]}: got {lanes}, rule {want}") - print(f"wave{wave}: image_get_resinfo {len(rcases)} cases, image_get_lod {len(lcases)} cases") - return bad, report - - -# ---- self-test: values read on gfx1036 (Radeon Graphics of a Ryzen 9 9950X3D, Windows driver 32.0.21045.16010) ---- - -MEASURED_RESINFO = [ - ((16, 4, TYPE_2D, 0x3F, 0, 4, 0), [16, 4, 0, 5]), - ((16, 4, TYPE_2D, 0x1FFF, 0, 4, 1), [8, 2, 0, 5]), - ((16, 4, TYPE_2D, 0, 0, 4, 5), [0, 0, 0, 5]), - ((16, 4, TYPE_2D, 0, 1, 4, 0), [8, 2, 0, 4]), - ((16, 4, TYPE_2D, 0, 2, 3, 1), [2, 1, 0, 2]), - ((256, 256, TYPE_2D_ARRAY, 5, 0, 8, 1), [128, 128, 3, 9]), - ((256, 256, TYPE_2D_ARRAY, 6, 0, 8, 2), [64, 64, 1, 9]), - ((256, 256, TYPE_2D_ARRAY, 99, 1, 8, 3), [16, 16, 6, 8]), - ((16, 4, TYPE_2D_ARRAY, 5, 0, 2, 3), [0, 0, 0, 3]), -] -MEASURED_LOD = [ # (lod, mip, lo, hi, bias, levels) -> (clamped, raw) - ((0.25, MIP_NONE, 0, 15, 0, 5), (0.0, 0.25)), - ((0.5, MIP_POINT, 0, 15, 0, 5), (1.0, 0.5)), - ((2.75, MIP_POINT, 0.5, 2.25, 0, 5), (2.0, 2.75)), - ((6.0, MIP_POINT, 0, 15, 0, 5), (4.0, 6.0)), - ((0.5, MIP_LINEAR, 0, 0.25, 0, 5), (0.25, 0.5)), - ((-1.0, MIP_LINEAR, 0.5, 2.25, 0, 5), (0.5, -1.0)), - ((2.75, MIP_LINEAR, 0, 15, 0, 5), (2.75, 2.75)), - ((0.0, MIP_LINEAR, 5.5, 15, 0, 5), (4.0, 0.0)), - ((7.0, MIP_LINEAR, 3, 2, 0, 5), (3.0, 7.0)), - ((1.25, MIP_LINEAR, 0, 15, 1.0, 5), (2.25, 2.25)), - ((1.25, MIP_POINT, 0, 15, -0.5, 5), (1.0, 0.75)), -] - - -def self_test(): - bad = 0 - for args, want in MEASURED_RESINFO: - got = resinfo_model(*args) - if got != want: - print(f"resinfo {args}: rule {got}, measured {want}") - bad += 1 - for args, want in MEASURED_LOD: - got = lod_model(*args) - if got != want: - print(f"get_lod {args}: rule {got}, measured {want}") - bad += 1 - print(f"self-test: {len(MEASURED_RESINFO) + len(MEASURED_LOD)} measured values, {bad} disagree with the rules") - return 1 if bad else 0 - - -def _import_oracle(): - """The optional hardware oracle, imported only for a GPU run. - - --help and --self-test must not touch it: finding AMD clang, the HIP runtime and a host compiler is the - expensive startup work this probe would otherwise pay before argparse can answer --help. - """ - sys.dont_write_bytecode = True - if HERE not in sys.path: - sys.path.insert(0, HERE) - from hw_oracle import asm, runner - return asm, runner - - -def write_report(path, report): - """Stage the JSON report in a sibling temp file and swap it in, so a write or replace failure keeps any - previous report intact and preserves its permission bits.""" - parent = os.path.dirname(os.path.abspath(path)) - if parent: - os.makedirs(parent, exist_ok=True) - destination = os.path.realpath(path) - dest_parent = os.path.dirname(destination) or "." - if dest_parent != parent: - os.makedirs(dest_parent, exist_ok=True) - try: - mode = os.stat(destination).st_mode - except FileNotFoundError: - mode = None - if mode is not None and not stat.S_ISREG(mode): - with open(path, "w", encoding="utf-8", newline="\n") as f: - json.dump(report, f, indent=1) - return - if mode is not None: - # Keep the direct writer's permission check without truncating the previous report. - os.close(os.open(destination, os.O_WRONLY)) - tmp = None - try: - with tempfile.NamedTemporaryFile( - mode="w", encoding="utf-8", newline="\n", delete=False, - dir=dest_parent, prefix=".image_query_probe-", suffix=".tmp", - ) as f: - tmp = f.name - json.dump(report, f, indent=1) - if os.name != "nt": - os.chmod(tmp, published_mode(destination)) - replace_retry(tmp, destination) - except BaseException: - if tmp is not None: - try: - if os.path.lexists(tmp): - os.chmod(tmp, 0o600) - os.unlink(tmp) - except OSError: - pass - raise - - -def main(argv=None): - p = argparse.ArgumentParser(description=__doc__.split("\n")[0]) - p.add_argument("--waves", default="32,64") - p.add_argument("--json", help="write every case, its result and the rule's answer here") - p.add_argument("--self-test", action="store_true") - a = p.parse_args(argv) - if a.self_test: - return self_test() - waves = [int(w) for w in a.waves.split(",")] - if any(w not in (32, 64) for w in waves): - p.error("--waves takes 32 and/or 64") - asm, runner = _import_oracle() - try: - oracle = runner.open_oracle() - except runner.Unavailable as e: - print(f"hardware oracle unavailable: {e}") - return 77 - try: - if asm.family(oracle.arch) != "gfx10": - print(f"{oracle.arch} is not GFX10; this probe builds GFX10 descriptors") - return 77 - print(f"hardware oracle: arch={oracle.arch}") - try: - bad, report = run(oracle, waves) - except RuntimeError as e: - print(f"harness error: {e}") - return 2 - finally: - oracle.close() - total = len(report["resinfo"]) + len(report["lod"]) - print(f"{total - bad} of {total} results follow the rules, {bad} do not") - if a.json: - try: - write_report(a.json, report) - except OSError as exc: - print(f"cannot write {a.json}: {exc.strerror or exc}", file=sys.stderr) - return 2 # not 1: that would read as a result off the rules; the summary above has the result - return 1 if bad else 0 - - -if __name__ == "__main__": - try: # a redirected stdout is strict ANSI code page under -I; write '?' for what it cannot encode - sys.stdout.reconfigure(errors="replace") - except (AttributeError, ValueError, OSError): - pass - sys.exit(main()) diff --git a/tools/imhex/psin.hexpat b/tools/imhex/psin.hexpat deleted file mode 100644 index c3dc014d9..000000000 --- a/tools/imhex/psin.hexpat +++ /dev/null @@ -1,193 +0,0 @@ -// ImHex pattern for a PSIN metadata container (docs/psin.md; tools/psin_index.py and tools/psin_data.py read it). -// -// Layout, as measured in docs/psin.md: -// 0x00 "PSIN" -// 0x04 big-endian absolute offset of the first section -// 0x08 instance-data block table: rows of {u32 block type, u32 data size, aa x 8}, ended by "pppppppp" 8 bytes -// short of a 16-byte boundary. The blocks follow in table order, each padded to 16 bytes, numbered from 1; -// the last one ends at the first section. Their contents are shown as raw bytes: decoding them needs the -// schema walk that psin_data.py does. -// sections from the first-section offset to EOF: ASCII tag, big-endian total size (header included) -// LSCH struct headers (32 bytes) then all members (16 bytes); the header count is not stored, it is the one -// count whose headers and members fill the payload exactly -// LENM enum headers (24 bytes) then all values (16 bytes); same rule -// LSNS u32 block count, {u32 kind, u32 byte count} per block, then the blocks: opaque 16-byte records -// LRSC "0DRP", u32 version, ...; the u32 at +0x10 is the root block number -// CHKS big-endian file size and a 32-bit value (not verified here) -// LGID empty -// Little-endian everywhere except the first-section offset and the section sizes. A truncated container shows what -// is whole and the rest as raw bytes. - -#pragma description PSIN metadata container: block table, LSCH/LENM schema, LSNS, LRSC, CHKS (docs/psin.md) -#pragma endian little -#pragma magic [ 50 53 49 4E ] @ 0x00 -#pragma array_limit 1048576 -#pragma pattern_limit 8388608 - -import std.mem; -import std.core; - -// ---- header and instance-data block table --------------------------------------------------------------------- - -struct Header { - char magic[4]; - be u32 first_section [[comment("big-endian absolute offset of the first section")]]; -}; - -Header header @ 0x00; - -fn count_rows(u128 limit) { - u128 p = 0x08; - u32 n = 0; - while (p + 16 <= limit && std::mem::read_unsigned(p, 8) != 0x7070707070707070) { - p += 16; - n += 1; - } - return n; -}; - -u128 g_limit = header.first_section < std::mem::size() ? header.first_section : std::mem::size(); -u32 g_rows = count_rows(g_limit); - -struct BlockRow { - u32 type [[comment("struct name hash from LSCH, a member type code below 0x100, or 0x100 + n")]]; - u32 size [[comment("data size in bytes")]]; - u8 fill[8] [[comment("aa x 8")]]; -}; - -struct Block { - u32 i = std::core::array_index(); - u8 data[rows[i].size] [[comment("block number i + 1; raw: see psin_data.py")]]; - u8 pad[(16 - rows[i].size % 16) % 16]; -}; - -BlockRow rows[g_rows] @ 0x08; -char table_end[8] @ 0x08 + 16 * g_rows [[comment("\"pppppppp\"")]]; -Block blocks[g_rows] @ 0x08 + 16 * g_rows + 8; - -// ---- sections --------------------------------------------------------------------------------------------------- - -fn header_count(u128 payload, u128 length, u32 header_size, u32 element_size, u32 count_at, u32 count_size) { - if (length == 0) return 0; - u32 elements = 0; - u32 k = 1; - while (header_size * k <= length) { - elements += std::mem::read_unsigned(payload + header_size * (k - 1) + count_at, count_size); - if (header_size * k + element_size * elements == length) return k; - k += 1; - } - return 0xFFFFFFFF; // no count fits: shown as raw bytes -}; - -fn sum_counts(u128 payload, u32 k, u32 header_size, u32 count_at, u32 count_size) { - u32 total = 0; - for (u32 i = 0, i < k, i += 1) { - total += std::mem::read_unsigned(payload + header_size * i + count_at, count_size); - } - return total; -}; - -struct StructHeader { - u32 name_hash; - u32 signature [[comment("layout signature")]]; - u8 flags; - u8 align_log2; - u16 zero_0a; - u32 zero_0c; - u8 fill[8] [[comment("aa x 8")]]; - u32 size [[comment("byte size of the struct")]]; - u16 zero_1c; - u16 member_count; -}; - -struct Member { - u32 name_hash [[comment("0x100 = array element descriptor")]]; - u32 offset; - u8 type; - u8 sub; - u16 index [[comment("for type 0x5c: position of its 0x100 element descriptor in this struct's members")]]; - u32 ref_hash [[comment("struct or enum name hash for the referring types, else 0")]]; -}; - -struct EnumHeader { - u32 name_hash; - u32 signature; - u8 fill[8] [[comment("ee x 8")]]; - u32 value_count; - u32 zero_14; -}; - -struct EnumValue { - s64 value; - u64 name_hash [[comment("case-sensitive joaat in the low half")]]; -}; - -struct LsnsDesc { - u32 kind; - u32 bytes; -}; - -struct LsnsRecord { - u8 bytes[16] [[comment("opaque")]]; -}; - -struct LsnsBlock { - u32 i = std::core::array_index(); - LsnsRecord records[parent.descs[i].bytes / 16]; -}; - -bool g_bad = false; - -struct Section { - char tag[4]; - be u32 size [[comment("big-endian total size, header included")]]; - u128 payload = $; - if (size < 8 || addressof(tag) + size > std::mem::size()) { - g_bad = true; - u8 truncated[std::mem::size() - $] [[comment("section runs past the end of the file")]]; - } else { - u32 length = size - 8; - if (tag == "LSCH") { - u32 k = header_count(payload, length, 32, 16, 30, 2); - if (k == 0xFFFFFFFF) { - u8 raw[length] [[comment("no struct count fills the payload")]]; - } else { - StructHeader structs[k]; - Member members[sum_counts(payload, k, 32, 30, 2)]; - } - } else if (tag == "LENM") { - u32 k = header_count(payload, length, 24, 16, 16, 4); - if (k == 0xFFFFFFFF) { - u8 raw[length] [[comment("no enum count fills the payload")]]; - } else { - EnumHeader enums[k]; - EnumValue values[sum_counts(payload, k, 24, 16, 4)]; - } - } else if (tag == "LSNS" && length >= 4) { - u32 block_count; - if (4 + 8 * block_count <= length) { - LsnsDesc descs[block_count]; - LsnsBlock lsns_blocks[block_count]; - } - if ($ < payload + length) { - u8 rest[payload + length - $] [[comment("does not fit the block table")]]; - } - } else if (tag == "LRSC" && length >= 0x14 && std::mem::read_string(payload, 4) == "0DRP") { - char rsc_magic[4]; - u32 rsc_version; - u32 u32_08; - u32 u32_0c; - u32 root_block [[comment("block number of the root struct")]]; - u8 rest[length - 0x14]; - } else if (tag == "CHKS" && length >= 8) { - be u32 checksum_size [[comment("big-endian file size")]]; - u8 checksum[4] [[comment("32-bit value, not verified")]]; - u8 rest[length - 8]; - } else { - u8 raw[length]; - } - } -}; - -Section sections[while(!g_bad && header.first_section + 8 <= std::mem::size() && std::mem::size() - $ >= 8)] - @ header.first_section; diff --git a/tools/imhex/rbf0.hexpat b/tools/imhex/rbf0.hexpat deleted file mode 100644 index 8d311e099..000000000 --- a/tools/imhex/rbf0.hexpat +++ /dev/null @@ -1,96 +0,0 @@ -// ImHex pattern for one RBF0 resource: RAGE's binary form of an XML data file. -// -// The grammar is the one measured in docs/rbf0.md (section 3) and parsed by tools/rbf0_index.py (parse_rbf0): -// -// 0x00 "RBF0" -// 0x04 FB FF 01 00 optional prologue. With it, integers and floats are 8 bytes ("wide"); without it they are -// 4 bytes ("narrow") and the records start at 0x04. What the four bytes mean is not established; -// the width follows them in every measured resource (docs/rbf0.md). -// records, each a u8 descriptor index and a u8 type: -// FF FF close the open element -// FD FF text for the open element: u32 length, then that many bytes -// index == descriptors so far a new descriptor: u16 name length, then the UTF-8 name, before the payload -// type 0x00 open an element: u16 0, u16 0, u16 attribute count -// type 0x10 integer 0x20 true 0x30 false 0x40 float 0x50 three floats -// type 0x60 string: u16 length, then UTF-8 bytes -// The stream has no length field and no section table: it ends where the root element closes, and the pattern -// stops there. -// -// Open an inflated, joined resource, not the archive. A resource larger than 64 KiB is split over several zlib -// streams, with no header on the continuations (docs/rbf0.md section 2); tools/rbf0_index.py joins them. - -#pragma description RBF0 record stream (binary XML, docs/rbf0.md) -#pragma endian little -#pragma magic [ 52 42 46 30 ] @ 0x00 -// The largest measured resource has 68,398 elements and about twice as many records. -#pragma array_limit 4194304 -#pragma pattern_limit 33554432 - -import std.mem; -import std.io; - -bool g_wide = std::mem::size() >= 8 && std::mem::read_unsigned(0x04, 4) == 0x0001FFFB; -u32 g_descriptors = 0; -u32 g_depth = 0; -bool g_done = false; - -struct Header { - char magic[4]; - if (g_wide) { - u8 prologue[4] [[comment("FB FF 01 00: 8-byte integers and floats follow")]]; - } -}; - -struct Record { - u8 index; - u8 type; - if (index == 0xFF) { - if (g_depth > 0) g_depth -= 1; - if (g_depth == 0) g_done = true; - } else if (index == 0xFD) { - u32 text_length; - char text[text_length]; - } else { - if (index == g_descriptors) { - u16 name_length; - char name[name_length] [[comment("new descriptor")]]; - g_descriptors += 1; - } - if (type == 0x00) { - u16 word0; - u16 word1; - u16 attribute_count; - g_depth += 1; - } else if (type == 0x10) { - if (g_wide) { - u64 value_int; - } else { - u32 value_int; - } - } else if (type == 0x40) { - if (g_wide) { - double value_float; - } else { - float value_float; - } - } else if (type == 0x50) { - if (g_wide) { - double value_vec3[3]; - } else { - float value_vec3[3]; - } - } else if (type == 0x60) { - u16 string_length; - char value_string[string_length]; - } - } -} [[format("format_record")]]; - -fn format_record(Record r) { - if (r.index == 0xFF) return "close"; - if (r.index == 0xFD) return "text"; - return std::format("descriptor {} type 0x{:02X}", r.index, r.type); -}; - -Header header @ 0x00; -Record records[while(!g_done && !std::mem::eof())] @ sizeof(header); diff --git a/tools/imhex/rpf9.hexpat b/tools/imhex/rpf9.hexpat deleted file mode 100644 index aaa30df5f..000000000 --- a/tools/imhex/rpf9.hexpat +++ /dev/null @@ -1,32 +0,0 @@ -// ImHex pattern for the header of an RPF9 archive. -// -// Only measured fields are named (docs/rpf.md "What is readable"; docs/story.md "Signatures actually observed"): -// 0x00 "9FPR" RPF9 stored little-endian -// 0x04 data offset u32, where the data area (zlib streams laid end to end) starts -// 0x08 u32 present in every header; meaning not established -// 0x0C trailer size u32, the size of the block that ends the file (docs/rpf.md, The trailer at EOF) -// Everything from 0x10 to the data offset is the rest of the header and the table of contents. The TOC is -// encrypted/packed: this pattern shows that range as opaque bytes and decodes nothing in it (no keys, no decryption). -// -// This describes the archive's own header at offset 0. Nested RPF9 headers occur inside the data area -// (docs/story.md); their offsets are not covered here. - -#pragma description RPF9 archive header, opaque TOC and data area start (docs/rpf.md) -#pragma endian little -#pragma magic [ 39 46 50 52 ] @ 0x00 - -import std.mem; -import std.sys; - -struct Rpf9Header { - char magic[4] [[comment("\"9FPR\": RPF9 stored little-endian")]]; - u32 data_offset [[comment("start of the data area (docs/rpf.md)")]]; - u32 u32_08 [[comment("meaning not established")]]; - u32 trailer_size [[comment("size of the block at EOF (docs/rpf.md)")]]; -}; - -Rpf9Header header @ 0x00; -std::assert(header.data_offset >= sizeof(header) && header.data_offset <= std::mem::size(), - "the data offset is outside the file"); -u8 header_rest_and_toc[header.data_offset - sizeof(header)] @ sizeof(header) - [[comment("rest of the header and the table of contents: encrypted/packed, not decoded")]]; diff --git a/tools/import_call_sites.py b/tools/import_call_sites.py deleted file mode 100644 index 8a9c9746d..000000000 --- a/tools/import_call_sites.py +++ /dev/null @@ -1,177 +0,0 @@ -"""Count and locate the direct calls to chosen imports of an x86-64 PE image, from the file alone. - -Usage: - python -I tools/import_call_sites.py [--import DLL!NAME ...] [--dll DLL ...] [--json] - -An MSVC image calls an imported function through a thunk, `jmp qword [rip+disp32]` through the import's address-table -slot, and reaches the thunk with `call rel32` (or `jmp rel32` as a tail call). This finds each wanted import's thunk, -then every `E8`/`E9 rel32` in an executable section whose target is that thunk. Nothing is run and nothing is -disassembled, so this is a byte pattern: a stray `E8` or `E9` inside another instruction that happens to land on a -thunk would be counted too, which is rare, and a call that goes through a register (`call rax` after a load of the -slot) is not seen. Read the counts as a lower bound for indirect uses and an upper bound for direct ones. - -With no `--import` and no `--dll`, every import is listed. An import named `#N` is an ordinal import. A `--import` value must -carry both halves of `DLL!NAME` and a `--dll` value only a DLL name, and both must name an import of the image: a value -that can match no import is refused instead of being answered with a count of zero. Output is counts and RVAs only, no -instruction bytes (docs/runtime_imports.md, "The -retail executable (RT-5)"). -""" -import argparse -import json -import os -import re -import struct -import sys - -ROOT = os.path.dirname(os.path.abspath(__file__)) -if ROOT not in sys.path: - sys.path.insert(0, ROOT) -import pe_inspect # noqa: E402 - -JMP_INDIRECT = re.compile(b"\xff\x25") -REL_BRANCH = re.compile(b"[\xe8\xe9]") - - -def import_slots(img): - """{IAT slot RVA: 'dll!name'} for every import of a PE32+ image.""" - return {at: f"{dll}!{name}" for at, (dll, name) in import_entries(img).items()} - - -def import_entries(img): - """{IAT slot RVA: (dll, name)}: the two parts kept apart, since a DLL name may itself contain '!'.""" - rva, size = img.directory(1) - slots = {} - if not rva or not size: - return slots - for i in range(size // 20): - at = img.offset(rva + i * 20, 20) - if at is None: - break - oft, _stamp, _forwarder, dll_rva, iat_rva = struct.unpack_from(" len(blob): - continue - target = rva + s + 6 + struct.unpack_from(" len(blob): - continue - key = thunks.get(rva + s + 5 + struct.unpack_from(" str: - """--import: `DLL!NAME`, the form `selected()` matches. A bare DLL, a bare name or an empty half selects no import, - so the run printed "0 import(s), 0 call site(s)" for a typo in either half: the answer read as "the image never - calls it" (docs/xmem_exe_calls.md reads those counts that way).""" - dll, sep, name = text.partition("!") - if not sep or not dll or not name: - raise argparse.ArgumentTypeError(f"expected DLL!NAME, got {text!r}") - return text - - -def dll_selector(text: str) -> str: - """--dll: a DLL name. `DLL!NAME` is the --import form and names no DLL, so it selected nothing.""" - if not text or "!" in text: - raise argparse.ArgumentTypeError(f"expected a DLL name, got {text!r}") - return text - - -def unmatched_selectors(data: bytes, wanted, dlls) -> list: - """The well-formed selectors that name nothing this image imports: a misspelled half of `DLL!NAME`, or a DLL the - image does not import. They answered "0 import(s), 0 call site(s)", which reads as "the image never calls it". - `call_sites()` keeps answering `{}` for a caller that selects nothing on purpose.""" - keys = import_slots(pe_inspect.PeImage(data)) - names = {key.lower() for key in keys.values()} - libs = {key.partition("!")[0].lower() for key in keys.values()} - return [f"--import {w}" for w in wanted if w.lower() not in names] + \ - [f"--dll {d}" for d in dlls if d.lower() not in libs] - - -def main(argv=None): - ap = argparse.ArgumentParser(description="Count the direct calls to chosen imports of an x86-64 PE image.") - ap.add_argument("image") - ap.add_argument("--import", dest="imports", action="append", default=[], metavar="DLL!NAME", type=import_selector, - help="an import to look for (repeatable); '#N' names an ordinal import") - ap.add_argument("--dll", dest="dlls", action="append", default=[], metavar="DLL", type=dll_selector, - help="every import of this DLL (repeatable)") - ap.add_argument("--json", action="store_true", help="print JSON (RVAs in hex) instead of the table") - args = ap.parse_args(argv) - try: - with open(args.image, "rb") as f: - data = f.read() - result = call_sites(data, set(args.imports) or None, set(args.dlls) or None) - except (OSError, pe_inspect.PeFormatError) as e: - print(f"{os.path.basename(sys.argv[0])}: {e}", file=sys.stderr) - return 2 - imports = result["imports"] - missing = unmatched_selectors(data, args.imports, args.dlls) - if missing: - print(f"{os.path.basename(sys.argv[0])}: {os.path.basename(args.image)}: " - f"no import matches {', '.join(missing)}", file=sys.stderr) - return 2 - if args.json: - printable = {k: {f: [hex(x) for x in v] for f, v in e.items()} for k, e in imports.items()} - print(json.dumps({"image_base": hex(result["image_base"]), "imports": printable}, indent=1)) - return 0 - print(f"{'import':56s} {'thunks':>6s} {'call':>5s} {'jmp':>4s}") - for key, e in sorted(imports.items(), key=lambda kv: (-(len(kv[1]["call"]) + len(kv[1]["jmp"])), kv[0])): - print(f"{key:56s} {len(e['thunks']):6d} {len(e['call']):5d} {len(e['jmp']):4d}") - total = sum(len(e["call"]) + len(e["jmp"]) for e in imports.values()) - print(f"{len(imports)} import(s), {total} call site(s)") - return 0 - - -if __name__ == "__main__": - try: # a redirected stdout is strict ANSI code page under -I; write '?' for what it cannot encode - sys.stdout.reconfigure(errors="replace") - except (AttributeError, ValueError, OSError): - pass - sys.exit(main()) diff --git a/tools/import_fail_fast.py b/tools/import_fail_fast.py deleted file mode 100644 index 2bf87fda9..000000000 --- a/tools/import_fail_fast.py +++ /dev/null @@ -1,295 +0,0 @@ -"""List the call sites where an x86-64 PE image stops itself when an import returns a failure, from the file alone. - -Usage: - python -I tools/import_fail_fast.py [--import DLL!NAME ...] [--dll DLL ...] [--all] [--json] - -A title treats some results as impossible: it tests the returned value and branches to `int3` (MSVC's `__debugbreak` -and the marker it places after a call that does not return) when the value is the failing one. A shim that returns -that value at such a site stops the boot there, with no error message. This lists, per import, how many of its call -sites do that and on which value, so the results each shim must get right are known before a run reaches them. - -How, with nothing run: -1. Call sites. A `call rel32` to the import's thunk (tools/import_call_sites.py finds the thunks) and a - `call qword [rip+disp32]` through the import's address-table slot, the form an image uses for the - `api-ms-win-*` imports. A site's RVA is that of its `E8` or `FF` byte. Tail jumps are skipped: their result - is tested by a caller, not here. -2. The test. The instructions after the call are decoded (tools/gdk_runtime_calls.py's decoder) up to the first - `test` or `cmp` of the result: rax at any width, or a register it was copied to with `mov`. A `test` of the - register with itself or with a constant, or a `cmp` with a constant. When a branch, a call, a return or - another write to every copy of the result comes first, the site is not one this tool can judge. -3. The branch. The next instruction must be a conditional jump. Each side is followed for a few instructions, and - through up to two unconditional jumps. A side is fatal when it reaches `int3`, `ud2` or `int 29h` - (`__fastfail`), or a `call` whose next instruction is `int3` (a call that does not return). -4. The condition is the value that takes the fatal side, written with the result register at the width the test - read: `eax == 0`, `rax == -1`, `eax < 0` (a failed HRESULT), `eax != 1`, `(al & 0x1) == 0`. `u` - are unsigned comparisons. A site where both sides are fatal is not counted. - -What a count means: a site found here is code that can stop the title, not proof that the boot reaches it. Only -straight-line code after the call is read, so a result stored and tested later, or a failure path that logs before -it stops, is not seen. The counts are heuristic: they can miss sites that way, and a stray `E8` or `FF 15` byte pair -inside another instruction could add a false one, which is rare. Output is import names, counts, conditions and RVAs only, no instruction bytes. - -`--json` prints every import the image names (or every one `--import`/`--dll` selects), including those with no -call site (`"calls": 0`), with `"fatal"` empty when none of its sites is fatal. The table's last line, -"N of M import(s) called directly", gives both numbers: M imports named (or selected), N of them with at least one -direct call site. The rest are reached only through a stored pointer or a tail jump, or not at all. -""" -import argparse -import json -import os -import re -import struct -import sys - -ROOT = os.path.dirname(os.path.abspath(__file__)) -if ROOT not in sys.path: - sys.path.insert(0, ROOT) -import pe_inspect # noqa: E402 -from gdk_runtime_calls import RAX, decode, writes # noqa: E402 -from import_call_sites import call_sites, import_slots # noqa: E402 - -CALL_SLOT = re.compile(b"\xff\x15") -PREFIXES = frozenset((0x26, 0x2E, 0x36, 0x3E, 0x64, 0x65, 0x66, 0x67, 0xF0, 0xF2, 0xF3)) -COPY_OPS = frozenset((0x8B, 0x63, 0x1B6, 0x1B7, 0x1BE, 0x1BF)) # mov, movsxd, movzx, movsx: r <- r/m -TEST_WINDOW = 8 # instructions read after a call to find the test of its result -SIDE_WINDOW = 4 # instructions read on each side of the branch, per jump followed -SIDE_JUMPS = 2 # unconditional jumps followed on a side - -# Condition codes of jcc (low nibble of 70-7F / 0F 80-8F), as the comparison that takes the jump. -CMP_CONDITION = {0x2: "=u", 0x4: "==", 0x5: "!=", 0x6: "<=u", 0x7: ">u", - 0xC: "<", 0xD: ">=", 0xE: "<=", 0xF: ">"} -# After `test r, r`: CF = OF = 0, so the condition is one on the sign and zero of r. -SELF_TEST_CONDITION = {0x4: "== 0", 0x5: "!= 0", 0x6: "== 0", 0x7: "!= 0", 0x8: "< 0", 0x9: ">= 0", - 0xC: "< 0", 0xD: ">= 0", 0xE: "<= 0", 0xF: "> 0"} -RESULT_NAME = {8: "al", 16: "ax", 32: "eax", 64: "rax"} - - -def instruction_bytes(img, insn): - at = img.offset(insn.rva, insn.size) - return img.data[at:at + insn.size] if at is not None else b"" - - -def decode_at(img, rva): - at = img.offset(rva) - if at is None: - return None - return decode(img.data, at, rva - at) - - -def width(raw, insn): - """Operand width of an ALU instruction: 8 for the byte forms, else 64 with REX.W, 16 with a 0x66 prefix, 32.""" - if insn.op in (0x84, 0x80, 0x3C, 0xA8, 0xF6): - return 8 - if insn.wide: - return 64 - for b in raw: - if b == 0x66: - return 16 - if b not in PREFIXES: - break - return 32 - - -def immediate(raw, insn, size): - """The instruction's trailing immediate (sign-extended).""" - fmt = {1: " len(blob): - continue - key = slots.get(s["rva"] + at + 6 + struct.unpack_from("5s} {'fatal':>5s} stops the program when") - for key, e in sorted(rows, key=lambda kv: (-len(kv[1]["fatal"]), kv[0])): - print(f"{key:{w}s} {e['calls']:5d} {len(e['fatal']):5d} {summary(e)}") - called = sum(1 for e in imports.values() if e["calls"]) - with_fatal = sum(1 for e in imports.values() if e["fatal"]) - sites = sum(len(e["fatal"]) for e in imports.values()) - print(f"{called} of {len(imports)} import(s) called directly, {with_fatal} with a fatal result check, " - f"{sites} fatal site(s)") - return 0 - - -if __name__ == "__main__": - try: # a redirected stdout is strict ANSI code page under -I; write '?' for what it cannot encode - sys.stdout.reconfigure(errors="replace") - except (AttributeError, ValueError, OSError): - pass - sys.exit(main()) diff --git a/tools/inline_scan.py b/tools/inline_scan.py deleted file mode 100644 index 6fd617cfd..000000000 --- a/tools/inline_scan.py +++ /dev/null @@ -1,239 +0,0 @@ -"""Find the inline command-list writes in an x64 image and say whether each one checks the cursor limit first. - -Usage: - python -I tools/inline_scan.py [--base 0x140000000] [--sites] - -Code compiled against the console headers writes some commands into the list's buffer itself -(docs/d3d12_command_objects.md, "The list object is wider than its vtable"): it compares the write cursor -`[list+18h]` with a limit (`[list+28h]` for a dispatch, `[list+30h]` for root arguments in the package's DLLs), -writes the packet through the cursor, advances it and stores it back; when the buffer is full it calls the vtable -method instead. A layer that keeps the cursor at the limit sees every command only if every such write checks -first. This tool finds each cursor store-back `mov [list+18h],reg` that follows stores through the cursor, looks -back to the previous store-back of the same list, and sorts the site into: - - checked a compare of the cursor against `[list+X]` (X != 18h), or against a register, followed by an - unsigned branch; the branch target's vtable call is reported as the fallback slot - UNCHECKED no compare, but the cursor was loaded from the list and the list's own fields are touched - (+140h..+143h, +344h, +544h): an inline write that a cursor-at-limit layer never sees - unrelated no compare and no list field: another structure with a pointer at +18h - -A PE is disassembled with MSVC `dumpbin /disasm:nobytes` (it comes with the build tools the runtime needs) and -streamed, so an image of any size works in one pass; a saved dumpbin listing (with or without the byte column) -works too, on any OS. Nothing is executed. The output is RVAs, counts and constants, no code bytes. -An input with no instructions in it (an empty or other text file, a PE dumpbin prints no code for) exits 2 -instead of reporting zero sites, so "UNCHECKED 0" always means something was scanned. -The matcher knows the instruction shapes MSVC emits for these writes (see tests/test_inline_scan.py); a shape it -does not know shows up as `unrelated`, so read a few of those by hand on a new image. -""" -import argparse -import collections -import re -import shutil -import subprocess -import sys -from pathlib import Path - -LOOKBACK = 64 # instructions searched backwards from a store-back -FALLBACK_WINDOW = 16 # instructions after the branch target to look for the vtable call -PENDING_WINDOW = 400 # instructions to wait for a forward branch target -TAIL_WINDOW = 6 # instructions after a store-back that may still show a list field -REG64 = r"r(?:[abcd]x|[sd]i|bp|sp|8|9|1[0-5])" -DUMPBIN_GLOB = "Program Files*/Microsoft Visual Studio/*/*/VC/Tools/MSVC/*/bin/Hostx64/x64/dumpbin.exe" - -LINE = re.compile(r"^\s+([0-9A-F]{8,16}): (?:(?:[0-9A-F]{2} )+\s+)?([a-z][a-z0-9]*)\s*(.*)$") -LOAD = re.compile(rf"^({REG64}),qword ptr \[({REG64})\+18h\]$") -STORE_BACK = re.compile(rf"^qword ptr \[({REG64})\+18h\],({REG64})$") -CMP = re.compile(rf"^(?:({REG64}),qword ptr \[({REG64})\+([0-9A-F]+)h?\]|qword ptr \[({REG64})\+([0-9A-F]+)h?\],({REG64}))$") -LEA = re.compile(rf"^({REG64}),\[({REG64})\+([0-9A-F]+)h?\]$") -ADD = re.compile(rf"^({REG64}),([0-9A-F]+)h?$") -STORE = re.compile(r"^(?:byte|word|dword|qword|xmmword|ymmword) ptr \[(\w+)(?:\+([0-9A-F]+)h?)?\],(.+)$") -IMM = re.compile(r"^([0-9A-F]+)h?$") -COPY = re.compile(rf"^({REG64}),({REG64})$") -LIMIT_LOAD = re.compile(rf"^({REG64}),qword ptr \[({REG64})\+([0-9A-F]+)h?\]$") -LIST_FIELDS = re.compile(r"\[(\w+)(?:\+\w+\*\d)?\+0*(?:140|141|143|344|544)h\]") # fields only a D3D12.X list has -VCALL = re.compile(rf"^qword ptr \[({REG64})\+([0-9A-F]+)h?\]$") -UNSIGNED_JCC = {"jae", "jb", "ja", "jbe"} -REG_LIMIT = -1 # limit compared through a register loaded outside the scanned span -JCC_TARGET = re.compile(r"^([0-9A-F]{8,16})$") - - -def read_lines(source: Path): - if source.suffix.lower() in (".exe", ".dll"): - dumpbin = shutil.which("dumpbin") or next(iter(sorted(Path("C:/").glob(DUMPBIN_GLOB))), None) - if not dumpbin: - sys.exit("dumpbin.exe not found: run from a VS developer shell or install the MSVC build tools") - proc = subprocess.Popen([str(dumpbin), "/nologo", "/disasm:nobytes", str(source)], - stdout=subprocess.PIPE, text=True, errors="replace") - yield from proc.stdout - if proc.wait(): - sys.exit(f"dumpbin failed with exit code {proc.returncode}") - return - with open(source, encoding="utf-8", errors="replace") as f: - yield from f - - -def instructions(lines): - for line in lines: - m = LINE.match(line) - if m: - yield int(m.group(1), 16), m.group(2), m.group(3).strip() - - -def classify(window, base, stored): - """Look back from a store-back of `stored` into [base+18h]. Return a site dict or None.""" - chain, size, load, bases, broken = {stored}, 0, None, {base}, False - touched = {stored} # every register the cursor passed through, for counting stores - span = [] - for addr, mnem, ops in reversed(window): - if mnem == "ret" or (mnem == "mov" and (sb := STORE_BACK.match(ops)) and sb.group(1) in bases): - break # the previous site of this list, or the previous function - span.append((addr, mnem, ops)) - if mnem == "mov" and (cp := COPY.match(ops)) and cp.group(1) in bases: - bases.add(cp.group(2)) # `mov rbx,rcx`: the list is in both - if load is None and not broken: - if mnem == "mov" and (lm := LOAD.match(ops)) and lm.group(1) in chain and lm.group(2) in bases: - load = addr - elif mnem == "lea" and (le := LEA.match(ops)) and le.group(1) in chain: - chain.discard(le.group(1)) # defined here; older values of it are not the cursor - chain.add(le.group(2)) - touched.add(le.group(2)) - size += int(le.group(3), 16) - elif mnem == "add" and (am := ADD.match(ops)) and am.group(1) in chain: - size += int(am.group(2), 16) - elif ops.split(",", 1)[0] in chain and mnem not in ("cmp", "test") and not mnem.startswith("j"): - broken = True # the stored value was computed from something other than the cursor - span.reverse() - stores, header, limit, target, evidence = 0, None, None, None, False - limit_regs = {} # register -> limit offset, for `mov rdx,[list+30h]` ... `cmp rcx,rdx` - for i, (addr, mnem, ops) in enumerate(span): - if mnem == "mov" and (lr := LIMIT_LOAD.match(ops)) and lr.group(2) in bases and int(lr.group(3), 16) != 0x18: - limit_regs[lr.group(1)] = int(lr.group(3), 16) - if mnem == "cmp" and (rr := COPY.match(ops)) and (rr.group(1) in touched or rr.group(1) in limit_regs): - nxt = span[i + 1] if i + 1 < len(span) else None - if nxt and nxt[1] in UNSIGNED_JCC: - # the limit came from [list+X] here, or in a block that jumps to this one (REG_LIMIT) - limit = limit_regs.get(rr.group(2), limit_regs.get(rr.group(1), REG_LIMIT)) - if jt := JCC_TARGET.match(nxt[2]): - target = int(jt.group(1), 16) - if mnem.startswith(("mov", "vmov")) and (st := STORE.match(ops)) and st.group(1) in touched: - stores += 1 - imm = IMM.match(st.group(3)) - if header is None and not st.group(2) and imm and mnem == "mov": - header = int(imm.group(1), 16) - if (lf := LIST_FIELDS.search(ops)) and lf.group(1) in bases: - evidence = True - if mnem == "cmp" and (cm := CMP.match(ops)): - reg_base, disp = (cm.group(2), cm.group(3)) if cm.group(1) else (cm.group(4), cm.group(5)) - if reg_base in bases and int(disp, 16) != 0x18: - limit = int(disp, 16) - nxt = span[i + 1] if i + 1 < len(span) else None - if nxt and nxt[1].startswith("j") and nxt[1] != "jmp" and (jt := JCC_TARGET.match(nxt[2])): - target = int(jt.group(1), 16) - if not stores or base == "rsp": - return None - checked = limit is not None - # A guard-free list write must load the cursor from the list nearby; without that it is some other structure. - is_list = checked or (evidence and load is not None and not broken) - return {"load": load, "base": base, "checked": checked, "list": is_list, "limit": limit, "size": size, - "stores": stores, "header": header, "target": target, "fallback_slot": None, - "bases": bases, "load_traced": load is not None and not broken} - - -def scan(lines, stats=None): - """Yield one dict per cursor store-back site; fallback slots are filled in once the branch target is seen. - `stats["instructions"]` (if a dict is passed) counts the instructions read.""" - stats = {} if stats is None else stats - stats["instructions"] = 0 - window = collections.deque(maxlen=LOOKBACK) - pending, watching, tail = [], [], [] - for idx, (addr, mnem, ops) in enumerate(instructions(lines)): - stats["instructions"] = idx + 1 - for item in tail[:]: # list fields written right after the store-back (e.g. clearing +140h) count too - site, left = item - tail.remove(item) - if (lf := LIST_FIELDS.search(ops)) and lf.group(1) in site["bases"] and site["load_traced"]: - site["list"] = True - elif left > 1: - tail.append((site, left - 1)) - for item in watching[:]: - site, left = item - watching.remove(item) - if mnem == "call" and (vm := VCALL.match(ops)): - site["fallback_slot"] = int(vm.group(2), 16) // 8 - elif left > 1: - watching.append((site, left - 1)) - for item in pending[:]: - site, opened = item - if addr == site["target"]: - watching.append((site, FALLBACK_WINDOW)) - pending.remove(item) - elif idx - opened > PENDING_WINDOW: - pending.remove(item) - if mnem == "mov" and (sb := STORE_BACK.match(ops)): - site = classify(window, sb.group(1), sb.group(2)) - if site: - site["store_back"] = addr - if site["target"] is not None: - pending.append((site, idx)) - if not site["list"]: - tail.append((site, TAIL_WINDOW)) - yield site - window.append((addr, mnem, ops)) - - -def limit_text(limit): - return "none" if limit is None else "reg" if limit == REG_LIMIT else f"+0x{limit:x}" - - -def summarize(sites, instructions=None): - checked = [s for s in sites if s["checked"]] - unchecked = [s for s in sites if not s["checked"] and s["list"]] - unrelated = [s for s in sites if not s["list"]] - plain = lambda v: "none" if v is None else str(v) - out = [] if instructions is None else [f"instructions scanned: {instructions}"] - out += [f"list sites {len(checked) + len(unchecked)}: checked {len(checked)}, UNCHECKED {len(unchecked)} " - f"(plus {len(unrelated)} cursor-like stores with no list field nearby, likely other structures)"] - for title, key, group, fmt in (("limit offsets (checked)", "limit", checked, limit_text), - ("fallback vtable slots (checked)", "fallback_slot", checked, plain), - ("packet sizes, checked", "size", checked, plain), - ("packet sizes, unchecked", "size", unchecked, plain)): - hist = collections.Counter(s[key] for s in group) - out.append(f"{title}: " + ", ".join(f"{fmt(k)} x{n}" for k, n in hist.most_common(12))) - headers = collections.Counter(s["header"] for s in sites if s["header"] is not None) - out.append("header dwords: " + ", ".join(f"0x{h:08x} x{n}" for h, n in headers.most_common(12))) - return "\n".join(out) - - -def main() -> int: - p = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) - p.add_argument("source", type=Path) - p.add_argument("--base", type=lambda s: int(s, 16), help="image base (default: inferred from the first site)") - p.add_argument("--sites", action="store_true", help="print every site") - args = p.parse_args() - if not args.source.is_file(): - print(f"{args.source} not found", file=sys.stderr) - return 2 - stats = {} - sites = list(scan(read_lines(args.source), stats)) - if not stats["instructions"]: - print(f"{args.source}: no instructions found (not a dumpbin listing, or an image without code)", - file=sys.stderr) - return 2 - base = args.base if args.base is not None else min((s["store_back"] for s in sites), default=0) & ~0xFFFFFFF - print(summarize(sites, stats["instructions"])) - if args.sites: - rva = lambda a: "?" if a is None else f"+0x{a - base:x}" - for s in sites: - state = f"checked {limit_text(s['limit'])}" if s["checked"] else "UNCHECKED" if s["list"] else "unrelated" - header = "-" if s["header"] is None else f"0x{s['header']:08x}" - print(f" load {rva(s['load'])} store {rva(s['store_back'])} [{s['base']}] {state} size {s['size']} " - f"stores {s['stores']} header {header} fallback {s['fallback_slot']}") - return 0 - - -if __name__ == "__main__": - try: # a redirected stdout is strict ANSI code page under -I; write '?' for what it cannot encode - sys.stdout.reconfigure(errors="replace") - except (AttributeError, ValueError, OSError): - pass - sys.exit(main()) diff --git a/tools/instance_lists.py b/tools/instance_lists.py deleted file mode 100644 index 7504665c5..000000000 --- a/tools/instance_lists.py +++ /dev/null @@ -1,396 +0,0 @@ -"""Count and check the instanced props and grass in map resources (CMapData instancedData). - -Map resources (docs/world.md) can hold two more list structs besides CEntityDef. Their names are the -case-sensitive joaat of the GTA V class names, and the resource's own schema gives every member offset: - - 0xBA049770 rage__fwPropInstanceListDef (0x170): CEntityDef members, InstanceList @0x90, - BatchAABB @0xA0, ScaleRange @0x160, InstanceLodDist @0x168 - 0xEA6B3A96 rage__fwPropInstanceListDef__InstanceData (0x40): InstMat @0 (3x4 floats, translation in the last - column), Tint @0x34 - 0x7C475B5D rage__fwGrassInstanceListDef (0x1A0): CEntityDef members, BatchAABB @0x80, - ScaleRange @0xA0, LodFadeStartDist @0xB8, - InstanceLodDist @0xBC, OrientToTerrain @0xC0, - IsSLODList @0x150, InstanceList @0x178 - 0xED86F522 rage__fwGrassInstanceListDef__InstanceData (0x10): Position @0 (3 x u16 in BatchAABB), NormalX @6, - NormalY @7, Color @8 (3 bytes), Scale @0xB, ScaleZ @0xC, - RotationIdx @0xD - -Fields are read through the schema member table (by name hash), never at fixed offsets, and the tool counts how -often the schema agrees with the offsets above. An InstanceList is an array: a u64 pointer whose low 12 bits are -the 1-based block index and whose bits 20+ are the byte offset in that block, then a u16 count. The block table -entry places the block in the virtual (0x5...) or physical (0x6...) buffer of the resource; the buffers are the -first v and next p zlib streams of the resource, with v and p in the block map (+0x08 -> +8, +9). - -Only counts and aggregate checks are written. No position, matrix, name or other value leaves the tool. - -Usage: - python -I tools/instance_lists.py [...] [--start N] [--limit BYTES] [--json out.json] -""" -import argparse -import json -import math -import mmap -import os -import struct -import sys -import zlib - -sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) -import world_index as wi # noqa: E402 (same 0x7a header, schema and stream helpers) - -PROP_LIST, PROP_INST = 0xBA049770, 0xEA6B3A96 -GRASS_LIST, GRASS_INST = 0x7C475B5D, 0xED86F522 -STRUCT_SIZE = {PROP_LIST: 0x170, PROP_INST: 0x40, GRASS_LIST: 0x1A0, GRASS_INST: 0x10} -# member name -> joaat (case-sensitive), and the offset measured in the schema -M = { - "InstanceList": 0x1C080BB9, "BatchAABB": 0x6ECEBA6E, "ScaleRange": 0xA0664EE6, - "InstanceLodDist": 0xC0156D12, "LodFadeStartDist": 0x8419A4AA, "OrientToTerrain": 0xC72ADEFA, - "IsSLODList": 0x4579099D, "lodDist": 0xBF74DFA7, "lodLevel": 0x6C8F1715, "archetypeName": 0xA023A02C, - "InstMat": 0x7EE6CC43, "Tint": 0x2D5482DF, - "Position": 0x0C928991, "NormalX": 0xBB0B13F0, "NormalY": 0x1051BE7C, "Color": 0x4E036667, - "Scale": 0x3CBA3FE6, "ScaleZ": 0x2A728D38, "RotationIdx": 0xBA36796D, -} -EXPECTED = { - PROP_LIST: {"InstanceList": 0x90, "BatchAABB": 0xA0, "ScaleRange": 0x160, "InstanceLodDist": 0x168}, - PROP_INST: {"InstMat": 0x0, "Tint": 0x34}, - GRASS_LIST: {"BatchAABB": 0x80, "ScaleRange": 0xA0, "LodFadeStartDist": 0xB8, "InstanceLodDist": 0xBC, - "OrientToTerrain": 0xC0, "IsSLODList": 0x150, "InstanceList": 0x178}, - GRASS_INST: {"Position": 0x0, "NormalX": 0x6, "NormalY": 0x7, "Color": 0x8, "Scale": 0xB, "ScaleZ": 0xC, - "RotationIdx": 0xD}, -} - - -def add(d, k, v=1): - d[k] = d.get(k, 0) + v - - -def schema(V): - """(structs {name: (size, members)}, blocks [(name, size, pointer)]) of a 0x7a resource, or None.""" - if len(V) < 0x50 or V[0x10:0x14] != wi.SIGNATURE or V[0x14] != wi.VERSION: - return None - nst, nbl = wi._u16(V, 0x48), wi._u16(V, 0x4C) - st, it = wi._ptr(wi._u64(V, 0x28), len(V)), wi._ptr(wi._u64(V, 0x38), len(V)) - if st is None or it is None or st + 32 * nst > len(V) or it + 16 * nbl > len(V): - return None - structs = {} - for i in range(nst): - o = st + 32 * i - name, size, count = wi._u32(V, o), wi._u32(V, o + 0x18), wi._u16(V, o + 0x1E) - mem = wi._members(V, wi._ptr(wi._u64(V, o + 0x10), len(V)), count, len(V)) - if mem is None: - return None - structs.setdefault(name, (size, mem)) - blocks = [(wi._u32(V, it + 16 * i), wi._u32(V, it + 16 * i + 4), wi._u64(V, it + 16 * i + 8)) for i in range(nbl)] - return structs, blocks - - -def resolve(V, P, p): - """Byte offset and buffer of a 0x5/0x6 resource pointer.""" - if p >> 28 == 5: - off = p & 0x0FFFFFFF - return (V, off) if off < len(V) else (None, None) - if p >> 28 == 6: - off = p & 0x0FFFFFFF - return (P, off) if off < len(P) else (None, None) - return None, None - - -def array(V, P, blocks, base_buf, at): - """Follow a PSO array (u64 block pointer + u16 count) to (buffer, offset, count), or None.""" - p = struct.unpack_from("> 20) - return buf, off, count - - -def member(structs, name, field): - size, mem = structs.get(name, (0, {})) - m = mem.get(M[field]) - return m[0] if m else None - - -def member_or(structs, name, field, default): - off = member(structs, name, field) - return default if off is None else off - - -def measure(V, P, T): - sc = schema(V) - if sc is None: - return False - structs, blocks = sc - if PROP_LIST not in structs and GRASS_LIST not in structs: - return False - add(T, "resources_with_lists") - for sname, size_expected in STRUCT_SIZE.items(): - if sname in structs: - add(T.setdefault("struct_size_matches", {}), f"{sname:08x}", structs[sname][0] == size_expected) - for field, off in EXPECTED[sname].items(): - add(T.setdefault("member_offset_matches", {}), f"{sname:08x}.{field}", - member(structs, sname, field) == off) - for bname, bsize, bptr in blocks: - if bname not in (PROP_LIST, GRASS_LIST): - continue - lsize = structs.get(bname, (0,))[0] # a block the schema has no struct for is unresolved - buf, boff = resolve(V, P, bptr) - if buf is None or lsize == 0 or bsize % lsize: - add(T, "list_blocks_unresolved") - continue - for k in range(bsize // lsize): - lo = boff + k * lsize - if bname == PROP_LIST: - prop_list(V, P, blocks, structs, buf, lo, T.setdefault("prop", {})) - else: - grass_list(V, P, blocks, structs, buf, lo, T.setdefault("grass", {})) - return True - - -def _f(buf, at, n=1): - return struct.unpack_from(f"<{n}f", buf, at) - - -def list_common(structs, name, buf, lo, R): - add(R, "lists") - lvl = buf[lo + member(structs, name, "lodLevel")] if member(structs, name, "lodLevel") is not None else None - add(R.setdefault("lodLevel", {}), str(lvl)) - sr_at = member(structs, name, "ScaleRange") - if sr_at is not None: - smin, smax = _f(buf, lo + sr_at, 2) - add(R, "scale_range_ordered", int(0 < smin <= smax)) - ild = member(structs, name, "InstanceLodDist") - ld = member(structs, name, "lodDist") - if ild is not None and ld is not None: - a, b = _f(buf, lo + ild)[0], _f(buf, lo + ld)[0] - add(R, "instance_loddist_le_loddist", int(0 < a <= b)) - bb = member(structs, name, "BatchAABB") - box = None - if bb is not None: - mn, mx = _f(buf, lo + bb, 3), _f(buf, lo + bb + 16, 3) - if all(math.isfinite(x) for x in mn + mx) and all(mn[i] <= mx[i] for i in range(3)): - add(R, "aabb_valid") - box = (mn, mx) - return box - - -def prop_list(V, P, blocks, structs, buf, lo, R): - box = list_common(structs, PROP_LIST, buf, lo, R) - il = member(structs, PROP_LIST, "InstanceList") - ref = array(V, P, blocks, buf, lo + il) if il is not None else None - if ref == "empty": - add(R, "lists_empty") - return - if ref is None: - add(R, "lists_unresolved") - return - ib, io, n = ref - isz = structs.get(PROP_INST, (0x40, {}))[0] or 0x40 - mat = member_or(structs, PROP_INST, "InstMat", 0) - add(R, "instances", n) - for i in range(n): - o = io + i * isz - if mat < 0 or o + max(48, mat + 48) > len(ib): - add(R, "instances_truncated") - break - m = _f(ib, o + mat, 12) - cols = [(m[0], m[4], m[8]), (m[1], m[5], m[9]), (m[2], m[6], m[10])] - t = (m[3], m[7], m[11]) - lens = [math.sqrt(sum(c * c for c in col)) for col in cols] - if min(lens) <= 1e-6 or not all(math.isfinite(x) for x in m): - add(R, "matrix_degenerate") - continue - u = [[c / l for c in col] for col, l in zip(cols, lens)] - ortho = max(abs(sum(u[a][k] * u[b][k] for k in range(3))) for a, b in ((0, 1), (0, 2), (1, 2))) - det = (u[0][0] * (u[1][1] * u[2][2] - u[1][2] * u[2][1]) - u[0][1] * (u[1][0] * u[2][2] - u[1][2] * u[2][0]) - + u[0][2] * (u[1][0] * u[2][1] - u[1][1] * u[2][0])) - add(R, "matrix_orthonormal_axes", int(ortho < 0.01)) - add(R, "matrix_right_handed", int(det > 0)) - add(R, "matrix_uniform_scale", int(max(lens) - min(lens) < 0.01 * max(lens))) - add(R, "matrix_unit_scale", int(all(abs(x - 1) < 0.01 for x in lens))) - if box: - mn, mx = box - add(R, "translation_in_aabb", int(all(mn[k] - 0.01 <= t[k] <= mx[k] + 0.01 for k in range(3)))) - - -def grass_list(V, P, blocks, structs, buf, lo, R): - list_common(structs, GRASS_LIST, buf, lo, R) - for field, key in (("IsSLODList", "IsSLODList"),): - at = member(structs, GRASS_LIST, field) - if at is not None: - add(R.setdefault(key, {}), str(buf[lo + at])) - ot = member(structs, GRASS_LIST, "OrientToTerrain") - if ot is not None: - add(R.setdefault("OrientToTerrain", {}), repr(round(_f(buf, lo + ot)[0], 2))) - il = member(structs, GRASS_LIST, "InstanceList") - ref = array(V, P, blocks, buf, lo + il) if il is not None else None - if ref == "empty": - add(R, "lists_empty") - return - if ref is None: - add(R, "lists_unresolved") - return - ib, io, n = ref - isz = structs.get(GRASS_INST, (0x10, {}))[0] or 0x10 - nx, ny = member_or(structs, GRASS_INST, "NormalX", 6), member_or(structs, GRASS_INST, "NormalY", 7) - sz, rot = member_or(structs, GRASS_INST, "ScaleZ", 0xC), member_or(structs, GRASS_INST, "RotationIdx", 0xD) - sc = member_or(structs, GRASS_INST, "Scale", 0xB) - need = max(isz, nx + 1, ny + 1, sc + 1, sz + 1, rot + 1) - add(R, "instances", n) - rmax = 0 - for i in range(n): - o = io + i * isz - if min(nx, ny, sc, sz, rot) < 0 or o + need > len(ib): - add(R, "instances_truncated") - break - x, y = ib[o + nx] / 127.5 - 1, ib[o + ny] / 127.5 - 1 - add(R, "normal_xy_inside_unit_disc", int(x * x + y * y <= 1.0 + 2 / 127.5)) - add(R, "scale_zero", int(ib[o + sc] == 0)) - add(R, "scalez_equals_scale", int(ib[o + sz] == ib[o + sc])) - rmax = max(rmax, ib[o + rot]) - R["rotation_idx_max"] = max(R.get("rotation_idx_max", 0), rmax) - - -def resource_buffers(m, s, size): - """The virtual and physical buffers of the resource whose first stream starts at s.""" - data, used, eof, _ = wi._inflate_stream(m, s, size, 64 << 20, keep=True) - if not eof or len(data) < 0x20: - return None, None, max(used, 1) - bm = wi._ptr(wi._u64(data, 8), len(data)) - if bm is None or bm + 10 > len(data): - return data, b"", used - vc, pc = max(1, data[bm + 8]), data[bm + 9] - parts, total, pos = [data], used, s + used - for _ in range(vc + pc - 1): - nxt = (pos + 15) & ~15 - if nxt >= size or not wi.ZHDR.match(m, nxt, size): - break - more, mused, meof, _ = wi._inflate_stream(m, nxt, size, 64 << 20, keep=True) - if not meof: - break - parts.append(more) - total = nxt + mused - s - pos = nxt + mused - V = b"".join(parts[:vc]) - P = b"".join(parts[vc:vc + pc]) - return V, P, total - - -def scan(path, T, start=None, limit=None): - with open(path, "rb") as f: - if os.fstat(f.fileno()).st_size < 8: - raise ValueError(f"{path}: not an RPF9 archive") - with mmap.mmap(f.fileno(), 0, access=mmap.ACCESS_READ) as m: - size = len(m) - if m[:4] not in (b"RPF9", b"9FPR"): - raise ValueError(f"{path}: not an RPF9 archive") - data_start = wi._u32(m[:8], 4) - if not 8 <= data_start <= size: - raise ValueError(f"{path}: RPF9 data start is outside the archive") - if start is not None and not data_start <= start < size: - raise ValueError(f"--start 0x{start:x} is outside the data area of {path}") - pos = start if start is not None else data_start - end = min(size, pos + limit) if limit is not None else size - while pos < end: - found = wi.ZHDR.search(m, pos, end) - if not found: - break - s = found.start() - if s % 16: - pos = s + 1 - continue - try: - head = zlib.decompressobj().decompress(m[s:s + 4096], 0x15) - except zlib.error: - pos = s + 1 - continue - if head[0x10:0x15] != b"0DRPz": - pos = s + 1 - continue - try: - V, P, used = resource_buffers(m, s, size) - except zlib.error: - pos = s + 1 - continue - add(T, "map_resources_read") - if V is not None: - try: - measure(V, P, T) - except (struct.error, IndexError): - add(T, "resources_truncated") - pos = s + max(used, 1) - - -def same_output_path(first, second): - if os.path.normcase(os.path.realpath(first)) == os.path.normcase(os.path.realpath(second)): - return True - try: - return os.path.samefile(first, second) - except OSError: - return False - - -def _int_arg(text): - try: - return int(text, 0) - except ValueError: - raise argparse.ArgumentTypeError(f"invalid int value: {text!r}") from None - - -def main(argv=None): - ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) - ap.add_argument("inputs", nargs="+", help=".rpf archives") - ap.add_argument("--start", type=_int_arg) - ap.add_argument("--limit", type=_int_arg) - ap.add_argument("--json") - args = ap.parse_args(argv) - if args.start is not None and args.start < 0: - print("error: --start must be >= 0", file=sys.stderr) - return 2 - if args.limit is not None and args.limit <= 0: - print("error: --limit must be > 0", file=sys.stderr) - return 2 - # The report is written after the whole scan, so check its path first: an archive given as --json used to be - # replaced by the report (exit 0), and a directory ended the run in a traceback. - if args.json: - if os.path.isdir(args.json): - print(f"error: --json {args.json} is a directory", file=sys.stderr) - return 2 - for path in args.inputs: - if same_output_path(args.json, path): - print(f"error: --json would overwrite the input {path}", file=sys.stderr) - return 2 - T = {} - for path in args.inputs: - if not os.path.isfile(path): - print(f"error: {path} is not a file", file=sys.stderr) - return 2 - try: - scan(path, T, args.start, args.limit) - except (ValueError, OSError) as exc: - print(f"error: {exc}", file=sys.stderr) - return 2 - print(json.dumps(T, indent=1, sort_keys=True)) - if args.json: - try: - os.makedirs(os.path.dirname(os.path.abspath(args.json)), exist_ok=True) - with open(args.json, "w", encoding="utf-8", newline="\n") as fh: - json.dump(T, fh, indent=1, sort_keys=True) - except OSError as exc: - print(f"error: cannot write {args.json}: {exc.strerror or exc}", file=sys.stderr) - return 2 - return 0 - - -if __name__ == "__main__": - try: # a redirected stdout is strict ANSI code page under -I; write '?' for what it cannot encode - sys.stdout.reconfigure(errors="replace") - except (AttributeError, ValueError, OSError): - pass - sys.exit(main()) diff --git a/tools/int3_cause.py b/tools/int3_cause.py deleted file mode 100644 index 1001b150a..000000000 --- a/tools/int3_cause.py +++ /dev/null @@ -1,922 +0,0 @@ -"""Name the call whose result sends an x86-64 PE image to a given int3, from the file alone. - -Usage: - python -I tools/int3_cause.py
[
...] [--json] - python -I tools/int3_cause.py --any
... # any instruction, e.g. a `return 0` path - python -I tools/int3_cause.py --returns
... # what the function holding it returns - -A boot that stops on a title assertion reports where it stopped. LEONIDA_SKIP_ASSERTS, LEONIDA_SKIP_INT3 and the -fault log give the `int3` as `exe+0x...`, `game+0x...`, an RVA or a virtual address. What failed is the call whose -result the title tested before it branched there. That branch is often far from the `int3`, in another part of the -function, so the test is not in sight of the stop. This finds it, with nothing run: - -1. The stop. The instruction at the address must be `int3`, `ud2` or `int 29h`. An address one past an `int3` is - taken as that `int3`, because Wine reports a breakpoint after the instruction. -2. The doomed code. The function that holds the stop (its `.pdata` entry) is decoded from its start with - tools/gdk_runtime_calls.py's decoder. An instruction is doomed when every way on from it reaches the stop without - a return. That covers straight-line code, a jump to doomed code, and a conditional jump whose two sides are both - doomed. Calls are taken to return. -3. The guards. A conditional jump with one side doomed and the other not is where the title decided to stop. Jumps - into the doomed code from other functions count too. They are rel32 `jmp`/`jcc`, found by byte pattern and kept - only when decoding their own function from its start lands on them. An unconditional jump from another function - is followed into that function the same way. -4. The condition. The last instruction before the guard that sets the flags is read, skipping the moves, `lea`s and - other flag-neutral instructions in between. The forms read are `test r, r`, `test r, imm`, `cmp r, imm` and - `cmp r, r`, each also with one memory operand, plus `and` (read as `test`), `sub` (as `cmp`) and `bt`. The - condition is written as what takes the doomed side: `eax < 0`, `al == 0`, `ecx != 1`, `bit 5 of eax is set`, - with `u` for unsigned comparisons. -5. The call. From the flag-setting instruction, each tested register is followed back through register copies to - what wrote it, and the result of a call (`rax`) is named: - - an import (`dll!Name`, through its thunk or its address-table slot); - - a vtable slot (`call [reg+disp]` is slot disp/8), with `this` noted when it was loaded from a global; - - a function of the image, by RVA. - A register loaded from memory, set to a constant or computed is reported as such. A copy, a `lea r, [r2+disp]` - or an added constant is followed through. A block that follows a return or a jump is entered through the one - jump that reaches it. A register nothing wrote since the function start is one of its arguments (rcx, rdx, r8, - r9). The function's direct call sites are then read for what each passes in it, as a tally ("argument 1 at the - function's 53 call sites: 5 the result of vtable slot 133, ..."). For a load, the pointer register is followed - too. A value read from a global, or from a field of an object a global points to, is read at the global's - stores, each `mov [rip+x], r` or `mov [rip+x], imm` to it, with what it stores (the call that set it, or 0). -6. A function whose start is doomed never returns. Each of its direct call sites is then read the same way, as if - the call were the stop. Steps 3 and 6 go at most 3 functions away from the stop. - -With `--any` the address may be any instruction, for example the `xor eax, eax` of a `return 0` path or the start of -a fallback. Steps 2 to 5 then name the branches that decide whether it runs, and step 6 is skipped. With -`--returns` the address may be anywhere in a function. Each value the function can return in rax (a constant with -its value, a call's result, an argument, a load) is found over the paths into each `ret` that the bounded search -recovers (up to a step and source limit; the report says when it stopped there), through register copies. -For each value, the instruction that sets it is read as with `--any`. A function that returns through a tail jump -is not read past the jump. - -What it does not see: -- a stop reached through a jump table or a function pointer; -- a condition set by an instruction outside the forms in 4 (it names the instruction's RVA instead); -- a value that came through the stack. - -Output is for local reading: it carries RVAs. What a run shares is the call's name and the condition -(docs/runtime_imports.md, "The retail executable (RT-5)"). Exit status 0 when every address is a stop the tool could -read, 1 when one is not, 2 when the image can't be read. Standard library only. -""" -from __future__ import annotations - -import argparse -import bisect -import json -import os -import re -import struct -import sys -from array import array - -ROOT = os.path.dirname(os.path.abspath(__file__)) -if ROOT not in sys.path: - sys.path.insert(0, ROOT) -from gdk_runtime_calls import R8, R9, RAX, RCX, RDX, RIP, RSP, VOLATILE, Code, writes # noqa: E402 -from import_call_sites import import_slots # noqa: E402 -import pe_inspect # noqa: E402 - -DEPTH = 3 # functions away from the stop that jumps in and callers are followed -TRACE_BACK = 48 # instructions walked back from a test to what wrote its register -FLAGS_BACK = 8 # instructions walked back from a guard to the instruction that set its flags -MAX_LINKS = 16 # jumps in or call sites followed per function -MAX_SITES = 256 # call sites read for an argument the stop depends on -MAX_STORES = 64 # stores read per global the stop depends on -_RIP_STORE = re.compile(rb"[\x88\x89\xc6\xc7][\x05\x0d\x15\x1d\x25\x2d\x35\x3d]") -_REL32 = re.compile(rb"\xe8|\xe9|\x0f[\x80-\x8f]") -_REL32_KINDS = ("call", "jmp", "jcc") -ARGUMENTS = {RCX: 1, RDX: 2, R8: 3, R9: 4} - -JCC = ("jo", "jno", "jb", "jae", "je", "jne", "jbe", "ja", "js", "jns", "jp", "jnp", "jl", "jge", "jle", "jg") -# Taken-when of a jcc after `cmp a, b`, as `a b`. -CMP_REL = {0x2: "=u", 0x4: "==", 0x5: "!=", 0x6: "<=u", 0x7: ">u", 0xC: "<", 0xD: ">=", 0xE: "<=", - 0xF: ">"} -# After `test a, b` (also `and`): CF = OF = 0, so a condition on the sign and zero of a & b. -SELF_TEST = {0x4: "== 0", 0x5: "!= 0", 0x6: "== 0", 0x7: "!= 0", 0x8: "< 0", 0x9: ">= 0", 0xC: "< 0", 0xD: ">= 0", - 0xE: "<= 0", 0xF: "> 0"} - -NAMES64 = ("rax", "rcx", "rdx", "rbx", "rsp", "rbp", "rsi", "rdi") + tuple(f"r{n}" for n in range(8, 16)) -NAMES32 = ("eax", "ecx", "edx", "ebx", "esp", "ebp", "esi", "edi") + tuple(f"r{n}d" for n in range(8, 16)) -NAMES16 = ("ax", "cx", "dx", "bx", "sp", "bp", "si", "di") + tuple(f"r{n}w" for n in range(8, 16)) -NAMES8 = ("al", "cl", "dl", "bl", "spl", "bpl", "sil", "dil") + tuple(f"r{n}b" for n in range(8, 16)) -PREFIXES = frozenset((0x26, 0x2E, 0x36, 0x3E, 0x64, 0x65, 0x66, 0x67, 0xF0, 0xF2, 0xF3)) - -# Instructions that leave the flags alone (opcode numbering as in gdk_runtime_calls.decode). -_NEUTRAL = frozenset([0x63, 0x86, 0x87, 0x88, 0x89, 0x8A, 0x8B, 0x8D, 0x8F, 0x90, 0x98, 0x99, 0xA4, 0xA5, 0xAA, - 0xAB, 0xC6, 0xC7, *range(0x50, 0x60), *range(0xB0, 0xC0), *range(0x110, 0x118), 0x118, 0x11F, - 0x128, 0x129, *range(0x140, 0x150), *range(0x16E, 0x170), 0x17E, 0x17F, - *range(0x190, 0x1A0), 0x1B6, 0x1B7, 0x1BE, 0x1BF, 0x1D6, 0x1E7]) -# VEX forms that set the flags: vucomis*/vcomis*, vtestp*, vptest, andn, blsr/blsmsk/blsi, bzhi, bextr. -_VEX_FLAGS = frozenset((0x112E, 0x112F, 0x120E, 0x120F, 0x1217, 0x12F2, 0x12F3, 0x12F5, 0x12F7)) -COPY_OPS = frozenset((0x8A, 0x8B, 0x63, 0x1B6, 0x1B7, 0x1BE, 0x1BF)) # r <- r/m -LOAD_OPS = COPY_OPS - - -class Image: - def __init__(self, data: bytes): - self.img = pe_inspect.PeImage(data) - self.code = Code(self.img) - self.slots = import_slots(self.img) - self._runs = {} - self._flows = {} - self._rel32 = None # sorted target << shift | rva << 2 | kind, for every rel32 call/jmp/jcc pattern - self._stores = None # sorted target << shift | rva, for every `mov [rip+x], r/imm` pattern - # Room for any RVA of the image (code targets and globals alike), plus two bits for the kind. - ends = [self.img.size_of_image] + [b + len(d) for b, d in self.code.sections] - self._shift = max(ends).bit_length() + 2 - - # ---- decoding ---- - - def raw(self, insn) -> bytes: - data, base = self.code.view(insn.rva) - return bytes(data[insn.rva - base:insn.end - base]) if data is not None else b"" - - def function(self, rva: int): - return self.code.function(rva) - - def run(self, func): - """The function's instructions from its start, as far as decoding goes (up to its end).""" - if func not in self._runs: - out, rva = [], func[0] - while rva < func[1]: - insn = self.code.decode(rva) - if insn is None: - break - out.append(insn) - rva = insn.end - self._runs[func] = out - return self._runs[func] - - def flow(self, func): - """(instructions, {rva: index}, {rva: [index of each jump to it]}) of the function.""" - if func not in self._flows: - insns = self.run(func) - into = {} - for n, i in enumerate(insns): - if (is_jcc(i) or is_jmp(i)) and i.target is not None: - into.setdefault(i.target, []).append(n) - self._flows[func] = (insns, {i.rva: n for n, i in enumerate(insns)}, into) - return self._flows[func] - - def lands_on(self, func, rva: int) -> bool: - return rva in self.flow(func)[1] - - # ---- indexes: one pass over the code, built on first use, then a bisect per target ---- - # - # Each entry packs (target, rva, kind) into one integer that sorts by target, then rva, so a lookup is a bisect - # on the target's range and the results come out in address order, as a scan would find them. Matches are the - # same non-overlapping regex matches a scan sees; a pattern that is not really an instruction is dropped later, - # when the caller checks that decoding the function lands on it. - - def _lookup(self, index: array, target: int): - lo = bisect.bisect_left(index, target << self._shift) - hi = bisect.bisect_left(index, (target + 1) << self._shift) - return index[lo:hi] - - def rel32_from(self, target: int): - """[(rva, kind)] of each rel32 call/jmp/jcc pattern aimed at target, in address order.""" - if self._rel32 is None: - limit, shift, entries = 1 << (self._shift - 2), self._shift, [] - for base, data in self.code.sections: - end = len(data) - 4 - for m in _REL32.finditer(data): - at = m.end() - if at > end: - continue - to = base + at + 4 + struct.unpack_from("> 2 & mask, _REL32_KINDS[e & 3]) for e in self._lookup(self._rel32, target)] - - def stores_to(self, target: int): - """RVAs of each `mov [rip+x], r/imm` pattern (its opcode) storing to target, in address order.""" - if self._stores is None: - limit, shift, entries = 1 << (self._shift - 2), self._shift, [] - for base, data in self.code.sections: - for m in _RIP_STORE.finditer(data): - op = data[m.start()] - if op in (0xC6, 0xC7) and data[m.start() + 1] != 0x05: - continue - at = m.end() - if at + 4 > len(data): - continue - end = at + 4 + {0xC6: 1, 0xC7: 4}.get(op, 0) - to = base + end + struct.unpack_from("= 0 - and insn.disp % 8 == 0): - out = {"slot": insn.disp // 8} - for prev in reversed(insns[max(0, k - 12):k]): - if RCX in writes(prev): - if prev.op == 0x8B and prev.base == RIP: - out["this_global"] = prev.target - break - if prev.ends_flow() or prev.is_call(): - break - return out - return {"indirect": True} - - -def stop_at(image: Image, rva: int): - """(rva, kind) of the int3, ud2 or int 29h at rva, or one byte before it (Wine), else None.""" - for at in (rva, rva - 1): - insn = image.code.decode(at) - if insn is None: - continue - if insn.op == 0xCC: - return at, "int3" - if at == rva and insn.op == 0x10B: - return at, "ud2" - if at == rva and insn.op == 0xCD and image.raw(insn)[-1:] == b"\x29": - return at, "int 29h" - return None - - -def is_jcc(insn) -> bool: - return 0x70 <= insn.op <= 0x7F or 0x180 <= insn.op <= 0x18F or 0xE0 <= insn.op <= 0xE3 - - -def is_jmp(insn) -> bool: - return insn.op in (0xE9, 0xEB) - - -def doomed_code(insns, seeds: set[int]) -> set[int]: - """The RVAs of the instructions from which every way on reaches one of `seeds` without a return.""" - doomed = set(seeds) - changed = True - while changed: - changed = False - for insn in reversed(insns): - if insn.rva in doomed: - continue - if is_jcc(insn): - hit = insn.target in doomed and insn.end in doomed - elif is_jmp(insn): - hit = insn.target in doomed - elif insn.ends_flow() or insn.op in (0xCC, 0xCD, 0x10B): - hit = False - else: - hit = insn.end in doomed - if hit: - doomed.add(insn.rva) - changed = True - return doomed - - -def width(raw: bytes, insn) -> int: - if insn.op in (0x84, 0x80, 0x20, 0x22, 0x24, 0x28, 0x2A, 0x2C, 0x38, 0x3A, 0x3C, 0xA8, 0xF6): - return 8 - if insn.wide: - return 64 - for b in raw: - if b == 0x66: - return 16 - if b not in PREFIXES: - break - return 32 - - -def reg_name(reg: int, bits: int, rex: int) -> str: - if bits == 8 and not rex and 4 <= reg <= 7: - return ("ah", "ch", "dh", "bh")[reg - 4] - return {8: NAMES8, 16: NAMES16, 32: NAMES32, 64: NAMES64}[bits][reg] - - -def gpr(reg: int, bits: int, rex: int) -> int: - """The full register an operand is part of (ah..bh are rax..rbx without a REX prefix).""" - return reg - 4 if bits == 8 and not rex and 4 <= reg <= 7 else reg - - -def memory_name(insn, bits: int) -> str: - size = {8: "byte", 16: "word", 32: "dword", 64: "qword"}[bits] - if insn.base == RIP: - return f"{size} [global {insn.target:#x}]" - base = NAMES64[insn.base] if insn.base is not None else "" - index = f"+{NAMES64[insn.index]}*n" if insn.index is not None else "" - disp = f"{insn.disp:+#x}" if insn.disp else "" - return f"{size} [{base}{index}{disp}]" - - -def immediate(raw: bytes, size: int) -> int: - return struct.unpack_from({1: " str: - return str(value) if -10 < value < 10 else (f"-{-value:#x}" if value < 0 else f"{value:#x}") - - -# ALU forms read as a test: `and` as `test` ("mask"), `sub` as `cmp`. op r/m, r | op r, r/m | op al/eax, imm | /n -_ALU_FORMS = {0x20: ("mask", "rm"), 0x21: ("mask", "rm"), 0x22: ("mask", "reg"), 0x23: ("mask", "reg"), - 0x84: ("mask", "rm"), 0x85: ("mask", "rm"), - 0x28: ("cmp", "rm"), 0x29: ("cmp", "rm"), 0x2A: ("cmp", "reg"), 0x2B: ("cmp", "reg"), - 0x38: ("cmp", "rm"), 0x39: ("cmp", "rm"), 0x3A: ("cmp", "reg"), 0x3B: ("cmp", "reg")} -_ACC_FORMS = {0x24: "mask", 0x25: "mask", 0xA8: "mask", 0xA9: "mask", 0x2C: "cmp", 0x2D: "cmp", 0x3C: "cmp", - 0x3D: "cmp"} -_GROUP1 = {4: "mask", 5: "cmp", 7: "cmp"} # 80/81/83 /4 and, /5 sub, /7 cmp - - -def read_test(insn, raw: bytes): - """The test or comparison insn makes, as {form, left, right, bits, registers}: form "self" (`test r, r`), "mask" - (`test`/`and`) or "cmp" (`cmp`/`sub`); left and right as text (right an int for an immediate); registers the - general registers it reads. None for any other instruction. raw is the instruction's bytes.""" - op, bits = insn.op, width(raw, insn) - mask = (1 << bits) - 1 - - def rm(): - if insn.mod == 3: - return reg_name(insn.rm, bits, insn.rex), [gpr(insn.rm, bits, insn.rex)] - regs = [r for r in (insn.base, insn.index) if r is not None and r != RIP] - return memory_name(insn, bits), regs - - def reg(): - return reg_name(insn.reg, bits, insn.rex), [gpr(insn.reg, bits, insn.rex)] - - def imm(size): - value = immediate(raw, size) - return value & mask if form == "mask" else value - - if op in _ALU_FORMS: - form, first = _ALU_FORMS[op] - if insn.mod == 3 and insn.rm == insn.reg and form == "mask": - name, regs = reg() - return {"form": "self", "left": name, "right": None, "bits": bits, "registers": regs} - (a, ra), (b, rb) = (rm(), reg()) if first == "rm" else (reg(), rm()) - return {"form": form, "left": a, "right": b, "bits": bits, "registers": ra + rb} - if op in _ACC_FORMS: - form = _ACC_FORMS[op] - size = 1 if bits == 8 else (2 if bits == 16 else 4) - return {"form": form, "left": reg_name(RAX, bits, insn.rex), "right": imm(size), "bits": bits, - "registers": [RAX]} - if op in (0x80, 0x81, 0x83) and insn.reg & 7 in _GROUP1: - form = _GROUP1[insn.reg & 7] - size = 1 if op in (0x80, 0x83) else (2 if bits == 16 else 4) - left, regs = rm() - return {"form": form, "left": left, "right": imm(size), "bits": bits, "registers": regs} - if op == 0x1A3 or (op == 0x1BA and insn.reg & 7 == 4): # bt r/m, r | bt r/m, imm8 - left, regs = rm() - if op == 0x1A3: - right, more = reg() - return {"form": "bit", "left": left, "right": right, "bits": bits, "registers": regs + more} - return {"form": "bit", "left": left, "right": immediate(raw, 1), "bits": bits, "registers": regs} - if op in (0xF6, 0xF7) and insn.reg & 7 == 0: - form = "mask" - size = 1 if op == 0xF6 else (2 if bits == 16 else 4) - left, regs = rm() - return {"form": form, "left": left, "right": imm(size), "bits": bits, "registers": regs} - return None - - -def condition(test, cc: int): - """The condition under which a jcc with condition code cc is taken after `test`, as text, or None.""" - form, left, right, bits = test["form"], test["left"], test["right"], test["bits"] - if form == "bit": # bt: CF is the bit - return {0x2: f"bit {right} of {left} is set", 0x3: f"bit {right} of {left} is clear"}.get(cc) - if form in ("self", "mask"): - rel = SELF_TEST.get(cc) - if rel is None: - return None - if form == "self": - return f"{left} {rel}" - right = f"{right:#x}" if isinstance(right, int) else right - return f"({left} & {right}) {rel}" - rel = CMP_REL.get(cc) - if rel is None: - return None - if isinstance(right, int): - right = f"{right & ((1 << bits) - 1):#x}" if rel.endswith("u") else show(right) - return f"{left} {rel} {right}" - - -def flags_setter(insns, k): - """Index of the instruction that set the flags insns[k] (a jcc) reads, or None when a call, a branch or the - function start comes first.""" - for j in range(k - 1, max(-1, k - 1 - FLAGS_BACK), -1): - insn = insns[j] - if insn.is_call() or insn.ends_flow(): - return None - if is_jcc(insn) or insn.op in _NEUTRAL or (insn.op >= 0x1000 and insn.op not in _VEX_FLAGS) or ( - insn.op in (0xF6, 0xF7) and insn.reg & 7 == 2): - continue - return j - return None - - -def step(image: Image, func, i: int, reg: int, level: int): - """What instruction i of the function does to `reg`, walking back: None when it leaves it alone, - ("follow", register, how) for a copy (how "copied") or an offset (how "derived"), ("result", report, tag) when - it is where the value comes from (tag False for a report that is not about the value).""" - insns = image.flow(func)[0] - insn = insns[i] - if insn.is_call(): - if reg == RAX: - return "result", {"call": insn.rva, **image.call_name(insns, i)}, True - if reg in VOLATILE: - return "result", {"value": "clobbered by a call", "at": insn.rva}, False - return None - if reg not in writes(insn): - return None - if insn.mod == 3 and insn.op in COPY_OPS: - return "follow", insn.rm, "copied" if insn.rm != reg else None - if insn.mod == 3 and insn.op in (0x88, 0x89): - return "follow", insn.reg, "copied" if insn.reg != reg else None - if insn.op == 0x8D and insn.base not in (None, RIP) and insn.index is None: - return "follow", insn.base, "derived" - if insn.op in (0x81, 0x83) and insn.mod == 3 and insn.reg & 7 in (0, 5) and insn.rm == reg: - return "follow", reg, "derived" - if insn.op in LOAD_OPS and insn.mod != 3: - out = {"value": "loaded from memory", "at": insn.rva, "from": memory_name(insn, 64 if insn.wide else 32)} - if insn.base == RIP: - out["global"] = insn.target - elif insn.base == RSP: - out["value"] = "loaded from a stack slot" - elif insn.base not in (None, RIP) and level < 2: - out["base"] = {"register": NAMES64[insn.base], **trace(image, func, i, insn.base, level + 1)} - return "result", out, True - if (insn.op in (0x30, 0x31, 0x32, 0x33) and insn.mod == 3 and insn.reg == insn.rm) or ( - 0xB0 <= insn.op <= 0xBF) or (insn.op in (0xC6, 0xC7) and insn.mod == 3): - raw = image.raw(insn) - if insn.op in (0x30, 0x31, 0x32, 0x33): - value = 0 - elif insn.op < 0xB8 or insn.op == 0xC6: - value = struct.unpack_from(" bool: - """Whether instruction i - 1 falls through to instruction i.""" - return i > 0 and not (insns[i - 1].ends_flow() or insns[i - 1].op in (0xCC, 0x10B)) - - -def trace(image: Image, func, k: int, reg: int, level: int = 0): - """What wrote `reg` before the instruction at index k of the function. Followed back through register copies, - `lea r, [r2+disp]` and adding a constant (marked derived), and into a block through the one jump that reaches - it; a register no instruction wrote since the function start is an argument (rcx, rdx, r8, r9). For a load, - the pointer register is traced too (two levels).""" - insns, _, into = image.flow(func) - copied = derived = False - i = k - for _ in range(TRACE_BACK): - if i == 0: - return with_how(entry_value(reg), copied, derived) - if not falls_into(insns, i): - ways = into.get(insns[i].rva, []) - if len(ways) != 1: - return {"value": "not found: the block it is in is reached by " - + ("several jumps" if ways else "no jump this tool read")} - i = ways[0] # the jump writes nothing; go on before it - continue - i -= 1 - r = step(image, func, i, reg, level) - if r is None: - continue - if r[0] == "follow": - reg = r[1] - copied, derived = copied or r[2] == "copied", derived or r[2] == "derived" - continue - return with_how(r[1], copied, derived) if r[2] else r[1] - return {"value": "not found within the instructions read"} - - -def trace_paths(image: Image, func, k: int, reg: int, budget: int = 4000, limit: int = 64): - """The sources of `reg` before the instruction at index k, over the paths into it the search recovers (each - instruction and register visited once, up to `budget` steps and `limit` sources).""" - insns, _, into = image.flow(func) - found, seen, stack, steps = [], set(), [(k, reg, False, False)], 0 - while stack and steps < budget and len(found) < limit: - i, reg, copied, derived = stack.pop() - steps += 1 - ways = ([i - 1] if falls_into(insns, i) else []) + into.get(insns[i].rva, []) - if i == 0: - found.append(with_how(entry_value(reg), copied, derived)) - elif not ways: - found.append({"value": "not found: no way into this block was read"}) - for p in ways: - if (p, reg) in seen: - continue - seen.add((p, reg)) - r = step(image, func, p, reg, 0) - if r is None: - stack.append((p, reg, copied, derived)) - elif r[0] == "follow": - stack.append((p, r[1], copied or r[2] == "copied", derived or r[2] == "derived")) - else: - found.append(with_how(r[1], copied, derived) if r[2] else r[1]) - out, keys = [], set() - for r in found: - key = (r.get("at", r.get("call")), r["value"] if "value" in r else "call") - if key not in keys: - keys.add(key) - out.append(r) - return {"sources": out, "complete": not stack} - - -def guard(image: Image, func, k: int, taken: bool): - """The guard at index k of the function: its condition for the doomed side and what the tested registers - hold.""" - insns = image.flow(func)[0] - insn = insns[k] - cc = insn.op & 0xF - out = {"branch": insn.rva, "jump": JCC[cc] if insn.op < 0xE0 or insn.op >= 0x100 else "loop/jrcxz", - "doomed_side": "taken" if taken else "fall-through"} - j = flags_setter(insns, k) if insn.op < 0xE0 or insn.op >= 0x100 else None - if j is None: - out["condition"] = None - out["note"] = "no flag-setting instruction found before the branch" - return out - test = read_test(insns[j], image.raw(insns[j])) - out["flags_at"] = insns[j].rva - if test is None: - out["condition"] = None - out["note"] = "the flags come from an instruction this tool does not read" - return out - out["condition"] = condition(test, cc if taken else cc ^ 1) - out["registers"] = [{"register": NAMES64[r], **trace(image, func, j, r)} - for r in dict.fromkeys(test["registers"])] - return out - - -def rel32_sources(image: Image, targets: set[int], skip): - """RVAs of `jmp rel32`, `jcc rel32` and `call rel32` in executable sections whose target is in `targets`, - outside the range `skip`, each with its kind.""" - found = [(rva, kind, target) for target in targets for rva, kind in image.rel32_from(target) - if not (skip[0] <= rva < skip[1])] - return sorted(found) - - -def global_writers(image: Image, target: int): - """Each `mov [rip+x], r` / `mov [rip+x], imm` storing to the global at `target`, with what it stores.""" - found = [] - for at in image.stores_to(target): - for back in (0, 1, 2): # the opcode, or a REX / 66 prefix before it - rva = at - back - func = image.function(rva) - if func is not None and image.lands_on(func, rva): - found.append((rva, func)) - break - out = [] - for rva, func in found[:MAX_STORES]: - k = image.flow(func)[1][rva] - insn = image.flow(func)[0][k] - if insn.op in (0xC6, 0xC7): - raw = image.raw(insn) - value = immediate(raw, 1 if insn.op == 0xC6 else (2 if width(raw, insn) == 16 else 4)) - src = {"value": "a constant", "constant": value} - else: - src = trace(image, func, k, insn.reg) - out.append({"at": rva, "function": list(func), "source": src}) - return {"global": target, "writers": out, "writers_not_read": max(0, len(found) - MAX_STORES)} - - -def argument_sources(image: Image, func, numbers): - """For each argument number, what each direct call site of the function passes in it.""" - sites = [rva for rva, kind, _ in rel32_sources(image, {func[0]}, func) if kind == "call"] - out = [] - for rva in sites[:MAX_SITES]: - caller = image.function(rva) - if caller is None or not image.lands_on(caller, rva): - continue - k = image.flow(caller)[1][rva] - for n in numbers: - reg = next(r for r, m in ARGUMENTS.items() if m == n) - out.append({"at": rva, "caller": list(caller), "passed_as": n, "source": trace(image, caller, k, reg)}) - return {"sites": out, "sites_not_read": max(0, len(sites) - MAX_SITES)} - - -def explain(image: Image, seed: int, depth: int, seen: set, stop: bool = True): - """Report for a stop (or a call that does not return, or a jump into doomed code) at `seed`. With stop False, - seed is any instruction (`--any`): the guards decide whether it runs, and callers are not followed.""" - func = image.function(seed) - if func is None: - return {"at": seed, "function": None, "note": "no .pdata entry holds it"} - insns = image.run(func) - if not image.lands_on(func, seed): - return {"at": seed, "function": list(func), "note": "decoding from the function start does not land on it"} - doomed = doomed_code(insns, {seed}) - out = {"at": seed, "function": list(func), "guards": [], "jumps_in": [], "callers": []} - for k, insn in enumerate(insns): - if is_jcc(insn): - t, f = insn.target in doomed, insn.end in doomed - if t != f: - out["guards"].append(guard(image, func, k, t)) - out["never_returns"] = stop and func[0] in doomed - if not stop: - out["any"] = True - out["reached_from_start"] = func[0] in doomed - if depth <= 0 or func in seen: - return out - seen = seen | {func} - numbers = sorted({r["argument"] for g in out["guards"] for r in g.get("registers", []) - if r.get("value") == "argument"}) - if numbers: - out["arguments"] = argument_sources(image, func, numbers) - globals_read = [] - for g in out["guards"]: - for r in g.get("registers", []): - while r is not None: - if "global" in r and r["global"] not in globals_read: - globals_read.append(r["global"]) - r = r.get("base") - if globals_read: - out["globals"] = [global_writers(image, x) for x in globals_read[:4]] - links = [(rva, kind) for rva, kind, target in rel32_sources(image, doomed, func) - if kind != "call" or (target == func[0] and out["never_returns"])] - for rva, kind in links[:MAX_LINKS]: - other = image.function(rva) - if other is None or not image.lands_on(other, rva): - continue - if kind == "jcc": - k = image.flow(other)[1][rva] - out["jumps_in"].append({"from_function": list(other), **guard(image, other, k, True)}) - elif kind == "jmp": - out["jumps_in"].append({"jump": "jmp", "branch": rva, "from": explain(image, rva, depth - 1, seen)}) - else: - out["callers"].append(explain(image, rva, depth - 1, seen)) - out["links_not_followed"] = max(0, len(links) - MAX_LINKS) - return out - - -def returns(image: Image, rva: int): - """What the function holding rva returns in rax: the sources over the paths into each `ret` that the bounded - search recovers, each with the branches that decide whether its instruction runs.""" - func = image.function(rva) - if func is None: - return {"at": rva, "function": None, "note": "no .pdata entry holds it"} - insns = image.run(func) - rets = [k for k, i in enumerate(insns) if i.op in (0xC3, 0xC2)] - out, keys, complete = [], set(), True - for k in rets: - paths = trace_paths(image, func, k, RAX) - complete = complete and paths["complete"] - for x in paths["sources"]: - key = (x.get("at", x.get("call")), x.get("value", "call")) - if key in keys: - continue - keys.add(key) - at = x.get("call", x.get("at")) - if at is not None: - e = explain(image, at, 0, set(), stop=False) - x["guards"], x["reached_from_start"] = e.get("guards", []), e.get("reached_from_start", False) - out.append(x) - return {"at": rva, "function": list(func), "rets": len(rets), "returns": out, "complete": complete} - - -def parse_address(text: str, image_base: int) -> int: - m = re.fullmatch(r"(?:[\w.\-]+\+)?(?:0x)?([0-9a-fA-F]+)", text.strip()) - if not m: - raise ValueError(f"not an address: {text!r}") - value = int(m.group(1), 16) - return value - image_base if value >= image_base else value - - -def cause(data: bytes, addresses, any_instruction: bool = False, returned: bool = False): - """{address text: report} for each address. With any_instruction, an address may be any instruction; with - returned, the report is what the function holding the address returns.""" - image = Image(data) - out = {} - for text in addresses: - rva = parse_address(text, image.img.image_base) - if returned: - out[text] = {"rva": rva, "stop": "returns", **returns(image, rva)} - continue - if any_instruction: - if image.code.decode(rva) is None: - out[text] = {"rva": rva, "stop": None, "note": "no instruction decodes there"} - continue - out[text] = {"rva": rva, "stop": "instruction", **explain(image, rva, DEPTH, set(), stop=False)} - continue - stop = stop_at(image, rva) - if stop is None: - out[text] = {"rva": rva, "stop": None, "note": "not an int3, ud2 or int 29h (nor one byte past an int3)"} - continue - at, kind = stop - out[text] = {"rva": rva, "stop": kind, **explain(image, at, DEPTH, set())} - return out - - -# ---- text output ---- - -def source(r, where: bool = False) -> str: - """What a traced register holds, as text (without the register's name); with `where`, the RVAs too.""" - how = "derived from " if r.get("derived") else ("a copy of " if r.get("copied") else "") - if "call" in r: - if "import" in r: - what = r["import"] - elif "slot" in r: - what = f"vtable slot {r['slot']}" + (f" (this: global {r['this_global']:#x})" if "this_global" in r - else "") - elif "function" in r: - what = f"function {r['function']:#x}" - elif "pointer" in r: - what = f"the function pointer at {r['pointer']:#x}" - else: - what = "a call through a register" - return f"{how}the result of {what}" + (f", call at {r['call']:#x}" if where else "") - if r["value"] == "argument": - return f"{how}argument {r['argument']} ({r['argument_register']})" - src = f" ({r['from']})" if "from" in r else (f" ({show(r['constant'])})" if "constant" in r else "") - at = f" at {r['at']:#x}" if where and "at" in r else "" - base = f"; {r['base']['register']}: {source(r['base'], where)}" if "base" in r else "" - return f"{how}{r['value']}{src}{at}{base}" - - -def describe_register(r) -> str: - return f"{r['register']}: {source(r, True)}" - - -def tally_lines(items, indent: str): - tally = {} - for what in items: - tally[what] = tally.get(what, 0) + 1 - return [f"{indent} {count:4} {what}" for what, count in sorted(tally.items(), key=lambda kv: (-kv[1], kv[0]))] - - -def global_lines(globs, indent: str): - lines = [] - for g in globs: - n = len(g["writers"]) + g["writers_not_read"] - lines.append(f"{indent}global {g['global']:#x} is written at {n} site(s)" + (":" if n else - " this tool reads (none by a direct `mov`: through a pointer or not at all)")) - lines += tally_lines([source(w["source"]) for w in g["writers"]], indent) - if g["writers_not_read"]: - lines.append(f"{indent} {g['writers_not_read']} more not read") - return lines - - -def argument_lines(args, indent: str): - """A tally of what the call sites pass, most frequent first.""" - sites = args["sites"] - lines = [] - for n in sorted({x["passed_as"] for x in sites}): - passed = [source(x["source"]) for x in sites if x["passed_as"] == n] - lines.append(f"{indent}argument {n} at the function's {len(passed)} direct call site(s):") - lines += tally_lines(passed, indent) - if args.get("sites_not_read"): - lines.append(f"{indent}{args['sites_not_read']} more call site(s) not read") - return lines - - -def guard_lines(g, indent: str, verb: str = "stops when"): - head = f"{indent}{g['jump']} at {g['branch']:#x}, {g['doomed_side']} side: " - if g.get("condition"): - lines = [head + f"{verb} {g['condition']}"] - else: - where = f" (at {g['flags_at']:#x})" if "flags_at" in g else "" - lines = [head + g.get("note", "condition not read") + where] - for r in g.get("registers", []): - lines.append(f"{indent} {describe_register(r)}") - return lines - - -def report_lines(rep, indent: str = " "): - if rep.get("function") is None or "guards" not in rep: - return [f"{indent}{rep.get('note')}"] - lines = [] - for g in rep["guards"]: - lines += guard_lines(g, indent, "runs when" if rep.get("any") else "stops when") - if rep.get("arguments"): - lines += argument_lines(rep["arguments"], indent) - if rep.get("globals"): - lines += global_lines(rep["globals"], indent) - for j in rep["jumps_in"]: - if j.get("jump") == "jmp": - f = j["from"] - span = f"function {f['function'][0]:#x}" if f.get("function") else "no function" - lines.append(f"{indent}jmp at {j['branch']:#x} from {span}:") - lines += report_lines(f, indent + " ") - else: - lines.append(f"{indent}from function {j['from_function'][0]:#x}:") - lines += guard_lines(j, indent + " ") - if rep.get("never_returns") and rep["callers"]: - lines.append(f"{indent}the function never returns once entered; its direct call sites " - f"({len(rep['callers'])}):") - for c in rep["callers"]: - span = f"function {c['function'][0]:#x}" if c.get("function") else "no function" - lines.append(f"{indent} call at {c['at']:#x} in {span}:") - lines += report_lines(c, indent + " ") - if not lines: - if rep.get("reached_from_start"): - lines.append(f"{indent}no guard: every path from the function start reaches it") - else: - lines.append(f"{indent}no guard found: the stop is reached unconditionally from the function start, " - f"and nothing calls or jumps to it directly (a jump table or a pointer, if anything)") - if rep.get("links_not_followed"): - lines.append(f"{indent}{rep['links_not_followed']} more jump(s) or call(s) into it not followed") - return lines - - -def returns_lines(rep, indent: str = " "): - lines = [] - for x in rep["returns"]: - lines.append(f"{indent}{source(x, True)}:") - if x.get("reached_from_start"): - lines.append(f"{indent} on every path from the function start (unless set again later)") - elif x.get("guards"): - for g in x["guards"]: - lines += guard_lines(g, indent + " ", "runs when") - elif "guards" in x: - lines.append(f"{indent} no guard read (reached through a loop, a jump table or another function)") - if not rep["complete"]: - lines.append(f"{indent}(not every path was read: the search stopped at its limit)") - return lines - - -def to_text(results) -> str: - lines = [] - for text, rep in results.items(): - if rep["stop"] is None: - lines.append(f"{text}: {rep['note']}") - continue - span = (f"function {rep['function'][0]:#x}-{rep['function'][1]:#x}" if rep.get("function") - else "no function") - if rep["stop"] == "returns": - lines.append(f"{text}: {span}, {rep['rets']} ret(s); it returns:" if rep.get("function") else - f"{text}: {rep.get('note')}") - lines += returns_lines(rep) if rep.get("function") else [] - continue - lines.append(f"{text}: {rep['stop']} at {rep['at']:#x}, {span}") - lines += report_lines(rep) - return "\n".join(lines) + "\n" - - -def readable(results) -> bool: - return all(r["stop"] is not None and r.get("function") is not None and ("guards" in r or "returns" in r) - for r in results.values()) - - -def main(argv=None) -> int: - ap = argparse.ArgumentParser(description="Name the call whose result sends an x86-64 PE image to an int3.") - ap.add_argument("image") - ap.add_argument("addresses", nargs="+", metavar="address", - help="the stop: exe+0x..., an RVA or a virtual address (hex)") - ap.add_argument("--any", action="store_true", - help="an address may be any instruction (a `return 0` path, a fallback): print the branches " - "that decide whether it runs") - ap.add_argument("--returns", action="store_true", - help="an address may be anywhere in a function: print what the function returns in rax, each " - "value with where it is set and the branches that decide that") - ap.add_argument("--json", action="store_true", help="print JSON instead of text") - args = ap.parse_args(argv) - try: - with open(args.image, "rb") as f: - data = f.read() - results = cause(data, args.addresses, args.any, args.returns) - except (OSError, pe_inspect.PeFormatError, ValueError) as e: - print(f"{os.path.basename(sys.argv[0])}: {e}", file=sys.stderr) - return 2 - if args.json: - print(json.dumps(results, indent=1)) - else: - sys.stdout.write(to_text(results)) - return 0 if readable(results) else 1 - - -if __name__ == "__main__": - try: # a redirected stdout is strict ANSI code page under -I; write '?' for what it cannot encode - sys.stdout.reconfigure(errors="replace") - except (AttributeError, ValueError, OSError): - pass - sys.exit(main()) diff --git a/tools/int_hw_probe.py b/tools/int_hw_probe.py deleted file mode 100644 index c76b65978..000000000 --- a/tools/int_hw_probe.py +++ /dev/null @@ -1,1016 +0,0 @@ -r"""SHADER-137: RDNA2 hardware probe for the integer contract rows checked only on the CPU. - -Runs small, self-contained RDNA2 instruction sequences natively on an AMD GPU through tools/hw_oracle (wave32 and -wave64) and compares every output word with Leonida's live translator (tools/rdna2spirv.py -> -tests/semantic/spirv_mini_interp.py). Standard library only; no game files. - -Groups covered (each references its contract row in docs/design.md): - salu_absdiff_mulhi s_absdiff_i32, s_mul_hi_i32, s_mul_hi_u32 (SCC written vs kept) - salu_lshl_add s_lshl1..4_add_u32 (64-bit carry / shift-out into SCC) - salu_sext_flbit s_sext_i32_i8, s_sext_i32_i16, s_flbit_i32 (SCC kept) - salu_cmov_pack s_cmov_b32, s_cmovk_i32, s_pack_ll/lh/hh_b32_b16 (SCC kept) - salu_bfe_past31 s_bfe_u32, s_bfe_i32 with offset + width > 32 and width 0 - salu_cmov_b64 s_cmov_b64 on plain data pairs (SGPR pair, inline constants, literal, null, D itself) - salu_64_data s_brev_b64, s_bfe_u64/i64, s_bitset0/1_b64, s_flbit_i32_b64/i64 - salu_quad_bitrep s_quadmask_b32/b64, s_bitreplicate_b64_b32 - salu_64_bitwise s_and/or/xor/andn2/orn2/nand/nor/xnor/not_b64 on scalar data - salu_movrels s_movrels_b32, s_movrels_b64 (M0 indexing, SCC kept) - valu_add_nc_clamp v_add/sub/subrev_nc_u32, v_add/sub_nc_i32, v_add/sub_nc_u16/i16 with clamp - valu_add_co_clamp v_add/sub/subrev_co[_ci]_u32 with clamp (saturation + carry) - valu_mad64 v_mad_u64_u32, v_mad_i64_i32 (sdst bit 64 and inactive EXEC lane) - valu_sad_lerp v_sad_u8, v_sad_hi_u8, v_sad_u16, v_sad_u32, v_msad_u8, v_lerp_u8 - valu_qsad_mqsad v_qsad_pk_u16_u8, v_mqsad_pk_u16_u8, v_mqsad_u32_u8 - valu_mul24_sh64 v_mul_hi_u32_u24, v_mul_hi_i32_i24, v_lshrrev_b64, v_ashrrev_i64 - valu_mad16 v_mad_u16, v_mad_i16 (clamp, op_sel, kept half) - valu_cvt_16 v_cvt_f16_u16/i16, v_cvt_u16/i16_f16 (kept half, op_sel, NaN, inf) - valu_cvt_flr_rpi v_cvt_flr_i32_f32, v_cvt_rpi_i32_f32 (exact floor(x+0.5), signed NaN) - valu_cvt_pknorm v_cvt_pknorm_i16_f32, v_cvt_pknorm_u16_f32 (ties, saturation, NaN) - valu_cvt_norm_f16 v_cvt_pknorm_i16/u16_f16 and v_cvt_norm_i16/u16_f16 (near-ties, saturation, NaN, op_sel on the pk forms, neg/abs) - valu_bfe_past31 v_bfe_u32, v_bfe_i32 with offset + width > 32, width 0, offset/width bits above [4:0] - -Usage: - python -I tools/int_hw_probe.py # translator side only (CPU) - python -I tools/int_hw_probe.py --oracle hw # native AMD GPU only (wave32 + wave64) - python -I tools/int_hw_probe.py --oracle both # compare hardware vs translator - python -I tools/int_hw_probe.py --oracle both --strict # fail on known translator divergences too - python -I tools/int_hw_probe.py --self-test - -Exit codes: - 0 all unexpected comparisons match (and wave32 == wave64 on hardware) - 1 at least one unexpected mismatch, wave32/64 diff, or known divergence under --strict - 2 bad CLI arguments or harness error - 77 hardware oracle requested but unavailable on this machine -""" -import argparse -import json -import os -import struct -import sys -import tempfile -import warnings - -HERE = os.path.dirname(os.path.abspath(__file__)) -ROOT = os.path.dirname(HERE) -sys.dont_write_bytecode = True -for p in (HERE, os.path.join(ROOT, "tests", "semantic")): - if p not in sys.path: - sys.path.insert(0, p) - -import rdna2spirv # noqa: E402 -import spirv_mini_interp # noqa: E402 - -STUB_DXBC = b"DXBC" + bytes(24) + struct.pack(" (tag, expected_hw_words, reason). Empty: the five measured on gfx1035 (VOP3 clamp -# on the carry-out add/sub ops, v_cvt_rpi_i32_f32's exact floor(x + 0.5), and v_cvt_flr/rpi's NaN saturation by -# sign) are translated as the hardware does since #1831 and #1856. -KNOWN_DIVERGENCES = {} - - -class Case: - """One self-contained 4-word probe. `body` leaves results in v8..v11 and must not clobber s[0:3] or v0. - For wave-size-dependent mask instructions, `{vcc}`, `{exec}`, `{smov}`, `{stmp}` expand to wave32/wave64 forms.""" - - __slots__ = ("group", "name", "body", "note") - - def __init__(self, group, name, body, note=""): - self.group = group - self.name = name - self.body = tuple(body) - self.note = note - - def lines(self, wave=32): - vcc = "vcc_lo" if wave == 32 else "vcc" - exc = "exec_lo" if wave == 32 else "exec" - smov = "s_mov_b32" if wave == 32 else "s_mov_b64" - stmp = "s14" if wave == 32 else "s[14:15]" - return [ln.format(vcc=vcc, exec=exc, smov=smov, stmp=stmp) for ln in self.body] - - -def _scc_seed(val): - return "s_cmp_eq_u32 0, 0" if val else "s_cmp_eq_u32 0, 1" - - -def _salu32_pair(group, name, setup, op_line, note=""): - """Run one 32-bit scalar op twice: once with SCC preset to 0 (v8=D, v9=SCC) and once with SCC preset to 1 - (v10=D, v11=SCC), so 'SCC kept' and 'SCC written' are both directly observed.""" - body = [ - *setup, _scc_seed(0), op_line, - "s_cselect_b32 s30, 1, 0", "v_mov_b32 v8, s6", "v_mov_b32 v9, s30", - *setup, _scc_seed(1), op_line, - "s_cselect_b32 s30, 1, 0", "v_mov_b32 v10, s6", "v_mov_b32 v11, s30", - ] - return Case(group, name, body, note) - - -def _salu64_case(group, name, setup, op_line, scc_in, note=""): - """Run one 64-bit scalar op with SCC preset to scc_in; output v8=s6 (lo), v9=s7 (hi), v10=SCC, v11=0.""" - body = [ - *setup, _scc_seed(scc_in), op_line, - "s_cselect_b32 s30, 1, 0", - "v_mov_b32 v8, s6", "v_mov_b32 v9, s7", "v_mov_b32 v10, s30", "v_mov_b32 v11, 0", - ] - return Case(group, name, body, note) - - -def _valu4_case(group, name, body, note=""): - return Case(group, name, body, note) - - -# f16 inputs for the normalised conversions: +-0, +-1, 1 +- 1ulp, +-0.5 and the f16 neighbours of the 0.5 tie (0x37ff and 0x3801 are -# 0.5 -+ 2^-11, so x * 32767 is 16383.5 -+ a hair), +-0.25 and its neighbours, a denormal, +-65504, +-inf, quiet and signalling NaN. -F16_NORM_VALUES = (0x0000, 0x8000, 0x3C00, 0xBC00, 0x3BFF, 0x3C01, 0xBBFF, 0xBC01, 0x3800, 0xB800, 0x37FF, 0x3801, 0xB7FF, 0xB801, - 0x3400, 0xB400, 0x33FF, 0x3401, 0x0001, 0x8001, 0x03FF, 0x7BFF, 0xFBFF, 0x7C00, 0xFC00, 0x7E00, 0xFE00, 0x7C01, - 0xFC01, 0x3555, 0xB555, 0x2E66, 0x4000, 0xC000) - - -def _cvt_norm_f16_cases(): - cases = [] - vals = F16_NORM_VALUES - for i in range(0, len(vals) - 1, 1): - a, b = vals[i], vals[(i + 5) % len(vals)] - cases.append(_valu4_case("valu_cvt_norm_f16", f"pknorm_f16_{a:04x}_{b:04x}", [ - f"v_mov_b32 v1, 0x{(b << 16) | a:08x}", f"v_mov_b32 v2, 0x{(a << 16) | b:08x}", - "v_cvt_pknorm_i16_f16 v8, v1, v2", # lo(v1), lo(v2) - "v_cvt_pknorm_u16_f16 v9, v1, v2", - "v_cvt_pknorm_i16_f16 v10, -v1, |v2| op_sel:[1,0]", # hi(v1) negated, lo(v2) abs - "v_cvt_pknorm_u16_f16 v11, |v1|, -v2 op_sel:[0,1]", # lo(v1) abs, hi(v2) negated - ], f"v_cvt_pknorm_i16/u16_f16 on f16 {a:04x}/{b:04x} (op_sel, neg, abs)")) - for a in vals: - cases.append(_valu4_case("valu_cvt_norm_f16", f"norm_f16_{a:04x}", [ - f"v_mov_b32 v1, 0x{(0x3555 << 16) | a:08x}", f"v_mov_b32 v2, 0x{(a << 16) | 0x3C00:08x}", - f"v_mov_b32 v8, 0x{SENTINEL:08x}", f"v_mov_b32 v9, 0x{SENTINEL:08x}", - f"v_mov_b32 v10, 0x{SENTINEL:08x}", f"v_mov_b32 v11, 0x{SENTINEL:08x}", - "v_cvt_norm_i16_f16_e64 v8, v1", - "v_cvt_norm_u16_f16_e64 v9, v1", - "v_cvt_norm_i16_f16_e64 v10, -v2", # neg: GFX10 takes no op_sel on these two - "v_cvt_norm_u16_f16_e64 v11, |v2|", - ], f"v_cvt_norm_i16/u16_f16 on f16 {a:04x} (kept half, neg/abs)")) - return cases - - -def build_cases(): - cases = [] - - # 1. s_absdiff_i32, s_mul_hi_i32, s_mul_hi_u32 (docs/design.md) - cases += [ - _salu32_pair("salu_absdiff_mulhi", "s_absdiff_basic", - ["s_mov_b32 s4, 10", "s_mov_b32 s5, 25"], - "s_absdiff_i32 s6, s4, s5", "|10 - 25| = 15, SCC=1"), - _salu32_pair("salu_absdiff_mulhi", "s_absdiff_equal", - ["s_mov_b32 s4, 0x80000000", "s_mov_b32 s5, 0x80000000"], - "s_absdiff_i32 s6, s4, s5", "equal -> 0, SCC=0"), - _salu32_pair("salu_absdiff_mulhi", "s_absdiff_wrap_max_min", - ["s_mov_b32 s4, 0x7fffffff", "s_mov_b32 s5, 0x80000000"], - "s_absdiff_i32 s6, s4, s5", "0x7fffffff - 0x80000000 wraps to -1 -> abs 1, SCC=1"), - _salu32_pair("salu_absdiff_mulhi", "s_absdiff_int_min", - ["s_mov_b32 s4, 0x80000000", "s_mov_b32 s5, 0"], - "s_absdiff_i32 s6, s4, s5", "diff = INT_MIN stays 0x80000000, SCC=1"), - _salu32_pair("salu_absdiff_mulhi", "s_mul_hi_i32_min_min", - ["s_mov_b32 s4, 0x80000000", "s_mov_b32 s5, 0x80000000"], - "s_mul_hi_i32 s6, s4, s5", "(-2^31)*(-2^31) >> 32 = 0x40000000, SCC kept"), - _salu32_pair("salu_absdiff_mulhi", "s_mul_hi_i32_neg_pos", - ["s_mov_b32 s4, 0xffffffff", "s_mov_b32 s5, 2"], - "s_mul_hi_i32 s6, s4, s5", "(-1)*2 >> 32 = 0xffffffff, SCC kept"), - _salu32_pair("salu_absdiff_mulhi", "s_mul_hi_u32_max_max", - ["s_mov_b32 s4, 0xffffffff", "s_mov_b32 s5, 0xffffffff"], - "s_mul_hi_u32 s6, s4, s5", "(2^32-1)^2 >> 32 = 0xfffffffe, SCC kept"), - ] - - # 2. s_lshl1..4_add_u32 (64-bit shift-out + add carry into SCC) - for shift in (1, 2, 3, 4): - op = f"s_lshl{shift}_add_u32" - high_bit = 1 << (32 - shift) - cases += [ - _salu32_pair("salu_lshl_add", f"{op}_no_carry", - ["s_mov_b32 s4, 0x00010000", "s_mov_b32 s5, 5"], - f"{op} s6, s4, s5", "no shift-out, no add carry -> SCC=0"), - _salu32_pair("salu_lshl_add", f"{op}_shift_out_only", - [f"s_mov_b32 s4, 0x{high_bit:08x}", "s_mov_b32 s5, 0"], - f"{op} s6, s4, s5", "bit shifted out of S0 with S1=0 -> D=0, SCC=1"), - _salu32_pair("salu_lshl_add", f"{op}_add_carry_only", - ["s_mov_b32 s4, 1", "s_mov_b32 s5, 0xffffffff"], - f"{op} s6, s4, s5", "add carry without shift-out -> SCC=1"), - ] - - # 3. s_sext_i32_i8, s_sext_i32_i16, s_flbit_i32 - cases += [ - _salu32_pair("salu_sext_flbit", "s_sext_i8_neg", - ["s_mov_b32 s4, 0x12345680"], "s_sext_i32_i8 s6, s4", "0x80 -> 0xffffff80, SCC kept"), - _salu32_pair("salu_sext_flbit", "s_sext_i8_pos", - ["s_mov_b32 s4, 0xffffff7f"], "s_sext_i32_i8 s6, s4", "0x7f -> 0x0000007f, SCC kept"), - _salu32_pair("salu_sext_flbit", "s_sext_i16_neg", - ["s_mov_b32 s4, 0x00008001"], "s_sext_i32_i16 s6, s4", "0x8001 -> 0xffff8001, SCC kept"), - _salu32_pair("salu_sext_flbit", "s_sext_i16_pos", - ["s_mov_b32 s4, 0xffff7fff"], "s_sext_i32_i16 s6, s4", "0x7fff -> 0x00007fff, SCC kept"), - _salu32_pair("salu_sext_flbit", "s_flbit_i32_zero", - ["s_mov_b32 s4, 0"], "s_flbit_i32 s6, s4", "0 -> 0xffffffff, SCC kept"), - _salu32_pair("salu_sext_flbit", "s_flbit_i32_neg1", - ["s_mov_b32 s4, 0xffffffff"], "s_flbit_i32 s6, s4", "-1 -> 0xffffffff, SCC kept"), - _salu32_pair("salu_sext_flbit", "s_flbit_i32_pos1", - ["s_mov_b32 s4, 1"], "s_flbit_i32 s6, s4", "1 -> 30, SCC kept"), - _salu32_pair("salu_sext_flbit", "s_flbit_i32_neg16", - ["s_mov_b32 s4, 0xfffffff0"], "s_flbit_i32 s6, s4", "-16 -> 27, SCC kept"), - _salu32_pair("salu_sext_flbit", "s_flbit_i32_int_min", - ["s_mov_b32 s4, 0x80000000"], "s_flbit_i32 s6, s4", "INT_MIN -> 0, SCC kept"), - ] - - # 4. s_cmov_b32, s_cmovk_i32, s_pack_ll/lh/hh_b32_b16 - cases += [ - _salu32_pair("salu_cmov_pack", "s_cmov_b32", - ["s_mov_b32 s4, 0x11223344", "s_mov_b32 s6, 0xaabbccdd"], - "s_cmov_b32 s6, s4", "SCC=0 keeps D, SCC=1 takes S0, SCC kept"), - _salu32_pair("salu_cmov_pack", "s_cmovk_i32_neg", - ["s_mov_b32 s6, 0x12345678"], - "s_cmovk_i32 s6, -300", "SCC=0 keeps D, SCC=1 sign-extends imm16, SCC kept"), - _salu32_pair("salu_cmov_pack", "s_pack_ll", - ["s_mov_b32 s4, 0x11112222", "s_mov_b32 s5, 0x33334444"], - "s_pack_ll_b32_b16 s6, s4, s5", "{S1.lo, S0.lo} = 0x44442222, SCC kept"), - _salu32_pair("salu_cmov_pack", "s_pack_lh", - ["s_mov_b32 s4, 0x11112222", "s_mov_b32 s5, 0x33334444"], - "s_pack_lh_b32_b16 s6, s4, s5", "{S1.hi, S0.lo} = 0x33332222, SCC kept"), - _salu32_pair("salu_cmov_pack", "s_pack_hh", - ["s_mov_b32 s4, 0x11112222", "s_mov_b32 s5, 0x33334444"], - "s_pack_hh_b32_b16 s6, s4, s5", "{S1.hi, S0.hi} = 0x33331111, SCC kept"), - ] - - # 5. s_bfe_u32 / s_bfe_i32 past bit 31 - cases += [ - _salu32_pair("salu_bfe_past31", "s_bfe_i32_past31", - ["s_mov_b32 s4, 0xd2f90159", "s_mov_b32 s5, 0x7f001c"], - "s_bfe_i32 s6, s4, s5", "off=28 width=127 stops at bit 31 -> 0xfffffffd, SCC=1"), - _salu32_pair("salu_bfe_past31", "s_bfe_u32_past31", - ["s_mov_b32 s4, 0xd2f90159", "s_mov_b32 s5, 0xff7f001c"], - "s_bfe_u32 s6, s4, s5", "upper bits ignored, stops at bit 31 -> 0x0000000d, SCC=1"), - _salu32_pair("salu_bfe_past31", "s_bfe_i32_width0", - ["s_mov_b32 s4, 0xffffffff", "s_mov_b32 s5, 0x00000005"], - "s_bfe_i32 s6, s4, s5", "width=0 -> 0, SCC=0"), - ] - - # 5b. s_cmov_b64 on plain 64-bit data pairs: D = SCC ? S0 : D, SCC kept - for src_name, src_setup, src_op in ( - ("sgpr_pair", ["s_mov_b32 s4, 0x11223344", "s_mov_b32 s5, 0x55667788"], "s[4:5]"), - ("inline_m1", [], "-1"), - ("inline_m16", [], "-16"), - ("inline_64", [], "64"), - ("literal", [], "0x89abcdef"), - ("null", [], "null"), - ("self", [], "s[6:7]"), - ): - for scc_in in (0, 1): - cases.append(_salu64_case( - "salu_cmov_b64", f"s_cmov_b64_{src_name}_scc{scc_in}", - [*src_setup, "s_mov_b32 s6, 0xaabbccdd", "s_mov_b32 s7, 0x99887766"], - f"s_cmov_b64 s[6:7], {src_op}", scc_in, - "SCC=1 takes S0 (literal zero-extended, null = 0), SCC=0 keeps D, SCC kept")) - - # 6. 64-bit scalar data ops (s_brev_b64, s_bfe_u64/i64, s_bitset0/1_b64, s_flbit_i32_b64/i64) - cases += [ - _salu64_case("salu_64_data", "s_brev_b64_scc1", - ["s_mov_b32 s4, 0x80000001", "s_mov_b32 s5, 0x12345678"], - "s_brev_b64 s[6:7], s[4:5]", 1, "bit-reverse 64-bit pair, SCC kept"), - _salu64_case("salu_64_data", "s_bfe_u64_cross_past63", - ["s_mov_b32 s4, 0x12345678", "s_mov_b32 s5, 0xd2f90159", "s_mov_b32 s8, 0x7f003c"], - "s_bfe_u64 s[6:7], s[4:5], s8", 0, "off=60 width=127 stops at bit 63 -> 0xd, SCC=1"), - _salu64_case("salu_64_data", "s_bfe_i64_past63", - ["s_mov_b32 s4, 0x12345678", "s_mov_b32 s5, 0xd2f90159", "s_mov_b32 s8, 0x7f003c"], - "s_bfe_i64 s[6:7], s[4:5], s8", 0, "off=60 width=127 sign-extends 0xd -> -3, SCC=1"), - _salu64_case("salu_64_data", "s_bfe_u64_width0", - ["s_mov_b32 s4, 0xffffffff", "s_mov_b32 s5, 0xffffffff", "s_mov_b32 s8, 0x00000010"], - "s_bfe_u64 s[6:7], s[4:5], s8", 1, "width=0 -> 0, SCC=0"), - _salu64_case("salu_64_data", "s_bitset0_b64_hi", - ["s_mov_b32 s6, 0xffffffff", "s_mov_b32 s7, 0xffffffff", "s_mov_b32 s8, 63"], - "s_bitset0_b64 s[6:7], s8", 1, "clear bit 63, SCC kept"), - _salu64_case("salu_64_data", "s_bitset1_b64_mod64", - ["s_mov_b32 s6, 0", "s_mov_b32 s7, 0", "s_mov_b32 s8, 97"], - "s_bitset1_b64 s[6:7], s8", 0, "set bit 97 & 63 = 33 (hi bit 1), SCC kept"), - _salu32_pair("salu_64_data", "s_flbit_i32_b64_zero", - ["s_mov_b32 s4, 0", "s_mov_b32 s5, 0"], - "s_flbit_i32_b64 s6, s[4:5]", "0 -> -1, SCC kept"), - _salu32_pair("salu_64_data", "s_flbit_i32_b64_lo", - ["s_mov_b32 s4, 0x00010000", "s_mov_b32 s5, 0"], - "s_flbit_i32_b64 s6, s[4:5]", "bit 16 -> 47 leading zeros, SCC kept"), - _salu32_pair("salu_64_data", "s_flbit_i32_i64_neg", - ["s_mov_b32 s4, 0xfffffff0", "s_mov_b32 s5, 0xffffffff"], - "s_flbit_i32_i64 s6, s[4:5]", "-16 -> 59 sign bits, SCC kept"), - _salu32_pair("salu_64_data", "s_flbit_i32_i64_neg1", - ["s_mov_b32 s4, 0xffffffff", "s_mov_b32 s5, 0xffffffff"], - "s_flbit_i32_i64 s6, s[4:5]", "-1 -> -1, SCC kept"), - ] - - # 7. s_quadmask_b32/b64, s_bitreplicate_b64_b32 - cases += [ - _salu32_pair("salu_quad_bitrep", "s_quadmask_b32_nz", - ["s_mov_b32 s4, 0x10080041"], - "s_quadmask_b32 s6, s4", "quads 0,1,4,7 set -> 0x93, SCC=1"), - _salu32_pair("salu_quad_bitrep", "s_quadmask_b32_zero", - ["s_mov_b32 s4, 0"], - "s_quadmask_b32 s6, s4", "0 -> 0, SCC=0"), - _salu64_case("salu_quad_bitrep", "s_quadmask_b64_hi", - ["s_mov_b32 s4, 0x00000000", "s_mov_b32 s5, 0x80000001"], - "s_quadmask_b64 s[6:7], s[4:5]", 0, "quads 8,15 -> lo=0x8100 hi=0, SCC=1"), - _salu64_case("salu_quad_bitrep", "s_bitreplicate_b64_b32", - ["s_mov_b32 s4, 0x80010005"], - "s_bitreplicate_b64_b32 s[6:7], s4", 1, "each bit doubled, SCC kept"), - ] - - # 8. 64-bit scalar bitwise ops on scalar data - for op in ("s_and_b64", "s_or_b64", "s_xor_b64", "s_andn2_b64", "s_orn2_b64", - "s_nand_b64", "s_nor_b64", "s_xnor_b64"): - cases.append(_salu64_case( - "salu_64_bitwise", f"{op}_data", - ["s_mov_b32 s4, 0xf0f000ff", "s_mov_b32 s5, 0x12345678", - "s_mov_b32 s8, 0x0ff0ff00", "s_mov_b32 s9, 0x87654321"], - f"{op} s[6:7], s[4:5], s[8:9]", 0, f"{op} on 64-bit scalar data + SCC", - )) - cases.append(_salu64_case( - "salu_64_bitwise", "s_not_b64_all_ones", - ["s_mov_b32 s4, 0xffffffff", "s_mov_b32 s5, 0xffffffff"], - "s_not_b64 s[6:7], s[4:5]", 1, "~(-1) = 0, SCC=0", - )) - - # 9. s_movrels_b32 / s_movrels_b64 - cases += [ - _salu32_pair("salu_movrels", "s_movrels_b32_m0_2", - ["s_mov_b32 s10, 0x11111111", "s_mov_b32 s11, 0x22222222", - "s_mov_b32 s12, 0x33333333", "s_mov_b32 m0, 2"], - "s_movrels_b32 s6, s10", "SGPR[10+2] = 0x33333333, SCC kept"), - _salu64_case("salu_movrels", "s_movrels_b64_m0_2", - ["s_mov_b32 s10, 0x11111111", "s_mov_b32 s11, 0x22222222", - "s_mov_b32 s12, 0x33333333", "s_mov_b32 s13, 0x44444444", "s_mov_b32 m0, 2"], - "s_movrels_b64 s[6:7], s[10:11]", 1, "SGPR[12:13], SCC kept"), - ] - - # 10. Integer clamp on v_add/sub/subrev_nc_u32, v_add/sub_nc_i32, v_add/sub_nc_u16, v_add/sub_nc_i16 - cases += [ - _valu4_case("valu_add_nc_clamp", "v_add_sub_nc_u32_clamp", [ - "v_mov_b32 v1, 0xfffffff0", "v_mov_b32 v2, 0x30", - "v_add_nc_u32_e64 v8, v1, v2 clamp", # saturates to 0xffffffff - "v_sub_nc_u32_e64 v9, v2, v1 clamp", # saturates to 0 - "v_subrev_nc_u32_e64 v10, v1, v2 clamp", # v2 - v1 -> saturates to 0 - "v_subrev_nc_u32_e64 v11, v2, v1 clamp", # v1 - v2 = 0xffffffc0 - ], "u32 nc add/sub/subrev with clamp"), - _valu4_case("valu_add_nc_clamp", "v_add_sub_nc_i32_clamp", [ - "v_mov_b32 v1, 0x7ffffff0", "v_mov_b32 v2, 0x30", - "v_mov_b32 v3, 0x80000010", "v_mov_b32 v4, 0x30", - "v_add_nc_i32_e64 v8, v1, v2 clamp", # +overflow -> 0x7fffffff - "v_sub_nc_i32_e64 v9, v3, v4 clamp", # -overflow -> 0x80000000 - "v_add_nc_i32_e64 v10, v3, v3 clamp", # neg+neg overflow -> 0x80000000 - "v_sub_nc_i32_e64 v11, v1, v3 clamp", # pos-neg overflow -> 0x7fffffff - ], "i32 nc add/sub with clamp"), - _valu4_case("valu_add_nc_clamp", "v_add_sub_nc_u16_clamp", [ - "v_mov_b32 v1, 0x1234fff0", "v_mov_b32 v2, 0x56780030", - f"v_mov_b32 v8, 0x{SENTINEL:08x}", - f"v_mov_b32 v9, 0x{SENTINEL:08x}", - f"v_mov_b32 v10, 0x{SENTINEL:08x}", - f"v_mov_b32 v11, 0x{SENTINEL:08x}", - "v_add_nc_u16_e64 v8, v1, v2 clamp", # lo saturates 0xffff, hi kept - "v_sub_nc_u16_e64 v9, v2, v1 clamp", # lo saturates 0x0000, hi kept - "v_add_nc_u16_e64 v10, v1, v2 op_sel:[0,0,1] clamp", # write hi saturates 0xffff, lo kept - "v_sub_nc_u16_e64 v11, v1, v2 op_sel:[1,1,0] clamp", # 0x1234 - 0x5678 -> 0x0000, hi kept - ], "u16 nc add/sub with clamp and op_sel (untouched half kept)"), - _valu4_case("valu_add_nc_clamp", "v_add_sub_nc_i16_clamp", [ - "v_mov_b32 v1, 0x12347ff0", "v_mov_b32 v2, 0x56780030", - "v_mov_b32 v3, 0x12348000", "v_mov_b32 v4, 0x56780001", - f"v_mov_b32 v8, 0x{SENTINEL:08x}", - f"v_mov_b32 v9, 0x{SENTINEL:08x}", - f"v_mov_b32 v10, 0x{SENTINEL:08x}", - f"v_mov_b32 v11, 0x{SENTINEL:08x}", - "v_add_nc_i16_e64 v8, v1, v2 clamp", # 0x7ff0 + 0x0030 = 0x8020 -> saturates 0x7fff, hi kept - "v_sub_nc_i16_e64 v9, v3, v4 clamp", # -32768 - 1 = -32769 -> saturates 0x8000, hi kept - "v_add_nc_i16_e64 v10, v1, v2 op_sel:[0,0,1] clamp", # write hi saturates 0x7fff, lo kept - "v_sub_nc_i16_e64 v11, v1, v2 op_sel:[1,1,0] clamp", # 0x1234 - 0x5678 = -0x4444 in range -> 0xbbbc, hi kept - ], "i16 nc add/sub with clamp and op_sel (untouched half kept)"), - ] - - # 11. v_add/sub/subrev_co[_ci]_u32 with clamp (known divergence: translator ignores clamp) - cases += [ - _valu4_case("valu_add_co_clamp", "v_add_co_u32_clamp", [ - "v_mov_b32 v1, 0xffffffff", "v_mov_b32 v2, 0xffffffff", - "v_add_co_u32 v8, {vcc}, v1, v2 clamp", - "v_cndmask_b32_e64 v9, 0, 1, {vcc}", - "v_mov_b32 v3, 5", "v_mov_b32 v4, 10", - "v_sub_co_u32 v10, {vcc}, v3, v4 clamp", - "v_cndmask_b32_e64 v11, 0, 1, {vcc}", - ], "v_add_co_u32 / v_sub_co_u32 clamp: hardware saturates D and reports real carry/borrow"), - _valu4_case("valu_add_co_clamp", "v_subrev_co_u32_clamp", [ - "v_mov_b32 v1, 10", "v_mov_b32 v2, 5", - "v_subrev_co_u32 v8, {vcc}, v1, v2 clamp", - "v_cndmask_b32_e64 v9, 0, 1, {vcc}", - "v_mov_b32 v3, 0", "v_mov_b32 v4, 0", - "{smov} {vcc}, -1", - "v_subrev_co_ci_u32_e64 v10, {vcc}, v3, v4, {vcc} clamp", - "v_cndmask_b32_e64 v11, 0, 1, {vcc}", - ], "v_subrev_co_u32 / v_subrev_co_ci_u32 clamp: hardware saturates D to 0 and reports borrow=1"), - _valu4_case("valu_add_co_clamp", "v_add_co_ci_u32_clamp", [ - "v_mov_b32 v1, 0xffffffff", "v_mov_b32 v2, 0", - "{smov} {vcc}, -1", - "v_add_co_ci_u32_e64 v8, {vcc}, v1, v2, {vcc} clamp", - "v_cndmask_b32_e64 v9, 0, 1, {vcc}", - "v_mov_b32 v3, 0", "v_mov_b32 v4, 0", - "{smov} {vcc}, -1", - "v_sub_co_ci_u32_e64 v10, {vcc}, v3, v4, {vcc} clamp", - "v_cndmask_b32_e64 v11, 0, 1, {vcc}", - ], "v_add_co_ci_u32 / v_sub_co_ci_u32 clamp: carry-in overflow saturates D and sets carry-out"), - ] - - # 12. v_mad_u64_u32, v_mad_i64_i32 (sdst bit 64 and EXEC masking) - cases += [ - _valu4_case("valu_mad64", "v_mad_u64_u32_carry", [ - "v_mov_b32 v1, 0xffffffff", "v_mov_b32 v2, 0xffffffff", - "v_mov_b32 v4, 0xffffffff", "v_mov_b32 v5, 0xffffffff", - "v_mad_u64_u32 v[8:9], {vcc}, v1, v2, v[4:5]", - "v_cndmask_b32_e64 v10, 0, 1, {vcc}", - "v_mov_b32 v11, 0", - ], "u64 max*max + max64 -> carry=1"), - _valu4_case("valu_mad64", "v_mad_i64_i32_pos_overflow", [ - "v_mov_b32 v1, 0x80000000", "v_mov_b32 v2, 0x80000000", - "v_mov_b32 v4, 0xffffffff", "v_mov_b32 v5, 0x7fffffff", - "v_mad_i64_i32 v[8:9], {vcc}, v1, v2, v[4:5]", - "v_cndmask_b32_e64 v10, 0, 1, {vcc}", - "v_mov_b32 v11, 0", - ], "(-2^31)^2 + INT64_MAX > 0 (signed overflow, positive exact sum -> sdst=0)"), - _valu4_case("valu_mad64", "v_mad_i64_i32_neg_sum", [ - "v_mov_b32 v1, 0xfffffffe", "v_mov_b32 v2, 3", - "v_mov_b32 v4, 0", "v_mov_b32 v5, 0", - "v_mad_i64_i32 v[8:9], {vcc}, v1, v2, v[4:5]", - "v_cndmask_b32_e64 v10, 0, 1, {vcc}", - "v_mov_b32 v11, 0", - ], "(-2)*3 + 0 = -6 -> sdst=1 (bit 64 sign of exact 65-bit sum)"), - _valu4_case("valu_mad64", "v_mad_u64_u32_inactive_lane", [ - "v_mov_b32 v1, 0xffffffff", "v_mov_b32 v2, 0xffffffff", - "v_mov_b32 v4, 0xffffffff", "v_mov_b32 v5, 0xffffffff", - "v_mov_b32 v8, 0x11111111", "v_mov_b32 v9, 0x22222222", - "{smov} {vcc}, -1", - "{smov} {stmp}, {exec}", - "{smov} {exec}, 0", - "v_mad_u64_u32 v[8:9], {vcc}, v1, v2, v[4:5]", - "{smov} {exec}, {stmp}", - "v_cndmask_b32_e64 v10, 0, 1, {vcc}", - "v_mov_b32 v11, 0", - ], "inactive EXEC lane: D untouched and sdst bit cleared to 0"), - ] - - # 13. v_sad_u8, v_sad_hi_u8, v_sad_u16, v_sad_u32, v_msad_u8, v_lerp_u8 - cases += [ - _valu4_case("valu_sad_lerp", "v_sad_ops", [ - "v_mov_b32 v1, 0xff801001", "v_mov_b32 v2, 0x0080f002", "v_mov_b32 v3, 0xffffff00", - "v_sad_u8 v8, v1, v2, v3", # wraps 32-bit - "v_sad_hi_u8 v9, v1, v2, v3", # (byte_sad << 16) + S2 - "v_sad_u16 v10, v1, v2, v3", # 2x16-bit SAD + S2 - "v_sad_u32 v11, v1, v2, v3", # |v1 - v2| + S2 - ], "v_sad_u8 / v_sad_hi_u8 / v_sad_u16 / v_sad_u32 with 32-bit wrap"), - _valu4_case("valu_sad_lerp", "v_msad_and_lerp", [ - "v_mov_b32 v1, 0xff801001", "v_mov_b32 v2, 0x00800005", "v_mov_b32 v3, 100", - "v_msad_u8 v8, v1, v2, v3", # skips bytes 1 and 3 where S1 byte == 0 - "v_mov_b32 v4, 0xff030200", "v_mov_b32 v5, 0xff040301", "v_mov_b32 v6, 0x01000100", - "v_lerp_u8 v9, v4, v5, v6", # per-byte (a+b+(c&1))>>1 - "v_mov_b32 v7, 0x00feffff", - "v_lerp_u8 v10, v4, v5, v7", # upper bits of S2 bytes ignored - "v_mov_b32 v11, 0", - ], "v_msad_u8 zero-byte mask and v_lerp_u8 rounding/no-carry"), - ] - - # 14. v_qsad_pk_u16_u8, v_mqsad_pk_u16_u8, v_mqsad_u32_u8 - cases += [ - _valu4_case("valu_qsad_mqsad", "v_qsad_mqsad_pk_u16", [ - "v_mov_b32 v2, 0x40302010", "v_mov_b32 v3, 0x80706050", - "v_mov_b32 v4, 0x00150025", # S1 has two zero bytes for mqsad - "v_mov_b32 v6, 0xfffe0005", "v_mov_b32 v7, 0xfff00100", - "v_qsad_pk_u16_u8 v[8:9], v[2:3], v4, v[6:7]", - "v_mqsad_pk_u16_u8 v[10:11], v[2:3], v4, v[6:7]", - ], "v_qsad_pk_u16_u8 and v_mqsad_pk_u16_u8 with 16-bit wrap and zero S1 bytes"), - _valu4_case("valu_qsad_mqsad", "v_mqsad_u32_u8", [ - "v_mov_b32 v2, 0x40302010", "v_mov_b32 v3, 0x80706050", - "v_mov_b32 v4, 0x00150025", - "v_mov_b32 v12, 0xfffffffe", "v_mov_b32 v13, 10", - "v_mov_b32 v14, 20", "v_mov_b32 v15, 0xffffffff", - "v_mqsad_u32_u8 v[8:11], v[2:3], v4, v[12:15]", - ], "v_mqsad_u32_u8 four 32-bit accumulators with wrap"), - ] - - # 15. v_mul_hi_u32_u24, v_mul_hi_i32_i24, v_lshrrev_b64, v_ashrrev_i64 - cases += [ - _valu4_case("valu_mul24_sh64", "v_mul_hi_24", [ - "v_mov_b32 v1, 0xabffffff", "v_mov_b32 v2, 0xcdffffff", - "v_mul_hi_u32_u24 v8, v1, v2", # upper 8 bits ignored - "v_mul_hi_i32_i24 v9, v1, v2", # (-1)*(-1) >> 32 = 0 - "v_mov_b32 v3, 0x12800000", "v_mov_b32 v4, 0x347fffff", - "v_mul_hi_i32_i24 v10, v3, v4", # (-2^23)*(2^23-1) >> 32 - "v_mul_hi_u32_u24 v11, v3, v4", - ], "v_mul_hi_u32_u24 and v_mul_hi_i32_i24 (upper 8 bits ignored)"), - _valu4_case("valu_mul24_sh64", "v_lshr_ashr_64", [ - "v_mov_b32 v2, 0x12345678", "v_mov_b32 v3, 0x87654321", - "v_mov_b32 v1, 36", - "v_lshrrev_b64 v[8:9], v1, v[2:3]", - "v_ashrrev_i64 v[10:11], v1, v[2:3]", - ], "v_lshrrev_b64 and v_ashrrev_i64 shift=36"), - _valu4_case("valu_mul24_sh64", "v_lshr_ashr_64_mod64", [ - "v_mov_b32 v2, 0x12345678", "v_mov_b32 v3, 0x87654321", - "v_mov_b32 v1, 68", # 68 & 63 = 4 - "v_lshrrev_b64 v[8:9], v1, v[2:3]", - "v_ashrrev_i64 v[10:11], v1, v[2:3]", - ], "v_lshrrev_b64 and v_ashrrev_i64 shift masked to 6 bits"), - ] - - # 16. v_mad_u16 / v_mad_i16 (clamp, op_sel, kept half) - cases += [ - _valu4_case("valu_mad16", "v_mad_u16_i16_clamp_opsel", [ - "v_mov_b32 v1, 0x80000300", "v_mov_b32 v2, 0x00020200", "v_mov_b32 v3, 0x00010010", - f"v_mov_b32 v8, 0x{SENTINEL:08x}", - f"v_mov_b32 v9, 0x{SENTINEL:08x}", - f"v_mov_b32 v10, 0x{SENTINEL:08x}", - f"v_mov_b32 v11, 0x{SENTINEL:08x}", - "v_mad_u16 v8, v1, v2, v3 clamp", # 0x300*0x200+0x10 = 0x60010 -> 0xffff - "v_mad_u16 v9, v1, v2, v3", # wraps to 0x0010, hi kept - "v_mad_i16 v10, v1, v2, v3 op_sel:[1,1,1,0] clamp", # (-32768)*2 + 1 = -65535 -> 0x8000 - "v_mad_i16 v11, v1, v2, v3 op_sel:[0,0,0,1] clamp", # 0x300*0x200+0x10 -> 0x7fff in hi, lo kept - ], "v_mad_u16 / v_mad_i16 clamp, op_sel and untouched destination half"), - ] - - # 17. v_cvt_f16_u16 / v_cvt_f16_i16 / v_cvt_u16_f16 / v_cvt_i16_f16 (kept half, NaN, inf) - cases += [ - _valu4_case("valu_cvt_16", "v_cvt_u16_i16_f16_e64_nan_inf", [ - "v_mov_b32 v1, 0x00007e00", # +qNaN - "v_mov_b32 v2, 0x0000fe00", # -qNaN - "v_mov_b32 v3, 0x00007c00", # +inf - "v_mov_b32 v4, 0x0000fc00", # -inf - f"v_mov_b32 v8, 0x{SENTINEL:08x}", - f"v_mov_b32 v9, 0x{SENTINEL:08x}", - f"v_mov_b32 v10, 0x{SENTINEL:08x}", - f"v_mov_b32 v11, 0x{SENTINEL:08x}", - "v_cvt_u16_f16_e64 v8, v1", # +qNaN -> 0, check high half - "v_cvt_i16_f16_e64 v9, v2", # -qNaN -> 0, check high half - "v_cvt_u16_f16_e64 v10, v3", # +inf -> 0xffff, check high half - "v_cvt_i16_f16_e64 v11, v4", # -inf -> 0x8000, check high half - ], "v_cvt_u16/i16_f16_e64 on +-qNaN and +-inf (high half behavior)"), - _valu4_case("valu_cvt_16", "v_cvt_f16_u16_i16_e64_keep", [ - "v_mov_b32 v1, 0x0000fff0", # 65520 -> +inf (0x7c00) - "v_mov_b32 v2, 0x00008000", # -32768 -> -32768.0 (0xf800) - "v_mov_b32 v3, 0x0000002a", # 42 -> 42.0 (0x5140) - "v_mov_b32 v4, 0x00007fff", # 32767 -> 32768.0 (0x7800) - f"v_mov_b32 v8, 0x{SENTINEL:08x}", - f"v_mov_b32 v9, 0x{SENTINEL:08x}", - f"v_mov_b32 v10, 0x{SENTINEL:08x}", - f"v_mov_b32 v11, 0x{SENTINEL:08x}", - "v_cvt_f16_u16_e64 v8, v1", - "v_cvt_f16_i16_e64 v9, v2", - "v_cvt_f16_u16_e64 v10, v3", - "v_cvt_f16_i16_e64 v11, v4", - ], "v_cvt_f16_u16/i16_e64 overflow to +inf and high half behavior"), - ] - - # 18. v_cvt_flr_i32_f32 / v_cvt_rpi_i32_f32 (exact floor(x+0.5) + signed NaN; v_cvt_i32_f32 control) - cases += [ - _valu4_case("valu_cvt_flr_rpi", "v_cvt_rpi_precision", [ - "v_mov_b32 v1, 0x3effffff", # 0.49999997 (f32(x+0.5)==1.0, exact floor(x+0.5)==0) - "v_mov_b32 v2, 0x4b000001", # 8388609.0 (f32(x+0.5)==8388610.0, exact==8388609) - "v_mov_b32 v3, 0x4b7fffff", # 16777215.0 (f32(x+0.5)==16777216.0, exact==16777215) - "v_mov_b32 v4, 0xbf000000", # -0.5 -> floor(-0.5 + 0.5) = 0 - "v_cvt_rpi_i32_f32 v8, v1", - "v_cvt_rpi_i32_f32 v9, v2", - "v_cvt_rpi_i32_f32 v10, v3", - "v_cvt_rpi_i32_f32 v11, v4", - ], "v_cvt_rpi_i32_f32 exact floor(x+0.5) vs binary32 x+0.5"), - _valu4_case("valu_cvt_flr_rpi", "v_cvt_flr_rpi_nan_inf", [ - "v_mov_b32 v1, 0x7fc00000", # +qNaN - "v_mov_b32 v2, 0xffc00000", # -qNaN - "v_cvt_flr_i32_f32 v8, v1", - "v_cvt_flr_i32_f32 v9, v2", - "v_cvt_rpi_i32_f32 v10, v1", - "v_cvt_rpi_i32_f32 v11, v2", - ], "v_cvt_flr_i32_f32 / v_cvt_rpi_i32_f32 on +qNaN and -qNaN"), - _valu4_case("valu_cvt_flr_rpi", "v_cvt_i32_f32_nan_control", [ - "v_mov_b32 v1, 0x7fc00000", # +qNaN - "v_mov_b32 v2, 0xffc00000", # -qNaN - "v_mov_b32 v3, 0x7f800001", # +sNaN - "v_mov_b32 v4, 0xff800001", # -sNaN - "v_cvt_i32_f32 v8, v1", - "v_cvt_i32_f32 v9, v2", - "v_cvt_i32_f32 v10, v3", - "v_cvt_i32_f32 v11, v4", - ], "control: v_cvt_i32_f32 returns 0 for every NaN"), - _valu4_case("valu_cvt_flr_rpi", "v_cvt_flr_edges", [ - "v_mov_b32 v1, 0xbf800001", # -1.0000001 -> -2 - "v_mov_b32 v2, 0x7f800000", # +inf -> INT_MAX - "v_mov_b32 v3, 0xff800000", # -inf -> INT_MIN - "v_mov_b32 v4, 0x4f000000", # +2^31 -> INT_MAX - "v_cvt_flr_i32_f32 v8, v1", - "v_cvt_flr_i32_f32 v9, v2", - "v_cvt_flr_i32_f32 v10, v3", - "v_cvt_flr_i32_f32 v11, v4", - ], "v_cvt_flr_i32_f32 negative fraction, infinities and 2^31 saturation"), - ] - - # 19. v_cvt_pknorm_i16_f32 / v_cvt_pknorm_u16_f32 (NaN, inf, out-of-range, ties) - cases += [ - _valu4_case("valu_cvt_pknorm", "v_cvt_pknorm_nan_inf", [ - "v_mov_b32 v1, 0x7fc00000", # +qNaN - "v_mov_b32 v2, 0xffc00000", # -qNaN - "v_mov_b32 v3, 0x7f800000", # +inf - "v_mov_b32 v4, 0xff800000", # -inf - "v_cvt_pknorm_i16_f32 v8, v1, v2", - "v_cvt_pknorm_u16_f32 v9, v1, v2", - "v_cvt_pknorm_i16_f32 v10, v3, v4", - "v_cvt_pknorm_u16_f32 v11, v3, v4", - ], "v_cvt_pknorm_i16/u16_f32 on +-qNaN and +-inf"), - _valu4_case("valu_cvt_pknorm", "v_cvt_pknorm_ties", [ - "v_mov_b32 v1, 0x3f000000", # 0.5 -> 0.5*32767 = 16383.5 (RNE=16384), 0.5*65535 = 32767.5 (RNE=32768) - "v_mov_b32 v2, 0xbf000000", # -0.5 -> -16383.5 (RNE=-16384), u16 -> 0 - "v_mov_b32 v3, 0x3f800000", # 1.0 -> 32767 / 65535 - "v_mov_b32 v4, 0xbf800000", # -1.0 -> -32767 (0x8001) / 0 - "v_cvt_pknorm_i16_f32 v8, v1, v2", - "v_cvt_pknorm_u16_f32 v9, v1, v2", - "v_cvt_pknorm_i16_f32 v10, v3, v4", - "v_cvt_pknorm_u16_f32 v11, v3, v4", - ], "v_cvt_pknorm_i16/u16_f32 ties at +-0.5 and +-1.0 endpoints"), - ] - - # 19b. v_cvt_pknorm_i16/u16_f16 and v_cvt_norm_i16/u16_f16 (f16 sources) - cases += _cvt_norm_f16_cases() - - # 20. Packed 16-bit integer ops (v_pk_add/sub_u16/i16, v_pk_mul_lo_u16, v_pk_mad_u16/i16, v_pk_min/max_u16/i16) - cases += [ - _valu4_case("valu_pk_int16", "v_pk_add_sub_u16_i16_clamp", [ - "v_mov_b32 v1, 0xffff8000", "v_mov_b32 v2, 0x00028001", - "v_pk_add_u16 v8, v1, v2", # wraps both halves - "v_pk_add_u16 v9, v1, v2 clamp", # saturates both halves to 0xffff - "v_mov_b32 v3, 0x00010005", "v_mov_b32 v4, 0x00020003", - "v_pk_sub_u16 v10, v3, v4 clamp", # hi clamps to 0, lo = 2 - "v_mov_b32 v5, 0x7fff8000", "v_mov_b32 v6, 0x0001ffff", - "v_pk_add_i16 v11, v5, v6 clamp", # hi clamps +32767, lo clamps -32768 - ], "v_pk_add/sub_u16/i16 wrap and clamp saturation"), - _valu4_case("valu_pk_int16", "v_pk_sub_i16_mul_minmax", [ - "v_mov_b32 v1, 0x80007fff", "v_mov_b32 v2, 0x0001ffff", - "v_pk_sub_i16 v8, v1, v2 clamp", # hi clamps -32768, lo clamps +32767 - "v_mov_b32 v3, 0x01000010", "v_mov_b32 v4, 0x02000020", - "v_pk_mul_lo_u16 v9, v3, v4", # hi wraps to 0x0000, lo = 0x0200 - "v_mov_b32 v5, 0xffff0005", "v_mov_b32 v6, 0x0001fffb", - "v_pk_min_i16 v10, v5, v6", - "v_pk_max_u16 v11, v5, v6", - ], "v_pk_sub_i16 clamp, v_pk_mul_lo_u16, v_pk_min_i16 and v_pk_max_u16"), - _valu4_case("valu_pk_int16", "v_pk_mad_u16_i16_clamp", [ - "v_mov_b32 v1, 0x0100ffff", "v_mov_b32 v2, 0x02000002", "v_mov_b32 v3, 0x00010001", - "v_pk_mad_u16 v8, v1, v2, v3", # wraps both halves - "v_pk_mad_u16 v9, v1, v2, v3 clamp", # saturates both halves to 0xffff - "v_mov_b32 v4, 0x7fff8000", "v_mov_b32 v5, 0x00020002", "v_mov_b32 v6, 0x0001ffff", - "v_pk_mad_i16 v10, v4, v5, v6", # wraps both halves - "v_pk_mad_i16 v11, v4, v5, v6 clamp", # hi -> 0x7fff, lo -> 0x8000 - ], "v_pk_mad_u16 / v_pk_mad_i16 wrap and full-width clamp"), - _valu4_case("valu_pk_int16", "v_pk_int16_opsel_minmax", [ - "v_mov_b32 v1, 0x00100001", "v_mov_b32 v2, 0x00200002", - "v_pk_add_i16 v8, v1, v2 op_sel:[1,0] op_sel_hi:[0,1]", - "v_pk_sub_i16 v9, v1, v2 op_sel:[0,1] op_sel_hi:[1,0]", - "v_mov_b32 v3, 0xffff0005", "v_mov_b32 v4, 0x0001fffb", - "v_pk_max_i16 v10, v3, v4", - "v_pk_min_u16 v11, v3, v4", - ], "v_pk_*_i16/u16 op_sel/op_sel_hi, v_pk_max_i16 and v_pk_min_u16"), - ] - - # 21. 16-bit three-operand min/max/median (v_min3/max3_f16, v_min3/max3/med3_i16/u16) - cases += [ - _valu4_case("valu_min3_max3_med3_16", "v_min3_max3_f16_nan_zero", [ - f"v_mov_b32 v8, 0x{SENTINEL:08x}", - f"v_mov_b32 v9, 0x{SENTINEL:08x}", - f"v_mov_b32 v10, 0x{SENTINEL:08x}", - f"v_mov_b32 v11, 0x{SENTINEL:08x}", - "v_mov_b32 v1, 0x00007e00", "v_mov_b32 v2, 0x00003c00", "v_mov_b32 v3, 0x00004000", - "v_min3_f16 v8, v1, v2, v3", # NaN yields other operand, hi kept - "v_max3_f16 v9, v2, v1, v3", - "v_mov_b32 v4, 0x00000000", "v_mov_b32 v5, 0x00008000", "v_mov_b32 v6, 0x0000bc00", - "v_min3_f16 v10, v4, v5, v2", # -0 orders below +0 - "v_max3_f16 v11, v4, v5, v6 clamp", # +0 > -0 > -1.0, clamped to [0, 1] - ], "v_min3_f16 / v_max3_f16 NaN, -0/+0 ordering, clamp and untouched hi half"), - _valu4_case("valu_min3_max3_med3_16", "v_min3_max3_med3_i16_u16", [ - f"v_mov_b32 v8, 0x{SENTINEL:08x}", - f"v_mov_b32 v9, 0x{SENTINEL:08x}", - f"v_mov_b32 v10, 0x{SENTINEL:08x}", - f"v_mov_b32 v11, 0x{SENTINEL:08x}", - "v_mov_b32 v1, 0xfff00005", "v_mov_b32 v2, 0x00010002", "v_mov_b32 v3, 0x0003fff8", - "v_min3_i16 v8, v1, v2, v3 op_sel:[1,0,0,1]", # writes hi, keeps lo - "v_max3_u16 v9, v1, v2, v3 op_sel:[1,0,0,0]", # writes lo, keeps hi - "v_min3_u16 v10, v1, v2, v3 op_sel:[1,0,0,0]", - "v_max3_i16 v11, v1, v2, v3 op_sel:[1,0,0,1]", - ], "v_min3/max3_i16/u16 with op_sel and untouched destination half"), - _valu4_case("valu_min3_max3_med3_16", "v_med3_i16_u16_opsel", [ - f"v_mov_b32 v8, 0x{SENTINEL:08x}", - f"v_mov_b32 v9, 0x{SENTINEL:08x}", - f"v_mov_b32 v10, 0x{SENTINEL:08x}", - f"v_mov_b32 v11, 0x{SENTINEL:08x}", - "v_mov_b32 v1, 0xfff00010", "v_mov_b32 v2, 0x00050020", "v_mov_b32 v3, 0x0001fff5", - "v_med3_i16 v8, v1, v2, v3 op_sel:[1,1,0,1]", # signed median of -16, 5, -11 = -11 in hi - "v_med3_u16 v9, v1, v2, v3 op_sel:[1,1,0,0]", # unsigned median of 0xfff0, 5, 0xfff5 = 0xfff0 in lo - "v_med3_i16 v10, v1, v2, v3", - "v_med3_u16 v11, v1, v2, v3", - ], "v_med3_i16 / v_med3_u16 signed vs unsigned median with op_sel"), - _valu4_case("valu_min3_max3_med3_16", "v_min3_max3_i16_u16_clamp", [ - "v_mov_b32 v8, 0xbeef5a5a", - "v_mov_b32 v9, 0xbeef5a5a", - "v_mov_b32 v10, 0xbeef5a5a", - "v_mov_b32 v11, 0xbeef5a5a", - "v_mov_b32 v1, 0xfff00005", "v_mov_b32 v2, 0x00010002", "v_mov_b32 v3, 0x0003fff8", - "v_min3_i16 v8, v1, v2, v3 op_sel:[1,0,0,1] clamp", # writes hi (fff0), keeps lo (5a5a) - "v_max3_u16 v9, v1, v2, v3 op_sel:[1,0,0,0] clamp", # writes lo (fff8), keeps hi (beef) - "v_min3_u16 v10, v1, v2, v3 op_sel:[1,0,0,0] clamp", # writes lo (0002), keeps hi (beef) - "v_max3_i16 v11, v1, v2, v3 op_sel:[1,0,0,1] clamp", # writes hi (0002), keeps lo (5a5a) - ], "v_min3/max3_i16/u16 clamp range-invariance and untouched destination half"), - _valu4_case("valu_min3_max3_med3_16", "v_med3_i16_u16_clamp", [ - "v_mov_b32 v8, 0xbeef5a5a", - "v_mov_b32 v9, 0xbeef5a5a", - "v_mov_b32 v10, 0xbeef5a5a", - "v_mov_b32 v11, 0xbeef5a5a", - "v_mov_b32 v1, 0xfff00010", "v_mov_b32 v2, 0x00050020", "v_mov_b32 v3, 0x0001fff5", - "v_med3_i16 v8, v1, v2, v3 op_sel:[1,1,0,1] clamp", # writes hi (fff5), keeps lo (5a5a) - "v_med3_u16 v9, v1, v2, v3 op_sel:[1,1,0,0] clamp", # writes lo (fff0), keeps hi (beef) - "v_med3_i16 v10, v1, v2, v3 clamp", # writes lo (0010), keeps hi (beef) - "v_med3_u16 v11, v1, v2, v3 clamp", # writes lo (0020), keeps hi (beef) - ], "v_med3_i16 / v_med3_u16 clamp range-invariance and untouched destination half"), - _valu4_case("valu_min3_max3_med3_16", "v_min3_max3_med3_f16_clamp_nan", [ - "v_mov_b32 v8, 0xbeef5a5a", - "v_mov_b32 v9, 0xbeef5a5a", - "v_mov_b32 v10, 0xbeef5a5a", - "v_mov_b32 v11, 0xbeef5a5a", - "v_mov_b32 v1, 0x38007e00", - "v_mov_b32 v2, 0xc0004000", - "v_mov_b32 v3, 0x3800bc00", - "v_min3_f16 v8, v1, v2, v3 clamp", - "v_max3_f16 v9, v1, v2, v3 clamp", - "v_med3_f16 v10, v1, v2, v3 clamp", - "v_med3_f16 v11, v1, v2, v3 op_sel:[1,1,1,1] clamp", - ], "v_min3/max3/med3_f16 NaN, DX10 clamp, dirty high-half sentinels and op_sel"), - ] - - # 22. v_swaprel_b32 (M0[25:16] dst offset, M0[9:0] src offset, ignored upper M0 bits, self-swap, inactive EXEC) - cases += [ - _valu4_case("valu_swaprel", "v_swaprel_offsets_and_ignored_m0", [ - "v_mov_b32 v8, 0x11111111", "v_mov_b32 v9, 0x22222222", - "v_mov_b32 v10, 0x33333333", "v_mov_b32 v11, 0x44444444", - "s_mov_b32 m0, 0xfc01fc02", # dst_off=1 (v9), src_off=2 (v10); upper M0 bits ignored - "v_swaprel_b32 v8, v8", - ], "v_swaprel_b32 M0[25:16] and M0[9:0] offsets with ignored upper M0 bits"), - _valu4_case("valu_swaprel", "v_swaprel_self_and_inactive_exec", [ - "v_mov_b32 v8, 0x12345678", "v_mov_b32 v9, 0x9abcdef0", - "v_mov_b32 v10, 0x55555555", "v_mov_b32 v11, 0x66666666", - "s_mov_b32 m0, 0x00000001", - "v_swaprel_b32 v9, v8", # self-swap v9 <-> v9 (unchanged) - "s_mov_b32 m0, 0x00010002", - "{smov} {stmp}, {exec}", - "{smov} {exec}, 0", - "v_swaprel_b32 v8, v8", # inactive lane leaves v9 and v10 untouched - "{smov} {exec}, {stmp}", - ], "v_swaprel_b32 self-swap and inactive EXEC lane preservation"), - ] - - # 23. v_pack_b32_f16 source abs / -|src| modifiers (including -0 and -qNaN payload) - cases += [ - _valu4_case("valu_pack_b32_f16_abs", "v_pack_b32_f16_abs_neg_opsel", [ - "v_mov_b32 v1, 0xfe01bc00", "v_mov_b32 v2, 0x8000fe05", - "v_pack_b32_f16 v8, |v1|, |v2|", - "v_pack_b32_f16 v9, |v1|, |v2| op_sel:[1,1]", - "v_pack_b32_f16 v10, -|v1|, -|v2| op_sel:[1,0]", - "v_pack_b32_f16 v11, -v1, |v2| op_sel:[0,1]", - ], "v_pack_b32_f16 abs and -|src| with op_sel on -1.0, -0.0 and -qNaN payloads"), - ] - - # 24. v_bfe_u32 / v_bfe_i32 past bit 31 (offset + width > 32), width 0, and the bits above [4:0]. The first - # three cases take offset and width from VGPRs (the translator's bfe_width path), the last one from constants - # (folded at translation time). - cases += [ - _valu4_case("valu_bfe_past31", "v_bfe_past31_vgpr", [ - "v_mov_b32 v1, 0xd2f90159", "v_mov_b32 v2, 28", "v_mov_b32 v3, 16", "v_mov_b32 v4, 31", - "v_bfe_i32 v8, v1, v2, v3", # off 28 + width 16: a field that would end at bit 43 - "v_bfe_u32 v9, v1, v2, v3", - "v_bfe_i32 v10, v1, v2, v4", # off 28 + width 31 - "v_bfe_u32 v11, v1, v2, v4", - ], "v_bfe_i32/u32 with offset + width > 32 from VGPRs"), - _valu4_case("valu_bfe_past31", "v_bfe_past31_sign", [ - "v_mov_b32 v1, 0x5f000000", "v_mov_b32 v2, 30", "v_mov_b32 v3, 4", "v_mov_b32 v4, 3", - "v_bfe_i32 v8, v1, v2, v3", # field bits 30-31 = 01, bit 33 (width 4's top) does not exist - "v_bfe_i32 v9, v1, 24, v3", # off 24 + width 4 inside: control, 0xf -> -1 - "v_mov_b32 v5, 0x80000000", "v_mov_b32 v6, 1", - "v_bfe_i32 v10, v5, v4, v6", # off 3 width 1 on bit 3 = 0: control - "v_bfe_i32 v11, v5, 31, v3", # off 31 + width 4: only bit 31 exists, so -1 (not 1) - ], "v_bfe_i32 sign of a field cut at bit 31"), - _valu4_case("valu_bfe_past31", "v_bfe_high_bits", [ - "v_mov_b32 v1, 0xd2f90159", "v_mov_b32 v2, 36", "v_mov_b32 v3, 32", "v_mov_b32 v4, 0xfffffffc", - "v_mov_b32 v5, 0xfffffff0", - "v_bfe_u32 v8, v1, v2, 8", # offset 36: 4 if only [4:0] is read - "v_bfe_u32 v9, v1, 0, v3", # width 32: 0 if only [4:0] is read - "v_bfe_i32 v10, v1, v4, v5", # offset 0xfffffffc (28), width 0xfffffff0 (16) - "v_bfe_i32 v11, v1, v2, 0", # width 0 - ], "v_bfe offset and width bits above [4:0], and width 0"), - _valu4_case("valu_bfe_past31", "v_bfe_past31_const", [ - "v_mov_b32 v1, 0xd2f90159", - "v_bfe_i32 v8, v1, 28, 16", # constant offset and width: folded by the translator - "v_bfe_u32 v9, 0xd2f90159, 28, 31", - "v_bfe_i32 v10, v1, 60, 48", # 60 & 31 = 28, 48 & 31 = 16 - "v_bfe_i32 v11, v1, 31, 64", # width 64 & 31 = 0 - ], "v_bfe with constant offset and width past bit 31"), - ] - - return cases - - -def _translate_case(work, case): - os.makedirs(os.path.join(work, "disasm"), exist_ok=True) - name = f"ps_int_hw_{case.name}" - src = os.path.join(work, "disasm", name + ".s") - body = case.lines(wave=32) + ["exp mrt0 v8, v9, v10, v11 done vm", "s_endpgm"] - with open(src, "w", encoding="utf-8", newline="\n") as f: - f.write(f"; {name}\n" + "".join(f"\t{ln}\n" for ln in body)) - with open(os.path.join(work, name + ".dxbc"), "wb") as f: - f.write(STUB_DXBC) - with warnings.catch_warnings(): - warnings.simplefilter("ignore", ResourceWarning) - spv = rdna2spirv.translate(src) - return list(spirv_mini_interp.run_fragment(spv)["%out_mrt0"]) - - -def run_translator(cases): - out = {} - with tempfile.TemporaryDirectory(prefix="int_hw_probe_") as work: - for case in cases: - try: - out[case.name] = _translate_case(work, case) - except Exception as e: - out[case.name] = f"error: {type(e).__name__}: {e}" - return out - - -def run_hw(cases, arch=None, waves=(32, 64)): - from hw_oracle import asm, runner # noqa: E402 - oracle = runner.open_oracle(arch=arch) - try: - device = oracle.device - per_wave = {} - for wave in waves: - kernels = [asm.Kernel(case.lines(wave=wave), wave=wave, threads=1, words=4) for case in cases] - res = oracle.run(kernels, words=4) - per_wave[wave] = {case.name: r for case, r in zip(cases, res)} - return device, per_wave - finally: - oracle.close() - - -def _fmt_words(w): - if isinstance(w, list): - return " ".join(f"0x{x:08x}" for x in w) - return str(w) - - -def self_test(): - cases = build_cases() - names = [c.name for c in cases] - assert len(names) == len(set(names)), "duplicate case names" - for name in KNOWN_DIVERGENCES: - assert name in names, f"unknown KNOWN_DIVERGENCES key: {name}" - res = run_translator(cases) - errors = {k: v for k, v in res.items() if not isinstance(v, list)} - assert not errors, f"translator errors: {errors}" - print(f"self-test: {len(cases)} cases across {len({c.group for c in cases})} groups translated and ran on CPU OK") - return 0 - - -def _validate_json_out(raw_path): - """Validate --json output path before running translator/hardware cases; return (abs_path, err_msg).""" - if not raw_path.strip(): - return None, "ERROR: --json path must not be empty" - out_path = os.path.abspath(raw_path) - if os.path.isdir(out_path): - return None, f"ERROR: --json path is a directory: {out_path}" - cur = os.path.dirname(out_path) - while cur: - if os.path.exists(cur): - if not os.path.isdir(cur): - return None, f"ERROR: --json parent path is not a directory: {cur}" - break - parent = os.path.dirname(cur) - if parent == cur: - break - cur = parent - return out_path, None - - -def main(argv=None): - ap = argparse.ArgumentParser(description=__doc__.splitlines()[0]) - ap.add_argument("--oracle", choices=("translator", "hw", "both"), default="translator") - ap.add_argument("--wave", choices=("32", "64", "both"), default="both") - ap.add_argument("--group", action="append", default=[], help="run only named group(s)") - ap.add_argument("--hw-arch", default=None, help="override GPU architecture for hw_oracle") - ap.add_argument("--list-groups", action="store_true") - ap.add_argument("--strict", action="store_true", help="treat known translator divergences as failures") - ap.add_argument("--json", dest="json_out", default=None, help="write raw results to a JSON file") - ap.add_argument("--self-test", action="store_true") - args = ap.parse_args(argv) - - if args.self_test: - return self_test() - - cases = build_cases() - groups = [] - for c in cases: - if c.group not in groups: - groups.append(c.group) - if args.list_groups: - for g in groups: - n = sum(1 for c in cases if c.group == g) - print(f"{g:<22} ({n} cases)") - return 0 - - if args.group: - unknown = [g for g in args.group if g not in groups] - if unknown: - print(f"unknown group(s): {', '.join(unknown)}", file=sys.stderr) - return 2 - want = set(args.group) - cases = [c for c in cases if c.group in want] - - out_path = None - if args.json_out is not None: - out_path, err_msg = _validate_json_out(args.json_out) - if err_msg: - print(err_msg, file=sys.stderr) - return 2 - - waves = (32, 64) if args.wave == "both" else (int(args.wave),) - tr_res = run_translator(cases) if args.oracle in ("translator", "both") else None - hw_device, hw_res = None, None - if args.oracle in ("hw", "both"): - from hw_oracle import runner # noqa: E402 - try: - hw_device, hw_res = run_hw(cases, arch=args.hw_arch, waves=waves) - except runner.Unavailable as e: - print(f"hardware oracle unavailable: {e}", file=sys.stderr) - return 77 - print(f"hardware oracle: {hw_device} (waves: {','.join(str(w) for w in waves)})") - - mismatches = 0 - known_diffs = 0 - wave_diffs = 0 - records = [] - for c in cases: - tr = tr_res[c.name] if tr_res is not None else None - h32 = hw_res[32][c.name] if hw_res and 32 in hw_res else None - h64 = hw_res[64][c.name] if hw_res and 64 in hw_res else None - hw_ref = h32 if h32 is not None else h64 - status = "OK" - tag = None - if h32 is not None and h64 is not None and h32 != h64: - status = "WAVE_DIFF" - wave_diffs += 1 - elif (tr is not None and not isinstance(tr, list)) or (hw_ref is not None and not isinstance(hw_ref, list)): - status = "ERROR" - mismatches += 1 - elif tr is not None and hw_ref is not None and tr != hw_ref: - known = KNOWN_DIVERGENCES.get(c.name) - if known and hw_ref == known[1]: - status = "KNOWN_DIFF" - tag = known[0] - known_diffs += 1 - else: - status = "MISMATCH" - mismatches += 1 - records.append({ - "group": c.group, "name": c.name, "note": c.note, "status": status, "known_tag": tag, - "translator": tr, "hw_w32": h32, "hw_w64": h64, - }) - if status != "OK" or args.oracle != "both": - label = f"{status}:{tag}" if tag else status - print(f"[{label:<22}] {c.group}/{c.name}: {c.note}") - if h32 is not None: - print(f" hw_w32: {_fmt_words(h32)}") - if h64 is not None and h64 != h32: - print(f" hw_w64: {_fmt_words(h64)}") - if tr is not None: - print(f" transl: {_fmt_words(tr)}") - - total = len(cases) - matched = total - mismatches - known_diffs - wave_diffs - print(f"summary: {total} cases: {matched} match, {known_diffs} known divergence, " - f"{mismatches} unexpected mismatch, {wave_diffs} wave32/64 diff") - - if out_path is not None: - try: - parent = os.path.dirname(out_path) - if parent: - os.makedirs(parent, exist_ok=True) - with open(out_path, "w", encoding="utf-8", newline="\n") as f: - json.dump({"device": hw_device, "waves": list(waves), "cases": records}, f, indent=2) - f.write("\n") - except OSError as e: - print(f"ERROR: failed to write --json {out_path}: {e}", file=sys.stderr) - return 2 - - if mismatches or wave_diffs or (args.strict and known_diffs): - return 1 - return 0 - - -if __name__ == "__main__": - try: # a redirected stdout is strict ANSI code page under -I; write '?' for what it cannot encode - sys.stdout.reconfigure(errors="replace") - except (AttributeError, ValueError, OSError): - pass - sys.exit(main()) diff --git a/tools/interp_hw_probe.py b/tools/interp_hw_probe.py deleted file mode 100644 index 14efbeb89..000000000 --- a/tools/interp_hw_probe.py +++ /dev/null @@ -1,292 +0,0 @@ -r"""SHADER-430: what the RDNA2 v_interp ALU ops compute from the attribute words, measured on an AMD GPU. - -v_interp_* run in a compute wave too: they read the attribute words from LDS at M0 (gfx1036, M0 = 0: attribute N -takes 12 dwords from byte 48*N; channel c's P0 and P10 words are dwords 2c and 2c+1, its P20 word is dword 8+c). This -tool writes random parameter words there (plain f32 values, and packed f16 pairs as a 16-bit varying leaves them), -runs every op through tools/hw_oracle and checks each result against exact models (fractions.Fraction, round to -nearest even): - - v_interp_mov_f32 p0 the raw P0 word - v_interp_p1_f32 fma(P10, I, P0), one rounding to f32 (also for a packed channel: raw words as f32) - v_interp_p2_f32 fma(P20, J, p1), one rounding to f32 - v_interp_p1ll_f16 [high] fma(h10, I, h0) on the chosen f16 halves, exact widening, one rounding to f32 - v_interp_p2_f16 [high] fma(h20, J, p1ll) rounded ONCE to f16 (not f32 then f16); the high half of vdst kept - -Then a set of hand-built f16 rounding ties (p1ll lands exactly between two f16, P20*J is far below one f32 ulp) that -the two p2_f16 rounding models disagree on. What it does not cover: what the SPI writes into LDS for a real draw -(whether P10/P20 of a packed channel are f32 or per-half f16 differences under FP16_INTERP_MODE), v_interp_p1lv_f16, -f16 inf/NaN halves. Standard library only; no game files. - -Usage: - python -I tools/interp_hw_probe.py # gfx1036, seeds 1-4, 4 kernels each, f32 denormals kept - python -I tools/interp_hw_probe.py --arch gfx1030 --seeds 1,2,3 --kernels 8 - python -I tools/interp_hw_probe.py --denorm32 0 # MODE flushing f32 denormals: denormal P0/P10/P20 read as 0 - -Exit codes: 0 every model matches, 1 a mismatch, 2 a harness error, 77 no hardware oracle on this machine. -""" -import argparse -import math -import os -import random -import struct -import sys -from fractions import Fraction as F - -sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) -from hw_oracle import asm, runner # noqa: E402 - -LANES = 32 -ATTRS = 8 -IJ_BASE = 1024 - - -def f32v(x): return struct.unpack(" a: - e -= 1 - e = max(e, emin) - ulp = F(2) ** (e - mbits) - n = a / ulp - fl = math.floor(n) - r = n - fl - if r > F(1, 2) or (r == F(1, 2) and fl % 2): - fl += 1 - v = fl * ulp - if v >= F(2) ** (emax + 1): - return s * math.inf - return s * float(v) - - -def r32(q): return rnd(q, 23, -126, 127) -def r16(q): return rnd(q, 10, -14, 15) - - -def same(got, want, bits=32): - g = f32v(got) if bits == 32 else f16v(got) - if want == 0: - return g == 0 and math.copysign(1, g) == math.copysign(1, want) - return g == want - - -def finite(*xs): return all(math.isfinite(x) for x in xs) - - -def flush32(x, flush): - return math.copysign(0.0, x) if flush and x != 0 and abs(x) < 2.0 ** -126 else x - - -def lds_prologue(params, ij): - """Lane 0 writes the attribute words, each lane its I/J pair; then M0 = 0 and v20/v21 = I/J.""" - L = ["s_mov_b32 s40, exec_lo", "s_mov_b32 exec_lo, 1"] - - def wr(addr, val): - L.extend([f"v_mov_b32_e32 v31, {addr:#x}", f"v_mov_b32_e32 v32, {val:#x}", "ds_write_b32 v31, v32"]) - for (a, c), (p0, p10, p20) in params.items(): - wr(48 * a + 8 * c, p0) - wr(48 * a + 8 * c + 4, p10) - wr(48 * a + 32 + 4 * c, p20) - for lane, (i, j) in enumerate(ij): - L.append(f"s_mov_b32 exec_lo, {1 << lane:#x}") - wr(IJ_BASE + 8 * lane, i) - wr(IJ_BASE + 8 * lane + 4, j) - L += ["s_mov_b32 exec_lo, s40", "s_waitcnt lgkmcnt(0)", "s_barrier", - "v_lshlrev_b32_e32 v33, 3, v0", f"v_add_nc_u32_e32 v33, {IJ_BASE:#x}, v33", - "ds_read_b32 v20, v33", "ds_read_b32 v21, v33 offset:4", "s_waitcnt lgkmcnt(0)", - "s_mov_b32 m0, 0", "s_nop 7"] - return L - - -# --- random kernels -------------------------------------------------------------------------------------------------- - -def gen_word(rng, packed): - if packed: - while True: - lo, hi = rng.getrandbits(16), rng.getrandbits(16) - if (lo & 0x7C00) != 0x7C00 and (hi & 0x7C00) != 0x7C00: # no f16 inf/NaN halves - return lo | hi << 16 - return f32w(rng.uniform(-8, 8) * 2.0 ** rng.randint(-6, 6)) - - -NOUT_PER = 7 - - -def random_kernel(rng, mode): - params, kinds = {}, {} - for a in range(ATTRS): - packed = a % 2 == 1 or rng.random() < 0.5 - for c in range(4): - params[a, c] = tuple(gen_word(rng, packed) for _ in range(3)) - kinds[a, c] = "packed" if packed else "f32" - ij = [(f32w(rng.uniform(-0.25, 1.25)), f32w(rng.uniform(-0.25, 1.25))) for _ in range(LANES)] - L = lds_prologue(params, ij) - nout = ATTRS * 4 * NOUT_PER - L.append(f"v_mul_u32_u24_e32 v34, {4 * nout}, v0") - k = 0 - - def st(reg): - nonlocal k - L.append(f"global_store_dword v34, v{reg}, s[2:3] offset:{4 * k}") - k += 1 - for a in range(ATTRS): - for c in "xyzw": - at = f"attr{a}.{c}" - L += [f"v_interp_p1_f32 v2, v20, {at}", "s_nop 3"]; st(2) - L += [f"v_interp_p2_f32 v2, v21, {at}", "s_nop 3"]; st(2) - L += [f"v_interp_p1ll_f16 v3, v20, {at}", "s_nop 3"]; st(3) - L += ["v_mov_b32_e32 v5, 0xdeadbeef", f"v_interp_p2_f16 v5, v21, {at}, v3", "s_nop 3"]; st(5) - L += [f"v_interp_p1ll_f16 v3, v20, {at} high", "s_nop 3"]; st(3) - L += ["v_mov_b32_e32 v5, 0xdeadbeef", f"v_interp_p2_f16 v5, v21, {at}, v3 high", "s_nop 3"]; st(5) - L += [f"v_interp_mov_f32 v6, p0, {at}", "s_nop 3"]; st(6) - L += ["s_waitcnt vmcnt(0)", "s_endpgm"] - kern = asm.Kernel(L, wave=32, threads=LANES, words=nout * LANES, raw=True, lds=2048, vgprs=40, sgprs=48, mode=mode) - return kern, (params, kinds, ij, nout) - - -def check_random(res, info, flush, tally, bad): - params, kinds, ij, nout = info - for lane, (ib, jb) in enumerate(ij): - I, J = F(f32v(ib)), F(f32v(jb)) - for (a, ci), (p0, p10, p20) in params.items(): - o = res[lane * nout + (a * 4 + ci) * NOUT_PER:][:NOUT_PER] - kind = kinds[a, ci] - - def t(name, ok, detail): - tally.setdefault((kind, name), [0, 0])[0 if ok else 1] += 1 - if not ok and len(bad) < 10: - bad.append(f"{kind} {name}: lane {lane} attr{a}.{'xyzw'[ci]} words {p0:#010x} {p10:#010x} " - f"{p20:#010x} I/J {ib:#010x} {jb:#010x} {detail}") - t("mov p0 = raw word", o[6] == p0, f"got {o[6]:#010x}") - P0, P10, P20 = f32v(p0), f32v(p10), f32v(p20) - if finite(P0, P10, P20): - w1 = flush32(r32(F(flush32(P10, flush)) * I + F(flush32(P0, flush))), flush) - t("p1_f32 = fma(P10, I, P0)", same(o[0], w1), f"got {o[0]:#010x} want {f32w(w1):#010x}") - g1 = f32v(o[0]) - if math.isfinite(g1): - w2 = flush32(r32(F(flush32(P20, flush)) * J + F(g1)), flush) - t("p2_f32 = fma(P20, J, p1)", same(o[1], w2), f"got {o[1]:#010x} want {f32w(w2):#010x}") - for hi, (i1, i2) in ((0, (2, 3)), (1, (4, 5))): - sh = 16 * hi - h0, h10, h20 = f16v(p0 >> sh), f16v(p10 >> sh), f16v(p20 >> sh) - tag = "high" if hi else "low" - if not finite(h0, h10, h20): # an f32 word's halves can be f16 inf/NaN: not modelled - continue - w1 = r32(F(h10) * I + F(h0)) - t(f"p1ll_f16 {tag} = fma(h10, I, h0) in f32", same(o[i1], w1), f"got {o[i1]:#010x} want {f32w(w1):#010x}") - g = f32v(o[i1]) - if math.isfinite(g): - w = r16(F(h20) * J + F(g)) - if math.isfinite(w): - t(f"p2_f16 {tag} = fma(h20, J, p1ll) in f16", same(o[i2] & 0xFFFF, w, 16), - f"got {o[i2]:#010x} want {f16w(w):#06x}") - t(f"p2_f16 {tag} keeps vdst[31:16]", o[i2] >> 16 == 0xDEAD, f"got {o[i2]:#010x}") - - -# --- rounding ties for p2_f16 ---------------------------------------------------------------------------------------- - -def tie_kernel(mode): - """Attribute a holds one (h0, h10, h20) triple in both halves; each lane gets I/J that put p1ll on an f16 tie.""" - groups = [] - for base in (1.0, 1.0 + 2 ** -10, -1.0, 0.5, 3.0): - step = 2.0 ** (math.frexp(abs(base))[1] - 12) # half an f16 ulp at |base| - groups.append(((base, math.copysign(1.0, base), 2.0 ** -14), - [(k * step, J) for k in (1, 3) for J in (2.0 ** -20, -2.0 ** -20, 2.0 ** -30)])) - params = {} - for a, ((h0, h10, h20), _) in enumerate(groups): - params[a, 0] = tuple(f16w(v) | f16w(v) << 16 for v in (h0, h10, h20)) - lanes = [(a, I, J) for a, (_, ij) in enumerate(groups) for I, J in ij][:LANES] - ij = [(f32w(I), f32w(J)) for _, I, J in lanes] - ij += [ij[-1]] * (LANES - len(ij)) - L = lds_prologue(params, ij) - nout = 4 * len(groups) - L.append(f"v_mul_u32_u24_e32 v34, {4 * nout}, v0") - k = 0 - for a in range(len(groups)): - for hi in ("", " high"): - L += [f"v_interp_p1ll_f16 v3, v20, attr{a}.x{hi}", "s_nop 3", "v_mov_b32_e32 v5, 0", - f"v_interp_p2_f16 v5, v21, attr{a}.x, v3{hi}", "s_nop 3", - f"global_store_dword v34, v3, s[2:3] offset:{4 * k}", - f"global_store_dword v34, v5, s[2:3] offset:{4 * k + 4}"] - k += 2 - L += ["s_waitcnt vmcnt(0)", "s_endpgm"] - kern = asm.Kernel(L, wave=32, threads=LANES, words=nout * LANES, raw=True, lds=2048, vgprs=40, sgprs=48, mode=mode) - return kern, (groups, lanes, nout) - - -def check_ties(res, info, tally, bad): - groups, lanes, nout = info - for lane, (a, I, J) in enumerate(lanes): - h20 = groups[a][0][2] - for hix in range(2): - p1 = f32v(res[lane * nout + a * 4 + 2 * hix]) - got = res[lane * nout + a * 4 + 2 * hix + 1] & 0xFFFF - q = F(h20) * F(J) + F(p1) - once, twice = f16w(r16(q)), f16w(r16(F(r32(q)))) - if once == twice: - continue - ok = got == once - tally.setdefault(("tie", "p2_f16 rounds once (not f32, then f16)"), [0, 0])[0 if ok else 1] += 1 - if not ok and len(bad) < 10: - bad.append(f"tie: lane {lane} p1ll {p1!r} J {J!r} got {got:#06x} once {once:#06x} twice {twice:#06x}") - - -def main(argv=None): - ap = argparse.ArgumentParser(description=__doc__.splitlines()[0]) - ap.add_argument("--arch", default="gfx1036", help="hw_oracle target (default gfx1036)") - ap.add_argument("--seeds", default="1,2,3,4", help="comma-separated random seeds (default 1,2,3,4)") - ap.add_argument("--kernels", type=int, default=4, help="random kernels per seed (default 4)") - ap.add_argument("--denorm32", type=int, choices=(0, 3), default=3, - help="MODE f32 denormal field: 3 keeps them (default), 0 flushes (denormal P0/P10/P20 words then read as 0)") - args = ap.parse_args(argv) - try: - seeds = [int(s) for s in args.seeds.split(",")] - except ValueError: - ap.error("--seeds takes integers separated by commas") - mode = {"denorm32": args.denorm32} - try: - o = runner.open_oracle(arch=args.arch) - except runner.Unavailable as e: - print(f"hardware oracle unavailable: {e}", file=sys.stderr) - return 77 - tally, bad = {}, [] - try: - for seed in seeds: - rng = random.Random(seed) - ks = [random_kernel(rng, mode) for _ in range(args.kernels)] - for r, (_, info) in zip(o.run([k for k, _ in ks]), ks): - if isinstance(r, str): - print(f"kernel failed: {r}", file=sys.stderr) - return 2 - check_random(r, info, args.denorm32 == 0, tally, bad) - kern, info = tie_kernel(mode) - r = o.run([kern])[0] - if isinstance(r, str): - print(f"kernel failed: {r}", file=sys.stderr) - return 2 - check_ties(r, info, tally, bad) - finally: - o.close() - print(f"{args.arch}, MODE denorm32 {args.denorm32}, seeds {args.seeds} x {args.kernels} kernels") - for (kind, name), (ok, nbad) in sorted(tally.items()): - print(f" {kind:7s} {name:44s} {ok:6d} match {nbad:5d} differ") - for b in bad: - print(" mismatch:", b) - return 1 if any(n for _, n in tally.values()) else 0 - - -if __name__ == "__main__": - try: # a redirected stdout is strict ANSI code page under -I; write '?' for what it cannot encode - sys.stdout.reconfigure(errors="replace") - except (AttributeError, ValueError, OSError): - pass - sys.exit(main()) diff --git a/tools/isa_coverage.py b/tools/isa_coverage.py deleted file mode 100644 index 61e945eca..000000000 --- a/tools/isa_coverage.py +++ /dev/null @@ -1,461 +0,0 @@ -#!/usr/bin/env python3 -"""RDNA2 ISA coverage of the translator (tools/rdna2spirv.py), measured against AMD's machine-readable ISA XML. - - python -I tools/isa_coverage.py --isa amdgpu_isa_rdna2.xml [--json] [--list] [--llvm-mc llvm-mc] - -Needs no game data and no GPU, only the standard library. The XML is AMD's "machine-readable GPU ISA -specification" (MIT licence, see docs/isa_coverage.md for the download line); it is not vendored. - -What it reports - * every RDNA2 instruction in the XML, grouped by encoding (SOP1 ... EXP, plus the DPP/SDWA modifier forms); - * for each one, what the translator does with it: - handled-exact its name is a string the translator compares the opcode with (a == / in test, or a key of - a mnemonic table such as NOOPS or F2); - handled-family no exact name, but it starts with a prefix the translator tests with op.startswith(...) - (v_cmp_, ds_, buffer_atomic_ ...), or ends with a suffix it tests with op.endswith(...) where - the test has no startswith (s_*_saveexec_b64 ...; a ` in self.TABLE` beside it limits - the family to the stems that table holds); - refused the name sits in a test whose whole body is `raise Unsupported(...)`; - unknown none of the above: the translator reaches its final `raise Unsupported(op)` for it, or - handles it by a rule this static scan cannot see; - * the names the translator matches that are not RDNA2 instructions (typos, GFX9 or GFX11 spellings, names - that base_op() can never produce). This list is the most useful output. - -Method and limits (static, by ast): the translator dispatches with a long if/elif chain on the opcode string, so -the scan collects the string constants that are compared with `op` (== / != / in / not in, also base_op(...)), -the keys and elements of every dict / set / tuple that holds mnemonics, the prefixes given to op.startswith and the -suffixes given to op.endswith. -It cannot see: a branch that accepts an instruction and then rejects some operand forms (reported separately as -`partial`, when the branch body contains a raise Unsupported), names built by string formatting, and whether the -emitted code is right. "handled" means "has a rule", not "is correct". A broad prefix such as ds_ marks every -ds_* instruction handled-family even where a sub-dispatch then refuses it; the exact names found inside the -sub-dispatch still count as handled-exact, so read handled-family as an upper bound. -Usage: `python -I tools/isa_coverage.py --help` lists the options. -""" -import argparse -import ast -import collections -import json -import os -import re -import subprocess -import sys -import xml.etree.ElementTree as ET - -HERE = os.path.dirname(os.path.abspath(__file__)) -DEFAULT_TRANSLATOR = os.path.join(HERE, "rdna2spirv.py") -ENV_XML = "LEONIDA_RDNA2_ISA_XML" - -# What an opcode string looks like: a lower-case mnemonic starting with a known family word. -MNEMONIC = re.compile(r"^((s|v|ds|buffer|tbuffer|global|flat|scratch|image)(_[a-z0-9]+)+|exp)$") -# base_op() in the translator strips these, so a name that ends in one can never match. -STRIPPED_SUFFIXES = ("_e32", "_e64", "_sdwa", "_dpp") -# Names the translator compares the opcode with: `op`, or a call of base_op(). -OP_NAMES = {"op"} - -GROUP_ORDER = ["SOP1", "SOP2", "SOPC", "SOPK", "SOPP", "SMEM", "VOP1", "VOP2", "VOP3", "VOP3P", "VOPC", "DS", - "MUBUF", "MTBUF", "MIMG", "FLAT", "GLOBAL", "SCRATCH", "EXP", "VINTRP", "DPP/SDWA"] -CLASSES = ("handled-exact", "handled-family", "refused", "unknown") - - -def encoding_group(name): - """XML encoding name -> the group of the report, or None for an encoding we do not know.""" - n = name.upper() - if n.startswith("ENC_"): - n = n[4:] - if "_VOP_SDWA" in n or "_VOP_DPP" in n: - return "DPP/SDWA" - if n.endswith("_INST_LITERAL"): - n = n[: -len("_INST_LITERAL")] - if n.startswith("VOP3_SDST_ENC"): - return "VOP3" - if n.startswith("MIMG"): - return "MIMG" - if n == "FLAT_GLBL": - return "GLOBAL" - if n == "FLAT_SCRATCH": - return "SCRATCH" - return n if n in GROUP_ORDER else None - - -def read_isa(path): - """The XML -> (architecture name, schema version, licence, {mnemonic: [encoding groups]}).""" - root = ET.parse(path).getroot() - doc = root.find("Document") - arch = root.findtext("ISA/Architecture/ArchitectureName", "") - version = doc.findtext("SchemaVersion", "") if doc is not None else "" - licence = doc.findtext("License", "") if doc is not None else "" - out = {} - for ins in root.iterfind("ISA/Instructions/Instruction"): - name = (ins.findtext("InstructionName") or "").strip().lower() - if not name: - continue - groups = out.setdefault(name, []) - for enc in ins.iterfind("InstructionEncodings/InstructionEncoding"): - g = encoding_group(enc.findtext("EncodingName", "")) - g = g or "OTHER:" + enc.findtext("EncodingName", "?") - if g not in groups: - groups.append(g) - return {"architecture": arch, "schema": version, "license": licence, "instructions": out} - - -def _strings(node): - return [x.value for x in ast.walk(node) if isinstance(x, ast.Constant) and isinstance(x.value, str)] - - -def _mnemonics(node): - return [s for s in _strings(node) if MNEMONIC.match(s)] - - -def _is_op(node): - if isinstance(node, ast.Name): - return node.id in OP_NAMES - if isinstance(node, ast.Subscript): # ins["op"] - return isinstance(node.slice, ast.Constant) and node.slice.value == "op" - return isinstance(node, ast.Call) and isinstance(node.func, ast.Name) and node.func.id == "base_op" - - -def _only_raises_unsupported(body): - return (len(body) == 1 and isinstance(body[0], ast.Raise) and body[0].exc is not None and - "Unsupported" in ast.unparse(body[0].exc)) - - -def _raises_unsupported(nodes): - return any(isinstance(x, ast.Raise) and x.exc is not None and "Unsupported" in ast.unparse(x.exc) - for n in nodes for x in ast.walk(n)) - - -def _op_compare_names(test, positive_only=False): - """Mnemonics a test compares `op` with (== / in, and unless positive_only != / not in).""" - names = [] - allowed = (ast.Eq, ast.In) if positive_only else (ast.Eq, ast.NotEq, ast.In, ast.NotIn) - work = [test] - while work: - n = work.pop() - if positive_only and isinstance(n, ast.UnaryOp) and isinstance(n.op, ast.Not): - continue - if isinstance(n, ast.Compare) and _is_op(n.left) and all(isinstance(o, allowed) for o in n.ops): - for c in n.comparators: - names.extend(_mnemonics(c)) - work.extend(reversed(list(ast.iter_child_nodes(n)))) - return names - - -def _unconditional_op_names(test): - """Mnemonics `test` matches unconditionally (a positive op == / op in compare, or an `or` of them).""" - if isinstance(test, ast.Compare) and _is_op(test.left) and all(isinstance(o, (ast.Eq, ast.In)) for o in test.ops): - return [m for c in test.comparators for m in _mnemonics(c)] - if isinstance(test, ast.BoolOp) and isinstance(test.op, ast.Or): - parts = [_unconditional_op_names(v) for v in test.values] - return [m for p in parts for m in p] if parts and all(parts) else [] - return [] - - -def _mnemonic_collection(node): - """The mnemonics of a dict (its keys) or of a set / tuple / list that holds at least two of them.""" - if isinstance(node, ast.Dict): - elts = [k for k in node.keys if k is not None] - elif isinstance(node, (ast.Set, ast.Tuple, ast.List)): - elts = node.elts - else: - return [] - hits = [e.value for e in elts if isinstance(e, ast.Constant) and isinstance(e.value, str) and - MNEMONIC.match(e.value)] - return hits if isinstance(node, ast.Dict) or len(hits) >= 2 else [] - - -def scan_translator(path): - """Static scan of the translator source. Returns the sets described in the module docstring.""" - with open(path, encoding="utf-8") as f: - tree = ast.parse(f.read(), path) - exact = collections.defaultdict(set) # name -> {source kind} - prefixes = collections.defaultdict(set) # prefix -> {line} - suffixes = collections.defaultdict(set) - tables = {} - refused, partial = set(), set() - for node in ast.walk(tree): - if isinstance(node, ast.Compare) and _is_op(node.left): - for c in node.comparators: - for m in _mnemonics(c): - exact[m].add("compare") - elif isinstance(node, ast.Assign): # NOOPS = {...}, F2 = {"v_add_f32": ...}, BRANCHES = {...} - keys = (node.value.keys if isinstance(node.value, ast.Dict) else - node.value.elts if isinstance(node.value, (ast.Set, ast.Tuple, ast.List)) else []) - strs = [k.value for k in keys if isinstance(k, ast.Constant) and isinstance(k.value, str)] - if strs: - for t in node.targets: - if isinstance(t, ast.Name): - tables[t.id] = tuple(sorted(strs)) - for m in _mnemonic_collection(node.value): - exact[m].add("table") - elif isinstance(node, ast.Dict): # a table written inline - for m in _mnemonic_collection(node): - exact[m].add("table") - if isinstance(node, ast.If): - uncond = _unconditional_op_names(node.test) - names = _op_compare_names(node.test, positive_only=True) - if uncond and _only_raises_unsupported(node.body): - refused.update(uncond) - elif names and _raises_unsupported(node.body): - partial.update(names) - # Prefix families count only where the instruction dispatch is: Gen._insn and the methods it hands `op` to - # (self.image_op(op, ...), self.lds_op(op, ...)). Other op.startswith calls in the file (read/write analysis, - # memory ordering) say nothing about which instructions are translated. - methods = {fn.name: fn for fn in ast.walk(tree) if isinstance(fn, ast.FunctionDef)} - scope = {"_insn"} - if "_insn" in methods: - for c in ast.walk(methods["_insn"]): - if (isinstance(c, ast.Call) and isinstance(c.func, ast.Attribute) - and isinstance(c.func.value, ast.Name) and c.func.value.id == "self" - and any(isinstance(x, ast.Name) and x.id == "op" for x in c.args[:1])): - scope.add(c.func.attr) - for name in scope & set(methods): - for node in ast.walk(methods[name]): - if (isinstance(node, ast.Call) and isinstance(node.func, ast.Attribute) - and node.func.attr == "startswith" and _is_op(node.func.value)): - for p in _strings(node): - if re.match(r"^[a-z0-9_]+$", p): - prefixes[p].add(node.lineno) - for node in _chain_ifs(methods[name].body): - if _only_raises_unsupported(node.body): - continue - for suffix, stems in _suffix_tests(node.test, tables): - suffixes[(suffix, stems)].add(node.lineno) - return {"exact": {k: sorted(v) for k, v in exact.items()}, "prefixes": {k: sorted(v) for k, v in prefixes.items()}, - "suffixes": {k: sorted(v) for k, v in suffixes.items()}, - "refused": sorted(refused), "partial": sorted(partial)} - - -def _op_call(node, attr): - return (isinstance(node, ast.Call) and isinstance(node.func, ast.Attribute) and node.func.attr == attr - and _is_op(node.func.value)) - - -def _chain_ifs(body): - out = [] - for st in body: - while isinstance(st, ast.If): - out.append(st) - st = st.orelse[0] if len(st.orelse) == 1 and isinstance(st.orelse[0], ast.If) else None - return out - - -def _suffix_tests(test, tables): - parts = test.values if isinstance(test, ast.BoolOp) and isinstance(test.op, ast.And) else [test] - stems = None - for x in parts: - if _op_call(x, "endswith"): - continue - t = x.comparators[0] if isinstance(x, ast.Compare) and len(x.ops) == 1 and isinstance(x.ops[0], ast.In) else None - key = t.attr if isinstance(t, ast.Attribute) else t.id if isinstance(t, ast.Name) else None - if key not in tables or stems is not None: - return [] - stems = tables[key] - return [(s, stems) for x in parts if _op_call(x, "endswith") for s in _strings(x) - if re.match(r"^_[a-z0-9_]+$", s)] - - -def in_suffix_family(name, suffixes): - for suffix, stems in suffixes: - if name.endswith(suffix): - stem = name[: -len(suffix)] - if stems is None or any(stem.endswith("_" + k) for k in stems): - return True - return False - - -def classify(name, scan, handled_elsewhere): - """One of CLASSES. A name refused by a test and also handled by another test is handled.""" - if name in scan["exact"] and (name not in scan["refused"] or name in handled_elsewhere): - return "handled-exact" - if name in scan["refused"]: - return "refused" - if any(name.startswith(p) for p in scan["prefixes"]) or in_suffix_family(name, scan.get("suffixes", ())): - return "handled-family" - return "unknown" - - -def accepted_names(path): - """Names compared or tabled anywhere except inside a test whose body only raises Unsupported.""" - with open(path, encoding="utf-8") as f: - tree = ast.parse(f.read(), path) - skip = set() - for node in ast.walk(tree): - if isinstance(node, ast.If) and _unconditional_op_names(node.test) and _only_raises_unsupported(node.body): - skip.update(id(x) for x in ast.walk(node.test) if isinstance(x, ast.expr)) - names = set() - for node in ast.walk(tree): - if id(node) in skip: - continue - if isinstance(node, ast.Compare) and _is_op(node.left): - for c in node.comparators: - names.update(m for m in _mnemonics(c) if not _in_skipped(c, skip)) - elif isinstance(node, (ast.Assign, ast.Dict)): - names.update(_mnemonic_collection(node.value if isinstance(node, ast.Assign) else node)) - return names - - -def _in_skipped(node, skip): - return any(id(x) in skip for x in ast.walk(node) if isinstance(x, ast.expr)) - - -PROBE_TIMEOUT = 30 # seconds llvm-mc gets for one mnemonic - - -def probe_llvm_mc(llvm_mc, names, mcpu="gfx1013"): - """Ask llvm-mc about each mnemonic without operands and distinguish tool failures from opcode diagnostics.""" - out = {} - for n in names: - try: - r = subprocess.run([llvm_mc, "-arch=amdgcn", f"-mcpu={mcpu}"], input=n + "\n", capture_output=True, - text=True, timeout=PROBE_TIMEOUT) - except OSError as e: - return {"error": str(e)} - except subprocess.TimeoutExpired: - # A stalled llvm-mc would stall every remaining name for as long again: give up with one message. - return {"error": f"llvm-mc did not answer within {PROBE_TIMEOUT} s for {n!r}"} - text = r.stderr + "\n" + r.stdout - if "error: invalid instruction" in text: - out[n] = "unknown to LLVM" - elif "error: instruction not supported on this GPU" in text: - out[n] = f"LLVM: other GPU only (not {mcpu})" - elif r.returncode == 0 or "error: too few operands for instruction" in text: - out[n] = f"LLVM: valid on {mcpu}" - else: - diagnostic = next((line.strip() for line in text.splitlines() if line.strip()), "no diagnostic") - out[n] = f"LLVM probe failed (exit {r.returncode}): {diagnostic}" - return out - - -def build_report(isa, scan, accepted): - instrs = isa["instructions"] - scan = dict(scan) - scan["refused"] = sorted(set(scan["refused"]) - accepted) # refused and nowhere accepted - scan["exact"] = {k: v for k, v in scan["exact"].items() if k not in scan["refused"] or k in accepted} - cls = {n: classify(n, scan, accepted) for n in instrs} - groups = {g: collections.Counter() for g in GROUP_ORDER} - unknown_by_group = collections.defaultdict(list) - for n, encs in instrs.items(): - for g in encs: - groups.setdefault(g, collections.Counter())[cls[n]] += 1 - if cls[n] == "unknown": - unknown_by_group[g].append(n) - total = collections.Counter(cls.values()) - names_in_xml = set(instrs) - # Names the translator matches that are not RDNA2 instructions. - extra = sorted(n for n in set(scan["exact"]) | set(scan["refused"]) if n not in names_in_xml) - dead = [n for n in extra if n.endswith(STRIPPED_SUFFIXES)] - dead_stem = {n: next(n[: -len(s)] for s in STRIPPED_SUFFIXES if n.endswith(s)) for n in dead} - empty_prefixes = sorted(p for p in scan["prefixes"] if not any(n.startswith(p) for n in names_in_xml)) - partial = sorted(n for n in scan["partial"] if n in names_in_xml) - return { - "architecture": isa["architecture"], "schema": isa["schema"], "license": isa["license"], - "instructions": len(instrs), "totals": {c: total.get(c, 0) for c in CLASSES}, - "groups": {g: {c: groups[g].get(c, 0) for c in CLASSES} | {"total": sum(groups[g].values())} - for g in groups if sum(groups[g].values())}, - "class": cls, "unknown_by_group": {g: sorted(v) for g, v in unknown_by_group.items()}, - "refused": sorted(n for n in instrs if cls[n] == "refused"), - "partial": partial, - "not_in_rdna2": [{"name": n, "kind": sorted(scan["exact"].get(n, ["refused"])), - "never_matches_after_base_op": n in dead_stem, - **({"stem": dead_stem[n], "stem_in_rdna2": dead_stem[n] in names_in_xml} - if n in dead_stem else {})} for n in extra], - "prefixes": {p: sum(1 for n in names_in_xml if n.startswith(p)) for p in sorted(scan["prefixes"])}, - "prefixes_without_rdna2_match": empty_prefixes, - "suffixes": {s: sum(1 for n in names_in_xml if in_suffix_family(n, [(s, st)])) - for s, st in sorted(scan.get("suffixes", ()), key=lambda k: (k[0], k[1] or ()))}, - } - - -def markdown(rep, list_unknown=False): - t = rep["totals"] - n = rep["instructions"] - lines = [f"# RDNA2 ISA coverage of tools/rdna2spirv.py", "", - f"Spec: {rep['architecture']}, schema {rep['schema']}, licence {rep['license']}. {n} instructions.", "", - "| class | instructions | share |", "|---|---:|---:|"] - for c in CLASSES: - lines.append(f"| {c} | {t[c]} | {100 * t[c] / n:.1f}% |") - lines += ["", "An instruction with several encodings is counted once in the table above and once per group " - "below, so the group rows add up to more than the total.", "", - "| encoding | total | handled-exact | handled-family | refused | unknown |", - "|---|---:|---:|---:|---:|---:|"] - for g in sorted(rep["groups"], key=lambda g: GROUP_ORDER.index(g) if g in GROUP_ORDER else 99): - r = rep["groups"][g] - lines.append(f"| {g} | {r['total']} | {r['handled-exact']} | {r['handled-family']} | {r['refused']} | " - f"{r['unknown']} |") - lines += ["", f"## Matched by the translator but not an RDNA2 instruction ({len(rep['not_in_rdna2'])})", ""] - if rep["not_in_rdna2"]: - for e in rep["not_in_rdna2"]: - note = "" - if e["never_matches_after_base_op"]: - note = f" (ends in a suffix base_op() strips, so it never matches; `{e['stem']}` " + \ - ("is RDNA2)" if e["stem_in_rdna2"] else "is not RDNA2 either)") - if e.get("llvm"): - note += f" [{e['llvm']}]" - lines.append(f"- `{e['name']}` ({'/'.join(e['kind'])}){note}") - else: - lines.append("None.") - lines += ["", "Prefix families the dispatch tests with op.startswith (RDNA2 instructions each one matches): " + - ", ".join(f"`{p}` {c}" for p, c in rep["prefixes"].items())] - if rep["suffixes"]: - lines += ["", "Suffix families the dispatch tests with op.endswith (RDNA2 instructions each one matches): " + - ", ".join(f"`{s}` {c}" for s, c in rep["suffixes"].items())] - if rep["prefixes_without_rdna2_match"]: - lines += ["", "Prefixes (op.startswith) that match no RDNA2 instruction: " + - ", ".join(f"`{p}`" for p in rep["prefixes_without_rdna2_match"])] - lines += ["", f"## Refused ({len(rep['refused'])})", "", - ", ".join(f"`{x}`" for x in rep["refused"]) or "None.", - "", f"## Handled but with operand forms that raise Unsupported ({len(rep['partial'])})", "", - ", ".join(f"`{x}`" for x in rep["partial"]) or "None."] - if list_unknown: - lines += ["", "## Unknown, by encoding", ""] - for g in sorted(rep["unknown_by_group"], key=lambda g: GROUP_ORDER.index(g) if g in GROUP_ORDER else 99): - lines += [f"### {g} ({len(rep['unknown_by_group'][g])})", "", - ", ".join(f"`{x}`" for x in rep["unknown_by_group"][g]), ""] - return "\n".join(lines) + "\n" - - -def main(argv=None): - ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) - ap.add_argument("--isa", default=os.environ.get(ENV_XML), help=f"amdgpu_isa_rdna2.xml (default: ${ENV_XML})") - ap.add_argument("--translator", default=DEFAULT_TRANSLATOR) - ap.add_argument("--json", action="store_true", help="machine-readable output") - ap.add_argument("--list", action="store_true", help="also list the unknown instructions per encoding") - ap.add_argument("--llvm-mc", metavar="EXE", help="classify the non-RDNA2 names with llvm-mc (-mcpu=gfx1013)") - a = ap.parse_args(argv) - if not a.isa: - ap.error(f"--isa is required (or set {ENV_XML})") - try: - isa = read_isa(a.isa) - except OSError as e: - ap.error(f"--isa {a.isa}: {e.strerror or e}") - except ET.ParseError as e: - ap.error(f"--isa {a.isa}: invalid XML ({e})") - if not isa["instructions"]: - ap.error(f"--isa {a.isa}: no instructions (not the AMD ISA XML spec?)") - if "RDNA 2" not in isa["architecture"]: - print(f"warning: {a.isa} describes {isa['architecture']!r}, not AMD RDNA 2", file=sys.stderr) - try: - scan, accepted = scan_translator(a.translator), accepted_names(a.translator) - except OSError as e: - ap.error(f"--translator {a.translator}: {e.strerror or e}") - except UnicodeDecodeError as e: - ap.error(f"--translator {a.translator}: not valid UTF-8 ({e.reason} at byte {e.start})") - rep = build_report(isa, scan, accepted) - if a.llvm_mc: - probe = probe_llvm_mc(a.llvm_mc, [e["name"] for e in rep["not_in_rdna2"]]) - for e in rep["not_in_rdna2"]: - e["llvm"] = probe.get(e["name"]) if "error" not in probe else probe["error"] - if a.json: - print(json.dumps(rep, indent=1, sort_keys=True)) - else: - sys.stdout.write(markdown(rep, a.list)) - return 0 - - -if __name__ == "__main__": - try: # a redirected stdout is strict ANSI code page under -I; write '?' for what it cannot encode - sys.stdout.reconfigure(errors="replace") - except (AttributeError, ValueError, OSError): - pass - sys.exit(main()) diff --git a/tools/lane_masks.py b/tools/lane_masks.py deleted file mode 100644 index db1fc8047..000000000 --- a/tools/lane_masks.py +++ /dev/null @@ -1,309 +0,0 @@ -"""Which scalar registers hold a lane mask? - -On hardware a lane mask is one register for the whole wave, a bit per lane. The translator runs one invocation -per lane and keeps only that lane's bit in the register (all ones or zero), which is all that and/or/not, selects -and EXEC need. A few instructions look at the mask as a whole instead: s_bcnt1 (how many lanes), s_ff1 (the first -lane), v_mbcnt (how many lanes below this one). For those the translator has to collect the other lanes' bits. -The same instructions also run on plain 64-bit data, such as a light mask read from a buffer, and nothing in the -instruction says which of the two it has, so this module works it out from what wrote the register. - - masks, writes = analyse(blocks, succ) # blocks: lists of instructions; succ: successor block numbers per block - masks[id(ins)] # dict mapping each register holding a lane mask on every path to ins - # (SGPR number, "vcc", ("lane", vgpr, lane) parked in a VGPR lane, or - # ("v", vgpr) passing through a VGPR) to its kind (MASK, MASK_LO, MASK_HI) - id(ins) in writes # ins computes a mask into a VGPR (a plain copy does not count) - -A register counts as a mask only if every path to the instruction wrote a mask to it. Anything else is treated -as data, which is what the translator did for all of them before. - -Parked masks: a shader that runs out of SGPRs moves some into single lanes of a spare VGPR (v_writelane_b32) and -fetches them back later (v_readlane_b32). When the SGPR is a saved EXEC, the value that comes back has to be this -lane's bit again, not the bit of the lane it was parked in. - -Masks through a VGPR: the compiler does some scalar work in the vector unit, such as an OR of three SGPRs -(v_mov_b32 / v_or3_b32, then v_readfirstlane_b32 to get the scalar back). On hardware every lane computes the same -whole mask and the first lane's copy is read. Here each lane computes its own bit, so it has to read its own -copy, and it has to compute it whether or not it is active. A plain copy of a mask (v_mov_b32) is different: -it moves an already-computed value, so it is an ordinary VALU write and inactive lanes keep the old VGPR -(SHADER-21 part 2). -""" - -MASK = "mask" # full lane mask (64-bit pair, vcc, or wave32 single register) -MASK_LO = "mask_lo" # low 32-bit half of a 64-bit lane mask (lanes 0-31) -MASK_HI = "mask_hi" # high 32-bit half of a 64-bit lane mask (lanes 32-63) -MASK_KINDS = (MASK, MASK_LO, MASK_HI) -EITHER = "either" # a constant 0 or -1: no lanes or all lanes, and the same bits when read as data -# Absent from the state: data. - -COPIES = ("s_mov_b", "s_not_b", "s_wqm_b") -BITWISE = ("s_and_b", "s_or_b", "s_xor_b", "s_andn2_b", "s_orn2_b", "s_nand_b", "s_nor_b", "s_xnor_b", - "s_cselect_b") -NO_DESTINATION = ( # their first operand (if any) is a source, not a written register - "s_cmp", "s_bitcmp", "v_cmpx", "s_set", "s_rfe", - "s_store_", "s_buffer_store_", "s_dcache_", "s_icache_", - "s_sendmsg", "s_branch", "s_cbranch", "s_waitcnt", "s_nop", "s_sleep", "s_barrier", "s_endpgm", - "exp", - "buffer_store", "tbuffer_store", "global_store", "flat_store", "image_store", "ds_write", -) -DS_HAS_DST = ("ds_read", "ds_swizzle", "ds_permute", "ds_bpermute", - "ds_append", "ds_consume", "ds_ordered_count", "ds_nop") -VGPR_REL_DST = ("v_movreld_b32", "v_movrelsd_b32", "v_movrelsd_2_b32", "v_swaprel_b32") -SGPR_REL_DST = ("s_movreld_b32", "s_movreld_b64", "s_movrelsd_2_b32") -VECTOR_BITWISE = ("v_mov_b32", "v_or3_b32", "v_or_b32", "v_and_b32", "v_and_or_b32", - "v_xor_b32", "v_xor3_b32", "v_xnor_b32", "v_bfi_b32", "v_not_b32") - - -def base_op(op): - for suffix in ("_e32", "_e64", "_sdwa", "_dpp"): - if op.endswith(suffix): - return op[:-len(suffix)] - return op - - -def kind(state, a, wave64=True): - if a["k"] == "special": - t = a.get("t", "") - if t in ("exec_lo", "exec_hi", "exec"): - if not wave64: - return MASK - return MASK_LO if t == "exec_lo" else (MASK_HI if t == "exec_hi" else MASK) - if t == "vcc" or (not wave64 and t == "vcc_lo"): - return state.get("vcc") - if not wave64 and t == "vcc_hi": - return state.get("vcc_hi") - if t in ("vcc_lo", "vcc_hi"): - vk = state.get("vcc") - if vk in MASK_KINDS: - return MASK_LO if t == "vcc_lo" else MASK_HI - return vk if t == "vcc_lo" else None - return None - if a["k"] == "sgpr": - n = a.get("n", 1) - ks = [state.get(a["r"] + i) for i in range(n)] - if None in ks: - return None - if n == 2 and any(k in MASK_KINDS for k in ks): - return MASK - return ks[0] if len(set(ks)) == 1 else None - if a["k"] == "vgpr" and a.get("n", 1) == 1: - return state.get(("v", a["r"])) - if a["k"] == "imm" and a["v"] in (0, -1): - return EITHER - return None - - -def put(state, a, k, wave64=True): - if a["k"] == "sgpr": - n = a.get("n", 1) - if k == MASK and n == 2: - state[a["r"]] = MASK_LO - state[a["r"] + 1] = MASK_HI - return - regs = [a["r"] + i for i in range(n)] - elif a["k"] == "slist": - regs = [ - r if isinstance(r, int) else ("vcc_hi" if (r == "vcc_hi" and not wave64) else "vcc") - for r in a["r"] - ] - elif a["k"] == "special" and (a.get("t") == "vcc" or (not wave64 and a.get("t") == "vcc_lo")): - regs = ["vcc"] - elif a["k"] == "special" and not wave64 and a.get("t") == "vcc_hi": - regs = ["vcc_hi"] - elif a["k"] == "special" and a.get("t") in ("vcc_lo", "vcc_hi"): - # A mask / 0 / -1 half-write updates that half of %vcc in wave64 (put_mask), keeping VCC a lane mask; - # a plain-data half-write (k is None) ends VCC's life as one lane mask. - if k is not None and state.get("vcc") in MASK_KINDS: - state["vcc"] = MASK - elif a.get("t") == "vcc_lo" and k is not None: - state["vcc"] = k - else: - state.pop("vcc", None) - return - else: - return - for r in regs: - if k is None: - state.pop(r, None) - else: - state[r] = k - - -def _maskable_b32(x): - return x["k"] in ("sgpr", "imm") or ( - x["k"] == "special" and (x.get("t", "").startswith(("exec", "vcc")) or x.get("t") == "null") - ) - - -def lane_slot(vgpr, lane): - """State key for a mask parked in one lane of a VGPR, or None unless both operands are plain.""" - if vgpr["k"] != "vgpr" or lane["k"] != "imm": - return None - return ("lane", vgpr["r"], lane["v"] & 63) - - -def step(state, ins, wave64=True): - """Update `state` (register -> MASK | MASK_LO | MASK_HI | EITHER) for one instruction. True if it writes a mask to a VGPR. - - `wave64` False: the program runs in 32-lane waves, where a 64-bit s_bfm_b64 result can't be a lane mask.""" - op, a = base_op(ins["op"]), ins["args"] - if not a or op.startswith(NO_DESTINATION): - return - mods = ins.get("mods", ()) - if op.startswith(("buffer_load", "tbuffer_load")) and "lds" in mods: - return - if op.startswith(("buffer_atomic", "global_atomic", "flat_atomic", "image_atomic", - "s_atomic", "s_buffer_atomic")) and "glc" not in mods: - return - if op.startswith("ds_") and not op.startswith(DS_HAS_DST) and "_rtn" not in op: - return - if op == "v_readfirstlane_b32" and len(a) == 2: # sD = vS, the same in every lane - put(state, a[0], kind(state, a[1], wave64), wave64) - return - if op == "v_writelane_b32" and len(a) == 3 and lane_slot(a[0], a[2]): # vD[lane] = sS - state.pop(("v", a[0]["r"]), None) - k = kind(state, a[1], wave64) - if k is None: - state.pop(lane_slot(a[0], a[2]), None) - else: - state[lane_slot(a[0], a[2])] = k - return - if op == "v_readlane_b32" and len(a) == 3: # sD = vS[lane] - put(state, a[0], state.get(lane_slot(a[1], a[2])), wave64) - return - if op.startswith("v_cmp"): - # Handle v_cmp before VGPR clobber (defensive for 2-operand forms with implicit vcc). - put(state, {"k": "special", "t": "vcc"} if len(a) == 2 else a[0], MASK, wave64) - return - if op == "v_swap_b32": - written = set() - for x in a[:2]: - if x["k"] == "vgpr": - written.update(range(x["r"], x["r"] + x.get("n", 1))) - for key in [k for k in state if isinstance(k, tuple) and k[1] in written]: - del state[key] - return - if op in VGPR_REL_DST: - bases = [x["r"] for x in (a[:2] if op == "v_swaprel_b32" else a[:1]) if x["k"] == "vgpr"] - if bases: - lo = min(bases) - for key in [k for k in state if isinstance(k, tuple) and k[1] >= lo]: - del state[key] - return - if op in SGPR_REL_DST: - if a[0]["k"] == "sgpr": - lo = a[0]["r"] - for key in [k for k in state if isinstance(k, int) and k >= lo]: - del state[key] - return - if a[0]["k"] == "vgpr": # any other write to a VGPR ends what was parked in it - # A mask only when every source is one (or a constant 0 / -1) on every path: no EITHER for VGPRs, whose - # plain writes skip inactive lanes. The sources are looked at first: the destination can be one of them. - # SDWA/DPP or modified forms alter sub-dwords or read other lanes, so they are never plain mask ops. - plain_valu = (op in VECTOR_BITWISE and a[0].get("n", 1) == 1 - and not ins["op"].endswith(("_sdwa", "_dpp", "_dpp8")) - and not mods - and not any(x.get("neg") or x.get("abs") or x.get("sext") for x in a[1:])) - kinds = [kind(state, x, wave64) for x in a[1:]] if plain_valu else [None] - written = range(a[0]["r"], a[0]["r"] + a[0].get("n", 1)) - for key in [k for k in state if isinstance(k, tuple) and k[1] in written]: - del state[key] - if None not in kinds and any(k in MASK_KINDS for k in kinds): - ms = {k for k in kinds if k in MASK_KINDS} - state[("v", a[0]["r"])] = ms.pop() if len(ms) == 1 else MASK - # A plain copy (v_mov_b32) is an ordinary VALU write: inactive lanes keep the old - # VGPR (SHADER-21 part 2). Only per-lane mask computations take the all-lanes store, - # because whole-wave readers (wave_mask, v_readfirstlane) read every lane's bit. - return op != "v_mov_b32" - if "_saveexec_b" in op or "_wrexec_b" in op: - put(state, a[0], MASK_LO if (wave64 and op.endswith("_b32")) else MASK, wave64) - elif op == "s_bfm_b64": - # In wave32 code it is 64-bit data, e.g. the first two words of an S# built in place (the pipeline library's - # wave32 compute programs: s_bfm_b64 s[88:89], 2, 54); rdna2spirv computes the value there. - put(state, a[0], MASK if wave64 else None, wave64) - elif op.startswith(COPIES) and len(a) > 1: - k = kind(state, a[1], wave64) - dst_t = a[0].get("t") if a[0]["k"] == "special" else None - if k in (None, EITHER) and op.endswith("b64") and dst_t in ("vcc", "vcc_lo") and a[1]["k"] == "imm": - k = MASK - elif op == "s_not_b32" and dst_t in ("vcc", "vcc_lo") and _maskable_b32(a[1]): - k = MASK - elif op == "s_not_b32" and dst_t == "vcc_hi" and wave64 and state.get("vcc") in MASK_KINDS and _maskable_b32(a[1]): - return - put(state, a[0], k, wave64) - elif op.startswith(BITWISE): - kinds = [kind(state, x, wave64) for x in a[1:]] - ms = {k for k in kinds if k in MASK_KINDS} - dst_t = a[0].get("t") if a[0]["k"] == "special" else None - if None not in kinds: - if op.endswith("b32") and dst_t == "vcc_hi" and wave64 and state.get("vcc") in MASK_KINDS: - return - fallback = MASK if op.endswith("b64") and dst_t in ("vcc", "vcc_lo") else EITHER - put(state, a[0], (ms.pop() if len(ms) == 1 else MASK) if ms else fallback, wave64) - elif op.endswith("b64") and (ms or dst_t in ("vcc", "vcc_lo")) and \ - all(k is not None or x["k"] == "imm" for k, x in zip(kinds, a[1:])): - put(state, a[0], (ms.pop() if len(ms) == 1 else MASK) if ms else MASK, wave64) - elif op.endswith("b32") and dst_t in ("vcc", "vcc_lo") and all(_maskable_b32(x) for x in a[1:]): - put(state, a[0], MASK, wave64) - elif op.endswith("b32") and dst_t == "vcc_hi" and wave64 and state.get("vcc") in MASK_KINDS and \ - all(_maskable_b32(x) for x in a[1:]): - return - else: - put(state, a[0], None, wave64) - else: - put(state, a[0], None, wave64) - if ((op.startswith("v_") and "_co_" in op) - or op in ("v_mad_u64_u32", "v_mad_i64_i32", "v_div_scale_f32", "v_div_scale_f64")) and len(a) > 1: - put(state, a[1], MASK, wave64) # carry/sign/scale lane mask of VOP3b ops - - -def parked(blocks, masks): - """The (vgpr, lane) slots some v_readlane_b32 fetches a mask from, given analyse()'s result.""" - found = set() - for blk in blocks: - for ins in blk: - a = ins["args"] - if base_op(ins["op"]) == "v_readlane_b32" and len(a) == 3: - slot = lane_slot(a[1], a[2]) - if slot in masks.get(id(ins), ()): - found.add(slot[1:]) - return sorted(found) - - -def analyse(blocks, succ, *, include_either=False, wave64=True): - entry = [None] * len(blocks) # None: not reached yet - if blocks: - entry[0] = {} - work = [0] if blocks else [] - while work: - n = work.pop() - state = dict(entry[n]) - for ins in blocks[n]: - step(state, ins, wave64) - for s in succ[n]: - if entry[s] is None: - merged = dict(state) - else: # a mask on both paths, or a mask on one and 0 / -1 on the other - merged = {} - for r in entry[s].keys() & state.keys(): - a_k, b_k = entry[s][r], state[r] - if a_k == b_k: - merged[r] = a_k - elif a_k == EITHER: - merged[r] = b_k - elif b_k == EITHER: - merged[r] = a_k - else: - merged[r] = MASK - if merged != entry[s]: - entry[s] = merged - work.append(s) - out, writes, either = {}, set(), {} - for n, blk in enumerate(blocks): - state = dict(entry[n] or {}) - for ins in blk: - out[id(ins)] = {r: k for r, k in state.items() if k in MASK_KINDS} - if include_either: - either[id(ins)] = {r for r, k in state.items() if k == EITHER} - if step(state, ins, wave64): - writes.add(id(ins)) - return (out, writes, either) if include_either else (out, writes) diff --git a/tools/lds_fuzz.py b/tools/lds_fuzz.py deleted file mode 100644 index 780156053..000000000 --- a/tools/lds_fuzz.py +++ /dev/null @@ -1,1276 +0,0 @@ -r"""Differential fuzzer for the translator's LDS and ds_* instructions (FUZZ-6), standard library only. - -Generates seeded random compute programs (one 64-thread group, wave64 or wave32, 4 KiB LDS) that run a sequence -of ds_* instructions and compares every thread's result registers and the final LDS contents, bit for bit, with an -independent model of the RDNA2 instructions written here (it does not import the translator). Two oracles: - - translator (default) translate with rdna2spirv.py and run on the GPU with vk_compute_test - hw run the program natively on an AMD GPU (tools/hw_oracle/); tests the MODEL, wave32 and wave64 - - python -I tools/lds_fuzz.py --programs 200 --seed 1 [--wave 64|32|both] [--emulate] [--build runtime/build] - python -I tools/lds_fuzz.py --oracle hw --programs 2000 --seed 1 # the model against the AMD GPU; 77 if - # the hardware oracle's tools are missing - python -I tools/lds_fuzz.py --oracle translator,hw ... # both, and what the translator did - python -I tools/lds_fuzz.py --show 1:7 # print program 7 of seed 1 and the model's result - python -I tools/lds_fuzz.py --model-only ... # generate and run the model only (no GPU) - -Programs are deterministic: every op either touches addresses no other lane touches in the same op, or is an -order-independent atomic without return (add/sub/min/max/and/or/xor). ds_swizzle runs with all -lanes active (the ISA behaviour of a source lane that is off in EXEC isn't covered here, see --swizzle-exec); -ds_bpermute also runs under random EXEC masks (an inactive source lane reads 0). Swizzle offsets are -limited to the two patterns the LLVM swizzle() macros encode: bit 15 set = quad permute (4 x 2-bit selectors in -bits 7:0), clear = bit mask (and = bits 4:0, or = bits 9:5, xor = bits 14:10, within each 32-lane group). - -Options that widen the op mix (each changes the programs a seed generates, and their names; without them a seed -gives the same programs as before): --permute adds ds_permute_b32, --swizzle-exec runs ds_swizzle under EXEC masks, ---threads N or mix sets the group size (32, 64, 128, 256; a partial wave or several waves, joined by s_barrier), ---extended is all three. ds_permute_b32 and ds_swizzle under EXEC carry a hypothesis (the model's reading of the ISA -text, which nothing measured before the hardware oracle): a mismatch there is a falsified claim on the hardware and -a "hypothesis" line apart from the others on the translator. - -Each mismatch is printed with the words that differ and the op that last wrote them, and a --show line that -prints the program. Exit code: 0 when every program that ran matches, 1 on a mismatch, 2 on a harness error -(assembler, translator or vk_compute_test failure) or when no program could run (every one skipped), 77 when ---oracle hw was asked for and the hardware oracle's tools or GPU are missing. - -A wave32 program is skipped where vk_compute_test can't pin 32-lane subgroups ("compute subgroup size: 32 not -available", e.g. Mesa llvmpipe, whose subgroups are 8 wide): its words would come from another wave size. Wave64 -programs translated with --emulate use no subgroup operations, so they are compared at any subgroup size. -Usage: `python -I tools/lds_fuzz.py --help` lists the options. -""" -import argparse -import copy -import json -import os -import random -import re -import struct -import subprocess -import sys -import shutil -import tempfile -from pathlib import Path - -HERE = os.path.dirname(os.path.abspath(__file__)) -ROOT = os.path.dirname(HERE) -sys.path.insert(0, HERE) -sys.path.insert(0, os.path.join(ROOT, "runtime", "test", "shaders")) -import mc_command # noqa: E402 -from compute_fixture import compute_header, find_test_program, unpinned_subgroup # noqa: E402 - -THREADS = 64 # the default group size -GROUP_SIZES = (32, 64, 128, 256) # --threads mix -LDS_BYTES = 4096 -LDS_DWORDS = LDS_BYTES // 4 -POOL = list(range(20, 36)) # result / data registers stored at the end -ADDR = 6 # per-op address register -TMP = 7 -RSRC2 = 0x8088 & ~(0x1FF << 15) | ((LDS_BYTES // 512) << 15) -OUT_WORDS = THREADS * len(POOL) + LDS_DWORDS -M32 = 0xFFFFFFFF -HW_VGPRS = 40 # the programs use v0..v35 -EXEC_SAVE = 10 # s10 (s[10:11] in wave64) holds the entry EXEC in the native kernels - -READS = { # name: (bytes, kind) - "ds_read_b32": (4, "b32"), "ds_read_b64": (8, "wide"), "ds_read_b96": (12, "wide"), - "ds_read_b128": (16, "wide"), - "ds_read_u8": (1, "u"), "ds_read_i8": (1, "i"), "ds_read_u16": (2, "u"), "ds_read_i16": (2, "i"), - "ds_read_u16_d16": (2, "u_lo"), "ds_read_u16_d16_hi": (2, "u_hi"), - "ds_read_u8_d16": (1, "u_lo"), "ds_read_u8_d16_hi": (1, "u_hi"), - "ds_read_i8_d16": (1, "i_lo"), "ds_read_i8_d16_hi": (1, "i_hi"), -} -WRITES = { # name: (bytes, data bit offset) - "ds_write_b32": (4, 0), "ds_write_b64": (8, 0), "ds_write_b96": (12, 0), "ds_write_b128": (16, 0), - "ds_write_b8": (1, 0), "ds_write_b16": (2, 0), "ds_write_b8_d16_hi": (1, 16), "ds_write_b16_d16_hi": (2, 16), -} -SHARED_ATOMICS = ("add", "sub", "min_i32", "max_i32", "min_u32", "max_u32", "and", "or", "xor") -RTN_ATOMICS = SHARED_ATOMICS -EXEC_KINDS = ("atomic", "atomic_rtn", "bpermute", "cmpst", "permute", "read", "read2", "swizzle", "write", - "write2", "wrxchg", "wrxchg2") -ATOMIC_NAME = {"add": "ds_add%s_u32", "sub": "ds_sub%s_u32", "min_i32": "ds_min%s_i32", "max_i32": "ds_max%s_i32", - "min_u32": "ds_min%s_u32", "max_u32": "ds_max%s_u32", "and": "ds_and%s_b32", "or": "ds_or%s_b32", - "xor": "ds_xor%s_b32"} - -# What the model gets wrong on purpose (--perturb, --negative-control): each name switches one deliberate error -# into model_op / atomic / swizzle_src, to prove the comparison can fail. name: (op family it changes, description) -PERTURBATIONS = { - "max_i32_unsigned": ("max_i32", "ds_max_i32 compares as unsigned"), - "min_u32_signed": ("min_u32", "ds_min_u32 compares as signed"), - "cmpst_swap": ("cmpst", "ds_cmpst stores data0 and compares with data1 (operands swapped)"), - "i8_zero_extend": ("read_i8", "ds_read_i8 zero-extends"), - "i16_zero_extend": ("read_i16", "ds_read_i16 zero-extends"), - "d16_hi_zeroes_low": ("read_d16_hi", "the d16_hi reads clear the low half instead of keeping it"), - "u8_d16_clobbers_hi": ("read_d16_lo", "the d16 (low half) reads clear the high half instead of keeping it"), - "b16_hi_shift_0": ("write_d16_hi", "ds_write_b16_d16_hi stores the low half"), - "write2_swapped": ("write2", "ds_write2 stores its data registers swapped"), - "st64_unit_4": ("read2", "the st64 forms scale their offsets by 4, not 256"), - "wrxchg2_swapped": ("wrxchg2", "ds_wrxchg2 stores data1 in its first element"), - "bpermute_inactive_reads": ("bpermute", "ds_bpermute reads an inactive source lane's register, not 0"), - "bpermute_wave64_cross": ("bpermute", "a wave64 ds_bpermute reaches all 64 lanes"), - "permute_wave64_cross": ("permute", "a wave64 ds_permute reaches all 64 lanes"), - "swizzle_quad_reversed": ("swizzle", "the quad-permute selectors are taken in reverse lane order"), - "swizzle_or_xor_swapped": ("swizzle", "the bit-mask or and xor fields are swapped"), - "permute_no_zero": ("permute", "ds_permute_b32 leaves an unwritten lane's register alone instead of writing 0"), - "permute_lowest_wins": ("permute", "ds_permute_b32 lets the lowest active source lane win a collision"), -} -PERTURB = set() - - -class perturbed: - """Context manager: the model with the named deliberate errors switched on.""" - - def __init__(self, *names): - self.names = set(names) - unknown = self.names - set(PERTURBATIONS) - if unknown: - raise ValueError(f"unknown perturbation {sorted(unknown)}") - - def __enter__(self): - self.old = set(PERTURB) - PERTURB.update(self.names) - return self - - def __exit__(self, *exc): - PERTURB.clear() - PERTURB.update(self.old) - - -def s32(x): - x &= M32 - return x - (1 << 32) if x & 0x80000000 else x - - -def atomic(op, old, data): - if op == "add": - return (old + data) & M32 - if op == "sub": - return (old - data) & M32 - if op == "min_i32": - return old if s32(old) <= s32(data) else data - if op == "max_i32": - if "max_i32_unsigned" in PERTURB: - return max(old, data) - return old if s32(old) >= s32(data) else data - if op == "min_u32": - if "min_u32_signed" in PERTURB: - return old if s32(old) <= s32(data) else data - return min(old, data) - if op == "max_u32": - return max(old, data) - if op == "and": - return old & data - if op == "or": - return old | data - if op == "xor": - return old ^ data - raise ValueError(op) - - -def swizzle_src(lane, offset): - """Source lane for ds_swizzle_b32 (lane = index in the wave).""" - if offset & 0x8000: - sh = 2 * (lane & 3) - if "swizzle_quad_reversed" in PERTURB: - sh = 6 - sh - sel = (offset >> sh) & 3 - return (lane & ~3) | sel - and_m, or_m, xor_m = offset & 31, (offset >> 5) & 31, (offset >> 10) & 31 - if "swizzle_or_xor_swapped" in PERTURB: - or_m, xor_m = xor_m, or_m - return (lane & ~31) | ((((lane & 31) & and_m) | or_m) ^ xor_m) - - -def op_family(op): - """The name of the op family a generated op belongs to (the per-family tables and the perturbations use it).""" - k = op["kind"] - if k == "read": - name = op["name"] - if "d16" in name: - return "read_d16_hi" if name.endswith("_hi") else "read_d16_lo" - if name in ("ds_read_u8", "ds_read_i8", "ds_read_u16", "ds_read_i16"): - return "read_" + name.split("_")[-1] - return "read_b32" if name == "ds_read_b32" else "read_wide" - if k == "write": - name = op["name"] - if name.endswith("d16_hi"): - return "write_d16_hi" - return "write_small" if name in ("ds_write_b8", "ds_write_b16") else "write_b32" if name == "ds_write_b32" \ - else "write_wide" - if k == "atomic": - return "atomic_" + op["op"] - if k == "atomic_rtn": - return "atomic_rtn_" + op["op"] - return k - - -class Program: - """A generated program: a list of ops, the wave size and the initial values.""" - - def __init__(self, seed, index, wave, no_exec=(), threads=THREADS, permute=False, swizzle_exec=False): - """threads: the group size (a multiple of 32 that divides 1024), or "mix" to draw one from GROUP_SIZES. permute - adds ds_permute_b32 and swizzle_exec runs ds_swizzle under EXEC masks. With the defaults the program is the - one earlier versions generated for the seed; each option changes the draw sequence, so it changes the name.""" - extra = (f"t{threads}" if threads != THREADS else "") + ("p" if permute else "") + \ - ("x" if swizzle_exec else "") - self.rng = random.Random(f"{seed}:{index}:{wave}" + (f":{extra}" if extra else "")) - self.name = f"cs_ldsfuzz_s{seed}_{index}_w{wave}" + (f"_{extra}" if extra else "") - self.wave = wave - rng = self.rng - if threads == "mix": - threads = rng.choice(GROUP_SIZES) - if not isinstance(threads, int) or threads <= 0 or threads % 32 or LDS_DWORDS % threads: - raise ValueError(f"group size {threads!r}: a multiple of 32 that divides {LDS_DWORDS}") - self.threads = threads - self.out_words = threads * len(POOL) + LDS_DWORDS - self.permute, self.swizzle_exec = permute, swizzle_exec - self.lds_xor = rng.getrandbits(32) - self.lds_mul = rng.getrandbits(32) | 1 - self.pool_init = {r: (rng.randrange(1, 1 << 24), rng.getrandbits(32)) for r in POOL} - self.ops = [self.random_op() for _ in range(rng.randrange(4, 13))] - for op in self.ops: # the mask is still drawn, so the rest of the program is the same - if op["kind"] in no_exec: - op["exec"] = None - op.pop("hyp", None) - - def with_ops(self, ops): - """A copy of the program running only these ops.""" - c = copy.copy(self) - c.ops = list(ops) - return c - - @property - def hyp_ops(self): - return {i for i, op in enumerate(self.ops) if op.get("hyp")} - - @property - def partial_wave(self): - return self.threads % self.wave != 0 - - def exec_mask(self): - rng = self.rng - if rng.random() < 0.6: - return None - choice = rng.choice(("rand", "low", "high", "one", "none_hi")) - if choice == "rand": - return rng.getrandbits(64) - if choice == "low": - return 0x00000000FFFFFFFF - if choice == "high": - return 0xFFFFFFFF00000000 - if choice == "one": - return 1 << rng.randrange(64) - return rng.getrandbits(32) - - def lane_addresses(self, stride, base): - return [(t * stride + base) for t in range(self.threads)] - - def disjoint(self, spans): - """spans: per thread, list of (byte address, bytes). True when no byte is touched by two threads.""" - owner = {} - for t, ss in enumerate(spans): - for a, n in ss: - if a < 0 or a + n > LDS_BYTES: - return False - for b in range(a, a + n): - if owner.setdefault(b, t) != t: - return False - return True - - def pick_addr(self, size, align, distinct, extra=()): - """(stride, base, offset) so that every thread's access fits and, if distinct, threads don't overlap. - extra: further byte offsets each thread also touches (read2/write2 second slot).""" - rng = self.rng - for _ in range(200): - if distinct: - stride = rng.choice([s for s in (align, 2 * align, 4, 8, 16, 32, 48, 64) if s % align == 0 and s >= 1]) - else: - stride = rng.choice([0, align, 4, 8, 16, 32]) // align * align - top = LDS_BYTES - stride * (self.threads - 1) - size - max(extra, default=0) - if top < 0: - continue - off = rng.choice([0, 0, rng.randrange(0, min(top, 0xFFFF) + 1)]) // align * align - base_top = top - off - if base_top < 0: - continue - base = rng.randrange(0, base_top + 1) // align * align - spans = [[(a + off, size)] + [(a + off + e, size) for e in extra] for a in self.lane_addresses(stride, base)] - if not distinct or self.disjoint(spans): - return stride, base, off - return None - - def random_op(self): - rng = self.rng - kinds = ("read", "read", "write", "write", "read2", "write2", "atomic", "atomic_rtn", - "wrxchg", "wrxchg2", "cmpst", "swizzle", "bpermute") + (("permute",) if self.permute else ()) - while True: - op = self.make(rng.choice(kinds)) - if op: - return op - - def make(self, kind): - rng = self.rng - if kind == "read": - name = rng.choice(sorted(READS)) - size = READS[name][0] - align = min(size, 4) if size < 4 else (16 if size > 8 else size) - a = self.pick_addr(size, align, distinct=False) - if not a: - return None - n = (size + 3) // 4 if size >= 4 else 1 - dst = rng.randrange(POOL[0], POOL[-1] - n + 2) - return {"kind": kind, "name": name, "addr": a, "dst": dst, "exec": self.exec_mask()} - if kind == "write": - name = rng.choice(sorted(WRITES)) - size = WRITES[name][0] - align = min(size, 4) if size < 4 else (16 if size > 8 else size) - a = self.pick_addr(size, align, distinct=True) - if not a: - return None - n = (size + 3) // 4 if size >= 4 else 1 - src = rng.randrange(POOL[0], POOL[-1] - n + 2) - return {"kind": kind, "name": name, "addr": a, "src": src, "exec": self.exec_mask()} - if kind in ("read2", "write2"): - st64 = rng.random() < 0.3 - unit = 256 if st64 else 4 - o0, o1 = rng.randrange(0, 4 if st64 else 64), rng.randrange(0, 4 if st64 else 64) - if kind == "write2" and o0 == o1: - return None - lo = min(o0, o1) * unit - extra = (max(o0, o1) * unit - lo,) - a = self.pick_addr(4, 4, distinct=(kind == "write2"), extra=extra) - if not a: - return None - stride, base, _ = a - # the instruction's offsets are offset0/offset1; place the lower one at the picked spot - base = base + a[2] - if base - lo < 0: - return None - base -= lo - op = {"kind": kind, "st64": st64, "o0": o0, "o1": o1, "addr": (stride, base, 0), "exec": self.exec_mask()} - if kind == "read2": - op["dst"] = rng.randrange(POOL[0], POOL[-1]) - else: - op["src0"], op["src1"] = rng.choice(POOL), rng.choice(POOL) - return op - if kind == "wrxchg2": - st64 = rng.random() < 0.3 - unit = 256 if st64 else 4 - o0, o1 = rng.randrange(0, 4 if st64 else 64), rng.randrange(0, 4 if st64 else 64) - lo = min(o0, o1) * unit - extra = (max(o0, o1) * unit - lo,) - a = self.pick_addr(4, 4, distinct=True, extra=extra) - if not a: - return None - stride, base, _ = a - base = base + a[2] - if base - lo < 0: - return None - base -= lo - # the data pair is read before `vdst` is written, so `vdst` may alias it (measured on gfx1100) - srcs = rng.sample(POOL, 2) - dst = rng.randrange(POOL[0], POOL[-1]) # dst + 1 stays inside POOL - return {"kind": kind, "st64": st64, "o0": o0, "o1": o1, "addr": (stride, base, 0), "dst": dst, - "src0": srcs[0], "src1": srcs[1], "exec": self.exec_mask()} - if kind == "atomic": - a = self.pick_addr(4, 4, distinct=False) - if not a: - return None - return {"kind": kind, "op": rng.choice(SHARED_ATOMICS), "addr": a, "src": rng.choice(POOL), - "exec": self.exec_mask()} - if kind in ("atomic_rtn", "wrxchg", "cmpst"): - a = self.pick_addr(4, 4, distinct=True) - if not a: - return None - op = {"kind": kind, "addr": a, "src": rng.choice(POOL), "dst": rng.choice(POOL), "exec": self.exec_mask()} - if kind == "atomic_rtn": - op["op"] = rng.choice(RTN_ATOMICS) - if kind == "cmpst": - op["src2"] = rng.choice(POOL) - op["cmp_hit"] = rng.random() < 0.6 # make the compare value equal the memory word for some lanes - return op - if kind == "swizzle": - if rng.random() < 0.5: - offset = 0x8000 | rng.getrandbits(8) - else: - offset = rng.getrandbits(15) - op = {"kind": kind, "offset": offset, "src": rng.choice(POOL), "dst": rng.choice(POOL), "exec": None} - if self.swizzle_exec: - op["exec"] = self.exec_mask() - if op["exec"] is not None: - op["hyp"] = ("an active lane whose source lane is off in EXEC reads 0, like ds_bpermute; measured on gfx1150, " - "RDNA2 unmeasured") - return op - if kind == "bpermute": - return {"kind": kind, "mul": rng.randrange(0, 64), "add": rng.randrange(0, 64), - "offset": rng.choice([0, 0, 4 * rng.randrange(0, 64)]), "src": rng.choice(POOL), - "dst": rng.choice(POOL), "exec": self.exec_mask()} - if kind == "permute": - # allow both odd (bijective) and even (colliding) multipliers; RDNA2 hw (gfx1030, SHADER-133) and gfx1150 - # confirm the highest active source lane wins a collision, unaddressed active lanes get 0, halves separate - return {"kind": kind, "mul": rng.randrange(0, 64), "add": rng.randrange(0, 64), - "offset": rng.choice([0, 0, 4 * rng.randrange(0, 64)]), "src": rng.choice(POOL), - "dst": rng.choice(POOL), "exec": self.exec_mask(), - "hyp": "only active lanes send, highest active sender wins collisions, a lane nobody sends to " - "gets 0, each 32-lane half is separate (measured on gfx1030 SHADER-133 and gfx1150)"} - raise ValueError(kind) - - # ---- the program text ---- - - def asm(self): - """The program for the translator (llvm-mc gfx1013 text, buffer stores through the resource in s[0:3]).""" - head = [f"; {self.name}: tools/lds_fuzz.py (FUZZ-6)", f"; group: {self.threads},1,1", f"; rsrc2: {RSRC2:#x}"] - if self.wave == 64: - head.append("; mattr: +wavefrontsize64,-wavefrontsize32") - return "\n".join(head + self.body(self.ops)) + "\n" - - def hw_lines(self, arch, ops=None): - """The program as a native kernel body for tools/hw_oracle: the entry EXEC is saved and restored (a partial - wave has fewer lanes than -1), the stores go through the output pointer in s[2:3], and the ds_* mnemonics are - the ones the architecture names them, and so are the barrier and the LDS waits (GFX12, asm.sync_lines).""" - from hw_oracle import asm - ops = self.ops if ops is None else ops - lines = self.body(ops, hw=True, arch=arch) - return [out for ln in lines for out in asm.sync_lines(asm.ds_line(ln, arch), arch)] - - def body(self, ops, hw=False, arch="gfx1150"): - w64 = self.wave == 64 - T = self.threads - out = [] - if hw: - from hw_oracle import asm - gfx10 = asm.family(arch) == "gfx10" - e = EXEC_SAVE - full = f"s_mov_b64 exec, s[{e}:{e + 1}]" if w64 else f"s_mov_b32 exec_lo, s{e}" - out.append(f"s_mov_b64 s[{e}:{e + 1}], exec" if w64 else f"s_mov_b32 s{e}, exec_lo") - - def store(data, addr, off=None): - return (f"{'global_store_dword' if gfx10 else 'global_store_b32'} v{addr}, v{data}, s[2:3]" - + (f" offset:{off}" if off is not None else "")) - else: - full = "s_mov_b64 exec, -1" if w64 else "s_mov_b32 exec_lo, -1" - out.append(full) - - def store(data, addr, off=None): - return f"buffer_store_dword v{data}, v{addr}, s[0:3], 0 offen" + (f" offset:{off}" if off is not None else "") - for r, (k, c) in self.pool_init.items(): - out += [f"v_mul_u32_u24_e32 v{r}, {k:#x}, v0", f"v_xor_b32_e32 v{r}, {c:#x}, v{r}"] - for j in range(LDS_DWORDS // T): - out += [f"v_add_nc_u32_e32 v{TMP}, {T * j}, v0", - f"v_lshlrev_b32_e32 v{ADDR}, 2, v{TMP}", - f"v_mul_lo_u32 v{TMP}, v{TMP}, {self.lds_mul:#x}", - f"v_xor_b32_e32 v{TMP}, {self.lds_xor:#x}, v{TMP}", - f"ds_write_b32 v{ADDR}, v{TMP}"] - out += ["s_waitcnt lgkmcnt(0)", "s_barrier"] - for op in ops: - out += self.asm_op(op, w64, full) - out += ["s_waitcnt lgkmcnt(0)", "s_barrier"] - for i, r in enumerate(POOL): - out += [f"v_mul_u32_u24_e32 v{ADDR}, {4 * len(POOL)}, v0", store(r, ADDR, 4 * i)] - for j in range(LDS_DWORDS // T): - out += [f"v_add_nc_u32_e32 v{TMP}, {T * j}, v0", - f"v_lshlrev_b32_e32 v{TMP}, 2, v{TMP}", - f"ds_read_b32 v{ADDR}, v{TMP}", - "s_waitcnt lgkmcnt(0)", - f"v_add_nc_u32_e32 v{TMP}, {4 * T * len(POOL)}, v{TMP}", - store(ADDR, TMP)] - out.append("s_endpgm") - return out - - def asm_addr(self, stride, base): - return [f"v_mul_u32_u24_e32 v{ADDR}, {stride}, v0", f"v_add_nc_u32_e32 v{ADDR}, {base:#x}, v{ADDR}"] - - def asm_exec(self, mask, w64): - if mask is None: - return [] - mask &= (1 << min(self.threads, self.wave)) - 1 # lanes a partial wave doesn't have stay off - if w64: - return [f"s_mov_b32 exec_lo, {mask & M32:#x}", f"s_mov_b32 exec_hi, {mask >> 32:#x}"] - return [f"s_mov_b32 exec_lo, {mask & M32:#x}"] - - def asm_op(self, op, w64, full): - k = op["kind"] - lines = [] - if k in ("read", "write", "atomic", "atomic_rtn", "wrxchg", "wrxchg2", "cmpst", "read2", "write2"): - stride, base, off = op["addr"] - lines += self.asm_addr(stride, base) - if k == "cmpst" and op["cmp_hit"]: - # compare value = the word currently in memory for every lane (so the store happens): read it first - lines += [f"ds_read_b32 v{op['src']}, v{ADDR} offset:{op['addr'][2]}", "s_waitcnt lgkmcnt(0)"] - if k in ("bpermute", "permute"): - lines += [f"v_mul_u32_u24_e32 v{ADDR}, {op['mul']}, v0", f"v_add_nc_u32_e32 v{ADDR}, {op['add']}, v{ADDR}", - f"v_lshlrev_b32_e32 v{ADDR}, 2, v{ADDR}"] - lines += self.asm_exec(op["exec"], w64) - if k == "read": - size = READS[op["name"]][0] - n = (size + 3) // 4 if size >= 4 else 1 - dst = f"v{op['dst']}" if n == 1 else f"v[{op['dst']}:{op['dst'] + n - 1}]" - lines.append(f"{op['name']} {dst}, v{ADDR} offset:{op['addr'][2]}") - elif k == "write": - size = WRITES[op["name"]][0] - n = (size + 3) // 4 if size >= 4 else 1 - src = f"v{op['src']}" if n == 1 else f"v[{op['src']}:{op['src'] + n - 1}]" - lines.append(f"{op['name']} v{ADDR}, {src} offset:{op['addr'][2]}") - elif k == "read2": - nm = "ds_read2st64_b32" if op["st64"] else "ds_read2_b32" - lines.append(f"{nm} v[{op['dst']}:{op['dst'] + 1}], v{ADDR} offset0:{op['o0']} offset1:{op['o1']}") - elif k == "write2": - nm = "ds_write2st64_b32" if op["st64"] else "ds_write2_b32" - lines.append(f"{nm} v{ADDR}, v{op['src0']}, v{op['src1']} offset0:{op['o0']} offset1:{op['o1']}") - elif k == "atomic": - lines.append(f"{ATOMIC_NAME[op['op']] % ''} v{ADDR}, v{op['src']} offset:{op['addr'][2]}") - elif k == "atomic_rtn": - lines.append(f"{ATOMIC_NAME[op['op']] % '_rtn'} v{op['dst']}, v{ADDR}, v{op['src']} offset:{op['addr'][2]}") - elif k == "wrxchg": - lines.append(f"ds_wrxchg_rtn_b32 v{op['dst']}, v{ADDR}, v{op['src']} offset:{op['addr'][2]}") - elif k == "wrxchg2": - nm = "ds_wrxchg2st64_rtn_b32" if op["st64"] else "ds_wrxchg2_rtn_b32" - lines.append(f"{nm} v[{op['dst']}:{op['dst'] + 1}], v{ADDR}, v{op['src0']}, v{op['src1']} " - f"offset0:{op['o0']} offset1:{op['o1']}") - elif k == "cmpst": - lines.append(f"ds_cmpst_rtn_b32 v{op['dst']}, v{ADDR}, v{op['src']}, v{op['src2']} offset:{op['addr'][2]}") - elif k == "swizzle": - lines.append(f"ds_swizzle_b32 v{op['dst']}, v{op['src']} offset:{op['offset']:#x}") - elif k == "bpermute": - lines.append(f"ds_bpermute_b32 v{op['dst']}, v{ADDR}, v{op['src']} offset:{op['offset']}") - elif k == "permute": - lines.append(f"ds_permute_b32 v{op['dst']}, v{ADDR}, v{op['src']} offset:{op['offset']}") - if op["exec"] is not None: - lines.append(full) - return lines - - # ---- the model ---- - - def model(self): - """Run the program on the reference model. Returns (regs[t][r], lds bytearray).""" - T = self.threads - regs = [{r: ((t * k) & M32) ^ c for r, (k, c) in self.pool_init.items()} for t in range(T)] - lds = bytearray(LDS_BYTES) - for i in range(LDS_DWORDS): - struct.pack_into("= 4 else 1)) - if k in ("read2", "wrxchg2"): - return range(op["dst"], op["dst"] + 2) - if k in ("atomic_rtn", "wrxchg", "cmpst", "swizzle", "bpermute", "permute"): - return (op["dst"],) - return () - - def describe(self, i): - if i is None: - return "initial value" - op = self.ops[i] - what = op.get("name") or op.get("op") or ("st64" if op.get("st64") else "") - mask = "" if op["exec"] is None else f", EXEC {op['exec']:#x}" - return " ".join(x for x in (f"op {i}", op["kind"], what) if x) + mask - - def active(self, t, mask): - if mask is None: - return True - return bool((mask >> (t & (self.wave - 1))) & 1) - - def wave_lane(self, t): - return t & (self.wave - 1) - - def model_op(self, op, regs, lds): - k = op["kind"] - T = self.threads - rd = lambda a: struct.unpack_from("= 4: - new.append([rd(a + 4 * i) for i in range(size // 4)]) - continue - raw = int.from_bytes(lds[a:a + size], "little") - bits = 8 * size - sext = raw - (1 << bits) if raw >> (bits - 1) else raw - if (op["name"] == "ds_read_i8" and "i8_zero_extend" in PERTURB) or \ - (op["name"] == "ds_read_i16" and "i16_zero_extend" in PERTURB): - sext = raw - old = regs[t][op["dst"]] - if how == "u": - v = raw - elif how == "i": - v = sext & M32 - elif how in ("u_lo", "i_lo"): - keep = 0 if "u8_d16_clobbers_hi" in PERTURB else old & 0xFFFF0000 - v = keep | ((raw if how == "u_lo" else sext) & 0xFFFF) - else: - keep = 0 if "d16_hi_zeroes_low" in PERTURB else old & 0xFFFF - v = keep | (((raw if how == "u_hi" else sext) & 0xFFFF) << 16) - new.append([v]) - for t in range(T): - if new[t] is not None: - for i, v in enumerate(new[t]): - regs[t][op["dst"] + i] = v - elif k == "write": - size, shift = WRITES[op["name"]] - if op["name"] == "ds_write_b16_d16_hi" and "b16_hi_shift_0" in PERTURB: - shift = 0 - for t in range(T): - if not act[t]: - continue - if size >= 4: - for i in range(size // 4): - struct.pack_into("> shift) & ((1 << (8 * size)) - 1) - lds[addr[t]:addr[t] + size] = v.to_bytes(size, "little") - elif k in ("read2", "write2"): - unit = 256 if op["st64"] else 4 - if op["st64"] and "st64_unit_4" in PERTURB: - unit = 4 - stride, base, _ = op["addr"] - for t in range(T): - if not act[t]: - continue - a = t * stride + base - a0, a1 = a + op["o0"] * unit, a + op["o1"] * unit - if k == "read2": - regs[t][op["dst"]], regs[t][op["dst"] + 1] = rd(a0), rd(a1) - else: - d0, d1 = regs[t][op["src0"]], regs[t][op["src1"]] - if "write2_swapped" in PERTURB: - d0, d1 = d1, d0 - struct.pack_into("> 2 - if self.wave == 64 and "bpermute_wave64_cross" in PERTURB: - s = (t & ~63) | (word & 63) - else: - s = (t & ~31) | (word & 31) - new[t] = src[s] if s < T and (act[s] or "bpermute_inactive_reads" in PERTURB) else 0 - for t, v in new.items(): - regs[t][op["dst"]] = v - elif k == "permute": - # forward scatter within each 32-lane half: active lanes send to lane (addr + offset) / 4 of their 32-lane - # group; highest-numbered active source wins collisions; active destination lanes nobody targets get 0 - src = [regs[t][op["src"]] for t in range(T)] - sent = {} - lanes = range(T - 1, -1, -1) if "permute_lowest_wins" in PERTURB else range(T) - for t in lanes: - if act[t]: - word = ((t * op["mul"] + op["add"]) * 4 + op["offset"]) >> 2 - if self.wave == 64 and "permute_wave64_cross" in PERTURB: - sent[(t & ~63) | (word & 63)] = src[t] - else: - sent[(t & ~31) | (word & 31)] = src[t] - for t in range(T): - if act[t] and not ("permute_no_zero" in PERTURB and t not in sent): - regs[t][op["dst"]] = sent.get(t, 0) - else: - raise ValueError(k) - - -def programs(seed, count, waves, no_exec=(), **opts): - return [Program(seed, i, w, no_exec, **opts) for i in range(count) for w in waves] - - -def parse_dump(data, threads=THREADS): - words = struct.unpack(f"<{len(data) // 4}I", data) - return parse_words(words, threads) - - -def parse_words(words, threads=THREADS): - regs = [{r: words[t * len(POOL) + i] for i, r in enumerate(POOL)} for t in range(threads)] - lds = words[threads * len(POOL):threads * len(POOL) + LDS_DWORDS] - return regs, lds - - -def compare(p, got_regs, got_lds): - want_regs, want_lds = p.model() - diffs = [] - for t in range(p.threads): - for r in POOL: - if got_regs[t][r] != want_regs[t][r]: - diffs.append(f"thread {t} v{r}: got {got_regs[t][r]:#010x}, want {want_regs[t][r]:#010x}" - f" (last written by {p.describe(p.writer[t][r])})") - for i in range(LDS_DWORDS): - w = struct.unpack_from(" --target vk_compute_test)") - env = dict(os.environ, VKC_OUT_WORDS=str(p.out_words), VKC_DUMP=str(dump)) - if pc_tail: - env["LEONIDA_PC_TAIL_UBO"] = "1" - args = [exe, str(spv), "1", "dump"] - if p.wave == 64 and not emulate: - args.append("--require-wave64") - elif p.wave == 32 or emulate: - env["VKC_SUBGROUP_SIZE"] = "32" - if index_entry.get("subgroup_size") and not emulate: - env["VKC_SUBGROUP_SIZE"] = str(index_entry["subgroup_size"]) - r = subprocess.run(args, capture_output=True, text=True, env=env) - return r.returncode, (r.stdout + r.stderr).strip() - - -def show_cmd(p, no_exec, opts): - flags = "".join(f" --no-exec {k}" for k in no_exec) - if opts.get("permute"): - flags += " --permute" - if opts.get("swizzle_exec"): - flags += " --swizzle-exec" - if opts.get("threads", THREADS) != THREADS: - flags += f" --threads {opts['threads']}" - return flags - - -def run_translator(progs, a, work, tally): - """The translator oracle: translate every program with a whole number of waves and run it on the GPU. Returns the - exit code of this oracle (0, 1, 2) and fills tally["translator"][name] with the verdict.""" - pc_tail = bool(getattr(a, "pc_tail_ubo", False)) - try: - todo = [p for p in progs if not p.partial_wave] - for p in progs: - if p.partial_wave: - print(f"SKIP {p.name}: translator: a wave64 group of {p.threads} threads is a partial wave " - "(the translator cannot launch one)") - if todo: - index = translate(todo, work, a.emulate, pc_tail=True) if pc_tail else translate(todo, work, a.emulate) - else: - index = {} - except RuntimeError as e: - print(e) - return 2 - failed = hyp_only = untranslated = errors = 0 - skipped = len(progs) - len(todo) - for p in todo: - spv = work / "spirv" / (p.name + ".spv") - if p.name not in index or not spv.is_file(): - untranslated += 1 - print(f"NOT TRANSLATED {p.name}") - tally.setdefault("translator", {})[p.name] = "not translated" - continue - dump = work / (p.name + ".bin") - dump.unlink(missing_ok=True) - rc, msg = (run_gpu(p, spv, a.build, index[p.name], a.emulate, dump, pc_tail=True) - if pc_tail else run_gpu(p, spv, a.build, index[p.name], a.emulate, dump)) - if rc == 77: - skipped += 1 - print(f"SKIP {p.name}: {msg.splitlines()[-1] if msg else 'unsupported'}") - tally.setdefault("translator", {})[p.name] = "skipped" - continue - # A wave32 program needs 32-lane subgroups. Where vk_compute_test couldn't pin them, its words come from - # another wave size and are no evidence either way. --wave64-emulate output uses no subgroup operations. - lanes = unpinned_subgroup(msg) if rc == 0 and p.wave == 32 else None - if lanes: - skipped += 1 - print(f"SKIP {p.name}: the device can't run it at {lanes} lanes " - f"(vk_compute_test: compute subgroup size: {lanes} not available)") - tally.setdefault("translator", {})[p.name] = "skipped" - continue - data = dump.read_bytes() if dump.is_file() else b"" - if rc != 0 or len(data) != 4 * p.out_words: # dump mode itself never fails a run - errors += 1 - print(f"ERROR {p.name}: exit {rc}, {len(data)} of {4 * p.out_words} dump bytes: {msg[-400:]}") - tally.setdefault("translator", {})[p.name] = "error" - continue - regs, lds = parse_dump(data, p.threads) - diffs = compare(p, regs, lds) - if diffs and p.hyp_ops: - hyp_only += 1 - tally.setdefault("translator", {})[p.name] = "hypothesis" - print(f"HYPOTHESIS MISMATCH {p.name} ({len(diffs)} words; program has a hypothesis op); print it with " - f"--show {a.seed}:{p.name.split('_')[3]}:{p.wave}{show_cmd(p, a.no_exec, a.opts)}") - for d in diffs[:a.max_report]: - print(" ", d) - elif diffs: - failed += 1 - tally.setdefault("translator", {})[p.name] = "mismatch" - print(f"MISMATCH {p.name} ({len(diffs)} words); print it with --show {a.seed}:" - f"{p.name.split('_')[3]}:{p.wave}{show_cmd(p, a.no_exec, a.opts)}") - for d in diffs[:a.max_report]: - print(" ", d) - else: - tally.setdefault("translator", {})[p.name] = "match" - mode = "emulated" if a.emulate else "native" - ran = len(progs) - untranslated - skipped - errors - extra = f", {hyp_only} differ in a program with a hypothesis op" if hyp_only else "" - print(f"{ran - failed - hyp_only}/{ran} programs that ran match ({mode}); {failed} mismatched{extra}, " - f"{skipped} skipped, {untranslated} not translated, {errors} harness errors; work dir {work}") - if errors or ran == 0: - return 2 - return 1 if failed or untranslated else 0 - - -# ---- the hardware oracle ---- - -def hw_skip_reason(p, arch): - """Why a program cannot run natively on this GPU, or None. GFX11 renamed the ds_* loads and stores, which - asm.ds_line respells, and swaps ds_cmpstore's data operands (measured on gfx1150 and on gfx1201); GFX12 also - spells the barrier and the LDS wait differently, which asm.sync_lines respells. Everything else the generator - emits is spelled the same on GFX10, GFX11 and GFX12 (assembled for gfx1030, gfx1100, gfx1150 and gfx1201), so - the other skips are the assembler's own rejections, which the runner reports. - - One behaviour differs on GFX12: a wave64 ds_bpermute_b32 or ds_permute_b32 reaches all 64 lanes there, while - RDNA2 (the console's generation, and what this model describes) keeps each 32-lane half separate. Measured with - every lane asking for lane (l + 32) mod 64, and with every lane sending to that lane: an RX 9070 XT (gfx1201) - returns and delivers lane l ^ 32 in both directions, a gfx1036 iGPU returns and delivers lane l, and on gfx1201 - 300 of 300 wave64 programs match --perturb bpermute_wave64_cross. So those programs can't check the RDNA2 model - on GFX12 and are skipped there; wave32 and every other wave64 program still run.""" - from hw_oracle import asm - if asm.family(arch) == "gfx12" and p.wave == 64: - cross = {"bpermute": "bpermute_wave64_cross", "permute": "permute_wave64_cross"} - kinds = {op["kind"] for op in p.ops} & set(cross) - if any(k for k in kinds if cross[k] not in PERTURB): - return ("a wave64 ds_bpermute_b32 / ds_permute_b32 reaches all 64 lanes on GFX12 (measured on gfx1201), " - "not each 32-lane half") - return None - - -def hw_kernel(p, arch, ops=None): - from hw_oracle import asm - return asm.Kernel(p.hw_lines(arch, ops), p.wave, p.threads, p.out_words, raw=True, lds=LDS_BYTES, vgprs=HW_VGPRS) - - -def run_hw(oracle, progs, a, tally, results): - """The hardware oracle: run every program natively (wave32 or wave64, its real group size, its EXEC masks and - barriers) and compare every stored word with the model. results gets (program, regs, lds) of each run.""" - stats = {} - kernels, which = [], [] - verdicts = tally.setdefault("hw", {}) - for p in progs: - st = stats.setdefault(f"wave{p.wave} hw", {"programs": 0, "match": 0, "mismatch": 0, "hyp_only": 0, - "hyp_confirmed": 0, "skipped": 0, "rejected": 0}) - st["programs"] += 1 - why = hw_skip_reason(p, oracle.arch) - if why: - st["skipped"] += 1 - verdicts[p.name] = "skipped" - print(f"SKIP {p.name} [hw]: {why}") - continue - kernels.append(hw_kernel(p, oracle.arch)) - which.append(p) - harness = 0 - try: - ran = oracle.run(kernels) - except RuntimeError as e: - if re.search(r"LDS|group segment|words", str(e)): - print("hardware oracle unavailable: this backend cannot run these programs (no LDS support, or fewer " - f"output words than they store): {str(e)[:200]}") - return 77 - raise - for p, got in zip(which, ran): - st = stats[f"wave{p.wave} hw"] - if isinstance(got, str): - st["rejected"] += 1 - verdicts[p.name] = "rejected" - print(f"SKIP {p.name} [hw]: {got}") - continue - if len(got) != p.out_words: - harness += 1 - verdicts[p.name] = "error" - print(f"ERROR {p.name} [hw]: {len(got)} of {p.out_words} words") - continue - regs, lds = parse_words(got, p.threads) - results.append((p, regs, lds)) - diffs = compare(p, regs, lds) - hyp = bool(p.hyp_ops) - if not diffs: - st["match"] += 1 - st["hyp_confirmed"] += hyp - verdicts[p.name] = "match" - continue - # On the hardware a failing hypothesis is a falsified claim, and it could hide a model bug elsewhere in the - # program, so it is a mismatch like any other; hyp_only counts the ones that had a hypothesis op. - st["mismatch"] += 1 - st["hyp_only"] += hyp - verdicts[p.name] = "mismatch" - print(f"MISMATCH {p.name} [hw] ({len(diffs)} words){' (program has a hypothesis op)' if hyp else ''}; " - f"print it with --show {a.seed}:{p.name.split('_')[3]}:{p.wave}{show_cmd(p, a.no_exec, a.opts)}") - for d in diffs[:a.max_report]: - print(" ", d) - if a.minimize: - ops = minimize_hw(p, oracle) - print(" minimized (ops that still differ on the hardware):") - for i in range(len(ops)): - print(f" {ops[i]}" + (" ; hypothesis op" if ops[i].get("hyp") else "")) - if a.keep: - os.makedirs(a.keep, exist_ok=True) - Path(a.keep, f"{p.name}_hw.s").write_text("\n".join(p.hw_lines(oracle.arch)) + "\n", encoding="utf-8", newline="\n") - print("hardware summary:") - for key, st in sorted(stats.items()): - print(f" {key}: " + ", ".join(f"{k} {v}" for k, v in st.items())) - bad = sum(st["mismatch"] for st in stats.values()) - ran = sum(st["match"] + st["mismatch"] for st in stats.values()) - if harness or ran == 0: - return 2 - return 1 if bad else 0 - - -def minimize_hw(p, oracle): - """Drop ops while the program still differs on the hardware; returns the remaining ops.""" - def fails_with(ops): - q = p.with_ops(ops) - got = oracle.run([hw_kernel(q, oracle.arch)])[0] - if isinstance(got, str) or len(got) != p.out_words: - return False - regs, lds = parse_words(got, p.threads) - return bool(compare(q, regs, lds)) - ops = list(p.ops) - for i in range(len(ops) - 1, -1, -1): - trial = ops[:i] + ops[i + 1:] - if fails_with(trial): - ops = trial - return ops - - -def family_table(results, tally_hw): - """Per op family: ops executed in programs that matched on the hardware, in programs that did not.""" - fam = {} - for p, regs, lds in results: - ok = tally_hw.get(p.name) == "match" - for op in p.ops: - row = fam.setdefault(op_family(op), [0, 0, 0, 0]) - row[0 if ok else 1] += 1 - if op["exec"] is not None: - row[2 if ok else 3] += 1 - return fam - - -def attribute(results): - """Per op family: words that differ and were last written by an op of that family (registers only; LDS words - are counted under 'LDS').""" - out = {} - for p, regs, lds in results: - want_regs, want_lds = p.model() - for t in range(p.threads): - for r in POOL: - if regs[t][r] != want_regs[t][r]: - w = p.writer[t][r] - key = "initial value" if w is None else op_family(p.ops[w]) - out[key] = out.get(key, 0) + 1 - for i in range(LDS_DWORDS): - if lds[i] != struct.unpack_from("= 0 and WAVE in 32, 64") - if index < 0 or wave not in (32, 64): - ap.error("--show expects SEED:INDEX[:WAVE] with INDEX >= 0 and WAVE in 32, 64") - if a.hw_arch: - show(seed, index, wave, tuple(a.no_exec), arch=a.hw_arch, **a.opts) - else: - show(seed, index, wave, tuple(a.no_exec), **a.opts) - return 0 - waves = (64, 32) if a.wave == "both" else (int(a.wave),) - progs = programs(a.seed, a.programs, waves, tuple(a.no_exec), **a.opts) - if a.only is not None: - try: - keep = {int(x) for x in a.only.split(",")} - except ValueError: - ap.error("--only takes a comma-separated list of program indices") - progs = [p for p in progs if int(p.name.split("_")[3]) in keep] - if not progs: - ap.error("--only matches no program (the indices must be below --programs)") - if a.model_only: - for p in progs: - p.model() - print(f"{len(progs)} programs generated and modelled") - return 0 - oracle = None - if "hw" in backends: - from hw_oracle import runner - try: - oracle = runner.open_oracle(arch=a.hw_arch) - except runner.Unavailable as e: - print(f"hardware oracle unavailable: {e}") - return 77 - print(f"hardware oracle: {oracle.device}") - tally, rcs, results = {}, [], [] - try: - if "translator" in backends: - a.build = find_test_program(a.build, "vk_compute_test") or a.build # a Visual Studio config subfolder - try: - parent = Path(a.work).resolve() if a.work else None - if parent is not None: - parent.mkdir(parents=True, exist_ok=True) - work = Path(tempfile.mkdtemp(prefix="lds_fuzz_", dir=parent)) - except OSError as e: - print(f"ERROR: cannot create work directory: {e}", file=sys.stderr) - return 2 - print(f"work dir {work}") - rcs.append(run_translator(progs, a, work, tally)) - if oracle: - if a.perturb: - PERTURB.add(a.perturb) # the hardware side only: the translator is judged by the right model - hw_rc = run_hw(oracle, progs, a, tally, results) - PERTURB.discard(a.perturb) - if hw_rc == 77: - return 77 - rcs.append(hw_rc) - if "translator" in backends: - for p in progs: - if tally["hw"].get(p.name) == "mismatch": - print(f"{p.name}: hardware and model differ; translator: " - f"{tally['translator'].get(p.name, 'not run')}") - if results: - print("op families (ops run in programs that matched on the hardware / that differed; " - "of those, under a partial EXEC mask):") - for fam, (m, x, me, xe) in sorted(family_table(results, tally["hw"]).items()): - print(f" {fam:<22} {m:>6} / {x:<5} masked {me:>5} / {xe}") - bad = attribute(results) - if bad: - print("differing words by the family of the op that last wrote them: " + - ", ".join(f"{k} {v}" for k, v in sorted(bad.items()))) - if a.negative_control or a.perturb: - if a.perturb: - n_bad = sum(v == "mismatch" for v in tally["hw"].values()) - print(f"perturbed model '{a.perturb}' ({PERTURBATIONS[a.perturb][1]}): {n_bad} of " - f"{len(results)} programs mismatch" + ("" if n_bad else " -- NOT DETECTED")) - if hw_rc != 2: # a harness error stays one; otherwise a mismatch is the pass - rcs[-1] = 0 if n_bad else 1 - if a.negative_control: - print("negative control (wrong models judged against the same hardware words):") - silent = [] - for name, (cases, bad) in negative_control(results).items(): - note = "" if not cases else "" if bad else " -- NOT DETECTED" - if cases and not bad: - silent.append(name) - print(f" {name:<26} {cases:>5} programs with the op, {bad:>5} mismatch{note}" - + (" (no program has this op: not exercised)" if not cases else "")) - if silent: - print(f"canary FAILED: perturbations not detected: {', '.join(silent)}") - rcs.append(1) - finally: - PERTURB.clear() - if oracle: - oracle.close() - return 2 if 2 in rcs else 1 if 1 in rcs else 0 - - -if __name__ == "__main__": - try: # a redirected stdout is strict ANSI code page under -I; write '?' for what it cannot encode - sys.stdout.reconfigure(errors="replace") - except (AttributeError, ValueError, OSError): - pass - sys.exit(main()) diff --git a/tools/leonida_mods.py b/tools/leonida_mods.py deleted file mode 100644 index 3bd43b859..000000000 --- a/tools/leonida_mods.py +++ /dev/null @@ -1,1072 +0,0 @@ -#!/usr/bin/env python3 -"""Install and manage Leonida mods (docs/modding.md). - -A mod is a folder containing `mod.json`; `gta6rt` reads those folders from `mods/` next to itself. This tool manages -that folder without touching the game package or the generated work files. It can create a manifest, install a mod -folder or a ZIP/`.leonidamod` package, enable or disable installed mods, pack one for sharing, and start `gta6rt` -with the managed `--mods` folder. - -Standard library only. On Windows, `Mods.bat` opens the Tkinter GUI; the same actions stay available from the CLI: - - python -I tools/leonida_mods.py gui - python -I tools/leonida_mods.py --port "D:\\Games\\Leonida" list - python -I tools/leonida_mods.py --port "D:\\Games\\Leonida" install mandy.zip - python -I tools/leonida_mods.py --port "D:\\Games\\Leonida" new lucia_to_mandy \ - --name "Mandy" --game-version 1.0.2.1 --swap player_story000_00=cs_mandy - python -I tools/leonida_mods.py --port "D:\\Games\\Leonida" run --archetype-lookup 1A2B3C0 - -`--port` is the built port folder (the one with `gta6rt.exe` and `game_path.txt`). `--dir` names a mods folder -directly, which is useful for the repository's `mods/` examples or tests. With neither, the current folder and the -usual `Documents/Leonida` and `~/Leonida` build outputs are tried. -""" -from __future__ import annotations - -import argparse -import json -import os -import secrets -import shlex -import shutil -import stat -import subprocess -import sys -import tempfile -import zipfile -from dataclasses import dataclass, field -from pathlib import PurePosixPath -from types import SimpleNamespace - -EXPECTED_EXE = "game_scarlett_master.exe" -MANIFEST = "mod.json" -WINDOWS_RESERVED = {"CON", "PRN", "AUX", "NUL", *(f"COM{i}" for i in range(1, 10)), - *(f"LPT{i}" for i in range(1, 10))} - - -class ModsError(Exception): - """A user-facing failure: bad input, an unsafe package or a filesystem problem.""" - - -@dataclass -class Swap: - from_name: str - to_name: str - from_id: int - to_id: int - when: str = "always" - - -@dataclass -class ModInfo: - folder: str - path: str - name: str - enabled: bool - game_version: str - swaps: list[Swap] = field(default_factory=list) - warnings: list[str] = field(default_factory=list) - raw: dict = field(default_factory=dict) - - -def joaat(name: str) -> int: - """RAGE's joaat over the lowercased latin-1 bytes, the rule ``tools/hashdict.py`` (the pinned name - dictionary) and every other name-hashing tool use. - - Encoding to UTF-8 first gives a different hash for any non-ASCII character (``é`` is one byte 0xE9, not - 0xC3 0xA9), so a model or swap name written with an accent would resolve to an id nothing in the package - has. Characters outside latin-1 hash as ``?``, as ``hashdict.joaat`` does.""" - h = 0 - for byte in name.lower().encode("latin-1", "replace"): - h = (h + byte) & 0xFFFFFFFF - h = (h + (h << 10)) & 0xFFFFFFFF - h ^= h >> 6 - h = (h + (h << 3)) & 0xFFFFFFFF - h ^= h >> 11 - return (h + (h << 15)) & 0xFFFFFFFF - - -def parse_model_id(text: str) -> int: - if not isinstance(text, str) or not text: - raise ValueError("empty model name") - if text.startswith(("0x", "0X")): - digits = text[2:] - if not digits: - raise ValueError("0x has no hash digits") - if len(digits) > 8 or any(c not in "0123456789abcdefABCDEF" for c in digits): - raise ValueError(f"{text} is not a 32-bit hash") - return int(digits, 16) - return joaat(text) - - -def validate_manifest(data: object, folder: str, path: str = "") -> ModInfo: - if not isinstance(data, dict): - raise ModsError(f"{folder}: {MANIFEST} is not a JSON object") - mod = ModInfo(folder=folder, path=path, name=folder, enabled=True, game_version="", raw=data) - name = data.get("name") - if isinstance(name, str) and name.strip(): - mod.name = name - elif name is not None: - mod.warnings.append('"name" is not a string; the folder name is shown instead') - version = data.get("game_version") - if isinstance(version, str): - mod.game_version = version - elif version is not None: - mod.warnings.append('"game_version" is not a string; gta6rt ignores it') - enabled = data.get("enabled", True) - if not isinstance(enabled, bool): - raise ModsError(f'{folder}: "enabled" must be true or false') - mod.enabled = enabled - swaps = data.get("archetype_swaps") - if swaps is None: - mod.warnings.append("no archetype_swaps; this mod currently changes nothing") - return mod - if not isinstance(swaps, list): - raise ModsError(f'{folder}: "archetype_swaps" must be a list') - seen = {} - for index, item in enumerate(swaps): - label = f"archetype_swaps[{index}]" - if not isinstance(item, dict) or not isinstance(item.get("from"), str) or \ - not isinstance(item.get("to"), str): - raise ModsError(f'{folder}: {label} needs "from" and "to" model names') - swap = Swap(item["from"], item["to"], 0, 0) - try: - swap.from_id = parse_model_id(swap.from_name) - swap.to_id = parse_model_id(swap.to_name) - except ValueError as exc: - raise ModsError(f"{folder}: {label} {swap.from_name} -> {swap.to_name}: {exc}") from exc - when = item.get("when", "always") - if when != "always": - raise ModsError(f'{folder}: {label} "when" can only be "always" until a game hook provides mission ' - "state (docs/modding.md)") - if swap.from_id == swap.to_id: - raise ModsError(f"{folder}: {label} swaps a model with itself") - if swap.from_id in seen: - mod.warnings.append(f'{label} repeats {seen[swap.from_id]}; the later swap wins') - seen[swap.from_id] = label - mod.swaps.append(swap) - if not mod.swaps: - mod.warnings.append("archetype_swaps is empty; this mod currently changes nothing") - return mod - - -def read_manifest(path: str, folder: str) -> ModInfo: - try: - with open(path, encoding="utf-8") as f: - data = json.load(f) - except UnicodeDecodeError as exc: - raise ModsError(f"{folder}: {MANIFEST} is not UTF-8 ({exc})") from exc - except json.JSONDecodeError as exc: - raise ModsError(f"{folder}: {MANIFEST} is not valid JSON ({exc.msg} at line {exc.lineno}, " - f"column {exc.colno})") from exc - except OSError as exc: - raise ModsError(f"{folder}: cannot read {MANIFEST}: {exc}") from exc - return validate_manifest(data, folder, path) - - -def load_mods(mods_dir: str) -> tuple[list[ModInfo], list[str]]: - mods, errors = [], [] - if not os.path.isdir(mods_dir): - return mods, errors - try: - names = sorted(os.listdir(mods_dir)) - except OSError as exc: - raise ModsError(f"cannot list {mods_dir}: {exc}") from exc - for folder in names: - path = os.path.join(mods_dir, folder) - manifest = os.path.join(path, MANIFEST) - if not os.path.isdir(path) or not os.path.isfile(manifest): - continue - try: - mods.append(read_manifest(manifest, folder)) - except ModsError as exc: - errors.append(str(exc)) - return mods, errors - - -def active_swaps(mods: list[ModInfo]) -> dict[int, Swap]: - active = {} - for mod in mods: - if mod.enabled: - for swap in mod.swaps: - active[swap.from_id] = swap - return active - - -def default_port() -> str: - candidates = [os.getcwd(), - os.path.join(os.path.expanduser("~"), "Documents", "Leonida"), - os.path.join(os.path.expanduser("~"), "Leonida")] - for candidate in candidates: - if any(os.path.isfile(os.path.join(candidate, name)) - for name in ("gta6rt.exe", "gta6rt.sh", "game_path.txt")): - return candidate - raise ModsError("no built port found: pass --port or --dir ") - - -def mods_dir_for(args: argparse.Namespace) -> str: - if args.port and args.mods_dir: - raise ModsError("use either --port or --dir, not both") - if args.mods_dir: - return os.path.abspath(args.mods_dir) - port = os.path.abspath(args.port) if args.port else os.path.abspath(default_port()) - if not os.path.isdir(port): - raise ModsError(f"{port} is not a built port folder") - return os.path.join(port, "mods") - - -def port_for(args: argparse.Namespace) -> str: - if args.port: - return os.path.abspath(args.port) - if args.mods_dir: - parent = os.path.dirname(os.path.abspath(args.mods_dir)) - if os.path.basename(os.path.abspath(args.mods_dir)).lower() == "mods" and \ - any(os.path.isfile(os.path.join(parent, name)) - for name in ("gta6rt.exe", "gta6rt.sh", "game_path.txt")): - return parent - raise ModsError("--dir does not name a built port's mods folder; pass --port for run") - return os.path.abspath(default_port()) - - -def safe_folder_name(text: str) -> str: - bad = '<>:"/\\|?*' - cleaned = "".join("_" if ord(c) < 32 or c in bad else c for c in text.strip()) - cleaned = " ".join(cleaned.split()).rstrip(" .") - if not cleaned or cleaned in (".", "..") or cleaned.split(".", 1)[0].upper() in WINDOWS_RESERVED: - cleaned = "mod" - cleaned = cleaned[:80].rstrip(" .") - return cleaned or "mod" - - -def simple_selector(name: str) -> str: - if not name or name in (".", "..") or os.path.basename(name) != name: - raise ModsError(f"{name!r} is not an installed mod folder name") - return name - - -def is_within(path: str, directory: str) -> bool: - try: - return os.path.commonpath([os.path.abspath(path), os.path.abspath(directory)]) == \ - os.path.abspath(directory) - except ValueError: - return False - - -def find_manifest_root(directory: str) -> str: - if os.path.isfile(os.path.join(directory, MANIFEST)): - return directory - roots = [] - try: - children = sorted(os.listdir(directory)) - except OSError as exc: - raise ModsError(f"cannot list {directory}: {exc}") from exc - for child in children: - path = os.path.join(directory, child) - if os.path.isdir(path) and os.path.isfile(os.path.join(path, MANIFEST)): - roots.append(path) - if len(roots) == 1: - return roots[0] - if roots: - raise ModsError(f"{directory} has more than one top-level {MANIFEST}; keep one mod folder per package") - raise ModsError(f"{directory} has no {MANIFEST} at its top level or in one top-level folder") - - -def reject_symlinks(root: str) -> None: - for base, dirs, files in os.walk(root, followlinks=False): - for name in dirs + files: - path = os.path.join(base, name) - if os.path.islink(path): - raise ModsError(f"{path} is a symbolic link; mod packages must contain regular files") - - -def zip_parts(name: str) -> tuple[str, ...]: - if not name or "\\" in name or "\x00" in name: - raise ModsError(f"unsafe ZIP member name {name!r}") - parts = PurePosixPath(name).parts - if not parts or parts[0] == "/" or ".." in parts or "." in parts: - raise ModsError(f"unsafe ZIP member name {name!r}") - for part in parts: - if safe_folder_name(part) != part: - raise ModsError(f"unsafe ZIP member name {name!r}") - return parts - - -def extract_zip(source: str, destination: str) -> None: - os.makedirs(destination, exist_ok=True) - try: - archive = zipfile.ZipFile(source) - except zipfile.BadZipFile as exc: - raise ModsError(f"{source} is not a readable ZIP package") from exc - with archive: - for info in archive.infolist(): - parts = zip_parts(info.filename) - target = os.path.join(destination, *parts) - if not is_within(target, destination): - raise ModsError(f"unsafe ZIP member name {info.filename!r}") - mode = info.external_attr >> 16 - if mode and stat.S_IFMT(mode) == stat.S_IFLNK: - raise ModsError(f"ZIP member {info.filename!r} is a symbolic link") - if info.is_dir(): - os.makedirs(target, exist_ok=True) - continue - os.makedirs(os.path.dirname(target), exist_ok=True) - with archive.open(info) as src, open(target, "wb") as dst: - shutil.copyfileobj(src, dst) - - -def write_manifest(path: str, data: dict) -> None: - with open(path, "w", encoding="utf-8", newline="\n") as f: - json.dump(data, f, indent=2, ensure_ascii=False) - f.write("\n") - - -def set_enabled_in_manifest(manifest_path: str, enabled: bool) -> None: - try: - with open(manifest_path, encoding="utf-8") as f: - data = json.load(f) - except (OSError, UnicodeDecodeError, json.JSONDecodeError) as exc: - raise ModsError(f"cannot update {manifest_path}: {exc}") from exc - if not isinstance(data, dict): - raise ModsError(f"{manifest_path} is not a JSON object") - data["enabled"] = enabled - write_manifest(manifest_path, data) - - -def publish_mod(staged: str, target: str, force: bool) -> None: - backup = None - if os.path.lexists(target): - if not force: - raise ModsError(f"{os.path.basename(target)} is already installed; pass --force to replace it") - backup = os.path.join(os.path.dirname(target), - f".{os.path.basename(target)}.replaced-{secrets.token_hex(4)}") - os.replace(target, backup) - try: - os.replace(staged, target) - except OSError: - if backup is not None: - try: - os.replace(backup, target) - except OSError: - pass - raise - if backup is not None: - shutil.rmtree(backup, ignore_errors=True) - - -def stage_source(source: str, work: str) -> tuple[str, str, str]: - staged = os.path.join(work, "mod") - source = os.path.abspath(source) - if os.path.isdir(source): - root = find_manifest_root(source) - label = os.path.basename(root.rstrip(os.sep)) - reject_symlinks(root) - elif os.path.isfile(source) and zipfile.is_zipfile(source): - unpacked = os.path.join(work, "package") - extract_zip(source, unpacked) - root = find_manifest_root(unpacked) - label = os.path.splitext(os.path.basename(source))[0] if os.path.abspath(root) == \ - os.path.abspath(unpacked) else os.path.basename(root) - reject_symlinks(root) - elif os.path.isfile(source): - raise ModsError(f"{source} is not a mod folder or ZIP/.leonidamod package") - else: - raise ModsError(f"{source} does not exist") - try: - shutil.copytree(root, staged, symlinks=True) - except OSError as exc: - raise ModsError(f"cannot stage {root}: {exc}") from exc - return staged, root, label - - -def install_mod(source: str, mods_dir: str, name: str | None = None, force: bool = False, - enabled: bool | None = None) -> tuple[ModInfo, str]: - os.makedirs(mods_dir, exist_ok=True) - work = tempfile.mkdtemp(prefix=".leonida-install-", dir=mods_dir) - try: - staged, root, package_label = stage_source(source, work) - if is_within(root, mods_dir) and not is_within(root, work): - raise ModsError(f"{root} is already inside the managed mods folder") - label = safe_folder_name(name or package_label) - manifest_path = os.path.join(staged, MANIFEST) - mod = read_manifest(manifest_path, label) - if enabled is not None: - set_enabled_in_manifest(manifest_path, enabled) - mod.enabled = enabled - target = os.path.join(mods_dir, label) - publish_mod(staged, target, force) - mod.folder, mod.path = label, os.path.join(target, MANIFEST) - return mod, target - finally: - shutil.rmtree(work, ignore_errors=True) - - -def create_mod(folder: str, mods_dir: str, display_name: str | None, game_version: str | None, - swap_specs: list[str], disabled: bool, force: bool) -> tuple[ModInfo, str]: - if not swap_specs: - raise ModsError("new needs at least one --swap FROM=TO") - label = safe_folder_name(folder) - swaps = [] - for spec in swap_specs: - if "=" not in spec: - raise ModsError(f"--swap {spec!r} must be FROM=TO") - from_name, to_name = spec.split("=", 1) - swaps.append({"from": from_name, "to": to_name, "when": "always"}) - data = {"name": display_name or label, - "enabled": not disabled, - "archetype_swaps": swaps} - if game_version: - data["game_version"] = game_version - mod = validate_manifest(data, label) - os.makedirs(mods_dir, exist_ok=True) - work = tempfile.mkdtemp(prefix=".leonida-new-", dir=mods_dir) - try: - staged = os.path.join(work, "mod") - os.makedirs(staged) - write_manifest(os.path.join(staged, MANIFEST), data) - target = os.path.join(mods_dir, label) - publish_mod(staged, target, force) - return mod, target - finally: - shutil.rmtree(work, ignore_errors=True) - - -def find_mod_folder(mods_dir: str, selector: str) -> str: - wanted = simple_selector(selector) - try: - names = [n for n in os.listdir(mods_dir) if os.path.isdir(os.path.join(mods_dir, n))] - except OSError as exc: - raise ModsError(f"cannot list {mods_dir}: {exc}") from exc - matches = [n for n in names if n == wanted] - if not matches: - folded = wanted.casefold() - matches = [n for n in names if n.casefold() == folded] - if len(matches) > 1: - raise ModsError(f"{wanted} names more than one mod folder") - if not matches: - raise ModsError(f"{wanted} is not installed in {mods_dir}") - path = os.path.join(mods_dir, matches[0]) - if not os.path.isfile(os.path.join(path, MANIFEST)): - raise ModsError(f"{matches[0]} has no {MANIFEST}; refusing to manage it") - return path - - -def set_mod_enabled(mods_dir: str, selector: str, enabled: bool) -> ModInfo: - path = find_mod_folder(mods_dir, selector) - manifest = os.path.join(path, MANIFEST) - set_enabled_in_manifest(manifest, enabled) - return read_manifest(manifest, os.path.basename(path)) - - -def uninstall_mod(mods_dir: str, selector: str, yes: bool) -> str: - path = find_mod_folder(mods_dir, selector) - if os.path.islink(path) or not is_within(path, mods_dir): - raise ModsError(f"{path} is not a regular folder inside {mods_dir}") - if not yes: - if not sys.stdin.isatty(): - raise ModsError("uninstall needs --yes when input is not interactive") - answer = input(f"Remove {os.path.basename(path)} from {mods_dir}? [y/N] ") - if answer.strip().lower() not in ("y", "yes"): - raise ModsError("uninstall cancelled") - shutil.rmtree(path) - return path - - -def pack_mod(mods_dir: str, selector: str, output: str, force: bool) -> str: - path = find_mod_folder(mods_dir, selector) - reject_symlinks(path) - output = os.path.abspath(output) - if is_within(output, path): - raise ModsError("the package output cannot be inside the mod being packed") - if os.path.exists(output) and not force: - raise ModsError(f"{output} exists; pass --force to replace it") - os.makedirs(os.path.dirname(output) or ".", exist_ok=True) - folder = os.path.basename(path) - with zipfile.ZipFile(output, "w", zipfile.ZIP_DEFLATED) as archive: - for base, dirs, files in os.walk(path, followlinks=False): - dirs.sort() - for name in sorted(files): - full = os.path.join(base, name) - member = PurePosixPath(folder, os.path.relpath(full, path).replace(os.sep, "/")) - archive.write(full, member.as_posix()) - return output - - -def runtime_executable(port: str) -> str: - names = ("gta6rt.exe",) if os.name == "nt" else ("gta6rt.sh", "gta6rt.exe") - for name in names: - path = os.path.join(port, name) - if os.path.isfile(path): - return path - raise ModsError(f"{port} has no gta6rt executable; build the runtime stage first") - - -def runtime_command(args: argparse.Namespace, mods_dir: str) -> list[str]: - port = port_for(args) - game = os.path.abspath(args.game) if args.game else None - if game is None: - game_path = os.path.join(port, "game_path.txt") - try: - with open(game_path, encoding="utf-8") as f: - game = f.read().strip() - except OSError as exc: - raise ModsError(f"no --game given and {game_path} is unreadable: {exc}") from exc - if not game: - raise ModsError(f"{game_path} is empty; pass --game") - image = os.path.abspath(args.image) if args.image else os.path.join(game, EXPECTED_EXE) - if not os.path.isfile(image): - raise ModsError(f"{image} is not present; pass --image for a stand-in executable") - mode = "--dry-run" if args.dry_run else "--init" if args.init else "--run" - command = [runtime_executable(port), mode, image, "--game-dir", game, "--mods", mods_dir] - if args.archetype_lookup: - command += ["--archetype-lookup", args.archetype_lookup] - if args.trace_d3d12: - command.append("--trace-d3d12") - if args.trace: - command += ["--trace", args.trace] - command += args.game_args - return command - - -def run_args(port: str, game: str | None = None, image: str | None = None, mode: str = "--run", - archetype_lookup: str | None = None, game_args: list[str] | None = None) -> SimpleNamespace: - """The attribute set `runtime_command` reads, for callers that do not come through argparse.""" - return SimpleNamespace(port=port, mods_dir=None, game=game, image=image, - dry_run=mode == "--dry-run", init=mode == "--init", - archetype_lookup=archetype_lookup, trace_d3d12=False, trace=None, - game_args=game_args or []) - - -def port_from_mods_dir(mods_dir: str | None) -> str | None: - """The built-port parent of a `/mods` folder, when it has the runtime's marker files.""" - if not mods_dir: - return None - path = os.path.abspath(mods_dir) - if os.path.basename(path).lower() != "mods": - return None - parent = os.path.dirname(path) - if any(os.path.isfile(os.path.join(parent, name)) - for name in ("gta6rt.exe", "gta6rt.sh", "game_path.txt")): - return parent - return None - - -def print_report(mods_dir: str, mods: list[ModInfo], errors: list[str]) -> None: - print(f"mods dir: {mods_dir}") - if not mods and not errors: - print("no mods installed") - return - previous = {} - for mod in mods: - state = "enabled" if mod.enabled else "disabled" - version = f", game {mod.game_version}" if mod.game_version else "" - swaps = f"{len(mod.swaps)} swap" + ("" if len(mod.swaps) == 1 else "s") - print(f"{mod.folder}: {mod.name} [{state}; {swaps}{version}]") - for warning in mod.warnings: - print(f" warning: {warning}") - for swap in mod.swaps: - conflict = "" - if mod.enabled and swap.from_id in previous: - conflict = f" (overrides {previous[swap.from_id]})" - print(f" archetype {swap.from_name} (0x{swap.from_id:08X}) -> {swap.to_name} " - f"(0x{swap.to_id:08X}){conflict}") - if mod.enabled: - previous[swap.from_id] = mod.folder - for error in errors: - print(f"skipped {error}") - - -def report_json(mods_dir: str, mods: list[ModInfo], errors: list[str]) -> str: - data = { - "mods_dir": mods_dir, - "mods": [{ - "folder": m.folder, - "name": m.name, - "enabled": m.enabled, - "game_version": m.game_version, - "warnings": m.warnings, - "archetype_swaps": [{ - "from": s.from_name, "to": s.to_name, - "from_hash": f"0x{s.from_id:08X}", "to_hash": f"0x{s.to_id:08X}", - "when": s.when, - } for s in m.swaps], - } for m in mods], - "errors": errors, - } - return json.dumps(data, indent=2, ensure_ascii=False) - - -def run_gui(args: argparse.Namespace, initial_mods_dir: str | None) -> int: - """Open the Tkinter mod-manager window. Imported here so the CLI and tests need no display.""" - try: - import tkinter as tk - from tkinter import filedialog, messagebox, ttk - except ImportError as exc: - hint = ("on Windows install Python from python.org with Tcl/Tk" if os.name == "nt" else - "install your distribution's Tkinter package (Debian and Ubuntu: sudo apt install python3-tk)") - raise ModsError(f"Tkinter is not installed; {hint}") from exc - - class ModsApp: - def __init__(self, root): - self.root = root - self.mods = {} - self.errors = [] - port = args.port or port_from_mods_dir(initial_mods_dir) or "" - self.port_var = tk.StringVar(value=port) - self.mods_var = tk.StringVar(value=initial_mods_dir or (os.path.join(port, "mods") if port else "")) - self.game_var = tk.StringVar(value=self.read_game_path(port)) - self.image_var = tk.StringVar() - self.lookup_var = tk.StringVar() - self.new_folder_var = tk.StringVar() - self.new_name_var = tk.StringVar() - self.new_version_var = tk.StringVar(value="1.0.2.1") - self.new_from_var = tk.StringVar(value="player_story000_00") - self.new_to_var = tk.StringVar(value="cs_mandy") - self.new_disabled_var = tk.BooleanVar(value=False) - self.status_var = tk.StringVar() - self.build_layout() - if self.mods_var.get(): - self.refresh() - else: - self.status("Choose the built Leonida port folder") - - def read_game_path(self, port): - if not port: - return "" - try: - with open(os.path.join(port, "game_path.txt"), encoding="utf-8") as f: - return f.read().strip() - except OSError: - return "" - - def build_layout(self): - self.root.title("Leonida Mod Manager") - self.root.minsize(860, 620) - self.root.columnconfigure(0, weight=1) - self.root.rowconfigure(0, weight=1) - outer = ttk.Frame(self.root, padding=10) - outer.grid(row=0, column=0, sticky="nsew") - outer.columnconfigure(0, weight=1) - outer.rowconfigure(1, weight=1) - outer.rowconfigure(4, weight=1) - - paths = ttk.LabelFrame(outer, text="Folders", padding=8) - paths.grid(row=0, column=0, sticky="ew") - paths.columnconfigure(1, weight=1) - ttk.Label(paths, text="Port").grid(row=0, column=0, sticky="w") - ttk.Entry(paths, textvariable=self.port_var).grid(row=0, column=1, sticky="ew", padx=6) - ttk.Button(paths, text="Browse...", command=self.choose_port).grid(row=0, column=2) - ttk.Label(paths, text="Mods").grid(row=1, column=0, sticky="w", pady=(6, 0)) - ttk.Entry(paths, textvariable=self.mods_var).grid(row=1, column=1, sticky="ew", padx=6, - pady=(6, 0)) - mods_buttons = ttk.Frame(paths) - mods_buttons.grid(row=1, column=2, pady=(6, 0)) - ttk.Button(mods_buttons, text="Browse...", command=self.choose_mods).pack(side="left") - ttk.Button(mods_buttons, text="Open", command=lambda: self.guard(self.open_mods)).pack( - side="left", padx=(6, 0)) - - installed = ttk.LabelFrame(outer, text="Installed mods", padding=8) - installed.grid(row=1, column=0, sticky="nsew", pady=(8, 0)) - installed.columnconfigure(0, weight=1) - installed.rowconfigure(0, weight=1) - columns = ("folder", "name", "state", "swaps", "version") - self.tree = ttk.Treeview(installed, columns=columns, show="headings", height=9, - selectmode="browse") - for column, title, width in (("folder", "Folder", 190), ("name", "Name", 250), - ("state", "State", 75), ("swaps", "Swaps", 60), - ("version", "Game", 90)): - self.tree.heading(column, text=title) - self.tree.column(column, width=width, anchor="w") - scroll = ttk.Scrollbar(installed, orient="vertical", command=self.tree.yview) - self.tree.configure(yscrollcommand=scroll.set) - self.tree.grid(row=0, column=0, sticky="nsew") - scroll.grid(row=0, column=1, sticky="ns") - actions = ttk.Frame(installed) - actions.grid(row=1, column=0, columnspan=2, sticky="ew", pady=(8, 0)) - for text, command in (("Refresh", self.refresh), - ("Install ZIP", self.install_package), - ("Install folder", self.install_folder), - ("Enable/disable", self.toggle_selected), - ("Pack", self.pack_selected), - ("Uninstall", self.uninstall_selected), - ("Check", self.check_mods)): - ttk.Button(actions, text=text, command=lambda c=command: self.guard(c)).pack(side="left", - padx=(0, 6)) - - bottom = ttk.Frame(outer) - bottom.grid(row=2, column=0, sticky="ew", pady=(8, 0)) - bottom.columnconfigure(0, weight=1) - bottom.columnconfigure(1, weight=1) - - creator = ttk.LabelFrame(bottom, text="New archetype swap", padding=8) - creator.grid(row=0, column=0, sticky="nsew", padx=(0, 4)) - for col in range(4): - creator.columnconfigure(col, weight=1) - fields = (("Folder", self.new_folder_var), ("Name", self.new_name_var), - ("Game version", self.new_version_var), ("From", self.new_from_var), - ("To", self.new_to_var)) - for row, (label, var) in enumerate(fields): - ttk.Label(creator, text=label).grid(row=row, column=0, sticky="w", pady=2) - ttk.Entry(creator, textvariable=var).grid(row=row, column=1, columnspan=3, sticky="ew", - padx=6, pady=2) - ttk.Checkbutton(creator, text="Install disabled", variable=self.new_disabled_var).grid( - row=5, column=1, sticky="w", pady=4) - ttk.Button(creator, text="Create mod", command=lambda: self.guard(self.create_new)).grid( - row=5, column=3, sticky="e", pady=4) - - launcher = ttk.LabelFrame(bottom, text="Run", padding=8) - launcher.grid(row=0, column=1, sticky="nsew", padx=(4, 0)) - launcher.columnconfigure(1, weight=1) - ttk.Label(launcher, text="Game folder").grid(row=0, column=0, sticky="w") - ttk.Entry(launcher, textvariable=self.game_var).grid(row=0, column=1, sticky="ew", padx=6) - ttk.Button(launcher, text="Browse...", - command=lambda: self.choose_directory(self.game_var, "Choose the game package folder")).grid( - row=0, column=2) - ttk.Label(launcher, text="Image").grid(row=1, column=0, sticky="w", pady=(6, 0)) - ttk.Entry(launcher, textvariable=self.image_var).grid(row=1, column=1, sticky="ew", padx=6, - pady=(6, 0)) - ttk.Button(launcher, text="Browse...", - command=lambda: self.choose_file(self.image_var, "Choose an image to load")).grid( - row=1, column=2, pady=(6, 0)) - ttk.Label(launcher, text="Lookup RVA").grid(row=2, column=0, sticky="w", pady=(6, 0)) - ttk.Entry(launcher, textvariable=self.lookup_var).grid(row=2, column=1, sticky="ew", padx=6, - pady=(6, 0)) - run_buttons = ttk.Frame(launcher) - run_buttons.grid(row=3, column=0, columnspan=3, sticky="ew", pady=(8, 0)) - for text, mode, print_only in (("Run", "--run", False), ("Dry run", "--dry-run", False), - ("Command", "--run", True)): - ttk.Button(run_buttons, text=text, - command=lambda m=mode, p=print_only: self.guard(self.launch, m, p)).pack( - side="left", padx=(0, 6)) - - log_frame = ttk.LabelFrame(outer, text="Log", padding=8) - log_frame.grid(row=4, column=0, sticky="nsew", pady=(8, 0)) - log_frame.columnconfigure(0, weight=1) - log_frame.rowconfigure(0, weight=1) - self.log_text = tk.Text(log_frame, height=7, wrap="word", state="disabled") - log_scroll = ttk.Scrollbar(log_frame, orient="vertical", command=self.log_text.yview) - self.log_text.configure(yscrollcommand=log_scroll.set) - self.log_text.grid(row=0, column=0, sticky="nsew") - log_scroll.grid(row=0, column=1, sticky="ns") - ttk.Label(outer, textvariable=self.status_var).grid(row=5, column=0, sticky="ew", - pady=(6, 0)) - - def log(self, text): - self.log_text.configure(state="normal") - self.log_text.insert("end", text.rstrip() + "\n") - self.log_text.see("end") - self.log_text.configure(state="disabled") - - def status(self, text): - self.status_var.set(text) - - def guard(self, fn, *argv): - try: - fn(*argv) - except Exception as exc: - self.log(f"ERROR: {exc}") - messagebox.showerror("Leonida Mod Manager", str(exc)) - - def mods_dir(self): - path = self.mods_var.get().strip() - if not path: - raise ModsError("choose the port or mods folder first") - return os.path.abspath(path) - - def choose_port(self): - folder = filedialog.askdirectory(title="Choose the built Leonida port folder") - if folder: - self.port_var.set(folder) - self.mods_var.set(os.path.join(folder, "mods")) - game = self.read_game_path(folder) - if game: - self.game_var.set(game) - self.guard(self.refresh) - - def choose_mods(self): - folder = filedialog.askdirectory(title="Choose the mods folder") - if folder: - self.mods_var.set(folder) - port = port_from_mods_dir(folder) - if port: - self.port_var.set(port) - self.guard(self.refresh) - - def choose_directory(self, variable, title): - folder = filedialog.askdirectory(title=title) - if folder: - variable.set(folder) - - def choose_file(self, variable, title): - path = filedialog.askopenfilename(title=title) - if path: - variable.set(path) - - def refresh(self): - path = self.mods_var.get().strip() - self.tree.delete(*self.tree.get_children()) - self.mods = {} - if not path: - self.status("Choose the built Leonida port folder") - return - self.mods_list, self.errors = load_mods(path) - for mod in self.mods_list: - self.mods[mod.folder] = mod - self.tree.insert("", "end", iid=mod.folder, - values=(mod.folder, mod.name, "enabled" if mod.enabled else "disabled", - len(mod.swaps), mod.game_version)) - active = len(active_swaps(self.mods_list)) - self.status(f"{len(self.mods_list)} mod(s), {active} active swap(s), " - f"{len(self.errors)} manifest error(s)") - for error in self.errors: - self.log(f"skipped {error}") - - def selected(self): - selection = self.tree.selection() - if not selection: - raise ModsError("select a mod first") - folder = selection[0] - if folder not in self.mods: - raise ModsError("select an installed mod first") - return self.mods[folder] - - def open_mods(self): - path = self.mods_dir() - os.makedirs(path, exist_ok=True) - if hasattr(os, "startfile"): - os.startfile(path) - elif sys.platform == "darwin": - subprocess.Popen(["open", path]) - else: - subprocess.Popen(["xdg-open", path]) - self.log(f"opened {path}") - - def install_source(self, source): - try: - mod, target = install_mod(source, self.mods_dir()) - except ModsError as exc: - if "already installed" not in str(exc) or not messagebox.askyesno( - "Replace mod?", f"{exc}\nReplace it?"): - raise - mod, target = install_mod(source, self.mods_dir(), force=True) - self.log(f"installed {mod.folder}: {mod.name} -> {target}") - self.refresh() - - def install_package(self): - source = filedialog.askopenfilename( - title="Install a mod package", - filetypes=(("Leonida mod packages", "*.leonidamod *.zip"), ("All files", "*.*"))) - if source: - self.install_source(source) - - def install_folder(self): - source = filedialog.askdirectory(title="Install a mod folder") - if source: - self.install_source(source) - - def create_new(self): - folder = self.new_folder_var.get().strip() - if not folder: - raise ModsError("folder is required") - spec = f"{self.new_from_var.get().strip()}={self.new_to_var.get().strip()}" - try: - mod, target = create_mod(folder, self.mods_dir(), self.new_name_var.get().strip() or None, - self.new_version_var.get().strip() or None, [spec], - self.new_disabled_var.get(), False) - except ModsError as exc: - if "already installed" not in str(exc) or not messagebox.askyesno( - "Replace mod?", f"{exc}\nReplace it?"): - raise - mod, target = create_mod(folder, self.mods_dir(), self.new_name_var.get().strip() or None, - self.new_version_var.get().strip() or None, [spec], - self.new_disabled_var.get(), True) - self.log(f"created {mod.folder}: {mod.name} -> {target}") - self.refresh() - - def toggle_selected(self): - mod = self.selected() - updated = set_mod_enabled(self.mods_dir(), mod.folder, not mod.enabled) - self.log(f"{updated.folder}: {'enabled' if updated.enabled else 'disabled'}") - self.refresh() - - def pack_selected(self): - mod = self.selected() - output = filedialog.asksaveasfilename( - title="Pack mod", defaultextension=".leonidamod", initialfile=mod.folder + ".leonidamod", - filetypes=(("Leonida mod package", "*.leonidamod"), ("ZIP", "*.zip"), ("All files", "*.*"))) - if output: - replace = os.path.exists(output) - if replace and not messagebox.askyesno("Replace package?", f"{output} exists. Replace it?"): - return - self.log(f"packed {pack_mod(self.mods_dir(), mod.folder, output, replace)}") - - def uninstall_selected(self): - mod = self.selected() - if not messagebox.askyesno("Uninstall mod?", f"Remove {mod.folder}?"): - return - self.log(f"removed {uninstall_mod(self.mods_dir(), mod.folder, True)}") - self.refresh() - - def check_mods(self): - mods, errors = load_mods(self.mods_dir()) - if errors: - messagebox.showerror("Mod check", "\n".join(errors)) - else: - messagebox.showinfo("Mod check", f"{len(mods)} mod(s) checked; no manifest errors") - self.refresh() - - def launch(self, mode, print_only): - port = self.port_var.get().strip() - if not port: - raise ModsError("choose the built port folder first") - command_args = run_args(port, self.game_var.get().strip() or None, - self.image_var.get().strip() or None, mode, - self.lookup_var.get().strip() or None) - command = runtime_command(command_args, self.mods_dir()) - if print_only: - self.log(shlex.join(command)) - return - flags = getattr(subprocess, "CREATE_NEW_CONSOLE", 0) - process = subprocess.Popen(command, cwd=port, creationflags=flags) - self.log(f"started {mode} as process {process.pid}: {shlex.join(command)}") - - try: - root = tk.Tk() - except tk.TclError as exc: - raise ModsError(f"cannot open the GUI: {exc}") from exc - ModsApp(root) - root.mainloop() - return 0 - - -def add_target_args(parser: argparse.ArgumentParser) -> None: - target = parser.add_mutually_exclusive_group() - target.add_argument("--port", help="built port folder containing gta6rt (its mods/ folder is managed)") - target.add_argument("--dir", dest="mods_dir", help="manage this mods folder directly") - - -def build_parser() -> argparse.ArgumentParser: - parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) - add_target_args(parser) - commands = parser.add_subparsers(dest="command", required=True) - - commands.add_parser("gui", help="open the mod-manager window") - commands.add_parser("path", help="print the managed mods folder") - - listing = commands.add_parser("list", help="list installed mods") - listing.add_argument("--json", action="store_true", help="print machine-readable JSON") - - check = commands.add_parser("check", help="validate installed manifests") - check.add_argument("--json", action="store_true", help="print machine-readable JSON") - - install = commands.add_parser("install", help="install a mod folder or ZIP/.leonidamod package") - install.add_argument("source") - install.add_argument("--name", help="installed folder name") - install.add_argument("--force", action="store_true", help="replace an installed mod with the same folder") - enabled = install.add_mutually_exclusive_group() - enabled.add_argument("--enable", dest="set_enabled", action="store_true", default=None, - help="mark the installed manifest enabled") - enabled.add_argument("--disable", dest="set_enabled", action="store_false", - help="mark the installed manifest disabled") - - new = commands.add_parser("new", help="create an archetype-swap mod") - new.add_argument("folder", help="installed folder name") - new.add_argument("--name", help="display name (default: folder)") - new.add_argument("--game-version", help="package version the mod was made for") - new.add_argument("--swap", action="append", default=[], metavar="FROM=TO", - help="archetype swap; repeat for more than one") - new.add_argument("--disabled", action="store_true", help="install it disabled") - new.add_argument("--force", action="store_true", help="replace an installed mod with the same folder") - - for command, enabled_state in (("enable", True), ("disable", False)): - sub = commands.add_parser(command, help=f"mark a mod {command}d") - sub.add_argument("mod") - sub.set_defaults(enabled_state=enabled_state) - - uninstall = commands.add_parser("uninstall", help="remove an installed mod folder") - uninstall.add_argument("mod") - uninstall.add_argument("--yes", action="store_true", help="do not ask for confirmation") - - pack = commands.add_parser("pack", help="write an installed mod as a ZIP package") - pack.add_argument("mod") - pack.add_argument("--out", required=True, help="output .zip or .leonidamod file") - pack.add_argument("--force", action="store_true", help="replace the output file") - - run = commands.add_parser("run", help="start gta6rt with this mods folder") - mode = run.add_mutually_exclusive_group() - mode.add_argument("--dry-run", action="store_true", help="map the image without running game code") - mode.add_argument("--init", action="store_true", help="run module initialisation but not the entry point") - run.add_argument("--game", help="game package folder (default: game_path.txt)") - run.add_argument("--image", help=f"image to load (default: /{EXPECTED_EXE})") - run.add_argument("--archetype-lookup", metavar="RVA[,ARG]", - help="hook the measured archetype lookup for this executable") - run.add_argument("--trace-d3d12", action="store_true", help="log D3D12 calls") - run.add_argument("--trace", help="write the startup JSONL trace here") - run.add_argument("--print", dest="print_command", action="store_true", - help="print the command without starting it") - run.add_argument("game_args", nargs=argparse.REMAINDER, - help="arguments after -- are passed to the game") - return parser - - -def main(argv: list[str] | None = None) -> int: - args = build_parser().parse_args(argv) - try: - if args.command == "gui": - try: - mods_dir = mods_dir_for(args) - except ModsError: - if args.port or args.mods_dir: - raise - mods_dir = None - return run_gui(args, mods_dir) - mods_dir = mods_dir_for(args) - if args.command == "path": - print(mods_dir) - elif args.command in ("list", "check"): - mods, errors = load_mods(mods_dir) - if args.json: - print(report_json(mods_dir, mods, errors)) - else: - print_report(mods_dir, mods, errors) - if args.command == "check" and errors: - return 1 - elif args.command == "install": - mod, target = install_mod(args.source, mods_dir, args.name, args.force, args.set_enabled) - print(f"installed {mod.folder}: {mod.name} -> {target}") - for warning in mod.warnings: - print(f"warning: {warning}") - elif args.command == "new": - mod, target = create_mod(args.folder, mods_dir, args.name, args.game_version, args.swap, - args.disabled, args.force) - print(f"created {mod.folder}: {mod.name} -> {target}") - for warning in mod.warnings: - print(f"warning: {warning}") - elif args.command in ("enable", "disable"): - mod = set_mod_enabled(mods_dir, args.mod, args.enabled_state) - print(f"{mod.folder}: {'enabled' if mod.enabled else 'disabled'}") - elif args.command == "uninstall": - print(f"removed {uninstall_mod(mods_dir, args.mod, args.yes)}") - elif args.command == "pack": - print(f"packed {pack_mod(mods_dir, args.mod, args.out, args.force)}") - elif args.command == "run": - game_args = list(args.game_args) - if game_args[:1] == ["--"]: - game_args = game_args[1:] - args.game_args = game_args - command = runtime_command(args, mods_dir) - if args.print_command: - print(shlex.join(command)) - else: - return subprocess.call(command) - else: - raise ModsError(f"unknown command {args.command}") - except (ModsError, OSError, zipfile.BadZipFile) as exc: - print(f"ERROR: {exc}", file=sys.stderr) - return 2 - return 0 - - -if __name__ == "__main__": - try: - sys.stdout.reconfigure(errors="replace") - except (AttributeError, ValueError, OSError): - pass - sys.exit(main()) diff --git a/tools/leonida_tui.py b/tools/leonida_tui.py deleted file mode 100644 index 72a542588..000000000 --- a/tools/leonida_tui.py +++ /dev/null @@ -1,1165 +0,0 @@ -"""Stdlib LEONIDA build console: setup form + switchable per-stage log panes. - -No third-party TUI libraries. When stdin/stdout are not TTYs, callers skip this module. -""" -from __future__ import annotations - -import contextvars -import os -import shutil -import subprocess -import sys -import threading -import time -from collections import deque -from dataclasses import dataclass - -STAGE_ORDER = ("shaders", "assets", "runtime", "pipelines") - -# Figlet-style wordmark (single block, ASCII only). -LEONIDA_BANNER = [ - r" _ _____ ___ _ _ ___ ____ _ ", - r" | | | ____/ _ \| \ | |_ _| _ \ / \ ", - r" | | | _|| | | | \| || || | | |/ _ \ ", - r" | |___| |__| |_| | |\ || || |_| / ___ \ ", - r" |_____|_____\___/|_| \_|___|____/_/ \_" + "\\", -] - -# ANSI (used only when enable_ansi() succeeded). -_RESET = "\033[0m" -_BOLD = "\033[1m" -_DIM = "\033[2m" -_CYAN = "\033[36m" -_GREEN = "\033[32m" -_YELLOW = "\033[33m" -_RED = "\033[31m" -_WHITE = "\033[37m" -_REVERSE = "\033[7m" # selection: invert, not a blue fill - -_current_stage: contextvars.ContextVar[str | None] = contextvars.ContextVar("leonida_stage", default=None) -_board_ref: contextvars.ContextVar[object | None] = contextvars.ContextVar("leonida_board", default=None) -# Process-wide fallback: ContextVar is not visible in every worker on every Python/thread setup, -# but make_game.run() must still find the board to pipe cmake/dotnet away from the console. -_active_board: object | None = None -_live_procs: set = set() -_live_procs_lock = threading.Lock() -_interrupt_lock = threading.Lock() -_interrupt_fired = False -_ctrl_handler_installed = False -# Windows console input mode while the board is live (mouse wheel → scroll). -_nt_mouse_armed: tuple | None = None # (handle, old_mode) or None -_nt_key_queue: deque = deque() - -# Console input flags (Windows). -_ENABLE_PROCESSED_INPUT = 0x0001 -_ENABLE_LINE_INPUT = 0x0002 -_ENABLE_ECHO_INPUT = 0x0004 -_ENABLE_WINDOW_INPUT = 0x0008 -_ENABLE_MOUSE_INPUT = 0x0010 -_ENABLE_EXTENDED_FLAGS = 0x0080 -_ENABLE_QUICK_EDIT_MODE = 0x0040 -_KEY_EVENT = 0x0001 -_MOUSE_EVENT = 0x0002 -_MOUSE_WHEELED = 0x0004 -_MOUSE_HWHEELED = 0x0008 - - -@dataclass -class SetupConfig: - jobs: int - overlap: bool - - -def cpu_jobs_bounds() -> tuple[int, int, int]: - """(minimum, default, maximum) job counts from the machine's CPU count.""" - cpus = max(1, os.cpu_count() or 2) - return 1, max(1, cpus // 2), cpus - - -def clamp_jobs(jobs: int) -> int: - lo, _, hi = cpu_jobs_bounds() - return max(lo, min(hi, int(jobs))) - - -def tui_eligible(no_tui: bool) -> bool: - if no_tui: - return False - try: - return bool(sys.stdin and sys.stdin.isatty() and sys.stdout and sys.stdout.isatty()) - except Exception: - return False - - -def current_stage() -> str | None: - return _current_stage.get() - - -def current_board(): - return _board_ref.get() or _active_board - - -def stage_scope(name: str): - """Set the active stage for log()/subprocess capture in this context/thread.""" - return _StageScope(name) - - -class _StageScope: - def __init__(self, name: str): - self.name = name - self._token = None - - def __enter__(self): - self._token = _current_stage.set(self.name) - board = current_board() - if board is not None: - board.set_status(self.name, "running") - return self - - def __exit__(self, exc_type, exc, tb): - board = current_board() - if board is not None: - board.set_status(self.name, "failed" if exc_type else "done") - if self._token is not None: - _current_stage.reset(self._token) - return False - - -def enable_ansi() -> bool: - """Turn on VT processing on Windows consoles; True when clear/home sequences are usable.""" - if os.name != "nt": - return True - try: - import ctypes - from ctypes import wintypes - - kernel32 = ctypes.windll.kernel32 - handle = kernel32.GetStdHandle(-11) # STD_OUTPUT_HANDLE - mode = wintypes.DWORD() - if not kernel32.GetConsoleMode(handle, ctypes.byref(mode)): - return False - return bool(kernel32.SetConsoleMode(handle, mode.value | 0x0004)) - except Exception: - return False - - -def term_size() -> tuple[int, int]: - size = shutil.get_terminal_size(fallback=(100, 30)) - return max(60, size.columns), max(20, size.lines) - - -def restore_console(stream=None, *, ansi: bool, leave_alt: bool = False) -> None: - """Undo TUI modes and clear the visible buffer so the shell prompt is not painted over leftovers.""" - out = stream if stream is not None else sys.stdout - try: - if not ansi: - try: - out.write("\n") - out.flush() - except OSError: - pass - return - parts = [ - "\033[?1007l", # alternate scroll (wheel → arrows) off - "\033[?1000l", # mouse tracking off - "\033[?1006l", # SGR mouse off - "\033[?7h", # wrap on - "\033[?25h", # cursor on - "\033[0m", # attributes off - ] - if leave_alt: - parts.append("\033[?1049l") - # Clear the buffer we are about to show the user (main screen after leaving alt). - parts.extend(["\033[H", "\033[J"]) - try: - out.write("".join(parts)) - out.flush() - except OSError: - pass - finally: - _nt_disarm_mouse_input() - - -def _c(text: str, *codes: str, on: bool) -> str: - if not on or not codes: - return text - return "".join(codes) + text + _RESET - - -def wrap_log_lines(lines: list[str], width: int, max_rows: int) -> list[str]: - """Hard-wrap log lines to width; keep the newest max_rows rows (terminal-like).""" - cols = max(1, width) - wrapped: list[str] = [] - for ln in lines: - text = ln.replace("\t", " ") - if text == "": - wrapped.append("") - continue - while text: - wrapped.append(text[:cols]) - text = text[cols:] - if max_rows <= 0: - return wrapped - return wrapped[-max_rows:] - - -def _nt_arm_mouse_input() -> None: - """Enable console mouse-wheel reports; disable Quick Edit so the OS delivers them.""" - global _nt_mouse_armed - if os.name != "nt" or _nt_mouse_armed is not None: - return - try: - import ctypes - from ctypes import wintypes - - kernel32 = ctypes.windll.kernel32 - handle = kernel32.GetStdHandle(-10) # STD_INPUT_HANDLE - old = wintypes.DWORD() - if not kernel32.GetConsoleMode(handle, ctypes.byref(old)): - return - # Keep processed input; drop line/echo/quick-edit so keys and wheel are readable. - new_mode = ( - (old.value | _ENABLE_PROCESSED_INPUT | _ENABLE_MOUSE_INPUT - | _ENABLE_EXTENDED_FLAGS | _ENABLE_WINDOW_INPUT) - & ~(_ENABLE_LINE_INPUT | _ENABLE_ECHO_INPUT | _ENABLE_QUICK_EDIT_MODE) - ) - if not kernel32.SetConsoleMode(handle, new_mode): - return - _nt_mouse_armed = (handle, old.value) - _nt_key_queue.clear() - except Exception: - _nt_mouse_armed = None - - -def _nt_disarm_mouse_input() -> None: - global _nt_mouse_armed - if _nt_mouse_armed is None: - return - handle, old_mode = _nt_mouse_armed - _nt_mouse_armed = None - _nt_key_queue.clear() - try: - import ctypes - ctypes.windll.kernel32.SetConsoleMode(handle, old_mode) - except Exception: - pass - - -def _nt_wheel_delta_to_keys(delta: int, *, horizontal: bool = False) -> list[str]: - """Map a Win32 wheel delta to keys (120 units ≈ one notch). - - Vertical → Up/Down (log scroll). Horizontal → Left/Right (stage tabs), inverted so a - right tilt/swipe selects the previous tab (opposite of the keyboard arrows). - """ - if delta == 0: - return [] - notches = max(1, abs(int(delta)) // 120) - if horizontal: - key = "Left" if delta > 0 else "Right" - else: - key = "Up" if delta > 0 else "Down" - return [key] * notches - - -def _nt_decode_key_event(key_down: bool, vk: int, ch: str) -> str | None: - if not key_down: - return None - if ch in ("\x03", "\x1a"): - request_interrupt() - return None - # Virtual-key map for arrows / paging (UnicodeChar is often NUL for these). - vk_map = { - 0x26: "Up", 0x28: "Down", 0x25: "Left", 0x27: "Right", - 0x21: "PageUp", 0x22: "PageDown", 0x24: "Home", 0x23: "End", - 0x09: "Tab", 0x0D: "Enter", 0x1B: "Esc", 0x20: "Space", - } - if vk in vk_map: - return vk_map[vk] - if ch == "\r": - return "Enter" - if ch == "\t": - return "Tab" - if ch == "\x1b": - return "Esc" - if ch == " ": - return "Space" - if ch and ch.isprintable(): - return ch - return None - - -def _nt_read_console_key(timeout_s: float) -> str | None: - """Read one key or wheel step via ReadConsoleInput (mouse mode armed).""" - if _nt_key_queue: - return _nt_key_queue.popleft() - if _nt_mouse_armed is None: - return None - handle, _ = _nt_mouse_armed - try: - import ctypes - from ctypes import wintypes - except ImportError: - return None - - class COORD(ctypes.Structure): - _fields_ = [("X", wintypes.SHORT), ("Y", wintypes.SHORT)] - - class KEY_EVENT_RECORD(ctypes.Structure): - _fields_ = [ - ("bKeyDown", wintypes.BOOL), - ("wRepeatCount", wintypes.WORD), - ("wVirtualKeyCode", wintypes.WORD), - ("wVirtualScanCode", wintypes.WORD), - ("UnicodeChar", wintypes.WCHAR), - ("dwControlKeyState", wintypes.DWORD), - ] - - class MOUSE_EVENT_RECORD(ctypes.Structure): - _fields_ = [ - ("dwMousePosition", COORD), - ("dwButtonState", wintypes.DWORD), - ("dwControlKeyState", wintypes.DWORD), - ("dwEventFlags", wintypes.DWORD), - ] - - class INPUT_UNION(ctypes.Union): - _fields_ = [("KeyEvent", KEY_EVENT_RECORD), ("MouseEvent", MOUSE_EVENT_RECORD)] - - class INPUT_RECORD(ctypes.Structure): - _fields_ = [("EventType", wintypes.WORD), ("Event", INPUT_UNION)] - - kernel32 = ctypes.windll.kernel32 - timeout_ms = 0 if timeout_s <= 0 else max(1, int(timeout_s * 1000)) - deadline = time.monotonic() + max(0.0, timeout_s) - - while True: - if _nt_key_queue: - return _nt_key_queue.popleft() - wait = kernel32.WaitForSingleObject(handle, timeout_ms if timeout_s > 0 else 0) - if wait != 0: # WAIT_OBJECT_0 == 0 - if timeout_s <= 0 or time.monotonic() >= deadline: - return None - remaining = deadline - time.monotonic() - timeout_ms = max(1, int(remaining * 1000)) - continue - rec = INPUT_RECORD() - nread = wintypes.DWORD() - if not kernel32.ReadConsoleInputW(handle, ctypes.byref(rec), 1, ctypes.byref(nread)): - return None - if nread.value == 0: - return None - if rec.EventType == _MOUSE_EVENT: - flags = rec.Event.MouseEvent.dwEventFlags - if flags & (_MOUSE_WHEELED | _MOUSE_HWHEELED): - # High word of ButtonState is a signed wheel delta. - raw = rec.Event.MouseEvent.dwButtonState - delta = ctypes.c_short((raw >> 16) & 0xFFFF).value - keys = _nt_wheel_delta_to_keys(delta, horizontal=bool(flags & _MOUSE_HWHEELED)) - if not keys: - continue - _nt_key_queue.extend(keys[1:]) - return keys[0] - # Clicks / moves: consume so they do not clog the buffer. - continue - if rec.EventType != _KEY_EVENT: - continue - ke = rec.Event.KeyEvent - mapped = _nt_decode_key_event(bool(ke.bKeyDown), int(ke.wVirtualKeyCode), ke.UnicodeChar or "") - if mapped is not None: - # RepeatCount > 1 (held key): queue extras. - for _ in range(max(0, int(ke.wRepeatCount) - 1)): - _nt_key_queue.append(mapped) - return mapped - if timeout_s <= 0: - # Non-blocking: keep draining until a useful event or empty. - wait = kernel32.WaitForSingleObject(handle, 0) - if wait != 0: - return None - continue - if time.monotonic() >= deadline: - return None - - -def _parse_sgr_mouse(params: str, trail: str) -> str | None: - """CSI < btn ; col ; row M/m → wheel buttons (64/65 vertical, 66/67 horizontal).""" - if trail not in ("M", "m"): - return None - parts = params.split(";") - if not parts: - return None - try: - btn = int(parts[0]) - except ValueError: - return None - # 64/65 = vertical wheel; 66/67 = horizontal (inverted: 66 → Left, 67 → Right). - if btn == 64: - return "Up" - if btn == 65: - return "Down" - if btn == 66: - return "Left" - if btn == 67: - return "Right" - return None - - -def _read_key(timeout_s: float = 0.05) -> str | None: - """One key from stdin, or None. Returns Tab, Left, Right, Enter, Esc, Space, or a character.""" - if os.name == "nt": - if _nt_mouse_armed is not None: - return _nt_read_console_key(timeout_s) - try: - import msvcrt - except ImportError: - return None - # timeout <= 0: single non-blocking poll (the board loop used 0.0 and never read keys). - if timeout_s <= 0: - if not msvcrt.kbhit(): - return None - return _nt_consume(msvcrt) - deadline = time.monotonic() + timeout_s - while True: - if msvcrt.kbhit(): - return _nt_consume(msvcrt) - if time.monotonic() >= deadline: - return None - time.sleep(0.02) - - import select - - try: - import termios - import tty - except ImportError: - return None - fd = sys.stdin.fileno() - old = termios.tcgetattr(fd) - try: - tty.setcbreak(fd) - ready, _, _ = select.select([sys.stdin], [], [], max(0.0, timeout_s)) - if not ready: - return None - ch = sys.stdin.read(1) - if ch in ("\x03", "\x1a"): - request_interrupt() - return None - if ch == "\x1b": - ready, _, _ = select.select([sys.stdin], [], [], 0.02) - if not ready: - return "Esc" - rest = sys.stdin.read(1) - if rest != "[": - return "Esc" - ready, _, _ = select.select([sys.stdin], [], [], 0.02) - if not ready: - return "Esc" - code = sys.stdin.read(1) - if code == "<": - # SGR mouse: CSI < btn ; col ; row M/m (wheel → Up/Down). - buf = "" - while len(buf) < 32: - ready, _, _ = select.select([sys.stdin], [], [], 0.02) - if not ready: - break - c = sys.stdin.read(1) - if c in ("M", "m"): - return _parse_sgr_mouse(buf, c) - buf += c - return None - if code == "A": - return "Up" - if code == "B": - return "Down" - if code == "D": - return "Left" - if code == "C": - return "Right" - if code == "H": - return "Home" - if code == "F": - return "End" - # CSI n~ : PageUp=5, PageDown=6, Home=1, End=4 - ready, _, _ = select.select([sys.stdin], [], [], 0.02) - tilde = sys.stdin.read(1) if ready else "" - if tilde == "~": - return {"5": "PageUp", "6": "PageDown", "1": "Home", "4": "End"}.get(code) - return "Esc" - if ch == "\n": - return "Enter" - if ch == "\t": - return "Tab" - if ch == " ": - return "Space" - return ch - finally: - termios.tcsetattr(fd, termios.TCSADRAIN, old) - - -def _nt_consume(msvcrt) -> str | None: - ch = msvcrt.getwch() - # With msvcrt polling, Ctrl+C often arrives as \x03 instead of a console CTRL_C_EVENT, so the - # main thread never sees KeyboardInterrupt and the build looks wedged. - if ch in ("\x03", "\x1a"): # Ctrl+C, Ctrl+Z - request_interrupt() - return None - if ch in ("\x00", "\xe0"): - code = msvcrt.getwch() - return {"H": "Up", "P": "Down", "K": "Left", "M": "Right", - "I": "PageUp", "Q": "PageDown", "G": "Home", "O": "End"}.get(code) - if ch == "\r": - return "Enter" - if ch == "\x1b": - return "Esc" - if ch == "\t": - return "Tab" - if ch == " ": - return "Space" - return ch - - -def install_interrupt_handlers() -> None: - """Make Ctrl+C reliable under the TUI (msvcrt often eats it; children can wedge joins).""" - global _ctrl_handler_installed - if _ctrl_handler_installed: - return - _ctrl_handler_installed = True - try: - import signal - signal.signal(signal.SIGINT, lambda *_: force_exit_interrupt()) - if hasattr(signal, "SIGBREAK"): - signal.signal(signal.SIGBREAK, lambda *_: force_exit_interrupt()) - except (ValueError, OSError, AttributeError): - pass - if os.name == "nt": - try: - import ctypes - from ctypes import wintypes - - Handler = ctypes.WINFUNCTYPE(wintypes.BOOL, wintypes.DWORD) - - def _handler(ctrl_type): - # 0=CTRL_C, 1=CTRL_BREAK — return True so the default handler does not race us. - if ctrl_type in (0, 1): - force_exit_interrupt() - return True - return False - - # Keep a reference so the callback is not GC'd. - install_interrupt_handlers._handler = Handler(_handler) # type: ignore[attr-defined] - ctypes.windll.kernel32.SetConsoleCtrlHandler(install_interrupt_handlers._handler, True) - except Exception: - pass - - -def force_exit_interrupt() -> None: - """Restore the console, kill children, and exit 130. Does not return. - - Graceful KeyboardInterrupt paths still hang when a worker is blocked in readline() or - ThreadPoolExecutor shutdown waits — this is the reliable Ctrl+C path for the TUI. - """ - global _interrupt_fired, _active_board - with _interrupt_lock: - if _interrupt_fired: - os._exit(130) - _interrupt_fired = True - board = current_board() - if board is not None: - try: - board._stop.set() - except Exception: - pass - kill_live_processes() - out = sys.__stdout__ - err = sys.__stderr__ - ansi = True - leave_alt = False - if board is not None: - out = getattr(board, "_real_out", out) or out - err = getattr(board, "_real_err", err) or err - ansi = bool(getattr(board, "_ansi", True)) - leave_alt = bool(getattr(board, "_alt_screen", False)) - try: - sys.stdout = out - sys.stderr = err - except Exception: - pass - try: - restore_console(out, ansi=ansi, leave_alt=leave_alt) - except Exception: - pass - try: - err.write("Stopped. Run it again to continue where it left off.\n") - err.flush() - except Exception: - pass - _active_board = None - os._exit(130) - - -def request_interrupt() -> None: - """Ctrl+C from the key reader — hard-exit so the build cannot stay wedged.""" - force_exit_interrupt() - - -def register_live_process(proc) -> None: - with _live_procs_lock: - _live_procs.add(proc) - - -def unregister_live_process(proc) -> None: - with _live_procs_lock: - _live_procs.discard(proc) - - -def kill_live_processes() -> None: - """Terminate every subprocess started for board capture (including Windows child trees).""" - with _live_procs_lock: - procs = list(_live_procs) - _live_procs.clear() - for proc in procs: - try: - if proc.poll() is not None: - continue - if os.name == "nt" and proc.pid: - # PowerShell → cmd → cmake is a tree; terminate() alone leaves grandchildren. - subprocess.run( - ["taskkill", "/F", "/T", "/PID", str(proc.pid)], - stdout=subprocess.DEVNULL, - stderr=subprocess.DEVNULL, - check=False, - ) - else: - proc.terminate() - try: - proc.wait(timeout=1.0) - except subprocess.TimeoutExpired: - proc.kill() - except (OSError, ProcessLookupError, AttributeError): - try: - proc.kill() - except (OSError, ProcessLookupError, AttributeError): - pass - - -def run_setup(default_jobs: int | None = None, default_overlap: bool = True) -> SetupConfig: - """Interactive LEONIDA build setup. Esc keeps the defaults (clamped). - - Up/Down select a row; Left/Right change its value; Enter starts; Esc keeps defaults. - Selection paints only the label+value, not the full terminal width. - """ - install_interrupt_handlers() - lo, half, hi = cpu_jobs_bounds() - if default_jobs is None: - default_jobs = half - default_jobs = clamp_jobs(default_jobs) - jobs = default_jobs - overlap = bool(default_overlap) - # 0 = Jobs, 1 = Overlap - cursor = 0 - fields = ("jobs", "overlap") - ansi = enable_ansi() - result: SetupConfig | None = None - - def _row(label: str, value: str, selected: bool, bar_width: int) -> str: - # Highlight covers label+value only (not full terminal width), but Jobs and Overlap - # share one bar width so a short jobs number does not leave a shorter white strip. - body = f" {label:<12} {value}".ljust(bar_width) - if selected: - return _c(body, _BOLD, _REVERSE, on=ansi) - return body - - def draw() -> None: - width, height = term_size() - rule = _c("=" * width, _DIM, _CYAN, on=ansi) - thin = _c("-" * width, _DIM, on=ansi) - jobs_text = f" {'Jobs':<12} {jobs}" - overlap_text = f" {'Overlap':<12} {'yes' if overlap else 'no'}" - bar_width = max(len(jobs_text), len(overlap_text)) - rows = [""] * height - rows[0] = rule - rows[1] = "" - for i, line in enumerate(LEONIDA_BANNER): - rows[2 + i] = _c(line[:width].ljust(width), _BOLD, _CYAN, on=ansi) - rows[7] = "" - rows[8] = _c(" Build setup", _BOLD, _WHITE, on=ansi) - rows[9] = thin - rows[10] = "" - # Hint stays outside the selection highlight so the bar does not run to the edge. - rows[11] = ( - _row("Jobs", str(jobs), cursor == 0, bar_width) - + _c(f" min {lo} · default {half} · max {hi}", _DIM, on=ansi) - ) - rows[12] = "" - rows[13] = _row("Overlap", "yes" if overlap else "no", cursor == 1, bar_width) - rows[height - 3] = thin - rows[height - 2] = _c( - " Up/Down select Left/Right change Enter start Esc defaults", - _DIM, on=ansi) - rows[height - 1] = rule - - if ansi: - parts = ["\033[?25l\033[?7l\033[H\033[J"] - for r, line in enumerate(rows, start=1): - parts.append(f"\033[{r};1H\033[2K{line}") - parts.append("\033[1;1H") - sys.stdout.write("".join(parts)) - else: - sys.stdout.write("\n".join(rows)) - sys.stdout.flush() - - try: - draw() - while True: - key = _read_key(0.1) - if key is None: - continue - if key == "Esc": - result = SetupConfig(jobs=default_jobs, overlap=bool(default_overlap)) - break - if key == "Enter": - result = SetupConfig(jobs=jobs, overlap=overlap) - break - if key in ("Up", "Down", "Tab"): - cursor = (cursor + (1 if key in ("Down", "Tab") else -1)) % len(fields) - draw() - elif key in ("Left", "["): - if cursor == 0: - jobs = max(lo, jobs - 1) - else: - overlap = not overlap - draw() - elif key in ("Right", "]", "/", "Space"): - if cursor == 0: - jobs = min(hi, jobs + 1) - else: - overlap = not overlap - draw() - finally: - # Setup draws on the main buffer (not alt screen). Clear it so the board / shell - # does not come back to a full-screen leftover form. - restore_console(ansi=ansi) - return result if result is not None else SetupConfig(jobs=default_jobs, overlap=bool(default_overlap)) - - -class StageConsole: - """Ring buffer + on-disk log for one build stage.""" - - def __init__(self, name: str, log_path: str, maxlen: int = 2000): - self.name = name - self.log_path = log_path - self.lines: deque[str] = deque(maxlen=maxlen) - self.status = "idle" # idle | running | done | failed - self._lock = threading.Lock() - os.makedirs(os.path.dirname(log_path) or ".", exist_ok=True) - self._file = open(log_path, "a", encoding="utf-8", errors="replace", newline="\n") - - def close(self) -> None: - with self._lock: - try: - self._file.close() - except Exception: - pass - - def write_line(self, line: str) -> None: - line = line.rstrip("\r\n") - with self._lock: - self.lines.append(line) - try: - self._file.write(line + "\n") - self._file.flush() - except OSError: - pass - - def snapshot(self, n: int) -> list[str]: - with self._lock: - if n <= 0: - return list(self.lines) - return list(self.lines)[-n:] - - def line_count(self) -> int: - with self._lock: - return len(self.lines) - - -class _BoardStream: - """Catch stray print()/stdout writes and fold them into the active stage pane.""" - - def __init__(self, board: "LeonidaBoard", real): - self._board = board - self._real = real - self._buf = "" - self._lock = threading.Lock() - - def write(self, data): - if not isinstance(data, str): - data = str(data) - if self._board._is_drawing(): - return self._real.write(data) - with self._lock: - self._buf += data - while "\n" in self._buf: - line, self._buf = self._buf.split("\n", 1) - line = line.rstrip("\r") - if line: - self._board.write(current_stage(), line) - return len(data) - - def flush(self): - with self._lock: - leftover = self._buf - self._buf = "" - if leftover and not self._board._is_drawing(): - self._board.write(current_stage(), leftover.rstrip("\r")) - return self._real.flush() - - def fileno(self): - return self._real.fileno() - - def isatty(self): - return False - - @property - def encoding(self): - return getattr(self._real, "encoding", "utf-8") - - -class LeonidaBoard: - """LEONIDA-branded live view with key-switchable stage panes.""" - - # Fixed chrome (1-based): rows 1–13 header (rule, banner, summary, tabs, pane-top rule); - # PANE_TOP is the first log row; last 3 rows are thin / help / rule. - PANE_TOP = 14 - - def __init__(self, stages: list[str], log_dir: str): - self.stages = [s for s in STAGE_ORDER if s in stages] or list(stages) - self.log_dir = log_dir - self.consoles = { - name: StageConsole(name, os.path.join(log_dir, f"{name}.log")) - for name in self.stages - } - self.selected = 0 - self.summary = "build starting" - # Lines scrolled up from the live tail (0 = follow newest output). - self.scroll = 0 - self._ansi = enable_ansi() - self._lock = threading.Lock() - self._stop = threading.Event() - self._thread: threading.Thread | None = None - self._dirty = True - self._token = None - self._alt_screen = False - self._tls = threading.local() - self._real_out = sys.stdout - self._real_err = sys.stderr - self._proxy_out = _BoardStream(self, self._real_out) - self._proxy_err = _BoardStream(self, self._real_err) - - def _is_drawing(self) -> bool: - return bool(getattr(self._tls, "drawing", False)) - - def __enter__(self): - global _active_board - install_interrupt_handlers() - self._token = _board_ref.set(self) - _active_board = self - sys.stdout = self._proxy_out - sys.stderr = self._proxy_err - if self._ansi: - try: - # Alt screen + hide cursor + disable autowrap (wrap is what pushes logs "below"). - # 1007: wheel → Up/Down in alt screen; 1000/1006: SGR mouse wheel reports. - self._raw("\033[?1049h\033[?25l\033[?7l\033[?1007h\033[?1000h\033[?1006h") - self._alt_screen = True - except OSError: - self._alt_screen = False - _nt_arm_mouse_input() - self._thread = threading.Thread(target=self._loop, name="leonida-board", daemon=True) - self._thread.start() - self._redraw(force=True) - return self - - def __exit__(self, exc_type, exc, tb): - global _active_board - self.stop() - sys.stdout = self._real_out - sys.stderr = self._real_err - # Leave alt screen (if we entered it) and clear the main buffer. Without the clear, - # Windows Terminal shows the pre-board main buffer (setup form / leaked cmake lines). - restore_console(self._real_out, ansi=self._ansi, leave_alt=self._alt_screen) - self._alt_screen = False - if self._token is not None: - _board_ref.reset(self._token) - if _active_board is self: - _active_board = None - for c in self.consoles.values(): - c.close() - print(f"LEONIDA: stage logs in {self.log_dir}", flush=True) - return False - - def _raw(self, text: str) -> None: - self._tls.drawing = True - try: - self._real_out.write(text) - self._real_out.flush() - finally: - self._tls.drawing = False - - def stop(self) -> None: - self._stop.set() - if self._thread and self._thread.is_alive(): - self._thread.join(timeout=2.0) - - def set_status(self, name: str, status: str) -> None: - c = self.consoles.get(name) - if c is None: - return - with self._lock: - c.status = status - self._dirty = True - - def set_summary(self, text: str) -> None: - with self._lock: - self.summary = text - self._dirty = True - - def write(self, stage: str | None, line: str) -> None: - if stage and stage in self.consoles: - self.consoles[stage].write_line(line) - visible = stage - elif self.stages: - self.consoles[self.stages[self.selected]].write_line(line) - visible = self.stages[self.selected] - else: - return - with self._lock: - if visible == self.stages[self.selected]: - self._dirty = True - - def note(self, line: str) -> None: - """Build-level message: update summary; do not spam the log pane.""" - with self._lock: - self.summary = line - self._dirty = True - - def _loop(self) -> None: - while not self._stop.is_set(): - while True: - key = _read_key(0.0) - if not key: - break - self._handle_key(key) - # Always repaint: child processes that inherit the console can scroll the - # alt buffer between ticks; a dirty-only redraw never heals that. - self._redraw(force=True) - self._stop.wait(0.08) - - def _handle_key(self, key: str) -> None: - n = len(self.stages) - if n == 0: - return - with self._lock: - if key in ("Tab", "Right"): - self.selected = (self.selected + 1) % n - self.scroll = 0 - self._dirty = True - elif key == "Left": - self.selected = (self.selected - 1) % n - self.scroll = 0 - self._dirty = True - elif key in "1234": - idx = int(key) - 1 - if idx < n: - self.selected = idx - self.scroll = 0 - self._dirty = True - elif key in ("Up", "Down", "PageUp", "PageDown", "Home", "End"): - # Pane height is measured at redraw; use a conservative step here. - _, height = term_size() - pane_h = max(1, height - self.PANE_TOP - 2) - if key == "Up": - self.scroll += 1 - elif key == "Down": - self.scroll = max(0, self.scroll - 1) - elif key == "PageUp": - self.scroll += pane_h - elif key == "PageDown": - self.scroll = max(0, self.scroll - pane_h) - elif key == "Home": - self.scroll = 10**9 # clamped in _redraw against buffer length - elif key == "End": - self.scroll = 0 - self._dirty = True - - def _status_style(self, status: str) -> tuple[str, tuple[str, ...]]: - if status == "running": - return "[~]", (_YELLOW,) - if status == "done": - return "[+]", (_GREEN,) - if status == "failed": - return "[x]", (_RED,) - return "[ ]", (_DIM,) - - def _redraw(self, force: bool = False) -> None: - with self._lock: - if not force and not self._dirty: - return - self._dirty = False - selected = self.selected - summary = self.summary - scroll = self.scroll - stages = list(self.stages) - statuses = {n: self.consoles[n].status for n in stages} - if not stages: - return - - width, height = term_size() - # Last 3 rows: thin, help, rule. Pane is everything from PANE_TOP through the row above. - footer_thin = height - 2 # 1-based row of the footer thin rule - pane_bottom = footer_thin - 1 - pane_top = min(self.PANE_TOP, pane_bottom) - pane_h = max(1, pane_bottom - pane_top + 1) - - name = stages[selected] - log_lines = self.consoles[name].snapshot(0) - if not log_lines: - log_lines = ["(no output yet)"] - wrapped = wrap_log_lines(log_lines, max(1, width - 2), max_rows=0) - max_scroll = max(0, len(wrapped) - pane_h) - if scroll > max_scroll: - scroll = max_scroll - with self._lock: - self.scroll = scroll - end = len(wrapped) - scroll - start = max(0, end - pane_h) - body = wrapped[start:end] - body = [""] * (pane_h - len(body)) + body - - ansi = self._ansi - rule = _c("=" * width, _DIM, _CYAN, on=ansi) - thin = _c("-" * width, _DIM, on=ansi) - tabs = [] - for i, s in enumerate(stages): - mark, style = self._status_style(statuses[s]) - label = f" {mark} {s} " - if i == selected: - tabs.append(_c(label, _BOLD, _REVERSE, on=ansi)) - else: - tabs.append(_c(label, *style, on=ansi)) - - banner = [_c(line[:width].ljust(width), _BOLD, _CYAN, on=ansi) for line in LEONIDA_BANNER] - scroll_hint = " Up/Down/wheel scroll" if scroll else "" - help_line = _c( - (f" Left/Right / Tab / 1-{len(stages)} stage" - f"{scroll_hint} End live logs: {self.log_dir}")[:width].ljust(width), - _DIM, on=ansi) - - # Exact height rows — never emit more lines than the terminal has (avoids scroll). - rows = [""] * height - rows[0] = rule - if height > 1: - rows[1] = "" - for i, line in enumerate(banner): - idx = 2 + i - if idx < height: - rows[idx] = line - if 7 < height: - rows[7] = "" - if 8 < height: - rows[8] = _c(f" {summary}"[:width].ljust(width), _BOLD, _WHITE, on=ansi) - if 9 < height: - rows[9] = "" - if 10 < height: - # Join tabs as-is (ANSI codes); wrap is disabled so overflow cannot scroll. - rows[10] = " " + " ".join(tabs) - if 11 < height: - rows[11] = "" - if 12 < height and pane_top > 13: - rows[12] = thin - for i, ln in enumerate(body): - row = pane_top - 1 + i # 0-based - if 0 <= row < footer_thin - 1: - rows[row] = (" " + ln) if ln else "" - if 0 <= footer_thin - 1 < height: - rows[footer_thin - 1] = thin - if footer_thin < height: - rows[footer_thin] = help_line - if footer_thin + 1 < height: - rows[footer_thin + 1] = rule - - try: - if ansi: - parts = ["\033[H\033[J"] - for r, line in enumerate(rows[:height], start=1): - # Clear the row then write — no newlines, so the terminal cannot scroll. - parts.append(f"\033[{r};1H\033[2K{line}") - # Park at home (cursor hidden). Parking in the pane let leaked console - # writes advance downward until they scrolled past the frame. - parts.append("\033[1;1H") - self._raw("".join(parts)) - else: - # No trailing newline: height lines already fill the viewport. - self._raw("\n".join(rows[:height])) - except OSError: - pass - - -def capture_popen_kwargs() -> dict: - """Popen kwargs that fold a child's output into the board instead of the console. - - On Windows, cmake/ninja/MSBuild often WriteConsole past a piped stdout when they still - have a console handle — that is the brief flash on top of the LEONIDA frame. CREATE_NO_WINDOW - removes the console handle so those tools fall back to the pipe. - """ - kw: dict = { - "stdout": subprocess.PIPE, - "stderr": subprocess.STDOUT, - "text": True, - "errors": "replace", - } - if os.name == "nt": - kw["creationflags"] = subprocess.CREATE_NO_WINDOW - return kw - - -def pump_process(proc, stage: str | None, board: LeonidaBoard | None) -> int: - """Read proc.stdout line-by-line into the stage console; return exit code.""" - register_live_process(proc) - try: - stream = proc.stdout - if stream is not None: - while True: - if board is not None and getattr(board, "_stop", None) is not None and board._stop.is_set(): - kill_live_processes() - break - raw = stream.readline() - if raw == "" or raw == b"": - break - if isinstance(raw, bytes): - line = raw.decode("utf-8", errors="replace") - else: - line = raw - # Ninja status uses \\r; treat each chunk as a line so progress is visible. - line = line.replace("\r", "\n").rstrip("\n") - if not line: - continue - for piece in line.split("\n"): - piece = piece.strip() - if not piece: - continue - if board is not None: - board.write(stage, piece) - else: - print(piece, flush=True) - try: - stream.close() - except OSError: - pass - try: - return proc.wait(timeout=0.5) - except subprocess.TimeoutExpired: - kill_live_processes() - try: - return proc.wait(timeout=2.0) - except subprocess.TimeoutExpired: - return proc.poll() if proc.poll() is not None else 1 - finally: - unregister_live_process(proc) diff --git a/tools/mad_denorm_probe.py b/tools/mad_denorm_probe.py deleted file mode 100644 index 860f6b615..000000000 --- a/tools/mad_denorm_probe.py +++ /dev/null @@ -1,342 +0,0 @@ -r"""Measure RDNA1 f32 denormal flush in v_mad_f32, v_mac_f32 and v_mad_legacy_f32 (SHADER-340). - -docs/design.md ("Denormal flush in v_mad_f32, v_mac_f32, v_mad_legacy_f32") states that -these three GFX10.1 instructions have no f32 denormal support: subnormal operands, rounded -products and results flush to signed zero regardless of MODE, and the flush runs after -output modifiers (`div:2`/`mul:2`/`mul:4`/`clamp`). Both claims were inferred from LLVM's -`SITargetLowering::isFMADLegal` and unmeasured on hardware (GFX10.3+ dropped these opcodes). - -Each case tests one of: - input subnormal operand (src0, src1, src2 / accumulator) - product two normal operands whose rounded product is subnormal - result normal operands and product whose sum is subnormal - omod output modifier (`div:2`, `mul:2`, `mul:4`, `clamp`) crossing the subnormal boundary - legacy v_mad_legacy_f32 `0 * anything -> +0` with subnormal multipliers - control normal values, signed zeros, infinities, NaNs - -Sides: - translator tools/rdna2spirv.py -> tests/semantic/spirv_mini_interp.py, on the CPU. - hw the native instruction on an AMD GPU (tools/hw_oracle: HIP on Windows, - libdrm on Linux), wave32 and wave64, across five MODE combinations - including `denorm32=3` (f32 denormals kept). - - python -I tools/mad_denorm_probe.py # translator side only - python -I tools/mad_denorm_probe.py --oracle hw # + the AMD GPU in this machine - -Exit code: 0 when every hardware word equals the translator's, 1 when one differs, 2 on a -harness error, 77 when the hardware oracle is unavailable. Nothing here reads game files. -Usage: `python -I tools/mad_denorm_probe.py --help` lists the options. -""" -import argparse -import os -import struct -import sys -import tempfile -import warnings - -HERE = os.path.dirname(os.path.abspath(__file__)) -ROOT = os.path.dirname(HERE) -sys.dont_write_bytecode = True -TOOLS_DIR = os.environ.get("LEONIDA_TOOLS_DIR") or HERE -for p in (TOOLS_DIR, os.path.join(ROOT, "tests", "semantic")): - if p not in sys.path: - sys.path.insert(0, p) - -import rdna2spirv # noqa: E402 -import spirv_mini_interp # noqa: E402 - -STUB_DXBC = b"DXBC" + bytes(24) + struct.pack(" +0"), - Case("input", "v_mad_f32", NEG_SUBNORM_MIN, ONE, POS_ZERO, "src0 -subnorm + +0 -> +0"), - Case("input", "v_mad_f32", NEG_SUBNORM_MIN, ONE, NEG_ZERO, "src0 -subnorm + -0 -> -0"), - Case("input", "v_mad_f32", ONE, SUBNORM_MAX, POS_ZERO, "src1 +subnorm -> +0"), - Case("input", "v_mad_f32", ONE, NEG_SUBNORM_MIN, NEG_ZERO, "src1 -subnorm + -0 -> -0"), - Case("input", "v_mad_f32", POS_ZERO, POS_ZERO, SUBNORM_HALF, "src2 +subnorm -> +0"), - Case("input", "v_mad_f32", NEG_ZERO, ONE, NEG_SUBNORM_HALF, "(-0)*1 + (-subnorm) -> -0"), - Case("input", "v_mad_f32", SUBNORM_MIN, ONE, POS_ZERO, "-src0(+subnorm) + +0 -> +0", neg_a=True), - Case("input", "v_mad_f32", SUBNORM_MIN, ONE, NEG_ZERO, "-src0(+subnorm) + -0 -> -0", neg_a=True), - Case("input", "v_mac_f32", SUBNORM_MIN, ONE, SUBNORM_MIN, "mac subnorm src0, acc -> +0"), - Case("input", "v_mac_f32", NEG_SUBNORM_MIN, ONE, NEG_SUBNORM_MIN, "mac -subnorm src0, acc -> -0"), - Case("input", "v_mac_f32", POS_ZERO, POS_ZERO, SUBNORM_HALF, "mac subnorm acc -> +0"), - Case("input", "v_mac_f32", ONE, ONE, SUBNORM_MIN, "mac 1*1 + subnorm -> 1.0"), - Case("input", "v_mad_legacy_f32", POS_ZERO, POS_ZERO, SUBNORM_HALF, "legacy subnorm src2 -> +0"), - Case("input", "v_mad_legacy_f32", ONE, ONE, NEG_SUBNORM_HALF, "legacy 1*1 + (-subnorm) -> 1.0"), - - # Normal operands whose rounded product is subnormal - Case("product", "v_mad_f32", FLT_MIN, HALF, FLT_MIN, "2^-126 * 0.5 + 2^-126 (prod flushed)"), - Case("product", "v_mac_f32", FLT_MIN, HALF, FLT_MIN, "mac 2^-126 * 0.5 + 2^-126"), - Case("product", "v_mad_legacy_f32", FLT_MIN, HALF, FLT_MIN, "legacy 2^-126 * 0.5 + 2^-126"), - Case("product", "v_mad_f32", 0x17800000, 0x1C800000, SUBNORM_MIN, "2^-80 * 2^-70 + 2^-149 -> +0"), - Case("product", "v_mad_f32", 0x17800000, 0x21800000, 0x00000200, "2^-80 * 2^-59 + 2^-140 -> +0"), - Case("product", "v_mad_f32", NEG_FLT_MIN, HALF, NEG_ZERO, "-2^-126 * 0.5 + -0 -> -0"), - Case("product", "v_mac_f32", NEG_FLT_MIN, HALF, NEG_ZERO, "mac -2^-126 * 0.5 + -0 -> -0"), - - # Normal operands and normal product whose sum is subnormal - Case("result", "v_mad_f32", FLT_MIN_1_5, ONE, NEG_FLT_MIN, "1.5*2^-126 - 2^-126 -> +0"), - Case("result", "v_mad_f32", NEG_FLT_MIN_1_5, ONE, FLT_MIN, "-1.5*2^-126 + 2^-126 -> -0"), - Case("result", "v_mac_f32", FLT_MIN_1_5, ONE, NEG_FLT_MIN, "mac 1.5*2^-126 - 2^-126 -> +0"), - Case("result", "v_mac_f32", NEG_FLT_MIN_1_5, ONE, FLT_MIN, "mac -1.5*2^-126 + 2^-126 -> -0"), - Case("result", "v_mad_legacy_f32", FLT_MIN_1_5, ONE, NEG_FLT_MIN, "legacy 1.5*2^-126 - 2^-126 -> +0"), - Case("result", "v_mad_legacy_f32", NEG_FLT_MIN_1_5, ONE, FLT_MIN, "legacy -1.5*2^-126 + 2^-126 -> -0"), - - # Output modifiers (div:2, mul:2, mul:4, clamp) vs flush order - Case("omod", "v_mad_f32", FLT_MIN, ONE, POS_ZERO, "FLT_MIN div:2 -> +0", mods="div:2"), - Case("omod", "v_mad_f32", NEG_FLT_MIN, ONE, NEG_ZERO, "-FLT_MIN div:2 -> -0", mods="div:2"), - Case("omod", "v_mad_f32", NEG_FLT_MIN, ONE, NEG_ZERO, "-FLT_MIN clamp div:2 -> +0", mods="clamp div:2"), - Case("omod", "v_mad_f32", FLT_MIN_1_5, ONE, NEG_FLT_MIN, "(1.5*2^-126 - 2^-126) mul:2", mods="mul:2"), - Case("omod", "v_mad_f32", FLT_MIN_1_5, ONE, NEG_FLT_MIN, "(1.5*2^-126 - 2^-126) mul:4", mods="mul:4"), - Case("omod", "v_mad_f32", SUBNORM_HALF, ONE, POS_ZERO, "subnorm_half mul:2 (input flushed)", mods="mul:2"), - Case("omod", "v_mad_legacy_f32", FLT_MIN, ONE, POS_ZERO, "legacy FLT_MIN div:2 -> +0", mods="div:2"), - Case("omod", "v_mad_legacy_f32", FLT_MIN_1_5, ONE, NEG_FLT_MIN, "legacy (1.5*2^-126 - 2^-126) mul:2", mods="mul:2"), - - # Legacy 0 * anything -> +0 after subnormal input flush - Case("legacy", "v_mad_legacy_f32", SUBNORM_MIN, POS_INF, NEG_ONE, "subnorm * +inf + -1 -> -1"), - Case("legacy", "v_mad_legacy_f32", NEG_SUBNORM_MIN, POS_INF, ONE, "-subnorm * +inf + 1 -> 1"), - Case("legacy", "v_mad_legacy_f32", SUBNORM_MIN, QNAN, ONE, "subnorm * qNaN + 1 -> 1"), - Case("legacy", "v_mad_legacy_f32", NEG_SUBNORM_MIN, SNAN, TWO, "-subnorm * sNaN + 2 -> 2"), - Case("legacy", "v_mad_legacy_f32", SUBNORM_MIN, NEG_SUBNORM_MIN, NEG_ZERO, "subnorm * -subnorm + -0 -> +0"), - - # Control cases - Case("control", "v_mad_f32", TWO, THREE, FOUR, "2*3 + 4 = 10"), - Case("control", "v_mac_f32", TWO, THREE, FOUR, "mac 2*3 + 4 = 10"), - Case("control", "v_mad_legacy_f32", TWO, THREE, FOUR, "legacy 2*3 + 4 = 10"), - Case("control", "v_mad_f32", NEG_ZERO, TWO, NEG_ZERO, "(-0)*2 + (-0) -> -0"), - Case("control", "v_mad_legacy_f32", NEG_ZERO, TWO, NEG_ZERO, "legacy (-0)*2 + (-0) -> +0"), - Case("control", "v_mad_f32", POS_INF, ONE, NEG_INF, "+inf + (-inf) -> NaN"), - Case("control", "v_mad_f32", QNAN, ONE, ONE, "qNaN pass-through"), -) - - -def _is_nan(word): - return (word & 0x7F800000) == 0x7F800000 and (word & 0x007FFFFF) != 0 - - -def _equal_word(got, want): - if _is_nan(got) and _is_nan(want): - return True - return got == want - - -def _insn_lines(case, dst="v0"): - s0 = "-v1" if case.neg_a else "v1" - mod_s = f" {case.mods}" if case.mods else "" - if case.op == "v_mac_f32": - return [ - f"v_mov_b32 v1, 0x{case.a:x}", - f"v_mov_b32 v2, 0x{case.b:x}", - f"v_mov_b32 {dst}, 0x{case.c:x}", - f"{case.op} {dst}, {s0}, v2{mod_s}", - ] - return [ - f"v_mov_b32 v1, 0x{case.a:x}", - f"v_mov_b32 v2, 0x{case.b:x}", - f"v_mov_b32 v3, 0x{case.c:x}", - f"v_mov_b32 {dst}, 0x{SENTINEL:x}", - f"{case.op} {dst}, {s0}, v2, v3{mod_s}", - ] - - -# ---- the translator, on the CPU ---- - -def _translate(work, name, text): - os.makedirs(os.path.join(work, "disasm"), exist_ok=True) - src = os.path.join(work, "disasm", name + ".s") - with open(src, "w", encoding="utf-8", newline="\n") as f: - f.write(text) - with open(os.path.join(work, name + ".dxbc"), "wb") as f: - f.write(STUB_DXBC) - with warnings.catch_warnings(): - warnings.simplefilter("ignore", ResourceWarning) - return rdna2spirv.translate(src) - - -def ps_listing(case): - # Bit-exact export: spirv_mini_interp keeps raw f32 bit patterns on %out_mrt0. - lines = _insn_lines(case, dst="v0") + ["exp mrt0 v0, v0, v0, v0 done vm", "s_endpgm"] - return "; mad_denorm_probe\n" + "".join(f"\t{ln}\n" for ln in lines) - - -def run_translator(case_list=CASES): - out = [] - with tempfile.TemporaryDirectory(prefix="mad_denorm_probe_") as work: - for i, c in enumerate(case_list): - spv = _translate(work, f"ps_mad_denorm_{i}", ps_listing(c)) - out.append(spirv_mini_interp.run_fragment(spv)["%out_mrt0"][0]) - return out - - -# ---- the hardware ---- - -def hw_lines(case): - return _insn_lines(case, dst="v8") + [ - "v_mov_b32 v20, 0", - "global_store_dword v20, v8, s[2:3]", - "s_endpgm", - ] - - -def run_hw(oracle, case_list, wave, mode): - from hw_oracle import asm - got = oracle.run([asm.Kernel(hw_lines(c), wave, 1, 1, raw=True, mode=mode) for c in case_list], words=1) - return [w if isinstance(w, str) else w[0] for w in got] - - -def check_mode_denorm_effect(oracle): - """Sanity check: MODE.denorm32=3 actually keeps a subnormal product on v_mul_f32 while MODE.denorm32=0 flushes it.""" - from hw_oracle import asm - prog = [ - f"v_mov_b32 v1, 0x{FLT_MIN:x}", - f"v_mov_b32 v2, 0x{HALF:x}", - "v_mul_f32 v8, v1, v2", - "v_mov_b32 v20, 0", - "global_store_dword v20, v8, s[2:3]", - "s_endpgm", - ] - kernels = [ - asm.Kernel(prog, 32, 1, 1, raw=True, mode=GAME_MODE), - asm.Kernel(prog, 32, 1, 1, raw=True, mode=dict(GAME_MODE, denorm32=3)), - ] - got = oracle.run(kernels, words=1) - return [w if isinstance(w, str) else w[0] for w in got] - - -def _has_scale_omod(mods): - return any(m.startswith(("mul:", "div:")) for m in mods.split()) - - -def main(argv=None): - ap = argparse.ArgumentParser(description=__doc__.split("\n", 1)[0]) - ap.add_argument("--oracle", default="translator", help="translator (default) or translator,hw / hw") - ap.add_argument("--hw-arch", help="override the hardware architecture (LEONIDA_HW_ARCH)") - a = ap.parse_args(argv) - sides = {s.strip() for s in a.oracle.split(",") if s.strip()} - {"translator"} - if sides - {"hw"}: - ap.error(f"unknown --oracle side(s): {', '.join(sorted(sides - {'hw'}))}") - try: - want = run_translator(CASES) - # Under MODE.IEEE=1, AMD hardware ignores VOP3 mul:2/mul:4/div:2 (docs/design.md). - no_scale_cases = [ - Case(c.group, c.op, c.a, c.b, c.c, c.what, mods=("clamp" if "clamp" in c.mods.split() else ""), neg_a=c.neg_a) - for c in CASES - ] - want_no_scale = run_translator(no_scale_cases) - except Exception as e: # noqa: BLE001 - harness error - print(f"translator side failed: {e}") - return 2 - groups = ("input", "product", "result", "omod", "legacy", "control") - print(f"translator: {len(CASES)} cases across {len(groups)} groups") - if "hw" not in sides: - for c, w in zip(CASES, want): - print(f" [{c.group:7s}] {c.op:16s} {c.what:38s} -> 0x{w:08x}") - return 0 - from hw_oracle import asm, runner - try: - oracle = runner.open_oracle(arch=a.hw_arch) - except runner.Unavailable as e: - print(f"hardware oracle unavailable: {e}") - return 77 - # The probe's three opcodes are GFX10.1 only: on gfx1030 and later the assembler rejects every kernel, which is - # "this GPU can't run it" (a skip), not a harness error. - why = asm.valu_skip_reason("v_mad_f32", oracle.arch) - if why: - oracle.close() - print(f"hardware oracle unavailable: {why}") - return 77 - status = 0 - try: - print(f"hardware oracle: {oracle.device} ({oracle.arch})") - sanity = check_mode_denorm_effect(oracle) - if any(isinstance(x, str) for x in sanity): - print(f"MODE denorm32 sanity error: {sanity}") - return 2 - print(f"MODE sanity (v_mul_f32 FLT_MIN * 0.5): denorm32=0 -> 0x{sanity[0]:08x}, denorm32=3 -> 0x{sanity[1]:08x}") - if sanity != [POS_ZERO, SUBNORM_HALF]: - print(f"MODE denorm32 sanity failed: expected [0x{POS_ZERO:08x}, 0x{SUBNORM_HALF:08x}], got {[hex(x) for x in sanity]}") - return 2 - for wave in (32, 64): - for name, mode in MODES: - got = run_hw(oracle, CASES, wave, mode) - errors = [g for g in got if isinstance(g, str)] - if errors: - print(f"wave{wave} {name}: harness error: {errors[0]}") - return 2 - expected = [ - (want_no_scale[i] if (mode["ieee"] == 1 and _has_scale_omod(c.mods)) else want[i]) - for i, c in enumerate(CASES) - ] - diffs = [(c, g, w) for c, g, w in zip(CASES, got, expected) if not _equal_word(g, w)] - per_group = { - gr: ( - sum(1 for c, g, w in zip(CASES, got, expected) if c.group == gr and _equal_word(g, w)), - sum(1 for c in CASES if c.group == gr), - ) - for gr in groups - } - summary = ", ".join(f"{gr} {ok}/{tot}" for gr, (ok, tot) in per_group.items()) - note = " [IEEE=1 ignores omod]" if mode["ieee"] == 1 else "" - print(f"wave{wave} {name}: {len(CASES) - len(diffs)}/{len(CASES)} match ({summary}){note}") - for c, g, w in diffs: - print(f" DIFF [{c.group}] {c.op} ({c.what}): hw 0x{g:08x}, expected 0x{w:08x}") - if diffs: - status = 1 - finally: - oracle.close() - return status - - -if __name__ == "__main__": - try: - sys.stdout.reconfigure(errors="replace") - except (AttributeError, ValueError, OSError): - pass - sys.exit(main()) diff --git a/tools/manifest.py b/tools/manifest.py deleted file mode 100644 index 30cdc7851..000000000 --- a/tools/manifest.py +++ /dev/null @@ -1,287 +0,0 @@ -"""SHA-256 manifest of a game folder, so later copies (and the exe, when it arrives) can be checked. - -Usage: - python -I manifest.py create [--out FILE] [--jobs N] - python -I manifest.py verify [--manifest FILE] [--jobs N] - -Files are hashed with up to --jobs threads (default: half the CPU count; 1 = serial). -The manifest itself is excluded when its path is inside the scanned folder. -On Windows it lowers its own priority to BelowNormal so the PC stays usable. -""" -import argparse -import hashlib -import json -import os -import sys -import tempfile -import time -from concurrent.futures import ThreadPoolExecutor, as_completed - -# -I keeps the script directory off sys.path, so add it explicitly before importing the sibling module. -sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) -from report_paths import same_report_path # noqa: E402 - -CHUNK = 8 * 1024 * 1024 -DEFAULT = os.path.join(os.path.dirname(__file__), "..", "reports", "manifest.json") - - -class ManifestError(Exception): - """An input or manifest error that the CLI reports without a traceback.""" - - -def default_jobs() -> int: - return max(1, (os.cpu_count() or 2) // 2) - - -def positive_int(text: str) -> int: - try: - value = int(text) - except ValueError: - raise argparse.ArgumentTypeError(f"invalid int value: {text!r}") from None - if value < 1: - raise argparse.ArgumentTypeError("must be at least 1") - return value - - -def below_normal() -> None: - if os.name == "nt": - import ctypes - from ctypes import wintypes - - k32 = ctypes.windll.kernel32 - k32.GetCurrentProcess.argtypes = () - k32.GetCurrentProcess.restype = wintypes.HANDLE - k32.SetPriorityClass.argtypes = (wintypes.HANDLE, wintypes.DWORD) - k32.SetPriorityClass.restype = wintypes.BOOL - k32.SetPriorityClass(k32.GetCurrentProcess(), 0x00004000) # BELOW_NORMAL_PRIORITY_CLASS - - -def _file_stamp(st: os.stat_result) -> tuple[int, int, int]: - return st.st_size, st.st_mtime_ns, st.st_ctime_ns - - -def _hash_file(path: str, *, expected_size: int | None = None) -> tuple[int, str]: - """Return the size and digest of the same open file, or fail if it changes.""" - h = hashlib.sha256() - with open(path, "rb", buffering=0) as f: - before = os.fstat(f.fileno()) - size = before.st_size - if expected_size is not None and size != expected_size: - raise ManifestError(f"{path}: file size changed before hashing") - remaining = size - if remaining: - # One buffer for the whole file: f.read() made a new CHUNK-sized bytes object while the last one was - # still referenced, so each worker held two chunks at its peak. - with memoryview(bytearray(min(CHUNK, remaining))) as buf: - while remaining: - count = f.readinto(buf[:remaining]) - if not count: - break - h.update(buf[:count]) - remaining -= count - # Compare timestamps from the same handle. Windows can report different times by path. - # Compare the path by identity so a replacement of the open file is detected too. - if (remaining or _file_stamp(os.fstat(f.fileno())) != _file_stamp(before) - or not os.path.samestat(before, os.stat(path))): - raise ManifestError(f"{path}: file changed while hashing") - return size, h.hexdigest() - - -def sha256(path: str, *, expected_size: int | None = None) -> str: - return _hash_file(path, expected_size=expected_size)[1] - - -def walk(game_dir: str, *, exclude=None): - def scan_failed(error: OSError) -> None: - raise error - - excluded_dir = excluded_name = None - if exclude is not None: - directory, name = os.path.split(os.path.abspath(exclude)) - excluded_dir = os.path.normcase(os.path.realpath(directory)) - excluded_name = os.path.normcase(name) - - # os.walk otherwise treats missing or unreadable directories as empty. - for root, _, files in os.walk(game_dir, onerror=scan_failed): - contains_manifest = excluded_dir is not None and os.path.normcase(os.path.realpath(root)) == excluded_dir - for name in sorted(files): - if contains_manifest and os.path.normcase(name) == excluded_name: - continue - p = os.path.join(root, name) - rel = os.path.relpath(p, game_dir) - if os.sep != "/": - rel = rel.replace(os.sep, "/") - if os.altsep and os.altsep != "/": - rel = rel.replace(os.altsep, "/") - yield rel, p - - -def create(game_dir: str, out: str, jobs: int = 1) -> int: - # walk() excludes the manifest path itself, so an existing game file named like --out would otherwise be - # hashed first and replaced by the manifest (os.replace below), leaving the recorded hash wrong. Allow only an - # existing file that already reads as a manifest (re-creating one in place); refuse any other existing target - # inside the folder and every hard link to a file that will be hashed. - if os.path.isdir(out): - raise ManifestError(f"--out is a folder, not a manifest file: {out}") - if os.path.isfile(out): - try: - inside = os.path.normcase(os.path.commonpath( - [os.path.realpath(game_dir), os.path.realpath(out)])) == os.path.normcase(os.path.realpath(game_dir)) - except ValueError: - inside = False - if inside: - try: - load_manifest(out) - except (ManifestError, OSError): - raise ManifestError(f"--out would overwrite the input {out}; " - "choose a manifest path that is not one of the hashed files") from None - files = sorted(walk(game_dir, exclude=out)) - for _rel, path in files: - if same_report_path(out, path): - raise ManifestError(f"--out would overwrite the input {path}; " - "choose a manifest path that is not one of the hashed files") - sizes = {path: os.path.getsize(path) for _, path in files} - total = sum(sizes.values()) - entries = {} - done = count = 0 - t0 = time.time() - - def finish(rel: str, size: int, digest: str) -> None: - nonlocal done, count - entries[rel] = {"size": size, "sha256": digest} - done += size - count += 1 - rate = done / max(time.time() - t0, 1e-6) / 2**20 - pct = done / total if total else 1.0 - # One line per completed file, printed only from the main thread. Completion order is not - # stable with threads, so this reports counts and bytes rather than coupling output to a path. - print(f"[{pct:6.1%}] {count}/{len(files)} files {rate:7.0f} MiB/s", flush=True) - - def work(rel: str, path: str) -> tuple[str, int, str]: - size, digest = _hash_file(path, expected_size=sizes[path]) - return rel, size, digest - - if jobs == 1: - for rel, p in files: - finish(*work(rel, p)) - else: - with ThreadPoolExecutor(max_workers=jobs) as pool: - futures = [pool.submit(work, rel, p) for rel, p in files] - for future in as_completed(futures): - finish(*future.result()) - - # Re-insert in walk order so the JSON is independent of which worker finished first. - entries = {rel: entries[rel] for rel, _ in files} - out_dir = os.path.dirname(os.path.abspath(out)) - os.makedirs(out_dir, exist_ok=True) - with tempfile.TemporaryDirectory(dir=out_dir) as staging: - staged = os.path.join(staging, "manifest.json") - with open(staged, "w", encoding="utf-8", newline="\n") as f: - json.dump({"created": time.strftime("%Y-%m-%d %H:%M:%S"), "files": entries}, f, indent=1) - os.replace(staged, out) - print(f"{len(entries)} files, {total / 2**30:.1f} GiB -> {out}") - return 0 - - -def _reject_duplicate_keys(pairs: list[tuple[str, object]]) -> dict: - out = {} - for key, value in pairs: - if key in out: - raise ValueError(f"duplicate key {key!r}") - out[key] = value - return out - - -def load_manifest(manifest: str) -> dict: - """The manifest's "files" table, checked entry by entry, so a damaged file is reported by name rather than - as a JSONDecodeError, KeyError or TypeError traceback halfway through verify.""" - with open(manifest, encoding="utf-8") as f: - try: - doc = json.load(f, object_pairs_hook=_reject_duplicate_keys) - except ValueError as error: # JSONDecodeError, duplicate keys, or UnicodeDecodeError for non-UTF-8 - raise ManifestError(f"{manifest} is not valid JSON ({error}); create it again") from None - files = doc.get("files") if isinstance(doc, dict) else None - if not isinstance(files, dict): - raise ManifestError(f"{manifest} has no \"files\" table; create it again") - for rel, info in files.items(): - if not (isinstance(info, dict) and type(info.get("size")) is int and isinstance(info.get("sha256"), str)): - raise ManifestError(f"{manifest}: entry {rel!r} needs an integer \"size\" and a \"sha256\" string") - return files - - -def verify(game_dir: str, manifest: str, jobs: int = 1) -> int: - want = load_manifest(manifest) - have = dict(walk(game_dir, exclude=manifest)) - if not want and have: - # A create that was cut short, or a mistyped --manifest, would otherwise print OK without checking a file. - raise ManifestError(f"{manifest} lists no files, but {game_dir} holds {len(have)}; create it again") - problems = {} - pending = [] - for rel, info in want.items(): - p = have.get(rel) - if p is None: - problems[rel] = "MISSING" - elif os.path.getsize(p) != info["size"]: - problems[rel] = "SIZE" - else: - pending.append((rel, p, info["sha256"].lower())) - - def hash_pending(rel: str, path: str) -> str: - return sha256(path, expected_size=want[rel]["size"]) - - if jobs == 1: - for rel, p, digest in pending: - if hash_pending(rel, p) != digest: - problems[rel] = "CHANGED" - else: - with ThreadPoolExecutor(max_workers=jobs) as pool: - futures = {pool.submit(hash_pending, rel, p): (rel, digest) for rel, p, digest in pending} - for future in as_completed(futures): - rel, digest = futures[future] - if future.result() != digest: - problems[rel] = "CHANGED" - - # Print in manifest order, not completion order, so the report is identical for any --jobs. - bad = 0 - for rel in want: - kind = problems.get(rel) - if kind: - print(f"{kind:<10}{rel}") - bad += 1 - for rel in sorted(set(have) - set(want)): - print(f"{'NEW':<10}{rel}") - print("OK" if not bad else f"{bad} problem(s)") - return 1 if bad else 0 - - -def add_jobs(parser: argparse.ArgumentParser) -> None: - parser.add_argument( - "--jobs", type=positive_int, default=default_jobs(), metavar="N", - help="hash up to N files concurrently with threads; 1 hashes serially " - "(default: half the CPU count = %(default)s)") - - -def main() -> int: - ap = argparse.ArgumentParser() - sub = ap.add_subparsers(dest="cmd", required=True) - c = sub.add_parser("create"); c.add_argument("game_dir"); c.add_argument("--out", default=DEFAULT) - add_jobs(c) - v = sub.add_parser("verify"); v.add_argument("game_dir"); v.add_argument("--manifest", default=DEFAULT) - add_jobs(v) - a = ap.parse_args() - below_normal() - try: - if a.cmd == "create": - return create(a.game_dir, a.out, a.jobs) - return verify(a.game_dir, a.manifest, a.jobs) - except (OSError, ManifestError) as error: - print(f"ERROR: {error}", file=sys.stderr) - return 2 - - -if __name__ == "__main__": - try: # a redirected stdout is strict ANSI code page under -I; write '?' for what it cannot encode - sys.stdout.reconfigure(errors="replace") - except (AttributeError, ValueError, OSError): - pass - sys.exit(main()) diff --git a/tools/manifest_verifier.py b/tools/manifest_verifier.py deleted file mode 100644 index 49a96f912..000000000 --- a/tools/manifest_verifier.py +++ /dev/null @@ -1,612 +0,0 @@ -"""Parallel SHA-256 manifest integrity verifier with progress reporting. - -Verifies a target directory against a SHA-256 JSON manifest. Files are verified -concurrently using up to --jobs threads (defaulting to half the CPU count; 1 = serial). -Live progress is reported continuously during verification. - ---cache FILE remembers files that already passed. if a file's size, times and id haven't changed it gets skipped, -so rechecking takes like a second instead of rereading the whole package. leave it off if you want every byte read. -it's a shortcut not proof, anyone who can edit the cache can make a broken copy pass, so keep it out of the game -folder and don't share it. - -Usage: - python -I manifest_verifier.py [--manifest FILE] [--jobs N] [--cache FILE] - [--quiet] [--verbose] [--json] [--strict] - python -I manifest_verifier.py verify [--manifest FILE] [--jobs N] [--cache FILE] -""" -from __future__ import annotations - -import argparse -from concurrent.futures import ThreadPoolExecutor, as_completed -from dataclasses import dataclass, field -import hashlib -import json -import os -import re -import stat -import sys -import time -from typing import Callable, Optional, TextIO - -CHUNK = 8 * 1024 * 1024 -DEFAULT_MANIFEST = os.path.join(os.path.dirname(__file__), "..", "reports", "manifest.json") -CACHE_VERSION = 1 -# don't cache files written this recently, a write in the same timestamp tick wouldn't change the stamp -# (FAT and some network shares only keep 2s times) -RACY_WINDOW_NS = 3_000_000_000 - - -def default_jobs() -> int: - return max(1, (os.cpu_count() or 2) // 2) - - -def positive_int(text: str) -> int: - try: - val = int(text) - except ValueError: - raise argparse.ArgumentTypeError(f"invalid int value: {text!r}") from None - if val < 1: - raise argparse.ArgumentTypeError("must be at least 1") - return val - - -def below_normal() -> None: - if os.name == "nt": - try: - import ctypes - from ctypes import wintypes - - k32 = ctypes.windll.kernel32 - k32.GetCurrentProcess.argtypes = () - k32.GetCurrentProcess.restype = wintypes.HANDLE - k32.SetPriorityClass.argtypes = (wintypes.HANDLE, wintypes.DWORD) - k32.SetPriorityClass.restype = wintypes.BOOL - k32.SetPriorityClass(k32.GetCurrentProcess(), 0x00004000) # BELOW_NORMAL_PRIORITY_CLASS - except Exception: - pass - - -class ManifestError(Exception): - """Raised when a manifest file is missing, unparseable, or invalid.""" - - -def _file_stamp(st: os.stat_result) -> tuple[int, int, int]: - return st.st_size, st.st_mtime_ns, st.st_ctime_ns - - -def sha256_file(path: str, chunk_size: int = CHUNK, *, expected_size: int | None = None) -> str: - """Hash a stable open file, refusing a resize, rewrite or path replacement during the read.""" - if chunk_size < 1: - raise ValueError("chunk_size must be at least 1") - h = hashlib.sha256() - with open(path, "rb", buffering=0) as f: - before = os.fstat(f.fileno()) - if expected_size is not None and before.st_size != expected_size: - raise OSError(f"{path}: file size changed before hashing") - remaining = before.st_size - if remaining: - with memoryview(bytearray(min(chunk_size, remaining))) as buf: - while remaining: - count = f.readinto(buf[:remaining]) - if not count: - break - h.update(buf[:count]) - remaining -= count - # Compare handle timestamps to each other; Windows may report different times by path. - # The final path stat checks that the name still refers to the same open file. - if (remaining or f.read(1) or _file_stamp(os.fstat(f.fileno())) != _file_stamp(before) - or not os.path.samestat(before, os.stat(path))): - raise OSError(f"{path}: file changed while hashing") - return h.hexdigest() - - -def _cache_key(abs_path: str) -> str: - return os.path.normcase(os.path.realpath(abs_path)) - - -def _change_time(path: str, st: os.stat_result) -> int: - # st_ctime on windows is creation time, so a rewrite with the old mtime put back wouldn't show up. - # NTFS ChangeTime moves on any write or metadata change, same job as ctime on linux - if os.name != "nt": - return st.st_ctime_ns - try: - import ctypes - import msvcrt - - info = (ctypes.c_longlong * 5)() # FILE_BASIC_INFO, ChangeTime is [3] - k32 = ctypes.windll.kernel32 - k32.GetFileInformationByHandleEx.argtypes = (ctypes.c_void_p, ctypes.c_int, ctypes.c_void_p, ctypes.c_ulong) - with open(path, "rb") as f: - if k32.GetFileInformationByHandleEx(msvcrt.get_osfhandle(f.fileno()), 0, info, ctypes.sizeof(info)): - return info[3] or st.st_ctime_ns # FAT has no change time - except (OSError, AttributeError, ImportError): - pass - return st.st_ctime_ns - - -def _cache_stamp(path: str, st: os.stat_result) -> list[int]: - # file id (st_dev, st_ino) catches a file swapped for another one with the same size and times - return [st.st_size, st.st_mtime_ns, _change_time(path, st), st.st_dev, st.st_ino] - - -def load_cache(path: str) -> dict[str, dict]: - """Loads the verify cache. missing or broken cache just counts as empty, never an error.""" - try: - with open(path, encoding="utf-8") as f: - doc = json.load(f) - if doc["version"] == CACHE_VERSION: - return {k: e for k, e in doc["files"].items() if isinstance(e, dict) and "stamp" in e and "sha256" in e} - except (OSError, ValueError, KeyError, TypeError, AttributeError): - pass - return {} - - -def save_cache(path: str, entries: dict[str, dict]) -> None: - """Saves the cache via a temp file + replace, so if it gets interrupted the old one is still there.""" - directory = os.path.dirname(os.path.abspath(path)) - if directory: - os.makedirs(directory, exist_ok=True) - tmp = path + ".tmp" - try: - with open(tmp, "w", encoding="utf-8", newline="\n") as f: - json.dump({"version": CACHE_VERSION, "files": dict(sorted(entries.items()))}, f, indent=1) - os.replace(tmp, path) - except BaseException: - try: - os.unlink(tmp) - except OSError: - pass - raise - - -def walk(target_dir: str, *, exclude: str | tuple[str, ...] | None = None): - """Yields (relative_path, absolute_path) using forward slashes, excluding the selected manifest (and cache).""" - def scan_failed(error: OSError) -> None: - raise error - - excluded: dict[str, set[str]] = {} - for path in (exclude,) if isinstance(exclude, str) else exclude or (): - if path is None: - continue - directory, name = os.path.split(os.path.abspath(path)) - excluded.setdefault(os.path.normcase(os.path.realpath(directory)), set()).add(os.path.normcase(name)) - - # os.walk otherwise treats missing or unreadable directories as empty. - for root, _, files in os.walk(target_dir, onerror=scan_failed): - dir_exclusions = excluded.get(os.path.normcase(os.path.realpath(root))) - for name in sorted(files): - if dir_exclusions and os.path.normcase(name) in dir_exclusions: - continue - abs_p = os.path.join(root, name) - rel_p = os.path.relpath(abs_p, target_dir).replace(os.sep, "/") - yield rel_p, abs_p - - -def load_manifest(path: str) -> dict[str, dict]: - """Loads and validates a manifest file. - - Supports: - {"files": {: {"size": , "sha256": }, ...}} - or flat: - {: {"size": , "sha256": }, ...} - In a flat manifest, `created`, `title`, `version` and `note` are metadata unless - their value is an explicit file object with a `sha256` field. - - Rejects repeated JSON keys and normalizes relative paths to forward - slashes and hashes to lowercase hex. - """ - try: - mode = os.stat(path).st_mode - except FileNotFoundError: - raise ManifestError(f"manifest file not found: {path}") from None - except OSError as err: - raise ManifestError(f"cannot read manifest {path}: {err}") from None - if not stat.S_ISREG(mode): - raise ManifestError(f"manifest path is not a regular file: {path}") - - def unique_object(pairs: list[tuple[str, object]]) -> dict[str, object]: - result: dict[str, object] = {} - for key, value in pairs: - if key in result: - raise ManifestError(f"{path}: duplicate JSON key {key!r}") - result[key] = value - return result - - try: - with open(path, encoding="utf-8") as f: - doc = json.load(f, object_pairs_hook=unique_object) - except ValueError as err: - raise ManifestError(f"{path} is not valid JSON ({err})") from None - except OSError as err: - raise ManifestError(f"cannot read manifest {path}: {err}") from None - - if not isinstance(doc, dict): - raise ManifestError(f"{path}: root must be a JSON object") - - nested = "files" in doc - if nested: - raw_files = doc["files"] - if not isinstance(raw_files, dict): - raise ManifestError(f"{path}: 'files' must be a JSON object") - else: - raw_files = doc - - entries: dict[str, dict] = {} - for raw_rel, info in raw_files.items(): - if (not nested and raw_rel in ("created", "title", "version", "note") - and not (isinstance(info, dict) and "sha256" in info)): - continue - rel = str(raw_rel).replace("\\", "/") - if rel in entries: - raise ManifestError(f"{path}: duplicate normalized path {rel!r}") - if isinstance(info, dict): - size = info.get("size") - digest = info.get("sha256") - if not isinstance(digest, str): - raise ManifestError(f"{path}: entry {rel!r} missing 'sha256' string") - if size is not None and not (isinstance(size, int) and not isinstance(size, bool) and size >= 0): - raise ManifestError(f"{path}: entry {rel!r} has invalid integer 'size'") - elif isinstance(info, str): - size, digest = None, info - else: - raise ManifestError(f"{path}: entry {rel!r} must be an object or digest string") - if re.fullmatch(r"[0-9a-fA-F]{64}", digest) is None: - raise ManifestError(f"{path}: entry {rel!r} needs a SHA-256 digest of 64 hexadecimal characters") - entries[rel] = {"size": size, "sha256": digest.lower()} - return entries - - -@dataclass -class ProgressInfo: - completed_files: int - total_files: int - completed_bytes: int - total_bytes: int - rate_mib: float - pct: float - rel_path: str - status: str - - -@dataclass -class ManifestReport: - passed: bool - total_manifest_files: int - matched: list[str] = field(default_factory=list) - missing: list[str] = field(default_factory=list) - size_mismatch: list[str] = field(default_factory=list) - hash_mismatch: list[str] = field(default_factory=list) - unreadable: list[tuple[str, str]] = field(default_factory=list) - untracked: list[str] = field(default_factory=list) - problems: dict[str, str] = field(default_factory=dict) - bytes_verified: int = 0 - cached: int = 0 - bytes_cached: int = 0 - elapsed_seconds: float = 0.0 - strict: bool = False - - def count_problems(self, *, strict: Optional[bool] = None) -> int: - count = len(self.missing) + len(self.size_mismatch) + len(self.hash_mismatch) + len(self.unreadable) - if strict is None: - strict = self.strict - if strict: - count += len(self.untracked) - return count - - @property - def problem_count(self) -> int: - return self.count_problems() - - def to_dict(self) -> dict: - return { - "passed": self.passed, - "total_manifest_files": self.total_manifest_files, - "matched_count": len(self.matched), - "problem_count": self.problem_count, - "missing": self.missing, - "size_mismatch": self.size_mismatch, - "hash_mismatch": self.hash_mismatch, - "unreadable": self.unreadable, - "untracked": self.untracked, - "problems": self.problems, - "bytes_verified": self.bytes_verified, - "cached_count": self.cached, - "bytes_cached": self.bytes_cached, - "elapsed_seconds": round(self.elapsed_seconds, 4), - } - - -def verify_manifest( - target_dir: str, - manifest_path: str = DEFAULT_MANIFEST, - jobs: int = 1, - progress_callback: Optional[Callable[[ProgressInfo], None]] = None, - progress_stream: Optional[TextIO] = None, - strict: bool = False, - cache_path: Optional[str] = None, -) -> ManifestReport: - """Verifies target_dir against manifest_path, optionally in parallel.""" - try: - mode = os.stat(target_dir).st_mode - except FileNotFoundError: - raise ManifestError(f"target directory does not exist: {target_dir}") from None - except OSError as err: - raise ManifestError(f"cannot access target directory {target_dir}: {err}") from None - if not stat.S_ISDIR(mode): - raise ManifestError(f"target path is not a directory: {target_dir}") - - want = load_manifest(manifest_path) - have = dict(walk(target_dir, exclude=manifest_path if cache_path is None else (manifest_path, cache_path))) - if not want and have: - # A cut-short create or a mistyped --manifest would otherwise print OK without checking a file. - raise ManifestError(f"{manifest_path} lists no files, but {target_dir} holds {len(have)}") - untracked = sorted(set(have.keys()) - set(want.keys())) - - cache = load_cache(cache_path) if cache_path is not None else {} - kept: dict[str, dict] = {} # what gets saved, only files that passed this run so the cache doesn't pile up - stamps: dict[str, list[int]] = {} - cached_files = 0 - cached_bytes = 0 - - problems: dict[str, str] = {} - unreadable_map: dict[str, str] = {} - pending: list[tuple[str, str, int, str]] = [] - total_manifest_bytes = 0 - - for rel in sorted(want.keys()): - info = want[rel] - abs_p = have.get(rel) - if abs_p is None: - problems[rel] = "MISSING" - continue - try: - if cache_path is None: - actual_size = os.path.getsize(abs_p) - else: - st = os.stat(abs_p) - actual_size = st.st_size - except OSError as err: - problems[rel] = "UNREADABLE" - unreadable_map[rel] = str(err) - continue - expected_size = info.get("size") - if expected_size is not None and actual_size != expected_size: - problems[rel] = "SIZE" - continue - expected_sha256 = info["sha256"] - if cache_path is not None: - stamp = _cache_stamp(abs_p, st) - key = _cache_key(abs_p) - hit = cache.get(key) - if hit is not None and hit["stamp"] == stamp and hit["sha256"] == expected_sha256: - kept[key] = hit - cached_files += 1 - cached_bytes += actual_size - continue - stamps[rel] = stamp - pending.append((rel, abs_p, actual_size, expected_sha256)) - total_manifest_bytes += actual_size - - total_pending_files = len(pending) - completed_files = 0 - completed_bytes = 0 - bytes_verified = 0 - t0 = time.time() - - def hash_worker(rel: str, abs_p: str, size: int, expected_hash: str) -> tuple[str, int, str, Optional[str]]: - try: - actual_hash = sha256_file(abs_p, expected_size=size) - if actual_hash.lower() != expected_hash: - return rel, size, "CHANGED", None - except OSError as err: - return rel, size, "UNREADABLE", str(err) - if cache_path is not None: - # only save it if the stamp didn't move while hashing and it wasn't written super recently, - # otherwise a sneaky write could hide behind the cache - try: - after = _cache_stamp(abs_p, os.stat(abs_p)) - except OSError: - after = None - if after == stamps[rel] and time.time_ns() - after[1] > RACY_WINDOW_NS: - kept[_cache_key(abs_p)] = {"stamp": after, "sha256": expected_hash} - return rel, size, "OK", None - - def on_file_done(rel: str, size: int, status: str, err_msg: Optional[str]) -> None: - nonlocal completed_files, completed_bytes, bytes_verified - completed_files += 1 - completed_bytes += size - if status != "UNREADABLE": - bytes_verified += size - if status != "OK": - problems[rel] = status - if status == "UNREADABLE" and err_msg: - unreadable_map[rel] = err_msg - - elapsed = max(time.time() - t0, 1e-6) - rate_mib = (completed_bytes / elapsed) / (1024 * 1024) - pct = ( - completed_bytes / total_manifest_bytes - if total_manifest_bytes > 0 - else (completed_files / total_pending_files if total_pending_files > 0 else 1.0) - ) - info = ProgressInfo( - completed_files=completed_files, - total_files=total_pending_files, - completed_bytes=completed_bytes, - total_bytes=total_manifest_bytes, - rate_mib=rate_mib, - pct=pct, - rel_path=rel, - status=status, - ) - if progress_callback is not None: - progress_callback(info) - if progress_stream is not None: - progress_stream.write(f"[{pct:6.1%}] {completed_files}/{total_pending_files} files {rate_mib:7.0f} MiB/s\n") - progress_stream.flush() - - if jobs <= 1: - for rel, abs_p, size, expected_hash in pending: - rel_res, size_res, status, err_msg = hash_worker(rel, abs_p, size, expected_hash) - on_file_done(rel_res, size_res, status, err_msg) - else: - with ThreadPoolExecutor(max_workers=jobs) as pool: - futures = [ - pool.submit(hash_worker, rel, abs_p, size, expected_hash) - for rel, abs_p, size, expected_hash in pending - ] - for future in as_completed(futures): - rel_res, size_res, status, err_msg = future.result() - on_file_done(rel_res, size_res, status, err_msg) - - matched: list[str] = [] - missing: list[str] = [] - size_mismatch: list[str] = [] - hash_mismatch: list[str] = [] - unreadable: list[tuple[str, str]] = [] - - for rel in sorted(want.keys()): - kind = problems.get(rel) - if kind == "MISSING": - missing.append(rel) - elif kind == "SIZE": - size_mismatch.append(rel) - elif kind == "CHANGED": - hash_mismatch.append(rel) - elif kind == "UNREADABLE": - unreadable.append((rel, unreadable_map.get(rel, "unreadable file"))) - else: - matched.append(rel) - - problem_count = len(missing) + len(size_mismatch) + len(hash_mismatch) + len(unreadable) - passed = (problem_count == 0) and (not strict or len(untracked) == 0) - if cache_path is not None and kept != cache: - try: - save_cache(cache_path, kept) - except OSError as err: # not fatal, next run is just slow again - print(f"warning: cannot write verify cache {cache_path}: {err}", file=sys.stderr) - elapsed_total = time.time() - t0 - - return ManifestReport( - passed=passed, - total_manifest_files=len(want), - matched=matched, - missing=missing, - size_mismatch=size_mismatch, - hash_mismatch=hash_mismatch, - unreadable=unreadable, - untracked=untracked, - problems={rel: problems[rel] for rel in sorted(problems.keys())}, - bytes_verified=bytes_verified, - cached=cached_files, - bytes_cached=cached_bytes, - elapsed_seconds=elapsed_total, - strict=strict, - ) - - -def print_report( - report: ManifestReport, - out: TextIO = sys.stdout, - verbose: bool = False, - strict: Optional[bool] = None, -) -> None: - unreadable_reasons = dict(report.unreadable) - for rel in sorted(report.problems.keys()): - kind = report.problems[rel] - if kind == "UNREADABLE": - reason = unreadable_reasons.get(rel, "unreadable file") - out.write(f"{kind} {rel}: {reason}\n") - else: - out.write(f"{kind:<10}{rel}\n") - for rel in report.untracked: - out.write(f"{'NEW':<10}{rel}\n") - - bad = report.count_problems(strict=strict) - - if bad == 0: - if verbose: - gib = report.bytes_verified / (1024**3) - cached = f"; {report.cached} from cache" if report.cached else "" - out.write(f"OK ({len(report.matched)} files, {gib:.2f} GiB in {report.elapsed_seconds:.2f}s{cached})\n") - else: - out.write("OK\n") - else: - out.write(f"{bad} problem(s)\n") - out.flush() - - -def build_parser() -> argparse.ArgumentParser: - ap = argparse.ArgumentParser( - prog="manifest_verifier.py", - description="Verify SHA-256 manifest integrity in parallel with progress reporting.", - ) - ap.add_argument("cmd_or_dir", metavar="PATH", help="Target directory to verify (or 'verify' subcommand)") - ap.add_argument("target_dir", nargs="?", default=None, metavar="TARGET_DIR", - help="Target directory (if 'verify' subcommand was used)") - ap.add_argument("--manifest", default=DEFAULT_MANIFEST, help=f"Manifest JSON file (default: {DEFAULT_MANIFEST})") - ap.add_argument( - "--jobs", "-j", type=positive_int, default=default_jobs(), metavar="N", - help="Hash up to N files concurrently (default: %(default)s; 1 = serial)", - ) - ap.add_argument("--cache", metavar="FILE", default=None, - help="Skip files unchanged since they last passed. Shortcut, not proof: keep it out of " - "the target and don't share it (default: off)") - ap.add_argument("--quiet", "-q", action="store_true", help="Suppress live progress output") - ap.add_argument("--progress-stream", choices=["stderr", "stdout"], default="stderr", - help="Stream for live progress reporting (default: stderr)") - ap.add_argument("--verbose", "-v", action="store_true", help="Print verbose summary statistics") - ap.add_argument("--json", action="store_true", help="Output verification report as JSON") - ap.add_argument("--strict", action="store_true", help="Fail if untracked (NEW) files exist") - return ap - - -def main(argv: Optional[list[str]] = None) -> int: - parser = build_parser() - args = parser.parse_args(argv) - - if args.cmd_or_dir == "verify": - game_dir = args.target_dir - if not game_dir: - parser.error("target directory required when using 'verify'") - else: - if args.target_dir is not None: - parser.error(f"unrecognized arguments: {args.target_dir}") - game_dir = args.cmd_or_dir - - below_normal() - - progress_stream = None - if not args.quiet and not args.json: - progress_stream = sys.stdout if args.progress_stream == "stdout" else sys.stderr - - try: - report = verify_manifest( - target_dir=game_dir, - manifest_path=args.manifest, - jobs=args.jobs, - progress_stream=progress_stream, - strict=args.strict, - cache_path=args.cache, - ) - except ManifestError as err: - print(f"ERROR: {err}", file=sys.stderr) - return 2 - except OSError as err: - print(f"ERROR: {err}", file=sys.stderr) - return 2 - - if args.json: - print(json.dumps(report.to_dict(), indent=2)) - else: - print_report(report, out=sys.stdout, verbose=args.verbose) - - return 0 if report.passed else 1 - - -if __name__ == "__main__": - try: # a redirected stdout is strict ANSI code page under -I; write '?' for what it cannot encode - sys.stdout.reconfigure(errors="replace") - except (AttributeError, ValueError, OSError): - pass - sys.exit(main()) diff --git a/tools/mask_channels.py b/tools/mask_channels.py deleted file mode 100644 index 222effc36..000000000 --- a/tools/mask_channels.py +++ /dev/null @@ -1,128 +0,0 @@ -"""Per-channel counts for a mask texture: which channels carry content and what shape it has. - - python -I tools/mask_channels.py [--thresholds 64,128,192] [--json FILE] - -The DDS is decoded with ``dds_png.decode_dds`` (stored values, no sRGB transfer). For each of R, G, B and A the -tool prints the minimum, maximum, mean and number of distinct values, and for each threshold the share of texels -at or above it, the number of 4-connected blobs of such texels and the share of them in the largest blob. A -constant channel carries nothing a selector could pick; a channel of a few large blobs is a broad layer and one of -tens of thousands of small blobs a spotty one. ``docs/gamedata.md`` uses these counts to tie the `AlphaChannels` -`Channel` numbers to texture channels. - -Only counts are written. The input is the user's own export and stays local. - -`--json` is published from a staging file next to the destination, creating the folder when it is missing, so -a run that fails while writing leaves an older report in place; a write error is one `ERROR:` line and exit 2. -Usage: `python -I tools/mask_channels.py --help` lists the options. -""" -from __future__ import annotations - -import argparse -import json -import os -import sys -import tempfile - -_TOOLS_DIR = os.path.dirname(os.path.abspath(__file__)) -if _TOOLS_DIR not in sys.path: - sys.path.insert(0, _TOOLS_DIR) -import dds_png # noqa: E402 -from file_mode import published_mode # noqa: E402 -from report_paths import same_report_path # noqa: E402 - -CHANNELS = "RGBA" - - -def blobs(mask: bytearray, width: int, height: int) -> list[int]: - """Sizes of the 4-connected blobs of set texels in a row-major mask, largest first.""" - seen = bytearray(len(mask)) - sizes = [] - for start in range(len(mask)): - if not mask[start] or seen[start]: - continue - seen[start] = 1 - stack, n = [start], 0 - while stack: - i = stack.pop() - n += 1 - x = i % width - for j in (i - 1 if x else -1, i + 1 if x < width - 1 else -1, i - width, i + width): - if 0 <= j < len(mask) and mask[j] and not seen[j]: - seen[j] = 1 - stack.append(j) - sizes.append(n) - return sorted(sizes, reverse=True) - - -def channel_counts(width: int, height: int, rgba: bytes, thresholds=(64, 128, 192)) -> dict: - """Counts for each channel of an RGBA8 image (see the module docstring).""" - texels = width * height - out = {} - for c, name in enumerate(CHANNELS): - values = rgba[c::4] - row = {"min": min(values), "max": max(values), "mean": round(sum(values) / texels, 2), - "distinct": len(set(values)), "thresholds": {}} - for t in thresholds: - mask = bytearray(v >= t for v in values) - covered = sum(mask) - sizes = blobs(mask, width, height) if row["min"] != row["max"] else ([covered] if covered else []) - row["thresholds"][t] = {"cover": round(covered / texels, 4), "blobs": len(sizes), - "largest_share": round(sizes[0] / covered, 4) if covered else 0.0} - out[name] = row - return out - - -def main(argv=None) -> int: - ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) - ap.add_argument("dds", help="an exported .dds texture") - ap.add_argument("--thresholds", default="64,128,192", help="comma-separated 1..255 levels (default 64,128,192)") - ap.add_argument("--json", help="also write the counts here") - a = ap.parse_args(argv) - try: - thresholds = tuple(int(t) for t in a.thresholds.split(",")) - except ValueError: - ap.error("--thresholds takes integers") - if not thresholds or any(not 0 < t <= 255 for t in thresholds): - ap.error("--thresholds must be within 1..255") - if a.json and same_report_path(a.dds, a.json): - ap.error("--json names the input texture; writing it would replace the DDS") - if a.json and os.path.isdir(a.json): - print(f"error: --json path is a directory: {a.json}", file=sys.stderr) - return 2 - try: - with open(a.dds, "rb") as fh: - width, height, rgba = dds_png.decode_dds(fh.read()) - except (OSError, ValueError) as e: - print(f"error: cannot read {a.dds}: {getattr(e, 'strerror', None) or e}", file=sys.stderr) - return 2 - counts = channel_counts(width, height, rgba, thresholds) - print(f"{width}x{height}") - for name, row in counts.items(): - parts = [f"{t}: cover {v['cover']:.3f} blobs {v['blobs']} largest {v['largest_share']:.3f}" - for t, v in row["thresholds"].items()] - print(f"{name} min {row['min']} max {row['max']} mean {row['mean']} distinct {row['distinct']} | " - + " | ".join(parts)) - if a.json: - out_dir = os.path.dirname(os.path.abspath(a.json)) - try: - os.makedirs(out_dir, exist_ok=True) - with tempfile.TemporaryDirectory(prefix=".mask-json-", dir=out_dir) as staging: - staged = os.path.join(staging, "masks.json") - with open(staged, "w", encoding="utf-8", newline="\n") as fh: - json.dump({"width": width, "height": height, "channels": counts}, fh, indent=2) - os.chmod(staged, published_mode(a.json)) # tempfile creates 0600; the report gets the usual bits - os.replace(staged, a.json) - except OSError as error: - # A failed write must not leave a half-written report where the last good one was. - reason = error.strerror or str(error) - print(f"ERROR: {a.json}: {reason}", file=sys.stderr) - return 2 - return 0 - - -if __name__ == "__main__": - try: # a redirected stdout is strict ANSI code page under -I; write '?' for what it cannot encode - sys.stdout.reconfigure(errors="replace") - except (AttributeError, ValueError, OSError): - pass - sys.exit(main()) diff --git a/tools/mc_command.py b/tools/mc_command.py deleted file mode 100644 index 762008d7a..000000000 --- a/tools/mc_command.py +++ /dev/null @@ -1,152 +0,0 @@ -"""Resolve LLVM_MC to an argv list. - -LLVM_MC may be one executable (a path, spaces and all, with or without its .exe) or a whole command line. Windows -needs the command-line form when llvm-mc runs inside WSL, because the official Windows LLVM build has no AMDGPU -target: - - set LLVM_MC=wsl -d Ubuntu -e /usr/lib/llvm-21/bin/llvm-mc - -On Windows, arguments follow the MSVC C runtime's quoting rules. Double a trailing backslash in a quoted -argument before the closing quote. - -With LLVM_MC unset, the plain name llvm-mc is used when it is on PATH. Debian and Ubuntu install `llvm-` under -versioned names only (/usr/bin/llvm-mc- and /usr/lib/llvm-/bin/llvm-mc; the plain name comes with the -unversioned `llvm` package), so off Windows the newest of those is used when the plain name is missing. - -run() starts such a command and turns a missing llvm-mc into one line instead of a FileNotFoundError traceback. -""" -from __future__ import annotations - -import glob -import os -import re -import shlex -import shutil -import subprocess -import sys - - -def split_windows_command(raw: str) -> list[str]: - """Decode an MSVC-style argument list, rejecting unmatched quotes.""" - args = [] - pos = 0 - while pos < len(raw): - if raw[pos] in " \t": - pos += 1 - continue - arg = [] - quoted = False - while pos < len(raw) and (quoted or raw[pos] not in " \t"): - start = pos - while pos < len(raw) and raw[pos] == "\\": - pos += 1 - backslashes = pos - start - if pos < len(raw) and raw[pos] == '"': - # Backslashes are special only before a quote. An odd final slash escapes that quote. - arg.append("\\" * (backslashes // 2)) - if backslashes % 2: - arg.append('"') - elif quoted and raw[pos + 1:pos + 2] == '"': - arg.append('"') - pos += 1 - else: - quoted = not quoted - pos += 1 - else: - arg.append("\\" * backslashes) - if pos == len(raw) or (not quoted and raw[pos] in " \t"): - break - arg.append(raw[pos]) - pos += 1 - if quoted: - raise ValueError("No closing quotation") - args.append("".join(arg)) - return args - - -def split_command(raw: str) -> list[str]: - """Split a command line without eating the backslashes of a Windows path (POSIX shlex would).""" - raw = raw.strip() - if not raw: - return [] - if os.path.isfile(raw): - return [raw] # a plain path, spaces and all - if ("/" in raw or "\\" in raw) and shutil.which(raw): - # A path whose extension is left out (C:\Program Files\LLVM\bin\llvm-mc): Windows finds llvm-mc.exe - # for it, but it is no file under that exact name, so it used to be split at its spaces. - return [raw] - try: - return split_windows_command(raw) if os.name == "nt" else shlex.split(raw) - except ValueError as e: - # shader_disasm.py calls mc_command() at import time: a bad LLVM_MC must give one clear line, - # not a ValueError traceback before any tool's own argument parsing runs. - raise SystemExit(f"LLVM_MC: invalid command line {raw!r}: {e}") from None - - -DEBIAN_LLVM_MC = "/usr/lib/llvm-*/bin/llvm-mc" # Debian and Ubuntu: one folder per llvm- package - - -def versioned_llvm_mc() -> str | None: - """Off Windows: the newest llvm-mc installed under a versioned name, llvm-mc- on PATH or - /usr/lib/llvm-/bin/llvm-mc, or None. Only names are looked at; nothing is started, because - shader_disasm.py resolves the command at import time. Empty PATH entries (the current folder) are skipped.""" - if os.name == "nt": - return None - found = {} - for folder in os.environ.get("PATH", "").split(os.pathsep): - if not folder: - continue - for path in glob.glob(os.path.join(glob.escape(folder), "llvm-mc-[0-9]*")): - m = re.fullmatch(r"llvm-mc-(\d+)", os.path.basename(path)) - if m and os.path.isfile(path) and os.access(path, os.X_OK): - found.setdefault(int(m.group(1)), path) - for path in glob.glob(DEBIAN_LLVM_MC): - m = re.fullmatch(r"llvm-(\d+)", os.path.basename(os.path.dirname(os.path.dirname(path)))) - if m and os.path.isfile(path) and os.access(path, os.X_OK): - found.setdefault(int(m.group(1)), path) - return found[max(found)] if found else None - - -def default_command() -> str: - """llvm-mc when the plain name is on PATH (the name a work folder's disassembly record already holds), else - versioned_llvm_mc(), else the plain name, which then fails with not_found()'s message.""" - if shutil.which("llvm-mc"): - return "llvm-mc" - return versioned_llvm_mc() or "llvm-mc" - - -def mc_command(raw: str | None = None) -> list: - """LLVM_MC is a path, or a command line: 'wsl -d Ubuntu -e /usr/lib/llvm-21/bin/llvm-mc'. Unset or empty, - default_command().""" - if raw is None: - raw = os.environ.get("LLVM_MC", "") - return split_command(raw) or [default_command()] - - -def install_hint() -> str: - """Where to get an llvm-mc with the AMDGPU target on this OS, for the messages that report a missing one.""" - if os.name == "nt": - return ("The official Windows LLVM build has no AMDGPU target: build a native one with " - "scripts\\build_llvm_mc.ps1 (it sets LLVM_MC), or install llvm-21 in WSL and set LLVM_MC to the " - "whole command, e.g.\n LLVM_MC=wsl -d Ubuntu -e /usr/lib/llvm-21/bin/llvm-mc") - if sys.platform == "darwin": - return ("Homebrew's llvm has the AMDGPU target but is keg-only (not on PATH): brew install llvm, then\n" - " LLVM_MC=\"$(brew --prefix llvm)/bin/llvm-mc\"") - return ("Distribution LLVM packages include the AMDGPU target: on Debian or Ubuntu, sudo apt install llvm-21\n" - "(found as /usr/lib/llvm-21/bin/llvm-mc without further setup); elsewhere install your distribution's\n" - "LLVM 21+ package and put llvm-mc on PATH, or set LLVM_MC=/path/to/llvm-mc") - - -def not_found(exe: str, error: OSError, flag: str | None = None) -> str: - """The message for an llvm-mc that can't be started (shader_disasm.py's wording). `flag` is the tool's own - option for the command, if it has one (run_gpu_tests.py's --llvm-mc); the others read LLVM_MC only.""" - where = f"set LLVM_MC (or pass {flag})" if flag else "set LLVM_MC" - return f"'{exe}' could not be started: {error}. Put llvm-mc on PATH or {where} to it.\n{install_hint()}" - - -def run(cmd: list, flag: str | None = None, **kwargs) -> subprocess.CompletedProcess: - """subprocess.run for an llvm-mc command line; one that can't be started ends the tool with not_found().""" - try: - return subprocess.run(cmd, **kwargs) - except OSError as e: - raise SystemExit(not_found(cmd[0], e, flag)) from None diff --git a/tools/mem_diff.py b/tools/mem_diff.py deleted file mode 100644 index 6e1efc156..000000000 --- a/tools/mem_diff.py +++ /dev/null @@ -1,841 +0,0 @@ -r"""Differential fuzzer for the translator's memory instructions (FUZZ-5; standard library only). - -Seeded programs made of scalar and buffer memory instructions are run two ways and compared bit-exact: - * a small reference model in this file, written from the RDNA2 buffer and scalar-memory addressing rules - (below), which shares no code with the translator; - * tools/rdna2spirv.py, executed by tests/semantic/spirv_mini_interp.py. - -Both the exported words (mrt0) and the final memory contents are compared, so stores are checked too. - -Addressing modelled (AMD RDNA2 ISA, buffer resource descriptor and MUBUF/SMEM addressing): - * V# base = word0 | (word1 & 0xFFFF) << 32; stride = word1[29:16]. - * MUBUF = base + soffset + inst_offset + (offen ? voffset : 0) + (idxen ? vindex * stride : 0), - with the offsets summed in 32 bits. Swizzled buffers are not generated. - * s_load = 64-bit pointer s[p:p+1] + soffset (u32) + imm. - * s_buffer_load = V# base + soffset + imm. - -Every generated access lies inside its buffer (index < num_records for structured buffers, the whole access -below num_records for raw ones) and is dword aligned. Untyped buffer accesses use a word3 with only OOB_SELECT -(STRUCTURED with a stride, RAW without). Out-of-bounds behaviour, the -s_buffer_load alignment truncation and swizzling depend on descriptor fields docs/design.md lists as not modelled, -so they are left to a GPU-confirmed follow-up instead of being guessed here. - -Typed buffer loads (buffer_load_format_*, tbuffer_load_format_*) are decoded from the GFX10 format names in -tools/gfx10_formats.json, not from the translator's table. MUBUF applies DST_SEL and repeats missing channels -(*c* mod *n*). MTBUF uses instruction-format channels in order, zero-fills absent channels and returns zero -for an INVALID V# format. UNORM/SNORM use correctly rounded division, and MUBUF DST_SEL 1 is integer 1 -for UINT/SINT (SHADER-86, RX 6700). - -Usage: - python -I tools/mem_diff.py [--programs N] [--seed S] [--max-ops N] - python -I tools/mem_diff.py --self-test - -Exit code 0 when every program matches, 1 on a mismatch (the first one is printed with its listing), 2 on a -harness error or when every program was skipped (nothing was compared). Skips are counted with their reasons, never silent. -""" -import argparse -import gc -import os -import random -import struct -import sys -import tempfile -import warnings - -HERE = os.path.dirname(os.path.abspath(__file__)) -sys.dont_write_bytecode = True -if HERE not in sys.path: - sys.path.insert(0, HERE) -SEM_DIR = os.path.join(os.path.dirname(HERE), "tests", "semantic") -if SEM_DIR not in sys.path: - sys.path.insert(0, SEM_DIR) - -import rdna2spirv # noqa: E402 -from spirv_mini_interp import run_fragment # noqa: E402 - -MASK32 = 0xFFFFFFFF -MASK64 = (1 << 64) - 1 -STUB_DXBC = b"DXBC" + bytes(24) + struct.pack(" name (Mesa gfx10-rsrc.json), data only -ONE_F32 = 0x3F800000 - - -def parse_format(name): - """'GFX10_FORMAT_16_16_SNORM' -> ([16, 16] for X, Y from bit 0, 'SNORM'). The name lists the channel widths - from the top bit down (2_10_10_10 is X10 Y10 Z10 W2 from bit 0), so the list is reversed. Returns None for - names this model does not decode (packed floats, scaled, sRGB, block formats).""" - parts = name.replace("GFX10_FORMAT_", "").split("_") - kind = parts[-1] - try: - widths = [int(p) for p in parts[:-1]] - except ValueError: - return None - if kind not in ("UNORM", "SNORM", "UINT", "SINT", "FLOAT") or not widths: - return None - if kind == "FLOAT" and any(w not in (16, 32) for w in widths): - return None - if sum(widths) % 8: - return None - return list(reversed(widths)), kind - - -def f32_round(q): - """Nearest-even binary32 of an exact rational (Fraction), as bits.""" - from fractions import Fraction - if q == 0: - return 0 - d = float(q) - cands = set() - for scale in (1.0, 1 + 2 ** -26, 1 - 2 ** -26): - try: - cands.add(struct.unpack(" f32 bits. Exact for finite and infinite halves; a NaN shifts its 10-bit payload into the f32 - mantissa and keeps the sign and the quiet bit exactly as the half has them (measured on gfx1036 with - tools/f16_widen_probe.py: 0x7ddb -> 0x7fbb6000, 0x7fe6 -> 0x7ffcc000). struct's '> 15) << 31 - exp = (h >> 10) & 0x1F - frac = h & 0x03FF - if exp == 0x1F: - return sign | 0x7F800000 | (frac << 13) - if exp == 0 and frac: - b = frac.bit_length() - return sign | ((b + 102) << 23) | ((frac << (24 - b)) & 0x7FFFFF) - if exp == 0: - return sign - return sign | ((exp + 112) << 23) | (frac << 13) - - -def decode_element(raw, widths, kind): - """Decode one element (an int of sum(widths) bits) -> 4 result words; missing channels repeat (*c* mod *n*).""" - from fractions import Fraction - out, bit = [], 0 - for w in widths: - v = (raw >> bit) & ((1 << w) - 1) - bit += w - if kind == "UNORM": - out.append(f32_round(Fraction(v, (1 << w) - 1))) - elif kind == "SNORM": - s = v - (1 << w) if v >> (w - 1) else v - q = max(Fraction(s, (1 << (w - 1)) - 1), Fraction(-1)) - bits_ = f32_round(abs(q)) - out.append(bits_ | (0x80000000 if q < 0 else 0)) - elif kind == "UINT": - out.append(v) - elif kind == "SINT": - out.append((v - (1 << w) if v >> (w - 1) else v) & MASK32) - elif w == 32: - out.append(v) - else: # FLOAT 16 -> f32 bits (exact, NaN payload kept) - out.append(f16_to_f32(v)) - n = len(out) - while len(out) < 4: - out.append(out[len(out) % n]) - return out - - -# ---------------------------------------------------------------- reference model - -class RefMachine: - """Executes the subset of RDNA2 this fuzzer emits, for one lane.""" - - def __init__(self, memory): - self.mem = memory - self.s = {} - self.v = {} - - def word(self, addr): - if addr & 3: - raise AssertionError(f"reference model: unaligned dword at {addr:#x}") - return self.mem.get(addr & MASK64, 0) - - def put(self, addr, value): - if addr & 3: - raise AssertionError(f"reference model: unaligned dword at {addr:#x}") - self.mem[addr & MASK64] = value & MASK32 - - def scalar(self, text): - text = text.strip() - if text.startswith("s") and text[1:].isdigit(): - return self.s.get(int(text[1:]), 0) - if text.startswith("v") and text[1:].isdigit(): - return self.v.get(int(text[1:]), 0) - return int(text, 0) & MASK32 - - def run(self, lines): - for line in lines: - self.step(line) - - def step(self, line): - op, _, rest = line.partition(" ") - args = [a.strip() for a in rest.split(",")] if rest else [] - mods = [] - if args: - tail = args[-1].split() - args[-1], mods = tail[0], tail[1:] - if op == "s_mov_b32": - self.s[int(args[0][1:])] = self.scalar(args[1]) - elif op == "v_mov_b32": - src = args[1] - self.v[int(args[0][1:])] = self.scalar(src) - elif op.startswith("s_load_dword") or op.startswith("s_buffer_load_dword"): - n = 1 if op.endswith("dword") else int(op.rsplit("x", 1)[1]) - dst = reg_first(args[0]) - base_reg = reg_first(args[1]) - lo, hi = self.s.get(base_reg, 0), self.s.get(base_reg + 1, 0) - if op.startswith("s_buffer"): - hi &= 0xFFFF - addr = (hi << 32 | lo) + self.scalar(args[2]) - for m in mods: - if m.startswith("offset:"): - addr += int(m.split(":", 1)[1], 0) - for i in range(n): - self.s[dst + i] = self.word((addr + 4 * i) & MASK64) - elif op.startswith("buffer_load_dword") or op.startswith("buffer_store_dword"): - n = 1 if op.endswith("dword") else int(op.rsplit("x", 1)[1]) - vdata = reg_first(args[0]) - addr = self._mubuf_addr(args[1], args[2], args[3], mods) - for i in range(n): - if op.startswith("buffer_load"): - self.v[vdata + i] = self.word(addr + 4 * i) - else: - self.put(addr + 4 * i, self.v.get(vdata + i, 0)) - elif op in BUFFER_SUB: - addr = self._mubuf_addr(args[1], args[2], args[3], mods) - self.v[reg_first(args[0])] = self._sub_dword(addr, *BUFFER_SUB[op]) - elif op.startswith(("buffer_load_format_", "tbuffer_load_format_")): - ncomp = len(op.rsplit("_", 1)[1]) - vdata, rsrc = reg_first(args[0]), reg_first(args[2]) - vaddr = None if args[1] == "off" else reg_first(args[1]) - d0, d1, d3 = self.s.get(rsrc, 0), self.s.get(rsrc + 1, 0), self.s.get(rsrc + 3, 0) - base, stride = (d1 & 0xFFFF) << 32 | d0, (d1 >> 16) & 0x3FFF - offset = self.scalar(args[3]) + sum(int(m.split(":", 1)[1], 0) for m in mods if m.startswith("offset:")) - regs = [] if vaddr is None else [vaddr, vaddr + 1] - if "idxen" in mods: - offset += self.v.get(regs.pop(0), 0) * stride - if "offen" in mods: - offset += self.v.get(regs.pop(0), 0) - addr = base + (offset & MASK32) - fm = next((m for m in mods if m.startswith("format:")), None) - tbuffer = op.startswith("tbuffer") - descriptor_format = (d3 >> 12) & 0x7F - if tbuffer: - if descriptor_format == 0: - for c in range(ncomp): - self.v[vdata + c] = 0 - return - # LLVM omits the default MTBUF instruction format from its listing. - fmt = DEFAULT_TBUFFER_FORMAT if fm is None else fm.split("BUF_FMT_")[-1].rstrip("]") - name = "GFX10_FORMAT_" + fmt - else: - name = FORMAT_NAMES[descriptor_format] - widths, kind = parse_format(name) - nbytes = sum(widths) // 8 - raw = 0 - for i in range(nbytes): # little-endian bytes from dword memory - a = addr + i - raw |= ((self.word(a & ~3) >> (8 * (a & 3))) & 0xFF) << (8 * i) - comps = decode_element(raw, widths, kind) - if tbuffer: - for c in range(ncomp): - self.v[vdata + c] = comps[c] if c < len(widths) else 0 - return - one = 1 if kind in ("UINT", "SINT") else ONE_F32 - for c in range(ncomp): - sel = (d3 >> (3 * c)) & 7 - self.v[vdata + c] = {0: 0, 1: one, 4: comps[0], 5: comps[1], 6: comps[2], 7: comps[3]}.get(sel, 0) - elif op.startswith("buffer_atomic_"): - kind = op[len("buffer_atomic_"):] - vdata = reg_first(args[0]) - addr = self._mubuf_addr(args[1], args[2], args[3], mods) - old = self._apply_atomic(kind, addr, self.v.get(vdata, 0), self.v.get(vdata + 1, 0)) - if "glc" in mods: - self.v[vdata] = old - elif op.startswith("global_atomic_"): - kind = op[len("global_atomic_"):] - glc = "glc" in mods - vaddr, vdata_arg, saddr = (args[1], args[2], args[3]) if glc else (args[0], args[1], args[2]) - addr = self._global_addr(vaddr, saddr, mods) - vdata = reg_first(vdata_arg) - old = self._apply_atomic(kind, addr, self.v.get(vdata, 0), self.v.get(vdata + 1, 0)) - if glc: - self.v[reg_first(args[0])] = old - elif op.startswith("global_load") or op.startswith("global_store"): - load = op.startswith("global_load") - data, vaddr = (reg_first(args[0]), args[1]) if load else (reg_first(args[1]), args[0]) - addr = self._global_addr(vaddr, args[2], mods) - sub = GLOBAL_SUB_SPEC.get(op) - if sub: - self.v[data] = self._sub_dword(addr, *sub) - else: - n = 1 if op.endswith("dword") else int(op.rsplit("x", 1)[1]) - for i in range(n): - if load: - self.v[data + i] = self.word(addr + 4 * i) - else: - self.put(addr + 4 * i, self.v.get(data + i, 0)) - elif op.startswith("s_waitcnt") or op == "exp" or op == "s_endpgm": - pass - else: - raise AssertionError(f"reference model: unexpected op {op}") - - def _mubuf_addr(self, vaddr_arg, rsrc_arg, soff_arg, mods): - vaddr = None if vaddr_arg == "off" else reg_first(vaddr_arg) - rsrc = reg_first(rsrc_arg) - d0, d1 = self.s.get(rsrc, 0), self.s.get(rsrc + 1, 0) - base, stride = (d1 & 0xFFFF) << 32 | d0, (d1 >> 16) & 0x3FFF - offset = self.scalar(soff_arg) + sum(int(m.split(":", 1)[1], 0) for m in mods if m.startswith("offset:")) - regs = [] if vaddr is None else [vaddr, vaddr + 1] - if "idxen" in mods: - offset += self.v.get(regs.pop(0), 0) * stride - if "offen" in mods: - offset += self.v.get(regs.pop(0), 0) - return base + (offset & MASK32) - - def _global_addr(self, vaddr, saddr, mods): - inst = sum(int(m.split(":", 1)[1], 0) for m in mods if m.startswith("offset:")) - if saddr == "off": - v0 = reg_first(vaddr) - addr = self.v.get(v0 + 1, 0) << 32 | self.v.get(v0, 0) - else: - s0 = reg_first(saddr) - addr = (self.s.get(s0 + 1, 0) << 32 | self.s.get(s0, 0)) + self.v.get(reg_first(vaddr), 0) - return (addr + inst) & MASK64 # the printed offset is already signed (llvm-mc) - - def _sub_dword(self, addr, bits, sign): - shift = (addr & 3) * 8 - value = (self.word(addr & ~3) >> shift) & ((1 << bits) - 1) - if sign and value >> (bits - 1): - value -= 1 << bits - return value & MASK32 - - def _apply_atomic(self, kind, addr, src, cmp_val=0): - old = self.word(addr) - s32 = lambda x: x - (1 << 32) if x >> 31 else x # noqa: E731 - new = {"add": old + src, "sub": old - src, "umin": min(old, src), "umax": max(old, src), - "smin": old if s32(old) <= s32(src) else src, "smax": old if s32(old) >= s32(src) else src, - "and": old & src, "or": old | src, "xor": old ^ src, "swap": src, - "cmpswap": src if old == cmp_val else old}[kind] - self.put(addr, new) - return old - - -def reg_first(text): - """'v4' / 's[8:11]' / 'v[2:3]' -> 4 / 8 / 2.""" - text = text.strip() - if "[" in text: - return int(text[2:].split(":")[0]) - return int(text[1:]) - - -def reg_range(kind, first, n): - return f"{kind}{first}" if n == 1 else f"{kind}[{first}:{first + n - 1}]" - - -# ---------------------------------------------------------------- program generator - -def _seed_region(rng, memory, base): - for i in range(WORDS): - memory[base + 4 * i] = rng.getrandbits(32) - - -def _buffer_base(rng): - """A 48-bit, region-aligned base address. The high 16 bits exercise V# word1[15:0].""" - hi = rng.choice((0, 0, 1, 0x7F, 0xFFFF)) - lo = rng.randrange(1, 0x10000) * REGION - return (hi << 32 | lo) & ((1 << 48) - 1) - - -def _soffset(rng, prog, budget): - """A scalar offset operand: an inline constant or s6 seeded with a dword-aligned value below budget.""" - value = rng.randrange(0, max(1, budget // 4)) * 4 - if value <= 64 and rng.random() < 0.5: - return str(value), value - prog.lines.append(f"s_mov_b32 s{SOFF}, {value:#x}") - return f"s{SOFF}", value - - -def _emit_vsharp(rng, prog, base, stride, num_records): - word1 = (base >> 32) & 0xFFFF | (stride & 0x3FFF) << 16 - # word3: only OOB_SELECT (bits 29:28), the bounds check the accesses stay inside of: STRUCTURED for a stride, - # RAW without (the two RADV uses); every generated access is in range under either - for i, w in enumerate((base & MASK32, word1, num_records, OOB_STRUCTURED if stride else OOB_RAW)): - prog.lines.append(f"s_mov_b32 s{VSHARP + i}, {w:#x}") - - -def gen_s_load(rng, prog): - base = _buffer_base(rng) - _seed_region(rng, prog.memory, base) - n = rng.choice((1, 2, 4, 8)) - prog.lines.append(f"s_mov_b32 s{POINTER}, {base & MASK32:#x}") - prog.lines.append(f"s_mov_b32 s{POINTER + 1}, {base >> 32:#x}") - room = REGION - 4 * n - form = rng.choice(("imm", "sgpr", "both")) - if form == "imm": - off = rng.randrange(0, room // 4 + 1) * 4 - operand = f"{off:#x}" - elif form == "sgpr": - off = rng.randrange(0, room // 4 + 1) * 4 - prog.lines.append(f"s_mov_b32 s{SOFF}, {off:#x}") - operand = f"s{SOFF}" - else: - a = rng.randrange(0, room // 8 + 1) * 4 - b = rng.randrange(0, (room - a) // 4 + 1) * 4 - prog.lines.append(f"s_mov_b32 s{SOFF}, {a:#x}") - operand = f"s{SOFF} offset:{b:#x}" - prog.lines.append(f"s_load_dword{'' if n == 1 else 'x' + str(n)} {reg_range('s', SDST, n)}, " - f"s[{POINTER}:{POINTER + 1}], {operand}") - prog.lines.append("s_waitcnt lgkmcnt(0)") - return [("s", SDST + i) for i in range(n)] - - -def gen_s_buffer_load(rng, prog): - base = _buffer_base(rng) - _seed_region(rng, prog.memory, base) - n = rng.choice((1, 2, 4, 8)) - _emit_vsharp(rng, prog, base, 0, REGION) - room = REGION - 4 * n - if rng.random() < 0.5: - off = rng.randrange(0, room // 4 + 1) * 4 - operand = f"{off:#x}" - else: - off = rng.randrange(0, room // 4 + 1) * 4 - prog.lines.append(f"s_mov_b32 s{SOFF}, {off:#x}") - operand = f"s{SOFF}" - prog.lines.append(f"s_buffer_load_dword{'' if n == 1 else 'x' + str(n)} {reg_range('s', SDST, n)}, " - f"s[{VSHARP}:{VSHARP + 3}], {operand}") - prog.lines.append("s_waitcnt lgkmcnt(0)") - return [("s", SDST + i) for i in range(n)] - - -def _mubuf_operands(rng, prog, n): - """Pick a raw or structured layout and an in-bounds address. Returns the operand text after vdata.""" - base = _buffer_base(rng) - _seed_region(rng, prog.memory, base) - size = 4 * n - structured = rng.random() < 0.5 - inst = rng.randrange(0, 16) * 4 - if structured: - stride = rng.choice((4, 8, 12, 16, 32, 48, 64, 256)) - stride = max(stride, size) # the element holds the whole access - records = REGION // stride - index = rng.randrange(0, records) - inst = min(inst, stride - size) - inst -= inst % 4 - soff_text, soff = _soffset(rng, prog, stride - size - inst + 4) - within = soff + inst - voff = None - if within + size <= stride and rng.random() < 0.5: - voff = rng.randrange(0, (stride - size - within) // 4 + 1) * 4 - _emit_vsharp(rng, prog, base, stride, records) - prog.lines.append(f"v_mov_b32 v{VADDR}, {index:#x}") - if voff is not None: - prog.lines.append(f"v_mov_b32 v{VADDR + 1}, {voff:#x}") - return f"v[{VADDR}:{VADDR + 1}], s[{VSHARP}:{VSHARP + 3}], {soff_text} idxen offen offset:{inst}" - return f"v{VADDR}, s[{VSHARP}:{VSHARP + 3}], {soff_text} idxen offset:{inst}" - soff_text, soff = _soffset(rng, prog, REGION // 4) - room = REGION - size - soff - inst - voff = rng.randrange(0, room // 4 + 1) * 4 - _emit_vsharp(rng, prog, base, 0, REGION) - if rng.random() < 0.8: - prog.lines.append(f"v_mov_b32 v{VADDR}, {voff:#x}") - return f"v{VADDR}, s[{VSHARP}:{VSHARP + 3}], {soff_text} offen offset:{inst}" - return f"off, s[{VSHARP}:{VSHARP + 3}], {soff_text} offset:{inst}" - - -def gen_buffer_load(rng, prog): - n = rng.choice((1, 2, 3, 4)) - operands = _mubuf_operands(rng, prog, n) - prog.lines.append(f"buffer_load_dword{'' if n == 1 else 'x' + str(n)} {reg_range('v', VDATA, n)}, {operands}") - prog.lines.append("s_waitcnt vmcnt(0)") - return [("v", VDATA + i) for i in range(n)] - - -def gen_buffer_store(rng, prog): - n = rng.choice((1, 2, 3, 4)) - for i in range(n): - prog.lines.append(f"v_mov_b32 v{VDATA + i}, {rng.getrandbits(32):#x}") - operands = _mubuf_operands(rng, prog, n) - prog.lines.append(f"buffer_store_dword{'' if n == 1 else 'x' + str(n)} {reg_range('v', VDATA, n)}, {operands}") - # Read the same place back so the export sees the stored words too; memory is compared as a whole anyway. - prog.lines.append(f"buffer_load_dword{'' if n == 1 else 'x' + str(n)} {reg_range('v', VDATA, n)}, {operands}") - prog.lines.append("s_waitcnt vmcnt(0)") - return [("v", VDATA + i) for i in range(n)] - - -BUFFER_SUB = {"buffer_load_ubyte": (8, False), "buffer_load_sbyte": (8, True), - "buffer_load_ushort": (16, False), "buffer_load_sshort": (16, True)} - - -def gen_buffer_sub(rng, prog): - name = rng.choice(tuple(BUFFER_SUB)) - size = 1 if "byte" in name else 2 - operands = _mubuf_operands(rng, prog, 1) - head, inst_str = operands.rsplit("offset:", 1) - inst = int(inst_str, 0) + rng.randrange(0, 4 // size) * size - prog.lines.append(f"{name} v{VDATA}, {head}offset:{inst}") - prog.lines.append("s_waitcnt vmcnt(0)") - return [("v", VDATA)] - - -ATOMICS = ("add", "sub", "umin", "umax", "smin", "smax", "and", "or", "xor", "swap", "cmpswap") - - -def gen_buffer_atomic(rng, prog): - kind = rng.choice(ATOMICS) - glc = rng.random() < 0.7 - prog.lines.append(f"v_mov_b32 v{VDATA}, {rng.getrandbits(32):#x}") - operands = _mubuf_operands(rng, prog, 1) - if kind == "cmpswap": - # Half the time compare against the word that is really there, so the swap happens. - prog.lines.append(f"buffer_load_dword v{VDATA + 1}, {operands}" if rng.random() < 0.5 - else f"v_mov_b32 v{VDATA + 1}, {rng.getrandbits(32):#x}") - prog.lines.append("s_waitcnt vmcnt(0)") - vdata = f"v[{VDATA}:{VDATA + 1}]" - else: - vdata = f"v{VDATA}" - prog.lines.append(f"buffer_atomic_{kind} {vdata}, {operands}{' glc' if glc else ''}") - prog.lines.append(f"buffer_load_dword v{VDATA + 2}, {operands}") - prog.lines.append("s_waitcnt vmcnt(0)") - return [("v", VDATA), ("v", VDATA + 2)] - - -GLOBAL_SUB_SPEC = {"global_load_ubyte": (8, False), "global_load_sbyte": (8, True), - "global_load_ushort": (16, False), "global_load_sshort": (16, True)} -GLOBAL_SUB = tuple(GLOBAL_SUB_SPEC) - - -def _global_addr_operands(rng, prog, width, align, sub_size=0): - """Emit a 64-bit VGPR address or SGPR base + 32-bit VGPR offset reaching an in-bounds address.""" - base = _buffer_base(rng) + REGION # room below the base for negative offsets - _seed_region(rng, prog.memory, base - REGION) - _seed_region(rng, prog.memory, base) - inst = rng.randrange(-2048 // 4, 2048 // 4) * 4 - if sub_size: - inst += rng.randrange(0, 4 // sub_size) * sub_size - target = rng.randrange(-REGION // align, (REGION - width) // align + 1) * align - voff = target - inst - if voff >= 0 and rng.random() < 0.5: - prog.lines += [f"s_mov_b32 s{POINTER}, {base & MASK32:#x}", f"s_mov_b32 s{POINTER + 1}, {base >> 32:#x}", - f"v_mov_b32 v{VADDR}, {voff:#x}"] - vaddr, saddr = f"v{VADDR}", f"s[{POINTER}:{POINTER + 1}]" - else: - a = base + voff # 64-bit VGPR address - prog.lines += [f"v_mov_b32 v{VADDR}, {a & MASK32:#x}", f"v_mov_b32 v{VADDR + 1}, {a >> 32:#x}"] - vaddr, saddr = f"v[{VADDR}:{VADDR + 1}]", "off" - off = f" offset:{inst}" if inst else "" - return vaddr, saddr, off - - -def gen_global(rng, prog): - """global_load/store with a 64-bit VGPR address or an SGPR base + 32-bit VGPR offset, and a signed 12-bit - immediate printed the way llvm-mc prints it for gfx10 (decimal, negative values with a minus sign).""" - op = rng.choice(("load", "load", "store", "sub")) - n = rng.choice((1, 2, 3, 4)) if op != "sub" else 1 - width = 4 * n - sub_size = 0 - if op == "sub": - name = rng.choice(GLOBAL_SUB) - sub_size = 1 if "byte" in name else 2 - width = sub_size - vaddr, saddr, off = _global_addr_operands(rng, prog, width, 4 if op != "sub" else width, sub_size) - if op == "store": - for i in range(n): - prog.lines.append(f"v_mov_b32 v{VDATA + i}, {rng.getrandbits(32):#x}") - suffix = "" if n == 1 else f"x{n}" - prog.lines.append(f"global_store_dword{suffix} {vaddr}, {reg_range('v', VDATA, n)}, {saddr}{off}") - prog.lines.append(f"global_load_dword{suffix} {reg_range('v', VDATA, n)}, {vaddr}, {saddr}{off}") - elif op == "sub": - prog.lines.append(f"{name} v{VDATA}, {vaddr}, {saddr}{off}") - else: - suffix = "" if n == 1 else f"x{n}" - prog.lines.append(f"global_load_dword{suffix} {reg_range('v', VDATA, n)}, {vaddr}, {saddr}{off}") - prog.lines.append("s_waitcnt vmcnt(0)") - return [("v", VDATA + i) for i in range(n)] - - -def gen_global_atomic(rng, prog): - kind = rng.choice(ATOMICS) - glc = rng.random() < 0.7 - prog.lines.append(f"v_mov_b32 v{VDATA}, {rng.getrandbits(32):#x}") - vaddr, saddr, off = _global_addr_operands(rng, prog, 4, 4) - if kind == "cmpswap": - prog.lines.append(f"global_load_dword v{VDATA + 1}, {vaddr}, {saddr}{off}" if rng.random() < 0.5 - else f"v_mov_b32 v{VDATA + 1}, {rng.getrandbits(32):#x}") - prog.lines.append("s_waitcnt vmcnt(0)") - vdata = f"v[{VDATA}:{VDATA + 1}]" - else: - vdata = f"v{VDATA}" - vdst = f"v{VDATA + 2}, " if glc else "" - prog.lines.append(f"global_atomic_{kind} {vdst}{vaddr}, {vdata}, {saddr}{off}{' glc' if glc else ''}") - prog.lines.append(f"global_load_dword v{VDATA + 3}, {vaddr}, {saddr}{off}") - prog.lines.append("s_waitcnt vmcnt(0)") - return [("v", VDATA + 2 if glc else VDATA), ("v", VDATA + 3)] - - -DEFAULT_TBUFFER_FORMAT = "8_UNORM" -# Exercise the implicit LLVM spelling alongside the five MTBUF formats found in the 1.0.2.1 corpus. -TBUFFER_FORMATS = ("16_16_SNORM", "8_8_8_8_UNORM", "8_8_8_8_UINT", "2_10_10_10_UNORM", "16_16_16_16_UINT", - DEFAULT_TBUFFER_FORMAT) -XYZW = 4 | 5 << 3 | 6 << 6 | 7 << 9 -OOB_STRUCTURED, OOB_RAW = 1 << 28, 3 << 28 # V# word3 OOB_SELECT - - -def _typed_codes(): - """Formats buffer_load_format is generated with: the ones the translator claims to decode (its scope), each - checked here against the reference decode of its GFX10 name.""" - return sorted(c for c in rdna2spirv.Gen.FORMATS if parse_format(FORMAT_NAMES[c])) - - -def gen_buffer_format(rng, prog): - ncomp = rng.choice((1, 2, 3, 4)) - suffix = "xyzw"[:ncomp] - tbuffer = rng.random() < 0.5 - if tbuffer: - fname = rng.choice(TBUFFER_FORMATS) - widths, kind = parse_format("GFX10_FORMAT_" + fname) - word3 = (20 << 12) | XYZW # Bound 32_UINT V#; the instruction selects the format. - else: - code = rng.choice(_typed_codes()) - widths, kind = parse_format(FORMAT_NAMES[code]) - sels = [rng.choice((0, 1, 4, 5, 6, 7)) for _ in range(4)] - word3 = code << 12 | sels[0] | sels[1] << 3 | sels[2] << 6 | sels[3] << 9 - size = sum(widths) // 8 - base = _buffer_base(rng) - _seed_region(rng, prog.memory, base) - structured = rng.random() < 0.5 - if structured: - stride = size * rng.choice((1, 2, 3, 4)) - stride += -stride % 4 - records = REGION // stride - index = rng.randrange(0, records) - _emit_vsharp(rng, prog, base, stride, records) - prog.lines[-1] = f"s_mov_b32 s{VSHARP + 3}, {word3 | OOB_STRUCTURED:#x}" - prog.lines.append(f"v_mov_b32 v{VADDR}, {index:#x}") - operands = f"v{VADDR}, s[{VSHARP}:{VSHARP + 3}], 0" - addr_mods = "idxen" - else: - voff = rng.randrange(0, (REGION - 16) // size) * size - _emit_vsharp(rng, prog, base, 0, REGION) - prog.lines[-1] = f"s_mov_b32 s{VSHARP + 3}, {word3 | OOB_RAW:#x}" - prog.lines.append(f"v_mov_b32 v{VADDR}, {voff:#x}") - operands = f"v{VADDR}, s[{VSHARP}:{VSHARP + 3}], 0" - addr_mods = "offen" - vdata = reg_range("v", VDATA, ncomp) - if tbuffer: - format_mod = "" if fname == DEFAULT_TBUFFER_FORMAT else f" format:[BUF_FMT_{fname}]" - prog.lines.append(f"tbuffer_load_format_{suffix} {vdata}, {operands}{format_mod} {addr_mods}") - else: - prog.lines.append(f"buffer_load_format_{suffix} {vdata}, {operands} {addr_mods}") - prog.lines.append("s_waitcnt vmcnt(0)") - return [("v", VDATA + c) for c in range(ncomp)] - - -GENERATORS = { - "s_load": gen_s_load, - "s_buffer_load": gen_s_buffer_load, - "buffer_load": gen_buffer_load, - "buffer_sub": gen_buffer_sub, - "buffer_store": gen_buffer_store, - "buffer_atomic": gen_buffer_atomic, - "global": gen_global, - "global_atomic": gen_global_atomic, - "buffer_format": gen_buffer_format, -} - - -def generate_program(rng, n_ops, families=None): - """A program of n_ops memory operations; its last four result registers are exported through v8..v11.""" - prog = Program() - names = sorted(families or GENERATORS) - results = [] - for _ in range(n_ops): - family = rng.choice(names) - prog.lines.append(f"; {family}") - results = GENERATORS[family](rng, prog) or results - picks = [results[min(i, len(results) - 1)] for i in range(4)] if results else [] - for dst, (kind, reg) in zip(EXPORT, picks): - if not (kind == "v" and reg == dst): - prog.lines.append(f"v_mov_b32 v{dst}, {kind}{reg}") - return prog - - -# ---------------------------------------------------------------- running both sides - -def _listing(lines): - body = [line for line in lines if not line.startswith(";")] - return ("; mem_diff case code 0x0..0x1000\n" + "".join("\t" + line + "\n" for line in body) - + f"\texp mrt0 {', '.join('v%d' % r for r in EXPORT)} done vm\n\ts_endpgm\n") - - -def run_one(name, prog): - """Returns (status, detail): status is match, mismatch or skip.""" - ref = RefMachine(dict(prog.memory)) - ref.run([line for line in prog.lines if not line.startswith(";")]) - want = [ref.v.get(r, 0) for r in EXPORT] - with tempfile.TemporaryDirectory(prefix="mem-diff-") as tmp: - dis = os.path.join(tmp, "disasm") - os.mkdir(dis) - path = os.path.join(dis, name + ".s") - with open(path, "w", encoding="utf-8", newline="\n") as f: - f.write(_listing(prog.lines)) - with open(os.path.join(tmp, name + ".dxbc"), "wb") as f: - f.write(STUB_DXBC) - try: - with warnings.catch_warnings(): - warnings.simplefilter("ignore", ResourceWarning) - spvasm = rdna2spirv.translate(path) - gc.collect() - except rdna2spirv.Unsupported as e: - return "skip", f"translator unsupported: {e}" - memory = dict(prog.memory) - try: - out = run_fragment(spvasm, memory=memory) - except Exception as e: # noqa: BLE001 - the interpreter is half of the comparison - return "skip", f"mini_interp unsupported: {type(e).__name__}: {e}" - got = list(out.get("%out_mrt0", ())) - if got != want: - bad = [k for k in range(4) if k >= len(got) or got[k] != want[k]] - i = bad[0] - g = f"{got[i]:#010x}" if i < len(got) else "missing" - detail = f"export word {i}: expected {want[i]:#010x}, translated {g}" - return "mismatch", detail - if memory != ref.mem: - bad = sorted(a for a in set(memory) | set(ref.mem) if memory.get(a, 0) != ref.mem.get(a, 0)) - a = bad[0] - return "mismatch", (f"memory at {a:#x} ({len(bad)} word(s) differ): expected {ref.mem.get(a, 0):#010x}, " - f"translated {memory.get(a, 0):#010x}") - return "match", "" - - -def run_suite(programs, seed, max_ops, families=None): - counts = {"pass": 0, "mismatch": 0, "skip": {}, "harness-error": 0} - first = None - rng = random.Random(seed) - for i in range(programs): - prog = generate_program(rng, rng.randrange(1, max_ops + 1), families) - name = f"ps_mem_{i:05d}" - try: - status, detail = run_one(name, prog) - except Exception as e: # noqa: BLE001 - harness bugs must be loud - counts["harness-error"] += 1 - first = first or f"{name}: harness error {type(e).__name__}: {e}" - continue - if status == "match": - counts["pass"] += 1 - elif status == "mismatch": - counts["mismatch"] += 1 - if first is None: - first = f"{name} (seed {seed} program {i}): {detail}\n" + "\n".join("\t" + x for x in prog.lines) - else: - counts["skip"][detail] = counts["skip"].get(detail, 0) + 1 - return counts, first - - -def self_test(): - """Canaries: a hand-written case matches, and a corrupted reference is caught.""" - prog = Program() - prog.memory = {0x2000: 0x11111111, 0x2004: 0x22222222, 0x2008: 0x33333333, 0x200C: 0x44444444} - prog.lines = ["s_mov_b32 s0, 0x2000", "s_mov_b32 s1, 0", "s_mov_b32 s2, 0x10", "s_mov_b32 s3, 0x30000000", - "v_mov_b32 v2, 4", "buffer_load_dwordx3 v[8:10], v2, s[0:3], 0 offen", "s_waitcnt vmcnt(0)", - "v_mov_b32 v11, 7"] - status, detail = run_one("ps_mem_canary", prog) - if status != "match": - print(f"canary FAILED: hand-written case gave {status}: {detail}") - return False - ref = RefMachine(dict(prog.memory)) - ref.run(prog.lines) - if [ref.v.get(r) for r in EXPORT] != [0x22222222, 0x33333333, 0x44444444, 7]: - print("canary FAILED: the reference model read the wrong words") - return False - real_word = RefMachine.word - RefMachine.word = lambda self, addr: real_word(self, addr) ^ 1 # a reference that is off by one bit - try: - status, _ = run_one("ps_mem_canary_bad", prog) - finally: - RefMachine.word = real_word - if status != "mismatch": - print("canary FAILED: a corrupted reference was not caught") - return False - # The f16 reference keeps a NaN payload and its quiet bit, as gfx1036 does (tools/f16_widen_probe.py). - if decode_element(0x7DDB, [16], "FLOAT")[0] != 0x7FBB6000: - print("canary FAILED: the f16 NaN payload was not kept") - return False - print("canaries: match ok, mismatch detected") - return True - - -def main(argv=None): - ap = argparse.ArgumentParser(description="Differential fuzzer for memory instructions (FUZZ-5).") - ap.add_argument("--programs", type=int, default=200) - ap.add_argument("--seed", type=int, default=1) - ap.add_argument("--max-ops", type=int, default=3) - ap.add_argument("--family", action="append", choices=sorted(GENERATORS), help="restrict to one family (repeatable)") - ap.add_argument("--self-test", action="store_true") - a = ap.parse_args(argv) - if a.programs < 1 or a.max_ops < 1: - ap.error("--programs and --max-ops must be at least 1") - if a.self_test: - return 0 if self_test() else 1 - counts, first = run_suite(a.programs, a.seed, a.max_ops, a.family) - skips = sum(counts["skip"].values()) - print(f"{a.programs} programs (seed {a.seed}): {counts['pass']} pass, {counts['mismatch']} mismatch, " - f"{skips} skipped, {counts['harness-error']} harness errors") - for reason, n in sorted(counts["skip"].items()): - print(f" skip x{n}: {reason}") - if first: - print("FIRST FAILURE:\n" + first) - if counts["harness-error"]: - return 2 - if counts["mismatch"]: - return 1 - if not counts["pass"]: - print("no program ran: every one was skipped") - return 2 - return 0 - - -if __name__ == "__main__": - try: # a redirected stdout is strict ANSI code page under -I; write '?' for what it cannot encode - sys.stdout.reconfigure(errors="replace") - except (AttributeError, ValueError, OSError): - pass - sys.exit(main()) diff --git a/tools/mesh_compute_vs.py b/tools/mesh_compute_vs.py deleted file mode 100644 index 573b1b467..000000000 --- a/tools/mesh_compute_vs.py +++ /dev/null @@ -1,311 +0,0 @@ -#!/usr/bin/env python3 -"""Vertex shaders that draw what rdna2spirv.py --mesh-compute mesh shaders wrote. - -On a device without VK_EXT_mesh_shader, `rdna2spirv.py --mesh-compute` turns each mesh shader into a compute shader -with the same workgroup size. Each workgroup writes its vertex and primitive counts, its vertices and its -primitives into a slot of an output buffer. The layout is the shader's "mesh_compute" entry in index.json: -rdna2spirv.mesh_compute_layout. The buffer's device address is in push-constant dwords 36..37, for both the -compute shader and this vertex shader. - -The draw that follows is non-indexed: vkCmdDraw(groups * max_primitives * 3), where groups is the number of -workgroups dispatched. Vertex v belongs to workgroup v / (3 * max_primitives), primitive (v / 3) % max_primitives, -corner v % 3. A primitive past the workgroup's count, or one marked culled, gets the same position outside the -clip volume at all three corners, so it is clipped away. Otherwise the corner's vertex index (clamped to -max_vertices - 1) selects the vertex whose position, clip and cull distances and params this shader outputs. The -params go out at the locations the mesh shader used, so the pixel shader is unchanged. With rdna2spirv.py ---f16-interp-fallback the layout also has "f16_halves" ({param: [low location, high location]}), and each of those -params' f16 halves goes out decoded to f32 at those locations too, as a translated VS exports them. - - python -I tools/mesh_compute_vs.py # .mesh_vs.spv per --mesh-compute MS in index.json - -Standard library only; build_for_index assembles and validates with spirv-as / spirv-val from PATH. -""" -import json -import os -import shutil -import subprocess -import sys -import tempfile - -SUFFIX = ".mesh_vs" # .mesh_vs.spvasm / .spv next to the mesh shader -USER_SGPRS = 32 # push constants: s0..s31, heap base, code base, then the output address (rdna2spirv.py) - - -F16_HALF_TOP = 29 - - -def pair_f16_halves(layout, ps_f16_halves, ps_raw_inputs=(), top=F16_HALF_TOP): - """Choose non-colliding `f16_halves` ({str(param): [lo, hi]}) for a (--mesh-compute, PS) pair (SHADER-378). - - Keeps the PS's own `[lo, hi]` locations whenever every requested param is exported by `layout["params"]` and no - half location collides with any producer param or exceeds `top`. Otherwise packs all requested pairs downward - from `top` into locations disjoint from `producer_params | ps_raw_inputs`. - """ - producer_params = {int(k) for k in layout.get("params", {})} - ps_pairs = {int(k): [int(v[0]), int(v[1])] for k, v in ps_f16_halves.items()} - if not ps_pairs: - return {} - missing = sorted(p for p in ps_pairs if p not in producer_params) - if missing: - raise ValueError(f"mesh_compute_vs: producer does not export f16_halves param(s) {missing}") - if all(0 <= lo <= top and 0 <= hi <= top and lo != hi and lo not in producer_params and hi not in producer_params - for lo, hi in ps_pairs.values()): - used_halves = [loc for pair in ps_pairs.values() for loc in pair] - if len(set(used_halves)) == len(used_halves): - return {str(k): list(v) for k, v in sorted(ps_pairs.items())} - reserved = producer_params | {int(x) for x in ps_raw_inputs} - free = [loc for loc in range(top, -1, -1) if loc not in reserved] - need = 2 * len(ps_pairs) - if len(free) < need: - raise ValueError(f"mesh_compute_vs: need {need} decoded-half locations, only {len(free)} free in 0..{top}") - return {str(p): [free[2 * k + 1], free[2 * k]] for k, p in enumerate(sorted(ps_pairs))} - - -def vs_spvasm(layout, f16_halves=None): - """SPIR-V assembly of the vertex shader for one --mesh-compute layout (index.json "mesh_compute"). - - Optional `f16_halves` ({param: [low_loc, high_loc]}) overrides `layout["f16_halves"]` for per-pipeline pairing - (SHADER-378), so a producer with many params only exports the decoded halves its paired PS actually reads. - """ - lay = dict(layout) - if f16_halves is not None: - lay["f16_halves"] = f16_halves - params = sorted((int(k), int(v)) for k, v in lay["params"].items()) - maxv, maxp = int(lay["max_vertices"]), int(lay["max_primitives"]) - clip, cull = int(lay["clip_count"]), int(lay["cull_count"]) - consts = {} - - def c(v): - consts.setdefault(int(v), f"%c{int(v)}") - return consts[int(v)] - - ulongs = {} - - def cl(v): - ulongs.setdefault(int(v), f"%cl{int(v)}") - return ulongs[int(v)] - - body = [] - n = [0] - - def tmp(p="t"): - n[0] += 1 - return f"%{p}{n[0]}" - - def load_word(base64, off): - """uint at slot byte offset `off` (constant) from the ulong address `base64`.""" - a, p, v = tmp("a"), tmp("p"), tmp("w") - body.extend([f"{a} = OpIAdd %ulong {base64} {cl(off)}" if off else f"{a} = OpCopyObject %ulong {base64}", - f"{p} = OpConvertUToPtr %_ptr_PSB_uint {a}", f"{v} = OpLoad %uint {p} Aligned 4"]) - return v - - def load_floats(base64, off, count): - out = [] - for i in range(count): - w = load_word(base64, off + 4 * i) - f = tmp("f") - body.append(f"{f} = OpBitcast %float {w}") - out.append(f) - return out - - c(0), c(1), c(3), c(5), c(6) - if clip: - c(clip) - if cull: - c(cull) - body += [ - "%vid = OpLoad %int %vertex_index", "%vidu = OpBitcast %uint %vid", - f"%per = OpCopyObject %uint {c(3 * maxp)}", - "%wg = OpUDiv %uint %vidu %per", "%rem = OpUMod %uint %vidu %per", - f"%prim = OpUDiv %uint %rem {c(3)}", f"%corner = OpUMod %uint %rem {c(3)}", - f"%alo_p = OpAccessChain %_ptr_PC_uint %pc {c(5)}", f"%ahi_p = OpAccessChain %_ptr_PC_uint %pc {c(6)}", - "%alo = OpLoad %uint %alo_p", "%ahi = OpLoad %uint %ahi_p", - "%alo64 = OpUConvert %ulong %alo", "%ahi64 = OpUConvert %ulong %ahi", - f"%ahis = OpShiftLeftLogical %ulong %ahi64 {cl(32)}", "%addr = OpBitwiseOr %ulong %ahis %alo64", - "%wg64 = OpUConvert %ulong %wg", f"%soff = OpIMul %ulong %wg64 {cl(lay['slot_bytes'])}", - "%slot = OpIAdd %ulong %addr %soff"] - pcount = load_word("%slot", 4) - body += [f"%inrange = OpULessThan %bool %prim {pcount}", - f"%pofs = OpIMul %uint %prim {c(lay['primitive_stride'])}", "%pofs64 = OpUConvert %ulong %pofs", - f"%pbase0 = OpIAdd %ulong %slot {cl(lay['primitives'])}", "%pbase = OpIAdd %ulong %pbase0 %pofs64", - f"%cofs = OpIMul %uint %corner {c(4)}", "%cofs64 = OpUConvert %ulong %cofs", - "%iaddr = OpIAdd %ulong %pbase %cofs64", "%iptr = OpConvertUToPtr %_ptr_PSB_uint %iaddr", - "%idx0 = OpLoad %uint %iptr Aligned 4", - f"%idx = OpExtInst %uint %glsl UMin %idx0 {c(maxv - 1)}"] - culled_w = load_word("%pbase", 12) - body += [f"%culled = OpINotEqual %bool {culled_w} {c(0)}", "%notculled = OpLogicalNot %bool %culled", - "%valid = OpLogicalAnd %bool %inrange %notculled", - f"%vofs = OpIMul %uint %idx {c(lay['vertex_stride'])}", "%vofs64 = OpUConvert %ulong %vofs", - f"%vbase0 = OpIAdd %ulong %slot {cl(lay['vertices'])}", "%vbase = OpIAdd %ulong %vbase0 %vofs64"] - pos = load_floats("%vbase", 0, 4) - body += [f"%pos = OpCompositeConstruct %v4float {' '.join(pos)}", - "%pos_out = OpSelect %v4float %valid %pos %outside", "OpStore %out_pos %pos_out"] - if clip: - vals = load_floats("%vbase", lay["clip_offset"], clip) - body += [f"%clipv = OpCompositeConstruct %arr_clip {' '.join(vals)}", "OpStore %out_clip %clipv"] - if cull: - vals = load_floats("%vbase", lay["cull_offset"], cull) - body += [f"%cullv = OpCompositeConstruct %arr_cull {' '.join(vals)}", "OpStore %out_cull %cullv"] - for loc, off in params: - vals = load_floats("%vbase", off, 4) - body += [f"%par{loc} = OpCompositeConstruct %v4float {' '.join(vals)}", f"OpStore %out{loc} %par{loc}"] - halves = sorted((int(k), [int(x) for x in v]) for k, v in lay.get("f16_halves", {}).items()) - offsets = dict(params) - used_locs = set(offsets) - for loc, hlocs in halves: - if loc not in offsets: - raise ValueError(f"mesh_compute_vs: f16_halves param {loc} is not in layout params") - if len(hlocs) != 2 or hlocs[0] == hlocs[1] or hlocs[0] < 0 or hlocs[1] < 0: - raise ValueError(f"mesh_compute_vs: invalid f16_halves locations {hlocs} for param {loc}") - for hloc in hlocs: - if hloc in used_locs: - raise ValueError(f"mesh_compute_vs: f16_halves location {hloc} collides with another output") - used_locs.add(hloc) - for loc, hlocs in halves: # --f16-interp-fallback: each channel's two f16 halves decoded to f32 - parts = ([], []) - for i in range(4): - w, h2 = load_word("%vbase", offsets[loc] + 4 * i), tmp("h") - body.append(f"{h2} = OpExtInst %v2float %glsl UnpackHalf2x16 {w}") - for half in (0, 1): - e = tmp("e") - body.append(f"{e} = OpCompositeExtract %float {h2} {half}") - parts[half].append(e) - for half, hloc in enumerate(hlocs): - body += [f"%hv{hloc} = OpCompositeConstruct %v4float {' '.join(parts[half])}", - f"OpStore %out{hloc} %hv{hloc}"] - hout = [hloc for _, hlocs in halves for hloc in hlocs] - body += ["OpReturn", "OpFunctionEnd"] - - outs = ["%out_pos"] + (["%out_clip"] if clip else []) + (["%out_cull"] if cull else []) + \ - [f"%out{loc}" for loc, _ in params] + [f"%out{h}" for h in hout] - caps = ["Shader", "Int64", "PhysicalStorageBufferAddresses"] + (["ClipDistance"] if clip else []) + \ - (["CullDistance"] if cull else []) - head = [f"OpCapability {x}" for x in caps] + [ - 'OpExtension "SPV_KHR_physical_storage_buffer"', - '%glsl = OpExtInstImport "GLSL.std.450"', - "OpMemoryModel PhysicalStorageBuffer64 GLSL450", - f'OpEntryPoint Vertex %main "main" %vertex_index %pc {" ".join(outs)}', - "OpDecorate %vertex_index BuiltIn VertexIndex", - "OpDecorate %out_pos BuiltIn Position"] - if clip: - head.append("OpDecorate %out_clip BuiltIn ClipDistance") - if cull: - head.append("OpDecorate %out_cull BuiltIn CullDistance") - head += [f"OpDecorate %out{loc} Location {loc}" for loc in [p for p, _ in params] + hout] - head += ["OpDecorate %arr_ud ArrayStride 4", "OpDecorate %PC Block", "OpMemberDecorate %PC 0 Offset 0"] - head += [f"OpMemberDecorate %PC {k} Offset {4 * USER_SGPRS + 4 * (k - 1)}" for k in range(1, 7)] - head += ["OpDecorate %rt_uint ArrayStride 4"] - types = ["%void = OpTypeVoid", "%fn = OpTypeFunction %void", "%bool = OpTypeBool", - "%uint = OpTypeInt 32 0", "%int = OpTypeInt 32 1", "%ulong = OpTypeInt 64 0", - "%float = OpTypeFloat 32", "%v4float = OpTypeVector %float 4", "%v2float = OpTypeVector %float 2"] - types += [f"{name} = OpConstant %uint {v}" for v, name in sorted(consts.items())] - types += [f"{name} = OpConstant %ulong {v}" for v, name in sorted(ulongs.items())] - types += [f"%n_ud = OpConstant %uint {USER_SGPRS}", "%arr_ud = OpTypeArray %uint %n_ud", - "%PC = OpTypeStruct %arr_ud %uint %uint %uint %uint %uint %uint", - "%_ptr_PC = OpTypePointer PushConstant %PC", "%_ptr_PC_uint = OpTypePointer PushConstant %uint", - "%rt_uint = OpTypeRuntimeArray %uint", - "%_ptr_PSB_uint = OpTypePointer PhysicalStorageBuffer %uint", - "%_ptr_In_int = OpTypePointer Input %int", "%_ptr_Out_v4 = OpTypePointer Output %v4float", - "%f1 = OpConstant %float 1", "%f2 = OpConstant %float 2", - "%outside = OpConstantComposite %v4float %f2 %f2 %f2 %f1"] - if clip: - types += ["%arr_clip = OpTypeArray %float " + c(clip), "%_ptr_Out_clip = OpTypePointer Output %arr_clip"] - if cull: - types += ["%arr_cull = OpTypeArray %float " + c(cull), "%_ptr_Out_cull = OpTypePointer Output %arr_cull"] - gvars = ["%vertex_index = OpVariable %_ptr_In_int Input", "%pc = OpVariable %_ptr_PC PushConstant", - "%out_pos = OpVariable %_ptr_Out_v4 Output"] - if clip: - gvars.append("%out_clip = OpVariable %_ptr_Out_clip Output") - if cull: - gvars.append("%out_cull = OpVariable %_ptr_Out_cull Output") - gvars += [f"%out{loc} = OpVariable %_ptr_Out_v4 Output" for loc in [p for p, _ in params] + hout] - fn = ["%main = OpFunction %void None %fn", "%entry = OpLabel"] - return "\n".join(head + types + gvars + fn + body) + "\n" - - -def write_for_index(spirv_dir): - """Write .mesh_vs.spvasm for every entry of /index.json with a "mesh_compute" layout.""" - index_path = os.path.join(spirv_dir, "index.json") - if not os.path.isfile(index_path): - return [] - try: - with open(index_path, encoding="utf-8") as f: - index = json.load(f) - except (ValueError, RecursionError) as e: - raise RuntimeError(f"{index_path}: invalid JSON ({e})") from None - if not isinstance(index, dict): - raise RuntimeError(f"{index_path}: expected a shader index object") - written = [] - for name, meta in sorted(index.items()): - lay = meta.get("mesh_compute") if isinstance(meta, dict) else None - if not lay: - continue - try: - asm = vs_spvasm(lay) - except (AttributeError, KeyError, OverflowError, TypeError, ValueError) as e: - raise RuntimeError(f"{index_path}: invalid mesh_compute layout for {name!r}: {e}") from None - path = os.path.join(spirv_dir, name + SUFFIX + ".spvasm") - with open(path, "w", encoding="utf-8", newline="\n") as f: - f.write(asm) - written.append(path) - return written - - -def tool_path(name): - """The SPIR-V tool's full path, or RuntimeError naming it: subprocess's own FileNotFoundError says only - "the system cannot find the file specified", which does not say which tool is missing.""" - path = shutil.which(name) - if path is None: - raise RuntimeError(f"{name} not found on PATH (it ships with SPIRV-Tools, e.g. VulkanSDK/Bin)") - return path - - -def build_for_index(spirv_dir): - """write_for_index, then assemble to .mesh_vs.spv and validate (Vulkan 1.2, as for the translator). - Returns the .spv paths; raises RuntimeError with the tool output on failure.""" - steps = [("spirv-as", tool_path("spirv-as")), ("spirv-val", tool_path("spirv-val"))] - built = [] - for asm in write_for_index(spirv_dir): - spv = asm[: -len(".spvasm")] + ".spv" - with tempfile.TemporaryDirectory(prefix=".mesh-vs-", dir=os.path.dirname(spv)) as staging: - staged_spv = os.path.join(staging, os.path.basename(spv)) - for name, tool in steps: - args = [asm, "-o", staged_spv] if name == "spirv-as" else [staged_spv] - cmd = [tool, "--target-env", "vulkan1.2"] + args - r = subprocess.run(cmd, capture_output=True, text=True) - if r.returncode: - raise RuntimeError(f"{name} failed for {asm}:\n{r.stdout}{r.stderr}") - os.replace(staged_spv, spv) - built.append(spv) - return built - - -def main(argv): - if argv[1:] in (["-h"], ["--help"]): - print(__doc__) - return 0 - if len(argv) != 2: - print(__doc__, file=sys.stderr) - return 2 - if not os.path.isdir(argv[1]): - print(f"ERROR: {argv[1]}: not a directory", file=sys.stderr) - return 1 - try: - built = build_for_index(argv[1]) - except RuntimeError as e: - print(f"ERROR: {e}", file=sys.stderr) - return 1 - except OSError as e: - print(f"ERROR: {e.filename or argv[1]}: {e.strerror or e}", file=sys.stderr) - return 1 - for path in built: - print(path) - return 0 - - -if __name__ == "__main__": - try: # a redirected stdout is strict ANSI code page under -I; write '?' for what it cannot encode - sys.stdout.reconfigure(errors="replace") - except (AttributeError, ValueError, OSError): - pass - sys.exit(main(sys.argv)) diff --git a/tools/meshlet_page.py b/tools/meshlet_page.py deleted file mode 100644 index 71460068e..000000000 --- a/tools/meshlet_page.py +++ /dev/null @@ -1,1048 +0,0 @@ -"""Index the `63 30 00 00` mesh pages (vertex blocks plus meshlet groups) in carved streams or an RPF9 archive. - -`docs/story.md` lists 45 inflated streams in `shared_minigame000.rpf` that start with `63 30 00 00`. They are -geometry pages: a run of 16-byte-aligned chunks, each either a vertex block or a meshlet group. - -Vertex block (header 0x60 bytes, first u32 is 0x00003063): - +0x00..+0x58 23 slot words. A non-zero word is tag (low byte) | offset/2 (high 24 bits); the offset is - from the block start. Slot 0 is always tag 0x63 at offset 0x60. - +0x5C u32, 0x200 in every block measured. - slot 0 tag 0x63 12 bytes/vertex float3 position - slot 1 tag 0x26 4 bytes/vertex RGBA8 (absent in some blocks) - slot 2 tag 0x63 12 bytes/vertex float3 normal (absent in some blocks) - slot 3 tag 0x42 8 bytes/vertex float2 - slot 4 tag 0x42 8 bytes/vertex float2 (absent in some blocks) - a slot past 4 (seen: slot 12, tag 0x26) takes its tag's stride (the tag rule below) - The streams are stored in slot order 0, 2, 1, 3, 4. Only slot 0 is required. The vertex count is the span - from slot 0 to the next stream in offset order, divided by 12; the block ends 8 * count bytes after its last - slot. - -Meshlet group (first u32 has bit 31 set): - +0 u32 0x80000000 | meshlet count K - +4 u32 triangle count T - +8 u32 vertex reference count V - +12 K * 16-byte meshlet records: - u32 w0: bits 0-6 = vertices - 1, bits 7-13 = triangles - 1, bits 14-15 zero, bits 16-31 = the - meshlet's bounding-sphere radius around the w2/w3 centre, as an f16 (measured on `42 40` geometry) - u32 w1: low u16 = first vertex reference, high u16 = first triangle (running sums) - u32 w2, w3: bits 0-11 and 12-23 of w2 and bits 0-11 of w3 are the meshlet's centre in x, y and z as - 12-bit steps around 2047, (field - 2047) * step (measured on `42 40` geometry; the default - 0x007FF7FF / 0x7FF is the origin). The step is 2^e / 16 m with e = w2 bits 28-31 (0 to 4 - seen; larger meshlets further out), and w2 bits 24-27 are 0. w3 bits 14-30 are the normal cone: axis - octahedral u = bits 14-19, v = bits 20-25 (x / 31.5 - 1), sin(half-angle) = (31 - bits 26-30) - / 31; all zero = no cone. - then T u32 triangles: three 7-bit meshlet-local indices (bits 0-6, 7-13, 14-20), meshlet index in bits 21-31 - then V u16 vertex references into a vertex block - -`42 40 00 00` vertex block (header 0x80 bytes, first u32 is 0x00004042; ASSET-146): - +0x00..+0x58 23 slot words, encoded as above. Slot 0 is always tag 0x42 at offset 0x80. - +0x5C u32, 0x200 (as in the `63 30` block) - +0x60 f32 x3 bias +0x6C u32 axis order, 0, 1 or 2 - +0x70 f32 x3 scale +0x7C f32 UV scale for type-8 slots (4.0f in every block measured) - A slot tag byte is (stride / 4) << 5 | type (tag_stride, SLOT_TYPES): 0x42 = 8 bytes, 0x21, 0x25, 0x26, 0x27 and - 0x28 = 4 bytes, and 0x63 in the `63 30` block = 12 bytes. The vertex count is the span - from slot 0 to the next stream divided by 8; every stream is stride * count bytes and the block ends there. - Measured over every `42 40` block of `shared_minigame000.rpf`: 14,671 fit this exactly, and each one is - followed by a `42 40` block, a meshlet group, a `63 30` block or the end of the stream. - slot 0 tag 0x42 8 bytes/vertex packed position, read as one u64 q: - a = bits 8-31 (24 bits), b = bits 32-47 << 8 | bits 0-7 (24 bits), c = bits 48-63 (16 bits) - (a, b, c) = bias + scale * (a, b, c); axis 0 stores (z, y, x), axis 1 (y, z, x), axis 2 (x, y, z) - This is the rule `third_party/rpf9-explorer/Core/RageModelDecoder.cs` uses for `(8, 16)` positions; - `docs/story.md` has the independent check over the minigame archive. - slot 2 the vertex normal, in world order whatever the axis word: tag 0x21 (type 1) is octahedral, u = bits - 0-9 and v = bits 10-19 as unorm (x / 511.5 - 1), bits 20-31 not decoded; tag 0x27 (type 7) is x, y, z in - bits 0-9, 10-19, 20-29 as the same unorm. - slots 11 and 18 tag 0x27 (type 7): a tangent, x, y, z as in slot 2's type 7, perpendicular to the normal; bits - 30-31 are 3 or 0, read here as the bitangent sign +1 or -1. Other 4-byte streams are not decoded. - -A page starts with a `63 30` block, a `42 40` block or a group (continuation pages). The walk stops, without an -error, at a `42 40` block whose layout doesn't fit the rule above, at a group that continues past the end of -the stream, or where other data starts on a 256-byte boundary behind zero padding after the mesh chunks. Only -counts and layout checks are written; no vertex, index or float value leaves this tool. - -Usage: - python -I tools/meshlet_page.py [...] [--json out.json] [--quiet] - [--faces] [--centres] [--normals] [--cones] - python -I tools/meshlet_page.py --draw-system --geometry-offset [--json out.json] - python -I tools/meshlet_page.py --draw-system --drawable-offset -""" -import argparse -import json -import math -import mmap -import os -import re -import struct -import sys -import zlib - -BLOCK_MAGIC = 0x3063 -OTHER_BLOCK_MAGIC = 0x4042 -HEADER_SIZE = 0x60 -SLOT_COUNT = 23 -SLOT_STRIDE = {0: 12, 1: 4, 2: 12, 3: 8, 4: 8} -SLOT_TAG = {0: 0x63, 1: 0x26, 2: 0x63, 3: 0x42, 4: 0x42} -OTHER_HEADER_SIZE = 0x80 -# A slot tag byte is (stride / 4) << 5 | type, as rpf9-explorer's RageModelDecoder reads vertex slots. Types seen in -# shared_minigame000.rpf: 1, 2, 3, 6, 7, 8. Skinned blocks also use type 5 for joint indices. -SLOT_TYPES = {1: "octahedral normal, 10 + 10 bits unorm", 2: "2 x f32 or a packed position", 3: "3 x f32", - 5: "joint indices in skin slots", 6: "RGBA8", - 7: "3 x 10 bits unorm (the normal in slot 2, a tangent in slots 11 and 18)", - 8: "2 x snorm16 UV, scaled by the 42 40 header's +0x7C"} - - -def tag_stride(tag): - """Bytes per vertex for a slot tag (bits 5-7 times 4), or None for a type not seen or a zero stride.""" - stride = ((tag >> 5) & 7) * 4 - return stride if stride and (tag & 15) in SLOT_TYPES else None -ZHDR = re.compile(rb"\x78[\x01\x5e\x9c\xda]") - - -class PageError(ValueError): - pass - - -def _u32(data, at): - if at + 4 > len(data): - raise PageError(f"truncated at +0x{at:x}") - return struct.unpack_from(" len(data): - raise PageError(f"block header truncated at +0x{at:x}") - words = struct.unpack_from("<24I", data, at) - if words[0] != BLOCK_MAGIC: - raise PageError(f"no block magic at +0x{at:x}") - slots = {i: (w & 0xFF, (w >> 8) * 2) for i, w in enumerate(words[:SLOT_COUNT]) if w} - if 0 not in slots: - raise PageError(f"block at +0x{at:x} has no slot 0") - if slots[0][1] != HEADER_SIZE: - raise PageError(f"block at +0x{at:x}: slot 0 is not at +0x60") - order = sorted(slots, key=lambda i: slots[i][1]) - if len(order) < 2 or order[0] != 0: - raise PageError(f"block at +0x{at:x}: slot 0 is not followed by another stream") - span = slots[order[1]][1] - slots[0][1] - if span <= 0 or span % SLOT_STRIDE[0]: - raise PageError(f"block at +0x{at:x}: slot {order[1]} offset is not 12 * count past slot 0") - count = span // SLOT_STRIDE[0] - for here, nxt in zip(order, order[1:]): - stride = SLOT_STRIDE.get(here, tag_stride(slots[here][0])) # a slot past 4: its tag's stride - if stride is None or slots[nxt][1] - slots[here][1] != stride * count: - raise PageError(f"block at +0x{at:x}: slot {here} size is not stride * count") - last = order[-1] - if last not in (3, 4): - raise PageError(f"block at +0x{at:x}: last slot is {last}, expected a float2 slot") - end = at + slots[last][1] + 8 * count - if end > len(data): - raise PageError(f"block at +0x{at:x} runs past the page end") - record = {"kind": "block", "offset": at, "vertices": count, "flags": words[23], - "slots": [[i, slots[i][0], slots[i][1]] for i in sorted(slots)], - "tags_expected": all(SLOT_TAG.get(i) == t for i, (t, _) in slots.items())} - return record, end - - -def parse_other_block(data, at): - """Size a `42 40 00 00` vertex block at `at` from its slot words. Returns (record, end offset); the record holds - counts and tags only.""" - if at + OTHER_HEADER_SIZE > len(data): - raise PageError(f"42 40 block header truncated at +0x{at:x}") - words = struct.unpack_from("<32I", data, at) - if words[0] != OTHER_BLOCK_MAGIC: - raise PageError(f"no 42 40 block magic at +0x{at:x}") - slots = {i: (w & 0xFF, (w >> 8) * 2) for i, w in enumerate(words[:SLOT_COUNT]) if w} - if any(tag_stride(tag) is None for tag, _ in slots.values()): - raise PageError(f"42 40 block at +0x{at:x} has a slot tag with no known stride") - order = sorted(slots, key=lambda i: slots[i][1]) - if len(order) < 2 or order[0] != 0 or slots[0][1] != OTHER_HEADER_SIZE: - raise PageError(f"42 40 block at +0x{at:x}: slot 0 is not at +0x80 or has no stream after it") - span = slots[order[1]][1] - OTHER_HEADER_SIZE - if span <= 0 or span % tag_stride(slots[0][0]): - raise PageError(f"42 40 block at +0x{at:x}: slot 0 span is not a whole number of vertices") - count = span // tag_stride(slots[0][0]) - for here, nxt in zip(order, order[1:]): - if slots[nxt][1] - slots[here][1] != tag_stride(slots[here][0]) * count: - raise PageError(f"42 40 block at +0x{at:x}: slot {here} size is not stride * count") - last = order[-1] - end = at + slots[last][1] + tag_stride(slots[last][0]) * count - if end > len(data): - raise PageError(f"42 40 block at +0x{at:x} runs past the page end") - record = {"kind": "block4240", "offset": at, "vertices": count, "flags": words[23], "axis": words[27], - "slots": [[i, slots[i][0], slots[i][1]] for i in sorted(slots)]} - return record, end - - -def positions_4240(data, block): - """Decode a `42 40` block's slot-0 positions (the packed 8-byte form; see the module docstring). Returns a list of - (x, y, z) floats. Raises PageError for an axis word other than 0, 1 or 2 or a slot 0 that isn't tag 0x42.""" - at, n = block["offset"], block["vertices"] - slots = {i: (tag, off) for i, tag, off in block["slots"]} - if slots.get(0, (None,))[0] != 0x42: - raise PageError(f"42 40 block at +0x{at:x}: slot 0 is not a packed position (tag 0x42)") - bias = struct.unpack_from("<3f", data, at + 0x60) - axis = _u32(data, at + 0x6C) - scale = struct.unpack_from("<3f", data, at + 0x70) - if axis > 2: - raise PageError(f"42 40 block at +0x{at:x}: axis word {axis} is not 0, 1 or 2") - out = [] - for (q,) in struct.iter_unpack("> 8) & 0xFFFFFF) - b = bias[1] + scale[1] * (((q >> 32) & 0xFFFF) << 8 | (q & 0xFF)) - c = bias[2] + scale[2] * (q >> 48) - out.append((c, b, a) if axis == 0 else (b, c, a) if axis == 1 else (a, b, c)) - return out - - -def group_triangles(data, group): - """Yield each triangle of a parsed group as three vertex references (indices into its vertex block).""" - at, k = group["offset"], group["meshlets"] - rec_at, tri_at = at + 12, at + 12 + 16 * k - refs = struct.unpack_from(f"<{group['vertex_refs']}H", data, tri_at + 4 * group["triangles"]) - vbases = [] - vbase = 0 - for m in range(k): - vbases.append(vbase) - vbase += (_u32(data, rec_at + 16 * m) & 0x7F) + 1 - for t in struct.unpack_from(f"<{group['triangles']}I", data, tri_at): - vb = vbases[t >> 21] - yield refs[vb + (t & 0x7F)], refs[vb + ((t >> 7) & 0x7F)], refs[vb + ((t >> 14) & 0x7F)] - - -def face_agreement(positions, triangles): - """Count edges shared by exactly two triangles, and how many of those pairs have face normals within ~25 degrees - (dot > 0.9) or opposed (dot < -0.9). A wrong position decode scatters the normals; a right one leaves most - neighbours agreeing and almost none opposed.""" - normals = [] - for a, b, c in triangles: - if max(a, b, c) >= len(positions): - raise PageError("triangle references a vertex past its block") - p, q, r = positions[a], positions[b], positions[c] - u = (q[0] - p[0], q[1] - p[1], q[2] - p[2]) - v = (r[0] - p[0], r[1] - p[1], r[2] - p[2]) - n = (u[1] * v[2] - u[2] * v[1], u[2] * v[0] - u[0] * v[2], u[0] * v[1] - u[1] * v[0]) - length = math.sqrt(n[0] * n[0] + n[1] * n[1] + n[2] * n[2]) - normals.append((n[0] / length, n[1] / length, n[2] / length) if length and math.isfinite(length) else None) - faces = {} - for i, (a, b, c) in enumerate(triangles): - for e in ((a, b), (b, c), (c, a)): - faces.setdefault((min(e), max(e)), []).append(i) - out = {"shared_edges": 0, "agree": 0, "opposed": 0} - for pair in faces.values(): - if len(pair) != 2 or normals[pair[0]] is None or normals[pair[1]] is None: - continue - d = sum(x * y for x, y in zip(normals[pair[0]], normals[pair[1]])) - out["shared_edges"] += 1 - out["agree"] += d > 0.9 - out["opposed"] += d < -0.9 - return out - - -def centre_step(w2): - """Metres per step of a meshlet record's centre fields: 2^e / 16 with the exponent e in w2 bits 28-31.""" - return 2.0 ** ((w2 >> 28) & 15) / 16 - - -def meshlet_centre(w2, w3): - """The centre stored in a meshlet record's words +8 and +12, in metres (see the module docstring).""" - step = centre_step(w2) - return ((w2 & 0xFFF) - 2047) * step, (((w2 >> 12) & 0xFFF) - 2047) * step, ((w3 & 0xFFF) - 2047) * step - - -def meshlet_radius(w0): - """The bounding-sphere radius in a meshlet record's word 0 (bits 16-31, an f16), in metres.""" - return struct.unpack("> 16))[0] - - -def meshlet_cone(w3): - """The normal cone in a meshlet record's word +12: ((x, y, z) axis, cos of the half-angle), or None when bits - 12-31 are all zero (no cone).""" - if not w3 >> 12: - return None - axis = _octahedral(((w3 >> 14) & 63) / 31.5 - 1, ((w3 >> 20) & 63) / 31.5 - 1) - s = (31 - ((w3 >> 26) & 31)) / 31 - return axis, math.sqrt(max(0.0, 1 - s * s)) - - -def cone_agreement(data, group, positions): - """For each meshlet with a cone: does the axis lie within ~25 degrees of the area-weighted mean face normal, and - does every face normal lie inside the cone (dot with the axis at least cos(half-angle)), exactly or within 0.05?""" - at, k = group["offset"], group["meshlets"] - rec_at, tri_at = at + 12, at + 12 + 16 * k - refs = struct.unpack_from(f"<{group['vertex_refs']}H", data, tri_at + 4 * group["triangles"]) - out = {"meshlets": k, "cones": 0, "axis_within_25_degrees": 0, "faces_inside": 0, "faces_inside_within_0_05": 0} - vb = tb = 0 - for m in range(k): - w0, _, _, w3 = struct.unpack_from("<4I", data, rec_at + 16 * m) - vc, tc = (w0 & 0x7F) + 1, ((w0 >> 7) & 0x7F) + 1 - m_vb, m_tb = vb, tb - vb += vc - tb += tc - cone = meshlet_cone(w3) - if cone is None: - continue - axis, cos_half = cone - normals, total = [], [0.0, 0.0, 0.0] - for t in struct.unpack_from(f"<{tc}I", data, tri_at + 4 * m_tb): - idx = [refs[m_vb + ((t >> s) & 0x7F)] for s in (0, 7, 14)] - if max(idx) >= len(positions): - raise PageError("meshlet references a vertex past its block") - p, q, r = (positions[i] for i in idx) - u = (q[0] - p[0], q[1] - p[1], q[2] - p[2]) - v = (r[0] - p[0], r[1] - p[1], r[2] - p[2]) - n = (u[1] * v[2] - u[2] * v[1], u[2] * v[0] - u[0] * v[2], u[0] * v[1] - u[1] * v[0]) - length = math.sqrt(n[0] * n[0] + n[1] * n[1] + n[2] * n[2]) - if length and math.isfinite(length): - normals.append((n[0] / length, n[1] / length, n[2] / length)) - total = [a + b for a, b in zip(total, n)] - length = math.sqrt(sum(c * c for c in total)) - if not normals or not length or not math.isfinite(length): - continue - out["cones"] += 1 - out["axis_within_25_degrees"] += sum(a * c / length for a, c in zip(axis, total)) > 0.9 - smallest = min(sum(a * c for a, c in zip(axis, n)) for n in normals) - out["faces_inside"] += smallest >= cos_half - out["faces_inside_within_0_05"] += smallest >= cos_half - 0.05 - return out - - -def centre_agreement(data, group, positions): - """Compare each meshlet's stored centre with the centre of its vertices' box (axes whose difference rounds to 0 - or to at most one step of 1/16 or 1/8 m), and its stored radius with the farthest vertex from the stored centre - (covers it, covers it once the centre's rounding of at most sqrt(3)/2 steps is allowed for, and is at most 1.25 - times it plus that rounding).""" - at, k = group["offset"], group["meshlets"] - rec_at = at + 12 - refs_at = rec_at + 16 * k + 4 * group["triangles"] - refs = struct.unpack_from(f"<{group['vertex_refs']}H", data, refs_at) - out = {"meshlets": k, "default_words": 0, "coarse_steps": 0, "axes": 3 * k, "axes_exact": 0, - "axes_within_step": 0, - "radius_covers": 0, "radius_covers_within_rounding": 0, "radius_tight": 0} - vb = 0 - for m in range(k): - w0, _, w2, w3 = struct.unpack_from("<4I", data, rec_at + 16 * m) - out["default_words"] += w2 == 0x007FF7FF and w3 == 0x7FF - vc = (w0 & 0x7F) + 1 - m_vb = vb - vb += vc - pts = [positions[r] for r in refs[m_vb:m_vb + vc] if r < len(positions)] - if len(pts) != vc: - raise PageError("meshlet references a vertex past its block") - stored, size = meshlet_centre(w2, w3), centre_step(w2) - out["coarse_steps"] += (w2 >> 28) != 0 - for i in range(3): - vals = [p[i] for p in pts] - if not all(math.isfinite(v) for v in vals): - continue - diff = ((min(vals) + max(vals)) / 2 - stored[i]) / size - if math.isfinite(diff): - step = round(diff) - out["axes_exact"] += step == 0 - out["axes_within_step"] += abs(step) <= 1 - radius = meshlet_radius(w0) - if math.isfinite(radius) and all(math.isfinite(c) for p in pts for c in p): - far = max(math.dist(p, stored) for p in pts) - if math.isfinite(far): - slack = math.sqrt(3) / 2 * size - out["radius_covers"] += radius >= far * (1 - 2 ** -11) - out["radius_covers_within_rounding"] += radius + slack >= far - out["radius_tight"] += radius <= 1.25 * far + slack - return out - - -def _unorm10(x): - return x / 511.5 - 1 - - -def _octahedral(u, v): - z = 1 - abs(u) - abs(v) - x, y = u, v - if z < 0: - x, y = (1 - abs(v)) * math.copysign(1, u), (1 - abs(u)) * math.copysign(1, v) - length = math.sqrt(x * x + y * y + z * z) - return x / length, y / length, z / length - - -def normals_4240(data, block): - """Decode a `42 40` block's slot-2 normals (see the module docstring). Returns a list of unit (x, y, z), or None - when slot 2 is absent or of a type other than 1 or 7.""" - slots = {i: (tag, off) for i, tag, off in block["slots"]} - if 2 not in slots or (slots[2][0] & 15) not in (1, 7) or tag_stride(slots[2][0]) != 4: - return None - tag, off = slots[2] - at, n = block["offset"] + off, block["vertices"] - out = [] - for (w,) in struct.iter_unpack("> 10) & 1023))) - else: - v = [_unorm10((w >> s) & 1023) for s in (0, 10, 20)] - length = math.sqrt(sum(c * c for c in v)) or 1.0 - out.append(tuple(c / length for c in v)) - return out - - -def tangents_4240(data, block): - """Decode a `42 40` block's type-7 tangent slots (11 and 18). Returns {slot: [(x, y, z, sign), ...]}; sign is +1 - for bits 30-31 = 3, -1 for 0, and 0 for anything else.""" - out = {} - for slot, tag, off in block["slots"]: - if slot == 2 or tag & 15 != 7 or tag_stride(tag) != 4: - continue - at, n = block["offset"] + off, block["vertices"] - rows = [] - for (w,) in struct.iter_unpack("> s) & 1023) for s in (0, 10, 20)] - length = math.sqrt(sum(c * c for c in v)) or 1.0 - rows.append((v[0] / length, v[1] / length, v[2] / length, {3: 1, 0: -1}.get(w >> 30, 0))) - out[slot] = rows - return out - - -def tangent_agreement(normals, tangents): - """Counts for tangents against the same vertex's stored normal: |dot| < 0.05 (perpendicular) and the sign bits.""" - out = {"vertices": 0, "perpendicular": 0, "sign_plus": 0, "sign_minus": 0} - for rows in tangents.values(): - for nrm, (x, y, z, sign) in zip(normals, rows): - out["vertices"] += 1 - out["perpendicular"] += abs(nrm[0] * x + nrm[1] * y + nrm[2] * z) < 0.05 - out["sign_plus"] += sign == 1 - out["sign_minus"] += sign == -1 - return out - - -def normal_agreement(positions, normals, triangles): - """For each vertex the triangles use, compare its stored normal with the sum of its faces' (area-weighted) - normals. Counts vertices, dot > 0.99, dot > 0.9 and dot < 0.""" - acc = {} - for a, b, c in triangles: - if max(a, b, c) >= min(len(positions), len(normals)): - raise PageError("triangle references a vertex past its block") - p, q, r = positions[a], positions[b], positions[c] - u = (q[0] - p[0], q[1] - p[1], q[2] - p[2]) - v = (r[0] - p[0], r[1] - p[1], r[2] - p[2]) - n = (u[1] * v[2] - u[2] * v[1], u[2] * v[0] - u[0] * v[2], u[0] * v[1] - u[1] * v[0]) - for k in (a, b, c): - s = acc.setdefault(k, [0.0, 0.0, 0.0]) - s[0] += n[0] - s[1] += n[1] - s[2] += n[2] - out = {"vertices": 0, "within_8_degrees": 0, "within_25_degrees": 0, "opposed": 0} - for k, s in acc.items(): - length = math.sqrt(s[0] * s[0] + s[1] * s[1] + s[2] * s[2]) - if not length or not math.isfinite(length): - continue - d = sum(x * y / length for x, y in zip(normals[k], s)) - out["vertices"] += 1 - out["within_8_degrees"] += d > 0.99 - out["within_25_degrees"] += d > 0.9 - out["opposed"] += d < 0 - return out - - -def centre_distance(data, group, positions): - """Sum over a group's meshlets of the distance (per axis, in metres) between the stored centre and the centre of - the meshlet's vertex box, with these positions. The `42 40` block a group was built against gives the smallest - sum; a vertex reference past the block, or a sum that is not finite (NaN or infinite positions), gives None.""" - at, k = group["offset"], group["meshlets"] - rec_at = at + 12 - refs = struct.unpack_from(f"<{group['vertex_refs']}H", data, rec_at + 16 * k + 4 * group["triangles"]) - total = 0.0 - vb = 0 - for m in range(k): - w0, _, w2, w3 = struct.unpack_from("<4I", data, rec_at + 16 * m) - vc = (w0 & 0x7F) + 1 - m_vb = vb - vb += vc - pts = [positions[r] for r in refs[m_vb:m_vb + vc] if r < len(positions)] - if len(pts) != vc or not all(math.isfinite(c) for p in pts for c in p): - return None - stored = meshlet_centre(w2, w3) - total += sum(abs((min(p[i] for p in pts) + max(p[i] for p in pts)) / 2 - stored[i]) for i in range(3)) - return total if math.isfinite(total) else None - - -def block4240_checks(data, block): - """Count-only plausibility checks for one `42 40` block's decoded positions. Every position is bias + scale * q - with q between 0 and 2^24 - 1 (2^16 - 1 for the third field), so when the header's box is finite and inside - 300 m on every axis the counts follow from the header alone; only other blocks are decoded vertex by vertex.""" - at, n = block["offset"], block["vertices"] - bias, scale = struct.unpack_from("<3f", data, at + 0x60), struct.unpack_from("<3f", data, at + 0x70) - slot0 = {i: tag for i, tag, _ in block["slots"]}.get(0) - if slot0 == 0x42 and _u32(data, at + 0x6C) <= 2: - ends = [(b, b + s * q) for b, s, q in zip(bias, scale, (0xFFFFFF, 0xFFFFFF, 0xFFFF))] - if all(math.isfinite(e) for pair in ends for e in pair) and all(abs(e) <= 300 for pair in ends for e in pair): - return {"positions_4240": n, "positions_4240_finite": n, "positions_4240_within_300m": n} - - slots = {i: (tag, off) for i, tag, off in block["slots"]} - if slots.get(0, (None,))[0] != 0x42: - raise PageError(f"42 40 block at +0x{at:x}: slot 0 is not a packed position (tag 0x42)") - axis = _u32(data, at + 0x6C) - if axis > 2: - raise PageError(f"42 40 block at +0x{at:x}: axis word {axis} is not 0, 1 or 2") - - b0, b1, b2 = bias - s0, s1, s2 = scale - total = 0 - finite_count = 0 - within_300m_count = 0 - - slot0_off = slots[0][1] - for (q,) in struct.iter_unpack("> 8) & 0xFFFFFF) - b = b1 + s1 * (((q >> 32) & 0xFFFF) << 8 | (q & 0xFF)) - c = b2 + s2 * (q >> 48) - if math.isfinite(a) and math.isfinite(b) and math.isfinite(c): - finite_count += 1 - if abs(a) <= 300 and abs(b) <= 300 and abs(c) <= 300: - within_300m_count += 1 - - return {"positions_4240": total, "positions_4240_finite": finite_count, - "positions_4240_within_300m": within_300m_count} - - -def parse_group(data, at): - """Parse and validate a meshlet group at `at`. Returns (record, end offset).""" - head = _u32(data, at) - if not head & 0x80000000: - raise PageError(f"no group header at +0x{at:x}") - meshlets = head & 0x7FFFFFFF - if not meshlets: - raise PageError(f"group at +0x{at:x} has no meshlets") - triangles, refs = _u32(data, at + 4), _u32(data, at + 8) - rec_at = at + 12 - tri_at = rec_at + 16 * meshlets - ref_at = tri_at + 4 * triangles - end = ref_at + 2 * refs - if end > len(data): - raise PageError(f"group at +0x{at:x} runs past the page end") - vbase = tbase = 0 - full = 0 - for m in range(meshlets): - w0, w1, _, _ = struct.unpack_from("<4I", data, rec_at + 16 * m) - vcount, tcount = (w0 & 0x7F) + 1, ((w0 >> 7) & 0x7F) + 1 - if (w1 & 0xFFFF) != (vbase & 0xFFFF) or (w1 >> 16) != (tbase & 0xFFFF): - raise PageError(f"group at +0x{at:x}: meshlet {m} offsets are not running sums") - if tbase + tcount > triangles or vbase + vcount > refs: - raise PageError(f"group at +0x{at:x}: meshlet {m} runs past the group") - for t in struct.unpack_from(f"<{tcount}I", data, tri_at + 4 * tbase): - if (t >> 21) != m or max(t & 0x7F, (t >> 7) & 0x7F, (t >> 14) & 0x7F) >= vcount: - raise PageError(f"group at +0x{at:x}: bad triangle in meshlet {m}") - full += vcount == 128 - vbase += vcount - tbase += tcount - if vbase != refs or tbase != triangles: - raise PageError(f"group at +0x{at:x}: meshlet sums do not match the header") - vref = struct.unpack_from(f"<{refs}H", data, ref_at) if refs else () - span = (max(vref) + 1) if vref else 0 - record = {"kind": "group", "offset": at, "meshlets": meshlets, "triangles": triangles, - "vertex_refs": refs, "vertex_span": span, "unique_refs": len(set(vref)), - "full_meshlets": full} - return record, end - - -def is_mesh_page(data): - """True for a page that starts with a vertex block, or with a meshlet group that validates.""" - if len(data) < 16: - return False - word = struct.unpack_from("= 16 and not any(data[pos - 16:pos]) - - -def parse_page(data): - """Walk a whole page. Returns a list of chunk records; raises PageError on anything unexpected.""" - if len(data) < 4 or not is_mesh_page(data): - raise PageError("page starts with neither a vertex block nor a meshlet group") - chunks = [] - pos = 0 - while True: - while pos < len(data) and data[pos] == 0: - pos += 1 - if pos >= len(data): - break - pos &= ~15 - while _u32(data, pos) == 0: - pos += 4 - if pos % 16: - raise PageError(f"chunk at +0x{pos:x} is not 16-byte aligned") - word = _u32(data, pos) - if word == BLOCK_MAGIC: - record, pos = parse_block(data, pos) - elif word == OTHER_BLOCK_MAGIC: - try: - record, pos = parse_other_block(data, pos) - except PageError: - # a `42 40 00 00` block whose layout doesn't fit the measured strides: stop instead of guessing - chunks.append({"kind": "stop", "offset": pos, "reason": "42 40 00 00 block"}) - break - elif word & 0x80000000: - try: - record, pos = parse_group(data, pos) - except PageError as exc: - if "past the page end" in str(exc): - chunks.append({"kind": "stop", "offset": pos, "reason": "group continues past the stream"}) - break - if not _other_data(data, pos, chunks): - raise - chunks.append({"kind": "stop", "offset": pos, "reason": "non-mesh data after the chunks"}) - break - elif _other_data(data, pos, chunks): - chunks.append({"kind": "stop", "offset": pos, "reason": "non-mesh data after the chunks"}) - break - else: - raise PageError(f"unknown chunk at +0x{pos:x}") - chunks.append(record) - return chunks - - -def block_checks(data, block): - """Count-only plausibility checks for one block's streams. Returns a dict of counts.""" - n = block["vertices"] - at = block["offset"] - slots = {i: off for i, _, off in block["slots"]} - out = {"vertices": n, "positions_finite": 0, "positions_within_300m": 0, "normals_unit": 0, - "colour_alpha_255": 0, "colour_vertices": 0, "uv_finite": 0, "uv_vertices": 0, - "position_low_byte_zero": 0} - pos = struct.unpack_from(f"<{3 * n}f", data, at + slots[0]) - for v in range(n): - p = pos[3 * v:3 * v + 3] - if all(math.isfinite(c) for c in p): - out["positions_finite"] += 1 - out["positions_within_300m"] += all(abs(c) <= 300 for c in p) - if 2 in slots: - nrm = struct.unpack_from(f"<{3 * n}f", data, at + slots[2]) - for v in range(n): - q = nrm[3 * v:3 * v + 3] - if all(math.isfinite(c) for c in q) and abs(math.sqrt(sum(c * c for c in q)) - 1) < 0.02: - out["normals_unit"] += 1 - raw = data[at + slots[0]:at + slots[0] + 12 * n] - out["position_low_byte_zero"] = sum(1 for i in range(0, len(raw), 4) if raw[i] == 0) - if 1 in slots: - out["colour_vertices"] = n - out["colour_alpha_255"] = sum(1 for i in range(3, 4 * n, 4) if data[at + slots[1] + i] == 255) - for s in (3, 4): - if s in slots: - uv = struct.unpack_from(f"<{2 * n}f", data, at + slots[s]) - out["uv_vertices"] += n - out["uv_finite"] += sum(1 for v in range(n) if math.isfinite(uv[2 * v]) and math.isfinite(uv[2 * v + 1])) - return out - - -def summarise_page(data, name, faces=False, centres=False, normals=False, cones=False): - """Counts for one page. faces=True also runs face_agreement, centres=True centre_agreement, normals=True - normal_agreement and cones=True cone_agreement on every group whose vertex span matches a `42 40` block in the - page. With one such block, that block. With several, nothing - in the page orders them (a group of `Q0 Q1 G0 G1` belongs to Q0 in some pages and to Q1 in others), so the - block whose vertex boxes are closest to the group's stored centres (`centre_distance`); ties, and groups no - block fits, keep the nearest block before the group, else the first after it.""" - try: - chunks = parse_page(data) - except PageError as exc: - return {"name": name, "size": len(data), "error": str(exc)} - blocks = [c for c in chunks if c["kind"] == "block"] - others = [c for c in chunks if c["kind"] == "block4240"] - groups = [c for c in chunks if c["kind"] == "group"] - checks = {} - try: - for b in blocks: - for k, v in block_checks(data, b).items(): - checks[k] = checks.get(k, 0) + v - for b in others: - for k, v in block4240_checks(data, b).items(): - checks[k] = checks.get(k, 0) + v - if normals: - nrm = normals_4240(data, b) - if nrm is not None: - for k, v in tangent_agreement(nrm, tangents_4240(data, b)).items(): - checks["tangents_4240_" + k] = checks.get("tangents_4240_" + k, 0) + v - if faces or centres or normals or cones: - decoded = {} - for g in groups: - same = [b for b in others if b["vertices"] == g["vertex_span"]] - if not same: - continue - before = [b for b in same if b["offset"] < g["offset"]] - b = before[-1] if before else same[0] - if len(same) > 1: - checks["groups_4240_several_blocks"] = checks.get("groups_4240_several_blocks", 0) + 1 - scored = [] - for c in same: - if c["offset"] not in decoded: - decoded[c["offset"]] = positions_4240(data, c) - cost = centre_distance(data, g, decoded[c["offset"]]) - if cost is not None: - scored.append((cost, c is not b, c["offset"], c)) - best = min(scored, key=lambda x: x[:3])[3] if scored else b - if best is not b: - b = best - checks["groups_4240_block_by_centres"] = checks.get("groups_4240_block_by_centres", 0) + 1 - if b["offset"] not in decoded: - decoded[b["offset"]] = positions_4240(data, b) - if faces: - for k, v in face_agreement(decoded[b["offset"]], list(group_triangles(data, g))).items(): - checks["faces_4240_" + k] = checks.get("faces_4240_" + k, 0) + v - if centres: - for k, v in centre_agreement(data, g, decoded[b["offset"]]).items(): - checks["centres_4240_" + k] = checks.get("centres_4240_" + k, 0) + v - if cones: - for k, v in cone_agreement(data, g, decoded[b["offset"]]).items(): - checks["cones_4240_" + k] = checks.get("cones_4240_" + k, 0) + v - if normals: - nrm = normals_4240(data, b) - if nrm is not None: - tris = list(group_triangles(data, g)) - for k, v in normal_agreement(decoded[b["offset"]], nrm, tris).items(): - checks["normals_4240_" + k] = checks.get("normals_4240_" + k, 0) + v - except PageError as exc: - return {"name": name, "size": len(data), "error": str(exc)} - counts = {b["vertices"] for b in blocks} - counts_4240 = {b["vertices"] for b in others} - stop = [c for c in chunks if c["kind"] == "stop"] - return {"name": name, "size": len(data), "starts_with": chunks[0]["kind"], - "sequence": "".join({"block": "B", "block4240": "Q", "group": "G", "stop": "."}[c["kind"]] for c in chunks), - "stop": stop[0]["reason"] if stop else None, - "blocks": len(blocks), "groups": len(groups), - "blocks_with_colour": sum(1 for b in blocks if any(s[0] == 1 for s in b["slots"])), - "blocks_with_uv1": sum(1 for b in blocks if any(s[0] == 4 for s in b["slots"])), - "block_flags": sorted({b["flags"] for b in blocks}), - "tags_expected": all(b["tags_expected"] for b in blocks), - "meshlets": sum(g["meshlets"] for g in groups), - "full_meshlets": sum(g["full_meshlets"] for g in groups), - "triangles": sum(g["triangles"] for g in groups), - "vertex_refs": sum(g["vertex_refs"] for g in groups), - "groups_dense": sum(1 for g in groups if g["unique_refs"] == g["vertex_span"]), - "groups_matching_block_here": sum(1 for g in groups if g["vertex_span"] in counts), - "blocks_4240": len(others), "vertices_4240": sum(b["vertices"] for b in others), - "blocks_4240_flags": sorted({b["flags"] for b in others}), - "blocks_4240_axes": sorted({b["axis"] for b in others}), - "groups_matching_4240_block_here": sum(1 for g in groups if g["vertex_span"] in counts_4240), - "group_spans": [g["vertex_span"] for g in groups], - "block_counts": [b["vertices"] for b in blocks], - "checks": checks} - - -def iter_archive(path): - """Yield (name, inflated bytes) for every zlib stream in an RPF9 data area that is_mesh_page accepts.""" - with open(path, "rb") as fh: - if not os.fstat(fh.fileno()).st_size: - return - m = mmap.mmap(fh.fileno(), 0, access=mmap.ACCESS_READ) - try: - size = len(m) - pos = struct.unpack_from("= 8 else size - while pos < size: - match = ZHDR.search(m, pos) - if not match: - break - s = match.start() - d = zlib.decompressobj() - chunks, p = [], s - try: - while not d.eof and p < size: - block = m[p:p + (1 << 20)] - chunks.append(d.decompress(block)) - p += len(block) - if d.unused_data or d.eof: - break - out = b"".join(chunks) + d.flush() - except zlib.error: - pos = s + 1 - continue - if not d.eof or len(out) < 64: - pos = s + 1 - continue - if is_mesh_page(out): - yield f"0x{s:x}", out - pos = p - len(d.unused_data) - finally: - m.close() - - -def iter_inputs(paths, existing_report=None): - for path in paths: - if os.path.isdir(path): - for root, _, files in os.walk(path): - for f in sorted(files): - full = os.path.join(root, f) - with open(full, "rb") as fh: - head = fh.read(4) - if len(head) == 4 and (head in (b"\x63\x30\x00\x00", b"\x42\x40\x00\x00") or head[3] & 0x80): - data = head + fh.read() - if is_mesh_page(data): - if existing_report and same_output_path(existing_report, full): - raise PageError(f"--json would overwrite the input {full}") - yield os.path.relpath(full, path), data - elif path.lower().endswith(".rpf"): - yield from iter_archive(path) - else: - with open(path, "rb") as fh: - yield os.path.basename(path), fh.read() - - -def totals(pages): - keys = ("blocks", "groups", "blocks_with_colour", "blocks_with_uv1", "meshlets", "full_meshlets", - "triangles", "vertex_refs", "groups_dense", "groups_matching_block_here", "blocks_4240", - "vertices_4240", "groups_matching_4240_block_here") - out = {"pages": len(pages), "pages_parsed": sum(1 for p in pages if "error" not in p), - "block_led_pages": sum(1 for p in pages if p.get("starts_with") == "block"), - "group_led_pages": sum(1 for p in pages if p.get("starts_with") == "group"), - "block_4240_led_pages": sum(1 for p in pages if p.get("starts_with") == "block4240"), - "stopped_at_4240_block": sum(1 for p in pages if p.get("stop") == "42 40 00 00 block"), - "stopped_in_group": sum(1 for p in pages if p.get("stop") == "group continues past the stream"), - "stopped_at_other_data": sum(1 for p in pages if p.get("stop") == "non-mesh data after the chunks"), - "bytes": sum(p["size"] for p in pages)} - good = [p for p in pages if "error" not in p] - for k in keys: - out[k] = sum(p[k] for p in good) - out["vertices"] = sum(sum(p["block_counts"]) for p in good) - checks = {} - for p in good: - for k, v in p["checks"].items(): - checks[k] = checks.get(k, 0) + v - out["checks"] = checks - out["block_flags"] = sorted({f for p in good for f in p["block_flags"]}) - out["blocks_4240_flags"] = sorted({f for p in good for f in p.get("blocks_4240_flags", [])}) - out["blocks_4240_axes"] = sorted({m for p in good for m in p.get("blocks_4240_axes", [])}) - # A group's vertex span that matches a block in the same page or a neighbouring page (input order). - near = 0 - for i, p in enumerate(pages): - if "error" in p: - continue - pool = set(p["block_counts"]) - for j in (i - 1, i + 1): - if 0 <= j < len(pages) and "error" not in pages[j]: - pool.update(pages[j]["block_counts"]) - near += sum(1 for s in p["group_spans"] if s in pool) - out["groups_matching_block_near"] = near - return out - - -def _resource_pointer(system, at, base, segment, size): - if not 0 <= at <= len(system) - 8: - raise PageError("pointer field outside the system segment") - address = struct.unpack_from("> 10 - if (not flags & 1 or not count or _u32(system, layout) != 128 - or system[layout + 0xD0] != 8 or system[layout + 0x104] != 16 - or vertex_bytes < 128 + count * 8 or _u32(graphics, vertex) != OTHER_BLOCK_MAGIC): - raise PageError("unsupported vertex layout or invalid position extent") - meshlets, triangles, binding = struct.unpack_from("> 8) & 0x7FFFFF - if (stride != 4 or index_bytes < 12 or binding >> 31 or not (meshlets and triangles and refs) - or struct.unpack_from(" count or ((end + 15) & ~15) != index_bytes or any(data[end:])): - raise PageError("group references or padded extent exceed the declared layout") - return {"vertex_block": vertex, "meshlet_group": index, "vertices": count} - - -def same_output_path(first, second): - if os.path.normcase(os.path.realpath(first)) == os.path.normcase(os.path.realpath(second)): - return True - try: - return os.path.samefile(first, second) - except OSError: - return False - - -def is_scanned_input(path, input_path): - """True when a report path is one of the files the scan reads: writing it would destroy the input.""" - if same_output_path(path, input_path): - return True - if not os.path.isdir(input_path): - return False - # Reserved even before the carve writes it: other tools read /index.json as the carve manifest. - if same_output_path(path, os.path.join(input_path, "index.json")): - return True - if not os.path.isfile(path): - return False - root = os.path.normcase(os.path.abspath(input_path)) - target = os.path.normcase(os.path.abspath(path)) - if os.path.dirname(target) != root and not target.startswith(root + os.sep): - return False - base = os.path.basename(target) - return base.endswith(".bin") or base.endswith(".rpf") - - -def main(argv=None): - ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) - ap.add_argument("inputs", nargs="+", help="carved page files, folders of them, or .rpf archives") - ap.add_argument("--json", help="write per-page records and totals here") - ap.add_argument("--quiet", action="store_true") - ap.add_argument("--faces", action="store_true", - help="also count how often neighbouring faces of 42 40 geometry agree (slower)") - ap.add_argument("--normals", action="store_true", - help="also compare 42 40 slot-2 normals with their vertices' face normals, and tangents with " - "the normals (slower)") - ap.add_argument("--cones", action="store_true", - help="also compare meshlet records' normal cones with their 42 40 face normals (slower)") - ap.add_argument("--centres", action="store_true", - help="also compare meshlet records' stored centres with their 42 40 vertices (slower)") - ap.add_argument("--draw-system", help="inflated system segment paired with one graphics segment") - select = ap.add_mutually_exclusive_group() - select.add_argument("--geometry-offset", action="append", type=lambda s: int(s, 0), - help="known geometry record offset in the system segment (repeatable)") - select.add_argument("--drawable-offset", type=lambda s: int(s, 0), - help="walk geometry records from this system-segment drawable") - ap.add_argument("--lod", type=int, choices=range(4), help="drawable LOD index (default: 0)") - args = ap.parse_args(argv) - if args.lod is not None and args.drawable_offset is None: - ap.error("--lod requires --drawable-offset") - if args.json: - if os.path.isdir(args.json): - print(f"error: --json {args.json} is a directory", file=sys.stderr) - return 2 - candidates = list(args.inputs) - if args.draw_system: - candidates.append(args.draw_system) - for inp in candidates: - if is_scanned_input(args.json, inp): - print(f"error: --json would overwrite the input {inp}", file=sys.stderr) - return 2 - if args.draw_system is not None or args.geometry_offset is not None or args.drawable_offset is not None: - if not args.draw_system or (not args.geometry_offset and args.drawable_offset is None) or len(args.inputs) != 1: - ap.error("draw binding needs one graphics segment, --draw-system and a geometry or drawable offset") - try: - with open(args.draw_system, "rb") as source: - system = source.read() - with open(args.inputs[0], "rb") as source: - graphics = source.read() - rows = [] - offsets = args.geometry_offset or drawable_geometries(system, args.drawable_offset, args.lod or 0) - try: - for offset in offsets: - try: - rows.append({"geometry": offset, **draw_binding(system, graphics, offset)}) - except PageError as exc: - rows.append({"geometry": offset, "unresolved": str(exc)}) - except PageError as exc: - rows.append({"drawable": args.drawable_offset, "unresolved": str(exc)}) - report = json.dumps({"bindings": rows}, indent=2) - if args.json: - try: - with open(args.json, "w", encoding="utf-8", newline="\n") as out: - out.write(report + "\n") - except OSError as exc: - print(f"error: cannot write {args.json}: {exc.strerror or exc}", file=sys.stderr) - return 2 - if not args.quiet: - print(report) - return int(any("unresolved" in row for row in rows)) - except OSError as exc: - print(f"error: {exc}", file=sys.stderr) - return 2 - for path in args.inputs: - if not os.path.exists(path): - print(f"error: {path} does not exist", file=sys.stderr) - return 2 - existing_report = args.json if args.json and os.path.isfile(args.json) else None - try: - pages = [summarise_page(data, name, args.faces, args.centres, args.normals, args.cones) - for name, data in iter_inputs(args.inputs, existing_report)] - except PageError as exc: - print(f"error: {exc}", file=sys.stderr) - return 2 - total = totals(pages) - if not args.quiet: - for p in pages: - if "error" in p: - print(f"{p['name']}: {p['size']} bytes: ERROR {p['error']}") - else: - print(f"{p['name']}: {p['size']} bytes {p['sequence']} blocks={p['blocks']} groups={p['groups']} " - f"meshlets={p['meshlets']} triangles={p['triangles']}") - print(json.dumps(total, indent=1)) - if args.json: - try: - with open(args.json, "w", encoding="utf-8", newline="\n") as fh: - json.dump({"totals": total, "pages": pages}, fh, indent=1) - except OSError as exc: - print(f"error: cannot write {args.json}: {exc.strerror or exc}", file=sys.stderr) - return 2 - return 1 if total["pages"] != total["pages_parsed"] else 0 - - -if __name__ == "__main__": - try: # a redirected stdout is strict ANSI code page under -I; write '?' for what it cannot encode - sys.stdout.reconfigure(errors="replace") - except (AttributeError, ValueError, OSError): - pass - sys.exit(main()) diff --git a/tools/mission_tables.py b/tools/mission_tables.py deleted file mode 100644 index 9f996b868..000000000 --- a/tools/mission_tables.py +++ /dev/null @@ -1,658 +0,0 @@ -"""Read mission-state tables: 32-byte state records and the 64-byte pool elements they point at. - -`docs/mission_logic.md` describes the tables that carry mission structure in the PSIN streams of the script -archives. This tool is the reader for them. It takes inflated PSIN files (a directory of carved `.bin` -streams works too) and prints, per file, the number of records, the distinct state keys, the distinct -archetype and link hashes, and every entity it could resolve to a world transform. - -Record, 32 bytes: - - +0 u32 key joaat of the state name, lower-cased first - +4 u32 0 - +8 u32 colB an ascending band-like column; 1 on every record measured here - +12 u32 0 - +16 u32 (u16 kind at the low half, u16 offset at the high half) - +20 u32 band an ascending band counter, not always zero (0, 0, 1, 2, 2, ...) - +24 u32 (u16 n, u16 n) the entity count, stored twice - +28 u32 0 - -The offset is a byte offset. It is stored in the **high half** of the dword at +16, which is the big end of -the little-endian word; the low half is `kind`. The two u16s are not byte-swapped: the measured bytes -`03 00 80 07` resolve kind 3 and offset 0x780, not 0x8007. A record whose offset is outside the file is -still a record; it simply resolves to no entity. - -On PSIN input the two dwords at +16 and +20 are the halves of the container's u64 pointer: the low 20 -bits are a 1-based block number (the tool reads its low 16 bits as `kind`) and the bits above are the -byte offset, split between `band` (the high dword) and `poolOffset` (the high half of the low dword). -That is what the block-indexed resolution below reads; on a bare `.bin` there is no block table to -index and only the first two resolutions apply. - -Pool element, 64 bytes, 16 dwords: - - +0x00 u32 archetype/state hash - +0x04 u32 0 - +0x08 u32 0 - +0x0C u32 0 - +0x10 f32 pos.x, pos.y, pos.z (world coordinates in RAGE space, Z up) - +0x1C f32 pos.x the first position component, duplicated - +0x20 f32 rot.x, rot.y, rot.z - +0x2C f32 rot.x the first rotation component, duplicated - +0x30 u32 hash repeats the archetype hash on most elements - +0x34 u32 linkHash joaat of the lower-cased linked name (a character, for example) - +0x38 u32 0 a second hash on some elements, otherwise zero - +0x3C u32 0 zero on every element measured here - -The duplicated first component is the cheap structural test that separates a real element from a random -64-byte window. This tool requires it for both the position and the rotation, and finite values in a -plausible world range. The last two dwords are not required to be zero: a measured minority of elements -carries a second link hash in the third-last dword. Requiring `+0x38 == +0x3C == 0` would silently drop -those entities, so the reader keeps them and reports the extra hash as `extra`. - -Resolution is three-step, because the measured streams prove three encodings: - -1. **File-absolute** (the common case): the record's offset is the byte address of the element. -2. **Linked pool** (the family documented as the "next even-tagged pool chunk" rule): inside a PSIN - container, a block of records is followed by the block that holds its elements. The record offset is - then a 16-byte-unit offset into that pool block: `element = pool_block_base + (offset >> 4)`. The - measured family uses offsets such as 0x0, 0xC00, 0x1800, ... while its elements sit 0xC0 bytes apart. -3. **Block-indexed** (the container's own pointer form): `kind` is a 1-based block number, so - `block = blocks[kind - 1]` and the byte offset is `(band << 12) | (offset >> 4)`. This names a pool - even when the block is not the one after the record block, and it keeps the offset bits that do not - fit in `offset` alone. The records of one chunk are slices of one array, so their slot stride is - `(start[i + 1] - start[i]) / count[i]` when every slice agrees; a slot wider than 64 bytes then steps - by that stride rather than by 64. - -All three addresses are scored when they exist: the one that validates more of the record's `n` slots -wins, and a tie keeps the earlier reading (file-absolute, then linked pool, then block-indexed). A slot -that fails the duplicated-component test is counted as skipped, never reported as an entity. The scoring -matters on the pool-relative families, where an offset such as 0x3000 can also name an unrelated element -elsewhere in the file. - -Detection is structural rather than schema-driven so a bare `.bin` works as well as a PSIN container. A -record chunk is a run of at least two consecutive 32-byte records with the same `kind`; a lone record is -kept when it has a hash-sized key, a small `colB`, and an offset that already names an element. For PSIN -input the block table is used to find the linked pool block (skip sub-64-byte blocks and other record -blocks, then take the first block that starts with a valid element). Bytes outside a record chunk and a -resolved entity are counted as skipped. - -Usage: - python -I mission_tables.py [--json] [--limit N] - -Text output prints one line per file and one line per entity; `--json` writes `{files, summary}` with the -same numbers and the entity list (hashes as eight lowercase hex digits). -""" -import argparse -import collections -import json -import math -import os -import stat -import struct -import sys -import tempfile - -sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) -from file_mode import published_mode # noqa: E402 -from replace_retry import replace as replace_retry # noqa: E402 -try: - import psin_index # noqa: E402 -except ImportError: # a bare checkout without the sibling readers: scan raw bytes only - psin_index = None -try: - import psin_data # noqa: E402 -except ImportError: - psin_data = None - -RECORD_SIZE = 32 -ELEMENT_SIZE = 64 -MAX_ENTITIES = 4096 # a sane upper bound for the duplicated u16 count -MAX_WORLD = 1e7 # positions and rotations outside this are not world transforms -RECORD_KEY_MIN = 0x10000 # below this a u32 is a small field, not a joaat state key -POOL_SHIFT = 4 # linked-pool offsets are in 16-byte units - - -def joaat(text): - """joaat32 of a lower-cased name (Jenkins one-at-a-time, seed 0).""" - h = 0 - for byte in text.lower().encode("latin-1", "replace"): - h = (h + byte) & 0xFFFFFFFF - h = (h + (h << 10)) & 0xFFFFFFFF - h ^= h >> 6 - h = (h + (h << 3)) & 0xFFFFFFFF - h ^= h >> 11 - return (h + (h << 15)) & 0xFFFFFFFF - - -def decode_record(blob, at): - """Decode the 32-byte record at `at`, or None when the bytes are not a record. - - The only zero fields are +4, +12 and +28; `band` is deliberately not required to be zero (it is an - ascending band counter, not a reserved word). - """ - if at < 0 or at + RECORD_SIZE > len(blob): - return None - key, zero_a, col_b, zero_b, kind_offset, band, duplicated, zero_c = struct.unpack_from("<8I", blob, at) - kind = kind_offset & 0xFFFF - offset = kind_offset >> 16 - count_a, count_b = duplicated >> 16, duplicated & 0xFFFF - if key < RECORD_KEY_MIN or zero_a or zero_b or zero_c: - return None - if count_a != count_b or count_a > MAX_ENTITIES: - return None - return { - "offset": at, - "key": key, - "colB": col_b, - "kind": kind, - "poolOffset": offset, - "band": band, - "count": count_a, - } - - -def decode_element(blob, at): - """Decode the 64-byte pool element at `at`, or None when the layout does not hold.""" - if at < 0 or at + ELEMENT_SIZE > len(blob): - return None - words = struct.unpack_from("<16I", blob, at) - if words[0] == 0 or words[1] or words[2] or words[3]: - return None - if words[4] != words[7] or words[8] != words[11]: - return None - values = struct.unpack_from("<8f", blob, at + 16) - if not all(math.isfinite(v) and abs(v) <= MAX_WORLD for v in values): - return None - return { - "offset": at, - "archetype": words[0], - "pos": list(values[0:3]), - "rot": list(values[4:7]), - "hash": words[12], - "link": words[13], - "extra": words[14], - } - - -def pool_byte_offset(record): - """The byte offset a PSIN block pointer carries: `band` holds its high bits, `offset` its low bits.""" - return (record["band"] << 12) | (record["poolOffset"] >> POOL_SHIFT) - - -def block_at(blocks, record): - """(base, size) of the block a PSIN pointer names, or (None, None) when there is no such block.""" - kind = record["kind"] - if not blocks or not 1 <= kind <= len(blocks): - return None, None - _type, base, size = blocks[kind - 1] - return base, size - - -def chunk_stride(records, blocks): - """The slot stride shared by a chunk's slices of one block, or None when the bytes do not prove one. - - Consecutive records of one chunk are adjacent slices of one array, so the gap between two slice - starts is `count * stride`. The stride is returned only when every gap agrees, it is at least one - element wide, and the last slice fits in the block. A chunk whose records do not tile one block - (a single slice, or slices with gaps) returns None and the reader steps by ELEMENT_SIZE. - """ - kinds = {record["kind"] for record in records} - if len(kinds) != 1 or not blocks: - return None - base, size = block_at(blocks, records[0]) - if base is None: - return None - starts = [base + pool_byte_offset(record) for record in records] - if starts != sorted(starts) or len(set(starts)) != len(starts): - return None - strides = set() - for index in range(len(records) - 1): - count = records[index]["count"] - gap = starts[index + 1] - starts[index] - if not count or gap % count: - return None - strides.add(gap // count) - if len(strides) != 1: - return None - stride = strides.pop() - if stride < ELEMENT_SIZE or stride % 4: - return None - if starts[-1] + records[-1]["count"] * stride > base + size: - return None - return stride - - -def scan_elements(blob, end): - """Every valid pool element that starts in [0, end), keyed by its byte address.""" - found = {} - for at in range(0, max(0, end - ELEMENT_SIZE + 1), 4): - element = decode_element(blob, at) - if element is not None: - found[at] = element - return found - - -def find_chunks(blob, end, elements): - """Maximal record runs. Returns [{offset, records}] in file order. - - A run is two or more consecutive 32-byte records of the same kind. A lone record survives only when - its file-absolute offset already names a valid element, which keeps a synthetic one-record table - readable without turning every aligned window in a schema into a table. - """ - covered = bytearray(end) - chunks = [] - at = 0 - while at + RECORD_SIZE <= end: - if covered[at]: - at += 4 - continue - first = decode_record(blob, at) - if first is None: - at += 4 - continue - run = [(at, first)] - nxt = at + RECORD_SIZE - while nxt + RECORD_SIZE <= end: - following = decode_record(blob, nxt) - if following is None or following["kind"] != first["kind"]: - break - run.append((nxt, following)) - nxt += RECORD_SIZE - if len(run) >= 2 or (first["key"] >= 0x1000000 and first["colB"] <= 4 - and first["poolOffset"] in elements): - chunks.append({"offset": at, "records": run}) - for record_at, _ in run: - covered[record_at:record_at + RECORD_SIZE] = b"\x01" * RECORD_SIZE - at = nxt - else: - # A rejected lone window is not a real record, so resume scanning at the next 4-byte slot. - at += 4 - return chunks - - -def record_blocks(blob, blocks): - """The indices of blocks that are a whole table of same-kind records.""" - out = [] - for index, (_kind, base, size) in enumerate(blocks): - if size < RECORD_SIZE * 2 or size % RECORD_SIZE: - continue - first = decode_record(blob, base) - if first is None: - continue - rows = [decode_record(blob, base + at) for at in range(0, size, RECORD_SIZE)] - if all(row is not None and row["kind"] == first["kind"] for row in rows): - out.append(index) - return out - - -def linked_pool(blob, blocks, block_indices, chunk_at, elements): - """The base of the pool block linked to the record block that holds `chunk_at`, or None. - - The element block follows the record block. Sub-64-byte metadata blocks are stepped over; another - record block is skipped (its own pool follows it). The first other block must start with a valid - element, otherwise this chunk belongs to a pool family this reader does not decode. - """ - if not blocks: - return None - owner = None - for index, (_kind, base, size) in enumerate(blocks): - if base <= chunk_at < base + size: - owner = index - break - if owner is None or owner not in block_indices: - return None - for index in range(owner + 1, len(blocks)): - _kind, base, size = blocks[index] - if size < ELEMENT_SIZE: - continue - if index in block_indices: - continue - return base if base in elements else None - return None - - -def resolve(record, elements, pool_base, blocks=None, stride=None): - """Resolve one record to [(address, element)]. - - All three addresses are tried when they exist: the file-absolute address, the linked-pool address, - and the block-indexed address (`blocks[kind - 1]` plus the split pointer offset). The one that - validates more of the record's `n` slots wins; a tie keeps the earlier reading. This matters on the - pool-relative families, where an offset such as 0x3000 can also land on an unrelated element in the - file and would otherwise shadow the correct pool slot. - - Returns (entities, mode, skipped_slots). mode is "absolute", "pool", "block", "empty" or - "unresolved". - """ - count = record["count"] - if count == 0: - return [], "empty", 0 - default_step = stride or ELEMENT_SIZE - candidates = [(record["poolOffset"], "absolute", ELEMENT_SIZE)] - if pool_base is not None: - address = pool_base + (record["poolOffset"] >> POOL_SHIFT) - candidates.append((address, "pool", ELEMENT_SIZE)) - base, size = block_at(blocks, record) - if base is not None: - offset = pool_byte_offset(record) - if offset + count * default_step <= size: - candidates.append((base + offset, "block", default_step)) - best = None - for base_at, mode, slot_step in candidates: - entities = [] - skipped = 0 - for slot in range(count): - address = base_at + slot * slot_step - element = elements.get(address) - if element is None: - skipped += 1 - else: - entities.append((address, element)) - if best is None or len(entities) > len(best[0]): - best = (entities, mode, skipped) - entities, mode, skipped = best - if not entities: - return [], "unresolved", skipped - return entities, mode, skipped - - -def parse_blob(blob, name=""): - """Parse one inflated stream (PSIN or bare bytes) into the tool's per-file record.""" - first_section = len(blob) - blocks = [] - if psin_index is not None and blob[:4] == b"PSIN": - parsed = psin_index.parse(blob) - if parsed is not None: - first_section = min(max(parsed["first_section"], 0), len(blob)) - if psin_data is not None: - try: - blocks, _fill = psin_data.block_table(blob, first_section) - except (ValueError, struct.error): - blocks = [] - end = first_section - elements = scan_elements(blob, end) - chunks = find_chunks(blob, end, elements) - table_blocks = record_blocks(blob, blocks) if blocks else [] - if table_blocks: - known = {at for chunk in chunks for at, _record in chunk["records"]} - for index in table_blocks: - _kind, base, size = blocks[index] - addresses = list(range(base, base + size, RECORD_SIZE)) - if any(address in known for address in addresses): - continue - rows = [(address, decode_record(blob, address)) for address in addresses] - if all(row is not None for _address, row in rows): - chunks.append({"offset": base, "records": rows}) - known.update(addresses) - chunks.sort(key=lambda chunk: chunk["offset"]) - - records = [] - entity_by_address = {} - states = collections.defaultdict(lambda: {"key": 0, "records": 0, "slots": 0, "entities": 0}) - skipped_slots = 0 - unresolved = 0 - for chunk in chunks: - pool_base = linked_pool(blob, blocks, table_blocks, chunk["offset"], elements) - stride = chunk_stride([record for _at, record in chunk["records"]], blocks) - for _at, record in chunk["records"]: - records.append(record) - state = states[record["key"]] - state["key"] = record["key"] - state["records"] += 1 - found, _mode, skipped = resolve(record, elements, pool_base, blocks, stride) - skipped_slots += skipped - if not found and record["count"]: - unresolved += 1 - for address, element in found: - state["slots"] += 1 - entity_by_address.setdefault(address, element) - for state in states.values(): - state["entities"] = state["slots"] - - entities = [entity_by_address[address] for address in sorted(entity_by_address)] - covered = bytearray(end) - for chunk in chunks: - for at, _record in chunk["records"]: - covered[at:at + RECORD_SIZE] = b"\x01" * RECORD_SIZE - for address in entity_by_address: - covered[address:address + ELEMENT_SIZE] = b"\x01" * ELEMENT_SIZE - skipped_bytes = end - sum(covered) - trailing = end - while trailing > 0 and not covered[trailing - 1]: - trailing -= 1 - trailing_bytes = end - trailing - - return { - "file": name, - "size": len(blob), - "scan_bytes": end, - "records": len(records), - "chunks": len(chunks), - "record_blocks": len(table_blocks), - "state_keys": len(states), - "entities": len(entities), - "entity_slots": sum(state["slots"] for state in states.values()), - "unresolved_records": unresolved, - "skipped_slots": skipped_slots, - "skipped_bytes": skipped_bytes, - "trailing_bytes": trailing_bytes, - "distinct_archetypes": len({entity["archetype"] for entity in entities}), - "distinct_links": len({entity["link"] for entity in entities}), - "states": [ - { - "key": state["key"], - "records": state["records"], - "entities": state["entities"], - } - for _key, state in sorted(states.items()) - ], - "entity_list": [ - { - "archetype": entity["archetype"], - "link": entity["link"], - "hash": entity["hash"], - "extra": entity["extra"], - "pos": entity["pos"], - "rot": entity["rot"], - "offset": entity["offset"], - } - for entity in entities - ], - } - - -def parse_file(path): - with open(path, "rb") as handle: - blob = handle.read() - return parse_blob(blob, os.path.basename(path)) - - -def files_in(src): - """(path, name) pairs, sorted by name for a directory; one pair for a file.""" - if os.path.isfile(src): - yield src, os.path.basename(src) - return - for name in sorted(os.listdir(src)): - if not name.endswith(".bin"): - continue - path = os.path.join(src, name) - if os.path.isfile(path): - yield path, name - - -def collect(src, limit=None): - files = [] - for path, name in files_in(src): - record = parse_file(path) - record["file"] = name - files.append(record) - if limit and len(files) >= limit: - break - return files - - -def summarize(files): - """Totals over files; the distinct hash counts are over the union, not a sum of per-file counts.""" - archetypes = set() - links = set() - states = set() - for record in files: - states.update(state["key"] for state in record["states"]) - archetypes.update(entity["archetype"] for entity in record["entity_list"]) - links.update(entity["link"] for entity in record["entity_list"]) - return { - "files": len(files), - "records": sum(record["records"] for record in files), - "chunks": sum(record["chunks"] for record in files), - "state_keys": len(states), - "entities": sum(record["entities"] for record in files), - "entity_slots": sum(record["entity_slots"] for record in files), - "distinct_archetypes": len(archetypes), - "distinct_links": len(links), - "unresolved_records": sum(record["unresolved_records"] for record in files), - "skipped_slots": sum(record["skipped_slots"] for record in files), - "skipped_bytes": sum(record["skipped_bytes"] for record in files), - } - - -def _hex(value): - return f"{value:08x}" - - -def _json_record(record): - """The same record with hashes formatted as eight hex digits.""" - out = dict(record) - out["states"] = [dict(state, key=_hex(state["key"])) for state in record["states"]] - out["entity_list"] = [ - { - "archetype": _hex(entity["archetype"]), - "link": _hex(entity["link"]), - "hash": _hex(entity["hash"]), - "extra": _hex(entity["extra"]), - "pos": [round(value, 6) for value in entity["pos"]], - "rot": [round(value, 6) for value in entity["rot"]], - "offset": entity["offset"], - } - for entity in record["entity_list"] - ] - return out - - -def count(text): - """--limit: a positive file count.""" - try: - value = int(text) - except ValueError: - raise argparse.ArgumentTypeError(f"invalid int value: {text!r}") from None - if value < 1: - raise argparse.ArgumentTypeError("must be at least 1") - return value - - -def write_json(path, payload): - """Write `payload` as formatted JSON, staging regular files through a sibling temporary file.""" - destination = os.path.realpath(path) - try: - dest_stat = os.stat(destination) - except FileNotFoundError: - dest_stat = None - if dest_stat is not None and not stat.S_ISREG(dest_stat.st_mode): - with open(destination, "w", encoding="utf-8", newline="\n") as handle: - json.dump(payload, handle, indent=1) - handle.write("\n") - return - parent = os.path.dirname(destination) or "." - os.makedirs(parent, exist_ok=True) - if dest_stat is not None: - os.close(os.open(destination, os.O_WRONLY)) - staged_path = None - try: - with tempfile.NamedTemporaryFile( - mode="w", - encoding="utf-8", - newline="\n", - delete=False, - dir=parent, - prefix=".mission_tables-", - suffix=".tmp", - ) as staged: - staged_path = staged.name - json.dump(payload, staged, indent=1) - staged.write("\n") - if os.name != "nt": - os.chmod(staged_path, published_mode(destination)) - replace_retry(staged_path, destination) - staged_path = None - finally: - if staged_path is not None: - try: - os.unlink(staged_path) - except OSError: - pass - - -def main(argv=None): - ap = argparse.ArgumentParser(description="Read mission-state tables from inflated PSIN streams.") - ap.add_argument("src", help="PSIN file or directory of carved .bin streams") - ap.add_argument("--json", action="store_true", help="write the files and summary as JSON") - ap.add_argument("--out", help="write the files and summary as JSON to this file") - ap.add_argument("--limit", type=count, help="stop after this many files") - args = ap.parse_args(argv) - if not os.path.exists(args.src): - print(f"ERROR: {args.src}: no such file or folder", file=sys.stderr) - return 2 - if os.path.isfile(args.src): - # A lone argument is the inflated PSIN file; the bare carved streams are what a folder holds. - try: - with open(args.src, "rb") as handle: - magic = handle.read(4) - except OSError as error: - print(f"ERROR: {args.src}: {error}", file=sys.stderr) - return 2 - if magic != b"PSIN": - print(f"ERROR: {args.src}: not a PSIN container", file=sys.stderr) - return 2 - try: - files = collect(args.src, args.limit) - except OSError as error: - print(f"ERROR: {args.src}: {error}", file=sys.stderr) - return 2 - summary = summarize(files) - if args.out: - payload = {"files": [_json_record(record) for record in files], "summary": summary} - try: - write_json(args.out, payload) - except OSError as error: - reason = error.strerror or str(error) - print(f"ERROR: cannot write {args.out}: {reason}", file=sys.stderr) - return 2 - if args.json: - json.dump({"files": [_json_record(record) for record in files], "summary": summary}, - sys.stdout, indent=1) - sys.stdout.write("\n") - return 0 - if args.out: - return 0 - for record in files: - print(f"{record['file']} size={record['size']} records={record['records']} " - f"chunks={record['chunks']} states={record['state_keys']} " - f"entities={record['entities']} archetypes={record['distinct_archetypes']} " - f"links={record['distinct_links']} unresolved={record['unresolved_records']} " - f"skipped_slots={record['skipped_slots']} skipped_bytes={record['skipped_bytes']}") - for entity in record["entity_list"]: - pos = ", ".join(f"{value:.3f}" for value in entity["pos"]) - rot = ", ".join(f"{value:.3f}" for value in entity["rot"]) - print(f" entity {_hex(entity['archetype'])} {_hex(entity['link'])} " - f"pos=({pos}) rot=({rot}) +0x{entity['offset']:x}") - print(f"{summary['files']} files, {summary['records']} records in {summary['chunks']} chunks; " - f"{summary['state_keys']} distinct state keys; {summary['entities']} entities " - f"({summary['entity_slots']} slots), {summary['distinct_archetypes']} archetypes, " - f"{summary['distinct_links']} links; unresolved {summary['unresolved_records']}, " - f"skipped slots {summary['skipped_slots']}, skipped bytes {summary['skipped_bytes']}") - return 0 - - -if __name__ == "__main__": - try: # a redirected stdout is strict ANSI code page under -I; write '?' for what it cannot encode - sys.stdout.reconfigure(errors="replace") - except (AttributeError, ValueError, OSError): - pass - sys.exit(main()) diff --git a/tools/mode_diff.py b/tools/mode_diff.py deleted file mode 100644 index b46b727ac..000000000 --- a/tools/mode_diff.py +++ /dev/null @@ -1,1095 +0,0 @@ -r"""Differential fuzzer for MODE.FP_ROUND[3:2], the f16/f64 rounding field shaders switch at run time (standard -library only). - -The corpus writes this field 9,417 times (docs/design.md, Known approximations). -`s_setreg_imm32_b32 hwreg(HW_REG_MODE, 2, 2), 3` sets f16 rounding toward zero and `..., 0` sets it back to nearest -even; `s_round_mode` writes the same two bits (bits 3:2 of its immediate). While the field is toward zero, every VALU -f16 result except the seven transcendentals rounds toward zero, and a finite overflow gives +-65504. No other fuzzer -writes MODE (tools/f32_fuzz.py only reads it with s_getreg_b32), so the f16 fuzzers only ever run in nearest-even -mode. - -Two oracles, three stages: - - * Exact reference (the sweep and the random programs). Seeded straight-line programs mix MODE writes with the - 19 ops below. The four exported mrt0 words go to two places: - - the reference below, which tracks the mode and rounds the exact rational result (fractions.Fraction) once, - in that mode. It is written from the rules docs/design.md records and shares no code with the translator; - - tools/rdna2spirv.py, with the SPIR-V run in tests/semantic/spirv_mini_interp.py. - The comparison is bit for bit, except that a NaN the reference computed matches any NaN (payloads are not - modelled). A NaN that only passes through v_ldexp_f16 is compared exactly. - * Mode invariance (the invariance stage). Programs of ops whose result must not depend on the f16 rounding field - (the seven f16 transcendentals, the exact f16 ops, f16-to-int conversions, v_cvt_pkrtz_f16_f32, f32 arithmetic) - run with their MODE writes and again with every MODE write removed. The words must be identical. - -Reference rules (docs/design.md, "f16 rounding" and "Known approximations"): - - f16 operands and results keep denormals (denorm_mode_16_64 = 3). An f32 operand of v_fma_mix* reads as a zero of - its sign when it is denormal (denorm_mode_32 = 0, SHADER-298). - - add, sub, subrev, mul, fma, fmac, fmamk, fmaak, the packed forms and v_fma_mix{lo,hi}_f16: the exact result, - rounded once. Nearest even gives +-inf from 65520 up. Toward zero truncates, and a finite result past 65504 - gives +-65504. An exact zero sum is -0 only when both terms are -0. - - v_cvt_f16_f32, v_cvt_f16_u16, v_cvt_f16_i16: the source value rounded the same way. VOP3 mul:2 / mul:4 / div:2 - on v_cvt_f16_f32 applies to the rounded f16, as Gen.f16_omod documents (a zero or denormal gives +0, div:2 of - a smallest normal gives a signed zero, finite overflow gives +-inf, or +-65504 toward zero), then clamp. - - v_ldexp_f16: S0 * 2^S1.i16, rounded. Zero gives a signed zero, inf and NaN pass through. With clamp, a negative - result or a NaN gives +0. The toward-zero words are #5310's change and are not measured on hardware. - - v_fract_f16: S0 - floor(S0), rounded (fract(-(2^-10 + 2^-20)) = 1 - 2^-10 - 2^-20 needs 20 bits, so the mode - decides it). A result of 1.0 becomes 0x3bff. An infinity gives a NaN, or +0 with clamp. - - clamp: to [0, 1] on the exact value, before rounding. Not judged on a NaN or a -0 (FClamp is undefined there in - SPIR-V, and docs/design.md does not pin it). A program whose translation hits a value SPIR-V leaves undefined - (OpFDiv by zero, Log2 or Sqrt of a negative, which the mini interpreter refuses) is not judged either. - - The mode starts at nearest even. A write of 3 selects toward zero and a write of 0 selects nearest even (the - two values the corpus uses; the translator refuses 1 and 2). - -Program shape: v8..v15 seeded with v_mov_b32. Before an op, its operands are usually reseeded with values built for -it: an addend a few binades below the other operand, an f32 word near an f16 tie, the overflow edge, an f16 denormal, -a small negative for fract, an integer past 2048. Destinations are v8..v11, so later ops also read earlier results. -The program ends with `exp mrt0 v8, v9, v10, v11`. The sweep runs every form of every op under each of the four -MODE writes (setreg 0 / 3, s_round_mode 0x0 / 0xc). The random programs put a MODE write before about one op in -three. - -Not covered: v_add_f64 (the mini interpreter has no binary64 arithmetic; tests/test_mode_round.py checks it against -a Fraction oracle), v_interp_p2_f16 (needs a pixel input), the _sdwa and _dpp forms (tools/sdwa_diff.py's domain), -omod on f16 arithmetic (SHADER-297, open) and op_sel on an f32 operand of v_fma_mix*. - -Exit code 0 when every judged program matches, 1 on a mismatch (the first one is printed with its listing) or a -translator skip (every generated form is one the translator takes), 2 on a harness error. - -Usage: - python -I tools/mode_diff.py [--programs N] [--invariance N] [--seed S] [--max-ops N] [--ops v_add_f16,...] - python -I tools/mode_diff.py --list-ops - python -I tools/mode_diff.py --self-test -""" -import argparse -import gc -import math -import os -import random -import re -import struct -import sys -import tempfile -import warnings -from collections import Counter -from fractions import Fraction - -HERE = os.path.dirname(os.path.abspath(__file__)) -TOOLS_DIR = os.environ.get("LEONIDA_TOOLS_DIR") or HERE -sys.dont_write_bytecode = True -if TOOLS_DIR not in sys.path: - sys.path.insert(0, TOOLS_DIR) -SEM_DIR = os.path.join(os.path.dirname(HERE), "tests", "semantic") -if SEM_DIR not in sys.path: - sys.path.insert(0, SEM_DIR) - -import rdna2spirv # noqa: E402 -from spirv_mini_interp import UnsupportedConstruct, run_fragment # noqa: E402 - -M32 = 0xFFFFFFFF -M16 = 0xFFFF -STUB_DXBC = b"DXBC" + bytes(24) + struct.pack(" (forms, number of sources). Forms: e32 / e64 (printed suffix), vop3 / vop3p / k (no suffix). -FAMILY = { - "v_add_f16": (("e32", "e64"), 2), "v_sub_f16": (("e32", "e64"), 2), "v_subrev_f16": (("e32", "e64"), 2), - "v_mul_f16": (("e32", "e64"), 2), "v_fma_f16": (("vop3",), 3), "v_fmac_f16": (("e32", "e64"), 2), - "v_fmamk_f16": (("k",), 2), "v_fmaak_f16": (("k",), 2), - "v_pk_add_f16": (("vop3p",), 2), "v_pk_mul_f16": (("vop3p",), 2), "v_pk_fma_f16": (("vop3p",), 3), - "v_pk_fmac_f16": (("e32",), 2), - "v_fma_mixlo_f16": (("vop3p",), 3), "v_fma_mixhi_f16": (("vop3p",), 3), - "v_cvt_f16_f32": (("e32", "e64"), 1), "v_cvt_f16_u16": (("e32", "e64"), 1), "v_cvt_f16_i16": (("e32", "e64"), 1), - "v_ldexp_f16": (("e32", "e64"), 2), "v_fract_f16": (("e32", "e64"), 1), -} -OP_FORMS = { - "v_add_f16": "_e32 d, s0, s1 | _e64 d, [-][|]s0[|], [-][|]s1[|] [op_sel:[a,b,d]] [clamp]", - "v_sub_f16": "as v_add_f16", - "v_subrev_f16": "as v_add_f16 (S1 - S0)", - "v_mul_f16": "as v_add_f16", - "v_fma_f16": "d, [-][|]s0[|], [-][|]s1[|], [-][|]s2[|] [op_sel:[a,b,c,d]] [clamp]", - "v_fmac_f16": "_e32 d, s0, s1 | _e64 d, [-][|]s0[|], [-][|]s1[|] [clamp] (d is the addend)", - "v_fmamk_f16": "d, s0, K, s1 (s0 * K + s1)", - "v_fmaak_f16": "d, s0, s1, K (s0 * s1 + K)", - "v_pk_add_f16": "d, s0, s1 [op_sel:[a,b]] [op_sel_hi:[a,b]] [neg_lo:[a,b]] [neg_hi:[a,b]] [clamp]", - "v_pk_mul_f16": "as v_pk_add_f16", - "v_pk_fma_f16": "d, s0, s1, s2 [op_sel:[a,b,c]] [op_sel_hi:[a,b,c]] [neg_lo:[a,b,c]] [neg_hi:[a,b,c]] [clamp]", - "v_pk_fmac_f16": "_e32 d, s0, s1 (both halves of d are the addends)", - "v_fma_mixlo_f16": "d, [-][|]s0[|], [-][|]s1[|], [-][|]s2[|] op_sel:[a,b,c] op_sel_hi:[x,y,z] [clamp]", - "v_fma_mixhi_f16": "as v_fma_mixlo_f16, result in the high half", - "v_cvt_f16_f32": "_e32 d, s0 | _e64 d, [-][|]s0[|] [mul:2|mul:4|div:2] [clamp]", - "v_cvt_f16_u16": "_e32 d, s0 | _e64 d, s0 [op_sel:[a,d]] [clamp]", - "v_cvt_f16_i16": "as v_cvt_f16_u16", - "v_ldexp_f16": "_e32 d, s0, s1 | _e64 d, [-][|]s0[|], s1 [op_sel:[a,b,d]] [clamp]", - "v_fract_f16": "_e32 d, s0 | _e64 d, [-][|]s0[|] [op_sel:[a,d]] [clamp]", -} -# The invariance stage: results that must not depend on MODE.FP_ROUND[3:2]. -INVARIANT = ( - "v_rcp_f16", "v_rsq_f16", "v_sqrt_f16", "v_exp_f16", "v_log_f16", "v_sin_f16", "v_cos_f16", - "v_floor_f16", "v_ceil_f16", "v_trunc_f16", "v_rndne_f16", "v_frexp_mant_f16", "v_frexp_exp_i16_f16", - "v_cvt_f32_f16", "v_cvt_i16_f16", "v_cvt_u16_f16", "v_max_f16", "v_min_f16", "v_cvt_pkrtz_f16_f32", - "v_add_f32", "v_sub_f32", "v_mul_f32", "v_fma_f32", "v_fma_mix_f32", "v_med3_f16", "v_pk_max_f16", - "v_pk_min_f16", -) -INV_UNARY_OPSEL = INVARIANT[:13] # f16 VOP1 ops that also take an _e64 op_sel:[a,d] -INV_VOP2 = ("v_max_f16", "v_min_f16", "v_cvt_pkrtz_f16_f32", "v_add_f32", "v_sub_f32", "v_mul_f32") -INV_VOP3 = ("v_fma_f32", "v_fma_mix_f32", "v_med3_f16") -INV_VOP3P = ("v_pk_max_f16", "v_pk_min_f16") - -GRID_PER_PROGRAM = 4 - - -class HarnessError(Exception): - """The generator or the reference met something outside the modelled forms.""" - - -class NotJudged(Exception): - """The reference does not judge this program (the reason is counted).""" - - -# ---- numbers: (kind, sign, magnitude), kind "num" / "inf" / "nan", magnitude a Fraction ---- - -ZERO = ("num", 0, Fraction(0)) -ONE = ("num", 0, Fraction(1)) -NAN = ("nan", 0, Fraction(0)) -HALF = Fraction(1, 2) - - -def ilog2(q): - """floor(log2(q)) for a Fraction q > 0.""" - e = q.numerator.bit_length() - q.denominator.bit_length() - return e if Fraction(2) ** e <= q else e - 1 - - -def dec16(h): - s, e, m = h >> 15 & 1, h >> 10 & 31, h & 0x3FF - if e == 31: - return NAN if m else ("inf", s, Fraction(0)) - return ("num", s, Fraction(m, 1 << 24) if e == 0 else Fraction(1024 + m) * Fraction(2) ** (e - 25)) - - -def dec32(w, flush=False): - s, e, m = w >> 31 & 1, w >> 23 & 255, w & 0x7FFFFF - if e == 255: - return NAN if m else ("inf", s, Fraction(0)) - if e == 0: - return ("num", s, Fraction(0) if flush else Fraction(m) * Fraction(2) ** -149) - return ("num", s, Fraction((1 << 23) + m) * Fraction(2) ** (e - 150)) - - -def neg(v): - return v if v[0] == "nan" else (v[0], v[1] ^ 1, v[2]) - - -def fabs(v): - return v if v[0] == "nan" else (v[0], 0, v[2]) - - -def signed(v): - return -v[2] if v[1] else v[2] - - -def add(x, y): - if x[0] == "nan" or y[0] == "nan": - return NAN - if x[0] == "inf" or y[0] == "inf": - if x[0] == y[0] == "inf" and x[1] != y[1]: - return NAN - return x if x[0] == "inf" else y - s = signed(x) + signed(y) - if s == 0: # an exact zero is +0 in both modes unless both terms are -0 - return ("num", x[1] & y[1], Fraction(0)) - return ("num", int(s < 0), abs(s)) - - -def mul(x, y): - if x[0] == "nan" or y[0] == "nan": - return NAN - s = x[1] ^ y[1] - if x[0] == "inf" or y[0] == "inf": - if (x[0] == "num" and x[2] == 0) or (y[0] == "num" and y[2] == 0): - return NAN - return ("inf", s, Fraction(0)) - return ("num", s, x[2] * y[2]) - - -def fma(x, y, z): - return add(mul(x, y), z) - - -def round16(v, rtz): - """f16 bits of v rounded once: nearest even or toward zero (denormals kept). None for a NaN.""" - kind, s, mag = v - if kind == "nan": - return None - if kind == "inf": - return s << 15 | 0x7C00 - if mag == 0: - return s << 15 - e = ilog2(mag) - if e > 15: - return s << 15 | (0x7BFF if rtz else 0x7C00) - e = max(e, -14) - q = mag / Fraction(2) ** (e - 10) # [1024, 2048) for a normal, [0, 1024) below the normal range - n = q.numerator // q.denominator - rem = q - n - if not rtz and (rem > HALF or (rem == HALF and n & 1)): - n += 1 - return s << 15 | (((e + 14) << 10) + n) # n = 2048 carries into the exponent (0x7c00 past 65504) - - -def clamp01(v): - """VOP3 clamp through FClamp: [0, 1] on the exact value. A NaN or a -0 is not judged.""" - kind, s, mag = v - if kind == "nan": - raise NotJudged("clamp of a NaN") - if s: - if kind == "num" and mag == 0: - raise NotJudged("clamp of -0") - return ZERO - if kind == "inf" or mag > 1: - return ONE - return v - - -def is_nan16(h): - return h & 0x7C00 == 0x7C00 and h & 0x3FF != 0 - - -def omod16(h, k, rtz): - """Gen.f16_omod on v_cvt_f16_f32's rounded bits.""" - if h is None: - return None - e, sign = h >> 10 & 31, h & 0x8000 - if e == 31: - return h - if e == 0: - return 0 - if k == "div:2": - return sign if e == 1 else h - 0x400 - d = 1 if k == "mul:2" else 2 - if e >= 31 - d: - return sign | (0x7BFF if rtz else 0x7C00) - return h + (d << 10) - - -# ---- the program text ---- - -_SRC = re.compile(r"(-?)(\|?)v(\d+)\|?$") -_BITS = re.compile(r"(op_sel|op_sel_hi|neg_lo|neg_hi):\[([01](?:,[01])*)\]$") - - -def split_line(line): - """-> (op, operands, modifiers) for the generated forms: operands end at the first token without a comma.""" - toks = line.split() - args, i = [], 1 - while i < len(toks): - t = toks[i] - i += 1 - args.append(t.rstrip(",")) - if not t.endswith(","): - break - return toks[0], args, toks[i:] - - -def bits(mods, name, n, default=0): - for m in mods: - g = _BITS.match(m) - if g and g.group(1) == name: - return ([int(b) for b in g.group(2).split(",")] + [0] * n)[:n] - return [default] * n - - -def reg(tok): - g = _SRC.match(tok) - if not g: - raise HarnessError(f"operand {tok!r}") - return int(g.group(3)), bool(g.group(1)), bool(g.group(2)) - - -class Machine: - """The VGPR file as words, the halves that hold a computed NaN (payload not modelled), and the f16 rounding mode.""" - - def __init__(self): - self.v = [0] * 256 - self.unk = set() - self.mode = 0 - - def write_word(self, r, w): - self.v[r] = w & M32 - self.unk.discard((r, 0)) - self.unk.discard((r, 1)) - - def half(self, r, hi): - return None if (r, hi) in self.unk else self.v[r] >> (16 * hi) & M16 - - def set_half(self, r, hi, h): - if h is None: - self.unk.add((r, hi)) - h = 0x7E00 - else: - self.unk.discard((r, hi)) - sh = 16 * hi - self.v[r] = (self.v[r] & ~(M16 << sh) & M32) | (h & M16) << sh - - def word(self, r): - if (r, 0) in self.unk or (r, 1) in self.unk: - raise NotJudged("reads a computed NaN half as f32 or integer bits") - return self.v[r] - - def int_half(self, r, hi): - h = self.half(r, hi) - if h is None: - raise NotJudged("reads a computed NaN half as an integer") - return h - - def f16(self, tok, hi): - """An f16 operand (register half, or the literal K) with its neg/abs.""" - if tok.startswith("0x"): - return dec16(int(tok, 16) & M16) - r, n, a = reg(tok) - h = self.half(r, hi) - v = NAN if h is None else dec16(h) - return neg(fabs(v) if a else v) if n else (fabs(v) if a else v) - - def f32(self, tok, flush=False): - r, n, a = reg(tok) - v = dec32(self.word(r), flush) - return neg(fabs(v) if a else v) if n else (fabs(v) if a else v) - - -def _note(events, op, v, rtz): - if events is None or v[0] != "num" or v[2] == 0: - return - ev = events.setdefault(op, Counter()) - ev["toward zero" if rtz else "nearest"] += 1 - if round16(v, True) != round16(v, False): - ev["modes differ"] += 1 - if v[2] > 65504: - ev["overflow"] += 1 - elif v[2] < Fraction(1, 1 << 14): - ev["denormal"] += 1 - e = max(ilog2(v[2]), -14) - q = v[2] / Fraction(2) ** (e - 10) - if q - q.numerator // q.denominator == HALF: - ev["tie"] += 1 - - -def _out(mc, op, v, events): - rtz = mc.mode == RTZ - _note(events, op, v, rtz) - return round16(v, rtz) - - -def base_op(op): - return re.sub(r"_e(32|64)$", "", op) - - -def step(line, mc, events=None): - """Run one line on the reference machine.""" - if line.startswith("s_setreg_imm32_b32 hwreg(HW_REG_MODE, 2, 2),"): - mc.mode = int(line.rsplit(",", 1)[1], 0) & 3 - return - op, args, mods = split_line(line) - if op == "s_round_mode": - mc.mode = int(args[0], 0) >> 2 & 3 - return - if op == "v_mov_b32": - mc.write_word(reg(args[0])[0], int(args[1], 0)) - return - b = base_op(op) - if mc.mode not in (0, RTZ): - raise HarnessError(f"mode {mc.mode}") - clamp = "clamp" in mods - d = reg(args[0])[0] - if b in ("v_add_f16", "v_sub_f16", "v_subrev_f16", "v_mul_f16"): - sel = bits(mods, "op_sel", 3) - x, y = mc.f16(args[1], sel[0]), mc.f16(args[2], sel[1]) - v = {"v_add_f16": lambda: add(x, y), "v_sub_f16": lambda: add(x, neg(y)), - "v_subrev_f16": lambda: add(y, neg(x)), "v_mul_f16": lambda: mul(x, y)}[b]() - mc.set_half(d, sel[2], _out(mc, b, clamp01(v) if clamp else v, events)) - elif b == "v_fma_f16": - sel = bits(mods, "op_sel", 4) - v = fma(*(mc.f16(t, sel[i]) for i, t in enumerate(args[1:4]))) - mc.set_half(d, sel[3], _out(mc, b, clamp01(v) if clamp else v, events)) - elif b == "v_fmac_f16": - v = fma(mc.f16(args[1], 0), mc.f16(args[2], 0), mc.f16(args[0], 0)) - mc.set_half(d, 0, _out(mc, b, clamp01(v) if clamp else v, events)) - elif b in ("v_fmamk_f16", "v_fmaak_f16"): - v = fma(*(mc.f16(t, 0) for t in args[1:4])) # in print order both are a[1] * a[2] + a[3] - mc.set_half(d, 0, _out(mc, b, v, events)) - elif b in ("v_pk_add_f16", "v_pk_mul_f16", "v_pk_fma_f16"): - n = 3 if b == "v_pk_fma_f16" else 2 - sel, selhi = bits(mods, "op_sel", n), bits(mods, "op_sel_hi", n, 1) - nlo, nhi = bits(mods, "neg_lo", n), bits(mods, "neg_hi", n) - out = [] - for lane, (hs, ns) in enumerate(((sel, nlo), (selhi, nhi))): - vals = [mc.f16(t, hs[i]) for i, t in enumerate(args[1:1 + n])] - vals = [neg(x) if ns[i] else x for i, x in enumerate(vals)] - v = add(*vals) if b == "v_pk_add_f16" else mul(*vals) if b == "v_pk_mul_f16" else fma(*vals) - out.append(_out(mc, b, clamp01(v) if clamp else v, events)) - mc.set_half(d, 0, out[0]) - mc.set_half(d, 1, out[1]) - elif b == "v_pk_fmac_f16": - out = [_out(mc, b, fma(mc.f16(args[1], k), mc.f16(args[2], k), mc.f16(args[0], k)), events) for k in (0, 1)] - mc.set_half(d, 0, out[0]) - mc.set_half(d, 1, out[1]) - elif b in ("v_fma_mixlo_f16", "v_fma_mixhi_f16"): - sel, selhi = bits(mods, "op_sel", 3), bits(mods, "op_sel_hi", 3) - vals = [mc.f16(t, sel[i]) if selhi[i] else mc.f32(t, flush=True) for i, t in enumerate(args[1:4])] - v = fma(*vals) - mc.set_half(d, int(b == "v_fma_mixhi_f16"), _out(mc, b, clamp01(v) if clamp else v, events)) - elif b == "v_cvt_f16_f32": - h = _out(mc, b, mc.f32(args[1]), events) - k = next((m for m in mods if m in ("mul:2", "mul:4", "div:2")), None) - if k: - h = omod16(h, k, mc.mode == RTZ) - if clamp: - if h is None or is_nan16(h): - raise NotJudged("clamp of a NaN") - if h == 0x8000: - raise NotJudged("clamp of -0") - h = 0 if h & 0x8000 else min(h, 0x3C00) - mc.set_half(d, 0, h) - elif b in ("v_cvt_f16_u16", "v_cvt_f16_i16"): - sel = bits(mods, "op_sel", 2) - u = mc.int_half(reg(args[1])[0], sel[0]) - i = u - 0x10000 if b == "v_cvt_f16_i16" and u & 0x8000 else u - v = ("num", int(i < 0), Fraction(abs(i))) - mc.set_half(d, sel[1], _out(mc, b, clamp01(v) if clamp else v, events)) - elif b == "v_ldexp_f16": - sel = bits(mods, "op_sel", 3) - r, n, a = reg(args[1]) - h = mc.half(r, sel[0]) - k = mc.int_half(reg(args[2])[0], sel[1]) - k = k - 0x10000 if k & 0x8000 else k - if h is not None: - h = (h & 0x7FFF if a else h) ^ (0x8000 if n else 0) - x = dec16(h) - if x[0] == "num" and x[2] != 0: - h = _out(mc, b, ("num", x[1], x[2] * Fraction(2) ** max(-64, min(64, k))), events) - if clamp: # on the rounded bits: negative (or -0) and NaN give +0 - h = 0 if h is None or is_nan16(h) or h & 0x8000 else min(h, 0x3C00) - mc.set_half(d, sel[2], h) - elif b == "v_fract_f16": - sel = bits(mods, "op_sel", 2) - x = mc.f16(args[1], sel[0]) - if x[0] == "nan": - if clamp: - raise NotJudged("clamp of a NaN") - h = None - elif x[0] == "inf": - h = 0 if clamp else None - else: - q = signed(x) - v = ("num", 0, q - math.floor(q)) - h = _out(mc, b, v, events) - h = 0x3BFF if h == 0x3C00 else h - mc.set_half(d, sel[1], h) - else: - raise HarnessError(f"no reference for {op}") - - -def reference(lines, events=None): - """-> (the four exported words, the set of (register, half) that hold a computed NaN).""" - mc = Machine() - for line in lines: - step(line, mc, events) - return [mc.v[r] for r in EXPORT_REGS], {(i, h) for i, r in enumerate(EXPORT_REGS) for h in (0, 1) - if (r, h) in mc.unk} - - -def compare(want, nans, got): - """None when the translator's words match the reference's, else a description of the first difference.""" - for i, (w, g) in enumerate(zip(want, got)): - for hi in (0, 1): - wh, gh = w >> (16 * hi) & M16, g >> (16 * hi) & M16 - if (i, hi) in nans: - if not is_nan16(gh): - return f"v{EXPORT_REGS[i]}.{'hi' if hi else 'lo'}: want a NaN, got 0x{gh:04x}" - elif wh != gh: - return f"v{EXPORT_REGS[i]}.{'hi' if hi else 'lo'}: want 0x{wh:04x}, got 0x{gh:04x}" - return None - - -# ---- operand values ---- - -BOUND16 = (0x0001, 0x03FF, 0x0400, 0x3BFF, 0x3C00, 0x3C01, 0x7BFF, 0x7BFE, 0x5800, 0x1400, 0x6800, 0x2000) -SPECIAL16 = (0x0000, 0x8000, 0x7C00, 0xFC00, 0x7E00, 0x7C01) -SPECIAL32 = (0x00000000, 0x80000000, 0x7F800000, 0xFF800000, 0x7FC00000, 0x00000001, 0x807FFFFF) - - -def rand_half(rng, special=0.04): - k = rng.random() - if k < special: - return rng.choice(SPECIAL16) - if k < 0.3: - h = (rng.choice(BOUND16) + rng.randint(-3, 3)) & 0x7FFF - elif k < 0.42: - h = rng.randint(1, 0x3FF) - else: - h = rng.randint(1, 30) << 10 | rng.getrandbits(10) - if h >> 10 == 31: - h = 0x7BFF - return h | rng.getrandbits(1) << 15 - - -def near_half(rng, x): - """An addend that leaves bits below x's last place: a few binades under x, either sign, exactly half an ulp, or - so far under x that the f32 sum rounds back to x (only the exact sum then tells the toward-zero f16 result).""" - e = x >> 10 & 31 - if e in (0, 31) or rng.random() < 0.25: - return rand_half(rng) - sign = rng.getrandbits(1) << 15 - if e >= 16 and rng.random() < 0.25: # at most half an f32 ulp of x: the f32 sum rounds back to |x| - if e >= 25 and rng.random() < 0.3: - return (e - 24) << 10 | sign # exactly half an f32 ulp - if e >= 26: - return rng.randint(1, e - 25) << 10 | rng.getrandbits(10) | sign - return rng.randint(1, min(0x3FF, (1 << (e - 15)) - 1)) | sign - if rng.random() < 0.2: # x +- half an ulp: a tie - h = round16(("num", 0, Fraction(2) ** (max(e, 1) - 26)), False) - return h | sign - ey = e - rng.randint(1, 14) - if ey < 1: - return rng.randint(1, 0x3FF) | sign - return ey << 10 | rng.getrandbits(10) | sign - - -def addend_for(rng, x, y): - """z for x * y + z: near the product, its exact negation, or any half.""" - p = mul(dec16(x), dec16(y)) - k = rng.random() - if p[0] != "num" or k < 0.25: - return rand_half(rng) - pb = round16(p, False) - if k < 0.35 and pb is not None: - return pb ^ 0x8000 # cancels to the product's rounding error - return near_half(rng, pb & 0x7FFF) if pb is not None and pb & 0x7C00 != 0x7C00 else rand_half(rng) - - -def rand_f32(rng): - k = rng.random() - s = rng.getrandbits(1) << 31 - if k < 0.04: - return rng.choice(SPECIAL32) - if k < 0.25: # an f16 tie, or one f32 ulp either side - e = rng.randint(113, 142) - return s | e << 23 | rng.getrandbits(10) << 13 | (0x1000 + rng.choice((0, 0, -1, 1))) - if k < 0.38: # the overflow edge: 65504 .. 65536 and a little past - return s | (0x477FE000 + rng.randint(-0x4000, 0x24000)) - if k < 0.5: # the f16 denormal range - return s | rng.randint(102, 112) << 23 | rng.getrandbits(23) - return s | rng.randint(100, 150) << 23 | rng.getrandbits(23) - - -def rand_int16(rng): - return rng.choice((rng.getrandbits(16), rng.randint(2049, 4200), 0xFFFF - rng.randint(0, 40), - 0x7FFF - rng.randint(0, 40), 0x8000 + rng.randint(0, 40), rng.randint(0, 2048))) - - -def rand_fract_half(rng): - """Mostly a small negative with low bits, where 1 + x needs rounding.""" - if rng.random() < 0.6: - return 0x8000 | rng.randint(1, 14) << 10 | rng.getrandbits(10) - return rand_half(rng) - - -def pack(lo, hi): - return (hi & M16) << 16 | lo & M16 - - -def operand_words(rng, op, n, mods): - """Crafted words for the operands of one op (the accumulator last, for v_fmac_f16 / v_pk_fmac_f16).""" - if op in ("v_add_f16", "v_sub_f16", "v_subrev_f16", "v_pk_add_f16"): - xs = [rand_half(rng), rand_half(rng)] - ys = [near_half(rng, x & 0x7FFF) if rng.random() < 0.8 else rand_half(rng) for x in xs] - return [pack(*xs), pack(*ys)] - if op in ("v_mul_f16", "v_pk_mul_f16"): - return [pack(rand_half(rng), rand_half(rng)) for _ in range(2)] - if op in ("v_fma_f16", "v_fmac_f16", "v_fmamk_f16", "v_fmaak_f16", "v_pk_fma_f16", "v_pk_fmac_f16"): - xs, ys = [rand_half(rng), rand_half(rng)], [rand_half(rng), rand_half(rng)] - zs = [addend_for(rng, x, y) for x, y in zip(xs, ys)] - return [pack(*xs), pack(*ys), pack(*zs)] - if op in ("v_fma_mixlo_f16", "v_fma_mixhi_f16"): - hi = bits(mods, "op_sel_hi", 3) - out = [] - for i in range(3): - if hi[i]: - out.append(pack(rand_half(rng), rand_half(rng))) - elif rng.random() < 0.15: - out.append(rng.choice(SPECIAL32)) - else: - out.append(rng.getrandbits(1) << 31 | rng.randint(110, 140) << 23 | rng.getrandbits(23)) - if not any(hi) and rng.random() < 0.5: # x * y near an f16 tie, z small: a single-rounding case - x, z = out[0], out[2] - out[1] = rng.getrandbits(1) << 31 | 0x3F800000 - out[0] = x & 0x80000000 | rng.randint(113, 142) << 23 | rng.getrandbits(10) << 13 | 0x1000 - out[2] = z & 0x80000000 | rng.randint(80, 110) << 23 | rng.getrandbits(23) - return out - if op == "v_cvt_f16_f32": - if ("mul:2" in mods or "mul:4" in mods) and rng.random() < 0.5: # an f16 at 2^14 .. 65504: the omod overflows - return [rng.getrandbits(1) << 31 | rng.randint(141, 142) << 23 | rng.getrandbits(23)] - if "div:2" in mods and rng.random() < 0.5: # an f16 denormal or a smallest normal before div:2 - return [rng.getrandbits(1) << 31 | rng.randint(110, 113) << 23 | rng.getrandbits(23)] - return [rand_f32(rng)] - if op in ("v_cvt_f16_u16", "v_cvt_f16_i16"): - return [pack(rand_int16(rng), rand_int16(rng))] - if op == "v_ldexp_f16": - es = [rng.choice((rng.randint(-30, 30), rng.randint(-30, 30), rng.choice((-64, -65, 64, 65, -200, 300)))) - for _ in range(2)] - return [pack(rand_half(rng), rand_half(rng)), pack(*es)] - if op == "v_fract_f16": - return [pack(rand_fract_half(rng), rand_fract_half(rng))] - raise HarnessError(f"no operands for {op}") - - -def _src(rng, r, mods_ok): - if not mods_ok or rng.random() < 0.6: - return f"v{r}" - return rng.choice((f"-v{r}", f"|v{r}|", f"-|v{r}|")) - - -def _bitlist(rng, n, p=0.5): - return [int(rng.random() < p) for _ in range(n)] - - -def op_lines(rng, op, form=None, craft=True): - """The lines for one op: its reseeded operands (when ``craft``), then the op.""" - forms, n = FAMILY[op] - form = form or rng.choice(forms) - dst = rng.choice(DSTS) - regs = list(OPERAND_REGS[:n]) if craft else [rng.choice(VGPRS) for _ in range(n)] - mods = [] - e64 = form in ("e64", "vop3", "vop3p") - if op in ("v_fma_mixlo_f16", "v_fma_mixhi_f16"): - hi = _bitlist(rng, 3, 0.4) - sel = [s & h for s, h in zip(_bitlist(rng, 3), hi)] # op_sel only on f16 operands - mods += [f"op_sel:[{','.join(map(str, sel))}]", f"op_sel_hi:[{','.join(map(str, hi))}]"] - elif form == "vop3p": - for name, p in (("op_sel", 0.5), ("op_sel_hi", 0.5), ("neg_lo", 0.3), ("neg_hi", 0.3)): - if rng.random() < 0.5: - mods.append(f"{name}:[{','.join(map(str, _bitlist(rng, n, p if name != 'op_sel_hi' else 0.7)))}]") - elif e64 and op not in ("v_fmac_f16", "v_cvt_f16_f32") and rng.random() < 0.5: - nb = {"v_fma_f16": 4, "v_cvt_f16_u16": 2, "v_cvt_f16_i16": 2, "v_fract_f16": 2}.get(op, 3) - mods.append(f"op_sel:[{','.join(map(str, _bitlist(rng, nb)))}]") - if op == "v_cvt_f16_f32" and e64 and rng.random() < 0.4: - mods.append(rng.choice(("mul:2", "mul:4", "div:2"))) - if e64 and op != "v_pk_fmac_f16" and rng.random() < 0.2: - mods.append("clamp") - pre, k = [], None - words = operand_words(rng, op, n, mods) if craft else None - if op in ("v_fmamk_f16", "v_fmaak_f16"): # K is the literal's low half; the words are x, y, z of x * y + z - if craft: - x, y, z = words - k, words = (y, [x, z]) if op == "v_fmamk_f16" else (z, [x, y]) - else: - k = rand_half(rng) - k = f"0x{k & M16:04x}" - if craft: - if op in ("v_fmac_f16", "v_pk_fmac_f16"): - pre.append(f"v_mov_b32 v{dst}, 0x{words[2]:08x}") - pre += [f"v_mov_b32 v{r}, 0x{w:08x}" for r, w in zip(regs, words)] - abs_ok = e64 and form != "vop3p" and op not in ("v_cvt_f16_u16", "v_cvt_f16_i16") or op.startswith("v_fma_mix") - srcs = [_src(rng, r, abs_ok and not (op == "v_ldexp_f16" and i == 1)) for i, r in enumerate(regs)] - if k: - srcs = [srcs[0], k, srcs[1]] if op == "v_fmamk_f16" else [srcs[0], srcs[1], k] - name = op + ("_" + form if form in ("e32", "e64") else "") - tail = (" " + " ".join(mods)) if mods else "" - return pre + [f"{name} v{dst}, {', '.join(srcs)}{tail}"] - - -def seeds(rng): - out = [] - for r in VGPRS: - k = rng.random() - w = rand_f32(rng) if k < 0.3 else pack(rand_int16(rng), rand_int16(rng)) if k < 0.4 else \ - pack(rand_half(rng), rand_half(rng)) - out.append(f"v_mov_b32 v{r}, 0x{w:08x}") - return out - - -def program(rng, n_ops, ops=None): - """A random program: MODE writes before about one op in three. -> (lines, ops used).""" - pool = list(ops or FAMILY) - lines, used = seeds(rng), [] - for _ in range(n_ops): - if rng.random() < 0.35: - lines.append(rng.choice(MODE_WRITES)) - op = rng.choice(pool) - lines += op_lines(rng, op, craft=rng.random() < 0.75) - used.append(op) - return lines, used - - -def sweep_cases(ops=None): - return [(op, form, mw) for op in (ops or FAMILY) for form in FAMILY[op][0] for mw in MODE_WRITES] - - -def sweep_program(case, rng): - op, form, mw = case - lines = seeds(rng) + [mw] - for _ in range(GRID_PER_PROGRAM): - lines += op_lines(rng, op, form) - return lines - - -# ---- the invariance stage ---- - -def invariant_line(rng, op): - dst = rng.choice(DSTS) - r = [rng.choice(VGPRS) for _ in range(3)] - if op in INV_VOP3P: - sel = f" op_sel:[{rng.getrandbits(1)},{rng.getrandbits(1)}]" if rng.random() < 0.5 else "" - return f"{op} v{dst}, v{r[0]}, v{r[1]}{sel}" - if op in INV_VOP3: - if op == "v_fma_mix_f32": - hi = _bitlist(rng, 3, 0.4) - sel = [s & h for s, h in zip(_bitlist(rng, 3), hi)] - return (f"{op} v{dst}, v{r[0]}, v{r[1]}, v{r[2]} op_sel:[{','.join(map(str, sel))}] " - f"op_sel_hi:[{','.join(map(str, hi))}]") - return f"{op} v{dst}, v{r[0]}, v{r[1]}, v{r[2]}" - if op in INV_VOP2: - return f"{op}_e32 v{dst}, v{r[0]}, v{r[1]}" - if op in ("v_log_f16", "v_sqrt_f16", "v_rsq_f16"): # GLSL leaves a negative operand undefined - return f"{op}_e64 v{dst}, |v{r[0]}| op_sel:[{rng.getrandbits(1)},{rng.getrandbits(1)}]" - if op in INV_UNARY_OPSEL and rng.random() < 0.4: - return f"{op}_e64 v{dst}, {_src(rng, r[0], True)} op_sel:[{rng.getrandbits(1)},{rng.getrandbits(1)}]" - return f"{op}_e32 v{dst}, v{r[0]}" - - -def invariance_program(rng, n_ops): - """-> (lines with MODE writes, the same lines without them).""" - lines = seeds(rng) - first = True - for _ in range(n_ops): - if first or rng.random() < 0.4: - lines.append(rng.choice(MODE_WRITES[1::2]) if first else rng.choice(MODE_WRITES)) - first = False - if rng.random() < 0.5: - r = rng.choice(VGPRS) - w = pack(rand_half(rng, 0.08), rand_half(rng, 0.08)) if rng.random() < 0.7 else rand_f32(rng) - lines.append(f"v_mov_b32 v{r}, 0x{w:08x}") - lines.append(invariant_line(rng, rng.choice(INVARIANT))) - plain = [ln for ln in lines if ln not in MODE_WRITES] - return lines, plain - - -# ---- running the translator ---- - -def write_listing(path, lines, name): - with open(path, "w", encoding="utf-8", newline="\n") as f: - f.write(f"; {name} code 0x0..0x1000\n") - for line in lines: - f.write("\t" + line + "\n") - f.write("\t" + EXPORT + "\n") - f.write("\ts_endpgm\n") - - -def translate_listing(lines, name, tmpdir): - """The four mrt0 words the translator path produces. Raises rdna2spirv.Unsupported (and the mini interp's - UnsupportedConstruct) for anything outside the oracles' model.""" - dis = os.path.join(tmpdir, "disasm") - os.makedirs(dis, exist_ok=True) - path = os.path.join(dis, name + ".s") - write_listing(path, lines, name) - with open(os.path.join(tmpdir, name + ".dxbc"), "wb") as f: - f.write(STUB_DXBC) - with warnings.catch_warnings(): - warnings.simplefilter("ignore", ResourceWarning) - spvasm = rdna2spirv.translate(path) - gc.collect() - out = run_fragment(spvasm) - if list(out) != ["%out_mrt0"]: - raise HarnessError(f"outputs {sorted(out)}, want %out_mrt0") - return [w & M32 for w in out["%out_mrt0"]] - - -def check(lines, name="ps_mode_case"): - """None when both oracles agree, else the first difference.""" - with tempfile.TemporaryDirectory(prefix="mode-diff-") as tmp: - want, nans = reference(lines) - got = translate_listing(lines, name, tmp) - return compare(want, nans, got) - - -def _translate(lines, name, tmpdir): - """-> (words, None), or (None, why). A value SPIR-V leaves undefined (Log2 of 0, ...) raises NotJudged.""" - try: - return translate_listing(lines, name, tmpdir), None - except UnsupportedConstruct as e: - if "(undefined" in str(e): - raise NotJudged("undefined in SPIR-V: " + re.sub(r" of .*| \(undefined.*", "", str(e))) from None - return None, f"UnsupportedConstruct: {e}" - except rdna2spirv.Unsupported as e: - return None, f"{type(e).__name__}: {e}" - except (IndexError, KeyError, ValueError) as e: - return None, f"translator error {type(e).__name__}: {e}" - - -def run_one(lines, name, tmpdir, events=None): - """(status, detail) with status in {"match", "mismatch", "skip", "unjudged"}.""" - try: - want, nans = reference(lines, events) - except NotJudged as e: - return ("unjudged", str(e)) - try: - got, err = _translate(lines, name, tmpdir) - except NotJudged as e: - return ("unjudged", str(e)) - if err: - return ("skip", err) - diff = compare(want, nans, got) - return ("mismatch", diff) if diff else ("match", "") - - -def run_invariant(pair, name, tmpdir): - with_mode, plain = pair - try: - a, err = _translate(with_mode, name, tmpdir) - b, err2 = (None, None) if err else _translate(plain, name + "p", tmpdir) - except NotJudged as e: - return ("unjudged", str(e)) - if err or err2: - return ("skip", err or err2) - for i, (x, y) in enumerate(zip(a, b)): - if x != y: - return ("mismatch", f"v{EXPORT_REGS[i]}: 0x{x:08x} with the MODE writes, 0x{y:08x} without") - return ("match", "") - - -# ---- the suites ---- - -def _new_counts(): - return {"pass": 0, "mismatch": 0, "skip": Counter(), "unjudged": Counter(), "ops": Counter(), "events": {}} - - -def _tally(counts, status, detail): - if status == "match": - counts["pass"] += 1 - elif status in ("skip", "unjudged"): - counts[status][detail] += 1 - else: - counts["mismatch"] += 1 - - -def _run(counts, items, tag, invariance=False): - failure = None - with tempfile.TemporaryDirectory(prefix=f"mode-diff-{tag}-") as tmp: - for i, (label, lines, used) in enumerate(items): - counts["ops"].update(used) - name = f"ps_mode_{tag}{i:05d}" - status, detail = (run_invariant(lines, name, tmp) if invariance else - run_one(lines, name, tmp, counts["events"])) - _tally(counts, status, detail) - if status == "mismatch" and failure is None: - failure = (label, lines[0] if invariance else lines, detail) - return failure - - -# Each stage yields its (label, lines, ops) items one at a time, so a run holds one program's text, not the whole list. -def sweep_items(seed, ops=None): - for case in sweep_cases(ops): - tag = ":".join(case) - yield f"sweep {tag} (seed {seed})", sweep_program(case, random.Random(f"{seed}:{tag}")), [case[0]] - - -def suite_items(programs, seed, max_ops=6, ops=None): - rng = random.Random(f"suite:{seed}") - for i in range(programs): - lines, used = program(rng, rng.randint(1, max_ops), ops) - yield f"program {i} (seed {seed})", lines, used - - -def invariance_items(programs, seed, max_ops=6): - rng = random.Random(f"invariance:{seed}") - for i in range(programs): - pair = invariance_program(rng, rng.randint(1, max_ops)) - used = [base_op(split_line(ln)[0]) for ln in pair[1] if not ln.startswith("v_mov_b32 ")] - yield f"invariance program {i} (seed {seed})", pair, used - - -def run_sweep(seed, ops=None): - counts = _new_counts() - return counts, _run(counts, sweep_items(seed, ops), "sw") - - -def run_suite(programs, seed, max_ops=6, ops=None): - counts = _new_counts() - return counts, _run(counts, suite_items(programs, seed, max_ops, ops), "rn") - - -def run_invariance(programs, seed, max_ops=6): - counts = _new_counts() - return counts, _run(counts, invariance_items(programs, seed, max_ops), "iv", invariance=True) - - -REJECTED = ( - ("directed rounding toward +inf", SETREG.format(1)), - ("directed rounding toward -inf", SETREG.format(2)), - ("s_round_mode with directed f16 rounding", "s_round_mode 0x4"), - ("s_round_mode with f32 rounding", "s_round_mode 0x3"), - ("a MODE write from an SGPR", "s_setreg_b32 hwreg(HW_REG_MODE, 2, 2), s0"), - ("a write to other MODE bits", "s_setreg_imm32_b32 hwreg(HW_REG_MODE, 0, 4), 0xc"), - ("s_denorm_mode", "s_denorm_mode 0xf"), -) - -# RX 6800 words (tests/test_mode_round.py, SHADER-35): (setup, op, word without a MODE write / with RTZ, mask) -RX6800 = ( - (("v_mov_b32 v1, 0x4000", "v_mov_b32 v2, 0x0001"), "v_add_f16_e32 v3, v1, v2", 0x4000, 0x4000), - (("v_mov_b32 v1, 0x7bff", "v_mov_b32 v2, 0x4c00"), "v_add_f16_e32 v3, v1, v2", 0x7C00, 0x7BFF), - (("v_mov_b32 v1, 0xbc00", "v_mov_b32 v2, 0x1001"), "v_sub_f16_e32 v3, v1, v2", 0xBC01, 0xBC00), - (("v_mov_b32 v1, 0x3f800000", "v_mov_b32 v2, 0x40000000", "v_mov_b32 v4, 0xb0800000"), - "v_fma_mixlo_f16 v3, v1, v2, v4", 0x4000, 0x3FFF), -) - - -def measured_cases(): - """(name, setup, op, want nearest, want toward zero, mask) for the f16 words measured on RDNA2: the - tools/mode_round_probe.py cases (gfx1036; its two v_ldexp_f16 cases are not measured yet) and the RX 6800 rows.""" - import mode_round_probe as probe - out = [] - for name, setup, op, is_64, rne, rtz in probe.CASES: - if not is_64: - out.append((name, setup, op, rne, rtz, M32 if rne > M16 else M16)) - for i, (setup, op, rne, rtz) in enumerate(RX6800): - out.append((f"rx6800_{i}", setup, op, rne, rtz, M16)) - return out - - -def reference_word(setup, op, mode_line, reg_=3): - mc = Machine() - for line in tuple(setup) + ((mode_line,) if mode_line else ()) + (op,): - step(line, mc) - return mc.v[reg_] - - -def self_test(): - ok = True - - def report(good, what): - nonlocal ok - ok &= good - print(("ok " if good else "FAIL ") + what) - - cases = measured_cases() - bad = [name for name, setup, op, rne, rtz, mask in cases - if (reference_word(setup, op, MODE_WRITES[0]) & mask, reference_word(setup, op, MODE_WRITES[1]) & mask) - != (rne, rtz)] - report(not bad, f"the reference gives the measured words of {len(cases)} cases in both modes {bad or ''}") - report(reference_word(cases[0][1], cases[0][2], "s_round_mode 0xc") & M16 == cases[0][4], - "s_round_mode 0xc selects toward zero") - report(round16(("num", 0, Fraction(65520)), False) == 0x7C00 and round16(("num", 0, Fraction(65535)), True) - == 0x7BFF and round16(("num", 1, Fraction(3, 1 << 25)), True) == 0x8001, - "round16: 65520 -> inf nearest, 65535 -> 65504 toward zero, -1.5 * 2^-24 -> 0x8001 toward zero") - mc = Machine() - for line in ("v_mov_b32 v1, 0x9401", SETREG.format(3), "v_fract_f16_e32 v2, v1", SETREG.format(0), - "v_fract_f16_e32 v3, v1"): - step(line, mc) - report((mc.v[2] & M16, mc.v[3] & M16) == (0x3BFD, 0x3BFE), - "fract(-(2^-10 + 2^-20)) is 0x3bfd toward zero and 0x3bfe to nearest even") - for what, line in REJECTED: - try: - with tempfile.TemporaryDirectory(prefix="mode-diff-st-") as tmp: - translate_listing(seeds(random.Random(1)) + [line], "ps_mode_rej", tmp) - report(False, f"{what}: the translator accepted it") - except (rdna2spirv.Unsupported, UnsupportedConstruct): - report(True, f"{what}: the translator rejected it") - a = program(random.Random("st"), 5)[0] - b = program(random.Random("st"), 5)[0] - report(a == b, "generation is deterministic for a seed") - counts, failure = run_suite(8, 1) - report(failure is None and not counts["skip"], - f"a short seeded run matches ({counts['pass']} programs, skips {dict(counts['skip'])})") - counts, failure = run_invariance(4, 1) - report(failure is None and not counts["skip"], f"a short invariance run matches ({counts['pass']} programs)") - return ok - - -def main(): - ap = argparse.ArgumentParser(description=__doc__.split("\n")[0]) - ap.add_argument("--programs", type=int, default=300, help="random programs after the sweep") - ap.add_argument("--invariance", type=int, default=100, help="mode-invariance programs") - ap.add_argument("--seed", type=int, default=1) - ap.add_argument("--max-ops", type=int, default=6, help="ops per random program") - ap.add_argument("--ops", default=None, help="comma-separated opcodes for the sweep and the random programs") - ap.add_argument("--no-sweep", action="store_true", help="skip the sweep of every form under every MODE write") - ap.add_argument("--list-ops", action="store_true") - ap.add_argument("--self-test", action="store_true") - args = ap.parse_args() - if args.list_ops: - for op in FAMILY: - print(f"{op:18s} {OP_FORMS[op]}") - print("invariance stage: " + " ".join(INVARIANT)) - return 0 - if args.self_test: - return 0 if self_test() else 1 - ops = None - if args.ops: - ops = [o.strip() for o in args.ops.split(",") if o.strip()] - bad = [o for o in ops if o not in FAMILY] - if bad: - print(f"unknown op(s): {', '.join(bad)} (see --list-ops)", file=sys.stderr) - return 2 - stages = [] - if not args.no_sweep: - stages.append(("sweep", lambda: run_sweep(args.seed, ops))) - if args.programs > 0: - stages.append(("random", lambda: run_suite(args.programs, args.seed, args.max_ops, ops))) - if args.invariance > 0: - stages.append(("invariance", lambda: run_invariance(args.invariance, args.seed, args.max_ops))) - total = {"pass": 0, "mismatch": 0, "skip": 0, "unjudged": Counter(), "events": {}} - first = None - try: - for name, fn in stages: - counts, failure = fn() - n = counts["pass"] + counts["mismatch"] + sum(counts["skip"].values()) + sum(counts["unjudged"].values()) - print(f"{name}: {counts['pass']}/{n} programs match, {counts['mismatch']} mismatch; " - f"skips: {dict(counts['skip'])}; not judged: {sum(counts['unjudged'].values())}") - total["pass"] += counts["pass"] - total["mismatch"] += counts["mismatch"] - total["skip"] += sum(counts["skip"].values()) - total["unjudged"].update(counts["unjudged"]) - for op, ev in counts["events"].items(): - total["events"].setdefault(op, Counter()).update(ev) - if failure and first is None: - first = failure - except HarnessError as e: - print(f"harness error: {e}", file=sys.stderr) - return 2 - if total["events"]: - print("rounded results per op (nearest / toward zero / the modes differ / overflow / denormal / tie): " + - ", ".join(f"{op} {ev['nearest']}/{ev['toward zero']}/{ev['modes differ']}/{ev['overflow']}/" - f"{ev['denormal']}/{ev['tie']}" for op, ev in sorted(total["events"].items()))) - if total["unjudged"]: - print("not judged: " + ", ".join(f"{why} {n}" for why, n in total["unjudged"].most_common())) - judged = total["pass"] + total["mismatch"] + total["skip"] - print(f"MODE.FP_ROUND: {total['pass']}/{judged} judged programs match, {total['mismatch']} mismatch") - if first: - _report(first) - return 1 - if total["skip"]: - print(f"SKIPPED {total['skip']} program(s): every generated form should translate (reasons above)") - return 1 - return 0 - - -def _report(failure): - label, lines, detail = failure - print(f"\nFIRST MISMATCH: {label}: {detail}") - for line in lines: - print(" " + line) - - -if __name__ == "__main__": - try: # a redirected stdout is strict ANSI code page under -I; write '?' for what it cannot encode - sys.stdout.reconfigure(errors="replace") - except (AttributeError, ValueError, OSError): - pass - sys.exit(main()) diff --git a/tools/mode_round_probe.py b/tools/mode_round_probe.py deleted file mode 100644 index 2506d1731..000000000 --- a/tools/mode_round_probe.py +++ /dev/null @@ -1,308 +0,0 @@ -r"""Measure RDNA2 (GFX10) f16/f64 results under MODE.FP_ROUND[3:2] nearest-even vs toward-zero (SHADER-132). - -Runs two native sweeps through tools/hw_oracle in wave32 and wave64: -1. Targeted f16/f64 rounding cases (v_cvt_f16_f32, v_add_f16, v_sub_f16, v_mul_f16, v_fma_f16, v_pk_add_f16, - v_pk_fma_f16, v_fma_mixlo_f16, v_fma_mixhi_f16, v_ldexp_f16 overflow and denormal results, v_add_f64 including - exact-sum and finite-overflow saturation) - under s_setreg_imm32_b32 hwreg(HW_REG_MODE, 2, 2), 0 (RNE) vs 3 (RTZ). -2. Exhaustive 65,536-input RNE vs RTZ comparison of all seven f16 transcendentals (v_rcp_f16, v_rsq_f16, - v_sqrt_f16, v_sin_f16, v_cos_f16, v_exp_f16, v_log_f16), confirming that none of them depend on MODE.FP_ROUND. - -Usage: - python -I tools/mode_round_probe.py [--waves 32,64] [--json out.json] - python -I tools/mode_round_probe.py --self-test # pure-Python sanity checks, no GPU - -Exit 0 when every case matches (or --self-test passed), 1 on a mismatch or --json write failure, 2 on a harness error or invalid CLI arguments, 77 when -tools/hw_oracle is unavailable or the GPU is not GFX10. Standard library only; nothing here reads game files. -""" -import argparse -import json -import os -import stat -import sys -import tempfile - -HERE = os.path.dirname(os.path.abspath(__file__)) -sys.dont_write_bytecode = True -if HERE not in sys.path: - sys.path.insert(0, HERE) -from file_mode import published_mode # noqa: E402 -from replace_retry import replace as replace_retry # noqa: E402 - -RNE = "s_setreg_imm32_b32 hwreg(HW_REG_MODE, 2, 2), 0" -RTZ = "s_setreg_imm32_b32 hwreg(HW_REG_MODE, 2, 2), 3" - -# (name, setup_lines, op_line, is_64bit, want_rne, want_rtz) -CASES = ( - ("cvt_f16_f32_pos", ("v_mov_b32 v1, 0x3f801800",), "v_cvt_f16_f32_e32 v3, v1", False, 0x3C01, 0x3C00), - ("cvt_f16_f32_neg", ("v_mov_b32 v1, 0xbf801800",), "v_cvt_f16_f32_e32 v3, v1", False, 0xBC01, 0xBC00), - ("cvt_f16_f32_ovf", ("v_mov_b32 v1, 0x4788b800",), "v_cvt_f16_f32_e32 v3, v1", False, 0x7C00, 0x7BFF), - ("cvt_f16_f32_novf", ("v_mov_b32 v1, 0xc7800000",), "v_cvt_f16_f32_e32 v3, v1", False, 0xFC00, 0xFBFF), - ("cvt_f16_f32_sub", ("v_mov_b32 v1, 0x33c00000",), "v_cvt_f16_f32_e32 v3, v1", False, 0x0002, 0x0001), - ("add_f16_exact", ("v_mov_b32 v1, 0x4000", "v_mov_b32 v2, 0x8001"), - "v_add_f16_e32 v3, v1, v2", False, 0x4000, 0x3FFF), - ("add_f16_ovf", ("v_mov_b32 v1, 0x7bff", "v_mov_b32 v2, 0x4c00"), - "v_add_f16_e32 v3, v1, v2", False, 0x7C00, 0x7BFF), - ("sub_f16_neg", ("v_mov_b32 v1, 0xbc00", "v_mov_b32 v2, 0x1001"), - "v_sub_f16_e32 v3, v1, v2", False, 0xBC01, 0xBC00), - ("mul_f16_halfway", ("v_mov_b32 v1, 0x3e01", "v_mov_b32 v2, 0x3e01"), - "v_mul_f16_e32 v3, v1, v2", False, 0x4082, 0x4081), - ("fma_f16_exact", ("v_mov_b32 v1, 0x4000", "v_mov_b32 v2, 0x3c00", "v_mov_b32 v5, 0x8001"), - "v_fma_f16 v3, v1, v2, v5", False, 0x4000, 0x3FFF), - ("pk_add_f16", ("v_mov_b32 v1, 0xbc003c00", "v_mov_b32 v2, 0x92001200"), - "v_pk_add_f16 v3, v1, v2", False, 0xBC013C01, 0xBC003C00), - ("pk_fma_f16", ("v_mov_b32 v1, 0xc0004000", "v_mov_b32 v2, 0x3c003c00", "v_mov_b32 v5, 0x00018001"), - "v_pk_fma_f16 v3, v1, v2, v5", False, 0xC0004000, 0xBFFF3FFF), - ("fma_mixlo_f16", ("v_mov_b32 v1, 0x3f800000", "v_mov_b32 v2, 0x40000000", "v_mov_b32 v5, 0xb0800000"), - "v_fma_mixlo_f16 v3, v1, v2, v5", False, 0x4000, 0x3FFF), - ("fma_mixhi_f16", ("v_mov_b32 v1, 0x3f800000", "v_mov_b32 v2, 0xc0000000", - "v_mov_b32 v5, 0x30800000", "v_mov_b32 v3, 0x1234"), - "v_fma_mixhi_f16 v3, v1, v2, v5", False, 0xC0001234, 0xBFFF1234), - ("fma_mixlo_ovf", ("v_mov_b32 v1, 0x5f800000", "v_mov_b32 v2, 0x5f800000", "v_mov_b32 v5, 0"), - "v_fma_mixlo_f16 v3, v1, v2, v5", False, 0x7C00, 0x7BFF), - ("ldexp_f16_ovf", ("v_mov_b32 v1, 0x7bff", "v_mov_b32 v2, 1"), - "v_ldexp_f16_e32 v3, v1, v2", False, 0x7C00, 0x7BFF), - ("ldexp_f16_sub", ("v_mov_b32 v1, 0xbc03", "v_mov_b32 v2, -15"), - "v_ldexp_f16_e32 v3, v1, v2", False, 0x8202, 0x8201), - ("add_f64", ("v_mov_b32 v0, 0", "v_mov_b32 v1, 0x3ff00000", "v_mov_b32 v6, 0", "v_mov_b32 v7, 0xbc300000"), - "v_add_f64 v[3:4], v[0:1], v[6:7]", True, (0x00000000, 0x3FF00000), (0xFFFFFFFF, 0x3FEFFFFF)), - ("add_f64_ovf", ("v_mov_b32 v0, -1", "v_mov_b32 v1, 0x7fefffff"), - "v_add_f64 v[3:4], v[0:1], v[0:1]", True, (0x00000000, 0x7FF00000), (0xFFFFFFFF, 0x7FEFFFFF)), -) - -TRANSCENDENTALS = ( - ("v_rcp_f16_e32", 0x3037, 0x4798), - ("v_rsq_f16_e32", 0x3037, 0x4183), - ("v_sqrt_f16_e32", 0x4200, 0x3EEE), - ("v_sin_f16_e32", 0x3037, 0x39E4), - ("v_cos_f16_e32", 0x3037, 0x396A), - ("v_exp_f16_e32", 0x3037, 0x3C62), - ("v_log_f16_e32", 0x4A37, 0x4345), -) - - -def _case_kernel(asm_mod, setup, op, is_64, wave, mode_set): - lines = list(setup) + [mode_set, "s_nop 0", op, "v_mov_b32 v10, 0", "global_store_b32 v10, v3, s[2:3]"] - if is_64: - lines += ["v_mov_b32 v11, 4", "global_store_b32 v11, v4, s[2:3]"] - lines += ["s_waitcnt_vscnt null, 0x0", "s_endpgm"] - return asm_mod.Kernel(lines, wave, 1, 2, raw=True, vgprs=16, sgprs=16) - - -def probe_cases(oracle, asm_mod, wave): - ks = [] - for _, setup, op, is_64, _, _ in CASES: - ks.append(_case_kernel(asm_mod, setup, op, is_64, wave, RNE)) - ks.append(_case_kernel(asm_mod, setup, op, is_64, wave, RTZ)) - res = oracle.run(ks, words=2) - ok = 0 - mismatches = [] - for i, (name, _, _, is_64, want_rne, want_rtz) in enumerate(CASES): - r_rne, r_rtz = res[2 * i], res[2 * i + 1] - if isinstance(r_rne, str) or isinstance(r_rtz, str): - raise RuntimeError(f"{name} wave{wave}: rne={r_rne} rtz={r_rtz}") - if is_64: - got_rne, got_rtz = (r_rne[0], r_rne[1]), (r_rtz[0], r_rtz[1]) - else: - mask = 0xFFFFFFFF if want_rne > 0xFFFF else 0xFFFF - got_rne, got_rtz = r_rne[0] & mask, r_rtz[0] & mask - if got_rne == want_rne and got_rtz == want_rtz: - ok += 1 - else: - mismatches.append({"case": name, "got_rne": got_rne, "want_rne": want_rne, - "got_rtz": got_rtz, "want_rtz": want_rtz}) - return {"total": len(CASES), "ok": ok, "mismatches": mismatches} - - -def probe_transcendentals(oracle, asm_mod, wave): - """Exhaustive 65,536-input RNE vs RTZ diff + spot-check of measured nearest-even words.""" - report = {} - all_ok = True - for op, sample_in, sample_want in TRANSCENDENTALS: - ks = [] - for base in range(0, 65536, 1024): - lines = [ - f"v_add_nc_u32 v1, 0x{base:x}, v0", - RNE, "s_nop 0", f"{op} v2, v1", - RTZ, "s_nop 0", f"{op} v3, v1", - "v_xor_b32 v4, v2, v3", - "v_and_b32 v4, 0xffff, v4", - "v_lshlrev_b32 v5, 2, v0", - "global_store_b32 v5, v4, s[2:3]", - "s_waitcnt_vscnt null, 0x0", - "s_endpgm", - ] - ks.append(asm_mod.Kernel(lines, wave, 1024, 1024, raw=True, vgprs=8, sgprs=16)) - res = oracle.run(ks, words=1024) - diffs = 0 - for chunk in res: - if isinstance(chunk, str) or len(chunk) != 1024: - raise RuntimeError(f"{op} wave{wave}: {chunk}") - diffs += sum(1 for w in chunk if w != 0) - spot_k = _case_kernel(asm_mod, (f"v_mov_b32 v1, {sample_in:#x}",), f"{op} v3, v1", False, wave, RTZ) - spot_got = oracle.run([spot_k], words=2)[0][0] & 0xFFFF - ok = (diffs == 0) and (spot_got == sample_want) - if not ok: - all_ok = False - report[op] = {"inputs": 65536, "rne_rtz_diffs": diffs, "spot_got": f"{spot_got:#06x}", - "spot_want": f"{sample_want:#06x}", "ok": ok} - return {"all_ok": all_ok, "ops": report} - - -def self_test(): - # Every targeted case must distinguish RNE from RTZ - for name, _, _, _, want_rne, want_rtz in CASES: - assert want_rne != want_rtz, f"{name} does not distinguish RNE from RTZ" - assert len(TRANSCENDENTALS) == 7 - print("self-test OK") - - -def parse_waves(raw): - """Parse --waves comma-separated wave sizes; return (waves, error_message).""" - tokens = [t.strip() for t in raw.split(",") if t.strip()] - if not tokens: - return None, "--waves must not be empty" - waves = [] - for tok in tokens: - try: - w = int(tok) - except ValueError: - return None, f"invalid wave size in --waves: {tok!r}" - if w not in (32, 64): - return None, f"unsupported wave size in --waves: {w} (expected 32 or 64)" - waves.append(w) - return waves, None - - -def validate_json_path(path): - """Return an error string if `path` cannot be used as a --json output file, or None.""" - if not path or not path.strip(): - return "--json path must not be empty" - if "\x00" in path: - return "--json path contains a NUL byte" - if path.endswith(os.sep) or (os.altsep and path.endswith(os.altsep)) or os.path.isdir(path): - return f"--json path is a directory: {path}" - cur = os.path.dirname(os.path.abspath(path)) - while cur: - if os.path.isdir(cur): - break - if os.path.lexists(cur): - return f"--json parent is not a directory: {cur}" - nxt = os.path.dirname(cur) - if nxt == cur: - break - cur = nxt - return None - - -def write_json_report(path, data): - """Create missing parent directories and stage `data` as LF-terminated JSON via a sibling temp file, - so a write or replace failure keeps any previous report intact, or return an error string.""" - parent = os.path.dirname(os.path.abspath(path)) - if parent: - try: - os.makedirs(parent, exist_ok=True) - except OSError as exc: - return f"cannot create directory for --json {path}: {exc.strerror or exc}" - destination = os.path.realpath(path) - dest_parent = os.path.dirname(destination) or "." - if dest_parent != parent: - try: - os.makedirs(dest_parent, exist_ok=True) - except OSError as exc: - return f"cannot create directory for --json {path}: {exc.strerror or exc}" - try: - try: - mode = os.stat(destination).st_mode - except FileNotFoundError: - mode = None - if mode is not None and not stat.S_ISREG(mode): - with open(path, "w", encoding="utf-8", newline="\n") as f: - json.dump(data, f, indent=2) - return None - if mode is not None: - # Keep the direct writer's permission check without truncating the previous report. - os.close(os.open(destination, os.O_WRONLY)) - fd = None - tmp = None - try: - fd, tmp = tempfile.mkstemp(dir=dest_parent, prefix=".mode_round_probe-", suffix=".tmp") - with open(fd, "w", encoding="utf-8", newline="\n") as f: - fd = None - json.dump(data, f, indent=2) - if os.name != "nt": - os.chmod(tmp, published_mode(destination)) - replace_retry(tmp, destination) - except BaseException: - if fd is not None: - try: - os.close(fd) - except OSError: - pass - if tmp is not None: - try: - if os.path.lexists(tmp): - os.chmod(tmp, 0o600) - os.unlink(tmp) - except OSError: - pass - raise - except OSError as exc: - return f"cannot write --json {path}: {exc.strerror or exc}" - return None - - -def main(argv=None): - ap = argparse.ArgumentParser(description=__doc__.splitlines()[0]) - ap.add_argument("--waves", default="32,64", help="wave sizes to run (default: 32,64)") - ap.add_argument("--json", dest="json_out", help="write full JSON report to this path") - ap.add_argument("--self-test", action="store_true", help="check the case table without a GPU") - args = ap.parse_args(argv) - if args.self_test: - self_test() - return 0 - waves, wave_err = parse_waves(args.waves) - if wave_err: - print(f"error: {wave_err}", file=sys.stderr) - return 2 - if args.json_out is not None: - json_err = validate_json_path(args.json_out) - if json_err: - print(f"error: {json_err}", file=sys.stderr) - return 2 - from hw_oracle import asm, runner - try: - oracle = runner.open_oracle() - except runner.Unavailable as exc: - print(f"SKIP: {exc}", file=sys.stderr) - return 77 - if asm.family(oracle.arch) != "gfx10": - print(f"SKIP: {oracle.arch} is not GFX10 (RDNA1/RDNA2)", file=sys.stderr) - return 77 - out = {"arch": oracle.arch, "waves": {}} - mismatches = 0 - for wave in waves: - c = probe_cases(oracle, asm, wave) - t = probe_transcendentals(oracle, asm, wave) - out["waves"][str(wave)] = {"cases": c, "transcendentals": t} - if c["ok"] != c["total"] or not t["all_ok"]: - mismatches += 1 - t_ok = sum(info["ok"] for info in t["ops"].values()) - print(f"wave{wave} ({oracle.arch}): {c['ok']}/{c['total']} f16/f64 RNE/RTZ cases exact; " - f"{t_ok}/{len(t['ops'])} f16 transcendentals 0/65536 RNE/RTZ diffs") - for op, info in t["ops"].items(): - if not info["ok"]: - print(f" {op}: {info['rne_rtz_diffs']}/{info['inputs']} RNE/RTZ diffs, " - f"RTZ spot word {info['spot_got']} (want {info['spot_want']})") - if args.json_out is not None: - write_err = write_json_report(args.json_out, out) - if write_err: - print(f"error: {write_err}", file=sys.stderr) - return 1 - return 1 if mismatches else 0 - - -if __name__ == "__main__": - if hasattr(sys.stdout, "reconfigure"): - sys.stdout.reconfigure(errors="replace") - raise SystemExit(main()) diff --git a/tools/navmesh_cell_fit.py b/tools/navmesh_cell_fit.py deleted file mode 100644 index 17da521a3..000000000 --- a/tools/navmesh_cell_fit.py +++ /dev/null @@ -1,222 +0,0 @@ -"""Measure the cell grid the local-space navmeshes of ``navmeshes.rpf`` were built on (ASSET-332, docs/navmesh.md). - -For every non-grid navmesh tile (``flags & 4``) with ``flags == 7``, the ``u16[3]`` vertices of the split array at -``+0x70`` are dequantised over the tile's ``+0x60`` extents (step ``extent / 65535``). An x or y coordinate is on a -grid of cell size ``c`` when it is within 1.5 steps of a multiple of ``c``. A mesh fits ``c`` when at least -``--min-fraction`` of its x and y coordinates are on that grid. For each fitting mesh, the chance baseline is the -share of all 65,536 quantisation levels of its own step that land on the grid. ``--static-every N`` measures -every Nth static 128 m tile the same way, as a control. - -With ``--common`` (a ``tools/rpf9_carve.py`` carve of ``common.rpf``), the ``CVehiclePoints`` documents' -``fNavOverrideRecastCellSize`` values are counted, and every non-grid mesh is searched at every byte offset for the -``joaat`` of each document's ``ModelName`` (as written, lower-cased, and with ``.yft``). - -Only aggregates are printed and written: counts, cell sizes, extents and fractions. No model name, no vertex, no -file name. - -Usage: - python -I navmesh_cell_fit.py [--common CARVE_DIR] [--static-every N] [--out FILE] - [--min-fraction F] -""" -import argparse -import glob -import json -import os -import re -import struct -import sys -from collections import Counter - -ROOT = os.path.dirname(os.path.abspath(__file__)) -if ROOT not in sys.path: - sys.path.insert(0, ROOT) -import navmesh_decode as nd # noqa: E402 -from report_paths import same_report_path # noqa: E402 - -DOC_CELLS = (0.0625, 0.03125, 0.0325) # the nonzero fNavOverrideRecastCellSize values, coarsest first -OTHER_CELLS = (0.1, 0.125, 0.15, 0.2, 0.25, 0.5) # controls no document uses -LEVELS = 65536 -TOL_STEPS = 1.5 - - -def on_grid(x, cell, tol): - r = x % cell - return r <= tol or cell - r <= tol - - -def fit_fraction(quantised, extents, cell): - """Share of the x and y coordinates (axes with a nonzero extent) within TOL_STEPS steps of a multiple of cell.""" - hit = total = 0 - for k in (0, 1): - if extents[k] <= 0: - continue - step = extents[k] / (LEVELS - 1) - tol = TOL_STEPS * step - for v in quantised: - total += 1 - hit += on_grid(v[k] * step, cell, tol) - return hit / total if total else 0.0 - - -def baseline(extent, cell): - """Share of all quantisation levels of this extent's step that are on the grid: what the step alone gives.""" - step = extent / (LEVELS - 1) - tol = TOL_STEPS * step - return sum(on_grid(q * step, cell, tol) for q in range(LEVELS)) / LEVELS - - -def vertices(b): - """The u16[3] vertices of a navmesh tile, or None when its split array does not validate.""" - blocks = nd.split_array(b, 0x70, 6, nd._u32(b, 0xC0)) - if not blocks: - return None - out = [] - for o, n in blocks: - out.extend(struct.unpack_from("<3H", b, o + 6 * i) for i in range(n)) - return out - - -def vehicle_documents(carve): - """(cell-size Counter, set of ModelName values) of the CVehiclePoints documents in a carve of common.rpf.""" - cells, names = Counter(), set() - for p in sorted(glob.glob(os.path.join(carve, "*.bin"))): - with open(p, "rb") as f: - t = f.read() - m = re.search(rb"<(CVehiclePoints\w*)[\s>]", t) - if not m or m.group(1) != b"CVehiclePoints": - continue - v = re.search(rb'([^<]+)", t)) - return cells, names - - -def name_hashes(names): - out = set() - for n in names: - for v in {n, n.lower()}: - out.add(nd.joaat_cs(v)) - out.add(nd.joaat_cs(v + ".yft")) - return out - - -def mesh_row(b): - q = vertices(b) - if q is None: - return None - ext = struct.unpack_from("<3f", b, 0x60) - return {"n": len(q), "ext": ext, "fit": {c: fit_fraction(q, ext, c) for c in DOC_CELLS + OTHER_CELLS}} - - -def measure(archive, hashes=None, min_fraction=0.9, static_every=0): - meshes, static, hash_hits, scanned, n_static = [], [], 0, 0, 0 - orig = nd.decode_navmesh - - def wrapped(b, nstreams, stats, deep): - nonlocal hash_hits, scanned, n_static - row, chk = orig(b, nstreams, stats, deep) - flags = nd._u32(b, 0x10) - if not flags & 4 and static_every: - n_static += 1 - if n_static % static_every == 0: - r = mesh_row(b) - if r is not None: - static.append(r) - if flags & 4: - scanned += 1 - if hashes and any(struct.unpack_from(" 0) for t in tiles[:20]] - out["cells"][str(c)] = {"fit": sum(1 for t in tiles if t["fit"][c] >= min_fraction), - "baseline_mean": round(sum(bases) / len(bases), 4) if bases else None} - return out - - -def summarise(meshes, min_fraction=0.9): - def fits(m, c): - return m["fit"][c] >= min_fraction - out = {"meshes": len(meshes), "vertices": sum(m["n"] for m in meshes), "cells": {}, - "fit_none": sum(1 for m in meshes if not any(fits(m, c) for c in DOC_CELLS)), - "fit_0.03125_and_0.0325": sum(1 for m in meshes if fits(m, 0.03125) and fits(m, 0.0325)), - "other_cells": {str(c): sum(1 for m in meshes if fits(m, c)) for c in OTHER_CELLS}} - for c in DOC_CELLS: - g = [m for m in meshes if next((d for d in DOC_CELLS if fits(m, d)), None) == c] - if not g: - out["cells"][str(c)] = {"meshes": 0} - continue - bases = [max(baseline(m["ext"][k], c) for k in (0, 1) if m["ext"][k] > 0) for m in g] - out["cells"][str(c)] = { - "meshes": len(g), - "distinct_xy_extents": len({(round(m["ext"][0], 4), round(m["ext"][1], 4)) for m in g}), - "min_fraction": round(min(m["fit"][c] for m in g), 6), - "baseline_max": round(max(bases), 4), "baseline_mean": round(sum(bases) / len(bases), 4), - "extents_whole_cells": sum(1 for m in g if all(abs(m["ext"][k] / c - round(m["ext"][k] / c)) < 1e-3 - for k in (0, 1))), - "vertex_counts": dict(sorted(Counter(m["n"] for m in g).items())) if len(g) <= 16 else None, - } - return out - - -def main(): - ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) - ap.add_argument("archive", help="navmeshes.rpf") - ap.add_argument("--common", help="a tools/rpf9_carve.py carve of common.rpf (CVehiclePoints counts, hash search)") - ap.add_argument("--out", help="write the summary as JSON here") - ap.add_argument("--min-fraction", type=float, default=0.9) - ap.add_argument("--static-every", type=int, default=0, help="also measure every Nth static tile as a control") - a = ap.parse_args() - if not 0 <= a.min_fraction <= 1: - ap.error("--min-fraction must be between 0 and 1") - if a.static_every < 0: - ap.error("--static-every must be non-negative") - if a.out and same_report_path(a.out, a.archive): - ap.error("--out would overwrite the archive") - if not os.path.exists(a.archive): - print(f"ERROR: cannot read {a.archive}: no such file or folder", file=sys.stderr) - return 2 - hashes, docs = None, None - if a.common: - cells, names = vehicle_documents(a.common) - hashes = name_hashes(names) - docs = {"documents": sum(cells.values()), "models": len(names), - "cell_sizes": {("absent" if k is None else str(k)): v for k, v in sorted(cells.items(), key=str)}} - summary, scanned, hits, control = measure(a.archive, hashes, a.min_fraction, a.static_every) - report = {"local_space_meshes": summary, "non_grid_scanned": scanned} - if control is not None: - report["static_control"] = control - if docs is not None: - report["vehicle_documents"] = docs - report["non_grid_with_a_model_hash"] = hits - text = json.dumps(report, indent=1) - print(text) - if a.out: - with open(a.out, "w", encoding="utf-8", newline="\n") as f: - f.write(text + "\n") - return 0 - - -if __name__ == "__main__": - try: # a redirected stdout is strict ANSI code page under -I; write '?' for what it cannot encode - sys.stdout.reconfigure(errors="replace") - except (AttributeError, ValueError, OSError): - pass - sys.exit(main()) diff --git a/tools/navmesh_decode.py b/tools/navmesh_decode.py deleted file mode 100644 index b1c7c6c7d..000000000 --- a/tools/navmesh_decode.py +++ /dev/null @@ -1,1145 +0,0 @@ -"""Decode the resource classes in a navmesh archive (``navmeshes.rpf``) without the encrypted TOC. - -The archive's data area is a run of plain zlib streams. Three resource classes start a stream there. All three -begin with the same 16 bytes: eight zero bytes and a ``0x50000000``-based pointer to a block map whose u64 at +8 -is the number of zlib streams the resource occupies (1 or 2 on the measured archive). - -``0DRP`` - A self-describing ``0x7a`` resource (``0DRP`` at +0x10, version 122): struct, enum and instance-block tables - as decoded for ``levels.rpf`` in ``docs/world.md``. In this archive the schemas are cover-point data, not - navmesh geometry. The eight u16 words at +0x48 are the struct, enum and block counts, a 4 KiB page count - (0 or ``ceil(data_end / 4096)``), and four zero words. +0x60 is the start of the first instance block, not a - header field. -``0x00010015`` - The navmesh tile: a fixed 0xF0-byte header (``u32 0x00010015`` at +0x14) with vertex, polygon and - special-link counts, four 16 KiB-blocked split arrays, a quadtree root and the tile's 512 x 512 sector id. -``grid`` - A 0x60-byte header followed by a 16-slot open-addressing hash table (272-byte groups) and a ``u32`` array. - It pairs one-to-one with the static navmesh tiles by sector id. Its subsystem is not identified. - -``PSIN`` containers are counted and section-walked. Everything else is reported as ``other``. - -A resource continues into the next zlib stream when its block map says so. Some continuations inflate to fewer -than 64 bytes; the carver walk skips those, so this tool also accepts them, but only as continuations. Stream -counts in the summary follow the carver rule (64 bytes or more) so they can be compared with -``tools/navmesh_index.py``. - -The tool reads headers, tables and counts. It writes aggregate metadata only: no payload bytes, names or keys. -It never touches the encrypted table of contents. - -Usage: - python -I navmesh_decode.py [--out FILE] [--csv FILE] - [--start N] [--limit BYTES] [--deep] [--quiet] - - --out JSON summary (default: .navmesh-decode.json in the current directory) - --csv optional CSV, one row of numeric header fields per resource - --start first byte to scan in an archive (default: the archive's data start, u32 at offset 4) - --limit bytes to scan from --start; a resource that starts inside the window is read to its end, but a - stream past the window's end is reported under past_window, not in the carver counts - --deep also walk every navmesh polygon, quadtree node and grid hash-table slot (slower) - --quiet do not print the summary -""" -import argparse -import csv -import json -import math -import mmap -import os -import re -import struct -import sys -import time -import unicodedata -import zlib -from collections import Counter -from collections.abc import Iterator - -ROOT = os.path.dirname(os.path.abspath(__file__)) -if ROOT not in sys.path: - sys.path.insert(0, ROOT) -from zero_span import gap_split # noqa: E402 - -BASE = 0x50000000 -ZHDR = re.compile(rb"\x78[\x01\x5e\x9c\xda]") -HEX_PREFIX = re.compile(r"^(?:0[xX])?([0-9a-fA-F]{6,})(?:[^0-9a-zA-Z]|$)") -CHUNK = 1 << 20 -MIN_STREAM = 64 # the carver's threshold; shorter streams are only accepted as continuations -MAX_STREAMS = 16 -MAX_INFLATE = 256 << 20 # refuse to inflate a single stream or assembled resource past this size -MAX_QT_DEPTH = 32 -MAX_QT_NODES = 1 << 20 -VERSION_7A = 122 -DATA15 = 0x00010015 -HEADER_7A = 0x60 -HEADER_NAV = 0xF0 -GRID_GROUP = 272 # 16 control bytes + 16 slots of {u64 key, u64 value} -SPLIT_BLOCK = 16384 # byte budget of one split-array block -NODE_SIZE = 160 # CCoverPointNode -REGION_SIZE = 304 # CCoverPointRegion - -# Case-sensitive joaat. Every name below was typed by hand and kept only because its hash equals a struct, enum, -# member or enum-value hash in the archive's own 0x7a schema tables. Nothing is read from the game to build it. -NAMES = ( - "CCoverPointRegion", "CCoverPointNode", "CCoverNodeId", "CCoverPointUsageInfo", "CCoverSpatialTree", - "CCoverSpatialTreeNode", "CCoverPointRegionManifest", "CCoverPointRegionDef", "rage__spdAABB", - "eCoverFlags", "eCoverHeight", "eCoverUsage", "eCoverRegionFlags", "Uid", "SpatialTreeNodes", "Entries", - "RegionIndex", "COVHEIGHT_PRONE", "COVUSE_WALLTOLEFT", "COVUSE_WALLTORIGHT", "COVUSE_WALLTOBOTH", - "COVUSE_WALLTONEITHER", -) -REGION = 0x2283B2CB -NODE = 0x0BCB00E4 -DYNAMIC_COVER = 0x4712787B - -COLUMNS = [ - "offset", "class", "streams", "stored", "inflated", "complete", "checks_failed", - "version", "root_index", "n_structs", "n_enums", "n_blocks", "pages_4k", "root_hash", "cover_nodes", - "flags", "sector", "vertices", "polygons", "pool", "special_links", "volumes", "data_size", - "groups", "entries", "extent", -] - - -def joaat_cs(text): - """Jenkins one-at-a-time over the exact bytes (no lower-casing), as the 0x7a schema hashes use.""" - h = 0 - for c in text.encode("ascii"): - h = (h + c) & 0xFFFFFFFF - h = (h + (h << 10)) & 0xFFFFFFFF - h ^= h >> 6 - h = (h + (h << 3)) & 0xFFFFFFFF - h ^= h >> 11 - return (h + (h << 15)) & 0xFFFFFFFF - - -KNOWN = {joaat_cs(n): n for n in NAMES} - - -def _u16(b, o): - return struct.unpack_from("> 32 or not BASE <= value < BASE + 0x10000000: - return None - return value - BASE - - -def hx(value): - return "0x%08x" % value - - -def label(value): - return KNOWN.get(value, hx(value)) - - -# ---------------------------------------------------------------------------------------------------- streams - -def inflate_at(m, start, size, cap=MAX_INFLATE): - """Inflate one zlib stream within [start, size). Returns (data, stored_bytes) or None.""" - d = zlib.decompressobj() - parts, total, pos, pending = [], 0, start, b"" - try: - while not d.eof: - if not pending: - if pos >= size: - return None - pending = m[pos:min(pos + CHUNK, size)] - pos += len(pending) - out = d.decompress(pending, cap + 1 - total) - pending = d.unconsumed_tail - total += len(out) - if total > cap: - return None - parts.append(out) - except zlib.error: - return None - return b"".join(parts), pos - start - len(d.unused_data) - len(pending) - - -def walk(m, start, size): - """Yield (offset, stored, data) for every zlib stream from `start`, advancing by the bytes it consumed.""" - pos = start - while pos < size: - found = ZHDR.search(m, pos, size) - if not found: - return - s = found.start() - got = inflate_at(m, s, size) - if got is None or got[1] <= 0: - pos = s + 1 - continue - data, used = got - yield s, used, data - pos = s + used - - -def carved_files(root: str) -> Iterator[os.DirEntry[str]]: - with os.scandir(root) as entries: - for entry in entries: - if not entry.name.lower().endswith((".json", ".csv")) and entry.is_file(): - yield entry - - -def walk_dir(root): - """Yield (offset, None, data) from carved files sorted by leading hex offset, then name.""" - entries = [] - for entry in carved_files(root): - name, full = entry.name, entry.path - if os.path.getsize(full) > MAX_INFLATE: - raise ValueError("%s exceeds %d-byte limit" % (full, MAX_INFLATE)) - mt = HEX_PREFIX.match(name) - off = int(mt.group(1), 16) if mt else None - entries.append((off, name, full)) - fallback = 0 - for off, _, full in sorted(entries, key=lambda e: (e[0] is None, e[0] or 0, e[1])): - if off is None: - off = fallback - fallback = max(fallback, off + 1) - with open(full, "rb") as f: - yield off, None, f.read() - - -# ------------------------------------------------------------------------------------------------ classifying - -def classify(b): - if len(b) >= 4 and b[:4] == b"PSIN": - return "psin" - if len(b) >= HEADER_7A and b[0x10:0x14] == b"0DRP": - return "0drp" - if len(b) < 0x60 or not _zero(b, 0, 8) or offset_of(_u64(b, 8)) is None: - return "other" - if len(b) >= HEADER_NAV and _u32(b, 0x14) == DATA15: - return "navmesh" - groups = _u32(b, 0x10) - if (_u64(b, 0x18) == BASE + 0x60 and groups and groups & (groups - 1) == 0 - and _u32(b, 0x14) == _u32(b, 0x50)): - return "grid" - return "other" - - -def _psin_state(b): - """Return (complete, sections, needs_more) for a PSIN container.""" - if len(b) < 16: - return False, 0, True - at = struct.unpack_from(">I", b, 4)[0] - if at < 16: - return False, 0, False - count = 0 - while at + 8 <= len(b): - size = struct.unpack_from(">I", b, at + 4)[0] - if size < 8: - return False, count, False - at += size - count += 1 - if at == len(b): - # Ends exactly here: complete with at least one section; a bare header is incomplete, not continued. - return count > 0, count, False - return False, count, True - - -def wants_more(cls, b, nstreams): - """True when the resource in `b` (made of `nstreams` streams) should consume the next stream.""" - if nstreams >= MAX_STREAMS or len(b) >= MAX_INFLATE: - return False - if cls == "psin": - return _psin_state(b)[2] - if cls not in ("0drp", "navmesh", "grid"): - return False - bm = offset_of(_u64(b, 8)) - if bm is None: - return False - if bm + 16 > len(b): - return True - declared = _u64(b, bm + 8) - return declared is not None and nstreams < min(declared, MAX_STREAMS) - - -def is_complete(cls, b, nstreams): - """True when the resource in `b` has all streams declared by its header/block map (ignoring MAX_STREAMS).""" - if cls == "psin": - return _psin_state(b)[0] - if cls not in ("0drp", "navmesh", "grid"): - return True - bm = offset_of(_u64(b, 8)) - if bm is None or bm + 16 > len(b): - return False - declared = _u64(b, bm + 8) - return declared == nstreams - - -def block_map_ok(b, nstreams, size=24): - """Verify the block map at u64@0x08: {u64 0, u64 stream_count, u64 0[, u64 0]}.""" - bm = offset_of(_u64(b, 8)) - if bm is None or bm + size > len(b): - return False - if _u64(b, bm) != 0 or _u64(b, bm + 8) != nstreams or _u64(b, bm + 16) != 0: - return False - return size <= 24 or _u64(b, bm + 24) == 0 - - -# ----------------------------------------------------------------------------------------------------- 0DRP - -def decode_7a(b, len0, nstreams, stats): - """Decode a 0x7a resource. Returns (row, checks).""" - chk = {} - n28, n30, n38, n4e = (_u16(b, 0x48 + 2 * i) for i in range(4)) - version = _u32(b, 0x14) - root_index = _u32(b, 0x20) - q28, q30, q38, q40 = (offset_of(_u64(b, o)) for o in (0x28, 0x30, 0x38, 0x40)) - chk["prefix_zero"] = _zero(b, 0, 8) - chk["version_122"] = version == VERSION_7A - chk["reserved_zero"] = _zero(b, 0x18, 0x20) and _zero(b, 0x24, 0x28) and _zero(b, 0x50, 0x60) - chk["block_map"] = block_map_ok(b, nstreams, size=24) - row = {"version": version, "root_index": root_index, "n_structs": n28, "n_enums": n30, "n_blocks": n38, - "pages_4k": n4e, "root_hash": None, "cover_nodes": None} - - # Instance blocks: {u32 struct hash, u32 byte size, u64 pointer}. - blocks = [] - ok = q38 is not None and q38 + 16 * n38 <= len(b) - if ok: - for i in range(n38): - h, size, p = struct.unpack_from(" len(b): - ok = False - blocks = [] - break - blocks.append((h, size, t)) - chk["blocks_in_bounds"] = ok - spans = sorted((t, t + size) for _, size, t in blocks) - chk["blocks_disjoint"] = ok and all(a[1] <= c[0] for a, c in zip(spans, spans[1:])) - chk["payload_at_0x60"] = ok and any(t == HEADER_7A for _, _, t in blocks) - chk["root_index_valid"] = ok and root_index is not None and 1 <= root_index <= len(blocks) - root = blocks[root_index - 1] if chk["root_index_valid"] else None - - # Struct table: 32-byte records; member table: 16-byte records. - structs = {} - ok = q28 is not None and q28 + 32 * n28 <= len(b) - if ok: - for i in range(n28): - h, _, _, mp, size, _, count = struct.unpack_from(" len(b): - ok = False - structs = {} - break - structs[h] = (size, count, mt) - chk["structs_in_bounds"] = ok - chk["root_is_struct"] = root is not None and root[0] in structs - - # Enum table: 24-byte records {u32 hash, u32 signature, u64 -> values, u64 count}; values are 16 bytes. - ok = n30 == 0 or (q30 is not None and q30 + 24 * n30 <= len(b)) - dense = ok - checked_enums = {} - if ok: - for i in range(n30): - h, _, vp, count = struct.unpack_from(" 0x10000 or vt + 16 * count > len(b): - ok = dense = False - break - key = (vt, count) - if key not in checked_enums: - values = [struct.unpack_from("2"] += 1 - chk["q40_in_bounds"] = end is not None and end <= len(b) - - # u16@0x4e: always 0 or ceil(data_end / 4096). Equals pages whenever pages*4096 < stream_end, and 0 when - # pages*4096 > stream_end or on single-stream pages hitting the stream end; on two-stream pages where - # data_end lands in the final 4 KiB of stream 0 (pages*4096 == len0), both 0 and pages occur. - bm = offset_of(_u64(b, 8)) - if chk["blocks_in_bounds"] and blocks and bm is not None and q38 is not None: - data_end = max([t + size for _, size, t in blocks] + [q38 + 16 * n38, bm + 24]) - pages = (data_end + 4095) // 4096 - stream_end = len0 if data_end <= len0 else len(b) - if pages * 4096 < stream_end: - chk["pages_4k_rule"] = n4e == pages - elif data_end <= len0 and pages * 4096 == len0 and nstreams > 1: - chk["pages_4k_rule"] = n4e in (0, pages) - if n4e == pages: - stats["pages_4k_boundary"]["nonzero"] += 1 - elif n4e == 0: - stats["pages_4k_boundary"]["zero"] += 1 - else: - chk["pages_4k_rule"] = n4e == 0 - else: - chk["pages_4k_rule"] = False - - sig = tuple(sorted(structs)) - stats["schemas"][(label(root[0]) if root else "none", len(sig))] += 1 - stats["root"][label(root[0]) if root else "none"] += 1 - first = next((h for h, _, t in blocks if t == HEADER_7A), None) - stats["block_at_0x60"][label(first) if first is not None else "none"] += 1 - for h, _, _ in blocks: - stats["block_hash"][label(h)] += 1 - stats["u16"]["n_structs"][n28] += 1 - stats["u16"]["n_enums"][n30] += 1 - stats["u16"]["n_blocks"][n38] += 1 - stats["pages_4k_zero"] += n4e == 0 - stats["root_index"][root_index] += 1 - if root: - row["root_hash"] = hx(root[0]) - - # Cover payload: the node array, and the three 16-byte node ids at the start of every node. The first node - # usually sits at +0x60, which is what the old "+0x60 key / +0x68 u32 / +0x70 repeats" description saw. - nodes = [(size, t) for h, size, t in blocks if h == NODE] - if nodes and structs.get(NODE, (0,))[0] == NODE_SIZE: - size, t = nodes[0] - chk["cover_nodes_whole"] = size % NODE_SIZE == 0 - count = size // NODE_SIZE - row["cover_nodes"] = count - stats["cover_nodes"] += count - if root and root[0] == REGION: - stats["region_cover_nodes"] += count - elif root and root[0] == DYNAMIC_COVER: - stats["dynamic_cover_nodes"] += count - if t == HEADER_7A and count: - _, _, local0, _, _, local1 = struct.unpack_from(" len(b): - return None - _, declared, bp, sp, nblocks, tail = struct.unpack_from(" 0x10000 or bp is None or sp is None: - return None - if bp + 16 * nblocks > len(b) or sp + 4 * nblocks > len(b): - return None - per = SPLIT_BLOCK // stride - out, acc = [], 0 - for i in range(nblocks): - p, count = struct.unpack_from(" len(b) or _u32(b, sp + 4 * i) != acc: - return None - if i + 1 < nblocks and count != per: - return None - out.append((o, count)) - acc += count - return out if acc == total else None - - -def _u16_max(b, o, n): - if n == 0: - return -1 - view = memoryview(b)[o:o + 2 * n] - try: - if sys.byteorder == "little": - return max(view.cast("H")) - return max(v for (v,) in struct.iter_unpack(" MAX_QT_DEPTH or nodes >= MAX_QT_NODES or o + 0x60 > len(b): - return False, nodes, leaves, max_depth - seen.add(o) - nodes += 1 - if depth > max_depth: - max_depth = depth - if not _zero(b, o + 0x54, o + 0x60): - return False, nodes, leaves, max_depth - leaf_raw, c0, c1, c2, c3 = struct.unpack_from("<5Q", b, o + 0x2C) - if leaf_raw: - lo = offset_of(leaf_raw) - if lo is None or lo + 0x20 > len(b): - return False, nodes, leaves, max_depth - if lo not in seen_leaves: - z0, pp, z1, np = struct.unpack_from("<4Q", b, lo) - if z0 != 0 or z1 != 0 or np > n_polys: - return False, nodes, leaves, max_depth - if np: - po = offset_of(pp) - if po is None or po + 2 * np > len(b) or _u16_max(b, po, np) >= n_polys: - return False, nodes, leaves, max_depth - seen_leaves.add(lo) - leaves += 1 - for cp in (c0, c1, c2, c3): - if cp: - co = offset_of(cp) - if co is None: - return False, nodes, leaves, max_depth - stack.append((co, depth + 1)) - return True, nodes, leaves, max_depth - - -def decode_navmesh(b, nstreams, stats, deep): - chk = {} - flags = _u32(b, 0x10) - c0, c4, c8, cc, d4, d8, dc, e8 = (_u32(b, o) for o in (0xC0, 0xC4, 0xC8, 0xCC, 0xD4, 0xD8, 0xDC, 0xE8)) - pool = _u32(b, 0x90) - a8, b0, b8 = (_u64(b, o) for o in (0xA8, 0xB0, 0xB8)) - chk["prefix_zero"] = _zero(b, 0, 8) - chk["block_map"] = block_map_ok(b, nstreams, size=32) - chk["reserved_zero"] = all(_zero(b, lo, hi) for lo, hi in NAV_ZERO) - chk["identity_matrix"] = _f32s(b, 0x20, 16) == IDENTITY - chk["data_size_identity"] = cc == 6 * c0 + (2 + 12) * pool + 44 * c4 + 32 * d4 - chk["flag0_set"] = bool(flags & 1) - links = bool(a8 and b0 and d4 and d8) - no_links = not (a8 or b0 or d4 or d8) - chk["flag1_links"] = links if flags & 2 else no_links - chk["flag2_no_sector"] = (c8 == 0 and e8 == 0) == bool(flags & 4) - blocks = [] - for at, stride, count_at in SPLITS: - got = split_array(b, at, stride, _u32(b, count_at)) - chk["split_%02x" % at] = got is not None - blocks.append(got) - if got is not None: - stats["split_blocks_max"][hex(at)] = max(stats["split_blocks_max"].get(hex(at), 0), len(got)) - if blocks[1] is not None: - chk["indices_below_vertices"] = all(_u16_max(b, o, n) < c0 for o, n in blocks[1]) - ok = True - if flags & 2: - la, lb = offset_of(a8), offset_of(b0) - ok = (la is not None and lb is not None and la + 32 * d4 <= len(b) and lb + 2 * d8 <= len(b) - and _u16_max(b, lb, d8) < d4) - chk["links_in_bounds"] = ok - vol = offset_of(b8) - chk["volumes_in_bounds"] = (b8 == 0 and dc == 0) or (vol is not None and vol + 96 * dc <= len(b)) - - root = offset_of(_u64(b, 0xA0)) - chk["quadtree_root"] = root is not None and root + 0x60 <= len(b) - lo = _f32s(b, root, 3) if chk["quadtree_root"] else None - hi = _f32s(b, root + 0x10, 3) if chk["quadtree_root"] else None - ext = _f32s(b, 0x60, 3) - chk["extents_match_root"] = (lo is not None and hi is not None and ext is not None - and all(math.isfinite(v) for v in (*lo, *hi, *ext)) - and all(abs((hi[i] - lo[i]) - ext[i]) < 0.02 for i in range(3))) - if not flags & 4: - sx, sy = c8 & 0x1FF, c8 >> 9 - x0, y0 = (sx - 256) * 128.0, (sy - 256) * 128.0 - chk["sector_origin"] = (lo is not None and hi is not None and (lo[0], lo[1]) == (x0, y0) - and (hi[0], hi[1]) == (x0 + 128.0, y0 + 128.0)) - chk["tile_128m"] = ext is not None and (ext[0], ext[1]) == (128.0, 128.0) - stats["sectors"].add(c8) - stats["sector_x"][0] = min(stats["sector_x"][0], sx) - stats["sector_x"][1] = max(stats["sector_x"][1], sx) - stats["sector_y"][0] = min(stats["sector_y"][0], sy) - stats["sector_y"][1] = max(stats["sector_y"][1], sy) - _extend(stats["tile_bounds"], lo, hi) - if deep: - if blocks[3] is not None: - chain_ok, has_water = _poly_chain(b, blocks[3], c8, pool) - chk["polygons_chain"] = chain_ok - stats["water_bit3"]["b3_%d_w_%d" % (bool(flags & 8), has_water)] += 1 - qt_ok, qn, ql, qd = _walk_quadtree(b, root, c4) - chk["quadtree_valid"] = qt_ok - stats["quadtree"]["nodes"] += qn - stats["quadtree"]["leaves"] += ql - stats["quadtree"]["max_depth"] = max(stats["quadtree"]["max_depth"], qd) - chk["volumes_valid"] = _walk_volumes(b, vol, dc, stats) - - stats["flags"][flags] += 1 - stats["build"][hx(e8)] += 1 - for key, value in (("vertices", c0), ("polygons", c4), ("pool", pool), ("special_links", d4), - ("link_indices", d8), ("volumes", dc)): - stats["totals"][key] += value - stats["max"][key] = max(stats["max"].get(key, 0), value) - row = {"flags": flags, "sector": c8, "vertices": c0, "polygons": c4, "pool": pool, "special_links": d4, - "volumes": dc, "data_size": cc} - return row, chk - - -def _poly_chain(b, blocks, owner, pool): - """Every polygon's +0 is the tile id; +4 is (first index << 4) | count and the runs tile the index pool.""" - nxt = 0 - has_water = False - for o, n in blocks: - for mesh, packed, pf18 in struct.iter_unpack("> 4 != nxt: - return False, has_water - if pf18 & 0x80000: - has_water = True - nxt += packed & 0xF - return nxt == pool, has_water - - -def _walk_volumes(b, vol, dc, stats): - """Paired 96-byte obstacle footprint records at +0xB8 (count u32@0xDC, ASSET-281).""" - if dc == 0: - return vol is None - if vol is None or dc % 2 != 0 or vol + 96 * dc > len(b): - return False - flags = Counter() - vertex_counts = Counter() - for p in range(dc // 2): - o0 = vol + (2 * p) * 96 - o1 = o0 + 96 - if b[o0:o0 + 20] != b[o1:o1 + 20]: - return False - xyz = _f32s(b, o0 + 8, 3) - if xyz is None or not all(math.isfinite(v) for v in xyz): - return False - f0, vc0 = b[o0 + 0x14], b[o0 + 0x15] - f1, vc1 = b[o1 + 0x14], b[o1 + 0x15] - if f0 not in (0, 4) or f1 != 8 or vc0 not in (4, 8) or vc1 != 4: - return False - if not (_zero(b, o0 + 0x16 + 4 * vc0, o0 + 0x56) and _zero(b, o0 + 0x5A, o0 + 0x60)): - return False - if not (_zero(b, o1 + 0x16 + 4 * vc1, o1 + 0x56) and _zero(b, o1 + 0x5A, o1 + 0x60)): - return False - flags[f0] += 1 - flags[f1] += 1 - vertex_counts[vc0] += 1 - vertex_counts[vc1] += 1 - vstats = stats["volumes"] - vstats["pairs"] += dc // 2 - vstats["flags"].update(flags) - vstats["vertex_counts"].update(vertex_counts) - return True - - -# ------------------------------------------------------------------------------------------------------ grid - -def decode_grid(b, nstreams, stats, deep): - chk = {} - groups, entries = _u32(b, 0x10), _u32(b, 0x14) - payload = offset_of(_u64(b, 0x20)) - ex = struct.unpack_from("<3I", b, 0x28) - sector = _u32(b, 0x34) - origin = _f32s(b, 0x40, 3) - chk["prefix_zero"] = _zero(b, 0, 8) - chk["block_map"] = block_map_ok(b, nstreams, size=32) - chk["reserved_zero"] = _zero(b, 0x38, 0x40) and _zero(b, 0x4C, 0x50) and _zero(b, 0x54, 0x60) - chk["table_in_bounds"] = 0x60 + GRID_GROUP * groups <= len(b) - chk["payload_in_bounds"] = payload is not None and payload + 4 * entries <= len(b) - chk["cubic_extent"] = ex[0] == ex[1] == ex[2] - sx, sy = sector & 0x1FF, sector >> 9 - chk["sector_origin"] = origin is not None and (origin[0], origin[1]) == ((sx - 256) * 128.0, (sy - 256) * 128.0) - if chk["table_in_bounds"]: - ctrl = b"".join(b[0x60 + GRID_GROUP * g:0x60 + GRID_GROUP * g + 16] for g in range(groups)) - empty = ctrl.count(0x80) - valid_ctrl = max(ctrl) <= 0x80 if ctrl else True - used = len(ctrl) - empty if valid_ctrl else -1 - chk["control_bytes"] = valid_ctrl - chk["occupied_equals_entries"] = valid_ctrl and used == entries - if deep: - chk["values_bijective"] = chk["occupied_equals_entries"] and _grid_values(b, groups, entries) - if chk["values_bijective"] and chk["payload_in_bounds"]: - keys = _grid_slots(b, groups) - chk["keys_octree"] = len(keys) == entries and _grid_octree(keys) - if chk["keys_octree"]: - chk["inner_payload_ff00"] = _grid_payloads(b, payload, keys, stats) - stats["groups"][groups] += 1 - stats["extent"][ex[0]] += 1 - oz = origin[2] if (origin and math.isfinite(origin[2])) else None - stats["oz"][oz] += 1 - stats["sectors"].add(sector) - stats["entries_total"] += entries - stats["entries_max"] = max(stats["entries_max"], entries) - return {"sector": sector, "groups": groups, "entries": entries, "extent": ex[0]}, chk - - -def _grid_values(b, groups, entries): - seen = bytearray(entries) - for g in range(groups): - base = 0x60 + GRID_GROUP * g - for k, c in enumerate(b[base:base + 16]): - if c < 0x80: - value = _u64(b, base + 16 + 16 * k + 8) - if value is None or value >= entries or seen[value]: - return False - seen[value] = 1 - return all(seen) - - -def _grid_slots(b, groups): - """{key: value} of every occupied slot (call after _grid_values has accepted the table).""" - keys = {} - for g in range(groups): - base = 0x60 + GRID_GROUP * g - for k, c in enumerate(b[base:base + 16]): - if c < 0x80: - keys[_u64(b, base + 16 + 16 * k)] = _u64(b, base + 16 + 16 * k + 8) - return keys - - -def _grid_octree(keys): - """Keys are sentinel-bit linear octree keys: 1 is the root, a child is (parent << 3) | octant.""" - if 1 not in keys: - return False - for key in keys: - if key == 0 or (key.bit_length() - 1) % 3 or (key != 1 and key >> 3 not in keys): - return False - return True - - -GRID_INNER = 0x0000FF00 # payload of every node that has children -GRID_LEAF_KIND = {0x01: "low_byte_01", 0x03: "low_byte_03"} - - -def _grid_payloads(b, payload, keys, stats): - """Inner nodes carry 0x0000ff00; count leaf payloads by low byte and every key by depth.""" - inner = {key >> 3 for key in keys if key != 1} - words = {key: _u32(b, payload + 4 * value) for key, value in keys.items()} - if any(words[key] != GRID_INNER for key in inner): - return False - stats["inner_nodes"] += len(inner) - for key, word in words.items(): - stats["key_depth"][(key.bit_length() - 1) // 3] += 1 - if key in inner: - continue - kind = "ff00" if word == GRID_INNER else GRID_LEAF_KIND.get(word & 0xFF, "other") - stats["leaf_payload"][kind] += 1 - return True - - -# ------------------------------------------------------------------------------------------------------ scan - -def new_stats(): - inf = float("inf") - return { - "0drp": {"schemas": Counter(), "root": Counter(), "block_at_0x60": Counter(), "block_hash": Counter(), - "enums": Counter(), "q40_shape": Counter(), "root_index": Counter(), "pages_4k_zero": 0, - "pages_4k_boundary": Counter(), - "u16": {"n_structs": Counter(), "n_enums": Counter(), "n_blocks": Counter()}, - "cover_nodes": 0, "region_cover_nodes": 0, "dynamic_cover_nodes": 0, - "region_points": 0, "region_inumpoints": Counter(), "first_node": Counter(), - "region_bounds": [[inf] * 3, [-inf] * 3]}, - "navmesh": {"flags": Counter(), "build": Counter(), "totals": Counter(), "max": {}, "sectors": set(), - "sector_x": [inf, -inf], "sector_y": [inf, -inf], "split_blocks_max": {}, - "tile_bounds": [[inf] * 3, [-inf] * 3], "water_bit3": Counter(), - "quadtree": {"nodes": 0, "leaves": 0, "max_depth": 0}, - "volumes": {"pairs": 0, "flags": Counter(), "vertex_counts": Counter()}}, - "grid": {"groups": Counter(), "extent": Counter(), "oz": Counter(), "sectors": set(), "entries_total": 0, - "entries_max": 0, "key_depth": Counter(), "inner_nodes": 0, "leaf_payload": Counter()}, - "psin": {"version": Counter(), "complete": 0}, - } - - -def scan(path, start=None, limit=None, deep=False, rows=None): - """Decode every resource in an RPF9 archive or carved directory. Returns the summary dict.""" - if os.path.isdir(path): - return _scan_dir(path, deep, rows) - return _scan_rpf(path, start, limit, deep, rows) - - -def _scan_dir(path, deep, rows): - t0 = time.time() - stats = new_stats() - classes, checks, carver = {}, {}, Counter() - stream = walk_dir(path) - pending = next(stream, None) - while pending is not None: - s, used, head = pending - pending = next(stream, None) - if len(head) < MIN_STREAM: - carver["tiny_orphans"] += 1 - continue - carver["streams"] += 1 - carver["inflated"] += len(head) - cls = classify(head) - parts = [(s, used, head)] - buf = bytearray(head) - while pending is not None and wants_more(cls, buf, len(parts)): - if len(buf) + len(pending[2]) > MAX_INFLATE: - break - parts.append(pending) - _, _, cdata = pending - buf.extend(cdata) - if len(cdata) < MIN_STREAM: - carver["tiny_continuations"] += 1 - else: - carver["streams"] += 1 - carver["inflated"] += len(cdata) - pending = next(stream, None) - data = bytes(buf) - complete = is_complete(cls, data, len(parts)) - row, chk = _decode(cls, data, len(head), len(parts), stats, deep) - _record(classes, checks, cls, parts, data, complete, chk) - if rows is not None: - row.update({"offset": s, "class": cls, "streams": len(parts), "stored": None, - "inflated": len(data), "complete": complete, - "checks_failed": " ".join(k for k, v in sorted(chk.items()) if not v)}) - rows.append(row) - return _summary(path, "directory", None, None, carver, classes, checks, stats, time.time() - t0) - - -def _scan_rpf(path, start, limit, deep, rows): - t0 = time.time() - stats = new_stats() - classes, checks, carver = {}, {}, Counter() - with open(path, "rb") as fh: - size = os.fstat(fh.fileno()).st_size - if size < 8: - raise ValueError("%s is %d bytes, too small for an RPF header" % (path, size)) - with mmap.mmap(fh.fileno(), 0, access=mmap.ACCESS_READ) as m: - if m[1:4] != b"FPR" or m[0:1] not in (b"7", b"8", b"9"): - raise ValueError("%s: not an RPF7/8/9 archive" % path) - data_start = struct.unpack_from(" MAX_INFLATE: - break - parts.append(pending) - cs, cused, cdata = pending - buf.extend(cdata) - if len(cdata) < MIN_STREAM: - carver["tiny_continuations"] += 1 - else: - last = _account(m, carver, last, cs, cused, len(cdata), end) - pending = next(stream, None) - data = bytes(buf) - complete = is_complete(cls, data, len(parts)) - row, chk = _decode(cls, data, len(head), len(parts), stats, deep) - _record(classes, checks, cls, parts, data, complete, chk) - if rows is not None: - row.update({"offset": s, "class": cls, "streams": len(parts), - "stored": sum(p[1] for p in parts), "inflated": len(data), "complete": complete, - "checks_failed": " ".join(k for k, v in sorted(chk.items()) if not v)}) - rows.append(row) - if last < end: - gap_zero, gap_unread = gap_split(m, last, end) - carver["zero_padding" if not gap_unread else "unread"] += gap_zero + gap_unread - return _summary(path, "rpf", start, end, carver, classes, checks, stats, time.time() - t0) - - -def _account(m, carver, last, s, used, inflated, end): - """Carver-compatible accounting of one stream of 64 bytes or more, plus the gap before it. - - A stream that runs past the --limit window is still decoded (a resource is read to its end) but, as in - navmesh_index.py (#766), it is not counted as carved: its bytes inside the window fall into the tail, so - streams + zero_padding + unread add up to the span. It is reported under past_window instead.""" - if s + used > end: - carver["past_window"] += 1 - carver["past_window_stored"] += used - return last - if s > last and last < end: - gap_zero, gap_unread = gap_split(m, last, min(s, end)) - carver["zero_padding" if not gap_unread else "unread"] += gap_zero + gap_unread - carver["streams"] += 1 - carver["stored"] += used - carver["inflated"] += inflated - return max(last, s + used) - - -def _decode(cls, buf, len0, nstreams, stats, deep): - if cls == "0drp": - return decode_7a(buf, len0, nstreams, stats["0drp"]) - if cls == "navmesh": - return decode_navmesh(buf, nstreams, stats["navmesh"], deep) - if cls == "grid": - return decode_grid(buf, nstreams, stats["grid"], deep) - if cls == "psin": - complete, _, _ = _psin_state(buf) - stats["psin"]["version"][_u32(buf, 8)] += 1 - stats["psin"]["complete"] += complete - return {}, {} - return {}, {} - - -def _record(classes, checks, cls, parts, buf, complete, chk): - c = classes.setdefault(cls, {"resources": 0, "streams": Counter(), "stored": 0, "inflated": 0, - "incomplete": 0}) - c["resources"] += 1 - c["streams"][len(parts)] += 1 - if parts[0][1] is not None: - c["stored"] += sum(p[1] for p in parts) - c["inflated"] += len(buf) - c["incomplete"] += not complete - table = checks.setdefault(cls, {}) - for name, value in chk.items(): - slot = table.setdefault(name, [0, 0]) - slot[0 if value else 1] += 1 - - -def _counter(c, key=str): - return {key(k): v for k, v in sorted(c.items(), key=lambda kv: (-kv[1], str(kv[0])))} - - -def _box(box): - if box[0][0] == float("inf"): - return None - return {"min": [round(v, 3) for v in box[0]], "max": [round(v, 3) for v in box[1]]} - - -def _summary(path, mode, start, end, carver, classes, checks, stats, elapsed): - d, n, g = stats["0drp"], stats["navmesh"], stats["grid"] - static = n["sectors"] - return { - "input": os.path.basename(os.path.abspath(path)), - "mode": mode, - "start": start, - "end": end, - "span": (end - start) if (start is not None and end is not None) else None, - "carver_streams": {k: carver.get(k, 0) for k in ("streams", "stored", "inflated", "zero_padding", - "unread", "tiny_continuations", "tiny_orphans", - "past_window", "past_window_stored")}, - "resources": {cls: dict(v, streams={str(k): c for k, c in sorted(v["streams"].items())}) - for cls, v in sorted(classes.items())}, - "checks": {cls: {name: {"pass": p, "fail": f} for name, (p, f) in sorted(t.items())} - for cls, t in sorted(checks.items())}, - "0drp": { - "schemas": {"%s/%d structs" % k: v for k, v in sorted(d["schemas"].items(), key=lambda kv: -kv[1])}, - "root": _counter(d["root"]), - "block_at_0x60": _counter(d["block_at_0x60"]), - "block_hash": _counter(d["block_hash"]), - "enums": _counter(d["enums"]), - "q40_shape": _counter(d["q40_shape"]), - "root_index": _counter(d["root_index"]), - "u16_0x48": {k: _counter(v) for k, v in d["u16"].items()}, - "pages_4k_zero": d["pages_4k_zero"], - "pages_4k_boundary": dict(d["pages_4k_boundary"]), - "cover_nodes": d["cover_nodes"], - "region_cover_nodes": d["region_cover_nodes"], - "dynamic_cover_nodes": d["dynamic_cover_nodes"], - "region_points": d["region_points"], - "region_inumpoints": dict(d["region_inumpoints"]), - "first_node": dict(d["first_node"]), - "region_bounds": _box(d["region_bounds"]), - }, - "navmesh": { - "flags": _counter(n["flags"]), - "build_ids": len(n["build"]), - "totals": dict(n["totals"]), - "max": n["max"], - "static_sectors": len(static), - "sector_x": n["sector_x"] if static else None, - "sector_y": n["sector_y"] if static else None, - "split_blocks_max": n["split_blocks_max"], - "tile_bounds": _box(n["tile_bounds"]), - "water_bit3": dict(n["water_bit3"]), - "quadtree": dict(n["quadtree"]), - "volumes": {"pairs": n["volumes"]["pairs"], "flags": _counter(n["volumes"]["flags"]), - "vertex_counts": _counter(n["volumes"]["vertex_counts"])}, - }, - "grid": { - "groups": _counter(g["groups"]), - "extent": _counter(g["extent"]), - "origin_z": _counter(g["oz"]), - "sectors": len(g["sectors"]), - "sectors_not_in_navmesh": len(g["sectors"] - static), - "navmesh_sectors_not_in_grid": len(static - g["sectors"]), - "entries_total": g["entries_total"], - "entries_max": g["entries_max"], - "key_depth": _counter(g["key_depth"]), - "inner_nodes": g["inner_nodes"], - "leaf_payload": _counter(g["leaf_payload"]), - }, - "psin": {"version": _counter(stats["psin"]["version"]), "complete": stats["psin"]["complete"]}, - "elapsed_s": round(elapsed, 1), - } - - -def _make_parent(path): - """Create the folder an output path lives in: the scan is over by the time we write, so a missing - folder used to end the run in a FileNotFoundError and lose the result.""" - parent = os.path.dirname(os.path.abspath(path)) - if parent: - os.makedirs(parent, exist_ok=True) - - -def write_csv(path, rows): - _make_parent(path) - with open(path, "w", newline="", encoding="utf-8") as f: - w = csv.DictWriter(f, fieldnames=COLUMNS, extrasaction="ignore", lineterminator="\n") - w.writeheader() - for r in rows: - w.writerow({k: ("" if r.get(k) is None else r.get(k)) for k in COLUMNS}) - - -def _positive(text): - value = int(text, 0) - if value <= 0: - raise argparse.ArgumentTypeError("must be greater than zero") - return value - - -def _offset(text): - value = int(text, 0) - if value < 0: - raise argparse.ArgumentTypeError("must not be negative") - return value - - -_PC_CASE_SENSITIVE = 11 # on macOS; os.pathconf_names doesn't list it - - -def _case_insensitive_volume(path): - """True when the volume that will hold `path` ignores letter case, as macOS's default APFS volume does. - os.path.normcase folds case only on Windows, so on macOS `R.json` and `r.json` would pass as two reports.""" - if sys.platform != "darwin": - return False - while not os.path.exists(path): - parent = os.path.dirname(path) - if parent == path: - break - path = parent - try: - return os.pathconf(path, _PC_CASE_SENSITIVE) == 0 - except (OSError, ValueError): - return True # the macOS default; folding can only refuse a pair, never overwrite one - - -def _path_key(path): - path = os.path.normcase(os.path.realpath(path)) - if _case_insensitive_volume(path): - # APFS and HFS+ also treat composed and decomposed accents as one name. - path = unicodedata.normalize("NFD", path.casefold()) - return path - - -def same_report_path(first, second): - if _path_key(first) == _path_key(second): - return True - try: - return os.path.samefile(first, second) - except OSError: - return False - - -def main(argv=None): - ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) - ap.add_argument("input", help="RPF9 archive (navmeshes.rpf) or directory of carved streams") - ap.add_argument("--out", help="JSON summary (default: .navmesh-decode.json)") - ap.add_argument("--csv", help="optional CSV, one row per resource") - ap.add_argument("--start", type=_offset, help="first byte to scan in an archive") - ap.add_argument("--limit", type=_positive, help="bytes to scan from --start") - ap.add_argument("--deep", action="store_true", help="walk every polygon, quadtree node and grid slot") - ap.add_argument("--quiet", action="store_true", help="do not print the summary") - a = ap.parse_args(argv) - if not os.path.exists(a.input): - ap.error("%s does not exist" % a.input) - if os.path.isdir(a.input) and (a.start is not None or a.limit is not None): - ap.error("--start and --limit apply to archive inputs only") - base = os.path.basename(os.path.abspath(a.input)) or "navmesh" - out = a.out or os.path.splitext(base)[0] + ".navmesh-decode.json" - if a.csv and same_report_path(out, a.csv): - ap.error("--out and --csv must use different paths") - for flag, path in (("--out", out), ("--csv", a.csv)): - if not path: - continue - if os.path.isdir(path): # open() on a folder ends the run in a PermissionError traceback - ap.error(f"{flag} is a directory: {path}") - if same_report_path(path, a.input): - ap.error(f"{flag} would overwrite the input {a.input}") - if os.path.isfile(path) and os.path.isdir(a.input): - manifest = os.path.join(a.input, "index.json") - if same_report_path(path, manifest): - ap.error(f"{flag} would overwrite the carve manifest {manifest}") - for entry in carved_files(a.input): - if same_report_path(path, entry.path): - ap.error(f"{flag} would overwrite the input {entry.path}") - rows = [] if a.csv else None - try: - summary = scan(a.input, a.start, a.limit, a.deep, rows) - except ValueError as exc: - print("error: %s" % exc, file=sys.stderr) - return 2 - report_path = out - try: - _make_parent(out) - with open(out, "w", encoding="utf-8", newline="\n") as f: - json.dump(summary, f, indent=1, allow_nan=False) - if a.csv: - report_path = a.csv - write_csv(a.csv, rows) - except OSError as exc: - print(f"ERROR: cannot write {report_path}: {exc.strerror or exc}", file=sys.stderr) - return 2 - if not a.quiet: - print(json.dumps(summary, indent=1, allow_nan=False)) - print("wrote %s" % out + (", %s" % a.csv if a.csv else "")) - return 0 - - -if __name__ == "__main__": - try: # a redirected stdout is strict ANSI code page under -I; write '?' for what it cannot encode - sys.stdout.reconfigure(errors="replace") - except (AttributeError, ValueError, OSError): - pass - sys.exit(main()) diff --git a/tools/navmesh_index.py b/tools/navmesh_index.py deleted file mode 100644 index 6cf372144..000000000 --- a/tools/navmesh_index.py +++ /dev/null @@ -1,363 +0,0 @@ -"""Index the RPF9 resource page-directory streams in a navmesh archive or a carve folder. - -The measured directory page carries the four bytes ``0DRP`` at offset 16, followed by version ``0x7A`` -(122), a presumed page count at offset 32 and an opaque 64-bit key at offset 0x60. That marker is the RPF9 -page-directory container, **not** a navmesh-specific magic (it also occurs in ``data.rpf`` and -``levels.rpf``), so this tool indexes containers. Run it on ``navmeshes.rpf`` to inventory its directory -pages. - -The archive walk is the fixed one from ``rpf9_carve.py`` (advance by the bytes actually read, not by the -1 MiB chunk size). Tables of contents are encrypted and are not touched; only zlib streams are read. -No payload is written, and the output is metadata only. - -Usage: - python -I navmesh_index.py [--out FILE] [--csv FILE] - [--start N] [--limit BYTES] [--pattern GLOB] - - --out JSON path (default: .navmesh-index.json in the current directory) - --csv optional CSV path - --start first byte to scan in an archive, 0 or more (archive input only; default: u32 at offset 4) - --limit stop after this many bytes, at least 1 (archive input only; default: to the end) - --pattern glob for directory input (directory input only; default: *.bin, the carve file names) -""" -import argparse -import csv -import fnmatch -import glob -import json -import mmap -import os -import re -import struct -import sys -import tempfile -import time -import zlib -from contextlib import suppress - -sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) -from file_mode import published_mode # noqa: E402 - -# -I keeps the script directory off sys.path, so add it explicitly before importing the sibling module. -sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) -from report_paths import same_report_path # noqa: E402 -from zero_span import gap_split # noqa: E402 - -CHUNK = 1 << 20 -HEAD = 0x80 -MARKER = b"0DRP" -MARKER_OFFSET = 16 -VERSION_OFFSET = MARKER_OFFSET + 4 -PAGES_OFFSET = MARKER_OFFSET + 0x10 -KEY_OFFSET = 0x60 -FIELD68_OFFSET = 0x68 -FIELDS = ["source", "offset", "stored", "size", "signature", "version", "pages", "key64", "u32_68"] - -# zlib stream start. Bink is not expected in a navmesh archive but the carver recognizes it; here it is -# deliberately not matched, so a navmesh index only reports zlib resource pages. -ZHDR = re.compile(rb"\x78[\x01\x5e\x9c\xda]") - - -def below_normal(): - if os.name == "nt": - import ctypes - from ctypes import wintypes - - k = ctypes.windll.kernel32 - # The current-process pseudo-handle is pointer-sized on 64-bit Windows. - k.GetCurrentProcess.argtypes = () - k.GetCurrentProcess.restype = wintypes.HANDLE - k.SetPriorityClass.argtypes = (wintypes.HANDLE, wintypes.DWORD) - k.SetPriorityClass.restype = wintypes.BOOL - k.SetPriorityClass(k.GetCurrentProcess(), 0x00004000) - - -def u32(b, off): - return struct.unpack_from("= off + 4 else None - - -def page_fields(head): - """Return the measured page-directory fields, or None when the marker is absent at offset 16.""" - if len(head) < MARKER_OFFSET + 4 or head[MARKER_OFFSET:MARKER_OFFSET + 4] != MARKER: - return None - key = head[KEY_OFFSET:KEY_OFFSET + 8] if len(head) >= KEY_OFFSET + 8 else b"" - return { - "signature": "0DRP@16", - "version": u32(head, VERSION_OFFSET), - "pages": u32(head, PAGES_OFFSET), - "key64": key.hex() if key and key != bytes(8) else "", - # Measured range includes 0xFFFFFFF9, so this is not a dense file index; expose the raw word. - "u32_68": u32(head, FIELD68_OFFSET), - } - - -def scan_archive(path, start=None, limit=None): - """Walk zlib streams like the fixed carver. Returns (rows, summary). Rows are marker matches only.""" - with open(path, "rb") as fh: - with mmap.mmap(fh.fileno(), 0, access=mmap.ACCESS_READ) as m: - size = len(m) - if start is None: - start = u32(m, 4) or 0 - if not 0 <= start < size: - raise ValueError(f"start {start} is outside {path} ({size} bytes)") - end = min(size, start + limit) if limit else size - rows, total, last, unread, zero = [], 0, start, 0, 0 - total_stored = total_inflated = 0 - pos = start - t0 = time.time() - while pos < end: - mt = ZHDR.search(m, pos, end) - if not mt: - break - s = mt.start() - d = zlib.decompressobj() - head, total_out, p = bytearray(), 0, s - try: - # --limit bounds the scanned window, not just the header search: a stream whose body - # runs past `end` must not be counted, or the byte accounting exceeds the window. - while not d.eof and p < end: - chunk = m[p:min(p + CHUNK, end)] - if not chunk: - break - out = d.decompress(chunk) - if len(head) < HEAD: - head.extend(out[:HEAD - len(head)]) - total_out += len(out) - p += len(chunk) - if d.unused_data or d.eof: - break - tail = d.flush() - if len(head) < HEAD: - head.extend(tail[:HEAD - len(head)]) - total_out += len(tail) - except zlib.error: - pos = s + 1 - continue - if not d.eof or total_out < 64: - pos = s + 1 - continue - used = p - s - len(d.unused_data) - gap_zero, gap_unread = gap_split(m, last, s) - zero += gap_zero - unread += gap_unread - fields = page_fields(head) - total += 1 - total_stored += used - total_inflated += total_out - if fields: - rows.append({"source": path, "offset": s, "stored": used, "size": total_out, **fields}) - last = pos = s + used - gap_zero, gap_unread = gap_split(m, last, end) - zero += gap_zero - unread += gap_unread - span = end - start - summary = { - "input": path, "mode": "rpf", "start": start, "span": span, "streams": total, - "matched": len(rows), "compressed_bytes": total_stored, "inflated_bytes": total_inflated, - "matched_stored_bytes": sum(r["stored"] for r in rows), - "matched_inflated_bytes": sum(r["size"] for r in rows), - "zero_padding": zero, "unread_bytes": unread, - "readable_fraction": round(total_stored / span, 6) if span else 0.0, - "elapsed_s": round(time.time() - t0, 1), - } - return rows, summary - - -def scan_directory(root, pattern=None): - """Read the first 128 bytes of each matching carved file. Rows are marker matches only.""" - pattern = pattern or "*.bin" - rows, files, total_size = [], 0, 0 - t0 = time.time() - # Escape only the caller's root: a folder named "carve[1]" would otherwise be read as a character - # class by glob and match nothing. The pattern (and "**") stays as the caller's glob. - query = pattern.replace(os.altsep, os.sep) if os.altsep else pattern - if query.split(os.sep, 1)[0] != "**": - query = os.path.join("**", query) - matches = glob.iglob(os.path.join(glob.escape(os.fspath(root)), query), recursive=True) - # Separated ** segments (e.g. **/tiles/**/*.bin) can still match a pathname more than once. - for path in sorted(set(matches) if query.split(os.sep).count("**") > 1 else matches): - if not os.path.isfile(path): - continue - size = os.path.getsize(path) - with open(path, "rb") as f: - head = f.read(HEAD) - files += 1 - total_size += size - fields = page_fields(head) - if fields: - rows.append({"source": os.path.relpath(path, root), "offset": None, "stored": None, - "size": size, **fields}) - summary = { - "input": root, "mode": "directory", "pattern": pattern, "start": None, "span": total_size, - "streams": files, "matched": len(rows), "compressed_bytes": None, - "inflated_bytes": total_size, "matched_inflated_bytes": sum(r["size"] for r in rows), - "zero_padding": None, "unread_bytes": None, - "readable_fraction": None, "elapsed_s": round(time.time() - t0, 1), - } - return rows, summary - - -def add_distribution(summary, rows): - versions, pages = {}, {} - for r in rows: - versions[str(r["version"])] = versions.get(str(r["version"]), 0) + 1 - pages[str(r["pages"])] = pages.get(str(r["pages"]), 0) + 1 - summary["versions"] = dict(sorted(versions.items(), key=lambda kv: -kv[1])) - summary["page_counts"] = dict(sorted(pages.items(), key=lambda kv: -kv[1])) - summary["keys_present"] = sum(1 for r in rows if r["key64"]) - return summary - - -def _make_parent(path): - """Create the folder an output path lives in: the scan is over by the time we write, so a missing - folder used to end the run in a FileNotFoundError and lose the result.""" - parent = os.path.dirname(os.path.abspath(path)) - if parent: - os.makedirs(parent, exist_ok=True) - - -def _publish(dest, write, newline): - """Write a report next to `dest` and swap it in, so a run that fails or is interrupted while writing (a - serialization error, a full disk, Ctrl+C) leaves the previous report as it was instead of a truncated one. - The result keeps the previous report's permission bits, or gets the usual ones for a new file.""" - _make_parent(dest) - directory = os.path.dirname(os.path.abspath(dest)) - temp = None - try: - with tempfile.NamedTemporaryFile(mode="w", encoding="utf-8", newline=newline, dir=directory, - prefix=".navmesh_index-", suffix=".tmp", delete=False) as f: - temp = f.name - write(f) - os.chmod(temp, published_mode(dest)) - os.replace(temp, dest) - except BaseException: - if temp is not None: - with suppress(OSError): - # The staging file may have inherited a read-only destination's mode; make it deletable - # first, or Windows strands it beside the report when the replace fails. - os.chmod(temp, 0o600) - os.unlink(temp) - raise - - -def write_outputs(rows, summary, out_path, csv_path): - _publish(out_path, lambda f: json.dump({"summary": summary, "pages": rows}, f, indent=1), "\n") - written = [] - if csv_path: - - def write_csv(f): - w = csv.DictWriter(f, fieldnames=FIELDS, extrasaction="ignore", lineterminator="\n") - w.writeheader() - w.writerows(rows) - - _publish(csv_path, write_csv, "") - written.append(csv_path) - return written - - -def byte_count(text): - """--limit: 0 or less used to scan nothing (negative) or everything (0 is falsy) without a word.""" - try: - value = int(text, 0) - except ValueError: - raise argparse.ArgumentTypeError(f"invalid int value: {text!r}") from None - if value < 1: - raise argparse.ArgumentTypeError("must be at least 1") - return value - - -def offset(text): - """--start: a negative offset would slice the archive from its end.""" - try: - value = int(text, 0) - except ValueError: - raise argparse.ArgumentTypeError(f"invalid int value: {text!r}") from None - if value < 0: - raise argparse.ArgumentTypeError("must be 0 or more") - return value - - -def is_scanned_input(path, input_path, pattern): - """True when a report path would replace the carve manifest or a scanned input.""" - if same_report_path(path, input_path): - return True - if not os.path.isdir(input_path) or not os.path.isfile(path): - return False - if same_report_path(path, os.path.join(input_path, "index.json")): - return True - pattern = pattern or "*.bin" - # Walk up from the report path and compare each folder like same_report_path does (normcase, realpath, - # samefile), so a spelling that differs only in case, or goes through a link, is still inside the input. - target = os.path.abspath(path) - root = os.path.dirname(target) - while not same_report_path(root, input_path): - parent = os.path.dirname(root) - if parent == root: - break - root = parent - else: - if (fnmatch.fnmatch(os.path.relpath(target, root), pattern) - or fnmatch.fnmatch(os.path.basename(target), pattern)): - return True - # A different spelling or a hard link anywhere can still refer to a scanned file. - return any(same_report_path(target, scanned) - for scanned in glob.iglob( - os.path.join(glob.escape(os.fspath(input_path)), "**", pattern), recursive=True)) - - -def main() -> int: - ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) - ap.add_argument("input", help="RPF9 archive, or a directory of carved .bin files") - ap.add_argument("--out", help="JSON output (default: .navmesh-index.json)") - ap.add_argument("--csv", help="optional CSV output") - ap.add_argument("--start", type=offset, help="first byte to scan in an archive") - ap.add_argument("--limit", type=byte_count, help="maximum bytes to scan in an archive") - ap.add_argument("--pattern", default=None, help="directory input glob (default: *.bin)") - a = ap.parse_args() - is_dir = os.path.isdir(a.input) - if is_dir and (a.start is not None or a.limit is not None): - ap.error("--start and --limit apply to a single archive, not a directory") - if not is_dir and a.pattern is not None: - ap.error("--pattern applies to a directory, not an archive") - base = os.path.basename(os.path.normpath(a.input)) - out_path = a.out or os.path.splitext(base)[0] + ".navmesh-index.json" - if a.csv and same_report_path(out_path, a.csv): - ap.error("--out and --csv must refer to different files") - for flag, path in (("--out", out_path), ("--csv", a.csv)): - if path and os.path.isdir(path): # open() on a folder ends the run in a PermissionError traceback - ap.error(f"{flag} is a directory: {path}") - if path and is_scanned_input(path, a.input, a.pattern): - ap.error(f"{flag} would overwrite the input {path}") - if not os.path.exists(a.input): - print(f"ERROR: {a.input}: does not exist", file=sys.stderr) - return 2 - below_normal() - - if is_dir: - rows, summary = scan_directory(a.input, a.pattern) - else: - try: - with open(a.input, "rb") as f: - magic = f.read(8) - except OSError as e: - ap.error(f"{a.input}: {getattr(e, 'strerror', None) or e}") - if len(magic) < 8 or magic[1:4] != b"FPR" or magic[0] not in b"789": - ap.error(f"{a.input}: not an RPF7/8/9 archive (magic {magic[:4]!r})") - try: - rows, summary = scan_archive(a.input, a.start, a.limit) - except ValueError as e: - ap.error(str(e)) - - add_distribution(summary, rows) - written = write_outputs(rows, summary, out_path, a.csv) - print(json.dumps(summary, indent=1)) - print(f"wrote {out_path}" + (f", {', '.join(written)}" if written else "")) - return 0 - - -if __name__ == "__main__": - try: # a redirected stdout is strict ANSI code page under -I; write '?' for what it cannot encode - sys.stdout.reconfigure(errors="replace") - except (AttributeError, ValueError, OSError): - pass - sys.exit(main()) diff --git a/tools/navmesh_links.py b/tools/navmesh_links.py deleted file mode 100644 index bc146811f..000000000 --- a/tools/navmesh_links.py +++ /dev/null @@ -1,623 +0,0 @@ -#!/usr/bin/env python3 -"""Decode and verify navmesh +0x88 adjacent-polygon edges and +0xA8/+0xB0 special links. - -Reads a retail RPF9 navmeshes.rpf archive (or a directory of carved .bin streams) -in-place and validates the 12-byte adjacent-polygon edge records (+0x88, count u32@0x90), -the 32-byte special-link records (+0xA8, count u32@0xD4), the u16 special-link index -table (+0xB0, count u32@0xD8), and the polygon +0x20 special-link prefix-sum chain -across all 0x00010015 navmesh tiles. Emits aggregate counts and invariant pass/fail -totals only (no game data). -Usage: `python -I tools/navmesh_links.py --help` lists the options. -""" - -import argparse -from collections import Counter -import json -import math -import mmap -import os -import struct -import sys - -try: - from tools import navmesh_decode as nd - from tools.report_paths import same_report_path -except ImportError: # pragma: no cover - direct script execution - sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) - import navmesh_decode as nd - from report_paths import same_report_path - - -CHECK_NAMES = ( - "edges_valid", - "poly_link_chain", - "special_links_valid", - "link_indices_endpoints", -) - - -def _counter_top(counter, limit=32): - return {str(k): v for k, v in counter.most_common(limit)} - - -def _count_reciprocity(b, polygons, edges, sector, polygon_count, totals): - """Match directed polygon counts within one tile whose pool sizes agree.""" - records = (record for offset, count in edges - for record in struct.iter_unpack("> 4 != position: - return # Overlapping or missing spans make edge ownership ambiguous. - for _ in range(packed & 15): - target_sector, target = next(records) - if target_sector == 0xFFFFFFFF and target == 0xFFFF: - unlinked += 1 - elif target_sector == sector and target < polygon_count: - directed[source, target] += 1 - same += 1 - else: - invalid += 1 - position += packed & 15 - source += 1 - - excess = sum(max(0, n - directed[target, source]) - for (source, target), n in directed.items()) - totals["tiles_counted"] += 1 - totals["same_tile"] += same - totals["excess_directed"] += excess - totals["invalid_targets"] += invalid - totals["unlinked"] += unlinked - - -ENDPOINT_CLASSES = ( - "reversed", "same_direction", "degenerate", "repeated", "no_exact_return", -) - - -def _turn(a, b, c): - return (b[0] - a[0]) * (c[1] - a[1]) - (b[1] - a[1]) * (c[0] - a[0]) - - -def _xy_winding(points): - """Sign of twice the area of a simple projected ring, or zero if ambiguous.""" - n = len(points) - if n < 3: - return 0 - if n == 3: - area = _turn(*points) - return (area > 0) - (area < 0) - if len(set(points)) != n: - return 0 - area = 0 - for i, a in enumerate(points): - b = points[(i + 1) % n] - area += a[0] * b[1] - b[0] * a[1] - prev = points[i - 1] - if (_turn(prev, a, b) == 0 and - (prev[0] - a[0]) * (b[0] - a[0]) + (prev[1] - a[1]) * (b[1] - a[1]) > 0): - return 0 # Adjacent segments double back over one another. - for j in range(i + 2, n if i else n - 1): - c, d = points[j], points[(j + 1) % n] - if (max(a[0], b[0]) < min(c[0], d[0]) or max(c[0], d[0]) < min(a[0], b[0]) or - max(a[1], b[1]) < min(c[1], d[1]) or max(c[1], d[1]) < min(a[1], b[1])): - continue - if _turn(a, b, c) * _turn(a, b, d) <= 0 and _turn(c, d, a) * _turn(c, d, b) <= 0: - return 0 - return (area > 0) - (area < 0) - - -def _plane_ring(points): - """Return a canonical plane normal, winding sign and undirected corner cycle.""" - if len(points) < 3 or len(set(points)) != len(points): - return None - a, b = points[:2] - dx, dy, dz = (v - u for u, v in zip(a, b)) - for c in points[2:]: - ex, ey, ez = (v - u for u, v in zip(a, c)) - normal = (dy * ez - dz * ey, dz * ex - dx * ez, dx * ey - dy * ex) - if any(normal): - break - else: - return None - if any(sum(n * (v - u) for n, v, u in zip(normal, point, a)) for point in points): - return None - axis = next(i for i, n in enumerate(normal) if n) - divisor = math.gcd(*normal) * (1 if normal[axis] > 0 else -1) - plane = tuple(n // divisor for n in normal) - projected = [(p[(axis + 1) % 3], p[(axis + 2) % 3]) for p in points] - sign = _xy_winding(projected) - if not sign: - return None - corners = [p for i, p in enumerate(projected) - if _turn(projected[i - 1], p, projected[(i + 1) % len(points)])] - boundary = frozenset(tuple(sorted((p, corners[i - 1]))) for i, p in enumerate(corners)) - return plane, sign, boundary - - -def _plane_relation(left, right): - if left is None or right is None: - return "undefined_ring" - # The exact shared edge supplies a common point, so parallel planes coincide. - if left[0] != right[0]: - return "different_planes" - if left[2] == right[2]: - return "coincident" - return "same" if left[1] == right[1] else "opposite" - - -def _endpoint_counts(b, tables, sector, polygon_count, totals): - """Compare each slot under both cyclic boundary conventions within this tile.""" - vertices, indices, edges, polygons = tables - coords = [xyz for offset, count in vertices - for (xyz,) in struct.iter_unpack("<6s", b[offset:offset + count * 6])] - ring_indices = [index for offset, count in indices - for (index,) in struct.iter_unpack(" 0 for v in nd._f32s(b, 0x60, 2)) - signs = [] - coplanar = totals.get("coplanar_winding") - if coplanar is not None: - rings = [] - planes = {} - extents = nd._f32s(b, 0x60, 3) - valid_xyz = all(math.isfinite(v) and v >= 0 for v in extents) - - def plane(index): - if index not in planes: - points = [tuple(v if extent else 0 for v, extent in zip(struct.unpack("<3H", raw), extents)) - for raw in rings[index]] - planes[index] = _plane_ring(points) if valid_xyz else None - return planes[index] - - position = source = self_refs = unlinked = invalid = 0 - for offset, count in polygons: - for i in range(count): - span = nd._u32(b, offset + 44 * i + 4) - if span >> 4 != position: - return - end = position + (span & 15) - ring = [coords[index] for index in ring_indices[position:end]] - if coplanar is not None: - rings.append(ring) - if winding is not None: - signs.append(_xy_winding([xy[index] for index in ring_indices[position:end]]) - if valid_xy else 0) - for j, vertex in enumerate(ring): - target_sector, target = next(targets) - if (target_sector, target) == (0xffffffff, 0xffff): - unlinked += 1 - elif target_sector != sector or target >= polygon_count: - invalid += 1 - elif target == source: - self_refs += 1 - else: - hypotheses["outgoing"][source, target, vertex, ring[(j + 1) % len(ring)]] += 1 - hypotheses["incoming"][source, target, ring[j - 1], vertex] += 1 - position = end - source += 1 - - totals["tiles_counted"] += 1 - totals["self_references"] += self_refs - totals["unlinked"] += unlinked - totals["invalid_targets"] += invalid - for convention, counts in hypotheses.items(): - for (source, target, start, end), n in counts.items(): - reverse = counts[target, source, end, start] - same = counts[target, source, start, end] if start != end else 0 - if not (same or reverse): - category = "no_exact_return" - elif (n > 1 or reverse + same > 1 or - (start != end and counts[source, target, end, start])): - category = "repeated" - elif start == end: - category = "degenerate" - elif reverse: - category = "reversed" - else: - category = "same_direction" - totals[convention][category] += n - if winding is not None and convention == "outgoing" and category in winding: - product = signs[source] * signs[target] - relation = "ambiguous" if product == 0 else "same" if product > 0 else "opposite" - winding[category][relation] += n - if coplanar is not None and category == "same_direction" and relation == "ambiguous": - coplanar[_plane_relation(plane(source), plane(target))] += n - - -def verify_tile(b, stats): - """Verify +0x88 adjacent edges, polygon +0x20 link chain, and +0xA8/+0xB0 special links.""" - chk = {} - if len(b) < 0xF0: - for name in CHECK_NAMES: - chk[name] = False - return chk - - flags = nd._u32(b, 0x10) - c0, c4, c8, _, d4, d8 = (nd._u32(b, o) for o in (0xC0, 0xC4, 0xC8, 0xCC, 0xD4, 0xD8)) - pool = nd._u32(b, 0x90) - a8, b0 = nd._u64(b, 0xA8), nd._u64(b, 0xB0) - - # Cross-check u32@0xC0 (c0) and u32@0x90 (pool) against +0x70 (6-byte vertices), - # +0x80 (2-byte vertex indices < c0), +0x88 (12-byte edges), and the sum of polygon vertex counts in +0x98. - b70 = nd.split_array(b, 0x70, 6, c0) - b80 = nd.split_array(b, 0x80, 2, pool) - b88 = nd.split_array(b, 0x88, 12, pool) - b98 = nd.split_array(b, 0x98, 44, c4) - poly_vert_sum = 0 - if b98 is not None: - for po, pcnt in b98: - for pi in range(pcnt): - poly_vert_sum += struct.unpack_from("> 8] += 1 - if not edges_ok: - break - chk["edges_valid"] = edges_ok - if edges_ok: - est = stats["edges"] - est["total"] += pool - est["same_tile"] += same_tile - est["unlinked"] += unlinked - est["flags_low_byte"].update(edge_flags_lo) - est["meta_high_byte"].update(edge_meta_hi) - - # 2. 32-byte special links at +0xA8 (count = d4 = u32@0xD4) and u16 index table at +0xB0 (count = d8 = u32@0xD8). - has_links = bool(flags & 2) - la = nd.offset_of(a8) if a8 else None - lb = nd.offset_of(b0) if b0 else None - if not has_links: - links_bounds_ok = (a8 == 0 and b0 == 0 and d4 == 0 and d8 == 0) - else: - links_bounds_ok = ( - d4 > 0 - and d8 > 0 - and la is not None - and lb is not None - and la + 32 * d4 <= len(b) - and lb + 2 * d8 <= len(b) - ) - - links_ok = links_bounds_ok - intra = cross_s0 = cross_s1 = 0 - f0_hist = Counter() - f1_hist = Counter() - if links_ok and d4 > 0: - for i in range(d4): - p0, p1, s0, s1, f0, f1, heading, pad = struct.unpack_from("= 256 or pad != 0: - links_ok = False - break - if s0 == c8 and s1 == c8: - if p0 >= c4 or p1 >= c4: - links_ok = False - break - intra += 1 - elif s0 == c8: - if p0 >= c4: - links_ok = False - break - cross_s0 += 1 - elif s1 == c8: - if p1 >= c4: - links_ok = False - break - cross_s1 += 1 - else: - links_ok = False - break - f0_hist[f0] += 1 - f1_hist[f1] += 1 - chk["special_links_valid"] = links_ok - if links_ok and d4 > 0: - lst = stats["special_links"] - lst["link_tiles"] += 1 - lst["total"] += d4 - lst["indices_total"] += d8 - lst["intra_tile"] += intra - lst["cross_tile_s0"] += cross_s0 - lst["cross_tile_s1"] += cross_s1 - lst["flags0"].update(f0_hist) - lst["flags1"].update(f1_hist) - - # 3. 44-byte polygons at +0x98: u32@0x20 packs (flags_hi9 << 23) | (link_start << 6) | link_count, - # chaining across all c4 polygons to d8 and indexing +0xB0 -> +0xA8 endpoints touching that polygon. - chain_ok = b98 is not None and links_bounds_ok - endpoints_ok = chain_ok and links_ok - lidx = struct.unpack_from(f"<{d8}H", b, lb) if (links_bounds_ok and d8 > 0) else () - nxt = 0 - gpi = 0 - max_poly_links = 0 - w20_hi9 = Counter() - by_li = {} - if b98 is not None: - for po, pcnt in b98: - for pi in range(pcnt): - w20 = struct.unpack_from("> 6) & 0x1FFFF - w20_hi9[w20 >> 23] += 1 - if cnt > max_poly_links: - max_poly_links = cnt - if start != nxt or start + cnt > d8: - chain_ok = False - endpoints_ok = False - break - if cnt > 0 and endpoints_ok: - for k in range(start, start + cnt): - li = lidx[k] - if li >= d4: - endpoints_ok = False - break - p0, p1, s0, s1 = struct.unpack_from(" pst["max_links_per_poly"]: - pst["max_links_per_poly"] = max_poly_links - pst["w20_hi9_flags"].update(w20_hi9) - return chk - - -def new_stats(): - return { - "tiles": 0, - "checks": {name: {"pass": 0, "fail": 0} for name in CHECK_NAMES}, - "edges": { - "total": 0, - "same_tile": 0, - "unlinked": 0, - "flags_low_byte": Counter(), - "meta_high_byte": Counter(), - }, - "polygons": { - "total": 0, - "max_links_per_poly": 0, - "w20_hi9_flags": Counter(), - }, - "special_links": { - "link_tiles": 0, - "total": 0, - "indices_total": 0, - "intra_tile": 0, - "cross_tile_s0": 0, - "cross_tile_s1": 0, - "flags0": Counter(), - "flags1": Counter(), - }, - } - - -def _iter_resources(path, start=0, limit=None): - if os.path.isdir(path): - files = sorted(f for f in os.listdir(path) if f.endswith(".bin")) - idx = 0 - while idx < len(files): - with open(os.path.join(path, files[idx]), "rb") as fh: - d0 = fh.read() - idx += 1 - if len(d0) < 64: - continue - cls = nd.classify(d0) - buf = bytearray(d0) - n = 1 - while nd.wants_more(cls, buf, n) and idx < len(files): - with open(os.path.join(path, files[idx]), "rb") as fh: - dn = fh.read() - if len(dn) >= 64 and nd.classify(dn) != "other": - break - buf.extend(dn) - idx += 1 - n += 1 - if cls == "navmesh": - yield bytes(buf) - return - - size = os.path.getsize(path) - if size < 8: - return - with open(path, "rb") as fh, mmap.mmap(fh.fileno(), 0, access=mmap.ACCESS_READ) as m: - first = struct.unpack_from("= scan_end: - return - gen = nd.walk(m, scan_start, size) - pending = None - while True: - item = pending if pending is not None else next(gen, None) - pending = None - if item is None: - break - off0, _, d0 = item - if off0 >= scan_end: - break - if len(d0) < 64: - continue - cls = nd.classify(d0) - buf = bytearray(d0) - n = 1 - while nd.wants_more(cls, buf, n): - nxt = next(gen, None) - if nxt is None: - break - if len(nxt[2]) >= 64 and nd.classify(nxt[2]) != "other": - pending = nxt - break - buf.extend(nxt[2]) - n += 1 - if cls == "navmesh": - yield bytes(buf) - - -def scan(path, start=0, limit=None, *, reciprocity=False, endpoint_agreement=False, relative_winding=False, - coplanar_winding=False): - relative_winding = relative_winding or coplanar_winding - stats = new_stats() - if endpoint_agreement or relative_winding: - stats["endpoint_agreement"] = { - "tiles_counted": 0, "self_references": 0, "unlinked": 0, "invalid_targets": 0, - **{name: dict.fromkeys(ENDPOINT_CLASSES, 0) for name in ("incoming", "outgoing")}, - } - if relative_winding: - stats["endpoint_agreement"]["relative_winding"] = { - category: dict.fromkeys(("same", "opposite", "ambiguous"), 0) - for category in ("reversed", "same_direction") - } - if coplanar_winding: - stats["endpoint_agreement"]["coplanar_winding"] = dict.fromkeys( - ("same", "opposite", "different_planes", "coincident", "undefined_ring"), 0) - if reciprocity: - stats["reciprocity"] = dict.fromkeys( - ("tiles_counted", "same_tile", "excess_directed", "invalid_targets", "unlinked"), 0) - for buf in _iter_resources(path, start=start, limit=limit): - stats["tiles"] += 1 - chk = verify_tile(buf, stats) - for name, ok in chk.items(): - stats["checks"][name]["pass" if ok else "fail"] += 1 - return { - **({"endpoint_agreement": stats["endpoint_agreement"]} if endpoint_agreement or relative_winding else {}), - **({"reciprocity": stats["reciprocity"]} if reciprocity else {}), - "tiles": stats["tiles"], - "checks": stats["checks"], - "edges": { - "total": stats["edges"]["total"], - "same_tile": stats["edges"]["same_tile"], - "unlinked": stats["edges"]["unlinked"], - "flags_low_byte": _counter_top(stats["edges"]["flags_low_byte"]), - "meta_high_byte": _counter_top(stats["edges"]["meta_high_byte"]), - }, - "polygons": { - "total": stats["polygons"]["total"], - "max_links_per_poly": stats["polygons"]["max_links_per_poly"], - "w20_hi9_flags": _counter_top(stats["polygons"]["w20_hi9_flags"]), - }, - "special_links": { - "link_tiles": stats["special_links"]["link_tiles"], - "total": stats["special_links"]["total"], - "indices_total": stats["special_links"]["indices_total"], - "intra_tile": stats["special_links"]["intra_tile"], - "cross_tile_s0": stats["special_links"]["cross_tile_s0"], - "cross_tile_s1": stats["special_links"]["cross_tile_s1"], - "flags0": _counter_top(stats["special_links"]["flags0"]), - "flags1": _counter_top(stats["special_links"]["flags1"]), - }, - } - - -def main(argv=None): - ap = argparse.ArgumentParser(description=__doc__) - ap.add_argument("input", help="Path to navmeshes.rpf or a directory of carved .bin streams") - ap.add_argument("--start", type=int, default=0, help="Start byte offset inside an RPF9 archive") - ap.add_argument("--limit", type=int, default=None, help="Maximum byte span to scan") - ap.add_argument("--out", default=None, help="Optional JSON output path") - ap.add_argument("--quiet", action="store_true", help="Suppress stdout summary") - ap.add_argument("--reciprocity", action="store_true", - help="Count same-tile directed edges in excess of their reverse multiplicity") - ap.add_argument("--endpoint-agreement", action="store_true", - help="Compare incoming and outgoing boundary endpoints for same-tile edges") - ap.add_argument("--coplanar-winding", action="store_true", - help="Also classify XY-ambiguous same-direction slots using coplanar 3D rings") - ap.add_argument("--relative-winding", action="store_true", - help="Include endpoint agreement and compare polygon XY winding for unique outgoing matches") - args = ap.parse_args(argv) - - if args.start < 0: - sys.stderr.write("error: --start must be >= 0\n") - return 2 - if args.limit is not None and args.limit < 1: - sys.stderr.write("error: --limit must be >= 1\n") - return 2 - if not os.path.exists(args.input): - sys.stderr.write(f"error: input path not found: {args.input}\n") - return 2 - if os.path.isdir(args.input) and (args.start != 0 or args.limit is not None): - sys.stderr.write("error: --start and --limit only apply to RPF9 archive files\n") - return 2 - if args.out is not None: - if os.path.isdir(args.out): - sys.stderr.write(f"error: --out path is a directory: {args.out}\n") - return 2 - if same_report_path(args.out, args.input): - sys.stderr.write("error: --out must not overwrite the input path\n") - return 2 - if os.path.isdir(args.input): - for fname in os.listdir(args.input): - if fname.endswith(".bin") and same_report_path(args.out, os.path.join(args.input, fname)): - sys.stderr.write("error: --out must not overwrite a carved input stream\n") - return 2 - - doc = scan(args.input, start=args.start, limit=args.limit, reciprocity=args.reciprocity, - endpoint_agreement=args.endpoint_agreement, relative_winding=args.relative_winding, - coplanar_winding=args.coplanar_winding) - if args.out is not None: - parent = os.path.dirname(os.path.abspath(args.out)) - if parent: - os.makedirs(parent, exist_ok=True) - with open(args.out, "w", encoding="utf-8", newline="\n") as fh: - json.dump(doc, fh, indent=2) - fh.write("\n") - if not args.quiet: - print(json.dumps(doc, indent=2)) - return 0 - - -if __name__ == "__main__": - try: # a redirected stdout is strict ANSI code page under -I; write '?' for what it cannot encode - sys.stdout.reconfigure(errors="replace") - except (AttributeError, ValueError, OSError): - pass - sys.exit(main()) diff --git a/tools/navmesh_nodes.py b/tools/navmesh_nodes.py deleted file mode 100644 index 081f2226a..000000000 --- a/tools/navmesh_nodes.py +++ /dev/null @@ -1,348 +0,0 @@ -"""Count which navmesh polygon flags lie under the lane-graph nodes. - -The lane graph (tools/world_lights_paths.py, levels.rpf) gives every road node a world position. A navmesh tile -(tools/navmesh_decode.py, navmeshes.rpf) gives polygons with two flag words whose bits are mostly unnamed. This -tool puts the two together: for each node it finds the polygon of the node's 128 m tile that contains the node in -plan view and is closest in height, and counts the bits of that polygon's `+0x18` and `+0x28` words. A polygon's -height is the mean of its vertex heights, not the surface height under the node, so on a slope the two differ. Next -to it, it sums the plan area of the polygons that carry each bit, over the tiles that hold at least one node; -surfaces that lie above one another (a bridge over a road, stacked tiles of one sector) each add their area. A bit that -most nodes sit on while it covers a small share of the area is tied to the roads. Two bits of `+0x18` do that, -8 and 13, so the summary also says how they combine (both, only one, neither) for the nodes and for the area; see -docs/navmesh.md, "Polygon flags under the lane graph". - -A tile's vertices are three u16 each: position = tile minimum + u16 / 65535 * tile extent (the minimum is the -quadtree root's, the extent the header's `+0x60`). The node heights test that: a wrong scale would leave the -nodes far above or below every polygon. - -Only static tiles are used (header flag bit 2 clear); a dynamic tile has no place on the 128 m grid. - -Usage: - python -I navmesh_nodes.py [--out summary.json] [--jobs N] [--max-dz METRES] - -The output is counts only: no position, name or payload is written. -""" -import argparse -import collections -import json -import math -import mmap -import os -import struct -import sys - -# -I keeps the script directory off sys.path, so add it explicitly before importing the sibling readers. -sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) - -import navmesh_decode as nd # noqa: E402 -import world_lights_paths as wlp # noqa: E402 -from report_paths import same_report_path # noqa: E402 - -TILE = 128.0 -CELL = 8.0 # bucket size of the per-tile lookup grid, metres -POLYGON = struct.Struct("> PAIR[0]) & 1, (flags18 >> PAIR[1]) & 1 - if low and high: - return "both" - if low: - return "only_%d" % PAIR[0] - return "only_%d" % PAIR[1] if high else "neither" - - -def sector_of(x, y): - """The (sx, sy) of the 128 m tile that holds a world position, as stored in a tile's `+0xC8` word.""" - return int(math.floor(x / TILE)) + 256, int(math.floor(y / TILE)) + 256 - - -def tile_geometry(b): - """Vertices and polygons of one static navmesh tile, or None when it is dynamic or does not read. - - -> {"sector": (sx, sy), "polygons": [(points, flags18, flags28)]} with points as (x, y, z) in world space. - """ - if len(b) < nd.HEADER_NAV or nd._u32(b, 0x14) != nd.DATA15 or nd._u32(b, 0x10) & 4: - return None - n_verts, n_polys, sector = (nd._u32(b, o) for o in (0xC0, 0xC4, 0xC8)) - pool = nd._u32(b, 0x90) - vertex_blocks = nd.split_array(b, 0x70, 6, n_verts) - index_blocks = nd.split_array(b, 0x80, 2, pool) - polygon_blocks = nd.split_array(b, 0x98, 44, n_polys) - root = nd.offset_of(nd._u64(b, 0xA0)) - if vertex_blocks is None or index_blocks is None or polygon_blocks is None or root is None \ - or root + 0x20 > len(b): - return None - lo = nd._f32s(b, root, 3) - ext = nd._f32s(b, 0x60, 3) - if not all(math.isfinite(v) for v in (*lo, *ext)): - return None - verts = [] - for at, count in vertex_blocks: - for vx, vy, vz in struct.iter_unpack("<3H", b[at:at + 6 * count]): - verts.append((lo[0] + vx / 65535.0 * ext[0], lo[1] + vy / 65535.0 * ext[1], - lo[2] + vz / 65535.0 * ext[2])) - index = [] - for at, count in index_blocks: - index.extend(struct.unpack_from("<%dH" % count, b, at)) - polygons = [] - for at, count in polygon_blocks: - for _tile, packed, flags18, flags28 in POLYGON.iter_unpack(b[at:at + 44 * count]): - first, n = packed >> 4, packed & 0xF - if first + n > len(index) or any(i >= len(verts) for i in index[first:first + n]): - return None - polygons.append(([verts[i] for i in index[first:first + n]], flags18, flags28)) - return {"sector": (sector & 0x1FF, sector >> 9), "polygons": polygons} - - -def plan_area(points): - """Area of a polygon's projection on the ground plane (shoelace).""" - total = 0.0 - for k, (x1, y1, _z1) in enumerate(points): - x2, y2, _z2 = points[(k + 1) % len(points)] - total += x1 * y2 - x2 * y1 - return abs(total) / 2.0 - - -def contains(points, x, y): - """Even-odd test of (x, y) against a polygon's ground-plane projection.""" - inside = False - for k, (x1, y1, _z1) in enumerate(points): - x2, y2, _z2 = points[(k + 1) % len(points)] - if (y1 > y) != (y2 > y) and x < (x2 - x1) * (y - y1) / (y2 - y1) + x1: - inside = not inside - return inside - - -def polygon_under(polygons, grid, x, y, z): - """The polygon containing (x, y) whose mean height is closest to z -> (height difference, polygon) or None.""" - best = None - for i in grid.get((int(math.floor(x / CELL)), int(math.floor(y / CELL))), ()): - points = polygons[i][0] - if len(points) >= 3 and contains(points, x, y): - dz = abs(sum(p[2] for p in points) / len(points) - z) - if best is None or dz < best[0]: - best = (dz, polygons[i]) - return best - - -def new_tally(): - return { - "tiles_with_nodes": 0, "tiles_unreadable": 0, "polygons": 0, "area": 0.0, - "area18": collections.Counter(), "area28": collections.Counter(), - "polygons18": collections.Counter(), "polygons28": collections.Counter(), - "pair_area": collections.Counter(), "pair_polygons": collections.Counter(), - "best": {}, # node index -> (height difference, flags18, flags28) - } - - -def tally_tile(tally, b, by_sector, nodes): - """Add one assembled navmesh resource to the tally. Tiles without a node are skipped.""" - if len(b) < nd.HEADER_NAV or nd._u32(b, 0x10) & 4: - return - sector = nd._u32(b, 0xC8) - mine = by_sector.get((sector & 0x1FF, sector >> 9)) - if not mine: - return - geometry = tile_geometry(b) - if geometry is None: - tally["tiles_unreadable"] += 1 - return - tally["tiles_with_nodes"] += 1 - polygons = geometry["polygons"] - grid = collections.defaultdict(list) - for i, (points, flags18, flags28) in enumerate(polygons): - if len(points) < 3: - continue - area = plan_area(points) - tally["polygons"] += 1 - tally["area"] += area - tally["pair_area"][pair_key(flags18)] += area - tally["pair_polygons"][pair_key(flags18)] += 1 - for word, area_by, count_by in ((flags18, tally["area18"], tally["polygons18"]), - (flags28, tally["area28"], tally["polygons28"])): - bit = 0 - while word: - if word & 1: - area_by[bit] += area - count_by[bit] += 1 - word >>= 1 - bit += 1 - xs = [p[0] for p in points] - ys = [p[1] for p in points] - for gx in range(int(math.floor(min(xs) / CELL)), int(math.floor(max(xs) / CELL)) + 1): - for gy in range(int(math.floor(min(ys) / CELL)), int(math.floor(max(ys) / CELL)) + 1): - grid[(gx, gy)].append(i) - for n in mine: - x, y, z = nodes[n] - found = polygon_under(polygons, grid, x, y, z) - if found is not None and (n not in tally["best"] or found[0] < tally["best"][n][0]): - tally["best"][n] = (found[0], found[1][1], found[1][2]) - - -def starts_resource(b): - """True when stream `b` opens a resource of its own (the check navmesh_links.py makes).""" - return len(b) >= nd.MIN_STREAM and nd.classify(b) != "other" - - -def navmesh_resources(path): - """Yield the assembled bytes of every navmesh tile in an RPF archive (the walk of navmesh_decode).""" - with open(path, "rb") as fh: - size = os.fstat(fh.fileno()).st_size - if size < 8: - raise ValueError("%s is %d bytes, too small for an RPF header" % (path, size)) - with mmap.mmap(fh.fileno(), 0, access=mmap.ACCESS_READ) as m: - if m[1:4] != b"FPR" or m[0:1] not in (b"7", b"8", b"9"): - raise ValueError("%s: not an RPF7/8/9 archive" % path) - data_start = struct.unpack_from(" nd.MAX_INFLATE or starts_resource(pending[2]): - break - buf.extend(pending[2]) - parts += 1 - pending = next(stream, None) - if cls == "navmesh" and nd.is_complete(cls, buf, parts): - yield bytes(buf) - - -def node_positions(levels, jobs=1): - """(positions, nodes read): the finite lane-graph node positions of levels.rpf.""" - total = wlp.scan(levels, jobs) - read = [n["position"] for part in total["nodes"] for n in part] - return [tuple(p) for p in read if all(math.isfinite(v) for v in p)], len(read) - - -def cross_check(navmeshes, nodes, max_dz=3.0): - """Summary of the polygons under `nodes` ((x, y, z) tuples) in the navmesh archive `navmeshes`.""" - by_sector = collections.defaultdict(list) - for n, (x, y, _z) in enumerate(nodes): - by_sector[sector_of(x, y)].append(n) - tally = new_tally() - for b in navmesh_resources(navmeshes): - tally_tile(tally, b, by_sector, nodes) - return summarize(tally, len(nodes), len(by_sector), max_dz) - - -def summarize(tally, n_nodes, n_sectors, max_dz): - near = [v for v in tally["best"].values() if v[0] <= max_dz] - heights = sorted(v[0] for v in tally["best"].values()) - under18, under28 = collections.Counter(), collections.Counter() - pair_nodes = collections.Counter(pair_key(flags18) for _dz, flags18, _flags28 in near) - pair_names = ("both", "only_%d" % PAIR[0], "only_%d" % PAIR[1], "neither") - for _dz, flags18, flags28 in near: - for word, into in ((flags18, under18), (flags28, under28)): - bit = 0 - while word: - if word & 1: - into[bit] += 1 - word >>= 1 - bit += 1 - - def table(under, area, count): - return {str(bit): {"nodes": under.get(bit, 0), "polygons": count.get(bit, 0), - "area_m2": round(area.get(bit, 0.0))} - for bit in sorted(set(under) | set(area))} - - def quantile(q): - return round(heights[min(len(heights) - 1, int(len(heights) * q))], 3) if heights else None - - return { - "nodes": n_nodes, - "tiles_named_by_nodes": n_sectors, - "tiles_with_nodes": tally["tiles_with_nodes"], - "tiles_unreadable": tally["tiles_unreadable"], - "nodes_over_a_polygon": len(tally["best"]), - "max_dz": max_dz, - "nodes_within_max_dz": len(near), - "height_difference_m": {"p10": quantile(0.1), "p50": quantile(0.5), "p90": quantile(0.9), - "p99": quantile(0.99)}, - "polygons": tally["polygons"], - "area_m2": round(tally["area"]), - "flags18": table(under18, tally["area18"], tally["polygons18"]), - "flags28": table(under28, tally["area28"], tally["polygons28"]), - "flags18_bits_%d_and_%d" % PAIR: { - name: {"nodes": pair_nodes.get(name, 0), "polygons": tally["pair_polygons"].get(name, 0), - "area_m2": round(tally["pair_area"].get(name, 0.0))} - for name in pair_names}, - } - - -def out_problem(path): - """Why the summary cannot be written at `path`, or None. - - Checked before the archives are read: the levels graph takes minutes to scan, so a destination this run - cannot write should not cost the whole run and then end in a traceback. - """ - parent = os.path.dirname(os.path.abspath(path)) - try: - os.makedirs(parent, exist_ok=True) - except OSError as e: - return "cannot create its folder: %s" % e - if not os.access(parent, os.W_OK): - return "its folder is not writable: %s" % parent - if os.path.exists(path) and not os.access(path, os.W_OK): - return "the existing summary is read-only" - return None - - -def main(argv=None): - ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) - ap.add_argument("navmeshes", help="navmeshes.rpf") - ap.add_argument("levels", help="levels.rpf (the lane graph)") - ap.add_argument("--out", help="summary JSON (default: stdout)") - ap.add_argument("--jobs", type=int, default=1, help="processes for the levels.rpf scan") - ap.add_argument("--max-dz", type=float, default=3.0, - help="a node counts when its polygon is at most this many metres above or below it") - a = ap.parse_args(argv) - if a.jobs < 1: - ap.error("--jobs must be at least 1") - if not math.isfinite(a.max_dz) or a.max_dz < 0: - ap.error("--max-dz must be 0 or more") - for path in (a.navmeshes, a.levels): - if not os.path.isfile(path): - ap.error("%s: no such file" % path) - if a.out: - if os.path.isdir(a.out) or any(same_report_path(a.out, p) for p in (a.navmeshes, a.levels)): - ap.error("--out must be a file other than the two archives") - problem = out_problem(a.out) - if problem: - ap.error("--out: %s" % problem) - try: - nodes, read = node_positions(a.levels, a.jobs) - summary = cross_check(a.navmeshes, nodes, a.max_dz) - except (OSError, ValueError) as e: - print("ERROR: %s" % e, file=sys.stderr) - return 2 - summary["nodes_read"] = read - text = json.dumps(summary, indent=1, sort_keys=True) - if a.out: - os.makedirs(os.path.dirname(os.path.abspath(a.out)), exist_ok=True) - with open(a.out, "w", encoding="utf-8", newline="\n") as f: - f.write(text + "\n") - else: - sys.stdout.write(text + "\n") - return 0 - - -if __name__ == "__main__": - try: # a redirected stdout is strict ANSI code page under -I; write '?' for what it cannot encode - sys.stdout.reconfigure(errors="replace") - except (AttributeError, ValueError, OSError): - pass - sys.exit(main()) diff --git a/tools/navmesh_tile_obj.py b/tools/navmesh_tile_obj.py deleted file mode 100644 index 66042a75c..000000000 --- a/tools/navmesh_tile_obj.py +++ /dev/null @@ -1,80 +0,0 @@ -"""Export one static navmesh tile's polygon boundaries to a private Wavefront OBJ. - ---tile is the zero-based ordinal among complete navmesh resources in archive order, -including dynamic tiles. A dynamic or unreadable selection is an error. Groups -use zero-based polygon record numbers. Each record owns its OBJ vertices, so -coincident positions, repeated slots and winding survive without welding. -""" -import argparse -import os -import sys -import tempfile -from contextlib import closing -from pathlib import Path - -sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) -from navmesh_nodes import navmesh_resources, tile_geometry -from report_paths import same_report_path - - -def write_obj(out, geometry, ordinal): - out.write(f"o tile_{ordinal}\n") - first = 1 - for record, (points, _, _) in enumerate(geometry["polygons"]): - out.write(f"g polygon_{record}\n") - if not points: - out.write("# empty record\n") - continue - for x, y, z in points: - out.write(f"v {x} {y} {z}\n") - refs = list(range(first, first + len(points))) - first += len(points) - if len(points) >= 3: - refs.append(refs[0]) - op = "p" if len(points) == 1 else "l" - out.write(op + " " + " ".join(map(str, refs)) + "\n") - - -def main(argv=None): - parser = argparse.ArgumentParser(description=__doc__) - parser.add_argument("archive") - parser.add_argument("--tile", type=int, required=True) - parser.add_argument("--out", type=Path, required=True, help="local OBJ destination") - args = parser.parse_args(argv) - if args.tile < 0: - parser.error("--tile must be non-negative") - temp = None - try: - if same_report_path(args.archive, args.out): - raise ValueError("--out aliases the archive") - with closing(navmesh_resources(args.archive)) as resources: - for ordinal, tile in enumerate(resources): - if ordinal == args.tile: - geometry = tile_geometry(tile) - break - else: - raise ValueError("tile ordinal outside archive") - if geometry is None: - raise ValueError("selected tile is dynamic or unreadable") - args.out.parent.mkdir(parents=True, exist_ok=True) - with tempfile.NamedTemporaryFile(mode="w", encoding="utf-8", newline="\n", - dir=args.out.parent, delete=False) as out: - temp = Path(out.name) - write_obj(out, geometry, ordinal) - os.replace(temp, args.out) - temp = None - except (OSError, ValueError) as exc: - print(f"ERROR: {exc}", file=sys.stderr) - return 2 - finally: - if temp is not None: - temp.unlink(missing_ok=True) - return 0 - - -if __name__ == "__main__": - try: # a redirected stdout is strict ANSI code page under -I; write '?' for what it cannot encode - sys.stdout.reconfigure(errors="replace") - except (AttributeError, ValueError, OSError): - pass - sys.exit(main()) diff --git a/tools/odrp_7a.py b/tools/odrp_7a.py deleted file mode 100644 index 7777944b5..000000000 --- a/tools/odrp_7a.py +++ /dev/null @@ -1,1265 +0,0 @@ -"""Distinguish and parse standalone `0DRP`/`0x7a` resources vs `PSIN` `LRSC` records. - -`0DRP` + version `122` (`0x7a`) occurs in two distinct placements across RPF9 archives: - -1. `standalone` (`0x7a` metadata or map-placement resource): - Starts an inflated RAGE system stream with an 8-byte zero prefix, a `0x50000000`-based - page-map pointer at `+0x08`, and the 80-byte `0DRP` header at `+0x10..+0x5f` (`0x60` bytes - total). Table slots at `+0x28` (structs, 32 B each) and `+0x38` (instance blocks, 16 B each) - hold `0x50000000`-based virtual pointers (`+0x30` enums and `+0x40` hold `0` or a - `0x50000000`-based pointer), and `+0x48` stores four `u16` values - `(structs, enums, blocks, unknown_4e)`. When a table or virtual block crosses the first - stream's end, contiguous zlib streams continue the resource. - -2. `psin_lrsc` (`PSIN` `LRSC` root/count summary record): - Sits at `+0x00` of an 80-byte `LRSC` section payload (`"LRSC"` + big-endian `88` = 88 bytes - total) near the end of a `PSIN` container, followed by a 20-byte `CHKS` section. It reuses - the same 80-byte `0DRP` header frame without the 16-byte page prefix, but fills all four - table-pointer slots (`+0x18..+0x37`) and `+0x40..+0x47` with `0xbb` (`0xbbbbbbbbbbbbbbbb`) - because structs, enums and instance blocks live in `PSIN`'s own `LSCH`, `LENM` and `+0x08` - block table. Its `+0x08..+0x0f` qword is zero (`+0x0c` is never a page count), `u32@+0x10` - is the 1-based root block index in `1..blocks`, and the four `u16`s at `+0x38` are - `(structs, enums, blocks, 0)`. - -This module parses and validates both placements without misreading one as the other, and scans -RPF9 data areas, carved `.bin` directories, or single carved files. Output contains structural -counts and offsets only; no game payloads, names, or asset hashes are written. - -Usage: - python -I tools/odrp_7a.py [--start N] [--limit BYTES] - [--max-inflate BYTES] [--quiet] -""" -import argparse -import csv -import json -import mmap -import os -import re -import struct -import sys -import tempfile -import time -import zlib - -sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) -from file_mode import published_mode # noqa: E402 - -SIGNATURE = b"0DRP" -VERSION = 0x7A -PSIN_MAGIC = b"PSIN" -LRSC_TAG = b"LRSC" -CHKS_TAG = b"CHKS" - -STANDALONE_HEADER_SIZE = 0x60 -ODRP_FRAME_SIZE = 0x50 -LRSC_PAYLOAD_SIZE = 0x50 -LRSC_SECTION_SIZE = 8 + LRSC_PAYLOAD_SIZE -CHKS_SECTION_SIZE = 20 - -VIRTUAL_BASE = 0x50000000 -PHYSICAL_BASE = 0x60000000 -SEGMENT_SPAN = 0x10000000 - -LRSC_PTR_FILL_32 = b"\xbb" * 32 -LRSC_TAIL_FILL_8 = b"\xbb" * 8 -BLOCK_ROW_FILL_8 = b"\xaa" * 8 -BLOCK_TABLE_END = 0x70707070 - -ARRAY_ELEMENT_HASH = 0x100 -ARRAY_MEMBER_TYPE = 0x5C -ENTITY_STRUCT = 0xCE501483 -MAPDATA_STRUCT = 0xD3593FA6 - -MAX_INFLATE = 64 << 20 -MAX_CONTINUATIONS = 32 -ZHDR = re.compile(rb"\x78[\x01\x5e\x9c\xda]|KB2[a-z]") - -COLUMNS = [ - "offset", - "stored", - "size", - "streams", - "placement", - "framing", - "version", - "complete", - "resource_kind", - "structs", - "enums", - "blocks", - "root_objects", - "root_block", - "entities", - "schema_checked", - "error", -] - - -def _u16(data, at): - return struct.unpack_from("I", data, at)[0] if 0 <= at and at + 4 <= len(data) else None - - -def virtual_offset(pointer): - """Resolve a zero-extended `0x50000000`-based virtual pointer to its logical resource offset.""" - if pointer is None: - return None - if (pointer >> 32) == 0 and VIRTUAL_BASE <= pointer < VIRTUAL_BASE + SEGMENT_SPAN: - return pointer - VIRTUAL_BASE - return None - - -def physical_offset(pointer): - """Resolve a zero-extended `0x60000000`-based physical/graphics pointer to its segment offset.""" - if pointer is None: - return None - if (pointer >> 32) == 0 and PHYSICAL_BASE <= pointer < PHYSICAL_BASE + SEGMENT_SPAN: - return pointer - PHYSICAL_BASE - return None - - -def _optional_virtual_offset(pointer): - """Allow either `0` (absent optional table) or a `0x50000000`-based virtual pointer.""" - if pointer == 0: - return 0 - return virtual_offset(pointer) - - -def parse_standalone_header(data): - """Validate the fixed `0x60`-byte header of a standalone `0DRP`/`0x7a` resource. - - Returns a header dict when `data` begins with the 16-byte RAGE system-page prefix - (`8` zero bytes + `0x50000000` pointer) followed by `"0DRP"`, version `122`, and valid - `0x50000000` table pointers; otherwise returns `None`. - """ - if len(data) < STANDALONE_HEADER_SIZE: - return None - if data[0x00:0x08] != b"\x00" * 8: - return None - page_map = virtual_offset(_u64(data, 0x08)) - if page_map is None: - return None - if data[0x10:0x14] != SIGNATURE or _u32(data, 0x14) != VERSION: - return None - if data[0x18:0x20] != b"\x00" * 8: - return None - root_objects = _u32(data, 0x20) - if _u32(data, 0x24) != 0: - return None - q28 = virtual_offset(_u64(data, 0x28)) - q30 = _optional_virtual_offset(_u64(data, 0x30)) - q38 = virtual_offset(_u64(data, 0x38)) - q40 = _optional_virtual_offset(_u64(data, 0x40)) - q50 = _optional_virtual_offset(_u64(data, 0x50)) - if None in (q28, q30, q38, q40, q50): - return None - if data[0x58:0x60] != b"\x00" * 8: - return None - structs, enums, blocks, unknown_4e = struct.unpack_from("<4H", data, 0x48) - if not (1 <= structs <= 4096 and enums <= 4096 and 1 <= blocks <= 4096): - return None - if enums > 0 and _u64(data, 0x30) == 0: - return None - return { - "page_map": page_map, - "version": VERSION, - "root_objects": root_objects, - "structs": structs, - "enums": enums, - "blocks": blocks, - "unknown_4e": unknown_4e, - "tables": { - "q28": q28, - "q30": None if _u64(data, 0x30) == 0 else q30, - "q38": q38, - "q40": None if _u64(data, 0x40) == 0 else q40, - "q50": None if _u64(data, 0x50) == 0 else q50, - }, - } - - -def parse_standalone(data): - """Parse and validate a standalone `0DRP`/`0x7a` resource (single or joined system bytes). - - Returns `None` when `data` does not start with a valid standalone `0DRP`/`0x7a` header. - When the header validates, checks struct/member/enum/instance tables: - - If a table or virtual block extends past `len(data)`, returns `complete=False` and - `needs_continuation=True` so an archive/directory scanner can append continuation streams. - - If an in-bounds pointer, struct size, or member offset violates the `0x7a` schema rules, - returns `complete=False` and `needs_continuation=False` with a descriptive `error`. - """ - hdr = parse_standalone_header(data) - if hdr is None: - return None - - size = len(data) - nst = hdr["structs"] - nen = hdr["enums"] - nbl = hdr["blocks"] - q28 = hdr["tables"]["q28"] - q30 = hdr["tables"]["q30"] - q38 = hdr["tables"]["q38"] - - base_row = { - "placement": "standalone", - "framing": "resource", - "version": VERSION, - "complete": False, - "needs_continuation": False, - "resource_kind": "meta", - "structs": nst, - "enums": nen, - "blocks": nbl, - "root_objects": hdr["root_objects"], - "root_block": None, - "unknown_4e": hdr["unknown_4e"], - "virtual_blocks": 0, - "physical_blocks": 0, - "entities": 0, - "schema_checked": False, - "error": "", - } - - if q28 + 32 * nst > size: - base_row["needs_continuation"] = True - base_row["error"] = "struct table extends past stream end" - return base_row - if nen > 0 and q30 is not None and q30 + 24 * nen > size: - base_row["needs_continuation"] = True - base_row["error"] = "enum table extends past stream end" - return base_row - if q38 + 16 * nbl > size: - base_row["needs_continuation"] = True - base_row["error"] = "instance table extends past stream end" - return base_row - - struct_sizes = {} - for i in range(nst): - off = q28 + 32 * i - shash, _sig, _flags, _zero0c, mptr_raw, ssize, _zero1c, mcount = struct.unpack_from( - " (1 << 20) or mcount > 256: - base_row["error"] = f"struct {i} exceeds size or member cap" - return base_row - if mcount > 0: - moff = virtual_offset(mptr_raw) - if moff is None: - base_row["error"] = f"struct {i} has non-virtual member pointer" - return base_row - if moff + 16 * mcount > size: - base_row["needs_continuation"] = True - base_row["error"] = f"struct {i} member table extends past stream end" - return base_row - for j in range(mcount): - mhash, field_off, mtype, _sub, elem_idx, _ref = struct.unpack_from( - "= ssize: - base_row["error"] = f"struct {i} member {j} offset {field_off} >= size {ssize}" - return base_row - if mtype == ARRAY_MEMBER_TYPE: - if elem_idx >= mcount: - base_row["error"] = f"struct {i} array member {j} index {elem_idx} out of range" - return base_row - desc_hash = _u32(data, moff + 16 * elem_idx) - if desc_hash != ARRAY_ELEMENT_HASH: - base_row["error"] = f"struct {i} array member {j} target is not 0x100" - return base_row - struct_sizes.setdefault(shash, ssize) - - virtual_blocks = 0 - physical_blocks = 0 - resolved_struct_block = False - needs_more_blocks = False - block_list = [] - - for i in range(nbl): - off = q38 + 16 * i - bhash, bsize, bptr = struct.unpack_from(" (1 << 24): - base_row["error"] = f"block {i} exceeds 16 MiB cap" - return base_row - voff = virtual_offset(bptr) - if voff is not None: - virtual_blocks += 1 - if voff + bsize > size: - needs_more_blocks = True - else: - if bhash in struct_sizes: - resolved_struct_block = True - block_list.append((bhash, bsize, voff)) - continue - poff = physical_offset(bptr) - if poff is not None: - physical_blocks += 1 - block_list.append((bhash, bsize, None)) - continue - base_row["error"] = f"block {i} has invalid segment pointer" - return base_row - - base_row["virtual_blocks"] = virtual_blocks - base_row["physical_blocks"] = physical_blocks - - if needs_more_blocks: - base_row["needs_continuation"] = True - base_row["error"] = "virtual block payload extends past stream end" - return base_row - - if not resolved_struct_block: - base_row["error"] = "no virtual block matches a declared struct" - return base_row - - entity_size = struct_sizes.get(ENTITY_STRUCT, 0) - map_size = struct_sizes.get(MAPDATA_STRUCT, 0) - if entity_size > 0 and map_size > 0: - base_row["resource_kind"] = "map" - base_row["entities"] = sum( - bsize // entity_size - for bhash, bsize, voff in block_list - if bhash == ENTITY_STRUCT and voff is not None and voff + bsize <= size and bsize % entity_size == 0 - ) - - base_row["complete"] = True - base_row["schema_checked"] = True - return base_row - - -def parse_lrsc_payload(payload): - """Validate an 80-byte `PSIN` `LRSC` `0DRP` payload. - - Returns a dict on an exact 80-byte `LRSC` payload with `"0DRP"` + `122`, zero `+0x08..+0x0f`, - `1 <= root_block <= blocks`, `0xbb` fill at `+0x18..+0x37` and `+0x40..+0x47`, `u16@+0x3e == 0`, - and zero `+0x48..+0x4f`; otherwise returns `None`. - """ - if len(payload) != LRSC_PAYLOAD_SIZE: - return None - if payload[0x00:0x04] != SIGNATURE or _u32(payload, 0x04) != VERSION: - return None - if payload[0x08:0x10] != b"\x00" * 8: - return None - root_block, root_hi = struct.unpack_from(" len(blob): - return None - at = 8 - count = 0 - sizes = [] - while at + 8 <= first_section: - kind = _u32(blob, at) - if kind == BLOCK_TABLE_END: - break - if at + 16 > first_section or blob[at + 8:at + 16] != BLOCK_ROW_FILL_8: - return None - sizes.append(_u32(blob, at + 4)) - count += 1 - at += 16 - else: - return None - end = (at + 15) & ~15 - if end > first_section or blob[at:end] != b"\x70" * (end - at): - return None - pos = end - for bsize in sizes: - if pos + bsize > first_section: - return None - pos += (bsize + 15) & ~15 - if pos != first_section: - return None - return count - - -def _parse_psin_container(blob): - """Walk a `PSIN` container to locate and cross-check its `LRSC` `0DRP` record. - - Returns: - - a record dict when `LRSC` contains `"0DRP"` (complete or truncated), OR when a `PSIN` - stream is truncated before reaching `LRSC` (`needs_continuation=True`, `has_odrp=False`), - - `None` when the `PSIN` container is complete and has no `LRSC` section (e.g. `PMAP`/`PSCH`). - """ - first = _be32(blob, 4) - if first is None or first < 16: - return None - if first + 8 > len(blob): - return { - "has_odrp": False, - "needs_continuation": True, - "error": "first section offset extends past stream end", - } - pos = first - lsch_count = None - lenm_count = None - lrsc_off = None - lrsc_size = None - walk_error = "" - needs_cont = False - - while pos + 8 <= len(blob): - tag = blob[pos:pos + 4] - if any(c < 0x20 or c > 0x7E for c in tag): - walk_error = f"non-ASCII section tag at {pos}" - break - ssize = _be32(blob, pos + 4) - if ssize is None or ssize < 8: - walk_error = f"invalid section size at {pos}" - break - if pos + ssize > len(blob): - needs_cont = True - walk_error = f"section {tag.decode('ascii')} extends past stream end" - if tag == LRSC_TAG: - lrsc_off = pos - lrsc_size = ssize - break - pay = blob[pos + 8:pos + ssize] - if tag == b"LSCH" and lsch_count is None: - lsch_count = _header_count(pay, 32, 16, 30, "= 4 and avail_pay[:4] != SIGNATURE: - return None - if len(avail_pay) < LRSC_PAYLOAD_SIZE or lrsc_off + lrsc_size > len(blob): - return { - "has_odrp": True, - "placement": "psin_lrsc", - "framing": "psin", - "version": _u32(avail_pay, 4) if len(avail_pay) >= 8 else VERSION, - "complete": False, - "needs_continuation": True, - "resource_kind": None, - "structs": None, - "enums": None, - "blocks": None, - "root_objects": None, - "root_block": _u32(avail_pay, 0x10) if len(avail_pay) >= 0x14 else None, - "entities": None, - "schema_checked": False, - "error": walk_error or "truncated LRSC payload", - } - - if lrsc_size != LRSC_SECTION_SIZE: - return { - "has_odrp": True, - "placement": "psin_lrsc", - "framing": "psin", - "version": _u32(avail_pay, 4), - "complete": False, - "needs_continuation": False, - "resource_kind": None, - "structs": None, - "enums": None, - "blocks": None, - "root_objects": None, - "root_block": None, - "entities": None, - "schema_checked": False, - "error": f"LRSC section size is {lrsc_size}, expected {LRSC_SECTION_SIZE}", - } - - parsed = parse_lrsc_payload(avail_pay) - if parsed is None: - return { - "has_odrp": True, - "placement": "psin_lrsc", - "framing": "psin", - "version": _u32(avail_pay, 4), - "complete": False, - "needs_continuation": False, - "resource_kind": None, - "structs": None, - "enums": None, - "blocks": None, - "root_objects": None, - "root_block": None, - "entities": None, - "schema_checked": False, - "error": "LRSC payload failed 0DRP/0x7a validation", - } - - block_count = _psin_block_count(blob, first) - mismatches = [] - if lsch_count is not None and parsed["structs"] != lsch_count: - mismatches.append(f"structs {parsed['structs']} != LSCH {lsch_count}") - if lenm_count is not None and parsed["enums"] != lenm_count: - mismatches.append(f"enums {parsed['enums']} != LENM {lenm_count}") - if block_count is not None and parsed["blocks"] != block_count: - mismatches.append(f"blocks {parsed['blocks']} != block_table {block_count}") - - err = "; ".join(x for x in (walk_error, ", ".join(mismatches)) if x) - checked = ( - not err - and lsch_count is not None - and lenm_count is not None - and block_count is not None - ) - return { - "has_odrp": True, - "placement": "psin_lrsc", - "framing": "psin", - "version": VERSION, - "complete": not err, - "needs_continuation": needs_cont, - "resource_kind": None, - "structs": parsed["structs"], - "enums": parsed["enums"], - "blocks": parsed["blocks"], - "root_objects": None, - "root_block": parsed["root_block"], - "entities": None, - "schema_checked": checked, - "error": err, - } - - -def parse_psin_lrsc(blob): - """Parse a `PSIN` `LRSC` `0DRP`/`0x7a` record from any of its four framings: - - - `"psin"`: a `PSIN` container starting with `"PSIN"` at `+0x00`; - - `"lrsc_section"`: a bare 88-byte `"LRSC"` section (`"LRSC"` + big-endian `88` + payload); - - `"lrsc_payload"`: a bare 80-byte `LRSC` `0DRP` payload starting with `"0DRP"` at `+0x00`; - - `"psin_tail"`: an unjoined `PSIN` continuation stream ending with an 88-byte `"LRSC"` - section + 20-byte `"CHKS"` section at EOF. - - Returns a record dict when `blob` matches one of those `LRSC` framings, or `None` otherwise. - """ - if len(blob) >= 16 and blob[:4] == PSIN_MAGIC: - res = _parse_psin_container(blob) - if res is None or not res.get("has_odrp"): - return None - out = dict(res) - out.pop("has_odrp", None) - return out - - if len(blob) >= 8 and blob[:4] == LRSC_TAG: - declared = _be32(blob, 4) - if declared != LRSC_SECTION_SIZE or len(blob) != LRSC_SECTION_SIZE: - return { - "placement": "psin_lrsc", - "framing": "lrsc_section", - "version": _u32(blob, 12) if len(blob) >= 16 else None, - "complete": False, - "needs_continuation": len(blob) < LRSC_SECTION_SIZE, - "resource_kind": None, - "structs": None, - "enums": None, - "blocks": None, - "root_objects": None, - "root_block": None, - "entities": None, - "schema_checked": False, - "error": f"LRSC section length {len(blob)} (declared {declared}) != {LRSC_SECTION_SIZE}", - } - parsed = parse_lrsc_payload(blob[8:]) - if parsed is None: - return { - "placement": "psin_lrsc", - "framing": "lrsc_section", - "version": _u32(blob, 12), - "complete": False, - "needs_continuation": False, - "resource_kind": None, - "structs": None, - "enums": None, - "blocks": None, - "root_objects": None, - "root_block": None, - "entities": None, - "schema_checked": False, - "error": "LRSC payload failed 0DRP/0x7a validation", - } - return { - "placement": "psin_lrsc", - "framing": "lrsc_section", - "version": VERSION, - "complete": True, - "needs_continuation": False, - "resource_kind": None, - "structs": parsed["structs"], - "enums": parsed["enums"], - "blocks": parsed["blocks"], - "root_objects": None, - "root_block": parsed["root_block"], - "entities": None, - "schema_checked": False, - "error": "", - } - - if len(blob) >= 4 and blob[:4] == SIGNATURE: - parsed = parse_lrsc_payload(blob) - if parsed is not None: - return { - "placement": "psin_lrsc", - "framing": "lrsc_payload", - "version": VERSION, - "complete": True, - "needs_continuation": False, - "resource_kind": None, - "structs": parsed["structs"], - "enums": parsed["enums"], - "blocks": parsed["blocks"], - "root_objects": None, - "root_block": parsed["root_block"], - "entities": None, - "schema_checked": False, - "error": "", - } - # Reject stripped standalone headers (`0x50000000` pointers at +0x18/+0x28) or malformed - # `0DRP@0x0` buffers explicitly rather than guessing a placement. - return None - - tail_len = LRSC_SECTION_SIZE + CHKS_SECTION_SIZE - if len(blob) >= tail_len and parse_standalone_header(blob) is None: - lrsc_at = len(blob) - tail_len - chks_at = len(blob) - CHKS_SECTION_SIZE - if ( - blob[lrsc_at:lrsc_at + 4] == LRSC_TAG - and _be32(blob, lrsc_at + 4) == LRSC_SECTION_SIZE - and blob[chks_at:chks_at + 4] == CHKS_TAG - and _be32(blob, chks_at + 4) == CHKS_SECTION_SIZE - ): - parsed = parse_lrsc_payload(blob[lrsc_at + 8:chks_at]) - if parsed is not None: - return { - "placement": "psin_lrsc", - "framing": "psin_tail", - "version": VERSION, - "complete": True, - "needs_continuation": False, - "resource_kind": None, - "structs": parsed["structs"], - "enums": parsed["enums"], - "blocks": parsed["blocks"], - "root_objects": None, - "root_block": parsed["root_block"], - "entities": None, - "schema_checked": False, - "error": "", - } - return None - - -def classify_blob(blob): - """Classify and parse a single buffer as `standalone` or `psin_lrsc`, or `None` if neither.""" - standalone = parse_standalone(blob) - if standalone is not None: - return standalone - return parse_psin_lrsc(blob) - - -def _starts_new_container(data): - return ( - (len(data) >= 16 and data[:4] == PSIN_MAGIC) - or parse_standalone_header(data) is not None - ) - - -def _finalize_row(record, offset, stored, size, streams): - out = dict(record) - out.pop("needs_continuation", None) - out.pop("unknown_4e", None) - out.pop("virtual_blocks", None) - out.pop("physical_blocks", None) - out["offset"] = offset - out["stored"] = stored - out["size"] = size - out["streams"] = streams - return out - - -class _StreamConsumer: - """Bounded-memory stream consumer that joins contiguous `standalone` and `PSIN` continuations.""" - - def __init__(self, max_inflate=MAX_INFLATE): - self.max_inflate = max_inflate - self.rows = [] - self.pending = None - - def _flush_pending(self): - if self.pending is None: - return - item = self.pending - self.pending = None - if item["kind"] == "standalone": - self.rows.append( - _finalize_row(item["rec"], item["offset"], item["stored"], len(item["data"]), item["streams"]) - ) - elif item["rec"] is not None and item["rec"].get("has_odrp"): - rec = dict(item["rec"]) - rec.pop("has_odrp", None) - self.rows.append( - _finalize_row(rec, item["offset"], item["stored"], len(item["data"]), item["streams"]) - ) - - def feed(self, offset, stored, data, inflated_size=None): - actual_size = len(data) if inflated_size is None else inflated_size - next_off = ((offset + stored + 15) & ~15) if stored is not None else None - - if self.pending is not None: - item = self.pending - can_join = ( - item["next_off"] is not None - and item["next_off"] == offset - and item["streams"] <= MAX_CONTINUATIONS - and not _starts_new_container(data) - and actual_size == len(data) - and len(item["data"]) + len(data) <= self.max_inflate - ) - if can_join: - item["data"].extend(data) - if item["stored"] is not None and stored is not None: - item["stored"] += stored - item["next_off"] = next_off - item["streams"] += 1 - joined = bytes(item["data"]) - if item["kind"] == "standalone": - rec = parse_standalone(joined) - else: - rec = _parse_psin_container(joined) - item["rec"] = rec - if rec is None or not rec.get("needs_continuation"): - self._flush_pending() - return - self._flush_pending() - - if parse_standalone_header(data) is not None: - rec = parse_standalone(data) - if rec["needs_continuation"] and next_off is not None: - self.pending = { - "kind": "standalone", - "offset": offset, - "stored": stored, - "next_off": next_off, - "data": bytearray(data), - "streams": 1, - "rec": rec, - } - else: - self.rows.append(_finalize_row(rec, offset, stored, actual_size, 1)) - return - - if len(data) >= 16 and data[:4] == PSIN_MAGIC: - res = _parse_psin_container(data) - if res is not None and res["needs_continuation"] and next_off is not None: - self.pending = { - "kind": "psin", - "offset": offset, - "stored": stored, - "next_off": next_off, - "data": bytearray(data), - "streams": 1, - "rec": res, - } - elif res is not None and res.get("has_odrp"): - rec = dict(res) - rec.pop("has_odrp", None) - self.rows.append(_finalize_row(rec, offset, stored, actual_size, 1)) - return - - rec = parse_psin_lrsc(data) - if rec is not None: - self.rows.append(_finalize_row(rec, offset, stored, actual_size, 1)) - - def finish(self): - self._flush_pending() - return self.rows - - -def _gap_bytes(gap): - return (len(gap), 0) if gap.count(0) == len(gap) else (0, len(gap)) - - -def scan_rpf(path, start=None, limit=None, max_inflate=MAX_INFLATE): - """Walk an RPF9 archive data area inside `[start, start + limit)`. No TOC is touched.""" - t0 = time.time() - file_size = os.path.getsize(path) - if file_size == 0: - raise ValueError("empty file") - - consumer = _StreamConsumer(max_inflate=max_inflate) - tail_keep = LRSC_SECTION_SIZE + CHKS_SECTION_SIZE - stream_bytes = 0 - inflated_bytes = 0 - stream_count = 0 - zero = unread = skipped = 0 - - with open(path, "rb") as fh: - with mmap.mmap(fh.fileno(), 0, access=mmap.ACCESS_READ) as m: - size = len(m) - first = _u32(m, 4) if size >= 8 else 0 - pos = start if start is not None else first - if not 0 <= pos <= size: - raise ValueError("start offset is outside the archive") - end = min(size, pos + limit) if limit is not None else size - span = end - pos - last = pos - while pos < end: - found = ZHDR.search(m, pos, end) - if not found: - break - s = found.start() - if m[s:s + 3] == b"KB2": - blen = (_u32(m, s + 4) or 0) + 8 - w, h = _u32(m, s + 0x14), _u32(m, s + 0x18) - if not (64 <= blen <= end - s and w and h and 16 <= w <= 8192 and 16 <= h <= 8192): - pos = s + 1 - continue - consumer._flush_pending() - z, u = _gap_bytes(m[last:s]) - zero += z - unread += u - stream_count += 1 - stream_bytes += blen - inflated_bytes += blen - last = pos = s + blen - continue - - if consumer.pending is not None and consumer.pending["next_off"] != s: - consumer._flush_pending() - keep_full = consumer.pending is not None - - d = zlib.decompressobj() - p = s - total = 0 - head = bytearray() - tail = bytearray() - chunks = [] - decided = False - too_big = False - try: - while not d.eof and p < end: - block = m[p:min(p + (1 << 20), end)] - if not block: - break - p += len(block) - while block and not d.eof: - chunk = d.decompress(block, 1 << 20) - block = d.unconsumed_tail - if chunk: - total += len(chunk) - if total > max_inflate: - too_big = True - break - if keep_full: - chunks.append(chunk) - elif not decided: - chunks.append(chunk) - if len(head) < STANDALONE_HEADER_SIZE: - head.extend(chunk[:STANDALONE_HEADER_SIZE - len(head)]) - if len(head) >= STANDALONE_HEADER_SIZE: - decided = True - if head[:4] == PSIN_MAGIC or parse_standalone_header(head) is not None: - keep_full = True - else: - joined_so_far = b"".join(chunks) - tail = bytearray(joined_so_far[-tail_keep:]) - chunks.clear() - else: - if len(chunk) >= tail_keep: - tail = bytearray(chunk[-tail_keep:]) - else: - tail.extend(chunk) - if len(tail) > tail_keep: - del tail[:-tail_keep] - if not block: - break - if too_big: - break - except zlib.error: - pos = s + 1 - continue - if too_big or not d.eof or total < 64: - skipped += 1 - pos = s + 1 - continue - used = p - s - len(d.unused_data) - z, u = _gap_bytes(m[last:s]) - zero += z - unread += u - if keep_full or not decided: - data = b"".join(chunks) - consumer.feed(s, used, data, inflated_size=total) - else: - # Non-container stream: head (0x60 B) + tail (<= 108 B) suffices for psin_tail check. - probe = bytes(head) + bytes(tail) if total > STANDALONE_HEADER_SIZE + len(tail) else bytes(head) - if total <= STANDALONE_HEADER_SIZE + tail_keep and len(probe) != total: - # Overlap between head and tail on short streams (64..196 B): reconstruct exact bytes. - overlap = STANDALONE_HEADER_SIZE + len(tail) - total - probe = bytes(head) + bytes(tail[overlap:]) - consumer.feed(s, used, probe, inflated_size=total) - stream_count += 1 - stream_bytes += used - inflated_bytes += total - last = pos = s + used - - z, u = _gap_bytes(m[last:end]) - zero += z - unread += u - - rows = consumer.finish() - summary = summarise( - rows, - mode="rpf9", - source=path, - streams=stream_count, - compressed_bytes=stream_bytes, - inflated_bytes=inflated_bytes, - span=span, - zero_padding=zero, - unread_bytes=unread, - skipped_candidates=skipped, - elapsed=round(time.time() - t0, 3), - ) - return rows, summary - - -def _carve_stored_map(folder): - manifest = os.path.join(folder, "index.json") - try: - with open(manifest, encoding="utf-8") as fh: - files = json.load(fh).get("files", []) - return {int(item["off"]): int(item["stored"]) for item in files} - except (OSError, ValueError, TypeError, KeyError, AttributeError): - return {} - - -def _is_carved_file(path): - return path.lower().endswith(".bin") and os.path.isfile(path) - - -def scan_dir(path, max_inflate=MAX_INFLATE): - """Scan a directory of carved `.bin` files in bounded memory.""" - t0 = time.time() - by_off = _carve_stored_map(path) - candidates = [] - skipped = 0 - for idx, name in enumerate(sorted(os.listdir(path))): - full = os.path.join(path, name) - if not _is_carved_file(full): - continue - fsize = os.path.getsize(full) - if fsize > max_inflate: - skipped += 1 - continue - m = re.match(r"([0-9a-fA-F]{6,})", name) - offset = int(m.group(1), 16) if m else idx - candidates.append((not bool(m), offset, full, fsize)) - - candidates.sort(key=lambda item: (item[0], item[1])) - consumer = _StreamConsumer(max_inflate=max_inflate) - inflated = 0 - stored_sum = 0 - for _no_hex, offset, full, _fsize in candidates: - with open(full, "rb") as fh: - data = fh.read() - stored = by_off.get(offset) - inflated += len(data) - stored_sum += stored if stored is not None else len(data) - consumer.feed(offset, stored, data) - - rows = consumer.finish() - summary = summarise( - rows, - mode="directory", - source=path, - streams=len(candidates), - compressed_bytes=stored_sum, - inflated_bytes=inflated, - span=stored_sum, - zero_padding=0, - unread_bytes=0, - skipped_candidates=skipped, - elapsed=round(time.time() - t0, 3), - ) - return rows, summary - - -def scan_file(path, max_inflate=MAX_INFLATE): - """Parse a single carved/extracted binary file.""" - t0 = time.time() - fsize = os.path.getsize(path) - if fsize > max_inflate: - return [], summarise( - [], - mode="file", - source=path, - streams=0, - compressed_bytes=0, - inflated_bytes=0, - span=0, - zero_padding=0, - unread_bytes=0, - skipped_candidates=1, - elapsed=round(time.time() - t0, 3), - ) - with open(path, "rb") as fh: - data = fh.read() - rec = classify_blob(data) - rows = [_finalize_row(rec, 0, len(data), len(data), 1)] if rec is not None else [] - summary = summarise( - rows, - mode="file", - source=path, - streams=1, - compressed_bytes=len(data), - inflated_bytes=len(data), - span=len(data), - zero_padding=0, - unread_bytes=0, - skipped_candidates=0, - elapsed=round(time.time() - t0, 3), - ) - return rows, summary - - -def summarise( - rows, - *, - mode, - source, - streams, - compressed_bytes, - inflated_bytes, - span, - zero_padding, - unread_bytes, - skipped_candidates, - elapsed, -): - standalone = [r for r in rows if r["placement"] == "standalone"] - psin_lrsc = [r for r in rows if r["placement"] == "psin_lrsc"] - framings = {} - for r in rows: - framings[r["framing"]] = framings.get(r["framing"], 0) + 1 - return { - "mode": mode, - "source": source, - "streams": streams, - "compressed_bytes": compressed_bytes, - "inflated_bytes": inflated_bytes, - "span": span, - "zero_padding": zero_padding, - "unread_bytes": unread_bytes, - "readable_fraction": round(compressed_bytes / span, 6) if span else 0.0, - "skipped_candidates": skipped_candidates, - "records": len(rows), - "complete": sum(1 for r in rows if r["complete"]), - "incomplete": sum(1 for r in rows if not r["complete"]), - "standalone": len(standalone), - "standalone_complete": sum(1 for r in standalone if r["complete"]), - "standalone_meta": sum(1 for r in standalone if r["resource_kind"] == "meta"), - "standalone_map": sum(1 for r in standalone if r["resource_kind"] == "map"), - "standalone_joined": sum(1 for r in standalone if r["streams"] > 1), - "standalone_entities": sum(r["entities"] or 0 for r in standalone), - "psin_lrsc": len(psin_lrsc), - "psin_lrsc_complete": sum(1 for r in psin_lrsc if r["complete"]), - "psin_lrsc_joined": sum(1 for r in psin_lrsc if r["streams"] > 1), - "psin_lrsc_schema_checked": sum(1 for r in psin_lrsc if r["schema_checked"]), - "framings": dict(sorted(framings.items())), - "elapsed_seconds": elapsed, - } - - -def write_output(path, rows, summary): - ext = os.path.splitext(path)[1].lower() - parent = os.path.dirname(os.path.abspath(path)) - tmp = None - try: - if ext == ".json": - with tempfile.NamedTemporaryFile("w", encoding="utf-8", newline="\n", dir=parent, - prefix=".odrp_7a-", suffix=".tmp", delete=False) as fh: - tmp = fh.name - json.dump({"summary": summary, "records": rows}, fh, indent=1) - else: - with tempfile.NamedTemporaryFile("w", encoding="utf-8", newline="", dir=parent, - prefix=".odrp_7a-", suffix=".tmp", delete=False) as fh: - tmp = fh.name - writer = csv.DictWriter(fh, fieldnames=COLUMNS, lineterminator="\n") - writer.writeheader() - for row in rows: - out = {} - for col in COLUMNS: - val = row[col] - if col == "offset": - out[col] = f"0x{val:x}" - elif isinstance(val, bool): - out[col] = int(val) - elif val is None: - out[col] = "" - else: - out[col] = val - writer.writerow(out) - os.chmod(tmp, published_mode(path)) - os.replace(tmp, path) - except BaseException: - if tmp is not None: - try: - if os.path.lexists(tmp): - os.chmod(tmp, 0o600) - os.remove(tmp) - except OSError: - pass - raise - - -def _offset_arg(text): - try: - value = int(text, 0) - except ValueError: - raise argparse.ArgumentTypeError("must be 0 or more") from None - if value < 0: - raise argparse.ArgumentTypeError("must be 0 or more") - return value - - -def _positive_bytes_arg(text): - try: - value = int(text, 0) - except ValueError: - raise argparse.ArgumentTypeError("must be at least 1") from None - if value < 1: - raise argparse.ArgumentTypeError("must be at least 1") - return value - - -def _same_path(first, second): - if os.path.normcase(os.path.realpath(first)) == os.path.normcase(os.path.realpath(second)): - return True - try: - return os.path.samefile(first, second) - except OSError: - return False - - -def _is_rpf_file(path): - if not os.path.isfile(path) or os.path.getsize(path) < 4: - return path.lower().endswith(".rpf") - with open(path, "rb") as fh: - return fh.read(4) == b"9FPR" - - -def main(argv=None): - ap = argparse.ArgumentParser(description=__doc__.splitlines()[0]) - ap.add_argument("source", help=".rpf archive, carved directory, or single binary stream") - ap.add_argument("out", help="output path ending in .json or .csv") - ap.add_argument("--start", type=_offset_arg, help="first archive offset to scan (default: RPF data start)") - ap.add_argument("--limit", type=_positive_bytes_arg, help="number of archive bytes to scan") - ap.add_argument( - "--max-inflate", - type=_positive_bytes_arg, - default=MAX_INFLATE, - help="skip or cap resources inflating above this many bytes (default: 64 MiB)", - ) - ap.add_argument("--quiet", action="store_true") - args = ap.parse_args(argv) - - if os.path.isdir(args.out): - ap.error(f"{args.out} is a folder, not a .json or .csv file") - ext = os.path.splitext(args.out)[1].lower() - if ext not in (".json", ".csv"): - ap.error("output must end in .json or .csv") - parent = os.path.dirname(os.path.abspath(args.out)) - if not os.path.isdir(parent): - ap.error(f"{parent} is not a folder, so {args.out} cannot be written") - if _same_path(args.source, args.out): - ap.error("output must not overwrite the source") - - if os.path.isdir(args.source): - if args.start is not None or args.limit is not None: - ap.error("--start and --limit apply to an .rpf archive, not a directory") - manifest = os.path.join(args.source, "index.json") - if os.path.isfile(manifest) and _same_path(manifest, args.out): - ap.error(f"output would overwrite the carve manifest: {args.out}") - if os.path.isfile(args.out): - for name in os.listdir(args.source): - cand = os.path.join(args.source, name) - if _is_carved_file(cand) and _same_path(cand, args.out): - ap.error(f"output would overwrite an input file: {args.out}") - elif os.path.isfile(args.source): - is_rpf = _is_rpf_file(args.source) - if not is_rpf and (args.start is not None or args.limit is not None): - ap.error("--start and --limit apply to an .rpf archive, not a single stream file") - else: - sys.exit(f"{args.source}: no such file or folder") - - try: - if os.path.isdir(args.source): - rows, summary = scan_dir(args.source, args.max_inflate) - elif _is_rpf_file(args.source): - rows, summary = scan_rpf(args.source, args.start, args.limit, args.max_inflate) - else: - rows, summary = scan_file(args.source, args.max_inflate) - write_output(args.out, rows, summary) - except ValueError as exc: - sys.exit(f"{args.source}: {exc}") - except OSError as exc: - sys.exit(f"{args.source}: {exc.strerror or exc}") - - if not args.quiet: - print(json.dumps(summary, indent=1)) - return 0 - - -if __name__ == "__main__": - try: # a redirected stdout is strict ANSI code page under -I; write '?' for what it cannot encode - sys.stdout.reconfigure(errors="replace") - except (AttributeError, ValueError, OSError): - pass - sys.exit(main()) diff --git a/tools/op_reach.py b/tools/op_reach.py deleted file mode 100644 index 0a1043073..000000000 --- a/tools/op_reach.py +++ /dev/null @@ -1,202 +0,0 @@ -"""How many shaders of a disassembled corpus use each instruction, all encodings of it counted as one. - - python -I tools/op_reach.py /shaders/dxbc/disasm [OP ...] [--index /shaders/dxbc/index.json] - [--fssm /shaders/dxbc/fssm] [--json OUT] - -Reads every `.s` listing in the folder (shader_disasm.py output: an instruction line starts with a tab). An -instruction's base name drops the encoding suffix LLVM prints (`_e32`, `_e64`, `_sdwa`, `_dpp`, the same ones -rdna2spirv's `base_op()` strips), so `v_cndmask_b32_e32` and `v_cndmask_b32_e64` count as `v_cndmask_b32`, and a -shader using both counts once. tools/shader_profile.py counts the printed names instead. - -An OP with `*` or `?` is a pattern over the printed names instead (`fnmatch`, case-sensitive): `'*_dpp'` counts -the shaders with any DPP instruction, `'v_*_f16_sdwa'` the 16-bit SDWA forms. - -Only the program counts: lines after a listing's last `s_endpgm` are data words LLVM decoded anyway (some -listings run past the program; on 1.0.2.1 every `s_cmov_b32` in a listing is there), so they are left out and -their total is reported separately as `after_last_endpgm`. A listing with no `s_endpgm` counts whole. - -With OPs, prints those only, an OP no listing uses with 0 (that is the answer to "does the game reach this -rule"). Without, prints every base name, most-used first. `--index` (the carve index) adds the count per stage; -`--fssm` (the folder of sidecar `.fssm` headers) the count per compiled wave size, from the header flag -`fssm_header.wave_size()` reads (`u32[0xD4]` bit 5), and with both, per stage and wave size. - -Standard library only. Prints and writes counts and instruction names only, nothing from the listings. -""" -import argparse -import fnmatch -import json -import os -import re -import sys -from collections import Counter, defaultdict - -sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) -import fssm_header # noqa: E402 - -INSTRUCTION = re.compile(r"^\t([a-z][a-z0-9_]*)", re.M) -ENCODING = re.compile(r"_(e32|e64|sdwa|dpp)$") -HEADER_BYTES = 0x100 # wave_size() reads u32[0xD4] - - -def base_name(op): - """The instruction without the encoding suffix LLVM prints.""" - return ENCODING.sub("", op) - - -def is_pattern(op): - return any(c in op for c in "*?[") - - -def listing_ops(text): - """(printed name -> instructions up to the last s_endpgm, instructions after it) for one listing.""" - ops = INSTRUCTION.findall(text) - end = max((i for i, op in enumerate(ops) if op == "s_endpgm"), default=len(ops) - 1) - return Counter(ops[:end + 1]), len(ops) - end - 1 - - -def stages_of(index_path): - """Listing stem -> stage from the carve index.""" - with open(index_path, encoding="utf-8") as f: - index = json.load(f) - if not isinstance(index, list) or not all(isinstance(e, dict) for e in index): - raise ValueError("index.json is not a list of shader entries") - return {os.path.splitext(e["file"])[0]: e.get("stage") for e in index if isinstance(e.get("file"), str)} - - -def waves_of(fssm_dir, stems): - """Listing stem -> 32, 64, or None (no sidecar, or not an FSSM header).""" - waves = {} - for stem in stems: - try: - with open(os.path.join(fssm_dir, stem + ".fssm"), "rb") as f: - waves[stem] = fssm_header.wave_size(f.read(HEADER_BYTES)) - except FileNotFoundError: - waves[stem] = None - return waves - - -def group_keys(stage, wave, has_waves): - """(stage key, wave key, stage-and-wave key) a listing counts under; None where that split is not asked for.""" - w = (f"w{wave}" if wave else "w?") if has_waves else None - return stage, w, (f"{stage}/{w}" if stage and w else None) - - -def census(disasm_dir, stages=None, fssm_dir=None): - """Every .s file's printed-name counts, with its stage (index) and wave size (FSSM header) when given.""" - names = sorted(n for n in os.listdir(disasm_dir) if n.endswith(".s")) - stems = [n[:-2] for n in names] - waves = waves_of(fssm_dir, stems) if fssm_dir is not None else None - listings = [] - after = 0 - by_name = defaultdict(list) # printed name -> [(listing, count)] - for i, (name, stem) in enumerate(zip(names, stems)): - with open(os.path.join(disasm_dir, name), encoding="utf-8", errors="replace") as f: - ops, tail = listing_ops(f.read()) - after += tail - stage = (stages.get(stem) or "unindexed") if stages is not None else None - wave = waves[stem] if waves is not None else None - listings.append((stage, wave)) - for op, count in ops.items(): - by_name[op].append((i, count)) - groups = [Counter(), Counter(), Counter()] - for stage, wave in listings: - for g, key in zip(groups, group_keys(stage, wave, waves is not None)): - if key: - g[key] += 1 - shaders, instructions = Counter(), Counter() - for op, uses in by_name.items(): - base = base_name(op) - instructions[base] += sum(c for _, c in uses) - for base in instructions: - shaders[base] = len(_users(by_name, [op for op in by_name if base_name(op) == base])) - return {"listings": len(names), "after_last_endpgm": after, "has_stages": stages is not None, - "has_waves": waves is not None, "listing_groups": listings, "by_name": by_name, - "listings_by_stage": dict(sorted(groups[0].items())), "listings_by_wave": dict(sorted(groups[1].items())), - "listings_by_stage_wave": dict(sorted(groups[2].items())), - "shaders": shaders, "instructions": instructions} - - -def _users(by_name, names): - users = set() - for op in names: - users.update(i for i, _ in by_name[op]) - return users - - -def report(result, ops=None): - """Rows for the selected OPs (base names or patterns), or every base name: shaders, instructions, and the - shader count per stage / wave size / both when the census has them.""" - by_name = result["by_name"] - if ops: - chosen = [op if is_pattern(op) else base_name(op) for op in ops] - else: - chosen = sorted(result["shaders"], key=lambda o: (-result["shaders"][o], o)) - rows = [] - for op in chosen: - if is_pattern(op): - names = [n for n in by_name if fnmatch.fnmatchcase(n, op)] - else: - names = [n for n in by_name if base_name(n) == op] - users = _users(by_name, names) - row = {"op": op, "shaders": len(users), "instructions": sum(c for n in names for _, c in by_name[n])} - groups = [Counter(), Counter(), Counter()] - for i in users: - stage, wave = result["listing_groups"][i] - for g, key in zip(groups, group_keys(stage, wave, result["has_waves"])): - if key: - g[key] += 1 - row["by_stage"] = dict(sorted(groups[0].items())) - if result["has_waves"]: - row["by_wave"] = dict(sorted(groups[1].items())) - if result["has_stages"]: - row["by_stage_wave"] = dict(sorted(groups[2].items())) - rows.append(row) - return rows - - -def main(argv=None): - ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) - ap.add_argument("disasm", help="folder of .s listings (/shaders/dxbc/disasm)") - ap.add_argument("ops", nargs="*", help="base instruction names or name patterns to report (default: all names)") - ap.add_argument("--index", help="carve index.json: also count per stage") - ap.add_argument("--fssm", help="folder of the sidecar .fssm headers: also count per wave size") - ap.add_argument("--json", help="also write the rows as JSON") - a = ap.parse_args(argv) - for path in (a.disasm, a.fssm): - if path is not None and not os.path.isdir(path): - print(f"ERROR: {path} is not a folder", file=sys.stderr) - return 2 - try: - stages = stages_of(a.index) if a.index else None - result = census(a.disasm, stages, a.fssm) - except (OSError, ValueError) as e: - print(f"ERROR: {e}", file=sys.stderr) - return 2 - if not result["listings"]: - print(f"ERROR: no .s listing in {a.disasm}", file=sys.stderr) - return 1 - rows = report(result, a.ops) - groups = {k: result[k] for k in ("listings_by_stage", "listings_by_wave", "listings_by_stage_wave") if result[k]} - print(f"{result['listings']} listings" + "".join(f" {v}" for v in groups.values()) + - f", {result['after_last_endpgm']} decoded instructions after the last s_endpgm left out") - for row in rows: - split = row.get("by_stage_wave") or row.get("by_stage") or row.get("by_wave") - detail = f" {split}" if (stages is not None or a.fssm) and split else "" - print(f"{row['op']:32s} {row['shaders']:7d} shaders {row['instructions']:9d} instructions{detail}") - if a.json: - try: - with open(a.json, "w", encoding="utf-8", newline="\n") as f: - json.dump({"listings": result["listings"], **groups, - "after_last_endpgm": result["after_last_endpgm"], "rows": rows}, f, indent=1) - except OSError as e: - print(f"ERROR: cannot write {a.json}: {e.strerror or e}", file=sys.stderr) - return 2 - return 0 - - -if __name__ == "__main__": - try: # a redirected stdout is strict ANSI code page under -I; write '?' for what it cannot encode - sys.stdout.reconfigure(errors="replace") - except (AttributeError, ValueError, OSError): - pass - sys.exit(main()) diff --git a/tools/opus_tags.py b/tools/opus_tags.py deleted file mode 100644 index d106d5685..000000000 --- a/tools/opus_tags.py +++ /dev/null @@ -1,278 +0,0 @@ -"""Write stream names, dialogue labels and subtitles into the Ogg Opus files that awc_opus.py exports. - -awc_opus.py writes //.ogg with an empty OpusTags header. This tool fills that header in place, -from two local work products: - -``--names`` awc_names.py CSV (source, bank, stream_id, name, rule). A file is matched by its stream id (the file - name; awc_opus.py's ``~2.ogg`` for a second stream with the same id gets the same name) and its - bank (the folder path below the Opus folder; if that has no match, the path with its leading folders - removed one at a time, so the Opus folder may hold several archives' outputs). -``--dialogue`` text_tables.py dialogue CSV (wave, key, label, speaker, text_ ...). A named stream whose name is - a dialogue wave gets that line's label, speaker and subtitles. - -Comments written (RFC 7845 section 5.2; empty values are left out): - - TITLE= - LABEL= SPEAKER= - SUBTITLE= - SUBTITLE_= one per language column with text - -Subtitle markup (``~n~``, ``~sl:...~``, ``~COLOR_...~`` and other ``~...~`` tokens) becomes a space. Only the OpusTags -page (page 1, which holds that packet alone) is replaced, so the audio pages are copied byte for byte and the page -sequence numbers do not change. Streams without a name are left untouched, and so is a stream whose id its bank names -twice (counted as ``ambiguous name``): the archive stores only the low 29 bits of a name hash, so two names can claim -one id, and writing either would put another stream's name and, through --dialogue, its subtitle in the file. Running -the tool again replaces the tags it wrote. A tags packet larger than one Ogg page (65,024 bytes) is skipped and counted. -Files with a bad page checksum or truncated page are also skipped and left untouched; all pages are checked before any replacement is written. - -Usage: - python -I opus_tags.py --names names.csv [--dialogue dialogue.csv] [--source LABEL] [--dry-run] - -Standard library only. The CSVs and the tagged files hold game names and text: keep them in your local work folder. -""" -import argparse -import collections -import csv -import os -import re -import struct -import sys - -sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) -from awc_opus import ogg_crc, ogg_page, write_file # noqa: E402 - -VENDOR = b"leonida " -MARKUP = re.compile(r"~[^~]*~") -SPACES = re.compile(r"\s+") -STREAM_FILE = re.compile(r"^([0-9A-Fa-f]{8})(?:~\d+)?\.ogg$") # ~2 ...: a later stream with the same id -MAX_PACKET = 255 * 255 - 1 # lacing values of one page: 254 full segments and a final short one - - -def clean(text: str) -> str: - return SPACES.sub(" ", MARKUP.sub(" ", text)).strip() - - -def tags_packet(comments) -> bytes: - """An OpusTags packet: magic, vendor string, then the comments as KEY=value (RFC 7845 section 5.2).""" - items = [f"{k}={v}".encode("utf-8") for k, v in comments if v] - out = b"OpusTags" + struct.pack(" len(data): - raise ValueError(f"no Ogg page at byte {at}") - segments = data[at + 26] - end = at + 27 + segments + sum(data[at + 27:at + 27 + segments]) - if end > len(data): - raise ValueError(f"page at byte {at} runs past the end of the file") - yield at, end - at = end - - -def checked_pages(data: bytes): - """Validate every page checksum before its bytes are used or copied to the output.""" - for start, end in pages(data): - page = bytearray(data[start:end]) # bounded by one Ogg page, not the whole stream - expected, = struct.unpack_from(" bytes: - """`data` with its OpusTags page replaced; refuse corrupt or truncated input.""" - if len(packet) > MAX_PACKET: - raise ValueError("tags do not fit in one page") - it = checked_pages(data) - try: - _, (tags_at, tags_end) = next(it), next(it) - except StopIteration: - raise ValueError("fewer than two Ogg pages") from None - body = tags_at + 27 + data[tags_at + 26] - if data[body:body + 8] != b"OpusTags": - raise ValueError("page 1 does not start an OpusTags packet") - segments = data[tags_at + 27:tags_at + 27 + data[tags_at + 26]] - if not segments or segments[-1] == 255: - raise ValueError("the OpusTags packet continues past page 1") - if any(segment != 255 for segment in segments[:-1]): - raise ValueError("the OpusTags page contains another packet") - for _ in it: # also check the audio tail before publishing any replacement - pass - serial, seq = struct.unpack_from(" int: - ap = argparse.ArgumentParser(description=__doc__.splitlines()[0]) - ap.add_argument("opus", help="folder written by awc_opus.py") - ap.add_argument("--names", required=True, help="awc_names.py CSV") - ap.add_argument("--dialogue", help="text_tables.py dialogue CSV") - ap.add_argument("--source", help="only use names rows with this source label") - ap.add_argument("--dry-run", action="store_true", help="count what would be tagged; write nothing") - a = ap.parse_args(argv) - for path in [a.opus, a.names] + ([a.dialogue] if a.dialogue else []): - if not os.path.exists(path): - print(f"opus_tags: error: {path}: no such file or folder", file=sys.stderr) - return 2 - if not os.path.isdir(a.opus): - print(f"opus_tags: error: {a.opus}: not a folder", file=sys.stderr) - return 2 - try: - names, ambiguous = load_names(a.names, a.source) - dialogue, langs = load_dialogue(a.dialogue) if a.dialogue else ({}, []) - except (OSError, KeyError, ValueError) as e: - print(f"opus_tags: error: cannot read a CSV: {e}", file=sys.stderr) - return 2 - try: - stats = tag_folder(a.opus, names, dialogue, langs, a.dry_run, ambiguous) - except OSError as e: - print(f"opus_tags: error: {e.filename or e}: {e.strerror or e}", file=sys.stderr) - return 2 - for k, v in stats.items(): - print(f"{k:32} {v:,}") - return 0 - - -if __name__ == "__main__": - try: # a redirected stdout is strict ANSI code page under -I; write '?' for what it cannot encode - sys.stdout.reconfigure(errors="replace") - except (AttributeError, ValueError, OSError): - pass - sys.exit(main()) diff --git a/tools/page_index.py b/tools/page_index.py deleted file mode 100644 index a9b5be3e5..000000000 --- a/tools/page_index.py +++ /dev/null @@ -1,494 +0,0 @@ -"""Index RPF9 `0DRP` page directories without the encrypted table of contents. - -The RPF9 data area is a sequence of zlib streams. A directory stream starts with eight zero bytes, a -`0x50000000`-based self-pointer, `0DRP` at +0x10, version 122 at +0x14, table pointers, and four u16 counts -at +0x48. The fixed header is 0x60 bytes; the first resource payload starts at +0x60. - -The table at +0x38 is the useful one: `u16@0x4c` records of 16 bytes, each `{u32 hash, u32 size, u64 pointer}`. -The pointer is a virtual offset into the logical resource after subtracting 0x50000000, not an archive offset -and not necessarily an offset inside this zlib stream. If the table or a payload crosses the inflated stream -end, the next zlib stream in archive order continues the same resource. This tool concatenates only as many -continuation streams as the declared table and entry ranges require, then reports exact virtual boundaries. - -The header has no key: what earlier reports called a 64-bit key at +0x60 is the first payload byte on -29,297 of 29,298 measured pages. This tool reports `payload_at_0x60` instead. - -The +0x28 table (32-byte records) is reported raw as `q28_records`: the hash in its first u32 matches a +0x38 -hash on most pages, its +0x10 pointer resolves in the resource or is null (`target` null), and its +0x1c word -behaves as flags. The +0x08 and +0x18 words are not decoded and are exported as `field_08` and `count_or_size`. -The +0x30 and +0x40 tables are reported by offset only; their internal layout is not decoded here. - -Each page also carries a `resource`: the directory stream plus the continuations that reach the q38 table and its -last record, their byte total, and the +0x20 count next to the 64 KiB units the group occupies. The count does not -predict the boundary (its best byte reading matches 56.7% of `story000` pages), so the table extent is used and the -mismatch stays visible as `declared_matches_units`. - -Usage: - python -I page_index.py [--start N] [--limit BYTES] [--quiet] - python -I page_index.py [--quiet] - ---start and --limit apply to a single archive only; with a directory they are an error (exit 2). -""" -import argparse -from collections import Counter -import csv -import json -import mmap -import os -import re -import struct -import sys -import zlib - -# -I omits the script directory from sys.path. -sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) -from report_paths import same_report_path # noqa: E402 - -# zlib stream start. Kept in step with rpf9_carve.py. -ZHDR = re.compile(rb"\x78[\x01\x5e\x9c\xda]") -BASE = 0x50000000 -HEADER_SIZE = 0x60 -PAGE_UNIT = 0x10000 # 64 KiB: the unit a resource's declared +0x20 count is compared against -MAX_CONTINUATIONS = 16 -Q28_UNREAD = "q28 table ends past the streams read for q38" -COLUMNS = [ - "page_offset", "stored", "inflated", "version", "page_count", - "q28_count", "q30_count", "q38_count", "span", "complete", - "record_index", "hash", "size", "target", "target_stream", -] - - -def _u16(data, at): - return struct.unpack_from("= at + 2 else None - - -def _u32(data, at): - return struct.unpack_from("= at + 4 else None - - -def _u64(data, at): - return struct.unpack_from("= at + 8 else None - - -def offset_of(value): - """Decode a 0x50000000-based pointer. All measured values are zero-extended 32-bit.""" - if value is None: - return None - if value >> 32 == 0 and BASE <= value < BASE + 0x10000000: - return value - BASE - if value >> 32 == BASE: # tolerate a full-width form of the same base - return value & 0xFFFFFFFF - return None - - -def is_page(data): - return len(data) >= HEADER_SIZE and data[0x10:0x14] == b"0DRP" - - -def scan_rpf(path, start=None, limit=None): - """Yield (archive_offset, stored_bytes, inflated_bytes) for each zlib stream.""" - with open(path, "rb") as fh: - if os.fstat(fh.fileno()).st_size < 8: # no header word; mmap also refuses an empty file - return - m = mmap.mmap(fh.fileno(), 0, access=mmap.ACCESS_READ) - size = len(m) - first = struct.unpack_from(".bin` files, sorted by offset.""" - entries = [] - for name in os.listdir(path): - full = os.path.join(path, name) - if not os.path.isfile(full) or name.lower().endswith((".json", ".csv")): - continue - match = re.match(r"([0-9a-fA-F]{6,})", name) - offset = int(match.group(1), 16) if match else None - entries.append((offset, name, full)) - fallback = 0 - for offset, name, full in sorted(entries, key=lambda e: (e[0] is None, e[0] or 0, e[1])): - if offset is None: - offset = fallback - fallback = max(fallback, offset + 1) - with open(full, "rb") as f: - data = f.read() - yield offset, None, data - - -def _q38(data, q38, count): - """Parse a q38 table from `data`. Returns (records, complete, error).""" - if q38 is None: - return [], True, "q38 is not a 0x50000000 pointer" - if count == 0: - return [], True, "" - if q38 + 16 * count > len(data): - return [], False, "" - records = [] - for i in range(count): - h, size, pointer = struct.unpack_from(" len(data): - return [], False, "" - return records, True, "" - - -def _q28(data, q28, count): - """Parse the +0x28 table raw. Unresolved words keep their measured names. - - A record whose pointer is null is kept with `target` None: its other words are set, and the records after - it are ordinary ones (3,672 such records on 3,511 of 22,823 `anim.rpf` pages). A table that ends past the - streams read for q38 is not read, and says so instead of looking like a page without one. - """ - if not count: - return [], "" - if q28 is None: # none on data.rpf, navmeshes.rpf or anim.rpf; named so declared records cannot go missing - return [], "q28 is not a 0x50000000 pointer" - if q28 + 32 * count > len(data): - return [], Q28_UNREAD - out = [] - for i in range(count): - hash_a, hash_b, field_08, pointer, count_or_size, flags = struct.unpack_from( - "= starts[i]: - stream = i - item = dict(r) - item["target_stream"] = stream - item["spans_streams"] = stream + 1 < len(starts) and r["target"] + r["size"] > starts[stream + 1] - enriched.append(item) - page["q38_records"] = enriched - q28 = page["tables"]["q28"] - page["q28_records"], page["q28_error"] = _q28(data, q28, page["counts"][0] or 0) - return page, True - - -def resource_of(page): - """The streams that make up one logical resource, and how its declared count compares. - - The boundary is the q38 table and its last record: the resource is the directory stream plus the - continuation streams needed to reach them. The +0x20 count is reported next to the 64 KiB units - the group actually occupies, so a caller can see a disagreement instead of trusting the field. - """ - streams = [{"offset": page["offset"], "inflated": page["inflated"]}] - streams += [{"offset": c["offset"], "inflated": c["inflated"]} for c in page["continuations"]] - total = page["inflated"] + sum(c["inflated"] for c in page["continuations"]) - units = max(1, -(-total // PAGE_UNIT)) - declared = page["page_count"] - return { - "streams": streams, - "bytes": total, - "page_units": units, - "declared_pages": declared, - "declared_matches_units": None if declared is None else declared == units, - } - - -def index_streams(streams, progress=None): - """Consume a stream sequence and return page records. At most one page waits for a continuation.""" - pages = [] - waiting = None - streams_seen = 0 - - def add(page): - page["resource"] = resource_of(page) - pages.append(page) - - def start(offset, stored, data): - page, complete = parse_page(data, []) - page["offset"] = offset - page["stored"] = stored - if complete: - add(page) - return None - return (page, data, []) - - for offset, stored, data in streams: - streams_seen += 1 - if progress and streams_seen % 2000 == 0: - progress(streams_seen, len(pages)) - if waiting is not None: - page, base, cont = waiting - cont.append((offset, stored, data)) - page, complete = parse_page(base, cont) - page["offset"] = waiting[0]["offset"] - page["stored"] = waiting[0]["stored"] - if complete: - add(page) - waiting = None - continue - if is_page(data): - # The previous resource ended before its declared table/entries did. Report it, then - # treat this stream as the new directory page instead of swallowing it as a continuation. - # Report the page re-parsed with this stream: waiting[0] is the parse before the last - # continuation was appended and would lose it from the reported continuations/records. - page["complete"] = False - page["error"] = page["error"] or "resource ended before q38 was complete" - add(page) - waiting = start(offset, stored, data) - continue - if len(cont) >= MAX_CONTINUATIONS: - page["complete"] = False - page["error"] = page["error"] or "too many continuation streams" - add(page) - waiting = None - else: - waiting = (page, base, cont) - continue - if is_page(data): - waiting = start(offset, stored, data) - if waiting is not None: - page = waiting[0] - page["complete"] = False - page["error"] = page["error"] or "archive ended before q38 was complete" - add(page) - return pages, streams_seen - - -def summarise(pages, mode, source): - complete = sum(1 for p in pages if p["complete"]) - return { - "mode": mode, - "source": source, - "pages": len(pages), - "complete_pages": complete, - "incomplete_pages": len(pages) - complete, - "q38_records": sum(len(p["q38_records"]) for p in pages), - "q28_records": sum(len(p["q28_records"]) for p in pages), - "q28_declared": sum(p["counts"][0] or 0 for p in pages), - "q28_null_targets": sum(1 for p in pages for r in p["q28_records"] if r["target"] is None), - "q28_tables_unread": sum(1 for p in pages if p.get("q28_error") == Q28_UNREAD), - "pages_with_continuations": sum(1 for p in pages if p["continuations"]), - "span_bytes": sum(p["span"] for p in pages), - "payload_at_0x60": sum(1 for p in pages if p["payload_at_0x60"]), - "resource_streams": {str(n): sum(1 for p in pages if len(p["resource"]["streams"]) == n) - for n in sorted({len(p["resource"]["streams"]) for p in pages})}, - "page_units": sum(p["resource"]["page_units"] for p in pages), - "declared_matches_units": sum(1 for p in pages if p["resource"]["declared_matches_units"]), - "declared_differs_from_units": sum(1 for p in pages - if p["resource"]["declared_matches_units"] is False), - "versions": {str(v): sum(1 for p in pages if p["version"] == v) - for v in sorted({p["version"] for p in pages})}, - "page_counts": {str(v): n for v, n in sorted(Counter( - p["page_count"] for p in pages if p["page_count"] is not None).items())}, - } - - -def write_json(path, pages, summary): - with open(path, "w", encoding="utf-8", newline="\n") as f: - json.dump({"summary": summary, "pages": pages}, f, indent=1) - - -def write_csv(path, pages): - with open(path, "w", newline="", encoding="utf-8") as f: - w = csv.DictWriter(f, fieldnames=COLUMNS, lineterminator="\n") - w.writeheader() - for page in pages: - records = page["q38_records"] - base = { - "page_offset": "0x%x" % page["offset"], - "stored": "" if page["stored"] is None else page["stored"], - "inflated": page["inflated"], - "version": page["version"], - "page_count": page["page_count"], - "q28_count": page["counts"][0], - "q30_count": page["counts"][1], - "q38_count": page["counts"][2], - "span": page["span"], - "complete": int(page["complete"]), - } - if not records: - w.writerow(dict(base, record_index="", hash="", size="", target="", target_stream="")) - continue - for i, r in enumerate(records): - w.writerow(dict(base, record_index=i, hash="0x%08x" % r["hash"], size=r["size"], - target="0x%x" % r["target"], target_stream=r["target_stream"])) - - -def byte_count(text): - """--limit: 0 or less used to scan nothing (negative) or everything (0 is falsy) without a word.""" - try: - value = int(text, 0) - except ValueError: - raise argparse.ArgumentTypeError(f"invalid int value: {text!r}") from None - if value < 1: - raise argparse.ArgumentTypeError("must be at least 1") - return value - - -def offset(text): - """--start: a negative offset would slice the archive from its end.""" - try: - value = int(text, 0) - except ValueError: - raise argparse.ArgumentTypeError(f"invalid int value: {text!r}") from None - if value < 0: - raise argparse.ArgumentTypeError("must be 0 or more") - return value - - -def main(argv=None): - ap = argparse.ArgumentParser(description="Index RPF9 0DRP page directories (read-only, no TOC decryption)") - ap.add_argument("source", help="archive.rpf or a directory of carved .bin files") - ap.add_argument("out", help="output .json or .csv") - ap.add_argument("--start", type=offset, help="first archive offset (default: header u32@4)") - ap.add_argument("--limit", type=byte_count, help="stop after this many bytes") - ap.add_argument("--quiet", action="store_true") - a = ap.parse_args(argv) - if os.path.isdir(a.source) and (a.start is not None or a.limit is not None): - ap.error("--start and --limit apply to a single archive, not a directory") - if os.path.isdir(a.out): - ap.error(f"{a.out} is a folder, not a .json or .csv file") - ext = os.path.splitext(a.out)[1].lower() - if ext not in (".json", ".csv"): # checked before the scan, which can take minutes on a large archive - ap.error("output must end in .json or .csv") - if same_report_path(a.source, a.out): - ap.error("output must not overwrite the source") - if os.path.isdir(a.source): - manifest = os.path.join(a.source, "index.json") - if same_report_path(manifest, a.out): - ap.error(f"output would overwrite the carve manifest: {a.out}") - if os.path.isfile(a.out): - for name in os.listdir(a.source): - inp = os.path.join(a.source, name) - if os.path.isfile(inp) and not name.lower().endswith((".json", ".csv")): - if same_report_path(inp, a.out): - ap.error(f"output would overwrite an input file: {a.out}") - folder = os.path.dirname(os.path.abspath(a.out)) - if not os.path.isdir(folder): - ap.error(f"{folder} is not a folder, so {a.out} cannot be written") - - def progress(n, pages): - print("streams=%d pages=%d" % (n, pages), file=sys.stderr, flush=True) - - if os.path.isdir(a.source): - streams = scan_dir(a.source) - mode = "directory" - elif os.path.isfile(a.source): - streams = scan_rpf(a.source, a.start, a.limit) - mode = "rpf9" - else: - print("not a file or directory: %s" % a.source, file=sys.stderr) - return 2 - try: - pages, streams_seen = index_streams(streams, None if a.quiet else progress) - except (OSError, ValueError) as e: - print("%s: %s" % (a.source, e), file=sys.stderr) - return 2 - summary = summarise(pages, mode, a.source) - summary["streams"] = streams_seen - try: - if ext == ".json": - write_json(a.out, pages, summary) - else: - write_csv(a.out, pages) - except OSError as e: - print(f"{a.out}: {e.strerror or e}", file=sys.stderr) - return 2 - if not a.quiet: - print(json.dumps(summary, indent=1)) - return 0 - - -if __name__ == "__main__": - try: # a redirected stdout is strict ANSI code page under -I; write '?' for what it cannot encode - sys.stdout.reconfigure(errors="replace") - except (AttributeError, ValueError, OSError): - pass - sys.exit(main()) diff --git a/tools/pal_stages.py b/tools/pal_stages.py deleted file mode 100644 index 36ee779b3..000000000 --- a/tools/pal_stages.py +++ /dev/null @@ -1,273 +0,0 @@ -"""Read the PAL stage descriptors that head an FSSM blob. - -An FSSM header carries a table of fixed-size hardware-stage records at offset 0x100. Record k starts -at 0x100 + 0x88 * k and its first qword is - - 0x000000C0_0002_AAHH - - HH byte 0 PAL hardware stage - AA byte 1 API stage - -Measured over all 26,503 blobs of the 1.0.2.1 corpus (the "stage" column is the carve index's, which -the record's API id matches in every case): - - placement 0x100, stride 0x88; the table ends at the first zero or non-tag qword - count 26,308 blobs have one record, 195 have two (all GS: the first is GS, the second its - VS copy at 0x188) - API id 0 vs 2,236, 1 ps 12,101, 2 gs 195, 3 cs 2,689, 6 ms 9,282 - hardware id 3 gs and 4 vs for the 195 GS pairs, 4 vs 2,236, 5 ps 12,101, 6 cs 2,689, 7 the - 9,282 mesh shaders, 2 es in the first XBCH payload of the 195 two-payload VS - containers (their second payload is the 4 vs one) - sentinel 860 blobs (1,055 records: the 195 GS pairs included) fill unused fields with paired - qwords 0xDEADBEEFDEADBEEF; a lone 32-bit 0xDEADBEEF never occurs there. The other - 25,643 records store zeros. Those 860 are the blobs whose 0x120/0x12C/0x130 - section-directory words are 0xDEADBEEF. - -The hardware ids 0 and 1 and the API ids 4 and 5 are not in this corpus. The hardware-stage names -(ls, hs, es, gs, vs, ps, cs, ngg) come from an outside project's description of the id order; only the -numeric correlation with the carve-index stage is measured here. The rest of a record is not decoded. - -Usage: - python -I pal_stages.py [--json] [--limit N] - -A DXBC container is read through `fssm_unpack.unpack_all`, so every tag-0x0D payload is reported (195 -containers have two). `--limit` counts files, not payloads. -""" -import argparse -import json -import os -import struct -import sys -from collections import Counter - -sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) -import fssm_header # noqa: E402 -import fssm_unpack # noqa: E402 - -MAGIC = b"FSSM" -TABLE_OFFSET = 0x100 -RECORD_SIZE = 0x88 -CODE_OFFSET = 0xC0 -TAG_MASK = 0xFFFFFFFFFFFF0000 -TAG = 0x000000C000020000 -SENTINEL32 = 0xDEADBEEF -SENTINEL64 = 0xDEADBEEFDEADBEEF -MAX_RECORDS = 16 - -# Low byte of the tag; 0 and 1 are not in the corpus. -HARDWARE_STAGES = {0: "ls", 1: "hs", 2: "es", 3: "gs", 4: "vs", 5: "ps", 6: "cs", 7: "ngg"} -# Second byte of the tag; 4 and 5 are not in the corpus. -API_STAGES = {0: "vs", 1: "ps", 2: "gs", 3: "cs", 6: "ms"} - - -def _u32(data, offset): - return struct.unpack_from("= CODE_OFFSET + 8: - code_off = _u64(blob, CODE_OFFSET) - if 0 < code_off <= len(blob): - return code_off - return len(blob) - - -def sentinels(record): - """(aligned 64-bit 0xDEADBEEFDEADBEEF pairs, lone 32-bit 0xDEADBEEF words) in one record.""" - pairs = [offset for offset in range(0, len(record) - 7, 8) if _u64(record, offset) == SENTINEL64] - covered = {offset + half for offset in pairs for half in (0, 4)} - words = [offset for offset in range(0, len(record) - 3, 4) if _u32(record, offset) == SENTINEL32] - return len(pairs), sum(1 for offset in words if offset not in covered) - - -def stage_descriptors(blob): - """Return the stage records of an FSSM blob, in table order, as dicts. - - Keys: index, offset, stride, tag, api_id, api_stage, hardware_id, hardware_stage, sentinel_words - (paired 0xDEADBEEFDEADBEEF qwords) and lone_sentinel_words (32-bit 0xDEADBEEF not part of a - pair). An unknown id maps to None. An empty list means the blob lacks the FSSM magic or does not - start with a tag. - """ - if len(blob) < TABLE_OFFSET + 8 or blob[:4] != MAGIC: - return [] - end = min(header_end(blob), len(blob)) - out = [] - for index in range(MAX_RECORDS): - offset = TABLE_OFFSET + RECORD_SIZE * index - if offset + 8 > end: - break - tag = _u64(blob, offset) - if tag == 0 or (tag & TAG_MASK) != TAG: - break - api_id, hardware_id = (tag >> 8) & 0xFF, tag & 0xFF - paired, lone = sentinels(blob[offset:min(offset + RECORD_SIZE, end)]) - out.append({ - "index": index, - "offset": offset, - "stride": RECORD_SIZE, - "tag": tag, - "api_id": api_id, - "api_stage": API_STAGES.get(api_id), - "hardware_id": hardware_id, - "hardware_stage": HARDWARE_STAGES.get(hardware_id), - "sentinel_words": paired, - "lone_sentinel_words": lone, - }) - return out - - -def api_stage(blob): - """API stage name of the blob's first record ("vs", "ps", "gs", "cs", "ms"), or None.""" - records = stage_descriptors(blob) - return records[0]["api_stage"] if records else None - - -def hardware_stage(blob): - """PAL hardware stage name of the blob's first record, or None.""" - records = stage_descriptors(blob) - return records[0]["hardware_stage"] if records else None - - -def files_of(path): - """Files to read: every .fssm, plus a .dxbc whose stem has no .fssm beside it.""" - if os.path.isfile(path): - return [path] - with os.scandir(path) as entries: - names = sorted(entry.path for entry in entries if entry.is_file()) - fssm = [name for name in names if name.endswith(".fssm")] - taken = {os.path.splitext(os.path.basename(name))[0] for name in fssm} - dxbc = [name for name in names - if name.endswith(".dxbc") and os.path.splitext(os.path.basename(name))[0] not in taken] - return sorted(fssm + dxbc) - - -def blob_rows(path, limit=None): - """One row per FSSM blob in a file or folder: a bare FSSM, or every tag-0x0D payload of a container.""" - rows = [] - for full in files_of(path)[:limit]: - name = os.path.basename(full) - try: - with open(full, "rb") as f: - data = f.read() - if data[:4] == MAGIC: - rows.append({"name": name, "payload": "fssm", "blob": data}) - continue - blobs = fssm_unpack.unpack_all(data) - except (OSError, ValueError, struct.error) as e: - rows.append({"name": name, "payload": None, "error": str(e)}) - continue - if not blobs: - rows.append({"name": name, "payload": None, "error": "no tag-0x0D payload"}) - for index, blob in enumerate(blobs): - rows.append({"name": name, "payload": f"xdat{index}", "blob": blob}) - return rows - - -def summarize(row, stage=None): - """Decode one blob_rows() row for the text and JSON output.""" - out = {"name": row["name"], "payload": row["payload"], "stage": stage} - if "blob" not in row: - out["error"] = row["error"] - return out - records = stage_descriptors(row["blob"]) - out["descriptors"] = records - out["api_stage"] = records[0]["api_stage"] if records else None - out["hardware_stage"] = records[0]["hardware_stage"] if records else None - return out - - -def tally(rows): - decoded = [row for row in rows if "descriptors" in row] - records = [record for row in decoded for record in row["descriptors"]] - known = [row for row in decoded if row["stage"] and row["api_stage"]] - sentinel_rows = sum(1 for row in decoded if any(r["sentinel_words"] for r in row["descriptors"])) - return { - "blobs": len(decoded), - "errors": sum(1 for row in rows if "error" in row), - "descriptor_counts": dict(sorted(Counter(len(row["descriptors"]) for row in decoded).items())), - "api_ids": dict(sorted(Counter(r["api_id"] for r in records).items())), - "hardware_ids": dict(sorted(Counter(r["hardware_id"] for r in records).items())), - "sentinel_blobs": sentinel_rows, - "lone_sentinel_words": sum(r["lone_sentinel_words"] for r in records), - "stage_known": len(known), - "stage_matches": sum(1 for row in known if row["stage"] == row["api_stage"]), - } - - -def positive_count(text): - """--limit: a count of files, at least 1. 0 used to select no file at all and report an empty run as - a clean one; a negative one sliced from the end of the folder listing.""" - try: - value = int(text, 0) - except ValueError: - raise argparse.ArgumentTypeError(f"invalid int value: {text!r}") from None - if value < 1: - raise argparse.ArgumentTypeError("must be at least 1") - return value - - -def main(argv=None): - ap = argparse.ArgumentParser(description="Read the PAL stage descriptors in FSSM headers.") - ap.add_argument("path", help="an .fssm file, a DXBC container, or a folder of either") - ap.add_argument("--json", action="store_true", help="print one JSON document instead of lines") - ap.add_argument("--limit", type=positive_count, help="stop after this many files (at least 1)") - args = ap.parse_args(argv) - - if not os.path.exists(args.path): - print(f"ERROR: {args.path} does not exist", file=sys.stderr) - return 2 - try: - rows = blob_rows(args.path, args.limit) - except OSError as e: - print(f"ERROR: cannot list {args.path}: {e.strerror or e}", file=sys.stderr) - return 2 - stages = fssm_header.stage_index(args.path) - decoded = [] - for row in rows: - stem = os.path.splitext(row["name"])[0] - decoded.append(summarize(row, stages.get(stem))) - summary = tally(decoded) - - if args.json: - json.dump({"blobs": decoded, "tally": summary}, sys.stdout, indent=1) - sys.stdout.write("\n") - return 0 - - for row in decoded: - label = f"[{row['payload']}]" if row["payload"] else "" - if "error" in row: - print(f"{row['name']} {label}: ERROR {row['error']}") - continue - print(f"{row['name']} {label}: stage={row['stage'] or '?'} " - f"descriptors={len(row['descriptors'])} stride=0x{RECORD_SIZE:x}") - for record in row["descriptors"]: - lone = f" lone_sentinel={record['lone_sentinel_words']}" if record["lone_sentinel_words"] else "" - print(f" +0x{record['offset']:03x} tag=0x{record['tag']:016x} " - f"api={record['api_id']} ({record['api_stage'] or '?'}) " - f"hw={record['hardware_id']} ({record['hardware_stage'] or '?'}) " - f"sentinel={record['sentinel_words']}{lone}") - total = summary - print(f"{total['blobs']} blobs, errors {total['errors']}, " - f"descriptors per blob {total['descriptor_counts'] or '{}'}") - print("api ids: " + ", ".join(f"{k}:{v}" for k, v in total["api_ids"].items())) - print("hardware ids: " + ", ".join(f"{k}:{v}" for k, v in total["hardware_ids"].items())) - print(f"sentinel blobs {total['sentinel_blobs']}, lone 32-bit sentinel words " - f"{total['lone_sentinel_words']}") - if total["stage_known"]: - print(f"API stage matches the index: {total['stage_matches']}/{total['stage_known']}") - else: - print("(no index.json found: no stage to compare the API id with)") - return 0 - - -if __name__ == "__main__": - try: # a redirected stdout is strict ANSI code page under -I; write '?' for what it cannot encode - sys.stdout.reconfigure(errors="replace") - except (AttributeError, ValueError, OSError): - pass - sys.exit(main()) diff --git a/tools/pe_inspect.py b/tools/pe_inspect.py deleted file mode 100644 index 3369f13ff..000000000 --- a/tools/pe_inspect.py +++ /dev/null @@ -1,569 +0,0 @@ -"""Inspect a PE image (exe or dll) for porting work. - -Usage: - python -I pe_inspect.py [--game-dir DIR] [--out DIR] - -Writes /.json and /.md, where is the image's full file name (game.exe.json, -game.dll.md), so an exe and a dll with the same stem get separate reports. Images with the same file name from -different directories get a numbered suffix (x.exe-2.json), and the name used is printed to stderr. The same file -given twice with the same import search folder is inspected once. Reads the file only; never runs it. - -The report also lists run-time load candidates: DLL names the image holds as ASCII or UTF-16 strings without -importing them, where a LoadLibrary* the import table doesn't show would point (docs/runtime_imports.md). - -Standard library only: the headers, the section table, the import, delay-import, export, TLS and relocation -directories are parsed with struct, so the tool runs under `python -I` without third-party packages and is covered -by the same standard-library-only CI job as the other tools. -""" -from __future__ import annotations - -import argparse -import json -import math -import os -import re -import struct -import sys -from collections import Counter - -SYSTEM32 = os.path.join(os.environ.get("SystemRoot", r"C:\Windows"), "System32") - -MACHINES = {0x8664: "x86-64", 0x14C: "x86", 0xAA64: "ARM64"} -SUBSYSTEMS = {2: "GUI", 3: "Console", 14: "Xbox"} - -DIR_EXPORT = 0 -DIR_IMPORT = 1 -DIR_EXCEPTION = 3 -DIR_BASERELOC = 5 -DIR_TLS = 9 -DIR_DELAY_IMPORT = 13 - -MAX_ENTRIES = 65536 # a table this long is not a table; stops a malformed image from looping forever - - -class PeFormatError(ValueError): - """The file is not a PE image this parser can read.""" - - -def entropy(data: bytes) -> float: - if not data: - return 0.0 - n = len(data) - return -sum(c / n * math.log2(c / n) for c in Counter(data).values()) - - -# An MSVC decorated name can be 4,096 characters (the documented limit of a decorated name); with the 512 this -# was, a long template import became "?" and a DLL with a long name lost its whole entry. -NAME_LIMIT = 4097 - - -def _cstring(data: bytes, offset: int, limit: int = NAME_LIMIT) -> str | None: - end = data.find(b"\0", offset, min(len(data), offset + limit)) - if end < 0: - return None - return data[offset:end].decode(errors="replace") - - -class PeImage: - """The parts of a PE file this tool reports on, read in place from the file bytes.""" - - def __init__(self, data: bytes): - self.data = data - if data[:2] != b"MZ": - raise PeFormatError("no MZ header") - if len(data) < 0x40: - # The MZ signature is there; the file is just too short to carry the MS-DOS header whose dword at - # 0x3c holds e_lfanew. Saying "no MZ header" here would blame a signature that is present. - raise PeFormatError(f"file is {len(data)} bytes, shorter than the 64-byte MS-DOS header") - self.nt = struct.unpack_from(" len(data): - raise PeFormatError(f"file is {len(data)} bytes, too short to hold the PE header at 0x{self.nt:x}") - if data[self.nt:self.nt + 4] != b"PE\0\0": - raise PeFormatError("no PE signature") - (self.machine, self.section_count, self.timestamp, _symbol_table, _symbols, opt_size, - self.characteristics) = struct.unpack_from(" len(data): - raise PeFormatError("truncated optional header") - magic = struct.unpack_from(" len(data): - raise PeFormatError("truncated optional header") - self.is64 = magic == 0x20B - self.entry_rva = struct.unpack_from(" len(data): - raise PeFormatError("truncated section table") - vsize, rva, rawsize, rawptr = struct.unpack_from(" tuple[int, int]: - return self.directories[index] if index < len(self.directories) else (0, 0) - - def _range(self, rva: int) -> tuple[int, int] | None: - """Contiguous file [start, end) backed by headers or the single section holding `rva`.""" - if rva < 0: - return None - if rva < self.size_of_headers: - end = min(self.size_of_headers, len(self.data)) - return (rva, end) if rva < end else None - for s in self.sections: - # A section is VirtualSize bytes in memory (SizeOfRawData when that is 0). File bytes past it are not - # mapped, as in runtime/src/pe_loader.cpp: with SizeOfRawData larger than the span to the next - # section, max(vsize, rawsize) answered the next section's RVAs from this one's raw tail. - span = s["vsize"] or s["rawsize"] - if s["rva"] <= rva < s["rva"] + span: - delta = rva - s["rva"] - mapped = min(s["rawsize"], span) - if delta >= mapped: - return None - at = s["rawptr"] + delta - end = min(s["rawptr"] + mapped, len(self.data)) - return (at, end) if at < end else None - return None - - def offset(self, rva: int, size: int = 1) -> int | None: - """File offset of an RVA span wholly backed by headers or one section.""" - if size <= 0: - return None - bounds = self._range(rva) - if bounds is None: - return None - start, end = bounds - return start if start + size <= end else None - - def section_data(self, section: dict) -> bytes: - at = section["rawptr"] - if at >= len(self.data): - return b"" - return self.data[at:at + min(section["rawsize"], len(self.data) - at)] - - def string_at(self, rva: int) -> str | None: - bounds = self._range(rva) - if bounds is None: - return None - start, end = bounds - return _cstring(self.data, start, min(NAME_LIMIT, end - start)) - - def word(self, at: int) -> int: - return struct.unpack_from(" list[str]: - """Names (or '#ordinal') of one lookup table, which is terminated by a zero entry.""" - ordinal_flag = 1 << (63 if self.is64 else 31) - out = [] - width = 8 if self.is64 else 4 - for i in range(MAX_ENTRIES): - at = self.offset(lookup_rva + i * width, width) - if at is None: - break - value = self.word(at) - if not value: - break - if value & ordinal_flag: - out.append(f"#{value & 0xFFFF}") - continue - name = self.string_at(value + 2) # skip the 2-byte hint - out.append(name if name is not None else "?") - return out - - -def _imports(img: PeImage, kind: str, index: int, delay: bool = False) -> list[dict]: - rva, size = img.directory(index) - if not rva or not size: - return [] - - entries = [] - step = 32 if delay else 20 - for i in range(min(size // step, MAX_ENTRIES)): - base = img.offset(rva + i * step, step) - if base is None: - break - if delay: - (attributes, dll_rva, _handle, iat_rva, int_rva, _bound, _unload, - _stamp) = struct.unpack_from(" 0 else iat_rva - entries.append({"dll": dll, "kind": kind, "functions": img.thunk_names(lookup) if lookup > 0 else []}) - return entries - - -def _exports(img: PeImage) -> list[str]: - rva, size = img.directory(DIR_EXPORT) - if not rva or size < 40: - return [] - at = img.offset(rva, 40) - if at is None: - start = img.offset(rva) - if start is not None and start + 40 > len(img.data): - raise PeFormatError("truncated export directory") - return [] - (_chars, _stamp, _major, _minor, _name, base, functions, name_count, addr_functions, - addr_names, addr_ordinals) = struct.unpack_from(" bool: - if index >= functions: - return False - # A zero RVA marks an unused slot. An RVA inside the export directory is a valid forwarder. - slot = img.offset(addr_functions + index * 4, 4) - return slot is not None and struct.unpack_from(" str: - """The module name the export directory records (its Name field), or "" when there is none.""" - rva, size = img.directory(DIR_EXPORT) - at = img.offset(rva, 40) if rva and size >= 40 else None - if at is None: - return "" - return img.string_at(struct.unpack_from(" int: - rva, size = img.directory(DIR_TLS) - header_size = 40 if img.is64 else 24 - callbacks_end = 32 if img.is64 else 16 - if not rva or size < header_size: - return 0 - at = img.offset(rva, header_size) - if at is None: - start = img.offset(rva) - if start is not None and start + callbacks_end > len(img.data): - raise PeFormatError("truncated TLS directory") - return 0 - callbacks_va = struct.unpack_from(" bool: - """True if this Windows' API-set schema maps the contract to a host DLL (ntdll query; nothing is loaded).""" - if name not in _apiset_cache: - _apiset_cache[name] = _query_apiset(name) - return _apiset_cache[name] - - -def _query_apiset(name: str) -> bool: - if os.name != "nt": - return False - try: - import ctypes - from ctypes import wintypes - - class UNICODE_STRING(ctypes.Structure): - _fields_ = [("Length", wintypes.USHORT), ("MaximumLength", wintypes.USHORT), ("Buffer", wintypes.LPWSTR)] - - query = ctypes.WinDLL("ntdll").ApiSetQueryApiSetPresence - query.argtypes = [ctypes.POINTER(UNICODE_STRING), ctypes.POINTER(ctypes.c_ubyte)] - query.restype = ctypes.c_long - base = name[:-4] if name.lower().endswith(".dll") else name - buf = ctypes.create_unicode_buffer(base) - text = ctypes.cast(buf, wintypes.LPWSTR) - us = UNICODE_STRING(len(base) * 2, (len(base) + 1) * 2, text) - present = ctypes.c_ubyte(0) - status = query(ctypes.byref(us), ctypes.byref(present)) - return status == 0 and bool(present.value) - except (OSError, AttributeError, ValueError): - return False - - -# A DLL file name as an image stores it for LoadLibrary*: ASCII or UTF-16LE, letters, digits, '_', '-' and '.'. -# A UTF-16 name starts after a NUL (or at the start), so the tail of an ASCII string followed by one isn't read as one. -_DLL_ASCII = re.compile(rb"[A-Za-z0-9_][A-Za-z0-9_.\-]{0,63}\.[dD][lL][lL](?![A-Za-z0-9_])") -_DLL_WIDE = re.compile(rb"(? list[dict]: - """DLL names the image holds as strings but doesn't import: candidates for a run-time LoadLibrary*, which the - import table doesn't show (XCurl.dll and libHttpClient.GDK.dll reach xgameruntime.dll only this way, - docs/runtime_imports.md). `imported` is the lower-cased names from the import tables; the image's own names - (its file name and the name in its export directory) are left out too. Each entry is {"name", "encoding": - "ascii" | "utf-16" | "both"}, sorted by name. A string is not proof of a load, only of where to look.""" - seen: dict[str, set[str]] = {} - for m in _DLL_ASCII.finditer(data): - seen.setdefault(m.group().decode("ascii").lower(), set()).add("ascii") - for m in _DLL_WIDE.finditer(data): - seen.setdefault(m.group().decode("utf-16-le").lower(), set()).add("utf-16") - own = (own_name,) if isinstance(own_name, str) else own_name - skip = imported | {n.lower() for n in own if n} - return [{"name": n, "encoding": "both" if len(e) == 2 else next(iter(e))} - for n, e in sorted(seen.items()) if n not in skip] - - -def classify_dll(name: str, game_dir: str | None) -> str: - """bundled = ships beside the game, system = present on this Windows, shim = must be reimplemented.""" - if game_dir and os.path.isfile(os.path.join(game_dir, name)): - return "bundled" - low = name.lower() - if low.startswith("api-ms-win-") or low.startswith("ext-ms-win-"): - # API sets resolve through the OS schema: ask this Windows whether it knows the contract. - return "system" if _apiset_resolves(name) else "shim" - if os.path.isfile(os.path.join(SYSTEM32, name)): - return "system" - return "shim" - - -def inspect(path: str, game_dir: str | None) -> dict: - """The report for one image. A file cut off inside a table raises PeFormatError like any other bad image; - the struct.error it used to raise escaped main() and stopped a multi-file run at that file.""" - try: - return _inspect(path, game_dir) - except struct.error as e: - raise PeFormatError(f"truncated or corrupt table: {e}") from None - - -def _inspect(path: str, game_dir: str | None) -> dict: - with open(path, "rb") as f: - img = PeImage(f.read()) - sections = [] - for s in img.sections: - data = img.section_data(s) - e = entropy(data) - sections.append({ - "name": s["name"], - "rva": s["rva"], "vsize": s["vsize"], "rawsize": s["rawsize"], - "exec": s["exec"], - "write": s["write"], - "entropy": round(e, 3), - "looks_encrypted": e > 7.9 and len(data) > 4096, - }) - - imports = _imports(img, "normal", DIR_IMPORT) + _imports(img, "delay", DIR_DELAY_IMPORT, delay=True) - for entry in imports: - entry["where"] = classify_dll(entry["dll"], game_dir) - - exports = _exports(img) - own_names = (os.path.basename(path), _export_module_name(img)) - loads = dll_strings(img.data, {i["dll"].lower() for i in imports}, own_names) - for entry in loads: - entry["where"] = classify_dll(entry["name"], game_dir) - pdata_rva, pdata_size = img.directory(DIR_EXCEPTION) - reloc_rva, reloc_size = img.directory(DIR_BASERELOC) - - return { - "file": os.path.basename(path), - "size": os.path.getsize(path), - "machine": MACHINES.get(img.machine, hex(img.machine)), - "timestamp": img.timestamp, - "is_dll": bool(img.characteristics & 0x2000), - "subsystem": SUBSYSTEMS.get(img.subsystem, img.subsystem), - "image_base": hex(img.image_base), - "size_of_image": img.size_of_image, - "entry_rva": hex(img.entry_rva), - "has_relocs": bool(reloc_rva and reloc_size), - "dynamic_base": bool(img.dll_characteristics & 0x40), - "sections": sections, - "imports": imports, - "export_count": len(exports), - "exports": exports, - "pdata_functions": pdata_size // 12 if pdata_rva and pdata_size >= 12 else 0, - "tls_callbacks": _tls_callbacks(img), - "runtime_load_candidates": loads, - } - - -def to_markdown(r: dict) -> str: - out = [f"# {r['file']}", "", - f"- {r['machine']}, {'DLL' if r['is_dll'] else 'EXE'}, subsystem {r['subsystem']}, {r['size']:,} bytes", - f"- image base {r['image_base']}, size {r['size_of_image']:,}, entry RVA {r['entry_rva']}", - f"- relocations: {'yes' if r['has_relocs'] else 'NO (must load at preferred base)'}; " - f"ASLR flag: {r['dynamic_base']}", - f"- .pdata functions: {r['pdata_functions']:,}; TLS callbacks: {r['tls_callbacks']}; exports: {r['export_count']}", - "", "## Sections", "", "| name | rva | vsize | exec | write | entropy | |", "|---|---|---|---|---|---|---|"] - for s in r["sections"]: - flag = "**encrypted?**" if s["looks_encrypted"] else "" - out.append(f"| {s['name']} | {s['rva']:#x} | {s['vsize']:,} | {s['exec']} | {s['write']} | {s['entropy']} | {flag} |") - out += ["", "## Imports", ""] - by_where = Counter() - for imp in r["imports"]: - by_where[imp["where"]] += len(imp["functions"]) - out.append(", ".join(f"{k}: {v}" for k, v in sorted(by_where.items())) or "none") - out += ["", "| dll | kind | resolves | functions |", "|---|---|---|---|"] - for imp in sorted(r["imports"], key=lambda i: (i["where"] != "shim", i["dll"].lower())): - out.append(f"| {imp['dll']} | {imp['kind']} | {imp['where']} | {len(imp['functions'])} |") - loads = r.get("runtime_load_candidates", []) - if loads: - out += ["", "## Run-time load candidates", "", - "DLL names held as strings but not imported: a `LoadLibrary*` the import table doesn't show " - "(a string is where to look, not proof of a load).", "", - "| dll | encoding | resolves |", "|---|---|---|"] - out += [f"| {d['name']} | {d['encoding']} | {d['where']} |" for d in loads] - shims = [i for i in r["imports"] if i["where"] == "shim"] - if shims: - out += ["", "## Needs checking or a shim", ""] - for imp in shims: - out.append(f"### {imp['dll']} ({imp['where']})") - out.append("") - out.append(", ".join(f"`{f}`" for f in imp["functions"])) - out.append("") - return "\n".join(out) + "\n" - - -def same_output_path(first: str, second: str) -> bool: - """True when writing ``second`` would truncate ``first`` (same file, path or hard link).""" - if os.path.normcase(os.path.realpath(first)) == os.path.normcase(os.path.realpath(second)): - return True - try: - return os.path.samefile(first, second) - except OSError: - return False - - -def main(argv: list[str] | None = None) -> int: - ap = argparse.ArgumentParser() - ap.add_argument("image", nargs="+") - ap.add_argument("--game-dir") - ap.add_argument("--out", default=os.path.join(os.path.dirname(__file__), "..", "reports", "pe")) - a = ap.parse_args(argv) - missing = [img for img in a.image if not os.path.exists(img)] - if missing: - for img in missing: - print(f"ERROR: {img}: does not exist", file=sys.stderr) - return 2 - if os.path.isfile(a.out): - print(f"cannot create output directory {a.out}: path is a file, not a directory", file=sys.stderr) - return 1 - try: - os.makedirs(a.out, exist_ok=True) - except OSError as e: - print(f"cannot create output directory {a.out}: {e.strerror or e}", file=sys.stderr) - return 1 - rc = 0 - seen_paths: set[tuple[str, str]] = set() - used_names: set[str] = set() - for img in a.image: - search_dir = a.game_dir or os.path.dirname(os.path.abspath(img)) - key = (os.path.normcase(os.path.realpath(img)), os.path.normcase(os.path.abspath(search_dir))) - if key in seen_paths: - print(f"{img}: given more than once; inspected once", file=sys.stderr) - continue - seen_paths.add(key) - try: - r = inspect(img, search_dir) - except (PeFormatError, OSError) as e: - print(f"{img}: not a PE image ({e})", file=sys.stderr) - rc = 1 - continue - # One report per image: the full file name keeps game.exe and game.dll apart, and a numbered suffix keeps - # a/x.exe and b/x.exe apart. Compared case-insensitively, as Windows file names are. - name = r["file"] - n = 1 - while name.lower() in used_names: - n += 1 - name = f"{r['file']}-{n}" - used_names.add(name.lower()) - if n > 1: - print(f"{img}: another input is also named {r['file']}; report written as {name}.json/.md", - file=sys.stderr) - stem = os.path.join(a.out, name) - json_path = stem + ".json" - md_path = stem + ".md" - collision = None - for other in a.image: - if same_output_path(other, json_path): - collision = json_path - break - if same_output_path(other, md_path): - collision = md_path - break - if collision: - print(f"{img}: report {collision} would overwrite input file", file=sys.stderr) - rc = 1 - continue - try: - with open(json_path, "w", encoding="utf-8", newline="\n") as f: - json.dump(r, f, indent=1) - with open(md_path, "w", encoding="utf-8", newline="\n") as f: - f.write(to_markdown(r)) - except OSError as e: - print(f"{img}: cannot write report ({e.strerror or e})", file=sys.stderr) - rc = 1 - continue - enc = [s["name"] for s in r["sections"] if s["looks_encrypted"]] - shim = sum(len(i["functions"]) for i in r["imports"] if i["where"] == "shim") - print(f"{r['file']:<40} {r['machine']:<7} subsys={r['subsystem']!s:<7} pdata={r['pdata_functions']:<7} " - f"shim-imports={shim:<5} encrypted={','.join(enc) or '-'}") - return rc - - -if __name__ == "__main__": - try: # a redirected stdout is strict ANSI code page under -I; write '?' for what it cannot encode - sys.stdout.reconfigure(errors="replace") - except (AttributeError, ValueError, OSError): - pass - sys.exit(main()) diff --git a/tools/pe_shader_containers.py b/tools/pe_shader_containers.py deleted file mode 100644 index ed03e1495..000000000 --- a/tools/pe_shader_containers.py +++ /dev/null @@ -1,329 +0,0 @@ -"""Inventory the DXBC shader containers embedded in a PE image, outside `shaders.rpf`. - -The package ships shader programs in two places: the game's own containers inside `shaders.rpf`, which -`tools/shader_carve.py` recovers, and containers embedded in DLLs. This tool scans any binary for the latter, -validates each container's chunk table, reads the `ILDN` module name, and reports what each container carries: - -* `has_xbch`: the `DXIL` chunk's `XDAT` tag 0x0d starts with `XBCH`. This is the console program: - `tools/fssm_unpack.py` decompresses it to `FSSM` and the game's RDNA2 pipeline (disasm + `rdna2spirv.py`) - translates it, exactly like a shader from `shaders.rpf`. `docs/embedded_shaders.md` has the measurement. -* `has_fspx`: the `ACCC` chunk starts with `FSPX`. That is the FidelityFX AOT compute program, a different - format (`tools/fspx_unpack.py`, `docs/fspx.md`). -* `has_bitcode`: the `DXIL` chunk contains an LLVM bitcode magic (`BC C0 DE`). Some containers carry both the - bitcode and the console `XBCH` record; the console runtime uses the latter. - -Usage: - python -I pe_shader_containers.py [ ...] [--json FILE] [--extract DIR] [--verbose] - -`--json` writes the per-container records (offset, size, sha256, chunk list, name, stage, flags). `--extract` writes -each container as `.dxbc` plus an `index.json` whose entries the translator reads (with `stage` from -`PSV0`, defaulting to `"cs"` when absent), so the next step can be `fssm_unpack.py `: nothing is extracted unless asked for, and extracted shaders are game -data that must stay in the user's work folder, never in the repository. Nothing here prints shader bytes. - -Standard library only; reads files, never runs them. -""" - -from __future__ import annotations - -import argparse -import hashlib -import json -import os -import re -import struct -import sys - -# -I keeps the script directory off sys.path, so add it explicitly before importing the sibling module. -sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) -from report_paths import same_report_path # noqa: E402 - -DXBC = b"DXBC" -XDAT = b"XDAT" -XBCH = b"XBCH" -FSPX = b"FSPX" -BITCODE = b"BC\xc0\xde" -MAX_CHUNKS = 64 # a container with more chunks is not one this parser accepts -NAME_LIMIT = 4096 # longer than any ILDN path seen; stops a malformed length from reading the image -SAFE_NAME = re.compile(r"[^A-Za-z0-9_.-]+") - - -class ContainerError(ValueError): - """The bytes at this offset do not form a DXBC container this parser accepts.""" - - -def u32(data: bytes, offset: int) -> int: - return struct.unpack_from(" len(data): - raise ContainerError("truncated header") - total, count = u32(data, offset + 24), u32(data, offset + 28) - if not 32 < total <= len(data) - offset: - raise ContainerError(f"total size {total} does not fit the image") - if not 0 < count <= MAX_CHUNKS: - raise ContainerError(f"implausible chunk count {count}") - table_end = 32 + 4 * count - if table_end > total: - raise ContainerError("chunk table past the container") - chunks = [] - for k in range(count): - start = u32(data, offset + 32 + 4 * k) - if not table_end <= start <= total - 8: - raise ContainerError(f"chunk {k} offset {start} outside the container") - fourcc = data[offset + start : offset + start + 4] - size = u32(data, offset + start + 4) - if start + 8 + size > total: - raise ContainerError(f"chunk {k} payload past the container") - if start % 4: - raise ContainerError(f"chunk {k} offset {start} not 4-byte aligned") - if not all(0x20 <= b < 0x7F for b in fourcc): - raise ContainerError(f"chunk {k} fourcc is not printable") - chunks.append((fourcc, start, size)) - starts = [start for _, start, _ in chunks] - if starts != sorted(starts) or len(set(starts)) != len(starts): - raise ContainerError("chunk table is not sorted and unique") - if not chunks or max(start + 8 + size for _, start, size in chunks) != total: - raise ContainerError("the last chunk does not end at the container size") - return total, chunks - - -def chunk_payload(data: bytes, offset: int, chunk) -> bytes: - _, start, size = chunk - return data[offset + start + 8 : offset + start + 8 + size] - - -def module_name(ildn: bytes) -> str | None: - """The module name in an `ILDN` part: `00 00 `; basename without `.pdb`.""" - if len(ildn) < 4: - return None - length = struct.unpack_from(" str | None: - """Return the shader stage from a `PSV0` chunk payload, or None if short/unknown.""" - if len(psv0) < 29: - return None - info_size = u32(psv0, 0) - if info_size < 25 or 4 + 24 >= len(psv0): - return None - return PSV0_STAGES.get(psv0[4 + 24]) - - -def xdat_tags(dxil: bytes) -> list[dict]: - """The XDAT entries of a `DXIL` part, as {tag, size, magic} with the first four payload bytes as ASCII.""" - start = dxil.find(XDAT) - if start < 0 or start + 12 > len(dxil): - return [] - count, _header = struct.unpack_from(" 256: - return [] - out = [] - for k in range(count): - at = start + 12 + 12 * k - if at + 12 > len(dxil): - break - tag, offset, size = struct.unpack_from(" len(dxil): - continue - magic = dxil[offset : offset + 4] - out.append( - { - "tag": tag, - "size": size, - "magic": magic.decode("latin-1") - if all(0x20 <= b < 0x7F for b in magic) - else "", - } - ) - return out - - -def inspect(data: bytes, image: str) -> tuple[list[dict], list[int]]: - """Every valid container in `data`, and the offsets of `DXBC` hits that failed validation.""" - found, rejected = [], [] - i = 0 - while True: - i = data.find(DXBC, i) - if i < 0: - break - try: - total, chunks = parse_container(data, i) - except ContainerError: - rejected.append(i) - i += 4 - continue - parts = {fourcc: (start, size) for fourcc, start, size in chunks} - dialect = b"" - if b"DXIL" in parts: - dialect = chunk_payload(data, i, (b"DXIL",) + parts[b"DXIL"]) - elif b"ACCC" in parts: - dialect = chunk_payload(data, i, (b"ACCC",) + parts[b"ACCC"]) - tags = xdat_tags(dialect) if b"DXIL" in parts else [] - stage = ( - psv0_stage(chunk_payload(data, i, (b"PSV0",) + parts[b"PSV0"])) - if b"PSV0" in parts - else None - ) - record = { - "image": image, - "offset": i, - "size": total, - "sha256": hashlib.sha256(data[i : i + total]).hexdigest(), - "name": module_name(chunk_payload(data, i, (b"ILDN",) + parts[b"ILDN"])) - if b"ILDN" in parts - else None, - "stage": stage, - "chunks": [ - {"fourcc": fourcc.decode("latin-1"), "size": size} - for fourcc, _, size in chunks - ], - "xdat_tags": tags, - "has_xbch": any(t["tag"] == 0x0D and t["magic"] == "XBCH" for t in tags), - "has_fspx": (b"ACCC" in parts and dialect[:4] == FSPX), - "has_bitcode": BITCODE in dialect, - } - found.append(record) - i += total - return found, rejected - - -def safe_stem(name: str | None, index: int) -> str: - stem = SAFE_NAME.sub("_", name or "").strip("._") - return stem or f"container_{index:02d}" - - -def extract(data: bytes, records: list[dict], directory: str) -> list[dict]: - """Write each container as `.dxbc`; return the translator's index entries.""" - os.makedirs(directory, exist_ok=True) - index = [] - for k, record in enumerate(records): - stem = safe_stem(record["name"], k) - file = f"{stem}.dxbc" - target = os.path.join(directory, file) - n = k - while True: - try: - with open(target, "xb") as f: - f.write(data[record["offset"] : record["offset"] + record["size"]]) - break - except FileExistsError: - file = f"{stem}_{n:02d}.dxbc" - target = os.path.join(directory, file) - n += 1 - index.append({"name": stem, "file": file, "stage": record.get("stage") or "cs"}) - return index - - -def main(argv=None) -> int: - ap = argparse.ArgumentParser( - description="Inventory the DXBC shader containers embedded in PE images." - ) - ap.add_argument("images", nargs="+", help="PE image(s) to scan") - ap.add_argument("--json", help="write the per-container records here") - ap.add_argument( - "--extract", - metavar="DIR", - help="write each container as .dxbc plus index.json (game data: keep it out of the repo)", - ) - ap.add_argument( - "--verbose", action="store_true", help="print one line per container" - ) - a = ap.parse_args(argv) - - if a.extract and os.path.exists(a.extract) and not os.path.isdir(a.extract): - ap.error(f"--extract {a.extract} is not a folder") - if a.extract: - index_path = os.path.join(a.extract, "index.json") - for image in a.images: - if same_report_path(index_path, image): - ap.error(f"--extract index {index_path} would overwrite the input image {image}") - if a.json: - if os.path.isdir(a.json): - ap.error(f"--json {a.json} is a folder, not a file") - for image in a.images: - if same_report_path(a.json, image): - ap.error(f"--json {a.json} would overwrite the input image {image}") - if a.extract and same_report_path(a.json, index_path): - ap.error(f"--json {a.json} would overwrite the extract index") - - all_records, status, index = [], 0, [] - for image in a.images: - try: - with open(image, "rb") as f: - data = f.read() - except OSError as e: - print(f"ERROR: cannot read {image}: {e.strerror or e}", file=sys.stderr) - status = 2 - continue - records, rejected = inspect(data, image) - all_records.extend(records) - print( - f"{image}: {len(records)} container(s), {len(rejected)} rejected DXBC hit(s)" - ) - if a.verbose: - for r in records: - name = r["name"] or "?" - flags = "".join( - c - for c, on in ( - ("X", r["has_xbch"]), - ("F", r["has_fspx"]), - ("B", r["has_bitcode"]), - ) - if on - ) - chunks = ",".join(c["fourcc"] for c in r["chunks"]) - print( - f" {r['offset']:#x} {r['size']:>7} {flags:<3} {name:<28} {chunks}" - ) - if a.extract: - try: - index.extend(extract(data, records, a.extract)) - except OSError as e: - print(f"ERROR: cannot write {a.extract}: {e}", file=sys.stderr) - return 2 - - if a.extract: - try: - with open(index_path, "w", encoding="utf-8", newline="\n") as f: - json.dump(index, f, indent=0) - except OSError as e: - print(f"ERROR: cannot write {index_path}: {e}", file=sys.stderr) - return 2 - print(f" extracted {len(index)} file(s) to {a.extract}") - print(" these are game data: do not commit them", file=sys.stderr) - - if a.json: - try: - os.makedirs(os.path.dirname(os.path.abspath(a.json)), exist_ok=True) - with open(a.json, "w", encoding="utf-8", newline="\n") as f: - json.dump(all_records, f, indent=1) - except OSError as e: - print(f"ERROR: cannot write {a.json}: {e}", file=sys.stderr) - return 2 - print(f"wrote {a.json}") - return status - - -if __name__ == "__main__": - try: # a redirected stdout is strict ANSI code page under -I; write '?' for what it cannot encode - sys.stdout.reconfigure(errors="replace") - except (AttributeError, ValueError, OSError): - pass - sys.exit(main()) diff --git a/tools/ped_assemble.py b/tools/ped_assemble.py deleted file mode 100644 index 4e8a240ef..000000000 --- a/tools/ped_assemble.py +++ /dev/null @@ -1,2457 +0,0 @@ -"""Modular ped body assembler, standing-space aligner, and coplanar seam stitcher. - -Usage: - python -I tools/ped_assemble.py assemble -o [options] - python -I tools/ped_assemble.py cull-overlap --target --ref [options] - python -I tools/ped_assemble.py inspect-seams [options] - -Pure standard-library Python (`python -I`, no numpy or Pillow). Implements the -three geometric assembly steps required to combine RAGE 9 modular ped parts -(`head`, `eyes`, `teeth`, `hand_*_nude_cull`, `feet_*_nude_cull`, -`bodynipplesgen_*`, `bodygenitalsgen_*`, and garments) into a watertight -binary glTF 2.0 (`.glb`): - -1. **Standing-space alignment:** Human modular drawables store root-relative - bind positions anchored at ``SKEL_ROOT = (0, 0, +1.0 m)`` in RAGE Z-up - (``(0, +1.0 m, 0)`` in glTF Y-up). Applying the standing-space transform - places feet on the ground plane and aligns all slots without per-part - offset tables. -2. **Coplanar triangle overlap culling (``_nude_cull`` stitching):** - ``hand_*_nude_cull`` (upper body) and ``feet_*_nude_cull`` (lower body) - share an intentional ~13.9 cm coplanar waist overlap band (258 triangles), - and ``hand_fr1_000_nude_cull`` / ``feet_fr1_000_nude_cull`` carry coplanar - backing triangles behind ``bodynipplesgen_fr1_*`` (26 triangles) and - ``bodygenitalsgen_fr1_*`` (64 triangles). Culling coplanar overlapping - triangles via quantized vertex/triangle key matching plus spatial-hashed - centroid/plane/normal checks eliminates Z-fighting while keeping the - assembled seam watertight. -3. **Multi-part glTF 2.0 (`.glb`) export:** Merges decoded parts (positions, - normals, UVs, optional vertex colors, optional 4- or 8-influence skinning - ``JOINTS_0``/``WEIGHTS_0``/``JOINTS_1``/``WEIGHTS_1``, optional skeleton - hierarchy with inverse bind matrices, and PBR material/texture slots) into - a strict binary glTF 2.0 container. - -Supports JSON mesh/manifest specs, Wavefront OBJ (via ``tools/glb_writer.py``), -and binary glTF 2.0 (``.glb``) inputs, including sparse mesh attributes and indices. -A GLB may expand up to 1,000,000 implicit zero-initialized accessor rows across its -imported mesh instances. For larger parts, supply a dense base bufferView. -Standard library only; no game files. -""" -from __future__ import annotations - -import argparse -import base64 -import json -import math -import os -import re -import struct -import sys -from collections import defaultdict -from dataclasses import dataclass, field -from typing import Iterable - -TOOLS_DIR = os.path.dirname(os.path.abspath(__file__)) -if TOOLS_DIR not in sys.path: - sys.path.insert(0, TOOLS_DIR) - -import glb_writer # noqa: E402 - -GLB_MAGIC = b"glTF" -GLB_VERSION = 2 -MAX_IMPLICIT_ACCESSOR_ROWS = 1_000_000 -CHUNK_TYPE_JSON = 0x4E4F534A -CHUNK_TYPE_BIN = 0x004E4942 -TARGET_ARRAY_BUFFER = 34962 -TARGET_ELEMENT_ARRAY_BUFFER = 34963 - -COMPONENT_BYTE = 5120 -COMPONENT_UNSIGNED_BYTE = 5121 -COMPONENT_SHORT = 5122 -COMPONENT_UNSIGNED_SHORT = 5123 -COMPONENT_UNSIGNED_INT = 5125 -COMPONENT_FLOAT = 5126 - -COMPONENT_STRUCT = { - COMPONENT_BYTE: ("b", 1), - COMPONENT_UNSIGNED_BYTE: ("B", 1), - COMPONENT_SHORT: ("h", 2), - COMPONENT_UNSIGNED_SHORT: ("H", 2), - COMPONENT_UNSIGNED_INT: ("I", 4), - COMPONENT_FLOAT: ("f", 4), -} - -TYPE_COMPONENTS = { - "SCALAR": 1, - "VEC2": 2, - "VEC3": 3, - "VEC4": 4, - "MAT2": 4, - "MAT3": 9, - "MAT4": 16, -} - -# Standing-space offset between RAGE bind-space (SKEL_ROOT at origin, feet ~ -1.0 m) -# and standing-space (feet at ground plane, SKEL_ROOT at +1.0 m). -DEFAULT_STANDING_OFFSET_M = 1.0 - -# Measured coplanar culling tolerances (meters) for RAGE 9 modular ped parts: -# - hand_*_nude_cull vs feet_*_nude_cull waist overlap: 258 triangles (<1.5 mm separation) -# - hand_fr1_000_nude_cull vs bodynipplesgen_fr1_*: 26 triangles -# - feet_fr1_000_nude_cull vs bodygenitalsgen_fr1_*: 64 triangles -DEFAULT_WAIST_CENTROID_TOL = 0.004 -DEFAULT_NIPPLE_CENTROID_TOL = 0.0025 -DEFAULT_GENITAL_CENTROID_TOL = 0.0016 -DEFAULT_VERTEX_QUANT_TOL = 1e-4 -DEFAULT_NORMAL_COS_MIN = 0.85 -DEFAULT_WELD_TOL = 1e-4 - -ROLE_UPPER_BODY = "upper_body" -ROLE_LOWER_BODY = "lower_body" -ROLE_NIPPLES = "nipples" -ROLE_GENITALS_FEMALE = "genitals_female" -ROLE_GENITALS_MALE = "genitals_male" -ROLE_HEAD = "head" -ROLE_EYES = "eyes" -ROLE_EYECAP = "eyecap" -ROLE_TEETH = "teeth" -ROLE_CLOTHING = "clothing" -ROLE_OTHER = "other" - -_RE_UPPER_NUDE = re.compile(r"(?:^|[/\\])(?:hand_[a-z0-9]+_000_nude_cull|uppr(?:_|$))", re.I) -_RE_LOWER_NUDE = re.compile(r"(?:^|[/\\])(?:feet_[a-z0-9]+_000_nude_cull|lowr(?:_|$))", re.I) -_RE_NIPPLES = re.compile(r"bodynipplesgen_", re.I) -_RE_GENITALS_FR = re.compile(r"bodygenitalsgen_f[a-z0-9]+_", re.I) -_RE_GENITALS_MR = re.compile(r"bodygenitalsgen_m[a-z0-9]+_", re.I) -_RE_EYECAP = re.compile(r"(?:^|_)eyecap(?:$|_)", re.I) -_RE_EYES = re.compile(r"(?:^|_)eyes(?:$|_)", re.I) -_RE_TEETH = re.compile(r"(?:^|_)teeth", re.I) -_RE_HEAD = re.compile(r"(?:^|_)head(?:$|_)", re.I) - - -class PedAssembleError(ValueError): - """Raised when a modular ped input, seam spec, or GLB container is invalid.""" - - -@dataclass -class MaterialSpec: - """PBR material definition for an assembled ped part.""" - - name: str = "default" - base_color_factor: tuple[float, float, float, float] = (0.8, 0.8, 0.8, 1.0) - metallic_factor: float = 0.0 - roughness_factor: float = 0.85 - alpha_mode: str = "OPAQUE" - alpha_cutoff: float | None = None - double_sided: bool = False - base_color_png: bytes | None = None - normal_png: bytes | None = None - metallic_roughness_png: bytes | None = None - - -@dataclass -class MeshPart: - """Decoded modular body part geometry in a single coordinate space.""" - - name: str - positions: list[tuple[float, float, float]] - triangles: list[tuple[int, int, int]] - role: str = "" - coord_space: str = "z-up" - translation: tuple[float, float, float] = (0.0, 0.0, 0.0) - normals: list[tuple[float, float, float]] | None = None - uvs: list[tuple[float, float]] | None = None - uvs_extra: dict[int, list[tuple[float, float]]] = field(default_factory=dict) - colors: list[tuple[float, float, float, float]] | None = None - joints_0: list[tuple[int, int, int, int]] | None = None - weights_0: list[tuple[float, float, float, float]] | None = None - joints_1: list[tuple[int, int, int, int]] | None = None - weights_1: list[tuple[float, float, float, float]] | None = None - joint_names: list[str] | None = None - material: MaterialSpec | None = None - - def __post_init__(self) -> None: - if not self.role: - self.role = classify_part_role(self.name) - if self.coord_space not in ("z-up", "y-up"): - raise PedAssembleError(f"{self.name}: coord_space must be 'z-up' or 'y-up'") - - -@dataclass -class SkeletonJoint: - """Single joint in an optional ped skeleton hierarchy.""" - - name: str - parent: int = -1 - translation: tuple[float, float, float] = (0.0, 0.0, 0.0) - rotation: tuple[float, float, float, float] = (0.0, 0.0, 0.0, 1.0) - scale: tuple[float, float, float] = (1.0, 1.0, 1.0) - # 16 column-major floats in glTF Y-up (or RAGE Z-up if skeleton.coord_space == "z-up") - inverse_bind_matrix: tuple[float, ...] | None = None - - -@dataclass -class SkeletonSpec: - """Optional skeleton definition attached to an assembled GLB.""" - - name: str - joints: list[SkeletonJoint] - coord_space: str = "z-up" - standing_offset: float | None = None - - -# --------------------------------------------------------------------------- math & coords - -def rage_to_yup_vec3(v: tuple[float, float, float]) -> tuple[float, float, float]: - """Convert RAGE Z-up ``(x, y, z)`` to glTF Y-up ``(x, z, -y)``.""" - return (float(v[0]), float(v[2]), float(-v[1])) - - -def yup_to_rage_vec3(v: tuple[float, float, float]) -> tuple[float, float, float]: - """Convert glTF Y-up ``(x, y, z)`` to RAGE Z-up ``(x, -z, y)``.""" - return (float(v[0]), float(-v[2]), float(v[1])) - - -def rage_to_yup_quat(q: tuple[float, float, float, float]) -> tuple[float, float, float, float]: - """Convert a RAGE Z-up quaternion ``(x, y, z, w)`` to glTF Y-up.""" - x, y, z, w = float(q[0]), float(q[1]), float(q[2]), float(q[3]) - nx, ny, nz, nw = x, z, -y, w - norm = math.sqrt(nx * nx + ny * ny + nz * nz + nw * nw) - if norm <= 1e-12: - return (0.0, 0.0, 0.0, 1.0) - return (nx / norm, ny / norm, nz / norm, nw / norm) - - -def rage_to_yup_mat4_col(col: Iterable[float]) -> tuple[float, ...]: - """Convert a 4x4 column-major matrix from RAGE Z-up to glTF Y-up via ``C * M * C^T``.""" - vals = [float(x) for x in col] - if len(vals) != 16: - raise PedAssembleError(f"Expected 16 floats for MAT4, got {len(vals)}") - # Convert column-major to row-major 4x4 - m = [[vals[c * 4 + r] for c in range(4)] for r in range(4)] - # Basis change C: (x, y, z, 1) -> (x, z, -y, 1) - c_mat = ( - (1.0, 0.0, 0.0, 0.0), - (0.0, 0.0, 1.0, 0.0), - (0.0, -1.0, 0.0, 0.0), - (0.0, 0.0, 0.0, 1.0), - ) - # cm = C * M - cm = [ - [sum(c_mat[r][k] * m[k][col_i] for k in range(4)) for col_i in range(4)] - for r in range(4) - ] - # out = (C * M) * C^T - out = [ - [sum(cm[r][k] * c_mat[col_i][k] for k in range(4)) for col_i in range(4)] - for r in range(4) - ] - return tuple(out[r][col_i] for col_i in range(4) for r in range(4)) - - -def _vec_sub(a: tuple[float, float, float], b: tuple[float, float, float]) -> tuple[float, float, float]: - return (a[0] - b[0], a[1] - b[1], a[2] - b[2]) - - -def _vec_add(a: tuple[float, float, float], b: tuple[float, float, float]) -> tuple[float, float, float]: - return (a[0] + b[0], a[1] + b[1], a[2] + b[2]) - - -def _vec_dot(a: tuple[float, float, float], b: tuple[float, float, float]) -> float: - return a[0] * b[0] + a[1] * b[1] + a[2] * b[2] - - -def _vec_cross(a: tuple[float, float, float], b: tuple[float, float, float]) -> tuple[float, float, float]: - return ( - a[1] * b[2] - a[2] * b[1], - a[2] * b[0] - a[0] * b[2], - a[0] * b[1] - a[1] * b[0], - ) - - -def _vec_len(v: tuple[float, float, float]) -> float: - return math.sqrt(v[0] * v[0] + v[1] * v[1] + v[2] * v[2]) - - -def _vec_norm(v: tuple[float, float, float]) -> tuple[float, float, float] | None: - length = _vec_len(v) - if length <= 1e-12: - return None - inv = 1.0 / length - return (v[0] * inv, v[1] * inv, v[2] * inv) - - -def _identity_mat4_col() -> tuple[float, ...]: - return ( - 1.0, 0.0, 0.0, 0.0, - 0.0, 1.0, 0.0, 0.0, - 0.0, 0.0, 1.0, 0.0, - 0.0, 0.0, 0.0, 1.0, - ) - - -def classify_part_role(name: str) -> str: - """Infer the modular ped slot role from a drawable or part name.""" - base = os.path.splitext(os.path.basename(name))[0].strip().lower() - if _RE_UPPER_NUDE.search(base): - return ROLE_UPPER_BODY - if _RE_LOWER_NUDE.search(base): - return ROLE_LOWER_BODY - if _RE_NIPPLES.search(base): - return ROLE_NIPPLES - if _RE_GENITALS_FR.search(base): - return ROLE_GENITALS_FEMALE - if _RE_GENITALS_MR.search(base): - return ROLE_GENITALS_MALE - if _RE_EYECAP.search(base): - return ROLE_EYECAP - if _RE_EYES.search(base): - return ROLE_EYES - if _RE_TEETH.search(base): - return ROLE_TEETH - if _RE_HEAD.search(base): - return ROLE_HEAD - if any(tok in base for tok in ("hand_", "torso", "upper", "bodyupper")): - return ROLE_UPPER_BODY - if any(tok in base for tok in ("feet_", "pelvis", "lower", "bodylower")): - return ROLE_LOWER_BODY - if any(tok in base for tok in ("nipple",)): - return ROLE_NIPPLES - if any(tok in base for tok in ("genital",)): - return ROLE_GENITALS_FEMALE if ("fr1" in base or "female" in base) else ROLE_GENITALS_MALE - if any(tok in base for tok in ("shirt", "jacket", "pants", "shorts", "shoes", "hoodie", "bra", "undies", "dress")): - return ROLE_CLOTHING - return ROLE_OTHER - - -# --------------------------------------------------------------------------- standing space - -def standing_offset_vector(offset_m: float = DEFAULT_STANDING_OFFSET_M, coord_space: str = "z-up") -> tuple[float, float, float]: - """Return the vertical ``SKEL_ROOT`` standing-space offset vector in the requested space.""" - if coord_space == "z-up": - return (0.0, 0.0, float(offset_m)) - if coord_space == "y-up": - return (0.0, float(offset_m), 0.0) - raise PedAssembleError(f"Unsupported coord_space {coord_space!r}; expected 'z-up' or 'y-up'") - - -def is_bind_space_biped( - positions: Iterable[tuple[float, float, float]], - *, - coord_space: str = "z-up", - threshold: float = -0.4, -) -> bool: - """Return True when the lowest vertical coordinate sits below ``threshold`` (bind space, feet ~ -1.0 m).""" - axis = 2 if coord_space == "z-up" else 1 - min_v = None - for p in positions: - v = p[axis] - if min_v is None or v < min_v: - min_v = v - return min_v is not None and min_v < threshold - - -def apply_standing_offset( - positions: list[tuple[float, float, float]], - *, - offset_m: float = DEFAULT_STANDING_OFFSET_M, - coord_space: str = "z-up", -) -> list[tuple[float, float, float]]: - """Translate ``positions`` by the vertical ``SKEL_ROOT`` standing offset.""" - ox, oy, oz = standing_offset_vector(offset_m, coord_space) - return [(p[0] + ox, p[1] + oy, p[2] + oz) for p in positions] - - -def align_part_to_standing_space( - part: MeshPart, - *, - standing_offset: float = DEFAULT_STANDING_OFFSET_M, - target_space: str = "y-up", - apply_offset: bool = True, -) -> MeshPart: - """Return a copy of ``part`` aligned into standing space and converted to ``target_space``. - - Applies any part-local ``translation`` first, then applies ``+standing_offset`` - along the part's vertical axis when ``apply_offset`` is True, and finally - converts coordinates and normals from ``part.coord_space`` to ``target_space``. - """ - if target_space not in ("z-up", "y-up"): - raise PedAssembleError(f"Unsupported target_space {target_space!r}") - tx, ty, tz = part.translation - ox, oy, oz = standing_offset_vector(standing_offset, part.coord_space) if apply_offset else (0.0, 0.0, 0.0) - shifted = [(p[0] + tx + ox, p[1] + ty + oy, p[2] + tz + oz) for p in part.positions] - normals = list(part.normals) if part.normals is not None else None - - if part.coord_space != target_space: - convert = rage_to_yup_vec3 if target_space == "y-up" else yup_to_rage_vec3 - shifted = [convert(p) for p in shifted] - if normals is not None: - normals = [convert(n) for n in normals] - - return MeshPart( - name=part.name, - positions=shifted, - triangles=list(part.triangles), - role=part.role, - coord_space=target_space, - translation=(0.0, 0.0, 0.0), - normals=normals, - uvs=list(part.uvs) if part.uvs is not None else None, - uvs_extra={k: list(v) for k, v in part.uvs_extra.items()}, - colors=list(part.colors) if part.colors is not None else None, - joints_0=list(part.joints_0) if part.joints_0 is not None else None, - weights_0=list(part.weights_0) if part.weights_0 is not None else None, - joints_1=list(part.joints_1) if part.joints_1 is not None else None, - weights_1=list(part.weights_1) if part.weights_1 is not None else None, - joint_names=list(part.joint_names) if part.joint_names is not None else None, - material=part.material, - ) - - -# --------------------------------------------------------------------------- overlap culling & seams - -def _quantize_point(p: tuple[float, float, float], tol: float) -> tuple[int, int, int]: - inv = 1.0 / max(tol, 1e-12) - return (int(round(p[0] * inv)), int(round(p[1] * inv)), int(round(p[2] * inv))) - - -def _canonical_tri_key( - p0: tuple[float, float, float], - p1: tuple[float, float, float], - p2: tuple[float, float, float], - tol: float, -) -> tuple[tuple[int, int, int], tuple[int, int, int], tuple[int, int, int]]: - q0 = _quantize_point(p0, tol) - q1 = _quantize_point(p1, tol) - q2 = _quantize_point(p2, tol) - a, b, c = sorted((q0, q1, q2)) - return (a, b, c) - - -def _triangle_geometry( - positions: list[tuple[float, float, float]], - tri: tuple[int, int, int], - offset: tuple[float, float, float] = (0.0, 0.0, 0.0), -) -> tuple[ - tuple[float, float, float], - tuple[float, float, float], - tuple[float, float, float], - tuple[float, float, float], - tuple[float, float, float] | None, -]: - ox, oy, oz = offset - a = positions[tri[0]] - b = positions[tri[1]] - c = positions[tri[2]] - p0 = (a[0] + ox, a[1] + oy, a[2] + oz) - p1 = (b[0] + ox, b[1] + oy, b[2] + oz) - p2 = (c[0] + ox, c[1] + oy, c[2] + oz) - centroid = ((p0[0] + p1[0] + p2[0]) / 3.0, (p0[1] + p1[1] + p2[1]) / 3.0, (p0[2] + p1[2] + p2[2]) / 3.0) - normal = _vec_norm(_vec_cross(_vec_sub(p1, p0), _vec_sub(p2, p0))) - return p0, p1, p2, centroid, normal - - -def _cell_of(p: tuple[float, float, float], cell_size: float) -> tuple[int, int, int]: - inv = 1.0 / max(cell_size, 1e-9) - return (math.floor(p[0] * inv), math.floor(p[1] * inv), math.floor(p[2] * inv)) - - -def find_coplanar_overlap_indices( - target: MeshPart, - ref_parts: list[MeshPart], - *, - centroid_tol: float = DEFAULT_WAIST_CENTROID_TOL, - plane_tol: float | None = None, - normal_cos_min: float = DEFAULT_NORMAL_COS_MIN, - vertex_tol: float = DEFAULT_VERTEX_QUANT_TOL, -) -> tuple[set[int], dict]: - """Identify triangle indices in ``target`` that coplanarly overlap any triangle in ``ref_parts``. - - Combines two checks: - 1. Canonical quantized vertex-set triangle key matching (``vertex_tol``), - catching exact 1:1 shared triangles regardless of vertex index order. - 2. Spatial-hashed centroid + plane distance + normal alignment checks - (``centroid_tol``, ``plane_tol``, ``normal_cos_min``), catching slightly - offset coplanar overlap strips (e.g. ``hand_*_nude_cull`` vs - ``feet_*_nude_cull`` / ``bodynipplesgen_*`` / ``bodygenitalsgen_fr1_*``) - while preserving nearby non-coplanar geometry. - """ - if not target.triangles or not ref_parts: - return set(), { - "target": target.name, - "target_triangles_before": len(target.triangles), - "culled_exact_key": 0, - "culled_coplanar_proximity": 0, - "culled_total": 0, - "target_triangles_after": len(target.triangles), - } - - eff_plane_tol = float(centroid_tol if plane_tol is None else plane_tol) - cell_size = max(float(centroid_tol), 1e-4) - ctol_sq = float(centroid_tol) * float(centroid_tol) - - ref_exact_keys: dict[tuple[tuple[int, int, int], tuple[int, int, int], tuple[int, int, int]], list[tuple[float, float, float] | None]] = defaultdict(list) - grid: dict[tuple[int, int, int], list[tuple[tuple[float, float, float], tuple[float, float, float] | None]]] = defaultdict(list) - - for ref in ref_parts: - if ref.coord_space != target.coord_space: - raise PedAssembleError( - f"Coordinate space mismatch: target {target.name!r} is {target.coord_space} " - f"but ref {ref.name!r} is {ref.coord_space}" - ) - for tri in ref.triangles: - p0, p1, p2, cent, norm = _triangle_geometry(ref.positions, tri, ref.translation) - key = _canonical_tri_key(p0, p1, p2, vertex_tol) - ref_exact_keys[key].append(norm) - grid[_cell_of(cent, cell_size)].append((cent, norm)) - - culled: set[int] = set() - exact_hits = 0 - proximity_hits = 0 - - for ti, tri in enumerate(target.triangles): - p0, p1, p2, cent, norm = _triangle_geometry(target.positions, tri, target.translation) - - # Tier 1: exact canonical quantized vertex key match - key = _canonical_tri_key(p0, p1, p2, vertex_tol) - if key in ref_exact_keys: - matched_exact = False - if normal_cos_min <= 0.0 or norm is None: - matched_exact = True - else: - for rn in ref_exact_keys[key]: - if rn is None or abs(_vec_dot(norm, rn)) >= normal_cos_min: - matched_exact = True - break - if matched_exact: - culled.add(ti) - exact_hits += 1 - continue - - # Tier 2: 3D spatial hash neighbor search for coplanar centroid/plane/normal overlap - cx, cy, cz = _cell_of(cent, cell_size) - hit = False - for dx in (-1, 0, 1): - if hit: - break - for dy in (-1, 0, 1): - if hit: - break - for dz in (-1, 0, 1): - bucket = grid.get((cx + dx, cy + dy, cz + dz)) - if not bucket: - continue - for rcent, rnorm in bucket: - ddx = cent[0] - rcent[0] - ddy = cent[1] - rcent[1] - ddz = cent[2] - rcent[2] - if ddx * ddx + ddy * ddy + ddz * ddz > ctol_sq: - continue - if normal_cos_min > 0.0 and norm is not None and rnorm is not None: - if abs(_vec_dot(norm, rnorm)) < normal_cos_min: - continue - if rnorm is not None: - # Both centroid and all 3 vertices must lie near the reference triangle plane - # to reject skewed non-coplanar faces whose centroid happens to cross the plane. - plane_d = abs(ddx * rnorm[0] + ddy * rnorm[1] + ddz * rnorm[2]) - if plane_d > eff_plane_tol: - continue - v_plane_limit = max(eff_plane_tol * 1.5, eff_plane_tol + 1e-4) - if ( - abs(_vec_dot(_vec_sub(p0, rcent), rnorm)) > v_plane_limit - or abs(_vec_dot(_vec_sub(p1, rcent), rnorm)) > v_plane_limit - or abs(_vec_dot(_vec_sub(p2, rcent), rnorm)) > v_plane_limit - ): - continue - hit = True - break - if hit: - break - if hit: - culled.add(ti) - proximity_hits += 1 - - stats = { - "target": target.name, - "target_triangles_before": len(target.triangles), - "culled_exact_key": exact_hits, - "culled_coplanar_proximity": proximity_hits, - "culled_total": len(culled), - "target_triangles_after": len(target.triangles) - len(culled), - } - return culled, stats - - -def cull_part_overlap( - target: MeshPart, - ref_parts: list[MeshPart], - *, - centroid_tol: float = DEFAULT_WAIST_CENTROID_TOL, - plane_tol: float | None = None, - normal_cos_min: float = DEFAULT_NORMAL_COS_MIN, - vertex_tol: float = DEFAULT_VERTEX_QUANT_TOL, - compact_vertices: bool = False, -) -> tuple[MeshPart, dict]: - """Return a copy of ``target`` with coplanar triangles overlapping ``ref_parts`` removed.""" - culled_idx, stats = find_coplanar_overlap_indices( - target, - ref_parts, - centroid_tol=centroid_tol, - plane_tol=plane_tol, - normal_cos_min=normal_cos_min, - vertex_tol=vertex_tol, - ) - kept_tris = [t for i, t in enumerate(target.triangles) if i not in culled_idx] - out = MeshPart( - name=target.name, - positions=list(target.positions), - triangles=kept_tris, - role=target.role, - coord_space=target.coord_space, - translation=target.translation, - normals=list(target.normals) if target.normals is not None else None, - uvs=list(target.uvs) if target.uvs is not None else None, - uvs_extra={k: list(v) for k, v in target.uvs_extra.items()}, - colors=list(target.colors) if target.colors is not None else None, - joints_0=list(target.joints_0) if target.joints_0 is not None else None, - weights_0=list(target.weights_0) if target.weights_0 is not None else None, - joints_1=list(target.joints_1) if target.joints_1 is not None else None, - weights_1=list(target.weights_1) if target.weights_1 is not None else None, - joint_names=list(target.joint_names) if target.joint_names is not None else None, - material=target.material, - ) - if compact_vertices: - out = compact_part_vertices(out) - return out, stats - - -def compact_part_vertices(part: MeshPart) -> MeshPart: - """Drop vertices no longer referenced by any triangle and remap triangle indices.""" - used: dict[int, int] = {} - order: list[int] = [] - new_tris: list[tuple[int, int, int]] = [] - for a, b, c in part.triangles: - remapped = [] - for idx in (a, b, c): - ni = used.get(idx) - if ni is None: - ni = len(order) - used[idx] = ni - order.append(idx) - remapped.append(ni) - new_tris.append((remapped[0], remapped[1], remapped[2])) - - def _remap(seq): - return [seq[i] for i in order] if seq is not None else None - - return MeshPart( - name=part.name, - positions=[part.positions[i] for i in order], - triangles=new_tris, - role=part.role, - coord_space=part.coord_space, - translation=part.translation, - normals=_remap(part.normals), - uvs=_remap(part.uvs), - uvs_extra={k: [v[i] for i in order] for k, v in part.uvs_extra.items()}, - colors=_remap(part.colors), - joints_0=_remap(part.joints_0), - weights_0=_remap(part.weights_0), - joints_1=_remap(part.joints_1), - weights_1=_remap(part.weights_1), - joint_names=list(part.joint_names) if part.joint_names is not None else None, - material=part.material, - ) - - -def apply_standard_ped_culling( - parts: list[MeshPart], - *, - waist_tol: float = DEFAULT_WAIST_CENTROID_TOL, - nipple_tol: float = DEFAULT_NIPPLE_CENTROID_TOL, - genital_tol: float = DEFAULT_GENITAL_CENTROID_TOL, - plane_tol: float | None = None, - normal_cos_min: float = DEFAULT_NORMAL_COS_MIN, - vertex_tol: float = DEFAULT_VERTEX_QUANT_TOL, - compact_vertices: bool = False, -) -> tuple[list[MeshPart], list[dict]]: - """Apply the RAGE 9 modular ped coplanar overlap culling passes across ``parts``. - - Passes match the measured ``_nude_cull`` overlap hierarchy: - 1. Upper body (``hand_*_nude_cull`` / ``uppr``) culled against lower body - (``feet_*_nude_cull`` / ``lowr``) using ``waist_tol`` (default 4.0 mm). - 2. Upper body culled against female nipple patches (``bodynipplesgen_*``) - using ``nipple_tol`` (default 2.5 mm). - 3. Lower body culled against female genital patches (``bodygenitalsgen_fr1_*``) - using ``genital_tol`` (default 1.6 mm). - """ - lower_parts = [p for p in parts if p.role == ROLE_LOWER_BODY] - nipple_parts = [p for p in parts if p.role == ROLE_NIPPLES] - fr_genital_parts = [p for p in parts if p.role == ROLE_GENITALS_FEMALE] - - out_parts: list[MeshPart] = [] - reports: list[dict] = [] - - for part in parts: - cur = part - if part.role == ROLE_UPPER_BODY: - if lower_parts: - cur, st = cull_part_overlap( - cur, - lower_parts, - centroid_tol=waist_tol, - plane_tol=plane_tol, - normal_cos_min=normal_cos_min, - vertex_tol=vertex_tol, - ) - st["pass"] = "upper_vs_lower_waist" - reports.append(st) - if nipple_parts: - cur, st = cull_part_overlap( - cur, - nipple_parts, - centroid_tol=nipple_tol, - plane_tol=plane_tol, - normal_cos_min=normal_cos_min, - vertex_tol=vertex_tol, - ) - st["pass"] = "upper_vs_nipples" - reports.append(st) - if compact_vertices and cur is not part: - cur = compact_part_vertices(cur) - elif part.role == ROLE_LOWER_BODY: - if fr_genital_parts: - cur, st = cull_part_overlap( - cur, - fr_genital_parts, - centroid_tol=genital_tol, - plane_tol=plane_tol, - normal_cos_min=normal_cos_min, - vertex_tol=vertex_tol, - ) - st["pass"] = "lower_vs_female_genitals" - reports.append(st) - if compact_vertices: - cur = compact_part_vertices(cur) - out_parts.append(cur) - - return out_parts, reports - - -def count_mesh_islands( - positions: list[tuple[float, float, float]], - triangles: list[tuple[int, int, int]], - *, - by_position: bool = False, - quant_tol: float = DEFAULT_WELD_TOL, -) -> dict: - """Count disconnected triangle islands (connected components) in a mesh. - - With ``by_position=False`` (default), connectivity follows shared vertex - indices, matching RAGE 9 physical ``_nude_cull`` island splits (e.g. - 449 / 290 / 257 / 264 islands). With ``by_position=True``, vertices within - ``quant_tol`` are welded before computing components. - """ - n_tris = len(triangles) - if n_tris == 0: - return {"island_count": 0, "largest_island_triangles": 0, "smallest_island_triangles": 0} - - parent = list(range(n_tris)) - - def _find(x: int) -> int: - while parent[x] != x: - parent[x] = parent[parent[x]] - x = parent[x] - return x - - def _union(a: int, b: int) -> None: - ra, rb = _find(a), _find(b) - if ra != rb: - parent[rb] = ra - - vert_owner: dict[object, int] = {} - for ti, tri in enumerate(triangles): - for vi in tri: - key: object = _quantize_point(positions[vi], quant_tol) if by_position else vi - first = vert_owner.get(key) - if first is None: - vert_owner[key] = ti - else: - _union(first, ti) - - sizes: dict[int, int] = defaultdict(int) - for ti in range(n_tris): - sizes[_find(ti)] += 1 - counts = sorted(sizes.values(), reverse=True) - return { - "island_count": len(counts), - "largest_island_triangles": counts[0], - "smallest_island_triangles": counts[-1], - } - - -def analyze_edge_topology( - parts: list[MeshPart], - *, - weld_tol: float = DEFAULT_WELD_TOL, -) -> dict: - """Analyze welded edge manifoldness across one or more parts. - - Returns counts of total unique welded edges, boundary edges (incident to - 1 triangle), manifold interior edges (incident to 2 triangles), and - non-manifold edges (incident to >2 triangles — typically caused by - double-drawn coplanar overlap bands). Triangles with fewer than three - distinct welded corners are counted separately; they no longer form faces. - """ - edge_counts: dict[tuple[tuple[int, int, int], tuple[int, int, int]], int] = defaultdict(int) - collapsed = 0 - for part in parts: - ox, oy, oz = part.translation - qpts = [ - _quantize_point((p[0] + ox, p[1] + oy, p[2] + oz), weld_tol) - for p in part.positions - ] - for a, b, c in part.triangles: - qa, qb, qc = qpts[a], qpts[b], qpts[c] - if qa == qb or qb == qc or qc == qa: - collapsed += 1 - continue - for u, v in ((qa, qb), (qb, qc), (qc, qa)): - edge = (u, v) if u < v else (v, u) - edge_counts[edge] += 1 - - boundary = 0 - manifold = 0 - non_manifold = 0 - for cnt in edge_counts.values(): - if cnt == 1: - boundary += 1 - elif cnt == 2: - manifold += 1 - else: - non_manifold += 1 - - return { - "unique_edges": len(edge_counts), - "boundary_edges": boundary, - "manifold_edges": manifold, - "non_manifold_edges": non_manifold, - "collapsed_triangles": collapsed, - } - - -def inspect_seams( - parts: list[MeshPart], - *, - weld_tol: float = DEFAULT_WELD_TOL, - overlap_tol: float = DEFAULT_WAIST_CENTROID_TOL, - plane_tol: float | None = None, - normal_cos_min: float = DEFAULT_NORMAL_COS_MIN, -) -> dict: - """Inspect islands, bounding boxes, welded edge topology, and pairwise overlaps.""" - part_summaries = [] - for p in parts: - ox, oy, oz = p.translation - if p.positions: - xs = [v[0] + ox for v in p.positions] - ys = [v[1] + oy for v in p.positions] - zs = [v[2] + oz for v in p.positions] - bounds = [[min(xs), min(ys), min(zs)], [max(xs), max(ys), max(zs)]] - else: - bounds = None - islands = count_mesh_islands(p.positions, p.triangles, by_position=False) - welded_islands = count_mesh_islands(p.positions, p.triangles, by_position=True, quant_tol=weld_tol) - part_summaries.append({ - "name": p.name, - "role": p.role, - "coord_space": p.coord_space, - "vertices": len(p.positions), - "triangles": len(p.triangles), - "physical_islands": islands["island_count"], - "welded_islands": welded_islands["island_count"], - "bounds": bounds, - }) - - pairwise_overlaps = [] - for i in range(len(parts)): - for j in range(i + 1, len(parts)): - culled_ij, st = find_coplanar_overlap_indices( - parts[i], - [parts[j]], - centroid_tol=overlap_tol, - plane_tol=plane_tol, - normal_cos_min=normal_cos_min, - ) - if culled_ij: - pairwise_overlaps.append({ - "part_a": parts[i].name, - "part_b": parts[j].name, - "overlapping_triangles_in_a": len(culled_ij), - "exact_key_hits": st["culled_exact_key"], - "proximity_hits": st["culled_coplanar_proximity"], - }) - - topology = analyze_edge_topology(parts, weld_tol=weld_tol) - return { - "part_count": len(parts), - "parts": part_summaries, - "combined_topology": topology, - "pairwise_overlaps": pairwise_overlaps, - } - - -# --------------------------------------------------------------------------- I/O (JSON, OBJ, GLB) - -def _read_png_spec(val: object, base_dir: str) -> bytes | None: - if val is None: - return None - if isinstance(val, (bytes, bytearray)): - return bytes(val) - if isinstance(val, str): - if val.startswith("base64:"): - return base64.b64decode(val[len("base64:"):]) - path = val if os.path.isabs(val) else os.path.join(base_dir, val) - with open(path, "rb") as f: - return f.read() - raise PedAssembleError(f"Unsupported PNG texture spec: {type(val).__name__}") - - -def _parse_material_dict(raw: dict | None, base_dir: str) -> MaterialSpec | None: - if raw is None: - return None - if not isinstance(raw, dict): - raise PedAssembleError("material must be a JSON object") - bcf = raw.get("base_color_factor", raw.get("baseColorFactor", (0.8, 0.8, 0.8, 1.0))) - if len(bcf) == 3: - bcf = (float(bcf[0]), float(bcf[1]), float(bcf[2]), 1.0) - elif len(bcf) == 4: - bcf = (float(bcf[0]), float(bcf[1]), float(bcf[2]), float(bcf[3])) - else: - raise PedAssembleError("base_color_factor must have 3 or 4 floats") - return MaterialSpec( - name=str(raw.get("name", "material")), - base_color_factor=bcf, - metallic_factor=float(raw.get("metallic_factor", raw.get("metallicFactor", 0.0))), - roughness_factor=float(raw.get("roughness_factor", raw.get("roughnessFactor", 0.85))), - alpha_mode=str(raw.get("alpha_mode", raw.get("alphaMode", "OPAQUE"))).upper(), - alpha_cutoff=float(raw["alpha_cutoff"]) if "alpha_cutoff" in raw and raw["alpha_cutoff"] is not None else None, - double_sided=bool(raw.get("double_sided", raw.get("doubleSided", False))), - base_color_png=_read_png_spec(raw.get("base_color_png", raw.get("baseColorPng")), base_dir), - normal_png=_read_png_spec(raw.get("normal_png", raw.get("normalPng")), base_dir), - metallic_roughness_png=_read_png_spec(raw.get("metallic_roughness_png", raw.get("metallicRoughnessPng")), base_dir), - ) - - -def _normalize_triangles(raw_indices: list) -> list[tuple[int, int, int]]: - if not raw_indices: - return [] - first = raw_indices[0] - if isinstance(first, (list, tuple)): - return [(int(t[0]), int(t[1]), int(t[2])) for t in raw_indices] - if len(raw_indices) % 3 != 0: - raise PedAssembleError(f"Flat index array length {len(raw_indices)} is not a multiple of 3") - return [ - (int(raw_indices[i]), int(raw_indices[i + 1]), int(raw_indices[i + 2])) - for i in range(0, len(raw_indices), 3) - ] - - -def _parse_joint_names(raw: object, *, part_name: str) -> list[str] | None: - if raw is None: - return None - if not isinstance(raw, list): - raise PedAssembleError(f"{part_name}: joint_names must be a list of strings") - out: list[str] = [] - for idx, item in enumerate(raw): - if item is None: - out.append("") - elif isinstance(item, str): - out.append(item) - else: - raise PedAssembleError( - f"{part_name}: joint_names[{idx}] must be a string or null, got {type(item).__name__}" - ) - return out - - -def _part_from_dict(raw: dict, *, default_name: str, default_space: str, base_dir: str) -> MeshPart: - name = str(raw.get("name", default_name)) - positions = [(float(p[0]), float(p[1]), float(p[2])) for p in raw.get("positions", [])] - triangles = _normalize_triangles(raw.get("triangles", raw.get("indices", []))) - normals = [(float(n[0]), float(n[1]), float(n[2])) for n in raw["normals"]] if raw.get("normals") else None - uvs = [(float(u[0]), float(u[1])) for u in raw["uvs"]] if raw.get("uvs") else None - raw_extra = raw.get("uvs_extra", {}) - if not isinstance(raw_extra, dict) or any( - re.fullmatch(r"[1-9][0-9]{0,8}", str(key)) is None for key in raw_extra - ): - raise PedAssembleError(f"{name}: uvs_extra keys must be positive texture coordinate set indices") - uvs_extra = { - int(key): [(float(u[0]), float(u[1])) for u in values] - for key, values in raw_extra.items() - } - colors = None - if raw.get("colors"): - colors = [ - (float(c[0]), float(c[1]), float(c[2]), float(c[3]) if len(c) > 3 else 1.0) - for c in raw["colors"] - ] - joints_0 = [tuple(int(x) for x in j) for j in raw["joints_0"]] if raw.get("joints_0") else None - weights_0 = [tuple(float(x) for x in w) for w in raw["weights_0"]] if raw.get("weights_0") else None - joints_1 = [tuple(int(x) for x in j) for j in raw["joints_1"]] if raw.get("joints_1") else None - weights_1 = [tuple(float(x) for x in w) for w in raw["weights_1"]] if raw.get("weights_1") else None - joint_names = _parse_joint_names(raw.get("joint_names", raw.get("jointNames")), part_name=name) - trans = raw.get("translation", (0.0, 0.0, 0.0)) - return MeshPart( - name=name, - positions=positions, - triangles=triangles, - role=str(raw.get("role", "")), - coord_space=str(raw.get("coord_space", default_space)), - translation=(float(trans[0]), float(trans[1]), float(trans[2])), - normals=normals, - uvs=uvs, - uvs_extra=uvs_extra, - colors=colors, - joints_0=joints_0, - weights_0=weights_0, - joints_1=joints_1, - weights_1=weights_1, - joint_names=joint_names, - material=_parse_material_dict(raw.get("material"), base_dir), - ) - - -def _skeleton_from_dict(raw: dict | None, default_space: str) -> SkeletonSpec | None: - if raw is None: - return None - joints = [] - for j in raw.get("joints", []): - t = j.get("translation", (0.0, 0.0, 0.0)) - r = j.get("rotation", (0.0, 0.0, 0.0, 1.0)) - s = j.get("scale", (1.0, 1.0, 1.0)) - ibm = j.get("inverse_bind_matrix", j.get("inverseBindMatrix")) - joints.append(SkeletonJoint( - name=str(j["name"]), - parent=int(j.get("parent", -1)), - translation=(float(t[0]), float(t[1]), float(t[2])), - rotation=(float(r[0]), float(r[1]), float(r[2]), float(r[3])), - scale=(float(s[0]), float(s[1]), float(s[2])), - inverse_bind_matrix=tuple(float(x) for x in ibm) if ibm is not None else None, - )) - return SkeletonSpec( - name=str(raw.get("name", "ped_skeleton")), - joints=joints, - coord_space=str(raw.get("coord_space", default_space)), - standing_offset=float(raw["standing_offset"]) if "standing_offset" in raw and raw["standing_offset"] is not None else None, - ) - - -def part_to_dict(part: MeshPart) -> dict: - """Serialize a ``MeshPart`` to a JSON-compatible dict.""" - out: dict = { - "name": part.name, - "role": part.role, - "coord_space": part.coord_space, - "translation": list(part.translation), - "positions": [list(p) for p in part.positions], - "triangles": [list(t) for t in part.triangles], - } - if part.normals is not None: - out["normals"] = [list(n) for n in part.normals] - if part.uvs is not None: - out["uvs"] = [list(u) for u in part.uvs] - if part.uvs_extra: - out["uvs_extra"] = {str(key): [list(u) for u in values] - for key, values in sorted(part.uvs_extra.items())} - if part.colors is not None: - out["colors"] = [list(c) for c in part.colors] - if part.joints_0 is not None: - out["joints_0"] = [list(j) for j in part.joints_0] - if part.weights_0 is not None: - out["weights_0"] = [list(w) for w in part.weights_0] - if part.joints_1 is not None: - out["joints_1"] = [list(j) for j in part.joints_1] - if part.weights_1 is not None: - out["weights_1"] = [list(w) for w in part.weights_1] - if part.joint_names is not None: - out["joint_names"] = list(part.joint_names) - if part.material is not None: - mat: dict = { - "name": part.material.name, - "base_color_factor": list(part.material.base_color_factor), - "metallic_factor": part.material.metallic_factor, - "roughness_factor": part.material.roughness_factor, - "alpha_mode": part.material.alpha_mode, - "double_sided": part.material.double_sided, - } - if part.material.alpha_cutoff is not None: - mat["alpha_cutoff"] = part.material.alpha_cutoff - for slot in ("base_color_png", "normal_png", "metallic_roughness_png"): - payload = getattr(part.material, slot) - if payload is not None: - mat[slot] = "base64:" + base64.b64encode(payload).decode("ascii") - out["material"] = mat - return out - - -_GLB_ATTRIBUTE_TYPES = { - "POSITION": ("VEC3",), - "NORMAL": ("VEC3",), - "TEXCOORD_0": ("VEC2",), - "COLOR_0": ("VEC3", "VEC4"), - "JOINTS_0": ("VEC4",), - "WEIGHTS_0": ("VEC4",), - "JOINTS_1": ("VEC4",), - "WEIGHTS_1": ("VEC4",), -} -_GLB_UNSIGNED_INT_COMPONENTS = ( - COMPONENT_UNSIGNED_BYTE, - COMPONENT_UNSIGNED_SHORT, - COMPONENT_UNSIGNED_INT, -) - - -def _check_glb_document(doc: object, bin_chunk: bytes, path: str) -> None: - """Refuse a GLB document `read_glb_parts` cannot walk, with one message instead of a traceback. - - Checks only what the reader dereferences: the tables it indexes, the accessors its primitives name (their - type, and that their bytes are inside the BIN chunk) and the material fields it converts. - """ - def bad(detail: str) -> PedAssembleError: - return PedAssembleError(f"{path}: malformed GLB: {detail}") - - def is_index(value: object) -> bool: - return type(value) is int and value >= 0 - - def is_whole(value: object) -> bool: - """A count, offset or stride: the reader takes these through int(), so 3.0 reads as 3.""" - return is_index(value) or (type(value) is float and value.is_integer() and value >= 0) - - def check_name(value: object, what: str) -> None: - """The part name is the node's name, else the mesh's; a value that is not text cannot be classified.""" - if value and not isinstance(value, str): - raise bad(f"{what} must be a string, got {value!r}") - - def number(value: object, what: str) -> None: - try: - float(value) - except (TypeError, ValueError): - raise bad(f"{what} must be a number, got {value!r}") from None - - if not isinstance(doc, dict): - raise bad("the JSON chunk must be an object") - tables = {} - for name in ("nodes", "meshes", "materials", "skins", "accessors", "bufferViews"): - table = doc.get(name, []) - if not isinstance(table, list): - raise bad(f"{name} must be a list") - tables[name] = table - nodes, meshes, materials = tables["nodes"], tables["meshes"], tables["materials"] - accessors, views = tables["accessors"], tables["bufferViews"] - - def check_accessor( - index: object, - what: str, - allowed: tuple[str, ...], - *, - component_types: tuple[int, ...] | None = None, - ) -> None: - if not is_index(index) or index >= len(accessors): - raise bad(f"{what} names accessor {index!r} (GLB has {len(accessors)})") - acc = accessors[index] - if not isinstance(acc, dict): - raise bad(f"accessors[{index}] must be an object") - ctype, atype, count = acc.get("componentType"), acc.get("type"), acc.get("count") - if type(ctype) is not int or ctype not in COMPONENT_STRUCT: - raise bad(f"accessors[{index}] has unsupported componentType {ctype!r}") - if component_types is not None and ctype not in component_types: - raise bad(f"{what} is accessor {index} with componentType {ctype}, expected unsigned integer") - if not isinstance(atype, str) or atype not in TYPE_COMPONENTS: - raise bad(f"accessors[{index}] has unsupported type {atype!r}") - if atype not in allowed: - raise bad(f"{what} is accessor {index} of type {atype}, expected {' or '.join(allowed)}") - if not is_whole(count): - raise bad(f"accessors[{index}] has invalid count {count!r}") - count = int(count) - component_size = COMPONENT_STRUCT[ctype][1] - elem_bytes = component_size * TYPE_COMPONENTS[atype] - label = f"accessors[{index}]" - has_sparse = "sparse" in acc - - def check_region(section, name, rows, size, alignment, *, packed=False): - """Validate the rows before unpacking them; sparse indices/values always use tight packing.""" - view_index = section.get("bufferView") - if packed and is_whole(view_index): - view_index = int(view_index) - if not is_index(view_index) or view_index >= len(views): - raise bad(f"{name} names bufferView {view_index!r} (GLB has {len(views)})") - view = views[view_index] - if not isinstance(view, dict): - raise bad(f"bufferViews[{view_index}] must be an object") - offsets = (view.get("byteOffset", 0), section.get("byteOffset", 0)) - stride = view.get("byteStride") - if not all(is_whole(v) for v in offsets) or not (stride is None or is_whole(stride)): - raise bad(f"{name} has an invalid byteOffset or byteStride") - start, offset = map(int, offsets) - step = int(stride or size) - end = offset + ((rows - 1) * step + size if rows else 0) - if rows and start + end > len(bin_chunk): - raise bad(f"{name} ({what}) runs past the BIN chunk ({len(bin_chunk)} bytes)") - if has_sparse: - if packed and ("byteStride" in view or "target" in view): - raise bad(f"{name} must use a bufferView without byteStride or target") - if offset % alignment or (start + offset) % alignment or step < size or step % alignment: - raise bad(f"{name} has an invalid offset alignment or stride") - buffers = doc.get("buffers") - if (not is_whole(view.get("buffer")) or view["buffer"] != 0 - or not isinstance(buffers, list) or not buffers or not isinstance(buffers[0], dict) - or "uri" in buffers[0]): - raise bad(f"{name} must use the embedded GLB buffer") - length = view.get("byteLength") - limit = buffers[0].get("byteLength") - if (not is_whole(length) or not is_whole(limit) or end > length - or start + length > limit or limit > len(bin_chunk)): - raise bad(f"{name} exceeds its bufferView or embedded buffer") - return start + offset - - if "bufferView" in acc: - check_region(acc, label, count, elem_bytes, component_size) - elif "byteOffset" in acc: - raise bad(f"{label} cannot specify byteOffset without a base bufferView") - elif not has_sparse: - required = doc.get("extensionsRequired", []) - if not isinstance(required, list): - raise bad("extensionsRequired must be a list") - if "KHR_draco_mesh_compression" in required: - raise PedAssembleError(f"{path}: required KHR_draco_mesh_compression is unsupported") - if not has_sparse: - return - - sparse = acc["sparse"] - if not isinstance(sparse, dict): - raise bad(f"{label}.sparse must be an object") - n = sparse.get("count") - if not is_whole(n) or not 1 <= n <= count: - raise bad(f"{label}.sparse.count must be between 1 and {count}") - n = int(n) - indices, values = sparse.get("indices"), sparse.get("values") - if not isinstance(indices, dict) or not isinstance(values, dict): - raise bad(f"{label}.sparse needs indices and values objects") - index_type = indices.get("componentType") - if not is_whole(index_type) or index_type not in (COMPONENT_UNSIGNED_BYTE, COMPONENT_UNSIGNED_SHORT, - COMPONENT_UNSIGNED_INT): - raise bad(f"{label}.sparse.indices must use unsigned byte, short or int components") - fmt, width = COMPONENT_STRUCT[int(index_type)] - start = check_region(indices, f"{label}.sparse.indices", n, width, width, packed=True) - check_region(values, f"{label}.sparse.values", n, elem_bytes, component_size, packed=True) - previous = -1 - for (dest,) in struct.iter_unpack("<" + fmt, memoryview(bin_chunk)[start:start + n * width]): - if not previous < dest < count: - raise bad(f"{label}.sparse.indices must be strictly increasing and below {count}") - previous = dest - - for i, mesh in enumerate(meshes): - if not isinstance(mesh, dict): - raise bad(f"meshes[{i}] must be an object") - primitives = mesh.get("primitives", []) - if not isinstance(primitives, list): - raise bad(f"meshes[{i}].primitives must be a list") - for pi, prim in enumerate(primitives): - where = f"meshes[{i}].primitives[{pi}]" - if not isinstance(prim, dict): - raise bad(f"{where} must be an object") - attrs = prim.get("attributes", {}) - if not isinstance(attrs, dict): - raise bad(f"{where}.attributes must be an object") - if "POSITION" not in attrs: - continue - for name, allowed in _GLB_ATTRIBUTE_TYPES.items(): - if name in attrs: - ctypes = _GLB_UNSIGNED_INT_COMPONENTS if name in ("JOINTS_0", "JOINTS_1") else None - check_accessor(attrs[name], f"{where}.{name}", allowed, component_types=ctypes) - for name, index in attrs.items(): - if re.fullmatch(r"TEXCOORD_[1-9][0-9]{0,8}", name): - check_accessor(index, f"{where}.{name}", ("VEC2",)) - if "indices" in prim: - check_accessor( - prim["indices"], - f"{where}.indices", - ("SCALAR",), - component_types=_GLB_UNSIGNED_INT_COMPONENTS, - ) - if "material" not in prim: - continue - material_index = prim["material"] - if type(material_index) is not int: - raise bad(f"{where}.material must be an index, got {material_index!r}") - if not 0 <= material_index < len(materials): - continue # the reader leaves such a part without a material - material = materials[material_index] - if not isinstance(material, dict): - raise bad(f"materials[{material_index}] must be an object") - pbr = material.get("pbrMetallicRoughness", {}) - if not isinstance(pbr, dict): - raise bad(f"materials[{material_index}].pbrMetallicRoughness must be an object") - factor = pbr.get("baseColorFactor", [0.8, 0.8, 0.8, 1.0]) - if not isinstance(factor, list) or len(factor) < 4: - raise bad(f"materials[{material_index}] baseColorFactor must be a list of 4 numbers") - for value in factor[:4]: - number(value, f"materials[{material_index}] baseColorFactor") - for owner, key in ((pbr, "metallicFactor"), (pbr, "roughnessFactor"), (material, "alphaCutoff")): - if key in owner: - number(owner[key], f"materials[{material_index}] {key}") - - for i, node in enumerate(nodes): - if not isinstance(node, dict): - raise bad(f"nodes[{i}] must be an object") - if not any("mesh" in node for node in nodes): - for i, mesh in enumerate(meshes): # the reader then makes one part per mesh - check_name(mesh.get("name"), f"meshes[{i}].name") - for i, node in enumerate(nodes): - if "mesh" not in node: - continue - if not is_index(node["mesh"]) or node["mesh"] >= len(meshes): - raise bad(f"nodes[{i}] names mesh {node['mesh']!r} (GLB has {len(meshes)})") - check_name(node.get("name"), f"nodes[{i}].name") - if not node.get("name"): - check_name(meshes[node["mesh"]].get("name"), f"meshes[{node['mesh']}].name") - translation = node.get("translation", (0.0, 0.0, 0.0)) - if not isinstance(translation, (list, tuple)) or len(translation) != 3: - raise bad(f"nodes[{i}].translation must be a list of 3 numbers") - for value in translation: - number(value, f"nodes[{i}].translation") - - -def _read_glb_accessor(doc: dict, bin_chunk: bytes, acc_idx: int) -> list: - acc = doc["accessors"][acc_idx] - ctype = acc["componentType"] - atype = acc["type"] - count = int(acc["count"]) - fmt_char, comp_size = COMPONENT_STRUCT[ctype] - n_comp = TYPE_COMPONENTS[atype] - elem_bytes = comp_size * n_comp - normalized = bool(acc.get("normalized", False)) - denom = None - if normalized: - if ctype == COMPONENT_UNSIGNED_BYTE: - denom = 255.0 - elif ctype == COMPONENT_UNSIGNED_SHORT: - denom = 65535.0 - elif ctype == COMPONENT_BYTE: - denom = 127.0 - elif ctype == COMPONENT_SHORT: - denom = 32767.0 - - unpack = struct.Struct(f"<{n_comp}{fmt_char}").unpack_from - - def read_row(offset): - vals = unpack(bin_chunk, offset) - if denom is not None: - if ctype in (COMPONENT_BYTE, COMPONENT_SHORT): - # Both signed minimum encodings represent -1 in glTF's normalized range. - vals = tuple(max(v, -denom) / denom for v in vals) - else: - vals = tuple(v / denom for v in vals) - return vals[0] if n_comp == 1 else vals - - def start_of(section): - view = doc["bufferViews"][int(section["bufferView"])] - return int(view.get("byteOffset", 0)) + int(section.get("byteOffset", 0)) - - if "bufferView" in acc: - base = start_of(acc) - stride = int(doc["bufferViews"][acc["bufferView"]].get("byteStride") or elem_bytes) - out = [read_row(base + i * stride) for i in range(count)] - else: - zero = 0 if n_comp == 1 else (0,) * n_comp - out = [zero] * count - - if "sparse" in acc: - sparse = acc["sparse"] - indices = sparse["indices"] - fmt, width = COMPONENT_STRUCT[int(indices["componentType"])] - start = start_of(indices) - packed_indices = memoryview(bin_chunk)[start:start + int(sparse["count"]) * width] - values_start = start_of(sparse["values"]) - for i, (dest,) in enumerate(struct.iter_unpack("<" + fmt, packed_indices)): - out[dest] = read_row(values_start + i * elem_bytes) - return out - - -def _extract_glb_skin_joint_names( - doc: dict, - skin_idx: object, - *, - path: str, - part_name: str, -) -> list[str]: - skins = doc.get("skins", []) - nodes = doc.get("nodes", []) - if not isinstance(skin_idx, int) or isinstance(skin_idx, bool) or not (0 <= skin_idx < len(skins)): - raise PedAssembleError( - f"{path}: part {part_name!r} references invalid skin index {skin_idx!r} " - f"(GLB has {len(skins)} skin(s))" - ) - skin = skins[skin_idx] - if not isinstance(skin, dict): - raise PedAssembleError(f"{path}: skins[{skin_idx}] must be a JSON object") - raw_joints = skin.get("joints") - if not isinstance(raw_joints, list): - raise PedAssembleError(f"{path}: skins[{skin_idx}].joints must be a list") - joint_names: list[str] = [] - for slot, j_node_idx in enumerate(raw_joints): - if ( - not isinstance(j_node_idx, int) - or isinstance(j_node_idx, bool) - or not (0 <= j_node_idx < len(nodes)) - ): - raise PedAssembleError( - f"{path}: skins[{skin_idx}].joints[{slot}] references invalid node index {j_node_idx!r} " - f"(GLB has {len(nodes)} node(s))" - ) - jnode = nodes[j_node_idx] - if not isinstance(jnode, dict): - raise PedAssembleError(f"{path}: nodes[{j_node_idx}] must be a JSON object") - raw_name = jnode.get("name") - if raw_name is None: - joint_names.append("") - elif isinstance(raw_name, str): - joint_names.append(raw_name) - else: - raise PedAssembleError( - f"{path}: skins[{skin_idx}].joints[{slot}] (node {j_node_idx}) " - f"has non-string name {raw_name!r}" - ) - return joint_names - - -def read_glb_parts(path: str) -> list[MeshPart]: - """Read mesh parts from a binary glTF 2.0 (``.glb``) file (always Y-up).""" - with open(path, "rb") as f: - data = f.read() - if len(data) < 20 or data[:4] != GLB_MAGIC: - raise PedAssembleError(f"{path}: not a valid GLB container") - version, total_len = struct.unpack_from(" len(data): - raise PedAssembleError(f"{path}: unsupported GLB version or truncated length") - - pos = 12 - doc = None - bin_chunk = b"" - while pos + 8 <= total_len: - chunk_len, chunk_type = struct.unpack_from(" remaining_implicit_rows: - raise PedAssembleError(f"{path}: accessors[{index}] would exceed the per-file limit of " - f"{MAX_IMPLICIT_ACCESSOR_ROWS:,} implicit accessor rows") - remaining_implicit_rows -= rows - return _read_glb_accessor(doc, bin_chunk, index) - - mesh_nodes = [(n, n["mesh"]) for n in nodes if "mesh" in n] - if not mesh_nodes: - mesh_nodes = [({"name": m.get("name", f"{stem}_{i}")}, i) for i, m in enumerate(meshes)] - - for node, mesh_idx in mesh_nodes: - mesh = meshes[mesh_idx] - node_name = node.get("name") or mesh.get("name") or stem - trans = tuple(float(v) for v in node.get("translation", (0.0, 0.0, 0.0))) - has_node_skin = "skin" in node and node["skin"] is not None - node_joint_names = ( - _extract_glb_skin_joint_names(doc, node["skin"], path=path, part_name=node_name) - if has_node_skin - else None - ) - for pi, prim in enumerate(mesh.get("primitives", [])): - attrs = prim.get("attributes", {}) - if "POSITION" not in attrs: - continue - positions = [tuple(float(x) for x in p) for p in read_accessor(attrs["POSITION"])] - if "indices" in prim: - raw_idx = [int(i) for i in read_accessor(prim["indices"])] - else: - raw_idx = list(range(len(positions))) - triangles = _normalize_triangles(raw_idx) - normals = ( - [tuple(float(x) for x in n) for n in read_accessor(attrs["NORMAL"])] - if "NORMAL" in attrs else None - ) - uvs = ( - [tuple(float(x) for x in u) for u in read_accessor(attrs["TEXCOORD_0"])] - if "TEXCOORD_0" in attrs else None - ) - uvs_extra = { - int(semantic[9:]): [tuple(float(x) for x in u) - for u in read_accessor(accessor)] - for semantic, accessor in attrs.items() - if re.fullmatch(r"TEXCOORD_[1-9][0-9]{0,8}", semantic) - } - colors = None - if "COLOR_0" in attrs: - raw_c = read_accessor(attrs["COLOR_0"]) - colors = [ - (float(c[0]), float(c[1]), float(c[2]), float(c[3]) if len(c) > 3 else 1.0) - for c in raw_c - ] - joints_0 = ( - [tuple(int(x) for x in j) for j in read_accessor(attrs["JOINTS_0"])] - if "JOINTS_0" in attrs else None - ) - weights_0 = ( - [tuple(float(x) for x in w) for w in read_accessor(attrs["WEIGHTS_0"])] - if "WEIGHTS_0" in attrs else None - ) - joints_1 = ( - [tuple(int(x) for x in j) for j in read_accessor(attrs["JOINTS_1"])] - if "JOINTS_1" in attrs else None - ) - weights_1 = ( - [tuple(float(x) for x in w) for w in read_accessor(attrs["WEIGHTS_1"])] - if "WEIGHTS_1" in attrs else None - ) - pname = node_name if len(mesh.get("primitives", [])) == 1 else f"{node_name}_p{pi}" - has_skin_attrs = joints_0 is not None or joints_1 is not None - if has_node_skin: - part_joint_names = list(node_joint_names) if (has_skin_attrs and node_joint_names is not None) else None - elif has_skin_attrs: - if len(skins) == 1: - part_joint_names = _extract_glb_skin_joint_names( - doc, - 0, - path=path, - part_name=pname, - ) - elif len(skins) > 1: - raise PedAssembleError( - f"{path}: skinned part {pname!r} has no node 'skin' index " - f"and GLB defines {len(skins)} skins (ambiguous skin binding)" - ) - else: - part_joint_names = [] - else: - part_joint_names = None - - mat_spec = None - if "material" not in prim or 0 <= prim["material"] < len(materials): - gm = materials[prim["material"]] if "material" in prim else {"name": f"{pname}_mat"} - pbr = gm.get("pbrMetallicRoughness", {}) - # glTF defaults also apply to primitives with no material; other input formats keep their clay defaults. - bcf = pbr.get("baseColorFactor", [1.0, 1.0, 1.0, 1.0]) - mat_spec = MaterialSpec( - name=str(gm.get("name", f"{node_name}_mat")), - base_color_factor=(float(bcf[0]), float(bcf[1]), float(bcf[2]), float(bcf[3])), - metallic_factor=float(pbr.get("metallicFactor", 1.0)), - roughness_factor=float(pbr.get("roughnessFactor", 1.0)), - alpha_mode=str(gm.get("alphaMode", "OPAQUE")), - alpha_cutoff=float(gm["alphaCutoff"]) if "alphaCutoff" in gm else None, - double_sided=bool(gm.get("doubleSided", False)), - ) - parts.append(MeshPart( - name=pname, - positions=positions, - triangles=triangles, - coord_space="y-up", - translation=trans, - normals=normals, - uvs=uvs, - uvs_extra=uvs_extra, - colors=colors, - joints_0=joints_0, - weights_0=weights_0, - joints_1=joints_1, - weights_1=weights_1, - joint_names=part_joint_names, - material=mat_spec, - )) - return parts - - -def load_parts_from_path( - path: str, - *, - source_space: str = "z-up", -) -> tuple[list[MeshPart], SkeletonSpec | None]: - """Load one or more ``MeshPart`` objects from a ``.json``, ``.obj``, or ``.glb`` file.""" - ext = os.path.splitext(path)[1].lower() - stem = os.path.splitext(os.path.basename(path))[0] - base_dir = os.path.dirname(os.path.abspath(path)) - - if ext == ".glb": - return read_glb_parts(path), None - - if ext == ".obj": - # Parse OBJ keeping raw coordinates in the declared source_space - prims = glb_writer.parse_obj(path, up_axis="y") - parts: list[MeshPart] = [] - for idx, prim in enumerate(prims): - pname = prim.get("name") or (stem if len(prims) == 1 else f"{stem}_{idx}") - parts.append(MeshPart( - name=pname, - positions=[tuple(p) for p in prim["positions"]], - triangles=_normalize_triangles(prim["indices"]), - coord_space=source_space, - normals=[tuple(n) for n in prim["normals"]] if prim.get("normals") else None, - uvs=[tuple(u) for u in prim["uvs"]] if prim.get("uvs") else None, - )) - return parts, None - - if ext == ".json": - with open(path, encoding="utf-8-sig") as f: - data = json.load(f) - if isinstance(data, dict) and "parts" in data: - skel = _skeleton_from_dict(data.get("skeleton"), default_space=data.get("coord_space", source_space)) - default_sp = str(data.get("coord_space", source_space)) - parts = [] - for idx, entry in enumerate(data["parts"]): - if isinstance(entry, str): - sub_path = entry if os.path.isabs(entry) else os.path.join(base_dir, entry) - sub_parts, _ = load_parts_from_path(sub_path, source_space=default_sp) - parts.extend(sub_parts) - elif isinstance(entry, dict) and "path" in entry and "positions" not in entry: - sub_path = entry["path"] if os.path.isabs(entry["path"]) else os.path.join(base_dir, entry["path"]) - sub_parts, _ = load_parts_from_path(sub_path, source_space=entry.get("coord_space", default_sp)) - for sp in sub_parts: - if entry.get("name"): - sp.name = str(entry["name"]) - if entry.get("role"): - sp.role = str(entry["role"]) - if "joint_names" in entry or "jointNames" in entry: - raw_jn = entry.get("joint_names", entry.get("jointNames")) - sp.joint_names = _parse_joint_names(raw_jn, part_name=sp.name) - parts.append(sp) - elif isinstance(entry, dict): - parts.append(_part_from_dict(entry, default_name=f"{stem}_{idx}", default_space=default_sp, base_dir=base_dir)) - else: - raise PedAssembleError(f"{path}: unsupported part entry at index {idx}") - return parts, skel - if isinstance(data, dict): - return [_part_from_dict(data, default_name=stem, default_space=source_space, base_dir=base_dir)], None - raise PedAssembleError(f"{path}: JSON root must be an object") - - raise PedAssembleError(f"{path}: unsupported input extension {ext!r} (expected .json, .obj, or .glb)") - - -# --------------------------------------------------------------------------- GLB assembly writer - -def _pad4(buf: bytearray, pad_byte: int = 0) -> None: - rem = len(buf) & 3 - if rem: - buf.extend(bytes([pad_byte]) * (4 - rem)) - - -def _append_bv( - bin_buf: bytearray, - buffer_views: list[dict], - payload: bytes, - target: int | None = None, -) -> int: - _pad4(bin_buf, 0) - offset = len(bin_buf) - bin_buf.extend(payload) - bv: dict = {"buffer": 0, "byteOffset": offset, "byteLength": len(payload)} - if target is not None: - bv["target"] = target - buffer_views.append(bv) - return len(buffer_views) - 1 - - -def _append_accessor( - accessors: list[dict], - buffer_view: int, - component_type: int, - count: int, - acc_type: str, - *, - min_vals: list[float] | None = None, - max_vals: list[float] | None = None, - normalized: bool = False, -) -> int: - acc: dict = { - "bufferView": buffer_view, - "componentType": component_type, - "count": count, - "type": acc_type, - } - if normalized: - acc["normalized"] = True - if min_vals is not None: - acc["min"] = min_vals - if max_vals is not None: - acc["max"] = max_vals - accessors.append(acc) - return len(accessors) - 1 - - -def _pack_u16_vec4(rows: list[tuple[int, int, int, int]]) -> bytes: - buf = bytearray(len(rows) * 8) - for i, (a, b, c, d) in enumerate(rows): - struct.pack_into("<4H", buf, i * 8, a, b, c, d) - return bytes(buf) - - -def _pack_f32_vec(rows: list[tuple[float, ...]], comps: int) -> bytes: - fmt = f"<{comps}f" - stride = comps * 4 - buf = bytearray(len(rows) * stride) - for i, row in enumerate(rows): - struct.pack_into(fmt, buf, i * stride, *row[:comps]) - return bytes(buf) - - -def remap_part_joints( - part: MeshPart, - skeleton: SkeletonSpec, -) -> tuple[list[tuple[int, int, int, int]] | None, list[tuple[int, int, int, int]] | None]: - """Validate and remap ``part``'s skinning joint indices into ``skeleton.joints`` slot order. - - When ``part.joint_names`` is present (for example from a skinned ``.glb`` input - or a manifest specifying source joint names), every non-zero-weighted influence - slot is resolved through ``part.joint_names[src_idx]`` and mapped to the unique - matching joint name in ``skeleton.joints``. Missing, unnamed, out-of-range, or - ambiguous (duplicate-name) correspondences raise :class:`PedAssembleError` - (a :class:`ValueError` subclass). Zero-weight padding slots are remapped when - unambiguous and otherwise reset to ``0``. - - When ``part.joint_names`` is ``None`` (raw inputs authored directly in the - target skeleton's index space), every non-zero-weighted joint index is validated - to lie within ``[0, len(skeleton.joints))``. - """ - if part.joints_0 is None and part.weights_0 is None and part.joints_1 is None and part.weights_1 is None: - return None, None - if (part.joints_0 is None) != (part.weights_0 is None): - raise PedAssembleError(f"{part.name}: joints_0 and weights_0 must both be provided") - if (part.joints_1 is None) != (part.weights_1 is None): - raise PedAssembleError(f"{part.name}: joints_1 and weights_1 must both be provided") - if part.joints_1 is not None and part.joints_0 is None: - raise PedAssembleError(f"{part.name}: joints_1/weights_1 provided without joints_0/weights_0") - - n_verts = len(part.positions) - if part.joints_0 is not None and (len(part.joints_0) != n_verts or len(part.weights_0) != n_verts): - raise PedAssembleError( - f"{part.name}: joints_0 ({len(part.joints_0)}) / weights_0 ({len(part.weights_0)}) " - f"must match vertex count ({n_verts})" - ) - if part.joints_1 is not None and (len(part.joints_1) != n_verts or len(part.weights_1) != n_verts): - raise PedAssembleError( - f"{part.name}: joints_1 ({len(part.joints_1)}) / weights_1 ({len(part.weights_1)}) " - f"must match vertex count ({n_verts})" - ) - - n_dst = len(skeleton.joints) - if n_dst == 0: - raise PedAssembleError( - f"{part.name}: target skeleton {skeleton.name!r} has no joints for skinned mesh" - ) - if n_dst > 65536: - raise PedAssembleError( - f"{part.name}: target skeleton {skeleton.name!r} has {n_dst} joints (exceeds u16 JOINTS_n limit)" - ) - - slot_map: list[tuple[bool, int | str]] | None = None - if part.joint_names is not None: - src_by_name: dict[str, list[int]] = defaultdict(list) - for src_idx, sname in enumerate(part.joint_names): - if sname and sname.strip(): - src_by_name[sname].append(src_idx) - - dst_by_name: dict[str, list[int]] = defaultdict(list) - for dst_idx, joint in enumerate(skeleton.joints): - if joint.name and joint.name.strip(): - dst_by_name[joint.name].append(dst_idx) - - slot_map = [] - for src_idx, sname in enumerate(part.joint_names): - if not sname or not sname.strip(): - slot_map.append(( - False, - f"source joint slot {src_idx} is unnamed and cannot be mapped to skeleton {skeleton.name!r}", - )) - continue - src_slots = src_by_name[sname] - if len(src_slots) > 1: - slot_map.append(( - False, - f"source joint name {sname!r} is ambiguous in source skin (slots {src_slots})", - )) - continue - dst_slots = dst_by_name.get(sname) - if not dst_slots: - slot_map.append(( - False, - f"source joint {sname!r} (slot {src_idx}) not found in target skeleton {skeleton.name!r}", - )) - continue - if len(dst_slots) > 1: - slot_map.append(( - False, - f"target joint name {sname!r} is ambiguous in skeleton {skeleton.name!r} (slots {dst_slots})", - )) - continue - slot_map.append((True, dst_slots[0])) - - def _remap_attr( - joints: list[tuple[int, int, int, int]] | None, - weights: list[tuple[float, float, float, float]] | None, - attr_name: str, - ) -> list[tuple[int, int, int, int]] | None: - if joints is None or weights is None: - return None - remapped: list[tuple[int, int, int, int]] = [] - for vi, (j_row, w_row) in enumerate(zip(joints, weights)): - if len(j_row) != 4 or len(w_row) != 4: - raise PedAssembleError( - f"{part.name}: {attr_name} vertex {vi} must have 4 joint/weight components" - ) - out_row: list[int] = [] - for comp, (src_idx, weight) in enumerate(zip(j_row, w_row)): - active = weight != 0.0 - if slot_map is not None: - if active: - if not (0 <= src_idx < len(slot_map)): - if len(slot_map) == 0: - raise PedAssembleError( - f"{part.name}: {attr_name} vertex {vi}[{comp}] has weight {weight} " - f"on slot {src_idx}, but source part has no skin joints to map to " - f"skeleton {skeleton.name!r}" - ) - raise PedAssembleError( - f"{part.name}: {attr_name} vertex {vi}[{comp}] references out-of-range " - f"source joint slot {src_idx} (source skin has {len(slot_map)} joint(s))" - ) - ok, payload = slot_map[src_idx] - if not ok: - raise PedAssembleError( - f"{part.name}: {attr_name} vertex {vi}[{comp}] (weight={weight}): {payload}" - ) - out_row.append(int(payload)) - else: - if 0 <= src_idx < len(slot_map) and slot_map[src_idx][0]: - out_row.append(int(slot_map[src_idx][1])) - else: - out_row.append(0) - else: - if active: - if not (0 <= src_idx < n_dst): - raise PedAssembleError( - f"{part.name}: {attr_name} vertex {vi}[{comp}] references out-of-range " - f"joint index {src_idx} for skeleton {skeleton.name!r} ({n_dst} joint(s))" - ) - out_row.append(src_idx) - else: - out_row.append(src_idx if 0 <= src_idx < n_dst else 0) - remapped.append((out_row[0], out_row[1], out_row[2], out_row[3])) - return remapped - - new_j0 = _remap_attr(part.joints_0, part.weights_0, "JOINTS_0") - new_j1 = _remap_attr(part.joints_1, part.weights_1, "JOINTS_1") - return new_j0, new_j1 - - -def build_assembled_glb( - parts: list[MeshPart], - *, - skeleton: SkeletonSpec | None = None, - standing_offset: float = DEFAULT_STANDING_OFFSET_M, - apply_standing: bool = True, - generator: str = "Leonida ped_assemble.py", -) -> tuple[bytes, dict]: - """Serialize assembled modular ped ``parts`` (and optional ``skeleton``) to a glTF 2.0 GLB. - - All mesh geometry is converted into glTF Y-up standing space. When - ``skeleton`` is provided, joint nodes, inverse bind matrices, and a - standing-space root wrapper node are emitted and bound to every skinned - mesh node. Skinned parts carrying ``joint_names`` have their ``JOINTS_0`` - and ``JOINTS_1`` slots remapped by joint name into ``skeleton.joints`` order. - """ - non_empty = [p for p in parts if p.positions and p.triangles] - if not non_empty: - raise PedAssembleError("No non-empty mesh parts to export") - - bin_buf = bytearray() - buffer_views: list[dict] = [] - accessors: list[dict] = [] - images: list[dict] = [] - textures: list[dict] = [] - samplers: list[dict] = [] - materials: list[dict] = [] - meshes: list[dict] = [] - nodes: list[dict] = [] - scene_nodes: list[int] = [] - - png_cache: dict[bytes, int] = {} - - def _add_png_texture(png_bytes: bytes) -> int: - if png_bytes in png_cache: - return png_cache[png_bytes] - if not samplers: - samplers.append({"magFilter": 9729, "minFilter": 9987, "wrapS": 10497, "wrapT": 10497}) - bv = _append_bv(bin_buf, buffer_views, png_bytes, target=None) - img_idx = len(images) - images.append({"bufferView": bv, "mimeType": "image/png"}) - tex_idx = len(textures) - textures.append({"sampler": 0, "source": img_idx}) - png_cache[png_bytes] = tex_idx - return tex_idx - - def _add_material(spec: MaterialSpec | None, fallback_name: str) -> int: - ms = spec or MaterialSpec(name=fallback_name) - pbr: dict = { - "baseColorFactor": [float(v) for v in ms.base_color_factor], - "metallicFactor": float(ms.metallic_factor), - "roughnessFactor": float(ms.roughness_factor), - } - if ms.base_color_png is not None: - pbr["baseColorTexture"] = {"index": _add_png_texture(ms.base_color_png)} - if ms.metallic_roughness_png is not None: - pbr["metallicRoughnessTexture"] = {"index": _add_png_texture(ms.metallic_roughness_png)} - mat_obj: dict = {"name": ms.name, "pbrMetallicRoughness": pbr} - if ms.normal_png is not None: - mat_obj["normalTexture"] = {"index": _add_png_texture(ms.normal_png)} - if ms.alpha_mode and ms.alpha_mode != "OPAQUE": - mat_obj["alphaMode"] = ms.alpha_mode - if ms.alpha_mode == "MASK" and ms.alpha_cutoff is not None: - mat_obj["alphaCutoff"] = float(ms.alpha_cutoff) - if ms.double_sided: - mat_obj["doubleSided"] = True - materials.append(mat_obj) - return len(materials) - 1 - - skinned_node_indices: list[int] = [] - total_verts = 0 - total_tris = 0 - - for part in non_empty: - is_skinned_part = part.joints_0 is not None and part.weights_0 is not None and skeleton is not None - # For skinned parts with a skeleton, standing offset lives on the skeleton root node - # (so bind-space vertices match IBMs cleanly); for static parts, bake standing offset into vertices. - aligned = align_part_to_standing_space( - part, - standing_offset=standing_offset, - target_space="y-up", - apply_offset=(apply_standing and not is_skinned_part), - ) - n_verts = len(aligned.positions) - flat_indices = [idx for tri in aligned.triangles for idx in tri] - if aligned.normals is not None and len(aligned.normals) == n_verts: - normals = aligned.normals - else: - normals = glb_writer._compute_smooth_normals(aligned.positions, flat_indices) - - pos_bytes = _pack_f32_vec(aligned.positions, 3) - pos_bv = _append_bv(bin_buf, buffer_views, pos_bytes, target=TARGET_ARRAY_BUFFER) - xs = [p[0] for p in aligned.positions] - ys = [p[1] for p in aligned.positions] - zs = [p[2] for p in aligned.positions] - pos_acc = _append_accessor( - accessors, pos_bv, COMPONENT_FLOAT, n_verts, "VEC3", - min_vals=[min(xs), min(ys), min(zs)], - max_vals=[max(xs), max(ys), max(zs)], - ) - - nrm_bytes = _pack_f32_vec(normals, 3) - nrm_bv = _append_bv(bin_buf, buffer_views, nrm_bytes, target=TARGET_ARRAY_BUFFER) - nrm_acc = _append_accessor(accessors, nrm_bv, COMPONENT_FLOAT, n_verts, "VEC3") - - attrs: dict[str, int] = {"POSITION": pos_acc, "NORMAL": nrm_acc} - - if aligned.uvs is not None and len(aligned.uvs) == n_verts: - uv_bytes = _pack_f32_vec(aligned.uvs, 2) - uv_bv = _append_bv(bin_buf, buffer_views, uv_bytes, target=TARGET_ARRAY_BUFFER) - attrs["TEXCOORD_0"] = _append_accessor(accessors, uv_bv, COMPONENT_FLOAT, n_verts, "VEC2") - - if any(type(key) is not int or not 1 <= key <= 999999999 for key in aligned.uvs_extra): - raise PedAssembleError(f"{part.name}: uvs_extra keys must be positive texture coordinate set indices") - for key, values in sorted(aligned.uvs_extra.items()): - if f"TEXCOORD_{key - 1}" not in attrs: - raise PedAssembleError(f"{part.name}: texture coordinate sets must start at 0 without gaps") - if len(values) != n_verts or any(len(u) != 2 for u in values): - raise PedAssembleError(f"{part.name}: TEXCOORD_{key} must contain one VEC2 per vertex") - uv_bv = _append_bv(bin_buf, buffer_views, _pack_f32_vec(values, 2), target=TARGET_ARRAY_BUFFER) - attrs[f"TEXCOORD_{key}"] = _append_accessor(accessors, uv_bv, COMPONENT_FLOAT, n_verts, "VEC2") - - if aligned.colors is not None and len(aligned.colors) == n_verts: - col_bytes = _pack_f32_vec(aligned.colors, 4) - col_bv = _append_bv(bin_buf, buffer_views, col_bytes, target=TARGET_ARRAY_BUFFER) - attrs["COLOR_0"] = _append_accessor(accessors, col_bv, COMPONENT_FLOAT, n_verts, "VEC4") - - joints_0_out = aligned.joints_0 - joints_1_out = aligned.joints_1 - has_any_skin = ( - aligned.joints_0 is not None - or aligned.weights_0 is not None - or aligned.joints_1 is not None - or aligned.weights_1 is not None - ) - if has_any_skin and skeleton is not None: - joints_0_out, joints_1_out = remap_part_joints(aligned, skeleton) - - if joints_0_out is not None and aligned.weights_0 is not None: - j0_bv = _append_bv(bin_buf, buffer_views, _pack_u16_vec4(joints_0_out), target=TARGET_ARRAY_BUFFER) - w0_bv = _append_bv(bin_buf, buffer_views, _pack_f32_vec(aligned.weights_0, 4), target=TARGET_ARRAY_BUFFER) - attrs["JOINTS_0"] = _append_accessor(accessors, j0_bv, COMPONENT_UNSIGNED_SHORT, n_verts, "VEC4") - attrs["WEIGHTS_0"] = _append_accessor(accessors, w0_bv, COMPONENT_FLOAT, n_verts, "VEC4") - - if joints_1_out is not None and aligned.weights_1 is not None: - j1_bv = _append_bv(bin_buf, buffer_views, _pack_u16_vec4(joints_1_out), target=TARGET_ARRAY_BUFFER) - w1_bv = _append_bv(bin_buf, buffer_views, _pack_f32_vec(aligned.weights_1, 4), target=TARGET_ARRAY_BUFFER) - attrs["JOINTS_1"] = _append_accessor(accessors, j1_bv, COMPONENT_UNSIGNED_SHORT, n_verts, "VEC4") - attrs["WEIGHTS_1"] = _append_accessor(accessors, w1_bv, COMPONENT_FLOAT, n_verts, "VEC4") - - idx_bytes, idx_ctype = glb_writer._pack_indices(flat_indices, n_verts) - idx_bv = _append_bv(bin_buf, buffer_views, idx_bytes, target=TARGET_ELEMENT_ARRAY_BUFFER) - idx_acc = _append_accessor(accessors, idx_bv, idx_ctype, len(flat_indices), "SCALAR") - - mat_idx = _add_material(aligned.material, f"{aligned.name}_mat") - mesh_idx = len(meshes) - meshes.append({ - "name": aligned.name, - "primitives": [{ - "attributes": attrs, - "indices": idx_acc, - "material": mat_idx, - "mode": 4, - }], - }) - - node_idx = len(nodes) - node_obj: dict = {"name": aligned.name, "mesh": mesh_idx} - nodes.append(node_obj) - scene_nodes.append(node_idx) - if is_skinned_part: - skinned_node_indices.append(node_idx) - - total_verts += n_verts - total_tris += len(aligned.triangles) - - skins: list[dict] = [] - if skeleton is not None and skeleton.joints: - joint_node_indices: list[int] = [] - root_joint_nodes: list[int] = [] - ibm_floats: list[float] = [] - base_idx = len(nodes) - skel_zup = skeleton.coord_space == "z-up" - - for ji, j in enumerate(skeleton.joints): - t = rage_to_yup_vec3(j.translation) if skel_zup else j.translation - r = rage_to_yup_quat(j.rotation) if skel_zup else j.rotation - s = (j.scale[0], j.scale[2], j.scale[1]) if skel_zup else j.scale - jnode: dict = {"name": j.name} - if any(abs(v) > 1e-7 for v in t): - jnode["translation"] = [round(v, 7) for v in t] - if any(abs(v - d0) > 1e-7 for v, d0 in zip(r, (0.0, 0.0, 0.0, 1.0))): - jnode["rotation"] = [round(v, 7) for v in r] - if any(abs(v - 1.0) > 1e-6 for v in s): - jnode["scale"] = [round(v, 7) for v in s] - nodes.append(jnode) - joint_node_indices.append(base_idx + ji) - - if j.inverse_bind_matrix is not None: - ibm = rage_to_yup_mat4_col(j.inverse_bind_matrix) if skel_zup else j.inverse_bind_matrix - else: - ibm = _identity_mat4_col() - ibm_floats.extend(ibm) - - for ji, j in enumerate(skeleton.joints): - nidx = joint_node_indices[ji] - if 0 <= j.parent < len(skeleton.joints): - nodes[joint_node_indices[j.parent]].setdefault("children", []).append(nidx) - else: - root_joint_nodes.append(nidx) - - skel_off = standing_offset if skeleton.standing_offset is None else skeleton.standing_offset - rig_root_node: dict = {"name": f"{skeleton.name}_root", "children": root_joint_nodes} - if apply_standing and abs(skel_off) > 1e-7: - rig_root_node["translation"] = [0.0, float(skel_off), 0.0] - rig_root_idx = len(nodes) - nodes.append(rig_root_node) - scene_nodes.append(rig_root_idx) - - ibm_bytes = struct.pack(f"<{len(ibm_floats)}f", *ibm_floats) - ibm_bv = _append_bv(bin_buf, buffer_views, ibm_bytes, target=None) - ibm_acc = _append_accessor(accessors, ibm_bv, COMPONENT_FLOAT, len(skeleton.joints), "MAT4") - - skins.append({ - "name": skeleton.name, - "joints": joint_node_indices, - "skeleton": rig_root_idx, - "inverseBindMatrices": ibm_acc, - }) - for sni in skinned_node_indices: - nodes[sni]["skin"] = 0 - - _pad4(bin_buf, 0) - gltf: dict = { - "asset": {"version": "2.0", "generator": generator}, - "scene": 0, - "scenes": [{"nodes": scene_nodes}], - "nodes": nodes, - "meshes": meshes, - "materials": materials, - "accessors": accessors, - "bufferViews": buffer_views, - "buffers": [{"byteLength": len(bin_buf)}], - } - if images: - gltf["images"] = images - gltf["textures"] = textures - gltf["samplers"] = samplers - if skins: - gltf["skins"] = skins - - json_bytes = bytearray(json.dumps(gltf, separators=(",", ":"), ensure_ascii=True).encode("utf-8")) - _pad4(json_bytes, 0x20) - - total_length = 12 + 8 + len(json_bytes) + 8 + len(bin_buf) - header = struct.pack("<4sII", GLB_MAGIC, GLB_VERSION, total_length) - json_hdr = struct.pack(" dict: - """Build and atomically write an assembled modular ped GLB to ``path``.""" - glb_bytes, stats = build_assembled_glb( - parts, - skeleton=skeleton, - standing_offset=standing_offset, - apply_standing=apply_standing, - ) - glb_writer._write_bytes_atomic(path, glb_bytes) - return stats - - -# --------------------------------------------------------------------------- CLI - -def _load_cli_parts( - inputs: list[str], - manifest: str | None, - source_space: str, -) -> tuple[list[MeshPart], SkeletonSpec | None]: - parts: list[MeshPart] = [] - skeleton: SkeletonSpec | None = None - paths = ([manifest] if manifest else []) + list(inputs) - if not paths: - raise PedAssembleError("Provide at least one input part or --manifest") - for p in paths: - loaded, skel = load_parts_from_path(p, source_space=source_space) - parts.extend(loaded) - if skel is not None and skeleton is None: - skeleton = skel - return parts, skeleton - - -def _write_json_report(path: str, data: dict) -> None: - parent = os.path.dirname(os.path.abspath(path)) - if parent: - os.makedirs(parent, exist_ok=True) - with open(path, "w", encoding="utf-8", newline="\n") as f: - json.dump(data, f, indent=2) - f.write("\n") - - -def _cmd_assemble(args: argparse.Namespace) -> int: - parts, skeleton = _load_cli_parts(args.inputs, args.manifest, args.source_space) - # Normalize all parts into a common coordinate space before overlap culling - common_space = args.source_space - aligned_for_cull = [ - align_part_to_standing_space( - p, - standing_offset=0.0, - target_space=common_space, - apply_offset=False, - ) - for p in parts - ] - before_seams = inspect_seams( - aligned_for_cull, - weld_tol=args.weld_tol, - overlap_tol=args.waist_tol, - plane_tol=args.plane_tol, - normal_cos_min=args.normal_cos, - ) - - cull_reports: list[dict] = [] - assembled_parts = aligned_for_cull - if not args.no_cull: - assembled_parts, cull_reports = apply_standard_ped_culling( - aligned_for_cull, - waist_tol=args.waist_tol, - nipple_tol=args.nipple_tol, - genital_tol=args.genital_tol, - plane_tol=args.plane_tol, - normal_cos_min=args.normal_cos, - vertex_tol=args.vertex_tol, - compact_vertices=args.compact_vertices, - ) - - after_seams = inspect_seams( - assembled_parts, - weld_tol=args.weld_tol, - overlap_tol=args.waist_tol, - plane_tol=args.plane_tol, - normal_cos_min=args.normal_cos, - ) - - glb_stats = write_assembled_glb( - args.out, - assembled_parts, - skeleton=skeleton, - standing_offset=args.standing_offset, - apply_standing=not args.no_standing_offset, - ) - - report = { - "output": args.out, - "standing_offset_m": 0.0 if args.no_standing_offset else args.standing_offset, - "cull_passes": cull_reports, - "before_seams": before_seams, - "after_seams": after_seams, - "glb": glb_stats, - } - if args.json: - _write_json_report(args.json, report) - - total_culled = sum(r["culled_total"] for r in cull_reports) - print( - f"assembled {glb_stats['parts']} part(s) -> {args.out} " - f"({glb_stats['vertices']} verts, {glb_stats['triangles']} tris, " - f"culled {total_culled} overlap tris, " - f"non_manifold {before_seams['combined_topology']['non_manifold_edges']} -> " - f"{after_seams['combined_topology']['non_manifold_edges']})" - ) - return 0 - - -def _cmd_cull_overlap(args: argparse.Namespace) -> int: - target_parts, _ = load_parts_from_path(args.target, source_space=args.source_space) - if len(target_parts) != 1: - raise PedAssembleError(f"--target must contain exactly 1 mesh part, got {len(target_parts)}") - target = align_part_to_standing_space( - target_parts[0], standing_offset=0.0, target_space=args.source_space, apply_offset=False - ) - - refs: list[MeshPart] = [] - for ref_path in args.ref: - loaded, _ = load_parts_from_path(ref_path, source_space=args.source_space) - for rp in loaded: - refs.append(align_part_to_standing_space( - rp, standing_offset=0.0, target_space=args.source_space, apply_offset=False - )) - - culled_part, stats = cull_part_overlap( - target, - refs, - centroid_tol=args.tol, - plane_tol=args.plane_tol, - normal_cos_min=args.normal_cos, - vertex_tol=args.vertex_tol, - compact_vertices=args.compact_vertices, - ) - - if args.out: - out_ext = os.path.splitext(args.out)[1].lower() - if out_ext == ".glb": - write_assembled_glb( - args.out, - [culled_part], - standing_offset=args.standing_offset, - apply_standing=not args.no_standing_offset, - ) - elif out_ext == ".json": - _write_json_report(args.out, part_to_dict(culled_part)) - else: - raise PedAssembleError(f"Unsupported output extension {out_ext!r}; use .glb or .json") - - if args.json: - _write_json_report(args.json, stats) - - print( - f"cull-overlap {target.name}: {stats['target_triangles_before']} -> " - f"{stats['target_triangles_after']} tris " - f"(culled {stats['culled_total']}: {stats['culled_exact_key']} exact, " - f"{stats['culled_coplanar_proximity']} proximity)" - ) - return 0 - - -def _cmd_inspect_seams(args: argparse.Namespace) -> int: - parts, _ = _load_cli_parts(args.inputs, args.manifest, args.source_space) - normalized = [ - align_part_to_standing_space(p, standing_offset=0.0, target_space=args.source_space, apply_offset=False) - for p in parts - ] - report = inspect_seams( - normalized, - weld_tol=args.weld_tol, - overlap_tol=args.overlap_tol, - plane_tol=args.plane_tol, - normal_cos_min=args.normal_cos, - ) - if args.json: - _write_json_report(args.json, report) - - topo = report["combined_topology"] - print( - f"inspect-seams: {report['part_count']} part(s), " - f"edges={topo['unique_edges']} (manifold={topo['manifold_edges']}, " - f"boundary={topo['boundary_edges']}, non_manifold={topo['non_manifold_edges']}), " - f"collapsed_triangles={topo['collapsed_triangles']}, " - f"overlapping_pairs={len(report['pairwise_overlaps'])}" - ) - for p in report["parts"]: - print( - f" {p['name']} [{p['role']}]: {p['vertices']} v / {p['triangles']} t, " - f"islands={p['physical_islands']} (welded={p['welded_islands']})" - ) - for ov in report["pairwise_overlaps"]: - print( - f" overlap {ov['part_a']} vs {ov['part_b']}: " - f"{ov['overlapping_triangles_in_a']} tris " - f"({ov['exact_key_hits']} exact, {ov['proximity_hits']} proximity)" - ) - return 0 - - -def build_parser() -> argparse.ArgumentParser: - parser = argparse.ArgumentParser( - prog="ped_assemble.py", - description="Assemble modular RAGE 9 ped parts with standing-space alignment and coplanar overlap culling.", - ) - sub = parser.add_subparsers(dest="command", required=True) - - p_asm = sub.add_parser("assemble", help="Align, cull coplanar overlaps, and export a multi-part GLB.") - p_asm.add_argument("inputs", nargs="*", help="Input part files (.json, .obj, or .glb).") - p_asm.add_argument("--manifest", help="Optional JSON manifest listing parts and optional skeleton.") - p_asm.add_argument("-o", "--out", required=True, help="Output binary glTF 2.0 (.glb) path.") - p_asm.add_argument("--source-space", choices=("z-up", "y-up"), default="z-up", - help="Coordinate space of JSON/OBJ inputs (default: z-up).") - p_asm.add_argument("--standing-offset", type=float, default=DEFAULT_STANDING_OFFSET_M, - help="Vertical SKEL_ROOT standing offset in meters (default: 1.0).") - p_asm.add_argument("--no-standing-offset", action="store_true", - help="Do not add the +1.0 m standing-space offset.") - p_asm.add_argument("--no-cull", action="store_true", - help="Skip coplanar overlap culling passes.") - p_asm.add_argument("--waist-tol", type=float, default=DEFAULT_WAIST_CENTROID_TOL, - help="Centroid tolerance (m) for upper/lower waist culling (default: 0.004).") - p_asm.add_argument("--nipple-tol", type=float, default=DEFAULT_NIPPLE_CENTROID_TOL, - help="Centroid tolerance (m) for upper/nipple culling (default: 0.0025).") - p_asm.add_argument("--genital-tol", type=float, default=DEFAULT_GENITAL_CENTROID_TOL, - help="Centroid tolerance (m) for lower/female genital culling (default: 0.0016).") - p_asm.add_argument("--plane-tol", type=float, default=None, - help="Optional explicit point-to-plane tolerance (m) for coplanarity check.") - p_asm.add_argument("--normal-cos", type=float, default=DEFAULT_NORMAL_COS_MIN, - help="Minimum |dot(n_t, n_r)| for coplanar match (default: 0.85).") - p_asm.add_argument("--vertex-tol", type=float, default=DEFAULT_VERTEX_QUANT_TOL, - help="Quantization tolerance (m) for exact vertex-key triangle match (default: 1e-4).") - p_asm.add_argument("--weld-tol", type=float, default=DEFAULT_WELD_TOL, - help="Vertex weld tolerance (m) for seam topology inspection (default: 1e-4).") - p_asm.add_argument("--compact-vertices", action="store_true", - help="Drop unreferenced vertices after triangle culling.") - p_asm.add_argument("--json", help="Optional JSON report output path.") - p_asm.set_defaults(func=_cmd_assemble) - - p_cull = sub.add_parser("cull-overlap", help="Cull coplanar triangles in a target part against reference parts.") - p_cull.add_argument("--target", required=True, help="Target part file (.json, .obj, or .glb).") - p_cull.add_argument("--ref", action="append", required=True, help="Reference part file (repeatable).") - p_cull.add_argument("-o", "--out", help="Optional output path (.glb or .json).") - p_cull.add_argument("--source-space", choices=("z-up", "y-up"), default="z-up", - help="Coordinate space of JSON/OBJ inputs (default: z-up).") - p_cull.add_argument("--tol", type=float, default=DEFAULT_WAIST_CENTROID_TOL, - help="Centroid distance tolerance in meters (default: 0.004).") - p_cull.add_argument("--plane-tol", type=float, default=None, - help="Optional explicit point-to-plane tolerance in meters.") - p_cull.add_argument("--normal-cos", type=float, default=DEFAULT_NORMAL_COS_MIN, - help="Minimum |dot(n_t, n_r)| for coplanar match (default: 0.85).") - p_cull.add_argument("--vertex-tol", type=float, default=DEFAULT_VERTEX_QUANT_TOL, - help="Quantization tolerance (m) for exact triangle match (default: 1e-4).") - p_cull.add_argument("--standing-offset", type=float, default=DEFAULT_STANDING_OFFSET_M, - help="Standing offset (m) when writing .glb output (default: 1.0).") - p_cull.add_argument("--no-standing-offset", action="store_true", - help="Do not add standing offset when writing .glb output.") - p_cull.add_argument("--compact-vertices", action="store_true", - help="Drop unreferenced vertices after triangle culling.") - p_cull.add_argument("--json", help="Optional JSON stats output path.") - p_cull.set_defaults(func=_cmd_cull_overlap) - - p_seam = sub.add_parser("inspect-seams", help="Inspect island counts, boundary edges, and coplanar overlaps.") - p_seam.add_argument("inputs", nargs="*", help="Input part files (.json, .obj, or .glb).") - p_seam.add_argument("--manifest", help="Optional JSON manifest listing parts.") - p_seam.add_argument("--source-space", choices=("z-up", "y-up"), default="z-up", - help="Coordinate space of JSON/OBJ inputs (default: z-up).") - p_seam.add_argument("--weld-tol", type=float, default=DEFAULT_WELD_TOL, - help="Vertex weld tolerance in meters (default: 1e-4).") - p_seam.add_argument("--overlap-tol", type=float, default=DEFAULT_WAIST_CENTROID_TOL, - help="Centroid tolerance (m) for overlap detection (default: 0.004).") - p_seam.add_argument("--plane-tol", type=float, default=None, - help="Optional explicit point-to-plane tolerance in meters.") - p_seam.add_argument("--normal-cos", type=float, default=DEFAULT_NORMAL_COS_MIN, - help="Minimum |dot(n_t, n_r)| for coplanar match (default: 0.85).") - p_seam.add_argument("--json", help="Optional JSON report output path.") - p_seam.set_defaults(func=_cmd_inspect_seams) - - return parser - - -def main(argv: list[str] | None = None) -> int: - parser = build_parser() - args = parser.parse_args(argv) - try: - return int(args.func(args)) - except PedAssembleError as exc: - print(f"ERROR: {exc}", file=sys.stderr) - return 2 - - -if __name__ == "__main__": - try: # a redirected stdout is strict ANSI code page under -I; write '?' for what it cannot encode - sys.stdout.reconfigure(errors="replace") - except (AttributeError, ValueError, OSError): - pass - sys.exit(main()) diff --git a/tools/ped_catalogues.py b/tools/ped_catalogues.py deleted file mode 100644 index 0b65be43c..000000000 --- a/tools/ped_catalogues.py +++ /dev/null @@ -1,1623 +0,0 @@ -"""Parse and resolve resource-packed `0DRP` v122 and standalone `PSIN` ped appearance catalogues (`0x8dcb4cf5`). - -Ped appearance catalogues exist in two container framings that share the exact same schema and -internal `(block = ptr & 0xfffff, offset = ptr >> 20)` pointer encoding: - -1. Standalone `PSIN` containers (e.g. player/wardrobe catalogues): - Standard `PSIN` block table + `LSCH`/`LENM`/`LRSC` sections (`tools/psin_data.py`), with root - struct `0x8dcb4cf5`. -2. Resource-packed `0DRP` v122 containers (compiled per-archetype ped catalogues inside RPF9): - Standard `0x60`-byte `0DRP`/`0x7a` resource header (`tools/odrp_7a.py`): 16-byte RAGE system - prefix (`8` zero bytes + `0x50000000` page-map pointer), `b"0DRP"` + version `122` at `+0x10`, - 1-based root block index at `+0x20`, struct table at `+0x28`, enum table at `+0x30`, block - directory at `+0x38` (`(u32 key, u32 size, u64 virtual_ptr)`), and `(ns, ne, nb, u4e)` `u16` - counts at `+0x48..+0x4e`. - -Schema chain parsed by this module: -- `0x8dcb4cf5` (192 B root): two `0x60bcb6f3` preset buckets at `+0x00`/`+0x30` (each carrying a - `0x5c` array of `0xf795e8ba` presets at `+0x08`) and two `0x4c70a132` secondary buckets at - `+0x60`/`+0x90`. -- `0xf795e8ba` (88 B preset): `id` (`+0x00`), `parent_id` (`+0x04`, cycle-guarded inheritance), - `0x5c` state array (`+0x08` count, `+0x10` ptr -> `0x37e52277`), `category` (`+0x18`), and - `0x71` tag map `0x12f85293` (`+0x30` ptr, `+0x38` count -> 24 B slots in synthetic block - `0x100..0x1ff` -> `u32` values in block `0x4a`). -- `0x37e52277` (184 B drawable/texture state): `state_id` (`+0x00`), `flags` (`+0x04`), embedded - 56 B `0x147fdab5` at `+0x08` (`drawable_hash` `h0` at `+0x08`, `albedo_hash` at `+0x10`, - `normal_hash` at `+0x18`, `extra_hash` at `+0x20`, `0x71` extension map `0xb70a22c1` at - `+0x28` with 16 B `(u32 key, pad4, u64 target_ptr)` slots), and state tag map `0x12f85293` at - `+0xa0` (`+0xa8` ptr, `+0xb0` count). -- `0x147fdab5` -> `0xb70a22c1` -> key `0x46e1a048` (`joaat("cull_drawable")`) -> `0x3d780b74` - (16 B record: 8 B zero header at `+0x00`, `u64` `murmur64` cull drawable hash `0x7deba6f8` at - `+0x08`). - -Synthetic map-slot block IDs (`0x100..0x1ff`) depend on per-file schema emission order and are -never hardcoded to `0x100` or `0x101`. Standard library only; no game data is bundled. - -Usage: - python -I tools/ped_catalogues.py census [--json] [--out FILE] - [--start N] [--limit BYTES] [--max-inflate BYTES] - python -I tools/ped_catalogues.py inspect [--json] [--out FILE] [--limit N] - python -I tools/ped_catalogues.py resolve [--name NAME ...] - [--names-file FILE] [--hash HEX ...] [--cull-only] - [--require-textures] [--json] [--out FILE] - [--start N] [--limit BYTES] [--max-inflate BYTES] -""" -from __future__ import annotations - -import argparse -import collections -from dataclasses import dataclass -import json -import mmap -import os -import re -import struct -import sys -import zlib -from typing import Iterable, Iterator - -# -I keeps the script directory off sys.path, so add it explicitly before importing sibling modules. -sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) -import odrp_7a # noqa: E402 -import psin_data # noqa: E402 -from report_paths import same_report_path, path_key # noqa: E402 -import world_names # noqa: E402 - -# Schema & struct hashes (measured over retail packs.rpf 0DRP + PSIN catalogues). -CATALOG_ROOT_HASH = 0x8DCB4CF5 -CATALOG_ROOT_SIZE = 192 -PRESET_BUCKET_HASH = 0x60BCB6F3 -SECONDARY_BUCKET_HASH = 0x4C70A132 -PRESET_STRUCT_HASH = 0xF795E8BA -PRESET_STRIDE = 88 -STATE_STRUCT_HASH = 0x37E52277 -STATE_STRIDE = 184 -STATE_INNER_HASH = 0x147FDAB5 -STATE_INNER_OFFSET = 0x08 -EXT_MAP_FIELD_HASH = 0xB70A22C1 -EXT_MAP_OFFSET = 0x28 # 0x37e52277 + 0x08 (0x147fdab5) + 0x20 (0xb70a22c1) -EXT_MAP_SLOT_SIZE = 16 -TAG_MAP_FIELD_HASH = 0x12F85293 -TAG_MAP_SLOT_SIZE = 24 -TAG_VALUE_BLOCK_TYPE = 0x4A - -# Extension map keys and target structs. -CULL_DRAWABLE_KEY = 0x46E1A048 # joaat("cull_drawable") -CULL_DRAWABLE_STRUCT_HASH = 0x3D780B74 -CULL_DRAWABLE_STRIDE = 16 -CULL_DRAWABLE_HASH_FIELD = 0x7DEBA6F8 - -# Well-known tag keys and preset categories. -DRAWABLE_TAG_KEYS = (0x4BFD27DD, 0x1C114E61) -HEAD_CATEGORY = 0x378AD10C -BODY_SKIN_CATEGORIES = frozenset((0x3817131D, 0x44925BFD, 0x9D283797)) - -# Synthetic anonymous map-slot struct IDs vary per file with schema emission order. -SYNTHETIC_BLOCK_MIN = 0x100 -SYNTHETIC_BLOCK_MAX = 0x1FF - -# Bounds and safety guards against malformed or cyclic inputs. -MAX_TAG_VALUES = 256 -MAX_PARENT_DEPTH = 16 -MAX_INFLATE = 64 << 20 -MAX_CONTINUATIONS = 2048 -RPF9_MAGIC = b"9FPR" -ZHDR = re.compile(rb"\x78[\x01\x5e\x9c\xda]|KB2[a-z]") - - -def decode_ptr(ptr: int) -> tuple[int, int]: - """Decode a PSIN/0DRP internal pointer into `(block_number_1based, byte_offset)`.""" - return ptr & 0xFFFFF, ptr >> 20 - - -def joaat32(text: str, *, case_sensitive: bool = False) -> int: - """32-bit Jenkins one-at-a-time hash matching RAGE name/tag hashes.""" - return world_names.joaat(text, case_sensitive=case_sensitive) - - -def murmur64(text: str) -> int: - """64-bit asset hash: low 64-bit word of MurmurHash3 x64_128 (seed 0) over UTF-8 bytes.""" - return world_names.hash64(text) - - -@dataclass(frozen=True) -class CullDrawableRef: - """One resolved `0x147fdab5` -> `0xb70a22c1` (`0x46e1a048`) -> `0x3d780b74` link.""" - - key: int - block: int - offset: int - target_type: int - drawable_hash: int - header_qword: int = 0 - - def to_dict(self) -> dict: - return { - "key": f"0x{self.key:08x}", - "block": self.block, - "offset": self.offset, - "target_type": f"0x{self.target_type:08x}", - "drawable_hash": f"{self.drawable_hash:016x}", - "header_qword": f"0x{self.header_qword:016x}", - } - - -@dataclass(frozen=True) -class StateRecord: - """One 184-byte `0x37e52277` drawable/texture state record.""" - - index: int - block: int - offset: int - state_id: int - flags: int - drawable_hash: int - albedo_hash: int - normal_hash: int - extra_hash: int - cull_drawable: int | None - cull_ref: CullDrawableRef | None - ext_map_keys: tuple[int, ...] - tags: dict[int, tuple[int, ...]] - - def to_dict(self) -> dict: - return { - "index": self.index, - "block": self.block, - "offset": self.offset, - "state_id": f"0x{self.state_id:08x}", - "flags": self.flags, - "drawable_hash": f"{self.drawable_hash:016x}", - "albedo_hash": f"{self.albedo_hash:016x}", - "normal_hash": f"{self.normal_hash:016x}", - "extra_hash": f"{self.extra_hash:016x}", - "cull_drawable": f"{self.cull_drawable:016x}" if self.cull_drawable is not None else None, - "cull_ref": self.cull_ref.to_dict() if self.cull_ref is not None else None, - "ext_map_keys": [f"0x{k:08x}" for k in self.ext_map_keys], - "tags": {f"0x{k:08x}": [f"0x{v:08x}" for v in vs] for k, vs in sorted(self.tags.items())}, - } - - -@dataclass(frozen=True) -class PresetRecord: - """One 88-byte `0xf795e8ba` preset record.""" - - block: int - index: int - preset_id: int - parent_id: int - category: int - tags: dict[int, tuple[int, ...]] - states: tuple[StateRecord, ...] - - def to_dict(self) -> dict: - return { - "block": self.block, - "index": self.index, - "preset_id": f"0x{self.preset_id:08x}", - "parent_id": f"0x{self.parent_id:08x}", - "category": f"0x{self.category:08x}", - "tags": {f"0x{k:08x}": [f"0x{v:08x}" for v in vs] for k, vs in sorted(self.tags.items())}, - "states": [s.to_dict() for s in self.states], - } - - -@dataclass(frozen=True) -class CatalogueContainer: - """Parsed `0x8dcb4cf5` ped appearance catalogue from a `0DRP` v122 or `PSIN` container.""" - - source: str - framing: str - root_block: int - root_type: int - block_count: int - presets: tuple[PresetRecord, ...] - presets_by_id: dict[int, PresetRecord] - warnings: tuple[str, ...] - stats: dict[str, int] - - def summary_dict(self) -> dict: - return { - "source": self.source, - "framing": self.framing, - "root_block": self.root_block, - "root_type": f"0x{self.root_type:08x}", - "block_count": self.block_count, - "stats": dict(self.stats), - "warnings": list(self.warnings), - } - - -@dataclass(frozen=True) -class ResolvedBinding: - """One resolved drawable/texture/cull_drawable binding from a preset state.""" - - source: str - framing: str - preset_id: int - parent_chain: tuple[int, ...] - category: int - state_index: int - match_kind: str - matched_hash: int - matched_hash_bits: int - matched_name: str | None - drawable_hash: int - albedo_hash: int - normal_hash: int - extra_hash: int - cull_drawable_hash: int | None - cull_drawable_name: str | None = None - - def to_dict(self) -> dict: - fmt = f"0x{self.matched_hash:08x}" if self.matched_hash_bits == 32 else f"{self.matched_hash:016x}" - out = { - "source": self.source, - "framing": self.framing, - "preset_id": f"0x{self.preset_id:08x}", - "parent_chain": [f"0x{p:08x}" for p in self.parent_chain], - "category": f"0x{self.category:08x}", - "state_index": self.state_index, - "match_kind": self.match_kind, - "matched_hash": fmt, - "drawable_hash": f"{self.drawable_hash:016x}", - "albedo_hash": f"{self.albedo_hash:016x}", - "normal_hash": f"{self.normal_hash:016x}", - "extra_hash": f"{self.extra_hash:016x}", - "cull_drawable_hash": ( - f"{self.cull_drawable_hash:016x}" if self.cull_drawable_hash is not None else None - ), - } - if self.matched_name is not None: - out["matched_name"] = self.matched_name - if self.cull_drawable_name is not None: - out["cull_drawable_name"] = self.cull_drawable_name - return out - - -# ---------------------------------------------------------------- container parsing - - -def _parse_0drp_blocks_state( - data: bytes | bytearray | memoryview, -) -> tuple[str, int, int, dict[int, tuple[int, memoryview]], str]: - """Parse a resource-packed `0DRP` v122 block directory. - - Returns `(status, root_block, root_type, blocks, error)` where `status` is one of: - - `"ok"`: complete block directory parsed and all virtual blocks in bounds - - `"truncated"`: valid `0DRP` v122 header, but block table or a virtual block extends past `len(data)` - - `"invalid"`: not a valid `0DRP` v122 resource or malformed table/pointers - """ - mv = memoryview(data) - hdr = odrp_7a.parse_standalone_header(mv) - if hdr is None: - return "invalid", 0, 0, {}, "not a valid standalone 0DRP/0x7a header" - bp = hdr["tables"]["q38"] - nb = hdr["blocks"] - rblk = hdr["root_objects"] - if bp + nb * 16 > len(mv): - return "truncated", rblk, 0, {}, "0DRP block directory extends past buffer end" - - blocks: dict[int, tuple[int, memoryview]] = {} - for i in range(nb): - key, size, bptr = struct.unpack_from(" (1 << 24): - return "invalid", rblk, 0, {}, f"0DRP block {i + 1} exceeds 16 MiB cap" - voff = odrp_7a.virtual_offset(bptr) - if voff is not None: - if voff + size > len(mv): - return "truncated", rblk, 0, {}, f"0DRP block {i + 1} extends past buffer end" - blocks[i + 1] = (key, mv[voff:voff + size]) - continue - if odrp_7a.physical_offset(bptr) is not None: - continue - return "invalid", rblk, 0, {}, f"0DRP block {i + 1} has invalid segment pointer 0x{bptr:x}" - - if not (1 <= rblk <= nb) or rblk not in blocks: - return "invalid", rblk, 0, {}, f"0DRP root block index {rblk} is missing or out of range (1..{nb})" - return "ok", rblk, blocks[rblk][0], blocks, "" - - -def parse_0drp_blocks( - data: bytes | bytearray | memoryview, -) -> tuple[int, int, dict[int, tuple[int, memoryview]]] | None: - """Parse a complete resource-packed `0DRP` v122 buffer into `(root_block, root_type, blocks)`.""" - status, rblk, rtype, blocks, _err = _parse_0drp_blocks_state(data) - if status != "ok": - return None - return rblk, rtype, blocks - - -def _parse_psin_blocks_state( - data: bytes | bytearray | memoryview, -) -> tuple[str, int, int, dict[int, tuple[int, memoryview]], str]: - """Parse a standalone `PSIN` container's blocks into `(status, root_block, root_type, blocks, error)`.""" - raw = bytes(data) - if len(raw) < 16 or raw[:4] != odrp_7a.PSIN_MAGIC: - return "invalid", 0, 0, {}, "not a PSIN container" - probe = odrp_7a._parse_psin_container(raw) - if probe is not None and probe.get("needs_continuation"): - return "truncated", 0, 0, {}, probe.get("error") or "PSIN container truncated" - try: - container = psin_data.Container(raw) - except (ValueError, struct.error, IndexError) as exc: - return "invalid", 0, 0, {}, str(exc) - mv = memoryview(raw) - blocks = {i + 1: (kind, mv[off:off + size]) for i, (kind, off, size) in enumerate(container.blocks)} - rblk = container.root - if not (1 <= rblk <= len(container.blocks)) or rblk not in blocks: - return "invalid", rblk, 0, {}, f"PSIN root block index {rblk} out of range" - return "ok", rblk, blocks[rblk][0], blocks, "" - - -def parse_psin_blocks( - data: bytes | bytearray | memoryview, -) -> tuple[int, int, dict[int, tuple[int, memoryview]]] | None: - """Parse a complete standalone `PSIN` container into `(root_block, root_type, blocks)`.""" - status, rblk, rtype, blocks, _err = _parse_psin_blocks_state(data) - if status != "ok": - return None - return rblk, rtype, blocks - - -# ---------------------------------------------------------------- record parsing - - -def read_tag_map( - blocks: dict[int, tuple[int, memoryview]], - map_ptr: int, - count: int, - *, - warnings: list[str] | None = None, - observed_block_types: collections.Counter | None = None, -) -> dict[int, tuple[int, ...]]: - """Read a `0x71` sorted tag map (`0x12f85293`, 24-byte slots -> `0x4a` `u32` arrays). - - Synthetic block IDs (`0x100..0x1ff`) depend on per-file schema emission order and are not - hardcoded to `0x100`. - """ - tags: dict[int, tuple[int, ...]] = {} - if not count or not map_ptr: - return tags - tb, to = decode_ptr(map_ptr) - if tb not in blocks: - if warnings is not None: - warnings.append(f"tag map points to missing block {tb}") - return tags - bk, tdata = blocks[tb] - if not (SYNTHETIC_BLOCK_MIN <= bk <= SYNTHETIC_BLOCK_MAX): - if warnings is not None: - warnings.append(f"tag map points to non-synthetic block type 0x{bk:x}") - return tags - if observed_block_types is not None: - observed_block_types[bk] += 1 - if to < 0 or to + count * TAG_MAP_SLOT_SIZE > len(tdata): - if warnings is not None: - warnings.append(f"tag map truncated at block {tb}+0x{to:x} (count={count})") - max_slots = max(0, (len(tdata) - to) // TAG_MAP_SLOT_SIZE) if to >= 0 else 0 - for j in range(min(count, max_slots)): - slot_off = to + j * TAG_MAP_SLOT_SIZE - tk, tc, _tcap, tpp = struct.unpack_from(" MAX_TAG_VALUES: - if warnings is not None: - warnings.append(f"tag key 0x{tk:08x} value count {tc} exceeds cap {MAX_TAG_VALUES}") - continue - ub, uo = decode_ptr(tpp) - if ub not in blocks or blocks[ub][0] != TAG_VALUE_BLOCK_TYPE: - if warnings is not None: - warnings.append(f"tag key 0x{tk:08x} value block {ub} missing or not 0x4a") - continue - udata = blocks[ub][1] - if uo < 0 or uo + tc * 4 > len(udata): - if warnings is not None: - warnings.append(f"tag key 0x{tk:08x} value array truncated in block {ub}+0x{uo:x}") - avail = max(0, (len(udata) - uo) // 4) if uo >= 0 else 0 - vals = tuple(struct.unpack_from(" tuple[CullDrawableRef | None, tuple[int, ...]]: - """Resolve `0x147fdab5` -> `0xb70a22c1` (`0x46e1a048` `"cull_drawable"`) -> `0x3d780b74`. - - Returns `(cull_ref, all_ext_map_keys)`. Synthetic block IDs (`0x100..0x1ff`) are matched - dynamically rather than hardcoding `0x101`. - """ - if not ext_count or not ext_ptr: - return None, () - mb, mo = decode_ptr(ext_ptr) - if mb not in blocks: - if warnings is not None: - warnings.append(f"0xb70a22c1 map points to missing block {mb}") - return None, () - mbk, mdata = blocks[mb] - if not (SYNTHETIC_BLOCK_MIN <= mbk <= SYNTHETIC_BLOCK_MAX): - if warnings is not None: - warnings.append(f"0xb70a22c1 map points to non-synthetic block type 0x{mbk:x}") - return None, () - if observed_block_types is not None: - observed_block_types[mbk] += 1 - if mo < 0 or mo + ext_count * EXT_MAP_SLOT_SIZE > len(mdata): - if warnings is not None: - warnings.append(f"0xb70a22c1 map truncated at block {mb}+0x{mo:x} (count={ext_count})") - max_slots = max(0, (len(mdata) - mo) // EXT_MAP_SLOT_SIZE) if mo >= 0 else 0 - keys: list[int] = [] - cull_ref: CullDrawableRef | None = None - for j in range(min(ext_count, max_slots)): - mk, mp = struct.unpack_from(" len(tdata): - if warnings is not None: - warnings.append(f"cull_drawable record truncated at block {tb}+0x{to:x}") - continue - header_qword, cull_hash = struct.unpack_from(" CatalogueContainer: - """Parse a `0x8dcb4cf5` ped appearance catalogue from a validated 1-based block dictionary.""" - if root_block not in blocks: - raise ValueError(f"root block {root_block} not present in block table") - root_type, root_data = blocks[root_block] - if root_type != CATALOG_ROOT_HASH: - raise ValueError(f"root type is 0x{root_type:08x}, expected 0x{CATALOG_ROOT_HASH:08x}") - - warnings: list[str] = [] - tag_block_types: collections.Counter[int] = collections.Counter() - ext_block_types: collections.Counter[int] = collections.Counter() - - # Measure preset count referenced by the root struct's two 0x60bcb6f3 buckets. - root_bucket_presets = 0 - if len(root_data) >= 96: - for slot in range(2): - cnt, _cap, _ptr = struct.unpack_from(" len(rdata): - warnings.append(f"preset 0x{pid:08x} state array truncated at block {rb}+0x{ro:x} (count={c1})") - avail = max(0, (len(rdata) - ro) // STATE_STRIDE) if ro >= 0 else 0 - for si in range(min(c1, avail)): - sbase = ro + si * STATE_STRIDE - state_id, sflags = struct.unpack_from("= MAX_PARENT_DEPTH: - warnings.append(f"parent_id chain depth reached cap ({MAX_PARENT_DEPTH}) at preset 0x{rec.preset_id:08x}") - break - cur = parent.parent_id - if depth > max_parent_depth: - max_parent_depth = depth - - state_records_in_blocks = sum( - len(data) // STATE_STRIDE for bk, data in blocks.values() if bk == STATE_STRUCT_HASH - ) - cull_records_in_blocks = sum( - len(data) // CULL_DRAWABLE_STRIDE for bk, data in blocks.values() if bk == CULL_DRAWABLE_STRUCT_HASH - ) - - stats: dict[str, int] = { - "presets": len(presets), - "root_bucket_presets": root_bucket_presets, - "duplicate_preset_ids": duplicate_preset_ids, - "presets_with_parent": presets_with_parent, - "max_parent_depth": max_parent_depth, - "parent_cycles": parent_cycles, - "unresolved_parents": unresolved_parents, - "states": states_total, - "state_records_in_blocks": state_records_in_blocks, - "states_with_drawable": states_with_drawable, - "states_with_albedo": states_with_albedo, - "states_with_normal": states_with_normal, - "states_with_extra": states_with_extra, - "states_with_tags": states_with_tags, - "states_with_cull_drawable": states_with_cull_drawable, - "cull_nonzero_hashes": cull_nonzero_hashes, - "cull_records_in_blocks": cull_records_in_blocks, - } - for bk, cnt in sorted(tag_block_types.items()): - stats[f"tag_map_block_0x{bk:x}"] = cnt - for bk, cnt in sorted(ext_block_types.items()): - stats[f"ext_map_block_0x{bk:x}"] = cnt - - return CatalogueContainer( - source=source, - framing=framing, - root_block=root_block, - root_type=root_type, - block_count=len(blocks), - presets=tuple(presets), - presets_by_id=presets_by_id, - warnings=tuple(warnings), - stats=stats, - ) - - -def parse_catalogue_strict( - data: bytes | bytearray | memoryview, - *, - source: str = "", -) -> CatalogueContainer: - """Parse one `0DRP` v122 or `PSIN` `0x8dcb4cf5` catalogue; raise `ValueError` on any format error.""" - mv = memoryview(data) - if len(mv) >= 16 and mv[:4].tobytes() == odrp_7a.PSIN_MAGIC: - status, rblk, _rtype, blocks, err = _parse_psin_blocks_state(mv) - if status != "ok": - raise ValueError(f"PSIN parse failed ({status}): {err}") - return parse_catalogue_blocks(blocks, rblk, framing="psin", source=source) - - if len(mv) >= 20 and mv[16:20].tobytes() == odrp_7a.SIGNATURE: - status, rblk, _rtype, blocks, err = _parse_0drp_blocks_state(mv) - if status != "ok": - raise ValueError(f"0DRP parse failed ({status}): {err}") - return parse_catalogue_blocks(blocks, rblk, framing="0drp", source=source) - - raise ValueError("input is neither a PSIN container nor a standalone 0DRP/0x7a resource") - - -def parse_catalogue( - data: bytes | bytearray | memoryview, - *, - source: str = "", -) -> CatalogueContainer | None: - """Parse a `0x8dcb4cf5` catalogue from a `0DRP` v122 or `PSIN` buffer, or return `None` if not one.""" - try: - return parse_catalogue_strict(data, source=source) - except ValueError: - return None - - -# ---------------------------------------------------------------- inheritance & resolution - - -def resolve_ancestor_tags( - catalogue: CatalogueContainer, - preset: PresetRecord, - tag_keys: tuple[int, ...] = DRAWABLE_TAG_KEYS, - *, - max_depth: int = MAX_PARENT_DEPTH, -) -> tuple[dict[int, tuple[int, ...]], tuple[int, ...], bool]: - """Walk `parent_id` ancestors with cycle protection until an ancestor defines one of `tag_keys`. - - Returns `(matched_tags_subset, parent_chain_traversed, hit_cycle)`. - """ - if not preset.parent_id: - return {}, (), False - visited = {preset.preset_id} - chain: list[int] = [] - cur = preset.parent_id - while cur and len(chain) < max_depth: - if cur in visited: - return {}, tuple(chain), True - parent = catalogue.presets_by_id.get(cur) - if parent is None: - break - visited.add(cur) - chain.append(cur) - found = {k: parent.tags[k] for k in tag_keys if k in parent.tags and parent.tags[k]} - if found: - return found, tuple(chain), False - cur = parent.parent_id - return {}, tuple(chain), False - - -def resolve_effective_tags( - catalogue: CatalogueContainer, - preset: PresetRecord, - *, - max_depth: int = MAX_PARENT_DEPTH, -) -> tuple[dict[int, tuple[int, ...]], tuple[int, ...], bool]: - """Merge tags along the `parent_id` chain (child keys override ancestor keys) with cycle guard.""" - visited = {preset.preset_id} - ancestors: list[PresetRecord] = [preset] - chain: list[int] = [] - hit_cycle = False - cur = preset.parent_id - while cur and len(chain) < max_depth: - if cur in visited: - hit_cycle = True - break - parent = catalogue.presets_by_id.get(cur) - if parent is None: - break - visited.add(cur) - chain.append(cur) - ancestors.append(parent) - cur = parent.parent_id - merged: dict[int, tuple[int, ...]] = {} - for rec in reversed(ancestors): - merged.update(rec.tags) - return merged, tuple(chain), hit_cycle - - -def resolve_cull_map(catalogue: CatalogueContainer) -> dict[int, list[int]]: - """Map non-zero state `drawable_hash` (`h0`) -> sorted unique `cull_drawable` hashes.""" - mapping: dict[int, set[int]] = collections.defaultdict(set) - for preset in catalogue.presets: - for state in preset.states: - if state.drawable_hash and state.cull_drawable: - mapping[state.drawable_hash].add(state.cull_drawable) - return {h0: sorted(culls) for h0, culls in sorted(mapping.items())} - - -def resolve_preset_bindings( - catalogue: CatalogueContainer, - *, - drawable_names: Iterable[str] | None = None, - filter_hashes_32: set[int] | None = None, - filter_hashes_64: set[int] | None = None, - require_textures: bool = False, - cull_only: bool = False, - max_depth: int = MAX_PARENT_DEPTH, -) -> list[ResolvedBinding]: - """Resolve drawable, texture, and `cull_drawable` bindings across all presets in `catalogue`. - - Resolution precedence per state mirrors runtime catalogue lookup: - 1. Direct preset drawable tag (`0x4bfd27dd` / `0x1c114e61`, `joaat32`). - 2. Direct state drawable tag (`0x4bfd27dd` / `0x1c114e61`, `joaat32`). - 3. Inherited ancestor drawable tag via `parent_id` chain (`joaat32`, cycle-guarded). - 4. Direct state drawable `h0` (`murmur64`). - 5. Direct `cull_drawable` target (`murmur64`, when `h0 == 0` or matched by a `cull_drawable` query). - """ - j32_names: dict[int, list[str]] = collections.defaultdict(list) - m64_names: dict[int, list[str]] = collections.defaultdict(list) - want_32: set[int] = set(filter_hashes_32 or ()) - want_64: set[int] = set(filter_hashes_64 or ()) - if drawable_names is not None: - for raw in drawable_names: - name = raw.strip() - if not name: - continue - h32 = joaat32(name) - h64 = murmur64(name) - j32_names[h32].append(name) - m64_names[h64].append(name) - want_32.add(h32) - want_64.add(h64) - filtering = bool(want_32 or want_64 or drawable_names is not None) - - out: list[ResolvedBinding] = [] - for preset in catalogue.presets: - preset_dtags = [v for tk in DRAWABLE_TAG_KEYS for v in preset.tags.get(tk, ()) if v] - inherited_tags: dict[int, tuple[int, ...]] | None = None - inherited_chain: tuple[int, ...] = () - - for state in preset.states: - if require_textures and not state.albedo_hash and not state.normal_hash: - continue - if cull_only and not state.cull_drawable: - continue - - state_dtags = [v for tk in DRAWABLE_TAG_KEYS for v in state.tags.get(tk, ()) if v] - cull_name = m64_names[state.cull_drawable][0] if state.cull_drawable in m64_names else None - - candidates: list[tuple[str, int, int, tuple[int, ...]]] = [] - for v in preset_dtags: - candidates.append(("drawable_tag", v, 32, ())) - for v in state_dtags: - if v not in preset_dtags: - candidates.append(("state_drawable_tag", v, 32, ())) - if not candidates and preset.parent_id: - if inherited_tags is None: - inherited_tags, inherited_chain, _cyc = resolve_ancestor_tags( - catalogue, preset, DRAWABLE_TAG_KEYS, max_depth=max_depth - ) - for tk in DRAWABLE_TAG_KEYS: - for v in inherited_tags.get(tk, ()): - if v: - candidates.append(("inherited_drawable_tag", v, 32, inherited_chain)) - if not candidates and state.drawable_hash: - candidates.append(("state_drawable_hash", state.drawable_hash, 64, ())) - if not candidates and state.cull_drawable: - candidates.append(("cull_drawable_hash", state.cull_drawable, 64, ())) - - matched_any = False - for kind, mhash, bits, pchain in candidates: - if filtering: - if bits == 32 and mhash not in want_32: - continue - if bits == 64 and mhash not in want_64: - continue - names = j32_names.get(mhash) if bits == 32 else m64_names.get(mhash) - if names: - for nm in names: - out.append( - ResolvedBinding( - source=catalogue.source, - framing=catalogue.framing, - preset_id=preset.preset_id, - parent_chain=pchain, - category=preset.category, - state_index=state.index, - match_kind=kind, - matched_hash=mhash, - matched_hash_bits=bits, - matched_name=nm, - drawable_hash=state.drawable_hash, - albedo_hash=state.albedo_hash, - normal_hash=state.normal_hash, - extra_hash=state.extra_hash, - cull_drawable_hash=state.cull_drawable, - cull_drawable_name=cull_name, - ) - ) - matched_any = True - else: - out.append( - ResolvedBinding( - source=catalogue.source, - framing=catalogue.framing, - preset_id=preset.preset_id, - parent_chain=pchain, - category=preset.category, - state_index=state.index, - match_kind=kind, - matched_hash=mhash, - matched_hash_bits=bits, - matched_name=None, - drawable_hash=state.drawable_hash, - albedo_hash=state.albedo_hash, - normal_hash=state.normal_hash, - extra_hash=state.extra_hash, - cull_drawable_hash=state.cull_drawable, - cull_drawable_name=cull_name, - ) - ) - matched_any = True - - # When filtering by name/hash, also match direct h0 or cull_drawable even if preset had a tag. - if filtering and not matched_any: - if state.drawable_hash and state.drawable_hash in want_64: - names = m64_names.get(state.drawable_hash) or [None] - for nm in names: - out.append( - ResolvedBinding( - source=catalogue.source, - framing=catalogue.framing, - preset_id=preset.preset_id, - parent_chain=(), - category=preset.category, - state_index=state.index, - match_kind="state_drawable_hash", - matched_hash=state.drawable_hash, - matched_hash_bits=64, - matched_name=nm, - drawable_hash=state.drawable_hash, - albedo_hash=state.albedo_hash, - normal_hash=state.normal_hash, - extra_hash=state.extra_hash, - cull_drawable_hash=state.cull_drawable, - cull_drawable_name=cull_name, - ) - ) - elif state.cull_drawable and state.cull_drawable in want_64: - names = m64_names.get(state.cull_drawable) or [None] - for nm in names: - out.append( - ResolvedBinding( - source=catalogue.source, - framing=catalogue.framing, - preset_id=preset.preset_id, - parent_chain=(), - category=preset.category, - state_index=state.index, - match_kind="cull_drawable_hash", - matched_hash=state.cull_drawable, - matched_hash_bits=64, - matched_name=nm, - drawable_hash=state.drawable_hash, - albedo_hash=state.albedo_hash, - normal_hash=state.normal_hash, - extra_hash=state.extra_hash, - cull_drawable_hash=state.cull_drawable, - cull_drawable_name=cull_name, - ) - ) - return out - - -# ---------------------------------------------------------------- source scanners - - -def _is_rpf_file(path: str) -> bool: - if not os.path.isfile(path) or os.path.getsize(path) < 4: - return False - with open(path, "rb") as fh: - return fh.read(4) == RPF9_MAGIC - - -def _inflate_at(buf: mmap.mmap | bytes, pos: int, end: int, max_inflate: int) -> tuple[bytes, int] | None: - """Inflate one complete zlib stream at `pos` inside `[pos, end)`. Returns `(data, stored_len)` or `None`.""" - d = zlib.decompressobj() - p = pos - total = 0 - chunks: list[bytes] = [] - try: - while not d.eof and p < end: - block = buf[p:min(p + (1 << 20), end)] - if not block: - break - p += len(block) - while block and not d.eof: - chunk = d.decompress(block, 1 << 20) - block = d.unconsumed_tail - if chunk: - total += len(chunk) - if total > max_inflate: - return None - chunks.append(chunk) - if not block: - break - if not d.eof: - tail = d.flush() - if tail: - total += len(tail) - if total > max_inflate: - return None - chunks.append(tail) - except zlib.error: - return None - if not d.eof or total == 0: - return None - stored = (p - pos) - len(d.unused_data) - if stored <= 0: - return None - return b"".join(chunks), stored - - -def _peek_zlib_head(buf: mmap.mmap | bytes, pos: int, end: int) -> bytes | None: - """Quickly inflate up to `0x60` bytes of a candidate zlib stream to test for `PSIN` or `0DRP` v122.""" - try: - d = zlib.decompressobj() - return d.decompress(buf[pos:min(pos + 512, end)], odrp_7a.STANDALONE_HEADER_SIZE) - except zlib.error: - return None - - -def _try_parse_candidate( - blob: bytes | bytearray, - *, - source: str, -) -> tuple[str, CatalogueContainer | None]: - """Return `("catalogue", cat)`, `("truncated", None)`, or `("skip", None)`.""" - if len(blob) >= 16 and blob[:4] == odrp_7a.PSIN_MAGIC: - status, rblk, rtype, blocks, _err = _parse_psin_blocks_state(blob) - if status == "truncated": - return "truncated", None - if status == "ok" and rtype == CATALOG_ROOT_HASH: - return "catalogue", parse_catalogue_blocks(blocks, rblk, framing="psin", source=source) - return "skip", None - - if len(blob) >= odrp_7a.STANDALONE_HEADER_SIZE and blob[16:20] == odrp_7a.SIGNATURE: - status, rblk, rtype, blocks, _err = _parse_0drp_blocks_state(blob) - if status == "truncated": - return "truncated", None - if status == "ok" and rtype == CATALOG_ROOT_HASH: - return "catalogue", parse_catalogue_blocks(blocks, rblk, framing="0drp", source=source) - return "skip", None - - return "skip", None - - -def iter_catalogues_in_file(path: str, *, max_inflate: int = MAX_INFLATE) -> Iterator[CatalogueContainer]: - """Yield a `0x8dcb4cf5` catalogue if `path` contains one (raw `0DRP`/`PSIN` or single zlib stream).""" - if os.path.getsize(path) > max_inflate: - return - with open(path, "rb") as fh: - data = fh.read() - cat = parse_catalogue(data, source=path) - if cat is not None: - yield cat - return - # Also accept a single zlib-compressed 0DRP/PSIN stream. - if len(data) >= 2 and data[0] == 0x78 and data[1] in (0x01, 0x5E, 0x9C, 0xDA): - inflated = _inflate_at(data, 0, len(data), max_inflate) - if inflated is not None: - cat = parse_catalogue(inflated[0], source=path) - if cat is not None: - yield cat - - -def _row_file_name(row: dict) -> str: - name = row.get("file") - return name if isinstance(name, str) and name else f"{row['offset']:012x}.bin" - - -def iter_catalogues_in_dir(path: str, *, max_inflate: int = MAX_INFLATE) -> Iterator[CatalogueContainer]: - """Yield all `0x8dcb4cf5` catalogues in a carved directory (joining contiguous streams when `index.json` exists).""" - manifest = os.path.join(path, "index.json") - if os.path.isfile(manifest): - try: - with open(manifest, encoding="utf-8") as fh: - doc = json.load(fh) - except (OSError, json.JSONDecodeError): - doc = None - if isinstance(doc, dict) and isinstance(doc.get("files"), list): - rows = sorted( - (r for r in doc["files"] if isinstance(r, dict) and type(r.get("offset")) is int and r["offset"] >= 0), - key=lambda r: r["offset"], - ) - i = 0 - while i < len(rows): - row = rows[i] - fname = _row_file_name(row) - fpath = os.path.join(path, fname) - if not os.path.isfile(fpath) or os.path.getsize(fpath) > max_inflate: - i += 1 - continue - with open(fpath, "rb") as fh: - head = fh.read(odrp_7a.STANDALONE_HEADER_SIZE) - if not ( - (len(head) >= 16 and head[:4] == odrp_7a.PSIN_MAGIC) - or odrp_7a.parse_standalone_header(head) is not None - ): - i += 1 - continue - buf = bytearray(head + fh.read()) - src = f"{path}:{fname}" - status, cat = _try_parse_candidate(buf, source=src) - j = i - streams = 1 - while status == "truncated" and j + 1 < len(rows) and streams <= MAX_CONTINUATIONS: - stored = rows[j].get("stored") - if type(stored) is not int or stored < 0: - break - next_off = (rows[j]["offset"] + stored + 15) & ~15 - if rows[j + 1]["offset"] != next_off: - break - nname = _row_file_name(rows[j + 1]) - npath = os.path.join(path, nname) - if not os.path.isfile(npath): - break - with open(npath, "rb") as fh: - chunk = fh.read() - if len(buf) + len(chunk) > max_inflate: - break - if (len(chunk) >= 16 and chunk[:4] == odrp_7a.PSIN_MAGIC) or ( - odrp_7a.parse_standalone_header(chunk) is not None - ): - break - buf.extend(chunk) - j += 1 - streams += 1 - status, cat = _try_parse_candidate(buf, source=src) - if status == "catalogue" and cat is not None: - yield cat - i = j + 1 - return - - for root, dirs, files in os.walk(path): - dirs.sort() - for name in sorted(files): - fpath = os.path.join(root, name) - yield from iter_catalogues_in_file(fpath, max_inflate=max_inflate) - - -def iter_catalogues_in_rpf( - path: str, - *, - start: int | None = None, - limit: int | None = None, - max_inflate: int = MAX_INFLATE, -) -> Iterator[CatalogueContainer]: - """Walk an RPF9 archive data area and yield every `0x8dcb4cf5` `0DRP` and `PSIN` catalogue. - - Uses a 96-byte zlib header peek to skip non-`PSIN`/non-`0DRP` streams without inflating them, - and joins contiguous continuation streams automatically when a catalogue spans multiple zlib blocks. - """ - file_size = os.path.getsize(path) - if file_size == 0: - raise ValueError("empty file") - with open(path, "rb") as fh: - with mmap.mmap(fh.fileno(), 0, access=mmap.ACCESS_READ) as mm: - size = len(mm) - first = struct.unpack_from("= 8 else 0 - pos = start if start is not None else first - if not 0 <= pos <= size: - raise ValueError("start offset is outside the archive") - end = min(size, pos + limit) if limit is not None else size - while pos < end: - found = ZHDR.search(mm, pos, end) - if not found: - break - s = found.start() - if mm[s:s + 3] == b"KB2": - blen = (struct.unpack_from("= 16 and head[:4] == odrp_7a.PSIN_MAGIC) - or odrp_7a.parse_standalone_header(head) is not None - ): - pos = s + 1 - continue - - inflated = _inflate_at(mm, s, end, max_inflate) - if inflated is None: - pos = s + 1 - continue - data, stored = inflated - buf = bytearray(data) - src = f"{path}@0x{s:x}" - status, cat = _try_parse_candidate(buf, source=src) - cur_end = s + stored - streams = 1 - while status == "truncated" and streams <= MAX_CONTINUATIONS: - next_off = (cur_end + 15) & ~15 - if next_off + 2 > end: - break - if not (mm[next_off] == 0x78 and mm[next_off + 1] in (0x01, 0x5E, 0x9C, 0xDA)): - break - nxt = _inflate_at(mm, next_off, end, max_inflate - len(buf)) - if nxt is None: - break - ndata, nstored = nxt - if (len(ndata) >= 16 and ndata[:4] == odrp_7a.PSIN_MAGIC) or ( - odrp_7a.parse_standalone_header(ndata) is not None - ): - break - buf.extend(ndata) - cur_end = next_off + nstored - streams += 1 - status, cat = _try_parse_candidate(buf, source=src) - if status == "catalogue" and cat is not None: - yield cat - pos = cur_end - - -def iter_catalogues( - source: str, - *, - start: int | None = None, - limit: int | None = None, - max_inflate: int = MAX_INFLATE, -) -> Iterator[CatalogueContainer]: - """Dispatch `source` (file, carved directory, or `.rpf` archive) to the matching scanner.""" - if os.path.isdir(source): - yield from iter_catalogues_in_dir(source, max_inflate=max_inflate) - elif _is_rpf_file(source): - yield from iter_catalogues_in_rpf(source, start=start, limit=limit, max_inflate=max_inflate) - elif os.path.isfile(source): - yield from iter_catalogues_in_file(source, max_inflate=max_inflate) - else: - raise FileNotFoundError(f"{source}: no such file or folder") - - -def census( - source: str, - *, - start: int | None = None, - limit: int | None = None, - max_inflate: int = MAX_INFLATE, -) -> dict: - """Collect aggregate structural counts across all `0x8dcb4cf5` catalogues in `source`.""" - totals: collections.Counter[str] = collections.Counter() - by_framing: collections.Counter[str] = collections.Counter() - tag_map_blocks: collections.Counter[str] = collections.Counter() - ext_map_blocks: collections.Counter[str] = collections.Counter() - max_parent_depth = 0 - catalogues_with_cull = 0 - catalogues_with_warnings = 0 - warning_count = 0 - - for cat in iter_catalogues(source, start=start, limit=limit, max_inflate=max_inflate): - totals["catalogues"] += 1 - by_framing[cat.framing] += 1 - if cat.stats.get("states_with_cull_drawable", 0) > 0: - catalogues_with_cull += 1 - if cat.warnings: - catalogues_with_warnings += 1 - warning_count += len(cat.warnings) - if cat.stats.get("max_parent_depth", 0) > max_parent_depth: - max_parent_depth = cat.stats["max_parent_depth"] - for k, v in cat.stats.items(): - if k == "max_parent_depth": - continue - if k.startswith("tag_map_block_"): - tag_map_blocks[k.removeprefix("tag_map_block_")] += 1 - elif k.startswith("ext_map_block_"): - ext_map_blocks[k.removeprefix("ext_map_block_")] += 1 - else: - totals[k] += v - - return { - "source": source, - "catalogues": totals["catalogues"], - "by_framing": dict(sorted(by_framing.items())), - "presets": totals["presets"], - "root_bucket_presets": totals["root_bucket_presets"], - "duplicate_preset_ids": totals["duplicate_preset_ids"], - "presets_with_parent": totals["presets_with_parent"], - "max_parent_depth": max_parent_depth, - "parent_cycles": totals["parent_cycles"], - "unresolved_parents": totals["unresolved_parents"], - "states": totals["states"], - "state_records_in_blocks": totals["state_records_in_blocks"], - "states_with_drawable": totals["states_with_drawable"], - "states_with_albedo": totals["states_with_albedo"], - "states_with_normal": totals["states_with_normal"], - "states_with_extra": totals["states_with_extra"], - "states_with_tags": totals["states_with_tags"], - "catalogues_with_cull_drawable": catalogues_with_cull, - "states_with_cull_drawable": totals["states_with_cull_drawable"], - "cull_nonzero_hashes": totals["cull_nonzero_hashes"], - "cull_records_in_blocks": totals["cull_records_in_blocks"], - "tag_map_block_types": dict(sorted(tag_map_blocks.items())), - "ext_map_block_types": dict(sorted(ext_map_blocks.items())), - "catalogues_with_warnings": catalogues_with_warnings, - "warnings": warning_count, - } - - -# ---------------------------------------------------------------- CLI - - -def _nonneg_int(text: str) -> int: - try: - value = int(text, 0) - except ValueError: - raise argparse.ArgumentTypeError("must be an integer >= 0") from None - if value < 0: - raise argparse.ArgumentTypeError("must be >= 0") - return value - - -def _pos_int(text: str) -> int: - try: - value = int(text, 0) - except ValueError: - raise argparse.ArgumentTypeError("must be an integer >= 1") from None - if value < 1: - raise argparse.ArgumentTypeError("must be >= 1") - return value - - -def _parse_hex_hash(text: str) -> tuple[int, int]: - """Parse a 32-bit or 64-bit hex hash string into `(bits, value)`.""" - s = text.strip().lower() - if s.startswith("0x"): - s = s[2:] - if not s or any(c not in "0123456789abcdef" for c in s): - raise ValueError(f"invalid hex hash: {text!r}") - val = int(s, 16) - if len(s) <= 8: - return 32, val - if len(s) <= 16: - return 64, val - raise ValueError(f"hash wider than 64 bits: {text!r}") - - -def _is_under_dir(path: str, folder: str) -> bool: - """Return True when `path` resolves to `folder` or any path beneath it.""" - folder_key = path_key(folder) - target_key = path_key(path) - try: - return os.path.commonpath([folder_key, target_key]) == folder_key - except ValueError: - return False - - -def _check_out_path(out_path: str, inputs: list[str]) -> str | None: - if os.path.isdir(out_path): - return f"{out_path} is a folder, not a file" - for inp in inputs: - if not inp: - continue - if same_report_path(inp, out_path): - return f"output must not overwrite input {inp}" - if os.path.isdir(inp) and _is_under_dir(out_path, inp): - return f"output must not be inside input folder {inp}" - parent = os.path.dirname(os.path.abspath(out_path)) - if not os.path.isdir(parent): - return f"{parent} is not a folder" - return None - - -def _write_json(path: str, payload: object) -> None: - with open(path, "w", encoding="utf-8", newline="\n") as fh: - json.dump(payload, fh, indent=1) - fh.write("\n") - - -def _cmd_census(args: argparse.Namespace) -> int: - if args.out: - err = _check_out_path(args.out, [args.source]) - if err: - print(f"ERROR: {err}", file=sys.stderr) - return 2 - if not os.path.exists(args.source): - print(f"ERROR: {args.source}: no such file or folder", file=sys.stderr) - return 2 - if (args.start is not None or args.limit is not None) and not _is_rpf_file(args.source): - print("ERROR: --start and --limit apply to an .rpf archive only", file=sys.stderr) - return 2 - try: - report = census(args.source, start=args.start, limit=args.limit, max_inflate=args.max_inflate) - except (OSError, ValueError) as exc: - print(f"ERROR: {args.source}: {exc}", file=sys.stderr) - return 2 - if args.out: - _write_json(args.out, report) - if args.json: - json.dump(report, sys.stdout, indent=1) - sys.stdout.write("\n") - return 0 - print(f"source: {report['source']}") - print(f"catalogues (0x8dcb4cf5): {report['catalogues']:,} {report['by_framing']}") - print(f"presets (0xf795e8ba): {report['presets']:,} (root buckets: {report['root_bucket_presets']:,})") - print( - f"presets with parent_id: {report['presets_with_parent']:,} " - f"(max depth: {report['max_parent_depth']}, cycles: {report['parent_cycles']}, " - f"unresolved: {report['unresolved_parents']})" - ) - print( - f"states (0x37e52277): {report['states']:,} " - f"(blocks: {report['state_records_in_blocks']:,}, " - f"h0: {report['states_with_drawable']:,}, " - f"albedo: {report['states_with_albedo']:,}, " - f"normal: {report['states_with_normal']:,})" - ) - print( - f"cull_drawable (0x3d780b74): {report['states_with_cull_drawable']:,} links in " - f"{report['catalogues_with_cull_drawable']:,} catalogues " - f"(non-zero: {report['cull_nonzero_hashes']:,}, block records: {report['cull_records_in_blocks']:,})" - ) - print(f"tag map block types: {report['tag_map_block_types']}") - print(f"ext map block types: {report['ext_map_block_types']}") - if report["warnings"]: - print(f"warnings: {report['warnings']:,} across {report['catalogues_with_warnings']:,} catalogues") - return 0 - - -def _cmd_inspect(args: argparse.Namespace) -> int: - if args.out: - err = _check_out_path(args.out, [args.file]) - if err: - print(f"ERROR: {err}", file=sys.stderr) - return 2 - if not os.path.isfile(args.file): - print(f"ERROR: {args.file}: no such file", file=sys.stderr) - return 2 - try: - with open(args.file, "rb") as fh: - data = fh.read() - if len(data) >= 2 and data[0] == 0x78 and data[1] in (0x01, 0x5E, 0x9C, 0xDA): - inflated = _inflate_at(data, 0, len(data), MAX_INFLATE) - if inflated is not None: - data = inflated[0] - cat = parse_catalogue_strict(data, source=args.file) - except (OSError, ValueError) as exc: - print(f"ERROR: {args.file}: {exc}", file=sys.stderr) - return 2 - - payload = cat.summary_dict() - if args.limit > 0: - payload["presets"] = [p.to_dict() for p in cat.presets[:args.limit]] - if args.out: - _write_json(args.out, payload) - if args.json: - json.dump(payload, sys.stdout, indent=1) - sys.stdout.write("\n") - return 0 - print(f"{cat.source} [{cat.framing}] root=block {cat.root_block} (0x{cat.root_type:08x}) blocks={cat.block_count}") - for k, v in sorted(cat.stats.items()): - print(f" {k:32} {v:,}") - if cat.warnings: - print(f" warnings ({len(cat.warnings)}):") - for w in cat.warnings[:10]: - print(f" - {w}") - if args.limit > 0: - shown = min(args.limit, len(cat.presets)) - print(f" first {shown} preset(s):") - for p in cat.presets[:shown]: - culls = sum(1 for s in p.states if s.cull_drawable is not None) - print( - f" preset 0x{p.preset_id:08x} parent=0x{p.parent_id:08x} " - f"cat=0x{p.category:08x} tags={len(p.tags)} states={len(p.states)} culls={culls}" - ) - return 0 - - -def _cmd_resolve(args: argparse.Namespace) -> int: - inputs = [args.source] - if args.names_file: - inputs.append(args.names_file) - if args.out: - err = _check_out_path(args.out, inputs) - if err: - print(f"ERROR: {err}", file=sys.stderr) - return 2 - if not os.path.exists(args.source): - print(f"ERROR: {args.source}: no such file or folder", file=sys.stderr) - return 2 - if (args.start is not None or args.limit is not None) and not _is_rpf_file(args.source): - print("ERROR: --start and --limit apply to an .rpf archive only", file=sys.stderr) - return 2 - - names: list[str] = list(args.name or ()) - if args.names_file: - try: - with open(args.names_file, encoding="utf-8") as fh: - for line in fh: - s = line.strip() - if s and not s.startswith("#"): - names.append(s) - except OSError as exc: - print(f"ERROR: {args.names_file}: {exc}", file=sys.stderr) - return 2 - - h32: set[int] = set() - h64: set[int] = set() - for raw in args.hash or (): - try: - bits, val = _parse_hex_hash(raw) - except ValueError as exc: - print(f"ERROR: {exc}", file=sys.stderr) - return 2 - if bits == 32: - h32.add(val) - else: - h64.add(val) - - bindings: list[ResolvedBinding] = [] - catalogues_scanned = 0 - try: - for cat in iter_catalogues(args.source, start=args.start, limit=args.limit, max_inflate=args.max_inflate): - catalogues_scanned += 1 - bindings.extend( - resolve_preset_bindings( - cat, - drawable_names=names if names else None, - filter_hashes_32=h32 or None, - filter_hashes_64=h64 or None, - require_textures=args.require_textures, - cull_only=args.cull_only, - ) - ) - except (OSError, ValueError) as exc: - print(f"ERROR: {args.source}: {exc}", file=sys.stderr) - return 2 - - payload = { - "source": args.source, - "catalogues_scanned": catalogues_scanned, - "matches": len(bindings), - "bindings": [b.to_dict() for b in bindings], - } - if args.out: - _write_json(args.out, payload) - if args.json: - json.dump(payload, sys.stdout, indent=1) - sys.stdout.write("\n") - return 0 - print(f"scanned {catalogues_scanned:,} catalogue(s) -> {len(bindings):,} resolved binding(s)") - for b in bindings[:50]: - label = b.matched_name or (f"0x{b.matched_hash:08x}" if b.matched_hash_bits == 32 else f"{b.matched_hash:016x}") - cull = f" cull={b.cull_drawable_hash:016x}" if b.cull_drawable_hash is not None else "" - chain = f" via={[f'0x{p:08x}' for p in b.parent_chain]}" if b.parent_chain else "" - print( - f" {label} [{b.match_kind}{chain}] preset=0x{b.preset_id:08x} " - f"h0={b.drawable_hash:016x} alb={b.albedo_hash:016x} nrm={b.normal_hash:016x}{cull}" - ) - if len(bindings) > 50: - print(f" ... ({len(bindings) - 50:,} more; use --json or --out FILE for full output)") - return 0 - - -def build_parser() -> argparse.ArgumentParser: - ap = argparse.ArgumentParser( - description="Parse and resolve 0DRP v122 and PSIN ped appearance catalogues (0x8dcb4cf5)." - ) - sub = ap.add_subparsers(dest="command", required=True) - - p_cen = sub.add_parser("census", help="count 0x8dcb4cf5 catalogues, presets, states, and cull_drawable links") - p_cen.add_argument("source", help=".pso/.0drp file, carved directory, or .rpf archive") - p_cen.add_argument("--json", action="store_true", help="print counts as JSON") - p_cen.add_argument("--out", help="write JSON report to FILE") - p_cen.add_argument("--start", type=_nonneg_int, help="first RPF archive offset to scan") - p_cen.add_argument("--limit", type=_pos_int, help="maximum RPF archive bytes to scan") - p_cen.add_argument("--max-inflate", type=_pos_int, default=MAX_INFLATE, help="inflate cap in bytes (default 64 MiB)") - p_cen.set_defaults(func=_cmd_census) - - p_ins = sub.add_parser("inspect", help="parse one standalone .pso or .0drp file strictly") - p_ins.add_argument("file", help="path to one .pso or .0drp file") - p_ins.add_argument("--json", action="store_true", help="print inspection result as JSON") - p_ins.add_argument("--out", help="write JSON result to FILE") - p_ins.add_argument("--limit", type=_nonneg_int, default=10, help="number of presets to include (default 10, 0 for summary)") - p_ins.set_defaults(func=_cmd_inspect) - - p_res = sub.add_parser("resolve", help="resolve preset inheritance, textures, and cull_drawable swaps") - p_res.add_argument("source", help=".pso/.0drp file, carved directory, or .rpf archive") - p_res.add_argument("--name", action="append", help="drawable name to filter by (repeatable)") - p_res.add_argument("--names-file", help="newline-delimited drawable name list") - p_res.add_argument("--hash", action="append", help="32-bit joaat or 64-bit murmur64 hex hash to filter by (repeatable)") - p_res.add_argument("--cull-only", action="store_true", help="keep only states carrying a cull_drawable target") - p_res.add_argument("--require-textures", action="store_true", help="keep only states with non-zero albedo or normal") - p_res.add_argument("--json", action="store_true", help="print resolved bindings as JSON") - p_res.add_argument("--out", help="write JSON result to FILE") - p_res.add_argument("--start", type=_nonneg_int, help="first RPF archive offset to scan") - p_res.add_argument("--limit", type=_pos_int, help="maximum RPF archive bytes to scan") - p_res.add_argument("--max-inflate", type=_pos_int, default=MAX_INFLATE, help="inflate cap in bytes (default 64 MiB)") - p_res.set_defaults(func=_cmd_resolve) - - return ap - - -def main(argv: list[str] | None = None) -> int: - ap = build_parser() - args = ap.parse_args(argv) - return args.func(args) - - -if __name__ == "__main__": - try: # a redirected stdout is strict ANSI code page under -I; write '?' for what it cannot encode - sys.stdout.reconfigure(errors="replace") - except (AttributeError, ValueError, OSError): - pass - sys.exit(main()) diff --git a/tools/pk16_diff.py b/tools/pk16_diff.py deleted file mode 100644 index b7df85388..000000000 --- a/tools/pk16_diff.py +++ /dev/null @@ -1,613 +0,0 @@ -r"""Differential fuzzing of packed and 16-bit integer VALU (v_pk_* integer ops, 16-bit VOP3 integer ops). Standard -library only. - -Generates seeded straight-line programs of 16-bit integer vector instructions, one lane, runs them through - - * the reference below, written from the RDNA2 ISA guide's pseudocode for each opcode, and - * tools/rdna2spirv.py, executing the SPIR-V with tests/semantic/spirv_mini_interp.py (lane 0 of a wave32), - -and compares four exported words bit for bit (v8..v11). The reference does not share code with the translator, with -tools/cpu_ref.py or with the other fuzzers. tools/valu_fuzz.py --family f16 runs some of the same opcodes on the GPU -with VGPR sources; this one adds the packed add/sub/mul/min/max/mad, the signed add/sub, min3/max3/med3 and mad, -clamp, and SGPR, inline-constant and literal sources in every position the encoding allows. - -What is modelled, per instruction: - * v_pk_* (VOP3P, OPS_PK): each result half is the op on the halves its sources select: op_sel bit i picks the - half of source i for the low result, op_sel_hi bit i for the high result (default op_sel:[0,..], - op_sel_hi:[1,..]). clamp saturates the exact result of add/sub/mad to [0, 0xffff] or [-32768, 32767]; - without it the result wraps to 16 bits. Shift amounts are their low 4 bits. - * 16-bit VOP3 ops (OPS_16): op_sel bits 0..n-1 pick source halves, bit n (the last) the destination half. The - result is written to that half and the other half of vD is kept. clamp as above (v_add_nc_*16, v_sub_nc_*16, - v_mad_*16). On GFX10 these are VOP3 only: the VOP2 forms of v_mul_lo_u16, v_min/max_u16/i16 and the 16-bit - shifts do not exist (the assembler refuses v_mul_lo_u16_e32). LLVM prints their VOP3 form without a suffix - and the translator tells it from a VOP2 write (which zeroes the high half) by the listing's encoding bytes. - A program here has no encodings, so these are written with _e64. - * sources: VGPRs v0..v7 and v12..v19, SGPRs s4..s19, integer inline constants -16..64, float inline constants - (0.5, 1.0, 2.0, 4.0, their negatives, 1/(2*pi)) and literals, at most one literal and two scalar values per - instruction (the GFX10 constant bus). A constant is its 32-bit value split into halves like a register: -16 is - 0xfff0 / 0xffff, 1.0 is 0x0000 / 0x3f80 (its f32 bits, not the f16 constant of the f16 ops), a literal of a - 16-bit VOP3 op has 16 bits (the assembler rejects a wider one), so its high half is 0. -Every rule was checked against an RDNA2 GPU (AMD Radeon iGPU, gfx1036, Windows driver 26.10.1) with --oracle hw. - -Not generated: neg_lo/neg_hi on the integer packed ops (the translator rejects them, their meaning on integers is -unmeasured), clamp on min/max/mul_lo/shifts, DPP and SDWA forms (tools/sdwa_diff.py), v_mad_u32_u16 and the other -16x16->32 ops (tools/vint_diff.py), v_dot* (#2229), f16 ops (tools/valu_fuzz.py --family f16). - -Known divergences (KNOWN_DIVERGENCES): by default the generator leaves out the forms where the translator is known to -differ from the hardware, so that a run shows new problems only; --known puts them back (a hardware-only run always -has them): - * pk-const-hi: a constant (inline or literal) in a packed add/sub/mul_lo/min/max/mad source whose high half - op_sel or op_sel_hi reads. The translator raises Unsupported (counted as a skip); #2224 removes that. - -With --oracle hw the same programs also run natively on an AMD GPU (tools/hw_oracle/), one lane of a wave32 compute -dispatch, and the four words are compared with the reference: that validates the reference itself. Without the -oracle tools the run exits 77. - -Usage: - python -I tools/pk16_diff.py [--programs N] [--seed S] [--max-ops N] [--ops v_pk_mad_u16,v_med3_i16] - python -I tools/pk16_diff.py --no-literals # sources without literals - python -I tools/pk16_diff.py --known # also the forms in KNOWN_DIVERGENCES - python -I tools/pk16_diff.py --oracle hw # hardware vs reference only - python -I tools/pk16_diff.py --oracle translator,hw - python -I tools/pk16_diff.py --list-ops - python -I tools/pk16_diff.py --self-test - -Exit 0 when every program matches, 1 on a mismatch (the shortest failing program is printed after removing -instructions that do not matter), 2 on a harness error, 77 when the requested hardware oracle is unavailable. -Skips are counted with their reasons. -""" -import argparse -import gc -import os -import random -import re -import struct -import sys -import tempfile -import warnings - -HERE = os.path.dirname(os.path.abspath(__file__)) -sys.dont_write_bytecode = True -if HERE not in sys.path: - sys.path.insert(0, HERE) -SEM_DIR = os.path.join(os.path.dirname(HERE), "tests", "semantic") -if SEM_DIR not in sys.path: - sys.path.insert(0, SEM_DIR) - -M16 = 0xFFFF -M32 = 0xFFFFFFFF -STUB_DXBC = b"DXBC" + bytes(24) + struct.pack(" (nsrc, fn on 16-bit source halves -> exact integer, clamp fn or None). The result keeps its low 16 bits. -OPS_PK = { - "v_pk_add_u16": (2, lambda a, b: a + b, satu), - "v_pk_add_i16": (2, lambda a, b: sx16(a) + sx16(b), sati), - "v_pk_sub_u16": (2, lambda a, b: a - b, satu), - "v_pk_sub_i16": (2, lambda a, b: sx16(a) - sx16(b), sati), - "v_pk_mul_lo_u16": (2, lambda a, b: a * b, None), - "v_pk_min_u16": (2, min, None), - "v_pk_max_u16": (2, max, None), - "v_pk_min_i16": (2, lambda a, b: min(sx16(a), sx16(b)), None), - "v_pk_max_i16": (2, lambda a, b: max(sx16(a), sx16(b)), None), - "v_pk_lshlrev_b16": (2, lambda a, b: b << (a & 15), None), - "v_pk_lshrrev_b16": (2, lambda a, b: b >> (a & 15), None), - "v_pk_ashrrev_i16": (2, lambda a, b: sx16(b) >> (a & 15), None), - "v_pk_mad_u16": (3, lambda a, b, c: a * b + c, satu), - "v_pk_mad_i16": (3, lambda a, b, c: sx16(a) * sx16(b) + sx16(c), sati), -} -PK_SHIFTS = ("v_pk_lshlrev_b16", "v_pk_lshrrev_b16", "v_pk_ashrrev_i16") -OPS_16 = { - "v_add_nc_u16": (2, lambda a, b: a + b, satu), - "v_sub_nc_u16": (2, lambda a, b: a - b, satu), - "v_add_nc_i16": (2, lambda a, b: sx16(a) + sx16(b), sati), - "v_sub_nc_i16": (2, lambda a, b: sx16(a) - sx16(b), sati), - "v_mul_lo_u16": (2, lambda a, b: a * b, None), - "v_min_u16": (2, min, None), - "v_max_u16": (2, max, None), - "v_min_i16": (2, lambda a, b: min(sx16(a), sx16(b)), None), - "v_max_i16": (2, lambda a, b: max(sx16(a), sx16(b)), None), - "v_lshlrev_b16": (2, lambda a, b: b << (a & 15), None), - "v_lshrrev_b16": (2, lambda a, b: b >> (a & 15), None), - "v_ashrrev_i16": (2, lambda a, b: sx16(b) >> (a & 15), None), - "v_min3_u16": (3, min, None), - "v_max3_u16": (3, max, None), - "v_med3_u16": (3, med3, None), - "v_min3_i16": (3, lambda a, b, c: min(sx16(a), sx16(b), sx16(c)), None), - "v_max3_i16": (3, lambda a, b, c: max(sx16(a), sx16(b), sx16(c)), None), - "v_med3_i16": (3, lambda a, b, c: med3(sx16(a), sx16(b), sx16(c)), None), - "v_mad_u16": (3, lambda a, b, c: a * b + c, satu), - "v_mad_i16": (3, lambda a, b, c: sx16(a) * sx16(b) + sx16(c), sati), -} -# GFX10 has only the VOP3 encoding of these (VOP2 names on earlier chips). LLVM prints them without a suffix and the -# translator then tells VOP3 from VOP2 by the listing's encoding bytes; a program here has none, so it says _e64. -E64 = ("v_mul_lo_u16", "v_min_u16", "v_max_u16", "v_min_i16", "v_max_i16", "v_lshlrev_b16", "v_lshrrev_b16", - "v_ashrrev_i16") -ALL_OPS = sorted(OPS_PK) + sorted(OPS_16) - -KNOWN = False # also generate the forms in KNOWN_DIVERGENCES (--known; always on for a hardware-only run) -LITERALS = True -KNOWN_DIVERGENCES = { - "pk-const-hi": "a constant in a packed add/sub/mul_lo/min/max/mad source whose high half op_sel or op_sel_hi " - "reads: the translator raises Unsupported, #2224 reads the constant's 32-bit value", -} - - -# ---- program generation ------------------------------------------------------------------------------------- - -def rand_value(rng): - r = rng.random() - if r < 0.5: - return rng.choice(HALVES) | (rng.choice(HALVES) << 16) - if r < 0.6: - return rng.randrange(0, 64) - return rng.getrandbits(32) - - -def is_const(tok): - return not re.fullmatch(r"[vs]\d+", tok) - - -class Gen: - def __init__(self, rng): - self.r = rng - - def vreg(self): - return f"v{self.r.choice(VREGS)}" - - def const(self, lit_ok, lit16): - r = self.r - k = r.random() - if k < 0.25: - return r.choice(tuple(INLINE_F)) - if k < 0.6 or not lit_ok: - return str(r.randint(-16, 64)) - v = rand_value(r) & (M16 if lit16 else M32) - if v <= 64: - v = 0x1234 if lit16 else 0x12345678 - return f"0x{v:x}" - - def srcs(self, n, lit16, const_ok): - """n sources: at most one literal and two scalar values (the literal counted among them). const_ok[i]: a - constant may go in source i.""" - r = self.r - out, bus, lit = [], set(), False - for i in range(n): - k = r.random() - if k < 0.5: - out.append(self.vreg()) - elif k < 0.75 or not const_ok[i]: - s = f"s{r.choice(SREGS)}" - if s not in bus and len(bus) >= 2: - out.append(self.vreg()) - continue - bus.add(s) - out.append(s) - else: - c = self.const(LITERALS and not lit and len(bus) < 2, lit16) - if c.startswith("0x"): - lit = True - bus.add("lit") - out.append(c) - return out - - def op(self, ops): - r = self.r - name = r.choice(ops) - d = r.choice(VREGS) - if name in OPS_PK: - n, _, cl = OPS_PK[name] - sel = [int(r.random() < 0.3) for _ in range(n)] - hi = [int(r.random() < 0.7) for _ in range(n)] - free = KNOWN or name in PK_SHIFTS - srcs = self.srcs(n, False, [free or not (sel[i] or hi[i]) for i in range(n)]) - line = f"{name} v{d}, {', '.join(srcs)}" - if any(sel): - line += f" op_sel:[{','.join(map(str, sel))}]" - if not all(hi): - line += f" op_sel_hi:[{','.join(map(str, hi))}]" - if cl and r.random() < 0.3: - line += " clamp" - return [line] - n, _, cl = OPS_16[name] - line = f"{name}{'_e64' if name in E64 else ''} v{d}, {', '.join(self.srcs(n, True, [True] * n))}" - sel = [int(r.random() < 0.3) for _ in range(n + 1)] - if any(sel): - line += f" op_sel:[{','.join(map(str, sel))}]" - if cl and r.random() < 0.3: - line += " clamp" - return [line] - - -def seeds(rng): - return ([f"v_mov_b32_e32 v{v}, 0x{rand_value(rng):x}" for v in VREGS] - + [f"s_mov_b32 s{s}, 0x{rand_value(rng):x}" for s in SREGS]) - - -def observe(regs): - return [f"v_mov_b32_e32 v{8 + i}, v{r}" for i, r in enumerate(regs)] - - -def generate(rng, n_ops, ops): - gen = Gen(rng) - body = [] - for _ in range(n_ops): - body += gen.op(ops) - written = [] - for line in reversed(body): - dst = int(line.split()[1].rstrip(",")[1:]) - if dst not in written: - written.append(dst) - regs = written[:4] - regs += [rng.choice(VREGS) for _ in range(4 - len(regs))] - return seeds(rng) + body + observe(regs) - - -# ---- the reference interpreter -------------------------------------------------------------------------------- - -_MOD = re.compile(r"\s+(op_sel|op_sel_hi):\[([01,]+)\]|\s+(clamp)\b") - - -def parse(rest): - """Operands and modifiers of one instruction.""" - mods = {} - for m in _MOD.finditer(rest): - if m.group(3): - mods["clamp"] = True - else: - mods[m.group(1)] = [int(x) for x in m.group(2).split(",")] - rest = _MOD.sub("", rest) - return [a.strip() for a in rest.split(",")], mods - - -def value(tok, st): - if re.fullmatch(r"v\d+", tok): - return st["v"].get(int(tok[1:]), 0) - if re.fullmatch(r"s\d+", tok): - if tok not in st["s"]: - raise RefError(f"{tok} read before it is written") - return st["s"][tok] - if tok in INLINE_F: - return INLINE_F[tok] - return int(tok, 0) & M32 - - -def half(v, hi): - return (v >> 16) & M16 if hi else v & M16 - - -def reference(lines): - """Run the program; returns the four exported words.""" - st = {"v": {}, "s": {}} - for line in lines: - op, _, rest = line.partition(" ") - args, mods = parse(rest) - if op == "s_mov_b32": - st["s"][args[0]] = value(args[1], st) - continue - d = int(args[0][1:]) - vals = [value(a, st) for a in args[1:]] - if op == "v_mov_b32_e32": - st["v"][d] = vals[0] - continue - if op in OPS_PK: - n, fn, cl = OPS_PK[op] - out = 0 - for k, sel in enumerate((mods.get("op_sel", [0] * n), mods.get("op_sel_hi", [1] * n))): - r = fn(*[half(v, sel[i]) for i, v in enumerate(vals)]) - if mods.get("clamp") and cl: - r = cl(r) - out |= (r & M16) << (16 * k) - st["v"][d] = out - continue - op = op[:-4] if op.endswith("_e64") and op[:-4] in E64 else op - if op not in OPS_16: - raise RefError(f"{op} is not modelled") - n, fn, cl = OPS_16[op] - sel = mods.get("op_sel", [0] * (n + 1)) - r = fn(*[half(v, sel[i]) for i, v in enumerate(vals)]) - if mods.get("clamp") and cl: - r = cl(r) - old = st["v"].get(d, 0) - st["v"][d] = ((old & M16) | ((r & M16) << 16)) if sel[n] else ((old & 0xFFFF0000) | (r & M16)) - return [st["v"].get(8 + i, 0) for i in range(4)] - - -# ---- the translator side ----------------------------------------------------------------------------------- - -def translated(lines, name="ps_pk16"): - """Translate and execute; returns the four exported words, or raises Skip.""" - import rdna2spirv - from spirv_mini_interp import run_fragment - with tempfile.TemporaryDirectory(prefix="pk16-diff-") as tmp: - dis = os.path.join(tmp, "disasm") - os.mkdir(dis) - path = os.path.join(dis, name + ".s") - with open(path, "w", encoding="utf-8", newline="\n") as f: - f.write(f"; {name} pk16_diff case\n") - for line in lines: - f.write("\t" + line + "\n") - f.write("\texp mrt0 v8, v9, v10, v11 done vm\n\ts_endpgm\n") - with open(os.path.join(tmp, name + ".dxbc"), "wb") as f: - f.write(STUB_DXBC) - try: - with warnings.catch_warnings(): - warnings.simplefilter("ignore", ResourceWarning) - spvasm = rdna2spirv.translate(path) - gc.collect() - except rdna2spirv.Unsupported as e: - raise Skip(f"translator unsupported: {e}") from None - try: - out = run_fragment(spvasm) - except Exception as e: # noqa: BLE001 - an interpreter gap is a counted skip, never a pass - raise Skip(f"mini_interp: {type(e).__name__}: {str(e)[:80]}") from None - return [w & M32 for w in out["%out_mrt0"]] - - -def hw_kernel(lines, wave=32): - """A raw kernel for tools/hw_oracle: the program on one lane, then v8..v11 stored at the output pointer. wave 64 - runs it in a wave64 wave with the lane masks as 64-bit pairs.""" - from hw_oracle import asm - if wave == 64: - import vk_fuzz_run - lines = [vk_fuzz_run.wave64_text(ln) for ln in lines] - return asm.Kernel(list(lines) + ["v_mov_b32 v0, 0", "global_store_b128 v0, v[8:11], s[2:3]", "s_endpgm"], - wave=wave, threads=1, words=4, raw=True) - - -# ---- comparison, shrinking, the run -------------------------------------------------------------------------- - -def _diff(lines, want, got, label): - bad = [k for k in range(4) if want[k] != got[k]] - if not bad: - return None - i = bad[0] - return f"word {i} ({lines[-N_OBS + i].split(', ')[1]}): reference 0x{want[i]:08x}, {label} 0x{got[i]:08x}" - - -def check(lines, backends=("translator",), hw=None): - """None on a match, else a description. Raises Skip (every backend skipped) / RefError. - hw is the hardware result for this program (four words or a str reason), or a callable lines -> that.""" - want = reference(lines) - problems, skips = [], [] - if "translator" in backends: - try: - problems.append(_diff(lines, want, translated(lines), "translated")) - except Skip as e: - skips.append(e) - if "hw" in backends: - got = hw(lines) if callable(hw) else hw - if isinstance(got, str): - skips.append(Skip(f"hardware: {got}")) - else: - problems.append(_diff(lines, want, got, "hardware")) - if skips and len(skips) == len(backends): - raise skips[0] - return "; ".join(p for p in problems if p) or None - - -def shrink(lines, check_fn=check): - """Observe one register if that still fails, drop instructions while the program still mismatches, then the - seeds of registers nothing reads.""" - def fails(trial): - try: - return bool(check_fn(trial)) - except (Skip, RefError): - return False - seed, body, obs = lines[:N_SEED], lines[N_SEED:-N_OBS], lines[-N_OBS:] - for line in obs: - one = [line.replace(line.split()[1], f"v{8 + i},") for i in range(4)] - if fails(seed + body + one): - obs = one - break - changed = True - while changed: - changed = False - for i in range(len(body) - 1, -1, -1): - trial = body[:i] + body[i + 1:] - if fails(seed + trial + obs): - body, changed = trial, True - used = set() - for line in body: - used |= set(re.findall(r"\b[vs]\d+\b", line)) # a 16-bit write keeps the other half of vD: it reads vD - for line in obs: - used |= set(re.findall(r"\b[vs]\d+\b", line.partition(" ")[2])) - seed = [line for line in seed if line.split()[1].rstrip(",") in used] - return seed + body + obs - - -def run_suite(programs, seed, max_ops, ops, backends=("translator",), oracle=None, wave=32, build=None, work=None, - vk_constants=False): - counts = {"pass": 0, "mismatch": 0, "skip": {}, "vk": {}, "vk_failures": []} - failures = [] - rng = random.Random(seed) - progs = [generate(rng, rng.randrange(1, max_ops + 1), ops) for _ in range(programs)] - hw = oracle.run([hw_kernel(p, wave) for p in progs]) if "hw" in backends else [None] * programs - if "vk" in backends: - import vk_fuzz_run - counts["vk"], counts["vk_failures"] = vk_fuzz_run.judge(progs, hw, vk_fuzz_run.exact_verdict, wave=wave, - build=build, work_parent=work, opaque=not vk_constants) - backends = tuple(b for b in backends if b != "vk") - for i, lines in enumerate(progs): - try: - problem = check(lines, backends, hw[i]) - except Skip as e: - counts["skip"][str(e)] = counts["skip"].get(str(e), 0) + 1 - continue - if problem is None: - counts["pass"] += 1 - continue - counts["mismatch"] += 1 - failures.append((i, problem, lines)) - return counts, failures - - -def self_test(): - """Harness canaries: a hand program matches, the reference gives hand-worked values, a bad form is a skip.""" - base = [f"v_mov_b32_e32 v{v}, 0x{0x00010001 * v:x}" for v in VREGS] + [f"s_mov_b32 s{s}, {s}" for s in SREGS] - body = ["v_pk_add_u16 v1, v2, s4 op_sel:[1,0] op_sel_hi:[0,0]", # lo: 2 + 4, hi: 2 + 4 - "v_pk_mad_i16 v3, v3, -1, v5 op_sel_hi:[1,0,1] clamp", # -1 in both halves: 5 - 3 - "v_mad_u16 v4, v6, 0x8000, v7 op_sel:[0,0,0,1] clamp", # 6 * 0x8000 + 7 saturates; high half - "v_max3_i16 v2, v2, -16, s5 op_sel:[0,0,0,0]"] - lines = base + body + observe([1, 3, 4, 2]) - ok = check(lines) is None - worked = reference(lines) == [0x00060006, 0x00020002, 0xFFFF0004, 0x00020005] - try: - translated(base + ["v_pk_add_u16_sdwa_dpp v1, v2, v3"] + observe([1, 2, 3, 4])) - skipped = False - except Skip: - skipped = True - print(f"self-test: match {ok}, hand values {worked}, unsupported form skipped {skipped}") - return ok and worked and skipped - - -def main(argv=None): - ap = argparse.ArgumentParser(description="Packed and 16-bit integer VALU differential fuzzing.") - ap.add_argument("--programs", type=int, default=300) - ap.add_argument("--seed", type=int, default=1) - ap.add_argument("--max-ops", type=int, default=6) - ap.add_argument("--ops", default=None, help="comma-separated opcodes (--list-ops)") - ap.add_argument("--no-literals", action="store_true", help="no literal sources") - ap.add_argument("--list-ops", action="store_true") - ap.add_argument("--self-test", action="store_true") - ap.add_argument("--all-failures", action="store_true", help="print every failing program, not just the first") - ap.add_argument("--known", action="store_true", - help="also generate the forms where the translator is known to differ (KNOWN_DIVERGENCES; " - "always on with --oracle hw alone)") - ap.add_argument("--oracle", default="translator", - help="comma-separated comparison targets: translator (default), hw (natively on an AMD GPU; see " - "tools/hw_oracle/). 'hw' alone compares the hardware with the reference only") - ap.add_argument("--hw-arch", default=None, help="GPU architecture to assemble for (default: detected)") - ap.add_argument("--wave", type=int, choices=(32, 64), default=32, - help="the wave size of the hardware kernels and of the vk programs (64 needs native 64-wide " - "subgroups; lane 0 is judged)") - ap.add_argument("--build", default=os.path.join(os.path.dirname(HERE), "runtime", "build"), - help="with vk: the folder with vk_compute_test") - ap.add_argument("--vk-constants", action="store_true", - help="with vk: keep the seeds as literal v_mov_b32 constants (the driver may fold them)") - ap.add_argument("--work", default=None, help="with vk: a folder for the temporary files (VK_FUZZ_KEEP=1 keeps them)") - a = ap.parse_args(argv) - if a.programs < 1 or a.max_ops < 1: - ap.error("--programs and --max-ops must be at least 1") - backends = tuple(dict.fromkeys(t.strip() for t in a.oracle.split(","))) - if not backends or any(t not in ("translator", "hw", "vk") for t in backends): - ap.error("--oracle takes translator, hw, vk (with hw) or a comma-separated mix") - if "vk" in backends and "hw" not in backends: - ap.error("--oracle vk judges the translated programs against the hardware's words: use --oracle hw,vk") - global KNOWN, LITERALS - KNOWN = a.known or backends == ("hw",) - LITERALS = not a.no_literals - if a.list_ops: - for name in ALL_OPS: - if name in OPS_PK: - n, _, cl = OPS_PK[name] - print(f"{name:18} VOP3P, {n} sources, op_sel/op_sel_hi{', clamp' if cl else ''}") - else: - n, _, cl = OPS_16[name] - print(f"{name:18} VOP3, {n} sources, op_sel (sources and destination half){', clamp' if cl else ''}") - return 0 - if a.self_test: - return 0 if self_test() else 1 - if a.ops is not None: - tokens = [t.strip() for t in a.ops.split(",")] - if not any(tokens) or any(not t for t in tokens): - ap.error("--ops must be a comma-separated list of opcodes") - ops = sorted(set(tokens)) - else: - ops = list(ALL_OPS) - unknown = [o for o in ops if o not in ALL_OPS] - if unknown: - ap.error("unknown ops: " + ", ".join(unknown)) - oracle = None - if "hw" in backends: - from hw_oracle import runner - try: - oracle = runner.open_oracle(arch=a.hw_arch) - except runner.Unavailable as e: - print(f"hardware oracle unavailable: {e}") - return 77 - print(f"hardware oracle: {oracle.device}") - try: - counts, failures = run_suite(a.programs, a.seed, a.max_ops, ops, backends, oracle, a.wave, a.build, a.work, - a.vk_constants) - vk_bad = counts.pop("vk_failures") - skips = sum(counts["skip"].values()) - print(f"{a.programs} programs (seed {a.seed}, {'+'.join(backends)}{', known' if KNOWN else ''}): " - f"{counts['pass']} pass, {counts['mismatch']} mismatch, {skips} skipped") - for reason, n in sorted(counts["skip"].items(), key=lambda kv: -kv[1]): - print(f" skip x{n}: {reason}") - - want_vk = "vk" in backends - if want_vk: - print(f"translated on the Vulkan GPU (wave{a.wave}) against the hardware: " - + ", ".join(f"{k} {n}" for k, n in sorted(counts["vk"].items(), key=lambda kv: kv[0].startswith("skip")))) - for i, detail, lines in vk_bad[: None if a.all_failures else 3]: - print(f"VK MISMATCH program {i}: {detail}") - print("\n".join("\t" + line for line in lines)) - backends = tuple(b for b in backends if b != "vk") - - def check_fn(lines): - return check(lines, backends, (lambda l: oracle.run([hw_kernel(l, a.wave)])[0]) if oracle else None) - for i, problem, lines in failures[: None if a.all_failures else 1]: - small = shrink(lines, check_fn) - print(f"MISMATCH program {i}: {check_fn(small) or problem}") - print("\n".join("\t" + line for line in small)) - except (RefError, RuntimeError) as e: - print(f"harness error: {e}") - return 2 - finally: - if oracle: - oracle.close() - if failures or vk_bad: - return 1 - if not counts["pass"]: # nothing was compared: every program was skipped - print("no program ran: every one was skipped") - return 2 - if want_vk: - import vk_fuzz_run - if vk_fuzz_run.all_skipped(counts["vk"]): - print("no Vulkan program ran: every one was skipped") - return 2 - return 0 - - -if __name__ == "__main__": - try: # a redirected stdout is strict ANSI code page under -I; write '?' for what it cannot encode - sys.stdout.reconfigure(errors="replace") - except (AttributeError, ValueError, OSError): - pass - sys.exit(main()) diff --git a/tools/pk_int16_clamp_probe.py b/tools/pk_int16_clamp_probe.py deleted file mode 100644 index f647635b7..000000000 --- a/tools/pk_int16_clamp_probe.py +++ /dev/null @@ -1,420 +0,0 @@ -r"""Measure RDNA2 VOP3P clamp behavior on v_pk_mul_lo_u16 and v_pk_{max,min}_{u16,i16}. Standard library only. - -`v_pk_add_{u16,i16}`, `v_pk_sub_{u16,i16}`, and `v_pk_mad_{u16,i16}` saturate per 16-bit half when `clamp` is set. -For `v_pk_mul_lo_u16`, `v_pk_max_u16`, `v_pk_min_u16`, `v_pk_max_i16`, and `v_pk_min_i16`, running this probe natively -on RDNA2 (`gfx1036`) across wave32 and wave64 verifies whether VOP3P `clamp` is a hardware no-op (notably whether -overflowing `v_pk_mul_lo_u16 clamp` wraps modulo 2^16 rather than saturating to 0xFFFF), alongside `v_pk_add_u16` as a -positive saturation control. - -Usage: - python -I tools/pk_int16_clamp_probe.py [--waves 32,64] [--ops ...] [--hw-arch gfx1036] [--json out.json] - python -I tools/pk_int16_clamp_probe.py --self-test - -Exit 0 when all hardware results match the model across requested ops/waves (with wave32 and wave64 agreeing bit-for-bit, -and plain vs clamp matching bit-for-bit on all five target ops while differing on overflowing v_pk_add_u16), 1 on a -model mismatch or wave32/wave64 difference or control failure, 2 on a harness/CLI error, and 77 when the hardware -oracle is unavailable or the GPU is not GFX10. Nothing here reads game files. -""" -import argparse -from dataclasses import dataclass -import json -import os -import sys - -HERE = os.path.dirname(os.path.abspath(__file__)) -sys.dont_write_bytecode = True -if HERE not in sys.path: - sys.path.insert(0, HERE) - -TARGET_OPS: tuple[str, ...] = ( - "v_pk_mul_lo_u16", - "v_pk_max_u16", - "v_pk_min_u16", - "v_pk_max_i16", - "v_pk_min_i16", -) -CONTROL_OPS: tuple[str, ...] = ("v_pk_add_u16",) -OPS: tuple[str, ...] = TARGET_OPS + CONTROL_OPS -CLAMP_MODES: tuple[bool, ...] = (False, True) - - -@dataclass(frozen=True) -class Case: - name: str - src0: int - src1: int - src0_asm: str | None = None - src1_asm: str | None = None - sel: tuple[int, int] = (0, 0) - selhi: tuple[int, int] = (1, 1) - alias: str | None = None # "src0" | "src1" | None - sgpr0: bool = False - - -CASES: tuple[Case, ...] = ( - Case("zero_zero", 0x00000000, 0x00000000), - Case("u16_max_x_max", 0xFFFFFFFF, 0xFFFFFFFF), - Case("u16_max_pair_2", 0xFFFFFFFF, 0x00020002), - Case("u16_hi_overflow_lo_exact", 0xFFFF0003, 0x00030005), - Case("i16_min_edges", 0x80008001, 0x7FFF8000), - Case("i16_signed_boundaries", 0x80007FFF, 0xFFFF0001), - Case("i16_neg_vs_pos", 0xFFFE8005, 0x00027FFE), - Case("mixed_halves", 0x12345678, 0x9ABCDEF0), - Case("pow2_overflow_wrap", 0x02000100, 0x01000200), - Case("carry_boundary", 0x01010100, 0x01000101), - Case("u16_diff_overflow", 0xFFFF00FF, 0xFFFF0101), - Case("half_max_minus1", 0x7FFE8002, 0x7FFF8001), - Case("sel_swap_both", 0x01000200, 0x03000100, sel=(1, 1), selhi=(0, 0)), - Case("sel_cross_01_10", 0x80007FFF, 0x7FFE8001, sel=(0, 1), selhi=(1, 0)), - Case("sel_broadcast_lo", 0x02000300, 0x04000500, sel=(0, 0), selhi=(0, 0)), - Case("sel_broadcast_hi", 0xFFFF0002, 0x0003FFFF, sel=(1, 1), selhi=(1, 1)), - Case("sel_mixed_sign", 0xFF800080, 0x0090FF70, sel=(1, 0), selhi=(0, 1)), - Case("inline_neg1_vgpr", 0xFFFFFFFF, 0x02000002, src0_asm="-1", sel=(0, 0), selhi=(1, 1)), - Case("inline_neg16_vgpr", 0xFFFFFFF0, 0x00108000, src0_asm="-16", sel=(1, 0), selhi=(0, 1)), - Case("inline_5_vgpr", 0x00000005, 0x10004000, src0_asm="5", sel=(0, 0), selhi=(1, 1)), - Case("inline_64_vgpr", 0x00000040, 0x08000400, src0_asm="64", sel=(0, 0), selhi=(1, 1)), - Case("vgpr_literal_overflow", 0x02000100, 0x02000400, src1_asm="0x02000400", sel=(0, 0), selhi=(1, 1)), - Case("literal_vgpr_mixed", 0x80017FFF, 0xFFFE0003, src0_asm="0x80017fff", sel=(1, 0), selhi=(0, 1)), - Case("sgpr_vgpr_mixed", 0x0300FFFE, 0x02000100, sel=(0, 1), selhi=(1, 0), sgpr0=True), - Case("dst_alias_src0", 0x02007FFF, 0x01008000, alias="src0"), - Case("dst_alias_src1", 0xFFFF0003, 0x0002FFFF, alias="src1"), -) - - -def _s16(x: int) -> int: - x &= 0xFFFF - return x - 0x10000 if (x & 0x8000) else x - - -def expected_pk_int16( - op: str, - src0: int, - src1: int, - *, - sel: tuple[int, int] = (0, 0), - selhi: tuple[int, int] = (1, 1), - clamp: bool = False, -) -> int: - """Reference 32-bit packed result for VOP3P int16 op; clamp saturates add only.""" - if op not in OPS: - raise ValueError(f"unsupported op: {op}") - kind = op[len("v_pk_"):].rsplit("_", 1)[0] - signed = op.endswith("i16") - out = 0 - for h, sl in enumerate((sel, selhi)): - a = (src0 >> (16 * sl[0])) & 0xFFFF - b = (src1 >> (16 * sl[1])) & 0xFFFF - if signed: - a, b = _s16(a), _s16(b) - if kind == "add": - r = a + b - elif kind == "mul_lo": - r = a * b - elif kind == "max": - r = max(a, b) - elif kind == "min": - r = min(a, b) - else: - raise ValueError(f"unsupported kind: {kind}") - if clamp and kind == "add": - r = max(-32768, min(32767, r)) if signed else max(0, min(0xFFFF, r)) - out |= (r & 0xFFFF) << (16 * h) - return out - - -def case_instruction(op: str, c: Case, clamp: bool) -> list[str]: - """Emit raw GFX10 setup + VOP3P instruction lines storing result in v2.""" - lines: list[str] = [] - if c.alias == "src0": - lines.append(f"v_mov_b32_e32 v2, {c.src0:#010x}") - lines.append(f"v_mov_b32_e32 v1, {c.src1:#010x}") - s0_op, s1_op = "v2", "v1" - elif c.alias == "src1": - lines.append(f"v_mov_b32_e32 v0, {c.src0:#010x}") - lines.append(f"v_mov_b32_e32 v2, {c.src1:#010x}") - s0_op, s1_op = "v0", "v2" - else: - if c.sgpr0: - lines.append(f"s_mov_b32 s4, {c.src0:#010x}") - s0_op = "s4" - elif c.src0_asm is not None: - s0_op = c.src0_asm - else: - lines.append(f"v_mov_b32_e32 v0, {c.src0:#010x}") - s0_op = "v0" - if c.src1_asm is not None: - s1_op = c.src1_asm - else: - lines.append(f"v_mov_b32_e32 v1, {c.src1:#010x}") - s1_op = "v1" - lines.append("v_mov_b32_e32 v2, 0xaaaaaaaa") - - mods: list[str] = [] - if c.sel != (0, 0): - mods.append(f"op_sel:[{c.sel[0]},{c.sel[1]}]") - if c.selhi != (1, 1): - mods.append(f"op_sel_hi:[{c.selhi[0]},{c.selhi[1]}]") - if clamp: - mods.append("clamp") - suffix = (" " + " ".join(mods)) if mods else "" - lines.append(f"{op} v2, {s0_op}, {s1_op}{suffix}") - return lines - - -def kernel_lines(op: str, clamp: bool) -> list[str]: - """Raw GFX10 kernel running every case in CASES sequentially on lane 0.""" - lines: list[str] = [] - for idx, c in enumerate(CASES): - lines.extend(case_instruction(op, c, clamp)) - lines.append(f"v_mov_b32_e32 v3, {idx * 4}") - lines.append("global_store_dword v3, v2, s[2:3]") - lines.append("s_waitcnt vmcnt(0)") - lines.append("s_endpgm") - return lines - - -def build_jobs(ops: list[str], waves: list[int]): - """Build (kernels, metadata) pairs for oracle.run().""" - from hw_oracle import asm - - kernels, meta = [], [] - for wave in waves: - for op in ops: - for clamp in CLAMP_MODES: - kernels.append(asm.Kernel(kernel_lines(op, clamp), wave=wave, threads=1, words=len(CASES), raw=True)) - meta.append((wave, op, clamp)) - return kernels, meta - - -def evaluate_results(ops: list[str], waves: list[int], meta, raw_results) -> dict: - """Compare hardware outputs against expected_pk_int16, plain vs clamp parity, and wave32 vs wave64 parity.""" - by_key: dict[tuple[int, str, bool], list[int]] = {} - harness_errors: list[dict] = [] - for (wave, op, clamp), res in zip(meta, raw_results): - if isinstance(res, str): - harness_errors.append({"wave": wave, "op": op, "clamp": clamp, "error": res}) - continue - if len(res) != len(CASES): - harness_errors.append({ - "wave": wave, - "op": op, - "clamp": clamp, - "error": f"expected {len(CASES)} words, got {len(res)}", - }) - continue - by_key[(wave, op, clamp)] = [w & 0xFFFFFFFF for w in res] - - if harness_errors: - return { - "total_cases": len(meta) * len(CASES), - "mismatches": 0, - "wave_diffs": 0, - "target_clamp_diffs": 0, - "control_clamp_diffs": 0, - "harness_errors": harness_errors, - "first_mismatches": [], - "first_wave_diffs": [], - "first_target_clamp_diffs": [], - } - - mismatches = 0 - first_mismatches: list[dict] = [] - for wave in waves: - for op in ops: - for clamp in CLAMP_MODES: - got_words = by_key[(wave, op, clamp)] - for c, got in zip(CASES, got_words): - want = expected_pk_int16(op, c.src0, c.src1, sel=c.sel, selhi=c.selhi, clamp=clamp) - if got != want: - mismatches += 1 - if len(first_mismatches) < 16: - first_mismatches.append({ - "wave": wave, - "op": op, - "clamp": clamp, - "case": c.name, - "got": f"0x{got:08x}", - "want": f"0x{want:08x}", - }) - - wave_diffs = 0 - first_wave_diffs: list[dict] = [] - if len(waves) > 1: - w0 = waves[0] - for w in waves[1:]: - for op in ops: - for clamp in CLAMP_MODES: - for c, a_w, b_w in zip(CASES, by_key[(w0, op, clamp)], by_key[(w, op, clamp)]): - if a_w != b_w: - wave_diffs += 1 - if len(first_wave_diffs) < 16: - first_wave_diffs.append({ - "op": op, - "clamp": clamp, - "case": c.name, - f"w{w0}": f"0x{a_w:08x}", - f"w{w}": f"0x{b_w:08x}", - }) - - target_clamp_diffs = 0 - first_target_clamp_diffs: list[dict] = [] - control_clamp_diffs = 0 - for wave in waves: - for op in ops: - plain_words = by_key[(wave, op, False)] - clamp_words = by_key[(wave, op, True)] - for c, pw, cw in zip(CASES, plain_words, clamp_words): - if op in TARGET_OPS and pw != cw: - target_clamp_diffs += 1 - if len(first_target_clamp_diffs) < 16: - first_target_clamp_diffs.append({ - "wave": wave, - "op": op, - "case": c.name, - "plain": f"0x{pw:08x}", - "clamp": f"0x{cw:08x}", - }) - elif op in CONTROL_OPS and pw != cw: - control_clamp_diffs += 1 - - return { - "total_cases": len(waves) * len(ops) * len(CLAMP_MODES) * len(CASES), - "mismatches": mismatches, - "wave_diffs": wave_diffs, - "target_clamp_diffs": target_clamp_diffs, - "control_clamp_diffs": control_clamp_diffs, - "harness_errors": [], - "first_mismatches": first_mismatches, - "first_wave_diffs": first_wave_diffs, - "first_target_clamp_diffs": first_target_clamp_diffs, - } - - -def write_report(path: str, doc: dict) -> bool: - """Write JSON report with LF line endings, creating parent folders.""" - try: - os.makedirs(os.path.dirname(os.path.abspath(path)), exist_ok=True) - with open(path, "w", encoding="utf-8", newline="\n") as f: - json.dump(doc, f, indent=1) - f.write("\n") - except OSError as e: - print(f"ERROR: cannot write {path}: {e}", file=sys.stderr) - return False - return True - - -def self_test() -> int: - """Verify the reference model and kernel generator without GPU or clang.""" - # v_pk_mul_lo_u16 wraps modulo 2^16 under clamp rather than saturating to 0xFFFF - assert expected_pk_int16("v_pk_mul_lo_u16", 0x02000100, 0x01000200, clamp=False) == 0x00000000 - assert expected_pk_int16("v_pk_mul_lo_u16", 0x02000100, 0x01000200, clamp=True) == 0x00000000 - assert expected_pk_int16("v_pk_mul_lo_u16", 0xFFFFFFFF, 0xFFFFFFFF, clamp=True) == 0x00010001 - assert expected_pk_int16("v_pk_mul_lo_u16", 0xFFFFFFFF, 0x00020002, clamp=True) == 0xFFFEFFFE - # v_pk_add_u16 control saturates under clamp - assert expected_pk_int16("v_pk_add_u16", 0xFFFFFFFF, 0x00020002, clamp=False) == 0x00010001 - assert expected_pk_int16("v_pk_add_u16", 0xFFFFFFFF, 0x00020002, clamp=True) == 0xFFFFFFFF - # v_pk_{max,min}_{u16,i16} ignore clamp and preserve signed vs unsigned comparison - assert expected_pk_int16("v_pk_max_u16", 0x80007FFF, 0x7FFF8000, clamp=True) == 0x80008000 - assert expected_pk_int16("v_pk_min_u16", 0x80007FFF, 0x7FFF8000, clamp=True) == 0x7FFF7FFF - assert expected_pk_int16("v_pk_max_i16", 0x80007FFF, 0x7FFF8000, clamp=True) == 0x7FFF7FFF - assert expected_pk_int16("v_pk_min_i16", 0x80007FFF, 0x7FFF8000, clamp=True) == 0x80008000 - # op_sel and op_sel_hi selection on constants and registers - assert expected_pk_int16( - "v_pk_mul_lo_u16", 0x80017FFF, 0xFFFE0003, sel=(1, 0), selhi=(0, 1), clamp=True - ) == 0x00028003 - # Kernel assembly sanity - kl = kernel_lines("v_pk_mul_lo_u16", True) - assert kl[-2:] == ["s_waitcnt vmcnt(0)", "s_endpgm"] - assert "v_pk_mul_lo_u16 v2, v0, v1 clamp" in kl - assert "v_pk_mul_lo_u16 v2, v0, 0x02000400 clamp" in kl - assert "v_pk_mul_lo_u16 v2, -16, v1 op_sel:[1,0] op_sel_hi:[0,1] clamp" in kl - print(f"self-test ok ({len(CASES)} cases, {len(OPS) * len(CLAMP_MODES) * len(CASES)} checks/wave)") - return 0 - - -def main(argv=None) -> int: - ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) - ap.add_argument("--ops", default=",".join(OPS)) - ap.add_argument("--waves", default="32,64") - ap.add_argument("--json", help="write measurement summary JSON here") - ap.add_argument("--hw-arch") - ap.add_argument("--self-test", action="store_true") - a = ap.parse_args(argv) - if a.self_test: - return self_test() - - ops = [o.strip() for o in a.ops.split(",") if o.strip()] - wave_tokens = [w.strip() for w in a.waves.split(",") if w.strip()] - bad_ops = [o for o in ops if o not in OPS] - bad_waves = [w for w in wave_tokens if w not in ("32", "64")] - if bad_ops or bad_waves or not ops or not wave_tokens: - ap.error("unknown or empty: " + ", ".join(bad_ops + bad_waves or ["--ops/--waves"])) - waves = [int(w) for w in wave_tokens] - if a.json and os.path.isdir(a.json): - ap.error(f"--json {a.json} is a folder, not a file") - - from hw_oracle import asm, runner - - try: - oracle = runner.open_oracle(arch=a.hw_arch) - except runner.Unavailable as e: - print(f"hardware oracle unavailable: {e}") - return 77 - - try: - if asm.family(oracle.arch) != "gfx10": - print(f"hardware oracle unavailable: {oracle.arch} is not GFX10") - return 77 - print(f"hardware oracle: {oracle.device} ({oracle.arch})") - kernels, meta = build_jobs(ops, waves) - raw_results = oracle.run(kernels) - summary = evaluate_results(ops, waves, meta, raw_results) - except RuntimeError as e: - print(f"harness error: {e}") - return 2 - finally: - oracle.close() - - report = { - "device": str(oracle.device), - "arch": oracle.arch, - "waves": waves, - "ops": ops, - "clamp_modes": ["plain", "clamp"], - "cases": len(CASES), - **summary, - } - if a.json and not write_report(a.json, report): - return 2 - - if summary["harness_errors"]: - for err in summary["harness_errors"][:5]: - print(f"harness error: wave{err['wave']} {err['op']} clamp={err['clamp']}: {err['error']}") - return 2 - - print( - f"{summary['total_cases']} evaluations across {len(waves)} wave(s) x {len(ops)} op(s) x 2 clamp modes: " - f"mismatches={summary['mismatches']}, wave_diffs={summary['wave_diffs']}, " - f"target_clamp_diffs={summary['target_clamp_diffs']}, control_clamp_diffs={summary['control_clamp_diffs']}" - ) - for m in summary["first_mismatches"]: - print(f" MISMATCH wave{m['wave']} {m['op']} clamp={m['clamp']} {m['case']}: got {m['got']}, want {m['want']}") - for d in summary["first_wave_diffs"]: - print(f" WAVE DIFF {d['op']} clamp={d['clamp']} {d['case']}: {d}") - for d in summary["first_target_clamp_diffs"]: - print(f" CLAMP DIFF wave{d['wave']} {d['op']} {d['case']}: plain={d['plain']} clamp={d['clamp']}") - - control_missing = "v_pk_add_u16" in ops and summary["control_clamp_diffs"] == 0 - if summary["mismatches"] or summary["wave_diffs"] or summary["target_clamp_diffs"] or control_missing: - if control_missing: - print(" CONTROL ERROR: v_pk_add_u16 clamp did not differ from plain on overflowing inputs") - return 1 - return 0 - - -if __name__ == "__main__": - try: - sys.stdout.reconfigure(errors="replace") - except (AttributeError, ValueError, OSError): - pass - sys.exit(main()) diff --git a/tools/pknorm_probe.py b/tools/pknorm_probe.py deleted file mode 100644 index 952a991aa..000000000 --- a/tools/pknorm_probe.py +++ /dev/null @@ -1,232 +0,0 @@ -r"""What do v_cvt_pknorm_i16_f32 / v_cvt_pknorm_u16_f32 give for NaN on RDNA2? A probe, standard library only. - -docs/design.md ("v_cvt_pknorm_i16_f32, v_cvt_pknorm_u16_f32" row) says NaN gives 0, as v_cvt_i32_f32 does, and that -this is not measured on hardware (SHADER-339). D[15:0] comes from S0 and D[31:16] from S1, so each case puts a value in -one half and another value in the other; every NaN pattern below appears in both halves. - -The translator multiplies in f32 (OpFMul) and then rounds to nearest even, two roundings. NEAR_TIES holds inputs where -that differs by one from rounding the exact x * 32767 (or 65535) once: the f32 product lands exactly on k + 0.5 while -the exact product is just below it (the translator goes up to the even k + 1, single rounding gives k) or just above it -(the translator goes down to the even k, single rounding gives k + 1). The probe reports which rule each side follows. - -Sides (each prints the dword per case; the probe compares them): - - translator tools/rdna2spirv.py -> tests/semantic/spirv_mini_interp.py, on the CPU. Always runs. - hw the native instruction on an AMD GPU (tools/hw_oracle: HIP on Windows, libdrm on Linux), one lane, in - wave32 and wave64, under each MODE in MODES: the one inferred for the game (IEEE 0, DX10_CLAMP 1, f32 - denormals flushed, f16/f64 kept, nearest) and variants of IEEE, DX10_CLAMP and the f32 denormal mode. - - python -I tools/pknorm_probe.py # translator side only - python -I tools/pknorm_probe.py --oracle hw # + the AMD GPU in this machine - -Exit code: 0 when every hardware word equals the translator's, 1 when one differs, 2 on a harness error, 77 when the -hardware oracle is unavailable. Nothing here reads game files. -Usage: `python -I tools/pknorm_probe.py --help` lists the options. -""" -import argparse -import os -import struct -import sys -import tempfile -import warnings -from fractions import Fraction - -HERE = os.path.dirname(os.path.abspath(__file__)) -ROOT = os.path.dirname(HERE) -sys.dont_write_bytecode = True -TOOLS_DIR = os.environ.get("LEONIDA_TOOLS_DIR") or HERE -for p in (TOOLS_DIR, os.path.join(ROOT, "tests", "semantic")): - if p not in sys.path: - sys.path.insert(0, p) - -import rdna2spirv # noqa: E402 -import spirv_mini_interp # noqa: E402 - -STUB_DXBC = b"DXBC" + bytes(24) + struct.pack(" Fraction(1, 2) or (r == Fraction(1, 2) and n % 2): - n += 1 - return n - - -def single_half(op, word): - """One half under single rounding: NaN gives 0, else clamp, the exact product, round to nearest even once.""" - x = _f32(word) - if x != x: - return 0 - lo = -1 if op == "v_cvt_pknorm_i16_f32" else 0 - q = Fraction(min(max(x, lo), 1)) - return _round_even(q * SCALE[op]) & 0xFFFF - - -def single_word(op, s0, s1): - return single_half(op, s0) | single_half(op, s1) << 16 - - -def group(case): - _, s0, s1 = case - if s0 in NANS or s1 in NANS: - return "nan" - if any(w in NEAR_TIES[case[0]] for w in (s0, s1)): - return "near_tie" - return "other" - - -# ---- the translator, on the CPU ---- - -def _translate(work, name, text): - os.makedirs(os.path.join(work, "disasm"), exist_ok=True) - src = os.path.join(work, "disasm", name + ".s") - with open(src, "w", encoding="utf-8", newline="\n") as f: - f.write(text) - with open(os.path.join(work, name + ".dxbc"), "wb") as f: - f.write(STUB_DXBC) - with warnings.catch_warnings(): - warnings.simplefilter("ignore", ResourceWarning) - return rdna2spirv.translate(src) - - -def ps_listing(op, s0, s1): - """A pixel shader that runs one case. D leaves as two 16-bit halves ORed into 0x40000000, so no export channel is a - NaN or denormal pattern a float round trip could change (as tests/semantic/test_alu_cvt_pknorm_f32.py does).""" - body = [f"v_mov_b32 v1, 0x{s0:x}", f"v_mov_b32 v2, 0x{s1:x}", "v_mov_b32 v0, 0xdeadbeef", f"{op} v0, v1, v2", - "v_and_b32 v5, 0xffff, v0", "v_lshrrev_b32 v6, 16, v0", "v_or_b32 v5, 0x40000000, v5", - "v_or_b32 v6, 0x40000000, v6", "exp mrt0 v5, v6, v5, v5 done vm", "s_endpgm"] - return "; pknorm_probe\n" + "".join(f"\t{ln}\n" for ln in body) - - -def run_translator(case_list): - out = [] - with tempfile.TemporaryDirectory(prefix="pknorm_probe_") as work: - for i, (op, s0, s1) in enumerate(case_list): - spv = _translate(work, f"ps_pknorm_{i}", ps_listing(op, s0, s1)) - lo, hi = spirv_mini_interp.run_fragment(spv)["%out_mrt0"][:2] - out.append((lo & 0xFFFF) | (hi & 0xFFFF) << 16) - return out - - -# ---- the hardware ---- - -def hw_lines(op, s0, s1): - return [f"v_mov_b32 v1, 0x{s0:x}", f"v_mov_b32 v2, 0x{s1:x}", "v_mov_b32 v8, 0xdeadbeef", f"{op} v8, v1, v2", - "v_mov_b32 v20, 0", "global_store_b32 v20, v8, s[2:3]", "s_endpgm"] - - -def run_hw(oracle, case_list, wave, mode): - from hw_oracle import asm - got = oracle.run([asm.Kernel(hw_lines(*c), wave, 1, 1, raw=True, mode=mode) for c in case_list], words=1) - return [w if isinstance(w, str) else w[0] for w in got] - - -def main(argv=None): - ap = argparse.ArgumentParser(description=__doc__.split("\n", 1)[0]) - ap.add_argument("--oracle", default="translator", help="translator (default) or translator,hw / hw") - ap.add_argument("--hw-arch", help="override the hardware architecture (LEONIDA_HW_ARCH)") - a = ap.parse_args(argv) - sides = {s.strip() for s in a.oracle.split(",") if s.strip()} - {"translator"} - if sides - {"hw"}: - ap.error(f"unknown --oracle side(s): {', '.join(sorted(sides - {'hw'}))}") - case_list = cases() - try: - want = run_translator(case_list) - except Exception as e: # noqa: BLE001 - a harness error, not a finding - print(f"translator side failed: {e}") - return 2 - groups = [group(c) for c in case_list] - counts = {g: groups.count(g) for g in ("nan", "near_tie", "other")} - print(f"translator: {len(case_list)} cases ({counts['nan']} with a NaN operand, {counts['near_tie']} near a tie, " - f"{counts['other']} other)") - single = [single_word(*c) for c in case_list] - t_single = sum(1 for g, w, s in zip(groups, want, single) if g == "near_tie" and w == s) - print(f"translator near ties: {t_single} of {counts['near_tie']} equal single rounding of the exact product") - if "hw" not in sides: - for (op, s0, s1), w in zip(case_list, want): - print(f" {op} {s0:08x} {s1:08x} -> {w:08x}") - return 0 - from hw_oracle import runner - try: - oracle = runner.open_oracle(arch=a.hw_arch) - except runner.Unavailable as e: - print(f"hardware oracle unavailable: {e}") - return 77 - status = 0 - try: - print(f"hardware oracle: {oracle.device} ({oracle.arch})") - for wave in (32, 64): - for name, mode in MODES: - got = run_hw(oracle, case_list, wave, mode) - diffs = [(c, g, w) for c, g, w in zip(case_list, got, want) if g != w] - errors = [g for g in got if isinstance(g, str)] - if errors: - print(f"wave{wave} {name}: harness error: {errors[0]}") - return 2 - same = {k: sum(1 for gr, g, w in zip(groups, got, want) if gr == k and g == w) for k in counts} - hw_single = sum(1 for gr, g, s in zip(groups, got, single) if gr == "near_tie" and g == s) - nan_halves = [(g >> (16 * h)) & 0xFFFF for (_, s0, s1), g in zip(case_list, got) - for h, s in enumerate((s0, s1)) if s in NANS] - print(f"wave{wave} {name}: NaN halves giving 0: {nan_halves.count(0)}/{len(nan_halves)}") - print(f"wave{wave} {name}: equal to the translator: NaN {same['nan']}/{counts['nan']}, " - f"near ties {same['near_tie']}/{counts['near_tie']}, other {same['other']}/{counts['other']}; " - f"near ties equal to single rounding: {hw_single}/{counts['near_tie']}") - for (op, s0, s1), g, w in diffs: - print(f" {op} {s0:08x} {s1:08x}: hw {g:08x}, translator {w:08x}") - if diffs: - status = 1 - finally: - oracle.close() - return status - - -if __name__ == "__main__": - try: # a redirected stdout is strict ANSI code page under -I; write '?' for what it cannot encode - sys.stdout.reconfigure(errors="replace") - except (AttributeError, ValueError, OSError): - pass - sys.exit(main()) diff --git a/tools/pool_workers.py b/tools/pool_workers.py deleted file mode 100644 index f10dbf916..000000000 --- a/tools/pool_workers.py +++ /dev/null @@ -1,19 +0,0 @@ -"""How many worker processes one pool can have on this platform. - -Windows waits on a pool's workers with WaitForMultipleObjects, which takes at most 64 handles. Above 61 workers -concurrent.futures.ProcessPoolExecutor raises `ValueError: max_workers must be <= 61`, and multiprocessing.Pool -prints `ValueError: need at most 63 handles` from its result thread and never returns (measured on Windows 11, -Python 3.12.5: 62 workers were killed after 60 s, 61 finished in 0.8 s). A tool whose --jobs defaults to half the -CPU count, or is handed make_game.py's, reaches that on a large machine with no option given. - -A pool is therefore created with process_workers(jobs): the same number everywhere else, 61 at most on Windows. -Threads have no such limit. tools/world_census.py rejects --jobs above the limit instead (its MAX_JOBS). -""" -import os - -MAX_PROCESS_WORKERS = 61 if os.name == "nt" else None - - -def process_workers(jobs): - """`jobs`, lowered to the most worker processes one pool can have here.""" - return jobs if MAX_PROCESS_WORKERS is None else min(jobs, MAX_PROCESS_WORKERS) diff --git a/tools/pr_conflict_label.py b/tools/pr_conflict_label.py deleted file mode 100644 index 174db8ba3..000000000 --- a/tools/pr_conflict_label.py +++ /dev/null @@ -1,153 +0,0 @@ -"""Label the open pull requests that conflict with their base branch `needs rebase`, and unlabel them once they merge. - - python -I tools/pr_conflict_label.py --repo OWNER/NAME [--pr N] [--dry-run] - -`.github/workflows/conflict-label.yml` runs this on every push to `main` (a merge can make other pull requests -conflict), on a pull request being opened, reopened or pushed to (a rebase can clear a conflict), and hourly in case -GitHub had not finished computing a merge. Every pull request gets reviewed by hand; the label lets a reviewer skip -the ones that cannot be merged as they stand and tells their authors to rebase. - -GitHub computes `mergeable` in the background and answers `null` until it has, so a pull request whose answer is -still unknown is asked again a few times and otherwise left as it is for the next run. Only the GitHub REST API is -read and written: no pull request code is checked out or run, which is what makes the `pull_request_target` trigger -safe here. The token comes from `GITHUB_TOKEN` (or `GH_TOKEN`); `--dry-run` prints the changes and writes nothing. -Standard library only; no game files. -""" -import argparse -import json -import os -import sys -import time -import urllib.error -import urllib.parse -import urllib.request - -LABEL = "needs rebase" -LABEL_COLOR = "d93f0b" -LABEL_DESCRIPTION = "Conflicts with the base branch: rebase it on main" -API = "https://api.github.com" - - -class ApiError(Exception): - def __init__(self, status, message): - super().__init__(f"HTTP {status}: {message}") - self.status = status - - -def github_api(token): - """A function (method, path, body=None) -> parsed JSON (or None) that calls the GitHub REST API with `token`.""" - def call(method, path, body=None): - data = None if body is None else json.dumps(body).encode("utf-8") - req = urllib.request.Request(API + path, data=data, method=method, headers={ - "Accept": "application/vnd.github+json", - "Authorization": f"Bearer {token}", - "User-Agent": "pr-conflict-label", - "X-GitHub-Api-Version": "2022-11-28", - }) - try: - with urllib.request.urlopen(req, timeout=30) as resp: - raw = resp.read() - except urllib.error.HTTPError as e: - raise ApiError(e.code, e.read().decode("utf-8", "replace")[:300]) from None - return json.loads(raw) if raw else None - return call - - -def decide(mergeable, labeled): - """'add', 'remove' or None for a pull request whose `mergeable` is True, False or None (not computed yet).""" - if mergeable is False and not labeled: - return "add" - if mergeable is True and labeled: - return "remove" - return None - - -def open_pull_numbers(api, repo): - numbers, page = [], 1 - while True: - batch = api("GET", f"/repos/{repo}/pulls?state=open&per_page=100&page={page}") - numbers += [p["number"] for p in batch] - if len(batch) < 100: - return numbers - page += 1 - - -def ensure_label(api, repo): - try: - api("POST", f"/repos/{repo}/labels", - {"name": LABEL, "color": LABEL_COLOR, "description": LABEL_DESCRIPTION}) - except ApiError as e: - if e.status != 422: # 422: the label exists already - raise - - -def apply(api, repo, number, action): - if action == "add": - api("POST", f"/repos/{repo}/issues/{number}/labels", {"labels": [LABEL]}) - else: - try: - api("DELETE", f"/repos/{repo}/issues/{number}/labels/{urllib.parse.quote(LABEL, safe='')}") - except ApiError as e: - if e.status != 404: # 404: someone removed it in between - raise - - -def run(api, repo, numbers, dry_run=False, attempts=4, wait=10.0, sleep=time.sleep, out=print): - """Label or unlabel each pull request of `numbers`. Returns {'add': [...], 'remove': [...], 'unknown': [...]}.""" - done = {"add": [], "remove": [], "unknown": []} - pending = list(numbers) - label_ready = dry_run - for attempt in range(attempts): - if attempt: - sleep(wait) # asking for a pull request starts GitHub's merge computation; give it time - unknown = [] - for number in pending: - pr = api("GET", f"/repos/{repo}/pulls/{number}") - if pr.get("state") != "open": - continue - labeled = any(label.get("name") == LABEL for label in pr.get("labels", [])) - if pr.get("mergeable") is None: - unknown.append(number) - continue - action = decide(pr["mergeable"], labeled) - if action is None: - continue - out(f"#{number}: {action} '{LABEL}'" + (" (dry run)" if dry_run else "")) - if not dry_run: - if action == "add" and not label_ready: - ensure_label(api, repo) - label_ready = True - apply(api, repo, number, action) - done[action].append(number) - pending = unknown - if not pending: - break - done["unknown"] = pending - if pending: - out("mergeable not computed yet, left for the next run: " + " ".join(f"#{n}" for n in pending)) - return done - - -def main(argv=None): - ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) - ap.add_argument("--repo", default=os.environ.get("GITHUB_REPOSITORY"), help="OWNER/NAME") - ap.add_argument("--pr", type=int, action="append", help="only this pull request (repeatable)") - ap.add_argument("--dry-run", action="store_true", help="print the changes, write nothing") - args = ap.parse_args(argv) - token = os.environ.get("GITHUB_TOKEN") or os.environ.get("GH_TOKEN") - if not args.repo or not token: - ap.error("needs --repo (or GITHUB_REPOSITORY) and GITHUB_TOKEN (or GH_TOKEN)") - api = github_api(token) - numbers = args.pr or open_pull_numbers(api, args.repo) - done = run(api, args.repo, numbers, dry_run=args.dry_run) - print(f"{len(numbers)} checked: {len(done['add'])} labeled, {len(done['remove'])} unlabeled, " - f"{len(done['unknown'])} not computed yet") - return 0 - - -if __name__ == "__main__": - try: # a redirected stdout is strict ANSI code page under -I; write '?' for what it cannot encode - sys.stdout.reconfigure(errors="replace") - except (AttributeError, ValueError, OSError): - pass - sys.exit(main()) diff --git a/tools/probe_gfx1036_vcmp16.py b/tools/probe_gfx1036_vcmp16.py deleted file mode 100644 index 109724bf5..000000000 --- a/tools/probe_gfx1036_vcmp16.py +++ /dev/null @@ -1,370 +0,0 @@ -"""Probe gfx1036 silicon across wave32 and wave64 for 16-bit vector compares: - - v_cmp and v_cmpx (EXEC update and inactive-lane 0 write in sdst). - - Inline int/float constants and 32-bit literals with op_sel=0/1. - - SGPR high halves, f16 abs/neg/ordered-vs-unordered NaN. - -Usage: - powershell -File C:\\Leonida-worktrees\\with-gpu-lock.ps1 "cd C:\\Leonida-worktrees\\w4-cmp16-opsel; python scripts/probe_gfx1036_vcmp16.py" -""" -import math -import os -import struct -import subprocess -import sys -import tempfile - -ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) -sys.path.insert(0, ROOT) -sys.path.insert(0, os.path.join(ROOT, "tests", "semantic")) -sys.path.insert(0, os.path.join(ROOT, "tools")) - -from support import STUB_DXBC, rdna2spirv -import spirv_mini_interp as si - -VK_COMPUTE_TEST = os.path.join(ROOT, "runtime", "build", "vk_compute_test.exe") - -# Half-precision bit constants -H_ZERO = 0x0000 # +0.0 -H_NZERO = 0x8000 # -0.0 -H_HALF = 0x3800 # +0.5 -H_ONE = 0x3C00 # +1.0 -H_TWO = 0x4000 # +2.0 -H_THREE = 0x4200 # +3.0 -H_FOUR = 0x4400 # +4.0 -H_MONE = 0xBC00 # -1.0 -H_MTWO = 0xC000 # -2.0 -H_MFOUR = 0xC400 # -4.0 -H_INF = 0x7C00 # +inf -H_NINF = 0xFC00 # -inf -H_QNAN = 0x7E00 # qNaN -H_SNAN = 0x7D00 # sNaN - -SENTINEL = 0xDEADBEEF - -def pack16(lo: int, hi: int) -> int: - return ((hi & 0xFFFF) << 16) | (lo & 0xFFFF) - -def run_on_silicon(name, asm_lines, wave_size=32, user_sgprs=None): - with tempfile.TemporaryDirectory() as tmp: - os.mkdir(os.path.join(tmp, "disasm")) - os.mkdir(os.path.join(tmp, "fssm")) - s_path = os.path.join(tmp, "disasm", name + ".s") - with open(s_path, "w", encoding="utf-8", newline="\n") as f: - f.write(f"; {name}\n") - for ln in asm_lines: - f.write(f"\t{ln}\n") - f.write("\ts_endpgm\n") - with open(os.path.join(tmp, name + ".dxbc"), "wb") as f: - f.write(STUB_DXBC) - rsrc2 = 0x8090 if user_sgprs else 0x8088 - with open(os.path.join(tmp, "fssm", name + ".fssm"), "wb") as f: - f.write(bytes(0x138) + struct.pack("<4I", rsrc2, wave_size, 1, 1)) - - spv_text = rdna2spirv.translate(s_path) - sa_path = os.path.join(tmp, name + ".spvasm") - spv_path = os.path.join(tmp, name + ".spv") - with open(sa_path, "w", encoding="utf-8", newline="\n") as f: - f.write(spv_text) - rdna2spirv.assemble_spirv(sa_path, spv_path) - - dump_path = os.path.join(tmp, "dump.bin") - env = os.environ.copy() - env["LEONIDA_VK_DEVICE"] = "radeon" - env["VKC_DUMP"] = dump_path - env["VKC_OUT_WORDS"] = str(wave_size) - if user_sgprs: - env["VKC_SGPRS"] = ",".join(hex(w) for w in user_sgprs) - - extra_args = ["--require-wave64"] if wave_size == 64 else [] - res = subprocess.run([VK_COMPUTE_TEST, spv_path, "1", "none"] + extra_args, - env=env, capture_output=True, text=True) - if res.returncode != 0: - print(f"FAILED {name} (rc={res.returncode}):\nSTDOUT: {res.stdout}\nSTDERR: {res.stderr}") - return None - - with open(dump_path, "rb") as f: - data = f.read() - return struct.unpack(f"<{len(data)//4}I", data)[:wave_size] - - -def test_vcmp_inactive_lanes(wave_size): - """Verify v_cmp writes 0 for inactive lanes into sdst (wave32 and wave64).""" - name = f"cs_probe_vcmp_inactive_w{wave_size}" - # Inactive lanes: odd lanes killed in EXEC before compare. - # Active lanes: v1 == v2 (true). - # Then re-enable EXEC so all lanes can store their bit from sdst. - if wave_size == 32: - exec_init = "s_mov_b32 exec_lo, 0x55555555" # even lanes active - cmp_line = "v_cmp_eq_u16_e64 s4, v1, v2 op_sel:[0,0]" - exec_restore = "s_mov_b32 exec_lo, -1" - read_bit = [ - "v_lshrrev_b32_e32 v3, v0, s4", - "v_and_b32_e32 v3, 1, v3", - ] - else: - exec_init = "s_mov_b64 exec, 0x5555555555555555" - cmp_line = "v_cmp_eq_u16_e64 s[4:5], v1, v2 op_sel:[0,0]" - exec_restore = "s_mov_b64 exec, -1" - read_bit = [ - "v_cmp_ge_u32_e64 s6, v0, 32", - "v_cndmask_b32_e64 v4, s4, s5, s6", - "v_and_b32_e32 v5, 31, v0", - "v_lshrrev_b32_e32 v3, v5, v4", - "v_and_b32_e32 v3, 1, v3", - ] - - body = [ - "v_mov_b32 v1, 0x1234", - "v_mov_b32 v2, 0x1234", - exec_init, - cmp_line, - exec_restore, - *read_bit, - "v_lshlrev_b32_e32 v6, 2, v0", - "buffer_store_dword v3, v6, s[0:3], 0 offen", - ] - out = run_on_silicon(name, body, wave_size=wave_size) - assert out is not None, f"Silicon run failed for {name}" - for lane in range(wave_size): - expected = 1 if (lane % 2 == 0) else 0 - if out[lane] != expected: - raise AssertionError(f"{name} lane {lane}: got {out[lane]}, expected {expected}") - print(f"[{name}] PASSED on gfx1036 silicon (inactive lanes set to 0 in sdst)") - - -def test_vcmpx_exec_update(wave_size): - """Verify v_cmpx kills inactive/failing lanes in EXEC across wave32 and wave64.""" - name = f"cs_probe_vcmpx_exec_w{wave_size}" - # Even lanes have v1.hi < v2.lo (1.0 < 2.0 -> True). - # Odd lanes have v1.hi > v2.lo (4.0 > 2.0 -> False). - body = [ - # Pre-fill with SENTINEL - "v_lshlrev_b32_e32 v4, 2, v0", - f"v_mov_b32 v5, {SENTINEL:#x}", - "buffer_store_dword v5, v4, s[0:3], 0 offen", - # Even lanes get v1 = pack16(0, 1.0); odd lanes get v1 = pack16(0, 4.0) - "v_and_b32_e32 v3, 1, v0", - f"v_cmp_eq_u32_e64 {'vcc' if wave_size == 64 else 'vcc_lo'}, v3, 0", - f"v_mov_b32 v6, {pack16(0, H_ONE):#x}", - f"v_mov_b32 v7, {pack16(0, H_FOUR):#x}", - f"v_cndmask_b32_e64 v1, v7, v6, {'vcc' if wave_size == 64 else 'vcc_lo'}", - f"v_mov_b32 v2, {pack16(H_TWO, 0):#x}", - # v_cmpx with op_sel:[1, 0]: reads hi half of v1, lo half of v2 - "v_cmpx_lt_f16_e64 v1, v2 op_sel:[1,0]", - # Only surviving lanes write lane | 0x100 - "v_or_b32_e32 v5, 0x100, v0", - "buffer_store_dword v5, v4, s[0:3], 0 offen", - ] - out = run_on_silicon(name, body, wave_size=wave_size) - assert out is not None, f"Silicon run failed for {name}" - for lane in range(wave_size): - expected = (0x100 | lane) if (lane % 2 == 0) else SENTINEL - if out[lane] != expected: - raise AssertionError(f"{name} lane {lane}: got {hex(out[lane])}, expected {hex(expected)}") - print(f"[{name}] PASSED on gfx1036 silicon (EXEC properly updated by v_cmpx)") - - -def test_constants_and_literals(wave_size=32): - """Probe inline float/int constants and 32-bit literals with op_sel=0 and 1.""" - name = f"cs_probe_consts_lits_w{wave_size}" - # Test cases: (description, cmp_line, v1_word, expected_bit) - tests = [ - # Inline float constants: 1.0 (0x3C00 in lo, 0.0 in hi) - # v1 = pack16(1.0, 2.0). 1.0 == 1.0 -> 1; 2.0 == 1.0 -> 0. - ("f16_float_const_opsel0", "v_cmp_eq_f16_e64 s4, v1, 1.0 op_sel:[0,0]", pack16(H_ONE, H_TWO), 1), - ("f16_float_const_opsel0_diff", "v_cmp_eq_f16_e64 s4, v1, 1.0 op_sel:[1,0]", pack16(H_ONE, H_TWO), 0), - # op_sel=1 on 1.0 reads +0.0: - ("f16_float_const_opsel1_reads_zero", "v_cmp_eq_f16_e64 s4, v1, 1.0 op_sel:[0,1]", pack16(H_ZERO, H_TWO), 1), - ("f16_float_const_opsel1_nonzero", "v_cmp_eq_f16_e64 s4, v1, 1.0 op_sel:[0,1]", pack16(H_ONE, H_TWO), 0), - # Inline float constant -2.0: - ("f16_float_const_neg2", "v_cmp_eq_f16_e64 s4, v1, -2.0 op_sel:[0,0]", pack16(H_MTWO, H_ONE), 1), - ("f16_float_const_neg2_hi_zero", "v_cmp_eq_f16_e64 s4, v1, -2.0 op_sel:[0,1]", pack16(H_ZERO, H_ONE), 1), - - # 32-bit literal constant in f16: 0x40003C00 (lo = 1.0, hi = 2.0) - ("f16_lit_opsel0", "v_cmp_eq_f16_e64 s4, v1, 0x40003C00 op_sel:[0,0]", pack16(H_ONE, H_FOUR), 1), - ("f16_lit_opsel1", "v_cmp_eq_f16_e64 s4, v1, 0x40003C00 op_sel:[1,1]", pack16(H_FOUR, H_TWO), 1), - - # Inline integer constants in u16: 1 - ("u16_int_const1_opsel0", "v_cmp_eq_u16_e64 s4, v1, 1 op_sel:[0,0]", pack16(1, 2), 1), - ("u16_int_const1_opsel1_reads_0", "v_cmp_eq_u16_e64 s4, v1, 1 op_sel:[0,1]", pack16(0, 2), 1), - # Inline integer constant -1 (0xFFFFFFFF) in u16: - ("u16_int_const_neg1_opsel0", "v_cmp_eq_u16_e64 s4, v1, -1 op_sel:[0,0]", pack16(0xFFFF, 0), 1), - ("u16_int_const_neg1_opsel1", "v_cmp_eq_u16_e64 s4, v1, -1 op_sel:[0,1]", pack16(0xFFFF, 0), 1), - - # Inline integer constants in i16: - ("i16_int_const_neg1_opsel0", "v_cmp_eq_i16_e64 s4, v1, -1 op_sel:[0,0]", pack16(0xFFFF, 0), 1), - ("i16_int_const_neg1_opsel1", "v_cmp_eq_i16_e64 s4, v1, -1 op_sel:[0,1]", pack16(0xFFFF, 0), 1), - ("i16_int_const1_opsel0", "v_cmp_eq_i16_e64 s4, v1, 1 op_sel:[0,0]", pack16(1, 2), 1), - ("i16_int_const1_opsel1_reads_0", "v_cmp_eq_i16_e64 s4, v1, 1 op_sel:[0,1]", pack16(0, 2), 1), - - # 32-bit literals in u16 and i16: 0x80007FFF (lo = 0x7FFF = 32767, hi = 0x8000 = -32768) - ("u16_lit_opsel0", "v_cmp_eq_u16_e64 s4, v1, 0x80007FFF op_sel:[0,0]", pack16(0x7FFF, 0), 1), - ("u16_lit_opsel1", "v_cmp_eq_u16_e64 s4, v1, 0x80007FFF op_sel:[0,1]", pack16(0x8000, 0), 1), - ("i16_lit_opsel0_signed", "v_cmp_eq_i16_e64 s4, v1, 0x80007FFF op_sel:[0,0]", pack16(0x7FFF, 0), 1), - ("i16_lit_opsel1_signed", "v_cmp_eq_i16_e64 s4, v1, 0x80007FFF op_sel:[1,1]", pack16(0, 0x8000), 1), - ("i16_lit_lt_signed", "v_cmp_lt_i16_e64 s4, v1, 0x80007FFF op_sel:[0,1]", pack16(0, 0), 0), # 0 < -32768 is False! - ] - - # For simplicity, run each individually or batch them into slots - for idx, (tag, cmp_line, v1_w, want) in enumerate(tests): - single_body = [ - f"v_mov_b32 v1, {v1_w:#x}", - cmp_line, - "v_and_b32_e32 v2, 1, s4", - "v_lshlrev_b32_e32 v3, 2, v0", - "buffer_store_dword v2, v3, s[0:3], 0 offen", - ] - out = run_on_silicon(f"cs_const_{idx}", single_body, wave_size=wave_size) - assert out is not None, f"Failed {tag}" - got = out[0] - if got != want: - raise AssertionError(f"Test '{tag}' FAILED on silicon: got {got}, want {want}") - print(f" [{tag}] -> {got} (matched expected {want})") - print(f"[{name}] ALL {len(tests)} CONSTANT/LITERAL TESTS PASSED on gfx1036 silicon!") - - -def test_sgpr_high_halves(wave_size=32): - """Probe SGPR high halves as src0 and src1 with op_sel and modifiers.""" - name = f"cs_probe_sgpr_hi_w{wave_size}" - # User SGPR s4 is passed via VKC_SGPRS: - # Set s4 = 0x44003C00 (lo = 1.0, hi = 4.0) - user_sgpr_s4 = pack16(H_ONE, H_FOUR) - - tests = [ - # (tag, cmp_line, v1_word, want) - # s4 as src1: - ("f16_sgpr_src1_opsel0", "v_cmp_eq_f16_e64 s5, v1, s4 op_sel:[0,0]", pack16(H_ONE, 0), 1), - ("f16_sgpr_src1_opsel1", "v_cmp_eq_f16_e64 s5, v1, s4 op_sel:[0,1]", pack16(H_FOUR, 0), 1), - # s4 as src0: - ("f16_sgpr_src0_opsel0", "v_cmp_eq_f16_e64 s5, s4, v1 op_sel:[0,0]", pack16(H_ONE, 0), 1), - ("f16_sgpr_src0_opsel1", "v_cmp_eq_f16_e64 s5, s4, v1 op_sel:[1,0]", pack16(H_FOUR, 0), 1), - # s4 with neg / abs on high half: - ("f16_sgpr_neg_hi", "v_cmp_eq_f16_e64 s5, v1, -s4 op_sel:[0,1]", pack16(H_MFOUR, 0), 1), - ("f16_sgpr_abs_hi", "v_cmp_eq_f16_e64 s5, v1, |s4| op_sel:[0,1]", pack16(H_FOUR, 0), 1), - - # u16 / i16 with SGPR: - # s4 = pack16(0x7FFF, 0x8000) (lo = +32767, hi = -32768 in i16 / 32768 in u16) - ] - for idx, (tag, cmp_line, v1_w, want) in enumerate(tests): - single_body = [ - f"v_mov_b32 v1, {v1_w:#x}", - cmp_line, - "v_and_b32_e32 v2, 1, s5", - "v_lshlrev_b32_e32 v3, 2, v0", - "buffer_store_dword v2, v3, s[0:3], 0 offen", - ] - out = run_on_silicon(f"cs_sgpr_{idx}", single_body, wave_size=wave_size, user_sgprs=[user_sgpr_s4]) - assert out is not None, f"Failed {tag}" - got = out[0] - if got != want: - raise AssertionError(f"Test '{tag}' FAILED on silicon: got {got}, want {want}") - print(f" [{tag}] -> {got} (matched expected {want})") - - # Also test integer SGPR with s4 = pack16(0x7FFF, 0xFFFF) (lo = 32767, hi = -1 in i16) - int_sgpr = pack16(0x7FFF, 0xFFFF) - int_tests = [ - ("u16_sgpr_opsel0", "v_cmp_eq_u16_e64 s5, v1, s4 op_sel:[0,0]", pack16(0x7FFF, 0), 1), - ("u16_sgpr_opsel1", "v_cmp_eq_u16_e64 s5, v1, s4 op_sel:[0,1]", pack16(0xFFFF, 0), 1), - ("i16_sgpr_opsel1_lt", "v_cmp_lt_i16_e64 s5, s4, v1 op_sel:[1,0]", pack16(0, 0), 1), # -1 < 0 is True - ("u16_sgpr_opsel1_lt", "v_cmp_lt_u16_e64 s5, s4, v1 op_sel:[1,0]", pack16(0, 0), 0), # 65535 < 0 is False - ] - for idx, (tag, cmp_line, v1_w, want) in enumerate(int_tests, len(tests)): - single_body = [ - f"v_mov_b32 v1, {v1_w:#x}", - cmp_line, - "v_and_b32_e32 v2, 1, s5", - "v_lshlrev_b32_e32 v3, 2, v0", - "buffer_store_dword v2, v3, s[0:3], 0 offen", - ] - out = run_on_silicon(f"cs_sgpr_{idx}", single_body, wave_size=wave_size, user_sgprs=[int_sgpr]) - assert out is not None, f"Failed {tag}" - got = out[0] - if got != want: - raise AssertionError(f"Test '{tag}' FAILED on silicon: got {got}, want {want}") - print(f" [{tag}] -> {got} (matched expected {want})") - print(f"[{name}] ALL SGPR HIGH-HALF TESTS PASSED on gfx1036 silicon!") - - -def test_f16_nan_and_modifiers(wave_size=32): - """Probe ordered vs unordered, qNaN, sNaN, abs and neg modifiers on silicon.""" - name = f"cs_probe_nan_mods_w{wave_size}" - # Nan pairs: - # v1 = pack16(1.0, qNaN), v2 = pack16(qNaN, 2.0) - xw = pack16(H_ONE, H_QNAN) - yw = pack16(H_QNAN, H_TWO) - - tests = [ - # (0, 0): 1.0 vs qNaN -> unordered - ("f16_ord_00", "v_cmp_o_f16_e64 s4, v1, v2 op_sel:[0,0]", 0), - ("f16_unord_00", "v_cmp_u_f16_e64 s4, v1, v2 op_sel:[0,0]", 1), - ("f16_eq_nan_00", "v_cmp_eq_f16_e64 s4, v1, v2 op_sel:[0,0]", 0), - ("f16_neq_nan_00", "v_cmp_neq_f16_e64 s4, v1, v2 op_sel:[0,0]", 1), - - # (0, 1): 1.0 vs 2.0 -> ordered - ("f16_ord_01", "v_cmp_o_f16_e64 s4, v1, v2 op_sel:[0,1]", 1), - ("f16_unord_01", "v_cmp_u_f16_e64 s4, v1, v2 op_sel:[0,1]", 0), - ("f16_lt_01", "v_cmp_lt_f16_e64 s4, v1, v2 op_sel:[0,1]", 1), - ("f16_gt_01", "v_cmp_gt_f16_e64 s4, v1, v2 op_sel:[0,1]", 0), - - # (1, 0): qNaN vs qNaN -> unordered - ("f16_ord_10", "v_cmp_o_f16_e64 s4, v1, v2 op_sel:[1,0]", 0), - ("f16_unord_10", "v_cmp_u_f16_e64 s4, v1, v2 op_sel:[1,0]", 1), - - # Modifiers on high half: - # v1.hi is qNaN: |qNaN| is still NaN! - ("f16_abs_nan_ord", "v_cmp_o_f16_e64 s4, |v1|, v2 op_sel:[1,1]", 0), - ("f16_neg_nan_unord", "v_cmp_u_f16_e64 s4, -v1, v2 op_sel:[1,1]", 1), - ] - for idx, (tag, cmp_line, want) in enumerate(tests): - single_body = [ - f"v_mov_b32 v1, {xw:#x}", - f"v_mov_b32 v2, {yw:#x}", - cmp_line, - "v_and_b32_e32 v3, 1, s4", - "v_lshlrev_b32_e32 v4, 2, v0", - "buffer_store_dword v3, v4, s[0:3], 0 offen", - ] - out = run_on_silicon(f"cs_nan_{idx}", single_body, wave_size=wave_size) - assert out is not None, f"Failed {tag}" - got = out[0] - if got != want: - raise AssertionError(f"Test '{tag}' FAILED on silicon: got {got}, want {want}") - print(f" [{tag}] -> {got} (matched expected {want})") - print(f"[{name}] ALL NaN & MODIFIER TESTS PASSED on gfx1036 silicon!") - - -def main(): - print("=" * 70) - print("PROBING GFX1036 SILICON FOR V_CMP(X) 16-BIT OP_SEL & CONSTANTS") - print("=" * 70) - - print("\n--- 1. Testing v_cmp inactive-lane 0 write in sdst (wave32 & wave64) ---") - test_vcmp_inactive_lanes(32) - test_vcmp_inactive_lanes(64) - - print("\n--- 2. Testing v_cmpx EXEC update (wave32 & wave64) ---") - test_vcmpx_exec_update(32) - test_vcmpx_exec_update(64) - - print("\n--- 3. Testing inline float/int constants & 32-bit literals with op_sel=0/1 (wave32 & wave64) ---") - test_constants_and_literals(32) - test_constants_and_literals(64) - - print("\n--- 4. Testing SGPR high halves with op_sel & modifiers (wave32 & wave64) ---") - test_sgpr_high_halves(32) - test_sgpr_high_halves(64) - - print("\n--- 5. Testing f16 NaN (ordered vs unordered) & modifiers (wave32 & wave64) ---") - test_f16_nan_and_modifiers(32) - test_f16_nan_and_modifiers(64) - - print("\n" + "=" * 70) - print("ALL GFX1036 SILICON PROBES (WAVE32 & WAVE64) PASSED WITH ZERO DIVERGENCES!") - print("=" * 70) - -if __name__ == "__main__": - try: # a redirected stdout is strict ANSI code page under -I; write '?' for what it cannot encode - sys.stdout.reconfigure(errors="replace") - except (AttributeError, ValueError, OSError): - pass - main() diff --git a/tools/progress_dashboard.html b/tools/progress_dashboard.html deleted file mode 100644 index 3933f6fb9..000000000 --- a/tools/progress_dashboard.html +++ /dev/null @@ -1,439 +0,0 @@ - - - - - -Leonida progress - - - - -
-
- -

Leonida progress

What works, what changed, what blocks next
-
-
- -
-
-
-
-

Metrics each one a ratio with its own denominator; there is no overall percentage

-
MetricValueNumerator / denominatorFormula
-

Trend one point per snapshot

-
-
A hollow point means the metric's formula changed there; the line breaks because the values on either side are not comparable.
- - - - -

Sources a missing source is never counted as zero or as a failure

-
SourceStatusRecordsPathNote
-
-
- - - - - diff --git a/tools/progress_dashboard.py b/tools/progress_dashboard.py deleted file mode 100644 index 600179f5f..000000000 --- a/tools/progress_dashboard.py +++ /dev/null @@ -1,1106 +0,0 @@ -"""Progress dashboard: what works, what changed and what blocks next, from outcomes the project already produces. - - python -I tools/progress_dashboard.py --out [--work ] [--run-tests] - [--ctest-junit FILE] [--junit FILE ...] [--github] [--login NAME] - -Writes, into --out only (a folder inside the repository is refused, so nothing here can be committed by accident): - progress.html one self-contained page (no network, no packages; open it from disk) - snapshots/progress_.json the data behind it; a snapshot equal to the previous one is not written again - history.json one summary line per snapshot, for the trend chart - unit_results.json the last --run-tests outcome, kept so a later run can show what changed since - -Sources, each optional and reported as missing rather than counted as zero when absent: - unit tests --run-tests runs tests/test_*.py the way CI selects them (standard-library files with a - __main__ block), one process each; the outcome and the commit it ran on are kept - ctest --ctest-junit selects the local CTest report (default: runtime/build/Testing/Temporary/LastTest.log). - --junit adds independent CTest or pytest runs. - gpu tests --gpu-log: saved output of runtime/test/shaders/check.py, one panel group per GPU - contract the translator contract table in docs/design.md, by how each row says it was confirmed - imports the measured import tables in docs/runtime_imports.md - corpus --work: counts per stage from /shaders/dxbc/index.json and /shaders/spirv/index.json - github --github, read-only through `gh`: every pull request into main (merged = implemented, open = - partial), latest CI runs on main, the D3D- table of the D3D12 tracking issue checked against those merges, the - coordination issue's section sizes and, with --login, that account's claims and pull requests - -No game data leaves the inputs: the page and the JSON carry counts, pass/fail, error classes and the project's -own document text; never a shader name, a carved file name or a path into the game copy. -Usage: `python -I tools/progress_dashboard.py --help` lists the options. -""" -import argparse -import base64 -import datetime as dt -import hashlib -import json -import os -import re -import shutil -import subprocess -import sys -import tempfile -import time -import xml.etree.ElementTree as ET -from concurrent.futures import ThreadPoolExecutor - -sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) -from file_mode import published_mode # noqa: E402 -from report_paths import same_report_path # noqa: E402 - -ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) -TEMPLATE = os.path.join(ROOT, "tools", "progress_dashboard.html") -LOGO = os.path.join(ROOT, "assets", "logo.png") -SCHEMA = "leonida.progress/1" -STATUSES = ("verified", "implemented", "partial", "failed", "missing", "blocked", "unknown") -PYTEST_MARKERS = re.compile(r"^import pytest|^ *HAVE_NUMPY =", re.M) # the CI selection rule (ci.yml) -DEFAULT_REPO = "ProjectLeonidaL/leonida" - - -# ----------------------------------------------------------------------------------------------- helpers -def now_utc(): - return dt.datetime.now(dt.timezone.utc).replace(microsecond=0) - - -def iso(t): - if t is None: - return None - if isinstance(t, (int, float)): - t = dt.datetime.fromtimestamp(t, dt.timezone.utc) - return t.replace(microsecond=0).astimezone(dt.timezone.utc).isoformat().replace("+00:00", "Z") - - -def parse_iso(s): - if not s: - return None - try: - d = dt.datetime.fromisoformat(s.replace("Z", "+00:00")) - except ValueError: - return None - return d if d.tzinfo else d.astimezone() - - -def read_utf8(path): - with open(path, encoding="utf-8", errors="replace") as f: - return f.read() - - -def save_text(path, text): - # A fixed `path + ".tmp"` blocks refreshes when that name is taken by a stale directory - # or a concurrent writer. Publish from a unique temp in the same directory instead. - directory = os.path.dirname(os.path.abspath(path)) - fd, tmp = tempfile.mkstemp(prefix=os.path.basename(path) + ".", suffix=".tmp", dir=directory) - try: - with os.fdopen(fd, "w", encoding="utf-8", newline="\n") as f: - f.write(text) - os.chmod(tmp, published_mode(path)) # mkstemp creates 0600 - os.replace(tmp, path) - except BaseException: - try: - os.chmod(tmp, 0o600) # a read-only temp cannot be unlinked on Windows - os.unlink(tmp) - except OSError: - pass - raise - - -def dump_json(obj): - return json.dumps(obj, ensure_ascii=False, sort_keys=True, indent=1) + "\n" - - -def run(cmd, cwd=None, timeout=60): - try: - r = subprocess.run(cmd, cwd=cwd, capture_output=True, timeout=timeout) - except (OSError, subprocess.TimeoutExpired): - return None - if r.returncode != 0: - return None - return r.stdout.decode("utf-8", "replace") - - -HOME = os.path.expanduser("~") - - -def scrub(text, limit=240): - """One line of tool output with every absolute path replaced: a path inside the repository becomes its relative - path, any other path (the work folder, the home folder, a temp folder) becomes , file name included, since - a file name outside the repository can be a carved shader's name.""" - if not text: - return "" - line = text.strip().splitlines()[-1] if text.strip() else "" - - def shown(m): - path = m.group(0) - if os.name != "nt" and re.match(r"(?i)[a-z]:[\\/]", path): - # A drive-letter path is relative to the current folder elsewhere, so realpath would put it inside the - # repository and print it whole (user name and file name included): it is never one of ours here. - return "" - if inside(path, ROOT): - rel = os.path.relpath(os.path.realpath(path), os.path.realpath(ROOT)).replace(os.sep, "/") - return "." if rel == "." else rel - return "" - - # Match the known checkout prefix before the generic patterns stop at whitespace. - if os.name == "nt": - root = r"[\\/]".join(re.escape(part) for part in re.split(r"[\\/]", ROOT)) - checkout = rf"(?i:(? 3: - line = line.replace(HOME, "~") - line = re.sub(r"~[\\/][^\s'\"]*", "", line) - return line[:limit] - - -def inside(child, parent): - child, parent = os.path.realpath(child), os.path.realpath(parent) - try: - return os.path.commonpath([child, parent]) == parent - except ValueError: # different drives on Windows - return False - - -class Collector: - """Gathers components (one per cell), metrics (ratios with an explicit denominator) and source records.""" - - def __init__(self): - self.components = [] - self.ids = set() - self.metrics = [] - self.sources = [] - self.notes = [] - self.panels = {} - - def panel(self, pid, title, unit, weighted=False): - self.panels[pid] = {"id": pid, "title": title, "unit": unit, "weighted": weighted} - - def source(self, sid, path, status, records=None, note=None): - rel = None - if path: - rel = os.path.relpath(path, ROOT).replace("\\", "/") if inside(path, ROOT) else "/" + os.path.basename(path) - self.sources.append({k: v for k, v in {"id": sid, "path": rel, "status": status, "records": records, "note": note}.items() - if v is not None}) - - def add(self, cid, panel, group, name, status, detail=None, weight=None, **attrs): - assert status in STATUSES, status - if cid in self.ids: - n = 2 - while f"{cid}#{n}" in self.ids: - n += 1 - cid = f"{cid}#{n}" - self.ids.add(cid) - c = {"id": cid, "panel": panel, "group": group, "name": name, "status": status} - if detail: - c["detail"] = detail - if weight is not None: - c["weight"] = weight - c.update({k: v for k, v in attrs.items() if v not in (None, "", [], {})}) - self.components.append(c) - - def metric(self, mid, panel, title, num, den, formula, note=None): - val = None if num is None or not den else round(num / den, 6) - self.metrics.append({k: v for k, v in {"id": mid, "panel": panel, "title": title, "numerator": num, "denominator": den, - "value": val, "formula": formula, "note": note, - "definition": hashlib.sha256(formula.encode("utf-8")).hexdigest()[:10]}.items() - if v is not None or k in ("value", "numerator", "denominator")}) - - -# ----------------------------------------------------------------------------------------------- git -def git_info(): - head = run(["git", "rev-parse", "HEAD"], cwd=ROOT) - if head is None: - return {"available": False} - info = {"available": True, "head": head.strip()} - info["head_time"] = iso(int((run(["git", "log", "-1", "--format=%ct"], cwd=ROOT) or "0").strip() or 0)) - info["branch"] = (run(["git", "rev-parse", "--abbrev-ref", "HEAD"], cwd=ROOT) or "").strip() - status = run(["git", "status", "--porcelain", "--untracked-files=no"], cwd=ROOT) or "" - info["modified_files"] = len([l for l in status.splitlines() if l.strip()]) - up = run(["git", "rev-parse", "--verify", "--quiet", "origin/main"], cwd=ROOT) - if up: - info["origin_main"] = up.strip() - counts = run(["git", "rev-list", "--left-right", "--count", "HEAD...origin/main"], cwd=ROOT) - if counts: - ahead, behind = counts.split() - info["ahead"], info["behind"] = int(ahead), int(behind) - return info - - -def changed_since(commit): - """Files changed between `commit` and HEAD plus uncommitted changes, or None when git cannot tell.""" - out = run(["git", "diff", "--name-only", commit, "--"], cwd=ROOT) - if out is None: - return None - return {l.strip() for l in out.splitlines() if l.strip()} - - -def last_commit_time(path): - out = run(["git", "log", "-1", "--format=%ct", "--", path], cwd=ROOT) - return int(out.strip()) if out and out.strip() else None - - -# ----------------------------------------------------------------------------------------------- unit tests -def _walk_error(exc: OSError): - # os.walk skips a directory it cannot list unless onerror raises; the dashboard must not report an - # incomplete test selection or code digest as complete. main() turns the OSError into one error line. - raise exc - - -def ci_test_files(): - """tests/test_*.py that CI runs one by one: standard-library files with a __main__ block (ci.yml).""" - found = [] - tests = os.path.join(ROOT, "tests") - for base, dirs, files in os.walk(tests, onerror=_walk_error): - dirs[:] = sorted(d for d in dirs if d not in ("semantic", "__pycache__", "fixtures")) - for name in sorted(files): - if not (name.startswith("test_") and name.endswith(".py")): - continue - path = os.path.join(base, name) - text = read_utf8(path) - if PYTEST_MARKERS.search(text) or "__main__" not in text: - continue - found.append(os.path.relpath(path, ROOT).replace("\\", "/")) - return found - - -def run_one_test(rel, timeout): - t0 = time.monotonic() - try: - r = subprocess.run([sys.executable, "-I", os.path.join(ROOT, rel)], cwd=ROOT, capture_output=True, timeout=timeout) - out = (r.stdout + r.stderr).decode("utf-8", "replace") - skipped = re.search(r"^OK \(skipped=(\d+)\)\r?$", out, re.M) - res = "pass" if r.returncode == 0 else "fail" - tail = "" if res == "pass" else scrub(out) - ran = re.search(r"Ran (\d+) tests?", out) - cases = int(ran.group(1)) if ran else None - return {"test": rel, "result": res, "seconds": round(time.monotonic() - t0, 2), "detail": tail, - "cases": cases, "all_skipped": bool(skipped and cases == int(skipped.group(1)))} - except subprocess.TimeoutExpired: - return {"test": rel, "result": "fail", "seconds": timeout, "detail": f"timed out after {timeout} s"} - - -CODE_DIRS = ("tools", "scripts", "runtime/test/shaders") - - -def file_digest(rel): - try: - with open(os.path.join(ROOT, rel), "rb") as f: - return hashlib.sha256(f.read()).hexdigest()[:16] - except OSError: - return None - - -def code_digest(): - """Hash make_game.py and the Python files in CODE_DIRS by content, including uncommitted edits.""" - h = hashlib.sha256() - rels = ["make_game.py"] - for d in CODE_DIRS: - for base, dirs, files in os.walk(os.path.join(ROOT, d), onerror=_walk_error): - dirs[:] = sorted(x for x in dirs if x not in ("__pycache__", "bin", "obj", "target", "build") and not x.startswith(".")) - rels += [os.path.relpath(os.path.join(base, f), ROOT).replace("\\", "/") for f in sorted(files) if f.endswith(".py")] - for rel in rels: - h.update(rel.encode("utf-8") + b"\0" + (file_digest(rel) or "-").encode("ascii")) - return h.hexdigest()[:16] - - -def run_unit_tests(files, jobs, timeout): - before = code_digest() - with ThreadPoolExecutor(max_workers=max(1, jobs)) as pool: - results = list(pool.map(lambda f: run_one_test(f, timeout), files)) - for r in results: - r["digest"] = file_digest(r["test"]) - g = git_info() - after = code_digest() - return {"ran_at": iso(now_utc()), "commit": g.get("head"), "modified_files": g.get("modified_files"), - "code_digest": after if after == before else None, # code edited during the run: nothing is current - "python": sys.version.split()[0], "results": sorted(results, key=lambda r: r["test"])} - - -def collect_unit(col, out_dir, args): - col.panel("tests", "Unit tests (CI selection)", "test files") - path = os.path.join(out_dir, "unit_results.json") - if args.run_tests: - print(f"running unit tests ({len(args.test_files)} selected, {args.jobs} at a time)...") - data = run_unit_tests(args.test_files, args.jobs, args.test_timeout) - save_text(path, dump_json(data)) - elif os.path.isfile(path): - data = json.loads(read_utf8(path)) - else: - col.source("unit_results", None, "missing", note="no unit-test outcome yet: run with --run-tests") - return - col.source("unit_results", path, "ok", len(data["results"]), note=f"ran {data['ran_at']} on {str(data.get('commit'))[:10]}") - code_now = code_digest() - code_same = data.get("code_digest") is not None and data["code_digest"] == code_now - passed = current = 0 - for r in data["results"]: - test = r["test"] - if r["result"] != "pass": - fresh = "failed" - elif not r.get("digest") or data.get("code_digest") is None: - fresh = "unknown" - elif code_same and file_digest(test) == r["digest"]: - fresh = "current" - else: - fresh = "revalidation_required" - status = {"pass": "verified", "fail": "failed"}.get(r["result"], "unknown") - if r["result"] == "pass" and r.get("all_skipped"): - status = "unknown" - if status == "verified" and fresh == "revalidation_required": - status = "partial" - passed += r["result"] == "pass" - current += status == "verified" - name = test.split("/", 1)[-1] - col.add("test." + name, "tests", group_of_test(name), name, status, detail=r.get("detail") or None, - freshness=fresh, seconds=r.get("seconds"), cases=r.get("cases"), ran_on=str(data.get("commit"))[:10]) - n = len(data["results"]) - col.metric("tests.passed", "tests", "Unit-test files passing (last run)", passed, n, "files whose last run exited 0 / files run") - col.metric("tests.current", "tests", "Unit-test files passing on the current code", current, n, - "files that passed with no change since to themselves, make_game.py or Python files under " - + ", ".join(d + "/" for d in CODE_DIRS) + " / files run") - - -def group_of_test(name): - stem = name[len("test_"):-3] if name.startswith("test_") else name - head = stem.split("_")[0] - families = {"docs": "docs", "i18n": "docs", "rdna2spirv": "translator", "spirv": "translator", "f16": "translator", - "f32": "translator", "valu": "translator", "cf": "translator", "rpf9": "archives", "rpf9dump": "archives", - "rbf0": "formats", "psin": "formats", "world": "world", "anim": "animation", "tex": "textures", - "bcpack": "textures", "ttpf": "textures", "audio": "audio", "bink": "audio", "make": "make_game", - "gamedata": "gamedata", "navmesh": "world", "story": "world", "d3d12": "runtime", "vk": "runtime"} - return families.get(head, "other") - - -# ----------------------------------------------------------------------------------------------- ctest / junit -def parse_junit(xml): - """[(name, result, seconds, detail)] from CTest (--output-junit) or pytest (--junitxml) XML.""" - root = xml if isinstance(xml, ET.Element) else ET.fromstring(xml) - suites = [root] if root.tag == "testsuite" else root.findall("testsuite") - out = [] - for suite in suites: - for tc in suite.iter("testcase"): - status = tc.get("status") - st = (status or "").lower() - fail = tc.find("failure") if tc.find("failure") is not None else tc.find("error") - if fail is not None or st == "fail": - res = "fail" - elif tc.find("skipped") is not None or st in ("notrun", "disabled"): - res = "skip" - else: - res = "pass" - name, cls = tc.get("name") or "?", tc.get("classname") - if cls and cls != name: - name = f"{cls}::{name}" - try: - secs = float(tc.get("time")) if tc.get("time") else None - except ValueError: - secs = None - detail = scrub((fail.get("message") or "") if fail is not None else "") - out.append((name, res, secs, detail)) - return out - - -def parse_lasttest(text: str) -> list[tuple[str, str, float | None]]: - """[(name, result, seconds)] from CTest's Testing/Temporary/LastTest.log.""" - out, name, secs = [], None, None - captured = False - nested_runs = 0 - lines = text.splitlines() - for index, line in enumerate(lines): - next_line = lines[index + 1] if index + 1 < len(lines) else "" - if captured: - # CTest writes child output verbatim, so it can contain complete nested logs. - if line.startswith("Start testing: ") and next_line == "-" * 58: - nested_runs += 1 - elif nested_runs and line.startswith("End testing: "): - nested_runs -= 1 - elif not nested_runs and line == "" and next_line.startswith("Test time ="): - captured = False - continue - m = re.match(r"^\d+/\d+ Test: (.+)$", line) - if m: - name, secs = m.group(1).strip(), None - continue - if not name: - continue - if line == "Output:": - captured = True - continue - m = re.match(r"^Test time =\s*([\d.]+) sec", line) - if m: - secs = float(m.group(1)) - continue - if line.startswith("Test Passed"): - res = "pass" - elif line == "Test Pass Reason:" and next_line: - res = "skip" if next_line.startswith("Skip regular expression found in output.") else "pass" - elif line.startswith("Test Failed") or line == "Test Fail Reason:": - res = "fail" - elif line.startswith("Test Not Run"): - res = "skip" - else: - continue - out.append((name, res, secs)) - name = None - return out - - -def collect_ctest(col, args): - col.panel("runtime", "Runtime tests (CTest)", "tests") - runtime_changed = last_commit_time("runtime") - seen = 0 - log = os.path.join(ROOT, "runtime", "build", "Testing", "Temporary", "LastTest.log") - sets = [] - reports = [] - local_report = getattr(args, "ctest_junit", None) - if local_report: - reports.append(("ctest_junit", "ctest", local_report)) - elif os.path.isfile(log): - sets.append(("ctest", log, [(n, r, s, "") for n, r, s in parse_lasttest(read_utf8(log))], True)) - col.source("ctest_lasttest", log, "ok", len(sets[-1][2])) - else: - col.source("ctest_lasttest", log, "missing", note="no runtime/build CTest run on this machine") - for path in args.junit or []: - if local_report and same_report_path(path, local_report): - continue - reports.append(("junit", "junit:" + os.path.basename(path), path)) - for source_id, label, path in reports: - if not os.path.isfile(path): - col.source(source_id, path, "missing") - continue - try: - root = ET.parse(path).getroot() - except (ET.ParseError, LookupError, ValueError, OSError) as e: - col.source(source_id, path, "invalid", note=str(e)) - continue - # CTest writes a single testsuite with a disabled count and hostname. pytest wraps its suite in testsuites. - is_ctest = root.tag == "testsuite" and {"disabled", "hostname"} <= root.attrib.keys() - if source_id == "ctest_junit" and not is_ctest: - col.source(source_id, path, "invalid", note="expected a CTest --output-junit report") - continue - rows = parse_junit(root) - sets.append((label, path, rows, is_ctest)) - col.source(source_id, path, "ok", len(rows)) - for label, path, rows, is_ctest in sets: - ran = os.path.getmtime(path) - for name, res, secs, detail in rows: - if res == "fail": - fresh, status = "failed", "failed" - elif res == "skip": - fresh, status = "unknown", "unknown" - elif is_ctest and runtime_changed and ran < runtime_changed: - fresh, status = "revalidation_required", "partial" - else: - fresh, status = "current", "verified" - seen += 1 - col.add(f"ctest.{label}.{name}", "runtime", label, name, status, detail=detail or None, freshness=fresh, seconds=secs, - ran_at=iso(ran)) - if seen: - ok = sum(1 for c in col.components if c["panel"] == "runtime" and c["status"] == "verified") - col.metric("runtime.current", "runtime", "Runtime tests passing on the current code", ok, seen, - "passing tests, excluding CTest reports older than the last commit touching runtime/ / tests recorded") - - -# ----------------------------------------------------------------------------------------------- GPU tests -GPU_LINE = re.compile(r"^(\S+)\s+(ok|SKIP \(.*\)|.+)$") -GPU_SUMMARY = re.compile(r"^(\d+) of (\d+) pass, (\d+) skipped") - - -def parse_gpu_log(text): - """[(shader test, result, detail)] from the output of runtime/test/shaders/check.py (one line per test, - " ok", " SKIP (why)" or " ", then "N of M pass, K skipped").""" - rows, summary = [], None - for line in text.splitlines(): - m = GPU_SUMMARY.match(line.strip()) - if m: - summary = tuple(int(x) for x in m.groups()) - continue - m = GPU_LINE.match(line.rstrip()) - # check.py prints f"{name:20} {result}": the result starts right after the name padded to 20 columns, - # which tells result lines from the other lines it prints (the build folder it picked, warnings) - if not m or not re.fullmatch(r"[A-Za-z0-9_.]+", m.group(1)) or m.start(2) != max(len(m.group(1)), 20) + 1: - continue - name, rest = m.group(1), m.group(2).strip() - if rest == "ok": - rows.append((name, "pass", "")) - elif rest.startswith("SKIP"): - rows.append((name, "skip", rest)) - else: - rows.append((name, "fail", scrub(rest))) - return rows, summary - - -def collect_gpu(col, logs): - col.panel("gpu", "GPU tests (hand-written RDNA2 programs)", "test programs") - if not logs: - col.source("gpu_logs", None, "missing", note="pass --gpu-log [=]") - return - changed = max(t for t in (last_commit_time("runtime/test/shaders"), last_commit_time("tools/rdna2spirv.py"), 0) if t is not None) - for spec in logs: - path, _, label = spec.partition("=") - if not os.path.isfile(path): - col.source("gpu_log", path, "missing") - continue - rows, summary = parse_gpu_log(read_utf8(path)) - label = label or os.path.splitext(os.path.basename(path))[0] - note = None - if summary and summary[1] != len(rows): - note = f"summary says {summary[1]} tests, {len(rows)} lines parsed" - col.source("gpu_log", path, "ok" if rows else "invalid", len(rows), note=note) - ran = os.path.getmtime(path) - for name, res, detail in rows: - if res == "fail": - status, fresh = "failed", "failed" - elif res == "skip": - status, fresh = "unknown", "unknown" - elif changed and ran < changed: - status, fresh = "partial", "revalidation_required" - else: - status, fresh = "verified", "current" - col.add(f"gpu.{label}.{name}", "gpu", label, name, status, detail=detail or None, freshness=fresh, ran_at=iso(ran)) - tested = [c for c in col.components if c["panel"] == "gpu" and c["status"] != "unknown"] - if tested: - col.metric("gpu.current", "gpu", "GPU test programs passing on the current translator", sum(c["status"] == "verified" for c in tested), - len(tested), "programs ok after the last commit touching runtime/test/shaders or tools/rdna2spirv.py / programs run (skips excluded)") - - -# ----------------------------------------------------------------------------------------------- docs -def md_tables(text): - """[(heading, header_cells, rows, first_line)] for every pipe table in a Markdown text.""" - lines, out, heading, i = text.splitlines(), [], None, 0 - sep = re.compile(r"^\s*\|?\s*:?-{3,}:?\s*(\|\s*:?-{3,}:?\s*)*\|?\s*$") - while i < len(lines): - ln = lines[i] - if ln.startswith("#"): - heading = ln.lstrip("#").strip() - if ln.lstrip().startswith("|") and i + 1 < len(lines) and sep.match(lines[i + 1]): - header = cells(ln) - rows, j = [], i + 2 - while j < len(lines) and lines[j].lstrip().startswith("|"): - rows.append(cells(lines[j])) - j += 1 - out.append((heading, header, rows, i + 1)) - i = j - continue - i += 1 - return out - - -def cells(line): - s = line.strip().strip("|") - parts, buf, tick = [], [], False - for ch in s: - if ch == "`": - tick = not tick - if ch == "|" and not tick: - parts.append("".join(buf).strip()) - buf = [] - else: - buf.append(ch) - parts.append("".join(buf).strip()) - return parts - - -def plain(s): - s = re.sub(r"\[([^\]]+)\]\([^)]+\)", r"\1", s) - return re.sub(r"\*\*|`", "", s).strip() - - -# How a contract row says it was confirmed. The first matching rule decides; the matched words are kept as evidence. -CONFIRMATION = [ - ("not_gpu", "partial", re.compile(r"not yet GPU-(?:verified|checked)|Unmeasured|still needs an? [^.]{0,40}(?:GPU|part)|no GPU measurement", re.I)), - ("gpu", "verified", re.compile(r"GPU-checked|GPU-verified|measured on (?:an? )?(?:gfx\d+|AMD|NVIDIA|Intel|Apple|RX |RTX |GeForce|Radeon)|" - r"run_gpu_tests|on an? (?:AMD|NVIDIA|Intel|Apple) [^.]{0,30}(?:GPU|Radeon|GeForce|RTX|RX|Arc|M\d)", re.I)), - ("reference", "implemented", re.compile(r"Source: (?:LLVM|Mesa)|LLVM `|Mesa `|llvm-mc|ACO|RADV", re.I)), - ("corpus", "implemented", re.compile(r"\bcorpus\b|of the 26,\d{3}|over (?:all|the) [\d,]+ shaders", re.I)), - ("cpu", "implemented", re.compile(r"CPU-checked|CPU reference|unit test|tests/semantic|exact-arithmetic model", re.I)), -] -OPEN = re.compile(r"\bstill open\b|\bremains? open\b|\bopen items?\b", re.I) - - -def classify_contract(text): - for kind, status, rx in CONFIRMATION: - m = rx.search(text) - if m: - return kind, status, m.group(0) - return "unstated", "unknown", None - - -def collect_contract(col): - col.panel("contract", "Translator contract (docs/design.md)", "contract rows") - path = os.path.join(ROOT, "docs", "design.md") - if not os.path.isfile(path): - col.source("contract", path, "missing") - return - tables = [t for t in md_tables(read_utf8(path)) if t[0] and "contract" in t[0].lower()] - if not tables: - col.source("contract", path, "invalid", note="no table under a 'contract' heading") - return - rows = tables[0][2] - counts = {} - for k, row in enumerate(rows): - if len(row) < 2: - continue - piece, text = plain(row[0]), plain(" ".join(row[1:])) - kind, status, words = classify_contract(text) - if status == "verified" and OPEN.search(text): - status = "partial" - kind += "+open" - counts[kind] = counts.get(kind, 0) + 1 - col.add(f"contract.{k:03d}", "contract", kind_label(kind), piece[:120], status, - detail=(f"confirmation: “{words}”" if words else "no confirmation method stated in the row"), - line=tables[0][3] + 2 + k, open_items=bool(OPEN.search(text)) or None) - col.source("contract", path, "ok", len(rows)) - gpu = sum(1 for c in col.components if c["panel"] == "contract" and c["status"] == "verified") - col.metric("contract.gpu", "contract", "Contract rows confirmed on a GPU, nothing left open", gpu, len(rows), - "rows naming a GPU check and no open item / rows in the contract table") - stated = sum(1 for c in col.components if c["panel"] == "contract" and c["status"] != "unknown") - col.metric("contract.stated", "contract", "Contract rows that state how they were confirmed", stated, len(rows), - "rows matching a confirmation rule (GPU, LLVM/Mesa reference, corpus count, CPU test) / rows") - - -def kind_label(kind): - return {"gpu": "GPU-checked", "gpu+open": "GPU-checked, items open", "not_gpu": "Waiting for a GPU measurement", - "reference": "LLVM/Mesa reference", "corpus": "Corpus count", "cpu": "CPU test only", - "unstated": "Confirmation not stated"}.get(kind, kind) - - -def collect_imports(col): - col.panel("imports", "Runtime imports (docs/runtime_imports.md)", "imports") - path = os.path.join(ROOT, "docs", "runtime_imports.md") - if not os.path.isfile(path): - col.source("imports", path, "missing") - return - n = unimpl = 0 - for heading, header, rows, _ in md_tables(read_utf8(path)): - h = [plain(x).lower() for x in header] - if "binding" in h and "import" in h: - bi, ii, ci = h.index("binding"), h.index("import"), h.index("consumer") if "consumer" in h else 0 - for row in rows: - if len(row) <= max(bi, ii): - continue - binding = plain(row[bi]).lower() - status = "missing" if "unimpl" in binding or binding in ("none", "missing") else "implemented" - unimpl += status == "missing" - n += 1 - col.add(f"import.{plain(row[ci])}.{plain(row[ii])}", "imports", plain(row[ci]), plain(row[ii]), status, - detail=f"binding: {binding}") - elif "unimplemented" in h and "image" in h: - ui, ii = h.index("unimplemented"), h.index("image") - for row in rows: - if len(row) > ui and plain(row[ui]).replace(",", "").isdigit(): - k = int(plain(row[ui]).replace(",", "")) - col.add(f"image.{plain(row[ii])}", "imports", "Images (unimplemented imports)", plain(row[ii]), - "verified" if k == 0 else "missing", detail=f"{k} unimplemented import(s), as measured in the document") - col.source("imports", path, "ok", n) - if n: - col.metric("imports.bound", "imports", "Measured imports with a binding", n - unimpl, n, - "imports bound to a shim, the host or a shipped module / imports listed") - - -# ----------------------------------------------------------------------------------------------- corpus (counts only) -def collect_corpus(col, work): - col.panel("corpus", "Shader corpus (your own run; counts only)", "shaders, aggregated per stage", weighted=True) - if not work: - col.source("corpus", None, "missing", note="pass --work to count your own translation run") - return - # make_game.py writes /shaders/dxbc and /shaders/spirv; the shaders folder itself is accepted too - shaders = os.path.join(work, "shaders") if os.path.isdir(os.path.join(work, "shaders", "dxbc")) else work - carved_p, spirv_p = os.path.join(shaders, "dxbc", "index.json"), os.path.join(shaders, "spirv", "index.json") - if not os.path.isfile(carved_p): - col.source("corpus", None, "missing", note="no /shaders/dxbc/index.json (run make_game.py's shaders stage)") - return - carved = json.loads(read_utf8(carved_p)) - entries = carved if isinstance(carved, list) else list(carved.values()) - per_stage = {} - for e in entries: - st = (e.get("stage") if isinstance(e, dict) else None) or "unknown" - per_stage.setdefault(st, [0, 0])[0] += 1 - validated_total = 0 - if os.path.isfile(spirv_p): - spirv = json.loads(read_utf8(spirv_p)) - for meta in spirv.values(): - if isinstance(meta, dict) and "error" not in meta: - st = meta.get("stage") or "unknown" - per_stage.setdefault(st, [0, 0])[1] += 1 - validated_total += 1 - col.source("corpus_spirv", "/shaders/spirv/index.json", "ok", len(spirv)) - else: - col.source("corpus_spirv", "/shaders/spirv/index.json", "missing", note="translation not finished") - col.source("corpus_carved", "/shaders/dxbc/index.json", "ok", len(entries)) - for st, (n_carved, n_valid) in sorted(per_stage.items()): - stage = str(st) - if n_valid: - col.add(f"corpus.{stage}.validated", "corpus", stage, f"{stage}: pass spirv-val", "implemented", - detail=f"{n_valid:,} of {n_carved:,} carved", weight=n_valid, count=n_valid) - rest = max(n_carved - n_valid, 0) - if rest: - col.add(f"corpus.{stage}.not_validated", "corpus", stage, f"{stage}: not translated or rejected by spirv-val", - "failed", detail=f"{rest:,} of {n_carved:,} carved", weight=rest, count=rest) - col.metric("corpus.validated", "corpus", "Carved shaders that translate and pass spirv-val", validated_total, len(entries), - "entries in /shaders/spirv/index.json without an error / entries in /shaders/dxbc/index.json", - note="validation is not execution: nothing here says a shader's output is right") - col.notes.append("corpus: counts come from your own work folder; no shader name or path is stored") - - -# ----------------------------------------------------------------------------------------------- github (read-only) -def gh_json(args, timeout=60): - out = run(["gh"] + args, timeout=timeout) - if out is None: - return None - try: - return json.loads(out) - except ValueError: - return None - - -def d3d_state(owner, pr, status_text, merged_prs=None, open_prs=None): - """State of one D3D- row. With the repository's merged and open pull-request numbers, a PR the table still shows - as open but already merged counts as merged, and one closed without merging is dropped; without them the - table's own words decide.""" - refs = re.findall(r"#(\d+)((?:\s+(?:merged|closed|on main))?)", pr) - said_merged = {int(r) for r, suffix in refs if "merged" in suffix or "on main" in suffix} - bare = [int(r) for r, suffix in refs if not suffix.strip()] - text_open = "PR open" in status_text or "draft" in status_text.lower() - if merged_prs is not None and open_prs is not None: - merged = said_merged | {r for r in bare if r in merged_prs} - still_open = [r for r in bare if r in open_prs] - text_open = text_open and not refs - else: - merged, still_open = said_merged, bare - if still_open or text_open: - return "partial", "pull request open" - if merged: - return "implemented", "merged on main" - if owner and owner not in ("—", "-", ""): - return "unknown", "claimed, no code yet" - return "missing", "unclaimed" - - -PR_LIMIT = 5000 -ITEM_ID = re.compile(r"\b([A-Z][A-Z0-9]{0,9})-(\d+)\b") -NOT_ITEMS = {"SHA", "UTF", "IEEE", "ISO", "RFC", "CRC", "CVE", "MD", "BC", "X", "R", "G", "B"} - - -def item_ids(title): - """Coordination item IDs named in a pull-request title ("D3D-86: ...", "... (SHADER-339)"), in order, once each. - A prefix ending in a digit (D3D12-, OPTIONS2-) or a known non-item word (SHA-256, UTF-8) is not an item.""" - out = [] - for prefix, num in ITEM_ID.findall(title or ""): - if prefix in NOT_ITEMS or prefix[-1].isdigit(): - continue - if f"{prefix}-{num}" not in out: - out.append(f"{prefix}-{num}") - return out - - -def d3d_item_ids(pulls): - """D3D- item IDs named by the titles of these pull requests.""" - return {i for p in pulls for i in item_ids(p.get("title")) if i.startswith("D3D-")} - - -def collect_pulls(col, repo, merged, open_prs, limit=PR_LIMIT): - """Every pull request into main: merged is IMPLEMENTED, open is PARTIAL; closed without merging is left out. - Grouped by the item family its title names (D3D, SHADER, BUILD, ...).""" - col.panel("merged", f"Pull requests into main ({repo}): merged = implemented", "pull requests") - note = f"{len(merged)} merged, {len(open_prs)} open" - if len(merged) >= limit or len(open_prs) >= limit: - note += f"; the {limit}-PR limit was reached, older pull requests are not counted" - col.source("github_prs", None, "ok", len(merged) + len(open_prs), note=note) - items_merged, items_any = set(), set() - for p, status in [(p, "implemented") for p in merged] + [(p, "partial") for p in open_prs]: - ids = item_ids(p.get("title")) - items_any.update(ids) - if status == "implemented": - items_merged.update(ids) - group = (ids[0].split("-")[0] + " items") if ids else "no item ID" - if status == "implemented": - detail = f"merged on main {p.get('mergedAt') or ''}".strip() - else: - detail = "pull request open" + (" (draft)" if p.get("isDraft") else "") - col.add(f"pr.{p['number']}", "merged", group, f"#{p['number']} {p.get('title') or ''}"[:120], status, detail=detail, - number=p["number"], items=ids, merged_at=p.get("mergedAt") if status == "implemented" else None, - author=(p.get("author") or {}).get("login")) - col.metric("merged.prs", "merged", "Pull requests into main that are merged", len(merged), len(merged) + len(open_prs), - "pull requests merged into main / merged + open (closed without merging are left out)") - if items_any: - col.metric("merged.items", "merged", "Coordination items with a merged pull request", len(items_merged), len(items_any), - "item IDs (D3D-, SHADER-, BUILD-, ...) named by a merged PR title / item IDs named by a merged or open PR title") - latest = sorted(merged, key=lambda p: p.get("mergedAt") or "", reverse=True)[:30] - return [{"number": p["number"], "title": (p.get("title") or "")[:120], "merged_at": p.get("mergedAt"), - "items": item_ids(p.get("title")), "author": (p.get("author") or {}).get("login")} for p in latest] - - -D3D_ISSUE_TITLE = "D3D12 → Vulkan layer" - - -def find_d3d_issue(repo): - """Number of the open issue that tracks the D3D12 → Vulkan layer in this repository, or None. - - It is looked up by title, like the coordination issue: a fixed number only holds for one repository (it was - #313 where the project started), and in another one the same number is some unrelated issue or pull request.""" - found = gh_json(["issue", "list", "-R", repo, "--state", "open", "--search", "D3D12 Vulkan layer in:title", - "--json", "number,title"]) or [] - want = re.sub(r"\W+", " ", D3D_ISSUE_TITLE).lower().split() - for issue in sorted(found, key=lambda i: i["number"]): - if re.sub(r"\W+", " ", issue.get("title") or "").lower().split()[:len(want)] == want: - return issue["number"] - return None - - -def collect_github(col, repo, login, d3d_issue=None): - col.panel("d3d12", "D3D12 → Vulkan layer items", "D3D- items") - col.panel("ci", "CI on main", "workflows") - if not shutil.which("gh"): - col.source("github", None, "missing", note="gh is not installed") - return {} - summary = {"repo": repo} - # every pull request into main, so a merge shows up on the next run even before a tracking table is edited - merged = gh_json(["pr", "list", "-R", repo, "--state", "merged", "--base", "main", "--limit", str(PR_LIMIT), - "--json", "number,title,mergedAt,author"], timeout=300) - open_prs = gh_json(["pr", "list", "-R", repo, "--state", "open", "--base", "main", "--limit", str(PR_LIMIT), - "--json", "number,title,isDraft,author"], timeout=300) - merged_set = open_set = None - if merged is None or open_prs is None: - col.panel("merged", f"Pull requests into main ({repo}): merged = implemented", "pull requests") - col.source("github_prs", None, "invalid", note="gh pr list failed (not logged in?)") - else: - summary["merged_latest"] = collect_pulls(col, repo, merged, open_prs) - merged_set, open_set = {p["number"] for p in merged}, {p["number"] for p in open_prs} - runs = gh_json(["run", "list", "-R", repo, "--branch", "main", "--limit", "40", - "--json", "workflowName,conclusion,status,headSha,createdAt,url"]) - if runs is None: - col.source("github_ci", None, "invalid", note="gh run list failed (not logged in?)") - else: - latest, pending = {}, {} - for r in runs: # newest first: the first completed run per workflow decides; a newer one still running is noted - if r["status"] == "completed": - latest.setdefault(r["workflowName"], r) - elif r["workflowName"] not in latest: - pending.setdefault(r["workflowName"], r) - for name in sorted(set(latest) | set(pending)): - r, newer = latest.get(name), pending.get(name) - if r is None: - status, what, r = "unknown", f"no completed run in the last 40; one {newer['status']}", newer - else: - status, what = ("verified" if r["conclusion"] == "success" else "failed"), r["conclusion"] - col.add(f"ci.{name}", "ci", "latest completed run per workflow", name, status, - detail=f"{what} on {r['headSha'][:10]}" + (f"; a newer run is {newer['status']}" if newer and newer is not r else ""), - at=r["createdAt"], url=r.get("url")) - col.source("github_ci", None, "ok", len(latest)) - d3d_number = d3d_issue or find_d3d_issue(repo) - issue = None - if d3d_number is None: - col.source("github_d3d12", None, "missing", - note=f'no open issue titled "{D3D_ISSUE_TITLE} ..." in {repo}: pass --d3d-issue N to name one') - else: - col.panel("d3d12", f"D3D12 → Vulkan layer items (#{d3d_number})", "D3D- items") - summary["d3d_issue"] = d3d_number - issue = gh_json(["issue", "view", str(d3d_number), "-R", repo, "--json", "body,updatedAt"]) - if not issue: - col.source("github_d3d12", None, "invalid", note=f"issue #{d3d_number} could not be read") - if issue: - n = 0 - table_ids, table_done = set(), set() - for heading, header, rows, _ in md_tables(issue["body"]): - h = [plain(x).lower() for x in header] - if h[:1] != ["id"] or "pr" not in h: - continue - for row in rows: - if not plain(row[0]).startswith("D3D-") or len(row) < len(h): - continue - owner, pr, st = plain(row[h.index("owner")]), plain(row[h.index("pr")]), plain(row[h.index("status")]) if "status" in h else "" - status, why = d3d_state(owner, pr, st, merged_set, open_set) - table_ids.add(plain(row[0])) - if status == "implemented": - table_done.add(plain(row[0])) - n += 1 - col.add(f"d3d.{plain(row[0])}", "d3d12", why, f"{plain(row[0])} {plain(row[1])}"[:120], status, - detail=(st or why)[:200], owner=owner, prs=pr[:120]) - col.source("github_d3d12", None, "ok", n, note=f"issue #{d3d_number}, updated {issue.get('updatedAt')}") - if n: - # the table lists only items still in progress; a merged item leaves it, so the merges are counted where they are recorded - lists_read = merged_set is not None - merged_ids = d3d_item_ids(merged) if lists_read else set() - open_ids = d3d_item_ids(open_prs) if lists_read else set() - pr_done = (merged_ids - table_ids) - open_ids # rows in the issue keep the table's state; the rest need a merged PR and no open one - col.metric("d3d12.merged", "d3d12", "D3D- items merged on main" + ("" if lists_read else " (partial)"), - len(table_done | pr_done), len(table_ids | merged_ids | open_ids), - "tracking-issue rows whose state is implemented (d3d_state), plus D3D- IDs not in it that a merged PR title names " - "and no open PR title names / all known D3D- IDs (its rows plus IDs named by any merged or open PR title)", - note=None if lists_read else "partial: the merged or open PR list could not be read, " - "so only the tracking issue's rows are counted") - coord = gh_json(["issue", "list", "-R", repo, "--state", "open", "--search", "Coordinating who works on what in:title", - "--json", "number,title,updatedAt"]) - if coord: - num = coord[0]["number"] - body = gh_json(["issue", "view", str(num), "-R", repo, "--json", "body"]) or {} - text = body.get("body", "") - sizes = {} - for sec in ("Up for grabs", "Ready for review or a GPU test", "Needs a rebase on `main`"): - m = re.search(r"### " + re.escape(sec) + r"(.*?)(?=\n### |\Z)", text, re.S) - if m: - part = m.group(1) - sizes[plain(sec)] = (len(re.findall(r"^\|\s*(?:⭐\s*)?[A-Z]+-\d+", part, re.M)) if sec == "Up for grabs" - else len(set(re.findall(r"#(\d+)", part)))) - summary["coordination"] = {"issue": num, "updated": coord[0]["updatedAt"], "sizes": sizes} - col.source("github_coordination", None, "ok", len(sizes), note=f"issue #{num}") - if login: - # claims made in the issue this one continues still count (its own first paragraph says so) - prev = re.search(r"continues #(\d+)", text) - claims = [] - for n in [num] + ([int(prev.group(1))] if prev else []): - comments = gh_json(["issue", "view", str(n), "-R", repo, "--json", "comments"]) or {} - claims += [{"at": c.get("createdAt"), "issue": n, "text": plain(c["body"].splitlines()[0])[:160]} - for c in comments.get("comments", []) - if c.get("author", {}).get("login") == login and "claiming" in c["body"].lower()] - prs = gh_json(["pr", "list", "-R", repo, "--author", login, "--state", "all", "--limit", "50", - "--json", "number,title,state,isDraft,updatedAt"]) or [] - summary["mine"] = {"login": login, "claims": claims, - "pull_requests": [{"number": p["number"], "title": p["title"][:120], "state": p["state"], - "draft": p.get("isDraft"), "updated": p.get("updatedAt")} for p in prs]} - return summary - - -# ----------------------------------------------------------------------------------------------- snapshot + page -def counts_by_panel(components): - out = {} - for c in components: - p = out.setdefault(c["panel"], {s: 0 for s in STATUSES}) - p[c["status"]] += 1 - return out - - -def build(args, out_dir): - col = Collector() - g = git_info() - collect_unit(col, out_dir, args) - collect_ctest(col, args) - collect_gpu(col, args.gpu_log) - collect_contract(col) - collect_imports(col) - collect_corpus(col, args.work) - gh = collect_github(col, args.repo, args.login, args.d3d_issue) if args.github else {} - if not args.github: - col.source("github", None, "skipped", note="pass --github to read pull requests into main, CI, the D3D12 tracking issue and the " - "coordination issue") - snap = { - "schema": SCHEMA, "generated_at": iso(now_utc()), "git": g, - "panels": [col.panels[k] for k in ("tests", "runtime", "gpu", "contract", "imports", "corpus", "merged", "d3d12", "ci") if k in col.panels], - "counts": counts_by_panel(col.components), "components": col.components, "metrics": col.metrics, - "sources": col.sources, "notes": col.notes, "github": gh, - } - body = {k: v for k, v in snap.items() if k != "generated_at"} - snap["content_hash"] = hashlib.sha256(json.dumps(body, sort_keys=True, ensure_ascii=False).encode("utf-8")).hexdigest() - return snap - - -def summary_line(snap): - return {"generated_at": snap["generated_at"], "head": (snap["git"].get("head") or "")[:10], "content_hash": snap["content_hash"][:16], - "metrics": {m["id"]: {"v": m["value"], "n": m["numerator"], "d": m["denominator"], "f": m["definition"]} for m in snap["metrics"]}} - - -def logo_src(): - """The project logo (assets/logo.png) as a data: URI, so the page stays one file that opens from disk; empty when - the asset is absent, and the page then shows no image.""" - try: - with open(LOGO, "rb") as f: - data = f.read() - except OSError: - return "" - return "data:image/png;base64," + base64.b64encode(data).decode("ascii") if data[:8] == b"\x89PNG\r\n\x1a\n" else "" - - -def render_page(snap, history): - template = read_utf8(TEMPLATE) - payload = json.dumps({"snapshot": snap, "history": history}, ensure_ascii=False, sort_keys=True) - payload = payload.replace(" {os.path.join(out_dir, 'progress.html')}" - + ("" if new else " (no change since the last snapshot)")) - return 0 - - -if __name__ == "__main__": - try: # a redirected stdout is strict ANSI code page under -I; write '?' for what it cannot encode - sys.stdout.reconfigure(errors="replace") - except (AttributeError, ValueError, OSError): - pass - sys.exit(main()) diff --git a/tools/ps_helper_probe.py b/tools/ps_helper_probe.py deleted file mode 100644 index d05ffe1a4..000000000 --- a/tools/ps_helper_probe.py +++ /dev/null @@ -1,289 +0,0 @@ -r"""SHADER-681: measure pixel-shader helper lanes at a triangle edge on an AMD GPU (raw RDNA2 ISA, ps_oracle.py). - -docs/design.md's whole-quad-mode row left "helper-invocation behaviour at triangle edges" untested, and the -translator's model of a pixel wave's entry EXEC (helpers off until s_wqm turns their quad on) came from the ISA guide -and ACO. This draws one triangle whose edge cuts 2x2 quads of a 16 x 16 target (vertices (-1, -1), (1.3, -1), -(-1, 0.9); the varying at location 0 is the vertex position, so every lane's interpolated value is its own pixel -centre in NDC) and runs seven wave64 programs as the pixel shader: - - masks, self each covered lane exports its lane id, the wave's EXEC at entry and after s_wqm_b64 - nb12, nb3 after s_wqm, each covered lane reads its quad neighbours' interpolated x/y through DPP quad_perm, - so a helper's values reach the target through a covered pixel - nowqm_ij no s_wqm: a helper's raw I/J (v0/v1) and an unwritten VGPR, read with fetch-inactive DPP, and a - DPP read of an inactive lane without fi into a preloaded destination - nowqm_masks no s_wqm: EXEC at entry and later - helper_export after s_wqm (helpers on in EXEC) an `exp mrt0 ... done vm`: are pixels outside the triangle written? - -The template pixel shader takes a derivative (OpDPdx), so the driver builds it as a shader that needs quads. Every -check and its result is printed; --json writes the raw words. Standard library only, no game files. - - python -I tools/ps_helper_probe.py --build [--json out.json] - -Select the GPU with LEONIDA_VK_DEVICE, as for ps_oracle. Exit codes: 0 every check holds (the gfx1036 -measurement), 1 a check differs, 2 a harness error, 77 no pixel-shader oracle on this device (see ps_oracle) or a -wave32 pixel stage (the programs are wave64). -Usage: `python -I tools/ps_helper_probe.py --help` lists the options. -""" -import argparse -import json -import os -import struct -import sys -import tempfile - -HERE = os.path.dirname(os.path.abspath(__file__)) -sys.path.insert(0, HERE) -import ps_oracle # noqa: E402 - -SIZE = (16, 16) -TRI = ((-1.0, -1.0), (1.3, -1.0), (-1.0, 0.9)) -CLEAR = (0xBF800000,) * 4 # vk_harness clears to -1.0 -SENTINEL = 0x11111111 - -VS_EDGE = """\ - OpCapability Shader - OpMemoryModel Logical GLSL450 - OpEntryPoint Vertex %main "main" %vid %pos %out0 - OpDecorate %vid BuiltIn VertexIndex - OpDecorate %pos BuiltIn Position - OpDecorate %out0 Location 0 - %void = OpTypeVoid - %fn = OpTypeFunction %void - %uint = OpTypeInt 32 0 - %int = OpTypeInt 32 1 - %float = OpTypeFloat 32 - %v4 = OpTypeVector %float 4 - %p_in = OpTypePointer Input %int - %p_out = OpTypePointer Output %v4 - %u3 = OpConstant %uint 3 - %arr = OpTypeArray %v4 %u3 - %p_arr = OpTypePointer Function %arr - %p_v4 = OpTypePointer Function %v4 - %fm1 = OpConstant %float -1 - %f0 = OpConstant %float 0 - %f1 = OpConstant %float 1 - %fx1 = OpConstant %float {bx} - %fy2 = OpConstant %float {cy} - %p0 = OpConstantComposite %v4 %fm1 %fm1 %f0 %f1 - %p1 = OpConstantComposite %v4 %fx1 %fm1 %f0 %f1 - %p2 = OpConstantComposite %v4 %fm1 %fy2 %f0 %f1 - %pa = OpConstantComposite %arr %p0 %p1 %p2 - %vid = OpVariable %p_in Input - %pos = OpVariable %p_out Output - %out0 = OpVariable %p_out Output - %main = OpFunction %void None %fn - %e = OpLabel - %vp = OpVariable %p_arr Function - OpStore %vp %pa - %i = OpLoad %int %vid - %pp = OpAccessChain %p_v4 %vp %i - %p = OpLoad %v4 %pp - OpStore %pos %p - OpStore %out0 %p - OpReturn - OpFunctionEnd -""".format(bx=TRI[1][0], cy=TRI[2][1]) - -PS_DERIV = """\ - OpCapability Shader - OpMemoryModel Logical GLSL450 - OpEntryPoint Fragment %main "main" %in0 %out - OpExecutionMode %main OriginUpperLeft - OpDecorate %out Location 0 - OpDecorate %in0 Location 0 - %void = OpTypeVoid - %fn = OpTypeFunction %void - %float = OpTypeFloat 32 - %v4 = OpTypeVector %float 4 - %p_in = OpTypePointer Input %v4 - %p_out = OpTypePointer Output %v4 - %out = OpVariable %p_out Output - %in0 = OpVariable %p_in Input - %f1 = OpConstant %float 1 - %main = OpFunction %void None %fn - %e = OpLabel - %a = OpLoad %v4 %in0 - %x = OpCompositeExtract %float %a 0 - %y = OpCompositeExtract %float %a 1 - %dx = OpDPdx %float %x - %r = OpCompositeConstruct %v4 %x %y %dx %f1 - OpStore %out %r - OpReturn - OpFunctionEnd -""" - -DPP = " row_mask:0xf bank_mask:0xf" -# v0/v1 = I/J and M0 from s2, as --show-template prints for this template on gfx1036 (RADV) -HEAD = ["s_mov_b64 s[20:21], exec", "{wqm}", "s_mov_b64 s[22:23], exec", "s_mov_b32 m0, s2", - "v_interp_p1_f32_e32 v2, v0, attr0.x", "v_interp_p2_f32_e32 v2, v1, attr0.x", - "v_interp_p1_f32_e32 v3, v0, attr0.y", "v_interp_p2_f32_e32 v3, v1, attr0.y", - "v_mbcnt_lo_u32_b32 v4, -1, 0", "v_mbcnt_hi_u32_b32 v4, -1, v4"] -RESTORE = ["s_mov_b64 exec, s[20:21]"] -X1, X2, X3 = "quad_perm:[1,0,3,2]", "quad_perm:[2,3,0,1]", "quad_perm:[3,2,1,0]" # lane ^ 1, ^ 2, ^ 3 -PROGRAMS = { - "masks": (True, RESTORE + ["v_mov_b32_e32 v5, s20", "v_mov_b32_e32 v6, s21", "v_mov_b32_e32 v7, s22", - "exp mrt0, v4, v5, v6, v7 done vm", "s_endpgm"]), - "self": (True, RESTORE + ["v_mov_b32_e32 v5, s23", "exp mrt0, v4, v5, v2, v3 done vm", "s_endpgm"]), - "nb12": (True, [f"v_mov_b32_dpp v5, v2 {X1}{DPP}", f"v_mov_b32_dpp v6, v3 {X1}{DPP}", - f"v_mov_b32_dpp v7, v2 {X2}{DPP}", f"v_mov_b32_dpp v8, v3 {X2}{DPP}"] + RESTORE + - ["exp mrt0, v5, v6, v7, v8 done vm", "s_endpgm"]), - "nb3": (True, [f"v_mov_b32_dpp v5, v2 {X3}{DPP}", f"v_mov_b32_dpp v6, v3 {X3}{DPP}"] + RESTORE + - ["exp mrt0, v5, v6, v5, v6 done vm", "s_endpgm"]), - "nowqm_ij": (False, ["v_mov_b32_e32 v9, 0x7fc0dead", - f"v_mov_b32_dpp v5, v0 {X1}{DPP} fi:1", f"v_mov_b32_dpp v6, v1 {X1}{DPP} fi:1", - f"v_mov_b32_dpp v7, v2 {X1}{DPP} fi:1", - f"v_mov_b32_e32 v8, 0x{SENTINEL:08x}", f"v_mov_b32_dpp v8, v9 {X1}{DPP}", - "exp mrt0, v5, v6, v7, v8 done vm", "s_endpgm"]), - "nowqm_masks": (False, ["v_mov_b32_e32 v5, s20", "v_mov_b32_e32 v6, s21", "v_mov_b32_e32 v7, s22", - "exp mrt0, v4, v5, v6, v7 done vm", "s_endpgm"]), - "helper_export": (True, ["v_mov_b32_e32 v5, 0x3f800000", "exp mrt0, v5, v5, v5, v5 done vm", "s_endpgm"]), -} - - -def program(name): - wqm, tail = PROGRAMS[name] - return [ln.format(wqm="s_wqm_b64 exec, exec" if wqm else "s_nop 0") for ln in HEAD] + tail - - -def f32(w): - return struct.unpack("> 1)) - - -def analyze(res, size=SIZE, tri=TRI): - """[(check, ok, detail)] from res: {program name: {(x, y): 4 words}}.""" - cov = {p for p, w in res["masks"].items() if tuple(w) != CLEAR} - lane = {p: res["masks"][p][0] for p in cov} - entry = {p: res["masks"][p][1] | res["masks"][p][2] << 32 for p in cov} - wqm = {p: res["masks"][p][3] | res["self"][p][1] << 32 for p in cov} - helpers = {(p, k) for p in cov for k in (1, 2, 3) if neighbour(p, k) not in cov} - out = [("partial quads at the edge", bool(helpers), f"{len(cov)} covered pixels, {len(helpers)} (covered lane, " - "helper neighbour) pairs")] - waves = {} - for p in cov: - waves.setdefault(entry[p], []).append(p) - entry_ok, wqm_ok, packed, detail = True, True, True, [] - for e, pix in sorted(waves.items()): - lanes = [lane[p] for p in pix] - quads = {ln // 4 for ln in lanes} - w = {wqm[p] for p in pix} - bits = lambda m: {i for i in range(64) if m >> i & 1} # noqa: E731 - entry_ok &= len(set(lanes)) == len(lanes) and bits(e) == set(lanes) - wqm_ok &= len(w) == 1 and bits(w.pop() if len(w) == 1 else 0) == {4 * q + i for q in quads for i in range(4)} - packed &= quads == set(range(len(quads))) - detail.append(f"0x{e:016x}: {len(pix)} covered lanes in {len(quads)} quads") - out.append(("entry EXEC = the covered pixels (helpers off)", entry_ok, f"{len(waves)} waves: " + "; ".join(detail))) - out.append(("s_wqm turns on exactly the quads with a covered pixel", wqm_ok, "")) - out.append(("quads packed from lane 0; none without a covered pixel", packed, "")) - order = {(p[0] & 1) + 2 * (p[1] & 1) == lane[p] % 4 for p in cov} - out.append(("lane % 4 = (x & 1) + 2 (y & 1): 0 top-left, 1 top-right, 2 bottom-left, 3 bottom-right", - order == {True}, "")) - err_c = max(max(abs(f32(res["self"][p][2]) - ndc(p, size)[0]), abs(f32(res["self"][p][3]) - ndc(p, size)[1])) - for p in cov) - err_h = 0.0 - for p, k in helpers: - got = {1: res["nb12"][p][0:2], 2: res["nb12"][p][2:4], 3: res["nb3"][p][0:2]}[k] - ex = ndc(neighbour(p, k), size) - err_h = max(err_h, abs(f32(got[0]) - ex[0]), abs(f32(got[1]) - ex[1])) - out.append(("after s_wqm a helper interpolates its own pixel centre, as precisely as a covered pixel", - err_h <= 1.5 * err_c + 1e-6, f"helper |error| max {err_h:.2e}, covered {err_c:.2e}")) - nm = res["nowqm_masks"] - out.append(("without s_wqm EXEC stays the entry mask", all( - (nm[p][1] | nm[p][2] << 32) == entry[p] and nm[p][3] == entry[p] & 0xFFFFFFFF for p in cov), "")) - h1 = [p for p in cov if neighbour(p, 1) not in cov] - ij = {p: (f32(res["nowqm_ij"][p][0]), f32(res["nowqm_ij"][p][1])) for p in h1} - err_ij = max([max(abs(g[0] - bary(neighbour(p, 1), size, tri)[0]), abs(g[1] - bary(neighbour(p, 1), size, tri)[1])) - for p, g in ij.items()] or [0.0]) - out.append(("without s_wqm a helper's v0/v1 already hold its own pixel's I/J (outside: I + J > 1)", - bool(ij) and err_ij < 1e-4 and all(i + j > 1 for i, j in ij.values()), - f"{len(ij)} helpers, |error| max {err_ij:.2e}")) - out.append(("DPP without fi from an inactive lane leaves the destination unchanged", - bool(h1) and {res["nowqm_ij"][p][3] for p in h1} == {SENTINEL}, "")) - written = [p for p, w in res["helper_export"].items() if p not in cov and tuple(w) != CLEAR] - out.append(("an exp ... vm with helpers on in EXEC writes no pixel outside the triangle", not written, - f"{len(written)} written")) - return out - - -def coverage_map(res, size=SIZE): - cov = {p for p, w in res["masks"].items() if tuple(w) != CLEAR} - return ["".join("#" if (x, y) in cov else "." for x in range(size[0])) for y in range(size[1])] - - -def measure(build): - """(device, {program: {(x, y): words}}) on the selected GPU.""" - with tempfile.TemporaryDirectory(prefix="ps_helper_probe_") as d: - vs, ps = os.path.join(d, "vs_edge.spvasm"), os.path.join(d, "ps_deriv.spvasm") - for path, text in ((vs, VS_EDGE), (ps, PS_DERIV)): - with open(path, "w", encoding="utf-8", newline="\n") as fh: - fh.write(text) - return _run(ps_oracle.Oracle(build, vs=vs, ps=ps, size=SIZE, work=os.path.join(d, "work"))) - - -def _run(o): - try: - if not o.wave64: - raise ps_oracle.Unavailable("the pixel stage is wave32; these programs are wave64") - res = {} - for name in PROGRAMS: - px = o.run(program(name)) - res[name] = {(i % SIZE[0], i // SIZE[0]): tuple(w) for i, w in enumerate(px)} - return o.device, res - finally: - o.close() - - -def main(argv=None): - ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) - ap.add_argument("--build", required=True, help="runtime build folder with vk_harness") - ap.add_argument("--json", help="write {device, checks, words} here") - a = ap.parse_args(argv) - try: - device, res = measure(a.build) - except ps_oracle.Unavailable as e: - print(f"ps_helper_probe unavailable: {e}") - return 77 - except (OSError, ValueError, RuntimeError) as e: - print(f"ps_helper_probe: {e}") - return 2 - print(f"device: {device}") - print("coverage (# covered):") - for row in coverage_map(res): - print(" " + row) - checks = analyze(res) - for name, ok, detail in checks: - print(f"{'ok ' if ok else 'FAIL'} {name}" + (f" ({detail})" if detail else "")) - good = sum(ok for _n, ok, _d in checks) - print(f"{good}/{len(checks)} checks hold") - if a.json: - with open(a.json, "w", encoding="utf-8", newline="\n") as fh: - json.dump({"device": device, "checks": [[n, ok, d] for n, ok, d in checks], - "words": {n: {f"{x},{y}": list(w) for (x, y), w in px.items()} for n, px in res.items()}}, - fh, indent=1) - return 0 if good == len(checks) else 1 - - -if __name__ == "__main__": - try: # a redirected stdout is strict ANSI code page under -I; write '?' for what it cannot encode - sys.stdout.reconfigure(errors="replace") - except (AttributeError, ValueError, OSError): - pass - sys.exit(main()) diff --git a/tools/ps_interp_modes.py b/tools/ps_interp_modes.py deleted file mode 100644 index 01fded995..000000000 --- a/tools/ps_interp_modes.py +++ /dev/null @@ -1,482 +0,0 @@ -"""Decode pixel-shader interpolation modes from a DXBC container and its FSSM sidecar. - -The translator declares every pixel-shader interpolant as a perspective-centre input -(tools/rdna2spirv.py Gen.attribute; the PS system-input layout comment says the pair is -"the perspective-center one, the only pair this layout models"). Which inputs are -actually centre/centroid/sample and perspective/linear is not in the FSSM header word set: -a scan of every u16 in the first 0x138 bytes of all 12,101 corpus pixel shaders against the -SPI_PS_INPUT_ENA value reconstructed from the DXBC signature finds no matching word (the -only equalities are constants that coincide for the persp-centre-only cohort). The mode -lives in the DXBC container that is carved next to the FSSM: - -PSV0 chunk (writer: dxc lib/DxilContainer/DxilPipelineStateValidation.{h,cpp}, -DxilPSVWriter in lib/DxilContainer/DxilContainerAssembler.cpp): - - u32 runtime-info size, runtime info bytes, - u32 resource count, [u32 bind-info size, bind records], - u32 string-table size, strings, - u32 semantic-index entries, u32 per entry, - u32 signature-element size (16 on the corpus), then input elements, output elements, - each element 16 bytes: - u32 semantic-name offset (0 = system value, no string) - u32 semantic-index offset - u8 rows - u8 start row (register) - u8 cols [3:0], start col [5:4], allocated [6] - u8 semantic kind (DXIL::SemanticKind: 0 Arbitrary, 3 Position, 6 ClipDistance, - 7 CullDistance, 12 SampleIndex, 13 IsFrontFace, 14 Coverage) - u8 component type (DxilProgramSigCompType: 1 UInt32, 3 Float32, 6 Float16) - u8 interpolation mode (DXIL::InterpolationMode, "must match D3D_INTERPOLATION_MODE": - 1 Constant, 2 Linear, 3 LinearCentroid, 4 LinearNoperspective, - 5 LinearNoperspectiveCentroid, 6 LinearSample, - 7 LinearNoperspectiveSample) - u8 dynamic mask [3:0] | output stream [5:4] - u8 reserved - -The mode maps onto the barycentric pair the hardware must enable, named by the -SPI_PS_INPUT_ENA/SPI_PS_INPUT_ADDR fields shared by both registers -(Mesa src/amd/registers/gfx103.json, mm 165580/0x286CC and 165584/0x286D0): - - mode 2 Linear -> PERSP_CENTER_ENA (bit 1) - mode 3 LinearCentroid -> PERSP_CENTROID_ENA (bit 2) - mode 6 LinearSample -> PERSP_SAMPLE_ENA (bit 0) - mode 4 LinearNoperspective -> LINEAR_CENTER_ENA (bit 5) - mode 5 LinearNoperspectiveCentroid-> LINEAR_CENTROID_ENA(bit 6) - mode 7 LinearNoperspectiveSample -> LINEAR_SAMPLE_ENA (bit 4) - mode 1 Constant -> none (flat: P0 coefficient) - -D3D forces noperspective on SV_Position, so Position rows carry mode 4 (a few 5) everywhere; -an SV_Position delivered through the parameter cache is interpolated with the *linear* pair, -while one read as a system input arrives in the POS_X/Y/Z/W_FLOAT VGPRs after the barycentric -pair. The FSSM input table itself (tools/fssm_header.py, 8-byte records from 0x138) carries -the read method, not the mode - corpus-wide the record flags agree with the disassembly as -bit 0 (0x01) read through v_interp_mov_f32, bit 1 (0x02) read through 32-bit v_interp_p1/p2, -bit 3 (0x08) 16-bit parameter (Float16 component type), bit 4 (0x10, FLAG_FP16) read through -the *_f16 interpolation opcodes. - -Usage: - python -I ps_interp_modes.py [--json] [--limit N] - -For a directory, one row per pixel shader (stage from index.json) with the PSV0 input -modes, the FSSM table read-method decode and the v_interp usage from a sibling disasm/ -directory, then a census tally. Output is counts and bit layouts only; no game data. -""" - -import argparse -import json -import os -import re -import struct -import sys -from collections import Counter - -sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) -import fssm_header # noqa: E402 - -# DXIL::SemanticKind values that reach the shader as system inputs, not parameter-cache -# interpolation (names from dxc include/dxc/DXIL/DxilConstants.h). -SYSTEM_KINDS = {1: "vertex-id", 2: "instance-id", 12: "sample-index", 13: "front-face", - 14: "coverage", 15: "inner-coverage", 25: "barycentrics", 26: "shading-rate"} - -# (kind class, mode) -> (class name, SPI_PS_INPUT_ENA bit). Mode numbers are -# DXIL::InterpolationMode ("must match D3D_INTERPOLATION_MODE"); bit numbers and names are -# Mesa gfx103.json register type SPI_PS_INPUT_ENA. -MODE_CLASS = { - 1: ("flat", 0), - 2: ("persp_center", 1 << 1), - 3: ("persp_centroid", 1 << 2), - 6: ("persp_sample", 1 << 0), - 4: ("linear_center", 1 << 5), - 5: ("linear_centroid", 1 << 6), - 7: ("linear_sample", 1 << 4), -} - -COMPONENT_TYPES = {1: "uint", 2: "sint", 3: "float", 4: "uint16", 5: "sint16", 6: "float16"} - -VINTERP = re.compile(r"v_interp_(p1_f32|p2_f32|mov_f32|p1ll_f16|p1lv_f16|p2_f16)\S*\s+\S+,\s*(\S+)," - r"\s*attr(\d+)\.([xyzw])") - - -def chunk_table(data): - """fourcc -> (offset, size) for a DXBC container, or {} when the header does not parse.""" - if len(data) < 32 or data[:4] != b"DXBC": - return {} - count = struct.unpack_from(" len(data): - return {} - out = {} - for i in range(count): - off = struct.unpack_from(" len(data): - continue - out[data[off:off + 4]] = (off, struct.unpack_from(" len(data): - raise ValueError("PSV0 past end of container") - p = data[off + 8:off + 8 + size] - if len(p) < 4: - raise ValueError("truncated before runtime-info size") - rt_size = struct.unpack_from(" len(p): - raise ValueError("truncated before resource count") - resources = struct.unpack_from(" len(p): - raise ValueError("truncated before bind-info size") - bind = struct.unpack_from(" len(p): - raise ValueError("truncated before string table") - strings = struct.unpack_from(" len(p): - raise ValueError("truncated before semantic-index table") - semantic = struct.unpack_from(" len(p): - raise ValueError("truncated before element size") - esz = struct.unpack_from(" len(p): - raise ValueError("runtime info too short for element counts") - count = p[r1 + 4] - if pos + esz * count > len(p): - raise ValueError("element array past chunk end") - out = [] - for i in range(count): - b = p[pos + i * esz:pos + (i + 1) * esz] - noff = struct.unpack_from(" noff: - name = heap[noff:end].decode("latin-1") - out.append({ - "rows": b[8], - "row": b[9], - "cols": b[10] & 0xF, - "start_col": (b[10] >> 4) & 0x3, - "kind": b[11], - "ctype": b[12], - "mode": b[13], - "name": name, - }) - return out - - -def isg1_elements(data): - """ISG1 elements as dicts (register, mask, rw, name); the repo's 32-byte layout.""" - chunks = chunk_table(data) - if b"ISG1" not in chunks: - return [] - off, size = chunks[b"ISG1"] - if off + 8 + size > len(data): - return [] - p = data[off + 8:off + 8 + size] - if len(p) < 8: - return [] - count, first = struct.unpack_from(" len(p): - break - _, noff, sem_idx, sysv, ctype, reg = struct.unpack_from("<6I", p, base) - name = "" - if 8 <= noff < len(p): - end = p.find(b"\0", noff) - if end > noff: - name = p[noff:end].decode("latin-1") - out.append({"register": reg, "semantic_index": sem_idx, "system_value": sysv, - "component_type": ctype, "mask": p[base + 24], "rw": p[base + 25], - "name": name}) - return out - - -def interp_class(kind, mode): - """(class, SPI_PS_INPUT_ENA bit) of one input row, or ("system", 0) for system inputs.""" - if kind in SYSTEM_KINDS: - return "system", 0 - if mode not in MODE_CLASS: - return "other", 0 - return MODE_CLASS[mode] - - -def read_method(flags): - """FSSM record flags -> the read method the corpus disassembly agrees with.""" - return { - "mov": bool(flags & 0x01), - "p1p2": bool(flags & 0x02), - "param16": bool(flags & 0x08), - "f16_ops": bool(flags & 0x10), - } - - -def disasm_facts(text): - """attr -> set of read kinds, plus the I/J operand set of the non-mov interpolations.""" - per = {} - ij = set() - for line in text.splitlines(): - m = VINTERP.search(line.split(";")[0]) - if not m: - continue - op, src, attr = m.group(1), m.group(2), int(m.group(3)) - kind = "mov" if op == "mov_f32" else ("f16" if op.endswith("_f16") else "p1p2") - per.setdefault(attr, set()).add(kind) - if kind != "mov": - ij.add(src) - return per, ij - - -def pair_class(rows, table, usage, ij): - """The one barycentric pair the code reads, as a class name. - - Every corpus pixel shader that interpolates reads the same single pair (v0/v1, plus one - shader that moves it to v14), so a shader's pair has one class even though - SPI_PS_INPUT_ENA itself is not stored anywhere in the FSSM: - - persp_center - a read arbitrary/clip/cull row with a perspective mode: the pair is - PERSP_CENTER (centroid/sample would need their own pair, and no shader - reads a second pair) - linear_* - SV_Position rows are the only read inputs: the position is interpolated - through the parameter cache with the linear pair (D3D forces - noperspective on SV_Position; mode 5 asks for the centroid variant). - A shader that reads any other row interpolates that row instead and - takes SV_Position from the system VGPRs after the pair. - flat_only - interpolation reads only Constant rows (P0 semantics): any enabled pair - gives the same value - none - no v_interp at all (system inputs only) - """ - read = [r for r in rows if r["rw"]] - persp = [r for r in read if r["kind"] in (0, 6, 7) - and interp_class(r["kind"], r["mode"])[0] in ("persp_center", "persp_centroid", - "persp_sample")] - positions = [r for r in read if r["kind"] == 3] - others = [r for r in read if r["kind"] != 3] - interpolates = any(k - {"mov"} for k in usage.values()) - if interpolates and persp: - return "persp_center" - if interpolates and positions and not others: - # the position rows are the only read inputs, so the interpolation reads them - # through the parameter cache with the linear pair (D3D forces noperspective on - # SV_Position; mode 5 asks for the centroid variant). A shader that also reads - # other rows interpolates those and takes SV_Position from the system VGPRs. - mode = max(r["mode"] for r in positions) - return "linear_centroid" if mode == 5 else "linear_center" - if interpolates: - return "flat_only" - if ij: - return "raw_bary" - return "none" - - -def shader_row(dxbc_path, fssm_path, disasm_path): - """Decode one pixel shader; returns None when the PSV0 chunk is absent/unparsable.""" - with open(dxbc_path, "rb") as f: - data = f.read() - try: - rows = psv0_inputs(data) - except ValueError: - return None - isg = isg1_elements(data) - for r in rows: - rmask = (((1 << r["cols"]) - 1) << r["start_col"]) & 0xF - span = range(r["row"], r["row"] + max(r.get("rows", 1), 1)) - reg_matches = [e for e in isg if e["register"] in span] - col_matches = [e for e in reg_matches if not rmask or not e["mask"] or (e["mask"] & rmask)] - matches = col_matches or reg_matches - rw_val = 0 - for e in matches: - rw_val |= (e["rw"] & rmask) if (rmask and e["mask"]) else e["rw"] - r["rw"] = rw_val - if not r["name"]: - for e in matches: - if e["name"]: - r["name"] = e["name"] - break - r["class"], r["ena_bit"] = interp_class(r["kind"], r["mode"]) - table = [] - if fssm_path and os.path.isfile(fssm_path): - with open(fssm_path, "rb") as f: - table = fssm_header.pixel_inputs(f.read()) - usage, ij = {}, set() - if disasm_path and os.path.isfile(disasm_path): - with open(disasm_path, encoding="utf-8", errors="replace") as f: - usage, ij = disasm_facts(f.read()) - pair = pair_class(rows, table, usage, ij) - ena = 0 - for r in rows: - ena |= r["ena_bit"] - return { - "name": os.path.splitext(os.path.basename(dxbc_path))[0], - "inputs": [{k: r[k] for k in ("row", "cols", "kind", "ctype", "mode", "rw", "class", - "name")} for r in rows], - "table": [{**read_method(t["flags"]), "mask": t["mask"], "flags": t["flags"]} - for t in table], - "usage": {str(a): sorted(k) for a, k in sorted(usage.items())}, - "ij": sorted(ij), - "pair_class": pair, - "ena_bits": ena, - } - - -def tally(rows): - """Census over per-shader rows: counts only.""" - inputs = [i for r in rows for i in r["inputs"]] - live = [i for i in inputs if i["rw"]] - modes = Counter((i["kind"], i["mode"]) for i in inputs) - live_modes = Counter((i["kind"], i["mode"]) for i in live) - non_pc = [i for i in live if i["class"] in ("persp_centroid", "persp_sample", - "linear_center", "linear_centroid", - "linear_sample")] - method = Counter() - for r in rows: - for t in r["table"]: - method[(t["mov"], t["p1p2"], t["param16"], t["f16_ops"])] += 1 - flag_use = Counter() - for r in rows: - for pos, kinds in r["usage"].items(): - t = r["table"][int(pos)] if int(pos) < len(r["table"]) else None - if t: - flag_use[(t["mov"], t["p1p2"], t["f16_ops"], tuple(kinds))] += 1 - flag_vs_usage = {} - for (mov, p1p2, f16ops, kinds), n in sorted(flag_use.items()): - key = (f"mov={int(mov)} p1p2={int(p1p2)} f16={int(f16ops)}" - f" -> {'+'.join(kinds) or 'unread'}") - flag_vs_usage[key] = flag_vs_usage.get(key, 0) + n - return { - "shaders": len(rows), - "inputs": len(inputs), - "live_inputs": len(live), - "mode_by_kind": {f"kind{k} mode{m}": n for (k, m), n in sorted(modes.items())}, - "live_mode_by_kind": {f"kind{k} mode{m}": n for (k, m), n in sorted(live_modes.items())}, - "live_non_persp_center_inputs": len(non_pc), - "shaders_with_non_persp_center": sum(1 for r in rows - if any(i["class"] in ("persp_centroid", "persp_sample", - "linear_center", "linear_centroid", - "linear_sample") and i["rw"] - for i in r["inputs"])), - "pair_class": dict(Counter(r["pair_class"] for r in rows)), - "ij_sets": {",".join(ij) or "(none)": n - for ij, n in Counter(tuple(r["ij"]) for r in rows).items()}, - "table_records": sum(len(r["table"]) for r in rows), - "table_flags": {f"mov={a} p1p2={b} p16={c} f16={d}": n - for (a, b, c, d), n in sorted(method.items())}, - "flag_vs_usage": flag_vs_usage, - } - - -def files_of(path): - if os.path.isfile(path): - return [path] - out = [] - for n in sorted(os.listdir(path)): - if not n.endswith(".dxbc"): - continue - candidate = os.path.join(path, n) - if os.path.isfile(candidate): - out.append(candidate) - return out - - -def _at_least_one(value): - """An integer option that must be at least 1: 0 and negatives used to export one shader.""" - try: - n = int(value) - except ValueError: - raise argparse.ArgumentTypeError(f"expected an integer, got {value!r}") from None - if n < 1: - raise argparse.ArgumentTypeError(f"must be at least 1 (got {n})") - return n - - -def main(argv=None): - ap = argparse.ArgumentParser(description="Decode PS interpolation modes (PSV0 + FSSM + disasm).") - ap.add_argument("path", help="a .dxbc file or a directory of them") - ap.add_argument("--json", action="store_true", help="print one JSON document") - ap.add_argument("--limit", type=_at_least_one, default=None, help="stop after this many pixel shaders") - args = ap.parse_args(argv) - - if not os.path.exists(args.path): - print(f"ERROR: {args.path} does not exist", file=sys.stderr) - return 2 - base = args.path if os.path.isdir(args.path) else os.path.dirname(args.path) - stages = fssm_header.stage_index(base) - try: - paths = files_of(args.path) - except OSError as e: - print(f"ERROR: cannot list {args.path}: {e.strerror or e}", file=sys.stderr) - return 2 - rows = [] - skipped = Counter() - for path in paths: - stem = os.path.splitext(os.path.basename(path))[0] - if stages and stages.get(stem) != "ps": - continue - fssm = os.path.join(base, "fssm", stem + ".fssm") - disasm = os.path.join(base, "disasm", stem + ".s") - try: - row = shader_row(path, fssm, disasm) - except OSError as e: - print(f"ERROR: cannot read {e.filename or path}: {e.strerror or e}", file=sys.stderr) - return 2 - if row is None: - skipped["no psv0"] += 1 - continue - row["stage"] = stages.get(stem) - rows.append(row) - if args.limit is not None and len(rows) >= args.limit: - break - - if args.json: - json.dump({"files": rows, "tally": tally(rows), "skipped": dict(skipped)}, - sys.stdout, indent=1) - sys.stdout.write("\n") - return 0 - for r in rows: - ins = ", ".join(f"{i['name'] or 'kind' + str(i['kind'])}@{i['row']}" - f":{COMPONENT_TYPES.get(i['ctype'], i['ctype'])}" - f"/mode{i['mode']}{'/rw' if i['rw'] else ''}" for i in r["inputs"]) - print(f"{r['name']}: pair={r['pair_class']} ij={','.join(r['ij']) or '-'}") - if ins: - print(f" inputs: {ins}") - t = tally(rows) - print(f"{t['shaders']} shaders, {t['inputs']} inputs ({t['live_inputs']} read), " - f"{t['table_records']} FSSM records") - print("pair classes:", ", ".join(f"{k}:{v}" for k, v in sorted(t["pair_class"].items()))) - print("I/J operand sets:", ", ".join(f"{k}:{v}" for k, v in sorted(t["ij_sets"].items()))) - print("modes (kind, mode):", ", ".join(f"{k}:{v}" for k, v in sorted(t["mode_by_kind"].items()))) - print("live modes:", ", ".join(f"{k}:{v}" for k, v in sorted(t["live_mode_by_kind"].items()))) - print(f"live non-perspective-centre inputs: {t['live_non_persp_center_inputs']} " - f"in {t['shaders_with_non_persp_center']} shaders") - if skipped: - print("skipped:", ", ".join(f"{k}:{v}" for k, v in skipped.items())) - return 0 - - -if __name__ == "__main__": - try: # a redirected stdout is strict ANSI code page under -I; write '?' for what it cannot encode - sys.stdout.reconfigure(errors="replace") - except (AttributeError, ValueError, OSError): - pass - sys.exit(main()) diff --git a/tools/ps_oracle.py b/tools/ps_oracle.py deleted file mode 100644 index 61d5777d0..000000000 --- a/tools/ps_oracle.py +++ /dev/null @@ -1,858 +0,0 @@ -r"""Run hand-written RDNA2 pixel-shader ISA on an AMD GPU: a hardware oracle for what only a pixel shader can do. - -tools/hw_oracle launches compute kernels; v_interp_*, the parameter data the SPI writes into LDS, exports and helper -lanes need a real draw. This tool gets one through Vulkan's VK_KHR_pipeline_binary (the AMD Windows driver exposes -it, with uncompressed data): - - 1. vk_harness builds a pipeline from a template vertex + pixel shader (SPIR-V) and writes its binary - (VKH_BINARY_OUT). On AMD that binary is one PAL ELF: `.text` holds `_amdgpu_gs_main` (the vertex stage) and - `_amdgpu_ps_main`, the `.note` holds the PAL metadata (msgpack): register counts and the SPI setup - (SPI_PS_INPUT_ENA/ADDR, the parameter layout, the export format), which the driver programs from the metadata. - 2. The ISA under test is assembled with AMD clang (gfx1036 or the --mcpu given) and replaces `_amdgpu_ps_main`; - `.text` grows when it is longer, and the pixel stage's VGPR/SGPR counts in the metadata are raised to cover the - registers it names. - 3. vk_harness builds the pipeline from the patched binary (VKH_BINARY_IN), draws one full-screen triangle into an - RGBA32F target and reads it back, so every pixel's mrt0 export comes back as four raw dwords. - -The template decides what the hardware sets up before the code runs: which barycentrics are in VGPRs, which user -SGPRs hold what (the PS sets M0 from one of them for v_interp), how many parameters the SPI writes into LDS and in -what format, and the export format of mrt0 (32_ABGR for the harness' RGBA32F target). --show-template prints the -template's own ISA and that part of its metadata, so the code under test can follow the same conventions. -Templates: `const` (no inputs), `interp2` (two smooth vec4 varyings: location 0 = (u, v, 0, 1) and location 1 = -(u, v, 0, 0) with u, v = 0..2 across the screen, as scripts/run_gpu_tests.py's vs_tri), or --vs/--ps files -(.spv, or .spvasm assembled with spirv-as). --format picks another color target (the driver then picks the export -format for it, as for a game pipeline); the readback is that target's texels as stored. The selected format, -including the default RGBA32F, takes precedence over a VKH_COLOR_FORMAT inherited from the shell. - -Checked on an AMD Radeon iGPU (gfx1036, Windows driver 26.10.1): the driver accepts a patched binary and the patched -code runs as the pixel shader (no checksum over the code). The pixel stage there is compiled as wave64. - -On Linux, RADV (Mesa) returns one binary per stage instead (radv_shader_serialize's layout, see the RADV section -below); the pixel stage's code, sizes and register counts are found by their values and patched there. RADV takes -GFX10 (RDNA1/RDNA2) devices only (GFX11+ is refused: no v_interp), --set is PAL-only, and Mesa may merge a template's -varyings (interp2 becomes one parameter, attr0 = (2u, 2v, 0, 1)). Checked on gfx1036 with Mesa 26.3.1. - -Usage: - python -I tools/ps_oracle.py --build --template interp2 --show-template - python -I tools/ps_oracle.py --build --template interp2 --asm body.s [--size 8 8] [--json out.json] - -Select the AMD GPU with LEONIDA_VK_DEVICE (e.g. radeon). Standard library only; needs vk_harness from the runtime -build, AMD clang (LEONIDA_AMD_CLANG, as tools/hw_oracle), llvm-objdump (llvm-mc on RADV) next to it for ---show-template, and spirv-as on PATH for the templates. Exit codes: 0 ran, 1 the GPU run failed, 2 usage or a -bad input, 77 the device or a tool is missing (no VK_KHR_pipeline_binary, neither a PAL nor a RADV binary, a RADV -GPU other than GFX10, no clang). -""" -import argparse -import collections -import json -import os -import re -import shutil -import struct -import subprocess -import sys -import tempfile - -HERE = os.path.dirname(os.path.abspath(__file__)) -sys.path.insert(0, HERE) -from report_paths import same_report_path # noqa: E402 - -PS_SYMBOL = "_amdgpu_ps_main" -S_CODE_END = struct.pack("= 0xE0: - return t - 0x100, i + 1 - if 0x80 <= t <= 0x8F or t in (0xDE, 0xDF): - n, i = (t & 0x0F, i + 1) if t <= 0x8F else (struct.unpack_from(">H" if t == 0xDE else ">I", b, i + 1)[0], - i + (3 if t == 0xDE else 5)) - d = {} - for _ in range(n): - k, i = mp_load(b, i) - v, i = mp_load(b, i) - d[k] = v - return d, i - if 0x90 <= t <= 0x9F or t in (0xDC, 0xDD): - n, i = (t & 0x0F, i + 1) if t <= 0x9F else (struct.unpack_from(">H" if t == 0xDC else ">I", b, i + 1)[0], - i + (3 if t == 0xDC else 5)) - out = [] - for _ in range(n): - v, i = mp_load(b, i) - out.append(v) - return out, i - if 0xA0 <= t <= 0xBF or t in (0xD9, 0xDA, 0xDB): - if t <= 0xBF: - n, i = t & 0x1F, i + 1 - else: - w = {0xD9: 1, 0xDA: 2, 0xDB: 4}[t] - n, i = int.from_bytes(b[i + 1:i + 1 + w], "big"), i + 1 + w - return b[i:i + n].decode("utf-8"), i + n - if t in (0xC4, 0xC5, 0xC6): - w = {0xC4: 1, 0xC5: 2, 0xC6: 4}[t] - n = int.from_bytes(b[i + 1:i + 1 + w], "big") - return bytes(b[i + 1 + w:i + 1 + w + n]), i + 1 + w + n - if t == 0xC0: - return None, i + 1 - if t in (0xC2, 0xC3): - return t == 0xC3, i + 1 - if t == 0xCA: - return F32(struct.unpack_from(">f", b, i + 1)[0]), i + 5 - if t == 0xCB: - return struct.unpack_from(">d", b, i + 1)[0], i + 9 - ints = {0xCC: ">B", 0xCD: ">H", 0xCE: ">I", 0xCF: ">Q", 0xD0: ">b", 0xD1: ">h", 0xD2: ">i", 0xD3: ">q"} - if t in ints: - return struct.unpack_from(ints[t], b, i + 1)[0], i + 1 + struct.calcsize(ints[t]) - raise ValueError(f"msgpack type 0x{t:02x} at {i} is not supported") - - -def _mp_len(n, small, small_max, wide): - if n <= small_max: - return bytes([small | n]) - for code, fmt, top in wide: - if n < top: - return bytes([code]) + struct.pack(fmt, n) - raise ValueError("too long") - - -def mp_dump(v): - if v is None: - return b"\xc0" - if v is True or v is False: - return b"\xc3" if v else b"\xc2" - if isinstance(v, int): - if 0 <= v <= 0x7F: - return bytes([v]) - if -32 <= v < 0: - return bytes([v + 0x100]) - for code, fmt, lo, hi in ((0xCC, ">B", 0, 1 << 8), (0xCD, ">H", 0, 1 << 16), (0xCE, ">I", 0, 1 << 32), - (0xCF, ">Q", 0, 1 << 64), (0xD0, ">b", -(1 << 7), 0), (0xD1, ">h", -(1 << 15), 0), - (0xD2, ">i", -(1 << 31), 0), (0xD3, ">q", -(1 << 63), 0)): - if lo <= v < hi: - return bytes([code]) + struct.pack(fmt, v) - raise ValueError(f"integer {v} out of range") - if isinstance(v, F32): - return b"\xca" + struct.pack(">f", v) - if isinstance(v, float): - return b"\xcb" + struct.pack(">d", v) - if isinstance(v, str): - s = v.encode("utf-8") - if len(s) <= 31: - return bytes([0xA0 | len(s)]) + s - return _mp_len(len(s), 0, -1, ((0xD9, ">B", 1 << 8), (0xDA, ">H", 1 << 16), (0xDB, ">I", 1 << 32))) + s - if isinstance(v, (bytes, bytearray)): - return _mp_len(len(v), 0, -1, ((0xC4, ">B", 1 << 8), (0xC5, ">H", 1 << 16), (0xC6, ">I", 1 << 32))) + bytes(v) - if isinstance(v, list): - return _mp_len(len(v), 0x90, 15, ((0xDC, ">H", 1 << 16), (0xDD, ">I", 1 << 32))) + b"".join(map(mp_dump, v)) - if isinstance(v, dict): - head = _mp_len(len(v), 0x80, 15, ((0xDE, ">H", 1 << 16), (0xDF, ">I", 1 << 32))) - return head + b"".join(mp_dump(k) + mp_dump(x) for k, x in v.items()) - raise TypeError(f"cannot write {type(v).__name__} as msgpack") - - -# ---- the PAL ELF of a pipeline binary ---- - -_SH = " [(key size, 32 key bytes, data)].""" - with open(path, "rb") as f: - d = f.read() - n, at, out = struct.unpack_from(" / v[a:b] and s / s[a:b].""" - top = {"v": 0, "s": 0} - for line in lines: - for kind, single, last in _REG.findall(line.split(";", 1)[0]): - top[kind] = max(top[kind], int(last or single) + 1) - return top["v"], top["s"] - - -def set_meta(pipe, path, value): - """Set one value in the pipeline's metadata map: path is '/'-separated keys from amdpal.pipelines[0] (list - indices as numbers), e.g. ".graphics_registers/.spi_ps_input_cntl/0/.fp16_interp_mode".""" - keys = [int(k) if k.isdigit() else k for k in path.split("/") if k] - node = pipe - for k in keys[:-1]: - node = node[k] - if keys[-1] not in node if isinstance(node, dict) else not 0 <= keys[-1] < len(node): - raise ValueError(f"no metadata entry {path!r}") - old = node[keys[-1]] - if isinstance(old, F32): - value = F32(value) - node[keys[-1]] = value - - -def patch_ps(elf_bytes, code, lines=(), sets=()): - """The ELF with `_amdgpu_ps_main` replaced by `code` (raw instruction bytes), padded with s_code_end, the pixel - stage's VGPR/SGPR counts raised to cover the registers `lines` name, and each (path, value) of `sets` written - into the metadata (set_meta). `_amdgpu_ps_main` must be the last function of .text (it is in the AMD driver's - binaries).""" - elf = Elf(elf_bytes) - syms = {s[0]: s for s in elf.symbols()} - if PS_SYMBOL not in syms: - raise Unavailable(f"no {PS_SYMBOL} in the pipeline binary") - _, start, _, entry = syms[PS_SYMBOL] - if any(v > start for n, v, _s, _e in syms.values() if n and n != PS_SYMBOL): - raise ValueError(f"{PS_SYMBOL} is not the last function of .text") - ti = elf.index(".text") - code = bytes(code) + S_CODE_END * ((-len(code) % 64) // 4 + 64) # the hardware prefetches past the end - elf.data[ti] = bytearray(elf.data[ti][:start]) + bytearray(code) - elf.set_symbol_size(entry, len(code) - 64 * 4) - v, s = regs_used(lines) - meta = elf.metadata() - stage = ps_stage(meta) - changed = bool(sets) - for path, value in sets: - set_meta(meta["amdpal.pipelines"][0], path, value) - if v > stage.get(".vgpr_count", 0) or s > stage.get(".sgpr_count", 0): - stage[".vgpr_count"] = max(stage.get(".vgpr_count", 0), v) - stage[".sgpr_count"] = max(stage.get(".sgpr_count", 0), s) - changed = True - if changed: - elf.set_metadata(meta) - return elf.to_bytes() - - -def ps_code(elf_bytes): - """(start, bytes) of `_amdgpu_ps_main` in .text (to the end of .text, s_code_end padding included).""" - elf = Elf(elf_bytes) - syms = {s[0]: s for s in elf.symbols()} - start = syms[PS_SYMBOL][1] - return start, bytes(elf.data[elf.index(".text")][start:]) - - -def is_wave64(elf_bytes): - """The pixel stage's wave size from its first instruction, s_version (UC_VERSION_W64_BIT).""" - _, code = ps_code(elf_bytes) - word = struct.unpack_from("> 23 != 0x161: # SOPK opcode 1 (s_version) in GFX10: 0xB080xxxx - return None - return bool(word & W64_BIT) - - -# ---- RADV (Mesa) stage binaries ---- -# RADV hands back one binary per stage, as radv_shader_serialize writes it (Mesa 26.3, radv_pipeline_cache.c; the -# structs in radv_shader.h): uint32 type (0 = legacy), struct ac_shader_config (ac_binary.h: num_sgprs, num_vgprs -# first, rsrc1 later), struct radv_shader_info (its size changes between Mesa versions; wave_size, a byte, stage, -# next_stage sit together in it), uint32 total_size (padded to 8), then code_size, exec_size, ir_size, disasm_size, -# stats_size, debug_info_size, then the data: stats, code, ir, disasm, debug info. Debug strings may follow -# total_size. RADV builds an imported binary with radv_shader_create_uncached (no cache lookup) and programs -# SPI_SHADER_PGM_RSRC1_PS from config.rsrc1, whose VGPRS field is (num_vgprs - 1) / (wave32 ? 8 : 4) -# (radv_postprocess_binary_config). Only the two leading config fields are read at a fixed place; the rest is found -# from values that must agree with each other, so a Mesa with another layout is refused instead of misread. - -RadvLayout = collections.namedtuple("RadvLayout", "code code_size exec_size sizes_at total_at vgprs sgprs rsrc1_at " - "wave is_ps") -MESA_FRAGMENT, MESA_NONE = 4, 0xFF -# Mesa's chip names (amd_family.c) of GFX10 with their LLVM targets (ac_get_llvm_processor_name) -RADV_GFX10 = {"NAVI10": "gfx1010", "NAVI12": "gfx1011", "NAVI14": "gfx1012", "GFX1013": "gfx1013", - "NAVI21": "gfx1030", "NAVI22": "gfx1031", "NAVI23": "gfx1032", "VANGOGH": "gfx1033", - "NAVI24": "gfx1034", "REMBRANDT": "gfx1035", "RAPHAEL_MENDOCINO": "gfx1036"} - - -def radv_layout(data): - """Where the code, its sizes and the register counts are in one RADV stage binary (RadvLayout), or Unavailable.""" - u32 = lambda at: struct.unpack_from("> 12 & 0xFF - and any(u32(j) == u32(k) >> 12 & 0xFF for j in range(12, k, 4))] - if len(rsrc1) != 1: - raise Unavailable("the RADV binary's rsrc1 was not found (an unknown Mesa layout)") - return RadvLayout(code_at, code_size, exec_size, sizes_at, total_at, vgprs, sgprs, rsrc1[0], wave, True) - - -def radv_ps_index(bins): - """Which of RADV's stage binaries is the pixel stage.""" - ps = [i for i, (_ks, _key, data) in enumerate(bins) if radv_layout(data).is_ps] - if len(ps) != 1: - raise Unavailable(f"{len(ps)} of the {len(bins)} RADV binaries are a pixel stage (expected one)") - return ps[0] - - -def radv_arch(device): - """The LLVM target of a RADV device name ('... (RADV RAPHAEL_MENDOCINO)'), Unavailable when it is not GFX10.""" - m = re.search(r"\(RADV ([A-Z0-9_]+)\)", device or "") - if not m: - raise Unavailable(f"the pipeline came back as several binaries and the device ({device or '?'}) is not RADV") - if m.group(1) not in RADV_GFX10: - raise Unavailable(f"unsupported architecture: {m.group(1)} ({device}); on RADV this tool runs GFX10 " - "(RDNA1/RDNA2) pixel shaders only (GFX11+ interpolates with lds_param_load, not v_interp)") - return RADV_GFX10[m.group(1)] - - -def patch_radv_ps(data, code, lines=()): - """The RADV pixel-stage binary with its code replaced by `code` (raw instruction bytes, padded with s_code_end), - the sizes fixed and num_vgprs/num_sgprs and rsrc1's VGPRS raised to cover the registers `lines` name.""" - lay = radv_layout(data) - if not lay.is_ps: - raise ValueError("not the pixel-stage binary") - padded = bytes(code) + S_CODE_END * ((-len(code) % 64) // 4 + 64) # the hardware prefetches past the end - out = bytearray(data[:lay.code]) + padded + data[lay.code + lay.code_size:] - put = lambda at, v: struct.pack_into(" --out [--n 480] [--seed 20261122] - python -I tools/ps_sweep.py run --spirv --out --tag a --exe --glslang - VK_LOADER_DRIVERS_DISABLE=*nv* python -I tools/ps_sweep.py run ... --tag b # another GPU (any loader filter) - python -I tools/ps_sweep.py compare --out --tags a b - -For native and fallback translations drawn from the same sample, compare exact RGBA32F target bytes: - - python -I tools/ps_sweep.py compare --exact --out --tags native fallback --variant z - -The report (exact_.json) gives one row per sampled draw, with target classes in attachment order for -compatible pairs. An exact draw is observable if any component differs from the worker's -1 clear value. -Pass --occlusion to run on a device supporting precise occlusion queries. Both compare modes then include -samples_passed in tag order for each draw (null for an unavailable measurement). -Pass --depth on both runs for an additional D32_SFLOAT attachment cleared to 1.0. This enables precise -queries and depth writes with an ALWAYS comparison. Both reports compare depth words exactly, count differing -pixels, and report non-clear pixels and passing samples separately. Shaders without an explicit depth output -write rasterized depth. Use --two-clear on both tags to repeat each draw in a fresh worker with the same -inputs and pipeline settings, clearing depth to 1 then 0. The report counts identical depth words, pixels -that follow both clears, and other changes. For deterministic draws, identical words across distinct clears -show an attachment write. Following both clears is consistent with untouched depth. Changing coverage, -side effects or undefined shader inputs limit this inference. Color and query repeatability are checked. -A clear-only color match cannot distinguish a discarded fragment from an explicit write of the clear value. - -A `--spirv` folder translated with `--bary-fallback`, with `python -I tools/bary_fallback_gs.py ` run on it -(it writes `.bary_gs.spv`), draws each shader that reads raw barycentrics through that pass-through geometry -shader (`VKS_GS`), so it runs on a device without `fragmentShaderBarycentric`; the sample itself comes from the -normal translation (`sample` keeps its own strata), and the folder only has to contain the sampled shaders. - -`--variant z` (default) leaves every texture lookup on the zero fallback; `--variant t` replaces the fallback images -with a UNORM gradient. The sint and uint variants require a matching 2D integer image at binding 0, -element zero, and constant in-bounds texel fetches at mip zero; other modules report unsupported. `--lo/--hi` split the sample over parallel workers -and `--only 3,7` re-runs single shaders (into `__re`, which `compare` prefers), for example the ones that -timed out while another process was starting. - -Shaders are numbered by their place in `sample.json`; the summary lines and everything under `` except -`sample.json` (which names the sampled shaders, so keep it out of reports) are counts and numbers only. -Usage: `python -I tools/ps_sweep.py --help` lists the options. -""" -from collections import Counter -import argparse -import json -import math -import os -import random -import struct -import subprocess -import sys -import time - -W = H = 32 -NOT_TRANSLATED = -1 # result code of a sampled shader that is not in the --spirv index -TOLERANCE = 1e-3 - - -def load_ps(spirv): - with open(os.path.join(spirv, "index.json"), encoding="utf-8") as f: - index = json.load(f) - return {k: v for k, v in index.items() if v.get("stage") == "ps"} - - -def stratum(meta): - """(needs barycentrics, descriptor class, control-flow style): what decides whether and how a shader runs.""" - bary = "fragmentShaderBarycentric" in meta.get("features", []) - b = meta.get("bindings", []) - klass = "none" if not b else ("low" if max(b) <= 3 else "high") - return (bary, klass, meta.get("control_flow")) - - -def pick_sample(ps, n, seed): - """At least min(10, size) shaders per stratum and the rest in proportion; `n` in all, or more when the floors alone add up to more.""" - groups = {} - for name in sorted(ps): - groups.setdefault(stratum(ps[name]), []).append(name) - total = sum(len(g) for g in groups.values()) - alloc = {s: min(len(g), max(10, round(n * len(g) / total))) for s, g in groups.items()} - while sum(alloc.values()) > n: - big = max(sorted(alloc, key=str), key=lambda s: alloc[s]) - if alloc[big] <= min(10, len(groups[big])): - break - alloc[big] -= 1 - rng = random.Random(seed) - picked = [] - for s in sorted(groups, key=str): - picked += rng.sample(groups[s], alloc[s]) - return picked, {s: (len(groups[s]), alloc[s]) for s in groups} - - -def _raw_glsl(loc): - """The generated vec4 of the vertex shader's output at location `loc` (the value a pixel shader reads there).""" - return (f"vec4(fract(0.13 * {loc + 1}.0 + p.x * 0.7), fract(0.29 * {loc + 1}.0 + p.y * 0.6)," - f" 0.1 + 0.1 * {loc % 7}.0, 1.0)") - - -def vs_glsl(locations, flats, halves=None): - """A vertex shader for one pixel-shader interface: a viewport-covering triangle from the vertex index and a vec4 - at each input location (varying across the triangle, constant per vertex for the flat ones). - - `halves` is the `f16_halves` of a pixel shader translated with --f16-interp-fallback, {param: [low, high]}. The - producer of that interface exports the two f16 halves of every param's raw word, decoded to f32, at those two - locations (UnpackHalf2x16, docs/design.md "16-bit interpolation without PerVertexKHR"). Here the param is the - same vec4 a default translation reads raw (and per vertex) at its own location, so both translations get the same - values: the halves are decoded from its bits at each vertex.""" - halves = {int(n): tuple(pair) for n, pair in (halves or {}).items()} - half_locs = {loc for pair in halves.values() for loc in pair} - lines = ["#version 450"] - for loc in locations: - lines.append(f"layout(location={loc}) {'flat ' if loc in flats else ''}out vec4 o{loc};") - lines.append("void main() {") - lines.append(" vec2 p = vec2(float((gl_VertexIndex << 1) & 2), float(gl_VertexIndex & 2));") - lines.append(" gl_Position = vec4(p * 2.0 - 1.0, 0.5, 1.0);") - for loc in locations: - if loc not in half_locs: - lines.append(f" o{loc} = {_raw_glsl(loc)};") - for n, pair in sorted(halves.items()): - lines.append(f" {{ vec4 r = {_raw_glsl(n)}; uvec4 w = floatBitsToUint(r);") - for half, loc in enumerate(pair): - if loc in locations: - comps = ", ".join(f"unpackHalf2x16(w.{c})[{half}]" for c in "xyzw") - lines.append(f" o{loc} = vec4({comps});") - lines.append(" }") - lines.append("}") - return "\n".join(lines) + "\n" - - -def gs_for(spirv, name): - """The pass-through geometry shader of a pixel shader translated with --bary-fallback - (`python -I tools/bary_fallback_gs.py ` writes `.bary_gs.spv` beside it), or None.""" - path = os.path.join(spirv, name + ".bary_gs.spv") - return path if os.path.isfile(path) else None - - -JOB_VARS = ("VKS_GS", "VKS_TEX", "VKS_NEED_MAINTENANCE8") - - -def job_env(base, timeout, variant, meta, gs): - """The environment of one draw: the parent's, minus every per-job variable it may have inherited, plus this job's.""" - env = {k: v for k, v in base.items() if k not in JOB_VARS} - env.update(VKS_TIMEOUT_S=str(timeout), VKS_HEAP_KB="1024") - if variant == "t": - env["VKS_TEX"] = "1" - if variant in ("sint", "uint"): - env["VKS_TEX"] = variant - if gs: - env["VKS_GS"] = gs - if meta.get("needs_maintenance8"): - env["VKS_NEED_MAINTENANCE8"] = "1" - return env - - -def make_vs(glslang, meta, cache_dir): - locs = sorted(meta.get("inputs", [])) - flats = set(meta.get("ps_flat_interpolants", [])) & set(locs) - halves = meta.get("f16_halves") or {} - key = ("vs_" + ("_".join(map(str, locs)) if locs else "none") + ("_f" + "_".join(map(str, sorted(flats))) if flats else "") - + "".join(f"_h{n}_{lo}_{hi}" for n, (lo, hi) in sorted(halves.items(), key=lambda kv: int(kv[0])))) - spv = os.path.join(cache_dir, key + ".spv") - if not os.path.exists(spv): - src = spv[:-4] + ".vert" - with open(src, "w", encoding="utf-8", newline="\n") as f: - f.write(vs_glsl(locs, flats, halves)) - r = subprocess.run([glslang, "-V", "-S", "vert", src, "-o", spv], capture_output=True, text=True) - if r.returncode: - raise SystemExit("glslangValidator failed: " + r.stdout[-300:]) - return spv - - -def cmd_sample(a): - ps = load_ps(a.spirv) - picked, per = pick_sample(ps, a.n, a.seed) - os.makedirs(a.out, exist_ok=True) - with open(os.path.join(a.out, "sample.json"), "w", encoding="utf-8", newline="\n") as f: - json.dump([{"name": k, "stratum": list(stratum(ps[k]))} for k in picked], f) - print(f"population {len(ps)} strata {len(per)} sampled {len(picked)}") - for s in sorted(per, key=str): - print(f" stratum {s}: population {per[s][0]} sampled {per[s][1]}") - - -def run_dir(a, tag): - return os.path.join(a.out, f"{tag}_{a.variant}{a.suffix}") - - -def cmd_run(a): - ps = load_ps(a.spirv) - with open(os.path.join(a.out, "sample.json"), encoding="utf-8") as f: - sample = json.load(f) - out_dir = run_dir(a, a.tag) - os.makedirs(out_dir, exist_ok=True) - cache = os.path.join(a.out, "vs") - os.makedirs(cache, exist_ok=True) - log = os.path.join(out_dir, f"results_{a.lo}.jsonl") - done = set() - if os.path.exists(log): - with open(log, encoding="utf-8") as f: - for line in f: - if line.strip(): - previous = json.loads(line) - if a.occlusion and previous["code"] == 0 and "samples_passed" not in previous: - raise SystemExit("--occlusion needs a fresh tag or suffix for previously unmeasured draws") - if previous["code"] != NOT_TRANSLATED and bool(previous.get("depth")) != a.depth: - raise SystemExit("different depth mode needs a fresh tag or suffix") - if previous["code"] != NOT_TRANSLATED and bool(previous.get("two_clear")) != a.two_clear: - raise SystemExit("different two-clear mode needs a fresh tag or suffix") - done.add(previous["i"]) - hi = a.hi or len(sample) - for i, s in enumerate(sample): - if i < a.lo or i >= hi or i in done or (a.only and i not in a.only): - continue - meta = ps.get(s["name"]) - if meta is None: # the translation in --spirv refused it (e.g. --bary-fallback and a computed I/J pair) - with open(log, "a", encoding="utf-8", newline="\n") as f: - f.write(json.dumps({"i": i, "code": NOT_TRANSLATED, "reason": "not translated", "targets": 0, "sec": 0}) + "\n") - continue - raw = os.path.join(out_dir, f"{i}.raw") - if os.path.exists(raw): - os.unlink(raw) - targets = max(meta.get("outputs") or [0]) + 1 - gs = gs_for(a.spirv, s["name"]) if meta.get("bary_fallback_input") else None - if meta.get("bary_fallback_input") and not gs: # a missing companion is not a pipeline failure - with open(log, "a", encoding="utf-8", newline="\n") as f: - f.write(json.dumps({"i": i, "code": NOT_TRANSLATED, "reason": "no bary_gs companion", "targets": 0, "sec": 0}) + "\n") - continue - env = job_env(os.environ, a.timeout, a.variant, meta, gs) - cmd = [a.exe, make_vs(a.glslang, meta, cache), os.path.join(a.spirv, s["name"] + ".spv"), raw, - str(W), str(H), str(targets)] - if a.depth: - cmd.append("--depth") - if os.path.exists(raw + ".depth"): - os.unlink(raw + ".depth") - if a.occlusion: - cmd.append("--occlusion") - start = time.time() - counts = [] - for zero in ([False, True] if a.two_clear else [False]): - draw = cmd.copy() - if zero: - draw[3] = raw + ".zero" - draw[draw.index("--depth")] = "--depth-zero" - for path in (draw[3], draw[3] + ".depth"): - if os.path.exists(path): - os.unlink(path) - try: - r = subprocess.run(draw, env=env, capture_output=True, text=True, timeout=a.timeout + 15, - stdin=subprocess.DEVNULL) - code, out, err = r.returncode, r.stdout, r.stderr - except subprocess.TimeoutExpired: - code, out, err = 3, "", "" - if code: - break - if a.occlusion or a.depth: - values = [line.removeprefix("samples_passed ") for line in out.splitlines() - if line.startswith("samples_passed ")] - if len(values) != 1 or not values[0].isascii() or not values[0].isdecimal(): - raise SystemExit("worker succeeded without a valid samples_passed measurement") - counts.append(int(values[0])) - reason = "" # a coarse reason: a missing feature or the failing Vulkan call, never a shader name - if code == 77: - reason = out.strip().replace("unsupported: ", "")[:80] - elif code not in (0, 3): - for line in err.splitlines(): - if line.startswith(("FAILED", "DEVICE_LOST", "PIPELINE")): - reason = line.split(" (line")[0][:60] - break - rec = {"i": i, "code": code, "reason": reason, "targets": targets, "sec": round(time.time() - start, 2)} - if a.depth: - rec["depth"] = True - if a.two_clear: - rec["two_clear"] = True - if counts and code == 0: - rec["samples_passed"] = counts[0] - if a.two_clear: - rec["zero_samples_passed"] = counts[1] - with open(log, "a", encoding="utf-8", newline="\n") as f: - f.write(json.dumps(rec) + "\n") - print("done", a.tag, a.variant, a.lo) - - -def written_stats(vals): - """(has NaN, every written value is zero, nothing written). The harness clears every target to -1.""" - written = [x for x in vals if x != -1.0] - return (any(math.isnan(x) for x in vals), bool(written) and all(x == 0.0 for x in written), not written) - - -def classify_pair(rec_a, rec_b, raw_a, raw_b, tol=TOLERANCE): - """The class of one shader from its two result records and output files.""" - code_a, code_b = rec_a["code"], rec_b["code"] - if NOT_TRANSLATED in (code_a, code_b): - return "not translated", "" - if 3 in (code_a, code_b): - return "timeout", "" - if code_a == 0 and code_b == 0: - targets_a, targets_b = rec_a.get("targets"), rec_b.get("targets") - if any(type(n) is not int or not 1 <= n <= 8 for n in (targets_a, targets_b)): - return "invalid readback", "invalid target count" - if targets_a != targets_b: - return "invalid readback", "target counts differ" - size = W * H * 16 * targets_a # RGBA32F, packed target by target - outputs = [] - for tag, path in (("a", raw_a), ("b", raw_b)): - try: - with open(path, "rb") as f: - data = f.read(size + 1) # detect trailing bytes without reading an unbounded file - except FileNotFoundError: - return "invalid readback", f"{tag}: missing output" - if len(data) != size: - return "invalid readback", f"{tag}: wrong output size" - outputs.append(struct.unpack(f"<{size // 4}f", data)) - fa, fb = outputs - nan_a, zero_a, none_a = written_stats(fa) - nan_b, zero_b, none_b = written_stats(fb) - if (nan_a, zero_a, none_a) != (nan_b, zero_b, none_b): - return "NaN or zero on one GPU only", "nan" if nan_a != nan_b else ("zero" if zero_a != zero_b else "unwritten") - worst, bad = 0.0, 0 - for x, y in zip(fa, fb): - if x == y or (math.isnan(x) and math.isnan(y)): - continue - if not (math.isfinite(x) and math.isfinite(y)): - # A NaN against a number, or an infinity against anything else, always differs; the tolerance - # arithmetic would pass inf against 1.0 and NaN against NaN in another component. - bad += 1 - worst = math.inf - continue - d = abs(x - y) - if d > tol + tol * max(abs(x), abs(y)): - bad += 1 - worst = max(worst, d) - if bad: - tier = "gross (>0.1)" if worst > 0.1 else ("moderate (>1e-2)" if worst > 1e-2 else "small (>1e-3)") - return "differs beyond tolerance", tier - return "OK on both", "" - if code_a != 0 and code_b != 0: - return "fails on both", f"{code_a}/{code_b}" - bad_rec, which = (rec_a, "a") if code_a != 0 else (rec_b, "b") - kind = "missing device feature" if bad_rec["code"] == 77 else f"exit {bad_rec['code']}" - return "fails on one GPU", f"{which}: {kind}" - - -def load_results(a, tag): - d = run_dir(a, tag) - recs = {} - for folder in (d, d + "_re"): # re-runs override the first pass - if not os.path.isdir(folder): - continue - for name in sorted(os.listdir(folder)): - if name.startswith("results_") and name.endswith(".jsonl"): - with open(os.path.join(folder, name), encoding="utf-8") as f: - for line in f: - if line.strip(): - r = json.loads(line) - r["dir"] = folder - recs[r["i"]] = r - return recs - - -def exact_pair(i, left, right): - """Compare successful draws with complete, equally shaped readbacks. Ignore stale files of failed draws.""" - target_bytes = W * H * 16 - clear = struct.pack("= 2**31, so both readings are - checked), 0x65 u32 enum bit set, 0x68 64-bit enum (ref = LENM enum hash) - 0x71 {u64 1, u64 pointer, u16 count, u16 capacity, u32 0}: a sorted array of (key, value) pairs - 0x73 {u32 capacity, u32 count, u64 pointer}: open addressing over `capacity` (key, value) slots; key 0 = empty - 0x75 {u32 groups, u32 count, u64 pointer}: groups of 16 control bytes + 16 (key, value) slots; a control - byte with bit 7 set is an empty slot - -An array's element is the member at its element index (+10); a map's key and value elements are the members at -`ref & 0xffff` and `ref >> 16`. In a (key, value) slot the value starts at the key size rounded up to the value's -alignment, and the slot is rounded up to the larger alignment. Alignment is the struct's 2^(+9) for type 5, 16 for -the 16-byte vectors and 0x36, 1 for 0x40, 4 for 0x32, else the element size capped at 8. - -Usage: - python -I psin_data.py [--json] [--limit N] - python -I psin_data.py --dump - -The default output is counts only: containers, block tables, bytes reached from the root, pointers, arrays and maps, -with every check. `--dump` prints the decoded tree of one container on stdout, hashes as hex, for local inspection; -it writes no file. Unknown member types (0x5a, 0x76, 0x77, ...) are counted and skipped, never guessed. - -In a carve directory, a stream that does not start with the `PSIN` magic is skipped (the folder holds other files -too). As the only argument it is a wrong path, so it is one `ERROR:` line and exit 2 rather than an empty count. -""" -import argparse -import bisect -import collections -import json -import os -import struct -import sys - -sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) -import psin_index # noqa: E402 - -END_OF_TABLE = 0x70707070 -FILL = b"\xaa" * 8 -ROW = 16 -ELEMENT = psin_index.ARRAY_ELEMENT -MAX_DEPTH = 64 - -SCALARS = { - 0x01: " first or blob[at + 8:at + ROW] != FILL: - raise ValueError(f"block table row at {at} has no 0xaa fill") - blocks.append((kind, struct.unpack_from(" first: # a damaged table must not make the walker allocate past the region - raise ValueError(f"block table declares blocks past the first section at {first}") - out.append((kind, at, size)) - at += (size + 15) & ~15 - return out, at == first - - -class Container: - """One PSIN container's schema, blocks and root, ready to walk.""" - - def __init__(self, blob): - self.blob = blob - self.error = "" - record = psin_index.parse(blob) - if record is None: - raise ValueError("not a PSIN container") - if not record["complete"]: - raise ValueError(f"incomplete container: {record['error']}") - sections = {s["tag"]: s for s in record["sections"]} - if "LSCH" not in sections or "LRSC" not in sections: - raise ValueError("no LSCH or LRSC section") - lsch, lenm, lrsc = sections["LSCH"], sections.get("LENM"), sections["LRSC"] - self.structs = {s["hash"]: s for s in psin_index.decode_lsch( - blob[lsch["offset"] + 8:lsch["offset"] + lsch["size"]])} - self.enums = {} - if lenm: - self.enums = {e["hash"]: e for e in psin_index.decode_lenm( - blob[lenm["offset"] + 8:lenm["offset"] + lenm["size"]])} - self.blocks, self.fills = block_table(blob, record["first_section"]) - if lrsc["payload"] < 0x14 or blob[lrsc["offset"] + 8:lrsc["offset"] + 12] != b"0DRP": - raise ValueError("LRSC does not start with a 0DRP header") - self.root = struct.unpack_from("> 20 - - def resolve(self, at, need, stats, kind): - """The (block type, absolute offset, block number) a pointer reaches, or None (null or out of range).""" - number, off = self.pointer(at) - if number == 0 and off == 0: - stats[f"{kind} null"] += 1 - return None - if not 1 <= number <= len(self.blocks): - stats[f"{kind} block out of range"] += 1 - return None - btype, base, size = self.blocks[number - 1] - if off + need > size: - stats[f"{kind} past block end"] += 1 - return None - stats[f"{kind} resolved"] += 1 - return btype, base + off, number - - -class Walker: - """Visits every value reachable from the root; collects counts, byte coverage and (optionally) the values.""" - - def __init__(self, container, stats, keep=False): - self.c = container - self.stats = stats - self.keep = keep - self.cover = [bytearray(size) for _, _, size in container.blocks] - self.seen = set() - self._block_bases = [base for _, base, _ in container.blocks] - self._block_ends = [base + size for _, base, size in container.blocks] - self._limit = None - - def _block_end(self, at): - i = bisect.bisect_right(self._block_bases, at) - 1 - if i >= 0 and at <= self._block_ends[i]: - return self._block_ends[i] - return None - - def _active_end(self, at): - return self._limit if self._limit is not None else self._block_end(at) - - def _read_size(self, m): - t = m["type"] - if t in SCALARS: - return struct.calcsize(SCALARS[t]) - if t in HASHES: - return struct.calcsize(HASHES[t]) - if t in ENUMS: - return struct.calcsize(ENUMS[t]) - if t == 0x40: - return m["ref"] - return _HEADER_BYTES.get(t) - - def mark(self, number, absolute, n): - btype, base, size = self.c.blocks[number - 1] - lo = absolute - base - self.cover[number - 1][lo:min(size, lo + n)] = b"\x01" * max(0, min(size, lo + n) - lo) - - def run(self): - c, st = self.c, self.stats - if not 1 <= c.root <= len(c.blocks): - st["root out of range"] += 1 - return None - btype, base, size = c.blocks[c.root - 1] - if btype not in c.structs: - st["root not a struct block"] += 1 - return None - if size < c.structs[btype]["size"]: - st["root past block end"] += 1 - return None - value = self.struct(btype, base, 0, c.root) - reached = sum(sum(b) for b in self.cover) - st["bytes"] += sum(size for _, _, size in c.blocks) - st["bytes reached"] += reached - st["blocks"] += len(c.blocks) - st["blocks reached"] += sum(1 for b in self.cover if any(b)) - return value - - def struct(self, name, at, depth, number=None): - c, st = self.c, self.stats - s = c.structs.get(name) - if s is None: - st["struct not in LSCH"] += 1 - return None - if number: - _, base, size = c.blocks[number - 1] - limit = base + size - else: - limit = self._active_end(at) - if limit is None or at < 0 or at + s["size"] > limit: - st["struct past block end"] += 1 - return None - if number: - self.mark(number, at, s["size"]) - if (name, at) in self.seen or depth > MAX_DEPTH: - return None - self.seen.add((name, at)) - st["structs"] += 1 - out = {} if self.keep else None - prev_limit = self._limit - self._limit = limit - try: - for m in s["members"]: - if m["hash"] == ELEMENT: - continue - v = self.value(m, s["members"], at + m["offset"], depth) - if self.keep: - out[f"{m['hash']:08x}"] = v - finally: - self._limit = prev_limit - return out - - def elements(self, el, members, base, count, depth): - size = self.c.size_of(el) - return [self.value(el, members, base + i * size, depth + 1) for i in range(count)] - - def value(self, m, members, at, depth): - c, st, blob = self.c, self.stats, self.c.blob - t = m["type"] - st[f"type {t:02x}"] += 1 - need = self._read_size(m) - if need is not None: - end = self._active_end(at) - if end is None or at < 0 or at + need > end: - st["member past block end"] += 1 - return None - if t in SCALARS: - v = struct.unpack_from(SCALARS[t], blob, at) - return (v[0] if len(v) == 1 else list(v)) if self.keep else None - if t in HASHES: - if not self.keep: - return None - return f"{struct.unpack_from(HASHES[t], blob, at)[0]:0{struct.calcsize(HASHES[t]) * 2}x}" - if t in ENUMS: - return self.enum(m, t, at) - if t == 0x05: - return self.struct(m["ref"], at, depth + 1) - if t == 0x07: - number, _ = c.pointer(at) - need = 1 - if 1 <= number <= len(c.blocks): - s = c.structs.get(c.blocks[number - 1][0]) - if s is not None: - need = max(1, s["size"]) - r = c.resolve(at, need, st, "struct pointer") - if r is None: - return None - btype, absolute, number = r - if btype not in c.structs: - st["struct pointer to a non-struct block"] += 1 - return None - return self.struct(btype, absolute, depth + 1, number) - if t == 0x44 and blob[at + 15] & 0x80: - n = blob[at + 15] & 0x7F - if n <= 15 and blob[at + n] == 0: - st["short strings in place"] += 1 - return blob[at:at + n].decode("utf-8", "replace") if self.keep else None - st["short string length mismatch"] += 1 - return None - if t in (0x42, 0x44): - r = c.resolve(at, 1, st, "string pointer") - if r is None: - return None - btype, absolute, number = r - _, base, size = c.blocks[number - 1] - end = blob.find(b"\0", absolute, base + size) - if end < 0: - st["string without NUL"] += 1 - return None - st["strings"] += 1 - self.mark(number, absolute, end - absolute + 1) - return blob[absolute:end].decode("utf-8", "replace") if self.keep else None - if t == 0x40: - st["char arrays"] += 1 - return blob[at:at + m["ref"]].split(b"\0")[0].decode("utf-8", "replace") if self.keep else None - if t in (0x50, 0x53, 0x54, 0x5C, 0x52): - return self.array(m, members, at, depth) - if t in (0x71, 0x73, 0x75): - return self.map(m, members, at, depth) - st[f"type {t:02x} not decoded"] += 1 - return None - - def enum(self, m, t, at): - c, st = self.c, self.stats - v = struct.unpack_from(ENUMS[t], c.blob, at)[0] - e = c.enums.get(m["ref"]) - if e is None: - st["enum not in LENM"] += 1 - elif t == 0x65: - allowed = 0 - for x in e["values"]: - if 0 <= x["value"] < 32: - allowed |= 1 << x["value"] - st["bit set within its enum" if v & ~allowed == 0 else "bit set outside its enum"] += 1 - else: - values = {x["value"] for x in e["values"]} - if t == 0x62 and v not in values and (v & 0xFFFFFFFF) in values: - v &= 0xFFFFFFFF # 32-bit enum: LENM lists both negative values and values >= 2**31 - st["enum value listed" if v in values else "enum value not listed"] += 1 - return v if self.keep else None - - def array(self, m, members, at, depth): - c, st, blob = self.c, self.stats, self.c.blob - t = m["type"] - idx = m["index"] - if idx >= len(members) or members[idx]["hash"] != ELEMENT: - st["array without element descriptor"] += 1 - return None - el = members[idx] - size = c.size_of(el) - if not size: - st[f"array of undecoded type {el['type']:02x}"] += 1 - return None - if t in (0x50, 0x53): - st["fixed arrays"] += 1 - n = m["ref"] & 0xFFFF - end = self._active_end(at) - if end is None or at < 0 or at + size * n > end: - st["fixed array out of bounds"] += 1 - return None - return self.elements(el, members, at, n, depth) - if t == 0x54: - end = self._active_end(at) - if end is None or at < 0 or at + 8 > end: - st["inline array out of bounds"] += 1 - return None - capacity, count = struct.unpack_from(" capacity"] += 1 - n = min(count, capacity) - if at + 8 + size * n > end: - st["inline array out of bounds"] += 1 - return None - return self.elements(el, members, at + 8, n, depth) - if t == 0x5C: - count, capacity = struct.unpack_from(" capacity"] += 1 - if count == 0: - st[f"{kind} empty"] += 1 - return [] - r = c.resolve(where, size * count, st, kind) - if r is None: - return None - btype, absolute, number = r - want = el["ref"] if el["type"] == 0x05 else el["type"] - st[f"{kind} block type matches element" if btype == want else f"{kind} block type differs"] += 1 - self.mark(number, absolute, size * count) - _, blk_base, blk_size = c.blocks[number - 1] - prev_limit = self._limit - self._limit = blk_base + blk_size - try: - return self.elements(el, members, absolute, count, depth) - finally: - self._limit = prev_limit - - def map(self, m, members, at, depth): - c, st, blob = self.c, self.stats, self.c.blob - t = m["type"] - ki, vi = m["ref"] & 0xFFFF, m["ref"] >> 16 - if ki >= len(members) or vi >= len(members) or members[ki]["hash"] != ELEMENT or members[vi]["hash"] != ELEMENT: - st["map without element descriptors"] += 1 - return None - key, val = members[ki], members[vi] - layout = c.slot(key, val) - if layout is None: - st[f"map of undecoded types {key['type']:02x}/{val['type']:02x}"] += 1 - return None - voff, slot = layout - kind = f"map {t:02x}" - pairs = [] - if t == 0x71: - flag = struct.unpack_from(" capacity"] += 1 - if count == 0: - st[f"{kind} empty"] += 1 - return {} if self.keep else None - r = c.resolve(at + 8, (count - 1) * slot + voff + c.size_of(val), st, kind) - if r is None: - return None - _, absolute, number = r - self.mark(number, absolute, count * slot) - keys = [blob[absolute + i * slot:absolute + i * slot + c.size_of(key)][::-1] for i in range(count)] - st[f"{kind} keys ascending" if keys == sorted(keys) else f"{kind} keys not ascending"] += 1 - slots = [absolute + i * slot for i in range(count)] - elif t == 0x75: - groups, count = struct.unpack_from(" 0 and (groups & (groups - 1) == 0) - st[f"{kind} groups a power of two" if power else f"{kind} groups not a power of two"] += 1 - slots = [] - for g in range(groups): - base = absolute + g * group - for i in range(16): - if not blob[base + i] & 0x80: - slots.append(base + 16 + i * slot) - st[f"{kind} used slots == count" if len(slots) == count else f"{kind} used slots != count"] += 1 - else: - capacity, count = struct.unpack_from("= limit: - break - return dict(sorted(stats.items())) - - -def main(): - ap = argparse.ArgumentParser(description="Decode PSIN instance data through its LSCH schema.") - ap.add_argument("src", help="PSIN file or directory of carved .bin streams") - ap.add_argument("--json", action="store_true", help="print the counts as JSON") - ap.add_argument("--limit", type=psin_index.count, help="stop after this many PSIN files") - ap.add_argument("--dump", action="store_true", help="print one container's decoded tree (local inspection only)") - a = ap.parse_args() - if not os.path.exists(a.src): - print(f"ERROR: {a.src}: no such file or folder", file=sys.stderr) - return 2 - if os.path.isfile(a.src): - # a directory skips a stream without the magic, but a lone file named on the command line is a wrong path - try: - with open(a.src, "rb") as f: - magic = f.read(4) - except OSError as e: - print(f"ERROR: {a.src}: {e}", file=sys.stderr) - return 2 - if magic != psin_index.MAGIC: - print(f"ERROR: {a.src}: not a PSIN container", file=sys.stderr) - return 2 - if a.dump: - if not os.path.isfile(a.src): - print("ERROR: --dump takes one PSIN file", file=sys.stderr) - return 2 - try: - with open(a.src, "rb") as f: - blob = f.read() - container = Container(blob) - stats = collections.Counter() - tree = Walker(container, stats, keep=True).run() - except (OSError, ValueError, struct.error, IndexError) as e: - print(f"ERROR: {a.src}: {e}", file=sys.stderr) - return 2 - root_type = container.blocks[container.root - 1][0] if 1 <= container.root <= len(container.blocks) else 0 - json.dump({f"{root_type:08x}": tree}, sys.stdout, indent=1, default=str) - sys.stdout.write("\n") - return 0 - try: - stats = collect(a.src, a.limit) - except OSError as e: - print(f"ERROR: {a.src}: {e}", file=sys.stderr) - return 2 - if a.json: - json.dump(stats, sys.stdout, indent=1) - sys.stdout.write("\n") - return 0 - for k, v in stats.items(): - print(f"{k:48} {v:,}") - if stats.get("bytes"): - print(f"{'bytes reached from the root':48} {100 * stats['bytes reached'] / stats['bytes']:.2f}%") - return 0 - - -if __name__ == "__main__": - try: # a redirected stdout is strict ANSI code page under -I; write '?' for what it cannot encode - sys.stdout.reconfigure(errors="replace") - except (AttributeError, ValueError, OSError): - pass - sys.exit(main()) diff --git a/tools/psin_index.py b/tools/psin_index.py deleted file mode 100644 index 5672cffa2..000000000 --- a/tools/psin_index.py +++ /dev/null @@ -1,468 +0,0 @@ -"""Index the PSIN metadata container used by the game's data and script archives. - -PSIN is a small metadata container. It appears at the start of carved zlib streams in `data.rpf` and -`script.rpf`; it is not a script program and it is not a model or texture resource. Every measured -file uses the same header: - - +0 50 53 49 4e "PSIN" - +4 u32 big-endian absolute offset of the first section (LSCH) - +8 u32 little-endian version (22 on every measured file) - +12 u32 little-endian byte count of the hash table that follows the header - -The section table starts at the offset in `+4` and runs to the end of the file. Every section is: - - +0 4-byte ASCII tag - +4 u32 big-endian total size, including this 8-byte header - -Sections are contiguous: the next section starts at `offset + size`, and the last one ends at EOF. -The measured tags are `LSCH`, `LENM`, `LSNS`, `LGID`, `LRSC` and `CHKS`. `LGID` is an empty section -(8 bytes). `LRSC` starts with a `0DRP` page directory header. `CHKS` carries the file size and a -checksum. - -`LSNS` is a block table followed by the blocks (measured over every `LSNS` section in the package; docs/psin.md): - - +0 u32 little-endian block count n (0 for the empty 12-byte section) - +4 n x (u32 kind, u32 byte count) - then the n blocks back to back, each a whole number of 16-byte records - -The byte counts fill the payload exactly. The kind's high byte is 1 or 2 (records read as 4- or 8-byte words); -its low byte varies. The records themselves are uniformly random bytes that match no tested name hash; this tool -reads the layout, not the contents. - -`LSCH` is a type schema and `LENM` its enum table (measured over all 18,640 PSIN streams in the archives of package -1.0.2.1; see docs/psin.md). Both store all headers first and then all elements, and neither stores the -header count: it is the one count k for which the headers' element counts fill the payload exactly. - - LSCH struct header, 32 bytes LSCH member, 16 bytes LENM enum header, 24 bytes - +0 u32 name hash +0 u32 name hash +0 u32 name hash - +4 u32 layout signature +4 u32 byte offset +4 u32 layout signature - +8 u8 flags +8 u8 type code +8 8 fill bytes (0xee) - +9 u8 log2 alignment +9 u8 sub-code +16 u32 value count - +10 u16 0, +12 u32 0 +10 u16 element index +20 u32 0 - +16 8 fill bytes (0xaa) +12 u32 reference hash LENM value, 16 bytes - +24 u32 byte size +0 i64 value - +28 u16 0, +30 u16 member count +8 u64 name hash (high half 0) - -Names are case-sensitive joaat. A member whose name hash is 0x100 is the element descriptor of an array member -(type 0x5c), whose element index points at it; a struct member (type 5) references a struct name hash, and the -enum members (0x60, 0x62, 0x65, ...) reference an enum name hash in `LENM`. - -On the package measured here the `script.rpf` carve contains 671 streams that start with `PSIN`: -670 are complete and one is the first 64 KiB of a larger record (its first-section offset is beyond -the carved block). A complete record in `data.rpf` is validated by the project's existing -`ArchiveReader` path, not by this tool. The tool deliberately indexes containers; it does not assign -meaning to the CHKS payload or to the bytes between the header and the first section. - -Usage: - python -I psin_index.py [--json] [--schema] [--limit N] - -Text output prints one line per PSIN file and a summary; `--json` writes `{files, summary}`. `--schema` adds the -decoded LSCH structs and LENM enums (hashes as hex) to each JSON record, or prints them in text mode. -""" -import argparse -import json -import os -import struct -import sys - -MAGIC = b"PSIN" -HEADER = 16 -SECTION_HEADER = 8 -STRUCT_HEADER = 32 -MEMBER = 16 -ENUM_HEADER = 24 -ENUM_VALUE = 16 -ARRAY_ELEMENT = 0x100 # member name hash of an array's element descriptor -ARRAY_TYPE = 0x5C - - -def _u32_be(blob, off): - return struct.unpack_from(">I", blob, off)[0] - - -def _u32_le(blob, off): - return struct.unpack_from(" len(payload): - raise ValueError(f"LSNS block table ({n} blocks) runs past the section") - blocks = [struct.unpack_from("= s["size"]: - return f"struct {s['hash']:08x} member {i} at offset {m['offset']} is past size {s['size']}" - if m["type"] == ARRAY_TYPE: - j = m["index"] - if j >= len(s["members"]) or s["members"][j]["hash"] != ARRAY_ELEMENT: - return f"struct {s['hash']:08x} array member {i} points at {j}, not an element descriptor" - return "" - - -def _hexed(structs, enums): - """The decoded schema with hashes as 8-digit hex, for JSON and text output.""" - out_s = [dict(s, hash=f"{s['hash']:08x}", signature=f"{s['signature']:08x}", - members=[dict(m, hash=f"{m['hash']:08x}", ref=f"{m['ref']:08x}") for m in s["members"]]) - for s in structs] - out_e = [dict(e, hash=f"{e['hash']:08x}", signature=f"{e['signature']:08x}", - values=[{"value": v["value"], "hash": f"{v['hash']:08x}"} for v in e["values"]]) - for e in enums] - return {"structs": out_s, "enums": out_e} - - -def parse(blob, schema=False): - """Parse one PSIN container. Returns None when the blob is not PSIN. - - With `schema`, the record also carries the decoded LSCH structs and LENM enums under "schema". - """ - if len(blob) < HEADER or blob[:4] != MAGIC: - return None - first = _u32_be(blob, 4) - version = _u32_le(blob, 8) - table_bytes = _u32_le(blob, 12) - record = { - "magic": "PSIN", - "size": len(blob), - "first_section": first, - "version": version, - "table_bytes": table_bytes, - "sections": [], - "rsc_version": None, - "checksum_size": None, - "checksum": "", - "structs": None, - "members": None, - "enums": None, - "enum_values": None, - "schema_error": "", - "lsns_blocks": None, - "lsns_records": None, - "lsns_error": "", - "complete": False, - "error": "", - } - structs = enums = None - lsch_seen = lenm_seen = False - lsch_error = lenm_error = "" - if first < HEADER or first > len(blob): - record["error"] = f"first section offset {first} is outside the file" - return _with_schema(record, schema, structs, enums) - if len(blob) - first < SECTION_HEADER: - record["error"] = f"missing or truncated first section header at {first}" - return _with_schema(record, schema, structs, enums) - offset = first - while offset + SECTION_HEADER <= len(blob): - tag = blob[offset:offset + 4] - size = _u32_be(blob, offset + 4) - if any(c < 0x20 or c > 0x7E for c in tag): - record["error"] = f"non-text section tag at {offset}" - break - if size < SECTION_HEADER or offset + size > len(blob): - record["error"] = f"section {tag.decode('latin-1')} at {offset} has size {size}" - break - payload_off = offset + SECTION_HEADER - section = { - "tag": tag.decode("latin-1"), - "offset": offset, - "size": size, - "payload": size - SECTION_HEADER, - } - if tag == b"LRSC" and size - SECTION_HEADER >= 8 and blob[payload_off:payload_off + 4] == b"0DRP": - section["rsc_magic"] = "0DRP" - section["rsc_version"] = _u32_le(blob, payload_off + 4) - if record["rsc_version"] is None: - record["rsc_version"] = section["rsc_version"] - elif tag == b"CHKS" and size - SECTION_HEADER >= 8: - section["checksum_size"] = _u32_be(blob, payload_off) - section["checksum"] = blob[payload_off + 4:payload_off + 8].hex() - if record["checksum_size"] is None: - record["checksum_size"] = section["checksum_size"] - record["checksum"] = section["checksum"] - elif tag == b"LSNS": - try: - blocks = decode_lsns(blob[payload_off:offset + size]) - except ValueError as e: - section["lsns_error"] = record["lsns_error"] = str(e) - else: - section["blocks"] = [{"kind": f"0x{k:x}", "bytes": b} for k, b in blocks] - record["lsns_blocks"] = len(blocks) - record["lsns_records"] = sum(b for _k, b in blocks) // LSNS_RECORD - elif tag == b"LSCH" and not lsch_seen: - lsch_seen = True - try: - structs = decode_lsch(blob[payload_off:offset + size]) - except ValueError as e: - lsch_error = str(e) - else: - record["structs"] = len(structs) - record["members"] = sum(len(s["members"]) for s in structs) - lsch_error = check_schema(structs) - elif tag == b"LENM" and not lenm_seen: - lenm_seen = True - try: - enums = decode_lenm(blob[payload_off:offset + size]) - except ValueError as e: - lenm_error = str(e) - else: - record["enums"] = len(enums) - record["enum_values"] = sum(len(e["values"]) for e in enums) - record["sections"].append(section) - offset += size - record["schema_error"] = "; ".join(e for e in (lsch_error, lenm_error) if e) - if not record["error"] and offset != len(blob): - record["error"] = f"section walk ended at {offset} of {len(blob)}" - record["complete"] = not record["error"] and offset == len(blob) - return _with_schema(record, schema, structs, enums, lsch_error, lenm_error) - - -def _with_schema(record, schema, structs, enums, lsch_error="", lenm_error=""): - """With `schema`, give every record the same "schema" shape, whether or not the sections were reached. - - "lsch" and "lenm" say whether each section was decoded; "reason" says why one was not (a structural error - that stopped the walk first, a missing section, or the decode error), and is "" when both were. - """ - if not schema: - return record - entry = _hexed(structs or [], enums or []) - entry["lsch"] = structs is not None - entry["lenm"] = enums is not None - reasons = [] - for name, decoded, section_error in ( - ("LSCH", entry["lsch"], lsch_error), - ("LENM", entry["lenm"], lenm_error), - ): - if decoded: - continue - if any(s["tag"] == name for s in record["sections"]): - reasons.append(section_error or f"{name} not decoded") - elif record["error"]: - reasons.append(f"no whole {name} section: {record['error']}") - else: - reasons.append(f"no {name} section") - entry["reason"] = "; ".join(dict.fromkeys(reasons)) - record["schema"] = entry - return record - - -def input_paths(src): - """Paths read from a single source file or a directory of carved PSIN streams.""" - if os.path.isfile(src): - yield src - return - for name in sorted(os.listdir(src)): - if not name.endswith(".bin"): - continue - path = os.path.join(src, name) - if os.path.isfile(path): - yield path - - -def files_in(src): - for path in input_paths(src): - with open(path, "rb") as f: - yield os.path.basename(path), f.read() - - -def collect(src, limit=None, schema=False): - records = [] - for name, blob in files_in(src): - record = parse(blob, schema) - if record is None: - continue - record["file"] = name - records.append(record) - if limit and len(records) >= limit: - break - return records - - -def summarize(records): - tags = {} - versions = {} - for r in records: - versions[r["version"]] = versions.get(r["version"], 0) + 1 - for s in r["sections"]: - tags[s["tag"]] = tags.get(s["tag"], 0) + 1 - return { - "files": len(records), - "complete": sum(1 for r in records if r["complete"]), - "incomplete": sum(1 for r in records if not r["complete"]), - "versions": {str(k): v for k, v in sorted(versions.items())}, - "section_tags": dict(sorted(tags.items())), - "section_bytes": sum(s["size"] for r in records for s in r["sections"]), - "rsc_122": sum(1 for r in records if r["rsc_version"] == 122), - "checksummed": sum(1 for r in records if r["checksum_size"] is not None), - "lsch_decoded": sum(1 for r in records if r["structs"] is not None), - "lenm_decoded": sum(1 for r in records if r["enums"] is not None), - "schema_errors": sum(1 for r in records if r["schema_error"]), - "structs": sum(r["structs"] or 0 for r in records), - "members": sum(r["members"] or 0 for r in records), - "enums": sum(r["enums"] or 0 for r in records), - "enum_values": sum(r["enum_values"] or 0 for r in records), - "lsns_decoded": sum(1 for r in records if r["lsns_blocks"] is not None), - "lsns_empty": sum(1 for r in records if r["lsns_blocks"] == 0), - "lsns_errors": sum(1 for r in records if r["lsns_error"]), - "lsns_records": sum(r["lsns_records"] or 0 for r in records), - "lsns_kinds": dict(sorted(_lsns_kinds(records).items())), - } - - -def _lsns_kinds(records): - kinds = {} - for r in records: - for s in r["sections"]: - for b in s.get("blocks", ()): - kinds[b["kind"]] = kinds.get(b["kind"], 0) + 1 - return kinds - - -def count(text): - """--limit: 0 or a negative value used to mean no limit (0 is falsy, a negative count is never reached).""" - try: - value = int(text) - except ValueError: - raise argparse.ArgumentTypeError(f"invalid int value: {text!r}") from None - if value < 1: - raise argparse.ArgumentTypeError("must be at least 1") - return value - - -def main(): - ap = argparse.ArgumentParser(description="Index PSIN metadata containers.") - ap.add_argument("src", help="PSIN file or directory of carved .bin streams") - ap.add_argument("--json", action="store_true", help="write records and summary as JSON") - ap.add_argument("--schema", action="store_true", help="include the decoded LSCH structs and LENM enums") - ap.add_argument("--limit", type=count, help="stop after this many PSIN files") - a = ap.parse_args() - - if not os.path.exists(a.src): # files_in took any non-file for a folder: a typo ended in a traceback - print(f"ERROR: {a.src}: no such file or folder", file=sys.stderr) - return 2 - try: - records = collect(a.src, a.limit, a.schema) - except OSError as e: - print(f"ERROR: {a.src}: {e}", file=sys.stderr) - return 2 - summary = summarize(records) - if a.json: - json.dump({"files": records, "summary": summary}, sys.stdout, indent=1) - sys.stdout.write("\n") - return 0 - for r in records: - tags = " ".join(f"{s['tag']}:{s['size']}" for s in r["sections"]) or "-" - state = "ok" if r["complete"] else f"INCOMPLETE ({r['error']})" - extra = "" - if r["rsc_version"] is not None: - extra += f" rsc={r['rsc_version']}" - if r["checksum_size"] is not None: - extra += f" chks={r['checksum_size']}" - if r["structs"] is not None: - extra += f" structs={r['structs']} members={r['members']}" - if r["enums"] is not None: - extra += f" enums={r['enums']} values={r['enum_values']}" - if r["schema_error"]: - extra += f" SCHEMA ({r['schema_error']})" - print(f"{r['file']} size={r['size']} v={r['version']} {state} {tags}{extra}") - if a.schema: - if r["schema"]["reason"]: - print(f" schema: {r['schema']['reason']}") - for s in r["schema"]["structs"]: - print(f" struct {s['hash']} sig={s['signature']} size={s['size']} " - f"align=2^{s['align_log2']} flags={s['flags']:#x} members={len(s['members'])}") - for m in s["members"]: - print(f" {m['hash']} +{m['offset']:#x} type={m['type']:#04x} sub={m['sub']} " - f"index={m['index']} ref={m['ref']}") - for e in r["schema"]["enums"]: - print(f" enum {e['hash']} sig={e['signature']} values={len(e['values'])}") - for v in e["values"]: - print(f" {v['hash']} = {v['value']}") - print(f"{summary['files']} PSIN files, {summary['complete']} complete, " - f"{summary['incomplete']} incomplete; tags {summary['section_tags']}; " - f"rsc122 {summary['rsc_122']}, checksummed {summary['checksummed']}; " - f"LSCH decoded {summary['lsch_decoded']} ({summary['structs']} structs, {summary['members']} members), " - f"LENM decoded {summary['lenm_decoded']} ({summary['enums']} enums, {summary['enum_values']} values), " - f"schema errors {summary['schema_errors']}; " - f"LSNS decoded {summary['lsns_decoded']} ({summary['lsns_empty']} empty, {summary['lsns_records']} records), " - f"LSNS errors {summary['lsns_errors']}") - return 0 - - -if __name__ == "__main__": - try: # a redirected stdout is strict ANSI code page under -I; write '?' for what it cannot encode - sys.stdout.reconfigure(errors="replace") - except (AttributeError, ValueError, OSError): - pass - sys.exit(main()) diff --git a/tools/psin_names.py b/tools/psin_names.py deleted file mode 100644 index 729f798af..000000000 --- a/tools/psin_names.py +++ /dev/null @@ -1,254 +0,0 @@ -"""Resolve the name-hash fields of PSIN instance data against a local list of resource names. - -`psin_data.py` walks a PSIN container from its root through the `LSCH` schema. Members of type 0x4a, 0x4d and 0x4b -hold a u32 hash and members of type 0x4f a u64 hash. Many of them are the names of other resources (drawables, -fragments, dictionaries, maps). This tool collects every such value reached from the root and looks it up in a -dictionary built from names you already have: - - u32 hash joaat of the lower-cased name (the rule docs/world_names.md gives for `archetypeName`) - u64 hash low 64 bits of MurmurHash3 x64 128, seed 0, over the name's UTF-8 bytes (as listed and lower-cased) - -Every run also hashes a salted control: each name with CONTROL_SALT appended, through the same two rules. Control -names are not real names, so their matches show how many of the real matches chance alone would give. The summary -reports both, per field and in total. - -Names come from `rpf9_names.py` JSON (the `.#dr`, `.#ft`, `.#dd` suffix is dropped) or from text files with one name -per line. They are game-derived: keep the name lists, `--refs` output and `--json` field tables in your local work -folder. Only aggregate counts belong in git, issues or pull requests. - -Usage: - python -I psin_names.py --names [--names ...] - [--json] [--fields N] [--refs OUT.tsv] [--limit N] - -`--refs` writes one row per resolved value: file, struct hash, field hash, member type, value and name. -""" -import argparse -import collections -import json -import os -import re -import struct -import sys - -sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) -import psin_data # noqa: E402 -import psin_index # noqa: E402 -from report_paths import same_report_path # noqa: E402 -from world_names import joaat, murmur3_x64_128 # noqa: E402 - -CONTROL_SALT = "#zq" -HASH32 = (0x4A, 0x4D, 0x4B) -HASH64 = (0x4F,) -SUFFIX = re.compile(r"\.#[a-z0-9]{2}$") - - -class HashWalker(psin_data.Walker): - """A psin_data walker that also records every hash value with the struct and member it belongs to. - - Array elements and map keys and values carry the hash of the member that holds the array or map. - """ - - def __init__(self, container, stats): - super().__init__(container, stats) - self.found = [] - self._structs = [] - self._fields = [] - - def struct(self, name, at, depth, number=None): - self._structs.append(name) - try: - return super().struct(name, at, depth, number) - finally: - self._structs.pop() - - def value(self, m, members, at, depth): - named = m["hash"] != psin_data.ELEMENT - if named: - self._fields.append(m["hash"]) - try: - t = m["type"] - if t in psin_data.HASHES and self._structs and self._fields: - v = struct.unpack_from(psin_data.HASHES[t], self.c.blob, at)[0] - self.found.append((self._structs[-1], self._fields[-1], t, v)) - return super().value(m, members, at, depth) - finally: - if named: - self._fields.pop() - - -def hash_values(blob): - """[(struct hash, field hash, member type, value)] for one PSIN container. Raises ValueError if it is unreadable.""" - container = psin_data.Container(blob) - walker = HashWalker(container, collections.Counter()) - try: - walker.run() - except (struct.error, IndexError) as e: - raise ValueError(f"walk error: {e}") from None - return walker.found - - -def load_names(paths): - """The set of names in rpf9_names.py JSON files and one-name-per-line text files. A .json file that is not - JSON, or not the shape rpf9_names.py writes, raises ValueError naming the file (--names is repeatable).""" - names = set() - for path in paths: - if path.endswith(".json"): - try: - with open(path, encoding="utf-8") as f: - doc = json.load(f) - except (ValueError, RecursionError) as e: # ValueError: not JSON, or not UTF-8 - raise ValueError(f"{path}: not JSON: {e}") from None - rows = doc.get("files", []) if isinstance(doc, dict) else None - if not isinstance(rows, list): - raise ValueError(f"{path}: expected rpf9_names.py JSON, an object with a 'files' array") - for row in rows: - listed = row.get("names", []) if isinstance(row, dict) else None - if not isinstance(listed, list) or not all(isinstance(n, str) for n in listed): - raise ValueError(f"{path}: each 'files' row must be an object whose 'names' is an array of " - "strings") - names.update(SUFFIX.sub("", n) for n in listed) - else: - with open(path, encoding="utf-8", errors="replace") as f: - names.update(line.strip() for line in f) - names.discard("") - return names - - -def dictionaries(names, salt=""): - """({u32 hash: name}, {u64 hash: name}) for the names with `salt` appended.""" - d32, d64 = {}, {} - for n in sorted(names): - s = n + salt - d32.setdefault(joaat(s), n) - for form in {s, s.lower()}: - d64.setdefault(murmur3_x64_128(form.encode("utf-8"))[0], n) - return d32, d64 - - -def scan(src, names, limit=None, refs=None): - """Resolve every hash value in the PSIN containers under `src`. Returns the summary and the per-field table.""" - real = dictionaries(names) - control = dictionaries(names, CONTROL_SALT) - total = collections.Counter(names=len(names)) - fields = collections.defaultdict(collections.Counter) - distinct = collections.defaultdict(set) - seen = 0 - for file_name, blob in psin_index.files_in(src): - if blob[:4] != psin_index.MAGIC: - continue - total["PSIN files"] += 1 - seen += 1 - try: - found = hash_values(blob) - except ValueError: - total["skipped"] += 1 - found = None - if found is not None: - total["containers"] += 1 - hit = False - for s, field, t, v in found: - size = "u64" if t in HASH64 else "u32" - which = 1 if size == "u64" else 0 - row = fields[(s, field, t)] - row["values"] += 1 - total[f"{size} values"] += 1 - if v == 0: - row["zero"] += 1 - continue - distinct[(s, field, t)].add(v) - name = real[which].get(v) - if name is not None: - hit = True - row["resolved"] += 1 - total[f"{size} resolved"] += 1 - if refs: - refs.write(f"{file_name}\t{s:08x}\t{field:08x}\t{t:02x}\t{v:x}\t{name}\n") - if v in control[which]: - row["control"] += 1 - total[f"{size} control"] += 1 - total["containers with a resolved name"] += hit - if limit and seen >= limit: - break - table = [] - for key, row in fields.items(): - s, field, t = key - table.append({"struct": f"{s:08x}", "field": f"{field:08x}", "type": f"{t:02x}", - "values": row["values"], "zero": row["zero"], "distinct": len(distinct[key]), - "resolved": row["resolved"], "control": row["control"]}) - table.sort(key=lambda r: (-r["resolved"], r["struct"], r["field"])) - total["fields"] = len(table) - total["fields with a resolved value"] = sum(1 for r in table if r["resolved"]) - return dict(sorted(total.items())), table - - -def fields_count(text): - n = int(text) - if n < 0: - raise argparse.ArgumentTypeError("must be 0 or more") - return n - - -def main(): - ap = argparse.ArgumentParser(description="Resolve PSIN name-hash fields against a local name list.") - ap.add_argument("src", help="PSIN file or directory of carved .bin streams") - ap.add_argument("--names", action="append", required=True, - help="rpf9_names.py JSON or a text file with one name per line (repeatable)") - ap.add_argument("--json", action="store_true", help="print the summary and the whole field table as JSON") - ap.add_argument("--fields", type=fields_count, default=10, - help="fields to list in the text output (0 for none)") - ap.add_argument("--refs", help="write every resolved value as TSV (local only: it holds game names)") - ap.add_argument("--limit", type=psin_index.count, help="stop after this many PSIN files") - a = ap.parse_args() - inputs = [a.src, *a.names] - for path in inputs: - if not os.path.exists(path): - print(f"ERROR: {path}: no such file or folder", file=sys.stderr) - return 2 - try: - if a.refs: - if os.path.isdir(a.refs): - ap.error("--refs must be a file path, not a directory") - if any(same_report_path(path, a.refs) for path in inputs): - ap.error("--refs must not overwrite an input") - if os.path.isdir(a.src): - src_real = os.path.realpath(a.src) - refs_real = os.path.realpath(a.refs) - try: - inside_src = os.path.commonpath([src_real, refs_real]) == src_real - except ValueError: - inside_src = False - if inside_src: - ap.error("--refs must not overwrite an input") - carve_inputs = [os.path.join(a.src, "index.json"), *psin_index.input_paths(a.src)] - if any(same_report_path(path, a.refs) for path in carve_inputs): - ap.error("--refs must not overwrite an input") - names = load_names(a.names) - if a.refs: - with open(a.refs, "w", encoding="utf-8", newline="\n") as refs: - refs.write("file\tstruct\tfield\ttype\tvalue\tname\n") - summary, table = scan(a.src, names, a.limit, refs) - else: - summary, table = scan(a.src, names, a.limit) - except (OSError, ValueError) as e: - print(f"ERROR: {e}", file=sys.stderr) - return 2 - if a.json: - json.dump({"summary": summary, "fields": table}, sys.stdout, indent=1) - sys.stdout.write("\n") - return 0 - for k, v in summary.items(): - print(f"{k:36} {v:,}") - if table and a.fields: - print(f"\n{'struct':8} {'field':8} {'type':4} {'values':>9} {'distinct':>9} {'resolved':>9} {'control':>8}") - for r in table[:a.fields]: - print(f"{r['struct']} {r['field']} {r['type']:4} {r['values']:9,} {r['distinct']:9,} " - f"{r['resolved']:9,} {r['control']:8,}") - return 0 - - -if __name__ == "__main__": - try: # a redirected stdout is strict ANSI code page under -I; write '?' for what it cannot encode - sys.stdout.reconfigure(errors="replace") - except (AttributeError, ValueError, OSError): - pass - sys.exit(main()) diff --git a/tools/psin_psch.py b/tools/psin_psch.py deleted file mode 100644 index 0c38705f1..000000000 --- a/tools/psin_psch.py +++ /dev/null @@ -1,524 +0,0 @@ -"""Decode the PSO-style PMAP/PSCH/PSIG/STNS PSIN containers (docs/psin.md). - -57 complete PSIN streams (54 in data.rpf, 2 in packs.rpf, 1 in anim.rpf) use the -PSO-style `PMAP`/`PSCH`/`PSIG`/`STNS` (plus optional `STFN`/`STDN`) section chain -instead of `LSCH`/`LENM`/`LSNS`/`LRSC`: - - +0x00.."PSIN", +0x04 u32be first_section, +0x08.."pppppppp", data blocks at +0x10 - PMAP: u32be root_block_id, u16be flags, u16be 0, u16be block_count, "pppppp", - then `block_count` x 16B big-endian rows {u32 name_hash, u32 offset, u32 0, u32 length} - PSCH: u32be entry_count, `entry_count` x (u32 name_hash, u32 section_offset), - followed by struct entries (kind=0, 12B hdr + 12B members) and enum entries (kind=1, 4B hdr + 16B values) - PSIG: `entry_count` x u32be layout signatures - STNS: u32le block_count, `block_count` x (u32le kind, u32le bytes), 16B-aligned blocks (+ 0/4 zero pad) - -Usage: - python -I tools/psin_psch.py [--carve-dir DIR] [--json FILE] - -Prints and writes aggregate counts, schema validation checks and type histograms -only; no game payloads or decoded values leave local runs. Standard library only. -""" -from __future__ import annotations - -import argparse -from collections import Counter -import json -import os -import struct -import sys - -# -I keeps the script directory off sys.path, so add it explicitly before importing sibling helpers. -TOOLS = os.path.dirname(os.path.abspath(__file__)) -if TOOLS not in sys.path: - sys.path.insert(0, TOOLS) - -import gamedata_index as gi # noqa: E402 -import gamedata_maps as gm # noqa: E402 -import psin_index # noqa: E402 -from report_paths import same_report_path # noqa: E402 - -ARRAY_ELEMENT = psin_index.ARRAY_ELEMENT -PSCH_TYPE_STRUCT = 0x0C -PSCH_TYPE_ARRAY = 0x0D -PSCH_TYPE_ENUM = 0x0E -PSCH_TYPE_MAP = 0x10 -PMAP_FILL = b"pppppp" -HEADER_FILL = b"pppppppp" - - -def is_psch_container(blob: bytes) -> bool: - """True when `blob` is a PSIN container carrying PMAP or PSCH sections.""" - rec = psin_index.parse(blob) - if rec is None or not rec["complete"]: - return False - tags = {s["tag"] for s in rec["sections"]} - return "PMAP" in tags or "PSCH" in tags - - -def decode_pmap(payload: bytes, blob: bytes, first_section: int) -> dict: - """Decode the PMAP block table (big-endian).""" - if len(payload) < 16: - raise ValueError("PMAP payload shorter than 16-byte header") - if len(blob) < 16 or blob[8:16] != HEADER_FILL: - raise ValueError("PMAP container lacks 8-byte 'pppppppp' header fill at +0x08") - root_id, flags, z0, block_count = struct.unpack_from(">IHHH", payload, 0) - if payload[10:16] != PMAP_FILL: - raise ValueError("PMAP header lacks 6-byte 'pppppp' fill at +10") - if len(payload) != 16 + block_count * 16: - raise ValueError(f"PMAP size {len(payload)} != 16 + {block_count} * 16") - if block_count == 0 or not (1 <= root_id <= block_count): - raise ValueError(f"PMAP root_block_id {root_id} outside 1..{block_count}") - - blocks = [] - nonzero_row_reserved = 0 - for idx in range(block_count): - name_hash, offset, reserved, length = struct.unpack_from(">4I", payload, 16 + idx * 16) - if reserved != 0: - nonzero_row_reserved += 1 - if offset < 16 or offset + length > first_section: - raise ValueError(f"PMAP block {idx + 1} ({offset:#x}+{length}) outside data area 0x10..{first_section:#x}") - blocks.append({ - "id": idx + 1, - "hash": name_hash, - "offset": offset, - "reserved": reserved, - "length": length, - }) - - if blocks[0]["offset"] != 16: - raise ValueError(f"first PMAP block starts at {blocks[0]['offset']:#x}, expected 0x10") - exact_end = (blocks[-1]["offset"] + blocks[-1]["length"]) == first_section - if not exact_end and ((blocks[-1]["offset"] + blocks[-1]["length"] + 15) & ~15) != first_section: - raise ValueError("last PMAP block does not end at first_section") - - return { - "root_block_id": root_id, - "flags": flags, - "reserved_zero": z0 == 0 and nonzero_row_reserved == 0, - "blocks": blocks, - "exact_end": exact_end, - } - - -def decode_psch(section_bytes: bytes) -> dict: - """Decode a complete PSCH section (8-byte PSCH header included).""" - if len(section_bytes) < 12 or section_bytes[:4] != b"PSCH": - raise ValueError("not a PSCH section") - entry_count = struct.unpack_from(">I", section_bytes, 8)[0] - dir_end = 12 + entry_count * 8 - if dir_end > len(section_bytes): - raise ValueError(f"PSCH directory ({entry_count} entries) runs past section end") - - directory = [struct.unpack_from(">2I", section_bytes, 12 + i * 8) for i in range(entry_count)] - offsets = [d[1] for d in directory] + [len(section_bytes)] - if entry_count and offsets[0] != dir_end: - raise ValueError(f"first PSCH entry at {offsets[0]} != directory end {dir_end}") - if any(offsets[i] >= offsets[i + 1] or offsets[i + 1] > len(section_bytes) for i in range(entry_count)): - raise ValueError("PSCH directory offsets are not strictly ascending inside the section") - - structs = [] - enums = [] - for i, (name_hash, _off) in enumerate(directory): - eb = section_bytes[offsets[i]:offsets[i + 1]] - if len(eb) < 4: - raise ValueError(f"PSCH entry {i} shorter than 4 bytes") - kind, flags, count = struct.unpack_from(">BBH", eb, 0) - if kind == 0: - if len(eb) != 12 + count * 12: - raise ValueError(f"PSCH struct {name_hash:08x} size {len(eb)} != 12 + {count} * 12") - byte_size, reserved = struct.unpack_from(">2I", eb, 4) - members = [] - for j in range(count): - m_hash, m_type, m_sub, m_off, m_ref = struct.unpack_from(">IBBHI", eb, 12 + j * 12) - members.append({ - "hash": m_hash, - "type": m_type, - "sub": m_sub, - "offset": m_off, - "ref": m_ref, - }) - structs.append({ - "hash": name_hash, - "flags": flags, - "size": byte_size, - "reserved": reserved, - "members": members, - }) - elif kind == 1: - if len(eb) != 4 + count * 16: - raise ValueError(f"PSCH enum {name_hash:08x} size {len(eb)} != 4 + {count} * 16") - values = [] - for j in range(count): - v_hash, v_zero, v_val = struct.unpack_from(">IIq", eb, 4 + j * 16) - values.append({"hash": v_hash, "reserved": v_zero, "value": v_val}) - enums.append({"hash": name_hash, "flags": flags, "values": values}) - else: - raise ValueError(f"unknown PSCH entry kind {kind} for {name_hash:08x}") - - return {"entry_count": entry_count, "directory": directory, "structs": structs, "enums": enums} - - -def decode_psig(payload: bytes, entry_count: int) -> list[int]: - """Decode PSIG big-endian per-entry layout signatures.""" - if len(payload) != 4 * entry_count: - raise ValueError(f"PSIG payload {len(payload)} != 4 * {entry_count}") - return list(struct.unpack_from(f">{entry_count}I", payload, 0)) if entry_count else [] - - -def decode_stns(payload: bytes) -> dict: - """Decode STNS little-endian 16-byte record block table.""" - if len(payload) < 4: - raise ValueError("STNS shorter than 4-byte block count") - count = struct.unpack_from(" len(payload): - raise ValueError(f"STNS table ({count} blocks) runs past section end") - blocks = [] - data_bytes = 0 - for i in range(count): - kind, size = struct.unpack_from("<2I", payload, 4 + i * 8) - if size % 16 != 0: - raise ValueError(f"STNS block {i} (kind {kind:#x}) size {size} is not a multiple of 16") - blocks.append({"kind": kind, "bytes": size, "records": size // 16}) - data_bytes += size - expected_len = ((table_end + data_bytes) + 15) & ~15 - tail_len = len(payload) - (table_end + data_bytes) - if len(payload) != expected_len or any(b != 0 for b in payload[table_end + data_bytes:]): - raise ValueError(f"STNS length/padding invalid (len={len(payload)}, expected={expected_len})") - return { - "blocks": blocks, - "records": data_bytes // 16, - "tail_pad": tail_len, - "raw_blocks": payload[table_end:table_end + data_bytes], - } - - -def check_psch_schema(pmap: dict, psch: dict) -> list[str]: - """Validate PMAP block sizes/root and PSCH member bounds and local descriptors.""" - errors = [] - struct_by_hash = {s["hash"]: s for s in psch["structs"]} - enum_hashes = {e["hash"] for e in psch["enums"]} - - root_block = pmap["blocks"][pmap["root_block_id"] - 1] - if root_block["hash"] not in struct_by_hash: - errors.append(f"PMAP root block hash {root_block['hash']:08x} missing from PSCH") - - for blk in pmap["blocks"]: - st = struct_by_hash.get(blk["hash"]) - if st is not None and st["size"] > 0 and blk["length"] % st["size"] != 0: - errors.append(f"PMAP block {blk['id']} length {blk['length']} not divisible by struct size {st['size']}") - - for s in psch["structs"]: - members = s["members"] - for idx, m in enumerate(members): - if m["hash"] != ARRAY_ELEMENT and m["offset"] >= s["size"]: - errors.append(f"struct {s['hash']:08x} member {idx} offset {m['offset']} >= size {s['size']}") - if m["type"] == PSCH_TYPE_ARRAY: - elem_idx = m["ref"] & 0xFFFF - if elem_idx >= len(members) or members[elem_idx]["hash"] != ARRAY_ELEMENT: - errors.append(f"struct {s['hash']:08x} array member {idx} bad descriptor {elem_idx}") - elif m["type"] == PSCH_TYPE_ENUM and m["ref"] not in enum_hashes: - errors.append(f"struct {s['hash']:08x} enum member {idx} missing enum {m['ref']:08x}") - elif m["type"] == PSCH_TYPE_MAP: - k_idx = m["ref"] & 0xFFFF - v_idx = m["ref"] >> 16 - if k_idx >= len(members) or members[k_idx]["hash"] != ARRAY_ELEMENT: - errors.append(f"struct {s['hash']:08x} map member {idx} bad key descriptor {k_idx}") - if v_idx >= len(members) or members[v_idx]["hash"] != ARRAY_ELEMENT: - errors.append(f"struct {s['hash']:08x} map member {idx} bad value descriptor {v_idx}") - - return errors - - -def parse_psch_container(blob: bytes) -> dict: - """Parse and cross-check one PMAP/PSCH/PSIG/STNS PSIN container.""" - rec = psin_index.parse(blob) - if rec is None: - raise ValueError("not a PSIN container") - if not rec["complete"]: - raise ValueError(f"incomplete PSIN container: {rec['error']}") - - secs = {s["tag"]: s for s in rec["sections"]} - for required in ("PMAP", "PSCH", "PSIG", "STNS"): - if required not in secs: - raise ValueError(f"missing {required} section") - - def section_payload(tag: str) -> bytes: - s = secs[tag] - return blob[s["offset"] + 8:s["offset"] + s["size"]] - - pmap = decode_pmap(section_payload("PMAP"), blob, rec["first_section"]) - psch_sec = secs["PSCH"] - psch = decode_psch(blob[psch_sec["offset"]:psch_sec["offset"] + psch_sec["size"]]) - psig = decode_psig(section_payload("PSIG"), psch["entry_count"]) - stns = decode_stns(section_payload("STNS")) - - errors = check_psch_schema(pmap, psch) - - stdn_match = None - if "STDN" in secs: - stdn_pay = section_payload("STDN") - stdn_match = stns["raw_blocks"].startswith(stdn_pay) - if not stdn_match: - errors.append("STDN payload does not match STNS block data prefix") - - stfn_bytes = len(section_payload("STFN")) if "STFN" in secs else None - struct_map = {s["hash"]: s for s in psch["structs"]} - anon_kinds = Counter() - struct_blocks = 0 - for blk in pmap["blocks"]: - if blk["hash"] in struct_map: - struct_blocks += 1 - else: - anon_kinds[f"{blk['hash']:#x}"] += 1 - - mtypes = Counter() - for s in psch["structs"]: - for m in s["members"]: - mtypes[f"{m['type']:#04x}"] += 1 - - return { - "valid": len(errors) == 0, - "errors": errors, - "size": len(blob), - "first_section": rec["first_section"], - "section_tags": [s["tag"] for s in rec["sections"]], - "pmap_blocks": len(pmap["blocks"]), - "pmap_struct_blocks": struct_blocks, - "pmap_anon_kinds": dict(sorted(anon_kinds.items())), - "pmap_exact_end": pmap["exact_end"], - "psch_entries": psch["entry_count"], - "structs": len(psch["structs"]), - "members": sum(len(s["members"]) for s in psch["structs"]), - "enums": len(psch["enums"]), - "enum_values": sum(len(e["values"]) for e in psch["enums"]), - "member_type_counts": dict(sorted(mtypes.items())), - "psig_count": len(psig), - "stns_blocks": len(stns["blocks"]), - "stns_records": stns["records"], - "stns_tail_pad": stns["tail_pad"], - "stns_kinds": [f"{b['kind']:#x}" for b in stns["blocks"]], - "stdn_match": stdn_match, - "stfn_bytes": stfn_bytes, - "_struct_hashes": {s["hash"] for s in psch["structs"]}, - "_enum_hashes": {e["hash"] for e in psch["enums"]}, - "_member_hashes": {m["hash"] for s in psch["structs"] for m in s["members"]}, - "_enum_value_hashes": {v["hash"] for e in psch["enums"] for v in e["values"]}, - "_signatures": set(psig), - "_raw_structs": psch["structs"], - } - - -def scan_target(target: str, carve_dir: str | None = None) -> dict: - """Collect and summarize all PMAP/PSCH containers in a file, carve folder or .rpf archive.""" - if os.path.isfile(target): - with open(target, "rb") as f: - head = f.read(16) - if head[:4] == b"9FPR": - source = gi.ArchiveSource(target, carve_dir) - try: - rows = source.rows - blobs = [] - for r in rows: - if not r.get("head", "").startswith("5053494e"): - continue - data = source.read(r) - if is_psch_container(data): - blobs.append((f"{r['off']:#x}", data)) - finally: - source.close() - else: - with open(target, "rb") as f: - data = f.read() - if not is_psch_container(data): - raise ValueError(f"{target}: not a PMAP/PSCH PSIN container") - blobs = [(os.path.basename(target), data)] - elif os.path.isdir(target): - if os.path.isfile(os.path.join(target, "index.json")): - source = gi.DirectorySource(target) - blobs = [] - for r in source.rows: - if not r.get("head", "").startswith("5053494e"): - continue - data = source.read(r) - if is_psch_container(data): - blobs.append((f"{r['off']:#x}", data)) - else: - blobs = [] - for name in sorted(os.listdir(target)): - if not name.lower().endswith(".bin"): - continue - full = os.path.join(target, name) - if not os.path.isfile(full): - continue - with open(full, "rb") as f: - data = f.read() - if is_psch_container(data): - blobs.append((name, data)) - else: - raise FileNotFoundError(target) - - if not blobs: - raise ValueError(f"{target}: no PMAP/PSCH PSIN containers found") - - parsed = [] - all_structs: set[int] = set() - all_enums: set[int] = set() - all_members: set[int] = set() - all_evals: set[int] = set() - all_sigs: set[int] = set() - mtype_totals: Counter[str] = Counter() - anon_totals: Counter[str] = Counter() - chain_totals: Counter[str] = Counter() - stns_kind_totals: Counter[str] = Counter() - - for label, blob in blobs: - info = parse_psch_container(blob) - info["label"] = label - parsed.append(info) - all_structs.update(info["_struct_hashes"]) - all_enums.update(info["_enum_hashes"]) - all_members.update(info["_member_hashes"]) - all_evals.update(info["_enum_value_hashes"]) - all_sigs.update(info["_signatures"]) - mtype_totals.update(info["member_type_counts"]) - anon_totals.update(info["pmap_anon_kinds"]) - chain_totals["+".join(info["section_tags"])] += 1 - for k in info["stns_kinds"]: - stns_kind_totals[k] += 1 - - # Measure struct reference resolution locally vs across containers in the scan. - struct_refs_local = struct_refs_cross = struct_refs_unresolved = 0 - for info in parsed: - local_s = info["_struct_hashes"] - for s in info["_raw_structs"]: - for m in s["members"]: - if m["type"] == PSCH_TYPE_STRUCT and m["ref"] != 0: - if m["ref"] in local_s: - struct_refs_local += 1 - elif m["ref"] in all_structs: - struct_refs_cross += 1 - else: - struct_refs_unresolved += 1 - - valid_count = sum(1 for p in parsed if p["valid"]) - return { - "valid": valid_count == len(parsed), - "containers": len(parsed), - "valid_containers": valid_count, - "section_chains": dict(sorted(chain_totals.items())), - "pmap_blocks": sum(p["pmap_blocks"] for p in parsed), - "pmap_struct_blocks": sum(p["pmap_struct_blocks"] for p in parsed), - "pmap_anon_kinds": dict(sorted(anon_totals.items())), - "pmap_exact_end": sum(1 for p in parsed if p["pmap_exact_end"]), - "structs": sum(p["structs"] for p in parsed), - "distinct_structs": len(all_structs), - "members": sum(p["members"] for p in parsed), - "distinct_members": len(all_members), - "enums": sum(p["enums"] for p in parsed), - "distinct_enums": len(all_enums), - "enum_values": sum(p["enum_values"] for p in parsed), - "distinct_enum_values": len(all_evals), - "distinct_signatures": len(all_sigs), - "member_type_counts": dict(sorted(mtype_totals.items())), - "struct_refs": { - "local": struct_refs_local, - "cross_file": struct_refs_cross, - "unresolved": struct_refs_unresolved, - }, - "stns_blocks": sum(p["stns_blocks"] for p in parsed), - "stns_records": sum(p["stns_records"] for p in parsed), - "stns_kinds": dict(sorted(stns_kind_totals.items())), - "stdn_containers": sum(1 for p in parsed if p["stdn_match"] is not None), - "stdn_matches": sum(1 for p in parsed if p["stdn_match"] is True), - "stfn_containers": sum(1 for p in parsed if p["stfn_bytes"] is not None), - } - - -def check_report_path(out_path: str, target: str, carve_dir: str | None = None, - rows: list[dict] | None = None) -> None: - """Refuse a --json destination that is a directory or collides with any input file.""" - if os.path.isdir(out_path): - raise ValueError(f"--json is a directory: {out_path}") - if carve_dir: - idx = os.path.join(carve_dir, "index.json") - if same_report_path(out_path, carve_dir) or same_report_path(out_path, idx): - raise ValueError(f"--json would overwrite the input {carve_dir}") - if os.path.isdir(target): - if os.path.isfile(os.path.join(target, "index.json")): - gm.check_report_path(out_path, target, rows=rows) - elif same_report_path(out_path, target): - raise ValueError(f"--json would overwrite the input {target}") - else: - for name in os.listdir(target): - if name.lower().endswith(".bin") and same_report_path(out_path, os.path.join(target, name)): - raise ValueError(f"--json would overwrite the input {name}") - elif same_report_path(out_path, target): - raise ValueError(f"--json would overwrite the input {target}") - - -def main(argv=None) -> int: - ap = argparse.ArgumentParser(description=__doc__.splitlines()[0]) - ap.add_argument("target", help="PSIN file, carve folder, or .rpf archive") - ap.add_argument("--carve-dir", help="existing rpf9_carve.py index.json folder for an .rpf archive") - ap.add_argument("--json", help="write aggregate decoded counts to this JSON file") - a = ap.parse_args(argv) - - if not os.path.exists(a.target): - print(f"ERROR: cannot read {a.target}: no such file or folder", file=sys.stderr) - return 2 - try: - if a.json: - rows = ( - gm._read_index_rows(a.target) - if os.path.isdir(a.target) and os.path.isfile(os.path.join(a.target, "index.json")) - else None - ) - check_report_path(a.json, a.target, a.carve_dir, rows=rows) - summary = scan_target(a.target, carve_dir=a.carve_dir) - except (OSError, ValueError, KeyError, TypeError, struct.error, RuntimeError) as e: - print("error:", e, file=sys.stderr) - return 2 if isinstance(e, ValueError) and "--json" in str(e) else 1 - - print( - f'PSCH containers: {summary["valid_containers"]}/{summary["containers"]} valid ' - f'(pmap blocks={summary["pmap_blocks"]}: {summary["pmap_struct_blocks"]} struct, ' - f'exact_end={summary["pmap_exact_end"]}/{summary["containers"]})' - ) - print( - f' schema: {summary["structs"]} structs ({summary["distinct_structs"]} distinct), ' - f'{summary["members"]} members ({summary["distinct_members"]} distinct), ' - f'{summary["enums"]} enums ({summary["distinct_enums"]} distinct), ' - f'{summary["enum_values"]} values ({summary["distinct_enum_values"]} distinct), ' - f'{summary["distinct_signatures"]} signatures' - ) - print( - f' refs: local={summary["struct_refs"]["local"]}, ' - f'cross={summary["struct_refs"]["cross_file"]}, ' - f'unresolved={summary["struct_refs"]["unresolved"]}' - ) - print( - f' STNS: {summary["stns_blocks"]} blocks, {summary["stns_records"]} records ' - f'(STDN match={summary["stdn_matches"]}/{summary["stdn_containers"]}, ' - f'STFN={summary["stfn_containers"]})' - ) - - if a.json: - try: - gm._make_parent(a.json) - with open(a.json, "w", encoding="utf-8", newline="\n") as f: - json.dump(summary, f, indent=1) - except OSError as e: - print(f"error: cannot write {a.json}: {e.strerror or e}", file=sys.stderr) - return 1 - print("wrote", a.json) - - return 0 if summary["valid"] else 1 - - -if __name__ == "__main__": - try: # a redirected stdout is strict ANSI code page under -I; write '?' for what it cannot encode - sys.stdout.reconfigure(errors="replace") - except (AttributeError, ValueError, OSError): - pass - sys.exit(main()) diff --git a/tools/psocache_extract.py b/tools/psocache_extract.py deleted file mode 100644 index 357f0953e..000000000 --- a/tools/psocache_extract.py +++ /dev/null @@ -1,316 +0,0 @@ -"""Carve the PSO/shader cache out of an RPF9 archive, reproducibly and without the encrypted TOC. - -The cache starts with the magic ``PS\\0\\x09``. In the measured package it is one resource stored as a chain of -zlib streams in an archive's data area: 4,205 adjacent streams, 4,204 of 64 KiB and a 27,436-byte last one, -31,437 bytes of zero padding between them, 275,540,780 inflated bytes in total. It is the last resource in its -archive, but that is not assumed here. - -How the search stays bounded and deterministic: - -1. The archive header gives the data start (`u32` at +4). From there the tool walks the stream table in archive - order, the same walk `rpf9_carve.py` uses. A stream starts at a zlib header (`78 01/5e/9c/da`); anything else - between streams is zero padding or unread bytes. Every stream is inflated in 1 MiB pieces so the walk learns - where it ends; only the first 4 inflated bytes are kept for the test. The output is discarded otherwise. -2. The first stream whose inflated bytes start with ``PS\\0\\x09`` wins and the scan stops. If none is found - before ``--budget`` compressed bytes (default 8 GiB) or ``--max-streams`` streams (default 200,000), or at the - end of the archive, the tool exits 2 without writing anything. -3. The header of that stream declares the total: ``0x80 + graphics*0x70 + compute*0x18 + meta_index*8 + - shader_index*8 + meta_size + code_size``. The tool appends following streams after at most 1 MiB of zero - padding until exactly that many inflated bytes exist. A stream that would overshoot, a missing stream, or a - missing header is reported with the byte counts, not guessed. -4. The file is written to ``--out``, which must be inside the system temporary directory, and then checked with - ``psocache_inspect.inspect``. The exit code is 0 only when that model holds. - -Usage: - python -I psocache_extract.py [--budget BYTES] [--max-streams N] [--quiet] - -Exit code: 0 extracted and the model holds, 1 extracted but the model disagrees, 2 not found, unreadable input, -a source budget exhausted, or an output path outside the temporary directory. The tool prints counts, offsets -and sizes only, never an archive name or a path from the package. -""" - -import argparse -import mmap -import os -import re -import struct -import sys -import tempfile -import zlib - -sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) - -import psocache_inspect # noqa: E402 - -ZHDR = re.compile(rb"\x78[\x01\x5e\x9c\xda]") -MAGIC = psocache_inspect.MAGIC -HEADER_SIZE = psocache_inspect.HEADER_SIZE -GRAPHICS_STRIDE = psocache_inspect.GRAPHICS_STRIDE -COMPUTE_STRIDE = psocache_inspect.COMPUTE_STRIDE -INDEX_STRIDE = psocache_inspect.INDEX_STRIDE -COUNT_OFFS = psocache_inspect.COUNT_OFFS -SIZE_OFFS = psocache_inspect.SIZE_OFFS -MAX_GAP = 1 << 20 # zero padding allowed between two streams of one resource -DEFAULT_BUDGET = 1 << 33 # compressed bytes examined before the search gives up -DEFAULT_MAX_STREAMS = 200000 - - -class NotFound(Exception): - """The cache was not found inside the search budget.""" - - -def inflate(m, start, end, keep_all=False): - """Inflate one zlib stream at ``start``. - - Returns ``(used, head)`` where ``used`` is the first byte after the stream (the decompressor may have read - past its end) and ``head`` is the first 4 inflated bytes, or ``(None, None)`` when it does not decode. - With ``keep_all`` the inflated bytes are returned in place of the 4-byte head; memory then grows with the - stream, which is why the search path does not use it. - """ - d = zlib.decompressobj() - head = bytearray() - out = bytearray() if keep_all else None - p = start - try: - while p < end and not d.eof: - piece = m[p : min(p + (1 << 20), end)] - chunk = d.decompress(piece) - p += len(piece) - if keep_all: - out += chunk - elif len(head) < len(MAGIC): - head += chunk[: len(MAGIC) - len(head)] - except zlib.error: - return None, None - if not d.eof: - return None, None - used = p - len(d.unused_data) - return used, bytes(out if keep_all else head) - - -def declared_total(header): - """The total the cache header declares, or None when the header is too short.""" - if len(header) < HEADER_SIZE: - return None - counts = tuple(struct.unpack_from(" total: - raise ValueError( - "first stream is %d bytes, more than the declared %d" % (len(data), total) - ) - pos = used - while len(data) < total: - gap = 0 - while pos < size and m[pos] == 0 and gap < MAX_GAP: - pos += 1 - gap += 1 - if gap >= MAX_GAP or not ZHDR.match(m, pos): - raise ValueError( - "only %d of %d declared bytes are in contiguous streams" - % (len(data), total) - ) - used, chunk = inflate(m, pos, size, keep_all=True) - if used is None: - raise ValueError("stream after %d bytes does not inflate" % len(data)) - if len(data) + len(chunk) > total: - raise ValueError( - "stream after %d bytes adds %d, past the declared %d" - % (len(data), len(chunk), total) - ) - data += chunk - pos = used - return bytes(data) - - -def inside_tempdir(path): - root = os.path.realpath(tempfile.gettempdir()) - target = os.path.realpath(os.path.abspath(path)) - return target.startswith(root + os.sep) - - -def archives(source): - if os.path.isdir(source): - return [ - os.path.join(source, name) - for name in sorted(os.listdir(source)) - if os.path.isfile(os.path.join(source, name)) - ] - return [source] - - -def extract( - source, out, budget=DEFAULT_BUDGET, max_streams=DEFAULT_MAX_STREAMS, quiet=False -): - """Find, carve and validate the cache. Returns ``(archive_index, report, search)`` or raises NotFound.""" - if not inside_tempdir(out): - raise ValueError("--out must be a file inside the temporary directory") - paths = archives(source) - left = budget - spent = 0 - streams = 0 - for index, path in enumerate(paths, 1): - if left <= 0: - break - try: - fh = open(path, "rb") - except OSError as e: - raise ValueError( - "archive #%d cannot be opened: %s" % (index, e.strerror or "I/O error") - ) - with fh: - size = os.fstat(fh.fileno()).st_size - if size < 8: - continue - with mmap.mmap(fh.fileno(), 0, access=mmap.ACCESS_READ) as m: - if bytes(m[:4]) not in (b"RPF9", b"9FPR"): - continue - data_start = struct.unpack_from(" [--json] [--quiet] - -Exit code: 0 when every region fits and the regions add up to the file size, 1 when the file disagrees with the -model, 2 when it cannot be read or does not start with the magic. -""" - -import argparse -import collections -import json -import mmap -import os -import struct -import sys - -MAGIC = b"PS\x00\x09" -HEADER_SIZE = 0x80 -GRAPHICS_STRIDE = 0x70 -COMPUTE_STRIDE = 0x18 -INDEX_STRIDE = 8 -CHUNK_SIZE = 32 -CHUNK_TYPES = (0x41, 0x42, 0x43) -ENTRY_HEADER_MAX = 0x40 # largest per-entry meta header the model allows -S_END_PGM = b"\x00\x00\x81\xbf" # s_endpgm, 0xBF810000 little-endian -S_CODE_END = b"\x00\x00\x9f\xbf" # s_code_end, 0xBF9F0000 little-endian -HASH_OFF = 0x48 -STRING_OFFS = (0x04, 0x24) -COUNT_OFFS = (0x50, 0x54, 0x58, 0x5C) -SIZE_OFFS = (0x60, 0x64) - - -def u32(m, off): - return struct.unpack_from("> 16, (w[5] >> 8) & 0xFF, w[5] & 0xFF) - ) - elif w[0] == 0x42: - lines.append( - " 0x42 slot=0x%06x space=%d middle=%d width=%d key=0x%x w4=0x%x" - % ( - w[2], - (w[2] >> 16) & 0xFF, - (w[2] >> 8) & 0xFF, - w[2] & 0xFF, - w[3], - w[4], - ) - ) - elif w[0] == 0x43: - lines.append(" 0x43 16-byte value, not printed") - else: - lines.append(" 0x%x unexpected chunk" % w[0]) - return lines - - -def decode_meta(m, base, spans, limit=None): - """Aggregate the 0x41/0x42 shape over chunk-list records. - - ``spans`` is a list of ``(offset, size)`` meta entries that parse as chunk lists. Everything here is measured - shape, not a decoder: tags, byte fields and counts are reported as found. ``limit`` bounds the records read. - """ - records = ordered = one_hash = exact = with_extras = 0 - tags = {} - slot_space = collections.Counter() - slot_middle = collections.Counter() - slot_width = collections.Counter() - slot_w4 = collections.Counter() - cross = collections.Counter() - extras = collections.Counter() - extras_per_record = collections.Counter() - for start, size in spans: - if limit is not None and records >= limit: - break - chunks = entry_chunks(m, base, start, size) - if chunks is None: - continue - records += 1 - kinds = [w[0] for w in chunks] - if kinds == sorted(kinds) and kinds.count(0x43) == 1 and kinds[-1] == 0x43: - ordered += 1 - if kinds.count(0x43) == 1: - one_hash += 1 - for w in chunks: - if w[0] == 0x41: - entry = tags.setdefault( - w[1], - { - "count": 0, - "offset_min": w[2], - "offset_max": w[2], - "offsets": set(), - "aligned8": True, - "sizes": collections.Counter(), - "a": collections.Counter(), - "b": collections.Counter(), - "counts": set(), - }, - ) - entry["count"] += 1 - entry["offset_min"] = min(entry["offset_min"], w[2]) - entry["offset_max"] = max(entry["offset_max"], w[2]) - entry["offsets"].add(w[2]) - entry["aligned8"] = entry["aligned8"] and w[2] % 8 == 0 - entry["sizes"][w[5] & 0xFF] += 1 - entry["a"][w[5] >> 16] += 1 - entry["b"][(w[5] >> 8) & 0xFF] += 1 - entry["counts"].add(w[4]) - elif w[0] == 0x42: - slot_space[(w[2] >> 16) & 0xFF] += 1 - slot_middle[(w[2] >> 8) & 0xFF] += 1 - slot_width[w[2] & 0xFF] += 1 - slot_w4[w[4]] += 1 - descriptor_41 = [ - w for w in chunks if w[0] == 0x41 and w[1] in (0x300, 0x302, 0x303) - ] - slots_42 = [w for w in chunks if w[0] == 0x42] - if len(descriptor_41) == len(slots_42): - exact += 1 - for w, slot in zip(descriptor_41, slots_42): - cross[(w[1], (slot[2] >> 8) & 0xFF)] += 1 - elif len(slots_42) > len(descriptor_41): - with_extras += 1 - extra = len(slots_42) - len(descriptor_41) - extras_per_record[extra] += 1 - for slot in slots_42[len(descriptor_41) :]: - extras[ - ((slot[2] >> 16) & 0xFF, (slot[2] >> 8) & 0xFF, slot[2] & 0xFF) - ] += 1 - return { - "records": records, - "ordered": ordered, - "one_hash": one_hash, - "exact_pairs": exact, - "records_with_extras": with_extras, - "extras_per_record": {str(k): v for k, v in sorted(extras_per_record.items())}, - "extras": { - "space=%d middle=%d width=%d" % k: v for k, v in extras.most_common(8) - }, - "tags": { - "0x%x" % tag: { - "count": entry["count"], - "offset_min": entry["offset_min"], - "offset_max": entry["offset_max"], - "offset_values": len(entry["offsets"]), - "aligned8": entry["aligned8"], - "sizes": {str(k): v for k, v in entry["sizes"].most_common()}, - "a": {("0x%x" % k): v for k, v in entry["a"].most_common(6)}, - "b": {("0x%x" % k): v for k, v in entry["b"].most_common(8)}, - "count_values": len(entry["counts"]), - } - for tag, entry in sorted(tags.items()) - }, - "slot_space": {str(k): v for k, v in sorted(slot_space.items())}, - "slot_middle": {str(k): v for k, v in sorted(slot_middle.items())}, - "slot_width": {str(k): v for k, v in sorted(slot_width.items())}, - "slot_w4": {str(k): v for k, v in sorted(slot_w4.items())}, - "tag_middle": { - "0x%x/%d" % k: v - for k, v in sorted(cross.items(), key=lambda kv: (kv[0][0], kv[0][1])) - }, - } - - -def inspect(path, with_meta=False, entry=None, limit=None): - """Read ``path`` and return the report as a dict. Raises OSError/ValueError on unusable input.""" - if limit is not None and limit < 1: - raise ValueError("--limit must be at least 1") - with open(path, "rb") as fh: - size = os.fstat(fh.fileno()).st_size - if size < HEADER_SIZE: - raise ValueError( - "file is %d bytes, shorter than the 0x%x-byte header" - % (size, HEADER_SIZE) - ) - with mmap.mmap(fh.fileno(), 0, access=mmap.ACCESS_READ) as m: - magic = bytes(m[:4]) - if magic != MAGIC: - raise ValueError("no PS\\0\\x09 magic at 0x0 (found %s)" % magic.hex()) - report = { - "file": path, - "size": size, - "magic_ok": True, - "header_size": HEADER_SIZE, - } - counts = dict( - zip( - ("graphics", "compute", "meta_index", "shader_index"), - (u32(m, off) for off in COUNT_OFFS), - ) - ) - sizes = dict(zip(("meta", "code"), (u32(m, off) for off in SIZE_OFFS))) - report["counts"] = counts - report["sizes"] = sizes - report["header_hash"] = m[HASH_OFF : HASH_OFF + 8].hex() - report["header_strings"] = [] - for off in STRING_OFFS: - end = m.find(b"\x00", off, HEADER_SIZE) - report["header_strings"].append( - {"offset": off, "length": (end - off) if end >= 0 else 0} - ) - problems = [] - if any( - m[off : off + 4] != b"\x00\x00\x00\x00" - for off in range(0x68, HEADER_SIZE, 4) - ): - problems.append("header words at 0x68..0x7f are not zero") - - off = 0x80 - regions = collections.OrderedDict() - for name, count, stride, nbytes in ( - ("graphics", counts["graphics"], GRAPHICS_STRIDE, None), - ("compute", counts["compute"], COMPUTE_STRIDE, None), - ("meta_index", counts["meta_index"], INDEX_STRIDE, None), - ("shader_index", counts["shader_index"], INDEX_STRIDE, None), - ("meta_blob", None, None, sizes["meta"]), - ("code_blob", None, None, sizes["code"]), - ): - reg = region(name, off, count, stride, nbytes, size) - regions[name] = reg - off = reg["end"] - if not reg["fits"]: - problems.append( - "%s region ends at 0x%x, 0x%x bytes past the file end" - % (name, reg["end"], reg["shortfall"]) - ) - report["regions"] = regions - report["regions_end"] = off - report["slack"] = size - off - if off != size: - problems.append( - "regions end at 0x%x, %d bytes %s the file size 0x%x" - % (off, abs(off - size), "past" if off > size else "short of", size) - ) - report["problems"] = problems - report["references"] = None - report["meta_index"] = None - report["meta"] = None - report["meta_entry"] = None - report["shader_index"] = None - report["chunks"] = None - report["markers"] = None - - meta_off = regions["meta_blob"]["offset"] - code_off = regions["code_blob"]["offset"] - meta_size = sizes["meta"] - code_size = sizes["code"] - - # The PSO records name meta-index entries in their small u32 fields (0xffffffff is a hole). All of - # them must stay below the meta-index count: a wrong count or stride shifts the records and shows up - # here as out-of-range references. - if ( - regions["graphics"]["fits"] - and regions["compute"]["fits"] - and counts["meta_index"] - ): - meta_limit = counts["meta_index"] - bad_graphics = 0 - for i in range(counts["graphics"]): - base = regions["graphics"]["offset"] + i * GRAPHICS_STRIDE - for delta in (8, 0xC, 0x50, 0x54, 0x58, 0x5C): - value = u32(m, base + delta) - if value != 0xFFFFFFFF and value >= meta_limit: - bad_graphics += 1 - bad_compute = 0 - for i in range(counts["compute"]): - base = regions["compute"]["offset"] + i * COMPUTE_STRIDE - for delta in (8, 0xC, 0x10, 0x14): - if u32(m, base + delta) >= meta_limit: - bad_compute += 1 - report["references"] = { - "limit": meta_limit, - "graphics_out_of_range": bad_graphics, - "compute_out_of_range": bad_compute, - } - if bad_graphics or bad_compute: - problems.append( - "%d graphics and %d compute record references are outside the %d-entry meta index" - % (bad_graphics, bad_compute, meta_limit) - ) - - # Meta index: contiguous (offset, size) pairs covering the meta blob from 0. - if regions["meta_index"]["fits"] and regions["meta_blob"]["fits"]: - entries = [] - bad = 0 - for i in range(counts["meta_index"]): - a, b = struct.unpack_from( - " meta_size: - bad += 1 - entries.append((a, b)) - gaps = overlaps = 0 - expected = 0 - for a, b in entries: - if a > expected: - gaps += 1 - elif a < expected: - overlaps += 1 - expected = max(expected, a + b) - report["meta_index"] = { - "entries": len(entries), - "out_of_range": bad, - "gaps": gaps, - "overlaps": overlaps, - "coverage": expected, - "declared": meta_size, - "contiguous": gaps == 0 - and overlaps == 0 - and expected == meta_size - and bad == 0, - } - if bad: - problems.append( - "%d meta index entries point past the meta blob" % bad - ) - if gaps or overlaps: - problems.append( - "meta index is not contiguous: %d gaps, %d overlaps" - % (gaps, overlaps) - ) - if expected != meta_size: - problems.append( - "meta index covers 0x%x bytes of the 0x%x-byte meta blob" - % (expected, meta_size) - ) - - # Chunk histogram. Entries that are not 0x41/0x42/0x43 lists are counted, not guessed. - parsed = unparsed = no_chunks = 0 - headers = collections.Counter() - types = collections.Counter() - user_tags = collections.Counter() - spans = [] - for a, b in entries: - if a + b > meta_size: - unparsed += 1 - continue - header, tags = parse_chunks(m, meta_off, a, b) - if header is None: - unparsed += 1 - continue - headers[header] += 1 - if not tags: - no_chunks += 1 - continue - parsed += 1 - spans.append((a, b)) - for tag, word1 in tags: - types[tag] += 1 - if tag == 0x41: - user_tags[word1] += 1 - report["chunks"] = { - "entries": len(entries), - "chunk_lists": parsed, - "empty_lists": no_chunks, - "unparsed": unparsed, - "entry_headers": {hex(k): v for k, v in sorted(headers.items())}, - "types": {hex(k): v for k, v in sorted(types.items())}, - "user_tags": {hex(k): v for k, v in sorted(user_tags.items())}, - } - report["meta"] = None - report["meta_entry"] = None - if with_meta: - report["meta"] = decode_meta(m, meta_off, spans, limit) - if entry is not None: - if not 0 <= entry < len(entries): - raise ValueError( - "--entry %d is outside the %d-entry meta index" - % (entry, len(entries)) - ) - report["meta_entry"] = describe_entry(m, meta_off, *entries[entry]) - - # Shader index: (offset, size) pairs inside the code blob, in ascending offset order. - if regions["shader_index"]["fits"] and regions["code_blob"]["fits"]: - entries = [] - bad = 0 - for i in range(counts["shader_index"]): - a, b = struct.unpack_from( - " code_size: - bad += 1 - entries.append((a, b)) - ascending = all( - entries[i][0] <= entries[i + 1][0] for i in range(len(entries) - 1) - ) - max_end = max((a + b for a, b in entries), default=0) - report["shader_index"] = { - "entries": len(entries), - "out_of_range": bad, - "ascending": ascending, - "max_end": max_end, - "code_size": code_size, - "slack": code_size - max_end, - } - if bad: - problems.append( - "%d shader index entries point past the code blob" % bad - ) - if not ascending: - problems.append("shader index offsets are not ascending") - if max_end > code_size: - problems.append( - "shader index reaches 0x%x, past the 0x%x-byte code blob" - % (max_end, code_size) - ) - - # Markers: total counts, and how many s_endpgm each shader entry holds. - per_entry = collections.Counter() - for a, b in entries: - if a + b > code_size: - continue - per_entry[ - min( - 4, - count_marker(m, S_END_PGM, code_off + a, code_off + a + b), - ) - ] += 1 - report["markers"] = { - "s_endpgm": count_marker( - m, S_END_PGM, code_off, code_off + code_size - ), - "s_code_end": count_marker( - m, S_CODE_END, code_off, code_off + code_size - ), - "entries_with_none": per_entry.get(0, 0), - "entries_with_one": per_entry.get(1, 0), - "entries_with_two": per_entry.get(2, 0), - "entries_with_three_or_more": per_entry.get(3, 0) - + per_entry.get(4, 0), - } - - report["problems"] = problems - report["verdict"] = ( - "model holds" if not problems else "disagrees with the model" - ) - return report - - -def print_report(r, out=sys.stdout): - p = lambda *a: print(*a, file=out) - p("file: %d bytes (0x%x)" % (r["size"], r["size"])) - p("magic: PS\\0\\x09 at 0x0, header %d bytes" % r["header_size"]) - p( - "header: hash at 0x%x, strings %s" - % ( - HASH_OFF, - ", ".join( - "0x%x (%d bytes)" % (s["offset"], s["length"]) - for s in r["header_strings"] - ), - ) - ) - p( - "counts: graphics=%d compute=%d meta_index=%d shader_index=%d" - % ( - r["counts"]["graphics"], - r["counts"]["compute"], - r["counts"]["meta_index"], - r["counts"]["shader_index"], - ) - ) - p("sizes: meta=%d code=%d" % (r["sizes"]["meta"], r["sizes"]["code"])) - p("regions:") - for name, g in r["regions"].items(): - unit = ("x 0x%x" % g["stride"]) if g["stride"] is not None else "bytes" - count = ("%d " % g["count"]) if g["count"] is not None else "" - p( - " %-12s off 0x%08x %s%s = %d end 0x%08x %s" - % ( - name, - g["offset"], - count, - unit, - g["bytes"], - g["end"], - "fits" - if g["fits"] - else "DOES NOT FIT (%d bytes short)" % g["shortfall"], - ) - ) - p( - "regions end 0x%x, file 0x%x, slack %d" - % (r["regions_end"], r["size"], r["slack"]) - ) - refs = r["references"] - if refs: - p( - "record references: meta index limit %d, graphics out of range %d, compute out of range %d" - % ( - refs["limit"], - refs["graphics_out_of_range"], - refs["compute_out_of_range"], - ) - ) - mi = r["meta_index"] - if mi: - p( - "meta index: %d entries, coverage %d of %d, gaps %d, overlaps %d, out of range %d, %s" - % ( - mi["entries"], - mi["coverage"], - mi["declared"], - mi["gaps"], - mi["overlaps"], - mi["out_of_range"], - "contiguous" if mi["contiguous"] else "NOT contiguous", - ) - ) - si = r["shader_index"] - if si: - p( - "shader index: %d entries, max end 0x%x of 0x%x, slack %d, %s, out of range %d" - % ( - si["entries"], - si["max_end"], - si["code_size"], - si["slack"], - "ascending" if si["ascending"] else "NOT ascending", - si["out_of_range"], - ) - ) - ch = r["chunks"] - if ch: - p( - "meta chunks: %d of %d entries are chunk lists (%d empty, %d unparsed); headers %s" - % ( - ch["chunk_lists"], - ch["entries"], - ch["empty_lists"], - ch["unparsed"], - " ".join("%s=%d" % (k, v) for k, v in ch["entry_headers"].items()), - ) - ) - p( - " chunk types: %s" - % " ".join("%s=%d" % (k, v) for k, v in ch["types"].items()) - ) - p( - " 0x41 user tags: %s" - % " ".join("%s=%d" % (k, v) for k, v in ch["user_tags"].items()) - ) - md = r.get("meta") - if md: - p( - "meta decode: %d records, %d ordered 0x41..0x42..0x43, %d with one 0x43, %d exact-count pairs" - % (md["records"], md["ordered"], md["one_hash"], md["exact_pairs"]) - ) - for tag, t in md["tags"].items(): - p( - " 0x41 %s: %d, offset 0x%x..0x%x (%d values%s), sizes %s, b %s, counts %d values" - % ( - tag, - t["count"], - t["offset_min"], - t["offset_max"], - t["offset_values"], - ", 8-aligned" if t["aligned8"] else "", - " ".join("%s=%d" % (k, v) for k, v in t["sizes"].items()), - " ".join("%s=%d" % (k, v) for k, v in t["b"].items()), - t["count_values"], - ) - ) - p( - " 0x42 spaces: %s" - % " ".join("%s=%d" % (k, v) for k, v in md["slot_space"].items()) - ) - p( - " 0x42 middle bytes: %s" - % " ".join("%s=%d" % (k, v) for k, v in md["slot_middle"].items()) - ) - p( - " 0x42 widths: %s" - % " ".join("%s=%d" % (k, v) for k, v in md["slot_width"].items()) - ) - p( - " 0x41 kind -> 0x42 middle where counts match: %s" - % " ".join("%s=%d" % (k, v) for k, v in md["tag_middle"].items()) - ) - p( - " 0x42 beyond the 0x41 descriptor count: %d records %s, shapes %s" - % ( - md["records_with_extras"], - md["extras_per_record"], - " ".join("%s=%d" % (k, v) for k, v in md["extras"].items()), - ) - ) - entry_lines = r.get("meta_entry") - if entry_lines: - for line in entry_lines: - p(line) - mk = r["markers"] - if mk: - p( - "markers: s_endpgm %d, s_code_end %d in the code blob" - % (mk["s_endpgm"], mk["s_code_end"]) - ) - p( - " shader entries by s_endpgm count: 0=%d 1=%d 2=%d 3+=%d" - % ( - mk["entries_with_none"], - mk["entries_with_one"], - mk["entries_with_two"], - mk["entries_with_three_or_more"], - ) - ) - for problem in r["problems"]: - p("problem: %s" % problem) - p("verdict: %s" % r["verdict"]) - - -def main(argv=None): - ap = argparse.ArgumentParser( - description="Check a PS\\0\\x09 PSO/shader cache against the 0x80/0x70/0x18 layout." - ) - ap.add_argument("cache", help="cache file (read-only)") - ap.add_argument("--json", action="store_true", help="print the report as JSON") - ap.add_argument( - "--meta", - action="store_true", - help="decode the meta chunk records (0x41 kinds, 0x42 slot bytes, positional pairing)", - ) - ap.add_argument( - "--entry", - type=int, - default=None, - metavar="N", - help="with --meta, also list meta index entry N", - ) - ap.add_argument( - "--limit", - type=int, - default=None, - metavar="N", - help="with --meta, decode at most N chunk-list records", - ) - ap.add_argument( - "--quiet", action="store_true", help="print nothing, only set the exit code" - ) - a = ap.parse_args(argv) - try: - report = inspect( - a.cache, - with_meta=a.meta or a.entry is not None, - entry=a.entry, - limit=a.limit, - ) - except (OSError, ValueError) as e: - print("%s: %s" % (a.cache, e), file=sys.stderr) - return 2 - if not a.quiet: - if a.json: - print(json.dumps(report, indent=1)) - else: - print_report(report) - return 0 if not report["problems"] else 1 - - -if __name__ == "__main__": - try: # a redirected stdout is strict ANSI code page under -I; write '?' for what it cannot encode - sys.stdout.reconfigure(errors="replace") - except (AttributeError, ValueError, OSError): - pass - sys.exit(main()) diff --git a/tools/psocache_usersig.py b/tools/psocache_usersig.py deleted file mode 100644 index c89134365..000000000 --- a/tools/psocache_usersig.py +++ /dev/null @@ -1,464 +0,0 @@ -"""Describe the root-signature / user-data side of the graphics PSO records in a PS\\0\\x09 cache. - -Each graphics PSO record (0x70 bytes) names a stage record at +8 and an input-layout record at +0xC. The stage -record names the per-stage chunk records that carry the user data. A chunk record (0x41/0x42/0x43 list) is -decoded here as: - -- 0x41 entry: kind, offset (w2), key (w3), count (w4), and w5 split into `a` (bits 16..31), `b` (bits 8..15) - and element size (bits 0..7). For 0x300/0x302/0x303 the tool reads `b` as the register space, `a` as the base - register and w4 as the count. For 0x401 it reads `a` as the number of 32-bit constants. The 0x2 kind is a - sampler entry with no slot. -- 0x42 entry: the slot word splits as 0x00SS_IIRR. SS is read as the descriptor-table / root-parameter index, - II as the D3D12_DESCRIPTOR_RANGE_TYPE order (0 SRV, 1 UAV, 2 CBV, 3 sampler) and RR as a width (1, or 2 for - the extra slots). w4 is reported as found. -- 0x43 entry: a 16-byte value, not printed. - -The 32-dword root-argument budget is computed as `constants + 2 * tables` (the layer's default mapping of two -dwords per descriptor table) and alternatively as `constants + 1 * tables` (the one-dword-per-table model -measured on the console shaders, see docs/d3d12_vulkan.md 3.5). A record fits when the total is at most 32. - -The names and readings above are inferences from measured shapes, not a decoded driver format; the tool prints -the raw bytes it used next to each field so the reading can be checked. It never prints a hash or a path. - -Usage: - python -I psocache_usersig.py [--entry N] [--limit N] [--json] [--quiet] - ---entry N prints one graphics PSO (0-based). --limit N samples the first N graphics PSOs (default: all). -Exit code: 0 on success, 2 when the cache cannot be read or the inspector reports a disagreement. -""" - -import argparse -import collections -import json -import mmap -import os -import struct -import sys - -sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) - -import psocache_inspect as pi # noqa: E402 - -KIND_NAMES = { - 0x300: "SRV", - 0x302: "CBV", - 0x303: "UAV", - 0x2: "Sampler", - 0x401: "constants", - 0x100: "unknown-0x100", -} -DESCRIPTOR_KINDS = (0x300, 0x302, 0x303) -RANGE_NAMES = {0: "SRV", 1: "UAV", 2: "CBV", 3: "Sampler"} -STAGE_REFS = (0x4, 0x2C, 0x78, 0x90, 0x150, 0x1A4) -CONTRACT_DWORDS = 32 - - -def describe_chunk(w): - """One decoded chunk as a JSON-safe dict.""" - if w[0] == 0x41: - kind = w[1] - item = { - "chunk": "0x41", - "tag": "0x%03x" % kind, - "name": KIND_NAMES.get(kind, "unknown"), - "offset": w[2], - "key": w[3], - "count": w[4], - "a": w[5] >> 16, - "b": (w[5] >> 8) & 0xFF, - "size": w[5] & 0xFF, - } - if kind in DESCRIPTOR_KINDS: - item["space"] = item["b"] - item["base_register"] = item["a"] - elif kind == 0x401: - item["constant_count"] = item["a"] - return item - if w[0] == 0x42: - return { - "chunk": "0x42", - "tag": "0x42", - "slot": "0x%06x" % w[2], - "SS": (w[2] >> 16) & 0xFF, - "II": (w[2] >> 8) & 0xFF, - "RR": w[2] & 0xFF, - "key": w[3], - "w4": w[4], - } - return {"tag": "0x%x" % w[0]} - - -def describe_record(index, chunks): - """Decode one chunk record and compute its 32-dword cost under both table models.""" - entries = [] - descriptors = [] - slots = [] - hashes = 0 - for w in chunks: - if w[0] == 0x41: - entries.append(describe_chunk(w)) - if w[1] in DESCRIPTOR_KINDS: - descriptors.append((w, len(entries) - 1)) - elif w[0] == 0x42: - slots.append(w) - elif w[0] == 0x43: - hashes += 1 - pairs = [] - for i, (w, entry_index) in enumerate(descriptors): - slot = describe_chunk(slots[i]) if i < len(slots) else None - pairs.append({"entry": entries[entry_index], "slot": slot}) - extras = [describe_chunk(w) for w in slots[len(descriptors) :]] - tables = sorted({(w[2] >> 16) & 0xFF for w in slots}) - constants = sum(w[5] >> 16 for w in chunks if w[0] == 0x41 and w[1] == 0x401) - cost_two = constants + 2 * len(tables) - cost_one = constants + len(tables) - kinds = collections.Counter(e["name"] for e in entries) - return { - "record": index, - "chunks": len(chunks), - "hashes": hashes, - "entries": entries, - "pairs": pairs, - "extras": extras, - "tables": tables, - "constants": constants, - "cost_two_per_table": cost_two, - "cost_one_per_table": cost_one, - "fits_two_per_table": cost_two <= CONTRACT_DWORDS, - "fits_one_per_table": cost_one <= CONTRACT_DWORDS, - "kinds": dict(kinds), - } - - -def stage_record_refs(m, meta_off, meta_index, chunk_records, stage): - """(stage offset, chunk record index) for every stage field that names a chunk record, deduplicated.""" - if not 0 <= stage < len(meta_index): - return [] - a, b = meta_index[stage] - out = [] - seen = set() - for p in STAGE_REFS: - if p + 4 <= b: - value = pi.u32(m, meta_off + a + p) - if chunk_records.get(value) is not None and value not in seen: - seen.add(value) - out.append((p, value)) - return out - - -def describe_pso(m, region, meta_off, meta_index, chunk_records, index): - """Decode one graphics PSO and the chunk records its stage record names.""" - offset = region + index * pi.GRAPHICS_STRIDE - stage = pi.u32(m, offset + 8) - layout = pi.u32(m, offset + 0xC) - refs = stage_record_refs(m, meta_off, meta_index, chunk_records, stage) - records = [describe_record(record, chunk_records[record]) for _, record in refs] - fits_two = all(r["fits_two_per_table"] for r in records) - fits_one = all(r["fits_one_per_table"] for r in records) - return { - "pso": index, - "offset": offset, - "stage": stage, - "input_layout": layout, - "records": [ - { - "field": "0x%x" % p, - "index": record, - "size": meta_index[record][1], - "decode": decode, - } - for (p, record), decode in zip(refs, records) - ], - "fits_two_per_table": fits_two, - "fits_one_per_table": fits_one, - } - - -def summarise(m, report, limit=None): - """Aggregate the sampled graphics PSOs. Returns a JSON-safe dict.""" - counts = report["counts"] - graphics = counts["graphics"] - sampled = graphics if limit is None else min(graphics, limit) - meta_off = report["regions"]["meta_blob"]["offset"] - meta_region = report["regions"]["meta_index"] - graphics_region = report["regions"]["graphics"] - meta_index = [ - struct.unpack_from(" [--jobs N] [--limit N] [--json OUT] [--index-out OUT] - - is `/shaders/disasm` (the carve's index.json one level up gives each stage). --json writes the -summary; --index-out writes {number: {"stage", "user_sgpr_reads"}} with shaders numbered in listing order, not -named, which `tools/user_sgpr_census.py` reads. Neither prints or writes a shader name, listing or byte. --limit -stops after that many listings and must be at least 1; a smaller value is a usage error. -""" -import argparse -import json -import os -import sys -from collections import Counter, defaultdict -from concurrent.futures import ProcessPoolExecutor - -sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) -import pool_workers # noqa: E402 -import rdna2spirv # noqa: E402 -import shader_meta # noqa: E402 -from report_paths import same_report_path # noqa: E402 - -STAGES = ("vs", "ps", "cs", "gs", "hs", "ds", "ms", "as") -TABLE_LOADS = ("s_load_dwordx4", "s_load_dwordx8", "s_load_dwordx16") - - -class _Reached(Exception): - """Raised from the patched shader_meta.collect: translate() got as far as the metadata call.""" - - def __init__(self, blocks, succ, user_sgpr_limit, system_sgprs): - super().__init__("metadata reached") - self.args_ = (blocks, succ, user_sgpr_limit, system_sgprs) - - -def _capture(_path, _name, blocks, succ, user_sgpr_limit=32, system_sgprs=()): - raise _Reached(blocks, succ, user_sgpr_limit, system_sgprs) - - -def access_of(op): - op = shader_meta.base_op(op) - if op.startswith("global_"): - return "global" - return "table" if op in TABLE_LOADS else "scalar" - - -def high_of(hi_t): - if shader_meta._user_of(hi_t) is not None: - return "user" - if hi_t is not None and hi_t[0] == "const": - return "zero" if hi_t[1] == 0 else "const" - return "unknown" - - -def pointer_sites(blocks, succ, user_sgpr_limit=32, system_sgprs=()): - """Run analyse_instructions with every base pair it looks at recorded. - - Returns (result of analyse_instructions, sites); a site is (sgpr or None, low tag kind, high, access), - deduplicated by instruction address (node splitting clones blocks).""" - current = {} - seen = {} - step, record = shader_meta._step_state, shader_meta._record_ptr_pair - - def step_state(sym, scale, ptr_stride, vscale, ins, events=None): - current["ins"] = ins - return step(sym, scale, ptr_stride, vscale, ins, events) - - def record_ptr_pair(events, sym, slots, is_desc_width=False): - lo_t, hi_t = shader_meta._slot_tag(sym, slots[0]), shader_meta._slot_tag(sym, slots[1]) - ins = current["ins"] - key = (ins.get("pc", id(ins)), ins["op"]) - lo = shader_meta._user_of(lo_t) - site = (lo, lo_t[0] if lo is not None else "other", high_of(hi_t), access_of(ins["op"])) - seen.setdefault(key, set()).add(site) - return record(events, sym, slots, is_desc_width) - - shader_meta._step_state, shader_meta._record_ptr_pair = step_state, record_ptr_pair - try: - result = shader_meta.analyse_instructions(blocks, succ, user_sgpr_limit=user_sgpr_limit, - system_sgprs=system_sgprs) - finally: - shader_meta._step_state, shader_meta._record_ptr_pair = step, record - sites = sorted({s for group in seen.values() for s in group}, key=repr) - return result, sites - - -def global_without_sgpr_base(ins): - """A global_* instruction whose address is a VGPR pair (saddr `off`): shader_meta never looks at it.""" - op = shader_meta.base_op(ins["op"]) - if not op.startswith("global_"): - return False - a = ins["args"] - k = 3 if op.startswith("global_atomic_") and "glc" in ins.get("mods", ()) else 2 - return not (len(a) > k and shader_meta._sgpr_slots(a[k], 2) is not None) - - -def scan_one(path): - """Per-shader record (no name): stage, whether translate() reached the metadata call, and the sites.""" - real = shader_meta.collect - shader_meta.collect = _capture - rdna2spirv._shader_meta = shader_meta - reached = None - try: - rdna2spirv.translate(path) - error = "translate returned without reaching shader_meta.collect" - except _Reached as r: - reached, error = r.args_, None - except rdna2spirv.Unsupported as e: - error = f"Unsupported: {e}" - except (IndexError, KeyError, ValueError) as e: - error = f"translator error {type(e).__name__}" - finally: - shader_meta.collect = real - name = os.path.splitext(os.path.basename(path))[0] - stage = rdna2spirv.stage_of(name, path) - out = {"stage": stage, "error": error} - if reached is None: - return out - blocks, succ, limit, system = reached - stock = shader_meta.analyse_instructions(blocks, succ, user_sgpr_limit=limit, system_sgprs=system) - result, sites = pointer_sites(blocks, succ, user_sgpr_limit=limit, system_sgprs=system) - ops = {shader_meta.base_op(i["op"]) for b in blocks for i in b} - out.update({ - "sites": [list(s) for s in sites], - "truncates_high": stock["truncates_high"], - "instrumented_truncates_high": result["truncates_high"], - "user_sgpr_reads": stock["user_sgpr_reads"], - "flat": any(o.startswith("flat_") for o in ops), - "scratch": any(o.startswith("scratch_") for o in ops), - "vsharp_memory": any(o.startswith(("buffer_", "tbuffer_", "s_buffer_")) for o in ops), - "getpc": "s_getpc_b64" in ops, - "global_vgpr_address": sum(1 for b in blocks for i in b if global_without_sgpr_base(i)), - }) - return out - - -def scan_many(paths): - return [scan_one(p) for p in paths] - - -def summarise(records): - """records: scan_one() results -> summary dict (counts only).""" - shaders, reached, errors = Counter(), Counter(), Counter() - trunc_shaders, mode, per_shader = Counter(), defaultdict(Counter), defaultdict(Counter) - trunc_access, trunc_low, trunc_sgpr = defaultdict(Counter), defaultdict(Counter), defaultdict(Counter) - untrunc_high, both_ways, kind_shown = defaultdict(Counter), Counter(), defaultdict(Counter) - blind = defaultdict(Counter) - mismatch = 0 - for r in records: - st = r["stage"] - shaders[st] += 1 - if r.get("error"): - errors[r["error"]] += 1 - continue - reached[st] += 1 - trunc, other = defaultdict(set), defaultdict(set) - untracked = set() - for sgpr, low, high, access in r["sites"]: - if sgpr is None: - untracked.add(f"lo not a user SGPR, hi {high} ({access})") - continue - (trunc if high == "zero" else other)[sgpr].add((low, high, access)) - for what in untracked: - blind[st]["shaders with " + what] += 1 - flag = bool(trunc) - if flag != r["truncates_high"] or flag != r["instrumented_truncates_high"]: - mismatch += 1 - if r.get("flat"): - blind[st]["shaders using flat_*"] += 1 - if r.get("scratch"): - blind[st]["shaders using scratch_*"] += 1 - if r.get("global_vgpr_address"): - blind[st]["shaders with a VGPR-addressed global_*"] += 1 - blind[st]["VGPR-addressed global_* instructions"] += r["global_vgpr_address"] - if r.get("getpc"): - blind[st]["shaders using s_getpc_b64"] += 1 - if r.get("vsharp_memory"): - blind[st]["shaders using a V# (buffer_*, tbuffer_*, s_buffer_*)"] += 1 - pointers = set(trunc) | set(other) - if not pointers: - mode[st]["no pointer"] += 1 - continue - if not trunc: - mode[st]["none truncated"] += 1 - elif other: - mode[st]["some truncated"] += 1 - else: - mode[st]["all truncated"] += 1 - if not trunc: - for sites in other.values(): - for _, high, access in sites: - untrunc_high[st][f"{high} ({access})"] += 1 - continue - trunc_shaders[st] += 1 - per_shader[st][len(trunc)] += 1 - kinds = {row["sgpr"]: row["kind"] for row in r["user_sgpr_reads"]} - for sgpr, sites in trunc.items(): - trunc_sgpr[st][f"s{sgpr}"] += 1 - kind_shown[st][kinds.get(sgpr, "not read")] += 1 - for a in sorted({s[2] for s in sites}): - trunc_access[st][a] += 1 - trunc_low[st]["+".join(sorted({s[0] for s in sites}))] += 1 - if sgpr in other: - both_ways[st] += 1 - for sgpr, sites in other.items(): - for _, high, access in sites: - untrunc_high[st][f"{high} ({access})"] += 1 - stages = [s for s in STAGES if shaders[s]] + sorted(s for s in shaders if s not in STAGES) - - def per(d): - return {s: dict(sorted(d[s].items())) for s in stages if d[s]} - - return { - "shaders": {s: shaders[s] for s in stages}, - "total": sum(shaders.values()), - "reached_metadata": {s: reached[s] for s in stages}, - "not_reached": dict(errors.most_common()), - "truncating_shaders": {s: trunc_shaders[s] for s in stages}, - "pointer_mode": per(mode), - "truncated_pointers_per_shader": {s: {str(k): v for k, v in sorted(per_shader[s].items())} - for s in stages if per_shader[s]}, - "truncated_pointer_access": per(trunc_access), - "truncated_pointer_low_half": per(trunc_low), - "truncated_pointer_sgpr": {s: dict(sorted(trunc_sgpr[s].items(), key=lambda kv: int(kv[0][1:]))) - for s in stages if trunc_sgpr[s]}, - "truncated_pointer_kind_in_index": per(kind_shown), - "truncated_also_used_untruncated": {s: both_ways[s] for s in stages if both_ways[s]}, - "untruncated_site_high_half": per(untrunc_high), - "not_seen": per(blind), - "flag_mismatches": mismatch, - } - - -def print_summary(s, out=None): - out = out or sys.stdout - w = lambda text="": print(text, file=out) # noqa: E731 - w(f"{s['total']} shaders: " + ", ".join(f"{k} {v}" for k, v in s["shaders"].items())) - w("reached shader_meta: " + ", ".join(f"{k} {v}" for k, v in s["reached_metadata"].items()) - + (f"; not reached {s['not_reached']}" if s["not_reached"] else "")) - total = sum(s["truncating_shaders"].values()) - w(f"truncate a pointer's high dword: {total}: " + ", ".join(f"{k} {v}" for k, v in s["truncating_shaders"].items())) - for title, key in (("pointers (all/some/none truncated)", "pointer_mode"), - ("truncated pointers per shader", "truncated_pointers_per_shader"), - ("truncated pointer, by access", "truncated_pointer_access"), - ("truncated pointer, low half", "truncated_pointer_low_half"), - ("truncated pointer, user SGPR", "truncated_pointer_sgpr"), - ("truncated pointer, kind in user_sgpr_reads", "truncated_pointer_kind_in_index"), - ("high half of untruncated sites", "untruncated_site_high_half"), - ("not seen by the classifier", "not_seen")): - w(f"{title}:") - for st, row in s[key].items(): - w(f" {st}: " + ", ".join(f"{k} {v}" for k, v in row.items())) - if s["truncated_also_used_untruncated"]: - w(f"truncated pointer also dereferenced untruncated: {s['truncated_also_used_untruncated']}") - w(f"flag mismatches against shader_meta.analyse_instructions: {s['flag_mismatches']}") - - -def listings(src): - with os.scandir(src) as entries: - return sorted(e.path for e in entries if e.name.endswith(".s") and e.is_file()) - - -def positive_int(text: str) -> int: - """--limit -1 dropped the last listing and --limit 0 scanned none, both with exit 0.""" - try: - value = int(text) - except ValueError: - raise argparse.ArgumentTypeError(f"invalid int value: {text!r}") from None - if value < 1: - raise argparse.ArgumentTypeError("must be at least 1 (a smaller value would silently scan fewer listings)") - return value - - -def main(argv=None): - ap = argparse.ArgumentParser(description=__doc__.split("\n")[0]) - ap.add_argument("src", help="folder of .s listings (/shaders/disasm)") - ap.add_argument("--jobs", type=int, default=max(1, (os.cpu_count() or 2) - 1)) - ap.add_argument("--limit", type=positive_int, help="scan at most this many listings (at least 1)") - ap.add_argument("--json", help="write the summary here") - ap.add_argument("--index-out", help="write {number: {stage, user_sgpr_reads}} for tools/user_sgpr_census.py") - a = ap.parse_args(argv) - if not os.path.isdir(a.src): - print(f"ERROR: {a.src} is not a folder", file=sys.stderr) - return 2 - if a.json and a.index_out and same_report_path(a.json, a.index_out): - ap.error(f"--json and --index-out name one file: {a.json}; the second report would replace the first") - files = listings(a.src)[: a.limit] if a.limit is not None else listings(a.src) - jobs = pool_workers.process_workers(max(1, a.jobs)) - if jobs == 1 or len(files) < 64: - records = scan_many(files) - else: - size = max(1, len(files) // (jobs * 8)) - chunks = [files[i:i + size] for i in range(0, len(files), size)] - with ProcessPoolExecutor(max_workers=jobs) as pool: - records = [r for part in pool.map(scan_many, chunks) for r in part] - summary = summarise(records) - print_summary(summary) - try: - if a.json: - with open(a.json, "w", encoding="utf-8", newline="\n") as f: - json.dump(summary, f, indent=1, sort_keys=True) - if a.index_out: - index = {str(n): {"stage": r["stage"], "user_sgpr_reads": r.get("user_sgpr_reads", [])} - for n, r in enumerate(records) if not r.get("error")} - with open(a.index_out, "w", encoding="utf-8", newline="\n") as f: - json.dump(index, f, indent=1, sort_keys=True) - except OSError as e: - print(f"ERROR: cannot write: {e.strerror or e}", file=sys.stderr) - return 2 - return 1 if summary["flag_mismatches"] else 0 - - -if __name__ == "__main__": - try: # a redirected stdout is strict ANSI code page under -I; write '?' for what it cannot encode - sys.stdout.reconfigure(errors="replace") - except (AttributeError, ValueError, OSError): - pass - sys.exit(main()) diff --git a/tools/rbf0_encode.py b/tools/rbf0_encode.py deleted file mode 100644 index 8ec622c2c..000000000 --- a/tools/rbf0_encode.py +++ /dev/null @@ -1,327 +0,0 @@ -"""Encode an RBF0 tree document back to bytes, and check that decoding and encoding give the original resource. - -`rbf0_tree.parse_resource` turns one RBF0 resource into a tree document (docs/rbf0.md section 9). `encode(doc)` -writes that tree back as an RBF0 record stream with the grammar of docs/rbf0.md section 3: the `FB FF 01 00` -prologue and 8-byte values for the wide layout, no prologue and 4-byte values for the narrow one; each descriptor -name at its first use, in index order; an element's three header words `0, 0, attribute count`; its attributes, then -its content in tree order; text and strings with the bytes and terminating NUL the tree records. - -The encoder fails closed. When the tree cannot hold the original bytes it raises EncodeError with a short reason -instead of writing something else: - status the parse was not complete (bad, truncated, or bytes after the root closed) - utf8 a descriptor name, string or text had invalid UTF-8, or an edit contains an unpaired surrogate - nan a float or vec3 component was NaN, whose bits the tree renders as text (infinities are exact) - order a value counted as an attribute came after the element's content started, or an element short of - its attribute count has a value in its content, which would decode as an attribute - descriptor a descriptor index outside the table, or a first use out of order - length a string or text no longer has its recorded byte length - value a value the record cannot hold (an integer out of range, a float that overflows the layout, an - unknown type, more attribute records than the element's attribute count) - -Usage: - python -I rbf0_encode.py --check [--limit N] - Decode every RBF0 resource (joining 64 KiB continuations as rbf0_tree.py does), encode it, and compare the - result with the original bytes. Prints counts only: exact, different, and refused by reason. Exit 1 when a - resource encodes to different bytes or was refused: only a run where every resource is exact exits 0. - python -I rbf0_encode.py - Write each resource of an rbf0_tree.py JSON report (possibly edited) as .rbf. The directory must be - new or empty. Exit 1 if any resource is refused; valid resources are still written. - -Everything written is game data: keep it in your work folder, out of git, issues and pull requests. -""" -import argparse -import json -import math -import os -import struct -import sys - -sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) - -import rbf0_tree # noqa: E402 - -MAGIC = rbf0_tree.MAGIC -PROLOGUE = rbf0_tree.PROLOGUE -REASONS = ("status", "utf8", "nan", "order", "descriptor", "length", "value") - - -class EncodeError(ValueError): - """The tree cannot be written back byte for byte; `reason` is one of REASONS.""" - - def __init__(self, reason, message): - super().__init__(f"{reason}: {message}") - self.reason = reason - - -class _Writer: - def __init__(self, doc): - self.wide = doc.get("layout") == "wide-64" - self.out = bytearray(MAGIC + (PROLOGUE if self.wide else b"")) - self.names = [d.get("name") for d in doc.get("descriptors") or []] - self.bad_names = {d["index"] for d in doc.get("descriptors") or [] if d.get("utf8_valid") is False} - self.emitted = 0 - - def record(self, node, kind): - index = node.get("descriptor") - if not isinstance(index, int) or isinstance(index, bool) or not 0 <= index < 0xFD: - raise EncodeError("descriptor", f"descriptor index {index!r} cannot be written") - if index > self.emitted: - raise EncodeError("descriptor", f"descriptor {index} is used before descriptor {self.emitted}") - self.out += bytes((index, kind)) - name = node.get("name", "") - if index == self.emitted: - if index in self.bad_names: - raise EncodeError("utf8", f"descriptor {index} name had invalid UTF-8") - if index < len(self.names) and self.names[index] not in (None, name): - raise EncodeError("descriptor", f"descriptor {index} is named both {self.names[index]!r} and {name!r}") - if index == len(self.names): - self.names.append(name) - else: - self.names[index] = name - raw = name.encode("utf-8") - if len(raw) > 0xFFFF: - raise EncodeError("length", f"descriptor {index} name is {len(raw)} bytes") - self.out += struct.pack(" 0xFFFF or ("byte_length" in node and len(raw) != node["byte_length"]): - raise EncodeError("length", f"string of {len(raw)} bytes, recorded {node.get('byte_length')}") - self.record(node, 0x60) - self.out += struct.pack(" 0xFFFFFFFF or ("length" in node and len(raw) != node["length"]): - raise EncodeError("length", f"text of {len(raw)} bytes, recorded {node.get('length')}") - self.out += b"\xfd\xff" + struct.pack(" attrs: - raise EncodeError("value", f"element {node.get('name')!r} has {listed} attribute records, count {attrs}") - if listed < attrs and any(c.get("kind") == "value" for c in node.get("content", [])): - raise EncodeError("order", f"element {node.get('name')!r} is short of its {attrs} attributes and has a " - "value in its content") - self.record(node, 0x00) - self.out += struct.pack("= 0 else i - name = f"{file_offset:08x}.rbf" - if os.path.exists(os.path.join(out_dir, name)): - name = f"{file_offset:08x}-{i:04d}.rbf" - target = os.path.join(out_dir, name) - try: - with open(target, "xb") as f: - f.write(blob) - except OSError as e: - raise SystemExit(f"{target}: cannot write: {e.strerror or e}") from None - written += 1 - return written, refused - - -def main(argv=None): - ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) - ap.add_argument("--check", metavar="SOURCE", help="round-trip every resource of a carve directory or file") - ap.add_argument("--limit", type=int, help="with --check, stop after N resources") - ap.add_argument("report", nargs="?", help="an rbf0_tree.py JSON report to encode") - ap.add_argument("out", nargs="?", help="a new or empty output directory") - a = ap.parse_args(argv) - if a.check: - if a.report or a.out: - ap.error("--check takes no report or output directory") - if a.limit is not None and a.limit < 1: - ap.error("--limit must be at least 1") - if not os.path.exists(a.check): - ap.error(f"{a.check}: no such file or directory") - try: - r = check(a.check, a.limit) - except rbf0_tree.SelectionError as e: - ap.error(str(e)) - print(f"{r['resources']} resource(s): {r['exact']} exact, {r['different']} different, {r['refused']} refused") - for reason, n in r["refused_by_reason"].items(): - print(f" refused ({reason}): {n}") - for layout, c in sorted(r["by_layout"].items()): - print(f" {layout}: {c['exact']} of {c['resources']} exact") - return 1 if r["different"] or r["refused"] else 0 - if not a.report or not a.out: - ap.error("give --check SOURCE, or a report and an output directory") - if a.limit is not None: - ap.error("--limit only applies to --check") - if not os.path.isfile(a.report): - ap.error(f"{a.report}: no such file") - written, refused = write_all(a.report, a.out) - print(f"{written} resource(s) written, {len(refused)} refused") - for offset, why in refused: - print(f" 0x{offset:x}: {why}" if isinstance(offset, int) else f" {offset}: {why}") - return 1 if refused else 0 - - -if __name__ == "__main__": - try: # a redirected stdout is strict ANSI code page under -I; write '?' for what it cannot encode - sys.stdout.reconfigure(errors="replace") - except (AttributeError, ValueError, OSError): - pass - sys.exit(main()) diff --git a/tools/rbf0_index.py b/tools/rbf0_index.py deleted file mode 100644 index 2b47cdbf9..000000000 --- a/tools/rbf0_index.py +++ /dev/null @@ -1,604 +0,0 @@ -"""Index RBF0 resources in an RPF9 data area or a folder of carved streams. - -RBF0 is RAGE's binary form of an XML data file. This tool walks the same zlib streams as rpf9_carve.py, joins the -64 KiB continuation chunks of one logical resource, and parses the record stream far enough to report the root -schema name, the inline descriptor table, element/value/text counts, scalar counts and readable strings. It never -decrypts, never writes payloads, and does not turn RBF0 back into XML. - -Format facts and the measured corpus composition are in docs/rbf0.md. Two layouts occur: a 4-byte prologue -`FB FF 01 00` followed by 64-bit scalar values, and no prologue with 32-bit scalar values. A record is one -descriptor-index byte and one type byte; a new descriptor adds a u16 name length and its UTF-8 name. Types: -0x00 opens an element (three u16 words, the third is its attribute count), 0x10 an integer, 0x20 true, 0x30 false, -0x40 a float, 0x50 three floats, 0x60 a string (u16 length), 0xFD text (u32 length), 0xFF closes the open element. -The stream must end where the root closes. No section table or name-hash table is present. - -Usage: - python -I rbf0_index.py [--start N] [--limit BYTES] [--strings N] - python -I rbf0_index.py [--strings N] - -The output contains names taken from the archive, so treat it as game data: keep it out of git and do not attach -it to an issue or a pull request. -""" -import argparse -import collections -import csv -import json -import mmap -import os -import re -import stat -import struct -import sys -import tempfile -import zlib - -ROOT = os.path.dirname(os.path.abspath(__file__)) -if ROOT not in sys.path: - sys.path.insert(0, ROOT) -from file_mode import published_mode # noqa: E402 -from replace_retry import replace as replace_retry # noqa: E402 -from zero_span import gap_split # noqa: E402 - -MAGIC = b"RBF0" -PROLOGUE = b"\xfb\xff\x01\x00" -# zlib stream start, or a Bink 2 video ('KB2' + revision letter). Kept in step with rpf9_carve.py. -ZHDR = re.compile(rb"\x78[\x01\x5e\x9c\xda]|KB2[a-z]") -MAX_CHUNK = 65536 -MAX_CHUNKS = 256 -MAX_BYTES = 64 * 1024 * 1024 -KEYWORDS = ("anim/", "pack:/", "skel_", "rbf0", "xml", "nav", "map", "ipl", "handling", "meta", "hud", - "radio", "vehicle", "ped/", "weapon", "credits", "phone", "rage__", "fwui") -IDENT = re.compile(r"[A-Za-z0-9_.:@+-]+") -COLUMNS = ["offset", "stored", "size", "chunks", "layout", "root", "descriptors", "elements", "values", - "texts", "strings", "ints", "floats", "depth", "status", "sample"] -TYPE_NAMES = {0x00: "open", 0x10: "int", 0x20: "true", 0x30: "false", 0x40: "float", - 0x50: "vec3", 0x60: "string", 0xFD: "text"} - - -class RbfError(ValueError): - """A malformed or truncated RBF0 record stream.""" - - def __init__(self, message, offset, truncated=False): - super().__init__(f"{message} at 0x{offset:x}") - self.detail = message - self.offset = offset - self.truncated = truncated - - -def _u32(data, at): - return struct.unpack_from("= at + 4 else None - - -def parse_rbf0(data, string_limit=None): - """Parse one complete RBF0 resource. Returns a dict; a truncated or bad stream keeps its partial counts. - - `string_limit` caps the returned `strings` list only; every count is still complete. - """ - if data[:4] != MAGIC: - raise RbfError("not an RBF0 stream", 0) - wide = data[4:8] == PROLOGUE - p = 8 if wide else 4 - scalar = 8 if wide else 4 - descs = [] - stack = [] # [attribute_count, attributes_seen, content_started] - strings = [] - ints = [] - floats = [] - types = collections.Counter() - root = "" - root_end = None - elements = values = texts = 0 - max_depth = 0 - attr_mismatches = 0 - status = "ok" - error = "" - - def take(n, what): - nonlocal p - if p + n > len(data): - raise RbfError(f"{what} truncated", p, truncated=True) - start = p - p += n - return data[start:p] - - try: - while p < len(data): - at = p - index = take(1, "record index")[0] - kind = take(1, "record type")[0] - if index == 0xFF: - if kind != 0xFF: - raise RbfError("close tag is not FF FF", at) - if not stack: - raise RbfError("close without an open element", at) - attrs, seen, content_started = stack.pop() - if not content_started and seen < attrs: - attr_mismatches += 1 - if not stack: - root_end = p - break - continue - if index == 0xFD: - if kind != 0xFF: - raise RbfError("text tag is not FD FF", at) - n = struct.unpack(" len(descs): - raise RbfError(f"descriptor index {index} of {len(descs)}", at) - name = descs[index][0] - if kind == 0x00: - raw = take(6, "element header") - word0, word1, attrs = struct.unpack(" MAX_CHUNK or nxt["head"][:4] in (MAGIC, b"PSIN"): - break - if check_gap and nxt["offset"] > rows[j - 1]["offset"] + rows[j - 1]["stored"] + 16: - break - blob += read(nxt) - chunks += 1 - parsed = parse_rbf0(blob, string_limit=None) - if parsed["status"] != "truncated": - break - j += 1 - return blob, chunks, parsed - - -def resources_from_rows(rows, read, check_gap=True, string_limit=16): - """Parse every RBF0 start row, join its continuations, and build the reported records.""" - out = [] - for i, row in enumerate(rows): - if row["head"][:4] != MAGIC: - continue - blob, chunks, parsed = join_resource(rows, i, read, check_gap=check_gap) - sample = parsed["strings"][:string_limit] if string_limit is not None else list(parsed["strings"]) - out.append({ - "offset": row["offset"], - "stored": sum(rows[j]["stored"] for j in range(i, i + chunks)), - "size": len(blob), - "chunks": chunks, - "layout": parsed["layout"], - "prologue": parsed["prologue"], - "root": parsed["root"], - "descriptors": parsed["descriptors"], - "elements": parsed["elements"], - "values": parsed["values"], - "texts": parsed["texts"], - "strings": len(parsed["strings"]), - "ints": len(parsed["ints"]), - "floats": len(parsed["floats"]), - "depth": parsed["depth"], - "attributes": parsed["attributes"], - "types": parsed["types"], - "status": parsed["status"], - "error": parsed["error"], - "descriptor_names": parsed["descriptor_names"], - "sample": sample, - "_all_strings": parsed["strings"], - }) - return out - - -def _bucket(size): - if size < 1024: - return "<1K" - if size < 4096: - return "1-4K" - if size < 16384: - return "4-16K" - if size < 65536: - return "16-64K" - if size < 1048576: - return "64K-1M" - return ">=1M" - - -def summarise(rows, records, span, zero, unread, mode): - rbf0_stored = sum(r["stored"] for r in records) - rbf0_inflated = sum(r["size"] for r in records) - all_strings = [s for r in records for s in r["_all_strings"]] - keywords = collections.Counter() - for word in KEYWORDS: - keywords[word] = sum(1 for s in all_strings if word in s.lower()) - distinct_strings = {s for s in all_strings} - return { - "mode": mode, - "streams": len(rows), - "compressed_bytes": sum(r["stored"] for r in rows), - "inflated_bytes": sum(r["size"] for r in rows), - "span": span, - "zero_padding": zero, - "unread_bytes": unread, - "readable_fraction": round(sum(r["stored"] for r in rows) / span, 6) if span else 0.0, - "rbf0": { - "resources": len(records), - "single_stream": sum(1 for r in records if r["chunks"] == 1), - "multi_chunk": sum(1 for r in records if r["chunks"] > 1), - "max_chunks": max((r["chunks"] for r in records), default=0), - "stored_bytes": rbf0_stored, - "inflated_bytes": rbf0_inflated, - "layouts": dict(collections.Counter(r["layout"] for r in records)), - "status": dict(collections.Counter(r["status"] for r in records)), - "by_root": dict(collections.Counter(r["root"] for r in records)), - "size_buckets": dict(collections.Counter(_bucket(r["size"]) for r in records)), - "descriptors": sum(r["descriptors"] for r in records), - "elements": sum(r["elements"] for r in records), - "values": sum(r["values"] for r in records), - "texts": sum(r["texts"] for r in records), - "strings": len(all_strings), - "distinct_strings": len(distinct_strings), - "path_occurrences": sum(1 for s in all_strings if "/" in s), - "path_strings": sum(1 for s in distinct_strings if "/" in s), - "identifier_strings": sum(1 for s in all_strings if IDENT.fullmatch(s) is not None), - "ints": sum(r["ints"] for r in records), - "floats": sum(r["floats"] for r in records), - "max_depth": max((r["depth"] for r in records), default=0), - "attribute_mismatches": sum(r["attributes"] for r in records), - "keyword_occurrences": dict(keywords), - }, - } - - -def scan_rpf(path, start=None, limit=None, progress=None, string_limit=16): - """Walk an RPF9 data area and return (rows, records, summary). No table of contents is read or decrypted.""" - rows = [] - if os.path.getsize(path) == 0: - raise ValueError("empty file") - with open(path, "rb") as fh, mmap.mmap(fh.fileno(), 0, access=mmap.ACCESS_READ) as mm: - size = len(mm) - first = struct.unpack_from("= 8 else 0 - pos = start if start is not None else first - if not 0 <= pos <= size: - raise ValueError("start offset is outside the archive") - end = min(size, pos + limit) if limit else size - span_start = pos - last, zero, unread = pos, 0, 0 - while pos < end: - match = ZHDR.search(mm, pos, end) - if not match: - break - s = match.start() - if mm[s:s + 3] == b"KB2": - blen = (_u32(mm, s + 4) or 0) + 8 - w, h = _u32(mm, s + 0x14), _u32(mm, s + 0x18) - if not (64 <= blen <= end - s and w and h and 16 <= w <= 8192 and 16 <= h <= 8192): - pos = s + 1 - continue - gap_zero, gap_unread = gap_split(mm, last, s) - zero += gap_zero - unread += gap_unread - rows.append({"offset": s, "stored": blen, "size": blen, "head": mm[s:s + 8]}) - last = pos = s + blen - continue - d = zlib.decompressobj() - chunks, p = [], s - try: - while not d.eof and p < end: # inside the --limit window, as in story_index (#712) - block = mm[p:min(p + (1 << 20), end)] - chunks.append(d.decompress(block)) - p += len(block) - if d.unused_data or d.eof: - break - out = b"".join(chunks) + d.flush() - except zlib.error: - pos = s + 1 - continue - if not d.eof or len(out) < 64: - pos = s + 1 - continue - used = p - s - len(d.unused_data) - gap_zero, gap_unread = gap_split(mm, last, s) - zero += gap_zero - unread += gap_unread - rows.append(_row(out, s, used)) - last = pos = s + used - if progress and len(rows) % 2000 == 0: - progress(len(rows), pos, end) - gap_zero, gap_unread = gap_split(mm, last, end) - zero += gap_zero - unread += gap_unread - mspan = end - span_start - with ArchiveReader(path) as reader: - records = resources_from_rows(rows, reader.read, check_gap=True, string_limit=string_limit) - summary = summarise(rows, records, mspan, zero, unread, "rpf9") - summary["archive"] = path - return rows, records, summary - - -def carved_streams(path): - for name in sorted(os.listdir(path)): - full = os.path.join(path, name) - # rpf9_carve.py's index.json and any .csv report sit next to the streams; they are not payloads. - if not name.lower().endswith((".json", ".csv")) and os.path.isfile(full): - yield name, full - - -def scan_dir(path, string_limit=16): - """Index already-carved files. Sorting by a leading hexadecimal file name keeps archive order.""" - entries = [] - unnamed = [] - for name, full in carved_streams(path): - with open(full, "rb") as f: - data = f.read() - match = re.match(r"([0-9a-fA-F]{6,})", name) - if match: - entries.append((int(match.group(1), 16), data)) - else: - unnamed.append(data) - next_offset = max((e[0] for e in entries), default=-1) + 1 - for data in unnamed: - entries.append((next_offset, data)) - next_offset += 1 - entries.sort(key=lambda e: e[0]) - rows = [_row(data, offset, len(data)) for offset, data in entries] - by_row = {id(row): data for row, (_, data) in zip(rows, entries)} - records = resources_from_rows(rows, lambda row: by_row[id(row)], check_gap=False, - string_limit=string_limit) - summary = summarise(rows, records, sum(len(d) for _, d in entries), 0, 0, "directory") - summary["directory"] = path - return rows, records, summary - - -def write_json(path, payload): - """Write ``payload`` as JSON, staging regular files via a sibling temporary file.""" - destination = os.path.realpath(path) - try: - st = os.stat(destination) - except FileNotFoundError: - st = None - if st is not None and not stat.S_ISREG(st.st_mode): - with open(destination, "w", encoding="utf-8", newline="\n") as f: - json.dump(payload, f, indent=1) - return - if st is not None: - # Fail before staging when an existing regular destination is not writable. - os.close(os.open(destination, os.O_WRONLY)) - staged_path = None - try: - with tempfile.NamedTemporaryFile( - mode="w", encoding="utf-8", newline="\n", delete=False, - dir=os.path.dirname(destination) or ".", prefix=".rbf0_index-", suffix=".tmp", - ) as staged: - staged_path = staged.name - json.dump(payload, staged, indent=1) - if os.name != "nt": - os.chmod(staged_path, published_mode(destination)) - replace_retry(staged_path, destination) - staged_path = None - finally: - if staged_path is not None: - try: - os.unlink(staged_path) - except OSError: - pass - - -def write_output(path, records, summary, all_strings=False): - """Write CSV or JSON, chosen by the extension.""" - ext = os.path.splitext(path)[1].lower() - if ext == ".json": - docs = [] - for r in records: - doc = {k: v for k, v in r.items() if k not in ("_all_strings", "sample", "strings")} - doc["string_count"] = r["strings"] - doc["sample_strings"] = r["_all_strings"] if all_strings else r["sample"] - doc["sample_truncated"] = not all_strings and r["strings"] > len(r["sample"]) - docs.append(doc) - write_json(path, {"summary": summary, "files": docs}) - return - with open(path, "w", encoding="utf-8", newline="") as f: - writer = csv.writer(f, lineterminator="\n") - writer.writerow(COLUMNS) - for r in records: - sample = "; ".join(r["sample"]) - if r["strings"] > len(r["sample"]): - sample += f" (+{r['strings'] - len(r['sample'])} more)" - writer.writerow([ - f"0x{r['offset']:x}", r["stored"], r["size"], r["chunks"], r["layout"], r["root"], - r["descriptors"], r["elements"], r["values"], r["texts"], r["strings"], r["ints"], - r["floats"], r["depth"], r["status"], sample]) - - -def offset(text): - """--start: 0 or more, decimal or 0x hex.""" - try: - value = int(text, 0) - except ValueError: - raise argparse.ArgumentTypeError("must be 0 or more") from None - if value < 0: - raise argparse.ArgumentTypeError("must be 0 or more") - return value - - -def byte_count(text): - """--limit: at least 1; 0 used to mean no limit and a negative value silently scanned less.""" - try: - value = int(text, 0) - except ValueError: - raise argparse.ArgumentTypeError("must be at least 1") from None - if value < 1: - raise argparse.ArgumentTypeError("must be at least 1") - return value - - -def same_output_path(first, second): - """True when writing ``second`` would truncate ``first`` (same file, path or hard link).""" - if os.path.normcase(os.path.realpath(first)) == os.path.normcase(os.path.realpath(second)): - return True - try: - return os.path.samefile(first, second) - except OSError: - return False - - -def main(): - ap = argparse.ArgumentParser(description=__doc__.splitlines()[0]) - ap.add_argument("source", help="an .rpf archive or a directory of carved streams") - ap.add_argument("out", help="output path ending in .csv or .json") - ap.add_argument("--start", type=offset, help="first byte to scan (default: the RPF data start)") - ap.add_argument("--limit", type=byte_count, help="number of bytes to scan") - ap.add_argument("--strings", type=int, default=16, help="readable strings kept per resource (default 16)") - ap.add_argument("--all-strings", action="store_true", help="write every readable string to JSON (game data)") - ap.add_argument("--quiet", action="store_true") - a = ap.parse_args() - if same_output_path(a.source, a.out): - ap.error("output must not overwrite the source") - if a.strings < 0: - ap.exit(2, f"{ap.prog}: error: argument --strings: must be 0 or more\n") - if os.path.isdir(a.source) and (a.start is not None or a.limit is not None): - ap.error("--start and --limit apply to a single archive, not a directory") - if os.path.isdir(a.out): - ap.error(f"{a.out} is a folder, not a .csv or .json file") - folder = os.path.dirname(os.path.abspath(a.out)) - if not os.path.isdir(folder): - ap.error(f"{folder} is not a folder, so {a.out} cannot be written") - limit = None if a.all_strings else a.strings - try: - if os.path.isdir(a.source): - manifest = os.path.join(a.source, "index.json") - if same_output_path(manifest, a.out) or (os.path.isfile(a.out) and any( - same_output_path(path, a.out) for _, path in carved_streams(a.source))): - ap.error(f"output would overwrite a carve input: {a.out}") - rows, records, summary = scan_dir(a.source, string_limit=limit) - else: - def progress(n, pos, end): - if not a.quiet: - print(f"[{pos / max(1, end):6.1%}] {n} streams", flush=True) - rows, records, summary = scan_rpf(a.source, a.start, a.limit, progress, string_limit=limit) - except ValueError as e: - sys.exit(f"{a.source}: {e}") - except OSError as e: - sys.exit(f"{a.source}: {e.strerror or e}") - write_output(a.out, records, summary, all_strings=a.all_strings) - if not a.quiet: - s = summary["rbf0"] - print(f"{s['resources']} RBF0 resources, {s['multi_chunk']} multi-chunk, " - f"{s['inflated_bytes']} inflated bytes -> {a.out}") - print(f"roots: {len(s['by_root'])} classes; status: {s['status']}") - return 0 - - -if __name__ == "__main__": - try: # a redirected stdout is strict ANSI code page under -I; write '?' for what it cannot encode - sys.stdout.reconfigure(errors="replace") - except (AttributeError, ValueError, OSError): - pass - sys.exit(main()) diff --git a/tools/rbf0_tree.py b/tools/rbf0_tree.py deleted file mode 100644 index 0a69d5db4..000000000 --- a/tools/rbf0_tree.py +++ /dev/null @@ -1,767 +0,0 @@ -"""Decode RBF0 resources into strict JSON trees, with an optional CSV node table and simple XML rendering. - -RBF0 is RAGE's binary form of an XML data file: one record stream with an inline descriptor table. This tool reads -inflated RBF0 resources from a carve directory or a single resource file, joins the 64 KiB continuation streams of -one logical resource, and builds the element tree. It reports unknown descriptors, unknown record types, truncated -payloads and structural violations as errors instead of guessing a value. - -The output contains names and payloads taken from the archive, so treat it as game data: keep it out of git and do -not attach it to an issue or a pull request. Format facts and aggregate counts are in docs/rbf0.md. - -Usage: - python -I tools/rbf0_tree.py [--csv PATH] [--xml DIR] [--root NAME]... [--offset 0x...] [--limit N] - -The input directory holds inflated zlib streams or complete RBF0 resources. A file name that starts with a -hexadecimal archive offset is used to order and label the resource, as in the rbf0_index.py carve layout. -""" -import argparse -import collections -import csv -import json -import math -import os -import re -import struct -import sys -import tempfile -from contextlib import suppress -from xml.etree import ElementTree as ET - -sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) - -import rbf0_index # noqa: E402 -from file_mode import published_mode # noqa: E402 - -MAGIC = rbf0_index.MAGIC -PROLOGUE = rbf0_index.PROLOGUE -MAX_CHUNK = rbf0_index.MAX_CHUNK -MAX_CHUNKS = rbf0_index.MAX_CHUNKS -MAX_BYTES = rbf0_index.MAX_BYTES -RbfError = rbf0_index.RbfError -TYPE_NAMES = {0x00: "open", 0x10: "int", 0x20: "true", 0x30: "false", 0x40: "float", - 0x50: "vec3", 0x60: "string"} -VALUE_TYPES = {0x10: "int", 0x20: "bool", 0x30: "bool", 0x40: "float", 0x50: "vec3", 0x60: "string"} -XML_BAD = re.compile(r"[^\u0009\u000a\u000d\u0020-\ud7ff\ue000-\ufffd\U00010000-\U0010ffff]") -CSV_COLUMNS = ["resource", "root", "status", "parent", "slot", "sibling", "child_index", "depth", "kind", - "name", "descriptor", "offset", "end", "attrs", "children", "content_count", "type", - "length", "nul", "utf8", "value", "source"] - - -def _utf8(raw): - """Return (text, valid). Invalid bytes become U+FFFD and are counted, never silently accepted.""" - try: - return raw.decode("utf-8"), True - except UnicodeDecodeError: - return raw.decode("utf-8", "replace"), False - - -def _render(value): - """A stable textual form for XML and for JSON consumers that want one scalar spelling.""" - if isinstance(value, bool): - return "true" if value else "false" - if isinstance(value, float): - if math.isnan(value): - return "nan" - if math.isinf(value): - return "inf" if value > 0 else "-inf" - return repr(value) - if isinstance(value, (list, tuple)): - return "[" + ", ".join(_render(v) for v in value) + "]" - return str(value) - - -class TreeError(RbfError): - """A malformed or truncated RBF0 record stream.""" - - -class SelectionError(ValueError): - """An invalid resource offset or limit.""" - - -class Parser: - """One RBF0 resource. `parse()` always returns a document, with a partial tree on failure.""" - - def __init__(self, data, source="", offset=0, chunks=1): - self.data = data - self.source = source - self.offset = offset - self.chunks = chunks - self.wide = data[4:8] == PROLOGUE - self.p = 8 if self.wide else 4 - self.scalar = 8 if self.wide else 4 - self.descs = [] - self.stack = [] - self.root = None - self.status = "ok" - self.error = "" - self.error_offset = None - self.counts = collections.Counter() - self.descriptor_names = set() - self.attribute_mismatches = 0 - self.attribute_order_violations = 0 - self.text_after_child = 0 - self.text_before_child = 0 - self.value_after_child = 0 - self.invalid_utf8 = 0 - self.max_depth = 0 - - def take(self, n, what): - if self.p + n > len(self.data): - raise TreeError(f"{what} truncated", self.p, truncated=True) - start = self.p - self.p += n - return self.data[start:self.p] - - def _descriptor(self, index, kind, at): - if index == len(self.descs): - n = struct.unpack(" len(self.descs): - raise TreeError(f"descriptor index {index} of {len(self.descs)}", at) - desc = self.descs[index] - desc["uses"] += 1 - key = TYPE_NAMES.get(kind, f"0x{kind:02x}") - desc["types"][key] = desc["types"].get(key, 0) + 1 - return desc - - def _attach(self, frame, node): - node["depth"] = frame["depth"] + 1 - if frame["node"]["kind"] != "element": - raise TreeError("record outside an element", node["offset"]) - if node["kind"] == "value" and frame["attrs_seen"] < frame["attrs_declared"]: - if frame["content_started"]: - frame["node"]["attribute_order_violation"] = True - self.attribute_order_violations += 1 - frame["node"]["attributes"].append(node) - frame["node"]["attrs_actual"] += 1 - frame["attrs_seen"] += 1 - return - if node["kind"] in ("element", "text") and frame["attrs_seen"] < frame["attrs_declared"]: - frame["node"]["attribute_order_violation"] = True - self.attribute_order_violations += 1 - frame["content_started"] = True - frame["node"]["content"].append(node) - frame["node"]["content_count"] += 1 - if node["kind"] == "element": - frame["node"]["children"] += 1 - if frame["text_seen"]: - frame["node"]["text_before_child"] = True - self.text_before_child += 1 - frame["child_seen"] = True - elif node["kind"] == "value": - if frame["child_seen"]: - frame["node"]["value_after_child"] = True - self.value_after_child += 1 - elif node["kind"] == "text": - if frame["child_seen"]: - frame["node"]["text_after_child"] = True - self.text_after_child += 1 - if frame["text_seen"]: - frame["node"]["multiple_text"] = True - frame["text_seen"] = True - - def parse(self): - data = self.data - if len(data) < 4 or data[:4] != MAGIC: - raise TreeError("not an RBF0 stream", 0) - try: - while self.p < len(data): - self.record_offset = self.p - at = self.p - index = self.take(1, "record index")[0] - kind = self.take(1, "record type")[0] - if index == 0xFF: - if kind != 0xFF: - raise TreeError("close tag is not FF FF", at) - if not self.stack: - raise TreeError("close without an open element", at) - frame = self.stack.pop() - frame["node"]["end"] = self.p - if frame["attrs_seen"] < frame["attrs_declared"]: - frame["node"]["attribute_mismatch"] = True - self.attribute_mismatches += 1 - if not self.stack: - self.root = frame["node"] - break - continue - if index == 0xFD: - if kind != 0xFF: - raise TreeError("text tag is not FD FF", at) - n = struct.unpack(" MAX_CHUNK or nxt["head"][:4] in (MAGIC, b"PSIN"): - break - blob += read(nxt) - chunks += 1 - doc = parse_resource(blob, rows[i]["name"], rows[i]["offset"], chunks) - if doc["status"] != "truncated": - break - if wanted and doc["root_name"] not in wanted: - continue - docs.append(doc) - if limit is not None and len(docs) >= limit: - break - if progress: - progress(len(docs), len(starts)) - summary = _summary(docs) - summary["source"] = os.path.abspath(source) - return docs, summary - - -def _summary(docs): - roots = collections.Counter(d["root_name"] for d in docs) - layouts = collections.Counter(d["layout"] for d in docs) - status = collections.Counter(d["status"] for d in docs) - counts = collections.Counter() - for d in docs: - counts.update(d["counts"]) - by_depth = collections.Counter() - children_hist = collections.Counter() - content_hist = collections.Counter() - attr_hist = collections.Counter() - nodes = 0 - tree_roots = 0 - leaf_elements = empty_elements = text_only_elements = 0 - max_children = 0 - for d in docs: - root = d["tree"] - if root is None: - continue - tree_roots += 1 - stack = [root] - while stack: - node = stack.pop() - nodes += 1 - if node["kind"] != "element": - continue - by_depth[node["depth"]] += 1 - attr_hist[node["attrs_declared"]] += 1 - child_count = node.get("children", sum(1 for c in node["content"] if c["kind"] == "element")) - children_hist[child_count] += 1 - content_hist[node.get("content_count", len(node["content"]))] += 1 - max_children = max(max_children, child_count) - if child_count == 0: - leaf_elements += 1 - content = node["content"] - if not content: - empty_elements += 1 - elif all(c["kind"] == "text" for c in content): - text_only_elements += 1 - for child in content: - stack.append(child) - for attribute in node["attributes"]: - stack.append(attribute) - tree_elements = sum(children_hist.values()) - edges = tree_elements - tree_roots - return { - "resources": len(docs), - "ok": status.get("ok", 0), - "bad": status.get("bad", 0), - "truncated": status.get("truncated", 0), - "trailing": status.get("trailing", 0), - "layouts": dict(layouts), - "roots": dict(roots), - "descriptors": sum(d["descriptor_count"] for d in docs), - "distinct_descriptor_names": len({x["name"] for d in docs for x in d["descriptors"]}), - "elements": counts.get("elements", 0), - "values": counts.get("values", 0), - "texts": counts.get("texts", 0), - "strings": counts.get("strings", 0), - "ints": counts.get("ints", 0), - "floats": counts.get("floats", 0), - "bools": counts.get("bools", 0), - "vec3": counts.get("vec3", 0), - "nodes": nodes, - "max_depth": max((d["max_depth"] for d in docs), default=0), - "elements_by_depth": {str(k): v for k, v in sorted(by_depth.items())}, - "children_histogram": {str(k): v for k, v in sorted(children_hist.items())}, - "content_length_histogram": {str(k): v for k, v in sorted(content_hist.items())}, - "attribute_count_histogram": {str(k): v for k, v in sorted(attr_hist.items())}, - "leaf_elements": leaf_elements, - "empty_elements": empty_elements, - "text_only_elements": text_only_elements, - "parent_child_edges": edges, - "max_children": max_children, - "mean_children": round(edges / tree_elements, 4) if tree_elements else 0.0, - "attribute_mismatches": sum(d["attribute_mismatches"] for d in docs), - "attribute_order_violations": sum(d["attribute_order_violations"] for d in docs), - "text_after_child": sum(d["text_after_child"] for d in docs), - "value_after_child": sum(d["value_after_child"] for d in docs), - "invalid_utf8": sum(d["invalid_utf8"] for d in docs), - "status": dict(status), - } - - -def _xml_safe(text): - return XML_BAD.sub("\ufffd", text) - - -def _xml_node(parent, node, tag=None): - if node["kind"] == "element": - attrs = {"name": _xml_safe(node["name"]), "descriptor": str(node["descriptor"]), - "offset": f"0x{node['offset']:x}", "attrs": str(node["attrs_declared"])} - if node.get("end") is not None: - attrs["end"] = f"0x{node['end']:x}" - el = ET.SubElement(parent, "node", attrs) - for value in node["attributes"]: - _xml_node(el, value, "attr") - for child in node["content"]: - _xml_node(el, child) - return el - tag = tag or ("text" if node["kind"] == "text" else "value") - attrs = {"offset": f"0x{node['offset']:x}"} - if node["kind"] == "value": - attrs.update({"name": _xml_safe(node["name"]), "descriptor": str(node["descriptor"]), - "type": node["type"]}) - if node.get("float_special") is not None: - text = _render(node["float_special"]) - else: - text = _render(node["value"]) - else: - attrs["length"] = str(node["length"]) - text = node["text"] - if node.get("utf8_valid") is False: - attrs["utf8"] = "invalid" - el = ET.SubElement(parent, tag, attrs) - el.text = _xml_safe(text) - return el - - -def write_xml(directory, docs): - """Write one generic XML file per resource. Element names are fixed, so any descriptor name is safe.""" - os.makedirs(directory, exist_ok=True) - paths = [] - used = set() - for i, doc in enumerate(docs): - root = ET.Element("rbf0", { - "root": _xml_safe(doc["root_name"]), "layout": doc["layout"], - "offset": f"0x{doc['offset']:x}", - "size": str(doc["size"]), "chunks": str(doc["chunks"]), - "descriptors": str(doc["descriptor_count"]), "status": doc["status"]}) - if doc["error"]: - root.set("error", _xml_safe(doc["error"])) - if doc["tree"] is not None: - _xml_node(root, doc["tree"]) - ET.indent(root, space=" ") - name = f"{doc['offset']:08x}.xml" - if name in used: - name = f"{doc['offset']:08x}-{i:04d}.xml" - used.add(name) - path = os.path.join(directory, name) - # XML readers normalize literal carriage returns. Escape them after serializing ordinary XML text. - xml = ET.tostring(root, encoding="utf-8", xml_declaration=True).replace(b"\r", b" ") - with open(path, "wb") as f: - f.write(xml) - paths.append(path) - return paths - - -def write_csv(path, docs): - """Write one row per tree node. Parent offsets and sibling slots make the flat table reconstructable. - - The rows carry names and payloads, so the file is game data and must stay local. - """ - with open(path, "w", encoding="utf-8", newline="") as f: - writer = csv.writer(f, lineterminator="\n") - writer.writerow(CSV_COLUMNS) - for doc in docs: - root = doc["tree"] - if root is None: - continue - resource = f"0x{doc['offset']:x}" - stack = [(root, "", "", "", "")] - while stack: - node, parent, slot, sibling, child_index = stack.pop() - if node["kind"] == "element": - end = f"0x{node['end']:x}" if node.get("end") is not None else "" - writer.writerow([ - resource, doc["root_name"], doc["status"], parent, slot, sibling, child_index, - node["depth"], node["kind"], node["name"], node["descriptor"], - f"0x{node['offset']:x}", end, node["attrs_declared"], node["children"], - node["content_count"], "", "", "", "", "", doc["source"]]) - content = node["content"] - child_indices = [] - next_child = 0 - for c in content: - if c["kind"] == "element": - child_indices.append(str(next_child)) - next_child += 1 - else: - child_indices.append("") - for i in range(len(content) - 1, -1, -1): - stack.append((content[i], f"0x{node['offset']:x}", "content", str(i), - child_indices[i])) - for i in range(len(node["attributes"]) - 1, -1, -1): - stack.append((node["attributes"][i], f"0x{node['offset']:x}", "attribute", - str(i), "")) - elif node["kind"] == "value": - if node.get("float_special") is not None: - value = _render(node["float_special"]) - else: - value = _render(node["value"]) - writer.writerow([ - resource, doc["root_name"], doc["status"], parent, slot, sibling, child_index, - node["depth"], node["kind"], node["name"], node["descriptor"], - f"0x{node['offset']:x}", "", "", "", "", node["type"], - node.get("byte_length", ""), - "" if "nul_terminated" not in node else int(node["nul_terminated"]), - "" if "utf8_valid" not in node else int(node["utf8_valid"]), value, doc["source"]]) - else: - writer.writerow([ - resource, doc["root_name"], doc["status"], parent, slot, sibling, child_index, - node["depth"], node["kind"], "", "", f"0x{node['offset']:x}", "", - "", "", "", "text", node["length"], - int(node["nul_terminated"]), int(node["utf8_valid"]), node["text"], doc["source"]]) - - -def write_json(path, docs, summary): - """Replace the report only after the full JSON has been written, keeping its permission bits.""" - directory = os.path.dirname(os.path.abspath(path)) - temp = None - try: - with tempfile.NamedTemporaryFile(mode="w", encoding="utf-8", newline="\n", dir=directory, - prefix=".rbf0_tree-", suffix=".tmp", delete=False) as f: - temp = f.name - json.dump({"tool": "rbf0_tree", "format": 1, "summary": summary, "resources": docs}, - f, indent=1, ensure_ascii=False, allow_nan=False) - os.chmod(temp, published_mode(path)) # NamedTemporaryFile creates 0600 - os.replace(temp, path) - except BaseException: - if temp is not None: - with suppress(OSError): - # The staging file may have inherited a read-only destination's mode; make it deletable - # first, or Windows strands it beside the report when the replace fails. - os.chmod(temp, 0o600) - os.unlink(temp) - raise - - -def same_output_path(first, second): - if os.path.normcase(os.path.realpath(first)) == os.path.normcase(os.path.realpath(second)): - return True - try: - return os.path.samefile(first, second) - except OSError: - return False - - -def main(argv=None): - ap = argparse.ArgumentParser(description=__doc__.splitlines()[0]) - ap.add_argument("source", help="a carve directory, a complete resource, or a single RBF0 stream") - ap.add_argument("out", help="JSON output path") - ap.add_argument("--csv", metavar="PATH", help="also write one flat CSV row per tree node (game data)") - ap.add_argument("--xml", metavar="DIR", help="also write one generic XML file per resource into DIR") - ap.add_argument("--root", action="append", metavar="NAME", help="keep only this root schema (repeatable)") - ap.add_argument("--offset", type=lambda s: int(s, 0), help="decode only the resource at this archive offset") - ap.add_argument("--limit", type=int, help="stop after this many selected resources") - ap.add_argument("--quiet", action="store_true") - args = ap.parse_args(argv) - # The reports are written after the decode: an out or --csv naming the source used to replace it, and the - # same file for both left only the CSV. - if args.csv and same_output_path(args.out, args.csv): - ap.error("out and --csv must be different files") - if os.path.isfile(args.source): - for flag, path in (("out", args.out), ("--csv", args.csv)): - if path and same_output_path(path, args.source): - ap.error(f"{flag} would overwrite the source {args.source}") - elif os.path.isdir(args.source): - # A carve folder: out or --csv naming one of its streams used to replace that stream, and --xml on the - # folder itself put the XML files among the streams, where the next run read them as resources. - try: - streams = [full for full in (os.path.join(args.source, n) for n in os.listdir(args.source)) - if os.path.isfile(full) and not full.lower().endswith((".json", ".csv"))] - except OSError: - streams = [] # decode_source reports the unreadable folder - for flag, path in (("out", args.out), ("--csv", args.csv)): - if path and os.path.exists(path) and any(same_output_path(path, s) for s in streams): - ap.error(f"{flag} would overwrite the stream {path} in the source folder") - if args.xml and same_output_path(args.xml, args.source): - ap.error("--xml must not be the source folder: its XML files would be read as streams") - - def progress(n, total): - if not args.quiet and (n % 100 == 0 or n == total): - print(f"[{n}/{total}] resources", flush=True) - - path = args.source - try: - docs, summary = decode_source(path, roots=args.root, offset=args.offset, - limit=args.limit, progress=progress) - path = args.out - write_json(path, docs, summary) - if args.csv: - path = args.csv - write_csv(path, docs) - paths = [] - if args.xml: - path = args.xml - paths = write_xml(path, docs) - except SelectionError as error: - ap.error(str(error)) - except RecursionError: - print(f"{path}: tree exceeds the export depth limit", file=sys.stderr) - return 1 - except OSError as error: - print(f"{path}: {error.strerror or error}", file=sys.stderr) - return 1 - if not args.quiet: - print(f"{summary['resources']} resources: {summary['ok']} ok, {summary['bad']} bad, " - f"{summary['truncated']} truncated, {summary['trailing']} trailing") - print(f"{summary['elements']} elements, {summary['texts']} texts, {summary['strings']} strings, " - f"{summary['descriptors']} descriptors -> {args.out}") - print(f"tree: {summary['parent_child_edges']} parent-child edges, {summary['leaf_elements']} leaves, " - f"{summary['empty_elements']} empty, max depth {summary['max_depth']}, " - f"max children {summary['max_children']}") - if args.csv: - print(f"node CSV -> {args.csv}") - if paths: - print(f"{len(paths)} XML files -> {args.xml}") - return 0 if summary["ok"] == summary["resources"] else 1 - - -if __name__ == "__main__": - try: # a redirected stdout is strict ANSI code page under -I; write '?' for what it cannot encode - sys.stdout.reconfigure(errors="replace") - except (AttributeError, ValueError, OSError): - pass - sys.exit(main()) diff --git a/tools/rdna2_decode.py b/tools/rdna2_decode.py deleted file mode 100644 index e92ed73d8..000000000 --- a/tools/rdna2_decode.py +++ /dev/null @@ -1,1454 +0,0 @@ -"""Pure-Python RDNA2 (GFX10.1 / GFX10.3) binary ISA decoder (no LLVM dependency). - -Decodes raw RDNA2 machine code directly into either: - - `shader_ir`-compatible instruction dictionaries (`decode_bytes`), or - - `shader_ir`-compatible `.s` disassembly text with `; encoding: [...]` (`disasm_bytes`). - -Opcode tables in `tools/rdna2_isa_tables.py` are derived from AMD's MIT-licensed -machine-readable RDNA2 ISA specification (`amdgpu_isa_rdna2.xml`), plus the seven -gfx1013 legacy/waveid instructions documented in `docs/isa_coverage.md`. - -Standard library only; no game data, no external tools. -""" -from __future__ import annotations - -import json -import os -import struct -import sys -from collections.abc import Iterator -from io import StringIO - -HERE = os.path.dirname(os.path.abspath(__file__)) -if HERE not in sys.path: - sys.path.insert(0, HERE) - -import rdna2_isa_tables as T # noqa: E402 - -with open(os.path.join(HERE, "gfx10_formats.json"), encoding="utf-8") as _f: - _GFX10_FORMATS = {int(k): v for k, v in json.load(_f).items()} - -# Inline float constants (codes 240..248) matching LLVM AMDGPUInstPrinter. -_INLINE_FLOAT = { - 240: 0.5, - 241: -0.5, - 242: 1.0, - 243: -1.0, - 244: 2.0, - 245: -2.0, - 246: 4.0, - 247: -4.0, - 248: 0.15915494, # 1 / (2 * pi) -} - -_INLINE_FLOAT_STR = { - 240: "0.5", - 241: "-0.5", - 242: "1.0", - 243: "-1.0", - 244: "2.0", - 245: "-2.0", - 246: "4.0", - 247: "-4.0", - 248: "0.15915494", -} - -# VOP2 instructions that always carry a trailing 32-bit literal constant. -_VOP2_MANDATORY_LITERAL = frozenset({ - 0x20, # v_madmk_f32 (gfx1013) - 0x21, # v_madak_f32 (gfx1013) - 0x2C, # v_fmamk_f32 - 0x2D, # v_fmaak_f32 - 0x37, # v_fmamk_f16 - 0x38, # v_fmaak_f16 -}) - -# SOPK instructions that always carry a trailing 32-bit literal constant. -_SOPK_MANDATORY_LITERAL = frozenset({ - 0x15, # s_setreg_imm32_b32 -}) - -_MIMG_DIMS = { - 0: "SQ_RSRC_IMG_1D", - 1: "SQ_RSRC_IMG_2D", - 2: "SQ_RSRC_IMG_3D", - 3: "SQ_RSRC_IMG_CUBE", - 4: "SQ_RSRC_IMG_1D_ARRAY", - 5: "SQ_RSRC_IMG_2D_ARRAY", - 6: "SQ_RSRC_IMG_2D_MSAA", - 7: "SQ_RSRC_IMG_2D_MSAA_ARRAY", -} - -_MIMG_DIM_COORDS = {0: 1, 1: 2, 2: 3, 3: 3, 4: 2, 5: 3, 6: 3, 7: 4} -_MIMG_GRAD_COORDS = {0: 1, 1: 2, 2: 3, 3: 2, 4: 1, 5: 2, 6: 2, 7: 2} - -_SDWA_SELS = { - 0: "BYTE_0", - 1: "BYTE_1", - 2: "BYTE_2", - 3: "BYTE_3", - 4: "WORD_0", - 5: "WORD_1", - 6: "DWORD", -} -_SDWA_UNUSED = {0: "UNUSED_PAD", 1: "UNUSED_SEXT", 2: "UNUSED_PRESERVE"} -_OMOD_MODS = {1: "mul:2", 2: "mul:4", 3: "div:2"} - -_HWREG_NAMES = { - 1: "HW_REG_MODE", - 2: "HW_REG_STATUS", - 3: "HW_REG_TRAPSTS", - 4: "HW_REG_HW_ID1", - 5: "HW_REG_GPR_ALLOC", - 6: "HW_REG_LDS_ALLOC", - 7: "HW_REG_IB_STS", - 15: "HW_REG_SH_MEM_BASES", - 16: "HW_REG_TBA_LO", - 17: "HW_REG_TBA_HI", - 18: "HW_REG_TMA_LO", - 19: "HW_REG_TMA_HI", - 20: "HW_REG_FLAT_SCR_LO", - 21: "HW_REG_FLAT_SCR_HI", - 22: "HW_REG_XNACK_MASK", - 23: "HW_REG_HW_ID2", - 24: "HW_REG_POPS_PACKER", - 26: "HW_REG_SHADER_CYCLES", -} - -_SENDMSG_NAMES = { - 1: "MSG_INTERRUPT", - 2: "MSG_GS", - 3: "MSG_GS_DONE", - 4: "MSG_SAVEWAVE", - 5: "MSG_STALL_WAVE_GEN", - 6: "MSG_HALT_WAVES", - 7: "MSG_ORDERED_PS_DONE", - 8: "MSG_EARLY_PRIM_DEALLOC", - 9: "MSG_GS_ALLOC_REQ", - 10: "MSG_GET_DOORBELL", - 11: "MSG_GET_DDID", - 15: "MSG_SYSMSG", -} - -_GS_OPS = {0: "GS_OP_NOP", 1: "GS_OP_CUT", 2: "GS_OP_EMIT", 3: "GS_OP_EMIT_CUT"} - -# SOPP branch instructions (16-bit signed word offset relative to next PC). -_SOPP_BRANCHES = frozenset({ - "s_branch", "s_cbranch_scc0", "s_cbranch_scc1", "s_cbranch_vccz", "s_cbranch_vccnz", - "s_cbranch_execz", "s_cbranch_execnz", "s_cbranch_cdbgsys", "s_cbranch_cdbguser", - "s_cbranch_cdbgsys_or_user", "s_cbranch_cdbgsys_and_user", -}) - -# SOPP instructions that take no operand at all. -_SOPP_NO_OPERAND = frozenset({ - "s_endpgm", "s_barrier", "s_icache_inv", "s_ttracedata", - "s_wakeup", "s_endpgm_saved", "s_code_end", "s_endpgm_ordered_ps_done", -}) - - -def _s16(v: int) -> int: - v &= 0xFFFF - return v - 0x10000 if v & 0x8000 else v - - -def _s12(v: int) -> int: - v &= 0xFFF - return v - 0x1000 if v & 0x800 else v - - -def _s21(v: int) -> int: - v &= 0x1FFFFF - return v - 0x200000 if v & 0x100000 else v - - -def _sreg(code: int, n: int) -> dict: - """Decode a scalar destination/source register code (0..127) with width `n` dwords.""" - if code <= 105: - if n <= 1: - return {"k": "sgpr", "r": code, "n": 1, "neg": False, "abs": False} - if code + n <= 106: - return {"k": "sgpr", "r": code, "n": n, "neg": False, "abs": False} - # LLVM VCCTuple spanning SGPRs into vcc_lo (106) / vcc_hi (107). - if code + n <= 108: - items = [] - for r in range(code, code + n): - if r <= 105: - items.append(r) - elif r == 106: - items.append("vcc_lo") - else: - items.append("vcc_hi") - return {"k": "slist", "r": items, "n": n} - return {"k": "sgpr", "r": code, "n": n, "neg": False, "abs": False} - if code == 106: - return {"k": "special", "t": "vcc" if n == 2 else "vcc_lo", "neg": False, "abs": False} - if code == 107: - return {"k": "special", "t": "vcc_hi", "neg": False, "abs": False} - if 108 <= code <= 123: - lo = code - 108 - t = f"ttmp{lo}" if n <= 1 else f"ttmp[{lo}:{lo + n - 1}]" - return {"k": "ttmp", "t": t} - if code == 124: - return {"k": "special", "t": "m0", "neg": False, "abs": False} - if code == 125: - return {"k": "special", "t": "null", "neg": False, "abs": False} - if code == 126: - return {"k": "special", "t": "exec" if n == 2 else "exec_lo", "neg": False, "abs": False} - if code == 127: - return {"k": "special", "t": "exec_hi", "neg": False, "abs": False} - return {"k": "raw", "t": f"sreg_{code}"} - - -def _vreg(reg: int, n: int = 1) -> dict: - return {"k": "vgpr", "r": reg & 0xFF, "n": max(1, n), "neg": False, "abs": False} - - -def _src(code: int, n: int, lit: int | None, *, neg: bool = False, absm: bool = False) -> dict: - """Decode a 9-bit RDNA2 source operand (0..511).""" - if code <= 127: - op = _sreg(code, n) - elif 128 <= code <= 192: - op = {"k": "imm", "v": code - 128} - elif 193 <= code <= 208: - op = {"k": "imm", "v": -(code - 192)} - elif code in _INLINE_FLOAT: - op = {"k": "fimm", "v": _INLINE_FLOAT[code], "abs": False} - elif code == 251: - op = {"k": "special", "t": "src_vccz", "neg": False, "abs": False} - elif code == 252: - op = {"k": "special", "t": "src_execz", "neg": False, "abs": False} - elif code == 253: - op = {"k": "special", "t": "src_scc", "neg": False, "abs": False} - elif code == 254: - op = {"k": "special", "t": "src_lds_direct", "neg": False, "abs": False} - elif code == 255: - op = {"k": "imm", "v": 0 if lit is None else lit} - elif 256 <= code <= 511: - op = _vreg(code - 256, n) - else: - op = {"k": "raw", "t": f"src_{code}"} - - if absm: - op["abs"] = True - if neg: - if op["k"] in ("imm", "fimm"): - # Preserve neg modifier on constants (same semantics as shader_ir.operand("neg(...)")). - op["neg"] = True - else: - op["neg"] = True - return op - - -def _vcc_operand(wave32: bool) -> dict: - return {"k": "special", "t": "vcc_lo" if wave32 else "vcc", "neg": False, "abs": False} - - -def _width(nregs: int, wave32: bool) -> int: - if nregs == -1: - return 1 if wave32 else 2 - return nregs - - -def _format_hwreg(simm16: int) -> str: - reg_id = simm16 & 0x3F - offset = (simm16 >> 6) & 0x1F - size = ((simm16 >> 11) & 0x1F) + 1 - rname = _HWREG_NAMES.get(reg_id, str(reg_id)) - if offset == 0 and size == 32: - return f"hwreg({rname})" - return f"hwreg({rname}, {offset}, {size})" - - -def _format_waitcnt(simm16: int) -> list[dict]: - # GFX10 s_waitcnt layout: vmcnt = bits[3:0] | (bits[15:14] << 4), expcnt = bits[6:4], lgkmcnt = bits[13:8]. - vmcnt = (simm16 & 0xF) | (((simm16 >> 14) & 0x3) << 4) - expcnt = (simm16 >> 4) & 0x7 - lgkmcnt = (simm16 >> 8) & 0x3F - parts = [] - if vmcnt != 63: - parts.append({"k": "special", "t": f"vmcnt({vmcnt})"}) - if expcnt != 7: - parts.append({"k": "special", "t": f"expcnt({expcnt})"}) - if lgkmcnt != 63: - parts.append({"k": "special", "t": f"lgkmcnt({lgkmcnt})"}) - if not parts: - parts.append({"k": "imm", "v": simm16}) - return parts - - -def _format_sendmsg(simm16: int) -> str: - msg_id = simm16 & 0xF - op = (simm16 >> 4) & 0x7 - stream = (simm16 >> 8) & 0x3 - mname = _SENDMSG_NAMES.get(msg_id) - if mname is None: - return f"sendmsg({simm16})" - if msg_id in (2, 3): - op_name = _GS_OPS.get(op, str(op)) - if op == 0: - return f"sendmsg({mname}|{op_name})" - return f"sendmsg({mname}|{op_name}|{stream})" - if op: - return f"sendmsg({mname}|{op})" - return f"sendmsg({mname})" - - -def _format_dpp16_ctrl(ctrl: int) -> str: - if ctrl <= 0xFF: - q = [(ctrl >> (2 * i)) & 3 for i in range(4)] - return f"quad_perm:[{q[0]},{q[1]},{q[2]},{q[3]}]" - if 0x101 <= ctrl <= 0x10F: - return f"row_shl:{ctrl - 0x100}" - if 0x111 <= ctrl <= 0x11F: - return f"row_shr:{ctrl - 0x110}" - if 0x121 <= ctrl <= 0x12F: - return f"row_ror:{ctrl - 0x120}" - if ctrl == 0x140: - return "row_mirror" - if ctrl == 0x141: - return "row_half_mirror" - if 0x150 <= ctrl <= 0x15F: - return f"row_share:{ctrl - 0x150}" - if 0x160 <= ctrl <= 0x16F: - return f"row_xmask:{ctrl - 0x160}" - return f"dpp_ctrl:0x{ctrl:x}" - - -def _format_ds_swizzle(offset16: int) -> str: - if (offset16 & 0x8000) == 0: - # Bitmask mode: bits [4:0] = and_mask, [9:5] = or_mask, [14:10] = xor_mask. - # Match LLVM's canonical aliases (SWAP, REVERSE, BROADCAST) before general BITMASK_PERM. - and_m = offset16 & 0x1F - or_m = (offset16 >> 5) & 0x1F - xor_m = (offset16 >> 10) & 0x1F - if and_m == 0x1F and or_m == 0: - if xor_m in (1, 2, 4, 8, 16): - return f"offset:swizzle(SWAP,{xor_m})" - if xor_m in (3, 7, 15, 31): - return f"offset:swizzle(REVERSE,{xor_m + 1})" - if xor_m == 0 and (or_m & and_m) == 0 and (0x1F ^ and_m) in (1, 3, 7, 15, 31): - grp = (0x1F ^ and_m) + 1 - return f"offset:swizzle(BROADCAST,{grp},{or_m})" - chars = [] - for bit in range(4, -1, -1): - a = (and_m >> bit) & 1 - o = (or_m >> bit) & 1 - x = (xor_m >> bit) & 1 - if a == 0 and o == 0 and x == 0: - chars.append("0") - elif a == 0 and o == 1 and x == 0: - chars.append("1") - elif a == 1 and o == 0 and x == 0: - chars.append("p") - elif a == 1 and o == 0 and x == 1: - chars.append("i") - else: - return f"offset:{offset16}" - return f'offset:swizzle(BITMASK_PERM,"{"".join(chars)}")' - if (offset16 & 0xFF00) == 0x8000: - p = [(offset16 >> (2 * i)) & 3 for i in range(4)] - return f"offset:swizzle(QUAD_PERM,{p[0]},{p[1]},{p[2]},{p[3]})" - return f"offset:{offset16}" - - -def _mimg_addr_count(name: str, dim: int, a16: bool) -> int: - """Number of address VGPRs for an MIMG instruction.""" - if name in ("image_bvh_intersect_ray", "image_bvh64_intersect_ray"): - return 11 if name == "image_bvh_intersect_ray" else 12 - if name == "image_get_resinfo": - return 1 - if name == "image_get_lod": - return _MIMG_DIM_COORDS.get(dim, 2) - base = _MIMG_DIM_COORDS.get(dim, 2) - if name.startswith("image_atomic_"): - return (base + 1) // 2 if a16 else base - # Separate 32-bit address components (offset, bias, z-compare, derivatives) from a16-packable coords/lod/clamp. - has_o = name.endswith("_o") or "_o_" in name - base_name = name[:-2] if name.endswith("_o") else name - has_cl = base_name.endswith("_cl") - if has_cl: - base_name = base_name[:-3] - fixed32 = 1 if has_o else 0 - if "_b" in base_name and not base_name.startswith("image_bvh"): - fixed32 += 1 - if "_c" in base_name and not base_name.startswith(("image_atomic", "image_get")): - fixed32 += 1 - if "_d" in base_name and not base_name.startswith(("image_atomic", "image_get")): - fixed32 += 2 * _MIMG_GRAD_COORDS.get(dim, 2) - packable = base - if "_l" in base_name and "_lz" not in base_name and not base_name.startswith( - ("image_load", "image_store", "image_atomic", "image_get")): - packable += 1 - if has_cl: - packable += 1 - if base_name in ("image_load_mip", "image_store_mip"): - packable += 1 - if a16: - # On GFX10, a16 packs coordinates (and lod/clamp after coords) two 16-bit values per VGPR; clamp/lod - # after 2D coords starts a new VGPR when coords are even (e.g., 2D + cl -> 1 + 1 = 2 VGPRs). - packed = (base + 1) // 2 + (packable - base) - return fixed32 + packed - return fixed32 + packable - - -def _mimg_data_count(name: str, dmask: int, d16: bool, tfe: bool) -> int: - if name in ("image_bvh_intersect_ray", "image_bvh64_intersect_ray"): - return 4 - if name.startswith("image_atomic_"): - # The GFX10 atomic dmask selects the total VDATA width, including - # both compare and swap values for cmpswap (masks 0x3 and 0xf). - if dmask in (1, 3, 15): - return dmask.bit_count() - n = 2 if "cmpswap" in name else 1 - if name.endswith("_x2"): - n *= 2 - return n - if name.startswith("image_gather4"): - n = 4 - else: - n = bin(dmask & 0xF).count("1") or 1 - if d16: - n = (n + 1) // 2 - return n + (1 if tfe else 0) - - -def _decode_one(code: bytes, pc: int, wave32: bool, mcpu: str) -> tuple[dict | None, int]: - """Decode one RDNA2 instruction at byte offset `pc`. Returns (ins_dict_or_None, byte_length).""" - if pc + 4 > len(code): - return None, len(code) - pc - w0 = struct.unpack_from(" bool: - return pc + nbytes <= len(code) - - def finish(op: str, args: list, mods: list, nbytes: int) -> tuple[dict, int]: - return { - "op": op, - "args": args, - "mods": mods, - "enc": code[pc:pc + nbytes].hex(), - "pc": pc, - }, nbytes - - # ---- 1. Bit 31 == 0: VOP1 / VOPC / VOP2 (plus DPP16 / DPP8 / SDWA / literal) ---- - if (w0 >> 31) == 0: - hi7 = w0 >> 25 - src0 = w0 & 0x1FF - is_dpp16 = src0 == 250 - is_dpp8 = src0 in (233, 234) - is_sdwa = src0 == 249 - - if hi7 == 0x3F: # VOP1 - opc = (w0 >> 9) & 0xFF - vdst = (w0 >> 17) & 0xFF - entry = T.VOP1.get(opc) - if entry is None: - return None, 4 - name, spec = entry - mods = [] - if is_dpp16 or is_dpp8 or is_sdwa: - if not need(8): - return None, 4 - w1 = struct.unpack_from("> 8) & 0x1FF - fi = (w1 >> 18) & 1 - bc = (w1 >> 19) & 1 - bank_m = (w1 >> 24) & 0xF - row_m = (w1 >> 28) & 0xF - neg0 = bool((w1 >> 20) & 1) - abs0 = bool((w1 >> 21) & 1) - s0 = _vreg(src0_reg, 1) - s0["neg"], s0["abs"] = neg0, abs0 - mods.append(_format_dpp16_ctrl(ctrl)) - mods.append(f"row_mask:0x{row_m:x}") - mods.append(f"bank_mask:0x{bank_m:x}") - if bc: - mods.append("bound_ctrl:1") - if fi: - mods.append("fi:1") - elif is_dpp8: - op_name = name + "_dpp" - lanes = [(w1 >> (8 + 3 * i)) & 7 for i in range(8)] - s0 = _vreg(src0_reg, 1) - mods.append(f"dpp8:[{','.join(str(x) for x in lanes)}]") - if src0 == 234: - mods.append("fi:1") - else: # SDWA - op_name = name + "_sdwa" - dst_sel = (w1 >> 8) & 7 - dst_unused = (w1 >> 11) & 3 - clamp = (w1 >> 13) & 1 - omod = (w1 >> 14) & 3 - src0_sel = (w1 >> 16) & 7 - src0_sext = bool((w1 >> 19) & 1) - src0_neg = bool((w1 >> 20) & 1) - src0_abs = bool((w1 >> 21) & 1) - s0_is_sgpr = bool((w1 >> 23) & 1) - s0 = _src(src0_reg, 1, None) if s0_is_sgpr else _vreg(src0_reg, 1) - if src0_sext: - s0["sext"] = True - s0["neg"], s0["abs"] = src0_neg, src0_abs - if clamp: - mods.append("clamp") - if omod in _OMOD_MODS: - mods.append(_OMOD_MODS[omod]) - mods.append(f"dst_sel:{_SDWA_SELS.get(dst_sel, 'DWORD')}") - mods.append(f"dst_unused:{_SDWA_UNUSED.get(dst_unused, 'UNUSED_PAD')}") - mods.append(f"src0_sel:{_SDWA_SELS.get(src0_sel, 'DWORD')}") - args = [] - for fn, nr, _ in spec: - w = _width(nr, wave32) - if fn == "VDST": - args.append(_vreg(vdst, w)) - elif fn == "SRC0": - args.append(s0) - return finish(op_name, args, mods, nbytes) - lit = None - nbytes = 4 - if src0 == 255: - if not need(8): - return None, 4 - lit = struct.unpack_from("> 17) & 0xFF - vsrc1 = (w0 >> 9) & 0xFF - entry = T.VOPC.get(opc) - if entry is None: - return None, 4 - name, spec = entry - mods = [] - if is_sdwa: - if not need(8): - return None, 4 - w1 = struct.unpack_from("> 8) & 0x7F - sd = bool((w1 >> 15) & 1) - src0_sel = (w1 >> 16) & 7 - src0_sext = bool((w1 >> 19) & 1) - src0_neg = bool((w1 >> 20) & 1) - src0_abs = bool((w1 >> 21) & 1) - s0_is_sgpr = bool((w1 >> 23) & 1) - src1_sel = (w1 >> 24) & 7 - src1_sext = bool((w1 >> 27) & 1) - src1_neg = bool((w1 >> 28) & 1) - src1_abs = bool((w1 >> 29) & 1) - s1_is_sgpr = bool((w1 >> 31) & 1) - s0 = _src(src0_reg, 1, None) if s0_is_sgpr else _vreg(src0_reg, 1) - s1 = _src(vsrc1, 1, None) if s1_is_sgpr else _vreg(vsrc1, 1) - if src0_sext: - s0["sext"] = True - if src1_sext: - s1["sext"] = True - s0["neg"], s0["abs"] = src0_neg, src0_abs - s1["neg"], s1["abs"] = src1_neg, src1_abs - mods.append(f"src0_sel:{_SDWA_SELS.get(src0_sel, 'DWORD')}") - mods.append(f"src1_sel:{_SDWA_SELS.get(src1_sel, 'DWORD')}") - dst_op = _sreg(sdst, 1 if wave32 else 2) if sd else _vcc_operand(wave32) - args = [dst_op, s0, s1] if not name.startswith("v_cmpx_") else [s0, s1] - return finish(name + "_sdwa", args, mods, 8) - lit = None - nbytes = 4 - if src0 == 255: - if not need(8): - return None, 4 - lit = struct.unpack_from("> 25) & 0x3F - vdst = (w0 >> 17) & 0xFF - vsrc1 = (w0 >> 9) & 0xFF - entry = T.VOP2.get(opc) - if entry is None: - return None, 4 - name, spec = entry - mods = [] - if is_dpp16 or is_dpp8 or is_sdwa: - if not need(8): - return None, 4 - w1 = struct.unpack_from("> 8) & 0x1FF - fi = (w1 >> 18) & 1 - bc = (w1 >> 19) & 1 - neg0 = bool((w1 >> 20) & 1) - abs0 = bool((w1 >> 21) & 1) - neg1 = bool((w1 >> 22) & 1) - abs1 = bool((w1 >> 23) & 1) - bank_m = (w1 >> 24) & 0xF - row_m = (w1 >> 28) & 0xF - s0 = _vreg(src0_reg, 1) - s0["neg"], s0["abs"] = neg0, abs0 - s1 = _vreg(vsrc1, 1) - s1["neg"], s1["abs"] = neg1, abs1 - mods.append(_format_dpp16_ctrl(ctrl)) - mods.append(f"row_mask:0x{row_m:x}") - mods.append(f"bank_mask:0x{bank_m:x}") - if bc: - mods.append("bound_ctrl:1") - if fi: - mods.append("fi:1") - elif is_dpp8: - op_name = name + "_dpp" - lanes = [(w1 >> (8 + 3 * i)) & 7 for i in range(8)] - s0 = _vreg(src0_reg, 1) - s1 = _vreg(vsrc1, 1) - mods.append(f"dpp8:[{','.join(str(x) for x in lanes)}]") - if src0 == 234: - mods.append("fi:1") - else: # SDWA - op_name = name + "_sdwa" - dst_sel = (w1 >> 8) & 7 - dst_unused = (w1 >> 11) & 3 - clamp = (w1 >> 13) & 1 - omod = (w1 >> 14) & 3 - src0_sel = (w1 >> 16) & 7 - src0_sext = bool((w1 >> 19) & 1) - src0_neg = bool((w1 >> 20) & 1) - src0_abs = bool((w1 >> 21) & 1) - s0_is_sgpr = bool((w1 >> 23) & 1) - src1_sel = (w1 >> 24) & 7 - src1_sext = bool((w1 >> 27) & 1) - src1_neg = bool((w1 >> 28) & 1) - src1_abs = bool((w1 >> 29) & 1) - s1_is_sgpr = bool((w1 >> 31) & 1) - s0 = _src(src0_reg, 1, None) if s0_is_sgpr else _vreg(src0_reg, 1) - s1 = _src(vsrc1, 1, None) if s1_is_sgpr else _vreg(vsrc1, 1) - if src0_sext: - s0["sext"] = True - if src1_sext: - s1["sext"] = True - s0["neg"], s0["abs"] = src0_neg, src0_abs - s1["neg"], s1["abs"] = src1_neg, src1_abs - if clamp: - mods.append("clamp") - if omod in _OMOD_MODS: - mods.append(_OMOD_MODS[omod]) - mods.append(f"dst_sel:{_SDWA_SELS.get(dst_sel, 'DWORD')}") - mods.append(f"dst_unused:{_SDWA_UNUSED.get(dst_unused, 'UNUSED_PAD')}") - mods.append(f"src0_sel:{_SDWA_SELS.get(src0_sel, 'DWORD')}") - mods.append(f"src1_sel:{_SDWA_SELS.get(src1_sel, 'DWORD')}") - args = [] - for fn, nr, _ in spec: - w = _width(nr, wave32) - if fn == "VDST": - args.append(_vreg(vdst, w)) - elif fn == "VCC": - args.append(_vcc_operand(wave32)) - elif fn == "SRC0": - args.append(s0) - elif fn == "VSRC1": - args.append(s1) - return finish(op_name, args, mods, 8) - - has_lit = (src0 == 255) or (opc in _VOP2_MANDATORY_LITERAL) - lit = None - nbytes = 4 - if has_lit: - if not need(8): - return None, 4 - lit = struct.unpack_from("> 30) == 0b10: - hi9 = w0 >> 23 - if hi9 == 0x17D: # SOP1 - opc = (w0 >> 8) & 0xFF - sdst = (w0 >> 16) & 0x7F - ssrc0 = w0 & 0xFF - entry = T.SOP1.get(opc) - if entry is None: - return None, 4 - name, spec = entry - lit = None - nbytes = 4 - if ssrc0 == 255: - if not need(8): - return None, 4 - lit = struct.unpack_from("> 16) & 0x7F - ssrc0 = w0 & 0xFF - ssrc1 = (w0 >> 8) & 0xFF - entry = T.SOPC.get(opc) - if entry is None: - return None, 4 - name, spec = entry - lit = None - nbytes = 4 - if ssrc0 == 255 or ssrc1 == 255: - if not need(8): - return None, 4 - lit = struct.unpack_from("> 16) & 0x7F - simm16 = w0 & 0xFFFF - entry = T.SOPP.get(opc) - if entry is None: - return None, 4 - name, spec = entry - if name in _SOPP_NO_OPERAND: - return finish(name, [], [], 4) - if name == "s_waitcnt": - return finish(name, _format_waitcnt(simm16), [], 4) - if name == "s_waitcnt_vscnt": - # s_waitcnt_vscnt is SOPK, not SOPP; kept defensive. - return finish(name, [{"k": "imm", "v": simm16}], [], 4) - if name == "s_sendmsg" or name == "s_sendmsghalt": - return finish(name, [{"k": "special", "t": _format_sendmsg(simm16)}], [], 4) - if name in _SOPP_BRANCHES: - return finish(name, [{"k": "imm", "v": _s16(simm16)}], [], 4) - if name == "s_clause": - return finish(name, [{"k": "imm", "v": simm16}], [], 4) - return finish(name, [{"k": "imm", "v": simm16}], [], 4) - - if (w0 >> 28) == 0xB: # SOPK - opc = (w0 >> 23) & 0x1F - sdst = (w0 >> 16) & 0x7F - simm16 = w0 & 0xFFFF - entry = T.SOPK.get(opc) - if entry is None: - return None, 4 - name, spec = entry - lit = None - nbytes = 4 - if opc in _SOPK_MANDATORY_LITERAL: - if not need(8): - return None, 4 - lit = struct.unpack_from("> 23) & 0x7F - sdst = (w0 >> 16) & 0x7F - ssrc1 = (w0 >> 8) & 0xFF - ssrc0 = w0 & 0xFF - entry = T.SOP2.get(opc) - if entry is None: - return None, 4 - name, spec = entry - lit = None - nbytes = 4 - if ssrc0 == 255 or ssrc1 == 255: - if not need(8): - return None, 4 - lit = struct.unpack_from("> 26 - - if hi6 == 0x32: # VINTRP (32-bit!) - opc = (w0 >> 16) & 3 - vdst = (w0 >> 18) & 0xFF - attr = (w0 >> 10) & 0x3F - chan = "xyzw"[(w0 >> 8) & 3] - vsrc = w0 & 0xFF - entry = T.VINTRP.get(opc) - if entry is None: - return None, 4 - name, _ = entry - if name == "v_interp_mov_f32": - p = {0: "p10", 1: "p20", 2: "p0"}.get(vsrc & 3, f"p{vsrc}") - args = [_vreg(vdst, 1), {"k": "interp", "t": p}, {"k": "attr", "a": attr, "c": (w0 >> 8) & 3}] - else: - args = [_vreg(vdst, 1), _vreg(vsrc, 1), {"k": "attr", "a": attr, "c": (w0 >> 8) & 3}] - return finish(name, args, [], 4) - - # All remaining encodings are at least 64 bits. - if not need(8): - return None, 4 - w1 = struct.unpack_from("> 16) & 0x7F - vdst = w0 & 0xFF - neg_hi = (w0 >> 8) & 7 - op_sel = (w0 >> 11) & 7 - op_sel_hi_2 = (w0 >> 14) & 1 - clamp = (w0 >> 15) & 1 - src0 = w1 & 0x1FF - src1 = (w1 >> 9) & 0x1FF - src2 = (w1 >> 18) & 0x1FF - op_sel_hi_01 = (w1 >> 27) & 3 - op_sel_hi = op_sel_hi_01 | (op_sel_hi_2 << 2) - neg_lo = (w1 >> 29) & 7 - entry = T.VOP3P.get(opc) - if entry is None: - return None, 4 - name, spec = entry - lit = None - nbytes = 8 - nsrc = sum(1 for fn, _, _ in spec if fn in ("SRC0", "SRC1", "SRC2")) - srcs_codes = [src0, src1, src2][:nsrc] - if 255 in srcs_codes: - if not need(12): - return None, 4 - lit = struct.unpack_from("> i) & 1 for i in range(nsrc)] - selhi_bits = [(op_sel_hi >> i) & 1 for i in range(nsrc)] - neglo_bits = [(neg_lo >> i) & 1 for i in range(nsrc)] - neghi_bits = [(neg_hi >> i) & 1 for i in range(nsrc)] - # v_fma_mix* uses op_sel/op_sel_hi with default [0,...]; standard packed ops default op_sel_hi to [1,...]. - if any(sel_bits): - mods.append(f"op_sel:[{','.join(str(b) for b in sel_bits)}]") - default_hi = [0] * nsrc if is_mix else [1] * nsrc - if selhi_bits != default_hi: - mods.append(f"op_sel_hi:[{','.join(str(b) for b in selhi_bits)}]") - if not is_mix and any(neglo_bits): - mods.append(f"neg_lo:[{','.join(str(b) for b in neglo_bits)}]") - if not is_mix and any(neghi_bits): - mods.append(f"neg_hi:[{','.join(str(b) for b in neghi_bits)}]") - if clamp: - mods.append("clamp") - return finish(name, args, mods, nbytes) - - if hi6 == 0x35: # VOP3 / VOP3B (64-bit, +literal) - opc = (w0 >> 16) & 0x3FF - vdst = w0 & 0xFF - clamp = (w0 >> 15) & 1 - src0 = w1 & 0x1FF - src1 = (w1 >> 9) & 0x1FF - src2 = (w1 >> 18) & 0x1FF - omod = (w1 >> 27) & 3 - neg = (w1 >> 29) & 7 - is_vop3b = opc in T.VOP3B - entry = T.VOP3B.get(opc) if is_vop3b else T.VOP3.get(opc) - if entry is None: - return None, 4 - name, spec = entry - if opc == 0x140 and mcpu.startswith("gfx101"): - name = "v_mad_legacy_f32" - sdst = (w0 >> 8) & 0x7F - abs_bits = 0 if is_vop3b else ((w0 >> 8) & 7) - op_sel = 0 if is_vop3b else ((w0 >> 11) & 0xF) - nsrc = sum(1 for fn, _, _ in spec if fn in ("SRC0", "SRC1", "SRC2")) - srcs_codes = [src0, src1, src2][:nsrc] - lit = None - nbytes = 8 - if 255 in srcs_codes: - if not need(12): - return None, 4 - lit = struct.unpack_from("> 6) & 3}) - if opc in (0x342, 0x343, 0x35A) and ((src0 >> 8) & 1): - mods.append("high") - else: - args.append(_src(src0, w, lit, neg=bool(neg & 1), absm=bool(abs_bits & 1))) - elif fn == "SRC1": - if opc == 0x202: # v_interp_mov_f32_e64: param selector p10/p20/p0 - p = {0: "p10", 1: "p20", 2: "p0"}.get(src1 & 3, f"p{src1}") - args.append({"k": "interp", "t": p}) - else: - args.append(_src(src1, w, lit, neg=bool(neg & 2), absm=bool(abs_bits & 2))) - elif fn == "SRC2": - args.append(_src(src2, w, lit, neg=bool(neg & 4), absm=bool(abs_bits & 4))) - if name in ("v_permlane16_b32", "v_permlanex16_b32"): - # Only [FI, BOUND_CTRL] exist here (docs/design.md, SHADER-74); llvm-mc 18.1.8 prints these two bits. - if op_sel & 3: - mods.append(f"op_sel:[{op_sel & 1},{(op_sel >> 1) & 1}]") - elif op_sel: - # op_sel prints [s0,s1,...,dst] (nsrc + 1 bits, or nsrc for VOPC). - nbits = nsrc if opc < 0x100 else (nsrc + 1) - bits = [(op_sel >> i) & 1 for i in range(nsrc)] - if nbits > nsrc: - bits.append((op_sel >> 3) & 1) - mods.append(f"op_sel:[{','.join(str(b) for b in bits)}]") - if clamp: - mods.append("clamp") - if omod in _OMOD_MODS: - mods.append(_OMOD_MODS[omod]) - return finish(op_name, args, mods, nbytes) - - if hi6 == 0x36: # DS (64-bit) - opc = (w0 >> 18) & 0xFF - offset0 = w0 & 0xFF - offset1 = (w0 >> 8) & 0xFF - gds = (w0 >> 17) & 1 - addr = w1 & 0xFF - data0 = (w1 >> 8) & 0xFF - data1 = (w1 >> 16) & 0xFF - vdst = (w1 >> 24) & 0xFF - entry = T.DS.get(opc) - if entry is None: - return None, 4 - name, spec = entry - args = [] - for fn, nr, _ in spec: - w = _width(nr, wave32) - if fn == "VDST": - args.append(_vreg(vdst, w)) - elif fn == "ADDR": - args.append(_vreg(addr, w)) - elif fn == "DATA0": - args.append(_vreg(data0, w)) - elif fn == "DATA1": - args.append(_vreg(data1, w)) - mods = [] - is_2addr = ("2_" in name or "2st64_" in name) - if name == "ds_swizzle_b32": - mods.append(_format_ds_swizzle(offset0 | (offset1 << 8))) - elif is_2addr: - if offset0: - mods.append(f"offset0:{offset0}") - if offset1: - mods.append(f"offset1:{offset1}") - else: - off16 = offset0 | (offset1 << 8) - if off16: - mods.append(f"offset:{off16}") - if gds: - mods.append("gds") - return finish(name, args, mods, 8) - - if hi6 == 0x37: # FLAT / SCRATCH / GLOBAL (64-bit) - seg = (w0 >> 14) & 3 - opc = (w0 >> 18) & 0x7F - off12 = w0 & 0xFFF - dlc = (w0 >> 12) & 1 - lds = (w0 >> 13) & 1 - glc = (w0 >> 16) & 1 - slc = (w0 >> 17) & 1 - addr = w1 & 0xFF - data = (w1 >> 8) & 0xFF - saddr = (w1 >> 16) & 0x7F - vdst = (w1 >> 24) & 0xFF - tbl = {0: T.FLAT, 1: T.SCRATCH, 2: T.GLOBAL}.get(seg) - if tbl is None or opc not in tbl: - return None, 4 - name, spec = tbl[opc] - is_atomic = "_atomic_" in name - has_saddr = seg in (1, 2) - saddr_off = saddr in (0x7D, 0x7F) # GFX10 null (125) or ST-mode/legacy 127 => off - args = [] - for fn, nr, _ in spec: - w = _width(nr, wave32) - if fn == "VDST": - if (is_atomic and not glc) or (lds and seg in (1, 2)): - continue - args.append(_vreg(vdst, w)) - elif fn == "ADDR": - if seg == 1 and saddr != 0x7D: - args.append({"k": "special", "t": "off", "neg": False, "abs": False}) - else: - aw = 2 if (seg == 0 or (seg == 2 and saddr_off)) else 1 - args.append(_vreg(addr, aw)) - elif fn == "DATA": - args.append(_vreg(data, w)) - elif fn == "SADDR" and has_saddr: - if saddr_off: - args.append({"k": "special", "t": "off", "neg": False, "abs": False}) - else: - args.append(_sreg(saddr, 2 if seg == 2 else 1)) - mods = [] - off_s = _s12(off12) if seg in (1, 2) else off12 - if off_s: - mods.append(f"offset:{off_s}") - if glc: - mods.append("glc") - if slc: - mods.append("slc") - if dlc: - mods.append("dlc") - if lds: - mods.append("lds") - return finish(name, args, mods, 8) - - if hi6 == 0x38: # MUBUF (64-bit) - opc = (w0 >> 18) & 0xFF - off12 = w0 & 0xFFF - offen = (w0 >> 12) & 1 - idxen = (w0 >> 13) & 1 - glc = (w0 >> 14) & 1 - dlc = (w0 >> 15) & 1 - lds = (w0 >> 16) & 1 - vaddr = w1 & 0xFF - vdata = (w1 >> 8) & 0xFF - srsrc = ((w1 >> 16) & 0x1F) * 4 - slc = (w1 >> 22) & 1 - tfe = (w1 >> 23) & 1 - soff = (w1 >> 24) & 0xFF - entry = T.MUBUF.get(opc) - if entry is None: - return None, 4 - name, spec = entry - args = [] - for fn, nr, _ in spec: - w = _width(nr, wave32) - if fn == "VDATA": - args.append(_vreg(vdata, w)) - elif fn == "VADDR": - if not offen and not idxen: - args.append({"k": "special", "t": "off", "neg": False, "abs": False}) - else: - args.append(_vreg(vaddr, 2 if (offen and idxen) else 1)) - elif fn == "SRSRC": - args.append(_sreg(srsrc, 4)) - elif fn == "SOFFSET": - args.append(_src(soff, 1, None)) - mods = [] - if idxen: - mods.append("idxen") - if offen: - mods.append("offen") - if off12: - mods.append(f"offset:{off12}") - if glc: - mods.append("glc") - if slc: - mods.append("slc") - if dlc: - mods.append("dlc") - if lds: - mods.append("lds") - if tfe: - mods.append("tfe") - return finish(name, args, mods, 8) - - if hi6 == 0x3A: # MTBUF (64-bit) - opc = ((w0 >> 16) & 0x7) | (((w1 >> 21) & 1) << 3) - off12 = w0 & 0xFFF - offen = (w0 >> 12) & 1 - idxen = (w0 >> 13) & 1 - glc = (w0 >> 14) & 1 - dlc = (w0 >> 15) & 1 - fmt_code = (w0 >> 19) & 0x7F - vaddr = w1 & 0xFF - vdata = (w1 >> 8) & 0xFF - srsrc = ((w1 >> 16) & 0x1F) * 4 - slc = (w1 >> 22) & 1 - tfe = (w1 >> 23) & 1 - soff = (w1 >> 24) & 0xFF - entry = T.MTBUF.get(opc) - if entry is None: - return None, 4 - name, spec = entry - args = [] - for fn, nr, _ in spec: - w = _width(nr, wave32) - if fn == "VDATA": - args.append(_vreg(vdata, w)) - elif fn == "VADDR": - if not offen and not idxen: - args.append({"k": "special", "t": "off", "neg": False, "abs": False}) - else: - args.append(_vreg(vaddr, 2 if (offen and idxen) else 1)) - elif fn == "SRSRC": - args.append(_sreg(srsrc, 4)) - elif fn == "SOFFSET": - args.append(_src(soff, 1, None)) - mods = [] - fmt_name = _GFX10_FORMATS.get(fmt_code) - if fmt_name and fmt_code != 1: # BUF_FMT_8_UNORM (code 1) is the GFX10 default - short = fmt_name.replace("GFX10_FORMAT_", "BUF_FMT_") - mods.append(f"format:[{short}]") - elif fmt_code != 1: - mods.append(f"format:{fmt_code}") - if idxen: - mods.append("idxen") - if offen: - mods.append("offen") - if off12: - mods.append(f"offset:{off12}") - if glc: - mods.append("glc") - if slc: - mods.append("slc") - if dlc: - mods.append("dlc") - if tfe: - mods.append("tfe") - return finish(name, args, mods, 8) - - if hi6 == 0x3C: # MIMG (64-bit + up to 3 NSA dwords) - nsa_dwords = (w0 >> 1) & 3 - dim = (w0 >> 3) & 7 - dlc = (w0 >> 7) & 1 - dmask = (w0 >> 8) & 0xF - unorm = (w0 >> 12) & 1 - glc = (w0 >> 13) & 1 - r128 = (w0 >> 15) & 1 - tfe = (w0 >> 16) & 1 - lwe = (w0 >> 17) & 1 - opc = ((w0 >> 18) & 0x7F) | ((w0 & 1) << 7) - vaddr0 = w1 & 0xFF - vdata = (w1 >> 8) & 0xFF - srsrc = ((w1 >> 16) & 0x1F) * 4 - ssamp = ((w1 >> 21) & 0x1F) * 4 - slc = (w0 >> 25) & 1 - a16 = (w1 >> 30) & 1 - d16 = (w1 >> 31) & 1 - entry = T.MIMG.get(opc) - if entry is None: - return None, 4 - name, spec = entry - nbytes = 8 + 4 * nsa_dwords - if not need(nbytes): - return None, 4 - n_addr = _mimg_addr_count(name, dim, bool(a16)) - if nsa_dwords: - # First address VGPR is vaddr0; remaining bytes sit in the trailing NSA dwords. - extra_bytes = code[pc + 8:pc + nbytes] - vregs = [vaddr0] + list(extra_bytes[:max(0, n_addr - 1)]) - vaddr_op = {"k": "vlist", "r": vregs} - else: - vaddr_op = _vreg(vaddr0, n_addr) - n_data = _mimg_data_count(name, dmask, bool(d16), bool(tfe)) - rsrc_w = 4 if (r128 or name.startswith("image_bvh")) else 8 - args = [] - for fn, nr, _ in spec: - if fn == "VDATA": - args.append(_vreg(vdata, n_data)) - elif fn == "VADDR": - args.append(vaddr_op) - elif fn == "SRSRC": - args.append(_sreg(srsrc, rsrc_w)) - elif fn == "SSAMP": - args.append(_sreg(ssamp, 4)) - mods = [] - if dmask and not name.startswith("image_bvh"): - mods.append(f"dmask:0x{dmask:x}") - if not name.startswith("image_bvh"): - mods.append(f"dim:{_MIMG_DIMS.get(dim, 'SQ_RSRC_IMG_2D')}") - if unorm: - mods.append("unorm") - if glc: - mods.append("glc") - if slc: - mods.append("slc") - if r128 and not name.startswith("image_bvh"): - mods.append("r128") - if tfe: - mods.append("tfe") - if lwe: - mods.append("lwe") - if a16: - mods.append("a16") - if d16: - mods.append("d16") - if dlc: - mods.append("dlc") - return finish(name, args, mods, nbytes) - - if hi6 == 0x3D: # SMEM (64-bit) - sbase = (w0 & 0x3F) * 2 - sdata = (w0 >> 6) & 0x7F - dlc = (w0 >> 14) & 1 - glc = (w0 >> 16) & 1 - opc = (w0 >> 18) & 0xFF - off21 = w1 & 0x1FFFFF - soff = (w1 >> 25) & 0x7F - entry = T.SMEM.get(opc) - if entry is None: - return None, 4 - name, spec = entry - is_buf = "buffer" in name - args = [] - mods = [] - for fn, nr, _ in spec: - w = _width(nr, wave32) - if fn == "SDATA": - args.append(_sreg(sdata, w)) - elif fn == "SBASE": - args.append(_sreg(sbase, w)) - elif fn in ("OFFSET", "SOFFSET"): - pass - # SMEM offset operands: soff != 125 (null) => register offset (+ optional offset:IMM); else immediate (or null if 0). - if any(fn in ("OFFSET", "SOFFSET") for fn, _, _ in spec): - imm_val = off21 if is_buf else _s21(off21) - if soff == 125: # null => immediate offset (or null when 0) - if imm_val == 0: - args.append({"k": "special", "t": "null", "neg": False, "abs": False}) - else: - args.append({"k": "imm", "v": imm_val}) - else: - args.append(_sreg(soff, 1)) - if imm_val > 0: - mods.append(f"offset:{imm_val:#x}") - elif imm_val < 0: - mods.append(f"offset:-0x{-imm_val:x}") - if glc: - mods.append("glc") - if dlc: - mods.append("dlc") - return finish(name, args, mods, 8) - - if hi6 == 0x3E: # EXP (64-bit) - en = w0 & 0xF - tgt = (w0 >> 4) & 0x3F - compr = (w0 >> 10) & 1 - done = (w0 >> 11) & 1 - vm = (w0 >> 12) & 1 - vsrcs = [(w1 >> (8 * i)) & 0xFF for i in range(4)] - if tgt <= 7: - tname = f"mrt{tgt}" - elif tgt == 8: - tname = "mrtz" - elif tgt == 9: - tname = "null" - elif 12 <= tgt <= 16: - tname = f"pos{tgt - 12}" - elif tgt == 20: - tname = "prim" - elif 32 <= tgt <= 63: - tname = f"param{tgt - 32}" - else: - tname = f"tgt{tgt}" - if tname == "null": # shader_ir.operand reads the null target as the special register of that name - args = [{"k": "special", "t": "null", "neg": False, "abs": False}] - else: - args = [{"k": "target", "t": tname}] - if compr: - # Compressed export: en bit 0/1 enables vsrc0 (printed twice), bit 2/3 enables vsrc1 (printed twice). - for pair in (0, 1): - enabled = bool((en >> (2 * pair)) & 3) - op = _vreg(vsrcs[pair], 1) if enabled else {"k": "special", "t": "off", "neg": False, "abs": False} - args.append(op) - args.append(dict(op)) - else: - for i in range(4): - if (en >> i) & 1: - args.append(_vreg(vsrcs[i], 1)) - else: - args.append({"k": "special", "t": "off", "neg": False, "abs": False}) - mods = [] - if done: - mods.append("done") - if compr: - mods.append("compr") - if vm: - mods.append("vm") - return finish("exp", args, mods, 8) - - return None, 4 - - -def _format_operand(a: dict, hex_imm: bool = False) -> str: - k = a["k"] - if k in ("vgpr", "sgpr"): - p = "v" if k == "vgpr" else "s" - r, n = a["r"], a.get("n", 1) - s = f"{p}{r}" if n == 1 else f"{p}[{r}:{r + n - 1}]" - elif k == "vlist": - s = "[" + ",".join(f"v{r}" for r in a["r"]) + "]" - elif k == "slist": - s = "[" + ",".join(f"s{r}" if isinstance(r, int) else r for r in a["r"]) + "]" - elif k == "attr": - s = f"attr{a['a']}.{'xyzw'[a['c']]}" - elif k in ("special", "target", "interp", "ttmp", "raw"): - s = a["t"] - elif k == "imm": - v = a["v"] - s = f"0x{v:x}" if hex_imm or v >= 100 else str(v) - elif k == "fimm": - v = a["v"] - s = next((txt for code, txt in _INLINE_FLOAT_STR.items() if _INLINE_FLOAT[code] == v), repr(v)) - else: - s = str(a) - - if a.get("sext"): - s = f"sext({s})" - if a.get("abs"): - s = f"|{s}|" - if a.get("neg"): - if k in ("imm", "fimm"): - s = f"neg({s})" - else: - s = f"-{s}" - return s - - -def format_insn(ins: dict) -> str: - """Format one decoded instruction dict as an LLVM-compatible `.s` line.""" - op = ins["op"] - args = ins["args"] - mods = ins["mods"] - hex_imm = op == "s_ttracedata_imm" - if op == "exp" and args: - head = f"{op} {_format_operand(args[0], hex_imm)} " + ", ".join( - _format_operand(x, hex_imm) for x in args[1:]) - elif args: - head = f"{op} " + ", ".join(_format_operand(x, hex_imm) for x in args) - else: - head = op - if mods: - head += " " + " ".join(mods) - enc_bytes = bytes.fromhex(ins["enc"]) - enc_str = ",".join(f"0x{b:02x}" for b in enc_bytes) - return f"\t{head:<40s}; encoding: [{enc_str}]" - - -def _iter_insns(code: bytes, wave32: bool, code_start: int, mcpu: str) -> Iterator[dict | None]: - """Yield each decoded instruction, or None for each invalid word counted.""" - off = 0 - while off < len(code): - ins, nbytes = _decode_one(code, off, wave32, mcpu) - if ins is None: - off += max(4, nbytes) - else: - ins["pc"] = code_start + off - off += nbytes - yield ins - - -def decode_bytes(code: bytes, *, mcpu: str = "gfx1013", wave32: bool = True, code_start: int = 0, name: str = "") -> dict: - """Decode raw RDNA2 machine code into the exact dict layout `shader_ir.parse_file()` returns.""" - insns = [] - invalid = 0 - for ins in _iter_insns(code, wave32, code_start, mcpu): - if ins is None: - invalid += 1 - else: - insns.append(ins) - return {"name": name, "code_start": code_start, "insns": insns, "invalid": invalid} - - -def disasm_bytes(code: bytes, *, mcpu: str = "gfx1013", wave32: bool = True, code_start: int = 0, name: str = "") -> tuple[str, int]: - """Decode raw RDNA2 machine code into `(llvm_compatible_text, invalid_word_count)`. - - The listing contains only instructions. `name` is accepted for caller compatibility. - """ - invalid = 0 - with StringIO() as listing: - for ins in _iter_insns(code, wave32, code_start, mcpu): - if ins is None: - invalid += 1 - else: - listing.write(f"{format_insn(ins)}\n") - return listing.getvalue(), invalid diff --git a/tools/rdna2_isa_tables.py b/tools/rdna2_isa_tables.py deleted file mode 100644 index cab2596ee..000000000 --- a/tools/rdna2_isa_tables.py +++ /dev/null @@ -1,1537 +0,0 @@ -"""RDNA2 (GFX10.1/GFX10.3) opcode tables for tools/rdna2_decode.py. - -Derived from AMD's machine-readable RDNA2 ISA specification (amdgpu_isa_rdna2.xml, -MIT licence; https://gpuopen.com/machine-readable-isa), plus the seven gfx1013 -legacy/waveid instructions documented in docs/isa_coverage.md. -""" - -DS = { - 0x0: ('ds_add_u32', (('ADDR', 1, 'i'), ('DATA0', 1, 'i'))), - 0x1: ('ds_sub_u32', (('ADDR', 1, 'i'), ('DATA0', 1, 'i'))), - 0x2: ('ds_rsub_u32', (('ADDR', 1, 'i'), ('DATA0', 1, 'i'))), - 0x3: ('ds_inc_u32', (('ADDR', 1, 'i'), ('DATA0', 1, 'i'))), - 0x4: ('ds_dec_u32', (('ADDR', 1, 'i'), ('DATA0', 1, 'i'))), - 0x5: ('ds_min_i32', (('ADDR', 1, 'i'), ('DATA0', 1, 'i'))), - 0x6: ('ds_max_i32', (('ADDR', 1, 'i'), ('DATA0', 1, 'i'))), - 0x7: ('ds_min_u32', (('ADDR', 1, 'i'), ('DATA0', 1, 'i'))), - 0x8: ('ds_max_u32', (('ADDR', 1, 'i'), ('DATA0', 1, 'i'))), - 0x9: ('ds_and_b32', (('ADDR', 1, 'i'), ('DATA0', 1, 'i'))), - 0xa: ('ds_or_b32', (('ADDR', 1, 'i'), ('DATA0', 1, 'i'))), - 0xb: ('ds_xor_b32', (('ADDR', 1, 'i'), ('DATA0', 1, 'i'))), - 0xc: ('ds_mskor_b32', (('ADDR', 1, 'i'), ('DATA0', 1, 'i'), ('DATA1', 1, 'i'))), - 0xd: ('ds_write_b32', (('ADDR', 1, 'i'), ('DATA0', 1, 'i'))), - 0xe: ('ds_write2_b32', (('ADDR', 1, 'i'), ('DATA0', 1, 'i'), ('DATA1', 1, 'i'))), - 0xf: ('ds_write2st64_b32', (('ADDR', 1, 'i'), ('DATA0', 1, 'i'), ('DATA1', 1, 'i'))), - 0x10: ('ds_cmpst_b32', (('ADDR', 1, 'i'), ('DATA0', 1, 'i'), ('DATA1', 1, 'i'))), - 0x11: ('ds_cmpst_f32', (('ADDR', 1, 'i'), ('DATA0', 1, 'f32'), ('DATA1', 1, 'f32'))), - 0x12: ('ds_min_f32', (('ADDR', 1, 'i'), ('DATA0', 1, 'f32'))), - 0x13: ('ds_max_f32', (('ADDR', 1, 'i'), ('DATA0', 1, 'f32'))), - 0x14: ('ds_nop', ()), - 0x15: ('ds_add_f32', (('ADDR', 1, 'i'), ('DATA0', 1, 'f32'))), - 0x18: ('ds_gws_sema_release_all', ()), - 0x19: ('ds_gws_init', (('ADDR', 1, 'i'),)), - 0x1a: ('ds_gws_sema_v', ()), - 0x1b: ('ds_gws_sema_br', (('ADDR', 1, 'i'),)), - 0x1c: ('ds_gws_sema_p', ()), - 0x1d: ('ds_gws_barrier', (('ADDR', 1, 'i'),)), - 0x1e: ('ds_write_b8', (('ADDR', 1, 'i'), ('DATA0', 1, 'i'))), - 0x1f: ('ds_write_b16', (('ADDR', 1, 'i'), ('DATA0', 1, 'i'))), - 0x20: ('ds_add_rtn_u32', (('VDST', 1, 'i'), ('ADDR', 1, 'i'), ('DATA0', 1, 'i'))), - 0x21: ('ds_sub_rtn_u32', (('VDST', 1, 'i'), ('ADDR', 1, 'i'), ('DATA0', 1, 'i'))), - 0x22: ('ds_rsub_rtn_u32', (('VDST', 1, 'i'), ('ADDR', 1, 'i'), ('DATA0', 1, 'i'))), - 0x23: ('ds_inc_rtn_u32', (('VDST', 1, 'i'), ('ADDR', 1, 'i'), ('DATA0', 1, 'i'))), - 0x24: ('ds_dec_rtn_u32', (('VDST', 1, 'i'), ('ADDR', 1, 'i'), ('DATA0', 1, 'i'))), - 0x25: ('ds_min_rtn_i32', (('VDST', 1, 'i'), ('ADDR', 1, 'i'), ('DATA0', 1, 'i'))), - 0x26: ('ds_max_rtn_i32', (('VDST', 1, 'i'), ('ADDR', 1, 'i'), ('DATA0', 1, 'i'))), - 0x27: ('ds_min_rtn_u32', (('VDST', 1, 'i'), ('ADDR', 1, 'i'), ('DATA0', 1, 'i'))), - 0x28: ('ds_max_rtn_u32', (('VDST', 1, 'i'), ('ADDR', 1, 'i'), ('DATA0', 1, 'i'))), - 0x29: ('ds_and_rtn_b32', (('VDST', 1, 'i'), ('ADDR', 1, 'i'), ('DATA0', 1, 'i'))), - 0x2a: ('ds_or_rtn_b32', (('VDST', 1, 'i'), ('ADDR', 1, 'i'), ('DATA0', 1, 'i'))), - 0x2b: ('ds_xor_rtn_b32', (('VDST', 1, 'i'), ('ADDR', 1, 'i'), ('DATA0', 1, 'i'))), - 0x2c: ('ds_mskor_rtn_b32', (('VDST', 1, 'i'), ('ADDR', 1, 'i'), ('DATA0', 1, 'i'), ('DATA1', 1, 'i'))), - 0x2d: ('ds_wrxchg_rtn_b32', (('VDST', 1, 'i'), ('ADDR', 1, 'i'), ('DATA0', 1, 'i'))), - 0x2e: ('ds_wrxchg2_rtn_b32', (('VDST', 2, 'i'), ('ADDR', 1, 'i'), ('DATA0', 1, 'i'), ('DATA1', 1, 'i'))), - 0x2f: ('ds_wrxchg2st64_rtn_b32', (('VDST', 2, 'i'), ('ADDR', 1, 'i'), ('DATA0', 1, 'i'), ('DATA1', 1, 'i'))), - 0x30: ('ds_cmpst_rtn_b32', (('VDST', 1, 'i'), ('ADDR', 1, 'i'), ('DATA0', 1, 'i'), ('DATA1', 1, 'i'))), - 0x31: ('ds_cmpst_rtn_f32', (('VDST', 1, 'f32'), ('ADDR', 1, 'i'), ('DATA0', 1, 'f32'), ('DATA1', 1, 'f32'))), - 0x32: ('ds_min_rtn_f32', (('VDST', 1, 'f32'), ('ADDR', 1, 'i'), ('DATA0', 1, 'f32'))), - 0x33: ('ds_max_rtn_f32', (('VDST', 1, 'f32'), ('ADDR', 1, 'i'), ('DATA0', 1, 'f32'))), - 0x34: ('ds_wrap_rtn_b32', (('VDST', 1, 'i'), ('ADDR', 1, 'i'), ('DATA0', 1, 'i'), ('DATA1', 1, 'i'))), - 0x35: ('ds_swizzle_b32', (('VDST', 1, 'i'), ('ADDR', 1, 'i'))), - 0x36: ('ds_read_b32', (('VDST', 1, 'i'), ('ADDR', 1, 'i'))), - 0x37: ('ds_read2_b32', (('VDST', 2, 'i'), ('ADDR', 1, 'i'))), - 0x38: ('ds_read2st64_b32', (('VDST', 2, 'i'), ('ADDR', 1, 'i'))), - 0x39: ('ds_read_i8', (('VDST', 1, 'i'), ('ADDR', 1, 'i'))), - 0x3a: ('ds_read_u8', (('VDST', 1, 'i'), ('ADDR', 1, 'i'))), - 0x3b: ('ds_read_i16', (('VDST', 1, 'i'), ('ADDR', 1, 'i'))), - 0x3c: ('ds_read_u16', (('VDST', 1, 'i'), ('ADDR', 1, 'i'))), - 0x3d: ('ds_consume', (('VDST', 1, 'i'),)), - 0x3e: ('ds_append', (('VDST', 1, 'i'),)), - 0x3f: ('ds_ordered_count', (('VDST', 1, 'i'), ('ADDR', 1, 'i'))), - 0x40: ('ds_add_u64', (('ADDR', 1, 'i'), ('DATA0', 2, 'i'))), - 0x41: ('ds_sub_u64', (('ADDR', 1, 'i'), ('DATA0', 2, 'i'))), - 0x42: ('ds_rsub_u64', (('ADDR', 1, 'i'), ('DATA0', 2, 'i'))), - 0x43: ('ds_inc_u64', (('ADDR', 1, 'i'), ('DATA0', 2, 'i'))), - 0x44: ('ds_dec_u64', (('ADDR', 1, 'i'), ('DATA0', 2, 'i'))), - 0x45: ('ds_min_i64', (('ADDR', 1, 'i'), ('DATA0', 2, 'i'))), - 0x46: ('ds_max_i64', (('ADDR', 1, 'i'), ('DATA0', 2, 'i'))), - 0x47: ('ds_min_u64', (('ADDR', 1, 'i'), ('DATA0', 2, 'i'))), - 0x48: ('ds_max_u64', (('ADDR', 1, 'i'), ('DATA0', 2, 'i'))), - 0x49: ('ds_and_b64', (('ADDR', 1, 'i'), ('DATA0', 2, 'i'))), - 0x4a: ('ds_or_b64', (('ADDR', 1, 'i'), ('DATA0', 2, 'i'))), - 0x4b: ('ds_xor_b64', (('ADDR', 1, 'i'), ('DATA0', 2, 'i'))), - 0x4c: ('ds_mskor_b64', (('ADDR', 1, 'i'), ('DATA0', 2, 'i'), ('DATA1', 2, 'i'))), - 0x4d: ('ds_write_b64', (('ADDR', 1, 'i'), ('DATA0', 2, 'i'))), - 0x4e: ('ds_write2_b64', (('ADDR', 1, 'i'), ('DATA0', 2, 'i'), ('DATA1', 2, 'i'))), - 0x4f: ('ds_write2st64_b64', (('ADDR', 1, 'i'), ('DATA0', 2, 'i'), ('DATA1', 2, 'i'))), - 0x50: ('ds_cmpst_b64', (('ADDR', 1, 'i'), ('DATA0', 2, 'i'), ('DATA1', 2, 'i'))), - 0x51: ('ds_cmpst_f64', (('ADDR', 1, 'i'), ('DATA0', 2, 'f64'), ('DATA1', 2, 'f64'))), - 0x52: ('ds_min_f64', (('ADDR', 1, 'i'), ('DATA0', 2, 'f64'))), - 0x53: ('ds_max_f64', (('ADDR', 1, 'i'), ('DATA0', 2, 'f64'))), - 0x55: ('ds_add_rtn_f32', (('VDST', 1, 'f32'), ('ADDR', 1, 'i'), ('DATA0', 1, 'f32'))), - 0x60: ('ds_add_rtn_u64', (('VDST', 2, 'i'), ('ADDR', 1, 'i'), ('DATA0', 2, 'i'))), - 0x61: ('ds_sub_rtn_u64', (('VDST', 2, 'i'), ('ADDR', 1, 'i'), ('DATA0', 2, 'i'))), - 0x62: ('ds_rsub_rtn_u64', (('VDST', 2, 'i'), ('ADDR', 1, 'i'), ('DATA0', 2, 'i'))), - 0x63: ('ds_inc_rtn_u64', (('VDST', 2, 'i'), ('ADDR', 1, 'i'), ('DATA0', 2, 'i'))), - 0x64: ('ds_dec_rtn_u64', (('VDST', 2, 'i'), ('ADDR', 1, 'i'), ('DATA0', 2, 'i'))), - 0x65: ('ds_min_rtn_i64', (('VDST', 2, 'i'), ('ADDR', 1, 'i'), ('DATA0', 2, 'i'))), - 0x66: ('ds_max_rtn_i64', (('VDST', 2, 'i'), ('ADDR', 1, 'i'), ('DATA0', 2, 'i'))), - 0x67: ('ds_min_rtn_u64', (('VDST', 2, 'i'), ('ADDR', 1, 'i'), ('DATA0', 2, 'i'))), - 0x68: ('ds_max_rtn_u64', (('VDST', 2, 'i'), ('ADDR', 1, 'i'), ('DATA0', 2, 'i'))), - 0x69: ('ds_and_rtn_b64', (('VDST', 2, 'i'), ('ADDR', 1, 'i'), ('DATA0', 2, 'i'))), - 0x6a: ('ds_or_rtn_b64', (('VDST', 2, 'i'), ('ADDR', 1, 'i'), ('DATA0', 2, 'i'))), - 0x6b: ('ds_xor_rtn_b64', (('VDST', 2, 'i'), ('ADDR', 1, 'i'), ('DATA0', 2, 'i'))), - 0x6c: ('ds_mskor_rtn_b64', (('VDST', 2, 'i'), ('ADDR', 1, 'i'), ('DATA0', 2, 'i'), ('DATA1', 2, 'i'))), - 0x6d: ('ds_wrxchg_rtn_b64', (('VDST', 2, 'i'), ('ADDR', 1, 'i'), ('DATA0', 2, 'i'))), - 0x6e: ('ds_wrxchg2_rtn_b64', (('VDST', 4, 'i'), ('ADDR', 1, 'i'), ('DATA0', 2, 'i'), ('DATA1', 2, 'i'))), - 0x6f: ('ds_wrxchg2st64_rtn_b64', (('VDST', 4, 'i'), ('ADDR', 1, 'i'), ('DATA0', 2, 'i'), ('DATA1', 2, 'i'))), - 0x70: ('ds_cmpst_rtn_b64', (('VDST', 2, 'i'), ('ADDR', 1, 'i'), ('DATA0', 2, 'i'), ('DATA1', 2, 'i'))), - 0x71: ('ds_cmpst_rtn_f64', (('VDST', 2, 'f64'), ('ADDR', 1, 'i'), ('DATA0', 2, 'f64'), ('DATA1', 2, 'f64'))), - 0x72: ('ds_min_rtn_f64', (('VDST', 2, 'f64'), ('ADDR', 1, 'i'), ('DATA0', 2, 'f64'))), - 0x73: ('ds_max_rtn_f64', (('VDST', 2, 'f64'), ('ADDR', 1, 'i'), ('DATA0', 2, 'f64'))), - 0x76: ('ds_read_b64', (('VDST', 2, 'i'), ('ADDR', 1, 'i'))), - 0x77: ('ds_read2_b64', (('VDST', 4, 'i'), ('ADDR', 1, 'i'))), - 0x78: ('ds_read2st64_b64', (('VDST', 4, 'i'), ('ADDR', 1, 'i'))), - 0x7e: ('ds_condxchg32_rtn_b64', (('VDST', 2, 'i'), ('ADDR', 1, 'i'), ('DATA0', 2, 'i'))), - 0xa0: ('ds_write_b8_d16_hi', (('ADDR', 1, 'i'), ('DATA0', 1, 'i'))), - 0xa1: ('ds_write_b16_d16_hi', (('ADDR', 1, 'i'), ('DATA0', 1, 'i'))), - 0xa2: ('ds_read_u8_d16', (('VDST', 1, 'i'), ('ADDR', 1, 'i'))), - 0xa3: ('ds_read_u8_d16_hi', (('VDST', 1, 'i'), ('ADDR', 1, 'i'))), - 0xa4: ('ds_read_i8_d16', (('VDST', 1, 'i'), ('ADDR', 1, 'i'))), - 0xa5: ('ds_read_i8_d16_hi', (('VDST', 1, 'i'), ('ADDR', 1, 'i'))), - 0xa6: ('ds_read_u16_d16', (('VDST', 1, 'i'), ('ADDR', 1, 'i'))), - 0xa7: ('ds_read_u16_d16_hi', (('VDST', 1, 'i'), ('ADDR', 1, 'i'))), - 0xb0: ('ds_write_addtid_b32', (('DATA0', 1, 'i'),)), - 0xb1: ('ds_read_addtid_b32', (('VDST', 1, 'i'),)), - 0xb2: ('ds_permute_b32', (('VDST', 1, 'i'), ('ADDR', 1, 'i'), ('DATA0', 1, 'i'))), - 0xb3: ('ds_bpermute_b32', (('VDST', 1, 'i'), ('ADDR', 1, 'i'), ('DATA0', 1, 'i'))), - 0xde: ('ds_write_b96', (('ADDR', 1, 'i'), ('DATA0', 3, 'i'))), - 0xdf: ('ds_write_b128', (('ADDR', 1, 'i'), ('DATA0', 4, 'i'))), - 0xfe: ('ds_read_b96', (('VDST', 3, 'i'), ('ADDR', 1, 'i'))), - 0xff: ('ds_read_b128', (('VDST', 4, 'i'), ('ADDR', 1, 'i'))), -} - -FLAT = { - 0x8: ('flat_load_ubyte', (('VDST', 1, 'i'), ('ADDR', 2, 'i'))), - 0x9: ('flat_load_sbyte', (('VDST', 1, 'i'), ('ADDR', 2, 'i'))), - 0xa: ('flat_load_ushort', (('VDST', 1, 'i'), ('ADDR', 2, 'i'))), - 0xb: ('flat_load_sshort', (('VDST', 1, 'i'), ('ADDR', 2, 'i'))), - 0xc: ('flat_load_dword', (('VDST', 1, 'i'), ('ADDR', 2, 'i'))), - 0xd: ('flat_load_dwordx2', (('VDST', 2, 'i'), ('ADDR', 2, 'i'))), - 0xe: ('flat_load_dwordx4', (('VDST', 4, 'i'), ('ADDR', 2, 'i'))), - 0xf: ('flat_load_dwordx3', (('VDST', 3, 'i'), ('ADDR', 2, 'i'))), - 0x18: ('flat_store_byte', (('ADDR', 2, 'i'), ('DATA', 1, 'i'))), - 0x19: ('flat_store_byte_d16_hi', (('ADDR', 2, 'i'), ('DATA', 1, 'i'))), - 0x1a: ('flat_store_short', (('ADDR', 2, 'i'), ('DATA', 1, 'i'))), - 0x1b: ('flat_store_short_d16_hi', (('ADDR', 2, 'i'), ('DATA', 1, 'i'))), - 0x1c: ('flat_store_dword', (('ADDR', 2, 'i'), ('DATA', 1, 'i'))), - 0x1d: ('flat_store_dwordx2', (('ADDR', 2, 'i'), ('DATA', 2, 'i'))), - 0x1e: ('flat_store_dwordx4', (('ADDR', 2, 'i'), ('DATA', 4, 'i'))), - 0x1f: ('flat_store_dwordx3', (('ADDR', 2, 'i'), ('DATA', 3, 'i'))), - 0x20: ('flat_load_ubyte_d16', (('VDST', 1, 'i'), ('ADDR', 2, 'i'))), - 0x21: ('flat_load_ubyte_d16_hi', (('VDST', 1, 'i'), ('ADDR', 2, 'i'))), - 0x22: ('flat_load_sbyte_d16', (('VDST', 1, 'i'), ('ADDR', 2, 'i'))), - 0x23: ('flat_load_sbyte_d16_hi', (('VDST', 1, 'i'), ('ADDR', 2, 'i'))), - 0x24: ('flat_load_short_d16', (('VDST', 1, 'i'), ('ADDR', 2, 'i'))), - 0x25: ('flat_load_short_d16_hi', (('VDST', 1, 'i'), ('ADDR', 2, 'i'))), - 0x30: ('flat_atomic_swap', (('VDST', 1, 'i'), ('ADDR', 2, 'i'), ('DATA', 1, 'i'))), - 0x31: ('flat_atomic_cmpswap', (('VDST', 1, 'i'), ('ADDR', 2, 'i'), ('DATA', 2, 'i'))), - 0x32: ('flat_atomic_add', (('VDST', 1, 'i'), ('ADDR', 2, 'i'), ('DATA', 1, 'i'))), - 0x33: ('flat_atomic_sub', (('VDST', 1, 'i'), ('ADDR', 2, 'i'), ('DATA', 1, 'i'))), - 0x35: ('flat_atomic_smin', (('VDST', 1, 'i'), ('ADDR', 2, 'i'), ('DATA', 1, 'i'))), - 0x36: ('flat_atomic_umin', (('VDST', 1, 'i'), ('ADDR', 2, 'i'), ('DATA', 1, 'i'))), - 0x37: ('flat_atomic_smax', (('VDST', 1, 'i'), ('ADDR', 2, 'i'), ('DATA', 1, 'i'))), - 0x38: ('flat_atomic_umax', (('VDST', 1, 'i'), ('ADDR', 2, 'i'), ('DATA', 1, 'i'))), - 0x39: ('flat_atomic_and', (('VDST', 1, 'i'), ('ADDR', 2, 'i'), ('DATA', 1, 'i'))), - 0x3a: ('flat_atomic_or', (('VDST', 1, 'i'), ('ADDR', 2, 'i'), ('DATA', 1, 'i'))), - 0x3b: ('flat_atomic_xor', (('VDST', 1, 'i'), ('ADDR', 2, 'i'), ('DATA', 1, 'i'))), - 0x3c: ('flat_atomic_inc', (('VDST', 1, 'i'), ('ADDR', 2, 'i'), ('DATA', 1, 'i'))), - 0x3d: ('flat_atomic_dec', (('VDST', 1, 'i'), ('ADDR', 2, 'i'), ('DATA', 1, 'i'))), - 0x3e: ('flat_atomic_fcmpswap', (('VDST', 1, 'f32'), ('ADDR', 2, 'i'), ('DATA', 2, 'i'))), - 0x3f: ('flat_atomic_fmin', (('VDST', 1, 'i'), ('ADDR', 2, 'i'), ('DATA', 1, 'i'))), - 0x40: ('flat_atomic_fmax', (('VDST', 1, 'i'), ('ADDR', 2, 'i'), ('DATA', 1, 'i'))), - 0x50: ('flat_atomic_swap_x2', (('VDST', 2, 'i'), ('ADDR', 2, 'i'), ('DATA', 2, 'i'))), - 0x51: ('flat_atomic_cmpswap_x2', (('VDST', 2, 'i'), ('ADDR', 2, 'i'), ('DATA', 4, 'i'))), - 0x52: ('flat_atomic_add_x2', (('VDST', 2, 'i'), ('ADDR', 2, 'i'), ('DATA', 2, 'i'))), - 0x53: ('flat_atomic_sub_x2', (('VDST', 2, 'i'), ('ADDR', 2, 'i'), ('DATA', 2, 'i'))), - 0x55: ('flat_atomic_smin_x2', (('VDST', 2, 'i'), ('ADDR', 2, 'i'), ('DATA', 2, 'i'))), - 0x56: ('flat_atomic_umin_x2', (('VDST', 2, 'i'), ('ADDR', 2, 'i'), ('DATA', 2, 'i'))), - 0x57: ('flat_atomic_smax_x2', (('VDST', 2, 'i'), ('ADDR', 2, 'i'), ('DATA', 2, 'i'))), - 0x58: ('flat_atomic_umax_x2', (('VDST', 2, 'i'), ('ADDR', 2, 'i'), ('DATA', 2, 'i'))), - 0x59: ('flat_atomic_and_x2', (('VDST', 2, 'i'), ('ADDR', 2, 'i'), ('DATA', 2, 'i'))), - 0x5a: ('flat_atomic_or_x2', (('VDST', 2, 'i'), ('ADDR', 2, 'i'), ('DATA', 2, 'i'))), - 0x5b: ('flat_atomic_xor_x2', (('VDST', 2, 'i'), ('ADDR', 2, 'i'), ('DATA', 2, 'i'))), - 0x5c: ('flat_atomic_inc_x2', (('VDST', 2, 'i'), ('ADDR', 2, 'i'), ('DATA', 2, 'i'))), - 0x5d: ('flat_atomic_dec_x2', (('VDST', 2, 'i'), ('ADDR', 2, 'i'), ('DATA', 2, 'i'))), - 0x5e: ('flat_atomic_fcmpswap_x2', (('VDST', 2, 'f64'), ('ADDR', 2, 'i'), ('DATA', 4, 'i'))), - 0x5f: ('flat_atomic_fmin_x2', (('VDST', 2, 'i'), ('ADDR', 2, 'i'), ('DATA', 2, 'i'))), - 0x60: ('flat_atomic_fmax_x2', (('VDST', 2, 'i'), ('ADDR', 2, 'i'), ('DATA', 2, 'i'))), -} - -GLOBAL = { - 0x8: ('global_load_ubyte', (('VDST', 1, 'i'), ('ADDR', 2, 'i'), ('SADDR', 2, 'i'))), - 0x9: ('global_load_sbyte', (('VDST', 1, 'i'), ('ADDR', 2, 'i'), ('SADDR', 2, 'i'))), - 0xa: ('global_load_ushort', (('VDST', 1, 'i'), ('ADDR', 2, 'i'), ('SADDR', 2, 'i'))), - 0xb: ('global_load_sshort', (('VDST', 1, 'i'), ('ADDR', 2, 'i'), ('SADDR', 2, 'i'))), - 0xc: ('global_load_dword', (('VDST', 1, 'i'), ('ADDR', 2, 'i'), ('SADDR', 2, 'i'))), - 0xd: ('global_load_dwordx2', (('VDST', 2, 'i'), ('ADDR', 2, 'i'), ('SADDR', 2, 'i'))), - 0xe: ('global_load_dwordx4', (('VDST', 4, 'i'), ('ADDR', 2, 'i'), ('SADDR', 2, 'i'))), - 0xf: ('global_load_dwordx3', (('VDST', 3, 'i'), ('ADDR', 2, 'i'), ('SADDR', 2, 'i'))), - 0x16: ('global_load_dword_addtid', (('VDST', 1, 'i'), ('SADDR', 2, 'i'))), - 0x17: ('global_store_dword_addtid', (('DATA', 1, 'i'), ('SADDR', 2, 'i'))), - 0x18: ('global_store_byte', (('ADDR', 2, 'i'), ('DATA', 1, 'i'), ('SADDR', 2, 'i'))), - 0x19: ('global_store_byte_d16_hi', (('ADDR', 2, 'i'), ('DATA', 1, 'i'), ('SADDR', 2, 'i'))), - 0x1a: ('global_store_short', (('ADDR', 2, 'i'), ('DATA', 1, 'i'), ('SADDR', 2, 'i'))), - 0x1b: ('global_store_short_d16_hi', (('ADDR', 2, 'i'), ('DATA', 1, 'i'), ('SADDR', 2, 'i'))), - 0x1c: ('global_store_dword', (('ADDR', 2, 'i'), ('DATA', 1, 'i'), ('SADDR', 2, 'i'))), - 0x1d: ('global_store_dwordx2', (('ADDR', 2, 'i'), ('DATA', 2, 'i'), ('SADDR', 2, 'i'))), - 0x1e: ('global_store_dwordx4', (('ADDR', 2, 'i'), ('DATA', 4, 'i'), ('SADDR', 2, 'i'))), - 0x1f: ('global_store_dwordx3', (('ADDR', 2, 'i'), ('DATA', 3, 'i'), ('SADDR', 2, 'i'))), - 0x20: ('global_load_ubyte_d16', (('VDST', 1, 'i'), ('ADDR', 2, 'i'), ('SADDR', 2, 'i'))), - 0x21: ('global_load_ubyte_d16_hi', (('VDST', 1, 'i'), ('ADDR', 2, 'i'), ('SADDR', 2, 'i'))), - 0x22: ('global_load_sbyte_d16', (('VDST', 1, 'i'), ('ADDR', 2, 'i'), ('SADDR', 2, 'i'))), - 0x23: ('global_load_sbyte_d16_hi', (('VDST', 1, 'i'), ('ADDR', 2, 'i'), ('SADDR', 2, 'i'))), - 0x24: ('global_load_short_d16', (('VDST', 1, 'i'), ('ADDR', 2, 'i'), ('SADDR', 2, 'i'))), - 0x25: ('global_load_short_d16_hi', (('VDST', 1, 'i'), ('ADDR', 2, 'i'), ('SADDR', 2, 'i'))), - 0x30: ('global_atomic_swap', (('VDST', 1, 'i'), ('ADDR', 2, 'i'), ('DATA', 1, 'i'), ('SADDR', 2, 'i'))), - 0x31: ('global_atomic_cmpswap', (('VDST', 1, 'i'), ('ADDR', 2, 'i'), ('DATA', 2, 'i'), ('SADDR', 2, 'i'))), - 0x32: ('global_atomic_add', (('VDST', 1, 'i'), ('ADDR', 2, 'i'), ('DATA', 1, 'i'), ('SADDR', 2, 'i'))), - 0x33: ('global_atomic_sub', (('VDST', 1, 'i'), ('ADDR', 2, 'i'), ('DATA', 1, 'i'), ('SADDR', 2, 'i'))), - 0x34: ('global_atomic_csub', (('VDST', 1, 'i'), ('ADDR', 2, 'i'), ('DATA', 1, 'i'), ('SADDR', 2, 'i'))), - 0x35: ('global_atomic_smin', (('VDST', 1, 'i'), ('ADDR', 2, 'i'), ('DATA', 1, 'i'), ('SADDR', 2, 'i'))), - 0x36: ('global_atomic_umin', (('VDST', 1, 'i'), ('ADDR', 2, 'i'), ('DATA', 1, 'i'), ('SADDR', 2, 'i'))), - 0x37: ('global_atomic_smax', (('VDST', 1, 'i'), ('ADDR', 2, 'i'), ('DATA', 1, 'i'), ('SADDR', 2, 'i'))), - 0x38: ('global_atomic_umax', (('VDST', 1, 'i'), ('ADDR', 2, 'i'), ('DATA', 1, 'i'), ('SADDR', 2, 'i'))), - 0x39: ('global_atomic_and', (('VDST', 1, 'i'), ('ADDR', 2, 'i'), ('DATA', 1, 'i'), ('SADDR', 2, 'i'))), - 0x3a: ('global_atomic_or', (('VDST', 1, 'i'), ('ADDR', 2, 'i'), ('DATA', 1, 'i'), ('SADDR', 2, 'i'))), - 0x3b: ('global_atomic_xor', (('VDST', 1, 'i'), ('ADDR', 2, 'i'), ('DATA', 1, 'i'), ('SADDR', 2, 'i'))), - 0x3c: ('global_atomic_inc', (('VDST', 1, 'i'), ('ADDR', 2, 'i'), ('DATA', 1, 'i'), ('SADDR', 2, 'i'))), - 0x3d: ('global_atomic_dec', (('VDST', 1, 'i'), ('ADDR', 2, 'i'), ('DATA', 1, 'i'), ('SADDR', 2, 'i'))), - 0x3e: ('global_atomic_fcmpswap', (('VDST', 1, 'f32'), ('ADDR', 2, 'i'), ('DATA', 2, 'i'), ('SADDR', 2, 'i'))), - 0x3f: ('global_atomic_fmin', (('VDST', 1, 'i'), ('ADDR', 2, 'i'), ('DATA', 1, 'i'), ('SADDR', 2, 'i'))), - 0x40: ('global_atomic_fmax', (('VDST', 1, 'i'), ('ADDR', 2, 'i'), ('DATA', 1, 'i'), ('SADDR', 2, 'i'))), - 0x50: ('global_atomic_swap_x2', (('VDST', 2, 'i'), ('ADDR', 2, 'i'), ('DATA', 2, 'i'), ('SADDR', 2, 'i'))), - 0x51: ('global_atomic_cmpswap_x2', (('VDST', 2, 'i'), ('ADDR', 2, 'i'), ('DATA', 4, 'i'), ('SADDR', 2, 'i'))), - 0x52: ('global_atomic_add_x2', (('VDST', 2, 'i'), ('ADDR', 2, 'i'), ('DATA', 2, 'i'), ('SADDR', 2, 'i'))), - 0x53: ('global_atomic_sub_x2', (('VDST', 2, 'i'), ('ADDR', 2, 'i'), ('DATA', 2, 'i'), ('SADDR', 2, 'i'))), - 0x55: ('global_atomic_smin_x2', (('VDST', 2, 'i'), ('ADDR', 2, 'i'), ('DATA', 2, 'i'), ('SADDR', 2, 'i'))), - 0x56: ('global_atomic_umin_x2', (('VDST', 2, 'i'), ('ADDR', 2, 'i'), ('DATA', 2, 'i'), ('SADDR', 2, 'i'))), - 0x57: ('global_atomic_smax_x2', (('VDST', 2, 'i'), ('ADDR', 2, 'i'), ('DATA', 2, 'i'), ('SADDR', 2, 'i'))), - 0x58: ('global_atomic_umax_x2', (('VDST', 2, 'i'), ('ADDR', 2, 'i'), ('DATA', 2, 'i'), ('SADDR', 2, 'i'))), - 0x59: ('global_atomic_and_x2', (('VDST', 2, 'i'), ('ADDR', 2, 'i'), ('DATA', 2, 'i'), ('SADDR', 2, 'i'))), - 0x5a: ('global_atomic_or_x2', (('VDST', 2, 'i'), ('ADDR', 2, 'i'), ('DATA', 2, 'i'), ('SADDR', 2, 'i'))), - 0x5b: ('global_atomic_xor_x2', (('VDST', 2, 'i'), ('ADDR', 2, 'i'), ('DATA', 2, 'i'), ('SADDR', 2, 'i'))), - 0x5c: ('global_atomic_inc_x2', (('VDST', 2, 'i'), ('ADDR', 2, 'i'), ('DATA', 2, 'i'), ('SADDR', 2, 'i'))), - 0x5d: ('global_atomic_dec_x2', (('VDST', 2, 'i'), ('ADDR', 2, 'i'), ('DATA', 2, 'i'), ('SADDR', 2, 'i'))), - 0x5e: ('global_atomic_fcmpswap_x2', (('VDST', 2, 'f64'), ('ADDR', 2, 'i'), ('DATA', 4, 'i'), ('SADDR', 2, 'i'))), - 0x5f: ('global_atomic_fmin_x2', (('VDST', 2, 'i'), ('ADDR', 2, 'i'), ('DATA', 2, 'i'), ('SADDR', 2, 'i'))), - 0x60: ('global_atomic_fmax_x2', (('VDST', 2, 'i'), ('ADDR', 2, 'i'), ('DATA', 2, 'i'), ('SADDR', 2, 'i'))), -} - -MIMG = { - 0x0: ('image_load', (('VDATA', 4, 'i'), ('VADDR', 4, 'i'), ('SRSRC', 8, 'i'))), - 0x1: ('image_load_mip', (('VDATA', 4, 'i'), ('VADDR', 4, 'i'), ('SRSRC', 8, 'i'))), - 0x2: ('image_load_pck', (('VDATA', 4, 'i'), ('VADDR', 4, 'i'), ('SRSRC', 8, 'i'))), - 0x3: ('image_load_pck_sgn', (('VDATA', 4, 'i'), ('VADDR', 4, 'i'), ('SRSRC', 8, 'i'))), - 0x4: ('image_load_mip_pck', (('VDATA', 4, 'i'), ('VADDR', 4, 'i'), ('SRSRC', 8, 'i'))), - 0x5: ('image_load_mip_pck_sgn', (('VDATA', 4, 'i'), ('VADDR', 4, 'i'), ('SRSRC', 8, 'i'))), - 0x8: ('image_store', (('VDATA', 4, 'i'), ('VADDR', 4, 'i'), ('SRSRC', 8, 'i'))), - 0x9: ('image_store_mip', (('VDATA', 4, 'i'), ('VADDR', 4, 'i'), ('SRSRC', 8, 'i'))), - 0xa: ('image_store_pck', (('VDATA', 4, 'i'), ('VADDR', 4, 'i'), ('SRSRC', 8, 'i'))), - 0xb: ('image_store_mip_pck', (('VDATA', 4, 'i'), ('VADDR', 4, 'i'), ('SRSRC', 8, 'i'))), - 0xe: ('image_get_resinfo', (('VDATA', 4, 'i'), ('VADDR', 1, 'i'), ('SRSRC', 8, 'i'))), - 0xf: ('image_atomic_swap', (('VDATA', 4, 'i'), ('VADDR', 4, 'i'), ('SRSRC', 8, 'i'))), - 0x10: ('image_atomic_cmpswap', (('VDATA', 1, 'i'), ('VADDR', 4, 'i'), ('SRSRC', 8, 'i'))), - 0x11: ('image_atomic_add', (('VDATA', 4, 'i'), ('VADDR', 4, 'i'), ('SRSRC', 8, 'i'))), - 0x12: ('image_atomic_sub', (('VDATA', 4, 'i'), ('VADDR', 4, 'i'), ('SRSRC', 8, 'i'))), - 0x14: ('image_atomic_smin', (('VDATA', 4, 'i'), ('VADDR', 4, 'i'), ('SRSRC', 8, 'i'))), - 0x15: ('image_atomic_umin', (('VDATA', 4, 'i'), ('VADDR', 4, 'i'), ('SRSRC', 8, 'i'))), - 0x16: ('image_atomic_smax', (('VDATA', 4, 'i'), ('VADDR', 4, 'i'), ('SRSRC', 8, 'i'))), - 0x17: ('image_atomic_umax', (('VDATA', 4, 'i'), ('VADDR', 4, 'i'), ('SRSRC', 8, 'i'))), - 0x18: ('image_atomic_and', (('VDATA', 4, 'i'), ('VADDR', 4, 'i'), ('SRSRC', 8, 'i'))), - 0x19: ('image_atomic_or', (('VDATA', 4, 'i'), ('VADDR', 4, 'i'), ('SRSRC', 8, 'i'))), - 0x1a: ('image_atomic_xor', (('VDATA', 4, 'i'), ('VADDR', 4, 'i'), ('SRSRC', 8, 'i'))), - 0x1b: ('image_atomic_inc', (('VDATA', 4, 'i'), ('VADDR', 4, 'i'), ('SRSRC', 8, 'i'))), - 0x1c: ('image_atomic_dec', (('VDATA', 4, 'i'), ('VADDR', 4, 'i'), ('SRSRC', 8, 'i'))), - 0x1d: ('image_atomic_fcmpswap', (('VDATA', 1, 'f32'), ('VADDR', 4, 'i'), ('SRSRC', 8, 'i'))), - 0x1e: ('image_atomic_fmin', (('VDATA', 4, 'i'), ('VADDR', 4, 'i'), ('SRSRC', 8, 'i'))), - 0x1f: ('image_atomic_fmax', (('VDATA', 4, 'i'), ('VADDR', 4, 'i'), ('SRSRC', 8, 'i'))), - 0x20: ('image_sample', (('VDATA', 4, 'i'), ('VADDR', 3, 'f32'), ('SRSRC', 8, 'i'), ('SSAMP', 4, 'i'))), - 0x21: ('image_sample_cl', (('VDATA', 4, 'i'), ('VADDR', 4, 'f32'), ('SRSRC', 8, 'i'), ('SSAMP', 4, 'i'))), - 0x22: ('image_sample_d', (('VDATA', 4, 'i'), ('VADDR', 9, 'f32'), ('SRSRC', 8, 'i'), ('SSAMP', 4, 'i'))), - 0x23: ('image_sample_d_cl', (('VDATA', 4, 'i'), ('VADDR', 10, 'f32'), ('SRSRC', 8, 'i'), ('SSAMP', 4, 'i'))), - 0x24: ('image_sample_l', (('VDATA', 4, 'i'), ('VADDR', 4, 'f32'), ('SRSRC', 8, 'i'), ('SSAMP', 4, 'i'))), - 0x25: ('image_sample_b', (('VDATA', 4, 'i'), ('VADDR', 4, 'f32'), ('SRSRC', 8, 'i'), ('SSAMP', 4, 'i'))), - 0x26: ('image_sample_b_cl', (('VDATA', 4, 'i'), ('VADDR', 5, 'f32'), ('SRSRC', 8, 'i'), ('SSAMP', 4, 'i'))), - 0x27: ('image_sample_lz', (('VDATA', 4, 'i'), ('VADDR', 3, 'f32'), ('SRSRC', 8, 'i'), ('SSAMP', 4, 'i'))), - 0x28: ('image_sample_c', (('VDATA', 4, 'i'), ('VADDR', 4, 'f32'), ('SRSRC', 8, 'i'), ('SSAMP', 4, 'i'))), - 0x29: ('image_sample_c_cl', (('VDATA', 4, 'i'), ('VADDR', 5, 'f32'), ('SRSRC', 8, 'i'), ('SSAMP', 4, 'i'))), - 0x2a: ('image_sample_c_d', (('VDATA', 4, 'i'), ('VADDR', 10, 'f32'), ('SRSRC', 8, 'i'), ('SSAMP', 4, 'i'))), - 0x2b: ('image_sample_c_d_cl', (('VDATA', 4, 'i'), ('VADDR', 11, 'f32'), ('SRSRC', 8, 'i'), ('SSAMP', 4, 'i'))), - 0x2c: ('image_sample_c_l', (('VDATA', 4, 'i'), ('VADDR', 5, 'f32'), ('SRSRC', 8, 'i'), ('SSAMP', 4, 'i'))), - 0x2d: ('image_sample_c_b', (('VDATA', 4, 'i'), ('VADDR', 5, 'f32'), ('SRSRC', 8, 'i'), ('SSAMP', 4, 'i'))), - 0x2e: ('image_sample_c_b_cl', (('VDATA', 4, 'i'), ('VADDR', 6, 'f32'), ('SRSRC', 8, 'i'), ('SSAMP', 4, 'i'))), - 0x2f: ('image_sample_c_lz', (('VDATA', 4, 'i'), ('VADDR', 4, 'f32'), ('SRSRC', 8, 'i'), ('SSAMP', 4, 'i'))), - 0x30: ('image_sample_o', (('VDATA', 4, 'i'), ('VADDR', 4, 'f32'), ('SRSRC', 8, 'i'), ('SSAMP', 4, 'i'))), - 0x31: ('image_sample_cl_o', (('VDATA', 4, 'i'), ('VADDR', 5, 'f32'), ('SRSRC', 8, 'i'), ('SSAMP', 4, 'i'))), - 0x32: ('image_sample_d_o', (('VDATA', 4, 'i'), ('VADDR', 10, 'f32'), ('SRSRC', 8, 'i'), ('SSAMP', 4, 'i'))), - 0x33: ('image_sample_d_cl_o', (('VDATA', 4, 'i'), ('VADDR', 11, 'f32'), ('SRSRC', 8, 'i'), ('SSAMP', 4, 'i'))), - 0x34: ('image_sample_l_o', (('VDATA', 4, 'i'), ('VADDR', 5, 'f32'), ('SRSRC', 8, 'i'), ('SSAMP', 4, 'i'))), - 0x35: ('image_sample_b_o', (('VDATA', 4, 'i'), ('VADDR', 5, 'f32'), ('SRSRC', 8, 'i'), ('SSAMP', 4, 'i'))), - 0x36: ('image_sample_b_cl_o', (('VDATA', 4, 'i'), ('VADDR', 6, 'f32'), ('SRSRC', 8, 'i'), ('SSAMP', 4, 'i'))), - 0x37: ('image_sample_lz_o', (('VDATA', 4, 'i'), ('VADDR', 4, 'f32'), ('SRSRC', 8, 'i'), ('SSAMP', 4, 'i'))), - 0x38: ('image_sample_c_o', (('VDATA', 4, 'i'), ('VADDR', 5, 'f32'), ('SRSRC', 8, 'i'), ('SSAMP', 4, 'i'))), - 0x39: ('image_sample_c_cl_o', (('VDATA', 4, 'i'), ('VADDR', 6, 'f32'), ('SRSRC', 8, 'i'), ('SSAMP', 4, 'i'))), - 0x3a: ('image_sample_c_d_o', (('VDATA', 4, 'i'), ('VADDR', 11, 'f32'), ('SRSRC', 8, 'i'), ('SSAMP', 4, 'i'))), - 0x3b: ('image_sample_c_d_cl_o', (('VDATA', 4, 'i'), ('VADDR', 12, 'f32'), ('SRSRC', 8, 'i'), ('SSAMP', 4, 'i'))), - 0x3c: ('image_sample_c_l_o', (('VDATA', 4, 'i'), ('VADDR', 6, 'f32'), ('SRSRC', 8, 'i'), ('SSAMP', 4, 'i'))), - 0x3d: ('image_sample_c_b_o', (('VDATA', 4, 'i'), ('VADDR', 6, 'f32'), ('SRSRC', 8, 'i'), ('SSAMP', 4, 'i'))), - 0x3e: ('image_sample_c_b_cl_o', (('VDATA', 4, 'i'), ('VADDR', 7, 'f32'), ('SRSRC', 8, 'i'), ('SSAMP', 4, 'i'))), - 0x3f: ('image_sample_c_lz_o', (('VDATA', 4, 'i'), ('VADDR', 5, 'f32'), ('SRSRC', 8, 'i'), ('SSAMP', 4, 'i'))), - 0x40: ('image_gather4', (('VDATA', 4, 'i'), ('VADDR', 3, 'f32'), ('SRSRC', 8, 'i'), ('SSAMP', 4, 'i'))), - 0x41: ('image_gather4_cl', (('VDATA', 4, 'i'), ('VADDR', 4, 'f32'), ('SRSRC', 8, 'i'), ('SSAMP', 4, 'i'))), - 0x42: ('image_load_by2', (('VDATA', 4, 'i'), ('VADDR', 4, 'i'), ('SRSRC', 8, 'i'))), - 0x43: ('image_load_by4', (('VDATA', 4, 'i'), ('VADDR', 4, 'i'), ('SRSRC', 8, 'i'))), - 0x44: ('image_gather4_l', (('VDATA', 4, 'i'), ('VADDR', 4, 'f32'), ('SRSRC', 8, 'i'), ('SSAMP', 4, 'i'))), - 0x45: ('image_gather4_b', (('VDATA', 4, 'i'), ('VADDR', 4, 'f32'), ('SRSRC', 8, 'i'), ('SSAMP', 4, 'i'))), - 0x46: ('image_gather4_b_cl', (('VDATA', 4, 'i'), ('VADDR', 5, 'f32'), ('SRSRC', 8, 'i'), ('SSAMP', 4, 'i'))), - 0x47: ('image_gather4_lz', (('VDATA', 4, 'i'), ('VADDR', 3, 'f32'), ('SRSRC', 8, 'i'), ('SSAMP', 4, 'i'))), - 0x48: ('image_gather4_c', (('VDATA', 4, 'i'), ('VADDR', 4, 'f32'), ('SRSRC', 8, 'i'), ('SSAMP', 4, 'i'))), - 0x49: ('image_gather4_c_cl', (('VDATA', 4, 'i'), ('VADDR', 5, 'f32'), ('SRSRC', 8, 'i'), ('SSAMP', 4, 'i'))), - 0x4a: ('image_load_mip_by2', (('VDATA', 4, 'i'), ('VADDR', 4, 'i'), ('SRSRC', 8, 'i'))), - 0x4b: ('image_load_mip_by4', (('VDATA', 4, 'i'), ('VADDR', 4, 'i'), ('SRSRC', 8, 'i'))), - 0x4c: ('image_gather4_c_l', (('VDATA', 4, 'i'), ('VADDR', 5, 'f32'), ('SRSRC', 8, 'i'), ('SSAMP', 4, 'i'))), - 0x4d: ('image_gather4_c_b', (('VDATA', 4, 'i'), ('VADDR', 5, 'f32'), ('SRSRC', 8, 'i'), ('SSAMP', 4, 'i'))), - 0x4e: ('image_gather4_c_b_cl', (('VDATA', 4, 'i'), ('VADDR', 6, 'f32'), ('SRSRC', 8, 'i'), ('SSAMP', 4, 'i'))), - 0x4f: ('image_gather4_c_lz', (('VDATA', 4, 'i'), ('VADDR', 4, 'f32'), ('SRSRC', 8, 'i'), ('SSAMP', 4, 'i'))), - 0x50: ('image_gather4_o', (('VDATA', 4, 'i'), ('VADDR', 4, 'f32'), ('SRSRC', 8, 'i'), ('SSAMP', 4, 'i'))), - 0x51: ('image_gather4_cl_o', (('VDATA', 4, 'i'), ('VADDR', 5, 'f32'), ('SRSRC', 8, 'i'), ('SSAMP', 4, 'i'))), - 0x52: ('image_store_by2', (('VDATA', 4, 'i'), ('VADDR', 4, 'i'), ('SRSRC', 8, 'i'))), - 0x53: ('image_store_by4', (('VDATA', 4, 'i'), ('VADDR', 4, 'i'), ('SRSRC', 8, 'i'))), - 0x54: ('image_gather4_l_o', (('VDATA', 4, 'i'), ('VADDR', 5, 'f32'), ('SRSRC', 8, 'i'), ('SSAMP', 4, 'i'))), - 0x55: ('image_gather4_b_o', (('VDATA', 4, 'i'), ('VADDR', 5, 'f32'), ('SRSRC', 8, 'i'), ('SSAMP', 4, 'i'))), - 0x56: ('image_gather4_b_cl_o', (('VDATA', 4, 'i'), ('VADDR', 6, 'f32'), ('SRSRC', 8, 'i'), ('SSAMP', 4, 'i'))), - 0x57: ('image_gather4_lz_o', (('VDATA', 4, 'i'), ('VADDR', 4, 'f32'), ('SRSRC', 8, 'i'), ('SSAMP', 4, 'i'))), - 0x58: ('image_gather4_c_o', (('VDATA', 4, 'i'), ('VADDR', 5, 'f32'), ('SRSRC', 8, 'i'), ('SSAMP', 4, 'i'))), - 0x59: ('image_gather4_c_cl_o', (('VDATA', 4, 'i'), ('VADDR', 6, 'f32'), ('SRSRC', 8, 'i'), ('SSAMP', 4, 'i'))), - 0x5a: ('image_store_mip_by2', (('VDATA', 4, 'i'), ('VADDR', 4, 'i'), ('SRSRC', 8, 'i'))), - 0x5b: ('image_store_mip_by4', (('VDATA', 4, 'i'), ('VADDR', 4, 'i'), ('SRSRC', 8, 'i'))), - 0x5c: ('image_gather4_c_l_o', (('VDATA', 4, 'i'), ('VADDR', 6, 'f32'), ('SRSRC', 8, 'i'), ('SSAMP', 4, 'i'))), - 0x5d: ('image_gather4_c_b_o', (('VDATA', 4, 'i'), ('VADDR', 6, 'f32'), ('SRSRC', 8, 'i'), ('SSAMP', 4, 'i'))), - 0x5e: ('image_gather4_c_b_cl_o', (('VDATA', 4, 'i'), ('VADDR', 7, 'f32'), ('SRSRC', 8, 'i'), ('SSAMP', 4, 'i'))), - 0x5f: ('image_gather4_c_lz_o', (('VDATA', 4, 'i'), ('VADDR', 5, 'f32'), ('SRSRC', 8, 'i'), ('SSAMP', 4, 'i'))), - 0x60: ('image_get_lod', (('VDATA', 4, 'i'), ('VADDR', 3, 'f32'), ('SRSRC', 8, 'i'), ('SSAMP', 4, 'i'))), - 0x61: ('image_gather4h', (('VDATA', 4, 'i'), ('VADDR', 3, 'f32'), ('SRSRC', 8, 'i'), ('SSAMP', 4, 'i'))), - 0x62: ('image_gather4h_pck', (('VDATA', 4, 'i'), ('VADDR', 3, 'f32'), ('SRSRC', 8, 'i'), ('SSAMP', 4, 'i'))), - 0x63: ('image_gather8h_pck', (('VDATA', 4, 'i'), ('VADDR', 3, 'f32'), ('SRSRC', 8, 'i'), ('SSAMP', 4, 'i'))), - 0x68: ('image_sample_cd', (('VDATA', 4, 'i'), ('VADDR', 9, 'f32'), ('SRSRC', 8, 'i'), ('SSAMP', 4, 'i'))), - 0x69: ('image_sample_cd_cl', (('VDATA', 4, 'i'), ('VADDR', 10, 'f32'), ('SRSRC', 8, 'i'), ('SSAMP', 4, 'i'))), - 0x6a: ('image_sample_c_cd', (('VDATA', 4, 'i'), ('VADDR', 10, 'f32'), ('SRSRC', 8, 'i'), ('SSAMP', 4, 'i'))), - 0x6b: ('image_sample_c_cd_cl', (('VDATA', 4, 'i'), ('VADDR', 11, 'f32'), ('SRSRC', 8, 'i'), ('SSAMP', 4, 'i'))), - 0x6c: ('image_sample_cd_o', (('VDATA', 4, 'i'), ('VADDR', 10, 'f32'), ('SRSRC', 8, 'i'), ('SSAMP', 4, 'i'))), - 0x6d: ('image_sample_cd_cl_o', (('VDATA', 4, 'i'), ('VADDR', 11, 'f32'), ('SRSRC', 8, 'i'), ('SSAMP', 4, 'i'))), - 0x6e: ('image_sample_c_cd_o', (('VDATA', 4, 'i'), ('VADDR', 11, 'f32'), ('SRSRC', 8, 'i'), ('SSAMP', 4, 'i'))), - 0x6f: ('image_sample_c_cd_cl_o', (('VDATA', 4, 'i'), ('VADDR', 12, 'f32'), ('SRSRC', 8, 'i'), ('SSAMP', 4, 'i'))), - 0x70: ('image_load_pck2', (('VDATA', 4, 'i'), ('VADDR', 4, 'i'), ('SRSRC', 8, 'i'))), - 0x71: ('image_load_pck4', (('VDATA', 4, 'i'), ('VADDR', 4, 'i'), ('SRSRC', 8, 'i'))), - 0x73: ('image_load_mip_pck2', (('VDATA', 4, 'i'), ('VADDR', 4, 'i'), ('SRSRC', 8, 'i'))), - 0x74: ('image_load_mip_pck4', (('VDATA', 4, 'i'), ('VADDR', 4, 'i'), ('SRSRC', 8, 'i'))), - 0x76: ('image_store_pck2', (('VDATA', 4, 'i'), ('VADDR', 4, 'i'), ('SRSRC', 8, 'i'))), - 0x77: ('image_store_pck4', (('VDATA', 4, 'i'), ('VADDR', 4, 'i'), ('SRSRC', 8, 'i'))), - 0x79: ('image_store_mip_pck2', (('VDATA', 4, 'i'), ('VADDR', 4, 'i'), ('SRSRC', 8, 'i'))), - 0x7a: ('image_store_mip_pck4', (('VDATA', 4, 'i'), ('VADDR', 4, 'i'), ('SRSRC', 8, 'i'))), - 0x80: ('image_msaa_load', (('VDATA', 4, 'i'), ('VADDR', 4, 'i'), ('SRSRC', 8, 'i'))), - 0xa2: ('image_sample_d_g16', (('VDATA', 4, 'i'), ('VADDR', 7, 'f32'), ('SRSRC', 8, 'i'), ('SSAMP', 4, 'i'))), - 0xa3: ('image_sample_d_cl_g16', (('VDATA', 4, 'i'), ('VADDR', 8, 'f32'), ('SRSRC', 8, 'i'), ('SSAMP', 4, 'i'))), - 0xaa: ('image_sample_c_d_g16', (('VDATA', 4, 'i'), ('VADDR', 8, 'f32'), ('SRSRC', 8, 'i'), ('SSAMP', 4, 'i'))), - 0xab: ('image_sample_c_d_cl_g16', (('VDATA', 4, 'i'), ('VADDR', 9, 'f32'), ('SRSRC', 8, 'i'), ('SSAMP', 4, 'i'))), - 0xb2: ('image_sample_d_o_g16', (('VDATA', 4, 'i'), ('VADDR', 8, 'f32'), ('SRSRC', 8, 'i'), ('SSAMP', 4, 'i'))), - 0xb3: ('image_sample_d_cl_o_g16', (('VDATA', 4, 'i'), ('VADDR', 9, 'f32'), ('SRSRC', 8, 'i'), ('SSAMP', 4, 'i'))), - 0xba: ('image_sample_c_d_o_g16', (('VDATA', 4, 'i'), ('VADDR', 9, 'f32'), ('SRSRC', 8, 'i'), ('SSAMP', 4, 'i'))), - 0xbb: ('image_sample_c_d_cl_o_g16', (('VDATA', 4, 'i'), ('VADDR', 10, 'f32'), ('SRSRC', 8, 'i'), ('SSAMP', 4, 'i'))), - 0xe6: ('image_bvh_intersect_ray', (('VDATA', 4, 'i'), ('VADDR', 11, 'i'), ('SRSRC', 4, 'i'))), - 0xe7: ('image_bvh64_intersect_ray', (('VDATA', 4, 'i'), ('VADDR', 12, 'i'), ('SRSRC', 4, 'i'))), - 0xe8: ('image_sample_cd_g16', (('VDATA', 4, 'i'), ('VADDR', 7, 'f32'), ('SRSRC', 8, 'i'), ('SSAMP', 4, 'i'))), - 0xe9: ('image_sample_cd_cl_g16', (('VDATA', 4, 'i'), ('VADDR', 8, 'f32'), ('SRSRC', 8, 'i'), ('SSAMP', 4, 'i'))), - 0xea: ('image_sample_c_cd_g16', (('VDATA', 4, 'i'), ('VADDR', 8, 'f32'), ('SRSRC', 8, 'i'), ('SSAMP', 4, 'i'))), - 0xeb: ('image_sample_c_cd_cl_g16', (('VDATA', 4, 'i'), ('VADDR', 9, 'f32'), ('SRSRC', 8, 'i'), ('SSAMP', 4, 'i'))), - 0xec: ('image_sample_cd_o_g16', (('VDATA', 4, 'i'), ('VADDR', 8, 'f32'), ('SRSRC', 8, 'i'), ('SSAMP', 4, 'i'))), - 0xed: ('image_sample_cd_cl_o_g16', (('VDATA', 4, 'i'), ('VADDR', 9, 'f32'), ('SRSRC', 8, 'i'), ('SSAMP', 4, 'i'))), - 0xee: ('image_sample_c_cd_o_g16', (('VDATA', 4, 'i'), ('VADDR', 9, 'f32'), ('SRSRC', 8, 'i'), ('SSAMP', 4, 'i'))), - 0xef: ('image_sample_c_cd_cl_o_g16', (('VDATA', 4, 'i'), ('VADDR', 10, 'f32'), ('SRSRC', 8, 'i'), ('SSAMP', 4, 'i'))), -} - -MTBUF = { - 0x0: ('tbuffer_load_format_x', (('VDATA', 1, 'i'), ('VADDR', 2, 'i'), ('SRSRC', 4, 'i'), ('SOFFSET', 1, 'i'))), - 0x1: ('tbuffer_load_format_xy', (('VDATA', 2, 'i'), ('VADDR', 2, 'i'), ('SRSRC', 4, 'i'), ('SOFFSET', 1, 'i'))), - 0x2: ('tbuffer_load_format_xyz', (('VDATA', 3, 'i'), ('VADDR', 2, 'i'), ('SRSRC', 4, 'i'), ('SOFFSET', 1, 'i'))), - 0x3: ('tbuffer_load_format_xyzw', (('VDATA', 4, 'i'), ('VADDR', 2, 'i'), ('SRSRC', 4, 'i'), ('SOFFSET', 1, 'i'))), - 0x4: ('tbuffer_store_format_x', (('VDATA', 1, 'i'), ('VADDR', 2, 'i'), ('SRSRC', 4, 'i'), ('SOFFSET', 1, 'i'))), - 0x5: ('tbuffer_store_format_xy', (('VDATA', 2, 'i'), ('VADDR', 2, 'i'), ('SRSRC', 4, 'i'), ('SOFFSET', 1, 'i'))), - 0x6: ('tbuffer_store_format_xyz', (('VDATA', 3, 'i'), ('VADDR', 2, 'i'), ('SRSRC', 4, 'i'), ('SOFFSET', 1, 'i'))), - 0x7: ('tbuffer_store_format_xyzw', (('VDATA', 4, 'i'), ('VADDR', 2, 'i'), ('SRSRC', 4, 'i'), ('SOFFSET', 1, 'i'))), - 0x8: ('tbuffer_load_format_d16_x', (('VDATA', 1, 'i'), ('VADDR', 2, 'i'), ('SRSRC', 4, 'i'), ('SOFFSET', 1, 'i'))), - 0x9: ('tbuffer_load_format_d16_xy', (('VDATA', 1, 'i'), ('VADDR', 2, 'i'), ('SRSRC', 4, 'i'), ('SOFFSET', 1, 'i'))), - 0xa: ('tbuffer_load_format_d16_xyz', (('VDATA', 2, 'i'), ('VADDR', 2, 'i'), ('SRSRC', 4, 'i'), ('SOFFSET', 1, 'i'))), - 0xb: ('tbuffer_load_format_d16_xyzw', (('VDATA', 2, 'i'), ('VADDR', 2, 'i'), ('SRSRC', 4, 'i'), ('SOFFSET', 1, 'i'))), - 0xc: ('tbuffer_store_format_d16_x', (('VDATA', 1, 'i'), ('VADDR', 2, 'i'), ('SRSRC', 4, 'i'), ('SOFFSET', 1, 'i'))), - 0xd: ('tbuffer_store_format_d16_xy', (('VDATA', 1, 'i'), ('VADDR', 2, 'i'), ('SRSRC', 4, 'i'), ('SOFFSET', 1, 'i'))), - 0xe: ('tbuffer_store_format_d16_xyz', (('VDATA', 2, 'i'), ('VADDR', 2, 'i'), ('SRSRC', 4, 'i'), ('SOFFSET', 1, 'i'))), - 0xf: ('tbuffer_store_format_d16_xyzw', (('VDATA', 2, 'i'), ('VADDR', 2, 'i'), ('SRSRC', 4, 'i'), ('SOFFSET', 1, 'i'))), -} - -MUBUF = { - 0x0: ('buffer_load_format_x', (('VDATA', 1, 'i'), ('VADDR', 2, 'i'), ('SRSRC', 4, 'i'), ('SOFFSET', 1, 'i'))), - 0x1: ('buffer_load_format_xy', (('VDATA', 2, 'i'), ('VADDR', 2, 'i'), ('SRSRC', 4, 'i'), ('SOFFSET', 1, 'i'))), - 0x2: ('buffer_load_format_xyz', (('VDATA', 3, 'i'), ('VADDR', 2, 'i'), ('SRSRC', 4, 'i'), ('SOFFSET', 1, 'i'))), - 0x3: ('buffer_load_format_xyzw', (('VDATA', 4, 'i'), ('VADDR', 2, 'i'), ('SRSRC', 4, 'i'), ('SOFFSET', 1, 'i'))), - 0x4: ('buffer_store_format_x', (('VDATA', 1, 'i'), ('VADDR', 2, 'i'), ('SRSRC', 4, 'i'), ('SOFFSET', 1, 'i'))), - 0x5: ('buffer_store_format_xy', (('VDATA', 2, 'i'), ('VADDR', 2, 'i'), ('SRSRC', 4, 'i'), ('SOFFSET', 1, 'i'))), - 0x6: ('buffer_store_format_xyz', (('VDATA', 3, 'i'), ('VADDR', 2, 'i'), ('SRSRC', 4, 'i'), ('SOFFSET', 1, 'i'))), - 0x7: ('buffer_store_format_xyzw', (('VDATA', 4, 'i'), ('VADDR', 2, 'i'), ('SRSRC', 4, 'i'), ('SOFFSET', 1, 'i'))), - 0x8: ('buffer_load_ubyte', (('VDATA', 1, 'i'), ('VADDR', 2, 'i'), ('SRSRC', 4, 'i'), ('SOFFSET', 1, 'i'))), - 0x9: ('buffer_load_sbyte', (('VDATA', 1, 'i'), ('VADDR', 2, 'i'), ('SRSRC', 4, 'i'), ('SOFFSET', 1, 'i'))), - 0xa: ('buffer_load_ushort', (('VDATA', 1, 'i'), ('VADDR', 2, 'i'), ('SRSRC', 4, 'i'), ('SOFFSET', 1, 'i'))), - 0xb: ('buffer_load_sshort', (('VDATA', 1, 'i'), ('VADDR', 2, 'i'), ('SRSRC', 4, 'i'), ('SOFFSET', 1, 'i'))), - 0xc: ('buffer_load_dword', (('VDATA', 1, 'i'), ('VADDR', 2, 'i'), ('SRSRC', 4, 'i'), ('SOFFSET', 1, 'i'))), - 0xd: ('buffer_load_dwordx2', (('VDATA', 2, 'i'), ('VADDR', 2, 'i'), ('SRSRC', 4, 'i'), ('SOFFSET', 1, 'i'))), - 0xe: ('buffer_load_dwordx4', (('VDATA', 4, 'i'), ('VADDR', 2, 'i'), ('SRSRC', 4, 'i'), ('SOFFSET', 1, 'i'))), - 0xf: ('buffer_load_dwordx3', (('VDATA', 3, 'i'), ('VADDR', 2, 'i'), ('SRSRC', 4, 'i'), ('SOFFSET', 1, 'i'))), - 0x18: ('buffer_store_byte', (('VDATA', 1, 'i'), ('VADDR', 2, 'i'), ('SRSRC', 4, 'i'), ('SOFFSET', 1, 'i'))), - 0x19: ('buffer_store_byte_d16_hi', (('VDATA', 1, 'i'), ('VADDR', 2, 'i'), ('SRSRC', 4, 'i'), ('SOFFSET', 1, 'i'))), - 0x1a: ('buffer_store_short', (('VDATA', 1, 'i'), ('VADDR', 2, 'i'), ('SRSRC', 4, 'i'), ('SOFFSET', 1, 'i'))), - 0x1b: ('buffer_store_short_d16_hi', (('VDATA', 1, 'i'), ('VADDR', 2, 'i'), ('SRSRC', 4, 'i'), ('SOFFSET', 1, 'i'))), - 0x1c: ('buffer_store_dword', (('VDATA', 1, 'i'), ('VADDR', 2, 'i'), ('SRSRC', 4, 'i'), ('SOFFSET', 1, 'i'))), - 0x1d: ('buffer_store_dwordx2', (('VDATA', 2, 'i'), ('VADDR', 2, 'i'), ('SRSRC', 4, 'i'), ('SOFFSET', 1, 'i'))), - 0x1e: ('buffer_store_dwordx4', (('VDATA', 4, 'i'), ('VADDR', 2, 'i'), ('SRSRC', 4, 'i'), ('SOFFSET', 1, 'i'))), - 0x1f: ('buffer_store_dwordx3', (('VDATA', 3, 'i'), ('VADDR', 2, 'i'), ('SRSRC', 4, 'i'), ('SOFFSET', 1, 'i'))), - 0x20: ('buffer_load_ubyte_d16', (('VDATA', 1, 'i'), ('VADDR', 2, 'i'), ('SRSRC', 4, 'i'), ('SOFFSET', 1, 'i'))), - 0x21: ('buffer_load_ubyte_d16_hi', (('VDATA', 1, 'i'), ('VADDR', 2, 'i'), ('SRSRC', 4, 'i'), ('SOFFSET', 1, 'i'))), - 0x22: ('buffer_load_sbyte_d16', (('VDATA', 1, 'i'), ('VADDR', 2, 'i'), ('SRSRC', 4, 'i'), ('SOFFSET', 1, 'i'))), - 0x23: ('buffer_load_sbyte_d16_hi', (('VDATA', 1, 'i'), ('VADDR', 2, 'i'), ('SRSRC', 4, 'i'), ('SOFFSET', 1, 'i'))), - 0x24: ('buffer_load_short_d16', (('VDATA', 1, 'i'), ('VADDR', 2, 'i'), ('SRSRC', 4, 'i'), ('SOFFSET', 1, 'i'))), - 0x25: ('buffer_load_short_d16_hi', (('VDATA', 1, 'i'), ('VADDR', 2, 'i'), ('SRSRC', 4, 'i'), ('SOFFSET', 1, 'i'))), - 0x26: ('buffer_load_format_d16_hi_x', (('VDATA', 1, 'i'), ('VADDR', 2, 'i'), ('SRSRC', 4, 'i'), ('SOFFSET', 1, 'i'))), - 0x27: ('buffer_store_format_d16_hi_x', (('VDATA', 1, 'i'), ('VADDR', 2, 'i'), ('SRSRC', 4, 'i'), ('SOFFSET', 1, 'i'))), - 0x30: ('buffer_atomic_swap', (('VDATA', 1, 'i'), ('VADDR', 2, 'i'), ('SRSRC', 4, 'i'), ('SOFFSET', 1, 'i'))), - 0x31: ('buffer_atomic_cmpswap', (('VDATA', 2, 'i'), ('VADDR', 2, 'i'), ('SRSRC', 4, 'i'), ('SOFFSET', 1, 'i'))), - 0x32: ('buffer_atomic_add', (('VDATA', 1, 'i'), ('VADDR', 2, 'i'), ('SRSRC', 4, 'i'), ('SOFFSET', 1, 'i'))), - 0x33: ('buffer_atomic_sub', (('VDATA', 1, 'i'), ('VADDR', 2, 'i'), ('SRSRC', 4, 'i'), ('SOFFSET', 1, 'i'))), - 0x34: ('buffer_atomic_csub', (('VDATA', 1, 'i'), ('VADDR', 2, 'i'), ('SRSRC', 4, 'i'), ('SOFFSET', 1, 'i'))), - 0x35: ('buffer_atomic_smin', (('VDATA', 1, 'i'), ('VADDR', 2, 'i'), ('SRSRC', 4, 'i'), ('SOFFSET', 1, 'i'))), - 0x36: ('buffer_atomic_umin', (('VDATA', 1, 'i'), ('VADDR', 2, 'i'), ('SRSRC', 4, 'i'), ('SOFFSET', 1, 'i'))), - 0x37: ('buffer_atomic_smax', (('VDATA', 1, 'i'), ('VADDR', 2, 'i'), ('SRSRC', 4, 'i'), ('SOFFSET', 1, 'i'))), - 0x38: ('buffer_atomic_umax', (('VDATA', 1, 'i'), ('VADDR', 2, 'i'), ('SRSRC', 4, 'i'), ('SOFFSET', 1, 'i'))), - 0x39: ('buffer_atomic_and', (('VDATA', 1, 'i'), ('VADDR', 2, 'i'), ('SRSRC', 4, 'i'), ('SOFFSET', 1, 'i'))), - 0x3a: ('buffer_atomic_or', (('VDATA', 1, 'i'), ('VADDR', 2, 'i'), ('SRSRC', 4, 'i'), ('SOFFSET', 1, 'i'))), - 0x3b: ('buffer_atomic_xor', (('VDATA', 1, 'i'), ('VADDR', 2, 'i'), ('SRSRC', 4, 'i'), ('SOFFSET', 1, 'i'))), - 0x3c: ('buffer_atomic_inc', (('VDATA', 1, 'i'), ('VADDR', 2, 'i'), ('SRSRC', 4, 'i'), ('SOFFSET', 1, 'i'))), - 0x3d: ('buffer_atomic_dec', (('VDATA', 1, 'i'), ('VADDR', 2, 'i'), ('SRSRC', 4, 'i'), ('SOFFSET', 1, 'i'))), - 0x3e: ('buffer_atomic_fcmpswap', (('VDATA', 2, 'i'), ('VADDR', 2, 'i'), ('SRSRC', 4, 'i'), ('SOFFSET', 1, 'i'))), - 0x3f: ('buffer_atomic_fmin', (('VDATA', 1, 'i'), ('VADDR', 2, 'i'), ('SRSRC', 4, 'i'), ('SOFFSET', 1, 'i'))), - 0x40: ('buffer_atomic_fmax', (('VDATA', 1, 'i'), ('VADDR', 2, 'i'), ('SRSRC', 4, 'i'), ('SOFFSET', 1, 'i'))), - 0x50: ('buffer_atomic_swap_x2', (('VDATA', 2, 'i'), ('VADDR', 2, 'i'), ('SRSRC', 4, 'i'), ('SOFFSET', 1, 'i'))), - 0x51: ('buffer_atomic_cmpswap_x2', (('VDATA', 4, 'i'), ('VADDR', 2, 'i'), ('SRSRC', 4, 'i'), ('SOFFSET', 1, 'i'))), - 0x52: ('buffer_atomic_add_x2', (('VDATA', 2, 'i'), ('VADDR', 2, 'i'), ('SRSRC', 4, 'i'), ('SOFFSET', 1, 'i'))), - 0x53: ('buffer_atomic_sub_x2', (('VDATA', 2, 'i'), ('VADDR', 2, 'i'), ('SRSRC', 4, 'i'), ('SOFFSET', 1, 'i'))), - 0x55: ('buffer_atomic_smin_x2', (('VDATA', 2, 'i'), ('VADDR', 2, 'i'), ('SRSRC', 4, 'i'), ('SOFFSET', 1, 'i'))), - 0x56: ('buffer_atomic_umin_x2', (('VDATA', 2, 'i'), ('VADDR', 2, 'i'), ('SRSRC', 4, 'i'), ('SOFFSET', 1, 'i'))), - 0x57: ('buffer_atomic_smax_x2', (('VDATA', 2, 'i'), ('VADDR', 2, 'i'), ('SRSRC', 4, 'i'), ('SOFFSET', 1, 'i'))), - 0x58: ('buffer_atomic_umax_x2', (('VDATA', 2, 'i'), ('VADDR', 2, 'i'), ('SRSRC', 4, 'i'), ('SOFFSET', 1, 'i'))), - 0x59: ('buffer_atomic_and_x2', (('VDATA', 2, 'i'), ('VADDR', 2, 'i'), ('SRSRC', 4, 'i'), ('SOFFSET', 1, 'i'))), - 0x5a: ('buffer_atomic_or_x2', (('VDATA', 2, 'i'), ('VADDR', 2, 'i'), ('SRSRC', 4, 'i'), ('SOFFSET', 1, 'i'))), - 0x5b: ('buffer_atomic_xor_x2', (('VDATA', 2, 'i'), ('VADDR', 2, 'i'), ('SRSRC', 4, 'i'), ('SOFFSET', 1, 'i'))), - 0x5c: ('buffer_atomic_inc_x2', (('VDATA', 2, 'i'), ('VADDR', 2, 'i'), ('SRSRC', 4, 'i'), ('SOFFSET', 1, 'i'))), - 0x5d: ('buffer_atomic_dec_x2', (('VDATA', 2, 'i'), ('VADDR', 2, 'i'), ('SRSRC', 4, 'i'), ('SOFFSET', 1, 'i'))), - 0x5e: ('buffer_atomic_fcmpswap_x2', (('VDATA', 4, 'i'), ('VADDR', 2, 'i'), ('SRSRC', 4, 'i'), ('SOFFSET', 1, 'i'))), - 0x5f: ('buffer_atomic_fmin_x2', (('VDATA', 2, 'i'), ('VADDR', 2, 'i'), ('SRSRC', 4, 'i'), ('SOFFSET', 1, 'i'))), - 0x60: ('buffer_atomic_fmax_x2', (('VDATA', 2, 'i'), ('VADDR', 2, 'i'), ('SRSRC', 4, 'i'), ('SOFFSET', 1, 'i'))), - 0x71: ('buffer_gl0_inv', ()), - 0x72: ('buffer_gl1_inv', ()), - 0x80: ('buffer_load_format_d16_x', (('VDATA', 1, 'i'), ('VADDR', 2, 'i'), ('SRSRC', 4, 'i'), ('SOFFSET', 1, 'i'))), - 0x81: ('buffer_load_format_d16_xy', (('VDATA', 1, 'i'), ('VADDR', 2, 'i'), ('SRSRC', 4, 'i'), ('SOFFSET', 1, 'i'))), - 0x82: ('buffer_load_format_d16_xyz', (('VDATA', 2, 'i'), ('VADDR', 2, 'i'), ('SRSRC', 4, 'i'), ('SOFFSET', 1, 'i'))), - 0x83: ('buffer_load_format_d16_xyzw', (('VDATA', 2, 'i'), ('VADDR', 2, 'i'), ('SRSRC', 4, 'i'), ('SOFFSET', 1, 'i'))), - 0x84: ('buffer_store_format_d16_x', (('VDATA', 1, 'i'), ('VADDR', 2, 'i'), ('SRSRC', 4, 'i'), ('SOFFSET', 1, 'i'))), - 0x85: ('buffer_store_format_d16_xy', (('VDATA', 1, 'i'), ('VADDR', 2, 'i'), ('SRSRC', 4, 'i'), ('SOFFSET', 1, 'i'))), - 0x86: ('buffer_store_format_d16_xyz', (('VDATA', 2, 'i'), ('VADDR', 2, 'i'), ('SRSRC', 4, 'i'), ('SOFFSET', 1, 'i'))), - 0x87: ('buffer_store_format_d16_xyzw', (('VDATA', 2, 'i'), ('VADDR', 2, 'i'), ('SRSRC', 4, 'i'), ('SOFFSET', 1, 'i'))), -} - -SCRATCH = { - 0x8: ('scratch_load_ubyte', (('VDST', 1, 'i'), ('ADDR', 1, 'i'), ('SADDR', 1, 'i'))), - 0x9: ('scratch_load_sbyte', (('VDST', 1, 'i'), ('ADDR', 1, 'i'), ('SADDR', 1, 'i'))), - 0xa: ('scratch_load_ushort', (('VDST', 1, 'i'), ('ADDR', 1, 'i'), ('SADDR', 1, 'i'))), - 0xb: ('scratch_load_sshort', (('VDST', 1, 'i'), ('ADDR', 1, 'i'), ('SADDR', 1, 'i'))), - 0xc: ('scratch_load_dword', (('VDST', 1, 'i'), ('ADDR', 1, 'i'), ('SADDR', 1, 'i'))), - 0xd: ('scratch_load_dwordx2', (('VDST', 2, 'i'), ('ADDR', 1, 'i'), ('SADDR', 1, 'i'))), - 0xe: ('scratch_load_dwordx4', (('VDST', 4, 'i'), ('ADDR', 1, 'i'), ('SADDR', 1, 'i'))), - 0xf: ('scratch_load_dwordx3', (('VDST', 3, 'i'), ('ADDR', 1, 'i'), ('SADDR', 1, 'i'))), - 0x18: ('scratch_store_byte', (('ADDR', 1, 'i'), ('DATA', 1, 'i'), ('SADDR', 1, 'i'))), - 0x19: ('scratch_store_byte_d16_hi', (('ADDR', 1, 'i'), ('DATA', 1, 'i'), ('SADDR', 1, 'i'))), - 0x1a: ('scratch_store_short', (('ADDR', 1, 'i'), ('DATA', 1, 'i'), ('SADDR', 1, 'i'))), - 0x1b: ('scratch_store_short_d16_hi', (('ADDR', 1, 'i'), ('DATA', 1, 'i'), ('SADDR', 1, 'i'))), - 0x1c: ('scratch_store_dword', (('ADDR', 1, 'i'), ('DATA', 1, 'i'), ('SADDR', 1, 'i'))), - 0x1d: ('scratch_store_dwordx2', (('ADDR', 1, 'i'), ('DATA', 2, 'i'), ('SADDR', 1, 'i'))), - 0x1e: ('scratch_store_dwordx4', (('ADDR', 1, 'i'), ('DATA', 4, 'i'), ('SADDR', 1, 'i'))), - 0x1f: ('scratch_store_dwordx3', (('ADDR', 1, 'i'), ('DATA', 3, 'i'), ('SADDR', 1, 'i'))), - 0x20: ('scratch_load_ubyte_d16', (('VDST', 1, 'i'), ('ADDR', 1, 'i'), ('SADDR', 1, 'i'))), - 0x21: ('scratch_load_ubyte_d16_hi', (('VDST', 1, 'i'), ('ADDR', 1, 'i'), ('SADDR', 1, 'i'))), - 0x22: ('scratch_load_sbyte_d16', (('VDST', 1, 'i'), ('ADDR', 1, 'i'), ('SADDR', 1, 'i'))), - 0x23: ('scratch_load_sbyte_d16_hi', (('VDST', 1, 'i'), ('ADDR', 1, 'i'), ('SADDR', 1, 'i'))), - 0x24: ('scratch_load_short_d16', (('VDST', 1, 'i'), ('ADDR', 1, 'i'), ('SADDR', 1, 'i'))), - 0x25: ('scratch_load_short_d16_hi', (('VDST', 1, 'i'), ('ADDR', 1, 'i'), ('SADDR', 1, 'i'))), -} - -SMEM = { - 0x0: ('s_load_dword', (('SDATA', 1, 'i'), ('SBASE', 2, 'i'), ('SOFFSET', 1, 'i'))), - 0x1: ('s_load_dwordx2', (('SDATA', 2, 'i'), ('SBASE', 2, 'i'), ('SOFFSET', 1, 'i'))), - 0x2: ('s_load_dwordx4', (('SDATA', 4, 'i'), ('SBASE', 2, 'i'), ('SOFFSET', 1, 'i'))), - 0x3: ('s_load_dwordx8', (('SDATA', 8, 'i'), ('SBASE', 2, 'i'), ('SOFFSET', 1, 'i'))), - 0x4: ('s_load_dwordx16', (('SDATA', 16, 'i'), ('SBASE', 2, 'i'), ('SOFFSET', 1, 'i'))), - 0x8: ('s_buffer_load_dword', (('SDATA', 1, 'i'), ('SBASE', 4, 'i'), ('SOFFSET', 1, 'i'))), - 0x9: ('s_buffer_load_dwordx2', (('SDATA', 2, 'i'), ('SBASE', 4, 'i'), ('SOFFSET', 1, 'i'))), - 0xa: ('s_buffer_load_dwordx4', (('SDATA', 4, 'i'), ('SBASE', 4, 'i'), ('SOFFSET', 1, 'i'))), - 0xb: ('s_buffer_load_dwordx8', (('SDATA', 8, 'i'), ('SBASE', 4, 'i'), ('SOFFSET', 1, 'i'))), - 0xc: ('s_buffer_load_dwordx16', (('SDATA', 16, 'i'), ('SBASE', 4, 'i'), ('SOFFSET', 1, 'i'))), - 0x1f: ('s_gl1_inv', ()), - 0x20: ('s_dcache_inv', ()), - 0x24: ('s_memtime', (('SDATA', 2, 'i'),)), - 0x25: ('s_memrealtime', (('SDATA', 2, 'i'),)), - 0x2a: ('s_get_waveid_in_workgroup', (('SDATA', 1, 'i'),)), -} - -SOP1 = { - 0x3: ('s_mov_b32', (('SDST', 1, 'i'), ('SSRC0', 1, 'i'))), - 0x4: ('s_mov_b64', (('SDST', 2, 'i'), ('SSRC0', 2, 'i'))), - 0x5: ('s_cmov_b32', (('SDST', 1, 'i'), ('SSRC0', 1, 'i'))), - 0x6: ('s_cmov_b64', (('SDST', 2, 'i'), ('SSRC0', 2, 'i'))), - 0x7: ('s_not_b32', (('SDST', 1, 'i'), ('SSRC0', 1, 'i'))), - 0x8: ('s_not_b64', (('SDST', 2, 'i'), ('SSRC0', 2, 'i'))), - 0x9: ('s_wqm_b32', (('SDST', 1, 'i'), ('SSRC0', 1, 'i'))), - 0xa: ('s_wqm_b64', (('SDST', 2, 'i'), ('SSRC0', 2, 'i'))), - 0xb: ('s_brev_b32', (('SDST', 1, 'i'), ('SSRC0', 1, 'i'))), - 0xc: ('s_brev_b64', (('SDST', 2, 'i'), ('SSRC0', 2, 'i'))), - 0xd: ('s_bcnt0_i32_b32', (('SDST', 1, 'i'), ('SSRC0', 1, 'i'))), - 0xe: ('s_bcnt0_i32_b64', (('SDST', 1, 'i'), ('SSRC0', 2, 'i'))), - 0xf: ('s_bcnt1_i32_b32', (('SDST', 1, 'i'), ('SSRC0', 1, 'i'))), - 0x10: ('s_bcnt1_i32_b64', (('SDST', 1, 'i'), ('SSRC0', 2, 'i'))), - 0x11: ('s_ff0_i32_b32', (('SDST', 1, 'i'), ('SSRC0', 1, 'i'))), - 0x12: ('s_ff0_i32_b64', (('SDST', 1, 'i'), ('SSRC0', 2, 'i'))), - 0x13: ('s_ff1_i32_b32', (('SDST', 1, 'i'), ('SSRC0', 1, 'i'))), - 0x14: ('s_ff1_i32_b64', (('SDST', 1, 'i'), ('SSRC0', 2, 'i'))), - 0x15: ('s_flbit_i32_b32', (('SDST', 1, 'i'), ('SSRC0', 1, 'i'))), - 0x16: ('s_flbit_i32_b64', (('SDST', 1, 'i'), ('SSRC0', 2, 'i'))), - 0x17: ('s_flbit_i32', (('SDST', 1, 'i'), ('SSRC0', 1, 'i'))), - 0x18: ('s_flbit_i32_i64', (('SDST', 1, 'i'), ('SSRC0', 2, 'i'))), - 0x19: ('s_sext_i32_i8', (('SDST', 1, 'i'), ('SSRC0', 1, 'i'))), - 0x1a: ('s_sext_i32_i16', (('SDST', 1, 'i'), ('SSRC0', 1, 'i'))), - 0x1b: ('s_bitset0_b32', (('SDST', 1, 'i'), ('SSRC0', 1, 'i'))), - 0x1c: ('s_bitset0_b64', (('SDST', 2, 'i'), ('SSRC0', 1, 'i'))), - 0x1d: ('s_bitset1_b32', (('SDST', 1, 'i'), ('SSRC0', 1, 'i'))), - 0x1e: ('s_bitset1_b64', (('SDST', 2, 'i'), ('SSRC0', 1, 'i'))), - 0x1f: ('s_getpc_b64', (('SDST', 2, 'i'),)), - 0x20: ('s_setpc_b64', (('SSRC0', 2, 'i'),)), - 0x21: ('s_swappc_b64', (('SDST', 2, 'i'), ('SSRC0', 2, 'i'))), - 0x22: ('s_rfe_b64', (('SSRC0', 2, 'i'),)), - 0x24: ('s_and_saveexec_b64', (('SDST', 2, 'i'), ('SSRC0', 2, 'i'))), - 0x25: ('s_or_saveexec_b64', (('SDST', 2, 'i'), ('SSRC0', 2, 'i'))), - 0x26: ('s_xor_saveexec_b64', (('SDST', 2, 'i'), ('SSRC0', 2, 'i'))), - 0x27: ('s_andn2_saveexec_b64', (('SDST', 2, 'i'), ('SSRC0', 2, 'i'))), - 0x28: ('s_orn2_saveexec_b64', (('SDST', 2, 'i'), ('SSRC0', 2, 'i'))), - 0x29: ('s_nand_saveexec_b64', (('SDST', 2, 'i'), ('SSRC0', 2, 'i'))), - 0x2a: ('s_nor_saveexec_b64', (('SDST', 2, 'i'), ('SSRC0', 2, 'i'))), - 0x2b: ('s_xnor_saveexec_b64', (('SDST', 2, 'i'), ('SSRC0', 2, 'i'))), - 0x2c: ('s_quadmask_b32', (('SDST', 1, 'i'), ('SSRC0', 1, 'i'))), - 0x2d: ('s_quadmask_b64', (('SDST', 2, 'i'), ('SSRC0', 2, 'i'))), - 0x2e: ('s_movrels_b32', (('SDST', 1, 'i'), ('SSRC0', 1, 'i'))), - 0x2f: ('s_movrels_b64', (('SDST', 2, 'i'), ('SSRC0', 2, 'i'))), - 0x30: ('s_movreld_b32', (('SDST', 1, 'i'), ('SSRC0', 1, 'i'))), - 0x31: ('s_movreld_b64', (('SDST', 2, 'i'), ('SSRC0', 2, 'i'))), - 0x34: ('s_abs_i32', (('SDST', 1, 'i'), ('SSRC0', 1, 'i'))), - 0x37: ('s_andn1_saveexec_b64', (('SDST', 2, 'i'), ('SSRC0', 2, 'i'))), - 0x38: ('s_orn1_saveexec_b64', (('SDST', 2, 'i'), ('SSRC0', 2, 'i'))), - 0x39: ('s_andn1_wrexec_b64', (('SDST', 2, 'i'), ('SSRC0', 2, 'i'))), - 0x3a: ('s_andn2_wrexec_b64', (('SDST', 2, 'i'), ('SSRC0', 2, 'i'))), - 0x3b: ('s_bitreplicate_b64_b32', (('SDST', 2, 'i'), ('SSRC0', 1, 'i'))), - 0x3c: ('s_and_saveexec_b32', (('SDST', 1, 'i'), ('SSRC0', 1, 'i'))), - 0x3d: ('s_or_saveexec_b32', (('SDST', 1, 'i'), ('SSRC0', 1, 'i'))), - 0x3e: ('s_xor_saveexec_b32', (('SDST', 1, 'i'), ('SSRC0', 1, 'i'))), - 0x3f: ('s_andn2_saveexec_b32', (('SDST', 1, 'i'), ('SSRC0', 1, 'i'))), - 0x40: ('s_orn2_saveexec_b32', (('SDST', 1, 'i'), ('SSRC0', 1, 'i'))), - 0x41: ('s_nand_saveexec_b32', (('SDST', 1, 'i'), ('SSRC0', 1, 'i'))), - 0x42: ('s_nor_saveexec_b32', (('SDST', 1, 'i'), ('SSRC0', 1, 'i'))), - 0x43: ('s_xnor_saveexec_b32', (('SDST', 1, 'i'), ('SSRC0', 1, 'i'))), - 0x44: ('s_andn1_saveexec_b32', (('SDST', 1, 'i'), ('SSRC0', 1, 'i'))), - 0x45: ('s_orn1_saveexec_b32', (('SDST', 1, 'i'), ('SSRC0', 1, 'i'))), - 0x46: ('s_andn1_wrexec_b32', (('SDST', 1, 'i'), ('SSRC0', 1, 'i'))), - 0x47: ('s_andn2_wrexec_b32', (('SDST', 1, 'i'), ('SSRC0', 1, 'i'))), - 0x49: ('s_movrelsd_2_b32', (('SDST', 1, 'i'), ('SSRC0', 1, 'i'))), -} - -SOP2 = { - 0x0: ('s_add_u32', (('SDST', 1, 'i'), ('SSRC0', 1, 'i'), ('SSRC1', 1, 'i'))), - 0x1: ('s_sub_u32', (('SDST', 1, 'i'), ('SSRC0', 1, 'i'), ('SSRC1', 1, 'i'))), - 0x2: ('s_add_i32', (('SDST', 1, 'i'), ('SSRC0', 1, 'i'), ('SSRC1', 1, 'i'))), - 0x3: ('s_sub_i32', (('SDST', 1, 'i'), ('SSRC0', 1, 'i'), ('SSRC1', 1, 'i'))), - 0x4: ('s_addc_u32', (('SDST', 1, 'i'), ('SSRC0', 1, 'i'), ('SSRC1', 1, 'i'))), - 0x5: ('s_subb_u32', (('SDST', 1, 'i'), ('SSRC0', 1, 'i'), ('SSRC1', 1, 'i'))), - 0x6: ('s_min_i32', (('SDST', 1, 'i'), ('SSRC0', 1, 'i'), ('SSRC1', 1, 'i'))), - 0x7: ('s_min_u32', (('SDST', 1, 'i'), ('SSRC0', 1, 'i'), ('SSRC1', 1, 'i'))), - 0x8: ('s_max_i32', (('SDST', 1, 'i'), ('SSRC0', 1, 'i'), ('SSRC1', 1, 'i'))), - 0x9: ('s_max_u32', (('SDST', 1, 'i'), ('SSRC0', 1, 'i'), ('SSRC1', 1, 'i'))), - 0xa: ('s_cselect_b32', (('SDST', 1, 'i'), ('SSRC0', 1, 'i'), ('SSRC1', 1, 'i'))), - 0xb: ('s_cselect_b64', (('SDST', 2, 'i'), ('SSRC0', 2, 'i'), ('SSRC1', 2, 'i'))), - 0xe: ('s_and_b32', (('SDST', 1, 'i'), ('SSRC0', 1, 'i'), ('SSRC1', 1, 'i'))), - 0xf: ('s_and_b64', (('SDST', 2, 'i'), ('SSRC0', 2, 'i'), ('SSRC1', 2, 'i'))), - 0x10: ('s_or_b32', (('SDST', 1, 'i'), ('SSRC0', 1, 'i'), ('SSRC1', 1, 'i'))), - 0x11: ('s_or_b64', (('SDST', 2, 'i'), ('SSRC0', 2, 'i'), ('SSRC1', 2, 'i'))), - 0x12: ('s_xor_b32', (('SDST', 1, 'i'), ('SSRC0', 1, 'i'), ('SSRC1', 1, 'i'))), - 0x13: ('s_xor_b64', (('SDST', 2, 'i'), ('SSRC0', 2, 'i'), ('SSRC1', 2, 'i'))), - 0x14: ('s_andn2_b32', (('SDST', 1, 'i'), ('SSRC0', 1, 'i'), ('SSRC1', 1, 'i'))), - 0x15: ('s_andn2_b64', (('SDST', 2, 'i'), ('SSRC0', 2, 'i'), ('SSRC1', 2, 'i'))), - 0x16: ('s_orn2_b32', (('SDST', 1, 'i'), ('SSRC0', 1, 'i'), ('SSRC1', 1, 'i'))), - 0x17: ('s_orn2_b64', (('SDST', 2, 'i'), ('SSRC0', 2, 'i'), ('SSRC1', 2, 'i'))), - 0x18: ('s_nand_b32', (('SDST', 1, 'i'), ('SSRC0', 1, 'i'), ('SSRC1', 1, 'i'))), - 0x19: ('s_nand_b64', (('SDST', 2, 'i'), ('SSRC0', 2, 'i'), ('SSRC1', 2, 'i'))), - 0x1a: ('s_nor_b32', (('SDST', 1, 'i'), ('SSRC0', 1, 'i'), ('SSRC1', 1, 'i'))), - 0x1b: ('s_nor_b64', (('SDST', 2, 'i'), ('SSRC0', 2, 'i'), ('SSRC1', 2, 'i'))), - 0x1c: ('s_xnor_b32', (('SDST', 1, 'i'), ('SSRC0', 1, 'i'), ('SSRC1', 1, 'i'))), - 0x1d: ('s_xnor_b64', (('SDST', 2, 'i'), ('SSRC0', 2, 'i'), ('SSRC1', 2, 'i'))), - 0x1e: ('s_lshl_b32', (('SDST', 1, 'i'), ('SSRC0', 1, 'i'), ('SSRC1', 1, 'i'))), - 0x1f: ('s_lshl_b64', (('SDST', 2, 'i'), ('SSRC0', 2, 'i'), ('SSRC1', 1, 'i'))), - 0x20: ('s_lshr_b32', (('SDST', 1, 'i'), ('SSRC0', 1, 'i'), ('SSRC1', 1, 'i'))), - 0x21: ('s_lshr_b64', (('SDST', 2, 'i'), ('SSRC0', 2, 'i'), ('SSRC1', 1, 'i'))), - 0x22: ('s_ashr_i32', (('SDST', 1, 'i'), ('SSRC0', 1, 'i'), ('SSRC1', 1, 'i'))), - 0x23: ('s_ashr_i64', (('SDST', 2, 'i'), ('SSRC0', 2, 'i'), ('SSRC1', 1, 'i'))), - 0x24: ('s_bfm_b32', (('SDST', 1, 'i'), ('SSRC0', 1, 'i'), ('SSRC1', 1, 'i'))), - 0x25: ('s_bfm_b64', (('SDST', 2, 'i'), ('SSRC0', 1, 'i'), ('SSRC1', 1, 'i'))), - 0x26: ('s_mul_i32', (('SDST', 1, 'i'), ('SSRC0', 1, 'i'), ('SSRC1', 1, 'i'))), - 0x27: ('s_bfe_u32', (('SDST', 1, 'i'), ('SSRC0', 1, 'i'), ('SSRC1', 1, 'i'))), - 0x28: ('s_bfe_i32', (('SDST', 1, 'i'), ('SSRC0', 1, 'i'), ('SSRC1', 1, 'i'))), - 0x29: ('s_bfe_u64', (('SDST', 2, 'i'), ('SSRC0', 2, 'i'), ('SSRC1', 1, 'i'))), - 0x2a: ('s_bfe_i64', (('SDST', 2, 'i'), ('SSRC0', 2, 'i'), ('SSRC1', 1, 'i'))), - 0x2c: ('s_absdiff_i32', (('SDST', 1, 'i'), ('SSRC0', 1, 'i'), ('SSRC1', 1, 'i'))), - 0x2e: ('s_lshl1_add_u32', (('SDST', 1, 'i'), ('SSRC0', 1, 'i'), ('SSRC1', 1, 'i'))), - 0x2f: ('s_lshl2_add_u32', (('SDST', 1, 'i'), ('SSRC0', 1, 'i'), ('SSRC1', 1, 'i'))), - 0x30: ('s_lshl3_add_u32', (('SDST', 1, 'i'), ('SSRC0', 1, 'i'), ('SSRC1', 1, 'i'))), - 0x31: ('s_lshl4_add_u32', (('SDST', 1, 'i'), ('SSRC0', 1, 'i'), ('SSRC1', 1, 'i'))), - 0x32: ('s_pack_ll_b32_b16', (('SDST', 1, 'i'), ('SSRC0', 1, 'i'), ('SSRC1', 1, 'i'))), - 0x33: ('s_pack_lh_b32_b16', (('SDST', 1, 'i'), ('SSRC0', 1, 'i'), ('SSRC1', 1, 'i'))), - 0x34: ('s_pack_hh_b32_b16', (('SDST', 1, 'i'), ('SSRC0', 1, 'i'), ('SSRC1', 1, 'i'))), - 0x35: ('s_mul_hi_u32', (('SDST', 1, 'i'), ('SSRC0', 1, 'i'), ('SSRC1', 1, 'i'))), - 0x36: ('s_mul_hi_i32', (('SDST', 1, 'i'), ('SSRC0', 1, 'i'), ('SSRC1', 1, 'i'))), -} - -SOPC = { - 0x0: ('s_cmp_eq_i32', (('SSRC0', 1, 'i'), ('SSRC1', 1, 'i'))), - 0x1: ('s_cmp_lg_i32', (('SSRC0', 1, 'i'), ('SSRC1', 1, 'i'))), - 0x2: ('s_cmp_gt_i32', (('SSRC0', 1, 'i'), ('SSRC1', 1, 'i'))), - 0x3: ('s_cmp_ge_i32', (('SSRC0', 1, 'i'), ('SSRC1', 1, 'i'))), - 0x4: ('s_cmp_lt_i32', (('SSRC0', 1, 'i'), ('SSRC1', 1, 'i'))), - 0x5: ('s_cmp_le_i32', (('SSRC0', 1, 'i'), ('SSRC1', 1, 'i'))), - 0x6: ('s_cmp_eq_u32', (('SSRC0', 1, 'i'), ('SSRC1', 1, 'i'))), - 0x7: ('s_cmp_lg_u32', (('SSRC0', 1, 'i'), ('SSRC1', 1, 'i'))), - 0x8: ('s_cmp_gt_u32', (('SSRC0', 1, 'i'), ('SSRC1', 1, 'i'))), - 0x9: ('s_cmp_ge_u32', (('SSRC0', 1, 'i'), ('SSRC1', 1, 'i'))), - 0xa: ('s_cmp_lt_u32', (('SSRC0', 1, 'i'), ('SSRC1', 1, 'i'))), - 0xb: ('s_cmp_le_u32', (('SSRC0', 1, 'i'), ('SSRC1', 1, 'i'))), - 0xc: ('s_bitcmp0_b32', (('SSRC0', 1, 'i'), ('SSRC1', 1, 'i'))), - 0xd: ('s_bitcmp1_b32', (('SSRC0', 1, 'i'), ('SSRC1', 1, 'i'))), - 0xe: ('s_bitcmp0_b64', (('SSRC0', 2, 'i'), ('SSRC1', 1, 'i'))), - 0xf: ('s_bitcmp1_b64', (('SSRC0', 2, 'i'), ('SSRC1', 1, 'i'))), - 0x12: ('s_cmp_eq_u64', (('SSRC0', 2, 'i'), ('SSRC1', 2, 'i'))), - 0x13: ('s_cmp_lg_u64', (('SSRC0', 2, 'i'), ('SSRC1', 2, 'i'))), -} - -SOPK = { - 0x0: ('s_movk_i32', (('SDST', 1, 'i'), ('SIMM16', 1, 'i'))), - 0x1: ('s_version', (('SIMM16', 1, 'i'),)), - 0x2: ('s_cmovk_i32', (('SDST', 1, 'i'), ('SIMM16', 1, 'i'))), - 0x3: ('s_cmpk_eq_i32', (('SDST', 1, 'i'), ('SIMM16', 1, 'i'))), - 0x4: ('s_cmpk_lg_i32', (('SDST', 1, 'i'), ('SIMM16', 1, 'i'))), - 0x5: ('s_cmpk_gt_i32', (('SDST', 1, 'i'), ('SIMM16', 1, 'i'))), - 0x6: ('s_cmpk_ge_i32', (('SDST', 1, 'i'), ('SIMM16', 1, 'i'))), - 0x7: ('s_cmpk_lt_i32', (('SDST', 1, 'i'), ('SIMM16', 1, 'i'))), - 0x8: ('s_cmpk_le_i32', (('SDST', 1, 'i'), ('SIMM16', 1, 'i'))), - 0x9: ('s_cmpk_eq_u32', (('SDST', 1, 'i'), ('SIMM16', 1, 'i'))), - 0xa: ('s_cmpk_lg_u32', (('SDST', 1, 'i'), ('SIMM16', 1, 'i'))), - 0xb: ('s_cmpk_gt_u32', (('SDST', 1, 'i'), ('SIMM16', 1, 'i'))), - 0xc: ('s_cmpk_ge_u32', (('SDST', 1, 'i'), ('SIMM16', 1, 'i'))), - 0xd: ('s_cmpk_lt_u32', (('SDST', 1, 'i'), ('SIMM16', 1, 'i'))), - 0xe: ('s_cmpk_le_u32', (('SDST', 1, 'i'), ('SIMM16', 1, 'i'))), - 0xf: ('s_addk_i32', (('SDST', 1, 'i'), ('SIMM16', 1, 'i'))), - 0x10: ('s_mulk_i32', (('SDST', 1, 'i'), ('SIMM16', 1, 'i'))), - 0x12: ('s_getreg_b32', (('SDST', 1, 'i'), ('SIMM16', 1, 'i'))), - 0x13: ('s_setreg_b32', (('SIMM16', 1, 'i'), ('SDST', 1, 'i'))), - 0x15: ('s_setreg_imm32_b32', (('SIMM16', 1, 'i'), ('LITERAL', 1, 'i'))), - 0x16: ('s_call_b64', (('SDST', 2, 'i'), ('SIMM16', 1, 'i'))), - 0x17: ('s_waitcnt_vscnt', (('SDST', 1, 'i'), ('SIMM16', 1, 'i'))), - 0x18: ('s_waitcnt_vmcnt', (('SDST', 1, 'i'), ('SIMM16', 1, 'i'))), - 0x19: ('s_waitcnt_expcnt', (('SDST', 1, 'i'), ('SIMM16', 1, 'i'))), - 0x1a: ('s_waitcnt_lgkmcnt', (('SDST', 1, 'i'), ('SIMM16', 1, 'i'))), - 0x1b: ('s_subvector_loop_begin', (('SDST', 1, 'i'), ('SIMM16', 1, 'i'))), - 0x1c: ('s_subvector_loop_end', (('SDST', 1, 'i'), ('SIMM16', 1, 'i'))), -} - -SOPP = { - 0x0: ('s_nop', (('SIMM16', 1, 'i'),)), - 0x1: ('s_endpgm', ()), - 0x2: ('s_branch', (('SIMM16', 1, 'i'),)), - 0x3: ('s_wakeup', ()), - 0x4: ('s_cbranch_scc0', (('SIMM16', 1, 'i'),)), - 0x5: ('s_cbranch_scc1', (('SIMM16', 1, 'i'),)), - 0x6: ('s_cbranch_vccz', (('SIMM16', 1, 'i'),)), - 0x7: ('s_cbranch_vccnz', (('SIMM16', 1, 'i'),)), - 0x8: ('s_cbranch_execz', (('SIMM16', 1, 'i'),)), - 0x9: ('s_cbranch_execnz', (('SIMM16', 1, 'i'),)), - 0xa: ('s_barrier', ()), - 0xb: ('s_setkill', (('SIMM16', 1, 'i'),)), - 0xc: ('s_waitcnt', (('SIMM16', 1, 'i'),)), - 0xd: ('s_sethalt', (('SIMM16', 1, 'i'),)), - 0xe: ('s_sleep', (('SIMM16', 1, 'i'),)), - 0xf: ('s_setprio', (('SIMM16', 1, 'i'),)), - 0x10: ('s_sendmsg', (('SIMM16', 1, 'i'),)), - 0x11: ('s_sendmsghalt', (('SIMM16', 1, 'i'),)), - 0x12: ('s_trap', (('SIMM16', 1, 'i'),)), - 0x13: ('s_icache_inv', ()), - 0x14: ('s_incperflevel', (('SIMM16', 1, 'i'),)), - 0x15: ('s_decperflevel', (('SIMM16', 1, 'i'),)), - 0x16: ('s_ttracedata', ()), - 0x17: ('s_cbranch_cdbgsys', (('SIMM16', 1, 'i'),)), - 0x18: ('s_cbranch_cdbguser', (('SIMM16', 1, 'i'),)), - 0x19: ('s_cbranch_cdbgsys_or_user', (('SIMM16', 1, 'i'),)), - 0x1a: ('s_cbranch_cdbgsys_and_user', (('SIMM16', 1, 'i'),)), - 0x1b: ('s_endpgm_saved', ()), - 0x1e: ('s_endpgm_ordered_ps_done', ()), - 0x1f: ('s_code_end', ()), - 0x20: ('s_inst_prefetch', (('SIMM16', 1, 'i'),)), - 0x21: ('s_clause', (('SIMM16', 1, 'i'),)), - 0x23: ('s_waitcnt_depctr', (('SIMM16', 1, 'i'),)), - 0x24: ('s_round_mode', (('SIMM16', 1, 'i'),)), - 0x25: ('s_denorm_mode', (('SIMM16', 1, 'i'),)), - 0x28: ('s_ttracedata_imm', (('SIMM16', 1, 'i'),)), -} - -VINTRP = { - 0x0: ('v_interp_p1_f32', (('VDST', 1, 'f32'), ('VSRC', 1, 'f32'), ('ATTR', 1, 'i'))), - 0x1: ('v_interp_p2_f32', (('VDST', 1, 'f32'), ('VSRC', 1, 'f32'), ('ATTR', 1, 'i'))), - 0x2: ('v_interp_mov_f32', (('VDST', 1, 'f32'), ('VSRC', 1, 'i'), ('ATTR', 1, 'i'))), -} - -VOP1 = { - 0x0: ('v_nop', ()), - 0x1: ('v_mov_b32', (('VDST', 1, 'i'), ('SRC0', 1, 'i'))), - 0x2: ('v_readfirstlane_b32', (('VDST', 1, 'i'), ('SRC0', 1, 'i'))), - 0x3: ('v_cvt_i32_f64', (('VDST', 1, 'i'), ('SRC0', 2, 'f64'))), - 0x4: ('v_cvt_f64_i32', (('VDST', 2, 'f64'), ('SRC0', 1, 'i'))), - 0x5: ('v_cvt_f32_i32', (('VDST', 1, 'f32'), ('SRC0', 1, 'i'))), - 0x6: ('v_cvt_f32_u32', (('VDST', 1, 'f32'), ('SRC0', 1, 'i'))), - 0x7: ('v_cvt_u32_f32', (('VDST', 1, 'i'), ('SRC0', 1, 'f32'))), - 0x8: ('v_cvt_i32_f32', (('VDST', 1, 'i'), ('SRC0', 1, 'f32'))), - 0xa: ('v_cvt_f16_f32', (('VDST', 1, 'f16'), ('SRC0', 1, 'f32'))), - 0xb: ('v_cvt_f32_f16', (('VDST', 1, 'f32'), ('SRC0', 1, 'f16'))), - 0xc: ('v_cvt_rpi_i32_f32', (('VDST', 1, 'i'), ('SRC0', 1, 'f32'))), - 0xd: ('v_cvt_flr_i32_f32', (('VDST', 1, 'i'), ('SRC0', 1, 'f32'))), - 0xe: ('v_cvt_off_f32_i4', (('VDST', 1, 'f32'), ('SRC0', 1, 'i'))), - 0xf: ('v_cvt_f32_f64', (('VDST', 1, 'f32'), ('SRC0', 2, 'f64'))), - 0x10: ('v_cvt_f64_f32', (('VDST', 2, 'f64'), ('SRC0', 1, 'f32'))), - 0x11: ('v_cvt_f32_ubyte0', (('VDST', 1, 'f32'), ('SRC0', 1, 'i'))), - 0x12: ('v_cvt_f32_ubyte1', (('VDST', 1, 'f32'), ('SRC0', 1, 'i'))), - 0x13: ('v_cvt_f32_ubyte2', (('VDST', 1, 'f32'), ('SRC0', 1, 'i'))), - 0x14: ('v_cvt_f32_ubyte3', (('VDST', 1, 'f32'), ('SRC0', 1, 'i'))), - 0x15: ('v_cvt_u32_f64', (('VDST', 1, 'i'), ('SRC0', 2, 'f64'))), - 0x16: ('v_cvt_f64_u32', (('VDST', 2, 'f64'), ('SRC0', 1, 'i'))), - 0x17: ('v_trunc_f64', (('VDST', 2, 'f64'), ('SRC0', 2, 'f64'))), - 0x18: ('v_ceil_f64', (('VDST', 2, 'f64'), ('SRC0', 2, 'f64'))), - 0x19: ('v_rndne_f64', (('VDST', 2, 'f64'), ('SRC0', 2, 'f64'))), - 0x1a: ('v_floor_f64', (('VDST', 2, 'f64'), ('SRC0', 2, 'f64'))), - 0x1b: ('v_pipeflush', ()), - 0x20: ('v_fract_f32', (('VDST', 1, 'f32'), ('SRC0', 1, 'f32'))), - 0x21: ('v_trunc_f32', (('VDST', 1, 'f32'), ('SRC0', 1, 'f32'))), - 0x22: ('v_ceil_f32', (('VDST', 1, 'f32'), ('SRC0', 1, 'f32'))), - 0x23: ('v_rndne_f32', (('VDST', 1, 'f32'), ('SRC0', 1, 'f32'))), - 0x24: ('v_floor_f32', (('VDST', 1, 'f32'), ('SRC0', 1, 'f32'))), - 0x25: ('v_exp_f32', (('VDST', 1, 'f32'), ('SRC0', 1, 'f32'))), - 0x27: ('v_log_f32', (('VDST', 1, 'f32'), ('SRC0', 1, 'f32'))), - 0x2a: ('v_rcp_f32', (('VDST', 1, 'f32'), ('SRC0', 1, 'f32'))), - 0x2b: ('v_rcp_iflag_f32', (('VDST', 1, 'f32'), ('SRC0', 1, 'f32'))), - 0x2e: ('v_rsq_f32', (('VDST', 1, 'f32'), ('SRC0', 1, 'f32'))), - 0x2f: ('v_rcp_f64', (('VDST', 2, 'f64'), ('SRC0', 2, 'f64'))), - 0x31: ('v_rsq_f64', (('VDST', 2, 'f64'), ('SRC0', 2, 'f64'))), - 0x33: ('v_sqrt_f32', (('VDST', 1, 'f32'), ('SRC0', 1, 'f32'))), - 0x34: ('v_sqrt_f64', (('VDST', 2, 'f64'), ('SRC0', 2, 'f64'))), - 0x35: ('v_sin_f32', (('VDST', 1, 'f32'), ('SRC0', 1, 'f32'))), - 0x36: ('v_cos_f32', (('VDST', 1, 'f32'), ('SRC0', 1, 'f32'))), - 0x37: ('v_not_b32', (('VDST', 1, 'i'), ('SRC0', 1, 'i'))), - 0x38: ('v_bfrev_b32', (('VDST', 1, 'i'), ('SRC0', 1, 'i'))), - 0x39: ('v_ffbh_u32', (('VDST', 1, 'i'), ('SRC0', 1, 'i'))), - 0x3a: ('v_ffbl_b32', (('VDST', 1, 'i'), ('SRC0', 1, 'i'))), - 0x3b: ('v_ffbh_i32', (('VDST', 1, 'i'), ('SRC0', 1, 'i'))), - 0x3c: ('v_frexp_exp_i32_f64', (('VDST', 1, 'i'), ('SRC0', 2, 'f64'))), - 0x3d: ('v_frexp_mant_f64', (('VDST', 2, 'f64'), ('SRC0', 2, 'f64'))), - 0x3e: ('v_fract_f64', (('VDST', 2, 'f64'), ('SRC0', 2, 'f64'))), - 0x3f: ('v_frexp_exp_i32_f32', (('VDST', 1, 'i'), ('SRC0', 1, 'f32'))), - 0x40: ('v_frexp_mant_f32', (('VDST', 1, 'f32'), ('SRC0', 1, 'f32'))), - 0x41: ('v_clrexcp', ()), - 0x42: ('v_movreld_b32', (('VDST', 1, 'i'), ('SRC0', 1, 'i'))), - 0x43: ('v_movrels_b32', (('VDST', 1, 'i'), ('SRC0', 1, 'i'))), - 0x44: ('v_movrelsd_b32', (('VDST', 1, 'i'), ('SRC0', 1, 'i'))), - 0x48: ('v_movrelsd_2_b32', (('VDST', 1, 'i'), ('SRC0', 1, 'i'))), - 0x50: ('v_cvt_f16_u16', (('VDST', 1, 'f16'), ('SRC0', 1, 'i'))), - 0x51: ('v_cvt_f16_i16', (('VDST', 1, 'f16'), ('SRC0', 1, 'i'))), - 0x52: ('v_cvt_u16_f16', (('VDST', 1, 'i'), ('SRC0', 1, 'f16'))), - 0x53: ('v_cvt_i16_f16', (('VDST', 1, 'i'), ('SRC0', 1, 'f16'))), - 0x54: ('v_rcp_f16', (('VDST', 1, 'f16'), ('SRC0', 1, 'f16'))), - 0x55: ('v_sqrt_f16', (('VDST', 1, 'f16'), ('SRC0', 1, 'f16'))), - 0x56: ('v_rsq_f16', (('VDST', 1, 'f16'), ('SRC0', 1, 'f16'))), - 0x57: ('v_log_f16', (('VDST', 1, 'f16'), ('SRC0', 1, 'f16'))), - 0x58: ('v_exp_f16', (('VDST', 1, 'f16'), ('SRC0', 1, 'f16'))), - 0x59: ('v_frexp_mant_f16', (('VDST', 1, 'f16'), ('SRC0', 1, 'f16'))), - 0x5a: ('v_frexp_exp_i16_f16', (('VDST', 1, 'i'), ('SRC0', 1, 'f16'))), - 0x5b: ('v_floor_f16', (('VDST', 1, 'f16'), ('SRC0', 1, 'f16'))), - 0x5c: ('v_ceil_f16', (('VDST', 1, 'f16'), ('SRC0', 1, 'f16'))), - 0x5d: ('v_trunc_f16', (('VDST', 1, 'f16'), ('SRC0', 1, 'f16'))), - 0x5e: ('v_rndne_f16', (('VDST', 1, 'f16'), ('SRC0', 1, 'f16'))), - 0x5f: ('v_fract_f16', (('VDST', 1, 'f16'), ('SRC0', 1, 'f16'))), - 0x60: ('v_sin_f16', (('VDST', 1, 'f16'), ('SRC0', 1, 'f16'))), - 0x61: ('v_cos_f16', (('VDST', 1, 'f16'), ('SRC0', 1, 'f16'))), - 0x62: ('v_sat_pk_u8_i16', (('VDST', 1, 'i'), ('SRC0', 1, 'i'))), - 0x63: ('v_cvt_norm_i16_f16', (('VDST', 1, 'i'), ('SRC0', 1, 'f16'))), - 0x64: ('v_cvt_norm_u16_f16', (('VDST', 1, 'i'), ('SRC0', 1, 'f16'))), - 0x65: ('v_swap_b32', (('VDST', 1, 'i'), ('SRC0', 1, 'i'))), - 0x68: ('v_swaprel_b32', (('VDST', 1, 'i'), ('SRC0', 1, 'i'))), -} - -VOP2 = { - 0x1: ('v_cndmask_b32', (('VDST', 1, 'i'), ('SRC0', 1, 'i'), ('VSRC1', 1, 'i'), ('VCC', -1, 'i'))), - 0x2: ('v_dot2c_f32_f16', (('VDST', 1, 'f32'), ('SRC0', 1, 'f16'), ('VSRC1', 1, 'f16'))), - 0x3: ('v_add_f32', (('VDST', 1, 'f32'), ('SRC0', 1, 'f32'), ('VSRC1', 1, 'f32'))), - 0x4: ('v_sub_f32', (('VDST', 1, 'f32'), ('SRC0', 1, 'f32'), ('VSRC1', 1, 'f32'))), - 0x5: ('v_subrev_f32', (('VDST', 1, 'f32'), ('SRC0', 1, 'f32'), ('VSRC1', 1, 'f32'))), - 0x6: ('v_fmac_legacy_f32', (('VDST', 1, 'f32'), ('SRC0', 1, 'f32'), ('VSRC1', 1, 'f32'))), - 0x7: ('v_mul_legacy_f32', (('VDST', 1, 'f32'), ('SRC0', 1, 'f32'), ('VSRC1', 1, 'f32'))), - 0x8: ('v_mul_f32', (('VDST', 1, 'f32'), ('SRC0', 1, 'f32'), ('VSRC1', 1, 'f32'))), - 0x9: ('v_mul_i32_i24', (('VDST', 1, 'i'), ('SRC0', 1, 'i'), ('VSRC1', 1, 'i'))), - 0xa: ('v_mul_hi_i32_i24', (('VDST', 1, 'i'), ('SRC0', 1, 'i'), ('VSRC1', 1, 'i'))), - 0xb: ('v_mul_u32_u24', (('VDST', 1, 'i'), ('SRC0', 1, 'i'), ('VSRC1', 1, 'i'))), - 0xc: ('v_mul_hi_u32_u24', (('VDST', 1, 'i'), ('SRC0', 1, 'i'), ('VSRC1', 1, 'i'))), - 0xd: ('v_dot4c_i32_i8', (('VDST', 1, 'i'), ('SRC0', 1, 'i'), ('VSRC1', 1, 'i'))), - 0xf: ('v_min_f32', (('VDST', 1, 'f32'), ('SRC0', 1, 'f32'), ('VSRC1', 1, 'f32'))), - 0x10: ('v_max_f32', (('VDST', 1, 'f32'), ('SRC0', 1, 'f32'), ('VSRC1', 1, 'f32'))), - 0x11: ('v_min_i32', (('VDST', 1, 'i'), ('SRC0', 1, 'i'), ('VSRC1', 1, 'i'))), - 0x12: ('v_max_i32', (('VDST', 1, 'i'), ('SRC0', 1, 'i'), ('VSRC1', 1, 'i'))), - 0x13: ('v_min_u32', (('VDST', 1, 'i'), ('SRC0', 1, 'i'), ('VSRC1', 1, 'i'))), - 0x14: ('v_max_u32', (('VDST', 1, 'i'), ('SRC0', 1, 'i'), ('VSRC1', 1, 'i'))), - 0x16: ('v_lshrrev_b32', (('VDST', 1, 'i'), ('SRC0', 1, 'i'), ('VSRC1', 1, 'i'))), - 0x18: ('v_ashrrev_i32', (('VDST', 1, 'i'), ('SRC0', 1, 'i'), ('VSRC1', 1, 'i'))), - 0x1a: ('v_lshlrev_b32', (('VDST', 1, 'i'), ('SRC0', 1, 'i'), ('VSRC1', 1, 'i'))), - 0x1b: ('v_and_b32', (('VDST', 1, 'i'), ('SRC0', 1, 'i'), ('VSRC1', 1, 'i'))), - 0x1c: ('v_or_b32', (('VDST', 1, 'i'), ('SRC0', 1, 'i'), ('VSRC1', 1, 'i'))), - 0x1d: ('v_xor_b32', (('VDST', 1, 'i'), ('SRC0', 1, 'i'), ('VSRC1', 1, 'i'))), - 0x1e: ('v_xnor_b32', (('VDST', 1, 'i'), ('SRC0', 1, 'i'), ('VSRC1', 1, 'i'))), - 0x1f: ('v_mac_f32', (('VDST', 1, 'f32'), ('SRC0', 1, 'f32'), ('VSRC1', 1, 'f32'))), - 0x20: ('v_madmk_f32', (('VDST', 1, 'f32'), ('SRC0', 1, 'f32'), ('SIMM32', 0, 'f32'), ('VSRC1', 1, 'f32'))), - 0x21: ('v_madak_f32', (('VDST', 1, 'f32'), ('SRC0', 1, 'f32'), ('VSRC1', 1, 'f32'), ('SIMM32', 0, 'f32'))), - 0x25: ('v_add_nc_u32', (('VDST', 1, 'i'), ('SRC0', 1, 'i'), ('VSRC1', 1, 'i'))), - 0x26: ('v_sub_nc_u32', (('VDST', 1, 'i'), ('SRC0', 1, 'i'), ('VSRC1', 1, 'i'))), - 0x27: ('v_subrev_nc_u32', (('VDST', 1, 'i'), ('SRC0', 1, 'i'), ('VSRC1', 1, 'i'))), - 0x28: ('v_add_co_ci_u32', (('VDST', 1, 'i'), ('VCC', -1, 'i'), ('SRC0', 1, 'i'), ('VSRC1', 1, 'i'), ('VCC', -1, 'i'))), - 0x29: ('v_sub_co_ci_u32', (('VDST', 1, 'i'), ('VCC', -1, 'i'), ('SRC0', 1, 'i'), ('VSRC1', 1, 'i'), ('VCC', -1, 'i'))), - 0x2a: ('v_subrev_co_ci_u32', (('VDST', 1, 'i'), ('VCC', -1, 'i'), ('SRC0', 1, 'i'), ('VSRC1', 1, 'i'), ('VCC', -1, 'i'))), - 0x2b: ('v_fmac_f32', (('VDST', 1, 'f32'), ('SRC0', 1, 'f32'), ('VSRC1', 1, 'f32'))), - 0x2c: ('v_fmamk_f32', (('VDST', 1, 'f32'), ('SRC0', 1, 'f32'), ('LITERAL', 1, 'f32'), ('VSRC1', 1, 'f32'))), - 0x2d: ('v_fmaak_f32', (('VDST', 1, 'f32'), ('SRC0', 1, 'f32'), ('VSRC1', 1, 'f32'), ('LITERAL', 1, 'f32'))), - 0x2f: ('v_cvt_pkrtz_f16_f32', (('VDST', 1, 'f16'), ('SRC0', 1, 'f32'), ('VSRC1', 1, 'f32'))), - 0x32: ('v_add_f16', (('VDST', 1, 'f16'), ('SRC0', 1, 'f16'), ('VSRC1', 1, 'f16'))), - 0x33: ('v_sub_f16', (('VDST', 1, 'f16'), ('SRC0', 1, 'f16'), ('VSRC1', 1, 'f16'))), - 0x34: ('v_subrev_f16', (('VDST', 1, 'f16'), ('SRC0', 1, 'f16'), ('VSRC1', 1, 'f16'))), - 0x35: ('v_mul_f16', (('VDST', 1, 'f16'), ('SRC0', 1, 'f16'), ('VSRC1', 1, 'f16'))), - 0x36: ('v_fmac_f16', (('VDST', 1, 'f16'), ('SRC0', 1, 'f16'), ('VSRC1', 1, 'f16'))), - 0x37: ('v_fmamk_f16', (('VDST', 1, 'f16'), ('SRC0', 1, 'f16'), ('LITERAL', 1, 'f16'), ('VSRC1', 1, 'f16'))), - 0x38: ('v_fmaak_f16', (('VDST', 1, 'f16'), ('SRC0', 1, 'f16'), ('VSRC1', 1, 'f16'), ('LITERAL', 1, 'f16'))), - 0x39: ('v_max_f16', (('VDST', 1, 'f16'), ('SRC0', 1, 'f16'), ('VSRC1', 1, 'f16'))), - 0x3a: ('v_min_f16', (('VDST', 1, 'f16'), ('SRC0', 1, 'f16'), ('VSRC1', 1, 'f16'))), - 0x3b: ('v_ldexp_f16', (('VDST', 1, 'f16'), ('SRC0', 1, 'f16'), ('VSRC1', 1, 'f16'))), - 0x3c: ('v_pk_fmac_f16', (('VDST', 1, 'f16'), ('SRC0', 1, 'f16'), ('VSRC1', 1, 'f16'))), -} - -VOP3 = { - 0x0: ('v_cmp_f_f32', (('VDST', -1, 'i'), ('SRC0', 1, 'f32'), ('SRC1', 1, 'f32'))), - 0x1: ('v_cmp_lt_f32', (('VDST', -1, 'i'), ('SRC0', 1, 'f32'), ('SRC1', 1, 'f32'))), - 0x2: ('v_cmp_eq_f32', (('VDST', -1, 'i'), ('SRC0', 1, 'f32'), ('SRC1', 1, 'f32'))), - 0x3: ('v_cmp_le_f32', (('VDST', -1, 'i'), ('SRC0', 1, 'f32'), ('SRC1', 1, 'f32'))), - 0x4: ('v_cmp_gt_f32', (('VDST', -1, 'i'), ('SRC0', 1, 'f32'), ('SRC1', 1, 'f32'))), - 0x5: ('v_cmp_lg_f32', (('VDST', -1, 'i'), ('SRC0', 1, 'f32'), ('SRC1', 1, 'f32'))), - 0x6: ('v_cmp_ge_f32', (('VDST', -1, 'i'), ('SRC0', 1, 'f32'), ('SRC1', 1, 'f32'))), - 0x7: ('v_cmp_o_f32', (('VDST', -1, 'i'), ('SRC0', 1, 'f32'), ('SRC1', 1, 'f32'))), - 0x8: ('v_cmp_u_f32', (('VDST', -1, 'i'), ('SRC0', 1, 'f32'), ('SRC1', 1, 'f32'))), - 0x9: ('v_cmp_nge_f32', (('VDST', -1, 'i'), ('SRC0', 1, 'f32'), ('SRC1', 1, 'f32'))), - 0xa: ('v_cmp_nlg_f32', (('VDST', -1, 'i'), ('SRC0', 1, 'f32'), ('SRC1', 1, 'f32'))), - 0xb: ('v_cmp_ngt_f32', (('VDST', -1, 'i'), ('SRC0', 1, 'f32'), ('SRC1', 1, 'f32'))), - 0xc: ('v_cmp_nle_f32', (('VDST', -1, 'i'), ('SRC0', 1, 'f32'), ('SRC1', 1, 'f32'))), - 0xd: ('v_cmp_neq_f32', (('VDST', -1, 'i'), ('SRC0', 1, 'f32'), ('SRC1', 1, 'f32'))), - 0xe: ('v_cmp_nlt_f32', (('VDST', -1, 'i'), ('SRC0', 1, 'f32'), ('SRC1', 1, 'f32'))), - 0xf: ('v_cmp_tru_f32', (('VDST', -1, 'i'), ('SRC0', 1, 'f32'), ('SRC1', 1, 'f32'))), - 0x10: ('v_cmpx_f_f32', (('VDST', -1, 'i'), ('SRC0', 1, 'f32'), ('SRC1', 1, 'f32'))), - 0x11: ('v_cmpx_lt_f32', (('VDST', -1, 'i'), ('SRC0', 1, 'f32'), ('SRC1', 1, 'f32'))), - 0x12: ('v_cmpx_eq_f32', (('VDST', -1, 'i'), ('SRC0', 1, 'f32'), ('SRC1', 1, 'f32'))), - 0x13: ('v_cmpx_le_f32', (('VDST', -1, 'i'), ('SRC0', 1, 'f32'), ('SRC1', 1, 'f32'))), - 0x14: ('v_cmpx_gt_f32', (('VDST', -1, 'i'), ('SRC0', 1, 'f32'), ('SRC1', 1, 'f32'))), - 0x15: ('v_cmpx_lg_f32', (('VDST', -1, 'i'), ('SRC0', 1, 'f32'), ('SRC1', 1, 'f32'))), - 0x16: ('v_cmpx_ge_f32', (('VDST', -1, 'i'), ('SRC0', 1, 'f32'), ('SRC1', 1, 'f32'))), - 0x17: ('v_cmpx_o_f32', (('VDST', -1, 'i'), ('SRC0', 1, 'f32'), ('SRC1', 1, 'f32'))), - 0x18: ('v_cmpx_u_f32', (('VDST', -1, 'i'), ('SRC0', 1, 'f32'), ('SRC1', 1, 'f32'))), - 0x19: ('v_cmpx_nge_f32', (('VDST', -1, 'i'), ('SRC0', 1, 'f32'), ('SRC1', 1, 'f32'))), - 0x1a: ('v_cmpx_nlg_f32', (('VDST', -1, 'i'), ('SRC0', 1, 'f32'), ('SRC1', 1, 'f32'))), - 0x1b: ('v_cmpx_ngt_f32', (('VDST', -1, 'i'), ('SRC0', 1, 'f32'), ('SRC1', 1, 'f32'))), - 0x1c: ('v_cmpx_nle_f32', (('VDST', -1, 'i'), ('SRC0', 1, 'f32'), ('SRC1', 1, 'f32'))), - 0x1d: ('v_cmpx_neq_f32', (('VDST', -1, 'i'), ('SRC0', 1, 'f32'), ('SRC1', 1, 'f32'))), - 0x1e: ('v_cmpx_nlt_f32', (('VDST', -1, 'i'), ('SRC0', 1, 'f32'), ('SRC1', 1, 'f32'))), - 0x1f: ('v_cmpx_tru_f32', (('VDST', -1, 'i'), ('SRC0', 1, 'f32'), ('SRC1', 1, 'f32'))), - 0x20: ('v_cmp_f_f64', (('VDST', -1, 'i'), ('SRC0', 2, 'f64'), ('SRC1', 2, 'f64'))), - 0x21: ('v_cmp_lt_f64', (('VDST', -1, 'i'), ('SRC0', 2, 'f64'), ('SRC1', 2, 'f64'))), - 0x22: ('v_cmp_eq_f64', (('VDST', -1, 'i'), ('SRC0', 2, 'f64'), ('SRC1', 2, 'f64'))), - 0x23: ('v_cmp_le_f64', (('VDST', -1, 'i'), ('SRC0', 2, 'f64'), ('SRC1', 2, 'f64'))), - 0x24: ('v_cmp_gt_f64', (('VDST', -1, 'i'), ('SRC0', 2, 'f64'), ('SRC1', 2, 'f64'))), - 0x25: ('v_cmp_lg_f64', (('VDST', -1, 'i'), ('SRC0', 2, 'f64'), ('SRC1', 2, 'f64'))), - 0x26: ('v_cmp_ge_f64', (('VDST', -1, 'i'), ('SRC0', 2, 'f64'), ('SRC1', 2, 'f64'))), - 0x27: ('v_cmp_o_f64', (('VDST', -1, 'i'), ('SRC0', 2, 'f64'), ('SRC1', 2, 'f64'))), - 0x28: ('v_cmp_u_f64', (('VDST', -1, 'i'), ('SRC0', 2, 'f64'), ('SRC1', 2, 'f64'))), - 0x29: ('v_cmp_nge_f64', (('VDST', -1, 'i'), ('SRC0', 2, 'f64'), ('SRC1', 2, 'f64'))), - 0x2a: ('v_cmp_nlg_f64', (('VDST', -1, 'i'), ('SRC0', 2, 'f64'), ('SRC1', 2, 'f64'))), - 0x2b: ('v_cmp_ngt_f64', (('VDST', -1, 'i'), ('SRC0', 2, 'f64'), ('SRC1', 2, 'f64'))), - 0x2c: ('v_cmp_nle_f64', (('VDST', -1, 'i'), ('SRC0', 2, 'f64'), ('SRC1', 2, 'f64'))), - 0x2d: ('v_cmp_neq_f64', (('VDST', -1, 'i'), ('SRC0', 2, 'f64'), ('SRC1', 2, 'f64'))), - 0x2e: ('v_cmp_nlt_f64', (('VDST', -1, 'i'), ('SRC0', 2, 'f64'), ('SRC1', 2, 'f64'))), - 0x2f: ('v_cmp_tru_f64', (('VDST', -1, 'i'), ('SRC0', 2, 'f64'), ('SRC1', 2, 'f64'))), - 0x30: ('v_cmpx_f_f64', (('VDST', -1, 'i'), ('SRC0', 2, 'f64'), ('SRC1', 2, 'f64'))), - 0x31: ('v_cmpx_lt_f64', (('VDST', -1, 'i'), ('SRC0', 2, 'f64'), ('SRC1', 2, 'f64'))), - 0x32: ('v_cmpx_eq_f64', (('VDST', -1, 'i'), ('SRC0', 2, 'f64'), ('SRC1', 2, 'f64'))), - 0x33: ('v_cmpx_le_f64', (('VDST', -1, 'i'), ('SRC0', 2, 'f64'), ('SRC1', 2, 'f64'))), - 0x34: ('v_cmpx_gt_f64', (('VDST', -1, 'i'), ('SRC0', 2, 'f64'), ('SRC1', 2, 'f64'))), - 0x35: ('v_cmpx_lg_f64', (('VDST', -1, 'i'), ('SRC0', 2, 'f64'), ('SRC1', 2, 'f64'))), - 0x36: ('v_cmpx_ge_f64', (('VDST', -1, 'i'), ('SRC0', 2, 'f64'), ('SRC1', 2, 'f64'))), - 0x37: ('v_cmpx_o_f64', (('VDST', -1, 'i'), ('SRC0', 2, 'f64'), ('SRC1', 2, 'f64'))), - 0x38: ('v_cmpx_u_f64', (('VDST', -1, 'i'), ('SRC0', 2, 'f64'), ('SRC1', 2, 'f64'))), - 0x39: ('v_cmpx_nge_f64', (('VDST', -1, 'i'), ('SRC0', 2, 'f64'), ('SRC1', 2, 'f64'))), - 0x3a: ('v_cmpx_nlg_f64', (('VDST', -1, 'i'), ('SRC0', 2, 'f64'), ('SRC1', 2, 'f64'))), - 0x3b: ('v_cmpx_ngt_f64', (('VDST', -1, 'i'), ('SRC0', 2, 'f64'), ('SRC1', 2, 'f64'))), - 0x3c: ('v_cmpx_nle_f64', (('VDST', -1, 'i'), ('SRC0', 2, 'f64'), ('SRC1', 2, 'f64'))), - 0x3d: ('v_cmpx_neq_f64', (('VDST', -1, 'i'), ('SRC0', 2, 'f64'), ('SRC1', 2, 'f64'))), - 0x3e: ('v_cmpx_nlt_f64', (('VDST', -1, 'i'), ('SRC0', 2, 'f64'), ('SRC1', 2, 'f64'))), - 0x3f: ('v_cmpx_tru_f64', (('VDST', -1, 'i'), ('SRC0', 2, 'f64'), ('SRC1', 2, 'f64'))), - 0x80: ('v_cmp_f_i32', (('VDST', -1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'))), - 0x81: ('v_cmp_lt_i32', (('VDST', -1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'))), - 0x82: ('v_cmp_eq_i32', (('VDST', -1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'))), - 0x83: ('v_cmp_le_i32', (('VDST', -1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'))), - 0x84: ('v_cmp_gt_i32', (('VDST', -1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'))), - 0x85: ('v_cmp_ne_i32', (('VDST', -1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'))), - 0x86: ('v_cmp_ge_i32', (('VDST', -1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'))), - 0x87: ('v_cmp_t_i32', (('VDST', -1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'))), - 0x88: ('v_cmp_class_f32', (('VDST', -1, 'i'), ('SRC0', 1, 'f32'), ('SRC1', 1, 'i'))), - 0x89: ('v_cmp_lt_i16', (('VDST', -1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'))), - 0x8a: ('v_cmp_eq_i16', (('VDST', -1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'))), - 0x8b: ('v_cmp_le_i16', (('VDST', -1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'))), - 0x8c: ('v_cmp_gt_i16', (('VDST', -1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'))), - 0x8d: ('v_cmp_ne_i16', (('VDST', -1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'))), - 0x8e: ('v_cmp_ge_i16', (('VDST', -1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'))), - 0x8f: ('v_cmp_class_f16', (('VDST', -1, 'i'), ('SRC0', 1, 'f16'), ('SRC1', 1, 'f16'))), - 0x90: ('v_cmpx_f_i32', (('VDST', -1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'))), - 0x91: ('v_cmpx_lt_i32', (('VDST', -1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'))), - 0x92: ('v_cmpx_eq_i32', (('VDST', -1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'))), - 0x93: ('v_cmpx_le_i32', (('VDST', -1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'))), - 0x94: ('v_cmpx_gt_i32', (('VDST', -1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'))), - 0x95: ('v_cmpx_ne_i32', (('VDST', -1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'))), - 0x96: ('v_cmpx_ge_i32', (('VDST', -1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'))), - 0x97: ('v_cmpx_t_i32', (('VDST', -1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'))), - 0x98: ('v_cmpx_class_f32', (('VDST', -1, 'i'), ('SRC0', 1, 'f32'), ('SRC1', 1, 'i'))), - 0x99: ('v_cmpx_lt_i16', (('VDST', -1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'))), - 0x9a: ('v_cmpx_eq_i16', (('VDST', -1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'))), - 0x9b: ('v_cmpx_le_i16', (('VDST', -1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'))), - 0x9c: ('v_cmpx_gt_i16', (('VDST', -1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'))), - 0x9d: ('v_cmpx_ne_i16', (('VDST', -1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'))), - 0x9e: ('v_cmpx_ge_i16', (('VDST', -1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'))), - 0x9f: ('v_cmpx_class_f16', (('VDST', -1, 'i'), ('SRC0', 1, 'f16'), ('SRC1', 1, 'f16'))), - 0xa0: ('v_cmp_f_i64', (('VDST', -1, 'i'), ('SRC0', 2, 'i'), ('SRC1', 2, 'i'))), - 0xa1: ('v_cmp_lt_i64', (('VDST', -1, 'i'), ('SRC0', 2, 'i'), ('SRC1', 2, 'i'))), - 0xa2: ('v_cmp_eq_i64', (('VDST', -1, 'i'), ('SRC0', 2, 'i'), ('SRC1', 2, 'i'))), - 0xa3: ('v_cmp_le_i64', (('VDST', -1, 'i'), ('SRC0', 2, 'i'), ('SRC1', 2, 'i'))), - 0xa4: ('v_cmp_gt_i64', (('VDST', -1, 'i'), ('SRC0', 2, 'i'), ('SRC1', 2, 'i'))), - 0xa5: ('v_cmp_ne_i64', (('VDST', -1, 'i'), ('SRC0', 2, 'i'), ('SRC1', 2, 'i'))), - 0xa6: ('v_cmp_ge_i64', (('VDST', -1, 'i'), ('SRC0', 2, 'i'), ('SRC1', 2, 'i'))), - 0xa7: ('v_cmp_t_i64', (('VDST', -1, 'i'), ('SRC0', 2, 'i'), ('SRC1', 2, 'i'))), - 0xa8: ('v_cmp_class_f64', (('VDST', -1, 'i'), ('SRC0', 2, 'f64'), ('SRC1', 1, 'i'))), - 0xa9: ('v_cmp_lt_u16', (('VDST', -1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'))), - 0xaa: ('v_cmp_eq_u16', (('VDST', -1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'))), - 0xab: ('v_cmp_le_u16', (('VDST', -1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'))), - 0xac: ('v_cmp_gt_u16', (('VDST', -1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'))), - 0xad: ('v_cmp_ne_u16', (('VDST', -1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'))), - 0xae: ('v_cmp_ge_u16', (('VDST', -1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'))), - 0xb0: ('v_cmpx_f_i64', (('VDST', -1, 'i'), ('SRC0', 2, 'i'), ('SRC1', 2, 'i'))), - 0xb1: ('v_cmpx_lt_i64', (('VDST', -1, 'i'), ('SRC0', 2, 'i'), ('SRC1', 2, 'i'))), - 0xb2: ('v_cmpx_eq_i64', (('VDST', -1, 'i'), ('SRC0', 2, 'i'), ('SRC1', 2, 'i'))), - 0xb3: ('v_cmpx_le_i64', (('VDST', -1, 'i'), ('SRC0', 2, 'i'), ('SRC1', 2, 'i'))), - 0xb4: ('v_cmpx_gt_i64', (('VDST', -1, 'i'), ('SRC0', 2, 'i'), ('SRC1', 2, 'i'))), - 0xb5: ('v_cmpx_ne_i64', (('VDST', -1, 'i'), ('SRC0', 2, 'i'), ('SRC1', 2, 'i'))), - 0xb6: ('v_cmpx_ge_i64', (('VDST', -1, 'i'), ('SRC0', 2, 'i'), ('SRC1', 2, 'i'))), - 0xb7: ('v_cmpx_t_i64', (('VDST', -1, 'i'), ('SRC0', 2, 'i'), ('SRC1', 2, 'i'))), - 0xb8: ('v_cmpx_class_f64', (('VDST', -1, 'i'), ('SRC0', 2, 'f64'), ('SRC1', 1, 'i'))), - 0xb9: ('v_cmpx_lt_u16', (('VDST', -1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'))), - 0xba: ('v_cmpx_eq_u16', (('VDST', -1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'))), - 0xbb: ('v_cmpx_le_u16', (('VDST', -1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'))), - 0xbc: ('v_cmpx_gt_u16', (('VDST', -1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'))), - 0xbd: ('v_cmpx_ne_u16', (('VDST', -1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'))), - 0xbe: ('v_cmpx_ge_u16', (('VDST', -1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'))), - 0xc0: ('v_cmp_f_u32', (('VDST', -1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'))), - 0xc1: ('v_cmp_lt_u32', (('VDST', -1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'))), - 0xc2: ('v_cmp_eq_u32', (('VDST', -1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'))), - 0xc3: ('v_cmp_le_u32', (('VDST', -1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'))), - 0xc4: ('v_cmp_gt_u32', (('VDST', -1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'))), - 0xc5: ('v_cmp_ne_u32', (('VDST', -1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'))), - 0xc6: ('v_cmp_ge_u32', (('VDST', -1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'))), - 0xc7: ('v_cmp_t_u32', (('VDST', -1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'))), - 0xc8: ('v_cmp_f_f16', (('VDST', -1, 'i'), ('SRC0', 1, 'f16'), ('SRC1', 1, 'f16'))), - 0xc9: ('v_cmp_lt_f16', (('VDST', -1, 'i'), ('SRC0', 1, 'f16'), ('SRC1', 1, 'f16'))), - 0xca: ('v_cmp_eq_f16', (('VDST', -1, 'i'), ('SRC0', 1, 'f16'), ('SRC1', 1, 'f16'))), - 0xcb: ('v_cmp_le_f16', (('VDST', -1, 'i'), ('SRC0', 1, 'f16'), ('SRC1', 1, 'f16'))), - 0xcc: ('v_cmp_gt_f16', (('VDST', -1, 'i'), ('SRC0', 1, 'f16'), ('SRC1', 1, 'f16'))), - 0xcd: ('v_cmp_lg_f16', (('VDST', -1, 'i'), ('SRC0', 1, 'f16'), ('SRC1', 1, 'f16'))), - 0xce: ('v_cmp_ge_f16', (('VDST', -1, 'i'), ('SRC0', 1, 'f16'), ('SRC1', 1, 'f16'))), - 0xcf: ('v_cmp_o_f16', (('VDST', -1, 'i'), ('SRC0', 1, 'f16'), ('SRC1', 1, 'f16'))), - 0xd0: ('v_cmpx_f_u32', (('VDST', -1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'))), - 0xd1: ('v_cmpx_lt_u32', (('VDST', -1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'))), - 0xd2: ('v_cmpx_eq_u32', (('VDST', -1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'))), - 0xd3: ('v_cmpx_le_u32', (('VDST', -1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'))), - 0xd4: ('v_cmpx_gt_u32', (('VDST', -1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'))), - 0xd5: ('v_cmpx_ne_u32', (('VDST', -1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'))), - 0xd6: ('v_cmpx_ge_u32', (('VDST', -1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'))), - 0xd7: ('v_cmpx_t_u32', (('VDST', -1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'))), - 0xd8: ('v_cmpx_f_f16', (('VDST', -1, 'i'), ('SRC0', 1, 'f16'), ('SRC1', 1, 'f16'))), - 0xd9: ('v_cmpx_lt_f16', (('VDST', -1, 'i'), ('SRC0', 1, 'f16'), ('SRC1', 1, 'f16'))), - 0xda: ('v_cmpx_eq_f16', (('VDST', -1, 'i'), ('SRC0', 1, 'f16'), ('SRC1', 1, 'f16'))), - 0xdb: ('v_cmpx_le_f16', (('VDST', -1, 'i'), ('SRC0', 1, 'f16'), ('SRC1', 1, 'f16'))), - 0xdc: ('v_cmpx_gt_f16', (('VDST', -1, 'i'), ('SRC0', 1, 'f16'), ('SRC1', 1, 'f16'))), - 0xdd: ('v_cmpx_lg_f16', (('VDST', -1, 'i'), ('SRC0', 1, 'f16'), ('SRC1', 1, 'f16'))), - 0xde: ('v_cmpx_ge_f16', (('VDST', -1, 'i'), ('SRC0', 1, 'f16'), ('SRC1', 1, 'f16'))), - 0xdf: ('v_cmpx_o_f16', (('VDST', -1, 'i'), ('SRC0', 1, 'f16'), ('SRC1', 1, 'f16'))), - 0xe0: ('v_cmp_f_u64', (('VDST', -1, 'i'), ('SRC0', 2, 'i'), ('SRC1', 2, 'i'))), - 0xe1: ('v_cmp_lt_u64', (('VDST', -1, 'i'), ('SRC0', 2, 'i'), ('SRC1', 2, 'i'))), - 0xe2: ('v_cmp_eq_u64', (('VDST', -1, 'i'), ('SRC0', 2, 'i'), ('SRC1', 2, 'i'))), - 0xe3: ('v_cmp_le_u64', (('VDST', -1, 'i'), ('SRC0', 2, 'i'), ('SRC1', 2, 'i'))), - 0xe4: ('v_cmp_gt_u64', (('VDST', -1, 'i'), ('SRC0', 2, 'i'), ('SRC1', 2, 'i'))), - 0xe5: ('v_cmp_ne_u64', (('VDST', -1, 'i'), ('SRC0', 2, 'i'), ('SRC1', 2, 'i'))), - 0xe6: ('v_cmp_ge_u64', (('VDST', -1, 'i'), ('SRC0', 2, 'i'), ('SRC1', 2, 'i'))), - 0xe7: ('v_cmp_t_u64', (('VDST', -1, 'i'), ('SRC0', 2, 'i'), ('SRC1', 2, 'i'))), - 0xe8: ('v_cmp_u_f16', (('VDST', -1, 'i'), ('SRC0', 1, 'f16'), ('SRC1', 1, 'f16'))), - 0xe9: ('v_cmp_nge_f16', (('VDST', -1, 'i'), ('SRC0', 1, 'f16'), ('SRC1', 1, 'f16'))), - 0xea: ('v_cmp_nlg_f16', (('VDST', -1, 'i'), ('SRC0', 1, 'f16'), ('SRC1', 1, 'f16'))), - 0xeb: ('v_cmp_ngt_f16', (('VDST', -1, 'i'), ('SRC0', 1, 'f16'), ('SRC1', 1, 'f16'))), - 0xec: ('v_cmp_nle_f16', (('VDST', -1, 'i'), ('SRC0', 1, 'f16'), ('SRC1', 1, 'f16'))), - 0xed: ('v_cmp_neq_f16', (('VDST', -1, 'i'), ('SRC0', 1, 'f16'), ('SRC1', 1, 'f16'))), - 0xee: ('v_cmp_nlt_f16', (('VDST', -1, 'i'), ('SRC0', 1, 'f16'), ('SRC1', 1, 'f16'))), - 0xef: ('v_cmp_tru_f16', (('VDST', -1, 'i'), ('SRC0', 1, 'f16'), ('SRC1', 1, 'f16'))), - 0xf0: ('v_cmpx_f_u64', (('VDST', -1, 'i'), ('SRC0', 2, 'i'), ('SRC1', 2, 'i'))), - 0xf1: ('v_cmpx_lt_u64', (('VDST', -1, 'i'), ('SRC0', 2, 'i'), ('SRC1', 2, 'i'))), - 0xf2: ('v_cmpx_eq_u64', (('VDST', -1, 'i'), ('SRC0', 2, 'i'), ('SRC1', 2, 'i'))), - 0xf3: ('v_cmpx_le_u64', (('VDST', -1, 'i'), ('SRC0', 2, 'i'), ('SRC1', 2, 'i'))), - 0xf4: ('v_cmpx_gt_u64', (('VDST', -1, 'i'), ('SRC0', 2, 'i'), ('SRC1', 2, 'i'))), - 0xf5: ('v_cmpx_ne_u64', (('VDST', -1, 'i'), ('SRC0', 2, 'i'), ('SRC1', 2, 'i'))), - 0xf6: ('v_cmpx_ge_u64', (('VDST', -1, 'i'), ('SRC0', 2, 'i'), ('SRC1', 2, 'i'))), - 0xf7: ('v_cmpx_t_u64', (('VDST', -1, 'i'), ('SRC0', 2, 'i'), ('SRC1', 2, 'i'))), - 0xf8: ('v_cmpx_u_f16', (('VDST', -1, 'i'), ('SRC0', 1, 'f16'), ('SRC1', 1, 'f16'))), - 0xf9: ('v_cmpx_nge_f16', (('VDST', -1, 'i'), ('SRC0', 1, 'f16'), ('SRC1', 1, 'f16'))), - 0xfa: ('v_cmpx_nlg_f16', (('VDST', -1, 'i'), ('SRC0', 1, 'f16'), ('SRC1', 1, 'f16'))), - 0xfb: ('v_cmpx_ngt_f16', (('VDST', -1, 'i'), ('SRC0', 1, 'f16'), ('SRC1', 1, 'f16'))), - 0xfc: ('v_cmpx_nle_f16', (('VDST', -1, 'i'), ('SRC0', 1, 'f16'), ('SRC1', 1, 'f16'))), - 0xfd: ('v_cmpx_neq_f16', (('VDST', -1, 'i'), ('SRC0', 1, 'f16'), ('SRC1', 1, 'f16'))), - 0xfe: ('v_cmpx_nlt_f16', (('VDST', -1, 'i'), ('SRC0', 1, 'f16'), ('SRC1', 1, 'f16'))), - 0xff: ('v_cmpx_tru_f16', (('VDST', -1, 'i'), ('SRC0', 1, 'f16'), ('SRC1', 1, 'f16'))), - 0x101: ('v_cndmask_b32', (('VDST', 1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'), ('SRC2', -1, 'i'))), - 0x103: ('v_add_f32', (('VDST', 1, 'f32'), ('SRC0', 1, 'f32'), ('SRC1', 1, 'f32'))), - 0x104: ('v_sub_f32', (('VDST', 1, 'f32'), ('SRC0', 1, 'f32'), ('SRC1', 1, 'f32'))), - 0x105: ('v_subrev_f32', (('VDST', 1, 'f32'), ('SRC0', 1, 'f32'), ('SRC1', 1, 'f32'))), - 0x106: ('v_fmac_legacy_f32', (('VDST', 1, 'f32'), ('SRC0', 1, 'f32'), ('SRC1', 1, 'f32'))), - 0x107: ('v_mul_legacy_f32', (('VDST', 1, 'f32'), ('SRC0', 1, 'f32'), ('SRC1', 1, 'f32'))), - 0x108: ('v_mul_f32', (('VDST', 1, 'f32'), ('SRC0', 1, 'f32'), ('SRC1', 1, 'f32'))), - 0x109: ('v_mul_i32_i24', (('VDST', 1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'))), - 0x10a: ('v_mul_hi_i32_i24', (('VDST', 1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'))), - 0x10b: ('v_mul_u32_u24', (('VDST', 1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'))), - 0x10c: ('v_mul_hi_u32_u24', (('VDST', 1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'))), - 0x10f: ('v_min_f32', (('VDST', 1, 'f32'), ('SRC0', 1, 'f32'), ('SRC1', 1, 'f32'))), - 0x110: ('v_max_f32', (('VDST', 1, 'f32'), ('SRC0', 1, 'f32'), ('SRC1', 1, 'f32'))), - 0x111: ('v_min_i32', (('VDST', 1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'))), - 0x112: ('v_max_i32', (('VDST', 1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'))), - 0x113: ('v_min_u32', (('VDST', 1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'))), - 0x114: ('v_max_u32', (('VDST', 1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'))), - 0x116: ('v_lshrrev_b32', (('VDST', 1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'))), - 0x118: ('v_ashrrev_i32', (('VDST', 1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'))), - 0x11a: ('v_lshlrev_b32', (('VDST', 1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'))), - 0x11b: ('v_and_b32', (('VDST', 1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'))), - 0x11c: ('v_or_b32', (('VDST', 1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'))), - 0x11d: ('v_xor_b32', (('VDST', 1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'))), - 0x11e: ('v_xnor_b32', (('VDST', 1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'))), - 0x11f: ('v_mac_f32', (('VDST', 1, 'f32'), ('SRC0', 1, 'f32'), ('SRC1', 1, 'f32'))), - 0x125: ('v_add_nc_u32', (('VDST', 1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'))), - 0x126: ('v_sub_nc_u32', (('VDST', 1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'))), - 0x127: ('v_subrev_nc_u32', (('VDST', 1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'))), - 0x12b: ('v_fmac_f32', (('VDST', 1, 'f32'), ('SRC0', 1, 'f32'), ('SRC1', 1, 'f32'))), - 0x12f: ('v_cvt_pkrtz_f16_f32', (('VDST', 1, 'f16'), ('SRC0', 1, 'f32'), ('SRC1', 1, 'f32'))), - 0x132: ('v_add_f16', (('VDST', 1, 'f16'), ('SRC0', 1, 'f16'), ('SRC1', 1, 'f16'))), - 0x133: ('v_sub_f16', (('VDST', 1, 'f16'), ('SRC0', 1, 'f16'), ('SRC1', 1, 'f16'))), - 0x134: ('v_subrev_f16', (('VDST', 1, 'f16'), ('SRC0', 1, 'f16'), ('SRC1', 1, 'f16'))), - 0x135: ('v_mul_f16', (('VDST', 1, 'f16'), ('SRC0', 1, 'f16'), ('SRC1', 1, 'f16'))), - 0x136: ('v_fmac_f16', (('VDST', 1, 'f16'), ('SRC0', 1, 'f16'), ('SRC1', 1, 'f16'))), - 0x139: ('v_max_f16', (('VDST', 1, 'f16'), ('SRC0', 1, 'f16'), ('SRC1', 1, 'f16'))), - 0x13a: ('v_min_f16', (('VDST', 1, 'f16'), ('SRC0', 1, 'f16'), ('SRC1', 1, 'f16'))), - 0x13b: ('v_ldexp_f16', (('VDST', 1, 'f16'), ('SRC0', 1, 'f16'), ('SRC1', 1, 'f16'))), - 0x140: ('v_fma_legacy_f32', (('VDST', 1, 'f32'), ('SRC0', 1, 'f32'), ('SRC1', 1, 'f32'), ('SRC2', 1, 'f32'))), - 0x141: ('v_mad_f32', (('VDST', 1, 'f32'), ('SRC0', 1, 'f32'), ('SRC1', 1, 'f32'), ('SRC2', 1, 'f32'))), - 0x142: ('v_mad_i32_i24', (('VDST', 1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'), ('SRC2', 1, 'i'))), - 0x143: ('v_mad_u32_u24', (('VDST', 1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'), ('SRC2', 1, 'i'))), - 0x144: ('v_cubeid_f32', (('VDST', 1, 'f32'), ('SRC0', 1, 'f32'), ('SRC1', 1, 'f32'), ('SRC2', 1, 'f32'))), - 0x145: ('v_cubesc_f32', (('VDST', 1, 'f32'), ('SRC0', 1, 'f32'), ('SRC1', 1, 'f32'), ('SRC2', 1, 'f32'))), - 0x146: ('v_cubetc_f32', (('VDST', 1, 'f32'), ('SRC0', 1, 'f32'), ('SRC1', 1, 'f32'), ('SRC2', 1, 'f32'))), - 0x147: ('v_cubema_f32', (('VDST', 1, 'f32'), ('SRC0', 1, 'f32'), ('SRC1', 1, 'f32'), ('SRC2', 1, 'f32'))), - 0x148: ('v_bfe_u32', (('VDST', 1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'), ('SRC2', 1, 'i'))), - 0x149: ('v_bfe_i32', (('VDST', 1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'), ('SRC2', 1, 'i'))), - 0x14a: ('v_bfi_b32', (('VDST', 1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'), ('SRC2', 1, 'i'))), - 0x14b: ('v_fma_f32', (('VDST', 1, 'f32'), ('SRC0', 1, 'f32'), ('SRC1', 1, 'f32'), ('SRC2', 1, 'f32'))), - 0x14c: ('v_fma_f64', (('VDST', 2, 'f64'), ('SRC0', 2, 'f64'), ('SRC1', 2, 'f64'), ('SRC2', 2, 'f64'))), - 0x14d: ('v_lerp_u8', (('VDST', 1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'), ('SRC2', 1, 'i'))), - 0x14e: ('v_alignbit_b32', (('VDST', 1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'), ('SRC2', 1, 'i'))), - 0x14f: ('v_alignbyte_b32', (('VDST', 1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'), ('SRC2', 1, 'i'))), - 0x150: ('v_mullit_f32', (('VDST', 1, 'f32'), ('SRC0', 1, 'f32'), ('SRC1', 1, 'f32'), ('SRC2', 1, 'f32'))), - 0x151: ('v_min3_f32', (('VDST', 1, 'f32'), ('SRC0', 1, 'f32'), ('SRC1', 1, 'f32'), ('SRC2', 1, 'f32'))), - 0x152: ('v_min3_i32', (('VDST', 1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'), ('SRC2', 1, 'i'))), - 0x153: ('v_min3_u32', (('VDST', 1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'), ('SRC2', 1, 'i'))), - 0x154: ('v_max3_f32', (('VDST', 1, 'f32'), ('SRC0', 1, 'f32'), ('SRC1', 1, 'f32'), ('SRC2', 1, 'f32'))), - 0x155: ('v_max3_i32', (('VDST', 1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'), ('SRC2', 1, 'i'))), - 0x156: ('v_max3_u32', (('VDST', 1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'), ('SRC2', 1, 'i'))), - 0x157: ('v_med3_f32', (('VDST', 1, 'f32'), ('SRC0', 1, 'f32'), ('SRC1', 1, 'f32'), ('SRC2', 1, 'f32'))), - 0x158: ('v_med3_i32', (('VDST', 1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'), ('SRC2', 1, 'i'))), - 0x159: ('v_med3_u32', (('VDST', 1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'), ('SRC2', 1, 'i'))), - 0x15a: ('v_sad_u8', (('VDST', 1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'), ('SRC2', 1, 'i'))), - 0x15b: ('v_sad_hi_u8', (('VDST', 1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'), ('SRC2', 1, 'i'))), - 0x15c: ('v_sad_u16', (('VDST', 1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'), ('SRC2', 1, 'i'))), - 0x15d: ('v_sad_u32', (('VDST', 1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'), ('SRC2', 1, 'i'))), - 0x15e: ('v_cvt_pk_u8_f32', (('VDST', 1, 'i'), ('SRC0', 1, 'f32'), ('SRC1', 1, 'i'), ('SRC2', 1, 'i'))), - 0x15f: ('v_div_fixup_f32', (('VDST', 1, 'f32'), ('SRC0', 1, 'f32'), ('SRC1', 1, 'f32'), ('SRC2', 1, 'f32'))), - 0x160: ('v_div_fixup_f64', (('VDST', 2, 'f64'), ('SRC0', 2, 'f64'), ('SRC1', 2, 'f64'), ('SRC2', 2, 'f64'))), - 0x164: ('v_add_f64', (('VDST', 2, 'f64'), ('SRC0', 2, 'f64'), ('SRC1', 2, 'f64'))), - 0x165: ('v_mul_f64', (('VDST', 2, 'f64'), ('SRC0', 2, 'f64'), ('SRC1', 2, 'f64'))), - 0x166: ('v_min_f64', (('VDST', 2, 'f64'), ('SRC0', 2, 'f64'), ('SRC1', 2, 'f64'))), - 0x167: ('v_max_f64', (('VDST', 2, 'f64'), ('SRC0', 2, 'f64'), ('SRC1', 2, 'f64'))), - 0x168: ('v_ldexp_f64', (('VDST', 2, 'f64'), ('SRC0', 2, 'f64'), ('SRC1', 1, 'i'))), - 0x169: ('v_mul_lo_u32', (('VDST', 1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'))), - 0x16a: ('v_mul_hi_u32', (('VDST', 1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'))), - 0x16c: ('v_mul_hi_i32', (('VDST', 1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'))), - 0x16f: ('v_div_fmas_f32', (('VDST', 1, 'f32'), ('SRC0', 1, 'f32'), ('SRC1', 1, 'f32'), ('SRC2', 1, 'f32'))), - 0x170: ('v_div_fmas_f64', (('VDST', 2, 'f64'), ('SRC0', 2, 'f64'), ('SRC1', 2, 'f64'), ('SRC2', 2, 'f64'))), - 0x171: ('v_msad_u8', (('VDST', 1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'), ('SRC2', 1, 'i'))), - 0x172: ('v_qsad_pk_u16_u8', (('VDST', 2, 'i'), ('SRC0', 2, 'i'), ('SRC1', 1, 'i'), ('SRC2', 2, 'i'))), - 0x173: ('v_mqsad_pk_u16_u8', (('VDST', 2, 'i'), ('SRC0', 2, 'i'), ('SRC1', 1, 'i'), ('SRC2', 2, 'i'))), - 0x174: ('v_trig_preop_f64', (('VDST', 2, 'f64'), ('SRC0', 2, 'f64'), ('SRC1', 1, 'i'))), - 0x175: ('v_mqsad_u32_u8', (('VDST', 4, 'i'), ('SRC0', 2, 'i'), ('SRC1', 1, 'i'), ('SRC2', 4, 'i'))), - 0x178: ('v_xor3_b32', (('VDST', 1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'), ('SRC2', 1, 'i'))), - 0x180: ('v_nop', ()), - 0x181: ('v_mov_b32', (('VDST', 1, 'i'), ('SRC0', 1, 'i'))), - 0x182: ('v_readfirstlane_b32', (('VDST', 1, 'i'), ('SRC0', 1, 'i'))), - 0x183: ('v_cvt_i32_f64', (('VDST', 1, 'i'), ('SRC0', 2, 'f64'))), - 0x184: ('v_cvt_f64_i32', (('VDST', 2, 'f64'), ('SRC0', 1, 'i'))), - 0x185: ('v_cvt_f32_i32', (('VDST', 1, 'f32'), ('SRC0', 1, 'i'))), - 0x186: ('v_cvt_f32_u32', (('VDST', 1, 'f32'), ('SRC0', 1, 'i'))), - 0x187: ('v_cvt_u32_f32', (('VDST', 1, 'i'), ('SRC0', 1, 'f32'))), - 0x188: ('v_cvt_i32_f32', (('VDST', 1, 'i'), ('SRC0', 1, 'f32'))), - 0x18a: ('v_cvt_f16_f32', (('VDST', 1, 'f16'), ('SRC0', 1, 'f32'))), - 0x18b: ('v_cvt_f32_f16', (('VDST', 1, 'f32'), ('SRC0', 1, 'f16'))), - 0x18c: ('v_cvt_rpi_i32_f32', (('VDST', 1, 'i'), ('SRC0', 1, 'f32'))), - 0x18d: ('v_cvt_flr_i32_f32', (('VDST', 1, 'i'), ('SRC0', 1, 'f32'))), - 0x18e: ('v_cvt_off_f32_i4', (('VDST', 1, 'f32'), ('SRC0', 1, 'i'))), - 0x18f: ('v_cvt_f32_f64', (('VDST', 1, 'f32'), ('SRC0', 2, 'f64'))), - 0x190: ('v_cvt_f64_f32', (('VDST', 2, 'f64'), ('SRC0', 1, 'f32'))), - 0x191: ('v_cvt_f32_ubyte0', (('VDST', 1, 'f32'), ('SRC0', 1, 'i'))), - 0x192: ('v_cvt_f32_ubyte1', (('VDST', 1, 'f32'), ('SRC0', 1, 'i'))), - 0x193: ('v_cvt_f32_ubyte2', (('VDST', 1, 'f32'), ('SRC0', 1, 'i'))), - 0x194: ('v_cvt_f32_ubyte3', (('VDST', 1, 'f32'), ('SRC0', 1, 'i'))), - 0x195: ('v_cvt_u32_f64', (('VDST', 1, 'i'), ('SRC0', 2, 'f64'))), - 0x196: ('v_cvt_f64_u32', (('VDST', 2, 'f64'), ('SRC0', 1, 'i'))), - 0x197: ('v_trunc_f64', (('VDST', 2, 'f64'), ('SRC0', 2, 'f64'))), - 0x198: ('v_ceil_f64', (('VDST', 2, 'f64'), ('SRC0', 2, 'f64'))), - 0x199: ('v_rndne_f64', (('VDST', 2, 'f64'), ('SRC0', 2, 'f64'))), - 0x19a: ('v_floor_f64', (('VDST', 2, 'f64'), ('SRC0', 2, 'f64'))), - 0x19b: ('v_pipeflush', ()), - 0x1a0: ('v_fract_f32', (('VDST', 1, 'f32'), ('SRC0', 1, 'f32'))), - 0x1a1: ('v_trunc_f32', (('VDST', 1, 'f32'), ('SRC0', 1, 'f32'))), - 0x1a2: ('v_ceil_f32', (('VDST', 1, 'f32'), ('SRC0', 1, 'f32'))), - 0x1a3: ('v_rndne_f32', (('VDST', 1, 'f32'), ('SRC0', 1, 'f32'))), - 0x1a4: ('v_floor_f32', (('VDST', 1, 'f32'), ('SRC0', 1, 'f32'))), - 0x1a5: ('v_exp_f32', (('VDST', 1, 'f32'), ('SRC0', 1, 'f32'))), - 0x1a7: ('v_log_f32', (('VDST', 1, 'f32'), ('SRC0', 1, 'f32'))), - 0x1aa: ('v_rcp_f32', (('VDST', 1, 'f32'), ('SRC0', 1, 'f32'))), - 0x1ab: ('v_rcp_iflag_f32', (('VDST', 1, 'f32'), ('SRC0', 1, 'f32'))), - 0x1ae: ('v_rsq_f32', (('VDST', 1, 'f32'), ('SRC0', 1, 'f32'))), - 0x1af: ('v_rcp_f64', (('VDST', 2, 'f64'), ('SRC0', 2, 'f64'))), - 0x1b1: ('v_rsq_f64', (('VDST', 2, 'f64'), ('SRC0', 2, 'f64'))), - 0x1b3: ('v_sqrt_f32', (('VDST', 1, 'f32'), ('SRC0', 1, 'f32'))), - 0x1b4: ('v_sqrt_f64', (('VDST', 2, 'f64'), ('SRC0', 2, 'f64'))), - 0x1b5: ('v_sin_f32', (('VDST', 1, 'f32'), ('SRC0', 1, 'f32'))), - 0x1b6: ('v_cos_f32', (('VDST', 1, 'f32'), ('SRC0', 1, 'f32'))), - 0x1b7: ('v_not_b32', (('VDST', 1, 'i'), ('SRC0', 1, 'i'))), - 0x1b8: ('v_bfrev_b32', (('VDST', 1, 'i'), ('SRC0', 1, 'i'))), - 0x1b9: ('v_ffbh_u32', (('VDST', 1, 'i'), ('SRC0', 1, 'i'))), - 0x1ba: ('v_ffbl_b32', (('VDST', 1, 'i'), ('SRC0', 1, 'i'))), - 0x1bb: ('v_ffbh_i32', (('VDST', 1, 'i'), ('SRC0', 1, 'i'))), - 0x1bc: ('v_frexp_exp_i32_f64', (('VDST', 1, 'i'), ('SRC0', 2, 'f64'))), - 0x1bd: ('v_frexp_mant_f64', (('VDST', 2, 'f64'), ('SRC0', 2, 'f64'))), - 0x1be: ('v_fract_f64', (('VDST', 2, 'f64'), ('SRC0', 2, 'f64'))), - 0x1bf: ('v_frexp_exp_i32_f32', (('VDST', 1, 'i'), ('SRC0', 1, 'f32'))), - 0x1c0: ('v_frexp_mant_f32', (('VDST', 1, 'f32'), ('SRC0', 1, 'f32'))), - 0x1c1: ('v_clrexcp', ()), - 0x1c2: ('v_movreld_b32', (('VDST', 1, 'i'), ('SRC0', 1, 'i'))), - 0x1c3: ('v_movrels_b32', (('VDST', 1, 'i'), ('SRC0', 1, 'i'))), - 0x1c4: ('v_movrelsd_b32', (('VDST', 1, 'i'), ('SRC0', 1, 'i'))), - 0x1c8: ('v_movrelsd_2_b32', (('VDST', 1, 'i'), ('SRC0', 1, 'i'))), - 0x1d0: ('v_cvt_f16_u16', (('VDST', 1, 'f16'), ('SRC0', 1, 'i'))), - 0x1d1: ('v_cvt_f16_i16', (('VDST', 1, 'f16'), ('SRC0', 1, 'i'))), - 0x1d2: ('v_cvt_u16_f16', (('VDST', 1, 'i'), ('SRC0', 1, 'f16'))), - 0x1d3: ('v_cvt_i16_f16', (('VDST', 1, 'i'), ('SRC0', 1, 'f16'))), - 0x1d4: ('v_rcp_f16', (('VDST', 1, 'f16'), ('SRC0', 1, 'f16'))), - 0x1d5: ('v_sqrt_f16', (('VDST', 1, 'f16'), ('SRC0', 1, 'f16'))), - 0x1d6: ('v_rsq_f16', (('VDST', 1, 'f16'), ('SRC0', 1, 'f16'))), - 0x1d7: ('v_log_f16', (('VDST', 1, 'f16'), ('SRC0', 1, 'f16'))), - 0x1d8: ('v_exp_f16', (('VDST', 1, 'f16'), ('SRC0', 1, 'f16'))), - 0x1d9: ('v_frexp_mant_f16', (('VDST', 1, 'f16'), ('SRC0', 1, 'f16'))), - 0x1da: ('v_frexp_exp_i16_f16', (('VDST', 1, 'i'), ('SRC0', 1, 'f16'))), - 0x1db: ('v_floor_f16', (('VDST', 1, 'f16'), ('SRC0', 1, 'f16'))), - 0x1dc: ('v_ceil_f16', (('VDST', 1, 'f16'), ('SRC0', 1, 'f16'))), - 0x1dd: ('v_trunc_f16', (('VDST', 1, 'f16'), ('SRC0', 1, 'f16'))), - 0x1de: ('v_rndne_f16', (('VDST', 1, 'f16'), ('SRC0', 1, 'f16'))), - 0x1df: ('v_fract_f16', (('VDST', 1, 'f16'), ('SRC0', 1, 'f16'))), - 0x1e0: ('v_sin_f16', (('VDST', 1, 'f16'), ('SRC0', 1, 'f16'))), - 0x1e1: ('v_cos_f16', (('VDST', 1, 'f16'), ('SRC0', 1, 'f16'))), - 0x1e2: ('v_sat_pk_u8_i16', (('VDST', 1, 'i'), ('SRC0', 1, 'i'))), - 0x1e3: ('v_cvt_norm_i16_f16', (('VDST', 1, 'i'), ('SRC0', 1, 'f16'))), - 0x1e4: ('v_cvt_norm_u16_f16', (('VDST', 1, 'i'), ('SRC0', 1, 'f16'))), - 0x200: ('v_interp_p1_f32', (('VDST', 1, 'f32'), ('SRC1', 1, 'f32'), ('SRC0', 1, 'i'))), - 0x201: ('v_interp_p2_f32', (('VDST', 1, 'f32'), ('SRC1', 1, 'f32'), ('SRC0', 1, 'i'))), - 0x202: ('v_interp_mov_f32', (('VDST', 1, 'f32'), ('SRC1', 1, 'i'), ('SRC0', 1, 'i'))), - 0x2ff: ('v_lshlrev_b64', (('VDST', 2, 'i'), ('SRC0', 1, 'i'), ('SRC1', 2, 'i'))), - 0x300: ('v_lshrrev_b64', (('VDST', 2, 'i'), ('SRC0', 1, 'i'), ('SRC1', 2, 'i'))), - 0x301: ('v_ashrrev_i64', (('VDST', 2, 'i'), ('SRC0', 1, 'i'), ('SRC1', 2, 'i'))), - 0x303: ('v_add_nc_u16', (('VDST', 1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'))), - 0x304: ('v_sub_nc_u16', (('VDST', 1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'))), - 0x305: ('v_mul_lo_u16', (('VDST', 1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'))), - 0x307: ('v_lshrrev_b16', (('VDST', 1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'))), - 0x308: ('v_ashrrev_i16', (('VDST', 1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'))), - 0x309: ('v_max_u16', (('VDST', 1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'))), - 0x30a: ('v_max_i16', (('VDST', 1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'))), - 0x30b: ('v_min_u16', (('VDST', 1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'))), - 0x30c: ('v_min_i16', (('VDST', 1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'))), - 0x30d: ('v_add_nc_i16', (('VDST', 1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'))), - 0x30e: ('v_sub_nc_i16', (('VDST', 1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'))), - 0x311: ('v_pack_b32_f16', (('VDST', 1, 'i'), ('SRC0', 1, 'f16'), ('SRC1', 1, 'f16'))), - 0x312: ('v_cvt_pknorm_i16_f16', (('VDST', 1, 'i'), ('SRC0', 1, 'f16'), ('SRC1', 1, 'f16'))), - 0x313: ('v_cvt_pknorm_u16_f16', (('VDST', 1, 'i'), ('SRC0', 1, 'f16'), ('SRC1', 1, 'f16'))), - 0x314: ('v_lshlrev_b16', (('VDST', 1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'))), - 0x340: ('v_mad_u16', (('VDST', 1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'), ('SRC2', 1, 'i'))), - 0x342: ('v_interp_p1ll_f16', (('VDST', 1, 'f32'), ('SRC1', 1, 'f32'), ('SRC0', 1, 'f16'))), - 0x343: ('v_interp_p1lv_f16', (('VDST', 1, 'f32'), ('SRC1', 1, 'f32'), ('SRC0', 1, 'f16'), ('SRC2', 1, 'f16'))), - 0x344: ('v_perm_b32', (('VDST', 1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'), ('SRC2', 1, 'i'))), - 0x345: ('v_xad_u32', (('VDST', 1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'), ('SRC2', 1, 'i'))), - 0x346: ('v_lshl_add_u32', (('VDST', 1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'), ('SRC2', 1, 'i'))), - 0x347: ('v_add_lshl_u32', (('VDST', 1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'), ('SRC2', 1, 'i'))), - 0x34b: ('v_fma_f16', (('VDST', 1, 'f16'), ('SRC0', 1, 'f16'), ('SRC1', 1, 'f16'), ('SRC2', 1, 'f16'))), - 0x351: ('v_min3_f16', (('VDST', 1, 'f16'), ('SRC0', 1, 'f16'), ('SRC1', 1, 'f16'), ('SRC2', 1, 'f16'))), - 0x352: ('v_min3_i16', (('VDST', 1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'), ('SRC2', 1, 'i'))), - 0x353: ('v_min3_u16', (('VDST', 1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'), ('SRC2', 1, 'i'))), - 0x354: ('v_max3_f16', (('VDST', 1, 'f16'), ('SRC0', 1, 'f16'), ('SRC1', 1, 'f16'), ('SRC2', 1, 'f16'))), - 0x355: ('v_max3_i16', (('VDST', 1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'), ('SRC2', 1, 'i'))), - 0x356: ('v_max3_u16', (('VDST', 1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'), ('SRC2', 1, 'i'))), - 0x357: ('v_med3_f16', (('VDST', 1, 'f16'), ('SRC0', 1, 'f16'), ('SRC1', 1, 'f16'), ('SRC2', 1, 'f16'))), - 0x358: ('v_med3_i16', (('VDST', 1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'), ('SRC2', 1, 'i'))), - 0x359: ('v_med3_u16', (('VDST', 1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'), ('SRC2', 1, 'i'))), - 0x35a: ('v_interp_p2_f16', (('VDST', 1, 'f16'), ('SRC1', 1, 'f32'), ('SRC0', 1, 'f16'), ('SRC2', 1, 'f32'))), - 0x35e: ('v_mad_i16', (('VDST', 1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'), ('SRC2', 1, 'i'))), - 0x35f: ('v_div_fixup_f16', (('VDST', 1, 'f16'), ('SRC0', 1, 'f16'), ('SRC1', 1, 'f16'), ('SRC2', 1, 'f16'))), - 0x360: ('v_readlane_b32', (('VDST', 1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'))), - 0x361: ('v_writelane_b32', (('VDST', 1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'))), - 0x362: ('v_ldexp_f32', (('VDST', 1, 'f32'), ('SRC0', 1, 'f32'), ('SRC1', 1, 'i'))), - 0x363: ('v_bfm_b32', (('VDST', 1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'))), - 0x364: ('v_bcnt_u32_b32', (('VDST', 1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'))), - 0x365: ('v_mbcnt_lo_u32_b32', (('VDST', 1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'))), - 0x366: ('v_mbcnt_hi_u32_b32', (('VDST', 1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'))), - 0x368: ('v_cvt_pknorm_i16_f32', (('VDST', 1, 'i'), ('SRC0', 1, 'f32'), ('SRC1', 1, 'f32'))), - 0x369: ('v_cvt_pknorm_u16_f32', (('VDST', 1, 'i'), ('SRC0', 1, 'f32'), ('SRC1', 1, 'f32'))), - 0x36a: ('v_cvt_pk_u16_u32', (('VDST', 1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'))), - 0x36b: ('v_cvt_pk_i16_i32', (('VDST', 1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'))), - 0x36d: ('v_add3_u32', (('VDST', 1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'), ('SRC2', 1, 'i'))), - 0x36f: ('v_lshl_or_b32', (('VDST', 1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'), ('SRC2', 1, 'i'))), - 0x371: ('v_and_or_b32', (('VDST', 1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'), ('SRC2', 1, 'i'))), - 0x372: ('v_or3_b32', (('VDST', 1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'), ('SRC2', 1, 'i'))), - 0x373: ('v_mad_u32_u16', (('VDST', 1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'), ('SRC2', 1, 'i'))), - 0x375: ('v_mad_i32_i16', (('VDST', 1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'), ('SRC2', 1, 'i'))), - 0x376: ('v_sub_nc_i32', (('VDST', 1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'))), - 0x377: ('v_permlane16_b32', (('VDST', 1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'), ('SRC2', 1, 'i'))), - 0x378: ('v_permlanex16_b32', (('VDST', 1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'), ('SRC2', 1, 'i'))), - 0x37f: ('v_add_nc_i32', (('VDST', 1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'))), -} - -VOP3B = { - 0x128: ('v_add_co_ci_u32', (('VDST', 1, 'i'), ('SDST', -1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'), ('SRC2', -1, 'i'))), - 0x129: ('v_sub_co_ci_u32', (('VDST', 1, 'i'), ('SDST', -1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'), ('SRC2', -1, 'i'))), - 0x12a: ('v_subrev_co_ci_u32', (('VDST', 1, 'i'), ('SDST', -1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'), ('SRC2', -1, 'i'))), - 0x16d: ('v_div_scale_f32', (('VDST', 1, 'f32'), ('SDST', -1, 'i'), ('SRC0', 1, 'f32'), ('SRC1', 1, 'f32'), ('SRC2', 1, 'f32'))), - 0x16e: ('v_div_scale_f64', (('VDST', 2, 'f64'), ('SDST', -1, 'i'), ('SRC0', 2, 'f64'), ('SRC1', 2, 'f64'), ('SRC2', 2, 'f64'))), - 0x176: ('v_mad_u64_u32', (('VDST', 2, 'i'), ('SDST', -1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'), ('SRC2', 2, 'i'))), - 0x177: ('v_mad_i64_i32', (('VDST', 2, 'i'), ('SDST', -1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'), ('SRC2', 2, 'i'))), - 0x30f: ('v_add_co_u32', (('VDST', 1, 'i'), ('SDST', -1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'))), - 0x310: ('v_sub_co_u32', (('VDST', 1, 'i'), ('SDST', -1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'))), - 0x319: ('v_subrev_co_u32', (('VDST', 1, 'i'), ('SDST', -1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'))), -} - -VOP3P = { - 0x0: ('v_pk_mad_i16', (('VDST', 1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'), ('SRC2', 1, 'i'))), - 0x1: ('v_pk_mul_lo_u16', (('VDST', 1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'))), - 0x2: ('v_pk_add_i16', (('VDST', 1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'))), - 0x3: ('v_pk_sub_i16', (('VDST', 1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'))), - 0x4: ('v_pk_lshlrev_b16', (('VDST', 1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'))), - 0x5: ('v_pk_lshrrev_b16', (('VDST', 1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'))), - 0x6: ('v_pk_ashrrev_i16', (('VDST', 1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'))), - 0x7: ('v_pk_max_i16', (('VDST', 1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'))), - 0x8: ('v_pk_min_i16', (('VDST', 1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'))), - 0x9: ('v_pk_mad_u16', (('VDST', 1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'), ('SRC2', 1, 'i'))), - 0xa: ('v_pk_add_u16', (('VDST', 1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'))), - 0xb: ('v_pk_sub_u16', (('VDST', 1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'))), - 0xc: ('v_pk_max_u16', (('VDST', 1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'))), - 0xd: ('v_pk_min_u16', (('VDST', 1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'))), - 0xe: ('v_pk_fma_f16', (('VDST', 1, 'f16'), ('SRC0', 1, 'f16'), ('SRC1', 1, 'f16'), ('SRC2', 1, 'f16'))), - 0xf: ('v_pk_add_f16', (('VDST', 1, 'f16'), ('SRC0', 1, 'f16'), ('SRC1', 1, 'f16'))), - 0x10: ('v_pk_mul_f16', (('VDST', 1, 'f16'), ('SRC0', 1, 'f16'), ('SRC1', 1, 'f16'))), - 0x11: ('v_pk_min_f16', (('VDST', 1, 'f16'), ('SRC0', 1, 'f16'), ('SRC1', 1, 'f16'))), - 0x12: ('v_pk_max_f16', (('VDST', 1, 'f16'), ('SRC0', 1, 'f16'), ('SRC1', 1, 'f16'))), - 0x13: ('v_dot2_f32_f16', (('VDST', 1, 'f32'), ('SRC0', 1, 'f16'), ('SRC1', 1, 'f16'), ('SRC2', 1, 'f32'))), - 0x14: ('v_dot2_i32_i16', (('VDST', 1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'), ('SRC2', 1, 'i'))), - 0x15: ('v_dot2_u32_u16', (('VDST', 1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'), ('SRC2', 1, 'i'))), - 0x16: ('v_dot4_i32_i8', (('VDST', 1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'), ('SRC2', 1, 'i'))), - 0x17: ('v_dot4_u32_u8', (('VDST', 1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'), ('SRC2', 1, 'i'))), - 0x18: ('v_dot8_i32_i4', (('VDST', 1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'), ('SRC2', 1, 'i'))), - 0x19: ('v_dot8_u32_u4', (('VDST', 1, 'i'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'), ('SRC2', 1, 'i'))), - 0x20: ('v_fma_mix_f32', (('VDST', 1, 'f32'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'), ('SRC2', 1, 'i'))), - 0x21: ('v_fma_mixlo_f16', (('VDST', 1, 'f16'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'), ('SRC2', 1, 'i'))), - 0x22: ('v_fma_mixhi_f16', (('VDST', 1, 'f16'), ('SRC0', 1, 'i'), ('SRC1', 1, 'i'), ('SRC2', 1, 'i'))), -} - -VOPC = { - 0x0: ('v_cmp_f_f32', (('VCC', -1, 'i'), ('SRC0', 1, 'f32'), ('VSRC1', 1, 'f32'))), - 0x1: ('v_cmp_lt_f32', (('VCC', -1, 'i'), ('SRC0', 1, 'f32'), ('VSRC1', 1, 'f32'))), - 0x2: ('v_cmp_eq_f32', (('VCC', -1, 'i'), ('SRC0', 1, 'f32'), ('VSRC1', 1, 'f32'))), - 0x3: ('v_cmp_le_f32', (('VCC', -1, 'i'), ('SRC0', 1, 'f32'), ('VSRC1', 1, 'f32'))), - 0x4: ('v_cmp_gt_f32', (('VCC', -1, 'i'), ('SRC0', 1, 'f32'), ('VSRC1', 1, 'f32'))), - 0x5: ('v_cmp_lg_f32', (('VCC', -1, 'i'), ('SRC0', 1, 'f32'), ('VSRC1', 1, 'f32'))), - 0x6: ('v_cmp_ge_f32', (('VCC', -1, 'i'), ('SRC0', 1, 'f32'), ('VSRC1', 1, 'f32'))), - 0x7: ('v_cmp_o_f32', (('VCC', -1, 'i'), ('SRC0', 1, 'f32'), ('VSRC1', 1, 'f32'))), - 0x8: ('v_cmp_u_f32', (('VCC', -1, 'i'), ('SRC0', 1, 'f32'), ('VSRC1', 1, 'f32'))), - 0x9: ('v_cmp_nge_f32', (('VCC', -1, 'i'), ('SRC0', 1, 'f32'), ('VSRC1', 1, 'f32'))), - 0xa: ('v_cmp_nlg_f32', (('VCC', -1, 'i'), ('SRC0', 1, 'f32'), ('VSRC1', 1, 'f32'))), - 0xb: ('v_cmp_ngt_f32', (('VCC', -1, 'i'), ('SRC0', 1, 'f32'), ('VSRC1', 1, 'f32'))), - 0xc: ('v_cmp_nle_f32', (('VCC', -1, 'i'), ('SRC0', 1, 'f32'), ('VSRC1', 1, 'f32'))), - 0xd: ('v_cmp_neq_f32', (('VCC', -1, 'i'), ('SRC0', 1, 'f32'), ('VSRC1', 1, 'f32'))), - 0xe: ('v_cmp_nlt_f32', (('VCC', -1, 'i'), ('SRC0', 1, 'f32'), ('VSRC1', 1, 'f32'))), - 0xf: ('v_cmp_tru_f32', (('VCC', -1, 'i'), ('SRC0', 1, 'f32'), ('VSRC1', 1, 'f32'))), - 0x10: ('v_cmpx_f_f32', (('OPR_EXEC', -1, 'i'), ('SRC0', 1, 'f32'), ('VSRC1', 1, 'f32'))), - 0x11: ('v_cmpx_lt_f32', (('OPR_EXEC', -1, 'i'), ('SRC0', 1, 'f32'), ('VSRC1', 1, 'f32'))), - 0x12: ('v_cmpx_eq_f32', (('OPR_EXEC', -1, 'i'), ('SRC0', 1, 'f32'), ('VSRC1', 1, 'f32'))), - 0x13: ('v_cmpx_le_f32', (('OPR_EXEC', -1, 'i'), ('SRC0', 1, 'f32'), ('VSRC1', 1, 'f32'))), - 0x14: ('v_cmpx_gt_f32', (('OPR_EXEC', -1, 'i'), ('SRC0', 1, 'f32'), ('VSRC1', 1, 'f32'))), - 0x15: ('v_cmpx_lg_f32', (('OPR_EXEC', -1, 'i'), ('SRC0', 1, 'f32'), ('VSRC1', 1, 'f32'))), - 0x16: ('v_cmpx_ge_f32', (('OPR_EXEC', -1, 'i'), ('SRC0', 1, 'f32'), ('VSRC1', 1, 'f32'))), - 0x17: ('v_cmpx_o_f32', (('OPR_EXEC', -1, 'i'), ('SRC0', 1, 'f32'), ('VSRC1', 1, 'f32'))), - 0x18: ('v_cmpx_u_f32', (('OPR_EXEC', -1, 'i'), ('SRC0', 1, 'f32'), ('VSRC1', 1, 'f32'))), - 0x19: ('v_cmpx_nge_f32', (('OPR_EXEC', -1, 'i'), ('SRC0', 1, 'f32'), ('VSRC1', 1, 'f32'))), - 0x1a: ('v_cmpx_nlg_f32', (('OPR_EXEC', -1, 'i'), ('SRC0', 1, 'f32'), ('VSRC1', 1, 'f32'))), - 0x1b: ('v_cmpx_ngt_f32', (('OPR_EXEC', -1, 'i'), ('SRC0', 1, 'f32'), ('VSRC1', 1, 'f32'))), - 0x1c: ('v_cmpx_nle_f32', (('OPR_EXEC', -1, 'i'), ('SRC0', 1, 'f32'), ('VSRC1', 1, 'f32'))), - 0x1d: ('v_cmpx_neq_f32', (('OPR_EXEC', -1, 'i'), ('SRC0', 1, 'f32'), ('VSRC1', 1, 'f32'))), - 0x1e: ('v_cmpx_nlt_f32', (('OPR_EXEC', -1, 'i'), ('SRC0', 1, 'f32'), ('VSRC1', 1, 'f32'))), - 0x1f: ('v_cmpx_tru_f32', (('OPR_EXEC', -1, 'i'), ('SRC0', 1, 'f32'), ('VSRC1', 1, 'f32'))), - 0x20: ('v_cmp_f_f64', (('VCC', -1, 'i'), ('SRC0', 2, 'f64'), ('VSRC1', 2, 'f64'))), - 0x21: ('v_cmp_lt_f64', (('VCC', -1, 'i'), ('SRC0', 2, 'f64'), ('VSRC1', 2, 'f64'))), - 0x22: ('v_cmp_eq_f64', (('VCC', -1, 'i'), ('SRC0', 2, 'f64'), ('VSRC1', 2, 'f64'))), - 0x23: ('v_cmp_le_f64', (('VCC', -1, 'i'), ('SRC0', 2, 'f64'), ('VSRC1', 2, 'f64'))), - 0x24: ('v_cmp_gt_f64', (('VCC', -1, 'i'), ('SRC0', 2, 'f64'), ('VSRC1', 2, 'f64'))), - 0x25: ('v_cmp_lg_f64', (('VCC', -1, 'i'), ('SRC0', 2, 'f64'), ('VSRC1', 2, 'f64'))), - 0x26: ('v_cmp_ge_f64', (('VCC', -1, 'i'), ('SRC0', 2, 'f64'), ('VSRC1', 2, 'f64'))), - 0x27: ('v_cmp_o_f64', (('VCC', -1, 'i'), ('SRC0', 2, 'f64'), ('VSRC1', 2, 'f64'))), - 0x28: ('v_cmp_u_f64', (('VCC', -1, 'i'), ('SRC0', 2, 'f64'), ('VSRC1', 2, 'f64'))), - 0x29: ('v_cmp_nge_f64', (('VCC', -1, 'i'), ('SRC0', 2, 'f64'), ('VSRC1', 2, 'f64'))), - 0x2a: ('v_cmp_nlg_f64', (('VCC', -1, 'i'), ('SRC0', 2, 'f64'), ('VSRC1', 2, 'f64'))), - 0x2b: ('v_cmp_ngt_f64', (('VCC', -1, 'i'), ('SRC0', 2, 'f64'), ('VSRC1', 2, 'f64'))), - 0x2c: ('v_cmp_nle_f64', (('VCC', -1, 'i'), ('SRC0', 2, 'f64'), ('VSRC1', 2, 'f64'))), - 0x2d: ('v_cmp_neq_f64', (('VCC', -1, 'i'), ('SRC0', 2, 'f64'), ('VSRC1', 2, 'f64'))), - 0x2e: ('v_cmp_nlt_f64', (('VCC', -1, 'i'), ('SRC0', 2, 'f64'), ('VSRC1', 2, 'f64'))), - 0x2f: ('v_cmp_tru_f64', (('VCC', -1, 'i'), ('SRC0', 2, 'f64'), ('VSRC1', 2, 'f64'))), - 0x30: ('v_cmpx_f_f64', (('OPR_EXEC', -1, 'i'), ('SRC0', 2, 'f64'), ('VSRC1', 2, 'f64'))), - 0x31: ('v_cmpx_lt_f64', (('OPR_EXEC', -1, 'i'), ('SRC0', 2, 'f64'), ('VSRC1', 2, 'f64'))), - 0x32: ('v_cmpx_eq_f64', (('OPR_EXEC', -1, 'i'), ('SRC0', 2, 'f64'), ('VSRC1', 2, 'f64'))), - 0x33: ('v_cmpx_le_f64', (('OPR_EXEC', -1, 'i'), ('SRC0', 2, 'f64'), ('VSRC1', 2, 'f64'))), - 0x34: ('v_cmpx_gt_f64', (('OPR_EXEC', -1, 'i'), ('SRC0', 2, 'f64'), ('VSRC1', 2, 'f64'))), - 0x35: ('v_cmpx_lg_f64', (('OPR_EXEC', -1, 'i'), ('SRC0', 2, 'f64'), ('VSRC1', 2, 'f64'))), - 0x36: ('v_cmpx_ge_f64', (('OPR_EXEC', -1, 'i'), ('SRC0', 2, 'f64'), ('VSRC1', 2, 'f64'))), - 0x37: ('v_cmpx_o_f64', (('OPR_EXEC', -1, 'i'), ('SRC0', 2, 'f64'), ('VSRC1', 2, 'f64'))), - 0x38: ('v_cmpx_u_f64', (('OPR_EXEC', -1, 'i'), ('SRC0', 2, 'f64'), ('VSRC1', 2, 'f64'))), - 0x39: ('v_cmpx_nge_f64', (('OPR_EXEC', -1, 'i'), ('SRC0', 2, 'f64'), ('VSRC1', 2, 'f64'))), - 0x3a: ('v_cmpx_nlg_f64', (('OPR_EXEC', -1, 'i'), ('SRC0', 2, 'f64'), ('VSRC1', 2, 'f64'))), - 0x3b: ('v_cmpx_ngt_f64', (('OPR_EXEC', -1, 'i'), ('SRC0', 2, 'f64'), ('VSRC1', 2, 'f64'))), - 0x3c: ('v_cmpx_nle_f64', (('OPR_EXEC', -1, 'i'), ('SRC0', 2, 'f64'), ('VSRC1', 2, 'f64'))), - 0x3d: ('v_cmpx_neq_f64', (('OPR_EXEC', -1, 'i'), ('SRC0', 2, 'f64'), ('VSRC1', 2, 'f64'))), - 0x3e: ('v_cmpx_nlt_f64', (('OPR_EXEC', -1, 'i'), ('SRC0', 2, 'f64'), ('VSRC1', 2, 'f64'))), - 0x3f: ('v_cmpx_tru_f64', (('OPR_EXEC', -1, 'i'), ('SRC0', 2, 'f64'), ('VSRC1', 2, 'f64'))), - 0x80: ('v_cmp_f_i32', (('VCC', -1, 'i'), ('SRC0', 1, 'i'), ('VSRC1', 1, 'i'))), - 0x81: ('v_cmp_lt_i32', (('VCC', -1, 'i'), ('SRC0', 1, 'i'), ('VSRC1', 1, 'i'))), - 0x82: ('v_cmp_eq_i32', (('VCC', -1, 'i'), ('SRC0', 1, 'i'), ('VSRC1', 1, 'i'))), - 0x83: ('v_cmp_le_i32', (('VCC', -1, 'i'), ('SRC0', 1, 'i'), ('VSRC1', 1, 'i'))), - 0x84: ('v_cmp_gt_i32', (('VCC', -1, 'i'), ('SRC0', 1, 'i'), ('VSRC1', 1, 'i'))), - 0x85: ('v_cmp_ne_i32', (('VCC', -1, 'i'), ('SRC0', 1, 'i'), ('VSRC1', 1, 'i'))), - 0x86: ('v_cmp_ge_i32', (('VCC', -1, 'i'), ('SRC0', 1, 'i'), ('VSRC1', 1, 'i'))), - 0x87: ('v_cmp_t_i32', (('VCC', -1, 'i'), ('SRC0', 1, 'i'), ('VSRC1', 1, 'i'))), - 0x88: ('v_cmp_class_f32', (('VCC', -1, 'i'), ('SRC0', 1, 'f32'), ('VSRC1', 1, 'i'))), - 0x89: ('v_cmp_lt_i16', (('VCC', -1, 'i'), ('SRC0', 1, 'i'), ('VSRC1', 1, 'i'))), - 0x8a: ('v_cmp_eq_i16', (('VCC', -1, 'i'), ('SRC0', 1, 'i'), ('VSRC1', 1, 'i'))), - 0x8b: ('v_cmp_le_i16', (('VCC', -1, 'i'), ('SRC0', 1, 'i'), ('VSRC1', 1, 'i'))), - 0x8c: ('v_cmp_gt_i16', (('VCC', -1, 'i'), ('SRC0', 1, 'i'), ('VSRC1', 1, 'i'))), - 0x8d: ('v_cmp_ne_i16', (('VCC', -1, 'i'), ('SRC0', 1, 'i'), ('VSRC1', 1, 'i'))), - 0x8e: ('v_cmp_ge_i16', (('VCC', -1, 'i'), ('SRC0', 1, 'i'), ('VSRC1', 1, 'i'))), - 0x8f: ('v_cmp_class_f16', (('VCC', -1, 'i'), ('SRC0', 1, 'f16'), ('VSRC1', 1, 'f16'))), - 0x90: ('v_cmpx_f_i32', (('OPR_EXEC', -1, 'i'), ('SRC0', 1, 'i'), ('VSRC1', 1, 'i'))), - 0x91: ('v_cmpx_lt_i32', (('OPR_EXEC', -1, 'i'), ('SRC0', 1, 'i'), ('VSRC1', 1, 'i'))), - 0x92: ('v_cmpx_eq_i32', (('OPR_EXEC', -1, 'i'), ('SRC0', 1, 'i'), ('VSRC1', 1, 'i'))), - 0x93: ('v_cmpx_le_i32', (('OPR_EXEC', -1, 'i'), ('SRC0', 1, 'i'), ('VSRC1', 1, 'i'))), - 0x94: ('v_cmpx_gt_i32', (('OPR_EXEC', -1, 'i'), ('SRC0', 1, 'i'), ('VSRC1', 1, 'i'))), - 0x95: ('v_cmpx_ne_i32', (('OPR_EXEC', -1, 'i'), ('SRC0', 1, 'i'), ('VSRC1', 1, 'i'))), - 0x96: ('v_cmpx_ge_i32', (('OPR_EXEC', -1, 'i'), ('SRC0', 1, 'i'), ('VSRC1', 1, 'i'))), - 0x97: ('v_cmpx_t_i32', (('OPR_EXEC', -1, 'i'), ('SRC0', 1, 'i'), ('VSRC1', 1, 'i'))), - 0x98: ('v_cmpx_class_f32', (('OPR_EXEC', -1, 'i'), ('SRC0', 1, 'f32'), ('VSRC1', 1, 'i'))), - 0x99: ('v_cmpx_lt_i16', (('OPR_EXEC', -1, 'i'), ('SRC0', 1, 'i'), ('VSRC1', 1, 'i'))), - 0x9a: ('v_cmpx_eq_i16', (('OPR_EXEC', -1, 'i'), ('SRC0', 1, 'i'), ('VSRC1', 1, 'i'))), - 0x9b: ('v_cmpx_le_i16', (('OPR_EXEC', -1, 'i'), ('SRC0', 1, 'i'), ('VSRC1', 1, 'i'))), - 0x9c: ('v_cmpx_gt_i16', (('OPR_EXEC', -1, 'i'), ('SRC0', 1, 'i'), ('VSRC1', 1, 'i'))), - 0x9d: ('v_cmpx_ne_i16', (('OPR_EXEC', -1, 'i'), ('SRC0', 1, 'i'), ('VSRC1', 1, 'i'))), - 0x9e: ('v_cmpx_ge_i16', (('OPR_EXEC', -1, 'i'), ('SRC0', 1, 'i'), ('VSRC1', 1, 'i'))), - 0x9f: ('v_cmpx_class_f16', (('OPR_EXEC', -1, 'i'), ('SRC0', 1, 'f16'), ('VSRC1', 1, 'f16'))), - 0xa0: ('v_cmp_f_i64', (('VCC', -1, 'i'), ('SRC0', 2, 'i'), ('VSRC1', 2, 'i'))), - 0xa1: ('v_cmp_lt_i64', (('VCC', -1, 'i'), ('SRC0', 2, 'i'), ('VSRC1', 2, 'i'))), - 0xa2: ('v_cmp_eq_i64', (('VCC', -1, 'i'), ('SRC0', 2, 'i'), ('VSRC1', 2, 'i'))), - 0xa3: ('v_cmp_le_i64', (('VCC', -1, 'i'), ('SRC0', 2, 'i'), ('VSRC1', 2, 'i'))), - 0xa4: ('v_cmp_gt_i64', (('VCC', -1, 'i'), ('SRC0', 2, 'i'), ('VSRC1', 2, 'i'))), - 0xa5: ('v_cmp_ne_i64', (('VCC', -1, 'i'), ('SRC0', 2, 'i'), ('VSRC1', 2, 'i'))), - 0xa6: ('v_cmp_ge_i64', (('VCC', -1, 'i'), ('SRC0', 2, 'i'), ('VSRC1', 2, 'i'))), - 0xa7: ('v_cmp_t_i64', (('VCC', -1, 'i'), ('SRC0', 2, 'i'), ('VSRC1', 2, 'i'))), - 0xa8: ('v_cmp_class_f64', (('VCC', -1, 'i'), ('SRC0', 2, 'f64'), ('VSRC1', 1, 'i'))), - 0xa9: ('v_cmp_lt_u16', (('VCC', -1, 'i'), ('SRC0', 1, 'i'), ('VSRC1', 1, 'i'))), - 0xaa: ('v_cmp_eq_u16', (('VCC', -1, 'i'), ('SRC0', 1, 'i'), ('VSRC1', 1, 'i'))), - 0xab: ('v_cmp_le_u16', (('VCC', -1, 'i'), ('SRC0', 1, 'i'), ('VSRC1', 1, 'i'))), - 0xac: ('v_cmp_gt_u16', (('VCC', -1, 'i'), ('SRC0', 1, 'i'), ('VSRC1', 1, 'i'))), - 0xad: ('v_cmp_ne_u16', (('VCC', -1, 'i'), ('SRC0', 1, 'i'), ('VSRC1', 1, 'i'))), - 0xae: ('v_cmp_ge_u16', (('VCC', -1, 'i'), ('SRC0', 1, 'i'), ('VSRC1', 1, 'i'))), - 0xb0: ('v_cmpx_f_i64', (('OPR_EXEC', -1, 'i'), ('SRC0', 2, 'i'), ('VSRC1', 2, 'i'))), - 0xb1: ('v_cmpx_lt_i64', (('OPR_EXEC', -1, 'i'), ('SRC0', 2, 'i'), ('VSRC1', 2, 'i'))), - 0xb2: ('v_cmpx_eq_i64', (('OPR_EXEC', -1, 'i'), ('SRC0', 2, 'i'), ('VSRC1', 2, 'i'))), - 0xb3: ('v_cmpx_le_i64', (('OPR_EXEC', -1, 'i'), ('SRC0', 2, 'i'), ('VSRC1', 2, 'i'))), - 0xb4: ('v_cmpx_gt_i64', (('OPR_EXEC', -1, 'i'), ('SRC0', 2, 'i'), ('VSRC1', 2, 'i'))), - 0xb5: ('v_cmpx_ne_i64', (('OPR_EXEC', -1, 'i'), ('SRC0', 2, 'i'), ('VSRC1', 2, 'i'))), - 0xb6: ('v_cmpx_ge_i64', (('OPR_EXEC', -1, 'i'), ('SRC0', 2, 'i'), ('VSRC1', 2, 'i'))), - 0xb7: ('v_cmpx_t_i64', (('OPR_EXEC', -1, 'i'), ('SRC0', 2, 'i'), ('VSRC1', 2, 'i'))), - 0xb8: ('v_cmpx_class_f64', (('OPR_EXEC', -1, 'i'), ('SRC0', 2, 'f64'), ('VSRC1', 1, 'i'))), - 0xb9: ('v_cmpx_lt_u16', (('OPR_EXEC', -1, 'i'), ('SRC0', 1, 'i'), ('VSRC1', 1, 'i'))), - 0xba: ('v_cmpx_eq_u16', (('OPR_EXEC', -1, 'i'), ('SRC0', 1, 'i'), ('VSRC1', 1, 'i'))), - 0xbb: ('v_cmpx_le_u16', (('OPR_EXEC', -1, 'i'), ('SRC0', 1, 'i'), ('VSRC1', 1, 'i'))), - 0xbc: ('v_cmpx_gt_u16', (('OPR_EXEC', -1, 'i'), ('SRC0', 1, 'i'), ('VSRC1', 1, 'i'))), - 0xbd: ('v_cmpx_ne_u16', (('OPR_EXEC', -1, 'i'), ('SRC0', 1, 'i'), ('VSRC1', 1, 'i'))), - 0xbe: ('v_cmpx_ge_u16', (('OPR_EXEC', -1, 'i'), ('SRC0', 1, 'i'), ('VSRC1', 1, 'i'))), - 0xc0: ('v_cmp_f_u32', (('VCC', -1, 'i'), ('SRC0', 1, 'i'), ('VSRC1', 1, 'i'))), - 0xc1: ('v_cmp_lt_u32', (('VCC', -1, 'i'), ('SRC0', 1, 'i'), ('VSRC1', 1, 'i'))), - 0xc2: ('v_cmp_eq_u32', (('VCC', -1, 'i'), ('SRC0', 1, 'i'), ('VSRC1', 1, 'i'))), - 0xc3: ('v_cmp_le_u32', (('VCC', -1, 'i'), ('SRC0', 1, 'i'), ('VSRC1', 1, 'i'))), - 0xc4: ('v_cmp_gt_u32', (('VCC', -1, 'i'), ('SRC0', 1, 'i'), ('VSRC1', 1, 'i'))), - 0xc5: ('v_cmp_ne_u32', (('VCC', -1, 'i'), ('SRC0', 1, 'i'), ('VSRC1', 1, 'i'))), - 0xc6: ('v_cmp_ge_u32', (('VCC', -1, 'i'), ('SRC0', 1, 'i'), ('VSRC1', 1, 'i'))), - 0xc7: ('v_cmp_t_u32', (('VCC', -1, 'i'), ('SRC0', 1, 'i'), ('VSRC1', 1, 'i'))), - 0xc8: ('v_cmp_f_f16', (('VCC', -1, 'i'), ('SRC0', 1, 'f16'), ('VSRC1', 1, 'f16'))), - 0xc9: ('v_cmp_lt_f16', (('VCC', -1, 'i'), ('SRC0', 1, 'f16'), ('VSRC1', 1, 'f16'))), - 0xca: ('v_cmp_eq_f16', (('VCC', -1, 'i'), ('SRC0', 1, 'f16'), ('VSRC1', 1, 'f16'))), - 0xcb: ('v_cmp_le_f16', (('VCC', -1, 'i'), ('SRC0', 1, 'f16'), ('VSRC1', 1, 'f16'))), - 0xcc: ('v_cmp_gt_f16', (('VCC', -1, 'i'), ('SRC0', 1, 'f16'), ('VSRC1', 1, 'f16'))), - 0xcd: ('v_cmp_lg_f16', (('VCC', -1, 'i'), ('SRC0', 1, 'f16'), ('VSRC1', 1, 'f16'))), - 0xce: ('v_cmp_ge_f16', (('VCC', -1, 'i'), ('SRC0', 1, 'f16'), ('VSRC1', 1, 'f16'))), - 0xcf: ('v_cmp_o_f16', (('VCC', -1, 'i'), ('SRC0', 1, 'f16'), ('VSRC1', 1, 'f16'))), - 0xd0: ('v_cmpx_f_u32', (('OPR_EXEC', -1, 'i'), ('SRC0', 1, 'i'), ('VSRC1', 1, 'i'))), - 0xd1: ('v_cmpx_lt_u32', (('OPR_EXEC', -1, 'i'), ('SRC0', 1, 'i'), ('VSRC1', 1, 'i'))), - 0xd2: ('v_cmpx_eq_u32', (('OPR_EXEC', -1, 'i'), ('SRC0', 1, 'i'), ('VSRC1', 1, 'i'))), - 0xd3: ('v_cmpx_le_u32', (('OPR_EXEC', -1, 'i'), ('SRC0', 1, 'i'), ('VSRC1', 1, 'i'))), - 0xd4: ('v_cmpx_gt_u32', (('OPR_EXEC', -1, 'i'), ('SRC0', 1, 'i'), ('VSRC1', 1, 'i'))), - 0xd5: ('v_cmpx_ne_u32', (('OPR_EXEC', -1, 'i'), ('SRC0', 1, 'i'), ('VSRC1', 1, 'i'))), - 0xd6: ('v_cmpx_ge_u32', (('OPR_EXEC', -1, 'i'), ('SRC0', 1, 'i'), ('VSRC1', 1, 'i'))), - 0xd7: ('v_cmpx_t_u32', (('OPR_EXEC', -1, 'i'), ('SRC0', 1, 'i'), ('VSRC1', 1, 'i'))), - 0xd8: ('v_cmpx_f_f16', (('OPR_EXEC', -1, 'i'), ('SRC0', 1, 'f16'), ('VSRC1', 1, 'f16'))), - 0xd9: ('v_cmpx_lt_f16', (('OPR_EXEC', -1, 'i'), ('SRC0', 1, 'f16'), ('VSRC1', 1, 'f16'))), - 0xda: ('v_cmpx_eq_f16', (('OPR_EXEC', -1, 'i'), ('SRC0', 1, 'f16'), ('VSRC1', 1, 'f16'))), - 0xdb: ('v_cmpx_le_f16', (('OPR_EXEC', -1, 'i'), ('SRC0', 1, 'f16'), ('VSRC1', 1, 'f16'))), - 0xdc: ('v_cmpx_gt_f16', (('OPR_EXEC', -1, 'i'), ('SRC0', 1, 'f16'), ('VSRC1', 1, 'f16'))), - 0xdd: ('v_cmpx_lg_f16', (('OPR_EXEC', -1, 'i'), ('SRC0', 1, 'f16'), ('VSRC1', 1, 'f16'))), - 0xde: ('v_cmpx_ge_f16', (('OPR_EXEC', -1, 'i'), ('SRC0', 1, 'f16'), ('VSRC1', 1, 'f16'))), - 0xdf: ('v_cmpx_o_f16', (('OPR_EXEC', -1, 'i'), ('SRC0', 1, 'f16'), ('VSRC1', 1, 'f16'))), - 0xe0: ('v_cmp_f_u64', (('VCC', -1, 'i'), ('SRC0', 2, 'i'), ('VSRC1', 2, 'i'))), - 0xe1: ('v_cmp_lt_u64', (('VCC', -1, 'i'), ('SRC0', 2, 'i'), ('VSRC1', 2, 'i'))), - 0xe2: ('v_cmp_eq_u64', (('VCC', -1, 'i'), ('SRC0', 2, 'i'), ('VSRC1', 2, 'i'))), - 0xe3: ('v_cmp_le_u64', (('VCC', -1, 'i'), ('SRC0', 2, 'i'), ('VSRC1', 2, 'i'))), - 0xe4: ('v_cmp_gt_u64', (('VCC', -1, 'i'), ('SRC0', 2, 'i'), ('VSRC1', 2, 'i'))), - 0xe5: ('v_cmp_ne_u64', (('VCC', -1, 'i'), ('SRC0', 2, 'i'), ('VSRC1', 2, 'i'))), - 0xe6: ('v_cmp_ge_u64', (('VCC', -1, 'i'), ('SRC0', 2, 'i'), ('VSRC1', 2, 'i'))), - 0xe7: ('v_cmp_t_u64', (('VCC', -1, 'i'), ('SRC0', 2, 'i'), ('VSRC1', 2, 'i'))), - 0xe8: ('v_cmp_u_f16', (('VCC', -1, 'i'), ('SRC0', 1, 'f16'), ('VSRC1', 1, 'f16'))), - 0xe9: ('v_cmp_nge_f16', (('VCC', -1, 'i'), ('SRC0', 1, 'f16'), ('VSRC1', 1, 'f16'))), - 0xea: ('v_cmp_nlg_f16', (('VCC', -1, 'i'), ('SRC0', 1, 'f16'), ('VSRC1', 1, 'f16'))), - 0xeb: ('v_cmp_ngt_f16', (('VCC', -1, 'i'), ('SRC0', 1, 'f16'), ('VSRC1', 1, 'f16'))), - 0xec: ('v_cmp_nle_f16', (('VCC', -1, 'i'), ('SRC0', 1, 'f16'), ('VSRC1', 1, 'f16'))), - 0xed: ('v_cmp_neq_f16', (('VCC', -1, 'i'), ('SRC0', 1, 'f16'), ('VSRC1', 1, 'f16'))), - 0xee: ('v_cmp_nlt_f16', (('VCC', -1, 'i'), ('SRC0', 1, 'f16'), ('VSRC1', 1, 'f16'))), - 0xef: ('v_cmp_tru_f16', (('VCC', -1, 'i'), ('SRC0', 1, 'f16'), ('VSRC1', 1, 'f16'))), - 0xf0: ('v_cmpx_f_u64', (('OPR_EXEC', -1, 'i'), ('SRC0', 2, 'i'), ('VSRC1', 2, 'i'))), - 0xf1: ('v_cmpx_lt_u64', (('OPR_EXEC', -1, 'i'), ('SRC0', 2, 'i'), ('VSRC1', 2, 'i'))), - 0xf2: ('v_cmpx_eq_u64', (('OPR_EXEC', -1, 'i'), ('SRC0', 2, 'i'), ('VSRC1', 2, 'i'))), - 0xf3: ('v_cmpx_le_u64', (('OPR_EXEC', -1, 'i'), ('SRC0', 2, 'i'), ('VSRC1', 2, 'i'))), - 0xf4: ('v_cmpx_gt_u64', (('OPR_EXEC', -1, 'i'), ('SRC0', 2, 'i'), ('VSRC1', 2, 'i'))), - 0xf5: ('v_cmpx_ne_u64', (('OPR_EXEC', -1, 'i'), ('SRC0', 2, 'i'), ('VSRC1', 2, 'i'))), - 0xf6: ('v_cmpx_ge_u64', (('OPR_EXEC', -1, 'i'), ('SRC0', 2, 'i'), ('VSRC1', 2, 'i'))), - 0xf7: ('v_cmpx_t_u64', (('OPR_EXEC', -1, 'i'), ('SRC0', 2, 'i'), ('VSRC1', 2, 'i'))), - 0xf8: ('v_cmpx_u_f16', (('OPR_EXEC', -1, 'i'), ('SRC0', 1, 'f16'), ('VSRC1', 1, 'f16'))), - 0xf9: ('v_cmpx_nge_f16', (('OPR_EXEC', -1, 'i'), ('SRC0', 1, 'f16'), ('VSRC1', 1, 'f16'))), - 0xfa: ('v_cmpx_nlg_f16', (('OPR_EXEC', -1, 'i'), ('SRC0', 1, 'f16'), ('VSRC1', 1, 'f16'))), - 0xfb: ('v_cmpx_ngt_f16', (('OPR_EXEC', -1, 'i'), ('SRC0', 1, 'f16'), ('VSRC1', 1, 'f16'))), - 0xfc: ('v_cmpx_nle_f16', (('OPR_EXEC', -1, 'i'), ('SRC0', 1, 'f16'), ('VSRC1', 1, 'f16'))), - 0xfd: ('v_cmpx_neq_f16', (('OPR_EXEC', -1, 'i'), ('SRC0', 1, 'f16'), ('VSRC1', 1, 'f16'))), - 0xfe: ('v_cmpx_nlt_f16', (('OPR_EXEC', -1, 'i'), ('SRC0', 1, 'f16'), ('VSRC1', 1, 'f16'))), - 0xff: ('v_cmpx_tru_f16', (('OPR_EXEC', -1, 'i'), ('SRC0', 1, 'f16'), ('VSRC1', 1, 'f16'))), -} - diff --git a/tools/rdna2spirv.py b/tools/rdna2spirv.py deleted file mode 100644 index 18c502377..000000000 --- a/tools/rdna2spirv.py +++ /dev/null @@ -1,19177 +0,0 @@ -"""RDNA2 (gfx10) shader -> SPIR-V assembly. - -Model: one SPIR-V invocation runs one lane. VGPRs and SGPRs are Function-scope uint arrays; float ops bitcast, -so register contents keep exact bit patterns. EXEC is a per-invocation active flag, and a lane mask keeps only this -lane's bit; the few instructions that read a whole mask (s_bcnt1, s_ff1, v_mbcnt, ...) collect the other lanes with -subgroup operations (lane_masks.py, and wave64_halves.py for wave64). Control flow is structured by -cfg_structure.py, with a loop around a switch where it can't be (or for every shader with --dispatch-loop). - -Anything not modelled raises Unsupported and is reported, never guessed. The contract table in docs/design.md -("Translator status and runtime contract") lists what each instruction family does and how it was confirmed. -Vertex inputs: v0 = VertexIndex - BaseVertex and v3 = InstanceIndex - BaseInstance (the hardware's ids are zero-based). - -Usage (needs spirv-val on PATH, from the Vulkan SDK or spirv-tools; spirv-as too unless --assembler python): - python3 -I rdna2spirv.py --out DIR [--limit N] [--shard i/n] -Writes .spvasm for each translated shader and .spv only for validated modules. -Prints coverage and validation results. -""" -import argparse -import bisect -import hashlib -import os -import re -import struct -import subprocess -import sys -import tempfile -import time -import zlib -from collections import Counter, defaultdict -from pathlib import Path - -sys.path.insert(0, os.path.dirname(__file__)) -from report_paths import path_key, same_report_path # noqa: E402 -from shader_ir import HDR, parse_file # noqa: E402 -from replace_retry import replace as replace_retry # noqa: E402 -import cfg_structure # noqa: E402 -import fssm_header # noqa: E402 -import fssm_unpack # noqa: E402 -import lane_masks # noqa: E402 -import shader_meta as _shader_meta # noqa: E402 -import wave64_emulate_opt # noqa: E402 -import wave64_halves # noqa: E402 - -STRUCTURED = True # False (--dispatch-loop): every shader with branches as one loop around a switch -# Deeper structured trees are emitted in the flat dispatch-loop form instead (--max-structured-depth, 0 = never). -# `spirv-val`'s selection/loop checking cost grows with the nesting depth, and before cfg_structure hoisted tails -# (#1904) the 1.0.2.1 corpus nested up to 118 deep, where the flat form validates 2.3x (depth 50-64) to 10x (118) -# faster (SHADER-299). Since #1904 the corpus's deepest tree is 29 and the flat form saves only 12% of `spirv-val` -# time on the modules deeper than 16, while NVIDIA compiles it 1.7-2x slower (SHADER-427). The bound sits above -# the corpus, as a guard for depths where validation really grows. Both forms are equivalent; only the routing -# differs. docs/design.md "Control flow" has the numbers. -MAX_STRUCTURED_DEPTH = 64 -WAVE64_EMULATE = False # --wave64-emulate: wave64 compute/mesh shaders exact on any subgroup size (Gen.x_round) -# --max-shared-memory: a cap on a compute shader's Workgroup variables, LDS plus %x_buf (SHADER-309, #1721). The -# default is the hard cap: 64 KiB, RDNA2's LDS per workgroup and the largest maxComputeSharedMemorySize drivers -# report (RADV, NVIDIA). It is not the device limit: the AMD Windows (RDNA4) and Intel drivers report 32768, the -# Vulkan minimum is 16384. The translator runs offline, so it records the exact total as lds_bytes in index.json and -# the runtime compares that with the device's limit before it creates the pipeline. spirv-val checks neither. -MAX_SHARED_BYTES = 65536 -WAVE64_GRAPHICS = "warn" # --wave64-graphics: tier C wave64 VS/PS/GS (not exact on 32-wide subgroups): warn | error | off -W64G_COUNTS = Counter() # tiers of the wave64 VS/PS/GS translated so far, for the summary line -# --bary-fallback: raw barycentric reads come from an ordinary perspective-interpolated vec3 input (the location is -# in the metadata as "bary_fallback_input") instead of BuiltIn BaryCoordKHR, for devices without -# VK_KHR_fragment_shader_barycentric. Whatever feeds the stage before the PS (a pass-through geometry shader) writes -# (1,0,0), (0,1,0), (0,0,1) at the triangle's three vertices; interpolating those gives the perspective-correct -# barycentrics, so .y/.z are AMD's i/j as with BaryCoordKHR. -BARY_FALLBACK = False -SHADER_CLOCK = False -FMA_KHR = False # --fma khr: fused multiply-adds are OpFmaKHR (SPV_KHR_fma, VK_KHR_shader_fma), not GLSL Fma -FMA_EXACT = False # --fma exact: fused multiply-adds are emulated from single-rounded f32 ops (Gen.fma_exact) -# --texel-offset-fallback: image_sample*_o without VK_KHR_maintenance8. The run-time texel offset is folded into the -# coordinate (coordinate + offset / size of the sampled mip level) instead of the SPIR-V Offset operand, which needs -# maintenance8 outside gather. Implicit-LOD samples become Grad samples with the derivatives of the original -# coordinate, so a per-pixel offset doesn't change the LOD. Gathers keep their Offset (shaderImageGatherExtended). -TEXEL_OFFSET_FALLBACK = False -FLOAT_CONTROLS = True # False (--no-float-controls): no SignedZeroInfNanPreserve, for drivers without the property -# --mesh-compute: mesh shaders become compute shaders (same workgroup size and code) for devices without -# VK_EXT_mesh_shader. Instead of SetMeshOutputs and the mesh outputs, the epilogue writes the vertex and primitive -# counts, each lane's vertex and each lane's primitive into this workgroup's slot of a buffer whose device address is -# in push-constant dwords 36..37 (the block grows from 144 to 152 bytes). The slot layout is mesh_compute_layout(); -# the index records it as "mesh_compute". tools/mesh_compute_vs.py writes the vertex shader that draws the slots. -MESH_COMPUTE = False -# --pc-tail-ubo: for devices with 128 bytes of push constants, Vulkan's minimum (AMD's Windows driver on RDNA2 iGPUs, -# some Intel Arc drivers; D3D-14's push_constants_need_fallback). The push-constant block keeps s0..s31 (128 bytes). -# The tail that follows them by default (dwords 32..35: heap base, code base; 36..37: the --mesh-compute output -# address) moves, in the same order and at the same relative offsets, to a uniform block at set PC_TAIL_SET, binding -# PC_TAIL_BINDING. It is declared only when the shader reads it; the index records it as "pc_tail", and -# "push_constant_bytes" is 128. Set 1 is unused otherwise, so set 0's update-after-bind table is unchanged. -PC_TAIL_UBO = False -PC_TAIL_SET, PC_TAIL_BINDING = 1, 0 -# --f16-interp-fallback: *_f16 interps without PerVertexKHR, for devices that have VK_KHR_fragment_shader_barycentric -# but can't use its per-vertex inputs (MoltenVK: SPIRV-Cross has no MSL form of PerVertexKHR). Every VS and mesh -# `exp paramN` also exports the channel's two f16 halves decoded to f32, low halves at f16_half_location(N, 0) and high -# halves at f16_half_location(N, 1), and a PS *_f16 read of attrN.c takes component c of that smooth input. The -# interpolation is linear, so this is the same P0 + i(P1 - P0) + j(P2 - P0) of the decoded halves, rounded by the -# device's interpolator instead of by explicit arithmetic. The halves count down from location F16_HALF_TOP (param 0's -# high halves, its low halves one below), so a producer with params 0..P-1 has room for the halves of params -# 0..(28 - P) / 2; Gen.export skips the ones that would land on its own params. The top is 29, not 30 (SHADER-291): -# MoltenVK's maxVertexOutputComponents is 124 because Metal counts gl_Position in its 128 vertex-output scalars, and -# the validation layer counts it too (VUID-RuntimeSpirv-Location-06272), so (29 + 1) * 4 + 4 = 124 is the most a VS -# can use there. -F16_HALVES = False -F16_HALF_TOP = 29 -OPT_SPIRV = False # --opt: run tools/spirv_opt.py basic-block peephole pass on emitted SPIR-V (#884) - - -# The heap base as one %ulong, in the entry block of %main: the push constants don't change during the invocation, and -# the entry block dominates every use. Gen.host_addr adds an address to it. -HEAP_BASE_ENTRY = ["%heap_base_lo = OpLoad %uint %ud_base_lo_p", - "%heap_base_hi = OpLoad %uint %ud_base_hi_p", - "%heap_base_lo64 = OpUConvert %ulong %heap_base_lo", - "%heap_base_hi64 = OpUConvert %ulong %heap_base_hi", - "%heap_base_hi_sh = OpShiftLeftLogical %ulong %heap_base_hi64 %c64_32", - "%heap_base = OpBitwiseOr %ulong %heap_base_hi_sh %heap_base_lo64"] - - -def pc_tail_chain(name, member, c): - """`name` = pointer to push-constant tail member `member`, numbered as in %UserData (1-2 heap base, 3-4 code base, - 5-6 --mesh-compute output address): a member of the push-constant block by default, member - 1 of the uniform - block %pc_tail with --pc-tail-ubo. `c` maps an integer to its constant's id.""" - if PC_TAIL_UBO: - return f"{name} = OpAccessChain %_ptr_Uniform_uint_tail %pc_tail {c(member - 1)}" - return f"{name} = OpAccessChain %_ptr_PC_uint %user_data {c(member)}" - - -def f16_half_location(n, half): - """--f16-interp-fallback: the canonical location of param n's decoded low (half 0) or high (half 1) f16 halves.""" - return F16_HALF_TOP - 2 * n - 1 + half - - -def assign_f16_half_locations(f16_attrs, raw_locs, top=F16_HALF_TOP): - """--f16-interp-fallback: map each attribute in `f16_attrs` to `(low_loc, high_loc)` in `0..top` (SHADER-378). - - Keeps the canonical `28 - 2n` / `29 - 2n` slots whenever every pair fits in `0..top` without colliding with - `raw_locs` (preserving byte-identical output for non-colliding shaders). Otherwise packs all pairs downward from - `top` into free locations disjoint from `raw_locs`, raising `Unsupported` only when `0..top` has fewer than - `2 * len(f16_attrs)` free locations left. - """ - attrs = sorted(f16_attrs) - if not attrs: - return {} - raw = set(raw_locs) - fixed = {n: (f16_half_location(n, 0), f16_half_location(n, 1)) for n in attrs} - if all(0 <= lo and hi <= top and lo not in raw and hi not in raw for lo, hi in fixed.values()): - return fixed - free = [loc for loc in range(top, -1, -1) if loc not in raw] - need = 2 * len(attrs) - if len(free) < need: - raise Unsupported( - f"--f16-interp-fallback: need {need} decoded-half locations, only {len(free)} free in 0..{top}" - ) - return {n: (free[2 * k + 1], free[2 * k]) for k, n in enumerate(attrs)} - - -def mesh_compute_layout(maxv, maxp, clip_count, cull_count, params): - """Byte layout of one workgroup's slot in the --mesh-compute output buffer. Everything is 16-byte aligned: - header (vertex count, primitive count, 2 unused dwords), then maxv vertices of `vertex_stride` bytes - (position xyzw; the clip distances, then the cull distances, each padded to whole vec4s; one vec4 per param - location in ascending order), then maxp primitives of 16 bytes (three vertex indices, then 1 if culled).""" - clip_vec4 = -(-clip_count // 4) - cull_vec4 = -(-cull_count // 4) - params = sorted(params) - stride = 16 * (1 + clip_vec4 + cull_vec4 + len(params)) - vertices = 16 - primitives = vertices + maxv * stride - lay = {"slot_bytes": primitives + maxp * 16, "vertices": vertices, "vertex_stride": stride, - "primitives": primitives, "primitive_stride": 16, "max_vertices": maxv, "max_primitives": maxp, - "clip_count": clip_count, "clip_offset": 16, "cull_count": cull_count, - "cull_offset": 16 * (1 + clip_vec4), - "params": {n: 16 * (1 + clip_vec4 + cull_vec4 + k) for k, n in enumerate(params)}, - "push_constant_bytes": 4 * USER_SGPRS + 24, "address_dwords": [USER_SGPRS + 4, USER_SGPRS + 5]} - if PC_TAIL_UBO: # the address is dwords 4..5 of the --pc-tail-ubo block, not a push constant - lay.update(push_constant_bytes=4 * USER_SGPRS, address_dwords=None, pc_tail_address_dwords=[4, 5]) - return lay - -# GFX10 buffer format codes (Mesa src/amd/registers/gfx10-rsrc.json, enum GFX10_FORMAT). -import json as _json # noqa: E402 -with open(os.path.join(os.path.dirname(__file__), "gfx10_formats.json"), encoding="utf-8") as _f: - GFX10_FORMATS = {int(k): v for k, v in _json.load(_f).items()} -# Measured natively on RDNA2 (gfx1036, all 128 7-bit V# FORMAT codes): MUBUF DST_SEL=1 produces 1.0 (0x3F800000 / d16 -# 0x3C00) iff FORMAT[6:0] is a valid float/normalized/scaled code (1..77 ending in _UNORM/_SNORM/_USCALED/_SSCALED/ -# _FLOAT), and integer 1 (0x00000001 / d16 0x0001) for UINT/SINT, INVALID (0), and reserved codes (78..127). -_FLOAT_FMT_MASKS = tuple( - sum( - 1 << (code - 32 * grp) - for code in range(32 * grp, 32 * grp + 32) - if GFX10_FORMATS.get(code, "").endswith(("_UNORM", "_SNORM", "_USCALED", "_SSCALED", "_FLOAT")) - ) - for grp in range(3) -) - -# User SGPRs s0..s(USER_SGPRS-1) are initialised from push constants (128 bytes = Vulkan's guaranteed minimum). -USER_SGPRS = 32 - -# v_pipeflush (GFX10 VOP1) only flushes the VALU pipeline: no register, memory or EXEC effect to translate. -# s_icache_inv invalidates the instruction cache; s_ttracedata / s_ttracedata_imm send thread-trace data; -# s_code_end pads the end of a code object; s_version records the ISA version. None of them has a register, memory, -# SCC or EXEC effect. (Data-cache invalidations such as buffer_gl0_inv are about cross-wave coherence and are not -# here.) ds_nop is the DS unit's no-operation (no address, data or result). v_clrexcp clears the exception bits of -# TRAPSTS, which nothing translated reads (s_getreg_b32 is unsupported and there are no traps). -# s_atc_probe / s_atc_probe_buffer probe (prefetch) an address in the address translation cache: no data comes back -# and nothing is written (RDNA2 ISA, SMEM). s_incperflevel / s_decperflevel step a performance counter and s_wakeup -# pings the other waves of the threadgroup out of an s_sleep (itself a no-op here): neither touches a register, -# memory, SCC, VCC or EXEC (RDNA2 ISA, SOPP). -NOOPS = {"s_sleep", "v_nop", "v_pipeflush", "s_nop", "s_inst_prefetch", "s_endpgm", "s_setprio", "s_clause", - "s_delay_alu", "s_waitcnt", "s_waitcnt_vscnt", "s_waitcnt_vmcnt", "s_waitcnt_expcnt", "s_waitcnt_lgkmcnt", - "s_waitcnt_depctr", "s_icache_inv", "s_ttracedata", "s_ttracedata_imm", "s_code_end", "s_version", - "ds_nop", "v_clrexcp", "s_atc_probe", "s_atc_probe_buffer", "s_incperflevel", "s_decperflevel", "s_wakeup"} - -F2 = {"v_add_f32": "OpFAdd", "v_sub_f32": "OpFSub", "v_mul_f32": "OpFMul", - "v_max_f32": "max", "v_min_f32": "min"} -U2 = {"v_add_nc_u32": "OpIAdd", "v_sub_nc_u32": "OpISub", "v_and_b32": "OpBitwiseAnd", "v_or_b32": "OpBitwiseOr", - "v_xor_b32": "OpBitwiseXor", "v_mul_u32_u24": "mul24"} -SHIFT_REV = {"v_lshlrev_b32": "OpShiftLeftLogical", "v_lshrrev_b32": "OpShiftRightLogical", - "v_ashrrev_i32": "OpShiftRightArithmetic"} -F1 = {"v_rcp_f32": "rcp", "v_rsq_f32": "InverseSqrt", "v_sqrt_f32": "Sqrt", "v_exp_f32": "Exp2", - "v_log_f32": "Log2", "v_floor_f32": "Floor", "v_fract_f32": "Fract", "v_ceil_f32": "Ceil", - "v_trunc_f32": "Trunc"} -S2 = {"s_and_b32": "OpBitwiseAnd", "s_or_b32": "OpBitwiseOr", - "s_lshl_b32": "OpShiftLeftLogical", "s_lshr_b32": "OpShiftRightLogical", "s_mul_i32": "OpIMul"} - -# RDNA2 ISA SOPC scalar compare (14 ops) and bit-test (4 ops) exact mnemonic sets (tools/rdna2_isa_tables.py SOPC). -SOPC_CMP32_OPS = frozenset({ - "s_cmp_eq_i32", "s_cmp_lg_i32", "s_cmp_gt_i32", "s_cmp_ge_i32", "s_cmp_lt_i32", "s_cmp_le_i32", - "s_cmp_eq_u32", "s_cmp_lg_u32", "s_cmp_gt_u32", "s_cmp_ge_u32", "s_cmp_lt_u32", "s_cmp_le_u32", -}) -SOPC_CMP64_OPS = frozenset({"s_cmp_eq_u64", "s_cmp_lg_u64"}) -SOPC_BITCMP_OPS = frozenset({"s_bitcmp0_b32", "s_bitcmp1_b32", "s_bitcmp0_b64", "s_bitcmp1_b64"}) -SOPC_SRC32_SPECIALS = frozenset({ - "null", "m0", "vcc_lo", "vcc_hi", "exec_lo", "exec_hi", - "scc", "src_scc", "src_pops_exiting_wave_id", -}) -SOPC_SRC64_SPECIALS = frozenset({"vcc", "exec", "null"}) - -# Runs of lane-local VALU instructions share one `if (active)` instead of an OpSelect per VGPR write (Gen.insns). -# VALU ops that are not lane-local: they read other lanes, write a lane mask, SCC or EXEC, or write a carry or -# other scalar result in every lane (v_add_co_u32's mask goes to inactive lanes too). -NOT_LANE_LOCAL = ("v_cmp", "v_readlane", "v_readfirstlane", "v_writelane", "v_permlane", "v_mbcnt", "v_interp", - "v_div_scale", "v_mad_u64_u32", "v_mad_i64_i32") -DPP_MODS = ("quad_perm", "row_", "wave_", "dpp8", "bank_mask", "bound_ctrl", "fi:") -# A single lane-local instruction keeps its select: on an RX 5700 XT wrapping it bought nothing measurable -# (64 divergent if/else of 1-4 ops: within 1%), and it adds labels. Long runs are where the time goes. -MIN_ACTIVE_RUN = 2 - - -def base_op(op): - for suf in ("_e32", "_e64", "_sdwa", "_dpp"): - if op.endswith(suf): - return op[: -len(suf)] - return op - - -class Unsupported(Exception): - pass - - -class Gen: - def __init__(self, stage, hoist_reg_ptrs=False, cache_active=False): - self.stage = stage - self.hoist_reg_ptrs = hoist_reg_ptrs - self.reg_ptrs = {} - self.cache_active = cache_active - self.exec_static_true = False - self._active_ssa = None - self.body = [] - self.consts = {} - # tof/tou results -> the id they were bitcast from. A bitcast of a bitcast gives the original id back: wherever - # the key is valid its source is too (the key's own definition uses it), so no dominance is lost. - self.bitcast_from = {} - self.n = 0 - self.outputs = {} - self.partial_color_outputs: set[str] = set() - self.inputs = {} - self.interpolated = set() # inputs read through v_interp_p1/p2; the rest are flat (v_interp_mov only) - self.per_vertex = set() # PS: attribute numbers read by a *_f16 interp: PerVertexKHR, decoded per half - self.f16_halves = set() # PS, --f16-interp-fallback: the same attributes, read from decoded-half inputs - self.f16_half_locs = {} # PS/VS/MS, --f16-interp-fallback: attr/param n -> (low_loc, high_loc) - self.param_max = -1 # VS/MS: the highest exp paramN (--f16-interp-fallback keeps halves above it) - self.f16_half_outs = {} # VS/MS, --f16-interp-fallback: param n -> its two decoded-half output names - self.ij_capture = {} # computed-I/J pairs: pair key -> the I float id the p1 loaded (SHADER-177) - self.uses_psb = False - self.uses_active = False - self.vm_latch = False # PS: EXEC can change after a `vm` or color export, so EXEC at those is kept - self.col_latched = [] # PS with vm_latch: the color targets (mrtN) whose export EXEC is kept - self.uses_perm = False # emulate: ds_permute_b32 parks its winning source lane in %x_perm - self.uses_tex = False - self.uses_dynamic_sampled_index = False - self.uses_dynamic_storage_index = False - self.uses_subgroup = False - self.uses_tex_array = False - self.uses_storage = False - self.uses_query = False - self.uses_tex_1d = False - self.uses_tex_3d = False - self.uses_v4uint = False - self.uses_store_views = set() # image_store dims used (index into STORE_DIMS) - self.uses_int_sampler = False # 2D typed sampled-image types for sampling and gathering - self.uses_int_fetch = set() # typed image_load dims (index into STORE_DIMS): uint/sint sampled aliases - self.uses_d16_image = False # a d16 image result is narrowed: needs the normalized / 32-bit-float tables - self.uses_fmt_size = False # %fmt_size_tab: byte size of each 7-bit buffer FORMAT code (0 = not in FORMATS) - self.reads_store_views = False # a coherent image_load reads a storage view (StorageImageReadWithoutFormat) - self.coherent_images = False # a glc image_load/image_store: the storage views are decorated Coherent - self.writes_depth = False - self.uses_smul = False - self.uses_minlod = False - self.uses_img_offset = False - self.uses_pops = False - self.round_mode = False # the program writes MODE.FP_ROUND[3:2] (f16/f64 rounding): kept in %mode_r16 - self.uses_fhalf = False # %fhalf_g (0.5) constant - self.uses_f64 = False - self.uses_fma_khr = False # an OpFmaKHR was emitted: capability FMAKHR + extension SPV_KHR_fma - self.uses_fma_khr32 = False # ... on f32 (feature shaderFmaFloat32) - self.uses_fma_khr64 = False # ... on f64 (feature shaderFmaFloat64) - # The --fma option this module is translated under, for the index: a caller that changes the option before - # shader_meta (translation and indexing in separate steps) must not relabel it. - self.fma_mode = "exact" if FMA_EXACT else "khr" if FMA_KHR else "glsl" - self.uses_clock = set() - self.uses_bvh = False - self.lconsts = {} # 64-bit constants: value -> id - self.uses_vote = False # wave-uniform branches (OpGroupNonUniformAny) - self.uses_ballot = False # wave mask ballot (OpGroupNonUniformBallot) - self.uses_bcast_first = False # OpGroupNonUniformBroadcastFirst (desc_lookup): Ballot capability only - self.uses_wave_bits = False # a whole lane mask gathered from the wave (OpGroupNonUniformBitwiseOr) - self.uses_quad = False # s_wqm on a lane mask (OpGroupNonUniformQuadSwap) - self.lane_masks = {} # id(instruction) -> registers holding a lane mask there (lane_masks.py) - self.ever_mask = set() # SGPRs that held a lane mask anywhere in the shader (conservative) - self.cur_masks = {} - self.cur_ins = None - self.mask_writes = set() # id(instruction) of the ones that write a lane mask to a VGPR - self.write_all_lanes = False - self.dpp_guard = None # per-lane bool: a DPP instruction's row/bank/valid write mask - self.active_run = False # inside insns' `if (active)` around a run of lane-local VALU instructions - self.exec_changes = False # some instruction may write EXEC (may_write_exec): only then are runs worth it - self.parked = {} # (vgpr, lane) a mask is parked in -> the spare SGPR slot that keeps it per lane - self.uses_lds = False - self.lds_dwords = 16384 # CS: set from RSRC2 LDS_SIZE (power of two, covers every offset used) - self.lds_need = 0 # CS: dwords the program needs (LDS_SIZE, largest constant offset) - self.lds_declared = 0 # CS: dwords RSRC2 LDS_SIZE allocates (the hardware allocation, unclipped) - self.lds_bound = None # CS: bounds-checked LDS (dwords): out of range reads 0, writes are dropped - self.cs = None # CS: user SGPR count, enabled workgroup ids, thread-id VGPR count, group size - self.ms = None # MS: {"maxv", "maxp", "threads"} from PSV0 - self.ms_params = set() # MS: param export indices used - self.ms_alloc = False # MS: s_sendmsg GS_ALLOC_REQ seen - self.pos_map = {} # VS/MS: pos index (1..3) -> {comp: ("clip"|"cull", idx)} from OSG1 - self.mrt_targets = [] # PS: the declared SV_Target indices in order (OSG1); export k goes to the k-th - self.pos_misc = set() # VS: misc system values in pos1 (4=Layer, 5=ViewportIndex) from OSG1 - self.clip_count = 0 # ClipDistance array length (1..8) - self.cull_count = 0 # CullDistance array length (1..8) - self.uses_clip = False # True once a pos1+ export writes a ClipDistance slot - self.uses_cull = False # True once a pos1+ export writes a CullDistance slot - self.uses_layer = False # VS: True once pos1 misc writes BuiltIn Layer - self.uses_viewport = False # VS: True once pos1 misc writes BuiltIn ViewportIndex - self.gs = None # GS: {"in": [(reg, sv)], "out": [(reg, sv)], "nreg": n, "maxv": n} - self.wave64 = False # compiled for 64-lane waves (64-bit EXEC writes, exec_hi, v_mbcnt_hi, ...) - self.cur_uniform_readlane = False - self.w64g = None # wave64 VS/PS/GS: wave64_halves.analyse() result (tier, reasons, rewrite sites) - self.w64_scalar_spills = set() # (vgpr, lane) pure scalar spill slots lowered to self.parked (SHADER-10) - self.emulate = False # --wave64-emulate: exact wave64 on any subgroup size (cs/ms; see x_round) - self.emulate_inline = False # emulate: current block emits direct inline barriers (no x_split) - self.emulate_plan = None # emulate: structured plan from wave64_emulate_opt.plan_structured_emulation - self.mini_segs = defaultdict(list) # emulate_plan: mini_idx -> continuation segment ids - self.tail_segs = [] # emulate_plan: continuation segment ids belonging to tail_scheduler - self.x_seg = 0 # emulate: number of the next continuation segment (past the block numbers) - self.x_marks = [] # emulate: (index into body, segment) where a segment of the current block ends - self.x_segs = {} # emulate: continuation segment -> its SPIR-V lines - self.x_spills = [] # emulate: (Function variable, pointer type) carrying a value across a round - self.eager_vars = [] # (Function variable, pointer type) a subgroup op's result is stored to (see eager) - self.x_ptr_types = {} # emulate: value type -> Function pointer type declared for spills - self.x_dirty = set() # emulate: (memory kind "lds"/"mem", "r"/"w") accessed since the last round - self.x_tok = {} # emulate: register -> the SSA id last stored to it in this block (its value's identity) - self.x_gen = 0 # emulate: bumped at every label (control flow inside a block): forgets x_tok - self.x_mcache = {} # emulate: wave_mask key -> (lo, hi) already exchanged in this block - self.lane_either = {} # id(instruction) -> SGPRs holding constant 0/-1 (EITHER) there - self.cur_either = () - self.x_lanes = 64 # emulate: workgroup invocations rounded up to whole waves - self.scc_live = None # emulate: set of id(ins) whose SCC write is live-out (wave64_emulate_opt) - self.cur_scc_live = True # emulate: whether the current instruction's SCC result is live-out - self.bar_rounds = False # native wave32 cs with an s_barrier outside uniform control flow (bar_scheduler) - self.uses_storage3d = False - self.uses_heap = False - self.uses_codebase = False - self.uses_pc_tail = False # --pc-tail-ubo and the shader reads the tail (set in assemble) - self.uses_long = False - self.vertex_inputs = [] # (D3D input register, component type 1=uint 2=sint 3=float) for fetch-calling VS - self.vertex_signature = [] # full ISG1: (register, mask, system value, component type) for PSO lookup - self.dynamic_format = False # True when a buffer_load used a runtime V# FORMAT (unknown codes -> 0 at runtime) - self.fixed_format_codes = set() # static tbuffer/fixed format codes seen (validated against FORMATS) - self.frag_inputs = {} # PS: VGPR -> gl_FragCoord component, from the verified system-VGPR layout - self.pixel_interpolants = None # PS: (count, fp16_mask) from the FSSM pixel-input table; None = no table - self.v_interp_copy = {} # PS: vgpr -> (root barycentric register v0/v1, program-order index of its - # single defining plain v_mov of it); valid I/J sources (SHADER-177) - self.blocks = [] # per basic block: list of SPIR-V lines (dispatch-loop form), empty = straight-line - self.succ = [] # per basic block: the blocks it can go to next (none = the program ends there) - self.desc_fn = None # lines of the descriptor-lookup function, once an instruction needs it - self.tbuffer_norm_fns: dict[int, list[str]] = {} # one exact quotient per used magnitude width - self.fmt_fn = None # lines of the typed-buffer format-decode function, once a dynamic-format load needs it - self.fmt_norm_fn = None # lines of the shared exact norm quotient for a run-time width (SHADER-849) - self.fmt_enc_fn = None # lines of the format-encode and element-size functions, once a typed store needs them - self.uses_fmt_tables = False # %fmt_desc_tab / %fmt_norm_rep_tab: a format's kind and channel widths - self.x_round_fns: dict[str, list[str]] = {} # emulate_inline: helper functions for x_round pre-barrier setup - self.x_round_fn_types: dict[int, str] = {} # emulate_inline: arity -> OpTypeFunction id for x_round_fns - self.sgpr_imm = {} # SGPR -> literal an s_mov_b32 put there earlier in this basic block (see gather_addr_modes) - self.desc_cache = {} # (first SGPR, dwords) -> id of the %desc_lookup_fn result in the current basic block - self._scan = (None, 0, []) # (body list, lines already seen, open merge labels): see desc_cache_ok - self.block_label = "%entry" # label of the SPIR-V block the current instruction starts in - self.build_meta = {} # runtime build metadata from tools/shader_meta.py - - def tmp(self): - self.n += 1 - return f"%t{self.n}" - - def cu(self, v): - v &= 0xFFFFFFFF - if v not in self.consts: - self.consts[v] = f"%c{v:x}" - return self.consts[v] - - def emit(self, s): - self.body.append(" " + s) - if s.startswith("OpStore %active "): - if self.exec_static_true: - raise RuntimeError(f"OpStore %active emitted with exec_static_true: {s}") - self._active_ssa = s.split()[2] - elif s.endswith("= OpLabel"): - self._active_ssa = None - if self.emulate: - if s.startswith(("OpStore %vcc ", "OpStore %active ")): - reg, val = s.split()[1:3] - self.x_tok[reg] = val - elif s.endswith("= OpLabel"): - self.x_gen += 1 - - # ---- register access ---- - def reg_ptr(self, kind, r): - """Return a pointer to element `r` of `%vgpr` or `%sgpr`. - - When `hoist_reg_ptrs` is enabled (the default for `translate()`), emit one - `OpAccessChain` per distinct register in `%entry` (in `assemble()`) instead of - repeating it at every load/store; direct `Gen()` callers keep inline chains.""" - arr = "%vgpr" if kind == "vgpr" else "%sgpr" - if self.hoist_reg_ptrs: - key = (kind, r) - p = self.reg_ptrs.get(key) - if p is None: - self.cu(r) - p = f"%reg_{'v' if kind == 'vgpr' else 's'}{r}" - self.reg_ptrs[key] = p - return p - p = self.tmp() - self.emit(f"{p} = OpAccessChain %_ptr_Function_uint {arr} {self.cu(r)}") - return p - - def load_reg(self, kind, r): - p = self.reg_ptr(kind, r) - t = self.tmp() - self.emit(f"{t} = OpLoad %uint {p}") - return t - - def store_reg(self, kind, r, val): - if kind == "sgpr": - self.sgpr_imm.pop(r, None) - self.x_tok[("sgpr", r)] = val - if self.desc_cache: # every write to the %sgpr array comes through here (see desc_lookup_sgpr) - self.desc_cache = {k: v for k, v in self.desc_cache.items() if not (k[0] <= r < k[0] + k[1])} - p = self.reg_ptr(kind, r) - self.emit(f"OpStore {p} {val}") - - def imm_val(self, a): - """Integer literal value if 'a' is an immediate or known SGPR constant, else None.""" - if a.get("abs") or a.get("neg"): - return None - k = a.get("k") - if k == "imm": - return a["v"] & 0xFFFFFFFF - if k == "sgpr" and a.get("n", 1) == 1 and a.get("r") in self.sgpr_imm: - return self.sgpr_imm[a["r"]] & 0xFFFFFFFF - if k == "special" and a.get("t") == "null": - return 0 - return None - - def src_u(self, a): - k = a["k"] - if k in ("vgpr", "sgpr"): - if a.get("n", 1) != 1: - raise Unsupported("64-bit operand") - v = self.load_reg(k, a["r"]) - elif k == "special" and a["t"] == "null": - v = self.cu(0) # RDNA 'null' source reads as zero (e.g. soffset) - elif k == "special" and a["t"] in ("exec_lo", "exec", "exec_hi"): - v = self.exec_value() - elif k == "special" and a["t"] == "m0": - v = self.tmp() - self.emit(f"{v} = OpLoad %uint %m0") - elif k == "special" and a["t"] == "vcc_hi": - # wave64: vcc_hi is the upper half of VCC when VCC holds a lane mask (each lane's bit lives in %vcc). - # wave32 (or plain data): vcc_hi is an ordinary SGPR. - v = self.tmp() - self.emit(f"{v} = OpLoad %uint {'%vcc' if (self.wave64 and 'vcc' in self.cur_masks) else '%vcc_hi'}") - elif k == "special" and a["t"] in ("scc", "src_scc"): - v = self.tmp() - self.emit(f"{v} = OpLoad %uint %scc") - elif k == "special" and a["t"] == "src_pops_exiting_wave_id": - # POPS (primitive-ordered pixel shading): the hardware wait loop compares this against the - # collision word. Ordering comes from fragment-shader interlock around the whole shader instead - # (see assemble), so the id reads as 0 and the runtime puts 0 (no collision) in the collision SGPR. - v = self.cu(0) - self.uses_pops = True - elif k == "imm": - v = self.cu(a["v"]) - elif k == "fimm": - v = self.cu(struct.unpack(" (source selects, dst bit). - A select bit of 1 reads the high half of that source; the last bit sends the result to the high half. - No modifier means all zeros.""" - sel = next((m for m in mods if m.startswith("op_sel:")), None) - if sel is None: - return [0] * nsrc, 0 - bits = [int(x) for x in sel.split("[")[1].rstrip("]").split(",")] + [0] * (nsrc + 1) - return bits[:nsrc], bits[nsrc] - - def u16_half(self, u, hi=0): - """Zero-extended 16-bit half of u32 ``u`` (high half when ``hi`` is truthy). - Do not follow ``OpShiftRightLogical %uint u 16`` with a redundant ``OpBitwiseAnd ... 0xFFFF``: - AMD's Windows LLPC driver (measured on RDNA2, drivers 22.40.84.06 in #1506 and 24.10.24) drops the - ``>> 16`` when ``(u >> 16) & 0xFFFF`` follows two partial-half writes and feeds ``OpIAdd``, ``OpIMul``, - or ``OpShiftLeftLogical``.""" - h = self.tmp() - if hi: - self.emit(f"{h} = OpShiftRightLogical %uint {u} {self.cu(16)}") - else: - self.emit(f"{h} = OpBitwiseAnd %uint {u} {self.cu(0xFFFF)}") - return h - - def i16_half(self, u, hi=0): - """Sign-extended 16-bit half of u32 ``u`` as ``%int`` (high half when ``hi`` is truthy). - Avoids ``OpBitFieldSExtract (OpShiftRightLogical u 16) 0 16``, which hits the same AMD Windows LLPC - bug as ``(u >> 16) & 0xFFFF`` (#1506) and drops the shift.""" - h = self.tmp() - if hi: - self.emit(f"{h} = OpShiftRightArithmetic %int {self.as_int(u)} {self.cu(16)}") - else: - self.emit(f"{h} = OpBitFieldSExtract %int {self.as_int(u)} {self.cu(0)} {self.cu(16)}") - return h - - def src_h(self, s): - """Raw 32 bits of an operand of a 16-bit float op, before its neg/abs. An inline float constant (0.5, 1.0, - -2.0, ...) is the f16 value in the low half over a zero high half, not f32 bits. Measured on an RX 6800 - (gfx1030, raw kernel, wave32 and wave64): v_add_f16 d, 1.0, v with v.lo = 0.25 gives 1.25, - v_cvt_f32_f16 d, 0.5 gives 0x3f000000, v_pack_b32_f16 d, 1.0, v puts 0x3c00 in the low half, and op_sel's - high half of the constant reads +0.0. Under SDWA, src_sel then narrows those 32 bits like a register's - (gfx1036: v_add_f16_sdwa d, 1.0, v src0_sel:WORD_1 reads +0.0).""" - if s["k"] == "fimm": - try: - v = self.cu(struct.unpack(" f16 bits as RDNA2's buffer unit narrows a float: toward zero, a finite value past the range - -> +-65504, an f32 denormal -> +-0 (f16_bits(rtz=True)), and a NaN keeps its sign and the top 10 bits of its - payload without being quieted, 1 if those are all 0 (0x7fa00000 -> 0x7d00, 0x7f800001 -> 0x7c01). Measured - natively on gfx1036 for 16_FLOAT stores and 32_FLOAT d16 loads (SHADER-358).""" - h = self.f16_bits(f, rtz=True) - x, mag, nan, top, one, keep, sg, nb, out = (self.tmp() for _ in range(9)) - self.emit(f"{x} = OpBitcast %uint {f}") - self.emit(f"{mag} = OpBitwiseAnd %uint {x} {self.cu(0x7FFFFFFF)}") - self.emit(f"{nan} = OpUGreaterThan %bool {mag} {self.cu(0x7F800000)}") - self.emit(f"{top} = OpBitFieldUExtract %uint {x} {self.cu(13)} {self.cu(10)}") - self.emit(f"{one} = OpIEqual %bool {top} {self.cu(0)}") - self.emit(f"{keep} = OpSelect %uint {one} {self.cu(1)} {top}") - self.emit(f"{sg} = OpShiftRightLogical %uint {x} {self.cu(16)}") - sgm = self.tmp() - self.emit(f"{sgm} = OpBitwiseAnd %uint {sg} {self.cu(0x8000)}") - kn = self.tmp() - self.emit(f"{kn} = OpBitwiseOr %uint {keep} {self.cu(0x7C00)}") - self.emit(f"{nb} = OpBitwiseOr %uint {sgm} {kn}") - self.emit(f"{out} = OpSelect %uint {nan} {nb} {h}") - return out - - def pack_f16_pair_int(self, f0, f1): - """Two f32 values -> one u32 (lo f16 | hi f16 << 16), each narrowed by f16_bits: integer ops only, no - GLSL.std.450 at all (#489: an amdvlk64 pipeline-creation crash came from PackHalf2x16 on a d16 - image_sample result feeding a structured loop with OpGroupNonUniformAny). For d16 memory results (image - samples and gathers, typed buffer loads): those are converted outside the VALU, so they stay round to - nearest even and don't go through f16_pack2. f16_bits replaced #489's own f32_to_f16_int on 2026-11-22; the - two gave the same bits on 30,648 inputs (every f32 exponent, ties, the subnormal and overflow edges, NaN).""" - lo = self.f16_bits(f0) - hi = self.f16_bits(f1) - hi_s, out = self.tmp(), self.tmp() - self.emit(f"{hi_s} = OpShiftLeftLogical %uint {hi} {self.cu(16)}") - self.emit(f"{out} = OpBitwiseOr %uint {lo} {hi_s}") - return out - - def f16_in(self, s, hi=0): - """Read operand ``s`` as an f16 (low half, or high half when ``hi``) widened to f32, then apply its neg/abs. - - RDNA2's f16 MODE keeps denormals, but on NVIDIA (RTX 5060 Ti, 610.88) UnpackHalf2x16 gives 0 for a denormal - that an SDWA BYTE_1 select produced, from an inline constant or a VGPR alike (ps_sdwa_f16_const), while the - same denormal in a register or a literal widens right. A half with a zero exponent field is therefore - widened exactly with integer ops: sign * mantissa * 2^-24.""" - return self.f16_in_bits(s, hi, apply_mods=False)[0] - - @staticmethod - def _f16_const_nan(s, hi=0): - """Return True/False when ``s`` (with half ``hi``) is statically NaN/non-NaN, or None at run time.""" - if not s or "sdwa_sel" in s: - return None - if s["k"] == "fimm": - return s["v"] != s["v"] - if s["k"] == "imm": - hv = ((s["v"] & 0xFFFFFFFF) >> (16 if hi else 0)) & 0xFFFF - return (hv & 0x7FFF) > 0x7C00 - return None - - def _f16_half_nan(self, h): - ab, cond = self.tmp(), self.tmp() - self.emit(f"{ab} = OpBitwiseAnd %uint {h} {self.cu(0x7FFF)}") - self.emit(f"{cond} = OpUGreaterThan %bool {ab} {self.cu(0x7C00)}") - return cond - - def all_f16_nan_cond(self, half_pairs): - """Given ``[(h_uint, const_status), ...]``, return True (all const NaN), None (impossible), or %bool ID.""" - if any(st is False for _, st in half_pairs): - return None - checks = [self._f16_half_nan(h) for h, st in half_pairs if st is None] - if not checks: - return True - cond = checks[0] - for c in checks[1:]: - nxt = self.tmp() - self.emit(f"{nxt} = OpLogicalAnd %bool {cond} {c}") - cond = nxt - return cond - - def _f16_half_word(self, u, hi=0): - """Extract the selected 16-bit half of ``u`` into ``%uint[15:0]`` (high half shifts cleanly without redundant & 0xFFFF).""" - h = self.tmp() - if hi: - self.emit(f"{h} = OpShiftRightLogical %uint {u} {self.cu(16)}") - else: - self.emit(f"{h} = OpBitwiseAnd %uint {u} {self.cu(0xFFFF)}") - return h - - def f16_in_bits(self, s, hi=0, apply_mods=True): - """Like ``f16_in``, also returning ``(h_bits, const_nan_status)``; ``h_bits`` keeps abs/neg if ``apply_mods``.""" - u = self.src_h(s) - v2, f = self.tmp(), self.tmp() - self.emit(f"{v2} = OpExtInst %v2float %glsl UnpackHalf2x16 {u}") - self.emit(f"{f} = OpCompositeExtract %float {v2} {1 if hi else 0}") - ex, small, mant, mf, den, neg, isneg, sden, out = (self.tmp() for _ in range(9)) - h = self._f16_half_word(u, hi) - self.emit(f"{ex} = OpBitwiseAnd %uint {h} {self.cu(0x7C00)}") - self.emit(f"{small} = OpIEqual %bool {ex} {self.cu(0)}") - self.emit(f"{mant} = OpBitwiseAnd %uint {h} {self.cu(0x3FF)}") - self.emit(f"{mf} = OpConvertUToF %float {mant}") - self.emit(f"{den} = OpFMul %float {mf} {self.fconst(2.0 ** -24)}") - self.emit(f"{neg} = OpFNegate %float {den}") - self.emit(f"{isneg} = OpUGreaterThanEqual %bool {h} {self.cu(0x8000)}") - self.emit(f"{sden} = OpSelect %float {isneg} {neg} {den}") - self.emit(f"{out} = OpSelect %float {small} {sden} {f}") - h_mod = h - if apply_mods: - if s.get("abs"): - ha = self.tmp() - self.emit(f"{ha} = OpBitwiseAnd %uint {h_mod} {self.cu(0x7FFF)}") - h_mod = ha - if s.get("neg"): - hn = self.tmp() - self.emit(f"{hn} = OpBitwiseXor %uint {h_mod} {self.cu(0x8000)}") - h_mod = hn - return self.modify_f(out, s), h_mod, self._f16_const_nan(s, hi) - - def fma_mix_srcs(self, a, mods): - """Read the 3 operands of v_fma_mix*: f16 at op_sel[i] when op_sel_hi[i] is set (via src_h so fimm is binary16), else f32.""" - sel = next((m for m in mods if m.startswith("op_sel:")), "op_sel:[0,0,0]") - selhi = next((m for m in mods if m.startswith("op_sel_hi:")), "op_sel_hi:[0,0,0]") - # A hand-written list shorter than the three operands (op_sel_hi:[0,0]) is padded with 0, as llvm-mc prints it. - sb = ([int(x) for x in sel.split("[")[1].rstrip("]").split(",")] + [0, 0, 0])[:3] - hb = ([int(x) for x in selhi.split("[")[1].rstrip("]").split(",")] + [0, 0, 0])[:3] - # An f32 operand reads as a zero of its sign when it is denormal: the game's MODE flushes f32 denormals - # (denorm_mode_32 = 0), measured on gfx1036 for 0x00000001, 0x807fffff and the integer inline constants 1 and - # 64 used as f32 operands (@Sanonymous01, SHADER-298). The f16 operands widen to normal f32 values. - return [self.f16_in(src, sb[i]) if hb[i] else self.flush_f32(self.src_f(src)) for i, src in enumerate(a[1:4])] - - def f16_bits(self, f, rtz=False, exact_tiny=False, is_z=None): - """f32 ``f`` -> f16 bits in the low 16 bits of a %uint, computed with integer ops only (SHADER-56). - - GLSL.std.450 PackHalf2x16 leaves the rounding mode to the implementation, and drivers fold a - PackHalf2x16 -> UnpackHalf2x16 round trip to a no-op (#513: NVIDIA under --wave64-emulate; #512: RTX - 5080), so a following f16 op would see the unrounded f32. Integer ops can't be folded through. - ``rtz=False``: round to nearest even, |x| >= 65520 -> inf (v_cvt_f16_f32 and every f16 ALU result). - ``rtz=True``: round toward zero, finite values above the range -> +-65504 (v_cvt_pkrtz_f16_f32). - f16 denormals are produced (RDNA2's default FP16 denorm mode keeps them); f32 denormal inputs give +-0. - NaN -> quiet NaN with the top payload bits kept; +-inf -> +-inf. - ``exact_tiny``: the caller guarantees that every ``f`` below 2^-14 in magnitude is already an f16 value (a - sum of two f16 values, without omod: a multiple of 2^-24), so that range needs no rounding.""" - t = self.tmp - x, sgn, sg, a = t(), t(), t(), t() - self.emit(f"{x} = OpBitcast %uint {f}") - self.emit(f"{sgn} = OpShiftRightLogical %uint {x} {self.cu(16)}") - self.emit(f"{sg} = OpBitwiseAnd %uint {sgn} {self.cu(0x8000)}") - self.emit(f"{a} = OpBitwiseAnd %uint {x} {self.cu(0x7FFFFFFF)}") - # normal range: rebias the exponent (127 -> 15) and drop 13 mantissa bits - m, nh = t(), t() - self.emit(f"{m} = OpISub %uint {a} {self.cu(0x38000000)}") - if rtz: - self.emit(f"{nh} = OpShiftRightLogical %uint {m} {self.cu(13)}") - else: - lsb, bias, mb, = t(), t(), t() - self.emit(f"{lsb} = OpBitFieldUExtract %uint {m} {self.cu(13)} {self.cu(1)}") - self.emit(f"{bias} = OpIAdd %uint {lsb} {self.cu(0xFFF)}") - if is_z: - bias = self.unless_rtz(is_z, bias) - self.emit(f"{mb} = OpIAdd %uint {m} {bias}") - self.emit(f"{nh} = OpShiftRightLogical %uint {mb} {self.cu(13)}") - # subnormal range (2^-25 <= |x| < 2^-14): shift the full mantissa right by 126 - e (14..25) - e, man, sh, short, shc, sub = t(), t(), t(), t(), t(), t() - self.emit(f"{e} = OpShiftRightLogical %uint {a} {self.cu(23)}") - self.emit(f"{man} = OpBitwiseOr %uint {self.cu(0x800000)} {self.emit_and(a, 0x7FFFFF)}") - self.emit(f"{sh} = OpISub %uint {self.cu(126)} {e}") - # min(sh, 25) without GLSL.std.450, so the d16 memory results can use this too (see pack_f16_pair_int) - self.emit(f"{short} = OpULessThan %bool {sh} {self.cu(25)}") - self.emit(f"{shc} = OpSelect %uint {short} {sh} {self.cu(25)}") - self.emit(f"{sub} = OpShiftRightLogical %uint {man} {shc}") - # |x| < 2^-25 needs no test of its own: there shc is 25, and man (plus the bias below) shifts out to 0 - if not rtz and not exact_tiny: - # nearest even, as in the normal range: add half - 1 + the kept low bit, then shift - one, half, below, odd, bias2, mb2, sub2 = (t() for _ in range(7)) - self.emit(f"{one} = OpShiftLeftLogical %uint {self.cu(1)} {shc}") - self.emit(f"{half} = OpShiftRightLogical %uint {one} {self.cu(1)}") - self.emit(f"{below} = OpISub %uint {half} {self.cu(1)}") - self.emit(f"{odd} = OpBitwiseAnd %uint {sub} {self.cu(1)}") - self.emit(f"{bias2} = OpIAdd %uint {below} {odd}") - if is_z: - bias2 = self.unless_rtz(is_z, bias2) - self.emit(f"{mb2} = OpIAdd %uint {man} {bias2}") - self.emit(f"{sub2} = OpShiftRightLogical %uint {mb2} {shc}") - sub = sub2 - # pick the range - isn, big, isinf, isnan = t(), t(), t(), t() - self.emit(f"{isn} = OpUGreaterThanEqual %bool {a} {self.cu(0x38800000)}") - r1, r2, r3, r4, r5, nanb, res = t(), t(), t(), t(), t(), t(), t() - self.emit(f"{r1} = OpSelect %uint {isn} {nh} {sub}") - r2 = r1 - if rtz: - self.emit(f"{big} = OpUGreaterThanEqual %bool {a} {self.cu(0x47800000)}") - self.emit(f"{r3} = OpSelect %uint {big} {self.cu(0x7BFF)} {r2}") - elif is_z: - limit, top = t(), t() - self.emit(f"{limit} = OpSelect %uint {is_z} {self.cu(0x47800000)} {self.cu(0x477FF000)}") - self.emit(f"{top} = OpSelect %uint {is_z} {self.cu(0x7BFF)} {self.cu(0x7C00)}") - self.emit(f"{big} = OpUGreaterThanEqual %bool {a} {limit}") - self.emit(f"{r3} = OpSelect %uint {big} {top} {r2}") - else: - self.emit(f"{big} = OpUGreaterThanEqual %bool {a} {self.cu(0x477FF000)}") - self.emit(f"{r3} = OpSelect %uint {big} {self.cu(0x7C00)} {r2}") - if rtz or is_z: - self.emit(f"{isinf} = OpIEqual %bool {a} {self.cu(0x7F800000)}") - self.emit(f"{r4} = OpSelect %uint {isinf} {self.cu(0x7C00)} {r3}") - else: - r4 = r3 # inf is >= 65520, so the overflow select already gave 0x7C00 - pay = t() - self.emit(f"{pay} = OpShiftRightLogical %uint {a} {self.cu(13)}") - self.emit(f"{nanb} = OpBitwiseOr %uint {self.emit_and(pay, 0x3FF)} {self.cu(0x7E00)}") - self.emit(f"{isnan} = OpUGreaterThan %bool {a} {self.cu(0x7F800000)}") - self.emit(f"{r5} = OpSelect %uint {isnan} {nanb} {r4}") - self.emit(f"{res} = OpBitwiseOr %uint {r5} {sg}") - return res - - def emit_and(self, v, k): - r = self.tmp() - self.emit(f"{r} = OpBitwiseAnd %uint {v} {self.cu(k)}") - return r - - def f16_res(self, f, exact_tiny=False): - """f32 ``f`` -> f16 bits (low 16) as a VALU f16 result rounds it: to nearest even (f16_bits), or, when the - program writes MODE.FP_ROUND[3:2], by the current mode in %mode_r16 (0 nearest even, 3 toward zero with - f16_bits(rtz=True); 1 and 2 are refused when the setreg is translated). Shaders that never write the field - get exactly f16_bits. Integer ops only either way (SHADER-56).""" - if not self.round_mode: - return self.f16_bits(f, exact_tiny=exact_tiny) - m, is_z = self.tmp(), self.tmp() - self.emit(f"{m} = OpLoad %uint %mode_r16") - self.emit(f"{is_z} = OpIEqual %bool {m} {self.cu(3)}") - return self.f16_bits(f, exact_tiny=exact_tiny, is_z=is_z) - - def unless_rtz(self, is_z, v): - r = self.tmp() - self.emit(f"{r} = OpSelect %uint {is_z} {self.cu(0)} {v}") - return r - - def f16_omod(self, h, mods): - """VOP3 mul:2 / mul:4 / div:2 on the rounded f16 bits ``h`` (low 16) of v_cvt_f16_f32, as measured on RDNA2 - (RX 6800 on #718; gfx1036 across wave32/wave64 and MODE RNE/RTZ): after rounding and before clamp, so 65520 - div:2 is inf in nearest mode and 32752 (0x77ff) toward zero. The hardware applies an omod to an f16 result - only with IEEE off and f16 denormals flushed, and a compiler emits one only for that mode (the corpus argument - of the f32 output modifier rows in docs/design.md), so this models that mode: a zero or denormal f16 before - the omod (e == 0, including -0.0) gives +0 (0x0000), div:2 underflowing a smallest normal (e == 1) flushes - to signed zero (h & 0x8000, so -2^-14 div:2 gives 0x8000), inf and NaN pass through, and finite mul:2/mul:4 - overflow gives +-inf in nearest mode and +-65504 (0x7bff / 0xfbff) under MODE toward zero.""" - k = next((m for m in mods if m in ("mul:2", "mul:4", "div:2")), None) - if k is None: - return h - d = {"mul:2": 1, "mul:4": 2, "div:2": -1}[k] - t = self.tmp - sh, e, special, tiny, scaled, r = t(), t(), t(), t(), t(), t() - self.emit(f"{sh} = OpShiftRightLogical %uint {h} {self.cu(10)}") - self.emit(f"{e} = OpBitwiseAnd %uint {sh} {self.cu(31)}") - self.emit(f"{special} = OpIEqual %bool {e} {self.cu(31)}") - # Zero and denormal inputs (e == 0) flush to +0 (including -0 -> +0). For div:2, underflowing a - # smallest normal (e == 1) flushes to signed zero (h & 0x8000: -2^-14 div:2 -> -0.0 on gfx1036). - self.emit(f"{tiny} = OpIEqual %bool {e} {self.cu(0)}") - if d < 0: - sub_one, under, sign = t(), t(), t() - self.emit(f"{sub_one} = OpISub %uint {h} {self.cu(1 << 10)}") - self.emit(f"{under} = OpIEqual %bool {e} {self.cu(1)}") - self.emit(f"{sign} = OpBitwiseAnd %uint {h} {self.cu(0x8000)}") - self.emit(f"{scaled} = OpSelect %uint {under} {sign} {sub_one}") - else: - add, sign, over, inf, big = t(), t(), t(), t(), t() - self.emit(f"{add} = OpIAdd %uint {h} {self.cu(d << 10)}") - self.emit(f"{sign} = OpBitwiseAnd %uint {h} {self.cu(0x8000)}") - self.emit(f"{over} = OpUGreaterThanEqual %bool {e} {self.cu(31 - d)}") - self.emit(f"{inf} = OpBitwiseOr %uint {sign} {self.cu(0x7C00)}") - if self.round_mode: - m, is_z, top, sel = t(), t(), t(), t() - self.emit(f"{m} = OpLoad %uint %mode_r16") - self.emit(f"{is_z} = OpIEqual %bool {m} {self.cu(3)}") - self.emit(f"{top} = OpBitwiseOr %uint {sign} {self.cu(0x7BFF)}") - self.emit(f"{sel} = OpSelect %uint {is_z} {top} {inf}") - inf = sel - self.emit(f"{big} = OpSelect %uint {over} {inf} {add}") - scaled = big - z = t() - self.emit(f"{z} = OpSelect %uint {tiny} {self.cu(0)} {scaled}") - self.emit(f"{r} = OpSelect %uint {special} {h} {z}") - return r - - def sum_toward_zero(self, x, y, r): - """f32 ``r`` = x + y (nearest even) for an f16 add/sub that will be narrowed by f16_res. Under MODE toward zero - the f32 rounding must not decide the f16 result: x + y = 2 - 2^-24 rounds to 2.0 in f32, but toward zero - it is 0x3FFF in f16. When the exact TwoSum error shows r rounded away from zero, step r one f32 ulp toward - zero: the exact sum then lies strictly between r and the stepped value, with no f16 value between them, - so the toward-zero narrowing gives the exact result. (f16 FMAs don't need this: fma_f16_odd's round-to-odd - f32 value narrows exactly in any direction.) The sums here (f16 operands) never overflow or - reach f32 subnormals. Returns r unchanged when the program never writes MODE.""" - if not self.round_mode: - return r - bb, t1, t2, t3, e = (self.tmp() for _ in range(5)) - self.emit(f"{bb} = OpFSub %float {r} {x}") - self.emit(f"{t1} = OpFSub %float {r} {bb}") - self.emit(f"{t2} = OpFSub %float {x} {t1}") - self.emit(f"{t3} = OpFSub %float {y} {bb}") - self.emit(f"{e} = OpFAdd %float {t2} {t3}") - rp, rn, ep, en, a1, a2, away, m, isz, step = (self.tmp() for _ in range(10)) - self.emit(f"{rp} = OpFOrdGreaterThan %bool {r} %f0") - self.emit(f"{rn} = OpFOrdLessThan %bool {r} %f0") - self.emit(f"{ep} = OpFOrdGreaterThan %bool {e} %f0") - self.emit(f"{en} = OpFOrdLessThan %bool {e} %f0") - self.emit(f"{a1} = OpLogicalAnd %bool {rp} {en}") - self.emit(f"{a2} = OpLogicalAnd %bool {rn} {ep}") - self.emit(f"{away} = OpLogicalOr %bool {a1} {a2}") - self.emit(f"{m} = OpLoad %uint %mode_r16") - self.emit(f"{isz} = OpIEqual %bool {m} {self.cu(3)}") - self.emit(f"{step} = OpLogicalAnd %bool {away} {isz}") - u, dec, su = self.tou(r), self.tmp(), self.tmp() - self.emit(f"{dec} = OpISub %uint {u} {self.cu(1)}") - self.emit(f"{su} = OpSelect %uint {step} {dec} {u}") - return self.tof(su) - - def sum_toward_zero2(self, x, y, r): - """sum_toward_zero on each half of v2float operands; returns a v2float.""" - if not self.round_mode: - return r - out = [] - for i in (0, 1): - xi, yi, ri = self.tmp(), self.tmp(), self.tmp() - self.emit(f"{xi} = OpCompositeExtract %float {x} {i}") - self.emit(f"{yi} = OpCompositeExtract %float {y} {i}") - self.emit(f"{ri} = OpCompositeExtract %float {r} {i}") - out.append(self.sum_toward_zero(xi, yi, ri)) - v = self.tmp() - self.emit(f"{v} = OpCompositeConstruct %v2float {out[0]} {out[1]}") - return v - - def _f32_step_toward_zero(self, r, step): - rb, nb, sb, out = (self.tmp() for _ in range(4)) - self.emit(f"{rb} = OpBitcast %uint {r}") - self.emit(f"{nb} = OpISub %uint {rb} {self.cu(1)}") - self.emit(f"{sb} = OpSelect %uint {step} {nb} {rb}") - self.emit(f"{out} = OpBitcast %float {sb}") - return out - - def _f32_finite(self, x): - i, n, o, f = (self.tmp() for _ in range(4)) - self.emit(f"{i} = OpIsInf %bool {x}") - self.emit(f"{n} = OpIsNan %bool {x}") - self.emit(f"{o} = OpLogicalOr %bool {i} {n}") - self.emit(f"{f} = OpLogicalNot %bool {o}") - return f - - def _f32_overflowed(self, r, x, y): - ri, fx, fy, both, of = (self.tmp() for _ in range(5)) - self.emit(f"{ri} = OpIsInf %bool {r}") - fx, fy = self._f32_finite(x), self._f32_finite(y) - self.emit(f"{both} = OpLogicalAnd %bool {fx} {fy}") - self.emit(f"{of} = OpLogicalAnd %bool {ri} {both}") - return of - - def _f32_away(self, r, e): - rp, rn, ep, en, a1, a2, away = (self.tmp() for _ in range(7)) - self.emit(f"{rp} = OpFOrdGreaterThan %bool {r} %f0") - self.emit(f"{rn} = OpFOrdLessThan %bool {r} %f0") - self.emit(f"{ep} = OpFOrdGreaterThan %bool {e} %f0") - self.emit(f"{en} = OpFOrdLessThan %bool {e} %f0") - self.emit(f"{a1} = OpLogicalAnd %bool {rp} {en}") - self.emit(f"{a2} = OpLogicalAnd %bool {rn} {ep}") - self.emit(f"{away} = OpLogicalOr %bool {a1} {a2}") - return away - - def f32_sub_rtz(self, x, y): - r, bb, t1, t2, t3, e = (self.tmp() for _ in range(6)) - self.emit(f"{r} = OpFSub %float {x} {y}") - self.emit(f"{bb} = OpFSub %float {r} {x}") - self.emit(f"{t1} = OpFSub %float {r} {bb}") - self.emit(f"{t2} = OpFSub %float {x} {t1}") - self.emit(f"{t3} = OpFAdd %float {y} {bb}") - self.emit(f"{e} = OpFSub %float {t2} {t3}") - step = self.tmp() - self.emit(f"{step} = OpLogicalOr %bool {self._f32_away(r, e)} {self._f32_overflowed(r, x, y)}") - return self._f32_step_toward_zero(r, step) - - def f32_mul_rtz(self, x, y): - m = self.tmp() - self.emit(f"{m} = OpFMul %float {x} {y}") - - def mant(v): - b, k, s, f, ex, nz, nm, ok = (self.tmp() for _ in range(8)) - self.emit(f"{b} = OpBitcast %uint {v}") - self.emit(f"{k} = OpBitwiseAnd %uint {b} {self.cu(0x007FFFFF)}") - self.emit(f"{s} = OpBitwiseOr %uint {k} {self.cu(0x3F800000)}") - self.emit(f"{f} = OpBitcast %float {s}") - self.emit(f"{ex} = OpBitFieldUExtract %uint {b} {self.cu(23)} {self.cu(8)}") - self.emit(f"{nz} = OpINotEqual %bool {ex} {self.cu(0)}") - self.emit(f"{nm} = OpINotEqual %bool {ex} {self.cu(0xFF)}") - self.emit(f"{ok} = OpLogicalAnd %bool {nz} {nm}") - return f, ok - - def split(v): - c, d, hi_, lo_ = (self.tmp() for _ in range(4)) - self.emit(f"{c} = OpFMul %float {self.tof(self.cu(0x45801000))} {v}") - self.emit(f"{d} = OpFSub %float {c} {v}") - self.emit(f"{hi_} = OpFSub %float {c} {d}") - self.emit(f"{lo_} = OpFSub %float {v} {hi_}") - return hi_, lo_ - - xm, xok = mant(x) - ym, yok = mant(y) - p = self.tmp() - self.emit(f"{p} = OpFMul %float {xm} {ym}") - (xh, xl), (yh, yl) = split(xm), split(ym) - hh, hl, lh, ll, e1, e2, e3, e = (self.tmp() for _ in range(8)) - self.emit(f"{hh} = OpFMul %float {xh} {yh}") - self.emit(f"{hl} = OpFMul %float {xh} {yl}") - self.emit(f"{lh} = OpFMul %float {xl} {yh}") - self.emit(f"{ll} = OpFMul %float {xl} {yl}") - self.emit(f"{e1} = OpFSub %float {hh} {p}") - self.emit(f"{e2} = OpFAdd %float {e1} {hl}") - self.emit(f"{e3} = OpFAdd %float {e2} {lh}") - self.emit(f"{e} = OpFAdd %float {e3} {ll}") - over, normals, mfin, valid, step = (self.tmp() for _ in range(5)) - self.emit(f"{over} = OpFOrdLessThan %bool {e} %f0") - self.emit(f"{normals} = OpLogicalAnd %bool {xok} {yok}") - mf = self._f32_finite(m) - self.emit(f"{mfin} = OpLogicalAnd %bool {normals} {mf}") - self.emit(f"{valid} = OpLogicalAnd %bool {mfin} {over}") - self.emit(f"{step} = OpLogicalOr %bool {valid} {self._f32_overflowed(m, x, y)}") - return self._f32_step_toward_zero(m, step) - - def f64_add_mode(self, x, y, r, lo, hi): - """v_add_f64 under MODE.FP_ROUND[3:2]: ``r`` = x + y rounded to nearest (bits lo/hi). When the mode is - toward zero (3) and the nearest result rounded away from zero, step one ulp back. Ordering the operands so - |a| >= |b| keeps FastTwoSum (bb = r - a, e = b - bb; every float op is NoContraction) inside +-DBL_MAX - whenever ``r`` is finite (``|r - a| <= max(|r|, |a|) <= DBL_MAX``), whereas unordered TwoSum ``r - x`` can - overflow to +-inf and turn ``e`` into NaN when |x| < |y| with opposite signs near +-DBL_MAX; r was rounded - away from zero when e and r have opposite signs. A finite sum that overflowed to inf becomes +-DBL_MAX. - Returns the new (lo, hi).""" - xv, xlo, xhi, yv, ylo, yhi, axhi, ayhi = (self.tmp() for _ in range(8)) - self.emit(f"{xv} = OpBitcast %v2uint_d {x}") - self.emit(f"{xlo} = OpCompositeExtract %uint {xv} 0") - self.emit(f"{xhi} = OpCompositeExtract %uint {xv} 1") - self.emit(f"{yv} = OpBitcast %v2uint_d {y}") - self.emit(f"{ylo} = OpCompositeExtract %uint {yv} 0") - self.emit(f"{yhi} = OpCompositeExtract %uint {yv} 1") - mask = self.cu(0x7FFFFFFF) - self.emit(f"{axhi} = OpBitwiseAnd %uint {xhi} {mask}") - self.emit(f"{ayhi} = OpBitwiseAnd %uint {yhi} {mask}") - hlt, heq, llt, tie, swap, a, b = (self.tmp() for _ in range(7)) - self.emit(f"{hlt} = OpULessThan %bool {axhi} {ayhi}") - self.emit(f"{heq} = OpIEqual %bool {axhi} {ayhi}") - self.emit(f"{llt} = OpULessThan %bool {xlo} {ylo}") - self.emit(f"{tie} = OpLogicalAnd %bool {heq} {llt}") - self.emit(f"{swap} = OpLogicalOr %bool {hlt} {tie}") - self.emit(f"{a} = OpSelect %double {swap} {y} {x}") - self.emit(f"{b} = OpSelect %double {swap} {x} {y}") - bb, e = self.tmp(), self.tmp() - self.emit(f"{bb} = OpFSub %double {r} {a}") - self.emit(f"{e} = OpFSub %double {b} {bb}") - z2, zd = self.tmp(), self.tmp() - self.emit(f"{z2} = OpCompositeConstruct %v2uint_d {self.cu(0)} {self.cu(0)}") - self.emit(f"{zd} = OpBitcast %double {z2}") - en, rp, ep, rn, a1, a2, away = (self.tmp() for _ in range(7)) - self.emit(f"{rp} = OpFOrdGreaterThan %bool {r} {zd}") - self.emit(f"{rn} = OpFOrdLessThan %bool {r} {zd}") - self.emit(f"{en} = OpFOrdLessThan %bool {e} {zd}") - self.emit(f"{ep} = OpFOrdGreaterThan %bool {e} {zd}") - self.emit(f"{a1} = OpLogicalAnd %bool {rp} {en}") - self.emit(f"{a2} = OpLogicalAnd %bool {rn} {ep}") - self.emit(f"{away} = OpLogicalOr %bool {a1} {a2}") - # overflow: r is inf while x and y are finite - ri, xi, yi, xn, yn, xs, ys, xf, of = (self.tmp() for _ in range(9)) - self.emit(f"{ri} = OpIsInf %bool {r}") - self.emit(f"{xi} = OpIsInf %bool {x}") - self.emit(f"{yi} = OpIsInf %bool {y}") - self.emit(f"{xn} = OpIsNan %bool {x}") - self.emit(f"{yn} = OpIsNan %bool {y}") - self.emit(f"{xs} = OpLogicalOr %bool {xi} {xn}") - self.emit(f"{ys} = OpLogicalOr %bool {yi} {yn}") - self.emit(f"{xf} = OpLogicalOr %bool {xs} {ys}") - nf = self.tmp() - self.emit(f"{nf} = OpLogicalNot %bool {xf}") - self.emit(f"{of} = OpLogicalAnd %bool {ri} {nf}") - step, any_, m, isz = (self.tmp() for _ in range(4)) - self.emit(f"{any_} = OpLogicalOr %bool {away} {of}") - self.emit(f"{m} = OpLoad %uint %mode_r16") - self.emit(f"{isz} = OpIEqual %bool {m} {self.cu(3)}") - self.emit(f"{step} = OpLogicalAnd %bool {any_} {isz}") - # one ulp toward zero on the magnitude bits: (hi:lo) - 1 (inf - 1 = DBL_MAX) - nlo, bor, bu, nhi, rlo, rhi = (self.tmp() for _ in range(6)) - self.emit(f"{nlo} = OpISub %uint {lo} {self.cu(1)}") - self.emit(f"{bor} = OpIEqual %bool {lo} {self.cu(0)}") - self.emit(f"{bu} = OpSelect %uint {bor} {self.cu(1)} {self.cu(0)}") - self.emit(f"{nhi} = OpISub %uint {hi} {bu}") - self.emit(f"{rlo} = OpSelect %uint {step} {nlo} {lo}") - self.emit(f"{rhi} = OpSelect %uint {step} {nhi} {hi}") - return rlo, rhi - - def mode_write(self, op, a): - """s_setreg* on HW_REG_MODE. Only FP_ROUND[3:2] (f16/f64 rounding) is modelled, the one MODE field the - corpus writes (9,417 writes: value 3 = toward zero 6,694, value 0 = nearest even 2,723). A write that - reaches another MODE bit or only part of the field, sets directed rounding (+inf/-inf), or takes its value - from an SGPR is refused, so nothing changes silently. Other hardware registers (FLAT_SCR, POPS packer) are not MODE: ignored.""" - t = a[0].get("t", "") if a and a[0]["k"] == "special" else "" - m = re.match(r"hwreg\((\w+)(?:,\s*(\d+),\s*(\d+))?\)", t) - if not m or m.group(1) != "HW_REG_MODE": - return - off, size = (int(m.group(2)), int(m.group(3))) if m.group(2) else (0, 32) - if (off, size) != (2, 2): - raise Unsupported(f"{op} on MODE bits {off}..{off + size - 1} (only FP_ROUND[3:2] as a whole is modelled)") - if op != "s_setreg_imm32_b32" or a[1]["k"] != "imm": - raise Unsupported(f"{op} with a register value on MODE.FP_ROUND") - self.write_half_round_mode(op, a[1]["v"] & 3) - - def write_half_round_mode(self, op: str, mode: int) -> None: - if mode in (1, 2): - raise Unsupported(f"{op}: MODE.FP_ROUND[3:2] directed rounding (+inf/-inf)") - self.emit(f"OpStore %mode_r16 {self.cu(mode)}") - - def emit_ne0(self, v): - r = self.tmp() - self.emit(f"{r} = OpINotEqual %bool {v} {self.cu(0)}") - return r - - def emit_fma(self, r, x, y, z): - """r = x * y + z as an f32 multiply-add with ONE rounding, which is what RDNA2's v_fma_* do. - - GLSL.std.450 Fma is specified in the Vulkan environment as "inherited from OpFMul followed by OpFAdd", so a - driver may round twice. With --fma khr it is OpFmaKHR instead: "correctly rounded" (SPV_KHR_fma), which needs - VK_KHR_shader_fma + shaderFmaFloat32 and is recorded in the index as capability FMAKHR.""" - if FMA_KHR: - self.uses_fma_khr = self.uses_fma_khr32 = True - self.emit(f"{r} = OpFmaKHR %float {x} {y} {z}") - elif FMA_EXACT: - self.fma_exact(r, x, y, z) - else: - self.emit(f"{r} = OpExtInst %float %glsl Fma {x} {y} {z}") - - def emit_fma64(self, r, x, y, z): - """r = x * y + z on doubles with ONE rounding, as RDNA2's f64 multiply-adds do. GLSL.std.450 Fma may round - twice here as for f32, and NVIDIA's driver does (RTX 4090, 621.24: the fma(a, a, c) cancellation probe with - a = 1 + 2^-30 gives 0, not 2^-60). With --fma khr it is OpFmaKHR on doubles, which needs VK_KHR_shader_fma + - shaderFmaFloat64 (feature shaderFmaFloat64 in the index). --fma exact has no f64 form and keeps Fma.""" - if FMA_KHR: - self.uses_fma_khr = self.uses_fma_khr64 = True - self.emit(f"{r} = OpFmaKHR %double {x} {y} {z}") - else: - self.emit(f"{r} = OpExtInst %double %glsl Fma {x} {y} {z}") - - def fma_exact(self, r, x, y, z): - """r = x * y + z rounded once to f32, built from single-rounded NoContraction f32 operations (--fma exact, - SHADER-497): for a device whose driver splits GLSL Fma into two roundings and that has no VK_KHR_shader_fma - (Intel UHD Graphics, Xe-LP, Windows driver 101.7088: cs_fma_fused words 0, 2, 3 and 5 split). - - Boldo and Melquiond's emulated FMA ("Emulation of a FMA and correctly-rounded sums: proved algorithms using - rounding to odd", IEEE Transactions on Computers 57(4), 2008): p + pe = x * y exactly (Dekker's product; the - factors are split into 12-bit halves by masking the low 12 mantissa bits, so the split cannot overflow), - th + tl = z + p exactly (TwoSum), v = tl + pe rounded to odd (as fma_f16_odd), and r = th + v rounded to - nearest, or th when v is zero (th + 0 would turn a -0 sum into +0). - - That needs every intermediate in the f32 normal range, so the operands are first scaled by powers of two, - which is exact, and the result scaled back: by 2^-64 when the product or z is at least 2^126 (the product may - overflow while z brings the sum back into range; a z below 2^-62 there, which would scale out of the normal - range, becomes a signed 2^-126, see below), by 2^96 when both are tiny (|x*y| < 2^-76 and - |z| < 2^-46), and a factor below 2^-100 is traded 2^64 against one above 2^-20, so the low split halves stay - normal on a driver that flushes f32 denormals. Infinite or NaN operands, and finite ones whose product is - beyond even the scaled range (the result is +-inf), take the plain Fma, except that finite x and y with an - infinite z give z (a split Fma turns an overflowing x*y and the other infinity into a NaN), and normal x and y - with a zero z give the rounded x*y (the split path turns an underflowing negative product plus +0 into +0, not - -0). Exact (checked - against an exact rational reference in tests/semantic/test_fma_exact.py) for finite operands with a normal or - zero result, with f32 denormals kept or flushed; a result in the denormal range is scaled back with a second - rounding, and a denormal operand follows the driver's denormal mode, as for every f32 operation here.""" - t = self.tmp - one = "%f1" - - def op(name, *args, ty="%float"): - o = t() - self.emit(f"{o} = {name} {ty} {' '.join(args)}") - return o - - def mag(v): - return op("OpBitwiseAnd", op("OpBitcast", v, ty="%uint"), self.cu(0x7FFFFFFF), ty="%uint") - - def below(m, k): - return op("OpULessThan", m, self.cu(k), ty="%bool") - - def above(m, k): - return op("OpUGreaterThan", m, self.cu(k), ty="%bool") - - def sel(c, a, b): - return op("OpSelect", c, a, b) - - up64, dn64, up96, dn96 = (self.fconst(2.0 ** e) for e in (64, -64, 96, -96)) - mx, my, mz = mag(x), mag(y), mag(z) - p0 = op("OpFMul", x, y) - mp0 = mag(p0) - big = op("OpLogicalOr", above(mp0, 0x7E7FFFFF), above(mz, 0x7E7FFFFF), ty="%bool") # >= 2^126 (or inf) - tiny = self.emit_land(below(mp0, 0x19800000), below(mz, 0x28800000)) # < 2^-76, < 2^-46 - xsm = op("OpULessThan", mx, my, ty="%bool") - # big: the larger factor and z down by 2^64; tiny: the smaller factor and z up by 2^96; the result back. - fx = sel(big, sel(xsm, one, dn64), sel(tiny, sel(xsm, up96, one), one)) - fy = sel(big, sel(xsm, dn64, one), sel(tiny, sel(xsm, one, up96), one)) - fz = sel(big, dn64, sel(tiny, up96, one)) - fr = sel(big, up64, sel(tiny, dn96, one)) - x1, y1 = op("OpFMul", x, fx), op("OpFMul", y, fy) - # big and 0 < |z| < 2^-62: z * 2^-64 would drop below 2^-126 (to 0, or to a denormal a flushing driver drops). - # The product is at least 2^126, so its last bit is at least 2^79 and z can only break a tie of it; a signed - # 2^-126 keeps that, as v_div_fmas_f32 does for its own pre-scaling. - lost = self.emit_land(big, self.emit_land(above(mz, 0), below(mz, 0x20800000))) - zst = op("OpBitcast", op("OpBitwiseOr", op("OpBitwiseAnd", op("OpBitcast", z, ty="%uint"), self.cu(0x80000000), - ty="%uint"), self.cu(0x00800000), ty="%uint")) - z1 = sel(lost, zst, op("OpFMul", z, fz)) - # A factor below 2^-100 next to one above 2^-20: trade 2^64 between them (the product is unchanged). - mx1, my1 = mag(x1), mag(y1) - bx = self.emit_land(below(mx1, 0x0D800000), above(my1, 0x35800000)) - by = self.emit_land(below(my1, 0x0D800000), above(mx1, 0x35800000)) - xa = op("OpFMul", x1, sel(bx, up64, sel(by, dn64, one))) - ya = op("OpFMul", y1, sel(bx, dn64, sel(by, up64, one))) - # Dekker's product: p + pe = xa * ya, every partial product exact (12 x 12 bits). - p = op("OpFMul", xa, ya) - halves = [] - for v in (xa, ya): - hi = op("OpBitcast", op("OpBitwiseAnd", op("OpBitcast", v, ty="%uint"), self.cu(0xFFFFF000), ty="%uint")) - halves += [hi, op("OpFSub", v, hi)] - xh, xl, yh, yl = halves - t1 = op("OpFSub", op("OpFMul", xh, yh), p) - t2 = op("OpFAdd", t1, op("OpFMul", xh, yl)) - t3 = op("OpFAdd", t2, op("OpFMul", xl, yh)) - pe = op("OpFAdd", t3, op("OpFMul", xl, yl)) - - def two_sum(a, b): - s = op("OpFAdd", a, b) - bb = op("OpFSub", s, a) - e = op("OpFAdd", op("OpFSub", a, op("OpFSub", s, bb)), op("OpFSub", b, bb)) - return s, e - - th, tl = two_sum(p, z1) - # v = tl + pe rounded to odd: the nearest sum, moved one ulp towards its error when inexact and even. - s, e = two_sum(tl, pe) - sbits, ebits = op("OpBitcast", s, ty="%uint"), op("OpBitcast", e, ty="%uint") - even = op("OpIEqual", op("OpBitwiseAnd", sbits, self.cu(1), ty="%uint"), self.cu(0), ty="%bool") - inexact = self.emit_land(op("OpFUnordNotEqual", e, "%f0", ty="%bool"), op("OpFOrdEqual", e, e, ty="%bool")) - same = below(op("OpBitwiseXor", sbits, ebits, ty="%uint"), 0x80000000) # same sign: away from zero - adj = op("OpSelect", same, op("OpIAdd", sbits, self.cu(1), ty="%uint"), - op("OpISub", sbits, self.cu(1), ty="%uint"), ty="%uint") - v = op("OpBitcast", op("OpSelect", self.emit_land(even, inexact), adj, sbits, ty="%uint")) - rs = sel(op("OpFOrdEqual", v, "%f0", ty="%bool"), th, op("OpFAdd", th, v)) - # z = +-0 with normal x and y: the exact x*y + z is x*y, which is not zero, so the one rounding of x*y is the - # result. The split path loses the sign of a product that underflows even after the 2^96 scale: p rounds to - # -0, th = p + z1 is -0 + +0 = +0, and so is the result where the exact one is -0. - xy_normal = self.emit_land(above(mx, 0x007FFFFF), above(my, 0x007FFFFF)) - times = self.emit_land(op("OpIEqual", mz, self.cu(0), ty="%bool"), xy_normal) - rr = sel(times, p0, op("OpFMul", rs, fr)) - special = op("OpLogicalOr", op("OpLogicalOr", above(mx, 0x7F7FFFFF), above(my, 0x7F7FFFFF), ty="%bool"), - op("OpLogicalOr", above(mz, 0x7F7FFFFF), op("OpIsNan", rr, ty="%bool"), ty="%bool"), ty="%bool") - g = op("OpExtInst", "%glsl Fma", x, y, z) - # Finite x and y with an infinite z give z. A split Fma would round x*y first, and when that overflows to the - # other infinity the sum is a NaN. - xyfin = op("OpLogicalNot", op("OpLogicalOr", above(mx, 0x7F7FFFFF), above(my, 0x7F7FFFFF), ty="%bool"), - ty="%bool") - g = sel(self.emit_land(xyfin, op("OpIEqual", mz, self.cu(0x7F800000), ty="%bool")), z, g) - self.emit(f"{r} = OpSelect %float {special} {g} {rr}") - - def fma_f16_odd(self, x, y, z): - """fma(x, y, z) for f16 inputs (widened to f32), rounded to f32 with round-to-odd (SHADER-55). - - RDNA2's v_fma_f16 / v_fmac_f16 / v_pk_fma_f16 round once, to f16 (measured: 0 of 12,612 mismatches against a - correctly rounded f16 FMA on an RX 6700, #374). GLSL Fma rounds to f32 first, so narrowing it to f16 is a - double rounding that can be 1 ulp off. Here: x*y is exact in f32 (11-bit significands give 22 bits, and the - f16 range squared stays inside the f32 normal range), TwoSum splits p + z into the rounded sum s and its - exact error, and when the error is non-zero and s is even, s moves one f32 ulp towards the error. That makes - s the round-to-odd f32 value of the exact result, and round-to-odd at 24 bits then rounds correctly to any - format with at most 22 bits, so f16_bits gives the single-rounded f16. The FAdd/FMul carry NoContraction - (no_contraction), so the driver can't fuse or reorder TwoSum.""" - t = self.tmp - pr, s_, bb, sb, da, db, err = (t() for _ in range(7)) - self.emit(f"{pr} = OpFMul %float {x} {y}") - self.emit(f"{s_} = OpFAdd %float {pr} {z}") - self.emit(f"{bb} = OpFSub %float {s_} {pr}") - self.emit(f"{sb} = OpFSub %float {s_} {bb}") - self.emit(f"{da} = OpFSub %float {pr} {sb}") - self.emit(f"{db} = OpFSub %float {z} {bb}") - self.emit(f"{err} = OpFAdd %float {da} {db}") - sbits, ebits, lsb, even, nz, fin, need, same, xs, up, dn, adj, res, r = (t() for _ in range(14)) - self.emit(f"{sbits} = OpBitcast %uint {s_}") - self.emit(f"{ebits} = OpBitcast %uint {err}") - self.emit(f"{lsb} = OpBitwiseAnd %uint {sbits} {self.cu(1)}") - self.emit(f"{even} = OpIEqual %bool {lsb} {self.cu(0)}") - self.emit(f"{nz} = OpFUnordNotEqual %bool {err} %f0") # true for a NaN error too... - self.emit(f"{fin} = OpFOrdEqual %bool {err} {err}") # ...so require a non-NaN error - self.emit(f"{need} = OpLogicalAnd %bool {even} {self.emit_land(nz, fin)}") - self.emit(f"{xs} = OpBitwiseXor %uint {sbits} {ebits}") - self.emit(f"{same} = OpULessThan %bool {xs} {self.cu(0x80000000)}") # same sign: away from zero - self.emit(f"{up} = OpIAdd %uint {sbits} {self.cu(1)}") - self.emit(f"{dn} = OpISub %uint {sbits} {self.cu(1)}") - self.emit(f"{adj} = OpSelect %uint {same} {up} {dn}") - self.emit(f"{res} = OpSelect %uint {need} {adj} {sbits}") - self.emit(f"{r} = OpBitcast %float {res}") - return r - - def fma_mix_odd(self, x, y, z): - """fma(x, y, z) for f32 operands rounded to f32 with round-to-odd, so that narrowing it to f16 in any direction - gives the exactly rounded f16 (the hardware rounds v_fma_mix once, straight to f16, under MODE toward zero). - Unlike fma_f16_odd the product is not exact in f32: r = Fma (nearest) is corrected by the sign of - exact - r = (s - r) + (se + pe), where p = x*y, pe = Fma(x, y, -p) is the exact product error, s = p + z and se - the TwoSum error of that sum. When that is non-zero and r is even, r moves one f32 ulp towards it (the exact - value lies between r and its neighbour, so the neighbour is the odd one). A zero, infinite or NaN r is - left alone (an f32 subnormal narrows to +-0 either way), except that a finite exact value whose f32 Fma - overflowed to +-inf becomes +-FLT_MAX (toward zero it is 65504 in f16). A tiny product takes the residual - sign from its operands (below). Sign-exact except where se + pe itself rounds to the opposite side of - s - r, which needs an f32-ulp-level cancellation, or where x*y overflows while z cancels it.""" - t = self.tmp - r, p, np_, pe, s_, bb, sb, da, db, se = (t() for _ in range(10)) - self.emit_fma(r, x, y, z) - self.emit(f"{p} = OpFMul %float {x} {y}") - self.emit(f"{np_} = OpFNegate %float {p}") - self.emit_fma(pe, x, y, np_) - self.emit(f"{s_} = OpFAdd %float {p} {z}") - self.emit(f"{bb} = OpFSub %float {s_} {p}") - self.emit(f"{sb} = OpFSub %float {s_} {bb}") - self.emit(f"{da} = OpFSub %float {p} {sb}") - self.emit(f"{db} = OpFSub %float {z} {bb}") - self.emit(f"{se} = OpFAdd %float {da} {db}") - tt, d0, res = t(), t(), t() - self.emit(f"{tt} = OpFAdd %float {se} {pe}") - self.emit(f"{d0} = OpFSub %float {s_} {r}") - self.emit(f"{res} = OpFAdd %float {d0} {tt}") - rbits, mag, lsb, even, nzr, ok, need = (t() for _ in range(7)) - self.emit(f"{rbits} = OpBitcast %uint {r}") - self.emit(f"{mag} = OpBitwiseAnd %uint {rbits} {self.cu(0x7FFFFFFF)}") - self.emit(f"{lsb} = OpBitwiseAnd %uint {rbits} {self.cu(1)}") - self.emit(f"{even} = OpIEqual %bool {lsb} {self.cu(0)}") - self.emit(f"{nzr} = OpULessThan %bool {self.cu(0)} {mag}") - self.emit(f"{ok} = OpULessThan %bool {mag} {self.cu(0x7F800000)}") # finite - rnz, rfin = t(), t() - self.emit(f"{rnz} = OpFUnordNotEqual %bool {res} %f0") # true for a NaN residual too... - self.emit(f"{rfin} = OpFOrdEqual %bool {res} {res}") # ...so require a non-NaN one - inexact = self.emit_land(rnz, rfin) - # A tiny product (|x*y| < 2^-64, or flushed to 0) has its error pe below the f32 normal range (pe's lowest bit is - # 2^-47 of p's), so pe and the residual can underflow or be flushed and read as exact. z dominates there - # (anything the f16 result can see has an f32 ulp far above 2^-64), so the residual's sign is the - # product's: sign(x) xor sign(y), whatever the driver does with denormals. - xb, yb, pb, pmag, ptiny, xnz, ynz, tiny, tsign, ebits0 = (t() for _ in range(10)) - self.emit(f"{pb} = OpBitcast %uint {p}") - self.emit(f"{pmag} = OpBitwiseAnd %uint {pb} {self.cu(0x7FFFFFFF)}") - self.emit(f"{ptiny} = OpULessThan %bool {pmag} {self.cu(0x1F800000)}") - self.emit(f"{xnz} = OpFUnordNotEqual %bool {x} %f0") - self.emit(f"{ynz} = OpFUnordNotEqual %bool {y} %f0") - self.emit(f"{tiny} = OpLogicalAnd %bool {ptiny} {self.emit_land(xnz, ynz)}") - self.emit(f"{xb} = OpBitcast %uint {x}") - self.emit(f"{yb} = OpBitcast %uint {y}") - self.emit(f"{tsign} = OpBitwiseXor %uint {xb} {yb}") - inexact2, ebits = t(), t() - self.emit(f"{inexact2} = OpLogicalOr %bool {inexact} {tiny}") - self.emit(f"{need} = OpLogicalAnd %bool {self.emit_land(even, inexact2)} {self.emit_land(nzr, ok)}") - self.emit(f"{ebits0} = OpBitcast %uint {res}") - self.emit(f"{ebits} = OpSelect %uint {tiny} {tsign} {ebits0}") - xs, same, up, dn, adj, out, rr = (t() for _ in range(7)) - self.emit(f"{xs} = OpBitwiseXor %uint {rbits} {ebits}") - self.emit(f"{same} = OpULessThan %bool {xs} {self.cu(0x80000000)}") # same sign: away from zero - self.emit(f"{up} = OpIAdd %uint {rbits} {self.cu(1)}") - self.emit(f"{dn} = OpISub %uint {rbits} {self.cu(1)}") - self.emit(f"{adj} = OpSelect %uint {same} {up} {dn}") - self.emit(f"{out} = OpSelect %uint {need} {adj} {rbits}") - self.emit(f"{rr} = OpBitcast %float {out}") - # Fma overflowed to +-inf with finite operands: the exact value is finite, so toward zero it is +-FLT_MAX. - ri, xi, yi, zi, anyi, ovf, sg, mx, fin, rfl = (t() for _ in range(10)) - self.emit(f"{ri} = OpIsInf %bool {r}") - self.emit(f"{xi} = OpIsInf %bool {x}") - self.emit(f"{yi} = OpIsInf %bool {y}") - self.emit(f"{zi} = OpIsInf %bool {z}") - xyi, nai = t(), t() - self.emit(f"{xyi} = OpLogicalOr %bool {xi} {yi}") - self.emit(f"{anyi} = OpLogicalOr %bool {xyi} {zi}") - self.emit(f"{nai} = OpLogicalNot %bool {anyi}") - self.emit(f"{ovf} = OpLogicalAnd %bool {ri} {nai}") - self.emit(f"{sg} = OpBitwiseAnd %uint {rbits} {self.cu(0x80000000)}") - self.emit(f"{mx} = OpBitwiseOr %uint {sg} {self.cu(0x7F7FFFFF)}") - self.emit(f"{fin} = OpSelect %uint {ovf} {mx} {out}") - self.emit(f"{rfl} = OpBitcast %float {fin}") - return rfl - - def emit_land(self, a, b): - r = self.tmp() - self.emit(f"{r} = OpLogicalAnd %bool {a} {b}") - return r - - def eager(self, ty, val): - """val (a %uint or %bool), stored to a Function variable of its own and loaded back (SHADER-529). - - SPIRV-Cross (MoltenVK) inlines a result used once into the expression that uses it. On the right of an - OpLogicalAnd/OpLogicalOr that is a short-circuiting && / ||, and in an arm of a scalar OpSelect a ternary, - so a subgroup op there runs only in the lanes that get that far: a ballot misses the other lanes' bits and - a shuffle reads from lanes that never ran it. A store is a statement, which every lane runs.""" - ptr = {"%uint": "%_ptr_Function_uint", "%bool": "%_ptr_Function_bool"}[ty] - var = f"%eager{len(self.eager_vars)}" - self.eager_vars.append((var, ptr)) - self.emit(f"OpStore {var} {val}") - r = self.tmp() - self.emit(f"{r} = OpLoad {ty} {var}") - return r - - def f16_pack2(self, lo, hi, exact_tiny=False): - """Two f32 values -> one %uint of two f16 halves (lo | hi << 16), each rounded as f16_res, without PackHalf2x16.""" - a, b, sh, r = self.f16_res(lo, exact_tiny), self.f16_res(hi, exact_tiny), self.tmp(), self.tmp() - self.emit(f"{sh} = OpShiftLeftLogical %uint {b} {self.cu(16)}") - self.emit(f"{r} = OpBitwiseOr %uint {a} {sh}") - return r - - def put_f16_bits(self, d, lo, hi=0): - """Write 16-bit %uint ``lo`` into the low half of ``d``, or to the high half when ``hi``, keeping the other half.""" - if not hi: - self.write_lo16(d, lo) - return - if d["k"] != "vgpr": - raise Unsupported("op_sel destination") - old, keep, sh16, v = (self.tmp() for _ in range(4)) - self.emit(f"{old} = OpCopyObject %uint {self.load_reg('vgpr', d['r'])}") - self.emit(f"{keep} = OpBitwiseAnd %uint {old} {self.cu(0xFFFF)}") - self.emit(f"{sh16} = OpShiftLeftLogical %uint {lo} {self.cu(16)}") - self.emit(f"{v} = OpBitwiseOr %uint {keep} {sh16}") - self.dst(d, v) - - def f16_out(self, d, r, hi=0, fract=False, mode=True, exact_tiny=False): - """Narrow f32 ``r`` to f16 (f16_res: nearest even, or toward zero under MODE) and write it to the low half of ``d``, or to the high half when - ``hi`` (op_sel destination bit). Either way the other half is kept (see write_lo16). - ``fract`` (v_fract_f16): a result that rounded up to 1.0 (0x3c00) becomes 0x3bff, the largest f16 below 1, - as on hardware (docs/design.md, float min/max/med3 with NaN and v_fract).""" - lo = self.f16_res(r, exact_tiny) if mode else self.f16_bits(r) # mode=False: the op ignores MODE rounding (rcp/rsq/sqrt) - if fract: - one, below = self.tmp(), self.tmp() - self.emit(f"{one} = OpIEqual %bool {lo} {self.cu(0x3C00)}") - self.emit(f"{below} = OpSelect %uint {one} {self.cu(0x3BFF)} {lo}") - lo = below - self.put_f16_bits(d, lo, hi) - - def f16_roundtrip(self, f): - """f32 -> f16 -> f32 (round to nearest; f16 denormals flushed to signed zero), modelling a 32-bit - v_interp read of a 16-bit interpolant (FSSM pixel-input table flag bit 4 marks the position; see - the PS input path in translate). - - OpQuantizeToF16 returns +0 or -0 when the magnitude is too small for a normal f16, and the spec - pins no rounding mode (round-to-nearest is measured on hardware, not guaranteed). Do not reuse - this helper where f16 denormals or a specific rounding mode matter. - - Single OpQuantizeToF16 instruction on purpose: a PackHalf2x16/UnpackHalf2x16 round-trip is - observably folded to a no-op by at least one Vulkan driver (RTX 5080, validated), while a lone - OpQuantizeToF16 is implemented as a real conversion.""" - r = self.tmp() - self.emit(f"{r} = OpQuantizeToF16 %float {f}") - return r - - def f16_rtz(self, f): - """f32 -> f16 bits (low 16) with round-toward-zero, as v_cvt_pkrtz does. Finite values above the f16 range - become +-65504, never inf; inf/NaN stay inf/NaN. Integer-only (f16_bits): the earlier PackHalf2x16 -> - UnpackHalf2x16 -> compare version relied on the round trip not being folded, and on llvmpipe and NVIDIA - it was (FUZZ-2: v_cvt_pkrtz_f16_f32 gave the nearest value, one ulp above RTZ).""" - return self.f16_bits(f, rtz=True) - - def modify_f(self, f, a): - return self.tof(self.modify(self.tou(f), a)) - - def host_addr(self, xbox_va): - """Xbox GPU virtual address (ulong id) -> host buffer device address: heap base (push constant - dwords 32..33) + VA. The runtime maps the console's GPU address window into one host buffer. The base is - %heap_base, built once in the entry block (HEAP_BASE_ENTRY): it was six instructions at every access.""" - r = self.tmp() - self.emit(f"{r} = OpIAdd %ulong %heap_base {xbox_va}") - self.uses_heap = True - self.cu(1), self.cu(2) # member indices of the push-constant block, declared before assembly - return r - - def tof(self, u): - """The %float with the bits of %uint u. Bitcasting a tou result back gives tou's argument (Gen.bitcast_from), - so u must be a %uint and tou's argument a %float; an %int's bits go through int_bits.""" - if u in self.bitcast_from: - return self.bitcast_from[u] - f = self.tmp() - self.emit(f"{f} = OpBitcast %float {u}") - self.bitcast_from[f] = u - return f - - def tou(self, f): - if f in self.bitcast_from: - return self.bitcast_from[f] - u = self.tmp() - self.emit(f"{u} = OpBitcast %uint {f}") - self.bitcast_from[u] = f - return u - - def int_bits(self, i): - """The %uint bits of %int i. Not tou: tou remembers its argument, which tof would then return as a %float.""" - u = self.tmp() - self.emit(f"{u} = OpBitcast %uint {i}") - return u - def src_f(self, a): - return self.tof(self.src_u(a)) - - # ---- EXEC (this lane's active bit) ---- - def active_b(self): - if self.exec_static_true: - return "%true" - if self.cache_active: - if self._active_ssa is None: - b = self.tmp() - self.emit(f"{b} = OpLoad %bool %active") - self._active_ssa = b - return self._active_ssa - b = self.tmp() - self.emit(f"{b} = OpLoad %bool %active") - return b - - def exec_value(self): - """EXEC as a lane mask for this invocation: all-ones if active, else 0.""" - if self.exec_static_true: - return self.cu(0xFFFFFFFF) - r = self.tmp() - self.emit(f"{r} = OpSelect %uint {self.active_b()} {self.cu(0xFFFFFFFF)} {self.cu(0)}") - return r - - def exec_bit(self, word): - """Bit L of a 32-bit value written to EXEC as data, as this invocation's 0 or 1: a computed value is one - bit per lane (`s_lshl_b32 exec_lo, 1, s5` sets lane 3). A value that already holds this lane's bit of a - mask (0 or ~0, `lane_masks.py`) gives the same answer, so no caller needs to say which it has.""" - sh, shr, bit = self.tmp(), self.tmp(), self.tmp() - self.emit(f"{sh} = OpBitwiseAnd %uint {self.wave_lane()} {self.cu(31)}") - self.emit(f"{shr} = OpShiftRightLogical %uint {word} {sh}") - self.emit(f"{bit} = OpBitwiseAnd %uint {shr} {self.cu(1)}") - return bit - - def set_exec(self, mask_u): - self.emit(f"OpStore %active {self.tmp_bool_nz(mask_u)}") - self.uses_active = True - - def vcc_half_keeps_mask(self): - """Whether the current wave64 vcc_lo / vcc_hi write keeps VCC as a lane mask (put_mask on that half) rather - than replacing it with plain scalar data (s_buffer_load_dword vcc_lo, scalar ALU, non-mask constant, ...).""" - if "vcc" not in self.cur_masks: - return False - if self.cur_ins is None: - return True - st = dict(self.cur_masks) - for x in self.cur_ins["args"][1:]: - if x.get("k") == "sgpr" and x.get("n", 1) == 1: - r = x["r"] - if r not in st and self.sgpr_imm.get(r) in (0, 0xFFFFFFFF): - st[r] = lane_masks.EITHER - lane_masks.step(st, self.cur_ins, self.wave64) - return st.get("vcc") in lane_masks.MASK_KINDS - - def dst(self, a, val, *, eager=False): - if a.get("sdwa_dst") and a["k"] == "vgpr": - val = self.sdwa_dst(a, val) - if a["k"] == "special" and a["t"] == "null": - return # result discarded - if self.wave64 and a["k"] == "special" and a["t"] in ("exec_lo", "exec_hi"): - self.exec_half_write(1 if a["t"] == "exec_hi" else 0, self.exec_bit(val)) - return - if a["k"] == "special" and a["t"] in ("exec_lo", "exec"): - self.set_exec(self.exec_bit(val)) - return - if a["k"] == "vgpr" and a.get("n", 1) == 1: - # VALU writes only land in active lanes. The exception is a lane mask on its way through a VGPR - # (lane_masks.py): every lane works out its own bit of it, active or not. Inside an active run - # (insns) the enclosing `if (active)` already leaves inactive lanes out, and when the shader never - # modifies EXEC (`exec_static_true`) every lane is always active (DPP is guarded separately). - if self.write_all_lanes or ((self.active_run or self.exec_static_true) and self.dpp_guard is None): - self.store_reg("vgpr", a["r"], val) - return - p = self.reg_ptr("vgpr", a["r"]) - old, r = self.tmp(), self.tmp() - self.emit(f"{old} = OpLoad %uint {p}") - if eager: - mask = self.exec_value() - if self.dpp_guard is not None: - guarded = self.tmp() - self.emit(f"{guarded} = OpSelect %uint {self.dpp_guard} {mask} {self.cu(0)}") - mask = guarded - keep, write, preserve = self.tmp(), self.tmp(), self.tmp() - self.emit(f"{keep} = OpNot %uint {mask}") - self.emit(f"{write} = OpBitwiseAnd %uint {val} {mask}") - self.emit(f"{preserve} = OpBitwiseAnd %uint {old} {keep}") - self.emit(f"{r} = OpBitwiseOr %uint {write} {preserve}") - else: - active = self.active_b() - if self.dpp_guard is not None: - guarded = self.tmp() - self.emit(f"{guarded} = OpLogicalAnd %bool {active} {self.dpp_guard}") - active = guarded - self.emit(f"{r} = OpSelect %uint {active} {val} {old}") - self.emit(f"OpStore {p} {r}") - elif a["k"] == "sgpr" and a.get("n", 1) == 1: - self.store_reg(a["k"], a["r"], val) - elif self.wave64 and a["k"] == "special" and a["t"] in ("vcc_lo", "vcc_hi") and self.vcc_half_keeps_mask(): - # One half of a wave64 VCC lane mask (VCC_LO = VCC[31:0], VCC_HI = VCC[63:32]): the other half's lanes - # keep their bit, as for exec_lo / exec_hi. %vcc_hi still gets the word for a later read as data. - self.put_mask(a, val, a["t"][-2:]) - if a["t"] == "vcc_hi": - self.emit(f"OpStore %vcc_hi {val}") - elif a["k"] == "special" and a["t"] in ("vcc_lo", "vcc"): - self.emit(f"OpStore %vcc {val}") - elif a["k"] == "special" and a["t"] == "m0": - self.emit(f"OpStore %m0 {val}") - elif a["k"] == "special" and a["t"] == "vcc_hi": - self.emit(f"OpStore %vcc_hi {val}") - elif a["k"] == "special" and a["t"] == "scc": - self.emit(f"OpStore %scc {val}") - else: - raise Unsupported(f"destination {a.get('t', a['k'])}") - - # ---- runs of lane-local VALU instructions under one `if (active)` ---- - def lane_local(self, ins): - """True when ins only reads and writes this invocation's own registers, and its VGPR writes are the only - ones EXEC gates. Each invocation is one lane, so skipping it where the lane is inactive is the same as - keeping the old value of everything it writes: what dst()'s per-write OpSelect does. A lane mask read as - data is this lane's bit (only s_bcnt1, s_ff1 and v_mbcnt gather the whole wave's); a mask on its way - through a VGPR (mask_writes) is written in every lane, so it stays out.""" - op = base_op(ins["op"]) - a = ins["args"] - return (op.startswith("v_") and op not in NOOPS and not op.startswith(NOT_LANE_LOCAL) and "_co_" not in op - and not ins["op"].endswith("_dpp") and not any(m.startswith(DPP_MODS) for m in ins["mods"]) - and bool(a) and a[0]["k"] == "vgpr" and id(ins) not in self.mask_writes) - - def insns(self, seq): - """Translate seq, a straight run of instructions (no branch among them). A run of at least MIN_ACTIVE_RUN - lane-local VALU instructions goes inside one `if (active)` and writes its VGPRs directly: the driver - then predicates it with its own EXEC, instead of keeping the old and new value of every register live for - an OpSelect per write. Only in a shader that may write EXEC (elsewhere %active stays true and the driver - folds the selects away), and not under --wave64-emulate, whose rounds split blocks at instruction - boundaries.""" - local = [self.exec_changes and not self.emulate and self.lane_local(i) for i in seq] - i = 0 - while i < len(seq): - j = i - while j < len(seq) and local[j]: - j += 1 - if j - i < MIN_ACTIVE_RUN: - self.insn(seq[i]) - i += 1 - continue - act = self.active_b() - do, end = self.tmp() + "_run", self.tmp() + "_end" - self.emit(f"OpSelectionMerge {end} None") - self.emit(f"OpBranchConditional {act} {do} {end}") - self.emit(f"{do} = OpLabel") - self.active_run = True - for ins in seq[i:j]: - start = len(self.body) - self.insn(ins) - self.check_lane_local(ins, self.body[start:]) - self.active_run = False - self.emit(f"OpBranch {end}") - self.emit(f"{end} = OpLabel") - i = j - - @staticmethod - def may_write_exec(ins): - """Whether ins can change EXEC: it names EXEC as an operand, or is a v_cmpx or an s_*_saveexec. A wrong - guess either way only costs speed (runs where EXEC never changes, or per-write selects where it does).""" - op = base_op(ins["op"]) - return ("saveexec" in op or op.startswith("v_cmpx") - or any(x["k"] == "special" and x.get("t", "").startswith("exec") for x in ins["args"])) - - # What a lane-local instruction may emit inside an active run: anything but these (other lanes, side effects, - # control flow out of the run) and stores to registers other than the VGPR file. - RUN_FORBIDDEN = ("OpGroup", "OpControlBarrier", "OpMemoryBarrier", "OpImage", "OpDPd", "OpFwidth", "OpAtomic", - "OpKill", "OpTerminateInvocation", "OpDemoteToHelperInvocation", "OpEmit", "OpEndPrimitive", - "OpReturn", "OpFunctionCall", "OpLoopMerge") - - def check_lane_local(self, ins, lines): - """Fail loudly if ins, judged lane-local, emitted something an active run can't hold.""" - # hoisted register pointers (#4440) are declared once in %entry, so they never appear in these lines - vgpr_ptrs = {p for (kind, _), p in self.reg_ptrs.items() if kind == "vgpr"} - for line in lines: - s = line.strip() - words = s.split() - if len(words) > 4 and words[2] == "OpAccessChain" and words[4] == "%vgpr": - vgpr_ptrs.add(words[0]) - bad = (s.split(" = ")[-1].startswith(self.RUN_FORBIDDEN) - or (s.startswith("OpStore ") and words[1] not in vgpr_ptrs)) - if bad: - raise AssertionError(f"{ins['op']} is not lane-local inside an active run: {s}") - - def mov64(self, d, s): - """64-bit scalar move, including EXEC save/restore (EXEC = this lane's active bit).""" - if d["k"] == "special" and d["t"] == "exec": - self.set_exec(self.mask_src(s)) - return - if d["k"] == "special" and d["t"] in ("vcc", "vcc_lo"): - self.emit(f"OpStore %vcc {self.mask_src(s)}") - return - if d["k"] != "sgpr" or d.get("n") != 2: - raise Unsupported("s_mov_b64 destination") - lit_lo = lit_hi = None - if s["k"] == "special" and s["t"] == "exec": - lo = hi = self.exec_value() - elif s["k"] == "sgpr" and s.get("n") == 2: - lit_lo = self.sgpr_imm.get(s["r"]) - lit_hi = self.sgpr_imm.get(s["r"] + 1) - lo, hi = self.load_reg("sgpr", s["r"]), self.load_reg("sgpr", s["r"] + 1) - elif s["k"] == "imm": - v = s["v"] & 0xFFFFFFFFFFFFFFFF - if s["v"] < 0: - v = s["v"] & 0xFFFFFFFFFFFFFFFF - lit_lo = v & 0xFFFFFFFF - lit_hi = (v >> 32) & 0xFFFFFFFF - lo, hi = self.cu(lit_lo), self.cu(lit_hi) - elif s["k"] == "special" and s["t"] == "vcc": - lo = hi = self.tmp() # this lane's bit in both halves, as for EXEC - self.emit(f"{lo} = OpLoad %uint %vcc") - else: - raise Unsupported("s_mov_b64 source") - self.store_reg("sgpr", d["r"], lo) - self.store_reg("sgpr", d["r"] + 1, hi) - if self.desc_cache_ok(): - if lit_lo is not None: - self.sgpr_imm[d["r"]] = lit_lo - if lit_hi is not None: - self.sgpr_imm[d["r"] + 1] = lit_hi - - def compare(self, op, a, scalar, exec_only=False, mods=()): - """v_cmp_* / s_cmp_*: lane result into VCC/SGPR mask (vector), SCC (scalar), or EXEC (v_cmpx).""" - parts = op.split("_") # v_cmp_lt_f32 / s_cmp_eq_u32 - cond, ty = parts[2], parts[3] - srcs = a[0:2] if scalar else a[-2:] - dst = None if (scalar or exec_only) else a[0] - if not scalar and ty in ("f64", "i64", "u64") and cond in ("f", "tru" if ty == "f64" else "t"): - # The sources do not affect a constant predicate, even when a double is NaN. - self.write_compare_result("%false" if cond == "f" else "%true", dst, scalar, exec_only) - return - if ty in ("f32", "f16"): - if ty == "f32": - x, y = self.src_f(srcs[0]), self.src_f(srcs[1]) - else: # f16 compare: op_sel selects lo/hi half of each source, compared as f32 (exact for f16 values) - sel, _ = self.opsel_bits(mods, 2) - x, y = self.f16_in(srcs[0], sel[0]), self.f16_in(srcs[1], sel[1]) - ops = {"lt": "OpFOrdLessThan", "le": "OpFOrdLessThanEqual", "gt": "OpFOrdGreaterThan", - "ge": "OpFOrdGreaterThanEqual", "eq": "OpFOrdEqual", "neq": "OpFUnordNotEqual", - "lg": "OpFOrdNotEqual", "nlg": "OpFUnordEqual", "nlt": "OpFUnordGreaterThanEqual", - "ngt": "OpFUnordLessThanEqual", "nle": "OpFUnordGreaterThan", "nge": "OpFUnordLessThan"} - elif ty in ("u16", "i16"): - sel, _ = self.opsel_bits(mods, 2) - x, y = self.src_u(srcs[0]), self.src_u(srcs[1]) - xs, ys = self.tmp(), self.tmp() - f = "OpBitFieldSExtract" if ty == "i16" else "OpBitFieldUExtract" - self.emit(f"{xs} = {f} %uint {x} {self.cu(16 if sel[0] else 0)} {self.cu(16)}") - self.emit(f"{ys} = {f} %uint {y} {self.cu(16 if sel[1] else 0)} {self.cu(16)}") - x, y = xs, ys - if ty == "i16": - x, y = self.as_int(x), self.as_int(y) - s = ty == "i16" - ops = {"lt": "OpSLessThan" if s else "OpULessThan", "le": "OpSLessThanEqual" if s else "OpULessThanEqual", - "gt": "OpSGreaterThan" if s else "OpUGreaterThan", - "ge": "OpSGreaterThanEqual" if s else "OpUGreaterThanEqual", - "eq": "OpIEqual", "ne": "OpINotEqual", "lg": "OpINotEqual"} - elif ty in ("u32", "i32"): - use_wave_equal = False - wave_equal_half = None - m0, m1 = self.holds_lane_mask(srcs[0]), self.holds_lane_mask(srcs[1]) - if scalar and (m0 or m1): - h0 = self.mask_half(srcs[0]) if m0 else None - h1 = self.mask_half(srcs[1]) if m1 else None - - def _is_u32_zero_or_all_ones(src): - return src["k"] == "imm" and (src["v"] & 0xFFFFFFFF) == 0 - - can_vote = False - if cond in ("eq", "ne", "lg"): - if m0 and m1: - if not self.wave64: - can_vote = h0 != "hi" and h1 != "hi" - elif h0 is not None and h0 == h1: - can_vote = True - wave_equal_half = h0 - else: - other = srcs[1] if m0 else srcs[0] - mh = h0 if m0 else h1 - if _is_u32_zero_or_all_ones(other): - if not self.wave64: - can_vote = mh != "hi" - elif mh is not None: - can_vote = True - wave_equal_half = mh - - if can_vote: - use_wave_equal = True - x, y = self.src_u(srcs[0]), self.src_u(srcs[1]) - else: - def _mask_word(src, is_mask): - if not is_mask: - return self.src_u(src) - lo, hi = self.wave_mask(src) - return hi if self.mask_half(src) == "hi" else lo - x, y = _mask_word(srcs[0], m0), _mask_word(srcs[1], m1) - else: - x, y = self.src_u(srcs[0]), self.src_u(srcs[1]) - if ty == "i32": - x, y = self.as_int(x), self.as_int(y) - s = ty == "i32" - ops = {"lt": "OpSLessThan" if s else "OpULessThan", "le": "OpSLessThanEqual" if s else "OpULessThanEqual", - "gt": "OpSGreaterThan" if s else "OpUGreaterThan", - "ge": "OpSGreaterThanEqual" if s else "OpUGreaterThanEqual", - "eq": "OpIEqual", "ne": "OpINotEqual", "lg": "OpINotEqual"} - elif ty == "f64" and not scalar: - b = self.compare_f64_cond(op, cond, srcs, mods) - self.write_compare_result(b, dst, False, exec_only) - return - else: - raise Unsupported(op) - is_float = ty in ("f32", "f16") - b = self.tmp() - if cond in (("f", "tru", "o", "u") if is_float else ("f", "t")): - # Constant compares: f is always false, t / tru always true. o (ordered) is true when neither source - # is NaN, u (unordered) when either is. - if cond in ("o", "u"): - nx, ny, either = self.tmp(), self.tmp(), self.tmp() - self.emit(f"{nx} = OpIsNan %bool {x}") - self.emit(f"{ny} = OpIsNan %bool {y}") - self.emit(f"{either} = OpLogicalOr %bool {nx} {ny}") - if cond == "u": - b = either - else: - self.emit(f"{b} = OpLogicalNot %bool {either}") - else: - self.emit(f"{b} = OpCopyObject %bool {'%false' if cond == 'f' else '%true'}") - elif cond not in ops: - raise Unsupported(op) - elif is_float and cond == "lg": - # LG is ordered (false when either source is NaN), as less-or-greater. Not OpFOrdNotEqual: SPIRV-Cross - # (MoltenVK) writes that as `!=`, which is true on a NaN. - lt, gt = self.tmp(), self.tmp() - self.emit(f"{lt} = OpFOrdLessThan %bool {x} {y}") - self.emit(f"{gt} = OpFOrdGreaterThan %bool {x} {y}") - self.emit(f"{b} = OpLogicalOr %bool {lt} {gt}") - else: - self.emit(f"{b} = {ops[cond]} %bool {x} {y}") - if scalar and ty in ("u32", "i32") and use_wave_equal: - b = self.wave_equal(b, cond == "eq", half=wave_equal_half) - self.write_compare_result(b, dst, scalar, exec_only) - - def write_compare_result(self, b: str, dst: dict | None, scalar: bool, exec_only: bool) -> None: - r = self.tmp() - # Lane masks are all-ones/zero per invocation (one lane), SCC is 1/0. A VOPC result bit is 0 for lanes - # that are off in EXEC (as on hardware), so wave-wide reductions of the mask (s_cbranch_vccz) are exact. - bm = b - if not scalar and not exec_only: - bm = self.tmp() - self.emit(f"{bm} = OpLogicalAnd %bool {b} {self.active_b()}") - self.emit(f"{r} = OpSelect %uint {bm} {self.cu(1 if scalar else 0xFFFFFFFF)} {self.cu(0)}") - if scalar: - self.emit(f"OpStore %scc {r}") - elif dst is None: # v_cmpx: EXEC &= cond - a2 = self.tmp() - self.emit(f"{a2} = OpLoad %bool %active") - a3 = self.tmp() - self.emit(f"{a3} = OpLogicalAnd %bool {a2} {b}") - self.emit(f"OpStore %active {a3}") - self.uses_active = True - else: - self.mask_dst(dst, r) - - def compare_x(self, op, a, mods=()): - """v_cmpx_*: like v_cmp but the result ANDs into EXEC. e32 form has only the two sources; e64 also names - a destination (vcc/sgpr) which gets the compare result too.""" - srcs = a[-2:] - self.compare("v_cmp_" + op[len("v_cmpx_"):], [None] + list(srcs), scalar=False, exec_only=True, mods=mods) - - def compare_f64_cond(self, op, cond, srcs, mods): - """Evaluate an IEEE-754 binary64 compare predicate using pure 32-bit integer ops (no Float64 capability, - denormal-safe). Supports all 16 RDNA2 float compare conditions (f, lt, eq, le, gt, lg, ge, o, u, nge, nlg, - ngt, nle, neq, nlt, tru).""" - unord_dual = {"nlt": "lt", "nle": "le", "ngt": "gt", "nge": "ge", "neq": "eq", "nlg": "lg"} - if cond not in ("f", "tru", "o", "u", "lt", "le", "gt", "ge", "eq", "lg") and cond not in unord_dual: - raise Unsupported(op) - if mods: - raise Unsupported(op + " modifiers") - - def emit_b(line): - t = self.tmp() - self.emit(f"{t} = {line}") - return t - - def read_f64_words(sv): - if sv["k"] in ("vgpr", "sgpr") and sv.get("n") == 2: - lo, hi = self.load_reg(sv["k"], sv["r"]), self.load_reg(sv["k"], sv["r"] + 1) - elif sv["k"] == "fimm": - bits = struct.unpack("> 32) - elif sv["k"] == "imm": - v = sv["v"] - if sv.get("literal") or (not (-16 <= v <= 64) and -0x80000000 <= v <= 0xFFFFFFFF): - lo, hi = self.cu(0), self.cu(v & 0xFFFFFFFF) - else: - bits = v & 0xFFFFFFFFFFFFFFFF - lo, hi = self.cu(bits & 0xFFFFFFFF), self.cu(bits >> 32) - else: - raise Unsupported(op + " operand") - if sv.get("abs"): - hi = emit_b(f"OpBitwiseAnd %uint {hi} {self.cu(0x7FFFFFFF)}") - if sv.get("neg"): - hi = emit_b(f"OpBitwiseXor %uint {hi} {self.cu(0x80000000)}") - return lo, hi - - alo, ahi = read_f64_words(srcs[0]) - blo, bhi = read_f64_words(srcs[1]) - if cond in ("f", "tru"): - return emit_b(f"OpCopyObject %bool {'%false' if cond == 'f' else '%true'}") - - def is_nan_words(lo, hi): - exp_m = emit_b(f"OpBitwiseAnd %uint {hi} {self.cu(0x7FF00000)}") - expmax = emit_b(f"OpIEqual %bool {exp_m} {self.cu(0x7FF00000)}") - man_hi = emit_b(f"OpBitwiseAnd %uint {hi} {self.cu(0x000FFFFF)}") - man_or = emit_b(f"OpBitwiseOr %uint {man_hi} {lo}") - man_nz = emit_b(f"OpINotEqual %bool {man_or} {self.cu(0)}") - return emit_b(f"OpLogicalAnd %bool {expmax} {man_nz}") - - nan_a, nan_b = is_nan_words(alo, ahi), is_nan_words(blo, bhi) - any_nan = emit_b(f"OpLogicalOr %bool {nan_a} {nan_b}") - if cond == "u": - return any_nan - ordered = emit_b(f"OpLogicalNot %bool {any_nan}") - if cond == "o": - return ordered - - def order_key(lo, hi): - # Canonicalize -0.0 to +0.0, then map IEEE-754 sign-magnitude to a monotonic unsigned 64-bit key. - abs_hi = emit_b(f"OpBitwiseAnd %uint {hi} {self.cu(0x7FFFFFFF)}") - mag_or = emit_b(f"OpBitwiseOr %uint {abs_hi} {lo}") - is_z = emit_b(f"OpIEqual %bool {mag_or} {self.cu(0)}") - c_hi = emit_b(f"OpSelect %uint {is_z} {self.cu(0)} {hi}") - sign = emit_b(f"OpShiftRightLogical %uint {c_hi} {self.cu(31)}") - is_neg = self.tmp_bool_nz(sign) - neg_hi = emit_b(f"OpNot %uint {c_hi}") - neg_lo = emit_b(f"OpNot %uint {lo}") - pos_hi = emit_b(f"OpBitwiseXor %uint {c_hi} {self.cu(0x80000000)}") - khi = emit_b(f"OpSelect %uint {is_neg} {neg_hi} {pos_hi}") - klo = emit_b(f"OpSelect %uint {is_neg} {neg_lo} {lo}") - return klo, khi - - aklo, akhi = order_key(alo, ahi) - bklo, bkhi = order_key(blo, bhi) - invert = cond in unord_dual - base = unord_dual.get(cond, cond) - hi_eq = emit_b(f"OpIEqual %bool {akhi} {bkhi}") - if base in ("eq", "lg"): - lo_eq = emit_b(f"OpIEqual %bool {aklo} {bklo}") - cmp_res = emit_b(f"OpLogicalAnd %bool {hi_eq} {lo_eq}") - if base == "lg": - cmp_res = emit_b(f"OpLogicalNot %bool {cmp_res}") - else: - hi_op = "OpULessThan" if base in ("lt", "le") else "OpUGreaterThan" - lo_op = {"lt": "OpULessThan", "le": "OpULessThanEqual", - "gt": "OpUGreaterThan", "ge": "OpUGreaterThanEqual"}[base] - hi_cmp = emit_b(f"{hi_op} %bool {akhi} {bkhi}") - lo_cmp = emit_b(f"{lo_op} %bool {aklo} {bklo}") - lo_tie = emit_b(f"OpLogicalAnd %bool {hi_eq} {lo_cmp}") - cmp_res = emit_b(f"OpLogicalOr %bool {hi_cmp} {lo_tie}") - ord_res = emit_b(f"OpLogicalAnd %bool {ordered} {cmp_res}") - return emit_b(f"OpLogicalNot %bool {ord_res}") if invert else ord_res - - def _validate_sopc_operand(self, op, src, *, is_64): - if src.get("neg") or src.get("abs") or src.get("sext"): - raise Unsupported(f"{op}: operand modifiers not supported on SOPC") - k = src.get("k") - if is_64: - if k == "sgpr" and src.get("n", 1) == 2: - return - if k == "imm": - return - if k == "special" and src.get("t") in SOPC_SRC64_SPECIALS: - return - raise Unsupported(f"{op}: expected 64-bit scalar operand") - if k == "sgpr" and src.get("n", 1) == 1: - return - if k in ("imm", "fimm"): - return - if k == "special" and src.get("t") in SOPC_SRC32_SPECIALS: - return - raise Unsupported(f"{op}: expected 32-bit scalar operand") - - def _validate_sopc(self, ins, op, a, mods, *, src0_64=False, src1_64=False): - if ins["op"] != op: - raise Unsupported(f"{ins['op']}: encoding suffix not supported on SOPC") - if mods: - raise Unsupported(f"{op}: modifiers not supported on SOPC") - if len(a) != 2: - raise Unsupported(f"{op}: expected 2 operands, got {len(a)}") - self._validate_sopc_operand(op, a[0], is_64=src0_64) - self._validate_sopc_operand(op, a[1], is_64=src1_64) - - def bitcmp(self, op, a): - """s_bitcmp0/1_b32/b64: test if bit (a[1]) of scalar a[0] is 0 or 1, result in SCC.""" - is_64 = op.endswith("b64") - test_one = op.startswith("s_bitcmp1") - if self.holds_lane_mask(a[0]): - lo, hi = self.wave_mask(a[0]) - if not is_64 and self.wave64: - half = self.mask_half(a[0]) - if half == "hi": - lo = hi - elif is_64 and a[0]["k"] == "sgpr" and a[0].get("n") == 2: - lo, hi = self.load_reg("sgpr", a[0]["r"]), self.load_reg("sgpr", a[0]["r"] + 1) - elif is_64 and a[0]["k"] == "imm": - v = a[0]["v"] & 0xFFFFFFFFFFFFFFFF - lo, hi = self.cu(v & 0xFFFFFFFF), self.cu(v >> 32) - elif is_64 and a[0]["k"] == "special" and a[0].get("t") == "null": - lo, hi = self.cu(0), self.cu(0) - elif is_64 and a[0]["k"] == "special" and a[0].get("t") == "vcc": - lo, hi = self.tmp(), self.tmp() - self.emit(f"{lo} = OpLoad %uint %vcc") - self.emit(f"{hi} = OpLoad %uint %vcc_hi") - elif is_64: - lo, hi = self.mask_src(a[0]), self.cu(0) - else: - lo = self.src_u(a[0]) - - sh = self.src_u(a[1]) - mask_bits = 63 if is_64 else 31 - m = self.tmp() - self.emit(f"{m} = OpBitwiseAnd %uint {sh} {self.cu(mask_bits)}") - - if is_64: - is_hi = self.tmp() - self.emit(f"{is_hi} = OpUGreaterThanEqual %bool {m} {self.cu(32)}") - word = self.tmp() - self.emit(f"{word} = OpSelect %uint {is_hi} {hi} {lo}") - sh32 = self.tmp() - self.emit(f"{sh32} = OpBitwiseAnd %uint {m} {self.cu(31)}") - else: - word = lo - sh32 = m - - shifted, bit = self.tmp(), self.tmp() - self.emit(f"{shifted} = OpShiftRightLogical %uint {word} {sh32}") - self.emit(f"{bit} = OpBitwiseAnd %uint {shifted} {self.cu(1)}") - cond = self.tmp() - self.emit(f"{cond} = {'OpINotEqual' if test_one else 'OpIEqual'} %bool {bit} {self.cu(0)}") - res = self.tmp() - self.emit(f"{res} = OpSelect %uint {cond} {self.cu(1)} {self.cu(0)}") - self.emit(f"OpStore %scc {res}") - - def swizzle(self, a, mods, ins): - """ds_swizzle_b32 vD, vS [offset:swizzle(...) | offset:N]: a subgroup shuffle (one invocation per lane).""" - line = " ".join(m for m in mods) + " " + " ".join(x.get("t", "") for x in a if x["k"] in ("special", "raw")) - import re as _re - text = line + " " + str(ins.get("raw", "")) - bm = _re.search(r'swizzle\(BITMASK_PERM,\s*"([01pi]{5})"\)', text) - m = _re.search(r"swizzle\((\w+)((?:,\s*\d+)*)\)", text) - and_m = or_m = xor_m = 0 - if bm: - kind, args = "BITMASK_PERM", [] - # One character per lane-index bit, bit 4 first: p = keep, i = invert, 0 / 1 = force. - # Source lane = ((lane & and_mask) | or_mask) ^ xor_mask, within each group of 32 lanes. - for k, ch in enumerate(bm.group(1)): - bit = 1 << (4 - k) - if ch in "pi": - and_m |= bit - if ch == "i": - xor_m |= bit - if ch == "1": - or_m |= bit - elif m: - kind = m.group(1) - args = [int(x) for x in m.group(2).split(",")[1:]] if m.group(2) else [] - else: - # Raw 16-bit DS_SWIZZLE_B32 offset (RDNA2 ISA): llvm-mc prints numeric offset:N when QDMode bits 13:8 - # are non-zero (e.g. 0x81e4 -> offset:33252) and omits offset: when it is 0. Measured across all 65,536 - # offsets on gfx1036: 0x0000..0x7FFF is bitmask mode, 0x8000..0xBFFF is QDMode (bits 13:8 ignored), and - # 0xC000..0xFFFF (bits 15:14 = 11) is a separate hardware mode (not a quad permute) and stays Unsupported. - if ("swizzle(" in text or len(mods) > 1 or len(a) != 2 or - any(x["k"] in ("special", "raw") for x in a) or - any(not mod.startswith("offset:") for mod in mods)): - raise Unsupported("ds_swizzle pattern") - off = 0 - if mods: - try: - off = int(mods[0][7:], 0) - except ValueError: - raise Unsupported("ds_swizzle pattern") from None - if not 0 <= off <= 0xBFFF: - raise Unsupported("ds_swizzle offset") - if off & 0x8000: - kind = "QUAD_PERM" - args = [(off >> (2 * i)) & 3 for i in range(4)] - else: - kind, args = "BITMASK_PERM", [] - and_m, or_m, xor_m = off & 0x1F, (off >> 5) & 0x1F, (off >> 10) & 0x1F - self.uses_subgroup = True - lane = self.tmp() - self.sub_lane(lane) - if kind == "BITMASK_PERM": - t1, t2, src = self.tmp(), self.tmp(), self.tmp() - self.emit(f"{t1} = OpBitwiseAnd %uint {lane} {self.cu(and_m | 0xFFFFFFE0)}") - self.emit(f"{t2} = OpBitwiseOr %uint {t1} {self.cu(or_m)}") - self.emit(f"{src} = OpBitwiseXor %uint {t2} {self.cu(xor_m)}") - elif kind == "QUAD_PERM": - sel, base, src = self.tmp(), self.tmp(), self.cu(0) - self.emit(f"{sel} = OpBitwiseAnd %uint {lane} {self.cu(3)}") - self.emit(f"{base} = OpBitwiseAnd %uint {lane} {self.cu(0xFFFFFFFC)}") - pick = self.cu(args[0]) - for i in (1, 2, 3): - e, nxt = self.tmp(), self.tmp() - self.emit(f"{e} = OpIEqual %bool {sel} {self.cu(i)}") - self.emit(f"{nxt} = OpSelect %uint {e} {self.cu(args[i])} {pick}") - pick = nxt - src = self.tmp() - self.emit(f"{src} = OpBitwiseOr %uint {base} {pick}") - elif kind == "SWAP": - src = self.tmp() - self.emit(f"{src} = OpBitwiseXor %uint {lane} {self.cu(args[0])}") - elif kind == "REVERSE": - src = self.tmp() - self.emit(f"{src} = OpBitwiseXor %uint {lane} {self.cu(args[0] - 1)}") - elif kind == "BROADCAST": - src, keep = self.tmp(), self.tmp() - self.emit(f"{keep} = OpBitwiseAnd %uint {lane} {self.cu(~(args[0] - 1) & 0xFFFFFFFF)}") - self.emit(f"{src} = OpBitwiseOr %uint {keep} {self.cu(args[1])}") - else: - raise Unsupported("ds_swizzle " + kind) - self.ds_lane_read(a[0], self.src_u(a[1]), src, lane) - - # op: (bytes, store?, signed, VGPR half the data comes from / lands in: None = the whole register) - BUFFER_SUB16 = { # the plain 8/16-bit loads are buffer_load_sub's (BUFFER_SUB) - "buffer_load_ubyte_d16": (1, False, False, 0), "buffer_load_ubyte_d16_hi": (1, False, False, 1), - "buffer_load_sbyte_d16": (1, False, True, 0), "buffer_load_sbyte_d16_hi": (1, False, True, 1), - "buffer_load_short_d16": (2, False, False, 0), "buffer_load_short_d16_hi": (2, False, False, 1), - "buffer_store_byte": (1, True, False, None), "buffer_store_byte_d16_hi": (1, True, False, 1), - "buffer_store_short": (2, True, False, None), "buffer_store_short_d16_hi": (2, True, False, 1)} - - def buffer_sub(self, op, a, mods): - """The d16 8/16-bit MUBUF loads and the 8/16-bit stores (RDNA2 ISA); the plain buffer_load_{u,s}byte / - {u,s}short are buffer_load_sub's. The _d16 loads write one 16-bit half of vdata (ubyte / sbyte extended to 16 bits) and - keep the other; buffer_store_byte / short write the low 8 / 16 bits (the _d16_hi forms the high half). The - address is buffer_address's, and the bounds check covers the access's own size (1 or 2 bytes) as for a typed - element of that size: a load out of range gives 0 (in the half it writes, for d16), a store out of range - writes nothing. Each byte is its own access, so a 16-bit one that crosses a dword is exact (in a swizzled - buffer the next dword is `step` bytes on); a store merges each byte into its dword with atomic and / or, as - buffer byte format stores do. Inactive lanes neither load nor store.""" - if any(m in mods for m in ("lds", "tfe")): - raise Unsupported(op + " form") - nbytes, store, signed, half = self.BUFFER_SUB16[op] - vd = a[0] - if vd["k"] != "vgpr" or vd.get("n", 1) != 1: - raise Unsupported(op + " data") - addr, _, in_b, step = self.buffer_address(a, mods, elem="fmt", fixed_fmt=1 if nbytes == 1 else 7) - old = self.load_reg("vgpr", vd["r"]) - cond = self.tmp() - self.emit(f"{cond} = OpLogicalAnd %bool {self.active_b()} {in_b}") - lbl_do, lbl_end = self.tmp() + "_do", self.tmp() + "_end" - pre = self.current_label_placeholder() - self.emit(f"OpSelectionMerge {lbl_end} None") - self.emit(f"OpBranchConditional {cond} {lbl_do} {lbl_end}") - self.emit(f"{lbl_do} = OpLabel") - value = None - for k in range(nbytes): - va = addr - if k: - va = self.tmp() - self.emit(f"{va} = OpIAdd %ulong {addr} {self.cl(k)}") - if step is not None: - # the second byte of an access at byte 3 is in the access's next dword, `step` bytes on - lo, b3, cross, s64, far, sel = (self.tmp() for _ in range(6)) - self.emit(f"{lo} = OpUConvert %uint {addr}") - self.emit(f"{b3} = OpBitwiseAnd %uint {lo} {self.cu(3)}") - self.emit(f"{cross} = OpIEqual %bool {b3} {self.cu(3)}") - self.emit(f"{s64} = OpUConvert %ulong {step}") - self.emit(f"{far} = OpIAdd %ulong {addr} {s64}") - f2 = self.tmp() - self.emit(f"{f2} = OpISub %ulong {far} {self.cl(3)}") - self.emit(f"{sel} = OpSelect %ulong {cross} {f2} {va}") - va = sel - p, sh = self.global_byte_ptr(va) - if store: - byte, mk, inv, vs, t1, t2 = (self.tmp() for _ in range(6)) - self.emit(f"{byte} = OpBitFieldUExtract %uint {old} {self.cu(16 * (half or 0) + 8 * k)} {self.cu(8)}") - self.emit(f"{mk} = OpShiftLeftLogical %uint {self.cu(0xFF)} {sh}") - self.emit(f"{inv} = OpNot %uint {mk}") - self.emit(f"{vs} = OpShiftLeftLogical %uint {byte} {sh}") - self.emit(f"{t1} = OpAtomicAnd %uint {p} {self.cu(1)} {self.cu(0)} {inv}") - self.emit(f"{t2} = OpAtomicOr %uint {p} {self.cu(1)} {self.cu(0)} {vs}") - else: - w, b = self.tmp(), self.tmp() - self.emit(f"{w} = OpLoad %uint {p} Aligned 4") - self.emit(f"{b} = OpBitFieldUExtract %uint {w} {sh} {self.cu(8)}") - if value is None: - value = b - else: - hi8, v2 = self.tmp(), self.tmp() - self.emit(f"{hi8} = OpShiftLeftLogical %uint {b} {self.cu(8)}") - self.emit(f"{v2} = OpBitwiseOr %uint {value} {hi8}") - value = v2 - if not store and signed: - sx = self.tmp() - self.emit(f"{sx} = OpBitFieldSExtract %uint {value} {self.cu(0)} {self.cu(8 * nbytes)}") - value = sx - self.emit(f"OpBranch {lbl_end}") - self.emit(f"{lbl_end} = OpLabel") - if store: - return - got = self.tmp() - self.emit(f"{got} = OpPhi %uint {value} {lbl_do} {self.cu(0)} {pre}") # out of range / inactive: 0 - if half is None: - # a whole-register load: inactive lanes keep vdata (dst writes active lanes only) - self.dst(vd, got) - else: - new = self.tmp() - self.emit(f"{new} = OpBitFieldInsert %uint {old} {got} {self.cu(16 * half)} {self.cu(16)}") - self.dst(vd, new) - - def buffer_load(self, op, a, mods): - """buffer_load_dword[xN] vD, vaddr, s[V#], soffset [offen|idxen] offset:N -> buffer-device-address loads. - addr = V#.base + soffset + inst_offset + (offen ? vaddr : 0) + (idxen ? vindex * V#.stride : 0), byte exact. - Each dword is loaded only when it is in range per the V#'s OOB_SELECT (buffer_address; docs/design.md, Buffer - bounds checking): for modes 0 and 3 dword i ends inside the stride / num_records, else it is 0 and memory is - not read; modes 1 and 2 check the index / num_records once. Inactive lanes don't load.""" - if any(m in mods for m in ("lds", "tfe")) or "format" in op: - raise Unsupported(op + " form") - n = 1 if op.endswith("dword") else int(op.rsplit("x", 1)[1]) - vd = a[0] - addr, _, in_b, raw_parts, step = self.buffer_address(a, mods, parts=True) - act = self.active_b() - ptr, host = self.tmp(), self.host_addr(addr) - self.emit(f"{ptr} = OpConvertUToPtr %_ptr_PSB_arr {host}") - - def guarded(cond, dwords): - """One selection construct that loads these dwords when cond holds; the phis give 0 otherwise.""" - lbl_do, lbl_end = self.tmp() + "_do", self.tmp() + "_end" - pre_label = self.current_label_placeholder() - self.emit(f"OpSelectionMerge {lbl_end} None") - self.emit(f"OpBranchConditional {cond} {lbl_do} {lbl_end}") - self.emit(f"{lbl_do} = OpLabel") - loaded = [] - for i in dwords: - p, v_do = self.buf_dword_ptr(ptr, host, step, i), self.tmp() - self.emit(f"{v_do} = OpLoad %uint {p} Aligned 4") - loaded.append(v_do) - self.emit(f"OpBranch {lbl_end}") - self.emit(f"{lbl_end} = OpLabel") - out = [] - for v_do in loaded: - v = self.tmp() - self.emit(f"{v} = OpPhi %uint {v_do} {lbl_do} {self.cu(0)} {pre_label}") - out.append(v) - return out - - if raw_parts is None: # literal mode 1/2: one check for the whole load - cond = self.tmp() - self.emit(f"{cond} = OpLogicalAnd %bool {act} {in_b}") - phis = guarded(cond, range(n)) - else: # mode 0/3 (or a run-time V#): each dword checks its own end - phis = [] - for i in range(n): - cond = self.tmp() - self.emit(f"{cond} = OpLogicalAnd %bool {act} {raw_parts(i)}") - phis += guarded(cond, [i]) - for i, v in enumerate(phis): - self.dst({"k": "vgpr", "r": vd["r"] + i, "n": 1}, v) - - BUFFER_SUB = { - "buffer_load_ubyte": (1, False), "buffer_load_sbyte": (1, True), - "buffer_load_ushort": (2, False), "buffer_load_sshort": (2, True), - } - - def buffer_load_sub(self, op, a, mods): - """buffer_load_{u,s}byte / buffer_load_{u,s}short vD, vaddr, s[V#], soffset [offen|idxen] offset:N. - Loads 1 or 2 bytes from V#.base + offsets, zero- or sign-extended to 32 bits. Out-of-bounds lanes - (OOB_SELECT with element size 1 or 2) return 0 without reading memory; inactive lanes keep vD.""" - if any(m in mods for m in ("lds", "tfe", "d16")): - raise Unsupported(op + " form") - nbytes, signed = self.BUFFER_SUB[op] - vd = a[0] - if vd["k"] != "vgpr" or vd.get("n", 1) != 1: - raise Unsupported(op + " destination") - addr, _, in_b, step = self.buffer_address(a, mods, elem=nbytes) - act = self.active_b() - cond = self.tmp() - self.emit(f"{cond} = OpLogicalAnd %bool {act} {in_b}") - lbl_do, lbl_end = self.tmp() + "_do", self.tmp() + "_end" - pre_label = self.current_label_placeholder() - self.emit(f"OpSelectionMerge {lbl_end} None") - self.emit(f"OpBranchConditional {cond} {lbl_do} {lbl_end}") - self.emit(f"{lbl_do} = OpLabel") - alo, b3, b64, aligned, sh = (self.tmp() for _ in range(5)) - self.emit(f"{alo} = OpUConvert %uint {addr}") - self.emit(f"{b3} = OpBitwiseAnd %uint {alo} {self.cu(3)}") - self.emit(f"{b64} = OpUConvert %ulong {b3}") - self.emit(f"{aligned} = OpISub %ulong {addr} {b64}") - self.emit(f"{sh} = OpShiftLeftLogical %uint {b3} {self.cu(3)}") - ptr, host = self.tmp(), self.host_addr(aligned) - self.emit(f"{ptr} = OpConvertUToPtr %_ptr_PSB_arr {host}") - p0, w0 = self.buf_dword_ptr(ptr, host, step, 0), self.tmp() - self.emit(f"{w0} = OpLoad %uint {p0} Aligned 4") - ext = "OpBitFieldSExtract" if signed else "OpBitFieldUExtract" - val = self.tmp() - if nbytes == 1: - self.emit(f"{val} = {ext} %uint {w0} {sh} {self.cu(8)}") - else: - cross, idx1, w1, lo_part, hi_byte, hi_sh, crossed, raw = (self.tmp() for _ in range(8)) - self.emit(f"{cross} = OpIEqual %bool {b3} {self.cu(3)}") - self.emit(f"{idx1} = OpSelect %uint {cross} {self.cu(1)} {self.cu(0)}") - p1 = self.buf_dword_ptr(ptr, host, step, idx1, same_base=True) # idx1 0: the dword p0 reads - self.emit(f"{w1} = OpLoad %uint {p1} Aligned 4") - self.emit(f"{lo_part} = OpShiftRightLogical %uint {w0} {sh}") - self.emit(f"{hi_byte} = OpBitFieldUExtract %uint {w1} {self.cu(0)} {self.cu(8)}") - self.emit(f"{hi_sh} = OpShiftLeftLogical %uint {hi_byte} {self.cu(8)}") - self.emit(f"{crossed} = OpBitwiseOr %uint {lo_part} {hi_sh}") - self.emit(f"{raw} = OpSelect %uint {cross} {crossed} {lo_part}") - self.emit(f"{val} = {ext} %uint {raw} {self.cu(0)} {self.cu(16)}") - self.emit(f"OpBranch {lbl_end}") - self.emit(f"{lbl_end} = OpLabel") - res = self.tmp() - self.emit(f"{res} = OpPhi %uint {val} {lbl_do} {self.cu(0)} {pre_label}") - self.dst(vd, res) - - # GFX10 buffer formats (from Mesa src/amd/registers/gfx10-rsrc.json, GFX10_FORMAT): - # code: (bytes, kind, component bit widths from bit 0) - # The names list the widths from the top bit down, so 2_10_10_10 (50) is R10G10B10A2. - # Full-width SINT and UINT preserve the same raw dwords. Keep separate kinds for signed D16 conversion. - # Kinds: unorm/snorm/uint (the first entries), uscaled/sscaled (the integer converted to float, not divided), sint - # (sign-extended), ufloat (the unsigned 5-bit-exponent 10/11-bit float). 10_11_11 and 11_11_10 are the FLOAT ones - # only on GFX11; GFX10's own UNORM/SNORM/USCALED/SSCALED/UINT/SINT codes of those two (30-35, 37-42) are in the table. - FORMATS = {22: (4, "f32", (32,)), 64: (8, "f32", (32, 32)), 74: (12, "f32", (32, 32, 32)), - 77: (16, "f32", (32, 32, 32, 32)), 20: (4, "u32", (32,)), 62: (8, "u32", (32, 32)), - 72: (12, "u32", (32, 32, 32)), 75: (16, "u32", (32, 32, 32, 32)), - 21: (4, "i32", (32,)), 63: (8, "i32", (32, 32)), 73: (12, "i32", (32, 32, 32)), - 76: (16, "i32", (32, 32, 32, 32)), 13: (2, "f16", (16,)), 29: (4, "f16", (16, 16)), - 71: (8, "f16", (16, 16, 16, 16)), 1: (1, "unorm", (8,)), 5: (1, "uint", (8,)), 14: (2, "unorm", (8, 8)), - 56: (4, "unorm", (8, 8, 8, 8)), 57: (4, "snorm", (8, 8, 8, 8)), 60: (4, "uint", (8, 8, 8, 8)), - 7: (2, "unorm", (16,)), 23: (4, "unorm", (16, 16)), 24: (4, "snorm", (16, 16)), - 65: (8, "unorm", (16, 16, 16, 16)), 66: (8, "snorm", (16, 16, 16, 16)), - 44: (4, "unorm", (2, 10, 10, 10)), 50: (4, "unorm", (10, 10, 10, 2)), - 69: (8, "uint", (16, 16, 16, 16)), 27: (4, "uint", (16, 16)), - 2: (1, "snorm", (8,)), 8: (2, "snorm", (16,)), 15: (2, "snorm", (8, 8)), - # Narrow integer formats, measured natively on gfx1036 (wave32 and wave64): UINT loads zero-extend - # and stores saturate to the channel; SINT loads sign-extend and stores clamp the 32-bit signed value - # to [-2^(w-1), 2^(w-1) - 1]. - 3: (1, "uscaled", (8,)), 4: (1, "sscaled", (8,)), 5: (1, "uint", (8,)), 6: (1, "sint", (8,)), - 9: (2, "uscaled", (16,)), 10: (2, "sscaled", (16,)), 11: (2, "uint", (16,)), 12: (2, "sint", (16,)), - 16: (2, "uscaled", (8, 8)), 17: (2, "sscaled", (8, 8)), 18: (2, "uint", (8, 8)), - 19: (2, "sint", (8, 8)), 25: (4, "uscaled", (16, 16)), 26: (4, "sscaled", (16, 16)), - 28: (4, "sint", (16, 16)), 36: (4, "ufloat", (11, 11, 10)), 43: (4, "ufloat", (10, 11, 11)), - 45: (4, "snorm", (2, 10, 10, 10)), 46: (4, "uscaled", (2, 10, 10, 10)), - 47: (4, "sscaled", (2, 10, 10, 10)), 48: (4, "uint", (2, 10, 10, 10)), 49: (4, "sint", (2, 10, 10, 10)), - 51: (4, "snorm", (10, 10, 10, 2)), 52: (4, "uscaled", (10, 10, 10, 2)), - 53: (4, "sscaled", (10, 10, 10, 2)), 54: (4, "uint", (10, 10, 10, 2)), 55: (4, "sint", (10, 10, 10, 2)), - 58: (4, "uscaled", (8, 8, 8, 8)), 59: (4, "sscaled", (8, 8, 8, 8)), 61: (4, "sint", (8, 8, 8, 8)), - 67: (8, "uscaled", (16, 16, 16, 16)), 68: (8, "sscaled", (16, 16, 16, 16)), - 70: (8, "sint", (16, 16, 16, 16)), - # 10_11_11 (x 11 bits, y 11, z 10) and 11_11_10 (x 10, y 11, z 11) with the other numeric formats: GFX11 has none - # of them, a real RDNA2 (gfx1036, @AwkGrep256, #2022) validated the layout and conversions of all twelve. - 30: (4, "unorm", (11, 11, 10)), 31: (4, "snorm", (11, 11, 10)), 32: (4, "uscaled", (11, 11, 10)), - 33: (4, "sscaled", (11, 11, 10)), 34: (4, "uint", (11, 11, 10)), 35: (4, "sint", (11, 11, 10)), - 37: (4, "unorm", (10, 11, 11)), 38: (4, "snorm", (10, 11, 11)), 39: (4, "uscaled", (10, 11, 11)), - 40: (4, "sscaled", (10, 11, 11)), 41: (4, "uint", (10, 11, 11)), 42: (4, "sint", (10, 11, 11))} - - # The run-time FORMAT decode (SHADER-849): a format's conversion is one of these kinds, and the tables below - # describe them per format code, so that the decode needs no branch and no copy per format. - FMT_RAW, FMT_SINT, FMT_USCALED, FMT_SSCALED, FMT_UNORM, FMT_SNORM, FMT_F16, FMT_UFLOAT = range(8) - FMT_NONE = 8 # a code outside FORMATS: the decode gives 0 - FMT_KINDS = {"f32": FMT_RAW, "u32": FMT_RAW, "i32": FMT_RAW, "uint": FMT_RAW, - "sint": FMT_SINT, "uscaled": FMT_USCALED, "sscaled": FMT_SSCALED, - "unorm": FMT_UNORM, "snorm": FMT_SNORM, "f16": FMT_F16, "ufloat": FMT_UFLOAT} - - @classmethod - def fmt_desc_table(cls): - """One uint per format code: the conversion kind, the channel count and the four channel widths. - - The bit offset of a channel is the sum of the widths before it, so the table holds the widths only and the - offsets follow. A code outside FORMATS gets FMT_NONE.""" - table = [] - for code in range(128): - entry = cls.FORMATS.get(code) - kind = cls.FMT_KINDS.get(entry[1], cls.FMT_NONE) if entry else cls.FMT_NONE - widths = entry[2] if entry else () - word = kind | (len(widths) << 4) - for i in range(4): - word |= (widths[i] if i < len(widths) else 0) << (7 + 6 * i) - table.append(word) - return table - - @classmethod - def fmt_norm_reps(cls): - """The 64-bit repeat constants of the exact norm quotient, one per width (1..16). - - The quotient m / (2^n - 1) is m's n bits repeated; the constant holds the first 64 of them.""" - return [0] + [sum(1 << (64 - n * (k + 1)) for k in range(64 // n)) for n in range(1, 17)] - - def encode_norm_bits(self, u, w, signed): - """Exact single-rounded UNORM/SNORM channel bits from an f32 bit pattern u (NaN already mapped to 0). - - RDNA2 (gfx1036, wave32 and wave64, MUBUF and MTBUF) rounds the exact product clamp(x) * scale once with - ties away from zero, rather than rounding through an intermediate f32 multiply (which double-rounds e.g. - UNORM16(0.3) to 19660 instead of 19661). For |x| < 2^-17 and w <= 16, |x| * scale < 0.5 so the result is 0; - for 2^-17 <= |x| < 1.0, exp is in 110..126, shift = 150 - exp is in 24..40, and (m * scale + 2^(shift-1)) - >> shift fits in 64-bit unsigned integer arithmetic with no overflow.""" - scale = (1 << (w - 1)) - 1 if signed else (1 << w) - 1 - sign, neg, a = self.tmp(), self.tmp(), self.tmp() - self.emit(f"{sign} = OpShiftRightLogical %uint {u} {self.cu(31)}") - self.emit(f"{neg} = OpINotEqual %bool {sign} {self.cu(0)}") - self.emit(f"{a} = OpBitwiseAnd %uint {u} {self.cu(0x7FFFFFFF)}") - small, ge1, exp_, ec, ec2, shift, sh64, sh1, sh1_64 = (self.tmp() for _ in range(9)) - self.emit(f"{small} = OpULessThan %bool {a} {self.cu(0x37000000)}") - self.emit(f"{ge1} = OpUGreaterThanEqual %bool {a} {self.cu(0x3F800000)}") - self.emit(f"{exp_} = OpShiftRightLogical %uint {a} {self.cu(23)}") - self.emit(f"{ec} = OpExtInst %uint %glsl UMax {exp_} {self.cu(110)}") - self.emit(f"{ec2} = OpExtInst %uint %glsl UMin {ec} {self.cu(126)}") - self.emit(f"{shift} = OpISub %uint {self.cu(150)} {ec2}") - self.emit(f"{sh64} = OpUConvert %ulong {shift}") - self.emit(f"{sh1} = OpISub %uint {shift} {self.cu(1)}") - self.emit(f"{sh1_64} = OpUConvert %ulong {sh1}") - mant, m, m64, p, half, ps, q64, q, mag1, mag = (self.tmp() for _ in range(10)) - self.emit(f"{mant} = OpBitwiseAnd %uint {a} {self.cu(0x7FFFFF)}") - self.emit(f"{m} = OpBitwiseOr %uint {mant} {self.cu(0x800000)}") - self.emit(f"{m64} = OpUConvert %ulong {m}") - self.emit(f"{p} = OpIMul %ulong {m64} {self.cl(scale)}") - self.emit(f"{half} = OpShiftLeftLogical %ulong {self.cl(1)} {sh1_64}") - self.emit(f"{ps} = OpIAdd %ulong {p} {half}") - self.emit(f"{q64} = OpShiftRightLogical %ulong {ps} {sh64}") - self.emit(f"{q} = OpUConvert %uint {q64}") - self.emit(f"{mag1} = OpSelect %uint {small} {self.cu(0)} {q}") - self.emit(f"{mag} = OpSelect %uint {ge1} {self.cu(scale)} {mag1}") - res = self.tmp() - if signed: - nmag = self.tmp() - self.emit(f"{nmag} = OpISub %uint {self.cu(0)} {mag}") - self.emit(f"{res} = OpSelect %uint {neg} {nmag} {mag}") - else: - self.emit(f"{res} = OpSelect %uint {neg} {self.cu(0)} {mag}") - return res - - def encode_format(self, fcomps, icomps, code): - """Encode one element of format `code` -> list of uint ids (whole dwords; elements under 4 bytes return one - value in the low bits). fcomps are f32 bit patterns (float/normalized kinds), icomps integer bit patterns - (u32/i32/uint/sint).""" - try: - size, kind, widths = self.FORMATS[code] - except KeyError: - raise Unsupported(f"format {code} (not in FORMATS)") - if kind == "f32": - return list(fcomps[:len(widths)]) - if kind in ("u32", "i32"): - return list(icomps[:len(widths)]) - words = [self.cu(0)] * max(1, (size + 3) // 4) - bit = 0 - for c, w in enumerate(widths): - if kind == "f16": - # f32 -> f16 toward zero, finite values past the range -> +-65504: measured natively on gfx1036 for - # 16_FLOAT, 16_16_FLOAT and 16_16_16_16_FLOAT stores (SHADER-358; gfx1150 does the same, #1548). - field = self.mem_f16(self.tof(fcomps[c])) - elif kind in ("unorm", "uscaled"): # a SCALED store converts as its NORM format - field = self.encode_norm_bits(fcomps[c], w, signed=False) - elif kind in ("snorm", "sscaled"): - field = self.encode_norm_bits(fcomps[c], w, signed=True) - elif kind == "sint": # Narrow SINT stores clamp the signed value to the field's range. - clamped, field = self.tmp(), self.tmp() - lo, hi = self.as_int(self.cu((-(1 << (w - 1))) & 0xFFFFFFFF)), self.as_int(self.cu((1 << (w - 1)) - 1)) - self.emit(f"{clamped} = OpExtInst %int %glsl SClamp {self.as_int(icomps[c])} {lo} {hi}") - self.emit(f"{field} = OpBitcast %uint {clamped}") - elif kind == "ufloat": - field = self.ufloat_encode_bits(fcomps[c], w) - else: # Narrow UINT stores saturate to the field width before insertion. - field = self.tmp() - self.emit(f"{field} = OpExtInst %uint %glsl UMin {icomps[c]} {self.cu((1 << w) - 1)}") - wi = bit // 32 - ins = self.tmp() - self.emit(f"{ins} = OpBitFieldInsert %uint {words[wi]} {field} {self.cu(bit % 32)} {self.cu(w)}") - words[wi] = ins - bit += w - return words - - def ufloat_encode_bits(self, x, w): - """The w-bit unsigned float (5 exponent bits, bias 15, w - 5 mantissa bits) of the f32 bits x, integer ops only. - Round toward zero; a value past the largest finite one gives that largest finite value; +-0 and every negative - number except a NaN give 0; +inf gives infinity; a NaN keeps the top mantissa bits of its payload, or 1 when they - are all zero, so it stays a NaN (all measured on gfx1150, tools/buffer_format_fuzz.py).""" - mb = w - 5 - (a, ex, sg, sig, hid, sh0, sh, shc, dn, nr0, nr, nm, nm1, nz, nmant, nanb, isnan, isinf, big, norm, - r0, r1, r2, neg, ng, r3, snan) = (self.tmp() for _ in range(27)) - self.emit(f"{a} = OpBitwiseAnd %uint {x} {self.cu(0x7FFFFFFF)}") - self.emit(f"{sg} = OpShiftRightLogical %uint {x} {self.cu(31)}") - self.emit(f"{ex} = OpShiftRightLogical %uint {a} {self.cu(23)}") - self.emit(f"{hid} = OpBitwiseAnd %uint {a} {self.cu(0x7FFFFF)}") - self.emit(f"{sig} = OpBitwiseOr %uint {hid} {self.cu(0x800000)}") - self.emit(f"{sh0} = OpISub %uint {self.cu(136 - mb)} {ex}") # denormal result: sig >> (136 - mb - e) - self.emit(f"{shc} = OpExtInst %uint %glsl UMin {sh0} {self.cu(31)}") - self.emit(f"{dn} = OpShiftRightLogical %uint {sig} {shc}") - self.emit(f"{nr0} = OpISub %uint {a} {self.cu(112 << 23)}") # normal result: rebias, drop mantissa bits - self.emit(f"{nr} = OpShiftRightLogical %uint {nr0} {self.cu(23 - mb)}") - self.emit(f"{nm} = OpShiftRightLogical %uint {a} {self.cu(23 - mb)}") - self.emit(f"{nm1} = OpBitwiseAnd %uint {nm} {self.cu((1 << mb) - 1)}") - self.emit(f"{nz} = OpIEqual %bool {nm1} {self.cu(0)}") - self.emit(f"{nmant} = OpSelect %uint {nz} {self.cu(1)} {nm1}") - self.emit(f"{nanb} = OpBitwiseOr %uint {nmant} {self.cu(31 << mb)}") - self.emit(f"{isnan} = OpUGreaterThan %bool {a} {self.cu(0x7F800000)}") - self.emit(f"{isinf} = OpIEqual %bool {a} {self.cu(0x7F800000)}") - self.emit(f"{big} = OpUGreaterThanEqual %bool {a} {self.cu(0x47800000)}") - self.emit(f"{norm} = OpUGreaterThanEqual %bool {a} {self.cu(0x38800000)}") - self.emit(f"{r0} = OpSelect %uint {norm} {nr} {dn}") - self.emit(f"{r1} = OpSelect %uint {big} {self.cu((30 << mb) | ((1 << mb) - 1))} {r0}") - self.emit(f"{r2} = OpSelect %uint {isinf} {self.cu(31 << mb)} {r1}") - self.emit(f"{r3} = OpSelect %uint {isnan} {nanb} {r2}") - self.emit(f"{neg} = OpINotEqual %bool {sg} {self.cu(0)}") - self.emit(f"{snan} = OpLogicalNot %bool {isnan}") - self.emit(f"{ng} = OpLogicalAnd %bool {neg} {snan}") - res = self.tmp() - self.emit(f"{res} = OpSelect %uint {ng} {self.cu(0)} {r3}") - return res - - def field_extract(self, src, off, width): - """(src >> off) & ((1 << width) - 1). off and width are ints (constants) or ids (run-time values).""" - if isinstance(off, int) and isinstance(width, int): - f = self.tmp() - self.emit(f"{f} = OpBitFieldUExtract %uint {src} {self.cu(off)} {self.cu(width)}") - return f - o = self.cu(off) if isinstance(off, int) else off - w = self.cu(width) if isinstance(width, int) else width - sh, one, m1, shifted, res = (self.tmp() for _ in range(5)) - self.emit(f"{sh} = OpBitwiseAnd %uint {w} {self.cu(31)}") - self.emit(f"{one} = OpShiftLeftLogical %uint {self.cu(1)} {sh}") - self.emit(f"{m1} = OpISub %uint {one} {self.cu(1)}") - self.emit(f"{shifted} = OpShiftRightLogical %uint {src} {o}") - self.emit(f"{res} = OpBitwiseAnd %uint {shifted} {m1}") - return res - - def ufloat_decode_bits(self, f, w): - """f32 bits of the w-bit unsigned float in the low bits of f (see ufloat_encode_bits): exact, integer ops only. - A NaN keeps its payload shifted up, unquieted; there is no sign. w is an int (a constant width) or an id (a - run-time width, SHADER-849).""" - if isinstance(w, int): - mb = w - 5 - else: - mb = self.tmp() - self.emit(f"{mb} = OpISub %uint {w} {self.cu(5)}") - # A width under 5 wraps around, and one over 23 would shift the mantissa out: the candidate is only - # used for the two ufloat formats (widths 10 and 11), so any value in range is fine here. - hi, mb2 = self.tmp(), self.tmp() - self.emit(f"{hi} = OpUGreaterThan %bool {mb} {self.cu(23)}") - self.emit(f"{mb2} = OpSelect %uint {hi} {self.cu(23)} {mb}") - mb = mb2 - eb, es, ms, nrm, p, pi, pb, db, dsh, dm, dmk, dn, nzm, isz, dres, inf, mz, r0, r1, r2 = \ - (self.tmp() for _ in range(20)) - e = self.field_extract(f, mb, 5) - m = self.field_extract(f, 0, mb) - self.emit(f"{eb} = OpIAdd %uint {e} {self.cu(112)}") - self.emit(f"{es} = OpShiftLeftLogical %uint {eb} {self.cu(23)}") - if isinstance(w, int): - self.emit(f"{ms} = OpShiftLeftLogical %uint {m} {self.cu(23 - mb)}") - else: - sh = self.tmp() - self.emit(f"{sh} = OpISub %uint {self.cu(23)} {mb}") - self.emit(f"{ms} = OpShiftLeftLogical %uint {m} {sh}") - self.emit(f"{nrm} = OpBitwiseOr %uint {es} {ms}") - # exponent 0: a denormal m * 2^(-14 - mb); its top set bit p gives the f32 exponent p + 113 - mb - self.emit(f"{pi} = OpExtInst %int %glsl FindUMsb {m}") - self.emit(f"{p} = OpBitcast %uint {pi}") - if isinstance(w, int): - self.emit(f"{pb} = OpIAdd %uint {p} {self.cu(113 - mb)}") - else: - pb2 = self.tmp() - self.emit(f"{pb2} = OpISub %uint {self.cu(113)} {mb}") - self.emit(f"{pb} = OpIAdd %uint {p} {pb2}") - self.emit(f"{db} = OpShiftLeftLogical %uint {pb} {self.cu(23)}") - self.emit(f"{dsh} = OpISub %uint {self.cu(23)} {p}") - self.emit(f"{dm} = OpShiftLeftLogical %uint {m} {dsh}") - self.emit(f"{dmk} = OpBitwiseAnd %uint {dm} {self.cu(0x7FFFFF)}") - self.emit(f"{dn} = OpBitwiseOr %uint {db} {dmk}") - self.emit(f"{mz} = OpIEqual %bool {m} {self.cu(0)}") - self.emit(f"{dres} = OpSelect %uint {mz} {self.cu(0)} {dn}") - self.emit(f"{isz} = OpIEqual %bool {e} {self.cu(0)}") - self.emit(f"{r0} = OpSelect %uint {isz} {dres} {nrm}") - self.emit(f"{inf} = OpIEqual %bool {e} {self.cu(31)}") - self.emit(f"{r1} = OpBitwiseOr %uint {ms} {self.cu(0x7F800000)}") - self.emit(f"{r2} = OpSelect %uint {inf} {r1} {r0}") - return r2 - - def f16_widen_bits(self, f): - """The f32 bits of the half in the low 16 bits of f, with the NaN payload the hardware widens to. - - A half NaN widens by shifting its payload, keeping the sign and the quiet bit as they are: measured natively - on RDNA2 (gfx1036, tools/f16_widen_probe.py) 0x7ddb (sNaN) -> 0x7FBB6000 and 0x7FE6 (qNaN) -> 0x7FFCC000, - the same words for formats 13, 29 and 71, MUBUF and MTBUF, wave32 and wave64. UnpackHalf2x16 leaves a NaN - undefined: the interpreter canonicalises it to 0x7FC00000 and v_cvt_f32_f16 (what a driver lowers it to) sets - the quiet bit, which the typed load does not, so the NaN case is built from the bits.""" - v2, x = self.tmp(), self.tmp() - self.emit(f"{v2} = OpExtInst %v2float %glsl UnpackHalf2x16 {f}") - self.emit(f"{x} = OpCompositeExtract %float {v2} 0") - mag, is_nan, sg, sgsh, fr, mant, nan0, nan_bits, xb, res = (self.tmp() for _ in range(10)) - self.emit(f"{mag} = OpBitwiseAnd %uint {f} {self.cu(0x7FFF)}") - self.emit(f"{is_nan} = OpUGreaterThan %bool {mag} {self.cu(0x7C00)}") - self.emit(f"{sg} = OpBitwiseAnd %uint {f} {self.cu(0x8000)}") - self.emit(f"{sgsh} = OpShiftLeftLogical %uint {sg} {self.cu(16)}") - self.emit(f"{fr} = OpBitwiseAnd %uint {f} {self.cu(0x3FF)}") - self.emit(f"{mant} = OpShiftLeftLogical %uint {fr} {self.cu(13)}") - self.emit(f"{nan0} = OpBitwiseOr %uint {sgsh} {self.cu(0x7F800000)}") - self.emit(f"{nan_bits} = OpBitwiseOr %uint {nan0} {mant}") - self.emit(f"{xb} = OpBitcast %uint {x}") - self.emit(f"{res} = OpSelect %uint {is_nan} {nan_bits} {xb}") - return res - - def norm_bits(self, m, n): - """f32 bits of m / (2^n - 1), correctly rounded, for an n-bit unsigned id m (1 <= n <= 16), integer ops only. - - In binary, m / (2^n - 1) is m's n bits repeated forever. T = m * sum(2^(64 - n(k+1))) holds the first 64 of - them (the partial block at the bottom is dropped, below every bit used here). For 0 < m < 2^n - 1 the top 1 of - T is in its high dword (T >= 2^(64-n)), so p = FindUMsb(T >> 32) is 16..31 and the value is in [2^(p-32), - 2^(p-31)). The mantissa is T >> (p + 9) (24 bits with the hidden one) and the round bit the one below it. The - repeating tail is never all zero, so a tie can't happen: round to nearest is "add the round bit". A carry - out of the mantissa moves into the exponent through the plain add. 0 and 2^n - 1 are exact (0 and 1.0).""" - rep = sum(1 << (64 - n * (k + 1)) for k in range(64 // n)) - m64, t, h64, hi, pi, p, s, s64, q64, q, s1, s164, r64, rb, e, eb, b0, b1, b2, z, one, b3, b4 = \ - (self.tmp() for _ in range(23)) - self.emit(f"{m64} = OpUConvert %ulong {m}") - self.emit(f"{t} = OpIMul %ulong {m64} {self.cl(rep)}") - self.emit(f"{h64} = OpShiftRightLogical %ulong {t} {self.cl(32)}") - self.emit(f"{hi} = OpUConvert %uint {h64}") - self.emit(f"{pi} = OpExtInst %int %glsl FindUMsb {hi}") - self.emit(f"{p} = OpBitcast %uint {pi}") - self.emit(f"{s} = OpIAdd %uint {p} {self.cu(9)}") # m = 0 gives p = -1: s = 8, result unused - self.emit(f"{s64} = OpUConvert %ulong {s}") - self.emit(f"{q64} = OpShiftRightLogical %ulong {t} {s64}") - self.emit(f"{q} = OpUConvert %uint {q64}") - self.emit(f"{s1} = OpISub %uint {s} {self.cu(1)}") - self.emit(f"{s164} = OpUConvert %ulong {s1}") - self.emit(f"{r64} = OpShiftRightLogical %ulong {t} {s164}") - self.emit(f"{rb} = OpUConvert %uint {r64}") - self.emit(f"{e} = OpIAdd %uint {p} {self.cu(95)}") # biased exponent p - 32 + 127 - self.emit(f"{eb} = OpShiftLeftLogical %uint {e} {self.cu(23)}") - self.emit(f"{b0} = OpISub %uint {q} {self.cu(0x800000)}") # drop the hidden one - self.emit(f"{b1} = OpIAdd %uint {eb} {b0}") - self.emit(f"{b2} = OpBitwiseAnd %uint {rb} {self.cu(1)}") - self.emit(f"{b3} = OpIAdd %uint {b1} {b2}") - self.emit(f"{z} = OpIEqual %bool {m} {self.cu(0)}") - self.emit(f"{one} = OpIEqual %bool {m} {self.cu((1 << n) - 1)}") - self.emit(f"{b4} = OpSelect %uint {one} {self.cu(0x3F800000)} {b3}") - res = self.tmp() - self.emit(f"{res} = OpSelect %uint {z} {self.cu(0)} {b4}") - return res - - def tbuffer_norm_bits(self, magnitude: str, width: int) -> str: - """Share the fixed-format quotient across instructions and channels with the same magnitude width.""" - function = f"%tbuffer_norm_{width}" - if width not in self.tbuffer_norm_fns: - parameter = f"{function}_m" - outer_body, self.body = self.body, [] - result = self.norm_bits(parameter, width) - lines, self.body = self.body, outer_body - self.tbuffer_norm_fns[width] = [ - f"{function} = OpFunction %uint Pure %fn_tbuffer_norm", - f"{parameter} = OpFunctionParameter %uint", f"{function}_entry = OpLabel", - *lines, f"OpReturnValue {result}", "OpFunctionEnd", - ] - result = self.tmp() - self.emit(f"{result} = OpFunctionCall %uint {function} {magnitude}") - return result - - def decode_format(self, words, code, *, fixed: bool = False): - """Decode one element of format `code` from raw dwords -> 4 uint ids holding f32 or integer bits. - - Missing channels repeat the format's own (component c = c mod n): measured on RX 6700 for SHADER-86. - UNORM/SNORM give the correctly rounded quotient, as the RX 6700 does, built with integer ops (norm_bits): - OpFDiv is allowed 2.5 ULP and the AMD and NVIDIA drivers return the reciprocal-multiply result for it (#599).""" - try: - size, kind, widths = self.FORMATS[code] - except KeyError: - raise Unsupported(f"format {code} (not in FORMATS)") - if kind in ("f32", "u32", "i32"): - n = len(widths) - vals = list(words[:n]) - while len(vals) < 4: - vals.append(vals[len(vals) % n]) - return vals - normalize = self.tbuffer_norm_bits if fixed else self.norm_bits - out, bit = [], 0 - for w in widths: - src = words[bit // 32] - f = self.tmp() - self.emit(f"{f} = OpBitFieldUExtract %uint {src} {self.cu(bit % 32)} {self.cu(w)}") - if kind == "f16": - out.append(self.f16_widen_bits(f)) - elif kind == "unorm": - out.append(normalize(f, w)) - elif kind == "uscaled": - x = self.tmp() - self.emit(f"{x} = OpConvertUToF %float {f}") - out.append(self.tou(x)) - elif kind in ("sscaled", "sint"): - si = self.tmp() - self.emit(f"{si} = OpBitFieldSExtract %int {self.as_int(src)} {self.cu(bit % 32)} {self.cu(w)}") - if kind == "sint": - u = self.tmp() - self.emit(f"{u} = OpBitcast %uint {si}") - out.append(u) - else: - x = self.tmp() - self.emit(f"{x} = OpConvertSToF %float {si}") - out.append(self.tou(x)) - elif kind == "ufloat": - out.append(self.ufloat_decode_bits(f, w)) - elif kind == "snorm": - # magnitude over 2^(w-1)-1 with the same integer rounding; the most negative code is -1.0 - si, neg, ab, au, sg, sel, lo, res = (self.tmp() for _ in range(8)) - self.emit(f"{si} = OpBitFieldSExtract %int {self.as_int(src)} {self.cu(bit % 32)} {self.cu(w)}") - self.emit(f"{neg} = OpSLessThan %bool {si} {self.as_int(self.cu(0))}") - self.emit(f"{ab} = OpExtInst %int %glsl SAbs {si}") - self.emit(f"{au} = OpBitcast %uint {ab}") - mag = normalize(au, w - 1) - self.emit(f"{sg} = OpBitwiseOr %uint {mag} {self.cu(0x80000000)}") - self.emit(f"{sel} = OpSelect %uint {neg} {sg} {mag}") - self.emit(f"{lo} = OpULessThan %bool {au} {self.cu(1 << (w - 1))}") - self.emit(f"{res} = OpSelect %uint {lo} {sel} {self.cu(0xBF800000)}") - out.append(res) - elif kind == "sint": - si, su = self.tmp(), self.tmp() - self.emit(f"{si} = OpBitFieldSExtract %int {self.as_int(src)} {self.cu(bit % 32)} {self.cu(w)}") - self.emit(f"{su} = OpBitcast %uint {si}") - out.append(su) - else: # uint: raw integer - out.append(f) - bit += w - n = len(out) - while len(out) < 4: - out.append(out[len(out) % n]) - return out - - BUF_ATOMICS = {"add": ("OpAtomicIAdd", 0), "sub": ("OpAtomicISub", 0), "umin": ("OpAtomicUMin", 0xFFFFFFFF), - "umax": ("OpAtomicUMax", 0), "smin": ("OpAtomicSMin", 0x7FFFFFFF), "smax": ("OpAtomicSMax", 0x80000000), - "and": ("OpAtomicAnd", 0xFFFFFFFF), "or": ("OpAtomicOr", 0), "xor": ("OpAtomicXor", 0), - "swap": ("OpAtomicExchange", None), "cmpswap": ("OpAtomicCompareExchange", None)} - - def atomic_inc_dec_cas(self, p, val, kind, lbl_do): - """Structured OpAtomicCompareExchange CAS loop on `%_ptr_PSB_uint` pointer `p` for RDNA2 32-bit unsigned - wrapping atomic inc/dec (RDNA2 ISA): - inc: M = (M >= DATA) ? 0 : M + 1 - dec: M = (M == 0 || M > DATA) ? DATA : M - 1 - csub: M = (DATA > M) ? 0 : M - DATA, a subtract clamped at 0 (GFX10.3 BUFFER/GLOBAL_ATOMIC_CSUB; measured - on gfx1036, #3193) - Returns `(old_val, exit_label)` where `old_val` is the pre-op word in memory.""" - lbl_hdr, lbl_cont, lbl_exit = (self.tmp() + s for s in ("_hdr", "_cont", "_exit")) - init = self.tmp() - self.emit(f"{init} = OpAtomicLoad %uint {p} {self.cu(1)} {self.cu(0)}") - self.emit(f"OpBranch {lbl_hdr}") - self.emit(f"{lbl_hdr} = OpLabel") - cur, got = self.tmp(), self.tmp() - self.emit(f"{cur} = OpPhi %uint {init} {lbl_do} {got} {lbl_cont}") - if kind == "csub": - wrap, step, new_u = self.tmp(), self.tmp(), self.tmp() - self.emit(f"{wrap} = OpUGreaterThan %bool {val} {cur}") - self.emit(f"{step} = OpISub %uint {cur} {val}") - self.emit(f"{new_u} = OpSelect %uint {wrap} {self.cu(0)} {step}") - elif kind == "inc": - wrap, step, new_u = self.tmp(), self.tmp(), self.tmp() - self.emit(f"{wrap} = OpUGreaterThanEqual %bool {cur} {val}") - self.emit(f"{step} = OpIAdd %uint {cur} {self.cu(1)}") - self.emit(f"{new_u} = OpSelect %uint {wrap} {self.cu(0)} {step}") - else: - is_z, gt, wrap, step, new_u = (self.tmp() for _ in range(5)) - self.emit(f"{is_z} = OpIEqual %bool {cur} {self.cu(0)}") - self.emit(f"{gt} = OpUGreaterThan %bool {cur} {val}") - self.emit(f"{wrap} = OpLogicalOr %bool {is_z} {gt}") - self.emit(f"{step} = OpISub %uint {cur} {self.cu(1)}") - self.emit(f"{new_u} = OpSelect %uint {wrap} {val} {step}") - done = self.tmp() - self.emit(f"{got} = OpAtomicCompareExchange %uint {p} {self.cu(1)} {self.cu(0)} {self.cu(0)} {new_u} {cur}") - self.emit(f"{done} = OpIEqual %bool {got} {cur}") - self.emit(f"OpLoopMerge {lbl_exit} {lbl_cont} None") - self.emit(f"OpBranchConditional {done} {lbl_exit} {lbl_cont}") - self.emit(f"{lbl_cont} = OpLabel") - self.emit(f"OpBranch {lbl_hdr}") - self.emit(f"{lbl_exit} = OpLabel") - return cur, lbl_exit - - def atomic_aligned(self, addr, align_bytes): - """True iff 64-bit Xbox VA `addr` is naturally aligned to `align_bytes` (4 or 8). - Measured natively on RDNA2 (gfx1036, wave32 & wave64): unaligned buffer_atomic* and global_atomic* - leave memory untouched and active glc lanes receive 0 / (0, 0), while inactive lanes keep vdst.""" - lo, rem, ok = self.tmp(), self.tmp(), self.tmp() - self.emit(f"{lo} = OpUConvert %uint {addr}") - self.emit(f"{rem} = OpBitwiseAnd %uint {lo} {self.cu(align_bytes - 1)}") - self.emit(f"{ok} = OpIEqual %bool {rem} {self.cu(0)}") - return ok - - def _emit_atomic_fminmax_cas(self, kind, addr, val_f, cond): - """Shared CAS loop for 32-bit float atomic min/max (global_atomic_{fmin,fmax} and buffer_atomic_{fmin,fmax}). - Returns the pre-op uint word on taken lanes and 0 on skipped lanes (caller writes via self.dst so inactive - lanes keep their destination VGPR untouched).""" - lbl_do, lbl_hdr, lbl_cont, lbl_exit, lbl_end = ( - self.tmp() + s for s in ("_do", "_hdr", "_cont", "_exit", "_end")) - pre = self.current_label_placeholder() - self.emit(f"OpSelectionMerge {lbl_end} None") - self.emit(f"OpBranchConditional {cond} {lbl_do} {lbl_end}") - self.emit(f"{lbl_do} = OpLabel") - ptr, p, init = self.tmp(), self.tmp(), self.tmp() - self.emit(f"{ptr} = OpConvertUToPtr %_ptr_PSB_arr {self.host_addr(addr)}") - self.emit(f"{p} = OpAccessChain %_ptr_PSB_uint {ptr} {self.cu(0)}") - self.emit(f"{init} = OpAtomicLoad %uint {p} {self.cu(1)} {self.cu(0)}") - self.emit(f"OpBranch {lbl_hdr}") - self.emit(f"{lbl_hdr} = OpLabel") - cur, cur_f, new_f, new_u, got, done = (self.tmp() for _ in range(6)) - self.emit(f"{cur} = OpPhi %uint {init} {lbl_do} {got} {lbl_cont}") - self.emit(f"{cur_f} = OpBitcast %float {cur}") - glsl_op = "NMin" if kind == "fmin" else "NMax" - self.emit(f"{new_f} = OpExtInst %float %glsl {glsl_op} {cur_f} {val_f}") - self.emit(f"{new_u} = OpBitcast %uint {new_f}") - self.emit(f"{got} = OpAtomicCompareExchange %uint {p} {self.cu(1)} {self.cu(0)} {self.cu(0)} {new_u} {cur}") - self.emit(f"{done} = OpIEqual %bool {got} {cur}") - self.emit(f"OpLoopMerge {lbl_exit} {lbl_cont} None") - self.emit(f"OpBranchConditional {done} {lbl_exit} {lbl_cont}") - self.emit(f"{lbl_cont} = OpLabel") - self.emit(f"OpBranch {lbl_hdr}") - self.emit(f"{lbl_exit} = OpLabel") - self.emit(f"OpBranch {lbl_end}") - self.emit(f"{lbl_end} = OpLabel") - old = self.tmp() - self.emit(f"{old} = OpPhi %uint {cur} {lbl_exit} {self.cu(0)} {pre}") - return old - - def global_atomic(self, op, a, mods): - """global_atomic_ [vdst,] vaddr, vdata, saddr|off [offset:N] [glc]: a 32-bit atomic at the global_* address - (RDNA2 ISA, FLAT/GLOBAL). With glc the pre-op value lands in vdst (the first operand); without it there is no - vdst. cmpswap takes vdata as a pair {DATA, CMP}: M = (M == CMP) ? DATA : M. Inactive lanes don't touch memory - and keep vdst; active unaligned lanes (addr % 4 != 0, or addr % 8 != 0 for _x2) leave memory untouched and - write 0 / (0, 0) to vdst (measured natively on gfx1036). and/or/xor/swap_x2 work on a 64-bit element (two - dwords, low first) as one 32-bit atomic per dword, with no Int64 atomics. That leaves the same memory for a - bitwise op, whose bits are independent, but not always for an exchange: two lanes swapping into one element at - once can leave one's low dword with the other's high dword (A.lo, B.lo, B.hi, A.hi). The returned pair is two - reads, so another lane's 64-bit op on the same element between them could be seen half done. The other _x2 - forms (add/sub/min/max carry or compare across the dwords, cmpswap_x2 compares all 64 bits) and inc/dec stay - Unsupported. fcmpswap compares as binary32 (float_cmpswap_loop).""" - kind = op[len("global_atomic_"):] - if kind in ("and_x2", "or_x2", "xor_x2", "swap_x2"): - return self.global_atomic_x2(op, kind[:-3], a, mods) - if kind in ("fmin", "fmax"): - return self.global_atomic_float(op, kind, a, mods) - is_inc_dec = kind in ("inc", "dec", "csub") - fcmp = kind == "fcmpswap" # float compare: see float_cmpswap_loop - known = kind in self.BUF_ATOMICS or is_inc_dec or fcmp - if not known or any(m in mods for m in ("slc", "dlc", "lds")): - raise Unsupported(op if not known else op + " form") - rtn = "glc" in mods - if len(a) != (4 if rtn else 3): - raise Unsupported(op + " operands") - vdst, vaddr, vdata, saddr = a if rtn else (None,) + tuple(a) - if vdata["k"] != "vgpr" or vdata.get("n", 1) != (2 if kind in ("cmpswap", "fcmpswap") else 1) or \ - (vdst is not None and (vdst["k"] != "vgpr" or vdst.get("n", 1) != 1)): - raise Unsupported(op + " operands") - full = self.global_address(op, vaddr, saddr, mods) - val = self.load_reg("vgpr", vdata["r"]) - cmp = self.load_reg("vgpr", vdata["r"] + 1) if kind in ("cmpswap", "fcmpswap") else None - al = self.atomic_aligned(full, 4) - cond = self.tmp() - self.emit(f"{cond} = OpLogicalAnd %bool {self.active_b()} {al}") - lbl_do, lbl_end, old = self.tmp() + "_do", self.tmp() + "_end", self.tmp() - pre = self.current_label_placeholder() - self.emit(f"OpSelectionMerge {lbl_end} None") - self.emit(f"OpBranchConditional {cond} {lbl_do} {lbl_end}") - self.emit(f"{lbl_do} = OpLabel") - ptr, p = self.tmp(), self.tmp() - self.emit(f"{ptr} = OpConvertUToPtr %_ptr_PSB_arr {self.host_addr(full)}") - self.emit(f"{p} = OpAccessChain %_ptr_PSB_uint {ptr} {self.cu(0)}") - if is_inc_dec: - res, done_lbl = self.atomic_inc_dec_cas(p, val, kind, lbl_do) - elif fcmp: - res = self.float_cmpswap_loop(p, val, cmp, self.cu(1)) - done_lbl = self.current_label_placeholder() # the loop's exit block - else: - res, done_lbl = self.tmp(), lbl_do - if kind == "cmpswap": - self.emit(f"{res} = OpAtomicCompareExchange %uint {p} {self.cu(1)} {self.cu(0)} {self.cu(0)} {val} {cmp}") - else: - self.emit(f"{res} = {self.BUF_ATOMICS[kind][0]} %uint {p} {self.cu(1)} {self.cu(0)} {val}") - self.emit(f"OpBranch {lbl_end}") - self.emit(f"{lbl_end} = OpLabel") - self.emit(f"{old} = OpPhi %uint {res} {done_lbl} {self.cu(0)} {pre}") - if vdst is not None: - self.dst(vdst, old) - - def global_atomic_float(self, op, kind, a, mods): - """global_atomic_{fmin,fmax} [vdst,] vaddr, vdata, saddr|off [offset:N] [glc]: 32-bit float min/max at the - global_* address via a CAS loop (OpAtomicCompareExchange + GLSL.std.450 NMin/NMax, so no shader float atomic - extension is needed). Inactive lanes don't touch memory and keep vdst; active unaligned lanes write 0.""" - if any(m in mods for m in ("slc", "dlc", "lds")): - raise Unsupported(op + " form") - rtn = "glc" in mods - if len(a) != (4 if rtn else 3): - raise Unsupported(op + " operands") - vdst, vaddr, vdata, saddr = a if rtn else (None,) + tuple(a) - if vdata["k"] != "vgpr" or vdata.get("n", 1) != 1 or \ - (vdst is not None and (vdst["k"] != "vgpr" or vdst.get("n", 1) != 1)): - raise Unsupported(op + " operands") - full = self.global_address(op, vaddr, saddr, mods) - val_f = self.tof(self.load_reg("vgpr", vdata["r"])) - al = self.atomic_aligned(full, 4) - cond = self.tmp() - self.emit(f"{cond} = OpLogicalAnd %bool {self.active_b()} {al}") - old = self._emit_atomic_fminmax_cas(kind, full, val_f, cond) - if vdst is not None: - self.dst(vdst, old) - - def global_atomic_x2(self, op, kind, a, mods): - """global_atomic_{and,or,xor,swap}_x2 (see global_atomic): one 32-bit atomic per dword of the element.""" - if any(m in mods for m in ("slc", "dlc", "lds")): - raise Unsupported(op + " form") - rtn = "glc" in mods - if len(a) != (4 if rtn else 3): - raise Unsupported(op + " operands") - vdst, vaddr, vdata, saddr = a if rtn else (None,) + tuple(a) - if vdata["k"] != "vgpr" or vdata.get("n", 1) != 2 or \ - (vdst is not None and (vdst["k"] != "vgpr" or vdst.get("n", 1) != 2)): - raise Unsupported(op + " operands") - full = self.global_address(op, vaddr, saddr, mods) - vals = [self.load_reg("vgpr", vdata["r"] + w) for w in range(2)] - spv = self.BUF_ATOMICS[kind][0] - al = self.atomic_aligned(full, 8) - cond = self.tmp() - self.emit(f"{cond} = OpLogicalAnd %bool {self.active_b()} {al}") - lbl_do, lbl_end = self.tmp() + "_do", self.tmp() + "_end" - pre = self.current_label_placeholder() - self.emit(f"OpSelectionMerge {lbl_end} None") - self.emit(f"OpBranchConditional {cond} {lbl_do} {lbl_end}") - self.emit(f"{lbl_do} = OpLabel") - ptr = self.tmp() - self.emit(f"{ptr} = OpConvertUToPtr %_ptr_PSB_arr {self.host_addr(full)}") - res = [] - for w in range(2): - p, r = self.tmp(), self.tmp() - self.emit(f"{p} = OpAccessChain %_ptr_PSB_uint {ptr} {self.cu(w)}") - self.emit(f"{r} = {spv} %uint {p} {self.cu(1)} {self.cu(0)} {vals[w]}") - res.append(r) - self.emit(f"OpBranch {lbl_end}") - self.emit(f"{lbl_end} = OpLabel") - olds = [] - for w in range(2): # both OpPhi first: they must open the merge block - old = self.tmp() - self.emit(f"{old} = OpPhi %uint {res[w]} {lbl_do} {self.cu(0)} {pre}") - olds.append(old) - if vdst is not None: - for w in range(2): - self.dst({"k": "vgpr", "r": vdst["r"] + w, "n": 1}, olds[w]) - - def float_cmpswap_loop(self, p, new, cmp, scope): - """tmp = M; M = (tmp == CMP as binary32) ? NEW : tmp; returns tmp (RDNA2 ISA, *_FCMPSWAP / DS_CMPST_F32). A - float compare (OpFOrdEqual: -0 == +0, a NaN never matches) is not what OpAtomicCompareExchange compares (the - bits), so this is a loop: read M (an atomic load at `scope`, as atomic_inc_dec_cas), pick NEW or M by the float - compare, swap that in if M still holds what was read, else retry. Exact under contention. p: a uint pointer - (PhysicalStorageBuffer with device scope, or Workgroup).""" - lbl_hdr, lbl_cont, lbl_exit = (self.tmp() + t for t in ("_hdr", "_cont", "_exit")) - init = self.tmp() - self.emit(f"{init} = OpAtomicLoad %uint {p} {scope} {self.cu(0)}") - entry = self.current_label_placeholder() - self.emit(f"OpBranch {lbl_hdr}") - self.emit(f"{lbl_hdr} = OpLabel") - cur, cf, kf, eq, st, got, done = (self.tmp() for _ in range(7)) - self.emit(f"{cur} = OpPhi %uint {init} {entry} {got} {lbl_cont}") - self.emit(f"{cf} = OpBitcast %float {cur}") - self.emit(f"{kf} = OpBitcast %float {cmp}") - self.emit(f"{eq} = OpFOrdEqual %bool {cf} {kf}") - self.emit(f"{st} = OpSelect %uint {eq} {new} {cur}") - self.emit(f"{got} = OpAtomicCompareExchange %uint {p} {scope} {self.cu(0)} {self.cu(0)} {st} {cur}") - self.emit(f"{done} = OpIEqual %bool {got} {cur}") - self.emit(f"OpLoopMerge {lbl_exit} {lbl_cont} None") - self.emit(f"OpBranchConditional {done} {lbl_exit} {lbl_cont}") - self.emit(f"{lbl_cont} = OpLabel") - self.emit(f"OpBranch {lbl_hdr}") - self.emit(f"{lbl_exit} = OpLabel") - return cur - - def buffer_atomic(self, op, a, mods): - """buffer_atomic_ vdata, vaddr, s[V#], soffset ...: 32-bit atomic at the element address (buffer device - address). With 'glc' the pre-op value is returned in vdata. Inactive lanes don't touch memory and keep vdata; - active OOB or unaligned (addr % 4 != 0) lanes leave memory untouched and write 0 with glc (measured on gfx1036).""" - kind = op[len("buffer_atomic_"):] - if kind in ("and_x2", "or_x2", "xor_x2", "swap_x2"): - return self.buffer_atomic_x2(op, kind[:-3], a, mods) - if kind in ("fmin", "fmax"): - return self.buffer_atomic_float(op, kind, a, mods) - is_inc_dec = kind in ("inc", "dec", "csub") - fcmp = kind == "fcmpswap" # float compare: see float_cmpswap_loop - if (kind not in self.BUF_ATOMICS and not is_inc_dec and not fcmp) or "x2" in kind: - raise Unsupported(op) - vd = a[0] - if is_inc_dec and (vd["k"] != "vgpr" or vd.get("n", 1) != 1): - raise Unsupported(op + " data") - addr, _, in_b, _ = self.buffer_address(a, mods) - val = self.load_reg("vgpr", vd["r"]) - al = self.atomic_aligned(addr, 4) - ok, cond = self.tmp(), self.tmp() - self.emit(f"{ok} = OpLogicalAnd %bool {in_b} {al}") - self.emit(f"{cond} = OpLogicalAnd %bool {self.active_b()} {ok}") - # Guard all atomics with a structured if so inactive, OOB or unaligned lanes never touch memory. - lbl_do, lbl_end, old = self.tmp() + "_do", self.tmp() + "_end", self.tmp() - pre_label = self.current_label_placeholder() - self.emit(f"OpSelectionMerge {lbl_end} None") - self.emit(f"OpBranchConditional {cond} {lbl_do} {lbl_end}") - self.emit(f"{lbl_do} = OpLabel") - ptr, p = self.tmp(), self.tmp() - self.emit(f"{ptr} = OpConvertUToPtr %_ptr_PSB_arr {self.host_addr(addr)}") - self.emit(f"{p} = OpAccessChain %_ptr_PSB_uint {ptr} {self.cu(0)}") - if is_inc_dec: - res_do, done_lbl = self.atomic_inc_dec_cas(p, val, kind, lbl_do) - elif fcmp: - cmp = self.load_reg("vgpr", vd["r"] + 1) - res_do = self.float_cmpswap_loop(p, val, cmp, self.cu(1)) - done_lbl = self.current_label_placeholder() # the loop's exit block - else: - spv, _ = self.BUF_ATOMICS[kind] - res_do, done_lbl = self.tmp(), lbl_do - if kind == "cmpswap": - cmp = self.load_reg("vgpr", vd["r"] + 1) - self.emit(f"{res_do} = OpAtomicCompareExchange %uint {p} {self.cu(1)} {self.cu(0)} {self.cu(0)} {val} {cmp}") - elif kind == "swap": - self.emit(f"{res_do} = OpAtomicExchange %uint {p} {self.cu(1)} {self.cu(0)} {val}") - else: - self.emit(f"{res_do} = {spv} %uint {p} {self.cu(1)} {self.cu(0)} {val}") - self.emit(f"OpBranch {lbl_end}") - self.emit(f"{lbl_end} = OpLabel") - self.emit(f"{old} = OpPhi %uint {res_do} {done_lbl} {self.cu(0)} {pre_label}") - if "glc" in mods: - self.dst({"k": "vgpr", "r": vd["r"], "n": 1}, old) - - def buffer_atomic_float(self, op, kind, a, mods): - """buffer_atomic_{fmin,fmax} vdata, vaddr, s[V#], soffset ...: 32-bit float min/max at the MUBUF address via - the shared OpAtomicCompareExchange + GLSL.std.450 NMin/NMax CAS loop (no float-atomic extension needed). - Enforces V# bounds and 4-byte natural alignment; with glc returns the old word (0 when OOB/unaligned, - preserved when inactive).""" - if "lds" in mods: - raise Unsupported(op + " form") - vd = a[0] - if vd["k"] != "vgpr" or vd.get("n", 1) != 1: - raise Unsupported(op + " data") - addr, _, in_b, _ = self.buffer_address(a, mods) - val_f = self.tof(self.load_reg("vgpr", vd["r"])) - al = self.atomic_aligned(addr, 4) - ok, cond = self.tmp(), self.tmp() - self.emit(f"{ok} = OpLogicalAnd %bool {in_b} {al}") - self.emit(f"{cond} = OpLogicalAnd %bool {self.active_b()} {ok}") - old = self._emit_atomic_fminmax_cas(kind, addr, val_f, cond) - if "glc" in mods: - self.dst({"k": "vgpr", "r": vd["r"], "n": 1}, old) - - def buffer_atomic_x2(self, op, kind, a, mods): - """buffer_atomic_{and,or,xor,swap}_x2 vdata[0:1], vaddr, s[V#], soffset: M = op(M, DATA) on the 64-bit element - (two dwords, low first); with glc the old 64 bits are returned in vdata. Each dword is its own 32-bit atomic, so - no Int64 atomics are needed. That leaves the same memory for a bitwise op, whose bits are independent, but an - exchange can tear: two lanes swapping into one element at once can leave one's low dword with the other's high - dword (A.lo, B.lo, B.hi, A.hi). The returned pair is two reads, so another lane's 64-bit op on the same element - between them could be seen half done. Measured natively on RDNA2 (gfx1036, wave32 & wave64): the bounds check - covers the whole 8-byte element all or nothing (fixed_fmt=62) and addresses with (addr & 7) != 0 are dropped - (memory untouched, active glc returns (0, 0), inactive preserves vdata).""" - vd = a[0] - if vd["k"] != "vgpr" or vd.get("n", 1) != 2: - raise Unsupported(op + " data") - addr, _, in_b, _ = self.buffer_address(a, mods, elem="fmt", fixed_fmt=62) # step: as buffer_atomic - vals = [self.load_reg("vgpr", vd["r"] + w) for w in range(2)] - al = self.atomic_aligned(addr, 8) - ok, cond = self.tmp(), self.tmp() - self.emit(f"{ok} = OpLogicalAnd %bool {in_b} {al}") - self.emit(f"{cond} = OpLogicalAnd %bool {self.active_b()} {ok}") - lbl_do, lbl_end = self.tmp() + "_do", self.tmp() + "_end" - pre = self.current_label_placeholder() - self.emit(f"OpSelectionMerge {lbl_end} None") - self.emit(f"OpBranchConditional {cond} {lbl_do} {lbl_end}") - self.emit(f"{lbl_do} = OpLabel") - ptr = self.tmp() - self.emit(f"{ptr} = OpConvertUToPtr %_ptr_PSB_arr {self.host_addr(addr)}") - res = [] - for w in range(2): - p, r = self.tmp(), self.tmp() - self.emit(f"{p} = OpAccessChain %_ptr_PSB_uint {ptr} {self.cu(w)}") - self.emit(f"{r} = {self.BUF_ATOMICS[kind][0]} %uint {p} {self.cu(1)} {self.cu(0)} {vals[w]}") - res.append(r) - self.emit(f"OpBranch {lbl_end}") - self.emit(f"{lbl_end} = OpLabel") - olds = [] - for w in range(2): # both OpPhi first: they must open the merge block - old = self.tmp() - # an inactive, out-of-range or unaligned lane skips the atomic (active gets 0, inactive keeps vdata via dst) - self.emit(f"{old} = OpPhi %uint {res[w]} {lbl_do} {self.cu(0)} {pre}") - olds.append(old) - if "glc" in mods: - for w in range(2): - self.dst({"k": "vgpr", "r": vd["r"] + w, "n": 1}, olds[w]) - - def current_label_placeholder(self): - """Label of the block currently being emitted (needed for OpPhi). Blocks are opened by OpLabel lines; - under --wave64-emulate only those of the current segment count (an earlier one runs in another round).""" - for line in reversed(self.body[self.x_marks[-1][0] if self.x_marks else 0:]): - s = line.strip() - if s.endswith("= OpLabel"): - return s.split(" = ")[0] - return self.block_label - - def image_get_lod(self, a, mods): - """image_get_lod vD, vaddr, T#, S#: (clamped lod, unclamped lod) like OpImageQueryLod (2D, 2D array). For - arrays the query takes only the 2D coordinate; the layer doesn't affect the LOD.""" - dim = next((m for m in mods if m.startswith("dim:")), "dim:SQ_RSRC_IMG_2D") - if dim not in ("dim:SQ_RSRC_IMG_2D", "dim:SQ_RSRC_IMG_2D_ARRAY") or self.stage != "ps": - raise Unsupported("image_get_lod form") - a16 = "a16" in mods - if a16 and ("tfe" in mods or "lwe" in mods): - raise Unsupported("image_get_lod form") - arr = dim.endswith("_ARRAY") - if arr: - self.uses_tex_array = True - dm = next((m for m in mods if m.startswith("dmask:")), "dmask:0x3") - dmask = int(dm.split(":")[1], 0) - vdata = a[0] - if vdata["k"] != "vgpr": # `off`, an SGPR or a constant where the VGPR range of the result goes - raise Unsupported("image_get_lod destination") - addr = self.addr_regs(a[1]) - img_idx = self.desc_lookup_sgpr(a[2], 8) - smp_idx = self.desc_lookup_sgpr(a[3], 4) - ip, img, sp, smp, si = (self.tmp() for _ in range(5)) - self.dynamic_sampled_access(ip, "%_ptr_UC_imga" if arr else "%_ptr_UC_img", - "%images_arr" if arr else "%images", img_idx) - self.emit(f"{img} = OpLoad {'%img2da' if arr else '%img2d'} {ip}") - self.dynamic_sampled_access(sp, "%_ptr_UC_smp", "%samplers", smp_idx) - self.emit(f"{smp} = OpLoad %smp {sp}") - self.emit(f"{si} = OpSampledImage {'%simg2da' if arr else '%simg2d'} {img} {smp}") - if a16: - # U and V occupy the low and high halves of the first address VGPR. The array layer - # is a separate address component and does not contribute to the LOD derivatives. - packed = self.load_reg("vgpr", addr[0]) - uv = self.tmp() - self.emit(f"{uv} = OpExtInst %v2float %glsl UnpackHalf2x16 {packed}") - else: - f = [self.tof(self.load_reg("vgpr", r)) for r in addr[:2]] - uv = self.tmp() - self.emit(f"{uv} = OpCompositeConstruct %v2float {f[0]} {f[1]}") - lod = self.tmp() - self.emit(f"{lod} = OpImageQueryLod %v2float {si} {uv}") - self.uses_query = True - out = 0 - for c in range(2): - if dmask >> c & 1: - comp = self.tmp() - self.emit(f"{comp} = OpCompositeExtract %float {lod} {c}") - self.dst({"k": "vgpr", "r": vdata["r"] + out, "n": 1}, self.tou(comp)) - out += 1 - - def fmt_table_get(self, ptr_type, table, index, elem="%uint"): - """One element of a module-level table (a Private array indexed by a run-time value). - - The result type is a pointer to the element, as an OpAccessChain into an array needs.""" - p = self.tmp() - self.emit(f"{p} = OpAccessChain {ptr_type} {table} {index}") - v = self.tmp() - self.emit(f"{v} = OpLoad {elem} {p}") - return v - - def fmt_norm_bits_dyn(self, m, n): - """The f32 bits of m / (2^n - 1), correctly rounded, with n a run-time width (SHADER-849). - - The same code as norm_bits, but the 64-bit repeat constant of the width comes from a table and the width is a - value: the quotient of a field by 2^n - 1 depends on nothing else.""" - rep = self.fmt_table_get("%_ptr_Private_fmt_elem64", "%fmt_norm_rep_tab", n, "%ulong") - m64, t, h64, hi, pi, p, s, s64, q64, q, s1, s164, r64, rb = (self.tmp() for _ in range(14)) - self.emit(f"{m64} = OpUConvert %ulong {m}") - self.emit(f"{t} = OpIMul %ulong {m64} {rep}") - self.emit(f"{h64} = OpShiftRightLogical %ulong {t} {self.cu(32)}") - self.emit(f"{hi} = OpUConvert %uint {h64}") - self.emit(f"{pi} = OpExtInst %int %glsl FindUMsb {hi}") - self.emit(f"{p} = OpBitcast %uint {pi}") - self.emit(f"{s} = OpIAdd %uint {p} {self.cu(9)}") # m = 0 gives p = -1: s = 8, result unused - self.emit(f"{s64} = OpUConvert %ulong {s}") - self.emit(f"{q64} = OpShiftRightLogical %ulong {t} {s64}") - self.emit(f"{q} = OpUConvert %uint {q64}") - self.emit(f"{s1} = OpISub %uint {s} {self.cu(1)}") - self.emit(f"{s164} = OpUConvert %ulong {s1}") - self.emit(f"{r64} = OpShiftRightLogical %ulong {t} {s164}") - self.emit(f"{rb} = OpUConvert %uint {r64}") - e, eb, b0, b1, b2, b3 = (self.tmp() for _ in range(6)) - self.emit(f"{e} = OpIAdd %uint {p} {self.cu(95)}") # biased exponent p - 32 + 127 - self.emit(f"{eb} = OpShiftLeftLogical %uint {e} {self.cu(23)}") - self.emit(f"{b0} = OpISub %uint {q} {self.cu(0x800000)}") # drop the hidden one - self.emit(f"{b1} = OpIAdd %uint {eb} {b0}") - self.emit(f"{b2} = OpBitwiseAnd %uint {rb} {self.cu(1)}") - self.emit(f"{b3} = OpIAdd %uint {b1} {b2}") - sh, one, m1, is_one, b4, z, res = (self.tmp() for _ in range(7)) - self.emit(f"{sh} = OpBitwiseAnd %uint {n} {self.cu(31)}") - self.emit(f"{one} = OpShiftLeftLogical %uint {self.cu(1)} {sh}") - self.emit(f"{m1} = OpISub %uint {one} {self.cu(1)}") - self.emit(f"{is_one} = OpIEqual %bool {m} {m1}") - self.emit(f"{b4} = OpSelect %uint {is_one} {self.cu(0x3F800000)} {b3}") - self.emit(f"{z} = OpIEqual %bool {m} {self.cu(0)}") - self.emit(f"{res} = OpSelect %uint {z} {self.cu(0)} {b4}") - return res - - def fmt_norm_function(self): - """The shared %fmt_norm_bits(m, n): the exact quotient by 2^n - 1 for a run-time width.""" - if self.fmt_norm_fn is None: - saved, self.body = self.body, [] - res = self.fmt_norm_bits_dyn("%fn_m", "%fn_n") - lines, self.body = self.body, saved - self.fmt_norm_fn = (["%fmt_norm_bits = OpFunction %uint None %fn_fmt_norm", - "%fn_m = OpFunctionParameter %uint", "%fn_n = OpFunctionParameter %uint", - "%fmt_norm_entry = OpLabel"] + lines + [f"OpReturnValue {res}", "OpFunctionEnd"]) - return self.fmt_norm_fn - - def fmt_dec_component(self, k, params): - """The value of output component k of an element of the run-time FORMAT, branch-free (SHADER-849). - - The format's kind, channel count and channel widths come from one table word; the conversion the kind names - is chosen with selects, so the decode has no branch and the module carries one copy of it, not one per - format. A format with fewer channels repeats its own (component c = c mod n), as the RX 6700 does (SHADER-86).""" - fmt, wvec = params[0], params[1] - # The four dwords of the element, as a v4uint: the function type must not repeat another one in the module - # (SPIR-V forbids two non-aggregate types with the same structure). - words = [] - for i in range(4): - e = self.tmp() - self.emit(f"{e} = OpCompositeExtract %uint {wvec} {i}") - words.append(e) - # The table word: kind | channel count << 4 | the four channel widths. - desc = self.fmt_table_get("%_ptr_Private_fmt_elem", "%fmt_desc_tab", fmt) - mode = self.tmp() - self.emit(f"{mode} = OpBitwiseAnd %uint {desc} {self.cu(15)}") - ncomp_raw, ncomp = self.tmp(), self.tmp() - self.emit(f"{ncomp_raw} = OpShiftRightLogical %uint {desc} {self.cu(4)}") - self.emit(f"{ncomp} = OpBitwiseAnd %uint {ncomp_raw} {self.cu(7)}") - widths = [] - for i in range(4): - raw, w = self.tmp(), self.tmp() - self.emit(f"{raw} = OpShiftRightLogical %uint {desc} {self.cu(7 + 6 * i)}") - self.emit(f"{w} = OpBitwiseAnd %uint {raw} {self.cu(63)}") - widths.append(w) - # The channel of the format that output component k takes: component c = c mod n. - # Its width and its bit offset (the sum of the widths before it). - if k == 0: - wid, off = widths[0], self.cu(0) - else: - offsets = [self.cu(0)] - for i in range(1, 4): - o = self.tmp() - self.emit(f"{o} = OpIAdd %uint {offsets[-1]} {widths[i - 1]}") - offsets.append(o) - if k == 1: - one, wid, off = self.tmp(), self.tmp(), self.tmp() - self.emit(f"{one} = OpIEqual %bool {ncomp} {self.cu(1)}") - self.emit(f"{wid} = OpSelect %uint {one} {widths[0]} {widths[1]}") - self.emit(f"{off} = OpSelect %uint {one} {offsets[0]} {offsets[1]}") - elif k == 2: - two, wid, off = self.tmp(), self.tmp(), self.tmp() - self.emit(f"{two} = OpULessThanEqual %bool {ncomp} {self.cu(2)}") - self.emit(f"{wid} = OpSelect %uint {two} {widths[0]} {widths[2]}") - self.emit(f"{off} = OpSelect %uint {two} {offsets[0]} {offsets[2]}") - else: - one, two, three = self.tmp(), self.tmp(), self.tmp() - w1, w2, wid, o1, o2, off = (self.tmp() for _ in range(6)) - self.emit(f"{one} = OpIEqual %bool {ncomp} {self.cu(1)}") - self.emit(f"{two} = OpIEqual %bool {ncomp} {self.cu(2)}") - self.emit(f"{three} = OpIEqual %bool {ncomp} {self.cu(3)}") - # component 3 takes channel 0 of a one- or three-channel format, channel 1 of a two-channel one - # and channel 3 of a four-channel one - self.emit(f"{w1} = OpSelect %uint {three} {widths[0]} {widths[3]}") - self.emit(f"{w2} = OpSelect %uint {two} {widths[1]} {w1}") - self.emit(f"{wid} = OpSelect %uint {one} {widths[0]} {w2}") - self.emit(f"{o1} = OpSelect %uint {three} {offsets[0]} {offsets[3]}") - self.emit(f"{o2} = OpSelect %uint {two} {offsets[1]} {o1}") - self.emit(f"{off} = OpSelect %uint {one} {offsets[0]} {o2}") - # A code outside FORMATS has no channel: keep the width at 1, so the shifts below stay defined. - is0, wid2 = self.tmp(), self.tmp() - self.emit(f"{is0} = OpIEqual %bool {wid} {self.cu(0)}") - self.emit(f"{wid2} = OpSelect %uint {is0} {self.cu(1)} {wid}") - wid = wid2 - # The dword the channel starts in, and the field itself. - wi = self.tmp() - self.emit(f"{wi} = OpShiftRightLogical %uint {off} {self.cu(5)}") - word = words[0] - for i in (1, 2, 3): - eq, sel = self.tmp(), self.tmp() - self.emit(f"{eq} = OpIEqual %bool {wi} {self.cu(i)}") - self.emit(f"{sel} = OpSelect %uint {eq} {words[i]} {word}") - word = sel - shift = self.tmp() - self.emit(f"{shift} = OpBitwiseAnd %uint {off} {self.cu(31)}") - shifted = self.tmp() - self.emit(f"{shifted} = OpShiftRightLogical %uint {word} {shift}") - wsh, one, m1, is32, mask, raw = (self.tmp() for _ in range(6)) - self.emit(f"{wsh} = OpBitwiseAnd %uint {wid} {self.cu(31)}") - self.emit(f"{one} = OpShiftLeftLogical %uint {self.cu(1)} {wsh}") - self.emit(f"{m1} = OpISub %uint {one} {self.cu(1)}") - self.emit(f"{is32} = OpIEqual %bool {wid} {self.cu(32)}") - self.emit(f"{mask} = OpSelect %uint {is32} {self.cu(0xFFFFFFFF)} {m1}") - self.emit(f"{raw} = OpBitwiseAnd %uint {shifted} {mask}") - # The field as a signed value, for the signed kinds. - sw, lsh, si = self.tmp(), self.tmp(), self.tmp() - self.emit(f"{sw} = OpISub %uint {self.cu(32)} {wid}") - self.emit(f"{lsh} = OpShiftLeftLogical %uint {raw} {sw}") - self.emit(f"{si} = OpShiftRightArithmetic %int {self.as_int(lsh)} {sw}") - sv = self.int_bits(si) - # The candidates of the kinds that convert the field to a float. - fr, fs = self.tmp(), self.tmp() - self.emit(f"{fr} = OpConvertUToF %float {raw}") - self.emit(f"{fs} = OpConvertSToF %float {si}") - c_fraw, c_fsv = self.tou(fr), self.tou(fs) - # The exact quotient by 2^n - 1: UNORM divides the field by 2^w - 1, SNORM its magnitude by 2^(w-1) - 1. - ab, au = self.tmp(), self.tmp() - self.emit(f"{ab} = OpExtInst %int %glsl SAbs {si}") - self.emit(f"{au} = OpBitcast %uint {ab}") - is_snorm, num, w1, n, hi_n, zero_n, n2 = (self.tmp() for _ in range(7)) - self.emit(f"{is_snorm} = OpIEqual %bool {mode} {self.cu(self.FMT_SNORM)}") - self.emit(f"{num} = OpSelect %uint {is_snorm} {au} {raw}") - self.emit(f"{w1} = OpISub %uint {wid} {self.cu(1)}") - self.emit(f"{n} = OpSelect %uint {is_snorm} {w1} {wid}") - self.emit(f"{hi_n} = OpUGreaterThan %bool {n} {self.cu(16)}") - self.emit(f"{n2} = OpSelect %uint {hi_n} {self.cu(16)} {n}") - self.emit(f"{zero_n} = OpIEqual %bool {n2} {self.cu(0)}") - n3 = self.tmp() - self.emit(f"{n3} = OpSelect %uint {zero_n} {self.cu(1)} {n2}") - c_norm = self.tmp() - self.emit(f"{c_norm} = OpFunctionCall %uint %fmt_norm_bits {num} {n3}") - # SNORM: the magnitude's quotient with the sign, and the most negative code as -1.0. - neg, sgn, signed_norm, lim, is_min, c_snorm = (self.tmp() for _ in range(6)) - self.emit(f"{neg} = OpSLessThan %bool {si} {self.as_int(self.cu(0))}") - self.emit(f"{sgn} = OpBitwiseOr %uint {c_norm} {self.cu(0x80000000)}") - self.emit(f"{signed_norm} = OpSelect %uint {neg} {sgn} {c_norm}") - self.emit(f"{lim} = OpShiftLeftLogical %uint {self.cu(1)} {w1}") - self.emit(f"{is_min} = OpULessThan %bool {au} {lim}") - self.emit(f"{c_snorm} = OpSelect %uint {is_min} {signed_norm} {self.cu(0xBF800000)}") - # The two float kinds with their own layout. - c_f16 = self.f16_widen_bits(raw) - c_ufloat = self.ufloat_decode_bits(raw, wid) - # The kind picks the value: a code outside FORMATS (FMT_NONE) matches none and gives 0. - res = self.cu(0) - for kind, value in ((self.FMT_UFLOAT, c_ufloat), (self.FMT_F16, c_f16), (self.FMT_SNORM, c_snorm), - (self.FMT_UNORM, c_norm), (self.FMT_SSCALED, c_fsv), (self.FMT_USCALED, c_fraw), - (self.FMT_SINT, sv), (self.FMT_RAW, raw)): - eq, sel = self.tmp(), self.tmp() - self.emit(f"{eq} = OpIEqual %bool {mode} {self.cu(kind)}") - self.emit(f"{sel} = OpSelect %uint {eq} {value} {res}") - res = sel - return res - - def fmt_dec_functions(self): - """The shared per-component decode functions (SHADER-849), one per output component.""" - if self.fmt_fn is None: - self.uses_fmt_tables = True - # The tables are constants: register them here, while the constant section can still take them. - for v in Gen.fmt_desc_table(): - self.cu(v) - for v in Gen.fmt_norm_reps(): - self.cl(v) - fns = list(self.fmt_norm_function()) - for k in range(4): - saved, self.body = self.body, [] - params = [f"%fd{k}_fmt", f"%fd{k}_words"] - res = self.fmt_dec_component(k, params) - lines, self.body = self.body, saved - fns += ([f"%fmt_dec_c{k} = OpFunction %uint None %fn_fmt_dec"] + - [f"{params[0]} = OpFunctionParameter %uint", f"{params[1]} = OpFunctionParameter %v4uint_fmt"] + - [f"%fmt_dec_c{k}_entry = OpLabel"] + lines + [f"OpReturnValue {res}", "OpFunctionEnd"]) - self.fmt_fn = fns - return self.fmt_fn - - def format_decode_call(self, fmt, words): - """4 uint ids: the element decoded per the run-time FORMAT, through the shared per-component functions. - - One function per output component (SHADER-849): the run-time format picks the conversion with selects, so the - decode has no branch and the module carries one copy of it, not one copy per format. Before, the shared - function held every format's decode and a binary search over the codes: 3,498 instructions and 306 branches - in a module, 250 KB for a shader with one dynamic-format load.""" - self.fmt_dec_functions() - # The four dwords of the element, as one v4uint: the decode functions take them as a vector. - wvec = self.tmp() - self.emit(f"{wvec} = OpCompositeConstruct %v4uint_fmt " + " ".join(words[:4])) - comps = [] - for k in range(4): - r = self.tmp() - self.emit(f"{r} = OpFunctionCall %uint %fmt_dec_c{k} {fmt} {wvec}") - comps.append(r) - return comps - - def fmt_size_of(self, fmt): - """Byte size of the 7-bit buffer FORMAT code `fmt` (a uint id), 0 for a code FORMATS does not decode: one load - from %fmt_size_tab. Typed loads used to select it through a chain over all of FORMATS per load (about 150 - instructions); ScreenProbes_ActivateProbes has 3,281 such loads and its module was 2.5 M ids.""" - self.uses_fmt_size = True - # The table's length and entries are constants: register them here, while the constant section can still - # take them, not at assembly (an OpTypeArray naming a constant declared after it fails spirv-val). - for v in {128, 0, *(f[0] for f in self.FORMATS.values())}: - self.cu(v) - ptr, size = self.tmp(), self.tmp() - self.emit(f"{ptr} = OpAccessChain %_ptr_Private_uint %fmt_size_tab {fmt}") - self.emit(f"{size} = OpLoad %uint {ptr}") - return size - - def buffer_load_format(self, op, a, mods, fixed_fmt=None): - """buffer_load_format_[x|xy|xyz|xyzw]: element at V#.base + offsets, decoded per the V# FORMAT field - (word3 bits 12-18), then swizzled by DST_SEL_X/Y/Z/W (word3 bits 0-11: 0=0, 1=1, 4..7 = X..W). - Formats outside FORMATS decode to 0. An element that starts mid-dword may spill into later dwords: - need = ceil((byte_shift + size) / 4) loaded dwords, then the window is shifted so decode sees a - packed stream starting at the element. The bounds check is on the whole element (buffer_address, elem="fmt").""" - if fixed_fmt is not None: - self.fixed_format_codes.add(fixed_fmt) - else: - self.dynamic_format = True - if any(m in mods for m in ("lds", "tfe", "d16")): - raise Unsupported(op + " form") - d16 = "_d16_" in op - ncomp = len(op.rsplit("_", 1)[1]) - vd = a[0] - addr, d3, in_b, step = self.buffer_address(a, mods, elem="fmt", fixed_fmt=fixed_fmt) - if fixed_fmt is not None: - # An INVALID V# format denotes an unbound resource, even for an explicit MTBUF format. - descriptor_format, bound, accessible = (self.tmp() for _ in range(3)) - self.emit(f"{descriptor_format} = OpBitFieldUExtract %uint {d3} {self.cu(12)} {self.cu(7)}") - self.emit(f"{bound} = OpINotEqual %bool {descriptor_format} {self.cu(0)}") - self.emit(f"{accessible} = OpLogicalAnd %bool {in_b} {bound}") - in_b = accessible - fmt = self.cu(fixed_fmt) # tbuffer: format from the instruction - else: - fmt = self.tmp() - self.emit(f"{fmt} = OpBitFieldUExtract %uint {d3} {self.cu(12)} {self.cu(7)}") - # Byte address of the element, split into a dword-aligned address and a byte shift (for 1/2-byte formats). - alo, bsh, al64, aligned, b3 = (self.tmp() for _ in range(5)) - self.emit(f"{alo} = OpUConvert %uint {addr}") - self.emit(f"{b3} = OpBitwiseAnd %uint {alo} {self.cu(3)}") - self.emit(f"{bsh} = OpIMul %uint {b3} {self.cu(8)}") - self.emit(f"{al64} = OpUConvert %ulong {b3}") - self.emit(f"{aligned} = OpISub %ulong {addr} {al64}") - # How many dwords the element occupies, including a mid-dword start: - # need = ceil((byte_shift + size) / 4) = (b3 + size + 3) >> 2. A 16-byte - # element that starts at byte 3 spans 5 dwords. Extra unused loads re-read - # dword 0 so a load never walks an out-of-range index. - # (a format FORMATS does not decode loads one dword, as before) - if fixed_fmt is not None: - if fixed_fmt in self.FORMATS: - sum_, need = self.tmp(), self.tmp() - self.emit(f"{sum_} = OpIAdd %uint {b3} {self.cu(self.FORMATS[fixed_fmt][0] + 3)}") - self.emit(f"{need} = OpShiftRightLogical %uint {sum_} {self.cu(2)}") - else: - need = self.cu(1) - else: - size = self.fmt_size_of(fmt) - known, sum_, sum3, n2, need = (self.tmp() for _ in range(5)) - self.emit(f"{known} = OpINotEqual %bool {size} {self.cu(0)}") - self.emit(f"{sum_} = OpIAdd %uint {b3} {size}") - self.emit(f"{sum3} = OpIAdd %uint {sum_} {self.cu(3)}") - self.emit(f"{n2} = OpShiftRightLogical %uint {sum3} {self.cu(2)}") - self.emit(f"{need} = OpSelect %uint {known} {n2} {self.cu(1)}") - # Two-byte typed loads at odd effective addresses read like out-of-bounds - # loads, including the descriptor's constant channel selectors. - if fixed_fmt is None or self.FORMATS.get(fixed_fmt, (0,))[0] == 2: - low_bit, even = self.tmp(), self.tmp() - self.emit(f"{low_bit} = OpBitwiseAnd %uint {alo} {self.cu(1)}") - self.emit(f"{even} = OpIEqual %bool {low_bit} {self.cu(0)}") - permitted = even - if fixed_fmt is None: - other_size, permitted = self.tmp(), self.tmp() - self.emit(f"{other_size} = OpINotEqual %bool {size} {self.cu(2)}") - self.emit(f"{permitted} = OpLogicalOr %bool {other_size} {even}") - accessible = self.tmp() - self.emit(f"{accessible} = OpLogicalAnd %bool {in_b} {permitted}") - in_b = accessible - cond = self.tmp() - self.emit(f"{cond} = OpLogicalAnd %bool {self.active_b()} {in_b}") - lbl_do, lbl_end = self.tmp() + "_do", self.tmp() + "_end" - pre_label = self.current_label_placeholder() - self.emit(f"OpSelectionMerge {lbl_end} None") - self.emit(f"OpBranchConditional {cond} {lbl_do} {lbl_end}") - self.emit(f"{lbl_do} = OpLabel") - ptr, host = self.tmp(), self.host_addr(aligned) - self.emit(f"{ptr} = OpConvertUToPtr %_ptr_PSB_arr {host}") - loaded = [] - for i in range(5): - ok, idx, v = self.tmp(), self.tmp(), self.tmp() - self.emit(f"{ok} = OpULessThan %bool {self.cu(i)} {need}") - self.emit(f"{idx} = OpSelect %uint {ok} {self.cu(i)} {self.cu(0)}") - p = self.buf_dword_ptr(ptr, host, step, idx) - self.emit(f"{v} = OpLoad %uint {p} Aligned 4") - loaded.append(v) - self.emit(f"OpBranch {lbl_end}") - self.emit(f"{lbl_end} = OpLabel") - words = [] - for v_do in loaded: - v = self.tmp() - self.emit(f"{v} = OpPhi %uint {v_do} {lbl_do} {self.cu(0)} {pre_label}") - words.append(v) - # Shift the whole window so dword 0 starts at the element. (32 - bsh) & 31 - # keeps the left shift below 32 when bsh is 0; that result is discarded. - packed = [] - for i in range(4): - w0s, w1sh0, w1sh, w1s, nz, merged, bw = (self.tmp() for _ in range(7)) - self.emit(f"{w0s} = OpShiftRightLogical %uint {words[i]} {bsh}") - self.emit(f"{w1sh0} = OpISub %uint {self.cu(32)} {bsh}") - self.emit(f"{w1sh} = OpBitwiseAnd %uint {w1sh0} {self.cu(31)}") - self.emit(f"{w1s} = OpShiftLeftLogical %uint {words[i + 1]} {w1sh}") - self.emit(f"{nz} = OpINotEqual %bool {bsh} {self.cu(0)}") - self.emit(f"{merged} = OpBitwiseOr %uint {w0s} {w1s}") - self.emit(f"{bw} = OpSelect %uint {nz} {merged} {words[i]}") - packed.append(bw) - words = packed - if fixed_fmt is not None: - # MTBUF takes both the format and its identity selectors from the instruction: - # X000, XY00, XYZ0 or XYZW. The V# selectors apply only to MUBUF. - comps = self.decode_format(words, fixed_fmt, fixed=True) - widths = self.FORMATS[fixed_fmt][2] - d3 = self.cu(sum((4 + c) << (3 * c) for c in range(len(widths)))) - else: - comps = self.format_decode_call(fmt, words) - # DST_SEL swizzle: 0 -> 0, 1 -> 1.0 (float/norm/scaled) or integer 1 (UINT/SINT, INVALID or reserved; - # SHADER-86, SHADER-429), 4..7 -> X..W. On an out-of-bounds MUBUF load `words` are 0 so `comps` decode to 0, - # while DST_SEL=1 still produces 1.0f / 1 (MTBUF overrides `d3` above with 4..7 / 0, so OOB and INVALID stay 0). - grp, bit, fmask = self.tmp(), self.tmp(), self.cu(0) - self.emit(f"{grp} = OpShiftRightLogical %uint {fmt} {self.cu(5)}") - self.emit(f"{bit} = OpBitwiseAnd %uint {fmt} {self.cu(31)}") - for g_idx, mask_val in enumerate(_FLOAT_FMT_MASKS): - eq, nxt = self.tmp(), self.tmp() - self.emit(f"{eq} = OpIEqual %bool {grp} {self.cu(g_idx)}") - self.emit(f"{nxt} = OpSelect %uint {eq} {self.cu(mask_val)} {fmask}") - fmask = nxt - fsh, fbit, is_int_fmt = self.tmp(), self.tmp(), self.tmp() - self.emit(f"{fsh} = OpShiftRightLogical %uint {fmask} {bit}") - self.emit(f"{fbit} = OpBitwiseAnd %uint {fsh} {self.cu(1)}") - self.emit(f"{is_int_fmt} = OpIEqual %bool {fbit} {self.cu(0)}") - is_signed = "%false" - if d16: - for code_v, (_, kind, _) in self.FORMATS.items(): - if kind in ("i32", "sint"): - e, signed = self.tmp(), self.tmp() - self.emit(f"{e} = OpIEqual %bool {fmt} {self.cu(code_v)}") - self.emit(f"{signed} = OpLogicalOr %bool {is_signed} {e}") - is_signed = signed - dst1 = self.tmp() - self.emit(f"{dst1} = OpSelect %uint {is_int_fmt} {self.cu(1)} {self.cu(0x3F800000)}") - # In-bounds gate applies to components read from buffer memory, leaving DST_SEL=1 intact (SHADER-429). - bounded_comps = [] - for comp in comps: - cb = self.tmp() - self.emit(f"{cb} = OpSelect %uint {in_b} {comp} {self.cu(0)}") - bounded_comps.append(cb) - outs = [] - for c in range(ncomp): - sel = self.tmp() - self.emit(f"{sel} = OpBitFieldUExtract %uint {d3} {self.cu(3 * c)} {self.cu(3)}") - r = self.cu(0) - for code_v, src in ((1, dst1), (4, bounded_comps[0]), (5, bounded_comps[1]), (6, bounded_comps[2]), (7, bounded_comps[3])): - e, s = self.tmp(), self.tmp() - self.emit(f"{e} = OpIEqual %bool {sel} {self.cu(code_v)}") - self.emit(f"{s} = OpSelect %uint {e} {src} {r}") - r = s - if d16: - outs.append(r) - else: - self.dst({"k": "vgpr", "r": vd["r"] + c, "n": 1}, r) - if d16: - # D16 packs two results per register, saturating integer formats according to signedness. - def int_half(word): - unsigned = self.saturate_int16(word, signed=False) - signed = self.saturate_int16(word, signed=True) - half = self.tmp() - self.emit(f"{half} = OpSelect %uint {is_signed} {signed} {unsigned}") - return half - - is_norm, is_f32 = "%false", "%false" - for code_v, (_, kind, _) in self.FORMATS.items(): - if kind in ("unorm", "snorm", "f32") and (fixed_fmt is None or code_v == fixed_fmt): - e, o = self.tmp(), self.tmp() - self.emit(f"{e} = OpIEqual %bool {fmt} {self.cu(code_v)}") - acc = is_f32 if kind == "f32" else is_norm - self.emit(f"{o} = OpLogicalOr %bool {acc} {e}") - if kind == "f32": - is_f32 = o - else: - is_norm = o - for i in range(0, len(outs), 2): - dest = {"k": "vgpr", "r": vd["r"] + i // 2, "n": 1} - lo = outs[i] - il = int_half(lo) - r = self.tmp() - if i + 1 == len(outs): - # For d16_x and d16_xyz the unaddressed high half keeps its previous bits. - fl = self.d16_norm_f16(lo, is_norm, is_f32) - self.emit(f"{r} = OpSelect %uint {is_int_fmt} {il} {fl}") - self.write_lo16(dest, r) - continue - hi = outs[i + 1] - ph = self.tmp() - fh_s = self.tmp() - self.emit(f"{fh_s} = OpShiftLeftLogical %uint {self.d16_norm_f16(hi, is_norm, is_f32)} {self.cu(16)}") - self.emit(f"{ph} = OpBitwiseOr %uint {self.d16_norm_f16(lo, is_norm, is_f32)} {fh_s}") - ih, pi = self.tmp(), self.tmp() - high_half = int_half(hi) - self.emit(f"{ih} = OpShiftLeftLogical %uint {high_half} {self.cu(16)}") - self.emit(f"{pi} = OpBitwiseOr %uint {il} {ih}") - self.emit(f"{r} = OpSelect %uint {is_int_fmt} {pi} {ph}") - self.dst(dest, r) - - # The f32 quotients m / (2^n - 1), 1 <= n <= 16, that land exactly on an f16 halfway point: 0x3f7ff000 is - # 16379/16383, 32759/32767 and 65519/65535, 0x3f7fb000 is 65455/65535 (an enumeration of every m and n). The exact - # quotient is below the halfway point each time, and RDNA2 rounds it once, straight to f16 (BUILD-161, RX 6700). - D16_NORM_HALFWAY = (0x3F7FF000, 0x3F7FB000) - - def d16_norm_f16(self, bits, is_norm, is_f32=None): - """f16 bits of a typed d16 buffer load component from its decoded f32 ``bits``. Round to nearest even - (f16_bits), except that a UNORM/SNORM quotient (``is_norm``) whose f32 is one of D16_NORM_HALFWAY takes the - f16 below it. The hardware rounds the exact quotient once; f32 first and then f16 rounds twice, which is 1 ulp - high on exactly those values (UNORM16 0xffaf and 0xffef, SNORM16 0x7ff7 and 0x8009, the 14- and 15-bit - twins). Measured on an RX 6700 (gfx1031) for every UNORM8/SNORM8/UNORM10/UNORM16/SNORM16 value, MUBUF and - MTBUF, wave32 and wave64 (tools/d16_format_probe.py). A 32-bit float format (``is_f32``) is narrowed toward - zero instead, finite values past the range giving +-65504: measured natively on gfx1036 for 32_FLOAT, - 32_32_FLOAT and 32_32_32_32_FLOAT, d16_x/xy/xyzw, wave32 and wave64 (SHADER-358).""" - h = self.f16_bits(self.tof(bits)) - if is_f32 is not None: - hz, sel = self.tmp(), self.tmp() - self.emit(f"{hz} = OpCopyObject %uint {self.mem_f16(self.tof(bits))}") - self.emit(f"{sel} = OpSelect %uint {is_f32} {hz} {h}") - h = sel - mag, a, b, hit, both, dn, out = (self.tmp() for _ in range(7)) - self.emit(f"{mag} = OpBitwiseAnd %uint {bits} {self.cu(0x7FFFFFFF)}") - self.emit(f"{a} = OpIEqual %bool {mag} {self.cu(self.D16_NORM_HALFWAY[0])}") - self.emit(f"{b} = OpIEqual %bool {mag} {self.cu(self.D16_NORM_HALFWAY[1])}") - self.emit(f"{hit} = OpLogicalOr %bool {a} {b}") - self.emit(f"{both} = OpLogicalAnd %bool {hit} {is_norm}") - self.emit(f"{dn} = OpISub %uint {h} {self.cu(1)}") # sign-magnitude: 1 ulp toward zero - self.emit(f"{out} = OpSelect %uint {both} {dn} {h}") - return out - - def global_address(self, op, vaddr, saddr, mods): - """The 64-bit Xbox GPU VA a global_* instruction accesses (ulong id): (saddr: 64-bit SGPR pair + zero-extended - 32-bit vaddr | off: 64-bit VGPR pair) + the signed 12-bit instruction offset.""" - # The instruction offset is a 12-bit signed byte offset, and llvm-mc prints it signed (offset:-4 for the - # field 0xffc; it rejects offset:0xffc and anything outside -2048..2047), which is the only spelling the - # disassembler and build.py deliver. RX 6800 (gfx1030): pointer 0x1000, offset:-4 reads byte 0xffc. - inst = [m.split(":", 1)[1] for m in mods if m.startswith("offset:")] - if len(inst) > 1: - raise Unsupported(f"{op} offset form") - try: - inst = int(inst[0], 0) if inst else 0 - except ValueError: - raise Unsupported(f"{op} offset:{inst[0]}") from None - if 0x800 <= inst <= 0xFFF: - inst -= 0x1000 # the raw 12-bit field from a tool that prints it unsigned: same offset - if not -0x800 <= inst <= 0x7FF: - raise Unsupported(f"{op} offset:{inst}") # not a 12-bit value: don't guess an address - if (saddr["k"] == "sgpr" and saddr.get("n") == 2) or (saddr["k"] == "slist" and len(saddr["r"]) == 2): - lo, hi = self.sgpr_words(saddr, 2) - voff = self.load_reg("vgpr", vaddr["r"]) - l64, h64, sh, base, v64, va = (self.tmp() for _ in range(6)) - self.emit(f"{l64} = OpUConvert %ulong {lo}") - self.emit(f"{h64} = OpUConvert %ulong {hi}") - self.emit(f"{sh} = OpShiftLeftLogical %ulong {h64} %c64_32") - self.emit(f"{base} = OpBitwiseOr %ulong {sh} {l64}") - self.emit(f"{v64} = OpUConvert %ulong {voff}") - self.emit(f"{va} = OpIAdd %ulong {base} {v64}") - elif saddr["k"] == "special" and saddr["t"] == "off" and vaddr["k"] == "vgpr" and vaddr.get("n") == 2: - lo, hi = self.load_reg("vgpr", vaddr["r"]), self.load_reg("vgpr", vaddr["r"] + 1) - l64, h64, sh, va = (self.tmp() for _ in range(4)) - self.emit(f"{l64} = OpUConvert %ulong {lo}") - self.emit(f"{h64} = OpUConvert %ulong {hi}") - self.emit(f"{sh} = OpShiftLeftLogical %ulong {h64} %c64_32") - self.emit(f"{va} = OpBitwiseOr %ulong {sh} {l64}") - else: - raise Unsupported(op + " addressing") - self.uses_psb = True - off64, full = self.tmp(), self.tmp() - ioff = self.tmp() - self.emit(f"{ioff} = OpBitcast %uint {self.as_int(self.cu(inst & 0xFFFFFFFF))}") - self.emit(f"{off64} = OpSConvert %long {self.as_int(ioff)}") - o2 = self.tmp() - self.emit(f"{o2} = OpBitcast %ulong {off64}") - self.emit(f"{full} = OpIAdd %ulong {va} {o2}") - self.uses_long = True - return full - - GLOBAL_SUB = { # op: (bytes, store?, signed, VGPR half the data comes from / lands in, or None = whole register) - "global_store_byte": (1, True, False, None), "global_store_byte_d16_hi": (1, True, False, 1), - "global_store_short": (2, True, False, None), "global_store_short_d16_hi": (2, True, False, 1), - "global_load_ubyte_d16": (1, False, False, 0), "global_load_ubyte_d16_hi": (1, False, False, 1), - "global_load_sbyte_d16": (1, False, True, 0), "global_load_sbyte_d16_hi": (1, False, True, 1), - "global_load_short_d16": (2, False, False, 0), "global_load_short_d16_hi": (2, False, False, 1)} - - def global_byte_ptr(self, va): - """(pointer to the dword holding byte `va`, bit offset of that byte in it) for a ulong Xbox VA.""" - lo, b3, b64, al, arr, p, sh = (self.tmp() for _ in range(7)) - self.emit(f"{lo} = OpUConvert %uint {va}") - self.emit(f"{b3} = OpBitwiseAnd %uint {lo} {self.cu(3)}") - self.emit(f"{b64} = OpUConvert %ulong {b3}") - self.emit(f"{al} = OpISub %ulong {va} {b64}") - # MoltenVK 1.4.0 needs an addressable array element for the Metal atomic operations (as buffer stores). - self.emit(f"{arr} = OpConvertUToPtr %_ptr_PSB_arr {self.host_addr(al)}") - self.emit(f"{p} = OpAccessChain %_ptr_PSB_uint {arr} {self.cu(0)}") - self.emit(f"{sh} = OpShiftLeftLogical %uint {b3} {self.cu(3)}") - return p, sh - - def global_sub(self, op, a, mods): - """8- and 16-bit global stores (global_store_byte/short[_d16_hi]) and the d16 loads - (global_load_{u,s}byte_d16[_hi], global_load_short_d16[_hi]). The access is done one byte at a time, so a - 16-bit one that crosses a dword boundary is exact too: a store merges each byte into its dword with atomic and - / or (neighbouring bytes, maybe another lane's, are kept, as buffer stores do); a load reads each byte. A d16 - load writes one 16-bit half of vdst (the u/sbyte forms zero/sign-extend the byte to 16 bits) and keeps the - other; a _d16_hi store takes its data from the high half. Inactive lanes neither store nor load.""" - if any(m in mods for m in ("lds", "tfe", "slc", "dlc")): - raise Unsupported(op + " form") - nbytes, store, signed, half = self.GLOBAL_SUB[op] - data, vaddr, saddr = (a[1], a[0], a[2]) if store else (a[0], a[1], a[2]) - if data["k"] != "vgpr" or data.get("n", 1) != 1: - raise Unsupported(op + " data") - full = self.global_address(op, vaddr, saddr, mods) - act = self.active_b() - lbl_do, lbl_end = self.tmp() + "_do", self.tmp() + "_end" - old = self.load_reg("vgpr", data["r"]) - pre = self.current_label_placeholder() - self.emit(f"OpSelectionMerge {lbl_end} None") - self.emit(f"OpBranchConditional {act} {lbl_do} {lbl_end}") - self.emit(f"{lbl_do} = OpLabel") - value = None - for k in range(nbytes): - va = full - if k: - va = self.tmp() - self.emit(f"{va} = OpIAdd %ulong {full} {self.cl(k)}") - p, sh = self.global_byte_ptr(va) - if store: - byte, mk, inv, vs, t1, t2 = (self.tmp() for _ in range(6)) - self.emit(f"{byte} = OpBitFieldUExtract %uint {old} {self.cu(16 * (half or 0) + 8 * k)} {self.cu(8)}") - self.emit(f"{mk} = OpShiftLeftLogical %uint {self.cu(0xFF)} {sh}") - self.emit(f"{inv} = OpNot %uint {mk}") - self.emit(f"{vs} = OpShiftLeftLogical %uint {byte} {sh}") - self.emit(f"{t1} = OpAtomicAnd %uint {p} {self.cu(1)} {self.cu(0)} {inv}") - self.emit(f"{t2} = OpAtomicOr %uint {p} {self.cu(1)} {self.cu(0)} {vs}") - else: - w, b = self.tmp(), self.tmp() - self.emit(f"{w} = OpLoad %uint {p} Aligned 4") - self.emit(f"{b} = OpBitFieldUExtract %uint {w} {sh} {self.cu(8)}") - if value is None: - value = b - else: - hi8, v2 = self.tmp(), self.tmp() - self.emit(f"{hi8} = OpShiftLeftLogical %uint {b} {self.cu(8)}") - self.emit(f"{v2} = OpBitwiseOr %uint {value} {hi8}") - value = v2 - if not store: - if signed: - sx = self.tmp() - self.emit(f"{sx} = OpBitFieldSExtract %uint {value} {self.cu(0)} {self.cu(8 * nbytes)}") - value = sx - new = self.tmp() - self.emit(f"{new} = OpBitFieldInsert %uint {old} {value} {self.cu(16 * half)} {self.cu(16)}") - self.emit(f"OpBranch {lbl_end}") - self.emit(f"{lbl_end} = OpLabel") - if not store: - ph = self.tmp() - self.emit(f"{ph} = OpPhi %uint {new} {lbl_do} {old} {pre}") - self.store_reg("vgpr", data["r"], ph) - - def global_mem(self, op, a, mods): - """global_load_dword[xN] vD, vaddr, saddr|off offset:N / global_store_dword[xN] vaddr, vD, saddr|off. - Address = (saddr: 64-bit SGPR pair + zero-extended 32-bit vaddr | off: 64-bit VGPR pair) + offset, - an Xbox GPU VA translated through the heap base. Stores and loads only take effect in active lanes.""" - load = op.startswith("global_load") - if op.endswith("_addtid"): - # global_load/store_dword_addtid address by the lane id and M0, not vaddr; until 2026-11-22 it crashed - # here with IndexError (no vaddr operand) - raise Unsupported(op) - if any(m in mods for m in ("lds", "tfe", "d16")): - raise Unsupported(op + " form") - sub = {"global_load_ushort": (16, False), "global_load_sshort": (16, True), - "global_load_ubyte": (8, False), "global_load_sbyte": (8, True)}.get(op) - n = 1 if (op.endswith("dword") or sub) else int(op.rsplit("x", 1)[1]) - data, vaddr, saddr = (a[0], a[1], a[2]) if load else (a[1], a[0], a[2]) - full = self.global_address(op, vaddr, saddr, mods) - act = self.active_b() - lbl_do, lbl_end = self.tmp() + "_do", self.tmp() + "_end" - if load: - # Inactive lanes don't load (and keep their registers): guard the access, merge with OpPhi per dword. - olds = [self.load_reg("vgpr", data["r"] + i) for i in range(n)] - pre = self.current_label_placeholder() - self.emit(f"OpSelectionMerge {lbl_end} None") - self.emit(f"OpBranchConditional {act} {lbl_do} {lbl_end}") - self.emit(f"{lbl_do} = OpLabel") - vals = [] - if sub: - # 8/16-bit load: read the containing dword and extract (zero- or sign-extended); a 16-bit load at - # byte offset 3 within a dword merges byte 0 of the next dword without over-reading non-crossing ones. - bits, signed = sub - lo32, b3, b64, al, ptr, p0, w, shb, v = (self.tmp() for _ in range(9)) - self.emit(f"{lo32} = OpUConvert %uint {full}") - self.emit(f"{b3} = OpBitwiseAnd %uint {lo32} {self.cu(3)}") - self.emit(f"{b64} = OpUConvert %ulong {b3}") - self.emit(f"{al} = OpISub %ulong {full} {b64}") - self.emit(f"{ptr} = OpConvertUToPtr %_ptr_PSB_arr {self.host_addr(al)}") - self.emit(f"{p0} = OpAccessChain %_ptr_PSB_uint {ptr} {self.cu(0)}") - self.emit(f"{w} = OpLoad %uint {p0} Aligned 4") - self.emit(f"{shb} = OpShiftLeftLogical %uint {b3} {self.cu(3)}") - ext = "OpBitFieldSExtract" if signed else "OpBitFieldUExtract" - if bits == 8: - self.emit(f"{v} = {ext} %uint {w} {shb} {self.cu(8)}") - else: - lo_part, cross, p1, w1, hi_byte, hi_sh, crossed, raw = (self.tmp() for _ in range(8)) - lbl_cross, lbl_cend = self.tmp() + "_cross", self.tmp() + "_cend" - self.emit(f"{lo_part} = OpShiftRightLogical %uint {w} {shb}") - self.emit(f"{cross} = OpIEqual %bool {b3} {self.cu(3)}") - self.emit(f"OpSelectionMerge {lbl_cend} None") - self.emit(f"OpBranchConditional {cross} {lbl_cross} {lbl_cend}") - self.emit(f"{lbl_cross} = OpLabel") - self.emit(f"{p1} = OpAccessChain %_ptr_PSB_uint {ptr} {self.cu(1)}") - self.emit(f"{w1} = OpLoad %uint {p1} Aligned 4") - self.emit(f"{hi_byte} = OpBitFieldUExtract %uint {w1} {self.cu(0)} {self.cu(8)}") - self.emit(f"{hi_sh} = OpShiftLeftLogical %uint {hi_byte} {self.cu(8)}") - self.emit(f"{crossed} = OpBitwiseOr %uint {lo_part} {hi_sh}") - self.emit(f"OpBranch {lbl_cend}") - self.emit(f"{lbl_cend} = OpLabel") - self.emit(f"{raw} = OpPhi %uint {crossed} {lbl_cross} {lo_part} {lbl_do}") - self.emit(f"{v} = {ext} %uint {raw} {self.cu(0)} {self.cu(16)}") - vals.append(v) - else: - ptr = self.tmp() - self.emit(f"{ptr} = OpConvertUToPtr %_ptr_PSB_arr {self.host_addr(full)}") - for i in range(n): - p, v = self.tmp(), self.tmp() - self.emit(f"{p} = OpAccessChain %_ptr_PSB_uint {ptr} {self.cu(i)}") - self.emit(f"{v} = OpLoad %uint {p} Aligned 4") - vals.append(v) - done_lbl = self.current_label_placeholder() - self.emit(f"OpBranch {lbl_end}") - self.emit(f"{lbl_end} = OpLabel") - phis = [] - for i in range(n): # all OpPhi first: they must open the merge block - ph = self.tmp() - self.emit(f"{ph} = OpPhi %uint {vals[i]} {done_lbl} {olds[i]} {pre}") - phis.append(ph) - for i, ph in enumerate(phis): - self.store_reg("vgpr", data["r"] + i, ph) - else: - vals = [self.load_reg("vgpr", data["r"] + i) for i in range(n)] - self.emit(f"OpSelectionMerge {lbl_end} None") - self.emit(f"OpBranchConditional {act} {lbl_do} {lbl_end}") - self.emit(f"{lbl_do} = OpLabel") - ptr = self.tmp() - self.emit(f"{ptr} = OpConvertUToPtr %_ptr_PSB_arr {self.host_addr(full)}") - for i in range(n): - p = self.tmp() - self.emit(f"{p} = OpAccessChain %_ptr_PSB_uint {ptr} {self.cu(i)}") - self.emit(f"OpStore {p} {vals[i]} Aligned 4") - self.emit(f"OpBranch {lbl_end}") - self.emit(f"{lbl_end} = OpLabel") - - def buf_dword_ptr(self, arr, host, step, i, same_base=False): - """Pointer to dword i (a Python int or a uint id) of a buffer access whose first dword is at host address - `host`, `arr` the same address as a PSB array: arr[i] for the linear layout (step None), else host + i * step - in scratch-swizzle mode (SWIZZLE_ENABLE=1, idxen=0, ADD_TID_ENABLE=1), where dword k is 4 * index_stride - bytes after dword k - 1 (buffer_address). `same_base` indexes `arr` by i * index_stride instead of converting a - second address to a pointer: on MoltenVK (Apple M4) a load through a second pointer converted from the same - address as one through `arr` returned wrong values (#1864, @sovljanskii: buffer_load_ushort at byte 2 of a - dword read 0).""" - ix = self.cu(i) if isinstance(i, int) else i - p = self.tmp() - if step is None or i == 0: - self.emit(f"{p} = OpAccessChain %_ptr_PSB_uint {arr} {ix}") - return p - if same_base: # step = 4 * index_stride: dword i is element i * index_stride of arr - q, k = self.tmp(), self.tmp() - self.emit(f"{q} = OpShiftRightLogical %uint {step} {self.cu(2)}") - self.emit(f"{k} = OpIMul %uint {ix} {q}") - self.emit(f"{p} = OpAccessChain %_ptr_PSB_uint {arr} {k}") - return p - o, o64, h = self.tmp(), self.tmp(), self.tmp() - self.emit(f"{o} = OpIMul %uint {ix} {step}") - self.emit(f"{o64} = OpUConvert %ulong {o}") - self.emit(f"{h} = OpIAdd %ulong {host} {o64}") - self.emit(f"{p} = OpConvertUToPtr %_ptr_PSB_uint {h}") - return p - - def buffer_address(self, a, mods, parts=False, elem=None, fixed_fmt=None): - """(64-bit element address id, V# word3 id, in_bounds bool id, ..., step) for a MUBUF/MTBUF instruction: - vdata, vaddr, srsrc, soffset. With `idx` = idxen ? vindex : (ADD_TID_ENABLE ? lane : 0) (idxen ignores - ADD_TID_ENABLE), `off` = uint32((offen ? vaddr : 0) + inst_offset) (32-bit wrap), `offs` = uint64(off) + - uint64(soffset) (64-bit, no wrap), out of range on RDNA2 as measured natively on gfx1036 - (docs/buffer_bounds.md, docs/design.md): - 0 STRUCTURED_WITH_OFFSET: idx >= num_records or off + 4k + 4 > stride - 1 STRUCTURED: idx >= num_records - 2 DISABLED: num_records == 0 - 3 RAW (linear or stride 0): offs + 4k + 4 > num_records - 3 SWIZZLED (swz_active and stride != 0): uint64(idx) + uint64(soffset) >= num_records or off + 4k + 4 > stride - SWIZZLE_ENABLE (word1[31]) activates only when idxen or ADD_TID_ENABLE is active (`swz_active`); with neither, - addressing is linear and mode 3 stays RAW. Two swizzle sub-modes exist on RDNA2 (measured natively on gfx1036, - wave32 & wave64): - - Scratch swizzle (`SWIZZLE_ENABLE=1, idxen=0, ADD_TID_ENABLE=1`): raw multi-dword accesses step by - `4 * index_stride` bytes (`step`), and typed formats > 4 bytes (plus 8-byte `buffer_atomic_*_x2`) are - suppressed (even in mode 2). - - Indexed swizzle (`SWIZZLE_ENABLE=1, idxen=1`): multi-dword raw, typed, and `_x2` atomic accesses step - linearly by `+4` bytes (`step = None`), and typed formats > 4 bytes execute normally. - A literal V# word1/word3 (`sgpr_imm`) folds each bit; a run-time one selects dynamically. elem="fmt" checks the - whole element's format size; parts=True adds a 4th element `k -> in-range bool id` for per-dword checks.""" - vaddr, rsrc = a[1], a[2] - soff = a[3] if len(a) > 3 else {"k": "imm", "v": 0} - if (rsrc["k"] == "sgpr" and rsrc.get("n") == 4): - lit3, lit1 = self.sgpr_imm.get(rsrc["r"] + 3), self.sgpr_imm.get(rsrc["r"] + 1) - elif rsrc["k"] == "slist" and len(rsrc["r"]) == 4: - lit3 = self.sgpr_imm.get(rsrc["r"][3]) if isinstance(rsrc["r"][3], int) else None - lit1 = self.sgpr_imm.get(rsrc["r"][1]) if isinstance(rsrc["r"][1], int) else None - else: - raise Unsupported("buffer V#") - d0, d1, d2, d3 = self.sgpr_words(rsrc, 4) - hi, stride = self.tmp(), self.tmp() - self.emit(f"{hi} = OpBitwiseAnd %uint {d1} {self.cu(0xFFFF)}") - self.emit(f"{stride} = OpBitFieldUExtract %uint {d1} {self.cu(16)} {self.cu(14)}") - # Swizzled buffers (docs/design.md, Swizzled buffer addressing; native gfx1036 measurement): SWIZZLE_ENABLE is - # word1[31], INDEX_STRIDE word3[22:21] (IS = 8 << n), ADD_TID_ENABLE word3[23], element_size fixed at 4. - # A literal word folds its bit (a Python bool); a run-time one is None. - swz = bool(lit1 >> 31) if lit1 is not None else None - tid = bool(lit3 >> 23 & 1) if lit3 is not None else None - has_idx = "idxen" in mods - inst = next((int(m.split(":")[1], 0) for m in mods if m.startswith("offset:")), 0) - soff_zero = soff["k"] == "imm" and soff["v"] == 0 - soff_v = self.src_u(soff) - vregs = [] if vaddr["k"] == "special" else [vaddr["r"] + i for i in range(vaddr.get("n", 1))] - voff = None - if "offen" in mods: - voff = self.load_reg("vgpr", vregs[1] if has_idx else vregs[0]) - # Effective index: idxen uses vindex alone and ignores ADD_TID_ENABLE; without idxen, ADD_TID_ENABLE supplies - # the wave lane (thread_id[5:0]). - tid_b = None - if has_idx: - idx = self.load_reg("vgpr", vregs[0]) - elif tid is False: - idx = None - else: - lane = self.wave_lane() - if tid is None: # lane * run-time ADD_TID_ENABLE - tid_b, idx = self.tmp(), self.tmp() - self.emit(f"{tid_b} = OpBitFieldUExtract %uint {d3} {self.cu(23)} {self.cu(1)}") - self.emit(f"{idx} = OpIMul %uint {lane} {tid_b}") - else: - idx = lane - # SWIZZLE_ENABLE activates only with idxen or ADD_TID_ENABLE; scratch-swizzle stepping/suppression applies only - # when SWIZZLE_ENABLE=1, idxen=0, ADD_TID_ENABLE=1. - swz_u = None - if has_idx: - swz_active = swz - scratch_swz = False - if swz_active is None: - swz_u = self.tmp() - self.emit(f"{swz_u} = OpBitFieldUExtract %uint {d1} {self.cu(31)} {self.cu(1)}") - elif swz is False or tid is False: - swz_active = False - scratch_swz = False - elif swz is True and tid is True: - swz_active = True - scratch_swz = True - else: - swz_active = None - scratch_swz = None - if swz is True: - swz_u = tid_b - else: - swz_b = self.tmp() - self.emit(f"{swz_b} = OpBitFieldUExtract %uint {d1} {self.cu(31)} {self.cu(1)}") - if tid is True: - swz_u = swz_b - else: - swz_u = self.tmp() - self.emit(f"{swz_u} = OpBitwiseAnd %uint {swz_b} {tid_b}") - # off = uint32((offen ? voff : 0) + inst_offset): wraps at 32 bits on RDNA2. - if voff is not None: - if inst: - off = self.tmp() - self.emit(f"{off} = OpIAdd %uint {voff} {self.cu(inst)}") - else: - off = voff - else: - off = self.cu(inst) - # step: bytes between consecutive dwords of a raw access, None for linear +4 (including all idxen=1 and fmt). - step = None - if swz_active is False: - if soff_zero: - total = off - else: - total = self.tmp() - self.emit(f"{total} = OpIAdd %uint {soff_v} {off}") - if idx is not None: - m, t = self.tmp(), self.tmp() - self.emit(f"{m} = OpIMul %uint {idx} {stride}") - self.emit(f"{t} = OpIAdd %uint {total} {m}") - total = t - sw3 = False - else: - # buffer_offset = (index / IS * stride + (off & ~3)) * IS + (index % IS) * 4 + (off & 3), IS = 2^L; - # L = 0 (run-time V# with swz_u == 0) reduces to the linear address index * stride + off. - if lit3 is not None: - Li = 3 + (lit3 >> 21 & 3) - L = self.cu(Li) - else: - f, L, Li = self.tmp(), self.tmp(), None - self.emit(f"{f} = OpBitFieldUExtract %uint {d3} {self.cu(21)} {self.cu(2)}") - self.emit(f"{L} = OpIAdd %uint {f} {self.cu(3)}") - if swz_active is None: # L * swz_u: 0 when not swizzled - t = self.tmp() - self.emit(f"{t} = OpIMul %uint {L} {swz_u}") - L, Li = t, None - om4, ol, sh = self.tmp(), self.tmp(), self.tmp() - self.emit(f"{om4} = OpBitwiseAnd %uint {off} {self.cu(0xFFFFFFFC)}") - self.emit(f"{ol} = OpBitwiseAnd %uint {off} {self.cu(3)}") - msb, ms, inner, lsb, l4, im = (self.tmp() for _ in range(6)) - self.emit(f"{msb} = OpShiftRightLogical %uint {idx} {L}") - self.emit(f"{ms} = OpIMul %uint {msb} {stride}") - self.emit(f"{inner} = OpIAdd %uint {ms} {om4}") - self.emit(f"{sh} = OpShiftLeftLogical %uint {inner} {L}") - if Li is not None: - self.emit(f"{lsb} = OpBitwiseAnd %uint {idx} {self.cu((1 << Li) - 1)}") - else: # index - (index >> L << L) - hi_part = self.tmp() - self.emit(f"{hi_part} = OpShiftLeftLogical %uint {msb} {L}") - self.emit(f"{lsb} = OpISub %uint {idx} {hi_part}") - self.emit(f"{l4} = OpShiftLeftLogical %uint {lsb} {self.cu(2)}") - self.emit(f"{im} = OpIAdd %uint {sh} {l4}") - b_off = self.tmp() - self.emit(f"{b_off} = OpIAdd %uint {im} {ol}") - if soff_zero: - total = b_off - else: - total = self.tmp() - self.emit(f"{total} = OpIAdd %uint {soff_v} {b_off}") - if elem != "fmt" and scratch_swz is not False: - if Li is not None: - step = self.cu(4 << Li) - else: - step = self.tmp() - self.emit(f"{step} = OpShiftLeftLogical %uint {self.cu(4)} {L}") - # OOB_SELECT 3 with active swizzle and stride != 0 checks (idx + soffset) >= num_records or off + payload > stride. - if lit1 is not None and (lit1 >> 16 & 0x3FFF) == 0: - sw3 = False - elif swz_active is True: - if lit1 is not None: - sw3 = True - else: - sw3 = self.tmp() - self.emit(f"{sw3} = OpINotEqual %bool {stride} {self.cu(0)}") - else: # L * stride != 0: swz_u == 1 (L >= 3) and stride != 0 (no overflow) - ls, sw3 = self.tmp(), self.tmp() - self.emit(f"{ls} = OpIMul %uint {L} {stride}") - self.emit(f"{sw3} = OpINotEqual %bool {ls} {self.cu(0)}") - self.uses_psb = True - l64, h64, sh, base, o64, addr = (self.tmp() for _ in range(6)) - self.emit(f"{l64} = OpUConvert %ulong {d0}") - self.emit(f"{h64} = OpUConvert %ulong {hi}") - self.emit(f"{sh} = OpShiftLeftLogical %ulong {h64} %c64_32") - self.emit(f"{base} = OpBitwiseOr %ulong {sh} {l64}") - self.emit(f"{o64} = OpUConvert %ulong {total}") - self.emit(f"{addr} = OpIAdd %ulong {base} {o64}") - mode = None if lit3 is None else lit3 >> 28 & 3 - mode0_rule = mode in (None, 0) or (mode == 3 and sw3 is not False) - need_raw = mode in (None, 3) and sw3 is not True - need_p3 = mode in (None, 3) and sw3 is not False - need_p1 = mode in (None, 0, 1) or (need_p3 and soff_zero) - p1 = p2 = p3_idx = None - if need_p1: - p1 = self.tmp() - if idx is None: - self.emit(f"{p1} = OpINotEqual %bool {d2} {self.cu(0)}") - else: - self.emit(f"{p1} = OpULessThan %bool {idx} {d2}") - if mode in (None, 2): - p2 = self.tmp() - self.emit(f"{p2} = OpINotEqual %bool {d2} {self.cu(0)}") - off64 = d2_64 = soff64 = None - if mode0_rule or need_raw: - off64 = self.tmp() - self.emit(f"{off64} = OpUConvert %ulong {off}") - if need_raw or (need_p3 and not soff_zero and idx is not None): - d2_64 = self.tmp() - self.emit(f"{d2_64} = OpUConvert %ulong {d2}") - if not soff_zero and (need_raw or (need_p3 and idx is not None)): - soff64 = self.tmp() - self.emit(f"{soff64} = OpUConvert %ulong {soff_v}") - if need_p3: - if soff_zero: - p3_idx = p1 - elif idx is None: - p3_idx = self.tmp() - self.emit(f"{p3_idx} = OpULessThan %bool {soff_v} {d2}") - else: - idx64, idx_s, p3_idx = self.tmp(), self.tmp(), self.tmp() - self.emit(f"{idx64} = OpUConvert %ulong {idx}") - self.emit(f"{idx_s} = OpIAdd %ulong {idx64} {soff64}") - self.emit(f"{p3_idx} = OpULessThan %bool {idx_s} {d2_64}") - lim = {} - if mode0_rule: - st64 = self.tmp() - self.emit(f"{st64} = OpUConvert %ulong {stride}") - lim[0] = (off64, st64) - if need_raw: - if soff_zero: - offs64 = off64 - else: - offs64 = self.tmp() - self.emit(f"{offs64} = OpIAdd %ulong {off64} {soff64}") - lim[3] = (offs64, d2_64) - sel = None - if mode is None: - md, m1, m2, m3 = (self.tmp() for _ in range(4)) - self.emit(f"{md} = OpBitFieldUExtract %uint {d3} {self.cu(28)} {self.cu(2)}") - self.emit(f"{m1} = OpIEqual %bool {md} {self.cu(1)}") - self.emit(f"{m2} = OpIEqual %bool {md} {self.cu(2)}") - self.emit(f"{m3} = OpIEqual %bool {md} {self.cu(3)}") - sel = (m1, m2, m3) - - ends = {} # (offset id, end) -> the ulong sum: modes 0 and 3 share it when soffset is 0 - - def end_ok(which, end_bytes): - """The access ends inside its limit: offset + end <= stride (mode 0) or <= num_records (mode 3); - end_bytes is a Python int or the id of a ulong.""" - x, limit = lim[which] - end = ends.get((x, end_bytes)) - if end is None: - end = ends[(x, end_bytes)] = self.tmp() - self.emit(f"{end} = OpIAdd %ulong {x} {self.cl(end_bytes) if isinstance(end_bytes, int) else end_bytes}") - ok = self.tmp() - self.emit(f"{ok} = OpULessThanEqual %bool {end} {limit}") - return ok - - def raw_or_swizzled(e3_sw, end_bytes): - """mode 3: the raw end check, or the swizzled-with-stride check (sw3).""" - if sw3 is True: - return e3_sw - raw = end_ok(3, end_bytes) - if sw3 is False: - return raw - r = self.tmp() - self.emit(f"{r} = OpSelect %bool {sw3} {e3_sw} {raw}") - return r - - def check_end(end_bytes): - """in-range bool of an access that ends end_bytes after its first byte.""" - if mode == 1: - return p1 - if mode == 2: - return p2 - if mode == 3 and sw3 is False: - return end_ok(3, end_bytes) - off_ok = end_ok(0, end_bytes) - if mode == 0: - e0 = self.tmp() - self.emit(f"{e0} = OpLogicalAnd %bool {p1} {off_ok}") - return e0 - if mode == 3: - e3_sw = self.tmp() - self.emit(f"{e3_sw} = OpLogicalAnd %bool {p3_idx} {off_ok}") - return raw_or_swizzled(e3_sw, end_bytes) - e0 = self.tmp() - self.emit(f"{e0} = OpLogicalAnd %bool {p1} {off_ok}") - if sw3 is False: - e3 = end_ok(3, end_bytes) - else: - if p3_idx == p1: - e3_sw = e0 - else: - e3_sw = self.tmp() - self.emit(f"{e3_sw} = OpLogicalAnd %bool {p3_idx} {off_ok}") - e3 = raw_or_swizzled(e3_sw, end_bytes) - s12, s3, r = self.tmp(), self.tmp(), self.tmp() - self.emit(f"{s12} = OpSelect %bool {sel[0]} {p1} {e0}") - self.emit(f"{s3} = OpSelect %bool {sel[1]} {p2} {s12}") - self.emit(f"{r} = OpSelect %bool {sel[2]} {e3} {s3}") - return r - - def check(k): - """in-range bool of dword k of the access (k = 0: the first dword).""" - return check_end(4 * k + 4) - - if isinstance(elem, int): - in_b = check_end(elem) - return addr, d3, in_b, step - if elem == "fmt": - # a typed element is all or nothing and ends at its size (measured, gfx1150: 32_32_32_32 at off 20 of 32 - # reads 0 entirely): the size of the V#'s (or the instruction's) format - code = fixed_fmt if fixed_fmt is not None else (lit3 >> 12 & 0x7F if lit3 is not None else None) - if code is not None: - size = self.FORMATS.get(code, (4,))[0] - else: - fc = self.tmp() - self.emit(f"{fc} = OpBitFieldUExtract %uint {d3} {self.cu(12)} {self.cu(7)}") - tab, unknown, sz = self.fmt_size_of(fc), self.tmp(), self.tmp() # 4 for a code FORMATS lacks - self.emit(f"{unknown} = OpIEqual %bool {tab} {self.cu(0)}") - self.emit(f"{sz} = OpSelect %uint {unknown} {self.cu(4)} {tab}") - size = self.tmp() - self.emit(f"{size} = OpUConvert %ulong {sz}") - in_b = check_end(size) - if scratch_swz is not False: - # Native gfx1036 measurement (wave32 & wave64): in scratch-swizzle mode (SWIZZLE_ENABLE=1, idxen=0, - # ADD_TID_ENABLE=1), typed formats > 4 bytes and 8-byte buffer_atomic_*_x2 are suppressed even in - # OOB_SELECT 2 (DISABLED). - if isinstance(size, int): - if size > 4: - if scratch_swz is True: - in_b = "%false" - else: - ns, ok = self.tmp(), self.tmp() - self.emit(f"{ns} = OpIEqual %bool {swz_u} {self.cu(0)}") - self.emit(f"{ok} = OpLogicalAnd %bool {in_b} {ns}") - in_b = ok - else: - le4 = self.tmp() - self.emit(f"{le4} = OpULessThanEqual %bool {size} {self.cl(4)}") - if scratch_swz is True: - ok = self.tmp() - self.emit(f"{ok} = OpLogicalAnd %bool {in_b} {le4}") - in_b = ok - else: - ns, allow, ok = self.tmp(), self.tmp(), self.tmp() - self.emit(f"{ns} = OpIEqual %bool {swz_u} {self.cu(0)}") - self.emit(f"{allow} = OpLogicalOr %bool {ns} {le4}") - self.emit(f"{ok} = OpLogicalAnd %bool {in_b} {allow}") - in_b = ok - return addr, d3, in_b, None - in_b = check(0) - if parts: - # modes 0 and 3 end-check every dword on its own; 1 and 2 (a literal V#) share the first-byte check. - # Dword 0's check is in_b itself: computed here, before any of the caller's branches, so it dominates - # every use (the loads and stores used to compute it a second time). - def part(k): - return in_b if k == 0 else check(k) - return addr, d3, in_b, (part if mode in (None, 0, 3) else None), step - return addr, d3, in_b, step - - def format_encode_call(self, fmt, fc, normalized, unorm_view, ic, signed_ic, two): - """The 4 words of the element a typed store writes, per the run-time FORMAT, and its size in bytes (0 for a code - outside FORMATS: nothing is stored). One function per module like the decode (format_decode_call): inlined, every - store site carried every format's encode, three times the module of the older table (cs_store 169 KB -> 503 KB). - The five lists are 4 uint ids each: the raw float bits, the same with NaN -> 0 (NORM stores), the B/R-swapped - view for 50 and 56, the integers and the sign-extended d16 integers; a component the instruction does not give is 0.""" - if self.fmt_enc_fn is None: - names = ["%fe_fmt"] + [f"%fe_{g}{i}" for g in "fnvis" for i in range(4)] + [f"%fe_t{i}" for i in range(8)] - saved, self.body = self.body, [] - params = names[1:21] - tw = names[21:29] # the channels a two-component V# store takes: norm, float, int, signed int (2 each) - lists = [params[4 * g:4 * g + 4] for g in range(5)] - for code, (size, kind, widths) in self.FORMATS.items(): - e = self.tmp() - self.emit(f"{e} = OpIEqual %bool {names[0]} {self.cu(code)}") - ld, le = self.tmp() + "_s", self.tmp() + "_se" - self.emit(f"OpSelectionMerge {le} None") - self.emit(f"OpBranchConditional {e} {ld} {le}") - self.emit(f"{ld} = OpLabel") - source = lists[1] if kind in ("unorm", "snorm", "uscaled", "sscaled") else lists[0] - if code in (50, 56): - source = lists[2] - integer_source = lists[4] if kind in ("i32", "sint") else lists[3] - if len(widths) == 2: - # through a V# a two-component format takes the channels DST_SEL picks (x, y; x, w; y, x; ...), swizzled - # at the store site like gfx1036 does it; tbuffer stores are encoded in line, with (x, y) - source = tw[0:2] if kind in ("unorm", "snorm", "uscaled", "sscaled") else tw[2:4] - integer_source = tw[6:8] if kind in ("i32", "sint") else tw[4:6] - words = self.encode_format(source[:len(widths)] + [self.cu(0)] * 4, - integer_source[:len(widths)] + [self.cu(0)] * 4, code) - words = (words + [self.cu(0)] * 4)[:4] - res = self.tmp() - self.emit(f"{res} = OpCompositeConstruct %v4uint_fmt " + " ".join(words)) - self.emit(f"OpReturnValue {res}") - self.emit(f"{le} = OpLabel") - zero = self.tmp() - self.emit(f"{zero} = OpCompositeConstruct %v4uint_fmt " + " ".join([self.cu(0)] * 4)) - self.emit(f"OpReturnValue {zero}") - lines, self.body = self.body, saved - size_lines = [] - outer, self.body = self.body, [] - sz = self.cu(0) - for code, (size, _, _) in self.FORMATS.items(): - e, n2 = self.tmp(), self.tmp() - self.emit(f"{e} = OpIEqual %bool %fs_fmt {self.cu(code)}") - self.emit(f"{n2} = OpSelect %uint {e} {self.cu(size)} {sz}") - sz = n2 - size_lines, self.body = self.body, outer - self.fmt_enc_fn = (["%fmt_encode_fn = OpFunction %v4uint_fmt None %fn_fmt_encode"] + - [f"{q} = OpFunctionParameter %uint" for q in names] + ["%fe_entry = OpLabel"] + lines + - ["OpFunctionEnd", "%fmt_size_fn = OpFunction %uint Pure %fn_tbuffer_norm", - "%fs_fmt = OpFunctionParameter %uint", "%fs_entry = OpLabel"] + size_lines + - [f"OpReturnValue {sz}", "OpFunctionEnd"]) - r, size = self.tmp(), self.tmp() - args = [fmt] + fc + normalized + unorm_view + ic + signed_ic + two - self.emit(f"{r} = OpFunctionCall %v4uint_fmt %fmt_encode_fn " + " ".join(args)) - self.emit(f"{size} = OpFunctionCall %uint %fmt_size_fn {fmt}") - words = [] - for c in range(4): - x = self.tmp() - self.emit(f"{x} = OpCompositeExtract %uint {r} {c}") - words.append(x) - return words, size - - def mtbuf_format(self, op, mods): - """The format code an MTBUF instruction (tbuffer_load/store_format_*) encodes for itself, which replaces the - V#'s. LLVM omits the modifier for GFX10's default, BUF_FMT_8_UNORM (code 1).""" - fm = next((m for m in mods if m.startswith("format:")), "format:[BUF_FMT_8_UNORM]") - name = "GFX10_FORMAT_" + fm.split("BUF_FMT_")[-1].rstrip("]") - code = next((c for c, n in GFX10_FORMATS.items() if n == name), None) - if code is None or code not in self.FORMATS: - raise Unsupported(op + " " + name) - self.fixed_format_codes.add(code) - return code - - def buffer_store(self, op, a, mods, fixed_fmt=None): - """buffer_store_dword[xN] (raw) and buffer_store_format_* (every format in FORMATS, read from the V# at run - time). tbuffer_store_format_* comes here with its own format in fixed_fmt: only that one is encoded, and the - bounds check uses its element size, whatever the V# says. Only active lanes store, inside a structured if.""" - if any(m in mods for m in ("lds", "tfe", "d16")): - raise Unsupported(op + " form") - d16 = "_d16_" in op - vd = a[0] - dword_store = op.startswith("buffer_store_dword") - if dword_store: - addr, d3, in_b, per, step = self.buffer_address(a, mods, parts=True) - else: - addr, d3, in_b, step = self.buffer_address(a, mods, elem="fmt", fixed_fmt=fixed_fmt) - per = None - if dword_store: - n = 1 if op.endswith("dword") else int(op.rsplit("x", 1)[1]) - words = [self.load_reg("vgpr", vd["r"] + i) for i in range(n)] - plans = None - else: - n = len(op.rsplit("_", 1)[1]) - if d16: - # two 16-bit values per register: f16 for float kinds, 16-bit integers for integer kinds - regs = [self.load_reg("vgpr", vd["r"] + i) for i in range((n + 1) // 2)] - comps, icomps = [], [] - for i in range(n): - r = regs[i // 2] - iv = self.u16_half(r, i % 2) - v2, f = self.tmp(), self.tmp() - self.emit(f"{v2} = OpExtInst %v2float %glsl UnpackHalf2x16 {iv}") - self.emit(f"{f} = OpCompositeExtract %float {v2} 0") - comps.append(self.tou(f)) - icomps.append(iv) - else: - comps = [self.load_reg("vgpr", vd["r"] + i) for i in range(n)] - icomps = comps - if fixed_fmt is not None: - fmt = None # tbuffer: the instruction's format, so no V# FORMAT to branch on - else: - fmt = self.tmp() - self.emit(f"{fmt} = OpBitFieldUExtract %uint {d3} {self.cu(12)} {self.cu(7)}") - # Encodings for the formats that appear in store-heavy shaders; others store nothing. - f32 = {22: 1, 64: 2, 74: 3, 77: 4} - # Float views of the components, computed before any branch so every branch can use them. - fl = [self.tof(c) for c in comps] + ["%f0"] * (4 - len(comps)) - plans = (fmt, comps, f32, fl, icomps) - words = None - if words is not None and per is not None and len(words) > 1: - # modes 0 and 3: every dword is stored only if it ends inside (measured: a store that straddles the edge - # writes the dwords before it); a store past the end of the buffer is a host-memory hazard otherwise - ptr, host = self.tmp(), self.host_addr(addr) - self.emit(f"{ptr} = OpConvertUToPtr %_ptr_PSB_arr {host}") - for i, w in enumerate(words): - cond, lbl_do, lbl_end = self.tmp(), self.tmp() + "_do", self.tmp() + "_end" - self.emit(f"{cond} = OpLogicalAnd %bool {self.active_b()} {per(i)}") - self.emit(f"OpSelectionMerge {lbl_end} None") - self.emit(f"OpBranchConditional {cond} {lbl_do} {lbl_end}") - self.emit(f"{lbl_do} = OpLabel") - p = self.buf_dword_ptr(ptr, host, step, i) - self.emit(f"OpStore {p} {w} Aligned 4") - self.emit(f"OpBranch {lbl_end}") - self.emit(f"{lbl_end} = OpLabel") - return - if fixed_fmt is not None: - # A V# whose FORMAT is 0 (INVALID) disables the store, though MTBUF brings its own format (measured natively - # on gfx1035, wave32 and wave64, in OOB_SELECT 0, 1 and 3). - vf, valid, ok = self.tmp(), self.tmp(), self.tmp() - self.emit(f"{vf} = OpBitFieldUExtract %uint {d3} {self.cu(12)} {self.cu(7)}") - self.emit(f"{valid} = OpINotEqual %bool {vf} {self.cu(0)}") - self.emit(f"{ok} = OpLogicalAnd %bool {in_b} {valid}") - in_b = ok - act = self.tmp() - self.emit(f"{act} = OpLogicalAnd %bool {self.active_b()} {in_b}") - lbl_do, lbl_end = self.tmp() + "_do", self.tmp() + "_end" - self.emit(f"OpSelectionMerge {lbl_end} None") - self.emit(f"OpBranchConditional {act} {lbl_do} {lbl_end}") - self.emit(f"{lbl_do} = OpLabel") - ptr, host = self.tmp(), self.host_addr(addr) - self.emit(f"{ptr} = OpConvertUToPtr %_ptr_PSB_arr {host}") - if words is not None: - for i, w in enumerate(words): - p = self.buf_dword_ptr(ptr, host, step, i) - self.emit(f"OpStore {p} {w} Aligned 4") - else: - fmt, comps, f32, fl, icomps = plans - # Every format in FORMATS (the same table the loads decode); unknown formats store nothing. - fc = comps + [self.cu(0)] * (4 - len(comps)) - ic = icomps + [self.cu(0)] * (4 - len(icomps)) - # Normalized stores map either sign of NaN to zero before clamping. - # Compute this once per source component; float and integer formats use the original bits. - normalized = [] - for component, float_value in zip(comps, fl): - nan, value = self.tmp(), self.tmp() - self.emit(f"{nan} = OpIsNan %bool {float_value}") - self.emit(f"{value} = OpSelect %uint {nan} {self.cu(0)} {component}") - normalized.append(value) - # The runtime names B8G8R8A8 and A2R10G10B10 UNORM with V# selectors Z,Y,X,W. - # Pad the input first: even store_format_x must put its red value in the third field. - unorm_rgba = normalized + [self.cu(0)] * (4 - n) - selectors, bgra, red, blue = (self.tmp() for _ in range(4)) - self.emit(f"{selectors} = OpBitwiseAnd %uint {d3} {self.cu(0xfff)}") - self.emit(f"{bgra} = OpIEqual %bool {selectors} {self.cu(0xf2e)}") - self.emit(f"{red} = OpSelect %uint {bgra} {unorm_rgba[2]} {unorm_rgba[0]}") - self.emit(f"{blue} = OpSelect %uint {bgra} {unorm_rgba[0]} {unorm_rgba[2]}") - unorm_view = [red, unorm_rgba[1], blue, unorm_rgba[3]] - signed_ic = ic - if d16: - signed_ic = [self.int_bits(self.i16_half(regs[i // 2], i % 2)) for i in range(n)] - signed_ic = signed_ic + [self.cu(0)] * (4 - len(signed_ic)) - # MUBUF 2-component stores infer COMP_SWAP from V# DST_SEL_X/Y/Z (measured natively on gfx1036 across - # all 1,296 valid DST_SEL tuples, wave32 and wave64): XY01 -> (x, y), YX01 -> (y, x), XYZW -> (x, w), - # YXZW/ZYXW -> (w, x). MTBUF (fixed_fmt is not None) ignores DST_SEL and always stores (x, y). - if fixed_fmt is None: - sx, sy, sz = self.tmp(), self.tmp(), self.tmp() - self.emit(f"{sx} = OpBitFieldUExtract %uint {d3} {self.cu(0)} {self.cu(3)}") - self.emit(f"{sy} = OpBitFieldUExtract %uint {d3} {self.cu(3)} {self.cu(3)}") - self.emit(f"{sz} = OpBitFieldUExtract %uint {d3} {self.cu(6)} {self.cu(3)}") - sy_reg, sz_reg, sz_const, use_y = (self.tmp() for _ in range(4)) - self.emit(f"{sy_reg} = OpUGreaterThanEqual %bool {sy} {self.cu(4)}") - self.emit(f"{sz_reg} = OpUGreaterThanEqual %bool {sz} {self.cu(4)}") - self.emit(f"{sz_const} = OpLogicalNot %bool {sz_reg}") - self.emit(f"{use_y} = OpLogicalAnd %bool {sy_reg} {sz_const}") - sx_ne4, yz_reg, rev2 = self.tmp(), self.tmp(), self.tmp() - self.emit(f"{sx_ne4} = OpINotEqual %bool {sx} {self.cu(4)}") - self.emit(f"{yz_reg} = OpLogicalOr %bool {sy_reg} {sz_reg}") - self.emit(f"{rev2} = OpLogicalAnd %bool {sx_ne4} {yz_reg}") - - def swiz2(arr): - sec, c0, c1 = self.tmp(), self.tmp(), self.tmp() - self.emit(f"{sec} = OpSelect %uint {use_y} {arr[1]} {arr[3]}") - self.emit(f"{c0} = OpSelect %uint {rev2} {sec} {arr[0]}") - self.emit(f"{c1} = OpSelect %uint {rev2} {arr[0]} {sec}") - return [c0, c1] - - norm2 = swiz2(unorm_rgba) - fc2 = swiz2(fc) - ic2 = swiz2(ic) - signed_ic2 = swiz2(signed_ic) if d16 else ic2 - if fmt is None: # tbuffer_store: its own format, encoded in line - code = fixed_fmt - size, kind, widths = self.FORMATS[code] - if True: - ncomp = min(len(widths), n) - source = normalized if kind in ("unorm", "snorm", "uscaled", "sscaled") else fc - fcs = source[:ncomp] + [self.cu(0)] * (len(widths) - ncomp) - if code in (50, 56): - fcs = unorm_view - integer_source = signed_ic if kind in ("i32", "sint") else ic - ics = integer_source[:ncomp] + [self.cu(0)] * (len(widths) - ncomp) - words = self.encode_format(fcs + [self.cu(0)] * 4, ics + [self.cu(0)] * 4, code) - if size >= 4: - for k, w in enumerate(words[:size // 4]): - pp = self.buf_dword_ptr(ptr, host, step, k) - self.emit(f"OpStore {pp} {w} Aligned 4") - else: - # 1- or 2-byte element: merge into its dword with atomics so neighbours are kept. - al, sh, sh8, ap, mk, mks, inv, val, vs, t1, t2 = (self.tmp() for _ in range(11)) - self.emit(f"{sh} = OpUConvert %uint {addr}") - lo3, lo64 = self.tmp(), self.tmp() - self.emit(f"{lo3} = OpBitwiseAnd %uint {sh} {self.cu(3)}") - self.emit(f"{lo64} = OpUConvert %ulong {lo3}") - self.emit(f"{al} = OpISub %ulong {addr} {lo64}") - self.emit(f"{sh8} = OpShiftLeftLogical %uint {sh} {self.cu(3)}") - sh24 = self.tmp() - self.emit(f"{sh24} = OpBitwiseAnd %uint {sh8} {self.cu(24)}") - # MoltenVK 1.4.0 needs an addressable array element for the Metal atomic operations. - dword_arr = self.tmp() - self.emit(f"{dword_arr} = OpConvertUToPtr %_ptr_PSB_arr {self.host_addr(al)}") - self.emit(f"{ap} = OpAccessChain %_ptr_PSB_uint {dword_arr} {self.cu(0)}") - self.emit(f"{mk} = OpCopyObject %uint {self.cu((1 << (8 * size)) - 1)}") - self.emit(f"{mks} = OpShiftLeftLogical %uint {mk} {sh24}") - self.emit(f"{inv} = OpNot %uint {mks}") - self.emit(f"{val} = OpBitwiseAnd %uint {words[0]} {mk}") - self.emit(f"{vs} = OpShiftLeftLogical %uint {val} {sh24}") - self.emit(f"{t1} = OpAtomicAnd %uint {ap} {self.cu(1)} {self.cu(0)} {inv}") - self.emit(f"{t2} = OpAtomicOr %uint {ap} {self.cu(1)} {self.cu(0)} {vs}") - else: - pad = lambda xs: (list(xs) + [self.cu(0)] * 4)[:4] # noqa: E731 - two = norm2 + fc2 + ic2 + signed_ic2 if fixed_fmt is None else [self.cu(0)] * 8 - words, size = self.format_encode_call(fmt, pad(fc), pad(normalized), pad(unorm_view), pad(ic), pad(signed_ic), two) - # whole dwords: dword k is stored when the element has more than 4k bytes - for k in range(4): - big, lk, le = self.tmp(), self.tmp() + "_s", self.tmp() + "_se" - self.emit(f"{big} = OpUGreaterThanEqual %bool {size} {self.cu(4 * (k + 1))}") - self.emit(f"OpSelectionMerge {le} None") - self.emit(f"OpBranchConditional {big} {lk} {le}") - self.emit(f"{lk} = OpLabel") - pp = self.buf_dword_ptr(ptr, host, step, k) - self.emit(f"OpStore {pp} {words[k]} Aligned 4") - self.emit(f"OpBranch {le}") - self.emit(f"{le} = OpLabel") - # 1- or 2-byte element: merge into its dword with atomics so neighbours are kept. - small, ld, le = self.tmp(), self.tmp() + "_s", self.tmp() + "_se" - sm1 = self.tmp() - self.emit(f"{sm1} = OpISub %uint {size} {self.cu(1)}") - self.emit(f"{small} = OpULessThan %bool {sm1} {self.cu(2)}") # size 1 or 2 (0 wraps to a large value) - self.emit(f"OpSelectionMerge {le} None") - self.emit(f"OpBranchConditional {small} {ld} {le}") - self.emit(f"{ld} = OpLabel") - al, sh, sh8, ap, mk, mks, inv, val, vs, t1, t2, one = (self.tmp() for _ in range(12)) - self.emit(f"{sh} = OpUConvert %uint {addr}") - lo3, lo64 = self.tmp(), self.tmp() - self.emit(f"{lo3} = OpBitwiseAnd %uint {sh} {self.cu(3)}") - self.emit(f"{lo64} = OpUConvert %ulong {lo3}") - self.emit(f"{al} = OpISub %ulong {addr} {lo64}") - self.emit(f"{sh8} = OpShiftLeftLogical %uint {sh} {self.cu(3)}") - sh24 = self.tmp() - self.emit(f"{sh24} = OpBitwiseAnd %uint {sh8} {self.cu(24)}") - # MoltenVK 1.4.0 needs an addressable array element for the Metal atomic operations. - dword_arr = self.tmp() - self.emit(f"{dword_arr} = OpConvertUToPtr %_ptr_PSB_arr {self.host_addr(al)}") - self.emit(f"{ap} = OpAccessChain %_ptr_PSB_uint {dword_arr} {self.cu(0)}") - self.emit(f"{one} = OpIEqual %bool {size} {self.cu(1)}") - self.emit(f"{mk} = OpSelect %uint {one} {self.cu(0xFF)} {self.cu(0xFFFF)}") - self.emit(f"{mks} = OpShiftLeftLogical %uint {mk} {sh24}") - self.emit(f"{inv} = OpNot %uint {mks}") - self.emit(f"{val} = OpBitwiseAnd %uint {words[0]} {mk}") - self.emit(f"{vs} = OpShiftLeftLogical %uint {val} {sh24}") - self.emit(f"{t1} = OpAtomicAnd %uint {ap} {self.cu(1)} {self.cu(0)} {inv}") - self.emit(f"{t2} = OpAtomicOr %uint {ap} {self.cu(1)} {self.cu(0)} {vs}") - self.emit(f"OpBranch {le}") - self.emit(f"{le} = OpLabel") - self.emit(f"OpBranch {lbl_end}") - self.emit(f"{lbl_end} = OpLabel") - - def cmp_class(self, a, exec_only=False, ty="f32", mods=()): - """Test x's class against the mask and write the result to VCC/SGPR or EXEC. - Bits: 0 sNaN, 1 qNaN, 2 -inf, 3 -normal, 4 -denormal, 5 -0, 6 +0, 7 +denormal, 8 +normal, 9 +inf. - Supports f32, f16 (with op_sel[0], abs/neg on raw 16-bit bits) and f64 (integer bitwise on lo/hi, - no OpCapability Float64 needed).""" - if ty != "f32" and any(m == "clamp" or m.startswith(("mul:", "div:")) for m in mods): - raise Unsupported(f"v_cmp_class_{ty} output modifier") - # For f16, the class mask takes float inline constants as 16-bit binary16 (low half over 0) before SDWA selection. - mask = self.src_h(a[-1]) if ty == "f16" else self.src_u(a[-1]) - - def b(cond_line): - t = self.tmp() - self.emit(f"{t} = {cond_line}") - return t - - if ty == "f32": - src = a[-2] - # Apply abs/neg as raw sign-bit moves on uint bits: RDNA2 (gfx1036, wave32/64, IEEE=0/1, denorm keep/flush) - # never quiets an sNaN or flushes a denormal on v_cmp(x)_class_f32, whereas SPIR-V FAbs/OpFNegate may quiet. - u = self.src_u({k: v for k, v in src.items() if k not in ("abs", "neg")}) - if src.get("abs"): - g = self.tmp() - self.emit(f"{g} = OpBitwiseAnd %uint {u} {self.cu(0x7FFFFFFF)}") - u = g - if src.get("neg"): - g = self.tmp() - self.emit(f"{g} = OpBitwiseXor %uint {u} {self.cu(0x80000000)}") - u = g - sign, absu = self.tmp(), self.tmp() - self.emit(f"{sign} = OpShiftRightLogical %uint {u} {self.cu(31)}") - self.emit(f"{absu} = OpBitwiseAnd %uint {u} {self.cu(0x7FFFFFFF)}") - exp_, man = self.tmp(), self.tmp() - self.emit(f"{exp_} = OpShiftRightLogical %uint {absu} {self.cu(23)}") - self.emit(f"{man} = OpBitwiseAnd %uint {absu} {self.cu(0x7FFFFF)}") - neg = self.tmp_bool_nz(sign) - is_zero = b(f"OpIEqual %bool {absu} {self.cu(0)}") - exp0 = b(f"OpIEqual %bool {exp_} {self.cu(0)}") - expmax = b(f"OpIEqual %bool {exp_} {self.cu(255)}") - man0 = b(f"OpIEqual %bool {man} {self.cu(0)}") - quiet = b(f"OpUGreaterThanEqual %bool {man} {self.cu(0x400000)}") - elif ty == "f16": - sel, dhi = self.opsel_bits(mods, 2) - if sel[1] or dhi: - raise Unsupported("v_cmp_class_f16 op_sel") - sv = a[-2] - u = self.src_h(sv) - if sel[0]: - t = self.tmp() - self.emit(f"{t} = OpShiftRightLogical %uint {u} {self.cu(16)}") - u = t - h = self.tmp() - self.emit(f"{h} = OpBitwiseAnd %uint {u} {self.cu(0xFFFF)}") - if sv.get("abs"): - t = self.tmp() - self.emit(f"{t} = OpBitwiseAnd %uint {h} {self.cu(0x7FFF)}") - h = t - if sv.get("neg"): - t = self.tmp() - self.emit(f"{t} = OpBitwiseXor %uint {h} {self.cu(0x8000)}") - h = t - sign, absu, exp_, man = (self.tmp() for _ in range(4)) - self.emit(f"{sign} = OpShiftRightLogical %uint {h} {self.cu(15)}") - self.emit(f"{absu} = OpBitwiseAnd %uint {h} {self.cu(0x7FFF)}") - self.emit(f"{exp_} = OpShiftRightLogical %uint {absu} {self.cu(10)}") - self.emit(f"{man} = OpBitwiseAnd %uint {absu} {self.cu(0x3FF)}") - neg = self.tmp_bool_nz(sign) - is_zero = b(f"OpIEqual %bool {absu} {self.cu(0)}") - exp0 = b(f"OpIEqual %bool {exp_} {self.cu(0)}") - expmax = b(f"OpIEqual %bool {exp_} {self.cu(31)}") - man0 = b(f"OpIEqual %bool {man} {self.cu(0)}") - quiet = b(f"OpUGreaterThanEqual %bool {man} {self.cu(0x200)}") - else: # f64 - if any(m.startswith("op_sel") for m in mods): - raise Unsupported("v_cmp_class_f64 op_sel") - sv = a[-2] - if sv["k"] in ("vgpr", "sgpr") and sv.get("n") == 2: - lo, hi = self.load_reg(sv["k"], sv["r"]), self.load_reg(sv["k"], sv["r"] + 1) - elif sv["k"] == "fimm": - bits = struct.unpack("> 32) - elif sv["k"] == "imm": - v = sv["v"] - if -16 <= v <= 64: - v64 = v & 0xFFFFFFFFFFFFFFFF - lo, hi = self.cu(v64 & 0xFFFFFFFF), self.cu(v64 >> 32) - else: - # 32-bit literal dword on a 64-bit float operand occupies the upper 32 bits (RDNA2 ISA). - lo, hi = self.cu(0), self.cu(v & 0xFFFFFFFF) - else: - raise Unsupported("v_cmp_class_f64 operand") - if sv.get("abs"): - t = self.tmp() - self.emit(f"{t} = OpBitwiseAnd %uint {hi} {self.cu(0x7FFFFFFF)}") - hi = t - if sv.get("neg"): - t = self.tmp() - self.emit(f"{t} = OpBitwiseXor %uint {hi} {self.cu(0x80000000)}") - hi = t - sign, absu, exp_, man_hi, man_or, all_or = (self.tmp() for _ in range(6)) - self.emit(f"{sign} = OpShiftRightLogical %uint {hi} {self.cu(31)}") - self.emit(f"{absu} = OpBitwiseAnd %uint {hi} {self.cu(0x7FFFFFFF)}") - self.emit(f"{exp_} = OpShiftRightLogical %uint {absu} {self.cu(20)}") - self.emit(f"{man_hi} = OpBitwiseAnd %uint {absu} {self.cu(0xFFFFF)}") - self.emit(f"{man_or} = OpBitwiseOr %uint {man_hi} {lo}") - self.emit(f"{all_or} = OpBitwiseOr %uint {absu} {lo}") - neg = self.tmp_bool_nz(sign) - is_zero = b(f"OpIEqual %bool {all_or} {self.cu(0)}") - exp0 = b(f"OpIEqual %bool {exp_} {self.cu(0)}") - expmax = b(f"OpIEqual %bool {exp_} {self.cu(2047)}") - man0 = b(f"OpIEqual %bool {man_or} {self.cu(0)}") - quiet = b(f"OpUGreaterThanEqual %bool {man_hi} {self.cu(0x80000)}") - man_nz = b(f"OpLogicalNot %bool {man0}") - is_inf = b(f"OpLogicalAnd %bool {expmax} {man0}") - is_nan = b(f"OpLogicalAnd %bool {expmax} {man_nz}") - snan = b(f"OpLogicalAnd %bool {is_nan} " + b(f"OpLogicalNot %bool {quiet}")) - qnan = b(f"OpLogicalAnd %bool {is_nan} {quiet}") - denorm = b(f"OpLogicalAnd %bool {exp0} {man_nz}") - normal = b(f"OpLogicalAnd %bool " + b(f"OpLogicalNot %bool {exp0}") + " " + b(f"OpLogicalNot %bool {expmax}")) - pos = b(f"OpLogicalNot %bool {neg}") - classes = [snan, qnan, b(f"OpLogicalAnd %bool {is_inf} {neg}"), b(f"OpLogicalAnd %bool {normal} {neg}"), - b(f"OpLogicalAnd %bool {denorm} {neg}"), b(f"OpLogicalAnd %bool {is_zero} {neg}"), - b(f"OpLogicalAnd %bool {is_zero} {pos}"), b(f"OpLogicalAnd %bool {denorm} {pos}"), - b(f"OpLogicalAnd %bool {normal} {pos}"), b(f"OpLogicalAnd %bool {is_inf} {pos}")] - acc = "%false" - for i, c in enumerate(classes): - bit = b(f"OpBitwiseAnd %uint {mask} {self.cu(1 << i)}") - on = b(f"OpINotEqual %bool {bit} {self.cu(0)}") - hit = b(f"OpLogicalAnd %bool {on} {c}") - acc = b(f"OpLogicalOr %bool {acc} {hit}") - acc = b(f"OpLogicalAnd %bool {acc} {self.active_b()}") # inactive lanes write 0 - if exec_only: - self.emit(f"OpStore %active {acc}") - self.uses_active = True - return - r = b(f"OpSelect %uint {acc} {self.cu(0xFFFFFFFF)} {self.cu(0)}") - self.mask_dst({"k": "special", "t": "vcc"} if len(a) == 2 else a[0], r) - - @staticmethod - def mod_int(mods, name, default): - m = next((m for m in mods if m.startswith(name + ":")), None) - return int(m.split(":", 1)[1], 0) if m else default - - def cmp_class_f64(self, op, a, exec_only=False, mods=()): - """v_cmp_class_f64 / v_cmpx_class_f64: test IEEE-754 binary64 class against the 10-bit mask using pure 32-bit - integer ops (no Float64 capability required). - Bits: 0 sNaN, 1 qNaN, 2 -inf, 3 -normal, 4 -denormal, 5 -0, 6 +0, 7 +denormal, 8 +normal, 9 +inf.""" - if mods: - raise Unsupported(op + " modifiers") - if exec_only: - if not (len(a) == 2 or (len(a) == 3 and a[0]["k"] == "special" and a[0]["t"] in ("exec", "exec_lo"))): - raise Unsupported(op + " operands") - else: - if len(a) not in (2, 3): - raise Unsupported(op + " operands") - if len(a) == 3 and not self.is_mask_dst(a[0]): - raise Unsupported(op + " destination") - src0, mask_op = a[-2], a[-1] - if mask_op.get("n", 1) != 1 or mask_op.get("abs") or mask_op.get("neg"): - raise Unsupported(op + " mask") - if src0["k"] in ("vgpr", "sgpr") and src0.get("n") == 2: - lo, hi = self.load_reg(src0["k"], src0["r"]), self.load_reg(src0["k"], src0["r"] + 1) - elif src0["k"] == "fimm": - bits = struct.unpack("> 32) - elif src0["k"] == "imm": - v = src0["v"] - # RDNA2 ISA: inline integers (-16..64) sign-extend to 64 bits; a 32-bit literal occupies bits [63:32]. - if src0.get("literal") or (not (-16 <= v <= 64) and -0x80000000 <= v <= 0xFFFFFFFF): - lo, hi = self.cu(0), self.cu(v & 0xFFFFFFFF) - else: - bits = v & 0xFFFFFFFFFFFFFFFF - lo, hi = self.cu(bits & 0xFFFFFFFF), self.cu(bits >> 32) - else: - raise Unsupported(op + " operand") - if src0.get("abs"): - t = self.tmp() - self.emit(f"{t} = OpBitwiseAnd %uint {hi} {self.cu(0x7FFFFFFF)}") - hi = t - if src0.get("neg"): - t = self.tmp() - self.emit(f"{t} = OpBitwiseXor %uint {hi} {self.cu(0x80000000)}") - hi = t - mask = self.src_u(mask_op) - - def b(cond_line): - t = self.tmp() - self.emit(f"{t} = {cond_line}") - return t - - sign = b(f"OpShiftRightLogical %uint {hi} {self.cu(31)}") - exp_s = b(f"OpShiftRightLogical %uint {hi} {self.cu(20)}") - exp_ = b(f"OpBitwiseAnd %uint {exp_s} {self.cu(0x7FF)}") - man_hi = b(f"OpBitwiseAnd %uint {hi} {self.cu(0xFFFFF)}") - man_or = b(f"OpBitwiseOr %uint {man_hi} {lo}") - neg = self.tmp_bool_nz(sign) - pos = b(f"OpLogicalNot %bool {neg}") - exp0 = b(f"OpIEqual %bool {exp_} {self.cu(0)}") - expmax = b(f"OpIEqual %bool {exp_} {self.cu(0x7FF)}") - man0 = b(f"OpIEqual %bool {man_or} {self.cu(0)}") - man_nz = b(f"OpLogicalNot %bool {man0}") - is_zero = b(f"OpLogicalAnd %bool {exp0} {man0}") - denorm = b(f"OpLogicalAnd %bool {exp0} {man_nz}") - normal = b(f"OpLogicalAnd %bool " + b(f"OpLogicalNot %bool {exp0}") + " " + b(f"OpLogicalNot %bool {expmax}")) - is_inf = b(f"OpLogicalAnd %bool {expmax} {man0}") - is_nan = b(f"OpLogicalAnd %bool {expmax} {man_nz}") - qbit = b(f"OpBitwiseAnd %uint {man_hi} {self.cu(0x80000)}") - quiet = self.tmp_bool_nz(qbit) - snan = b(f"OpLogicalAnd %bool {is_nan} " + b(f"OpLogicalNot %bool {quiet}")) - qnan = b(f"OpLogicalAnd %bool {is_nan} {quiet}") - classes = [ - snan, qnan, - b(f"OpLogicalAnd %bool {is_inf} {neg}"), b(f"OpLogicalAnd %bool {normal} {neg}"), - b(f"OpLogicalAnd %bool {denorm} {neg}"), b(f"OpLogicalAnd %bool {is_zero} {neg}"), - b(f"OpLogicalAnd %bool {is_zero} {pos}"), b(f"OpLogicalAnd %bool {denorm} {pos}"), - b(f"OpLogicalAnd %bool {normal} {pos}"), b(f"OpLogicalAnd %bool {is_inf} {pos}"), - ] - acc = "%false" - for i, c in enumerate(classes): - bit = b(f"OpBitwiseAnd %uint {mask} {self.cu(1 << i)}") - on = b(f"OpINotEqual %bool {bit} {self.cu(0)}") - hit = b(f"OpLogicalAnd %bool {on} {c}") - acc = b(f"OpLogicalOr %bool {acc} {hit}") - acc = b(f"OpLogicalAnd %bool {acc} {self.active_b()}") # inactive lanes write 0 - if exec_only: - self.emit(f"OpStore %active {acc}") - self.uses_active = True - return - r = b(f"OpSelect %uint {acc} {self.cu(0xFFFFFFFF)} {self.cu(0)}") - self.mask_dst({"k": "special", "t": "vcc"} if len(a) == 2 else a[0], r) - - # LDS atomics (non-returning name -> SPIR-V atomic); _rtn_ forms share the entry. - LDS_ATOMICS = {"ds_add_u32": "OpAtomicIAdd", "ds_sub_u32": "OpAtomicISub", "ds_min_u32": "OpAtomicUMin", - "ds_max_u32": "OpAtomicUMax", "ds_min_i32": "OpAtomicSMin", "ds_max_i32": "OpAtomicSMax", - "ds_and_b32": "OpAtomicAnd", "ds_or_b32": "OpAtomicOr", "ds_xor_b32": "OpAtomicXor", - "ds_wrxchg_rtn_b32": "OpAtomicExchange"} - - def lds_ptr(self, addr, byte_off): - """Pointer to the LDS dword at (addr + byte_off) / 4, wrapped to the array (LDS is a Workgroup uint array).""" - s1, i, m, p = self.tmp(), self.tmp(), self.tmp(), self.tmp() - self.emit(f"{s1} = OpIAdd %uint {addr} {self.cu(byte_off)}") - self.emit(f"{i} = OpShiftRightLogical %uint {s1} {self.cu(2)}") - self.emit(f"{m} = OpBitwiseAnd %uint {i} {self.cu(self.lds_dwords - 1)}") - self.emit(f"{p} = OpAccessChain %_ptr_WG_uint %lds {m}") - return p - - def lds_access(self, addr, byte_off, fn, bound=None): - """One LDS dword access: fn(pointer) emits it and returns its uint result id (a load, an atomic's old value) - or None (a store). Without lds_bound this is fn(lds_ptr(...)), the wrapped access shaders always had. With - it (SHADER-309: the program reaches past its RSRC2 allocation, or the array was shrunk to it), the dword - index is checked: RDNA2 LDS does not wrap, an access outside the allocation reads 0 and its write is dropped - (RDNA2 ISA sections 3.6.1 and 3.6.6), so the access runs only in range and the result is 0 otherwise. `bound` - (dwords) checks this one access even when lds_bound is unset.""" - bound = self.lds_bound if bound is None else bound - if bound is None: - return fn(self.lds_ptr(addr, byte_off)) - s1, i, ok, p = self.tmp(), self.tmp(), self.tmp(), self.tmp() - pre, do, end = self.tmp() + "_lb", self.tmp() + "_lin", self.tmp() + "_lend" - self.emit(f"{s1} = OpIAdd %uint {addr} {self.cu(byte_off)}") - self.emit(f"{i} = OpShiftRightLogical %uint {s1} {self.cu(2)}") - self.emit(f"{ok} = OpULessThan %bool {i} {self.cu(bound)}") - self.emit(f"OpBranch {pre}") - self.emit(f"{pre} = OpLabel") - self.emit(f"OpSelectionMerge {end} None") - self.emit(f"OpBranchConditional {ok} {do} {end}") - self.emit(f"{do} = OpLabel") - self.emit(f"{p} = OpAccessChain %_ptr_WG_uint %lds {i}") - r = fn(p) - done_lbl = self.current_label_placeholder() - self.emit(f"OpBranch {end}") - self.emit(f"{end} = OpLabel") - if r is None: - return None - v = self.tmp() - self.emit(f"{v} = OpPhi %uint {r} {done_lbl} {self.cu(0)} {pre}") - return v - - def lds_load(self, addr, byte_off, bound=None): - # Volatile: another lane's ds_write may come between two accesses of this lane, and the Vulkan memory model - # orders nothing between invocations without a barrier, so a driver may otherwise move this read ahead of - # the wave's earlier writes or merge it with another read (docs/design.md, "LDS access order within a wave"). - def f(p): - v = self.tmp() - self.emit(f"{v} = OpLoad %uint {p} Volatile") - return v - return self.lds_access(addr, byte_off, f, bound) - - def lds_cross_bound(self): - """Bound (dwords) for the next dword a dword-crossing access reaches: the allocation, never wrapped to dword 0, - even in a shader whose other accesses keep the wrapped power-of-two array.""" - if self.lds_bound is not None: - return self.lds_bound - return min(self.lds_declared, self.lds_dwords) if self.lds_declared else self.lds_dwords - - def lds_store(self, addr, byte_off, val): - self.lds_access(addr, byte_off, lambda p: self.emit(f"OpStore {p} {val} Volatile")) # as lds_load - - def lds_next_in_bounds(self, addr, byte_off): - """Bool: the dword after the one at (addr + byte_off) is inside the allocation (lds_cross_bound).""" - s1, i, ok = self.tmp(), self.tmp(), self.tmp() - self.emit(f"{s1} = OpIAdd %uint {addr} {self.cu(byte_off + 1)}") - self.emit(f"{i} = OpShiftRightLogical %uint {s1} {self.cu(2)}") - self.emit(f"{ok} = OpULessThan %bool {i} {self.cu(self.lds_cross_bound())}") - return ok - - def lds_u16_cross_read(self, addr, byte_off, w, sh): - """A 16-bit LDS read at byte 3 of a dword (bit offset `sh` 24) also takes byte 0 of the next dword, as RDNA2 - LDS reads it in unaligned mode (llc -mcpu=gfx1030 -mattr=+unaligned-access-mode emits one ds_read_u16 at - offset 3; gfx1036 hardware agrees). When that byte is past the allocation the whole read returns 0, as on - gfx1036. Returns (word, bit offset) for the 16-bit extract; the next dword is only read when crossing.""" - cross, lo, hi, both, comb, w2, sh2 = (self.tmp() for _ in range(7)) - x_do, x_end = self.tmp() + "_x", self.tmp() + "_xend" - self.emit(f"{cross} = OpIEqual %bool {sh} {self.cu(24)}") - pre = self.current_label_placeholder() - self.emit(f"OpSelectionMerge {x_end} None") - self.emit(f"OpBranchConditional {cross} {x_do} {x_end}") - self.emit(f"{x_do} = OpLabel") - ok = self.lds_next_in_bounds(addr, byte_off) - nxt = self.lds_load(addr, byte_off + 1, self.lds_cross_bound()) - self.emit(f"{lo} = OpShiftRightLogical %uint {w} {self.cu(24)}") - self.emit(f"{hi} = OpShiftLeftLogical %uint {nxt} {self.cu(8)}") - self.emit(f"{both} = OpBitwiseOr %uint {lo} {hi}") - self.emit(f"{comb} = OpSelect %uint {ok} {both} {self.cu(0)}") - last = self.current_label_placeholder() - self.emit(f"OpBranch {x_end}") - self.emit(f"{x_end} = OpLabel") - self.emit(f"{w2} = OpPhi %uint {comb} {last} {w} {pre}") - self.emit(f"{sh2} = OpSelect %uint {cross} {self.cu(0)} {sh}") - return w2, sh2 - - def lds_atomic(self, addr, byte_off, rest): - """`rest` is the atomic instruction after its result id, with {p} where the pointer goes.""" - def f(p): - v = self.tmp() - self.emit(f"{v} = " + rest.replace("{p}", p)) - return v - return self.lds_access(addr, byte_off, f) - - def ds_append(self, op, a, mods): - """ds_append / ds_consume vD [offset:N]: one LDS add (append) or subtract (consume) of the number of lanes on in - EXEC, for the whole wave, at the byte address N; every active lane gets the value before the op, inactive lanes - keep vD. Measured natively on RDNA2 gfx1036 (hunt6 hw_append.py, wave32 and wave64 with EXEC across both - halves): the address is the offset field alone, M0 (0x4, 0x100, 0x10000, 0x40000, 0x80000) does not move it. - The add is done once, by the first active lane of the wave (the wave's EXEC gathered as for s_bcnt1); the old - value reaches the other lanes by a subgroup shuffle from that lane, or an exchange round under - --wave64-emulate (a wave64 on 32-wide subgroups without it: right in the half of the first active lane only, - the known cross-half approximation). The gds form is refused.""" - if "gds" in mods: - raise Unsupported(op + " gds") - if not a or a[0]["k"] != "vgpr": - raise Unsupported(op + " operands") - off = self.mod_int(mods, "offset", 0) - lo, hi = self.wave_mask({"k": "special", "t": "exec"}) - cl, ch, cnt, lz, hz, l, h, h32, fh, first, lane, me, act, do = (self.tmp() for _ in range(14)) - self.emit(f"{cl} = OpBitCount %uint {lo}") - self.emit(f"{ch} = OpBitCount %uint {hi}") - self.emit(f"{cnt} = OpIAdd %uint {cl} {ch}") - self.emit(f"{lz} = OpINotEqual %bool {lo} {self.cu(0)}") - self.emit(f"{hz} = OpINotEqual %bool {hi} {self.cu(0)}") - self.emit(f"{l} = OpExtInst %uint %glsl FindILsb {lo}") - self.emit(f"{h} = OpExtInst %uint %glsl FindILsb {hi}") - self.emit(f"{h32} = OpIAdd %uint {h} {self.cu(32)}") - self.emit(f"{fh} = OpSelect %uint {hz} {h32} {self.cu(64)}") # no lane on: 64, nobody's lane - self.emit(f"{first} = OpSelect %uint {lz} {l} {fh}") - self.emit(f"{lane} = OpCopyObject %uint {self.wave_lane()}") - self.emit(f"{me} = OpIEqual %bool {lane} {first}") - self.emit(f"{act} = OpCopyObject %bool {self.active_b()}") - self.emit(f"{do} = OpLogicalAnd %bool {me} {act}") - lbl_do, lbl_end = self.tmp() + "_do", self.tmp() + "_end" - pre = self.current_label_placeholder() - self.emit(f"OpSelectionMerge {lbl_end} None") - self.emit(f"OpBranchConditional {do} {lbl_do} {lbl_end}") - self.emit(f"{lbl_do} = OpLabel") - spv = "OpAtomicIAdd" if op == "ds_append" else "OpAtomicISub" - r = self.lds_atomic(self.cu(0), off, f"{spv} %uint {{p}} {self.cu(2)} {self.cu(0)} {cnt}") - done = self.current_label_placeholder() - self.emit(f"OpBranch {lbl_end}") - self.emit(f"{lbl_end} = OpLabel") - old = self.tmp() - self.emit(f"{old} = OpPhi %uint {r} {done} {self.cu(0)} {pre}") - if self.emulate: - read, _ = self.x_round(data=old) - fi = self.tmp() - self.emit(f"{fi} = OpBitwiseAnd %uint {first} {self.cu(63)}") - val = read(fi) - else: - self.uses_subgroup = self.uses_ballot = True - fi, val = self.tmp(), self.tmp() - self.emit(f"{fi} = OpBitwiseAnd %uint {first} {self.cu(63 if self.wave64 else 31)}") - self.emit(f"{val} = OpGroupNonUniformShuffle %uint {self.cu(3)} {old} {fi}") - self.dst(a[0], val) - - def lds_op(self, op, a, mods): - """LDS (GFX10 DS encoding). Addresses are bytes. offset:N is bytes; read2/write2 offset0/offset1 count - data-size units (x64 for st64). Writes and atomics run only in active lanes; results land in VGPRs through - dst (inactive lanes unchanged). Sub-dword writes use atomic and/or so neighbouring lanes don't race.""" - if self.stage not in ("cs", "ms"): - raise Unsupported(op + " outside compute") - self.uses_lds = True - if op in ("ds_append", "ds_consume"): - return self.ds_append(op, a, mods) # wave-wide: before the per-lane EXEC selection below - rtn = "_rtn_" in op - name = op if op == "ds_wrxchg_rtn_b32" else op.replace("_rtn_", "_") - act = self.active_b() - lbl_do, lbl_end = self.tmp() + "_do", self.tmp() + "_end" - self.emit(f"OpSelectionMerge {lbl_end} None") - self.emit(f"OpBranchConditional {act} {lbl_do} {lbl_end}") - self.emit(f"{lbl_do} = OpLabel") - off = self.mod_int(mods, "offset", 0) - sc, sem = self.cu(2), self.cu(0) - sizes = {"b32": 1, "b64": 2, "b96": 3, "b128": 4} - if op in ("ds_read_addtid_b32", "ds_write_addtid_b32"): - if "gds" in mods or not 0 <= off <= 0xFFFF: - raise Unsupported(op + " addressing") - if len(a) != 1 or a[0]["k"] != "vgpr" or a[0].get("n", 1) != 1: - raise Unsupported(op + " operand") - # RDNA2 ISA: LDS_BASE + offset + M0[15:0] + 4 * lane within the wave. - # The Workgroup array makes LDS_BASE implicit. - m0, base, lane_bytes, addr = (self.tmp() for _ in range(4)) - self.emit(f"{m0} = OpLoad %uint %m0") - self.emit(f"{base} = OpBitwiseAnd %uint {m0} {self.cu(0xFFFF)}") - self.emit(f"{lane_bytes} = OpShiftLeftLogical %uint {self.wave_lane()} {self.cu(2)}") - self.emit(f"{addr} = OpIAdd %uint {base} {lane_bytes}") - ptr = self.lds_ptr(addr, off) - if op == "ds_read_addtid_b32": - value = self.tmp() - self.emit(f"{value} = OpLoad %uint {ptr} Volatile") # as lds_load - self.dst(a[0], value) - else: - self.emit(f"OpStore {ptr} {self.src_u(a[0])} Volatile") - elif op in ("ds_read_b32", "ds_read_b64", "ds_read_b96", "ds_read_b128"): - addr = self.src_u(a[1]) - for k in range(sizes[op.rsplit("_", 1)[1]]): - v = self.lds_load(addr, off + 4 * k) - self.dst({"k": "vgpr", "r": a[0]["r"] + k, "n": 1}, v) - elif op in ("ds_write_b32", "ds_write_b64", "ds_write_b96", "ds_write_b128"): - addr = self.src_u(a[0]) - for k in range(sizes[op.rsplit("_", 1)[1]]): - v = self.load_reg("vgpr", a[1]["r"] + k) - self.lds_store(addr, off + 4 * k, v) - elif op in ("ds_read2_b32", "ds_read2st64_b32", "ds_write2_b32", "ds_write2st64_b32", - "ds_read2_b64", "ds_read2st64_b64", "ds_write2_b64", "ds_write2st64_b64"): - # Two elements at ADDR + offset0 * unit and ADDR + offset1 * unit; unit = element size (4 or 8 bytes), - # times 64 for st64. A b64 element is two consecutive dwords (low first): read2_b64 fills - # v[d:d+3], write2_b64 takes two VGPR pairs. - words = 2 if op.endswith("_b64") else 1 - unit = 4 * words * (64 if "st64" in op else 1) - offs = (self.mod_int(mods, "offset0", 0) * unit, self.mod_int(mods, "offset1", 0) * unit) - if op.startswith("ds_read2"): - addr = self.src_u(a[1]) - vals = [] - for o in offs: - for w in range(words): - vals.append(self.lds_load(addr, o + 4 * w)) - for k, v in enumerate(vals): # every load before the first write (vdst may alias vaddr) - self.dst({"k": "vgpr", "r": a[0]["r"] + k, "n": 1}, v) - else: - addr = self.src_u(a[0]) - for k, o in enumerate(offs): - data = a[1 + k] - for w in range(words): - if words == 1: - v = self.src_u(data) - elif data["k"] == "vgpr" and data.get("n") == 2: - v = self.load_reg("vgpr", data["r"] + w) - else: - raise Unsupported(op + " data") - self.lds_store(addr, o + 4 * w, v) - elif op in ("ds_read_u16", "ds_read_i16", "ds_read_u8", "ds_read_i8", "ds_read_u16_d16_hi", "ds_read_u16_d16", - "ds_read_u8_d16", "ds_read_u8_d16_hi", "ds_read_i8_d16", "ds_read_i8_d16_hi"): - bits = 16 if "16" in op.split("_")[2] else 8 - addr = self.src_u(a[1]) - s1, sh, sh2, w, v = (self.tmp() for _ in range(5)) - self.emit(f"{s1} = OpIAdd %uint {addr} {self.cu(off)}") - self.emit(f"{sh} = OpShiftLeftLogical %uint {s1} {self.cu(3)}") # byte address -> bit offset - self.emit(f"{sh2} = OpBitwiseAnd %uint {sh} {self.cu(31)}") - w = self.lds_load(addr, off) - if bits == 16: - w, sh2 = self.lds_u16_cross_read(addr, off, w, sh2) - f = "OpBitFieldSExtract" if op.split("_")[2].startswith("i") else "OpBitFieldUExtract" - self.emit(f"{v} = {f} %uint {w} {sh2} {self.cu(bits)}") - d = a[0] - if "_d16" in op: - # u8/i8: v is the 8-bit field extended to 32 bits; the insert keeps only its low 16 bits, so the - # i8 sign extension is 8 -> 16 as the ISA says. The other half of the destination is kept. - hi = op.endswith("_hi") - r = self.tmp() - self.emit(f"{r} = OpBitFieldInsert %uint {self.load_reg('vgpr', d['r'])} {v} " - f"{self.cu(16 if hi else 0)} {self.cu(16)}") - v = r - self.dst(d, v) - elif op in ("ds_write_b16", "ds_write_b8", "ds_write_b16_d16_hi", "ds_write_b8_d16_hi"): - bits = 16 if "b16" in op else 8 - addr = self.src_u(a[0]) - val = self.src_u(a[1]) - if op.endswith("_d16_hi"): - hv = self.tmp() - self.emit(f"{hv} = OpShiftRightLogical %uint {val} {self.cu(16)}") - val = hv - s1, sh, sh2, fld, pos, msk, inv = (self.tmp() for _ in range(7)) - self.emit(f"{s1} = OpIAdd %uint {addr} {self.cu(off)}") - self.emit(f"{sh} = OpShiftLeftLogical %uint {s1} {self.cu(3)}") - self.emit(f"{sh2} = OpBitwiseAnd %uint {sh} {self.cu(31)}") - self.emit(f"{fld} = OpBitwiseAnd %uint {val} {self.cu((1 << bits) - 1)}") - self.emit(f"{pos} = OpShiftLeftLogical %uint {fld} {sh2}") - self.emit(f"{msk} = OpShiftLeftLogical %uint {self.cu((1 << bits) - 1)} {sh2}") - self.emit(f"{inv} = OpNot %uint {msk}") - - def sub_dword(p): - t1, t2 = self.tmp(), self.tmp() - self.emit(f"{t1} = OpAtomicAnd %uint {p} {sc} {sem} {inv}") - self.emit(f"{t2} = OpAtomicOr %uint {p} {sc} {sem} {pos}") - if bits != 16: - self.lds_access(addr, off, sub_dword) - else: - # A halfword at byte 3 writes its high byte to byte 0 of the next dword. When that byte is past the - # allocation the whole write is dropped, as on gfx1036 (the low byte is not written either). - cross, ok, nok, drop, keep, both, hb = (self.tmp() for _ in range(7)) - k_do, k_end = self.tmp() + "_k", self.tmp() + "_kend" - x_do, x_end = self.tmp() + "_x", self.tmp() + "_xend" - self.emit(f"{cross} = OpIEqual %bool {sh2} {self.cu(24)}") - ok = self.lds_next_in_bounds(addr, off) - self.emit(f"{nok} = OpLogicalNot %bool {ok}") - self.emit(f"{drop} = OpLogicalAnd %bool {cross} {nok}") - self.emit(f"{keep} = OpLogicalNot %bool {drop}") - self.emit(f"{both} = OpLogicalAnd %bool {cross} {ok}") - self.emit(f"OpSelectionMerge {k_end} None") - self.emit(f"OpBranchConditional {keep} {k_do} {k_end}") - self.emit(f"{k_do} = OpLabel") - self.lds_access(addr, off, sub_dword) - self.emit(f"OpBranch {k_end}") - self.emit(f"{k_end} = OpLabel") - self.emit(f"OpSelectionMerge {x_end} None") - self.emit(f"OpBranchConditional {both} {x_do} {x_end}") - self.emit(f"{x_do} = OpLabel") - self.emit(f"{hb} = OpShiftRightLogical %uint {fld} {self.cu(8)}") - - def next_byte0(p): - t1, t2 = self.tmp(), self.tmp() - self.emit(f"{t1} = OpAtomicAnd %uint {p} {sc} {sem} {self.cu(0xFFFFFF00)}") - self.emit(f"{t2} = OpAtomicOr %uint {p} {sc} {sem} {hb}") - self.lds_access(addr, off + 1, next_byte0, self.lds_cross_bound()) - self.emit(f"OpBranch {x_end}") - self.emit(f"{x_end} = OpLabel") - elif name in self.LDS_ATOMICS: - d, ad, dat = (a[0], a[1], a[2]) if rtn else (None, a[0], a[1]) - old = self.lds_atomic(self.src_u(ad), off, - f"{self.LDS_ATOMICS[name]} %uint {{p}} {sc} {sem} {self.src_u(dat)}") - if d is not None: - self.dst(d, old) - elif op in ("ds_wrxchg2_rtn_b32", "ds_wrxchg2st64_rtn_b32"): - # Two atomic exchanges, at ADDR + offset0 * unit and ADDR + offset1 * unit (unit 4 bytes, x64 for st64), - # as ds_write2_b32 addresses them: M[A0] = DATA, M[A1] = DATA2; vdst = {old M[A0], old M[A1]}. - d = a[0] - if d["k"] != "vgpr" or d.get("n") != 2: - raise Unsupported(op + " destination") - unit = 4 * (64 if "st64" in op else 1) - addr = self.src_u(a[1]) - olds = [] - for k, name in enumerate(("offset0", "offset1")): - old = self.lds_atomic(addr, self.mod_int(mods, name, 0) * unit, - f"OpAtomicExchange %uint {{p}} {sc} {sem} {self.src_u(a[2 + k])}") - olds.append(old) - for k, old in enumerate(olds): # both exchanges before the first write (vdst may alias) - self.dst({"k": "vgpr", "r": d["r"] + k, "n": 1}, old) - elif op in ("ds_wrxchg_rtn_b64", "ds_wrxchg2_rtn_b64", "ds_wrxchg2st64_rtn_b64"): - # 64-bit exchanges: M[A] = DATA (two dwords, low first) and vdst gets the old 64 bits. wrxchg_rtn_b64 has - # one element at ADDR + offset; the 2 forms have two, at ADDR + offset0/offset1 * 8 (x64 for st64), as - # ds_write2_b64 addresses them, and vdst is four VGPRs. Each dword is its own 32-bit exchange, with no Int64 - # atomics on Workgroup memory. That can tear: two lanes exchanging into one element at once can leave one's - # low dword with the other's high dword (A.lo, B.lo, B.hi, A.hi), which a 64-bit exchange never does. The - # returned pair is two reads, so another lane's 64-bit op on the same element between them could be seen - # half done (as for ds_and/or/xor_b64). - two = op != "ds_wrxchg_rtn_b64" - d = a[0] - if d["k"] != "vgpr" or d.get("n") != (4 if two else 2): - raise Unsupported(op + " destination") - datas = a[2:4] if two else a[2:3] - if any(x["k"] != "vgpr" or x.get("n") != 2 for x in datas): - raise Unsupported(op + " data") - unit = 8 * (64 if "st64" in op else 1) - offs = ([self.mod_int(mods, f, 0) * unit for f in ("offset0", "offset1")] if two else [off]) - addr = self.src_u(a[1]) - vals = [[self.load_reg("vgpr", x["r"] + w) for w in range(2)] for x in datas] - olds = [] - for o, val in zip(offs, vals): - for w in range(2): - old = self.lds_atomic(addr, o + 4 * w, f"OpAtomicExchange %uint {{p}} {sc} {sem} {val[w]}") - olds.append(old) - for k, old in enumerate(olds): # every exchange before the first write (vdst may alias) - self.dst({"k": "vgpr", "r": d["r"] + k, "n": 1}, old) - elif name in ("ds_and_b64", "ds_or_b64", "ds_xor_b64"): - # M = M op D on a 64-bit LDS element (the dwords at ADDR and ADDR + 4, low first); the _rtn_ form returns - # the old 64 bits in a VGPR pair. A bitwise op works on each bit alone, so one 32-bit atomic per dword - # leaves exactly the memory a 64-bit atomic would, with no Int64 atomics on Workgroup memory (optional in - # Vulkan). The returned pair is two reads, so a 64-bit op from another lane on the same element between - # them could be seen half done; the memory result is exact either way. - d, ad, dat = (a[0], a[1], a[2]) if rtn else (None, a[0], a[1]) - if dat["k"] != "vgpr" or dat.get("n") != 2 or (d is not None and (d["k"] != "vgpr" or d.get("n") != 2)): - raise Unsupported(op + " operands") - k = {"ds_and_b64": "OpAtomicAnd", "ds_or_b64": "OpAtomicOr", "ds_xor_b64": "OpAtomicXor"}[name] - addr = self.src_u(ad) - vals = [self.load_reg("vgpr", dat["r"] + w) for w in range(2)] - olds = [] - for w in range(2): - old = self.lds_atomic(addr, off + 4 * w, f"{k} %uint {{p}} {sc} {sem} {vals[w]}") - olds.append(old) - if d is not None: - for w in range(2): - self.dst({"k": "vgpr", "r": d["r"] + w, "n": 1}, olds[w]) - elif op in ("ds_mskor_b32", "ds_mskor_rtn_b32"): - # tmp = M[A]; M[A] = (tmp & ~DATA) | DATA2; the _rtn_ form returns tmp (RDNA2 ISA, DS). As two atomics: - # AND with ~DATA (its result is tmp, exactly), then OR with DATA2. The memory ends as the single op - # leaves it unless another lane's op on the same dword lands between the two; the returned value is exact. - d, ad, msk, dat = (a[0], a[1], a[2], a[3]) if rtn else (None, a[0], a[1], a[2]) - addr = self.src_u(ad) - inv = self.tmp() - m_val, d_val = self.src_u(msk), self.src_u(dat) - self.emit(f"{inv} = OpNot %uint {m_val}") - - def mskor(p): - old, _or = self.tmp(), self.tmp() - self.emit(f"{old} = OpAtomicAnd %uint {p} {sc} {sem} {inv}") - self.emit(f"{_or} = OpAtomicOr %uint {p} {sc} {sem} {d_val}") - return old - old = self.lds_access(addr, off, mskor) # bounds-checked when lds_bound is set (SHADER-309) - if d is not None: - self.dst(d, old) - elif op in ("ds_add_f32", "ds_add_rtn_f32"): - # M = M + DATA as binary32 (RDNA2 ISA, DS_ADD_F32); the _rtn_ form returns the old M. No core SPIR-V atomic - # adds floats on Workgroup memory, so this is an OpAtomicCompareExchange loop with an OpFAdd (round to - # nearest even, NoContraction): exact under contention, every update one successful exchange of the - # value it read. How the LDS adder treats denormals and NaN payloads is not measured: OpFAdd's IEEE - # result is what is computed. - d, ad, dat = (a[0], a[1], a[2]) if rtn else (None, a[0], a[1]) - p = self.lds_ptr(self.src_u(ad), off) - x = self.tof(self.src_u(dat)) - lbl_hdr, lbl_cont, lbl_exit = (self.tmp() + t for t in ("_hdr", "_cont", "_exit")) - init = self.tmp() - self.emit(f"{init} = OpAtomicLoad %uint {p} {sc} {sem}") - entry = self.current_label_placeholder() - self.emit(f"OpBranch {lbl_hdr}") - self.emit(f"{lbl_hdr} = OpLabel") - cur, cur_f, sum_f, new, got, done = (self.tmp() for _ in range(6)) - self.emit(f"{cur} = OpPhi %uint {init} {entry} {got} {lbl_cont}") - self.emit(f"{cur_f} = OpBitcast %float {cur}") - self.emit(f"{sum_f} = OpFAdd %float {cur_f} {x}") - self.emit(f"{new} = OpBitcast %uint {sum_f}") - self.emit(f"{got} = OpAtomicCompareExchange %uint {p} {sc} {sem} {sem} {new} {cur}") - self.emit(f"{done} = OpIEqual %bool {got} {cur}") - self.emit(f"OpLoopMerge {lbl_exit} {lbl_cont} None") - self.emit(f"OpBranchConditional {done} {lbl_exit} {lbl_cont}") - self.emit(f"{lbl_cont} = OpLabel") - self.emit(f"OpBranch {lbl_hdr}") - self.emit(f"{lbl_exit} = OpLabel") - if d is not None: - self.dst(d, cur) - elif op in ("ds_cmpst_rtn_f32", "ds_cmpst_f32"): - # ds_cmpst_b32's operands (DATA = the compare value, DATA2 = the new one), compared as binary32. A CAS - # loop, so lds_ptr as the other CAS-loop LDS atomics (lds_access's merge assumes a single-block access). - d, ad, cmp_, src = (a[0], a[1], a[2], a[3]) if rtn else (None, a[0], a[1], a[2]) - p = self.lds_ptr(self.src_u(ad), off) - old = self.float_cmpswap_loop(p, self.src_u(src), self.src_u(cmp_), sc) - if d is not None: - self.dst(d, old) - elif op in ("ds_cmpst_rtn_b32", "ds_cmpst_b32"): - # tmp = M[A]; M[A] = (tmp == DATA) ? DATA2 : tmp; the _rtn_ form returns tmp, ds_cmpst_b32 drops it. - d, ad, cmp_, src = (a[0], a[1], a[2], a[3]) if rtn else (None, a[0], a[1], a[2]) - old = self.lds_atomic(self.src_u(ad), off, f"OpAtomicCompareExchange %uint {{p}} {sc} {sem} {sem} " - f"{self.src_u(src)} {self.src_u(cmp_)}") - if d is not None: - self.dst(d, old) - elif name in ("ds_inc_u32", "ds_dec_u32", "ds_rsub_u32", "ds_min_f32", "ds_max_f32"): - # RDNA2 ISA 32-bit DS atomics via Workgroup-scope OpAtomicCompareExchange CAS loop: - # ds_inc_u32: M = (M >= DATA) ? 0 : M + 1 (unsigned compare) - # ds_dec_u32: M = (M == 0 || M > DATA) ? DATA : M - 1 (unsigned compare) - # ds_rsub_u32: M = DATA - M (32-bit wrapping) - # ds_min_f32 / ds_max_f32: GLSL.std.450 NMin / NMax (no shader float atomic extension needed) - if len(a) != (3 if rtn else 2): - raise Unsupported(op + " operands") - d, ad, dat = (a[0], a[1], a[2]) if rtn else (None, a[0], a[1]) - if dat["k"] != "vgpr" or dat.get("n", 1) != 1 or \ - (d is not None and (d["k"] != "vgpr" or d.get("n", 1) != 1)): - raise Unsupported(op + " operands") - addr = self.src_u(ad) - val = self.src_u(dat) - val_f = None - if name in ("ds_min_f32", "ds_max_f32"): - val_f = self.tmp() - self.emit(f"{val_f} = OpBitcast %float {val}") - - def cas(p): - entry_lbl = self.current_label_placeholder() - lbl_hdr, lbl_cont, lbl_exit = (self.tmp() + s for s in ("_hdr", "_cont", "_exit")) - init = self.tmp() - self.emit(f"{init} = OpAtomicLoad %uint {p} {sc} {sem}") - self.emit(f"OpBranch {lbl_hdr}") - self.emit(f"{lbl_hdr} = OpLabel") - cur, got = self.tmp(), self.tmp() - self.emit(f"{cur} = OpPhi %uint {init} {entry_lbl} {got} {lbl_cont}") - if name == "ds_inc_u32": - wrap, step, new_u = self.tmp(), self.tmp(), self.tmp() - self.emit(f"{wrap} = OpUGreaterThanEqual %bool {cur} {val}") - self.emit(f"{step} = OpIAdd %uint {cur} {self.cu(1)}") - self.emit(f"{new_u} = OpSelect %uint {wrap} {self.cu(0)} {step}") - elif name == "ds_dec_u32": - is_z, gt, wrap, step, new_u = (self.tmp() for _ in range(5)) - self.emit(f"{is_z} = OpIEqual %bool {cur} {self.cu(0)}") - self.emit(f"{gt} = OpUGreaterThan %bool {cur} {val}") - self.emit(f"{wrap} = OpLogicalOr %bool {is_z} {gt}") - self.emit(f"{step} = OpISub %uint {cur} {self.cu(1)}") - self.emit(f"{new_u} = OpSelect %uint {wrap} {val} {step}") - elif name == "ds_rsub_u32": - new_u = self.tmp() - self.emit(f"{new_u} = OpISub %uint {val} {cur}") - else: - cur_f, new_f, new_u = self.tmp(), self.tmp(), self.tmp() - self.emit(f"{cur_f} = OpBitcast %float {cur}") - glsl_op = "NMin" if name == "ds_min_f32" else "NMax" - self.emit(f"{new_f} = OpExtInst %float %glsl {glsl_op} {cur_f} {val_f}") - self.emit(f"{new_u} = OpBitcast %uint {new_f}") - done = self.tmp() - self.emit(f"{got} = OpAtomicCompareExchange %uint {p} {sc} {sem} {sem} {new_u} {cur}") - self.emit(f"{done} = OpIEqual %bool {got} {cur}") - self.emit(f"OpLoopMerge {lbl_exit} {lbl_cont} None") - self.emit(f"OpBranchConditional {done} {lbl_exit} {lbl_cont}") - self.emit(f"{lbl_cont} = OpLabel") - self.emit(f"OpBranch {lbl_hdr}") - self.emit(f"{lbl_exit} = OpLabel") - return cur if d is not None else None - - old = self.lds_access(addr, off, cas) # bounds-checked when lds_bound is set (SHADER-309) - if d is not None: - self.dst(d, old) - else: - raise Unsupported(op) - self.emit(f"OpBranch {lbl_end}") - self.emit(f"{lbl_end} = OpLabel") - - def cl(self, v): - """64-bit unsigned constant id (declared with the PhysicalStorageBuffer types).""" - v &= 0xFFFFFFFFFFFFFFFF - if v not in self.lconsts: - self.lconsts[v] = f"%cl{v:x}" - self.uses_psb = True - return self.lconsts[v] - - def local_index(self): - """LocalInvocationIndex of a compute or mesh shader invocation (thread i of its workgroup): the mesh shader - loads the built-in; a compute shader flattens LocalInvocationId with the group size from its header.""" - li = self.tmp() - if self.stage == "ms": - self.emit(f"{li} = OpLoad %uint %local_index") - return li - lid, x, y, z, lx, t1, t2 = (self.tmp() for _ in range(7)) - sx, sy, _ = self.cs["size"] - self.emit(f"{lid} = OpLoad %v3uint %local_id") - self.emit(f"{x} = OpCompositeExtract %uint {lid} 0") - self.emit(f"{y} = OpCompositeExtract %uint {lid} 1") - self.emit(f"{z} = OpCompositeExtract %uint {lid} 2") - self.emit(f"{t1} = OpIMul %uint {y} {self.cu(sx)}") - self.emit(f"{t2} = OpIMul %uint {z} {self.cu(sx * sy)}") - self.emit(f"{lx} = OpIAdd %uint {x} {t1}") - self.emit(f"{li} = OpIAdd %uint {lx} {t2}") - return li - - def subgroup_lane(self): - """This invocation's lane within its Vulkan subgroup (0..31 or 0..63).""" - self.uses_subgroup = True - r = self.tmp() - self.emit(f"{r} = OpLoad %uint %sg_lane") - return r - - @property - def wave32_fragment(self): - return self.stage == "ps" and not self.wave64 - - def wave_lane(self): - """This invocation's hardware lane within its wave. Compute and mesh shaders: LocalInvocationIndex mod the - wave size (exact: thread i of a group is wave i / W, lane i % W). Other stages: the subgroup lane; wave32 - pixel shaders use the lane within either 32-lane half.""" - lane = self.tmp() - if self.stage in ("cs", "ms"): - self.emit(f"{lane} = OpBitwiseAnd %uint {self.local_index()} {self.cu(63 if self.wave64 else 31)}") - else: - subgroup_lane = self.subgroup_lane() - if self.wave32_fragment: - self.emit(f"{lane} = OpBitwiseAnd %uint {subgroup_lane} {self.cu(31)}") - else: - self.emit(f"{lane} = OpCopyObject %uint {subgroup_lane}") - return lane - - def wave_source_lane(self, lane): - """Map a logical wave32 lane to this fragment invocation's physical subgroup lane.""" - if not self.wave32_fragment: - return lane - half, local, source = (self.tmp() for _ in range(3)) - subgroup_lane = self.subgroup_lane() - self.emit(f"{half} = OpBitwiseAnd %uint {subgroup_lane} {self.cu(32)}") - self.emit(f"{local} = OpBitwiseAnd %uint {lane} {self.cu(31)}") - self.emit(f"{source} = OpBitwiseOr %uint {half} {local}") - return source - - def wave32_ballot_word(self, ballot): - """Select this logical wave32's 32-bit word from a physical subgroup ballot.""" - lo, hi = self.tmp(), self.tmp() - half, upper, word = (self.tmp() for _ in range(3)) - self.emit(f"{lo} = OpCompositeExtract %uint {ballot} 0") - self.emit(f"{hi} = OpCompositeExtract %uint {ballot} 1") - lane = self.subgroup_lane() - self.emit(f"{half} = OpBitwiseAnd %uint {lane} {self.cu(32)}") - self.emit(f"{upper} = OpINotEqual %bool {half} {self.cu(0)}") - self.emit(f"{word} = OpSelect %uint {upper} {hi} {lo}") - return word - - def wave32_first_running_lane(self): - """The lowest running lane of this wave32 fragment's 32-lane half (0-31): the lane a uniform value is read - from. A fixed lane (0 of the half) need not be running: a quad with no covered sample, or helpers a driver - leaves out of subgroup operations, read as undefined (SHADER-1016).""" - ballot, any_, lsb, first = (self.tmp() for _ in range(4)) - self.emit(f"{ballot} = OpGroupNonUniformBallot %v4uint_bal {self.cu(3)} %true") - word = self.wave32_ballot_word(ballot) - # An empty word (a helper a driver leaves out of its own ballot) reads lane 0, as v_readfirstlane does, - # never FindILsb's 0xFFFFFFFF. - self.emit(f"{any_} = OpINotEqual %bool {word} {self.cu(0)}") - self.emit(f"{lsb} = OpExtInst %uint %glsl FindILsb {word}") - self.emit(f"{first} = OpSelect %uint {any_} {lsb} {self.cu(0)}") - self.uses_subgroup = self.uses_ballot = True - return first - - def ballot_lsb_by_words(self, bal): - """The lowest set bit of a subgroup ballot, from its four words with FindILsb: the lane - OpGroupNonUniformBallotFindLSB gives (a ballot has no bit at or above the subgroup size), without asking for - the subgroup size. MoltenVK lowers BallotFindLSB, like the SubgroupSize built-in, to Metal's - threads_per_simdgroup input, which a vertex function can't declare (Apple M4, MoltenVK 1.4.2), so vertex - shaders use this form. Like the op, the result means nothing for an empty ballot; callers select 0 then.""" - r = None - for k in (3, 2, 1, 0): # the lowest non-zero word wins, so it is selected last - w, lsb = self.tmp(), self.tmp() - self.emit(f"{w} = OpCompositeExtract %uint {bal} {k}") - self.emit(f"{lsb} = OpExtInst %uint %glsl FindILsb {w}") - if k: - at = self.tmp() - self.emit(f"{at} = OpIAdd %uint {lsb} {self.cu(32 * k)}") - lsb = at - if r is None: - r = lsb - else: - nz, pick = self.tmp(), self.tmp() - self.emit(f"{nz} = OpINotEqual %bool {w} {self.cu(0)}") - self.emit(f"{pick} = OpSelect %uint {nz} {lsb} {r}") - r = pick - return r - - # ---- wave64 emulation (--wave64-emulate) ---- - # A wave64 compute or mesh shader runs exact on any subgroup size. Each lane is one invocation as usual, but no - # subgroup operation is used: everything a lane needs from the rest of its wave goes through a Workgroup buffer - # (%x_buf). The shader runs in rounds (assemble: the emulated scheduler). In a round every wave that isn't done - # or waiting at s_barrier runs one segment of its program; then the whole workgroup meets at one OpControlBarrier - # in uniform control flow. A cross-lane operation ends a segment after its lane has written its share, and the - # code after it runs in the next round, when every lane of the wave has. Buffer layout, L = x_lanes: - # [0, 2L) per-lane data, double-buffered by round parity (written in round r, read in r + 1) - # [2L, 2L + 6W) two mask words per wave, ORed atomically, 3 slots by round mod 3 (W = waves) - # [2L + 6W, +6) per round slot: lanes not done, lanes neither done nor waiting at s_barrier - # last word a sink for the stores of lanes that have nothing to reset - def x_sizes(self): - w = self.x_lanes // 64 - mask = 2 * self.x_lanes - sched = mask + 6 * w - return w, mask, sched, sched + 6 - - def x_buf_bytes(self): - """Workgroup bytes of %x_buf: the wave64 exchange (emulate) or the barrier-round counts (bar_rounds).""" - if self.emulate: - return 4 * (self.x_sizes()[3] + 1) - return 12 if self.bar_rounds and not self.bar_counts_in_lds() else 0 - - def bar_counts_in_lds(self, lds_used=None): - """SHADER-579: whether the barrier rounds keep their count in a borrowed LDS word instead of %x_buf. Only - when the 12 bytes of %x_buf would take the total past 16384 B, the Vulkan minimum maxComputeSharedMemorySize: - a full 32 KiB LDS plus %x_buf is 32,780 B, over the 32,768 B of the AMD Windows and Intel drivers. Under - that, %x_buf fits on every device and costs no extra barriers (bar_scheduler). lds_used: before any code is - generated (fit_shared_memory), whether the shader will use its LDS is not known yet; assume it does.""" - used = self.uses_lds if lds_used is None else lds_used - return self.bar_rounds and used and 4 * self.lds_dwords + 12 > 16384 - - def fit_shared_memory(self): - """SHADER-309: a compute shader's Workgroup memory, the LDS array plus %x_buf, must fit in MAX_SHARED_BYTES - (#1721: RADV dies on a module 4 bytes over 64 KiB; the device's own limit is the runtime's check). Called before any code is generated. The LDS array is a - power of two at least the program's need; when that plus %x_buf is over the limit but the need still fits, - the array shrinks to the RSRC2 allocation and its accesses are bounds-checked (lds_access), as hardware checks - them. %x_buf is already sized to the workgroup, so when even the allocation does not fit, assemble refuses - the shader.""" - if not self.cs: - return - room = (MAX_SHARED_BYTES - (0 if self.bar_counts_in_lds(lds_used=True) else self.x_buf_bytes())) // 4 - if self.lds_bound is None and self.lds_dwords > room >= max(self.lds_declared, 1): - self.lds_dwords = self.lds_bound = self.lds_declared - self.cu(self.lds_declared) - - def x_split(self): - """End the current segment here: the rest of the block runs as a new segment in the next round.""" - seg = self.x_seg - self.x_seg += 1 - self.emit(f"OpStore %pc {self.cu(seg)}") - self.x_marks.append((len(self.body), seg)) - self.desc_cache.clear() - self.sgpr_imm.clear() - self._active_ssa = None - self.block_label = f"%blk{seg}" - self.x_dirty = set() - - def x_word(self, idx): - p, v = self.tmp(), self.tmp() - self.emit(f"{p} = OpAccessChain %_ptr_WG_uint_x %x_buf {idx}") - self.emit(f"{v} = OpLoad %uint {p}") - return v - - def x_mask_slot(self, it): - """Index of the wave's first mask word in the slot of round `it`.""" - s, a, b, c = (self.tmp() for _ in range(4)) - w, mask, _, _ = self.x_sizes() - self.emit(f"{s} = OpUMod %uint {it} {self.cu(3)}") - self.emit(f"{a} = OpIMul %uint {s} {self.cu(w)}") - self.emit(f"{b} = OpIAdd %uint {a} %x_wave") - self.emit(f"{c} = OpIMul %uint {b} {self.cu(2)}") - r = self.tmp() - self.emit(f"{r} = OpIAdd %uint {c} {self.cu(mask)}") - return r - - def x_order_barrier(self): - """Order pending memory/LDS accesses across both halves of an emulated wave64.""" - if self.emulate_inline: - self.emit(f"OpControlBarrier {self.cu(2)} {self.cu(2)} {self.cu(0x948)}") - self.x_dirty = set() - else: - self.x_split() - - def _ensure_x_pre_fn(self, kind): - """Build (once per module) the barrier-free helper OpFunction for an inline wave64 x_round pre-barrier step. - - Outlines the ~20-30 instructions of ring-buffer slot clearing (`sn = (it + 1) % 3`), mask/data slot indexing, - and pre-barrier %x_buf store/OpAtomicOr out of %main while keeping OpControlBarrier directly at the callsite - in %main. Returns the helper function's SPIR-V id (`%x_pre_vote_fn`, `%x_pre_mask_fn`, or `%x_pre_data_fn`). - """ - fn_name = f"%x_pre_{kind}_fn" - if kind in self.x_round_fns: - return fn_name - w, mask, sched, sink = self.x_sizes() - tail_params = {"vote": ["val"], "data": ["val"], "mask": ["b0", "b1"], "both": ["val", "b0", "b1"]}[kind] - if w == 1: - p_names = ["it", "li"] + tail_params - else: - p_names = ["it", "li", "lane", "wave"] + tail_params - arity = len(p_names) - fn_type = self.x_round_fn_types.setdefault(arity, f"%fn_x_pre{arity}") - params = {k: f"%xp_{kind}_{k}" for k in p_names} - p_it, p_li = params["it"], params["li"] - saved, self.body = self.body, [] - n1, sn = self.tmp(), self.tmp() - self.emit(f"{n1} = OpIAdd %uint {p_it} {self.cu(1)}") - self.emit(f"{sn} = OpUMod %uint {n1} {self.cu(3)}") - if w == 1: - m2, m3, m4, ml, m5, m6, mp5, mp6 = (self.tmp() for _ in range(8)) - self.emit(f"{m2} = OpIMul %uint {sn} {self.cu(2)}") - self.emit(f"{m3} = OpIAdd %uint {m2} {self.cu(mask)}") - self.emit(f"{m4} = OpIAdd %uint {m3} {self.cu(1)}") - self.emit(f"{ml} = OpIEqual %bool {p_li} {self.cu(0)}") - self.emit(f"{m5} = OpSelect %uint {ml} {m3} {self.cu(sink)}") - self.emit(f"{m6} = OpSelect %uint {ml} {m4} {self.cu(sink)}") - self.emit(f"{mp5} = OpAccessChain %_ptr_WG_uint_x %x_buf {m5}") - self.emit(f"OpStore {mp5} {self.cu(0)}") - self.emit(f"{mp6} = OpAccessChain %_ptr_WG_uint_x %x_buf {m6}") - self.emit(f"OpStore {mp6} {self.cu(0)}") - else: - p_lane, p_wave = params["lane"], params["wave"] - m0, m1, m2, m3, m4, ml, m5, m6, mp5, mp6 = (self.tmp() for _ in range(10)) - self.emit(f"{m0} = OpIMul %uint {sn} {self.cu(w)}") - self.emit(f"{m1} = OpIAdd %uint {m0} {p_wave}") - self.emit(f"{m2} = OpIMul %uint {m1} {self.cu(2)}") - self.emit(f"{m3} = OpIAdd %uint {m2} {self.cu(mask)}") - self.emit(f"{m4} = OpIAdd %uint {m3} {self.cu(1)}") - self.emit(f"{ml} = OpIEqual %bool {p_lane} {self.cu(0)}") - self.emit(f"{m5} = OpSelect %uint {ml} {m3} {self.cu(sink)}") - self.emit(f"{m6} = OpSelect %uint {ml} {m4} {self.cu(sink)}") - self.emit(f"{mp5} = OpAccessChain %_ptr_WG_uint_x %x_buf {m5}") - self.emit(f"OpStore {mp5} {self.cu(0)}") - self.emit(f"{mp6} = OpAccessChain %_ptr_WG_uint_x %x_buf {m6}") - self.emit(f"OpStore {mp6} {self.cu(0)}") - q0, q1, q2, ql, q3, q4, qp3, qp4 = (self.tmp() for _ in range(8)) - self.emit(f"{q0} = OpIMul %uint {sn} {self.cu(2)}") - self.emit(f"{q1} = OpIAdd %uint {q0} {self.cu(sched)}") - self.emit(f"{q2} = OpIAdd %uint {q1} {self.cu(1)}") - self.emit(f"{ql} = OpIEqual %bool {p_li} {self.cu(0)}") - self.emit(f"{q3} = OpSelect %uint {ql} {q1} {self.cu(sink)}") - self.emit(f"{q4} = OpSelect %uint {ql} {q2} {self.cu(sink)}") - self.emit(f"{qp3} = OpAccessChain %_ptr_WG_uint_x %x_buf {q3}") - self.emit(f"OpStore {qp3} {self.cu(0)}") - self.emit(f"{qp4} = OpAccessChain %_ptr_WG_uint_x %x_buf {q4}") - self.emit(f"OpStore {qp4} {self.cu(0)}") - if kind in ("data", "both"): - par, data_base, i, p = (self.tmp() for _ in range(4)) - self.emit(f"{par} = OpBitwiseAnd %uint {p_it} {self.cu(1)}") - self.emit(f"{data_base} = OpIMul %uint {par} {self.cu(self.x_lanes)}") - self.emit(f"{i} = OpIAdd %uint {data_base} {p_li}") - self.emit(f"{p} = OpAccessChain %_ptr_WG_uint_x %x_buf {i}") - self.emit(f"OpStore {p} {params['val']}") - ret_id = data_base - if kind in ("vote", "mask", "both"): - if w == 1: - s, c, rm = self.tmp(), self.tmp(), self.tmp() - self.emit(f"{s} = OpUMod %uint {p_it} {self.cu(3)}") - self.emit(f"{c} = OpIMul %uint {s} {self.cu(2)}") - self.emit(f"{rm} = OpIAdd %uint {c} {self.cu(mask)}") - else: - s, a, b, c, rm = (self.tmp() for _ in range(5)) - self.emit(f"{s} = OpUMod %uint {p_it} {self.cu(3)}") - self.emit(f"{a} = OpIMul %uint {s} {self.cu(w)}") - self.emit(f"{b} = OpIAdd %uint {a} {params['wave']}") - self.emit(f"{c} = OpIMul %uint {b} {self.cu(2)}") - self.emit(f"{rm} = OpIAdd %uint {c} {self.cu(mask)}") - p0, old0 = self.tmp(), self.tmp() - self.emit(f"{p0} = OpAccessChain %_ptr_WG_uint_x %x_buf {rm}") - self.emit(f"{old0} = OpAtomicOr %uint {p0} {self.cu(2)} {self.cu(0)} {params['b0' if kind in ('mask', 'both') else 'val']}") - if kind in ("mask", "both"): - rm1, p1, old1 = self.tmp(), self.tmp(), self.tmp() - self.emit(f"{rm1} = OpIAdd %uint {rm} {self.cu(1)}") - self.emit(f"{p1} = OpAccessChain %_ptr_WG_uint_x %x_buf {rm1}") - self.emit(f"{old1} = OpAtomicOr %uint {p1} {self.cu(2)} {self.cu(0)} {params['b1']}") - ret_id = rm - lines, self.body = self.body, saved - self.x_round_fns[kind] = ( - [f"{fn_name} = OpFunction %uint None {fn_type}"] + - [f"{params[k]} = OpFunctionParameter %uint" for k in p_names] + - [f"{fn_name}_entry = OpLabel"] + - lines + - [f" OpReturnValue {ret_id}", "OpFunctionEnd"] - ) - return fn_name - - def x_round(self, data=None, bits=None): - """One exchange: this lane's uint `data` goes to its slot, `bits` (lo, hi; None = nothing) are ORed into - the wave's two mask words. Returns (read, (lo, hi)): read(lane) loads `data` of a lane (0-63) of this wave, - and (lo, hi) is the OR over all 64 lanes. In round-loop mode both are valid in the next segment; in - inline structured mode (`emulate_inline`) the barrier runs directly in place with zero x_split.""" - if self.emulate_inline: - w, _, _, _ = self.x_sizes() - it, n1 = self.tmp(), self.tmp() - self.emit(f"{it} = OpLoad %uint %x_it") - if data is not None and bits is None: - fn = self._ensure_x_pre_fn("data") - args = f"{it} %x_li {data}" if w == 1 else f"{it} %x_li %x_lane %x_wave {data}" - data_base = self.tmp() - self.emit(f"{data_base} = OpFunctionCall %uint {fn} {args}") - self.emit(f"OpControlBarrier {self.cu(2)} {self.cu(2)} {self.cu(0x948)}") - self.emit(f"{n1} = OpIAdd %uint {it} {self.cu(1)}") - self.emit(f"OpStore %x_it {n1}") - self.x_dirty = set() - - def read(lane): - if w == 1: - j = self.tmp() - self.emit(f"{j} = OpIAdd %uint {data_base} {lane}") - return self.x_word(j) - i, j = self.tmp(), self.tmp() - self.emit(f"{i} = OpIAdd %uint {data_base} %x_wbase") - self.emit(f"{j} = OpIAdd %uint {i} {lane}") - return self.x_word(j) - return read, None - if data is None and bits is not None and bits[0] is not None and bits[1] is None: - fn = self._ensure_x_pre_fn("vote") - args = f"{it} %x_li {bits[0]}" if w == 1 else f"{it} %x_li %x_lane %x_wave {bits[0]}" - rm = self.tmp() - self.emit(f"{rm} = OpFunctionCall %uint {fn} {args}") - self.emit(f"OpControlBarrier {self.cu(2)} {self.cu(2)} {self.cu(0x948)}") - self.emit(f"{n1} = OpIAdd %uint {it} {self.cu(1)}") - self.emit(f"OpStore %x_it {n1}") - self.x_dirty = set() - return None, (self.x_word(rm), None) - if data is None and bits is not None: - fn = self._ensure_x_pre_fn("mask") - b0 = bits[0] if bits[0] is not None else self.cu(0) - b1 = bits[1] if bits[1] is not None else self.cu(0) - args = f"{it} %x_li {b0} {b1}" if w == 1 else f"{it} %x_li %x_lane %x_wave {b0} {b1}" - rm, hi_i = self.tmp(), self.tmp() - self.emit(f"{rm} = OpFunctionCall %uint {fn} {args}") - self.emit(f"OpControlBarrier {self.cu(2)} {self.cu(2)} {self.cu(0x948)}") - self.emit(f"{n1} = OpIAdd %uint {it} {self.cu(1)}") - self.emit(f"OpStore %x_it {n1}") - self.x_dirty = set() - self.emit(f"{hi_i} = OpIAdd %uint {rm} {self.cu(1)}") - return None, (self.x_word(rm), self.x_word(hi_i)) - fn = self._ensure_x_pre_fn("both") - b0 = bits[0] if bits[0] is not None else self.cu(0) - b1 = bits[1] if bits[1] is not None else self.cu(0) - args = f"{it} %x_li {data} {b0} {b1}" if w == 1 else f"{it} %x_li %x_lane %x_wave {data} {b0} {b1}" - rm, hi_i = self.tmp(), self.tmp() - self.emit(f"{rm} = OpFunctionCall %uint {fn} {args}") - self.emit(f"OpControlBarrier {self.cu(2)} {self.cu(2)} {self.cu(0x948)}") - self.emit(f"{n1} = OpIAdd %uint {it} {self.cu(1)}") - self.emit(f"OpStore %x_it {n1}") - self.x_dirty = set() - self.emit(f"{hi_i} = OpIAdd %uint {rm} {self.cu(1)}") - res = (self.x_word(rm), self.x_word(hi_i)) - - def read(lane): - par2, base = self.tmp(), self.tmp() - self.emit(f"{par2} = OpBitwiseAnd %uint {it} {self.cu(1)}") - self.emit(f"{base} = OpIMul %uint {par2} {self.cu(self.x_lanes)}") - if w == 1: - j = self.tmp() - self.emit(f"{j} = OpIAdd %uint {base} {lane}") - return self.x_word(j) - i, j = self.tmp(), self.tmp() - self.emit(f"{i} = OpIAdd %uint {base} %x_wbase") - self.emit(f"{j} = OpIAdd %uint {i} {lane}") - return self.x_word(j) - return read, res - it = self.tmp() - self.emit(f"{it} = OpLoad %uint %x_it") - if data is not None: - par, base, i, p = (self.tmp() for _ in range(4)) - self.emit(f"{par} = OpBitwiseAnd %uint {it} {self.cu(1)}") - self.emit(f"{base} = OpIMul %uint {par} {self.cu(self.x_lanes)}") - self.emit(f"{i} = OpIAdd %uint {base} %x_li") - self.emit(f"{p} = OpAccessChain %_ptr_WG_uint_x %x_buf {i}") - self.emit(f"OpStore {p} {data}") - if bits is not None: - m = self.x_mask_slot(it) - for k, b in enumerate(bits): - if b is None: - continue - i, p, old = self.tmp(), self.tmp(), self.tmp() - self.emit(f"{i} = OpIAdd %uint {m} {self.cu(k)}") - self.emit(f"{p} = OpAccessChain %_ptr_WG_uint_x %x_buf {i}") - self.emit(f"{old} = OpAtomicOr %uint {p} {self.cu(2)} {self.cu(0)} {b}") - self.x_split() - now, prev = self.tmp(), self.tmp() - self.emit(f"{now} = OpLoad %uint %x_it") - self.emit(f"{prev} = OpISub %uint {now} {self.cu(1)}") - res = None - if bits is not None: - m = self.x_mask_slot(prev) - hi_i = self.tmp() - self.emit(f"{hi_i} = OpIAdd %uint {m} {self.cu(1)}") - res = (self.x_word(m), self.x_word(hi_i)) - - def read(lane): - par, base, i = self.tmp(), self.tmp(), self.tmp() - self.emit(f"{par} = OpBitwiseAnd %uint {prev} {self.cu(1)}") - self.emit(f"{base} = OpIMul %uint {par} {self.cu(self.x_lanes)}") - self.emit(f"{i} = OpIAdd %uint {base} %x_wbase") - j = self.tmp() - self.emit(f"{j} = OpIAdd %uint {i} {lane}") - return self.x_word(j) - return read, res - - def x_memory_order(self, op): - """On hardware a wave's lanes run each instruction together: every lane's access of one instruction comes - before every lane's access of the next. Two halves of an emulated wave can be in different subgroups, so an - access that conflicts with an earlier one of the same segment (read after write, write after read, write - after write, on the same memory) waits for the next round, whose barrier orders the memory. A scalar load - (s_load / s_buffer_load) is a read of the same memory as the vector ops: on hardware every lane's earlier - store is done before the wave issues it, but here the other half could load before this half has stored - (#1587: valu_fuzz --family mem --emulate, lanes 32-63 read the fill pattern). Not ordered: sampling an - image the wave wrote.""" - if op in ("ds_swizzle_b32", "ds_bpermute_b32", "ds_permute_b32", "ds_nop"): - return - if op.startswith("ds_"): - kind = "lds" - elif op.startswith(("buffer_", "tbuffer_", "global_", "flat_", "image_load", "image_store", "image_atomic", - "s_load_", "s_buffer_load_")): - kind = "mem" - else: - return - store = "store" in op or op.startswith("ds_write") - reads = not store - writes = store or "atomic" in op or (kind == "lds" and not op.startswith("ds_read")) - if (kind, "w") in self.x_dirty or (writes and (kind, "r") in self.x_dirty): - self.x_order_barrier() - if reads: - self.x_dirty.add((kind, "r")) - if writes: - self.x_dirty.add((kind, "w")) - - def g_vote(self, r, kind, b): - """r = OpGroupNonUniform{Any,All} of bool b over the wave.""" - if not self.emulate: - if self.wave32_fragment: - if kind == "All": - inv = self.tmp() - self.emit(f"{inv} = OpLogicalNot %bool {b}") - b = inv - ballot, any_ = self.tmp(), self.tmp() - self.emit(f"{ballot} = OpGroupNonUniformBallot %v4uint_bal {self.cu(3)} {b}") - word = self.wave32_ballot_word(ballot) - self.emit(f"{any_} = OpINotEqual %bool {word} {self.cu(0)}") - if kind == "Any": - self.emit(f"{r} = OpCopyObject %bool {any_}") - else: - self.emit(f"{r} = OpLogicalNot %bool {any_}") - self.uses_subgroup = self.uses_ballot = True - return - self.emit(f"{r} = OpGroupNonUniform{kind} %bool {self.cu(3)} {b}") - return - if kind == "All": - nb = self.tmp() - self.emit(f"{nb} = OpLogicalNot %bool {b}") - b = nb - bit = self.tmp() - self.emit(f"{bit} = OpSelect %uint {b} {self.cu(1)} {self.cu(0)}") - lo = self.x_round(bits=(bit, None))[1][0] - self.emit(f"{r} = {'OpIEqual' if kind == 'All' else 'OpINotEqual'} %bool {lo} {self.cu(0)}") - - def g_shuffle(self, r, v, src): - """r = v of lane src of this wave (OpGroupNonUniformShuffle, or any emulated lane 0-63).""" - if not self.emulate: - self.emit(f"{r} = OpGroupNonUniformShuffle %uint %c3 {v} {self.wave_source_lane(src)}") - return - read = self.x_round(data=v)[0] - self.emit(f"{r} = OpCopyObject %uint {read(src)}") - - def ds_lane_read(self, dst: dict, data: str, src: str, lane: str) -> None: - """DS swizzle and backward permute read zero from an inactive or absent source lane.""" - value, result = self.tmp(), self.tmp() - self.emit(f"{value} = OpSelect %uint {self.active_b()} {data} {self.cu(0)}") - if self.emulate: - self.g_shuffle(result, value, src) - else: - # Redirect absent source lanes before the shuffle: even a masked undefined result is undefined. - ballot, present, safe_src, shuffled, mask = (self.tmp() for _ in range(5)) - physical_src = self.wave_source_lane(src) - self.emit(f"{ballot} = OpGroupNonUniformBallot %v4uint_bal %c3 %true") - self.emit(f"{present} = OpGroupNonUniformBallotBitExtract %bool %c3 {ballot} {physical_src}") - self.emit(f"{safe_src} = OpSelect %uint {present} {src} {lane}") - self.emit(f"{shuffled} = OpGroupNonUniformShuffle %uint %c3 {value} {self.wave_source_lane(safe_src)}") - self.emit(f"{mask} = OpSelect %uint {present} {self.cu(0xFFFFFFFF)} {self.cu(0)}") - self.emit(f"{result} = OpBitwiseAnd %uint {shuffled} {mask}") - self.uses_subgroup = self.uses_ballot = True - # Bitwise masks keep MSL from placing the ballot and shuffle in a short-circuiting ternary. - self.dst(dst, result, eager=not self.emulate) - - def ds_permute(self, a, mods): - """ds_permute_b32 vD, vAddr, vData offset:N, the forward (scatter) permute: every source lane that is on in - EXEC sends vData to lane ((vAddr + offset) / 4) mod 32 of its own half (as ds_bpermute_b32, RDNA ISA - 10.4.4: a wave64 runs it as two wave32s); a destination lane nobody sends to gets 0; EXEC gates only the - destination write. Several sources to one lane: the highest-numbered source wins (ISA: "the final value is - not predictable but will be the value from one of the writers"). Vulkan has no subgroup scatter, so each - destination lane scans the 32 source lanes of its half in order and keeps the last one that targets it. - Each source lane publishes its target plus one (0 = off in EXEC, so a lane that doesn't exist in a partial - wave reads as "no target" as well).""" - d, ad, dat = a[0], self.src_u(a[1]), self.src_u(a[2]) - off = self.mod_int(mods, "offset", 0) - s1, sh, dl, dp, tp = (self.tmp() for _ in range(5)) - self.emit(f"{s1} = OpIAdd %uint {ad} {self.cu(off)}") - self.emit(f"{sh} = OpShiftRightLogical %uint {s1} {self.cu(2)}") - self.emit(f"{dl} = OpBitwiseAnd %uint {sh} {self.cu(31)}") - self.emit(f"{dp} = OpIAdd %uint {dl} {self.cu(1)}") - self.emit(f"{tp} = OpSelect %uint {self.active_b()} {dp} {self.cu(0)}") - if self.emulate: - # Round 1 publishes the targets; the next segment finds each lane's winning source and parks it in - # %x_perm; round 2 publishes the data; the segment after that reads the winner's data. - self.uses_perm = True - read = self.x_round(data=tp)[0] - lane, rl, mine, half, win = (self.tmp() for _ in range(5)) - self.emit(f"{lane} = OpCopyObject %uint {self.wave_lane()}") - self.emit(f"{rl} = OpBitwiseAnd %uint {lane} {self.cu(31)}") - self.emit(f"{mine} = OpIAdd %uint {rl} {self.cu(1)}") - self.emit(f"{half} = OpBitwiseAnd %uint {lane} {self.cu(32)}") - acc = self.cu(32) - for j in range(32): - src, v, hit, nxt = (self.tmp() for _ in range(4)) - self.emit(f"{src} = OpBitwiseOr %uint {half} {self.cu(j)}") - self.emit(f"{v} = OpCopyObject %uint {read(src)}") - self.emit(f"{hit} = OpIEqual %bool {v} {mine}") - self.emit(f"{nxt} = OpSelect %uint {hit} {self.cu(j)} {acc}") - acc = nxt - self.emit(f"OpStore %x_perm {acc}") - dat2 = self.src_u(a[2]) - read2 = self.x_round(data=dat2)[0] - w, ok, half2, src, got, r, lane2 = (self.tmp() for _ in range(7)) - self.emit(f"{w} = OpLoad %uint %x_perm") - self.emit(f"{ok} = OpULessThan %bool {w} {self.cu(32)}") - self.emit(f"{lane2} = OpCopyObject %uint {self.wave_lane()}") - self.emit(f"{half2} = OpBitwiseAnd %uint {lane2} {self.cu(32)}") - wc = self.tmp() - self.emit(f"{wc} = OpBitwiseAnd %uint {w} {self.cu(31)}") - self.emit(f"{src} = OpBitwiseOr %uint {half2} {wc}") - self.emit(f"{got} = OpCopyObject %uint {read2(src)}") - self.emit(f"{r} = OpSelect %uint {ok} {got} {self.cu(0)}") - self.dst(d, r) - return - self.uses_subgroup = self.uses_ballot = True - lane, rl, mine, half = (self.tmp() for _ in range(4)) - self.emit(f"{lane} = OpCopyObject %uint {self.wave_lane()}") - self.emit(f"{rl} = OpBitwiseAnd %uint {lane} {self.cu(31)}") - self.emit(f"{mine} = OpIAdd %uint {rl} {self.cu(1)}") - if self.wave64 or self.wave32_fragment: - sgl = self.tmp() - self.emit(f"{sgl} = OpLoad %uint %sg_lane") - self.emit(f"{half} = OpBitwiseAnd %uint {sgl} {self.cu(32)}") - bal = self.tmp() - self.emit(f"{bal} = OpGroupNonUniformBallot %v4uint_bal %c3 %true") - acc = self.cu(0) - for j in range(32): - src = self.cu(j) - if self.wave64 or self.wave32_fragment: - src = self.tmp() - self.emit(f"{src} = OpBitwiseOr %uint {half} {self.cu(j)}") - ex, shv, v, shd, hit, nxt = (self.tmp() for _ in range(6)) - # a shuffle from a lane that isn't running (the missing lanes of a partial wave) is undefined - self.emit(f"{ex} = OpGroupNonUniformBallotBitExtract %bool %c3 {bal} {src}") - self.emit(f"{shv} = OpGroupNonUniformShuffle %uint %c3 {tp} {src}") - self.emit(f"{v} = OpSelect %uint {ex} {shv} {self.cu(0)}") - self.emit(f"{shd} = OpGroupNonUniformShuffle %uint %c3 {dat} {src}") - self.emit(f"{hit} = OpIEqual %bool {v} {mine}") - self.emit(f"{nxt} = OpSelect %uint {hit} {shd} {acc}") - acc = nxt - self.dst(d, acc) - - def sub_lane(self, r): - """r = the lane the subgroup shuffles above index: the subgroup lane, or the wave lane when emulated.""" - if self.emulate or self.wave32_fragment: - self.emit(f"{r} = OpCopyObject %uint {self.wave_lane()}") - else: - self.emit(f"{r} = OpLoad %uint %sg_lane") - - def exec_half_write(self, half, val, const=None): - """Write one 32-bit half of EXEC. In the per-lane model a lane is active iff its bit is set. A constant - sets each lane from its own bit; a register value (mask representation: all-ones / zero per lane) sets - the lanes of that half from their own copy. Lanes of the other half are unchanged.""" - lane = self.wave_lane() - rel, inh, bit, on, cur, new = (self.tmp() for _ in range(6)) - if half == 0: - self.emit(f"{inh} = OpULessThan %bool {lane} {self.cu(32)}") - self.emit(f"{rel} = OpCopyObject %uint {lane}") - else: - self.emit(f"{inh} = OpUGreaterThanEqual %bool {lane} {self.cu(32)}") - self.emit(f"{rel} = OpISub %uint {lane} {self.cu(32)}") - if const is not None: - r31 = self.tmp() - self.emit(f"{r31} = OpBitwiseAnd %uint {rel} {self.cu(31)}") - # Shift and mask, not OpBitFieldUExtract: Intel's Windows driver (UHD 770 / Xe-LP, 32.0.101.6129; - # also seen on Xe-LPG) extracts from a constant that fits in 16 bits with the offset taken mod 16, so - # exec_lo = 0xffff turned on all 32 lanes. GPU-checked with cs_exec_const.asm. - shr = self.tmp() - self.emit(f"{shr} = OpShiftRightLogical %uint {self.cu(const & 0xFFFFFFFF)} {r31}") - self.emit(f"{bit} = OpBitwiseAnd %uint {shr} {self.cu(1)}") - self.emit(f"{on} = OpINotEqual %bool {bit} {self.cu(0)}") - else: - self.emit(f"{on} = OpINotEqual %bool {val} {self.cu(0)}") - self.emit(f"{cur} = OpLoad %bool %active") - self.emit(f"{new} = OpSelect %bool {inh} {on} {cur}") - self.emit(f"OpStore %active {new}") - self.uses_active = True - - def set_scc(self, b): - """SCC = bool id (1/0).""" - r = self.tmp() - self.emit(f"{r} = OpSelect %uint {b} {self.cu(1)} {self.cu(0)}") - self.emit(f"OpStore %scc {r}") - - def scc_nonzero(self, v): - self.set_scc(self.tmp_bool_nz(v)) - - def scc_add_overflow(self, x, y, r, sub=False): - """Signed overflow of r = x + y (or x - y): SCC for s_add_i32 / s_sub_i32 / s_addk_i32.""" - a1, a2, m, sh = self.tmp(), self.tmp(), self.tmp(), self.tmp() - if sub: - self.emit(f"{a1} = OpBitwiseXor %uint {x} {y}") - self.emit(f"{a2} = OpBitwiseXor %uint {x} {r}") - else: - self.emit(f"{a1} = OpBitwiseXor %uint {x} {r}") - self.emit(f"{a2} = OpBitwiseXor %uint {y} {r}") - self.emit(f"{m} = OpBitwiseAnd %uint {a1} {a2}") - self.emit(f"{sh} = OpShiftRightLogical %uint {m} {self.cu(31)}") - self.scc_nonzero(sh) - - def bfe_width(self, off, wid): - """A bitfield-extract width cut to 32 - off (off in 0-31): SPIR-V leaves offset + count > 32 undefined. The - field then runs to bit 31: gfx1150 hardware does this for s_bfe (4000 random control words, salu_diff - --oracle hw), and LLVM's v_bfe fold (constantFoldBFE in AMDGPUISelLowering.cpp, 5-bit width) is analogous: - Src0 >> Offset, logical for the unsigned and arithmetic for the signed extract. On RDNA2 v_bfe_u32/v_bfe_i32 - do the same (gfx1036, wave32 and wave64, tools/int_hw_probe.py group valu_bfe_past31), and s_bfe too (gfx1035, - SHADER-137).""" - room, fits, w = self.tmp(), self.tmp(), self.tmp() - self.emit(f"{room} = OpISub %uint {self.cu(32)} {off}") - self.emit(f"{fits} = OpULessThan %bool {wid} {room}") - self.emit(f"{w} = OpSelect %uint {fits} {wid} {room}") - return w - - def tmp_bool_nz(self, v): - b = self.tmp() - self.emit(f"{b} = OpINotEqual %bool {v} {self.cu(0)}") - return b - - def scc_from_mask(self, v): - """SCC after a lane-mask instruction: 1 if the wave's mask is non-zero. One invocation holds one lane's - bit, so that is a vote across the subgroup, as for s_cbranch_vccz. Taken per lane, the lanes of one wave - could follow different s_cbranch_scc paths, which a hardware wave never does: it has one SCC.""" - if not self.cur_scc_live: - return - any_, z = self.tmp(), self.tmp() - self.g_vote(any_, "Any", self.tmp_bool_nz(v)) - self.uses_vote = True - self.emit(f"{z} = OpSelect %uint {any_} {self.cu(1)} {self.cu(0)}") - self.emit(f"OpStore %scc {z}") - - MASK_SOP2_B32 = ("s_and_b32", "s_or_b32", "s_xor_b32", "s_andn2_b32", "s_orn2_b32", "s_nand_b32", "s_nor_b32", - "s_xnor_b32", "s_cselect_b32") - - @staticmethod - def _maskable_b32(x): - return x["k"] in ("sgpr", "imm") or ( - x["k"] == "special" and (x.get("t", "").startswith(("exec", "vcc")) or x.get("t") == "null") - ) - - def _mask_b32_dst_half(self, d, srcs): - """For a 32-bit bitwise SALU op (s_not_b32 / MASK_SOP2_B32), return (to_mask_dst, half) where to_mask_dst - is True when d is EXEC or VCC (each lane holds its own bit) and half is 'lo'/'hi' in wave64 or None.""" - if d["k"] != "special": - return False, None - t = d.get("t", "") - if not self.wave64: - return t in ("exec_lo", "vcc_lo", "exec", "vcc"), None - if t in ("exec_lo", "exec_hi"): - return True, "hi" if t == "exec_hi" else "lo" - if t in ("vcc_lo", "vcc_hi") and ("vcc" in self.cur_masks or any(self.holds_lane_mask(s) for s in srcs)): - return True, "hi" if t == "vcc_hi" else "lo" - return False, None - - def _mask_b32_src(self, s, dst_half): - """Read one 32-bit source for a mask-writing bitwise SALU op (wave32, or wave64 half `dst_half`).""" - if self.wave64 and dst_half is not None and self.holds_lane_mask(s): - sh = self.mask_half(s) - if sh is not None and sh != dst_half: - # Opposite wave64 half (e.g. exec_lo <- vcc_hi): collect that half's 32-bit mask and take bit lane&31. - lo, hi = self.wave_mask(s) - word = hi if sh == "hi" else lo - lane = self.wave_lane() - s5, shr, bit, r = (self.tmp() for _ in range(4)) - self.emit(f"{s5} = OpBitwiseAnd %uint {lane} {self.cu(31)}") - self.emit(f"{shr} = OpShiftRightLogical %uint {word} {s5}") - self.emit(f"{bit} = OpBitwiseAnd %uint {shr} {self.cu(1)}") - self.emit(f"{r} = OpSelect %uint {self.tmp_bool_nz(bit)} {self.cu(0xFFFFFFFF)} {self.cu(0)}") - return r - return self.mask_src(s, wide=False) - - def _store_b32_mask_dst(self, d, val, to_mask_dst, dst_half): - """Store a 32-bit bitwise SALU result, preserving the untouched half of EXEC/VCC in wave64.""" - if to_mask_dst and self.wave64 and d["k"] == "special" and d.get("t") in ("vcc_lo", "vcc_hi"): - self.put_mask(d, val, dst_half) - if d["t"] == "vcc_hi": - self.emit(f"OpStore %vcc_hi {val}") - return - self.dst(d, val) - - def sop2_b32_srcs(self, op, a): - """The two sources of a 32-bit SOP2. A bitwise op (or s_cselect) that writes EXEC / VCC reads both through - _mask_b32_src / mask_src (in wave32 and on either half of a wave64 mask), so a constant, inline or held in - an SGPR, gives each lane its own bit; a mask is read as before. Until 2026-11-22 a constant was used whole: - `s_and_b32 exec_lo, exec_lo, 0xff00` (or the same constant in an SGPR) left every lane of EXEC on. An SGPR - destination stays a data read, because lane_masks.py classifies it as data when the other operand is a - constant (s_and_b32 s20, exec_lo, 1; s_bcnt1_i32_b32 s21, s20 gave 32 and 0 instead of 1, #1792).""" - if op in self.MASK_SOP2_B32 and len(a) >= 3: - to_mask, dst_half = self._mask_b32_dst_half(a[0], a[1:3]) - if to_mask and all(self._maskable_b32(x) for x in a[1:3]): - return self._mask_b32_src(a[1], dst_half), self._mask_b32_src(a[2], dst_half) - return self.src_u(a[1]), self.src_u(a[2]) - - def scc_logic(self, a, r): - """SCC of a 32-bit bitwise SALU op (s_not_b32 and s_and/or/xor/andn2/orn2/nand/nor/xnor_b32): D != 0. - When the op works on a lane mask (writes EXEC/VCC or reads a lane-mask operand), D is the wave's mask - (or one 32-lane half of it in wave64), so SCC is a subgroup Any vote over the wave (wave32) or that half - (wave64, scc_any_half) rather than this lane's own bit.""" - srcs = a[1:] - to_mask_dst, dst_half = self._mask_b32_dst_half(a[0], srcs) - mask_srcs = [s for s in srcs if self.holds_lane_mask(s)] - if to_mask_dst: - self.scc_any_half(r, dst_half) - elif mask_srcs: - if not self.wave64: - self.scc_from_mask(r) - else: - halves = {self.mask_half(s) for s in mask_srcs} - {None} - if len(halves) == 1: - self.scc_any_half(r, halves.pop()) - elif not halves: - self.scc_from_mask(r) - else: - self.scc_nonzero(r) - else: - self.scc_nonzero(r) - - SGPRS = 128 # size of the %sgpr array without the parking slots - - def park_masks(self, blocks): - """Run the lane-mask analysis and give every VGPR lane a mask is fetched back from a slot of its own, - after the real registers in the %sgpr array (the array grows by as many).""" - self.lane_masks, self.mask_writes, self.lane_either = lane_masks.analyse(*blocks, include_either=True, - wave64=self.wave64) - # lane_masks merges a mask on one path with plain data on another by dropping the register, - # so "not in cur_masks" does not prove it is data on every path. Keep a conservative set. - self.ever_mask = {r for m in self.lane_masks.values() for r in m if isinstance(r, int)} - slots = lane_masks.parked(blocks[0], self.lane_masks) - self.parked = {slot: self.SGPRS + i for i, slot in enumerate(slots)} - - def mask_half(self, a): - """For a 32-bit lane-mask operand in wave64, return 'lo' (lanes 0-31), 'hi' (lanes 32-63), or None.""" - if not self.wave64: - return None - if a["k"] == "special": - t = a.get("t", "") - if t in ("exec_lo", "vcc_lo"): - return "lo" - if t in ("exec_hi", "vcc_hi"): - return "hi" - return None - if a["k"] == "sgpr" and a.get("n", 1) == 1: - k = self.cur_masks.get(a["r"]) - if k == lane_masks.MASK_LO: - return "lo" - if k == lane_masks.MASK_HI: - return "hi" - return None - - def lane_mask_word(self, a): - """The 32-bit word of the lane mask in `a` as real bits, for a b32 scalar op that reads it as a number - (s_flbit_i32_b32 of vcc_lo): the whole wave's lanes 0-31, or for the high half of a wave64 mask lanes - 32-63. A register holds only this lane's 0 / ~0, so reading it as data gave every lane its own answer.""" - lo, hi = self.wave_mask(a) - if self.wave64: - half = self.mask_half(a) - if half is not None: - return hi if half == "hi" else lo - return lo - - def wave_equal(self, mine, equal, half=None): - """s_cmp_eq / s_cmp_lg of a lane mask (with 0, or with another mask): the masks are equal when every lane's - bit is, so the lanes vote. `mine` is this lane's result for the comparison asked (equal, or not equal). - When `half` is 'lo' or 'hi' (32-bit compare on one half of a wave64 mask), restrict the vote to that half.""" - self.uses_vote = True - if half is not None: - lane = self.wave_lane() - in_h = self.tmp() - op = "OpULessThan" if half == "lo" else "OpUGreaterThanEqual" - self.emit(f"{in_h} = {op} %bool {lane} {self.cu(32)}") - eff = self.tmp() - if equal: - self.emit(f"{eff} = OpSelect %bool {in_h} {mine} %true") - else: - self.emit(f"{eff} = OpLogicalAnd %bool {in_h} {mine}") - mine = eff - r = self.tmp() - self.g_vote(r, "All" if equal else "Any", mine) - return r - - def holds_lane_mask(self, a): - """Whether operand `a` certainly holds a lane mask here: EXEC, or VCC / an SGPR that lane_masks.py found - written as a mask on every path. An SGPR pair filled from a buffer (a light mask, say) is data.""" - if a["k"] == "special": - t = a.get("t", "") - if t.startswith("exec"): - return True - if t in ("vcc", "vcc_lo"): - return "vcc" in self.cur_masks - if t == "vcc_hi": - return ("vcc" if self.wave64 else "vcc_hi") in self.cur_masks - return False - if a["k"] == "sgpr": - n = a.get("n", 1) - if n == 2: - return any(a["r"] + i in self.cur_masks for i in range(2)) and \ - all(a["r"] + i in self.cur_masks or a["r"] + i in self.cur_either for i in range(2)) - return all(a["r"] + i in self.cur_masks for i in range(n)) - return False - - def any_mask_word(self, a): - """Whether any dword of an SGPR pair is a lane mask (EITHER constants are data here). - - holds_lane_mask() needs every dword, but a pair with one mask word and one - zero/-1 word is a zero-extended mask: selecting it as data would read this lane's bit. - """ - return a["k"] == "sgpr" and any(a["r"] + i in self.cur_masks for i in range(a.get("n", 1))) - - def any_ever_mask_word(self, a): - """Whether any dword of an SGPR pair held a lane mask on any path, even earlier in the shader.""" - return a["k"] == "sgpr" and any(a["r"] + i in self.ever_mask for i in range(a.get("n", 1))) - - def wave_mask(self, a): - """The whole wave's lane mask in operand `a` as real bits: (lanes 0-31, lanes 32-63). A register holds - only this lane's bit (all ones or zero), so each lane puts its bit at its own position and the subgroup - (= the wave) ORs them together. For the instructions that look at a mask as a whole: until 2026-11-21 - they saw the one lane, so the lane count of a wave was 64 or 0 and its first lane 0 or none.""" - self.uses_subgroup = True - special = a["k"] == "special" and a.get("t", "").startswith("exec") - key = None - if self.emulate: - # The same value of the same register needs no second exchange: the lanes' bits are what they were. - # Values are told apart by the SSA id last stored to the register in this block (x_tok, forgotten at - # a label); a register not written yet has its value from the start of the block. - if special: - key = ("exec", self.x_gen, self.x_tok.get("%active", "start")) - elif a["k"] == "sgpr": - toks = tuple(self.x_tok.get(("sgpr", a["r"] + i), ("start", a["r"] + i)) for i in range(a.get("n", 1))) - key = ("v", self.x_gen, toks) - elif a["k"] == "special" and a["t"] in ("vcc", "vcc_lo", "vcc_hi"): - reg = "%vcc_hi" if (a["t"] == "vcc_hi" and not self.wave64) else "%vcc" - key = ("v", self.x_gen, self.x_tok.get(reg, ("start", reg[1:]))) - if key in self.x_mcache: - return self.x_mcache[key] - mine = self.tmp_bool_nz(self.exec_value() if special else self.mask_src(a)) - if self.emulate: - res = self.x_round(bits=self.lane_bits(mine))[1] - if key is not None: - self.x_mcache[key] = res - return res - if self.wave32_fragment: - ballot = self.tmp() - self.emit(f"{ballot} = OpGroupNonUniformBallot %v4uint_bal {self.cu(3)} {mine}") - word = self.wave32_ballot_word(ballot) - self.uses_ballot = True - return word, self.cu(0) - self.uses_wave_bits = True - lane = self.wave_lane() - low, sh, bit, b, lo_in, hi_in, lo, hi = (self.tmp() for _ in range(8)) - self.emit(f"{low} = OpULessThan %bool {lane} {self.cu(32)}") - self.emit(f"{sh} = OpBitwiseAnd %uint {lane} {self.cu(31)}") - self.emit(f"{bit} = OpShiftLeftLogical %uint {self.cu(1)} {sh}") - self.emit(f"{b} = OpSelect %uint {mine} {bit} {self.cu(0)}") - self.emit(f"{lo_in} = OpSelect %uint {low} {b} {self.cu(0)}") - self.emit(f"{hi_in} = OpSelect %uint {low} {self.cu(0)} {b}") - self.emit(f"{lo} = OpGroupNonUniformBitwiseOr %uint {self.cu(3)} Reduce {lo_in}") - self.emit(f"{hi} = OpGroupNonUniformBitwiseOr %uint {self.cu(3)} Reduce {hi_in}") - return lo, hi - - def quad_any(self, v): - """This lane's value after whole-quad mode: all ones if any of the 4 lanes of its quad (4n .. 4n+3 of the - wave) has `v` non-zero, else 0. A quad never crosses the 32/32 half of a wave64, so a 32-wide subgroup is - exact. Without emulation the subgroup's quad ops do it (the invocations of a quad are 4 consecutive subgroup - invocations; in a fragment shader the 2x2 quad, which on hardware is also 4 consecutive lanes; vertex, - geometry and mesh shaders shuffle, as quad operations are only guaranteed in fragment and compute stages); - emulated, the four lanes' values are read through the exchange buffer. Not handled: an absent invocation in - a partial quad (a compute group whose size is not a multiple of 4) gives an undefined value natively.""" - b = self.tmp() - self.emit(f"{b} = OpSelect %uint {self.tmp_bool_nz(v)} {self.cu(1)} {self.cu(0)}") - if self.emulate: - lane, base = self.wave_lane(), self.tmp() - self.emit(f"{base} = OpBitwiseAnd %uint {lane} {self.cu(0xFFFFFFFC)}") - read = self.x_round(data=b)[0] - acc = None - for k in range(4): - i = self.tmp() - self.emit(f"{i} = OpIAdd %uint {base} {self.cu(k)}") - w = read(i) - if acc is None: - acc = w - else: - o = self.tmp() - self.emit(f"{o} = OpBitwiseOr %uint {acc} {w}") - acc = o - elif self.stage in ("ps", "cs"): - self.uses_subgroup = self.uses_quad = True - acc = b - for d in (0, 1): # horizontal, then vertical neighbour - sw, o = self.tmp(), self.tmp() - self.emit(f"{sw} = OpGroupNonUniformQuadSwap %uint {self.cu(3)} {acc} {self.cu(d)}") - self.emit(f"{o} = OpBitwiseOr %uint {acc} {sw}") - acc = o - else: - # Quad operations are only guaranteed in fragment and compute shaders (quadOperationsInAllStages): - # vertex, geometry and mesh shaders shuffle from the four lanes of the quad instead. - self.uses_subgroup = True - lane, base = self.tmp(), self.tmp() - self.sub_lane(lane) - self.emit(f"{base} = OpBitwiseAnd %uint {lane} {self.cu(0xFFFFFFFC)}") - acc = b - for k in range(4): - i, w, o = self.tmp(), self.tmp(), self.tmp() - self.emit(f"{i} = OpIAdd %uint {base} {self.cu(k)}") - self.g_shuffle(w, b, i) - self.emit(f"{o} = OpBitwiseOr %uint {acc} {w}") - acc = o - r = self.tmp() - self.emit(f"{r} = OpSelect %uint {self.tmp_bool_nz(acc)} {self.cu(0xFFFFFFFF)} {self.cu(0)}") - return r - - def wqm_word(self, w): - """s_wqm on 32 bits of plain data: each group of 4 bits becomes 1111 if any of its bits is set.""" - acc = w - for k in (1, 2, 3): - x, o = self.tmp(), self.tmp() - self.emit(f"{x} = OpShiftRightLogical %uint {w} {self.cu(k)}") - self.emit(f"{o} = OpBitwiseOr %uint {acc} {x}") - acc = o - m, r = self.tmp(), self.tmp() - self.emit(f"{m} = OpBitwiseAnd %uint {acc} {self.cu(0x11111111)}") - self.emit(f"{r} = OpIMul %uint {m} {self.cu(15)}") - return r - - def put_mask(self, d, v, half): - """mask_dst, except that a 32-bit half of EXEC / VCC in wave64 only changes the lanes of that half.""" - if half and d["k"] == "special" and d.get("t") in ("exec_lo", "exec_hi", "vcc_lo", "vcc_hi"): - h = 1 if d["t"].endswith("hi") else 0 - if d["t"].startswith("exec"): - self.exec_half_write(h, v) - else: - lane, inh, cur, new = (self.tmp() for _ in range(4)) - self.emit(f"{lane} = OpCopyObject %uint {self.wave_lane()}") - self.emit(f"{inh} = {'OpUGreaterThanEqual' if h else 'OpULessThan'} %bool {lane} {self.cu(32)}") - self.emit(f"{cur} = OpLoad %uint %vcc") - self.emit(f"{new} = OpSelect %uint {inh} {v} {cur}") - self.emit(f"OpStore %vcc {new}") - return - self.mask_dst(d, v) - - def scc_any_half(self, v, half): - """SCC = some lane of the wave (of one 32-lane half of a wave64 when `half`) has `v` non-zero.""" - if not self.cur_scc_live: - return - mine = self.tmp_bool_nz(v) - if half: - lane, inh, both = (self.tmp() for _ in range(3)) - self.emit(f"{lane} = OpCopyObject %uint {self.wave_lane()}") - self.emit(f"{inh} = {'OpUGreaterThanEqual' if half == 'hi' else 'OpULessThan'} %bool {lane} {self.cu(32)}") - self.emit(f"{both} = OpLogicalAnd %bool {inh} {mine}") - mine = both - any_ = self.tmp() - self.g_vote(any_, "Any", mine) - self.uses_vote = True - z = self.tmp() - self.emit(f"{z} = OpSelect %uint {any_} {self.cu(1)} {self.cu(0)}") - self.emit(f"OpStore %scc {z}") - - def wqm(self, op, a): - """s_wqm_b32 / s_wqm_b64: D = every quad (4 consecutive bits) of S0 that has a bit set becomes 1111; - SCC = D != 0. A lane mask is one bit per lane here (this lane's), so the quad's bits are gathered with - quad_any and SCC is the wave-wide any. Anything else is data and is computed on the bits. A 32-bit form - in wave64 (exec_lo / exec_hi, vcc_lo / vcc_hi, a half-mask SGPR) only changes, and only votes over, its own - half: it is the half of the source, or of the destination when that is one of the halves.""" - half = None - if self.wave64 and op.endswith("b32"): - half = self.mask_half(a[1]) or self.mask_half(a[0]) - if self.holds_lane_mask(a[1]): - r = self.quad_any(self.mask_src(a[1])) - self.put_mask(a[0], r, half) - self.scc_any_half(r, half) - return - src = a[1] - if op.endswith("b64") and src["k"] == "sgpr" and src.get("n") == 2: - words = [self.load_reg("sgpr", src["r"]), self.load_reg("sgpr", src["r"] + 1)] - elif op.endswith("b64") and src["k"] == "imm": - words = [self.cu(src["v"] & 0xFFFFFFFF), self.cu((src["v"] >> 32) & 0xFFFFFFFF)] - else: - words = [self.src_u(src)] + ([self.cu(0)] if op.endswith("b64") else []) - res = [self.wqm_word(w) for w in words] - d = a[0] - if d["k"] == "sgpr": - self.store_reg("sgpr", d["r"], res[0]) - if len(res) == 2: - self.store_reg("sgpr", d["r"] + 1, res[1]) - elif not self.wave64 and d["k"] == "special" and d.get("t") == "vcc_hi": - self.emit(f"OpStore %vcc_hi {res[0]}") - else: - # EXEC / VCC filled from data: this lane takes its own bit of the result. - lane = self.wave_lane() - sh, b, pick = self.tmp(), self.tmp(), self.tmp() - self.emit(f"{sh} = OpBitwiseAnd %uint {lane} {self.cu(31)}") - word = res[0] - if len(res) == 2: - hi, word = self.tmp(), self.tmp() - self.emit(f"{hi} = OpUGreaterThanEqual %bool {lane} {self.cu(32)}") - self.emit(f"{word} = OpSelect %uint {hi} {res[1]} {res[0]}") - self.emit(f"{b} = OpBitFieldUExtract %uint {word} {sh} {self.cu(1)}") - self.emit(f"{pick} = OpSelect %uint {self.tmp_bool_nz(b)} {self.cu(0xFFFFFFFF)} {self.cu(0)}") - self.put_mask(d, pick, half) - nz = res[0] - if len(res) == 2: - nz = self.tmp() - self.emit(f"{nz} = OpBitwiseOr %uint {res[0]} {res[1]}") - self.scc_nonzero(nz) - - def lane_bits(self, b): - """This lane's bool as its bit of a 64-lane mask: (lanes 0-31 word, lanes 32-63 word), one of them 0.""" - lane = self.wave_lane() - low, sh, bit, v, lo_in, hi_in = (self.tmp() for _ in range(6)) - self.emit(f"{low} = OpULessThan %bool {lane} {self.cu(32)}") - self.emit(f"{sh} = OpBitwiseAnd %uint {lane} {self.cu(31)}") - self.emit(f"{bit} = OpShiftLeftLogical %uint {self.cu(1)} {sh}") - self.emit(f"{v} = OpSelect %uint {b} {bit} {self.cu(0)}") - self.emit(f"{lo_in} = OpSelect %uint {low} {v} {self.cu(0)}") - self.emit(f"{hi_in} = OpSelect %uint {low} {self.cu(0)} {v}") - return lo_in, hi_in - - def _scalar_word_lane_bit(self, word, lane=None): - """Extract bit (lane & 31) of 32-bit scalar word as 0xFFFFFFFF / 0 for plain-data mask reads.""" - if lane is None: - lane = self.wave_lane() - sh, shr, bit, r = (self.tmp() for _ in range(4)) - self.emit(f"{sh} = OpBitwiseAnd %uint {lane} {self.cu(31)}") - self.emit(f"{shr} = OpShiftRightLogical %uint {word} {sh}") - self.emit(f"{bit} = OpBitwiseAnd %uint {shr} {self.cu(1)}") - self.emit(f"{r} = OpSelect %uint {self.tmp_bool_nz(bit)} {self.cu(0xFFFFFFFF)} {self.cu(0)}") - return r - - def mask_src(self, a, wide=True): - """A lane mask operand (sgpr pair, vcc, exec, imm) as one uint for this lane. A constant is a mask with one - bit per lane, so lane L takes its bit L: of the 64-bit value (`wide`, the default: a 64-bit SALU operand or - the VALU mask of a wave64; inline constants sign-extended, a literal with a zero high word, as src64_data) - or of the 32-bit value with L mod 32 (a b32 op). Until 2026-11-22 every lane took bit 0 (0xff00 was no - lane, 5 every lane).""" - if a["k"] == "sgpr": - if self.holds_lane_mask(a): - if self.wave64 and wide and a.get("n") == 2: - lo, hi = self.load_reg("sgpr", a["r"]), self.load_reg("sgpr", a["r"] + 1) - up, sel = self.tmp(), self.tmp() - self.emit(f"{up} = OpUGreaterThanEqual %bool {self.wave_lane()} {self.cu(32)}") - self.emit(f"{sel} = OpSelect %uint {up} {hi} {lo}") - return sel - return self.load_reg("sgpr", a["r"]) - # Not known to hold a mask: the SGPR may hold a constant (s_mov_b32 s20, 0x3ffffc00) that is the same in - # every invocation, so lane L takes its bit L, as for an immediate. Until 2026-11-22 the raw value was used - # and any non-zero constant enabled every lane. A mask the analysis missed is still exact: each - # invocation holds 0 or ~0 there, and bit L of that is the same 0 or 1. A pair in a wave64 64-bit - # context gives lanes 32..63 their bit from the high SGPR (a mask keeps the same 0 / ~0 in both). - lane = self.wave_lane() - word = self.load_reg("sgpr", a["r"]) - if a.get("n", 1) == 2 and wide and self.wave64: - hi, up, sel = self.load_reg("sgpr", a["r"] + 1), self.tmp(), self.tmp() - self.emit(f"{up} = OpUGreaterThanEqual %bool {lane} {self.cu(32)}") - self.emit(f"{sel} = OpSelect %uint {up} {hi} {word}") - word = sel - return self._scalar_word_lane_bit(word, lane) - if a["k"] == "special" and a["t"] == "null": - return self.cu(0) - if a["k"] == "special" and a["t"] == "vcc_hi" and not self.wave64: - v = self.tmp() - self.emit(f"{v} = OpLoad %uint %vcc_hi") - return v if self.holds_lane_mask(a) else self._scalar_word_lane_bit(v) - if a["k"] == "special" and a["t"] in ("vcc", "vcc_lo", "vcc_hi"): - v = self.tmp() - self.emit(f"{v} = OpLoad %uint %vcc") - return v - if a["k"] == "special" and a["t"] in ("exec", "exec_lo", "exec_hi"): - return self.exec_value() - if a["k"] == "imm": - w64 = wide and self.wave64 - v = a["v"] & (0xFFFFFFFFFFFFFFFF if w64 else 0xFFFFFFFF) - lo, hi = v & 0xFFFFFFFF, v >> 32 - if lo in (0, 0xFFFFFFFF) and (hi == lo or not w64): - return self.cu(lo) # 0 or -1: no lane or every lane, as before - lane = self.wave_lane() - sh, word, shr, bit, r = (self.tmp() for _ in range(5)) - self.emit(f"{sh} = OpBitwiseAnd %uint {lane} {self.cu(31)}") - if w64 and hi != lo: - up = self.tmp() - self.emit(f"{up} = OpUGreaterThanEqual %bool {lane} {self.cu(32)}") - self.emit(f"{word} = OpSelect %uint {up} {self.cu(hi)} {self.cu(lo)}") - else: - self.emit(f"{word} = OpCopyObject %uint {self.cu(lo)}") - # Shift and mask, not OpBitFieldUExtract (Intel's driver takes the offset mod 16 for a 16-bit constant; - # see exec_half_write). - self.emit(f"{shr} = OpShiftRightLogical %uint {word} {sh}") - self.emit(f"{bit} = OpBitwiseAnd %uint {shr} {self.cu(1)}") - self.emit(f"{r} = OpSelect %uint {self.tmp_bool_nz(bit)} {self.cu(0xFFFFFFFF)} {self.cu(0)}") - return r - raise Unsupported("mask operand") - - def is_mask_op(self, x): - return self.holds_lane_mask(x) or ( - x["k"] == "special" and x.get("t", "").startswith(("exec", "vcc")) - ) - - def f64_literal_one_dword(self, src: dict) -> bool: - """True when a literal source is the one ISA dword that supplies bits 63:32. - - LLVM prints a value that fits one literal dword without padding, so its hex width is at - most 8 digits; a spelling wider than that is the whole binary64 constant (the full-width - form `tools/f64_diff.py` writes). A decimal operand has no printed width and falls back to - the value, which is also what a padded one-dword spelling cannot survive. - """ - digits = src.get("literal_hex_digits") - if digits is not None: - return digits <= 8 - return -0x80000000 <= src["v"] <= 0xFFFFFFFF - - def f64_source_words(self, src: dict, op: str) -> tuple[str, str]: - if src["k"] in ("vgpr", "sgpr") and src.get("n") == 2: - return self.load_reg(src["k"], src["r"]), self.load_reg(src["k"], src["r"] + 1) - if src.get("f64_literal") and self.f64_literal_one_dword(src): - # One literal dword: bits 63:32 of the constant (docs/design.md, f64 literal sources). - return self.cu(0), self.cu(src["v"] & 0xFFFFFFFF) - # A wider literal is the whole constant, so both words of it are the value: fall through. - if src["k"] == "fimm": - bits = struct.unpack("> 32) - - def src64_data(self, s, op, *, allow_vgpr: bool = False): - kind = s["k"] - if s.get("n") == 2 and (kind == "sgpr" or (allow_vgpr and kind == "vgpr")): - return self.load_reg(kind, s["r"]), self.load_reg(kind, s["r"] + 1) - if s["k"] == "imm": - v = s["v"] & 0xFFFFFFFFFFFFFFFF - return self.cu(v & 0xFFFFFFFF), self.cu(v >> 32) - if s["k"] == "special" and s.get("t") == "null": - return self.cu(0), self.cu(0) - raise Unsupported(op + " source") - - def dst64_data(self, d, rlo, rhi, op, *, allow_null=False): - if allow_null and d["k"] == "special" and d.get("t") == "null": - return - if d["k"] != "sgpr" or d.get("n") != 2: - raise Unsupported(op + " destination") - self.store_reg("sgpr", d["r"], rlo) - self.store_reg("sgpr", d["r"] + 1, rhi) - - # f(S0, EXEC) of the saveexec / wrexec family (RDNA2 ISA SOP1; tools/cf_ref.py _SAVEEXEC): (op, NOT S0, NOT EXEC, - # NOT the result). andn1/orn1 complement S0, andn2/orn2 complement EXEC. - EXEC_LOGIC = {"and": ("OpBitwiseAnd", 0, 0, 0), "or": ("OpBitwiseOr", 0, 0, 0), "xor": ("OpBitwiseXor", 0, 0, 0), - "andn1": ("OpBitwiseAnd", 1, 0, 0), "andn2": ("OpBitwiseAnd", 0, 1, 0), - "orn1": ("OpBitwiseOr", 1, 0, 0), "orn2": ("OpBitwiseOr", 0, 1, 0), - "nand": ("OpBitwiseAnd", 0, 0, 1), "nor": ("OpBitwiseOr", 0, 0, 1), "xnor": ("OpBitwiseXor", 0, 0, 1)} - - def exec_logic(self, kind, s0, exec_): - """f(S0, EXEC) for one lane's mask bit (0 or ~0); see EXEC_LOGIC.""" - k, n0, ne, nr = self.EXEC_LOGIC[kind] - if n0: - t = self.tmp() - self.emit(f"{t} = OpNot %uint {s0}") - s0 = t - if ne: - t = self.tmp() - self.emit(f"{t} = OpNot %uint {exec_}") - exec_ = t - r = self.tmp() - self.emit(f"{r} = {k} %uint {s0} {exec_}") - if nr: - t = self.tmp() - self.emit(f"{t} = OpNot %uint {r}") - r = t - return r - - def is_mask_dst(self, d): - """Whether `d` is a valid scalar lane-mask destination for VALU mask instructions (e.g. v_cmp_*_e64).""" - k, t = d["k"], d.get("t") - return ( - k == "sgpr" - or (k == "special" and ( - t in ("exec", "exec_lo", "null", "vcc", "vcc_lo") - or (t == "vcc_hi" and not self.wave64) - )) - ) - - def mask_dst(self, d, v): - if self.wave64 and d["k"] == "special" and d["t"] in ("exec_lo", "exec_hi"): - self.exec_half_write(1 if d["t"] == "exec_hi" else 0, v) - elif d["k"] == "special" and d["t"] in ("exec", "exec_lo"): - self.set_exec(v) - elif d["k"] == "special" and d["t"] == "null": - return - elif d["k"] == "sgpr": - self.store_reg("sgpr", d["r"], v) - if d.get("n") == 2: - self.store_reg("sgpr", d["r"] + 1, v) - elif d["k"] == "special" and d["t"] in ("vcc", "vcc_lo"): - self.emit(f"OpStore %vcc {v}") - elif d["k"] == "special" and d["t"] == "vcc_hi" and not self.wave64: - self.emit(f"OpStore %vcc_hi {v}") - else: - raise Unsupported("mask destination") - - def clamp_mods(self, v, mods, allow_omod=True): - # RDNA2 (GFX10.3) VOP3 OMOD applies before clamp iff MODE.ieee == 0 AND output denorms - # for the destination precision are flushed. Under default shader MODE (IEEE=0, fp32 - # denorms flushed, fp16/fp64 denorms kept), omod scales f32 destinations (including - # v_cvt_f32_f16) and is ignored on f16 destinations while clamp still saturates [0, 1]. - if allow_omod: - for m in mods: - if m in ("mul:2", "mul:4", "div:2"): - k = {"mul:2": "2", "mul:4": "4", "div:2": "0.5"}[m] - c = self.fconst(float(k)) - g = self.tmp() - self.emit(f"{g} = OpFMul %float {v} {c}") - v = g - if "clamp" in mods: - g = self.tmp() - self.emit(f"{g} = OpExtInst %float %glsl FClamp {v} %f0 %f1") - return g - return v - - def clamp_f16(self, v, mods): - # f16 destination under default MODE (denorm16_64=3): omod ignored by silicon, clamp kept. - return self.clamp_mods(v, mods, allow_omod=False) - - def _validate_unary_f16(self, op, raw_op, a, mods): - """Validate operands, encoding suffix, and modifiers for unary f16 VOP1/VOP3/SDWA ops.""" - if len(a) != 2: - raise Unsupported(f"{op} operands") - dst, src = a - if (dst.get("k") != "vgpr" or dst.get("n", 1) != 1 - or dst.get("neg") or dst.get("abs") or dst.get("sext")): - raise Unsupported(f"{op} destination") - if src.get("n", 1) != 1 or src.get("sext"): - raise Unsupported(f"{op} source") - if raw_op.endswith("_dpp"): - raise Unsupported(f"{op} _dpp") - if raw_op.endswith("_e32"): - if src.get("neg") or src.get("abs"): - raise Unsupported(f"{op} _e32 source modifier") - if mods: - raise Unsupported(f"{op} _e32 modifier") - return - if raw_op.endswith("_sdwa"): - seen_clamp = False - seen_omod = False - seen_keys = set() - for m in mods: - if m == "clamp": - if seen_clamp: - raise Unsupported(f"{op} duplicate clamp") - seen_clamp = True - elif m in ("mul:2", "mul:4", "div:2"): - if seen_omod: - raise Unsupported(f"{op} duplicate omod") - seen_omod = True - elif ":" in m: - key, val = m.split(":", 1) - if key in seen_keys: - raise Unsupported(f"{op} duplicate {key}") - if key in ("src0_sel", "dst_sel") and val in self.SDWA_SEL: - seen_keys.add(key) - elif key == "dst_unused" and val in ("UNUSED_PAD", "UNUSED_SEXT", "UNUSED_PRESERVE"): - seen_keys.add(key) - else: - raise Unsupported(f"{op} _sdwa modifier") - else: - raise Unsupported(f"{op} _sdwa modifier") - return - # VOP3 (_e64 or bare) - seen_clamp = False - seen_omod = False - seen_opsel = False - for m in mods: - if m == "clamp": - if seen_clamp: - raise Unsupported(f"{op} duplicate clamp") - seen_clamp = True - elif m in ("mul:2", "mul:4", "div:2"): - if seen_omod: - raise Unsupported(f"{op} duplicate omod") - seen_omod = True - elif m.startswith("op_sel:"): - if seen_opsel or not (m.startswith("op_sel:[") and m.endswith("]")): - raise Unsupported(f"{op} op_sel") - raw_parts = m[len("op_sel:["):-1].split(",") - if not raw_parts or len(raw_parts) > 2 or any(p not in ("0", "1") for p in raw_parts): - raise Unsupported(f"{op} op_sel") - seen_opsel = True - else: - raise Unsupported(f"{op} modifier") - - def flush_f32(self, f): - """v_mad_f32, v_mac_f32, v_mad_legacy_f32 and default-mode v_mul_legacy_f32 flush f32 denormals: - a subnormal operand or result - reads as signed zero, whatever the MODE register says. LLVM's SITargetLowering::isFMADLegal forms - v_mad_f32/v_mac_f32 only when f32 denormals are flushed (SIISelLowering.cpp, llvm-project 1922c0c); - v_mad_legacy_f32 is the same VALU. Emulated as |x| < FLT_MIN -> copysign(0, x): inf and NaN compare - false and pass through, and 0 keeps its sign. Counted over the corpus before writing this (SHADER-118): - 9,297 of the 26,503 shaders use at least one of the three, 440,858 occurrences (0.99% of the corpus).""" - a, small, sign, z, r = (self.tmp() for _ in range(5)) - self.emit(f"{a} = OpExtInst %float %glsl FAbs {f}") - self.emit(f"{small} = OpFOrdLessThan %bool {a} {self.fconst(2.0 ** -126)}") - self.emit(f"{sign} = OpBitwiseAnd %uint {self.tou(f)} {self.cu(0x80000000)}") - self.emit(f"{z} = OpBitcast %float {sign}") - self.emit(f"{r} = OpSelect %float {small} {z} {f}") - return r - - def _validate_div_valu(self, ins, op, mods, *, dst_width, src_width=None, - allow_opsel=False, strict_omod=True, allow_null_dst=False): - """Validate encoding, arity, destination/source widths and modifiers for VOP3 IEEE-754 division ops.""" - raw_op = ins["op"] - raw_args = self.cur_ins["args"] - if raw_op.endswith(("_e32", "_sdwa", "_dpp")): - raise Unsupported(op + " encoding") - if len(raw_args) != 4: - raise Unsupported(op + " operands") - dst = raw_args[0] - is_null_dst = allow_null_dst and dst.get("k") == "special" and dst.get("t") == "null" - if not is_null_dst and (dst.get("k") != "vgpr" or dst.get("n", 1) != dst_width): - raise Unsupported(op + " destination") - if dst.get("neg") or dst.get("abs") or dst.get("sext"): - raise Unsupported(op + " destination modifier") - for src in raw_args[1:]: - if src.get("sext"): - raise Unsupported(op + " operand modifier") - if src_width is not None and src.get("n", 1) != src_width: - raise Unsupported(op + " operand width") - seen_clamp = False - seen_omod = False - seen_opsel = False - for m in mods: - if m == "clamp": - if seen_clamp: - raise Unsupported(op + " modifier") - seen_clamp = True - elif m in ("mul:2", "mul:4", "div:2"): - if strict_omod and seen_omod: - raise Unsupported(op + " modifier") - seen_omod = True - elif allow_opsel and m.startswith("op_sel:"): - if seen_opsel or not (m.startswith("op_sel:[") and m.endswith("]")): - raise Unsupported(op + " modifier") - bits = [p.strip() for p in m[8:-1].split(",")] - if not (1 <= len(bits) <= 4) or any(b not in ("0", "1") for b in bits): - raise Unsupported(op + " modifier") - seen_opsel = True - else: - raise Unsupported(f"{op} modifier {m}") - - def _validate_cvt32_valu(self, ins, op, mods, *, float_src, float_dst): - """Validate encoding, arity, destination/source widths and modifiers for unary 32-bit float/int conversions.""" - raw_op = ins["op"] - raw_args = self.cur_ins["args"] - if len(raw_args) != 2: - raise Unsupported(op + " operands") - dst, src = raw_args - is_null_dst = dst.get("k") == "special" and dst.get("t") == "null" - if not is_null_dst and (dst.get("k") != "vgpr" or dst.get("n", 1) != 1): - raise Unsupported(op + " destination") - if dst.get("neg") or dst.get("abs") or dst.get("sext"): - raise Unsupported(op + " destination modifier") - if src.get("n", 1) != 1: - raise Unsupported(op + " operand width") - is_sdwa = raw_op.endswith("_sdwa") - is_dpp = raw_op.endswith("_dpp") - is_e32 = raw_op.endswith("_e32") - if src.get("sext") and (float_src or not is_sdwa): - raise Unsupported(op + " operand modifier") - if (src.get("neg") or src.get("abs")) and (not float_src or is_e32): - raise Unsupported(op + " operand modifier") - if is_e32: - if mods: - raise Unsupported(op + " modifier") - return - if is_dpp: - if self.non_dpp_mods(raw_op, mods): - raise Unsupported(op + " modifier") - return - seen_sdwa = set() - seen_clamp = False - seen_omod = False - for m in mods: - if m == "clamp": - if not float_dst or seen_clamp: - raise Unsupported(op + " modifier") - seen_clamp = True - elif m in ("mul:2", "mul:4", "div:2"): - if not float_dst or seen_omod: - raise Unsupported(op + " modifier") - seen_omod = True - elif is_sdwa and ":" in m: - k, v = m.split(":", 1) - if k in seen_sdwa: - raise Unsupported(op + " duplicate SDWA modifier") - seen_sdwa.add(k) - if k in ("src0_sel", "dst_sel"): - if v not in self.SDWA_SEL: - raise Unsupported(op + " SDWA selector") - elif k == "dst_unused": - if v not in ("UNUSED_PAD", "UNUSED_SEXT", "UNUSED_PRESERVE"): - raise Unsupported(op + " SDWA dst_unused") - else: - raise Unsupported(op + " modifier") - else: - raise Unsupported(op + " modifier") - - def dst_f64(self, d, value, mods, op): - if d["k"] != "vgpr" or d.get("n") != 2: - raise Unsupported(op + " destination") - result = self.clamp_mods_f64(value, mods) - pair = self.tmp() - self.emit(f"{pair} = OpBitcast %v2uint_d {result}") - for i in range(2): - word = self.tmp() - self.emit(f"{word} = OpCompositeExtract %uint {pair} {i}") - self.dst({"k": "vgpr", "r": d["r"] + i, "n": 1}, word) - - def flush_f32_mods(self, v, mods): - """Flush a subnormal sum before output modifiers and flush again after them (SHADER-340, RDNA1 gfx1010).""" - v = self.flush_f32(v) - if any(m == "clamp" or m.startswith(("mul:", "div:")) for m in mods): - v = self.flush_f32(self.clamp_mods(v, mods)) - return v - - def clamp_mods_f64(self, v, mods): - """clamp_mods for a %double result (VOP3 f64 arithmetic): omod scales first, then clamp to [0, 1]. As - for f32 the clamp is GLSL.std.450 FClamp, so a NaN result and the sign of a -0 result are left to the - driver (the hardware, with DX10_CLAMP set, gives +0 for NaN).""" - for m in mods: - if m in ("mul:2", "mul:4", "div:2"): - g = self.tmp() - self.emit(f"{g} = OpFMul %double {v} {self.dconst({'mul:2': 2.0, 'mul:4': 4.0, 'div:2': 0.5}[m])}") - v = g - if "clamp" in mods: - g = self.tmp() - self.emit(f"{g} = OpExtInst %double %glsl FClamp {v} {self.dconst(0.0)} {self.dconst(1.0)}") - return g - return v - - def turn_angle(self, x): - """Reduce a turn count to [-0.5, 0.5] before scaling by 2*pi (SHADER-88). - - RDNA's v_sin/v_cos take turns and range-reduce in turns. Scaling first loses the fractional part for large - inputs (one f32 ulp at 255 turns is ~1.2e-4 rad) and leaves Sin outside the [-pi, pi] range where Vulkan - guarantees its precision. x - RoundEven(x) is exact in binary32 for every finite x, unlike Fract(x) (rounds - 1 - |x| for a negative x: -2**-26 became +0, and -0.1 was ~1.7e-7 off). RoundEven rather than Round so +-0.5 - reduce symmetrically. A zero keeps its sign (x - RoundEven(x) would turn -0 into +0). NaN and infinity stay - NaN through the subtraction. - """ - rnd, d, zero, t, arg = (self.tmp() for _ in range(5)) - self.emit(f"{rnd} = OpExtInst %float %glsl RoundEven {x}") - self.emit(f"{d} = OpFSub %float {x} {rnd}") - self.emit(f"{zero} = OpFOrdEqual %bool {x} {self.fconst(0.0)}") - self.emit(f"{t} = OpSelect %float {zero} {x} {d}") - self.emit(f"{arg} = OpFMul %float {t} {self.fconst(6.283185307179586)}") - return arg - - def trig_exact_zero(self, op, x, r): - """v_sin/v_cos: +0 where the hardware gives an exact zero, i.e. sin at an odd half turn and cos at an odd quarter - turn (|x - RoundEven(x)| is 0.5 or 0.25). Sin(2*pi*0.5) with a rounded 2*pi is about -8.7e-8 instead. Measured - natively on gfx1036 for f32 and f16, both signs, from 0.25 up to 2^22 turns (SHADER-134).""" - rnd, d, ad, hit, out = (self.tmp() for _ in range(5)) - self.emit(f"{rnd} = OpExtInst %float %glsl RoundEven {x}") - self.emit(f"{d} = OpFSub %float {x} {rnd}") - self.emit(f"{ad} = OpExtInst %float %glsl FAbs {d}") - self.emit(f"{hit} = OpFOrdEqual %bool {ad} {self.fconst(0.5 if 'sin' in op else 0.25)}") - self.emit(f"{out} = OpSelect %float {hit} %f0 {r}") - return out - - def fconst(self, x): - bits = struct.unpack("> 32)}") - self.emit(f"{d} = OpBitcast %double {v2}") - return d - - def round_f32_flushed(self, fn, x): - """v_floor_f32 / v_ceil_f32 / v_fract_f32 of the operand x (source modifiers applied) as RDNA2 computes them in - the MODE inferred for the game (IEEE 0, f32 denormals flushed), measured natively on gfx1036: a denormal - operand is a zero of its sign (floor(-1e-45) = -0, ceil(+1e-45) = +0, fract of either 0; using the denormal - gives -1.0, +1.0 and 0x3f7fffff), and a NaN operand passes through unchanged (signalling ones too). - fract(+-inf) is the negative quiet NaN 0xffc00000. Done here rather than left to the driver's f32 denormal - handling, which Vulkan does not fix.""" - bits, mag, exp, den, sgn, sz, xf, r = (self.tmp() for _ in range(8)) - self.emit(f"{bits} = OpBitcast %uint {x}") - self.emit(f"{mag} = OpBitwiseAnd %uint {bits} {self.cu(0x7FFFFFFF)}") - self.emit(f"{exp} = OpBitwiseAnd %uint {bits} {self.cu(0x7F800000)}") - self.emit(f"{den} = OpIEqual %bool {exp} {self.cu(0)}") - self.emit(f"{sgn} = OpBitwiseAnd %uint {bits} {self.cu(0x80000000)}") - self.emit(f"{sz} = OpSelect %uint {den} {sgn} {bits}") - self.emit(f"{xf} = OpBitcast %float {sz}") - self.emit(f"{r} = OpExtInst %float %glsl {fn} {xf}") - if fn == "Fract": - r = self.fract_below_one(r) - nan, inf, rb, keep, out = (self.tmp() for _ in range(5)) - self.emit(f"{rb} = OpBitcast %uint {r}") - self.emit(f"{nan} = OpUGreaterThan %bool {mag} {self.cu(0x7F800000)}") - self.emit(f"{keep} = OpSelect %uint {nan} {bits} {rb}") - if fn == "Fract": - fixed = self.tmp() - self.emit(f"{inf} = OpIEqual %bool {mag} {self.cu(0x7F800000)}") - self.emit(f"{fixed} = OpSelect %uint {inf} {self.cu(0xFFC00000)} {keep}") - keep = fixed - self.emit(f"{out} = OpBitcast %float {keep}") - return out - - def fract_below_one(self, r): - """v_fract: a Fract(x) that rounded up to 1.0 (x a tiny negative number) becomes 0x3f7fffff, the largest - float below 1, as on hardware. A compare and select, not FMin, so the NaN of fract(+-inf) is kept.""" - one, below = self.tmp(), self.tmp() - self.emit(f"{one} = OpFOrdEqual %bool {r} %f1") - self.emit(f"{below} = OpSelect %float {one} {self.tof(self.cu(0x3F7FFFFF))} {r}") - return below - - @staticmethod - def _f32_const_nan(s): - """Return True/False when ``s`` is statically NaN/non-NaN f32, or None at run time.""" - if not s or "sdwa_sel" in s: - return None - if s["k"] == "fimm": - return s["v"] != s["v"] - if s["k"] == "imm": - u = s["v"] & 0xFFFFFFFF - return (u & 0x7F800000) == 0x7F800000 and bool(u & 0x7FFFFF) - return None - - def _select_nan_first(self, res, first, nan_second, second=None, second_src=None): - """Return ``first`` when ``second`` is NaN, else ``res`` (RDNA2 S0 priority when both operands are NaN).""" - if nan_second is False: - return res - if nan_second is True: - return first - if nan_second is None: - st = self._f32_const_nan(second_src) - if st is False: - return res - if st is True: - return first - nan_second = self.tmp() - self.emit(f"{nan_second} = OpIsNan %bool {second}") - sel = self.tmp() - self.emit(f"{sel} = OpSelect %float {nan_second} {first} {res}") - return sel - - def nminmax_f32(self, glsl_op, x, y, y_src=None, nan_y=None): - """GLSL.std.450 ``NMin``/``NMax`` returning ``x`` with its bits intact whenever ``y`` is NaN.""" - r = self.tmp() - self.emit(f"{r} = OpExtInst %float %glsl {glsl_op} {x} {y}") - return self._select_nan_first(r, x, nan_y, y, y_src) - - _SDWA_UNUSED = ("UNUSED_PAD", "UNUSED_SEXT", "UNUSED_PRESERVE") - _F16_OMOD_MODS = ("mul:2", "mul:4", "div:2") - - @staticmethod - def _validate_f16_opsel_mod(mod, nsrc, op): - if not (mod.startswith("op_sel:[") and mod.endswith("]")): - raise Unsupported(op + " op_sel") - parts = [p.strip() for p in mod[len("op_sel:["):-1].split(",")] - if len(parts) != nsrc + 1 or any(p not in ("0", "1") for p in parts): - raise Unsupported(op + " op_sel") - - def _validate_f16_vop3_mods(self, mods, nsrc, op): - seen_clamp = False - seen_omod = False - seen_opsel = False - for m in mods: - if m == "clamp": - if seen_clamp: - raise Unsupported(op + " duplicate clamp") - seen_clamp = True - elif m in self._F16_OMOD_MODS: - if seen_omod: - raise Unsupported(op + " duplicate output modifier") - seen_omod = True - elif m.startswith("op_sel:"): - if seen_opsel: - raise Unsupported(op + " duplicate op_sel") - self._validate_f16_opsel_mod(m, nsrc, op) - seen_opsel = True - else: - raise Unsupported(op + " modifier " + m) - - def _validate_f16_sdwa_mods(self, mods, op): - seen_clamp = False - seen_omod = False - seen_keys = set() - for m in mods: - if m == "clamp": - if seen_clamp: - raise Unsupported(op + " duplicate clamp") - seen_clamp = True - elif m in self._F16_OMOD_MODS: - if seen_omod: - raise Unsupported(op + " duplicate output modifier") - seen_omod = True - elif ":" in m: - k, v = m.split(":", 1) - if k in ("src0_sel", "src1_sel", "dst_sel"): - if k in seen_keys or v not in self.SDWA_SEL: - raise Unsupported(op + " sdwa modifier " + m) - seen_keys.add(k) - elif k == "dst_unused": - if k in seen_keys or v not in self._SDWA_UNUSED: - raise Unsupported(op + " sdwa modifier " + m) - seen_keys.add(k) - else: - raise Unsupported(op + " modifier " + m) - else: - raise Unsupported(op + " modifier " + m) - - def _validate_f16_valu(self, ins, op, nsrc, *, allow_e32=False, allow_e64=True, - allow_sdwa=False, allow_dpp=False, int_srcs=()): - """Validate encoding suffix, arity, operand kinds/widths/modifiers, and instruction modifiers for f16 VALU ops.""" - raw_op, a, mods = ins["op"], ins["args"], ins["mods"] - allowed_suffixes = [""] - if allow_e32: - allowed_suffixes.append("_e32") - if allow_e64: - allowed_suffixes.append("_e64") - if allow_sdwa: - allowed_suffixes.append("_sdwa") - if allow_dpp: - allowed_suffixes.append("_dpp") - suf = raw_op[len(op):] - if suf not in allowed_suffixes: - raise Unsupported(raw_op + " encoding") - if len(a) != nsrc + 1: - raise Unsupported(op + " arity") - dst = a[0] - if dst.get("k") != "vgpr" or dst.get("n", 1) != 1 or dst.get("neg") or dst.get("abs") or dst.get("sext"): - raise Unsupported(op + " destination") - is_vop2_only = not allow_e64 - for idx, src in enumerate(a[1:]): - if src.get("n", 1) != 1 or src.get("sext"): - raise Unsupported(op + " source") - if (is_vop2_only or suf == "_e32" or idx in int_srcs) and (src.get("neg") or src.get("abs")): - raise Unsupported(op + " source modifier") - if is_vop2_only or suf == "_e32": - if mods: - raise Unsupported(op + " modifier") - elif suf == "_sdwa": - self._validate_f16_sdwa_mods(mods, op) - elif suf == "_dpp": - if self.non_dpp_mods(raw_op, mods): - raise Unsupported(op + " dpp modifier") - else: - self._validate_f16_vop3_mods(mods, nsrc, op) - - def _read_f16_minmax_srcs(self, srcs, sels, mods): - """Read f16 min/max/med3 sources and track raw modified ``src0`` half when ``clamp`` is absent.""" - if "clamp" in mods: - return [self.f16_in(s, sel) for s, sel in zip(srcs, sels)], None, None - in_bits = [self.f16_in_bits(s, sel, apply_mods=(i == 0)) for i, (s, sel) in enumerate(zip(srcs, sels))] - vals = [v for v, _, _ in in_bits] - all_nan = self.all_f16_nan_cond([(raw, st) for _, raw, st in in_bits]) - return vals, all_nan, in_bits[0][1] - - def _finish_f16_minmax_out(self, dst_op, r, mods, dhi, all_nan, h0_mod): - r = self.clamp_f16(r, mods) - if all_nan is None: - self.f16_out(dst_op, r, dhi) - return - if all_nan is True: - lo = h0_mod - else: - lo = self.f16_res(r) - sel_u = self.tmp() - self.emit(f"{sel_u} = OpSelect %uint {all_nan} {h0_mod} {lo}") - lo = sel_u - self.put_f16_bits(dst_op, lo, dhi) - - def med3_f(self, vals, srcs, sel=None): - """v_med3_f32 / v_med3_f16 on the f32 values ``vals`` of operands ``srcs`` (``sel``: the f16 half each one - reads). Without NaN: the median, NMin(NMax(z, NMin(x, y)), NMax(x, y)) — using NMax/NMin rather than FClamp - so evaluating the median before the NaN select is never GLSL.std.450 undefined when z is NaN or both x and y - are NaN. With any NaN operand the hardware returns min3(x, y, z) with the NaN-ignoring min (docs/design.md). - An inline or literal constant that is not a NaN gets no OpIsNan; with no operand left to check there is no - select.""" - x, y, z = vals - lo, hi, m1, m = self.tmp(), self.tmp(), self.tmp(), self.tmp() - self.emit(f"{lo} = OpExtInst %float %glsl NMin {x} {y}") - self.emit(f"{hi} = OpExtInst %float %glsl NMax {x} {y}") - self.emit(f"{m1} = OpExtInst %float %glsl NMax {z} {lo}") - self.emit(f"{m} = OpExtInst %float %glsl NMin {m1} {hi}") - checks = [] - preds = [] - for i, (v, s) in enumerate(zip(vals, srcs)): - bits = None - if s["k"] == "imm": - bits = s["v"] & 0xFFFFFFFF - elif s["k"] == "fimm": - bits = struct.unpack("> 16 if sel[i] else bits) & 0xFFFF - is_nan = (h & 0x7C00) == 0x7C00 and h & 0x3FF - if not is_nan: - preds.append(False) - continue - c = self.tmp() - self.emit(f"{c} = OpIsNan %bool {v}") - checks.append(c) - preds.append(c) - if not checks: - return m - nan = checks[0] - for c in checks[1:]: - o = self.tmp() - self.emit(f"{o} = OpLogicalOr %bool {nan} {c}") - nan = o - if sel is None: - mn1 = self._select_nan_first(lo, x, preds[1]) - mn = self.nminmax_f32("NMin", mn1, z, nan_y=preds[2]) - else: - mn = self.tmp() - self.emit(f"{mn} = OpExtInst %float %glsl NMin {lo} {z}") - r = self.tmp() - self.emit(f"{r} = OpSelect %float {nan} {mn} {m}") - return r - - # ---- instructions ---- - SDWA_SEL = {"BYTE_0": (0, 8), "BYTE_1": (8, 8), "BYTE_2": (16, 8), "BYTE_3": (24, 8), - "WORD_0": (0, 16), "WORD_1": (16, 16), "DWORD": (0, 32)} - - def insn(self, ins): - """SDWA (sub-dword addressing): each source is narrowed to src_sel (zero-extended, or sign-extended - under sext()) before the op and its neg/abs, and a VGPR result is placed at dst_sel with dst_unused - deciding the other bits (PAD = zero, SEXT = sign-extend, PRESERVE = keep the old bits). VOPC has no - dst_sel; v_cmpx (GFX10) has no written destination operand.""" - self.cur_ins = ins - self.cur_masks = self.lane_masks.get(id(ins), {}) - self.write_all_lanes = id(ins) in self.mask_writes - self.cur_uniform_readlane = bool(self.w64g) and id(ins) in self.w64g["uniform_readlane"] - self.cur_scc_live = (not self.emulate) or (self.scc_live is None) or (id(ins) in self.scc_live) - if self.emulate: - self.x_memory_order(base_op(ins["op"])) - self.cur_either = self.lane_either.get(id(ins), ()) - try: - if ins["op"].endswith("_dpp"): - bop = base_op(ins["op"]) - if bop in SOPC_CMP32_OPS or bop in SOPC_CMP64_OPS or bop in SOPC_BITCMP_OPS: - raise Unsupported(f"{ins['op']}: encoding suffix not supported on SOPC") - return self.dpp_insn(ins) - if not ins["op"].endswith("_sdwa"): - return self._insn(ins) - op, mods = base_op(ins["op"]), ins["mods"] - kv = dict(m.split(":", 1) for m in mods if m.split(":", 1)[0] in ("src0_sel", "src1_sel", "dst_sel", "dst_unused")) - args = [dict(x) for x in ins["args"]] - first = 0 if op.startswith("v_cmpx") else 1 - for i, key in enumerate(("src0_sel", "src1_sel")): - j = first + i - if j < len(args) and (kv.get(key, "DWORD") != "DWORD" or args[j].get("sext")): - args[j]["sdwa_sel"] = kv.get(key, "DWORD") - if not op.startswith("v_cmp") and args: # DWORD too: a 16-bit result then zeroes the high half (write_lo16) - args[0]["sdwa_dst"] = (kv.get("dst_sel", "DWORD"), kv.get("dst_unused", "UNUSED_PAD")) - return self._insn({**ins, "args": args}) - except (IndexError, TypeError): - # A line with no operands (hand-written input only: LLVM always prints them) fails the first - # operand read with IndexError, or TypeError where v_cmpx pads the source list with a None that - # never met a real operand. Report it as a rejection, not a translator error. With at least one - # operand printed either is internal and stays one. - if any(a is not None for a in ins["args"]): - raise - raise Unsupported(ins["op"] + ": no operands") from None - - def sdwa_src(self, v, a): - off, width = self.SDWA_SEL[a["sdwa_sel"]] - if width == 32: - return v - r = self.tmp() - f = "OpBitFieldSExtract" if a.get("sext") else "OpBitFieldUExtract" - self.emit(f"{r} = {f} %uint {v} {self.cu(off)} {self.cu(width)}") - return r - - def sdwa_dst(self, d, val): - sel, unused = d["sdwa_dst"] - off, width = self.SDWA_SEL[sel] - if width == 32: - return val - r = self.tmp() - if unused == "UNUSED_PRESERVE": - self.emit(f"{r} = OpBitFieldInsert %uint {self.load_reg('vgpr', d['r'])} {val} {self.cu(off)} {self.cu(width)}") - return r - lo = self.tmp() - ext = "OpBitFieldSExtract" if unused == "UNUSED_SEXT" else "OpBitFieldUExtract" - self.emit(f"{lo} = {ext} %uint {val} {self.cu(0)} {self.cu(width)}") - # SEXT: the sign-extended field shifted up leaves sign copies above it; bits below stay zero. - self.emit(f"{r} = OpShiftLeftLogical %uint {lo} {self.cu(off)}") - return r - - def dpp_insn(self, ins): - """DPP (data-parallel primitives) on a VOP1/VOP2 src0. The source lane follows quad_perm/row_* or dpp8, - then row_mask (one bit per 16-lane row) and bank_mask (one bit per 4-lane bank) decide which destination - lanes update. A source lane that is out of range or inactive under EXEC is invalid: bound_ctrl 1 reads 0, - otherwise the destination keeps its old value. dpp8 instead uses fi: fi 0 reads 0 from an inactive lane, - fi 1 reads its pre-existing value. DPP16/8 never reaches beyond its 16/8-lane group, so this is exact on - every subgroup at least that wide.""" - if "_sdwa" in ins["op"]: - raise Unsupported("DPP with SDWA") - mods = ins["mods"] - - def number(key, default): - for m in mods: - if m.startswith(key + ":"): - try: - return int(m.split(":", 1)[1], 0) - except ValueError: - raise Unsupported("DPP " + key) - return default - - def selectors(key, count, limit): - for m in mods: - if m.startswith(key + ":"): - try: - vals = [int(x, 0) for x in m.split("[", 1)[1].rstrip("]").split(",")] - except (IndexError, ValueError): - raise Unsupported("DPP " + key) - if len(vals) != count or any(not 0 <= v < limit for v in vals): - raise Unsupported("DPP " + key) - return vals - return None - - dpp8 = selectors("dpp8", 8, 8) - quad = selectors("quad_perm", 4, 4) - ctrl = None - for m in mods: - if m in ("row_mirror", "row_half_mirror"): - if ctrl is not None: - raise Unsupported("DPP controls") - ctrl = (m, None) - continue - for key in ("row_shl", "row_shr", "row_ror", "row_share", "row_xmask"): - if m.startswith(key + ":"): - if ctrl is not None: - raise Unsupported("DPP controls") - try: - value = int(m.split(":", 1)[1], 0) - except ValueError: - raise Unsupported("DPP " + key) - if not 0 <= value <= 15 or (key not in ("row_share", "row_xmask") and value == 0): - raise Unsupported("DPP " + key) - ctrl = (key, value) - break - if dpp8 is not None and (quad is not None or ctrl is not None): - raise Unsupported("DPP controls") - if quad is not None and ctrl is not None: - raise Unsupported("DPP controls") - if dpp8 is None and quad is None and ctrl is None: - raise Unsupported("DPP control") - fi = number("fi", 0) - bound = number("bound_ctrl", 0) - if fi not in (0, 1) or bound not in (0, 1): - raise Unsupported("DPP flag") - fi, bound = bool(fi), bool(bound) - row_mask = number("row_mask", 0xF) - bank_mask = number("bank_mask", 0xF) - if not (0 <= row_mask <= 0xF and 0 <= bank_mask <= 0xF): - raise Unsupported("DPP mask") - - args = [dict(a) for a in ins["args"]] - if len(args) < 2: - raise Unsupported("DPP operands") - if args[0].get("k") != "vgpr" or args[0].get("n", 1) != 1: - raise Unsupported("DPP destination") - if args[1].get("n", 1) != 1: - raise Unsupported("DPP 64-bit source") - if args[1].get("sext"): - raise Unsupported("DPP sext") - src = args[1] - src_val = self.src_u(src) # neg/abs are lane-uniform, so before or after the shuffle is the same - - lane = self.wave_lane() - group_bits = 7 if dpp8 is not None else 15 - local = self.tmp() - self.emit(f"{local} = OpBitwiseAnd %uint {lane} {self.cu(group_bits)}") - in_bounds = None - - if dpp8 is not None: - packed = sum(v << (3 * i) for i, v in enumerate(dpp8)) - sh = self.tmp() - self.emit(f"{sh} = OpIMul %uint {local} {self.cu(3)}") - p = self.tmp() - self.emit(f"{p} = OpShiftRightLogical %uint {self.cu(packed)} {sh}") - src_local = self.tmp() - self.emit(f"{src_local} = OpBitwiseAnd %uint {p} {self.cu(7)}") - elif quad is not None: - packed = sum(v << (2 * i) for i, v in enumerate(quad)) - q = self.tmp() - self.emit(f"{q} = OpBitwiseAnd %uint {local} {self.cu(3)}") - sh = self.tmp() - self.emit(f"{sh} = OpShiftLeftLogical %uint {q} {self.cu(1)}") - p = self.tmp() - self.emit(f"{p} = OpShiftRightLogical %uint {self.cu(packed)} {sh}") - perm = self.tmp() - self.emit(f"{perm} = OpBitwiseAnd %uint {p} {self.cu(3)}") - base = self.tmp() - self.emit(f"{base} = OpBitwiseAnd %uint {local} {self.cu(0xFFFFFFFC)}") - src_local = self.tmp() - self.emit(f"{src_local} = OpBitwiseOr %uint {base} {perm}") - else: - kind, value = ctrl - if kind == "row_shl": - src_local = self.tmp() - self.emit(f"{src_local} = OpIAdd %uint {local} {self.cu(value)}") - in_bounds = self.tmp() - self.emit(f"{in_bounds} = OpULessThan %bool {src_local} {self.cu(16)}") - elif kind == "row_shr": - in_bounds = self.tmp() - self.emit(f"{in_bounds} = OpUGreaterThanEqual %bool {local} {self.cu(value)}") - src_local = self.tmp() - self.emit(f"{src_local} = OpISub %uint {local} {self.cu(value)}") - elif kind == "row_ror": - t = self.tmp() - self.emit(f"{t} = OpISub %uint {local} {self.cu(value)}") - src_local = self.tmp() - self.emit(f"{src_local} = OpBitwiseAnd %uint {t} {self.cu(15)}") - elif kind == "row_share": - src_local = self.cu(value) - elif kind == "row_xmask": - src_local = self.tmp() - self.emit(f"{src_local} = OpBitwiseXor %uint {local} {self.cu(value)}") - elif kind == "row_mirror": - src_local = self.tmp() - self.emit(f"{src_local} = OpISub %uint {self.cu(15)} {local}") - else: # row_half_mirror - hi = self.tmp() - self.emit(f"{hi} = OpBitwiseAnd %uint {local} {self.cu(8)}") - lo = self.tmp() - self.emit(f"{lo} = OpBitwiseAnd %uint {local} {self.cu(7)}") - inv = self.tmp() - self.emit(f"{inv} = OpISub %uint {self.cu(7)} {lo}") - src_local = self.tmp() - self.emit(f"{src_local} = OpBitwiseOr %uint {hi} {inv}") - - if self.emulate: - # One workgroup exchange per DPP: every lane publishes src_val and its active bit, and the next round - # reads the selected lane. No subgroup operation is used, so this is exact on any subgroup size. - global_group = self.tmp() - self.emit(f"{global_group} = OpBitwiseAnd %uint {lane} {self.cu(~group_bits & 0xFFFFFFFF)}") - src_g = self.tmp() - self.emit(f"{src_g} = OpBitwiseOr %uint {global_group} {src_local}") - if in_bounds is not None: - safe_g = self.tmp() - self.emit(f"{safe_g} = OpSelect %uint {in_bounds} {src_g} {self.cu(0)}") - else: - safe_g = src_g - if fi: - # fi:1 fetches the inactive source as well; only an out-of-row lane is still invalid. - read, _ = self.x_round(data=src_val) - shuffled = read(safe_g) - src_ok = in_bounds if in_bounds is not None else "%true" - else: - lo_bit, hi_bit = self.lane_bits(self.active_b()) - read, (lo_word, hi_word) = self.x_round(data=src_val, bits=(lo_bit, hi_bit)) - shuffled = read(safe_g) - is_low = self.tmp() - self.emit(f"{is_low} = OpULessThan %bool {safe_g} {self.cu(32)}") - word = self.tmp() - self.emit(f"{word} = OpSelect %uint {is_low} {lo_word} {hi_word}") - sh = self.tmp() - self.emit(f"{sh} = OpBitwiseAnd %uint {safe_g} {self.cu(31)}") - bit = self.tmp() - self.emit(f"{bit} = OpShiftRightLogical %uint {word} {sh}") - one = self.tmp() - self.emit(f"{one} = OpBitwiseAnd %uint {bit} {self.cu(1)}") - active = self.tmp() - self.emit(f"{active} = OpINotEqual %bool {one} {self.cu(0)}") - if in_bounds is not None: - both = self.tmp() - self.emit(f"{both} = OpLogicalAnd %bool {in_bounds} {active}") - active = both - src_ok = active - else: - sgl = self.subgroup_lane() - sg_group = self.tmp() - self.emit(f"{sg_group} = OpBitwiseAnd %uint {sgl} {self.cu(~group_bits & 0xFFFFFFFF)}") - src_sg = self.tmp() - self.emit(f"{src_sg} = OpBitwiseOr %uint {sg_group} {src_local}") - if in_bounds is not None: - # Clamp an invalid source lane before the shuffle: its value is discarded below, but the lane index - # passed to OpGroupNonUniformShuffle must still be in range. - safe_sg = self.tmp() - self.emit(f"{safe_sg} = OpSelect %uint {in_bounds} {src_sg} {self.cu(0)}") - else: - safe_sg = src_sg - - if fi: - # fi:1 fetches the inactive source as well; only an out-of-row lane is still invalid. - src_ok = in_bounds if in_bounds is not None else "%true" - else: - ballot = self.tmp() - self.emit(f"{ballot} = OpGroupNonUniformBallot %v4uint_bal {self.cu(3)} {self.active_b()}") - self.uses_ballot = True - bit = self.tmp() - self.emit(f"{bit} = OpGroupNonUniformBallotBitExtract %bool {self.cu(3)} {ballot} {safe_sg}") - # Every lane runs the ballot, also the out-of-row lanes whose bit another lane reads (SHADER-529). - active = self.eager("%bool", bit) - if in_bounds is not None: - both = self.tmp() - self.emit(f"{both} = OpLogicalAnd %bool {in_bounds} {active}") - active = both - src_ok = active - if src.get("k") == "vgpr": - self.uses_subgroup = True - sh_val = self.tmp() - self.emit(f"{sh_val} = OpGroupNonUniformShuffle %uint {self.cu(3)} {src_val} {safe_sg}") - # The shuffle is read in the arms of selects below; every lane must still run it (SHADER-529). - shuffled = self.eager("%uint", sh_val) - else: - shuffled = src_val - - row = self.tmp() - self.emit(f"{row} = OpShiftRightLogical %uint {lane} {self.cu(4)}") - row_bit = self.tmp() - self.emit(f"{row_bit} = OpShiftRightLogical %uint {self.cu(row_mask)} {row}") - row_one = self.tmp() - self.emit(f"{row_one} = OpBitwiseAnd %uint {row_bit} {self.cu(1)}") - row_on = self.tmp() - self.emit(f"{row_on} = OpINotEqual %bool {row_one} {self.cu(0)}") - bank_sh = self.tmp() - self.emit(f"{bank_sh} = OpShiftRightLogical %uint {lane} {self.cu(2)}") - bank = self.tmp() - self.emit(f"{bank} = OpBitwiseAnd %uint {bank_sh} {self.cu(3)}") - bank_bit = self.tmp() - self.emit(f"{bank_bit} = OpShiftRightLogical %uint {self.cu(bank_mask)} {bank}") - bank_one = self.tmp() - self.emit(f"{bank_one} = OpBitwiseAnd %uint {bank_bit} {self.cu(1)}") - bank_on = self.tmp() - self.emit(f"{bank_on} = OpINotEqual %bool {bank_one} {self.cu(0)}") - enabled = self.tmp() - self.emit(f"{enabled} = OpLogicalAnd %bool {row_on} {bank_on}") - - zero = self.cu(0) - src0 = self.tmp() - self.emit(f"{src0} = OpSelect %uint {src_ok} {shuffled} {zero}") - if dpp8 is not None or bound: - write = enabled - else: - write = self.tmp() - self.emit(f"{write} = OpLogicalAnd %bool {enabled} {src_ok}") - args[1] = {"k": "ssa", "v": src0} - previous = self.dpp_guard - self.dpp_guard = write - try: - return self._insn({**ins, "args": args}) - finally: - self.dpp_guard = previous - - def permute_known_selector(self, src0, src1, selector): - """Emit only the selected bytes of V_PERM_B32 when S2 is known.""" - if selector == 0x03020100: - return src1 - if selector == 0x07060504: - return src0 - - bytes_ = [(selector >> offset) & 0xFF for offset in range(0, 32, 8)] - out = self.cu(sum(0xFF << (8 * i) for i, code in enumerate(bytes_) if code > 12)) - for i, code in enumerate(bytes_): - if code >= 12: - continue # Zero or 0xFF is already in out. - byte, result = self.tmp(), self.tmp() - if code < 8: - src = src1 if code < 4 else src0 - self.emit(f"{byte} = OpBitFieldUExtract %uint {src} {self.cu(8 * (code & 3))} {self.cu(8)}") - else: - src = src1 if code < 10 else src0 - sign = 15 + 16 * (code & 1) - self.emit(f"{byte} = OpBitFieldSExtract %uint {src} {self.cu(sign)} {self.cu(1)}") - self.emit(f"{result} = OpBitFieldInsert %uint {out} {byte} {self.cu(8 * i)} {self.cu(8)}") - out = result - return out - - def relative_vgpr_ptr(self, reg, offset): - """Use VGPR0 for out-of-range reads; callers also use the validity bit to guard writes.""" - index, valid, safe, ptr = (self.tmp() for _ in range(4)) - self.emit(f"{index} = OpIAdd %uint {self.cu(reg)} {offset}") - self.emit(f"{valid} = OpULessThan %bool {index} %n256") - self.emit(f"{safe} = OpSelect %uint {valid} {index} {self.cu(0)}") - self.emit(f"{ptr} = OpAccessChain %_ptr_Function_uint %vgpr {safe}") - return ptr, valid - - def _insn(self, ins): - op, a, mods = base_op(ins["op"]), ins["args"], ins["mods"] - if op in NOOPS or op.startswith("s_waitcnt"): - return - if op == "s_sendmsg" and a and self.stage == "gs": - t = a[0].get("t", "") - if "GS_OP_EMIT" in t: - self.gs_emit(end_primitive="GS_OP_EMIT_CUT" in t) - elif "GS_OP_CUT" in t: - self.gs_when_active("OpEndPrimitive") - elif "MSG_GS_DONE" not in t: - raise Unsupported("gs sendmsg " + t) - return - if op == "s_sendmsg" and a and "MSG_GS_ALLOC_REQ" in a[0].get("t", "") and self.stage == "ms": - # SHADER-766: use an atomic workgroup store so concurrent lanes/waves never cause - # SharedMemoryDataRace-RaceOnStore, while still storing %ms_counts when a non-zero - # wave (e.g. wave 1 in ms_wave_info_s3, where local_index != 0) sends the alloc. - m = self.tmp() - self.emit(f"{m} = OpLoad %uint %m0") - self.emit(f"OpAtomicStore %ms_counts {self.cu(2)} {self.cu(0)} {m}") - self.ms_alloc = True - return - if op == "s_sendmsg" and a and "MSG_ORDERED_PS_DONE" in a[0].get("t", ""): - # End of the POPS ordered section. The fragment-shader interlock already ends at shader exit (a longer - # critical section, same ordering), so nothing to do here. - return - if op in ("s_setreg_imm32_b32", "s_setreg_b32"): - self.mode_write(op, a) - return - if op == "s_round_mode": - if len(a) != 1 or a[0]["k"] != "imm": - raise Unsupported(op + " requires an immediate") - mode = a[0]["v"] - if mode & 3: - raise Unsupported(op + ": only nearest-even FP32 rounding is modelled") - self.write_half_round_mode(op, (mode >> 2) & 3) - return - if op == "s_denorm_mode": - raise Unsupported(op + ": denormal mode writes are not modelled") - if op == "s_mov_b32" and self.wave64: - to_mask_dst, dst_half = self._mask_b32_dst_half(a[0], a[1:2]) - if to_mask_dst and self.holds_lane_mask(a[1]) and self.mask_half(a[1]) not in (None, dst_half): - val = self._mask_b32_src(a[1], dst_half) - self._store_b32_mask_dst(a[0], val, True, dst_half) - return - if op == "s_mov_b32" and a[0]["k"] == "special" and a[0]["t"] in ("exec_lo", "exec_hi") and \ - (a[0]["t"] == "exec_hi" or a[1]["k"] in ("imm", "fimm") or - (a[1]["k"] == "sgpr" and not self.holds_lane_mask(a[1]))): - src = a[1] - const = (src["v"] & 0xFFFFFFFF) if src["k"] == "imm" else None - if src["k"] == "fimm": - const = struct.unpack("> 32) - else: - raise Unsupported(op + " source") - rlo, rhi = self.tmp(), self.tmp() - self.emit(f"{rlo} = OpBitReverse %uint {hi}") - self.emit(f"{rhi} = OpBitReverse %uint {lo}") - self.store_reg("sgpr", d["r"], rlo) - self.store_reg("sgpr", d["r"] + 1, rhi) - elif op == "s_brev_b32": - x = self.src_u(a[1]) - r = self.tmp() - self.emit(f"{r} = OpBitReverse %uint {x}") - self.dst(a[0], r) - elif op in ("s_quadmask_b32", "s_quadmask_b64", "s_bitreplicate_b64_b32"): - # RDNA2 ISA SOP1, on scalar data (a lane-mask operand stays Unsupported: each invocation holds only its - # own lane's bit, and these ops read the other lanes of its quad or move bits between lanes): - # s_quadmask_b32: D[i] = OR of S0[4i+3:4i], i in 0..7, D[31:8] = 0; SCC = D != 0. - # s_quadmask_b64: the same for 16 quads of the 64-bit S0, D[63:16] = 0; SCC = D != 0. - # s_bitreplicate_b64_b32: D[2i+1] = D[2i] = S0[i], i in 0..31; SCC is not written. - d, x = a[0], a[1] - wide_src = op == "s_quadmask_b64" - wide_dst = op != "s_quadmask_b32" - if self.is_mask_op(x): - raise Unsupported(op + " on a lane mask") - if d["k"] == "special" and d.get("t", "").startswith(("exec", "vcc")): - if op != "s_bitreplicate_b64_b32" or d["t"] != "exec": - raise Unsupported(op + " on a lane mask") - # EXEC's bit for lane L comes from scalar-source bit L // 2. - shift, shifted, bit = (self.tmp() for _ in range(3)) - lane = self.wave_lane() - word = self.src_u(x) - self.emit(f"{shift} = OpShiftRightLogical %uint {lane} {self.cu(1)}") - self.emit(f"{shifted} = OpShiftRightLogical %uint {word} {shift}") - self.emit(f"{bit} = OpBitwiseAnd %uint {shifted} {self.cu(1)}") - self.set_exec(bit) - return - if wide_src: - lo, hi = self.src64_data(x, op) - words = [lo, hi] - else: - words = [self.src_u(x)] - if op == "s_bitreplicate_b64_b32": - out = [] - for hi in (0, 1): - t = self.u16_half(words[0], hi) - # Spread the 16 bits to the even positions, then copy each to the odd one above it. - for sh, m in ((8, 0x00FF00FF), (4, 0x0F0F0F0F), (2, 0x33333333), (1, 0x55555555)): - u, o, n = self.tmp(), self.tmp(), self.tmp() - self.emit(f"{u} = OpShiftLeftLogical %uint {t} {self.cu(sh)}") - self.emit(f"{o} = OpBitwiseOr %uint {t} {u}") - self.emit(f"{n} = OpBitwiseAnd %uint {o} {self.cu(m)}") - t = n - u, r = self.tmp(), self.tmp() - self.emit(f"{u} = OpShiftLeftLogical %uint {t} {self.cu(1)}") - self.emit(f"{r} = OpBitwiseOr %uint {t} {u}") - out.append(r) - self.dst64_data(d, out[0], out[1], op) - else: - parts = [] - for w in words: - # Fold each nibble into its low bit, then pack bits 0, 4, ..., 28 into bits 0..7. - t = w - for sh in (1, 2): - u, o = self.tmp(), self.tmp() - self.emit(f"{u} = OpShiftRightLogical %uint {t} {self.cu(sh)}") - self.emit(f"{o} = OpBitwiseOr %uint {t} {u}") - t = o - for sh, m in ((None, 0x11111111), (3, 0x03030303), (6, 0x000F000F), (12, 0xFF)): - if sh is not None: - u, o = self.tmp(), self.tmp() - self.emit(f"{u} = OpShiftRightLogical %uint {t} {self.cu(sh)}") - self.emit(f"{o} = OpBitwiseOr %uint {t} {u}") - t = o - n = self.tmp() - self.emit(f"{n} = OpBitwiseAnd %uint {t} {self.cu(m)}") - t = n - parts.append(t) - r = parts[0] - if wide_src: - u, o = self.tmp(), self.tmp() - self.emit(f"{u} = OpShiftLeftLogical %uint {parts[1]} {self.cu(8)}") - self.emit(f"{o} = OpBitwiseOr %uint {r} {u}") - r = o - if wide_dst: - self.dst64_data(d, r, self.cu(0), op) - else: - self.dst(d, r) - self.scc_nonzero(r) - elif op == "v_cvt_f16_f32": - # Low 16 bits get the f16; on GFX10 the high half is kept (partial write: Mesa ACO instr_is_16bit lists - # v_cvt_f16_f32 as 16-bit for gfx_level >= GFX10). - # VOP3 omod and clamp apply to the f16 (ACO: dst(F16)), in the order an RX 6800 applies them: round, omod - # (f16_omod), then clamp. They were dropped until 2026-11-22. - x = self.src_f(a[1]) - h = self.f16_omod(self.f16_res(x), mods) - if "clamp" in mods: - v2, f = self.tmp(), self.tmp() - self.emit(f"{v2} = OpExtInst %v2float %glsl UnpackHalf2x16 {h}") - self.emit(f"{f} = OpCompositeExtract %float {v2} 0") - h = self.f16_bits(self.clamp_mods(f, ["clamp"])) # exact: the clamped value is an f16 - self.write_lo16(a[0], h) - elif op == "s_mulk_i32": - v = a[1]["v"] & 0xFFFF - k = v - 0x10000 if v & 0x8000 else v - x = self.src_u(a[0]) - r = self.tmp() - self.emit(f"{r} = OpIMul %uint {x} {self.cu(k)}") - self.dst(a[0], r) - elif op == "v_readfirstlane_b32": - # sD = vS of the first lane that is on in EXEC (lane 0 if none is): one value for the whole wave, so - # a ballot of the active lanes, its lowest bit, and a shuffle from that lane. Until 2026-11-21 every - # lane took its own value. That is the same thing only when all lanes hold the value, and after a - # kill the dead lanes don't: where the result is an address (a loop that picks a descriptor per group - # of lanes), they loaded from wherever their stale register pointed. - if a[1]["k"] == "vgpr" and ("v", a[1]["r"]) in self.cur_masks: - # A lane mask that went through the vector unit (three SGPRs ORed with v_or3_b32, say). The - # hardware reads the first lane's copy of the whole mask; here the lane's own copy is its bit. - self.dst(a[0], self.src_u(a[1])) - return - if self.wave32_fragment: - self.uses_subgroup = self.uses_ballot = True - v, act = self.src_u(a[1]), self.active_b() - ballot, any_, lsb, first, r = (self.tmp() for _ in range(5)) - self.emit(f"{ballot} = OpGroupNonUniformBallot %v4uint_bal {self.cu(3)} {act}") - word = self.wave32_ballot_word(ballot) - self.emit(f"{any_} = OpINotEqual %bool {word} {self.cu(0)}") - self.emit(f"{lsb} = OpExtInst %uint %glsl FindILsb {word}") - self.emit(f"{first} = OpSelect %uint {any_} {lsb} {self.wave32_first_running_lane()}") - self.g_shuffle(r, v, first) - self.dst(a[0], r) - return - if self.emulate: - # The wave's active lanes as two mask words and every lane's value, in one round. - v, act = self.src_u(a[1]), self.active_b() - lo_in, hi_in = self.lane_bits(act) - read, (lo, hi) = self.x_round(data=v, bits=(lo_in, hi_in)) - lz, hz, l, h, h32, fh, first = (self.tmp() for _ in range(7)) - self.emit(f"{lz} = OpINotEqual %bool {lo} {self.cu(0)}") - self.emit(f"{hz} = OpINotEqual %bool {hi} {self.cu(0)}") - self.emit(f"{l} = OpExtInst %uint %glsl FindILsb {lo}") - self.emit(f"{h} = OpExtInst %uint %glsl FindILsb {hi}") - self.emit(f"{h32} = OpIAdd %uint {h} {self.cu(32)}") - self.emit(f"{fh} = OpSelect %uint {hz} {h32} {self.cu(0)}") - self.emit(f"{first} = OpSelect %uint {lz} {l} {fh}") - self.dst(a[0], read(first)) - return - self.uses_subgroup = self.uses_ballot = self.uses_vote = True - v, act = self.src_u(a[1]), self.active_b() - bal, lsb, any_, first, r = (self.tmp() for _ in range(5)) - self.emit(f"{bal} = OpGroupNonUniformBallot %v4uint_bal {self.cu(3)} {act}") - if self.stage == "vs": - lsb = self.ballot_lsb_by_words(bal) - else: - self.emit(f"{lsb} = OpGroupNonUniformBallotFindLSB %uint {self.cu(3)} {bal}") - self.emit(f"{any_} = OpGroupNonUniformAny %bool {self.cu(3)} {act}") - self.emit(f"{first} = OpSelect %uint {any_} {lsb} {self.cu(0)}") - self.emit(f"{r} = OpGroupNonUniformShuffle %uint {self.cu(3)} {v} {first}") - self.dst(a[0], r) - elif op in ("image_sample_o", "image_sample_lz_o", "image_sample_l_o", "image_sample_b_o", - "image_sample_c_lz_o", "image_sample_c_o", "image_sample_c_b_o", "image_sample_cl_o", "image_sample_b_cl_o", - "image_sample_c_cl_o", "image_sample_c_b_cl_o") or op in ("image_sample", "image_sample_lz", "image_sample_l", "image_sample_b", "image_sample_c_lz", - "image_sample_c_l", "image_sample_c", "image_sample_c_b", "image_sample_cl", "image_sample_b_cl", "image_sample_c_cl", - "image_sample_c_b_cl", - "image_sample_d", "image_sample_d_cl", "image_load", "image_gather4_lz", "image_gather4_l", - "image_gather4_lz_o", "image_gather4_l_o") or op in self.GATHER4_LOD_OPS: - self.image_op(op, a, mods) - self.mimg_status(op, a, mods) - elif op in ("v_sin_f16", "v_cos_f16"): - self._validate_unary_f16(op, ins["op"], a, mods) - sel, dhi = self.opsel_bits(mods, 1) - f = self.f16_in(a[1], sel[0]) - t = self.turn_angle(f) - r = self.tmp() - self.emit(f"{r} = OpExtInst %float %glsl {'Sin' if 'sin' in op else 'Cos'} {t}") - r = self.trig_exact_zero(op, f, r) - r = self.clamp_f16(r, mods) - self.f16_out(a[0], r, dhi, mode=False) # sin ignores MODE rounding on hardware (RX 6800, SHADER-35); cos is unmeasured, assumed like it - elif op in ("v_pk_add_u16", "v_pk_add_i16", "v_pk_sub_u16", "v_pk_sub_i16", "v_pk_mul_lo_u16", - "v_pk_mad_u16", "v_pk_mad_i16", "v_pk_max_u16", "v_pk_max_i16", "v_pk_min_u16", "v_pk_min_i16"): - # Packed 16-bit integer ops (VOP3P, RDNA2 ISA): result half 0 takes each source's half from op_sel[i], - # result half 1 from op_sel_hi[i] (defaults [0,..] and [1,..]); each half is computed on its own and - # wraps to 16 bits. clamp saturates on add/sub/mad (the exact value fits in 32 bits: - # 0xFFFF * 0xFFFF + 0xFFFF < 2^32, and the i16 forms within int32), whereas on mul_lo/max/min - # VOP3P clamp is a hardware no-op (measured on gfx1036: v_pk_mul_lo_u16 clamp wraps modulo 2^16 - # rather than saturating to 0xFFFF, and max/min results are unchanged). neg_lo/neg_hi are float-only. - # Constant operands are treated as 32-bit dwords: op_sel=0 selects bits [15:0], op_sel=1 selects [31:16] - # (measured on gfx1036). Positive inlines zero-extend, negative inlines sign-extend, 32-bit literals - # retain their full dword; OpBitField*Extract at 16*sl[i] lowers this directly. - def bits(name, default): - m = next((m for m in mods if m.startswith(name + ":")), None) - return [int(v) for v in m.split("[")[1].rstrip("]").split(",")] if m else default - ns = 3 if "_mad_" in op else 2 - sel, selhi = bits("op_sel", [0] * ns), bits("op_sel_hi", [1] * ns) - if (len(sel) != ns or len(selhi) != ns - or any(m != "clamp" and not m.startswith(("op_sel:", "op_sel_hi:", "neg_lo:", "neg_hi:")) for m in mods) - or any(any(bits(n, [0] * ns)) for n in ("neg_lo", "neg_hi"))): - raise Unsupported(op + " modifiers") - kind = op[len("v_pk_"):].rsplit("_", 1)[0] # add, sub, mul_lo, mad, max, min - signed = op.endswith("i16") - clamp = "clamp" in mods and kind in ("add", "sub", "mad") - srcs = [self.src_u(t) for t in a[1:1 + ns]] - ext = "OpBitFieldSExtract" if signed else "OpBitFieldUExtract" - halves = [] - for sl in (sel, selhi): - v = [] - for i in range(ns): - e = self.tmp() - self.emit(f"{e} = {ext} %uint {srcs[i]} {self.cu(16 * sl[i])} {self.cu(16)}") - v.append(e) - r = self.tmp() - if kind in ("add", "sub"): - self.emit(f"{r} = {'OpIAdd' if kind == 'add' else 'OpISub'} %uint {v[0]} {v[1]}") - elif kind == "mul_lo": - # The low 16 bits of the product as ((x << 16) * y) >> 16, not (x * y) & 0xffff: the AMD Windows driver - # (26.10.1) dropped that mask when the other half of the result folded to zero (a constant half of 0: - # 0x1234 * 0xaaaa came out 0x0c229e88 for 0x00009e88). - xs = self.tmp() - self.emit(f"{xs} = OpShiftLeftLogical %uint {v[0]} {self.cu(16)}") - p16 = self.tmp() - self.emit(f"{p16} = OpIMul %uint {xs} {v[1]}") - self.emit(f"{r} = OpShiftRightLogical %uint {p16} {self.cu(16)}") - elif kind == "mad": - m = self.tmp() - self.emit(f"{m} = OpIMul %uint {v[0]} {v[1]}") - self.emit(f"{r} = OpIAdd %uint {m} {v[2]}") - else: - f = ("S" if signed else "U") + ("Max" if kind == "max" else "Min") - self.emit(f"{r} = OpExtInst %uint %glsl {f} {v[0]} {v[1]}") - if clamp: - c = self.tmp() - if signed: - self.emit(f"{c} = OpExtInst %uint %glsl SClamp {r} {self.cu(0xFFFF8000)} {self.cu(0x7FFF)}") - elif kind == "sub": - # unsigned difference below 0 clamps to 0: compare before the wrap - lt = self.tmp() - self.emit(f"{lt} = OpULessThan %bool {v[0]} {v[1]}") - self.emit(f"{c} = OpSelect %uint {lt} {self.cu(0)} {r}") - else: - self.emit(f"{c} = OpExtInst %uint %glsl UMin {r} {self.cu(0xFFFF)}") - r = c - r16 = self.tmp() - self.emit(f"{r16} = OpBitwiseAnd %uint {r} {self.cu(0xFFFF)}") - halves.append(r16) - hi, r = self.tmp(), self.tmp() - self.emit(f"{hi} = OpShiftLeftLogical %uint {halves[1]} {self.cu(16)}") - self.emit(f"{r} = OpBitwiseOr %uint {halves[0]} {hi}") - self.dst(a[0], r) - elif op in ("v_dot2_i32_i16", "v_dot2_u32_u16", "v_dot4_u32_u8", "v_dot8_i32_i4", "v_dot8_u32_u4", - "v_dot2c_i32_i16", "v_dot2c_u32_u16", "v_dot4c_u32_u8", "v_dot8c_i32_i4", "v_dot8c_u32_u4"): - # Packed integer dot products (RDNA2 ISA VOP3P and VOP2 accumulating v_dot*c_*): - # D = sum_{k=0..N-1} (S0.elem[k] * S1.elem[k]) + acc (acc = S2 for VOP3P, old D for VOP2) - # Wrapping at 32 bits by default; clamp saturates to [INT32_MIN, INT32_MAX] (signed) or - # [0, UINT32_MAX] (unsigned). For VOP3P, hardware default is op_sel:[0,0,0] and op_sel_hi:[1,1,1]; - # any other op_sel/op_sel_hi, neg_lo/neg_hi, DPP/SDWA, or source neg/abs are refused. For VOP2 - # v_dot*c_*, only optional clamp (VOP3 _e64) is accepted and D must be a VGPR. - is_c = op in ("v_dot2c_i32_i16", "v_dot2c_u32_u16", "v_dot4c_u32_u8", "v_dot8c_i32_i4", "v_dot8c_u32_u4") - if is_c: - if a[0]["k"] != "vgpr": - raise Unsupported(op + " destination") - if any(m != "clamp" for m in mods) or ins["op"].endswith(("_dpp", "_sdwa")) or any( - s.get("neg") or s.get("abs") for s in a): - raise Unsupported(op + " modifiers") - x, y, acc = self.src_u(a[1]), self.src_u(a[2]), self.src_u(a[0]) - else: - def bits(name, default): - m = next((m for m in mods if m.startswith(name + ":")), None) - return [int(v) for v in m.split("[")[1].rstrip("]").split(",")] if m else default - other = [m for m in mods if m != "clamp" and not m.startswith(("op_sel:", "op_sel_hi:"))] - if (other or ins["op"].endswith(("_dpp", "_sdwa")) or any(s.get("neg") or s.get("abs") for s in a) or - bits("op_sel", [0, 0, 0]) != [0, 0, 0] or bits("op_sel_hi", [1, 1, 1]) != [1, 1, 1]): - raise Unsupported(op + " modifiers") - x, y, acc = self.src_u(a[1]), self.src_u(a[2]), self.src_u(a[3]) - width = 16 if ("_dot2_" in op or "_dot2c_" in op) else (8 if "_dot4" in op else 4) - signed = op.endswith(("i16", "i4")) - clamp = "clamp" in mods - ext = "OpBitFieldSExtract" if signed else "OpBitFieldUExtract" - prods = [] - for off in range(0, 32, width): - xe, ye, p = self.tmp(), self.tmp(), self.tmp() - self.emit(f"{xe} = {ext} %uint {x} {self.cu(off)} {self.cu(width)}") - self.emit(f"{ye} = {ext} %uint {y} {self.cu(off)} {self.cu(width)}") - self.emit(f"{p} = OpIMul %uint {xe} {ye}") - prods.append(p) - if not clamp: - r = prods[0] - for term in prods[1:] + [acc]: - nxt = self.tmp() - self.emit(f"{nxt} = OpIAdd %uint {r} {term}") - r = nxt - elif not signed: - r = prods[0] - for term in prods[1:] + [acc]: - w, ovf, s = self.tmp(), self.tmp(), self.tmp() - self.emit(f"{w} = OpIAdd %uint {r} {term}") - self.emit(f"{ovf} = OpULessThan %bool {w} {r}") - self.emit(f"{s} = OpSelect %uint {ovf} {self.cu(0xFFFFFFFF)} {w}") - r = s - else: - def sadd_carry(lhs, rhs, carry_in): - w, xw, yw, ob, ov, na, st, d, nc = (self.tmp() for _ in range(9)) - self.emit(f"{w} = OpIAdd %uint {lhs} {rhs}") - self.emit(f"{xw} = OpBitwiseXor %uint {lhs} {w}") - self.emit(f"{yw} = OpBitwiseXor %uint {rhs} {w}") - self.emit(f"{ob} = OpBitwiseAnd %uint {xw} {yw}") - self.emit(f"{ov} = OpUGreaterThanEqual %bool {ob} {self.cu(0x80000000)}") - self.emit(f"{na} = OpUGreaterThanEqual %bool {lhs} {self.cu(0x80000000)}") - self.emit(f"{st} = OpSelect %uint {na} {self.cu(0xFFFFFFFF)} {self.cu(1)}") - self.emit(f"{d} = OpSelect %uint {ov} {st} {self.cu(0)}") - self.emit(f"{nc} = OpIAdd %uint {carry_in} {d}") - return w, nc - r = prods[0] - carry = self.cu(0) - for term in prods[1:]: - if width == 16: - r, carry = sadd_carry(r, term, carry) - else: - nxt = self.tmp() - self.emit(f"{nxt} = OpIAdd %uint {r} {term}") - r = nxt - r, carry = sadd_carry(r, acc, carry) - nz, neg_c, bound, sat = (self.tmp() for _ in range(4)) - self.emit(f"{nz} = OpINotEqual %bool {carry} {self.cu(0)}") - self.emit(f"{neg_c} = OpUGreaterThanEqual %bool {carry} {self.cu(0x80000000)}") - self.emit(f"{bound} = OpSelect %uint {neg_c} {self.cu(0x80000000)} {self.cu(0x7FFFFFFF)}") - self.emit(f"{sat} = OpSelect %uint {nz} {bound} {r}") - r = sat - self.dst(a[0], r) - elif op in ("v_dot2_f32_f16", "v_dot2c_f32_f16"): - # Half-to-float dot product (RDNA2 ISA): D = S0.lo*S1.lo + S0.hi*S1.hi + acc (acc = S2 for VOP3P - # v_dot2_f32_f16, old D for VOP2 v_dot2c_f32_f16). - if a[0]["k"] != "vgpr": - raise Unsupported(op + " destination") - if ins["op"].endswith(("_dpp", "_sdwa")) or any(s.get("neg") or s.get("abs") for s in a): - raise Unsupported(op + " modifiers") - if op == "v_dot2_f32_f16": - def bits(name, default): - m = next((m for m in mods if m.startswith(name + ":")), None) - return [int(v) for v in m.split("[")[1].rstrip("]").split(",")] if m else default - other = [m for m in mods if m != "clamp" and not m.startswith(("op_sel:", "op_sel_hi:", "neg_lo:", "neg_hi:"))] - if other: - raise Unsupported(op + " modifiers") - sel = bits("op_sel", [0, 0, 0]) - selhi = bits("op_sel_hi", [1, 1, 1]) - nlo = bits("neg_lo", [0, 0, 0]) - nhi = bits("neg_hi", [0, 0, 0]) - if any(len(v) != 3 or any(b not in (0, 1) for b in v) for v in (sel, selhi, nlo, nhi)): - raise Unsupported(op + " modifiers") - if sel[2] != 0 or selhi[2] != 1 or nhi[2] != 0: - raise Unsupported(op + " modifiers") - a0 = self.f16_in(a[1], sel[0]) - a1 = self.f16_in(a[1], selhi[0]) - b0 = self.f16_in(a[2], sel[1]) - b1 = self.f16_in(a[2], selhi[1]) - if nlo[0]: - t = self.tmp() - self.emit(f"{t} = OpFNegate %float {a0}") - a0 = t - if nhi[0]: - t = self.tmp() - self.emit(f"{t} = OpFNegate %float {a1}") - a1 = t - if nlo[1]: - t = self.tmp() - self.emit(f"{t} = OpFNegate %float {b0}") - b0 = t - if nhi[1]: - t = self.tmp() - self.emit(f"{t} = OpFNegate %float {b1}") - b1 = t - acc = self.flush_f32(self.src_f(a[3])) - if nlo[2]: - t = self.tmp() - self.emit(f"{t} = OpFNegate %float {acc}") - acc = t - else: - if any(m != "clamp" for m in mods): - raise Unsupported(op + " modifiers") - a0 = self.f16_in(a[1], 0) - a1 = self.f16_in(a[1], 1) - b0 = self.f16_in(a[2], 0) - b1 = self.f16_in(a[2], 1) - acc = self.flush_f32(self.src_f(a[0])) - p0, p1, s, r = (self.tmp() for _ in range(4)) - self.emit(f"{p0} = OpFMul %float {a0} {b0}") - self.emit(f"{p1} = OpFMul %float {a1} {b1}") - self.emit(f"{s} = OpFAdd %float {p0} {p1}") - self.emit(f"{r} = OpFAdd %float {s} {acc}") - r = self.clamp_mods(r, ["clamp"] if "clamp" in mods else []) - self.dst(a[0], self.tou(r)) - elif op in ("v_pk_lshlrev_b16", "v_pk_lshrrev_b16", "v_pk_ashrrev_i16"): - # Packed 16-bit shifts (VOP3P): result half h = src1 half (op_sel / op_sel_hi) shifted by src0 half & 15. - # A half of a register is read with a shift and a mask, not with OpBitField{S,U}Extract at offset 16, - # as for every other 16-bit half reader (docs/design.md, "16-bit high-half reads", #1506). The field - # extract here is what @Dark0rz measured miscompiled on an AMD Windows driver 25.10.36 (gfx1036): the - # offset came back taken mod 16, so both result halves read the low half of the source, in 5 of the - # 2,000 wave32 programs of `tools/valu_fuzz.py --family f16 --seed 1`. The same programs run clean on - # a second gfx1036 with driver 31.0.24002.92 (2000/2000 match), which is why this is a driver-proof - # lowering and not a value change: on 200,010 inputs (0, 1, 0xFFFF, 0x10000, 0x80000000, 0xFFFFFFFF, - # 0x7FFFFFFF, 0x8000 and random) BitField{S,U}Extract(x, 16, 16) equals x >> 16 with the matching - # right shift, and BitFieldUExtract(x, 16, 4) equals (x >> 16) & 15. - def bits(name, default): - m = next((m for m in mods if m.startswith(name + ":")), None) - if m is None: - return default - try: - body = m.split("[", 1)[1] - if not body.endswith("]"): - raise Unsupported(op + " modifiers") - return [int(v) for v in body[:-1].split(",")] - except (IndexError, ValueError): - raise Unsupported(op + " modifiers") from None - if "clamp" in mods: - raise Unsupported(op + " clamp") - if (any(not m.startswith(("op_sel:", "op_sel_hi:", "neg_lo:", "neg_hi:")) for m in mods) - or any(s.get("neg") or s.get("abs") for s in a)): - raise Unsupported(op + " modifiers") - sel, selhi = bits("op_sel", [0, 0]), bits("op_sel_hi", [1, 1]) - neg_lo, neg_hi = bits("neg_lo", [0, 0]), bits("neg_hi", [0, 0]) - # a three-entry list (op_sel:[1,0,0], as in tests/semantic/fixtures/disasm/ps_ops6.s) is read by its first - # two entries, as before #3853 - sel, selhi, neg_lo, neg_hi = (v[:2] if len(v) == 3 else v for v in (sel, selhi, neg_lo, neg_hi)) - if (len(sel) != 2 or len(selhi) != 2 or len(neg_lo) != 2 or len(neg_hi) != 2 - or any(b not in (0, 1) for b in sel + selhi) or any(neg_lo) or any(neg_hi)): - raise Unsupported(op + " modifiers") - sh_src, val_src = self.src_u(a[1]), self.src_u(a[2]) - signed = op.endswith("i16") - halves = [] - for h, sl in ((0, sel), (1, selhi)): - amt, val, am, r16 = self.tmp(), self.tmp(), self.tmp(), self.tmp() - if sl[0]: - half = self.tmp() - self.emit(f"{half} = OpShiftRightLogical %uint {sh_src} {self.cu(16)}") - self.emit(f"{amt} = OpBitwiseAnd %uint {half} {self.cu(15)}") - else: - self.emit(f"{amt} = OpBitFieldUExtract %uint {sh_src} {self.cu(0)} {self.cu(4)}") - if sl[1]: - # The high half: x >> 16 already extends it the right way for the shift that follows. - right = "OpShiftRightArithmetic" if signed else "OpShiftRightLogical" - self.emit(f"{val} = {right} %uint {val_src} {self.cu(16)}") - else: - ext = "OpBitFieldSExtract" if signed else "OpBitFieldUExtract" - self.emit(f"{val} = {ext} %uint {val_src} {self.cu(0)} {self.cu(16)}") - k = {"v_pk_lshlrev_b16": "OpShiftLeftLogical", "v_pk_lshrrev_b16": "OpShiftRightLogical", - "v_pk_ashrrev_i16": "OpShiftRightArithmetic"}[op] - self.emit(f"{am} = {k} %uint {val} {amt}") - self.emit(f"{r16} = OpBitwiseAnd %uint {am} {self.cu(0xFFFF)}") - halves.append(r16) - hi, r = self.tmp(), self.tmp() - self.emit(f"{hi} = OpShiftLeftLogical %uint {halves[1]} {self.cu(16)}") - self.emit(f"{r} = OpBitwiseOr %uint {halves[0]} {hi}") - self.dst(a[0], r) - elif op in ("v_sin_f32", "v_cos_f32"): - # RDNA takes the angle in turns: reduce in turns, then sin/cos(x * 2*pi). - x = self.src_f(a[1]) - t = self.turn_angle(x) - r = self.tmp() - self.emit(f"{r} = OpExtInst %float %glsl {'Sin' if 'sin' in op else 'Cos'} {t}") - r = self.trig_exact_zero(op, x, r) - self.dst(a[0], self.tou(self.clamp_mods(r, mods))) - elif op == "v_rndne_f32": - x = self.src_f(a[1]) - r = self.tmp() - self.emit(f"{r} = OpExtInst %float %glsl RoundEven {x}") - self.dst(a[0], self.tou(self.clamp_mods(r, mods))) - elif op in ("v_madak_f32", "v_madmk_f32"): - # madak D = S0 * S1 + K, printed `vdst, src0, vsrc1, K`; madmk D = S0 * K + S1, printed - # `vdst, src0, K, vsrc1`. In print order both are a[1] * a[2] + a[3]. Until 2026-11-21 madmk read - # a[3] as the factor, so it computed S0 * S1 + K. - x, y, z = (self.src_f(t) for t in a[1:4]) - m, r = self.tmp(), self.tmp() - self.emit(f"{m} = OpFMul %float {x} {y}") - self.emit(f"{r} = OpFAdd %float {m} {z}") - self.dst(a[0], self.tou(r)) - elif op == "v_bfi_b32": - mask = None if "sdwa_sel" in a[1] else self.imm_val(a[1]) - y, z = (self.src_u(t) for t in a[2:4]) - if mask == 0: - self.dst(a[0], z) - return - if mask == 0xFFFFFFFF: - self.dst(a[0], y) - return - if mask is not None: - offset = (mask & -mask).bit_length() - 1 - width = mask.bit_count() - if mask == ((1 << width) - 1) << offset: - # RDNA takes the field from its final bit positions; SPIR-V takes its low bits. - if offset: - shifted = self.tmp() - self.emit(f"{shifted} = OpShiftRightLogical %uint {y} {self.cu(offset)}") - y = shifted - r = self.tmp() - self.emit(f"{r} = OpBitFieldInsert %uint {z} {y} {self.cu(offset)} {self.cu(width)}") - self.dst(a[0], r) - return - x, n = self.cu(mask), self.cu(~mask) - else: - x, n = self.src_u(a[1]), self.tmp() - self.emit(f"{n} = OpNot %uint {x}") - p, q, r = self.tmp(), self.tmp(), self.tmp() - self.emit(f"{p} = OpBitwiseAnd %uint {x} {y}") - self.emit(f"{q} = OpBitwiseAnd %uint {n} {z}") - self.emit(f"{r} = OpBitwiseOr %uint {p} {q}") - self.dst(a[0], r) - elif op in ("v_lshl_or_b32", "v_lshl_add_u32", "v_add_lshl_u32", "v_or3_b32", "v_xor3_b32", - "v_add3_u32", "v_and_or_b32_"): - x, y, z = (self.src_u(t) for t in a[1:4]) - r = self.tmp() - if op in ("v_lshl_or_b32", "v_lshl_add_u32"): - s, m = self.tmp(), self.tmp() - self.emit(f"{m} = OpBitwiseAnd %uint {y} {self.cu(31)}") - self.emit(f"{s} = OpShiftLeftLogical %uint {x} {m}") - self.emit(f"{r} = {'OpBitwiseOr' if op == 'v_lshl_or_b32' else 'OpIAdd'} %uint {s} {z}") - elif op == "v_add_lshl_u32": - s, m = self.tmp(), self.tmp() - self.emit(f"{s} = OpIAdd %uint {x} {y}") - self.emit(f"{m} = OpBitwiseAnd %uint {z} {self.cu(31)}") - self.emit(f"{r} = OpShiftLeftLogical %uint {s} {m}") - else: - k = {"v_or3_b32": "OpBitwiseOr", "v_xor3_b32": "OpBitwiseXor", "v_add3_u32": "OpIAdd"}[op] - s = self.tmp() - self.emit(f"{s} = {k} %uint {x} {y}") - self.emit(f"{r} = {k} %uint {s} {z}") - self.dst(a[0], r) - elif op == "v_pack_b32_f16": - # dst = f16(src0) | f16(src1) << 16, each taken from the low half (op_sel picks high halves). - # neg/abs act on the selected 16-bit half of each source as plain bit moves, abs (clear bit 15) first and - # neg (xor bit 15) second: on an AMD Radeon Graphics RDNA2 iGPU (gfx1036) ``-v0``, ``|v0|``, and ``-|v0|`` - # were measured with 1,088 raw kernels across wave32 and wave64 (0 mismatches; #1548 SHADER-260). abs clears - # bit 15, neg flips it, and -|v0| sets bit 15 across all edge floats and NaNs; under IEEE 0 sNaN payloads are - # kept, under IEEE 1 they are quieted (SHADER-190). The translator moves the bits, which is exact under IEEE 0. - sel = next((m for m in mods if m.startswith("op_sel:")), "op_sel:[0,0,0]") - sb = [int(x) for x in sel.split("[")[1].rstrip("]").split(",")] - halves = [] - for i, src in enumerate(a[1:3]): - u = self.src_h(src) - m = self.u16_half(u, sb[i]) - if src.get("abs"): - # The ISA defines ABS on a float operand as |S|, clearing the sign bit (bit 15), applied before - # neg. Measured natively on gfx1036 across 1,088 raw kernels: clears bit 15 on all values. - a_ = self.tmp() - self.emit(f"{a_} = OpBitwiseAnd %uint {m} {self.cu(0x7FFF)}") - m = a_ - if src.get("neg"): - # SHADER-260, measured on gfx1036: a `neg` on this instruction flips the sign bit of the half it - # packs, before any quieting (0x7c01 -> 0xfc01 in IEEE mode 0, -> 0xfe01 in mode 1), in either - # half and with op_sel. It used to be refused along with every other modifier. - n = self.tmp() - self.emit(f"{n} = OpBitwiseXor %uint {m} {self.cu(0x8000)}") - m = n - halves.append(m) - hi, r = self.tmp(), self.tmp() - self.emit(f"{hi} = OpShiftLeftLogical %uint {halves[1]} {self.cu(16)}") - self.emit(f"{r} = OpBitwiseOr %uint {halves[0]} {hi}") - self.dst(a[0], r) - elif op in ("v_cmp_class_f32", "v_cmpx_class_f32", "v_cmp_class_f16", "v_cmpx_class_f16"): - # f64 goes to cmp_class_f64 below (the operand checks test_cmp_class_f64 pins); cmp_class's own f64 - # branch, merged later, has no operand-form checks. - self.cmp_class(a, exec_only=op.startswith("v_cmpx_"), ty=op.rsplit("_", 1)[1], mods=mods) - elif op in ("v_ffbl_b32", "v_ffbh_u32", "s_flbit_i32_b32") or \ - (op == "s_ff1_i32_b32" and not self.holds_lane_mask(a[1])): # of a lane mask: further down - x = self.lane_mask_word(a[1]) if op == "s_flbit_i32_b32" and self.holds_lane_mask(a[1]) else self.src_u(a[1]) - r = self.tmp() - if op in ("v_ffbl_b32", "s_ff1_i32_b32"): - # Index of lowest set bit, -1 (0xFFFFFFFF) if none: FindILsb has the same convention. - ri = self.tmp() - self.emit(f"{ri} = OpExtInst %int %glsl FindILsb {self.as_int(x)}") - self.emit(f"{r} = OpBitcast %uint {ri}") - else: - # Leading-zero count from the MSB side, -1 if zero: 31 - FindUMsb(x), with FindUMsb(0) = -1. - m, z, d = self.tmp(), self.tmp(), self.tmp() - self.emit(f"{m} = OpExtInst %int %glsl FindUMsb {x}") - mu = self.tmp() - self.emit(f"{mu} = OpBitcast %uint {m}") - self.emit(f"{d} = OpISub %uint {self.cu(31)} {mu}") - self.emit(f"{z} = OpIEqual %bool {x} {self.cu(0)}") - self.emit(f"{r} = OpSelect %uint {z} {self.cu(0xFFFFFFFF)} {d}") - self.dst(a[0], r) - elif op in ("image_get_resinfo", "image_load_mip", "image_store", "image_atomic_cmpswap") \ - or op in self.IMG_ATOMICS or op in self.IMG_ATOMICS_EXTRA: - self.image_misc(op, a, mods) - self.mimg_status(op, a, mods) - elif op in ("v_cubema_f32", "v_cubeid_f32", "v_cubesc_f32", "v_cubetc_f32"): - # Cube face selection (standard table): major axis Z if |z|>=|x| and |z|>=|y|, else Y if |y|>=|x|, - # else X. face: +X0 -X1 +Y2 -Y3 +Z4 -Z5 - # +X: sc=-z tc=-y -X: sc=+z tc=-y +Y: sc=+x tc=+z -Y: sc=+x tc=-z +Z: sc=+x tc=-y -Z: sc=-x tc=-y - # cubema = 2 * (signed major-axis coordinate) - x, y, z = (self.src_f(t) for t in a[1:4]) - ax, ay, az = (self.tmp() for _ in range(3)) - for t, s in ((ax, x), (ay, y), (az, z)): - self.emit(f"{t} = OpExtInst %float %glsl FAbs {s}") - zx, zy, zmaj, yx, ymaj = (self.tmp() for _ in range(5)) - self.emit(f"{zx} = OpFOrdGreaterThanEqual %bool {az} {ax}") - self.emit(f"{zy} = OpFOrdGreaterThanEqual %bool {az} {ay}") - self.emit(f"{zmaj} = OpLogicalAnd %bool {zx} {zy}") - self.emit(f"{yx} = OpFOrdGreaterThanEqual %bool {ay} {ax}") - nz = self.tmp() - self.emit(f"{nz} = OpLogicalNot %bool {zmaj}") - self.emit(f"{ymaj} = OpLogicalAnd %bool {nz} {yx}") - - def neg(v): - n = self.tmp() - self.emit(f"{n} = OpFNegate %float {v}") - return n - - def lt0(v): - b = self.tmp() - self.emit(f"{b} = OpFOrdLessThan %bool {v} %f0") - return b - - def pick(zv, yv, xv): - t1, t2 = self.tmp(), self.tmp() - self.emit(f"{t1} = OpSelect %float {ymaj} {yv} {xv}") - self.emit(f"{t2} = OpSelect %float {zmaj} {zv} {t1}") - return t2 - - def sel(c, t, f): - r = self.tmp() - self.emit(f"{r} = OpSelect %float {c} {t} {f}") - return r - xn, yn, zn = lt0(x), lt0(y), lt0(z) - if op == "v_cubema_f32": - # Measured natively on RDNA2 (gfx1036, wave32 & wave64, all 4 IEEE/DX10_CLAMP modes): - # v_cubema_f32 returns +0.0 (never -0.0) whenever the selected major axis is ±0.0, - # while preserving NaNs and signed non-zero major-axis values. - m = pick(z, y, x) - is_z, m2, r = self.tmp(), self.tmp(), self.tmp() - self.emit(f"{is_z} = OpFOrdEqual %bool {m} %f0") - self.emit(f"{m2} = OpFMul %float {m} {self.fconst(2.0)}") - self.emit(f"{r} = OpSelect %float {is_z} %f0 {m2}") - elif op == "v_cubeid_f32": - r = pick(sel(zn, self.fconst(5.0), self.fconst(4.0)), sel(yn, self.fconst(3.0), self.fconst(2.0)), - sel(xn, self.fconst(1.0), self.fconst(0.0))) - elif op == "v_cubesc_f32": - r = pick(sel(zn, neg(x), x), x, sel(xn, z, neg(z))) - else: - r = pick(neg(y), sel(yn, neg(z), z), neg(y)) - self.dst(a[0], self.tou(self.clamp_mods(r, mods))) - elif op in ("v_mbcnt_lo_u32_b32", "v_mbcnt_hi_u32_b32"): - # Count of set bits in the mask for lanes below this one (lo: lanes 0-31, hi: lanes 32-63), plus src1. - self.uses_subgroup = True - if self.holds_lane_mask(a[1]): # a real mask: the lanes below this one that are set in it - half = self.mask_half(a[1]) if self.wave64 else None - idx = (1 if half == "hi" else 0) if half is not None else (0 if op.endswith("lo_u32_b32") else 1) - mask = self.wave_mask(a[1])[idx] - acc = self.src_u(a[2]) - else: - mask, acc = self.src_u(a[1]), self.src_u(a[2]) - lane, rel, below, inrange, one, m1, cnt, r = (self.tmp() for _ in range(8)) - wl = self.wave_lane() - self.emit(f"{lane} = OpCopyObject %uint {wl}") - if op.endswith("lo_u32_b32"): - self.emit(f"{rel} = OpCopyObject %uint {lane}") - else: - self.emit(f"{rel} = OpISub %uint {lane} {self.cu(32)}") - # bits below `rel`, clamped to [0, 32] - self.emit(f"{inrange} = OpULessThan %bool {rel} {self.cu(32)}") - self.emit(f"{one} = OpShiftLeftLogical %uint {self.cu(1)} {rel}") - self.emit(f"{m1} = OpISub %uint {one} {self.cu(1)}") - big = self.tmp() - # lo: lanes >= 32 count all 32 bits; hi: lanes < 32 count none (rel wraps above 32). - self.emit(f"{big} = OpSelect %uint {inrange} {m1} " - f"{self.cu(0xFFFFFFFF) if op.endswith('lo_u32_b32') else self.cu(0)}") - if op.endswith("hi_u32_b32"): - lt32, fixed = self.tmp(), self.tmp() - self.emit(f"{lt32} = OpULessThan %bool {lane} {self.cu(32)}") - self.emit(f"{fixed} = OpSelect %uint {lt32} {self.cu(0)} {big}") - big = fixed - self.emit(f"{below} = OpBitwiseAnd %uint {mask} {big}") - self.emit(f"{cnt} = OpBitCount %uint {below}") - self.emit(f"{r} = OpIAdd %uint {cnt} {acc}") - self.dst(a[0], r) - elif op == "v_bfrev_b32": - x = self.src_u(a[1]) - r = self.tmp() - self.emit(f"{r} = OpBitReverse %uint {x}") - self.dst(a[0], r) - elif op == "v_bfm_b32": - w, o = self.src_u(a[1]), self.src_u(a[2]) - width = None if "sdwa_sel" in a[1] else self.imm_val(a[1]) - offset = None if "sdwa_sel" in a[2] else self.imm_val(a[2]) - if width is not None: - bits = (1 << (width & 31)) - 1 - if offset is not None: - self.dst(a[0], self.cu(bits << (offset & 31))) - return - if bits == 0: - self.dst(a[0], self.cu(0)) - return - mask = self.cu(bits) - else: - wm, one, mask = (self.tmp() for _ in range(3)) - self.emit(f"{wm} = OpBitwiseAnd %uint {w} {self.cu(31)}") - self.emit(f"{one} = OpShiftLeftLogical %uint {self.cu(1)} {wm}") - self.emit(f"{mask} = OpISub %uint {one} {self.cu(1)}") - if offset is None: - shift = self.tmp() - self.emit(f"{shift} = OpBitwiseAnd %uint {o} {self.cu(31)}") - elif offset & 31: - shift = self.cu(offset & 31) - else: - self.dst(a[0], mask) - return - r = self.tmp() - self.emit(f"{r} = OpShiftLeftLogical %uint {mask} {shift}") - self.dst(a[0], r) - elif op in ("s_bcnt1_i32_b64", "s_bcnt1_i32_b32", "s_bcnt0_i32_b64", "s_bcnt0_i32_b32"): - if self.holds_lane_mask(a[1]): - lo, hi = self.wave_mask(a[1]) - if op.endswith("b32") and self.wave64: - half = self.mask_half(a[1]) - if half is not None: - lo, hi = (hi if half == "hi" else lo), self.cu(0) - elif op.endswith("b64") and a[1]["k"] == "sgpr" and a[1].get("n") == 2: - lo, hi = self.load_reg("sgpr", a[1]["r"]), self.load_reg("sgpr", a[1]["r"] + 1) - elif op.endswith("b64") and a[1]["k"] == "imm": - lo, hi = self.src64_data(a[1], op) # a constant's own 64 bits, as s_ff1_i32_b64 reads them - else: - lo, hi = (self.mask_src(a[1]), self.cu(0)) if op.endswith("b64") else (self.src_u(a[1]), self.cu(0)) - if "bcnt0" in op: - nlo = self.tmp() - self.emit(f"{nlo} = OpNot %uint {lo}") - lo = nlo - if op.endswith("b64"): - nhi = self.tmp() - self.emit(f"{nhi} = OpNot %uint {hi}") - hi = nhi - c1, c2, r = self.tmp(), self.tmp(), self.tmp() - self.emit(f"{c1} = OpBitCount %uint {lo}") - if op.endswith("b64") or "bcnt1" in op: - # s_bcnt1_i32_b32 counts the high word too: for a lane mask of a wave32 shader running in a 64-lane - # subgroup (graphics stages can't request 32) the other lanes' bits are there; otherwise hi is 0. - # s_bcnt0_i32_b32 counts zeros of the low word only (~0 in the high word would add 32). - self.emit(f"{c2} = OpBitCount %uint {hi}") - self.emit(f"{r} = OpIAdd %uint {c1} {c2}") - else: - r = c1 - self.dst(a[0], r) - z = self.tmp() - self.emit(f"{z} = OpSelect %uint {self.tmp_bool_nz(r)} {self.cu(1)} {self.cu(0)}") - self.emit(f"OpStore %scc {z}") - elif op in ("v_add_nc_i32", "v_sub_nc_i32") or \ - (op in ("v_add_nc_u32", "v_sub_nc_u32", "v_subrev_nc_u32") and "clamp" in mods): - # 32-bit add/sub without carry out. The VOP3 clamp bit saturates an integer result (GFX9+: LLVM selects - # uaddsat/usubsat to v_add/sub_nc_u32 clamp and saddsat/ssubsat to v_add/sub_nc_i32 clamp): unsigned to - # [0, 0xFFFFFFFF], signed to [0x80000000, 0x7FFFFFFF]. Without clamp the result wraps. - x, y = self.src_u(a[1]), self.src_u(a[2]) - if op == "v_subrev_nc_u32": - x, y = y, x - sub = "_sub" in op - r = self.tmp() - if op.endswith("_u32"): - s_, w, c = self.tmp(), self.tmp(), self.tmp() - self.emit(f"{s_} = {'OpISubBorrow' if sub else 'OpIAddCarry'} %umul {x} {y}") - self.emit(f"{w} = OpCompositeExtract %uint {s_} 0") - self.emit(f"{c} = OpCompositeExtract %uint {s_} 1") - sat = self.cu(0) if sub else self.cu(0xFFFFFFFF) - self.emit(f"{r} = OpSelect %uint {self.tmp_bool_nz(c)} {sat} {w}") - else: - w = self.tmp() - self.emit(f"{w} = {'OpISub' if sub else 'OpIAdd'} %uint {x} {y}") - if "clamp" in mods: - # Signed overflow: add when x and y share a sign that w lacks; sub when x and y differ in sign - # and w differs from x. The saturated value follows x's sign. - t1, t2, ov, neg, lim = (self.tmp() for _ in range(5)) - if sub: - self.emit(f"{t1} = OpBitwiseXor %uint {x} {y}") - else: - self.emit(f"{t1} = OpBitwiseXor %uint {y} {w}") - self.emit(f"{t2} = OpBitwiseXor %uint {x} {w}") - ovm = self.tmp() - self.emit(f"{ovm} = OpBitwiseAnd %uint {t1} {t2}") - self.emit(f"{ov} = OpSLessThan %bool {self.as_int(ovm)} {self.as_int(self.cu(0))}") - self.emit(f"{neg} = OpSLessThan %bool {self.as_int(x)} {self.as_int(self.cu(0))}") - self.emit(f"{lim} = OpSelect %uint {neg} {self.cu(0x80000000)} {self.cu(0x7FFFFFFF)}") - self.emit(f"{r} = OpSelect %uint {ov} {lim} {w}") - else: - r = w - self.dst(a[0], r) - elif op == "v_subrev_nc_u32": - x, y = self.src_u(a[1]), self.src_u(a[2]) - r = self.tmp() - self.emit(f"{r} = OpISub %uint {y} {x}") - self.dst(a[0], r) - elif op in ("s_flbit_i32_b64", "s_flbit_i32_i64"): - # Leading-bit count of a 64-bit value, from bit 63 down: b64 counts the zeros before the first 1; i64 - # counts the bits before the first one that differs from the sign bit (b64 of ~S0 when S0 < 0). -1 when - # there is none (0, and for i64 also -1). SCC is not written. The pair is 64-bit data (as for - # s_lshl_b64); a lane-mask source stays Unsupported (#210). - x = a[1] - if self.holds_lane_mask(x): - raise Unsupported(op + " of a lane mask") - if x["k"] == "sgpr" and x.get("n") == 2: - lo, hi = self.load_reg("sgpr", x["r"]), self.load_reg("sgpr", x["r"] + 1) - elif x["k"] == "imm": - v = x["v"] & 0xFFFFFFFFFFFFFFFF - lo, hi = self.cu(v & 0xFFFFFFFF), self.cu(v >> 32) - else: - raise Unsupported(op + " source") - if op == "s_flbit_i32_i64": - neg, nlo, nhi, slo, shi = (self.tmp() for _ in range(5)) - self.emit(f"{neg} = OpSLessThan %bool {self.as_int(hi)} {self.as_int(self.cu(0))}") - self.emit(f"{nlo} = OpNot %uint {lo}") - self.emit(f"{nhi} = OpNot %uint {hi}") - self.emit(f"{slo} = OpSelect %uint {neg} {nlo} {lo}") - self.emit(f"{shi} = OpSelect %uint {neg} {nhi} {hi}") - lo, hi = slo, shi - mh, ml, mhu, mlu, ch, cl, hz, lz, r0, r = (self.tmp() for _ in range(10)) - self.emit(f"{mh} = OpExtInst %int %glsl FindUMsb {hi}") - self.emit(f"{ml} = OpExtInst %int %glsl FindUMsb {lo}") - self.emit(f"{mhu} = OpBitcast %uint {mh}") - self.emit(f"{mlu} = OpBitcast %uint {ml}") - self.emit(f"{ch} = OpISub %uint {self.cu(31)} {mhu}") # zeros above the top 1 of the high half - self.emit(f"{cl} = OpISub %uint {self.cu(63)} {mlu}") # 32 + zeros above the top 1 of the low half - self.emit(f"{hz} = OpIEqual %bool {hi} {self.cu(0)}") - self.emit(f"{lz} = OpIEqual %bool {lo} {self.cu(0)}") - self.emit(f"{r0} = OpSelect %uint {lz} {self.cu(0xFFFFFFFF)} {cl}") - self.emit(f"{r} = OpSelect %uint {hz} {r0} {ch}") - self.dst(a[0], r) - elif op in ("s_ff1_i32_b64", "s_ff1_i32_b32", "s_ff0_i32_b64", "s_ff0_i32_b32"): - # Lowest set (ff1) or zero (ff0) bit of a mask, -1 if none. For a lane mask that is the wave's first lane. - if self.holds_lane_mask(a[1]): - lo, hi = self.wave_mask(a[1]) - if op.endswith("b32") and self.wave64: - half = self.mask_half(a[1]) - if half is not None: - lo, hi = (hi if half == "hi" else lo), self.cu(0) - elif op.endswith("b32"): - # A b32 source is a plain scalar value, not a lane mask. - lo, hi = self.src_u(a[1]), self.cu(0) - elif a[1]["k"] == "imm": - # A 64-bit constant's own 64 bits (inline negative constants sign-extend, literals zero-extend), - # matching s_bcnt0/1_i32_b64 and src64_data. - lo, hi = self.src64_data(a[1], op) - elif a[1]["k"] != "sgpr" or a[1].get("n") != 2: - lo, hi = self.mask_src(a[1]), self.cu(0) - else: - lo, hi = self.load_reg("sgpr", a[1]["r"]), self.load_reg("sgpr", a[1]["r"] + 1) - if "ff0" in op: - nlo = self.tmp() - self.emit(f"{nlo} = OpNot %uint {lo}") - lo = nlo - if op.endswith("b64"): - nhi = self.tmp() - self.emit(f"{nhi} = OpNot %uint {hi}") - hi = nhi - l, h, hp, lz, r = (self.tmp() for _ in range(5)) - self.emit(f"{l} = OpExtInst %int %glsl FindILsb {self.as_int(lo)}") - if op.endswith("b64"): - self.emit(f"{h} = OpExtInst %int %glsl FindILsb {self.as_int(hi)}") - hu = self.tmp() - self.emit(f"{hu} = OpBitcast %uint {h}") - hz = self.tmp() - self.emit(f"{hz} = OpIEqual %bool {hi} {self.cu(0)}") - self.emit(f"{hp} = OpIAdd %uint {hu} {self.cu(32)}") - hsel = self.tmp() - self.emit(f"{hsel} = OpSelect %uint {hz} {self.cu(0xFFFFFFFF)} {hp}") - self.emit(f"{lz} = OpIEqual %bool {lo} {self.cu(0)}") - lu = self.tmp() - self.emit(f"{lu} = OpBitcast %uint {l}") - self.emit(f"{r} = OpSelect %uint {lz} {hsel} {lu}") - else: - lu = self.tmp() - self.emit(f"{lu} = OpBitcast %uint {l}") - r = lu - self.dst(a[0], r) - elif op == "ds_swizzle_b32": - self.swizzle(a, mods, ins) - elif op in ("v_cvt_f64_i32", "v_cvt_f64_u32"): - self.uses_f64 = True - src = self.src_u(a[1]) - result = self.tmp() - if op == "v_cvt_f64_i32": - self.emit(f"{result} = OpConvertSToF %double {self.as_int(src)}") - else: - self.emit(f"{result} = OpConvertUToF %double {src}") - # SHADER-721 follow-up, measured on gfx1036 through tools/hw_oracle (wave32 and wave64 identical on - # every case, tools/f64_omod_probe.py): a binary64 destination ignores mul:2/mul:4/div:2 while - # denorm_mode_16_64 = 3, which is the game's MODE, and applies them only with IEEE=0 and 16/64-bit - # denormals flushed. clamp applies in every MODE, so only it is passed on. - self.dst_f64(a[0], result, [m for m in mods if m == "clamp"], op) - elif op in ("v_trunc_f64", "v_ceil_f64", "v_rndne_f64", "v_floor_f64"): - if len(a) != 2 or a[0]["k"] != "vgpr" or a[0].get("n") != 2: - raise Unsupported(op + " operands") - dst, src = a - if (ins["op"].endswith(("_dpp", "_sdwa")) - or any(mod not in ("mul:2", "mul:4", "div:2", "clamp") for mod in mods)): - raise Unsupported(op + " modifier") - self.uses_f64 = True - if src["k"] in ("vgpr", "sgpr") and src.get("n") == 2: - low = self.load_reg(src["k"], src["r"]) - high = self.load_reg(src["k"], src["r"] + 1) - elif src["k"] == "fimm": - bits = struct.unpack("> 32) - elif src.get("f64_literal") and self.f64_literal_one_dword(src): - # One literal dword: bits 63:32 of the constant (docs/design.md, f64 literal sources). - low, high = self.cu(0), self.cu(src["v"] & 0xFFFFFFFF) - elif src["k"] == "imm" and (-16 <= src["v"] <= 64 or src.get("f64_literal")): - # An inline integer is sign-extended; a wider literal is the whole constant. - bits = src["v"] & 0xFFFFFFFFFFFFFFFF - low, high = self.cu(bits & 0xFFFFFFFF), self.cu(bits >> 32) - else: - raise Unsupported(op + " source") - if src.get("abs"): - mag = self.tmp() - self.emit(f"{mag} = OpBitwiseAnd %uint {high} {self.cu(0x7FFFFFFF)}") - high = mag - if src.get("neg"): - negated = self.tmp() - self.emit(f"{negated} = OpBitwiseXor %uint {high} {self.cu(0x80000000)}") - high = negated - pair, value, result = self.tmp(), self.tmp(), self.tmp() - self.emit(f"{pair} = OpCompositeConstruct %v2uint_d {low} {high}") - self.emit(f"{value} = OpBitcast %double {pair}") - rounding = {"v_trunc_f64": "Trunc", "v_ceil_f64": "Ceil", - "v_rndne_f64": "RoundEven", "v_floor_f64": "Floor"} - self.emit(f"{result} = OpExtInst %double %glsl {rounding[op]} {value}") - result = self.clamp_mods_f64(result, mods) - words = self.tmp() - self.emit(f"{words} = OpBitcast %v2uint_d {result}") - for index in range(2): - word = self.tmp() - self.emit(f"{word} = OpCompositeExtract %uint {words} {index}") - self.dst({"k": "vgpr", "r": dst["r"] + index, "n": 1}, word) - elif op in ("v_add_f64", "v_cvt_f32_f64", "v_rcp_f64", "v_rsq_f64", "v_sqrt_f64"): - # f64: register pairs as doubles (shaderFloat64). neg/abs modifiers apply to the double. - def f64(sv): - lo, hi = self.f64_source_words(sv, op) - v2, d = self.tmp(), self.tmp() - self.emit(f"{v2} = OpCompositeConstruct %v2uint_d {lo} {hi}") - self.emit(f"{d} = OpBitcast %double {v2}") - if sv.get("abs"): - t = self.tmp() - self.emit(f"{t} = OpExtInst %double %glsl FAbs {d}") - d = t - if sv.get("neg"): - t = self.tmp() - self.emit(f"{t} = OpFNegate %double {d}") - d = t - return d - self.uses_f64 = True - if op == "v_cvt_f32_f64": - x = f64(a[1]) - r = self.tmp() - self.emit(f"{r} = OpFConvert %float {x}") - self.dst(a[0], self.tou(self.clamp_mods(r, mods))) - else: - if op == "v_add_f64": - x, y = f64(a[1]), f64(a[2]) - r = self.tmp() - self.emit(f"{r} = OpFAdd %double {x} {y}") - if self.round_mode: - # MODE rounds the sum itself; clamp/omod then apply to the rounded value, as on the hardware. - m2, mlo, mhi, n2, rd = (self.tmp() for _ in range(5)) - self.emit(f"{m2} = OpBitcast %v2uint_d {r}") - self.emit(f"{mlo} = OpCompositeExtract %uint {m2} 0") - self.emit(f"{mhi} = OpCompositeExtract %uint {m2} 1") - mlo, mhi = self.f64_add_mode(x, y, r, mlo, mhi) - self.emit(f"{n2} = OpCompositeConstruct %v2uint_d {mlo} {mhi}") - self.emit(f"{rd} = OpBitcast %double {n2}") - r = rd - elif op == "v_rcp_f64": - x = f64(a[1]) - r = self.tmp() - self.emit(f"{r} = OpFDiv %double {self.dconst(1.0)} {x}") - elif op == "v_rsq_f64": - x = f64(a[1]) - r = self.tmp() - self.emit(f"{r} = OpExtInst %double %glsl InverseSqrt {x}") - else: # v_sqrt_f64 - x = f64(a[1]) - r = self.tmp() - self.emit(f"{r} = OpExtInst %double %glsl Sqrt {x}") - # VOP3 f64 ops carry HasClamp and HasOMod (LLVM VOPProfile, f64 is a modifier type). - self.dst_f64(a[0], r, mods, op) - elif op in ("v_cmp_class_f64", "v_cmpx_class_f64"): - self.cmp_class_f64(op, a, exec_only=op == "v_cmpx_class_f64", mods=mods) - elif op in ("image_bvh_intersect_ray", "image_bvh64_intersect_ray"): - self.image_bvh(op, a, mods) - elif op == "s_bfm_b64" and not self.wave64: - # In 32-lane waves a 64-bit result can't be a lane mask: D = ((1 << (S0 & 63)) - 1) << (S1 & 63) is 64-bit - # data, as for s_lshl_b64 (lane_masks.step leaves it data too). The pipeline library's wave32 compute - # programs build the first two words of an S# this way (3,342 times `s_bfm_b64 s[N:N+1], 2, 54`, then - # s_mov_b64 of the other two). SCC is not written. Every case seen has constant operands. - size, off = self.imm_val(a[1]), self.imm_val(a[2]) - if size is None or off is None: - raise Unsupported(op + " with a run-time operand in wave32") - self.mov64(a[0], {"k": "imm", "v": (((1 << (size & 63)) - 1) << (off & 63)) & 0xFFFFFFFFFFFFFFFF}) - elif op == "s_bfm_b64": - # D = ((1 << size) - 1) << offset as a lane mask: in the per-lane model this lane's bit is - # offset <= lane < offset + size (size/offset taken mod 64). - size, off = self.src_u(a[1]), self.src_u(a[2]) - lane = self.wave_lane() - sz, of, end, ge, lt, on, m = (self.tmp() for _ in range(7)) - self.emit(f"{sz} = OpBitwiseAnd %uint {size} {self.cu(63)}") - self.emit(f"{of} = OpBitwiseAnd %uint {off} {self.cu(63)}") - self.emit(f"{end} = OpIAdd %uint {of} {sz}") - self.emit(f"{ge} = OpUGreaterThanEqual %bool {lane} {of}") - self.emit(f"{lt} = OpULessThan %bool {lane} {end}") - self.emit(f"{on} = OpLogicalAnd %bool {ge} {lt}") - self.emit(f"{m} = OpSelect %uint {on} {self.cu(0xFFFFFFFF)} {self.cu(0)}") - self.mask_dst(a[0], m) - elif op in ("s_pack_ll_b32_b16", "s_pack_lh_b32_b16", "s_pack_hh_b32_b16"): - # D = {S1 half, S0 half}: the low result half comes from S0, the high one from S1; the letters name the - # half taken from each (l = bits 15:0, h = bits 31:16), S0 first. SCC is not written. - val = None - x_val, y_val = self.imm_val(a[1]), self.imm_val(a[2]) - if x_val is not None and y_val is not None: - lo_v = (x_val >> 16) if op == "s_pack_hh_b32_b16" else (x_val & 0xFFFF) - hi_v = ((y_val & 0xFFFF) << 16) if op == "s_pack_ll_b32_b16" else (y_val & 0xFFFF0000) - val = (lo_v | hi_v) & 0xFFFFFFFF - x, y = self.src_u(a[1]), self.src_u(a[2]) - lo, hi, r = self.tmp(), self.tmp(), self.tmp() - if op == "s_pack_hh_b32_b16": - self.emit(f"{lo} = OpShiftRightLogical %uint {x} {self.cu(16)}") - else: - self.emit(f"{lo} = OpBitwiseAnd %uint {x} {self.cu(0xFFFF)}") - if op == "s_pack_ll_b32_b16": - self.emit(f"{hi} = OpShiftLeftLogical %uint {y} {self.cu(16)}") - else: - self.emit(f"{hi} = OpBitwiseAnd %uint {y} {self.cu(0xFFFF0000)}") - self.emit(f"{r} = OpBitwiseOr %uint {lo} {hi}") - self.dst(a[0], r) - if val is not None and a[0]["k"] == "sgpr" and a[0].get("n", 1) == 1: - self.sgpr_imm[a[0]["r"]] = val - elif op == "s_bfm_b32": - # D = ((1 << (S0 & 31)) - 1) << (S1 & 31): an ordinary scalar value - val = None - x_val, y_val = self.imm_val(a[1]), self.imm_val(a[2]) - if x_val is not None and y_val is not None: - w_v = x_val & 31 - o_v = y_val & 31 - val = (((1 << w_v) - 1) << o_v) & 0xFFFFFFFF - x, y = self.src_u(a[1]), self.src_u(a[2]) - w, o, one, sh, mm, r = (self.tmp() for _ in range(6)) - self.emit(f"{w} = OpBitwiseAnd %uint {x} {self.cu(31)}") - self.emit(f"{o} = OpBitwiseAnd %uint {y} {self.cu(31)}") - self.emit(f"{sh} = OpShiftLeftLogical %uint {self.cu(1)} {w}") - self.emit(f"{mm} = OpISub %uint {sh} {self.cu(1)}") - self.emit(f"{r} = OpShiftLeftLogical %uint {mm} {o}") - self.dst(a[0], r) - if val is not None and a[0]["k"] == "sgpr" and a[0].get("n", 1) == 1: - self.sgpr_imm[a[0]["r"]] = val - elif op == "ds_bpermute_b32": - # vD = vData from lane ((vAddr + offset) / 4) mod 32: a subgroup shuffle (no LDS memory involved). - d, ad, dat = a[0], self.src_u(a[1]), self.src_u(a[2]) - off = self.mod_int(mods, "offset", 0) - s1, ln, src, lane = (self.tmp() for _ in range(4)) - self.emit(f"{s1} = OpIAdd %uint {ad} {self.cu(off)}") - self.emit(f"{ln} = OpShiftRightLogical %uint {s1} {self.cu(2)}") - self.emit(f"{src} = OpBitwiseAnd %uint {ln} {self.cu(31)}") - self.sub_lane(lane) - if self.wave64: - # RDNA2 ISA 10.4.4: each half-wave permutes independently. - half, full_src = self.tmp(), self.tmp() - self.emit(f"{half} = OpBitwiseAnd %uint {lane} {self.cu(32)}") - self.emit(f"{full_src} = OpBitwiseOr %uint {half} {src}") - src = full_src - self.ds_lane_read(d, dat, src, lane) - elif op == "ds_permute_b32": - self.ds_permute(a, mods) - elif op.startswith("ds_") and self.stage == "gs": - self.gs_ds(op, a, mods) - elif op.startswith("ds_"): - self.lds_op(op, a, mods) - elif op == "s_barrier": - # Workgroup execution barrier; AMD orders LDS through s_waitcnt before it, so include workgroup memory. - if self.stage not in ("cs", "ms"): - raise Unsupported("s_barrier outside compute") - if self.emulate_inline: - self.emit(f"OpControlBarrier {self.cu(2)} {self.cu(2)} {self.cu(0x948)}") - self.x_dirty = set() - return - if self.emulate or self.bar_rounds: - # The wave waits in the scheduler until every wave not done waits too (assemble). - self.emit("OpStore %x_bar %true") - self.x_split() - return - self.emit(f"OpControlBarrier {self.cu(2)} {self.cu(2)} {self.cu(0x108)}") - elif op == "v_readlane_b32": - # sD = vS[lane]: a subgroup shuffle from that lane (the result is uniform). - if self.cur_uniform_readlane: - # SHADER-10: wave64_halves proved the VGPR holds one value in every lane (written from scalars - # and constants while EXEC was the launch mask), so any lane has it: this lane's own copy. The - # shuffle would index a lane the 32-lane subgroup of a VS/PS/GS may not have (lane >= 32). - self.dst(a[0], self.src_u(a[1])) - return - slot = lane_masks.lane_slot(a[1], a[2]) - if slot in self.cur_masks: - # A lane mask parked there by v_writelane (a saved EXEC, when the shader ran out of SGPRs): this - # lane's bit comes back, from the slot the write kept it in. The shuffle would hand every lane - # the bit of the one lane the mask was parked in. - self.dst(a[0], self.load_reg("sgpr", self.parked[slot[1:]])) - return - if slot and slot[1:] in self.w64_scalar_spills: - # SHADER-10: wave64_halves proved this VGPR is pure scalar-spill storage (never read as a vector - # operand), so spills across all 64 lanes (including 32..63) reload from the parked scalar slot - # instead of shuffling from an out-of-range lane on a 32-wide subgroup. - self.dst(a[0], self.load_reg("sgpr", self.parked[slot[1:]])) - return - self.uses_subgroup = True - v, ln = self.src_u(a[1]), self.src_u(a[2]) - m, r = self.tmp(), self.tmp() - # RDNA2: wave64 uses S1[5:0] (mod 64); wave32 uses S1[4:0] (mod 32). Masking wave32 with 63 left - # lane selects 32..63 pointing past a 32-wide subgroup (SHADER-52 / FUZZ-7). - self.emit(f"{m} = OpBitwiseAnd %uint {ln} {self.cu(63 if self.wave64 else 31)}") - self.g_shuffle(r, v, m) - self.dst(a[0], r) - elif op == "v_writelane_b32": - # vD[lane] = sS: only the named lane changes (independent of EXEC, as on hardware). - slot = lane_masks.lane_slot(a[0], a[2]) - if slot and slot[1:] in self.w64_scalar_spills: - self.store_reg("sgpr", self.parked[slot[1:]], self.src_u(a[1])) - return - self.uses_subgroup = True - val, ln = self.src_u(a[1]), self.src_u(a[2]) - if slot and slot[1:] in self.parked: # somewhere a mask is fetched back from this lane: keep ours - self.store_reg("sgpr", self.parked[slot[1:]], val) - me, m, eq, old, r = (self.tmp() for _ in range(5)) - if self.stage in ("cs", "ms") or self.wave32_fragment: - # Wave32 fragments use their lane within either half of a wider Vulkan subgroup. - self.emit(f"{me} = OpCopyObject %uint {self.wave_lane()}") - else: - self.emit(f"{me} = OpLoad %uint %sg_lane") - self.emit(f"{m} = OpBitwiseAnd %uint {ln} {self.cu(63 if self.wave64 else 31)}") - self.emit(f"{eq} = OpIEqual %bool {me} {m}") - p = self.reg_ptr("vgpr", a[0]["r"]) - self.emit(f"{old} = OpLoad %uint {p}") - self.emit(f"{r} = OpSelect %uint {eq} {val} {old}") - self.emit(f"OpStore {p} {r}") - elif op in self.BUFFER_SUB16: - self.buffer_sub(op, a, mods) - elif op.startswith("buffer_store_dword") or op in ("buffer_store_format_x", "buffer_store_format_xy", - "buffer_store_format_xyz", "buffer_store_format_xyzw", - "buffer_store_format_d16_x", "buffer_store_format_d16_xy", - "buffer_store_format_d16_xyz", "buffer_store_format_d16_xyzw"): - self.buffer_store(op, a, mods) - elif op in ("v_permlanex16_b32", "v_permlane16_b32"): - # Lane l reads lane sel[l & 15] of (x16: the other 16-lane half of its row; plain: the same half). - # The 4-bit selectors for lanes 0-7 are in src1, for lanes 8-15 in src2. - self.uses_subgroup = True - v, s1, s2 = self.src_u(a[1]), self.src_u(a[2]), self.src_u(a[3]) - lane, within, hi8, sh, nib1, nib2, nib, row, src = (self.tmp() for _ in range(9)) - self.sub_lane(lane) - self.emit(f"{within} = OpBitwiseAnd %uint {lane} {self.cu(15)}") - self.emit(f"{hi8} = OpUGreaterThanEqual %bool {within} {self.cu(8)}") - w7 = self.tmp() - self.emit(f"{w7} = OpBitwiseAnd %uint {within} {self.cu(7)}") - self.emit(f"{sh} = OpIMul %uint {w7} {self.cu(4)}") - self.emit(f"{nib1} = OpBitFieldUExtract %uint {s1} {sh} {self.cu(4)}") - self.emit(f"{nib2} = OpBitFieldUExtract %uint {s2} {sh} {self.cu(4)}") - self.emit(f"{nib} = OpSelect %uint {hi8} {nib2} {nib1}") - half = self.tmp() - self.emit(f"{half} = OpBitwiseAnd %uint {lane} {self.cu(0xFFFFFFF0)}") - if op == "v_permlanex16_b32": - self.emit(f"{row} = OpBitwiseXor %uint {half} {self.cu(16)}") - else: - self.emit(f"{row} = OpCopyObject %uint {half}") - self.emit(f"{src} = OpBitwiseOr %uint {row} {nib}") - # op_sel:[FI, BOUND_CTRL] (LLVM: llvm.amdgcn.permlane16 -> op_sel bits 0, 1). - # FI=1 fetches the value of a source lane that is off in EXEC. FI=0 does not: the destination keeps its - # old value (BOUND_CTRL=0) or gets 0 (BOUND_CTRL=1). A source lane that is on gives its value either - # way. Measured on RDNA2 (issue #374). - (fi, bc), _ = self.opsel_bits(mods, 2) - if fi: - # FI=1 fetches the value of a source lane that is off in EXEC. - r = self.tmp() - self.g_shuffle(r, v, src) - self.dst(a[0], r) - elif self.emulate: - r = self.tmp() - self.g_shuffle(r, v, src) - sa, ok, r2 = (self.tmp() for _ in range(3)) - self.emit(f"{sa} = OpSelect %uint {self.active_b()} {self.cu(1)} {self.cu(0)}") - act = self.tmp() - self.g_shuffle(act, sa, src) - self.emit(f"{ok} = OpINotEqual %bool {act} {self.cu(0)}") - if bc: - self.emit(f"{r2} = OpSelect %uint {ok} {r} {self.cu(0)}") - else: - ptr, old = (self.tmp() for _ in range(2)) # a plain load, as dst() does: a VGPR that nothing has written yet is not an undefined value - self.emit(f"{ptr} = OpAccessChain %_ptr_Function_uint %vgpr {self.cu(a[0]['r'])}") - self.emit(f"{old} = OpLoad %uint {ptr}") - self.emit(f"{r2} = OpSelect %uint {ok} {r} {old}") - self.dst(a[0], r2) - else: - # A source lane that is off in EXEC (or absent from a workgroup smaller than the wave) is off too; - # a shuffle from it is undefined, so redirect it first, as ds_lane_read does. The scalar select that - # applied FI/BOUND_CTRL can become a short-circuiting ternary in MSL, moving the ballot and both - # shuffles into divergent control flow: on MoltenVK 1.4.2 and on MoltenVK main at SPIRV-Cross - # aa217aeb the FI=0 lanes then read the source lane's value instead of keeping the old one (#5895). - # Combine with bitwise masks instead, as #932 does for ds_bpermute: the ballot and the shuffles run - # before lane predication. - sa, ballot, present, safe_src, r, act, got, ok, mask = (self.tmp() for _ in range(9)) - self.emit(f"{sa} = OpSelect %uint {self.active_b()} {self.cu(1)} {self.cu(0)}") - physical_src = self.wave_source_lane(src) - self.emit(f"{ballot} = OpGroupNonUniformBallot %v4uint_bal %c3 %true") - self.emit(f"{present} = OpGroupNonUniformBallotBitExtract %bool %c3 {ballot} {physical_src}") - self.emit(f"{safe_src} = OpSelect %uint {present} {src} {lane}") - self.emit(f"{r} = OpGroupNonUniformShuffle %uint %c3 {v} {self.wave_source_lane(safe_src)}") - self.emit(f"{act} = OpGroupNonUniformShuffle %uint %c3 {sa} {self.wave_source_lane(safe_src)}") - self.emit(f"{got} = OpINotEqual %bool {act} {self.cu(0)}") - self.emit(f"{ok} = OpLogicalAnd %bool {present} {got}") - self.uses_subgroup = self.uses_ballot = True - self.emit(f"{mask} = OpSelect %uint {ok} {self.cu(0xFFFFFFFF)} {self.cu(0)}") - if bc: - r2 = self.tmp() - self.emit(f"{r2} = OpBitwiseAnd %uint {r} {mask}") - else: - ptr, old, keep, newv, oldv, r2 = (self.tmp() for _ in range(6)) - self.emit(f"{ptr} = OpAccessChain %_ptr_Function_uint %vgpr {self.cu(a[0]['r'])}") # as dst() does - self.emit(f"{old} = OpLoad %uint {ptr}") - self.emit(f"{keep} = OpNot %uint {mask}") - self.emit(f"{newv} = OpBitwiseAnd %uint {r} {mask}") - self.emit(f"{oldv} = OpBitwiseAnd %uint {old} {keep}") - self.emit(f"{r2} = OpBitwiseOr %uint {newv} {oldv}") - self.dst(a[0], r2, eager=True) - elif op.startswith("buffer_load_dword"): - self.buffer_load(op, a, mods) - elif op in self.BUFFER_SUB: - self.buffer_load_sub(op, a, mods) - elif op in ("buffer_load_format_x", "buffer_load_format_xy", "buffer_load_format_xyz", - "buffer_load_format_xyzw", "buffer_load_format_d16_x", "buffer_load_format_d16_xy", - "buffer_load_format_d16_xyz", "buffer_load_format_d16_xyzw"): - self.buffer_load_format(op, a, mods) - elif op in ("tbuffer_load_format_x", "tbuffer_load_format_xy", "tbuffer_load_format_xyz", - "tbuffer_load_format_xyzw", "tbuffer_load_format_d16_x", "tbuffer_load_format_d16_xy", - "tbuffer_load_format_d16_xyz", "tbuffer_load_format_d16_xyzw"): - self.buffer_load_format(op[1:], a, mods, fixed_fmt=self.mtbuf_format(op, mods)) - elif op in ("tbuffer_store_format_x", "tbuffer_store_format_xy", "tbuffer_store_format_xyz", - "tbuffer_store_format_xyzw", "tbuffer_store_format_d16_x", "tbuffer_store_format_d16_xy", - "tbuffer_store_format_d16_xyz", "tbuffer_store_format_d16_xyzw"): - self.buffer_store(op[1:], a, mods, fixed_fmt=self.mtbuf_format(op, mods)) - elif op in ("s_bitset0_b64", "s_bitset1_b64"): - # D[S0 & 63] = 0 / 1 in the SGPR pair D (D is both source and destination); SCC is not written. The pair - # is 64-bit data (as for s_lshl_b64); a pair that lane_masks.py marks as a lane mask stays Unsupported. - d = a[0] - if d["k"] != "sgpr" or d.get("n") != 2 or self.holds_lane_mask(d): - raise Unsupported(op + " destination") - b = self.src_u(a[1]) - m, low, bit, sh = self.tmp(), self.tmp(), self.tmp(), self.tmp() - self.emit(f"{m} = OpBitwiseAnd %uint {b} {self.cu(63)}") - self.emit(f"{low} = OpULessThan %bool {m} {self.cu(32)}") - self.emit(f"{bit} = OpBitwiseAnd %uint {m} {self.cu(31)}") - self.emit(f"{sh} = OpShiftLeftLogical %uint {self.cu(1)} {bit}") - for half in (0, 1): - old, want, mk, r = self.tmp(), self.tmp(), self.tmp(), self.tmp() - self.emit(f"{old} = OpCopyObject %uint {self.load_reg('sgpr', d['r'] + half)}") - # The bit lands in this half when (m < 32) matches (half == 0). - if half == 0: - self.emit(f"{mk} = OpSelect %uint {low} {sh} {self.cu(0)}") - else: - self.emit(f"{mk} = OpSelect %uint {low} {self.cu(0)} {sh}") - if op == "s_bitset1_b64": - self.emit(f"{r} = OpBitwiseOr %uint {old} {mk}") - else: - self.emit(f"{want} = OpNot %uint {mk}") - self.emit(f"{r} = OpBitwiseAnd %uint {old} {want}") - self.store_reg("sgpr", d["r"] + half, r) - elif op == "s_bitset1_b32": - # sD |= 1 << (src & 31) (sD is both source and destination) - b = self.src_u(a[1]) - m, sh, old, r = (self.tmp() for _ in range(4)) - self.emit(f"{m} = OpBitwiseAnd %uint {b} {self.cu(31)}") - self.emit(f"{sh} = OpShiftLeftLogical %uint {self.cu(1)} {m}") - self.emit(f"{old} = OpCopyObject %uint {self.src_u(a[0])}") - self.emit(f"{r} = OpBitwiseOr %uint {old} {sh}") - self.dst(a[0], r) - elif op in ("v_mul_hi_u32_u24", "v_mul_hi_i32_i24"): - # High 32 bits of the 48-bit product of the low 24 bits of each source: zero-extended for u24, - # sign-extended from bit 23 for i24 (RDNA2 ISA). The low 32 bits are v_mul_u32_u24 / v_mul_i32_i24. - x, y = self.src_u(a[1]), self.src_u(a[2]) - signed = op == "v_mul_hi_i32_i24" - xs, ys, s, r = (self.tmp() for _ in range(4)) - ext = "OpBitFieldSExtract" if signed else "OpBitFieldUExtract" - self.emit(f"{xs} = {ext} %uint {x} {self.cu(0)} {self.cu(24)}") - self.emit(f"{ys} = {ext} %uint {y} {self.cu(0)} {self.cu(24)}") - if signed: - xi, yi, hi = self.as_int(xs), self.as_int(ys), self.tmp() - self.emit(f"{s} = OpSMulExtended %smul {xi} {yi}") - self.emit(f"{hi} = OpCompositeExtract %int {s} 1") - self.emit(f"{r} = OpBitcast %uint {hi}") - self.uses_smul = True - else: - self.emit(f"{s} = OpUMulExtended %umul {xs} {ys}") - self.emit(f"{r} = OpCompositeExtract %uint {s} 1") - self.dst(a[0], r) - elif op in ("v_mul_i32_i24", "v_mad_i32_i24"): - # signed 24-bit operands (sign-extended from bit 23), low 32 bits of the product (+ src2 for mad) - x, y = self.src_u(a[1]), self.src_u(a[2]) - xs, ys, r = self.tmp(), self.tmp(), self.tmp() - self.emit(f"{xs} = OpBitFieldSExtract %uint {x} {self.cu(0)} {self.cu(24)}") - self.emit(f"{ys} = OpBitFieldSExtract %uint {y} {self.cu(0)} {self.cu(24)}") - self.emit(f"{r} = OpIMul %uint {xs} {ys}") - if op == "v_mad_i32_i24": - r2 = self.tmp() - self.emit(f"{r2} = OpIAdd %uint {r} {self.src_u(a[3])}") - r = r2 - self.dst(a[0], r) - elif op == "v_lerp_u8": - if "clamp" in mods: - raise Unsupported(op + " clamp") - x, y, z = (self.src_u(t) for t in a[1:4]) - # Per byte, x + y = 2*(x & y) + (x ^ y). Clear each low bit before the shift so the - # next byte cannot leak in. An odd sum rounds up only when the corresponding bit of z is 1. - # Both additions fit in each byte: even the rounded average is at most 255. - different, shared, even, half, round_bits, rounding, average, r = (self.tmp() for _ in range(8)) - self.emit(f"{different} = OpBitwiseXor %uint {x} {y}") - self.emit(f"{shared} = OpBitwiseAnd %uint {x} {y}") - self.emit(f"{even} = OpBitwiseAnd %uint {different} {self.cu(0xFEFEFEFE)}") - self.emit(f"{half} = OpShiftRightLogical %uint {even} {self.cu(1)}") - self.emit(f"{round_bits} = OpBitwiseAnd %uint {different} {z}") - self.emit(f"{rounding} = OpBitwiseAnd %uint {round_bits} {self.cu(0x01010101)}") - self.emit(f"{average} = OpIAdd %uint {shared} {half}") - self.emit(f"{r} = OpIAdd %uint {average} {rounding}") - self.dst(a[0], r) - elif op == "v_xnor_b32": - x, y = self.src_u(a[1]), self.src_u(a[2]) - t, r = self.tmp(), self.tmp() - self.emit(f"{t} = OpBitwiseXor %uint {x} {y}") - self.emit(f"{r} = OpNot %uint {t}") - self.dst(a[0], r) - elif op == "v_alignbyte_b32": - # (({src0, src1} as 64 bits) >> (8 * (src2 & 3))) low 32 bits - # (32 - b) & 31 keeps the left shift below 32 when b == 0; that result is discarded by the OpSelect. - sh_val = self.imm_val(a[3]) - if sh_val is not None: - sel = sh_val & 3 - if sel == 0: - self.dst(a[0], self.src_u(a[2])) - else: - hi_, lo_ = self.src_u(a[1]), self.src_u(a[2]) - b = sel * 8 - inv = 32 - b - a1, b1, r = self.tmp(), self.tmp(), self.tmp() - self.emit(f"{a1} = OpShiftRightLogical %uint {lo_} {self.cu(b)}") - self.emit(f"{b1} = OpShiftLeftLogical %uint {hi_} {self.cu(inv)}") - self.emit(f"{r} = OpBitwiseOr %uint {a1} {b1}") - self.dst(a[0], r) - else: - hi_, lo_, sh = (self.src_u(t) for t in a[1:4]) - m, b, inv0, inv, a1, b1, nz, r0, r = (self.tmp() for _ in range(9)) - self.emit(f"{m} = OpBitwiseAnd %uint {sh} {self.cu(3)}") - self.emit(f"{b} = OpShiftLeftLogical %uint {m} {self.cu(3)}") - self.emit(f"{inv0} = OpISub %uint {self.cu(32)} {b}") - self.emit(f"{inv} = OpBitwiseAnd %uint {inv0} {self.cu(31)}") - self.emit(f"{a1} = OpShiftRightLogical %uint {lo_} {b}") - self.emit(f"{b1} = OpShiftLeftLogical %uint {hi_} {inv}") - self.emit(f"{r0} = OpBitwiseOr %uint {a1} {b1}") - self.emit(f"{nz} = OpINotEqual %bool {b} {self.cu(0)}") - self.emit(f"{r} = OpSelect %uint {nz} {r0} {lo_}") - self.dst(a[0], r) - elif op == "v_swap_b32": - # exchange two VGPRs (active lanes only, through dst) - x, y = self.src_u(a[0]), self.src_u(a[1]) - xc, yc = self.tmp(), self.tmp() - self.emit(f"{xc} = OpCopyObject %uint {x}") - self.emit(f"{yc} = OpCopyObject %uint {y}") - self.dst(a[0], yc) - self.dst(a[1], xc) - elif op == "s_abs_i32": - x_val = self.imm_val(a[1]) - if x_val is not None: - xi = x_val if x_val < 0x80000000 else x_val - 0x100000000 - val = abs(xi) & 0xFFFFFFFF - r = self.cu(val) - self.dst(a[0], r) - if a[0]["k"] == "sgpr" and a[0].get("n", 1) == 1: - self.sgpr_imm[a[0]["r"]] = val - self.emit(f"OpStore %scc {self.cu(1 if val != 0 else 0)}") - return - x = self.src_u(a[1]) - i, ab, r, nz, sc = (self.tmp() for _ in range(5)) - self.emit(f"{i} = OpBitcast %int {x}") - self.emit(f"{ab} = OpExtInst %int %glsl SAbs {i}") - self.emit(f"{r} = OpBitcast %uint {ab}") - self.emit(f"{nz} = OpINotEqual %bool {r} {self.cu(0)}") - self.emit(f"{sc} = OpSelect %uint {nz} {self.cu(1)} {self.cu(0)}") - self.dst(a[0], r) - self.emit(f"OpStore %scc {sc}") - elif op in ("s_sext_i32_i8", "s_sext_i32_i16"): - # D = S0's low byte / half, sign-extended to 32 bits; SCC is not written. - x_val = self.imm_val(a[1]) - if x_val is not None: - if op.endswith("i8"): - b = x_val & 0xFF - val = ((b ^ 0x80) - 0x80) & 0xFFFFFFFF - else: - h = x_val & 0xFFFF - val = ((h ^ 0x8000) - 0x8000) & 0xFFFFFFFF - r = self.cu(val) - self.dst(a[0], r) - if a[0]["k"] == "sgpr" and a[0].get("n", 1) == 1: - self.sgpr_imm[a[0]["r"]] = val - return - x = self.src_u(a[1]) - r = self.tmp() - self.emit(f"{r} = OpBitFieldSExtract %uint {x} {self.cu(0)} {self.cu(8 if op.endswith('i8') else 16)}") - self.dst(a[0], r) - elif op in ("v_ffbh_i32", "s_flbit_i32"): - # bit position counted from the MSB of the first bit that differs from the sign bit; -1 if none. - # s_flbit_i32 is the scalar form (it does not write SCC). - x = self.as_int(self.lane_mask_word(a[1]) if op == "s_flbit_i32" and self.holds_lane_mask(a[1]) - else self.src_u(a[1])) - f, none, sub, r = (self.tmp() for _ in range(4)) - self.emit(f"{f} = OpExtInst %int %glsl FindSMsb {x}") - self.emit(f"{none} = OpSLessThan %bool {f} {self.as_int(self.cu(0))}") - self.emit(f"{sub} = OpISub %int {self.as_int(self.cu(31))} {f}") - subu = self.tmp() - self.emit(f"{subu} = OpBitcast %uint {sub}") - self.emit(f"{r} = OpSelect %uint {none} {self.cu(0xFFFFFFFF)} {subu}") - self.dst(a[0], r) - elif op.startswith(("v_cmp_", "v_cmpx_")) and op.endswith(("_u64", "_i64")) and \ - op.split("_")[2] in ("lt", "le", "gt", "ge"): - # 64-bit ordered compare: high words decide (signed for i64), equal high words fall back to the low words. - # v_cmpx (GFX10) writes EXEC only. - cmpx = op.startswith("v_cmpx_") - d, x, y = (None, a[-2], a[-1]) if cmpx else (a[0], a[1], a[2]) - def pair64(sv): - if sv["k"] == "vgpr" and sv.get("n") == 2: - return self.load_reg(sv["k"], sv["r"]), self.load_reg(sv["k"], sv["r"] + 1) - return self.src64_data(sv, op) - (x0, x1), (y0, y1) = pair64(x), pair64(y) - cond, signed = op.split("_")[2], op.endswith("_i64") - hi_op = {"lt": "LessThan", "le": "LessThan", "gt": "GreaterThan", "ge": "GreaterThan"}[cond] - lo_op = {"lt": "ULessThan", "le": "ULessThanEqual", "gt": "UGreaterThan", "ge": "UGreaterThanEqual"}[cond] - hx, hy = (self.as_int(x1), self.as_int(y1)) if signed else (x1, y1) - hlt, heq, llt, both, res, r = (self.tmp() for _ in range(6)) - self.emit(f"{hlt} = Op{'S' if signed else 'U'}{hi_op} %bool {hx} {hy}") - self.emit(f"{heq} = OpIEqual %bool {x1} {y1}") - self.emit(f"{llt} = Op{lo_op} %bool {x0} {y0}") - self.emit(f"{both} = OpLogicalAnd %bool {heq} {llt}") - self.emit(f"{res} = OpLogicalOr %bool {hlt} {both}") - ra = self.tmp() - self.emit(f"{ra} = OpLogicalAnd %bool {res} {self.active_b()}") # inactive lanes write 0 - if cmpx: - self.emit(f"OpStore %active {ra}") - self.uses_active = True - return - self.emit(f"{r} = OpSelect %uint {ra} {self.cu(0xFFFFFFFF)} {self.cu(0)}") - self.mask_dst(d, r) - elif op == "v_alignbit_b32": - # (({src0, src1} as 64 bits) >> (src2 & 31)) low 32 bits - # (32 - m) & 31 keeps the left shift below 32 when m == 0; that result is discarded by the OpSelect. - sh_val = self.imm_val(a[3]) - if sh_val is not None: - m_val = sh_val & 31 - if m_val == 0: - self.dst(a[0], self.src_u(a[2])) - else: - hi_, lo_ = self.src_u(a[1]), self.src_u(a[2]) - inv_val = 32 - m_val - a1, b1, r = self.tmp(), self.tmp(), self.tmp() - self.emit(f"{a1} = OpShiftRightLogical %uint {lo_} {self.cu(m_val)}") - self.emit(f"{b1} = OpShiftLeftLogical %uint {hi_} {self.cu(inv_val)}") - self.emit(f"{r} = OpBitwiseOr %uint {a1} {b1}") - self.dst(a[0], r) - else: - hi_, lo_, sh = (self.src_u(t) for t in a[1:4]) - m, inv0, inv, a1, b1, nz, r0, r = (self.tmp() for _ in range(8)) - self.emit(f"{m} = OpBitwiseAnd %uint {sh} {self.cu(31)}") - self.emit(f"{inv0} = OpISub %uint {self.cu(32)} {m}") - self.emit(f"{inv} = OpBitwiseAnd %uint {inv0} {self.cu(31)}") - self.emit(f"{a1} = OpShiftRightLogical %uint {lo_} {m}") - self.emit(f"{b1} = OpShiftLeftLogical %uint {hi_} {inv}") - self.emit(f"{r0} = OpBitwiseOr %uint {a1} {b1}") - self.emit(f"{nz} = OpINotEqual %bool {m} {self.cu(0)}") - self.emit(f"{r} = OpSelect %uint {nz} {r0} {lo_}") - self.dst(a[0], r) - elif op in ("v_lshlrev_b64", "v_lshrrev_b64", "v_ashrrev_i64"): - # v[d:d+1] = v[s:s+1] << / >> (src0 & 63): logical left, logical right, or arithmetic right (the sign - # bit 63 is copied in). - sh, src = a[1], a[2] - if a[0].get("n") != 2: - raise Unsupported(op + " operands") - if src["k"] in ("vgpr", "sgpr") and src.get("n") == 2: - lo, hi = self.load_reg(src["k"], src["r"]), self.load_reg(src["k"], src["r"] + 1) - elif src["k"] == "imm": - # 64-bit inline/literal constant: sign-extended from 32 bits. - v = src["v"] & 0xFFFFFFFFFFFFFFFF - lo, hi = self.cu(v & 0xFFFFFFFF), self.cu((v >> 32) & 0xFFFFFFFF) - else: - raise Unsupported(op + " operands") - s = self.src_u(sh) - l64, h64, x, sh64, m, res, rlo, rhi, t = (self.tmp() for _ in range(9)) - self.emit(f"{l64} = OpUConvert %ulong {lo}") - self.emit(f"{h64} = OpUConvert %ulong {hi}") - self.emit(f"{t} = OpShiftLeftLogical %ulong {h64} %c64_32") - self.emit(f"{x} = OpBitwiseOr %ulong {t} {l64}") - self.emit(f"{m} = OpBitwiseAnd %uint {s} {self.cu(63)}") - self.emit(f"{sh64} = OpUConvert %ulong {m}") - shop = {"v_lshlrev_b64": "OpShiftLeftLogical", "v_lshrrev_b64": "OpShiftRightLogical", - "v_ashrrev_i64": "OpShiftRightArithmetic"}[op] - self.emit(f"{res} = {shop} %ulong {x} {sh64}") - self.emit(f"{rlo} = OpUConvert %uint {res}") - hs = self.tmp() - self.emit(f"{hs} = OpShiftRightLogical %ulong {res} %c64_32") - self.emit(f"{rhi} = OpUConvert %uint {hs}") - self.uses_psb = True # needs Int64 (declared with the PSB types) - self.dst({"k": "vgpr", "r": a[0]["r"], "n": 1}, rlo) - self.dst({"k": "vgpr", "r": a[0]["r"] + 1, "n": 1}, rhi) - elif op == "v_fmac_f16": - # dst = fma(src0, src1, dst). The accumulator is dst itself: low half, or high half under op_sel's dst bit. - sel, dhi = self.opsel_bits(mods, 3) - vals = [self.f16_in(a[1], sel[0]), self.f16_in(a[2], sel[1]), self.f16_in(a[0], sel[2])] - r = self.fma_f16_odd(*vals) # one rounding, to f16 (SHADER-55); omod/clamp keep round-to-odd valid - r = self.clamp_f16(r, mods) - self.f16_out(a[0], r, dhi) # GFX10: f16 ops keep the other half - elif op in ("v_fmamk_f16", "v_fmaak_f16"): - # VOP2 with a literal K (RDNA2 ISA): fmamk D = S0 * K + S1, printed `vdst, src0, K, vsrc1`; fmaak - # D = S0 * S1 + K, printed `vdst, src0, vsrc1, K`. In print order both are a[1] * a[2] + a[3], as for - # v_fmamk/fmaak_f32. K is the f16 in the literal's low 16 bits (src_h: a float literal is converted). - # One rounding to f16, as v_fmac_f16 (SHADER-55); GFX10 f16 VOP2 writes the low half and keeps the high. - self._validate_f16_valu(ins, op, 3, allow_e32=True, allow_e64=False) - vals = [self.f16_in(t) for t in a[1:4]] - self.f16_out(a[0], self.fma_f16_odd(*vals), 0) - elif op in ("v_add_nc_u16", "v_sub_nc_u16", "v_add_nc_i16", "v_sub_nc_i16"): - # VOP3-only GFX10 names of the 16-bit add/sub (no carry): opsel-capable, so the high half is kept. The - # i16 forms differ only under clamp (signed saturation); v_add_i16 / v_sub_i16 are internal names. - self._insn({**ins, "op": {"v_add_nc_u16": "v_add_u16_e64", "v_sub_nc_u16": "v_sub_u16_e64", - "v_add_nc_i16": "v_add_i16_e64", "v_sub_nc_i16": "v_sub_i16_e64"}[op]}) - elif op in ("v_lshrrev_b16", "v_lshlrev_b16", "v_ashrrev_i16", "v_add_u16", "v_sub_u16", - "v_mul_lo_u16", "v_max_u16", "v_min_u16", "v_max_i16", "v_min_i16", - "v_add_i16", "v_sub_i16"): - # 16-bit integer ops on the low halves (op_sel picks high halves in the VOP3 form). Per Mesa ACO - # (can_use_opsel): the opsel-capable VOP3 (_e64) forms are partial writes that keep the high half, - # and the VOP2 (_e32) forms define the whole register (high half modelled as zero). - # VOP3 has bits [31:26] = 0b110101 (0x35): 8 bytes without a literal or 12 bytes with a 32-bit literal. - # VOP2 has bit 31 = 0: 4 bytes or 8 bytes with a literal/SDWA/DPP. LLVM 21 prints VOP3 16-bit integer - # ops without the _e64 suffix, so check the VOP3 prefix rather than byte length alone. - # v_add_i16 / v_sub_i16 are strictly VOP3. - enc = ins.get("enc") - e64 = ins["op"].endswith("_e64") or (bool(enc) and len(enc) >= 16 and (int(enc[6:8], 16) >> 2) == 0x35) - sel = next((m for m in mods if m.startswith("op_sel:")), "op_sel:[0,0,0]") - sb = [int(x) for x in sel.split("[")[1].rstrip("]").split(",")] + [0, 0, 0] - if not e64 and sb[:3] != [0, 0, 0]: - raise Unsupported(op + " op_sel") - r = self.tmp() - if op in ("v_lshrrev_b16", "v_lshlrev_b16", "v_ashrrev_i16"): - x = self.u16_half(self.src_u(a[1]), sb[0]) - sh = self.tmp() # shift amount is src0 (reversed operand order), low 4 bits - self.emit(f"{sh} = OpBitwiseAnd %uint {x} {self.cu(15)}") - if op == "v_lshrrev_b16": - y = self.u16_half(self.src_u(a[2]), sb[1]) - self.emit(f"{r} = OpShiftRightLogical %uint {y} {sh}") - elif op == "v_lshlrev_b16": - y = self.u16_half(self.src_u(a[2]), sb[1]) - self.emit(f"{r} = OpShiftLeftLogical %uint {y} {sh}") - else: - yi = self.i16_half(self.src_u(a[2]), sb[1]) - ri = self.tmp() - self.emit(f"{ri} = OpShiftRightArithmetic %int {yi} {sh}") - self.emit(f"{r} = OpBitcast %uint {ri}") - elif op in ("v_add_i16", "v_sub_i16"): - # signed 16-bit add / sub (v_add_nc_i16 / v_sub_nc_i16): the exact sum of the sign-extended halves; - # its low 16 bits are the wrapped result, clamp below saturates it to [-32768, 32767] - xi = self.i16_half(self.src_u(a[1]), sb[0]) - yi = self.i16_half(self.src_u(a[2]), sb[1]) - ri = self.tmp() - self.emit(f"{ri} = {'OpIAdd' if op == 'v_add_i16' else 'OpISub'} %int {xi} {yi}") - self.emit(f"{r} = OpBitcast %uint {ri}") - elif op in ("v_max_i16", "v_min_i16"): - xi = self.i16_half(self.src_u(a[1]), sb[0]) - yi = self.i16_half(self.src_u(a[2]), sb[1]) - ri = self.tmp() - self.emit(f"{ri} = OpExtInst %int %glsl {'SMax' if 'max' in op else 'SMin'} {xi} {yi}") - self.emit(f"{r} = OpBitcast %uint {ri}") - else: - x = self.u16_half(self.src_u(a[1]), sb[0]) - y = self.u16_half(self.src_u(a[2]), sb[1]) - k = {"v_add_u16": "OpIAdd", "v_sub_u16": "OpISub", "v_mul_lo_u16": "OpIMul"}.get(op) - if k: - self.emit(f"{r} = {k} %uint {x} {y}") - else: - self.emit(f"{r} = OpExtInst %uint %glsl {'UMax' if 'max' in op else 'UMin'} {x} {y}") - if "clamp" in mods: - # VOP3 clamp saturates the unsigned add/sub to [0, 0xFFFF], as for the 32-bit ops (docs/design.md, - # "Integer clamp"). The operands are zero-extended, so a result past 0xFFFF is an overflow (add) or a - # borrow (sub). Other 16-bit ops: rejected rather than guessed. - if op in ("v_add_i16", "v_sub_i16"): - sat = self.tmp() - self.emit(f"{sat} = OpExtInst %uint %glsl SClamp {r} {self.cu(0xFFFF8000)} {self.cu(0x7FFF)}") - r = sat - elif op not in ("v_add_u16", "v_sub_u16"): - raise Unsupported(op + " clamp") - if op in ("v_add_u16", "v_sub_u16"): - ov, sat = self.tmp(), self.tmp() - self.emit(f"{ov} = OpUGreaterThan %bool {r} {self.cu(0xFFFF)}") - self.emit(f"{sat} = OpSelect %uint {ov} {self.cu(0 if 'sub' in op else 0xFFFF)} {r}") - r = sat - lo = self.tmp() - self.emit(f"{lo} = OpBitwiseAnd %uint {r} {self.cu(0xFFFF)}") - if e64 and sb[2]: - # op_sel destination bit: the result goes to the high half, the low half is kept. - if a[0]["k"] != "vgpr": - raise Unsupported("op_sel destination") - old, keep, sh16, v = (self.tmp() for _ in range(4)) - self.emit(f"{old} = OpCopyObject %uint {self.load_reg('vgpr', a[0]['r'])}") - self.emit(f"{keep} = OpBitwiseAnd %uint {old} {self.cu(0xFFFF)}") - self.emit(f"{sh16} = OpShiftLeftLogical %uint {lo} {self.cu(16)}") - self.emit(f"{v} = OpBitwiseOr %uint {keep} {sh16}") - self.dst(a[0], v) - else: - self.write_lo16(a[0], lo, preserve_high=e64) - elif op in ("v_mad_u16", "v_mad_i16"): - # D.u16 = S0.u16 * S1.u16 + S2.u16 on the low halves (op_sel picks high halves: bits 0..2 the sources, bit 3 the - # destination); VOP3-only, so the high half of the destination is kept (RDNA2 ISA; Mesa ACO can_use_opsel). - # The product and sum are formed in 32 bits (no overflow possible), then the low 16 bits are kept. With - # `clamp` the full-width result saturates to [0, 0xFFFF] (v_mad_u16) or [-32768, 32767] (v_mad_i16). - sb, dhi = self.opsel_bits(mods, 3) - vals = [] - for k, s_ in enumerate(a[1:4]): - u = self.src_u(s_) - h = self.u16_half(u, sb[k]) if op == "v_mad_u16" else self.int_bits(self.i16_half(u, sb[k])) - vals.append(h) - x, y, z = vals - prod, tot = self.tmp(), self.tmp() - self.emit(f"{prod} = OpIMul %uint {x} {y}") - self.emit(f"{tot} = OpIAdd %uint {prod} {z}") - r = tot - if "clamp" in mods: - sat = self.tmp() - if op == "v_mad_u16": - ov = self.tmp() - self.emit(f"{ov} = OpUGreaterThan %bool {tot} {self.cu(0xFFFF)}") - self.emit(f"{sat} = OpSelect %uint {ov} {self.cu(0xFFFF)} {tot}") - else: - ti, lo_c, hi_c = self.as_int(tot), self.tmp(), self.tmp() - self.emit(f"{lo_c} = OpExtInst %int %glsl SMax {ti} {self.as_int(self.cu(0xFFFF8000))}") - self.emit(f"{hi_c} = OpExtInst %int %glsl SMin {lo_c} {self.as_int(self.cu(0x7FFF))}") - self.emit(f"{sat} = OpBitcast %uint {hi_c}") - r = sat - lo = self.tmp() - self.emit(f"{lo} = OpBitwiseAnd %uint {r} {self.cu(0xFFFF)}") - if dhi: - old, keep, sh16, v = (self.tmp() for _ in range(4)) - self.emit(f"{old} = OpCopyObject %uint {self.load_reg('vgpr', a[0]['r'])}") - self.emit(f"{keep} = OpBitwiseAnd %uint {old} {self.cu(0xFFFF)}") - self.emit(f"{sh16} = OpShiftLeftLogical %uint {lo} {self.cu(16)}") - self.emit(f"{v} = OpBitwiseOr %uint {keep} {sh16}") - self.dst(a[0], v) - else: - self.write_lo16(a[0], lo) - elif op in ("v_min3_i16", "v_min3_u16", "v_max3_i16", "v_max3_u16", "v_med3_i16", "v_med3_u16"): - # Three-operand 16-bit integer min/max/median on the low halves (op_sel bits 0..2 pick the high half of - # S0..S2, bit 3 writes the high half of D); VOP3-only, so the other half of D is kept (RDNA2 ISA; Mesa - # ACO can_use_opsel). clamp is accepted on hardware and is a no-op on the 16-bit bounded integer word. - sb, dhi = self.opsel_bits(mods, 3) - if dhi and a[0]["k"] != "vgpr": - raise Unsupported("op_sel destination") - signed = op.endswith("_i16") - vals = [] - for k, s_ in enumerate(a[1:4]): - u = self.src_u(s_) - vals.append(self.i16_half(u, sb[k]) if signed else self.u16_half(u, sb[k])) - x, y, z = vals - ty, pfx = ("%int", "S") if signed else ("%uint", "U") - if "med3" in op: - lo_, hi_, m = self.tmp(), self.tmp(), self.tmp() - self.emit(f"{lo_} = OpExtInst {ty} %glsl {pfx}Min {x} {y}") - self.emit(f"{hi_} = OpExtInst {ty} %glsl {pfx}Max {x} {y}") - self.emit(f"{m} = OpExtInst {ty} %glsl {pfx}Clamp {z} {lo_} {hi_}") - else: - m0, m = self.tmp(), self.tmp() - fn = pfx + ("Min" if "min3" in op else "Max") - self.emit(f"{m0} = OpExtInst {ty} %glsl {fn} {x} {y}") - self.emit(f"{m} = OpExtInst {ty} %glsl {fn} {m0} {z}") - if signed: - r = self.tmp() - self.emit(f"{r} = OpBitcast %uint {m}") - else: - r = m - lo = self.tmp() - self.emit(f"{lo} = OpBitwiseAnd %uint {r} {self.cu(0xFFFF)}") - self.write_half16(a[0], lo, dhi) - elif op == "v_bcnt_u32_b32": - self._check_int32_valu(op, ins["op"], a, mods) - x, acc = self.src_u(a[1]), self.src_u(a[2]) - c, r = self.tmp(), self.tmp() - self.emit(f"{c} = OpBitCount %uint {x}") - self.emit(f"{r} = OpIAdd %uint {c} {acc}") - self.dst(a[0], r) - elif op == "s_bitset0_b32": - b = self.src_u(a[1]) - m, sh, n, r = (self.tmp() for _ in range(4)) - self.emit(f"{m} = OpBitwiseAnd %uint {b} {self.cu(31)}") - self.emit(f"{sh} = OpShiftLeftLogical %uint {self.cu(1)} {m}") - self.emit(f"{n} = OpNot %uint {sh}") - self.emit(f"{r} = OpBitwiseAnd %uint {self.src_u(a[0])} {n}") - self.dst(a[0], r) - elif op in ("s_min_i32", "s_max_i32"): - x_val, y_val = self.imm_val(a[1]), self.imm_val(a[2]) - if x_val is not None and y_val is not None: - xi = x_val if x_val < 0x80000000 else x_val - 0x100000000 - yi = y_val if y_val < 0x80000000 else y_val - 0x100000000 - if "min" in op: - val = (xi if xi < yi else yi) & 0xFFFFFFFF - scc = 1 if xi < yi else 0 - else: - val = (xi if xi > yi else yi) & 0xFFFFFFFF - scc = 1 if xi > yi else 0 - r = self.cu(val) - self.dst(a[0], r) - if a[0]["k"] == "sgpr" and a[0].get("n", 1) == 1: - self.sgpr_imm[a[0]["r"]] = val - self.emit(f"OpStore %scc {self.cu(scc)}") - return - x, y = self.src_u(a[1]), self.src_u(a[2]) - r = self.tmp() - self.emit(f"{r} = OpExtInst %uint %glsl {'SMin' if 'min' in op else 'SMax'} {x} {y}") - self.dst(a[0], r) - # SCC = 1 when S0 is the one chosen: the ISA's D = S0 < S1 ? S0 : S1 (min) / S0 > S1 ? S0 : S1 (max) - # picks S1 on a tie, so SCC = S0 < S1 / S0 > S1, compared signed (as s_min_u32/s_max_u32 do unsigned). - # Until 2026-11-21 equal operands set SCC to 1. - c, z = self.tmp(), self.tmp() - xi, yi = self.as_int(x), self.as_int(y) - self.emit(f"{c} = {'OpSLessThan' if 'min' in op else 'OpSGreaterThan'} %bool {xi} {yi}") - self.emit(f"{z} = OpSelect %uint {c} {self.cu(1)} {self.cu(0)}") - self.emit(f"OpStore %scc {z}") - elif op == "v_fma_f16": - self._validate_f16_valu(ins, op, 3) - sel, dhi = self.opsel_bits(mods, 3) # op_sel:[src0,src1,src2,dst] - vals = [self.f16_in(s, sel[i]) for i, s in enumerate(a[1:4])] - r = self.fma_f16_odd(*vals) # one rounding, to f16 (SHADER-55); omod/clamp keep round-to-odd valid - r = self.clamp_f16(r, mods) - self.f16_out(a[0], r, dhi) # GFX10: f16 ops keep the other half - elif op == "v_pk_fmac_f16": - # VOP2 packed f16x2 fused multiply-accumulate into vdst: - # D.f16[0] = fma(S0.f16[0], S1.f16[0], D.f16[0]) - # D.f16[1] = fma(S0.f16[1], S1.f16[1], D.f16[1]) - if (self.non_dpp_mods(ins["op"], mods) or ins["op"].endswith("_sdwa") or - any(s.get("neg") or s.get("abs") for s in a) or a[0]["k"] != "vgpr"): - raise Unsupported("v_pk_fmac_f16 modifiers") - vecs = [] - for s in (a[1], a[2], a[0]): - u = self.src_h(s) - v2 = self.tmp() - self.emit(f"{v2} = OpExtInst %v2float %glsl UnpackHalf2x16 {u}") - vecs.append(v2) - comps = [] - for k in (0, 1): - ex = [self.tmp() for _ in range(3)] - for e_, v_ in zip(ex, vecs): - self.emit(f"{e_} = OpCompositeExtract %float {v_} {k}") - comps.append(self.fma_f16_odd(*ex)) - p = self.tmp() - self.emit(f"{p} = OpCopyObject %uint {self.f16_pack2(comps[0], comps[1])}") - self.dst(a[0], p) - elif op in ("v_pk_add_f16", "v_pk_mul_f16", "v_pk_max_f16", "v_pk_min_f16", "v_pk_fma_f16"): - # Packed f16x2 (VOP3P). Result lo: source i takes its half from op_sel[i] (0 = lo, 1 = hi), negated by - # neg_lo[i]. Result hi: half from op_sel_hi[i], negated by neg_hi[i]. Defaults: op_sel [0,0], - # op_sel_hi [1,1], no negation. - def bits(name, default): - m = next((m for m in mods if m.startswith(name + ":")), None) - if not m: - return default - # a list shorter than the operands (neg_lo:[1,0] on v_pk_fma_f16) is padded with 0, as llvm-mc prints it - return ([int(v) for v in m.split("[")[1].rstrip("]").split(",")] + [0] * len(default))[:len(default)] - ns = 3 if op == "v_pk_fma_f16" else 2 - sel, selhi = bits("op_sel", [0] * ns), bits("op_sel_hi", [1] * ns) - nlo, nhi = bits("neg_lo", [0] * ns), bits("neg_hi", [0] * ns) - track_pk_nan = op in ("v_pk_min_f16", "v_pk_max_f16") and "clamp" not in mods - pk_raw, pk_st, pk_h0 = ([], []), ([], []), [] - srcs = [] - for i in range(ns): - u = self.src_h(a[1 + i]) - v2 = self.tmp() - self.emit(f"{v2} = OpExtInst %v2float %glsl UnpackHalf2x16 {u}") - comps = [] - extracted = {} - for lane, (half_sel, neg) in enumerate(((sel[i], nlo[i]), (selhi[i], nhi[i]))): - c = self.tmp() - self.emit(f"{c} = OpCompositeExtract %float {v2} {half_sel}") - if neg: - n2 = self.tmp() - self.emit(f"{n2} = OpFNegate %float {c}") - c = n2 - comps.append(c) - if track_pk_nan: - if half_sel not in extracted: - extracted[half_sel] = self._f16_half_word(u, half_sel) - h_bits = extracted[half_sel] - pk_raw[i].append(h_bits) - pk_st[i].append(self._f16_const_nan(a[1 + i], half_sel)) - if i == 0: - if neg: - hn = self.tmp() - self.emit(f"{hn} = OpBitwiseXor %uint {h_bits} {self.cu(0x8000)}") - pk_h0.append(hn) - else: - pk_h0.append(h_bits) - vv = self.tmp() - self.emit(f"{vv} = OpCompositeConstruct %v2float {comps[0]} {comps[1]}") - srcs.append(vv) - vx, vy = srcs[:2] - r = self.tmp() - if op == "v_pk_fma_f16": - # one rounding per half, to f16 (SHADER-55) - comps = [] - for k in (0, 1): - ex = [self.tmp() for _ in range(3)] - for e_, v_ in zip(ex, (vx, vy, srcs[2])): - self.emit(f"{e_} = OpCompositeExtract %float {v_} {k}") - comps.append(self.fma_f16_odd(*ex)) - self.emit(f"{r} = OpCompositeConstruct %v2float {comps[0]} {comps[1]}") - elif op in ("v_pk_add_f16", "v_pk_mul_f16"): - self.emit(f"{r} = {'OpFAdd' if 'add' in op else 'OpFMul'} %v2float {vx} {vy}") - if "add" in op: - r = self.sum_toward_zero2(vx, vy, r) - else: - self.emit(f"{r} = OpExtInst %v2float %glsl {'NMax' if 'max' in op else 'NMin'} {vx} {vy}") - if "clamp" in mods: - c = self.tmp() - z2, o2 = self.tmp(), self.tmp() - self.emit(f"{z2} = OpCompositeConstruct %v2float %f0 %f0") - self.emit(f"{o2} = OpCompositeConstruct %v2float %f1 %f1") - self.emit(f"{c} = OpExtInst %v2float %glsl FClamp {r} {z2} {o2}") - r = c - p = self.tmp() - c0, c1 = self.tmp(), self.tmp() - self.emit(f"{c0} = OpCompositeExtract %float {r} 0") - self.emit(f"{c1} = OpCompositeExtract %float {r} 1") - if track_pk_nan: - lanes = [] - for k, c_val in enumerate((c0, c1)): - both_nan = self.all_f16_nan_cond([(pk_raw[0][k], pk_st[0][k]), (pk_raw[1][k], pk_st[1][k])]) - if both_nan is True: - lanes.append(pk_h0[k]) - else: - hk = self.f16_res(c_val) - if both_nan is not None: - sel_k = self.tmp() - self.emit(f"{sel_k} = OpSelect %uint {both_nan} {pk_h0[k]} {hk}") - hk = sel_k - lanes.append(hk) - sh = self.tmp() - self.emit(f"{sh} = OpShiftLeftLogical %uint {lanes[1]} {self.cu(16)}") - self.emit(f"{p} = OpBitwiseOr %uint {lanes[0]} {sh}") - else: - self.emit(f"{p} = OpCopyObject %uint {self.f16_pack2(c0, c1, exact_tiny=op == 'v_pk_add_f16')}") - self.dst(a[0], p) - elif op in ("s_movrels_b32", "s_movrels_b64"): - # Relative SGPR read through M0 (RDNA2 ISA SOP1): D = SGPR[S0 + M0] (the b64 form reads the pair at - # S0 + M0 and S0 + M0 + 1). The SGPR file is an array, so this is a dynamic load, as v_movrels is for - # VGPRs. The index wraps to the 128 array slots, so it can't reach the lane-mask parking slots past them - # (an SGPR that holds a lane mask is handled below); - # the hardware's own range check (and reads past s105 landing on VCC and the other specials) is not - # modelled. SCC is not written. s_movreld (a dynamic SGPR write) stays Unsupported: the translator keeps - # translate-time knowledge of SGPR values (literal S# words, descriptor caches) a dynamic write would - # invalidate. - n = 2 if op.endswith("_b64") else 1 - d, src = a[0], a[1] - if d["k"] != "sgpr" or src["k"] != "sgpr" or d.get("n", 1) != n or src.get("n", 1) != n: - raise Unsupported(op + " operands") - # An SGPR that lane_masks.py marks as a lane mask holds only this lane's bit, so a plain load would copy - # that bit as data (a saved EXEC of 5 read back as 0xffffffff in lanes 0 and 2, 0 elsewhere). For each - # such SGPR the whole wave's mask word is collected first (wave_mask, as for s_bcnt1) and replaces the - # load when the index lands on it. D then holds the mask as data, which is what lane_masks.py assumes - # for an s_movrels destination. The index is dynamic, so every mask SGPR here is a candidate (#1548, - # SHADER-284). - mask_words = [] - for r in sorted(k for k in self.cur_masks if isinstance(k, int) and k < self.SGPRS): - reg = {"k": "sgpr", "r": r, "n": 1} - lo, hi = self.wave_mask(reg) - mask_words.append((r, hi if self.mask_half(reg) == "hi" else lo)) - m0 = self.tmp() - self.emit(f"{m0} = OpLoad %uint %m0") - vals = [] - for w in range(n): - i, j, ptr, v = (self.tmp() for _ in range(4)) - self.emit(f"{i} = OpIAdd %uint {self.cu(src['r'] + w)} {m0}") - self.emit(f"{j} = OpBitwiseAnd %uint {i} {self.cu(self.SGPRS - 1)}") - self.emit(f"{ptr} = OpAccessChain %_ptr_Function_uint %sgpr {j}") - self.emit(f"{v} = OpLoad %uint {ptr}") - for r, word in mask_words: - hit, sel = self.tmp(), self.tmp() - self.emit(f"{hit} = OpIEqual %bool {j} {self.cu(r)}") - self.emit(f"{sel} = OpSelect %uint {hit} {word} {v}") - v = sel - vals.append(v) - for w, v in enumerate(vals): # every read before the first write (D may overlap the source) - self.store_reg("sgpr", d["r"] + w, v) - elif op == "v_swaprel_b32": - # GFX10 VOP1 (opcode 104): swap VGPR[D + M0[25:16]] and VGPR[S0 + M0[9:0]], the fields v_movrelsd_2_b32 - # uses (RDNA2 ISA: tmp = VGPR[D + M0[25:16]]; VGPR[D + M0[25:16]] = VGPR[S0 + M0[9:0]]; - # VGPR[S0 + M0[9:0]] = tmp). Both registers are read before either is written; inactive lanes keep both. - # Both operands are destinations. An out-of-range destination suppresses the entire swap. - d, s0 = a[0], a[1] - if d["k"] != "vgpr" or s0["k"] != "vgpr": - raise Unsupported(op + " operands") - m0, lo, hi, md = (self.tmp() for _ in range(4)) - self.emit(f"{m0} = OpLoad %uint %m0") - self.emit(f"{lo} = OpBitwiseAnd %uint {m0} {self.cu(0x3FF)}") - self.emit(f"{hi} = OpShiftRightLogical %uint {m0} {self.cu(16)}") - self.emit(f"{md} = OpBitwiseAnd %uint {hi} {self.cu(0x3FF)}") - dp, d_valid = self.relative_vgpr_ptr(d["r"], md) - sp, s_valid = self.relative_vgpr_ptr(s0["r"], lo) - d_old, s_old, both_valid, write = (self.tmp() for _ in range(4)) - self.emit(f"{d_old} = OpLoad %uint {dp}") - self.emit(f"{s_old} = OpLoad %uint {sp}") - self.emit(f"{both_valid} = OpLogicalAnd %bool {d_valid} {s_valid}") - self.emit(f"{write} = OpLogicalAnd %bool {self.active_b()} {both_valid}") - # D's slot gets S0's value, then S0's slot gets D's old value: when both name one register the second - # store writes back its own value, so the register is unchanged, as a swap with itself is. - for p_, new, old in ((dp, s_old, d_old), (sp, d_old, s_old)): - sel = self.tmp() - self.emit(f"{sel} = OpSelect %uint {write} {new} {old}") - self.emit(f"OpStore {p_} {sel}") - elif op in ("v_movrels_b32", "v_movreld_b32", "v_movrelsd_b32", "v_movrelsd_2_b32"): - # Relative VGPR indexing through M0: movrels reads VGPR[src + M0], movreld writes VGPR[dst + M0], - # movrelsd does both. The register file is an array, so these become dynamic array accesses. - # movrelsd_2 (GFX10) offsets each side by its own M0 field: VGPR[dst + M0[25:16]] = - # VGPR[src + M0[9:0]] (RDNA2 ISA, VOP1 opcode 72; the RDNA3 ISA gives the same fields). - # Only movreld's source is not indexed, so it is any VOP1 source: an SGPR, M0, an inline constant or a - # literal too (LLVM VOP_MOVRELD's src0 is VSrc_b32; the other three take VRegSrc_32, a VGPR). - d, s = a[0], a[1] - if d["k"] != "vgpr" or (s["k"] != "vgpr" and op != "v_movreld_b32"): - raise Unsupported(op + " operands") - m0 = self.tmp() - self.emit(f"{m0} = OpLoad %uint %m0") - m0_src = m0_dst = m0 - if op == "v_movrelsd_2_b32": - m0_src, hi, m0_dst = self.tmp(), self.tmp(), self.tmp() - self.emit(f"{m0_src} = OpBitwiseAnd %uint {m0} {self.cu(0x3FF)}") - self.emit(f"{hi} = OpShiftRightLogical %uint {m0} {self.cu(16)}") - self.emit(f"{m0_dst} = OpBitwiseAnd %uint {hi} {self.cu(0x3FF)}") - if op in ("v_movrels_b32", "v_movrelsd_b32", "v_movrelsd_2_b32"): - sp, _ = self.relative_vgpr_ptr(s["r"], m0_src) - v = self.tmp() - self.emit(f"{v} = OpLoad %uint {sp}") - else: - v = self.src_u(s) - if op in ("v_movreld_b32", "v_movrelsd_b32", "v_movrelsd_2_b32"): - dp, valid = self.relative_vgpr_ptr(d["r"], m0_dst) - old, write, sel = (self.tmp() for _ in range(3)) - self.emit(f"{old} = OpLoad %uint {dp}") - self.emit(f"{write} = OpLogicalAnd %bool {self.active_b()} {valid}") - self.emit(f"{sel} = OpSelect %uint {write} {v} {old}") - self.emit(f"OpStore {dp} {sel}") - else: - self.dst(d, v) - elif op in ("v_med3_f16", "v_min3_f16", "v_max3_f16"): - self._validate_f16_valu(ins, op, 3) - sel, dhi = self.opsel_bits(mods, 3) # op_sel:[src0,src1,src2,dst] - vals, all_nan, h0_mod = self._read_f16_minmax_srcs(a[1:4], sel, mods) - if op == "v_med3_f16": - r = self.med3_f(vals, a[1:4], sel) - else: - f = "NMax" if "max" in op else "NMin" # a NaN operand gives the other one (docs/design.md) - m, r = self.tmp(), self.tmp() - self.emit(f"{m} = OpExtInst %float %glsl {f} {vals[0]} {vals[1]}") - self.emit(f"{r} = OpExtInst %float %glsl {f} {m} {vals[2]}") - self._finish_f16_minmax_out(a[0], r, mods, dhi, all_nan, h0_mod) # opsel-capable VOP3: keeps the other half - elif op in ("v_qsad_pk_u16_u8", "v_mqsad_pk_u16_u8"): - # Four byte-SADs packed as u16 (RDNA ISA pseudocode): for k = 0..3, D.u16[k] = (S2.u16[k] + SAD of the - # 32-bit window S0[8k+31 : 8k] of the 64-bit S0 against S1) & 0xFFFF. The m form is masked: a byte where - # S1's byte is 0 is skipped (as v_msad_u8). clamp is not modelled: rejected rather than guessed. - if a[0].get("n") != 2 or "clamp" in mods: - raise Unsupported(op + " operands") - - x_lo, x_hi = self.src64_data(a[1], op, allow_vgpr=True) - y = self.src_u(a[2]) - c_lo, c_hi = self.src64_data(a[3], op, allow_vgpr=True) - words = [] - for k in range(4): - if k == 0: - win = x_lo - else: - t1, t2, win = self.tmp(), self.tmp(), self.tmp() - self.emit(f"{t1} = OpShiftRightLogical %uint {x_lo} {self.cu(8 * k)}") - self.emit(f"{t2} = OpShiftLeftLogical %uint {x_hi} {self.cu(32 - 8 * k)}") - self.emit(f"{win} = OpBitwiseOr %uint {t1} {t2}") - acc_w = c_lo if k < 2 else c_hi - total = self.tmp() - self.emit(f"{total} = OpBitFieldUExtract %uint {acc_w} {self.cu(16 * (k % 2))} {self.cu(16)}") - for off in (0, 8, 16, 24): - xb, yb, hi_, lo_, d, t = (self.tmp() for _ in range(6)) - self.emit(f"{xb} = OpBitFieldUExtract %uint {win} {self.cu(off)} {self.cu(8)}") - self.emit(f"{yb} = OpBitFieldUExtract %uint {y} {self.cu(off)} {self.cu(8)}") - self.emit(f"{hi_} = OpExtInst %uint %glsl UMax {xb} {yb}") - self.emit(f"{lo_} = OpExtInst %uint %glsl UMin {xb} {yb}") - self.emit(f"{d} = OpISub %uint {hi_} {lo_}") - if op == "v_mqsad_pk_u16_u8": - md = self.tmp() - self.emit(f"{md} = OpSelect %uint {self.tmp_bool_nz(yb)} {d} {self.cu(0)}") - d = md - self.emit(f"{t} = OpIAdd %uint {total} {d}") - total = t - w = self.tmp() - self.emit(f"{w} = OpBitwiseAnd %uint {total} {self.cu(0xFFFF)}") - words.append(w) - out = [] - for lo16, hi16 in ((words[0], words[1]), (words[2], words[3])): - sh, o = self.tmp(), self.tmp() - self.emit(f"{sh} = OpShiftLeftLogical %uint {hi16} {self.cu(16)}") - self.emit(f"{o} = OpBitwiseOr %uint {lo16} {sh}") - out.append(o) - self.dst({"k": "vgpr", "r": a[0]["r"], "n": 1}, out[0]) - self.dst({"k": "vgpr", "r": a[0]["r"] + 1, "n": 1}, out[1]) - elif op in ("v_sad_u8", "v_sad_hi_u8", "v_sad_u16", "v_sad_u32", "v_msad_u8"): - # Sums of absolute differences (RDNA ISA pseudocode), all unsigned and wrapping at 32 bits: - # v_sad_u8: S2 + sum over the 4 bytes of |S0.b - S1.b| - # v_sad_hi_u8: S2 + (that byte sum << 16) - # v_sad_u16: S2 + sum over the 2 halves of |S0.h - S1.h| - # v_sad_u32: S2 + |S0 - S1| - # v_msad_u8: v_sad_u8, skipping each byte where S1's byte is 0 (masked SAD) - # clamp is not modelled: rejected rather than guessed. - if "clamp" in mods: - raise Unsupported(op + " clamp") - x, y, acc = (self.src_u(t) for t in a[1:4]) - width = {"v_sad_u16": 16, "v_sad_u32": 32}.get(op, 8) - total = None - for off in range(0, 32, width): - if width == 32: - xa, ya = x, y - else: - xa, ya = self.tmp(), self.tmp() - self.emit(f"{xa} = OpBitFieldUExtract %uint {x} {self.cu(off)} {self.cu(width)}") - self.emit(f"{ya} = OpBitFieldUExtract %uint {y} {self.cu(off)} {self.cu(width)}") - hi_, lo_, d = self.tmp(), self.tmp(), self.tmp() - self.emit(f"{hi_} = OpExtInst %uint %glsl UMax {xa} {ya}") - self.emit(f"{lo_} = OpExtInst %uint %glsl UMin {xa} {ya}") - self.emit(f"{d} = OpISub %uint {hi_} {lo_}") - if op == "v_msad_u8": - md = self.tmp() - self.emit(f"{md} = OpSelect %uint {self.tmp_bool_nz(ya)} {d} {self.cu(0)}") - d = md - if total is None: - total = d - else: - t = self.tmp() - self.emit(f"{t} = OpIAdd %uint {total} {d}") - total = t - if op == "v_sad_hi_u8": - t = self.tmp() - self.emit(f"{t} = OpShiftLeftLogical %uint {total} {self.cu(16)}") - total = t - r = self.tmp() - self.emit(f"{r} = OpIAdd %uint {total} {acc}") - self.dst(a[0], r) - elif op == "v_mqsad_u32_u8": - # Four masked byte-SADs with full 32-bit accumulators (RDNA ISA pseudocode): for k = 0..3, - # D[k] = S2[k] + v_msad_u8 of the 32-bit window S0[8k+31 : 8k] of the 64-bit S0 against S1, wrapping at - # 32 bits; a byte where S1's byte is 0 adds nothing. S2 and D are 128-bit (four VGPRs). - # clamp is not modelled: rejected rather than guessed. - if a[0].get("n") != 4 or "clamp" in mods: - raise Unsupported(op + " operands") - s0, s2 = a[1], a[3] - x_lo, x_hi = self.src64_data(s0, op, allow_vgpr=True) - if s2["k"] == "vgpr" and s2.get("n") == 4: - accs = [self.load_reg("vgpr", s2["r"] + k) for k in range(4)] - else: - raise Unsupported(op + " operands") - y = self.src_u(a[2]) - outs = [] - for k in range(4): - if k == 0: - win = x_lo - else: - t1, t2, win = self.tmp(), self.tmp(), self.tmp() - self.emit(f"{t1} = OpShiftRightLogical %uint {x_lo} {self.cu(8 * k)}") - self.emit(f"{t2} = OpShiftLeftLogical %uint {x_hi} {self.cu(32 - 8 * k)}") - self.emit(f"{win} = OpBitwiseOr %uint {t1} {t2}") - total = accs[k] - for off in (0, 8, 16, 24): - xb, yb, hi_, lo_, d, md, t = (self.tmp() for _ in range(7)) - self.emit(f"{xb} = OpBitFieldUExtract %uint {win} {self.cu(off)} {self.cu(8)}") - self.emit(f"{yb} = OpBitFieldUExtract %uint {y} {self.cu(off)} {self.cu(8)}") - self.emit(f"{hi_} = OpExtInst %uint %glsl UMax {xb} {yb}") - self.emit(f"{lo_} = OpExtInst %uint %glsl UMin {xb} {yb}") - self.emit(f"{d} = OpISub %uint {hi_} {lo_}") - self.emit(f"{md} = OpSelect %uint {self.tmp_bool_nz(yb)} {d} {self.cu(0)}") - self.emit(f"{t} = OpIAdd %uint {total} {md}") - total = t - outs.append(total) - for k in range(4): # every source is read before the first write - self.dst({"k": "vgpr", "r": a[0]["r"] + k, "n": 1}, outs[k]) - elif op == "v_xad_u32": - x, y, z = (self.src_u(t) for t in a[1:4]) - t, r = self.tmp(), self.tmp() - self.emit(f"{t} = OpBitwiseXor %uint {x} {y}") - self.emit(f"{r} = OpIAdd %uint {t} {z}") - self.dst(a[0], r) - elif op == "s_not_b64": - if (a[0]["k"] == "special" and a[0].get("t", "").startswith(("exec", "vcc"))) or self.is_mask_op(a[1]): - v = self.mask_src(a[1]) - r = self.tmp() - self.emit(f"{r} = OpNot %uint {v}") - self.mask_dst(a[0], r) - self.scc_from_mask(r) - else: - if not ((a[0]["k"] == "sgpr" and a[0].get("n") == 2) or - (a[0]["k"] == "special" and a[0].get("t") == "null")): - raise Unsupported(op + " destination") - vlo, vhi = self.src64_data(a[1], op) - rlo, rhi = self.tmp(), self.tmp() - self.emit(f"{rlo} = OpNot %uint {vlo}") - self.emit(f"{rhi} = OpNot %uint {vhi}") - self.dst64_data(a[0], rlo, rhi, op, allow_null=True) - orr = self.tmp() - self.emit(f"{orr} = OpBitwiseOr %uint {rlo} {rhi}") - self.scc_nonzero(orr) - elif op in ("v_rsq_f16", "v_rcp_f16", "v_sqrt_f16", "v_exp_f16", "v_log_f16", "v_floor_f16", "v_fract_f16", - "v_ceil_f16", "v_trunc_f16", "v_rndne_f16"): - # f16 unary on the low half (op_sel:[src,dst] picks the high half of the source / of the destination); - # the other half of the destination is kept. - self._validate_unary_f16(op, ins["op"], a, mods) - sel, dhi = self.opsel_bits(mods, 1) - f = self.f16_in(a[1], sel[0]) - r = self.tmp() - fn = {"v_rsq_f16": "InverseSqrt", "v_sqrt_f16": "Sqrt", "v_exp_f16": "Exp2", "v_log_f16": "Log2", - "v_floor_f16": "Floor", "v_fract_f16": "Fract", "v_ceil_f16": "Ceil", "v_trunc_f16": "Trunc", - "v_rndne_f16": "RoundEven"}.get(op) - if fn == "Fract": - inf = self.tmp() - self.emit(f"{inf} = OpIsInf %bool {f}") - if "clamp" in mods: - # DX10_CLAMP maps the infinity result to +0. Give FClamp a defined operand. - clamp_input = self.tmp() - self.emit(f"{clamp_input} = OpSelect %float {inf} %f0 {f}") - f = clamp_input - # SPIR-V leaves 1/0, InverseSqrt(x <= 0) and Sqrt(x < 0) undefined, so those operands are replaced by 1.0 - # and the hardware's result is selected afterwards (docs/design.md, f16 transcendentals): rcp(+-0) = +-inf, - # rsq(+-0) = +-inf, rsq and sqrt of a negative operand (-inf included) = 0xfe00 (a negative quiet NaN). - x, edge = f, None - if op in ("v_rcp_f16", "v_rsq_f16", "v_sqrt_f16"): - sg, zero, below, bad = self.tmp(), self.tmp(), self.tmp(), self.tmp() - self.emit(f"{sg} = OpBitwiseAnd %uint {self.tou(f)} {self.cu(0x80000000)}") - self.emit(f"{zero} = OpFOrdEqual %bool {f} %f0") - self.emit(f"{below} = OpFOrdLessThan %bool {f} %f0") - if op == "v_rcp_f16": - self.emit(f"{bad} = OpCopyObject %bool {zero}") - elif op == "v_rsq_f16": - self.emit(f"{bad} = OpFOrdLessThanEqual %bool {f} %f0") - else: - self.emit(f"{bad} = OpCopyObject %bool {below}") - x = self.tmp() - self.emit(f"{x} = OpSelect %float {bad} %f1 {f}") - edge = (sg, zero, below) - if fn: - self.emit(f"{r} = OpExtInst %float %glsl {fn} {x}") - else: - self.emit(f"{r} = OpFDiv %float %f1 {x}") - if edge: - sg, zero, below = edge - ib, inf, nan, t = self.tmp(), self.tmp(), self.tof(self.cu(0xFFC00000)), self.tmp() - self.emit(f"{ib} = OpBitwiseOr %uint {sg} {self.cu(0x7F800000)}") - self.emit(f"{inf} = OpBitcast %float {ib}") - if op != "v_sqrt_f16": - self.emit(f"{t} = OpSelect %float {zero} {inf} {r}") - r = t - if op != "v_rcp_f16": - t = self.tmp() - self.emit(f"{t} = OpSelect %float {below} {nan} {r}") - r = t - if fn == "Fract": - r = self.fract_below_one(r) - r = self.clamp_f16(r, mods) - if fn == "Fract" and "clamp" not in mods: - # gfx1036 returns 0xfe00 for both infinities. Fract and FMul leave the NaN sign unspecified. - result = self.tmp() - self.emit(f"{result} = OpSelect %float {inf} {self.tof(self.cu(0xFFC00000))} {r}") - r = result - # rcp/rsq/sqrt (and sin below) ignore MODE rounding on hardware (RX 6800, SHADER-35); exp, log (and cos - # below) are unmeasured, assumed like them: nearest even always. - self.f16_out(a[0], r, dhi, fract=fn == "Fract", - mode=op not in ("v_rcp_f16", "v_rsq_f16", "v_sqrt_f16", "v_exp_f16", "v_log_f16")) # GFX10: f16 ops keep the other half - elif op == "v_not_b32": - x = self.src_u(a[1]) - r = self.tmp() - self.emit(f"{r} = OpNot %uint {x}") - self.dst(a[0], r) - elif op == "v_mul_hi_i32": - self._check_int32_valu(op, ins["op"], a, mods) - x, y = self.as_int(self.src_u(a[1])), self.as_int(self.src_u(a[2])) - s, hi, r = self.tmp(), self.tmp(), self.tmp() - self.emit(f"{s} = OpSMulExtended %smul {x} {y}") - self.emit(f"{hi} = OpCompositeExtract %int {s} 1") - self.emit(f"{r} = OpBitcast %uint {hi}") - self.uses_smul = True - self.dst(a[0], r) - elif op in ("v_add_f16", "v_sub_f16", "v_subrev_f16", "v_mul_f16", "v_max_f16", "v_min_f16"): - # f16 math on the low halves (op_sel:[src0,src1,dst] in the VOP3 form); the other half of the destination - # is kept. v_subrev_f16 is S1 - S0: op_sel still names src0 and src1, only the subtraction is swapped. - self._validate_f16_valu(ins, op, 2, allow_e32=True, allow_e64=True, allow_sdwa=True, allow_dpp=True) - sel, dhi = self.opsel_bits(mods, 2) - if op in ("v_max_f16", "v_min_f16"): - vals, all_nan, h0_mod = self._read_f16_minmax_srcs(a[1:3], sel, mods) - else: - vals = [self.f16_in(s, sel[i]) for i, s in enumerate(a[1:3])] - all_nan = h0_mod = None - if op == "v_subrev_f16": - vals.reverse() - r = self.tmp() - k = {"v_add_f16": "OpFAdd", "v_sub_f16": "OpFSub", "v_subrev_f16": "OpFSub", "v_mul_f16": "OpFMul"}.get(op) - if k: - self.emit(f"{r} = {k} %float {vals[0]} {vals[1]}") - if k == "OpFAdd": - r = self.sum_toward_zero(vals[0], vals[1], r) - elif k == "OpFSub" and self.round_mode: - ny = self.tmp() - self.emit(f"{ny} = OpFNegate %float {vals[1]}") - r = self.sum_toward_zero(vals[0], ny, r) - else: - self.emit(f"{r} = OpExtInst %float %glsl {'NMax' if 'max' in op else 'NMin'} {vals[0]} {vals[1]}") - self._finish_f16_minmax_out(a[0], r, mods, dhi, all_nan, h0_mod) - if k: - r = self.clamp_f16(r, mods) - # an f16 sum is exact below 2^-14; clamp keeps that, omod is ignored on f16 - exact = k in ("OpFAdd", "OpFSub") - self.f16_out(a[0], r, dhi, exact_tiny=exact) # GFX10: f16 ops keep the other half - elif op.startswith(("v_cmp_", "v_cmpx_")) and op.endswith(("_u64", "_i64")) and op.split("_")[2] in ("eq", "ne", "lg"): - # 64-bit equality compare: both halves of the register pairs. GFX10 v_cmpx has no destination operand: - # it writes EXEC only (inactive lanes stay inactive). - cmpx = op.startswith("v_cmpx_") - d, x, y = (None, a[-2], a[-1]) if cmpx else (a[0], a[1], a[2]) - def pair(s): - if s["k"] == "vgpr" and s.get("n") == 2: - return self.load_reg(s["k"], s["r"]), self.load_reg(s["k"], s["r"] + 1) - return self.src64_data(s, op) - (x0, x1), (y0, y1) = pair(x), pair(y) - e0, e1, eq, r = (self.tmp() for _ in range(4)) - self.emit(f"{e0} = OpIEqual %bool {x0} {y0}") - self.emit(f"{e1} = OpIEqual %bool {x1} {y1}") - self.emit(f"{eq} = OpLogicalAnd %bool {e0} {e1}") - if op.split("_")[2] != "eq": - ne = self.tmp() - self.emit(f"{ne} = OpLogicalNot %bool {eq}") - eq = ne - if cmpx: - both = self.tmp() - self.emit(f"{both} = OpLogicalAnd %bool {eq} {self.active_b()}") - self.emit(f"OpStore %active {both}") - self.uses_active = True - else: - eqa = self.tmp() - self.emit(f"{eqa} = OpLogicalAnd %bool {eq} {self.active_b()}") # inactive lanes write 0 - self.emit(f"{r} = OpSelect %uint {eqa} {self.cu(0xFFFFFFFF)} {self.cu(0)}") - self.mask_dst(d, r) - elif op == "s_not_b32": - to_mask_dst, dst_half = self._mask_b32_dst_half(a[0], a[1:2]) - x_val = self.imm_val(a[1]) - if x_val is not None and not to_mask_dst and not self.holds_lane_mask(a[1]): - val = (~x_val) & 0xFFFFFFFF - r = self.cu(val) - self.dst(a[0], r) - if a[0]["k"] == "sgpr" and a[0].get("n", 1) == 1: - self.sgpr_imm[a[0]["r"]] = val - self.emit(f"OpStore %scc {self.cu(1 if val != 0 else 0)}") - else: - x = (self._mask_b32_src(a[1], dst_half) - if (to_mask_dst and self._maskable_b32(a[1])) else self.src_u(a[1])) - r = self.tmp() - self.emit(f"{r} = OpNot %uint {x}") - self._store_b32_mask_dst(a[0], r, to_mask_dst, dst_half) - self.scc_logic(a, r) - elif op in SOPC_CMP64_OPS: - self._validate_sopc(ins, op, a, mods, src0_64=True, src1_64=True) - # 64-bit compare of masks/pointers: equal iff both halves are equal. - # Only canonical full-wave masks (exec, mask vcc, or a wave64 (MASK_LO, MASK_HI) pair) can take the - # per-lane vote path; pairs with EITHER (0/-1), plain data, swapped/duplicated halves, or wave32 masks - # materialize each 32-bit word independently so inactive/unlaunched lanes and data halves stay exact. - def _is_full_wave_mask(s): - if s["k"] == "special": - t = s.get("t", "") - return t == "exec" or (t == "vcc" and "vcc" in self.cur_masks) - if self.wave64 and s["k"] == "sgpr" and s.get("n") == 2: - r = s["r"] - return (self.cur_masks.get(r) == lane_masks.MASK_LO - and self.cur_masks.get(r + 1) == lane_masks.MASK_HI) - return False - - def _is_u64_zero(src): - return src["k"] == "imm" and (src["v"] & 0xFFFFFFFFFFFFFFFF) == 0 - - f0, f1 = _is_full_wave_mask(a[0]), _is_full_wave_mask(a[1]) - use_vote = (f0 and f1) or (f0 and _is_u64_zero(a[1])) or (f1 and _is_u64_zero(a[0])) - if use_vote: - x = self.mask_src(a[0]) if f0 else self.cu(0) - y = self.mask_src(a[1]) if f1 else self.cu(0) - eq = self.tmp() - self.emit(f"{eq} = OpIEqual %bool {x} {y}") - eq = self.wave_equal(eq, True) - else: - def halves(s, is_full): - if is_full: - return self.wave_mask(s) - if s["k"] == "sgpr" and s.get("n") == 2: - words = [] - for i in range(2): - r = s["r"] + i - rk = self.cur_masks.get(r) - if rk is not None: - lo, hi = self.wave_mask({"k": "sgpr", "r": r, "n": 1}) - words.append(hi if (self.wave64 and rk == lane_masks.MASK_HI) else lo) - else: - words.append(self.load_reg("sgpr", r)) - return words[0], words[1] - if s["k"] == "imm": - v = s["v"] & 0xFFFFFFFFFFFFFFFF - return self.cu(v & 0xFFFFFFFF), self.cu(v >> 32) - if s["k"] == "special" and s.get("t") == "null": - return self.cu(0), self.cu(0) - if self.holds_lane_mask(s): - return self.wave_mask(s) - if s["k"] == "special" and s.get("t") == "vcc": - lo, hi = self.tmp(), self.tmp() - self.emit(f"{lo} = OpLoad %uint %vcc") - self.emit(f"{hi} = OpLoad %uint %vcc_hi") - return lo, hi - m = self.mask_src(s) - return m, m - - (x0, x1), (y0, y1) = halves(a[0], f0), halves(a[1], f1) - e0, e1, eq = self.tmp(), self.tmp(), self.tmp() - self.emit(f"{e0} = OpIEqual %bool {x0} {y0}") - self.emit(f"{e1} = OpIEqual %bool {x1} {y1}") - self.emit(f"{eq} = OpLogicalAnd %bool {e0} {e1}") - if op == "s_cmp_lg_u64": - ne = self.tmp() - self.emit(f"{ne} = OpLogicalNot %bool {eq}") - eq = ne - r = self.tmp() - self.emit(f"{r} = OpSelect %uint {eq} {self.cu(1)} {self.cu(0)}") - self.emit(f"OpStore %scc {r}") - elif op.startswith("buffer_atomic_"): - self.buffer_atomic(op, a, mods) - elif op == "image_get_lod": - self.image_get_lod(a, mods) - self.mimg_status(op, a, mods) - elif op == "s_addk_i32": - v = a[1]["v"] & 0xFFFF - k = v - 0x10000 if v & 0x8000 else v - x = self.src_u(a[0]) # the destination can be m0/vcc_hi as well as an SGPR - r = self.tmp() - self.emit(f"{r} = OpIAdd %uint {x} {self.cu(k)}") - self.dst(a[0], r) - self.scc_add_overflow(x, self.cu(k & 0xFFFFFFFF), r) - elif op in ("v_add_co_u32", "v_add_co_ci_u32", "v_sub_co_u32", "v_sub_co_ci_u32", "v_subrev_co_u32", - "v_subrev_co_ci_u32"): - # Lane masks are all-ones/zero: carry in = (vcc or the named mask) != 0, carry out stored the same way. - if op.endswith("ci_u32") and len(a) == 3: - # the assembler's short form v_add_co_ci_u32 vD, src0, src1: carry out and in are VCC (llvm-mc and the - # disassembler print it as v_add_co_ci_u32_e32 vD, vcc_lo, src0, src1, vcc_lo) - vcc = {"k": "special", "t": "vcc"} - a = [a[0], vcc, a[1], a[2], vcc] - vd, cd = a[0], a[1] - srcs = a[2:] - x, y = self.src_u(srcs[0]), self.src_u(srcs[1]) - if op.startswith("v_subrev_co"): - x, y = y, x - sub = "sub" in op - if op.endswith("ci_u32"): - cin_m = self.mask_src(srcs[2]) if len(srcs) > 2 else self.mask_src({"k": "special", "t": "vcc"}) - cin = self.tmp() - self.emit(f"{cin} = OpSelect %uint {self.tmp_bool_nz(cin_m)} {self.cu(1)} {self.cu(0)}") - else: - cin = self.cu(0) - s1, c1, s2, c2, r, carry = (self.tmp() for _ in range(6)) - if sub: - self.emit(f"{s1} = OpISubBorrow %umul {x} {y}") - else: - self.emit(f"{s1} = OpIAddCarry %umul {x} {y}") - r1 = self.tmp() - self.emit(f"{r1} = OpCompositeExtract %uint {s1} 0") - self.emit(f"{c1} = OpCompositeExtract %uint {s1} 1") - self.emit(f"{s2} = {'OpISubBorrow' if sub else 'OpIAddCarry'} %umul {r1} {cin}") - self.emit(f"{r} = OpCompositeExtract %uint {s2} 0") - self.emit(f"{c2} = OpCompositeExtract %uint {s2} 1") - self.emit(f"{carry} = OpBitwiseOr %uint {c1} {c2}") - carry_nz = self.tmp_bool_nz(carry) - if "clamp" in mods: - # Hardware saturates D (0xffffffff on add carry, 0 on sub borrow) while reporting the real carry/borrow. - clamped = self.tmp() - self.emit(f"{clamped} = OpSelect %uint {carry_nz} {self.cu(0) if sub else self.cu(0xFFFFFFFF)} {r}") - r = clamped - self.dst(vd, r) - if not (cd["k"] == "special" and cd["t"] == "null"): - cm, m = self.tmp(), self.tmp() - self.emit(f"{cm} = OpLogicalAnd %bool {carry_nz} {self.active_b()}") # inactive lanes write 0 - self.emit(f"{m} = OpSelect %uint {cm} {self.cu(0xFFFFFFFF)} {self.cu(0)}") - self.mask_dst(cd, m) - elif op == "v_mul_legacy_f32": - # The inferred game's f32 denorm mode is flush-in/flush-out. Unlike an IEEE multiply, the legacy - # zero override gives +0 even when a negative subnormal operand becomes -0 after input flushing. - # Flush the product before omod: otherwise FLT_MIN * 0.5 mul:2 becomes FLT_MIN, not zero. - x, y = (self.flush_f32(self.src_f(t)) for t in a[1:3]) - m, zx, zy, either, r = (self.tmp() for _ in range(5)) - self.emit(f"{m} = OpFMul %float {x} {y}") - self.emit(f"{zx} = OpFOrdEqual %bool {x} %f0") - self.emit(f"{zy} = OpFOrdEqual %bool {y} %f0") - self.emit(f"{either} = OpLogicalOr %bool {zx} {zy}") - self.emit(f"{r} = OpSelect %float {either} %f0 {self.flush_f32(m)}") - r = self.flush_f32(self.clamp_mods(r, mods)) - if any(mod in ("mul:2", "mul:4", "div:2") for mod in mods): - # With IEEE off, omod makes -0 (including a flushed subnormal result) +0. - z, pos = self.tmp(), self.tmp() - self.emit(f"{z} = OpFOrdEqual %bool {r} %f0") - self.emit(f"{pos} = OpSelect %float {z} %f0 {r}") - r = pos - self.dst(a[0], self.tou(r)) - elif op in ("v_mad_legacy_f32", "v_mac_legacy_f32"): - # Legacy multiply treats 0 * anything (inf/NaN included) as 0, after the denormal flush. - # v_mac_legacy_f32 is the GFX10.1 VOP2 form with D as the addend, as v_mac_f32 is to v_mad_f32 (LLVM - # VOP2Instructions.td: V_MAC_LEGACY_F32 is VOP_F32_F32_F32 with $src2 tied to $vdst). - srcs = (a[1], a[2], a[0]) if op == "v_mac_legacy_f32" else a[1:4] - x, y, z = (self.flush_f32(self.src_f(t)) for t in srcs) - m, zx, zy, either, sel, r = (self.tmp() for _ in range(6)) - self.emit(f"{m} = OpFMul %float {x} {y}") - self.emit(f"{zx} = OpFOrdEqual %bool {x} %f0") - self.emit(f"{zy} = OpFOrdEqual %bool {y} %f0") - self.emit(f"{either} = OpLogicalOr %bool {zx} {zy}") - self.emit(f"{sel} = OpSelect %float {either} %f0 {self.flush_f32(m)}") - self.emit(f"{r} = OpFAdd %float {sel} {z}") - self.dst(a[0], self.tou(self.flush_f32_mods(r, mods))) - elif op in ("v_min3_i32", "v_min3_u32", "v_max3_i32", "v_max3_u32"): - x, y, z = (self.src_u(t) for t in a[1:4]) - f = ("S" if op.endswith("i32") else "U") + ("Min" if "min" in op else "Max") - m, r = self.tmp(), self.tmp() - self.emit(f"{m} = OpExtInst %uint %glsl {f} {x} {y}") - self.emit(f"{r} = OpExtInst %uint %glsl {f} {m} {z}") - self.dst(a[0], r) - elif op in ("v_med3_i32", "v_med3_u32"): - x, y, z = (self.src_u(t) for t in a[1:4]) - s = "S" if op.endswith("i32") else "U" - lo, hi, r = self.tmp(), self.tmp(), self.tmp() - self.emit(f"{lo} = OpExtInst %uint %glsl {s}Min {x} {y}") - self.emit(f"{hi} = OpExtInst %uint %glsl {s}Max {x} {y}") - self.emit(f"{r} = OpExtInst %uint %glsl {s}Clamp {z} {lo} {hi}") - self.dst(a[0], r) - elif op in ("v_div_fixup_f16", "v_div_fixup_f64"): - self._validate_div_valu( - ins, op, mods, - dst_width=1 if op == "v_div_fixup_f16" else 2, - src_width=1 if op == "v_div_fixup_f16" else None, - allow_opsel=op == "v_div_fixup_f16", - strict_omod=False, - ) - # Final IEEE-754 special-case fixup for division (RDNA2 ISA VOP3, S0=quot, S1=denom, S2=num): - # sign_out = sign(S1) ^ sign(S2); NaN(S2) -> quiet(S2); NaN(S1) -> quiet(S1); - # (0/0 or inf/inf) -> -qNaN; (x/inf or 0/y) -> +-0; (x/0 or inf/y or NaN(S0)) -> +-inf; - # otherwise copysign(S0, sign_out). Computed bit-exact on integer words; Float64 is only needed - # when VOP3 output modifiers (omod/clamp) are present on v_div_fixup_f64. - # The destination of both forms is a 16-bit or 64-bit float, and hardware ignores mul:/div: on those - # results while denorm_mode_16_64 = 3 (the game's MODE): measured with tools/hw_oracle on gfx1036, - # wave32 and wave64 identical, in tools/f64_omod_probe.py. clamp applies in every MODE. - has_clamp = "clamp" in mods - if op == "v_div_fixup_f16": - sel, dhi = self.opsel_bits(mods, 3) - def h16(sv, hi_half): - u = self.src_h(sv) - if hi_half: - t = self.tmp() - self.emit(f"{t} = OpShiftRightLogical %uint {u} {self.cu(16)}") - u = t - x = self.tmp() - self.emit(f"{x} = OpBitwiseAnd %uint {u} {self.cu(0xFFFF)}") - if sv.get("abs"): - t = self.tmp() - self.emit(f"{t} = OpBitwiseAnd %uint {x} {self.cu(0x7FFF)}") - x = t - if sv.get("neg"): - t = self.tmp() - self.emit(f"{t} = OpBitwiseXor %uint {x} {self.cu(0x8000)}") - x = t - return x - s0, s1, s2 = (h16(a[i + 1], sel[i]) for i in range(3)) - def cls16(w): - mag, iz, iinf, inan = (self.tmp() for _ in range(4)) - self.emit(f"{mag} = OpBitwiseAnd %uint {w} {self.cu(0x7FFF)}") - self.emit(f"{iz} = OpIEqual %bool {mag} {self.cu(0)}") - self.emit(f"{iinf} = OpIEqual %bool {mag} {self.cu(0x7C00)}") - self.emit(f"{inan} = OpUGreaterThan %bool {mag} {self.cu(0x7C00)}") - return mag, iz, iinf, inan - m0, _, _, nan0 = cls16(s0) - _, z1, inf1, nan1 = cls16(s1) - _, z2, inf2, nan2 = cls16(s2) - sx, sgn, inf_out, norm_out = (self.tmp() for _ in range(4)) - self.emit(f"{sx} = OpBitwiseXor %uint {s1} {s2}") - self.emit(f"{sgn} = OpBitwiseAnd %uint {sx} {self.cu(0x8000)}") - self.emit(f"{inf_out} = OpBitwiseOr %uint {sgn} {self.cu(0x7C00)}") - self.emit(f"{norm_out} = OpBitwiseOr %uint {sgn} {m0}") - b_zz, b_ii, b_ind, b_zero, b_inf1, b_inf = (self.tmp() for _ in range(6)) - self.emit(f"{b_zz} = OpLogicalAnd %bool {z1} {z2}") - self.emit(f"{b_ii} = OpLogicalAnd %bool {inf1} {inf2}") - self.emit(f"{b_ind} = OpLogicalOr %bool {b_zz} {b_ii}") - self.emit(f"{b_zero} = OpLogicalOr %bool {inf1} {z2}") - self.emit(f"{b_inf1} = OpLogicalOr %bool {z1} {inf2}") - self.emit(f"{b_inf} = OpLogicalOr %bool {b_inf1} {nan0}") - r1, r2, r3, r4, r5 = (self.tmp() for _ in range(5)) - self.emit(f"{r1} = OpSelect %uint {b_inf} {inf_out} {norm_out}") - self.emit(f"{r2} = OpSelect %uint {b_zero} {sgn} {r1}") - self.emit(f"{r3} = OpSelect %uint {b_ind} {self.cu(0xFE00)} {r2}") - self.emit(f"{r4} = OpSelect %uint {nan1} {s1} {r3}") - self.emit(f"{r5} = OpSelect %uint {nan2} {s2} {r4}") - if has_clamp: - v2f, fv = self.tmp(), self.tmp() - self.emit(f"{v2f} = OpExtInst %v2float %glsl UnpackHalf2x16 {r5}") - self.emit(f"{fv} = OpCompositeExtract %float {v2f} 0") - self.f16_out(a[0], self.clamp_f16(fv, mods), dhi) - elif not dhi: - self.write_lo16(a[0], r5) - else: - if a[0]["k"] != "vgpr": - raise Unsupported("op_sel destination") - old, keep, sh16, v = (self.tmp() for _ in range(4)) - self.emit(f"{old} = OpCopyObject %uint {self.load_reg('vgpr', a[0]['r'])}") - self.emit(f"{keep} = OpBitwiseAnd %uint {old} {self.cu(0xFFFF)}") - self.emit(f"{sh16} = OpShiftLeftLogical %uint {r5} {self.cu(16)}") - self.emit(f"{v} = OpBitwiseOr %uint {keep} {sh16}") - self.dst(a[0], v) - else: - d = a[0] - if d["k"] != "vgpr" or d.get("n") != 2: - raise Unsupported(op + " destination") - def d64_words(sv): - if sv["k"] in ("vgpr", "sgpr") and sv.get("n") == 2: - lo, hi = self.load_reg(sv["k"], sv["r"]), self.load_reg(sv["k"], sv["r"] + 1) - elif sv["k"] in ("imm", "fimm"): - bits = (struct.unpack("> 32) - else: - raise Unsupported(op + " operand") - if sv.get("abs"): - t = self.tmp() - self.emit(f"{t} = OpBitwiseAnd %uint {hi} {self.cu(0x7FFFFFFF)}") - hi = t - if sv.get("neg"): - t = self.tmp() - self.emit(f"{t} = OpBitwiseXor %uint {hi} {self.cu(0x80000000)}") - hi = t - return lo, hi - (lo0, hi0), (lo1, hi1), (lo2, hi2) = (d64_words(a[i]) for i in (1, 2, 3)) - def cls64(lo, hi): - mag, orz, iz, exp_all, loz, iinf, man_hi, man_or, man_nz, inan = (self.tmp() for _ in range(10)) - self.emit(f"{mag} = OpBitwiseAnd %uint {hi} {self.cu(0x7FFFFFFF)}") - self.emit(f"{orz} = OpBitwiseOr %uint {mag} {lo}") - self.emit(f"{iz} = OpIEqual %bool {orz} {self.cu(0)}") - self.emit(f"{exp_all} = OpIEqual %bool {mag} {self.cu(0x7FF00000)}") - self.emit(f"{loz} = OpIEqual %bool {lo} {self.cu(0)}") - self.emit(f"{iinf} = OpLogicalAnd %bool {exp_all} {loz}") - self.emit(f"{man_hi} = OpBitwiseAnd %uint {mag} {self.cu(0x7FF00000)}") - exp_max = self.tmp() - self.emit(f"{exp_max} = OpIEqual %bool {man_hi} {self.cu(0x7FF00000)}") - frac_hi = self.tmp() - self.emit(f"{frac_hi} = OpBitwiseAnd %uint {hi} {self.cu(0x000FFFFF)}") - self.emit(f"{man_or} = OpBitwiseOr %uint {frac_hi} {lo}") - self.emit(f"{man_nz} = OpINotEqual %bool {man_or} {self.cu(0)}") - self.emit(f"{inan} = OpLogicalAnd %bool {exp_max} {man_nz}") - return mag, iz, iinf, inan - m0, _, _, nan0 = cls64(lo0, hi0) - _, z1, inf1, nan1 = cls64(lo1, hi1) - _, z2, inf2, nan2 = cls64(lo2, hi2) - e1, e2, ediff, ediff_i, uf = (self.tmp() for _ in range(5)) - self.emit(f"{e1} = OpBitFieldUExtract %uint {hi1} {self.cu(20)} {self.cu(11)}") - self.emit(f"{e2} = OpBitFieldUExtract %uint {hi2} {self.cu(20)} {self.cu(11)}") - self.emit(f"{ediff} = OpISub %uint {e2} {e1}") - self.emit(f"{ediff_i} = OpBitcast %int {ediff}") - # Measured natively on RDNA2 gfx1036: underflow cutoff is e2 - e1 <= -1076 (no overflow check). - self.emit(f"{uf} = OpSLessThan %bool {ediff_i} {self.as_int(self.cu((-1075) & 0xFFFFFFFF))}") - sx, sgn, inf_hi, norm_hi = (self.tmp() for _ in range(4)) - self.emit(f"{sx} = OpBitwiseXor %uint {hi1} {hi2}") - self.emit(f"{sgn} = OpBitwiseAnd %uint {sx} {self.cu(0x80000000)}") - self.emit(f"{inf_hi} = OpBitwiseOr %uint {sgn} {self.cu(0x7FF00000)}") - self.emit(f"{norm_hi} = OpBitwiseOr %uint {sgn} {m0}") - b_zz, b_ii, b_ind, b_zero1, b_zero, b_inf1, b_inf = (self.tmp() for _ in range(7)) - self.emit(f"{b_zz} = OpLogicalAnd %bool {z1} {z2}") - self.emit(f"{b_ii} = OpLogicalAnd %bool {inf1} {inf2}") - self.emit(f"{b_ind} = OpLogicalOr %bool {b_zz} {b_ii}") - self.emit(f"{b_zero1} = OpLogicalOr %bool {inf1} {z2}") - self.emit(f"{b_zero} = OpLogicalOr %bool {b_zero1} {uf}") - self.emit(f"{b_inf1} = OpLogicalOr %bool {z1} {inf2}") - self.emit(f"{b_inf} = OpLogicalOr %bool {b_inf1} {nan0}") - z0 = self.cu(0) - h1, l1, h2, l2, h3, l3, h4, l4, r_hi, r_lo = (self.tmp() for _ in range(10)) - self.emit(f"{h1} = OpSelect %uint {b_inf} {inf_hi} {norm_hi}") - self.emit(f"{l1} = OpSelect %uint {b_inf} {z0} {lo0}") - self.emit(f"{h2} = OpSelect %uint {b_zero} {sgn} {h1}") - self.emit(f"{l2} = OpSelect %uint {b_zero} {z0} {l1}") - self.emit(f"{h3} = OpSelect %uint {b_ind} {self.cu(0xFFF80000)} {h2}") - self.emit(f"{l3} = OpSelect %uint {b_ind} {z0} {l2}") - self.emit(f"{h4} = OpSelect %uint {nan1} {hi1} {h3}") - self.emit(f"{l4} = OpSelect %uint {nan1} {lo1} {l3}") - self.emit(f"{r_hi} = OpSelect %uint {nan2} {hi2} {h4}") - self.emit(f"{r_lo} = OpSelect %uint {nan2} {lo2} {l4}") - if has_clamp: - self.uses_f64 = True - v2, dv, mv2 = self.tmp(), self.tmp(), self.tmp() - self.emit(f"{v2} = OpCompositeConstruct %v2uint_d {r_lo} {r_hi}") - self.emit(f"{dv} = OpBitcast %double {v2}") - dv = self.clamp_mods_f64(dv, [m for m in mods if m == "clamp"]) - self.emit(f"{mv2} = OpBitcast %v2uint_d {dv}") - r_lo, r_hi = self.tmp(), self.tmp() - self.emit(f"{r_lo} = OpCompositeExtract %uint {mv2} 0") - self.emit(f"{r_hi} = OpCompositeExtract %uint {mv2} 1") - self.dst({"k": "vgpr", "r": d["r"], "n": 1}, r_lo) - self.dst({"k": "vgpr", "r": d["r"] + 1, "n": 1}, r_hi) - elif op.startswith("s_load_dword") or op.startswith("s_buffer_load_dword"): - self.scalar_load(op, a, ins["mods"]) - elif op in ("s_memtime", "s_memrealtime"): - d = a[0] - if d["k"] != "sgpr" or d.get("n") != 2: - raise Unsupported(op + " destination") - if not SHADER_CLOCK: - raise Unsupported(op + " (needs --shader-clock khr)") - scope = "subgroup" if op == "s_memtime" else "device" - self.uses_clock.add(scope) - v, lo, hi = self.tmp(), self.tmp(), self.tmp() - self.emit(f"{v} = OpReadClockKHR %v2uint_d {self.cu(3 if scope == 'subgroup' else 1)}") - self.emit(f"{lo} = OpCompositeExtract %uint {v} 0") - self.emit(f"{hi} = OpCompositeExtract %uint {v} 1") - self.store_reg("sgpr", d["r"], lo) - self.store_reg("sgpr", d["r"] + 1, hi) - elif op in ("s_lshl_b64", "s_lshr_b64", "s_ashr_i64"): - # 64-bit shift of an SGPR pair by (src1 & 63); SCC = result != 0. - d, x = a[0], a[1] - if d["k"] != "sgpr" or d.get("n") != 2: - raise Unsupported(op + " destination") - if x["k"] == "sgpr" and x.get("n") == 2: - lo, hi = self.load_reg("sgpr", x["r"]), self.load_reg("sgpr", x["r"] + 1) - elif x["k"] == "imm": - v = x["v"] & 0xFFFFFFFFFFFFFFFF - lo, hi = self.cu(v & 0xFFFFFFFF), self.cu(v >> 32) - else: - raise Unsupported(op + " source") - sh = self.src_u(a[2]) - l64, h64, t, v64, m, s64, r, rlo, rh, rhi = (self.tmp() for _ in range(10)) - self.emit(f"{l64} = OpUConvert %ulong {lo}") - self.emit(f"{h64} = OpUConvert %ulong {hi}") - self.emit(f"{t} = OpShiftLeftLogical %ulong {h64} %c64_32") - self.emit(f"{v64} = OpBitwiseOr %ulong {t} {l64}") - self.emit(f"{m} = OpBitwiseAnd %uint {sh} {self.cu(63)}") - self.emit(f"{s64} = OpUConvert %ulong {m}") - if op == "s_ashr_i64": - vs64, rs64 = self.tmp(), self.tmp() - self.emit(f"{vs64} = OpBitcast %long {v64}") - self.emit(f"{rs64} = OpShiftRightArithmetic %long {vs64} {s64}") - self.emit(f"{r} = OpBitcast %ulong {rs64}") - elif op == "s_lshl_b64": - self.emit(f"{r} = OpShiftLeftLogical %ulong {v64} {s64}") - else: - self.emit(f"{r} = OpShiftRightLogical %ulong {v64} {s64}") - self.emit(f"{rlo} = OpUConvert %uint {r}") - self.emit(f"{rh} = OpShiftRightLogical %ulong {r} %c64_32") - self.emit(f"{rhi} = OpUConvert %uint {rh}") - self.store_reg("sgpr", d["r"], rlo) - self.store_reg("sgpr", d["r"] + 1, rhi) - nz, z = self.tmp(), self.tmp() - orr = self.tmp() - self.emit(f"{orr} = OpBitwiseOr %uint {rlo} {rhi}") - self.emit(f"{z} = OpSelect %uint {self.tmp_bool_nz(orr)} {self.cu(1)} {self.cu(0)}") - self.emit(f"OpStore %scc {z}") - self.uses_psb = True # Int64 capability and %ulong come with the PSB declarations - elif op == "s_ashr_i32": - x, sh = self.src_u(a[1]), self.src_u(a[2]) - m, xi, ri, r = (self.tmp() for _ in range(4)) - self.emit(f"{m} = OpBitwiseAnd %uint {sh} {self.cu(31)}") - self.emit(f"{xi} = OpBitcast %int {x}") - self.emit(f"{ri} = OpShiftRightArithmetic %int {xi} {m}") - self.emit(f"{r} = OpBitcast %uint {ri}") - self.dst(a[0], r) - z = self.tmp() - self.emit(f"{z} = OpSelect %uint {self.tmp_bool_nz(r)} {self.cu(1)} {self.cu(0)}") - self.emit(f"OpStore %scc {z}") - elif op.startswith("global_atomic_"): - self.global_atomic(op, a, mods) - elif op in self.GLOBAL_SUB: - self.global_sub(op, a, mods) - elif op.startswith(("global_load_dword", "global_store_dword")) or \ - op in ("global_load_ushort", "global_load_sshort", "global_load_ubyte", "global_load_sbyte"): - self.global_mem(op, a, mods) - elif op in ("s_add_u32", "s_addc_u32", "s_sub_u32", "s_subb_u32"): - # 32-bit add/sub with carry/borrow through SCC (used for 64-bit address arithmetic, e.g. s_getpc + offset). - sub = op.startswith("s_sub") - val = None - if op in ("s_add_u32", "s_sub_u32"): - x_val, y_val = self.imm_val(a[1]), self.imm_val(a[2]) - if x_val is not None and y_val is not None: - if sub: - val = (x_val - y_val) & 0xFFFFFFFF - else: - val = (x_val + y_val) & 0xFFFFFFFF - x, y = self.src_u(a[1]), self.src_u(a[2]) - s1, r1, c1 = self.tmp(), self.tmp(), self.tmp() - self.emit(f"{s1} = {'OpISubBorrow' if sub else 'OpIAddCarry'} %umul {x} {y}") - self.emit(f"{r1} = OpCompositeExtract %uint {s1} 0") - self.emit(f"{c1} = OpCompositeExtract %uint {s1} 1") - r, carry = r1, c1 - if op in ("s_addc_u32", "s_subb_u32"): - cin, s2, r2, c2, cc = (self.tmp() for _ in range(5)) - self.emit(f"{cin} = OpLoad %uint %scc") - self.emit(f"{s2} = {'OpISubBorrow' if sub else 'OpIAddCarry'} %umul {r1} {cin}") - self.emit(f"{r2} = OpCompositeExtract %uint {s2} 0") - self.emit(f"{c2} = OpCompositeExtract %uint {s2} 1") - self.emit(f"{cc} = OpBitwiseOr %uint {c1} {c2}") - r, carry = r2, cc - self.dst(a[0], r) - self.emit(f"OpStore %scc {carry}") - if val is not None and a[0]["k"] == "sgpr" and a[0].get("n", 1) == 1: - self.sgpr_imm[a[0]["r"]] = val - elif op in ("s_lshl1_add_u32", "s_lshl2_add_u32", "s_lshl3_add_u32", "s_lshl4_add_u32"): - # D = (S0 << N) + S1. SCC = unsigned overflow of the sum taken in 64 bits (RDNA ISA pseudocode: - # tmp = (64'U(S0) << N) + 64'U(S1); SCC = tmp >= 2^32), so bits shifted out of S0 count as a carry too. - n = int(op[6]) - val = None - x_val, y_val = self.imm_val(a[1]), self.imm_val(a[2]) - if x_val is not None and y_val is not None: - val = ((x_val << n) + y_val) & 0xFFFFFFFF - x, y = self.src_u(a[1]), self.src_u(a[2]) - sh, out, s, r, c, ovf = (self.tmp() for _ in range(6)) - self.emit(f"{sh} = OpShiftLeftLogical %uint {x} {self.cu(n)}") - self.emit(f"{out} = OpShiftRightLogical %uint {x} {self.cu(32 - n)}") - self.emit(f"{s} = OpIAddCarry %umul {sh} {y}") - self.emit(f"{r} = OpCompositeExtract %uint {s} 0") - self.emit(f"{c} = OpCompositeExtract %uint {s} 1") - self.emit(f"{ovf} = OpBitwiseOr %uint {out} {c}") - self.dst(a[0], r) - self.scc_nonzero(ovf) - if val is not None and a[0]["k"] == "sgpr" and a[0].get("n", 1) == 1: - self.sgpr_imm[a[0]["r"]] = val - elif op == "s_get_waveid_in_workgroup": - # D = this wave's index in its workgroup: thread i of a group is in wave i / W (W = 64 or 32), the rule - # wave_lane uses for the lane. Only compute and mesh shaders have a workgroup. SCC is not written. - if self.stage not in ("cs", "ms"): - raise Unsupported(op + " outside compute") - r = self.tmp() - self.emit(f"{r} = OpShiftRightLogical %uint {self.local_index()} {self.cu(6 if self.wave64 else 5)}") - self.dst(a[0], r) - elif op == "s_getpc_b64": - # Address of the next instruction: code base (push constants 34-35: where the runtime put this shader's - # FSSM blob in the Xbox VA window) + offset of the next instruction within the blob. - if a[0]["k"] != "sgpr" or a[0].get("n") != 2: - raise Unsupported("s_getpc_b64 destination") - if not ins.get("enc"): - # Without the `; encoding:` bytes the instruction's size, and so the next PC, is unknown. - raise Unsupported("s_getpc_b64 without encoding") - nxt = ins["pc"] + len(ins["enc"]) // 2 - lo, hi, s, rlo, c, rhi = (self.tmp() for _ in range(6)) - self.emit(f"{lo} = OpLoad %uint %ud_code_lo_p") - self.emit(f"{hi} = OpLoad %uint %ud_code_hi_p") - self.emit(f"{s} = OpIAddCarry %umul {lo} {self.cu(nxt)}") - self.emit(f"{rlo} = OpCompositeExtract %uint {s} 0") - self.emit(f"{c} = OpCompositeExtract %uint {s} 1") - self.emit(f"{rhi} = OpIAdd %uint {hi} {c}") - self.store_reg("sgpr", a[0]["r"], rlo) - self.store_reg("sgpr", a[0]["r"] + 1, rhi) - self.uses_codebase = True - self.cu(3), self.cu(4) - elif op in ("s_add_i32", "s_sub_i32", "s_min_u32", "s_max_u32", "s_xor_b32", "s_andn2_b32", - "s_cselect_b32", "s_orn2_b32", "s_nand_b32", "s_nor_b32", "s_xnor_b32"): - val = None - to_mask_dst, dst_half = (self._mask_b32_dst_half(a[0], a[1:3]) - if op in self.MASK_SOP2_B32 else (False, None)) - if op in ("s_xor_b32", "s_andn2_b32", "s_orn2_b32", "s_nand_b32", "s_nor_b32", "s_xnor_b32"): - x_val, y_val = self.imm_val(a[1]), self.imm_val(a[2]) - is_mask = to_mask_dst or self.holds_lane_mask(a[1]) or self.holds_lane_mask(a[2]) - if x_val is not None and y_val is not None and not is_mask: - if op == "s_xor_b32": - val = (x_val ^ y_val) & 0xFFFFFFFF - r = self.cu(val) - self.dst(a[0], r) - if a[0]["k"] == "sgpr" and a[0].get("n", 1) == 1: - self.sgpr_imm[a[0]["r"]] = val - self.emit(f"OpStore %scc {self.cu(1 if val != 0 else 0)}") - return - elif op == "s_andn2_b32": - val = (x_val & (~y_val)) & 0xFFFFFFFF - elif op == "s_orn2_b32": - val = (x_val | (~y_val)) & 0xFFFFFFFF - elif op == "s_nand_b32": - val = (~(x_val & y_val)) & 0xFFFFFFFF - elif op == "s_nor_b32": - val = (~(x_val | y_val)) & 0xFFFFFFFF - elif op == "s_xnor_b32": - val = (~(x_val ^ y_val)) & 0xFFFFFFFF - elif op in ("s_min_u32", "s_max_u32"): - x_val, y_val = self.imm_val(a[1]), self.imm_val(a[2]) - if x_val is not None and y_val is not None: - val = min(x_val, y_val) if "min" in op else max(x_val, y_val) - elif op in ("s_add_i32", "s_sub_i32"): - x_val, y_val = self.imm_val(a[1]), self.imm_val(a[2]) - if x_val is not None and y_val is not None: - xi = x_val if x_val < 0x80000000 else x_val - 0x100000000 - yi = y_val if y_val < 0x80000000 else y_val - 0x100000000 - val = (xi + yi if op == "s_add_i32" else xi - yi) & 0xFFFFFFFF - x, y = self.sop2_b32_srcs(op, a) - r = self.tmp() - if op == "s_cselect_b32": - c, b = self.tmp(), self.tmp() - self.emit(f"{c} = OpLoad %uint %scc") - self.emit(f"{b} = OpINotEqual %bool {c} {self.cu(0)}") - self.emit(f"{r} = OpSelect %uint {b} {x} {y}") - elif op == "s_andn2_b32": - n = self.tmp() - self.emit(f"{n} = OpNot %uint {y}") - self.emit(f"{r} = OpBitwiseAnd %uint {x} {n}") - elif op in ("s_min_u32", "s_max_u32"): - self.emit(f"{r} = OpExtInst %uint %glsl {'UMin' if 'min' in op else 'UMax'} {x} {y}") - elif op == "s_orn2_b32": - n = self.tmp() - self.emit(f"{n} = OpNot %uint {y}") - self.emit(f"{r} = OpBitwiseOr %uint {x} {n}") - elif op in ("s_nand_b32", "s_nor_b32", "s_xnor_b32"): - t = self.tmp() - k = {"s_nand_b32": "OpBitwiseAnd", "s_nor_b32": "OpBitwiseOr", "s_xnor_b32": "OpBitwiseXor"}[op] - self.emit(f"{t} = {k} %uint {x} {y}") - self.emit(f"{r} = OpNot %uint {t}") - else: - k = {"s_add_i32": "OpIAdd", "s_sub_i32": "OpISub", "s_sub_u32": "OpISub", - "s_xor_b32": "OpBitwiseXor"}[op] - self.emit(f"{r} = {k} %uint {x} {y}") - self._store_b32_mask_dst(a[0], r, to_mask_dst, dst_half) - # SCC (RDNA ISA): bitwise ops -> result != 0; s_add/sub_i32 -> signed overflow; - # s_min_u32 -> S0 < S1, s_max_u32 -> S0 > S1; s_cselect leaves SCC. - if op in ("s_xor_b32", "s_andn2_b32", "s_orn2_b32", "s_nand_b32", "s_nor_b32", "s_xnor_b32"): - self.scc_logic(a, r) - elif op in ("s_add_i32", "s_sub_i32"): - self.scc_add_overflow(x, y, r, sub=op == "s_sub_i32") - elif op in ("s_min_u32", "s_max_u32"): - b = self.tmp() - self.emit(f"{b} = {'OpULessThan' if 'min' in op else 'OpUGreaterThan'} %bool {x} {y}") - self.set_scc(b) - if val is not None and a[0]["k"] == "sgpr" and a[0].get("n", 1) == 1: - self.sgpr_imm[a[0]["r"]] = val - elif op in ("s_wqm_b64", "s_wqm_b32"): - self.wqm(op, a) - elif op == "v_fma_mix_f32": - # Each source is f32, or (op_sel_hi bit set) an f16 from the low/high half chosen by op_sel. - vals = self.fma_mix_srcs(a, mods) - r = self.tmp() - self.emit_fma(r, vals[0], vals[1], vals[2]) - self.dst(a[0], self.tou(self.clamp_mods(r, mods))) - elif op in ("v_div_fmas_f32", "v_div_fmas_f64"): - self._validate_div_valu( - ins, op, mods, - dst_width=1 if op == "v_div_fmas_f32" else 2, - src_width=1 if op == "v_div_fmas_f32" else None, - allow_opsel=False, - strict_omod=True, - allow_null_dst=op == "v_div_fmas_f32", - ) - # Scaled FMA for IEEE-754 division (RDNA2 ISA VOP3, measured natively on gfx1036 wave32/wave64): - # VCC == 0: fma(S0, S1, S2) - # VCC == 1: (exp(S2) > bias ? 2^S : 2^-S) * fma_exact(S0, S1, S2) - # where (bias, S) = (127, 64) for f32 and (1023, 128) for f64 (exp(S2) > bias <=> |S2| >= 2.0). - # Scale-up (|S2| >= 2.0): any non-zero cancellation residual against |S2| >= 2.0 stays well above - # normal minimum, and any intermediate overflow overflows after * 2^S too, so fma(x, y, z) * 2^S is - # exact. Scale-down (|S2| < 2.0): pre-scale only when |x*y| can overflow (|x|>=2^S & |y|>=1, or - # |y|>=2^S & |x|>=1, or |x|,|y|>=2^(S/2)), preserving a sticky bit when 0 < |z| < 2^(Emin+S); - # otherwise post-scale fma(x, y, z) * 2^-S (with f64 subnormal half-ULP tie correction so f64 - # subnormal outputs single-round, and f32 output denormal flush matching denorm32=0). - vcc_b = self.tmp_bool_nz(self.mask_src({"k": "special", "t": "vcc"})) - if op == "v_div_fmas_f32": - x, y, z = (self.src_f(t) for t in a[1:4]) - ax, ay, az, f_plain, scale_up, f_up = (self.tmp() for _ in range(6)) - self.emit(f"{ax} = OpExtInst %float %glsl FAbs {x}") - self.emit(f"{ay} = OpExtInst %float %glsl FAbs {y}") - self.emit(f"{az} = OpExtInst %float %glsl FAbs {z}") - self.emit_fma(f_plain, x, y, z) - self.emit(f"{scale_up} = OpFOrdGreaterThanEqual %bool {az} {self.fconst(2.0)}") - self.emit(f"{f_up} = OpFMul %float {f_plain} {self.fconst(2.0 ** 64)}") - gx64, gy1, bx, gy64, gx1, by, gx32, gy32, bxy, b1, big = (self.tmp() for _ in range(11)) - self.emit(f"{gx64} = OpFOrdGreaterThanEqual %bool {ax} {self.fconst(2.0 ** 64)}") - self.emit(f"{gy1} = OpFOrdGreaterThanEqual %bool {ay} {self.fconst(1.0)}") - self.emit(f"{bx} = OpLogicalAnd %bool {gx64} {gy1}") - self.emit(f"{gy64} = OpFOrdGreaterThanEqual %bool {ay} {self.fconst(2.0 ** 64)}") - self.emit(f"{gx1} = OpFOrdGreaterThanEqual %bool {ax} {self.fconst(1.0)}") - self.emit(f"{by} = OpLogicalAnd %bool {gy64} {gx1}") - self.emit(f"{gx32} = OpFOrdGreaterThanEqual %bool {ax} {self.fconst(2.0 ** 32)}") - self.emit(f"{gy32} = OpFOrdGreaterThanEqual %bool {ay} {self.fconst(2.0 ** 32)}") - self.emit(f"{bxy} = OpLogicalAnd %bool {gx32} {gy32}") - self.emit(f"{b1} = OpLogicalOr %bool {bx} {by}") - self.emit(f"{big} = OpLogicalOr %bool {b1} {bxy}") - xm64, ym64, xm32, ym32, xs1, xs, ys1, ys = (self.tmp() for _ in range(8)) - self.emit(f"{xm64} = OpFMul %float {x} {self.fconst(2.0 ** -64)}") - self.emit(f"{ym64} = OpFMul %float {y} {self.fconst(2.0 ** -64)}") - self.emit(f"{xm32} = OpFMul %float {x} {self.fconst(2.0 ** -32)}") - self.emit(f"{ym32} = OpFMul %float {y} {self.fconst(2.0 ** -32)}") - self.emit(f"{xs1} = OpSelect %float {by} {x} {xm32}") - self.emit(f"{xs} = OpSelect %float {bx} {xm64} {xs1}") - self.emit(f"{ys1} = OpSelect %float {by} {ym64} {ym32}") - self.emit(f"{ys} = OpSelect %float {bx} {y} {ys1}") - zu, zmag, znz, zlt, ztiny, zsgn, zst_u, zst, z_sc, zs = (self.tmp() for _ in range(10)) - self.emit(f"{zu} = OpBitcast %uint {z}") - self.emit(f"{zmag} = OpBitwiseAnd %uint {zu} {self.cu(0x7FFFFFFF)}") - self.emit(f"{znz} = OpINotEqual %bool {zmag} {self.cu(0)}") - self.emit(f"{zlt} = OpULessThan %bool {zmag} {self.cu(0x20800000)}") - self.emit(f"{ztiny} = OpLogicalAnd %bool {znz} {zlt}") - self.emit(f"{zsgn} = OpBitwiseAnd %uint {zu} {self.cu(0x80000000)}") - self.emit(f"{zst_u} = OpBitwiseOr %uint {zsgn} {self.cu(0x00800000)}") - self.emit(f"{zst} = OpBitcast %float {zst_u}") - self.emit(f"{z_sc} = OpFMul %float {z} {self.fconst(2.0 ** -64)}") - self.emit(f"{zs} = OpSelect %float {ztiny} {zst} {z_sc}") - f_pre, f_post, f_dn, sc, r = (self.tmp() for _ in range(5)) - self.emit_fma(f_pre, xs, ys, zs) - self.emit(f"{f_post} = OpFMul %float {f_plain} {self.fconst(2.0 ** -64)}") - self.emit(f"{f_dn} = OpSelect %float {big} {f_pre} {f_post}") - self.emit(f"{sc} = OpSelect %float {scale_up} {f_up} {f_dn}") - self.emit(f"{r} = OpSelect %float {vcc_b} {sc} {f_plain}") - r = self.flush_f32(r) - if mods: - r = self.clamp_mods(r, mods) - if any(m in ("mul:2", "mul:4", "div:2") for m in mods): - r = self.flush_f32(r) - self.dst(a[0], self.tou(r)) - else: - def f64(sv): - if sv["k"] in ("vgpr", "sgpr") and sv.get("n") == 2: - lo, hi = self.load_reg(sv["k"], sv["r"]), self.load_reg(sv["k"], sv["r"] + 1) - elif sv["k"] in ("imm", "fimm"): - bits = (struct.unpack("> 32) - else: - raise Unsupported(op + " operand") - v2, d = self.tmp(), self.tmp() - self.emit(f"{v2} = OpCompositeConstruct %v2uint_d {lo} {hi}") - self.emit(f"{d} = OpBitcast %double {v2}") - if sv.get("abs"): - t = self.tmp() - self.emit(f"{t} = OpExtInst %double %glsl FAbs {d}") - d = t - if sv.get("neg"): - t = self.tmp() - self.emit(f"{t} = OpFNegate %double {d}") - d = t - return d - d = a[0] - if d["k"] != "vgpr" or d.get("n") != 2: - raise Unsupported(op + " destination") - self.uses_f64 = True - x, y, z = (f64(t) for t in a[1:4]) - ax, ay, az, f_plain, scale_up, f_up = (self.tmp() for _ in range(6)) - self.emit(f"{ax} = OpExtInst %double %glsl FAbs {x}") - self.emit(f"{ay} = OpExtInst %double %glsl FAbs {y}") - self.emit(f"{az} = OpExtInst %double %glsl FAbs {z}") - self.emit_fma64(f_plain, x, y, z) - self.emit(f"{scale_up} = OpFOrdGreaterThanEqual %bool {az} {self.dconst(2.0)}") - self.emit(f"{f_up} = OpFMul %double {f_plain} {self.dconst(2.0 ** 128)}") - gx128, gy1, bx, gy128, gx1, by, gx64, gy64, bxy, b1, big = (self.tmp() for _ in range(11)) - self.emit(f"{gx128} = OpFOrdGreaterThanEqual %bool {ax} {self.dconst(2.0 ** 128)}") - self.emit(f"{gy1} = OpFOrdGreaterThanEqual %bool {ay} {self.dconst(1.0)}") - self.emit(f"{bx} = OpLogicalAnd %bool {gx128} {gy1}") - self.emit(f"{gy128} = OpFOrdGreaterThanEqual %bool {ay} {self.dconst(2.0 ** 128)}") - self.emit(f"{gx1} = OpFOrdGreaterThanEqual %bool {ax} {self.dconst(1.0)}") - self.emit(f"{by} = OpLogicalAnd %bool {gy128} {gx1}") - self.emit(f"{gx64} = OpFOrdGreaterThanEqual %bool {ax} {self.dconst(2.0 ** 64)}") - self.emit(f"{gy64} = OpFOrdGreaterThanEqual %bool {ay} {self.dconst(2.0 ** 64)}") - self.emit(f"{bxy} = OpLogicalAnd %bool {gx64} {gy64}") - self.emit(f"{b1} = OpLogicalOr %bool {bx} {by}") - self.emit(f"{big} = OpLogicalOr %bool {b1} {bxy}") - xm128, ym128, xm64, ym64, xs1, xs, ys1, ys = (self.tmp() for _ in range(8)) - self.emit(f"{xm128} = OpFMul %double {x} {self.dconst(2.0 ** -128)}") - self.emit(f"{ym128} = OpFMul %double {y} {self.dconst(2.0 ** -128)}") - self.emit(f"{xm64} = OpFMul %double {x} {self.dconst(2.0 ** -64)}") - self.emit(f"{ym64} = OpFMul %double {y} {self.dconst(2.0 ** -64)}") - self.emit(f"{xs1} = OpSelect %double {by} {x} {xm64}") - self.emit(f"{xs} = OpSelect %double {bx} {xm128} {xs1}") - self.emit(f"{ys1} = OpSelect %double {by} {ym128} {ym64}") - self.emit(f"{ys} = OpSelect %double {bx} {y} {ys1}") - zv2, zlo, zhi, zmag_hi, zmag_or, znz, zexp, zlt, ztiny, zsgn, zst_hi, zst_v2, zst, z_sc, zs = ( - self.tmp() for _ in range(15) - ) - self.emit(f"{zv2} = OpBitcast %v2uint_d {z}") - self.emit(f"{zlo} = OpCompositeExtract %uint {zv2} 0") - self.emit(f"{zhi} = OpCompositeExtract %uint {zv2} 1") - self.emit(f"{zmag_hi} = OpBitwiseAnd %uint {zhi} {self.cu(0x7FFFFFFF)}") - self.emit(f"{zmag_or} = OpBitwiseOr %uint {zmag_hi} {zlo}") - self.emit(f"{znz} = OpINotEqual %bool {zmag_or} {self.cu(0)}") - self.emit(f"{zexp} = OpBitwiseAnd %uint {zhi} {self.cu(0x7FF00000)}") - self.emit(f"{zlt} = OpULessThan %bool {zexp} {self.cu(129 << 20)}") - self.emit(f"{ztiny} = OpLogicalAnd %bool {znz} {zlt}") - self.emit(f"{zsgn} = OpBitwiseAnd %uint {zhi} {self.cu(0x80000000)}") - self.emit(f"{zst_hi} = OpBitwiseOr %uint {zsgn} {self.cu(0x00100000)}") - self.emit(f"{zst_v2} = OpCompositeConstruct %v2uint_d {self.cu(0)} {zst_hi}") - self.emit(f"{zst} = OpBitcast %double {zst_v2}") - self.emit(f"{z_sc} = OpFMul %double {z} {self.dconst(2.0 ** -128)}") - self.emit(f"{zs} = OpSelect %double {ztiny} {zst} {z_sc}") - f_pre = self.tmp() - self.emit_fma64(f_pre, xs, ys, zs) - # Subnormal-output single-rounding tie adjustment when |f_plain| in [2^-947, 2^-894). - pv2, plo, phi, pe_shift, pe_exp, e_ge, e_le, in_rng = (self.tmp() for _ in range(8)) - self.emit(f"{pv2} = OpBitcast %v2uint_d {f_plain}") - self.emit(f"{plo} = OpCompositeExtract %uint {pv2} 0") - self.emit(f"{phi} = OpCompositeExtract %uint {pv2} 1") - self.emit(f"{pe_shift} = OpShiftRightLogical %uint {phi} {self.cu(20)}") - self.emit(f"{pe_exp} = OpBitwiseAnd %uint {pe_shift} {self.cu(0x7FF)}") - self.emit(f"{e_ge} = OpUGreaterThanEqual %bool {pe_exp} {self.cu(76)}") - self.emit(f"{e_le} = OpULessThanEqual %bool {pe_exp} {self.cu(128)}") - self.emit(f"{in_rng} = OpLogicalAnd %bool {e_ge} {e_le}") - sh_raw, sh_c, sh_is_hi, sh_lo, lo_shr, lo_mask, lo_m1, lo_half, lo_and, tie_lo = ( - self.tmp() for _ in range(10) - ) - self.emit(f"{sh_raw} = OpISub %uint {self.cu(129)} {pe_exp}") - self.emit(f"{sh_c} = OpSelect %uint {in_rng} {sh_raw} {self.cu(1)}") - self.emit(f"{sh_is_hi} = OpUGreaterThan %bool {sh_c} {self.cu(32)}") - self.emit(f"{sh_lo} = OpSelect %uint {sh_is_hi} {self.cu(1)} {sh_c}") - self.emit(f"{lo_shr} = OpISub %uint {self.cu(32)} {sh_lo}") - self.emit(f"{lo_mask} = OpShiftRightLogical %uint {self.cu(0xFFFFFFFF)} {lo_shr}") - self.emit(f"{lo_m1} = OpISub %uint {sh_lo} {self.cu(1)}") - self.emit(f"{lo_half} = OpShiftLeftLogical %uint {self.cu(1)} {lo_m1}") - self.emit(f"{lo_and} = OpBitwiseAnd %uint {plo} {lo_mask}") - self.emit(f"{tie_lo} = OpIEqual %bool {lo_and} {lo_half}") - sh2_raw, sh2, hi_m, hi_sig, hi_shr, hi_mask, hi_m1, hi_half, hi_and, hi_eq, lo_z, tie_hi, is_tie = ( - self.tmp() for _ in range(13) - ) - self.emit(f"{sh2_raw} = OpISub %uint {sh_c} {self.cu(32)}") - self.emit(f"{sh2} = OpSelect %uint {sh_is_hi} {sh2_raw} {self.cu(1)}") - self.emit(f"{hi_m} = OpBitwiseAnd %uint {phi} {self.cu(0xFFFFF)}") - self.emit(f"{hi_sig} = OpBitwiseOr %uint {hi_m} {self.cu(0x100000)}") - self.emit(f"{hi_shr} = OpISub %uint {self.cu(32)} {sh2}") - self.emit(f"{hi_mask} = OpShiftRightLogical %uint {self.cu(0xFFFFFFFF)} {hi_shr}") - self.emit(f"{hi_m1} = OpISub %uint {sh2} {self.cu(1)}") - self.emit(f"{hi_half} = OpShiftLeftLogical %uint {self.cu(1)} {hi_m1}") - self.emit(f"{hi_and} = OpBitwiseAnd %uint {hi_sig} {hi_mask}") - self.emit(f"{hi_eq} = OpIEqual %bool {hi_and} {hi_half}") - self.emit(f"{lo_z} = OpIEqual %bool {plo} {self.cu(0)}") - self.emit(f"{tie_hi} = OpLogicalAnd %bool {lo_z} {hi_eq}") - self.emit(f"{is_tie} = OpSelect %bool {sh_is_hi} {tie_hi} {tie_lo}") - # Exact residual rem = (x*y + z) - f_plain via product error + TwoSum. - d0 = self.dconst(0.0) - pmul, np, pe_raw, p_z, x_nz, y_nz, xy_nz, p_uf = (self.tmp() for _ in range(8)) - self.emit(f"{pmul} = OpFMul %double {x} {y}") - self.emit(f"{np} = OpFNegate %double {pmul}") - self.emit_fma64(pe_raw, x, y, np) - self.emit(f"{p_z} = OpFOrdEqual %bool {pmul} {d0}") - self.emit(f"{x_nz} = OpFOrdNotEqual %bool {x} {d0}") - self.emit(f"{y_nz} = OpFOrdNotEqual %bool {y} {d0}") - self.emit(f"{xy_nz} = OpLogicalAnd %bool {x_nz} {y_nz}") - self.emit(f"{p_uf} = OpLogicalAnd %bool {p_z} {xy_nz}") - xv2, xhi, yv2, yhi, xysgn, psgn, pe_uf_v2, pe_uf, pe = (self.tmp() for _ in range(9)) - self.emit(f"{xv2} = OpBitcast %v2uint_d {x}") - self.emit(f"{xhi} = OpCompositeExtract %uint {xv2} 1") - self.emit(f"{yv2} = OpBitcast %v2uint_d {y}") - self.emit(f"{yhi} = OpCompositeExtract %uint {yv2} 1") - self.emit(f"{xysgn} = OpBitwiseXor %uint {xhi} {yhi}") - self.emit(f"{psgn} = OpBitwiseAnd %uint {xysgn} {self.cu(0x80000000)}") - self.emit(f"{pe_uf_v2} = OpCompositeConstruct %v2uint_d {self.cu(1)} {psgn}") - self.emit(f"{pe_uf} = OpBitcast %double {pe_uf_v2}") - self.emit(f"{pe} = OpSelect %double {p_uf} {pe_uf} {pe_raw}") - ssum, sv, s_sv, p_err, z_err, se, s_df, s_df_se, rem = (self.tmp() for _ in range(9)) - self.emit(f"{ssum} = OpFAdd %double {pmul} {z}") - self.emit(f"{sv} = OpFSub %double {ssum} {pmul}") - self.emit(f"{s_sv} = OpFSub %double {ssum} {sv}") - self.emit(f"{p_err} = OpFSub %double {pmul} {s_sv}") - self.emit(f"{z_err} = OpFSub %double {z} {sv}") - self.emit(f"{se} = OpFAdd %double {p_err} {z_err}") - self.emit(f"{s_df} = OpFSub %double {ssum} {f_plain}") - self.emit(f"{s_df_se} = OpFAdd %double {s_df} {se}") - self.emit(f"{rem} = OpFAdd %double {s_df_se} {pe}") - rem_nz, rem_pos, phi_pos, same_sgn, adj1, do_adj = (self.tmp() for _ in range(6)) - self.emit(f"{rem_nz} = OpFOrdNotEqual %bool {rem} {d0}") - self.emit(f"{rem_pos} = OpFOrdGreaterThan %bool {rem} {d0}") - self.emit(f"{phi_pos} = OpFOrdGreaterThan %bool {f_plain} {d0}") - self.emit(f"{same_sgn} = OpLogicalEqual %bool {rem_pos} {phi_pos}") - self.emit(f"{adj1} = OpLogicalAnd %bool {in_rng} {is_tie}") - self.emit(f"{do_adj} = OpLogicalAnd %bool {adj1} {rem_nz}") - lo_inc, lo_max, c_inc, hi_inc, lo_dec, c_dec, hi_dec = (self.tmp() for _ in range(7)) - self.emit(f"{lo_inc} = OpIAdd %uint {plo} {self.cu(1)}") - self.emit(f"{lo_max} = OpIEqual %bool {plo} {self.cu(0xFFFFFFFF)}") - self.emit(f"{c_inc} = OpSelect %uint {lo_max} {self.cu(1)} {self.cu(0)}") - self.emit(f"{hi_inc} = OpIAdd %uint {phi} {c_inc}") - self.emit(f"{lo_dec} = OpISub %uint {plo} {self.cu(1)}") - self.emit(f"{c_dec} = OpSelect %uint {lo_z} {self.cu(1)} {self.cu(0)}") - self.emit(f"{hi_dec} = OpISub %uint {phi} {c_dec}") - n_lo, n_hi, adj_lo, adj_hi, adj_v2, p_adj = (self.tmp() for _ in range(6)) - self.emit(f"{n_lo} = OpSelect %uint {same_sgn} {lo_inc} {lo_dec}") - self.emit(f"{n_hi} = OpSelect %uint {same_sgn} {hi_inc} {hi_dec}") - self.emit(f"{adj_lo} = OpSelect %uint {do_adj} {n_lo} {plo}") - self.emit(f"{adj_hi} = OpSelect %uint {do_adj} {n_hi} {phi}") - self.emit(f"{adj_v2} = OpCompositeConstruct %v2uint_d {adj_lo} {adj_hi}") - self.emit(f"{p_adj} = OpBitcast %double {adj_v2}") - f_post, f_dn, sc, r, v2, lo, hi = (self.tmp() for _ in range(7)) - self.emit(f"{f_post} = OpFMul %double {p_adj} {self.dconst(2.0 ** -128)}") - self.emit(f"{f_dn} = OpSelect %double {big} {f_pre} {f_post}") - self.emit(f"{sc} = OpSelect %double {scale_up} {f_up} {f_dn}") - self.emit(f"{r} = OpSelect %double {vcc_b} {sc} {f_plain}") - r = self.clamp_mods_f64(r, mods) - self.emit(f"{v2} = OpBitcast %v2uint_d {r}") - self.emit(f"{lo} = OpCompositeExtract %uint {v2} 0") - self.emit(f"{hi} = OpCompositeExtract %uint {v2} 1") - self.dst({"k": "vgpr", "r": d["r"], "n": 1}, lo) - self.dst({"k": "vgpr", "r": d["r"] + 1, "n": 1}, hi) - elif op in ("v_mad_f32", "v_mac_f32"): - # Unfused: the product is rounded before the add. v_mac_f32 is the VOP2 form with D as the addend - # (LLVM SIInstrInfo.cpp getNewFMAInst: V_MAC_F32 -> V_MAD_F32_e64, V_FMAC_F32 -> V_FMA_F32_e64). - # Neither supports f32 denormals (flush_f32): operands, the rounded product and the sum flush. - if op == "v_mac_f32": - x, y, z = self.src_f(a[1]), self.src_f(a[2]), self.src_f(a[0]) - else: - x, y, z = (self.src_f(t) for t in a[1:4]) - x, y, z = self.flush_f32(x), self.flush_f32(y), self.flush_f32(z) - m, r = self.tmp(), self.tmp() - self.emit(f"{m} = OpFMul %float {x} {y}") - self.emit(f"{r} = OpFAdd %float {self.flush_f32(m)} {z}") - self.dst(a[0], self.tou(self.flush_f32_mods(r, mods))) - elif op in ("v_mul_lo_u32", "v_min_u32", "v_max_u32", "v_min_i32", "v_max_i32"): - self._check_int32_valu(op, ins["op"], a, mods, allow_sdwa_dpp=(op != "v_mul_lo_u32")) - x, y = self.src_u(a[1]), self.src_u(a[2]) - r = self.tmp() - if op == "v_mul_lo_u32": - self.emit(f"{r} = OpIMul %uint {x} {y}") - else: - f = {"v_min_u32": "UMin", "v_max_u32": "UMax", "v_min_i32": "SMin", "v_max_i32": "SMax"}[op] - self.emit(f"{r} = OpExtInst %uint %glsl {f} {x} {y}") - self.dst(a[0], r) - elif op in ("v_cvt_f16_u16", "v_cvt_f16_i16", "v_cvt_u16_f16", "v_cvt_i16_f16"): - # 16-bit <-> f16 conversions of the low half (op_sel:[src,dst] picks the high half of the source / of the - # destination); the other half of the destination is kept, as for the other 16-bit-result ops. f16 -> int - # truncates toward zero, saturates to the 16-bit range (an f16 infinity too) and gives 0 for NaN, as the - # 32-bit conversions do (docs/design.md, "Float-to-int saturation"); output modifiers stay rejected on it. - # int -> f16 applies clamp_mods (mul:/div: then [0, 1] clamp) and rounds like every f16 result (f16_out). - sel, dhi = self.opsel_bits(mods, 1) - if op in ("v_cvt_f16_u16", "v_cvt_f16_i16"): - u = self.src_u({**a[1], "neg": False, "abs": False}) - f = self.tmp() - if op == "v_cvt_f16_u16": - m = self.u16_half(u, sel[0]) - self.emit(f"{f} = OpConvertUToF %float {m}") - else: - m = self.i16_half(u, sel[0]) - self.emit(f"{f} = OpConvertSToF %float {m}") - f = self.clamp_f16(f, mods) - self.f16_out(a[0], f, dhi) - else: - if any(m == "clamp" or m.startswith(("mul:", "div:")) for m in mods): - raise Unsupported(op + " output modifier") - x = self.f16_in(a[1], sel[0]) - nan, xs, tr, cl, conv, lo = (self.tmp() for _ in range(6)) - self.emit(f"{nan} = OpIsNan %bool {x}") - self.emit(f"{xs} = OpSelect %float {nan} %f0 {x}") # keep the conversion operand representable - self.emit(f"{tr} = OpExtInst %float %glsl Trunc {xs}") - lo_b, hi_b = (-32768.0, 32767.0) if op == "v_cvt_i16_f16" else (0.0, 65535.0) - self.emit(f"{cl} = OpExtInst %float %glsl FClamp {tr} {self.fconst(lo_b)} {self.fconst(hi_b)}") - if op == "v_cvt_i16_f16": - ci = self.tmp() - self.emit(f"{ci} = OpConvertFToS %int {cl}") - self.emit(f"{conv} = OpBitcast %uint {ci}") - else: - self.emit(f"{conv} = OpConvertFToU %uint {cl}") - self.emit(f"{lo} = OpBitwiseAnd %uint {conv} {self.cu(0xFFFF)}") - if not dhi: - self.write_lo16(a[0], lo) - else: - if a[0]["k"] != "vgpr": - raise Unsupported("op_sel destination") - old, keep, sh16, v = (self.tmp() for _ in range(4)) - self.emit(f"{old} = OpCopyObject %uint {self.load_reg('vgpr', a[0]['r'])}") - self.emit(f"{keep} = OpBitwiseAnd %uint {old} {self.cu(0xFFFF)}") - self.emit(f"{sh16} = OpShiftLeftLogical %uint {lo} {self.cu(16)}") - self.emit(f"{v} = OpBitwiseOr %uint {keep} {sh16}") - self.dst(a[0], v) - elif op in ("v_cvt_norm_i16_f16", "v_cvt_norm_u16_f16"): - # Normalized f16 -> snorm16/unorm16 (RDNA2 ISA VOP1/VOP3): round_even(clamp(S0, lo, 1.0) * scale), - # NaN -> 0, preserving the unwritten 16-bit half of the destination (op_sel:[src,dst] supported). - # For |cl| >= 0.25, cl * (scale + 1) is an exact even integer in f32 so round_even(cl * scale) == - # cl * (scale + 1) - RoundEven(cl), avoiding the f32 double-rounding ties near +-0.5. - # Measured natively on RDNA2 (gfx1036, wave32 & wave64, exhaustive 65,536 f16 sweep): VOP3 - # clamp and mul:2/mul:4/div:2 (and SDWA clamp) are hardware no-ops on these integer-destination - # normalized conversions. Keep rejecting unknown modifiers and invalid form/modifier combinations. - raw_op = ins["op"] - if raw_op.endswith("_sdwa"): - bad_mod = any( - m != "clamp" and m.split(":", 1)[0] not in ("src0_sel", "dst_sel", "dst_unused") - for m in mods - ) - elif raw_op.endswith("_dpp"): - bad_mod = bool(self.non_dpp_mods(raw_op, mods)) - elif raw_op.endswith("_e32"): - bad_mod = bool(mods) - else: - bad_mod = any( - m not in ("clamp", "mul:2", "mul:4", "div:2") and not m.startswith("op_sel:") - for m in mods - ) - if bad_mod: - raise Unsupported(op + " output modifier") - sel, dhi = self.opsel_bits(mods, 1) - snorm = op == "v_cvt_norm_i16_f16" - x = self.f16_in(a[1], sel[0]) - nan, xs, cl, ax, big, hp, rc, rbig, ps, rsm, rn, conv, lo = (self.tmp() for _ in range(13)) - self.emit(f"{nan} = OpIsNan %bool {x}") - self.emit(f"{xs} = OpSelect %float {nan} %f0 {x}") - lo_b = -1.0 if snorm else 0.0 - sc, sc1 = (32767.0, 32768.0) if snorm else (65535.0, 65536.0) - self.emit(f"{cl} = OpExtInst %float %glsl FClamp {xs} {self.fconst(lo_b)} {self.fconst(1.0)}") - self.emit(f"{ax} = OpExtInst %float %glsl FAbs {cl}") - self.emit(f"{big} = OpFOrdGreaterThanEqual %bool {ax} {self.fconst(0.25)}") - self.emit(f"{hp} = OpFMul %float {cl} {self.fconst(sc1)}") - self.emit(f"{rc} = OpExtInst %float %glsl RoundEven {cl}") - self.emit(f"{rbig} = OpFSub %float {hp} {rc}") - self.emit(f"{ps} = OpFMul %float {cl} {self.fconst(sc)}") - self.emit(f"{rsm} = OpExtInst %float %glsl RoundEven {ps}") - self.emit(f"{rn} = OpSelect %float {big} {rbig} {rsm}") - if snorm: - ci = self.tmp() - self.emit(f"{ci} = OpConvertFToS %int {rn}") - self.emit(f"{conv} = OpBitcast %uint {ci}") - else: - self.emit(f"{conv} = OpConvertFToU %uint {rn}") - self.emit(f"{lo} = OpBitwiseAnd %uint {conv} {self.cu(0xFFFF)}") - if not dhi: - self.write_lo16(a[0], lo) - else: - if a[0]["k"] != "vgpr": - raise Unsupported("op_sel destination") - old, keep, sh16, v = (self.tmp() for _ in range(4)) - self.emit(f"{old} = OpCopyObject %uint {self.load_reg('vgpr', a[0]['r'])}") - self.emit(f"{keep} = OpBitwiseAnd %uint {old} {self.cu(0xFFFF)}") - self.emit(f"{sh16} = OpShiftLeftLogical %uint {lo} {self.cu(16)}") - self.emit(f"{v} = OpBitwiseOr %uint {keep} {sh16}") - self.dst(a[0], v) - elif op in ("v_frexp_mant_f16", "v_frexp_exp_i16_f16", "v_ldexp_f16"): - # The binary16 version of v_frexp_mant_f32 / v_frexp_exp_i32_f32 / v_ldexp_f32, bit-exact on the f16 word - # of the low half (op_sel picks the high half of a source; the last bit sends the result to the high half; - # the other half of the destination is kept). A normal f16 has a biased exponent of 1..30 (bias 15); zero - # gives a signed zero (exponent 0) and exponent 31 (infinity, NaN) passes through. f16 denormals are kept, - # as in the MODE inferred for the game (denorm_mode_16_64 = 3): a denormal operand is normalized, and - # v_ldexp_f16 rounds a result below the normal range to nearest even. Measured natively on gfx1036 over - # every f16 input (docs/design.md). Under console MODE (0x1c0: IEEE=0, DX10_CLAMP=1, denorm16_64=3), - # VOP3 mul:2/mul:4/div:2 are hardware no-ops on v_frexp_mant_f16 and v_ldexp_f16 while clamp clamps to - # [0.0, 1.0] alone and combined with mul:*/div:*; on v_frexp_exp_i16_f16 (integer result), clamp and - # mul:2/mul:4/div:2 are all hardware no-ops across every MODE (0x1c0, 0x100, 0x3c0). - if op == "v_ldexp_f16": - self._validate_f16_valu(ins, op, 2, allow_e32=True, allow_e64=True, int_srcs=(1,)) - else: - bad = [m for m in mods if m not in ("clamp", "mul:2", "mul:4", "div:2") and not m.startswith("op_sel:")] - if bad: - raise Unsupported(op + " output modifier") - nsrc = 2 if op == "v_ldexp_f16" else 1 - sel, dhi = self.opsel_bits(mods, nsrc) - u = self.src_h(a[1]) - x = self.u16_half(u, sel[0]) - if a[1].get("abs"): - t = self.tmp() - self.emit(f"{t} = OpBitwiseAnd %uint {x} {self.cu(0x7FFF)}") - x = t - if a[1].get("neg"): - t = self.tmp() - self.emit(f"{t} = OpBitwiseXor %uint {x} {self.cu(0x8000)}") - x = t - e, em1, isnorm, isden, sgn, other = (self.tmp() for _ in range(6)) - self.emit(f"{e} = OpBitFieldUExtract %uint {x} {self.cu(10)} {self.cu(5)}") - self.emit(f"{em1} = OpISub %uint {e} {self.cu(1)}") - self.emit(f"{isnorm} = OpULessThan %bool {em1} {self.cu(30)}") # exponent field 1..30 - self.emit(f"{isden} = OpIEqual %bool {e} {self.cu(0)}") - self.emit(f"{sgn} = OpBitwiseAnd %uint {x} {self.cu(0x8000)}") - self.emit(f"{other} = OpSelect %uint {isden} {sgn} {x}") # zero -> +-0, inf/NaN -> S0 - # The significand with its leading one at bit 10 (sig11), and the exponent field ef that goes with it: e for - # a normal operand, 1 - (10 - msb) for a denormal one (2^-24 * frac), which can wrap below 0. - frac, nz, sub, fin, wide, sig, msb, msbu, lsh, lshc, sig11, ef0, ef = (self.tmp() for _ in range(13)) - self.emit(f"{frac} = OpBitwiseAnd %uint {x} {self.cu(0x3FF)}") - self.emit(f"{nz} = OpINotEqual %bool {frac} {self.cu(0)}") - self.emit(f"{sub} = OpLogicalAnd %bool {isden} {nz}") # a denormal operand - self.emit(f"{fin} = OpLogicalOr %bool {isnorm} {sub}") # finite and not zero - self.emit(f"{wide} = OpBitwiseOr %uint {frac} {self.cu(0x400)}") - self.emit(f"{sig} = OpSelect %uint {isnorm} {wide} {frac}") - self.emit(f"{msb} = OpExtInst %int %glsl FindUMsb {sig}") - self.emit(f"{msbu} = OpBitcast %uint {msb}") - self.emit(f"{lsh} = OpISub %uint {self.cu(10)} {msbu}") # 0 for a normal operand - self.emit(f"{lshc} = OpExtInst %uint %glsl UMin {lsh} {self.cu(10)}") # zero (msb -1) stays in range - self.emit(f"{sig11} = OpShiftLeftLogical %uint {sig} {lshc}") - self.emit(f"{ef0} = OpSelect %uint {isnorm} {e} {self.cu(1)}") - self.emit(f"{ef} = OpISub %uint {ef0} {lshc}") - r = self.tmp() - if op == "v_frexp_exp_i16_f16": - ex = self.tmp() - self.emit(f"{ex} = OpISub %uint {ef} {self.cu(14)}") # biased exponent - 15 + 1 - self.emit(f"{r} = OpSelect %uint {fin} {ex} {self.cu(0)}") - elif op == "v_frexp_mant_f16": - lo10, keep, m = self.tmp(), self.tmp(), self.tmp() - self.emit(f"{lo10} = OpBitwiseAnd %uint {sig11} {self.cu(0x3FF)}") - self.emit(f"{keep} = OpBitwiseOr %uint {sgn} {lo10}") - self.emit(f"{m} = OpBitwiseOr %uint {keep} {self.cu(0x3800)}") # biased exponent 14 - self.emit(f"{r} = OpSelect %uint {fin} {m} {other}") - else: - # D = S0 * 2^S1, S1 a signed 16-bit integer clamped to [-64, 64] and added to the exponent field; - # above 30 the result is +-inf; at 0 or below it is a denormal: the significand shifted right by - # 1 - field and rounded to nearest even (a carry into bit 10 gives the smallest normal). After a - # MODE.FP_ROUND[3:2] toward-zero write (%mode_r16 = 3) it rounds like every other VALU f16 result: - # overflow gives +-65504 and a denormal is truncated (not measured on hardware for this op). - n = self.src_u(a[2]) - n16 = self.i16_half(n, sel[1]) - nu, nb, small, neg, lim, nc = (self.tmp() for _ in range(6)) - self.emit(f"{nu} = OpBitcast %uint {n16}") - self.emit(f"{nb} = OpIAdd %uint {nu} {self.cu(64)}") - self.emit(f"{small} = OpULessThan %bool {nb} {self.cu(129)}") # -64 <= n <= 64 - self.emit(f"{neg} = OpBitFieldUExtract %uint {nu} {self.cu(31)} {self.cu(1)}") - self.emit(f"{lim} = OpSelect %uint {self.tmp_bool_nz(neg)} {self.cu(0xFFFFFFC0)} {self.cu(64)}") - self.emit(f"{nc} = OpSelect %uint {small} {nu} {lim}") - e2, e2m1, valid, pos, posb, over = (self.tmp() for _ in range(6)) - self.emit(f"{e2} = OpIAdd %uint {ef} {nc}") - self.emit(f"{e2m1} = OpISub %uint {e2} {self.cu(1)}") - self.emit(f"{valid} = OpULessThan %bool {e2m1} {self.cu(30)}") # new exponent field 1..30 - self.emit(f"{pos} = OpBitFieldUExtract %uint {e2} {self.cu(31)} {self.cu(1)}") - self.emit(f"{posb} = OpIEqual %bool {pos} {self.cu(0)}") - self.emit(f"{over} = OpLogicalAnd %bool {posb} {self.tmp_bool_nz(e2)}") # field 31 and above - sh, lo10, keep, norm, inf = (self.tmp() for _ in range(5)) - self.emit(f"{sh} = OpShiftLeftLogical %uint {e2} {self.cu(10)}") - self.emit(f"{lo10} = OpBitwiseAnd %uint {sig11} {self.cu(0x3FF)}") - self.emit(f"{keep} = OpBitwiseOr %uint {sgn} {lo10}") - self.emit(f"{norm} = OpBitwiseOr %uint {keep} {sh}") - is_z = None - if self.round_mode: - m, is_z, big = self.tmp(), self.tmp(), self.tmp() - self.emit(f"{m} = OpLoad %uint %mode_r16") - self.emit(f"{is_z} = OpIEqual %bool {m} {self.cu(3)}") - self.emit(f"{big} = OpSelect %uint {is_z} {self.cu(0x7BFF)} {self.cu(0x7C00)}") - self.emit(f"{inf} = OpBitwiseOr %uint {sgn} {big}") - else: - self.emit(f"{inf} = OpBitwiseOr %uint {sgn} {self.cu(0x7C00)}") - # Field 0 or below: shift right by 1 - field (clamped to 1..12; 12 leaves nothing) and round to even - # (toward zero: truncate). - rs, rsc, rsu, q, hm, half, mask, rem, gt, eq, odd, oddb, tie, up, inc, qd, den = \ - (self.tmp() for _ in range(17)) - self.emit(f"{rs} = OpISub %int {self.as_int(self.cu(1))} {self.as_int(e2)}") - self.emit(f"{rsc} = OpExtInst %int %glsl SClamp {rs} {self.as_int(self.cu(1))} " - f"{self.as_int(self.cu(12))}") - self.emit(f"{rsu} = OpBitcast %uint {rsc}") - self.emit(f"{q} = OpShiftRightLogical %uint {sig11} {rsu}") - self.emit(f"{hm} = OpShiftLeftLogical %uint {self.cu(1)} {rsu}") - self.emit(f"{half} = OpShiftRightLogical %uint {hm} {self.cu(1)}") - self.emit(f"{mask} = OpISub %uint {hm} {self.cu(1)}") - self.emit(f"{rem} = OpBitwiseAnd %uint {sig11} {mask}") - self.emit(f"{gt} = OpUGreaterThan %bool {rem} {half}") - self.emit(f"{eq} = OpIEqual %bool {rem} {half}") - self.emit(f"{odd} = OpBitwiseAnd %uint {q} {self.cu(1)}") - self.emit(f"{oddb} = OpINotEqual %bool {odd} {self.cu(0)}") - self.emit(f"{tie} = OpLogicalAnd %bool {eq} {oddb}") - self.emit(f"{up} = OpLogicalOr %bool {gt} {tie}") - if is_z is not None: - not_z, upn = self.tmp(), self.tmp() - self.emit(f"{not_z} = OpLogicalNot %bool {is_z}") - self.emit(f"{upn} = OpLogicalAnd %bool {up} {not_z}") - up = upn - self.emit(f"{inc} = OpSelect %uint {up} {self.cu(1)} {self.cu(0)}") - self.emit(f"{qd} = OpIAdd %uint {q} {inc}") - self.emit(f"{den} = OpBitwiseOr %uint {sgn} {qd}") - ov, scaled = self.tmp(), self.tmp() - self.emit(f"{ov} = OpSelect %uint {over} {inf} {den}") - self.emit(f"{scaled} = OpSelect %uint {valid} {norm} {ov}") - self.emit(f"{r} = OpSelect %uint {fin} {scaled} {other}") - lo = self.tmp() - self.emit(f"{lo} = OpBitwiseAnd %uint {r} {self.cu(0xFFFF)}") - if "clamp" in mods and op in ("v_frexp_mant_f16", "v_ldexp_f16"): - s15, e16, frac16, is_exp31, is_nan, is_zero_out, gt_one, c1, clamped_lo = \ - (self.tmp() for _ in range(9)) - self.emit(f"{s15} = OpBitFieldUExtract %uint {lo} {self.cu(15)} {self.cu(1)}") - is_neg = self.tmp_bool_nz(s15) - self.emit(f"{e16} = OpBitFieldUExtract %uint {lo} {self.cu(10)} {self.cu(5)}") - self.emit(f"{is_exp31} = OpIEqual %bool {e16} {self.cu(31)}") - self.emit(f"{frac16} = OpBitwiseAnd %uint {lo} {self.cu(0x3FF)}") - has_frac = self.tmp_bool_nz(frac16) - self.emit(f"{is_nan} = OpLogicalAnd %bool {is_exp31} {has_frac}") - self.emit(f"{is_zero_out} = OpLogicalOr %bool {is_neg} {is_nan}") - self.emit(f"{gt_one} = OpUGreaterThan %bool {lo} {self.cu(0x3C00)}") - self.emit(f"{c1} = OpSelect %uint {gt_one} {self.cu(0x3C00)} {lo}") - self.emit(f"{clamped_lo} = OpSelect %uint {is_zero_out} {self.cu(0)} {c1}") - lo = clamped_lo - self.write_half16(a[0], lo, dhi) - elif op == "v_cvt_f32_f16": - u = self.src_h(a[1]) - v2, f = self.tmp(), self.tmp() - self.emit(f"{v2} = OpExtInst %v2float %glsl UnpackHalf2x16 {u}") - self.emit(f"{f} = OpCompositeExtract %float {v2} 0") - self.dst(a[0], self.tou(self.clamp_mods(self.modify_f(f, a[1]), mods))) - elif op in ("v_interp_p1_f32", "v_interp_p2_f32", "v_interp_mov_f32"): - # Single-lane model: the barycentric p1/p2 pair yields the interpolated attribute, and the mov of P0 - # the provoking vertex's value. An input only ever read through the mov is declared Flat: such - # inputs carry integers (instance and material ids, buffer indices), and interpolating their bits - # as floats does not return them intact. No shader in this build reads one location both ways. - attr = next((x for x in a if x["k"] == "attr"), None) - if attr is None or self.stage != "ps": - raise Unsupported(op + " form") - vsel = "p0" - if op == "v_interp_mov_f32": - sel = a[1] if len(a) > 1 else None - vsel = sel.get("t") if sel is not None and sel.get("k") == "interp" else "operand" - if vsel not in ("p0", "p10", "p20"): - raise Unsupported(f"v_interp_mov_f32 vertex select {vsel}") - else: - self.interp_pair_src(op, a, ins) - half16 = self.pixel_interpolants is not None and (self.pixel_interpolants[1] >> attr["a"]) & 1 - if vsel != "p0": - # P10 = P1 - P0 and P20 = P2 - P0, the deltas the hardware keeps beside P0 for the p1/p2 pair - # (RDNA2 ISA, VINTRP: D = {P10, P20, P0}[S]): one f32 subtraction of the PerVertexKHR words. - if attr["a"] not in self.per_vertex: - raise Unsupported(f"v_interp_mov_f32 vertex select {vsel} without per-vertex inputs") - if half16: - raise Unsupported(f"v_interp_mov_f32 vertex select {vsel} of a 16-bit interpolant") - f = self.attribute(attr["a"], attr["c"], vertex_delta=1 if vsel == "p10" else 2) - else: - f = self.attribute(attr["a"], attr["c"], flat=op == "v_interp_mov_f32", - ij=self.interp_weights(ins)) - if half16 and vsel == "p0": - # 16-bit interpolant (FSSM table flag bit 4) read through a 32-bit op: the stored value only - # has f16 precision, so round to nearest f16 and back. Reads through the *_f16 opcodes already - # narrow to f16 and are unchanged. - f = self.f16_roundtrip(f) - if op in ("v_interp_p2_f32", "v_interp_mov_f32"): - # VOP3 output modifiers (mul:2 / mul:4 / div:2, clamp) apply to the interpolated result - # (LLVM gfx10_asm_vop3.s). No-op when mods has none. - f = self.clamp_mods(f, mods) - self.dst(a[0], self.tou(f)) - elif op == "s_movk_i32": - v = a[1]["v"] & 0xFFFF - val = (v - 0x10000 if v & 0x8000 else v) & 0xFFFFFFFF - self.dst(a[0], self.cu(val)) - if a[0]["k"] == "sgpr" and self.desc_cache_ok(): - self.sgpr_imm[a[0]["r"]] = val - elif op in ("s_cmov_b32", "s_cmovk_i32"): - # D = SCC ? S0 : D (s_cmovk_i32: S0 is the 16-bit immediate, sign-extended). SCC is read, not written. - if a[0]["k"] != "sgpr": - raise Unsupported(op + " destination") - if op == "s_cmovk_i32": - v = a[1]["v"] & 0xFFFF - x = self.cu((v - 0x10000 if v & 0x8000 else v) & 0xFFFFFFFF) - else: - x = self.src_u(a[1]) - old, c, r = self.tmp(), self.tmp(), self.tmp() - self.emit(f"{old} = OpCopyObject %uint {self.load_reg('sgpr', a[0]['r'])}") - self.emit(f"{c} = OpLoad %uint %scc") - self.emit(f"{r} = OpSelect %uint {self.tmp_bool_nz(c)} {x} {old}") - self.dst(a[0], r) - elif op == "s_cmov_b64": - # RDNA2 ISA SOP1: D = SCC ? S0 : D, SCC read and not written (LLVM AMDGPU SOPInstructions.td: - # S_CMOV_B64 : SOP1_64 under Uses = [SCC]). Plain 64-bit data only: a lane-mask pair holds one - # lane's bit here, so selecting it as data would silently read a bool instead of the wave's mask - # (issue #210). Those operands keep failing loudly. - if self.is_mask_op(a[1]) or self.any_mask_word(a[1]) or self.any_ever_mask_word(a[1]): - raise Unsupported("s_cmov_b64 lane-mask source") - if a[0]["k"] != "sgpr" or a[0].get("n") != 2: - raise Unsupported("s_cmov_b64 destination") - if self.holds_lane_mask(a[0]) or self.any_mask_word(a[0]) or self.any_ever_mask_word(a[0]): - raise Unsupported("s_cmov_b64 lane-mask destination") - (xlo, xhi) = self.src64_data(a[1], op) - # Read both old dwords before any store, so D overlapping S0 stays exact. - oldlo, oldhi = self.load_reg("sgpr", a[0]["r"]), self.load_reg("sgpr", a[0]["r"] + 1) - c, rlo, rhi = self.tmp(), self.tmp(), self.tmp() - self.emit(f"{c} = OpLoad %uint %scc") - b = self.tmp_bool_nz(c) - self.emit(f"{rlo} = OpSelect %uint {b} {xlo} {oldlo}") - self.emit(f"{rhi} = OpSelect %uint {b} {xhi} {oldhi}") - self.dst64_data(a[0], rlo, rhi, op) - elif op.startswith("v_cmp_") and not op.startswith("v_cmp_class"): - self.compare(op, a, scalar=False, mods=mods) - elif op.startswith("v_cmpx_") and not op.startswith("v_cmpx_class"): - self.compare_x(op, a, mods=mods) - elif op.endswith(("_saveexec_b64", "_saveexec_b32")) and op[2:].split("_saveexec")[0] in self.EXEC_LOGIC: - # RDNA2 ISA SOP1: D = EXEC; EXEC = f(S0, EXEC); SCC = (EXEC != 0). One invocation holds its own lane's bit - # (0 or ~0), so f is the bitwise op on that bit, NOT included: a lane EXEC had off becomes active when f - # gives 1 for it (nand, nor, orn2, xnor ...), as on hardware. Definitions as tools/cf_ref.py _SAVEEXEC. - # In wave64, the _b32 form operates strictly on EXEC_LO (lanes 0..31): EXEC_HI (lanes 32..63) is unchanged - # and SCC reflects EXEC_LO != 0 only. - kind = op[2:].split("_saveexec")[0] - saved = self.exec_value() - half32 = self.wave64 and op.endswith("_b32") - if half32 and self.holds_lane_mask(a[1]) and self.mask_half(a[1]) == "hi": - _, hi_w = self.wave_mask(a[1]) - sh, shr, bit, src = (self.tmp() for _ in range(4)) - self.emit(f"{sh} = OpBitwiseAnd %uint {self.wave_lane()} {self.cu(31)}") - self.emit(f"{shr} = OpShiftRightLogical %uint {hi_w} {sh}") - self.emit(f"{bit} = OpBitwiseAnd %uint {shr} {self.cu(1)}") - self.emit(f"{src} = OpSelect %uint {self.tmp_bool_nz(bit)} {self.cu(0xFFFFFFFF)} {self.cu(0)}") - else: - src = self.mask_src(a[1], wide=op.endswith("b64")) - r = self.exec_logic(kind, src, saved) - if half32: - if a[0]["k"] == "special" and a[0].get("t") in ("exec_hi", "vcc_hi"): - lo_w, _ = self.wave_mask({"k": "special", "t": "exec"}) - sh, shr, bit, mapped = (self.tmp() for _ in range(4)) - self.emit(f"{sh} = OpBitwiseAnd %uint {self.wave_lane()} {self.cu(31)}") - self.emit(f"{shr} = OpShiftRightLogical %uint {lo_w} {sh}") - self.emit(f"{bit} = OpBitwiseAnd %uint {shr} {self.cu(1)}") - self.emit(f"{mapped} = OpSelect %uint {self.tmp_bool_nz(bit)} {self.cu(0xFFFFFFFF)} {self.cu(0)}") - self.put_mask(a[0], mapped, "hi") - else: - self.put_mask(a[0], saved, "lo") - self.exec_half_write(0, r) - self.scc_any_half(r, "lo") - else: - self.mask_dst(a[0], saved) - self.set_exec(r) - self.scc_from_mask(r) - elif op in ("s_andn2_wrexec_b64", "s_andn2_wrexec_b32", "s_andn1_wrexec_b64", "s_andn1_wrexec_b32"): - # RDNA ISA: andn2: EXEC = S0 & ~EXEC; andn1: EXEC = ~S0 & EXEC; then D = EXEC; SCC = (EXEC != 0). - # In wave64, the _b32 form operates strictly on EXEC_LO (lanes 0..31). - kind = op[2:].split("_wrexec")[0] - half32 = self.wave64 and op.endswith("_b32") - if half32 and self.holds_lane_mask(a[1]) and self.mask_half(a[1]) == "hi": - _, hi_w = self.wave_mask(a[1]) - sh, shr, bit, x = (self.tmp() for _ in range(4)) - self.emit(f"{sh} = OpBitwiseAnd %uint {self.wave_lane()} {self.cu(31)}") - self.emit(f"{shr} = OpShiftRightLogical %uint {hi_w} {sh}") - self.emit(f"{bit} = OpBitwiseAnd %uint {shr} {self.cu(1)}") - self.emit(f"{x} = OpSelect %uint {self.tmp_bool_nz(bit)} {self.cu(0xFFFFFFFF)} {self.cu(0)}") - else: - x = self.mask_src(a[1], wide=op.endswith("b64")) - y = self.exec_value() - r = self.exec_logic(kind, x, y) - if half32: - self.exec_half_write(0, r) - if a[0]["k"] == "special" and a[0].get("t") in ("exec_hi", "vcc_hi"): - lo_w, _ = self.wave_mask({"k": "special", "t": "exec"}) - sh, shr, bit, mapped = (self.tmp() for _ in range(4)) - self.emit(f"{sh} = OpBitwiseAnd %uint {self.wave_lane()} {self.cu(31)}") - self.emit(f"{shr} = OpShiftRightLogical %uint {lo_w} {sh}") - self.emit(f"{bit} = OpBitwiseAnd %uint {shr} {self.cu(1)}") - self.emit(f"{mapped} = OpSelect %uint {self.tmp_bool_nz(bit)} {self.cu(0xFFFFFFFF)} {self.cu(0)}") - self.put_mask(a[0], mapped, "hi") - else: - self.put_mask(a[0], r, "lo") - self.scc_any_half(r, "lo") - else: - self.set_exec(r) - self.mask_dst(a[0], r) - self.scc_from_mask(r) - elif op in ("s_bfe_u64", "s_bfe_i64"): - # 64-bit bitfield extract: offset = S1[5:0], width = S1[22:16] (0-127). A width of 0 gives 0; a field - # running past bit 63 stops there (LLVM constantFoldBFE: Src0 >> Offset, arithmetic for i64), so the - # width is cut to 64 - offset. SCC = (D != 0). The pair is 64-bit data (as for s_lshl_b64); a lane-mask - # source stays Unsupported (#210). - d, x = a[0], a[1] - if d["k"] != "sgpr" or d.get("n") != 2 or self.holds_lane_mask(x): - raise Unsupported(op + " operands") - if x["k"] == "sgpr" and x.get("n") == 2: - lo, hi = self.load_reg("sgpr", x["r"]), self.load_reg("sgpr", x["r"] + 1) - elif x["k"] == "imm": - v = x["v"] & 0xFFFFFFFFFFFFFFFF - lo, hi = self.cu(v & 0xFFFFFFFF), self.cu(v >> 32) - else: - raise Unsupported(op + " source") - ctl = self.src_u(a[2]) - off, wid, room, fits, w, l64, h64, t, v64 = (self.tmp() for _ in range(9)) - self.emit(f"{off} = OpBitwiseAnd %uint {ctl} {self.cu(63)}") - self.emit(f"{wid} = OpBitFieldUExtract %uint {ctl} {self.cu(16)} {self.cu(7)}") - self.emit(f"{room} = OpISub %uint {self.cu(64)} {off}") - self.emit(f"{fits} = OpULessThan %bool {wid} {room}") - self.emit(f"{w} = OpSelect %uint {fits} {wid} {room}") # 0..64, and off + w <= 64 - self.emit(f"{l64} = OpUConvert %ulong {lo}") - self.emit(f"{h64} = OpUConvert %ulong {hi}") - self.emit(f"{t} = OpShiftLeftLogical %ulong {h64} %c64_32") - self.emit(f"{v64} = OpBitwiseOr %ulong {t} {l64}") - # Shift the field to the top, then back down: both amounts stay in 0..63 whenever w >= 1; w = 0 is - # handled by the final select, so its (clamped) shifts never decide the result. - wz = self.tmp() - self.emit(f"{wz} = OpIEqual %bool {w} {self.cu(0)}") - w1, up, down, up64, down64, sh, field = (self.tmp() for _ in range(7)) - self.emit(f"{w1} = OpSelect %uint {wz} {self.cu(1)} {w}") - ow = self.tmp() - self.emit(f"{ow} = OpIAdd %uint {off} {w1}") - self.emit(f"{up} = OpISub %uint {self.cu(64)} {ow}") - self.emit(f"{down} = OpISub %uint {self.cu(64)} {w1}") - self.emit(f"{up64} = OpUConvert %ulong {up}") - self.emit(f"{down64} = OpUConvert %ulong {down}") - self.emit(f"{sh} = OpShiftLeftLogical %ulong {v64} {up64}") - if op == "s_bfe_u64": - self.emit(f"{field} = OpShiftRightLogical %ulong {sh} {down64}") - else: - si_, ri = self.tmp(), self.tmp() - self.emit(f"{si_} = OpBitcast %long {sh}") - self.emit(f"{ri} = OpShiftRightArithmetic %long {si_} {down64}") - self.emit(f"{field} = OpBitcast %ulong {ri}") - flo, fh, fhi, rlo, rhi = (self.tmp() for _ in range(5)) - self.emit(f"{flo} = OpUConvert %uint {field}") - self.emit(f"{fh} = OpShiftRightLogical %ulong {field} %c64_32") - self.emit(f"{fhi} = OpUConvert %uint {fh}") - self.emit(f"{rlo} = OpSelect %uint {wz} {self.cu(0)} {flo}") - self.emit(f"{rhi} = OpSelect %uint {wz} {self.cu(0)} {fhi}") - self.store_reg("sgpr", d["r"], rlo) - self.store_reg("sgpr", d["r"] + 1, rhi) - orr = self.tmp() - self.emit(f"{orr} = OpBitwiseOr %uint {rlo} {rhi}") - self.scc_nonzero(orr) - self.uses_psb = True # Int64 capability and %ulong / %long come with the PSB declarations - elif op in ("s_bfe_u32", "s_bfe_i32"): - # src1 packs offset in bits [4:0] and width in bits [22:16]. - ctl_val = self.imm_val(a[2]) - if ctl_val is not None: - off_c = ctl_val & 31 - wid_raw = (ctl_val >> 16) & 0x7F - wid_c = min(wid_raw, 32 - off_c) - x_val = self.imm_val(a[1]) - if x_val is not None: - if wid_c == 0: - val = 0 - elif op == "s_bfe_u32": - val = (x_val >> off_c) & ((1 << wid_c) - 1) - else: - raw = (x_val >> off_c) & ((1 << wid_c) - 1) - sign_bit = 1 << (wid_c - 1) - val = ((raw ^ sign_bit) - sign_bit) & 0xFFFFFFFF - r = self.cu(val) - self.dst(a[0], r) - if a[0]["k"] == "sgpr" and a[0].get("n", 1) == 1: - self.sgpr_imm[a[0]["r"]] = val - self.emit(f"OpStore %scc {self.cu(1 if val != 0 else 0)}") - return - off = self.cu(off_c) - wid = self.cu(wid_c) - x = self.src_u(a[1]) - r = self.tmp() - if op == "s_bfe_u32": - self.emit(f"{r} = OpBitFieldUExtract %uint {x} {off} {wid}") - else: - xi, ri = self.as_int(x), self.tmp() - self.emit(f"{ri} = OpBitFieldSExtract %int {xi} {off} {wid}") - self.emit(f"{r} = OpBitcast %uint {ri}") - self.dst(a[0], r) - z = self.tmp() - self.emit(f"{z} = OpSelect %uint {self.tmp_bool_nz(r)} {self.cu(1)} {self.cu(0)}") - self.emit(f"OpStore %scc {z}") - return - x, ctl = self.src_u(a[1]), self.src_u(a[2]) - off, wid, r = self.tmp(), self.tmp(), self.tmp() - self.emit(f"{off} = OpBitwiseAnd %uint {ctl} {self.cu(31)}") - self.emit(f"{wid} = OpBitFieldUExtract %uint {ctl} {self.cu(16)} {self.cu(7)}") - wid = self.bfe_width(off, wid) - if op == "s_bfe_u32": - self.emit(f"{r} = OpBitFieldUExtract %uint {x} {off} {wid}") - else: - xi, ri = self.as_int(x), self.tmp() - self.emit(f"{ri} = OpBitFieldSExtract %int {xi} {off} {wid}") - self.emit(f"{r} = OpBitcast %uint {ri}") - self.dst(a[0], r) - z = self.tmp() - self.emit(f"{z} = OpSelect %uint {self.tmp_bool_nz(r)} {self.cu(1)} {self.cu(0)}") - self.emit(f"OpStore %scc {z}") - elif op == "v_perm_b32": - # Byte permute: result byte i = selector byte i picks from the 8 bytes {src0, src1} (src1 is low). - # Selector values 0-7 pick a byte; 8-11 repeat the sign bit of a 16-bit half (bit 15, 31, 47 or 63 of - # {src0, src1}, RDNA2 ISA reference, V_PERM_B32); 12 -> 0x00, >=13 -> 0xFF. - # Both candidate shifts are (k & 3) * 8, so every shift stays below 32 (SPIR-V leaves larger ones - # undefined, even on the side of the OpSelect that is discarded). - s0, s1 = self.src_u(a[1]), self.src_u(a[2]) - selector = self.imm_val(a[3]) - if selector is not None: - self.dst(a[0], self.permute_known_selector(s0, s1, selector)) - return - sel = self.src_u(a[3]) - out = self.cu(0) - for i in range(4): - sb, lo_pick, hi_pick, k, b, k3, sh, chosen, inrange, val, shifted, acc = \ - (self.tmp() for _ in range(12)) - self.emit(f"{sb} = OpBitFieldUExtract %uint {sel} {self.cu(8 * i)} {self.cu(8)}") - self.emit(f"{k} = OpBitwiseAnd %uint {sb} {self.cu(7)}") - self.emit(f"{b} = OpULessThan %bool {k} {self.cu(4)}") - self.emit(f"{k3} = OpBitwiseAnd %uint {k} {self.cu(3)}") - self.emit(f"{sh} = OpIMul %uint {k3} {self.cu(8)}") - self.emit(f"{lo_pick} = OpShiftRightLogical %uint {s1} {sh}") - self.emit(f"{hi_pick} = OpShiftRightLogical %uint {s0} {sh}") - self.emit(f"{chosen} = OpSelect %uint {b} {lo_pick} {hi_pick}") - self.emit(f"{inrange} = OpULessThan %bool {sb} {self.cu(8)}") - # 8-11: k3 = sb & 3 picks the half; its sign bit is bit 15 or 31 of src1 (k3 0, 1) or src0 (2, 3). - k2, in_s1, sgn_src, sgn_sh, sgn_bit, sgn, sb_hi, is_sgn, const, ff, big = (self.tmp() for _ in range(11)) - self.emit(f"{k2} = OpBitwiseAnd %uint {k3} {self.cu(2)}") - self.emit(f"{in_s1} = OpIEqual %bool {k2} {self.cu(0)}") - self.emit(f"{sgn_src} = OpSelect %uint {in_s1} {s1} {s0}") - self.emit(f"{sgn_sh} = OpBitFieldInsert %uint {self.cu(15)} {k3} {self.cu(4)} {self.cu(1)}") - self.emit(f"{sgn_bit} = OpBitFieldUExtract %uint {sgn_src} {sgn_sh} {self.cu(1)}") - self.emit(f"{sgn} = OpIMul %uint {sgn_bit} {self.cu(0xFF)}") - self.emit(f"{sb_hi} = OpBitwiseAnd %uint {sb} {self.cu(0xFC)}") - self.emit(f"{is_sgn} = OpIEqual %bool {sb_hi} {self.cu(8)}") - self.emit(f"{big} = OpUGreaterThanEqual %bool {sb} {self.cu(13)}") - self.emit(f"{const} = OpSelect %uint {big} {self.cu(0xFF)} {self.cu(0)}") - self.emit(f"{ff} = OpSelect %uint {is_sgn} {sgn} {const}") - self.emit(f"{val} = OpSelect %uint {inrange} {chosen} {ff}") - m8 = self.tmp() - self.emit(f"{m8} = OpBitwiseAnd %uint {val} {self.cu(0xFF)}") - self.emit(f"{shifted} = OpShiftLeftLogical %uint {m8} {self.cu(8 * i)}") - self.emit(f"{acc} = OpBitwiseOr %uint {out} {shifted}") - out = acc - self.dst(a[0], out) - elif op in ("s_and_b64", "s_or_b64", "s_xor_b64", "s_andn2_b64", "s_orn2_b64", - "s_nand_b64", "s_nor_b64", "s_xnor_b64"): - k = {"and": "OpBitwiseAnd", "or": "OpBitwiseOr", "xor": "OpBitwiseXor", "andn2": "OpBitwiseAnd", - "orn2": "OpBitwiseOr", "nand": "OpBitwiseAnd", "nor": "OpBitwiseOr", - "xnor": "OpBitwiseXor"}[op.split("_")[1]] - # s_nand/nor/xnor_b64: D = ~(S0 op S1). A lane's mask value is 0 or ~0, so the NOT is per lane too. - inv = op in ("s_nand_b64", "s_nor_b64", "s_xnor_b64") - if (a[0]["k"] == "special" and a[0].get("t", "").startswith(("exec", "vcc"))) or \ - self.is_mask_op(a[1]) or self.is_mask_op(a[2]): - x, y = self.mask_src(a[1]), self.mask_src(a[2]) - r = self.tmp() - if op.endswith("n2_b64"): - n = self.tmp() - self.emit(f"{n} = OpNot %uint {y}") - y = n - self.emit(f"{r} = {k} %uint {x} {y}") - if inv: - t, r = r, self.tmp() - self.emit(f"{r} = OpNot %uint {t}") - self.mask_dst(a[0], r) - self.scc_from_mask(r) - else: - if not ((a[0]["k"] == "sgpr" and a[0].get("n") == 2) or - (a[0]["k"] == "special" and a[0].get("t") == "null")): - raise Unsupported(op + " destination") - # Load all source dwords before storing to a[0] so destination aliasing stays exact; - # lane_masks.py already clears a[0]'s mask state when either source is non-mask. - (xlo, xhi), (ylo, yhi) = self.src64_data(a[1], op), self.src64_data(a[2], op) - if op.endswith("n2_b64"): - nlo, nhi = self.tmp(), self.tmp() - self.emit(f"{nlo} = OpNot %uint {ylo}") - self.emit(f"{nhi} = OpNot %uint {yhi}") - ylo, yhi = nlo, nhi - rlo, rhi = self.tmp(), self.tmp() - self.emit(f"{rlo} = {k} %uint {xlo} {ylo}") - self.emit(f"{rhi} = {k} %uint {xhi} {yhi}") - if inv: - (tlo, thi), rlo, rhi = (rlo, rhi), self.tmp(), self.tmp() - self.emit(f"{rlo} = OpNot %uint {tlo}") - self.emit(f"{rhi} = OpNot %uint {thi}") - self.dst64_data(a[0], rlo, rhi, op, allow_null=True) - orr = self.tmp() - self.emit(f"{orr} = OpBitwiseOr %uint {rlo} {rhi}") - self.scc_nonzero(orr) - elif op == "s_cselect_b64": - if (a[0]["k"] == "special" and a[0].get("t", "").startswith(("exec", "vcc"))) or \ - self.is_mask_op(a[1]) or self.is_mask_op(a[2]): - x, y = self.mask_src(a[1]), self.mask_src(a[2]) - c, b, r = self.tmp(), self.tmp(), self.tmp() - self.emit(f"{c} = OpLoad %uint %scc") - self.emit(f"{b} = OpINotEqual %bool {c} {self.cu(0)}") - self.emit(f"{r} = OpSelect %uint {b} {x} {y}") - self.mask_dst(a[0], r) - else: - if a[0]["k"] != "sgpr" or a[0].get("n") != 2: - raise Unsupported("s_cselect_b64 destination") - # Load all source dwords before storing to a[0] so destination aliasing stays exact; - # lane_masks.py already clears a[0]'s mask state when either source is non-mask. - (lo1, hi1), (lo2, hi2) = self.src64_data(a[1], op), self.src64_data(a[2], op) - c, b, rlo, rhi = self.tmp(), self.tmp(), self.tmp(), self.tmp() - self.emit(f"{c} = OpLoad %uint %scc") - self.emit(f"{b} = OpINotEqual %bool {c} {self.cu(0)}") - self.emit(f"{rlo} = OpSelect %uint {b} {lo1} {lo2}") - self.emit(f"{rhi} = OpSelect %uint {b} {hi1} {hi2}") - self.dst64_data(a[0], rlo, rhi, op) - elif op in ("v_interp_p1ll_f16", "v_interp_p1lv_f16", "v_interp_p2_f16"): - attr = next((x for x in a if x["k"] == "attr"), None) - if attr is None or self.stage != "ps": - raise Unsupported(op + " form") - self.interp_pair_src(op, a, ins) - # `high` (on both ops of the pair) selects the upper f16 of the packed channel (Mesa ACO - # emit-interp_instr passes high_16bits to p1ll and p2). Under --bary-fallback there are no per-vertex - # inputs, so the old smooth-f32 read stands and `high` cannot be told apart (docs/design.md). - f = self.attribute(attr["a"], attr["c"], half=1 if "high" in mods else 0, ij=self.interp_weights(ins)) - if op == "v_interp_p2_f16": - # VOP3 clamp applies to the f16 result (ACO: dst(F16); llvm-mc takes clamp but no omod on this op). - # Until 2026-11-22 it was dropped. A partial write like the other f16 results: the high half of vdst is - # kept (SHADER-430, measured on gfx1036 with tools/hw_oracle: a preset 0xdead high half survived every - # case). It used to be zeroed. - self.write_lo16(a[0], self.f16_res(self.clamp_f16(f, mods))) - else: # p1ll/p1lv produce the f32 intermediate consumed by p2_f16 - self.dst(a[0], self.tou(f)) - elif op in SOPC_CMP32_OPS: - self._validate_sopc(ins, op, a, mods) - self.compare(op, a, scalar=True) - elif op.startswith("s_cmpk_"): - # s_cmpk__ sX, imm16: zero-extended for u32, sign-extended for i32. - ty = op.rsplit("_", 1)[1] - v = a[1]["v"] & 0xFFFF - if ty == "i32" and v & 0x8000: - v -= 0x10000 - self.compare("s_cmp_" + op[len("s_cmpk_"):], [a[0], {"k": "imm", "v": v}], scalar=True) - elif op in SOPC_BITCMP_OPS: - self._validate_sopc(ins, op, a, mods, src0_64=op.endswith("_b64")) - self.bitcmp(op, a) - elif op == "s_mul_hi_u32": - x, y = self.src_u(a[1]), self.src_u(a[2]) - s, r = self.tmp(), self.tmp() - self.emit(f"{s} = OpUMulExtended %umul {x} {y}") - self.emit(f"{r} = OpCompositeExtract %uint {s} 1") - self.dst(a[0], r) - elif op == "s_mul_hi_i32": - # High 32 bits of the signed 64-bit product; SCC is not written. - x, y = self.as_int(self.src_u(a[1])), self.as_int(self.src_u(a[2])) - s, hi, r = self.tmp(), self.tmp(), self.tmp() - self.emit(f"{s} = OpSMulExtended %smul {x} {y}") - self.emit(f"{hi} = OpCompositeExtract %int {s} 1") - self.emit(f"{r} = OpBitcast %uint {hi}") - self.uses_smul = True - self.dst(a[0], r) - elif op == "s_absdiff_i32": - # RDNA2 ISA: D = S0 - S1 as a 32-bit signed value, negated if negative; SCC = (D != 0). The difference - # wraps before the absolute value (0x7FFFFFFF - 0x80000000 = -1 -> 1), and SAbs keeps 0x80000000 as is. - x_val, y_val = self.imm_val(a[1]), self.imm_val(a[2]) - if x_val is not None and y_val is not None: - diff = (x_val - y_val) & 0xFFFFFFFF - diff_i = diff if diff < 0x80000000 else diff - 0x100000000 - val = abs(diff_i) & 0xFFFFFFFF - r = self.cu(val) - self.dst(a[0], r) - if a[0]["k"] == "sgpr" and a[0].get("n", 1) == 1: - self.sgpr_imm[a[0]["r"]] = val - self.emit(f"OpStore %scc {self.cu(1 if val != 0 else 0)}") - return - x, y = self.src_u(a[1]), self.src_u(a[2]) - d, ab, r = self.tmp(), self.tmp(), self.tmp() - self.emit(f"{d} = OpISub %uint {x} {y}") - self.emit(f"{ab} = OpExtInst %int %glsl SAbs {self.as_int(d)}") - self.emit(f"{r} = OpBitcast %uint {ab}") - self.dst(a[0], r) - self.scc_nonzero(r) - elif op in ("v_fma_mixlo_f16", "v_fma_mixhi_f16"): - vals = self.fma_mix_srcs(a, mods) - r = self.fma_mix_odd(*vals) - r = self.clamp_f16(r, mods) - self.f16_out(a[0], r, hi=(op == "v_fma_mixhi_f16")) - elif op == "v_cvt_pk_u8_f32": - # Convert src0 to u8 (round to nearest even, clamp, NaN gives 0) and insert it at byte src1 of src2. - # Measured natively on RDNA2 (cs_cvt_pk_u8.asm). A NaN, found from its bits, is replaced by +0 - # before FClamp, which is undefined for a NaN operand. - x, byte, base = self.src_f(a[1]), self.src_u(a[2]), self.src_u(a[3]) - c, rn, u, sh, mask, nmask, keep, ins_, r = (self.tmp() for _ in range(9)) - mag, not_nan, safe = self.tmp(), self.tmp(), self.tmp() - self.emit(f"{mag} = OpBitwiseAnd %uint {self.tou(x)} {self.cu(0x7FFFFFFF)}") - self.emit(f"{not_nan} = OpULessThan %bool {mag} {self.cu(0x7F800001)}") - self.emit(f"{safe} = OpSelect %float {not_nan} {x} %f0") - self.emit(f"{c} = OpExtInst %float %glsl FClamp {safe} %f0 {self.fconst(255.0)}") - self.emit(f"{rn} = OpExtInst %float %glsl RoundEven {c}") - self.emit(f"{u} = OpConvertFToU %uint {rn}") - b3 = self.tmp() - self.emit(f"{b3} = OpBitwiseAnd %uint {byte} {self.cu(3)}") - self.emit(f"{sh} = OpIMul %uint {b3} {self.cu(8)}") - self.emit(f"{mask} = OpShiftLeftLogical %uint {self.cu(0xFF)} {sh}") - self.emit(f"{nmask} = OpNot %uint {mask}") - self.emit(f"{keep} = OpBitwiseAnd %uint {base} {nmask}") - self.emit(f"{ins_} = OpShiftLeftLogical %uint {u} {sh}") - self.emit(f"{r} = OpBitwiseOr %uint {keep} {ins_}") - self.dst(a[0], r) - elif op == "v_mul_hi_u32": - self._check_int32_valu(op, ins["op"], a, mods) - x, y = self.src_u(a[1]), self.src_u(a[2]) - s, r = self.tmp(), self.tmp() - self.emit(f"{s} = OpUMulExtended %umul {x} {y}") - self.emit(f"{r} = OpCompositeExtract %uint {s} 1") - self.dst(a[0], r) - elif op in ("v_cvt_pk_u16_u32", "v_cvt_pk_i16_i32"): - # D = {sat16(S1), sat16(S0)} (RDNA ISA pseudocode: u32_to_u16 / i32_to_i16 saturate): the low half from - # S0, the high half from S1; u16 clamps to [0, 0xFFFF], i16 to [-32768, 32767]. The whole dword is - # written. clamp is not modelled: rejected rather than guessed. - if "clamp" in mods: - raise Unsupported(op + " clamp") - halves = [] - for src in a[1:3]: - halves.append(self.saturate_int16(self.src_u(src), signed=(op == "v_cvt_pk_i16_i32"))) - sh, r = self.tmp(), self.tmp() - self.emit(f"{sh} = OpShiftLeftLogical %uint {halves[1]} {self.cu(16)}") - self.emit(f"{r} = OpBitwiseOr %uint {halves[0]} {sh}") - self.dst(a[0], r) - elif op in ("v_cvt_pknorm_i16_f32", "v_cvt_pknorm_u16_f32"): - # D = {norm16(S1), norm16(S0)}: each f32 clamped to [-1, 1] (i16) or [0, 1] (u16), scaled by 32767 or - # 65535 and rounded to nearest even. Mesa ACO emits these for NIR pack_snorm_2x16 / pack_unorm_2x16, - # which nir_opcodes.py defines as fround_even(fclamp(x) * 32767.0 / 65535.0). NaN gives 0, as - # v_cvt_i32_f32 does (measured on gfx1036, SHADER-339). The whole dword is written. - # RDNA2 rounds the exact product once (SHADER-363): the f32 OpFMul can land exactly on k + 0.5 when the - # exact product is just below or above it, and RoundEven then picks the even neighbour. The product's - # error e = Fma(c, s, -p) is exact, and on such a tie its sign decides: floor(p) + 1 above, floor(p) - # below, RoundEven when e is 0. Away from a tie both roundings agree, since k + 0.5 is an f32 here. - # Measured natively on RDNA2 (gfx1036, wave32 & wave64 across 6 HW_REG_MODE configs): VOP3 - # clamp is a hardware no-op on v_cvt_pknorm_{i16,u16}_f32 (each lane is already clamped to - # [-1, 1] / [0, 1] and packed to 16-bit integer). Reject other unexpected modifiers. - if any(m != "clamp" for m in mods): - raise Unsupported(op + " modifiers") - snorm = op == "v_cvt_pknorm_i16_f32" - halves = [] - for src in a[1:3]: - f = self.src_f(src) - nan, z, c, m, rr, i, h = (self.tmp() for _ in range(7)) - self.emit(f"{nan} = OpIsNan %bool {f}") - self.emit(f"{z} = OpSelect %float {nan} %f0 {f}") - self.emit(f"{c} = OpExtInst %float %glsl FClamp {z} {self.fconst(-1.0) if snorm else '%f0'} %f1") - scale = self.fconst(32767.0 if snorm else 65535.0) - self.emit(f"{m} = OpFMul %float {c} {scale}") - re_, nm, e, fl, fr, tie, epos, eneg, up, pick = (self.tmp() for _ in range(10)) - self.emit(f"{re_} = OpExtInst %float %glsl RoundEven {m}") - self.emit(f"{nm} = OpFNegate %float {m}") - self.emit_fma(e, c, scale, nm) - self.emit(f"{fl} = OpExtInst %float %glsl Floor {m}") - self.emit(f"{fr} = OpFSub %float {m} {fl}") - self.emit(f"{tie} = OpFOrdEqual %bool {fr} {self.fconst(0.5)}") - self.emit(f"{epos} = OpFOrdGreaterThan %bool {e} %f0") - self.emit(f"{eneg} = OpFOrdLessThan %bool {e} %f0") - self.emit(f"{up} = OpFAdd %float {fl} %f1") - self.emit(f"{pick} = OpSelect %float {epos} {up} {re_}") - adj = self.tmp() - self.emit(f"{adj} = OpSelect %float {eneg} {fl} {pick}") - self.emit(f"{rr} = OpSelect %float {tie} {adj} {re_}") - if snorm: - si_ = self.tmp() - self.emit(f"{si_} = OpConvertFToS %int {rr}") - self.emit(f"{i} = OpBitcast %uint {si_}") - else: - self.emit(f"{i} = OpConvertFToU %uint {rr}") - self.emit(f"{h} = OpBitwiseAnd %uint {i} {self.cu(0xFFFF)}") - halves.append(h) - sh, r = self.tmp(), self.tmp() - self.emit(f"{sh} = OpShiftLeftLogical %uint {halves[1]} {self.cu(16)}") - self.emit(f"{r} = OpBitwiseOr %uint {halves[0]} {sh}") - self.dst(a[0], r) - elif op in ("v_cvt_pknorm_i16_f16", "v_cvt_pknorm_u16_f16"): - # RDNA2 ISA (VOP3): D[15:0] = norm16(S0.f16), D[31:16] = norm16(S1.f16). Each f16 (selected by - # op_sel[0..1], with neg/abs source modifiers) is clamped to [-1, 1] (i16) or [0, 1] (u16), scaled by - # 32767 or 65535 and rounded once to nearest even (NaN -> 0). For |cl| >= 0.25, cl * (scale + 1) is an - # exact even integer in f32, so cl * (scale + 1) - RoundEven(cl) gives the exact single-rounded result - # without binary32 double-rounding at near-tie f16 inputs. Measured exhaustively on gfx1036 across all - # 65,536 f16 values (wave32 & wave64): VOP3 clamp is a hardware no-op, and op_sel[2] = 1 shifts the - # 32-bit packed result left by 16 bits (D[31:16] = norm16(S0.f16), D[15:0] = 0, overwriting D). - # Reserved VOP3 omod bits [60:59] are rejected by llvm-mc (gfx1036) and ignored by silicon, so - # mul:*/div:*, VOP3P modifiers, _dpp/_sdwa, and malformed op_sel lists are refused. - opsel_mods = [m for m in mods if m.startswith("op_sel:")] - if (ins["op"].endswith(("_dpp", "_sdwa")) or len(opsel_mods) > 1 or - any(m != "clamp" and not m.startswith("op_sel:") for m in mods)): - raise Unsupported(op + " modifier") - if opsel_mods: - m_sel = opsel_mods[0] - if not (m_sel.startswith("op_sel:[") and m_sel.endswith("]")): - raise Unsupported(op + " op_sel") - try: - raw_bits = [int(x) for x in m_sel[len("op_sel:["):-1].split(",")] - except ValueError: - raise Unsupported(op + " op_sel") from None - if not raw_bits or len(raw_bits) > 3 or any(b not in (0, 1) for b in raw_bits): - raise Unsupported(op + " op_sel") - sel, dhi = self.opsel_bits(mods, 2) - snorm = op == "v_cvt_pknorm_i16_f16" - lo_f = self.fconst(-1.0) if snorm else "%f0" - scale_f = self.fconst(32767.0 if snorm else 65535.0) - pow2_f = self.fconst(32768.0 if snorm else 65536.0) - qtr_f = self.fconst(0.25) - halves = [] - for idx, src in enumerate(a[1:3]): - f = self.f16_in(src, sel[idx]) - nan, z, cl, ab, big, p2, rc, r_big, m, r_sm, rr, i, h = (self.tmp() for _ in range(13)) - self.emit(f"{nan} = OpIsNan %bool {f}") - self.emit(f"{z} = OpSelect %float {nan} %f0 {f}") - self.emit(f"{cl} = OpExtInst %float %glsl FClamp {z} {lo_f} %f1") - self.emit(f"{ab} = OpExtInst %float %glsl FAbs {cl}") - self.emit(f"{big} = OpFOrdGreaterThanEqual %bool {ab} {qtr_f}") - self.emit(f"{p2} = OpFMul %float {cl} {pow2_f}") - self.emit(f"{rc} = OpExtInst %float %glsl RoundEven {cl}") - self.emit(f"{r_big} = OpFSub %float {p2} {rc}") - self.emit(f"{m} = OpFMul %float {cl} {scale_f}") - self.emit(f"{r_sm} = OpExtInst %float %glsl RoundEven {m}") - self.emit(f"{rr} = OpSelect %float {big} {r_big} {r_sm}") - if snorm: - si_ = self.tmp() - self.emit(f"{si_} = OpConvertFToS %int {rr}") - self.emit(f"{i} = OpBitcast %uint {si_}") - else: - self.emit(f"{i} = OpConvertFToU %uint {rr}") - self.emit(f"{h} = OpBitwiseAnd %uint {i} {self.cu(0xFFFF)}") - halves.append(h) - sh, r = self.tmp(), self.tmp() - self.emit(f"{sh} = OpShiftLeftLogical %uint {halves[1]} {self.cu(16)}") - self.emit(f"{r} = OpBitwiseOr %uint {halves[0]} {sh}") - if dhi: - r_hi = self.tmp() - self.emit(f"{r_hi} = OpShiftLeftLogical %uint {r} {self.cu(16)}") - r = r_hi - self.dst(a[0], r) - elif op == "v_cvt_pkrtz_f16_f32": - # Packs two f32 as f16 into one dword with round-toward-zero (exact, see f16_rtz). The earlier - # round-to-nearest version produced inf where hardware gives 65504 (found by the GPU smoke test). - x, y = self.src_f(a[1]), self.src_f(a[2]) - lo, hi = self.f16_rtz(x), self.f16_rtz(y) - sh, r = self.tmp(), self.tmp() - self.emit(f"{sh} = OpShiftLeftLogical %uint {hi} {self.cu(16)}") - self.emit(f"{r} = OpBitwiseOr %uint {lo} {sh}") - self.dst(a[0], r) - elif op == "v_cvt_off_f32_i4": - # RDNA ISA: D = CVT_OFF_TABLE[S0[3:0]], i.e. the 4-bit signed value / 16 (-0.5 .. 0.4375), exact in f32. - # Output modifiers (mul/div, clamp) apply to the result. - x = self.src_u(a[1]) - i4, fi, r = self.tmp(), self.tmp(), self.tmp() - self.emit(f"{i4} = OpBitFieldSExtract %uint {x} {self.cu(0)} {self.cu(4)}") - self.emit(f"{fi} = OpConvertSToF %float {self.as_int(i4)}") - self.emit(f"{r} = OpFMul %float {fi} {self.fconst(0.0625)}") - self.dst(a[0], self.tou(self.clamp_mods(r, mods))) - elif op == "v_rcp_iflag_f32": - x = self.src_f(a[1]) - r = self.tmp() - self.emit(f"{r} = OpFDiv %float %f1 {x}") - self.dst(a[0], self.tou(self.clamp_mods(r, mods))) - elif op in F2: - read_source = self.src_f_sign_mods if F2[op] in ("max", "min") else self.src_f - x, y = read_source(a[1]), read_source(a[2]) - r = self.tmp() - if F2[op] in ("max", "min"): - r = self.nminmax_f32("NMax" if F2[op] == "max" else "NMin", x, y, y_src=a[2]) - else: - self.emit(f"{r} = {F2[op]} %float {x} {y}") - self.dst(a[0], self.tou(self.clamp_mods(r, mods))) - elif op == "v_subrev_f32": - x, y = self.src_f(a[1]), self.src_f(a[2]) - r = self.tmp() - self.emit(f"{r} = OpFSub %float {y} {x}") - self.dst(a[0], self.tou(self.clamp_mods(r, mods))) - elif op in ("v_fma_f32", "v_fmac_f32", "v_fmaak_f32", "v_fmamk_f32", "v_med3_f32"): - if op in ("v_fma_f32", "v_fmaak_f32", "v_fmamk_f32"): - # fmaak D = S0 * S1 + K, printed `vdst, src0, vsrc1, K`; fmamk D = S0 * K + S1, printed - # `vdst, src0, K, vsrc1`. In print order both are fma(a[1], a[2], a[3]), like v_fma_f32. Until - # 2026-11-21 fmamk read a[3] as the factor, so it computed S0 * S1 + K. - x, y, z = (self.src_f(t) for t in a[1:4]) - elif op == "v_fmac_f32": - x, y, z = self.src_f(a[1]), self.src_f(a[2]), self.src_f(a[0]) - else: - r = self.med3_f([self.src_f_sign_mods(t) for t in a[1:4]], a[1:4]) - self.dst(a[0], self.tou(self.clamp_mods(r, mods))) - return - r = self.tmp() - self.emit_fma(r, x, y, z) - self.dst(a[0], self.tou(self.clamp_mods(r, mods))) - elif op in F1: - x = self.src_f(a[1]) - r = self.tmp() - if F1[op] == "rcp": - self.emit(f"{r} = OpFDiv %float %f1 {x}") - elif F1[op] in ("Floor", "Ceil", "Fract"): - r = self.round_f32_flushed(F1[op], x) - else: - self.emit(f"{r} = OpExtInst %float %glsl {F1[op]} {x}") - self.dst(a[0], self.tou(self.clamp_mods(r, mods))) - elif op in ("v_frexp_mant_f32", "v_frexp_exp_i32_f32", "v_ldexp_f32"): - # Bit-exact on the binary32 word (no float arithmetic). A normal input has biased exponent 1..254; - # zero and denormals are read as zero (the f32 denormal mode is not modelled, as for the other float ops) - # and infinities and NaNs (exponent 255) pass through: frexp_mant and ldexp return S0 unchanged, - # frexp_exp returns 0 (RDNA2 ISA, V_FREXP_MANT_F32 / V_FREXP_EXP_I32_F32 / V_LDEXP_F32). - x = self.src_u(a[1]) - e, em1, isnorm, isden, sgn, r = (self.tmp() for _ in range(6)) - self.emit(f"{e} = OpBitFieldUExtract %uint {x} {self.cu(23)} {self.cu(8)}") - self.emit(f"{em1} = OpISub %uint {e} {self.cu(1)}") - self.emit(f"{isnorm} = OpULessThan %bool {em1} {self.cu(254)}") # exponent field 1..254 - self.emit(f"{isden} = OpIEqual %bool {e} {self.cu(0)}") - self.emit(f"{sgn} = OpBitwiseAnd %uint {x} {self.cu(0x80000000)}") - other = self.tmp() - self.emit(f"{other} = OpSelect %uint {isden} {sgn} {x}") # zero/denormal -> +-0, inf/NaN -> S0 - if op == "v_frexp_exp_i32_f32": - # x = mant * 2^exp with mant in [0.5, 1): exp = biased exponent - 126. - ex = self.tmp() - self.emit(f"{ex} = OpISub %uint {e} {self.cu(126)}") - self.emit(f"{r} = OpSelect %uint {isnorm} {ex} {self.cu(0)}") - self.dst(a[0], r) - elif op == "v_frexp_mant_f32": - keep, m = self.tmp(), self.tmp() - self.emit(f"{keep} = OpBitwiseAnd %uint {x} {self.cu(0x807FFFFF)}") - self.emit(f"{m} = OpBitwiseOr %uint {keep} {self.cu(0x3F000000)}") # biased exponent 126 - self.emit(f"{r} = OpSelect %uint {isnorm} {m} {other}") - self.dst(a[0], self.tou(self.clamp_mods(self.tof(r), mods))) - else: - # D = S0 * 2^S1 with S1 a signed integer. The exponent is added in 32 bits after clamping S1 to - # [-512, 512] (enough to overflow or underflow any binary32), then the result saturates: above - # 254 it is +-inf, at 0 or below it is +-0 (no denormal results). - n = self.src_u(a[2]) - nb, small, neg, lim, nc, e2, e2m1, valid, pos, over = (self.tmp() for _ in range(10)) - self.emit(f"{nb} = OpIAdd %uint {n} {self.cu(512)}") - self.emit(f"{small} = OpULessThan %bool {nb} {self.cu(1025)}") # -512 <= n <= 512 - self.emit(f"{neg} = OpBitFieldUExtract %uint {n} {self.cu(31)} {self.cu(1)}") - negb = self.tmp_bool_nz(neg) - self.emit(f"{lim} = OpSelect %uint {negb} {self.cu(0xFFFFFE00)} {self.cu(512)}") - self.emit(f"{nc} = OpSelect %uint {small} {n} {lim}") - self.emit(f"{e2} = OpIAdd %uint {e} {nc}") - self.emit(f"{e2m1} = OpISub %uint {e2} {self.cu(1)}") - self.emit(f"{valid} = OpULessThan %bool {e2m1} {self.cu(254)}") # new exponent field 1..254 - self.emit(f"{pos} = OpBitFieldUExtract %uint {e2} {self.cu(31)} {self.cu(1)}") - posb = self.tmp() - self.emit(f"{posb} = OpIEqual %bool {pos} {self.cu(0)}") - self.emit(f"{over} = OpLogicalAnd %bool {posb} {self.tmp_bool_nz(e2)}") - sh, keep, norm, inf, ov = (self.tmp() for _ in range(5)) - self.emit(f"{sh} = OpShiftLeftLogical %uint {e2} {self.cu(23)}") - self.emit(f"{keep} = OpBitwiseAnd %uint {x} {self.cu(0x807FFFFF)}") - self.emit(f"{norm} = OpBitwiseOr %uint {keep} {sh}") - self.emit(f"{inf} = OpBitwiseOr %uint {sgn} {self.cu(0x7F800000)}") - self.emit(f"{ov} = OpSelect %uint {over} {inf} {sgn}") - scaled = self.tmp() - self.emit(f"{scaled} = OpSelect %uint {valid} {norm} {ov}") - self.emit(f"{r} = OpSelect %uint {isnorm} {scaled} {other}") - self.dst(a[0], self.tou(self.clamp_mods(self.tof(r), mods))) - elif op in ("v_frexp_mant_f64", "v_frexp_exp_i32_f64"): - # Binary64 frexp, bit-exact on the (lo, hi) dword pair without requiring Float64/Int64 unless VOP3 output - # modifiers are present. Measured natively on gfx1036 (wave32 & wave64, default denorm16_64=3, IEEE=0): - # - Normal inputs (biased exponent 1..2046): mant in [0.5, 1) with sign, exp = e - 1022. - # - Non-zero subnormals (e == 0, frac != 0): normalized to mant in [0.5, 1) with sign, exp = msb - 1073 - # (-1073..-1022), matching v_frexp_mant_f16 / v_frexp_exp_i16_f16. - # - Signed zero: +-0 / exp 0. Infinities and NaNs: unchanged / exp 0. - sv = a[1] - lo, hi = self.f64_source_words(sv, op) - if sv.get("abs"): - t = self.tmp() - self.emit(f"{t} = OpBitwiseAnd %uint {hi} {self.cu(0x7FFFFFFF)}") - hi = t - if sv.get("neg"): - t = self.tmp() - self.emit(f"{t} = OpBitwiseXor %uint {hi} {self.cu(0x80000000)}") - hi = t - e, em1, isnorm, is_e0, sgn = (self.tmp() for _ in range(5)) - self.emit(f"{e} = OpBitFieldUExtract %uint {hi} {self.cu(20)} {self.cu(11)}") - self.emit(f"{em1} = OpISub %uint {e} {self.cu(1)}") - self.emit(f"{isnorm} = OpULessThan %bool {em1} {self.cu(2046)}") # exponent field 1..2046 - self.emit(f"{is_e0} = OpIEqual %bool {e} {self.cu(0)}") - self.emit(f"{sgn} = OpBitwiseAnd %uint {hi} {self.cu(0x80000000)}") - f_hi, frac_or, nz_frac, is_sub, has_hi = (self.tmp() for _ in range(5)) - self.emit(f"{f_hi} = OpBitwiseAnd %uint {hi} {self.cu(0x000FFFFF)}") - self.emit(f"{frac_or} = OpBitwiseOr %uint {f_hi} {lo}") - self.emit(f"{nz_frac} = OpINotEqual %bool {frac_or} {self.cu(0)}") - self.emit(f"{is_sub} = OpLogicalAnd %bool {is_e0} {nz_frac}") # non-zero subnormal - self.emit(f"{has_hi} = OpINotEqual %bool {f_hi} {self.cu(0)}") - mh, ml, mhu, mlu = (self.tmp() for _ in range(4)) - self.emit(f"{mh} = OpExtInst %int %glsl FindUMsb {f_hi}") - self.emit(f"{ml} = OpExtInst %int %glsl FindUMsb {lo}") - self.emit(f"{mhu} = OpBitcast %uint {mh}") - self.emit(f"{mlu} = OpBitcast %uint {ml}") - if op == "v_frexp_exp_i32_f64": - if any(m in ("clamp", "mul:2", "mul:4", "div:2") for m in mods): - raise Unsupported(op + " output modifier") - ex_norm, ex_hi, ex_lo, ex_sub, r0, r = (self.tmp() for _ in range(6)) - self.emit(f"{ex_norm} = OpISub %uint {e} {self.cu(1022)}") - self.emit(f"{ex_hi} = OpISub %uint {mhu} {self.cu(1041)}") # (32 + mhu) - 1073 - self.emit(f"{ex_lo} = OpISub %uint {mlu} {self.cu(1073)}") - self.emit(f"{ex_sub} = OpSelect %uint {has_hi} {ex_hi} {ex_lo}") - self.emit(f"{r0} = OpSelect %uint {is_sub} {ex_sub} {self.cu(0)}") - self.emit(f"{r} = OpSelect %uint {isnorm} {ex_norm} {r0}") - self.dst(a[0], r) - else: - d = a[0] - if d["k"] != "vgpr" or d.get("n") != 2: - raise Unsupported(op + " destination") - keep, m_hi = self.tmp(), self.tmp() - self.emit(f"{keep} = OpBitwiseAnd %uint {hi} {self.cu(0x800FFFFF)}") - self.emit(f"{m_hi} = OpBitwiseOr %uint {keep} {self.cu(0x3FE00000)}") # biased exponent 1022 - # Normalize 52-bit subnormal (f_hi, lo) by shifting left (52 - msb) so the leading 1 lands at bit 52. - # Mask every shift count with 31 so unselected paths stay strictly in 0..31 (no SPIR-V shift UB). - # Case A (f_hi != 0): msb = 32 + mhu (mhu in 0..19), sh = 20 - mhu (1..20), inv = 12 + mhu (12..31). - sha0, sha, inva0, inva, a_lo, a_h1, a_h2, a_hi = (self.tmp() for _ in range(8)) - self.emit(f"{sha0} = OpISub %uint {self.cu(20)} {mhu}") - self.emit(f"{sha} = OpBitwiseAnd %uint {sha0} {self.cu(31)}") - self.emit(f"{inva0} = OpIAdd %uint {mhu} {self.cu(12)}") - self.emit(f"{inva} = OpBitwiseAnd %uint {inva0} {self.cu(31)}") - self.emit(f"{a_lo} = OpShiftLeftLogical %uint {lo} {sha}") - self.emit(f"{a_h1} = OpShiftLeftLogical %uint {f_hi} {sha}") - self.emit(f"{a_h2} = OpShiftRightLogical %uint {lo} {inva}") - self.emit(f"{a_hi} = OpBitwiseOr %uint {a_h1} {a_h2}") - # Case B (f_hi == 0): msb = mlu (0..31). - # B1 (mlu <= 20): sh >= 32 -> lo = 0, hi_frac = lo << (20 - mlu). - # B2 (mlu >= 21): sh = 52 - mlu (21..31), inv = mlu - 20 (1..11) -> lo = lo << sh, hi_frac = lo >> inv. - is_b1, shb1_0, shb1, b1_hi = (self.tmp() for _ in range(4)) - self.emit(f"{is_b1} = OpULessThanEqual %bool {mlu} {self.cu(20)}") - self.emit(f"{shb1_0} = OpISub %uint {self.cu(20)} {mlu}") - self.emit(f"{shb1} = OpBitwiseAnd %uint {shb1_0} {self.cu(31)}") - self.emit(f"{b1_hi} = OpShiftLeftLogical %uint {lo} {shb1}") - shb2_0, shb2, invb2_0, invb2, b2_lo, b2_hi = (self.tmp() for _ in range(6)) - self.emit(f"{shb2_0} = OpISub %uint {self.cu(52)} {mlu}") - self.emit(f"{shb2} = OpBitwiseAnd %uint {shb2_0} {self.cu(31)}") - self.emit(f"{invb2_0} = OpISub %uint {mlu} {self.cu(20)}") - self.emit(f"{invb2} = OpBitwiseAnd %uint {invb2_0} {self.cu(31)}") - self.emit(f"{b2_lo} = OpShiftLeftLogical %uint {lo} {shb2}") - self.emit(f"{b2_hi} = OpShiftRightLogical %uint {lo} {invb2}") - b_lo, b_hi, sub_lo, sub_hi_raw, sub_hi_frac, sub_hi_exp, sub_hi = (self.tmp() for _ in range(7)) - self.emit(f"{b_lo} = OpSelect %uint {is_b1} {self.cu(0)} {b2_lo}") - self.emit(f"{b_hi} = OpSelect %uint {is_b1} {b1_hi} {b2_hi}") - self.emit(f"{sub_lo} = OpSelect %uint {has_hi} {a_lo} {b_lo}") - self.emit(f"{sub_hi_raw} = OpSelect %uint {has_hi} {a_hi} {b_hi}") - self.emit(f"{sub_hi_frac} = OpBitwiseAnd %uint {sub_hi_raw} {self.cu(0x000FFFFF)}") - self.emit(f"{sub_hi_exp} = OpBitwiseOr %uint {sub_hi_frac} {self.cu(0x3FE00000)}") - self.emit(f"{sub_hi} = OpBitwiseOr %uint {sub_hi_exp} {sgn}") - # Signed zeros (+0/-0) and inf/NaN already pass through (lo, hi) unchanged. - other_hi, other_lo, r_hi, r_lo = (self.tmp() for _ in range(4)) - self.emit(f"{other_hi} = OpSelect %uint {is_sub} {sub_hi} {hi}") - self.emit(f"{other_lo} = OpSelect %uint {is_sub} {sub_lo} {lo}") - self.emit(f"{r_hi} = OpSelect %uint {isnorm} {m_hi} {other_hi}") - self.emit(f"{r_lo} = OpSelect %uint {isnorm} {lo} {other_lo}") - # SHADER-721 follow-up, measured with tools/hw_oracle on gfx1036 (wave32 and wave64 identical, - # tools/f64_omod_probe.py): a binary64 result ignores mul:2/mul:4/div:2 while denorm_mode_16_64 = 3, - # which is the game's MODE. clamp applies in every MODE, so only it needs Float64 here. - if "clamp" in mods: - self.uses_f64 = True - v2, dv, mv2 = self.tmp(), self.tmp(), self.tmp() - self.emit(f"{v2} = OpCompositeConstruct %v2uint_d {r_lo} {r_hi}") - self.emit(f"{dv} = OpBitcast %double {v2}") - dv = self.clamp_mods_f64(dv, [m for m in mods if m == "clamp"]) - self.emit(f"{mv2} = OpBitcast %v2uint_d {dv}") - r_lo, r_hi = self.tmp(), self.tmp() - self.emit(f"{r_lo} = OpCompositeExtract %uint {mv2} 0") - self.emit(f"{r_hi} = OpCompositeExtract %uint {mv2} 1") - self.dst({"k": "vgpr", "r": d["r"], "n": 1}, r_lo) - self.dst({"k": "vgpr", "r": d["r"] + 1, "n": 1}, r_hi) - elif op == "v_div_fixup_f32": - # IEEE-754 single-precision division fixup: D = div_fixup_f32(S0=quotient, S1=denom, S2=numer). - # Measured natively on RDNA2 (gfx1036, wave32 & wave64, 256 triples across 4 MODEs + modifier matrix) - # under the game's inferred MODE (IEEE=0, denorm32=0, DX10_CLAMP=1): - # - VOP3 abs (clear bit 31) then neg (flip bit 31) apply bitwise to S0/S1/S2 before classification - # (including on NaN payloads). - # - S1 and S2 subnormals flush to signed zero (exp == 0); S0 subnormals are preserved. - # - Priority order (highest first): - # 1. NaN(S2) -> S2 (unchanged under IEEE=0) - # 2. NaN(S1) -> S1 (unchanged under IEEE=0) - # 3. (zero(S1) && zero(S2)) || (inf(S1) && inf(S2)) -> 0xFFC00000 (-qNaN) - # 4. zero(S2) || inf(S1) -> sign_out (+-0.0) - # 5. zero(S1) || inf(S2) -> sign_out | 0x7F800000 (+-inf) - # 6. exp(S2) - exp(S1) <= -151 -> sign_out (+-0.0; pure biased-exponent diff, beats NaN(S0)) - # 7. NaN(S0) -> sign_out | 0x7F800000 (+-inf) - # 8. otherwise -> copysign(S0, sign_out) - # - Output modifiers: mul:2/mul:4/div:2 then clamp (DX10_CLAMP=1 maps NaN to +0.0 before [0, 1]). - self._validate_div_valu( - ins, op, mods, dst_width=1, src_width=1, allow_opsel=False, strict_omod=True, allow_null_dst=True, - ) - - def _raw_f32_bits(arg): - u_val = self.src_u({k: v for k, v in arg.items() if k not in ("abs", "neg")}) - if arg.get("abs"): - t = self.tmp() - self.emit(f"{t} = OpBitwiseAnd %uint {u_val} {self.cu(0x7FFFFFFF)}") - u_val = t - if arg.get("neg"): - t = self.tmp() - self.emit(f"{t} = OpBitwiseXor %uint {u_val} {self.cu(0x80000000)}") - u_val = t - return u_val - - def _emit(expr): - t = self.tmp() - self.emit(f"{t} = {expr}") - return t - - s0, s1, s2 = (_raw_f32_bits(arg) for arg in a[1:4]) - sign_xor = _emit(f"OpBitwiseXor %uint {s1} {s2}") - sign_out = _emit(f"OpBitwiseAnd %uint {sign_xor} {self.cu(0x80000000)}") - abs0 = _emit(f"OpBitwiseAnd %uint {s0} {self.cu(0x7FFFFFFF)}") - abs1 = _emit(f"OpBitwiseAnd %uint {s1} {self.cu(0x7FFFFFFF)}") - abs2 = _emit(f"OpBitwiseAnd %uint {s2} {self.cu(0x7FFFFFFF)}") - c_inf = self.cu(0x7F800000) - c_min_norm = self.cu(0x00800000) - nan0 = _emit(f"OpUGreaterThan %bool {abs0} {c_inf}") - nan1 = _emit(f"OpUGreaterThan %bool {abs1} {c_inf}") - nan2 = _emit(f"OpUGreaterThan %bool {abs2} {c_inf}") - inf1 = _emit(f"OpIEqual %bool {abs1} {c_inf}") - inf2 = _emit(f"OpIEqual %bool {abs2} {c_inf}") - zero1 = _emit(f"OpULessThan %bool {abs1} {c_min_norm}") - zero2 = _emit(f"OpULessThan %bool {abs2} {c_min_norm}") - e1 = _emit(f"OpShiftRightLogical %uint {abs1} {self.cu(23)}") - e2 = _emit(f"OpShiftRightLogical %uint {abs2} {self.cu(23)}") - e1_ge_e2 = _emit(f"OpUGreaterThanEqual %bool {e1} {e2}") - ediff = _emit(f"OpISub %uint {e1} {e2}") - ediff_ge_151 = _emit(f"OpUGreaterThanEqual %bool {ediff} {self.cu(151)}") - exp_uf = _emit(f"OpLogicalAnd %bool {e1_ge_e2} {ediff_ge_151}") - signed_inf = _emit(f"OpBitwiseOr %uint {sign_out} {c_inf}") - signed_s0 = _emit(f"OpBitwiseOr %uint {sign_out} {abs0}") - both_zero = _emit(f"OpLogicalAnd %bool {zero1} {zero2}") - both_inf = _emit(f"OpLogicalAnd %bool {inf1} {inf2}") - indet = _emit(f"OpLogicalOr %bool {both_zero} {both_inf}") - to_zero = _emit(f"OpLogicalOr %bool {zero2} {inf1}") - to_inf = _emit(f"OpLogicalOr %bool {zero1} {inf2}") - r = _emit(f"OpSelect %uint {nan0} {signed_inf} {signed_s0}") - r = _emit(f"OpSelect %uint {exp_uf} {sign_out} {r}") - r = _emit(f"OpSelect %uint {to_inf} {signed_inf} {r}") - r = _emit(f"OpSelect %uint {to_zero} {sign_out} {r}") - r = _emit(f"OpSelect %uint {indet} {self.cu(0xFFC00000)} {r}") - r = _emit(f"OpSelect %uint {nan1} {s1} {r}") - r = _emit(f"OpSelect %uint {nan2} {s2} {r}") - has_omod = any(m in ("mul:2", "mul:4", "div:2") for m in mods) - has_clamp = "clamp" in mods - if has_omod or has_clamp: - f = self.tof(r) - for m in mods: - if m in ("mul:2", "mul:4", "div:2"): - f = _emit(f"OpFMul %float {f} {self.fconst({'mul:2': 2.0, 'mul:4': 4.0, 'div:2': 0.5}[m])}") - if has_clamp: - is_nan = _emit(f"OpIsNan %bool {f}") - safe = _emit(f"OpSelect %float {is_nan} %f0 {f}") - f = _emit(f"OpExtInst %float %glsl FClamp {safe} %f0 %f1") - r = self.tou(f) - self.dst(a[0], r) - elif op == "v_ldexp_f64": - # Binary64 load-exponent: D.f64 = S0.f64 * 2^(S1.i32), lowered bit-exactly on the (lo, hi) dword pair - # using only 32-bit integer ops (no OpCapability Float64 or Int64 required, even with clamp). - # Measured natively on gfx1036 (wave32 & wave64, game MODE: ieee=0, dx10_clamp=1, denorm16_64=3): - # - +-0, +-inf, and NaNs (both qNaN and sNaN under ieee=0) pass through unchanged (after S0 abs/neg). - # - Subnormal inputs are normalized before scaling; subnormal outputs shift right by 1 - e2 (1..53) - # and round to nearest even (with carry into bit 52 giving +-min_norm; sh >= 54 flushes to +-0). - # - VOP3 clamp applies in both denorm16_64=3 and 0 (dx10_clamp=1: NaN/-0/<0 -> +0.0, >1.0 -> 1.0). - # - VOP3 omod (mul:2/mul:4/div:2) is ignored by hardware when denorm16_64=3 and active when 0, so it is - # rejected as MODE-dependent rather than guessed. - if any(m.startswith(("mul:", "div:")) for m in mods): - raise Unsupported(op + " output modifier") - d = a[0] - if d["k"] != "vgpr" or d.get("n") != 2: - raise Unsupported(op + " destination") - sv = a[1] - if sv["k"] in ("vgpr", "sgpr") and sv.get("n") == 2: - lo, hi = self.load_reg(sv["k"], sv["r"]), self.load_reg(sv["k"], sv["r"] + 1) - elif sv.get("f64_literal") and self.f64_literal_one_dword(sv): - lo, hi = self.cu(0), self.cu(sv["v"] & 0xFFFFFFFF) - elif sv["k"] == "fimm": - bits = struct.unpack("> 32) - elif sv["k"] == "imm": - v = sv["v"] - if -16 <= v <= 64 or not self.f64_literal_one_dword(sv): - bits = v & 0xFFFFFFFFFFFFFFFF - lo, hi = self.cu(bits & 0xFFFFFFFF), self.cu(bits >> 32) - else: - # RDNA2 places a 32-bit literal constant in bits [63:32] of an f64 operand (measured on gfx1036). - lo, hi = self.cu(0), self.cu(v & 0xFFFFFFFF) - else: - raise Unsupported(op + " operand") - n = self.src_u(a[2]) - if sv.get("abs"): - t = self.tmp() - self.emit(f"{t} = OpBitwiseAnd %uint {hi} {self.cu(0x7FFFFFFF)}") - hi = t - if sv.get("neg"): - t = self.tmp() - self.emit(f"{t} = OpBitwiseXor %uint {hi} {self.cu(0x80000000)}") - hi = t - e, em1, isnorm, isden, sgn, m_hi, m_or, m_nz, sub, fin = (self.tmp() for _ in range(10)) - self.emit(f"{e} = OpBitFieldUExtract %uint {hi} {self.cu(20)} {self.cu(11)}") - self.emit(f"{em1} = OpISub %uint {e} {self.cu(1)}") - self.emit(f"{isnorm} = OpULessThan %bool {em1} {self.cu(2046)}") # exponent field 1..2046 - self.emit(f"{isden} = OpIEqual %bool {e} {self.cu(0)}") - self.emit(f"{sgn} = OpBitwiseAnd %uint {hi} {self.cu(0x80000000)}") - self.emit(f"{m_hi} = OpBitwiseAnd %uint {hi} {self.cu(0x000FFFFF)}") - self.emit(f"{m_or} = OpBitwiseOr %uint {m_hi} {lo}") - self.emit(f"{m_nz} = OpINotEqual %bool {m_or} {self.cu(0)}") - self.emit(f"{sub} = OpLogicalAnd %bool {isden} {m_nz}") - self.emit(f"{fin} = OpLogicalOr %bool {isnorm} {sub}") - # Normalize finite non-zero input into 53-bit significand (sig_hi[20] = 1, sig_lo) and exponent field ef. - norm_hi, m_hi_nz, msb_hi_i, msb_hi, lsh_a_raw, lsh_a, rsh_a, a_hi1, a_hi2, a_hi, a_lo = \ - (self.tmp() for _ in range(11)) - self.emit(f"{norm_hi} = OpBitwiseOr %uint {m_hi} {self.cu(0x00100000)}") - self.emit(f"{m_hi_nz} = OpINotEqual %bool {m_hi} {self.cu(0)}") - self.emit(f"{msb_hi_i} = OpExtInst %int %glsl FindUMsb {m_hi}") - self.emit(f"{msb_hi} = OpBitcast %uint {msb_hi_i}") - self.emit(f"{lsh_a_raw} = OpISub %uint {self.cu(20)} {msb_hi}") - self.emit(f"{lsh_a} = OpExtInst %uint %glsl UMin {lsh_a_raw} {self.cu(20)}") # 1..20 when m_hi != 0 - self.emit(f"{rsh_a} = OpISub %uint {self.cu(32)} {lsh_a}") # 12..31 - self.emit(f"{a_hi1} = OpShiftLeftLogical %uint {m_hi} {lsh_a}") - self.emit(f"{a_hi2} = OpShiftRightLogical %uint {lo} {rsh_a}") - self.emit(f"{a_hi} = OpBitwiseOr %uint {a_hi1} {a_hi2}") - self.emit(f"{a_lo} = OpShiftLeftLogical %uint {lo} {lsh_a}") - msb_lo_i, msb_lo, msb_lo_c, lsh_b, b_lt32, lsh_b1, rsh_b1, b1_hi, b1_lo, lsh_b2_raw, lsh_b2, b2_hi, b_hi, b_lo = \ - (self.tmp() for _ in range(14)) - self.emit(f"{msb_lo_i} = OpExtInst %int %glsl FindUMsb {lo}") - self.emit(f"{msb_lo} = OpBitcast %uint {msb_lo_i}") - self.emit(f"{msb_lo_c} = OpExtInst %uint %glsl UMin {msb_lo} {self.cu(31)}") - self.emit(f"{lsh_b} = OpISub %uint {self.cu(52)} {msb_lo_c}") # 21..52 - self.emit(f"{b_lt32} = OpULessThan %bool {lsh_b} {self.cu(32)}") - self.emit(f"{lsh_b1} = OpExtInst %uint %glsl UMin {lsh_b} {self.cu(31)}") - self.emit(f"{rsh_b1} = OpISub %uint {self.cu(32)} {lsh_b1}") - self.emit(f"{b1_hi} = OpShiftRightLogical %uint {lo} {rsh_b1}") - self.emit(f"{b1_lo} = OpShiftLeftLogical %uint {lo} {lsh_b1}") - self.emit(f"{lsh_b2_raw} = OpISub %uint {lsh_b} {self.cu(32)}") - self.emit(f"{lsh_b2} = OpExtInst %uint %glsl UMin {lsh_b2_raw} {self.cu(20)}") - self.emit(f"{b2_hi} = OpShiftLeftLogical %uint {lo} {lsh_b2}") - self.emit(f"{b_hi} = OpSelect %uint {b_lt32} {b1_hi} {b2_hi}") - self.emit(f"{b_lo} = OpSelect %uint {b_lt32} {b1_lo} {self.cu(0)}") - sub_hi, sub_lo, sub_lsh, sub_ef, sig_hi, sig_lo, ef = (self.tmp() for _ in range(7)) - self.emit(f"{sub_hi} = OpSelect %uint {m_hi_nz} {a_hi} {b_hi}") - self.emit(f"{sub_lo} = OpSelect %uint {m_hi_nz} {a_lo} {b_lo}") - self.emit(f"{sub_lsh} = OpSelect %uint {m_hi_nz} {lsh_a} {lsh_b}") - self.emit(f"{sub_ef} = OpISub %uint {self.cu(1)} {sub_lsh}") - self.emit(f"{sig_hi} = OpSelect %uint {isnorm} {norm_hi} {sub_hi}") - self.emit(f"{sig_lo} = OpSelect %uint {isnorm} {lo} {sub_lo}") - self.emit(f"{ef} = OpSelect %uint {isnorm} {e} {sub_ef}") - # Clamp S1 to [-4096, 4096] (enough to overflow or underflow any binary64) and add to ef. - nc_i, e2_i, e2, e2m1, valid, over = (self.tmp() for _ in range(6)) - self.emit(f"{nc_i} = OpExtInst %int %glsl SClamp {self.as_int(n)} " - f"{self.as_int(self.cu(0xFFFFF000))} {self.as_int(self.cu(4096))}") - self.emit(f"{e2_i} = OpIAdd %int {self.as_int(ef)} {nc_i}") - self.emit(f"{e2} = OpBitcast %uint {e2_i}") - self.emit(f"{e2m1} = OpISub %uint {e2} {self.cu(1)}") - self.emit(f"{valid} = OpULessThan %bool {e2m1} {self.cu(2046)}") # 1..2046 - self.emit(f"{over} = OpSGreaterThan %bool {e2_i} {self.as_int(self.cu(2046))}") - e2_sh, sig_m, norm_r_hi0, norm_r_hi, inf_hi = (self.tmp() for _ in range(5)) - self.emit(f"{e2_sh} = OpShiftLeftLogical %uint {e2} {self.cu(20)}") - self.emit(f"{sig_m} = OpBitwiseAnd %uint {sig_hi} {self.cu(0x000FFFFF)}") - self.emit(f"{norm_r_hi0} = OpBitwiseOr %uint {sgn} {sig_m}") - self.emit(f"{norm_r_hi} = OpBitwiseOr %uint {norm_r_hi0} {e2_sh}") - self.emit(f"{inf_hi} = OpBitwiseOr %uint {sgn} {self.cu(0x7FF00000)}") - # Subnormal / underflow (e2 <= 0): shift 53-bit significand right by sh = 1 - e2 and round to nearest even. - sh_i, under, sh_ci, sh_c, sh_lt32, sh_eq32 = (self.tmp() for _ in range(6)) - self.emit(f"{sh_i} = OpISub %int {self.as_int(self.cu(1))} {e2_i}") - self.emit(f"{under} = OpSGreaterThan %bool {sh_i} {self.as_int(self.cu(53))}") - self.emit(f"{sh_ci} = OpExtInst %int %glsl SClamp {sh_i} {self.as_int(self.cu(1))} " - f"{self.as_int(self.cu(53))}") - self.emit(f"{sh_c} = OpBitcast %uint {sh_ci}") - self.emit(f"{sh_lt32} = OpULessThan %bool {sh_c} {self.cu(32)}") - self.emit(f"{sh_eq32} = OpIEqual %bool {sh_c} {self.cu(32)}") - # Path 1: 1 <= sh <= 31 - s1, rs1, sm1, q1_hi, q1_lo1, q1_lo2, q1_lo, half1, hm1, mask1, rem1, gt1, eq1 = \ - (self.tmp() for _ in range(13)) - self.emit(f"{s1} = OpExtInst %uint %glsl UMin {sh_c} {self.cu(31)}") - self.emit(f"{rs1} = OpISub %uint {self.cu(32)} {s1}") - self.emit(f"{sm1} = OpISub %uint {s1} {self.cu(1)}") - self.emit(f"{q1_hi} = OpShiftRightLogical %uint {sig_hi} {s1}") - self.emit(f"{q1_lo1} = OpShiftRightLogical %uint {sig_lo} {s1}") - self.emit(f"{q1_lo2} = OpShiftLeftLogical %uint {sig_hi} {rs1}") - self.emit(f"{q1_lo} = OpBitwiseOr %uint {q1_lo1} {q1_lo2}") - self.emit(f"{half1} = OpShiftLeftLogical %uint {self.cu(1)} {sm1}") - self.emit(f"{hm1} = OpShiftLeftLogical %uint {half1} {self.cu(1)}") - self.emit(f"{mask1} = OpISub %uint {hm1} {self.cu(1)}") - self.emit(f"{rem1} = OpBitwiseAnd %uint {sig_lo} {mask1}") - self.emit(f"{gt1} = OpUGreaterThan %bool {rem1} {half1}") - self.emit(f"{eq1} = OpIEqual %bool {rem1} {half1}") - # Path 2: sh == 32 - gt2, eq2 = self.tmp(), self.tmp() - self.emit(f"{gt2} = OpUGreaterThan %bool {sig_lo} {self.cu(0x80000000)}") - self.emit(f"{eq2} = OpIEqual %bool {sig_lo} {self.cu(0x80000000)}") - # Path 3: 33 <= sh <= 53 - s3_raw, s3_ci, s3, s3m1, q3_lo, half3, hm3, mask3, rem3, lo_nz, lo_z, r3_gt, r3_eq, r3_eq_nz, gt3, eq3 = \ - (self.tmp() for _ in range(16)) - self.emit(f"{s3_raw} = OpISub %int {sh_ci} {self.as_int(self.cu(32))}") - self.emit(f"{s3_ci} = OpExtInst %int %glsl SClamp {s3_raw} {self.as_int(self.cu(1))} " - f"{self.as_int(self.cu(21))}") - self.emit(f"{s3} = OpBitcast %uint {s3_ci}") - self.emit(f"{s3m1} = OpISub %uint {s3} {self.cu(1)}") - self.emit(f"{q3_lo} = OpShiftRightLogical %uint {sig_hi} {s3}") - self.emit(f"{half3} = OpShiftLeftLogical %uint {self.cu(1)} {s3m1}") - self.emit(f"{hm3} = OpShiftLeftLogical %uint {half3} {self.cu(1)}") - self.emit(f"{mask3} = OpISub %uint {hm3} {self.cu(1)}") - self.emit(f"{rem3} = OpBitwiseAnd %uint {sig_hi} {mask3}") - self.emit(f"{lo_nz} = OpINotEqual %bool {sig_lo} {self.cu(0)}") - self.emit(f"{lo_z} = OpLogicalNot %bool {lo_nz}") - self.emit(f"{r3_gt} = OpUGreaterThan %bool {rem3} {half3}") - self.emit(f"{r3_eq} = OpIEqual %bool {rem3} {half3}") - self.emit(f"{r3_eq_nz} = OpLogicalAnd %bool {r3_eq} {lo_nz}") - self.emit(f"{gt3} = OpLogicalOr %bool {r3_gt} {r3_eq_nz}") - self.emit(f"{eq3} = OpLogicalAnd %bool {r3_eq} {lo_z}") - # Combine paths and round to nearest even. - q23_lo, gt23, eq23, q_hi, q_lo, gt, eq, odd_u, odd, tie, up, inc, ql_inc, carry_b, carry, qh_inc = \ - (self.tmp() for _ in range(16)) - self.emit(f"{q23_lo} = OpSelect %uint {sh_eq32} {sig_hi} {q3_lo}") - self.emit(f"{gt23} = OpSelect %bool {sh_eq32} {gt2} {gt3}") - self.emit(f"{eq23} = OpSelect %bool {sh_eq32} {eq2} {eq3}") - self.emit(f"{q_hi} = OpSelect %uint {sh_lt32} {q1_hi} {self.cu(0)}") - self.emit(f"{q_lo} = OpSelect %uint {sh_lt32} {q1_lo} {q23_lo}") - self.emit(f"{gt} = OpSelect %bool {sh_lt32} {gt1} {gt23}") - self.emit(f"{eq} = OpSelect %bool {sh_lt32} {eq1} {eq23}") - self.emit(f"{odd_u} = OpBitwiseAnd %uint {q_lo} {self.cu(1)}") - self.emit(f"{odd} = OpINotEqual %bool {odd_u} {self.cu(0)}") - self.emit(f"{tie} = OpLogicalAnd %bool {eq} {odd}") - self.emit(f"{up} = OpLogicalOr %bool {gt} {tie}") - self.emit(f"{inc} = OpSelect %uint {up} {self.cu(1)} {self.cu(0)}") - self.emit(f"{ql_inc} = OpIAdd %uint {q_lo} {inc}") - self.emit(f"{carry_b} = OpULessThan %bool {ql_inc} {q_lo}") - self.emit(f"{carry} = OpSelect %uint {carry_b} {self.cu(1)} {self.cu(0)}") - self.emit(f"{qh_inc} = OpIAdd %uint {q_hi} {carry}") - den_hi0, den_hi, den_lo, nv_hi, nv_lo, sc_hi, sc_lo, r_hi, r_lo = (self.tmp() for _ in range(9)) - self.emit(f"{den_hi0} = OpBitwiseOr %uint {sgn} {qh_inc}") - self.emit(f"{den_hi} = OpSelect %uint {under} {sgn} {den_hi0}") - self.emit(f"{den_lo} = OpSelect %uint {under} {self.cu(0)} {ql_inc}") - self.emit(f"{nv_hi} = OpSelect %uint {over} {inf_hi} {den_hi}") - self.emit(f"{nv_lo} = OpSelect %uint {over} {self.cu(0)} {den_lo}") - self.emit(f"{sc_hi} = OpSelect %uint {valid} {norm_r_hi} {nv_hi}") - self.emit(f"{sc_lo} = OpSelect %uint {valid} {sig_lo} {nv_lo}") - self.emit(f"{r_hi} = OpSelect %uint {fin} {sc_hi} {hi}") - self.emit(f"{r_lo} = OpSelect %uint {fin} {sc_lo} {lo}") - if "clamp" in mods: - # DX10 clamp to [+0.0, 1.0]: NaN, -0.0, and negative values -> +0.0; > 1.0 (incl. +inf) -> 1.0. - re, re_all, rm_hi, rm_or, rm_nz, r_nan, r_neg, to_zero = (self.tmp() for _ in range(8)) - gt_hi, eq_hi, lo_gt0, eq_gt, to_one, c1_hi, c1_lo, c2_hi, c2_lo = (self.tmp() for _ in range(9)) - self.emit(f"{re} = OpBitwiseAnd %uint {r_hi} {self.cu(0x7FF00000)}") - self.emit(f"{re_all} = OpIEqual %bool {re} {self.cu(0x7FF00000)}") - self.emit(f"{rm_hi} = OpBitwiseAnd %uint {r_hi} {self.cu(0x000FFFFF)}") - self.emit(f"{rm_or} = OpBitwiseOr %uint {rm_hi} {r_lo}") - self.emit(f"{rm_nz} = OpINotEqual %bool {rm_or} {self.cu(0)}") - self.emit(f"{r_nan} = OpLogicalAnd %bool {re_all} {rm_nz}") - self.emit(f"{r_neg} = OpUGreaterThanEqual %bool {r_hi} {self.cu(0x80000000)}") - self.emit(f"{to_zero} = OpLogicalOr %bool {r_neg} {r_nan}") - self.emit(f"{gt_hi} = OpUGreaterThan %bool {r_hi} {self.cu(0x3FF00000)}") - self.emit(f"{eq_hi} = OpIEqual %bool {r_hi} {self.cu(0x3FF00000)}") - self.emit(f"{lo_gt0} = OpINotEqual %bool {r_lo} {self.cu(0)}") - self.emit(f"{eq_gt} = OpLogicalAnd %bool {eq_hi} {lo_gt0}") - self.emit(f"{to_one} = OpLogicalOr %bool {gt_hi} {eq_gt}") - self.emit(f"{c1_hi} = OpSelect %uint {to_one} {self.cu(0x3FF00000)} {r_hi}") - self.emit(f"{c1_lo} = OpSelect %uint {to_one} {self.cu(0)} {r_lo}") - self.emit(f"{c2_hi} = OpSelect %uint {to_zero} {self.cu(0)} {c1_hi}") - self.emit(f"{c2_lo} = OpSelect %uint {to_zero} {self.cu(0)} {c1_lo}") - r_hi, r_lo = c2_hi, c2_lo - self.dst({"k": "vgpr", "r": d["r"], "n": 1}, r_lo) - self.dst({"k": "vgpr", "r": d["r"] + 1, "n": 1}, r_hi) - elif op in ("v_cvt_f32_u32", "v_cvt_f32_i32"): - self._validate_cvt32_valu(ins, op, mods, float_src=False, float_dst=True) - x = self.src_u(a[1]) - r = self.tmp() - self.emit(f"{r} = {'OpConvertUToF' if op.endswith('u32') else 'OpConvertSToF'} %float " - f"{x if op.endswith('u32') else self.as_int(x)}") - self.dst(a[0], self.tou(self.clamp_mods(r, mods))) # VOP3: clamp, omod - elif op.startswith("v_cvt_f32_ubyte"): - n = int(op[-1]) - x = self.src_u(a[1]) - s, m, r = self.tmp(), self.tmp(), self.tmp() - self.emit(f"{s} = OpShiftRightLogical %uint {x} {self.cu(8 * n)}") - self.emit(f"{m} = OpBitwiseAnd %uint {s} {self.cu(0xFF)}") - self.emit(f"{r} = OpConvertUToF %float {m}") - self.dst(a[0], self.tou(self.clamp_mods(r, mods))) - elif op in ("v_cvt_flr_i32_f32", "v_cvt_rpi_i32_f32"): - self._validate_cvt32_valu(ins, op, mods, float_src=True, float_dst=False) - # Measured natively on RDNA2 (gfx1035 & gfx1036, wave32 & wave64): - # - v_cvt_flr_i32_f32 = sat_i32(floor(S0)). - # - v_cvt_rpi_i32_f32 = sat_i32(floor(S0 + 0.5)) computed exactly without binary32 rounding of S0 + 0.5: - # with f = Floor(x), frac = x - f is exact in binary32 across all normal ranges (0 for |x| >= 2^23, - # and rounds to >= 0.5 iff exact x - f >= 0.5 around -0.5), so (frac >= 0.5) ? (f + 1.0) : f is exact. - # - Out-of-range values (|x| >= 2^31, +-inf) and NaNs all saturate by the sign bit of x (+ -> 0x7FFFFFFF, - # - -> 0x80000000). Check x's bits before Floor so a driver cannot lose a NaN's sign bit. - x = self.src_f(a[1]) - x_bits = self.tou(x) - x_mag, x_neg, x_in_range, bound, safe_x_u, fl, signed, converted, result = (self.tmp() for _ in range(9)) - self.emit(f"{x_mag} = OpBitwiseAnd %uint {x_bits} {self.cu(0x7FFFFFFF)}") - self.emit(f"{x_in_range} = OpULessThan %bool {x_mag} {self.cu(0x4F000000)}") # |x| < 2^31 - self.emit(f"{x_neg} = OpINotEqual %bool {x_bits} {x_mag}") - self.emit(f"{bound} = OpSelect %uint {x_neg} {self.cu(0x80000000)} {self.cu(0x7FFFFFFF)}") - # Guard before Floor/FSub/FToS: -2^31 (0xCF000000) takes `bound` = 0x80000000 directly. A denormal operand - # is a zero, as on RDNA2 with f32 denormals flushed (the MODE inferred for the game; gfx1036 gives - # flr(-1e-45) = 0, where Floor of the kept denormal gives -1). - x_exp, x_norm, keep_x = self.tmp(), self.tmp(), self.tmp() - self.emit(f"{x_exp} = OpBitwiseAnd %uint {x_bits} {self.cu(0x7F800000)}") - self.emit(f"{x_norm} = OpINotEqual %bool {x_exp} {self.cu(0)}") - self.emit(f"{keep_x} = OpLogicalAnd %bool {x_in_range} {x_norm}") - self.emit(f"{safe_x_u} = OpSelect %uint {keep_x} {x_bits} {self.cu(0)}") - safe_x = self.tof(safe_x_u) - self.emit(f"{fl} = OpExtInst %float %glsl Floor {safe_x}") - if op == "v_cvt_rpi_i32_f32": - frac, ge_half, fl_plus1, rounded = (self.tmp() for _ in range(4)) - self.emit(f"{frac} = OpFSub %float {safe_x} {fl}") - self.emit(f"{ge_half} = OpFOrdGreaterThanEqual %bool {frac} {self.fconst(0.5)}") - self.emit(f"{fl_plus1} = OpFAdd %float {fl} %f1") - self.emit(f"{rounded} = OpSelect %float {ge_half} {fl_plus1} {fl}") - fl = rounded - self.emit(f"{signed} = OpConvertFToS %int {fl}") - self.emit(f"{converted} = OpBitcast %uint {signed}") - self.emit(f"{result} = OpSelect %uint {x_in_range} {converted} {bound}") - self.dst(a[0], result) - elif op in ("v_cvt_u32_f32", "v_cvt_i32_f32"): - self._validate_cvt32_valu(ins, op, mods, float_src=True, float_dst=False) - # Compare binary32 words before converting: the raw SPIR-V conversion - # must only see a representable operand, even when its result is discarded. - bits = self.src_u(a[1]) - zero = self.cu(0) - past_inf = self.cu(0x7F800001) - in_range, saturated, safe, converted, result = (self.tmp() for _ in range(5)) - if op == "v_cvt_u32_f32": - positive = self.tmp() - self.emit(f"{in_range} = OpULessThan %bool {bits} {self.cu(0x4F800000)}") # +2^32 - # Positive overflow through +inf saturates. Negative values and NaNs give zero. - self.emit(f"{positive} = OpULessThan %bool {bits} {past_inf}") - self.emit(f"{saturated} = OpSelect %uint {positive} {self.cu(0xFFFFFFFF)} {zero}") - else: - magnitude, negative, not_nan, bound = (self.tmp() for _ in range(4)) - self.emit(f"{magnitude} = OpBitwiseAnd %uint {bits} {self.cu(0x7FFFFFFF)}") - self.emit(f"{in_range} = OpULessThan %bool {magnitude} {self.cu(0x4F000000)}") # 2^31 - self.emit(f"{negative} = OpINotEqual %bool {bits} {magnitude}") - self.emit(f"{not_nan} = OpULessThan %bool {magnitude} {past_inf}") - self.emit(f"{bound} = OpSelect %uint {negative} {self.cu(0x80000000)} {self.cu(0x7FFFFFFF)}") - self.emit(f"{saturated} = OpSelect %uint {not_nan} {bound} {zero}") - self.emit(f"{safe} = OpSelect %uint {in_range} {bits} {zero}") - x = self.tof(safe) - if op == "v_cvt_u32_f32": - self.emit(f"{converted} = OpConvertFToU %uint {x}") - else: - signed = self.tmp() - self.emit(f"{signed} = OpConvertFToS %int {x}") - self.emit(f"{converted} = OpBitcast %uint {signed}") - self.emit(f"{result} = OpSelect %uint {in_range} {converted} {saturated}") - self.dst(a[0], result) - elif op in U2 or op in S2: - to_mask_dst, dst_half = (self._mask_b32_dst_half(a[0], a[1:3]) - if op in self.MASK_SOP2_B32 else (False, None)) - if op in S2: - x_val, y_val = self.imm_val(a[1]), self.imm_val(a[2]) - is_mask = to_mask_dst or ( - op in self.MASK_SOP2_B32 and (self.holds_lane_mask(a[1]) or self.holds_lane_mask(a[2])) - ) - if x_val is not None and y_val is not None and not is_mask: - folded = None - if op == "s_and_b32": - folded = (x_val & y_val) & 0xFFFFFFFF - elif op == "s_or_b32": - folded = (x_val | y_val) & 0xFFFFFFFF - elif op == "s_lshl_b32": - folded = (x_val << (y_val & 31)) & 0xFFFFFFFF - elif op == "s_lshr_b32": - folded = (x_val >> (y_val & 31)) & 0xFFFFFFFF - elif op == "s_mul_i32": - folded = (x_val * y_val) & 0xFFFFFFFF - if folded is not None: - r = self.cu(folded) - self.dst(a[0], r) - if a[0]["k"] == "sgpr" and a[0].get("n", 1) == 1 and op != "s_or_b32": - self.sgpr_imm[a[0]["r"]] = folded - if op in ("s_and_b32", "s_or_b32", "s_lshl_b32", "s_lshr_b32"): - self.emit(f"OpStore %scc {self.cu(1 if folded != 0 else 0)}") - return - r = self.tmp() - kind = U2.get(op) or S2.get(op) - if kind == "mul24": - x, y = self.src_u(a[1]), self.src_u(a[2]) - xm, ym = self.tmp(), self.tmp() - self.emit(f"{xm} = OpBitwiseAnd %uint {x} {self.cu(0xFFFFFF)}") - self.emit(f"{ym} = OpBitwiseAnd %uint {y} {self.cu(0xFFFFFF)}") - self.emit(f"{r} = OpIMul %uint {xm} {ym}") - else: - if op in ("s_lshl_b32", "s_lshr_b32"): - y_val = self.imm_val(a[2]) - if y_val is not None: - y = self.cu(y_val & 31) - else: - y_raw = self.src_u(a[2]) - m = self.tmp() - self.emit(f"{m} = OpBitwiseAnd %uint {y_raw} {self.cu(31)}") - y = m - x = self.src_u(a[1]) - else: - x, y = self.sop2_b32_srcs(op, a) # lane-mask sources as mask_src (s_and/or_b32 on EXEC) - self.emit(f"{r} = {kind} %uint {x} {y}") - self._store_b32_mask_dst(a[0], r, to_mask_dst, dst_half) - if op in ("s_and_b32", "s_or_b32"): - self.scc_logic(a, r) - elif op in ("s_lshl_b32", "s_lshr_b32"): - self.scc_nonzero(r) - elif op in SHIFT_REV: - sh_val = self.imm_val(a[1]) - if sh_val is not None: - m = self.cu(sh_val & 31) - else: - sh = self.src_u(a[1]) - m = self.tmp() - self.emit(f"{m} = OpBitwiseAnd %uint {sh} {self.cu(31)}") - x = self.src_u(a[2]) - r = self.tmp() - self.emit(f"{r} = {SHIFT_REV[op]} %uint {x} {m}") - self.dst(a[0], r) - elif op in ("v_bfe_u32", "v_bfe_i32"): - # offset and width are taken mod 32 (a width of 0 gives 0) - o_val, w_val = self.imm_val(a[2]), self.imm_val(a[3]) - if o_val is not None and w_val is not None: - off = o_val & 31 - wid = min(w_val & 31, 32 - off) - x_val = self.imm_val(a[1]) - if x_val is not None: - if wid == 0: - val = 0 - elif op == "v_bfe_u32": - val = (x_val >> off) & ((1 << wid) - 1) - else: - raw = (x_val >> off) & ((1 << wid) - 1) - sign_bit = 1 << (wid - 1) - val = ((raw ^ sign_bit) - sign_bit) & 0xFFFFFFFF - self.dst(a[0], self.cu(val)) - return - om = self.cu(off) - wc = self.cu(wid) - else: - if o_val is not None: - om = self.cu(o_val & 31) - else: - o = self.src_u(a[2]) - om = self.tmp() - self.emit(f"{om} = OpBitwiseAnd %uint {o} {self.cu(31)}") - if w_val is not None: - wm = self.cu(w_val & 31) - else: - w = self.src_u(a[3]) - wm = self.tmp() - self.emit(f"{wm} = OpBitwiseAnd %uint {w} {self.cu(31)}") - wc = self.bfe_width(om, wm) - x = self.src_u(a[1]) - r = self.tmp() - f = "OpBitFieldSExtract" if op.endswith("i32") else "OpBitFieldUExtract" - self.emit(f"{r} = {f} %uint {x} {om} {wc}") - self.dst(a[0], r) - elif op in ("v_mad_u64_u32", "v_mad_i64_i32"): - # {sdst, v[d:d+1]} = S0 * S1 + S2 as a 65-bit result (RDNA ISA pseudocode): 32 x 32 -> 64-bit product, - # unsigned or signed, plus the 64-bit S2. sdst (a lane mask) gets bit 64: the carry out for u64; for i64 - # the sign of the exact sum, which a 65-bit two's-complement value always holds. - if a[0].get("n") != 2 or "clamp" in mods: - raise Unsupported(op + " operands") - vd, sd, s0, s1, s2 = a[0], a[1], a[2], a[3], a[4] - signed = op == "v_mad_i64_i32" - if s2["k"] in ("vgpr", "sgpr") and s2.get("n") == 2: - c_lo, c_hi = self.load_reg(s2["k"], s2["r"]), self.load_reg(s2["k"], s2["r"] + 1) - elif s2["k"] == "imm": - v = s2["v"] & 0xFFFFFFFFFFFFFFFF # 64-bit inline/literal constant: sign-extended from 32 bits - c_lo, c_hi = self.cu(v & 0xFFFFFFFF), self.cu(v >> 32) - else: - raise Unsupported(op + " operands") - x, y = self.src_u(s0), self.src_u(s1) - pm, p_lo, p_hi = self.tmp(), self.tmp(), self.tmp() - if signed: - ph = self.tmp() - self.emit(f"{pm} = OpSMulExtended %smul {self.as_int(x)} {self.as_int(y)}") - pl = self.tmp() - self.emit(f"{pl} = OpCompositeExtract %int {pm} 0") - self.emit(f"{ph} = OpCompositeExtract %int {pm} 1") - self.emit(f"{p_lo} = OpBitcast %uint {pl}") - self.emit(f"{p_hi} = OpBitcast %uint {ph}") - self.uses_smul = True - else: - self.emit(f"{pm} = OpUMulExtended %umul {x} {y}") - self.emit(f"{p_lo} = OpCompositeExtract %uint {pm} 0") - self.emit(f"{p_hi} = OpCompositeExtract %uint {pm} 1") - s_lo, r_lo, c0, s_h1, h1, c1, s_h2, r_hi, c2 = (self.tmp() for _ in range(9)) - self.emit(f"{s_lo} = OpIAddCarry %umul {p_lo} {c_lo}") - self.emit(f"{r_lo} = OpCompositeExtract %uint {s_lo} 0") - self.emit(f"{c0} = OpCompositeExtract %uint {s_lo} 1") - self.emit(f"{s_h1} = OpIAddCarry %umul {p_hi} {c_hi}") - self.emit(f"{h1} = OpCompositeExtract %uint {s_h1} 0") - self.emit(f"{c1} = OpCompositeExtract %uint {s_h1} 1") - self.emit(f"{s_h2} = OpIAddCarry %umul {h1} {c0}") - self.emit(f"{r_hi} = OpCompositeExtract %uint {s_h2} 0") - self.emit(f"{c2} = OpCompositeExtract %uint {s_h2} 1") - if signed: - # Sign of the exact sum: the operands' common sign if they agree, else the wrapped sum's sign. - sp, sc, sr, same, neg = (self.tmp() for _ in range(5)) - self.emit(f"{sp} = OpShiftRightLogical %uint {p_hi} {self.cu(31)}") - self.emit(f"{sc} = OpShiftRightLogical %uint {c_hi} {self.cu(31)}") - self.emit(f"{sr} = OpShiftRightLogical %uint {r_hi} {self.cu(31)}") - self.emit(f"{same} = OpIEqual %bool {sp} {sc}") - self.emit(f"{neg} = OpSelect %uint {same} {sp} {sr}") - bit64 = neg - else: - bit64 = self.tmp() - self.emit(f"{bit64} = OpBitwiseOr %uint {c1} {c2}") - self.dst({"k": "vgpr", "r": vd["r"], "n": 1}, r_lo) - self.dst({"k": "vgpr", "r": vd["r"] + 1, "n": 1}, r_hi) - if not (sd["k"] == "special" and sd["t"] == "null"): - bm, m = self.tmp(), self.tmp() - self.emit(f"{bm} = OpLogicalAnd %bool {self.tmp_bool_nz(bit64)} {self.active_b()}") # inactive lanes write 0 - self.emit(f"{m} = OpSelect %uint {bm} {self.cu(0xFFFFFFFF)} {self.cu(0)}") - self.mask_dst(sd, m) - elif op in ("v_mad_u32_u16", "v_mad_i32_i16"): - # D = S0.half * S1.half + S2 (RDNA ISA pseudocode), wrapping at 32 bits: the 16-bit halves zero-extended - # (u16) or sign-extended (i16); op_sel bits 0 / 1 read the high half of S0 / S1. Measured on RDNA2 - # (gfx1036, raw kernels, wave32 and wave64, EGEN-HW-MAD-U32-U16) for the other bits: op_sel bit 2 adds - # S2[31:16] zero-extended, also in the i16 op (S2 = 0xffff8000 adds 0xffff); op_sel bit 3 writes the - # result shifted left by 16 (low half 0, the old D not kept); clamp saturates the sum to [0, 0xffffffff] - # (u16) or [0x80000000, 0x7fffffff] (i16), before that shift. - sel, dhi = self.opsel_bits(mods, 3) - signed = op == "v_mad_i32_i16" - ext = "OpBitFieldSExtract" if signed else "OpBitFieldUExtract" - hs = [] - for i, src in enumerate(a[1:3]): - h = self.tmp() - self.emit(f"{h} = {ext} %uint {self.src_u(src)} {self.cu(16 * sel[i])} {self.cu(16)}") - hs.append(h) - c = self.src_u(a[3]) - if sel[2]: - c2 = self.tmp() - self.emit(f"{c2} = OpShiftRightLogical %uint {c} {self.cu(16)}") - c = c2 - m, r = self.tmp(), self.tmp() - self.emit(f"{m} = OpIMul %uint {hs[0]} {hs[1]}") - self.emit(f"{r} = OpIAdd %uint {m} {c}") - if "clamp" in mods: - # Two 16-bit halves never overflow their 32-bit product, so only the addition can: unsigned when - # the sum is below the product, signed when product and addend share a sign the sum lacks. - ov, sat, rs = self.tmp(), self.tmp(), self.tmp() - if signed: - x1, x2, both, neg = self.tmp(), self.tmp(), self.tmp(), self.tmp() - self.emit(f"{x1} = OpBitwiseXor %uint {r} {m}") - self.emit(f"{x2} = OpBitwiseXor %uint {r} {c}") - self.emit(f"{both} = OpBitwiseAnd %uint {x1} {x2}") - self.emit(f"{ov} = OpSLessThan %bool {self.as_int(both)} {self.as_int(self.cu(0))}") - self.emit(f"{neg} = OpSLessThan %bool {self.as_int(c)} {self.as_int(self.cu(0))}") - self.emit(f"{sat} = OpSelect %uint {neg} {self.cu(0x80000000)} {self.cu(0x7FFFFFFF)}") - else: - self.emit(f"{ov} = OpULessThan %bool {r} {m}") - sat = self.cu(0xFFFFFFFF) - self.emit(f"{rs} = OpSelect %uint {ov} {sat} {r}") - r = rs - if dhi: - rd = self.tmp() - self.emit(f"{rd} = OpShiftLeftLogical %uint {r} {self.cu(16)}") - r = rd - self.dst(a[0], r) - elif op in ("v_dot4_i32_i8", "v_dot4c_i32_i8"): - # The four products of the signed bytes of two dwords, summed, plus an addend: the third source for - # v_dot4_i32_i8 (VOP3P), the destination's old value for v_dot4c_i32_i8 (VOP2). The sum wraps at 32 bits, - # or saturates to signed 32-bit [-2^31, 2^31-1] with clamp (VOP3P). - # Measured on RDNA2 hardware (docs/design.md, "Signed-byte dot products"): op_sel[k] picks the 16-bit half - # of source k (0=lo, 1=hi) for byte pairs 0..1, and op_sel_hi[k] picks the 16-bit half for byte pairs 2..3 - # (defaults op_sel=[0,0,0], op_sel_hi=[1,1,1]). S2 (addend) is 32-bit; non-default S2 half-select is refused. - # neg_lo/neg_hi are not ignored either: measured on v_dot4_i32_i8, they flip bit 15 and bit 31 of a - # source dword (and take the addend's absolute value, then negate it), as if the operands were floats. - # A set bit is refused; an all-zero field is the plain instruction. - def bits(name, default): - m = next((m for m in mods if m.startswith(name + ":")), None) - return [int(v) for v in m.split("[")[1].rstrip("]").split(",")] if m else default - is_vop3p = op == "v_dot4_i32_i8" - has_opsel = any(m.startswith("op_sel") for m in mods) - has_clamp = "clamp" in mods - if not is_vop3p and (has_opsel or has_clamp): - raise Unsupported(op + (" clamp" if has_clamp else " op_sel")) - if any(m.startswith(("neg_lo", "neg_hi")) and "1" in m.split(":", 1)[-1] for m in mods): - raise Unsupported(op + " neg") - sel = bits("op_sel", [0, 0, 0]) - selhi = bits("op_sel_hi", [1, 1, 1]) - if len(sel) != 3 or len(selhi) != 3 or sel[2] != 0 or selhi[2] != 1: - raise Unsupported(op + " op_sel") - x, y = self.src_u(a[1]), self.src_u(a[2]) - acc = self.src_u(a[3]) if is_vop3p else self.src_u(a[0]) - x_offs = (16 * sel[0], 16 * sel[0] + 8, 16 * selhi[0], 16 * selhi[0] + 8) - y_offs = (16 * sel[1], 16 * sel[1] + 8, 16 * selhi[1], 16 * selhi[1] + 8) - dot = None - for xo, yo in zip(x_offs, y_offs): - xb, yb, prod = self.tmp(), self.tmp(), self.tmp() - self.emit(f"{xb} = OpBitFieldSExtract %uint {x} {self.cu(xo)} {self.cu(8)}") - self.emit(f"{yb} = OpBitFieldSExtract %uint {y} {self.cu(yo)} {self.cu(8)}") - self.emit(f"{prod} = OpIMul %uint {xb} {yb}") - if dot is None: - dot = prod - else: - s = self.tmp() - self.emit(f"{s} = OpIAdd %uint {dot} {prod}") - dot = s - total = self.tmp() - self.emit(f"{total} = OpIAdd %uint {acc} {dot}") - if has_clamp: - # dot is in [-65024, 65536], so signed 32-bit overflow can only happen once in acc + dot: - # iff acc and dot share a sign bit and total has the opposite sign bit. - same_x, not_same, diff_sum, ov_bits, ov_sign, is_ov, acc_neg, sat, clamped = (self.tmp() for _ in range(9)) - self.emit(f"{same_x} = OpBitwiseXor %uint {acc} {dot}") - self.emit(f"{not_same} = OpNot %uint {same_x}") - self.emit(f"{diff_sum} = OpBitwiseXor %uint {acc} {total}") - self.emit(f"{ov_bits} = OpBitwiseAnd %uint {not_same} {diff_sum}") - self.emit(f"{ov_sign} = OpBitwiseAnd %uint {ov_bits} {self.cu(0x80000000)}") - self.emit(f"{is_ov} = OpINotEqual %bool {ov_sign} {self.cu(0)}") - self.emit(f"{acc_neg} = OpSLessThan %bool {acc} {self.cu(0)}") - self.emit(f"{sat} = OpSelect %uint {acc_neg} {self.cu(0x80000000)} {self.cu(0x7FFFFFFF)}") - self.emit(f"{clamped} = OpSelect %uint {is_ov} {sat} {total}") - total = clamped - self.dst(a[0], total) - elif op == "v_mad_u32_u24": - x, y, z = (self.src_u(t) for t in a[1:4]) - xm, ym, p, r = self.tmp(), self.tmp(), self.tmp(), self.tmp() - self.emit(f"{xm} = OpBitwiseAnd %uint {x} {self.cu(0xFFFFFF)}") - self.emit(f"{ym} = OpBitwiseAnd %uint {y} {self.cu(0xFFFFFF)}") - self.emit(f"{p} = OpIMul %uint {xm} {ym}") - self.emit(f"{r} = OpIAdd %uint {p} {z}") - self.dst(a[0], r) - elif op == "v_cndmask_b32": - # e32: dst, src0, src1 (vcc) ; e64: dst, src0, src1, sN[:N+1]/vcc. A bit move: the e64 abs/neg source - # modifiers are sign-bit moves, never float ops (see src_u_sign_mods). - x, y = self.src_u_sign_mods(a[1]), self.src_u_sign_mods(a[2]) - c = self.mask_src(a[3]) if len(a) > 3 else self.mask_src({"k": "special", "t": "vcc"}) - b, r = self.tmp(), self.tmp() - self.emit(f"{b} = OpINotEqual %bool {c} {self.cu(0)}") - self.emit(f"{r} = OpSelect %uint {b} {y} {x}") - self.dst(a[0], r) - elif op == "exp": - self.export(ins) - else: - raise Unsupported(op) - - def scalar_load(self, op, a, mods): - """s_load_dwordxN sD, s[p:p+1], off -> N dwords from a 64-bit pointer, no bound - s_buffer_load_dwordxN sD, s[v:v+3], off -> N dwords from a V#, each checked against NUM_RECORDS - Both become PhysicalStorageBuffer loads (Vulkan buffer device address). V# base = dword0 | (dword1 & 0xFFFF) << 32 - (AMD RDNA ISA, buffer resource descriptor). - off is an immediate or a scalar register. An SMEM load can carry both, which llvm-mc prints as - "sOFF offset:IMM" (the immediate arrives in mods); both are added. - Measured on an AMD Radeon RX 6800 (gfx1030) as a raw compute kernel, wave32 and wave64 (docs/design.md, - Scalar/buffer memory): - off = (sOFF & ~3) + (IMM & ~3); dword i is read at (base & ~3) + off + 4*i (base, sOFF, IMM truncated - each on its own, then added). - s_buffer_load*: dword i is 0, and memory is not read, when off + 4*i + 4 > limit, limit = NUM_RECORDS * - stride bytes when the V# stride (dword1[29:16]) is not 0, else NUM_RECORDS bytes (V# dword2). The bound - is per dword and does not see base & 3; IMM is unsigned. - s_load*: IMM is sign-extended from 21 bits and the sum is formed in 64 bits; no bound. - Measured on gfx1036 (RDNA2): x16 is bounded per dword like x8, NUM_RECORDS * stride is 64-bit (2^32 does not - wrap to 0), NUM_RECORDS >= 2^31 is unsigned, and an s_load with sOFF + IMM < 0 reads at the 64-bit signed sum. - An s_buffer_load immediate with bit 20 set does not follow the bound on hardware and is not modelled (kept as - the 32-bit value, as before).""" - n = 1 if op.endswith("dword") else int(op.rsplit("x", 1)[1]) - d, base = a[0], a[1] - # A single dword may also land in vcc_lo / m0 / vcc_hi (seen: s_buffer_load_dword vcc_lo, ...), and a wide - # load may target an LLVM VCCTuple list ending in vcc_lo,vcc_hi (seen in 6 FSPX shaders: s[100..105]+vcc). - single_special = (n == 1 and d["k"] == "special" and d["t"] in ("vcc_lo", "vcc", "m0", "vcc_hi")) or \ - (n == 2 and d["k"] == "special" and d["t"] == "vcc") - slist_dst = d["k"] == "slist" and len(d["r"]) == n - base_slots = (list(range(base["r"], base["r"] + base.get("n", 1))) if base["k"] == "sgpr" - else list(base["r"]) if base["k"] == "slist" else None) - if (d["k"] != "sgpr" and not single_special and not slist_dst) or base_slots is None: - raise Unsupported(f"{op} operands {d.get('t', d['k'])} {base.get('t', base['k'])}") - - def load_slot(slot): - if isinstance(slot, int): - return self.load_reg("sgpr", slot) - t = self.tmp() - self.emit(f"{t} = OpLoad %uint {'%vcc' if slot == 'vcc_lo' else '%vcc_hi'}") - return t - - def store_slot(slot, val): - if isinstance(slot, int): - self.store_reg("sgpr", slot, val) - else: - self.emit(f"OpStore {'%vcc' if slot == 'vcc_lo' else '%vcc_hi'} {val}") - - sbuf = op.startswith("s_buffer") - if sbuf: - if len(base_slots) != 4: - raise Unsupported("s_buffer_load without V#") - else: - if len(base_slots) != 2: - raise Unsupported("s_load without 64-bit pointer") - lo, hi = load_slot(base_slots[0]), load_slot(base_slots[1]) - word1 = hi - if sbuf: - m = self.tmp() - self.emit(f"{m} = OpBitwiseAnd %uint {hi} {self.cu(0xFFFF)}") - hi = m - off = a[2] if len(a) > 2 else {"k": "imm", "v": 0} - inst = [m.split(":", 1)[1] for m in mods if m.startswith("offset:")] - if len(a) > 3 or len(inst) > 1 or (inst and off["k"] == "imm"): - raise Unsupported(f"{op} offset form") # not something llvm-mc prints: don't guess an address - imm = 0 - if inst: - try: - imm = int(inst[0], 0) - except ValueError: - raise Unsupported(f"{op} offset:{inst[0]}") from None - reg = None - const_off = None - off_val = self.imm_val(off) - if off["k"] == "imm": - imm = off["v"] # immediate-only form - elif off_val is not None: - const_off = off_val & 0xFFFFFFFC # an SGPR offset the translator knows: added below - else: - reg = self.src_u(off) - if sbuf: - imm &= 0xFFFFFFFF # unsigned (measured up to 0xffffc) - else: - imm = ((imm & 0x1FFFFF) ^ 0x100000) - 0x100000 # 21-bit signed - imm &= ~3 # two's complement: -1 -> -4, -6 -> -8 - if const_off is not None: - # The same sum as the run-time path below, zext(sOFF & ~3) + imm, kept as a Python int: no 32-bit wrap. - # Until 2026-11-22 (#1686) the constant was added before the 32-bit truncation, so s8 = -4 with - # offset:20 read byte 16 instead of being out of range (hardware: 0xFFFFFFFC + 20 reads 0, measured by - # @Pierre-Kookis on gfx1036; found by @Impre-visible). The address and the s_buffer_load bound use it. - imm = const_off + imm - # Byte offset from the 4-truncated base, in 64 bits: zext(sOFF & ~3) + imm, or the constant alone. - if reg is not None: - r4, r64 = self.tmp(), self.tmp() - self.emit(f"{r4} = OpBitwiseAnd %uint {reg} {self.cu(0xFFFFFFFC)}") - self.emit(f"{r64} = OpUConvert %ulong {r4}") - if imm: - o64 = self.tmp() - self.emit(f"{o64} = OpIAdd %ulong {r64} {self.cl(imm)}") - else: - o64 = r64 - else: - o64 = self.cl(imm) - lo4, l64, h64, sh, addr, full = (self.tmp() for _ in range(6)) - self.emit(f"{lo4} = OpBitwiseAnd %uint {lo} {self.cu(0xFFFFFFFC)}") - self.emit(f"{l64} = OpUConvert %ulong {lo4}") - self.emit(f"{h64} = OpUConvert %ulong {hi}") - self.emit(f"{sh} = OpShiftLeftLogical %ulong {h64} %c64_32") - self.emit(f"{addr} = OpBitwiseOr %ulong {sh} {l64}") - self.emit(f"{full} = OpIAdd %ulong {addr} {o64}") - ptr = self.tmp() - self.emit(f"{ptr} = OpConvertUToPtr %_ptr_PSB_arr {self.host_addr(full)}") - self.uses_psb = True - lim = None - lim_val = None - if sbuf: - # limit = NUM_RECORDS * stride, or NUM_RECORDS when stride is 0 (bytes, 64-bit so the product can't wrap) - lit1 = self.sgpr_imm.get(base_slots[1]) if isinstance(base_slots[1], int) else None - lit2 = self.sgpr_imm.get(base_slots[2]) if isinstance(base_slots[2], int) else None - if lit1 is not None and lit2 is not None: - stride = (lit1 >> 16) & 0x3FFF - lim_val = lit2 if stride == 0 else lit2 * stride - lim = self.cl(lim_val) - else: - stride, nr64, st64, prod, raw, lim = (self.tmp() for _ in range(6)) - nr = load_slot(base_slots[2]) - self.emit(f"{stride} = OpBitFieldUExtract %uint {word1} {self.cu(16)} {self.cu(14)}") - self.emit(f"{nr64} = OpUConvert %ulong {nr}") - self.emit(f"{st64} = OpUConvert %ulong {stride}") - self.emit(f"{prod} = OpIMul %ulong {nr64} {st64}") - self.emit(f"{raw} = OpIEqual %bool {stride} {self.cu(0)}") - self.emit(f"{lim} = OpSelect %ulong {raw} {nr64} {prod}") - guarded = {} - if lim is not None and not (lim_val is not None and reg is None): - # A run-time bound: dword i is in range when off + 4*i + 4 <= limit, and out of range it is 0 with memory - # not read. The ends grow with i, so "dword i in range" implies every dword before it is: one selection - # on dword 0 covers the load. Inside it each dword reads at index i when in range, else at index 0 (in - # range there, so nothing outside the buffer is touched), and the out-of-range ones are then 0. Before, - # each dword had its own selection: 2N blocks per s_buffer_load_dwordxN, 11,000 of the 17,000 blocks of - # the cascade-shadow CS whose pipeline NVIDIA's compiler could not build in 16 GB. - oks = [] - for i in range(n): - end, ok = self.tmp(), self.tmp() - if reg is not None: - self.emit(f"{end} = OpIAdd %ulong {o64} {self.cl(4 * i + 4)}") - else: - end = self.cl(imm + 4 * i + 4) - self.emit(f"{ok} = OpUGreaterThanEqual %bool {lim} {end}") - oks.append(ok) - lbl_do, lbl_end = self.tmp() + "_do", self.tmp() + "_end" - pre = self.current_label_placeholder() - self.emit(f"OpSelectionMerge {lbl_end} None") - self.emit(f"OpBranchConditional {oks[0]} {lbl_do} {lbl_end}") - self.emit(f"{lbl_do} = OpLabel") - got_in = [] - for i in range(n): - idx, p, got, val = (self.tmp() for _ in range(4)) - if i == 0: - idx = self.cu(0) - else: - self.emit(f"{idx} = OpSelect %uint {oks[i]} {self.cu(i)} {self.cu(0)}") - self.emit(f"{p} = OpAccessChain %_ptr_PSB_uint {ptr} {idx}") - self.emit(f"{got} = OpLoad %uint {p} Aligned 4") - if i == 0: - val = got - else: - self.emit(f"{val} = OpSelect %uint {oks[i]} {got} {self.cu(0)}") - got_in.append(val) - self.emit(f"OpBranch {lbl_end}") - self.emit(f"{lbl_end} = OpLabel") - for i in range(n): - v = self.tmp() - self.emit(f"{v} = OpPhi %uint {got_in[i]} {lbl_do} {self.cu(0)} {pre}") - guarded[i] = v - for i in range(n): - p, v = self.tmp(), self.tmp() - if i in guarded: - v = guarded[i] - elif lim is None: - self.emit(f"{p} = OpAccessChain %_ptr_PSB_uint {ptr} {self.cu(i)}") - self.emit(f"{v} = OpLoad %uint {p} Aligned 4") - else: # a bound known at translate time (lim_val, constant offset): fold each dword - end_val = imm + 4 * i + 4 - if lim_val >= end_val: - self.emit(f"{p} = OpAccessChain %_ptr_PSB_uint {ptr} {self.cu(i)}") - self.emit(f"{v} = OpLoad %uint {p} Aligned 4") - else: - v = self.cu(0) - if single_special: - if n == 2: # vcc pair: low dword -> vcc_lo, high dword -> vcc_hi (data, not a lane mask) - self.emit(f"OpStore {'%vcc' if i == 0 else '%vcc_hi'} {v}") - else: - self.dst(d, v) - elif slist_dst: - store_slot(d["r"][i], v) - else: - self.store_reg("sgpr", d["r"] + i, v) - - # ---- images: T#/S# -> bindless index through a runtime-filled hash table ---- - # Table layout (storage buffer, set 0 binding 2): uint mask; then entries of 10 uints: - # key[0..7] (descriptor dwords; S# uses key[0..3] and key[4..7] = 0xFFFFFFFF), index, pad. - # Probes 8 slots from hash(key) & mask; a miss yields index 0 (the runtime puts a fallback there). - PROBES = 8 - - def desc_lookup(self, words): - """words: 8 uint ids. Returns a uint id with the bindless index. - - The probe is about 400 instructions, so it is one function in the module (%desc_lookup_fn) that every - image instruction calls. Inlined at each use it was most of the code of texture-heavy shaders: 194 image - instructions made over half of a 7 MB module.""" - self.uses_tex = True - if self.desc_fn is None: - params = [f"%dl_w{i}" for i in range(8)] - saved, self.body = self.body, [] - result = self.desc_probe(params) - lines, self.body = self.body, saved - self.desc_fn = (["%desc_lookup_fn = OpFunction %uint None %fn_desc_lookup"] + - [f"{p} = OpFunctionParameter %uint" for p in params] + ["%dl_entry = OpLabel"] + - lines + [f" OpReturnValue {result}", "OpFunctionEnd"]) - r = self.tmp() - self.emit(f"{r} = OpFunctionCall %uint %desc_lookup_fn " + " ".join(words)) - if self.emulate: - return r - if self.wave32_fragment: - # Each 32-lane half of a wider subgroup is its own wave with its own SGPRs: broadcast from the half's - # first running lane, as OpGroupNonUniformBroadcastFirst does for the whole subgroup below. - b = self.tmp() - self.g_shuffle(b, r, self.wave32_first_running_lane()) - return b - # The descriptor words are SGPRs, so the index is the same in every invocation of the subgroup; the - # broadcast is an identity on every driver and makes that uniformity explicit to the compiler. Mesa ANV - # (26.2.7, Alder Lake Xe-LP) segfaults compiling a sampler index straight from the probe loop when one - # sampler serves both a float and integer image; the broadcast avoids it. The wave64 emulation keeps no - # subgroup operation (x_round), so it is left out there. Track this separately from uses_subgroup: this - # operation needs GroupNonUniform + GroupNonUniformBallot, but no Shuffle capability or lane input. - b = self.tmp() - self.emit(f"{b} = OpGroupNonUniformBroadcastFirst %uint {self.cu(3)} {r}") - self.uses_bcast_first = True - return b - - def desc_probe(self, words): - """The lookup itself: FNV-1a of the 8 dwords, then PROBES slots compared in turn.""" - h = self.cu(2166136261) - for w in words: # FNV-1a over the 8 dwords - x, m = self.tmp(), self.tmp() - self.emit(f"{x} = OpBitwiseXor %uint {h} {w}") - self.emit(f"{m} = OpIMul %uint {x} {self.cu(16777619)}") - h = m - mp, mask = self.tmp(), self.tmp() - self.emit(f"{mp} = OpAccessChain %_ptr_SB_uint %desc_map %c0 %c0") - self.emit(f"{mask} = OpLoad %uint {mp}") - # One slot per turn of a loop that stops at the first match, not PROBES copies of the comparison. A shader - # compiler inlines this function at every use, and the unrolled copies were 95% of its work on a shader - # with 330 lookups (117 s to compile with 8 slots unrolled, 14 s with one, 6 s with none). Break directly - # to %dl_end on a hit with DontUnroll: overwriting %dl_k to fall out of a single-exit loop leaves %dl_idx - # on the loop header's phi, which Mesa ANV 26.1.6 (Intel UHD 630, CFL GT2) miscompiles in ps_table_fetch - # by hoisting the binding-table-index add above the loop (reading slot 0 / magenta before %dl_idx is set). - kv, iv = "%dl_k", "%dl_idx" # slot number, and the result (0 until a slot matches) - self.body[0:0] = [f" {kv} = OpVariable %_ptr_Function_uint Function %c0", - f" {iv} = OpVariable %_ptr_Function_uint Function %c0"] - self.emit("OpBranch %dl_head") - self.body.append("%dl_head = OpLabel") - self.emit("OpLoopMerge %dl_end %dl_cont DontUnroll") - self.emit("OpBranch %dl_body") - self.body.append("%dl_body = OpLabel") - k, s, slot, base = self.tmp(), self.tmp(), self.tmp(), self.tmp() - self.emit(f"{k} = OpLoad %uint {kv}") - self.emit(f"{s} = OpIAdd %uint {h} {k}") - self.emit(f"{slot} = OpBitwiseAnd %uint {s} {mask}") - self.emit(f"{base} = OpIMul %uint {slot} {self.cu(10)}") - match = "%true" - for j, w in enumerate(words): - o, p, v, e, m2 = self.tmp(), self.tmp(), self.tmp(), self.tmp(), self.tmp() - self.emit(f"{o} = OpIAdd %uint {base} {self.cu(1 + j)}") - self.emit(f"{p} = OpAccessChain %_ptr_SB_uint %desc_map %c0 {o}") - self.emit(f"{v} = OpLoad %uint {p}") - self.emit(f"{e} = OpIEqual %bool {v} {w}") - self.emit(f"{m2} = OpLogicalAnd %bool {match} {e}") - match = m2 - self.emit("OpSelectionMerge %dl_next None") - self.emit(f"OpBranchConditional {match} %dl_hit %dl_next") - self.body.append("%dl_hit = OpLabel") - o, p, v = self.tmp(), self.tmp(), self.tmp() - self.emit(f"{o} = OpIAdd %uint {base} {self.cu(9)}") - self.emit(f"{p} = OpAccessChain %_ptr_SB_uint %desc_map %c0 {o}") - self.emit(f"{v} = OpLoad %uint {p}") - self.emit(f"OpStore {iv} {v}") - self.emit("OpBranch %dl_end") # the first match breaks out of the probe loop directly - self.body.append("%dl_next = OpLabel") - self.emit("OpBranch %dl_cont") - self.body.append("%dl_cont = OpLabel") - k2, k3, more, r = self.tmp(), self.tmp(), self.tmp(), self.tmp() - self.emit(f"{k2} = OpLoad %uint {kv}") - self.emit(f"{k3} = OpIAdd %uint {k2} {self.cu(1)}") - self.emit(f"OpStore {kv} {k3}") - self.emit(f"{more} = OpULessThan %bool {k3} {self.cu(self.PROBES)}") - self.emit(f"OpBranchConditional {more} %dl_head %dl_end") - self.body.append("%dl_end = OpLabel") - self.emit(f"{r} = OpLoad %uint {iv}") - return r - - def desc_cache_ok(self): - """True when the next instruction is emitted at the top level of the basic block, outside any selection or - loop construct an earlier instruction opened and has not yet reached the merge label of. An id defined - there dominates everything after it in the block. One defined inside a construct would not dominate the - code after the merge, so lookups made there are not cached. The body is append-only within a block, so - this only reads the lines added since the last call.""" - body, seen, open_ = self._scan - if body is not self.body: - body, seen, open_ = self.body, 0, [] - for line in body[seen:]: - s = line.strip() - if s.startswith(("OpSelectionMerge ", "OpLoopMerge ")): - open_.append(s.split()[1]) - elif s.endswith("= OpLabel"): - name = s.split()[0] - if name in open_: - del open_[open_.index(name):] - self._scan = (body, len(body), open_) - return not open_ - - def mimg_status(self, op: str, a: list, mods: list[str]) -> None: - """MIMG tfe: the fetch status is one more dword after the data, at vdata[data_count] (SHADER-1266). - data_count is 4 for a gather and the dmask bit count otherwise, halved (rounded up) under d16; llvm-mc sizes - vdata from dmask, d16 and tfe, so lwe alone adds no register. A Vulkan image is always resident, so the - status is 0. Stores and atomics return no status.""" - if "tfe" not in mods or not a or a[0].get("k") != "vgpr" or op.startswith(("image_store", "image_atomic")): - return - if op.startswith("image_gather4"): - count = 4 - else: - dm = next((m for m in mods if m.startswith("dmask:")), "dmask:0x1") - count = bin(int(dm.split(":")[1], 0) & 0xF).count("1") or 1 - if "d16" in mods: - count = (count + 1) // 2 - self.dst({"k": "vgpr", "r": a[0]["r"] + count, "n": 1}, self.cu(0)) - - def store_gather_taps(self, first_vgpr: int, taps: list[str], d16: bool) -> None: - """Write four taps in gather order, two per destination VGPR for d16.""" - if d16: - words = [self.pack_f16_pair_int(taps[0], taps[1]), self.pack_f16_pair_int(taps[2], taps[3])] - else: - words = [self.tou(tap) for tap in taps] - for i, word in enumerate(words): - self.dst({"k": "vgpr", "r": first_vgpr + i, "n": 1}, word) - - GATHER4_LOD_OPS = ( - "image_gather4_c_l", "image_gather4_c_l_o", - "image_gather4_cl", "image_gather4_cl_o", - "image_gather4_c_cl", "image_gather4_c_cl_o", - "image_gather4_b", "image_gather4_b_o", - "image_gather4_b_cl", "image_gather4_b_cl_o", - "image_gather4_c_b", "image_gather4_c_b_o", - "image_gather4_c_b_cl", "image_gather4_c_b_cl_o", - ) - - # SQ_IMG_SAMP_WORD0 address modes (Mesa src/amd/registers/gfx10-rsrc.json: CLAMP_X = bits [2:0], CLAMP_Y = [5:3]; - # values: SQ_TEX_* in Mesa's gfx6.json, as RADV's radv_tex_wrap maps VkSamplerAddressMode onto them): 0 wrap, 1 mirror, 2 clamp last texel, 3 mirror once last texel, - # 4 clamp half border, 5 mirror once half border, 6 clamp border, 7 mirror once border. - def gather_addr_modes(self, s_op, unorm: bool = False): - """(x, y) address modes of an S# for the gather emulation, each either a Python int (the S# word 0 is a - literal an s_mov_b32 wrote earlier in this basic block) or the id of a uint computed from the S# at run time. - - Modes 6 (clamp border) and 7 (mirror once border) map a tap outside the image to the border colour (see - gather_border); a literal S# with a half-border mode (4, 5), or that sets FORCE_UNNORMALIZED, is Unsupported: - the four fetches can't reproduce it. A run-time S# can't be judged at translation time, so modes 4 and 5 are - treated as clamp-to-edge there, and FORCE_UNNORMALIZED (bit 15) is not applied (the two remaining - approximations, with gather_border_one's table colour at run time).""" - if s_op["k"] != "sgpr" or s_op.get("n", 1) < 4: - raise Unsupported("descriptor operand") - lit = self.sgpr_imm.get(s_op["r"]) - if lit is not None: - if not unorm and (lit & 0x8000): - raise Unsupported("image_gather4_l with FORCE_UNNORMALIZED") - m = (lit & 7, lit >> 3 & 7) - for mode in m: - if mode in (4, 5): - raise Unsupported(f"image_gather4_l address mode {mode} (half border)") - return m - w0 = self.load_reg("sgpr", s_op["r"]) - out = [] - for k in range(2): - m = self.tmp() - self.emit(f"{m} = OpBitFieldUExtract %uint {w0} {self.cu(3 * k)} {self.cu(3)}") - out.append(m) - return tuple(out) - - def gather_border_one(self, s_op, ch: int): - """Whether channel ch of the S#'s border colour is 1 (else 0), for a tap that a border mode (6, 7) puts - outside the image: a Python bool for a literal S# word 3, else a bool id. BORDER_COLOR_TYPE is word 3 [31:30] - (Mesa gfx10-rsrc.json SQ_IMG_SAMP_WORD3; SQ_TEX_BORDER_COLOR_* in gfx6.json): 0 transparent black (0,0,0,0), - 1 opaque black (0,0,0,1), 2 opaque white (1,1,1,1), 3 a colour from the border-colour table (BORDER_COLOR_PTR), - which the translator can't read: Unsupported on a literal S#, transparent black at run time.""" - lit = self.sgpr_imm.get(s_op["r"] + 3) - if lit is not None: - kind = lit >> 30 & 3 - if kind == 3: - raise Unsupported("image_gather4_l border colour from the table (BORDER_COLOR_TYPE 3)") - return kind == 2 or (kind == 1 and ch == 3) - kind, white = self.tmp(), self.tmp() - self.emit(f"{kind} = OpShiftRightLogical %uint {self.load_reg('sgpr', s_op['r'] + 3)} {self.cu(30)}") - self.emit(f"{white} = OpIEqual %bool {kind} {self.cu(2)}") - if ch != 3: - return white - black, one = self.tmp(), self.tmp() - self.emit(f"{black} = OpIEqual %bool {kind} {self.cu(1)}") - self.emit(f"{one} = OpLogicalOr %bool {white} {black}") - return one - - def clamp_gather_lod(self, lod: str, word_reg: int) -> str: - """Clamp to S# word 1's unsigned 4.8 MIN_LOD and MAX_LOD before choosing the fetch mip. - - A literal S# uses FClamp. A run-time S# clamps with FMax then FMin: LLPC 26.10.1 (32.0.32015.7029) - miscompiles the run-time FClamp here and leaves the gather at mip 0 when MIN_LOD should raise it (#1032). - The two-instruction form is the FClamp result for min <= max and passes on that driver.""" - literal = self.sgpr_imm.get(word_reg) - if literal is not None: - limits = [self.fconst(((literal >> bit) & 0xfff) / 256.0) for bit in (0, 12)] - clamped = self.tmp() - self.emit(f"{clamped} = OpExtInst %float %glsl FClamp {lod} {limits[0]} {limits[1]}") - return clamped - word = self.load_reg("sgpr", word_reg) - scale = self.fconst(1.0 / 256.0) - limits = [] - for bit in (0, 12): - raw, value, scaled = self.tmp(), self.tmp(), self.tmp() - self.emit(f"{raw} = OpBitFieldUExtract %uint {word} {self.cu(bit)} {self.cu(12)}") - self.emit(f"{value} = OpConvertUToF %float {raw}") - self.emit(f"{scaled} = OpFMul %float {value} {scale}") - limits.append(scaled) - lower = self.tmp() - self.emit(f"{lower} = OpExtInst %float %glsl FMax {lod} {limits[0]}") - clamped = self.tmp() - self.emit(f"{clamped} = OpExtInst %float %glsl FMin {lower} {limits[1]}") - return clamped - - def gather_addr(self, c, n, mode): - """Texel coordinate c (int id) after the address mode (int, or a uint id) for an axis of n texels (int id): - wrap: c mod n; mirror: c mod 2n, reflected in the upper half; mirror once: the negative side reflected - (-1 - c), then clamped; otherwise (clamp, and half-border modes at run time) clamped to [0, n-1]. As in the - Vulkan address-mode definitions (and RADV's radv_tex_wrap mapping of them onto SQ_TEX_*). A literal mode - emits only the code it needs; a run-time one emits all four and selects. - Returns (coordinate, outside): outside is a bool id that is true when a border mode (6 clamp border, 7 mirror - once border) puts the tap outside [0, n-1] before the clamp, so it takes the border colour, or None when the - literal mode has no border. - The modulo is OpSRem plus the period when the remainder is negative, not OpSMod: AMD's Windows driver - (24.10.24, RDNA2 iGPU) gave OpSMod of a negative coordinate the dividend's sign, so ps_gather_wrap's wrap and - mirror cases fetched outside the image and read zeros. The two are the same for a positive period.""" - zero, one = self.as_int(self.cu(0)), self.as_int(self.cu(1)) - static = isinstance(mode, int) - base = {6: 2, 7: 3}.get(mode, mode if mode <= 3 else 2) if static else None - want = {base} if static else {0, 1, 2, 3} - nm1 = self.tmp() - self.emit(f"{nm1} = OpISub %int {n} {one}") - pre = {} # the coordinate a border test sees: before the clamp - - def modulo(x, m): - """x mod m for m > 0, in [0, m).""" - r, neg, up, out = (self.tmp() for _ in range(4)) - self.emit(f"{r} = OpSRem %int {x} {m}") - self.emit(f"{neg} = OpSLessThan %bool {r} {zero}") - self.emit(f"{up} = OpIAdd %int {r} {m}") - self.emit(f"{out} = OpSelect %int {neg} {up} {r}") - return out - res = {} - if 2 in want: - res[2] = self.tmp() - self.emit(f"{res[2]} = OpExtInst %int %glsl SClamp {c} {zero} {nm1}") - if 0 in want: - res[0] = modulo(c, n) - if 1 in want: - n2, hi, rf, lt, res[1] = (self.tmp() for _ in range(5)) - self.emit(f"{n2} = OpIAdd %int {n} {n}") - p = modulo(c, n2) - self.emit(f"{hi} = OpISub %int {n2} {one}") - self.emit(f"{rf} = OpISub %int {hi} {p}") - self.emit(f"{lt} = OpSLessThan %bool {p} {n}") - self.emit(f"{res[1]} = OpSelect %int {lt} {p} {rf}") - if 3 in want: - neg, refl, ge, mo, res[3] = (self.tmp() for _ in range(5)) - self.emit(f"{neg} = OpISub %int {zero} {c}") - self.emit(f"{refl} = OpISub %int {neg} {one}") - self.emit(f"{ge} = OpSGreaterThanEqual %bool {c} {zero}") - self.emit(f"{mo} = OpSelect %int {ge} {c} {refl}") - self.emit(f"{res[3]} = OpExtInst %int %glsl SClamp {mo} {zero} {nm1}") - pre[3] = mo - pre[2] = c - - def outside(v): - lo, hi, out = self.tmp(), self.tmp(), self.tmp() - self.emit(f"{lo} = OpSLessThan %bool {v} {zero}") - self.emit(f"{hi} = OpSGreaterThan %bool {v} {nm1}") - self.emit(f"{out} = OpLogicalOr %bool {lo} {hi}") - return out - - if static: - return res[base], (outside(pre[base]) if mode in (6, 7) else None) - r = res[2] - for val in (3, 1, 0): - eq, nr = self.tmp(), self.tmp() - self.emit(f"{eq} = OpIEqual %bool {mode} {self.cu(val)}") - self.emit(f"{nr} = OpSelect %int {eq} {res[val]} {r}") - r = nr - # Mode 7 is mirror once in range; modes 6 and 7 send a tap outside the image to the border colour. - eq7, r7 = self.tmp(), self.tmp() - self.emit(f"{eq7} = OpIEqual %bool {mode} {self.cu(7)}") - self.emit(f"{r7} = OpSelect %int {eq7} {res[3]} {r}") - is6, b6, b7, out = (self.tmp() for _ in range(4)) - o6, o7 = outside(pre[2]), outside(pre[3]) - self.emit(f"{is6} = OpIEqual %bool {mode} {self.cu(6)}") - self.emit(f"{b6} = OpLogicalAnd %bool {is6} {o6}") - self.emit(f"{b7} = OpLogicalAnd %bool {eq7} {o7}") - self.emit(f"{out} = OpLogicalOr %bool {b6} {b7}") - return r7, out - - # SQ_IMG_SAMP_WORD0 DEPTH_COMPARE_FUNC [14:12] (SQ_TEX_DEPTH_COMPARE, same numbering as VkCompareOp): - # 0 NEVER, 1 LESS, 2 EQUAL, 3 LESS_EQUAL, 4 GREATER, 5 NOT_EQUAL, 6 GREATER_EQUAL, 7 ALWAYS. - _DEPTH_CMP_OPS = { - 1: "OpFOrdLessThan", - 2: "OpFOrdEqual", - 3: "OpFOrdLessThanEqual", - 4: "OpFOrdGreaterThan", - 5: "OpFUnordNotEqual", - 6: "OpFOrdGreaterThanEqual", - } - - def gather_depth_compare_prep(self, s_op): - """Decode S# word 0 DEPTH_COMPARE_FUNC [14:12] once per depth-compare gather4. - Returns ('const', func) for a literal S#, or ('dyn', b0, b1, b2, b02) for a run-time S#.""" - lit = self.sgpr_imm.get(s_op["r"]) if s_op["k"] == "sgpr" else None - if lit is not None: - return ("const", (lit >> 12) & 7) - w0 = self.sgpr_word(s_op, 0) - fn = self.tmp() - self.emit(f"{fn} = OpBitFieldUExtract %uint {w0} {self.cu(12)} {self.cu(3)}") - bits = [] - for mask in (1, 2, 4): - bu, bb = self.tmp(), self.tmp() - self.emit(f"{bu} = OpBitwiseAnd %uint {fn} {self.cu(mask)}") - self.emit(f"{bb} = OpINotEqual %bool {bu} {self.cu(0)}") - bits.append(bb) - b02 = self.tmp() - self.emit(f"{b02} = OpLogicalAnd %bool {bits[0]} {bits[2]}") - return ("dyn", bits[0], bits[1], bits[2], b02) - - def gather_depth_compare(self, cmp_state, ref: str, texel: str) -> str: - """Compare ref texel and return %float (%f1 if pass, else %f0).""" - if cmp_state[0] == "const": - func = cmp_state[1] - if func == 0: - return "%f0" - if func == 7: - return "%f1" - c, res = self.tmp(), self.tmp() - self.emit(f"{c} = {self._DEPTH_CMP_OPS[func]} %bool {ref} {texel}") - self.emit(f"{res} = OpSelect %float {c} %f1 %f0") - return res - _, b0, b1, b2, b02 = cmp_state - lt, eq, gt = self.tmp(), self.tmp(), self.tmp() - self.emit(f"{lt} = OpFOrdLessThan %bool {ref} {texel}") - self.emit(f"{eq} = OpFOrdEqual %bool {ref} {texel}") - self.emit(f"{gt} = OpFOrdGreaterThan %bool {ref} {texel}") - lt_m, eq_m, gt_m = self.tmp(), self.tmp(), self.tmp() - self.emit(f"{lt_m} = OpLogicalAnd %bool {b0} {lt}") - self.emit(f"{eq_m} = OpLogicalAnd %bool {b1} {eq}") - self.emit(f"{gt_m} = OpLogicalAnd %bool {b2} {gt}") - ord1, any_ord, unord, unord_m = (self.tmp() for _ in range(4)) - self.emit(f"{ord1} = OpLogicalOr %bool {lt} {eq}") - self.emit(f"{any_ord} = OpLogicalOr %bool {ord1} {gt}") - self.emit(f"{unord} = OpLogicalNot %bool {any_ord}") - self.emit(f"{unord_m} = OpLogicalAnd %bool {b02} {unord}") - m1, m2, passed, res = (self.tmp() for _ in range(4)) - self.emit(f"{m1} = OpLogicalOr %bool {lt_m} {eq_m}") - self.emit(f"{m2} = OpLogicalOr %bool {gt_m} {unord_m}") - self.emit(f"{passed} = OpLogicalOr %bool {m1} {m2}") - self.emit(f"{res} = OpSelect %float {passed} %f1 %f0") - return res - - def emit_gather4_lod(self, op, a, mods, dim, img, img_idx, si, coords, f, ncoord, is3d, dmask, vdata, a16, d16): - """Translate image_gather4_{c_l,cl,c_cl,b,b_cl,c_b,c_b_cl}[_o] via 2x2 OpImageFetch footprint. - Address order: [offset (_o)], [bias (_b)], [z_compare (_c)], s, t, [slice (2D_ARRAY)], [lod (_l) | clamp (_cl)].""" - kind = op[len("image_gather4"):] - goff = None - if kind.endswith("_o"): - if a16 and ("tfe" in mods or "lwe" in mods): - raise Unsupported(op + " a16 status") - parts = [] - for k in range(2): - u, i = self.tmp(), self.tmp() - self.emit(f"{u} = OpBitFieldSExtract %uint {coords[0]} {self.cu(8 * k)} {self.cu(6)}") - self.emit(f"{i} = OpBitcast %int {u}") - parts.append(i) - goff = self.tmp() - self.emit(f"{goff} = OpCompositeConstruct %v2int {parts[0]} {parts[1]}") - f = f[1:] - kind = kind[:-2] - has_clamp = kind.endswith("_cl") - if has_clamp: - kind = kind[:-3] - has_l = kind.endswith("_l") - if has_l: - kind = kind[:-2] - has_b = kind.endswith("_b") - if has_b: - kind = kind[:-2] - has_c = kind == "_c" - if not has_c and kind != "": - raise Unsupported(op) - if bin(dmask).count("1") != 1 or dim not in ("dim:SQ_RSRC_IMG_2D", "dim:SQ_RSRC_IMG_2D_ARRAY") or is3d: - raise Unsupported(op + " form") - if has_b and self.stage != "ps": - raise Unsupported(op) - bias = None - if has_b: - if not f: - raise Unsupported(op + " coords") - bias, f = f[0], f[1:] - ref = None - if has_c: - if not f: - raise Unsupported(op + " coords") - ref, f = f[0], f[1:] - need = ncoord + (1 if (has_l or has_clamp) else 0) - if len(f) < need: - raise Unsupported(op + " coords") - raw_lod_arg = f[ncoord] if has_l else None - minlod = f[ncoord] if has_clamp else None - - unorm = "unorm" in mods - modes = self.gather_addr_modes(a[3], unorm=unorm) - self.uses_query = True - self.uses_fhalf = True - ch = 0 if has_c else (dmask.bit_length() - 1) - uvf = self.tmp() - self.emit(f"{uvf} = OpCompositeConstruct %v2float {f[0]} {f[1]}") - qtype = "%v3int" if ncoord == 3 else "%v2int" - - if has_l: - raw_lod = raw_lod_arg - else: - if self.stage == "ps": - uv_q = uvf - if unorm: - sz0 = self.tmp() - self.emit(f"{sz0} = OpImageQuerySizeLod {qtype} {img} {self.as_int(self.cu(0))}") - if ncoord == 3: - sz0_2 = self.tmp() - self.emit(f"{sz0_2} = OpVectorShuffle %v2int {sz0} {sz0} 0 1") - sz0 = sz0_2 - sz0f, uv_q = self.tmp(), self.tmp() - self.emit(f"{sz0f} = OpConvertSToF %v2float {sz0}") - self.emit(f"{uv_q} = OpFDiv %v2float {uvf} {sz0f}") - q, qy = self.tmp(), self.tmp() - self.emit(f"{q} = OpImageQueryLod %v2float {si} {uv_q}") - self.emit(f"{qy} = OpCompositeExtract %float {q} 1") - raw_lod = qy - else: - raw_lod = "%f0" - if bias is not None: - lb = self.tmp() - self.emit(f"{lb} = OpFAdd %float {raw_lod} {bias}") - raw_lod = lb - if minlod is not None: - lc = self.tmp() - self.emit(f"{lc} = OpExtInst %float %glsl FMax {raw_lod} {minlod}") - raw_lod = lc - - lv, lvm, mi, mc, mz = (self.tmp() for _ in range(5)) - self.emit(f"{lv} = OpImageQueryLevels %int {img}") - self.emit(f"{lvm} = OpISub %int {lv} {self.as_int(self.cu(1))}") - lod = self.clamp_gather_lod(raw_lod, a[3]["r"] + 1) - # Share #4321's RDNA2 8-fraction-bit LOD rounding so ordinary and depth-compare gathers agree at - # mip boundaries such as 0x3eff0000 (127.5/256) and 0x3eff0001: mip = (RoundEven(lod * 256) + 128) >> 8. - sc, q, qi, b = self.tmp(), self.tmp(), self.tmp(), self.tmp() - self.emit(f"{sc} = OpFMul %float {lod} {self.fconst(256.0)}") - self.emit(f"{q} = OpExtInst %float %glsl RoundEven {sc}") - self.emit(f"{qi} = OpConvertFToS %int {q}") - self.emit(f"{b} = OpIAdd %int {qi} {self.as_int(self.cu(128))}") - self.emit(f"{mi} = OpShiftRightArithmetic %int {b} {self.cu(8)}") - self.emit(f"{mz} = OpExtInst %int %glsl SMax {mi} {self.as_int(self.cu(0))}") - self.emit(f"{mc} = OpExtInst %int %glsl SMin {mz} {lvm}") - - sz = self.tmp() - self.emit(f"{sz} = OpImageQuerySizeLod {qtype} {img} {mc}") - layer = None - if ncoord == 3: - sz2, szl, lmax, rlayer, ilayer, layer = (self.tmp() for _ in range(6)) - self.emit(f"{sz2} = OpVectorShuffle %v2int {sz} {sz} 0 1") - self.emit(f"{szl} = OpCompositeExtract %int {sz} 2") - self.emit(f"{lmax} = OpISub %int {szl} {self.as_int(self.cu(1))}") - self.emit(f"{rlayer} = OpExtInst %float %glsl RoundEven {f[2]}") - self.emit(f"{ilayer} = OpConvertFToS %int {rlayer}") - self.emit(f"{layer} = OpExtInst %int %glsl SClamp {ilayer} {self.as_int(self.cu(0))} {lmax}") - else: - sz2 = sz - - if unorm: - st = uvf - else: - szf, st = self.tmp(), self.tmp() - self.emit(f"{szf} = OpConvertSToF %v2float {sz2}") - self.emit(f"{st} = OpFMul %v2float {uvf} {szf}") - half, sub, flo, i0, one2, i1 = (self.tmp() for _ in range(6)) - self.emit(f"{half} = OpCompositeConstruct %v2float %fhalf_g %fhalf_g") - self.emit(f"{sub} = OpFSub %v2float {st} {half}") - self.emit(f"{flo} = OpExtInst %v2float %glsl Floor {sub}") - self.emit(f"{i0} = OpConvertFToS %v2int {flo}") - if goff is not None: - i0o = self.tmp() - self.emit(f"{i0o} = OpIAdd %v2int {i0} {goff}") - i0 = i0o - c1 = self.as_int(self.cu(1)) - self.emit(f"{one2} = OpCompositeConstruct %v2int {c1} {c1}") - self.emit(f"{i1} = OpIAdd %v2int {i0} {one2}") - x0, y0, x1, y1, szx, szy = (self.tmp() for _ in range(6)) - self.emit(f"{x0} = OpCompositeExtract %int {i0} 0") - self.emit(f"{y0} = OpCompositeExtract %int {i0} 1") - self.emit(f"{x1} = OpCompositeExtract %int {i1} 0") - self.emit(f"{y1} = OpCompositeExtract %int {i1} 1") - self.emit(f"{szx} = OpCompositeExtract %int {sz2} 0") - self.emit(f"{szy} = OpCompositeExtract %int {sz2} 1") - ax = [self.gather_addr(c, szx, modes[0]) for c in (x0, x1)] - ay = [self.gather_addr(c, szy, modes[1]) for c in (y0, y1)] - texels, outs = [], [] - for (xx, ox), (yy, oy) in ((ax[0], ay[1]), (ax[1], ay[1]), (ax[1], ay[0]), (ax[0], ay[0])): - cc = self.tmp() - if ncoord == 3: - self.emit(f"{cc} = OpCompositeConstruct %v3int {xx} {yy} {layer}") - else: - self.emit(f"{cc} = OpCompositeConstruct %v2int {xx} {yy}") - texels.append(cc) - if ox is not None and oy is not None: - both = self.tmp() - self.emit(f"{both} = OpLogicalOr %bool {ox} {oy}") - outs.append(both) - else: - outs.append(ox if ox is not None else oy) - border_one = self.gather_border_one(a[3], ch) if any(o is not None for o in outs) else None - - if has_c: - cmp_state = self.gather_depth_compare_prep(a[3]) - if border_one is not None: - if isinstance(border_one, bool): - border_v = "%f1" if border_one else "%f0" - else: - border_v = self.tmp() - self.emit(f"{border_v} = OpSelect %float {border_one} %f1 %f0") - taps = [] - for cc, out in zip(texels, outs): - tx, comp = self.tmp(), self.tmp() - self.emit(f"{tx} = OpImageFetch %v4float {img} {cc} Lod {mc}") - self.emit(f"{comp} = OpCompositeExtract %float {tx} 0") - if out is not None: - sel = self.tmp() - self.emit(f"{sel} = OpSelect %float {out} {border_v} {comp}") - comp = sel - taps.append(self.gather_depth_compare(cmp_state, ref, comp)) - self.store_gather_taps(vdata["r"], taps, d16) - return - - def gather_mip(image: str, cls: int, ty: str) -> str: - scalar = ("%float", "%uint", "%int")[cls] - if border_one is not None: - zero_v, one_v = (self.fconst(0.0), self.fconst(1.0)) if cls == 0 else \ - (self.cu(0), self.cu(1)) if cls == 1 else (self.as_int(self.cu(0)), self.as_int(self.cu(1))) - if isinstance(border_one, bool): - border_v = one_v if border_one else zero_v - else: - border_v = self.tmp() - self.emit(f"{border_v} = OpSelect {scalar} {border_one} {one_v} {zero_v}") - taps = [] - for cc, out in zip(texels, outs): - tx, comp = self.tmp(), self.tmp() - self.emit(f"{tx} = OpImageFetch {ty} {image} {cc} Lod {mc}") - self.emit(f"{comp} = OpCompositeExtract {scalar} {tx} {ch}") - if out is not None: - sel = self.tmp() - self.emit(f"{sel} = OpSelect {scalar} {out} {border_v} {comp}") - comp = sel - taps.append(comp) - result = self.tmp() - self.emit(f"{result} = OpCompositeConstruct {ty} {' '.join(taps)}") - return result - - self.image_read_typed(dim, self.sgpr_word(a[2], 1), img, img_idx, - 0xf, vdata, d16, gather_mip) - - def desc_lookup_sgpr(self, a, n): - """desc_lookup for an SGPR descriptor range (n=8: T#, n=4: S#), cached for the rest of the basic block. - - The cache holds the id of the call's result per (first SGPR, n). It is dropped by store_reg when any - SGPR of the range is written (all writes to the %sgpr array go through store_reg, including the 64-bit - ones, which are two calls, s_load results, v_readlane/v_readfirstlane results and the spare slots lane - masks are parked in) and cleared when a basic block starts. Only lookups made at the block's top level - are remembered, see desc_cache_ok. Returns the bindless index (a uint id).""" - if a["k"] == "slist" and len(a["r"]) >= n: - words = self.sgpr_words(a, n) - if n < 8: - words = words + [self.cu(0xFFFFFFFF)] * (8 - n) - return self.desc_lookup(words) - if a["k"] != "sgpr" or a.get("n", 1) < n: - raise Unsupported("descriptor operand") - key = (a["r"], n) - hit = self.desc_cache.get(key) - if hit is not None: - return hit - top = self.desc_cache_ok() - words = self.sgpr_words(a, n) - if n < 8: - words = words + [self.cu(0xFFFFFFFF)] * (8 - n) - idx = self.desc_lookup(words) - if top: - self.desc_cache[key] = idx - return idx - - def sgpr_word(self, a, i): - if a["k"] == "sgpr": - return self.load_reg("sgpr", a["r"] + i) - if a["k"] == "slist": - slot = a["r"][i] - if isinstance(slot, int): - return self.load_reg("sgpr", slot) - t = self.tmp() - self.emit(f"{t} = OpLoad %uint {'%vcc' if slot == 'vcc_lo' else '%vcc_hi'}") - return t - raise Unsupported("descriptor operand") - - def sgpr_words(self, a, n): - if a["k"] == "sgpr" and a.get("n", 1) >= n: - return [self.load_reg("sgpr", a["r"] + i) for i in range(n)] - if a["k"] == "slist" and len(a["r"]) >= n: - return [self.sgpr_word(a, i) for i in range(n)] - raise Unsupported("descriptor operand") - - def addr_regs(self, a): - """Image address operand: contiguous v[x:y] or an NSA list.""" - if a["k"] == "vgpr": - return [a["r"] + i for i in range(a.get("n", 1))] - if a["k"] == "vlist": - return a["r"] - raise Unsupported("image address operand") - - def dynamic_sampled_access(self, ptr, ptr_type, array, index): - """Index a sampled image or sampler array with the runtime descriptor lookup result.""" - self.uses_dynamic_sampled_index = True - self.emit(f"{ptr} = OpAccessChain {ptr_type} {array} {index}") - - def dynamic_storage_access(self, ptr, ptr_type, array, index): - """Index a storage image array with the runtime descriptor lookup result.""" - self.uses_dynamic_storage_index = True - self.emit(f"{ptr} = OpAccessChain {ptr_type} {array} {index}") - - def cube_coords(self, f): - """(s, t, face) of a cube sample -> the 6-layer 2D-array view. The hardware takes s and t in [1, 2] - (sc / |cubema| + 1.5) and the third coordinate as 8 * slice + face.""" - s, t, q, fl, d, layer = (self.tmp() for _ in range(6)) - self.emit(f"{s} = OpFSub %float {f[0]} %f1") - self.emit(f"{t} = OpFSub %float {f[1]} %f1") - self.emit(f"{q} = OpFMul %float {f[2]} {self.fconst(0.125)}") - self.emit(f"{fl} = OpExtInst %float %glsl Floor {q}") - self.emit(f"{d} = OpFMul %float {fl} {self.fconst(2.0)}") - self.emit(f"{layer} = OpFSub %float {f[2]} {d}") - return [s, t, layer] + f[3:] - - def image_op(self, op, a, mods): - a16 = "a16" in mods - d16 = "d16" in mods - dim = next((m for m in mods if m.startswith("dim:")), "dim:SQ_RSRC_IMG_2D") - kinds = {"dim:SQ_RSRC_IMG_2D": ("img2d", "%images", "simg2d", 2, "_ptr_UC_img"), - "dim:SQ_RSRC_IMG_2D_ARRAY": ("img2da", "%images_arr", "simg2da", 3, "_ptr_UC_imga"), - # Cube: the shader already did face selection (v_cube*), and cube_coords maps (s, t, face) onto a - # 6-layer 2D array view of the cube. The runtime binds cube textures as 2D-array views. - "dim:SQ_RSRC_IMG_CUBE": ("img2da", "%images_arr", "simg2da", 3, "_ptr_UC_imga"), - "dim:SQ_RSRC_IMG_1D": ("img1d", "%images_1d", "simg1d", 1, "_ptr_UC_img1"), - "dim:SQ_RSRC_IMG_3D": ("img3d", "%images_3d", "simg3d", -3, "_ptr_UC_img3")} - if dim not in kinds: - raise Unsupported(op + " " + dim.split("SQ_RSRC_IMG_")[-1]) - itype, iarr, stype, ncoord, iptr = kinds[dim] - is3d = ncoord == -3 # 3D: three real coordinates (and 3-component gradients) - if is3d: - ncoord = 3 - self.uses_tex_3d = True - elif ncoord == 3: - self.uses_tex_array = True - if ncoord == 1: - self.uses_tex_1d = True - if is3d and op in ("image_sample_d", "image_sample_d_cl") and ("tfe" in mods or "lwe" in mods): - raise Unsupported(op + " 3D gradient status") - grad_width = 3 if is3d else min(ncoord, 2) # an array layer has no derivative - # Cube loads use the same 2D-array view (sampled or storage) and integer layer as array loads. - view_dim = "dim:SQ_RSRC_IMG_2D_ARRAY" if dim == "dim:SQ_RSRC_IMG_CUBE" else dim - # glc makes the access coherent (see image_load_coherent). Only image_load can be: a sampled read has no - # coherent form in SPIR-V, so it is refused rather than read stale. - coherent = "glc" in mods - if coherent and (op != "image_load" or view_dim not in self.STORE_DIMS): - raise Unsupported(op + " glc " + dim.split("SQ_RSRC_IMG_")[-1]) - dm = next((m for m in mods if m.startswith("dmask:")), "dmask:0x1") - dmask = int(dm.split(":")[1], 0) - vdata = a[0] - if vdata["k"] != "vgpr": # `off`, an SGPR or a constant where the VGPR range of the result goes - raise Unsupported(op + " destination") - addr = self.addr_regs(a[1]) - if op == "image_sample_c_l": - # Vulkan Dref returns one scalar. Other component masks require the depth view's swizzle. - if (dim != "dim:SQ_RSRC_IMG_2D" or dmask != 1 or len(addr) != (3 if a16 else 4) - or any(m not in (dim, dm, "a16", "d16") for m in mods)): - raise Unsupported(op + " needs scalar 2D depth comparison") - img_idx = self.desc_lookup_sgpr(a[2], 8) - img = None # a coherent image_load reads the storage view, not this sampled one - if not coherent: - ip, img = self.tmp(), self.tmp() - self.dynamic_sampled_access(ip, f"%{iptr}", iarr, img_idx) - self.emit(f"{img} = OpLoad %{itype} {ip}") - coords = [self.load_reg("vgpr", r) for r in addr] - if a16: - # GFX10 A16 packs only the coordinates, and the LOD or clamp after them, as f16 pairs (low half first). - # The extra arguments before them keep a whole VGPR each, and so do non-G16 gradients (LLVM AMDGPU - # getAddrSizeMIMGOp: the extra arguments' words, the gradients, then the packed halves; llvm-mc wants - # v[0:2] for a 2D image_sample_c_b ... a16). A bias is an f16 in the low half of its VGPR, a z-compare - # an f32. Until 2026-11-21 those were unpacked as pairs too, and the coordinates after them were read a - # half early. A texel offset comes first and keeps its full dword under a16. - if op.startswith("image_sample"): - extras = op[len("image_sample"):] - elif op.startswith("image_gather4"): - extras = op[len("image_gather4"):] - else: - extras = "" - w_off = 1 if op.endswith("_o") else 0 - extras = extras[:-2] if w_off else extras - extras = extras[:-3] if extras.endswith("_cl") else extras # the clamp is packed with the coordinates - w_bias = 1 if extras in ("_b", "_c_b") else 0 - w_grad = 2 * grad_width if extras in ("_d", "_d_cl") else 0 - whole = w_off + w_bias + (1 if extras.startswith("_c") else 0) + w_grad - unpacked = [] - for i, c in enumerate(coords): - if i < whole and not w_off <= i < w_off + w_bias: - unpacked.append(c) # offset, z-compare or gradient: the whole word - continue - v2 = self.tmp() - self.emit(f"{v2} = OpExtInst %v2float %glsl UnpackHalf2x16 {c}") - for k in ((0,) if i < whole else (0, 1)): # a bias is the low half only - f = self.tmp() - self.emit(f"{f} = OpCompositeExtract %float {v2} {k}") - unpacked.append(self.tou(f)) - coords = unpacked - if op == "image_load": - # 16-bit integer coordinates: each half is an unsigned 16-bit int, not an f16. - coords = self.unpack_image_a16_uints([self.load_reg("vgpr", r) for r in addr]) - if op == "image_load": - if len(coords) < ncoord: - raise Unsupported("image_load coords") - ints = [self.as_int(c) for c in coords[:ncoord]] - if ncoord == 1: - iv = ints[0] - else: - iv = self.tmp() - self.emit(f"{iv} = OpCompositeConstruct {'%v2int' if ncoord == 2 else '%v3int'} {' '.join(ints)}") - if coherent: - self.image_load_coherent(view_dim, self.sgpr_word(a[2], 1), iv, img_idx, dmask, vdata, d16) - return - self.image_load_typed(view_dim, self.sgpr_word(a[2], 1), iv, img, img_idx, - dmask, vdata, self.cu(0), d16) - return - else: - smp_idx = self.desc_lookup_sgpr(a[3], 4) - sp, smp, si = self.tmp(), self.tmp(), self.tmp() - self.dynamic_sampled_access(sp, "%_ptr_UC_smp", "%samplers", smp_idx) - self.emit(f"{smp} = OpLoad %smp {sp}") - typed_implicit = op == "image_sample" and self.stage == "ps" and dim == "dim:SQ_RSRC_IMG_2D" - # An explicit-LOD sample has the same shape in every dimension, so it takes the typed read too: - # image_read_typed picks the UINT/SINT alias of the dimension's sampled binding (image_load does). - typed_sample = typed_implicit or op in ("image_sample_l", "image_sample_lz") - - def sampled_image(image, cls, di=0): - sampled = self.tmp() - sampler_type = f"itxsamp{cls}_{di}" if cls else stype - self.emit(f"{sampled} = OpSampledImage %{sampler_type} {image} {smp}") - return sampled - - no_sampled_img = op in ("image_gather4_lz", "image_gather4_lz_o", "image_gather4_l", "image_gather4_l_o", - "image_gather4_c_l", "image_gather4_c_l_o") or ( - op in ("image_gather4_cl", "image_gather4_cl_o", "image_gather4_c_cl", "image_gather4_c_cl_o") - and self.stage != "ps" - ) - if not typed_sample and not no_sampled_img: - self.emit(f"{si} = OpSampledImage %{stype} {img} {smp}") - f = [self.tof(c) for c in coords] - if op in self.GATHER4_LOD_OPS: - self.emit_gather4_lod(op, a, mods, dim, img, img_idx, si, coords, f, ncoord, is3d, dmask, vdata, a16, d16) - return - goff = None - if op in ("image_gather4_lz_o", "image_gather4_l_o"): - # first address dword: signed 6-bit texel offsets x [5:0], y [13:8] - if a16 and ("tfe" in mods or "lwe" in mods): - raise Unsupported(op + " a16 status") - parts = [] - for k in range(2): - u, i = self.tmp(), self.tmp() - self.emit(f"{u} = OpBitFieldSExtract %uint {coords[0]} {self.cu(8 * k)} {self.cu(6)}") - self.emit(f"{i} = OpBitcast %int {u}") - parts.append(i) - goff = self.tmp() - self.emit(f"{goff} = OpCompositeConstruct %v2int {parts[0]} {parts[1]}") - f = f[1:] - op = op[:-2] - self.uses_img_offset = True - if op == "image_gather4_l": - # Gather at an explicit LOD: Vulkan gathers have no Lod operand without an AMD extension, so fetch - # the 2x2 footprint at mip round(lod) (clamped to the mip range) in gather order - # (u0,v1) (u1,v1) (u1,v0) (u0,v0). Each texel coordinate goes through the S#'s own address mode - # (CLAMP_X/CLAMP_Y, see gather_addr_modes / gather_addr). - if bin(dmask).count("1") != 1 or ncoord != 2 or len(f) < 3: - raise Unsupported("image_gather4_l form") - modes = self.gather_addr_modes(a[3]) - self.uses_query = True - ch = dmask.bit_length() - 1 - lv, lvm, rl, mi, mc, mz, sz, uvf, szf, st, half, flo, i0, one2, i1 = (self.tmp() for _ in range(15)) - # Size and level-count queries read view properties; only the texel fetches need a typed alias. - self.emit(f"{lv} = OpImageQueryLevels %int {img}") - self.emit(f"{lvm} = OpISub %int {lv} {self.as_int(self.cu(1))}") - lod = self.clamp_gather_lod(f[2], a[3]["r"] + 1) - # Native gather rounds the LOD to the nearest mip with ties up, not to even (SHADER-152: on - # Radeon Graphics 26.10.1, LOD 0.5 with bounds [0,1] selected mip 1, where RoundEven selected 0). - # floor + (fraction >= 0.5), not Floor(lod + 0.5): lod - floor(lod) is exact in binary32, the sum is - # not (0x3effffff + 0.5 rounds to 1.0, which picked mip 1 where native sampling reads mip 0). - fr, up, fl, inc = self.tmp(), self.tmp(), self.tmp(), self.tmp() - self.emit(f"{rl} = OpExtInst %float %glsl Floor {lod}") - self.emit(f"{fr} = OpFSub %float {lod} {rl}") - self.emit(f"{up} = OpFOrdGreaterThanEqual %bool {fr} %fhalf_g") - self.emit(f"{fl} = OpConvertFToS %int {rl}") - self.emit(f"{inc} = OpSelect %int {up} {self.as_int(self.cu(1))} {self.as_int(self.cu(0))}") - self.emit(f"{mi} = OpIAdd %int {fl} {inc}") - self.emit(f"{mz} = OpExtInst %int %glsl SMax {mi} {self.as_int(self.cu(0))}") - self.emit(f"{mc} = OpExtInst %int %glsl SMin {mz} {lvm}") - self.emit(f"{sz} = OpImageQuerySizeLod %v2int {img} {mc}") - self.emit(f"{uvf} = OpCompositeConstruct %v2float {f[0]} {f[1]}") - self.emit(f"{szf} = OpConvertSToF %v2float {sz}") - self.emit(f"{st} = OpFMul %v2float {uvf} {szf}") - self.emit(f"{half} = OpCompositeConstruct %v2float %fhalf_g %fhalf_g") - sub = self.tmp() - self.emit(f"{sub} = OpFSub %v2float {st} {half}") - self.emit(f"{flo} = OpExtInst %v2float %glsl Floor {sub}") - self.emit(f"{i0} = OpConvertFToS %v2int {flo}") - if goff is not None: - i0o = self.tmp() - self.emit(f"{i0o} = OpIAdd %v2int {i0} {goff}") - i0 = i0o - c1 = self.as_int(self.cu(1)) - self.emit(f"{one2} = OpCompositeConstruct %v2int {c1} {c1}") - self.emit(f"{i1} = OpIAdd %v2int {i0} {one2}") - x0, y0, x1, y1 = (self.tmp() for _ in range(4)) - self.emit(f"{x0} = OpCompositeExtract %int {i0} 0") - self.emit(f"{y0} = OpCompositeExtract %int {i0} 1") - self.emit(f"{x1} = OpCompositeExtract %int {i1} 0") - self.emit(f"{y1} = OpCompositeExtract %int {i1} 1") - szx, szy = self.tmp(), self.tmp() - self.emit(f"{szx} = OpCompositeExtract %int {sz} 0") - self.emit(f"{szy} = OpCompositeExtract %int {sz} 1") - ax = [self.gather_addr(c, szx, modes[0]) for c in (x0, x1)] - ay = [self.gather_addr(c, szy, modes[1]) for c in (y0, y1)] - texels, outs = [], [] - for (xx, ox), (yy, oy) in ((ax[0], ay[1]), (ax[1], ay[1]), (ax[1], ay[0]), (ax[0], ay[0])): - cc = self.tmp() - self.emit(f"{cc} = OpCompositeConstruct %v2int {xx} {yy}") - texels.append(cc) - if ox is not None and oy is not None: - both = self.tmp() - self.emit(f"{both} = OpLogicalOr %bool {ox} {oy}") - outs.append(both) - else: - outs.append(ox if ox is not None else oy) - # SHADER-348: border modes give a tap outside the image the S# border colour's channel. - border_one = self.gather_border_one(a[3], ch) if any(o is not None for o in outs) else None - - def gather_mip(image: str, cls: int, ty: str) -> str: - scalar = ("%float", "%uint", "%int")[cls] - if border_one is not None: - zero_v, one_v = (self.fconst(0.0), self.fconst(1.0)) if cls == 0 else \ - (self.cu(0), self.cu(1)) if cls == 1 else (self.as_int(self.cu(0)), self.as_int(self.cu(1))) - if isinstance(border_one, bool): - border_v = one_v if border_one else zero_v - else: - border_v = self.tmp() - self.emit(f"{border_v} = OpSelect {scalar} {border_one} {one_v} {zero_v}") - taps = [] - for cc, out in zip(texels, outs): - tx, comp = self.tmp(), self.tmp() - self.emit(f"{tx} = OpImageFetch {ty} {image} {cc} Lod {mc}") - self.emit(f"{comp} = OpCompositeExtract {scalar} {tx} {ch}") - if out is not None: - sel = self.tmp() - self.emit(f"{sel} = OpSelect {scalar} {out} {border_v} {comp}") - comp = sel - taps.append(comp) - result = self.tmp() - self.emit(f"{result} = OpCompositeConstruct {ty} {' '.join(taps)}") - return result - - self.image_read_typed(dim, self.sgpr_word(a[2], 1), img, img_idx, - 0xf, vdata, d16, gather_mip) - self.uses_fhalf = True - return - if op == "image_gather4_lz": - # Gather the 2x2 footprint of one channel (dmask picks it) at mip 0 -> 4 results. - if bin(dmask).count("1") != 1 or ncoord not in (2, 3) or is3d or len(f) < ncoord: - raise Unsupported("image_gather4_lz form") - if dim == "dim:SQ_RSRC_IMG_CUBE": - f = self.cube_coords(f) - uv = self.tmp() - if ncoord == 3: # 2D array (or cube as a 6-layer array): layer is the 3rd coordinate - self.emit(f"{uv} = OpCompositeConstruct %v3float {f[0]} {f[1]} {f[2]}") - else: - self.emit(f"{uv} = OpCompositeConstruct %v2float {f[0]} {f[1]}") - component = self.cu(dmask.bit_length() - 1) - offset = f" Offset {goff}" if goff is not None else "" - - def gather(image, cls, ty): - sampled = sampled_image(image, cls) - res = self.tmp() - self.emit(f"{res} = OpImageGather {ty} {sampled} {uv} {component}{offset}") - return res - - if dim == "dim:SQ_RSRC_IMG_2D": - self.uses_int_sampler = True - # dmask selects one texture channel; all four taps are written. - self.image_read_typed(dim, self.sgpr_word(a[2], 1), img, img_idx, - 0xf, vdata, d16, gather) - return - res = gather(img, 0, "%v4float") - comps = [] - for c in range(4): - comp = self.tmp() - self.emit(f"{comp} = OpCompositeExtract %float {res} {c}") - comps.append(comp) - self.store_gather_taps(vdata["r"], comps, d16) - return - kind = op[len("image_sample"):] # '', '_lz', '_l', '_b', '_c_lz', '_d', '_d_cl' (+ '_o') - off = None - if kind.endswith("_o"): - # _o: the first address dword packs signed 6-bit texel offsets, x = [5:0], y = [13:8], z = [21:16] - # (GFX10 MIMG address order: offset, bias, z-compare, derivatives, coordinates). Mapped to the - # SPIR-V Offset operand; Vulkan only guarantees offsets within minTexelOffset..maxTexelOffset. - kind = kind[:-2] - raw, f = coords[0], f[1:] - n_off = 3 if is3d else (1 if ncoord == 1 else 2) - parts = [] - for k in range(n_off): - u, i = self.tmp(), self.tmp() - self.emit(f"{u} = OpBitFieldSExtract %uint {raw} {self.cu(8 * k)} {self.cu(6)}") - self.emit(f"{i} = OpBitcast %int {u}") - parts.append(i) - if n_off == 1: - off = parts[0] - else: - off = self.tmp() - self.emit(f"{off} = OpCompositeConstruct {'%v3int' if n_off == 3 else '%v2int'} {' '.join(parts)}") - if not TEXEL_OFFSET_FALLBACK: - self.uses_img_offset = True - minlod = None - clamp = kind.endswith("_cl") # a min-LOD clamp, read after the coordinates (after the gradients for _d) - if clamp: - kind = kind[:-3] - if kind not in ("", "_b", "_c", "_c_b", "_d"): - raise Unsupported(op) - self.uses_minlod = True - # Address order after the offset: bias, z-compare, gradients, coordinates, LOD, clamp. - bias = None - if kind in ("_b", "_c_b"): - bias, f = f[0], f[1:] - ref = None - if kind.startswith("_c"): - ref, f = f[0], f[1:] - grads = None - if kind == "_d": - # Address order: all dP/dx components, all dP/dy components, then the coordinates. - if len(f) < 2 * grad_width + ncoord: - raise Unsupported(op + " coords") - if grad_width == 1: - grads = (f[0], f[1]) - else: - gx, gy = self.tmp(), self.tmp() - self.emit(f"{gx} = OpCompositeConstruct %v{grad_width}float {' '.join(f[:grad_width])}") - self.emit(f"{gy} = OpCompositeConstruct %v{grad_width}float {' '.join(f[grad_width:2 * grad_width])}") - grads = (gx, gy) - f = f[2 * grad_width:] - if clamp: - # The clamp is the component right after the coordinates. Under a16 an f16 pad may follow it, so - # it isn't the last one there (taking the last one read that pad until 2026-11-21). - if len(f) <= ncoord: - raise Unsupported(op + " coords") - minlod, f = f[ncoord], f[:ncoord] - if len(f) < ncoord: - raise Unsupported(op + " coords") - if dim == "dim:SQ_RSRC_IMG_CUBE": - f = self.cube_coords(f) - if ncoord == 1: - uv = f[0] - elif ncoord == 3: - # The array layer arrives as a float coordinate; Vulkan rounds it the same way. - uv = self.tmp() - self.emit(f"{uv} = OpCompositeConstruct %v3float {f[0]} {f[1]} {f[2]}") - else: - uv = self.tmp() - self.emit(f"{uv} = OpCompositeConstruct %v2float {f[0]} {f[1]}") - lod = f[ncoord] if kind == "_l" and len(f) > ncoord else "%f0" - if typed_sample: - # The aliases image_read_typed declares are indexed by the dimension it reads: a cube samples its - # 6-layer 2D-array view, which is what `img` was loaded from above. - di = self.STORE_DIMS[view_dim][0] - operands = f"Lod {lod}" - if typed_implicit: - # Compute the quad gradients before the per-image format branch. - dx, dy = self.tmp(), self.tmp() - self.emit(f"{dx} = OpDPdx %v2float {uv}") - self.emit(f"{dy} = OpDPdy %v2float {uv}") - operands = f"Grad {dx} {dy}" - - def sample(image, cls, ty): - sampled = sampled_image(image, cls, di) - result = self.tmp() - self.emit(f"{result} = OpImageSampleExplicitLod {ty} {sampled} {uv} {operands}") - return result - - self.uses_int_sampler = True - self.image_read_typed(view_dim, self.sgpr_word(a[2], 1), img, img_idx, - dmask, vdata, d16, sample) - return - res = self.tmp() - if off is not None and kind not in ("", "_lz", "_l", "_b", "_c_lz", "_c", "_c_b"): - raise Unsupported(op) - implicit = kind in ("", "_b", "_c", "_c_b") and self.stage == "ps" - # A min-LOD clamp (_cl): MinLod goes with the implicit-LOD forms and Grad. Without derivatives (outside the - # PS) the base LOD is 0 (or bias for _b / _c_b) and the clamp raises it, so the explicit LOD is - # max(base, clamp) and no MinLod operand. - lod_zero = "%f0" - if minlod is not None and not implicit and kind not in ("_d", "_b", "_c_b"): - lod_zero = self.tmp() - self.emit(f"{lod_zero} = OpExtInst %float %glsl FMax %f0 {minlod}") - bias_lod = bias - if kind in ("_b", "_c_b") and not implicit and minlod is not None: - bias_lod = self.tmp() - self.emit(f"{bias_lod} = OpExtInst %float %glsl FMax {bias} {minlod}") - grads_fb = None - if off is not None and TEXEL_OFFSET_FALLBACK: - fb_lod = bias_lod if (not implicit and kind in ("_b", "_c_b")) else lod - uv, grads_fb = self.texel_offset_fold(img, si, uv, off, n_off, ncoord, kind, implicit, fb_lod, bias, - a[3]) - off = None - - def opnd(mask, args): - """Image operands in SPIR-V mask order: Bias / Lod, Offset (0x10), MinLod (0x80, implicit forms).""" - masks, vals = ([mask], [args]) if mask else ([], []) - if off is not None: - masks.append("Offset") - vals.append(off) - if minlod is not None and mask in ("", "Bias") and implicit: - masks.append("MinLod") - vals.append(minlod) - return f" {'|'.join(masks)} {' '.join(vals)}" if masks else "" - if kind == "_d": - if minlod is not None: - self.emit(f"{res} = OpImageSampleExplicitLod %v4float {si} {uv} Grad|MinLod {grads[0]} {grads[1]} {minlod}") - else: - self.emit(f"{res} = OpImageSampleExplicitLod %v4float {si} {uv} Grad {grads[0]} {grads[1]}") - elif grads_fb is not None and not kind.startswith("_c"): - self.emit(f"{res} = OpImageSampleExplicitLod %v4float {si} {uv} Grad{'|MinLod' if minlod else ''} " - f"{grads_fb[0]} {grads_fb[1]}{' ' + minlod if minlod else ''}") - elif kind == "": - self.emit(f"{res} = OpImageSampleImplicitLod %v4float {si} {uv}{opnd('', '')}" if self.stage == "ps" else - f"{res} = OpImageSampleExplicitLod %v4float {si} {uv}{opnd('Lod', lod_zero)}") - elif kind in ("_lz", "_l"): - self.emit(f"{res} = OpImageSampleExplicitLod %v4float {si} {uv}{opnd('Lod', lod)}") - elif kind == "_b": - self.emit(f"{res} = OpImageSampleImplicitLod %v4float {si} {uv}{opnd('Bias', bias)}" if self.stage == "ps" else - f"{res} = OpImageSampleExplicitLod %v4float {si} {uv}{opnd('Lod', bias_lod)}") - elif kind in ("_c_lz", "_c_l", "_c", "_c_b"): - d = self.tmp() - if kind in ("_c_lz", "_c_l") or (self.stage != "ps" and kind in ("_c", "_c_b")): - # _c / _c_b outside the PS have no derivatives (base LOD 0, or bias / max(bias, minlod) for _c_b) - d_lod = f[ncoord] if kind == "_c_l" else (bias_lod if kind == "_c_b" else lod_zero) - self.emit(f"{d} = OpImageSampleDrefExplicitLod %float {si} {uv} {ref}{opnd('Lod', d_lod)}") - elif grads_fb is not None: - self.emit(f"{d} = OpImageSampleDrefExplicitLod %float {si} {uv} {ref} Grad{'|MinLod' if minlod else ''} " - f"{grads_fb[0]} {grads_fb[1]}{' ' + minlod if minlod else ''}") - elif kind == "_c_b": - self.emit(f"{d} = OpImageSampleDrefImplicitLod %float {si} {uv} {ref}{opnd('Bias', bias)}") - else: - self.emit(f"{d} = OpImageSampleDrefImplicitLod %float {si} {uv} {ref}{opnd('', '')}") - if d16: - # d16: the compare result is an f16 in the low half, as in the other d16 paths below. Until - # 2026-11-21 it was written as f32 bits, whose low half is 0 for every result (1.0 = 0x3f800000). - r = self.f16_bits(d) - else: - r = self.tou(d) - self.dst({"k": "vgpr", "r": vdata["r"], "n": 1}, r) - return - else: - raise Unsupported(op) - ncomp = bin(dmask).count("1") - comps = [] - for c in range(4): - if dmask >> c & 1: - comp = self.tmp() - self.emit(f"{comp} = OpCompositeExtract %float {res} {c}") - comps.append(comp) - if len(comps) != ncomp: - raise Unsupported("dmask") - if d16: - # d16: components are packed two per register as f16 (x|y<<16, z|w<<16). - for i in range(0, len(comps), 2): - second = comps[i + 1] if i + 1 < len(comps) else "%f0" - p = self.pack_f16_pair_int(comps[i], second) - self.dst({"k": "vgpr", "r": vdata["r"] + i // 2, "n": 1}, p) - else: - for i, comp in enumerate(comps): - self.dst({"k": "vgpr", "r": vdata["r"] + i, "n": 1}, self.tou(comp)) - - # image atomic -> SPIR-V op (guarded inside `if (active)` so inactive lanes skip the access) - IMG_ATOMICS = {"image_atomic_umin": "OpAtomicUMin", "image_atomic_umax": "OpAtomicUMax", - "image_atomic_smin": "OpAtomicSMin", "image_atomic_smax": "OpAtomicSMax", - "image_atomic_or": "OpAtomicOr", "image_atomic_xor": "OpAtomicXor", - "image_atomic_and": "OpAtomicAnd", "image_atomic_add": "OpAtomicIAdd", - "image_atomic_sub": "OpAtomicISub"} - IMG_ATOMICS_EXTRA = ("image_atomic_swap", "image_atomic_inc", "image_atomic_dec", - "image_atomic_fmin", "image_atomic_fmax", "image_atomic_fcmpswap") - - # image_store views: dim -> (index, SPIR-V Dim, arrayed, coordinate count). Bindings 8 + 3 * index + class, - # class 0 = float, 1 = uint, 2 = sint (Vulkan needs the shader's component type to match the image format). - STORE_DIMS = {"dim:SQ_RSRC_IMG_2D": (0, "2D", 0, 2), "dim:SQ_RSRC_IMG_2D_ARRAY": (1, "2D", 1, 3), - "dim:SQ_RSRC_IMG_3D": (2, "3D", 0, 3), "dim:SQ_RSRC_IMG_1D": (3, "1D", 0, 1)} - # The sampled array of each STORE_DIMS index: its binding in set 0 (assemble declares %images, %images_arr, - # %images_3d and %images_1d there). Typed image_load reads UINT/SINT images through uint/sint aliases of it. - SAMPLED_BINDINGS = {0: 0, 1: 3, 2: 6, 3: 5} - INT_FORMATS = None # (uint mask words, sint mask words) over the 512 GFX10 formats - - @classmethod - def int_format_masks(cls): - if cls.INT_FORMATS is None: - u, si = [0] * 16, [0] * 16 - for k, name in GFX10_FORMATS.items(): - if name.endswith("_UINT"): - u[k >> 5] |= 1 << (k & 31) - elif name.endswith("_SINT"): - si[k >> 5] |= 1 << (k & 31) - cls.INT_FORMATS = (u, si) - return cls.INT_FORMATS - - FLOAT_FORMATS = None - - @classmethod - def float_format_masks(cls): - """(normalized, 32-bit-channel float) 512-bit tables over the GFX10 T# FORMAT field, for the d16 rounding - rule: a UNORM/SNORM channel is the one whose exact quotient the hardware rounds once, and a float channel - 32 bits wide is the one it narrows toward zero (SHADER-308).""" - if cls.FLOAT_FORMATS is None: - norm, f32 = [0] * 16, [0] * 16 - for k, name in GFX10_FORMATS.items(): - if name.endswith(("_UNORM", "_SNORM")): - norm[k >> 5] |= 1 << (k & 31) - elif name.endswith("_FLOAT") and re.fullmatch(r"GFX10_FORMAT_(32_)*32_FLOAT", name): - f32[k >> 5] |= 1 << (k & 31) - cls.FLOAT_FORMATS = (norm, f32) - return cls.FLOAT_FORMATS - - def fmt_float_flags(self, word1): - """(is UNORM/SNORM, is a 32-bit-channel float format) for a T# word1, from the 512-bit tables.""" - for w in [16] + sum(self.float_format_masks(), []): - self.cu(w) - fmt, word, bit = self.tmp(), self.tmp(), self.tmp() - self.emit(f"{fmt} = OpBitFieldUExtract %uint {word1} {self.cu(20)} {self.cu(9)}") - self.emit(f"{word} = OpShiftRightLogical %uint {fmt} {self.cu(5)}") - self.emit(f"{bit} = OpBitwiseAnd %uint {fmt} {self.cu(31)}") - flags = [] - for mask in ("%fmt_norm_mask", "%fmt_f32_mask"): - ptr, w, b, nz = self.tmp(), self.tmp(), self.tmp(), self.tmp() - self.emit(f"{ptr} = OpAccessChain %_ptr_Private_uint {mask} {word}") - self.emit(f"{w} = OpLoad %uint {ptr}") - self.emit(f"{b} = OpBitFieldUExtract %uint {w} {bit} {self.cu(1)}") - self.emit(f"{nz} = OpINotEqual %bool {b} {self.cu(0)}") - flags.append(nz) - return flags - - def fmt_int_flags(self, word1): - """(is UINT format, is SINT format) for a T# word1 (FORMAT [28:20]), from the 512-bit tables.""" - for w in [16] + sum(self.int_format_masks(), []): - self.cu(w) - fmt, word, bit = self.tmp(), self.tmp(), self.tmp() - self.emit(f"{fmt} = OpBitFieldUExtract %uint {word1} {self.cu(20)} {self.cu(9)}") - self.emit(f"{word} = OpShiftRightLogical %uint {fmt} {self.cu(5)}") - self.emit(f"{bit} = OpBitwiseAnd %uint {fmt} {self.cu(31)}") - flags = [] - for mask in ("%fmt_uint_mask", "%fmt_sint_mask"): - p, w, b, nz = self.tmp(), self.tmp(), self.tmp(), self.tmp() - self.emit(f"{p} = OpAccessChain %_ptr_Private_uint {mask} {word}") - self.emit(f"{w} = OpLoad %uint {p}") - self.emit(f"{b} = OpBitFieldUExtract %uint {w} {bit} {self.cu(1)}") - self.emit(f"{nz} = OpINotEqual %bool {b} {self.cu(0)}") - flags.append(nz) - return flags - - def saturate_int16(self, bits: str, signed: bool) -> str: - """Return the saturated integer as 16 bits in the low half of a uint.""" - half = self.tmp() - if signed: - value, clamped, raw = self.as_int(bits), self.tmp(), self.tmp() - self.emit(f"{clamped} = OpExtInst %int %glsl SClamp {value} {self.as_int(self.cu(0xFFFF8000))} " - f"{self.as_int(self.cu(0x7FFF))}") - self.emit(f"{raw} = OpBitcast %uint {clamped}") - self.emit(f"{half} = OpBitwiseAnd %uint {raw} {self.cu(0xFFFF)}") - else: - self.emit(f"{half} = OpExtInst %uint %glsl UMin {bits} {self.cu(0xFFFF)}") - return half - - def image_load_typed(self, dim, t1, iv, img, idx, dmask, vdata, lod, d16=False): - def fetch(image, _cls, ty): - res = self.tmp() - self.emit(f"{res} = OpImageFetch {ty} {image} {iv} Lod {lod}") - return res - self.image_read_typed(dim, t1, img, idx, dmask, vdata, d16, fetch) - - def image_load_coherent(self, dim, t1, iv, idx, dmask, vdata, d16): - """image_load with glc: a coherent read. On GFX10 a device-scope load is glc + dlc and a device-scope store - glc (Mesa ac_get_hw_cache_flags maps ACCESS_COHERENT to exactly these bits); the POPS pixel shaders read and - write their ordered images that way. Through the sampled array (image_load_typed) the read could not see - another invocation's store: sampled reads have no coherent form, and the interlock between POPS critical - sections only makes Coherent memory visible (Vulkan memory model, fragment shader interlock). So the read - goes through the storage view the stores write (OpImageRead, StorageImageReadWithoutFormat), and the - storage views are decorated Coherent (assemble).""" - di = self.STORE_DIMS[dim][0] - self.uses_store_views.add(di) - self.reads_store_views = True - self.coherent_images = True - - def view(cls): - ip, im = self.tmp(), self.tmp() - self.dynamic_storage_access(ip, f"%_ptr_UC_stv{cls}_{di}", f"%stv{cls}_{di}", idx) - self.emit(f"{im} = OpLoad %stimg{cls}_{di} {ip}") - return im - - def read(image, _cls, ty): - res = self.tmp() - self.emit(f"{res} = OpImageRead {ty} {image} {iv}") - return res - self.image_read_typed(dim, t1, None, idx, dmask, vdata, d16, read, view) - - def image_read_typed(self, dim, t1, img, idx, dmask, vdata, d16, read, view=None): - """Read an image using the component type selected by FORMAT in T# word 1. - read(image, cls, ty) emits the fetch or gather and returns its four components. The float view also - handles a lookup miss: index zero holds the RGBA8_UNORM fallback. view(cls) loads the image of class cls - (0 float, 1 uint, 2 sint); by default the sampled image img for float and, for UINT and SINT, typed aliases - of the dimension's sampled binding (SHADER-151), so no storage image feature is needed. - dmask selects the output components; d16 packs two per VGPR.""" - di = self.STORE_DIMS[dim][0] - if view is None: - self.uses_int_fetch.add(di) - - def view(cls): - if cls == 0: - return img - ip, im = self.tmp(), self.tmp() - self.dynamic_sampled_access(ip, f"%_ptr_UC_itx{cls}_{di}", f"%itx{cls}_{di}", idx) - self.emit(f"{im} = OpLoad %itximg{cls}_{di} {ip}") - return im - is_u, is_s = self.fmt_int_flags(t1) - # SHADER-308: d16 image results follow the same rounding rule as d16 typed buffer loads. UNORM/SNORM are the - # exact quotient rounded once (the two D16_NORM_HALFWAY f32 values are 1 ulp high through f32), and a - # 32-bit float channel is narrowed toward zero, not to nearest even. Measured on an RX 6700 (gfx1031). - if d16: - self.uses_d16_image = True - is_norm_fmt, is_f32_fmt = self.fmt_float_flags(t1) if d16 else (None, None) - hit = self.tmp() - self.emit(f"{hit} = OpINotEqual %bool {idx} {self.cu(0)}") - use_u, use_s = self.tmp(), self.tmp() - self.emit(f"{use_u} = OpLogicalAnd %bool {is_u} {hit}") - self.emit(f"{use_s} = OpLogicalAnd %bool {is_s} {hit}") - L = {k: self.tmp() + "_" + k for k in ("s", "rest", "e2", "u", "f", "e3")} - - def write(v4u, numeric_class): - xs = [] - for c in range(4): - if dmask >> c & 1: - x = self.tmp() - self.emit(f"{x} = OpCompositeExtract %uint {v4u} {c}") - if d16 and numeric_class: - x = self.saturate_int16(x, signed=(numeric_class == 2)) - xs.append(x) - if not d16: - for k, x in enumerate(xs): - self.dst({"k": "vgpr", "r": vdata["r"] + k, "n": 1}, x) - return - # D16 packs saturated integer or RTE floating-point halves, low half first. - for i in range(0, len(xs), 2): - dest = {"k": "vgpr", "r": vdata["r"] + i // 2, "n": 1} - if i + 1 == len(xs): - lo = (self.d16_norm_f16(xs[i], is_norm_fmt, is_f32_fmt) if numeric_class == 0 else xs[i]) - self.write_lo16(dest, lo) - continue - if numeric_class == 0: - hi_s, w = self.tmp(), self.tmp() - self.emit(f"{hi_s} = OpShiftLeftLogical %uint " - f"{self.d16_norm_f16(xs[i + 1], is_norm_fmt, is_f32_fmt)} {self.cu(16)}") - self.emit(f"{w} = OpBitwiseOr %uint {self.d16_norm_f16(xs[i], is_norm_fmt, is_f32_fmt)} {hi_s}") - else: - hi, w = self.tmp(), self.tmp() - self.emit(f"{hi} = OpShiftLeftLogical %uint {xs[i + 1]} {self.cu(16)}") - self.emit(f"{w} = OpBitwiseOr %uint {xs[i]} {hi}") - self.dst(dest, w) - - def read_integer(cls, ty): - im = view(cls) - b = self.tmp() - r = read(im, cls, ty) - self.emit(f"{b} = OpBitcast %v4uint_st {r}") - write(b, cls) - - self.emit(f"OpSelectionMerge {L['e2']} None") - self.emit(f"OpBranchConditional {use_s} {L['s']} {L['rest']}") - self.emit(f"{L['s']} = OpLabel") - read_integer(2, "%v4int_st") - self.emit(f"OpBranch {L['e2']}") - self.emit(f"{L['rest']} = OpLabel") - self.emit(f"OpSelectionMerge {L['e3']} None") - self.emit(f"OpBranchConditional {use_u} {L['u']} {L['f']}") - self.emit(f"{L['u']} = OpLabel") - read_integer(1, "%v4uint_st") - self.emit(f"OpBranch {L['e3']}") - self.emit(f"{L['f']} = OpLabel") - res = read(view(0), 0, "%v4float") - b = self.tmp() - self.emit(f"{b} = OpBitcast %v4uint_st {res}") - write(b, 0) - self.emit(f"OpBranch {L['e3']}") - self.emit(f"{L['e3']} = OpLabel") - self.emit(f"OpBranch {L['e2']}") - self.emit(f"{L['e2']} = OpLabel") - - def unpack_image_a16_uints(self, words: list[str]) -> list[str]: - """Unpack the unsigned address components of a samplerless MIMG instruction, low half first.""" - halves = [] - for word in words: - lo, hi = self.tmp(), self.tmp() - self.emit(f"{lo} = OpBitwiseAnd %uint {word} {self.cu(0xFFFF)}") - self.emit(f"{hi} = OpShiftRightLogical %uint {word} {self.cu(16)}") - halves.extend((lo, hi)) - return halves - - def image_store(self, a, mods, dim): - """image_store vData, vAddr, T#: write the dmask components to a storage image. The view is picked at run - time from T# word1 FORMAT [28:20]: *_UINT -> uint view, *_SINT -> sint view, anything else -> float view - (UNORM/SNORM/FLOAT convert from the float bits the shader wrote). Missing components are 0. - With d16, enabled components are packed two 16-bit values per consecutive VGPR (low half first): IEEE f16 - widened to f32 for float/norm views, zero-extended u16 for UINT views, and sign-extended i16 for SINT views.""" - # Cube storage images are bound as 6-layer 2D arrays (runtime/src/vulkan_bindless.h). - view_dim = "dim:SQ_RSRC_IMG_2D_ARRAY" if dim == "dim:SQ_RSRC_IMG_CUBE" else dim - if view_dim not in self.STORE_DIMS or any(m in mods for m in ("tfe", "lwe")): - raise Unsupported("image_store " + dim.split("SQ_RSRC_IMG_")[-1] + (" a16" if "a16" in mods else "") - + (" d16" if "d16" in mods else "")) - di, _, _, nc = self.STORE_DIMS[view_dim] - if "glc" in mods: - self.coherent_images = True # a coherent store (glc, device scope): see image_load_coherent - dm = next((m for m in mods if m.startswith("dmask:")), "dmask:0xf") - dmask = int(dm.split(":")[1], 0) - vdata, addr = a[0], self.addr_regs(a[1]) - if vdata.get("k") != "vgpr": - raise Unsupported("image_store vdata") - raw = [self.load_reg("vgpr", r) for r in addr] - if "a16" in mods: - raw = self.unpack_image_a16_uints(raw) - if len(raw) < nc: - raise Unsupported("image_store coords") - if "d16" in mods: - # Packed 16-bit data: enabled dmask components occupy consecutive 16-bit halves (low first) across - # ceil(popcount(dmask) / 2) VGPRs starting at vData. - n_en = sum((dmask >> c) & 1 for c in range(4)) - d16_regs = [self.load_reg("vgpr", vdata["r"] + i) for i in range((n_en + 1) // 2)] - f_pairs = [] - for reg in d16_regs: - v2 = self.tmp() - self.emit(f"{v2} = OpExtInst %v2float %glsl UnpackHalf2x16 {reg}") - f_pairs.append(v2) - fv, uv, sv = [], [], [] - pos = 0 - for c in range(4): - if (dmask >> c) & 1: - ri, hi = pos >> 1, pos & 1 - reg = d16_regs[ri] - fc, uc, sc = self.tmp(), self.tmp(), self.tmp() - self.emit(f"{fc} = OpCompositeExtract %float {f_pairs[ri]} {hi}") - self.emit(f"{uc} = OpBitFieldUExtract %uint {reg} {self.cu(16 * hi)} {self.cu(16)}") - self.emit(f"{sc} = OpBitFieldSExtract %uint {reg} {self.cu(16 * hi)} {self.cu(16)}") - fv.append(fc) - uv.append(uc) - sv.append(self.as_int(sc)) - pos += 1 - else: - fv.append(self.tof(self.cu(0))) - uv.append(self.cu(0)) - sv.append(self.as_int(self.cu(0))) - else: - # The enabled components come from consecutive VGPRs, in component order (dmask 0x9: R = vD, A = vD+1). - regs = iter(range(vdata["r"], vdata["r"] + 4)) - vals = [self.load_reg("vgpr", next(regs)) if dmask >> c & 1 else self.cu(0) for c in range(4)] - fv = [self.tof(v) for v in vals] - uv = vals - sv = [self.as_int(v) for v in vals] - coords = [self.as_int(c) for c in raw[:nc]] - idx = self.desc_lookup_sgpr(a[2], 8) - t1 = self.sgpr_word(a[2], 1) - self.uses_store_views.add(di) - for w in [16] + sum(self.int_format_masks(), []): # constants used by assemble's format masks - self.cu(w) - if nc == 1: - iv = coords[0] - else: - iv = self.tmp() - self.emit(f"{iv} = OpCompositeConstruct {'%v2int' if nc == 2 else '%v3int'} {' '.join(coords)}") - is_u, is_s = self.fmt_int_flags(t1) - v4f, v4u, v4s = self.tmp(), self.tmp(), self.tmp() - self.emit(f"{v4f} = OpCompositeConstruct %v4float {' '.join(fv)}") - self.emit(f"{v4u} = OpCompositeConstruct %v4uint_st {' '.join(uv)}") - self.emit(f"{v4s} = OpCompositeConstruct %v4int_st {' '.join(sv)}") - act = self.active_b() - L = {k: self.tmp() + "_" + k for k in ("do", "end", "s", "rest", "e2", "u", "f", "e3")} - - def write(cls, texel): - ip, img = self.tmp(), self.tmp() - self.dynamic_storage_access(ip, f"%_ptr_UC_stv{cls}_{di}", f"%stv{cls}_{di}", idx) - self.emit(f"{img} = OpLoad %stimg{cls}_{di} {ip}") - self.emit(f"OpImageWrite {img} {iv} {texel}") - - self.emit(f"OpSelectionMerge {L['end']} None") - self.emit(f"OpBranchConditional {act} {L['do']} {L['end']}") - self.emit(f"{L['do']} = OpLabel") - self.emit(f"OpSelectionMerge {L['e2']} None") - self.emit(f"OpBranchConditional {is_s} {L['s']} {L['rest']}") - self.emit(f"{L['s']} = OpLabel") - write(2, v4s) - self.emit(f"OpBranch {L['e2']}") - self.emit(f"{L['rest']} = OpLabel") - self.emit(f"OpSelectionMerge {L['e3']} None") - self.emit(f"OpBranchConditional {is_u} {L['u']} {L['f']}") - self.emit(f"{L['u']} = OpLabel") - write(1, v4u) - self.emit(f"OpBranch {L['e3']}") - self.emit(f"{L['f']} = OpLabel") - write(0, v4f) - self.emit(f"OpBranch {L['e3']}") - self.emit(f"{L['e3']} = OpLabel") - self.emit(f"OpBranch {L['e2']}") - self.emit(f"{L['e2']} = OpLabel") - self.emit(f"OpBranch {L['end']}") - self.emit(f"{L['end']} = OpLabel") - - def resinfo_words(self, img, level, array_query, word3): - """[width, height, depth, levels] (int ids) of image_get_resinfo for the uint mip level `level`, as RDNA2 - returns them (measured on gfx1036 with tools/image_query_probe.py, SHADER-388): the level count of the view; - past the last level (level >= levels, unsigned) width, height and depth are 0, and the size is not queried - there (OpImageQuerySizeLod is undefined past the view's levels); a 2D image's depth word is 0; a 2D array's - is its layer count minified like a 3D depth, max(1, layers >> (BASE_LEVEL + level)), BASE_LEVEL being T# - word 3 [15:12] (`word3`, a uint id), which is also the view's first level.""" - zero = self.as_int(self.cu(0)) - lv, lvu, ok, safe, sz = (self.tmp() for _ in range(5)) - self.emit(f"{lv} = OpImageQueryLevels %int {img}") - self.emit(f"{lvu} = OpBitcast %uint {lv}") - self.emit(f"{ok} = OpULessThan %bool {level} {lvu}") - lod = self.as_int(level) - self.emit(f"{safe} = OpSelect %int {ok} {lod} {zero}") - self.emit(f"{sz} = OpImageQuerySizeLod {'%v3int' if array_query else '%v2int'} {img} {safe}") - vals = [] - for axis in range(3 if array_query else 2): - extent = self.tmp() - self.emit(f"{extent} = OpCompositeExtract %int {sz} {axis}") - vals.append(extent) - if array_query: - base, shift, layers, mini, at_least = (self.tmp() for _ in range(5)) - self.emit(f"{base} = OpBitFieldUExtract %uint {word3} {self.cu(12)} {self.cu(4)}") - self.emit(f"{shift} = OpIAdd %uint {base} {level}") - self.emit(f"{layers} = OpBitcast %uint {vals[2]}") - self.emit(f"{mini} = OpShiftRightLogical %uint {layers} {shift}") - self.emit(f"{at_least} = OpExtInst %uint %glsl UMax {mini} {self.cu(1)}") - vals[2] = self.as_int(at_least) - else: - vals.append(zero) - for i in range(3): - if i < 2 or array_query: - kept = self.tmp() - self.emit(f"{kept} = OpSelect %int {ok} {vals[i]} {zero}") - vals[i] = kept - return vals + [lv] - - def emit_image_atomic_extra(self, op, ptr_ty, arr_var, idx, iv, vdata, mods): - """Lower 32-bit image_atomic_{swap,inc,dec,fmin,fmax,fcmpswap} on an r32ui storage image (2D or 3D). - Inactive lanes skip the op and preserve vdata. CAS loops use OpAtomicLoad (valid on Image pointers) + - OpAtomicCompareExchange, requiring no shader float atomic extension.""" - need_n = 2 if op == "image_atomic_fcmpswap" else 1 - if vdata["k"] != "vgpr" or vdata.get("n", 1) != need_n: - raise Unsupported(op + " operands") - val = self.load_reg("vgpr", vdata["r"]) - cmpv = self.load_reg("vgpr", vdata["r"] + 1) if op == "image_atomic_fcmpswap" else None - act = self.active_b() - lbl_do, lbl_end = self.tmp() + "_do", self.tmp() + "_end" - self.emit(f"OpSelectionMerge {lbl_end} None") - self.emit(f"OpBranchConditional {act} {lbl_do} {lbl_end}") - self.emit(f"{lbl_do} = OpLabel") - ip, tp = self.tmp(), self.tmp() - self.dynamic_storage_access(ip, ptr_ty, arr_var, idx) - self.emit(f"{tp} = OpImageTexelPointer %_ptr_Image_uint {ip} {iv} {self.cu(0)}") - sc, sem = self.cu(1), self.cu(0) - if op == "image_atomic_swap": - old = self.tmp() - self.emit(f"{old} = OpAtomicExchange %uint {tp} {sc} {sem} {val}") - if "glc" in mods: - self.dst({"k": "vgpr", "r": vdata["r"], "n": 1}, old) - elif op == "image_atomic_fcmpswap": - # IEEE-754 binary32 ordered equality on raw 32-bit words (denormal-safe on drivers with - # shaderDenormPreserveFloat32 = false): equal iff neither is NaN and (cur == cmpv or both are +-0.0). - abs_cmp, nan_cmp, init = self.tmp(), self.tmp(), self.tmp() - self.emit(f"{abs_cmp} = OpBitwiseAnd %uint {cmpv} {self.cu(0x7FFFFFFF)}") - self.emit(f"{nan_cmp} = OpUGreaterThan %bool {abs_cmp} {self.cu(0x7F800000)}") - self.emit(f"{init} = OpAtomicLoad %uint {tp} {sc} {sem}") - lbl_hdr, lbl_try, lbl_after, lbl_cont, lbl_exit = ( - self.tmp() + s for s in ("_hdr", "_try", "_after", "_cont", "_exit")) - self.emit(f"OpBranch {lbl_hdr}") - self.emit(f"{lbl_hdr} = OpLabel") - cur, got, abs_cur, nan_cur, any_nan, not_nan, same_bits, or_abs, both_zero, eq_val, eq_f = ( - self.tmp() for _ in range(11)) - self.emit(f"{cur} = OpPhi %uint {init} {lbl_do} {got} {lbl_cont}") - self.emit(f"{abs_cur} = OpBitwiseAnd %uint {cur} {self.cu(0x7FFFFFFF)}") - self.emit(f"{nan_cur} = OpUGreaterThan %bool {abs_cur} {self.cu(0x7F800000)}") - self.emit(f"{any_nan} = OpLogicalOr %bool {nan_cur} {nan_cmp}") - self.emit(f"{not_nan} = OpLogicalNot %bool {any_nan}") - self.emit(f"{same_bits} = OpIEqual %bool {cur} {cmpv}") - self.emit(f"{or_abs} = OpBitwiseOr %uint {abs_cur} {abs_cmp}") - self.emit(f"{both_zero} = OpIEqual %bool {or_abs} {self.cu(0)}") - self.emit(f"{eq_val} = OpLogicalOr %bool {same_bits} {both_zero}") - self.emit(f"{eq_f} = OpLogicalAnd %bool {not_nan} {eq_val}") - self.emit(f"OpLoopMerge {lbl_exit} {lbl_cont} None") - self.emit(f"OpBranchConditional {eq_f} {lbl_try} {lbl_exit}") - self.emit(f"{lbl_try} = OpLabel") - self.emit(f"{got} = OpAtomicCompareExchange %uint {tp} {sc} {sem} {sem} {val} {cur}") - done = self.tmp() - self.emit(f"{done} = OpIEqual %bool {got} {cur}") - self.emit(f"OpSelectionMerge {lbl_after} None") - self.emit(f"OpBranchConditional {done} {lbl_exit} {lbl_after}") - self.emit(f"{lbl_after} = OpLabel") - self.emit(f"OpBranch {lbl_cont}") - self.emit(f"{lbl_cont} = OpLabel") - self.emit(f"OpBranch {lbl_hdr}") - self.emit(f"{lbl_exit} = OpLabel") - if "glc" in mods: - self.dst({"k": "vgpr", "r": vdata["r"], "n": 1}, cur) - else: - val_f = None - if op in ("image_atomic_fmin", "image_atomic_fmax"): - val_f = self.tmp() - self.emit(f"{val_f} = OpBitcast %float {val}") - init = self.tmp() - self.emit(f"{init} = OpAtomicLoad %uint {tp} {sc} {sem}") - lbl_hdr, lbl_cont, lbl_exit = (self.tmp() + s for s in ("_hdr", "_cont", "_exit")) - self.emit(f"OpBranch {lbl_hdr}") - self.emit(f"{lbl_hdr} = OpLabel") - cur, got = self.tmp(), self.tmp() - self.emit(f"{cur} = OpPhi %uint {init} {lbl_do} {got} {lbl_cont}") - if op == "image_atomic_inc": - wrap, step, new_u = self.tmp(), self.tmp(), self.tmp() - self.emit(f"{wrap} = OpUGreaterThanEqual %bool {cur} {val}") - self.emit(f"{step} = OpIAdd %uint {cur} {self.cu(1)}") - self.emit(f"{new_u} = OpSelect %uint {wrap} {self.cu(0)} {step}") - elif op == "image_atomic_dec": - is_z, gt, wrap, step, new_u = (self.tmp() for _ in range(5)) - self.emit(f"{is_z} = OpIEqual %bool {cur} {self.cu(0)}") - self.emit(f"{gt} = OpUGreaterThan %bool {cur} {val}") - self.emit(f"{wrap} = OpLogicalOr %bool {is_z} {gt}") - self.emit(f"{step} = OpISub %uint {cur} {self.cu(1)}") - self.emit(f"{new_u} = OpSelect %uint {wrap} {val} {step}") - else: - cur_f, new_f, new_u = self.tmp(), self.tmp(), self.tmp() - self.emit(f"{cur_f} = OpBitcast %float {cur}") - glsl_op = "NMin" if op == "image_atomic_fmin" else "NMax" - self.emit(f"{new_f} = OpExtInst %float %glsl {glsl_op} {cur_f} {val_f}") - self.emit(f"{new_u} = OpBitcast %uint {new_f}") - done = self.tmp() - self.emit(f"{got} = OpAtomicCompareExchange %uint {tp} {sc} {sem} {sem} {new_u} {cur}") - self.emit(f"{done} = OpIEqual %bool {got} {cur}") - self.emit(f"OpLoopMerge {lbl_exit} {lbl_cont} None") - self.emit(f"OpBranchConditional {done} {lbl_exit} {lbl_cont}") - self.emit(f"{lbl_cont} = OpLabel") - self.emit(f"OpBranch {lbl_hdr}") - self.emit(f"{lbl_exit} = OpLabel") - if "glc" in mods: - self.dst({"k": "vgpr", "r": vdata["r"], "n": 1}, cur) - self.emit(f"OpBranch {lbl_end}") - self.emit(f"{lbl_end} = OpLabel") - - def image_misc(self, op, a, mods): - """Query sampled image dimensions, load mip texels and handle storage image operations.""" - if a and a[0]["k"] != "vgpr": # `off`, an SGPR or a constant where the VGPR range of the data goes - raise Unsupported(op + " data") - dim = next((m for m in mods if m.startswith("dim:")), "dim:SQ_RSRC_IMG_2D") - array_query = op == "image_get_resinfo" and dim == "dim:SQ_RSRC_IMG_2D_ARRAY" - is_atomic = op in self.IMG_ATOMICS or op == "image_atomic_cmpswap" or op in self.IMG_ATOMICS_EXTRA - is3d_atomic = dim == "dim:SQ_RSRC_IMG_3D" and is_atomic - if op == "image_store": - self.image_store(a, mods, dim) - return - if op == "image_load_mip" and "glc" in mods: - # A coherent read of one mip: image_load_coherent reads a storage view, which has one level. - raise Unsupported("image_load_mip glc") - if op == "image_load_mip" and dim == "dim:SQ_RSRC_IMG_3D" and "a16" not in mods: - # x, y, z, mip from a 3D sampled image (binding 6) - if "d16" in mods and ("tfe" in mods or "lwe" in mods): - raise Unsupported("image_load_mip d16 status") - vdata, addr = a[0], self.addr_regs(a[1]) - if len(addr) < 4: - raise Unsupported("image_load_mip coords") - idx = self.desc_lookup_sgpr(a[2], 8) - self.uses_tex_3d = True - ip, img, iv = self.tmp(), self.tmp(), self.tmp() - self.dynamic_sampled_access(ip, "%_ptr_UC_img3", "%images_3d", idx) - self.emit(f"{img} = OpLoad %img3d {ip}") - xs = [self.as_int(self.load_reg("vgpr", r)) for r in addr[:4]] - self.emit(f"{iv} = OpCompositeConstruct %v3int {xs[0]} {xs[1]} {xs[2]}") - dm = next((m for m in mods if m.startswith("dmask:")), "dmask:0x1") - self.image_load_typed(dim, self.sgpr_word(a[2], 1), iv, img, idx, int(dm.split(":")[1], 0), - vdata, xs[3], d16="d16" in mods) - return - packed_mip = op == "image_load_mip" and "tfe" not in mods and "lwe" not in mods - if ((dim != "dim:SQ_RSRC_IMG_2D" and not (is3d_atomic or array_query)) - or ("a16" in mods and not (is_atomic or packed_mip)) - or ("d16" in mods and op != "image_load_mip")): - raise Unsupported(op + " " + dim.split("SQ_RSRC_IMG_")[-1]) - vdata, addr = a[0], self.addr_regs(a[1]) - idx = self.desc_lookup_sgpr(a[2], 8) - - def atomic_coords(nc): - raw = [self.load_reg("vgpr", r) for r in addr] - if "a16" in mods: - # 16-bit packed unsigned coordinates: two per VGPR, low half first (same as image_store). - halves = [] - for c in raw: - lo, hi = self.tmp(), self.tmp() - self.emit(f"{lo} = OpBitwiseAnd %uint {c} {self.cu(0xFFFF)}") - self.emit(f"{hi} = OpShiftRightLogical %uint {c} {self.cu(16)}") - halves += [lo, hi] - raw = halves - if len(raw) < nc: - raise Unsupported(op + " coords") - return [self.as_int(c) for c in raw[:nc]] - - if is_atomic: - # 2D (binding 4) or 3D (binding 7) r32ui storage image atomics. - # Guard OpAccessChain / OpImageTexelPointer / OpAtomic* inside `if (active)` so inactive lanes never - # execute spurious RMWs or dereference uninitialized descriptors/coordinates. - if is3d_atomic: - self.uses_storage3d = True - coords = atomic_coords(3) - iv = self.tmp() - self.emit(f"{iv} = OpCompositeConstruct %v3int {coords[0]} {coords[1]} {coords[2]}") - ptr_ty, arr_var = "%_ptr_UC_simg3", "%simages3d" - else: - self.uses_storage = True - coords = atomic_coords(2) - iv = self.tmp() - self.emit(f"{iv} = OpCompositeConstruct %v2int {coords[0]} {coords[1]}") - ptr_ty, arr_var = "%_ptr_UC_simg", "%simages" - if op in self.IMG_ATOMICS_EXTRA: - self.emit_image_atomic_extra(op, ptr_ty, arr_var, idx, iv, vdata, mods) - return - if op == "image_atomic_cmpswap": - if vdata["k"] != "vgpr" or vdata.get("n", 1) != 2: - raise Unsupported(op + " data") - elif vdata["k"] != "vgpr": - raise Unsupported(op + " data") - # Two-VGPR dmask:0x3 forms of the nine standard ops are 64-bit atomics; keep main's low-dword - # 32-bit behavior here so corpus translation count does not drop while Int64ImageEXT + fallback - # is handled separately. - val = self.load_reg("vgpr", vdata["r"]) - cmpv = self.load_reg("vgpr", vdata["r"] + 1) if op == "image_atomic_cmpswap" else None - act = self.active_b() - do, end = self.tmp() + "_do", self.tmp() + "_end" - self.emit(f"OpSelectionMerge {end} None") - self.emit(f"OpBranchConditional {act} {do} {end}") - self.emit(f"{do} = OpLabel") # inactive lanes don't touch memory - ip, tp, old = self.tmp(), self.tmp(), self.tmp() - self.dynamic_storage_access(ip, ptr_ty, arr_var, idx) - self.emit(f"{tp} = OpImageTexelPointer %_ptr_Image_uint {ip} {iv} {self.cu(0)}") - if op == "image_atomic_cmpswap": - self.emit(f"{old} = OpAtomicCompareExchange %uint {tp} {self.cu(1)} {self.cu(0)} {self.cu(0)} {val} {cmpv}") - else: - spv = self.IMG_ATOMICS[op] - self.emit(f"{old} = {spv} %uint {tp} {self.cu(1)} {self.cu(0)} {val}") - if "glc" in mods: - self.dst({"k": "vgpr", "r": vdata["r"], "n": 1}, old) - self.emit(f"OpBranch {end}") - self.emit(f"{end} = OpLabel") - return - ip, img = self.tmp(), self.tmp() - if array_query: - self.uses_tex_array = True - self.dynamic_sampled_access(ip, "%_ptr_UC_imga", "%images_arr", idx) - self.emit(f"{img} = OpLoad %img2da {ip}") - else: - self.dynamic_sampled_access(ip, "%_ptr_UC_img", "%images", idx) - self.emit(f"{img} = OpLoad %img2d {ip}") - dm = next((m for m in mods if m.startswith("dmask:")), "dmask:0x1") - dmask = int(dm.split(":")[1], 0) - self.uses_query = True - if op == "image_get_resinfo": - vals = self.resinfo_words(img, self.load_reg("vgpr", addr[0]), array_query, - self.load_reg("sgpr", a[2]["r"] + 3)) - out = 0 - for c in range(4): - if dmask >> c & 1: - u = self.tmp() - self.emit(f"{u} = OpBitcast %uint {vals[c]}") - self.dst({"k": "vgpr", "r": vdata["r"] + out, "n": 1}, u) - out += 1 - return - # image_load_mip: x, y, mip, with the same typed SRV as image_load. - packed = "a16" in mods - if len(addr) < (2 if packed else 3): - raise Unsupported("image_load_mip coords") - if packed: - words = [self.load_reg("vgpr", r) for r in addr[:2]] - xs = [self.as_int(c) for c in self.unpack_image_a16_uints(words)[:3]] - else: - xs = [self.as_int(self.load_reg("vgpr", r)) for r in addr[:3]] - iv = self.tmp() - self.emit(f"{iv} = OpCompositeConstruct %v2int {xs[0]} {xs[1]}") - self.image_load_typed(dim, self.sgpr_word(a[2], 1), iv, img, idx, dmask, vdata, xs[2], d16="d16" in mods) - - - def interp_pair_src(self, op, a, ins): - """SHADER-177: the VGPR source of a v_interp_p1/p2 is the barycentric coordinate that op interpolates - with — p1 reads I = v0, p2 reads J = v1, per op. The model returns the attribute's interpolated value, - which is only that when the register really holds that coordinate: the hardware register, or a plain - v_mov copy rooted at it (self.v_interp_copy, from interp_copy_sources, which tracks each copy's root). - Anything else — the other coordinate, a copy rooted at the other one — is refused, not guessed at. - A computed-I/J site (ins["ij"], interp_ij_analysis) is exempt: its operand is a value the program - wrote, and attribute() weights the interpolation with that value.""" - if ins.get("ij") is not None: - return # computed-I/J site: the analysis vetted the source; attribute() weights with it - want, role = (0, "I") if op.startswith("v_interp_p1") else (1, "J") - s = a[1] if len(a) > 1 else None - c = self.v_interp_copy.get(s["r"]) if (s is not None and s.get("k") == "vgpr") else None - if not (s and s.get("k") == "vgpr" and s.get("n", 1) == 1 and - (s["r"] == want or (c is not None and c[0] == want and c[1] < ins.get("seq", 1 << 62)))): - what = f"v{s['r']}" if s is not None and s.get("k") == "vgpr" else "operand" - raise Unsupported(f"{op} {role} source {what}: only v{want} (or a plain v_mov copy of it) is modelled") - - def interp_weights(self, ins): - """(i, j) float ids for a computed-I/J v_interp site, or None for an untouched one (SHADER-177). - - The pair's p1 loads both operand registers and records its I; the p2 reuses that I and loads its - J fresh. The program may rewrite an operand between the two ops (corpus form: J is set up after - the p1), and hardware's final value uses the I of the p1 with the J of the p2. The p1's own - full-sum value is dead: nothing may read the partial between the ops (interp_ij_analysis).""" - tag = ins.get("ij") - if tag is None: - return None - kind, key, i_reg, j_reg = tag - if kind == "p1": - i, j = self.pair_value(i_reg), self.pair_value(j_reg) - self.ij_capture[key] = i - return i, j - cap = self.ij_capture.get(key) - if cap is None: - raise Unsupported("computed I/J pair: p2 emitted before its p1") - return cap, self.pair_value(j_reg) - - def pair_value(self, r): - """The value VGPR r holds now, as a float: the f32 bits the program last stored there.""" - u = self.load_reg("vgpr", r) - t = self.tmp() - self.emit(f"{t} = OpBitcast %float {u}") - return t - - def attribute(self, n, comp, flat=False, half=None, ij=None, vertex_delta=None): - """Component `comp` of fragment input attribute n (declared as a vec4 Input at Location n). - - An attribute in per_vertex is a PerVertexKHR vec4[3] of the producer's raw 32-bit words. For a packed - attribute, `half` 0/1 decodes its low/high f16 at each vertex; None keeps the - word as an f32; the three values are then weighted as AMD does, P0 + i(P1 - P0) + j(P2 - P0) with i, j = - BaryCoordKHR.y, .z, or vertex 0's taken when `flat`. `ij` overrides the weights with the given SPIR-V - values (computed-I/J sites, SHADER-177: the pair the program wrote into the operand registers). - `vertex_delta` 1/2 returns P1 - P0 / P2 - P0 instead (v_interp_mov_f32 p10/p20; n must be in per_vertex). - - --f16-interp-fallback: an f16 read (`half` 0/1) of an attribute in f16_halves is component `comp` of the smooth - input at f16_half_location(n, half), which the producer fills with that half decoded to f32 (F16_HALVES). - Other reads of such an attribute take the raw word as on any location (smooth, or flat = provoking vertex).""" - if half is not None and n in self.f16_halves: - name = f"%in_f16h{n}_{half}" - self.inputs.setdefault(name, None) # resolved in assemble() once every raw attribute is known - self.interpolated.add(name) - p, v = self.tmp(), self.tmp() - self.emit(f"{p} = OpAccessChain %_ptr_Input_float {name} {self.cu(comp)}") - self.emit(f"{v} = OpLoad %float {p}") - return v - name = f"%in_attr{n}" - self.inputs[name] = n - if not flat: - self.interpolated.add(name) - if n not in self.per_vertex: - p, v = self.tmp(), self.tmp() - self.emit(f"{p} = OpAccessChain %_ptr_Input_float {name} {self.cu(comp)}") - self.emit(f"{v} = OpLoad %float {p}") - return v - self.cu(3) # the array length - pv = [] - for k in range(1 if flat else 3): - p, v = self.tmp(), self.tmp() - self.emit(f"{p} = OpAccessChain %_ptr_Input_float {name} {self.cu(k)} {self.cu(comp)}") - self.emit(f"{v} = OpLoad %float {p}") - if half is not None: - h2, w = self.tmp(), self.tmp() - self.emit(f"{h2} = OpExtInst %v2float %glsl UnpackHalf2x16 {self.tou(v)}") - self.emit(f"{w} = OpCompositeExtract %float {h2} {half}") - v = w - pv.append(v) - if flat: - return pv[0] - if vertex_delta is not None: - d = self.tmp() - self.emit(f"{d} = OpFSub %float {pv[vertex_delta]} {pv[0]}") - return d - if ij is not None: - i, j = ij - else: - bc = self.tmp() - self.emit(f"{bc} = OpLoad %v3float %bary") - i, j = self.tmp(), self.tmp() - self.emit(f"{i} = OpCompositeExtract %float {bc} 1") - self.emit(f"{j} = OpCompositeExtract %float {bc} 2") - d1, d2, m1, m2, s, r = (self.tmp() for _ in range(6)) - self.emit(f"{d1} = OpFSub %float {pv[1]} {pv[0]}") - self.emit(f"{d2} = OpFSub %float {pv[2]} {pv[0]}") - self.emit(f"{m1} = OpFMul %float {d1} {i}") - self.emit(f"{s} = OpFAdd %float {pv[0]} {m1}") - self.emit(f"{m2} = OpFMul %float {d2} {j}") - self.emit(f"{r} = OpFAdd %float {s} {m2}") - return r - - def texel_offset_fold(self, img, si, uv, off, n_off, ncoord, kind, implicit, lod, bias, s_op): - """--texel-offset-fallback: return (uv + offset / size of the sampled level, implicit-LOD gradients or None). - - The level is 0 for _lz / _c_lz (and for implicit samples outside the PS, which sample LOD 0), the given LOD - for _l, and OpImageQueryLod's for implicit samples (plus the bias for _b), rounded the way the S#'s - MIP_FILTER (word 2 [27:26]) selects a level and clamped to the image's levels: floored for linear, nearest - with a tie rounding up (floor(lod + 0.5), as an RTX 5070 samples LOD 0.5 at mip 1 and image_query_probe.py - records for RDNA2) for point and for the value 3, which the runtime also samples as nearest, and 0 for - none, whose LOD the runtime holds in [0, 0.25] - (gfx10_descriptors.h vulkan_sampler). Texel offsets apply before wrapping and clamping, and an integer - offset commutes with them, so the shift is exact for any address mode at that level. Only a trilinear blend - of two levels differs: the coarser level moves by offset / 2 of its texels instead of offset. Implicit - samples become Grad samples with the derivatives of the original coordinate (scaled by 2^bias for _b): the - LOD and anisotropy are those of the unshifted sample, even when the offset changes from pixel to pixel.""" - self.uses_query = True - ci = lambda v: self.as_int(self.cu(v)) - lv, lvm = self.tmp(), self.tmp() - self.emit(f"{lv} = OpImageQueryLevels %int {img}") - self.emit(f"{lvm} = OpISub %int {lv} {ci(1)}") - spatial = n_off # 1D: 1, 2D / 2D array: 2, 3D: 3 (array layer excluded) - vf = {1: "%float", 2: "%v2float", 3: "%v3float"}[spatial] - vi = {1: "%int", 2: "%v2int", 3: "%v3int"}[spatial] - uvs = uv - if ncoord > spatial: # 2D array: the spatial part of (u, v, layer) - uvs = self.tmp() - self.emit(f"{uvs} = OpVectorShuffle %v2float {uv} {uv} 0 1") - level_f = None - if kind == "_l": - level_f = lod if lod is not None else "%f0" - elif implicit: - q, qx = self.tmp(), self.tmp() - self.emit(f"{q} = OpImageQueryLod %v2float {si} {uvs}") - self.emit(f"{qx} = OpCompositeExtract %float {q} 0") - level_f = qx - if kind in ("_b", "_c_b") and bias is not None: - qb = self.tmp() - self.emit(f"{qb} = OpFAdd %float {qx} {bias}") - level_f = qb - elif kind in ("_b", "_c_b"): - level_f = lod if lod is not None else bias - mip = None - if level_f is not None: - lit = self.sgpr_imm.get(s_op["r"] + 2) - if lit is not None: - mip = lit >> 26 & 3 - else: - mip = self.tmp() - self.emit(f"{mip} = OpBitFieldUExtract %uint {self.load_reg('sgpr', s_op['r'] + 2)} " - f"{self.cu(26)} {self.cu(2)}") - if mip == 0: - level_f = None - if level_f is None: - level = ci(0) - else: - static = isinstance(mip, int) - fl, li = self.tmp(), self.tmp() # linear: the finer of the two blended levels - self.emit(f"{fl} = OpExtInst %float %glsl Floor {level_f}") - self.emit(f"{li} = OpConvertFToS %int {fl}") - if not static or mip != 2: # point (and 3): nearest level, a tie rounds up - # floor + (fraction >= 0.5), not floor(lod + 0.5): lod - floor(lod) is exact in binary32, the sum - # is not (0x3f000001 + 0.5 rounds to 1.0, and 0x3effffff + 0.5 rounds up to 1.0 as well). - fr, up, inc, near = self.tmp(), self.tmp(), self.tmp(), self.tmp() - self.emit(f"{fr} = OpFSub %float {level_f} {fl}") - self.emit(f"{up} = OpFOrdGreaterThanEqual %bool {fr} {self.fconst(0.5)}") - self.emit(f"{inc} = OpSelect %int {up} {ci(1)} {ci(0)}") - self.emit(f"{near} = OpIAdd %int {li} {inc}") - if static: - li = near - else: - lin, none, pick, sel = self.tmp(), self.tmp(), self.tmp(), self.tmp() - self.emit(f"{lin} = OpIEqual %bool {mip} {self.cu(2)}") - self.emit(f"{pick} = OpSelect %int {lin} {li} {near}") - self.emit(f"{none} = OpIEqual %bool {mip} {self.cu(0)}") - self.emit(f"{sel} = OpSelect %int {none} {ci(0)} {pick}") - li = sel - lo = self.tmp() - self.emit(f"{lo} = OpExtInst %int %glsl SClamp {li} {ci(0)} {lvm}") - level = lo - # Size of that level: 1D int, 2D v2int, 2D array / 3D v3int (array: width, height, layers). - qtype = "%int" if ncoord == 1 else "%v3int" if ncoord == 3 else "%v2int" - sz = self.tmp() - self.emit(f"{sz} = OpImageQuerySizeLod {qtype} {img} {level}") - if qtype == "%v3int" and spatial == 2: - szs = self.tmp() - self.emit(f"{szs} = OpVectorShuffle %v2int {sz} {sz} 0 1") - sz = szs - szf, offf, sh, uvn = self.tmp(), self.tmp(), self.tmp(), self.tmp() - self.emit(f"{szf} = OpConvertSToF {vf} {sz}") - self.emit(f"{offf} = OpConvertSToF {vf} {off}") - self.emit(f"{sh} = OpFDiv {vf} {offf} {szf}") - self.emit(f"{uvn} = OpFAdd {vf} {uvs} {sh}") - out = uvn - if ncoord > spatial: - layer, full = self.tmp(), self.tmp() - self.emit(f"{layer} = OpCompositeExtract %float {uv} 2") - self.emit(f"{full} = OpCompositeConstruct %v3float {uvn} {layer}") - out = full - grads = None - if implicit: - dx, dy = self.tmp(), self.tmp() - self.emit(f"{dx} = OpDPdx {vf} {uvs}") - self.emit(f"{dy} = OpDPdy {vf} {uvs}") - if kind in ("_b", "_c_b") and bias is not None: - e, ev, sdx, sdy = self.tmp(), self.tmp(), self.tmp(), self.tmp() - self.emit(f"{e} = OpExtInst %float %glsl Exp2 {bias}") - if spatial == 1: - self.emit(f"{sdx} = OpFMul %float {dx} {e}") - self.emit(f"{sdy} = OpFMul %float {dy} {e}") - else: - self.emit(f"{sdx} = OpVectorTimesScalar {vf} {dx} {e}") - self.emit(f"{sdy} = OpVectorTimesScalar {vf} {dy} {e}") - dx, dy = sdx, sdy - grads = (dx, dy) - return out, grads - - def as_int(self, u): - i = self.tmp() - self.emit(f"{i} = OpBitcast %int {u}") - return i - - # ---- legacy (merged ES/GS) geometry shader on LDS rings ---- - # Inputs: input vertex i sits at the dword offset the system VGPRs give (v0 lo/hi, v1 lo); the entry sets them - # to 64*i, so an LDS read at byte address A + offset is vertex A >> 8, dword ((offset/4) mod 64) = 4*reg + comp - # of the ES output (= the GS input signature register). Outputs: every LDS write goes to the per-lane GSVS - # area: emitted vertex k is dwords [k*4*nreg, (k+1)*4*nreg), dword = 4*reg + comp of the GS output signature - # (checked on $GS_VoxelizeGeneric: 20 dwords = 5 output registers, writes match every declared mask). - # EMIT copies slot to the outputs and emits; CUT ends the strip. - GS_VTX_DW = 64 - - def gs_when_active(self, instr): - act = self.active_b() - do, end = self.tmp() + "_do", self.tmp() + "_end" - self.emit(f"OpSelectionMerge {end} None") - self.emit(f"OpBranchConditional {act} {do} {end}") - self.emit(f"{do} = OpLabel") - self.emit(instr) - self.emit(f"OpBranch {end}") - self.emit(f"{end} = OpLabel") - - def gs_ds(self, op, a, mods): - nreg = self.gs["nreg"] - if op in ("ds_read_b32", "ds_read_b64", "ds_read2_b32", "ds_read_b128", "ds_read_b96"): - if op == "ds_read2_b32": - dws = [self.mod_int(mods, "offset0", 0), self.mod_int(mods, "offset1", 0)] - else: - n = {"ds_read_b32": 1, "ds_read_b64": 2, "ds_read_b96": 3, "ds_read_b128": 4}[op] - base = self.mod_int(mods, "offset", 0) - if base % 4: - raise Unsupported("gs lds read alignment") - dws = [base // 4 + k for k in range(n)] - addr = self.src_u(a[1]) - vtx = self.tmp() - self.emit(f"{vtx} = OpShiftRightLogical %uint {addr} {self.cu(8)}") - for k, dw in enumerate(dws): - dw %= self.GS_VTX_DW - reg, comp = dw // 4, dw % 4 - regs = {r: sv for r, sv in self.gs["in"]} - if reg in regs: - var = "%gs_in_pos" if regs[reg] == 1 else f"%gs_in{reg}" - pp, v4, c = self.tmp(), self.tmp(), self.tmp() - self.emit(f"{pp} = OpAccessChain %_ptr_Input_v4 {var} {vtx}") - self.emit(f"{v4} = OpLoad %v4float {pp}") - self.emit(f"{c} = OpCompositeExtract %float {v4} {comp}") - val = self.tou(c) - else: - val = self.cu(0) - self.dst({"k": "vgpr", "r": a[0]["r"] + k, "n": 1}, val) - return - if op in ("ds_write_b32", "ds_write2_b32", "ds_write_b64"): - if op == "ds_write2_b32": - items = [(self.mod_int(mods, "offset0", 0), a[1]), (self.mod_int(mods, "offset1", 0), a[2])] - elif op == "ds_write_b64": - base = self.mod_int(mods, "offset", 0) // 4 - items = [(base, {"k": "vgpr", "r": a[1]["r"], "n": 1}), (base + 1, {"k": "vgpr", "r": a[1]["r"] + 1, "n": 1})] - else: - items = [(self.mod_int(mods, "offset", 0) // 4, a[1])] - for dw, src in items: - slot, rem = divmod(dw, 4 * nreg) - if slot >= self.gs["maxv"]: - raise Unsupported("gs output slot") - reg, comp = rem // 4, rem % 4 - v = self.tof(self.src_u(src)) - pp, old, new, sel = self.tmp(), self.tmp(), self.tmp(), self.tmp() - self.emit(f"{pp} = OpAccessChain %_ptr_Function_v4_gs %gs_stage {self.cu(slot * nreg + reg)}") - self.emit(f"{old} = OpLoad %v4float {pp}") - self.emit(f"{new} = OpCompositeInsert %v4float {v} {old} {comp}") - self.emit(f"{sel} = OpSelect %v4float {self.active_b()} {new} {old}") - self.emit(f"OpStore {pp} {sel}") - return - raise Unsupported(op + " in gs") - - def gs_emit(self, *, end_primitive: bool) -> None: - nreg = self.gs["nreg"] - act = self.active_b() - do, end = self.tmp() + "_do", self.tmp() + "_end" - self.emit(f"OpSelectionMerge {end} None") - self.emit(f"OpBranchConditional {act} {do} {end}") - self.emit(f"{do} = OpLabel") - k, base = self.tmp(), self.tmp() - self.emit(f"{k} = OpLoad %uint %gs_emitted") - self.emit(f"{base} = OpIMul %uint {k} {self.cu(nreg)}") - for reg, sv in self.gs["out"]: - i, pp, v = self.tmp(), self.tmp(), self.tmp() - self.emit(f"{i} = OpIAdd %uint {base} {self.cu(reg)}") - self.emit(f"{pp} = OpAccessChain %_ptr_Function_v4_gs %gs_stage {i}") - self.emit(f"{v} = OpLoad %v4float {pp}") - self.emit(f"OpStore {'%gs_out_pos' if sv == 1 else f'%gs_out{reg}'} {v}") - self.emit("OpEmitVertex") - if end_primitive: - self.emit("OpEndPrimitive") - k2 = self.tmp() - self.emit(f"{k2} = OpIAdd %uint {k} {self.cu(1)}") - self.emit(f"OpStore %gs_emitted {k2}") - self.emit(f"OpBranch {end}") - self.emit(f"{end} = OpLabel") - - # ---- ray tracing: image_bvh(64)_intersect_ray ---- - def image_bvh(self, op, a, mods): - """One BVH traversal step against AMD's hardware node format, emulated over buffer reads. Semantics follow - Mesa RADV's software path (radv_nir_rt_common.c: intersect_ray_amd_software_box / _tri), which RADV uses - in place of this instruction. Node id = byte address >> 3 with the node type in bits [2:0]: 0..3 triangle, - 4 box16, 5 box32. Address = descriptor base + ((node & ~7) << 3); the base is BVH descriptor bits [39:0] - taken in 256-byte units (ASSUMPTION: RADV only ever uses base 0). Box nodes return the four child ids - (misses and inactive boxes = 0xFFFFFFFF), sorted by entry distance when the descriptor's box_sort_enable - (bit 63) is set. Triangle nodes read the vertex slots of their type (TRI0 0,1,2; TRI1 1,3,2; TRI2 2,3,4; - TRI3 2,4,0) and return the words measured on RDNA2 (docs/design.md, Ray tracing row): with T, det and the - edge functions of the watertight test, k = |d[kz]|^3, a hit gives k*(T, det, b_i, b_j) and a miss - (copysign(inf, k*det), k*det, k*b_i, k*b_j), i and j chosen by the node type's byte of the triangle-ID word - at +60 (AMD GPURT; 0x09 is RADV's v, w). A NaN anywhere in the ray, or an infinite origin, gives - (inf, 1, 0, 0). Consumers divide by .y: t = T/det and the barycentrics b/det.""" - if "a16" in mods: - raise Unsupported(op + " a16") - is64 = op.startswith("image_bvh64") - self.uses_bvh = True - vd = a[0] - regs = self.addr_regs(a[1]) - need = 12 if is64 else 11 - if len(regs) < need or vd["k"] != "vgpr": - raise Unsupported(op + " operands") - desc = self.sgpr_words(a[2], 4) - ld = lambda r: self.load_reg("vgpr", r) - self.uses_psb = True - self.uses_long = True - e = self.emit - T = self.tmp - - def u64(lo, hi): - l, h, sh, r = T(), T(), T(), T() - e(f"{l} = OpUConvert %ulong {lo}") - e(f"{h} = OpUConvert %ulong {hi}") - e(f"{sh} = OpShiftLeftLogical %ulong {h} %c64_32") - e(f"{r} = OpBitwiseOr %ulong {sh} {l}") - return r - - # descriptor base (bits [39:0], 256-byte units) and sort flag - bhi, base40, base = T(), T(), T() - e(f"{bhi} = OpBitwiseAnd %uint {desc[1]} {self.cu(0xFF)}") - base40 = u64(desc[0], bhi) - e(f"{base} = OpShiftLeftLogical %ulong {base40} {self.cl(8)}") - sortb, sort = T(), T() - e(f"{sortb} = OpShiftRightLogical %uint {desc[1]} {self.cu(31)}") - e(f"{sort} = OpINotEqual %bool {sortb} {self.cu(0)}") - # node id - if is64: - node = u64(ld(regs[0]), ld(regs[1])) - rest = regs[2:] - else: - n32 = T() - e(f"{n32} = OpUConvert %ulong {ld(regs[0])}") - node = n32 - rest = regs[1:] - nlo, ntype = T(), T() - e(f"{nlo} = OpUConvert %uint {node}") - e(f"{ntype} = OpBitwiseAnd %uint {nlo} {self.cu(7)}") - nm, off, addr = T(), T(), T() - e(f"{nm} = OpBitwiseAnd %ulong {node} {self.cl(0xFFFFFFFFFFFFFFF8)}") - e(f"{off} = OpShiftLeftLogical %ulong {nm} {self.cl(3)}") - e(f"{addr} = OpIAdd %ulong {base} {off}") - ptr = T() - e(f"{ptr} = OpConvertUToPtr %_ptr_PSB_arr {self.host_addr(addr)}") - - def ldw(i): - pp, v = T(), T() - e(f"{pp} = OpAccessChain %_ptr_PSB_uint {ptr} {self.cu(i)}") - e(f"{v} = OpLoad %uint {pp} Aligned 4") - return v - - f = lambda r: self.tof(ld(r)) - tmax = f(rest[0]) - org = [f(r) for r in rest[1:4]] - dirv = [f(r) for r in rest[4:7]] - inv = [f(r) for r in rest[7:10]] - INF, ONE, NEGINF = (self.tof(self.cu(x)) for x in (0x7F800000, 0x3F800000, 0xFF800000)) - out = lambda k, v: self.dst({"k": "vgpr", "r": vd["r"] + k, "n": 1}, v) - - def fop(o, x, y): - r = T() - e(f"{r} = {o} %float {x} {y}") - return r - - def fext(name, *xs): - r = T() - e(f"{r} = OpExtInst %float %glsl {name} {' '.join(xs)}") - return r - - def bop(o, x, y): - r = T() - e(f"{r} = {o} %bool {x} {y}") - return r - - def sel(c, x, y, ty="%float"): - r = T() - e(f"{r} = OpSelect {ty} {c} {x} {y}") - return r - - is_tri, is_b16, is_box = T(), T(), T() - e(f"{is_tri} = OpULessThan %bool {ntype} {self.cu(4)}") - e(f"{is_b16} = OpIEqual %bool {ntype} {self.cu(4)}") - bx16 = T() - e(f"{bx16} = OpIEqual %bool {ntype} {self.cu(5)}") - e(f"{is_box} = OpLogicalOr %bool {is_b16} {bx16}") - L = {k: T() + "_" + k for k in ("tri", "nt", "box", "oth", "end1", "end2")} - e(f"OpSelectionMerge {L['end1']} None") - e(f"OpBranchConditional {is_tri} {L['tri']} {L['nt']}") - - # ---------------- triangle ---------------- - e(f"{L['tri']} = OpLabel") - # The node type picks the triangle's vertex slots in the 64-byte node (12 bytes each; slot 4 is the - # metadata words 12..14): TRI0 (0,1,2), TRI1 (1,3,2), TRI2 (2,3,4), TRI3 (2,4,0). AMD GPURT - # CalcTriangleCompressionVertexIndices; the XDXR software path's Read3Verts (docs/bvh.md 7a). - def ldw_dyn(i): - pp, v = T(), T() - e(f"{pp} = OpAccessChain %_ptr_PSB_uint {ptr} {i}") - e(f"{v} = OpLoad %uint {pp} Aligned 4") - return v - nsh = T() - e(f"{nsh} = OpShiftLeftLogical %uint {ntype} {self.cu(2)}") - V = [] - for table in (0x2210, 0x4331, 0x0422): # slot of vertex j for node types 0..3, one nibble each - slot, w0 = T(), T() - e(f"{slot} = OpBitFieldUExtract %uint {self.cu(table)} {nsh} {self.cu(4)}") - e(f"{w0} = OpIMul %uint {slot} {self.cu(3)}") - row = [] - for c in range(3): - wc = w0 - if c: - wc = T() - e(f"{wc} = OpIAdd %uint {w0} {self.cu(c)}") - row.append(self.tof(ldw_dyn(wc))) - V.append(row) - ad = [fext("FAbs", d) for d in dirv] - c01, c02, c12 = bop("OpFOrdGreaterThanEqual", ad[0], ad[1]), bop("OpFOrdGreaterThanEqual", ad[0], ad[2]), \ - bop("OpFOrdGreaterThanEqual", ad[1], ad[2]) - k_a = sel(c02, self.cu((0 << 4) | (2 << 2) | 1), self.cu((2 << 4) | (1 << 2) | 0), "%uint") - k_b = sel(c12, self.cu((1 << 4) | (0 << 2) | 2), self.cu((2 << 4) | (1 << 2) | 0), "%uint") - pk = sel(c01, k_a, k_b, "%uint") - kx0, ky0, kz = T(), T(), T() - e(f"{kx0} = OpBitwiseAnd %uint {pk} {self.cu(3)}") - e(f"{ky0} = OpBitFieldUExtract %uint {pk} {self.cu(2)} {self.cu(2)}") - e(f"{kz} = OpShiftRightLogical %uint {pk} {self.cu(4)}") - dvec = T() - e(f"{dvec} = OpCompositeConstruct %v3float {' '.join(dirv)}") - - def vx(vec, i): - r = T() - e(f"{r} = OpVectorExtractDynamic %float {vec} {i}") - return r - dkz = vx(dvec, kz) - neg = bop("OpFOrdLessThan", dkz, "%f0") - kx = sel(neg, ky0, kx0, "%uint") - ky = sel(neg, kx0, ky0, "%uint") - # Measured on RDNA2 (docs/design.md, Ray tracing row): the words are the watertight test's T, det and edge - # functions, scaled by k = |d[kz]|^3. They are computed here without a division, with the shear multiplied - # through by |d[kz]| (A'' = |d[kz]| A' = A[kx] |d[kz]| - sign(d[kz]) d[kx] A[kz]), so U, V, W and det carry - # |d[kz]|^2 and the sum below sign(d[kz]) |d[kz]|^3 T. The supplied inverse direction is not used. A shear - # divided by d[kz] gives the same words on every measured row but d.z = +inf (and divides by zero at d = 0); - # this form gives that row too, a fit after the runs. - adz = fext("FAbs", dkz) - NEG1 = self.tof(self.cu(0xBF800000)) - sgz = sel(neg, NEG1, ONE) - sx = fop("OpFMul", sgz, vx(dvec, kx)) # sign(d[kz]) d[kx], sign(d[kz]) d[ky] - sy = fop("OpFMul", sgz, vx(dvec, ky)) - rel = [] - for j in range(3): - vv = T() - comps = [fop("OpFSub", V[j][c], org[c]) for c in range(3)] - e(f"{vv} = OpCompositeConstruct %v3float {' '.join(comps)}") - rel.append(vv) - def shear(vv): - zk = vx(vv, kz) - return (fop("OpFSub", fop("OpFMul", vx(vv, kx), adz), fop("OpFMul", sx, zk)), - fop("OpFSub", fop("OpFMul", vx(vv, ky), adz), fop("OpFMul", sy, zk)), zk) - (ax, ay, az0), (bx, by, bz0), (cx, cy, cz0) = (shear(r) for r in rel) - uu = fop("OpFSub", fop("OpFMul", cx, by), fop("OpFMul", cy, bx)) - vv_ = fop("OpFSub", fop("OpFMul", ax, cy), fop("OpFMul", ay, cx)) - ww = fop("OpFSub", fop("OpFMul", bx, ay), fop("OpFMul", by, ax)) - lt0 = lambda x: bop("OpFOrdLessThan", x, "%f0") - gt0 = lambda x: bop("OpFOrdGreaterThan", x, "%f0") - eq0 = lambda x: bop("OpFOrdEqual", x, "%f0") - orr = lambda x, y: bop("OpLogicalOr", x, y) - andd = lambda x, y: bop("OpLogicalAnd", x, y) - det = fop("OpFAdd", uu, fop("OpFAdd", vv_, ww)) - tt = fop("OpFAdd", fop("OpFAdd", fop("OpFMul", uu, az0), fop("OpFMul", vv_, bz0)), fop("OpFMul", ww, cz0)) - tk = fop("OpFMul", sgz, tt) # k*T - # Inside: det is not 0 or NaN, and every edge function has det's sign, or is 0 and its edge passes RDNA2's tie - # rule (docs/design.md, Ray tracing row; measured with x, y and z dominant, both windings, both signs of - # d[kz]): the edge from P to Q, with (tx, ty) = Q - P in the sheared frame with the d[kz] < 0 swap undone, - # passes when ty == 0 ? sign(det) tx > 0 : sign(d[kz]) sign(det) ty > 0. Hit: inside and sign(det) T >= 0 - # (t = 0 hits); there is no test against the ray extent. Every compare is ordered, so a NaN fails it. - dpos, dneg = gt0(det), lt0(det) - sd = sel(dpos, ONE, NEG1) - sdz = fop("OpFMul", sgz, sd) # sign(d[kz]) sign(det) - - def inside(x, p, q): - tx, ty = fop("OpFSub", q[0], p[0]), fop("OpFSub", q[1], p[1]) - tx, ty = sel(neg, ty, tx), sel(neg, tx, ty) # undo the kx/ky swap of d[kz] < 0 - tie = sel(eq0(ty), gt0(fop("OpFMul", sd, tx)), gt0(fop("OpFMul", sdz, ty)), "%bool") - return sel(eq0(x), tie, gt0(fop("OpFMul", sd, x)), "%bool") - a2, b2, c2 = (ax, ay), (bx, by), (cx, cy) - front = bop("OpFOrdGreaterThanEqual", fop("OpFMul", sd, tk), "%f0") - hit = andd(andd(orr(dpos, dneg), andd(inside(uu, b2, c2), inside(vv_, c2, a2))), - andd(inside(ww, a2, b2), front)) - # The node's triangle-ID word (byte offset 60) holds one byte per node type: bits [1:0] pick which vertex's - # weight is returned first, bits [3:2] the second (0 = vertex 0's, U; 1 = V; 2 = W; 3 is not used by a - # builder and reads U, as in the XDXR software path). 0x09 is the plain (V, W). AMD GPURT - # SwizzleBarycentrics and TRIANGLE_ID_I/J_SRC_SHIFT; XDXR TestXboxBvh4Leaf (docs/bvh.md 7a). - tid, tsh, tby = T(), T(), T() - e(f"{tsh} = OpShiftLeftLogical %uint {ntype} {self.cu(3)}") - e(f"{tid} = OpShiftRightLogical %uint {ldw(15)} {tsh}") - e(f"{tby} = OpBitwiseAnd %uint {tid} {self.cu(0xF)}") - - def pick(shift): - s_ = T() - e(f"{s_} = OpBitFieldUExtract %uint {tby} {self.cu(shift)} {self.cu(2)}") - is1, is2 = T(), T() - e(f"{is1} = OpIEqual %bool {s_} {self.cu(1)}") - e(f"{is2} = OpIEqual %bool {s_} {self.cu(2)}") - return sel(is2, ww, sel(is1, vv_, uu)) - # The four words, hit or miss: (k*T, k*det, k*b_i, k*b_j). The hardware returns every zero as +0, where IEEE - # arithmetic gives -0 for some (t = 0, an edge function through a vertex on the ray), and every NaN as - # 0xFFC00000. SPIR-V leaves a NaN's bits to the driver, and a zero's sign too without float controls, so both - # are fixed by a select on the integer side. A miss replaces word 0 with copysign(inf, word 1): det = 0 gives - # +inf, a NaN det -inf. - def canon(x): - u, nan = self.tou(x), T() - e(f"{nan} = OpIsNan %bool {x}") - return sel(nan, self.cu(0xFFC00000), sel(eq0(x), self.cu(0), u, "%uint"), "%uint") - w = [canon(x) for x in [tk] + [fop("OpFMul", adz, x) for x in (det, pick(0), pick(2))]] - sgn, minf = T(), T() - e(f"{sgn} = OpBitwiseAnd %uint {w[1]} {self.cu(0x80000000)}") - e(f"{minf} = OpBitwiseOr %uint {sgn} {self.cu(0x7F800000)}") - w[0] = sel(hit, w[0], minf, "%uint") - # A NaN in t max, the origin, the direction or the inverse direction (an axis nothing else reads included), - # or an infinite origin, returns (inf, 1, 0, 0) whatever the node holds. - bad = None - for x, test in [(tmax, "OpIsNan")] + [(x, "OpIsNan") for x in org + dirv + inv] + [(x, "OpIsInf") for x in org]: - b = T() - e(f"{b} = {test} %bool {x}") - bad = b if bad is None else orr(bad, b) - for k, (v, c) in enumerate(zip(w, (0x7F800000, 0x3F800000, 0, 0))): - out(k, sel(bad, self.cu(c), v, "%uint")) - e(f"OpBranch {L['end1']}") - - # ---------------- not a triangle ---------------- - e(f"{L['nt']} = OpLabel") - e(f"OpSelectionMerge {L['end2']} None") - e(f"OpBranchConditional {is_box} {L['box']} {L['oth']}") - e(f"{L['box']} = OpLabel") - dist, idx = [], [] - for i in range(4): - child = ldw(i) - # box32: min/max f32 at 16 + 24 i; box16: 6 halves at 16 + 12 i (min x,y,z, max x,y,z) - m32 = [self.tof(ldw(4 + 6 * i + c)) for c in range(6)] - h = [ldw(4 + 3 * i + c) for c in range(3)] - m16 = [] - for w in h: - v2 = T() - e(f"{v2} = OpExtInst %v2float %glsl UnpackHalf2x16 {w}") - for c in range(2): - x = T() - e(f"{x} = OpCompositeExtract %float {v2} {c}") - m16.append(x) - mm = [sel(is_b16, m16[c], m32[c]) for c in range(6)] - b0 = [self.f32_mul_rtz(self.f32_sub_rtz(mm[c], org[c]), inv[c]) for c in range(3)] - b1 = [self.f32_mul_rtz(self.f32_sub_rtz(mm[3 + c], org[c]), inv[c]) for c in range(3)] - near, far, nnan, fnan = [], [], [], [] - for c in range(3): - pos = bop("OpFOrdGreaterThanEqual", inv[c], "%f0") - n_, f_ = sel(pos, b0[c], b1[c]), sel(pos, b1[c], b0[c]) - nn, fn = T(), T() - e(f"{nn} = OpIsNan %bool {n_}") - e(f"{fn} = OpIsNan %bool {f_}") - near.append(sel(nn, NEGINF, n_)) - far.append(sel(fn, INF, f_)) - nnan.append(nn) - fnan.append(fn) - tmin = fext("FMax", fext("FMax", near[0], near[1]), near[2]) - tmx = fext("FMin", fext("FMin", far[0], far[1]), far[2]) - nonan = T() - e(f"{nonan} = OpLogicalNot %bool " - f"{orr(andd(andd(nnan[0], nnan[1]), nnan[2]), andd(andd(fnan[0], fnan[1]), fnan[2]))}") - tnear = fext("FMax", "%f0", tmin) - h1 = bop("OpFOrdGreaterThanEqual", tmx, tnear) - h2 = bop("OpFOrdLessThan", tmin, tmax) - hb = andd(nonan, andd(h1, h2)) - dist.append(sel(hb, tnear, INF)) - idx.append(sel(hb, child, self.cu(0xFFFFFFFF), "%uint")) - for p_, q_ in ((0, 2), (1, 3), (0, 1), (2, 3), (1, 2)): - sw = andd(sort, bop("OpFOrdLessThan", dist[q_], dist[p_])) - dist[p_], dist[q_] = sel(sw, dist[q_], dist[p_]), sel(sw, dist[p_], dist[q_]) - idx[p_], idx[q_] = sel(sw, idx[q_], idx[p_], "%uint"), sel(sw, idx[p_], idx[q_], "%uint") - for k in range(4): - out(k, idx[k]) - e(f"OpBranch {L['end2']}") - e(f"{L['oth']} = OpLabel") - for k in range(4): # instance / aabb nodes are handled by the shader, not the instruction - out(k, self.cu(0xFFFFFFFF)) - e(f"OpBranch {L['end2']}") - e(f"{L['end2']} = OpLabel") - e(f"OpBranch {L['end1']}") - e(f"{L['end1']} = OpLabel") - - def ms_export(self, tgt, ins): - """NGG export in a mesh shader: thread t exports vertex t (pos/param) and primitive t (prim). The values are - staged in per-invocation variables and written to the mesh outputs at shader end, after - OpSetMeshOutputsEXT (see assemble). Exports whose operands are all 'off' are the dummy exports a wave with no - vertices must still issue: they write nothing.""" - a = ins["args"] - srcs = a[1:5] - if all(x["k"] == "special" and x["t"] == "off" for x in srcs): - return - act = self.active_b() - if tgt == "prim": - # Packed: v0 [8:0], v1 [18:10], v2 [28:20], null primitive [31]. - u = self.src_u(srcs[0]) - old, sel = self.tmp(), self.tmp() - self.emit(f"{old} = OpLoad %uint %ms_prim") - self.emit(f"{sel} = OpSelect %uint {act} {u} {old}") - self.emit("OpStore %ms_prim " + sel) - hp, hs = self.tmp(), self.tmp() - self.emit(f"{hp} = OpLoad %bool %ms_has_prim") - self.emit(f"{hs} = OpLogicalOr %bool {hp} {act}") - self.emit("OpStore %ms_has_prim " + hs) - return - if tgt.startswith("pos") and tgt != "pos0": - if "compr" in ins["mods"]: - raise Unsupported("mesh compressed export") - pidx = int(tgt[3:]) - mapping = self.pos_map.get(pidx) - if not mapping: - return - wrote = False - for comp, (kind, idx) in sorted(mapping.items()): - if comp >= len(srcs): - continue - x = srcs[comp] - if x["k"] == "special" and x["t"] == "off": - continue - fval = self.src_f(x) - if kind == "clip": - self.uses_clip = True - var = "%ms_clip" - else: - self.uses_cull = True - var = "%ms_cull_dist" - ptr, old, sel = self.tmp(), self.tmp(), self.tmp() - self.emit(f"{ptr} = OpAccessChain %_ptr_Function_float {var} {self.cu(idx)}") - self.emit(f"{old} = OpLoad %float {ptr}") - self.emit(f"{sel} = OpSelect %float {act} {fval} {old}") - self.emit(f"OpStore {ptr} {sel}") - wrote = True - if wrote: - hv, hs = self.tmp(), self.tmp() - self.emit(f"{hv} = OpLoad %bool %ms_has_vtx") - self.emit(f"{hs} = OpLogicalOr %bool {hv} {act}") - self.emit("OpStore %ms_has_vtx " + hs) - return - if not (tgt == "pos0" or tgt.startswith("param")): - raise Unsupported(f"mesh export {tgt}") - if "compr" in ins["mods"]: - raise Unsupported("mesh compressed export") - comps = [("%f0" if x["k"] == "special" and x["t"] == "off" else self.src_f(x)) for x in srcs] - comps += ["%f0"] * (4 - len(comps)) - v = self.tmp() - self.emit(f"{v} = OpCompositeConstruct %v4float {' '.join(comps[:4])}") - var = "%ms_pos" if tgt == "pos0" else f"%ms_param{int(tgt[5:])}" - if tgt != "pos0": - self.ms_params.add(int(tgt[5:])) - old, sel = self.tmp(), self.tmp() - self.emit(f"{old} = OpLoad %v4float {var}") - self.emit(f"{sel} = OpSelect %v4float {act} {v} {old}") - self.emit(f"OpStore {var} {sel}") - hv, hs = self.tmp(), self.tmp() - self.emit(f"{hv} = OpLoad %bool %ms_has_vtx") - self.emit(f"{hs} = OpLogicalOr %bool {hv} {act}") - self.emit("OpStore %ms_has_vtx " + hs) - - def export(self, ins): - a = ins["args"] - tgt = a[0]["t"] if a and a[0]["k"] in ("target", "special") else None - if self.vm_latch and "vm" in ins["mods"]: # any target, null included - self.emit(f"OpStore %vm_mask {self.active_b()}") - self.emit("OpStore %vm_set %true") - if self.vm_latch and is_color_export(ins): - if tgt not in self.col_latched: - self.col_latched.append(tgt) - self.emit(f"OpStore %col_mask_{tgt} {self.active_b()}") - self.emit(f"OpStore %col_set_{tgt} %true") - if tgt is None or tgt == "null": - return - if self.stage == "ms": - return self.ms_export(tgt, ins) - if tgt.startswith("pos") and tgt != "pos0" and self.stage == "vs": - srcs = a[1:5] - if all(x["k"] == "special" and x["t"] == "off" for x in srcs): - return - pidx = int(tgt[3:]) - act = self.active_b() - if pidx == 1 and self.pos_misc: - # GFX9+ misc vector at pos1: z[10:0] = Layer, z[19:16] = ViewportIndex. - if len(srcs) >= 3 and not (srcs[2]["k"] == "special" and srcs[2]["t"] == "off"): - z = self.src_u(srcs[2]) - if 4 in self.pos_misc: - self.uses_layer = True - lu, li, old, sel = self.tmp(), self.tmp(), self.tmp(), self.tmp() - self.emit(f"{lu} = OpBitwiseAnd %uint {z} {self.cu(0x7FF)}") - self.emit(f"{li} = OpBitcast %int {lu}") - self.emit(f"{old} = OpLoad %int %out_layer") - self.emit(f"{sel} = OpSelect %int {act} {li} {old}") - self.emit(f"OpStore %out_layer {sel}") - if 5 in self.pos_misc: - self.uses_viewport = True - vs_, vu, vi, old, sel = self.tmp(), self.tmp(), self.tmp(), self.tmp(), self.tmp() - self.emit(f"{vs_} = OpShiftRightLogical %uint {z} {self.cu(16)}") - self.emit(f"{vu} = OpBitwiseAnd %uint {vs_} {self.cu(0xF)}") - self.emit(f"{vi} = OpBitcast %int {vu}") - self.emit(f"{old} = OpLoad %int %out_viewport") - self.emit(f"{sel} = OpSelect %int {act} {vi} {old}") - self.emit(f"OpStore %out_viewport {sel}") - return - mapping = self.pos_map.get(pidx) - if not mapping: - return - for comp, (kind, idx) in sorted(mapping.items()): - if comp >= len(srcs): - continue - x = srcs[comp] - if x["k"] == "special" and x["t"] == "off": - continue - fval = self.src_f(x) - if kind == "clip": - self.uses_clip = True - var = "%out_clip" - else: - self.uses_cull = True - var = "%out_cull" - ptr, old, sel = self.tmp(), self.tmp(), self.tmp() - self.emit(f"{ptr} = OpAccessChain %_ptr_Output_float {var} {self.cu(idx)}") - self.emit(f"{old} = OpLoad %float {ptr}") - self.emit(f"{sel} = OpSelect %float {act} {fval} {old}") - self.emit(f"OpStore {ptr} {sel}") - return - if tgt == "mrtz" and self.stage == "ps": - # Depth export: x is the fragment depth when it's on in an uncompressed export (RGBA = Z, stencil, - # sample mask, alpha; Mesa ac_shader_util.c ac_get_spi_shader_z_format). A compressed mrtz is the 16-bit - # stencil and sample mask format, which never holds Z (ac_nir_lower_ps_late.c emit_ps_mrtz_export), and - # with x off no depth is exported. Until 2026-11-22 both wrote one anyway: 0.0, or an f16 half of the - # stencil word under compr. Stencil, sample mask and alpha aren't modelled. - x = a[1] if len(a) > 1 else None - if "compr" in ins["mods"] or x is None or (x["k"] == "special" and x["t"] == "off"): - return - self.writes_depth = True - old, sel = self.tmp(), self.tmp() - self.emit(f"{old} = OpLoad %float %out_depth") - self.emit(f"{sel} = OpSelect %float {self.active_b()} {self.src_f(x)} {old}") - self.emit(f"OpStore %out_depth {sel}") - return - comps = [] - if "compr" in ins["mods"]: - # Compressed export: two registers, each holding two f16 values (x,y) and (z,w). LLVM lists each register - # twice (one slot per half): 'exp mrt0 v4, v4, v5, v5 compr', so the pair is slots 1 and 3. - # (Found by the GPU texture test: taking the first two operands exported (r,g,r,g).) - srcs = a[1:5] - regs = [srcs[0], srcs[2]] if len(srcs) >= 3 else srcs[:1] - for x in regs: - if x["k"] == "special" and x["t"] == "off": - comps += [None, None] - continue - u = self.src_u(x) - v2 = self.tmp() - self.emit(f"{v2} = OpExtInst %v2float %glsl UnpackHalf2x16 {u}") - for c in (0, 1): - f = self.tmp() - self.emit(f"{f} = OpCompositeExtract %float {v2} {c}") - comps.append(f) - else: - for x in a[1:5]: - if x["k"] == "special" and x["t"] == "off": - comps.append(None) - else: - comps.append(self.src_f(x)) - while len(comps) < 4: - comps.append(None) - comps = comps[:4] - v = self.tmp() - name = {"pos0": "%out_pos"}.get(tgt) - if name is None: - if tgt.startswith("param") and self.stage == "vs": - name = f"%out_param{int(tgt[5:])}" - elif tgt.startswith("mrt") and tgt != "mrtz" and self.stage == "ps": - # Colour exports are packed: exp mrtK writes the K-th declared SV_Target, not render target K - # (docs/design.md, "Pixel colour exports"). Without an OSG1 the index is the render target. - k = int(tgt[3:]) - if self.mrt_targets and k >= len(self.mrt_targets): - raise Unsupported(f"export mrt{k} past the {len(self.mrt_targets)} declared SV_Target outputs") - rt = self.mrt_targets[k] if self.mrt_targets else k - name = f"%out_mrt{rt}" - tgt = f"mrt{rt}" - elif tgt.startswith("pos"): - return # pos1+ (clip/cull/point size): ignored in v0 - else: - raise Unsupported(f"export {tgt}") - self.outputs[name] = tgt - # Exports from inactive lanes don't happen: keep the previous output value. - old, sel = self.tmp(), self.tmp() - self.emit(f"{old} = OpLoad %v4float {name}") - if self.stage == "ps" and tgt.startswith("mrt") and None in comps: - # EN gates each component (each RG/BA pair when compressed). Keep the previous export in off slots. - self.partial_color_outputs.add(name) - for i, comp in enumerate(comps): - if comp is None: - comps[i] = self.tmp() - self.emit(f"{comps[i]} = OpCompositeExtract %float {old} {i}") - self.emit(f"{v} = OpCompositeConstruct %v4float {' '.join(comp or '%f0' for comp in comps)}") - self.emit(f"{sel} = OpSelect %v4float {self.active_b()} {v} {old}") - self.emit(f"OpStore {name} {sel}") - if F16_HALVES and tgt.startswith("param") and self.stage == "vs": - n = int(tgt[5:]) - for half, hv in enumerate(self.f16_halves_of(n, v)): - hname = f"%out_f16h{n}_{half}" - self.outputs[hname] = f"loc{self.f16_half_locs[n][half]}" - old, sel = self.tmp(), self.tmp() - self.emit(f"{old} = OpLoad %v4float {hname}") - self.emit(f"{sel} = OpSelect %v4float {self.active_b()} {hv} {old}") - self.emit(f"OpStore {hname} {sel}") - - def f16_halves_of(self, n, v): - """--f16-interp-fallback: param n's exported vec4 `v` as two vec4s, the low and the high f16 half of each - channel's raw word decoded to f32 (UnpackHalf2x16), or () when their locations would overlap a param this - shader exports (or fall below location 0): runtime PSO linking synthesizes missing halves per pair.""" - if n not in self.f16_half_locs: - if f16_half_location(n, 0) <= self.param_max: - return () - self.f16_half_locs[n] = (f16_half_location(n, 0), f16_half_location(n, 1)) - lo, hi = [], [] - for c in range(4): - e, u, h2, a, b = (self.tmp() for _ in range(5)) - self.emit(f"{e} = OpCompositeExtract %float {v} {c}") - self.emit(f"{u} = OpBitcast %uint {e}") - self.emit(f"{h2} = OpExtInst %v2float %glsl UnpackHalf2x16 {u}") - self.emit(f"{a} = OpCompositeExtract %float {h2} 0") - self.emit(f"{b} = OpCompositeExtract %float {h2} 1") - lo.append(a) - hi.append(b) - out = [] - for parts in (lo, hi): - r = self.tmp() - self.emit(f"{r} = OpCompositeConstruct %v4float {' '.join(parts)}") - out.append(r) - return tuple(out) - - -_TYPE_DECL = re.compile(r"\s*(%\w+) = (OpTypeVector|OpTypePointer) (.*)$") -_ID_REF = re.compile(r"%\w+") - - -def dedupe_types(text): - """SPIR-V forbids duplicate non-aggregate types. Separate features may each declare e.g. a uint4 vector - (%v4uint for r32ui storage, %v4uint_st for typed stores, %v4uint_in for vertex inputs): keep the first - declaration of each OpTypeVector / OpTypePointer and rename the others everywhere.""" - alias, seen, out = {}, {}, [] - lines = text.split("\n") - for i, line in enumerate(lines): - if " = OpFunction " in line: - out.extend(lines[i:]) - break - m = _TYPE_DECL.match(line) - if m: - name, opc, rest = m.groups() - key = (opc, _ID_REF.sub(lambda t: alias.get(t.group(0), t.group(0)), rest)) - if key in seen: - alias[name] = seen[key] - continue - seen[key] = name - out.append(line) - if not alias: - return text - pattern = re.compile(r"(?:" + "|".join(re.escape(k) for k in sorted(alias, key=len, reverse=True)) + r")\b") - return pattern.sub(lambda m: alias[m.group(0)], "\n".join(out)) - - -def mesh_compute_epilogue(gen): - """--mesh-compute: the mesh epilogue as buffer stores. Same barrier and counts as the mesh path; then lane 0 - writes the header, lane i < vertex count its vertex and lane i < primitive count its primitive, at the offsets - of gen.msc_layout in this workgroup's slot (linear workgroup index x + y*nx + z*nx*ny).""" - c, lay = gen.cu, gen.msc_layout - L = [f"OpControlBarrier {c(2)} {c(2)} " + c(0x108), - "%msc = OpLoad %uint %ms_counts", - f"%msv0 = OpBitwiseAnd %uint %msc {c(0xFFF)}", f"%msp1 = OpShiftRightLogical %uint %msc {c(12)}", - f"%msp0 = OpBitwiseAnd %uint %msp1 {c(0xFFF)}", - f"%msv = OpExtInst %uint %glsl UMin %msv0 {c(gen.ms['maxv'])}", - f"%msp = OpExtInst %uint %glsl UMin %msp0 {c(gen.ms['maxp'])}", - "%mli = OpLoad %uint %local_index", - # Slot base = output address (push-constant dwords 36..37, or --pc-tail-ubo dwords 4..5) + linear - # workgroup index * slot bytes. - pc_tail_chain("%moa_lo_p", 5, c), pc_tail_chain("%moa_hi_p", 6, c), - "%moa_lo = OpLoad %uint %moa_lo_p", "%moa_hi = OpLoad %uint %moa_hi_p", - "%moa_l64 = OpUConvert %ulong %moa_lo", "%moa_h64 = OpUConvert %ulong %moa_hi", - "%moa_sh = OpShiftLeftLogical %ulong %moa_h64 %c64_32", "%moa = OpBitwiseOr %ulong %moa_sh %moa_l64", - "%mwg = OpLoad %v3uint %wg_id", "%mnw = OpLoad %v3uint %num_wg", - "%mwx = OpCompositeExtract %uint %mwg 0", "%mwy = OpCompositeExtract %uint %mwg 1", - "%mwz = OpCompositeExtract %uint %mwg 2", "%mnx = OpCompositeExtract %uint %mnw 0", - "%mny = OpCompositeExtract %uint %mnw 1", - "%mnxy = OpIMul %uint %mnx %mny", "%mwyx = OpIMul %uint %mwy %mnx", "%mwzxy = OpIMul %uint %mwz %mnxy", - "%mwl0 = OpIAdd %uint %mwx %mwyx", "%mwl = OpIAdd %uint %mwl0 %mwzxy", - "%mwl64 = OpUConvert %ulong %mwl", f"%mso = OpIMul %ulong %mwl64 {gen.cl(lay['slot_bytes'])}", - "%msb = OpIAdd %ulong %moa %mso"] - n = [0] - - def store(off_u32, word): - """Store uint `word` at byte offset `off_u32` (a uint id) of the slot.""" - k = n[0] - n[0] += 1 - L.extend([f"%mo{k} = OpUConvert %ulong {off_u32}", f"%ma{k} = OpIAdd %ulong %msb %mo{k}", - f"%mp{k} = OpConvertUToPtr %_ptr_PSB_uint %ma{k}", f"OpStore %mp{k} {word} Aligned 4"]) - - def at(base, extra): - """uint id for base + a constant byte offset.""" - if not extra: - return base - k = n[0] - n[0] += 1 - L.append(f"%mx{k} = OpIAdd %uint {base} {c(extra)}") - return f"%mx{k}" - - def store_floats(base, values): - for i, f in enumerate(values): - k = n[0] - n[0] += 1 - L.append(f"%mf{k} = OpBitcast %uint {f}") - store(at(base, 4 * i), f"%mf{k}") - - # Header, lane 0. - L += ["%mh0 = OpIEqual %bool %mli %c0", "OpSelectionMerge %msc_hend None", - "OpBranchConditional %mh0 %msc_hdo %msc_hend", "%msc_hdo = OpLabel"] - store("%c0", "%msv") - store(c(4), "%msp") - L += ["OpBranch %msc_hend", "%msc_hend = OpLabel"] - # Vertex mli. - L += ["%mhv = OpLoad %bool %ms_has_vtx", "%mvi = OpULessThan %bool %mli %msv", - "%mwv = OpLogicalAnd %bool %mhv %mvi", - "OpSelectionMerge %msc_vend None", "OpBranchConditional %mwv %msc_vdo %msc_vend", "%msc_vdo = OpLabel", - f"%mvs = OpIMul %uint %mli {c(lay['vertex_stride'])}", f"%mvb = OpIAdd %uint %mvs {c(lay['vertices'])}", - "%mpv = OpLoad %v4float %ms_pos"] - comps = [] - for i in range(4): - L.append(f"%mpv{i} = OpCompositeExtract %float %mpv {i}") - comps.append(f"%mpv{i}") - store_floats("%mvb", comps) - for var, count, off in (("%ms_clip", lay["clip_count"], lay["clip_offset"]), - ("%ms_cull_dist", lay["cull_count"], lay["cull_offset"])): - vals = [] - for i in range(count): - k = n[0] - n[0] += 1 - L += [f"%mdp{k} = OpAccessChain %_ptr_Function_float {var} {c(i)}", f"%mdv{k} = OpLoad %float %mdp{k}"] - vals.append(f"%mdv{k}") - if vals: - store_floats(at("%mvb", off), vals) - for loc, off in sorted(lay["params"].items()): - L.append(f"%mq{loc} = OpLoad %v4float %ms_param{loc}") - vals = [] - for i in range(4): - L.append(f"%mq{loc}_{i} = OpCompositeExtract %float %mq{loc} {i}") - vals.append(f"%mq{loc}_{i}") - store_floats(at("%mvb", off), vals) - L += ["OpBranch %msc_vend", "%msc_vend = OpLabel"] - # Primitive mli: three 9-bit indices and the null-primitive bit (bit 31), as in the mesh path. - L += ["%mhp = OpLoad %bool %ms_has_prim", "%mpi = OpULessThan %bool %mli %msp", - "%mwp = OpLogicalAnd %bool %mhp %mpi", - "OpSelectionMerge %msc_pend None", "OpBranchConditional %mwp %msc_pdo %msc_pend", "%msc_pdo = OpLabel", - f"%mps = OpIMul %uint %mli {c(16)}", f"%mpb = OpIAdd %uint %mps {c(lay['primitives'])}", - "%mpr = OpLoad %uint %ms_prim", - f"%mi0 = OpBitwiseAnd %uint %mpr {c(0x1FF)}", - f"%mr1 = OpShiftRightLogical %uint %mpr {c(10)}", f"%mi1 = OpBitwiseAnd %uint %mr1 {c(0x1FF)}", - f"%mr2 = OpShiftRightLogical %uint %mpr {c(20)}", f"%mi2 = OpBitwiseAnd %uint %mr2 {c(0x1FF)}", - f"%mnb = OpShiftRightLogical %uint %mpr {c(31)}"] - for i, w in enumerate(("%mi0", "%mi1", "%mi2", "%mnb")): - store(at("%mpb", 4 * i), w) - L += ["OpBranch %msc_pend", "%msc_pend = OpLabel"] - return "".join((" " + l if " = OpLabel" not in l else l) + "\n" for l in L) - - -def insert_late_constants(gen, out, written): - """Define the uint constants assemble asked gen.cu for after it wrote the others (the format tables' lengths and - entries, prologue indices, ...), right after the last written one, so before any type or instruction that uses - them. Without this a constant nothing else had used (fmt_size_arr's length 128 in a shader with only a d16 typed - store) was an id with no definition, and the module failed spirv-val.""" - late = sorted(v for v in gen.consts if v not in written) - if not late: - return - last = max(written) - at = out.index(f"{written[last]} = OpConstant %uint {last}") + 1 - out[at:at] = [f"{gen.consts[v]} = OpConstant %uint {v}" for v in late] - - -def assemble(gen): - vs = gen.stage == "vs" - cs = gen.stage == "cs" - ms = gen.stage == "ms" - gsx = gen.stage == "gs" - msc = ms and MESH_COMPUTE - # --f16-interp-fallback, mesh: the params whose decoded halves fit clear of this shader's params (Gen.f16_halves_of) - if ms and not msc and F16_HALVES: - for n in sorted(gen.ms_params): - if n not in gen.f16_half_locs and f16_half_location(n, 0) > gen.param_max: - gen.f16_half_locs[n] = (f16_half_location(n, 0), f16_half_location(n, 1)) - ms_halves = [n for n in sorted(gen.ms_params) if n in gen.f16_half_locs] if ms and not msc else [] - if msc: - gen.msc_layout = mesh_compute_layout(gen.ms["maxv"], gen.ms["maxp"], gen.clip_count if gen.uses_clip else 0, - gen.cull_count if gen.uses_cull else 0, gen.ms_params) - # Built here, before any constant is emitted, so every constant it asks for gets declared. - gen.msc_epilogue = mesh_compute_epilogue(gen) - # --pc-tail-ubo: the uniform block exists only when the shader reads the tail (after the epilogue, which reads it). - gen.uses_pc_tail = PC_TAIL_UBO and (gen.uses_heap or gen.uses_codebase or msc) - if gen.emulate: - # No subgroup operation is left (x_round does them through %x_buf), so none of their capabilities. - if any("OpGroupNonUniform" in l or "%sg_lane" in l - for b in gen.blocks + list(gen.x_segs.values()) if b is not None for l in b): - raise Unsupported("wave64 emulation: a subgroup operation is left") - gen.uses_subgroup = gen.uses_vote = gen.uses_ballot = gen.uses_wave_bits = gen.uses_quad = False - gen.uses_bcast_first = False - x_waves, x_mask, x_sched, x_sink = gen.x_sizes() - x_zero = x_sink - x_mask # mask and schedule words: zeroed before the first round - x_threads = (gen.cs or gen.ms)["size"] - x_threads = x_threads[0] * x_threads[1] * x_threads[2] - sx, sy, _ = (gen.cs or gen.ms)["size"] - for v in (0, 1, 2, 3, 6, 31, 63, 0x948, x_mask, x_sched, x_sink, x_sink + 1, x_zero - 1, x_threads, - x_waves, sx, sx * sy, 0xFFFFFFC0): - gen.cu(v) - x_missing = gen.x_lanes - x_threads # lanes of a partial last wave that don't exist - for k in range(-(-max(x_zero, x_missing) // x_threads)): - gen.cu(k * x_threads) - if x_missing: - for v in (x_missing - 1, gen.x_lanes + x_threads): - gen.cu(v) - if gen.bar_rounds: - sx, sy, _ = gen.cs["size"] - for v in (0, 1, 2, 3, 0x108, sx, sx * sy): - gen.cu(v) - model = "Vertex" if vs else "GLCompute" if cs or msc else "MeshEXT" if ms else "Geometry" if gsx else "Fragment" - ms_blk = ms and not msc and (gen.uses_clip or gen.uses_cull) - iface = list(gen.outputs) + list(gen.inputs) + (["%vertex_index", "%instance_index", "%base_vertex", "%base_instance"] if vs else []) + (["%wg_id", "%local_id"] if cs else []) + (["%lds"] if gen.uses_lds else []) + ( - (["%wg_id", "%num_wg", "%local_index", "%ms_counts"] + ([] if msc else - [("%ms_out_vtx" if ms_blk else "%ms_out_pos"), "%ms_prim_idx", "%ms_cull"] + - [f"%ms_out_param{n}" for n in sorted(gen.ms_params)] + - [f"%ms_out_f16h{n}_{h}" for n in ms_halves for h in (0, 1)])) if ms else []) + ( - ["%x_buf"] if gen.emulate or gen.bar_rounds and not gen.bar_counts_in_lds() else []) + ( - ([("%gs_in_pos" if sv == 1 else f"%gs_in{r}") for r, sv in gen.gs["in"]] + - [("%gs_out_pos" if sv == 1 else f"%gs_out{r}") for r, sv in gen.gs["out"]]) if gsx else []) + (["%fmt_uint_mask", "%fmt_sint_mask"] if gen.uses_store_views or gen.uses_int_fetch else []) + \ - (["%fmt_norm_mask", "%fmt_f32_mask"] if gen.uses_d16_image else []) + \ - (["%fmt_size_tab"] if gen.uses_fmt_size else []) + \ - (["%fmt_desc_tab", "%fmt_norm_rep_tab"] if gen.uses_fmt_tables else []) + \ - [f"%stv{c}_{d}" for d in sorted(gen.uses_store_views) for c in range(3)] + \ - [f"%itx{c}_{d}" for d in sorted(gen.uses_int_fetch) for c in (1, 2)] - psb = gen.uses_psb - tex = gen.uses_tex - sg = gen.uses_subgroup - if tex: - iface += ["%images", "%samplers", "%desc_map"] + (["%images_arr"] if gen.uses_tex_array else []) + \ - (["%simages"] if gen.uses_storage else []) + (["%images_1d"] if gen.uses_tex_1d else []) + \ - (["%images_3d"] if gen.uses_tex_3d else []) + (["%simages3d"] if gen.uses_storage3d else []) - if sg: - iface += ["%sg_lane"] - if gen.writes_depth: - iface += ["%out_depth"] - if vs: - if gen.uses_clip: - iface += ["%out_clip"] - if gen.uses_cull: - iface += ["%out_cull"] - if gen.uses_layer: - iface += ["%out_layer"] - if gen.uses_viewport: - iface += ["%out_viewport"] - iface += [f"%vin{reg}" for reg, _ in gen.vertex_inputs] + ["%user_data"] + (["%pc_tail"] if gen.uses_pc_tail else []) - bary = any(str(c).startswith("bary") for c in gen.frag_inputs.values()) or bool(gen.per_vertex) - # --bary-fallback: %bary is a plain input at the lowest location no attribute uses, so no capability or - # extension. Lowest free, not one past the highest: a PS whose only input is attr30 would otherwise put it at 31, - # past what drivers with 128 input components accept (#804 review). - if gen.stage == "ps" and gen.f16_halves: - raw_locs = {v for k, v in gen.inputs.items() if not k.startswith("%in_f16h") and v is not None} - gen.f16_half_locs = assign_f16_half_locations(gen.f16_halves, raw_locs) - for k in list(gen.inputs): - if k.startswith("%in_f16h"): - a_str, h_str = k[len("%in_f16h"):].split("_") - gen.inputs[k] = gen.f16_half_locs[int(a_str)][int(h_str)] - used = set(gen.inputs.values()) - if len(used) != len(gen.inputs): # --f16-interp-fallback: a decoded-half location is also an attribute - raise Unsupported("--f16-interp-fallback: a decoded-half location is also read as an attribute") - # The producer fills both halves of every attribute in f16_halves (the index's f16_halves lists the pair), so a - # raw attribute at the location of a half this shader doesn't read is overwritten all the same. - reserved = {loc for pair in gen.f16_half_locs.values() for loc in pair} if gen.stage == "ps" else set() - if any(not k.startswith("%in_f16h") and v in reserved for k, v in gen.inputs.items()): - raise Unsupported("--f16-interp-fallback: a decoded-half location is also read as an attribute") - occupied = used | reserved - gen.bary_location = next(n for n in range(len(occupied) + 1) if n not in occupied) if bary and BARY_FALLBACK else None - bary_builtin = bary and gen.bary_location is None - if gen.frag_inputs or bary: - iface += ["%frag_coord"] + (["%front_facing"] if "front" in gen.frag_inputs.values() else []) + (["%bary"] if bary else []) - for i in range(USER_SGPRS): # index constants for the user-data copy at entry - gen.cu(i) - # SPIR-V module layout: every OpCapability, then every OpExtension, then imports. - caps = ["Shader"] + (["Int64", "PhysicalStorageBufferAddresses"] if psb else []) + \ - (["RuntimeDescriptorArray"] if tex else []) + (["GroupNonUniform", "GroupNonUniformShuffle"] if sg else []) + \ - (["ImageQuery"] if gen.uses_query else []) + (["Sampled1D"] if gen.uses_tex_1d else []) + \ - (["MinLod"] if gen.uses_minlod else []) + (["ImageGatherExtended"] if gen.uses_img_offset else []) + \ - (["FragmentBarycentricKHR"] if bary_builtin else []) - if gen.uses_vote: - caps += [c for c in ("GroupNonUniform", "GroupNonUniformVote") if c not in caps] - if gen.uses_ballot or gen.uses_bcast_first: - caps += [c for c in ("GroupNonUniform", "GroupNonUniformBallot") if c not in caps] - if gen.uses_wave_bits: - caps += [c for c in ("GroupNonUniform", "GroupNonUniformArithmetic") if c not in caps] - if gen.uses_quad: - caps += [c for c in ("GroupNonUniform", "GroupNonUniformQuad") if c not in caps] - if gen.uses_f64: - caps.append("Float64") - if gen.uses_fma_khr: - caps.append("FMAKHR") - if gen.uses_clock: - caps.append("ShaderClockKHR") - if gen.uses_dynamic_sampled_index: - caps.append("SampledImageArrayDynamicIndexing") - if gen.uses_dynamic_storage_index: - caps.append("StorageImageArrayDynamicIndexing") - if gen.uses_store_views: - caps.append("StorageImageWriteWithoutFormat") # shaderStorageImageWriteWithoutFormat - if gen.reads_store_views: - caps.append("StorageImageReadWithoutFormat") # shaderStorageImageReadWithoutFormat: coherent image_load - if 3 in gen.uses_store_views: - caps.append("Image1D") - if vs: - caps.append("DrawParameters") # BaseVertex / BaseInstance (shaderDrawParameters), see the seeding of v0 / v3 - if gsx: - caps.append("Geometry") - if ms and not msc: - caps.append("MeshShadingEXT") - if gen.uses_clip and not msc: # --mesh-compute: the distances go to the buffer, not to a builtin - caps.append("ClipDistance") - if gen.uses_cull and not msc: - caps.append("CullDistance") - if gen.uses_layer: - caps.append("ShaderLayer") - if gen.uses_viewport: - caps.append("ShaderViewportIndex") - if FLOAT_CONTROLS: - # RDNA2 float ops are IEEE: NaN, +-inf and -0 come out as computed, and f16 denormals are kept. Without these - # execution modes Vulkan lets the driver assume none of them occur, and drivers do: AMD's compiler folded a - # -0 product to +0 and lost a NaN result narrowed to f16 with integer ops (RX 9070 XT), and NVIDIA flushed - # an f16 denormal on its way into f32 (SHADER-526: the 0x0040 that _sdwa src0_sel:BYTE_1 selects read as - # +0, RTX 3090 and RTX 4070 SUPER; docs/design.md, "Float controls"). - # Core in SPIR-V 1.4, so no extension at vulkan1.2; the runtime checks the properties in "float_controls" - # (shaderSignedZeroInfNanPreserveFloat64 too for a module that uses Float64, SHADER-597). - caps += ["SignedZeroInfNanPreserve", "DenormPreserve"] - pops = gen.uses_pops and gen.stage == "ps" - exts = (["SPV_KHR_physical_storage_buffer"] if psb else []) + (["SPV_EXT_descriptor_indexing"] if tex else []) - if gen.uses_fma_khr: - exts.append("SPV_KHR_fma") - if gen.uses_clock: - exts.append("SPV_KHR_shader_clock") - if bary_builtin: - exts.append("SPV_KHR_fragment_shader_barycentric") - if ms and not msc: - exts.append("SPV_EXT_mesh_shader") - if pops: - caps.append("FragmentShaderPixelInterlockEXT") - exts.append("SPV_EXT_fragment_shader_interlock") - hdr = [f"OpCapability {c}" for c in caps] + [f'OpExtension "{e}"' for e in exts] + \ - ['%glsl = OpExtInstImport "GLSL.std.450"', - f"OpMemoryModel {'PhysicalStorageBuffer64' if psb else 'Logical'} GLSL450", - f"OpEntryPoint {model} %main \"main\" {' '.join(iface)}"] - if cs: - hdr.append("OpExecutionMode %main LocalSize {} {} {}".format(*gen.cs["size"])) - if gsx: - hdr += ["OpExecutionMode %main Triangles", "OpExecutionMode %main Invocations 1", - "OpExecutionMode %main OutputTriangleStrip", f"OpExecutionMode %main OutputVertices {gen.gs['maxv']}"] - if msc: - hdr.append("OpExecutionMode %main LocalSize {} {} {}".format(*gen.ms["size"])) - elif ms: - hdr += ["OpExecutionMode %main LocalSize {} {} {}".format(*gen.ms["size"]), - f"OpExecutionMode %main OutputVertices {gen.ms['maxv']}", - f"OpExecutionMode %main OutputPrimitivesEXT {gen.ms['maxp']}", - "OpExecutionMode %main OutputTrianglesEXT"] - if gen.stage == "ps": - hdr.append("OpExecutionMode %main OriginUpperLeft") - if pops: - hdr.append("OpExecutionMode %main PixelInterlockOrderedEXT") - if gen.writes_depth: - hdr.append("OpExecutionMode %main DepthReplacing") - if FLOAT_CONTROLS: - hdr.append("OpExecutionMode %main SignedZeroInfNanPreserve 32") - if gen.uses_f64: - # SHADER-597: the same for doubles (Vulkan guarantees neither -0 nor NaN/inf for f64 without it), only - # in modules that declare Float64; --no-float-controls leaves it out with the other modes. - hdr.append("OpExecutionMode %main SignedZeroInfNanPreserve 64") - hdr.append("OpExecutionMode %main DenormPreserve 16") - dec = [] - if vs: - dec.append("OpDecorate %vertex_index BuiltIn VertexIndex") - dec.append("OpDecorate %instance_index BuiltIn InstanceIndex") - dec.append("OpDecorate %base_vertex BuiltIn BaseVertex") - dec.append("OpDecorate %base_instance BuiltIn BaseInstance") - if cs: - dec += ["OpDecorate %wg_id BuiltIn WorkgroupId", "OpDecorate %local_id BuiltIn LocalInvocationId"] - if gsx: - for r, sv in gen.gs["in"]: - dec.append("OpDecorate %gs_in_pos BuiltIn Position" if sv == 1 else f"OpDecorate %gs_in{r} Location {r}") - for r, sv in gen.gs["out"]: - dec.append("OpDecorate %gs_out_pos BuiltIn Position" if sv == 1 else f"OpDecorate %gs_out{r} Location {r}") - ms_clip_member = ms_cull_member = None - if ms: - dec += ["OpDecorate %wg_id BuiltIn WorkgroupId", "OpDecorate %num_wg BuiltIn NumWorkgroups", - "OpDecorate %local_index BuiltIn LocalInvocationIndex"] - if msc: - pass # no mesh outputs: the epilogue stores to the --mesh-compute buffer - elif ms_blk: - dec += ["OpDecorate %ms_vtx_blk Block", "OpMemberDecorate %ms_vtx_blk 0 BuiltIn Position"] - mi = 1 - if gen.uses_clip: - dec.append(f"OpMemberDecorate %ms_vtx_blk {mi} BuiltIn ClipDistance") - ms_clip_member = mi - mi += 1 - if gen.uses_cull: - dec.append(f"OpMemberDecorate %ms_vtx_blk {mi} BuiltIn CullDistance") - ms_cull_member = mi - mi += 1 - else: - dec.append("OpDecorate %ms_out_pos BuiltIn Position") - if not msc: - # CullPrimitiveEXT as Block+bool member (VUID-07036): array-of-bool is also legal, but - # SPIRV-Tools ≤2025.1 falsely rejects it (#5980); the Block form passes both old and new validators. - # PerPrimitiveEXT is a MemberDecorate on the bool (glslang / SPIRV-Tools MeshEXT tests). - dec += ["OpDecorate %ms_prim_idx BuiltIn PrimitiveTriangleIndicesEXT", - "OpDecorate %ms_cull_blk Block", - "OpMemberDecorate %ms_cull_blk 0 BuiltIn CullPrimitiveEXT", - "OpMemberDecorate %ms_cull_blk 0 PerPrimitiveEXT"] - dec += [f"OpDecorate %ms_out_param{n} Location {n}" for n in sorted(gen.ms_params)] - dec += [f"OpDecorate %ms_out_f16h{n}_{h} Location {gen.f16_half_locs[n][h]}" for n in ms_halves - for h in (0, 1)] - if vs: - if gen.uses_clip: - dec.append("OpDecorate %out_clip BuiltIn ClipDistance") - if gen.uses_cull: - dec.append("OpDecorate %out_cull BuiltIn CullDistance") - if gen.uses_layer: - dec.append("OpDecorate %out_layer BuiltIn Layer") - if gen.uses_viewport: - dec.append("OpDecorate %out_viewport BuiltIn ViewportIndex") - for name, tgt in gen.outputs.items(): - if name == "%out_pos": - dec.append("OpDecorate %out_pos BuiltIn Position") - else: - dec.append(f"OpDecorate {name} Location {int(''.join(ch for ch in tgt if ch.isdigit()))}") - for name, n in gen.inputs.items(): - dec.append(f"OpDecorate {name} Location {n}") - if n in gen.per_vertex: - dec.append(f"OpDecorate {name} PerVertexKHR") - elif name not in gen.interpolated: - dec.append(f"OpDecorate {name} Flat") - types = ["%void = OpTypeVoid", "%fn = OpTypeFunction %void", "%bool = OpTypeBool", "%uint = OpTypeInt 32 0", - "%int = OpTypeInt 32 1", "%float = OpTypeFloat 32", "%v4float = OpTypeVector %float 4", - "%v2float = OpTypeVector %float 2", "%umul = OpTypeStruct %uint %uint", - "%smul = OpTypeStruct %int %int", - "%n256 = OpConstant %uint 256", f"%n_sgprs = OpConstant %uint {gen.SGPRS + len(gen.parked)}", - "%arr_v = OpTypeArray %uint %n256", "%arr_s = OpTypeArray %uint %n_sgprs", - "%null_v = OpConstantNull %arr_v", "%null_s = OpConstantNull %arr_s", - "%_ptr_Function_arr_v = OpTypePointer Function %arr_v", "%_ptr_Function_arr_s = OpTypePointer Function %arr_s", - "%_ptr_Function_uint = OpTypePointer Function %uint", "%_ptr_Output_v4 = OpTypePointer Output %v4float", - "%_ptr_Input_int = OpTypePointer Input %int", "%_ptr_Input_v4 = OpTypePointer Input %v4float", - "%_ptr_Input_float = OpTypePointer Input %float", - "%f0 = OpConstant %float 0", "%f1 = OpConstant %float 1", "%true = OpConstantTrue %bool", - "%false = OpConstantFalse %bool", - "%_ptr_Function_bool = OpTypePointer Function %bool"] - if psb: - types += ["%ulong = OpTypeInt 64 0", "%c64_32 = OpConstant %ulong 32", "%long = OpTypeInt 64 1", - "%rt_uint = OpTypeRuntimeArray %uint", "%_ptr_PSB_arr = OpTypePointer PhysicalStorageBuffer %rt_uint", - "%_ptr_PSB_uint = OpTypePointer PhysicalStorageBuffer %uint"] - dec.append("OpDecorate %rt_uint ArrayStride 4") - types += [f"{name} = OpConstant %ulong {v}" for v, name in sorted(gen.lconsts.items())] - if tex: - # Bindless set 0: images (binding 0), samplers (binding 1), descriptor hash table (binding 2). - types += ["%img2d = OpTypeImage %float 2D 0 0 0 1 Unknown", "%smp = OpTypeSampler", - "%simg2d = OpTypeSampledImage %img2d", "%v2int = OpTypeVector %int 2", - "%rt_img = OpTypeRuntimeArray %img2d", "%rt_smp = OpTypeRuntimeArray %smp", - "%_ptr_UC_rt_img = OpTypePointer UniformConstant %rt_img", - "%_ptr_UC_rt_smp = OpTypePointer UniformConstant %rt_smp", - "%_ptr_UC_img = OpTypePointer UniformConstant %img2d", "%_ptr_UC_smp = OpTypePointer UniformConstant %smp", - "%rt_map = OpTypeRuntimeArray %uint", "%DescMap = OpTypeStruct %rt_map", - "%_ptr_SB_DescMap = OpTypePointer StorageBuffer %DescMap", "%_ptr_SB_uint = OpTypePointer StorageBuffer %uint"] - dec += ["OpDecorate %images DescriptorSet 0", "OpDecorate %images Binding 0", - "OpDecorate %samplers DescriptorSet 0", "OpDecorate %samplers Binding 1", - "OpDecorate %desc_map DescriptorSet 0", "OpDecorate %desc_map Binding 2", - "OpDecorate %DescMap Block", "OpMemberDecorate %DescMap 0 Offset 0", - "OpDecorate %rt_map ArrayStride 4", "OpDecorate %desc_map NonWritable"] - types += ["%v3float = OpTypeVector %float 3", "%v3int = OpTypeVector %int 3"] - if gen.uses_tex_array: - types += ["%img2da = OpTypeImage %float 2D 0 1 0 1 Unknown", "%simg2da = OpTypeSampledImage %img2da", - "%rt_imga = OpTypeRuntimeArray %img2da", - "%_ptr_UC_rt_imga = OpTypePointer UniformConstant %rt_imga", - "%_ptr_UC_imga = OpTypePointer UniformConstant %img2da"] - dec += ["OpDecorate %images_arr DescriptorSet 0", "OpDecorate %images_arr Binding 3"] - if gen.uses_storage3d: - types += ["%simg3d_u = OpTypeImage %uint 3D 0 0 0 2 R32ui", "%rt_simg3 = OpTypeRuntimeArray %simg3d_u", - "%_ptr_UC_rt_simg3 = OpTypePointer UniformConstant %rt_simg3", - "%_ptr_UC_simg3 = OpTypePointer UniformConstant %simg3d_u"] - if not gen.uses_storage: - types += ["%_ptr_Image_uint = OpTypePointer Image %uint"] - dec += ["OpDecorate %simages3d DescriptorSet 0", "OpDecorate %simages3d Binding 7"] - if gen.uses_tex_3d: - types += ["%img3d = OpTypeImage %float 3D 0 0 0 1 Unknown", "%simg3d = OpTypeSampledImage %img3d", - "%rt_img3 = OpTypeRuntimeArray %img3d", - "%_ptr_UC_rt_img3 = OpTypePointer UniformConstant %rt_img3", - "%_ptr_UC_img3 = OpTypePointer UniformConstant %img3d"] - dec += ["OpDecorate %images_3d DescriptorSet 0", "OpDecorate %images_3d Binding 6"] - if gen.uses_tex_1d: - types += ["%img1d = OpTypeImage %float 1D 0 0 0 1 Unknown", "%simg1d = OpTypeSampledImage %img1d", - "%rt_img1 = OpTypeRuntimeArray %img1d", - "%_ptr_UC_rt_img1 = OpTypePointer UniformConstant %rt_img1", - "%_ptr_UC_img1 = OpTypePointer UniformConstant %img1d"] - dec += ["OpDecorate %images_1d DescriptorSet 0", "OpDecorate %images_1d Binding 5"] - if gen.uses_storage: - types += ["%simg2d_u = OpTypeImage %uint 2D 0 0 0 2 R32ui", "%rt_simg = OpTypeRuntimeArray %simg2d_u", - "%_ptr_UC_rt_simg = OpTypePointer UniformConstant %rt_simg", - "%_ptr_UC_simg = OpTypePointer UniformConstant %simg2d_u", - "%_ptr_Image_uint = OpTypePointer Image %uint", "%v4uint = OpTypeVector %uint 4"] - dec += ["OpDecorate %simages DescriptorSet 0", "OpDecorate %simages Binding 4"] - if sg: - types += ["%_ptr_Input_uint = OpTypePointer Input %uint"] - dec += ["OpDecorate %sg_lane BuiltIn SubgroupLocalInvocationId"] - if gen.stage == "ps": - dec += ["OpDecorate %sg_lane Flat"] - gen.consts.setdefault(3, "%c3") - if vs: - gen.consts.setdefault(3, "%c3") # the instance index goes to v3 - if gen.uses_clip: - gen.cu(gen.clip_count) - if gen.uses_cull: - gen.cu(gen.cull_count) - if ms_blk: - gen.cu(0) - if ms_clip_member is not None: - gen.cu(ms_clip_member) - if ms_cull_member is not None: - gen.cu(ms_cull_member) - # The buffer-format tables below (uses_fmt_size, uses_store_views/uses_int_fetch) build their - # array types from gen.cu ids. Register those constants here, before the dump: a cu() call - # after it returns an id that is never defined, and spirv-as then rejects the module. - if gen.uses_fmt_size: - gen.cu(128) - for c in range(128): - if c in Gen.FORMATS: - gen.cu(Gen.FORMATS[c][0]) - if gen.uses_fmt_tables: - gen.cu(128) - gen.cu(17) - if gen.uses_store_views or gen.uses_int_fetch: - gen.cu(16) - for words in Gen.int_format_masks(): - for w in words: - gen.cu(w) - gen.consts.setdefault(0, "%c0") - for v, name in sorted(gen.consts.items()): - types.append(f"{name} = OpConstant %uint {v}") - written = dict(gen.consts) # what the module defines; insert_late_constants adds what assemble asks for later - if gen.desc_fn: - types.append("%fn_desc_lookup = OpTypeFunction %uint " + " ".join(["%uint"] * 8)) - if gen.tbuffer_norm_fns or gen.fmt_enc_fn: - types.append("%fn_tbuffer_norm = OpTypeFunction %uint %uint") # also the element-size function's type - if gen.fmt_fn or gen.fmt_enc_fn: - types.append("%v4uint_fmt = OpTypeVector %uint 4") # dedupe_types merges it with any other uvec4 - if gen.fmt_fn: - # The decode function takes the format code and the element's four dwords as a v4uint: a type of its own - # structure, so it never repeats another function type in the module (SPIR-V forbids that). - types.append("%fn_fmt_dec = OpTypeFunction %uint %uint %v4uint_fmt") - types.append("%fn_fmt_norm = OpTypeFunction %uint %uint %uint") - if gen.fmt_enc_fn: - types.append("%fn_fmt_encode = OpTypeFunction %v4uint_fmt " + " ".join(["%uint"] * 29)) - for arity, fn_type in sorted(gen.x_round_fn_types.items()): - types.append(f"{fn_type} = OpTypeFunction %uint " + " ".join(["%uint"] * arity)) - # dedupe_types keeps the first uvec4 it meets: when the typed-image types follow, declare the ballot type after - # them, so a shader that gains a ballot keeps the name %v4uint_st (SHADER-1016). - st_types = gen.uses_store_views or gen.uses_int_fetch or gen.uses_d16_image - if gen.uses_ballot and not st_types: - types.append("%v4uint_bal = OpTypeVector %uint 4") # dedupe_types merges it with any other uvec4 - if gen.uses_bvh and not any(t.startswith("%v3float = ") for t in types): - types.append("%v3float = OpTypeVector %float 3") - if gen.partial_color_outputs: - types.append("%initial_mrt = OpConstantNull %v4float") - gvars = [f"{n} = OpVariable %_ptr_Output_v4 Output" + (" %initial_mrt" if n in gen.partial_color_outputs else "") - for n in gen.outputs] - # Push constants: s0..s31 user data, then the tail: the 64-bit host address of the Xbox GPU VA window (heap - # base), the code base and, with --mesh-compute, the output address. --pc-tail-ubo moves the tail to %pc_tail. - tail = ["%uint"] * (6 if msc else 4) - types += [f"%n_ud = OpConstant %uint {USER_SGPRS}", "%arr_ud = OpTypeArray %uint %n_ud", - " ".join(["%UserData = OpTypeStruct %arr_ud"] + ([] if PC_TAIL_UBO else tail)), - "%_ptr_PC_UserData = OpTypePointer PushConstant %UserData", - "%_ptr_PC_uint = OpTypePointer PushConstant %uint"] - dec += ["OpDecorate %arr_ud ArrayStride 4", "OpDecorate %UserData Block", "OpMemberDecorate %UserData 0 Offset 0"] - if not PC_TAIL_UBO: - dec += [f"OpMemberDecorate %UserData {k + 1} Offset {4 * USER_SGPRS + 4 * k}" for k in range(len(tail))] - gvars += ["%user_data = OpVariable %_ptr_PC_UserData PushConstant"] - if gen.uses_pc_tail: - types += [" ".join(["%PcTail = OpTypeStruct"] + tail), - "%_ptr_Uniform_PcTail = OpTypePointer Uniform %PcTail", - "%_ptr_Uniform_uint_tail = OpTypePointer Uniform %uint"] - dec += ["OpDecorate %PcTail Block"] + [f"OpMemberDecorate %PcTail {k} Offset {4 * k}" for k in range(len(tail))] - dec += [f"OpDecorate %pc_tail DescriptorSet {PC_TAIL_SET}", f"OpDecorate %pc_tail Binding {PC_TAIL_BINDING}"] - gvars += ["%pc_tail = OpVariable %_ptr_Uniform_PcTail Uniform"] - if gen.uses_fhalf: - types += ["%fhalf_g = OpConstant %float 0.5"] - if gen.uses_f64: - types += ["%double = OpTypeFloat 64"] - if gen.uses_f64 or gen.uses_clock: - types += ["%v2uint_d = OpTypeVector %uint 2"] - if gen.uses_ballot and not st_types: - types += ["%v4uint_bal = OpTypeVector %uint 4"] - if gen.uses_fmt_size: - sizes = [Gen.FORMATS[c][0] if c in Gen.FORMATS else 0 for c in range(128)] - types += [f"%fmt_size_arr = OpTypeArray %uint {gen.cu(128)}", - "%_ptr_Private_fmt_size = OpTypePointer Private %fmt_size_arr"] - if not (gen.uses_store_views or gen.uses_int_fetch or gen.uses_d16_image): - types += ["%_ptr_Private_uint = OpTypePointer Private %uint"] - types += ["%fmt_size_init = OpConstantComposite %fmt_size_arr " + " ".join(gen.cu(v) for v in sizes)] - gvars += ["%fmt_size_tab = OpVariable %_ptr_Private_fmt_size Private %fmt_size_init"] - if gen.uses_fmt_tables: - # The run-time format's kind and channel widths, and the repeat constants of the exact norm quotient. - types += [f"%fmt_desc_arr = OpTypeArray %uint {gen.cu(128)}", - "%_ptr_Private_fmt_desc = OpTypePointer Private %fmt_desc_arr", - "%_ptr_Private_fmt_elem = OpTypePointer Private %uint", - f"%fmt_rep_arr = OpTypeArray %ulong {gen.cu(17)}", - "%_ptr_Private_fmt_rep = OpTypePointer Private %fmt_rep_arr", - "%_ptr_Private_fmt_elem64 = OpTypePointer Private %ulong"] - types.append("%fmt_desc_init = OpConstantComposite %fmt_desc_arr " + - " ".join(gen.consts[v] for v in Gen.fmt_desc_table())) - types.append("%fmt_norm_rep_init = OpConstantComposite %fmt_rep_arr " + - " ".join(gen.lconsts[v] for v in Gen.fmt_norm_reps())) - gvars += ["%fmt_desc_tab = OpVariable %_ptr_Private_fmt_desc Private %fmt_desc_init", - "%fmt_norm_rep_tab = OpVariable %_ptr_Private_fmt_rep Private %fmt_norm_rep_init"] - if gen.uses_store_views or gen.uses_int_fetch or gen.uses_d16_image: - u, si = Gen.int_format_masks() - types += ["%v4uint_st = OpTypeVector %uint 4", "%v4int_st = OpTypeVector %int 4", - *(["%v4uint_bal = OpTypeVector %uint 4"] if gen.uses_ballot else []), - f"%fmt_mask_arr = OpTypeArray %uint {gen.cu(16)}", - "%_ptr_Private_fmt = OpTypePointer Private %fmt_mask_arr", - "%_ptr_Private_uint = OpTypePointer Private %uint"] - for nm, words in (("uint", u), ("sint", si)) + ( - (("norm", Gen.float_format_masks()[0]), ("f32", Gen.float_format_masks()[1])) - if gen.uses_d16_image else ()): - ids = " ".join(gen.cu(w) for w in words) - types += [f"%fmt_{nm}_init = OpConstantComposite %fmt_mask_arr {ids}"] - gvars += [f"%fmt_{nm}_mask = OpVariable %_ptr_Private_fmt Private %fmt_{nm}_init"] - # Typed image_load: uint/sint aliases of the dimension's sampled array (same set and binding; Vulkan allows - # several variables on one binding when the descriptor type fits). The runtime binds each image's view in - # its own format there, so the alias whose component type matches it is the one a shader reads through. - for di in sorted(gen.uses_int_fetch): - _, sdim, arr, _ = next(v for v in Gen.STORE_DIMS.values() if v[0] == di) - for cls, st in ((1, "%uint"), (2, "%int")): - types += [f"%itximg{cls}_{di} = OpTypeImage {st} {sdim} 0 {arr} 0 1 Unknown", - f"%rt_itx{cls}_{di} = OpTypeRuntimeArray %itximg{cls}_{di}", - f"%_ptr_UC_rt_itx{cls}_{di} = OpTypePointer UniformConstant %rt_itx{cls}_{di}", - f"%_ptr_UC_itx{cls}_{di} = OpTypePointer UniformConstant %itximg{cls}_{di}"] - if gen.uses_int_sampler: - types.append(f"%itxsamp{cls}_{di} = OpTypeSampledImage %itximg{cls}_{di}") - dec += [f"OpDecorate %itx{cls}_{di} DescriptorSet 0", - f"OpDecorate %itx{cls}_{di} Binding {Gen.SAMPLED_BINDINGS[di]}"] - gvars += [f"%itx{cls}_{di} = OpVariable %_ptr_UC_rt_itx{cls}_{di} UniformConstant"] - for di in sorted(gen.uses_store_views): - _, sdim, arr, _ = next(v for v in Gen.STORE_DIMS.values() if v[0] == di) - for cls, st in enumerate(("%float", "%uint", "%int")): - types += [f"%stimg{cls}_{di} = OpTypeImage {st} {sdim} 0 {arr} 0 2 Unknown", - f"%rt_stv{cls}_{di} = OpTypeRuntimeArray %stimg{cls}_{di}", - f"%_ptr_UC_rt_stv{cls}_{di} = OpTypePointer UniformConstant %rt_stv{cls}_{di}", - f"%_ptr_UC_stv{cls}_{di} = OpTypePointer UniformConstant %stimg{cls}_{di}"] - dec += [f"OpDecorate %stv{cls}_{di} DescriptorSet 0", f"OpDecorate %stv{cls}_{di} Binding {8 + 3 * di + cls}"] - if gen.coherent_images: - dec.append(f"OpDecorate %stv{cls}_{di} Coherent") - gvars += [f"%stv{cls}_{di} = OpVariable %_ptr_UC_rt_stv{cls}_{di} UniformConstant"] - if gsx: - nst = gen.gs["maxv"] * gen.gs["nreg"] - types += [f"%gs_arr_in = OpTypeArray %v4float {gen.cu(3)}", "%_ptr_Input_gs_arr = OpTypePointer Input %gs_arr_in", - "%_ptr_Output_v4_gs = OpTypePointer Output %v4float", - f"%gs_stage_arr = OpTypeArray %v4float {gen.cu(nst)}", - "%_ptr_Function_gs_stage = OpTypePointer Function %gs_stage_arr", - "%_ptr_Function_v4_gs = OpTypePointer Function %v4float", - "%null_gs_stage = OpConstantNull %gs_stage_arr"] - gvars += [("%gs_in_pos" if sv == 1 else f"%gs_in{r}") + " = OpVariable %_ptr_Input_gs_arr Input" - for r, sv in gen.gs["in"]] - gvars += [("%gs_out_pos" if sv == 1 else f"%gs_out{r}") + " = OpVariable %_ptr_Output_v4_gs Output" - for r, sv in gen.gs["out"]] - if ms: - maxv, maxp = gen.cu(gen.ms["maxv"]), gen.cu(gen.ms["maxp"]) - types += ["%v3uint = OpTypeVector %uint 3", "%_ptr_Input_v3u = OpTypePointer Input %v3uint", - "%_ptr_Input_uint_ms = OpTypePointer Input %uint", - "%_ptr_WG_uint_ms = OpTypePointer Workgroup %uint", - f"%ms_arr_v4 = OpTypeArray %v4float {maxv}", "%_ptr_Out_ms_arr_v4 = OpTypePointer Output %ms_arr_v4", - "%_ptr_Out_v4_ms = OpTypePointer Output %v4float", - f"%ms_arr_idx = OpTypeArray %v3uint {maxp}", "%_ptr_Out_ms_arr_idx = OpTypePointer Output %ms_arr_idx", - "%_ptr_Out_v3u_ms = OpTypePointer Output %v3uint", - "%ms_cull_blk = OpTypeStruct %bool", - f"%ms_arr_cull = OpTypeArray %ms_cull_blk {maxp}", - "%_ptr_Out_ms_arr_cull = OpTypePointer Output %ms_arr_cull", - "%_ptr_Out_bool_ms = OpTypePointer Output %bool", - "%_ptr_Function_v4_ms = OpTypePointer Function %v4float", - "%_ptr_Function_bool_ms = OpTypePointer Function %bool", - "%null_v4_ms = OpConstantNull %v4float"] - if ms and (gen.uses_clip or gen.uses_cull): # staging arrays; the Output block only without msc - types += ["%_ptr_Function_float = OpTypePointer Function %float", - "%_ptr_Out_float_ms = OpTypePointer Output %float"] - blk_fields = ["%v4float"] - if gen.uses_clip: - types += [f"%ms_arr_clip = OpTypeArray %float {gen.cu(gen.clip_count)}", - "%_ptr_Fn_ms_clip = OpTypePointer Function %ms_arr_clip", - "%null_ms_clip = OpConstantNull %ms_arr_clip"] - blk_fields.append("%ms_arr_clip") - if gen.uses_cull: - types += [f"%ms_arr_cull_d = OpTypeArray %float {gen.cu(gen.cull_count)}", - "%_ptr_Fn_ms_cull_d = OpTypePointer Function %ms_arr_cull_d", - "%null_ms_cull_d = OpConstantNull %ms_arr_cull_d"] - blk_fields.append("%ms_arr_cull_d") - types += [f"%ms_vtx_blk = OpTypeStruct {' '.join(blk_fields)}", - f"%ms_arr_vtx_blk = OpTypeArray %ms_vtx_blk {maxv}", - "%_ptr_Out_ms_arr_vtx_blk = OpTypePointer Output %ms_arr_vtx_blk"] - gvars += ["%wg_id = OpVariable %_ptr_Input_v3u Input", "%num_wg = OpVariable %_ptr_Input_v3u Input", - "%local_index = OpVariable %_ptr_Input_uint_ms Input", - "%ms_counts = OpVariable %_ptr_WG_uint_ms Workgroup"] - if not msc: - gvars += [("%ms_out_vtx = OpVariable %_ptr_Out_ms_arr_vtx_blk Output" if ms_blk else - "%ms_out_pos = OpVariable %_ptr_Out_ms_arr_v4 Output"), - "%ms_prim_idx = OpVariable %_ptr_Out_ms_arr_idx Output", - "%ms_cull = OpVariable %_ptr_Out_ms_arr_cull Output"] - gvars += [f"%ms_out_param{n} = OpVariable %_ptr_Out_ms_arr_v4 Output" for n in sorted(gen.ms_params)] - gvars += [f"%ms_out_f16h{n}_{h} = OpVariable %_ptr_Out_ms_arr_v4 Output" for n in ms_halves for h in (0, 1)] - if gen.uses_lds: - types += [f"%lds_arr = OpTypeArray %uint {gen.cu(gen.lds_dwords)}", - "%_ptr_WG_lds = OpTypePointer Workgroup %lds_arr", "%_ptr_WG_uint = OpTypePointer Workgroup %uint"] - gvars += ["%lds = OpVariable %_ptr_WG_lds Workgroup"] - if gen.emulate: - types += [f"%x_arr = OpTypeArray %uint {gen.cu(x_sink + 1)}", - "%_ptr_WG_x_arr = OpTypePointer Workgroup %x_arr", "%_ptr_WG_uint_x = OpTypePointer Workgroup %uint"] - gvars += ["%x_buf = OpVariable %_ptr_WG_x_arr Workgroup"] - elif gen.bar_rounds and not gen.bar_counts_in_lds(): - # Barrier rounds: one count of the invocations not done per round, 3 slots by round mod 3 (bar_scheduler). - # With a large LDS the count borrows an LDS word instead (SHADER-579, bar_counts_in_lds). - types += [f"%x_arr = OpTypeArray %uint {gen.cu(3)}", - "%_ptr_WG_x_arr = OpTypePointer Workgroup %x_arr", "%_ptr_WG_uint_x = OpTypePointer Workgroup %uint"] - gvars += ["%x_buf = OpVariable %_ptr_WG_x_arr Workgroup"] - if cs: - types += ["%v3uint = OpTypeVector %uint 3", "%_ptr_Input_v3u = OpTypePointer Input %v3uint"] - gvars += ["%wg_id = OpVariable %_ptr_Input_v3u Input", "%local_id = OpVariable %_ptr_Input_v3u Input"] - if gen.uses_lds: - types += [f"%lds_arr = OpTypeArray %uint {gen.cu(max(gen.lds_dwords, 1))}", - "%_ptr_WG_lds = OpTypePointer Workgroup %lds_arr", "%_ptr_WG_uint = OpTypePointer Workgroup %uint"] - gvars += ["%lds = OpVariable %_ptr_WG_lds Workgroup"] - # SHADER-309: what fit_shared_memory could not shrink. The LDS counts at its RSRC2 allocation when that is - # larger than the array (clipped to 16384 dwords): a declared allocation over the cap is refused, not cut. - # An access past the allocation is out of range on hardware (reads 0, writes dropped; lds_access). - lds_b = 4 * max(gen.lds_dwords, gen.lds_declared, 1) if gen.uses_lds else 0 - wg = lds_b + gen.x_buf_bytes() - if wg > MAX_SHARED_BYTES: - raise Unsupported(f"CS workgroup memory {wg} B (LDS {lds_b} B + " - f"{'wave64 exchange' if gen.emulate else 'barrier rounds'} {gen.x_buf_bytes()} B) " - f"over maxComputeSharedMemorySize {MAX_SHARED_BYTES} B") - if gen.frag_inputs or bary: - dec += ["OpDecorate %frag_coord BuiltIn FragCoord"] - gvars += ["%frag_coord = OpVariable %_ptr_Input_v4 Input"] - if "front" in gen.frag_inputs.values(): - types += ["%_ptr_Input_bool = OpTypePointer Input %bool"] - dec += ["OpDecorate %front_facing BuiltIn FrontFacing"] - gvars += ["%front_facing = OpVariable %_ptr_Input_bool Input"] - if bary: - if not tex: - types += ["%v3float = OpTypeVector %float 3"] - types += ["%_ptr_Input_v3f = OpTypePointer Input %v3float"] - # Default (smooth) interpolation is perspective-correct, matching BaryCoordKHR (not BaryCoordNoPerspKHR). - dec += ["OpDecorate %bary BuiltIn BaryCoordKHR" if bary_builtin - else f"OpDecorate %bary Location {gen.bary_location}"] - gvars += ["%bary = OpVariable %_ptr_Input_v3f Input"] - if gen.vertex_inputs: - types += ["%v4uint_in = OpTypeVector %uint 4", "%v4int_in = OpTypeVector %int 4", - "%_ptr_Input_v4u = OpTypePointer Input %v4uint_in", "%_ptr_Input_v4i = OpTypePointer Input %v4int_in"] - for reg, ctype in gen.vertex_inputs: - dec.append(f"OpDecorate %vin{reg} Location {reg}") - if gen.writes_depth: - types += ["%_ptr_Output_float = OpTypePointer Output %float"] - dec += ["OpDecorate %out_depth BuiltIn FragDepth"] - gvars += ["%out_depth = OpVariable %_ptr_Output_float Output"] - if vs: - if gen.uses_clip or gen.uses_cull: - types += ["%_ptr_Output_float = OpTypePointer Output %float"] - if gen.uses_clip: - types += [f"%arr_clip = OpTypeArray %float {gen.cu(gen.clip_count)}", - "%_ptr_Out_arr_clip = OpTypePointer Output %arr_clip"] - gvars += ["%out_clip = OpVariable %_ptr_Out_arr_clip Output"] - if gen.uses_cull: - types += [f"%arr_cull = OpTypeArray %float {gen.cu(gen.cull_count)}", - "%_ptr_Out_arr_cull = OpTypePointer Output %arr_cull"] - gvars += ["%out_cull = OpVariable %_ptr_Out_arr_cull Output"] - if gen.uses_layer or gen.uses_viewport: - types += ["%_ptr_Output_int = OpTypePointer Output %int"] - if gen.uses_layer: - gvars += ["%out_layer = OpVariable %_ptr_Output_int Output"] - if gen.uses_viewport: - gvars += ["%out_viewport = OpVariable %_ptr_Output_int Output"] - if gen.per_vertex: # the three vertices' raw words for Gen.attribute - types += [f"%arr_pv4 = OpTypeArray %v4float {gen.cu(3)}", "%_ptr_Input_pv4 = OpTypePointer Input %arr_pv4"] - gvars += [f"{n} = OpVariable {'%_ptr_Input_pv4' if k in gen.per_vertex else '%_ptr_Input_v4'} Input" - for n, k in gen.inputs.items()] - if sg: - gvars += ["%sg_lane = OpVariable %_ptr_Input_uint Input"] - if tex: - gvars += ["%images = OpVariable %_ptr_UC_rt_img UniformConstant", - "%samplers = OpVariable %_ptr_UC_rt_smp UniformConstant", - "%desc_map = OpVariable %_ptr_SB_DescMap StorageBuffer"] - if gen.uses_tex_array: - gvars += ["%images_arr = OpVariable %_ptr_UC_rt_imga UniformConstant"] - if gen.uses_storage: - gvars += ["%simages = OpVariable %_ptr_UC_rt_simg UniformConstant"] - if gen.uses_tex_1d: - gvars += ["%images_1d = OpVariable %_ptr_UC_rt_img1 UniformConstant"] - if gen.uses_tex_3d: - gvars += ["%images_3d = OpVariable %_ptr_UC_rt_img3 UniformConstant"] - if gen.uses_storage3d: - gvars += ["%simages3d = OpVariable %_ptr_UC_rt_simg3 UniformConstant"] - if vs: - gvars.append("%vertex_index = OpVariable %_ptr_Input_int Input") - gvars.append("%instance_index = OpVariable %_ptr_Input_int Input") - gvars.append("%base_vertex = OpVariable %_ptr_Input_int Input") - gvars.append("%base_instance = OpVariable %_ptr_Input_int Input") - for reg, ctype in gen.vertex_inputs: - ptr = {1: "%_ptr_Input_v4u", 2: "%_ptr_Input_v4i"}.get(ctype, "%_ptr_Input_v4") - gvars.append(f"%vin{reg} = OpVariable {ptr} Input") - fn = ["%main = OpFunction %void None %fn", "%entry = OpLabel", - # Registers start at zero (deterministic); real inputs are written explicitly at entry. - "%vgpr = OpVariable %_ptr_Function_arr_v Function %null_v", - "%sgpr = OpVariable %_ptr_Function_arr_s Function %null_s", - "%vcc = OpVariable %_ptr_Function_uint Function %c0", "%m0 = OpVariable %_ptr_Function_uint Function %c0", - "%vcc_hi = OpVariable %_ptr_Function_uint Function %c0", - "%scc = OpVariable %_ptr_Function_uint Function %c0", - *(["%mode_r16 = OpVariable %_ptr_Function_uint Function %c0"] if gen.round_mode else []), - "%active = OpVariable %_ptr_Function_bool Function %true", - *[f"{var} = OpVariable {ptr} Function" for var, ptr in gen.eager_vars]] - if gen.vm_latch: - fn += ["%vm_mask = OpVariable %_ptr_Function_bool Function %true", - "%vm_set = OpVariable %_ptr_Function_bool Function %false"] - for t in gen.col_latched: - fn += [f"%col_mask_{t} = OpVariable %_ptr_Function_bool Function %true", - f"%col_set_{t} = OpVariable %_ptr_Function_bool Function %false"] - if gen.emulate: - fn += ["%x_it = OpVariable %_ptr_Function_uint Function %c0", - "%x_bar = OpVariable %_ptr_Function_bool Function %false", - "%x_chain = OpVariable %_ptr_Function_bool Function %false"] - if gen.emulate_plan and gen.emulate_plan.get("mini_blocks"): - fn.append("%x_ldone = OpVariable %_ptr_Function_bool Function %false") - fn += [f"{var} = OpVariable {ptr} Function" for var, ptr in gen.x_spills] - if gen.uses_perm: - fn.append("%x_perm = OpVariable %_ptr_Function_uint Function %c0") - elif gen.bar_rounds: - fn += ["%x_it = OpVariable %_ptr_Function_uint Function %c0", - "%x_bar = OpVariable %_ptr_Function_bool Function %false"] - if gen.bar_counts_in_lds(): - fn.append("%xb_save = OpVariable %_ptr_Function_uint Function %c0") - fn += [f"{var} = OpVariable {ptr} Function" for var, ptr in gen.x_spills] - # User data: s0..s31 are loaded at entry from a push-constant block (the driver's user-SGPR setup). - if gen.uses_heap: - gen.consts.setdefault(1, "%c1") - gen.consts.setdefault(2, "%c2") - fn += [pc_tail_chain("%ud_base_lo_p", 1, gen.cu), pc_tail_chain("%ud_base_hi_p", 2, gen.cu)] + HEAP_BASE_ENTRY - if gen.uses_codebase: - fn += [pc_tail_chain("%ud_code_lo_p", 3, gen.cu), pc_tail_chain("%ud_code_hi_p", 4, gen.cu)] - for i in range(USER_SGPRS): - fn += [f"%ud{i}p = OpAccessChain %_ptr_PC_uint %user_data %c0 {gen.cu(i)}", - f"%ud{i} = OpLoad %uint %ud{i}p", - f"%ud{i}s = OpAccessChain %_ptr_Function_uint %sgpr {gen.cu(i)}", - f"OpStore %ud{i}s %ud{i}"] - if vs: - # The hardware's VS input VGPRs are zero-based: v0 is the vertex id without the draw's base vertex and v3 - # the instance id without its first instance (Mesa: ac.vertex_id = load_vertex_id_zero_base, the base in - # the base_vertex SGPR; ac.instance_id = load_instance_id, the base in start_instance). Vulkan's - # VertexIndex / InstanceIndex include firstVertex|vertexOffset / firstInstance, so subtract BaseVertex / - # BaseInstance. GPU-checked with runtime/test/shaders/vs_base_ids.asm (VKH_DRAW=16,7). - fn += ["%vi = OpLoad %int %vertex_index", "%bv = OpLoad %int %base_vertex", "%vz = OpISub %int %vi %bv", - "%viu = OpBitcast %uint %vz", - "%v0p = OpAccessChain %_ptr_Function_uint %vgpr %c0", "OpStore %v0p %viu"] - # v3 = instance id. Over the corpus, the 494 VS that read v3 before writing it are exactly ones whose input - # signature declares SV_InstanceID, and no VS reads v1 or v2 on entry. - fn += ["%ii = OpLoad %int %instance_index", "%bi = OpLoad %int %base_instance", "%iz = OpISub %int %ii %bi", - "%iiu = OpBitcast %uint %iz", - f"%v3p = OpAccessChain %_ptr_Function_uint %vgpr {gen.cu(3)}", "OpStore %v3p %iiu"] - if gsx: - fn[2:2] = ["%gs_stage = OpVariable %_ptr_Function_gs_stage Function %null_gs_stage", - "%gs_emitted = OpVariable %_ptr_Function_uint Function %c0"] - # Input vertex i at dword 64*i (v0 = vtx0 | vtx1 << 16, v1 = vtx2); s3[15:8] = 64 lanes of work (the - # prologue's s_bfm/s_cselect then leave EXEC full), s3[23:16] = 0. - fn += [f"%gv0p = OpAccessChain %_ptr_Function_uint %vgpr {gen.cu(0)}", f"OpStore %gv0p {gen.cu(64 << 16)}", - f"%gv1p = OpAccessChain %_ptr_Function_uint %vgpr {gen.cu(1)}", f"OpStore %gv1p {gen.cu(128)}", - f"%gs3p = OpAccessChain %_ptr_Function_uint %sgpr {gen.cu(3)}", f"OpStore %gs3p {gen.cu(0x4000)}"] - if ms: - fn[2:2] = ["%ms_pos = OpVariable %_ptr_Function_v4_ms Function %null_v4_ms", - "%ms_prim = OpVariable %_ptr_Function_uint Function %c0", - "%ms_has_vtx = OpVariable %_ptr_Function_bool_ms Function %false", - "%ms_has_prim = OpVariable %_ptr_Function_bool_ms Function %false"] + \ - (["%ms_clip = OpVariable %_ptr_Fn_ms_clip Function %null_ms_clip"] if gen.uses_clip else []) + \ - (["%ms_cull_dist = OpVariable %_ptr_Fn_ms_cull_d Function %null_ms_cull_d"] if gen.uses_cull else []) + \ - [f"%ms_param{n} = OpVariable %_ptr_Function_v4_ms Function %null_v4_ms" for n in sorted(gen.ms_params)] - # v5 = first launch vertex ID of the lane = linear group index * NumThreads + local index (the game's mesh - # entry does v5 >> 7 on lane 0 to get the group index; NumThreads is 128 in this corpus). - # s3 = merged-wave info with the wave id in [27:24]. - fn += ["%wgi = OpLoad %v3uint %wg_id", "%nwg = OpLoad %v3uint %num_wg", "%lidx = OpLoad %uint %local_index", - "%wgx = OpCompositeExtract %uint %wgi 0", "%wgy = OpCompositeExtract %uint %wgi 1", - "%wgz = OpCompositeExtract %uint %wgi 2", "%nwx = OpCompositeExtract %uint %nwg 0", - "%nwy = OpCompositeExtract %uint %nwg 1", "%nxy = OpIMul %uint %nwx %nwy", - "%wz = OpIMul %uint %wgz %nxy", "%wy = OpIMul %uint %wgy %nwx", "%wyz = OpIAdd %uint %wy %wz", - "%wlin = OpIAdd %uint %wgx %wyz", - f"%wbase = OpIMul %uint %wlin {gen.cu(gen.ms['threads'])}", "%v5v = OpIAdd %uint %wbase %lidx", - f"%v5p = OpAccessChain %_ptr_Function_uint %vgpr {gen.cu(5)}", "OpStore %v5p %v5v", - f"%wave = OpShiftRightLogical %uint %lidx {gen.cu(6)}", - f"%mwi = OpShiftLeftLogical %uint %wave {gen.cu(24)}", - f"%s3p = OpAccessChain %_ptr_Function_uint %sgpr {gen.cu(3)}", "OpStore %s3p %mwi"] - if cs: - # After the user-data copy: workgroup ids overwrite s[user..], thread ids go to v0..v2. - fn += ["%wgi = OpLoad %v3uint %wg_id", "%lci = OpLoad %v3uint %local_id"] - for k, c in enumerate(gen.cs["tgid"]): - r = gen.cs["user"] + k - fn += [f"%wg{c} = OpCompositeExtract %uint %wgi {c}", - f"%wgp{c} = OpAccessChain %_ptr_Function_uint %sgpr {gen.cu(r)}", f"OpStore %wgp{c} %wg{c}"] - for c in range(gen.cs["tid"] + 1): - fn += [f"%li{c} = OpCompositeExtract %uint %lci {c}", - f"%lip{c} = OpAccessChain %_ptr_Function_uint %vgpr {gen.cu(c)}", f"OpStore %lip{c} %li{c}"] - if gen.cs["tg_size"]: - # TG_SIZE_EN (RSRC2 bit 10): the SGPR after the workgroup ids holds the number of waves in the group in - # [5:0] and this wave's index in it in [11:6] (Mesa ac_nir_lower_intrinsics_to_args.c, GFX6-10: - # load_num_subgroups is tg_size[5:0], load_subgroup_id tg_size[11:6], and a wave64 compute shader's - # local invocation index is mbcnt(~0, tg_size & 0xfc0)), the wave index again in [24:20] (Mesa's GFX10.3 - # field) and bit 31 set in the group's first wave. Measured on gfx1036 through tools/hw_oracle (#6446: - # 100, 128 and 133 threads, wave32 and wave64; e.g. wave32 x 128 gives 80000004 00100044 00200084 - # 003000c4); the other bits were 0 there. One pipeline-library program reads [24:20]. Not measured on - # gfx1013. Thread i is in wave i / W, as for s_get_waveid_in_workgroup. - sx, sy, sz = gen.cs["size"] - w = 64 if gen.wave64 else 32 - r = gen.cs["user"] + len(gen.cs["tgid"]) - fn += ["%tgx = OpCompositeExtract %uint %lci 0", "%tgy = OpCompositeExtract %uint %lci 1", - "%tgz = OpCompositeExtract %uint %lci 2", - f"%tgyx = OpIMul %uint %tgy {gen.cu(sx)}", f"%tgzx = OpIMul %uint %tgz {gen.cu(sx * sy)}", - "%tgi0 = OpIAdd %uint %tgx %tgyx", "%tgi = OpIAdd %uint %tgi0 %tgzx", - f"%tgw = OpShiftRightLogical %uint %tgi {gen.cu(w.bit_length() - 1)}", - f"%tgws = OpShiftLeftLogical %uint %tgw {gen.cu(6)}", - f"%tgwh = OpShiftLeftLogical %uint %tgw {gen.cu(20)}", - f"%tgf0 = OpIEqual %bool %tgw {gen.cu(0)}", - f"%tgf = OpSelect %uint %tgf0 {gen.cu(0x80000000)} {gen.cu(0)}", - f"%tgv0 = OpBitwiseOr %uint %tgws {gen.cu(-(-(sx * sy * sz) // w))}", - "%tgv1 = OpBitwiseOr %uint %tgv0 %tgwh", "%tgv = OpBitwiseOr %uint %tgv1 %tgf", - f"%tgp = OpAccessChain %_ptr_Function_uint %sgpr {gen.cu(r)}", "OpStore %tgp %tgv"] - if gen.frag_inputs: - fn += ["%fc = OpLoad %v4float %frag_coord"] - if bary: - fn += ["%bc = OpLoad %v3float %bary"] - for r, c in gen.frag_inputs.items(): - if str(c).startswith("bary"): - k = 1 if c == "bary_i" else 2 - fn += [f"%bc{k} = OpCompositeExtract %float %bc {k}", f"%bcu{k} = OpBitcast %uint %bc{k}", - f"%bcp{k} = OpAccessChain %_ptr_Function_uint %vgpr {gen.cu(r)}", f"OpStore %bcp{k} %bcu{k}"] - continue - if c == "front": - fn += ["%ff = OpLoad %bool %front_facing", "%ffm1 = OpFNegate %float %f1", - "%ffv = OpSelect %float %ff %f1 %ffm1", "%ffu = OpBitcast %uint %ffv", - f"%ffp = OpAccessChain %_ptr_Function_uint %vgpr {gen.cu(r)}", "OpStore %ffp %ffu"] - continue - fn += [f"%fc{c} = OpCompositeExtract %float %fc {c}", f"%fcu{c} = OpBitcast %uint %fc{c}", - f"%fcp{c} = OpAccessChain %_ptr_Function_uint %vgpr {gen.cu(r)}", f"OpStore %fcp{c} %fcu{c}"] - for reg, ctype in gen.vertex_inputs: - vt = {1: "%v4uint_in", 2: "%v4int_in"}.get(ctype, "%v4float") - st = {1: "%uint", 2: "%int"}.get(ctype, "%float") - fn.append(f"%vinv{reg} = OpLoad {vt} %vin{reg}") - for c in range(4): - vg = 4 + 4 * reg + c - fn += [f"%vinc{reg}_{c} = OpCompositeExtract {st} %vinv{reg} {c}", - f"%vinb{reg}_{c} = OpBitcast %uint %vinc{reg}_{c}" if ctype != 1 else - f"%vinb{reg}_{c} = OpCopyObject %uint %vinc{reg}_{c}", - f"%vinp{reg}_{c} = OpAccessChain %_ptr_Function_uint %vgpr {gen.cu(vg)}", - f"OpStore %vinp{reg}_{c} %vinb{reg}_{c}"] - for (kind, r), p in gen.reg_ptrs.items(): - arr = "%vgpr" if kind == "vgpr" else "%sgpr" - fn.append(f"{p} = OpAccessChain %_ptr_Function_uint {arr} {gen.cu(r)}") - # Spill pointers last: a spilled value's type may be declared anywhere above. - types += [f"{ptr} = OpTypePointer Function {t}" for t, ptr in gen.x_ptr_types.items()] - helpers = (gen.desc_fn or []) + (gen.fmt_fn or []) + (gen.fmt_enc_fn or []) - for function in gen.tbuffer_norm_fns.values(): - helpers.extend(function) - for function in gen.x_round_fns.values(): - helpers.extend(function) - tree, nesting = (capped_tree(gen.succ) if gen.blocks and not gen.emulate and not gen.bar_rounds - else (None, None)) - if nesting is not None: - gen.nesting = nesting - gen.control_flow = "structured" if tree is not None else "dispatch loop" if gen.blocks else "straight line" - if gen.emulate: - gen.control_flow = "emulated wave64 structured" if gen.emulate_plan is not None else "emulated wave64 rounds" - elif gen.bar_rounds: - gen.control_flow = "barrier rounds" - - def place_structured(items, body, count): - def label(prefix): - count[0] += 1 - return f"%{prefix}{count[0]}" - - stack = [("items", items)] - while stack: - step = stack.pop() - if step[0] == "items": - for it in reversed(step[1]): - stack.append(("item", it)) - elif step[0] == "item": - it = step[1] - if it[0] == "block": - # Under its own label, as in the dispatch form: OpPhi in a body names it as a predecessor. - body.extend([f"OpBranch %blk{it[1]}", f"%blk{it[1]} = OpLabel"] + gen.blocks[it[1]]) - elif it[0] == "guard": - v, c, do, end = label("g_pc"), label("g_is"), label("g_do"), label("g_end") - body.extend([f"{v} = OpLoad %uint %pc", f"{c} = OpIEqual %bool {v} {gen.consts[it[1]]}", - f"OpSelectionMerge {end} None", f"OpBranchConditional {c} {do} {end}", - f"{do} = OpLabel"]) - stack.append(("guard_end", end)) - stack.append(("items", it[2])) - else: - head, top, cont, end = label("l_head"), label("l_body"), label("l_cont"), label("l_end") - v, again = label("l_pc"), label("l_again") - body.extend([f"OpBranch {head}", f"{head} = OpLabel", f"OpLoopMerge {end} {cont} None", - f"OpBranch {top}", f"{top} = OpLabel"]) - stack.append(("loop_end", it[1], head, cont, end, v, again)) - stack.append(("items", it[2])) - elif step[0] == "guard_end": - body.extend([f"OpBranch {step[1]}", f"{step[1]} = OpLabel"]) - else: - _, blk_id, head, cont, end, v, again = step - body.extend([f"OpBranch {cont}", f"{cont} = OpLabel", f"{v} = OpLoad %uint %pc", - f"{again} = OpIEqual %bool {v} {gen.consts[blk_id]}", - f"OpBranchConditional {again} {head} {end}", f"{end} = OpLabel"]) - - if tree is not None: - # Real loops and conditionals (cfg_structure): the blocks nested by dominance, each behind a test of %pc, - # and every natural loop as a loop that repeats while %pc names its header. - lines = ["%pc = OpVariable %_ptr_Function_uint Function %c0", - "%done = OpVariable %_ptr_Function_bool Function %false"] - body, count = [], [0] - place_structured(tree, body, count) - elif gen.emulate and gen.emulate_plan is not None: - plan = gen.emulate_plan - lines = x_prologue(gen, x_threads) - body, count = [], [0] - if plan["mode"] == "inline_all": - place_structured(plan["tree"], body, count) - else: - c = lambda v: gen.consts[v & 0xFFFFFFFF] # noqa: E731 - for step in plan["steps"]: - kind = step[0] - if kind == "inline_block": - b = step[1] - body.extend([f"OpBranch %blk{b}", f"%blk{b} = OpLabel"] + gen.blocks[b]) - elif kind == "inline_sync_free": - _, it, pre_bar = step - if pre_bar: - body.append(f"OpControlBarrier {c(2)} {c(2)} {c(0x948)}") - place_structured([it], body, count) - elif kind == "mini_scheduler": - _, midx, mblocks, pre_bar = step - if pre_bar: - body.append(f"OpControlBarrier {c(2)} {c(2)} {c(0x948)}") - seg_ids = sorted(set(mblocks) | set(gen.mini_segs[midx])) - body.extend(x_mini_scheduler(gen, midx, seg_ids)) - for i in seg_ids: - blines = gen.blocks[i] if i < len(gen.blocks) else gen.x_segs[i] - body.append(f"%blk{i} = OpLabel") - body += blines - body.append(f"OpBranch %xm{midx}_sw_merge") - body.extend(x_mini_scheduler_tail(gen, midx)) - else: # tail_scheduler - _, tblocks, pre_bar = step - if pre_bar: - body.append(f"OpControlBarrier {c(2)} {c(2)} {c(0x948)}") - seg_ids = sorted(set(tblocks) | set(gen.tail_segs)) - body.extend(x_round_loop_head(gen, seg_ids)) - for i in seg_ids: - blines = gen.blocks[i] if i < len(gen.blocks) else gen.x_segs[i] - body.append(f"%blk{i} = OpLabel") - body += blines - body.append("OpBranch %sw_merge") - body.extend(x_scheduler_tail(gen)) - if sum(1 for l in lines + body if "OpControlBarrier" in l) < 2: - body.append(f"OpControlBarrier {gen.consts[2]} {gen.consts[2]} {gen.consts[0x948]}") - elif gen.emulate: - lines = x_scheduler(gen, x_threads) - body = [] - for i, blines in sorted([(i, b) for i, b in enumerate(gen.blocks) if b is not None] + list(gen.x_segs.items())): - body.append(f"%blk{i} = OpLabel") - body += blines - body.append("OpBranch %sw_merge") - body += x_scheduler_tail(gen) - elif gen.bar_rounds: - lines = bar_scheduler(gen) - body = [] - for i, blines in sorted(list(enumerate(gen.blocks)) + list(gen.x_segs.items())): - body.append(f"%blk{i} = OpLabel") - body += blines - body.append("OpBranch %sw_merge") - body += bar_scheduler_tail(gen) - elif gen.blocks: - # Dispatch loop: any CFG (forward/backward branches) in structured SPIR-V form. Used for the irreducible - # graphs cfg_structure refuses (a loop with two entries), and with --dispatch-loop. - n = len(gen.blocks) - lines = ["%pc = OpVariable %_ptr_Function_uint Function %c0", - "%done = OpVariable %_ptr_Function_bool Function %false", - "OpBranch %loop_head", "%loop_head = OpLabel", "OpLoopMerge %loop_exit %loop_cont None", - "OpBranch %dispatch", "%dispatch = OpLabel", "%pcv = OpLoad %uint %pc", - "OpSelectionMerge %sw_merge None", - "OpSwitch %pcv %sw_default " + " ".join(f"{i} %blk{i}" for i in range(n))] - body = [] - for i, blines in enumerate(gen.blocks): - body.append(f"%blk{i} = OpLabel") - body += blines - body.append("OpBranch %sw_merge") - body += ["%sw_default = OpLabel", "OpStore %done %true", "OpBranch %sw_merge", - "%sw_merge = OpLabel", "OpBranch %loop_cont", "%loop_cont = OpLabel", - "%dn = OpLoad %bool %done", "OpBranchConditional %dn %loop_exit %loop_head", - "%loop_exit = OpLabel"] - if gen.blocks: - # %pc/%done must be declared with the other Function variables, at the top of the entry block, - # before the vertex-shader prologue. - fn_vars = lines[:2] - flow = lines[2:] - last_var = max(i for i, l in enumerate(fn) if " = OpVariable " in l) - fn = fn[:last_var + 1] + fn_vars + fn[last_var + 1:] - gen.body =[" " + l if not (l.startswith("%") and " = OpLabel" in l) else l for l in flow + body] - if pops: - fn.append("OpBeginInvocationInterlockEXT") # end of the entry block: uniform, executed once - out = hdr + dec + types + gvars + helpers + fn - end_lock = " OpEndInvocationInterlockEXT\n" if pops else "" - if msc: - end_lock = gen.msc_epilogue + end_lock - elif ms: - # All invocations reach the end: wait for the ALLOC_REQ write, declare the counts once (uniform), then each - # thread writes the vertex and primitive it exported (index = LocalInvocationIndex). - c = gen.cu - L = ["OpControlBarrier %c2 %c2 " + c(0x108), - "%msc = OpLoad %uint %ms_counts", - f"%msv0 = OpBitwiseAnd %uint %msc {c(0xFFF)}", f"%msp1 = OpShiftRightLogical %uint %msc {c(12)}", - f"%msp0 = OpBitwiseAnd %uint %msp1 {c(0xFFF)}", - f"%msv = OpExtInst %uint %glsl UMin %msv0 {c(gen.ms['maxv'])}", - f"%msp = OpExtInst %uint %glsl UMin %msp0 {c(gen.ms['maxp'])}", - "OpSetMeshOutputsEXT %msv %msp", - "%mli = OpLoad %uint %local_index", - "%mhv = OpLoad %bool %ms_has_vtx", "%mvi = OpULessThan %bool %mli %msv", - "%mwv = OpLogicalAnd %bool %mhv %mvi", - "OpSelectionMerge %ms_vend None", "OpBranchConditional %mwv %ms_vdo %ms_vend", - "%ms_vdo = OpLabel", - "%mpv = OpLoad %v4float %ms_pos", - ("%mpp = OpAccessChain %_ptr_Out_v4_ms %ms_out_vtx %mli %c0" if ms_blk else - "%mpp = OpAccessChain %_ptr_Out_v4_ms %ms_out_pos %mli"), - "OpStore %mpp %mpv"] - # Clip and cull distances are copied one float at a time, not as a whole array: SPIRV-Cross (1.4.363.0) - # turns a whole-array store into a mesh output into a plain C array assignment, which Metal rejects - # ("array type 'threadgroup float[1]' is not assignable"; SHADER-155). Same result on Vulkan. - if gen.uses_clip: - for i in range(gen.clip_count): - L += [f"%mcs{i} = OpAccessChain %_ptr_Function_float %ms_clip {c(i)}", - f"%mcv{i} = OpLoad %float %mcs{i}", - f"%mcvp{i} = OpAccessChain %_ptr_Out_float_ms %ms_out_vtx %mli {c(ms_clip_member)} {c(i)}", - f"OpStore %mcvp{i} %mcv{i}"] - if gen.uses_cull: - for i in range(gen.cull_count): - L += [f"%mks{i} = OpAccessChain %_ptr_Function_float %ms_cull_dist {c(i)}", - f"%mkv{i} = OpLoad %float %mks{i}", - f"%mkvp{i} = OpAccessChain %_ptr_Out_float_ms %ms_out_vtx %mli {c(ms_cull_member)} {c(i)}", - f"OpStore %mkvp{i} %mkv{i}"] - for n in sorted(gen.ms_params): - L += [f"%mq{n} = OpLoad %v4float %ms_param{n}", - f"%mqp{n} = OpAccessChain %_ptr_Out_v4_ms %ms_out_param{n} %mli", f"OpStore %mqp{n} %mq{n}"] - if n in ms_halves: # --f16-interp-fallback: each channel's f16 halves decoded to f32 - for k in range(4): - L += [f"%mqe{n}_{k} = OpCompositeExtract %float %mq{n} {k}", - f"%mqu{n}_{k} = OpBitcast %uint %mqe{n}_{k}", - f"%mqh{n}_{k} = OpExtInst %v2float %glsl UnpackHalf2x16 %mqu{n}_{k}"] - L += [f"%mqh{n}_{k}_{h} = OpCompositeExtract %float %mqh{n}_{k} {h}" for h in (0, 1)] - for h in (0, 1): - L += [f"%mqv{n}_{h} = OpCompositeConstruct %v4float " + - " ".join(f"%mqh{n}_{k}_{h}" for k in range(4)), - f"%mqvp{n}_{h} = OpAccessChain %_ptr_Out_v4_ms %ms_out_f16h{n}_{h} %mli", - f"OpStore %mqvp{n}_{h} %mqv{n}_{h}"] - L += ["OpBranch %ms_vend", "%ms_vend = OpLabel", - "%mhp = OpLoad %bool %ms_has_prim", "%mpi = OpULessThan %bool %mli %msp", - "%mwp = OpLogicalAnd %bool %mhp %mpi", - "OpSelectionMerge %ms_pend None", "OpBranchConditional %mwp %ms_pdo %ms_pend", - "%ms_pdo = OpLabel", - "%mpr = OpLoad %uint %ms_prim", - f"%mi0 = OpBitwiseAnd %uint %mpr {c(0x1FF)}", - f"%mr1 = OpShiftRightLogical %uint %mpr {c(10)}", f"%mi1 = OpBitwiseAnd %uint %mr1 {c(0x1FF)}", - f"%mr2 = OpShiftRightLogical %uint %mpr {c(20)}", f"%mi2 = OpBitwiseAnd %uint %mr2 {c(0x1FF)}", - "%mix = OpCompositeConstruct %v3uint %mi0 %mi1 %mi2", - "%mixp = OpAccessChain %_ptr_Out_v3u_ms %ms_prim_idx %mli", "OpStore %mixp %mix", - f"%mnb = OpShiftRightLogical %uint %mpr {c(31)}", "%mnull = OpINotEqual %bool %mnb %c0", - f"%mcp = OpAccessChain %_ptr_Out_bool_ms %ms_cull %mli {c(0)}", - # CullPrimitiveEXT gets a constant on each side of a branch, not the computed bool: llvmpipe - # (Mesa 25.2.8, LLVM 20) aborts compiling a computed per-primitive bool store in the wave64-emulated - # mesh epilogue ("Cannot emit physreg copy instruction"), and Mesa 26.3.1 drew no primitives for the - # same shaders (SHADER-575). Same result on every driver. - "OpSelectionMerge %ms_cend None", "OpBranchConditional %mnull %ms_cull1 %ms_cull0", - "%ms_cull1 = OpLabel", "OpStore %mcp %true", "OpBranch %ms_cend", - "%ms_cull0 = OpLabel", "OpStore %mcp %false", "OpBranch %ms_cend", - "%ms_cend = OpLabel", - "OpBranch %ms_pend", "%ms_pend = OpLabel"] - end_lock = "".join((" " + l if " = OpLabel" not in l else l) + "\n" for l in L) + end_lock - if gen.uses_active and gen.stage == "ps": - # A pixel is written when its lane was on in EXEC at the last `vm` export the path ran (if it ran one) and - # at the last export to its color target (measured on RDNA2 with one target; docs/design.md, EXEC). With - # several targets the pixel stays when any of them got an export from the lane: Vulkan can't skip one - # attachment per pixel, so the others keep what the lane exported before (or the initial value). Without a - # latch EXEC can't have changed since those exports, so EXEC at the end is the same mask; a path with no - # export at all also goes by EXEC at the end. - keep, latched = "%act_end", "" - if gen.vm_latch: - keep = "%vm_keep" - latched = (" %vm_was_set = OpLoad %bool %vm_set\n" - " %vm_exec = OpLoad %bool %vm_mask\n" - " %vm_part = OpSelect %bool %vm_was_set %vm_exec %true\n" - " %no_col = OpSelect %bool %vm_was_set %true %act_end\n") - any_set, any_on = "%false", "%false" - for t in gen.col_latched: - latched += (f" %col_was_set_{t} = OpLoad %bool %col_set_{t}\n" - f" %col_exec_{t} = OpLoad %bool %col_mask_{t}\n" - f" %col_on_{t} = OpLogicalAnd %bool %col_was_set_{t} %col_exec_{t}\n" - f" %col_any_set_{t} = OpLogicalOr %bool {any_set} %col_was_set_{t}\n" - f" %col_any_on_{t} = OpLogicalOr %bool {any_on} %col_on_{t}\n") - any_set, any_on = f"%col_any_set_{t}", f"%col_any_on_{t}" - latched += (f" %col_part = OpSelect %bool {any_set} {any_on} %no_col\n" - " %vm_keep = OpLogicalAnd %bool %vm_part %col_part\n") - tail = end_lock + (" %act_end = OpLoad %bool %active\n" + latched + - " OpSelectionMerge %live None\n" - f" OpBranchConditional {keep} %live %dead\n" - "%dead = OpLabel\n OpKill\n" - "%live = OpLabel\n OpReturn\n OpFunctionEnd\n") - else: - tail = end_lock + " OpReturn\n OpFunctionEnd\n" - insert_late_constants(gen, out, written) - return split_big_switch(no_contraction(dedupe_types( - "\n".join(" " + l if not l.startswith("%") or " = " not in l else l for l in out) + - "\n" + "\n".join(gen.body) + "\n" + tail))) - - -# SPIR-V caps an instruction at 65,535 words. The dispatch loop's OpSwitch has one (literal, label) pair per block, -# and with --wave64-emulate the two ScreenProbes compute shaders reach ~37k blocks (74k words). Past the limit the -# switch becomes two levels: an outer one on pc / SWITCH_CHUNK picks a chunk; each chunk is its own selection -# construct (inner OpSwitch on pc, merge %swm), and that chunk's blocks branch to %swm, which goes on to -# %sw_merge. Every block keeps its label and code, so only the routing changes. -SWITCH_CHUNK = 16000 # spirv-val also caps a switch at 16,383 (literal, label) pairs -_BIG_SWITCH = re.compile(r"^(\s*)OpSwitch %pcv %sw_default ((?:\d+ %\w+ ?)+)$", re.M) - - -def split_big_switch(text): - m = _BIG_SWITCH.search(text) - if not m: - return text - pairs = m.group(2).split() - cases = [(int(pairs[i]), pairs[i + 1]) for i in range(0, len(pairs), 2)] - if len(cases) <= 16383 and 3 + 2 * len(cases) <= 65535: - return text - ind = m.group(1) - chunk_of = {lbl: v // SWITCH_CHUNK for v, lbl in cases} - chunks = sorted(set(chunk_of.values())) - outer = f"{ind}OpSwitch %pcc %sw_default " + " ".join(f"{k} %swc{k}" for k in chunks) - heads = [] - for k in chunks: - inner = " ".join(f"{v} {lbl}" for v, lbl in cases if chunk_of[lbl] == k) - heads += [f"%swc{k} = OpLabel", f"{ind}OpSelectionMerge %swm{k} None", f"{ind}OpSwitch %pcv %swm{k} {inner}"] - # OpSelectionMerge must stay right before its switch, so the chunk index is computed above it - pre = text[:m.start()] - sel = pre.rfind("OpSelectionMerge %sw_merge None") - sel = pre.rfind("\n", 0, sel) + 1 - pre = pre[:sel] + f"{ind}%pcc = OpUDiv %uint %pcv %c_swchunk\n" + pre[sel:] - lines = pre.split("\n") + [outer] + heads + text[m.end():].split("\n")[1:] - # route each block's exits to its chunk's merge: a block runs from its label to the next case label - out, cur = [], None - for line in lines: - st = line.strip() - if st.endswith("= OpLabel"): - lbl = st.split(" = ")[0] - if lbl in chunk_of: - cur = chunk_of[lbl] - elif lbl in ("%sw_default", "%sw_merge") or lbl.startswith("%swc"): - cur = None - if lbl_is_sw_default(st): - out += [f"%swm{k} = OpLabel\n{ind}OpBranch %sw_merge" for k in chunks] # after every chunk's blocks - if cur is not None and st == "OpBranch %sw_merge": - line = line.replace("OpBranch %sw_merge", f"OpBranch %swm{cur}") - out.append(line) - text = "\n".join(out) - # the chunk-size constant, next to the other uint constants - first = re.search(r"^\s*%\w+ = OpConstant %uint \d+$", text, re.M) - return text[:first.start()] + f"%c_swchunk = OpConstant %uint {SWITCH_CHUNK}\n" + text[first.start():] - - -def lbl_is_sw_default(st): - return st == "%sw_default = OpLabel" - - -_FLOAT_ARITH = re.compile(r"^\s*(%\w+) = Op(?:FMul|FAdd|FSub|FDiv|FNegate|FRem|FMod) ", re.M) - - -def no_contraction(text): - """Decorate every float arithmetic instruction NoContraction (multiply, add, subtract, divide, negate, - remainder). The hardware rounds a v_mul and the v_add after it separately (its fused instructions are - emitted as Fma), but a driver may fuse or otherwise rewrite an undecorated expression, and whether it does - depends on how much of the code its optimiser can see at once: with real control flow instead of the - dispatch loop, one shader's output moved by a 16-bit-float step in 49 of 4,096 pixels on an AMD GPU (a - multiply and an add), and two more by one step in one pixel on Mesa's software driver (divide or negate).""" - ids = _FLOAT_ARITH.findall(text) - at = text.find("\n%void = OpTypeVoid") - if not ids or at < 0: - return text - return text[:at] + "".join(f"\n OpDecorate {i} NoContraction" for i in ids) + text[at:] - - -_STAGES = None - - -def stage_of(name, path): - """Shader stage from the carve index (the DXIL program header in each container), not the name.""" - global _STAGES - if _STAGES is None: - import json - idx = os.path.join(os.path.dirname(os.path.dirname(os.path.realpath(path))), "index.json") - _STAGES = {} - if os.path.isfile(idx): - with open(idx, encoding="utf-8") as f: - for e in json.load(f): - _STAGES[e["file"][:-5]] = e["stage"] - return _STAGES.get(name) or (name[:2].lower() if name[2:3] == "_" else "?") - - -# Wave64 markers in the instruction text. Besides EXEC/VCC forms, 64-bit lane-mask SOP1/SOP2 ops -# (bcnt/ff/wqm/bfm) imply a 64-lane wave even when the mask lives in ordinary SGPR pairs (#210 part 2). -WAVE64_RE = re.compile( - r"exec_hi|v_mbcnt_hi_u32_b32|_saveexec_b64|_wrexec_b64|" - r"s_bcnt[01]_i32_b64|s_ff[01]_i32_b64|s_wqm_b64|s_bfm_b64" -) -# Wave32-only EXEC mask ops, used to catch a wave64 FSSM header contradicting wave32 code. -WAVE32_RE = re.compile(r"_(?:saveexec|wrexec)_b32\b") - - -def halves_analysis(g, blocks, succ): - """SHADER-10: tier of a wave64 VS/PS/GS on 32-wide subgroups (tools/wave64_halves.py); tier C is refused under - --wave64-graphics=error. Runs after the lane-mask analysis, which it reads.""" - if not g.wave64 or g.stage not in ("vs", "ps", "gs") or g.emulate or WAVE64_GRAPHICS == "off": - return - try: - g.w64g = wave64_halves.analyse(blocks, succ, g.lane_masks, g.stage) - except Exception as e: # the analysis must never cost a translation; what it could not decide is tier C - g.w64g = {"tier": "C", "reasons": ["analysis-error"], "idioms": [], "uniform_readlane": set(), - "scalar_spills": [], "sites": [("analysis-error", None, type(e).__name__)]} - for slot in g.w64g.get("scalar_spills", ()): - if slot not in g.parked: - g.parked[slot] = g.SGPRS + len(g.parked) - g.w64_scalar_spills.add(slot) - W64G_COUNTS[g.w64g["tier"]] += 1 - if g.w64g["tier"] == "C" and WAVE64_GRAPHICS == "error": - raise Unsupported("wave64 graphics tier C: " + ", ".join(g.w64g["reasons"])) - - -def fold_far_branches(insns): - """s_getpc_b64 s[a:a+1]; s_add_u32 sa, sa, K; s_addc_u32 sa+1, sa+1, 0|-1; s_setpc_b64 s[a:a+1] is a far - branch (s_branch only reaches +-32K dwords): the target is the address after s_getpc plus K. Fold the four - instructions into one s_branch with an explicit byte target so the CFG sees an ordinary branch.""" - out, i = [], 0 - while i < len(insns): - w = insns[i:i + 4] - ops4 = [base_op(x["op"]) for x in w] - if len(w) == 4 and all(x.get("enc") for x in w) and ops4 in (["s_getpc_b64", "s_add_u32", "s_addc_u32", "s_setpc_b64"], - ["s_getpc_b64", "s_sub_u32", "s_subb_u32", "s_setpc_b64"]): - g, ad, ac, sp = w - r = g["args"][0].get("r") if g["args"] and g["args"][0]["k"] == "sgpr" else None - ok = r is not None and [x.get("r") for x in ad["args"][:2]] == [r, r] and ad["args"][2]["k"] == "imm" and [x.get("r") for x in ac["args"][:2]] == [r + 1, r + 1] and ac["args"][2]["k"] == "imm" and sp["args"] and sp["args"][0].get("r") == r - if ok: - k = ad["args"][2]["v"] & 0xFFFFFFFF - hi = ac["args"][2]["v"] & 0xFFFFFFFF - if hi == 0xFFFFFFFF: - k -= 1 << 32 - elif hi != 0: - ok = False - if ops4[1] == "s_sub_u32": # backward far branch (loop back-edge) - k = -k - if ok: - out.append({"op": "s_branch", "args": [], "mods": [], "pc": g["pc"], - "enc": "".join(x["enc"] for x in w), "target": g["pc"] + 4 + k}) - i += 4 - continue - out.append(insns[i]) - i += 1 - return out - - -def reachable_code(insns, code_end=None): - """Instructions reachable from the first one, following fall-through and branch targets. Fall-through stops - after s_endpgm, s_branch and s_setpc_b64. Raises Unsupported if a branch target isn't an instruction start, or if - an instruction falls through into words that are not an instruction (undecodable words before later code).""" - by_pc = {i["pc"]: k for k, i in enumerate(insns)} - # the code ends at the declared end of its range (the listing header), or else after the last printed instruction - code_end = max([i["pc"] + len(i["enc"]) // 2 for i in insns] + [code_end or 0]) - seen, work = set(), [0] - while work: - k = work.pop() - while k is not None and k < len(insns) and k not in seen: - seen.add(k) - ins = insns[k] - op = base_op(ins["op"]) - nxt = ins["pc"] + len(ins["enc"]) // 2 - if op in BRANCHES: - imm = next((x for x in ins["args"] if x["k"] == "imm"), None) - v = (imm["v"] & 0xFFFF) if imm else 0 - tgt = ins["target"] if "target" in ins else nxt + 4 * (v - 0x10000 if v & 0x8000 else v) - if tgt not in by_pc: - raise Unsupported("branch into data") - work.append(by_pc[tgt]) - if op == "s_branch": - break - if op in ("s_endpgm", "s_setpc_b64"): - break - k = by_pc.get(nxt) - if k is None and nxt < code_end: - # The next words are ones llvm-mc could not decode (re-anchoring skipped them) and this instruction - # runs into them: ending the path here would drop every later store and export without a word. - raise Unsupported("fall-through into undecodable words") - return [insns[k] for k in sorted(seen)] - - -def writes_exec(ins): - """Whether an instruction can change EXEC: v_cmpx, saveexec / wrexec, or EXEC in any destination operand - (operand 0 of everything but compares, plus operand 1 of VOP3b two-destination ops like v_add_co_u32, - v_sub_co_u32, v_mad_u64_u32, and v_div_scale_f32 whose second operand is the scalar carry/flag destination).""" - op, a = ins["op"], ins["args"] - bop = base_op(op) - if bop.startswith("v_cmpx") or "saveexec" in bop or "wrexec" in bop: - return True - if bop.startswith(("s_cmp_", "s_cmpk_", "s_bitcmp")): - return False - if a and a[0]["k"] == "special" and a[0]["t"].startswith("exec"): - return True - if bop in VOP3_TWO_DESTS and len(a) > 1 and a[1]["k"] == "special" and a[1]["t"].startswith("exec"): - return True - return False - - -def is_color_export(ins): - """An `exp` to a color target (mrt0-mrt7; not mrtz, null or a position / parameter).""" - a = ins["args"] - t = a[0].get("t", "") if a and a[0]["k"] in ("target", "special") else "" - return base_op(ins["op"]) == "exp" and t.startswith("mrt") and t[3:].isdigit() - - -def exec_changes_after_vm(blocks, succ): - """Whether some path writes EXEC after an `exp ... vm` or after a color export. Only then does a PS need EXEC - at those exports kept: a pixel is written when its lane was on at the last `vm` export and at the last color - export, and with EXEC unchanged since then that is EXEC at the end.""" - after = [] - for n, blk in enumerate(blocks): - seen_vm = False - for ins in blk: - op = base_op(ins["op"]) - if op == "s_endpgm" or op in BRANCHES: - break - if seen_vm and writes_exec(ins): - return True - if op == "exp" and ("vm" in ins["mods"] or is_color_export(ins)): - seen_vm = True - if seen_vm: - after += succ[n] - reached = set() - while after: - n = after.pop() - if n in reached or not 0 <= n < len(blocks): - continue - reached.add(n) - for ins in blocks[n]: - op = base_op(ins["op"]) - if op == "s_endpgm" or op in BRANCHES: - break - if writes_exec(ins): - return True - after += succ[n] - return False - - -def vgpr_dest_registers(ins: dict, extra: int = 0) -> range | tuple[int, ...]: - """Register numbers written by a VGPR-destination instruction, after filtering stores and compares.""" - args = ins["args"] - if base_op(ins["op"]) == "v_swap_b32": - return tuple(a["r"] for a in args[:2] if a["k"] == "vgpr") - dst = args[0] - return range(dst["r"], dst["r"] + dst.get("n", 1) + extra) - - -def sdwa_reads_dst(op: str, mods: list[str]) -> bool: - """A byte or word insert with UNUSED_PRESERVE reads the rest of its destination.""" - return (op.endswith("_sdwa") and "dst_unused:UNUSED_PRESERVE" in mods - and any(m.startswith(("dst_sel:BYTE_", "dst_sel:WORD_")) for m in mods)) - - -# All VGPR operands of these instructions are sources, including store address and data ranges. -VGPR_READ_ONLY_PREFIXES = ("exp", "buffer_store", "tbuffer_store", "image_store", "v_cmp", "ds_write", - "global_store", "flat_store", "scratch_store") - - -def read_before_write_vgprs(insns): - """VGPRs a shader reads before writing them: for a fetch-calling VS these are the fetched attributes.""" - written, first = set(), [] - for ins in insns: - a, op = ins["args"], ins["op"] - if not a: - continue - reads_all = op.startswith(VGPR_READ_ONLY_PREFIXES) \ - or (op.startswith("global_atomic_") and "glc" not in ins["mods"]) # no vdst without glc - regs = [] - for x in (a if reads_all or sdwa_reads_dst(op, ins.get("mods", [])) else a[1:]): - if x["k"] == "vgpr": - regs += range(x["r"], x["r"] + x.get("n", 1)) - elif x["k"] == "vlist": - regs += x["r"] - if (base_op(op) in ("v_swap_b32", "v_fmac_f32", "v_mac_f32", "v_mac_legacy_f32", "v_fmac_f16", "v_dot4c_i32_i8", "v_pk_fmac_f16", - "v_dot2c_f32_f16", "v_dot2c_i32_i16", "v_dot2c_u32_u16", "v_dot4c_u32_u8", - "v_dot8c_i32_i4", "v_dot8c_u32_u4") or - (op.startswith(("global_load_", "buffer_load_")) and "_d16" in op and "format" not in op)) and \ - a[0]["k"] == "vgpr": # d16 keeps a half - regs.append(a[0]["r"]) - for r in regs: - if r not in written and r not in first: - first.append(r) - if not reads_all and a[0]["k"] == "vgpr": - written.update(vgpr_dest_registers(ins)) - return set(first) - -def interp_ij_analysis(insns, g): - """SHADER-177: how each v_interp_p1/p2's I/J operand reaches the site, and what to do with it. - - Hardware weights the interpolation with the values the named VGPRs hold at the two ops, not with the - hardware's own pair (Vonsek's #1224 image evidence: zeroed sources interpolate to P0, swapped operand - roles to (v,u)). A program that overwrites v0/v1 with computed barycentrics -- evaluate-at-offset, - snapped coordinates, copies held in other registers -- therefore interpolates through the computed - pair. Each op of such a pair is annotated ins["ij"] = (kind, key, i VGPR, j VGPR): - - * pristine: both operands of the pair are v0/v1 and nothing in the shader writes those registers - (11,888 of 12,101 PS). The single-lane model's own read -- the interpolated input -- is exact and - the site is left untouched. - * computed: either operand is written anywhere in the shader (v0/v1 -- conservative under branches) - or before the site (any other register). The attribute becomes PerVertexKHR and both ops - interpolate with the operand values loaded from %vgpr, which holds whatever the program computed: - v_mov, arithmetic on the pair, multi-writer sequences. The p1 loads its I and keeps it for the p2 - (the program may rewrite an operand between the two ops: 574 corpus sites set J up between them), - and the p2 loads its J fresh; the p1's own full-sum value is dead unless something reads the - partial between the ops. - - A source that is neither v0/v1 nor written is left to interp_pair_src (#1224), which refuses it at - emission naming the role; a plain v_mov copy of the pair (g.v_interp_copy) stays #1224's to model, - keeping its bit-identical .spv. Refused here (Unsupported, naming the pattern): a computed pair - whose ops are not in one basic block (the captured I would not dominate the p2), whose shared - partial register -- the f32 vdst, or the f16 p2's fourth operand naming the p1's vdst -- is written - between the ops, or read between them by anything but a p2's partial operand, any computed site - under --bary-fallback or --f16-interp-fallback (neither has PerVertexKHR inputs), and a computed v_interp_*_f32 on a 16-bit-flagged - interpolant (which half the 32-bit op reads is not established). Over the corpus all of these are - empty: 213 PS hold computed pairs, every pair sits in one block, and no partial is touched - between the ops. - - Returns the set of attribute numbers the computed pairs need in g.per_vertex.""" - P1 = ("v_interp_p1_f32", "v_interp_p1ll_f16", "v_interp_p1lv_f16") - P2_OF = {"v_interp_p1_f32": "v_interp_p2_f32", - "v_interp_p1ll_f16": "v_interp_p2_f16", "v_interp_p1lv_f16": "v_interp_p2_f16"} - writes = defaultdict(list) # vgpr -> indexes of insns writing it (read_before_write rules) - for n, ins in enumerate(insns): - a, op = ins["args"], ins["op"] - if not a: - continue - reads_all = op.startswith(VGPR_READ_ONLY_PREFIXES) - if not reads_all and a[0]["k"] == "vgpr": - for r in vgpr_dest_registers(ins): - writes[r].append(n) - sites = [] - for n, ins in enumerate(insns): - op = base_op(ins["op"]) - if op not in P1 and op not in ("v_interp_p2_f32", "v_interp_p2_f16"): - continue - a = ins["args"] - attr = next((x for x in a if x["k"] == "attr"), None) - if attr is None or len(a) < 2 or a[0]["k"] != "vgpr" or a[1]["k"] != "vgpr": - continue # the emission site raises its own Unsupported - partial = a[3]["r"] if (op == "v_interp_p2_f16" and len(a) > 3 and a[3]["k"] == "vgpr") else None - sites.append({"n": n, "ins": ins, "op": op, "vdst": a[0]["r"], "src": a[1]["r"], "partial": partial, - "attr": attr["a"], "chan": attr["c"], "computed": False}) - - # Block index per instruction (translate's leader rule), for the reaching-write test and the - # same-block requirement. - def next_pc(i): - return i["pc"] + (len(i["enc"]) // 2 if i["enc"] else 4) - - def branch_target(i): - if "target" in i: - return i["target"] - imm = next((x for x in i["args"] if x["k"] == "imm"), None) - v = imm["v"] & 0xFFFF if imm is not None else 0 - return next_pc(i) + 4 * (v - 0x10000 if v & 0x8000 else v) - - leaders = {insns[0]["pc"]} - for i in insns: - if base_op(i["op"]) in BRANCHES or base_op(i["op"]) == "s_endpgm": - leaders.add(branch_target(i)) - leaders.add(next_pc(i)) - blk, cur, prev, block_of_pc = [], None, None, {} - for k, i in enumerate(insns): - if i["pc"] in leaders and i["pc"] != prev: - cur = k # a block starts at a leader pc that newly appears - prev = i["pc"] - blk.append(cur) - block_of_pc[i["pc"]] = cur - last_of = {} # block -> index of its last instruction, in one pass - for k, b in enumerate(blk): - last_of[b] = k - preds = defaultdict(set) # block -> blocks that can run right before it - for b in sorted(last_of): - last = last_of[b] - op = base_op(insns[last]["op"]) - if op == "s_endpgm": - continue - tgts = [] - if op in BRANCHES: - t = block_of_pc.get(branch_target(insns[last])) - if t is None: - raise Unsupported("branch target outside code") - tgts.append(t) - if op != "s_branch" and last + 1 < len(insns): - tgts.append(blk[last + 1]) # conditional branches and plain fallthrough - for t in tgts: - preds[t].add(b) - - def reaching_write(reg, s): - """A write of reg the site can see: earlier in its own block, or in any block a path runs - through first (loops included). A write at the site itself -- an interp whose destination is - its own I/J register -- happens after the operand is read and does not count.""" - ws = writes.get(reg) - if not ws: - return False - b = blk[s["n"]] - if any(w < s["n"] and blk[w] == b for w in ws): - return True - write_blocks = {blk[w] for w in ws} - # b itself is not pre-seeded: reached again through a back-edge, a write after the site counts - # (and index 0 is a valid write, so test membership, not truthiness). - seen, work = set(), [b] - while work: - for p in preds[work.pop()]: - if p not in seen: - seen.add(p) - if p in write_blocks: - return True - work.append(p) - return False - - for s in sites: - if s["src"] in (0, 1): - s["computed"] = reaching_write(s["src"], s) - elif reaching_write(s["src"], s) and s["src"] not in g.v_interp_copy: - s["computed"] = True - # any other source is pristine: interp_pair_src (#1224) accepts it only as the op's own - # coordinate (v0 for p1, v1 for p2) or a plain v_mov copy rooted there — which - # interp_copy_sources already vetted, so such a copy keeps #1224's centre-interpolated - # read and its bit-identical .spv — and refuses the rest at emission, naming the role - if s["computed"] and s["op"].endswith("_f32") and g.pixel_interpolants is not None and \ - (g.pixel_interpolants[1] >> s["attr"]) & 1: - raise Unsupported("computed I/J on 16-bit interpolant through v_interp_*_f32") - - # Sites by (op, anchor register, attribute, channel), in program order, for partner(): the f16 p2 is - # keyed by its partial (the p1's vdst it names), every other op by its vdst. - by_key = defaultdict(list) - for t in sites: - anchor_reg = t["partial"] if t["op"] == "v_interp_p2_f16" else t["vdst"] - by_key[(t["op"], anchor_reg, t["attr"], t["chan"])].append(t) - n_by_key = {key: [t["n"] for t in ts] for key, ts in by_key.items()} - - def partner(k, s): - """The other op of the pair: the p1 the p2 completes (nearest before), or the p2 that reads the - p1's vdst as its partial (nearest after). Same attribute channel; the f32 pair's vdst is shared, - the f16 p2 names the p1's vdst as its fourth operand.""" - if s["op"] in P1: - want = (P2_OF[s["op"]],) - anchor = s["vdst"] - elif s["op"] == "v_interp_p2_f32": - want = ("v_interp_p1_f32",) - anchor = s["vdst"] - else: - want = ("v_interp_p1ll_f16", "v_interp_p1lv_f16") - anchor = s["partial"] - # The f32 pair shares the vdst; the f16 p2 names the p1's vdst as its fourth operand (its - # partial), and its own vdst is just where the f16 result goes. by_key holds each kind's sites in - # program order, so the nearest one after (p1) or before (p2) the site is a binary search. - found = [] - for op in want: - key = (op, anchor, s["attr"], s["chan"]) - ts = by_key.get(key) - if not ts: - continue - ns = n_by_key[key] - if s["op"] in P1: - i = bisect.bisect_right(ns, k) - if i < len(ts): - found.append(ts[i]) - else: - i = bisect.bisect_left(ns, k) - if i: - found.append(ts[i - 1]) - if not found: - return None - return (min if s["op"] in P1 else max)(found, key=lambda t: t["n"]) - - # Which pairs are computed (either operand is): both ops then take the computed model, so a p2 whose - # own operand is pristine still weights with the I its p1 held. - pair_of = {} - for k, s in enumerate(sites): - m = partner(s["n"], s) - pair_of[id(s["ins"])] = m - if m is not None and (s["computed"] or m["computed"]): - s["computed"] = m["computed"] = True - attrs = set() - for k, s in enumerate(sites): - if not s["computed"]: - continue - m = pair_of[id(s["ins"])] - why = None - if m is None: - why = f"{s['op']} without its {'p2' if s['op'] in P1 else 'p1'} partner" - else: - lo, hi = min(s["n"], m["n"]), max(s["n"], m["n"]) - p1 = s if s["op"] in P1 else m - kr = p1["vdst"] # where the p1 partial lives (the f16 p2 reads it by name) - if blk[lo] != blk[hi]: - why = "the pair's ops are not in one basic block" - else: - rr, ww = reg_reads_writes(insns[lo + 1:hi]) - if kr in ww: - why = "the p1 partial is rewritten between the ops" - elif kr in rr: - # Another p2 reading the same partial is fine (two p2s of one p1); anything else - # would observe the p1 partial P10*I, which the full-sum model does not produce. - for t in insns[lo + 1:hi]: - r, _ = reg_reads_writes([t]) - if kr in r and not (base_op(t["op"]) == "v_interp_p2_f16" and - t["args"][3:4] and t["args"][3]["k"] == "vgpr" - and t["args"][3]["r"] == kr): - why = "the p1 partial is read between the ops" - break - if why: - raise Unsupported(f"computed I/J pair: {why}") - p1, p2 = (s, m) if s["op"] in P1 else (m, s) - s["ins"]["ij"] = ("p1" if s["op"] in P1 else "p2", (p1["vdst"], p1["attr"], p1["chan"]), - p1["src"], p2["src"]) - # A computed pair loads both weights from the VGPR file, including a hardware weight - # whose only use is v_interp. Initialize it even if some paths replace it before this site. - if s["src"] in (0, 1): - g.frag_inputs[s["src"]] = ("bary_i", "bary_j")[s["src"]] - attrs.add(s["attr"]) - if attrs and BARY_FALLBACK: - raise Unsupported("computed I/J pair under --bary-fallback: no PerVertexKHR inputs") - if attrs and F16_HALVES: - # --f16-interp-fallback reads decoded halves from the producer: no per-vertex inputs either - raise Unsupported("computed I/J pair under --f16-interp-fallback: no PerVertexKHR inputs") - return attrs - - -def reg_reads_writes(insns): - """(vgprs read, vgprs written) over a slice of insns, by read_before_write_vgprs' conventions.""" - rr, ww = set(), set() - for ins in insns: - a, op = ins["args"], ins["op"] - if not a: - continue - reads_all = op.startswith(VGPR_READ_ONLY_PREFIXES) - regs = [] - for x in (a if reads_all or sdwa_reads_dst(op, ins.get("mods", [])) else a[1:]): - if x["k"] == "vgpr": - regs += range(x["r"], x["r"] + x.get("n", 1)) - elif x["k"] == "vlist": - regs += x["r"] - if base_op(op) in ("v_swap_b32", "v_fmac_f32", "v_mac_f32", "v_mac_legacy_f32", "v_fmac_f16", "v_dot4c_i32_i8", "v_pk_fmac_f16", - "v_dot2c_f32_f16", "v_dot2c_i32_i16", "v_dot2c_u32_u16", "v_dot4c_u32_u8", - "v_dot8c_i32_i4", "v_dot8c_u32_u4") and a[0]["k"] == "vgpr": - regs.append(a[0]["r"]) - rr.update(regs) - if not reads_all and a[0]["k"] == "vgpr": - ww.update(vgpr_dest_registers(ins)) - return rr, ww - - -def shader_container(path, name): - """The DXBC container next to the .s file's folder (/../.dxbc). A pipeline-library program whose - source isn't in the carve has none (docs/shader_library.md): Unsupported for that shader, where the bare open() - raised FileNotFoundError and stopped the whole run.""" - try: - with open(os.path.join(os.path.dirname(os.path.dirname(os.path.realpath(path))), name + ".dxbc"), "rb") as f: - return f.read() - except FileNotFoundError: - raise Unsupported("no shader container (signatures, PSV0)") from None - - -def source_wave_size(path, name): - """Read the source container's wave size only when all of its FSSM payloads agree.""" - try: - blobs = fssm_unpack.unpack_all(shader_container(path, name)) - except (OSError, Unsupported, ValueError, struct.error, zlib.error): - return None - sizes = {fssm_header.wave_size(blob) for blob in blobs} - if len(sizes) == 1: - return sizes.pop() - return None - - -def input_signature_full(path, name): - """ISG1 elements as (system value, declared mask, read/write mask).""" - d = shader_container(path, name) - for k in range(struct.unpack_from("> 2) == 0x35 # VOP3 (encoding 110101) - vop3p = printed[3] == 0xCC - if not (vop3 or vop3p): - return False - op = base_op(op) - if op.startswith("v_cmpx_"): - source_count = 2 # EXEC is implicit on gfx10, but some listings spell it out. - else: - dest_count = 2 if op in VOP3_TWO_DESTS else 1 - source_count = operand_count - dest_count - for index, shift in enumerate((41, 50), start=1): # SRC1, SRC2 - if 0 <= source_count <= index and (diff >> shift) & 0x1FF == 0x80 and (r >> shift) & 0x1FF == 0: - diff &= ~(0x1FF << shift) - two_src = op.startswith("v_pk_") and not any(k in op for k in ("fma", "mad")) - if vop3p and source_count == 2 and two_src: - diff &= ~(1 << 14) - return diff == 0 - - -def mix_literal(raw, printed, op): - """The 32-bit literal of a v_fma_mix* when LLVM printed it cut to its low half, else None. - - A v_fma_mix source read as f16 (op_sel_hi set) takes the half op_sel names, so one literal can feed one source its - low half and another its high half (seen in the FidelityFX DLL's FSPX code: src0 low, src2 high, op_sel:[0,0,1] - op_sel_hi:[1,0,1]). llvm-mc prints that literal as its low 16 bits and re-encodes it with a zero high half, which - would read the high half as +0.0. Only that half may differ: the 8 instruction bytes must match (same_encoding - with all three sources counted as used, so nothing is forgiven and a live s0 can't pass as an inline 0) and the - printed literal must be the stored one's low half. That the hardware hands op_sel's high half of the - literal to that source is not measured; Mesa's ACO relies on it (optimize_constants() in aco_optimizer.cpp packs - two constants as the two f16 halves of one literal for v_fma_mix), and the console compiler emitted it here.""" - if not op.startswith("v_fma_mix") or len(raw) != 12 or len(printed) != 12 or raw[3] != 0xCC: - return None - if not same_encoding(raw[:8], printed[:8], op, 4): # vdst, src0, src1, src2 - return None - stored, shown = int.from_bytes(raw[8:], "little"), int.from_bytes(printed[8:], "little") - if stored == shown or shown != stored & 0xFFFF: - return None - return stored - - -def restore_mix_literal(ins, raw, literal): - """Give every source of ``ins`` that the stored bytes encode as the literal (SRC field 0xff) its 32-bit value.""" - w1 = int.from_bytes(raw[4:8], "little") - for i in range(3): - if (w1 >> (9 * i)) & 0x1FF == 0xFF and ins["args"][1 + i].get("k") == "imm": - ins["args"][1 + i] = {**ins["args"][1 + i], "v": literal} - - -# The f16 bits each inline constant code stands for when llvm-mc 21 prints a v_fma_mix* literal as that constant: -# 0..64, -1..-16, +-0.5, +-1.0, +-2.0, +-4.0 and 1/(2*pi). Measured with llvm-mc 21.1.8 (-mcpu=gfx1013) over all 65,536 -# low halves of a literal under three high halves (0x0000, 0x3f80, 0xffff): exactly these 90 low halves print as the -# inline constant, whatever the high half; every other literal prints in full. -MIX_INLINE_F16 = {**{0x80 + n: n for n in range(65)}, **{0xC0 + n: -n & 0xFFFF for n in range(1, 17)}, - 0xF0: 0x3800, 0xF1: 0xB800, 0xF2: 0x3C00, 0xF3: 0xBC00, 0xF4: 0x4000, 0xF5: 0xC000, - 0xF6: 0x4400, 0xF7: 0xC400, 0xF8: 0x3118} - - -def mix_inline_literal(raw, printed, op): - """The 32-bit literal of a v_fma_mix* that llvm-mc 21 printed as an inline constant, else None. - - llvm-mc 21's gfx1013 decoder reads a v_fma_mix* literal as 16 bits. When those low 16 bits are the f16 value of an - inline constant (MIX_INLINE_F16), it prints that constant and re-encodes the instruction in 8 bytes: each SRC - field that held 0xff (the literal) holds the inline code instead, and the literal word is gone (0x3f800000, 1.0 as - an f32 source, prints as 0; 0x3c003800 as `0.5`). llvm-mc 23 prints lit(...) instead. ``raw`` is the 12 stored - bytes at the instruction's offset, ``printed`` the 8-byte printed encoding. Only that change is accepted: every - source field that differs must be 0xff in the blob and the inline code of the literal's low half in the print, - and the rest of the 8 bytes must match exactly (same_encoding with all three sources live).""" - if not op.startswith("v_fma_mix") or len(raw) != 12 or len(printed) != 8 or raw[3] != 0xCC: - return None - literal = int.from_bytes(raw[8:], "little") - stored, shown = int.from_bytes(raw[4:8], "little"), int.from_bytes(printed[4:8], "little") - patched = shown - for i in range(3): - field = (shown >> 9 * i) & 0x1FF - if (stored >> 9 * i) & 0x1FF == 0xFF and field != 0xFF and MIX_INLINE_F16.get(field) == literal & 0xFFFF: - patched = (patched & ~(0x1FF << 9 * i)) | (0xFF << 9 * i) - if patched == shown or not same_encoding(raw[:8], printed[:4] + patched.to_bytes(4, "little"), op, 4): - return None - return literal - - -def restore_mix_inline_literal(ins, raw, literal): - """Give ``ins`` the stored instruction mix_inline_literal accepted: every source the blob encodes as the literal - (SRC field 0xff) reads the 32-bit ``literal`` with the stored neg (NEG) and abs (NEG_HI, as abs on v_fma_mix*) - bits, and the encoding is the 12 stored bytes, so the next instruction starts after them.""" - w0, w1 = int.from_bytes(raw[:4], "little"), int.from_bytes(raw[4:8], "little") - for i in range(3): - if (w1 >> 9 * i) & 0x1FF == 0xFF: - ins["args"][1 + i] = {"k": "imm", "v": literal, "neg": bool((w1 >> (29 + i)) & 1), - "abs": bool((w0 >> (8 + i)) & 1)} - ins["enc"] = raw.hex() - - -def output_signature(path, name): - """OSG1 elements as (register, system value), one per register (first element wins).""" - d = shader_container(path, name) - for k in range(struct.unpack_from("> c) & 1: - slots.append(("clip", clip_n)) - clip_n += 1 - cull_n = 0 - for _, _, mask in cull_elems: - for c in range(4): - if (mask >> c) & 1: - slots.append(("cull", cull_n)) - cull_n += 1 - base_pos = 2 if has_misc else 1 - pos_map = {} - for k, target in enumerate(slots[:8]): - p = base_pos + k // 4 - pos_map.setdefault(p, {})[k % 4] = target - clip_n = min(clip_n, 8) - cull_n = min(cull_n, max(0, 8 - clip_n)) - return pos_map, misc_svs, clip_n, cull_n - - -def check_read_methods(methods, insns): - """Refuse a PS whose FSSM read methods (tools/fssm_header.py, flags bits 0-1) disagree with its code. - - Bit 0 says the code reads the input through v_interp_mov_f32 (declared Flat here), bit 1 through - v_interp_p1/p2 or the f16 forms (a plain input: perspective, pixel centre, BaryCoordKHR for raw - i/j). In the corpus each read position agrees (12,101 of 12,101 PS) and neither-or-both never - occurs. A disagreement means a table this translator does not understand, so it is rejected - instead of being read as perspective-centre. That every interpolated input is perspective-centre - comes from PSV0 (docs/design.md "PS interpolation modes", #1256), not from these bits. Positions - past the table are not checked (the 10 kind-7 tables undercount).""" - for ins in insns: - op = base_op(ins["op"]) - if not op.startswith("v_interp_"): - continue - attr = next((x for x in ins["args"] if x["k"] == "attr"), None) - if attr is None or attr["a"] >= len(methods): - continue - want = fssm_header.READ_MOV if op == "v_interp_mov_f32" else fssm_header.READ_INTERP - if methods[attr["a"]] != want: - raise Unsupported(f"PS input {attr['a']} read method {methods[attr['a']]} read by {op}") - -def mesh_psv(path, name): - """PSV0 runtime info of a mesh shader: MSInfo (GroupSharedBytesUsed, GroupSharedViewIDDependentBytes, - PayloadSizeInBytes, u16 MaxOutputVertices, u16 MaxOutputPrimitives), wave lane counts, then PSVRuntimeInfo1 - (stage, UsesViewID, u8 SigPrimVectors, u8 MeshOutputTopology, ...) and PSVRuntimeInfo2 NumThreadsX/Y/Z.""" - d = shader_container(path, name) - for k in range(struct.unpack_from(".fssm for the game's shaders, and fspx/.code and - fspx/.json for the FSPX programs tools/fspx_unpack.py writes (docs/fspx.md).""" - root = os.path.dirname(os.path.dirname(os.path.realpath(path))) - return (os.path.join(root, "fssm", name + ".fssm"), os.path.join(root, "fspx", name + ".code"), - os.path.join(root, "fspx", name + ".json")) - - -def native_blob(path, name): - """The bytes the .s was disassembled from (its code_start offset is into these): the FSSM blob, or the FSPX - program when there is no FSSM for this name.""" - fssm, code, _ = native_paths(path, name) - with open(fssm if os.path.isfile(fssm) or not os.path.isfile(code) else code, "rb") as f: - return f.read() - - -def ds_const_extent(op, key, value): - """Dwords from LDS address 0 to the end of the access a DS instruction's constant offset field `key` makes with - vaddr 0: `offset` counts bytes; read2/write2/wrxchg2 offset0/offset1 count elements (x64 for st64). The access - width is the instruction's (b8 1 byte ... b128 16), so an access ending at a 64 KiB allocation counts 16384.""" - if key == "offset": - size = (16 if "b128" in op else 12 if "b96" in op else 8 if "b64" in op else - 2 if re.search(r"_[uib]16", op) else 1 if re.search(r"_[uib]8", op) else 4) - start = value - else: - size = 8 if op.endswith("_b64") else 4 - start = value * size * (64 if "st64" in op else 1) - return (start + size - 1) // 4 + 1 - - -def check_printed_encodings(path, info): - """A listing without undecodable words is translated from LLVM's text, which shows the instruction LLVM decoded, - not the bytes it read. Where those bytes sit next to the listing (fssm/ or fspx/), each instruction's printed - encoding must be the bytes at its offset (same_encoding), so a field the decoder drops is refused instead of - being translated as 0: llvm-mc's gfx1013 decoder prints 16-bit VOPC compares without their VOP3 op_sel bits - and re-encodes them as 0. On the 1.0.2.1 corpus all 30,335,381 instructions of the 25,030 such listings match. - Only a listing whose header names the code range it was disassembled from (shader_disasm.py), with a blob that - holds that range, is checked: a hand-written listing, run_gpu_tests.py's "code 0x0..0x0 (synthetic)" and a - test's header-only blob are not the bytes the text came from.""" - with open(path, encoding="utf-8", errors="replace") as f: - m = HDR.match(f.readline()) - if not m or int(m.group(3), 16) <= int(m.group(2), 16): - return - fssm, code, _ = native_paths(path, info["name"]) - if not (os.path.isfile(fssm) or os.path.isfile(code)): - return - blob = native_blob(path, info["name"]) - if int(m.group(3), 16) > len(blob): - return - shift = 0 # bytes the decoder read past the printed encodings so far (mix_inline_literal) - for ins in info["insns"]: - ins["pc"] += shift - if not ins.get("enc"): - continue - enc = bytes.fromhex(ins["enc"]) - raw = blob[ins["pc"]:ins["pc"] + len(enc)] - if not same_encoding(raw, enc, ins["op"], len(ins["args"])): - literal = mix_literal(raw, enc, base_op(ins["op"])) - if literal is not None: - restore_mix_literal(ins, raw, literal) - continue - raw12 = blob[ins["pc"]:ins["pc"] + 12] - literal = mix_inline_literal(raw12, enc, base_op(ins["op"])) - if literal is not None: - restore_mix_inline_literal(ins, raw12, literal) - shift += 4 - continue - raise Unsupported(f"{ins['op']} at 0x{ins['pc']:x}: the blob holds {raw.hex()}, LLVM printed " - f"{enc.hex()} (a field the disassembler dropped)") - - -def cs_dispatch_state(path, name): - """(COMPUTE_PGM_RSRC2, group x, y, z): FSSM header words 0x138..0x144, or an FSPX program's kind-0 entry.""" - fssm, _, meta = native_paths(path, name) - if os.path.isfile(fssm) or not os.path.isfile(meta): - with open(fssm, "rb") as f: - hdr = f.read(0x148) - return struct.unpack_from("<4I", hdr, 0x138) - with open(meta, encoding="utf-8") as f: - m = _json.load(f) - return (m["rsrc2"], *m["threads"]) - - -def fspx_wave_size(path, name): - """32 or 64 from an FSPX program's dispatch state, or None: the `wave32` field tools/fspx_unpack.py writes to - fspx/.json from kind 0's word 4 bit 20 (set = wave32; docs/fspx.md, "Kind 0: dispatch state"). None when - the program has an FSSM blob, no fspx/.json, or a kind 0 too short to hold word 4.""" - fssm, _, meta = native_paths(path, name) - if os.path.isfile(fssm) or not os.path.isfile(meta): - return None - try: - with open(meta, encoding="utf-8") as f: - wave32 = _json.load(f).get("wave32") - except (OSError, ValueError, AttributeError): - return None - return None if not isinstance(wave32, bool) else (32 if wave32 else 64) - - -def translate(path): - info = parse_file(path) - stage = stage_of(info["name"], path) - if stage not in ("vs", "ps", "cs", "ms", "gs"): - raise Unsupported(f"stage {stage}") - insns = info["insns"] - if not insns: - # parse_file only reads tab-indented instructions, so a hand-written or re-indented .s parses to nothing - # and used to translate to a module that passes spirv-val and does no work at all. Refuse it instead. - raise Unsupported("no instructions (nothing tab-indented?)") - if info["invalid"]: - # Undecodable words are constant tables embedded in the code range (147/155 such VS/PS use s_getpc_b64 to - # read them). LLVM skips them, so re-anchor every instruction to its true offset in the FSSM blob, then - # translate only code reachable from entry; a branch into data is rejected below. - blob = native_blob(path, info["name"]) - pos = info["code_start"] - for ins in insns: - enc = bytes.fromhex(ins["enc"]) - op, operand_count = ins["op"], len(ins["args"]) - skipped, at = 0, pos - while not same_encoding(blob[at:at + len(enc)], enc, op, operand_count): - literal = mix_literal(blob[at:at + len(enc)], enc, base_op(op)) - if literal is not None: - restore_mix_literal(ins, blob[at:at + len(enc)], literal) - break - literal = mix_inline_literal(blob[at:at + 12], enc, base_op(op)) - if literal is not None: - restore_mix_inline_literal(ins, blob[at:at + 12], literal) - enc = blob[at:at + 12] # the 12 bytes the decoder read: the next one starts after them - break - at += 4 - skipped += 4 - if skipped > 4096 or at >= len(blob): - at = None - break - if at is None: - # LLVM prints the encoding of the instruction it decoded, not the bytes it read: data words that - # decode with ignored fields set (e.g. 0xbe8d2242 -> s_rfe_b64, printed 0xbe802242) never match. - # The decoder consumed the same number of bytes, so the instruction sits at the current position. - # Such words are data in every case seen; reachable_code drops them unless a branch lands there. - if pos + len(enc) > len(blob): - raise Unsupported("undecodable words (cannot re-anchor)") - at = pos - ins["normalized"] = True - ins["pc"] = at - pos = at + len(enc) - insns = fold_far_branches(insns) - insns = reachable_code(insns, info.get("code_end")) - if any(i.get("normalized") for i in insns): - raise Unsupported("reachable instruction with normalized encoding") - else: - check_printed_encodings(path, info) - g = Gen(stage, hoist_reg_ptrs=True, cache_active=True) - g.exec_static_true = not any(writes_exec(i) for i in insns) - if stage in ("vs", "ms"): # --f16-interp-fallback places the decoded halves clear of every param - g.param_max = max((int(t[5:]) for i in insns if base_op(i["op"]) == "exp" for t in - (i["args"][0].get("t", ""),) if t.startswith("param") and t[5:].isdigit()), default=-1) - g.round_mode = any(i["op"] == "s_round_mode" or - (i["op"].startswith("s_setreg") and "HW_REG_MODE" in i["args"][0].get("t", "")) - for i in insns) - w64_marks = {base_op(i["op"]) for i in insns - if WAVE64_RE.search(" ".join([i["op"]] + [x.get("t", "") for x in i["args"]]))} - strict_w64 = bool(w64_marks) - code_w64 = strict_w64 or any(base_op(i["op"]).endswith("_b64") and any(x.get("t") in ("exec", "vcc") - for x in i["args"]) for i in insns) - code_w32 = any(WAVE32_RE.search(i["op"]) for i in insns) - # Authoritative wave size from the FSSM header flags at 0xD4 bit 5 (0x20 = wave32, 0 = wave64; - # verified with 0 contradictions across all 26,503 corpus blobs). Falls back to the code-marker - # heuristic (+ wave64 default for NGG mesh shaders) when no FSSM sidecar is present (FSPX or - # synthetic listings). - fssm_path, fspx_path, _ = native_paths(path, info["name"]) - fssm_ws = None - try: - with open(fssm_path, "rb") as f: - fssm_ws = fssm_header.wave_size(f.read(fssm_header.WAVE_FLAGS_OFFSET + 4)) - except OSError: - pass - # An FSPX program (the FidelityFX DLL's) has no FSSM header; its kind-0 dispatch state carries the wave size - # instead (word 4 bit 20 = wave32, docs/fspx.md). Only the strict markers count against it: a _b64 op on vcc or - # exec is not one, since these programs move vcc as an ordinary SGPR pair (s_mov_b64 vcc, s[..]) in wave32 code. - # Nor is s_bfm_b64: it is 64-bit data in wave32 code (958 pipeline-library compute programs whose state says - # wave32, 905 of them with *_saveexec_b32, build an S# with it; see the s_bfm_b64 translation). - fspx_ws = fspx_wave_size(path, info["name"]) if fssm_ws is None else None - if fssm_ws is not None: - if fssm_ws == 32 and code_w64: - raise Unsupported("FSSM wave32 header contradicts wave64 code") - if fssm_ws == 64 and code_w32: - raise Unsupported("FSSM wave64 header contradicts wave32 code") - g.wave64 = fssm_ws == 64 - elif fspx_ws is not None: - if fspx_ws == 32 and w64_marks - {"s_bfm_b64"}: - raise Unsupported("FSPX wave32 dispatch state contradicts wave64 code") - if fspx_ws == 64 and code_w32: - raise Unsupported("FSPX wave64 dispatch state contradicts wave32 code") - g.wave64 = fspx_ws == 64 - elif (stage in ("vs", "ps") and code_w64 and code_w32 and not (w64_marks - {"s_bfm_b64"}) - and os.path.isfile(fspx_path) and source_wave_size(path, info["name"]) == 32): - # A library program can use s_bfm_b64 as scalar data. Use the matching source's - # wave32 flags only when this program's own EXEC instructions corroborate them. - g.wave64 = False - else: - g.wave64 = code_w64 or stage == "ms" # NGG mesh shaders here are wave64 (thread = wave id * 64 + lane) - if stage == "gs": - ins_by_reg = {} - for reg, mask, sv, ctype in input_signature(path, info["name"]): - if reg in ins_by_reg and (ins_by_reg[reg] == 1) != (sv == 1): - raise Unsupported("gs signature") - ins_by_reg.setdefault(reg, sv) - ins_sig = sorted(ins_by_reg.items()) - outs = output_signature(path, info["name"]) - if not ins_sig or not outs: - raise Unsupported("gs signature") - n_emit = sum(1 for i in insns if base_op(i["op"]) == "s_sendmsg" and - any("GS_OP_EMIT" in x.get("t", "") for x in i["args"])) - if not (1 <= n_emit <= 64): - raise Unsupported("gs emit count") - g.gs = {"in": ins_sig, "out": outs, "nreg": max(r for r, _ in outs) + 1, "maxv": n_emit} - for i in (0, 1, 3, 8, 64, 128, 0x4000, g.gs["nreg"], 64 << 16): # used by assemble - g.cu(i) - for i in range(n_emit * g.gs["nreg"] + 1): - g.cu(i) - if stage == "ms": - # Mesh shaders run as NGG wave64 programs. PSV0 (DXBC) gives NumThreads, MaxOutputVertices/Primitives and - # the output topology. System inputs (Mesa radv_shader_args.c, mesh as NGG on GFX10.3): v5 = first launch - # vertex ID of the lane, groupIndex * NumThreads + lane ("vertex_id" slot); the merged-wave-info SGPR (s3 here) holds the wave id in [27:24]; user data - # follows in s16.. (from push constants, like every stage). - psv = mesh_psv(path, info["name"]) - if psv is None: - raise Unsupported("mesh PSV0") - if psv["topology"] != 2: - raise Unsupported(f"mesh topology {psv['topology']}") - if not (1 <= psv["threads"] <= 1024) or not (1 <= psv["maxv"] <= 256) or not (1 <= psv["maxp"] <= 512): - raise Unsupported("mesh limits") - g.ms = psv - g.cu(psv["threads"]) # the v5 seed (assemble) multiplies by it; constants must exist before assembly - # LDS: the declared group-shared size, grown to cover every constant offset the code uses. - need = (psv.get("shared", 0) + 3) // 4 - for ins in insns: - if not ins["op"].startswith("ds_") or ins["op"].startswith(("ds_swizzle", "ds_bpermute", "ds_permute")): - continue - for m in ins["mods"]: - k, _, v = m.partition(":") - if not v[:1].isdigit(): - continue - if k in ("offset", "offset0", "offset1"): - need = max(need, ds_const_extent(ins["op"], k, int(v, 0))) - n = 16 - while n < need: - n *= 2 - g.lds_dwords = min(n, 16384) - g.cu(g.lds_dwords) - g.cu(g.lds_dwords - 1) - for i in (2, 3, 5, 6, 10, 12, 20, 24, 31, 63, 0x108, 0x1FF, 0xFFF, psv["maxv"], psv["maxp"]): # used by assemble - g.cu(i) - if stage == "cs": - # Compute system registers come from the FSSM header. Word 0x138 is COMPUTE_PGM_RSRC2 (checked against - # the SGPRs all 2,689 CS read before writing: 2,540 stay inside it, the other 149 overshoot only through - # loop-carried registers of the straight-line check; docs/design.md): USER_SGPR [5:1], TGID_X/Y/Z_EN [9:7], - # TG_SIZE_EN [10], TIDIG_COMP_CNT [12:11]. Words 0x13C/0x140/0x144 are the thread-group size. Layout (Mesa - # radv_shader_args.c): s0..user-1 = user data, then the enabled workgroup ids, then with TG_SIZE_EN the - # thread-group SGPR; v0, v1, v2 = thread id x, y, z (separate VGPRs on GFX10). An FSPX program (the FidelityFX - # DLL's shaders) and a pipeline-library program (docs/shader_library.md) carry the same two fields in their - # kind-0 entry (docs/fspx.md). - rsrc2, lx, ly, lz = cs_dispatch_state(path, info["name"]) - if not (1 <= lx * ly * lz <= 1024): - raise Unsupported("CS group size") - user = (rsrc2 >> 1) & 31 - g.cs = {"user": user, "tgid": [c for c in range(3) if (rsrc2 >> (7 + c)) & 1], - "tid": (rsrc2 >> 11) & 3, "size": (lx, ly, lz), "tg_size": bool((rsrc2 >> 10) & 1)} - # LDS_SIZE [23:15] in 512-byte units. All 485 LDS-using corpus CS stay inside it; a constant offset past it, - # which RDNA2 treats as out of range, is bounds-checked below (SHADER-309). - need = ((rsrc2 >> 15) & 0x1FF) * 128 - for ins in insns: - if not ins["op"].startswith("ds_") or ins["op"].startswith(("ds_swizzle", "ds_bpermute", "ds_permute")): - continue - for m in ins["mods"]: - k, _, v = m.partition(":") - if not v[:1].isdigit(): - continue - if k in ("offset", "offset0", "offset1"): - need = max(need, ds_const_extent(ins["op"], k, int(v, 0))) - g.lds_declared = ((rsrc2 >> 15) & 0x1FF) * 128 - g.lds_need = need - if need > g.lds_declared: - # SHADER-309: a constant offset reaches past the RSRC2 allocation. RDNA2 reads 0 and drops the write - # there instead of wrapping (ISA 3.6.1, 3.6.6), so the array is the allocation and every access is - # bounds-checked (lds_access). Shaders that stay inside it keep the wrapped power-of-two array. - g.lds_dwords = g.lds_bound = g.lds_declared - g.cu(g.lds_bound) - else: - n = 16 - while n < need: - n *= 2 - g.lds_dwords = min(n, 16384) - g.cu(max(g.lds_dwords, 1)) - g.cu(max(g.lds_dwords, 1) - 1) - for i in range(user, user + 3): - g.cu(i) - if stage == "ps": - # Pixel-shader system VGPRs (12,098 of 12,101 PS exact; docs/design.md): v0-v1 = barycentrics (modelled through - # v_interp -> attributes), then v2.. = the SV_Position components the shader reads, packed in order. - # Anything else a PS reads before writing is an input layout we haven't confirmed: reject it. - sig = input_signature_full(path, info["name"]) - pos = [rw for sv, m, rw in sig if sv == 1] - used = pos[0] if pos else 0 - # Position w: AMD's POS_W_FLOAT input holds 1/w. Mesa (src/amd/common/nir/ac_nir_lower_intrinsics_to_args.c) - # lowers nir_intrinsic_load_frag_coord_w_rcp straight to frag_pos[3]. That's the same value as Vulkan's - # FragCoord.w, so all four components map directly. - # Hardware order (Mesa src/amd/vulkan/radv_shader_args.c): barycentric pairs, ..., POS_X/Y/Z/W, FRONT_FACE, - # ANCILLARY, SAMPLE_COVERAGE, POS_FIXED_PT. Only enabled inputs are packed. Front face is a float whose - # sign gives facing (Mesa: load_front_face = front_face > 0; load_front_face_fsign = the raw value). - layout = {} - nxt = 2 - for c in range(4): - if used >> c & 1: - layout[nxt] = c - nxt += 1 - if any(sv == 9 for sv, _, _ in sig): # D3D_NAME_IS_FRONT_FACE - layout[nxt] = "front" - nxt += 1 - no_bary = [dict(i, args=[x for k, x in enumerate(i["args"]) - if not (i["op"].startswith("v_interp") and x["k"] == "vgpr" and k != 0)]) - for i in insns] - reads = read_before_write_vgprs(no_bary) - # Reads inside the system-input range that aren't in the layout (raw barycentrics, unknown inputs): reject. - # Reads past the last hardware input can't be hardware inputs: they're values undefined on some path, and - # the zero-initialised registers stand in for them. - # Raw reads of the barycentric pair (v0 = i, v1 = j) outside v_interp, e.g. v_readfirstlane_b32 s41, v1 in - # 315 PS: AMD interpolates P = P0 + i(P1 - P0) + j(P2 - P0), so i and j are the weights of vertices 1 and 2, - # which VK_KHR_fragment_shader_barycentric gives as BaryCoordKHR.y / .z. Assumes the pair is the - # perspective-center one, the only pair this layout models. - for r, comp in ((0, "bary_i"), (1, "bary_j")): - if r in reads: - layout[r] = comp - unexplained = {r for r in reads if r < nxt and r not in layout} - if unexplained: - raise Unsupported("PS system inputs") - g.frag_inputs = layout - attr_reads: dict[str, set[int]] = defaultdict(set) - for ins in insns: - op = base_op(ins["op"]) - if op.startswith("v_interp_"): - attr_reads[op].update(arg["a"] for arg in ins["args"] if arg["k"] == "attr") - f16_read = attr_reads["v_interp_p1ll_f16"] | attr_reads["v_interp_p1lv_f16"] | attr_reads["v_interp_p2_f16"] - mixed_f32 = attr_reads["v_interp_mov_f32"] & (attr_reads["v_interp_p1_f32"] | attr_reads["v_interp_p2_f32"]) - if mixed_f32 and (BARY_FALLBACK or F16_HALVES): - raise Unsupported("flat and interpolated reads of one f32 attribute need per-vertex inputs") - mov_delta = {x["a"] for i in insns if base_op(i["op"]) == "v_interp_mov_f32" - and any(x.get("k") == "interp" and x.get("t") in ("p10", "p20") for x in i["args"]) - for x in i["args"] if x["k"] == "attr"} - if F16_HALVES: # decoded halves from the producer: no per-vertex inputs (and no barycentrics) - g.f16_halves = f16_read - elif not BARY_FALLBACK: - # A smooth input alone cannot supply P0 for a MOV reading the same location. - g.per_vertex = f16_read | mixed_f32 | mov_delta - for r in layout: - g.cu(r) - # FSSM pixel-input table (tools/fssm_header.py): the authoritative interpolant list. Position i of the - # table is v_interp attr i; interpolants() gives the count and the 16-bit flag mask by position. Every - # table position is declared as a fragment input (the table lists inputs the code never reads: 775 of - # 12,101 PS overcount by one or more), and the mask marks 16-bit interpolants for the v_interp path - # above. No sidecar, or a sidecar with no table, leaves the code-driven declarations untouched. - try: - with open(os.path.join(os.path.dirname(os.path.dirname(os.path.realpath(path))), "fssm", - info["name"] + ".fssm"), "rb") as f: - blob = f.read() - count, fp16 = fssm_header.interpolants(blob) - methods = fssm_header.read_methods(blob) - except OSError: - count, fp16, methods = 0, 0, [] - check_read_methods(methods, insns) - if count: - g.pixel_interpolants = (count, fp16) - g.pixel_flat = [n for n, m in enumerate(methods) if m == fssm_header.READ_MOV] - for n in range(count): - g.inputs.setdefault(f"%in_attr{n}", n) - if stage == "ps": - # D3D_NAME_TARGET (64); OSG1 keeps SV_Target n in register n, so the semantic index is the render target. - g.mrt_targets = sorted({sem for _, sem, sysv, _, _ in output_signature_full(path, info["name"]) if sysv == 64}) - if stage in ("vs", "ms"): - g.pos_map, g.pos_misc, g.clip_count, g.cull_count = pos_export_layout( - output_signature_full(path, info["name"]), insns) - if stage == "vs" and any(base_op(i["op"]) == "s_swappc_b64" for i in insns): - # The call goes to a driver-generated fetch program (not in the blob). Verified rule over 788 shaders: - # input-signature register r, component c is fetched into v(4 + 4r + c). Replace the call with Vulkan - # vertex inputs (location = register) written into those VGPRs at entry. - sig = [s for s in input_signature(path, info["name"]) if s[2] == 0] - # Any component of a declared register may be read: components the vertex format lacks come back as the - # format defaults (0, 0, 1 for y, z, w) from the hardware fetch, and Vulkan fills a vec4 input from a - # narrower format the same way. Seen: .w of an xyz position. - predicted = {4 + 4 * reg + c for reg, mask, _, _ in sig for c in range(4)} - reads = {r for r in read_before_write_vgprs(insns) if r >= 4} - if not reads <= predicted: - raise Unsupported("fetch mapping") - g.vertex_inputs = vertex_input_locations(sig) - g.vertex_signature = [{"register": reg, "mask": mask, "system_value": sv, "component_type": ctype} - for reg, mask, sv, ctype in sig] - for reg, _ in g.vertex_inputs: # register the VGPR index constants before assembly - for c in range(4): - g.cu(4 + 4 * reg + c) - insns = [i for i in insns if base_op(i["op"]) != "s_swappc_b64"] - user_limit = g.cs["user"] if g.cs else USER_SGPRS - sys_sgprs = (3,) if stage in ("ms", "gs") else () - if WAVE64_EMULATE and g.wave64 and stage in ("cs", "ms"): - g.emulate = True - size = (g.cs or g.ms)["size"] - g.x_lanes = -(-size[0] * size[1] * size[2] // 64) * 64 - insns = fold_far_branches(insns) - branchy = any(base_op(i["op"]) in BRANCHES for i in insns) - if stage == "ps": - g.v_interp_copy = interp_copy_sources(insns) # before v_interp runs: I/J guards (SHADER-177) - # SHADER-177: annotate v_interp sites whose I/J operand is a computed pair, and let those - # attributes be read per-vertex (attribute() weights them with the operand values). - g.per_vertex |= interp_ij_analysis(insns, g) - if any("ij" in i for i in insns): - # Computed v_interp sites load their I/J VGPRs at runtime; no_bary above stripped all - # v_interp sources, so an untouched (or conditionally/EXEC-masked written) v0/v1 still - # needs BaryCoordKHR loaded into %vgpr[0]/%vgpr[1] in the prologue. - with_ij = [dict(i, args=[x for k, x in enumerate(i["args"]) - if not (i["op"].startswith("v_interp") and "ij" not in i - and x["k"] == "vgpr" and k != 0)]) - for i in insns] - ij_reads = read_before_write_vgprs(with_ij) - conditional = branchy or any(writes_exec(i) for i in insns) - for r, comp in ((0, "bary_i"), (1, "bary_j")): - if (r in ij_reads or conditional) and r not in g.frag_inputs: - g.frag_inputs[r] = comp - g.cu(r) - if any(base_op(i["op"]) in BRANCHES and not i.get("enc") for i in insns): - # A branch target is relative to the next PC, which needs the branch's `; encoding:` bytes (missing in a - # hand-written listing). Until 2026-11-22 this was a TypeError in next_pc. - raise Unsupported("branch without encoding") - if not branchy and not g.emulate: - g.vm_latch = stage == "ps" and exec_changes_after_vm([insns], [[]]) - g.park_masks(([insns], [[]])) - halves_analysis(g, [insns], [[]]) - g.build_meta = _shader_meta.collect(path, info["name"], [insns], [[]], - user_sgpr_limit=user_limit, system_sgprs=sys_sgprs) - g.fit_shared_memory() - end = next((k for k, ins in enumerate(insns) if base_op(ins["op"]) == "s_endpgm"), len(insns)) - g.exec_changes = any(g.may_write_exec(ins) for ins in insns[:end]) - g.insns(insns[:end]) - translate.last_gen = g - out = assemble(g) - if OPT_SPIRV: - import spirv_opt - out = spirv_opt.optimize(out) - return out - - # ---- basic blocks ---- - def next_pc(ins): - return ins["pc"] + len(ins["enc"]) // 2 - - def target(ins): - if "target" in ins: - return ins["target"] - imm = next((x for x in ins["args"] if x["k"] == "imm"), None) - if imm is None: - raise Unsupported("branch without offset") - v = imm["v"] & 0xFFFF - return next_pc(ins) + 4 * (v - 0x10000 if v & 0x8000 else v) - - leaders = {insns[0]["pc"]} - for ins in insns: - if base_op(ins["op"]) in BRANCHES: - leaders.add(target(ins)) - leaders.add(next_pc(ins)) - pcs = {i["pc"] for i in insns} - starts = sorted(p for p in leaders if p in pcs) - if any(p not in starts for p in (target(i) for i in insns if base_op(i["op"]) in BRANCHES)): - raise Unsupported("branch target outside code") - index = {p: n for n, p in enumerate(starts)} - blocks = [[] for _ in starts] - for n in range(len(blocks) + 1): - g.cu(n) # block numbers: %pc is compared with any of them - cur = -1 - for ins in insns: - if ins["pc"] in index: - cur = index[ins["pc"]] - blocks[cur].append(ins) - - # Successors ahead of emission, for node splitting and lane-mask analysis (the loop below works them out - # again as it goes, and the two are compared at the end). - raw_edges = [] - for n, blk in enumerate(blocks): - last = next((i for i in blk if base_op(i["op"]) == "s_endpgm" or base_op(i["op"]) in BRANCHES), None) - fall = [n + 1] if n + 1 < len(blocks) else [] - if last is None: - raw_edges.append(fall) - elif base_op(last["op"]) == "s_endpgm": - raw_edges.append([]) - elif base_op(last["op"]) == "s_branch": - raw_edges.append([index[target(last)]]) - else: - raw_edges.append([index[target(last)]] + fall) - split_edges = None - if STRUCTURED: - res = cfg_structure.split_irreducible(raw_edges) - if res is not None and len(res[0]) > len(blocks): - split_edges, orig_of = res - # Shallow-copy each instruction dict so lane_masks.py's id(ins) keys stay unique across clones. - blocks = [[dict(ins) for ins in blocks[o]] for o in orig_of] - for n in range(len(blocks) + 1): - g.cu(n) - raw_edges = split_edges - succ = [list(dict.fromkeys(e)) for e in raw_edges] - g.vm_latch = stage == "ps" and exec_changes_after_vm(blocks, succ) - g.park_masks((blocks, succ)) - halves_analysis(g, blocks, succ) - g.build_meta = _shader_meta.collect(path, info["name"], blocks, succ, - user_sgpr_limit=user_limit, system_sgprs=sys_sgprs) - - g.bar_rounds = needs_barrier_rounds(g, blocks, succ) - folds, fold_chain, absorbed = {}, {}, set() - if g.emulate: - g.scc_live = wave64_emulate_opt.scc_live_outs(blocks, succ) - folds, fold_chain, absorbed = wave64_emulate_opt.find_local_exec_folds( - blocks, raw_edges, succ, g.lane_masks, g.scc_live, g.mask_writes) - if STRUCTURED: - g.emulate_plan = wave64_emulate_opt.plan_structured_emulation( - blocks, raw_edges, succ, folds, fold_chain, absorbed, g.lane_masks, g.scc_live, g.x_lanes) - g.fit_shared_memory() - g.exec_changes = any(g.may_write_exec(ins) for blk in blocks for ins in blk) - g.x_seg = len(blocks) + 1 # emulate: continuation segments are numbered after "done" (len(blocks)) - - def emit_folded_region(fd): - """Emit a safe lane-local s_cbranch_execz/nz region inline behind `if (%active)`. Uniform control flow - before the branch orders any prior conflicting accesses against reads/writes in the region; inside the - region zero x_split or OpControlBarrier calls occur, keeping all 64 lanes synchronized.""" - if (any((kind, "w") in g.x_dirty for kind in fd["mem_reads"]) - or any((kind, "r") in g.x_dirty or (kind, "w") in g.x_dirty for kind in fd["mem_writes"])): - g.x_order_barrier() - g.desc_cache.clear() - g._active_ssa = None - g.sgpr_imm.clear() - g.x_tok.clear() - g.x_mcache.clear() - act = g.active_b() - lbl_do, lbl_end = g.tmp(), g.tmp() - g.emit(f"OpSelectionMerge {lbl_end} None") - g.emit(f"OpBranchConditional {act} {lbl_do} {lbl_end}") - g.emit(f"{lbl_do} = OpLabel") - marks_before = len(g.x_marks) - body_before = len(g.body) - if fd["sub_tree"] is None: - for ins in blocks[fd["run"]]: - op = base_op(ins["op"]) - if op == "s_endpgm" or op in BRANCHES: - break - g.insn(ins) - else: - order = fd["order"] - idx_of = {u: i for i, u in enumerate(order)} - sub_end = len(order) - for i in range(sub_end + 1): - g.cu(i) - g.emit(f"OpStore %pc {g.cu(0)}") - stack = [("items", fd["sub_tree"])] - while stack: - step = stack.pop() - if step[0] == "items": - for it in reversed(step[1]): - stack.append(("item", it)) - elif step[0] == "item": - it = step[1] - if it[0] == "block": - u = order[it[1]] - blbl = g.tmp() - g.emit(f"OpBranch {blbl}") - g.emit(f"{blbl} = OpLabel") - g.desc_cache.clear() - g._active_ssa = None - g.sgpr_imm.clear() - g.x_tok.clear() - g.x_mcache.clear() - uterm = None - for ins in blocks[u]: - op = base_op(ins["op"]) - if op == "s_endpgm": - uterm = ("end",) - break - if op in BRANCHES: - uterm = ("br", op) - break - g.insn(ins) - uedges = raw_edges[u] - if uterm is None or uterm[0] == "end": - nxt = idx_of.get(uedges[0], sub_end) if (uterm is None and uedges) else sub_end - g.emit(f"OpStore %pc {g.cu(nxt)}") - elif uterm[1] == "s_branch": - g.emit(f"OpStore %pc {g.cu(idx_of.get(uedges[0], sub_end))}") - else: - uop = uterm[1] - utgt = g.cu(idx_of.get(uedges[0], sub_end)) - ufall = g.cu(idx_of.get(uedges[1], sub_end) if len(uedges) > 1 else sub_end) - if uop in ("s_cbranch_execz", "s_cbranch_execnz"): - uact = g.active_b() - if uop == "s_cbranch_execz": - ucond = g.tmp() - g.emit(f"{ucond} = OpLogicalNot %bool {uact}") - else: - ucond = uact - else: - ucond = branch_condition(g, uop) - ur = g.tmp() - g.emit(f"{ur} = OpSelect %uint {ucond} {utgt} {ufall}") - g.emit(f"OpStore %pc {ur}") - elif it[0] == "guard": - v, c, do, end = g.tmp(), g.tmp(), g.tmp(), g.tmp() - g.emit(f"{v} = OpLoad %uint %pc") - g.emit(f"{c} = OpIEqual %bool {v} {g.cu(it[1])}") - g.emit(f"OpSelectionMerge {end} None") - g.emit(f"OpBranchConditional {c} {do} {end}") - g.emit(f"{do} = OpLabel") - stack.append(("guard_end", end)) - stack.append(("items", it[2])) - else: - head, top, cont, end = g.tmp(), g.tmp(), g.tmp(), g.tmp() - g.emit(f"OpBranch {head}") - g.emit(f"{head} = OpLabel") - g.emit(f"OpLoopMerge {end} {cont} None") - g.emit(f"OpBranch {top}") - g.emit(f"{top} = OpLabel") - stack.append(("loop_end", it[1], head, cont, end)) - stack.append(("items", it[2])) - elif step[0] == "guard_end": - g.emit(f"OpBranch {step[1]}") - g.emit(f"{step[1]} = OpLabel") - else: - _, sub_id, head, cont, end = step - v, again = g.tmp(), g.tmp() - g.emit(f"OpBranch {cont}") - g.emit(f"{cont} = OpLabel") - g.emit(f"{v} = OpLoad %uint %pc") - g.emit(f"{again} = OpIEqual %bool {v} {g.cu(sub_id)}") - g.emit(f"OpBranchConditional {again} {head} {end}") - g.emit(f"{end} = OpLabel") - assert len(g.x_marks) == marks_before, "wave64 emulation: x_split inside a folded lane-local region" - assert not any("OpControlBarrier" in l for l in g.body[body_before:]), \ - "wave64 emulation: OpControlBarrier inside a folded lane-local region" - g.emit(f"OpBranch {lbl_end}") - g.emit(f"{lbl_end} = OpLabel") - for kind in fd["mem_reads"]: - g.x_dirty.add((kind, "r")) - for kind in fd["mem_writes"]: - g.x_dirty.add((kind, "w")) - g.desc_cache.clear() - g._active_ssa = None - g.sgpr_imm.clear() - g.x_tok.clear() - g.x_mcache.clear() - - for n, blk in enumerate(blocks): - if n in absorbed: - g.blocks.append(None) - g.succ.append(succ[n]) - continue - plan = g.emulate_plan - g.emulate_inline = bool(plan is not None and n in plan["inline_blocks"]) - mini_idx = plan["mini_of_block"].get(n) if plan is not None else None - mini_set = plan["mini_blocks"][mini_idx] if mini_idx is not None else None - in_tail = bool(plan is not None and n in plan["tail_blocks"]) - g.body = [] - g.block_label = f"%blk{n}" - g.x_marks = [] - g.x_dirty = set(plan["dirty_in"].get(n, ())) if g.emulate_inline else set() - g.x_tok, g.x_mcache = {}, {} # a register's value is only known from where this block wrote it - g.x_gen += 1 - g.desc_cache.clear() - g._active_ssa = None # a cached lookup is only good inside the block that made it - g.sgpr_imm.clear() - cur = n - while True: - term, body = None, blocks[cur] - for k, ins in enumerate(blocks[cur]): - op = base_op(ins["op"]) - if op == "s_endpgm": - term, body = ("end",), blocks[cur][:k] - break - if op in BRANCHES: - term, body = ("br", op, index[target(ins)]), blocks[cur][:k] - break - g.insns(body) - if cur in folds: - emit_folded_region(folds[cur]) - if cur in fold_chain: - cur = fold_chain[cur] - g.desc_cache.clear() - g._active_ssa = None - g.sgpr_imm.clear() - g.x_tok.clear() - g.x_mcache.clear() - continue - nxt_skip = folds[cur]["skip"] - g.emit(f"OpStore %pc {g.cu(nxt_skip)}") - if mini_set is not None and nxt_skip not in mini_set: - g.emit("OpStore %x_ldone %true") - g.succ.append(succ[n]) - break - edges = raw_edges[cur] - fall = (edges[0] if edges else None) if term is None else (edges[1] if len(edges) > 1 else None) - # Every block leaves the number of the block to run next in %pc (len(blocks) = none: the program is over), - # and its possible successors in g.succ for cfg_structure. - if term is None or term[0] == "end": - nxt = fall if term is None else None - g.emit(f"OpStore %pc {g.cu(nxt if nxt is not None else len(blocks))}") - if nxt is None: - g.emit("OpStore %done %true") - if mini_set is not None and (nxt is None or nxt not in mini_set): - g.emit("OpStore %x_ldone %true") - g.succ.append(succ[n] if cur != n else ([nxt] if nxt is not None else [])) - else: - _, op, _ = term - tgt = edges[0] - if op == "s_branch": - g.emit(f"OpStore %pc {g.cu(tgt)}") - if mini_set is not None and tgt not in mini_set: - g.emit("OpStore %x_ldone %true") - g.succ.append(succ[n] if cur != n else [tgt]) - else: - marks0, body0 = len(g.x_marks), len(g.body) - cond = branch_condition(g, op) - alt = g.cu(fall) if fall is not None else g.cu(len(blocks)) # past the end = default -> done - r = g.tmp() - g.emit(f"{r} = OpSelect %uint {cond} {g.cu(tgt)} {alt}") - g.emit(f"OpStore %pc {r}") - if g.emulate and not g.emulate_inline and op in ( - "s_cbranch_vccz", "s_cbranch_vccnz", "s_cbranch_execz", "s_cbranch_execnz"): - # This segment only reads the vote and sets %pc, and the code before the vote ran in an earlier - # round: the successor can start in this one (x_scheduler). That only holds when the vote's own - # x_split started this segment: then it holds the vote read and the %pc select and nothing else. - # A vote that reused an earlier exchange (no split) would put the end of the block in the - # successor's round, with no barrier between their memory accesses. - if len(g.x_marks) != marks0 + 1 or g.x_marks[-1][0] < body0: - raise Unsupported("wave64 emulation: a voted branch must start its own segment") - g.emit("OpStore %x_chain %true") - if mini_set is not None: - tgt_in = tgt in mini_set - fall_in = fall is not None and fall in mini_set - if not tgt_in and not fall_in: - g.emit("OpStore %x_ldone %true") - elif not tgt_in and fall_in: - g.emit(f"OpStore %x_ldone {cond}") - elif tgt_in and not fall_in: - nc = g.tmp() - g.emit(f"{nc} = OpLogicalNot %bool {cond}") - g.emit(f"OpStore %x_ldone {nc}") - g.succ.append(succ[n] if cur != n else list(dict.fromkeys([tgt] + ([fall] if fall is not None else [])))) - break - if g.emulate_inline: - assert not g.x_marks, "wave64 emulation: unexpected x_split in inline block" - if plan is not None and n in plan["sync_free_blocks"]: - assert not any("OpControlBarrier" in l for l in g.body), \ - "wave64 emulation: unexpected OpControlBarrier in sync-free multi-wave block" - lines = [l.strip() for l in g.body] - if g.x_marks: - cuts = [0] + [i for i, _ in g.x_marks] + [len(lines)] - parts = x_spill(g, [lines[a:b] for a, b in zip(cuts, cuts[1:])]) - g.blocks.append(parts[0]) - for (_, seg), part in zip(g.x_marks, parts[1:]): - g.x_segs[seg] = part - if mini_idx is not None: - g.mini_segs[mini_idx].append(seg) - elif in_tail: - g.tail_segs.append(seg) - else: - g.blocks.append(lines) - g.emulate_inline = False - assert succ == g.succ, "the lane-mask analysis ran on a different graph" - g.body = [] - translate.last_gen = g - out = assemble(g) - if OPT_SPIRV: - import spirv_opt - out = spirv_opt.optimize(out) - return out - - -_DEF = re.compile(r"(%\w+) = (Op\w+)(?: (%\w+))?") - - -def capped_tree(succ): - """(tree, nesting): the structured tree for `succ` and its depth, or (None, None) under --dispatch-loop or when - cfg_structure can't structure it; tree is None (nesting still the measured depth) when it nests deeper than - MAX_STRUCTURED_DEPTH. assemble() emits exactly this tree, and needs_barrier_rounds() decides from the same one - (SHADER-427 review): a barrier in a tree that falls back to the dispatch loop isn't at a structured top level.""" - tree = cfg_structure.structure(succ) if STRUCTURED else None - if tree is None: - return None, None - nesting = cfg_structure.depth(tree) - if MAX_STRUCTURED_DEPTH and nesting > MAX_STRUCTURED_DEPTH: - return None, nesting # too deep to validate cheaply: use the flat form - return tree, nesting - - -def needs_barrier_rounds(g, blocks, succ): - """SHADER-91: whether a native wave32 compute shader has to run in barrier rounds (bar_scheduler). On RDNA every - s_barrier counts against the same workgroup barrier, so waves on different paths meet at different s_barrier - sites. SPIR-V requires an OpControlBarrier to be reached by the whole workgroup in uniform control flow, and an - Intel GPU hangs (device lost) when it isn't (cs_barrier_divergent.asm). A barrier is only certain to be - uniform in a block at the top level of the structured tree, which every invocation runs; one under a guard - or in a loop, or anywhere in the dispatch loop, may be reached by some waves and not others.""" - if g.stage != "cs" or g.emulate or g.wave64: - return False # emulated: already rounds; native wave64 cs and ms run on AMD only - with_barrier = set() - for n, blk in enumerate(blocks): - for ins in blk: - op = base_op(ins["op"]) - if op == "s_endpgm" or op in BRANCHES: - break - if op == "s_barrier": - with_barrier.add(n) - break - if not with_barrier: - return False - tree, _ = capped_tree(succ) # the tree assemble() emits: over MAX_STRUCTURED_DEPTH it's the dispatch loop - top = {it[1] for it in tree if it[0] == "block"} if tree is not None else set() - return not with_barrier <= top - -def interp_copy_sources(insns): - """SHADER-177: the VGPRs a v_interp may name as its I/J barycentric source besides v0/v1, as - {vgpr: (root coordinate v0/v1 the copy chain carries, program-order index of the defining instruction)}. - A register qualifies when its single write in the whole shader is one plain v_mov_b32 from v0/v1 — which - must itself be unwritten up to that point: a copy of an already-overwritten v0/v1 carries a computed value, - not the pair, while a write after the copy is fine (the copy saved the value) — or from another - qualifying register defined earlier (compilers copy the pair out of v0/v1; the corpus has one - shader that reads its J through such a copy). One definition means every read that is not undefined - garbage reads the copied barycentric - value, whatever the control flow. Every VGPR destination counts as a write (memory stores only - read their data operand; tfe's extra status VGPR is one too).""" - writes = {} - for i, ins in enumerate(insns): - ins["seq"] = i # program order: also unique without encoding comments (test fixtures share a pc) - a = ins["args"] - if not (a and a[0].get("k") == "vgpr") or base_op(ins["op"]).startswith( - ("buffer_store", "tbuffer_store", "scratch_store", "global_store", "image_store", "ds_write")): - continue - for r in vgpr_dest_registers(ins, extra=int("tfe" in ins["mods"])): - writes.setdefault(r, []).append(ins) - copies = {} - grew = True - while grew: # copy chains resolve over passes: v15 = v14 after v14 = v1 - grew = False - for r, ws in writes.items(): - if r in copies or len(ws) != 1: - continue - ins = ws[0] - a = ins["args"] - s = a[1] if len(a) > 1 else None - plain = (base_op(ins["op"]) == "v_mov_b32" and not ins["mods"] and a[0].get("n", 1) == 1 - and not a[0].get("sdwa_dst") - and s is not None and s.get("k") == "vgpr" and s.get("n", 1) == 1 - and not s.get("neg") and not s.get("abs") and not s.get("sdwa_sel")) - if plain and ((s["r"] in (0, 1) and not any(w["seq"] < ins["seq"] for w in writes.get(s["r"], ()))) or - (s["r"] in copies and copies[s["r"]][1] < ins["seq"])): - copies[r] = (s["r"] if s["r"] in (0, 1) else copies[s["r"]][0], ins["seq"]) - grew = True - return copies - -def x_spill(g, parts): - """Emulated wave64 and barrier rounds: the segments of one block run in different rounds, i.e. in different - cases of the scheduler's switch and different loop iterations, so an SSA value defined in one and used in a - later one can't be referenced directly. It goes through a Function variable: stored at the end of the segment that - defines it and loaded, under a new id, at the top of each later segment that uses it.""" - defs, out = {}, [] - for k, part in enumerate(parts): - used = [] - for line in part: - for ref in _ID_REF.findall(line): - if ref in defs and ref not in used: - used.append(ref) - loads, rename = [], {} - for ref in used: - seg, typ, var = defs[ref] - if var is None: - if typ is None or typ.startswith("%_ptr"): - mode = "barrier rounds" if g.bar_rounds else "wave64 emulation" - raise Unsupported(f"{mode}: a pointer lives across a round") - ptr = {"%uint": "%_ptr_Function_uint", "%bool": "%_ptr_Function_bool"}.get(typ) - if ptr is None: - ptr = g.x_ptr_types.setdefault(typ, f"%_ptr_Function_x_{typ[1:]}") - var = f"%xs_{ref[1:]}" - g.x_spills.append((var, ptr)) - out[seg].append(f"OpStore {var} {ref}") - defs[ref] = (seg, typ, var) - new = f"{ref}_r{k}" - loads.append(f"{new} = OpLoad {typ} {var}") - rename[ref] = new - body = [_ID_REF.sub(lambda t: rename.get(t.group(0), t.group(0)), l) for l in part] if rename else list(part) - out.append(loads + body) - for line in part: - m = _DEF.match(line) - if m and m.group(2) != "OpLabel": - defs[m.group(1)] = (k, m.group(3), None) - return out - - -def x_prologue(gen, threads): - """Emulated wave64 prologue: %pc/%done declarations, invocation/lane/wave indices, and %x_buf zeroing + barrier. - Shared by x_scheduler (round loop) and structured wave64 emulation (inline_all / structured_hybrid).""" - c = lambda v: gen.consts[v & 0xFFFFFFFF] # noqa: E731 - _, x_mask, _, x_sink = gen.x_sizes() - sx, sy, _ = (gen.cs or gen.ms)["size"] - L = ["%pc = OpVariable %_ptr_Function_uint Function %c0", - "%done = OpVariable %_ptr_Function_bool Function %false"] - # This invocation's place: index in the workgroup, lane and wave (the same split as Gen.wave_lane). - if gen.stage == "ms": - L += ["%x_li = OpLoad %uint %local_index"] - else: - L += ["%x_lid = OpLoad %v3uint %local_id", "%x_lx = OpCompositeExtract %uint %x_lid 0", - "%x_ly = OpCompositeExtract %uint %x_lid 1", "%x_lz = OpCompositeExtract %uint %x_lid 2", - f"%x_ly2 = OpIMul %uint %x_ly {c(sx)}", f"%x_lz2 = OpIMul %uint %x_lz {c(sx * sy)}", - "%x_lxy = OpIAdd %uint %x_lx %x_ly2", "%x_li = OpIAdd %uint %x_lxy %x_lz2"] - L += [f"%x_lane = OpBitwiseAnd %uint %x_li {c(63)}", f"%x_wave = OpShiftRightLogical %uint %x_li {c(6)}", - f"%x_wbase = OpBitwiseAnd %uint %x_li {c(0xFFFFFFC0)}"] - # Workgroup memory starts undefined: zero the mask and schedule words, every invocation a share of them. - zero = x_sink - x_mask - for k in range(-(-zero // threads)): - L += [f"%x_z{k} = OpIAdd %uint %x_li {c(k * threads)}", - f"%x_zm{k} = OpExtInst %uint %glsl UMin %x_z{k} {c(zero - 1)}", - f"%x_zi{k} = OpIAdd %uint %x_zm{k} {c(x_mask)}", - f"%x_zp{k} = OpAccessChain %_ptr_WG_uint_x %x_buf %x_zi{k}", f"OpStore %x_zp{k} {c(0)}"] - # A partial last wave: its missing lanes never write their data slots. They read as 0, as a lane that is - # off does for ds_bpermute (and v_readlane of a lane that doesn't exist has no defined value anyway). - missing = gen.x_lanes - threads - for k in range(-(-missing // threads) if missing else 0): - for par, base in ((0, threads), (1, gen.x_lanes + threads)): - L += [f"%x_y{k}_{par} = OpIAdd %uint %x_li {c(k * threads)}", - f"%x_ym{k}_{par} = OpExtInst %uint %glsl UMin %x_y{k}_{par} {c(missing - 1)}", - f"%x_yi{k}_{par} = OpIAdd %uint %x_ym{k}_{par} {c(base)}", - f"%x_yp{k}_{par} = OpAccessChain %_ptr_WG_uint_x %x_buf %x_yi{k}_{par}", - f"OpStore %x_yp{k}_{par} {c(0)}"] - L.append(f"OpControlBarrier {c(2)} {c(2)} {c(0x948)}") - return L - - -def x_round_loop_head(gen, seg_ids): - """Emulated wave64 round loop head switching over `seg_ids` (shared by x_scheduler and tail_scheduler).""" - c = lambda v: gen.consts[v & 0xFFFFFFFF] # noqa: E731 - x_waves, x_mask, x_sched, x_sink = gen.x_sizes() - return ["OpBranch %loop_head", "%loop_head = OpLabel", "OpLoopMerge %loop_exit %loop_cont None", - "OpBranch %x_round", "%x_round = OpLabel", - "%x_itv = OpLoad %uint %x_it", f"%x_s = OpUMod %uint %x_itv {c(3)}", - # Free the slot of round + 1 for its writers. Its readers ran before the last barrier (round - 2 wrote - # it, round - 1 read it); its writers come after the next one. Lane 0 of each wave clears the wave's - # mask words, invocation 0 the counts; the others store to the sink word. - f"%x_n1 = OpIAdd %uint %x_itv {c(1)}", f"%x_sn = OpUMod %uint %x_n1 {c(3)}", - f"%x_m0 = OpIMul %uint %x_sn {c(x_waves)}", "%x_m1 = OpIAdd %uint %x_m0 %x_wave", - f"%x_m2 = OpIMul %uint %x_m1 {c(2)}", f"%x_m3 = OpIAdd %uint %x_m2 {c(x_mask)}", - f"%x_m4 = OpIAdd %uint %x_m3 {c(1)}", f"%x_ml = OpIEqual %bool %x_lane {c(0)}", - f"%x_m5 = OpSelect %uint %x_ml %x_m3 {c(x_sink)}", f"%x_m6 = OpSelect %uint %x_ml %x_m4 {c(x_sink)}", - "%x_mp5 = OpAccessChain %_ptr_WG_uint_x %x_buf %x_m5", f"OpStore %x_mp5 {c(0)}", - "%x_mp6 = OpAccessChain %_ptr_WG_uint_x %x_buf %x_m6", f"OpStore %x_mp6 {c(0)}", - f"%x_q0 = OpIMul %uint %x_sn {c(2)}", f"%x_q1 = OpIAdd %uint %x_q0 {c(x_sched)}", - f"%x_q2 = OpIAdd %uint %x_q1 {c(1)}", f"%x_ql = OpIEqual %bool %x_li {c(0)}", - f"%x_q3 = OpSelect %uint %x_ql %x_q1 {c(x_sink)}", f"%x_q4 = OpSelect %uint %x_ql %x_q2 {c(x_sink)}", - "%x_qp3 = OpAccessChain %_ptr_WG_uint_x %x_buf %x_q3", f"OpStore %x_qp3 {c(0)}", - "%x_qp4 = OpAccessChain %_ptr_WG_uint_x %x_buf %x_q4", f"OpStore %x_qp4 {c(0)}", - "%x_d = OpLoad %bool %done", "%x_b = OpLoad %bool %x_bar", "%x_nd = OpLogicalNot %bool %x_d", - "%x_nb = OpLogicalNot %bool %x_b", "%x_run = OpLogicalAnd %bool %x_nd %x_nb", - "OpSelectionMerge %x_ran None", "OpBranchConditional %x_run %dispatch %x_ran", - # A segment that only reads a vote and picks the next block sets %x_chain: that block runs in the same - # round (its code before the vote was in an earlier one, and it starts a fresh segment). - "%dispatch = OpLabel", "OpBranch %x_ch_head", "%x_ch_head = OpLabel", - "OpLoopMerge %x_ch_merge %x_ch_cont None", "OpBranch %x_ch_body", "%x_ch_body = OpLabel", - "%pcv = OpLoad %uint %pc", "OpSelectionMerge %sw_merge None", - "OpSwitch %pcv %sw_default " + " ".join(f"{i} %blk{i}" for i in seg_ids)] - - -def x_mini_scheduler(gen, midx, seg_ids): - """Local multi-wave round loop covering only one wave-divergent region `seg_ids` (no s_barrier / s_endpgm).""" - c = lambda v: gen.consts[v & 0xFFFFFFFF] # noqa: E731 - x_waves, x_mask, x_sched, x_sink = gen.x_sizes() - p = f"%xm{midx}" - return ["OpStore %x_ldone %false", - f"OpBranch {p}_head", f"{p}_head = OpLabel", f"OpLoopMerge {p}_exit {p}_cont None", - f"OpBranch {p}_round", f"{p}_round = OpLabel", - f"{p}_itv = OpLoad %uint %x_it", f"{p}_s = OpUMod %uint {p}_itv {c(3)}", - f"{p}_n1 = OpIAdd %uint {p}_itv {c(1)}", f"{p}_sn = OpUMod %uint {p}_n1 {c(3)}", - f"{p}_m0 = OpIMul %uint {p}_sn {c(x_waves)}", f"{p}_m1 = OpIAdd %uint {p}_m0 %x_wave", - f"{p}_m2 = OpIMul %uint {p}_m1 {c(2)}", f"{p}_m3 = OpIAdd %uint {p}_m2 {c(x_mask)}", - f"{p}_m4 = OpIAdd %uint {p}_m3 {c(1)}", f"{p}_ml = OpIEqual %bool %x_lane {c(0)}", - f"{p}_m5 = OpSelect %uint {p}_ml {p}_m3 {c(x_sink)}", - f"{p}_m6 = OpSelect %uint {p}_ml {p}_m4 {c(x_sink)}", - f"{p}_mp5 = OpAccessChain %_ptr_WG_uint_x %x_buf {p}_m5", f"OpStore {p}_mp5 {c(0)}", - f"{p}_mp6 = OpAccessChain %_ptr_WG_uint_x %x_buf {p}_m6", f"OpStore {p}_mp6 {c(0)}", - f"{p}_q0 = OpIMul %uint {p}_sn {c(2)}", f"{p}_q1 = OpIAdd %uint {p}_q0 {c(x_sched)}", - f"{p}_q2 = OpIAdd %uint {p}_q1 {c(1)}", f"{p}_ql = OpIEqual %bool %x_li {c(0)}", - f"{p}_q3 = OpSelect %uint {p}_ql {p}_q1 {c(x_sink)}", - f"{p}_q4 = OpSelect %uint {p}_ql {p}_q2 {c(x_sink)}", - f"{p}_qp3 = OpAccessChain %_ptr_WG_uint_x %x_buf {p}_q3", f"OpStore {p}_qp3 {c(0)}", - f"{p}_qp4 = OpAccessChain %_ptr_WG_uint_x %x_buf {p}_q4", f"OpStore {p}_qp4 {c(0)}", - f"{p}_d = OpLoad %bool %x_ldone", f"{p}_run = OpLogicalNot %bool {p}_d", - f"OpSelectionMerge {p}_ran None", f"OpBranchConditional {p}_run {p}_dispatch {p}_ran", - f"{p}_dispatch = OpLabel", f"OpBranch {p}_ch_head", f"{p}_ch_head = OpLabel", - f"OpLoopMerge {p}_ch_merge {p}_ch_cont None", f"OpBranch {p}_ch_body", f"{p}_ch_body = OpLabel", - f"{p}_pcv = OpLoad %uint %pc", f"OpSelectionMerge {p}_sw_merge None", - f"OpSwitch {p}_pcv {p}_default " + " ".join(f"{i} %blk{i}" for i in seg_ids)] - - -def x_mini_scheduler_tail(gen, midx): - """End of a local multi-wave mini-scheduler round: exits when every wave has left the region.""" - c = lambda v: gen.consts[v & 0xFFFFFFFF] # noqa: E731 - _, _, x_sched, _ = gen.x_sizes() - p = f"%xm{midx}" - return [f"{p}_default = OpLabel", "OpStore %x_ldone %true", f"OpBranch {p}_sw_merge", - f"{p}_sw_merge = OpLabel", f"OpBranch {p}_ch_cont", f"{p}_ch_cont = OpLabel", - f"{p}_chv = OpLoad %bool %x_chain", "OpStore %x_chain %false", - f"OpBranchConditional {p}_chv {p}_ch_head {p}_ch_merge", f"{p}_ch_merge = OpLabel", - f"OpBranch {p}_ran", f"{p}_ran = OpLabel", - f"{p}_d2 = OpLoad %bool %x_ldone", f"{p}_nd2 = OpLogicalNot %bool {p}_d2", - f"{p}_c0 = OpSelect %uint {p}_nd2 {c(1)} {c(0)}", - f"{p}_s0 = OpIMul %uint {p}_s {c(2)}", f"{p}_s1 = OpIAdd %uint {p}_s0 {c(x_sched)}", - f"{p}_p0 = OpAccessChain %_ptr_WG_uint_x %x_buf {p}_s1", - f"{p}_a0 = OpAtomicIAdd %uint {p}_p0 {c(2)} {c(0)} {p}_c0", - f"OpBranch {p}_cont", f"{p}_cont = OpLabel", - f"OpControlBarrier {c(2)} {c(2)} {c(0x948)}", - f"{p}_r0 = OpLoad %uint {p}_p0", - f"{p}_it1 = OpIAdd %uint {p}_itv {c(1)}", f"OpStore %x_it {p}_it1", - f"{p}_fin = OpIEqual %bool {p}_r0 {c(0)}", - f"OpBranchConditional {p}_fin {p}_exit {p}_head", - f"{p}_exit = OpLabel"] - - -def x_scheduler(gen, threads): - """Emulated wave64: the head of the round loop (see Gen.x_round), up to the switch over %pc. The first two - lines are the Function variables %pc and %done, as for the dispatch loop. - - Every invocation runs every round, so the loop and the barrier at its end are in uniform control flow. In a - round an invocation runs one segment unless it is done or waits at s_barrier. After the segment it adds - itself to the round's counts (not done; neither done nor waiting); after the barrier everyone reads the same - counts: no lane left ends the loop, and no lane left that isn't waiting releases the s_barrier.""" - seg_ids = sorted([i for i, b in enumerate(gen.blocks) if b is not None] + list(gen.x_segs)) - return x_prologue(gen, threads) + x_round_loop_head(gen, seg_ids) - - -def x_scheduler_tail(gen): - """Emulated wave64: the end of a round, after the switch (see x_scheduler).""" - c = lambda v: gen.consts[v & 0xFFFFFFFF] # noqa: E731 - _, _, x_sched, _ = gen.x_sizes() - return ["%sw_default = OpLabel", "OpStore %done %true", "OpBranch %sw_merge", - "%sw_merge = OpLabel", "OpBranch %x_ch_cont", "%x_ch_cont = OpLabel", - "%x_chv = OpLoad %bool %x_chain", "OpStore %x_chain %false", - "OpBranchConditional %x_chv %x_ch_head %x_ch_merge", "%x_ch_merge = OpLabel", - "OpBranch %x_ran", "%x_ran = OpLabel", - "%x_d2 = OpLoad %bool %done", "%x_b2 = OpLoad %bool %x_bar", - "%x_nd2 = OpLogicalNot %bool %x_d2", "%x_nb2 = OpLogicalNot %bool %x_b2", - "%x_w = OpLogicalAnd %bool %x_nd2 %x_nb2", - f"%x_c0 = OpSelect %uint %x_nd2 {c(1)} {c(0)}", f"%x_c1 = OpSelect %uint %x_w {c(1)} {c(0)}", - f"%x_s0 = OpIMul %uint %x_s {c(2)}", f"%x_s1 = OpIAdd %uint %x_s0 {c(x_sched)}", - f"%x_s2 = OpIAdd %uint %x_s1 {c(1)}", - "%x_p0 = OpAccessChain %_ptr_WG_uint_x %x_buf %x_s1", - "%x_p1 = OpAccessChain %_ptr_WG_uint_x %x_buf %x_s2", - f"%x_a0 = OpAtomicIAdd %uint %x_p0 {c(2)} {c(0)} %x_c0", - f"%x_a1 = OpAtomicIAdd %uint %x_p1 {c(2)} {c(0)} %x_c1", - "OpBranch %loop_cont", "%loop_cont = OpLabel", - # Workgroup, acquire-release, workgroup + uniform + image memory: also orders the stores a round made. - f"OpControlBarrier {c(2)} {c(2)} {c(0x948)}", - "%x_r0 = OpLoad %uint %x_p0", "%x_r1 = OpLoad %uint %x_p1", - f"%x_rel = OpIEqual %bool %x_r1 {c(0)}", "%x_b3 = OpLoad %bool %x_bar", - "%x_nrel = OpLogicalNot %bool %x_rel", "%x_b4 = OpLogicalAnd %bool %x_b3 %x_nrel", - "OpStore %x_bar %x_b4", f"%x_it1 = OpIAdd %uint %x_itv {c(1)}", "OpStore %x_it %x_it1", - f"%x_fin = OpIEqual %bool %x_r0 {c(0)}", "OpBranchConditional %x_fin %loop_exit %loop_head", - "%loop_exit = OpLabel"] - - -def bar_scheduler(gen): - """Barrier rounds (SHADER-91): a native wave32 compute shader whose s_barrier isn't in uniform control flow - (needs_barrier_rounds). The emulated wave64 loop without its cross-lane part: s_barrier ends a segment, and - the code after it is a continuation segment (x_split). In a round each invocation that isn't done runs its - blocks, through the switch over %pc, until it reaches an s_barrier or the end; then the whole workgroup meets - at one OpControlBarrier, at the end of the round loop, in uniform control flow. After the inner loop every - invocation is done or waits, so the barrier always releases the waiting ones, and a wave that has ended - doesn't hold the others back (RDNA's rule). Cross-lane operations stay subgroup operations: a wave runs one - segment at a time, as in the dispatch loop. The round's count of invocations not done ends the loop at 0. - - %x_buf holds 3 counts, by round mod 3: round r adds to its own slot before the barrier and reads it after, - and invocation 0 clears the slot of round r + 1, last read in round r - 2 (before the barrier of r - 1). - With a large LDS (bar_counts_in_lds, SHADER-579) there is no %x_buf: the count borrows LDS word 0 between - rounds, when no invocation runs shader code (see bar_scheduler_tail), and starts cleared in every round. - The first two lines are the Function variables %pc and %done, as for the dispatch loop.""" - c = lambda v: gen.consts[v & 0xFFFFFFFF] # noqa: E731 - sx, sy, _ = gen.cs["size"] - in_lds = gen.bar_counts_in_lds() - return ["%pc = OpVariable %_ptr_Function_uint Function %c0", - "%done = OpVariable %_ptr_Function_bool Function %false", - "%xb_lid = OpLoad %v3uint %local_id", "%xb_lx = OpCompositeExtract %uint %xb_lid 0", - "%xb_ly = OpCompositeExtract %uint %xb_lid 1", "%xb_lz = OpCompositeExtract %uint %xb_lid 2", - f"%xb_ly2 = OpIMul %uint %xb_ly {c(sx)}", f"%xb_lz2 = OpIMul %uint %xb_lz {c(sx * sy)}", - "%xb_lxy = OpIAdd %uint %xb_lx %xb_ly2", "%xb_li = OpIAdd %uint %xb_lxy %xb_lz2", - f"%xb_first = OpIEqual %bool %xb_li {c(0)}"] + ([] if in_lds else [ - # Workgroup memory starts undefined: invocation 0 clears round 0's count before the first round. - "OpSelectionMerge %xb_z_end None", "OpBranchConditional %xb_first %xb_z %xb_z_end", "%xb_z = OpLabel", - f"%xb_zp = OpAccessChain %_ptr_WG_uint_x %x_buf {c(0)}", f"OpStore %xb_zp {c(0)}", - "OpBranch %xb_z_end", "%xb_z_end = OpLabel", - f"OpControlBarrier {c(2)} {c(2)} {c(0x108)}"]) + [ - "OpBranch %loop_head", "%loop_head = OpLabel", "OpLoopMerge %loop_exit %loop_cont None", - "OpBranch %xb_round", "%xb_round = OpLabel", "%xb_itv = OpLoad %uint %x_it"] + ([] if in_lds else [ - f"%xb_s = OpUMod %uint %xb_itv {c(3)}", - f"%xb_n1 = OpIAdd %uint %xb_itv {c(1)}", f"%xb_sn = OpUMod %uint %xb_n1 {c(3)}", - "OpSelectionMerge %xb_r_end None", "OpBranchConditional %xb_first %xb_r %xb_r_end", "%xb_r = OpLabel", - "%xb_rp = OpAccessChain %_ptr_WG_uint_x %x_buf %xb_sn", f"OpStore %xb_rp {c(0)}", - "OpBranch %xb_r_end", "%xb_r_end = OpLabel"]) + [ - "%xb_d = OpLoad %bool %done", - "OpSelectionMerge %xb_ran None", "OpBranchConditional %xb_d %xb_ran %xb_run", "%xb_run = OpLabel", - # The invocation's blocks, until an s_barrier (%x_bar) or the end (%done). - "OpBranch %xb_in_head", "%xb_in_head = OpLabel", "OpLoopMerge %xb_in_merge %xb_in_cont None", - "OpBranch %dispatch", "%dispatch = OpLabel", - "%pcv = OpLoad %uint %pc", "OpSelectionMerge %sw_merge None", - "OpSwitch %pcv %sw_default " + " ".join(f"{i} %blk{i}" for i in - sorted(list(range(len(gen.blocks))) + list(gen.x_segs)))] - - -def bar_scheduler_tail(gen): - """Barrier rounds: the end of a round, after the switch (see bar_scheduler). - - SHADER-579, the count in LDS (bar_counts_in_lds): after s_barrier's own barrier (A) every invocation is done or - waits, so no shader code touches LDS until the next round. Invocation 0 saves LDS word 0 in a Function variable - and clears it; barrier B; every invocation not done adds 1; barrier C; all read the count; barrier D; - invocation 0 puts the saved word back; barrier E, before the next round's code. The shader sees its LDS - unchanged, and B to E only add workgroup barriers at a point where the whole workgroup already waits.""" - c = lambda v: gen.consts[v & 0xFFFFFFFF] # noqa: E731 - bar = f"OpControlBarrier {c(2)} {c(2)} {c(0x108)}" - head = ["%sw_default = OpLabel", "OpStore %done %true", "OpBranch %sw_merge", - "%sw_merge = OpLabel", "OpBranch %xb_in_cont", "%xb_in_cont = OpLabel", - "%xb_d1 = OpLoad %bool %done", "%xb_b1 = OpLoad %bool %x_bar", - "%xb_stop = OpLogicalOr %bool %xb_d1 %xb_b1", - "OpBranchConditional %xb_stop %xb_in_merge %xb_in_head", "%xb_in_merge = OpLabel"] - if gen.bar_counts_in_lds(): - return head + [ - "OpBranch %xb_ran", "%xb_ran = OpLabel", - bar, # A: s_barrier's own barrier - f"%xb_wp = OpAccessChain %_ptr_WG_uint %lds {c(0)}", - "OpSelectionMerge %xb_sv_end None", "OpBranchConditional %xb_first %xb_sv %xb_sv_end", - "%xb_sv = OpLabel", "%xb_old = OpLoad %uint %xb_wp", "OpStore %xb_save %xb_old", - f"OpStore %xb_wp {c(0)}", "OpBranch %xb_sv_end", "%xb_sv_end = OpLabel", - bar, # B: the word is cleared - "%xb_d2 = OpLoad %bool %done", - "OpSelectionMerge %xb_c_end None", "OpBranchConditional %xb_d2 %xb_c_end %xb_c", "%xb_c = OpLabel", - f"%xb_ca = OpAtomicIAdd %uint %xb_wp {c(2)} {c(0)} {c(1)}", - "OpBranch %xb_c_end", "%xb_c_end = OpLabel", - bar, # C: every count is in - "%xb_left = OpLoad %uint %xb_wp", - bar, # D: every invocation has read it - "OpSelectionMerge %xb_rs_end None", "OpBranchConditional %xb_first %xb_rs %xb_rs_end", - "%xb_rs = OpLabel", "%xb_old2 = OpLoad %uint %xb_save", "OpStore %xb_wp %xb_old2", - "OpBranch %xb_rs_end", "%xb_rs_end = OpLabel", - "OpBranch %loop_cont", "%loop_cont = OpLabel", - bar, # E: the shader's word is back - "OpStore %x_bar %false", - f"%xb_it1 = OpIAdd %uint %xb_itv {c(1)}", "OpStore %x_it %xb_it1", - f"%xb_fin = OpIEqual %bool %xb_left {c(0)}", "OpBranchConditional %xb_fin %loop_exit %loop_head", - "%loop_exit = OpLabel"] - return head + [ - # Not done: count this invocation in the round's slot. - "%xb_d2 = OpLoad %bool %done", - "OpSelectionMerge %xb_c_end None", "OpBranchConditional %xb_d2 %xb_c_end %xb_c", "%xb_c = OpLabel", - "%xb_cp = OpAccessChain %_ptr_WG_uint_x %x_buf %xb_s", - f"%xb_ca = OpAtomicIAdd %uint %xb_cp {c(2)} {c(0)} {c(1)}", - "OpBranch %xb_c_end", "%xb_c_end = OpLabel", - "OpBranch %xb_ran", "%xb_ran = OpLabel", - "OpBranch %loop_cont", "%loop_cont = OpLabel", - # s_barrier's own barrier (workgroup, acquire-release, workgroup memory), now in uniform control flow; - # it also orders the count, read below. - f"OpControlBarrier {c(2)} {c(2)} {c(0x108)}", - "%xb_lp = OpAccessChain %_ptr_WG_uint_x %x_buf %xb_s", "%xb_left = OpLoad %uint %xb_lp", - "OpStore %x_bar %false", - f"%xb_it1 = OpIAdd %uint %xb_itv {c(1)}", "OpStore %x_it %xb_it1", - f"%xb_fin = OpIEqual %bool %xb_left {c(0)}", "OpBranchConditional %xb_fin %loop_exit %loop_head", - "%loop_exit = OpLabel"] - - -BRANCHES = {"s_branch", "s_cbranch_scc0", "s_cbranch_scc1", "s_cbranch_vccz", "s_cbranch_vccnz", - "s_cbranch_execz", "s_cbranch_execnz"} - - -def branch_condition(g, op): - """Boolean SPIR-V id: whether the branch is taken for this lane.""" - if op in ("s_cbranch_scc0", "s_cbranch_scc1"): - s = g.tmp() - g.emit(f"{s} = OpLoad %uint %scc") - b = g.tmp() - g.emit(f"{b} = {'OpIEqual' if op.endswith('0') else 'OpINotEqual'} %bool {s} {g.cu(0)}") - return b - # VCC and EXEC are wave-wide registers: the hardware branch is taken (or not) by the whole wave. With one - # invocation per lane, each lane holds only its own bit, so the condition is reduced across the subgroup - # (= the wave). Deciding per lane would let lanes skip scalar instructions the wave executes, leaving their - # SGPRs stale, and would break cross-lane ops and barriers inside the block. - if op in ("s_cbranch_vccz", "s_cbranch_vccnz"): - s = g.tmp() - g.emit(f"{s} = OpLoad %uint %vcc") - lane = g.tmp() - g.emit(f"{lane} = OpINotEqual %bool {s} {g.cu(0)}") - if g.wave64 and "vcc" not in g.cur_masks: - # VCC holds data, not a lane mask: VCCZ/VCCNZ test all 64 bits, so the high word matters too. - # Each invocation holds the same data word, and the subgroup vote below reduces the bool once. - # A VCC certified as a lane mask keeps one bit per lane in %vcc; %vcc_hi is not the other half - # of the vote there, because that vote already covers both halves of the wave. - hi = g.tmp() - g.emit(f"{hi} = OpLoad %uint %vcc_hi") - hi_nz = g.tmp() - g.emit(f"{hi_nz} = OpINotEqual %bool {hi} {g.cu(0)}") - both = g.tmp() - g.emit(f"{both} = OpLogicalOr %bool {lane} {hi_nz}") - lane = both - else: - lane = g.active_b() - any_ = g.tmp() - g.g_vote(any_, "Any", lane) - g.uses_vote = True - if op in ("s_cbranch_vccnz", "s_cbranch_execnz"): - return any_ - b = g.tmp() - g.emit(f"{b} = OpLogicalNot %bool {any_}") - return b - - -def _sha256_file(path): - """Hex SHA-256 of a file, or None when the path is missing (fssm sidecars are optional).""" - try: - h = hashlib.sha256() - with open(path, "rb") as f: - for chunk in iter(lambda: f.read(1 << 20), b""): - h.update(chunk) - return h.hexdigest() - except OSError: - return None - - -def shader_meta(g, asm, src_path=None, fssm_path=None): - """What a runtime needs to create the pipeline for this module without inspecting it: stage, wave size, - Vulkan features/extensions it requires, descriptor bindings (set 0), push-constant size, workgroup size, - LDS bytes, mesh/geometry limits, the input/output locations, plus identity metadata (src/fssm hashes and - the full ISG1 vertex-input signature) for PSO lookup and corpus auditing.""" - caps = sorted(set(re.findall(r"OpCapability (\w+)", asm))) - exts = sorted(set(re.findall(r'OpExtension "([^"]+)"', asm))) - # Set 0 only: --pc-tail-ubo's %pc_tail is in set 1 and recorded as "pc_tail". - binds = sorted({int(b) for b in re.findall(r"OpDecorate %(?!pc_tail\b)\w+ Binding (\d+)", asm)}) - feats = {"FragmentBarycentricKHR": "fragmentShaderBarycentric", - "FragmentShaderPixelInterlockEXT": "fragmentShaderPixelInterlock", - "MeshShadingEXT": "meshShader", "Geometry": "geometryShader", "Float64": "shaderFloat64", - "Int64": "shaderInt64", "StorageImageWriteWithoutFormat": "shaderStorageImageWriteWithoutFormat", - "StorageImageReadWithoutFormat": "shaderStorageImageReadWithoutFormat", - "PhysicalStorageBufferAddresses": "bufferDeviceAddress", - "RuntimeDescriptorArray": "runtimeDescriptorArray", "ImageGatherExtended": "shaderImageGatherExtended", - "SampledImageArrayDynamicIndexing": "shaderSampledImageArrayDynamicIndexing", - "StorageImageArrayDynamicIndexing": "shaderStorageImageArrayDynamicIndexing", - "MinLod": "shaderResourceMinLod", "Image1D": "shaderImage1D? (core)", "Sampled1D": "core", - "ClipDistance": "shaderClipDistance", "CullDistance": "shaderCullDistance", - "ShaderLayer": "shaderOutputLayer", "ShaderViewportIndex": "shaderOutputViewportIndex", - "DrawParameters": "shaderDrawParameters", - } # FMAKHR: shaderFmaFloat32 / shaderFmaFloat64 (VK_KHR_shader_fma) by the width used, below - m = {"stage": g.stage, "wave64": bool(g.wave64), "control_flow": getattr(g, "control_flow", "straight line"), - # How fused multiply-adds were emitted. --fma khr is already implied by the FMAKHR capability, - # but --fma exact has no capability to distinguish it from the default GLSL Fma (TEST-1147). - "fma": g.fma_mode, - "capabilities": caps, "extensions": exts, - "features": sorted({feats[c] for c in caps if c in feats and not feats[c].startswith(("core", "shaderImage1D"))} | - {{"subgroup": "shaderSubgroupClock", "device": "shaderDeviceClock"}[k] - for k in getattr(g, "uses_clock", ())} | - {f for f, used in (("shaderFmaFloat32", getattr(g, "uses_fma_khr32", False)), - ("shaderFmaFloat64", getattr(g, "uses_fma_khr64", False))) if used}), - "bindings": binds, "push_constant_bytes": 4 * USER_SGPRS + 16, - "subgroup_size": 64 if g.wave64 else 32, - # Which stages can ask for a 64-wide subgroup is the driver's requiredSubgroupSizeStages, not a fixed rule: - # the AMD Windows driver (FRAGMENT | COMPUTE | TASK | MESH) and Mesa RADV on GFX10+ (COMPUTE | FRAGMENT | - # task/mesh) allow a wave64 PS to request 64, so it is exact there; NVIDIA has no 64 at all, and no driver - # lists VERTEX or GEOMETRY. The runtime decides per device (runtime/src/subgroup_size.h) from `wave64`, - # `subgroup_size` and `wave64_exchange`. This field stays true for VS/PS/GS wave64 (consumers rely on it): - # it says the shader has no cross-half exchange, so it is per-subgroup, not that it must run 2x32. - "wave64_emulated": bool(g.wave64 and (g.stage in ("vs", "ps", "gs") or g.emulate))} - if g.w64g: - # SHADER-10: partition invariance on 32-wide subgroups. A and B are exact there (B: aggregated atomics up to - # the order of the slots), C is not; the reasons name the construct (docs/design.md, Wave64 graphics). - m["wave64_graphics"] = g.w64g["tier"] - if g.w64g["reasons"]: - m["wave64_graphics_reasons"] = g.w64g["reasons"] - if g.w64g["idioms"]: - m["wave64_graphics_idioms"] = g.w64g["idioms"] - if g.emulate: - # Exact on any subgroup size: no subgroup operation, cross-lane data in %x_buf (workgroup memory). - m["wave64_exchange"] = "workgroup" - m["subgroup_size"] = None - if "Offset " in asm and re.search(r"OpImageSample\w+ [^\n]*Offset", asm): - m["needs_maintenance8"] = True - if "SignedZeroInfNanPreserve" in caps: - # Properties, not features: VkPhysicalDeviceFloatControlsProperties members the device must report true, - # one per width the module declares SignedZeroInfNanPreserve for (32 always, 64 with Float64; SHADER-597). - # DenormPreserve 16 comes after them: the driver may otherwise flush an f16 denormal (SHADER-526). - widths = sorted({int(w) for w in re.findall(r"OpExecutionMode %main SignedZeroInfNanPreserve (\d+)", asm)}) - m["float_controls"] = [f"shaderSignedZeroInfNanPreserveFloat{w}" for w in widths] - if "DenormPreserve" in caps: - m["float_controls"].append("shaderDenormPreserveFloat16") - if g.uses_codebase: - m["uses_code_base"] = True - if g.cs: - m["local_size"] = list(g.cs["size"]) - m["user_sgprs"] = g.cs["user"] - if getattr(g, "msc_layout", None): - # --mesh-compute: dispatch it as compute (same grid), then draw the slots with tools/mesh_compute_vs.py. - lay = dict(g.msc_layout) - lay["params"] = {str(k): v for k, v in lay["params"].items()} - m["mesh_compute"] = lay - m["push_constant_bytes"] = lay["push_constant_bytes"] - if PC_TAIL_UBO: - # --pc-tail-ubo: s0..s31 alone in push constants; the tail, if the shader reads it, in a uniform block. - m["push_constant_bytes"] = 4 * USER_SGPRS - if g.uses_pc_tail: - m["pc_tail"] = {"set": PC_TAIL_SET, "binding": PC_TAIL_BINDING, - "bytes": 24 if getattr(g, "msc_layout", None) else 16} - if g.ms: - m["local_size"] = list(g.ms["size"]) - m["max_vertices"], m["max_primitives"] = g.ms["maxv"], g.ms["maxp"] - m["params"] = sorted(g.ms_params) - if g.gs: - m["max_vertices"] = g.gs["maxv"] - m["gs_inputs"] = [r for r, _ in g.gs["in"]] - m["gs_outputs"] = [r for r, _ in g.gs["out"]] - m["gs_input_locations"] = sorted(r for r, sv in g.gs["in"] if sv != 1) - m["gs_output_locations"] = sorted(r for r, sv in g.gs["out"] if sv != 1) - # Every Workgroup byte of a compute shader (LDS + %x_buf of the emulation or the barrier rounds; SHADER-309): the - # runtime compares it with the device's maxComputeSharedMemorySize. A mesh shader also has its 4-byte %ms_counts. - lds = (4 * g.lds_dwords if g.uses_lds else 0) + (g.x_buf_bytes() if g.cs or g.emulate else 0) + (4 if g.ms else 0) - if lds: - m["lds_bytes"] = lds - if g.vertex_inputs: - m["vertex_inputs"] = [{"location": r, "type": {1: "uint", 2: "sint"}.get(t, "float")} for r, t in g.vertex_inputs] - if getattr(g, "vertex_signature", None): - m["vertex_input_signature"] = list(g.vertex_signature) - if getattr(g, "dynamic_format", False): - # A runtime V# FORMAT means codes outside FORMATS decode to 0; flag for atlas coverage. - m["dynamic_format"] = True - if getattr(g, "fixed_format_codes", None): - m["fixed_format_codes"] = sorted(g.fixed_format_codes) - if src_path: - src_hash = _sha256_file(src_path) - if src_hash: - m["src_sha256"] = src_hash - if fssm_path: - fssm_hash = _sha256_file(fssm_path) - if fssm_hash: - m["fssm_sha256"] = fssm_hash - if g.frag_inputs: - m["ps_system_inputs"] = sorted({str(c) for c in g.frag_inputs.values()}) - if getattr(g, "pixel_interpolants", None): - # FSSM pixel-input table the PS input path used: interpolant count and 16-bit positions by table order. - count, fp16 = g.pixel_interpolants - m["ps_interpolants"] = count - m["ps_fp16_interpolants"] = [n for n in range(count) if (fp16 >> n) & 1] - # Table positions whose read method is v_interp_mov (flags bit 0): the inputs declared Flat. - m["ps_flat_interpolants"] = getattr(g, "pixel_flat", []) - outs = sorted(int("".join(ch for ch in t if ch.isdigit()) or 0) for t in g.outputs.values() if not t.startswith("pos")) - if outs: - m["outputs"] = outs - if g.stage == "vs" and g.uses_clip: - m["clip_distance_count"] = g.clip_count - if g.stage == "vs" and g.uses_cull: - m["cull_distance_count"] = g.cull_count - if g.writes_depth: - m["writes_depth"] = True - if g.inputs: - m["inputs"] = sorted(g.inputs.values()) - if getattr(g, "bary_location", None) is not None: - # --bary-fallback: the raw barycentrics are a perspective-interpolated vec3 at this location; the stage - # before the PS must write (1,0,0), (0,1,0), (0,0,1) at the triangle's vertices (see BARY_FALLBACK). - m["bary_fallback_input"] = {"location": g.bary_location} - if F16_HALVES and g.stage in ("vs", "ms", "ps"): - # --f16-interp-fallback: PS = the attributes whose f16 reads take decoded halves, VS/MS = the params that - # export them; each as {n: [low-half location, high-half location]}. When a PS's canonical half slots would - # collide with its raw attributes, assign_f16_half_locations packs them into free locations <= F16_HALF_TOP - # and runtime PSO linking patches/synthesizes the producer's halves to match (SHADER-378). - if g.stage == "ms" and getattr(g, "msc_layout", None) is not None: - pairs = {n: (f16_half_location(n, 0), f16_half_location(n, 1)) - for n in sorted(g.ms_params) if f16_half_location(n, 0) > g.param_max} - else: - pairs = g.f16_half_locs - if pairs: - m["f16_halves"] = {str(n): [lo, hi] for n, (lo, hi) in sorted(pairs.items())} - if "mesh_compute" in m: # tools/mesh_compute_vs.py exports them from the slot's raw params - m["mesh_compute"] = dict(m["mesh_compute"], f16_halves=m["f16_halves"]) - if g.build_meta: - m.update(g.build_meta) - return m - - -def write_index(path, index): - """Write an index under another name and rename it into place, so a run stopped part-way never leaves half of - one: make_game.py takes these files as proof that a shard, or the whole translation, finished.""" - tmp = path + ".tmp" # must not end in .json: --merge globs index.part*.json - with open(tmp, "w", encoding="utf-8", newline="\n") as f: - _json.dump(index, f, indent=0, sort_keys=True) - f.flush() - os.fsync(f.fileno()) # on disk before the rename, or a power cut could leave the name with no data - replace_retry(tmp, path) # a scanner or sync client on Windows may hold the new file open for a moment - - -class ShardSetError(Exception): - """The index parts on disk are not one complete shard set: merging them would publish a partial index.""" - - -SHARD_MARKER = "shard{index}.json" - - -def _read_shard_markers(out): - """{index: count} from the shard.json markers a --shard run writes beside its index.part.json.""" - import glob as _gl, json as _js - markers = {} - for path in sorted(_gl.glob(os.path.join(out, "shard*.json"))): - m = re.fullmatch(r"shard(\d+)\.json", os.path.basename(path)) - if not m: # make_game.py's shards.json plan is not a marker - continue - try: - with open(path, encoding="utf-8") as f: - doc = _js.load(f) - except (OSError, ValueError) as e: - raise ShardSetError(f"cannot read the shard marker {path}: {e}; delete it and run the shard again") from None - try: - index, count = int(doc["index"]), int(doc["count"]) - except (KeyError, TypeError, ValueError): - raise ShardSetError(f"{path} is not a shard marker (expected an object with \"index\" and \"count\")") from None - if index != int(m.group(1)): - raise ShardSetError(f"{path} is a marker for shard {index}, but its name says shard {m.group(1)}") - if index in markers and markers[index] != count: - raise ShardSetError(f"shard markers disagree on the shard count: {path}") - markers[index] = count - return markers - - -def _missing_shard_summary(indices, expected): - """Describe gaps in sorted unique indices without allocating the full missing range.""" - valid = [i for i in indices if i < expected] - missing_count = expected - len(valid) - if not missing_count: - return "" - preview, start = [], 0 - for stop in (*valid, expected): - preview.extend(range(start, min(stop, start + 16 - len(preview)))) - if len(preview) == 16: - break - start = stop + 1 - omitted = missing_count - len(preview) - return f", missing {preview}" + (f" ({omitted} more)" if omitted else "") - - -def merge_shard_parts(out): - """{shader: meta} from index.part*.json, after checking the set is complete and not empty. - - A --shard i/n run writes index.part.json and shard.json ({"index": i, "count": n}); the markers say how - many parts the set has. Parts from before the markers existed fall back to make_game.py's shards.json plan. - When neither exists the count is unknown, so the parts must at least be contiguous from 0: the merge fails - closed instead of publishing a partial index that make_game.py would take as a finished translation. A - complete set of empty parts fails closed the same way: `index.json` is the marker that says the corpus was - translated, so publishing {} claims a translation of nothing.""" - import glob as _gl, json as _js - parts = sorted(_gl.glob(os.path.join(out, "index.part*.json"))) - if not parts: - raise ShardSetError(f"no index.part*.json in {out}; run --shard i/n first, then --merge") - indices = [] - for part in parts: - m = re.search(r"index\.part(\d+)\.json$", part) - if not m: - raise ShardSetError(f"{part} is not an index.part.json file") - indices.append(int(m.group(1))) - if len(set(indices)) != len(indices): - raise ShardSetError(f"index.part*.json has two parts with the same index: {sorted(indices)}") - indices.sort() - plan_jobs = None - plan = os.path.join(out, "shards.json") - if os.path.isfile(plan): - try: - with open(plan, encoding="utf-8") as f: - doc = _js.load(f) - jobs = doc.get("jobs") if isinstance(doc, dict) else None - if type(jobs) is not int or jobs < 1: - raise ValueError("no positive integer \"jobs\"") - except (OSError, ValueError, TypeError, AttributeError) as e: - raise ShardSetError(f"cannot read the shard plan {plan}: {e}; fix or remove it before --merge") from None - plan_jobs = jobs - markers = _read_shard_markers(out) - expected = None - if markers: - counts = set(markers.values()) - if len(counts) != 1: - raise ShardSetError(f"shard markers disagree on the shard count: {sorted(counts)}") - expected = counts.pop() - if plan_jobs is not None and plan_jobs != expected: - raise ShardSetError(f"shard markers say {expected} shards but the plan says {plan_jobs}; " - "delete the stale parts or the plan and run every shard again") - elif plan_jobs is not None: - expected = plan_jobs - if expected is not None: - missing = _missing_shard_summary(indices, expected) - extra = [i for i in indices if i >= expected] - if missing or extra: - raise ShardSetError( - f"incomplete shard set: {len(indices)} of {expected} parts (0..{expected - 1})" - + missing - + (f", unexpected {extra}" if extra else "") - + "; let every --shard run finish before --merge") - elif indices[-1] != len(indices) - 1: - raise ShardSetError(f"incomplete shard set: parts {indices} are not contiguous from 0" - + _missing_shard_summary(indices, indices[-1] + 1) - + "; without a shard count the merge refuses a set with a gap") - if markers and set(markers) != set(indices): - raise ShardSetError(f"index parts and shard markers disagree: parts {sorted(set(indices))}, " - f"markers {sorted(markers)}") - merged = {} - for part in parts: - try: - with open(part, encoding="utf-8") as f: - doc = _js.load(f) - except (OSError, ValueError) as e: - raise ShardSetError(f"cannot read {part}: {e}; delete that part and run --shard / again") from None - if not isinstance(doc, dict): - raise ShardSetError(f"{part} does not contain a shader index object") - merged.update(doc) - if not merged: - raise ShardSetError(f"the shard set in {out} holds no shaders: every part is empty; " - "check the disassembly (llvm-mc output and the .s files) before --merge") - return merged - - -def _run_spirv_tool(cmd, **kwargs): - try: - return subprocess.run(cmd, **kwargs) - except FileNotFoundError as exc: - # Windows CreateProcess omits the executable name from WinError 2. - if getattr(exc, "winerror", None) == 2 and exc.filename is None: - exc.filename = cmd[0] - raise - - -def assemble_spirv(sa, sv, asm_text=None, assembler="spirv-as", validate=True): - """Keep the assembled module out of the final path until validation succeeds. - - `assembler="spirv-as"` invokes the external spirv-as binary on `sa` (default); - `assembler="python"` encodes `asm_text` (or reads `sa`) directly in memory with - tools/spirv_asm.py, avoiding the spirv-as subprocess and temporary .spvasm I/O. - When `validate=False`, skip running `spirv-val` after assembly. - """ - with tempfile.NamedTemporaryFile(prefix=".spirv-", suffix=".tmp", dir=os.path.dirname(sv), delete=False) as f: - tmp = Path(f.name) - # spirv-as reads the .spvasm from stdin, and both tools run in the output folder with the staging file's bare - # name. On Windows they read their command line in the ANSI code page, so a folder name outside it (a Cyrillic or - # CJK user name, say) reached them as '?' and every shader failed with "file does not exist". - folder = os.path.dirname(os.path.abspath(tmp)) - try: - if assembler == "python": - import spirv_asm - try: - text = asm_text if asm_text is not None else Path(sa).read_text(encoding="utf-8") - tmp.write_bytes(spirv_asm.assemble(text, target_env="vulkan1.2")) - result = subprocess.CompletedProcess(["spirv_asm"], 0, "", "") - except (OSError, spirv_asm.SpirvAsmError) as exc: - result = subprocess.CompletedProcess(["spirv_asm"], 1, "", str(exc)) - else: - try: - with open(sa, "rb") as f: - source = f.read() - except OSError as exc: - result = subprocess.CompletedProcess(["spirv-as"], 1, "", f"error: cannot read {sa}: {exc}") - else: - result = _run_spirv_tool(["spirv-as", "-", "-o", tmp.name, "--target-env", "vulkan1.2"], - input=source, capture_output=True, cwd=folder) - # stdin is bytes, so the output is too; a test double may already answer in text. - if isinstance(result.stdout, bytes): - result.stdout = result.stdout.decode("utf-8", "replace") - if isinstance(result.stderr, bytes): - result.stderr = result.stderr.decode("utf-8", "replace") - if result.returncode == 0 and validate: - # Offset on non-gather: VK_KHR_maintenance8 - result = _run_spirv_tool(["spirv-val", "--target-env", "vulkan1.2", "--allow-offset-texture-operand", - tmp.name], capture_output=True, text=True, cwd=folder) - if result.returncode == 0: - tmp.replace(sv) - else: - Path(sv).unlink(missing_ok=True) - return result - finally: - tmp.unlink(missing_ok=True) - - -def _limit_arg(text): - """--limit N: at least 1. 0 used to mean "no limit" (the whole corpus) and a negative N dropped the last N.""" - try: - value = int(text) - except ValueError: - raise argparse.ArgumentTypeError(f"not a whole number: {text!r}") from None - if value < 1: - raise argparse.ArgumentTypeError("must be at least 1") - return value - - -def _shard_arg(text): - """--shard i/n with n >= 1 and 0 <= i < n. n = 0 was a ValueError (slice step 0) and i >= n translated nothing.""" - try: - si, sn = (int(x) for x in text.split("/")) - except ValueError: - raise argparse.ArgumentTypeError(f"expected i/n, for example 0/8, not {text!r}") from None - if sn < 1 or not 0 <= si < sn: - raise argparse.ArgumentTypeError(f"{text!r}: need n >= 1 and 0 <= i < n") - return si, sn - - -def _depth_arg(text): - """--max-structured-depth N: 0 (never fall back to the dispatch loop) or a positive nesting depth.""" - try: - value = int(text) - except ValueError: - raise argparse.ArgumentTypeError(f"not a whole number: {text!r}") from None - if value < 0: - raise argparse.ArgumentTypeError("must be 0 (no bound) or a positive depth") - return value - - -def _out_inside_input(src, out): - """True when --out is the input folder or a folder inside it: translating there writes among the inputs. - - `src` is a .s file or the folder of them; a single file's folder is its input folder. `same_report_path` - covers the same spelling, `..`, links and (on Windows) case; `path_key` folds a case-insensitive macOS - volume for the containment test. Standard library only. - """ - folder = src if os.path.isdir(src) else os.path.dirname(os.path.abspath(src)) - if same_report_path(folder, out): - return True - root, target = path_key(folder), path_key(out) - return target.startswith(root.rstrip(os.sep) + os.sep) - - -def main(): - global MAX_SHARED_BYTES, MAX_STRUCTURED_DEPTH - ap = argparse.ArgumentParser() - ap.add_argument("src") - ap.add_argument("--out", required=True) - ap.add_argument("--limit", type=_limit_arg) - ap.add_argument("--shard", type=_shard_arg, - help="i/n: translate every n-th shader starting at i (run n processes in parallel, " - "then merge the index.part*.json files with --merge)") - ap.add_argument("--no-asm", action="store_true", - help="delete each .spvasm once its .spv is written (the text is ~2.7x the binary: 35 GB for the corpus)") - ap.add_argument("--assembler", choices=("spirv-as", "python"), default="spirv-as", - help="SPIR-V binary assembler: spirv-as (default, external binary) or python (in-process " - "tools/spirv_asm.py; skips writing .spvasm to disk when combined with --no-asm)") - ap.add_argument("--no-validate", action="store_true", - help="skip spirv-val after assembly (for running GPU tests without SPIRV-Tools when paired " - "with --assembler python)") - ap.add_argument("--merge", action="store_true", help="merge index.part*.json in --out into index.json and exit") - ap.add_argument("--fssm-dir", default=None, - help="optional dir with .fssm sidecars: records fssm_sha256 per shader in the index") - ap.add_argument("--dispatch-loop", action="store_true", - help="emit control flow the old way, as one loop around a switch (to compare with the default)") - ap.add_argument("--no-float-controls", action="store_true", - help="don't declare SignedZeroInfNanPreserve or DenormPreserve (for a driver whose " - "shaderSignedZeroInfNanPreserveFloat32 or shaderDenormPreserveFloat16 is false); NaN, inf, " - "-0 and f16 denormals are then not guaranteed") - ap.add_argument("--wave64-emulate", action="store_true", - help="wave64 compute and mesh shaders exact on any subgroup size (32-wide NVIDIA, Intel): " - "cross-lane operations go through workgroup memory instead of subgroup operations") - ap.add_argument("--wave64-graphics", choices=("warn", "error", "off"), default="warn", - help="wave64 vertex, pixel and geometry shaders that are not exact on 32-wide subgroups (tier C of " - "tools/wave64_halves.py): warn = count them in the summary and mark them in the index, " - "error = refuse them (Unsupported), off = skip the analysis") - ap.add_argument("--bary-fallback", action="store_true", - help="pixel shaders that read raw barycentrics take them from an ordinary interpolated input " - "(metadata: bary_fallback_input) instead of BaryCoordKHR, for devices without " - "VK_KHR_fragment_shader_barycentric (e.g. NVIDIA Pascal)") - ap.add_argument("--texel-offset-fallback", action="store_true", - help="image_sample*_o without VK_KHR_maintenance8 (e.g. NVIDIA Pascal): fold the texel offset into " - "the coordinate instead of the Offset operand") - ap.add_argument("--mesh-compute", action="store_true", - help="mesh shaders become compute shaders that write their vertices and primitives to a buffer " - "(metadata: mesh_compute), drawn by tools/mesh_compute_vs.py, for devices without " - "VK_EXT_mesh_shader (e.g. NVIDIA Pascal)") - ap.add_argument("--shader-clock", choices=("off", "khr"), default="off", - help="s_memtime / s_memrealtime: off = Unsupported (default), khr = OpReadClockKHR (needs " - "VK_KHR_shader_clock; feature shaderSubgroupClock / shaderDeviceClock in the metadata)") - ap.add_argument("--fma", choices=("glsl", "khr", "exact"), default="glsl", - help="how fused multiply-adds (v_fma_f32, v_fmac_f32, v_fmaak/fmamk_f32, v_fma_mix*) are emitted: " - "glsl = GLSL.std.450 Fma (default; the Vulkan spec lets a driver round twice), khr = OpFmaKHR " - "(guaranteed single rounding, f32 and f64; needs VK_KHR_shader_fma + shaderFmaFloat32/64, listed in the " - "shader's metadata as capability FMAKHR / feature shaderFmaFloat32/64), exact = a single " - "rounding built from NoContraction f32 ops, for a device that splits Fma and has no " - "VK_KHR_shader_fma (about 110 instructions, 31 NoContraction decorations and 13 constants per multiply-add; no extension needed)") - ap.add_argument("--f16-interp-fallback", action="store_true", - help="16-bit interpolation without PerVertexKHR inputs, for devices that can't compile them " - "(MoltenVK): VS and mesh params also export their f16 halves decoded to f32, which the PS " - "reads as ordinary interpolated inputs (metadata: f16_halves)") - ap.add_argument("--max-shared-memory", type=int, default=MAX_SHARED_BYTES, metavar="BYTES", - help="cap on a compute shader's workgroup memory, its LDS plus what --wave64-emulate adds " - "(default %(default)s, the 64 KiB hard cap): over it the LDS array shrinks to the program's " - "need, or the shader is refused (Unsupported). The device's own maxComputeSharedMemorySize " - "(32768 on some drivers) is checked by the runtime against lds_bytes in index.json") - ap.add_argument("--pc-tail-ubo", action="store_true", - help="keep only s0..s31 (128 bytes) in push constants and read the heap base, code base and " - "--mesh-compute output address from a uniform block at set 1, binding 0 (metadata: pc_tail), " - "for devices whose maxPushConstantsSize is below 144") - ap.add_argument("--max-structured-depth", type=_depth_arg, default=MAX_STRUCTURED_DEPTH, metavar="N", - help="a shader whose structured control flow nests deeper than N is emitted in the dispatch-loop " - "form instead (default %(default)s; 0 = never): that form validates faster at great depth " - "but compiles 1.7-2x slower on NVIDIA (SHADER-427, docs/design.md \"Control flow\")") - ap.add_argument("--opt", action="store_true", - help="run basic-block SPIR-V peephole optimization (tools/spirv_opt.py: register store-to-load " - "forwarding, OpAccessChain CSE, dead-store elimination, OpSelect/CopyObject folding, DCE)") - a = ap.parse_args() - # A file at --out (or one above it) can never become a folder. Refuse it here, before - # --merge publishes an index or os.makedirs raises a traceback. Same check as #1607's - # shader_disasm.py and #1632's tex_export.py. - if os.path.lexists(a.out) and not os.path.isdir(a.out): - ap.error(f"{a.out} is a file, not a folder") - # realpath resolves symlink components before '..' is applied, so a symlinked parent - # does not make the walk inspect a different tree than os.makedirs will use. - ancestor = os.path.dirname(os.path.realpath(a.out)) - while ancestor and not os.path.exists(ancestor): - parent = os.path.dirname(ancestor) - if parent == ancestor: # a root that doesn't exist, e.g. an unmapped Windows drive - ap.error(f"cannot create {a.out}: {ancestor} is not a folder") - ancestor = parent - if ancestor and not os.path.isdir(ancestor): - ap.error(f"cannot create {a.out}: {ancestor} is a file, not a folder") - MAX_SHARED_BYTES = a.max_shared_memory - MAX_STRUCTURED_DEPTH = a.max_structured_depth - global STRUCTURED, WAVE64_EMULATE, WAVE64_GRAPHICS, BARY_FALLBACK, TEXEL_OFFSET_FALLBACK, MESH_COMPUTE, FMA_KHR, SHADER_CLOCK, F16_HALVES, OPT_SPIRV - global PC_TAIL_UBO - PC_TAIL_UBO = a.pc_tail_ubo - global FMA_EXACT - FMA_KHR = a.fma == "khr" - SHADER_CLOCK = a.shader_clock == "khr" - FMA_EXACT = a.fma == "exact" - STRUCTURED = not a.dispatch_loop - global FLOAT_CONTROLS - FLOAT_CONTROLS = not a.no_float_controls - WAVE64_EMULATE = a.wave64_emulate - WAVE64_GRAPHICS = a.wave64_graphics - BARY_FALLBACK = a.bary_fallback - TEXEL_OFFSET_FALLBACK = a.texel_offset_fallback - MESH_COMPUTE = a.mesh_compute - F16_HALVES = a.f16_interp_fallback - OPT_SPIRV = a.opt - if a.merge: - try: - merged = merge_shard_parts(a.out) - except ShardSetError as e: - print(f"ERROR: {e}", file=sys.stderr) - # The parts no longer describe the old index: leaving it would let the next run take the failed merge - # as a finished translation. It is regenerated by the next successful --merge. - index = os.path.join(a.out, "index.json") - try: - os.remove(index) - except FileNotFoundError: - pass - except OSError as remove_error: - print(f"WARNING: cannot remove the stale {index}: {remove_error}", file=sys.stderr) - return 2 - # The stubs go first: index.json is what tells make_game.py the translation finished. - import spirv_stubs - spirv_stubs.generate_for_index(a.out, merged) - write_index(os.path.join(a.out, "index.json"), merged) - print(f"merged {len(merged)} entries") - return 0 - single_file = os.path.isfile(a.src) and a.src.endswith(".s") - if not single_file and not os.path.isdir(a.src): - ap.error(f"{a.src} is not a .s file or a folder of .s files") - # Writing translations into the input folder mixes them with the .s inputs (and a rerun then scans its - # own output); refuse it before mkdir, the index or any module is written. --merge above is exempt: its - # src is not read, and merging parts in place is how a shard run finishes. - if _out_inside_input(a.src, a.out): - print(f"ERROR: --out {a.out} is the input folder or inside it; choose a separate output folder", - file=sys.stderr) - return 2 - try: - os.makedirs(a.out, exist_ok=True) - except OSError as e: # a trailing separator on a file, or a symlink changed since the check above - ap.error(f"cannot create {a.out}: {e.strerror or e}") - shard = None - idx_path = os.path.join(a.out, "index.json") - if a.shard: - shard, sn = a.shard - part = os.path.join(a.out, f"index.part{shard}.json") - # Resume trusts the part, and consumers trust the merged index. Withdraw both - # before scanning or modifying outputs, even if a retry is killed mid-shader. - Path(part).unlink(missing_ok=True) - Path(idx_path).unlink(missing_ok=True) - write_index(os.path.join(a.out, SHARD_MARKER.format(index=shard)), {"index": shard, "count": sn}) - idx_path = part - if single_file: - files = [a.src] - else: - with os.scandir(a.src) as entries: - files = sorted(e.path for e in entries if e.name.endswith(".s") and e.is_file()) - if a.limit is not None: - files = files[:a.limit] - if shard is not None: - files = files[shard::sn] - why, ok, valid = Counter(), 0, 0 - meta = {} - invalid = set() - total = len(files) - t0 = time.time() - last_progress = 0.0 - label = f"shard {shard}" if shard is not None else "translate" - missing_inputs = 0 - - def drop_stale(name): - # A shader that no longer translates must not stay published from an earlier run: remove its old - # module, and the index merge below drops its entry, exactly like a spirv-as/val rejection. The - # .spvasm text stays for diagnosis, as it does on a rejection. - Path(os.path.join(a.out, name + ".spv")).unlink(missing_ok=True) - invalid.add(name) - - for i, p in enumerate(files, 1): - name = os.path.splitext(os.path.basename(p))[0] - try: - asm = translate(p) - except FileNotFoundError as e: - # Optional inputs have fallbacks in translate(). A failed required read must also - # retire this shader's previous module and index entry on a retry. - print(f"ERROR: {name}: missing translation input {e.filename}", file=sys.stderr) - missing_inputs += 1 - drop_stale(name) - continue - except Unsupported as e: - why[str(e)] += 1 - drop_stale(name) - continue - except (IndexError, KeyError, ValueError, AssertionError, TypeError, AttributeError, ZeroDivisionError, - RecursionError) as e: - # A translator bug on one program refuses that program and is counted; it does not end a run over a - # whole pack (an assert in --wave64-emulate stopped make_game.py's shaders stage, #3976). - why[f"translator error {type(e).__name__}"] += 1 - drop_stale(name) - continue - ok += 1 - sa = os.path.join(a.out, name + ".spvasm") - sv = os.path.join(a.out, name + ".spv") - write_asm = not (a.no_asm and a.assembler == "python") - if write_asm: - with open(sa, "w", encoding="utf-8", newline="\n") as f: - f.write(asm) - try: - r = assemble_spirv(sa, sv, asm_text=asm, assembler=a.assembler, validate=not a.no_validate) - except OSError as e: - # A missing spirv-as/spirv-val fails every shader the same way; report it once as a setup - # error (exit 2) instead of a FileNotFoundError traceback from the first one. - if e.filename not in ("spirv-as", "spirv-val"): - raise - print(f"ERROR: {e.filename} not found; install SPIRV-Tools (spirv-as, spirv-val) " - "and put it on PATH", file=sys.stderr) - return 2 - if r.returncode == 0: - valid += 1 - try: - fssm_sidecar = os.path.join(a.fssm_dir, name + ".fssm") if a.fssm_dir else None - meta[name] = shader_meta(translate.last_gen, asm, src_path=p, fssm_path=fssm_sidecar) - except Exception as e: # noqa: BLE001 - metadata must never cost a translation - meta[name] = {"error": f"{type(e).__name__}: {e}"} - else: - if not write_asm: - with open(sa, "w", encoding="utf-8", newline="\n") as f: - f.write(asm) - drop_stale(name) - why["INVALID: " + (r.stderr.strip().splitlines() or ["?"])[0][:90]] += 1 - if a.no_asm and os.path.exists(sa): - os.remove(sa) - now = time.time() - if total and (i == total or i % 100 == 0 or now - last_progress >= 15.0): - last_progress = now - pct = 100 * i // total - elapsed = now - t0 - if 0 < i < total and elapsed > 0: - left = elapsed * (total - i) / i - if left < 60: - eta = f", ~{int(left)}s left" - elif left < 3600: - eta = f", ~{int(left) // 60}m left" - else: - eta = f", ~{int(left) // 3600}h {int(left) // 60 % 60:02d}m left" - else: - eta = "" - print(f" {label}: {i}/{total} ({pct}%){eta}", flush=True) - import json as _js - old = {} - if shard is None and os.path.isfile(idx_path) and a.limit is None and len(files) < 1000: - with open(idx_path, encoding="utf-8") as f: - old = _js.load(f) # partial runs merge into an existing index - for name in invalid: - old.pop(name, None) - old.update(meta) - if shard is None or not missing_inputs: - write_index(idx_path, old) - if shard is None: - import spirv_stubs - spirv_stubs.generate_for_index(a.out, old) - status_label = "assembled (spirv-val skipped)" if a.no_validate else "pass spirv-val" - print(f"{len(files)} shaders: {ok} translated, {valid} {status_label}") - if W64G_COUNTS: - print("wave64 VS/PS/GS on 32-wide subgroups: " + ", ".join(f"tier {t}: {n}" for t, n in sorted(W64G_COUNTS.items())) - + (" (tier C is not exact there; see wave64_graphics_reasons in the index)" if W64G_COUNTS["C"] else "")) - for k, v in why.most_common(25): - print(f" {v:6} {k}") - if missing_inputs: - print(f"{missing_inputs} of {len(files)} selected shaders missing required inputs", file=sys.stderr) - return 1 - - -if __name__ == "__main__": - try: # a redirected stdout is strict ANSI code page under -I; write '?' for what it cannot encode - sys.stdout.reconfigure(errors="replace") - except (AttributeError, ValueError, OSError): - pass - sys.exit(main()) diff --git a/tools/recomp_census.py b/tools/recomp_census.py deleted file mode 100644 index 1363e6798..000000000 --- a/tools/recomp_census.py +++ /dev/null @@ -1,226 +0,0 @@ -"""Recompiler census over a PE image's .pdata. - -Usage: - python -I recomp_census.py [--out DIR] [--limit N] [--top K] - -Walks every RUNTIME_FUNCTION entry in .pdata (the same table the SEH machinery and -tools/pe_inspect.py report on), decodes each function with the x86-64 decoder in -tools/x64_recomp.py and runs the translator over it. The report answers the -questions the arm64 port needs answered before any machine code gets emitted: - - * how many functions / code bytes does .pdata claim? - * which mnemonics dominate the corpus? - * how much of it does the current emitter cover (per-function and overall)? - * what are the blockers: decode gaps, unhandled mnemonics, indirect control - flow that needs the pc-table dispatch, x87/SIMD/sys instructions? - -Writes /.json and /.md. Standard library only; reads the -file, never runs it. -""" -from __future__ import annotations - -import argparse -import json -import os -import struct -import sys -from collections import Counter - -sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) - -import pe_inspect # noqa: E402 -import x64_recomp # noqa: E402 - -DIR_EXCEPTION = pe_inspect.DIR_EXCEPTION -MAX_FUNCS = 1 << 20 # .pdata this long is not a table; matches pe_inspect's guard spirit - -UNW_FLAG_NAMES = {0x1: "EHANDLER", 0x2: "UHANDLER", 0x4: "FHANDLER", 0x8: "CHAINED"} - -# insn kinds that always need the pc-table dispatch (target not statically known) -INDIRECT_KINDS = ("ret",) - - -def pdata_entries(img): - """Sorted [(begin_rva, end_rva, unwind_rva)] from the exception directory.""" - rva, size = img.directory(DIR_EXCEPTION) - if not rva or size < 12: - return [] - off = img.offset(rva, size) - if off is None: - return [] - out = [] - for i in range(min(size // 12, MAX_FUNCS)): - b, e, u = struct.unpack_from("= b: - out.append((b, e, u)) - out.sort() - return out - - -def function_bytes(img, begin, end): - """File bytes for [begin_rva, end_rva), or None when it spans sections/headers oddly.""" - off = img.offset(begin, end - begin) - if off is None: - return None - return img.data[off:off + (end - begin)] - - -def unwind_flags(img, unwind_rva): - """(version, flag_names, code_count) from an UNWIND_INFO header, or None.""" - off = img.offset(unwind_rva, 4) - if off is None: - return None - b0, b1, _b2, _b3 = img.data[off:off + 4] - flags = b0 >> 3 - names = [n for bit, n in UNW_FLAG_NAMES.items() if flags & bit] - return (b0 & 7, names, b1) - - -def census_function(img, begin, end, image_base): - """Decode + translate one .pdata function. Returns a stats dict.""" - code = function_bytes(img, begin, end) - st = {"rva": begin, "size": end - begin, "insns": 0, "translated": 0, - "unhandled": Counter(), "decode_errors": 0, "indirect": Counter(), - "branches": 0, "mnem": Counter()} - if code is None: - st["decode_errors"] += 1 - return st - good = [] - for ins in x64_recomp.disasm(code, image_base + begin): - if ins.unknown or ins.error: - st["decode_errors"] += 1 - st["unhandled"][f"decode:{ins.mnem}"] += 1 - break - good.append(ins) - st["insns"] = len(good) - for ins in good: - st["mnem"][ins.mnem] += 1 - if ins.kind in ("branch", "call") and ins.ops and ins.ops[0][0] != "a": - st["indirect"][ins.mnem] += 1 - elif ins.kind == "ret": - st["indirect"]["ret"] += 1 - if ins.kind == "branch": - st["branches"] += 1 - try: - tr = x64_recomp.FunctionTranslator(good) - tr.translate() - st["translated"] = tr.stats["insns"] - for u in tr.stats["unhandled"]: - st["unhandled"][u.split(":", 1)[0].split("@")[0]] += 1 - except Exception as e: # translator-wide failure still gets counted - st["unhandled"][f"translator:{type(e).__name__}"] += 1 - return st - - -def census(path, limit=None): - with open(path, "rb") as f: - img = pe_inspect.PeImage(f.read()) - if img.machine != 0x8664: - raise pe_inspect.PeFormatError( - f"machine {hex(img.machine)} is not x86-64; nothing to recompile") - entries = pdata_entries(img) - if limit: - entries = entries[:limit] - - mnem, unhandled, indirect, uw_flags = Counter(), Counter(), Counter(), Counter() - funcs = covered = partial = insns = translated = code_bytes = 0 - decode_errs = branches = 0 - worst = [] - for begin, end, uw in entries: - st = census_function(img, begin, end, img.image_base) - funcs += 1 - insns += st["insns"] - translated += st["translated"] - code_bytes += st["size"] - decode_errs += st["decode_errors"] - branches += st["branches"] - mnem += st["mnem"] - unhandled += st["unhandled"] - indirect += st["indirect"] - uw_info = unwind_flags(img, uw) - if uw_info: - uw_flags[",".join(uw_info[1]) or "none"] += 1 - if not st["unhandled"]: - covered += 1 - else: - partial += 1 - worst.append((len(st["unhandled"]) and sum(st["unhandled"].values()) or 0, - st["rva"], st["size"], dict(st["unhandled"]))) - worst.sort(reverse=True) - cov = (translated / insns * 100) if insns else 0.0 - return { - "file": os.path.basename(path), - "image_base": hex(img.image_base), - "pdata_functions": len(entries), - "code_bytes": code_bytes, - "insns": insns, - "insn_coverage_pct": round(cov, 2), - "functions_fully_covered": covered, - "functions_with_gaps": partial, - "decode_errors": decode_errs, - "branch_insns": branches, - "indirect_control_flow": dict(indirect), - "unwind_flags": dict(uw_flags), - "top_mnemonics": mnem.most_common(40), - "unhandled": unhandled.most_common(40), - "worst_functions": [{"rva": hex(r), "size": s, "unhandled": u} - for _c, r, s, u in worst[:20]], - } - - -def to_markdown(r): - out = [f"# recomp census: {r['file']}", "", - f"- .pdata functions: {r['pdata_functions']:,} covering {r['code_bytes']:,} code bytes", - f"- decoded instructions: {r['insns']:,}; translated: " - f"{r['insn_coverage_pct']}% ({r['functions_fully_covered']:,} functions fully covered, " - f"{r['functions_with_gaps']:,} with gaps)", - f"- decode errors (unknown/error insns): {r['decode_errors']:,}", - f"- branch instructions: {r['branch_insns']:,}; indirect control flow: " - + (", ".join(f"{k}={v}" for k, v in sorted(r["indirect_control_flow"].items())) or "none"), - "", "## Unwind info flags", ""] - for k, v in sorted(r["unwind_flags"].items(), key=lambda kv: -kv[1]): - out.append(f"- {k}: {v:,}") - out += ["", "## Top mnemonics", "", "| mnemonic | count |", "|---|---|"] - for k, v in r["top_mnemonics"]: - out.append(f"| {k} | {v:,} |") - out += ["", "## Unhandled / hazard mnemonics", "", "| mnemonic | count |", "|---|---|"] - for k, v in r["unhandled"]: - out.append(f"| {k} | {v:,} |") - out += ["", "## Worst functions", "", "| rva | size | unhandled |", "|---|---|---|"] - for w in r["worst_functions"]: - u = ", ".join(f"{k}={v}" for k, v in sorted(w["unhandled"].items())) - out.append(f"| {w['rva']} | {w['size']} | {u} |") - return "\n".join(out) + "\n" - - -def main(argv=None): - p = argparse.ArgumentParser(description="x86-64 -> arm64 recompiler census over .pdata") - p.add_argument("image") - p.add_argument("--out", default=".") - p.add_argument("--limit", type=int, default=0, help="only inspect the first N .pdata functions") - p.add_argument("--top", type=int, default=40) - a = p.parse_args(argv) - try: - r = census(a.image, a.limit or None) - except pe_inspect.PeFormatError as e: - print(f"{a.image}: {e}", file=sys.stderr) - return 1 - r["top_mnemonics"] = r["top_mnemonics"][:a.top] - r["unhandled"] = r["unhandled"][:a.top] - os.makedirs(a.out, exist_ok=True) - name = os.path.basename(a.image) - with open(os.path.join(a.out, name + ".recomp.json"), "w", encoding="utf-8", newline="\n") as f: - json.dump(r, f, indent=1) - with open(os.path.join(a.out, name + ".recomp.md"), "w", encoding="utf-8", newline="\n") as f: - f.write(to_markdown(r)) - print(f"{r['file']}: {r['pdata_functions']:,} fns, {r['insns']:,} insns, " - f"{r['insn_coverage_pct']}% covered, {len(r['unhandled'])} hazard kinds") - return 0 - - -if __name__ == "__main__": - try: # a redirected stdout is strict ANSI code page under -I; write '?' for what it cannot encode - sys.stdout.reconfigure(errors="replace") - except (AttributeError, ValueError, OSError): - pass - sys.exit(main()) diff --git a/tools/replace_retry.py b/tools/replace_retry.py deleted file mode 100644 index 0dd54cd3a..000000000 --- a/tools/replace_retry.py +++ /dev/null @@ -1,33 +0,0 @@ -"""os.replace() that rides out the short windows in which Windows refuses to rename a file it has just seen written. - -On Windows, os.replace raises PermissionError (winerror 5 or 32) while another process holds the source or the -destination open without share-delete: a virus scanner, the search indexer, a cloud-sync client on Documents. The -hold lasts milliseconds to a few seconds, so the rename is tried again for a bounded time and only then re-raised. -Elsewhere, and for every other error, this is os.replace. -""" -import os -import time - -RETRY_SECONDS = 5.0 -FIRST_DELAY = 0.01 -MAX_DELAY = 0.25 -_TRANSIENT_WINERRORS = (5, 32) # ERROR_ACCESS_DENIED, ERROR_SHARING_VIOLATION - - -def _transient(error): - return isinstance(error, PermissionError) and getattr(error, "winerror", None) in _TRANSIENT_WINERRORS - - -def replace(src, dst, *, seconds=None): - """os.replace(src, dst), retried with a doubling delay for `seconds` (default RETRY_SECONDS) on a transient - Windows PermissionError; the last error is raised once the time is up.""" - deadline = time.monotonic() + (RETRY_SECONDS if seconds is None else seconds) - delay = FIRST_DELAY - while True: - try: - return os.replace(src, dst) - except PermissionError as e: - if not _transient(e) or time.monotonic() >= deadline: - raise - time.sleep(min(delay, max(0.0, deadline - time.monotonic()))) - delay = min(delay * 2, MAX_DELAY) diff --git a/tools/report_paths.py b/tools/report_paths.py deleted file mode 100644 index 082d7db40..000000000 --- a/tools/report_paths.py +++ /dev/null @@ -1,93 +0,0 @@ -"""Do two report paths name the same file? One answer for the tools that refuse an output that would overwrite -an input or another output. - - from report_paths import same_report_path # after sys.path.insert(0, ), as -I needs - -`same_report_path(first, second)` is true when the two paths resolve to one name (`realpath`, then `normcase`, and on a -case-insensitive macOS volume also case-folded and with composed and decomposed accents treated alike) or when both -exist and `os.path.samefile` says they are one file (a hard link, another spelling the name rules missed). Neither -path has to exist: two report paths that don't exist yet still collide when they differ only in case on a volume that -ignores case. Where the name rules cannot tell, `same_name_on_folding_volume` asks the volume itself with one -scratch folder: a Linux mount that folds case (vfat, exFAT, CIFS) answers neither `normcase` nor `pathconf`. -Standard library only; no game data. -""" -import os -import posixpath -import sys -import tempfile -import unicodedata - -_PC_CASE_SENSITIVE = 11 # on macOS; os.pathconf_names doesn't list it - - -def case_insensitive_volume(path): - """True when the volume that will hold `path` ignores letter case, as macOS's default APFS volume does. - os.path.normcase folds case only on Windows, so on macOS `R.json` and `r.json` would pass as two reports.""" - if sys.platform != "darwin": - return False - while not os.path.exists(path): - parent = os.path.dirname(path) - if parent == path: - break - path = parent - try: - return os.pathconf(path, _PC_CASE_SENSITIVE) == 0 - except (OSError, ValueError): - return True # the macOS default; folding can only refuse a pair, never overwrite one - - -def path_key(path): - """A name two spellings of one path share: realpath, normcase, and on a case-insensitive volume case-folded NFD.""" - return _resolved_key(os.path.realpath(path)) - - -def _resolved_key(path): - """`path_key` for a path `os.path.realpath` has already resolved.""" - # Use the path rules of the platform we are resolving for. On macOS os.path is - # posixpath and keeps case; on Windows ntpath lowercases. Resolving a simulated - # macOS path through ntpath would hide the case-sensitive branch under test. - path = posixpath.normcase(path) if sys.platform == "darwin" else os.path.normcase(path) - if case_insensitive_volume(path): - # APFS and HFS+ also treat composed and decomposed accents as one name. - return unicodedata.normalize("NFD", path.casefold()) - return path - - -def same_name_on_folding_volume(first, second): - """True when two names that differ only by case are one file on the volume that holds them. - - os.path.normcase folds case only on Windows and the `pathconf` probe above answers only on macOS, so a Linux - mount that ignores case (vfat, exFAT, CIFS) would pass `R.json` and `r.json` as two reports and let the second - one overwrite the first. Ask the volume itself: create one spelling in a scratch folder beside the reports and - look for the other. Names that differ by more than case are never one file, so that costs nothing. - """ - return _same_resolved_name(os.path.realpath(first), os.path.realpath(second)) - - -def _same_resolved_name(first, second): - """`same_name_on_folding_volume` for paths `os.path.realpath` has already resolved.""" - first_dir, first_name = os.path.split(first) - second_dir, second_name = os.path.split(second) - if first_name.casefold() != second_name.casefold(): - return False - try: - if not os.path.samefile(first_dir, second_dir): - return False - with tempfile.TemporaryDirectory(prefix=".leonida-report-", dir=first_dir) as probe: - with open(os.path.join(probe, first_name), "xb"): - return os.path.exists(os.path.join(probe, second_name)) - except OSError: - return False - - -def same_report_path(first, second): - # Resolve each path once: the key and the volume probe both want the resolved name, and a guard runs once - # per input file, so a second realpath per path is the whole cost of the check (see #6220's review). - first, second = os.path.realpath(first), os.path.realpath(second) - if _resolved_key(first) == _resolved_key(second): - return True - try: - return os.path.samefile(first, second) - except OSError: - pass - return _same_resolved_name(first, second) diff --git a/tools/restofworld_index.py b/tools/restofworld_index.py deleted file mode 100644 index 61e5e2f34..000000000 --- a/tools/restofworld_index.py +++ /dev/null @@ -1,578 +0,0 @@ -"""Index the stream signatures in the rest-of-world and script RPF9 archives. - -The RPF9 table of contents is encrypted, so this walks the data area the same way -`rpf9_carve.py` does: find every zlib stream that inflates cleanly to its end, plus -validated Bink 2 streams, and classify what starts each stream. It reports the -measured signatures from `docs/restofworld.md` and writes one row per stream. It -does not decode resources, write payload bytes, or touch the table of contents. - -Signatures are only accepted at a stream start, except `0DRP`, which is accepted at -+0 or +0x10 because the PSIN LRSC payload and a 0x7a metadata resource use both -placements. A four-byte magic inside an inflated page or XML text is not a stream -signature; that distinction matters because `ADAT` occurs inside `METADATA`, and -`AWC` occurs inside printable names. - -Usage: - python -I restofworld_index.py [--start N] [--limit BYTES] - python -I restofworld_index.py -""" -import argparse -import array -from collections import Counter -import csv -import json -import mmap -import os -import re -import struct -import sys -import tempfile -import time -import zlib - -ROOT = os.path.dirname(os.path.abspath(__file__)) -if ROOT not in sys.path: - sys.path.insert(0, ROOT) -from file_mode import published_mode # noqa: E402 -from zero_span import gap_split # noqa: E402 - -# zlib stream start, or Bink 2 video ('KB2' + revision letter). Kept in step with rpf9_carve.py. -ZHDR = re.compile(rb"\x78[\x01\x5e\x9c\xda]|KB2[a-z]") -PSIN_TAGS = (b"LSCH", b"LENM", b"LSNS", b"LGID", b"LRSC", b"CHKS") -COLUMNS = ["offset", "stored", "size", "signature", "version", "count", "detail"] -MAX_INFLATE = 512 << 20 -MAX_TEX_SCAN = 16 << 20 -_UINT64_CODE = "Q" if array.array("Q").itemsize == 8 else None - -# DXGI format codes observed in RAGE9 0x980 texture descriptors (kept in step with tools/tex_headers.py). -DXGI_FORMATS = { - 2: "R32G32B32A32_FLOAT", 3: "R32G32B32A32_UINT", 4: "R32G32B32A32_SINT", - 6: "R32G32B32_FLOAT", 7: "R32G32B32_UINT", 8: "R32G32B32_SINT", - 10: "R16G16B16A16_FLOAT", 11: "R16G16B16A16_UNORM", 12: "R16G16B16A16_UINT", - 13: "R16G16B16A16_SNORM", 14: "R16G16B16A16_SINT", - 16: "R32G32_FLOAT", 17: "R32G32_UINT", 18: "R32G32_SINT", - 24: "R10G10B10A2_UNORM", 25: "R10G10B10A2_UINT", 26: "R11G11B10_FLOAT", - 28: "R8G8B8A8_UNORM", 29: "R8G8B8A8_UNORM_SRGB", 30: "R8G8B8A8_UINT", - 31: "R8G8B8A8_SNORM", 32: "R8G8B8A8_SINT", - 34: "R16G16_FLOAT", 35: "R16G16_UNORM", 36: "R16G16_UINT", - 37: "R16G16_SNORM", 38: "R16G16_SINT", - 41: "R32_FLOAT", 42: "R32_UINT", 43: "R32_SINT", - 49: "R8G8_UNORM", 50: "R8G8_UINT", 51: "R8G8_SNORM", 52: "R8G8_SINT", - 54: "R16_FLOAT", 56: "R16_UNORM", 57: "R16_UINT", 58: "R16_SNORM", 59: "R16_SINT", - 61: "R8_UNORM", 62: "R8_UINT", 63: "R8_SNORM", 64: "R8_SINT", - 71: "BC1_UNORM", 72: "BC1_UNORM_SRGB", - 74: "BC2_UNORM", 75: "BC2_UNORM_SRGB", - 77: "BC3_UNORM", 78: "BC3_UNORM_SRGB", - 80: "BC4_UNORM", 81: "BC4_SNORM", - 83: "BC5_UNORM", 84: "BC5_SNORM", - 87: "B8G8R8A8_UNORM", 91: "B8G8R8A8_UNORM_SRGB", - 95: "BC6H_UF16", 96: "BC6H_SF16", - 98: "BC7_UNORM", 99: "BC7_UNORM_SRGB", -} - - -def find_rage_textures(data): - """Find validated RAGE9 0x980 texture descriptors (ASSET-148; layout from tools/tex_headers.py). - - Returns a list of (width, height, depth, dxgi_name, flags_lo, mips) tuples. Requires dtype == 0x980, - 256-byte-aligned 0x60000000..0x6FFFFFFF GPU pointer, known DXGI format, and sane dimensions. - """ - n_qwords = len(data) // 8 - if n_qwords < 8: - return [] - mv = memoryview(data)[:n_qwords * 8] - if _UINT64_CODE is not None: - q = array.array(_UINT64_CODE) - q.frombytes(mv) - if sys.byteorder != "little": - q.byteswap() - else: - q = struct.unpack(f"<{n_qwords}Q", mv) - out = [] - for k in range(2, n_qwords - 5): - ptr = q[k] - if not (0x60000000 <= ptr <= 0x6FFFFFFF) or (ptr & 0xFF) != 0: - continue - if q[k - 1] != 0x980: - continue - d = q[k + 4].to_bytes(8, "little") - fmt = d[7] - if fmt not in DXGI_FORMATS: - continue - w = int.from_bytes(d[0:2], "little") - h = int.from_bytes(d[2:4], "little") - depth = int.from_bytes(d[4:6], "little") - if not (1 <= w <= 16384 and 1 <= h <= 16384 and 1 <= depth <= 2048): - continue - fword = q[k + 5] - mips = (fword >> 16) & 0xFF - if min(w, h) < 4 and not 1 <= mips <= max(w, h, depth).bit_length(): - continue - out.append((w, h, depth, DXGI_FORMATS[fmt], fword & 0xFFFF, mips)) - return out - - -def is_pg_tex_dictionary(data, count): - """True when a zero-prefix stream carries a standalone pgDictionary header matching count.""" - if count <= 0 or len(data) < 0x40: - return False - u8, u10 = struct.unpack_from("> 28) != 5 or u10 != 0: - return False - p20, c28, _cap2a, p30, c38, _cap3a = struct.unpack_from("> 28) == 5 and (p30 >> 28) == 5 and c28 == c38 == count - - -def _u32(data, at): - return struct.unpack_from("= at + 4 else None - - -def _u64(data, at): - return struct.unpack_from("= at + 8 else None - - -def _be32(data, at): - return int.from_bytes(data[at:at + 4], "big") if len(data) >= at + 4 else 0 - - -def _printable(data): - if not data: - return False - sample = data[:512] - good = sum(1 for b in sample if 32 <= b < 127 or b in (9, 10, 13)) - return len(sample) >= 64 and good / len(sample) > 0.9 - - -def psin_sections(data): - """Return a PSIN section chain as [(tag, offset, size), ...]. - - The header's big-endian first-section offset at +4 is authoritative when it points at a - known tag. A record is a four-byte tag and a big-endian u32 total size that includes the - eight-byte record header. The chain stops at CHKS or at the first unknown/out-of-range - record. Only the six measured tags are accepted. - """ - def parse(at): - chain = [] - pos = at - while pos + 8 <= len(data): - tag = data[pos:pos + 4] - if tag not in PSIN_TAGS: - break - size = _be32(data, pos + 4) - if size < 8 or pos + size > len(data): - break - chain.append((tag.decode("ascii"), pos, size)) - if tag == b"CHKS": - break - pos += size - return chain - - first = _be32(data, 4) - if 8 <= first < len(data) and data[first:first + 4] in PSIN_TAGS: - chain = parse(first) - if chain: - return chain - best = [] - start = 0 - while True: - at = data.find(b"LSCH", start) - if at < 0: - break - chain = parse(at) - if len(chain) > len(best): - best = chain - start = at + 1 - return best - - -def _is_xml(data): - if data.startswith(b"\xef\xbb\xbf"): - data = data[3:] - return data.lstrip()[:5] == b"= 0x20: - row.update(signature="bink2", version=chr(data[3]), count=_u32(data, 8), - detail=f"{_u32(data, 0x14)}x{_u32(data, 0x18)}", size=stored) - return row - if data[:4] == b"\x42\x40\x00\x00": - row.update(signature="respage", detail="0x4042") - return row - if data[:4] in (b"DDS ", b"DXT1", b"DXT3", b"DXT5", b"ATI2", b"BC5\x00", b"BC7\x00"): - row.update(signature=data[:4].decode("ascii", "replace")) - return row - if _is_xml(data): - row.update(signature="xml", detail="XML text") - return row - if len(data) >= 16 and _u32(data, 4) == 8 and _u32(data, 12) == 0 and 0 < (_u32(data, 8) or 0) <= 4096: - row.update(signature="typehash", version=8, count=_u32(data, 8), - detail=f"type={_u32(data, 0):#010x}") - return row - if len(data) >= 8 and _u32(data, 0) in (2, 3) and data[4:8] == b"\x01\x01\x00\x00": - row.update(signature="clip", version=_u32(data, 0)) - return row - if data[:8] == b"\x00" * 8: - pointer = _u64(data, 8) - detail = f"u64@8={pointer:#x}" if pointer is not None else "u64@8=?" - texs = find_rage_textures(data) if pointer not in (None, 0) else [] - if texs: - is_dict = is_pg_tex_dictionary(data, len(texs)) - fmts = Counter(t[3] for t in texs).most_common(4) - fmt_str = ",".join(f"{name}:{n}" for name, n in fmts) - detail += f";tex980={len(texs)};dict={int(is_dict)};fmts={fmt_str}" - row.update(signature="zero-prefix", count=len(texs), detail=detail) - else: - row.update(signature="zero-prefix", detail=detail) - return row - if _printable(data): - row.update(signature="text", detail="printable text") - return row - row.update(signature="raw:" + data[:4].hex()) - return row - - - -def scan_rpf(path, start=None, limit=None, max_inflate=MAX_INFLATE): - """Walk an RPF9 data area. Returns (rows, summary). No TOC is read or decrypted.""" - rows = [] - zero = unread = skipped = 0 - t0 = time.time() - if os.path.getsize(path) == 0: - raise ValueError("empty file") - with open(path, "rb") as fh: - with mmap.mmap(fh.fileno(), 0, access=mmap.ACCESS_READ) as m: - size = len(m) - first = struct.unpack_from("= 8 else 0 - pos = start if start is not None else first - if not 0 <= pos <= size: - raise ValueError("start offset is outside the archive") - end = min(size, pos + limit) if limit else size - span_start = pos - last = pos - while pos < end: - found = ZHDR.search(m, pos, end) - if not found: - break - s = found.start() - if m[s:s + 3] == b"KB2": - blen = (_u32(m, s + 4) or 0) + 8 - w, h = _u32(m, s + 0x14), _u32(m, s + 0x18) - if not (64 <= blen <= end - s and w and h and 16 <= w <= 8192 and 16 <= h <= 8192): - pos = s + 1 - continue - z, u = gap_split(m, last, s) - zero += z - unread += u - rows.append(classify(m[s:s + 256], s, blen)) - last = pos = s + blen - continue - d = zlib.decompressobj() - p, total, head, body = s, 0, b"", bytearray() - too_big = False - keep_body = True - try: - while not d.eof and p < end: # inside the --limit window, as in story_index (#712) - block = m[p:min(p + (1 << 20), end)] - if not block: - break - p += len(block) - while block and not d.eof: - chunk = d.decompress(block, 1 << 20) - block = d.unconsumed_tail - if chunk: - total += len(chunk) - if total > max_inflate: - too_big = True - break - if len(head) < 256: - head += chunk[:256 - len(head)] - if keep_body: - if len(head) >= 16: - is_psin = head[:4] == b"PSIN" - is_cpu = head[:8] == b"\x00" * 8 and head[:16] != b"\x00" * 16 - if not is_psin and not (is_cpu and total <= MAX_TEX_SCAN): - keep_body = False - body.clear() - if keep_body: - body += chunk - if not block: - break - if too_big: - break - except zlib.error: - pos = s + 1 - continue - if too_big or not d.eof or total < 64: - skipped += 1 - pos = s + 1 - continue - used = p - s - len(d.unused_data) - z, u = gap_split(m, last, s) - zero += z - unread += u - row = classify(bytes(body) if keep_body and body else head, s, used) - row["size"] = total - rows.append(row) - last = pos = s + used - z, u = gap_split(m, last, end) - zero += z - unread += u - summary = summarise(rows, end - span_start, zero, unread) - summary.update(mode="rpf9", archive=path, elapsed_seconds=round(time.time() - t0, 3), - skipped_candidates=skipped) - return rows, summary - - -def _carve_index(path): - """rpf9_carve.py's index.json in `path`: ({file name: stored bytes}, summary), or ({}, {}) without one.""" - try: - with open(os.path.join(path, "index.json"), encoding="utf-8") as f: - index = json.load(f) - stored = {f"{int(e['off']):012x}.bin": int(e["stored"]) for e in index.get("files", [])} - summary = index.get("summary", {}) - return stored, summary if isinstance(summary, dict) else {} - except (OSError, ValueError, TypeError, KeyError, AttributeError): - return {}, {} - - -def scan_dir(path, max_inflate=MAX_INFLATE): - """Index already-carved files. A leading hexadecimal file name supplies the offset. - - With rpf9_carve.py's index.json in the folder, each file's stored (compressed) size and the carve's span, - zero padding and unread bytes come from it, so compressed_bytes and readable_fraction mean what they mean in - archive mode. Without it, a file's stored size can only be its length on disk (the inflated size).""" - rows = [] - skipped = 0 - t0 = time.time() - carve_stored, carve_summary = _carve_index(path) - for name in sorted(os.listdir(path)): - full = os.path.join(path, name) - if not os.path.isfile(full) or not (name.endswith(".bin") or name.endswith(".bk2")): - continue - if name.endswith(".bin") and os.path.getsize(full) > max_inflate: - skipped += 1 - continue - found = re.match(r"([0-9a-fA-F]{6,})", name) - offset = int(found.group(1), 16) if found else len(rows) - with open(full, "rb") as f: - data = f.read() - stored = carve_stored.get(name, len(data)) - if len(data) >= 3 and data[:3] == b"KB2": - row = classify(data, offset, stored) - else: - row = classify(data, offset, stored) - row["size"] = len(data) - rows.append(row) - if carve_stored and "span" in carve_summary: - summary = summarise(rows, int(carve_summary["span"]), int(carve_summary.get("zero_padding", 0)), - int(carve_summary.get("unread_bytes", 0))) - else: - summary = summarise(rows, sum(r["stored"] for r in rows), 0, 0) - summary.update(mode="directory", directory=path, elapsed_seconds=round(time.time() - t0, 3), - skipped_candidates=skipped) - return rows, summary - - -def summarise(rows, span, zero, unread): - by_sig = {} - for row in rows: - entry = by_sig.setdefault(row["signature"], {"files": 0, "stored": 0, "inflated": 0}) - entry["files"] += 1 - entry["stored"] += row["stored"] - entry["inflated"] += row["size"] - stored = sum(row["stored"] for row in rows) - tex_rows = [row for row in rows if row["signature"] == "zero-prefix" and ";tex980=" in row["detail"]] - return { - "files": len(rows), - "compressed_bytes": stored, - "inflated_bytes": sum(row["size"] for row in rows), - "bink2_files": sum(1 for row in rows if row["signature"] == "bink2"), - "bink2_bytes": sum(row["stored"] for row in rows if row["signature"] == "bink2"), - "texture_streams": len(tex_rows), - "texture_dictionaries": sum(1 for row in tex_rows if ";dict=1" in row["detail"]), - "texture_headers": sum(row["count"] or 0 for row in tex_rows), - "zero_padding": zero, - "unread_bytes": unread, - "span": span, - "readable_fraction": round(stored / span, 6) if span else 0.0, - "signatures": by_sig, - } - - -def write_output(path, rows, summary): - """Write CSV or JSON from the file extension.""" - parent = os.path.dirname(os.path.abspath(path)) - tmp = None - try: - if os.path.splitext(path)[1].lower() == ".json": - with tempfile.NamedTemporaryFile("w", encoding="utf-8", newline="\n", dir=parent, - prefix=".restofworld_index-", suffix=".tmp", delete=False) as f: - tmp = f.name - json.dump({"summary": summary, "files": rows}, f, indent=1) - else: - with tempfile.NamedTemporaryFile("w", encoding="utf-8", newline="", dir=parent, - prefix=".restofworld_index-", suffix=".tmp", delete=False) as f: - tmp = f.name - writer = csv.writer(f, lineterminator="\n") - writer.writerow(COLUMNS) - for row in rows: - writer.writerow([f"0x{row['offset']:x}" if i == 0 else ("" if row[c] is None else row[c]) - for i, c in enumerate(COLUMNS)]) - os.chmod(tmp, published_mode(path)) - os.replace(tmp, path) - except BaseException: - if tmp is not None: - try: - if os.path.lexists(tmp): - os.chmod(tmp, 0o600) - os.remove(tmp) - except OSError: - pass - raise - - -def offset(text): - """--start: 0 or more, decimal or 0x hex.""" - try: - value = int(text, 0) - except ValueError: - raise argparse.ArgumentTypeError("must be 0 or more") from None - if value < 0: - raise argparse.ArgumentTypeError("must be 0 or more") - return value - - -def byte_count(text): - """--limit/--max-inflate: at least 1; 0 used to mean no limit.""" - try: - value = int(text, 0) - except ValueError: - raise argparse.ArgumentTypeError("must be at least 1") from None - if value < 1: - raise argparse.ArgumentTypeError("must be at least 1") - return value - - -def _samefile(source, out): - """True when `out` names the same existing file as `source`. - - os.path.samefile needs both paths on disk, so a not-yet-written output is - reported as "no alias" instead of forcing a scan or a write first. Any other - comparison failure propagates for the caller to report. - """ - try: - return os.path.samefile(source, out) - except FileNotFoundError: - return False - - -def main(): - ap = argparse.ArgumentParser(description=__doc__.splitlines()[0]) - ap.add_argument("source", help="an .rpf archive or a directory of carved .bin/.bk2 files") - ap.add_argument("out", help="output path ending in .csv or .json") - ap.add_argument("--start", type=offset, help="first byte to scan (default: RPF data start)") - ap.add_argument("--limit", type=byte_count, help="number of bytes to scan") - ap.add_argument("--max-inflate", type=byte_count, default=MAX_INFLATE, - help="skip a stream that inflates above this many bytes (default: 512 MiB)") - ap.add_argument("--quiet", action="store_true") - args = ap.parse_args() - if os.path.isdir(args.source) and (args.start is not None or args.limit is not None): - ap.error("--start and --limit apply to a single archive, not a directory") - if os.path.isdir(args.out): - ap.error(f"{args.out} is a folder, not a .csv or .json file") - folder = os.path.dirname(os.path.abspath(args.out)) - if not os.path.isdir(folder): - ap.error(f"{folder} is not a folder, so {args.out} cannot be written") - try: - overwrites_source = _samefile(args.source, args.out) - if not overwrites_source and os.path.isdir(args.source) and os.path.isfile(args.out): - # Protect scanned payloads and their carve manifest, including hard-link aliases. - for name in sorted(os.listdir(args.source)): - if name == "index.json" or name.endswith(".bin") or name.endswith(".bk2"): - full = os.path.join(args.source, name) - if os.path.isfile(full) and _samefile(full, args.out): - overwrites_source = True - break - except OSError as e: - ap.error(f"cannot compare source and output paths: {e}") - if overwrites_source: - ap.error("output must not overwrite the source archive") - try: - if os.path.isdir(args.source): - rows, summary = scan_dir(args.source, args.max_inflate) - else: - rows, summary = scan_rpf(args.source, args.start, args.limit, args.max_inflate) - except ValueError as e: - sys.exit(f"{args.source}: {e}") - except OSError as e: - sys.exit(f"{args.source}: {e.strerror or e}") - try: - write_output(args.out, rows, summary) - except OSError as e: - print(f"ERROR: cannot write {args.out}: {e.strerror or e}", file=sys.stderr) - return 1 - if not args.quiet: - print(json.dumps({k: summary[k] for k in - ("files", "compressed_bytes", "inflated_bytes", "zero_padding", - "unread_bytes", "span", "readable_fraction", "bink2_files", - "skipped_candidates", "elapsed_seconds")}, indent=1)) - for name, counts in sorted(summary["signatures"].items(), key=lambda kv: -kv[1]["files"]): - print(f" {name:24} {counts['files']:6} files {counts['stored']:12} stored " - f"{counts['inflated']:12} inflated") - return 0 - - -if __name__ == "__main__": - try: # a redirected stdout is strict ANSI code page under -I; write '?' for what it cannot encode - sys.stdout.reconfigure(errors="replace") - except (AttributeError, ValueError, OSError): - pass - sys.exit(main()) diff --git a/tools/restofworld_model_join.py b/tools/restofworld_model_join.py deleted file mode 100644 index 47a63efac..000000000 --- a/tools/restofworld_model_join.py +++ /dev/null @@ -1,1310 +0,0 @@ -"""Join RPF9 model system pages to their graphics pages without the encrypted TOC. - -In the rest-of-world RPF9 archives, `rpf9_carve.py` and `restofworld_index.py` see -individual zlib streams: zero-prefix system pages (`0x50000000`-based pointers) and -`42 40 00 00` / meshlet-group graphics pages (`0x60000000`-based pointers). Grouping -them into complete drawable, drawable-dictionary and fragment resources does not -require the encrypted RPF9 table of contents: - -1. A top-level resource starts on a 4,096-byte archive boundary + 16, preceded by - 16 zero bytes, with eight zero bytes at +0x00 and a `0x50000000`-based pointer - at +0x08 to its `datResourceMap` page header (`0DRP` directory pages have `0DRP` - at +0x10 and are excluded). -2. At `page_map = u64@+0x08 - 0x50000000`, `u8@(page_map + 8)` gives `system_pages` - and `u8@(page_map + 9)` gives `graphics_pages`, followed by `system_pages + - graphics_pages` 8-byte zero runtime slot words at `page_map + 0x10`. When - `system_pages > 1`, `page_map` sits near the end of the concatenated system - streams, and every non-final system or graphics stream is a full 64 KiB multiple. -3. The resource owns `system_pages` contiguous zlib streams followed immediately by - `graphics_pages` contiguous zlib streams (each internal gap is 0..15 zero bytes to - the next 16-byte archive boundary). -4. Every geometry record across all LODs (`+0x50..+0x68`) of every drawable in the - system segment cross-validates against the joined graphics segment: vertex buffer - `vb+0x18` (`0x60000000`-based) lands on a `0x42` or `0x63` vertex block matching - the FVF position encoding and vertex count, and meshlet descriptor `geo+0x40` - lands on an index buffer whose meshlet header, running sums and triangle indices - match the descriptor counts and reach into the final declared graphics page. - -No asset names, path strings, hashes or payload bytes are written. Reports contain -archive offsets, stream indices, byte sizes, page counts and geometry totals only. - -Usage: - python -I tools/restofworld_model_join.py - [--start N] [--limit BYTES] [--max-inflate BYTES] [--quiet] - python -I tools/restofworld_model_join.py - [--max-inflate BYTES] [--quiet] -""" -import argparse -import csv -import json -import math -import mmap -import os -import re -import struct -import sys -import time -import zlib - -ZHDR = re.compile(rb"\x78[\x01\x5e\x9c\xda]|KB2[a-z]") -SYS_BASE = 0x50000000 -GFX_BASE = 0x60000000 -MAX_SYS = 32 * 1024 * 1024 -MAX_GFX = 224 * 1024 * 1024 -MAX_PAGES = 32 -MAX_INFLATE = 512 << 20 -DECOMPRESS_CHUNK = 1 << 20 - -COLUMNS = [ - "offset", - "stream_index", - "kind", - "complete", - "system_pages", - "graphics_pages", - "graphics_first_offset", - "system_stored", - "system_bytes", - "graphics_stored", - "graphics_bytes", - "required_system_bytes", - "required_graphics_bytes", - "drawables", - "primary_geometries", - "primary_vertices", - "primary_triangles", - "all_lod_geometries", - "all_lod_vertices", - "all_lod_triangles", - "error", -] - - -class JoinError(ValueError): - """Raised when a candidate resource fails a structural or cross-page check.""" - - -def _u16(data, at): - if at < 0 or at + 2 > len(data): - raise JoinError(f"truncated u16 at +0x{at:x}") - return struct.unpack_from(" len(data): - raise JoinError(f"truncated u32 at +0x{at:x}") - return struct.unpack_from(" len(data): - raise JoinError(f"truncated u64 at +0x{at:x}") - return struct.unpack_from(" len(data): - return False - mn = struct.unpack_from("<3f", data, at) - mx = struct.unpack_from("<3f", data, at + 16) - if not all(math.isfinite(v) and abs(v) < 1e7 for v in mn + mx): - return False - return mn[0] <= mx[0] and mn[1] <= mx[1] and mn[2] <= mx[2] - - -def looks_like_drawable_header(data, at=0, embedded=False): - if len(data) < at + 176 or _u64(data, at) != 0: - return False - pages = _u64(data, at + 8) - shader = _u64(data, at + 16) - high = _u64(data, at + 80) - name = _u64(data, at + 168) - if (pages != 0) if embedded else (not is_sys_ptr(pages)): - return False - if not is_sys_ptr(shader) or not is_sys_ptr(high): - return False - if not (is_sys_ptr(name) or (embedded and name == 0)): - return False - radius = struct.unpack_from(" len(data): - return None - first = _u64(data, values) - if not is_sys_ptr(first): - return None - first_off = first - SYS_BASE - if first_off >= 64 and first_off + 176 <= len(data) and looks_like_drawable_header(data, first_off, embedded=True): - return "drawable_dict" - if first_off >= 64 and first_off + 0x70 <= len(data): - # Standalone texture dictionary: grcTexture entries have self-pointer +0x50 at +0x28 and tile mode 5 at +0x40. - if _u64(data, first_off + 0x28) == SYS_BASE + first_off + 0x50 and data[first_off + 0x40] == 5: - return "texture_dict" - return "other_dict" - - -def classify_system_root(sys_bytes): - """Classify an assembled system segment into a model kind or a non-model class.""" - if len(sys_bytes) < 64 or sys_bytes[:8] != b"\x00" * 8: - return None - if len(sys_bytes) >= 0x14 and sys_bytes[0x10:0x14] == b"0DRP": - return "0drp" - if not is_sys_ptr(_u64(sys_bytes, 8)): - return None - if looks_like_drawable_header(sys_bytes, 0, embedded=False): - return "drawable" - if looks_like_fragment_header(sys_bytes): - return "fragment" - dk = classify_dictionary_header(sys_bytes) - if dk is not None: - return dk - return "other_sys" - - -def classify_graphics_head(data): - """Coarse stream-start tag for a graphics stream.""" - if len(data) < 4: - return "short" - w0 = struct.unpack_from(" len(sys_bytes): - raise JoinError("page-map header extends past system segment") - w0, w4 = _u32(sys_bytes, off), _u32(sys_bytes, off + 4) - sys_pages = sys_bytes[off + 8] - gfx_pages = sys_bytes[off + 9] - pad10 = _u16(sys_bytes, off + 10) - pad12 = _u32(sys_bytes, off + 12) - if not (1 <= sys_pages <= MAX_PAGES and 0 <= gfx_pages <= MAX_PAGES): - raise JoinError(f"invalid page counts ({sys_pages}, {gfx_pages})") - total = sys_pages + gfx_pages - end = off + 16 + 8 * total - if end > len(sys_bytes): - raise JoinError("page-map slot array extends past system segment") - slots = struct.unpack_from(f"<{total}Q", sys_bytes, off + 16) - if w0 != 0 or w4 != 0 or pad10 != 0 or pad12 != 0 or any(slots): - raise JoinError("non-zero reserved or runtime slot word in page-map header") - return { - "offset": off, - "end": end, - "system_pages": sys_pages, - "graphics_pages": gfx_pages, - } - - -class ModelSystemPages: - """Track the existing model-map exception to the 64-byte scanned-stream cutoff. - - Only a map readable in the first, full-sized model page establishes a run. Callers supply their - framing checks. Archive and indexed-folder scans check recorded boundaries; loose folders - treat their ordered files as contiguous. No payload is retained. - """ - - def __init__(self): - self.remaining = 0 - - def reset(self): - self.remaining = 0 - - def minimum_size(self, adjacent): - return 1 if adjacent and self.remaining == 1 else 64 - - def accept(self, data, *, adjacent, root_framed): - previous = self.remaining - self.reset() - if not data or len(data) % 65536: - return - if adjacent and previous: - self.remaining = previous - 1 - elif root_framed and classify_system_root(data) in ("drawable", "drawable_dict", "fragment"): - try: - self.remaining = parse_page_map(data)["system_pages"] - 1 - except JoinError: - pass # The full join still checks maps that extend into another system page. - - -def _check_cstring(sys_bytes, ptr_at, skip=0): - """Validate that a name pointer resolves to printable ASCII without returning the name.""" - p = _u64(sys_bytes, ptr_at) - if not is_sys_ptr(p): - raise JoinError(f"invalid string pointer at +0x{ptr_at:x}") - start = (p - SYS_BASE) + skip - if start < 0 or start >= len(sys_bytes): - raise JoinError("string pointer outside system segment") - window = sys_bytes[start:min(len(sys_bytes), start + 256)] - nul = window.find(0) - if not 0 < nul < 256: - raise JoinError("unterminated or empty string in system segment") - raw = window[:nul] - try: - text = raw.decode("utf-8") - except UnicodeDecodeError as exc: - raise JoinError("non-UTF-8 bytes in string") from exc - if any(ord(ch) < 0x20 or ord(ch) == 0x7F for ch in text): - raise JoinError("control character in string") - return start + nul + 1 - - -def _validate_meshlet_buffer(gfx_bytes, ib_off, ib_bytes, desc_clusters, desc_tris, desc_refs, desc_binding): - """Validate a pointed-to meshlet group inside the joined graphics segment.""" - if ib_off < 0 or ib_off + ib_bytes > len(gfx_bytes) or ib_bytes < 32: - raise JoinError("index buffer outside graphics segment") - count_flags = _u32(gfx_bytes, ib_off) - bone_palette = (count_flags & 0x40000000) != 0 - clusters = count_flags & (0xFFFF if bone_palette else 0x7FFFFFFF) - tris = _u32(gfx_bytes, ib_off + 4) - refs = _u32(gfx_bytes, ib_off + 8) - palette_no_marker = (desc_binding & 0xFF) == 0 and (count_flags & 0xFFFF0000) == 0xC0000000 - if not ( - 0 < clusters <= 2048 - and 0 < tris <= 65535 - and 0 < refs <= 65535 - and clusters == desc_clusters - and tris == desc_tris - and refs == desc_refs - and (((desc_binding & 0x80000000) != 0) == bone_palette) - and (not bone_palette or (desc_binding & 0xFF) == 0x80 or palette_no_marker) - ): - raise JoinError("meshlet group header disagrees with system descriptor") - - ref_size = 2 if (count_flags & 0x80000000) else 4 - tri_at = ib_off + 12 + clusters * 16 - refs_at = tri_at + tris * 4 - pal_at = refs_at + refs * ref_size - end_at = pal_at + (clusters * 2 if bone_palette else 0) - if end_at > ib_off + ib_bytes: - raise JoinError("meshlet payload exceeds index buffer allocation") - - acc_refs = 0 - acc_tris = 0 - for c_idx in range(clusters): - rec_at = ib_off + 12 + c_idx * 16 - packed = _u32(gfx_bytes, rec_at) - offsets = _u32(gfx_bytes, rec_at + 4) - c_verts = (packed & 0x7F) + 1 - c_tris = ((packed >> 7) & 0xFF) + 1 - v_start = offsets & 0xFFFF - t_start = offsets >> 16 - if v_start != acc_refs or t_start != acc_tris: - raise JoinError("meshlet running offsets do not match accumulated counts") - if c_verts > refs - v_start or c_tris > tris - t_start: - raise JoinError("meshlet counts exceed group totals") - for t_word in struct.unpack_from(f"<{c_tris}I", gfx_bytes, tri_at + t_start * 4): - if (t_word >> 21) != c_idx: - raise JoinError("packed triangle cluster id mismatch") - if ( - (t_word & 0x7F) >= c_verts - or ((t_word >> 7) & 0x7F) >= c_verts - or ((t_word >> 14) & 0x7F) >= c_verts - ): - raise JoinError("packed triangle local index out of range") - acc_refs += c_verts - acc_tris += c_tris - - if acc_refs != refs or acc_tris != tris: - raise JoinError("meshlet sums do not match group header") - - if ref_size == 2: - max_ref = max(struct.unpack_from(f"<{refs}H", gfx_bytes, refs_at)) - else: - max_ref = max(struct.unpack_from(f"<{refs}I", gfx_bytes, refs_at)) - return max_ref, bone_palette - - -def inspect_model_resource(sys_bytes, gfx_bytes, gfx_page_sizes): - """Validate a joined (system, graphics) model resource and return structural totals.""" - if len(sys_bytes) > MAX_SYS: - raise JoinError("system segment exceeds limit") - if len(gfx_bytes) < 1 or len(gfx_bytes) > MAX_GFX: - raise JoinError("graphics segment empty or exceeds limit") - - pm = parse_page_map(sys_bytes) - if pm["graphics_pages"] < 1: - raise JoinError("model resource declares zero graphics pages") - if len(gfx_page_sizes) != pm["graphics_pages"] or sum(gfx_page_sizes) != len(gfx_bytes): - raise JoinError("graphics stream list disagrees with declared graphics_pages") - - kind = classify_system_root(sys_bytes) - if kind not in ("drawable", "drawable_dict", "fragment"): - raise JoinError(f"not a model resource ({kind})") - - req_sys = pm["end"] - req_gfx = 0 - - def s_off(ptr_at, size): - nonlocal req_sys - p = _u64(sys_bytes, ptr_at) - if not is_sys_ptr(p): - raise JoinError(f"expected system pointer at +0x{ptr_at:x}") - at = p - SYS_BASE - if at < 0 or at + size > len(sys_bytes): - raise JoinError(f"system pointer target +0x{at:x}..+0x{at + size:x} outside system segment") - if at + size > req_sys: - req_sys = at + size - return at - - def g_off(ptr_at, size): - nonlocal req_gfx - p = _u64(sys_bytes, ptr_at) - if not is_gfx_ptr(p): - raise JoinError(f"expected graphics pointer at +0x{ptr_at:x}") - at = p - GFX_BASE - if size <= 0 or at < 0 or at + size > len(gfx_bytes): - raise JoinError(f"graphics pointer target +0x{at:x}..+0x{at + size:x} outside graphics segment") - if at + size > req_gfx: - req_gfx = at + size - return at - - drawable_offsets = [] - if kind == "drawable_dict": - req_sys = max(req_sys, 64) - count = _u16(sys_bytes, 56) - hashes = s_off(32, count * 4) - ptrs = s_off(48, count * 8) - if hashes < 64 or ptrs < 64: - raise JoinError("dictionary tables overlap root header") - seen_children = set() - for i in range(count): - child = s_off(ptrs + i * 8, 192) - if child < 64 or child in seen_children or not looks_like_drawable_header(sys_bytes, child, embedded=True): - raise JoinError("invalid embedded drawable header in dictionary") - seen_children.add(child) - req_sys = max(req_sys, _check_cstring(sys_bytes, child + 168)) - drawable_offsets.append(child) - elif kind == "fragment": - req_sys = max(req_sys, 176) - req_sys = max(req_sys, _check_cstring(sys_bytes, 168)) - child = s_off(24, 192) - if child == 0 or not looks_like_drawable_header(sys_bytes, child, embedded=True): - raise JoinError("invalid fragment primary drawable header") - drawable_offsets.append(child) - else: - req_sys = max(req_sys, 192) - drawable_offsets.append(0) - - prim_geos = prim_verts = prim_tris = 0 - all_geos = all_verts = all_tris = 0 - bone_bound_drawables = 0 - total_meshes_checked = 0 - - for d_off in drawable_offsets: - req_sys = max(req_sys, d_off + 192) - if _u64(sys_bytes, d_off + 168) != 0: - req_sys = max(req_sys, _check_cstring(sys_bytes, d_off + 168)) - - drawable_bone_bound = False - seen_lods = set() - for lod_idx, lod_field in enumerate((80, 88, 96, 104)): - if _u64(sys_bytes, d_off + lod_field) == 0: - if lod_idx == 0: - raise JoinError("drawable missing primary LOD (+0x50)") - continue - lod = s_off(d_off + lod_field, 16) - if lod in seen_lods: - continue - seen_lods.add(lod) - model_count = _u16(sys_bytes, lod + 8) - if not (0 < model_count <= 256 and model_count == _u16(sys_bytes, lod + 10)): - raise JoinError("invalid LOD model array count") - model_ptrs = s_off(lod, model_count * 8) - seen_models = set() - seen_geos = set() - - for mi in range(model_count): - model = s_off(model_ptrs + mi * 8, 56) - if model in seen_models: - raise JoinError("duplicate model pointer in LOD") - seen_models.add(model) - geo_count = _u16(sys_bytes, model + 16) - if not ( - 0 < geo_count <= 1024 - and geo_count == _u16(sys_bytes, model + 18) == _u16(sys_bytes, model + 54) - ): - raise JoinError("inconsistent model geometry count") - bone_count = _u16(sys_bytes, model + 20) - if bone_count > 4096: - raise JoinError("model bone count out of range") - if lod_idx == 0 and bone_count > 0: - drawable_bone_bound = True - geo_ptrs = s_off(model + 8, geo_count * 8) - s_off(model + 24, (geo_count + (1 if geo_count > 1 else 0)) * 32) - if _u64(sys_bytes, model + 40) != 0: - s_off(model + 40, bone_count * 4 if bone_count > 0 else 1) - - for gi in range(geo_count): - total_meshes_checked += 1 - if total_meshes_checked > 4096: - raise JoinError("mesh count limit exceeded") - geo = s_off(geo_ptrs + gi * 8, 160) - if geo in seen_geos: - raise JoinError("duplicate geometry pointer in LOD") - seen_geos.add(geo) - - vb = s_off(geo + 8, 80) - fvf = s_off(vb + 64, 320) - flags = _u32(sys_bytes, fvf + 0x138) - vcount = flags >> 10 - pos_size = sys_bytes[fvf + 0xD0] - pos_fmt = sys_bytes[fvf + 0x104] - if not ( - (flags & 1) != 0 - and 0 < vcount <= 1_000_000 - and (pos_size, pos_fmt) in ((8, 16), (12, 6)) - ): - raise JoinError("unsupported FVF vertex count or position format") - - vb_stride = _u16(sys_bytes, vb + 12) - vb_bytes = _u32(sys_bytes, vb + 8) * vb_stride - pos_off = _u32(sys_bytes, fvf) - if not ( - 0 < vb_stride <= 32 - and vb_bytes > 0 - and pos_off >= (128 if (pos_size, pos_fmt) == (8, 16) else 96) - and pos_off <= vb_bytes - and vcount * pos_size <= vb_bytes - pos_off - ): - raise JoinError("invalid vertex buffer span") - vb_gfx = g_off(vb + 24, vb_bytes) - if _u64(sys_bytes, vb + 40) != 0: - s_off(vb + 40, 32) - vb_head = _u32(gfx_bytes, vb_gfx) - expected_tag = 0x42 if (pos_size, pos_fmt) == (8, 16) else 0x63 - if (vb_head & 0x7F) != expected_tag: - raise JoinError("vertex block tag disagrees with FVF position format") - - desc = s_off(geo + 64, 16) - ib = s_off(desc, 64) - ib_stride = _u16(sys_bytes, ib + 12) - ib_bytes = _u32(sys_bytes, ib + 8) * ib_stride - if ib_stride != 4 or ib_bytes < 32: - raise JoinError("invalid index buffer stride or size") - ib_gfx = g_off(ib + 24, ib_bytes) - if _u64(sys_bytes, ib + 40) != 0: - s_off(ib + 40, 32) - - d_clusters = _u16(sys_bytes, desc + 8) - d_tris = _u16(sys_bytes, desc + 10) - d_binding = _u32(sys_bytes, desc + 12) - d_refs = (d_binding >> 8) & 0x7FFFFF - max_ref, bone_pal = _validate_meshlet_buffer( - gfx_bytes, ib_gfx, ib_bytes, d_clusters, d_tris, d_refs, d_binding - ) - if max_ref >= vcount: - raise JoinError("meshlet vertex reference exceeds FVF vertex count") - if lod_idx == 0 and bone_pal: - drawable_bone_bound = True - - all_geos += 1 - all_verts += vcount - all_tris += d_tris - if lod_idx == 0: - prim_geos += 1 - prim_verts += vcount - prim_tris += d_tris - - # Shader group (+16): shader constant buffer (+48), embedded texture dictionary (+8), materials (+16/+24) - sg = s_off(d_off + 16, 64) - if _u64(sys_bytes, sg + 48) != 0: - sdesc = s_off(sg + 48, 32) - sbuf = s_off(sdesc, 64) - sstride = _u16(sys_bytes, sbuf + 12) - sbytes = _u32(sys_bytes, sbuf + 8) * sstride - if not (0 < sstride <= 32 and sbytes > 0): - raise JoinError("invalid shader buffer extent") - g_off(sbuf + 24, sbytes) - if _u64(sys_bytes, sg + 8) != 0: - txd = s_off(sg + 8, 64) - tcount = _u16(sys_bytes, txd + 56) - if tcount != _u16(sys_bytes, txd + 58) or tcount > 4096: - raise JoinError("invalid embedded texture dictionary count") - if tcount > 0: - s_off(txd + 32, tcount * 4) - tarr = s_off(txd + 48, tcount * 8) - for ti in range(tcount): - tex = s_off(tarr + ti * 8, 112) - eb = _u16(sys_bytes, tex + 0x0C) - tbytes = _u32(sys_bytes, tex + 0x08) * eb - if eb == 0 or tbytes <= 0: - raise JoinError("invalid embedded texture allocation") - g_off(tex + 0x18, tbytes) - - mat_count = _u16(sys_bytes, sg + 24) - if mat_count > 0: - if mat_count > 512 or mat_count != _u16(sys_bytes, sg + 26): - raise JoinError("invalid material array count") - mat_ptrs = s_off(sg + 16, mat_count * 8) - for mi in range(mat_count): - sh = s_off(mat_ptrs + mi * 8, 64) - if _u32(sys_bytes, sh + 4) == 0x6D657461: - info = s_off(sh + 32, 8) - params = sys_bytes[info + 4] - texs = sys_bytes[info + 1] - s_off(sh + 32, 8 + params * 8) - if texs > 0: - tarr = s_off(sh + 16, texs * 8) - for tj in range(texs): - if _u64(sys_bytes, tarr + tj * 8) != 0: - tex_ref = s_off(tarr + tj * 8, 80) - if _u64(sys_bytes, tex_ref + 48) != 0: - asset = s_off(tex_ref + 48, 16) - if asset >= 16 and _u32(sys_bytes, asset - 16) == 6: - req_sys = max(req_sys, asset + 16) - - if _u64(sys_bytes, d_off + 176) != 0: - rend = s_off(d_off + 176, 80) - for li in range(5): - lst = rend + li * 16 - lcnt = _u16(sys_bytes, lst + 8) - if lcnt != _u16(sys_bytes, lst + 10) or (li < 4 and lcnt > 4096): - raise JoinError("invalid renderer list count") - if lcnt > 0: - s_off(lst, lcnt * (4 if li < 4 else 80)) - - if drawable_bone_bound: - bone_bound_drawables += 1 - - if req_gfx <= 0: - raise JoinError("no graphics buffers referenced by drawable") - prev_gfx_bytes = sum(gfx_page_sizes[:-1]) - if req_gfx <= prev_gfx_bytes: - raise JoinError("final declared graphics page is not reached by any buffer") - - return { - "kind": kind, - "page_map_offset": pm["offset"], - "system_pages": pm["system_pages"], - "graphics_pages": pm["graphics_pages"], - "required_system_bytes": req_sys, - "required_graphics_bytes": req_gfx, - "drawables": len(drawable_offsets), - "dictionary_children": len(drawable_offsets) if kind == "drawable_dict" else 0, - "primary_geometries": prim_geos, - "primary_vertices": prim_verts, - "primary_triangles": prim_tris, - "all_lod_geometries": all_geos, - "all_lod_vertices": all_verts, - "all_lod_triangles": all_tris, - "bone_bound_drawables": bone_bound_drawables, - } - - -def _inflate_exact(buf, offset, end, max_inflate, *, min_inflate=64): - """Inflate one zlib stream at `offset` inside `buf[offset:end]`.""" - d = zlib.decompressobj() - p = offset - total = 0 - chunks = [] - try: - while not d.eof and p < end: - block = buf[p:min(p + DECOMPRESS_CHUNK, end)] - if not block: - break - p += len(block) - while block and not d.eof: - chunk = d.decompress(block, DECOMPRESS_CHUNK) - block = d.unconsumed_tail - if chunk: - total += len(chunk) - if total > max_inflate: - return None, 0, True - chunks.append(chunk) - if not block: - break - except zlib.error: - return None, 0, False - if not d.eof or total < min_inflate: - return None, 0, False - used = p - offset - len(d.unused_data) - if used <= 0: - return None, 0, False - return b"".join(chunks), used, False - - -def join_streams(streams, get_payload, require_archive_framing=True): - """Join model system streams to graphics streams over an indexed stream list.""" - resources = [] - tex_dicts_skipped = 0 - non_model_skipped = 0 - joined_4240 = 0 - total_4240 = sum(1 for s in streams if s["kind"] == "zlib" and s["head_tag"] == "0x4042") - - idx = 0 - n = len(streams) - while idx < n: - st = streams[idx] - if st["kind"] != "zlib" or not st["zero_prefix"] or st["is_0drp"] or not is_sys_ptr(st["u64_at_8"]): - idx += 1 - continue - if require_archive_framing and not (st["align4k_plus16"] and st["pre16_zero"]): - idx += 1 - continue - - first_data = get_payload(idx) - root_hint = classify_system_root(first_data) - # Assemble system continuation streams if u64@+0x08 points into a subsequent 64 KiB block. - p8_off = st["u64_at_8"] - SYS_BASE - sys_chunks = [first_data] - cur = idx - framing_err = None - while p8_off + 16 > sum(len(c) for c in sys_chunks): - if len(sys_chunks) >= MAX_PAGES: - framing_err = "system page count exceeds limit before page-map header" - break - if (len(sys_chunks[-1]) & 0xFFFF) != 0: - framing_err = "non-64KiB system page before continuation" - break - cur += 1 - if cur >= n or streams[cur]["kind"] != "zlib": - framing_err = "missing system continuation stream" - break - if require_archive_framing and (not streams[cur]["gap_zero"] or streams[cur]["gap_len"] >= 16): - framing_err = "non-zero or wide gap inside system continuation" - break - sys_chunks.append(get_payload(cur)) - - if framing_err is not None: - if root_hint in ("drawable", "drawable_dict", "fragment"): - resources.append(_failed_row(st, root_hint, framing_err)) - idx += 1 - continue - - sys_probe = b"".join(sys_chunks) - try: - pm = parse_page_map(sys_probe) - except JoinError as exc: - kind_guess = classify_system_root(sys_probe) - if kind_guess in ("drawable", "drawable_dict", "fragment"): - resources.append(_failed_row(st, kind_guess, str(exc))) - idx += 1 - continue - - sp = pm["system_pages"] - gp = pm["graphics_pages"] - if sp < len(sys_chunks) or idx + sp > n: - kind_guess = classify_system_root(sys_probe) - if kind_guess in ("drawable", "drawable_dict", "fragment"): - resources.append(_failed_row(st, kind_guess, "declared system_pages truncated at archive end")) - idx += 1 - continue - - # Append any remaining declared system pages beyond sys_chunks. - for extra_idx in range(idx + len(sys_chunks), idx + sp): - if (len(sys_chunks[-1]) & 0xFFFF) != 0: - framing_err = "non-64KiB non-final system stream" - break - if streams[extra_idx]["kind"] != "zlib": - framing_err = "non-zlib stream inside declared system_pages" - break - if require_archive_framing and (not streams[extra_idx]["gap_zero"] or streams[extra_idx]["gap_len"] >= 16): - framing_err = "non-zero or wide gap inside declared system_pages" - break - sys_chunks.append(get_payload(extra_idx)) - - sys_bytes = b"".join(sys_chunks) - rkind = classify_system_root(sys_bytes) - if rkind not in ("drawable", "drawable_dict", "fragment"): - if framing_err is None and idx + sp + gp <= n and all( - streams[idx + k]["kind"] == "zlib" - and (not require_archive_framing or (streams[idx + k]["gap_zero"] and streams[idx + k]["gap_len"] < 16)) - for k in range(1, sp + gp) - ): - if rkind == "texture_dict": - tex_dicts_skipped += 1 - else: - non_model_skipped += 1 - idx += sp + gp - else: - idx += 1 - continue - - if framing_err is not None: - resources.append(_failed_row(st, rkind, framing_err, sp, gp)) - idx += 1 - continue - - if gp < 1 or idx + sp + gp > n: - resources.append(_failed_row(st, rkind, "missing declared graphics streams", sp, gp)) - idx += 1 - continue - - gfx_meta = streams[idx + sp:idx + sp + gp] - gfx_chunks = [] - for gi, gst in enumerate(gfx_meta): - if gst["kind"] != "zlib": - framing_err = "non-zlib stream inside declared graphics_pages" - break - if require_archive_framing and (not gst["gap_zero"] or gst["gap_len"] >= 16): - framing_err = "non-zero or wide gap before graphics stream" - break - gdata = get_payload(idx + sp + gi) - if gi + 1 < gp and (len(gdata) & 0xFFFF) != 0: - framing_err = "non-64KiB non-final graphics stream" - break - gfx_chunks.append(gdata) - - if framing_err is not None: - resources.append(_failed_row(st, rkind, framing_err, sp, gp)) - idx += 1 - continue - - gfx_bytes = b"".join(gfx_chunks) - gfx_sizes = [len(c) for c in gfx_chunks] - try: - checked = inspect_model_resource(sys_bytes, gfx_bytes, gfx_sizes) - except JoinError as exc: - resources.append(_failed_row(st, rkind, str(exc), sp, gp)) - idx += 1 - continue - - sys_meta = streams[idx:idx + sp] - joined_4240 += sum(1 for gst in gfx_meta if gst["head_tag"] == "0x4042") - resources.append({ - "offset": st["offset"], - "stream_index": st["stream_index"], - "kind": checked["kind"], - "complete": True, - "error": None, - "page_map_offset": checked["page_map_offset"], - "system_pages": sp, - "graphics_pages": gp, - "system_streams": [ - { - "stream_index": s["stream_index"], - "offset": s["offset"], - "stored": s["stored"], - "size": s["size"], - } - for s in sys_meta - ], - "graphics_streams": [ - { - "stream_index": s["stream_index"], - "offset": s["offset"], - "stored": s["stored"], - "size": s["size"], - "head": s["head_tag"], - } - for s in gfx_meta - ], - "system_stored": sum(s["stored"] for s in sys_meta), - "system_bytes": len(sys_bytes), - "graphics_stored": sum(s["stored"] for s in gfx_meta), - "graphics_bytes": len(gfx_bytes), - "required_system_bytes": checked["required_system_bytes"], - "required_graphics_bytes": checked["required_graphics_bytes"], - "drawables": checked["drawables"], - "dictionary_children": checked["dictionary_children"], - "primary_geometries": checked["primary_geometries"], - "primary_vertices": checked["primary_vertices"], - "primary_triangles": checked["primary_triangles"], - "all_lod_geometries": checked["all_lod_geometries"], - "all_lod_vertices": checked["all_lod_vertices"], - "all_lod_triangles": checked["all_lod_triangles"], - "bone_bound_drawables": checked["bone_bound_drawables"], - }) - idx += sp + gp - - stats = { - "total_4240_starts": total_4240, - "joined_4240_starts": joined_4240, - "texture_dictionaries_skipped": tex_dicts_skipped, - "non_model_system_resources_skipped": non_model_skipped, - } - return resources, stats - - -def _failed_row(st, kind, error, sp=0, gp=0): - return { - "offset": st["offset"], - "stream_index": st["stream_index"], - "kind": kind, - "complete": False, - "error": error, - "page_map_offset": (st["u64_at_8"] - SYS_BASE) if is_sys_ptr(st["u64_at_8"]) else None, - "system_pages": sp, - "graphics_pages": gp, - "system_streams": [ - { - "stream_index": st["stream_index"], - "offset": st["offset"], - "stored": st["stored"], - "size": st["size"], - } - ], - "graphics_streams": [], - "system_stored": st["stored"], - "system_bytes": st["size"], - "graphics_stored": 0, - "graphics_bytes": 0, - "required_system_bytes": 0, - "required_graphics_bytes": 0, - "drawables": 0, - "dictionary_children": 0, - "primary_geometries": 0, - "primary_vertices": 0, - "primary_triangles": 0, - "all_lod_geometries": 0, - "all_lod_vertices": 0, - "all_lod_triangles": 0, - "bone_bound_drawables": 0, - } - - -def _summarise(resources, streams, stats, mode, source, skipped, elapsed): - joined = [r for r in resources if r["complete"]] - by_kind = {} - page_shapes = {} - for r in joined: - by_kind[r["kind"]] = by_kind.get(r["kind"], 0) + 1 - shape = f"{r['system_pages']}+{r['graphics_pages']}" - page_shapes[shape] = page_shapes.get(shape, 0) + 1 - return { - "mode": mode, - "source": source, - "streams": len(streams), - "zlib_streams": sum(1 for s in streams if s["kind"] == "zlib"), - "bink2_files": sum(1 for s in streams if s["kind"] == "bink2"), - "skipped_candidates": skipped, - "model_candidates": len(resources), - "joined_resources": len(joined), - "unjoined_candidates": len(resources) - len(joined), - "by_kind": dict(sorted(by_kind.items())), - "page_shapes": dict(sorted(page_shapes.items())), - "model_system_streams": sum(r["system_pages"] for r in joined), - "model_graphics_streams": sum(r["graphics_pages"] for r in joined), - "graphics_4240_starts_total": stats["total_4240_starts"], - "graphics_4240_starts_joined": stats["joined_4240_starts"], - "drawables": sum(r["drawables"] for r in joined), - "dictionary_children": sum(r["dictionary_children"] for r in joined), - "standalone_models": sum(1 for r in joined if r["kind"] in ("drawable", "fragment")), - "fragments": sum(1 for r in joined if r["kind"] == "fragment"), - "bone_bound_drawables": sum(r["bone_bound_drawables"] for r in joined), - "primary_geometries": sum(r["primary_geometries"] for r in joined), - "primary_vertices": sum(r["primary_vertices"] for r in joined), - "primary_triangles": sum(r["primary_triangles"] for r in joined), - "all_lod_geometries": sum(r["all_lod_geometries"] for r in joined), - "all_lod_vertices": sum(r["all_lod_vertices"] for r in joined), - "all_lod_triangles": sum(r["all_lod_triangles"] for r in joined), - "texture_dictionaries_skipped": stats["texture_dictionaries_skipped"], - "non_model_system_resources_skipped": stats["non_model_system_resources_skipped"], - "elapsed_seconds": round(elapsed, 3), - } - - -def scan_rpf(path, start=None, limit=None, max_inflate=MAX_INFLATE): - """Walk an RPF9 archive data area and join model system pages to graphics pages.""" - t0 = time.time() - file_size = os.path.getsize(path) - if file_size == 0: - raise ValueError("empty file") - if file_size < 8: - raise ValueError("too short for an RPF9 header") - streams = [] - skipped = 0 - with open(path, "rb") as fh: - with mmap.mmap(fh.fileno(), 0, access=mmap.ACCESS_READ) as m: - if m[:4] not in (b"9FPR", b"RPF9"): - raise ValueError("not an RPF9 archive") - first = struct.unpack_from(" file_size: - raise ValueError("RPF9 data offset is outside the archive") - pos = start if start is not None else first - if not 0 <= pos <= file_size: - raise ValueError("start offset is outside the archive") - end = min(file_size, pos + limit) if limit is not None else file_size - last = pos - system_pages = ModelSystemPages() - while pos < end: - found = ZHDR.search(m, pos, end) - if not found: - break - s = found.start() - if m[s:s + 3] == b"KB2": - if s + 0x1C > end: - pos = s + 1 - continue - blen = struct.unpack_from("= 16 and m[s - 16:s] == b"\x00" * 16, - "zero_prefix": False, - "is_0drp": False, - "u64_at_8": 0, - "head_tag": "bink2", - }) - last = pos = s + blen - system_pages.reset() - continue - - adjacent = s == ((last + 15) & ~15) and not any(m[last:s]) - # A declared final system page can be smaller than the minimum for a scanned stream. - data, used, too_big = _inflate_exact( - m, s, end, max_inflate, min_inflate=system_pages.minimum_size(adjacent)) - if data is None: - if too_big: - skipped += 1 - pos = s + 1 - continue - gap = m[last:s] - meta = { - "stream_index": len(streams), - "offset": s, - "stored": used, - "size": len(data), - "kind": "zlib", - "gap_len": len(gap), - "gap_zero": gap.count(0) == len(gap), - "align4k_plus16": (s & 0xFFF) == 0x10, - "pre16_zero": s >= 16 and m[s - 16:s] == b"\x00" * 16, - "zero_prefix": data[:8] == b"\x00" * 8, - "is_0drp": len(data) >= 0x14 and data[0x10:0x14] == b"0DRP", - "u64_at_8": struct.unpack_from("= 16 else 0, - "head_tag": classify_graphics_head(data), - } - streams.append(meta) - system_pages.accept(data, adjacent=adjacent, - root_framed=meta["align4k_plus16"] and meta["pre16_zero"]) - last = pos = s + used - - cache = {} - - def get_payload(s_idx): - if s_idx not in cache: - if len(cache) >= 64: - cache.clear() - meta = streams[s_idx] - payload, _, _ = _inflate_exact(m, meta["offset"], meta["offset"] + meta["stored"], max_inflate, - min_inflate=meta["size"]) - cache[s_idx] = payload - return cache[s_idx] - - resources, stats = join_streams(streams, get_payload, require_archive_framing=True) - - summary = _summarise(resources, streams, stats, "rpf9", path, skipped, time.time() - t0) - return resources, summary - - -def _carve_rows(path): - """Read physical stream boundaries in the order recorded by rpf9_carve.""" - try: - fh = open(os.path.join(path, "index.json"), encoding="utf-8") - except FileNotFoundError: - return None - with fh: - index = json.load(fh) - rows = index.get("files") if isinstance(index, dict) else None - if not isinstance(rows, list): - raise ValueError("index.json requires a files array") - result = {} - last_end = 0 - for row in rows: - if not isinstance(row, dict) or any(type(row.get(k)) is not int for k in ("off", "size", "stored")): - raise ValueError("invalid stream dimensions in index.json") - off, size, stored = row["off"], row["size"], row["stored"] - if off < last_end or min(size, stored) <= 0: - raise ValueError("overlapping or invalid stream in index.json") - last_end = off + stored - bink = row.get("type") == "bink2" - pre = row.get("pre") - if not bink and (not isinstance(pre, str) or - len(pre) != 2 * min(16, off) or not re.fullmatch(r"[0-9a-fA-F]*", pre)): - raise ValueError("invalid predecessor bytes in index.json") - name = f"{off:012x}." + ("bk2" if bink else "bin") - result[name] = (off, size, stored, b"" if bink else bytes.fromhex(pre)) - return result - - -def scan_dir(path, max_inflate=MAX_INFLATE): - """Join already-carved `.bin` / `.bk2` stream files in offset order.""" - t0 = time.time() - streams = [] - files = [] - skipped = 0 - system_pages = ModelSystemPages() - rows = _carve_rows(path) - previous_end = 0 - names = rows if rows is not None else sorted(os.listdir(path)) - for name in names: - full = os.path.join(path, name) - if rows is None and (not os.path.isfile(full) or not name.endswith((".bin", ".bk2"))): - continue - fsize = os.path.getsize(full) - if rows is None: - match = re.match(r"([0-9a-fA-F]{6,})", name) - off = int(match.group(1), 16) if match else len(streams) - stored, gap, gap_zero, pre16_zero = fsize, 0, True, True - else: - off, size, stored, pre = rows[name] - if size != fsize: - raise ValueError(f"{name}: size differs from index.json") - gap = off - previous_end - gap_zero = gap == 0 or (gap <= len(pre) and not any(pre[-gap:])) - pre16_zero = pre == bytes(16) - adjacent = rows is None or (off == ((previous_end + 15) & ~15) and gap_zero) - root_framed = rows is None or ((off & 0xFFF) == 0x10 and pre16_zero) - if name.endswith(".bin") and fsize > max_inflate: - skipped += 1 - system_pages.reset() - continue - minimum = 64 if name.endswith(".bk2") else system_pages.minimum_size(adjacent) - if fsize < minimum: - system_pages.reset() - continue - previous_end = off + stored - with open(full, "rb") as fh: - head = fh.read(32) - # The carver writes raw video as .bk2; a compressed .bin payload can also start with KB2. - is_bink = name.endswith(".bk2") and head[:3] == b"KB2" - if fsize % 65536 == 0 and not is_bink: - # Inspect the model header and map without copying a full page just for this metadata pass. - with mmap.mmap(fh.fileno(), 0, access=mmap.ACCESS_READ) as data: - system_pages.accept(data, adjacent=adjacent, root_framed=root_framed) - else: - system_pages.reset() - if fsize >= 64 and is_bink and len(head) >= 0x1C: - streams.append({ - "stream_index": len(streams), - "offset": off, - "stored": stored, - "size": fsize, - "kind": "bink2", - "gap_len": gap, - "gap_zero": gap_zero, - "align4k_plus16": (off & 0xFFF) == 0x10, - "pre16_zero": pre16_zero, - "zero_prefix": False, - "is_0drp": False, - "u64_at_8": 0, - "head_tag": "bink2", - }) - files.append(None) - continue - streams.append({ - "stream_index": len(streams), - "offset": off, - "stored": stored, - "size": fsize, - "kind": "zlib", - "gap_len": gap, - "gap_zero": gap_zero, - "align4k_plus16": (off & 0xFFF) == 0x10, - "pre16_zero": pre16_zero, - "zero_prefix": head[:8] == b"\x00" * 8, - "is_0drp": len(head) >= 0x14 and head[0x10:0x14] == b"0DRP", - "u64_at_8": struct.unpack_from("= 16 else 0, - "head_tag": classify_graphics_head(head), - }) - files.append(full) - - cache = {} - - def get_payload(s_idx): - if s_idx not in cache: - if len(cache) >= 64: - cache.clear() - with open(files[s_idx], "rb") as fh: - cache[s_idx] = fh.read() - return cache[s_idx] - - resources, stats = join_streams(streams, get_payload, require_archive_framing=rows is not None) - summary = _summarise(resources, streams, stats, "directory", path, skipped, time.time() - t0) - return resources, summary - - -def write_output(path, resources, summary): - """Write JSON or CSV based on the output path extension.""" - ext = os.path.splitext(path)[1].lower() - if ext == ".json": - with open(path, "w", encoding="utf-8", newline="\n") as fh: - json.dump({"summary": summary, "resources": resources}, fh, indent=1) - fh.write("\n") - return - with open(path, "w", encoding="utf-8", newline="") as fh: - writer = csv.DictWriter(fh, fieldnames=COLUMNS, lineterminator="\n") - writer.writeheader() - for r in resources: - gfx_first = ( - f"0x{r['graphics_streams'][0]['offset']:x}" if r["graphics_streams"] else "" - ) - writer.writerow({ - "offset": f"0x{r['offset']:x}", - "stream_index": r["stream_index"], - "kind": r["kind"], - "complete": int(r["complete"]), - "system_pages": r["system_pages"], - "graphics_pages": r["graphics_pages"], - "graphics_first_offset": gfx_first, - "system_stored": r["system_stored"], - "system_bytes": r["system_bytes"], - "graphics_stored": r["graphics_stored"], - "graphics_bytes": r["graphics_bytes"], - "required_system_bytes": r["required_system_bytes"], - "required_graphics_bytes": r["required_graphics_bytes"], - "drawables": r["drawables"], - "primary_geometries": r["primary_geometries"], - "primary_vertices": r["primary_vertices"], - "primary_triangles": r["primary_triangles"], - "all_lod_geometries": r["all_lod_geometries"], - "all_lod_vertices": r["all_lod_vertices"], - "all_lod_triangles": r["all_lod_triangles"], - "error": "" if r["error"] is None else r["error"], - }) - - -def offset_arg(text): - """--start: 0 or more, decimal or 0x hex.""" - try: - value = int(text, 0) - except ValueError: - raise argparse.ArgumentTypeError("must be 0 or more") from None - if value < 0: - raise argparse.ArgumentTypeError("must be 0 or more") - return value - - -def byte_count_arg(text): - """--limit/--max-inflate: at least 1.""" - try: - value = int(text, 0) - except ValueError: - raise argparse.ArgumentTypeError("must be at least 1") from None - if value < 1: - raise argparse.ArgumentTypeError("must be at least 1") - return value - - -def _aliases_input(out_path, source_path): - if os.path.normcase(os.path.realpath(out_path)) == os.path.normcase(os.path.realpath(source_path)): - return True - try: - if os.path.samefile(out_path, source_path): - return True - except OSError: - pass - if os.path.isdir(source_path): - index_path = os.path.join(source_path, "index.json") - if os.path.normcase(os.path.realpath(out_path)) == os.path.normcase(os.path.realpath(index_path)): - return True - if not os.path.isfile(out_path): - return False - if os.path.isfile(index_path) and os.path.samefile(out_path, index_path): - return True - src_root = os.path.normcase(os.path.abspath(source_path)) - target = os.path.normcase(os.path.abspath(out_path)) - if os.path.dirname(target) == src_root and target.endswith((".bin", ".bk2")): - return True - return False - - -def main(argv=None): - ap = argparse.ArgumentParser(description=__doc__.splitlines()[0]) - ap.add_argument("source", help="an .rpf archive or a directory of carved .bin/.bk2 files") - ap.add_argument("out", help="output path ending in .json or .csv") - ap.add_argument("--start", type=offset_arg, help="first byte to scan (default: RPF data start)") - ap.add_argument("--limit", type=byte_count_arg, help="number of bytes to scan") - ap.add_argument("--max-inflate", type=byte_count_arg, default=MAX_INFLATE, - help="skip a stream that inflates above this many bytes (default: 512 MiB)") - ap.add_argument("--quiet", action="store_true") - args = ap.parse_args(argv) - - if os.path.isdir(args.source) and (args.start is not None or args.limit is not None): - ap.error("--start and --limit apply to a single archive, not a directory") - if os.path.isdir(args.out): - ap.error(f"{args.out} is a folder, not a .json or .csv file") - if _aliases_input(args.out, args.source): - ap.error("output must not overwrite the source") - if os.path.splitext(args.out)[1].lower() not in (".json", ".csv"): - ap.error("output path must end in .json or .csv") - folder = os.path.dirname(os.path.abspath(args.out)) - if not os.path.isdir(folder): - ap.error(f"{folder} is not a folder, so {args.out} cannot be written") - - try: - if os.path.isdir(args.source): - resources, summary = scan_dir(args.source, args.max_inflate) - else: - resources, summary = scan_rpf(args.source, args.start, args.limit, args.max_inflate) - except ValueError as exc: - print(f"{args.source}: {exc}", file=sys.stderr) - return 1 - except OSError as exc: - print(f"{args.source}: {exc.strerror or exc}", file=sys.stderr) - return 1 - - try: - write_output(args.out, resources, summary) - except OSError as exc: - print(f"{args.out}: {exc.strerror or exc}", file=sys.stderr) - return 1 - - if not args.quiet: - print(json.dumps(summary, indent=1)) - return 1 if summary["unjoined_candidates"] else 0 - - -if __name__ == "__main__": - try: # a redirected stdout is strict ANSI code page under -I; write '?' for what it cannot encode - sys.stdout.reconfigure(errors="replace") - except (AttributeError, ValueError, OSError): - pass - sys.exit(main()) diff --git a/tools/root_sig_contract.py b/tools/root_sig_contract.py deleted file mode 100644 index 364e38364..000000000 --- a/tools/root_sig_contract.py +++ /dev/null @@ -1,278 +0,0 @@ -r"""Reconcile a root signature against the translator's user-SGPR reads (stdlib only). - -A shader is identified by its index.json entry (user_sgpr_reads from -tools/shader_meta.py); the candidate root signature is a hand-written JSON -file in this tool's format (see --example), never game data. -When a 64-bit pointer read names both source SGPRs in `pair`, they must supply -the low and high DWORDs of the same root address, in that order. - -Usage: - python -I tools/root_sig_contract.py --rootsig - python -I tools/root_sig_contract.py --rootsig --cluster - python -I tools/root_sig_contract.py --rootsig --model console - (rt::rootsig::pack_stage: each shader's stage base, one dword per table; D3D-448) - python -I tools/root_sig_contract.py --example - -Exit code is 0 when every read is compatible, 1 on the first contradiction -(hard fail: a mismatch means every draw/dispatch with that pair is corrupt). -""" -import argparse -import json -import sys - -# Packing order mirrors runtime/src/root_signature.{h,cpp}: constants take -# NumValues dwords, root descriptors and tables take 2 (VA lo/hi), static -# samplers take none. With a stage (--model console) it mirrors pack_stage(): -# from the stage's base, a table takes ONE dword (its 32-bit VA), and the -# SGPRs below the base are the driver's (D3D-448). -STAGE_BASE = {"ps": 8, "vs": 8, "gs": 8, "cs": 4, "ms": 16} -KIND_TO_TYPES = { - "const32": {"constants"}, - "ptr64_lo": {"descriptor", "table"}, - "ptr64_hi": {"descriptor", "table"}, - "ptr32_lo": {"descriptor", "table"}, - "vsharp": {"descriptor", "table"}, - "tsharp": {"descriptor", "table"}, - "ssharp": {"descriptor", "table"}, -} - - -def pack_layout(sig, stage=None): - """Lay out root params into 32 dwords. Returns (dwords, error). - - dwords[i] = {"param": index, "sub": sub-dword, "ptype": ptype}, indexed by SGPR. - stage None: rt::rootsig::pack (from s0, two dwords per table). A stage from - STAGE_BASE: rt::rootsig::pack_stage (from the stage base, one dword per table; - dwords below the base are {"param": None, "sub": 0, "ptype": "driver"}). - error is set (and dwords empty) on spill, cost overflow or bad input: - refuse, never truncate. - """ - if stage is not None and stage not in STAGE_BASE: - return [], f"no console base for stage {stage!r}" - base = STAGE_BASE[stage] if stage is not None else 0 - dwords = [{"param": None, "sub": 0, "ptype": "driver"} for _ in range(base)] - cost = 0 - params = [dict(p) for p in sig.get("params", [])] # normalized copy; input untouched - if len(params) > 64: - return [], "more than 64 root parameters" - for index, p in enumerate(params): - ptype = p.get("type", "") - if ptype == "constants": - count = p.get("count", 0) - if type(count) is not int or count < 1: - return [], f"param {index}: constants need an integer count >= 1" - width, cost_add = count, count - elif ptype in ("cbv", "srv", "uav"): - width, cost_add = 2, 2 - ptype = "descriptor" - elif ptype == "table": - width, cost_add = (1 if stage is not None else 2), 1 - else: - return [], f"param {index}: unknown type {ptype!r}" - cost += cost_add - if cost > 64: - return [], "exceeds the 64-dword D3D12 cost limit" - if len(dwords) + width > 32: - if stage is not None: - return [], (f"param {index} does not fit in the user SGPRs from s{base} " - "(spill array not modelled)") - return [], "needs more than 32 user SGPRs (spill unsupported)" - for sub in range(width): - dwords.append({"param": index, "sub": sub, "ptype": ptype}) - return dwords, "" - - -def _whole_address_copy(sgpr, slot, by_sgpr, dwords): - """True when `sgpr` is one half of a two-dword address slot and the shader reads both halves as const32. - - A shader that builds a buffer descriptor from a root CBV copies its 64-bit VA as two plain dwords; the read - classifier calls those const32 (the FidelityFX programs copy their root CBVs this way at s6..s13, - tools/rootsig_census.py --disasm "whole pairs"). One half alone stays a contradiction.""" - if slot["ptype"] not in ("descriptor", "table") or slot["param"] is None: - return False - other = sgpr + 1 if slot["sub"] == 0 else sgpr - 1 - if not 0 <= other < len(dwords): - return False - pair = dwords[other] - return (pair["param"] == slot["param"] and pair["sub"] == 1 - slot["sub"] - and "const32" in by_sgpr.get(other, [])) - - -def reconcile(shader_reads, dwords): - """Check one shader's reads against the packed layout. - - Returns a list of contradiction strings (empty = compatible). - """ - issues = [] - by_sgpr = {} - for read in shader_reads: - sgpr = read["sgpr"] - if type(sgpr) is not int: # bool is an int subclass, but not a valid SGPR index. - issues.append(f"invalid SGPR index {sgpr!r}: expected an integer") - continue - kind = read["kind"] - if kind in ("ptr64_lo", "ptr64_hi") and "pair" in read: - # shader_meta records the source SGPRs, which need not be neighbours. - # Checking each slot's kind alone accepts a VA spliced from two parameters. - lo = sgpr if kind == "ptr64_lo" else sgpr - 1 - hi = lo + 1 - pair = read["pair"] - if not (pair == [lo, hi] and all(type(i) is int for i in pair) - and 0 <= lo < hi < len(dwords) - and dwords[lo]["ptype"] in ("descriptor", "table") - and dwords[lo]["sub"] == 0 and dwords[hi]["sub"] == 1 - and dwords[lo]["param"] == dwords[hi]["param"]): - issues.append(f"s{sgpr} ({kind}): pair {pair!r} does not name both halves of one root address") - by_sgpr.setdefault(sgpr, []).append(kind) - for sgpr in sorted(by_sgpr): - kinds = by_sgpr[sgpr] - if sgpr < 0 or sgpr >= len(dwords): - issues.append(f"s{sgpr} read but layout has {len(dwords)} dwords") - continue - slot = dwords[sgpr] - if slot["ptype"] == "driver": - # Below the stage base: the driver's block, not a root argument. Constants there are system values - # (the corpus reads s1/s3 that way); an address there would be the spill pointer (section 7). - for kind in kinds: - if kind != "const32": - issues.append(f"s{sgpr} ({kind}) reads the driver block below the stage base as an address " - "(a spill pointer?)") - continue - for kind in kinds: - allowed = KIND_TO_TYPES.get(kind) - if allowed is None: - issues.append(f"s{sgpr}: unknown read kind {kind!r}") - elif kind == "const32" and _whole_address_copy(sgpr, slot, by_sgpr, dwords): - pass # both halves of a root view's 64-bit VA copied as data (into a V#), not loaded through - elif slot["ptype"] not in allowed: - issues.append( - f"s{sgpr} ({kind}) incompatible with param " - f"{slot['param']} ({slot['ptype']})") - elif kind in ("ptr32_lo", "ptr64_lo") and slot["sub"] != 0: - issues.append(f"s{sgpr} ({kind}) reads the high half of the address") - if kind == "ptr64_hi": - lo = dwords[sgpr - 1] if sgpr > 0 else None - if slot["sub"] != 1 or lo is None or lo["param"] != slot["param"] \ - or lo["sub"] != 0: - issues.append(f"s{sgpr} (ptr64_hi) without paired lo dword") - return issues - - -def cluster(shaders): - """Group by read-set shape, using the first shader name to break size ties.""" - groups = {} - for name in sorted(shaders): - reads = shaders[name].get("user_sgpr_reads", []) - shape = tuple(sorted( - ((r["sgpr"], r["kind"]) if type(r["sgpr"]) is int - else (f"invalid:{r['sgpr']!r}", r["kind"]) for r in reads), - key=lambda item: (type(item[0]) is not int, item[0], item[1]))) - groups.setdefault(shape, []).append(name) - ranked = sorted(groups.items(), key=lambda kv: -len(kv[1])) - return [(shape, len(names), names) for shape, names in ranked] - - -def _load_json(path): - try: - with open(path, encoding="utf-8") as f: - return json.load(f) - except (OSError, ValueError) as e: - reason = getattr(e, "strerror", None) or e - raise ValueError(f"cannot read {path}: {reason}") from None - - -def main(): - ap = argparse.ArgumentParser(description="Root-signature vs shader-reads reconciler.") - ap.add_argument("index", nargs="?", help="spirv/index.json") - ap.add_argument("--rootsig", default=None, help="hand-written root-signature JSON") - ap.add_argument("--cluster", action="store_true", help="print read-set shape clustering") - ap.add_argument("--example", action="store_true", help="print an empty hand-written sig template") - ap.add_argument("--model", choices=("s0", "console"), default="s0", - help="s0: rt::rootsig::pack (default); console: rt::rootsig::pack_stage with each shader's " - "own stage base, one dword per table (D3D-448)") - a = ap.parse_args() - if a.example: - print(json.dumps({"version": "1.1", "flags": 0, "params": [ - {"type": "constants", "count": 4, "visibility": "all"}, - {"type": "cbv", "visibility": "vertex"}, - {"type": "table", "ranges": [{"kind": "srv", "count": 8}], - "visibility": "pixel"}], - "static_samplers": []}, indent=2)) - return 0 - if not a.index or not a.rootsig: - ap.error("index.json and --rootsig are required (or --example)") - try: - index = _load_json(a.index) - sig = _load_json(a.rootsig) - except ValueError as e: - print(f"ERROR: {e}", file=sys.stderr) - return 2 - if not isinstance(index, dict): - print(f"ERROR: {a.index}: expected a JSON object of shader -> metadata entries", file=sys.stderr) - return 2 - if any(not isinstance(entry, dict) for entry in index.values()): - print(f"ERROR: {a.index}: each shader entry must be a JSON object", file=sys.stderr) - return 2 - if not isinstance(sig, dict): - print(f"ERROR: {a.rootsig}: expected a JSON object root signature", file=sys.stderr) - return 2 - params = sig.get("params", []) - if not isinstance(params, list): - print(f"ERROR: {a.rootsig}: 'params' must be a JSON array", file=sys.stderr) - return 2 - if any(not isinstance(p, dict) for p in params): - print(f"ERROR: {a.rootsig}: each param must be a JSON object", file=sys.stderr) - return 2 - for name in sorted(index): - reads = index[name].get("user_sgpr_reads", []) - if not isinstance(reads, list): - print(f"ERROR: {a.index}: {name}: 'user_sgpr_reads' must be a JSON array", file=sys.stderr) - return 2 - for read in reads: - if not isinstance(read, dict) or "sgpr" not in read or "kind" not in read: - print(f"ERROR: {a.index}: {name}: each read needs 'sgpr' and 'kind' fields", - file=sys.stderr) - return 2 - if not isinstance(read["kind"], str): - print(f"ERROR: {a.index}: {name}: each read kind must be a string", - file=sys.stderr) - return 2 - if a.model == "console": - layouts = {} - for stage in sorted({str(entry.get("stage")) for entry in index.values()}): - dwords, error = pack_layout(sig, stage) - if error: - print(f"root signature refused for {stage}: {error}") - return 1 - layouts[stage] = dwords - print(f"{stage}: packed {len(dwords) - STAGE_BASE[stage]} dwords from s{STAGE_BASE[stage]} " - f"({len(sig.get('params', []))} params)") - else: - dwords, error = pack_layout(sig) - if error: - print(f"root signature refused: {error}") - return 1 - print(f"packed {len(dwords)} dwords from {len(sig.get('params', []))} params") - bad = 0 - for name in sorted(index): - reads = index[name].get("user_sgpr_reads", []) - issues = reconcile(reads, layouts[str(index[name].get("stage"))] if a.model == "console" else dwords) - if issues: - bad += 1 - print(f"CONTRADICTION {name}:") - for issue in issues: - print(f" - {issue}") - if a.cluster: - print("read-set shapes (shape -> shaders):") - for shape, count, names in cluster(index)[:20]: - print(f" {count:6} {shape} e.g. {names[0]}") - print(f"{len(index)} shaders: {len(index) - bad} compatible, {bad} contradictory") - return 1 if bad else 0 - - -if __name__ == "__main__": - try: # a redirected stdout is strict ANSI code page under -I; write '?' for what it cannot encode - sys.stdout.reconfigure(errors="replace") - except (AttributeError, ValueError, OSError): - pass - sys.exit(main()) diff --git a/tools/root_spill_census.py b/tools/root_spill_census.py deleted file mode 100644 index 9da98c0b2..000000000 --- a/tools/root_spill_census.py +++ /dev/null @@ -1,187 +0,0 @@ -r"""Census of root-signature spill evidence in the translated corpus (stdlib only). - -Answers D3D-315's measuring half (docs/d3d12_vulkan.md section 3.5, "Root signature larger than 32 dwords"): does any -shader in the corpus read a root-signature spill pointer, and how close does each stage come to the 32 user SGPRs? - -On the console's register-based ABI the shader compiler decides the spill (`__XB_GetRootSignatureSpillPointer`), so -a shader whose root signature spilled must read a spill pointer from its user data. For compute that pointer was -measured at s[0:1], below the stage's first root-argument SGPR (section 7). This tool counts, per stage: - - * spill-pointer candidates: user-SGPR reads used as an address (ptr32_lo, ptr64_lo, ptr64_hi) below the stage - base (the census bases ps=8 vs=8 gs=8 cs=4 ms=16; --base overrides the stages it names and keeps the others). - A shader with none of them has no pointer a spill could sit behind in that block; - * the highest user SGPR each shader reads, and what that read is (a constant or an address); - * where index.json records it (user_sgprs, the RSRC2 USER_SGPR count; compute today): the largest count and the - root-argument dwords that leaves above the base; - * with --carve : how many shader containers carry an RTS0 part (a root signature) at all. - -What it does NOT measure: the root signatures themselves. The game builds them at run time; without RTS0 parts in -the containers they can only be dumped from the executable. A spill hidden behind a pointer at or above the base -(a root parameter the compiler happens to address like a table) is indistinguishable here from a table. - -It reads only index files (user_sgpr_reads, user_sgprs and stage from tools/shader_meta.py; the parts table from -tools/shader_carve.py): no game bytes, and it prints counts only. - -Usage: - python -I tools/root_spill_census.py [--carve ] [--json OUT] - python -I tools/root_spill_census.py --expect-no-spill - (exit 1 if any stage has a spill-pointer candidate) -""" -import argparse -import json -import os -import sys -from collections import Counter, defaultdict - -sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) -from report_paths import same_report_path # noqa: E402 - -POINTER_KINDS = ("ptr32_lo", "ptr64_lo", "ptr64_hi") -DEFAULT_BASE = {"ps": 8, "vs": 8, "gs": 8, "cs": 4, "ms": 16} -USER_SGPRS = 32 - - -def census(index, base=None, carve=None): - """index: spirv/index.json as a dict; base: {stage: first root-argument SGPR}; carve: dxbc/index.json (a list of - entries with a "parts" table) or None. Returns a summary dict of counts.""" - base = DEFAULT_BASE if base is None else base - shaders = Counter() - spill = defaultdict(Counter) # stage -> "sN:kind" -> shaders - spill_shaders = Counter() # stage -> shaders with at least one candidate - highest = defaultdict(Counter) # stage -> highest SGPR read -> shaders - highest_kind = defaultdict(Counter) # stage -> kind of that read -> shaders - user_sgprs = defaultdict(Counter) # stage -> RSRC2 USER_SGPR count -> shaders (where recorded) - for entry in index.values(): - if not isinstance(entry, dict): - continue - stage = entry.get("stage", "?") - shaders[stage] += 1 - reads = [r for r in entry.get("user_sgpr_reads") or [] if isinstance(r.get("sgpr"), int)] - b = base.get(stage) - found = set() - if b is not None: - for r in reads: - if r["sgpr"] < b and r.get("kind") in POINTER_KINDS: - found.add(f"s{r['sgpr']}:{r['kind']}") - for key in found: - spill[stage][key] += 1 - if found: - spill_shaders[stage] += 1 - if reads: - top = max(r["sgpr"] for r in reads) - highest[stage][top] += 1 - kinds = {r.get("kind") for r in reads if r["sgpr"] == top} - highest_kind[stage]["pointer" if kinds & set(POINTER_KINDS) else "/".join(sorted(map(str, kinds)))] += 1 - count = entry.get("user_sgprs") - if isinstance(count, int): - user_sgprs[stage][count] += 1 - out = {"stages": {}} - for stage in sorted(shaders): - s = { - "shaders": shaders[stage], - "base": base.get(stage), - "spill_pointer_candidates": dict(sorted(spill[stage].items())), - "shaders_with_spill_pointer_candidate": spill_shaders[stage], - "highest_sgpr_read": {f"s{k}": v for k, v in sorted(highest[stage].items())}, - "highest_read_kind": dict(sorted(highest_kind[stage].items())), - "max_highest_sgpr_read": max(highest[stage]) if highest[stage] else None, - } - if user_sgprs[stage]: - top = max(user_sgprs[stage]) - s["user_sgprs"] = {str(k): v for k, v in sorted(user_sgprs[stage].items())} - s["max_user_sgprs"] = top - s["shaders_using_all_user_sgprs"] = user_sgprs[stage][USER_SGPRS] - if base.get(stage) is not None: - s["max_root_dwords"] = max(top - base[stage], 0) - s["root_dwords_available"] = USER_SGPRS - base[stage] - out["stages"][stage] = s - if carve is not None: - entries = carve.values() if isinstance(carve, dict) else carve - containers = [e for e in entries if isinstance(e, dict)] - out["containers"] = len(containers) - out["containers_with_rts0"] = sum(1 for e in containers if "RTS0" in (e.get("parts") or {})) - return out - - -def stage_sgpr(text): - stage, _, value = text.partition("=") - message = f"expected STAGE=SGPR with a nonnegative SGPR: {text!r}" - try: - sgpr = int(value) - except ValueError: - raise argparse.ArgumentTypeError(message) from None - if not stage or sgpr < 0: - raise argparse.ArgumentTypeError(message) - return stage, sgpr - - -def main(argv=None): - ap = argparse.ArgumentParser(description=__doc__.split("\n")[0]) - ap.add_argument("index", help="spirv/index.json written by tools/rdna2spirv.py") - ap.add_argument("--carve", help="dxbc/index.json written by tools/shader_carve.py (counts RTS0 parts)") - ap.add_argument("--base", nargs="*", type=stage_sgpr, default=[], metavar="STAGE=SGPR", - help="first root-argument SGPR for the stages named; the others keep the defaults " - "ps=8 vs=8 gs=8 cs=4 ms=16") - ap.add_argument("--json", help="also write the summary here") - ap.add_argument("--expect-no-spill", action="store_true", - help="exit 1 if any shader reads a spill-pointer candidate") - a = ap.parse_args(argv) - if a.json: - if os.path.isdir(a.json): - ap.error(f"--json {a.json} is a folder, not a file") - for other in (a.index, a.carve): - if other and same_report_path(other, a.json): - ap.error("--json must not overwrite an input index") - if not os.path.exists(a.index): - print(f"ERROR: cannot read {a.index}: no such file", file=sys.stderr) - return 2 - if a.carve and not os.path.exists(a.carve): - print(f"ERROR: cannot read {a.carve}: no such file", file=sys.stderr) - return 2 - with open(a.index, encoding="utf-8-sig") as f: # an index saved with a UTF-8 BOM is still JSON - index = json.load(f) - if not isinstance(index, dict): - ap.error(f"{a.index} is not a translator index (expected a JSON object)") - carve = None - if a.carve: - with open(a.carve, encoding="utf-8-sig") as f: # same for the carve index - carve = json.load(f) - # --base overrides the stages it names and keeps the defaults for the rest, so a partial override never drops - # a stage from the check. - summary = census(index, {**DEFAULT_BASE, **dict(a.base)}, carve) - if "containers" in summary: - print(f"containers: {summary['containers']}, with an RTS0 part: {summary['containers_with_rts0']}") - for stage, s in summary["stages"].items(): - line = (f"{stage}: {s['shaders']} shaders; base s{s['base']}; " if s["base"] is not None - else f"{stage}: {s['shaders']} shaders; no base; ") - line += (f"spill-pointer candidates {s['shaders_with_spill_pointer_candidate']} " - f"{s['spill_pointer_candidates']}; highest read {s['highest_sgpr_read']} " - f"as {s['highest_read_kind']}") - if "max_user_sgprs" in s: - line += f"; user_sgprs up to {s['max_user_sgprs']}" - if "max_root_dwords" in s: - line += f" ({s['max_root_dwords']} of {s['root_dwords_available']} root dwords)" - print(line) - if a.json: - try: - os.makedirs(os.path.dirname(os.path.abspath(a.json)), exist_ok=True) - with open(a.json, "w", encoding="utf-8", newline="\n") as f: - json.dump(summary, f, indent=1, sort_keys=True) - f.write("\n") - except OSError as e: - print(f"error: cannot write {a.json}: {e.strerror or e}", file=sys.stderr) - return 2 - spilled = {st: s["shaders_with_spill_pointer_candidate"] for st, s in summary["stages"].items() - if s["shaders_with_spill_pointer_candidate"]} - if a.expect_no_spill and spilled: - print(f"SPILL POINTER CANDIDATES {spilled}", file=sys.stderr) - return 1 - return 0 - - -if __name__ == "__main__": - try: # a redirected stdout is strict ANSI code page under -I; write '?' for what it cannot encode - sys.stdout.reconfigure(errors="replace") - except (AttributeError, ValueError, OSError): - pass - sys.exit(main()) diff --git a/tools/rootsig_census.py b/tools/rootsig_census.py deleted file mode 100644 index 6c4ce1114..000000000 --- a/tools/rootsig_census.py +++ /dev/null @@ -1,343 +0,0 @@ -r"""Census of the root signatures the package carries next to a shader, and the two packing models (stdlib only). - -No game shader carries its root signature: all 26,503 containers in `shaders.rpf` have `SFI0`, `ISG1`, `OSG1`, `PSV0`, -`HASH`, `DXIL` and `PRIV`, and none has `RTS0`, so a game shader cannot say which root parameters it was compiled -against (docs/d3d12_vulkan.md section 3.5). The 29 compute containers in `amd_fidelityfx_upscaler_xbox.dll` do: each -carries `RTS0` beside its `ACCC`/`FSPX` program, and `tools/fspx_unpack.py` decodes that program's -`COMPUTE_PGM_RSRC2`, whose `USER_SGPR` field is the number of user SGPRs the console launched it with (docs/fspx.md, -kind 0). Those 29 are the only place in the package where a real signature and the dword count the driver supplied -sit next to each other. - -For each signature this reports two spans: - - * `table2`: the layer's model, `rt::rootsig::pack` in `runtime/src/root_signature.{h,cpp}`: a constant takes - `NumValues` dwords, a root descriptor and a descriptor table take two (a 64-bit console VA); - * `table1`: one dword per table pointer, which is the model the corpus census in section 3.5 found in the reads - (pointer SGPRs adjacent at distance 1, and no 64-bit pointer in any PS/VS/CS/MS). - -`--json` carries the numbers and the summary prints the spare dwords per model, so a reader can count how many -signatures each model fits. `--disasm DIR` adds the program's own reads, from a `tools/fspx_unpack.py --disasm` -folder: which user SGPRs it reads, which one it zero-extends into an `s_load` base, and which 64-bit pairs it copies -whole. That is where the tables and the root descriptors surface. - -What it does not measure: which parameter a shader reads. A read set needs `tools/shader_disasm.py` (LLVM_MC) and -`tools/rdna2spirv.py` on the program, and the game's own shaders have no signature to compare it with. - -Usage: - python -I tools/rootsig_census.py [--json OUT] - is a `tools/fspx_unpack.py --out` folder: `.dxbc` per container and `fspx/.json` per program. -""" -import argparse -import glob -import json -import os -import re -import struct -import sys -from collections import Counter - -KNOWN_VERSIONS = {1: "1.0", 2: "1.1", 3: "1.2"} -TYPE_NAMES = {0: "table", 1: "constants", 2: "cbv", 3: "srv", 4: "uav"} -# D3D12_SHADER_VISIBILITY. ALL is 0, so anything else is a stage-specific parameter; compute has no value of its own -# because every compute parameter is ALL. -VISIBILITY_NAMES = {0: "all", 1: "vertex", 2: "hull", 3: "domain", 4: "geometry", 5: "pixel", - 6: "amplification", 7: "mesh"} -VISIBILITY_ALL = 0 -MAX_PARAMS = 64 -MAX_SAMPLERS = 4096 - - -def parts(dxbc): - """{FourCC tag: payload} from a DXBC container, or {} when the container is malformed (as tools/fssm_unpack.py).""" - if len(dxbc) < 32 or dxbc[:4] != b"DXBC": - return {} - count = struct.unpack_from(" len(dxbc): - return {} - off = struct.unpack_from(" len(dxbc): - return {} - size = struct.unpack_from(" len(dxbc): - return {} - out[dxbc[off:off + 4]] = dxbc[off + 8:end] - return out - - -def _u32(payload, off): - if off < 0 or off + 4 > len(payload): - raise ValueError(f"read at 0x{off:x} is past the {len(payload)}-byte payload") - return struct.unpack_from(" MAX_PARAMS: - return None, f"{nparams} root parameters (more than {MAX_PARAMS})" - if nsamplers > MAX_SAMPLERS: - return None, f"{nsamplers} static samplers (absurd)" - flags_v11 = version >= 2 - try: - params = [] - for i in range(nparams): - entry = params_off + 12 * i - dtype = _u32(payload, entry) - visibility = _u32(payload, entry + 4) - offset = _u32(payload, entry + 8) - if dtype not in TYPE_NAMES: - return None, f"parameter {i}: unknown type {dtype}" - p = {"type": TYPE_NAMES[dtype], "visibility": visibility} - if dtype == 1: - p["count"] = _u32(payload, offset + 8) # D3D12_ROOT_CONSTANTS::Num32BitValues - elif dtype in (2, 3, 4): - if flags_v11: - p["flags"] = _u32(payload, offset + 8) # the flags dword exists from 1.1 on - else: - nranges = _u32(payload, offset) - ranges_off = _u32(payload, offset + 4) - if nranges > 1024: - return None, f"parameter {i}: {nranges} descriptor ranges (absurd)" - stride = 24 if flags_v11 else 20 - for j in range(nranges): - # Walk every range so a truncated table is an error here, where it is cheap to say so. - _u32(payload, ranges_off + j * stride + (20 if flags_v11 else 16)) - p["ranges"] = nranges - params.append(p) - samplers = [] - sampler_bytes = (14 if version == 3 else 13) * 4 - for i in range(nsamplers): - base = samplers_off + i * sampler_bytes - _u32(payload, base + sampler_bytes - 4) - samplers.append({"visibility": _u32(payload, base + 48)}) - except ValueError as e: - return None, f"truncated payload: {e}" - return {"version": KNOWN_VERSIONS[version], "raw_version": version, "flags": flags, - "params": params, "static_samplers": samplers}, "" - - -def span(sig, table_dwords=2, visibility=None): - """Dwords the block needs: constants take NumValues, a root descriptor two, a table `table_dwords`. - - `visibility` keeps only the parameters of that D3D12_SHADER_VISIBILITY value, which is what a model that omits - other stages' parameters would pass. - """ - total = 0 - for p in sig["params"]: - if visibility is not None and p["visibility"] != visibility: - continue - if p["type"] == "constants": - total += p.get("count", 0) - elif p["type"] == "table": - total += table_dwords - else: - total += 2 - return total - - -NO_DEST = ("s_cmp", "s_cbranch", "s_endpgm", "s_waitcnt", "s_clause", "s_inst_prefetch", "s_nop", - "s_barrier", "s_sleep", "s_setpc", "s_ttracedata", "s_sendmsg", "s_atc") -_REGISTER = re.compile(r"s\[(\d+):(\d+)\]|(? 1 else [])) - return out - - -def read_scan(asm, user_sgprs): - """The user SGPRs a program reads, the ones it zero-extends into a load base, and the pairs it copies whole. - - A descriptor table is one dword the compiler copies into the low half of a pair, zeroes the high half of and - passes to `s_load` as the base; a root CBV is a 64-bit pair copied whole into an SRD (docs/d3d12_vulkan.md 3.5). - Registers at or above `user_sgprs` (from `fspx/.json`) are scratch, not user data. - """ - ins = instructions(asm) - read, bases, pairs = set(), set(), set() - for i, (op, ops) in enumerate(ins): - for lo, hi in _registers(",".join(ops if op.startswith(NO_DEST) else ops[1:])): - read.update(r for r in range(lo, hi + 1) if r < user_sgprs) - if op == "s_mov_b32" and len(ops) >= 2: - dst, src = _registers(ops[0]), _registers(ops[1]) - if len(dst) == 1 and dst[0][0] == dst[0][1] and len(src) == 1 \ - and src[0][0] == src[0][1] and src[0][0] < user_sgprs: - low = dst[0][0] - window = ins[i + 1:i + 4] - zeroed = any(o == "s_mov_b32" and len(p) >= 2 and _registers(p[0]) == [(low + 1, low + 1)] - and p[1] == "0" for o, p in window) - loaded = any(o.startswith("s_load") and len(p) >= 2 and _registers(p[1]) == [(low, low + 1)] - for o, p in window) - if zeroed and loaded: - bases.add(src[0][0]) - elif op == "s_mov_b64" and len(ops) >= 2: - src = _registers(ops[1]) - if src and src[0][1] == src[0][0] + 1 and src[0][0] < user_sgprs: - pairs.add(src[0][0]) - return {"read": sorted(read), "table_bases": sorted(bases), "whole_pairs": sorted(pairs)} - - -def _read_summary(rows): - """Counts over the rows that carry a read scan; {} when no row does.""" - scans = [r["reads"] for r in rows if "reads" in r] - if not scans: - return {} - return { - "programs": len(scans), - "low_read": sum(1 for s in scans if set(range(4)) & set(s["read"])), - "table_bases": dict(sorted(Counter(b for s in scans for b in s["table_bases"]).items())), - "whole_pairs": dict(sorted(Counter(p for s in scans for p in s["whole_pairs"]).items())), - } - - -def census(root, disasm=None): - """Rows for every container in `root`, joined with the program's measured USER_SGPR count. - - With `disasm`, the `--disasm` folder of tools/fspx_unpack.py, each row also carries the program's reads. - """ - rows, errors = [], [] - for path in sorted(glob.glob(os.path.join(glob.escape(root), "*.dxbc"))): - name = os.path.basename(path)[:-5] - with open(path, "rb") as fh: - chunks = parts(fh.read()) - state_path = os.path.join(root, "fspx", name + ".json") - user_sgprs = None - if os.path.exists(state_path): - try: - with open(state_path, encoding="utf-8") as fh: - user_sgprs = json.load(fh).get("user_sgprs") - if user_sgprs is not None and (type(user_sgprs) is not int or user_sgprs < 0): - raise ValueError(f"user_sgprs must be a non-negative integer, got {user_sgprs!r}") - except (ValueError, AttributeError) as e: - errors.append(f"{state_path}: {e}") - continue - if b"RTS0" not in chunks: - rows.append({"name": name, "error": "no RTS0 part", "user_sgprs": user_sgprs}) - continue - sig, error = parse_rts0(chunks[b"RTS0"]) - if sig is None: - errors.append(f"{name}: {error}") - rows.append({"name": name, "error": error, "user_sgprs": user_sgprs}) - continue - row = {"name": name, "version": sig["version"], "flags": sig["flags"], - "params": sig["params"], "static_samplers": len(sig["static_samplers"]), - "user_sgprs": user_sgprs, - "span_table2": span(sig, 2), "span_table1": span(sig, 1), - "visible_table2": span(sig, 2, VISIBILITY_ALL), "visible_table1": span(sig, 1, VISIBILITY_ALL)} - if user_sgprs is not None: - row["spare_table2"] = user_sgprs - row["span_table2"] - row["spare_table1"] = user_sgprs - row["span_table1"] - asm_path = os.path.join(disasm, name + ".s") if disasm else None - if asm_path and os.path.exists(asm_path): - with open(asm_path, encoding="utf-8") as fh: - row["reads"] = read_scan(fh.read(), user_sgprs) - rows.append(row) - return rows, errors - - -def summarize(rows): - ok = [r for r in rows if "error" not in r] - params = [p for r in ok for p in r["params"]] - return { - "containers": len(rows), - "parsed": len(ok), - "errors": len(rows) - len(ok), - "versions": dict(sorted(Counter(r["version"] for r in ok).items())), - "flags": {hex(k): v for k, v in sorted(Counter(r["flags"] for r in ok).items())}, - "parameters": dict(sorted(Counter(p["type"] for p in params).items())), - "visibility": {VISIBILITY_NAMES.get(k, str(k)): v for k, v in sorted(Counter(p["visibility"] for p in params).items())}, - "static_samplers": dict(sorted(Counter(r["static_samplers"] for r in ok).items())), - "user_sgprs": dict(sorted(Counter(r["user_sgprs"] for r in ok if r["user_sgprs"] is not None).items())), - "span_table2": dict(sorted(Counter(r["span_table2"] for r in ok).items())), - "span_table1": dict(sorted(Counter(r["span_table1"] for r in ok).items())), - "spare_table2": dict(sorted(Counter(r["spare_table2"] for r in ok if "spare_table2" in r).items())), - "spare_table1": dict(sorted(Counter(r["spare_table1"] for r in ok if "spare_table1" in r).items())), - "read_scan": _read_summary(ok), - } - - -def main(argv=None): - ap = argparse.ArgumentParser(description=__doc__.split("\n")[0]) - ap.add_argument("root", help="tools/fspx_unpack.py --out folder") - ap.add_argument("--json", help="also write the rows and the summary here") - ap.add_argument("--disasm", help="a tools/fspx_unpack.py --disasm folder; adds each program's reads") - a = ap.parse_args(argv) - if a.json: - try: - if os.path.samefile(a.root, a.json): - ap.error("--json must not be the input folder") - except (FileNotFoundError, IsADirectoryError, NotADirectoryError): - pass - if not os.path.isdir(a.root): - ap.error(f"not a folder: {a.root}") - if a.disasm and not os.path.isdir(a.disasm): - ap.error(f"not a folder: {a.disasm}") - rows, errors = census(a.root, a.disasm) - summary = summarize(rows) - for row in rows: - if "error" in row: - print(f"{row['name']}: {row['error']}") - continue - types = Counter(p["type"] for p in row["params"]) - print(f"{row['name']}: RTS0 {row['version']}, {len(row['params'])} params {dict(sorted(types.items()))}, " - f"{row['static_samplers']} static sampler(s), user_sgprs {row['user_sgprs']}, " - f"span table2 {row['span_table2']} table1 {row['span_table1']}") - print(f"\n{summary['parsed']}/{summary['containers']} containers parsed; versions {summary['versions']}; " - f"flags {summary['flags']}") - print(f"parameters {summary['parameters']}; visibility {summary['visibility']}; " - f"static samplers {summary['static_samplers']}") - print(f"user_sgprs {summary['user_sgprs']}") - print(f"span table2 {summary['span_table2']} table1 {summary['span_table1']}") - print(f"spare table2 {summary['spare_table2']} table1 {summary['spare_table1']}") - if summary["read_scan"]: - rs = summary["read_scan"] - print(f"reads {rs['programs']} program(s): table bases {rs['table_bases']}, whole pairs {rs['whole_pairs']}, " - f"{rs['low_read']} read s0-s3") - for line in errors: - print(f"error: {line}", file=sys.stderr) - if a.json: - with open(a.json, "w", encoding="utf-8", newline="\n") as fh: - json.dump({"rows": rows, "summary": summary}, fh, indent=1, sort_keys=True) - fh.write("\n") - return 1 if errors else 0 - - -if __name__ == "__main__": - try: # a redirected stdout is strict ANSI code page under -I; write '?' for what it cannot encode - sys.stdout.reconfigure(errors="replace") - except (AttributeError, ValueError, OSError): - pass - sys.exit(main()) diff --git a/tools/rpf9_carve.py b/tools/rpf9_carve.py deleted file mode 100644 index 318a14598..000000000 --- a/tools/rpf9_carve.py +++ /dev/null @@ -1,287 +0,0 @@ -"""Carve the zlib-compressed files out of an RPF9 archive without its (encrypted) table of contents. - -The data area is mostly zlib streams laid end to end, separated by zero padding. This walks the archive, inflates -every stream that decodes cleanly to the end, and writes each one as .bin. It also records which byte -ranges it couldn't read, so coverage is measurable. - -index.json holds the summary (totals), `files` (one row per carved stream) and `unread`: one row per gap between -streams (or after the last one) that is not all zero bytes, with its offset, size and the Shannon entropy in -bits/byte of its first ENTROPY_SAMPLE bytes (`sampled`). An all-zero gap is padding and only counts toward -`zero_padding`. The bytes are counted, never decoded. - -Usage: - python -I rpf9_carve.py [--start N] [--limit BYTES] [--until-adat] [--index-only] - ---until-adat ends the scan at the first raw AWC bank (a little-endian `ADAT` whose header parses as one, -rsc8_audio.parse_adat_header_bytes), so the zlib-compressed audio config at the start of audio.rpf is carved without -touching the banks and without a build-specific --limit (docs/audio_config.md). The bytes `ADAT` alone are not -enough: they also occur inside `METADATA` and in compressed data. index.json's summary records the boundary. -""" -import argparse -import collections -import json -import math -import mmap -import os -import re -import struct -import sys -import time -import zlib - -sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) -from rsc8_audio import parse_adat_header_bytes # noqa: E402 -from report_paths import same_report_path # noqa: E402 -from restofworld_model_join import ModelSystemPages # noqa: E402 - -# zlib stream start, or a Bink 2 video ('KB2' + revision letter, then u32 size-8). -# RPF9 magic as it sits on disk: the tag "RPF9" stored little-endian (docs/rpf.md, docs/bvh.md). -MAGIC = b"9FPR" -ZHDR = re.compile(rb"\x78[\x01\x5e\x9c\xda]|KB2[a-z]") -ENTROPY_SAMPLE = 1 << 20 # bytes of an unread range used for its entropy -GAP_CHUNK = 1 << 20 # a gap is checked this many bytes at a time: one can be gigabytes long - - -def all_zero(buf, a, b, chunk=GAP_CHUNK): - """Whether buf[a:b] is all zero bytes, reading at most `chunk` bytes at a time. - - Slicing a whole gap of a multi-gigabyte archive at once ran out of memory (a 20 GB archive in this package). - """ - for p in range(a, b, chunk): - piece = buf[p:min(p + chunk, b)] - if piece.count(0) != len(piece): - return False - return True - - -def entropy(sample): - """Shannon entropy of a byte string in bits per byte (0.0 for an empty one).""" - if not sample: - return 0.0 - n = len(sample) - return -sum(c / n * math.log2(c / n) for c in collections.Counter(sample).values()) - - -def below_normal(): - if os.name == "nt": - import ctypes - from ctypes import wintypes - - k = ctypes.windll.kernel32 - # GetCurrentProcess returns a pointer-sized pseudo-handle. - k.GetCurrentProcess.argtypes = () - k.GetCurrentProcess.restype = wintypes.HANDLE - k.SetPriorityClass.argtypes = (wintypes.HANDLE, wintypes.DWORD) - k.SetPriorityClass.restype = wintypes.BOOL - k.SetPriorityClass(k.GetCurrentProcess(), 0x00004000) - - -def offset(text): - """--start: 0 or more, decimal or 0x hex.""" - try: - value = int(text, 0) - except ValueError: - raise argparse.ArgumentTypeError("must be 0 or more") from None - if value < 0: - raise argparse.ArgumentTypeError("must be 0 or more") - return value - - -def byte_count(text): - """--limit: at least 1; 0 used to mean no limit and a negative value silently scanned less.""" - try: - value = int(text, 0) - except ValueError: - raise argparse.ArgumentTypeError("must be at least 1") from None - if value < 1: - raise argparse.ArgumentTypeError("must be at least 1") - return value - - -ADAT_HEADER_READ = 1 << 20 # enough for every bank header the parser accepts in practice; it rejects longer ones - - -def first_adat_bank(m, start, end): - """Offset of the first raw AWC bank in m[start:end] whose header parses (not just the four bytes), or None.""" - size = len(m) - pos = start - while pos < end: - at = m.find(b"ADAT", pos, end) - if at < 0: - return None - if parse_adat_header_bytes(m[at:min(size, at + ADAT_HEADER_READ)], at, size) is not None: - return at - pos = at + 1 - return None - - -def main(argv=None) -> int: - ap = argparse.ArgumentParser() - ap.add_argument("archive") - ap.add_argument("out") - ap.add_argument("--start", type=offset) - ap.add_argument("--limit", type=byte_count) - ap.add_argument("--until-adat", action="store_true", - help="end the scan at the first raw AWC (ADAT) bank, e.g. the audio config at the start of " - "audio.rpf") - ap.add_argument("--index-only", action="store_true") - a = ap.parse_args(argv) - below_normal() - if os.path.isdir(a.archive): - sys.exit(f"{a.archive}: is a directory, not an RPF9 archive") - try: - size = os.path.getsize(a.archive) - except OSError as e: - sys.exit(f"{a.archive}: {e.strerror or e}") - if size == 0: - sys.exit(f"{a.archive}: empty file") - if size < 8: - sys.exit(f"{a.archive}: too short for an RPF9 header ({size} bytes)") - try: - with open(a.archive, "rb") as fh: - hdr = fh.read(8) - except OSError as e: - sys.exit(f"{a.archive}: {e.strerror or e}") - if hdr[:4] != MAGIC: - sys.exit(f"{a.archive}: not an RPF9 archive (expected the magic {MAGIC.decode()} at offset 0)") - if a.start is not None and not 0 <= a.start < size: - sys.exit(f"{a.archive}: --start {a.start} is outside the file (0..{size - 1})") - if a.start is None: - base = struct.unpack_from(" size: # base == size is an empty data area, which is fine - sys.exit(f"{a.archive}: header data offset {base} is past the end of the file ({size} bytes)") - else: - base = a.start - if os.path.exists(a.out) and not os.path.isdir(a.out): - sys.exit(f"{a.out}: output path is a file, not a directory") - index_path = os.path.join(a.out, "index.json") - if same_report_path(index_path, a.archive): - sys.exit(f"{index_path}: output must not overwrite input archive {a.archive}") - try: - os.makedirs(a.out, exist_ok=True) - except OSError as e: - sys.exit(f"{a.out}: cannot create output directory: {e.strerror or e}") - with open(a.archive, "rb") as fh, mmap.mmap(fh.fileno(), 0, access=mmap.ACCESS_READ) as m: - pos = base - end = min(size, pos + a.limit) if a.limit else size - boundary = None - if a.until_adat: - boundary = first_adat_bank(m, pos, end) - if boundary is None: - print(f"--until-adat: no AWC bank between {pos:#x} and {end:#x}; scanning all of it", flush=True) - else: - end = boundary - print(f"--until-adat: first AWC bank at {boundary:#x}; scanning {pos:#x}..{boundary:#x}", flush=True) - rows, last, unread, zero = [], pos, 0, 0 - unread_ranges = [] - system_pages = ModelSystemPages() - - def account(a, b): - """Count the gap m[a:b] as zero padding, or as an unread range that is also listed.""" - nonlocal zero, unread - if all_zero(m, a, b): - zero += b - a - return - unread += b - a - sample = m[a:min(b, a + ENTROPY_SAMPLE)] - unread_ranges.append({"off": a, "size": b - a, "entropy": round(entropy(sample), 3), - "sampled": len(sample)}) - - t0 = time.time() - while pos < end: - mt = ZHDR.search(m, pos, end) - if not mt: - break - s = mt.start() - if m[s:s + 3] == b"KB2": - if s + 0x1C > end: # header cut off by the end of the file or of --limit's window: not a video - pos = s + 1 - continue - blen = struct.unpack_from("= 16 and m[s - 16:s] == b"\0" * 16) - account(last, s) - rows.append({"off": s, "stored": used, "size": len(out), "pre": m[max(0, s - 16):s].hex(), - "head": out[:16].hex()}) - if not a.index_only: - out_file = os.path.join(a.out, f"{s:012x}.bin") - try: - with open(out_file, "wb") as f: - f.write(out) - except OSError as e: - sys.exit(f"{out_file}: cannot write: {e.strerror or e}") - last = pos = s + used - if len(rows) % 2000 == 0: - done = (pos - (a.start or 0)) / max(1, end - (a.start or 0)) - print(f"[{done:6.1%}] {len(rows)} files, {time.time() - t0:.0f}s", flush=True) - account(last, end) - total = sum(r["stored"] for r in rows) - bink = sum(r["stored"] for r in rows if r.get("type") == "bink2") - span = end - base - summary = {"archive": a.archive, "files": len(rows), "compressed_bytes": total, - "inflated_bytes": sum(r["size"] for r in rows), "bink2_bytes": bink, - "bink2_files": sum(1 for r in rows if r.get("type") == "bink2"), - "zero_padding": zero, "unread_bytes": unread, "unread_ranges": len(unread_ranges), - "span": span} - if a.until_adat: - summary["first_adat_bank"] = boundary # None: no bank in the window, the whole window was scanned - index_path = os.path.join(a.out, "index.json") - try: - with open(index_path, "w", encoding="utf-8", newline="\n") as f: - json.dump({"summary": summary, "files": rows, "unread": unread_ranges}, f) - except OSError as e: - sys.exit(f"{index_path}: cannot write: {e.strerror or e}") - print(json.dumps(summary, indent=1)) - span = max(1, span) # an empty data area (or --start at the end) has nothing to divide by - print(f"readable: {total / span:.1%}, zero padding {zero / span:.1%}, unread {unread / span:.1%}") - if unread_ranges: - print(f"unread: {len(unread_ranges)} range(s), largest {max(r['size'] for r in unread_ranges)} bytes " - f"(listed in index.json)") - return 0 - - -if __name__ == "__main__": - try: # a redirected stdout is strict ANSI code page under -I; write '?' for what it cannot encode - sys.stdout.reconfigure(errors="replace") - except (AttributeError, ValueError, OSError): - pass - sys.exit(main()) diff --git a/tools/rpf9_names.py b/tools/rpf9_names.py deleted file mode 100644 index 126ffad29..000000000 --- a/tools/rpf9_names.py +++ /dev/null @@ -1,278 +0,0 @@ -"""Index named RPF9 resources without the encrypted table of contents. - -The RPF9 data area is mostly zlib streams laid end to end. This walks it the same way -``rpf9_carve.py`` does, but inflates only a bounded prefix of each stream and records the -measured resource-name spelling (``name.#dr``, ``name.#ft``, ``name.#dd``, ...). The result is -a lightweight lookup index for targeted model/animation extraction; it does not decode a model -and it never writes game data. - -Usage: - python -I rpf9_names.py [--start N] [--limit BYTES] - [--max-inflate BYTES] [--types dr,ft,dd] [--quiet] - -The output contains archive offsets, compressed sizes, inflated sizes and the names found in -each stream. It is local scratch; do not commit the names or the index. -""" -import argparse -import json -import mmap -import os -import re -import struct -import sys -import tempfile -import time -import zlib - -sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) - -from file_mode import published_mode # noqa: E402 -from zero_span import gap_split # noqa: E402 - -# zlib stream start, or a Bink 2 video ('KB2' + revision letter, then u32 size-8). -ZHDR = re.compile(rb"\x78[\x01\x5e\x9c\xda]|KB2[a-z]") - -# Cap on the transient output a single decompress() call may produce, and the largest -# input feed read from the map. ``max_inflate`` remains the bound on -# how much of the inflated stream is kept for name extraction. -DECOMPRESS_MAX = 1 << 20 -# Most short streams end in the first read. zlib copies any bytes beyond EOF -# into unused_data, so reading a full MiB up front copies the next streams too. -INITIAL_FEED = 4096 -NAME = re.compile(rb"(? end: # header cut off by the end of the window: not a video - pos = s + 1 - continue - blen = struct.unpack_from("= 0") - if a.limit is not None and a.limit <= 0: - raise ValueError("--limit must be > 0") - if a.max_inflate <= 0: - raise ValueError("--max-inflate must be > 0") - if not os.path.isfile(a.archive): - raise ValueError("archive does not exist") - except ValueError as exc: - print(f"ERROR: {exc}", file=sys.stderr) - return 2 - out_abs = os.path.abspath(a.out) - try: - if os.path.exists(a.out) and os.path.samefile(a.archive, a.out): - raise ValueError(f"output {a.out} is the input archive") - except (OSError, ValueError) as exc: - print(f"ERROR: {exc}", file=sys.stderr) - return 2 - progress = None - if not a.quiet: - progress = lambda text: print(f" {text}", file=sys.stderr, flush=True) - try: - rows, summary = scan_archive(a.archive, a.start, a.limit, a.max_inflate, types, progress) - except (OSError, ValueError) as exc: - print(f"ERROR: {exc}", file=sys.stderr) - return 2 - try: - publish_report(out_abs, rows, summary) - except OSError as exc: - print(f"ERROR: cannot write report {a.out}: {exc.strerror or exc}", file=sys.stderr) - return 2 - if not a.quiet: - print(json.dumps(summary, indent=1)) - return 0 - - -if __name__ == "__main__": - try: # a redirected stdout is strict ANSI code page under -I; write '?' for what it cannot encode - sys.stdout.reconfigure(errors="replace") - except (AttributeError, ValueError, OSError): - pass - sys.exit(main()) diff --git a/tools/rpf9dump/ModelDecodeFailure.cs b/tools/rpf9dump/ModelDecodeFailure.cs deleted file mode 100644 index 619582184..000000000 --- a/tools/rpf9dump/ModelDecodeFailure.cs +++ /dev/null @@ -1,29 +0,0 @@ -using RpfPreview.Core; - -internal readonly record struct ModelDecodeFailure(string Code, string Detail) -{ - // The decoder returns null for all rejected layouts. Probe the resource - // again only on failure, so successful exports keep the existing path. - public static ModelDecodeFailure Explain(ReadOnlySpan system, int graphicsBytes) - { - if (system.Length > RageModelDecoder.MaxSystemBytes) - return new("system-size-limit", $"{system.Length} system bytes"); - if (graphicsBytes > RageModelDecoder.MaxGraphicsBytes) - return new("graphics-size-limit", $"{graphicsBytes} graphics bytes"); - - var extent = RageModelDecoder.ProbeRequiredExtents(system); - if (extent is null) - return RageModelDecoder.LooksLikeResource(system) - ? new("invalid-or-unsupported-layout", "recognized header, resource metadata probe failed") - : new("unrecognized-header", $"{system.Length} system bytes"); - if (extent.RequiredSystemBytes > system.Length) - return new("truncated-system", $"{system.Length}/{extent.RequiredSystemBytes} system bytes"); - if (!extent.MetadataComplete) - return new("incomplete-metadata", "resource metadata probe did not complete"); - if (extent.RequiredGraphicsBytes > graphicsBytes) - return new("truncated-graphics", $"{graphicsBytes}/{extent.RequiredGraphicsBytes} graphics bytes"); - if (graphicsBytes == 0) - return new("missing-graphics", "empty graphics segment"); - return new("decode-rejected", "size and metadata checks passed"); - } -} diff --git a/tools/rpf9dump/Program.cs b/tools/rpf9dump/Program.cs deleted file mode 100644 index efb4c9989..000000000 --- a/tools/rpf9dump/Program.cs +++ /dev/null @@ -1,422 +0,0 @@ -// Bulk exporter around rpf9-explorer's Core (github.com/breadbbbb/rpf9-explorer). -// Local use only: writes OBJ/DDS/JSON from the user's own package. No keys, no TOC decryption. -using System.Diagnostics; -using System.Globalization; -using System.Text.Json; -using RpfPreview.Core; - -// Optional --jobs N anywhere among the args (default: every core). Stripped before mode/src/outdir. -var argv = args.ToList(); -int jobs = Environment.ProcessorCount; -for (int i = 0; i < argv.Count; ) -{ - if (argv[i] == "--jobs") - { - if (i + 1 >= argv.Count || !int.TryParse(argv[i + 1], out jobs) || jobs < 1) - { - Console.Error.WriteLine("--jobs must be at least 1"); - return 2; - } - argv.RemoveAt(i); - argv.RemoveAt(i); - continue; - } - i++; -} -// The mode is checked before the source or the output folder is touched. A typo used to fall through every branch: -// it created the output folder, printed ok=0 fail=0 skip=0 and exited 0, which make_game reads as a finished stage. -string[] modes = ["ttpf", "audio", "xma", "models", "textures"]; -if (argv.Count < 3) { Usage(); return 2; } -if (!modes.Contains(argv[0])) { Console.Error.WriteLine($"unknown mode '{argv[0]}'"); Usage(); return 2; } -string mode = argv[0], src = Path.GetFullPath(argv[1]), outRoot = Path.GetFullPath(argv[2]); -// --start/--length scan one window of the file instead of the whole archive. A window is a raw slice of an -// archive (`levels.rpf` cut at an offset), so it need not carry the file's header and it is not an -// ArchiveDocument: models and textures then read every resource from its own compression blocks -// (tools/rpf9dump/Segments.cs). A window is how a multi-GiB archive is exported a piece at a time. -long scanStart = 0; long? scanLength = null; -for (int i = 3; i < argv.Count; i += 2) -{ - if (i + 1 >= argv.Count || !long.TryParse(argv[i + 1], NumberStyles.None, CultureInfo.InvariantCulture, out long bytes) || bytes < 0) - { - Console.WriteLine($"{argv[i]} needs a non-negative byte count."); - return 2; - } - if (argv[i] == "--start") scanStart = bytes; - else if (argv[i] == "--length") scanLength = bytes; - else { Console.WriteLine($"Unknown option {argv[i]}."); return 2; } -} -bool window = scanStart != 0 || scanLength is not null; -if (window && mode is not ("models" or "textures")) -{ - Console.WriteLine("--start/--length apply to models and textures; other modes need a recognized archive."); - return 2; -} -// A missing source, or a directory passed as one, is a usage error. Check it before the output folder is -// created: FileInfo.Length would otherwise throw after / already exists. -if (!File.Exists(src)) { Console.Error.WriteLine($"source is not a file: {src}"); return 2; } -long length = new FileInfo(src).Length; -if (window && scanStart > length) -{ - Console.Error.WriteLine($"--start ({scanStart}) exceeds source length ({length})."); - return 2; -} -long? effectiveScanLength = scanLength is long reqSpan ? Math.Min(reqSpan, length - scanStart) : null; -var json = new JsonSerializerOptions { WriteIndented = true }; -var sw = Stopwatch.StartNew(); -string baseName = Path.GetFileNameWithoutExtension(src); -string outDir = Path.Combine(outRoot, baseName); Directory.CreateDirectory(outDir); -int ok = 0, fail = 0, skip = 0, writeFail = 0; -// Every mode below works on all cores by default. Core's readers open their own read handle per call, entry and -// file names come from offsets and indexes, and results are put back in source order, so outputs match a -// one-thread run. --jobs caps that when make_game.py overlaps this with another CPU-heavy stage. -var par = new ParallelOptions { MaxDegreeOfParallelism = jobs }; - -if (mode == "ttpf") -{ - var info = TtpfReader.Inspect(src); - var rows = new object[info.Textures.Count]; - int done = 0; - Parallel.For(0, info.Textures.Count, par, i => - { - var t = info.Textures[i]; - string name = $"{t.Index:D6}_{Util.Safe(Path.GetFileNameWithoutExtension(t.Name))}.dds"; - string path = Path.Combine(outDir, name); - string? file = t.CanExtract ? name : null, limitation = t.Limitation; - if (!t.CanExtract) Interlocked.Increment(ref skip); - else if (File.Exists(path)) Interlocked.Increment(ref ok); - else - { - try - { - // Content the decoder cannot handle is a skip like !CanExtract. Pool read errors, DDS write errors, - // cancellation and anything unexpected stay failures. - byte[]? dds = null; - try { dds = TtpfReader.CreateDds(src, t.Index); } - catch (Exception e) when (e is NotSupportedException or InvalidDataException) - { Interlocked.Increment(ref skip); file = null; limitation = e.Message; } - if (dds != null) { Util.WriteAllBytes(path, dds); Interlocked.Increment(ref ok); } - } - catch (Exception e) { if (Interlocked.Increment(ref fail) <= 5) Console.WriteLine($" fail {t.Index}: {e.GetType().Name} {e.Message}"); } - int n = Interlocked.Increment(ref done); - if (n % 5000 == 0) Console.WriteLine($" {n}/{info.Textures.Count}"); - } - rows[i] = new { t.Index, t.Name, t.Id, AssetKey = t.AssetKey.ToString("X16"), t.Width, t.Height, - t.Depth, t.Dimension, t.DxgiFormat, t.Mips, t.SourceMips, t.BaseMipLevel, Limitation = limitation, File = file }; - }); - // The manifest is the build's completion marker. Keep successful DDS for retry, but withdraw a stale marker. - string manifest = Path.Combine(outDir, "manifest.json"); - if (fail == 0) - Util.WriteAllText(manifest, JsonSerializer.Serialize(new { src, info.Version, Count = info.Textures.Count, info.Metadata, Textures = rows }, json)); - else - { - try { WithdrawMarker(manifest); } - catch (Exception ex) { Console.WriteLine($" cannot withdraw the stale manifest: {ex.GetType().Name} {ex.Message}"); return 1; } - } -} -else if (mode == "audio") -{ - if (!AwcRecovery.HasCompleteCache(src)) - { - long last = -1; - var prog = new Progress(p => { long s = p / (4L << 30); if (s != last) { last = s; Console.WriteLine($" awc scan {100.0 * p / length:0.0}%"); } }); - var found = AwcRecovery.RecoverFull(src, prog); - AwcRecovery.WriteCache(src, found); - Console.WriteLine($" {found.Count:N0} AWC banks ({sw.Elapsed.TotalSeconds:0}s)"); - } - var doc = ArchiveReader.Open(src); - var banks = doc.Entries.Where(e => e.Extension == ".awc" && e.CanExtract).ToList(); - string sub = Path.Combine(outDir, "awc"); - var todo = banks.Where(e => !File.Exists(ArchiveReader.SafeDestination(sub, e.Path))).ToList(); - Console.WriteLine($" {banks.Count:N0} banks, {todo.Count:N0} to write"); - for (int i = 0; i < todo.Count; i += 500) - doc.ExtractAsync(todo.Skip(i).Take(500), sub).GetAwaiter().GetResult(); - ok = banks.Count; - var rows = banks.AsParallel().AsOrdered().WithDegreeOfParallelism(par.MaxDegreeOfParallelism).Select(e => { var info = AwcInfo.Inspect(src, e.Offset, e.Size); - return new { e.Path, e.Offset, e.Size, Streams = info?.Streams.Select(s => new { s.Index, Id = s.Id.ToString("X8"), s.Codec, s.Channels, s.SampleRate, s.DurationSeconds, s.IsStreamed }) }; }).ToList(); - Util.WriteAllText(Path.Combine(outDir, "audio_manifest.json"), JsonSerializer.Serialize(new { src, Count = banks.Count, Banks = rows }, json)); -} -else if (mode == "xma") -{ - // XMA2 streams (AWC codec 5) as RIFF XMA2 .wav files that ffmpeg decodes (AwcRecovery.WriteXmaWave). - var doc = ArchiveReader.Open(src); - var banks = doc.Entries.Where(e => e.Extension == ".awc" && e.CanExtract).ToList(); - string sub = Path.Combine(outDir, "xma"); Directory.CreateDirectory(sub); - Parallel.ForEach(banks, par, e => - { - var info = AwcInfo.Inspect(src, e.Offset, e.Size); - if (info == null) return; - foreach (var st in info.Streams.Where(x => x.Codec == 5)) - { - string dir = Path.Combine(sub, Util.Safe(Path.GetFileNameWithoutExtension(e.Name))); - Directory.CreateDirectory(dir); - string path = Path.Combine(dir, $"{st.Id:X8}.xma.wav"); - if (File.Exists(path)) { Interlocked.Increment(ref ok); continue; } - try { Util.WriteAtomic(path, tmp => AwcRecovery.WriteXmaWave(src, e.Offset, e.Size, st.Index, tmp)); Interlocked.Increment(ref ok); } - catch (Exception ex) { if (Interlocked.Increment(ref fail) <= 5) Console.WriteLine($" fail {e.Name}#{st.Index}: {ex.GetType().Name} {ex.Message}"); } - } - }); - // make_game marks audio/xma done on exit 0, so a failed stream must fail the run to be retried. - Console.WriteLine($"{mode} {baseName}: ok={ok} fail={fail} skip={skip} in {sw.Elapsed.TotalSeconds:0}s"); - return fail != 0 ? 1 : 0; -} -else if (mode is "models" or "textures") -{ - // Neither mode needs the archive document any more: the entries come from the index cache or from this run's - // scan, and every resource is read from its own compression blocks (tools/rpf9dump/Segments.cs). That is what - // lets a raw slice of an archive - a --start/--length window, or a file cut out of levels.rpf - be exported at - // all: a slice has no 9FPR header, so there is no document to open. - List list; - int? candidates; - if (window) - { - // A sub-range is never cached: the index cache is keyed by the file, not by the window inside it. - var cands = Scan(src, scanStart, effectiveScanLength); - candidates = cands.Count; - list = Recover(src, length, cands); - Console.WriteLine(" a window is scanned again on every run: no index cache is written"); - } - else - { - byte[] header; using (var f = File.OpenRead(src)) { header = new byte[(int)Math.Min(64, length)]; f.ReadExactly(header); } - var cached = RecoveryIndexCache.Load(mode, src, length, header); - // A partial index (rpf9-explorer stopped or still indexing) would export only part of the archive: scan again. - if (cached != null && !ScanCounts.IsFullScan(cached)) { Console.WriteLine($" cached {mode} index is not marked as a full scan ({cached.Entries.Count:N0} entries), rescanning"); cached = null; } - candidates = ScanCounts.Candidates(cached?.Coverage); - if (cached == null) - { - var cands = Scan(src, 0, null); - list = Recover(src, length, cands); - RecoveryIndexCache.Save(mode, src, list, ScanCounts.Coverage(cands.Count, list.Select(e => e.Offset).Distinct().Count()), complete: true); - candidates = cands.Count; - } - else - { - string want = mode == "models" ? "Recovered model" : "Recovered texture dictionary"; - list = cached.Entries.Where(e => e.Compression == want).ToList(); - } - } - Console.WriteLine($" {list.Count:N0} {mode} entries ({sw.Elapsed.TotalSeconds:0}s)"); - // A drawable dictionary yields one entry per child, all with the candidate's offset: count resources by offset. - int recovered = list.Select(e => e.Offset).Distinct().Count(); - if (candidates is int scannedCount && scannedCount > recovered) - Console.WriteLine($" {scannedCount - recovered:N0} of {scannedCount:N0} scan candidates were not recovered (rejected before decoding)"); - - // Scan a range and recover every resource it holds. Both run on all cores; the result is put back in offset - // order, so it does not depend on which chunk finished first. - IReadOnlyList Scan(string path, long start, long? span) - { - long total = Math.Max(1, span ?? (length - start)), last = -1; - var progress = new Progress(p => - { - long percent = 100 * (p - start) / total; - if (percent != last) { last = percent; Console.WriteLine($" scan {percent}%"); } - }); - var found = mode == "models" - ? Rpf9ModelRecovery.FindCandidateOffsets(path, start, span, progress) - : Rpf9TextureRecovery.FindCandidateOffsets(path, start, span, progress); - Console.WriteLine($" candidates {found.Count:N0} ({sw.Elapsed.TotalSeconds:0}s)"); - return found; - } - - List Recover(string path, long fileLength, IReadOnlyList offsets) - { - // Indexes are reassigned in offset order below, so the chunks' scheduling does not show in the result. - var chunks = offsets.Chunk(32).ToArray(); - var got = new IReadOnlyList[chunks.Length]; - int validated = 0, found = 0; - Parallel.For(0, chunks.Length, par, i => - { - got[i] = mode == "models" ? Rpf9ModelRecovery.RecoverAtOffsets(path, fileLength, chunks[i]) : Rpf9TextureRecovery.RecoverAtOffsets(path, fileLength, chunks[i]); - Interlocked.Add(ref found, got[i].Count); - int n = Interlocked.Add(ref validated, chunks[i].Length); - if (n / 6400 != (n - chunks[i].Length) / 6400) Console.WriteLine($" validated {n:N0}/{offsets.Count:N0} -> {Volatile.Read(ref found):N0} ({sw.Elapsed.TotalSeconds:0}s)"); - }); - return got.SelectMany(g => g).OrderBy(e => e.Offset).Select((e, k) => e with { Index = k }).ToList(); - } - string sub = Path.Combine(outDir, mode); Directory.CreateDirectory(sub); - // The manifest is streamed row by row: holding 150k rows (each capturing its decoded model through lazy - // projections) ran out of memory on levels.rpf. Written to a .partial file and renamed when complete. - string manifestPath = Path.Combine(sub, "manifest.json"), partial = manifestPath + ".partial"; - using var mstream = new FileStream(partial, FileMode.Create, FileAccess.Write, FileShare.None, 1 << 20); - using var writer = new Utf8JsonWriter(mstream, new JsonWriterOptions { Indented = true }); - writer.WriteStartObject(); - writer.WriteString("src", src); - writer.WriteNumber("Count", list.Count); - // Scan-level counts. Candidates the recovery step rejects never reach the per-item loop or - // ModelDecodeFailures, so NotRecovered is the only place they show up. Recovered counts resources (candidate - // offsets); Entries counts manifest items (one per dictionary child). Null when a cached index does not record - // the candidate count. - writer.WriteStartObject("Scan"); - if (candidates is int scanned) writer.WriteNumber("Candidates", scanned); else writer.WriteNull("Candidates"); - writer.WriteNumber("Recovered", recovered); - if (candidates is int total) writer.WriteNumber("NotRecovered", total - recovered); else writer.WriteNull("NotRecovered"); - writer.WriteNumber("Entries", list.Count); - if (window) - { - // Which slice of the file this manifest covers, so a later run can name the same window. - writer.WriteNumber("Start", scanStart); - writer.WriteNumber("Length", effectiveScanLength ?? (length - scanStart)); - } - writer.WriteEndObject(); - writer.WriteStartArray("Items"); - void Row(object row) => JsonSerializer.Serialize(writer, row, json); - int embedded = 0; - var modelDecodeFailures = new SortedDictionary(StringComparer.Ordinal); - // Entries are decoded and written in parallel a batch at a time; rows, counters and failure messages are then - // taken in list order on this thread, so the manifest and the log read as a one-thread run. The batch bounds - // how many rows (and the models they reference) are alive at once. - const int Batch = 1024; - var results = new Result[Batch]; - for (int start = 0; start < list.Count; start += Batch) - { - int n = Math.Min(Batch, list.Count - start); - Parallel.For(0, n, par, i => results[i] = Export(list[start + i])); - for (int i = 0; i < n; i++) - { - var r = results[i]; results[i] = default; - ok += r.Ok; fail += r.Fail; embedded += r.Embedded; writeFail += r.WriteFail; - if (r.DecodeFailure is { } reason) - { - int count = modelDecodeFailures.GetValueOrDefault(reason.Code) + 1; - modelDecodeFailures[reason.Code] = count; - if (count <= 3) - Console.Error.WriteLine($" model decode failed at 0x{list[start + i].Offset:X}: {reason.Code} ({reason.Detail})"); - } - if (r.Error != null && fail <= 5) Console.WriteLine(r.Error); - if (r.Row != null) Row(r.Row); - } - Console.WriteLine($" exported {start + n:N0}/{list.Count:N0}"); - } - - Result Export(ArchiveEntry e) - { - int ok = 0, fail = 0, embedded = 0; - string stem = Util.Safe(Path.GetFileNameWithoutExtension(e.Name)); - try - { - var data = RecoveredResource.Read(src, e); - int split = e.ResourceSystemBytes ?? checked((int)e.Segments![0].Size); - var sys = data.AsSpan(0, split); var gfx = data.AsSpan(split); - if (mode == "models") - { - var m = RageModelDecoder.Decode(sys, gfx, e.ResourceDrawableOffset); - if (m == null) - return new Result(null, 0, 1, 0, ModelDecodeFailure.Explain(sys, gfx.Length), null, 0); - string obj = Path.Combine(sub, stem + ".obj"); - string objText = RageModelDecoder.CreateObj(m); - // A failed obj write means the model is missing from disk: fatal for the run (retryable), - // unlike the decode failures above, which no rerun would change. - try { if (!File.Exists(obj)) Util.WriteAllText(obj, objText); } - catch (Exception wex) { return new Result(null, 0, 1, 0, null, $" fail {e.Name}: {wex.GetType().Name} {wex.Message}", 1); } - int wfail = 0; - if (m.EmbeddedTextures != null && m.EmbeddedTextureDictionaryOffset is int dOff) - { - // A directory or DDS write failure leaves the embedded texture missing from disk: retryable, - // so it fails the run like the obj write above. Embedded decode failures count like the - // textures branch counts dictionary decode failures: reported, non-fatal for the run. - string td; - try { td = Path.Combine(sub, stem + "_tex"); Directory.CreateDirectory(td); } - catch (Exception wex) { return new Result(null, 0, 1, 0, null, $" fail {e.Name}: {wex.GetType().Name} {wex.Message}", 1); } - foreach (var t in m.EmbeddedTextures) - { - string p = Path.Combine(td, $"{t.Index:D3}_{Util.Safe(t.Name)}.dds"); - if (File.Exists(p)) { embedded++; continue; } - byte[] dds; - try { dds = Util.BgraDds(RageTextureDecoder.DecodeEmbeddedTexturePixels(sys, gfx, dOff, t.Index)); } - catch { fail++; continue; } - try { Util.WriteAllBytes(p, dds); embedded++; } - catch (Exception wex) { fail++; wfail++; if (wfail <= 5) Console.WriteLine($" fail {p}: {wex.GetType().Name} {wex.Message}"); } - } - } - return new Result(new { e.Offset, Drawable = e.ResourceDrawableOffset, File = stem + ".obj", m.Name, Meshes = m.Meshes.Count, Verts = m.Meshes.Sum(x => x.Positions.Count), Tris = m.Meshes.Sum(x => x.Indices.Count) / 3, m.IsFragment, m.HasBoneBindings, - Min = new[] { m.BoundsMin.X, m.BoundsMin.Y, m.BoundsMin.Z }, Max = new[] { m.BoundsMax.X, m.BoundsMax.Y, m.BoundsMax.Z }, - // Per geometry, in the order of the OBJ's `o` groups: triangles, the model it belongs to in the - // drawable's primary-LOD list and its position in that model (a dehydrated BLAS leaf's geometry - // index counts the geometries whose shader it keeps, docs/bvh.md §4a). - MeshShaders = m.Meshes.Select(x => x.ShaderIndex).ToArray(), - MeshTris = m.Meshes.Select(x => x.Indices.Count / 3).ToArray(), - MeshModels = m.Meshes.Select(x => Util.MeshKey(x.Name).Model).ToArray(), - MeshGeoms = m.Meshes.Select(x => Util.MeshKey(x.Name).Geometry).ToArray(), - Embedded = m.EmbeddedTextures?.Select(t => new { t.Index, t.Name, t.Width, t.Height, t.Format, Hash = t.NameHash.ToString("X8"), Key = t.AssetKey?.ToString("X16") }).ToArray(), - Materials = m.Materials?.Select(x => new { x.ShaderIndex, Shader = x.ShaderHash.ToString("X8"), Preset = x.PresetHash.ToString("X8"), x.RenderBucket, - Textures = x.Textures.Select(r => new { Param = r.ParameterHash.ToString("X8"), r.TextureIndex, Name = r.NameHash.ToString("X8"), Id64 = r.OpaqueId64.ToString("X16"), Tag = r.Tag.ToString("X8") }).ToArray() }).ToArray() }, - 1, fail, embedded, null, null, wfail); - } - else - { - var dict = RageTextureDecoder.Inspect(sys, gfx); - if (dict == null) return new Result(null, 0, 1, 0, null, null, 0); - string td; - try { td = Path.Combine(sub, stem); Directory.CreateDirectory(td); } - catch (Exception wex) { return new Result(null, 0, 1, 0, null, $" fail {e.Name}: {wex.GetType().Name} {wex.Message}", 1); } - int wfail = 0; - foreach (var t in dict.Textures) - { - string p = Path.Combine(td, $"{t.Index:D3}_{Util.Safe(t.Name)}.dds"); - if (File.Exists(p)) { ok++; continue; } - // A decoder problem is counted like today and no rerun would change it; a failed DDS write - // is retryable, so it additionally counts as a write failure and fails the run. A retryable - // read I/O error on the resource belongs to the same retryable class. - byte[] dds; - try { dds = RageTextureDecoder.CreateDds(sys, gfx, t.Index); } - catch (Exception ex) when (ex is IOException) { fail++; wfail++; if (wfail <= 5) Console.WriteLine($" fail {p}: {ex.GetType().Name} {ex.Message}"); continue; } - catch { fail++; continue; } - try { Util.WriteAllBytes(p, dds); ok++; } - catch { fail++; wfail++; } - } - return new Result(new { e.Offset, Dir = stem, Textures = dict.Textures.Select(t => new { t.Index, t.Name, t.Width, t.Height, t.Format, t.MipCount, Hash = t.NameHash.ToString("X8"), Key = t.AssetKey?.ToString("X16") }).ToArray() }, - ok, fail, 0, null, null, wfail); - } - } - // A read I/O error while reading the resource is retryable like a write failure, so it also - // withholds the manifest; structural exceptions stay non-retryable. - catch (Exception ex) { return new Result(null, ok, fail + 1, embedded, null, $" fail {e.Name}: {ex.GetType().Name} {ex.Message}", ex is IOException ? 1 : 0); } - } - if (mode == "models") Console.WriteLine($" embedded textures {embedded:N0}"); - writer.WriteEndArray(); - if (mode == "models") - { - writer.WritePropertyName("ModelDecodeFailures"); - JsonSerializer.Serialize(writer, modelDecodeFailures, json); - foreach (var (code, count) in modelDecodeFailures) - Console.Error.WriteLine($" model decode failures ({code}): {count:N0}"); - } - writer.WriteEndObject(); - writer.Dispose(); // flushes; the later using-dispose is a no-op - mstream.Dispose(); - // The manifest is the completion marker make_game resumes on. Like ttpf, keep the successful exports for - // a retry, but a run with write failures must not mark the stage finished: withdraw a stale marker and - // drop the partial instead of publishing it. - if (writeFail == 0) - File.Move(partial, manifestPath, true); - else - { - Console.WriteLine($" {writeFail} write failure(s): manifest withheld; rerun retries the missing files"); - try { WithdrawMarker(manifestPath); WithdrawMarker(partial); } - catch (Exception ex) { Console.WriteLine($" cannot withdraw the stale manifest: {ex.GetType().Name} {ex.Message}"); return 1; } - } -} -Console.WriteLine($"{mode} {baseName}: ok={ok} fail={fail} skip={skip} in {sw.Elapsed.TotalSeconds:0}s"); -return (mode == "ttpf" && fail != 0) || writeFail != 0 ? 1 : 0; - -// A stale marker may be read-only from an earlier interrupted run; clear the attribute so the withdraw works. -static void WithdrawMarker(string path) -{ - if (!File.Exists(path)) return; - try { File.SetAttributes(path, FileAttributes.Normal); } catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) { } - File.Delete(path); -} - -static void Usage() -{ - Console.WriteLine("usage: rpf9dump [--jobs N] [--start BYTES] [--length BYTES]"); - Console.WriteLine(" ttpf texture dictionaries and world texture pools as DDS"); - Console.WriteLine(" models drawable models as OBJ, with their embedded textures"); - Console.WriteLine(" textures texture dictionaries as DDS"); - Console.WriteLine(" audio AWC banks whole, plus audio_manifest.json"); - Console.WriteLine(" xma XMA2 streams as RIFF XMA2 .wav for ffmpeg"); -} - -// One exported entry: its manifest row (null when nothing was written), counts, a failure to report in order, -// and how many of its failures were output-write failures (the ones a retry can fix; decode failures are not). -readonly record struct Result(object? Row, int Ok, int Fail, int Embedded, ModelDecodeFailure? DecodeFailure, string? Error, int WriteFail); diff --git a/tools/rpf9dump/ScanCounts.cs b/tools/rpf9dump/ScanCounts.cs deleted file mode 100644 index 7bbfeabc5..000000000 --- a/tools/rpf9dump/ScanCounts.cs +++ /dev/null @@ -1,28 +0,0 @@ -using System.Text.RegularExpressions; -using RpfPreview.Core; - -// Scan-level counts for the manifest. Candidates that RecoverAtOffsets rejects never reach Program.cs, so -// Candidates - Recovered is the only place those rejects show up. -internal static class ScanCounts -{ - // Written into the index cache's coverage text on a full scan. - public static string Coverage(int candidates, int recovered) => - FormattableString.Invariant($"rpf9dump full scan, {candidates} candidates, {recovered} recovered"); - - // Reads the candidate count back from a cached index. Older caches wrote culture-formatted numbers - // ("183,801", "183'801", "183\u2019801", ...), so any punctuation or space between the digits is dropped. Null when the text is not ours or not readable. - public static int? Candidates(string? coverage) - { - if (coverage is null) return null; - var m = Regex.Match(coverage, @"^rpf9dump full scan, ([0-9][0-9\p{P}\p{Zs}]*) candidates,"); - if (!m.Success) return null; - string digits = new(m.Groups[1].Value.Where(char.IsAsciiDigit).ToArray()); - return int.TryParse(digits, out int n) ? n : null; - } - - // Whether a cached index can stand in for a full scan. rpf9-explorer saves its model index while it is still - // indexing and when the scan is cancelled, and marks it complete only at the end. rpf9dump before this check saved - // full scans without the mark, so its own coverage text counts too. - public static bool IsFullScan(RecoveryIndexCache.CachedIndex? cached) => - cached is not null && (cached.IsComplete || Candidates(cached.Coverage) is not null); -} diff --git a/tools/rpf9dump/Segments.cs b/tools/rpf9dump/Segments.cs deleted file mode 100644 index 206b8d5f3..000000000 --- a/tools/rpf9dump/Segments.cs +++ /dev/null @@ -1,64 +0,0 @@ -// Reading a recovered resource from its own compression blocks, without an ArchiveDocument. -// -// The recovery step (Rpf9ModelRecovery/Rpf9TextureRecovery) records, for every entry it recovers, the file offsets -// of the zlib blocks that make up its system and graphics segments. ArchiveReader.ReadResourceData reaches the same -// bytes through an ArchiveDocument, which needs a recognizable archive header. A --start/--length window is a raw -// slice of an archive, so the header may be at an offset the slice does not contain (a window of levels.rpf) or -// absent entirely; these entries are then read from their blocks alone. -using System.IO.Compression; -using RpfPreview.Core; - -/// Reads a recovered resource that has no archive document behind it. -public static class RecoveredResource -{ - /// The limit ArchiveReader puts on a recovered resource; the decoder is not given more than this. - public const int MaxBytes = 256 * 1024 * 1024; - - /// The resource's inflated bytes, block by block, in stored order. - public static byte[] Read(string path, ArchiveEntry entry) - { - if (entry.Segments is not { Count: > 0 } segments || entry.Size < 1 || entry.Size > MaxBytes) - throw new InvalidDataException("The recovered resource has no blocks or exceeds the 256 MiB limit."); - byte[] data = new byte[checked((int)entry.Size)]; - using var file = File.Open(path, FileMode.Open, FileAccess.Read, FileShare.Read); - int written = 0; - foreach (var block in segments) - { - if (block.Offset < 0 || block.StoredSize < 6 || block.Size < 0 || block.Offset + block.StoredSize > file.Length) - throw new InvalidDataException("A recovered block runs past the file."); - if (block.Size > data.Length - written) - throw new InvalidDataException("The recovered blocks exceed the resource size."); - file.Position = block.Offset; - using Stream stored = new StoredBlock(file, block.StoredSize); - using Stream content = block.IsRaw ? stored : new ZLibStream(stored, CompressionMode.Decompress); - content.ReadExactly(data.AsSpan(written, checked((int)block.Size))); - written += (int)block.Size; - } - if (written != data.Length) throw new InvalidDataException("The recovered resource is truncated."); - return data; - } - - /// A read-only view of one stored block, so a compressed block is never copied whole before inflating. - private sealed class StoredBlock(Stream inner, long length) : Stream - { - private long remaining = length; - public override bool CanRead => true; - public override bool CanSeek => false; - public override bool CanWrite => false; - public override long Length => throw new NotSupportedException(); - public override long Position { get => throw new NotSupportedException(); set => throw new NotSupportedException(); } - public override int Read(byte[] buffer, int offset, int count) - { - if (remaining <= 0) return 0; - int read = inner.Read(buffer, offset, (int)Math.Min(count, remaining)); - if (read == 0) throw new InvalidDataException("A stored block is truncated."); - remaining -= read; - return read; - } - public override void Flush() { } - public override long Seek(long offset, SeekOrigin origin) => throw new NotSupportedException(); - public override void SetLength(long value) => throw new NotSupportedException(); - public override void Write(byte[] buffer, int offset, int count) => throw new NotSupportedException(); - // Deliberately no Dispose: the caller owns the file and the next block reads from it. - } -} diff --git a/tools/rpf9dump/Util.cs b/tools/rpf9dump/Util.cs deleted file mode 100644 index 67074e044..000000000 --- a/tools/rpf9dump/Util.cs +++ /dev/null @@ -1,103 +0,0 @@ -// Helpers shared by rpf9dump's exporters (linked into tests/Rpf9DumpDiagnostics too). -using RpfPreview.Core; - -public static class Util -{ - // Every output is written to a unique .*.partial and renamed into place. The exporters skip any file that - // already exists, and make_game.py takes manifest.json / audio_manifest.json as proof a step finished, so a - // file cut short by a stopped run or a full disk must never appear under its final name. - // Unique names matter on parallel export (two models with the same stem) and when a stale exclusive - // lock on the classic ".partial" name would throw IOException: "being used by another process". - public static void WriteAtomic(string path, Action write) - { - TryDelete(path + ".partial"); // leftover from older builds / stopped runs - string tmp = PartialName(path); - try - { - write(tmp); - MoveReplace(tmp, path); - } - finally { TryDelete(tmp); } - } - public static void WriteAllBytes(string path, byte[] data) => WriteAtomic(path, t => File.WriteAllBytes(t, data)); - public static void WriteAllText(string path, string text) => WriteAtomic(path, t => File.WriteAllText(t, text)); - - public static string PartialName(string path) => - path + $".{Environment.ProcessId}.{Environment.CurrentManagedThreadId}.{Guid.NewGuid():N}.partial"; - - public static void TryDelete(string path) - { - try { if (File.Exists(path)) File.Delete(path); } - catch (IOException) { } - catch (UnauthorizedAccessException) { } - } - - /// Create/truncate for exclusive write, retrying through brief file locks. - public static FileStream OpenExclusiveCreate(string path, int bufferSize = 1 << 20) - { - IOException? last = null; - for (int i = 0; i < 20; i++) - { - try - { - return new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.None, bufferSize); - } - catch (IOException ex) - { - last = ex; - TryDelete(path); - Thread.Sleep(50 * (i + 1)); - } - } - throw last!; - } - - /// Atomic publish with retries (File.Move onto a briefly locked target can fail). - public static void MoveReplace(string src, string dst) - { - IOException? last = null; - for (int i = 0; i < 20; i++) - { - try - { - File.Move(src, dst, overwrite: true); - return; - } - catch (IOException ex) - { - last = ex; - Thread.Sleep(50 * (i + 1)); - } - } - throw last!; - } - - // The decoder names every geometry mesh `model_{mi}_geometry_{gi}`, where mi is the position of the model in the - // drawable's primary-LOD model list and gi the position of the geometry in that model - the pair a dehydrated - // BLAS leaf stores as its geometry index (docs/bvh.md §4a). Other spellings give -1. - public static (int Model, int Geometry) MeshKey(string name) - { - string[] parts = name.Split('_'); - if (parts.Length == 4 && parts[0] == "model" && parts[2] == "geometry" && - int.TryParse(parts[1], System.Globalization.NumberStyles.None, System.Globalization.CultureInfo.InvariantCulture, out int model) && - int.TryParse(parts[3], System.Globalization.NumberStyles.None, System.Globalization.CultureInfo.InvariantCulture, out int geometry)) - return (model, geometry); - return (-1, -1); - } - - public static string Safe(string s) - { - var bad = Path.GetInvalidFileNameChars(); - var c = s.Select(ch => bad.Contains(ch) || char.IsControl(ch) ? '_' : ch).ToArray(); - var v = new string(c).Trim(' ', '.'); return v.Length == 0 ? "x" : v[..Math.Min(120, v.Length)]; - } - // Uncompressed 32-bit BGRA DDS (legacy header, A8R8G8B8 masks). - public static byte[] BgraDds(RageTexturePixels px) - { - var o = new byte[128 + px.Bgra32.Length]; - void U(int at, uint v) => BitConverter.TryWriteBytes(o.AsSpan(at), v); - U(0, 0x20534444); U(4, 124); U(8, 0x100F); U(12, (uint)px.Height); U(16, (uint)px.Width); U(20, (uint)(px.Width * 4)); - U(76, 32); U(80, 0x41); U(88, 32); U(92, 0x00FF0000); U(96, 0x0000FF00); U(100, 0x000000FF); U(104, 0xFF000000); U(108, 0x1000); - px.Bgra32.CopyTo(o, 128); return o; - } -} diff --git a/tools/rpf9dump/packages.lock.json b/tools/rpf9dump/packages.lock.json deleted file mode 100644 index 606e78df6..000000000 --- a/tools/rpf9dump/packages.lock.json +++ /dev/null @@ -1,26 +0,0 @@ -{ - "version": 1, - "dependencies": { - "net8.0": { - "BCnEncoder.Net": { - "type": "Transitive", - "resolved": "2.3.0", - "contentHash": "DJhHJiBJKXUXxlkkrv74ckzJb3wYxqIAZHjXD9G76kpsD0YyJOmqtNufHWEuJe0eH0tB1tCZn80/3JV2UVP7yQ==", - "dependencies": { - "CommunityToolkit.HighPerformance": "8.4.0" - } - }, - "CommunityToolkit.HighPerformance": { - "type": "Transitive", - "resolved": "8.4.0", - "contentHash": "flxspiBs0G/0GMp7IK2J2ijV9bTG6hEwFc/z6ekHqB6nwRJ4Ry2yLdx+TkbCUYFCl4XhABkAwomeKbT6zM2Zlg==" - }, - "rpfpreview.core": { - "type": "Project", - "dependencies": { - "BCnEncoder.Net": "[2.3.0, )" - } - } - } - } -} \ No newline at end of file diff --git a/tools/rpf9dump/rpf9dump.csproj b/tools/rpf9dump/rpf9dump.csproj deleted file mode 100644 index e14313b6f..000000000 --- a/tools/rpf9dump/rpf9dump.csproj +++ /dev/null @@ -1,5 +0,0 @@ - - Exenet8.0Majorenableenabletruetrue - - - diff --git a/tools/rpf_probe.py b/tools/rpf_probe.py deleted file mode 100644 index 63250b8d6..000000000 --- a/tools/rpf_probe.py +++ /dev/null @@ -1,138 +0,0 @@ -"""Survey the .rpf archives in a game folder: version magic, header words, and whether the table looks encrypted. - -Usage: - python -I rpf_probe.py [--out FILE] - -Reads the first 64 KiB of each archive only. It doesn't decrypt or extract anything. -A directory scan or archive read error stops the survey before it writes the report. -The report destination must not name an input archive or an alias of one. -""" -import argparse -import json -import math -import os -import struct -import sys -import tempfile -from collections import Counter - -# -I keeps the script directory off sys.path, so add it explicitly before importing the sibling module. -sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) -from file_mode import published_mode # noqa: E402 -from replace_retry import replace as replace_retry # noqa: E402 -from report_paths import same_report_path # noqa: E402 - - -def entropy(b: bytes) -> float: - if not b: - return 0.0 - n = len(b) - return -sum(c / n * math.log2(c / n) for c in Counter(b).values()) - - -def _write_json_report(path: str, rows: list) -> None: - """Publish complete JSON, or leave the previous report intact on replace failure.""" - # Resolve a symlinked --out to its target: the staged file then replaces the target, not the link. - destination = os.path.realpath(path) - out_dir = os.path.dirname(destination) or "." - os.makedirs(out_dir, exist_ok=True) - try: - mode = os.stat(destination).st_mode - except FileNotFoundError: - mode = None - except OSError: - # Non-regular destinations (pipes/devices) keep a direct write. - with open(destination, "w", encoding="utf-8", newline="\n") as f: - json.dump(rows, f, indent=1) - return - if mode is not None: - # Retain the direct writer's permission check without truncating the report. - os.close(os.open(destination, os.O_WRONLY)) - - staged = tempfile.NamedTemporaryFile( - mode="w", encoding="utf-8", newline="\n", delete=False, - dir=out_dir, prefix=".rpf_probe-", suffix=".tmp", - ) - try: - with staged: - json.dump(rows, staged, indent=1) - if os.name != "nt": - os.chmod(staged.name, published_mode(destination)) - replace_retry(staged.name, destination) - finally: - try: - os.unlink(staged.name) - except FileNotFoundError: - pass - - -def probe(path: str) -> dict: - with open(path, "rb") as f: - head = f.read(0x10000) - magic = head[:4] - # Little-endian 'RPFn' is stored as bytes 'nFPR'. - version = magic[::-1].decode("latin-1") if magic[1:] == b"FPR" else None - words = list(struct.unpack_from("<4I", head, 4)) if len(head) >= 20 else [] - body = head[16:] - return { - "file": path, - "size": os.path.getsize(path), - "version": version, - "header_words": [hex(w) for w in words], - "head_entropy": round(entropy(body), 3), - "looks_encrypted": entropy(body) > 7.9, - } - - -def main() -> int: - ap = argparse.ArgumentParser() - ap.add_argument("game_dir") - ap.add_argument("--out", default=os.path.join(os.path.dirname(__file__), "..", "reports", "rpf_probe.json")) - a = ap.parse_args() - if os.path.isdir(a.out): - print(f"ERROR: {a.out}: is a directory, not a file", file=sys.stderr) - return 2 - rows = [] - - def scan_failed(error: OSError) -> None: - raise error - - try: - archives = [] - for root, _, files in os.walk(a.game_dir, onerror=scan_failed): - for name in files: - if name.lower().endswith(".rpf"): - archives.append(os.path.join(root, name)) - for path in archives: - if same_report_path(a.out, path): - print(f"ERROR: --out would overwrite an input archive: {path}", file=sys.stderr) - return 2 - for path in archives: - rows.append(probe(path)) - except OSError as error: - path = error.filename or a.game_dir - reason = error.strerror or str(error) - print(f"ERROR: {path}: {reason}", file=sys.stderr) - return 2 - rows.sort(key=lambda r: (-r["size"], r["file"])) - try: - _write_json_report(a.out, rows) - except OSError as error: - reason = error.strerror or str(error) - print(f"ERROR: {a.out}: {reason}", file=sys.stderr) - return 2 - versions = Counter(r["version"] for r in rows) - print(f"{len(rows)} archives, {sum(r['size'] for r in rows) / 2**30:.1f} GiB, versions {dict(versions)}") - for r in rows: - rel = os.path.relpath(r["file"], a.game_dir) - print(f"{rel:<52} {r['size'] / 2**30:7.2f} GiB {r['version']} {' '.join(r['header_words'])} " - f"H={r['head_entropy']}{' packed/encrypted' if r['looks_encrypted'] else ''}") - return 0 - - -if __name__ == "__main__": - try: # a redirected stdout is strict ANSI code page under -I; write '?' for what it cannot encode - sys.stdout.reconfigure(errors="replace") - except (AttributeError, ValueError, OSError): - pass - sys.exit(main()) diff --git a/tools/rsc8_audio.py b/tools/rsc8_audio.py deleted file mode 100644 index 03510c4d1..000000000 --- a/tools/rsc8_audio.py +++ /dev/null @@ -1,2104 +0,0 @@ -"""Decode RSC8 (version 8001) facial/lip-sync animation clips embedded in AWC (ADAT) speech banks. - -`docs/story.md` and #716 flagged `RSC8` (version 8001) as the remaining undecoded mission-side -container in the story/minigame archives (`story000.rpf`, `shared_minigame000.rpf`, -`story000_restofworld.rpf`). Full-corpus decoding shows that `RSC8` v8001 is not a standalone -audio codec or audio container: every validated `RSC8` v8001 resource sits inside a standard -little-endian `ADAT` (AWC) bank as chunk tag `0x5c`, attached to a spoken dialogue stream whose -audio lives in sibling tag `0x55` (48 kHz mono Opus, codec `0x0b`, format tag `0x76`). - -Inside tag `0x5c`, the payload is an unencrypted RAGE `crClipDictionary` + `crClipAnimation` + -`crAnimationDictionary` + `crAnimation` facial/lip-sync animation resource: - - +0x00 4s "RSC8" - - +0x04 u32 version (8001 = 0x00001F41, or 0x01001F41 with version flag bit 24 set) - - +0x08 u32 body_size (bytes after +0x0C; exact tag 0x5c length == body_size + 12) - - +0x0C u32 flags (1) - - +0x10 ... virtual segment (`0x50xxxxxx` pointers resolve to `0x10 + (ptr - 0x50000000)`) - -This tool is stdlib-only, runs under `python -I`, decrypts nothing, and never writes game -strings or raw resource payloads to stdout, JSON, or CSV. Only structural offsets, sizes, -counts, hashes, string storage/lengths, frame counts, durations and track types are reported. - -Usage: - python -I tools/rsc8_audio.py [out.json|out.csv] - [--start N] [--limit BYTES] [--max-banks N] [--no-deep] [--curves] [--summary-only] [--quiet] - -`--curves` also decodes every clip's keyframes (the blocks are the sequence layout of -tools/anim_clips.py) and counts the outcome; it reports counts only, never a value. - -Every scan also reads the `0xbd` cue records of each stream; the summary's `marker_regions` block -matches the records whose value is joaat("start") or joaat("end") into region pairs, name by name -(pair_marker_regions(), docs/rsc8_audio.md). -""" -import argparse -import csv -import json -import math -import os -import statistics -import struct -import sys -import tempfile -import time - -sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) - -import anim_clips # noqa: E402 -from file_mode import published_mode # noqa: E402 - -RSC8_MAGIC = b"RSC8" -RSC8_VERSION = 8001 -RSC8_VERSION_FLAGGED = 0x01001F41 -RSC8_VERSIONS = (RSC8_VERSION, RSC8_VERSION_FLAGGED) -RSC8_FLAGS = 1 -RSC8_VIRTUAL_BASE = 0x10 -RSC8_VPTR_BASE = 0x50000000 -RSC8_VPTR_LIMIT = 0x60000000 -TRACK_SCHEMA_HASH = 0x364D3BDB # joaat("facialtranslation"): the track type of every directory entry - -ADAT_MAGIC = b"ADAT" -TAG_PEAK = 0x36 -TAG_STREAMED_MUSIC = 0x48 -TAG_DATA = 0x55 -TAG_GRID20 = 0x5A # undocumented 20-byte-entry table; decode_grid20_table() -TAG_RSC8_CLIP = 0x5C -TAG_FORMAT = 0x76 -TAG_SEEKTABLE = 0xA3 -TAG_LOUDNESS = 0xB2 -TAG_MARKER = 0xBD -TAG_INDEXRUN = 0xD9 # undocumented grouped index runs into the 0x5a entries; decode_index_runs() -# The most common cue-name hash of a `0xbd` record, not a magic: it is the first word of 88,082 of the -# 420,168 `0xbd` tags in `audio.rpf` (decode_marker_records()). The old name is kept for callers. -MARKER_NAME_COMMON = 0xE5C74063 -MARKER_MAGIC = MARKER_NAME_COMMON -MARKER_RECORD_BYTES = 16 -MAX_MARKER_BYTES = 16 * 1024 * 1024 -# A region cue stores a second name hash in its `value` word (pair_marker_regions()). -MARKER_VALUE_START = 0x84DC271F # joaat("start") -MARKER_VALUE_END = 0xB0C485D7 # joaat("end") -_REGION_VALUES = {MARKER_VALUE_START: "start", MARKER_VALUE_END: "end"} -MAX_REGION_EXCEPTIONS_LISTED = 64 - -ATTR_FLOAT = 0xFFFF0001 -ATTR_INT = 0xFFFF0002 -ATTR_BOOL = 0xFFFF0003 -ATTR_STRING = 0xFFFF0004 -ATTR_GUID = 0xFFFF000E -PROP_KEY_FPS = 0x10BF2F94 -PROP_KEY_LEAD_IN = 0xAAA6AF06 - -MAX_HEADER_BYTES = 32 * 1024 * 1024 -MAX_RSC8_BYTES = 32 * 1024 * 1024 -MAX_AWC_FILE_BYTES = 512 * 1024 * 1024 -MAX_BANK_STREAMS = 200_000 -MAX_ANIM_BLOCKS = 256 -MAX_TRACK_ENTRIES = 4096 -MAX_PROP_ENTRIES = 256 -SCAN_CHUNK_BYTES = 32 * 1024 * 1024 -PROGRESS_BYTES = 2 * 1024 * 1024 * 1024 - -CSV_COLUMNS = [ - "bank_offset", - "tag_offset", - "stream_id", - "tag_size", - "body_size", - "version", - "flags", - "stream_hash", - "dict_name_storage", - "dict_name_len", - "anim_block_count", - "anim_size", - "frame_count", - "clip_duration", - "audio_duration", - "audio_codec", - "audio_channels", - "audio_sample_rate", - "track_count", - "prop_count", - "valid", -] - - -def _u16(buf, off): - return struct.unpack_from(" vlen: - return None - q = _u64(virt, voff) - if q == 0: - return 0 - if RSC8_VPTR_BASE <= q < RSC8_VPTR_LIMIT: - target = q - RSC8_VPTR_BASE - if 0 <= target < vlen: - return target - return None - - -def _cstr_info(virt, off, max_scan=1024): - """Measure a NUL-terminated printable ASCII string without returning its text.""" - vlen = len(virt) - if off is None or off < 0 or off >= vlen: - return False, 0 - end = min(vlen, off + max_scan) - seg = bytes(virt[off:end]) - nul = seg.find(b"\x00") - if nul < 0: - return False, 0 - printable = all(32 <= b < 127 for b in seg[:nul]) - return printable, nul - - -def decode_sso_string(virt, voff): - """Decode a 16-byte RAGE SSO `atString` at `virt[voff : voff + 16]`. - - Layout: - - Inline mode: `byte[15] & 0x80 != 0`; `length = byte[15] & 0x7F` (<= 14), - ASCII text in `raw[0:length]`, NUL at `raw[length]`. - - Heap mode: `u64 ptr` (`0x50xxxxxx`), `u16 length`, `u16 capacity`, `u32 flags (= 1)`, - NUL-terminated ASCII string at `virt[ptr : ptr + length + 1]`. - - Never returns raw string content. - """ - vlen = len(virt) - if voff < 0 or voff + 16 > vlen: - return { - "storage": "invalid", - "length": 0, - "capacity": None, - "flags": None, - "ptr": None, - "ok": False, - } - raw = bytes(virt[voff : voff + 16]) - last = raw[15] - if last & 0x80: - length = last & 0x7F - ok = ( - length <= 14 - and raw[length] == 0 - and all(32 <= b < 127 for b in raw[:length]) - ) - return { - "storage": "inline", - "length": length, - "capacity": 15, - "flags": last, - "ptr": None, - "ok": ok, - } - ptr = resolve_vptr(virt, voff) - length, capacity, flags = struct.unpack_from("= vlen: - return { - "storage": "heap", - "length": length, - "capacity": capacity, - "flags": flags, - "ptr": ptr, - "ok": False, - } - text_ok = virt[ptr + length] == 0 and all(32 <= b < 127 for b in virt[ptr : ptr + length]) - return { - "storage": "heap", - "length": length, - "capacity": capacity, - "flags": flags, - "ptr": ptr, - "ok": text_ok and flags == 1, - } - - -def decode_properties(virt, props_off, props_size): - """Decode the `crProperties` table at `virt[props_off : props_off + props_size]`.""" - vlen = len(virt) - if ( - props_off is None - or props_off <= 0 - or props_size < 0x20 - or props_off + props_size > vlen - ): - return { - "in_bounds": False, - "clip_ptr": None, - "count": 0, - "capacity": 0, - "attributes": [], - "fps": None, - "lead_in": None, - "attrs_tiled_to_end": False, - } - - clip_ptr = resolve_vptr(virt, props_off + 0x10) - prop_count = _u32(virt, props_off + 0x18) - prop_cap = _u32(virt, props_off + 0x1C) - result = { - "in_bounds": True, - "clip_ptr": clip_ptr, - "count": prop_count, - "capacity": prop_cap, - "attributes": [], - "fps": None, - "lead_in": None, - "attrs_tiled_to_end": False, - } - if prop_count > MAX_PROP_ENTRIES: - result["in_bounds"] = False - return result - - # Locate typed attribute records `(u32 key_hash, u32 0xFFFFxxxx type_id, ...)` in the tail - # after the `0x48`-byte property descriptors (descriptors start after the 0x70-byte map header). - tail_start = 0x70 + prop_count * 0x48 - if tail_start > props_size: - result["in_bounds"] = False - return result - # Advance to the first aligned typed attribute (0xFFFFxxxx marker at +4). - pos = tail_start - while pos + 8 <= props_size and (_u32(virt, props_off + pos + 4) >> 16) != 0xFFFF: - pos += 4 - - attrs = [] - while pos + 8 <= props_size and len(attrs) < MAX_PROP_ENTRIES: - key_hash = _u32(virt, props_off + pos) - attr_type = _u32(virt, props_off + pos + 4) - if (attr_type >> 16) != 0xFFFF: - break - if attr_type == ATTR_STRING: - if pos + 0x40 > props_size: - break - str_len = _u64(virt, props_off + pos + 0x18) - attrs.append({"key_hash": key_hash, "type": attr_type, "string_len": str_len}) - pos += 0x40 - elif attr_type == ATTR_GUID: - if pos + 0x20 > props_size: - break - attrs.append({"key_hash": key_hash, "type": attr_type, "guid_bytes": 16}) - pos += 0x20 - elif attr_type in (ATTR_FLOAT, ATTR_INT, ATTR_BOOL): - if pos + 0x0C > props_size: - break - if attr_type == ATTR_FLOAT: - val = _f32(virt, props_off + pos + 8) - entry = {"key_hash": key_hash, "type": attr_type, "value": round(val, 6) if math.isfinite(val) else None} - if key_hash == PROP_KEY_LEAD_IN and math.isfinite(val): - result["lead_in"] = round(val, 6) - else: - val = _u32(virt, props_off + pos + 8) - entry = {"key_hash": key_hash, "type": attr_type, "value": val} - if key_hash == PROP_KEY_FPS and attr_type == ATTR_INT: - result["fps"] = val - attrs.append(entry) - pos += 0x0C - else: - break - - result["attributes"] = attrs - result["attrs_tiled_to_end"] = pos == props_size - return result - - -def _has_embedded_audio_container(data): - """Return True only if `data` contains a validated AWC, Ogg Opus, or RIFF WAVE header.""" - raw = data if isinstance(data, (bytes, bytearray)) else bytes(data) - mv_raw = memoryview(raw) - rlen = len(raw) - pos = 0 - while True: - idx = raw.find(ADAT_MAGIC, pos) - if idx < 0: - break - if parse_adat_header_bytes(mv_raw[idx:], 0, rlen - idx) is not None: - return True - pos = idx + 4 - if b"OggS\x00" in raw and b"OpusHead" in raw: - return True - pos = 0 - while True: - idx = raw.find(b"RIFF", pos) - if idx < 0: - break - if idx + 12 <= rlen and raw[idx + 8 : idx + 12] == b"WAVE": - return True - pos = idx + 4 - return False - - -def decode_facial_curves(virt, anim, anim_desc, stats=None): - """Decode the keyframes of one clip: `({track index: [value tuple per frame]}, frames, tracks)`. - - `virt` is the resource from `RSC8_VIRTUAL_BASE` on; `anim` and `anim_desc` come from `decode_rsc8`. - A packed block is one sequence of tools/anim_clips.py (0x20-byte header, version 2, 11 channel - types) and the track directory is its 12-byte `{id hash, track-type hash, value format}` list, so - the block and track decoders are that tool's. `tracks` is the directory as stored. Raises - `anim_clips.DecodeError` when a block does not decode. A contiguous view is decoded in place, - without copying the resource. - """ - if isinstance(virt, memoryview): - virt = virt.cast("B") if virt.c_contiguous else bytes(virt) - system = anim_clips.System(virt) - at, count = anim_desc["track_ptr"] or 0, anim_desc["track_count"] or 0 - if count and at + 12 * count > len(system.d): - raise anim_clips.DecodeError("track directory runs past the resource") - tracks = [struct.unpack_from(":"` per track, and whether the frame count and the header's - quantised-bit sum agree with the decoded data. - """ - stats = anim_clips.new_stats() - try: - values, frames, tracks = decode_facial_curves(virt, anim, anim_desc, stats) - except anim_clips.DecodeError as e: - return {"decoded": False, "error": str(e)[:80]} - components = {} - for index, rows in values.items(): - key = f"{tracks[index][2]}:{len(rows[0]) if rows else 0}" - components[key] = components.get(key, 0) + 1 - blocks = len(anim["blocks"]) - return { - "decoded": True, - "error": None, - "frames": frames, - "frames_match": frames == anim["frame_count"] and stats["frames_sum_matches"] == 1, - "quantize_bits_match": stats["quantize_bits_match"] == blocks, - "tracks_with_values": len(values), - "channels": {k[len("channel:"):]: v for k, v in sorted(stats.items()) if k.startswith("channel:")}, - "delta2_boundaries": stats["delta2_boundaries"], - "delta2_boundaries_closed": stats["delta2_boundaries_closed"], - "components": components, - } - - -def decode_rsc8(data, *, stream_id=None, deep=True, curves=False): - """Decode one `RSC8` (version 8001) facial/lip-sync animation resource. - - Accepts `bytes`, `bytearray`, or `memoryview`. Returns a structured dict of decoded fields - and boolean integrity checks. Never raises on malformed/truncated input (returns `valid=False`). - """ - mv = memoryview(data) - total_size = len(mv) - checks = { - "min_size_ok": total_size >= 0xE0, - "magic_ok": total_size >= 4 and bytes(mv[:4]) == RSC8_MAGIC, - "version_ok": False, - "size_matches_body_plus_12": False, - "flags_ok": False, - "aligned_16": (total_size % 16) == 0, - "dict_name_ok": False, - "anim_dict_entry_ok": False, - "props_in_bounds": False, - "clip_in_bounds": False, - "clip_name_ok": False, - "clip_hash_matches_root": False, - "clip_duration_matches_frames": False, - "anim_desc_in_bounds": False, - "anim_blocks_in_bounds": False, - "anim_payload_plus_32_eq_size": False, - "anim_chunk_off_in_bounds": False, - "anim_format_v2": False, - "anim_track_tag_11": False, - "anim_max_block_size_matches_desc": False, - "tracks_in_bounds": False, - "tracks_sorted": False, - "tracks_schema_ok": False, - "no_embedded_audio_container": True, - } - if stream_id is not None: - checks["stream_id_matches"] = False - - out = { - "total_size": total_size, - "magic": bytes(mv[:4]).decode("ascii", "replace") if total_size >= 4 else "", - "version": None, - "version_base": None, - "version_flags": None, - "body_size": None, - "flags": None, - "virtual_size": max(0, total_size - RSC8_VIRTUAL_BASE), - "stream_hash": None, - "dict_flags": None, - "dict_name": None, - "clip_map_buckets": None, - "clip_map_count": None, - "hash_map_buckets": None, - "hash_map_count": None, - "props_ptr": None, - "props_size": None, - "anim": None, - "clip": None, - "anim_desc": None, - "properties": None, - "tracks": None, - "curves": None, - "checks": checks, - "valid": False, - } - - if total_size < 0xE0 or not checks["magic_ok"]: - return out - - checks["no_embedded_audio_container"] = not _has_embedded_audio_container(data if isinstance(data, (bytes, bytearray)) else mv) - - version, body_size, flags = struct.unpack_from("> 16 - out["body_size"] = body_size - out["flags"] = flags - checks["version_ok"] = version in RSC8_VERSIONS - checks["size_matches_body_plus_12"] = body_size + 12 == total_size - checks["flags_ok"] = flags == RSC8_FLAGS - - virt = mv[RSC8_VIRTUAL_BASE:] - vlen = len(virt) - - # Root crClipDictionary at virt+0x00 .. virt+0xAF - dict_name = decode_sso_string(virt, 0x38) - out["dict_name"] = dict_name - checks["dict_name_ok"] = dict_name["ok"] - - out["clip_map_buckets"] = _u32(virt, 0x50) - out["clip_map_count"] = _u32(virt, 0x58) - stream_hash = _u32(virt, 0x68) - dict_flags = _u32(virt, 0x6C) - out["stream_hash"] = stream_hash - out["dict_flags"] = dict_flags - if stream_id is not None: - checks["stream_id_matches"] = (stream_hash & 0x1FFFFFFF) == stream_id - - out["hash_map_buckets"] = _u32(virt, 0x88) - out["hash_map_count"] = _u32(virt, 0x90) - - props_ptr = resolve_vptr(virt, 0xA0) - props_size = _u32(virt, 0xA8) - out["props_ptr"] = props_ptr - out["props_size"] = props_size - - # anim_dict_array at virt+0x70 (16-byte entries: u64 anim_dict_ptr, u32 anim_dict_hash, u32 flags) - arr70_ptr = resolve_vptr(virt, 0x70) - arr70_cnt, arr70_cap = struct.unpack_from(" 0 and props_size >= 0x20 and props_ptr + props_size <= vlen) - p_cnt = _u32(virt, props_ptr + 0x18) if props_ok else 0 - p_cap = _u32(virt, props_ptr + 0x1C) if props_ok else 0 - if props_ok and (p_cnt > MAX_PROP_ENTRIES or 0x70 + p_cnt * 0x48 > props_size): - props_ok = False - props = { - "in_bounds": props_ok, - "clip_ptr": resolve_vptr(virt, props_ptr + 0x10) if props_ok else None, - "count": p_cnt, - "capacity": p_cap, - "attributes": [], - "fps": None, - "lead_in": None, - "attrs_tiled_to_end": False, - } - out["properties"] = props - checks["props_in_bounds"] = props["in_bounds"] - - clip_ptr = props["clip_ptr"] - if clip_ptr and clip_ptr > 0 and clip_ptr + 0xA0 <= vlen: - checks["clip_in_bounds"] = True - clip_name = decode_sso_string(virt, clip_ptr + 0x28) - clip_hash = _u32(virt, clip_ptr + 0x58) - anim_desc_ptr = resolve_vptr(virt, clip_ptr + 0x68) - duration = _f32(virt, clip_ptr + 0x94) - rate = _f32(virt, clip_ptr + 0x98) - out["clip"] = { - "voff": clip_ptr, - "name": clip_name, - "hash": clip_hash, - "anim_desc_ptr": anim_desc_ptr, - "duration": round(duration, 6) if math.isfinite(duration) else None, - "rate": round(rate, 6) if math.isfinite(rate) else None, - } - checks["clip_name_ok"] = clip_name["ok"] - checks["clip_hash_matches_root"] = clip_hash == stream_hash - - # crAnimation descriptor at anim_desc_ptr - if anim_desc_ptr and anim_desc_ptr > 0 and anim_desc_ptr + 0x70 <= vlen: - checks["anim_desc_in_bounds"] = True - anim_dict_ref = resolve_vptr(virt, anim_desc_ptr + 0x18) - anim_name_ptr = resolve_vptr(virt, anim_desc_ptr + 0x30) - anim_name_ok, anim_name_len = _cstr_info(virt, anim_name_ptr) if anim_name_ptr else (False, 0) - max_blk_desc = _u32(virt, anim_desc_ptr + 0x48) - blk_arr_ptr = resolve_vptr(virt, anim_desc_ptr + 0x50) - blk_cnt, blk_cap = struct.unpack_from("`). - # Multi-block clips split long facial animations across adjacent blocks sharing the boundary - # frame, so total_frames = sum(block.frame_count) - (block_count - 1). - if ( - blk_arr_ptr - and 1 <= blk_cnt <= blk_cap - and blk_cnt <= MAX_ANIM_BLOCKS - and blk_arr_ptr + blk_cnt * 8 <= vlen - ): - blocks = [] - seen_bo = set() - all_in_bounds = True - all_payload_ok = True - all_chunk_ok = True - all_v2 = True - all_tag11 = True - for bi in range(blk_cnt): - bo = resolve_vptr(virt, blk_arr_ptr + bi * 8) - if bo is None or bo < 0xB0 or bo + 32 > vlen or bo in seen_bo: - all_in_bounds = False - break - seen_bo.add(bo) - ( - anim_sig, - payload_sz, - zero_b8, - chunk_off, - anim_sz, - fmt_ver, - b_frames, - extra_flags, - sub_count, - track_tag, - ) = struct.unpack_from(" vlen: - all_in_bounds = False - if payload_sz + 32 != anim_sz: - all_payload_ok = False - if chunk_off > payload_sz: - all_chunk_ok = False - if fmt_ver != 2: - all_v2 = False - if track_tag != 11: - all_tag11 = False - blocks.append({ - "voff": bo, - "signature": anim_sig, - "payload_size": payload_sz, - "reserved": zero_b8, - "chunk_data_offset": chunk_off, - "anim_size": anim_sz, - "format_version": fmt_ver, - "frame_count": b_frames, - "extra_flags": extra_flags, - "sub_count": sub_count, - "track_format_tag": track_tag, - }) - - if len(blocks) == blk_cnt: - total_anim_sz = sum(b["anim_size"] for b in blocks) - max_blk_sz = max(b["anim_size"] for b in blocks) - total_frames = sum(b["frame_count"] for b in blocks) - (len(blocks) - 1) - out["anim"] = { - "block_count": len(blocks), - "anim_size": total_anim_sz, - "max_block_size": max_blk_sz, - "frame_count": total_frames, - "blocks": blocks, - } - checks["anim_blocks_in_bounds"] = all_in_bounds - checks["anim_payload_plus_32_eq_size"] = all_payload_ok - checks["anim_chunk_off_in_bounds"] = all_chunk_ok - checks["anim_format_v2"] = all_v2 - checks["anim_track_tag_11"] = all_tag11 - checks["anim_max_block_size_matches_desc"] = max_blk_sz == max_blk_desc - if deep: - raw_fps = props.get("fps") - fps = 60 if raw_fps is None else raw_fps - expected_dur = (total_frames - 1) / float(fps) if total_frames > 0 and fps > 0 else 0.0 - checks["clip_duration_matches_frames"] = ( - math.isfinite(duration) - and fps > 0 - and all(b["frame_count"] > 0 for b in blocks) - and total_frames > 0 - and abs(duration - expected_dur) < 1e-4 - ) - - # Sorted track directory: count * 12 bytes - if tr_cnt == 0: - checks["tracks_in_bounds"] = tr_ptr == 0 or (tr_ptr is not None and tr_ptr <= vlen) - if deep: - checks["tracks_sorted"] = True - checks["tracks_schema_ok"] = True - out["tracks"] = {"count": 0, "type_counts": {}} - elif ( - tr_ptr - and tr_ptr > 0 - and tr_cnt <= tr_cap - and tr_cnt <= MAX_TRACK_ENTRIES - and tr_ptr + tr_cnt * 12 <= vlen - ): - checks["tracks_in_bounds"] = True - if deep: - prev_h = -1 - is_sorted = True - schema_ok = True - type_counts = {} - for ti in range(tr_cnt): - th, schema_h, ttype = struct.unpack_from(" MAX_BANK_STREAMS - or hdr_sz < 16 - or hdr_sz > MAX_HEADER_BYTES - or hdr_sz > len(hb) - or bank_offset + hdr_sz > file_size - ): - return None - pos = 16 - if flags & 0x00400000: - pos += 4 - if flags & 0x00010000: - pos += count * 2 - if flags & 0x00200000: - pos += (count + 1) * 4 - if count == 0: - # No stream ids and no tag rows follow, so the tables must fill the header exactly. - if pos != hdr_sz: - return None - elif pos + count * 4 > hdr_sz: - return None - - streams = [] - total_tags = 0 - for _ in range(count): - w = _u32(hb, pos) - pos += 4 - tc = w >> 29 - sid = w & 0x1FFFFFFF - total_tags += tc - streams.append((tc, sid)) - if pos + total_tags * 8 > hdr_sz: - return None - - max_end = hdr_sz - entries = [] - for tc, sid in streams: - tags = [] - for _ in range(tc): - q = _u64(hb, pos) - pos += 8 - tt = (q >> 56) & 0xFF - tsz = (q >> 28) & 0x0FFFFFFF - toff = q & 0x0FFFFFFF - if bank_offset + toff + tsz > file_size: - return None - if toff + tsz > max_end: - max_end = toff + tsz - tags.append((tt, toff, tsz)) - entries.append((sid, tags)) - - return { - "offset": bank_offset, - "flags": flags, - "count": count, - "header_size": hdr_sz, - "end": bank_offset + max_end, - "entries": entries, - } - - -def parse_adat_at_file(fh, bank_offset, file_size): - """Read and parse one `ADAT` bank header at `bank_offset` in open binary file `fh`. - - Zero-stream banks are validated by :func:`parse_adat_header_bytes`. - """ - if bank_offset < 0 or bank_offset + 16 > file_size: - return None - fh.seek(bank_offset) - hdr16 = fh.read(16) - if len(hdr16) < 16 or hdr16[:4] != ADAT_MAGIC: - return None - _, count, hdr_sz = struct.unpack_from(" MAX_BANK_STREAMS - or hdr_sz < 16 - or hdr_sz > MAX_HEADER_BYTES - or bank_offset + hdr_sz > file_size - ): - return None - fh.seek(bank_offset) - hb = fh.read(hdr_sz) - if len(hb) < hdr_sz: - return None - return parse_adat_header_bytes(hb, bank_offset, file_size) - - -GRID20_MAGIC = 12345678 -MAX_GRID20_BYTES = 64 * 1024 * 1024 -MAX_INDEXRUN_GROUPS = 1 << 20 - - -def decode_grid20_table(blob): - """Structurally decode the undocumented ``0x5a`` companion table. - - Measured on every one of the 1,185 ``audio.rpf`` streams that carry the tag (ASSET-256, framing - from @kotorvr's finding in #3232): a u32 ``12345678`` marker, ``N`` 20-byte entries, then an f32 - trailer, so ``size == 8 + 20 * N``:: - - +0 u32 position (a sample position at the stream's rate: strictly increasing, below the - stream's 0x76 sample count) - +4 f32 value (3.66..146.8; (position[k+1] - position[k]) * value[k] / rate is within 1% of 1 - on 365,803 of the 386,048 entry pairs, so it reads as a pitch in Hz) - +8 u16 p (a multiple of 512 on every measured entry), +10 u16 z (0..16 measured) - +12 u16 index_lo, +14 u16 index_hi - +16 u16 s, +18 u16 t - trailer: f32 (2/3 on 1,182 of the 1,185 streams), returned as ``tail_f32`` - - Nothing is guessed about ``p``, ``z``, ``s``, ``t`` or the trailer; the return value carries the - structural facts and the invariant checks only. - """ - out = { - "size_ok": False, - "magic_ok": None, - "entries": None, - "position_first": None, - "position_last": None, - "position_increasing": None, - "tail_f32": None, - "p_multiple_of_32": None, - } - raw = bytes(blob) - if len(raw) < 8 or len(raw) > MAX_GRID20_BYTES or (len(raw) - 8) % 20: - return out - out["size_ok"] = True - magic, = struct.unpack_from(" MAX_GRID20_BYTES: - return out - out["size_ok"] = True - vals = struct.unpack_from(f"<{len(raw) // 4}I", raw, 0) - declared, at = vals[0], 1 - groups = 0 - hashes = set() - values = 0 - index_max = None - ascending = True - marker_ok = True - while at < len(vals): - if at + 3 > len(vals) or groups >= MAX_INDEXRUN_GROUPS: - out["size_ok"] = False - return out - marker, length, h = vals[at], vals[at + 1], vals[at + 2] - if marker != 2: - marker_ok = False - if length > len(vals) - at - 3: - out["size_ok"] = False - return out - hashes.add(h) - run = vals[at + 3 : at + 3 + length] - if any(run[i] >= run[i + 1] for i in range(len(run) - 1)): - ascending = False - if run: - run_max = max(run) - index_max = run_max if index_max is None else max(index_max, run_max) - values += length - at += 3 + length - groups += 1 - out["group_count_matches"] = groups == declared - out["marker_ok"] = marker_ok - out["hash_single"] = len(hashes) == 1 - out["hashes"] = sorted(hashes) - out["groups"] = groups - out["values"] = values - out["indices_ascending"] = ascending - out["index_max"] = index_max - if grid_entries is None: - out["indices_within_grid"] = None - else: - out["indices_within_grid"] = True if index_max is None else index_max < grid_entries - return out - - -def decode_marker_records(blob, sample_count=None): - """Structurally decode a ``0xbd`` (``markers``) tag: a list of 16-byte cue records. - - Measured on all 420,168 ``0xbd`` tags of ``audio.rpf`` (781,350 records): the size is always a - multiple of 16, there is no header, and every record is:: - - +0 u32 name joaat of the cue name (167 distinct values) - +4 u32 value an f32 for most names, a second name hash for region cues - +8 u32 offset sample position in the stream; never decreases from one record to the next - +12 u32 extra 0..6 measured - - ``name`` and ``value`` are returned as stored. With ``sample_count`` (the stream's ``0x76`` count), - ``offsets_within_samples`` says whether every offset is at most that count. - """ - out = { - "size_ok": False, - "records": None, - "names": None, - "first_name": None, - "offsets_ascending": None, - "offset_max": None, - "offsets_within_samples": None, - "extra_max": None, - } - raw = bytes(blob) - if not raw or len(raw) % MARKER_RECORD_BYTES or len(raw) > MAX_MARKER_BYTES: - return out - out["size_ok"] = True - n = len(raw) // MARKER_RECORD_BYTES - names = {} - ascending = True - prev = None - offset_max = 0 - extra_max = 0 - for i in range(n): - name, _value, offset, extra = struct.unpack_from(" region["start"]] - for a in active: - if a["name"] == region["name"]: - continue - counts = out.setdefault((min(a["name"], region["name"]), max(a["name"], region["name"])), [0, 0]) - nested = region["end"] <= a["end"] or region["start"] == a["start"] - counts[0 if nested else 1] += 1 - active.append(region) - return out - - -def _new_region_tally(): - """Running totals of pair_marker_regions() over the tags of a scan; marker_region_report() finishes them.""" - return { - "tags": 0, # tags with at least one start/end record - "tags_all_paired": 0, # ... and no exception - "tags_with_sample_count": 0, # ... on a stream that has a 0x76 sample count - "pairs_per_tag": [], - "pairs_extra_differs": 0, - "overlaps": {}, # marker_region_overlaps(), added up - "names": {}, # name -> the counts of pair_marker_regions(), "tags" and the "lengths" of its pairs - "exceptions_total": 0, - "exceptions": [], # the first MAX_REGION_EXCEPTIONS_LISTED in scan order - } - - -def _tally_marker_regions(tally, records, *, bank_offset=0, stream_id=None, sample_count=None): - """Add one valid ``0xbd`` tag's region pairing to a `_new_region_tally()`.""" - paired = pair_marker_regions(records) - if not paired["names"]: - return - tally["tags"] += 1 - tally["tags_all_paired"] += not paired["exceptions"] - tally["tags_with_sample_count"] += sample_count is not None - tally["pairs_per_tag"].append(len(paired["regions"])) - for name, counts in paired["names"].items(): - into = tally["names"].setdefault(name, {"tags": 0, "lengths": []}) - into["tags"] += 1 - for key, count in counts.items(): - into[key] = into.get(key, 0) + count - for region in paired["regions"]: - tally["names"][region["name"]]["lengths"].append(region["end"] - region["start"]) - tally["pairs_extra_differs"] += region["extra_differs"] - _add_region_overlaps(tally["overlaps"], marker_region_overlaps(paired["regions"])) - tally["exceptions_total"] += len(paired["exceptions"]) - for exc in paired["exceptions"]: - if len(tally["exceptions"]) >= MAX_REGION_EXCEPTIONS_LISTED: - break - tally["exceptions"].append({ - "kind": exc["kind"], - "name": f"0x{exc['name']:08x}", - "value": f"0x{exc['value']:08x}", - "before": exc["before"], - "before_offset": exc["before_offset"], - "after": exc["after"], - "after_offset": exc["after_offset"], - "record": exc["index"], - "tag_records": len(records), - "offset": exc["offset"], - "tag_last_offset": records[-1][2], - "stream_samples": sample_count, - "bank_offset": bank_offset, - "stream_id": None if stream_id is None else f"0x{stream_id:08x}", - }) - - -def _add_region_overlaps(dst, src): - for names, (nested, crossing) in src.items(): - into = dst.setdefault(names, [0, 0]) - into[0] += nested - into[1] += crossing - - -def _merge_region_tally(dst, src): - for key, value in src.items(): - if key == "overlaps": - _add_region_overlaps(dst[key], value) - elif key == "names": - for name, counts in value.items(): - into = dst["names"].setdefault(name, {"tags": 0, "lengths": []}) - for field, count in counts.items(): - if field == "lengths": - into["lengths"].extend(count) - else: - into[field] = into.get(field, 0) + count - elif key == "exceptions": - dst[key].extend(value[: MAX_REGION_EXCEPTIONS_LISTED - len(dst[key])]) - elif isinstance(value, list): - dst[key].extend(value) - else: - dst[key] += value - - -def _min_median_max(values): - if not values: - return None - return {"min": min(values), "median": statistics.median(values), "max": max(values)} - - -def marker_region_report(tally): - """The `marker_regions` block of a scan summary, from a `_new_region_tally()`: counts, sample - offsets and 32-bit hashes only. - - ``names`` maps each region name (hex) to its ``starts``, ``ends``, ``pairs``, the four exception - counts of pair_marker_regions() and the ``length_samples`` (min/median/max) of its pairs. - ``overlaps_between_names`` counts pairs of paired regions of different names in one tag that share a - sample (marker_region_overlaps()), in all and per pair of names. ``exceptions`` lists the first - `MAX_REGION_EXCEPTIONS_LISTED` in scan order with where each one sits: its record index among the - tag's ``tag_records``, its offset, the tag's last offset, the stream's ``0x76`` sample count when it - has one, and what and where the neighbouring records of the same name are (``None``: it is the - name's first or last record of the tag). ``exceptions_total`` counts them all. - """ - names = {} - for name, counts in sorted(tally["names"].items(), key=lambda kv: (-kv[1]["starts"] - kv[1]["ends"], kv[0])): - row = {key: value for key, value in counts.items() if key != "lengths"} - row["length_samples"] = _min_median_max(counts["lengths"]) - names[f"0x{name:08x}"] = row - return { - "tags": tally["tags"], - "tags_all_paired": tally["tags_all_paired"], - "tags_with_sample_count": tally["tags_with_sample_count"], - "starts": sum(c["starts"] for c in tally["names"].values()), - "ends": sum(c["ends"] for c in tally["names"].values()), - "pairs": sum(c["pairs"] for c in tally["names"].values()), - "pairs_per_tag": _min_median_max(tally["pairs_per_tag"]), - "pairs_extra_differs": tally["pairs_extra_differs"], - "overlaps_between_names": { - "nested": sum(n for n, _c in tally["overlaps"].values()), - "crossing": sum(c for _n, c in tally["overlaps"].values()), - "by_names": { - f"0x{a:08x}+0x{b:08x}": {"nested": n, "crossing": c} - for (a, b), (n, c) in sorted(tally["overlaps"].items()) - }, - }, - "names": names, - "exceptions_total": tally["exceptions_total"], - "exceptions": list(tally["exceptions"]), - } - - -def _decode_companion_tags(read_slice, bank_offset, tag_map): - """Decode companion speech tags (`0x76`, `0x55`, `0x36`, `0x5a`, `0xa3`, `0xb2`, `0xbd`, `0xd9`) on a stream.""" - comp = { - "has_audio_data": TAG_DATA in tag_map, - "audio_data_bytes": tag_map[TAG_DATA][0][1] if TAG_DATA in tag_map else 0, - "audio_samples": None, - "audio_sample_rate": None, - "audio_codec": None, - "audio_channels": None, - "audio_duration": None, - "peak_entries": tag_map[TAG_PEAK][0][1] // 2 if TAG_PEAK in tag_map else 0, - "seek_entries": tag_map[TAG_SEEKTABLE][0][1] // 4 if TAG_SEEKTABLE in tag_map else 0, - "loudness_entries": tag_map[TAG_LOUDNESS][0][1] // 8 if TAG_LOUDNESS in tag_map else 0, - "markers": None, - } - if TAG_FORMAT in tag_map: - fo, fs = tag_map[TAG_FORMAT][0] - if fs >= 30: - fb = read_slice(bank_offset + fo, min(fs, 32)) - if len(fb) >= 30: - samples = _u32(fb, 0) - sr = _u16(fb, 8) - codec = fb[28] - ch = fb[29] - comp["audio_samples"] = samples - comp["audio_sample_rate"] = sr - comp["audio_codec"] = codec - comp["audio_channels"] = ch - if sr > 0: - comp["audio_duration"] = round(samples / float(sr), 6) - if TAG_MARKER in tag_map: - mo, ms = tag_map[TAG_MARKER][0] - if 0 < ms <= MAX_MARKER_BYTES: - comp["markers"] = decode_marker_records(read_slice(bank_offset + mo, ms), comp["audio_samples"]) - grid = None - if TAG_GRID20 in tag_map: - go, gs = tag_map[TAG_GRID20][0] - if 0 < gs <= MAX_GRID20_BYTES: - grid = decode_grid20_table(read_slice(bank_offset + go, gs)) - comp["grid20"] = grid - if TAG_INDEXRUN in tag_map: - io, isz = tag_map[TAG_INDEXRUN][0] - if 0 < isz <= MAX_GRID20_BYTES: - comp["indexrun"] = decode_index_runs( - read_slice(bank_offset + io, isz), - grid["entries"] if grid and grid["size_ok"] else None, - ) - return comp - - -def _make_record(bank_offset, tag_offset, stream_id, decoded, comp): - anim = decoded.get("anim") or {} - clip = decoded.get("clip") or {} - props = decoded.get("properties") or {} - tracks = decoded.get("tracks") or {} - dname = decoded.get("dict_name") or {} - return { - "bank_offset": bank_offset, - "tag_offset": tag_offset, - "stream_id": stream_id, - "tag_size": decoded["total_size"], - "body_size": decoded["body_size"], - "version": decoded["version"], - "flags": decoded["flags"], - "stream_hash": decoded["stream_hash"], - "dict_name_storage": dname.get("storage"), - "dict_name_len": dname.get("length"), - "anim_block_count": anim.get("block_count"), - "anim_size": anim.get("anim_size"), - "frame_count": anim.get("frame_count"), - "clip_duration": clip.get("duration"), - "has_audio_data": comp["has_audio_data"] if comp else None, - "audio_duration": comp["audio_duration"] if comp else None, - "audio_codec": comp["audio_codec"] if comp else None, - "audio_channels": comp["audio_channels"] if comp else None, - "audio_sample_rate": comp["audio_sample_rate"] if comp else None, - "track_count": tracks.get("count"), - "track_types": tracks.get("type_counts") or {}, - "prop_count": props.get("count"), - "curves": decoded.get("curves"), - "valid": decoded["valid"], - "checks": decoded["checks"], - } - - -def _new_grid_tally(): - return { - "grid20_streams": 0, - "grid20_entries": 0, - "grid20_invalid": 0, - # Streams with a 0x76 sample count whose last position is not below it (0 over audio.rpf, ASSET-256). - "grid20_position_past_samples": 0, - "indexrun_streams": 0, - "indexrun_groups": 0, - "indexrun_invalid": 0, - "indexrun_index_overruns": 0, - "marker_streams": 0, - "marker_records": 0, - "marker_invalid": 0, - "marker_first_names": {}, - # Region cues matched into start/end pairs (ASSET-320). A running `_new_region_tally()` while banks are - # read and in decode_awc_bank()'s result; a scan's summary carries marker_region_report() of it. - "marker_regions": _new_region_tally(), - } - - -def _merge_grid_tally(dst, src): - """Add one bank's companion-table tally to a running summary (counts add, per-name maps merge).""" - for key, start in _new_grid_tally().items(): - if key == "marker_regions": - _merge_region_tally(dst[key], src[key]) - elif isinstance(start, dict): - for name, count in src[key].items(): - dst[key][name] = dst[key].get(name, 0) + count - else: - dst[key] += src[key] - - -def _tally_undocumented_tables(read_slice, bank_base, tmap, tally, stream_id=None): - """Decode the ``0x5a``/``0xd9`` tables and the ``0xbd`` cue list on one stream into a running tally. - - A stream counts as invalid when one of the layout invariants measured over the whole ``audio.rpf`` - population fails, so the tally doubles as a package-wide validator. The region cues of a valid - ``0xbd`` tag are matched into start/end pairs (`marker_regions`); `stream_id` only labels the - exceptions listed there. - """ - grid = None - if TAG_GRID20 in tmap: - go, gs = tmap[TAG_GRID20][0] - if 0 < gs <= MAX_GRID20_BYTES: - grid = decode_grid20_table(read_slice(bank_base + go, gs)) - tally["grid20_streams"] += 1 - if grid is None or not ( - grid["size_ok"] - and grid["magic_ok"] - and grid["position_increasing"] - and grid["p_multiple_of_32"] - ): - tally["grid20_invalid"] += 1 - elif grid["entries"]: - tally["grid20_entries"] += grid["entries"] - if TAG_FORMAT in tmap and grid["position_last"] is not None: - fo, fs = tmap[TAG_FORMAT][0] - fb = read_slice(bank_base + fo, 4) if fs >= 4 else b"" - if len(fb) == 4 and grid["position_last"] >= _u32(fb, 0): - tally["grid20_position_past_samples"] += 1 - if TAG_INDEXRUN in tmap: - io, isz = tmap[TAG_INDEXRUN][0] - runs = None - if 0 < isz <= MAX_GRID20_BYTES: - runs = decode_index_runs( - read_slice(bank_base + io, isz), - grid["entries"] if grid and grid["size_ok"] else None, - ) - tally["indexrun_streams"] += 1 - if runs is None or not ( - runs["size_ok"] - and runs["group_count_matches"] - and runs["marker_ok"] - and runs["hash_single"] - and runs["indices_ascending"] - ): - tally["indexrun_invalid"] += 1 - else: - tally["indexrun_groups"] += runs["groups"] - if runs["indices_within_grid"] is False: - tally["indexrun_index_overruns"] += 1 - if TAG_MARKER in tmap: - mo, ms = tmap[TAG_MARKER][0] - marks = blob = None - if 0 < ms <= MAX_MARKER_BYTES: - blob = read_slice(bank_base + mo, ms) - marks = decode_marker_records(blob) - tally["marker_streams"] += 1 - if marks is None or not (marks["size_ok"] and marks["offsets_ascending"]): - tally["marker_invalid"] += 1 - else: - tally["marker_records"] += marks["records"] - key = f"0x{marks['first_name']:08x}" - firsts = tally["marker_first_names"] - firsts[key] = firsts.get(key, 0) + 1 - records = marker_records(blob) - if any(value in _REGION_VALUES for _name, value, _offset, _extra in records): - samples = None - if TAG_FORMAT in tmap: - fo, fs = tmap[TAG_FORMAT][0] - fb = read_slice(bank_base + fo, 4) if fs >= 4 else b"" - samples = _u32(fb, 0) if len(fb) == 4 else None - _tally_marker_regions(tally["marker_regions"], records, bank_offset=bank_base, - stream_id=stream_id, sample_count=samples) - - -def decode_awc_bank(data, bank_offset=0, *, deep=True, curves=False): - """Decode all `0x5c` (`RSC8` v8001) entries in one in-memory AWC (`ADAT`) bank.""" - bank = parse_adat_header_bytes(data, 0, len(data)) - if bank is None: - raise ValueError("not a valid little-endian ADAT (AWC) bank") - - def read_slice(off, n): - return data[off : off + n] - - records = [] - tag_counts = {} - non_rsc8_0x5c = 0 - tally = _new_grid_tally() - for sid, tags in bank["entries"]: - tmap = {} - for tt, toff, tsz in tags: - key = f"0x{tt:02x}" - tag_counts[key] = tag_counts.get(key, 0) + 1 - tmap.setdefault(tt, []).append((toff, tsz)) - _tally_undocumented_tables(read_slice, 0, tmap, tally, sid) - for tt, toff, tsz in tags: - if tt == TAG_RSC8_CLIP: - if tsz < 4 or tsz > MAX_RSC8_BYTES: - non_rsc8_0x5c += 1 - continue - blob = data[toff : toff + tsz] - if len(blob) < 4 or blob[:4] != RSC8_MAGIC: - non_rsc8_0x5c += 1 - continue - dec = decode_rsc8(blob, stream_id=sid, deep=deep, curves=curves) - comp = _decode_companion_tags(read_slice, 0, tmap) - records.append(_make_record(bank_offset, bank_offset + toff, sid, dec, comp)) - - return { - "bank_offset": bank_offset, - "bank_size": bank["end"] - bank["offset"], - "stream_count": bank["count"], - "tag_counts": tag_counts, - "non_rsc8_0x5c": non_rsc8_0x5c, - "records": records, - **tally, - } - - -def _new_summary(mode, source): - return { - "mode": mode, - "source": source, - "adat_banks": 0, - "adat_streams": 0, - "adat_bytes": 0, - "adat_banks_past_window": 0, - "adat_bytes_past_window": 0, - "window_starts_in_bank": None, - "adat_tag_counts": {}, - "invalid_files": 0, - "rsc8_decoded": 0, - "rsc8_in_adat": 0, - "rsc8_standalone": 0, - "rsc8_valid": 0, - "rsc8_invalid": 0, - "failed_checks": {}, - "rsc8_non_rsc8_0x5c": 0, - "rsc8_outside_adat": 0, - "rsc8_versions": {}, - "rsc8_other_versions": {}, - "rsc8_total_bytes": 0, - "rsc8_body_bytes": 0, - "stream_id_matches": 0, - "stream_id_mismatches": 0, - "dict_name_storage": {}, - "anim_block_counts": {}, - "track_counts": {}, - "track_types": {}, - "prop_counts": {}, - "audio_codecs": {}, - "same_stream_audio_yes": 0, - "same_stream_audio_no": 0, - "min_frames": None, - "max_frames": None, - "min_tag_size": None, - "max_tag_size": None, - "elapsed_seconds": 0.0, - **_new_grid_tally(), - "curve_clips": 0, - "curve_clips_decoded": 0, - "curve_errors": {}, - "curve_frames_mismatch": 0, - "curve_quantize_bits_mismatch": 0, - "curve_channels": {}, - "curve_components": {}, - "curve_delta2_boundaries": 0, - "curve_delta2_boundaries_closed": 0, - } - - -def _finish_summary(summary, t0): - """Close a scan's summary: the running region tally becomes its report, and the clock stops.""" - summary["marker_regions"] = marker_region_report(summary["marker_regions"]) - summary["elapsed_seconds"] = round(time.time() - t0, 3) - - -def _accumulate_record(summary, rec, *, in_adat=True, has_audio=None): - summary["rsc8_decoded"] += 1 - if in_adat: - summary["rsc8_in_adat"] += 1 - else: - summary["rsc8_standalone"] += 1 - if rec["valid"]: - summary["rsc8_valid"] += 1 - else: - summary["rsc8_invalid"] += 1 - for ck_name, ck_ok in (rec.get("checks") or {}).items(): - if not ck_ok and ck_name != "stream_id_matches": - summary["failed_checks"][ck_name] = summary["failed_checks"].get(ck_name, 0) + 1 - ver = rec.get("version") - if ver is not None: - vk = f"0x{ver:08x}" - summary["rsc8_versions"][vk] = summary["rsc8_versions"].get(vk, 0) + 1 - sid_chk = (rec.get("checks") or {}).get("stream_id_matches") - if sid_chk is True: - summary["stream_id_matches"] += 1 - elif sid_chk is False: - summary["stream_id_mismatches"] += 1 - tsz = rec["tag_size"] or 0 - bsz = rec["body_size"] or 0 - summary["rsc8_total_bytes"] += tsz - summary["rsc8_body_bytes"] += bsz - summary["min_tag_size"] = tsz if summary["min_tag_size"] is None else min(summary["min_tag_size"], tsz) - summary["max_tag_size"] = tsz if summary["max_tag_size"] is None else max(summary["max_tag_size"], tsz) - - st = rec.get("dict_name_storage") or "unknown" - summary["dict_name_storage"][st] = summary["dict_name_storage"].get(st, 0) + 1 - - bc = rec.get("anim_block_count") - if bc is not None: - bk = str(bc) - summary["anim_block_counts"][bk] = summary["anim_block_counts"].get(bk, 0) + 1 - - fr = rec.get("frame_count") - if fr is not None: - summary["min_frames"] = fr if summary["min_frames"] is None else min(summary["min_frames"], fr) - summary["max_frames"] = fr if summary["max_frames"] is None else max(summary["max_frames"], fr) - - tc = rec.get("track_count") - if tc is not None: - k = str(tc) - summary["track_counts"][k] = summary["track_counts"].get(k, 0) + 1 - for tt_k, tt_v in (rec.get("track_types") or {}).items(): - ks = str(tt_k) - summary["track_types"][ks] = summary["track_types"].get(ks, 0) + tt_v - - pc = rec.get("prop_count") - if pc is not None: - k = str(pc) - summary["prop_counts"][k] = summary["prop_counts"].get(k, 0) + 1 - - if has_audio is True: - summary["same_stream_audio_yes"] += 1 - elif has_audio is False: - summary["same_stream_audio_no"] += 1 - - if rec.get("audio_codec") is not None: - ck = f"codec={rec['audio_codec']},ch={rec['audio_channels']},sr={rec['audio_sample_rate']}" - summary["audio_codecs"][ck] = summary["audio_codecs"].get(ck, 0) + 1 - - cv = rec.get("curves") - if cv is not None: - summary["curve_clips"] += 1 - if not cv["decoded"]: - summary["curve_errors"][cv["error"]] = summary["curve_errors"].get(cv["error"], 0) + 1 - else: - summary["curve_clips_decoded"] += 1 - summary["curve_frames_mismatch"] += not cv["frames_match"] - summary["curve_quantize_bits_mismatch"] += not cv["quantize_bits_match"] - summary["curve_delta2_boundaries"] += cv["delta2_boundaries"] - summary["curve_delta2_boundaries_closed"] += cv["delta2_boundaries_closed"] - for key in ("channels", "components"): - into = summary["curve_" + key] - for name, n in cv[key].items(): - into[name] = into.get(name, 0) + n - - -def _bank_covering(fh, start, file_size): - """The `ADAT` bank that starts before `start` and runs past it, or `None`. - - Looks back from `start` (at most `MAX_AWC_FILE_BYTES`) for the nearest header that parses as a bank; banks - do not overlap, so only that one can cover `start`. - """ - floor = max(0, start - MAX_AWC_FILE_BYTES) - hi = start - while hi > floor: - lo = max(floor, hi - SCAN_CHUNK_BYTES) - fh.seek(lo) - buf = fh.read(hi - lo + len(ADAT_MAGIC) - 1) # a magic that starts just before hi; none starts at hi - idx = buf.rfind(ADAT_MAGIC) - while idx >= 0: - bank = parse_adat_at_file(fh, lo + idx, file_size) - if bank is not None: - return bank if bank["end"] > start else None - idx = buf.rfind(ADAT_MAGIC, 0, idx + len(ADAT_MAGIC) - 1) - hi = lo - return None - - -def scan_rpf(path, *, start=0, limit=None, max_banks=None, deep=True, collect_records=True, progress=None, - curves=False): - """Scan an RPF9 archive sequentially for `ADAT` banks and `RSC8` v8001 resources. - - With a window (`start`/`limit`), `adat_bytes` counts the window's bytes that belong to a bank, so it never - exceeds `span` and adjacent windows add up to the whole archive. A bank that starts inside the window is - decoded whole and counted in `adat_banks`; its bytes past the window are `adat_bytes_past_window`. A bank that - starts before the window and covers `start` (its offset is `window_starts_in_bank`) is not decoded or counted - as a bank, and the `RSC8` headers inside it are not reported as outside `ADAT`. - """ - t0 = time.time() - sz = os.path.getsize(path) - if start < 0 or start > sz: - raise ValueError("start offset is outside the archive") - scan_end = min(sz, start + limit) if limit is not None else sz - - summary = _new_summary("rpf9", path) - summary["span"] = scan_end - start - records = [] - adat_ranges = [] - - with open(path, "rb") as f, open(path, "rb") as f2: - def read_slice(off, n): - f2.seek(off) - return f2.read(n) - - if start > 0: - earlier = _bank_covering(f2, start, sz) - if earlier is not None: - summary["window_starts_in_bank"] = earlier["offset"] - summary["adat_bytes"] += min(earlier["end"], scan_end) - start - adat_ranges.append((earlier["offset"], earlier["end"])) - - pos = start - next_prog = start + PROGRESS_BYTES - while pos < scan_end: - f.seek(pos) - buf = f.read(min(SCAN_CHUNK_BYTES + 16, scan_end - pos)) - if not buf: - break - chunk_lim = min(len(buf), SCAN_CHUNK_BYTES) - - # 1. Discover valid ADAT banks in [pos, pos + chunk_lim) - cur = 0 - while cur < chunk_lim: - if max_banks is not None and summary["adat_banks"] >= max_banks: - break - idx = buf.find(ADAT_MAGIC, cur, chunk_lim + 4) - if idx < 0 or idx >= chunk_lim: - break - aoff = pos + idx - if adat_ranges and aoff < adat_ranges[-1][1]: - cur = min(chunk_lim, adat_ranges[-1][1] - pos) - continue - bank = parse_adat_at_file(f2, aoff, sz) - if bank is None: - cur = idx + 4 - continue - summary["adat_banks"] += 1 - summary["adat_streams"] += bank["count"] - summary["adat_bytes"] += min(bank["end"], scan_end) - bank["offset"] - if bank["end"] > scan_end: - summary["adat_banks_past_window"] += 1 - summary["adat_bytes_past_window"] += bank["end"] - scan_end - adat_ranges.append((bank["offset"], bank["end"])) - - bank_size = bank["end"] - bank["offset"] - has_5c = any(tt == TAG_RSC8_CLIP for _, tags in bank["entries"] for tt, _, _ in tags) - bank_bytes = None - if has_5c: - if bank["end"] <= pos + len(buf): - bank_bytes = memoryview(buf)[idx : bank["end"] - pos] - elif bank_size <= 64 * 1024 * 1024: - raw_bank = read_slice(aoff, bank_size) - if len(raw_bank) >= bank_size: - bank_bytes = memoryview(raw_bank) - - def bank_read_slice(off, n): - if bank_bytes is not None: - rel = off - aoff - return bytes(bank_bytes[rel : rel + n]) - return read_slice(off, n) - - for sid, tags in bank["entries"]: - tmap = {} - for tt, toff, tsz in tags: - tk = f"0x{tt:02x}" - summary["adat_tag_counts"][tk] = summary["adat_tag_counts"].get(tk, 0) + 1 - tmap.setdefault(tt, []).append((toff, tsz)) - _tally_undocumented_tables(bank_read_slice, aoff, tmap, summary, sid) - if not has_5c: - continue - for tt, toff, tsz in tags: - if tt == TAG_RSC8_CLIP: - if tsz < 4 or tsz > MAX_RSC8_BYTES: - summary["rsc8_non_rsc8_0x5c"] += 1 - continue - head4 = bank_read_slice(aoff + toff, 4) - if head4 != RSC8_MAGIC: - summary["rsc8_non_rsc8_0x5c"] += 1 - continue - blob = bank_read_slice(aoff + toff, tsz) - dec = decode_rsc8(blob, stream_id=sid, deep=deep, curves=curves) - comp = _decode_companion_tags(bank_read_slice, aoff, tmap) - rec = _make_record(aoff, aoff + toff, sid, dec, comp) - _accumulate_record(summary, rec, in_adat=True, has_audio=comp["has_audio_data"]) - if collect_records: - records.append(rec) - - cur = (bank["end"] - pos) if (bank["end"] - pos < chunk_lim) else chunk_lim - - # 2. Check for any raw RSC8 headers outside discovered ADAT banks - if max_banks is None: - cur = 0 - while cur < chunk_lim: - idx = buf.find(RSC8_MAGIC, cur, chunk_lim + 4) - if idx < 0 or idx >= chunk_lim: - break - if idx + 8 <= len(buf): - ver = _u32(buf, idx + 4) - if ver in RSC8_VERSIONS: - roff = pos + idx - lo, hi = 0, len(adat_ranges) - 1 - inside = False - while lo <= hi: - mid = (lo + hi) // 2 - rs, re = adat_ranges[mid] - if roff < rs: - hi = mid - 1 - elif roff >= re: - lo = mid + 1 - else: - inside = True - break - if not inside: - summary["rsc8_outside_adat"] += 1 - elif ver < 100_000: - vk = str(ver) - summary["rsc8_other_versions"][vk] = summary["rsc8_other_versions"].get(vk, 0) + 1 - cur = idx + 4 - - pos += SCAN_CHUNK_BYTES - if max_banks is not None and summary["adat_banks"] >= max_banks: - break - if progress and pos >= next_prog: - progress(pos, scan_end, summary) - next_prog += PROGRESS_BYTES - - _finish_summary(summary, t0) - return records, summary - - -def scan_dir(path, *, max_banks=None, deep=True, collect_records=True, curves=False): - """Scan a directory of `.awc` banks and/or standalone `.rsc8` files.""" - t0 = time.time() - summary = _new_summary("directory", path) - records = [] - files = [] - for root, _, names in os.walk(path): - for name in sorted(names): - low = name.lower() - if low.endswith((".awc", ".rsc8")): - fp = os.path.join(root, name) - if os.path.islink(fp) or not os.path.isfile(fp): - continue - files.append(fp) - files.sort() - - for fp in files: - if max_banks is not None and summary["adat_banks"] >= max_banks: - break - try: - fsize = os.path.getsize(fp) - with open(fp, "rb") as f: - head4 = f.read(4) - if head4 == ADAT_MAGIC: - if fsize > MAX_AWC_FILE_BYTES: - raise ValueError(f"AWC bank exceeds {MAX_AWC_FILE_BYTES} bytes") - with open(fp, "rb") as f: - raw = f.read() - bank_res = decode_awc_bank(raw, 0, deep=deep, curves=curves) - summary["adat_banks"] += 1 - summary["adat_streams"] += bank_res["stream_count"] - summary["adat_bytes"] += bank_res["bank_size"] - summary["rsc8_non_rsc8_0x5c"] += bank_res["non_rsc8_0x5c"] - for tk, tv in bank_res["tag_counts"].items(): - summary["adat_tag_counts"][tk] = summary["adat_tag_counts"].get(tk, 0) + tv - _merge_grid_tally(summary, bank_res) - for rec in bank_res["records"]: - _accumulate_record(summary, rec, in_adat=True, has_audio=rec.get("has_audio_data")) - if collect_records: - records.append(rec) - elif head4 == RSC8_MAGIC: - if fsize > MAX_RSC8_BYTES: - raise ValueError(f"RSC8 file exceeds {MAX_RSC8_BYTES} bytes") - with open(fp, "rb") as f: - raw = f.read() - dec = decode_rsc8(raw, deep=deep, curves=curves) - rec = _make_record(0, 0, None, dec, None) - _accumulate_record(summary, rec, in_adat=False, has_audio=None) - if collect_records: - records.append(rec) - else: - raise ValueError("not a valid little-endian ADAT (AWC) bank or RSC8 resource") - except (OSError, ValueError) as e: - summary["invalid_files"] += 1 - print(f"{fp}: {e}", file=sys.stderr) - - _finish_summary(summary, t0) - return records, summary - - -def scan_single_file(path, *, start=0, limit=None, max_banks=None, deep=True, collect_records=True, progress=None, - curves=False): - """Inspect a single `.rsc8`, `.awc`, or `.rpf` file.""" - fsize = os.path.getsize(path) - with open(path, "rb") as f: - head = f.read(4) - if head == RSC8_MAGIC and start == 0 and limit is None: - if fsize > MAX_RSC8_BYTES: - raise ValueError(f"RSC8 file exceeds {MAX_RSC8_BYTES} bytes") - t0 = time.time() - with open(path, "rb") as f: - raw = f.read() - dec = decode_rsc8(raw, deep=deep, curves=curves) - rec = _make_record(0, 0, None, dec, None) - summary = _new_summary("rsc8", path) - _accumulate_record(summary, rec, in_adat=False, has_audio=None) - _finish_summary(summary, t0) - return ([rec] if collect_records else []), summary - if head == ADAT_MAGIC and start == 0 and limit is None and fsize <= MAX_AWC_FILE_BYTES: - t0 = time.time() - with open(path, "rb") as f: - raw = f.read() - bank_res = decode_awc_bank(raw, 0, deep=deep, curves=curves) - summary = _new_summary("awc", path) - summary["adat_banks"] = 1 - summary["adat_streams"] = bank_res["stream_count"] - _merge_grid_tally(summary, bank_res) - summary["adat_bytes"] = bank_res["bank_size"] - summary["adat_tag_counts"] = bank_res["tag_counts"] - summary["rsc8_non_rsc8_0x5c"] = bank_res["non_rsc8_0x5c"] - for rec in bank_res["records"]: - _accumulate_record(summary, rec, in_adat=True, has_audio=rec.get("has_audio_data")) - _finish_summary(summary, t0) - return (bank_res["records"] if collect_records else []), summary - return scan_rpf( - path, - start=start, - limit=limit, - max_banks=max_banks, - deep=deep, - collect_records=collect_records, - progress=progress, - curves=curves, - ) - - -def _atomic_write_text(path, write_fn): - parent = os.path.dirname(os.path.abspath(path)) - if parent: - os.makedirs(parent, exist_ok=True) - tmp = None - try: - with tempfile.NamedTemporaryFile( - mode="w", - encoding="utf-8", - newline="", - dir=parent or ".", - prefix=".rsc8_audio.", - suffix=".part", - delete=False, - ) as f: - tmp = f.name - write_fn(f) - os.chmod(tmp, published_mode(path)) # NamedTemporaryFile creates 0600 - os.replace(tmp, path) - except BaseException: - if tmp and os.path.isfile(tmp): - try: - os.remove(tmp) - except OSError: - pass - raise - - -def write_report(path, records, summary): - """Atomically write JSON or CSV report (no game strings or raw payloads).""" - ext = os.path.splitext(path)[1].lower() - if ext == ".csv": - def _write_csv(f): - w = csv.writer(f, lineterminator="\n") - w.writerow(CSV_COLUMNS) - for r in records: - row = [] - for col in CSV_COLUMNS: - v = r.get(col) - if col in ("bank_offset", "tag_offset") and v is not None: - row.append(f"0x{v:x}") - elif col in ("stream_id", "stream_hash") and v is not None: - row.append(f"0x{v:08x}") - elif v is None: - row.append("") - else: - row.append(v) - w.writerow(row) - _atomic_write_text(path, _write_csv) - else: - def _write_json(f): - json.dump({"summary": summary, "records": records}, f, indent=1) - _atomic_write_text(path, _write_json) - - -def _parse_nonneg_int(text): - try: - val = int(text, 0) - except ValueError: - raise argparse.ArgumentTypeError(f"invalid int value: {text!r}") from None - if val < 0: - raise argparse.ArgumentTypeError("must be 0 or more") - return val - - -def _parse_pos_int(text): - try: - val = int(text, 0) - except ValueError: - raise argparse.ArgumentTypeError(f"invalid int value: {text!r}") from None - if val < 1: - raise argparse.ArgumentTypeError("must be at least 1") - return val - - -def main(argv=None): - ap = argparse.ArgumentParser(description=__doc__.splitlines()[0]) - ap.add_argument("source", help="an .rpf archive, .awc bank, .rsc8 file, or directory of .awc/.rsc8 files") - ap.add_argument("out", nargs="?", help="optional output report path (.json or .csv)") - ap.add_argument("--start", type=_parse_nonneg_int, default=None, help="start byte offset (single archive only)") - ap.add_argument("--limit", type=_parse_pos_int, default=None, help="maximum bytes to scan (single archive only)") - ap.add_argument("--max-banks", type=_parse_pos_int, default=None, help="stop after N ADAT banks") - ap.add_argument("--no-deep", action="store_true", help="skip per-track and property-attribute walks") - ap.add_argument("--curves", action="store_true", - help="also decode every clip's keyframes and count the outcome (slower; counts only)") - ap.add_argument("--summary-only", action="store_true", help="do not store per-clip records in memory/JSON") - ap.add_argument("--quiet", action="store_true", help="suppress progress on stderr; stdout contains the JSON summary") - args = ap.parse_args(argv) - - if not os.path.exists(args.source): - print(f"{args.source}: path not found", file=sys.stderr) - return 2 - if args.out and os.path.isfile(args.source): - try: - overwrites_source = os.path.samefile(args.source, args.out) - except FileNotFoundError: - overwrites_source = False - except OSError as e: - ap.error(f"cannot compare source and output paths: {e}") - if overwrites_source: - ap.error("output must not overwrite the source file") - collect = (not args.summary_only) and (args.out is not None) - if os.path.isdir(args.source): - if args.start is not None or args.limit is not None: - ap.error("--start and --limit apply to a single archive, not a directory") - try: - records, summary = scan_dir( - args.source, - max_banks=args.max_banks, - deep=not args.no_deep, - collect_records=collect, - curves=args.curves, - ) - except (OSError, ValueError) as e: - print(f"{args.source}: {e}", file=sys.stderr) - return 2 - else: - def progress(pos, end, s): - if not args.quiet: - print( - f"[{min(pos, end) / max(1, end):6.1%}] banks={s['adat_banks']} " - f"rsc8={s['rsc8_in_adat']} valid={s['rsc8_valid']} outside={s['rsc8_outside_adat']}", - file=sys.stderr, flush=True, - ) - try: - records, summary = scan_single_file( - args.source, - start=args.start or 0, - limit=args.limit, - max_banks=args.max_banks, - deep=not args.no_deep, - collect_records=collect, - progress=progress, - curves=args.curves, - ) - except (OSError, ValueError) as e: - print(f"{args.source}: {e}", file=sys.stderr) - return 2 - - if args.out: - try: - write_report(args.out, records, summary) - except OSError as e: - print(f"{args.out}: {e}", file=sys.stderr) - return 2 - - print(json.dumps(summary, indent=1)) - return 0 - - -if __name__ == "__main__": - try: # a redirected stdout is strict ANSI code page under -I; write '?' for what it cannot encode - sys.stdout.reconfigure(errors="replace") - except (AttributeError, ValueError, OSError): - pass - sys.exit(main()) diff --git a/tools/rtti_scan.py b/tools/rtti_scan.py deleted file mode 100644 index 9082b2f6d..000000000 --- a/tools/rtti_scan.py +++ /dev/null @@ -1,550 +0,0 @@ -"""Recover C++ class names, hierarchies and vtables from an x64 MSVC PE via RTTI. - -x64 RTTI uses image-relative (RVA) fields: - TypeDescriptor { u64 pVFTable; u64 spare; char name[] = ".?AVClass@ns@@" } - CompleteObjectLocator { u32 signature(=1); u32 offset; u32 cdOffset; u32 rvaTypeDescriptor; - u32 rvaClassHierarchy; u32 rvaSelf } - ClassHierarchyDescriptor { u32 signature; u32 attributes; u32 numBaseClasses; u32 rvaBaseClassArray } - BaseClassDescriptor { u32 rvaTypeDescriptor; u32 numContainedBases; i32 mdisp, pdisp, vdisp; u32 attrs; - u32 rvaClassHierarchy } -A vtable is preceded (at -8) by a pointer to its CompleteObjectLocator. - -Usage: - python -I rtti_scan.py [--out file.json] -Output: classes (demangled-ish name, type descriptor RVA, base classes) and vtables (RVA, class, offset in the -complete object, number of slots that point into executable sections). -""" -import argparse -import json -import os -import re -import struct -import sys -import tempfile - -sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) -from file_mode import published_mode # noqa: E402 - - - -IMAGE_SCN_MEM_EXECUTE = 0x20000000 -PE32PLUS_MAGIC = 0x020B -MAX_PE_IMAGE_SIZE = 0x80000000 # 2 GiB (PE32+ spec maximum) - - -def load_pe64_image(data: bytes) -> tuple[int, bytes, list[dict]]: - """Parse a 64-bit PE32+ image using only the Python standard library. - - Returns (image_base, memory_mapped_image, sections) where each section dict contains - 'name', 'virtual_address', 'virtual_size', 'raw_ptr', 'raw_size', and 'characteristics'. - """ - if len(data) < 0x40 or data[:2] != b"MZ": - raise ValueError("not a PE image: missing MZ header") - (e_lfanew,) = struct.unpack_from(" len(data) or data[e_lfanew : e_lfanew + 4] != b"PE\x00\x00": - raise ValueError("not a PE image: missing PE signature") - - _machine, num_sections, _ts, _sym, _nsym, opt_size, _chars = struct.unpack_from( - " len(data): - raise ValueError("truncated PE optional header") - (magic,) = struct.unpack_from(" len(data): - raise ValueError("truncated PE section table") - - sections: list[dict] = [] - mapped_size = size_of_image - for i in range(num_sections): - sec_off = sec_table_off + i * 40 - raw_name, vsize, vaddr, rsize, rptr, _rel, _ln, _nrel, _nln, chars = struct.unpack_from( - "<8sIIIIIIHHI", data, sec_off - ) - span = vsize if vsize > 0 else rsize - end = vaddr + max(vsize, rsize) - if end > mapped_size: - mapped_size = end - sections.append({ - "name": raw_name.split(b"\x00", 1)[0].decode("latin-1"), - "virtual_address": vaddr, - "virtual_size": span, - "raw_ptr": rptr, - "raw_size": rsize, - "characteristics": chars, - }) - - if mapped_size <= 0 or mapped_size > MAX_PE_IMAGE_SIZE: - raise ValueError(f"invalid PE mapped image size: {mapped_size}") - - img = bytearray(mapped_size) - hdr_copy = min(size_of_headers, len(data), mapped_size) - if hdr_copy > 0: - img[0:hdr_copy] = data[0:hdr_copy] - - for sec in sections: - rptr = sec["raw_ptr"] - rsize = sec["raw_size"] - vaddr = sec["virtual_address"] - if rsize <= 0 or rptr >= len(data) or vaddr >= mapped_size: - continue - copy_len = min(rsize, len(data) - rptr, mapped_size - vaddr) - if copy_len > 0: - img[vaddr : vaddr + copy_len] = data[rptr : rptr + copy_len] - - return image_base, bytes(img), sections - - -_CV = {"A": (), "B": ("const",), "C": ("volatile",), "D": ("const", "volatile")} -_BUILTIN = {"X": "void", "C": "signed char", "D": "char", "E": "unsigned char", "F": "short", "G": "unsigned short", - "H": "int", "I": "unsigned int", "J": "long", "K": "unsigned long", "M": "float", "N": "double", - "O": "long double", "_D": "__int8", "_E": "unsigned __int8", "_F": "__int16", "_G": "unsigned __int16", - "_H": "__int32", "_I": "unsigned __int32", "_J": "__int64", "_K": "unsigned __int64", "_L": "__int128", - "_M": "unsigned __int128", "_N": "bool", "_Q": "char8_t", "_S": "char16_t", "_U": "char32_t", - "_W": "wchar_t"} -_OPERATOR = {"2": " new", "3": " delete", "4": "=", "5": ">>", "6": "<<", "7": "!", "8": "==", "9": "!=", "A": "[]", - "B": "", "C": "->", "D": "*", "E": "++", "F": "--", "G": "-", "H": "+", "I": "&", "J": "->*", "K": "/", - "L": "%", "M": "<", "N": "<=", "O": ">", "P": ">=", "Q": ",", "R": "()", "S": "~", "T": "^", "U": "|", - "V": "&&", "W": "||", "X": "*=", "Y": "+=", "Z": "-=", "_0": "/=", "_1": "%=", "_2": ">>=", - "_3": "<<=", "_4": "&=", "_5": "|=", "_6": "^=", "_U": " new[]", "_V": " delete[]"} -_POINTER = {"P": " *", "Q": " * const", "R": " * volatile", "S": " * const volatile", "A": " &", "B": " & volatile"} -_QUALIFIERS = re.compile(r"(?: const| volatile)*$") -_SLOT = "\0" # in a function or array type: where a further `*`, `&` or qualifier goes, `void (*|)(int)` -_LOCAL_SCOPE = re.compile(r"\?(?:\d|[B-P][A-P]*@)\?") -# How a type descriptor's name ends: '@@'; a local scope's function ('@?...Z@', '_E@' when noexcept); a back-reference. -_NAME_END = re.compile(rb"(?:@@|@\?[\x21-\x7e]*(?:Z|_E)@|@\d+@)\x00$") - - -class _TypeName: - """A reader for the part of MSVC's name mangling that a class name can contain: scopes, templates and their - arguments, back-references, anonymous namespaces and names local to a function. A form it does not know - raises ValueError (or runs off the end: IndexError); it never guesses.""" - - def __init__(self, text): - self.s, self.i = text, 0 - self.names, self.params = [], [] # the back-reference tables: name pieces, function parameter types - - def peek(self): - return self.s[self.i:self.i + 1] - - def next(self): - c = self.s[self.i] - self.i += 1 - return c - - def eat(self, text): - if self.s.startswith(text, self.i): - self.i += len(text) - return True - return False - - def number(self): - negative = self.eat("?") - c = self.next() - if c.isdigit(): - value = int(c) + 1 - else: - value = 0 - while c != "@": - if not "A" <= c <= "P": - raise ValueError("bad number") - value = value * 16 + ord(c) - ord("A") - c = self.next() - return -value if negative else value - - def memorize(self, name): - if name not in self.names and len(self.names) < 10: - self.names.append(name) - - def simple(self): - end = self.s.index("@", self.i) - name = self.s[self.i:end] - if not name or name[0] in "?$" or name[0].isdigit(): - raise ValueError("bad name") - self.i = end + 1 - self.memorize(name) - return name - - def piece(self): - """One piece of a scope chain.""" - c = self.peek() - if c.isdigit(): - self.i += 1 - return self.names[int(c)] - if self.s.startswith("?$", self.i): - name = self.template() - self.memorize(name) - return name - if self.eat("?A"): - self.i = self.s.index("@", self.i) + 1 - self.memorize("`anonymous namespace'") - return "`anonymous namespace'" - if _LOCAL_SCOPE.match(self.s, self.i): - self.i += 1 - ordinal = self.number() - self.i += 1 - return f"`{self.symbol()}'::`{ordinal}'" - return self.simple() - - def qualified(self): - pieces = [self.piece()] - while not self.eat("@"): - pieces.append(self.piece()) - return "::".join(reversed(pieces)) - - def template(self): - """`?$name@arguments@`. A template name has back-reference tables of its own.""" - self.i += 2 - outer = self.names, self.params - self.names, self.params = [], [] - name = self.operator() if self.peek() == "?" else self.simple() - if name == "operator": - raise ValueError("a conversion operator template is not read") - arguments = [] - while not self.eat("@"): - if self.eat("$$$V") or self.eat("$$V") or self.eat("$$Z") or self.eat("$S"): - continue # an empty pack, or the boundary between two packs - if self.eat("$M"): # a value of a deduced (`auto`) type: the type, the value - self.type() - if not self.eat("0"): - raise ValueError("unknown template argument") - arguments.append(str(self.number())) - elif self.eat("$0"): - arguments.append(str(self.number())) - elif self.eat("$$Y"): - arguments.append(self.qualified()) - else: - arguments.append(self.type().replace(_SLOT, "")) - self.names, self.params = outer - return f"{name}<{', '.join(arguments)}>" - - def operator(self): - self.i += 1 - code = self.next() - if code == "_": - code += self.next() - if code in ("0", "1"): - return code # constructor, destructor: named after the class - if code not in _OPERATOR: - raise ValueError("unknown special name") - return "operator" + _OPERATOR[code] - - def symbol(self): - """A whole decorated function name, as a local scope holds one. Returns its qualified name; the signature - is read, to find where it ends, and dropped.""" - if not self.eat("?"): - raise ValueError("not a symbol") - c = self.peek() - if c.isdigit(): - self.i += 1 - name = self.names[int(c)] - elif self.s.startswith("?$", self.i): - name = self.template() - elif c == "?": - name = self.operator() - else: - name = self.simple() - scope = [] - while not self.eat("@"): - scope.append(self.piece()) - if name[0] in "01": - if not scope: - raise ValueError("a constructor outside a class") - name = ("~" if name[0] == "1" else "") + scope[0] + name[1:] - kind = self.next() - if kind in "ABEFIJMNQRUV": # a non-static member: `this` qualifiers - while self.peek() in ("E", "F", "G", "H", "I"): - self.i += 1 - self.cv() - elif kind not in "CDKLSTYZ": - raise ValueError("not a plain function") - result = self.signature()[0] - if name == "operator": # a conversion: named after the type it returns - name += " " + result.replace(_SLOT, "") - return "::".join(scope[::-1] + [name]) - - def cv(self): - return _CV[self.next()] - - def sizes(self): - """An array's dimensions: how many, then each.""" - count = self.number() - sizes = [self.number() for _ in range(count)] - if count < 1 or min(sizes) < 0: - raise ValueError("bad array dimensions") - return "".join(f"[{n}]" for n in sizes) - - @staticmethod - def declare(text, declarator, keep=False): - """The type `text` with `declarator` (` *`, ` (*)(int)`, ` [4]`, ...) applied. It goes after a plain type, - and inside the brackets of a function or array type: a pointer to `void (*)(int)` is `void (**)(int)`. - `keep` leaves the slot after a `*` or `&`; a function or array declarator brings its own.""" - if _SLOT in text: - return text.replace(_SLOT, declarator.lstrip() + (_SLOT if keep else "")) - return text + declarator - - @staticmethod - def qualify(text, qualifiers): - """`text` with `const`/`volatile` after it. A const pointer is marked twice, by its own code and by the - qualifiers of whatever refers to it, so one that is already there is not repeated.""" - head, slot, tail = text.partition(_SLOT) - present = _QUALIFIERS.search(head).group(0).split() - return head + "".join(f" {q}" for q in qualifiers if q not in present) + slot + tail - - def signature(self): - """Calling convention, return type, parameters, exception specification: (return type, parameters, - ` noexcept` or nothing).""" - if not "A" <= self.next() <= "W": - raise ValueError("unknown calling convention") - result = "" if self.eat("@") else self.type() - parameters = [] - if self.eat("X"): - parameters.append("void") - else: - while not self.eat("@"): - if self.eat("Z"): - parameters.append("...") - break - if self.peek().isdigit(): - parameters.append(self.params[int(self.next())]) - continue - start = self.i - parameters.append(self.type().replace(_SLOT, "")) - if self.i - start > 1 and len(self.params) < 10: - self.params.append(parameters[-1]) - if self.eat("_E"): - return result, parameters, " noexcept" - if not self.eat("Z"): - raise ValueError("no exception specification") - return result, parameters, "" - - def function(self, declarator): - result, parameters, noexcept = self.signature() - return self.declare(result, f" {declarator}({', '.join(parameters)}){noexcept}") - - def indirect(self, suffix): - """What a pointer or reference refers to, with `suffix` (` *`, ` &`, ...) after it.""" - unaligned = () - while self.peek() in ("E", "F", "I"): # __ptr64, __unaligned, __restrict - if self.next() == "F": - unaligned = ("__unaligned",) - if self.eat("6"): - return self.function(f"({suffix.strip()}{_SLOT})") - if self.eat("$A"): # a C++/CX handle - suffix = suffix.replace("*", "^") - qualifiers = self.cv() - if self.eat("Y"): - sizes = self.sizes() - return self.declare(self.qualify(self.type(), qualifiers + unaligned), f" ({suffix.strip()}{_SLOT}){sizes}") - return self.declare(self.qualify(self.type(), qualifiers + unaligned), suffix, keep=True) - - def type(self): - if self.eat("$$Q"): - return self.indirect(" &&") - if self.eat("$$T"): - return "std::nullptr_t" - if self.eat("$$A6"): - return self.function("") - if self.eat("$$C") or self.eat("?"): # a qualified type passed by value - qualifiers = self.cv() - return self.qualify(self.type(), qualifiers) - if self.eat("$$BY"): # an array passed as a template argument - sizes = self.sizes() - return self.declare(self.type(), " " + sizes) - c = self.next() - if c == "_": - c += self.next() - if c in _BUILTIN: - return _BUILTIN[c] - if c in ("T", "U", "V"): - return self.qualified() - if c == "W": - if not "0" <= self.next() <= "7": - raise ValueError("bad enum") - return self.qualified() - if c in _POINTER: - return self.indirect(_POINTER[c]) - raise ValueError("unknown type") - - -def simple_name(mangled: str) -> str: - """'.?AVFoo@bar@@' -> 'bar::Foo', '.?AV?$Foo@H@bar@@' -> 'bar::Foo'. The `class`/`struct`/`enum` keywords, - calling conventions and the signature of a function that a local class sits in are left out. A name with a - form this does not read (a member pointer or an array as a template argument, say) is returned as it is.""" - m = re.match(r"\.\?A(?:[TUV]|W[0-7]?)", mangled) - if not m or not mangled.endswith("@"): - return mangled - reader = _TypeName(mangled[m.end():]) - try: - name = reader.qualified() - except (ValueError, IndexError, KeyError, RecursionError): - return mangled - return name.replace(_SLOT, "") if reader.i == len(reader.s) else mangled - - -def scan_pe64_rtti(data: bytes) -> dict: - """Recover x64 MSVC TypeDescriptors, class hierarchies, and vtables from raw PE32+ bytes.""" - base, img, sections = load_pe64_image(data) - exec_ranges = [ - (s["virtual_address"], min(s["virtual_address"] + s["virtual_size"], len(img))) - for s in sections - if s["characteristics"] & IMAGE_SCN_MEM_EXECUTE - ] - - def is_exec(rva): - return any(lo <= rva < hi for lo, hi in exec_ranges) - - def u32(rva): - return struct.unpack_from("= 0: - tds[rva] = m.group(0)[:-1].decode("latin-1") - - # 2. Complete object locators: signature 1 and rvaSelf == own RVA. - cols = {} - for m in re.finditer(rb"\x01\x00\x00\x00", img): - rva = m.start() - if rva % 4 or rva + 24 > len(img): - continue - sig, off, cd, rtd, rchd, rself = struct.unpack_from("<6I", img, rva) - if rself == rva and rtd in tds: - cols[rva] = {"offset": off, "td": rtd, "chd": rchd} - - # 3. Class hierarchies. - classes = {} - chd_ok = set() - for rva, col in cols.items(): - td = col["td"] - if td in chd_ok: - continue - chd = col["chd"] - valid_chd = False - attrs, bases = 0, [] - if chd > 0: - try: - sig, attrs, nbase, rarr = struct.unpack_from("<4I", img, chd) - if sig == 0 and rarr > 0: - for i in range(1, min(nbase, 256)): - bcd = u32(rarr + 4 * i) - btd = u32(bcd) - if btd in tds: - bases.append(simple_name(tds[btd])) - valid_chd = True - else: - attrs = 0 - except struct.error: - attrs, bases = 0, [] - if valid_chd or td not in classes: - classes[td] = {"name": simple_name(tds[td]), "mangled": tds[td], "td_rva": td, - "multiple": bool(attrs & 1), "virtual": bool(attrs & 2), "bases": bases} - if valid_chd: - chd_ok.add(td) - - # 4. Vtables: a qword equal to (image base + COL rva), followed by code pointers. - vtables = [] - col_vas = {base + rva: rva for rva in cols} - for sec in sections: - if sec["characteristics"] & IMAGE_SCN_MEM_EXECUTE: - continue - lo = sec["virtual_address"] - hi = min(lo + sec["virtual_size"], len(img)) - for p in range((lo + 7) & ~7, hi - 8, 8): - q = struct.unpack_from(" {path}") - for c in out["classes"][:5]: - print(" ", c["name"], "<-", ", ".join(c["bases"][:4])) - return 0 - - -if __name__ == "__main__": - try: # a redirected stdout is strict ANSI code page under -I; write '?' for what it cannot encode - sys.stdout.reconfigure(errors="replace") - except (AttributeError, ValueError, OSError): - pass - sys.exit(main()) diff --git a/tools/sad_diff.py b/tools/sad_diff.py deleted file mode 100644 index bf5bdf848..000000000 --- a/tools/sad_diff.py +++ /dev/null @@ -1,619 +0,0 @@ -r"""Differential fuzzer for the RDNA2 sum-of-absolute-differences family (standard library only). - -Covers seven opcodes, one family (the "Sum of absolute differences" and `v_qsad` rows of -docs/design.md's contract table): - - v_sad_u8 v_sad_hi_u8 v_sad_u16 v_sad_u32 v_msad_u8 32-bit results - v_qsad_pk_u16_u8 v_mqsad_pk_u16_u8 packed four-lane u16 results - -Seeded straight-line programs run through two independent oracles, and the four exported mrt0 -words are compared bit for bit (everything here is integer, so a mismatch is never a rounding -convention): - - * the reference below, written from the RDNA2 ISA pseudocode as recorded in docs/design.md - (hardware-verified there: the SAD row on gfx1035 via SHADER-137's int_hw_probe run, - v_qsad/v_mqsad bit-exact on an RTX 3060 in #623), and - * tools/rdna2spirv.py, executing the SPIR-V with tests/semantic/spirv_mini_interp.py. - -Program shape: seeds in v8..v15 and s4..s7, then the family ops, then `exp mrt0 v8, v9, v10, v11` -so every result is observed. Every op's destination is v8..v11 (quad destinations are pairs inside -that), so later ops can chain on earlier results. - -Source kinds, in every operand position the encoding allows: - VGPR v8..v15, SGPR s4..s7, a hex literal (32 bits), an inline constant (decimal, 0..64 or - -16..-1), and `null` (reads 0) for the 32-bit sources. The quad ops' S0 and S2 are 64-bit: VGPR - or SGPR pairs, a hex literal (zero high word) or an inline constant (sign-extended), the rule the - contract table records for 64-bit constant operands. - -Two modes run one after the other: - * a sweep over the whole source-kind space: every (S0, S1, S2) kind combination of every op, - 125 per plain op and 80 per quad op, 785 programs, with values drawn from byte/half edge words; - * random programs (--programs), which widen the value coverage over the same kind space. - -Not generated, on purpose: `clamp` (the contract rows say the translator rejects it; --self-test -pins that as an expected rejection) and op_sel / neg / abs (the ISA does not define them for these -opcodes). v_mqsad_u32_u8 is left out: open PRs #1926/#2163 are on that op. - -Usage: - python -I tools/sad_diff.py [--programs N] [--seed S] [--max-ops N] [--no-sweep] - python -I tools/sad_diff.py --ops v_sad_u8,v_msad_u8 - python -I tools/sad_diff.py --list-ops - python -I tools/sad_diff.py --self-test - -Exit code 0 when every program matches, 1 on a mismatch (the first one is printed with its -listing), 2 on a harness error. Skips are counted with reasons and never silent. -Nothing here reads game files. -""" -import argparse -import gc -import os -import random -import re -import struct -import sys -import tempfile -import warnings -from collections import Counter - -HERE = os.path.dirname(os.path.abspath(__file__)) -TOOLS_DIR = os.environ.get("LEONIDA_TOOLS_DIR") or HERE -sys.dont_write_bytecode = True -if TOOLS_DIR not in sys.path: - sys.path.insert(0, TOOLS_DIR) -SEM_DIR = os.path.join(os.path.dirname(HERE), "tests", "semantic") -if SEM_DIR not in sys.path: - sys.path.insert(0, SEM_DIR) - -import rdna2spirv # noqa: E402 -from spirv_mini_interp import UnsupportedConstruct, run_fragment # noqa: E402 - -M32 = 0xFFFFFFFF -M64 = (1 << 64) - 1 -STUB_DXBC = b"DXBC" + bytes(24) + struct.pack("= y else y - x - - -def _lanes(word, width): - return [(word >> off) & ((1 << width) - 1) for off in range(0, 32, width)] - - -def sad_u8(x, y, masked=False): - """Sum over the four bytes of |x.b - y.b|; the masked form skips a byte where y's byte is 0.""" - return sum(_absdiff(p, q) for p, q in zip(_lanes(x, 8), _lanes(y, 8)) if not (masked and q == 0)) - - -def sad_u16(x, y): - return sum(_absdiff(p, q) for p, q in zip(_lanes(x, 16), _lanes(y, 16))) - - -def quad_sad(s0_lo, s0_hi, s1, acc_lo, acc_hi, masked=False): - """v_qsad_pk_u16_u8 / v_mqsad_pk_u16_u8 as one 64-bit result: for k = 0..3, - D.u16[k] = (S2.u16[k] + byte SAD of the 32-bit window S0[8k+31 : 8k] against S1) & 0xFFFF.""" - accs = _lanes(acc_lo, 16) + _lanes(acc_hi, 16) - out = 0 - for k in range(4): - if k == 0: - win = s0_lo & M32 - else: - win = ((s0_hi << (32 - 8 * k)) | (s0_lo >> (8 * k))) & M32 - total = sad_u8(win, s1 & M32, masked=masked) - out |= ((accs[k] + total) & 0xFFFF) << (16 * k) - return out & M64 - - -SINGLE_OPS = { - "v_sad_u8": lambda x, y, z: (sad_u8(x, y) + z) & M32, - "v_sad_hi_u8": lambda x, y, z: ((sad_u8(x, y) << 16) + z) & M32, - "v_sad_u16": lambda x, y, z: (sad_u16(x, y) + z) & M32, - "v_sad_u32": lambda x, y, z: (_absdiff(x & M32, y & M32) + z) & M32, - "v_msad_u8": lambda x, y, z: (sad_u8(x, y, masked=True) + z) & M32, -} - -_PAIR = re.compile(r"([sv])\[(\d+):(\d+)\]$") -_REG = re.compile(r"([sv])(\d+)$") - - -class HarnessError(Exception): - pass - - -def _single_word(tok, vgpr, sgpr): - """The 32-bit word a single-source token reads: a register, a hex literal, an inline constant - (two's complement at 32 bits) or `null`.""" - tok = tok.strip() - m = _REG.fullmatch(tok) - if m: - regs = vgpr if m.group(1) == "v" else sgpr - return regs.get(int(m.group(2)), 0) - if tok == "null": - return 0 - if tok.lower().startswith("0x"): - return int(tok, 16) & M32 - if tok.lstrip("+-").isdigit(): - return int(tok, 10) & M32 - raise HarnessError(f"unknown single source {tok!r}") - - -def _pair_words(tok, vgpr, sgpr): - """The two dwords a 64-bit source token reads: a register pair, a hex literal (zero high word) - or an inline constant (sign-extended).""" - tok = tok.strip() - m = _PAIR.fullmatch(tok) - if m: - regs = vgpr if m.group(1) == "v" else sgpr - lo, hi = int(m.group(2)), int(m.group(3)) - if hi != lo + 1: - raise HarnessError(f"not an even pair {tok!r}") - return regs.get(lo, 0), regs.get(hi, 0) - if tok.lower().startswith("0x"): - return int(tok, 16) & M32, 0 - if tok.lstrip("+-").isdigit(): - v = int(tok, 10) & M64 - return v & M32, (v >> 32) & M32 - raise HarnessError(f"unknown pair source {tok!r}") - - -def _dst_index(dst): - m = _REG.fullmatch(dst.strip()) - if not m or m.group(1) != "v": - raise HarnessError(f"unknown destination {dst!r}") - return int(m.group(2)) - - -def step(line, vgpr, sgpr): - """Execute one generated listing line on the reference's registers.""" - head, *args = line.split(",") - parts = head.split() - if len(parts) != 2: - raise HarnessError(line) - op, dst = parts - args = [a.strip() for a in args] - if op == "v_mov_b32": - vgpr[_dst_index(dst)] = _single_word(args[0], vgpr, sgpr) - elif op == "s_mov_b32": - if not dst.startswith("s"): - raise HarnessError(line) - sgpr[int(dst[1:])] = _single_word(args[0], vgpr, sgpr) - elif op in SINGLE_OPS: - x, y, z = (_single_word(a, vgpr, sgpr) for a in args) - vgpr[_dst_index(dst)] = SINGLE_OPS[op](x, y, z) - elif op in QUAD_OPS: - m = _PAIR.fullmatch(dst.strip()) - if not m or m.group(1) != "v" or int(m.group(3)) != int(m.group(2)) + 1: - raise HarnessError(f"quad destination {dst!r}") - d = int(m.group(2)) - (x_lo, x_hi), y, (c_lo, c_hi) = (_pair_words(args[0], vgpr, sgpr), - _single_word(args[1], vgpr, sgpr), - _pair_words(args[2], vgpr, sgpr)) - out = quad_sad(x_lo, x_hi, y, c_lo, c_hi, masked=(op == "v_mqsad_pk_u16_u8")) - vgpr[d] = out & M32 - vgpr[d + 1] = (out >> 32) & M32 - else: - raise HarnessError(line) - - -def reference(lines): - """The four exported mrt0 words the ISA pseudocode gives for a program (seeds and ops; the exp - and s_endpgm lines are ignored).""" - vgpr, sgpr = {}, {} - for line in lines: - first = line.split()[0] - if first in ("exp", "s_endpgm"): - continue - step(line, vgpr, sgpr) - return [vgpr.get(r, 0) for r in EXPORT_REGS] - - -# ---- program generation ---- - -def _seed_word(rng): - return rng.choice(EDGE) if rng.random() < 0.6 else rng.getrandbits(32) - - -def _single_source(rng, kind): - if kind == "vgpr": - return f"v{rng.randrange(8, 16)}" - if kind == "sgpr": - return f"s{rng.randrange(4, 8)}" - if kind == "lit": - return f"0x{_seed_word(rng):08x}" - if kind == "inline": - return str(rng.choice(INLINE)) - return "null" - - -def _pair_source(rng, kind): - if kind == "vgpr": - a = rng.randrange(8, 15) - return f"v[{a}:{a + 1}]" - if kind == "sgpr": - c = rng.randrange(4, 7) - return f"s[{c}:{c + 1}]" - if kind == "lit": - return f"0x{_seed_word(rng):08x}" - return str(rng.choice(INLINE)) - - -def program(rng, n_ops, ops=None): - """One straight-line program: (lines, ops_used). Ops drawn from `ops` (default: the family).""" - ops = list(ops) if ops else list(PLAIN_OPS) + list(QUAD_OPS) - lines = [] - used = Counter() - for r in range(8, 16): - lines.append(f"v_mov_b32 v{r}, 0x{_seed_word(rng):08x}") - for r in range(4, 8): - lines.append(f"s_mov_b32 s{r}, 0x{_seed_word(rng):08x}") - for _ in range(n_ops): - op = rng.choice(ops) - used[op] += 1 - if op in PLAIN_OPS: - dst = f"v{rng.choice(EXPORT_REGS)}" - srcs = ", ".join(_single_source(rng, rng.choice(PLAIN_KINDS)) for _ in range(3)) - else: - dpair = rng.choice((8, 9, 10)) - dst = f"v[{dpair}:{dpair + 1}]" - srcs = ", ".join((_pair_source(rng, rng.choice(QUAD64_KINDS)), - _single_source(rng, rng.choice(PLAIN_KINDS)), - _pair_source(rng, rng.choice(QUAD64_KINDS)))) - lines.append(f"{op} {dst}, {srcs}") - return lines, used - - -def kind_counts(lines): - """Per-opcode source-kind instances for the coverage report: ("v_sad_u8", "vgpr") -> n.""" - out = Counter() - for line in lines: - first = line.split()[0] - if first not in OP_FORMS: - continue - head, *args = line.split(",") - dst = head.split()[1].strip() - out[(first, "vpair" if ":" in dst else "vgpr")] += 1 - if first in PLAIN_OPS: - for a in args: - out[(first, _kind_of(a))] += 1 - else: - out[(first, _pair_kind_of(args[0]))] += 1 - out[(first, _kind_of(args[1]))] += 1 - out[(first, _pair_kind_of(args[2]))] += 1 - return out - - -def _kind_of(tok): - tok = tok.strip() - if tok == "null": - return "null" - if tok.lower().startswith("0x"): - return "lit" - if tok.lstrip("+-").isdigit(): - return "inline" - return "vgpr" if tok.startswith("v") else "sgpr" - - -def _pair_kind_of(tok): - tok = tok.strip() - if tok.lower().startswith("0x"): - return "lit" - if tok.lstrip("+-").isdigit(): - return "inline" - return "vpair" if tok.startswith("v") else "spair" - - -def sweep_ops(ops=None): - """Every op with every (S0, S1, S2) source-kind combination its encoding allows: 125 per plain - op, 80 per quad op. Returns a list of (label, kinds, value-rng seed).""" - ops = list(ops) if ops else list(PLAIN_OPS) + list(QUAD_OPS) - cases = [] - for op in ops: - kinds64 = QUAD64_KINDS if op in QUAD_OPS else PLAIN_KINDS - kinds32 = PLAIN_KINDS - if op in QUAD_OPS: - combos = ((k0, k1, k2) for k0 in kinds64 for k1 in kinds32 for k2 in kinds64) - else: - combos = ((k0, k1, k2) for k0 in kinds32 for k1 in kinds32 for k2 in kinds32) - for combo in combos: - cases.append((op, combo)) - return cases - - -def sweep_program(op, kinds, rng): - """One sweep program: seeds, then the op once, with the fixed kind combination.""" - lines = [f"v_mov_b32 v{r}, 0x{_seed_word(rng):08x}" for r in range(8, 16)] - lines += [f"s_mov_b32 s{r}, 0x{_seed_word(rng):08x}" for r in range(4, 8)] - if op in PLAIN_OPS: - srcs = ", ".join(_single_source(rng, k) for k in kinds) - lines.append(f"{op} v{rng.choice(EXPORT_REGS)}, {srcs}") - else: - dpair = rng.choice((8, 9, 10)) - srcs = ", ".join((_pair_source(rng, kinds[0]), _single_source(rng, kinds[1]), - _pair_source(rng, kinds[2]))) - lines.append(f"{op} v[{dpair}:{dpair + 1}], {srcs}") - return lines - - -# ---- the translator oracle ---- - -def write_listing(path, lines, name): - with open(path, "w", encoding="utf-8", newline="\n") as f: - f.write(f"; {name} code 0x0..0x1000\n") - for line in lines: - f.write("\t" + line + "\n") - f.write("\t" + EXPORT + "\n") - f.write("\ts_endpgm\n") - - -def translate_listing(lines, name, tmpdir): - """The four mrt0 words the translator path produces. Raises rdna2spirv.Unsupported (and mini - interp's UnsupportedConstruct) for anything outside the oracles' model.""" - dis = os.path.join(tmpdir, "disasm") - os.makedirs(dis, exist_ok=True) - path = os.path.join(dis, name + ".s") - write_listing(path, lines, name) - with open(os.path.join(tmpdir, name + ".dxbc"), "wb") as f: - f.write(STUB_DXBC) - with warnings.catch_warnings(): - warnings.simplefilter("ignore", ResourceWarning) - spvasm = rdna2spirv.translate(path) - gc.collect() - out = run_fragment(spvasm) - if list(out) != ["%out_mrt0"]: - raise HarnessError(f"outputs {sorted(out)}, want %out_mrt0") - return [w & M32 for w in out["%out_mrt0"]] - - -def check(lines, name="ps_sad_case"): - """None when both oracles agree, else the first differing word with both values.""" - with tempfile.TemporaryDirectory(prefix="sad-diff-") as tmp: - want = reference(lines) - got = translate_listing(lines, name, tmp) - for i, (w, g) in enumerate(zip(want, got)): - if w != (g & M32): - return f"word {i} (v{EXPORT_REGS[i]}): expected 0x{w:08x}, actual 0x{g:08x}" - return None - - -def run_one(lines, name, tmpdir): - """(status, detail) with status in {"match", "mismatch", "skip"}.""" - try: - want = reference(lines) - except HarnessError as e: - return ("skip", f"reference cannot run the program: {e}") - try: - got = translate_listing(lines, name, tmpdir) - except (rdna2spirv.Unsupported, UnsupportedConstruct) as e: - return ("skip", f"{type(e).__name__}: {e}") - except (IndexError, KeyError, ValueError) as e: - return ("skip", f"translator error {type(e).__name__}: {e}") - for i, (w, g) in enumerate(zip(want, got)): - if w != (g & M32): - return ("mismatch", f"word {i} (v{EXPORT_REGS[i]}): expected 0x{w:08x}, " - f"actual 0x{g:08x}") - return ("match", "") - - -# ---- the suites ---- - -def run_sweep(seed, ops=None): - """Every source-kind combination of every op, one program each. Returns (counts, failure).""" - counts = {"pass": 0, "mismatch": 0, "skip": Counter(), "ops": Counter(), "kinds": Counter()} - failure = None - cases = sweep_ops(ops) - with tempfile.TemporaryDirectory(prefix="sad-diff-sweep-") as tmp: - for i, (op, kinds) in enumerate(cases): - rng = random.Random(f"{seed}:{op}:{'/'.join(kinds)}") - lines = sweep_program(op, kinds, rng) - counts["ops"][op] += 1 - for key, n in kind_counts(lines).items(): - counts["kinds"][key] += n - status, detail = run_one(lines, f"ps_sad_sw{i:04d}", tmp) - if status == "match": - counts["pass"] += 1 - elif status == "skip": - counts["skip"][detail] += 1 - else: - counts["mismatch"] += 1 - if failure is None: - failure = (f"sweep {op} {'/'.join(kinds)} (case {i}, seed {seed})", lines, detail) - return counts, failure - - -def run_suite(programs, seed, max_ops=6, ops=None): - """Random seeded programs. Returns (counts, failure).""" - counts = {"pass": 0, "mismatch": 0, "skip": Counter(), "ops": Counter(), "kinds": Counter()} - failure = None - rng = random.Random(f"suite:{seed}") - with tempfile.TemporaryDirectory(prefix="sad-diff-run-") as tmp: - for i in range(programs): - lines, used = program(rng, rng.randint(1, max_ops), ops) - counts["ops"].update(used) - for key, n in kind_counts(lines).items(): - counts["kinds"][key] += n - status, detail = run_one(lines, f"ps_sad_{i:04d}", tmp) - if status == "match": - counts["pass"] += 1 - elif status == "skip": - counts["skip"][detail] += 1 - else: - counts["mismatch"] += 1 - if failure is None: - failure = (f"program {i} (seed {seed})", lines, detail) - return counts, failure - - -def self_test(): - """True when the reference's hand-pinned words, the negative controls and the harness canaries - all hold.""" - ok = True - - def expect(cond, what): - nonlocal ok - print(("ok " if cond else "FAIL ") + what) - ok = ok and cond - - # Hand-pinned reference words, each derived from the ISA pseudocode in the docstring. - expect(SINGLE_OPS["v_sad_u8"](0x01020304, 0xFF00FF00, 5) == 517, - "v_sad_u8(0x01020304, 0xFF00FF00) + 5 = 254+2+252+4+5 = 517") - expect(SINGLE_OPS["v_sad_hi_u8"](0x01020304, 0xFF00FF00, 5) == 0x02000005, - "v_sad_hi_u8: (byte sum << 16) + 5") - expect(SINGLE_OPS["v_sad_u16"](0x0001FFFF, 0xFFFF0001, 0) == 0x0001FFFC, - "v_sad_u16(0x0001FFFF, 0xFFFF0001) = 65534+65534") - expect(SINGLE_OPS["v_sad_u32"](0, 0xFFFFFFFF, 1) == 0, - "v_sad_u32(0, 0xFFFFFFFF) + 1 wraps to 0") - expect(SINGLE_OPS["v_msad_u8"](0x01020304, 0xFF000000, 5) == 259, - "v_msad_u8: only the byte where S1's byte is 0xFF counts: |01-FF|+5") - expect(quad_sad(0x04030201, 0x08070605, 0x04030201, 0, 0) == 0x000C000800040000, - "v_qsad_pk_u16_u8: the four sliding windows of 0x0807060504030201 give 0,4,8,12") - expect(quad_sad(M32, M32, 0, 5, 0, masked=True) == 5, - "v_mqsad_pk_u16_u8 with S1 = 0: everything masked, D = S2") - # 64-bit constant rule: a hex literal has a zero high word, an inline constant sign-extends - # (S1 = 0 makes every window's byte sum the lane value, so the words tell the high word apart). - lit_lit = reference(["v_qsad_pk_u16_u8 v[8:9], 0xFFFF8000, 0, 0"]) - lit_pair = reference(["v_mov_b32 v8, 0xFFFF8000", "v_qsad_pk_u16_u8 v[8:9], v[8:9], 0, 0"]) - expect(lit_lit == [0x027E027E, 0x00FF01FE, 0, 0], - "the literal 0xFFFF8000 as a 64-bit S0: lanes 638, 638, 510, 255 (zero high word)") - expect(lit_lit == lit_pair, - "that literal reads the same as the pair holding its word and 0") - inline = reference(["v_qsad_pk_u16_u8 v[8:9], -16, 0, 0"]) - expect(inline == [0x03FC03ED, 0x03FC03FC, 0, 0], - "the inline constant -16 as a 64-bit S0 sign-extends (lanes 1005, 1020, 1020, 1020)") - expect(inline[1] != lit_lit[1], - "the literal and the inline constant differ in the high word (the rule bites)") - - # The two-oracle path agrees on a fixed program, and a sabotaged word is caught. - lines = ["v_mov_b32 v8, 0x01020304", "v_mov_b32 v9, 0xFF00FF00", "v_mov_b32 v10, 5", - "v_sad_u8 v8, v8, v9, v10"] - expect(check(lines) is None, "a hand-pinned program matches on both oracles") - real = translate_listing - try: - globals()["translate_listing"] = lambda l, n, t: [516] + real(l, n, t)[1:] - expect(check(lines) is not None, "a sabotaged export word is reported") - finally: - globals()["translate_listing"] = real - - # Negative controls: forms the contract rows say are rejected, not guessed. - with tempfile.TemporaryDirectory(prefix="sad-diff-neg-") as tmp: - for what, bad in ( - ("clamp on v_sad_u8", ["v_mov_b32 v8, 1", "v_sad_u8 v8, v8, v8, v8 clamp"]), - ("clamp on v_qsad_pk_u16_u8", ["v_qsad_pk_u16_u8 v[8:9], v[9:10], v11, v[12:13] clamp"]), - ("a quad op to a single VGPR", ["v_qsad_pk_u16_u8 v8, v[9:10], v11, v[12:13]"]), - ("a quad op with a single-VGPR S0", ["v_qsad_pk_u16_u8 v[8:9], v9, v10, v[11:12]"]), - ): - try: - translate_listing(bad, "ps_sad_neg", tmp) - expect(False, f"{what}: the translator rejected it") - except (rdna2spirv.Unsupported, UnsupportedConstruct): - expect(True, f"{what}: the translator rejected it") - - # Determinism: the same seed gives the same program stream. - expect(program(random.Random(9), 4) == program(random.Random(9), 4), - "generation is deterministic for a seed") - counts, failure = run_suite(6, 3, 3) - expect(failure is None and counts["pass"] == 6 and not counts["skip"], - f"a short seeded run matches ({counts['pass']} programs, skips {dict(counts['skip'])})") - return ok - - -def main(): - ap = argparse.ArgumentParser(description=__doc__.splitlines()[0], - formatter_class=argparse.RawDescriptionHelpFormatter) - ap.add_argument("--programs", type=int, default=300, help="random programs after the sweep") - ap.add_argument("--seed", type=int, default=1) - ap.add_argument("--max-ops", type=int, default=6, help="ops per random program") - ap.add_argument("--ops", default=None, help="comma-separated opcodes to cover (default: all)") - ap.add_argument("--no-sweep", action="store_true", help="skip the source-kind sweep") - ap.add_argument("--list-ops", action="store_true") - ap.add_argument("--self-test", action="store_true") - args = ap.parse_args() - - if args.list_ops: - for op, form in OP_FORMS.items(): - print(f"{op:22s} {form}") - return 0 - if args.self_test: - return 0 if self_test() else 1 - - ops = [o.strip() for o in args.ops.split(",")] if args.ops else None - bad = [o for o in (ops or []) if o not in OP_FORMS] - if bad: - print(f"unknown op(s) {bad}; --list-ops shows the family", file=sys.stderr) - return 2 - - total_pass = total_run = total_mismatch = 0 - per_op = Counter() - failure = None - try: - if not args.no_sweep: - counts, first = run_sweep(args.seed, ops) - total_pass += counts["pass"] - total_mismatch += counts["mismatch"] - total_run += counts["pass"] + counts["mismatch"] + sum(counts["skip"].values()) - per_op.update(counts["ops"]) - print(f"sweep: {counts['pass']}/{counts['pass'] + counts['mismatch'] + sum(counts['skip'].values())} " - f"source-kind programs match, {counts['mismatch']} mismatch; " - f"skips: {dict(counts['skip'])}") - failure = failure or first - counts, first = run_suite(args.programs, args.seed, args.max_ops, ops) - total_pass += counts["pass"] - total_mismatch += counts["mismatch"] - total_run += counts["pass"] + counts["mismatch"] + sum(counts["skip"].values()) - per_op.update(counts["ops"]) - print(f"random: {counts['pass']}/{counts['pass'] + counts['mismatch'] + sum(counts['skip'].values())} " - f"programs match, {counts['mismatch']} mismatch; skips: {dict(counts['skip'])}") - failure = failure or first - except HarnessError as e: - print(f"harness error: {e}", file=sys.stderr) - return 2 - print("cases per op: " + ", ".join(f"{op} {per_op[op]}" for op in sorted(per_op))) - print(f"SAD family: {total_pass}/{total_run} programs match, {total_mismatch} mismatch " - f"({len(per_op)} of {len(OP_FORMS)} ops)") - if failure: - _report(failure) - return 1 - if not total_pass: # nothing was compared: every program was skipped - print("no program ran: every one was skipped") - return 2 - return 0 - - -def _report(failure): - name, lines, detail = failure - print(f"MISMATCH {name}: {detail}") - print("program:") - for line in lines: - print(" " + line) - - -if __name__ == "__main__": - try: # a redirected stdout is strict ANSI code page under -I; write '?' for what it cannot encode - sys.stdout.reconfigure(errors="replace") - except (AttributeError, ValueError, OSError): - pass - sys.exit(main()) diff --git a/tools/salu_diff.py b/tools/salu_diff.py deleted file mode 100644 index 634d5f7b4..000000000 --- a/tools/salu_diff.py +++ /dev/null @@ -1,856 +0,0 @@ -r"""Differential fuzzing of the scalar ALU and SCC (FUZZ-4 in #156). Standard library only. - -Generates seeded straight-line programs of SOP1/SOP2/SOPC/SOPK instructions, runs them through - - * the reference below, written from the RDNA2 ISA guide's pseudocode for each opcode, and - * tools/rdna2spirv.py, executing the SPIR-V with tests/semantic/spirv_mini_interp.py, - -and compares four exported words bit for bit: three SGPRs and SCC (through s_cselect_b32). -The reference is separate from tools/cpu_ref.py on purpose: it models only the scalar unit, keeps -SCC explicit for every opcode, and does not share code with the translator. - -With --oracle hw the same programs also run natively on an AMD GPU (tools/hw_oracle/) and the hardware's four -words are compared with the reference: that validates the reference itself, not the translator. The GPU is -whatever the machine has (gfx11 on an RDNA3 laptop), so a difference is checked against the ISA text before it -counts as a reference bug. Without the oracle tools the run exits 77. - -With --branches the programs also consume SCC in control flow: after an SCC-producing instruction comes either -a chain of 1..3 SCC consumers (s_cselect_b32, s_addc_u32, s_subb_u32) or s_cbranch_scc0/scc1 forward over the -next 1..3 scalar instructions (no loops, no nesting, one lane). In the program lines a branch is written -`s_cbranch_scc0 +N` (skip the next N instructions); the listing handed to the translator carries the real offset -in dwords and `; encoding:` placeholders of each instruction's size, which is what places the branch targets. -Half of the instructions are then drawn from the SCC producers among the selected opcodes, so over a few thousand -programs every producer is followed by every consumer and by both branch senses. The hardware oracle does not -take branch programs (its kernels are straight-line). - -Usage: - python -I tools/salu_diff.py [--programs N] [--seed S] [--max-ops N] [--ops s_min_i32,s_cselect_b32] - python -I tools/salu_diff.py --branches [--programs N] [--seed S] # SCC consumers and forward branches - python -I tools/salu_diff.py --oracle hw # hardware vs reference only - python -I tools/salu_diff.py --oracle translator,hw # both - python -I tools/salu_diff.py --list-ops - python -I tools/salu_diff.py --self-test - -Exit 0 when every program matches, 1 on a mismatch (the shortest failing program is printed after -removing instructions that do not matter), 2 on a harness error, 77 when the requested hardware oracle is -unavailable. Skips are counted with their reasons. - -By default the opcodes in LANE_MASK_OPS are left out (a hardware-only run keeps them: the GPU has no wave-mask -view of a 64-bit SGPR pair): the translator models those 64-bit values (and -s_wqm_b32) as per-lane wave masks, so a 64-bit integer reference disagrees with them by design (--ops -names them explicitly). s_bfe_* control words stay inside offset + width <= 32 unless --bfe-any: past -that the field stops at bit 31 (width = min(width, 32 - offset), so s_bfe_i32 sign-extends from the top bit -that exists). gfx1150 hardware and the translator both do that; the ISA pseudocode does not say so, and RDNA2 -itself is unmeasured (#156). s_ff0/ff1_i32_b32 with a constant source diverged until SHADER-46 (#349). - -SCC selects: s_cmov_b32, s_cmovk_i32 (SIMM16 sign-extended) and s_cmov_b64 keep D when SCC is 0; they read SCC -and do not write it, so --branches uses them as consumers too. Relative reads: when the opcodes include -s_movrels_b32/b64, the program sets M0 to 0..7 once, after the seeds, and every s_movrels reads -SGPR[S0 + M0] (the b64 form the pair there) inside the seeded SGPRs. With an odd M0 the b64 form is not -generated (the b32 one takes its place): an odd-aligned pair is unmeasured. These rows rest on the gfx1035 -cases of tools/int_hw_probe.py (docs/shader_validation.md). -""" -import argparse -import gc -import os -import random -import struct -import sys -import tempfile -import warnings - -HERE = os.path.dirname(os.path.abspath(__file__)) -sys.dont_write_bytecode = True -if HERE not in sys.path: - sys.path.insert(0, HERE) -SEM_DIR = os.path.join(os.path.dirname(HERE), "tests", "semantic") -if SEM_DIR not in sys.path: - sys.path.insert(0, SEM_DIR) - -M32 = 0xFFFFFFFF -M64 = (1 << 64) - 1 -STUB_DXBC = b"DXBC" + bytes(24) + struct.pack("> 63 else x - - -def sext8(x): - x &= 0xFF - return x - 0x100 if x & 0x80 else x - - -def sext16(x): - x &= 0xFFFF - return x - 0x10000 if x & 0x8000 else x - - -def flbit32(x): - x &= M32 - sign = x >> 31 - for n in range(1, 32): - if (x >> (31 - n)) & 1 != sign: - return n - return M32 - - -def is_nan(w): - return (w & 0x7F800000) == 0x7F800000 and (w & 0x7FFFFF) != 0 - - -def popcount(x): - return bin(x).count("1") - - -def first_set(x, width): - """Index of the lowest set bit, or -1 (0xFFFFFFFF).""" - for i in range(width): - if (x >> i) & 1: - return i - return M32 - - -def wqm(x, width): - out = 0 - for q in range(0, width, 4): - if (x >> q) & 0xF: - out |= 0xF << q - return out - - -def quadmask(x, width): - out = 0 - for q in range(width // 4): - if (x >> (4 * q)) & 0xF: - out |= 1 << q - return out - - -def bitreplicate(x): - out = 0 - for i in range(32): - if (x >> i) & 1: - out |= 3 << (2 * i) - return out - - -def flbit_signed(x, width): - mask = (1 << width) - 1 - x &= mask - sign = (x >> (width - 1)) & 1 - v = (~x & mask) if sign else x - return (width - v.bit_length()) if v else M32 - - -def bfe64(src, ctl, signed): - off, width = ctl & 63, (ctl >> 16) & 0x7F - width = min(width, 64 - off) - if width == 0: - return 0 - field = (src >> off) & ((1 << width) - 1) - if signed and (field >> (width - 1)) & 1: - field -= 1 << width - return field & M64 - - -def bfe(src, ctl, signed): - off, width = ctl & 31, (ctl >> 16) & 0x7F - # A field that runs past bit 31 stops there: s_bfe_i32 sign-extends from the top bit that exists (LLVM - # constantFoldBFE does for v_bfe; 5-bit width there). The s_bfe rule itself rests on the gfx1150 measurement - # (4000 random control words, --oracle hw), and RDNA2 agrees: gfx1036 (counts in the s_bfe row of docs/design.md). - width = min(width, 32 - off) - if width == 0: - return 0 - field = (src >> off) & ((1 << width) - 1) - if signed and (field >> (width - 1)) & 1: - field -= 1 << width - return field & M32 - - -# ---- the reference: one entry per opcode --------------------------------------------------------- -# form: "sop2" d, a, b (32-bit); "sop2_64" d, a, b (64-bit pairs); "sop2_64s" d64, a64, b32 (shift amount); -# "sop2_bfm64" d64, a32, b32; "sop1" d, a; "sop1_64" d64, a64; "sop1_64to32" d32, a64; "sopc" a, b; -# "sopc_64" a64, b64; "sopk" d, simm16 (d is read too); "movk"; "cmpk" a, simm16. -# fn(a, b, scc[, d]) -> (result, new_scc or None). None leaves SCC as it was. - -def _sop2(): - ops = {} - - def add(name, fn): - ops[name] = ("sop2", fn) - - add("s_add_u32", lambda a, b, c: ((a + b) & M32, (a + b) >> 32)) - add("s_sub_u32", lambda a, b, c: ((a - b) & M32, int(b > a))) - add("s_addc_u32", lambda a, b, c: ((a + b + c) & M32, (a + b + c) >> 32)) - add("s_subb_u32", lambda a, b, c: ((a - b - c) & M32, int(b + c > a))) - add("s_add_i32", lambda a, b, c: ((a + b) & M32, int(not -2**31 <= s32(a) + s32(b) < 2**31))) - add("s_sub_i32", lambda a, b, c: ((a - b) & M32, int(not -2**31 <= s32(a) - s32(b) < 2**31))) - add("s_min_i32", lambda a, b, c: (a if s32(a) < s32(b) else b, int(s32(a) < s32(b)))) - add("s_min_u32", lambda a, b, c: (a if a < b else b, int(a < b))) - add("s_max_i32", lambda a, b, c: (a if s32(a) > s32(b) else b, int(s32(a) > s32(b)))) - add("s_max_u32", lambda a, b, c: (a if a > b else b, int(a > b))) - add("s_cselect_b32", lambda a, b, c: (a if c else b, None)) - for name, f in (("and", lambda a, b: a & b), ("or", lambda a, b: a | b), ("xor", lambda a, b: a ^ b), - ("andn2", lambda a, b: a & ~b), ("orn2", lambda a, b: a | ~b), ("nand", lambda a, b: ~(a & b)), - ("nor", lambda a, b: ~(a | b)), ("xnor", lambda a, b: ~(a ^ b))): - add(f"s_{name}_b32", lambda a, b, c, f=f: (f(a, b) & M32, int(f(a, b) & M32 != 0))) - add("s_lshl_b32", lambda a, b, c: ((a << (b & 31)) & M32, int((a << (b & 31)) & M32 != 0))) - add("s_lshr_b32", lambda a, b, c: (a >> (b & 31), int(a >> (b & 31) != 0))) - add("s_ashr_i32", lambda a, b, c: ((s32(a) >> (b & 31)) & M32, int((s32(a) >> (b & 31)) & M32 != 0))) - add("s_bfm_b32", lambda a, b, c: ((((1 << (a & 31)) - 1) << (b & 31)) & M32, None)) - add("s_mul_i32", lambda a, b, c: ((s32(a) * s32(b)) & M32, None)) - add("s_mul_hi_u32", lambda a, b, c: ((a * b) >> 32, None)) - add("s_mul_hi_i32", lambda a, b, c: (((s32(a) * s32(b)) >> 32) & M32, None)) - add("s_absdiff_i32", lambda a, b, c: (abs(s32((a - b) & M32)) & M32, int(abs(s32((a - b) & M32)) & M32 != 0))) - add("s_lshl1_add_u32", lambda a, b, c: (((a << 1) + b) & M32, int(((a << 1) + b) >= (1 << 32)))) - add("s_lshl2_add_u32", lambda a, b, c: (((a << 2) + b) & M32, int(((a << 2) + b) >= (1 << 32)))) - add("s_lshl3_add_u32", lambda a, b, c: (((a << 3) + b) & M32, int(((a << 3) + b) >= (1 << 32)))) - add("s_lshl4_add_u32", lambda a, b, c: (((a << 4) + b) & M32, int(((a << 4) + b) >= (1 << 32)))) - add("s_bfe_u32", lambda a, b, c: (bfe(a, b, False), int(bfe(a, b, False) != 0))) - add("s_bfe_i32", lambda a, b, c: (bfe(a, b, True), int(bfe(a, b, True) != 0))) - add("s_pack_ll_b32_b16", lambda a, b, c: (((b & 0xFFFF) << 16) | (a & 0xFFFF), None)) - add("s_pack_lh_b32_b16", lambda a, b, c: ((b & 0xFFFF0000) | (a & 0xFFFF), None)) - add("s_pack_hh_b32_b16", lambda a, b, c: ((b & 0xFFFF0000) | ((a >> 16) & 0xFFFF), None)) - return ops - - -def _sop2_64(): - ops = {} - for name, f in (("and", lambda a, b: a & b), ("or", lambda a, b: a | b), ("xor", lambda a, b: a ^ b), - ("andn2", lambda a, b: a & ~b), ("orn2", lambda a, b: a | ~b), - ("nand", lambda a, b: ~(a & b)), ("nor", lambda a, b: ~(a | b)), - ("xnor", lambda a, b: ~(a ^ b))): - ops[f"s_{name}_b64"] = ("sop2_64", lambda a, b, c, f=f: (f(a, b) & M64, int(f(a, b) & M64 != 0))) - ops["s_cselect_b64"] = ("sop2_64", lambda a, b, c: (a if c else b, None)) - ops["s_lshl_b64"] = ("sop2_64s", lambda a, b, c: ((a << (b & 63)) & M64, int((a << (b & 63)) & M64 != 0))) - ops["s_lshr_b64"] = ("sop2_64s", lambda a, b, c: (a >> (b & 63), int(a >> (b & 63) != 0))) - ops["s_ashr_i64"] = ("sop2_64s", lambda a, b, c: ((s64(a) >> (b & 63)) & M64, int((s64(a) >> (b & 63)) & M64 != 0))) - ops["s_bfe_u64"] = ("sop2_64s", lambda a, b, c: (bfe64(a, b, False), int(bfe64(a, b, False) != 0))) - ops["s_bfe_i64"] = ("sop2_64s", lambda a, b, c: (bfe64(a, b, True), int(bfe64(a, b, True) != 0))) - ops["s_bfm_b64"] = ("sop2_bfm64", lambda a, b, c: ((((1 << (a & 63)) - 1) << (b & 63)) & M64, None)) - return ops - - -def _sop1(): - ops = { - "s_mov_b32": ("sop1", lambda a, b, c: (a, None)), - "s_not_b32": ("sop1", lambda a, b, c: (~a & M32, int(~a & M32 != 0))), - "s_brev_b32": ("sop1", lambda a, b, c: (int(f"{a:032b}"[::-1], 2), None)), - "s_bcnt0_i32_b32": ("sop1", lambda a, b, c: (32 - popcount(a), int(32 - popcount(a) != 0))), - "s_bcnt1_i32_b32": ("sop1", lambda a, b, c: (popcount(a), int(popcount(a) != 0))), - "s_ff0_i32_b32": ("sop1", lambda a, b, c: (first_set(~a & M32, 32), None)), - "s_ff1_i32_b32": ("sop1", lambda a, b, c: (first_set(a, 32), None)), - "s_flbit_i32_b32": ("sop1", lambda a, b, c: (32 - a.bit_length() if a else M32, None)), - "s_flbit_i32": ("sop1", lambda a, b, c: (flbit32(a), None)), - "s_sext_i32_i8": ("sop1", lambda a, b, c: (sext8(a) & M32, None)), - "s_sext_i32_i16": ("sop1", lambda a, b, c: (sext16(a) & M32, None)), - "s_quadmask_b32": ("sop1", lambda a, b, c: (quadmask(a, 32), int(quadmask(a, 32) != 0))), - "s_abs_i32": ("sop1", lambda a, b, c: (abs(s32(a)) & M32, int(abs(s32(a)) & M32 != 0))), - "s_wqm_b32": ("sop1", lambda a, b, c: (wqm(a, 32), int(wqm(a, 32) != 0))), - # D is read: bit S0[4:0] (or S0[5:0] for b64) of the destination is cleared or set. - "s_bitset0_b32": ("sop1_rmw", lambda a, b, c, d: (d & ~(1 << (a & 31)) & M32, None)), - "s_bitset1_b32": ("sop1_rmw", lambda a, b, c, d: (d | (1 << (a & 31)), None)), - "s_bitset0_b64": ("sop1_64_rmw", lambda a, b, c, d: (d & ~(1 << (a & 63)) & M64, None)), - "s_bitset1_b64": ("sop1_64_rmw", lambda a, b, c, d: (d | (1 << (a & 63)), None)), - # SCC ? S0 : D. SCC is read, not written. - "s_cmov_b32": ("sop1_rmw", lambda a, b, c, d: (a if c else d, None)), - "s_cmov_b64": ("sop1_64_rmw64", lambda a, b, c, d: (a if c else d, None)), - # SGPR[S0 + M0]: the reference reads the register (or pair) and passes its value as a. - "s_movrels_b32": ("movrels", lambda a, b, c: (a, None)), - "s_movrels_b64": ("movrels_64", lambda a, b, c: (a, None)), - "s_mov_b64": ("sop1_64", lambda a, b, c: (a, None)), - "s_not_b64": ("sop1_64", lambda a, b, c: (~a & M64, int(~a & M64 != 0))), - "s_brev_b64": ("sop1_64", lambda a, b, c: (int(f"{a:064b}"[::-1], 2), None)), - "s_quadmask_b64": ("sop1_64", lambda a, b, c: (quadmask(a, 64), int(quadmask(a, 64) != 0))), - "s_wqm_b64": ("sop1_64", lambda a, b, c: (wqm(a, 64), int(wqm(a, 64) != 0))), - "s_bitreplicate_b64_b32": ("sop1_32to64", lambda a, b, c: (bitreplicate(a), None)), - "s_bcnt0_i32_b64": ("sop1_64to32", lambda a, b, c: (64 - popcount(a), int(64 - popcount(a) != 0))), - "s_bcnt1_i32_b64": ("sop1_64to32", lambda a, b, c: (popcount(a), int(popcount(a) != 0))), - "s_ff0_i32_b64": ("sop1_64to32", lambda a, b, c: (first_set(~a & M64, 64), None)), - "s_ff1_i32_b64": ("sop1_64to32", lambda a, b, c: (first_set(a, 64), None)), - "s_flbit_i32_b64": ("sop1_64to32", lambda a, b, c: (64 - a.bit_length() if a else M32, None)), - "s_flbit_i32_i64": ("sop1_64to32", lambda a, b, c: (flbit_signed(a, 64), None)), - } - return ops - - -def _sopc(): - ops = {} - for cmp, f in (("eq", lambda x, y: x == y), ("lg", lambda x, y: x != y), ("gt", lambda x, y: x > y), - ("ge", lambda x, y: x >= y), ("lt", lambda x, y: x < y), ("le", lambda x, y: x <= y)): - ops[f"s_cmp_{cmp}_i32"] = ("sopc", lambda a, b, c, f=f: (None, int(f(s32(a), s32(b))))) - ops[f"s_cmp_{cmp}_u32"] = ("sopc", lambda a, b, c, f=f: (None, int(f(a, b)))) - # SOPK compares: SIMM16 sign-extended for i32, zero-extended for u32. - ops[f"s_cmpk_{cmp}_i32"] = ("cmpk", lambda a, k, c, f=f: (None, int(f(s32(a), sext16(k))))) - ops[f"s_cmpk_{cmp}_u32"] = ("cmpk", lambda a, k, c, f=f: (None, int(f(a, k & 0xFFFF)))) - ops["s_bitcmp0_b32"] = ("sopc", lambda a, b, c: (None, int(not (a >> (b & 31)) & 1))) - ops["s_bitcmp1_b32"] = ("sopc", lambda a, b, c: (None, int((a >> (b & 31)) & 1))) - ops["s_cmp_eq_u64"] = ("sopc_64", lambda a, b, c: (None, int(a == b))) - ops["s_cmp_lg_u64"] = ("sopc_64", lambda a, b, c: (None, int(a != b))) - ops["s_movk_i32"] = ("movk", lambda a, k, c: (sext16(k) & M32, None)) - ops["s_addk_i32"] = ("sopk", lambda d, k, c: ((d + sext16(k)) & M32, - int(not -2**31 <= s32(d) + sext16(k) < 2**31))) - ops["s_mulk_i32"] = ("sopk", lambda d, k, c: ((s32(d) * sext16(k)) & M32, None)) - ops["s_cmovk_i32"] = ("sopk", lambda d, k, c: (sext16(k) & M32 if c else d, None)) - return ops - - -OPS = {**_sop2(), **_sop2_64(), **_sop1(), **_sopc()} - -SCC_CONSUMERS = ("s_cselect_b32", "s_addc_u32", "s_subb_u32", "s_cmov_b32", "s_cmovk_i32", "s_cmov_b64") -RMW_FORMS = ("sop1_rmw", "sop1_64_rmw", "sop1_64_rmw64") # fn(a, b, scc, d): D is read too -MOVREL_FORMS = ("movrels", "movrels_64") -SCC_BRANCHES = ("s_cbranch_scc0", "s_cbranch_scc1") - - -def writes_scc(name): - """Whether the opcode writes SCC (each one always does or never does).""" - form, fn = OPS[name] - return (fn(1, 2, 0, 3) if form in RMW_FORMS else fn(1, 2, 0))[1] is not None - - -def branch_skip(line): - """For `s_cbranch_scc0/1 +N`: (mnemonic, N); None for any other line.""" - op, _, rest = line.partition(" ") - if op not in SCC_BRANCHES: - return None - if not rest.startswith("+"): - raise RefError(f"branch {line!r}: expected +N (instructions skipped)") - return op, int(rest[1:]) - - -# ---- program generation --------------------------------------------------------------------------- - -def _value(rng): - return rng.choice(INTERESTING) if rng.random() < 0.6 else rng.getrandbits(32) - - -def _src32(rng): - """An SGPR most of the time, sometimes an inline constant or a literal.""" - r = rng.random() - if r < 0.75: - return f"s{rng.choice(REGS)}" - if r < 0.9: - return str(rng.randrange(-16, 65)) - return f"0x{_value(rng):x}" - - -def _pair(r): - return f"s[{r}:{r + 1}]" - - -def _src64(rng): - if rng.random() < 0.85 or not INLINE64: - return _pair(rng.choice(PAIRS)) - return str(rng.randrange(-16, 65)) # an inline constant, sign-extended to 64 bits - - -def _bfe_ctl(rng): - off = rng.randrange(0, 32) - width = rng.randrange(0, 33 - off) # offset + width <= 32: the documented range - return f"0x{(width << 16) | off:x}" - - -def _shared_literal_sources(src0: str, src1: str, register: int) -> str: - # A scalar instruction can carry only one literal dword. Equal literals can share it. - if src0 != src1 and _is_literal(src0) and _is_literal(src1): - src0 = f"s{register}" - return f"{src0}, {src1}" - - -def emit(rng, name, m0=0): - """One instruction. m0: the program's M0, which keeps an s_movrels source inside the seeded SGPRs.""" - form = OPS[name][0] - d, p = rng.choice(REGS), rng.choice(PAIRS) - if form == "movrels_64" and m0 % 2: - name, form = "s_movrels_b32", "movrels" # an odd-aligned pair is not generated - if form == "movrels": - return f"{name} s{d}, s{rng.choice([r for r in REGS if r + m0 <= REGS[-1]])}" - if form == "movrels_64": - return f"{name} {_pair(p)}, {_pair(rng.choice([r for r in PAIRS if r + m0 + 1 <= REGS[-1]]))}" - if form == "sop2": - b = _src32(rng) if name.startswith("s_bfe") and BFE_ANY and rng.random() < 0.3 else _bfe_ctl(rng) if name.startswith("s_bfe") else _src32(rng) - return f"{name} s{d}, {_shared_literal_sources(_src32(rng), b, d)}" - if form == "sop2_64": - return f"{name} {_pair(p)}, {_src64(rng)}, {_src64(rng)}" - if form == "sop2_64s": - return f"{name} {_pair(p)}, {_src64(rng)}, {_src32(rng)}" - if form == "sop2_bfm64": - return f"{name} {_pair(p)}, {_shared_literal_sources(_src32(rng), _src32(rng), d)}" - if form in ("sop1", "sop1_rmw"): - return f"{name} s{d}, {_src32(rng)}" - if form in ("sop1_64", "sop1_64_rmw64"): - return f"{name} {_pair(p)}, {_src64(rng)}" - if form in ("sop1_32to64", "sop1_64_rmw"): - return f"{name} {_pair(p)}, {_src32(rng)}" - if form == "sop1_64to32": - return f"{name} s{d}, {_src64(rng)}" - if form == "sopc": - return f"{name} {_shared_literal_sources(_src32(rng), _src32(rng), d)}" - if form == "sopc_64": - return f"{name} {_src64(rng)}, {_src64(rng)}" - k = rng.choice((0, 1, 0x7FFF, 0x8000, 0xFFFF, 0xFFFE, rng.getrandbits(16))) - if form == "cmpk": - return f"{name} s{d}, 0x{k:x}" - return f"{name} s{d}, 0x{k:x}" # movk, sopk - - -def generate(rng, n_ops, ops, branches=False): - lines = [f"s_mov_b32 s{r}, 0x{_value(rng):x}" for r in REGS] - m0 = 0 - if any(OPS[o][0] in MOVREL_FORMS for o in ops): - m0 = rng.randrange(8) - lines.append(f"s_mov_b32 m0, {m0}") # part of the seeds: shrinking keeps it - lines.append(f"s_cmp_eq_u32 s{rng.choice(REGS)}, s{rng.choice(REGS)}") # a known SCC to start with - if branches: - lines += _cf_body(rng, n_ops, ops, m0) - else: - for _ in range(n_ops): - lines.append(emit(rng, rng.choice(ops), m0)) - lines += observe(rng.sample(REGS, 3)) - return lines - - -def _cf_body(rng, n_ops, ops, m0=0): - """n_ops instructions, half of them SCC producers. After a producer: sometimes a chain of SCC consumers, - sometimes s_cbranch_scc0/1 forward over the next 1..3 instructions (which never branch themselves).""" - producers = [o for o in ops if writes_scc(o)] or ops - body = [] - for _ in range(n_ops): - op = rng.choice(producers if rng.random() < 0.5 else ops) - body.append(emit(rng, op, m0)) - if not writes_scc(op): - continue - r = rng.random() - if r < 0.35: - body += [emit(rng, rng.choice(SCC_CONSUMERS), m0) for _ in range(rng.randint(1, 3))] - elif r < 0.8: - k = rng.randint(1, 3) - body.append(f"{rng.choice(SCC_BRANCHES)} +{k}") - body += [emit(rng, rng.choice(ops + list(SCC_CONSUMERS)), m0) for _ in range(k)] - return body - - -def observe(regs): - return [f"s_cselect_b32 s{OUT_SCC}, 1, 0", - f"v_mov_b32 v8, s{regs[0]}", f"v_mov_b32 v9, s{regs[1]}", f"v_mov_b32 v10, s{regs[2]}", - f"v_mov_b32 v11, s{OUT_SCC}"] - - -# ---- the reference interpreter ------------------------------------------------------------------- - -class RefError(Exception): - pass - - -def _parse_src(tok, sgpr, width): - tok = tok.strip() - if tok.startswith("s["): - lo = int(tok[2:tok.index(":")]) - if width == 32: - raise RefError(f"pair {tok} in a 32-bit position") - return sgpr.get(lo, 0) | sgpr.get(lo + 1, 0) << 32 - if tok.startswith("s"): - if width == 64: - raise RefError(f"{tok} in a 64-bit position") - return sgpr.get(int(tok[1:]), 0) - v = int(tok, 0) - if width == 64: - # inline constants are sign-extended; a 32-bit literal is zero-extended (not generated here) - return v & M64 if -16 <= v <= 64 else v & M32 - return v & M32 - - -def _write(sgpr, tok, value, width): - tok = tok.strip() - if width == 64: - lo = int(tok[2:tok.index(":")]) - sgpr[lo], sgpr[lo + 1] = value & M32, (value >> 32) & M32 - else: - sgpr[int(tok[1:])] = value & M32 - - -def reference(lines): - """Run the scalar program; returns the four exported words.""" - sgpr, scc, vgpr, m0 = {}, 0, {}, 0 - skip = 0 - for line in lines: - if skip: - skip -= 1 - continue - br = branch_skip(line) - if br: - # SOPP: if SCC == 0 (scc0) / SCC == 1 (scc1) then PC = PC + SIMM16 * 4 + 4; SCC is not written. - if scc == (0 if br[0] == "s_cbranch_scc0" else 1): - skip = br[1] - continue - op, _, rest = line.partition(" ") - args = [a.strip() for a in rest.split(", ")] if rest else [] - if op == "v_mov_b32": - vgpr[int(args[0][1:])] = _parse_src(args[1], sgpr, 32) - continue - if op == "s_mov_b32" and args[0] == "m0": - m0 = _parse_src(args[1], sgpr, 32) - continue - if op not in OPS: - raise RefError(f"{op} is not modelled") - form, fn = OPS[op] - if form == "sop2": - r, c = fn(_parse_src(args[1], sgpr, 32), _parse_src(args[2], sgpr, 32), scc) - _write(sgpr, args[0], r, 32) - elif form == "sop2_64": - r, c = fn(_parse_src(args[1], sgpr, 64), _parse_src(args[2], sgpr, 64), scc) - _write(sgpr, args[0], r, 64) - elif form == "sop2_64s": - r, c = fn(_parse_src(args[1], sgpr, 64), _parse_src(args[2], sgpr, 32), scc) - _write(sgpr, args[0], r, 64) - elif form == "sop2_bfm64": - r, c = fn(_parse_src(args[1], sgpr, 32), _parse_src(args[2], sgpr, 32), scc) - _write(sgpr, args[0], r, 64) - elif form == "sop1": - r, c = fn(_parse_src(args[1], sgpr, 32), None, scc) - _write(sgpr, args[0], r, 32) - elif form == "sop1_rmw": - r, c = fn(_parse_src(args[1], sgpr, 32), None, scc, _parse_src(args[0], sgpr, 32)) - _write(sgpr, args[0], r, 32) - elif form == "sop1_64": - r, c = fn(_parse_src(args[1], sgpr, 64), None, scc) - _write(sgpr, args[0], r, 64) - elif form == "sop1_64_rmw": - r, c = fn(_parse_src(args[1], sgpr, 32), None, scc, _parse_src(args[0], sgpr, 64)) - _write(sgpr, args[0], r, 64) - elif form == "sop1_64_rmw64": - r, c = fn(_parse_src(args[1], sgpr, 64), None, scc, _parse_src(args[0], sgpr, 64)) - _write(sgpr, args[0], r, 64) - elif form in MOVREL_FORMS: - n = 2 if form == "movrels_64" else 1 - base = int(args[1][2:args[1].index(":")] if n == 2 else args[1][1:]) + m0 - if base < REGS[0] or base + n - 1 > REGS[-1]: - raise RefError(f"{line!r}: SGPR {base} (S0 + M0) is outside the seeded s{REGS[0]}..s{REGS[-1]}") - r, c = fn(sum(sgpr.get(base + w, 0) << (32 * w) for w in range(n)), None, scc) - _write(sgpr, args[0], r, 32 * n) - elif form == "sop1_32to64": - r, c = fn(_parse_src(args[1], sgpr, 32), None, scc) - _write(sgpr, args[0], r, 64) - elif form == "sop1_64to32": - r, c = fn(_parse_src(args[1], sgpr, 64), None, scc) - _write(sgpr, args[0], r, 32) - elif form == "sopc": - _, c = fn(_parse_src(args[0], sgpr, 32), _parse_src(args[1], sgpr, 32), scc) - elif form == "sopc_64": - _, c = fn(_parse_src(args[0], sgpr, 64), _parse_src(args[1], sgpr, 64), scc) - elif form == "cmpk": - _, c = fn(_parse_src(args[0], sgpr, 32), int(args[1], 0), scc) - elif form == "movk": - r, c = fn(None, int(args[1], 0), scc) - _write(sgpr, args[0], r, 32) - elif form == "sopk": - r, c = fn(_parse_src(args[0], sgpr, 32), int(args[1], 0), scc) - _write(sgpr, args[0], r, 32) - else: - raise RefError(f"form {form}") - if c is not None: - scc = int(c) - return [vgpr.get(r, 0) for r in (8, 9, 10, 11)] - - -# ---- the translator side ------------------------------------------------------------------------- - -def _is_literal(tok): - """A 32-bit source that needs a literal dword: not a register or an integer inline constant (-16..64).""" - tok = tok.strip() - if tok[0] in "sv": - return False - return not -16 <= s32(int(tok, 0)) <= 64 - - -def insn_size(line): - """Encoded bytes of one generated line: 4, or 8 with a literal (a SOPK immediate sits in SIMM16).""" - op, _, rest = line.partition(" ") - if op == "exp": - return 8 - if op in SCC_BRANCHES or op == "s_endpgm" or (op in OPS and OPS[op][0] in ("sopk", "movk", "cmpk")): - return 4 - args = rest.split(", ") if rest else [] - srcs = args if op in OPS and OPS[op][0] in ("sopc", "sopc_64") else args[1:] - return 8 if any(_is_literal(a) for a in srcs) else 4 - - -def listing(lines): - """(text, size) per line, with `s_cbranch_scc0/1 +N` turned into the dword offset over the next N lines.""" - sizes = [insn_size(line) for line in lines] - out = [] - for i, line in enumerate(lines): - br = branch_skip(line) - if br: - if i + 1 + br[1] > len(lines): - raise RefError(f"branch {line!r} past the end of the program") - line = f"{br[0]} {sum(sizes[i + 1:i + 1 + br[1]]) // 4}" - out.append((line, sizes[i])) - return out - - -def has_branches(lines): - return any(branch_skip(line) for line in lines) - -def translated(lines, name="ps_salu"): - """Translate and execute; returns the four exported words, or raises Skip.""" - import rdna2spirv - from spirv_mini_interp import run_fragment - with tempfile.TemporaryDirectory(prefix="salu-diff-") as tmp: - dis = os.path.join(tmp, "disasm") - os.mkdir(dis) - path = os.path.join(dis, name + ".s") - with open(path, "w", encoding="utf-8", newline="\n") as f: - if has_branches(lines): - # The translator places branch targets from the encoding sizes; it does not read the bytes. - body = listing(lines + ["exp mrt0 v8, v9, v10, v11 done vm", "s_endpgm"]) - f.write(f"; {name} code 0x0..0x{sum(n for _, n in body):x}\n") - for text, n in body: - f.write("\t" + text + " ; encoding: [" + ",".join(["0x00"] * n) + "]\n") - else: - f.write(f"; {name} salu_diff case\n") - for line in lines: - f.write("\t" + line + "\n") - f.write("\texp mrt0 v8, v9, v10, v11 done vm\n\ts_endpgm\n") - with open(os.path.join(tmp, name + ".dxbc"), "wb") as f: - f.write(STUB_DXBC) - try: - with warnings.catch_warnings(): - warnings.simplefilter("ignore", ResourceWarning) - spvasm = rdna2spirv.translate(path) - gc.collect() - except rdna2spirv.Unsupported as e: - raise Skip(f"translator unsupported: {e}") from None - try: - out = run_fragment(spvasm) - except Exception as e: # noqa: BLE001 - an interpreter gap is a counted skip, never a pass - raise Skip(f"mini_interp: {type(e).__name__}: {str(e)[:80]}") from None - return [w & M32 for w in out["%out_mrt0"]] - - -class Skip(Exception): - pass - - -def _diff(lines, want, got, label, quiet_nan): - # A signalling-NaN pattern comes back quiet through the interpreter's Python floats; hardware is exact. - bad = [k for k in range(4) if want[k] != got[k] and not (quiet_nan and is_nan(want[k]) and is_nan(got[k]))] - if not bad: - return None - i = bad[0] - what = "SCC" if i == 3 else lines[-4 + i].split(", ")[1] - return f"word {i} ({what}): reference 0x{want[i]:08x}, {label} 0x{got[i]:08x}" - - -def check(lines, backends=("translator",), hw=None): - """None on a match, else a description. Raises Skip (every backend skipped) / RefError. - hw is the hardware result for this program (four words or a str reason), or a callable lines -> that.""" - want = reference(lines) - problems, skips = [], [] - if "translator" in backends: - try: - problems.append(_diff(lines, want, translated(lines), "translated", True)) - except Skip as e: - skips.append(e) - if "hw" in backends: - got = hw(lines) if callable(hw) else hw - if isinstance(got, str): - skips.append(Skip(f"hardware: {got}")) - else: - problems.append(_diff(lines, want, got, "hardware", False)) - if skips and len(skips) == len(backends): - raise skips[0] - return "; ".join(p for p in problems if p) or None - - -def drop(body, i): - """body without line i; a branch that skipped over that line now skips one line fewer.""" - out = [] - for j, line in enumerate(body): - if j == i: - continue - br = branch_skip(line) - if br and j < i <= j + br[1]: - line = f"{br[0]} +{br[1] - 1}" - out.append(line) - return out - - -def shrink(lines, check_fn=check): - """Drop instructions (not seeds or the observation) while the program still mismatches.""" - n_seed = len(REGS) + lines[len(REGS)].startswith("s_mov_b32 m0,") # the seeds, and M0 when set - body = lines[n_seed:-5] - changed = True - while changed: - changed = False - for i in range(len(body)): - trial = lines[:n_seed] + drop(body, i) + lines[-5:] - try: - if check_fn(trial): - body = drop(body, i) - changed = True - break - except (Skip, RefError): - continue - return lines[:n_seed] + body + lines[-5:] - - -def hw_prepare(oracle, programs): - """Run every program on the hardware in batches. Returns per program the four words, or a str reason it was skipped.""" - from hw_oracle import asm - out = [None] * len(programs) - todo = [] - for i, lines in enumerate(programs): - why = asm.skip_reason(lines, oracle.arch) - if why: - out[i] = why - else: - todo.append(i) - for i, r in zip(todo, oracle.run([programs[i] for i in todo])): - out[i] = r - return out - - -def run_suite(programs, seed, max_ops, ops, backends=("translator",), oracle=None, branches=False): - counts = {"pass": 0, "mismatch": 0, "skip": {}} - failures = [] - rng = random.Random(seed) - progs = [generate(rng, rng.randrange(1, max_ops + 1), ops, branches) for _ in range(programs)] - hw_words = hw_prepare(oracle, progs) if "hw" in backends else [None] * programs - for i, lines in enumerate(progs): - try: - problem = check(lines, backends, hw_words[i]) - except Skip as e: - counts["skip"][str(e)] = counts["skip"].get(str(e), 0) + 1 - continue - if problem is None: - counts["pass"] += 1 - continue - counts["mismatch"] += 1 - failures.append((i, problem, lines)) - return counts, failures - - -def self_test(): - ok = check(["s_mov_b32 s4, 5", "s_mov_b32 s5, 7", "s_add_u32 s6, s4, s5", "s_cmp_eq_u32 s4, s4"] - + observe([4, 5, 6])) is None - caught = reference(["s_mov_b32 s4, 0xffffffff", "s_add_u32 s5, s4, 1"] + observe([4, 5, 6]))[3] == 1 - try: - translated(["s_rfe_b64 s[4:5]"] + observe([4, 5, 6])) - skipped = False - except Skip: - skipped = True - print(f"self-test: match {ok}, carry modelled {caught}, unsupported op skipped {skipped}") - return ok and caught and skipped - - -def main(argv=None): - ap = argparse.ArgumentParser(description="Scalar ALU / SCC differential fuzzing (FUZZ-4).") - ap.add_argument("--programs", type=int, default=300) - ap.add_argument("--seed", type=int, default=1) - ap.add_argument("--max-ops", type=int, default=6) - ap.add_argument("--ops", default=None, help="comma-separated opcodes (default: all)") - ap.add_argument("--list-ops", action="store_true") - ap.add_argument("--self-test", action="store_true") - ap.add_argument("--all-failures", action="store_true", help="print every failing program, not just the first") - ap.add_argument("--bfe-any", action="store_true", - help="also give s_bfe_* control words past offset + width = 32 (measured on gfx1150 and gfx1036: the field stops at bit 31)") - ap.add_argument("--inline64", action="store_true", - help="also use inline constants as 64-bit sources (the translator reads them as lane masks)") - ap.add_argument("--oracle", default="translator", - help="comma-separated comparison targets: translator (default), hw (natively on the AMD GPU; see " - "tools/hw_oracle/). 'hw' alone compares the hardware with the reference only") - ap.add_argument("--hw-arch", default=None, help="GPU architecture to assemble for (default: detected)") - ap.add_argument("--branches", action="store_true", - help="SCC in control flow: consumer chains and s_cbranch_scc0/1 forward over 1..3 instructions " - "after SCC producers (translator oracle only)") - a = ap.parse_args(argv) - if a.programs < 1 or a.max_ops < 1: - ap.error("--programs and --max-ops must be at least 1") - backends = tuple(dict.fromkeys(t.strip() for t in a.oracle.split(","))) - if not backends or any(t not in ("translator", "hw") for t in backends): - ap.error("--oracle takes translator, hw or translator,hw") - if a.branches and "hw" in backends: - ap.error("--branches runs against the translator only (the hardware kernels are straight-line)") - global INLINE64, BFE_ANY - INLINE64, BFE_ANY = a.inline64, a.bfe_any - if a.list_ops: - for name in sorted(OPS): - print(f"{name:20} {OPS[name][0]}") - return 0 - if a.self_test: - return 0 if self_test() else 1 - if a.ops is not None: - tokens = [t.strip() for t in a.ops.split(",")] - if not any(tokens) or any(not t for t in tokens): - ap.error("--ops must be a comma-separated list of opcodes") - ops = sorted(set(tokens)) - else: - ops = sorted(o for o in OPS if backends == ("hw",) or o not in LANE_MASK_OPS) - unknown = [o for o in ops if o not in OPS] - if unknown: - ap.error("unknown ops: " + ", ".join(unknown)) - oracle = None - if "hw" in backends: - from hw_oracle import runner - try: - oracle = runner.open_oracle(arch=a.hw_arch) - except runner.Unavailable as e: - print(f"hardware oracle unavailable: {e}") - return 77 - print(f"hardware oracle: {oracle.device}") - try: - counts, failures = run_suite(a.programs, a.seed, a.max_ops, ops, backends, oracle, a.branches) - skips = sum(counts["skip"].values()) - mode = "+".join(backends) + (", branches" if a.branches else "") - print(f"{a.programs} programs (seed {a.seed}, {mode}): {counts['pass']} pass, " - f"{counts['mismatch']} mismatch, {skips} skipped") - for reason, n in sorted(counts["skip"].items(), key=lambda kv: -kv[1]): - print(f" skip x{n}: {reason}") - - def check_fn(lines): - return check(lines, backends, (lambda l: oracle.run([l])[0]) if oracle else None) - for i, problem, lines in failures[: None if a.all_failures else 1]: - small = shrink(lines, check_fn) - print(f"MISMATCH program {i}: {check_fn(small) or problem}") - shown = [text for text, _ in listing(small)] if has_branches(small) else small - print("\n".join("\t" + line for line in shown)) - finally: - if oracle: - oracle.close() - if failures: - return 1 - if not counts["pass"]: # nothing was compared: every program was skipped - print("no program ran: every one was skipped") - return 2 - return 0 - - -if __name__ == "__main__": - try: # a redirected stdout is strict ANSI code page under -I; write '?' for what it cannot encode - sys.stdout.reconfigure(errors="replace") - except (AttributeError, ValueError, OSError): - pass - sys.exit(main()) diff --git a/tools/sampler_lod_probe.py b/tools/sampler_lod_probe.py deleted file mode 100644 index 23ec56e9a..000000000 --- a/tools/sampler_lod_probe.py +++ /dev/null @@ -1,248 +0,0 @@ -r"""SHADER-539: measure on an AMD GPU (tools/hw_oracle) which mip level image_sample_l and image_sample_lz read under the -S#'s MIN_LOD / MAX_LOD / LOD_BIAS / MIP_FILTER and the T#'s MIN_LOD and BASE_LEVEL. - - python -I tools/sampler_lod_probe.py # each row's level under both rules below (no GPU) - python -I tools/sampler_lod_probe.py --oracle hw # native AMD GPU, wave32 and wave64, compared with the rule - -docs/d3d12_vulkan.md ("vk_sampler_test") says the S# LOD fields apply to an explicit LOD as Vulkan's minLod, maxLod and -mipLodBias do, taken from radv and not measured on RDNA2, and that the T#'s MIN_LOD (ResourceMinLODClamp) is untested. -Here a raw kernel samples a linear 64x64 R32_SFLOAT texture with seven levels, through a point min/mag filter, at -the top-left texel. The texture memory is a ramp, every dword holding its own index, so each sample returns the -dword offset of the texel it read: the start of the level it came from. The level starts are not assumed; a -calibration row per level (image_sample_l at LOD n, no clamp) finds them, and every other row's result is named by -that table. - -Two rules are computed for every row: - - rdna2_level, the rule the hardware rows are checked against: the model the gfx1036 measurement fits (see its - docstring; an exact half level rounds up, and the T#'s MIN_LOD clamps the fractional LOD before that rounding); - - vulkan_level, for comparison: Vulkan's rule for the sampler and view the runtime makes of the same S# and T# - (runtime/src/gfx10_descriptors.h): nearest is ceil(lambda + 0.5) - 1, and VK_EXT_image_view_min_lod raises the - integer level to floor(minLod). Rows where it differs are marked "Vulkan reads n"; that is not a failure. -DIFFERS means the hardware disagrees with the RDNA2 model, not with Vulkan. -Standard library only; the texture is built here, no game files. - -Exit codes: 0 every row matches the RDNA2 model (not "the hardware equals Vulkan"), 1 a row differs, 2 harness -error, 77 no hardware oracle. -Usage: `python -I tools/sampler_lod_probe.py --help` lists the options. -""" -import argparse -import math -import os -import struct -import sys - -HERE = os.path.dirname(os.path.abspath(__file__)) -sys.path.insert(0, os.path.join(HERE, "hw_oracle")) - -W = 64 -LEVELS = 7 # 64x64 .. 1x1 -RAMP_DWORDS = 16384 # more than the chain needs under any 256-byte level alignment -CLAMP_LAST_TEXEL = 2 -U = V = 0.25 / W # inside texel (0, 0) at every level - - -# (name, instruction, LOD, S# (mip_filter, min_lod, max_lod, bias), T# (base_level, min_lod)) -def rows(): - plain = (1, 0.0, 15.0, 0.0) - out = [(f"calib_lod{n}", "l", float(n), plain, (0, 0.0)) for n in range(LEVELS)] - out += [ - ("lz", "lz", 0.0, plain, (0, 0.0)), - # S# MIN_LOD / MAX_LOD on an explicit LOD and on _lz - ("s_min2_l0", "l", 0.0, (1, 2.0, 15.0, 0.0), (0, 0.0)), - ("s_min2_lz", "lz", 0.0, (1, 2.0, 15.0, 0.0), (0, 0.0)), - ("s_max1_l4", "l", 4.0, (1, 0.0, 1.0, 0.0), (0, 0.0)), - ("s_max0_l3", "l", 3.0, (1, 0.0, 0.0, 0.0), (0, 0.0)), - # S# LOD_BIAS on an explicit LOD and on _lz - ("s_bias+2_l1", "l", 1.0, (1, 0.0, 15.0, 2.0), (0, 0.0)), - ("s_bias+2_lz", "lz", 0.0, (1, 0.0, 15.0, 2.0), (0, 0.0)), - ("s_bias-1_l3", "l", 3.0, (1, 0.0, 15.0, -1.0), (0, 0.0)), - ("s_bias+2_max3_l3", "l", 3.0, (1, 0.0, 3.0, 2.0), (0, 0.0)), # bias before the clamp - ("s_bias+0.5_l1", "l", 1.0, (1, 0.0, 15.0, 0.5), (0, 0.0)), # 1.5: the nearest-level rounding - # point mip filter rounding of a fractional LOD - ("l1.25", "l", 1.25, plain, (0, 0.0)), - ("l1.5", "l", 1.5, plain, (0, 0.0)), - ("l1.75", "l", 1.75, plain, (0, 0.0)), - # MIP_FILTER none: the base level whatever the LOD and clamp - ("mipnone_l3", "l", 3.0, (0, 0.0, 15.0, 0.0), (0, 0.0)), - ("mipnone_min2_l0", "l", 0.0, (0, 2.0, 15.0, 0.0), (0, 0.0)), - ("mipnone_t_min3_l0", "l", 0.0, (0, 0.0, 15.0, 0.0), (0, 3.0)), # the T#'s MIN_LOD still applies - ("mipnone_t_min2.25", "l", 0.0, (0, 0.0, 15.0, 0.0), (0, 2.25)), - ("mipnone_t_min2.5", "l", 0.0, (0, 0.0, 15.0, 0.0), (0, 2.5)), - ("mipnone_base1_tmin3", "l", 0.0, (0, 0.0, 15.0, 0.0), (1, 3.0)), - # T# MIN_LOD (ResourceMinLODClamp) - ("t_min3_l1", "l", 1.0, plain, (0, 3.0)), - ("t_min3_lz", "lz", 0.0, plain, (0, 3.0)), - ("t_min3_l5", "l", 5.0, plain, (0, 3.0)), # above the clamp: unchanged - ("t_min2.5_l0", "l", 0.0, plain, (0, 2.5)), # fractional clamp, point mip - ("t_min2.5_l2.6", "l", 2.6, plain, (0, 2.5)), - ("t_min2.25_l0", "l", 0.0, plain, (0, 2.25)), # ceil(MIN_LOD), or clamp then round? - ("t_min2.75_l0", "l", 0.0, plain, (0, 2.75)), - ("t_min2.25_lz", "lz", 0.0, plain, (0, 2.25)), - # more half-way points: is an exact .5 rounded up wherever it comes from? - ("l0.5", "l", 0.5, plain, (0, 0.0)), - ("l2.5", "l", 2.5, plain, (0, 0.0)), - ("s_min1.5_l0", "l", 0.0, (1, 1.5, 15.0, 0.0), (0, 0.0)), - ("s_max1.5_l4", "l", 4.0, (1, 0.0, 1.5, 0.0), (0, 0.0)), - ("l1.49", "l", 1.49, plain, (0, 0.0)), - # BASE_LEVEL: S# fields count from the view's base, the T# MIN_LOD from the resource's level 0 - ("base1_l0", "l", 0.0, plain, (1, 0.0)), - ("base1_s_min1_l0", "l", 0.0, (1, 1.0, 15.0, 0.0), (1, 0.0)), - ("base1_t_min2_l0", "l", 0.0, plain, (1, 2.0)), - ("base1_t_min2_lz", "lz", 0.0, plain, (1, 2.0)), - ] - return out - - -def vulkan_level(instr, lod, s, t): - """Vulkan's level for the sampler and view the runtime makes of this S# and T#: nearest is ceil(lambda + 0.5) - 1, - and VK_EXT_image_view_min_lod raises the integer level to floor(minLod).""" - mip_filter, s_min, s_max, bias = s - base, t_min = t - last = LEVELS - 1 - if mip_filter == 0: - level = base - else: - lam = (0.0 if instr == "lz" else lod) + bias - lam = min(max(lam, s_min), s_max) - d = max(0, math.ceil(lam + 0.5) - 1) - level = min(base + d, last) - return min(max(level, math.floor(t_min)), last) - - -def rdna2_level(instr, lod, s, t): - """The model the gfx1036 measurement fits: lambda = LOD (0 for _lz) + LOD_BIAS, clamped to the S#'s - [MIN_LOD, MAX_LOD]; with a point mip filter the T#'s MIN_LOD raises the still fractional LOD (counted from the - resource's level 0) and the level is floor(lambda + 0.5): an exact .5 goes up. MIP_FILTER none ignores the S#'s - LOD fields and reads the view's base level, raised to floor(T# MIN_LOD).""" - mip_filter, s_min, s_max, bias = s - base, t_min = t - last = LEVELS - 1 - if mip_filter == 0: - return min(max(base, math.floor(t_min)), last) - lam = (0.0 if instr == "lz" else lod) + bias - lam = base + min(max(lam, s_min), s_max) - lam = max(lam, t_min) - return min(max(math.floor(lam + 0.5), base), last) - - -rule_level = rdna2_level - - -def fixed(value, frac_bits, total_bits, signed=False): - v = round(value * (1 << frac_bits)) - return v & ((1 << total_bits) - 1) if signed else max(0, min(v, (1 << total_bits) - 1)) - - -def sampler_words(s): - """S# positions as check.py's ssharp_words (Mesa gfx10-rsrc.json): WORD0 CLAMP_X/Y/Z [8:0], WORD1 MIN_LOD [11:0] and - MAX_LOD [23:12] (4.8), WORD2 LOD_BIAS [13:0] (signed 5.8) and MIP_FILTER [27:26]. Point min/mag (0).""" - mip_filter, s_min, s_max, bias = s - clamp = CLAMP_LAST_TEXEL | CLAMP_LAST_TEXEL << 3 | CLAMP_LAST_TEXEL << 6 - return [clamp, fixed(s_min, 8, 12) | fixed(s_max, 8, 12) << 12, fixed(bias, 8, 14, True) | mip_filter << 26, 0] - - -def image_words(arch, t): - """A linear 2D R32_SFLOAT T# with LEVELS levels. Mip fields as runtime/src/gfx10_descriptors.h has them: WORD1 - MIN_LOD [19:8] (4.8), WORD3 BASE_LEVEL [15:12] and LAST_LEVEL [19:16], WORD5 MAX_MIP [7:4].""" - import tsharp - if tsharp.check_arch(arch) != "gfx10": - raise ValueError(f"the mip fields here are GFX10's; {arch} is not GFX10") - base, t_min = t - w = tsharp.image_words(arch, "R32_SFLOAT", W, W, 4) - w[1] |= fixed(t_min, 8, 12) << 8 - w[3] |= base << 12 | (LEVELS - 1) << 16 - w[5] |= (LEVELS - 1) << 4 - return w - - -def f32(x): - return struct.unpack("2}{extra:12} rule {want} {'ok' if ok else 'DIFFERS'}{note}") - print(f"{len(table) - bad}/{len(table)} rows match the rule; Vulkan's level differs on {vk_diff}") - return 1 if bad else 0 - - -if __name__ == "__main__": - try: # a redirected stdout is strict ANSI code page under -I; write '?' for what it cannot encode - sys.stdout.reconfigure(errors="replace") - except (AttributeError, ValueError, OSError): - pass - sys.exit(main()) diff --git a/tools/sampler_source_census.py b/tools/sampler_source_census.py deleted file mode 100644 index b7277c07d..000000000 --- a/tools/sampler_source_census.py +++ /dev/null @@ -1,624 +0,0 @@ -r"""Where does the S# of every sampling instruction come from? (SHADER-735, stdlib only) - -docs/d3d12_vulkan.md section 3.5 left open whether the console driver hands a shader its static samplers through -a fixed table of its own: a shader that expected one would read the S# from an address the layer never fills, and -the layer would have to emulate that table. This tool measures it over a disassembly folder. - -For every `image_sample*`, `image_gather4*` and `image_get_lod` it follows the four SGPRs of the sampler operand -back to where their values were made. The forward dataflow is the one of tools/heap_index_census.py (entry SGPRs, -constants, dwords of a scalar load, offsets) with what the sampler operands of the corpus needed on top: constants -built with `s_brev_b32`, `s_getpc_b64` as a code-relative address, SGPRs spilled to a VGPR and read back -(`v_mov_b32` / `v_readfirstlane_b32`, `v_writelane_b32` / `v_readlane_b32`), and joins that keep the sources of -every path instead of giving the value up. Each instruction gets one class: - - * user_sgprs every dword is a user-data SGPR at entry: the S# is root data itself; - * user_pointer every dword was loaded from memory (s_load_dword*, s_buffer_load_dword*) at an address that - starts from user data: a pointer in a user SGPR, or a pointer or V# that was itself loaded - through one. A descriptor table and a directly indexed sampler heap both look like this - (D3D-329: the heap base is a user SGPR too), so the class is also counted by offset (static - or run-time) and by the shader's DXBC `SFI0` sampler-heap bit; - * literal every dword is a constant built from immediates, the `literal_samplers` of - tools/shader_meta.py; the ones that take `s_brev_b32` or `s_not_b32` are counted apart; - * other_base some dword, on some path, is held in or loaded through something that is not user data: a - constant address, a system SGPR (above the stage's user count, or the NGG s3 in MS/GS) or a - code-relative address. This is what a driver sampler table would look like, so it wins over - every other class, and the form is counted; - * undetermined anything else, with the reason: a value the dataflow does not model, sources of different - classes on different paths, a pointer whose high word is not followed, an S# that comes back - from a VGPR a vector load wrote, or from a spill slot that one path into the instruction does - not save to (the reason then names the class of what the other paths saved). - -Most of the undetermined ones in the corpus have one cause: the compiler builds or saves the S# inside a region it -jumps over with `s_cbranch_execz` when no lane is active, and samples after the region, so the path that skips it -brings whatever the registers held. The census therefore analyses a shader with such an instruction a second time -without the taken edge of those branches (the region always runs, which is what the code does when a lane is -active) and reports, next to the classes above, what the undetermined instructions become. The first analysis -stays the one the classes and --expect-none use: the second trusts that nothing samples on the skipping path. - -The user count is COMPUTE_PGM_RSRC2's USER_SGPR for CS and the translator's 32 for the graphics stages, as in -tools/heap_index_census.py: no graphics count is measured yet, so "user" there means "an entry SGPR below s32". -A listing with data words inside its code range is re-anchored to the FSSM blob and cut to the reachable code the -way tools/rdna2spirv.py does it. - -What it does NOT show: - * `user pointer + constant` and `constant address + user index` are the same arithmetic. Instead of deciding, - the census reports the largest constant added on the way to the address of a user_pointer load and the - largest static offset of such a load. - * It sees the shaders: not what the driver writes at the addresses they read, and not which literal S# is a - root signature's static sampler. - * Lane masks are not modelled. A spill is a masked write (`v_mov_b32` writes the active lanes only); a restore - is taken to read what the last save on its path wrote. - -It reads the listings, the carve index (`/../index.json`, for the stage), the DXBC containers -(`/../.dxbc`, for SFI0) and the FSSM blobs (`/../fssm/.fssm`). It prints counts only, -no shader names or bytes. - -Usage: - python -I tools/sampler_source_census.py /shaders/dxbc/disasm [--json OUT] [--jobs N] [--limit N] - python -I tools/sampler_source_census.py /shaders/dxbc/disasm --expect-none other_base - (exit 1 if an instruction falls in a listed class) - -A missing folder, an unreadable carve index and an unwritable --json each give one ERROR line and exit 2. -""" -import argparse -import json -import os -import sys -from collections import Counter, defaultdict -from concurrent.futures import ProcessPoolExecutor - -sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) -import heap_index_census as hic # noqa: E402 -import pool_workers # noqa: E402 -import shader_ir # noqa: E402 -import shader_meta # noqa: E402 - -CLASSES = ("user_sgprs", "user_pointer", "literal", "other_base", "undetermined") -ENDS = ("s_endpgm", "s_setpc_b64") # no fall-through and no successor the listing names -SCALAR_LOADS = ("s_load_dword", "s_buffer_load_dword") -# Constants the compiler builds with one more instruction than heap_index_census.step folds. -UNARY = {"s_brev_b32": lambda v: int(f"{v:032b}"[::-1], 2), "s_not_b32": lambda v: ~v & 0xFFFFFFFF} -PHI_MAX = 8 # sources kept at a join before the value is given up -VGPR_READ_ONLY = ("exp", "buffer_store", "tbuffer_store", "global_store", "flat_store", "scratch_store", - "image_store", "ds_write", "v_cmp") # a[0] is a VGPR these read; every other one writes it -VGPR_LOADS = ("buffer_load", "tbuffer_load", "global_load", "flat_load", "scratch_load", "ds_read") -GAP, VLOAD, TOP = ("gap",), ("vload",), ("top",) # spill-slot contents that are not a saved SGPR (see dataflow) -NOT_USER = {"constant": "constant address", "system": "system SGPR", "code": "code-relative address"} - - -# ---- listing -> basic blocks -------------------------------------------------------------------------------- - -def anchored(path, info): - """The instructions of a listing with data words in its code range, at their true offsets in the FSSM blob and - without the unreachable ones (tools/rdna2spirv.py translate() does the same before it builds the blocks).""" - import rdna2spirv # only these listings need the translator's front end - try: - blob = rdna2spirv.native_blob(path, info["name"]) - except OSError: - raise hic.Skip("embedded data words, no FSSM blob") from None - pos = info["code_start"] - for ins in info["insns"]: - if not ins["enc"]: - raise hic.Skip("embedded data words, instruction without encoding") - enc = bytes.fromhex(ins["enc"]) - at, skipped = pos, 0 - while not rdna2spirv.same_encoding(blob[at:at + len(enc)], enc, ins["op"], len(ins["args"])): - at += 4 - skipped += 4 - if skipped > 4096 or at >= len(blob): - at = pos # a data word LLVM printed normalized: it sits where the decoder stood - ins["normalized"] = True - break - ins["pc"] = at - pos = at + len(enc) - try: - insns = rdna2spirv.reachable_code(rdna2spirv.fold_far_branches(info["insns"])) - except rdna2spirv.Unsupported as e: - raise hic.Skip(f"embedded data words, {e}") from None - if any(i.get("normalized") for i in insns): - raise hic.Skip("embedded data words, reachable instruction with normalized encoding") - return insns - - -def blocks_of(insns): - """Basic blocks and successor lists. Unlike heap_index_census.blocks_of it takes the explicit `target` of a - folded far branch and code that is not contiguous (data words between two reachable runs).""" - def next_pc(ins): - return ins["pc"] + len(ins["enc"]) // 2 - - def target(ins): - if "target" in ins: - return ins["target"] - imm = next((x for x in ins["args"] if x["k"] == "imm"), None) - if imm is None: - raise hic.Skip("branch without offset") - v = imm["v"] & 0xFFFF - return next_pc(ins) + 4 * (v - 0x10000 if v & 0x8000 else v) - - def is_branch(ins): - return shader_meta.base_op(ins["op"]) in hic.BRANCHES - - if any(is_branch(i) and not i.get("enc") for i in insns): - raise hic.Skip("branch without encoding") - pcs = {i["pc"] for i in insns} - leaders = {insns[0]["pc"]} - for prev, ins in zip(insns, insns[1:]): - if next_pc(prev) != ins["pc"]: - leaders.add(ins["pc"]) - for ins in insns: - if is_branch(ins): - leaders.add(target(ins)) - leaders.add(next_pc(ins)) - starts = sorted(p for p in leaders if p in pcs) - index = {p: n for n, p in enumerate(starts)} - if any(target(i) not in index for i in insns if is_branch(i)): - raise hic.Skip("branch target outside code") - blocks = [[] for _ in starts] - cur = -1 - for ins in insns: - cur = index.get(ins["pc"], cur) - blocks[cur].append(ins) - succ = [] - for n, blk in enumerate(blocks): - last = next((i for i in blk if is_branch(i) or shader_meta.base_op(i["op"]) in ENDS), None) - fall = [n + 1] if n + 1 < len(blocks) and next_pc(blk[-1]) == starts[n + 1] else [] - if last is None: - succ.append(fall) - elif not is_branch(last): - succ.append([]) - elif shader_meta.base_op(last["op"]) == "s_branch": - succ.append([index[target(last)]]) - else: - succ.append(list(dict.fromkeys([index[target(last)]] + fall))) - return blocks, succ - - -# ---- dataflow ----------------------------------------------------------------------------------------------- -# -# The state maps an SGPR number to a tag, as in heap_index_census.step, and adds: -# ("code", pc, word) the pair s_getpc_b64 writes: an address next to the code; -# ("const", v, op) a constant folded here from op (UNARY), which that step leaves unknown; -# ("off", t, False, k) the constant k of a static offset, so the largest one can be reported; -# ("phi", {tags}) a join whose paths bring different constants, loads or entry SGPRs; -# key ("v", n) the tag of an SGPR spilled whole to VGPR n (v_mov_b32 vN, sM); -# key ("lane", n, lane) the tag of an SGPR spilled to one lane of VGPR n (v_writelane_b32). -# A spill slot holds, besides a saved tag: nothing an SGPR was saved to (no key; GAP inside a phi), VLOAD when a -# vector memory load wrote the VGPR, TOP when a join gave it up. - -def _signed(v): - return v - (1 << 32) if v & 0x80000000 else v - - -def spill_lanes(insns): - """{vgpr: {lanes}} of every v_writelane_b32 with an immediate lane: the spill slots a VGPR write clears.""" - out = defaultdict(set) - for ins in insns: - a = ins["args"] - if shader_meta.base_op(ins["op"]) == "v_writelane_b32" and len(a) >= 3 and a[0]["k"] == "vgpr" \ - and a[2]["k"] == "imm": - out[a[0]["r"]].add(a[2]["v"]) - return out - - -def step(sym, ins, lanes=None): - """heap_index_census.step plus the tags above.""" - op = shader_meta.base_op(ins["op"]) - a = ins["args"] - lanes = lanes or {} - srcs = unary = None - if (op in hic.ADDS or op in shader_meta.LSHL_ADD_SHIFT) and len(a) >= 3 and a[0]["k"] == "sgpr": - srcs = (hic._src(sym, a[1]), hic._src(sym, a[2])) - elif op == "s_addk_i32" and len(a) >= 2 and a[0]["k"] == "sgpr": - v = a[1]["v"] & 0xFFFF - srcs = (sym.get(a[0]["r"]), ("const", (v - 0x10000 if v & 0x8000 else v) & 0xFFFFFFFF)) - elif op in UNARY and len(a) >= 2 and a[0]["k"] == "sgpr" and a[0].get("n", 1) == 1: - unary = hic._src(sym, a[1]) - elif op == "v_readfirstlane_b32" and len(a) >= 2 and a[1]["k"] == "vgpr": - unary = sym.get(("v", a[1]["r"])) - elif op == "v_readlane_b32" and len(a) >= 3 and a[1]["k"] == "vgpr" and a[2]["k"] == "imm": - unary = sym.get(("lane", a[1]["r"], a[2]["v"])) - hic.step(sym, ins) - if not a: - return - if a[0]["k"] == "vgpr": - if op.startswith(VGPR_READ_ONLY): - return - written = [x for x in (a if op == "v_swap_b32" else a[:1]) if x["k"] == "vgpr"] - lane = a[2]["v"] if op == "v_writelane_b32" and len(a) >= 3 and a[2]["k"] == "imm" else None - moved = None - if op in ("v_mov_b32", "v_writelane_b32") and len(a) >= 2 and a[0].get("n", 1) == 1: - moved = sym.get(("v", a[1]["r"])) if a[1]["k"] == "vgpr" else hic._src(sym, a[1]) - for x in written: - for r in range(x["r"], x["r"] + x.get("n", 1)): - sym.pop(("v", r), None) - if op.startswith(VGPR_LOADS): - sym[("v", r)] = VLOAD - for one in (lane,) if lane is not None else lanes.get(r, ()): # v_writelane leaves the others - sym.pop(("lane", r, one), None) - if moved is not None and (op == "v_mov_b32" or lane is not None): - sym[("v", a[0]["r"]) if op == "v_mov_b32" else ("lane", a[0]["r"], lane)] = moved - elif a[0]["k"] != "sgpr": - return - elif op in UNARY and unary is not None and unary[0] == "const": - sym[a[0]["r"]] = ("const", UNARY[op](unary[1]), op) - elif op.startswith(("v_readfirstlane", "v_readlane")) and unary not in (None, TOP) and a[0].get("n", 1) == 1: - sym[a[0]["r"]] = unary - elif op == "s_getpc_b64" and a[0].get("n") == 2: - sym[a[0]["r"]], sym[a[0]["r"] + 1] = ("code", ins["pc"], 0), ("code", ins["pc"], 1) - elif srcs is not None: - d = a[0]["r"] - consts = [t[1] for t in srcs if t is not None and t[0] == "const"] - code = [t for t in srcs if hic.root(t)[0] is not None and hic.root(t)[0][0] == "code"] - if d not in sym and len(code) == 1 and not (srcs[1] is code[0] and op.startswith(("s_sub", "s_subb"))): - sym[d] = ("off", code[0], not consts) - new = sym.get(d) - if consts and new is not None and new[0] == "off" and not new[2]: - shifted = srcs[0] is not None and srcs[0][0] == "const" # s_lshlK_add_u32: the index is shifted - sym[d] = new[:3] + (consts[0] << shader_meta.LSHL_ADD_SHIFT.get(op, 0) if shifted else consts[0],) - - -def join(x, y): - """The tag of a value that is x on one path and y on another, or None when that is not worth keeping.""" - alts = (x[1] if x[0] == "phi" else frozenset((x,))) | (y[1] if y[0] == "phi" else frozenset((y,))) - if len(alts) > PHI_MAX or any(t[0] not in ("const", "ld", "in", "gap", "vload") for t in alts): - return None - return ("phi", alts) - - -def merge(old, new): - """The state at a join: `old` is what the block was entered with so far, `new` what one more path brings. - An SGPR whose value is given up stays unknown. A spill slot one path did not write is GAP there, so the slot - keeps what the other paths saved and the gap; given up, it is TOP.""" - out = {} - for k, v in old.items(): - w = new.get(k, GAP if isinstance(k, tuple) else None) - if w is not None: - w = v if w == v else join(v, w) - if w is not None or isinstance(k, tuple): - out[k] = w or TOP - for k, w in new.items(): - if isinstance(k, tuple) and k not in old: - out[k] = join(GAP, w) or TOP - return out - - -def analyse(insns, stage, user_count, follow_skips=True): - """{code offset: (class, detail)} of the reachable sampling instructions, in code order, and the shader's - statistics. detail: the offset kind for user_pointer ("static" / "dynamic"), the form for other_base, the - reason for undetermined, the instruction a literal needed folded (or None). - follow_skips=False leaves out the taken edge of every s_cbranch_execz that also falls through: the branch - skips a region when no lane is active, so without it the region always runs (see the module docstring).""" - blocks, succ = blocks_of(insns) - if not follow_skips: - succ = [s[1:] if len(s) == 2 and shader_meta.base_op(blk[-1]["op"]) == "s_cbranch_execz" else s - for blk, s in zip(blocks, succ)] - lanes = spill_lanes(insns) - system = set(hic.SYSTEM_SGPRS.get(stage, ())) - entry = [None] * len(blocks) - entry[0] = {r: ("in", r) for r in range(106)} - work = [0] - while work: - b = work.pop() - sym = dict(entry[b]) - for ins in blocks[b]: - if shader_meta.base_op(ins["op"]) in ENDS: - break - step(sym, ins, lanes) - for s in succ[b]: - merged = sym if entry[s] is None else merge(entry[s], sym) - if merged != entry[s]: - entry[s] = dict(merged) - work.append(s) - - stats = {"max_pointer_constant": 0, "max_static_offset": 0, "unreachable": 0} - loads, uses = {}, {} # pc -> load record; pc -> sampler dword tags - for b, blk in enumerate(blocks): - sym = dict(entry[b]) if entry[b] is not None else None - for ins in blk: - op = shader_meta.base_op(ins["op"]) - a = ins["args"] - if sym is None: # a block nothing reaches, or the rest of one after s_endpgm - stats["unreachable"] += op.startswith(shader_meta.SAMPLER_IMAGE_OPS) and len(a) >= 4 - continue - if op in ENDS: - sym = None - continue - if op.startswith(SCALAR_LOADS) and len(a) >= 2: - slots = shader_meta._sgpr_slots(a[1], 2 if op.startswith("s_load_dword") else 4) - loads[ins["pc"]] = { - "base": None if slots is None else [shader_meta._slot_tag(sym, s) for s in slots], - "offset": hic._src(sym, a[2]) if len(a) >= 3 else ("const", 0), - } - elif op.startswith(shader_meta.SAMPLER_IMAGE_OPS) and len(a) >= 4: - slots = shader_meta._sgpr_slots(a[3], 4, exact=False) - uses[ins["pc"]] = None if slots is None else [shader_meta._slot_tag(sym, s) for s in slots] - step(sym, ins, lanes) - - # What load_source found for a load, by code offset. A descriptor's dwords all come from one load, and a chain - # of loads asks for the first one from every dword of every later one, so each load is worked out once. Only - # an answer that ran into no cycle is kept: that one does not depend on where the question started. - found_load, cycles = {}, [0] - - def source(tag, seen=()): - """(where the address or value `tag` starts: "user" | "system" | "constant" | "code" | None, - whether an offset on the way is run-time, the largest constant offset on the way).""" - if tag is not None and tag[0] == "phi": - got = [source(t, seen) for t in tag[1]] - where = {g[0] for g in got} - return (where.pop() if len(where) == 1 else None), any(g[1] for g in got), max(g[2] for g in got) - dyn, k = False, 0 - while tag is not None and tag[0] == "off": - dyn = dyn or tag[2] - k = max(k, abs(_signed(tag[3] & 0xFFFFFFFF)) if len(tag) > 3 else 0) - tag = tag[1] - if tag is None: - return None, dyn, k - if tag[0] == "in": - return ("system" if tag[1] in system or tag[1] >= user_count else "user"), dyn, k - if tag[0] == "const": - return "constant", dyn, k - if tag[0] == "code": - return "code", dyn, k - if tag[0] != "ld" or tag[1] not in loads: - return None, dyn, k - if tag[1] in seen: # a load whose address depends on the load itself - cycles[0] += 1 - return None, dyn, k - # ("ld", pc, i): a pointer or V# that was itself loaded - where, _, k2, _ = found_load.get(tag[1]) or load_source(tag[1], seen) - return where, dyn, max(k, k2) - - def load_source(pc, seen=()): - """source() of the address the scalar load at pc reads, with the load's own offset counted as well - (run-time or not, and the constants in it), and the reason when the start is unknown. `seen` holds the - loads this one is being asked for.""" - if pc in found_load: - return found_load[pc] - before = cycles[0] - found = one_load_source(loads[pc], seen + (pc,)) - if cycles[0] == before: - found_load[pc] = found - return found - - def one_load_source(ld, seen): - base = ld["base"] - if base is None: - return None, False, 0, "load base not an SGPR range" - if len(base) == 4: # s_buffer_load: the V# decides - got = {source(t, seen) for t in base} - where, dyn, k = next(iter(got)) if len(got) == 1 else (None, False, 0) - reason = "V# from different sources" - else: - where, dyn, k = source(base[0], seen) - reason = "load base not followed" - if where == "user" and base[1] != ("const", 0) and source(base[1], seen)[0] != "user": - where, reason = None, "pointer high word not followed" - off = ld["offset"] - static = off is not None and off[0] == "const" and not dyn - return where, not static, k if static or off is None else max(k, source(off, seen)[2]), reason - - by_load = {} - - def one_load(pc): - """The class of a dword the load at pc brought.""" - if pc not in by_load: - ld = loads.get(pc) - where, dyn, k, reason = load_source(pc) if ld else (None, False, 0, "load not seen") - if where is None: - by_load[pc] = "undetermined", reason - elif where != "user": - by_load[pc] = "other_base", NOT_USER[where] - else: - stats["max_pointer_constant"] = max(stats["max_pointer_constant"], k) - if not dyn: - stats["max_static_offset"] = max(stats["max_static_offset"], ld["offset"][1]) - by_load[pc] = "user_pointer", "dynamic" if dyn else "static" - return by_load[pc] - - def one_dword(tag): - if tag[0] == "const": - return "literal", f"with {tag[2]}" if len(tag) > 2 else None - if tag[0] == "in": - return ("user_sgprs", None) if source(tag)[0] == "user" else ("other_base", "system SGPR") - return one_load(tag[1]) - - def classify(tags): - """The class of a sampler operand from the tags of its four dwords: the one class every source of every - dword has, other_base as soon as one source is, undetermined otherwise.""" - if tags is None: - return "undetermined", "sampler operand not an SGPR range" - known = [t for t in tags if t is not None and t[0] in ("phi", "const", "in", "ld", "vload")] - alts = [t[1] if t[0] == "phi" else frozenset((t,)) for t in known] - found = {one_dword(t) for a in alts for t in a if t not in (GAP, VLOAD)} - classes = {c for c, _ in found} - if "other_base" in classes: # one dword, on one path, from a fixed table is enough - return sorted(f for f in found if f[0] == "other_base")[0] - if len(known) < len(tags): - return "undetermined", "a dword the dataflow does not follow" - if "undetermined" in classes: - return sorted(f for f in found if f[0] == "undetermined")[0] - if any(a <= {GAP, VLOAD} for a in alts): - return "undetermined", "restored from a VGPR a vector load wrote" - if len(classes) > 1: - return "undetermined", "sources of different classes: " + "+".join(sorted(classes)) - cls = classes.pop() - slot = {t for a in alts for t in a} & {GAP, VLOAD} - if slot: - how = "fills with a vector load" if VLOAD in slot else "does not save to" - return "undetermined", f"spill slot a path {how} ({cls} where saved)" - details = sorted({d for _, d in found if d}) - return cls, ("dynamic" if "dynamic" in details else "/".join(details)) if details else None - - return {pc: classify(tags) for pc, tags in uses.items()}, stats - - -# ---- census ------------------------------------------------------------------------------------------------- - -def read_shader(job): - """One listing -> {"stage", "heap", "skip"}, plus {"uses": [(class, detail)], "stats", "straight"} when it - was analysed. "straight" counts, per class, the instructions that are undetermined with every edge followed - and get that class when the s_cbranch_execz skips are left out.""" - disasm_dir, name, stage = job - sfi0 = hic.sfi0_class(disasm_dir, name) - row = {"stage": stage, "heap": None if sfi0 is None else "smp" in sfi0, "skip": None} - if stage is None: - row["skip"] = "not in the carve index" - return row - path = os.path.join(disasm_dir, name + ".s") - info = shader_ir.parse_file(path) - if not info["insns"]: - row["skip"] = "no instructions" - return row - user = hic.USER_SGPRS - if stage == "cs": - user = hic.cs_user_count(disasm_dir, name) - if user is None: - row["skip"] = "no FSSM header" - return row - try: - insns = anchored(path, info) if info["invalid"] else info["insns"] - uses, row["stats"] = analyse(insns, stage, user) - row["uses"], row["straight"] = list(uses.values()), {} - if any(c == "undetermined" for c, _ in row["uses"]): - straight = analyse(insns, stage, user, follow_skips=False)[0] - row["straight"] = dict(Counter(straight.get(pc, ("not reached",))[0] for pc, (c, _) in uses.items() - if c == "undetermined")) - except hic.Skip as e: - row["skip"] = str(e) - row["sampling"] = sum(1 for i in info["insns"] if len(i["args"]) >= 4 and - shader_meta.base_op(i["op"]).startswith(shader_meta.SAMPLER_IMAGE_OPS)) - return row - - -def summarise(rows): - """The census from read_shader rows: per stage, instructions and shaders per class and per detail.""" - def counts(): - return {"instructions": 0, "shaders": 0} - - stages = defaultdict(lambda: { - "shaders": 0, "shaders_sampling": 0, "shaders_without_sfi0": 0, "instructions": 0, - "unreachable_instructions": 0, "undetermined_without_skips": Counter(), - "classes": {c: {**counts(), "in_sampler_heap_shaders": 0} for c in CLASSES}, - "detail": defaultdict(lambda: defaultdict(counts))}) - skipped, skipped_sampling = Counter(), Counter() - limits = {"max_pointer_constant": 0, "max_static_offset": 0} - n = 0 - for row in rows: - n += 1 - if row["skip"]: - skipped[row["skip"]] += 1 - skipped_sampling[row["skip"]] += row.get("sampling", 0) - continue - st = stages[row["stage"]] - st["shaders"] += 1 - st["shaders_sampling"] += bool(row["uses"]) - st["shaders_without_sfi0"] += row["heap"] is None - st["instructions"] += len(row["uses"]) - st["unreachable_instructions"] += row["stats"]["unreachable"] - st["undetermined_without_skips"].update(row["straight"]) - for (cls, detail), k in Counter(row["uses"]).items(): - st["classes"][cls]["instructions"] += k - st["classes"][cls]["in_sampler_heap_shaders"] += k * bool(row["heap"]) - if detail: - st["detail"][cls][detail]["instructions"] += k - st["detail"][cls][detail]["shaders"] += 1 - for cls in {c for c, _ in row["uses"]}: - st["classes"][cls]["shaders"] += 1 - if row["uses"]: - for k in limits: - limits[k] = max(limits[k], row["stats"][k]) - total = {c: sum(st["classes"][c]["instructions"] for st in stages.values()) for c in CLASSES} - return { - "shaders_read": n, - "skipped": dict(sorted(skipped.items())), - "skipped_sampling_instructions": {k: v for k, v in sorted(skipped_sampling.items()) if v}, - "stages": {s: {**st, "detail": {c: dict(sorted(d.items())) for c, d in sorted(st["detail"].items())}, - "undetermined_without_skips": dict(sorted(st["undetermined_without_skips"].items()))} - for s, st in sorted(stages.items())}, - "total": {"instructions": sum(total.values()), "classes": total, **limits}, - } - - -def census(disasm_dir, limit=None, jobs=1, stages=None): - if stages is None: - stages = hic.stage_index(disasm_dir) - names = sorted(n[:-2] for n in os.listdir(disasm_dir) if n.endswith(".s")) - if limit: - names = names[:limit] - work = [(disasm_dir, name, stages.get(name)) for name in names] - if jobs > 1: - with ProcessPoolExecutor(pool_workers.process_workers(jobs)) as pool: - return summarise(pool.map(read_shader, work, chunksize=64)) - return summarise(map(read_shader, work)) - - -def print_report(out): - print(f"shaders read: {out['shaders_read']}; skipped: {out['skipped'] or 'none'}" - + (f" (sampling instructions in them: {out['skipped_sampling_instructions']})" - if out["skipped_sampling_instructions"] else "")) - print(f"{'stage':<6}{'shaders':>8}{'sampling':>9}{'instr.':>8}" + "".join(f"{c:>14}" for c in CLASSES)) - for stage, st in out["stages"].items(): - print(f"{stage:<6}{st['shaders']:>8}{st['shaders_sampling']:>9}{st['instructions']:>8}" - + "".join(f"{st['classes'][c]['instructions']:>14}" for c in CLASSES)) - t = out["total"] - print(f"{'all':<6}{sum(s['shaders'] for s in out['stages'].values()):>8}" - f"{sum(s['shaders_sampling'] for s in out['stages'].values()):>9}{t['instructions']:>8}" - + "".join(f"{t['classes'][c]:>14}" for c in CLASSES)) - print("instructions in shaders whose SFI0 sets the sampler-heap bit:") - for stage, st in out["stages"].items(): - if st["instructions"]: - print(f"{stage:<6}{'':>25}" + "".join(f"{st['classes'][c]['in_sampler_heap_shaders']:>14}" for c in CLASSES) - + (f" ({st['shaders_without_sfi0']} shaders without SFI0)" if st["shaders_without_sfi0"] else "")) - for stage, st in out["stages"].items(): - for cls, detail in st["detail"].items(): - print(f" {stage} {cls}: " - + "; ".join(f"{k}: {v['instructions']} in {v['shaders']} shaders" for k, v in detail.items())) - if st["undetermined_without_skips"]: - print(f" {stage} undetermined, with the s_cbranch_execz skips left out: " - + ", ".join(f"{k} {v}" for k, v in st["undetermined_without_skips"].items())) - if st["unreachable_instructions"]: - print(f" {stage}: {st['unreachable_instructions']} sampling instructions in unreachable code, not counted") - print(f"user_pointer: largest static S# load offset {t['max_static_offset']:#x}, largest constant added to the " - f"pointer {t['max_pointer_constant']:#x}") - - -def main(argv=None): - ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) - ap.add_argument("disasm", help="/shaders/dxbc/disasm") - ap.add_argument("--json", help="write the full census here") - ap.add_argument("--jobs", type=shader_ir.positive_int, default=1, help="worker processes (default 1)") - ap.add_argument("--limit", type=shader_ir.positive_int, help="only the first N listings (sorted by name)") - ap.add_argument("--expect-none", nargs="*", choices=CLASSES, default=[], metavar="CLASS", - help="fail if an instruction falls in one of these classes: " + ", ".join(CLASSES)) - args = ap.parse_args(argv) - if not os.path.isdir(args.disasm): - print(f"ERROR: {args.disasm} is not a folder", file=sys.stderr) - return 2 - try: - stages = hic.stage_index(args.disasm) - except (OSError, ValueError, KeyError, TypeError) as e: - print(f"ERROR: cannot read the carve index next to {args.disasm}: {e}", file=sys.stderr) - return 2 - out = census(args.disasm, args.limit, args.jobs, stages) - print_report(out) - if args.json: - try: - os.makedirs(os.path.dirname(os.path.abspath(args.json)), exist_ok=True) - with open(args.json, "w", encoding="utf-8", newline="\n") as f: - json.dump(out, f, indent=1, sort_keys=True) - f.write("\n") - except OSError as e: - print(f"ERROR: cannot write {args.json}: {e}", file=sys.stderr) - return 2 - bad = [f"{c}: {out['total']['classes'][c]} instructions" for c in args.expect_none if out["total"]["classes"][c]] - for b in bad: - print("MISMATCH", b, file=sys.stderr) - return 1 if bad else 0 - - -if __name__ == "__main__": - try: # a redirected stdout is strict ANSI code page under -I; write '?' for what it cannot encode - sys.stdout.reconfigure(errors="replace") - except (AttributeError, ValueError, OSError): - pass - sys.exit(main()) diff --git a/tools/sandbox.py b/tools/sandbox.py deleted file mode 100644 index 7c46274ee..000000000 --- a/tools/sandbox.py +++ /dev/null @@ -1,174 +0,0 @@ -#!/usr/bin/env python3 -"""Real-shader sandbox: walk, fly or drive through placed props drawn by the game's own translated shaders. - - python -I tools/sandbox.py --work --entities --models --textures \ - [--center X Y] [--radius M] [--max-props N] (--window | --check) - -It packs the props around --center with tools/sandbox_scene.py, picks a translated VS/PS pair from -/shaders/spirv/index.json and runs runtime/build/vk_sandbox. The pair is chosen by what the shaders read, -not by name (the material -> program table is in the executable, #2519): a vertex shader with POSITION, NORMAL -and TEXCOORD inputs, user SGPR 8 as its only user data and no bindings, whose listing loads three descriptors from -s[8:9] at 0x0/0x40/0x60, a world translation at 0x30 and a 4x4 at 0x160; and a pixel shader with TEXCOORD and -COLOR inputs that loads one T# from s[8:9] + 0x20 and samples it once. vk_sandbox fills that table (see its -header). --check renders one frame headless and prints only counts: exit 0 when the frame is covered and, with -textures, shows texture detail; 77 when the package, the pair or a GPU is missing. Standard library only. -Usage: `python -I tools/sandbox.py --help` lists the options. -""" -import argparse -import json -import os -import re -import subprocess -import sys -import tempfile - -HERE = os.path.dirname(os.path.abspath(__file__)) -sys.path.insert(0, HERE) -import sandbox_scene # noqa: E402 - -VS_LAYOUT = (r"s_load_dwordx4 s\[\d+:\d+\], s\[8:9\], (?:null|0)\b", r"s_load_dwordx4 s\[\d+:\d+\], s\[8:9\], 0x40\b", - r"s_load_dwordx4 s\[\d+:\d+\], s\[8:9\], 0x60\b", r"s_buffer_load_dwordx16 s\[\d+:\d+\], s\[\d+:\d+\], 0x160\b", - r"s_buffer_load_dwordx4 s\[\d+:\d+\], s\[\d+:\d+\], 0x30\b") -SKY = bytes((140, 173, 217)) # vk_sandbox's clear colour (0.55, 0.68, 0.85) in 8 bits -PS_LAYOUT = (r"s_load_dwordx8 s\[\d+:\d+\], s\[8:9\], 0x20\b", r"\bimage_sample\b", r"\bexp mrt0\b") - - -def _signature(entry): - return [(e.get("semantic"), e.get("semantic_index"), e.get("mask")) for e in entry.get("input_signature") or []] - - -def _listing_matches(disasm_dir, name, patterns): - try: - with open(os.path.join(disasm_dir, name + ".s"), encoding="utf-8", errors="replace") as f: - text = f.read() - except OSError: - return False - return text.count("image_sample") <= 1 and all(re.search(p, text) for p in patterns) - - -def pick_pair(shaders_dir): - """(vs.spv, ps.spv) paths of the first matching pair in name order, or None.""" - spirv = os.path.join(shaders_dir, "spirv") - disasm = os.path.join(shaders_dir, "dxbc", "disasm") - try: - with open(os.path.join(spirv, "index.json"), encoding="utf-8-sig") as f: - index = json.load(f) - except (OSError, ValueError): - return None - ptr8 = {"kind": "ptr32_lo", "sgpr": 8} - vs = ps = None - for name in sorted(index): - e = index[name] - if not os.path.isfile(os.path.join(spirv, name + ".spv")): - continue - if (vs is None and e.get("stage") == "vs" and not e.get("bindings") - and e.get("user_sgpr_reads") == [ptr8] - and _signature(e) == [("POSITION", 0, 7), ("NORMAL", 0, 7), ("TEXCOORD", 0, 3)] - and _listing_matches(disasm, name, VS_LAYOUT)): - vs = name - elif (ps is None and e.get("stage") == "ps" and e.get("bindings") == [0, 1, 2] - and ptr8 in (e.get("user_sgpr_reads") or []) - and [s[0] for s in _signature(e)] == ["SV_Position", "TEXCOORD", "COLOR"] - and _listing_matches(disasm, name, PS_LAYOUT)): - ps = name - if vs and ps: - return os.path.join(spirv, vs + ".spv"), os.path.join(spirv, ps + ".spv") - return None - - -def find_tool(build): - for name in ("vk_sandbox.exe", "vk_sandbox"): - path = os.path.join(build, name) - if os.path.isfile(path): - return path - return None - - -def read_ppm(path): - with open(path, "rb") as f: - data = f.read() - head = data.split(b"\n", 3) - w, h = (int(v) for v in head[1].split()) - return w, h, head[3] - - -def check_frame(path, textured): - """(ok, message) from the rendered frame: coverage and, with textures, colour variety.""" - w, h, px = read_ppm(path) - sky = SKY - covered, colours = 0, set() - for i in range(0, len(px), 3): - p = px[i:i + 3] - if abs(p[0] - sky[0]) > 1 or abs(p[1] - sky[1]) > 1 or abs(p[2] - sky[2]) > 1: - covered += 1 - colours.add(p) - ok = covered >= w * h // 100 and (not textured or len(colours) >= 256) - return ok, f"{covered} of {w * h} pixels covered, {len(colours)} distinct colours" - - -def main(argv=None): - ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) - ap.add_argument("--work", required=True, help="make_game.py work folder (holds shaders/spirv and shaders/dxbc)") - ap.add_argument("--entities", required=True) - ap.add_argument("--models", required=True) - ap.add_argument("--textures", action="append", default=[]) - ap.add_argument("--center", type=float, nargs=2, metavar=("X", "Y")) - ap.add_argument("--radius", type=float, default=150.0) - ap.add_argument("--max-props", type=int, default=400) - ap.add_argument("--build", default=os.path.join(HERE, "..", "runtime", "build")) - ap.add_argument("--scene", help="scene file to write (default: a temporary file)") - mode = ap.add_mutually_exclusive_group(required=True) - mode.add_argument("--window", action="store_true") - mode.add_argument("--check", action="store_true") - a = ap.parse_args(argv) - - tool = find_tool(a.build) - pair = pick_pair(os.path.join(a.work, "shaders")) - if not tool or not pair or not os.path.isfile(a.entities): - print("unsupported: " + ("vk_sandbox is not built" if not tool else - "no matching translated shader pair" if not pair else "no entities file")) - return 77 - tmp = frame = None - scene = a.scene - if not scene: - fd, scene = tempfile.mkstemp(suffix=".bin") - os.close(fd) - tmp = scene - try: - try: - stats = sandbox_scene.build(argparse.Namespace(entities=a.entities, models=a.models, textures=a.textures, - center=a.center, radius=a.radius, max_props=a.max_props, - tex_size=256, out=scene)) - except SystemExit as e: # build() exits when no entity resolves to an exported model - print(f"unsupported: {e}") - return 77 - print(f"scene: {stats['placed']} props, {stats['draws']} draws, {stats['textures']} textures, " - f"{stats['textured_draws']} textured draws") - if stats["draws"] == 0: - print("unsupported: no prop near the centre resolves to an exported model") - return 77 - x, y, z = stats["center"] - cam = [str(x - 40), str(y - 40), str(z + 25), "45", "-20"] - if a.window: - return subprocess.call([tool, scene, *pair, "--window", "--cam", *cam]) - frame = scene + ".ppm" - r = subprocess.run([tool, scene, *pair, "--out", frame, "--size", "640", "360", "--cam", *cam], - capture_output=True, text=True) - if r.returncode: - print((r.stdout + r.stderr).strip().splitlines()[-1] if (r.stdout + r.stderr).strip() else "vk_sandbox failed") - return r.returncode - ok, msg = check_frame(frame, stats["textured_draws"] > 0) - print(("PASS: " if ok else "FAIL: ") + msg) - return 0 if ok else 1 - finally: - for path in (tmp, frame): - if path and os.path.exists(path): - os.remove(path) - - -if __name__ == "__main__": - try: # a redirected stdout is strict ANSI code page under -I; write '?' for what it cannot encode - sys.stdout.reconfigure(errors="replace") - except (AttributeError, ValueError, OSError): - pass - sys.exit(main()) diff --git a/tools/sandbox_scene.py b/tools/sandbox_scene.py deleted file mode 100644 index 6e5941f3c..000000000 --- a/tools/sandbox_scene.py +++ /dev/null @@ -1,208 +0,0 @@ -#!/usr/bin/env python3 -"""Pack the placed props around one spot into a scene file for runtime/test/vk_sandbox. - -Reads the same inputs as ``world_build.py --placements`` (``world_index.py --entities-out`` rows, the -``rpf9dump models`` manifests and the ``rpf9dump ttpf`` texture manifests), keeps the entities within ---radius metres of --center (RAGE world x y, Z-up), and writes one little-endian file: - - "LSB1", u32 version 1, u32 textures, u32 meshes, u32 draws, f32 center[3] - textures: u32 w, u32 h, w*h RGBA8 (the material's DiffuseTex, mip 0 box-scaled to --tex-size) - meshes: u32 vertex count, u32 index count, vertices (f32 pos[3], f32 normal[3], f32 uv[2]), u32 indices - draws: u32 mesh, i32 texture (-1: none), f32 rows[4][3] - -Positions stay in model space; a draw's rows are the entity's world transform as three basis rows plus the -translation, world = x*row0 + y*row1 + z*row2 + row3 (RAGE Z-up). The file holds decoded game data, so it -stays in the user's work folder. Standard library only. -Usage: `python -I tools/sandbox_scene.py --help` lists the options. -""" -import argparse -import math -import os -import struct -import sys - -sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) -import dds_png # noqa: E402 -import glb_writer # noqa: E402 -import world_build # noqa: E402 - -DIFFUSE_TEX = "C8E8C282" # joaat("DiffuseTex"), the albedo Param of a material texture reference -# Two-layer blend materials have no DiffuseTex; their first layer's albedo sits in this slot (name not known yet; -# beside it are the second layer's albedo, two normal maps, packed material maps and the blend mask). -LAYER0_ALBEDO = "346394EA" - - -def select_rows(rows, center, radius, limit): - """Rows within radius of center (x, y), nearest first. A limit of None keeps every match.""" - cx, cy = center - near = [] - for row in rows: - dx, dy = row["_pos"][0] - cx, row["_pos"][1] - cy - d = math.hypot(dx, dy) - if d <= radius: - near.append(row) - near.sort(key=lambda row: math.hypot(row["_pos"][0] - cx, row["_pos"][1] - cy)) - return near if limit is None or limit >= len(near) else near[:limit] - - -def draw_rows(rotation, scale_xy, scale_z, position): - """The VS's world rows (basis vectors then translation) for one entity.""" - m, _, _ = world_build.entity_transform(rotation, scale_xy, scale_z) - rows = [[m[i][j] for i in range(3)] for j in range(3)] # column j of M is the image of model axis j - rows.append([float(v) for v in position]) - return rows - - -def mesh_bytes(prim): - pos, nrm, uvs, idx = prim["positions"], prim.get("normals") or [], prim.get("uvs") or [], prim["indices"] - out = bytearray(struct.pack(" 0 else 0 - picked = select_rows(rows, args.center, args.radius, candidate_limit) - - textures, tex_ids = [], {} - meshes, mesh_ids = [], {} - draws = [] - stats = {"entities": len(picked), "placed": 0, "unresolved": 0, "textured_draws": 0, "z": []} - for row in picked: - model, _ = world_build.resolve_placement(index, row["_arch"], row.get("key")) - if model is None: - stats["unresolved"] += 1 - continue - models_dir, item = model - obj = os.path.join(models_dir, item.get("File") or "") - key = (os.path.normcase(obj), id(item)) # archetypes sharing an OBJ can differ in materials - if key not in mesh_ids: - try: - prims = glb_writer.parse_obj(obj, is_path=True, up_axis="y") - except (OSError, glb_writer.GlbError, ValueError): - prims = [] - tex_map = world_build.resolve_model_textures(models_dir, item, ttpf, LAYER0_ALBEDO) - tex_map.update(world_build.resolve_model_textures(models_dir, item, ttpf, DIFFUSE_TEX)) - shaders = world_build._list_field(item, "MeshShaders") - ids = [] - for p in prims: - if not p.get("positions") or not p.get("indices"): - continue - g = p.get("group_index", 0) - sidx = shaders[g] if 0 <= g < len(shaders) else g - tex = -1 - dds = tex_map.get(sidx) - if dds: - dkey = os.path.normcase(dds) - if dkey not in tex_ids: - blob = texture_bytes(dds, args.tex_size) - tex_ids[dkey] = len(textures) if blob else -1 - if blob: - textures.append(blob) - tex = tex_ids[dkey] - ids.append((len(meshes), tex)) - meshes.append(mesh_bytes(p)) - mesh_ids[key] = ids - if not mesh_ids[key]: - stats["unresolved"] += 1 - continue - rws = draw_rows(row["_rot"], row["_sxy"], row["_sz"], row["_pos"]) - for mesh, tex in mesh_ids[key]: - draws.append(struct.pack("= 0 - stats["placed"] += 1 - stats["z"].append(row["_pos"][2]) - if stats["placed"] >= args.max_props: - break - z = sorted(stats.pop("z")) or [0.0] - center = [args.center[0], args.center[1], z[len(z) // 2]] - with open(args.out, "wb") as f: - f.write(b"LSB1" + struct.pack("<4I3f", 1, len(textures), len(meshes), len(draws), *center)) - for blob in textures + meshes + draws: - f.write(blob) - stats.update(textures=len(textures), meshes=len(meshes), draws=len(draws), center=center, - selected_rows=counts["selected"]) - return stats - - -def main(argv=None): - ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) - ap.add_argument("--entities", required=True, help="world_index.py --entities-out file (JSON lines)") - ap.add_argument("--models", required=True, help="folder holding rpf9dump models manifests") - ap.add_argument("--textures", action="append", default=[], help="folder holding rpf9dump ttpf manifests (repeatable)") - ap.add_argument("--center", type=float, nargs=2, metavar=("X", "Y"), - help="RAGE world x y (default: densest 50 m cell of resolved model placements)") - ap.add_argument("--radius", type=float, default=150.0) - ap.add_argument("--max-props", type=int, default=400, help="entities to place, nearest first (each can be several draws)") - ap.add_argument("--tex-size", type=int, default=256) - ap.add_argument("--out", required=True) - args = ap.parse_args(argv) - if args.center is not None: - try: - if not all(math.isfinite(v) for v in args.center): - raise OverflowError - struct.pack("<2f", *args.center) - except OverflowError: - ap.error("--center coordinates must be finite float32 values") - if not math.isfinite(args.radius) or args.radius < 0: - ap.error("--radius must be finite and non-negative") - if args.max_props < 0: - ap.error("--max-props must be non-negative") - if os.path.isdir(args.out): - print(f"ERROR: --out is a folder, not a scene file: {args.out}", file=sys.stderr) - return 2 - try: - stats = build(args) - except OSError as e: - # An unreadable --entities/--models or an unwritable --out used to end in a traceback. - print(f"ERROR: {e}", file=sys.stderr) - return 2 - print(" ".join(f"{k}={v}" for k, v in stats.items())) - return 0 - - -if __name__ == "__main__": - try: # a redirected stdout is strict ANSI code page under -I; write '?' for what it cannot encode - sys.stdout.reconfigure(errors="replace") - except (AttributeError, ValueError, OSError): - pass - sys.exit(main()) diff --git a/tools/save_keys.py b/tools/save_keys.py deleted file mode 100644 index 76b812d08..000000000 --- a/tools/save_keys.py +++ /dev/null @@ -1,366 +0,0 @@ -#!/usr/bin/env python3 -"""save_keys: collect the hashed `$0x…` keys of GTA VI saves and resolve them against a local name dictionary. - -Save keys (block ids, group keys and field names in JSAV blocks and ASAV settings JSON) are the **case-sensitive** -joaat (Jenkins one-at-a-time, no lower-casing, seed 0) of the engine's names, the same rule as the engine member -hashes in docs/world_names.md. Lower-cased joaat, FNV-1/1a, CRC-32 and MurmurHash3 (32-bit, and both halves of the -64-bit) resolve none of them. See docs/saves.md. - -Standard library only. Run with `python -I tools/save_keys.py ...`. - -Commands - collect ... count the distinct `$0x…` keys in JSAV/ASAV files, `saves.py extract` folders - or loose .json files - resolve ... --dict F... [--compose N] [--out FILE] - harvest identifier-like strings from the dictionary files (any text or binary, - e.g. carved archive streams), hash them, and report how many keys resolve with - each hash family. --compose N also tries one- and two-word Pascal/camel/snake - names built from the N most frequent words and prints the expected number of - chance matches. --out writes hash -> names as JSON (a local work product: - resolved names are game data, so never commit or post it). - -Resolved names are game strings. Only counts belong in issues and pull requests. -Usage: `python -I tools/save_keys.py --help` lists the options. -""" -import argparse -import collections -import json -import os -import re -import struct -import sys -import zlib - -KEY = re.compile(rb'"\$0x([0-9a-fA-F]{8})"') -# A whole run of identifier characters. With a bound inside the pattern ({1,80}) a longer name was cut after 81 -# characters and the search went on in what was left, so one 89-character name became two names nobody wrote -# and the real one was never hashed. Runs past IDENT_MAX are not names (encoded blobs) and are left out whole. -IDENT = re.compile(rb"[A-Za-z_][A-Za-z0-9_]+") -IDENT_MAX = 255 -WORD = re.compile(r"[A-Z]?[a-z]+|[A-Z]+(?![a-z])|\d+") -M32 = 0xFFFFFFFF - - -# ---------------------------------------------------------------------------------------------- hash families -def joaat_step(h, data): - for c in data: - h = (h + c) & M32 - h = (h + (h << 10)) & M32 - h ^= h >> 6 - return h - - -def joaat_final(h): - h = (h + (h << 3)) & M32 - h ^= h >> 11 - return (h + (h << 15)) & M32 - - -def joaat(data, seed=0): - """Case-sensitive joaat: the save-key hash.""" - return joaat_final(joaat_step(seed, data)) - - -def fnv1a(data): - h = 0x811C9DC5 - for c in data: - h = ((h ^ c) * 0x01000193) & M32 - return h - - -def fnv1(data): - h = 0x811C9DC5 - for c in data: - h = ((h * 0x01000193) & M32) ^ c - return h - - -def murmur3_32(data, seed=0): - c1, c2 = 0xCC9E2D51, 0x1B873593 - h, n = seed, len(data) // 4 - for i in range(n): - k = struct.unpack_from("> 17)) & M32 - h ^= (k * c2) & M32 - h = ((h << 13) | (h >> 19)) & M32 - h = (h * 5 + 0xE6546B64) & M32 - k = 0 - for i, b in enumerate(data[n * 4:]): - k |= b << (8 * i) - if len(data) & 3: - k = (k * c1) & M32 - k = ((k << 15) | (k >> 17)) & M32 - h ^= (k * c2) & M32 - h ^= len(data) - h ^= h >> 16 - h = (h * 0x85EBCA6B) & M32 - h ^= h >> 13 - h = (h * 0xC2B2AE35) & M32 - return h ^ (h >> 16) - - -def murmur3_x64_64(data, seed=0): - """Low 64 bits of MurmurHash3 x64 128 (the 64-bit name key in docs/world_names.md).""" - m = (1 << 64) - 1 - - def rotl(x, r): - return ((x << r) | (x >> (64 - r))) & m - - def fmix(k): - k ^= k >> 33 - k = (k * 0xFF51AFD7ED558CCD) & m - k ^= k >> 33 - k = (k * 0xC4CEB9FE1A85EC53) & m - return k ^ (k >> 33) - - c1, c2 = 0x87C37B91114253D5, 0x4CF5AD432745937F - h1 = h2 = seed - n = len(data) // 16 - for i in range(n): - k1, k2 = struct.unpack_from(" 8: - h2 ^= (rotl((k2 * c2) & m, 33) * c1) & m - if tail: - h1 ^= (rotl((k1 * c1) & m, 31) * c2) & m - h1 ^= len(data) - h2 ^= len(data) - h1 = (h1 + h2) & m - h2 = (h2 + h1) & m - h1, h2 = fmix(h1), fmix(h2) - return (h1 + h2) & m - - -FAMILIES = { - "joaat": joaat, - "joaat_lower": lambda b: joaat(b.lower()), - "fnv1a": fnv1a, - "fnv1": fnv1, - "crc32": zlib.crc32, - "murmur3_32": murmur3_32, - "murmur3_64_lo32": lambda b: murmur3_x64_64(b) & M32, - "murmur3_64_hi32": lambda b: murmur3_x64_64(b) >> 32, -} - - -# ---------------------------------------------------------------------------------------------- inputs -def read(p): - with open(p, "rb") as f: - return f.read() - - -INPUT_EXTENSIONS = (".jsav", ".asav", ".json", ".bin") - - -def _walk_error(exc: OSError): - # os.walk skips a directory it cannot list unless onerror raises; a key collection must not report an - # incomplete directory as complete. main() turns the OSError into one error line naming the folder. - raise exc - - -def input_files(paths): - """Every save file (.jsav, .asav, .bin or no extension) or .json under the given paths, in reading order.""" - for p in paths: - if os.path.isdir(p): - for dp, _, fs in os.walk(p, onerror=_walk_error): - for f in sorted(fs): - if f.lower().endswith(INPUT_EXTENSIONS) or "." not in f: - yield os.path.join(dp, f) - else: - yield p - - -def iter_inputs(paths): - """Yield (path, bytes) for every file input_files() lists. - - The path lets warnings name the offending file when a batch contains a bad save. - """ - for source in input_files(paths): - yield source, read(source) - - -def out_problem(out, inputs, dicts): - """Why --out can't be written, checked before any work: it is one of the files read (the report would replace - the user's dictionary or a save), or its folder does not exist. "" when it is fine.""" - if not os.path.isdir(os.path.dirname(os.path.abspath(out))): - return f"the folder for --out {out} does not exist" - if os.path.exists(out): - for p in list(input_files(inputs)) + list(dicts): - if os.path.exists(p) and os.path.samefile(out, p): # samefile: a hard link or another spelling counts - return f"--out {out} is also an input ({p}); refusing to overwrite it" - return "" - - -def collect_keys(paths): - keys = collections.Counter() - for source, d in iter_inputs(paths): - if d[:4] == b"JSAV": # index hashes are block ids too - # A truncated or lying entry count must not abort a whole batch with a struct.error traceback. - # Skip only the table: the $0x... text keys below are still readable from the same bytes. - if len(d) < 16: - print(f"warning: {source}: JSAV header is only {len(d)} bytes; skipping its entry table", - file=sys.stderr) - n = 0 - else: - n = sum(struct.unpack_from(" len(d): - print(f"warning: {source}: JSAV header declares {n} entries but the file has {len(d)} bytes; " - "skipping its entry table", file=sys.stderr) - n = 0 - for i in range(n): - keys[struct.unpack_from("= 2 or w.isdigit(): - words[w.lower()] += 1 - # Ties are broken by the word, not by the order it was counted: `strings` is a set, so most_common() - # followed hash iteration and the same input reported a different composed count from run to run. - vocab = [w for w, _ in sorted(words.items(), key=lambda kv: (-kv[1], kv[0]))][:n_words] - pascal = [w.capitalize().encode() for w in vocab] - lower = [w.encode() for w in vocab] - hits, tried = collections.defaultdict(set), 0 - for p, low in zip(pascal, lower): - for c in (p, low, p.upper()): - tried += 1 - v = joaat(c) - if v in keys: - hits[v].add(c) - for firsts, sep, seconds in ((pascal, b"", pascal), (lower, b"", pascal), (lower, b"_", lower)): - for a in firsts: - ha = joaat_step(joaat_step(0, a), sep) - for b in seconds: - tried += 1 - v = joaat_final(joaat_step(ha, b)) - if v in keys: - hits[v].add(a + sep + b) - return hits, tried - - -# ---------------------------------------------------------------------------------------------- commands -def cmd_collect(a): - keys = collect_keys(a.inputs) - print(f"{len(keys)} distinct keys, {sum(keys.values())} occurrences") - - -def cmd_resolve(a): - if a.out and (problem := out_problem(a.out, a.inputs, a.dict)): - print("error:", problem, file=sys.stderr) - return 1 - keys = set(collect_keys(a.inputs)) - strings = harvest(a.dict) - chance = len(strings) * len(keys) / 2 ** 32 - print(f"{len(keys)} distinct keys; {len(strings)} dictionary strings " - f"(about {chance:.1f} keys per family expected by chance)") - resolved = {} - for name, fn in FAMILIES.items(): - hit = collections.defaultdict(set) - for s in strings: - v = fn(s) - if v in keys: - hit[v].add(s) - extra = "" - if name == "joaat": - resolved = hit - else: - only = len(set(hit) - set(resolved)) - extra = f" ({only} not already resolved by joaat)" - print(f" {name:16} {len(hit):6} keys resolve{extra}") - if a.compose: - hits, tried = compose(strings, keys, a.compose) - new = set(hits) - set(resolved) - print(f" joaat, composed {len(new):6} more keys from {tried} one/two-word names " - f"(about {tried * len(keys) / 2 ** 32:.1f} expected by chance)") - for k in new: - resolved[k] |= hits[k] - print(f" total (joaat) {len(resolved):6} of {len(keys)} keys ({100 * len(resolved) / max(1, len(keys)):.1f}%)") - if a.out: - try: - with open(a.out, "w", encoding="utf-8", newline="\n") as f: - json.dump({"%08x" % k: sorted(x.decode("latin-1") for x in v) for k, v in sorted(resolved.items())}, - f, indent=1) - except OSError as e: - print(f"error: cannot write {a.out}: {e.strerror or e}", file=sys.stderr) - return 1 - print(f"wrote {a.out} (local only: it contains game names)") - - -def main(argv=None): - ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) - sub = ap.add_subparsers(dest="cmd", required=True) - c = sub.add_parser("collect") - c.add_argument("inputs", nargs="+") - r = sub.add_parser("resolve") - r.add_argument("inputs", nargs="+") - r.add_argument("--dict", nargs="+", required=True) - r.add_argument("--compose", type=int, default=0, metavar="N") - r.add_argument("--out") - a = ap.parse_args(argv) - if a.cmd == "resolve" and a.compose < 0: - r.error("--compose must be 0 or more") - try: - return {"collect": cmd_collect, "resolve": cmd_resolve}[a.cmd](a) or 0 - except OSError as e: - if e.filename is None: # not a file we were asked to read (a closed pipe, say) - raise - # A missing or unreadable input or --dict file is one line naming it, not a traceback. - print(f"error: {e.filename}: {e.strerror or e}", file=sys.stderr) - return 1 - - -if __name__ == "__main__": - try: # a redirected stdout is strict ANSI code page under -I; write '?' for what it cannot encode - sys.stdout.reconfigure(errors="replace") - except (AttributeError, ValueError, OSError): - pass - sys.exit(main()) diff --git a/tools/saves.py b/tools/saves.py deleted file mode 100644 index 062e03fd2..000000000 --- a/tools/saves.py +++ /dev/null @@ -1,742 +0,0 @@ -#!/usr/bin/env python3 -"""saves.py: inspect, extract, rebuild and import the game's save containers (ASAV / JSAV / SLAYER1). - -Standard library only. Run with `python -I tools/saves.py ...`. -Reads files that are already plain on disk. It does no decryption and contains no keys; the packed SLAYER1 body -is reported, not decoded. Format notes: docs/saves.md. - -Commands - info ... print headers (auto-detects ASAV, JSAV, SLAYER1 and save folders) - extract JSAV -> index.json + blocks/NNN__.json + save.pretty.json - ASAV -> header.json + payload.bin (+ payload.json if it is text) - pack rebuild a JSAV from an `extract` folder (blocks are taken verbatim) - follows destination symlinks; destinations with multiple hard links are refused - verify ... check each rebuild for byte identity, continuing after individual errors - diff list blocks that were added, removed or changed between two saves - import ... [--out DIR] [--map OLD=CONTAINER/BLOB]... [--with-packed] [--force] [--dry-run] - copy the ASAV/JSAV payloads out of plain save folders into the on-disk layout - of the runtime's offline XGameSave (runtime/shims/xgameruntime_gamesave.cpp): - DIR/local-user//, names %-encoded the same way. - DIR defaults to %LOCALAPPDATA%\\Leonida\\saves (the shim's LEONIDA_SAVE_DIR default). - VERIFY: container/blob names are a guess until the executable shows them; by default - container = slot name (from the ASAV header), blob = payload file name. Use --map. -""" -import json -import os -import stat -import struct -import sys -import tempfile -from datetime import datetime, timezone - -sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) -from file_mode import published_mode # noqa: E402 -from report_paths import same_report_path # noqa: E402 - -# ---------------------------------------------------------------------------------------------- ASAV -ASAV_HDR = 0x170 # header size seen on every plain ASAV file -ASAV_TITLE = (0x28, 0x128) # UTF-16LE display title, 128 code units -ASAV_NAME = (0x128, 0x160) # ASCII slot name, 56 bytes - - -def ts(v): - try: - return datetime.fromtimestamp(v, timezone.utc).strftime('%Y-%m-%d %H:%M:%S UTC') - except (OverflowError, OSError, ValueError): - return None - - -def parse_asav(d): - if d[:4] != b'ASAV': - raise ValueError('not ASAV') - # The fixed fields below are read at absolute offsets, so a short file must be rejected here instead of - # letting struct.unpack_from raise a struct.error that says nothing about the save (the JSAV parser in #923). - if len(d) < ASAV_HDR: - raise ValueError(f'header is only {len(d)} bytes, an ASAV header is {ASAV_HDR}') - f = struct.unpack_from(' len(d): - raise ValueError(f"payload offset {h['payload_offset']:#x} is past the end of a {len(d)}-byte file") - return h - - -def asav_payload(d, h): - end = h['field_1c'] if h['unk_0c'] == 1 and h['field_1c'] <= len(d) else len(d) - return d[h['payload_offset']:end] - - -PROFILE_PAYLOAD_SIZE = 1644 -PROFILE_HEADER_SIZE = 112 - - -def parse_profile(pl): - """Decode an ASAV profile record (kind 3) payload. - - The payload has a fixed size of 1,644 bytes: - - 0x00..0x70 (112 bytes): active profile header starting with version=10, kind=3. - - 0x70..0x66C (1,532 bytes): zero padding / reserved expansion buffer. - """ - if len(pl) < 8: - raise ValueError(f'profile payload too short ({len(pl)} bytes, expected at least 8)') - ver, kind = struct.unpack_from(' PROFILE_HEADER_SIZE else True - - rec = { - 'version': ver, - 'kind': kind, - 'size': len(pl), - 'active_bytes': active_len, - 'zero_padding_bytes': zero_tail, - 'zero_padding_clean': zero_clean, - 'dwords': dwords, - } - if active_len >= 16: - rec['subversion'] = dwords[2] - rec['flags'] = dwords[3] - if active_len >= 24: - rec['account_id'] = struct.unpack_from(' limit: - return True - elif ch in "]}": - depth -= 1 - return False - - -def parse_jsav(d): - if d[:4] != b'JSAV': - raise ValueError('not JSAV') - if len(d) < JSAV_HDR: - raise ValueError('JSAV header is only %d bytes' % len(d)) - ver, n_code, n_script = struct.unpack_from(' len(d): - raise ValueError('JSAV header declares %d entries but the file has %d bytes' % (n, len(d))) - entries = [] - for i in range(n): - hsh, flags, rsv, off, size = JSAV_ENTRY.unpack_from(d, JSAV_HDR + i * JSAV_ENTRY.size) - entries.append({'index': i, 'group': 'code' if i < n_code else 'script', - 'hash': '%08x' % hsh, 'flags': flags, 'reserved': rsv, 'offset': off, 'size': size}) - try: - body_off = d.index(b'{', table_end) - except ValueError: - raise ValueError('JSAV body marker not found after the entry table') from None - try: - body_text = d[body_off:].rstrip(b'\0').decode('utf-8') - if json_nesting_exceeds(body_text): - raise ValueError(f'nesting exceeds {JSON_NESTING_LIMIT} levels') - _, json_end = json.JSONDecoder().raw_decode(body_text) - except (UnicodeError, json.JSONDecodeError, RecursionError, ValueError) as exc: - raise ValueError(f'JSAV body is not valid UTF-8 JSON: {exc}') from None - # raw_decode returns a character offset, while the entry table uses byte offsets. - # The last nonzero byte is not the JSON boundary: corrupt data can follow the document's padding. - body_end = body_off + len(body_text[:json_end].encode('utf-8')) - for entry in entries: - start, end = entry['offset'], entry['offset'] + entry['size'] - if start < body_off or end > body_end: - # Python slices silently truncate invalid ranges; never export or compare those as real blocks. - raise ValueError(f"JSAV entry {entry['index']} range {start:#x}..{end:#x} is outside " - f"the JSON body {body_off:#x}..{body_end:#x}") - if body_text[json_end:].strip(' \t\r\n'): - raise ValueError('JSAV has non-padding data after the JSON body') - return {'magic': 'JSAV', 'version': ver, 'code_blocks': n_code, 'script_blocks': n_script, - 'table_end': table_end, 'body_offset': body_off, 'body_end': body_end, - 'file_size': len(d)}, entries - - -def jsav_blocks(d, entries): - return [d[e['offset']:e['offset'] + e['size']] for e in entries] - - -def align(n, a): - return (n + a - 1) // a * a - - -def build_jsav(version, n_code, hashes, flags, blocks): - """Rebuild the exact framing seen in retail saves.""" - n = len(blocks) - body_off = align(JSAV_HDR + n * JSAV_ENTRY.size, 16) - # Retail framing: '{"CodeSaveBlocks":[\r\n' b0 ',\r\n' b1 ... '],\r\n"ScriptSaveBlocks":[\r\n' ... ']\r\n}' - # (the closing ']' follows the last block directly, no newline before it). - body = bytearray(b'{"CodeSaveBlocks":[\r\n') - offs = [] - for i, b in enumerate(blocks): - if i == n_code: - if n_code: - body[-len(JSAV_SEP):] = b'' - body += b'],\r\n"ScriptSaveBlocks":[\r\n' - offs.append(body_off + len(body)) - body += b + JSAV_SEP - if blocks: - body[-len(JSAV_SEP):] = b'' - if n_code == n: - body += b'],\r\n"ScriptSaveBlocks":[\r\n' - body += b']\r\n}' - out = bytearray(struct.pack('<4sIII', b'JSAV', version, n_code, n - n_code)) - for h, f, o, b in zip(hashes, flags, offs, blocks): - out += JSAV_ENTRY.pack(h, f, 0, o, len(b)) - out += b'\0' * (body_off - len(out)) - out += body - out += b'\0' * (align(len(out), 16) - len(out)) - return bytes(out) - - -# ---------------------------------------------------------------------------------------------- SLAYER1 -SLAYER1_HDR = 16 # "SLAYER1\0" + u32 version + u32 name length - - -def parse_slayer(d, path=None): - if d[:8] != b'SLAYER1\0': - raise ValueError('not SLAYER1') - where = f' in {path}' if path else '' - # The fixed preamble holds the magic, version and name length; a short file must be rejected here instead - # of letting struct.unpack_from raise a struct.error that says nothing about the save (see parse_asav/#923). - if len(d) < SLAYER1_HDR: - raise ValueError(f'SLAYER1 header is only {len(d)} bytes{where}, a SLAYER1 header is at least ' - f'{SLAYER1_HDR}') - ver, nlen = struct.unpack_from(' len(d): - raise ValueError(f'SLAYER1{where} declares a {nlen}-byte name; with the 8-byte payload size the header ' - f'needs {SLAYER1_HDR + nlen + 8} bytes, but the file has only {len(d)}') - name = d[SLAYER1_HDR:SLAYER1_HDR + nlen].decode('ascii', 'replace') - size = struct.unpack_from('= 8: - try: - prof = parse_profile(pl) - print(f'{indent} profile record version={prof["version"]} kind={prof["kind"]} ' - f'active={prof["active_bytes"]}B zero_pad={prof["zero_padding_bytes"]}B ' - f'(clean={prof["zero_padding_clean"]})') - except ValueError as ex: - print(f'{indent} profile record failed to decode: {ex}') - elif k == 'JSAV': - h, es = parse_jsav(d) - for key, v in h.items(): - print(f'{indent} {key:15} {v}') - groups = {} - for e, b in zip(es, jsav_blocks(d, es)): - g = b[2:15].decode('ascii', 'replace').strip('"') - groups.setdefault((e['group'], g), []).append(e['size']) - for (g, w), sizes in groups.items(): - print(f'{indent} {g:6} wrapper {w}: {len(sizes)} blocks, {sum(sizes)} bytes, largest {max(sizes)}') - elif k == 'SLAYER1': - h = parse_slayer(d, p) - for key, v in h.items(): - print(f'{indent} {key:15} {v}') - inner = d[h['payload_offset']:] - if inner[:4] == b'ASAV': - ih = parse_asav(inner) - print(f'{indent} inner ASAV: kind={ih["kind"]} title={ih["title"]!r} slot={ih["slot_name"]!r} ' - f'time={ih["timestamp_utc"]} f10={ih["field_10"]:#x} f18={ih["field_18"]} f1c={ih["field_1c"]}') - print(f'{indent} inner body is high-entropy (compressed and/or encrypted); not decoded') - - -def info(paths): - for p in paths: - if os.path.isdir(p): - cj = os.path.join(p, 'chives.json') - if os.path.exists(cj): - meta = json.loads(read(cj)) - print(f'{p}: save folder, dir {meta.get("save_directory")}') - for name in sorted(os.listdir(p)): - fp = os.path.join(p, name) - if os.path.isfile(fp) and kind_of(read(fp, 8)): - info_file(fp, ' ') - else: - info_file(p) - - -def extract(p, out): - d = read(p) - k = kind_of(d) - os.makedirs(out, exist_ok=True) - if k == 'JSAV': - h, es = parse_jsav(d) - bd = os.path.join(out, 'blocks') - os.makedirs(bd, exist_ok=True) - blocks = jsav_blocks(d, es) - for e, b in zip(es, blocks): - e['file'] = f'blocks/{e["index"]:03d}_{e["group"]}_{e["hash"]}.json' - with open(os.path.join(out, e['file']), 'wb') as f: - f.write(b) - with open(os.path.join(out, 'index.json'), 'w', encoding='utf-8', newline="\n") as f: - json.dump({'header': h, 'entries': es}, f, indent=1) - body = d[h['body_offset']:h['body_end']].decode('utf-8') - with open(os.path.join(out, 'save.pretty.json'), 'w', encoding='utf-8', newline="\n") as f: - json.dump(json.loads(body), f, indent=1) - print(f'{len(es)} blocks -> {out}') - elif k == 'ASAV': - h = parse_asav(d) - pl = asav_payload(d, h) - with open(os.path.join(out, 'header.json'), 'w', encoding='utf-8', newline="\n") as f: - json.dump(h, f, indent=1) - with open(os.path.join(out, 'header.bin'), 'wb') as f: - f.write(d[:h['payload_offset']]) - with open(os.path.join(out, 'payload.bin'), 'wb') as f: - f.write(pl) - if pl[:1] == b'{': - try: - obj = json.loads(pl.rstrip(b'\0').decode('utf-8')) - with open(os.path.join(out, 'payload.json'), 'w', encoding='utf-8', newline="\n") as f: - json.dump(obj, f, indent=1) - except ValueError as ex: - print('payload looks like text but did not parse as JSON:', ex) - elif h['kind'] == 3 and len(pl) >= 8: - try: - prof = parse_profile(pl) - with open(os.path.join(out, 'profile.json'), 'w', encoding='utf-8', newline="\n") as f: - json.dump(prof, f, indent=1) - except ValueError as ex: - print('profile payload did not parse:', ex) - print(f'ASAV kind {h["kind"]} ({h["slot_name"]}) -> {out}') - else: - sys.exit(f'{p}: extract supports JSAV and ASAV') - - -def pack_from_dir(src, refuse=None): - """The JSAV bytes for an extracted folder. `refuse` is the --out path: a source file it names is refused.""" - index_path = os.path.join(src, 'index.json') - - def invalid(field, expected): - raise ValueError(f'{index_path}: {field} must be {expected}') - - def source(name): - path = os.path.join(src, name) - if refuse is not None and same_report_path(path, refuse): - raise ValueError(f'{path}: pack reads this file, and --out {refuse} would replace it') - return read(path) - - text = source('index.json') - try: - if json_nesting_exceeds(text): - raise ValueError(f'nesting exceeds {JSON_NESTING_LIMIT} levels') - idx = json.loads(text) - except (ValueError, RecursionError) as exc: - raise ValueError(f'{index_path}: invalid JSON ({exc})') from None - if not isinstance(idx, dict): - invalid('index', 'an object') - h, es = idx.get('header'), idx.get('entries') - if not isinstance(h, dict): - invalid('header', 'an object') - if not isinstance(es, list): - invalid('entries', 'an array') - for field in ('version', 'code_blocks'): - value = h.get(field) - if type(value) is not int or not 0 <= value <= 0xFFFFFFFF: - invalid('header.' + field, 'a uint32 integer') - if h['code_blocks'] > len(es): - invalid('header.code_blocks', f'between 0 and the entry count ({len(es)})') - hashes = [] - for i, entry in enumerate(es): - prefix = f'entries[{i}]' - if not isinstance(entry, dict): - invalid(prefix, 'an object') - if not isinstance(entry.get('file'), str) or not entry['file']: - invalid(prefix + '.file', 'a nonempty path string') - flags = entry.get('flags') - if type(flags) is not int or not 0 <= flags <= 0xFFFFFFFF: - invalid(prefix + '.flags', 'a uint32 integer') - if not isinstance(entry.get('hash'), str): - invalid(prefix + '.hash', 'a hexadecimal uint32 string') - try: - hashed = int(entry['hash'], 16) - except ValueError: - invalid(prefix + '.hash', 'a hexadecimal uint32 string') - if not 0 <= hashed <= 0xFFFFFFFF: - invalid(prefix + '.hash', 'a hexadecimal uint32 string') - hashes.append(hashed) - blocks = [source(e['file']) for e in es] - return build_jsav(h['version'], h['code_blocks'], hashes, [e['flags'] for e in es], blocks) - - -def pack(src, out): - # Publish at the symlink's target, as open(out, 'wb') did, without replacing the link itself. - destination = os.path.realpath(out) - try: - existing = os.stat(destination) - except FileNotFoundError: - pass - else: - # Replacing one hard-link name cannot update the other aliases atomically. - if stat.S_ISREG(existing.st_mode) and existing.st_nlink > 1: - raise ValueError(f'{out}: destination has multiple hard links; choose an unlinked output path') - data = pack_from_dir(src, destination) - parent = os.path.dirname(destination) - tmp = None - try: - with tempfile.NamedTemporaryFile('wb', dir=parent, prefix='.saves-pack-', suffix='.tmp', - delete=False) as f: - tmp = f.name - f.write(data) - os.chmod(tmp, published_mode(destination)) - os.replace(tmp, destination) - except BaseException: - if tmp is not None: - try: - # A failed replacement may leave a read-only staging file on Windows. - os.chmod(tmp, 0o600) - os.remove(tmp) - except OSError: - pass - raise - print(f'wrote {out} ({len(data)} bytes)') - - -def verify(p): - d = read(p) - h, es = parse_jsav(d) - blocks = jsav_blocks(d, es) - for index, b in enumerate(blocks): - try: - if json_nesting_exceeds(b): - raise RecursionError - json.loads(b) # every block must be valid JSON on its own - except RecursionError as e: - raise ValueError(f'JSAV block {index} exceeds the JSON nesting limit') from e - rebuilt = build_jsav(h['version'], h['code_blocks'], [int(e['hash'], 16) for e in es], - [e['flags'] for e in es], blocks) - if rebuilt == d: - print(f'{p}: OK, {len(es)} blocks parse and the rebuild is byte-identical') - return True - n = next((i for i, (a, b) in enumerate(zip(rebuilt, d)) if a != b), min(len(rebuilt), len(d))) - print(f'{p}: MISMATCH at {n:#x} (rebuilt {len(rebuilt)} vs original {len(d)} bytes)') - return False - - -def diff(pa, pb): - da, db = read(pa), read(pb) - (_, ea), (_, eb) = parse_jsav(da), parse_jsav(db) - # A save can hold several blocks with the same (group, hash): keep them in order instead of letting - # later ones overwrite earlier ones in a dict, which silently dropped them from the comparison. - ma, mb = {}, {} - for entries, data, table in ((ea, da, ma), (eb, db, mb)): - for entry, block in zip(entries, jsav_blocks(data, entries)): - table.setdefault((entry['group'], entry['hash']), []).append(block) - for k in sorted(ma.keys() - mb.keys()): - for block in ma[k]: - print('only in A:', *k, len(block)) - for k in sorted(mb.keys() - ma.keys()): - for block in mb[k]: - print('only in B:', *k, len(block)) - same = 0 - for k in sorted(ma.keys() & mb.keys()): - left, right = ma[k], mb[k] - # Match identical blocks by content first: with duplicate keys, an unchanged block that moved - # position should be reported as a removal/addition of the others, not as a false "changed". - pending_right, matched_left = list(right), [False] * len(left) - for i, block in enumerate(left): - if block in pending_right: - matched_left[i] = True - pending_right.remove(block) - same += 1 - left = [block for i, block in enumerate(left) if not matched_left[i]] - for i in range(max(len(left), len(pending_right))): - a = left[i] if i < len(left) else None - b = pending_right[i] if i < len(pending_right) else None - if a is None or b is None: - label, block = ('only in B:', b) if a is None else ('only in A:', a) - print(label, *k, len(block)) - continue - if a == b: - same += 1 - continue - n = next((j for j, (x, y) in enumerate(zip(a, b)) if x != y), min(len(a), len(b))) - print(f'changed: {k[0]} {k[1]} {len(a)} -> {len(b)} bytes, first difference near: ' - f'A {a[max(0, n - 40):n + 40]!r} B {b[max(0, n - 40):n + 40]!r}') - print(f'{same} blocks identical') - - -# ---------------------------------------------------------------------------------------------- import -def xgs_encode(name): - """Same rule as encode_name() in runtime/shims/xgameruntime_gamesave.cpp: keep - [A-Za-z0-9_-] and '.' except as the first character; everything else becomes %XX (uppercase hex) per UTF-8 byte.""" - out = [] - for c in name.encode('utf-8'): - ch = chr(c) - if (ch.isascii() and ch.isalnum()) or ch in '_-' or (ch == '.' and out): - out.append(ch) - else: - out.append('%%%02X' % c) - return ''.join(out) - - -def save_slot(folder): - """Return (folder label, payload filename, slot name, title) for one save folder.""" - meta_path = os.path.join(folder, 'chives.json') - meta = json.loads(read(meta_path)) if os.path.isfile(meta_path) else {} - found = [] - for name in sorted(os.listdir(folder)): - fp = os.path.join(folder, name) - if os.path.isfile(fp) and name not in ('chives.json', 'chives.dat') and kind_of(read(fp, 8)) in ('ASAV', 'JSAV'): - found.append(name) - if not found: - raise SystemExit(f'{folder}: no ASAV/JSAV payload found') - if len(found) > 1: - # One save per folder: refuse to guess (e.g. "slot1" next to an older "slot1.bak"). - raise SystemExit(f'{folder}: {len(found)} ASAV/JSAV payloads, expected one: {", ".join(found)}; ' - 'move the extra files out or import a folder per save') - payload = found[0] - slot, title = payload, None - d = read(os.path.join(folder, payload)) - if kind_of(d) == 'ASAV': - h = parse_asav(d) - slot, title = h['slot_name'] or payload, h['title'] - packed = os.path.join(folder, 'chives.dat') - if os.path.isfile(packed): - p = read(packed) - if kind_of(p) == 'SLAYER1': - inner = p[parse_slayer(p, packed)['payload_offset']:] - if inner[:4] == b'ASAV': - ih = parse_asav(inner) - slot, title = ih['slot_name'] or slot, ih['title'] - return meta.get('save_directory') or os.path.basename(os.path.normpath(folder)), payload, slot, title - - -CONTAINER_PATH_CHARS = set('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_/') -CONTAINER_FILE_CHARS = set('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_.-') - - -def valid_container_name(name): - """XGameSaveCreateContainer's documented rule, as runtime/shims/xgameruntime_gamesave.cpp checks it: at most 256 - characters; a path part (up to the last '/') of [A-Za-z0-9_/], then a non-empty file part of [A-Za-z0-9_.-] that - does not end in '.' nor hold '..'. The runtime lists any folder, but the game can only open one by a valid name.""" - if not name or len(name) > 256: - return False - path, _, file = name.rpartition('/') - if path and not set(path + '/') <= CONTAINER_PATH_CHARS: - return False - return bool(file) and not file.endswith('.') and '..' not in file and set(file) <= CONTAINER_FILE_CHARS - - -def import_saves(args): - flags = {'--out', '--map', '--with-packed', '--force', '--dry-run'} - for option, following in zip(args, args[1:]): - if option in ('--out', '--map') and following in flags: - raise ValueError(f'import: {option} needs a value before {following}') - - import hashlib - out, maps, with_packed, force, dry = None, {}, False, False, False - folders = [] - it = iter(args) - - def value(flag): - v = next(it, None) - if v is None: - raise ValueError(f'import: {flag} needs a value') - return v - for a in it: - if a == '--out': - out = value(a) - elif a == '--map': - spec = value(a) - if '=' not in spec: - raise ValueError(f'import: --map needs OLD=CONTAINER/BLOB, got {spec!r}') - k, v = spec.split('=', 1) - c, _, b = v.partition('/') - maps[k] = (c, b or None) - elif a == '--with-packed': - with_packed = True - elif a == '--force': - force = True - elif a == '--dry-run': - dry = True - else: - folders.append(a) - if not folders: - raise SystemExit('import: give one or more save folders') - if out is None: - out = os.path.join(os.environ.get('LOCALAPPDATA', '.'), 'Leonida', 'saves') - root = os.path.join(out, 'local-user') - manifest = {'note': 'VERIFY: container/blob names are a guess until the executable shows them', - 'layout': '/local-user//', 'entries': []} - plan = [] - for folder in folders: - sd, payload, slot, title = save_slot(folder) - container, blob = slot, payload - for key in (sd, payload, slot): - if key in maps: - container = maps[key][0] or container - blob = maps[key][1] or blob - files = [(payload, blob)] - if with_packed and os.path.isfile(os.path.join(folder, 'chives.dat')): - files.append(('chives.dat', 'chives.dat')) - for src_name, blob_name in files: - src = os.path.join(folder, src_name) - dst = os.path.join(root, xgs_encode(container), xgs_encode(blob_name)) - plan.append((src, dst)) - data = read(src) - manifest['entries'].append({'folder': sd, 'source': src_name, 'title': title, 'container': container, - 'blob': blob_name, 'size': len(data), - 'sha256': hashlib.sha256(data).hexdigest()}) - print(f'{sd:34} {src_name:24} -> container {container!r:12} blob {blob_name!r:24} {len(data):>9} bytes' - f' ({title})') - if not valid_container_name(container): - print(f'warning: container {container!r} breaks XGameSaveCreateContainer\'s naming rule, so the game ' - f'cannot open it by that name; give it another with --map {sd}=NAME', file=sys.stderr) - dsts = [d.lower() for _, d in plan] - if len(set(dsts)) != len(dsts): - raise SystemExit('import: two payloads map to the same container/blob (names are case-insensitive on ' - 'Windows); use --map to separate them') - if dry: - print('dry run: nothing written') - return - for src, dst in plan: - if os.path.exists(dst) and not force: - raise SystemExit(f'{dst} exists; pass --force to overwrite') - for src, dst in plan: - os.makedirs(os.path.dirname(dst), exist_ok=True) - tmp = os.path.join(os.path.dirname(dst), '~' + os.path.basename(dst)) # the shim's temp-file convention - with open(tmp, 'wb') as f: - f.write(read(src)) - os.replace(tmp, dst) - with open(os.path.join(out, 'import-manifest.json'), 'w', encoding='utf-8', newline="\n") as f: - json.dump(manifest, f, indent=1) - print(f'wrote {len(plan)} blobs under {root}') - - -def main(argv): - if len(argv) < 2 or argv[1] in ('-h', '--help'): - print(__doc__) - return 0 - cmd, args = argv[1], argv[2:] - try: - if cmd == 'info' and args: - info(args) - elif cmd == 'extract' and len(args) == 2: - extract(*args) - elif cmd == 'pack' and len(args) == 2: - pack(*args) - elif cmd == 'verify' and args: - status = 0 - for path in args: - try: - if not verify(path): - status = max(status, 1) - except (ValueError, struct.error) as e: - print(f'ERROR: {e} ({path})', file=sys.stderr) - status = 2 - except OSError as e: - print(f'ERROR: {e.strerror or e} ({path})', file=sys.stderr) - status = 2 - return status - elif cmd == 'diff' and len(args) == 2: - diff(*args) - elif cmd == 'import': - import_saves(args) - else: - print(__doc__) - return 2 - except (ValueError, struct.error, OSError) as e: - # A malformed save must report one clear line, not a traceback. - print('ERROR: %s' % e, file=sys.stderr) - return 2 - return 0 - - -if __name__ == '__main__': - try: # a redirected stdout is strict ANSI code page under -I; write '?' for what it cannot encode - sys.stdout.reconfigure(errors="replace") - except (AttributeError, ValueError, OSError): - pass - sys.exit(main(sys.argv)) diff --git a/tools/script_qtable.py b/tools/script_qtable.py deleted file mode 100644 index afa037245..000000000 --- a/tools/script_qtable.py +++ /dev/null @@ -1,628 +0,0 @@ -"""Decode the 0x71717171-tagged ('qqqq') object-tree container in script.rpf. - -`rpf9_carve.py` extracts 1,012 PSIN containers from `script.rpf` plus one -42-stream binary container at offset `0x53000` (2,702,384 bytes inflated). It -begins with a 40-byte header holding `u32 record_count` at `+0x14`, followed by -`record_count` ascending `u64` byte offsets and `record_count` 16-byte-aligned -records. Internal 8-byte pointers carry `0x71717171` (`'qqqq'`) in the high -32 bits and `offsets[target] + 8` in the low 32 bits. - -Usage: - python -I tools/script_qtable.py [--root-hash HEX] [--type-hash HEX] [--json FILE] - -Default output and `--json` reports emit aggregate structure counts, size and -stride histograms, invariant checks and optional local query counts only; no -payload bytes or string tables are exported. Standard library only. -""" -from __future__ import annotations - -import argparse -from collections import Counter -import json -import os -import struct -import sys - -# -I keeps the script directory off sys.path, so add it explicitly before importing sibling helpers. -TOOLS = os.path.dirname(os.path.abspath(__file__)) -if TOOLS not in sys.path: - sys.path.insert(0, TOOLS) - -import gamedata_index as gi # noqa: E402 -import gamedata_maps as gm # noqa: E402 -from report_paths import same_report_path # noqa: E402 - -HEADER_BYTES = 40 -Q_TAG = 0x71717171 -ARRAY_MARKER = 0x14 -ARRAY_HEADER_BYTES = 48 -ARRAY_FLAG_POINTERS = 0x10000 -MAX_RECORDS = 1_000_000 - - -class UsageError(ValueError): - """CLI argument or output-path error reported with exit code 2.""" - - -def _align16(value: int) -> int: - return (value + 15) & ~15 - - -def is_qtable_prefix(blob: bytes) -> bool: - """True when `blob` begins with a valid 40-byte qtable header and offset[0].""" - if len(blob) < HEADER_BYTES + 8: - return False - words = struct.unpack_from("<10I", blob, 0) - record_count = words[5] - if not (1 <= record_count <= MAX_RECORDS): - return False - if any(words[i] != 0 for i in range(10) if i != 5): - return False - first_off = struct.unpack_from(" int: - try: - value = int(text, 16) - except ValueError as e: - raise UsageError(f"invalid hex u32: {text}") from e - if not (0 <= value <= 0xFFFFFFFF): - raise UsageError(f"hash out of u32 range: {text}") - return value - - -def _classify_record(idx: int, rec: bytes, ptrs: list[tuple[int, int, int | None]]) -> dict: - w2, w3 = struct.unpack_from("<2I", rec, 8) - if w2 == ARRAY_MARKER and w3 == 0: - if len(rec) < ARRAY_HEADER_BYTES: - return { - "index": idx, - "kind": "array", - "bytes": len(rec), - "count": 0, - "capacity": 0, - "stride": 0, - "array_flags": 0, - "element_type_hash": 0, - "header_complete": False, - "count_eq_capacity": False, - "size_exact": False, - "extra_words_zero": False, - "zero_element_hash": True, - } - cnt, cap, stride, aflags, w8, w9, elem_hash, w11 = struct.unpack_from("<8I", rec, 16) - expected_len = _align16(ARRAY_HEADER_BYTES + cnt * stride) - return { - "index": idx, - "kind": "array", - "bytes": len(rec), - "count": cnt, - "capacity": cap, - "stride": stride, - "array_flags": aflags, - "element_type_hash": elem_hash, - "header_complete": True, - "count_eq_capacity": cnt == cap, - "size_exact": expected_len == len(rec), - "extra_words_zero": (w8 == 0 and w9 == 0 and w11 == 0), - "zero_element_hash": elem_hash == 0, - } - - is_wrapper = ( - len(rec) == 32 - and w3 == 0 - and len(ptrs) == 1 - and ptrs[0][0] == 16 - and ptrs[0][2] == idx + 1 - and struct.unpack_from(" dict: - """Walk one tree from `root_idx` to measure node count, depth, bytes and type composition.""" - stack = [(root_idx, 0)] - seen: set[int] = set() - arrays = structs = max_depth = total_bytes = cross_edges = 0 - expected_next = root_idx - dfs_preorder = True - stride_counts: Counter[int] = Counter() - struct_sizes: Counter[int] = Counter() - - while stack: - node, depth = stack.pop() - if node in seen: - dfs_preorder = False - continue - seen.add(node) - if node != expected_next: - dfs_preorder = False - expected_next += 1 - if depth > max_depth: - max_depth = depth - rec_end = offsets[node + 1] if node + 1 < len(offsets) else end_off - total_bytes += rec_end - offsets[node] - info = records[node] - if info["kind"] == "array": - arrays += 1 - stride_counts[info["stride"]] += 1 - else: - structs += 1 - struct_sizes[info["bytes"]] += 1 - for child in reversed(adj[node]): - if root_idx <= child < limit_hi: - stack.append((child, depth + 1)) - else: - cross_edges += 1 - dfs_preorder = False - - if expected_next != limit_hi: - dfs_preorder = False - - return { - "nodes": len(seen), - "max_depth": max_depth, - "bytes": total_bytes, - "arrays": arrays, - "structs": structs, - "cross_tree_edges": cross_edges, - "dfs_preorder": dfs_preorder, - "array_strides": {str(k): stride_counts[k] for k in sorted(stride_counts)}, - "struct_sizes": {str(k): struct_sizes[k] for k in sorted(struct_sizes)}, - } - - -def parse_qtable(blob: bytes, *, root_hash: int | None = None, type_hash: int | None = None) -> dict: - """Validate and summarize a 0x71717171-tagged object-tree payload.""" - if not is_qtable_prefix(blob): - raise ValueError("payload does not begin with a valid 40-byte qtable header") - if len(blob) % 16 != 0: - raise ValueError(f"payload length {len(blob)} is not 16-byte aligned") - - n = struct.unpack_from("= len(blob): - raise ValueError(f"record {i} offset {off:#x} is out of bounds for {len(blob):#x} bytes") - if i > 0 and off <= offsets[i - 1]: - raise ValueError(f"record {i} offset {off:#x} <= previous {offsets[i - 1]:#x}") - - bounds = offsets + [len(blob)] - if any((bounds[i + 1] - bounds[i]) < 16 for i in range(n)): - raise ValueError("record shorter than 16 bytes") - - body_to_index = {offsets[i] + 8: i for i in range(n)} - in_degree = [0] * n - adj: list[list[int]] = [[] for _ in range(n)] - records: list[dict] = [] - - root_indices: list[int] = [] - root_hashes_by_idx: dict[int, int] = {} - root_flags_hist: Counter[int] = Counter() - nonroot_flags_nonzero = 0 - - total_pointers = resolved_pointers = unresolved_pointers = forward_edges = 0 - size_hist: Counter[int] = Counter() - array_stride_hist: Counter[int] = Counter() - array_flags_hist: Counter[int] = Counter() - struct_size_hist: Counter[int] = Counter() - element_hashes: set[int] = set() - struct_hashes: set[int] = set() - wrapper_count = struct_w3_nonzero = 0 - array_header_complete = array_count_eq_capacity = 0 - array_exact = array_extra_zero = array_zero_elem_hash = 0 - array_ptr_stride8 = array_ptr_count = 0 - - for i in range(n): - rec = blob[bounds[i]:bounds[i + 1]] - size_hist[len(rec)] += 1 - rkey, pflags = struct.unpack_from("<2I", rec, 0) - if rkey != 0: - root_indices.append(i) - root_hashes_by_idx[i] = rkey - root_flags_hist[pflags] += 1 - elif pflags != 0: - nonroot_flags_nonzero += 1 - - rec_ptrs: list[tuple[int, int, int | None]] = [] - for rel in range(8, len(rec), 8): - word = struct.unpack_from("> 32) == Q_TAG: - total_pointers += 1 - target_off = word & 0xFFFFFFFF - tgt = body_to_index.get(target_off) - rec_ptrs.append((rel, target_off, tgt)) - if tgt is None: - unresolved_pointers += 1 - else: - resolved_pointers += 1 - in_degree[tgt] += 1 - adj[i].append(tgt) - if tgt > i: - forward_edges += 1 - - info = _classify_record(i, rec, rec_ptrs) - info["root_key_hash"] = rkey - info["prefix_flags"] = pflags - records.append(info) - - if info["kind"] == "array": - array_stride_hist[info["stride"]] += 1 - array_flags_hist[info["array_flags"]] += 1 - element_hashes.add(info["element_type_hash"]) - if info["header_complete"]: - array_header_complete += 1 - if info["count_eq_capacity"]: - array_count_eq_capacity += 1 - if info["size_exact"]: - array_exact += 1 - if info["extra_words_zero"]: - array_extra_zero += 1 - if info["zero_element_hash"]: - array_zero_elem_hash += 1 - if info["array_flags"] == ARRAY_FLAG_POINTERS: - array_ptr_count += 1 - if info["stride"] == 8: - array_ptr_stride8 += 1 - else: - struct_size_hist[info["bytes"]] += 1 - struct_hashes.add(info["struct_type_hash"]) - if not info["w3_zero"]: - struct_w3_nonzero += 1 - if info["is_wrapper"]: - wrapper_count += 1 - - root_set = set(root_indices) - in_deg_zero = sum(1 for d in in_degree if d == 0) - nonroot_in_deg_one = all(in_degree[i] == 1 for i in range(n) if i not in root_set) - root_bijection_holds = ( - all((i in root_set) == (in_degree[i] == 0) for i in range(n)) - and nonroot_in_deg_one - ) - - tree_sizes: list[int] = [] - tree_depths: list[int] = [] - cross_tree_edges = 0 - tree_owner: list[int] = [-1] * n - all_dfs_preorder = bool(root_indices) and root_indices[0] == 0 - for pos, r_idx in enumerate(root_indices): - hi = root_indices[pos + 1] if pos + 1 < len(root_indices) else n - for member in range(r_idx, hi): - tree_owner[member] = r_idx - stats = _collect_subtree(r_idx, adj, records, offsets, len(blob), hi) - tree_sizes.append(stats["nodes"]) - tree_depths.append(stats["max_depth"]) - cross_tree_edges += stats["cross_tree_edges"] - if not stats["dfs_preorder"]: - all_dfs_preorder = False - - trees_partition_records = sum(tree_sizes) == n and cross_tree_edges == 0 - contiguous_preorder = ( - trees_partition_records - and forward_edges == resolved_pointers - and all_dfs_preorder - ) - - array_count = sum(1 for r in records if r["kind"] == "array") - struct_count = n - array_count - - valid = ( - unresolved_pointers == 0 - and root_bijection_holds - and contiguous_preorder - and array_header_complete == array_count - and array_count_eq_capacity == array_count - and array_exact == array_count - ) - - result: dict = { - "valid": valid, - "payload_bytes": len(blob), - "header_bytes": HEADER_BYTES, - "offset_table_bytes": n * 8, - "record_pool_offset": offsets[0], - "record_pool_bytes": len(blob) - offsets[0], - "record_count": n, - "root_count": len(root_indices), - "distinct_root_hashes": len(set(root_hashes_by_idx.values())), - "in_deg_zero_count": in_deg_zero, - "nonroot_in_deg_one": nonroot_in_deg_one, - "root_bijection_holds": root_bijection_holds, - "total_pointers": total_pointers, - "resolved_pointers": resolved_pointers, - "unresolved_pointers": unresolved_pointers, - "forward_edges": forward_edges, - "cross_tree_edges": cross_tree_edges, - "trees_partition_records": trees_partition_records, - "contiguous_preorder": contiguous_preorder, - "nonroot_prefix_flags_nonzero": nonroot_flags_nonzero, - "root_prefix_flags": {f"{k:#x}": root_flags_hist[k] for k in sorted(root_flags_hist)}, - "array_records": array_count, - "array_header_complete": array_header_complete, - "array_count_eq_capacity": array_count_eq_capacity, - "array_size_exact": array_exact, - "array_extra_words_zero": array_extra_zero, - "array_zero_element_hashes": array_zero_elem_hash, - "array_value_records": array_flags_hist.get(0, 0), - "array_pointer_records": array_ptr_count, - "array_pointer_stride8": array_ptr_stride8, - "array_flags": {f"{k:#x}": array_flags_hist[k] for k in sorted(array_flags_hist)}, - "array_strides": {str(k): array_stride_hist[k] for k in sorted(array_stride_hist)}, - "distinct_element_type_hashes": len(element_hashes), - "struct_records": struct_count, - "struct_wrappers": wrapper_count, - "struct_w3_nonzero": struct_w3_nonzero, - "distinct_struct_type_hashes": len(struct_hashes), - "struct_sizes": {str(k): struct_size_hist[k] for k in sorted(struct_size_hist)}, - "record_sizes": {str(k): size_hist[k] for k in sorted(size_hist)}, - "tree_nodes_min": min(tree_sizes) if tree_sizes else 0, - "tree_nodes_median": sorted(tree_sizes)[len(tree_sizes) // 2] if tree_sizes else 0, - "tree_nodes_max": max(tree_sizes) if tree_sizes else 0, - "tree_depth_min": min(tree_depths) if tree_depths else 0, - "tree_depth_max": max(tree_depths) if tree_depths else 0, - } - - if root_hash is not None: - matches = [] - for pos, r_idx in enumerate(root_indices): - if root_hashes_by_idx[r_idx] == root_hash: - hi = root_indices[pos + 1] if pos + 1 < len(root_indices) else n - sub = _collect_subtree(r_idx, adj, records, offsets, len(blob), hi) - sub["root_index"] = r_idx - sub["root_offset_hex"] = f"{offsets[r_idx]:#x}" - sub["root_type_hash"] = f"{records[r_idx].get('struct_type_hash', ARRAY_MARKER):#010x}" - matches.append(sub) - result["root_query"] = { - "hash": f"{root_hash:#010x}", - "matches": len(matches), - "trees": matches, - } - - if type_hash is not None: - matching_arrays = [r for r in records if r["kind"] == "array" and r["element_type_hash"] == type_hash] - matching_structs = [r for r in records if r["kind"] == "struct" and r["struct_type_hash"] == type_hash] - owner_roots = {tree_owner[r["index"]] for r in matching_arrays + matching_structs if tree_owner[r["index"]] >= 0} - result["type_query"] = { - "hash": f"{type_hash:#010x}", - "array_matches": len(matching_arrays), - "struct_matches": len(matching_structs), - "distinct_trees": len(owner_roots), - "array_strides": dict(sorted(Counter(str(r["stride"]) for r in matching_arrays).items())), - "struct_sizes": dict(sorted(Counter(str(r["bytes"]) for r in matching_structs).items())), - } - - return result - - -def _is_complete_qtable(blob: bytes) -> bool: - """True when `blob` already holds a complete, structurally valid qtable payload.""" - if not is_qtable_prefix(blob) or len(blob) % 16 != 0: - return False - n = struct.unpack_from(" len(blob): - return False - try: - return bool(parse_qtable(blob)["valid"]) - except ValueError: - return False - - -def _join_qtable_from_source(source) -> tuple[bytes, dict]: - rows = source.rows - n = len(rows) - for i in range(n): - data = source.read(rows[i]) - if not is_qtable_prefix(data): - continue - parts = [data] - stored = rows[i].get("stored", len(data)) - j = i + 1 - prev_len = len(data) - while j < n and prev_len > 0 and prev_len % 65536 == 0: - if _is_complete_qtable(b"".join(parts)): - break - nxt = source.read(rows[j]) - nk = gi.stream_kind(nxt, rows[j]) - if nk in ("decl", "bink2", "rbf0", "psin", "other") or gi.standalone_xml(nxt): - break - parts.append(nxt) - stored += rows[j].get("stored", len(nxt)) - prev_len = len(nxt) - j += 1 - blob = b"".join(parts) - meta = { - "source_type": "directory" if isinstance(source, (gi.DirectorySource, _BinFolderSource)) else "archive", - "offset": rows[i]["off"], - "offset_hex": f"{rows[i]['off']:#x}", - "chunks": j - i, - "stored": stored, - "inflated": len(blob), - } - return blob, meta - raise ValueError("no 0x71717171 object-tree container found") - - -class _BinFolderSource: - """Minimal sorted *.bin reader when a test/carve directory has no index.json.""" - - def __init__(self, directory: str): - names = sorted(n for n in os.listdir(directory) if n.lower().endswith(".bin")) - self.directory = directory - self.rows = [] - for idx, name in enumerate(names): - full = os.path.join(directory, name) - sz = os.path.getsize(full) - try: - off = int(os.path.splitext(name)[0], 16) - except ValueError: - off = idx * 0x10000 - self.rows.append({"off": off, "stored": sz, "size": sz, "_name": name}) - - def read(self, row: dict) -> bytes: - with open(os.path.join(self.directory, row["_name"]), "rb") as f: - return f.read() - - -def load_qtable_payload(target: str) -> tuple[bytes, dict]: - """Load the object-tree container from a carve directory, .rpf archive or raw .bin.""" - if os.path.isdir(target): - index_path = os.path.join(target, "index.json") - source = gi.DirectorySource(target) if os.path.isfile(index_path) else _BinFolderSource(target) - return _join_qtable_from_source(source) - - if not os.path.isfile(target): - raise FileNotFoundError(target) - - with open(target, "rb") as f: - head = f.read(64) - - if head[:4] == b"9FPR": - source = gi.ArchiveSource(target) - try: - return _join_qtable_from_source(source) - finally: - source.close() - - with open(target, "rb") as f: - blob = f.read() - if not is_qtable_prefix(blob): - raise ValueError(f"{target}: not an RPF9 archive or 0x71717171 object-tree payload") - return blob, { - "source_type": "file", - "offset": 0, - "offset_hex": "0x0", - "chunks": 1, - "stored": len(blob), - "inflated": len(blob), - } - - -def check_report_path(out_path: str, target: str, rows: list[dict] | None = None) -> None: - """Refuse a --json destination that is a directory or collides with any input.""" - if os.path.isdir(out_path): - raise UsageError(f"--json is a directory: {out_path}") - if os.path.isdir(target): - if os.path.isfile(os.path.join(target, "index.json")): - try: - gm.check_report_path(out_path, target, rows=rows) - except ValueError as e: - raise UsageError(str(e)) from e - elif same_report_path(out_path, target): - raise UsageError(f"--json would overwrite the input {target}") - else: - for name in os.listdir(target): - if name.lower().endswith(".bin") and same_report_path(out_path, os.path.join(target, name)): - raise UsageError(f"--json would overwrite the input {name}") - elif same_report_path(out_path, target): - raise UsageError(f"--json would overwrite the input {target}") - - -def _print_summary(report: dict) -> None: - loc = report["location"] - print( - f'qtable {loc["offset_hex"]}: {loc["chunks"]} streams, ' - f'{loc["stored"]:,} stored, {report["payload_bytes"]:,} inflated ' - f'(valid={report["valid"]})' - ) - print( - f' records: {report["record_count"]:,} ' - f'(arrays={report["array_records"]:,} exact={report["array_size_exact"]:,}, ' - f'structs={report["struct_records"]:,} wrappers={report["struct_wrappers"]:,})' - ) - print( - f' trees: {report["root_count"]:,} roots ({report["distinct_root_hashes"]:,} distinct hashes), ' - f'bijection={report["root_bijection_holds"]}, ' - f'preorder={report["contiguous_preorder"]}, ' - f'nodes min/med/max={report["tree_nodes_min"]}/{report["tree_nodes_median"]}/{report["tree_nodes_max"]}, ' - f'depth {report["tree_depth_min"]}..{report["tree_depth_max"]}' - ) - print( - f' pointers: {report["resolved_pointers"]:,}/{report["total_pointers"]:,} resolved ' - f'(forward={report["forward_edges"]:,}, unresolved={report["unresolved_pointers"]})' - ) - print(f' array strides: {report["array_strides"]} ({report["distinct_element_type_hashes"]} element hashes)') - print(f' struct sizes: {report["struct_sizes"]} ({report["distinct_struct_type_hashes"]} struct hashes)') - if "root_query" in report: - rq = report["root_query"] - print(f' --root-hash {rq["hash"]}: {rq["matches"]} match(es) {rq["trees"]}') - if "type_query" in report: - tq = report["type_query"] - print( - f' --type-hash {tq["hash"]}: arrays={tq["array_matches"]}, ' - f'structs={tq["struct_matches"]}, distinct_trees={tq["distinct_trees"]}' - ) - - -def main(argv=None) -> int: - ap = argparse.ArgumentParser(description=__doc__.splitlines()[0]) - ap.add_argument("target", help="carved script directory, script.rpf archive, or joined .bin file") - ap.add_argument("--root-hash", help="inspect subtrees for this u32 root hash (hex)") - ap.add_argument("--type-hash", help="summarize array/struct records matching this u32 type hash (hex)") - ap.add_argument("--json", help="write aggregate statistics JSON to this file") - a = ap.parse_args(argv) - - try: - root_h = _parse_hex_u32(a.root_hash) if a.root_hash is not None else None - type_h = _parse_hex_u32(a.type_hash) if a.type_hash is not None else None - if a.json: - rows = gm._read_index_rows(a.target) if os.path.isdir(a.target) and os.path.isfile(os.path.join(a.target, "index.json")) else None - check_report_path(a.json, a.target, rows=rows) - blob, meta = load_qtable_payload(a.target) - report = parse_qtable(blob, root_hash=root_h, type_hash=type_h) - except UsageError as e: - print(f"ERROR: {e}", file=sys.stderr) - return 2 - except FileNotFoundError: - print(f"ERROR: {a.target}: does not exist", file=sys.stderr) - return 2 - except OSError as e: - print(f"ERROR: cannot read {a.target}: {e.strerror or e}", file=sys.stderr) - return 2 - except (ValueError, KeyError, TypeError, struct.error, RuntimeError) as e: - print(f"ERROR: {e}", file=sys.stderr) - return 1 - - out = {"location": meta, **report} - _print_summary(out) - - if a.json: - try: - gm._make_parent(a.json) - with open(a.json, "w", encoding="utf-8", newline="\n") as f: - json.dump(out, f, indent=1) - except OSError as e: - print(f"ERROR: cannot write {a.json}: {e.strerror or e}", file=sys.stderr) - return 2 - print("wrote", a.json) - - return 0 if report["valid"] else 1 - - -if __name__ == "__main__": - try: # a redirected stdout is strict ANSI code page under -I; write '?' for what it cannot encode - sys.stdout.reconfigure(errors="replace") - except (AttributeError, ValueError, OSError): - pass - sys.exit(main()) diff --git a/tools/sdwa_diff.py b/tools/sdwa_diff.py deleted file mode 100644 index 726e06f38..000000000 --- a/tools/sdwa_diff.py +++ /dev/null @@ -1,831 +0,0 @@ -r"""Differential fuzzing of SDWA (sub-dword addressing) VALU forms. Standard library only. - -Generates seeded straight-line programs of `_sdwa` VOP1/VOP2/VOPC instructions, one lane, runs them through - - * the reference below, written from the RDNA2 ISA guide's SDWA description and each opcode's pseudocode, and - * tools/rdna2spirv.py, executing the SPIR-V with tests/semantic/spirv_mini_interp.py, - -and compares four exported words bit for bit: three VGPRs and VCC (through v_cndmask_b32_e64). The reference does -not share code with the translator or with tools/cpu_ref.py. - -What is modelled, per instruction: - * sources: VGPRs v1..v7, SGPRs s4..s7 (seeded with s_mov_b32, so the translator knows them as constants), integer - inline constants -16..64 and float inline constants (0.5, 1.0, 2.0, 4.0 and their negatives). A float constant - in an f16 op (v_cmp_class_f16's mask included) is the f16 value over a zero high half, in any other op - (v_cvt_f16_{u16,i16} included) its f32 bits. A source is narrowed to src0_sel/src1_sel (BYTE_0..3, WORD_0/1, - DWORD), constants too, zero-extended, or sign-extended under sext() (integer ops); then neg/abs (f16 ops, on - the sign bit of the f16 word) and the op. - * dst_sel and dst_unused: the result's low bits go to the selected field; UNUSED_PAD zeroes the other bits, - UNUSED_SEXT fills the bits above the field with its top bit (bits below stay zero), UNUSED_PRESERVE keeps them. - A 16-bit result (f16 ops, v_cvt_{u16,i16}_f16, v_cvt_f16_{u16,i16}) with dst_sel:DWORD zeroes the high half, - whatever dst_unused says: unlike the non-SDWA forms (docs/design.md "16-bit results"), which keep it. - * clamp: unsigned saturation on v_add/sub/subrev_nc_u32, [0, 1] on f16 results (clamp(-0) = +0) and on - v_cvt_f32_f16. - * f16 arithmetic rounds to nearest even with denormals kept (the MODE the translator assumes); min/max order -0 - below +0; v_fract_f16(-0) = +0 and the result stops at 0x3bff. - * VOPC writes VCC (one bit, this lane); v_cndmask_b32 reads it. -Every one of these rules was checked against an RDNA2 GPU (AMD Radeon iGPU, gfx1036, Windows driver 26.10.1) with ---oracle hw, the f16 constant, dst_sel:DWORD and v_fract_f16(-0) rules included. - -The int family is the 32-bit integer VOP2 ops, v_cndmask_b32, the integer VOP1 ops and v_cvt_f32_{u32,i32,ubyteN}, -and the 32- and 16-bit integer compares. The f16 family is v_add/sub/subrev/mul/min/max_f16, the f16 rounding ops -and v_fract_f16, the f16 <-> 16-bit integer and f16 -> f32 conversions, the f16 compares and v_cmp_class_f16. ---list-ops prints them. Not generated: omod, v_cmpx, an SGPR destination for VOPC, DPP, literals (SDWA has none), -transcendentals, f32 arithmetic. - -Skips (counted with their reasons): an f16 NaN operand of an op whose NaN result or IEEE-mode NaN rule is not -modelled (the compares and v_cmp_class_f16 take NaNs), v_fract_f16 of an infinity, and anything the translator or -the interpreter does not take. - -Known divergences (KNOWN_DIVERGENCES): by default the generator leaves out the forms where the translator is known to -differ from the hardware, so that a run shows new problems only; --known puts them back (a hardware-only run always -has them): - * a constant shift amount (inline constant or seeded SGPR) for v_lshlrev_b32 / v_lshrrev_b32 / v_ashrrev_i32 with - src0_sel other than DWORD or sext(): the translator's constant fold shifted by the whole constant (#2005). -Two forms that used to be listed here are generated in every run again now that main translates them: a 16-bit -result with dst_sel:DWORD (the high half zeroed, #2187) and a float inline constant with a src_sel other than DWORD -in an f16 op (the selection made from the f16 value, #2209). - -With --oracle hw the same programs also run natively on an AMD GPU (tools/hw_oracle/) and the hardware's four words -are compared with the reference: that validates the reference itself. SDWA exists on GFX9 and GFX10 only, so the -hardware oracle needs an RDNA1/RDNA2 GPU; anything else exits 77, like a missing tool. The kernel runs on one lane -of a wave32 compute dispatch, so IEEE mode is on there (it only changes NaN rules, which are skipped). - -Usage: - python -I tools/sdwa_diff.py [--programs N] [--seed S] [--max-ops N] [--ops v_add_f16,v_cmp_lt_u16] - python -I tools/sdwa_diff.py --family f16 # int, f16 or all (default) - python -I tools/sdwa_diff.py --known # also the forms in KNOWN_DIVERGENCES - python -I tools/sdwa_diff.py --oracle hw # hardware vs reference only - python -I tools/sdwa_diff.py --oracle translator,hw - python -I tools/sdwa_diff.py --list-ops - python -I tools/sdwa_diff.py --self-test - -Exit 0 when every program matches, 1 on a mismatch (the shortest failing program is printed after removing -instructions that do not matter), 2 on a harness error, 77 when the requested hardware oracle is unavailable. -""" -import argparse -import gc -import math -import os -import random -import re -import struct -import sys -import tempfile -import warnings - -HERE = os.path.dirname(os.path.abspath(__file__)) -sys.dont_write_bytecode = True -if HERE not in sys.path: - sys.path.insert(0, HERE) -SEM_DIR = os.path.join(os.path.dirname(HERE), "tests", "semantic") -if SEM_DIR not in sys.path: - sys.path.insert(0, SEM_DIR) - -M32 = 0xFFFFFFFF -STUB_DXBC = b"DXBC" + bytes(24) + struct.pack("> 31 else x - - -def sx(x, w): - x &= (1 << w) - 1 - return x - (1 << w) if x >> (w - 1) else x - - -# ---- f16 helpers (bit patterns in, bit patterns out) ------------------------------------------------------ - -def h2f(h): - return struct.unpack(" 0 else 0xFC00 - - -def f2u(x): - return struct.unpack("> 15 == 0), (h2f(b), b >> 15 == 0) - if want_max: - return a if ka > kb else b - return a if ka < kb else b - return op - - -def f16_round(fn): - def op(a, b=0): - a &= 0xFFFF - _no_nan(a) - x = h2f(a) - if math.isinf(x): - return a - return f2h(math.copysign(float(fn(x)), x)) - return op - - -def f16_fract(a, b=0): - a &= 0xFFFF - _no_nan(a) - x = h2f(a) - if math.isinf(x): - raise Skip("reference: v_fract_f16 of an infinity (NaN result)") - # x + -floor(x): fract(-0) = -0 + +0 = +0 (gfx1036); the result stops at the largest f16 below 1.0 - fl = math.copysign(float(math.floor(x)), x) if math.floor(x) == 0 else float(math.floor(x)) # floor(-0) = -0 - return min(f2h(x + -fl), 0x3BFF) - - -def cvt_u16_f16(a, b=0): - a &= 0xFFFF - _no_nan(a) - x = h2f(a) - return 0 if x <= 0 else 0xFFFF if x >= 65535 else int(x) - - -def cvt_i16_f16(a, b=0): - a &= 0xFFFF - _no_nan(a) - x = h2f(a) - if x >= 32767: - return 0x7FFF - if x <= -32768: - return 0x8000 - return int(x) & 0xFFFF - - -def cmp_class_f16(a, b): - a &= 0xFFFF - e, m, neg = (a >> 10) & 0x1F, a & 0x3FF, a >> 15 - if e == 0x1F: - bit = (0 if not m >> 9 else 1) if m else (2 if neg else 9) - elif e == 0: - bit = (4 if neg else 7) if m else (5 if neg else 6) - else: - bit = 3 if neg else 8 - return (b >> bit) & 1 - - -def ffbh_i32(a): - a &= M32 - if a in (0, M32): - return M32 - x = a ^ M32 if a >> 31 else a - return 32 - x.bit_length() - - -# ---- the reference: one entry per opcode ------------------------------------------------------------- -# (family, form, width, fn). family "int" / "f16" decides the modifiers (sext vs neg/abs) and how a float inline -# constant reads. form: "vop2" d, a, b; "vop1" d, a; "vopc" vcc, a, b; "cndmask" d, a, b, vcc. -# width: bits of the result (16 or 32); a 16-bit result has a zero high half under dst_sel:DWORD. -# fn(a, b) gets the selected 32-bit sources and returns the result (a bit for "vopc"). - -def _ops(): - ops = {} - - def add(name, family, form, fn, width=32, clamp=None): - ops[name] = (family, form, width, fn, clamp) - - usat = "usat" - add("v_add_nc_u32", "int", "vop2", lambda a, b: a + b, clamp=usat) - add("v_sub_nc_u32", "int", "vop2", lambda a, b: a - b, clamp=usat) - add("v_subrev_nc_u32", "int", "vop2", lambda a, b: b - a, clamp=usat) - add("v_and_b32", "int", "vop2", lambda a, b: a & b) - add("v_or_b32", "int", "vop2", lambda a, b: a | b) - add("v_xor_b32", "int", "vop2", lambda a, b: a ^ b) - add("v_xnor_b32", "int", "vop2", lambda a, b: ~(a ^ b)) - add("v_lshlrev_b32", "int", "vop2", lambda a, b: b << (a & 31)) - add("v_lshrrev_b32", "int", "vop2", lambda a, b: (b & M32) >> (a & 31)) - add("v_ashrrev_i32", "int", "vop2", lambda a, b: s32(b) >> (a & 31)) - add("v_mul_u32_u24", "int", "vop2", lambda a, b: (a & 0xFFFFFF) * (b & 0xFFFFFF)) - add("v_mul_hi_u32_u24", "int", "vop2", lambda a, b: ((a & 0xFFFFFF) * (b & 0xFFFFFF)) >> 32) - add("v_mul_i32_i24", "int", "vop2", lambda a, b: sx(a, 24) * sx(b, 24)) - add("v_mul_hi_i32_i24", "int", "vop2", lambda a, b: (sx(a, 24) * sx(b, 24)) >> 32) - add("v_min_u32", "int", "vop2", lambda a, b: min(a & M32, b & M32)) - add("v_max_u32", "int", "vop2", lambda a, b: max(a & M32, b & M32)) - add("v_min_i32", "int", "vop2", lambda a, b: min(s32(a), s32(b))) - add("v_max_i32", "int", "vop2", lambda a, b: max(s32(a), s32(b))) - add("v_cndmask_b32", "int", "cndmask", None) - add("v_mov_b32", "int", "vop1", lambda a, b: a) - add("v_not_b32", "int", "vop1", lambda a, b: ~a) - add("v_bfrev_b32", "int", "vop1", lambda a, b: int(f"{a & M32:032b}"[::-1], 2)) - add("v_ffbh_u32", "int", "vop1", lambda a, b: M32 if not a & M32 else 32 - (a & M32).bit_length()) - add("v_ffbl_b32", "int", "vop1", lambda a, b: M32 if not a & M32 else ((a & -a) & M32).bit_length() - 1) - add("v_ffbh_i32", "int", "vop1", lambda a, b: ffbh_i32(a)) - add("v_cvt_f32_u32", "int", "vop1", lambda a, b: f2u(float(a & M32))) - add("v_cvt_f32_i32", "int", "vop1", lambda a, b: f2u(float(s32(a)))) - for n in range(4): - add(f"v_cvt_f32_ubyte{n}", "int", "vop1", lambda a, b, n=n: f2u(float((a >> (8 * n)) & 0xFF))) - cmps = {"f": lambda a, b: False, "lt": lambda a, b: a < b, "eq": lambda a, b: a == b, - "le": lambda a, b: a <= b, "gt": lambda a, b: a > b, "ne": lambda a, b: a != b, - "ge": lambda a, b: a >= b, "t": lambda a, b: True} - for c, f in cmps.items(): - add(f"v_cmp_{c}_u32", "int", "vopc", lambda a, b, f=f: f(a & M32, b & M32)) - add(f"v_cmp_{c}_i32", "int", "vopc", lambda a, b, f=f: f(s32(a), s32(b))) - if c not in ("f", "t"): # GFX10 has no v_cmp_f/t_{i16,u16} - add(f"v_cmp_{c}_u16", "int", "vopc", lambda a, b, f=f: f(a & 0xFFFF, b & 0xFFFF)) - add(f"v_cmp_{c}_i16", "int", "vopc", lambda a, b, f=f: f(sx(a, 16), sx(b, 16))) - - fclamp = "f16" - add("v_add_f16", "f16", "vop2", f16_bin(lambda x, y: x + y), 16, fclamp) - add("v_sub_f16", "f16", "vop2", f16_bin(lambda x, y: x - y), 16, fclamp) - add("v_subrev_f16", "f16", "vop2", f16_bin(lambda x, y: y - x), 16, fclamp) - add("v_mul_f16", "f16", "vop2", f16_bin(lambda x, y: x * y), 16, fclamp) - add("v_max_f16", "f16", "vop2", f16_minmax(True), 16, fclamp) - add("v_min_f16", "f16", "vop2", f16_minmax(False), 16, fclamp) - add("v_floor_f16", "f16", "vop1", f16_round(math.floor), 16, fclamp) - add("v_ceil_f16", "f16", "vop1", f16_round(math.ceil), 16, fclamp) - add("v_trunc_f16", "f16", "vop1", f16_round(math.trunc), 16, fclamp) - add("v_rndne_f16", "f16", "vop1", f16_round(round), 16, fclamp) - add("v_fract_f16", "f16", "vop1", f16_fract, 16, fclamp) - add("v_cvt_f32_f16", "f16", "vop1", lambda a, b: f2u(h2f(a)) if not is_nan16(a) else _no_nan(a), 32, "f32") - add("v_cvt_u16_f16", "f16", "vop1", cvt_u16_f16, 16) - add("v_cvt_i16_f16", "f16", "vop1", cvt_i16_f16, 16) - add("v_cvt_f16_u16", "int16", "vop1", lambda a, b: f2h(float(a & 0xFFFF)), 16, fclamp) - add("v_cvt_f16_i16", "int16", "vop1", lambda a, b: f2h(float(sx(a, 16))), 16, fclamp) - - def fcmp(pred): - def op(a, b): - a, b = a & 0xFFFF, b & 0xFFFF - x, y = h2f(a), h2f(b) - unordered = math.isnan(x) or math.isnan(y) - return pred(x, y, unordered) - return op - fcmps = {"f": lambda x, y, u: False, "lt": lambda x, y, u: x < y, "eq": lambda x, y, u: x == y, - "le": lambda x, y, u: x <= y, "gt": lambda x, y, u: x > y, "lg": lambda x, y, u: not u and x != y, - "ge": lambda x, y, u: x >= y, "o": lambda x, y, u: not u, "u": lambda x, y, u: u, - "nge": lambda x, y, u: not x >= y, "nlg": lambda x, y, u: u or x == y, "ngt": lambda x, y, u: not x > y, - "nle": lambda x, y, u: not x <= y, "neq": lambda x, y, u: not x == y, "nlt": lambda x, y, u: not x < y, - "tru": lambda x, y, u: True} - for c, p in fcmps.items(): - add(f"v_cmp_{c}_f16", "f16", "vopc", fcmp(p)) - add("v_cmp_class_f16", "f16", "vopc", lambda a, b: cmp_class_f16(a, b & 0x3FF)) - return ops - - -OPS = _ops() -CLAMP_OPS = tuple(sorted(o for o, v in OPS.items() if v[4])) - - -# ---- program text: parsing ---------------------------------------------------------------------------- - -_SRC = re.compile(r"^(?P-)?(?P\|)?(?:sext\((?P[^)]+)\)|(?P[^|]+))\|?$") - - -def parse_src(tok): - """{'tok': register or constant text, 'neg', 'abs', 'sext'}.""" - tok = tok.strip() - if tok in FLOAT_CONSTS or re.fullmatch(r"-?\d+", tok): - return {"tok": tok, "neg": False, "abs": False, "sext": False} # -16 is a constant, not neg(16) - m = _SRC.match(tok) - if not m: - raise RefError(f"source {tok!r}") - t = m.group("sx") or m.group("tok") - return {"tok": t.strip(), "neg": bool(m.group("neg")), "abs": bool(m.group("abs")), "sext": bool(m.group("sx"))} - - -def parse(line): - """(op without _sdwa, [operand texts], {modifier: value}, clamp) for one SDWA line.""" - op, _, rest = line.partition(" ") - if not op.endswith("_sdwa"): - raise RefError(f"not an SDWA line: {line!r}") - mods = dict(m.split(":", 1) for m in re.findall(r"\b(?:src0_sel|src1_sel|dst_sel|dst_unused):\w+", rest)) - clamp = bool(re.search(r"\bclamp\b", rest)) - body = re.split(r"\s+(?:clamp|src0_sel|src1_sel|dst_sel|dst_unused)\b", rest, maxsplit=1)[0] - return op[:-len("_sdwa")], [a.strip() for a in body.split(",")], mods, clamp - - -# ---- the reference interpreter ------------------------------------------------------------------------ - -class State: - def __init__(self): - self.v, self.s, self.vcc = {}, {}, 0 - - -def read_raw(st, tok, f16): - if tok.startswith("v") and tok[1:].isdigit(): - return st.v.get(int(tok[1:]), 0) - if tok.startswith("s") and tok[1:].isdigit(): - return st.s.get(int(tok[1:]), 0) - if tok in FLOAT_CONSTS: - return FLOAT_CONSTS_F16[tok] if f16 else FLOAT_CONSTS[tok] - return int(tok, 0) & M32 - - -def select(value, sel, sext): - off, w = SEL[sel] - v = (value >> off) & ((1 << w) - 1) - if sext and w < 32: - v = sx(v, w) & M32 - return v - - -def place(old, res, width, sel, unused): - off, w = SEL[sel] - res &= M32 - if w == 32: - return res & 0xFFFF if width == 16 else res - field = res & ((1 << w) - 1) - if unused == "UNUSED_PRESERVE": - mask = ((1 << w) - 1) << off - return (old & ~mask & M32) | (field << off) - if unused == "UNUSED_SEXT": - return (sx(field, w) << off) & M32 - return field << off - - -def _clamp(kind, r): - if kind == "usat": - return max(0, min(M32, r)) - if kind == "f16": - if r & 0x8000: # negative, -0 included - return 0 - return min(r, 0x3C00) # +inf and anything above 1.0 (NaN results are skipped) - if kind == "f32": - if r & 0x80000000: - return 0 - return min(r, 0x3F800000) - return r - - -def step(st, line): - op, args, mods, clamp = parse(line) - if op not in OPS: - raise RefError(f"{op} is not modelled") - family, form, width, fn, clamp_kind = OPS[op] - if clamp and not clamp_kind: - raise RefError(f"{op}: clamp not modelled") - f16 = family == "f16" - srcs = args[1:3] if form in ("vop2", "vopc", "cndmask") else args[1:2] - vals = [] - for i, text in enumerate(srcs): - s = parse_src(text) - v = select(read_raw(st, s["tok"], f16), - mods.get(f"src{i}_sel", "DWORD"), s["sext"]) - if s["abs"]: - v &= ~0x8000 if f16 else ~0x80000000 - if s["neg"]: - v ^= 0x8000 if f16 else 0x80000000 - vals.append(v & M32) - if form == "vopc": - st.vcc = int(bool(fn(vals[0], vals[1]))) - return - if form == "cndmask": - r = vals[1] if st.vcc else vals[0] - else: - r = fn(vals[0], vals[1] if len(vals) > 1 else 0) - r = _clamp(clamp_kind, r) if clamp else r - d = int(args[0][1:]) - st.v[d] = place(st.v.get(d, 0), r, width, mods.get("dst_sel", "DWORD"), mods.get("dst_unused", "UNUSED_PAD")) - - -def reference(lines): - """Run the program; returns the four exported words. Raises Skip for what the reference does not model.""" - st = State() - for line in lines: - op, _, rest = line.partition(" ") - args = [a.strip() for a in rest.split(",")] - if op == "v_mov_b32": - st.v[int(args[0][1:])] = read_raw(st, args[1], False) - elif op == "s_mov_b32": - if args[0] == "vcc_lo": - st.vcc = int(args[1], 0) & 1 - else: - st.s[int(args[0][1:])] = int(args[1], 0) & M32 - elif op == "v_cndmask_b32_e64": - st.v[int(args[0][1:])] = int(args[2], 0) if st.vcc else int(args[1], 0) - else: - step(st, line) - return [st.v.get(r, 0) for r in (8, 9, 10, 11)] - - -# ---- program generation ------------------------------------------------------------------------------- - -def _word(rng): - r = rng.random() - if r < 0.35: - return rng.choice(INTERESTING) - if r < 0.7: - return _half(rng) | _half(rng) << 16 - return rng.getrandbits(32) - - -def _half(rng): - r = rng.random() - if r < 0.5: - return rng.choice(F16_INTERESTING) - if r < 0.65: - return rng.randrange(0, 0x400) | rng.choice((0, 0x8000)) # denormal - h = rng.getrandbits(16) - while is_nan16(h): - h = rng.getrandbits(16) - return h - - -def _src(rng, family, allow_const=True): - """An operand text for a source of an op of this family.""" - r = rng.random() - if r < 0.68 or not allow_const: - tok = f"v{rng.choice(VREGS)}" if r < 0.55 or not allow_const else f"s{rng.choice(SREGS)}" - elif r < 0.9: - tok = str(rng.choice((-16, -1, 0, 1, 2, 7, 15, 16, 24, 31, 32, 63, 64, rng.randrange(-16, 65)))) - else: - return rng.choice(tuple(FLOAT_CONSTS)) - if family == "cndmask": - return tok # llvm-mc takes no sext() on v_cndmask_b32_sdwa - if family in ("int", "int16"): - return f"sext({tok})" if rng.random() < 0.3 else tok - if not tok[0] in "vs": - return tok - if rng.random() < 0.2: - tok = f"|{tok}|" - if rng.random() < 0.25: - tok = "-" + tok - return tok - - -KNOWN = False # also generate the forms in KNOWN_DIVERGENCES (--known; always on for a hardware-only run) -SHIFTS = ("v_lshlrev_b32", "v_lshrrev_b32", "v_ashrrev_i32") -KNOWN_DIVERGENCES = { - "shift-const-sel": "a constant shift amount (inline or seeded SGPR) with src0_sel or sext(): until #2005 the " - "translator shifts by the whole constant", -} - - -def emit(rng, name): - family, form, width, fn, clamp_kind = OPS[name] - sels = tuple(SEL) - s0, s1 = rng.choice(sels), rng.choice(sels) - if form == "vopc": - src1_family = "int" if name == "v_cmp_class_f16" else family - a, b = _src(rng, family), _src(rng, src1_family) - else: - d = f"v{rng.choice(VREGS)}" - clamp = " clamp" if clamp_kind and rng.random() < 0.25 else "" - dsel = rng.choice(sels) - unused = rng.choice(UNUSED) - a = _src(rng, "cndmask" if form == "cndmask" else family) - b = _src(rng, "cndmask" if form == "cndmask" else family) if form != "vop1" else None - if form == "cndmask" and a[0] == b[0] == "s" and a != b: - b = f"v{rng.choice(VREGS)}" # VCC is on the constant bus too: at most one other SGPR (gfx1030) - if not KNOWN: - inner = a[5:-1] if a.startswith("sext(") else a - if name in SHIFTS and inner[0] != "v": - s0, a = "DWORD", inner - if form == "vopc": - return f"{name}_sdwa vcc_lo, {a}, {b} src0_sel:{s0} src1_sel:{s1}" - tail = f"{clamp} dst_sel:{dsel} dst_unused:{unused} src0_sel:{s0}" - if form == "vop1": - return f"{name}_sdwa {d}, {a}{tail}" - vcc = ", vcc_lo" if form == "cndmask" else "" - return f"{name}_sdwa {d}, {a}, {b}{vcc}{tail} src1_sel:{s1}" - - -def seeds(rng): - return ([f"v_mov_b32 v{r}, 0x{_word(rng):x}" for r in VREGS] + [f"s_mov_b32 s{r}, 0x{_word(rng):x}" for r in SREGS] - + [f"s_mov_b32 vcc_lo, {rng.randrange(2)}"]) - - -def observe(regs): - return [f"v_mov_b32 v8, v{regs[0]}", f"v_mov_b32 v9, v{regs[1]}", f"v_mov_b32 v10, v{regs[2]}", - "v_cndmask_b32_e64 v11, 0, 1, vcc_lo"] - - -def generate(rng, n_ops, ops): - body = [emit(rng, rng.choice(ops)) for _ in range(n_ops)] - written = [] - for line in reversed(body): - d = line.split()[1].rstrip(",") - if d[0] == "v" and d[1:].isdigit() and d not in written: - written.append(d) - regs = [int(d[1:]) for d in written[:3]] - regs += rng.sample([r for r in VREGS if r not in regs], 3 - len(regs)) - return seeds(rng) + body + observe(regs) - - -# ---- the translator side ------------------------------------------------------------------------------ - -def translated(lines, name="ps_sdwa"): - """Translate and execute; returns the four exported words, or raises Skip.""" - import rdna2spirv - from spirv_mini_interp import run_fragment - with tempfile.TemporaryDirectory(prefix="sdwa-diff-") as tmp: - dis = os.path.join(tmp, "disasm") - os.mkdir(dis) - path = os.path.join(dis, name + ".s") - with open(path, "w", encoding="utf-8", newline="\n") as f: - f.write(f"; {name} sdwa_diff case\n") - for line in lines: - f.write("\t" + line + "\n") - f.write("\texp mrt0 v8, v9, v10, v11 done vm\n\ts_endpgm\n") - with open(os.path.join(tmp, name + ".dxbc"), "wb") as f: - f.write(STUB_DXBC) - try: - with warnings.catch_warnings(): - warnings.simplefilter("ignore", ResourceWarning) - spvasm = rdna2spirv.translate(path) - gc.collect() - except rdna2spirv.Unsupported as e: - raise Skip(f"translator unsupported: {e}") from None - try: - out = run_fragment(spvasm) - except Exception as e: # noqa: BLE001 - an interpreter gap is a counted skip, never a pass - raise Skip(f"mini_interp: {type(e).__name__}: {str(e)[:80]}") from None - return [w & M32 for w in out["%out_mrt0"]] - - -def _diff(lines, want, got, label): - bad = [k for k in range(4) if want[k] != got[k]] - if not bad: - return None - i = bad[0] - what = "VCC" if i == 3 else lines[-N_OBS + i].split(", ")[1] - return f"word {i} ({what}): reference 0x{want[i]:08x}, {label} 0x{got[i]:08x}" - - -def check(lines, backends=("translator",), hw=None): - """None on a match, else a description. Raises Skip (the reference or every backend skipped) / RefError. - hw is the hardware result for this program (four words or a str reason), or a callable lines -> that.""" - want = reference(lines) - problems, skips = [], [] - if "translator" in backends: - try: - problems.append(_diff(lines, want, translated(lines), "translated")) - except Skip as e: - skips.append(e) - if "hw" in backends: - got = hw(lines) if callable(hw) else hw - if isinstance(got, str): - skips.append(Skip(f"hardware: {got}")) - else: - problems.append(_diff(lines, want, got, "hardware")) - if skips and len(skips) == len(backends): - raise skips[0] - return "; ".join(p for p in problems if p) or None - - -def shrink(lines, check_fn=check): - """Drop instructions (not the seeds or the observation) while the program still mismatches.""" - body = lines[N_SEED:-N_OBS] - changed = True - while changed: - changed = False - for i in range(len(body)): - trial = lines[:N_SEED] + body[:i] + body[i + 1:] + lines[-N_OBS:] - try: - if check_fn(trial): - body = body[:i] + body[i + 1:] - changed = True - break - except (Skip, RefError): - continue - return lines[:N_SEED] + body + lines[-N_OBS:] - - -def vk_verdict(lines, hw, got): - """(class, detail) for a program translated and run on a Vulkan GPU against the hardware's four words: match, nan - (the words differ and the reference declines the program for an f16 NaN: its payload and the IEEE-mode NaN rules are - not modelled, and the hardware kernels run with IEEE on where the translator assumes the game's MODE) or mismatch.""" - for k in range(4): - if hw[k] != got[k]: - try: - reference(lines) - except Skip as e: - if "NaN" in str(e): - return "nan", str(e) - except RefError: - pass - what = "VCC" if k == 3 else lines[-N_OBS + k].split(", ")[1] - return "mismatch", f"word {k} ({what}): hardware 0x{hw[k]:08x}, translated on the GPU 0x{got[k]:08x}" - return "match", "" - - -def hw_prepare(oracle, programs, wave=32): - """Run every program on the hardware in batches. Returns per program the four words, or a str reason. wave 64 runs - each in a wave64 wave with VCC as a 64-bit lane mask.""" - if wave == 64: - import vk_fuzz_run - from hw_oracle import asm - programs = [asm.Kernel([vk_fuzz_run.wave64_text(ln) for ln in p], wave=64, threads=1, words=4) - for p in programs] - return oracle.run(programs) - - -def run_suite(programs, seed, max_ops, ops, backends=("translator",), oracle=None, wave=32, build=None, work=None, - vk_constants=False): - counts = {"pass": 0, "mismatch": 0, "skip": {}, "vk": {}, "vk_failures": []} - failures = [] - rng = random.Random(seed) - progs = [generate(rng, rng.randrange(1, max_ops + 1), ops) for _ in range(programs)] - hw_words = hw_prepare(oracle, progs, wave) if "hw" in backends else [None] * programs - if "vk" in backends: - import vk_fuzz_run - counts["vk"], counts["vk_failures"] = vk_fuzz_run.judge(progs, hw_words, vk_verdict, wave=wave, - build=build, work_parent=work, opaque=not vk_constants, - uniform=False) - backends = tuple(b for b in backends if b != "vk") - for i, lines in enumerate(progs): - try: - problem = check(lines, backends, hw_words[i]) - except Skip as e: - counts["skip"][str(e)] = counts["skip"].get(str(e), 0) + 1 - continue - if problem is None: - counts["pass"] += 1 - continue - counts["mismatch"] += 1 - failures.append((i, problem, lines)) - return counts, failures - - -def self_test(): - base = [f"v_mov_b32 v{r}, 0x{0x11111111 * r:x}" for r in VREGS] + [f"s_mov_b32 s{r}, {r}" for r in SREGS] - base.append("s_mov_b32 vcc_lo, 0") - ok = check(base + ["v_add_nc_u32_sdwa v1, v2, v3 dst_sel:WORD_1 dst_unused:UNUSED_PRESERVE " - "src0_sel:BYTE_1 src1_sel:WORD_0"] + observe([1, 2, 3])) is None - # 0x2222 + 0x33 = 0x2255 into the high word of v1 (0x11111111): 0x22551111 - placed = reference(base + ["v_add_nc_u32_sdwa v1, v2, v3 dst_sel:WORD_1 dst_unused:UNUSED_PRESERVE " - "src0_sel:WORD_0 src1_sel:BYTE_0"] + observe([1, 2, 3]))[0] == 0x22551111 - try: - translated(base + ["v_add_nc_u32_dpp v1, v2, v3 quad_perm:[0,0,0,0] row_mask:0xf bank_mask:0xf" - .replace("_dpp", "_sdwa_dpp")] + observe([1, 2, 3])) - skipped = False - except Skip: - skipped = True - print(f"self-test: match {ok}, placement modelled {placed}, unsupported form skipped {skipped}") - return ok and placed and skipped - - -def main(argv=None): - ap = argparse.ArgumentParser(description="SDWA VOP1/VOP2/VOPC differential fuzzing.") - ap.add_argument("--programs", type=int, default=300) - ap.add_argument("--seed", type=int, default=1) - ap.add_argument("--max-ops", type=int, default=4) - ap.add_argument("--ops", default=None, help="comma-separated opcodes without _sdwa (default: the --family ones)") - ap.add_argument("--family", default="all", choices=("int", "f16", "all")) - ap.add_argument("--list-ops", action="store_true") - ap.add_argument("--self-test", action="store_true") - ap.add_argument("--all-failures", action="store_true", help="print every failing program, not just the first") - ap.add_argument("--oracle", default="translator", - help="comma-separated comparison targets: translator (default), hw (natively on an RDNA1/RDNA2 " - "GPU; see tools/hw_oracle/). 'hw' alone compares the hardware with the reference only") - ap.add_argument("--hw-arch", default=None, help="GPU architecture to assemble for (default: detected)") - ap.add_argument("--wave", type=int, choices=(32, 64), default=32, - help="the wave size of the hardware kernels and of the vk programs (64 needs native 64-wide " - "subgroups; lane 0 is judged)") - ap.add_argument("--build", default=os.path.join(os.path.dirname(HERE), "runtime", "build"), - help="with vk: the folder with vk_compute_test") - ap.add_argument("--vk-constants", action="store_true", - help="with vk: keep the seeds as literal v_mov_b32 constants (the driver may fold them)") - ap.add_argument("--work", default=None, help="with vk: a folder for the temporary files (VK_FUZZ_KEEP=1 keeps them)") - ap.add_argument("--known", action="store_true", - help="also generate the forms where the translator is known to differ (KNOWN_DIVERGENCES; " - "always on with --oracle hw alone)") - a = ap.parse_args(argv) - if a.programs < 1 or a.max_ops < 1: - ap.error("--programs and --max-ops must be at least 1") - backends = tuple(dict.fromkeys(t.strip() for t in a.oracle.split(","))) - if not backends or any(t not in ("translator", "hw", "vk") for t in backends): - ap.error("--oracle takes translator, hw, vk (with hw) or a comma-separated mix") - if "vk" in backends and "hw" not in backends: - ap.error("--oracle vk judges the translated programs against the hardware's words: use --oracle hw,vk") - global KNOWN - KNOWN = a.known or backends == ("hw",) - if a.list_ops: - for name in sorted(OPS): - family, form, width, _, clamp = OPS[name] - print(f"{name:20} {'f16' if family == 'f16' else 'int'} {form}{' clamp' if clamp else ''}") - return 0 - if a.self_test: - return 0 if self_test() else 1 - if a.ops is not None: - tokens = [t.strip() for t in a.ops.split(",")] - if not any(tokens) or any(not t for t in tokens): - ap.error("--ops must be a comma-separated list of opcodes") - ops = sorted(set(tokens)) - else: - ops = sorted(o for o, v in OPS.items() - if a.family == "all" or (a.family == "f16") == (v[0] == "f16")) - unknown = [o for o in ops if o not in OPS] - if unknown: - ap.error("unknown ops: " + ", ".join(unknown)) - oracle = None - if "hw" in backends: - from hw_oracle import asm, runner - try: - oracle = runner.open_oracle(arch=a.hw_arch) - except runner.Unavailable as e: - print(f"hardware oracle unavailable: {e}") - return 77 - if asm.family(oracle.arch) != "gfx10": - print(f"hardware oracle unavailable: {oracle.arch} has no SDWA (GFX9 and GFX10 only)") - oracle.close() - return 77 - print(f"hardware oracle: {oracle.device}") - try: - counts, failures = run_suite(a.programs, a.seed, a.max_ops, ops, backends, oracle, a.wave, a.build, a.work, - a.vk_constants) - vk_bad = counts.pop("vk_failures") - skips = sum(counts["skip"].values()) - print(f"{a.programs} programs (seed {a.seed}, {'+'.join(backends)}): {counts['pass']} pass, " - f"{counts['mismatch']} mismatch, {skips} skipped") - for reason, n in sorted(counts["skip"].items(), key=lambda kv: -kv[1]): - print(f" skip x{n}: {reason}") - - want_vk = "vk" in backends - if want_vk: - print(f"translated on the Vulkan GPU (wave{a.wave}) against the hardware: " - + ", ".join(f"{k} {n}" for k, n in sorted(counts["vk"].items(), key=lambda kv: kv[0].startswith("skip")))) - for i, detail, lines in vk_bad[: None if a.all_failures else 3]: - print(f"VK MISMATCH program {i}: {detail}") - print("\n".join("\t" + line for line in lines)) - backends = tuple(b for b in backends if b != "vk") - - def check_fn(lines): - return check(lines, backends, (lambda l: hw_prepare(oracle, [l], a.wave)[0]) if oracle else None) - for i, problem, lines in failures[: None if a.all_failures else 1]: - small = shrink(lines, check_fn) - print(f"MISMATCH program {i}: {check_fn(small) or problem}") - print("\n".join("\t" + line for line in small)) - except (RefError, RuntimeError) as e: - print(f"harness error: {e}") - return 2 - finally: - if oracle: - oracle.close() - if failures or vk_bad: - return 1 - if not counts["pass"]: # nothing was compared: every program was skipped - print("no program ran: every one was skipped") - return 2 - if want_vk: - import vk_fuzz_run - if vk_fuzz_run.all_skipped(counts["vk"]): - print("no Vulkan program ran: every one was skipped") - return 2 - return 0 - - -if __name__ == "__main__": - try: # a redirected stdout is strict ANSI code page under -I; write '?' for what it cannot encode - sys.stdout.reconfigure(errors="replace") - except (AttributeError, ValueError, OSError): - pass - sys.exit(main()) diff --git a/tools/semantic_mutants.py b/tools/semantic_mutants.py deleted file mode 100644 index 2350e0b8b..000000000 --- a/tools/semantic_mutants.py +++ /dev/null @@ -1,286 +0,0 @@ -"""Op-scoped mutation testing for a tests/semantic file: which one-line translator bugs would it miss? - - python -I tools/semantic_mutants.py tests/semantic/test_valu_sad_u8_hw.py --op v_sad_u8 - python -I tools/semantic_mutants.py tests/semantic/test_x.py --op ds_swizzle_b32 --function swizzle - python -I tools/semantic_mutants.py tests/semantic/test_x.py --lines 8375-8414 - -The tool finds the code in tools/rdna2spirv.py that translates the op: the `if op == "..."` / `elif op in (...)` -branch naming it (--op), a whole method (--function), or an explicit line range (--lines). It then makes one-line -mutants of that code with standard operators: swapped opcode pairs (OpIAdd/OpISub, OpBitwiseAnd/Or, shifts), swapped -GLSL.std.450 pairs (UMin/UMax, SMin/UMin, NMin/FMin, Floor/Ceil, ...), comparisons made strict or non-strict or of the -other signedness, small `self.cu(N)` constants moved by one, the two arms of an OpSelect swapped, and the last operand -of an emitted instruction replaced by the one before it. Each mutant is written into a private copy of tools/ (the -repository's own tools/ is never modified) and the test file is run against it through LEONIDA_TOOLS_DIR, as -tests/semantic/test_mutations.py does. A mutant the test file still passes is reported as SURVIVED. - -A surviving mutant is a lead, not a verdict: some mutants are equivalent (they can't change any result, e.g. a -constant that only feeds a branch the op never takes), so read each one before asking for a new case. Exit status: -0 when every mutant is caught, 1 when any survives, 2 on a usage or baseline error (the unmutated copy must pass -first). Synthetic: no game files, no GPU. -""" -from __future__ import annotations - -import argparse -import os -import re -import shutil -import subprocess -import sys -import tempfile -import time -from dataclasses import dataclass - -ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) -TRANSLATOR = "rdna2spirv.py" - -# Whole-token swaps: each pair is tried in both directions where it occurs. -PAIRS = [ - ("OpIAdd", "OpISub"), ("OpBitwiseAnd", "OpBitwiseOr"), ("OpBitwiseOr", "OpBitwiseXor"), - ("OpShiftLeftLogical", "OpShiftRightLogical"), ("OpShiftRightLogical", "OpShiftRightArithmetic"), - ("OpFAdd", "OpFSub"), ("OpFMul", "OpFAdd"), ("OpConvertFToS", "OpConvertFToU"), - ("OpConvertSToF", "OpConvertUToF"), ("OpBitFieldSExtract", "OpBitFieldUExtract"), - ("OpIEqual", "OpINotEqual"), ("OpULessThan", "OpULessThanEqual"), ("OpUGreaterThan", "OpUGreaterThanEqual"), - ("OpSLessThan", "OpSLessThanEqual"), ("OpSGreaterThan", "OpSGreaterThanEqual"), ("OpULessThan", "OpSLessThan"), - ("OpUGreaterThan", "OpSGreaterThan"), ("OpLogicalAnd", "OpLogicalOr"), - ("UMin", "UMax"), ("SMin", "SMax"), ("FMin", "FMax"), ("NMin", "NMax"), ("SMin", "UMin"), ("SMax", "UMax"), - ("NMin", "FMin"), ("NMax", "FMax"), ("SClamp", "UClamp"), ("Floor", "Ceil"), ("Trunc", "Floor"), - ("RoundEven", "Round"), - ("OpAtomicIAdd", "OpAtomicISub"), ("OpAtomicSMin", "OpAtomicUMin"), ("OpAtomicSMax", "OpAtomicUMax"), - ("OpAtomicUMin", "OpAtomicUMax"), ("OpAtomicAnd", "OpAtomicOr"), -] -CU = re.compile(r"self\.cu\((0x[0-9A-Fa-f]+|\d+)\)") -SELECT = re.compile(r"(OpSelect %\w+ \{[^}]+\} )(\{[^}]+\}|%\w+)( )(\{[^}]+\}|%\w+)") -LAST_OPERAND = re.compile(r"(\{[A-Za-z_][\w\[\]]*\}) (\{[A-Za-z_][\w\[\]]*\})(\"\))") - - -@dataclass -class Mutant: - line: int # 1-based line in rdna2spirv.py - label: str - old: str # the whole original line - new: str # the whole mutated line - - -def find_branch(lines: list[str], op: str) -> tuple[int, int]: - """(first, last) 0-based line indices of the if/elif branch whose condition names `op` as a string literal.""" - quoted = f'"{op}"' - for i, line in enumerate(lines): - stripped = line.lstrip() - if not re.match(r"(el)?if\b", stripped) or "op" not in stripped: - continue - cond, j = line, i - while not cond.rstrip().endswith(":") and j + 1 < len(lines): # a condition spread over several lines - j += 1 - cond += lines[j] - if quoted not in cond: - continue - indent = len(line) - len(stripped) - end = j - for k in range(j + 1, len(lines)): - text = lines[k] - if not text.strip(): - continue - if len(text) - len(text.lstrip()) <= indent: - break - end = k - return i, end - raise LookupError(f"no `if op ...` branch names {quoted}; try --function or --lines") - - -def table_mutants(lines: list[str], op: str, limit: int = 6) -> list[Mutant]: - """Mutants for an op translated through a lookup table: `"op": "Value"` inside a dict literal (F1, LDS_ATOMICS, - ...) gets each other value of the same table in turn (at most `limit`), e.g. "InverseSqrt" -> "Sqrt".""" - out: list[Mutant] = [] - entry = re.compile(rf'"{re.escape(op)}"\s*:\s*"([^"]+)"') - for i, line in enumerate(lines): - m = entry.search(line.split("#", 1)[0]) - if not m: - continue - start = i # the dict literal holding the entry: from its `{` ... - while start > 0 and "{" not in lines[start]: - start -= 1 - depth, end = 0, start # ... to the line that closes it - for k in range(start, len(lines)): - depth += lines[k].count("{") - lines[k].count("}") - end = k - if depth <= 0 and k >= i: - break - values: list[str] = [] - for k in range(start, end + 1): - for v in re.findall(r'"[^"]+"\s*:\s*"([^"]+)"', lines[k].split("#", 1)[0]): - if v != m.group(1) and v not in values: - values.append(v) - for v in values[:limit]: - new = line[:m.start(1)] + v + line[m.end(1):] - out.append(Mutant(i + 1, f'table entry "{op}": "{m.group(1)}" -> "{v}"', line, new)) - return out - - -def branch_ops(lines: list[str], first: int) -> list[str]: - """The op names a branch's condition lists (its string literals), in order.""" - cond, j = lines[first], first - while not cond.rstrip().endswith(":") and j + 1 < len(lines): - j += 1 - cond += lines[j] - return re.findall(r'"([a-z][a-z0-9_]*)"', cond) - - -def find_function(lines: list[str], name: str) -> tuple[int, int]: - for i, line in enumerate(lines): - if re.match(rf"\s*def {re.escape(name)}\(", line): - indent = len(line) - len(line.lstrip()) - end = i - for k in range(i + 1, len(lines)): - text = lines[k] - if text.strip() and len(text) - len(text.lstrip()) <= indent: - break - if text.strip(): - end = k - return i, end - raise LookupError(f"no method named {name}") - - -def mutants_for(lines: list[str], first: int, last: int) -> list[Mutant]: - out: list[Mutant] = [] - seen: set[tuple[int, str]] = set() - - def add(i: int, label: str, new: str) -> None: - if new != lines[i] and (i, new) not in seen: - seen.add((i, new)) - out.append(Mutant(i + 1, label, lines[i], new)) - - for i in range(first, last + 1): - line = lines[i] - code = line.split("#", 1)[0] if not line.lstrip().startswith(("f\"", "\"", "'")) else line - if not code.strip() or code.lstrip().startswith("#"): - continue - for a, b in PAIRS: - for x, y in ((a, b), (b, a)): - for m in re.finditer(rf"(? {y}", line[:m.start()] + y + line[m.end():]) - if "emit(" in code or "OpSelect" in code: - for m in CU.finditer(code): - text = m.group(1) - value = int(text, 0) - if value >= 0xFFFFFF00: - continue - for delta in (1, -1): - v = value + delta - if v < 0: - continue - shown = hex(v) if text.lower().startswith("0x") else str(v) - add(i, f"self.cu({text}) -> self.cu({shown})", line[:m.start(1)] + shown + line[m.end(1):]) - m = SELECT.search(code) - if m: - swapped = m.group(1) + m.group(4) + m.group(3) + m.group(2) - add(i, "OpSelect arms swapped", line[:m.start()] + swapped + line[m.end():]) - m = LAST_OPERAND.search(code) - if m: - add(i, f"last operand {m.group(2)} -> {m.group(1)}", - line[:m.start()] + f"{m.group(1)} {m.group(1)}{m.group(3)}" + line[m.end():]) - return out - - -def run_test(test_file: str, tools_dir: str, timeout: int) -> tuple[bool, str]: - """True when the test file passes against tools_dir.""" - here = os.path.dirname(os.path.abspath(test_file)) - path = os.pathsep.join(filter(None, [here, os.path.join(ROOT, "tests", "semantic"), os.environ.get("PYTHONPATH")])) - env = dict(os.environ, LEONIDA_TOOLS_DIR=os.path.abspath(tools_dir), PYTHONDONTWRITEBYTECODE="1", - PYTHONPATH=path) - # Through unittest, as tests/semantic/test_mutations.py does: a file with no `__main__` block runs nothing when - # started as a script, which would pass the baseline and let every mutant survive. - module = os.path.splitext(os.path.basename(test_file))[0] - try: - p = subprocess.run([sys.executable, "-m", "unittest", module], cwd=here, env=env, capture_output=True, - encoding="utf-8", errors="replace", timeout=timeout) - except subprocess.TimeoutExpired: - return False, f"timed out after {timeout} s" - if p.returncode == 5: # unittest's exit status when it found no tests (Python 3.12+) - return False, "no tests ran" - tail = ((p.stdout or "") + (p.stderr or "")).strip().splitlines() - return p.returncode == 0, tail[-1] if tail else "" - - -def main(argv: list[str] | None = None) -> int: - ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) - ap.add_argument("test_file") - where = ap.add_mutually_exclusive_group(required=True) - where.add_argument("--op", help="mutate the if/elif branch that names this op") - where.add_argument("--function", help="mutate this method of the translator") - where.add_argument("--lines", help="mutate this 1-based line range, e.g. 8375-8414") - ap.add_argument("--timeout", type=int, default=300, help="seconds per test run (default 300)") - ap.add_argument("--list", action="store_true", help="only list the mutants") - args = ap.parse_args(argv) - - src_path = os.path.join(ROOT, "tools", TRANSLATOR) - with open(src_path, encoding="utf-8", newline="") as f: - raw = f.read() - sep = "\r\n" if "\r\n" in raw else "\n" - lines = raw.replace("\r\n", "\n").split("\n") - table: list[Mutant] = table_mutants(lines, args.op) if args.op else [] - try: - if args.op: - try: - first, last = find_branch(lines, args.op) - except LookupError: - if not table: - raise LookupError(f'no `if op ...` branch or lookup-table entry names "{args.op}"; ' - "try --function or --lines") from None - first = last = -1 # table-driven only - elif args.function: - first, last = find_function(lines, args.function) - else: - a, b = (int(x) for x in args.lines.split("-")) - if not 1 <= a <= b <= len(lines): - raise LookupError(f"line range {args.lines} is outside 1..{len(lines)}") - first, last = a - 1, b - 1 - except (LookupError, ValueError) as e: - print(f"error: {e}", file=sys.stderr) - return 2 - mutants = (mutants_for(lines, first, last) if first >= 0 else []) + table - where = f"lines {first + 1}-{last + 1}" if first >= 0 else "no branch" - print(f"{TRANSLATOR} {where}" + (f" + {len(table)} table-entry mutants" if table else "") + - f": {len(mutants)} mutants") - if args.op and first >= 0: - named = branch_ops(lines, first) - if len(named) > 1: - # A shared branch also holds the other ops' code; a test of one op can't be expected to catch those. - print(f"the branch also handles: {', '.join(o for o in named if o != args.op)}") - if args.list: - for m in mutants: - print(f" line {m.line}: {m.label}") - return 0 - if not mutants: - return 0 - - with tempfile.TemporaryDirectory(prefix="semantic-mutants-") as tmp: - tools = os.path.join(tmp, "tools") - shutil.copytree(os.path.join(ROOT, "tools"), tools, ignore=shutil.ignore_patterns("__pycache__", "rpf9dump")) - target = os.path.join(tools, TRANSLATOR) - ok, last_line = run_test(args.test_file, tools, args.timeout) - if not ok: - print(f"error: the test file fails on the unmutated translator ({last_line})", file=sys.stderr) - return 2 - survived = 0 - t0 = time.time() - for m in mutants: - mutated = list(lines) - mutated[m.line - 1] = m.new - with open(target, "w", encoding="utf-8", newline="") as f: - f.write(sep.join(mutated)) - ok, last_line = run_test(args.test_file, tools, args.timeout) - if ok: - survived += 1 - print(f" {'SURVIVED' if ok else 'caught '} line {m.line}: {m.label}" - + ("" if ok else f" ({last_line})")) - print(f"{len(mutants) - survived} of {len(mutants)} mutants caught, {survived} survived " - f"({time.time() - t0:.0f} s)") - return 1 if survived else 0 - - -if __name__ == "__main__": - try: # a redirected stdout is strict ANSI code page under -I; write '?' for what it cannot encode - sys.stdout.reconfigure(errors="replace") - except (AttributeError, ValueError, OSError): - pass - sys.exit(main()) diff --git a/tools/sgd5_effects.py b/tools/sgd5_effects.py deleted file mode 100644 index c42d918e4..000000000 --- a/tools/sgd5_effects.py +++ /dev/null @@ -1,277 +0,0 @@ -"""Look up a stored effect/technique pass in the Xbox 1.0.2.1 shaders.rpf. - -python -I tools/sgd5_effects.py PATH/TO/shaders.rpf -python -I tools/sgd5_effects.py PATH/TO/shaders.rpf --list-effects -python -I tools/sgd5_effects.py PATH/TO/shaders.rpf --effect NAME -python -I tools/sgd5_effects.py PATH/TO/shaders.rpf --effect NAME --technique NAME -python -I tools/sgd5_effects.py PATH/TO/shaders.rpf --shader-hash HEX --technique NAME - -The default JSON contains only aggregate counts. A named query also returns -the database, group, ordinal and archive offsets of the selected programs. -Group 0 contains vertex and mesh programs, 1 pixel, 2 geometry and 5 compute. -Groups 3 and 4 are empty in this build. All returned offsets are absolute. -Use carve_offset to join to shader_carve's index.json by offset. Repeated -effect or technique names return every match with its offset and row index. ---shader-hash accepts the Materials[].Shader hex value from an rpf9dump model manifest. -This reads plain metadata in place. Runtime selection of a technique is unknown. -Usage: `python -I tools/sgd5_effects.py --help` lists the options. -""" -import argparse -import json -from pathlib import Path -import re -import struct -import sys -from typing import NamedTuple - -sys.path.insert(0, str(Path(__file__).resolve().parent)) -from hashdict import joaat -from shader_carve import ENTRY - -# SGD5 signature, first native group count, end of the padded effect region. -DATABASES = ((0x9000, 0x10E39, 0x10287000), (0x10287000, 0x10289C81, 0x10579000)) -IDENTIFIER = re.compile(rb"[A-Za-z_][A-Za-z0-9_]{0,254}\x00") -POOL = re.compile(rb"[\x20-\x7e\x00]+") -STRING = re.compile(rb"[^\x00]+\x00") - - -def u32(data, pos=0): - if pos + 4 > len(data): - raise ValueError("truncated SGD5 count") - return struct.unpack_from(" limit: - raise ValueError("program crosses the database boundary") - stream.seek(size + 152, 1) - trailer = u32(stream.read(4)) - if stream.tell() + trailer > limit: - raise ValueError("program trailer crosses the database boundary") - stream.seek(trailer, 1) - offsets.append(start) - groups.append(offsets) - return groups - - -def program_identity(stream, group, ordinal, start): - stream.seek(start) - length = stream.read(1)[0] - # shader_carve.ENTRY can include a printable native length byte (and up to - # 200 printable bytes in all). Match the same wire header to recover its key. - terminator = start + length - window_start = max(0, terminator - 200) - stream.seek(window_start) - window = stream.read(terminator + 18 - window_start) - pos = terminator - window_start - while pos and 0x21 <= window[pos - 1] <= 0x7e: - pos -= 1 - match = ENTRY.fullmatch(window, pos) - if match is None: - raise ValueError(f"no shader_carve entry matching program at {start:#x}") - return {"group": group, "ordinal": ordinal, "record_offset": start, "carve_offset": window_start + pos} - - -def program_lists(data, pos, groups): - lists = [] - for group in groups: - if pos + 4 > len(data): - return None - count = u32(data, pos) - pos += 4 - after = pos + 4 * count - if after > len(data): - return None - ordinals = [] - for (ordinal,) in struct.iter_unpack("= len(group): - return None - ordinals.append(ordinal) - lists.append(ordinals) - pos = after - return lists, pos - - -def advance(data, pos, size): - if pos + size > len(data): - raise ValueError("effect field exceeds the database boundary") - return pos + size - - -def pool_after_passes(data, pos): - # Counted words, a marker and two length-prefixed byte blocks. - pos = advance(data, pos + 4, 4 * u32(data, pos)) - if u32(data, pos) != 0x80000000: - raise ValueError("invalid post-pass marker") - pos += 4 - for _ in range(2): - pos = advance(data, pos + 4, u32(data, pos)) - # In 1.0.2.1 the observed entry counts fit in the low byte. Bits 8..23 - # are zero, and the high byte can be nonzero. Payload meanings are unknown. - packed = u32(data, pos) - if packed & 0x00ffff00: - raise ValueError("unsupported packed post-pass count") - pos += 4 - for _ in range(packed & 0xff): - tag = u32(data, pos) - pos = advance(data, pos + 4, 4 if tag == 0x80000000 else tag) - return pos - - -class Effect(NamedTuple): - start: int - name: str - lists: list - technique_rows: int - first_pass: int - pass_end: int - pool: int - end: int - - -def effect_records(data, groups, count): - start = 0 - for _ in range(count): - if start >= len(data): - raise ValueError("missing effect record") - name_end = advance(data, start + 1, data[start]) - if not IDENTIFIER.fullmatch(data, start + 1, name_end): - raise ValueError("invalid counted effect name") - name = data[start + 1:name_end - 1].decode("ascii") - arrays = program_lists(data, name_end + 4, groups) # word after the name is opaque - if arrays is None: - raise ValueError("invalid effect program lists") - lists, pos = arrays - pos = advance(data, pos, 80) - for width in (16, 24, 68, 36): - pos = advance(data, pos + 4, width * u32(data, pos)) - rows = pos + 4 - pass_count_at = advance(data, rows, 4 * u32(data, pos)) - first = pass_count_at + 4 - pass_end = advance(data, first, 24 * u32(data, pass_count_at)) - pool = pool_after_passes(data, pass_end) - end = advance(data, pool + 4, u32(data, pool)) - if (end == pool + 4 or data[pool + 4] != 0 or data[end - 1] != 0 - or not POOL.fullmatch(data, pool + 4, end)): - raise ValueError("invalid counted string pool") - yield Effect(start, name, lists, rows, first, pass_end, pool, end) - start = end - if not 4 <= len(data) - start <= 4096 or u32(data, start) != 1 or any(data[start + 4:]): - raise ValueError("declared effects do not reach the database terminator and zero padding") - - -def techniques(data, effect): - """Yield the stored name and passes, including zero-program passes.""" - names = {m.start() - effect.pool - 4: m.group()[:-1].decode("ascii") - for m in STRING.finditer(data, effect.pool + 4, effect.end)} - cursor = effect.first_pass - rows = memoryview(data)[effect.technique_rows:cursor - 4] - for name_bits, _, length in struct.iter_unpack(" effect.pass_end: - raise ValueError("invalid technique name offset or pass count") - passes = [] - for _ in range(length): - programs = [] - for group, selector in enumerate(data[cursor:cursor + 6]): - if selector > len(effect.lists[group]): - raise ValueError("pass selector is outside the effect's program list") - if selector: - programs.append((group, effect.lists[group][selector - 1])) - passes.append(programs) - cursor += 24 - yield name, passes - if cursor != effect.pass_end: - raise ValueError("technique pass counts do not sum to the table count") - - -def read_database(stream, layout, effect=None, technique=None, *, list_effects=False, shader_hash=None): - database, first_group, end = layout - stream.seek(database) - if stream.read(4) != b"SGD5": - raise ValueError(f"expected Xbox 1.0.2.1 SGD5 database at {database:#x}") - stream.seek(first_group) - groups = program_groups(stream, end) - count = u32(stream.read(4)) - base = stream.tell() - if base >= end: - raise ValueError("missing effect region") - data = stream.read(end - base) - if len(data) != end - base: - raise ValueError("truncated effect region") - result = {"database": database, "groups": list(map(len, groups)), "effects": count, - "named_effects": 0, "techniques": 0, "passes": 0, "matches": []} - for record in effect_records(data, groups, count): - name = record.name - key = joaat(name) - selected = name == effect or key == shader_hash - if list_effects: - result["matches"].append({"effect": name, "shader_hash": f"{key:08X}", "effect_offset": base + record.start}) - listing = [] - for index, (stored_name, passes) in enumerate(techniques(data, record)): - result["named_effects"] += index == 0 - result["techniques"] += 1 - result["passes"] += len(passes) - if not selected: - continue - if technique is None: - listing.append({"technique": stored_name, "technique_index": index, "pass_count": len(passes)}) - elif stored_name == technique: - resolved = [[program_identity(stream, g, ordinal, groups[g][ordinal]) for g, ordinal in row] - for row in passes] - result["matches"].append({"effect": name, "effect_offset": base + record.start, - "technique_index": index, "passes": resolved}) - if selected and technique is None: - result["matches"].append({"effect": name, "effect_offset": base + record.start, "techniques": listing}) - return result - - -def main(argv=None): - parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) - parser.add_argument("archive", type=Path) - query = parser.add_mutually_exclusive_group() - query.add_argument("--list-effects", action="store_true", help="list effect names and archive offsets locally") - query.add_argument("--effect", help="exact effect name, or list its techniques when --technique is omitted") - query.add_argument("--shader-hash", metavar="HEX", help="hexadecimal Materials[].Shader value from rpf9dump") - parser.add_argument("--technique", help="exact technique name from that effect") - args = parser.parse_args(argv) - shader_hash = None - if args.shader_hash is not None: - if not re.fullmatch(r"(?:0[xX])?[0-9a-fA-F]{1,8}", args.shader_hash): - parser.error("--shader-hash expects up to eight hexadecimal digits") - shader_hash = int(args.shader_hash, 16) - if args.technique is not None and args.effect is None and shader_hash is None: - parser.error("--technique requires --effect or --shader-hash") - try: - with args.archive.open("rb") as stream: - results = [read_database(stream, layout, args.effect, args.technique, - list_effects=args.list_effects, shader_hash=shader_hash) - for layout in DATABASES] - if (args.effect is not None or shader_hash is not None) and not any(row["matches"] for row in results): - parser.error("no matching effect or technique; use --list-effects, then --effect NAME") - except (ValueError, OSError) as exc: - parser.error(str(exc)) - print(json.dumps(results, indent=2)) - return 0 - - -if __name__ == "__main__": - try: # a redirected stdout is strict ANSI code page under -I; write '?' for what it cannot encode - sys.stdout.reconfigure(errors="replace") - except (AttributeError, ValueError, OSError): - pass - sys.exit(main()) diff --git a/tools/shader_carve.py b/tools/shader_carve.py deleted file mode 100644 index 0a3f50139..000000000 --- a/tools/shader_carve.py +++ /dev/null @@ -1,157 +0,0 @@ -"""Carve shader containers out of an RPF9 archive without reading its (encrypted) table of contents. - -Each shader in shaders.rpf is stored as: - - 00 - -and inflates to a DXBC container (`size` bytes) holding DXIL plus an Xbox PRIV part. - -Usage: - python -I shader_carve.py - -Writes /.dxbc and /index.json (name, offset, stage, shader model, parts). -""" -import argparse -import json -import mmap -import os -import re -import struct -import sys -import tempfile -import zlib - -# `python -I` leaves the script's directory off sys.path. -sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) -from replace_retry import replace as replace_retry # noqa: E402 -from shader_carve_accel import entry_search # noqa: E402 - -ENTRY = re.compile(rb"([\x21-\x7e]{3,200})\x00(.)(....)(....)\3(....)", re.DOTALL) -STAGES = {0: "ps", 1: "vs", 2: "gs", 3: "hs", 4: "ds", 5: "cs", 6: "lib", 13: "ms", 14: "as"} -RESERVED = {"CON", "PRN", "AUX", "NUL", *(f"COM{i}" for i in range(1, 10)), *(f"LPT{i}" for i in range(1, 10))} - - -def parts(dxbc: bytes) -> dict: - if len(dxbc) < 32: - raise ValueError("truncated DXBC header") - count = struct.unpack_from(" len(dxbc): - raise ValueError("truncated DXBC part table") - out = {} - for entry in range(32, table_end, 4): - off = struct.unpack_from(" len(dxbc): - raise ValueError("truncated DXBC part payload") - out[fourcc.decode("latin-1")] = (off + 8, size) - return out - - -def shader_model(dxbc: bytes, p: dict): - if "DXIL" not in p: - return None, None - off, size = p["DXIL"] - if size < 4: - raise ValueError("truncated DXIL version and stage") - ver, kind = struct.unpack_from("> 4}.{ver & 0xF}" - - -def file_name(name: str, seen: dict, used: set) -> str: - """A file name for `name` that no earlier shader has, as Windows compares them: without case, and with the - device names (CON, NUL, COM1...) that open a device instead of a file. Same name twice means distinct - variants; the second gets ~1, the third ~2.""" - base = re.sub(r'[<>:"/\\|?*]', "_", name) - if base.split(".")[0].upper() in RESERVED: - base = "_" + base - key = base.lower() - n = seen.get(key, 0) - while True: - fname = base + (f"~{n}" if n else "") + ".dxbc" - if fname.lower() not in used: - break - n += 1 - seen[key] = n + 1 - used.add(fname.lower()) - return fname - - -def main(argv=None) -> int: - ap = argparse.ArgumentParser(description="Carve DXBC shader containers out of an RPF9 archive.") - ap.add_argument("src", help="the shaders.rpf archive") - ap.add_argument("out", help="folder for the .dxbc files and index.json") - a = ap.parse_args(argv) - src, out = a.src, a.out - if not os.path.isfile(src): - ap.error(f"{src} is not a file") - if os.path.getsize(src) == 0: - ap.error(f"{src} is empty") - if os.path.isfile(out): - ap.error(f"{out} is a file, not a folder") - try: - os.makedirs(out, exist_ok=True) - except OSError as e: # a regular file where a parent folder is expected - ap.error(f"cannot create {out}: {e.strerror or e}") - index, seen, used, bad = [], {}, set(), 0 - with (open(src, "rb") as fh, mmap.mmap(fh.fileno(), 0, access=mmap.ACCESS_READ) as m, - entry_search(m, ENTRY) as search): - pos = 0 - while (mt := search(pos)) is not None: - # A rejected header is rescanned past its name (a real entry can start inside it); a carved - # shader resumes after its stored bytes, so deflate output never becomes a name or a match. - pos = mt.end(1) + 1 - name = mt.group(1).decode("latin-1") - stored = struct.unpack(" bool { - (0x21..=0x7e).contains(&byte) -} - -fn match_start(bytes: &[u8], start: usize, nul: usize) -> Option { - if bytes[nul + 2..nul + 6] != bytes[nul + 10..nul + 14] { - return None; - } - let floor = start.max(nul.saturating_sub(MAX_NAME)); - Some( - bytes[floor..nul] - .iter() - .rposition(|&byte| !printable(byte)) - .map_or(floor, |previous| floor + previous + 1), - ) -} - -#[cfg(target_arch = "x86_64")] -fn scan_blocks(bytes: &[u8], start: usize, end: usize) -> (Option, usize) { - use std::arch::x86_64::*; - - let mut cursor = start; - let mut carry = 0; - while end - cursor >= 16 { - let (nuls, names) = unsafe { - let block = _mm_loadu_si128(bytes.as_ptr().add(cursor).cast()); - let nuls = _mm_movemask_epi8(_mm_cmpeq_epi8(block, _mm_setzero_si128())); - let printable = _mm_and_si128( - _mm_cmpgt_epi8(block, _mm_set1_epi8(0x20)), - _mm_cmpgt_epi8(_mm_set1_epi8(0x7f), block), - ); - (nuls as u32, _mm_movemask_epi8(printable) as u32) - }; - let history = (names << MIN_NAME) | carry; - carry = names >> (16 - MIN_NAME); - let mut candidates = nuls & history & (history >> 1) & (history >> 2); - while candidates != 0 { - let nul = cursor + candidates.trailing_zeros() as usize; - if let Some(found) = match_start(bytes, start, nul) { - return (Some(found), cursor); - } - candidates &= candidates - 1; - } - cursor += 16; - } - (None, cursor) -} - -fn find(bytes: &[u8], start: usize) -> Option { - let end = bytes.len().checked_sub(TAIL)? + 1; - if end.saturating_sub(start) <= MIN_NAME { - return None; - } - #[cfg(target_arch = "x86_64")] - let cursor = { - let (found, cursor) = scan_blocks(bytes, start, end); - if found.is_some() { - return found; - } - cursor - }; - #[cfg(not(target_arch = "x86_64"))] - let cursor = start; - - (cursor.max(start + MIN_NAME)..end).find_map(|nul| { - if bytes[nul] == 0 && bytes[nul - MIN_NAME..nul].iter().copied().all(printable) { - match_start(bytes, start, nul) - } else { - None - } - }) -} - -#[no_mangle] -pub unsafe extern "C" fn leonida_shader_carve_find_v1( - bytes: *const u8, - len: usize, - start: usize, -) -> usize { - if bytes.is_null() || len > isize::MAX as usize || start > len { - return usize::MAX; - } - let bytes = unsafe { std::slice::from_raw_parts(bytes, len) }; - find(bytes, start).unwrap_or(len) -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn checks_every_block_alignment_and_tail_length() { - for offset in 0..32 { - let mut bytes = vec![0x80; offset]; - bytes.extend_from_slice(b"!~A"); - bytes.extend_from_slice(&[0; TAIL]); - assert_eq!(find(&bytes, 0), Some(offset)); - assert_eq!(find(&bytes, offset), Some(offset)); - assert_eq!(find(&bytes, offset + 1), None); - bytes.pop(); - assert_eq!(find(&bytes, 0), None); - } - } - - #[test] - fn checks_max_name_and_backreference() { - let mut bytes = vec![b'A'; MAX_NAME + 1]; - bytes.extend_from_slice(&[0; TAIL]); - assert_eq!(find(&bytes, 0), Some(1)); - bytes[MAX_NAME + 1 + 10] = 1; - assert_eq!(find(&bytes, 0), None); - } - - #[test] - fn distinguishes_no_match_from_refusal() { - let bytes = b"abc"; - let scan = - |start| unsafe { leonida_shader_carve_find_v1(bytes.as_ptr(), bytes.len(), start) }; - assert_eq!(scan(0), bytes.len()); - assert_eq!(scan(bytes.len()), bytes.len()); - assert_eq!(scan(bytes.len() + 1), usize::MAX); - assert_eq!( - unsafe { leonida_shader_carve_find_v1(std::ptr::null(), 0, 0) }, - usize::MAX - ); - } -} diff --git a/tools/shader_diff.py b/tools/shader_diff.py deleted file mode 100644 index e1719a4cc..000000000 --- a/tools/shader_diff.py +++ /dev/null @@ -1,391 +0,0 @@ -r"""Differential oracle for the RDNA2 translator (standard library only). - -Runs seeded straight-line ALU programs through two independent oracles and -compares their output words: - * tools/cpu_ref.py - the ISA model, executed per lane (lanes=1, lane=0) - * rdna2spirv + tests/semantic/spirv_mini_interp.py - the translated SPIR-V - -This is the runner designed in docs/shader_validation.md ("Harness design"): -it owns the program table, the seed and the comparison; cpu_ref stays a pure -interpreter and is never modified here. - -Usage: - python -I tools/shader_diff.py [--programs N] [--seed S] [--max-ops N] - python -I tools/shader_diff.py --program-index I --seed S --max-ops N - python -I tools/shader_diff.py --self-test # harness canaries (must fail loudly if broken) - python -I tools/shader_diff.py --list-ops - -Exit code is 0 when every program matches, 1 on the first mismatch (with the -case name, seed, lane, register, expected/actual bits and the RDNA2 -instruction that last wrote the value), 2 on harness errors or when every -program was skipped (nothing was compared). Skips are counted with reasons and never silent. -""" -import argparse -import gc -import os -import random -import struct -import sys -import tempfile -import warnings - -HERE = os.path.dirname(os.path.abspath(__file__)) -sys.dont_write_bytecode = True -if HERE not in sys.path: - sys.path.insert(0, HERE) -SEM_DIR = os.path.join(os.path.dirname(HERE), "tests", "semantic") -if SEM_DIR not in sys.path: - sys.path.insert(0, SEM_DIR) - -import cpu_ref # noqa: E402 -import rdna2spirv # noqa: E402 -from spirv_mini_interp import UnsupportedConstruct, run_fragment # noqa: E402 - -STUB_DXBC = b"DXBC" + bytes(24) + struct.pack("> 23) & 0xFF - return exp == 0xFF and (word & 0x7FFFFF) != 0 - - -def _emit_perm(rng, dst, srcs): - """Half the cases pin the selector so bytes 8-13 (sign bits, 0x00, 0xff) are not left to chance.""" - if rng.random() < 0.5: - sel = 0 - for i in range(4): - sel |= rng.randrange(0, 16) << (8 * i) - return f"v_perm_b32 v{dst}, v{srcs[0]}, v{srcs[1]}, 0x{sel:08x}" - return f"v_perm_b32 v{dst}, v{srcs[0]}, v{srcs[1]}, v{srcs[2]}" - - -def _op_templates(): - """(name, emitter) table owned by this runner. Emitters take - (rng, dst, srcs) and return one assembly line (without leading tab).""" - return [ - ("v_mov_b32", lambda r, d, s: f"v_mov_b32 v{d}, {r.choice(s)}"), - ("v_add_f32", lambda r, d, s: f"v_add_f32 v{d}, v{s[0]}, v{s[1]}"), - ("v_sub_f32", lambda r, d, s: f"v_sub_f32 v{d}, v{s[0]}, v{s[1]}"), - ("v_mul_f32", lambda r, d, s: f"v_mul_f32 v{d}, v{s[0]}, v{s[1]}"), - ("v_fma_f32", lambda r, d, s: f"v_fma_f32 v{d}, v{s[0]}, v{s[1]}, v{s[2]}"), - ("v_and_b32", lambda r, d, s: f"v_and_b32 v{d}, v{s[0]}, v{s[1]}"), - ("v_or_b32", lambda r, d, s: f"v_or_b32 v{d}, v{s[0]}, v{s[1]}"), - ("v_xor_b32", lambda r, d, s: f"v_xor_b32 v{d}, v{s[0]}, v{s[1]}"), - ("v_lshlrev_b32", lambda r, d, s: f"v_lshlrev_b32 v{d}, {r.randrange(0, 8)}, v{s[0]}"), - ("v_lshrrev_b32", lambda r, d, s: f"v_lshrrev_b32 v{d}, {r.randrange(0, 8)}, v{s[0]}"), - ("v_ashrrev_i32", lambda r, d, s: f"v_ashrrev_i32 v{d}, {r.randrange(0, 8)}, v{s[0]}"), - ("v_add_nc_u32", lambda r, d, s: f"v_add_nc_u32 v{d}, v{s[0]}, v{s[1]}"), - ("v_sub_nc_u32", lambda r, d, s: f"v_sub_nc_u32 v{d}, v{s[0]}, v{s[1]}"), - ("v_subrev_nc_u32", lambda r, d, s: f"v_subrev_nc_u32 v{d}, v{s[0]}, v{s[1]}"), - ("v_mul_u32_u24", lambda r, d, s: f"v_mul_u32_u24 v{d}, v{s[0]}, v{s[1]}"), - ("v_mul_i32_i24", lambda r, d, s: f"v_mul_i32_i24 v{d}, v{s[0]}, v{s[1]}"), - ("v_mul_lo_u32", lambda r, d, s: f"v_mul_lo_u32 v{d}, v{s[0]}, v{s[1]}"), - ("v_mul_hi_u32", lambda r, d, s: f"v_mul_hi_u32 v{d}, v{s[0]}, v{s[1]}"), - ("v_mul_hi_i32", lambda r, d, s: f"v_mul_hi_i32 v{d}, v{s[0]}, v{s[1]}"), - ("v_mad_u32_u24", lambda r, d, s: f"v_mad_u32_u24 v{d}, v{s[0]}, v{s[1]}, v{s[2]}"), - ("v_mad_i32_i24", lambda r, d, s: f"v_mad_i32_i24 v{d}, v{s[0]}, v{s[1]}, v{s[2]}"), - ("v_min_u32", lambda r, d, s: f"v_min_u32 v{d}, v{s[0]}, v{s[1]}"), - ("v_max_u32", lambda r, d, s: f"v_max_u32 v{d}, v{s[0]}, v{s[1]}"), - ("v_min_i32", lambda r, d, s: f"v_min_i32 v{d}, v{s[0]}, v{s[1]}"), - ("v_max_i32", lambda r, d, s: f"v_max_i32 v{d}, v{s[0]}, v{s[1]}"), - ("v_bfe_u32", lambda r, d, s: f"v_bfe_u32 v{d}, v{s[0]}, {r.randrange(0, 40)}, {r.randrange(0, 40)}"), - ("v_bfe_i32", lambda r, d, s: f"v_bfe_i32 v{d}, v{s[0]}, {r.randrange(0, 40)}, {r.randrange(0, 40)}"), - ("v_bfi_b32", lambda r, d, s: f"v_bfi_b32 v{d}, v{s[0]}, v{s[1]}, v{s[2]}"), - ("v_alignbit_b32", lambda r, d, s: f"v_alignbit_b32 v{d}, v{s[0]}, v{s[1]}, v{s[2]}"), - ("v_alignbyte_b32", lambda r, d, s: f"v_alignbyte_b32 v{d}, v{s[0]}, v{s[1]}, v{s[2]}"), - ("v_perm_b32", _emit_perm), - ("v_med3_i32", lambda r, d, s: f"v_med3_i32 v{d}, v{s[0]}, v{s[1]}, v{s[2]}"), - ("v_med3_u32", lambda r, d, s: f"v_med3_u32 v{d}, v{s[0]}, v{s[1]}, v{s[2]}"), - ("s_add_u32", lambda r, d, s: f"s_add_u32 s{d}, s{s[0]}, s{s[1]}"), - ] - - -# NOTE: s_add_u32 is deliberately NOT generated: the translator lowers scalar -# adds to OpIAddCarry, which tests/semantic/spirv_mini_interp.py does not -# model yet, so every such program would skip with a reason instead of -# proving anything. Scalar reads are still covered: seeds are moved through -# s_regs and observed via the v_mov_b32/sgpr copy into an exported VGPR. Extending the -# mini-interp (not this runner) re-enables scalar ALU coverage. -_VEC_OPS = ("v_mov_b32", "v_add_f32", "v_sub_f32", "v_mul_f32", "v_fma_f32", - "v_and_b32", "v_or_b32", "v_xor_b32", "v_lshlrev_b32", - "v_lshrrev_b32", "v_ashrrev_i32", - "v_add_nc_u32", "v_sub_nc_u32", "v_subrev_nc_u32", "v_mul_u32_u24", - "v_mul_i32_i24", "v_mul_lo_u32", "v_mul_hi_u32", "v_mul_hi_i32", - "v_mad_u32_u24", "v_mad_i32_i24", "v_min_u32", "v_max_u32", - "v_min_i32", "v_max_i32", - "v_bfe_u32", "v_bfe_i32", "v_bfi_b32", "v_alignbit_b32", - "v_alignbyte_b32", "v_perm_b32", "v_med3_i32", "v_med3_u32") -_FLOAT_OPS = ("v_add_f32", "v_sub_f32", "v_mul_f32", "v_fma_f32") - - -def _seed_value(rng): - if rng.random() < 0.7: - return rng.choice(_SMALL_INTS) - return _u32_bits(rng.choice(_EXACT_FLOATS)) - - -def generate_program(rng, n_ops): - """One straight-line program. Returns (body_lines, export_writers). - - body_lines are tab-less assembly lines (seeds, ops). export_writers maps - each exported VGPR to the (op_name, line) that last wrote it, for the - first-mismatch report. - """ - lines = [] - writers = {} - for v in SCRATCH: - lines.append(f"v_mov_b32 v{v}, {_seed_value(rng)}") - writers[v] = ("v_mov_b32/seed", len(lines)) - s_regs = (4, 5, 6, 7) - for s in s_regs: - lines.append(f"s_mov_b32 s{s}, {_seed_value(rng) % 256}") - vec_ops = [t for t in _op_templates() if t[0] in _VEC_OPS and t[0] != "v_mov_b32"] - # A float op may return any NaN payload (Vulkan does not promise one) and the - # comparison accepts both-NaN. If that value then fed an integer op, the two - # payloads would produce different integer results, so integer ops never read - # the destination of a float op. Every untainted register is bit-identical on - # both oracles; a later integer write clears the taint. - tainted = set() - for _ in range(n_ops): - name, emit = rng.choice(vec_ops) - dst = rng.choice(SCRATCH) - clean = [v for v in SCRATCH if v not in tainted] - if name not in _FLOAT_OPS and not clean: - # All float results may carry oracle-specific NaN payloads. Restore one - # known bit pattern before choosing integer operands, even when dst is read. - lines.append(f"v_mov_b32 v{dst}, 0") - writers[dst] = ("v_mov_b32/seed", len(lines)) - tainted.discard(dst) - clean = [dst] - pool = SCRATCH if name in _FLOAT_OPS else clean - srcs = [rng.choice(pool) for _ in range(4)] - lines.append(emit(rng, dst, srcs)) - writers[dst] = (name, len(lines)) - if name in _FLOAT_OPS: - tainted.add(dst) - else: - tainted.discard(dst) - # Reuse the oldest export: an untouched seed if possible, else an ALU result. - dst = min(EXPORT_REGS, key=lambda reg: writers[reg][1]) - lines.append(f"v_mov_b32 v{dst}, s{rng.choice(s_regs)}") - writers[dst] = ("v_mov_b32/sgpr-copy", len(lines)) - return lines, writers - - -def _write_listing(path, lines, with_export): - with open(path, "w", encoding="utf-8", newline="\n") as f: - f.write("; shader_diff case code 0x0..0x1000\n") - for line in lines: - f.write("\t" + line + "\n") - if with_export: - f.write("\texp mrt0 v8, v9, v10, v11 done vm\n") - f.write("\ts_endpgm\n") - - -def compare_pair(cpu_words, spv_words, *, writers=None): - """Compare two 4-word exports and return the first mismatch or None. - - Results of floating-point instructions can have different NaN payloads. - All other words must match bit for bit. - """ - if len(cpu_words) != 4 or len(spv_words) != 4: - return f"shape mismatch: cpu has {len(cpu_words)} words, spv has {len(spv_words)}" - writers = writers or {} - for i in range(4): - c = cpu_words[i] & 0xFFFFFFFF - s = spv_words[i] & 0xFFFFFFFF - if c == s: - continue - writer = writers.get(EXPORT_REGS[i]) - mismatch = f"lane word {i}: expected 0x{c:08x} ({c}), actual 0x{s:08x} ({s})" - if writer and cpu_ref.base_op(writer[0]) in _FLOAT_OPS: - c_nan, s_nan = _is_nan_bits(c), _is_nan_bits(s) - if c_nan and s_nan: - continue - if c_nan or s_nan: - mismatch = f"lane word {i}: only one side is NaN (cpu=0x{c:08x} spv=0x{s:08x})" - if writer: - mismatch += f" (last writer {writer[0]} at body line {writer[1]} for v{EXPORT_REGS[i]})" - return mismatch - return None - - -def run_one(name, lines, writers): - """Translate + execute both oracles for one program. - - Returns (status, detail) with status in {"match", "mismatch", "skip"}. - """ - with tempfile.TemporaryDirectory(prefix="shader-diff-") as tmp: - dis = os.path.join(tmp, "disasm") - os.mkdir(dis) - cpu_path = os.path.join(tmp, "cpu.s") - _write_listing(cpu_path, lines, with_export=False) - try: - cpu_res = cpu_ref.run(cpu_path, {"lanes": 1}) - except cpu_ref.CpuRefError as e: - return ("skip", f"cpu_ref unsupported: {e}") - spv_path = os.path.join(dis, name + ".s") - _write_listing(spv_path, lines, with_export=True) - with open(os.path.join(tmp, name + ".dxbc"), "wb") as f: - f.write(STUB_DXBC) - try: - with warnings.catch_warnings(): - warnings.simplefilter("ignore", ResourceWarning) - spvasm = rdna2spirv.translate(spv_path) - gc.collect() - except rdna2spirv.Unsupported as e: - return ("skip", f"translator unsupported: {e}") - try: - out = run_fragment(spvasm) - except UnsupportedConstruct as e: - return ("skip", f"mini_interp unsupported: {type(e).__name__}: {e}") - if list(out) != ["%out_mrt0"]: - return ("skip", f"mini_interp gave outputs {sorted(out)}, want [%out_mrt0]") - regs = cpu_res["registers"]["vgpr"] - cpu_words = [regs.get(r, [0])[0] if isinstance(regs.get(r), list) else regs.get(r, 0) - for r in EXPORT_REGS] - mismatch = compare_pair(cpu_words, list(out["%out_mrt0"]), writers=writers) - if mismatch is None: - return ("match", "") - return ("mismatch", mismatch) - - -def run_suite(programs, seed, max_ops, limit=None, *, start=0): - """Generate the seeded sequence, executing cases from index start. Return (counts, first_failure).""" - counts = {"pass": 0, "mismatch": 0, "skip": {}, "harness-error": 0} - first_failure = None - rng = random.Random(seed) - total = programs if limit is None else min(programs, limit) - for i in range(total): - lines, writers = generate_program(rng, rng.randrange(1, max_ops + 1)) - if i < start: # advance the original RNG stream, but skip both oracles - continue - name = f"ps_diff_{i:04d}" - try: - status, detail = run_one(name, lines, writers) - except Exception as e: # noqa: BLE001 - harness bugs must be loud - counts["harness-error"] += 1 - if first_failure is None: - first_failure = (f"{name}: harness error {type(e).__name__}: {e}\n" - f"Replay: --seed {seed} --max-ops {max_ops} --program-index {i}") - continue - if status == "match": - counts["pass"] += 1 - elif status == "mismatch": - counts["mismatch"] += 1 - if first_failure is None: - first_failure = (f"{name} (seed {seed} program {i}): {detail}\n" - f"Replay: --seed {seed} --max-ops {max_ops} --program-index {i}\n" + - "\n".join("\t" + line for line in lines)) - else: - counts["skip"][detail] = counts["skip"].get(detail, 0) + 1 - return counts, first_failure - - -def self_test(): - """Harness canaries. Returns True only if the harness can both pass and fail.""" - # 1. A hand-written program must match (the pipeline works). - lines = ["v_mov_b32 v8, 4", "v_mov_b32 v9, 8", "v_add_f32 v8, v8, v9", - "v_mov_b32 v10, 1", "v_mov_b32 v11, 2"] - writers = {8: ("v_add_f32", 3), 9: ("v_mov_b32/seed", 2), - 10: ("v_mov_b32/seed", 4), 11: ("v_mov_b32/seed", 5)} - status, detail = run_one("ps_canary_ok", lines, writers) - if status != "match": - print(f"canary FAILED: hand-written program did not match ({status}: {detail})") - return False - # 2. An intentionally wrong expectation must be caught (the harness can fail). - bad = compare_pair([1, 2, 3, 4], [1, 2, 3, 5]) - if bad is None or "lane word 3" not in bad: - print("canary FAILED: corrupted expectation was not flagged") - return False - # 3. An unsupported op must be a counted skip, not a silent pass. - status, detail = run_one("ps_canary_skip", ["v_interp_p1_f32 v8, v9, v10"], {}) - if status != "skip": - print(f"canary FAILED: unsupported op was not skipped (got {status})") - return False - print("canaries: match ok, mismatch detected, skip counted") - return True - - -def _at_least_one(value): - """An integer option that must be at least 1. - - 0 and negative values used to run nothing (--programs, --limit) or raise - `empty range in randrange(1, 1)` (--max-ops) instead of being refused. - """ - try: - n = int(value) - except ValueError: - raise argparse.ArgumentTypeError(f"expected an integer, got {value!r}") from None - if n < 1: - raise argparse.ArgumentTypeError(f"must be at least 1 (got {n})") - return n - - -def main(argv=None): - ap = argparse.ArgumentParser(description="Differential oracle: cpu_ref vs translated SPIR-V.") - selection = ap.add_mutually_exclusive_group() - selection.add_argument("--programs", type=_at_least_one, help="number of programs to run (default: 200)") - selection.add_argument("--program-index", type=int, metavar="I", - help="replay only zero-based program I using the original --seed and --max-ops") - ap.add_argument("--seed", type=int, default=1) - ap.add_argument("--max-ops", type=_at_least_one, default=8, - help="maximum ops per generated program (default: 8)") - ap.add_argument("--limit", type=_at_least_one, default=None, - help="run only the first N programs (N >= 1)") - ap.add_argument("--list-ops", action="store_true", help="print the op table and exit") - ap.add_argument("--self-test", action="store_true", help="run harness canaries and exit") - a = ap.parse_args(argv) - if a.list_ops: - for name, _ in _op_templates(): - print(name) - return 0 - if a.self_test: - return 0 if self_test() else 1 - if a.program_index is None: - counts, first_failure = run_suite(a.programs or 200, a.seed, a.max_ops, a.limit) - else: - if a.program_index < 0: - ap.error("--program-index must be nonnegative") - if a.limit is not None: - ap.error("--program-index cannot be combined with --limit") - print(f"replaying program {a.program_index} (seed {a.seed}, max ops {a.max_ops})") - counts, first_failure = run_suite(a.program_index + 1, a.seed, a.max_ops, start=a.program_index) - total_skips = sum(counts["skip"].values()) - total_run = counts["pass"] + counts["mismatch"] + total_skips + counts["harness-error"] - print(f"{total_run} programs (seed {a.seed}): " - f"{counts['pass']} pass, {counts['mismatch']} mismatch, " - f"{total_skips} skipped, {counts['harness-error']} harness errors") - for reason, n in sorted(counts["skip"].items()): - print(f" skip x{n}: {reason}") - if first_failure is not None: - print("FIRST FAILURE:\n" + first_failure) - if counts["harness-error"]: - return 2 - if counts["mismatch"]: - return 1 - if not counts["pass"]: - print("no program ran: every one was skipped") - return 2 - return 0 - - -if __name__ == "__main__": - try: # a redirected stdout is strict ANSI code page under -I; write '?' for what it cannot encode - sys.stdout.reconfigure(errors="replace") - except (AttributeError, ValueError, OSError): - pass - sys.exit(main()) diff --git a/tools/shader_disasm.py b/tools/shader_disasm.py deleted file mode 100644 index a119e74aa..000000000 --- a/tools/shader_disasm.py +++ /dev/null @@ -1,283 +0,0 @@ -"""Disassemble the native RDNA2 code in unpacked FSSM shader blobs with LLVM's AMDGPU disassembler. - -FSSM header (little-endian qwords at 0x00..): 'FSSM' 01 01, blob size, ..., then a table where the -code range appears as (offset, size) = qword[6], qword[7] in every blob checked so far (e.g. 0x2f8, 0x100). -The code ends with s_endpgm (0xBF810000). If the header guess doesn't hold for a blob, the tool falls back to -scanning back from the first s_endpgm to the start that decodes with no invalid instructions. - -Usage: - python -I shader_disasm.py [--unpack-index FILE] [--out DIR] [--mcpu gfx1013] [--limit N] [--skip-existing] -Writes /.s and prints a summary (decoded cleanly / with invalid words / failed). -Set LLVM_MC to llvm-mc's path, or to a whole command such as -'wsl -d Ubuntu -e /usr/lib/llvm-21/bin/llvm-mc' when the tool is not on PATH. Off Windows, a versioned install -(llvm-mc-21, /usr/lib/llvm-21/bin/llvm-mc) is found without it (tools/mc_command.py). -""" -import argparse -import os -import struct -import subprocess -import sys -import tempfile -from concurrent.futures import ThreadPoolExecutor - -sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) -from mc_command import install_hint, mc_command, not_found # noqa: E402 -from report_paths import path_key, same_report_path # noqa: E402 -from shader_stage_manifest import shader_stems # noqa: E402 -import fssm_header # noqa: E402 -import rdna2_decode # noqa: E402 - -TRIPLE = "amdgcn--amdpal" -ENDPGM = b"\x00\x00\x81\xbf" -PROBE = "0x00 0x00 0x81 0xbf" # s_endpgm: the one instruction every shader ends with -FAILED = [] # (path, first stderr line) for shaders that produced no disassembly - - -MC = mc_command() - - -def fail(msg: str) -> "None": - print(f"ERROR: {msg}", file=sys.stderr) - sys.exit(1) - - -def output_path(path: str, out: str) -> str: - return os.path.join(out, os.path.splitext(os.path.basename(path))[0] + ".s") - - -def validate_output(out: str, files: list) -> None: - """Refuse a planned /.s that is a folder or names an input, before probing llvm-mc or creating --out. - A single `foo.s` given with --out at its own folder (or the default ../disasm of a file already in disasm/) was - replaced by its own listing; on Windows and macOS `FOO.S` is the same file as the `FOO.s` written for it.""" - inputs = {path_key(p): p for p in files} - for src in files: - dst = output_path(src, out) - if os.path.isdir(dst): - fail(f"cannot write {dst}: destination is a folder, not a file") - hit = inputs.get(path_key(dst)) - if hit is None and same_report_path(src, dst): # a hard link or another spelling the name rules missed - hit = src - if hit is not None: - fail(f"output {dst} would overwrite input {hit}") - - -def positive_int(text: str) -> int: - """--jobs 0 made ThreadPoolExecutor raise, and --limit -1 silently dropped the last file.""" - try: - value = int(text) - except ValueError: - raise argparse.ArgumentTypeError(f"invalid int value: {text!r}") from None - if value < 1: - raise argparse.ArgumentTypeError("must be at least 1") - return value - - -def probe(mcpu: str) -> None: - """Disassemble one s_endpgm first, so a missing tool or AMDGPU target fails now and not per shader.""" - try: - p = subprocess.run(MC + ["--disassemble", f"-triple={TRIPLE}", f"-mcpu={mcpu}"], - input=PROBE, capture_output=True, text=True, errors="replace", - creationflags=getattr(subprocess, "BELOW_NORMAL_PRIORITY_CLASS", 0)) - except OSError as e: - fail(not_found(MC[0], e)) - if p.returncode != 0 or "s_endpgm" not in p.stdout: - why = (p.stderr.strip().splitlines() or [f"exit code {p.returncode}"])[0] - fail(f"'{' '.join(MC)}' did not disassemble an s_endpgm: {why}\n" - f"The disassembler needs LLVM 21+ with the AMDGPU target (docs/design.md, 'Disassembling shaders').\n" - f"{install_hint()}") - - -def disasm(code: bytes, mcpu: str, backend: str = "llvm-mc", wave32: bool = True): - if backend == "python": - asm, bad = rdna2_decode.disasm_bytes(code, mcpu=mcpu, wave32=wave32) - return asm, bad, "" - text = " ".join(f"0x{b:02x}" for b in code) - try: - p = subprocess.run(MC + ["--disassemble", f"-triple={TRIPLE}", f"-mcpu={mcpu}", "-show-encoding"], - input=text, capture_output=True, text=True, errors="replace", - creationflags=getattr(subprocess, "BELOW_NORMAL_PRIORITY_CLASS", 0)) - except OSError as e: - return "", 0, str(e) - bad = p.stderr.count("invalid instruction encoding") - if p.returncode != 0: - return "", bad, p.stderr.strip() or f"llvm-mc exited with code {p.returncode}" - return p.stdout, bad, p.stderr - - -MAX_DATA_DWORDS = 1 << 16 - - -def data_block_start(b: bytes, start: int, end: int) -> int: - """Where a constant-data block begins at the end of the code range [start, end), or `end` if there is none. - - Some blobs carry, after the last real s_endpgm, a block laid out as: s_endpgm, a dword count N, N dwords - of data, then one more s_endpgm (the one the range ends on) and s_code_end padding. The data is not code: - llvm-mc reports its words as invalid (and reads a 0xBF810000 inside it as a second program end). The - block is recognised only when the count N matches the distance to the closing s_endpgm and the dword - before the count is itself an s_endpgm, so ordinary code is not cut.""" - last = end - 4 - for n in range(min(MAX_DATA_DWORDS, (last - start) // 4 - 1) + 1): - count = last - 4 * (n + 1) - if count - 4 < start: - break - if struct.unpack_from("= 0xC4 else 0 - start = off + 0x28 - if 0 < off and start < len(b): - last = b.rfind(ENDPGM, start) - while last >= 0 and (last - start) % 4: - last = b.rfind(ENDPGM, start, last) - if last >= 0: - return start, data_block_start(b, start, last + 4), "header" - end = b.find(ENDPGM) - # Fallback instructions are dword-aligned in the blob. A matching byte sequence can straddle metadata words. - while end >= 0 and end % 4: - end = b.find(ENDPGM, end + 1) - return None, end + 4 if end >= 0 else None, "scan" - - -def one(path, out, mcpu, backend="llvm-mc"): - with open(path, "rb") as f: - b = f.read() - wave32 = fssm_header.wave_size(b) != 64 - start, end, how = code_range(b) - if end is None: - return "no s_endpgm" - if start is None: - # Walk back in 4-byte steps from the end and keep the longest clean decode. - start, best = end - 4, None - for s in range(end - 4, max(0x100, end - 0x4000) - 1, -4): - _, bad, _ = disasm(b[s:end], mcpu, backend=backend, wave32=wave32) - if bad == 0: - best = s - if best is None: - return "scan failed" - start = best - asm, bad, err = disasm(b[start:end], mcpu, backend=backend, wave32=wave32) - if not asm.strip(): # a broken toolchain, not a shader: never report this as "clean" - reason = (err.strip().splitlines() or ["no output"])[0] - FAILED.append((path, reason)) - return "failed" - name = os.path.splitext(os.path.basename(path))[0] - # Only a published listing can be reused after an interruption. - listing = tempfile.NamedTemporaryFile(mode="w", dir=out, prefix=".disasm-", suffix=".tmp", - encoding="utf-8", newline="\n", delete=False) - try: - with listing: - listing.write(f"; {name} code 0x{start:x}..0x{end:x} ({how}), {mcpu}, {bad} invalid words\n") - listing.write(asm) - if err.strip(): - listing.write("\n; --- llvm-mc messages ---\n; " + err.strip().replace("\n", "\n; ") + "\n") - os.replace(listing.name, output_path(path, out)) - finally: - if os.path.exists(listing.name): - os.unlink(listing.name) - return "clean" if bad == 0 else "invalid words" - - -def main(): - ap = argparse.ArgumentParser() - ap.add_argument("src") - ap.add_argument("--unpack-index", help="disassemble only the FSSMs listed in this unpack index") - ap.add_argument("--out") - ap.add_argument("--skip-existing", action="store_true", help="reuse complete listings from a matching run") - ap.add_argument("--mcpu", default="gfx1013") - ap.add_argument("--backend", choices=("llvm-mc", "python"), default="llvm-mc", - help="disassembler backend: llvm-mc (default) or pure-Python RDNA2 decoder (#1901)") - ap.add_argument("--limit", type=positive_int) - ap.add_argument("--jobs", type=positive_int, default=max(1, (os.cpu_count() or 2) // 2)) - a = ap.parse_args() - if os.path.isfile(a.src): - if a.unpack_index: - ap.error("--unpack-index requires an FSSM directory") - files = [a.src] - elif os.path.isdir(a.src): - try: - if a.unpack_index: - names = shader_stems(a.unpack_index, "name") - files = sorted(os.path.join(a.src, name + ".fssm") for name in names) - for path in files: - if not os.path.isfile(path): - raise ValueError(f"{a.unpack_index}: declared FSSM file is missing: {path}") - else: - with os.scandir(a.src) as entries: - files = sorted(entry.path for entry in entries - if entry.name.endswith(".fssm") and entry.is_file()) - except (OSError, ValueError) as e: - fail(f"cannot list shaders in {a.src}: {e}") - elif not os.path.exists(a.src): - print(f"ERROR: {a.src}: does not exist", file=sys.stderr) - return 2 - else: - fail(f"{a.src} is not a file or folder") - if not files: - fail(f"no .fssm files in {a.src}") - files = files[: a.limit] if a.limit else files - out = a.out or os.path.join(os.path.dirname(files[0]), "..", "disasm") - validate_output(out, files) - try: - os.makedirs(out, exist_ok=True) - except OSError as e: - fail(f"cannot create the output folder {out}: {e.strerror or e}") - from collections import Counter - res = Counter() - total = len(files) - every_stem = {os.path.splitext(os.path.basename(p))[0] for p in files} # before --skip-existing narrows files - if a.skip_existing: - pending = [] - for path in files: - listing = output_path(path, out) - if not os.path.islink(listing) and os.path.isfile(listing) and os.path.getsize(listing) > 0: - res["reused"] += 1 - else: - pending.append(path) - files = pending - if files: - if a.backend == "llvm-mc": - probe(a.mcpu) - with ThreadPoolExecutor(a.jobs) as ex: - res.update(ex.map(lambda p: one(p, out, a.mcpu, backend=a.backend), files)) - print(f"{total} shaders -> {os.path.abspath(out)}: {dict(res)}") - if FAILED: - path, reason = FAILED[0] - fail(f"{len(FAILED)} shader(s) produced no disassembly, first {path}: {reason}") - if not (res["clean"] or res["invalid words"] or res["reused"]): - fail(f"no disassembly produced for {a.src}") - if os.path.isdir(a.src) and not a.limit: - # A shader dropped by a re-carve must not keep its old listing: the translator reads every .s in this folder, - # so a stale one would still be translated and indexed even though the corpus no longer has it. Prune only - # after a successful decode, so a missing llvm-mc or a failed shader never deletes a usable listing. --limit - # is a partial run on purpose and leaves the rest of the folder alone. - # Every input's stem, not just this run's `files`: --skip-existing leaves the reused listings out of `files`, - # and pruning against that list deleted every listing a resumed run had just reused. - stems = every_stem - stale = [] - try: - with os.scandir(out) as entries: - stale = sorted(e.path for e in entries - if e.name.endswith(".s") and e.is_file() and e.name[:-2] not in stems) - for path in stale: - os.remove(path) - except OSError as e: - fail(f"cannot prune stale .s files in {out}: {e.strerror or e}") - if stale: - print(f"removed {len(stale)} stale .s file(s) that no .fssm in {a.src} names") - return 0 - - -if __name__ == "__main__": - try: # a redirected stdout is strict ANSI code page under -I; write '?' for what it cannot encode - sys.stdout.reconfigure(errors="replace") - except (AttributeError, ValueError, OSError): - pass - sys.exit(main()) diff --git a/tools/shader_ir.py b/tools/shader_ir.py deleted file mode 100644 index 2a4db1b0d..000000000 --- a/tools/shader_ir.py +++ /dev/null @@ -1,319 +0,0 @@ -"""Parse LLVM AMDGPU disassembly (.s from shader_disasm.py) into a structured instruction list. - -Each instruction: {"op": mnemonic, "args": [operand...], "mods": [modifier...], "enc": bytes, "pc": byte offset} -Operand kinds: sgpr s5 / s[4:7], vgpr v3 / v[0:3], special (vcc, exec, m0, scc...), inline constant, literal, -label/offset (for branches), hw register, and raw text for anything else. - -As a module: parse_file(path) -> {"name", "code_start", "insns": [...], "invalid": [pc...]} -As a tool: python -I shader_ir.py [--limit N] (parses everything and reports coverage) -Usage: `python -I tools/shader_ir.py --help` lists the options. -""" -import argparse -import os -import re -import sys -from collections import Counter - -ENC = re.compile(r";\s*encoding:\s*\[([^\]]*)\]") -HDR = re.compile(r"^;\s*(\S+)\s+code 0x([0-9a-f]+)\.\.0x([0-9a-f]+)") -SPECIAL = {"vcc", "vcc_lo", "vcc_hi", "exec", "exec_lo", "exec_hi", "m0", "scc", "null", "off", "src_scc", - "src_execz", "src_vccz", "src_lds_direct", "src_shared_base", "src_shared_limit", - "src_private_base", "src_private_limit", "src_pops_exiting_wave_id", "lds", "flat_scratch", - "flat_scratch_lo", "flat_scratch_hi", "ttmp", "tba", "tma"} - -# operand() runs once per operand of every instruction of every shader, so its patterns are compiled once here -# rather than looked up in re's cache on each call. -_NEG = re.compile(r"neg\((.+)\)") -_ABS = re.compile(r"abs\((.+)\)") -_SEXT = re.compile(r"sext\((.+)\)") -_REG = re.compile(r"([sv])(\d+)") -_REG_RANGE = re.compile(r"([sv])\[(\d+):(\d+)\]") -_TTMP = re.compile(r"ttmp(\d+)|ttmp\[(\d+):(\d+)\]") -_VLIST = re.compile(r"\[(v\d+(?:,\s*v\d+)+)\]") -_SLIST = re.compile(r"\[((?:s\d+|vcc_lo|vcc_hi)(?:\s*,\s*(?:s\d+|vcc_lo|vcc_hi))+)\]") -_ATTR = re.compile(r"attr(\d+)\.([xyzw])") -_TARGET = re.compile(r"(pos|param|mrt|mrtz|null|prim)(\d*)") -_INT = re.compile(r"-?(0x[0-9a-fA-F]+|\d+)") -_FLOAT = re.compile(r"-?\d+\.\d+(e[+-]?\d+)?") -# LLVM 23 prints a literal it could also show as an inline constant as lit(V), e.g. a v_fma_mix* f32 source -# `lit(0x42200000)`, where LLVM 21 printed the inline constant of the low half (0) and dropped the literal. -# Only a numeric constant is unwrapped: lit(v2) is no literal and stays raw (Unsupported), as before. -_LIT = re.compile(r"lit\((-?(?:0x[0-9a-fA-F]+|\d+(?:\.\d+(?:e[+-]?\d+)?)?))\)") - - -def operand(tok): - t = tok.strip() - if "lit(" in t: - # lit(V) is the constant V. A leading '-' on it is the VOP3 neg modifier, as neg(V) (not integer negation). - t = _LIT.sub(r"\1", t) - if t.startswith("-"): - t = "neg(" + t[1:] + ")" - neg = t.startswith("-") - core = t[1:] if neg else t - absm = len(core) > 2 and core.startswith("|") and core.endswith("|") - if absm: - core = core[1:-1] - # Fast path for the commonest operands: single register (v3, s12), special register, or unsigned decimal int. - if len(core) > 1 and core[0] in "sv" and core[1:].isdigit(): - return {"k": core[0] + "gpr", "r": int(core[1:]), "n": 1, "neg": neg, "abs": absm} - if core in SPECIAL: - return {"k": "special", "t": core, "neg": neg, "abs": absm} - if core.isascii() and core.isdigit(): - v = int(core, 10) - if absm: - out = {"k": "imm", "v": v, "abs": True} - if neg: - out["neg"] = True - return out - return {"k": "imm", "v": -v if neg else v} - if "(" in core: - m = _NEG.fullmatch(core) - if m: # VOP3 FP negation: neg(0), neg(1.0), neg(0x3f800000), neg(|1.0|), neg(v1) - inner = operand(m.group(1)) - if absm: - # Outer |...| absorbs the inner neg; outer '-' (if any) negates the result. - inner["abs"] = True - if neg: - inner["neg"] = True - elif inner.get("k") in ("imm", "fimm"): - inner.pop("neg", None) - else: - inner["neg"] = False - elif not neg: - # Keep neg as a VOP3 sign-bit modifier on constants instead of integer negation: - # in LLVM AMDGPU, neg(1) flips bit 31 (0x80000001) while -1 is 0xffffffff. - new_neg = not inner.get("neg", False) - if not new_neg and inner.get("k") in ("imm", "fimm"): - inner.pop("neg", None) - else: - inner["neg"] = new_neg - return inner - m = _ABS.fullmatch(core) - if m: # VOP3 FP absolute value: abs(v0), abs(0xbf800000), neg(abs(1.0)) - inner = operand(m.group(1)) - inner["abs"] = True - if neg: - inner["neg"] = True - elif inner.get("k") in ("imm", "fimm"): - inner.pop("neg", None) - else: - inner["neg"] = False - return inner - m = _SEXT.fullmatch(core) - if m: # SDWA integer sign-extension of the selected source bits - inner = operand(m.group(1)) - inner["sext"] = True - if absm: - inner["abs"] = True - inner["neg"] = inner.get("neg", False) or neg - return inner - if "[" in core: - m = _REG_RANGE.fullmatch(core) - if m: - lo, hi = int(m.group(2)), int(m.group(3)) - return {"k": m.group(1) + "gpr", "r": lo, "n": hi - lo + 1, "neg": neg, "abs": absm} - m = _VLIST.fullmatch(core) - if m: # NSA image address: non-contiguous VGPR list - return {"k": "vlist", "r": [int(x.strip()[1:]) for x in m.group(1).split(",")]} - m = _SLIST.fullmatch(core) - if m: # LLVM VCCTuple scalar register list, e.g. [s100,s101,s102,s103,s104,s105,vcc_lo,vcc_hi] - items = [int(x[1:]) if x.startswith("s") else x for x in (t.strip() for t in m.group(1).split(","))] - return {"k": "slist", "r": items, "n": len(items)} - if core.startswith("ttmp"): - m = _TTMP.fullmatch(core) - if m: - return {"k": "ttmp", "t": core} - if core.startswith("attr"): - m = _ATTR.fullmatch(core) - if m: - return {"k": "attr", "a": int(m.group(1)), "c": "xyzw".index(m.group(2))} - if core in ("p0", "p10", "p20"): - return {"k": "interp", "t": core} - m = _TARGET.fullmatch(core) - if m and core not in ("null",): - return {"k": "target", "t": core} - if _INT.fullmatch(core): - # int(core, 0) rejects the leading-zero decimals this regex accepts ('010', '08', '0001'), - # which aborts a whole parse_file() run on one disassembly line. - neg_core = core.startswith("-") - digits = core[1:] if neg_core else core - v = int(digits, 16) if digits.lower().startswith("0x") else int(digits, 10) - if neg_core: - v = -v - if absm: - out = {"k": "imm", "v": v, "abs": True} - if neg: - out["neg"] = True - return out - return {"k": "imm", "v": -v if neg else v} - if _FLOAT.fullmatch(core): - if absm: - out = {"k": "fimm", "v": float(core), "abs": True} - if neg: - out["neg"] = True - return out - return {"k": "fimm", "v": float(core) * (-1 if neg else 1), "abs": False} - if core.startswith("hwreg(") or core.startswith("sendmsg(") or core.startswith("vmcnt(") or \ - core.startswith("expcnt(") or core.startswith("lgkmcnt(") or core.startswith("vscnt(") or \ - core.startswith("depctr") or core.startswith("instid") or core.startswith("quad_perm") or \ - core.startswith("row_") or core.startswith("dpp") or core.startswith("sel:") or "(" in core: - return {"k": "special", "t": core} - return {"k": "raw", "t": t} - - -def split_args(s): - if "(" not in s and "[" not in s: - parts = s.split(",") - if parts and not parts[-1].strip(): - parts.pop() - return parts - out, depth, cur = [], 0, "" - for ch in s: - if ch in "([": - depth += 1 - elif ch in ")]": - depth -= 1 - if ch == "," and depth == 0: - out.append(cur) - cur = "" - else: - cur += ch - if cur.strip(): - out.append(cur) - return out - - -SENDMSG = re.compile(r"sendmsg\([^)]*\)") - -MODWORDS = re.compile(r"\b(offset:(?:swizzle\([^)]*\)|\S+)|offen|idxen|glc|slc|dlc|lds|tfe|unorm|da|d16|a16|nv|r128|lwe|clamp|" - r"mul:\d+|div:\d+|op_sel(?:_hi)?:\[[^\]]*\]|neg_lo:\[[^\]]*\]|neg_hi:\[[^\]]*\]|" - r"dmask:\S+|dim:\S+|format:\S+|done|vm|compr|row_mask:\S+|bank_mask:\S+|" - r"bound_ctrl:\S+|fi:\S+|offset0:\S+|offset1:\S+|gds|inst_offset:\S+|" - r"dst_sel:\S+|dst_unused:\S+|src0_sel:\S+|src1_sel:\S+|high|dpp8:\[[^\]]*\]|" - r"row_mirror|row_half_mirror|row_shl:\d+|row_shr:\d+|row_ror:\d+|row_share:\d+|" - r"row_xmask:\d+|quad_perm:\[[^\]]*\])(?=\s|,|$)") - - -def parse_line(line): - code, _, comment = line.partition(";") - enc = None - if comment and "encoding" in comment: - m = ENC.search(line) - if m: - enc = bytes(int(x, 16) for x in m.group(1).split(",") if x.strip()) - code = code.strip() - if not code: - return None - fields = code.split(maxsplit=1) - op = fields[0] - rest = fields[1] if len(fields) > 1 else "" - # sendmsg(MSG_GS, GS_OP_NOP) contains a comma: keep it as one operand. - if "sendmsg(" in rest: - rest = SENDMSG.sub(lambda m: m.group(0).replace(", ", "|").replace(",", "|"), rest) - mods = [] - if rest: - def _take_mod(match): - mods.append(match.group(1)) - return "" - rest = MODWORDS.sub(_take_mod, rest) - parts = [a for a in split_args(rest) if a.strip()] - if op in ("s_waitcnt", "s_waitcnt_depctr"): - # LLVM separates named wait counters with spaces. - parts = [token for part in parts for token in part.split()] - elif parts and len(parts[0].split()) == 2: - # 'exp pos0 v3, ...' / 'exp null off, ...': the target is space-separated from the first operand. - parts = parts[0].split() + parts[1:] - args = [operand(a) for a in parts] - if op.startswith(("v_add_f64", "v_cvt_f32_f64", "v_rcp_f64", "v_rsq_f64", "v_sqrt_f64", - "v_frexp_mant_f64", "v_frexp_exp_i32_f64", "v_ldexp_f64", "v_trunc_f64", - "v_ceil_f64", "v_rndne_f64", "v_floor_f64")): - for src, spelling in zip(args[1:], parts[1:]): - # LLVM prints inline integers in decimal and the separate literal dword in hex, - # even for two sources with the same numeric value (e.g. 0x1 and 1). - if src["k"] == "imm" and ("0x" in spelling or not -16 <= src["v"] <= 64): - src["f64_literal"] = True - # The hex digits are the operand's printed width: LLVM pads nothing, so a value that - # fits one literal dword prints in at most 8 of them (docs/design.md, f64 literal sources). - m = re.search(r"0x([0-9a-fA-F]+)", spelling) - if m: - src["literal_hex_digits"] = len(m.group(1)) - return {"op": op, "args": args, "mods": mods, "enc": enc.hex() if enc else None} - - -def parse_file(path): - with open(path, encoding="utf-8", errors="replace") as f: - lines = f.read().splitlines() - info = {"name": os.path.splitext(os.path.basename(path))[0], "insns": [], "invalid": 0} - m = HDR.match(lines[0]) if lines else None - pc = int(m.group(2), 16) if m else 0 - info["code_start"] = pc - # the end of the code range the header declares (exclusive), None without a header: undecodable words can sit - # between the last printed instruction and it - info["code_end"] = int(m.group(3), 16) if m else None - start = 1 if (lines and not lines[0].startswith("\t")) else 0 - for ln in lines[start:]: - if ln.startswith("; ---"): - break - if not ln.startswith("\t") or ln.lstrip().startswith("."): - continue - ins = parse_line(ln) - if not ins: - continue - ins["pc"] = pc - if ins["enc"]: - pc += len(ins["enc"]) // 2 - info["insns"].append(ins) - tail = "\n".join(lines) - info["invalid"] = tail.count("invalid instruction encoding") - return info - - -def positive_int(text): - try: - value = int(text) - except ValueError: - raise argparse.ArgumentTypeError(f"invalid int value: {text!r}") from None - if value < 1: - raise argparse.ArgumentTypeError("must be at least 1") - return value - - -def main(argv=None): - ap = argparse.ArgumentParser(description="Parse a folder of .s disassembly and report operand coverage.") - ap.add_argument("src", help="folder of .s files written by shader_disasm.py") - ap.add_argument("--limit", type=positive_int, help="parse only the first N files, sorted by name") - a = ap.parse_args(argv) - if not os.path.isdir(a.src): - ap.error(f"{a.src} is not a folder") - try: - with os.scandir(a.src) as entries: - files = sorted(entry.path for entry in entries - if entry.name.endswith(".s") and entry.is_file())[:a.limit] - except OSError as e: - print(f"ERROR: cannot list {a.src}: {e.strerror or e}", file=sys.stderr) - return 2 - kinds, raw, n_ins, no_enc = Counter(), Counter(), 0, 0 - for path in files: - try: - info = parse_file(path) - except OSError as e: - print(f"ERROR: cannot read {e.filename or path}: {e.strerror or e}", file=sys.stderr) - return 2 - for ins in info["insns"]: - n_ins += 1 - no_enc += ins["enc"] is None - for a in ins["args"]: - kinds[a["k"]] += 1 - if a["k"] == "raw": - raw[a["t"]] += 1 - print(f"{len(files)} shaders, {n_ins:,} instructions, {no_enc} without encoding bytes") - print("operand kinds:", dict(kinds.most_common())) - print("unparsed (raw) operands:", raw.most_common(15)) - - -if __name__ == "__main__": - try: # a redirected stdout is strict ANSI code page under -I; write '?' for what it cannot encode - sys.stdout.reconfigure(errors="replace") - except (AttributeError, ValueError, OSError): - pass - sys.exit(main()) diff --git a/tools/shader_library.py b/tools/shader_library.py deleted file mode 100644 index 3f4d6d457..000000000 --- a/tools/shader_library.py +++ /dev/null @@ -1,406 +0,0 @@ -"""Unpack the pipeline library in shaders.rpf: the zlib part of the archive that tools/shader_carve.py does not read. - -Behind the 26,503 raw-deflate shader entries, shaders.rpf holds one more file, stored as 64 KiB zlib blocks laid end -to end. It is a library of precompiled pipelines: graphics and compute pipeline records that name their programs per -stage, a table of state blobs and a table of native RDNA2 programs. Layout (docs/shader_library.md): - - 0x00 'PS' 00 09, a name ("0x65F41EDD") and a version string ("930.048.020") - 0x48 u64 hash - 0x50 u32 graphics pipelines G, u32 compute pipelines C, u32 blobs B, u32 programs P - 0x60 u32 blob section size, u32 code section size - 0x80 G x 0x70 graphics: u64 hash, u32 state blob, u32 input-layout blob, 40 bytes, 7 x (u32 program, u32 blob) - C x 24 compute: u64 hash, u32 state blob, u32 blob, u32 program, u32 blob - B x 8 (offset, size) into the blob section - P x 8 (offset, size) into the code section, 256-byte aligned - blob section, then code section; the file ends exactly there - -A missing stage is program 0xFFFFFFFF. Stage slots: 0 pixel, 1 vertex, 2 mesh (6 is used once and not identified). -A compute state blob has the 28-byte layout of an FSPX kind-0 entry (tools/fspx_unpack.py), and every program starts -with the same 36-byte hash prologue as an FSPX program, so the programs are written in the layout fspx_unpack.py uses -and tools/rdna2spirv.py reads (fspx/.code, fspx/.json, index.json). A compute program also gets its -record's state blob as fspx/.state, as fspx_unpack.py writes kind 0: the runtime finds a program the executable -passes to Xbox device slot 67 by the SHA-256 of both (docs/fspx.md, "Build and run-time lookup"). In the 1.0.2.1 -library every compute program has exactly one state blob (2,684 programs, 2,693 records). - -Usage: - python -I shader_library.py --out DIR [--stages cs,ps,vs,ms] [--disasm] - [--mcpu gfx1013] [--jobs N] - python -I shader_library.py --save library.bin # the reassembled file, nothing else - -DIR/library.json gets the header, both pipeline tables (stage -> program name) and the per-program stage. Programs -are named lib__. The output is game data and must stay in the user's work folder. -""" -import argparse -import json -import mmap -import os -import re -import struct -import sys -import zlib -from concurrent.futures import ThreadPoolExecutor - -sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) -import fspx_unpack # noqa: E402 - -MAGIC = b"PS\x00\x09" -HEADER = 0x80 -GFX_SIZE = 0x70 -CS_SIZE = 24 -NONE = 0xFFFFFFFF -SLOTS = {0: "ps", 1: "vs", 2: "ms", 6: "slot6"} -ZHDR = re.compile(rb"\x78[\x01\x5e\x9c\xda]") -BLOCK = 1 << 16 - - -class LibraryError(ValueError): - pass - - -def header(b: bytes) -> dict: - if len(b) < HEADER or b[:4] != MAGIC: - raise LibraryError("not a pipeline library (no 'PS' 00 09 header)") - g, c, nb, npg, bsize, csize = struct.unpack_from("<6I", b, 0x50) - return { - "name": b[4:0x24].split(b"\0")[0].decode("latin-1"), - "version": b[0x24:0x48].split(b"\0")[0].decode("latin-1"), - "hash": f"{struct.unpack_from(' dict: - """Section offsets for a header; 'end' is the size the file must have.""" - gfx = HEADER - cs = gfx + h["graphics"] * GFX_SIZE - blobs = cs + h["compute"] * CS_SIZE - progs = blobs + h["blobs"] * 8 - blob_data = progs + h["programs"] * 8 - code = blob_data + h["blob_bytes"] - return {"graphics": gfx, "compute": cs, "blob_table": blobs, "program_table": progs, "blob_data": blob_data, - "code": code, "end": code + h["code_bytes"]} - - -def find_library(m) -> bytes: - """Reassemble the library from the archive's zlib blocks: the first stream that inflates to the header starts - it, and the following streams are appended until the size the header gives.""" - pos, out, need, start = 0, None, None, None - while pos < len(m): - mt = ZHDR.search(m, pos) - if not mt: - break - s = mt.start() - d = zlib.decompressobj() - inp = m[s:s + 2 * BLOCK] # a 64 KiB block never deflates to more than this - try: - data = d.decompress(inp) + d.flush() - except zlib.error: - pos = s + 1 - continue - if not d.eof: - pos = s + 1 - continue - used = len(inp) - len(d.unused_data) - if out is None: - if data[:4] == MAGIC and len(data) >= HEADER: - need, out, start = layout(header(data))["end"], bytearray(data), s - else: - out += data - pos = s + used - if out is not None and len(out) >= need: - break - if out is None: - raise LibraryError("no pipeline library found") - if len(out) != need: - raise LibraryError(f"library at 0x{start:x} is {len(out)} bytes, the header gives {need}") - return bytes(out) - - -def table(b: bytes, off: int, count: int): - return [struct.unpack_from(" dict: - h = header(b) - lay = layout(h) - if lay["end"] != len(b): - raise LibraryError(f"file is {len(b)} bytes, the header gives {lay['end']}") - blobs = table(b, lay["blob_table"], h["blobs"]) - progs = table(b, lay["program_table"], h["programs"]) - for name, tab, size in (("blob", blobs, h["blob_bytes"]), ("program", progs, h["code_bytes"])): - for i, (o, s) in enumerate(tab): - if o + s > size: - raise LibraryError(f"{name} {i} ends past its section") - graphics, compute = [], [] - stage, links = {}, [] - - def ref(i, what): - if i != NONE and not i < (h["programs"] if what == "program" else h["blobs"]): - raise LibraryError(f"{what} index {i} out of range") - return None if i == NONE else i - - for i in range(h["graphics"]): - r = b[lay["graphics"] + i * GFX_SIZE: lay["graphics"] + (i + 1) * GFX_SIZE] - hsh, state, layout_blob = struct.unpack_from(" head size - - -def stage_digest(y: bytes): - """The 16-byte digest a stage's resource-layout blob ends with, or None. Layout: a head of STAGE_HEAD[kind] - bytes whose last word is tagged 0x40, 32-byte records tagged 0x41 or 0x42, then a word 0x43 and the digest (the - shape of an FSPX kind-7 entry, whose digest is its container's HASH part, docs/fspx.md).""" - head = STAGE_HEAD.get(y[0]) if y else None - if head is None or len(y) < head or y[head - 4] != 0x40: - return None - o = head - while o + 4 <= len(y): - tag = struct.unpack_from(" dict: - """digest -> [(shader name, container path)] over a tools/shader_carve.py output folder (its index.json and - .dxbc files).""" - import shader_carve - with open(os.path.join(folder, "index.json"), encoding="utf-8") as f: - index = json.load(f) - out = {} - for e in index: - path = os.path.join(folder, e["file"]) - try: - with open(path, "rb") as f: - c = f.read() - parts = shader_carve.parts(c) - if c[:4] != b"DXBC": - raise ValueError("not a DXBC container") - except FileNotFoundError: - continue - except (OSError, ValueError) as exc: - msg = exc.strerror if isinstance(exc, OSError) and exc.strerror else str(exc) - print(f"carve: {e['file']}: {msg}", file=sys.stderr) - if errors is not None: - errors.append((e["file"], msg)) - continue - if "HASH" in parts and parts["HASH"][1] >= 20: - o = parts["HASH"][0] - out.setdefault(c[o + 4:o + 20], []).append((e["name"], path)) - return out - - -def blob(b: bytes, lib: dict, i: int) -> bytes: - o, s = lib["blobs"][i] - base = lib["layout"]["blob_data"] - return b[base + o: base + o + s] - - -def program(b: bytes, lib: dict, i: int) -> bytes: - o, s = lib["programs"][i] - base = lib["layout"]["code"] - return b[base + o: base + o + s] - - -ENDPGM = struct.pack("= first and (last - start) % 4: - last = code.rfind(ENDPGM, 0, last) - return start, max(first, last + 4) - - -def program_name(i: int, stages) -> str: - st = "+".join(sorted(stages)) if stages else "unused" - return f"lib_{st}_{i:05d}" - - -def main(argv=None) -> int: - ap = argparse.ArgumentParser(description="Unpack the pipeline library stored in shaders.rpf.") - ap.add_argument("src", help="shaders.rpf, or a library file written with --save") - ap.add_argument("--out", help="output folder (library.json, index.json, fspx/, disasm/)") - ap.add_argument("--save", help="write the reassembled library file here") - ap.add_argument("--stages", default="cs,ps,vs,ms", - help="stages whose programs to write (default cs,ps,vs,ms; 'all' adds the unidentified slot)") - ap.add_argument("--disasm", action="store_true", help="also write disasm/.s (needs llvm-mc, see LLVM_MC)") - ap.add_argument("--mcpu", default="gfx1013", help="llvm-mc CPU for --disasm (default gfx1013)") - ap.add_argument("--carve", help="a tools/shader_carve.py output folder: name each program's source shader by the " - "digest its resource-layout blob ends with (the container's HASH part), and " - "copy that container to .dxbc for the translator's signature reads") - ap.add_argument("--jobs", type=int, default=max(1, (os.cpu_count() or 2) // 2), - help="llvm-mc processes for --disasm (default: half the CPUs)") - a = ap.parse_args(argv) - if a.jobs < 1: - ap.error("--jobs must be at least 1") - if not a.out and not a.save: - ap.error("give --out, --save or both") - with open(a.src, "rb") as f: - head = f.read(4) - f.seek(0) - if head == MAGIC: - b = f.read() - else: - if os.path.getsize(a.src) == 0: - raise LibraryError("empty input") - m = mmap.mmap(f.fileno(), 0, access=mmap.ACCESS_READ) - try: - b = find_library(m) - finally: - m.close() - lib = parse(b) - if a.save: - with open(a.save, "wb") as f: - f.write(b) - if not a.out: - print(f"library: {len(b)} bytes written to {a.save}") - return 0 - want = None if a.stages == "all" else set(a.stages.split(",")) - os.makedirs(os.path.join(a.out, "fspx"), exist_ok=True) - disasm = None - if a.disasm: - import shader_disasm # noqa: E402 (resolves LLVM_MC at import) - disasm = shader_disasm - os.makedirs(os.path.join(a.out, "disasm"), exist_ok=True) - names = {i: program_name(i, lib["stage"].get(i)) for i in range(lib["header"]["programs"])} - carve_errors = [] - sources = carve_digests(a.carve, errors=carve_errors) if a.carve else None - cs_state = {c["program"]: c["state"] for c in lib["compute"] - if c["program"] is not None and c["state"] is not None} - index, written, work = [], 0, [] - for i in range(lib["header"]["programs"]): - stages = lib["stage"].get(i, set()) - st = "+".join(sorted(stages)) if stages else "unused" - if want is not None and not stages & want: - continue - code = program(b, lib, i) - start, end = code_range(code) - meta = {"program": i, "stage": st, "offset": lib["programs"][i][0], "size": len(code), - "code": {"start": start, "end": end, "prologue": start == fspx_unpack.PROLOGUE_SIZE}} - state = blob(b, lib, cs_state[i]) if i in cs_state else None - if state is not None: - meta.update(fspx_unpack.decode_kind0(state)) - name = names[i] - entry = {"file": name + ".dxbc", "stage": st, "program": i} - digests = sorted(lib["digest"].get(i, ())) - meta["digest"] = [d.hex() for d in digests] - if sources is not None: - found = sorted({src for d in digests for src in sources.get(d, ())}) - entry["source"] = meta["source"] = sorted({n for n, _ in found}) - if found: - # The source container's signatures and PSV0 describe the stage's D3D12 interface, which the - # pipeline build keeps; the translator reads them from .dxbc next to its folder. - with open(found[0][1], "rb") as f: - container = f.read() - with open(os.path.join(a.out, name + ".dxbc"), "wb") as f: - f.write(container) - for k in ("threads", "wave32"): - if k in meta: - entry[k] = meta[k] - with open(os.path.join(a.out, "fspx", name + ".code"), "wb") as f: - f.write(code) - state_path = os.path.join(a.out, "fspx", name + ".state") - if state is not None: - with open(state_path, "wb") as f: # kind 0 as it is: its SHA-256 is the index's fspx_state_sha256 - f.write(state) - elif os.path.exists(state_path): - os.unlink(state_path) # a program that lost its compute record must not keep an old state key - with open(os.path.join(a.out, "fspx", name + ".json"), "w", encoding="utf-8", newline="\n") as f: - json.dump(meta, f, indent=1) - if disasm and end: - work.append((entry, name, code[start:end], start, end)) - index.append(entry) - written += 1 - - def one(job): - entry, name, code, start, end = job - asm, invalid, err = disasm.disasm(code, a.mcpu) - entry["invalid_words"] = invalid - with open(os.path.join(a.out, "disasm", name + ".s"), "w", encoding="utf-8", newline="\n") as f: - f.write(f"; {name} code 0x{start:x}..0x{end:x} (fspx), {a.mcpu}, {invalid} invalid words\n") - f.write(asm) - if err.strip(): - f.write("\n; --- llvm-mc messages ---\n; " + err.strip().replace("\n", "\n; ") + "\n") - - if work: - with ThreadPoolExecutor(a.jobs) as ex: # each job waits on its own llvm-mc process - list(ex.map(one, work)) - - def named(stages): - return {k: names[v["program"]] for k, v in stages.items()} - - summary = { - "header": lib["header"], - "layout": lib["layout"], - "graphics": [{"hash": g["hash"], "state": g["state"], "input_layout": g["input_layout"], - "stages": named(g["stages"])} for g in lib["graphics"]], - "compute": [{"hash": c["hash"], "state": c["state"], "program": names.get(c["program"])} - for c in lib["compute"]], - } - with open(os.path.join(a.out, "library.json"), "w", encoding="utf-8", newline="\n") as f: - json.dump(summary, f, indent=1) - with open(os.path.join(a.out, "index.json"), "w", encoding="utf-8", newline="\n") as f: - json.dump(index, f, indent=1) - h = lib["header"] - print(f"library {h['name']} {h['version']}: {h['graphics']} graphics + {h['compute']} compute pipelines, " - f"{h['programs']} programs; {written} written to {a.out}") - if sources is not None: - linked = sum(1 for e in index if e["source"]) - extra = (f", {len(carve_errors)} unreadable/corrupt container" - f"{'s' if len(carve_errors) != 1 else ''}") if carve_errors else "" - print(f"{linked} of {written} named by a carved shader's HASH digest, " - f"{written - linked} not in the carve{extra}") - return 0 - - -if __name__ == "__main__": - try: # a redirected stdout is strict ANSI code page under -I; write '?' for what it cannot encode - sys.stdout.reconfigure(errors="replace") - except AttributeError: - pass - try: - sys.exit(main()) - except LibraryError as e: - print(f"error: {e}", file=sys.stderr) - sys.exit(1) diff --git a/tools/shader_link_check.py b/tools/shader_link_check.py deleted file mode 100644 index b8ea82038..000000000 --- a/tools/shader_link_check.py +++ /dev/null @@ -1,350 +0,0 @@ -"""Check user-defined varying interfaces between translated graphics stages. - -Run `python -I tools/shader_link_check.py --help` for standalone pairs, batch checks, -and reflection of a single SPIR-V module. -""" -from __future__ import annotations - -import argparse -from dataclasses import asdict, dataclass -import json -import os -from pathlib import Path -import re -import sys -import tempfile - -sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) -from file_mode import published_mode # noqa: E402 -from spirv_interface import (Address, Declaration, InterfaceError, NumericType, # noqa: E402 - StageInterface, reflect_module) - - -STAGES = ("vs", "gs", "ms", "ps") -CHAINS = {("vs", "ps"), ("vs", "gs", "ps"), ("ms", "ps"), ("vs", "gs")} -# A manifest names a shader by its file stem in --shader-dir. The stem must stay one path component inside that -# folder: no separators or drive colon, not "." or "..", and no character a Windows file name can't hold. Anything -# else is allowed: make_game's corpus names use "~", "!", "&", "(" and a leading ".". -BAD_STEM = re.compile(r'[\\/:<>"|?*\x00-\x1f]') - - -def is_shader_stem(reference): - return isinstance(reference, str) and reference not in ("", ".", "..") \ - and not BAD_STEM.search(reference) and reference == reference.strip() - - -@dataclass(frozen=True) -class ModulePath: - path: Path - stage: str - entry: str = "main" - - -@dataclass(frozen=True) -class Pipeline: - name: str - modules: tuple[ModulePath, ...] - - -@dataclass(frozen=True) -class Problem: - kind: str - consumer: str - message: str - producer: str | None = None - location: Address | None = None - - def display(self): - stages = f"{self.producer} -> {self.consumer}" if self.producer else self.consumer - where = f" at {self.location.describe()}" if self.location is not None else "" - return f"{stages}{where} [{self.kind}] {self.message}" - - -@dataclass -class PipelineResult: - name: str - status: str - links_checked: int - problems: list[Problem] - - -def wider_vector_compatible(producer, consumer, allow): - if not allow or producer.structure or consumer.structure: - return False - if producer.indexed_by_vertex_or_primitive or consumer.indexed_by_vertex_or_primitive: - return False - p, c = producer.varyings[0].type, consumer.varyings[0].type - # maintenance4 relaxes the length of vector variables. Scalar vs vector, nested types, - # and arrays which were unwrapped for a stage's invocation index still need exact types. - return (isinstance(p, NumericType) and isinstance(c, NumericType) - and p.kind == c.kind and p.width == c.width and p.components > c.components >= 2) - - -def compare_stages(producer: StageInterface, consumer: StageInterface, maintenance4=False): - """Check consumer declarations against the preceding stage's output declarations.""" - output_slots = {slot: declaration - for declaration in producer.outputs - for varying in declaration.varyings - for slot in varying.occupied()} - problems = [] - for expected in consumer.inputs: - anchor = expected.varyings[0].address - actual = output_slots.get(anchor) - - def problem(kind, message): - return Problem(kind, consumer.stage, message, producer.stage, anchor) - - if actual is None: - problems.append(problem("missing-output", f"consumer expects {expected.describe()}")) - continue - if actual.structure != expected.structure or actual.block != expected.block: - problems.append(problem("structure-mismatch", f"{actual.describe()} cannot match {expected.describe()}")) - continue - if tuple(v.address for v in actual.varyings) != tuple(v.address for v in expected.varyings): - problems.append(problem("location-mismatch", - f"{actual.describe()} starts or places its members differently from " - f"{expected.describe()}")) - continue - if tuple(v.per_primitive for v in actual.varyings) != tuple(v.per_primitive for v in expected.varyings): - problems.append(problem("per-primitive-mismatch", - f"producer declares {actual.describe()}, consumer expects {expected.describe()}")) - continue - if tuple(v.type for v in actual.varyings) != tuple(v.type for v in expected.varyings): - if wider_vector_compatible(actual, expected, maintenance4): - continue - hint = (" (a wider output vector requires maintenance4)" - if wider_vector_compatible(actual, expected, True) else "") - problems.append(problem("type-mismatch", - f"producer declares {actual.describe()}, consumer expects {expected.describe()}" - f"{hint}")) - return problems - - -def stage_chain(refs): - stages = tuple(stage for stage in STAGES if stage in refs) - if stages not in CHAINS: - raise ValueError("expected vs+ps, vs+gs, vs+gs+ps, or ms+ps") - return stages - - -def reject_duplicate_keys(pairs): - doc = {} - for key, value in pairs: - if key in doc: - raise ValueError(f"duplicate key {key!r}") - doc[key] = value - return doc - - -def load_pipeline_manifest(path: Path, shader_dir: Path): - try: - # utf-8-sig: a hand-written manifest from Notepad or PowerShell 5 Out-File starts with a BOM. - with path.open(encoding="utf-8-sig") as source: - doc = json.load(source, object_pairs_hook=reject_duplicate_keys) - except (OSError, ValueError) as exc: - raise ValueError(f"{path}: {exc}") from exc - if (not isinstance(doc, dict) or set(doc) - {"pipelines", "version"} - or type(doc.get("version", 1)) is not int or doc.get("version", 1) != 1): - raise ValueError("expected a version 1 object with a pipelines list") - if not isinstance(doc.get("pipelines"), list) or not doc["pipelines"]: - raise ValueError("pipelines must be a nonempty list") - names = set() - pipelines = [] - for number, row in enumerate(doc["pipelines"], 1): - try: - if not isinstance(row, dict) or set(row) - {"name", *STAGES}: - raise ValueError("unexpected pipeline field") - name = row.get("name") - if not isinstance(name, str) or not name.strip() or any(ord(ch) < 32 for ch in name): - raise ValueError("expected one printable, nonempty pipeline name") - if name in names: - raise ValueError(f"duplicate pipeline name {name!r}") - stages = stage_chain(row) - modules = tuple(manifest_module(row[stage], shader_dir, stage) for stage in stages) - names.add(name) - pipelines.append(Pipeline(name, modules)) - except ValueError as exc: - raise ValueError(f"pipelines[{number - 1}]: {exc}") from exc - return pipelines - - -def manifest_module(reference, shader_dir, stage): - entry = "main" - if isinstance(reference, dict): - if set(reference) - {"shader", "entry"}: - raise ValueError(f"{stage}: unexpected shader reference field") - entry, reference = reference.get("entry", entry), reference.get("shader") - if not is_shader_stem(reference): - raise ValueError(f"{stage}: expected a shader name without directories") - if not isinstance(entry, str) or not entry or "\x00" in entry: - raise ValueError(f"{stage}: expected a nonempty entry-point name") - return ModulePath(shader_dir / (reference + ".spv"), stage, entry) - - -class InterfaceCache: - def __init__(self): - self.modules = {} - - def load(self, module): - if module not in self.modules: - try: - self.modules[module] = reflect_module(module.path.read_bytes(), module.stage, module.entry) - except (OSError, InterfaceError) as exc: - self.modules[module] = InterfaceError(f"{module.path}: {exc}") - result = self.modules[module] - if isinstance(result, InterfaceError): - raise result - return result - - -def check_pipeline(pipeline, cache, maintenance4=False): - interfaces = {} - problems = [] - for module in pipeline.modules: - try: - interfaces[module.stage] = cache.load(module) - except (OSError, InterfaceError) as exc: - problems.append(Problem("module-error", module.stage, str(exc))) - links = 0 - invalid = bool(problems) - for producer, consumer in zip(pipeline.modules, pipeline.modules[1:]): - if producer.stage in interfaces and consumer.stage in interfaces: - links += 1 - problems.extend(compare_stages(interfaces[producer.stage], interfaces[consumer.stage], maintenance4)) - status = "invalid" if invalid else ("incompatible" if problems else "compatible") - return PipelineResult(pipeline.name, status, links, problems) - - -def write_report(path: Path, doc): - path = path.absolute() - temporary = None - try: - with tempfile.NamedTemporaryFile(mode="w", encoding="utf-8", newline="\n", delete=False, - dir=path.parent, prefix=".shader-link-", suffix=".tmp") as target: - temporary = Path(target.name) - json.dump(doc, target, indent=2, ensure_ascii=False) - target.write("\n") - os.chmod(temporary, published_mode(path)) - os.replace(temporary, path) - finally: - if temporary is not None: - temporary.unlink(missing_ok=True) - - -def ensure_report_is_separate(output, inputs): - if output is None: - return - out = output.resolve() - try: - out_stat = out.stat() - except (FileNotFoundError, NotADirectoryError): - out_stat = None - for source in dict.fromkeys(inputs): - if out_stat is None: - aliases = out == source.resolve() - else: - try: - # Existing targets can be compared by file identity, including hard links. - aliases = os.path.samestat(out_stat, source.stat()) - except (FileNotFoundError, NotADirectoryError): - aliases = out == source.resolve() - if aliases: - raise ValueError(f"report would overwrite an input file: {source}") - - -def inspect(args): - ensure_report_is_separate(args.report, [args.module]) - interface = reflect_module(args.module.read_bytes(), args.stage, args.entry) - doc = { - "stage": interface.stage, - "entry": interface.entry, - "inputs": [declaration_row(item) for item in interface.inputs], - "outputs": [declaration_row(item) for item in interface.outputs], - } - if args.report: - write_report(args.report, doc) - else: - print(json.dumps(doc, indent=2)) - return 0 - - -def declaration_row(declaration): - return { - "id": declaration.symbol, - "structure": declaration.structure, - "block": declaration.block, - "indexed_by_vertex_or_primitive": declaration.indexed_by_vertex_or_primitive, - "varyings": [{**asdict(varying.address), "type": varying.type.describe(), - "per_primitive": varying.per_primitive} for varying in declaration.varyings], - } - - -def run_checks(args): - extra_inputs = [] - if args.command == "batch": - pipelines = load_pipeline_manifest(args.manifest, args.shader_dir) - extra_inputs = [args.manifest] - else: - refs = {} - for stage in STAGES: - path = getattr(args, stage) - entry = getattr(args, f"{stage}_entry") - if path is not None: - refs[stage] = ModulePath(path, stage, args.entry if entry is None else entry) - elif entry is not None: - raise ValueError(f"--{stage}-entry requires --{stage}") - pipelines = [Pipeline("pipeline", tuple(refs[stage] for stage in stage_chain(refs)))] - ensure_report_is_separate(args.report, [*extra_inputs, - *(module.path for pipeline in pipelines for module in pipeline.modules)]) - cache = InterfaceCache() - results = [check_pipeline(pipeline, cache, args.maintenance4) for pipeline in pipelines] - summary = {state: sum(result.status == state for result in results) - for state in ("compatible", "incompatible", "invalid")} - if args.report: - write_report(args.report, {"version": 1, "maintenance4": args.maintenance4, "summary": summary, - "pipelines": [asdict(result) for result in results]}) - for result in results: - if args.quiet and not result.problems: - continue - print(f"{result.name}: {result.status} ({result.links_checked} links checked)") - for problem in result.problems: - print(f" {problem.display()}") - print(", ".join(f"{count} {state}" for state, count in summary.items())) - if summary["invalid"]: - return 2 - return int(bool(summary["incompatible"])) - - -def main(argv=None): - parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) - commands = parser.add_subparsers(dest="command", required=True) - direct = commands.add_parser("check", help="check one graphics pipeline from SPIR-V file paths") - for stage in STAGES: - direct.add_argument("--" + stage, type=Path, metavar="SPV") - direct.add_argument(f"--{stage}-entry", metavar="NAME", help=f"override --entry for --{stage}") - direct.add_argument("--entry", default="main", help="default entry-point name for direct paths (default: main)") - batch = commands.add_parser("batch", help="check a JSON list of pipelines sharing a shader directory") - batch.add_argument("manifest", type=Path) - batch.add_argument("--shader-dir", type=Path, required=True, help="directory holding the named .spv files") - for command in (direct, batch): - command.add_argument("--maintenance4", action="store_true", - help="allow wider output vectors when the pipeline enables maintenance4") - command.add_argument("--quiet", action="store_true", help="display diagnostics and the summary") - command.add_argument("--report", type=Path, help="write structured results to JSON") - single = commands.add_parser("inspect", help="show the reflected user inputs and outputs of one entry point") - single.add_argument("module", type=Path) - single.add_argument("--stage", choices=STAGES, help="select a stage when multiple entry points share a name") - single.add_argument("--entry", default="main") - single.add_argument("--report", type=Path, help="write the reflection to JSON") - args = parser.parse_args(argv) - try: - return inspect(args) if args.command == "inspect" else run_checks(args) - except (OSError, ValueError) as exc: - print(f"shader_link_check: error: {exc}", file=sys.stderr) - return 2 - - -if __name__ == "__main__": - if hasattr(sys.stdout, "reconfigure"): - sys.stdout.reconfigure(errors="replace") - sys.exit(main()) diff --git a/tools/shader_meta.py b/tools/shader_meta.py deleted file mode 100644 index e08b16bb6..000000000 --- a/tools/shader_meta.py +++ /dev/null @@ -1,759 +0,0 @@ -"""Static build-time metadata extracted from RDNA2 disassembly, DXBC containers and FSSM blobs. - -Produces the per-shader fields described in docs/d3d12_vulkan.md (sections 3.5 and 3.6) for spirv/index.json so a -D3D12-to-Vulkan runtime can map root signatures to user SGPRs, match PSO shaders by FSSM content hash, bind vertex -inputs by ISG1 semantic name/index, pre-register literal S# samplers, and check descriptor-indexing modes without -parsing SPIR-V or guessing. - -Standard library only; no game data. -""" -import hashlib -import os -import struct - -# DXBC SFI0 (Shader Feature Info) 64-bit bitmask flags (Microsoft DXC DxilConstants.h). -SFI0_RESOURCE_DESCRIPTOR_HEAP_INDEXING = 1 << 25 # 0x02000000 -SFI0_SAMPLER_DESCRIPTOR_HEAP_INDEXING = 1 << 26 # 0x04000000 - -# DXBC ISG1 component types (D3D_REGISTER_COMPONENT_TYPE). -COMPONENT_TYPES = {1: "uint", 2: "sint", 3: "float"} - -# Instructions whose operands are all sources (no SGPR destination). -NO_SGPR_DST = ( - "exp", "s_cmp_", "s_cmpk_", "s_bitcmp", "s_set", "s_rfe", "s_sendmsg", "s_branch", "s_cbranch", - "s_endpgm", "s_waitcnt", "s_nop", "s_sleep", "s_barrier", "s_clause", "s_delay_alu", "s_setprio", - "s_inst_prefetch", "s_dcache_", "s_icache_", "s_store_", "s_buffer_store_", "buffer_store", - "buffer_atomic", "global_store", "global_atomic", "flat_store", "flat_atomic", "tbuffer_store", - "image_store", "image_atomic", "ds_write", -) - -# Scalar instructions that read AND write a[0]. -SGPR_RMW = ( - "s_addk_i32", "s_mulk_i32", "s_cmovk_i32", - "s_cmov_b32", "s_cmov_b64", - "s_bitset0_b32", "s_bitset1_b32", "s_bitset0_b64", "s_bitset1_b64", -) - -# Image instructions whose fourth operand a[3] is a 4-dword sampler descriptor (S#). -SAMPLER_IMAGE_OPS = ("image_sample", "image_gather4", "image_get_lod") - -# Scalar shift-add instructions: s_lshlK_add_u32 sD, sIdx, sBase -> sD = (sIdx << K) + sBase. -LSHL_ADD_SHIFT = { - "s_lshl1_add_u32": 1, - "s_lshl2_add_u32": 2, - "s_lshl3_add_u32": 3, - "s_lshl4_add_u32": 4, -} - -# Classification precedence when the same user SGPR participates in multiple roles. -KIND_PRIORITY = { - "const32": 0, - "ptr32_lo": 1, - "ptr64_lo": 2, - "ptr64_hi": 2, - "vsharp": 3, - "tsharp": 3, - "ssharp": 3, -} - - -def base_op(op): - for suffix in ("_e32", "_e64", "_sdwa", "_dpp"): - if op.endswith(suffix): - return op[:-len(suffix)] - return op - - -def _imm_u32(a): - """32-bit unsigned constant value of an imm/fimm operand, or None.""" - if a["k"] == "imm": - v = a["v"] & 0xFFFFFFFF - elif a["k"] == "fimm": - try: - v = struct.unpack("= n: - return list(range(a["r"], a["r"] + n)) - elif a["k"] == "slist": - items = a["r"] - if len(items) == n if exact else len(items) >= n: - return list(items[:n]) - return None - - -def _slot_tag(sym, slot): - return sym.get(slot) if isinstance(slot, int) else None - - -def _record_ptr_pair(events, sym, slots, is_desc_width=False): - lo_t, hi_t = _slot_tag(sym, slots[0]), _slot_tag(sym, slots[1]) - u_lo, u_hi = _user_of(lo_t), _user_of(hi_t) - if u_lo is not None and u_hi is not None: - events["ptr64"].add((u_lo, u_hi)) - if is_desc_width: - events["table_loads"] = True - elif u_lo is not None and hi_t == ("const", 0): - events["ptr32_lo"].add(u_lo) - events["truncates_high"] = True - if is_desc_width: - events["table_loads"] = True - elif u_lo is not None: - events["ptr64_lo_only"].add(u_lo) - if is_desc_width: - events["table_loads"] = True - - -def _user_of(tag): - if tag is not None and tag[0] in ("user", "user_off"): - return tag[1] - return None - - -def _const_of(sym, a): - v = _imm_u32(a) - if v is not None: - return v - if a["k"] == "sgpr" and a.get("n", 1) == 1: - t = sym.get(a["r"]) - if t is not None and t[0] == "const": - return t[1] - if a["k"] == "special" and a.get("t") == "null": - return 0 - return None - - -def _split_operands(ins): - """Return (read_sgprs, write_sgprs) for one parsed instruction.""" - op = base_op(ins["op"]) - a = ins["args"] - if not a: - return [], [] - if op.startswith(NO_SGPR_DST): - reads = [r for x in a for r in _sgpr_regs(x)] - return reads, [] - if op.startswith("v_cmpx_"): - # e32 has 2 source operands; e64 has dst in a[0] and 2 sources in a[1:3]. - if len(a) <= 2: - return [r for x in a for r in _sgpr_regs(x)], [] - return [r for x in a[1:] for r in _sgpr_regs(x)], _sgpr_regs(a[0]) - if op.startswith("v_cmp_"): - if len(a) <= 2: - return [r for x in a for r in _sgpr_regs(x)], [] - return [r for x in a[1:] for r in _sgpr_regs(x)], _sgpr_regs(a[0]) - if op in SGPR_RMW: - reads = [r for x in a for r in _sgpr_regs(x)] - return reads, _sgpr_regs(a[0]) - if (op.startswith("v_") and "_co_" in op) or op in ( - "v_mad_u64_u32", "v_mad_i64_i32", "v_div_scale_f32", "v_div_scale_f64", - ): - # vdst in a[0], scalar carry/scale-out dst in a[1], sources in a[2:]. - writes = _sgpr_regs(a[0]) + (_sgpr_regs(a[1]) if len(a) > 1 else []) - reads = [r for x in a[2:] for r in _sgpr_regs(x)] - return reads, writes - reads = [r for x in a[1:] for r in _sgpr_regs(x)] - writes = _sgpr_regs(a[0]) - return reads, writes - - -def _fold_scalar_alu(op, x, y): - if op in ("s_add_u32", "s_add_i32"): - return (x + y) & 0xFFFFFFFF - if op in ("s_sub_u32", "s_sub_i32"): - return (x - y) & 0xFFFFFFFF - if op == "s_and_b32": - return x & y - if op == "s_or_b32": - return x | y - if op == "s_xor_b32": - return x ^ y - if op == "s_andn2_b32": - return x & (~y & 0xFFFFFFFF) - if op == "s_orn2_b32": - return (x | (~y & 0xFFFFFFFF)) & 0xFFFFFFFF - if op == "s_nand_b32": - return ~(x & y) & 0xFFFFFFFF - if op == "s_nor_b32": - return ~(x | y) & 0xFFFFFFFF - if op == "s_xnor_b32": - return ~(x ^ y) & 0xFFFFFFFF - if op == "s_lshl_b32": - return (x << (y & 31)) & 0xFFFFFFFF - if op == "s_lshr_b32": - return (x & 0xFFFFFFFF) >> (y & 31) - if op == "s_mul_i32": - return (x * y) & 0xFFFFFFFF - if op == "s_ashr_i32": - signed = x - 0x100000000 if x & 0x80000000 else x - return (signed >> (y & 31)) & 0xFFFFFFFF - if op == "s_bfm_b32": - # A mask of (x & 31) ones, shifted left by (y & 31). - return (((1 << (x & 31)) - 1) << (y & 31)) & 0xFFFFFFFF - if op == "s_bfe_u32": - # y packs the offset in bits [4:0] and the width in bits [22:16]; the field stops at bit 31. - offset = y & 31 - width = min((y >> 16) & 0x7F, 32 - offset) - return ((x & 0xFFFFFFFF) >> offset) & ((1 << width) - 1) - if op == "s_min_u32": - return min(x & 0xFFFFFFFF, y & 0xFFFFFFFF) - if op == "s_max_u32": - return max(x & 0xFFFFFFFF, y & 0xFFFFFFFF) - return None - - -def _valid_stride(n): - return isinstance(n, int) and 4 <= n <= 4096 and n % 4 == 0 - - -def _step_state(sym, scale, ptr_stride, vscale, ins, events=None): - """Advance symbolic SGPR origin/constants and descriptor-stride state by one instruction.""" - op = base_op(ins["op"]) - a = ins["args"] - if not a: - return - - # Record pointer, descriptor, stride and literal-sampler observations BEFORE writes clobber operands. - if events is not None: - if op.startswith(("s_load_dword", "s_store_dword")) and len(a) >= 2: - slots = _sgpr_slots(a[1], 2) - if slots is not None: - is_desc_width = op in ("s_load_dwordx4", "s_load_dwordx8", "s_load_dwordx16") - _record_ptr_pair(events, sym, slots, is_desc_width=is_desc_width) - if is_desc_width: - if isinstance(slots[0], int): - events["strides"].update(ptr_stride.get(slots[0], ())) - if len(a) >= 3 and a[2]["k"] == "sgpr" and a[2].get("n", 1) == 1: - events["strides"].update(scale.get(a[2]["r"], ())) - elif op.startswith(("s_buffer_load_dword", "s_buffer_store_dword")) and len(a) >= 2: - slots = _sgpr_slots(a[1], 4) - if slots is not None: - tags = [_slot_tag(sym, s) for s in slots] - if all(t is not None and t[0] == "user" for t in tags): - for t in tags: - events["vsharp"].add(t[1]) - if op in ("s_buffer_load_dwordx4", "s_buffer_load_dwordx8", "s_buffer_load_dwordx16"): - if len(a) >= 3 and a[2]["k"] == "sgpr" and a[2].get("n", 1) == 1: - events["strides"].update(scale.get(a[2]["r"], ())) - elif op.startswith(("global_load", "global_store")) and len(a) >= 3: - slots = _sgpr_slots(a[2], 2) - if slots is not None: - _record_ptr_pair(events, sym, slots, is_desc_width=False) - elif op.startswith("global_atomic_"): - saddr_idx = 3 if "glc" in ins.get("mods", ()) else 2 - if len(a) > saddr_idx: - slots = _sgpr_slots(a[saddr_idx], 2) - if slots is not None: - _record_ptr_pair(events, sym, slots, is_desc_width=False) - elif op.startswith(("buffer_load", "buffer_store", "buffer_atomic", "tbuffer_")) and len(a) >= 3: - slots = _sgpr_slots(a[2], 4) - if slots is not None: - tags = [_slot_tag(sym, s) for s in slots] - if all(t is not None and t[0] == "user" for t in tags): - for t in tags: - events["vsharp"].add(t[1]) - elif op.startswith("image_") and len(a) >= 3: - slots = _sgpr_slots(a[2], 8, exact=False) - if slots is not None: - tags = [_slot_tag(sym, s) for s in slots] - if all(t is not None and t[0] == "user" for t in tags): - for t in tags: - events["tsharp"].add(t[1]) - if op.startswith(SAMPLER_IMAGE_OPS) and len(a) >= 4: - s_slots = _sgpr_slots(a[3], 4, exact=False) - if s_slots is not None: - tags = [_slot_tag(sym, s) for s in s_slots] - if all(t is not None and t[0] == "const" for t in tags): - events["literal_samplers"].add(tuple(t[1] for t in tags)) - elif all(t is not None and t[0] == "user" for t in tags): - for t in tags: - events["ssharp"].add(t[1]) - - # Track VGPR index scaling (e.g. v_lshlrev_b32 -> v_readfirstlane_b32 -> s_load_dwordx8). - if a[0]["k"] == "vgpr" and not op.startswith(NO_SGPR_DST) and not op.startswith("v_cmp"): - vd = a[0]["r"] - vn = a[0].get("n", 1) - new_vs = frozenset() - if vn == 1: - if op == "v_lshlrev_b32" and len(a) >= 3: - sh = _imm_u32(a[1]) - if sh is not None and 2 <= sh <= 12: - new_vs = frozenset((1 << sh,)) - elif op in ("v_mul_lo_u32", "v_mul_u32_u24", "v_mul_i32_i24") and len(a) >= 3: - c1, c2 = _imm_u32(a[1]), _imm_u32(a[2]) - c = c2 if c1 is None else c1 - if _valid_stride(c): - new_vs = frozenset((c,)) - elif op == "v_mov_b32" and len(a) >= 2 and a[1]["k"] == "vgpr" and a[1].get("n", 1) == 1: - new_vs = vscale.get(a[1]["r"], frozenset()) - elif op == "v_add_nc_u32" and len(a) >= 3: - if a[1]["k"] == "vgpr" and _imm_u32(a[2]) is not None: - new_vs = vscale.get(a[1]["r"], frozenset()) - elif a[2]["k"] == "vgpr" and _imm_u32(a[1]) is not None: - new_vs = vscale.get(a[2]["r"], frozenset()) - for r in range(vd, vd + vn): - if r == vd and new_vs: - vscale[r] = new_vs - else: - vscale.pop(r, None) - - # Update SGPR symbolic state for writes. - _, writes = _split_operands(ins) - if not writes: - return - - new_sym = {} - new_scale = {} - new_pstride = {} - - if op == "s_mov_b32" and len(a) >= 2 and a[0]["k"] == "sgpr" and a[0].get("n", 1) == 1: - d = a[0]["r"] - c = _const_of(sym, a[1]) - if c is not None: - new_sym[d] = ("const", c) - elif a[1]["k"] == "sgpr" and a[1].get("n", 1) == 1: - s = a[1]["r"] - if s in sym: - new_sym[d] = sym[s] - if s in scale: - new_scale[d] = scale[s] - if s in ptr_stride: - new_pstride[d] = ptr_stride[s] - elif op == "s_brev_b32" and len(a) >= 2 and a[0]["k"] == "sgpr" and a[0].get("n", 1) == 1: - c = _const_of(sym, a[1]) - if c is not None: - new_sym[a[0]["r"]] = ("const", int(f"{c & 0xFFFFFFFF:032b}"[::-1], 2)) - elif op == "s_movk_i32" and len(a) >= 2 and a[0]["k"] == "sgpr" and a[0].get("n", 1) == 1 and a[1]["k"] == "imm": - v = a[1]["v"] & 0xFFFF - if v & 0x8000: - v -= 0x10000 - new_sym[a[0]["r"]] = ("const", v & 0xFFFFFFFF) - elif op == "s_mov_b64" and len(a) >= 2 and a[0]["k"] == "sgpr" and a[0].get("n") == 2: - d = a[0]["r"] - if a[1]["k"] == "imm": - v = a[1]["v"] & 0xFFFFFFFFFFFFFFFF - new_sym[d] = ("const", v & 0xFFFFFFFF) - new_sym[d + 1] = ("const", (v >> 32) & 0xFFFFFFFF) - elif a[1]["k"] == "sgpr" and a[1].get("n") == 2: - s = a[1]["r"] - for i in (0, 1): - if s + i in sym: - new_sym[d + i] = sym[s + i] - if s + i in ptr_stride: - new_pstride[d + i] = ptr_stride[s + i] - elif op == "s_not_b32" and len(a) >= 2 and a[0]["k"] == "sgpr" and a[0].get("n", 1) == 1: - # A dword of a literal S# built as the complement of a known constant (for example 0xFFFFFFFF from 0). - c = _const_of(sym, a[1]) - if c is not None: - new_sym[a[0]["r"]] = ("const", ~c & 0xFFFFFFFF) - elif op == "s_abs_i32" and len(a) >= 2 and a[0]["k"] == "sgpr" and a[0].get("n", 1) == 1: - c = _const_of(sym, a[1]) - if c is not None: - signed = c - 0x100000000 if c & 0x80000000 else c - new_sym[a[0]["r"]] = ("const", abs(signed) & 0xFFFFFFFF) # abs(0x80000000) stays 0x80000000 - elif op == "v_readfirstlane_b32" and len(a) >= 2 and a[0]["k"] == "sgpr" and a[0].get("n", 1) == 1: - if a[1]["k"] == "vgpr" and a[1].get("n", 1) == 1 and a[1]["r"] in vscale: - new_scale[a[0]["r"]] = vscale[a[1]["r"]] - elif op in LSHL_ADD_SHIFT and len(a) >= 3 and a[0]["k"] == "sgpr" and a[0].get("n", 1) == 1: - d = a[0]["r"] - stride = 1 << LSHL_ADD_SHIFT[op] - base_tag = sym.get(a[2]["r"]) if a[2]["k"] == "sgpr" and a[2].get("n", 1) == 1 else None - u = _user_of(base_tag) - if u is not None: - new_sym[d] = ("user_off", u) - if _valid_stride(stride): - new_pstride[d] = ptr_stride.get(a[2]["r"], frozenset()) | frozenset((stride,)) - else: - cx, cy = _const_of(sym, a[1]), _const_of(sym, a[2]) - if cx is not None and cy is not None: - new_sym[d] = ("const", ((cx << LSHL_ADD_SHIFT[op]) + cy) & 0xFFFFFFFF) - elif op in ("s_add_u32", "s_add_i32", "s_sub_u32", "s_sub_i32") and len(a) >= 3 and a[0]["k"] == "sgpr": - d = a[0]["r"] - cx, cy = _const_of(sym, a[1]), _const_of(sym, a[2]) - if cx is not None and cy is not None: - new_sym[d] = ("const", _fold_scalar_alu(op, cx, cy)) - else: - tx = sym.get(a[1]["r"]) if a[1]["k"] == "sgpr" and a[1].get("n", 1) == 1 else None - ty = sym.get(a[2]["r"]) if a[2]["k"] == "sgpr" and a[2].get("n", 1) == 1 else None - ux, uy = _user_of(tx), _user_of(ty) - sx = scale.get(a[1]["r"], frozenset()) if a[1]["k"] == "sgpr" else frozenset() - sy = scale.get(a[2]["r"], frozenset()) if a[2]["k"] == "sgpr" else frozenset() - psx = ptr_stride.get(a[1]["r"], frozenset()) if a[1]["k"] == "sgpr" else frozenset() - psy = ptr_stride.get(a[2]["r"], frozenset()) if a[2]["k"] == "sgpr" else frozenset() - if ux is not None and uy is None: - new_sym[d] = ("user_off", ux) - if psx or sy: - new_pstride[d] = psx | sy - elif op.startswith("s_add") and uy is not None and ux is None: - new_sym[d] = ("user_off", uy) - if psy or sx: - new_pstride[d] = psy | sx - elif sx and cy is not None: - new_scale[d] = sx - elif op.startswith("s_add") and sy and cx is not None: - new_scale[d] = sy - elif op in ("s_addc_u32", "s_subb_u32") and len(a) >= 3 and a[0]["k"] == "sgpr": - d = a[0]["r"] - tx = sym.get(a[1]["r"]) if a[1]["k"] == "sgpr" and a[1].get("n", 1) == 1 else None - ty = sym.get(a[2]["r"]) if a[2]["k"] == "sgpr" and a[2].get("n", 1) == 1 else None - ux, uy = _user_of(tx), _user_of(ty) - if ux is not None: - new_sym[d] = ("user_off", ux) - elif op == "s_addc_u32" and uy is not None: - new_sym[d] = ("user_off", uy) - elif _const_of(sym, a[1]) == 0 and _const_of(sym, a[2]) == 0: - # High-dword carry-add on a zeroed upper word (descriptor table truncated below 4 GB). - new_sym[d] = ("const", 0) - elif op in ("s_lshl_b32", "s_lshr_b32", "s_mul_i32", "s_and_b32", "s_or_b32", "s_xor_b32", - "s_andn2_b32", "s_orn2_b32", "s_nand_b32", "s_nor_b32", "s_xnor_b32", "s_ashr_i32", - "s_bfm_b32", "s_bfe_u32", "s_min_u32", "s_max_u32") and len(a) >= 3 and a[0]["k"] == "sgpr": - d = a[0]["r"] - cx, cy = _const_of(sym, a[1]), _const_of(sym, a[2]) - if cx is not None and cy is not None: - new_sym[d] = ("const", _fold_scalar_alu(op, cx, cy)) - elif op == "s_lshl_b32" and cy is not None and 2 <= cy <= 12: - new_scale[d] = frozenset((1 << cy,)) - elif op == "s_mul_i32": - c = cy if cy is not None else cx - if _valid_stride(c): - new_scale[d] = frozenset((c,)) - elif op == "s_addk_i32" and len(a) >= 2 and a[0]["k"] == "sgpr" and a[0].get("n", 1) == 1 and a[1]["k"] == "imm": - d = a[0]["r"] - v = a[1]["v"] & 0xFFFF - if v & 0x8000: - v -= 0x10000 - old = sym.get(d) - if old is not None and old[0] == "const": - new_sym[d] = ("const", (old[1] + v) & 0xFFFFFFFF) - elif _user_of(old) is not None: - new_sym[d] = ("user_off", _user_of(old)) - if d in ptr_stride: - new_pstride[d] = ptr_stride[d] - elif d in scale: - new_scale[d] = scale[d] - elif op == "s_mulk_i32" and len(a) >= 2 and a[0]["k"] == "sgpr" and a[0].get("n", 1) == 1 and a[1]["k"] == "imm": - d = a[0]["r"] - v = a[1]["v"] & 0xFFFF - if v & 0x8000: - v -= 0x10000 - old = sym.get(d) - if old is not None and old[0] == "const": - new_sym[d] = ("const", (old[1] * v) & 0xFFFFFFFF) - elif _valid_stride(v): - new_scale[d] = frozenset((v,)) - - for r in writes: - if r in new_sym: - sym[r] = new_sym[r] - else: - sym.pop(r, None) - if r in new_scale: - scale[r] = new_scale[r] - else: - scale.pop(r, None) - if r in new_pstride: - ptr_stride[r] = new_pstride[r] - else: - ptr_stride.pop(r, None) - - -def analyse_instructions(blocks, succ, user_sgpr_limit=32, system_sgprs=()): - """Analyse reachable RDNA2 basic blocks for user-SGPR reads/kinds, descriptor strides and literal samplers. - - Returns a dict with: - user_sgpr_reads: [{"sgpr": r, "kind": "const32"|"ptr64_lo"|"ptr64_hi"|"ptr32_lo"|"vsharp"|"tsharp"|"ssharp", ...}] - descriptor_strides: sorted list of byte strides implied by descriptor address arithmetic - literal_samplers: sorted list of 4-dword literal S# values built from immediates - table_loads: bool, whether the shader loads 4/8/16-dword descriptors from a user-SGPR pointer - truncates_high: bool, whether any user-SGPR pointer has its high 32-bit word forced to 0 - """ - nblk = len(blocks) - if nblk == 0: - return {"user_sgpr_reads": [], "descriptor_strides": [], "literal_samplers": [], - "table_loads": False, "truncates_high": False} - sys_set = frozenset(system_sgprs) - user_range = {r for r in range(user_sgpr_limit) if r not in sys_set} - - # Fixed-point forward dataflow from block 0: - # entry_written[b]: SGPRs definitely written on every path to block b (must-write). - # entry_sym[b]: SGPR -> symbolic origin/const that agrees on every path to block b. - # entry_scale[b], entry_pstride[b], entry_vscale[b]: union of observed descriptor byte strides. - entry_written = [None] * nblk - entry_sym = [None] * nblk - entry_scale = [None] * nblk - entry_pstride = [None] * nblk - entry_vscale = [None] * nblk - - entry_written[0] = frozenset() - entry_sym[0] = {r: ("user", r) for r in user_range} - entry_scale[0] = {} - entry_pstride[0] = {} - entry_vscale[0] = {} - work = [0] - - def merge_sets(dst, src): - out = dict(dst) - for k, v in src.items(): - out[k] = out[k] | v if k in out else v - return out - - while work: - b = work.pop() - written = set(entry_written[b]) - sym = dict(entry_sym[b]) - scale = dict(entry_scale[b]) - pstride = dict(entry_pstride[b]) - vscale = dict(entry_vscale[b]) - for ins in blocks[b]: - if base_op(ins["op"]) == "s_endpgm": - break - _, writes = _split_operands(ins) - _step_state(sym, scale, pstride, vscale, ins, events=None) - written.update(writes) - out_w = frozenset(written) - for s in succ[b]: - if entry_written[s] is None: - mw = out_w - ms = dict(sym) - msc = dict(scale) - mps = dict(pstride) - mvs = dict(vscale) - else: - mw = entry_written[s] & out_w - ms = {k: v for k, v in entry_sym[s].items() if sym.get(k) == v} - msc = merge_sets(entry_scale[s], scale) - mps = merge_sets(entry_pstride[s], pstride) - mvs = merge_sets(entry_vscale[s], vscale) - if (mw != entry_written[s] or ms != entry_sym[s] or msc != entry_scale[s] or - mps != entry_pstride[s] or mvs != entry_vscale[s]): - entry_written[s] = mw - entry_sym[s] = ms - entry_scale[s] = msc - entry_pstride[s] = mps - entry_vscale[s] = mvs - work.append(s) - - # Final pass over all reachable blocks to collect read-before-write user SGPRs and events. - rbw = set() - events = { - "ptr64": set(), - "ptr64_lo_only": set(), - "ptr32_lo": set(), - "vsharp": set(), - "tsharp": set(), - "ssharp": set(), - "strides": set(), - "literal_samplers": set(), - "table_loads": False, - "truncates_high": False, - } - for b in range(nblk): - if entry_written[b] is None: - continue - written = set(entry_written[b]) - sym = dict(entry_sym[b]) - scale = dict(entry_scale[b]) - pstride = dict(entry_pstride[b]) - vscale = dict(entry_vscale[b]) - for ins in blocks[b]: - if base_op(ins["op"]) == "s_endpgm": - break - reads, writes = _split_operands(ins) - for r in reads: - if r in user_range and r not in written: - rbw.add(r) - _step_state(sym, scale, pstride, vscale, ins, events=events) - written.update(writes) - - # Assign the strongest observed kind to each read-before-write user SGPR. - kinds = {r: "const32" for r in rbw} - pairs = {} - - def promote(r, kind): - if r in kinds and KIND_PRIORITY[kind] > KIND_PRIORITY[kinds[r]]: - kinds[r] = kind - - for lo, hi in sorted(events["ptr64"]): - if lo in kinds and hi in kinds: - promote(lo, "ptr64_lo") - promote(hi, "ptr64_hi") - pairs[lo] = [lo, hi] - pairs[hi] = [lo, hi] - for lo in sorted(events["ptr64_lo_only"]): - promote(lo, "ptr64_lo") - for lo in sorted(events["ptr32_lo"]): - promote(lo, "ptr32_lo") - for kname in ("vsharp", "tsharp", "ssharp"): - for r in sorted(events[kname]): - promote(r, kname) - - user_reads = [] - for r in sorted(rbw): - row = {"sgpr": r, "kind": kinds[r]} - if r in pairs and kinds[r] in ("ptr64_lo", "ptr64_hi"): - row["pair"] = pairs[r] - user_reads.append(row) - - return { - "user_sgpr_reads": user_reads, - "descriptor_strides": sorted(events["strides"]), - "literal_samplers": [list(s) for s in sorted(events["literal_samplers"])], - "table_loads": events["table_loads"], - "truncates_high": events["truncates_high"], - } - - -def read_dxbc_meta(data): - """Parse ISG1 full input signature and SFI0 descriptor-heap indexing flags from a DXBC container.""" - if not data or len(data) < 32 or data[:4] != b"DXBC": - return {} - total, cnt = struct.unpack_from(" len(data) or total < table_end: - return {} - parts = {} - for k in range(cnt): - off = struct.unpack_from(" total: - continue - fourcc = data[off:off + 4] - plen = struct.unpack_from("= 8: - ecnt, eo = struct.unpack_from("= 8: - flags = struct.unpack_from("/../fssm/.fssm, or None if absent.""" - parent = os.path.dirname(os.path.dirname(os.path.realpath(disasm_path))) - fssm = os.path.join(parent, "fssm", name + ".fssm") - if not os.path.isfile(fssm): - return None - with open(fssm, "rb") as f: - return hashlib.sha256(f.read()).hexdigest() - - -def fspx_code_sha256_file(disasm_path, name): - """SHA-256 hex digest of /../fspx/.code, the kind-6 program tools/fspx_unpack.py writes for an - FSPX shader without an FSSM blob, or None. The run time computes the same key from the bytes a compute PSO gets - (docs/fspx.md, "Run-time lookup").""" - parent = os.path.dirname(os.path.dirname(os.path.realpath(disasm_path))) - if os.path.isfile(os.path.join(parent, "fssm", name + ".fssm")): - return None - code = os.path.join(parent, "fspx", name + ".code") - if not os.path.isfile(code): - return None - with open(code, "rb") as f: - return hashlib.sha256(f.read()).hexdigest() - - -def fspx_state_sha256_file(disasm_path, name): - """SHA-256 hex digest of /../fspx/.state, the program's kind-0 entry (dispatch state), or None. - Two FSPX programs can share their kind-6 bytes and differ in kind 0; the run time tells them apart by this key - when the bytecode carries kind 0 (docs/fspx.md, "Build and run-time lookup").""" - parent = os.path.dirname(os.path.dirname(os.path.realpath(disasm_path))) - state = os.path.join(parent, "fspx", name + ".state") - if not os.path.isfile(state): - return None - with open(state, "rb") as f: - return hashlib.sha256(f.read()).hexdigest() - - -def collect(disasm_path, name, blocks, succ, user_sgpr_limit=32, system_sgprs=()): - """Collect all build-time runtime metadata for one translated shader.""" - meta = {} - digest = fssm_sha256_file(disasm_path, name) - if digest is not None: - meta["fssm_sha256"] = digest - else: - code_digest = fspx_code_sha256_file(disasm_path, name) - if code_digest is not None: - meta["fspx_code_sha256"] = code_digest - state_digest = fspx_state_sha256_file(disasm_path, name) - if state_digest is not None: - meta["fspx_state_sha256"] = state_digest - - dxbc_info = {} - parent = os.path.dirname(os.path.dirname(os.path.realpath(disasm_path))) - dxbc_path = os.path.join(parent, name + ".dxbc") - if os.path.isfile(dxbc_path): - with open(dxbc_path, "rb") as f: - dxbc_info = read_dxbc_meta(f.read()) - if "input_signature" in dxbc_info: - meta["input_signature"] = dxbc_info["input_signature"] - - ins_info = analyse_instructions(blocks, succ, user_sgpr_limit=user_sgpr_limit, system_sgprs=system_sgprs) - if ins_info["user_sgpr_reads"]: - meta["user_sgpr_reads"] = ins_info["user_sgpr_reads"] - if ins_info["descriptor_strides"]: - meta["descriptor_strides"] = ins_info["descriptor_strides"] - if ins_info["literal_samplers"]: - meta["literal_samplers"] = ins_info["literal_samplers"] - - has_sfi0 = "sfi0_resource_heap_directly_indexed" in dxbc_info - if has_sfi0 or ins_info["table_loads"] or ins_info["truncates_high"]: - desc_access = { - "table_loads": ins_info["table_loads"], - "truncates_table_ptr_high": ins_info["truncates_high"], - } - if has_sfi0: - desc_access["resource_heap_directly_indexed"] = dxbc_info["sfi0_resource_heap_directly_indexed"] - desc_access["sampler_heap_directly_indexed"] = dxbc_info["sfi0_sampler_heap_directly_indexed"] - meta["descriptor_access"] = desc_access - - return meta diff --git a/tools/shader_profile.py b/tools/shader_profile.py deleted file mode 100644 index 0f049eee8..000000000 --- a/tools/shader_profile.py +++ /dev/null @@ -1,419 +0,0 @@ -"""Profile the disassembled shader corpus: which RDNA instructions the translator must support. - -Usage: - python -I shader_profile.py [--out profile.json] [--per-shader] - -Counts each mnemonic (number of shaders using it and total occurrences), groups them by encoding family, -classifies instructions (ALU vs memory vs branch), computes operation ratios, and summarises register pressure -per stage (VGPR/SGPR counts from `profile_shader`; `--per-shader` also lists every shader). -In the JSON report, ratios.alu_to_memory is null when the corpus has ALU instructions and no memory instructions. -`categories_by_stage` uses the carve index first, then a recognized stage prefix in the filename, otherwise `?`. - -`undecoded` counts the llvm-mc 'invalid instruction encoding' warnings shader_disasm.py copies into each .s file. -by_word lists the four bytes at each warning position, their total occurrences and how many shaders contain them. -unresolved counts warnings whose position or echoed input gives no complete word. Results depend on LLVM's -version, target and input range, which can include embedded data. - -The terminal prints warning totals. The JSON report includes the bytes, so keep reports from real shaders local -(see CONTRIBUTING.md). -""" -import argparse -import json -import os -import re -import sys -from collections import Counter, defaultdict - -FAMILIES = [("s_buffer_", "smem"), ("s_load", "smem"), ("s_", "scalar"), ("v_", "vector"), ("ds_", "lds"), - ("buffer_", "buffer"), ("tbuffer_", "buffer"), ("image_", "image"), ("global_", "global"), - ("flat_", "flat"), ("scratch_", "scratch"), ("exp", "export")] - -STAGE_PREFIX = re.compile(r"(ps|vs|gs|hs|ds|cs|ms|as|lib)_", re.IGNORECASE | re.ASCII) -VGPR_RANGE = re.compile(r"\bv\[(\d+):(\d+)\]") -VGPR_SINGLE = re.compile(r"\bv(\d+)\b") -SGPR_RANGE = re.compile(r"\bs\[(\d+):(\d+)\]") -SGPR_SINGLE = re.compile(r"\bs(\d+)\b") -SPECIAL_REG = re.compile(r"\b(vcc|vcc_lo|vcc_hi|exec|exec_lo|exec_hi|m0|scc|flat_scratch|flat_scratch_lo|flat_scratch_hi)\b") - - -def family(m): - for p, f in FAMILIES: - if m.startswith(p): - return f - return "other" - - -def classify_instruction(m: str) -> str: - """Classify an RDNA mnemonic into 'alu', 'memory', 'branch', 'export', or 'other'.""" - if not m: - return "other" - m = m.lower() - if m.startswith("exp"): - return "export" - if m == "s_branch" or m.startswith("s_cbranch_") or m in ("s_setpc_b64", "s_swappc_b64", "s_rfe_b64", "s_call_b64"): - return "branch" - if m.startswith(("s_buffer_", "s_load", "s_store_", "s_dcache_", "buffer_", "tbuffer_", "image_", "global_", "flat_", "scratch_", "ds_")): - return "memory" - if m.startswith("v_"): - return "alu" - if m.startswith("s_"): - if m in ("s_barrier", "s_nop", "s_endpgm", "s_trap", "s_sleep", "s_icache_inv") or \ - m.startswith(("s_waitcnt", "s_sendmsg", "s_setreg_", "s_getreg_", "s_setprio")): - return "other" - return "alu" - return "other" - - -def is_alu(m: str) -> bool: - return classify_instruction(m) == "alu" - - -def is_memory(m: str) -> bool: - return classify_instruction(m) == "memory" - - -def is_branch(m: str) -> bool: - return classify_instruction(m) == "branch" - - -def count_categories(mnemonics) -> dict: - """Count instruction occurrences by high-level category (alu, memory, branch, export, other).""" - counts = Counter() - if isinstance(mnemonics, dict): - for m, count in mnemonics.items(): - counts[classify_instruction(m)] += count - else: - for m in mnemonics: - counts[classify_instruction(m)] += 1 - total = sum(counts.values()) - return { - "alu": counts["alu"], - "memory": counts["memory"], - "branch": counts["branch"], - "export": counts["export"], - "other": counts["other"], - "total": total, - } - - -def compute_ratios(counts: dict) -> dict: - """Calculate ALU vs Memory vs Branch ratios relative to total instructions, - and relative ratios like alu_to_memory.""" - total = counts.get("total", 0) - if total <= 0: - total = sum(counts.get(k, 0) for k in ("alu", "memory", "branch", "export", "other")) - alu = counts.get("alu", 0) - mem = counts.get("memory", 0) - branch = counts.get("branch", 0) - return { - "alu_ratio": round(alu / total, 6) if total > 0 else 0.0, - "memory_ratio": round(mem / total, 6) if total > 0 else 0.0, - "branch_ratio": round(branch / total, 6) if total > 0 else 0.0, - "alu_to_memory": round(alu / mem, 6) if mem > 0 else (float("inf") if alu > 0 else 0.0), - } - - -def parse_registers(line: str) -> dict: - """Extract all VGPRs, SGPRs, and special registers referenced in a single disassembly line.""" - code, _, _ = line.partition(";") - vgprs = set() - for lo_s, hi_s in VGPR_RANGE.findall(code): - lo, hi = int(lo_s), int(hi_s) - vgprs.update(range(lo, hi + 1)) - code_no_vr = VGPR_RANGE.sub("", code) - for v_s in VGPR_SINGLE.findall(code_no_vr): - vgprs.add(int(v_s)) - - sgprs = set() - for lo_s, hi_s in SGPR_RANGE.findall(code): - lo, hi = int(lo_s), int(hi_s) - sgprs.update(range(lo, hi + 1)) - code_no_sr = SGPR_RANGE.sub("", code) - for s_s in SGPR_SINGLE.findall(code_no_sr): - sgprs.add(int(s_s)) - - specials = set(SPECIAL_REG.findall(code)) - return {"vgprs": vgprs, "sgprs": sgprs, "special": specials} - - -def instruction_lines(lines): - for line in lines: - if line.startswith("; ---"): - break - if line.startswith("\t"): - code = line.partition(";")[0].strip() - if code and not code.startswith("."): - yield code - - -def register_footprint(lines_or_text) -> dict: - """Calculate the register footprint (max index, allocation count, and unique sets) - across disassembly lines or text.""" - if isinstance(lines_or_text, str): - lines = lines_or_text.splitlines() - else: - lines = lines_or_text - - all_vgprs = set() - all_sgprs = set() - all_specials = set() - - for line in instruction_lines(lines): - regs = parse_registers(line) - all_vgprs.update(regs["vgprs"]) - all_sgprs.update(regs["sgprs"]) - all_specials.update(regs["special"]) - - max_vgpr = max(all_vgprs) if all_vgprs else -1 - max_sgpr = max(all_sgprs) if all_sgprs else -1 - - return { - "max_vgpr": max_vgpr, - "max_sgpr": max_sgpr, - "vgpr_count": max_vgpr + 1 if max_vgpr >= 0 else 0, - "sgpr_count": max_sgpr + 1 if max_sgpr >= 0 else 0, - "unique_vgprs": len(all_vgprs), - "unique_sgprs": len(all_sgprs), - "vgprs": sorted(all_vgprs), - "sgprs": sorted(all_sgprs), - "special": sorted(all_specials), - } - - -def profile_shader(text: str) -> dict: - """Profile a single shader's disassembly: mnemonics, categories, ratios, and register footprint.""" - lines = text.splitlines() - mnemonics = Counter(line.split(maxsplit=1)[0] for line in instruction_lines(lines)) - - cats = count_categories(mnemonics) - ratios = compute_ratios(cats) - reg_fp = register_footprint(lines) - - return { - "total_instructions": cats["total"], - "mnemonics": dict(mnemonics), - "categories": cats, - "ratios": ratios, - "registers": reg_fp, - } - - -LLVM_MESSAGES = "; --- llvm-mc messages ---" # the header shader_disasm.py writes above llvm-mc's stderr -INVALID_WORD_HEADER = re.compile(r"^;\s*\S+\s+code 0x[0-9a-f]+\.\.0x[0-9a-f]+ .+, ([0-9]{1,20}) invalid words$") -WARNING_LOCATION = re.compile(r"; :[1-9][0-9]*:([1-9][0-9]*)") -BYTE_ECHO = re.compile(r"; [ \t]*0x[0-9a-fA-F]{2}(?=[ \t]|$)") -WORD = re.compile(r"[ \t]+".join([r"0x([0-9a-fA-F]{2})"] * 4) + r"(?!\S)") # four complete 0xNN tokens - - -def warning_words(text: str): - """Invalid words from a listing, as (words identified from LLVM diagnostics, unresolved count). - - Each 'invalid instruction encoding' warning gives one word: the four complete 0xNN tokens starting exactly - at its one-based column of the source line LLVM echoes right after it, as e.g. 'ff ff ff d7'. A warning whose - position, echo or tokens don't give such a word counts as unresolved instead. The listing header also gives - an invalid-word count when the Python decoder produces no LLVM diagnostics.""" - header = text.partition("\n")[0].rstrip("\r") - count = INVALID_WORD_HEADER.fullmatch(header) - declared = int(count[1]) if count else 0 - if LLVM_MESSAGES not in text: - return [], declared - lines = text.splitlines() - try: - start = lines.index(LLVM_MESSAGES) + 1 - except ValueError: - return [], declared - words, unresolved = [], 0 - for index in range(start, len(lines)): - head = lines[index] - if not head.startswith("; :"): - continue - location, _, message = head.partition(": ") - if message != "warning: invalid instruction encoding": - continue - echo = lines[index + 1] if index + 1 < len(lines) else "" - position = WARNING_LOCATION.fullmatch(location) - word = None - # A column longer than the echo length in decimal cannot be in range. Check before int() to - # keep even arbitrarily long malformed locations from aborting the scan. - if position and len(position[1]) <= len(str(len(echo))) and BYTE_ECHO.match(echo): - col = int(position[1]) - # The producer added "; ". At a token start, echo[col] is the preceding whitespace and - # echo[col + 1] is the first byte's '0' (including the column-one case). - if col < len(echo) - 1 and echo[col] in " \t": - word = WORD.match(echo, col + 1) - if word: - words.append(" ".join(word.groups()).lower()) - else: - unresolved += 1 - return words, max(unresolved, declared - len(words)) - - -def register_summary(reg_stage) -> dict: - """Per-stage VGPR/SGPR pressure from (vgpr_count, sgpr_count) pairs: max, mean and a VGPR histogram. - - The histogram buckets are upper bounds on the VGPR count (wave32 RDNA2 allocates in blocks of 8 and caps a - wave at 256), so the counts show how many shaders fit each occupancy step.""" - out = {} - for stage in sorted(reg_stage): - pairs = reg_stage[stage] - if not pairs: - continue - v = [p[0] for p in pairs] - s = [p[1] for p in pairs] - hist = Counter() - for c in v: - hist[next(b for b in (32, 64, 128, 256) if c <= b) if c <= 256 else ">256"] += 1 - out[stage] = {"shaders": len(pairs), - "vgpr_max": max(v), "vgpr_mean": round(sum(v) / len(v), 2), - "sgpr_max": max(s), "sgpr_mean": round(sum(s) / len(s), 2), - "vgpr_hist": {str(k): hist[k] for k in (32, 64, 128, 256, ">256") if hist[k]}} - return out - - -def carve_index_path(disasm_dir): - return os.path.join(os.path.dirname(os.path.realpath(disasm_dir)), "index.json") - - -def stage_map(disasm_dir) -> dict: - """{shader file stem: stage} from shader_carve.py's index.json next to the disasm folder (the stage comes from - each container's program header), as rdna2spirv.stage_of reads it. Most corpus names carry no stage prefix, - so the name is only a fallback for shaders the index doesn't list. Empty when there is no readable index.""" - path = carve_index_path(disasm_dir) - try: - with open(path, encoding="utf-8-sig") as f: - entries = json.load(f) - return {os.path.splitext(e["file"])[0]: e["stage"] for e in entries - if isinstance(e, dict) and isinstance(e.get("file"), str) and isinstance(e.get("stage"), str)} - except (OSError, ValueError, TypeError): - return {} - - -def same_output_path(first, second): - """True when writing ``second`` would truncate ``first`` (same file, path or hard link).""" - if os.path.normcase(os.path.realpath(first)) == os.path.normcase(os.path.realpath(second)): - return True - try: - return os.path.samefile(first, second) - except OSError: - return False - - -def main(): - ap = argparse.ArgumentParser() - ap.add_argument("src") - ap.add_argument("--out") - ap.add_argument("--per-shader", action="store_true", - help="also list each shader's instruction count and VGPR/SGPR footprint") - a = ap.parse_args() - if not os.path.isdir(a.src): - what = "is not a folder" if os.path.exists(a.src) else "does not exist" - print(f"ERROR: {a.src} {what}. Give the folder of .s files shader_disasm.py writes.", file=sys.stderr) - return 2 - path = a.out or os.path.join(a.src, "..", "profile.json") - index = carve_index_path(a.src) - if same_output_path(index, path): - print(f"ERROR: output would overwrite the shader carve index {index}", file=sys.stderr) - return 2 - if os.path.isdir(path): - print(f"ERROR: cannot write {path}: destination is a directory, not a file", file=sys.stderr) - return 2 - out_dir = os.path.dirname(os.path.abspath(path)) - if not os.path.isdir(out_dir): # checked before the scan, which takes minutes on the whole corpus - print(f"ERROR: the folder for {path} does not exist", file=sys.stderr) - return 2 - try: - with os.scandir(a.src) as entries: - shader_files = [entry for entry in entries if entry.name.endswith(".s") and entry.is_file()] - except OSError as e: - print(f"ERROR: cannot list {a.src}: {e.strerror or e}", file=sys.stderr) - return 2 - for entry in shader_files: - if same_output_path(entry.path, path): - print(f"ERROR: output would overwrite input shader {entry.path}", file=sys.stderr) - return 2 - occ, users = Counter(), Counter() - word_occ, word_users = Counter(), Counter() # warned-at word -> warnings, shaders - unresolved = 0 - categories_by_stage = defaultdict(Counter) - reg_stage = defaultdict(list) # stage -> [(vgpr_count, sgpr_count)] - shaders = [] - stages = stage_map(a.src) - n = 0 - for entry in shader_files: - name = entry.name - n += 1 - stage = stages.get(name[:-2]) - if not stage: - prefix = STAGE_PREFIX.match(name) - stage = prefix[1].lower() if prefix else "?" - try: - with open(entry.path, encoding="utf-8", errors="replace") as f: - text = f.read() - except OSError as e: - print(f"ERROR: cannot read {entry.path}: {e.strerror or e}", file=sys.stderr) - return 2 - prof = profile_shader(text) - regs = prof["registers"] - reg_stage[stage].append((regs["vgpr_count"], regs["sgpr_count"])) - if a.per_shader: - shaders.append({"name": name[:-2], "stage": stage, "instructions": prof["total_instructions"], - "vgpr_count": regs["vgpr_count"], "sgpr_count": regs["sgpr_count"]}) - occ.update(prof["mnemonics"]) - users.update(prof["mnemonics"].keys()) - categories_by_stage[stage].update(prof["categories"]) - words, bad = warning_words(text) - word_occ.update(words) - word_users.update(set(words)) - unresolved += bad - fam = defaultdict(lambda: [0, 0]) - for m, c in occ.items(): - fam[family(m)][0] += 1 - fam[family(m)][1] += c - cats = count_categories(occ) - ratios = compute_ratios(cats) - if ratios["alu_to_memory"] == float("inf"): - ratios["alu_to_memory"] = None - ranked_users = sorted(users.items(), key=lambda item: (-item[1], item[0])) - out = {"shaders": n, "mnemonics": len(occ), - "families": {k: {"mnemonics": v[0], "occurrences": v[1]} for k, v in sorted(fam.items())}, - "categories": cats, - "categories_by_stage": dict(sorted(categories_by_stage.items())), - "ratios": ratios, - "by_mnemonic": [{"m": m, "shaders": shader_count, "count": occ[m]} - for m, shader_count in ranked_users], - "registers": register_summary(reg_stage), - "undecoded": {"warnings": sum(word_occ.values()) + unresolved, "unresolved": unresolved, - "by_word": [{"word": w, "shaders": word_users[w], "count": word_occ[w]} - for w in sorted(word_occ, key=lambda w: (-word_occ[w], -word_users[w], w))]}} - if a.per_shader: - out["per_shader"] = sorted(shaders, key=lambda e: e["name"]) - try: - with open(path, "w", encoding="utf-8", newline="\n") as f: - json.dump(out, f, indent=1, allow_nan=False) - except OSError as e: - print(f"ERROR: cannot write {path}: {e.strerror or e}", file=sys.stderr) - return 2 - print(f"{n} shaders, {len(occ)} distinct mnemonics -> {os.path.abspath(path)}") - for k, v in sorted(fam.items(), key=lambda item: (-item[1][1], item[0])): - print(f" {k:8} {v[0]:4} mnemonics {v[1]:>12,} uses") - print(f" ALU: {cats['alu']} ({ratios['alu_ratio'] * 100:.1f}%) Memory: {cats['memory']} ({ratios['memory_ratio'] * 100:.1f}%) Branch: {cats['branch']} ({ratios['branch_ratio'] * 100:.1f}%)") - cum, total = 0, sum(occ.values()) - for i, (m, c) in enumerate(occ.most_common(), 1): - cum += c - if total > 0 and cum / total >= 0.99: - print(f" {i} mnemonics cover 99% of all instructions") - break - for st, r in out["registers"].items(): - print(f" {st:2} registers: VGPR max {r['vgpr_max']} mean {r['vgpr_mean']}, " - f"SGPR max {r['sgpr_max']} mean {r['sgpr_mean']} ({r['shaders']} shaders)") - print(" most widespread:", ", ".join(f"{m} ({count})" for m, count in ranked_users[:12])) - print(f" undecoded: {out['undecoded']['warnings']} LLVM warnings, {len(word_occ)} distinct words, " - f"{unresolved} unresolved (words only in the JSON report)") - - -if __name__ == "__main__": - try: # a redirected stdout is strict ANSI code page under -I; write '?' for what it cannot encode - sys.stdout.reconfigure(errors="replace") - except (AttributeError, ValueError, OSError): - pass - sys.exit(main()) diff --git a/tools/shader_stage_manifest.py b/tools/shader_stage_manifest.py deleted file mode 100644 index eb5ffc913..000000000 --- a/tools/shader_stage_manifest.py +++ /dev/null @@ -1,43 +0,0 @@ -"""Read shader names from a completed carve or unpack index. - -An index.json saved with a UTF-8 BOM (Windows PowerShell 5.1, old Notepad) is read, not refused. -""" - -import json -import ntpath -import posixpath - - -def shader_stems(path: str, field: str, suffix: str = "") -> set[str]: - try: - # utf-8-sig: PowerShell 5.1 and old Notepad write JSON with a UTF-8 BOM. - with open(path, encoding="utf-8-sig") as f: - rows = json.load(f) - except UnicodeDecodeError as exc: - raise ValueError(f"{path}: invalid UTF-8: {exc}") from exc - except (ValueError, RecursionError) as exc: - raise ValueError(f"{path}: invalid JSON: {exc}") from exc - if not isinstance(rows, list): - raise ValueError(f"{path}: expected an array of shader entries") - stems = set() - for row in rows: - value = row.get(field) if isinstance(row, dict) else None - if ( - not isinstance(value, str) - or not value - or any(ord(c) < 32 or ord(c) == 127 for c in value) - or ":" in value - or "/" in value - or "\\" in value - or ntpath.splitdrive(value)[0] - or ntpath.basename(value) != value - or posixpath.basename(value) != value - ): - raise ValueError(f"{path}: expected a shader basename in {field!r}") - if suffix and (not value.endswith(suffix) or len(value) == len(suffix)): - raise ValueError(f"{path}: expected a {suffix} filename in {field!r}") - stem = value.removesuffix(suffix) - if not stem or stem in (".", ".."): - raise ValueError(f"{path}: expected a shader basename in {field!r}") - stems.add(stem) - return stems diff --git a/tools/skin_streams.py b/tools/skin_streams.py deleted file mode 100644 index 13b1dcc24..000000000 --- a/tools/skin_streams.py +++ /dev/null @@ -1,516 +0,0 @@ -"""Measure the vertex skin streams (joint indices and weights) of recovered drawable models (ASSET-12). - -Rigged models cannot be exported with their skeleton until the joint-index and skin-weight layout is -known. This tool walks every drawable resource that carves out of an RPF9 archive without its (encrypted) -table of contents — drawable dictionaries, fragments and standalone drawables — reads each geometry's FVF -semantic table, classifies the skin streams and validates the decoded bytes against the model's own bone -count. docs/character_skeleton.md carries the measured tables; no package data is stored or emitted. - -Resource shape (measured; the same walk rpf9-explorer's RageModelDecoder uses, pinned in third_party/): - - system page 0x50000000-based pointers; a resource starts at a 4096-aligned offset + 16 that is - preceded by 16 zero bytes and a zlib header (rpf9-explorer's candidate scan) - page directory +0x08 -> {+0x08 systemPages, +0x09 graphicsPages}; one zlib stream per page, system - pages first, then graphics pages (0x60000000-based pointers) - drawable LOD pointer fields +80..+104 -> {+0x08 model count u16} -> model pointer array - model (grmModel) +0x08 geometry pointer array, +0x10 geometry count u16, +0x14 local bone count u16 - geometry +0x08 -> vertex buffer header (vb); vb+0x40 -> FVF table; vb+0x18 -> graphics buffer - FVF table per semantic i: stream offset u32 at +4*i, element size u8 at +0xD0+i, format u8 at - +0x104+i; u32 flags at +0x138, vertex count = flags >> 10, bit 0 set - -The vertex buffer starts with one native buffer descriptor word per used semantic (stream offset in bits -7..28, a size code in bits 3..6); the tool cross-checks every skin slot's stream offset against its -descriptor word (the size code equals the element bytes only for the 4- and 8-byte slots). - -Skin semantics verified from the bytes (not from format names): - - semantic 16/17 weights: four u8 UNORM per slot; a vertex's bytes over all present weight slots sum - to 255 (a small tail rounds: 247-254, and below 247 in one packed 4-influence - population) - semantic 20/21 bone indices into the model's own bone list. In the packed layout each u32 holds a - 12-bit index in bits 0..11 (bits 9..11 are never set; bits 12..31 are a separate - unidentified field). A zero-weight component may carry any index, so indices are - range-checked only where the weight is non-zero. - -Usage: - python -I tools/skin_streams.py [...] [--sample N] [--json out.json] -""" -import argparse -import json -import mmap -import os -import re -import struct -import sys -import time -import zlib - -PAGE = 4096 -MAX_SYS = 32 * 1024 * 1024 -MAX_GFX = 224 * 1024 * 1024 -MAX_PAGE_COUNT = 32 -WEIGHT_SLOTS = (16, 17) -INDEX_SLOTS = (20, 21) -ZHDR = re.compile(rb"\x78[\x01\x5e\x9c\xda]") - -# FVF format byte -> (name, element bytes). Anchored on entries whose decoding is verified against -# package bytes: positions (12/6 float3, 8/16 quantized), UVs (4/38 snorm16 pairs), weights (4/28, rows -# sum to 255), bone indices (4/30, values below the bone count), rigid 16-bit indices (2/57, the format -# breadbbbb/rpf9-explorer#10 reads). Unverified format bytes fall back to the element size alone. -FORMATS = { - 2: ("R32G32B32A32_FLOAT", 16), - 3: ("R32G32B32A32_UINT", 16), - 6: ("R32G32B32_FLOAT", 12), - 12: ("R16G16B16A16_UINT", 8), - 16: ("R32G32_FLOAT", 8), - 28: ("R8G8B8A8_UNORM", 4), - 30: ("R8G8B8A8_UINT", 4), - 38: ("R16G16_SNORM", 4), - 41: ("R32_FLOAT", 4), - 57: ("R16_UINT", 2), - 62: ("R8_UINT", 1), -} - - -def u16(b, o): - return struct.unpack_from("= 1e7: - return False - return mn[0] <= mx[0] and mn[1] <= mx[1] and mn[2] <= mx[2] -def resource_kind(b): - """Drawable / drawable dictionary / fragment signature on the system page prefix, or None.""" - if len(b) < 192 or u64(b, 0) != 0: - return None - if sys_ptr(u64(b, 8)) and sys_ptr(u64(b, 32)) and sys_ptr(u64(b, 48)) and 0 < u16(b, 56) <= 4096 \ - and u16(b, 56) == u16(b, 58) == u16(b, 40) == u16(b, 42): - # DrawableDictionaryCheckBytes also reads the first child when its pointer array is inside - # the prefix; beyond it the decoder accepts the header without that read. - values = u64(b, 48) - 0x50000000 - if values > len(b) - 8 or sys_ptr(u64(b, values)): - return "dictionary" - if all(sys_ptr(u64(b, at)) for at in (8, 24, 168)) \ - and all(p == 0 or sys_ptr(p) for p in (u64(b, 16), u64(b, 32), u64(b, 40))) \ - and 0 < u16(b, 48) <= 4096 and u16(b, 50) <= 4096 \ - and u16(b, 52) <= u16(b, 54) <= 4096: - return "fragment" - if (sys_ptr(u64(b, 8)) or u64(b, 8) == 0) and sys_ptr(u64(b, 16)) and sys_ptr(u64(b, 80)) \ - and (sys_ptr(u64(b, 168)) or u64(b, 168) == 0): - radius = struct.unpack_from(" (size, fmt, offset) - self.gfx_at = gfx_at # graphics-page offset of the vertex buffer - self.gfx_len = gfx_len # vertex buffer length in bytes - - -def walk_resource(sys, kind): - """Walk drawable -> LOD -> model -> geometry -> FVF; return meshes carrying skin slots.""" - meshes = [] - for drawable in drawable_offsets(sys, kind): - seen_lods = set() - for lod_field in range(80, 105, 8): - if u64(sys, drawable + lod_field) == 0: - continue - lod = s_off(sys, drawable + lod_field, 16) - if lod in seen_lods: - continue - seen_lods.add(lod) - models = u16(sys, lod + 8) - check(0 < models <= 256 and models == u16(sys, lod + 10)) - ptrs = s_off(sys, lod, models * 8) - for mi in range(models): - model = s_off(sys, ptrs + mi * 8, 56) - count = u16(sys, model + 16) - bones = u16(sys, model + 20) - check(0 < count <= 256 and count == u16(sys, model + 18) == u16(sys, model + 54) - and bones <= 4096) - geometries = s_off(sys, model + 8, count * 8) - for gi in range(count): - geo = s_off(sys, geometries + gi * 8, 160) - vb = s_off(sys, geo + 8, 80) - fvf = s_off(sys, vb + 64, 0x13C) - flags = u32(sys, fvf + 0x138) - vertices = flags >> 10 - check(flags & 1 and 0 < vertices <= 1_000_000) - psize, pfmt = sys[fvf + 0xD0], sys[fvf + 0x104] - check((psize, pfmt) in ((12, 6), (8, 16))) # position semantic 0 - slots = {} - for i in range(0x34): - size, fmt = sys[fvf + 0xD0 + i], sys[fvf + 0x104 + i] - offset = u32(sys, fvf + 4 * i) - if size: # a size-0 slot is a placeholder with no stream - if fmt in FORMATS: - check(FORMATS[fmt][1] == size) - slots[i] = (size, fmt, offset) - gfx_len = u32(sys, vb + 8) * u16(sys, vb + 12) - check(0 < gfx_len <= MAX_GFX and u16(sys, vb + 12) <= 32) - p_off = u32(sys, fvf) - check(p_off >= 96 and p_off <= gfx_len and psize * vertices <= gfx_len - p_off) - for size, _fmt, offset in slots.values(): - check(offset <= gfx_len and size * vertices <= gfx_len - offset) - gfx_at = u64(sys, vb + 24) - 0x60000000 - check(0 <= gfx_at <= MAX_GFX - gfx_len) - if any(i in slots for i in WEIGHT_SLOTS + INDEX_SLOTS): - meshes.append(Mesh(vertices, bones, slots, gfx_at, gfx_len)) - check(len(meshes) <= 4096) - return meshes - - -def slot_signature(mesh): - parts = [] - for i in WEIGHT_SLOTS + INDEX_SLOTS: - if i in mesh.slots: - size, fmt, _ = mesh.slots[i] - parts.append(f"{i}:{size}b/{FORMATS.get(fmt, (f'fmt{fmt}', 0))[0]}") - return ",".join(parts) or "none" - - -def classify(mesh): - """Layout name for a mesh's skin slots, or None when they don't form a known layout.""" - weights = [i for i in WEIGHT_SLOTS if i in mesh.slots] - indices = [i for i in INDEX_SLOTS if i in mesh.slots] - if not indices: - return None - isz, ifmt, _ = mesh.slots[indices[0]] - for i in indices[1:]: - if mesh.slots[i][:2] != (isz, ifmt): - return None - for i in weights: - if mesh.slots[i][:2] != (4, 28): - return None - if not weights: - if (isz, ifmt) == (1, 62): - return "rigid-8bit" - if (isz, ifmt) == (2, 57): - return "rigid-16bit" - return None - influences = 4 * len(weights) - if (isz, ifmt) == (4, 30): - return f"weighted-{influences}inf-8bit" - if (isz, ifmt) == (16, 3): - return f"weighted-{influences}inf-packed" - if (isz, ifmt) == (8, 12): - return f"weighted-{influences}inf-16bit" - return None - - -def descriptor_offsets(data, limit): - """Stream offsets the native buffer descriptor words at the vertex buffer head encode. - - One word per used semantic, so the scan runs to `limit` — the slot-0 stream offset, the first - byte past the head. A word packs the stream offset in bits 7..28 and a size code in bits 3..6; - the code equals the element bytes for the 4- and 8-byte slots, but reads 1 for the 16-byte - packed index slot and 0 for the 1-byte rigid slot, so only the offset is checked. - """ - found = set() - for w in range(0, min(limit, len(data)) - 3, 4): - word = u32(data, w) - if word: - found.add((word >> 7) & 0x1FFFFFC) - return found - - -def validate(mesh, gfx, layout): - """Check the decoded skin bytes against the model's own bone count; returns a tally dict.""" - if mesh.gfx_at < 0 or mesh.gfx_at + mesh.gfx_len > len(gfx): - return {"buffer-short": 1, "vertices": mesh.vertices} - data = gfx[mesh.gfx_at:mesh.gfx_at + mesh.gfx_len] - n = mesh.vertices - t = {"vertices": n, "meshes": 1, "weighted-components": 0, "components-out-of-range": 0, - "weight-sum-255": 0, "weight-sum-247-254": 0, "weight-sum-other": 0, - "descriptor-mismatch": 0, "packed-bits-9-11-set": 0, "packed-bit-8-set": 0} - desc = descriptor_offsets(data, mesh.slots[0][2] if 0 in mesh.slots else 96) - weight_rows, index_rows = [], [] - for i in WEIGHT_SLOTS: - if i in mesh.slots: - size, _fmt, offset = mesh.slots[i] - weight_rows.append(data[offset:offset + size * n]) - if offset not in desc: - t["descriptor-mismatch"] += 1 - for i in INDEX_SLOTS: - if i in mesh.slots: - size, _fmt, offset = mesh.slots[i] - index_rows.append(data[offset:offset + size * n]) - if offset not in desc: - t["descriptor-mismatch"] += 1 - if weight_rows: - low = high = None - for v in range(n): - total = sum(sum(row[4 * v:4 * v + 4]) for row in weight_rows) - low = total if low is None else min(low, total) - high = total if high is None else max(high, total) - if total == 255: - t["weight-sum-255"] += 1 - elif 247 <= total <= 254: - t["weight-sum-247-254"] += 1 - else: - t["weight-sum-other"] += 1 - t["weight-sum-min"] = low - t["weight-sum-max"] = high - if layout.endswith("packed"): - for row in index_rows: - for word in struct.unpack_from(f"<{4 * n}I", row, 0): - t["weighted-components"] += 1 - if (word >> 9) & 7: - t["packed-bits-9-11-set"] += 1 - if (word >> 8) & 1: - t["packed-bit-8-set"] += 1 - if (word & 0xFFF) >= mesh.bones: - t["components-out-of-range"] += 1 - # The index is only meaningful where the matching weight is non-zero; the packed census keeps - # the raw in-range share, and the weight-masked count is reported for the 4-influence form. - elif index_rows: - for k, row in enumerate(index_rows): - weights = weight_rows[k] if k < len(weight_rows) else (weight_rows[0] if weight_rows else None) - if len(row) == n: # rigid-8bit - t["weighted-components"] += n - if max(row) >= mesh.bones: - t["components-out-of-range"] += sum(1 for b in row if b >= mesh.bones) - elif len(row) == 2 * n: # rigid-16bit - for idx in struct.unpack_from(f"<{n}H", row, 0): - t["weighted-components"] += 1 - if idx >= mesh.bones: - t["components-out-of-range"] += 1 - else: # four 8-bit or 16-bit indices per vertex, masked by the matching weights - wide = len(row) == 8 * n - for v in range(n): - base = 4 * v - joints = struct.unpack_from("<4H", row, 2 * base) if wide else row[base:base + 4] - for c, joint in enumerate(joints): - if weights is None or weights[base + c]: - t["weighted-components"] += 1 - if joint >= mesh.bones: - t["components-out-of-range"] += 1 - return t - - -def inflate_at(m, at, size): - """Inflate the zlib stream at `at`; returns (data, consumed) or (None, 0).""" - d = zlib.decompressobj() - out, p = [], at - try: - while not d.eof and p < size: - chunk = m[p:min(p + (1 << 20), size)] - if not chunk: - break - out.append(d.decompress(chunk)) - p += len(chunk) - if d.unused_data or d.eof: - break - data = b"".join(out) + d.flush() - except zlib.error: - return None, 0 - if not d.eof: - return None, 0 - return data, p - at - len(d.unused_data) - -def next_stream(m, fp, size): - """The next zlib stream at or after `fp` (padding between streams is zero): (data, start, used).""" - mt = ZHDR.search(m, fp, size) - if not mt: - return None - at = mt.start() - data, used = inflate_at(m, at, size) - if data is None: - return None - return data, at, used - - -def scan_archive(path, sample, log): - """Scan one archive; returns census and validation tallies per skin layout.""" - stats = {"candidates": 0, "resources": 0, "skipped": 0, "meshes": 0, "vertices": 0, - "unclassified": 0, "layouts": {}, "signatures": {}, "validated": {}} - size = os.path.getsize(path) - if size == 0: - return stats # mmap refuses an empty file; an empty archive has no resources to count - t0 = time.time() - with open(path, "rb") as fh: - m = mmap.mmap(fh.fileno(), 0, access=mmap.ACCESS_READ) - pos = 0 - while pos < size: - page = (pos + PAGE - 1) & ~(PAGE - 1) - at = page + 16 - if at + 2 > size: - break - pos = page + PAGE - if m[at - 16:at] != b"\0" * 16 or not ZHDR.match(m, at): - continue - data, used = inflate_at(m, at, size) - if data is None: - continue - kind = resource_kind(data) if len(data) >= 192 else None - if kind is None: - continue - stats["candidates"] += 1 - try: - directory = s_off(data, 8, 16) - system_pages, graphics_pages = data[directory + 8], data[directory + 9] - check(0 < system_pages <= MAX_PAGE_COUNT and 0 < graphics_pages <= MAX_PAGE_COUNT) - following, fp = [], at + used - for _ in range(system_pages - 1 + graphics_pages): - nxt = next_stream(m, fp, size) - if nxt is None: - break - more, start, used2 = nxt - following.append(more) - fp = start + used2 - resource_sys = b"".join([data] + following[:system_pages - 1]) - resource_gfx = b"".join(following[system_pages - 1:]) - meshes = walk_resource(resource_sys, kind) - except (Skip, struct.error): - stats["skipped"] += 1 - continue - stats["resources"] += 1 - for mesh in meshes: - layout = classify(mesh) or "unclassified" - row = stats["layouts"].setdefault(layout, {"meshes": 0, "vertices": 0}) - row["meshes"] += 1 - row["vertices"] += mesh.vertices - stats["meshes"] += 1 - stats["vertices"] += mesh.vertices - sig = slot_signature(mesh) - stats["signatures"][sig] = stats["signatures"].get(sig, 0) + 1 - if layout == "unclassified": - stats["unclassified"] += 1 - continue - acc = stats["validated"].setdefault(layout, {"_meshes": 0}) - if acc["_meshes"] < sample and 0 <= mesh.gfx_at and mesh.gfx_at + mesh.gfx_len <= len(resource_gfx): - acc["_meshes"] += 1 - for key, value in validate(mesh, resource_gfx, layout).items(): - if key.endswith(("-min", "-max")): - acc[key] = min(acc.get(key, value), value) if key.endswith("-min") \ - else max(acc.get(key, value), value) - else: - acc[key] = acc.get(key, 0) + value - pos = max(pos, fp) # the candidate scan resumes after the pages this resource consumed - if stats["resources"] % 500 == 0: - log(f" {os.path.basename(path)} @{page:#x}: {stats['resources']} resources, " - f"{stats['meshes']} meshes, {time.time() - t0:.0f}s") - return stats - - -def same_output_path(first, second): - """True when writing ``second`` would truncate ``first`` (same file, path or hard link).""" - if os.path.normcase(os.path.realpath(first)) == os.path.normcase(os.path.realpath(second)): - return True - try: - return os.path.samefile(first, second) - except OSError: - return False - - -def main(argv=None): - ap = argparse.ArgumentParser(description=__doc__.splitlines()[0]) - ap.add_argument("inputs", nargs="+", help="RPF9 archives to scan") - ap.add_argument("--sample", type=int, default=64, - help="meshes validated per layout per archive (the census covers every mesh)") - ap.add_argument("--json", help="write the full tallies to this file") - a = ap.parse_args(argv) - if a.sample < 1: - print("error: --sample must be at least 1", file=sys.stderr) - return 2 - for path in a.inputs: - if not os.path.isfile(path): - print(f"error: {path} is not a file", file=sys.stderr) - return 2 - if a.json: - if os.path.isdir(a.json): - print(f"error: --json {a.json} is a directory", file=sys.stderr) - return 2 - for path in a.inputs: - if same_output_path(a.json, path): - print(f"error: --json would overwrite the input {path}", file=sys.stderr) - return 2 - report, t0 = {}, time.time() - for path in a.inputs: - try: - stats = scan_archive(path, a.sample, lambda text: print(text, flush=True)) - except OSError as error: - print(f"error: cannot read {path}: {error.strerror or error}", file=sys.stderr) - return 2 - report[path] = stats - print(f"{os.path.basename(path)}: {stats['resources']} resources, {stats['meshes']} skin meshes, " - f"{stats['vertices']} vertices ({time.time() - t0:.0f}s)") - for layout in sorted(stats["layouts"]): - row = stats["layouts"][layout] - print(f" {layout:26s} {row['meshes']:8d} meshes {row['vertices']:12d} vertices") - if a.json: - try: - parent = os.path.dirname(os.path.abspath(a.json)) - if parent: - os.makedirs(parent, exist_ok=True) - with open(a.json, "w", encoding="utf-8", newline="\n") as fh: - json.dump(report, fh, indent=1) - except OSError as exc: - print(f"error: cannot write {a.json}: {exc.strerror or exc}", file=sys.stderr) - return 2 - return 0 - - -if __name__ == "__main__": - try: # a redirected stdout is strict ANSI code page under -I; write '?' for what it cannot encode - sys.stdout.reconfigure(errors="replace") - except (AttributeError, ValueError, OSError): - pass - sys.exit(main()) diff --git a/tools/skinned_glb.py b/tools/skinned_glb.py deleted file mode 100644 index 46bf4cf90..000000000 --- a/tools/skinned_glb.py +++ /dev/null @@ -1,1085 +0,0 @@ -"""Export a skinned GLB from a decoded RAGE pack model and its 8-influence skin streams. - -Usage:: - - python -I tools/skinned_glb.py out.glb \\ - --skeleton ambient_femalebody/model.json \\ - --component head/model.json \\ - --component jacket/model.json - -Inputs are read-only decoded pack directories: ``model.json``, its ``model.glb`` -geometry, and the graphics buffer named by ``buffer_files``. Nothing is written -except the output GLB; no source bytes are copied into the repository. - -Source layout (measured on the 1.0.2.1 package) ------------------------------------------------- - -The vertex skin streams are 4-byte elements at the offsets below, relative to the -start of the graphics buffer (``buffers/01_0.bin`` for both measured components). -Each section word in the 23-word mesh-block header encodes -``offset = (word >> 8) * 2`` and ``format = word & 0xFF``; the same triples are -also present in ``drawable.buffers[vertex_buffer].mesh_blob.sections`` as -``[semantic, offset, format]``. - -===== ===== ============================== ======== ========== ===== -Mesh Slot Meaning Offset Format Bytes -===== ===== ============================== ======== ========== ===== -head 8 JOINTS_0, 4 x u8 215,720 0x25 35,932 -head 9 JOINTS_1, 4 x u8 251,652 0x25 35,932 -head 6 WEIGHTS_0, 4 x u8 UNORM 143,856 0x26 35,932 -head 7 WEIGHTS_1, 4 x u8 UNORM 179,788 0x26 35,932 -jacket 8 JOINTS_0 275,032 0x25 39,272 -jacket 9 JOINTS_1 314,304 0x25 39,272 -jacket 6 WEIGHTS_0 196,488 0x26 39,272 -jacket 7 WEIGHTS_1 235,760 0x26 39,272 -===== ===== ============================== ======== ========== ===== - -Slots 8/9 may also use the packed layout, format ``0x8C``: 16 bytes per vertex, -four little-endian u32 words whose low 12 bits are the joint index. The reader -converts each vertex to the same 4 x u8 row as ``0x25`` and rejects an index -above 255. Only ``0x8C`` is accepted: no ``0x8B`` joint layout has been measured, -so ``0x8B`` is rejected rather than guessed. - -The joint index is local to the drawable model's own palette: a sorted ``u32`` -joaat32 array at ``grmModel + 0x20`` with its length at ``grmModel + 0x0C``. The -ped skeleton bind pose is ``drawable.skeleton[].bind_matrix`` from a decoded -skeleton resource (bone -> model, column-major, RAGE Z-up). Palette hashes are -resolved against the drawable's own skeleton/string table and then the ped -skeleton; a hash that resolves nowhere is emitted as ``bone_0x........``. - -Output has one skin. Its joints are the full ped skeleton plus any drawable-local -helper joints named by the palette. Every vertex keeps all eight influences as -``JOINTS_0``/``JOINTS_1`` (UNSIGNED_SHORT VEC4) and -``WEIGHTS_0``/``WEIGHTS_1`` (FLOAT VEC4). Source weights are u8 values that sum -to 255; they are normalised to 1.0. Bind matrices and inverse bind matrices use -the same RAGE Z-up -> glTF Y-up conversion as positions, ``(x, y, z) -> (x, z, -y)``. - -Only skinned primitives are exported, with clay materials. Textures, UV atlas -data and materials of the source package are not copied. This is a static export -path: it does not assemble a body or any other unrequested component. - -numpy is optional: when present it accelerates the weight pass; without it the -standard-library path produces the same bytes and is covered by the tests. -""" -from __future__ import annotations - -import argparse -import json -import math -import os -import struct -import sys -import tempfile - -sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) -from file_mode import published_mode # noqa: E402 - -try: # optional: the stdlib path below is the fallback and is covered by the tests - import numpy as _np -except ImportError: # pragma: no cover - depends on the interpreter - _np = None - -# -I keeps the script directory off sys.path, so add it explicitly before importing the sibling module. -sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) -from report_paths import same_report_path # noqa: E402 - -GLB_MAGIC = b"glTF" -GLB_VERSION = 2 -CHUNK_JSON = 0x4E4F534A -CHUNK_BIN = 0x004E4942 -ARRAY_BUFFER = 34962 -ELEMENT_ARRAY_BUFFER = 34963 -MODE_TRIANGLES = 4 - -COMPONENT_BYTE = 5121 -COMPONENT_UNSIGNED_SHORT = 5123 -COMPONENT_UNSIGNED_INT = 5125 -COMPONENT_FLOAT = 5126 - -JOINT_SLOTS = (8, 9) -WEIGHT_SLOTS = (6, 7) -INDEX_FORMAT = 0x25 # R8G8B8A8_UINT, one 4-byte element per vertex -PACKED_INDEX_FORMAT = 0x8C # R32G32B32A32_UINT, 16-byte element, index in bits 0..11 -WEIGHT_FORMAT = 0x26 # R8G8B8A8_UNORM -COMPONENT_SIZES = {5120: 1, 5121: 1, 5122: 2, 5123: 2, 5125: 4, 5126: 4} -TYPE_COMPONENTS = {"SCALAR": 1, "VEC2": 2, "VEC3": 3, "VEC4": 4, "MAT4": 16} - -# RAGE Z-up -> glTF Y-up: (x, y, z) -> (x, z, -y). -_YUP = ((1.0, 0.0, 0.0), (0.0, 0.0, 1.0), (0.0, -1.0, 0.0)) - -# Attribute names copied from the decoded model.glb. Skin attributes are rebuilt -# from the source streams; custom private attributes are not needed for display. -GEOMETRY_ATTRIBUTES = ( - "POSITION", "NORMAL", "TANGENT", - "TEXCOORD_0", "TEXCOORD_1", "TEXCOORD_2", "TEXCOORD_3", - "TEXCOORD_4", "TEXCOORD_5", "TEXCOORD_6", "TEXCOORD_7", - "COLOR_0", -) - -_ORIENTATION = {"O", "I", "F", "B", "CF", "CB", "LF", "LB", "RF", "RB"} -_SIDES = {"L", "R", "C"} - - -class SkinError(ValueError): - """A decoded model or skin stream is missing, inconsistent or out of range.""" - - -# --------------------------------------------------------------------------- math -def joaat32(name: str) -> int: - """RAGE joaat32 over the lowercased Latin-1 bytes of a bone name.""" - value = 0 - for byte in name.lower().encode("latin-1", "replace"): - value = (value + byte) & 0xFFFFFFFF - value = (value + (value << 10)) & 0xFFFFFFFF - value ^= value >> 6 - value = (value + (value << 3)) & 0xFFFFFFFF - value ^= value >> 11 - return (value + (value << 15)) & 0xFFFFFFFF - - -def mat_mul(a, b): - """Column-major 4x4 product ``a * b``.""" - out = [0.0] * 16 - for column in range(4): - for row in range(4): - out[column * 4 + row] = sum(a[k * 4 + row] * b[column * 4 + k] for k in range(4)) - return out - - -def invert_affine(m): - """Inverse of a column-major affine 4x4 (bottom row 0, 0, 0, 1).""" - a = lambda row, column: m[column * 4 + row] - det = (a(0, 0) * (a(1, 1) * a(2, 2) - a(1, 2) * a(2, 1)) - - a(0, 1) * (a(1, 0) * a(2, 2) - a(1, 2) * a(2, 0)) - + a(0, 2) * (a(1, 0) * a(2, 1) - a(1, 1) * a(2, 0))) - if not math.isfinite(det) or abs(det) < 1e-12: - raise SkinError("singular or non-finite bind matrix") - k = 1.0 / det - cofactors = ( - (a(1, 1) * a(2, 2) - a(1, 2) * a(2, 1)) * k, - (a(0, 2) * a(2, 1) - a(0, 1) * a(2, 2)) * k, - (a(0, 1) * a(1, 2) - a(0, 2) * a(1, 1)) * k, - (a(1, 2) * a(2, 0) - a(1, 0) * a(2, 2)) * k, - (a(0, 0) * a(2, 2) - a(0, 2) * a(2, 0)) * k, - (a(0, 2) * a(1, 0) - a(0, 0) * a(1, 2)) * k, - (a(1, 0) * a(2, 1) - a(1, 1) * a(2, 0)) * k, - (a(0, 1) * a(2, 0) - a(0, 0) * a(2, 1)) * k, - (a(0, 0) * a(1, 1) - a(0, 1) * a(1, 0)) * k, - ) - tx, ty, tz = a(0, 3), a(1, 3), a(2, 3) - out = [0.0] * 16 - for row in range(3): - for column in range(3): - out[column * 4 + row] = cofactors[row * 3 + column] - out[12 + row] = -(cofactors[row * 3] * tx - + cofactors[row * 3 + 1] * ty - + cofactors[row * 3 + 2] * tz) - out[15] = 1.0 - return out - - -def bind_to_gltf(m): - """Convert a column-major RAGE Z-up matrix to glTF Y-up: ``C * M * C^T``.""" - a = lambda row, column: m[column * 4 + row] - out = [0.0] * 16 - for row in range(3): - for column in range(3): - out[column * 4 + row] = sum( - _YUP[row][i] * a(i, j) * _YUP[column][j] - for i in range(3) for j in range(3) - ) - out[12 + row] = sum(_YUP[row][i] * a(i, 3) for i in range(3)) - out[15] = 1.0 - return out - - -def _identity() -> list[float]: - return [1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0] - - -def _is_identity(m) -> bool: - return all(abs(v - (1.0 if i in (0, 5, 10, 15) else 0.0)) <= 1e-9 for i, v in enumerate(m)) - - -def _finite_matrix(m) -> bool: - return len(m) == 16 and all(isinstance(v, (int, float)) and math.isfinite(v) for v in m) - - -# ------------------------------------------------------------------------ files -def _load_json(path: str) -> dict: - # An interrupted export leaves an empty or cut-off model.json: report it like any other bad input (BUILD-1031). - try: - with open(path, encoding="utf-8-sig") as handle: - value = json.load(handle) - except (UnicodeDecodeError, json.JSONDecodeError) as exc: - raise SkinError(f"{path}: invalid JSON: {exc}") from exc - if not isinstance(value, dict): - raise SkinError(f"{path}: model.json root is not an object") - return value - - -def model_json_path(path: str) -> tuple[str, str]: - """Return ``(directory, model.json path)`` for a decoded pack directory or file.""" - if os.path.isdir(path): - return path, os.path.join(path, "model.json") - if os.path.isfile(path) and os.path.basename(path).lower().endswith(".json"): - return os.path.dirname(os.path.abspath(path)), path - raise SkinError(f"{path}: expected a decoded model directory or its model.json") - - -def _stream_bytes(blob: bytes, base: int, offset: int, size: int, slot: int) -> bytes: - """Slice a section at ``base + offset``, rejecting a short graphics buffer.""" - start = base + offset - end = start + size - if start < base or end > len(blob): - raise SkinError(f"skin stream slot {slot} is outside its graphics buffer") - return blob[start:end] - - -def _unpack_packed_joints(data: bytes, slot: int) -> bytes: - """Convert four packed u32 joint words per vertex to four u8 indices.""" - out = bytearray() - for at in range(0, len(data), 16): - for word in struct.unpack_from("<4I", data, at): - index = word & 0xFFF - if index > 0xFF: - raise SkinError(f"skin stream slot {slot} joint index {index} does not fit u8") - out.append(index) - return bytes(out) - - -def source_input_paths(source: str) -> list[str]: - """Files one --skeleton/--component source may read or reference: its model.json, - the model.glb beside it and the buffer files named in model.json. A source that cannot - be resolved or read yet contributes only the paths known so far; the normal input checks - report it.""" - try: - model_dir, json_path = model_json_path(source) - except SkinError: - return [] - paths = [json_path] - try: - model = _load_json(json_path) - except (OSError, ValueError, SkinError): - return paths - glb_name = model.get("glb", "model.glb") - if isinstance(glb_name, str) and glb_name: - paths.append(os.path.join(model_dir, glb_name)) - buffer_files = model.get("buffer_files", []) - if isinstance(buffer_files, list): - paths += [os.path.join(model_dir, name) for name in buffer_files - if isinstance(name, str) and name] - return paths - - -def read_skin_streams(model_dir: str, model: dict, mesh: dict) -> dict: - """Read one mesh's JOINTS_0/1 and WEIGHTS_0/1 streams. - - Joint slots accept the 4 x u8 layout (``0x25``) and the packed 4 x u32 layout - (``0x8C``); both become 4 x u8 per vertex. Returns the four raw byte rows plus the - vertex count, local palette length and measured section table. The caller still - maps local indices to GLB joints. - """ - drawable = model.get("drawable") - if not isinstance(drawable, dict): - raise SkinError("model.json has no drawable object") - meshes = model.get("meshes") - if not isinstance(meshes, list): - raise SkinError("model.json has no meshes list") - try: - geometry = drawable["geometries"][mesh["geometry"]] - vertex_buffer_index = geometry["vertex_buffer"] - vertex_buffer = drawable["buffers"][vertex_buffer_index] - model_record = drawable["models"][mesh["model"]] - except (KeyError, IndexError, TypeError) as exc: - raise SkinError(f"mesh links to a missing drawable record: {exc}") from exc - - palette = model_record.get("bone_palette") - if not isinstance(palette, list) or not palette: - raise SkinError("model has no bone palette") - if not all(isinstance(v, int) and 0 <= v <= 0xFFFFFFFF for v in palette): - raise SkinError("bone palette must be u32 hashes") - - buffer_name = model.get("buffer_files", []) - try: - buffer_file = buffer_name[vertex_buffer_index] - except (IndexError, TypeError) as exc: - raise SkinError("vertex buffer has no buffer_files entry") from exc - buffer_path = os.path.join(model_dir, buffer_file) - with open(buffer_path, "rb") as handle: - blob = handle.read() - - base = int(vertex_buffer.get("gfx_off", 0) or 0) - if base < 0 or base > len(blob): - raise SkinError("vertex buffer offset is outside its buffer") - - sections = {} - mesh_blob = vertex_buffer.get("mesh_blob") - raw_sections = mesh_blob.get("sections") if isinstance(mesh_blob, dict) else None - if raw_sections: - for row in raw_sections: - if not isinstance(row, (list, tuple)) or len(row) != 3: - raise SkinError("mesh_blob.sections entries must be [semantic, offset, format]") - semantic, offset, fmt = (int(v) for v in row) - sections[semantic] = (offset, fmt) - else: - for semantic in range(23): - word = struct.unpack_from("> 8) * 2, word & 0xFF) - - for slot in (6, 8): - if slot not in sections: - raise SkinError(f"missing skin stream slot {slot}") - if (9 in sections) != (7 in sections): - raise SkinError("JOINTS_1 and WEIGHTS_1 must be present together") - - vertex_count = mesh.get("vertex_count", model.get("vertex_count")) - if not isinstance(vertex_count, int) or vertex_count <= 0: - raise SkinError("mesh has no positive vertex_count") - - rows = {} - for slot in (6, 7, 8, 9): - if slot not in sections: - continue - offset, fmt = sections[slot] - if slot in WEIGHT_SLOTS: - if fmt != WEIGHT_FORMAT: - raise SkinError( - f"skin stream slot {slot} has format 0x{fmt:02x}; " - f"expected 0x{WEIGHT_FORMAT:02x}" - ) - rows[slot] = _stream_bytes(blob, base, offset, 4 * vertex_count, slot) - elif fmt == INDEX_FORMAT: - rows[slot] = _stream_bytes(blob, base, offset, 4 * vertex_count, slot) - elif fmt == PACKED_INDEX_FORMAT: - packed = _stream_bytes(blob, base, offset, 16 * vertex_count, slot) - rows[slot] = _unpack_packed_joints(packed, slot) - else: - raise SkinError( - f"skin stream slot {slot} has format 0x{fmt:02x}; " - f"expected 0x{INDEX_FORMAT:02x} or 0x{PACKED_INDEX_FORMAT:02x}" - ) - - return { - "j0": rows[8], - "j1": rows.get(9, bytes(4 * vertex_count)), - "w0": rows[6], - "w1": rows.get(7, bytes(4 * vertex_count)), - "count": vertex_count, - "local_bones": len(palette), - "sections": sections, - "palette": palette, - } - - -# ---------------------------------------------------------------------- skeleton -def _bone_name_map(skeleton) -> tuple[dict[str, dict], dict[int, dict]]: - if not isinstance(skeleton, list) or not skeleton: - raise SkinError("skeleton has no bones") - by_name, by_hash = {}, {} - for bone in skeleton: - name = bone.get("name") - if not isinstance(name, str) or not name: - raise SkinError("skeleton bone has no name") - if not _finite_matrix(bone.get("bind_matrix")): - raise SkinError(f"skeleton bone {name!r} has no finite bind matrix") - by_name.setdefault(name, bone) - by_hash.setdefault(joaat32(name), bone) - return by_name, by_hash - - -class JointSet: - """Ped joints followed by drawable-local helper joints, with bind-pose worlds.""" - - def __init__(self, ped_skeleton): - self.ped_by_name, _ = _bone_name_map(ped_skeleton) - self.ped_count = len(ped_skeleton) - self.names: list[str] = [] - self.binds: list[list[float]] = [] - self.parents: list[int | None] = [] - self._by_name: dict[str, int] = {} - - roots = [i for i, bone in enumerate(ped_skeleton) if bone.get("parent") is None] - if not roots: - raise SkinError("ped skeleton has no root bone") - self.root = roots[0] - for index, bone in enumerate(ped_skeleton): - bind = bind_to_gltf(bone["bind_matrix"]) - parent = bone.get("parent") - if not isinstance(parent, int) or not 0 <= parent < len(ped_skeleton): - parent = None if index == self.root else self.root - self.names.append(bone["name"]) - self.binds.append(bind) - self.parents.append(parent) - self._by_name.setdefault(bone["name"], index) - - @property - def count(self) -> int: - return len(self.names) - - def find(self, name: str) -> int | None: - return self._by_name.get(name) - - def add(self, name: str, bind: list[float], parent: int) -> int: - if not _finite_matrix(bind): - raise SkinError(f"joint {name!r} has a non-finite bind matrix") - if not 0 <= parent < self.count: - raise SkinError(f"joint {name!r} has an invalid parent") - existing = self._by_name.get(name) - if existing is not None: - return existing - index = len(self.names) - self.names.append(name) - self.binds.append(bind) - self.parents.append(parent) - self._by_name[name] = index - return index - - def local_matrix(self, index: int) -> list[float]: - parent = self.parents[index] - if parent is None: - return list(self.binds[index]) - return mat_mul(invert_affine(self.binds[parent]), self.binds[index]) - - def inverse_bind(self, index: int) -> list[float]: - return invert_affine(self.binds[index]) - - -def _normalise_tokens(name: str) -> tuple[list[str], str | None]: - """Name tokens and side, with the drawable prefix and orientation suffixes removed.""" - upper = name.upper() - for prefix in ("GM_U01_", "EGM_U01_", "SKEL_", "BM_", "MH_", "RB_", "HH_", "PH_", "EO_", "IK_", "OH_"): - if upper.startswith(prefix): - upper = upper[len(prefix):] - break - tokens = [part for part in upper.split("_") if part] - while tokens and tokens[-1] in _ORIENTATION: - tokens.pop() - side = next((part for part in tokens if part in _SIDES), None) - return tokens, side - - -def _ped_tokens(name: str) -> tuple[list[str], str | None]: - return _normalise_tokens(name) - - -def _alias_tokens(tokens: list[str], side: str | None) -> set[str]: - aliases = set() - for token in tokens: - base = token.rstrip("0123456789") - digits = token[len(base):] - if "UPPERARM" in base: - aliases.add("UPPERARM") - elif "FOREARM" in base: - aliases.add("FOREARM") - elif "ELBOW" in base: - aliases.add("FOREARM") - elif "DELT" in base or "ARMPIT" in base: - aliases.add("UPPERARM") - elif "THIGH" in base: - aliases.add("PELVIS" if side == "C" else "THIGH") - elif "TRAP" in base: - aliases.add("CLAVICLE" if side in ("L", "R") else "SPINE6") - elif base == "PELVIS": - aliases.add("PELVIS") - elif base == "CLAVICLE": - aliases.add("CLAVICLE") - elif base == "NECK" and digits.isdigit(): - aliases.add(token) # Neck0 .. Neck2 are distinct deform bones - elif base == "SPINE" and digits.isdigit(): - aliases.add(token) # Spine0 .. Spine6 are distinct deform bones - return aliases - - -def infer_ped_parent( - name: str, - ped_by_name: dict[str, dict], - ped_indices: dict[str, int] | None = None, -) -> int | None: - """Pick the ped bone a drawable-local helper covers, by name tokens. - - Garment helpers such as ``GM_*_L_UpperArm01_CF`` carry no hierarchy of their - own in the measured resources. The helper is attached to the deform bone with - the matching side and body-part token; anatomy aliases cover common helper - spellings (delt/armpit -> upper arm, elbow -> forearm, side trap -> clavicle, - centre trap -> spine6). The fallback is the first deform bone. - """ - tokens, side = _ped_tokens(name) - aliases = _alias_tokens(tokens, side) - best: tuple[int, int, int, int] | None = None - for ordinal, bone in enumerate(ped_by_name.values()): - ped_name = bone["name"] - if not ped_name.upper().startswith("SKEL_"): - continue - index = ped_indices[ped_name] if ped_indices is not None and ped_name in ped_indices else ordinal - ped_tokens, ped_side = _ped_tokens(ped_name) - if side in ("L", "R") and ped_side in ("L", "R") and side != ped_side: - continue - if side == "C" and ped_side in ("L", "R"): - continue - ped_set = set(ped_tokens) - score = 0 - for alias in aliases: - if alias in ped_set: - score += 10 - elif not alias[-1].isdigit() and any(token.startswith(alias) for token in ped_set): - score += 5 - if score: - candidate = (score, -len(ped_name), -index, index) - if best is None or candidate > best: - best = candidate - if best is not None: - return best[3] - for ordinal, bone in enumerate(ped_by_name.values()): - ped_name = bone["name"] - if ped_name.upper().startswith("SKEL_"): - return ped_indices[ped_name] if ped_indices is not None and ped_name in ped_indices else ordinal - return None - - -class PaletteResolver: - """joaat32 palette -> bone name, using the drawable tables before the ped table.""" - - def __init__(self, component: dict, ped_by_name: dict[str, dict]): - self.ped_by_name = ped_by_name - drawable = component.get("drawable") or {} - own = drawable.get("skeleton") or [] - self.own_skeleton = own - self.own_by_name = {} - self.by_hash: dict[int, tuple[str, str]] = {} - for bone in own: - name = bone.get("name") - if isinstance(name, str) and name: - self.own_by_name.setdefault(name, bone) - self.by_hash.setdefault(joaat32(name), (name, "own")) - for text in drawable.get("strings") or []: - if not isinstance(text, str) or not text: - continue - self._add_string(text, "string") - # The measured string table has one entry with a stray leading - # character (EGM_... for the GM_... palette hash). Index that alias - # only when the unstripped spelling did not already claim the hash. - if len(text) > 2 and text[0].isalpha() and text[1].isupper(): - self._add_string(text[1:], "alias", only_if_absent=True) - for name, bone in ped_by_name.items(): - self.by_hash.setdefault(joaat32(name), (name, "ped")) - - def _add_string(self, text: str, source: str, only_if_absent: bool = False) -> None: - key = joaat32(text) - if only_if_absent and key in self.by_hash: - return - self.by_hash.setdefault(key, (text, source)) - - def resolve(self, value: int) -> tuple[str, str]: - found = self.by_hash.get(value) - if found is None: - return f"bone_0x{value:08x}", "fallback" - return found - - -def own_parent_name(record, own_skeleton) -> str | None: - """The name of a drawable-local bone's own_skeleton parent, by name or by index.""" - if not isinstance(record, dict): - return None - parent_name = record.get("parent_name") - if parent_name is None: - parent = record.get("parent") - if isinstance(parent, int) and 0 <= parent < len(own_skeleton): - parent_name = own_skeleton[parent].get("name") - return parent_name if isinstance(parent_name, str) and parent_name else None - - -# --------------------------------------------------------------------- weights -def normalise_weights(j0: bytes, j1: bytes, w0: bytes, w1: bytes, count: int, - local_bones: int, local_to_joint: list[int], - joint_count: int | None = None) -> dict: - """Map local joint bytes to GLB joints and normalise every 8-weight row to 1.0.""" - if count <= 0 or local_bones <= 0: - raise SkinError("skin stream has no vertices or no local bones") - if len(local_to_joint) != local_bones: - raise SkinError("joint palette map has the wrong length") - if any(not isinstance(v, int) or v < 0 or - (joint_count is not None and v >= joint_count) for v in local_to_joint): - raise SkinError("joint palette map contains an invalid joint index") - expected = 4 * count - for row in (j0, j1, w0, w1): - if len(row) != expected: - raise SkinError("skin stream is shorter than the vertex count") - - oversized = {slot for slot, joint in enumerate(local_to_joint) if joint > 0xFFFF} - if oversized: - for indices, weights in ((j0, w0), (j1, w1)): - if any(weight and index in oversized for index, weight in zip(indices, weights)): - raise SkinError("a weighted joint index exceeds the glTF UNSIGNED_SHORT limit (65535)") - # NumPy converts the entire palette, including entries no weighted slot uses. - local_to_joint = [0 if slot in oversized else joint for slot, joint in enumerate(local_to_joint)] - - if _np is not None: - indices = _np.concatenate( - [_np.frombuffer(j0, dtype=_np.uint8).reshape(count, 4), - _np.frombuffer(j1, dtype=_np.uint8).reshape(count, 4)], axis=1, - ).astype(_np.int64) - weights = _np.concatenate( - [_np.frombuffer(w0, dtype=_np.uint8).reshape(count, 4), - _np.frombuffer(w1, dtype=_np.uint8).reshape(count, 4)], axis=1, - ).astype(_np.float64) - totals = weights.sum(axis=1) - if bool((totals <= 0).any()): - raise SkinError("a vertex has no skin weight") - if bool((weights > 0).any()): - weighted = indices[weights > 0] - if int(weighted.max()) >= local_bones: - raise SkinError("a weighted joint index is outside the local palette") - weights /= totals[:, None] - # A zero-weight component may carry any index; clear it before the palette lookup - # so an out-of-palette value cannot raise where the stdlib path returns zeros. - zero = weights == 0 - indices[zero] = 0 - mapping = _np.asarray(local_to_joint, dtype=_np.uint16) - indices[weights == 0] = 0 - indices = mapping[indices] - indices[zero] = 0 - if joint_count is not None and bool((indices >= joint_count).any()): - raise SkinError("remapped joint index is invalid") - return { - "j0": indices[:, :4].astype("= local_bones: - raise SkinError("a weighted joint index is outside the local palette") - remapped = [local_to_joint[index] if raw[slot] else 0 for slot, index in enumerate(local)] - floats = [weight / total for weight in raw] - j0_out.extend(struct.pack("<4H", *remapped[:4])) - j1_out.extend(struct.pack("<4H", *remapped[4:])) - w0_out.extend(struct.pack("<4f", *floats[:4])) - w1_out.extend(struct.pack("<4f", *floats[4:])) - return { - "j0": bytes(j0_out), "j1": bytes(j1_out), "w0": bytes(w0_out), "w1": bytes(w1_out), - "sum_min": sum_min / 255.0, "sum_max": sum_max / 255.0, - } - - -# ------------------------------------------------------------------------ glb io -def read_glb(path: str) -> tuple[dict, bytes]: - """Parse a GLB container into its JSON object and BIN chunk.""" - with open(path, "rb") as handle: - data = handle.read() - if len(data) < 20 or data[:4] != GLB_MAGIC: - raise SkinError(f"{path}: not a binary glTF file") - json_length = struct.unpack_from(" tuple[bytes, dict]: - """Return tightly packed accessor bytes and a copy of its glTF metadata.""" - try: - accessor = gltf["accessors"][index] - view = gltf["bufferViews"][accessor["bufferView"]] - except (KeyError, IndexError, TypeError) as exc: - raise SkinError(f"invalid accessor {index}: {exc}") from exc - if accessor.get("sparse") is not None: - raise SkinError("sparse accessors are not supported") - component_type = accessor.get("componentType") - if component_type not in COMPONENT_SIZES: - raise SkinError(f"unsupported accessor component type {component_type!r}") - element = COMPONENT_SIZES[component_type] * TYPE_COMPONENTS.get(accessor.get("type"), 0) - count = accessor.get("count") - if element <= 0 or not isinstance(count, int) or count < 0: - raise SkinError(f"invalid accessor {index} shape") - stride = view.get("byteStride", element) - if not isinstance(stride, int) or stride < element: - raise SkinError(f"accessor {index} has an invalid byteStride") - start = view.get("byteOffset", 0) + accessor.get("byteOffset", 0) - end = start + ((count - 1) * stride + element if count else 0) - if start < 0 or end > len(bin_data): - raise SkinError(f"accessor {index} is outside the BIN chunk") - if stride == element: - packed = bin_data[start:start + element * count] - else: - packed = b"".join(bin_data[start + i * stride:start + i * stride + element] - for i in range(count)) - return packed, dict(accessor) - - -# -------------------------------------------------------------------- exporter -class _GlbBuilder: - def __init__(self) -> None: - self.bin = bytearray() - self.views: list[dict] = [] - self.accessors: list[dict] = [] - - def view(self, payload: bytes, target: int | None = None, *, stride: int | None = None) -> int: - self.bin.extend(b"\x00" * ((-len(self.bin)) % 4)) - offset = len(self.bin) - self.bin.extend(payload) - entry = {"buffer": 0, "byteOffset": offset, "byteLength": len(payload)} - if target is not None: - entry["target"] = target - if stride is not None: - entry["byteStride"] = stride - self.views.append(entry) - return len(self.views) - 1 - - def accessor(self, payload: bytes, component_type: int, kind: str, count: int, - target: int | None, *, normalized: bool = False, - minimum: list[float] | None = None, maximum: list[float] | None = None) -> int: - stride = None - if target == ARRAY_BUFFER: - element_size = COMPONENT_SIZES[component_type] * TYPE_COMPONENTS[kind] - padding = bytes((-element_size) % 4) - if padding: - # Accessors are read as tightly packed bytes, but glTF vertex rows must align to four bytes. - payload = b"".join(payload[i:i + element_size] + padding - for i in range(0, len(payload), element_size)) - stride = element_size + len(padding) - entry = { - "bufferView": self.view(payload, target, stride=stride), - "componentType": component_type, - "count": count, - "type": kind, - } - if normalized: - entry["normalized"] = True - if minimum is not None: - entry["min"] = minimum - if maximum is not None: - entry["max"] = maximum - self.accessors.append(entry) - return len(self.accessors) - 1 - - -def _component_geometry(gltf: dict, bin_data: bytes, primitive: dict) -> tuple[dict, int]: - attributes = primitive.get("attributes") - if not isinstance(attributes, dict): - raise SkinError("source primitive has no attributes") - out = {} - for name in GEOMETRY_ATTRIBUTES: - if name not in attributes: - continue - payload, accessor = accessor_bytes(gltf, bin_data, attributes[name]) - out[name] = (payload, accessor) - if "POSITION" not in out: - raise SkinError("source primitive has no POSITION accessor") - if "indices" not in primitive: - raise SkinError("source primitive has no index accessor") - index_payload, index_accessor = accessor_bytes(gltf, bin_data, primitive["indices"]) - return out, (index_payload, index_accessor) - - -def _source_meshes(model: dict) -> list[dict]: - meshes = model.get("meshes") - if not isinstance(meshes, list) or not meshes: - raise SkinError("model.json has no mesh records") - return meshes - - -def _component_primitives(gltf: dict, wanted: int) -> list[dict]: - primitives = [] - for mesh in gltf.get("meshes") or []: - primitives.extend(mesh.get("primitives") or []) - if len(primitives) != wanted: - raise SkinError( - f"model.glb has {len(primitives)} primitives for {wanted} mesh records" - ) - return primitives - - -def build_skinned_glb(skeleton_path: str, component_paths: list[str], *, - generator: str = "Leonida skinned_glb") -> tuple[bytes, dict]: - """Build one skinned GLB from a ped skeleton and one or more component models.""" - if not component_paths: - raise SkinError("at least one --component is required") - _skeleton_dir, skeleton_json = model_json_path(skeleton_path) - ped_model = _load_json(skeleton_json) - ped_skeleton = (ped_model.get("drawable") or {}).get("skeleton") - joints = JointSet(ped_skeleton) - - builder = _GlbBuilder() - primitives_out = [] - records = [] - weight_min, weight_max = math.inf, -math.inf - - for component_path in component_paths: - model_dir, json_path = model_json_path(component_path) - model = _load_json(json_path) - source_meshes = _source_meshes(model) - glb_name = model.get("glb", "model.glb") - if not isinstance(glb_name, str) or not glb_name: - raise SkinError(f"{model_dir}: model.json has no model.glb name") - gltf, glb_bin = read_glb(os.path.join(model_dir, glb_name)) - source_primitives = _component_primitives(gltf, len(source_meshes)) - pairs = [(mesh, primitive) for mesh, primitive in zip(source_meshes, source_primitives) - if mesh.get("skinned") and mesh.get("skin_influences")] - if not pairs: - raise SkinError(f"{model_dir}: model has no skinned mesh with skin_influences") - resolver = PaletteResolver(model, joints.ped_by_name) - - def attach(name: str, chain: tuple = ()) -> int: - """Add a drawable-local bone after the own_skeleton ancestors it names. - - A palette can list a child before its parent, and that parent can be an - unweighted own_skeleton bone no palette entry names; attaching the ancestors - first keeps the explicit link instead of falling back to infer_ped_parent. - """ - existing = joints.find(name) - if existing is not None: - return existing - record = resolver.own_by_name.get(name) - parent_name = own_parent_name(record, resolver.own_skeleton) - parent_index = joints.find(parent_name) if parent_name else None - if parent_index is None and parent_name and parent_name not in chain: - if parent_name in resolver.own_by_name: - parent_index = attach(parent_name, chain + (name,)) - if parent_index is None: - parent_index = infer_ped_parent(name, joints.ped_by_name, joints._by_name) - if parent_index is None: - parent_index = joints.root - bind = None - if isinstance(record, dict) and _finite_matrix(record.get("bind_matrix")): - bind = bind_to_gltf(record["bind_matrix"]) - if bind is None: - bind = list(joints.binds[parent_index]) - return joints.add(name, bind, parent_index) - - component_joint_start = joints.count - component_record_start = len(records) - for mesh, source_primitive in pairs: - streams = read_skin_streams(model_dir, model, mesh) - palette = streams["palette"] - if len(palette) != streams["local_bones"]: - raise SkinError("palette length changed while reading the skin stream") - local_to_joint = [] - for value in palette: - name, _source = resolver.resolve(value) - local_to_joint.append(attach(name)) - - attributes, index_pair = _component_geometry(gltf, glb_bin, source_primitive) - position = attributes["POSITION"][1] - if position.get("count") != streams["count"]: - raise SkinError( - f"{mesh.get('name', 'mesh')}: model.glb position count " - f"{position.get('count')} != skin stream count {streams['count']}" - ) - - normalised = normalise_weights( - streams["j0"], streams["j1"], streams["w0"], streams["w1"], - streams["count"], streams["local_bones"], local_to_joint, joints.count, - ) - weight_min = min(weight_min, normalised["sum_min"]) - weight_max = max(weight_max, normalised["sum_max"]) - - gltf_attributes = {} - for name, (payload, accessor) in attributes.items(): - minimum = accessor.get("min") if name == "POSITION" else None - maximum = accessor.get("max") if name == "POSITION" else None - gltf_attributes[name] = builder.accessor( - payload, accessor["componentType"], accessor["type"], accessor["count"], - ARRAY_BUFFER, normalized=bool(accessor.get("normalized")), - minimum=minimum, maximum=maximum, - ) - index_payload, index_accessor = index_pair - index_count = index_accessor["count"] - if index_count % 3: - raise SkinError("source index count is not a multiple of 3") - gltf_attributes["JOINTS_0"] = builder.accessor( - normalised["j0"], COMPONENT_UNSIGNED_SHORT, "VEC4", streams["count"], ARRAY_BUFFER) - gltf_attributes["JOINTS_1"] = builder.accessor( - normalised["j1"], COMPONENT_UNSIGNED_SHORT, "VEC4", streams["count"], ARRAY_BUFFER) - gltf_attributes["WEIGHTS_0"] = builder.accessor( - normalised["w0"], COMPONENT_FLOAT, "VEC4", streams["count"], ARRAY_BUFFER) - gltf_attributes["WEIGHTS_1"] = builder.accessor( - normalised["w1"], COMPONENT_FLOAT, "VEC4", streams["count"], ARRAY_BUFFER) - index_accessor_index = builder.accessor( - index_payload, index_accessor["componentType"], index_accessor["type"], - index_count, ELEMENT_ARRAY_BUFFER, - ) - primitives_out.append({ - "attributes": gltf_attributes, - "indices": index_accessor_index, - "material": 0, - "mode": MODE_TRIANGLES, - }) - records.append({ - "component": os.path.basename(os.path.dirname(json_path)) or "component", - "mesh": mesh.get("name", "mesh"), - "vertices": streams["count"], - "triangles": index_count // 3, - "source_weight_sum_min": round(normalised["sum_min"] * 255.0, 6), - "source_weight_sum_max": round(normalised["sum_max"] * 255.0, 6), - "local_bones": streams["local_bones"], - }) - component_joints = joints.count - component_joint_start - for record in records[component_record_start:]: - record["component_local_joints"] = component_joints - - if joints.count > 0x10000: - raise SkinError("a skin may address at most 65,536 joints with UNSIGNED_SHORT indices") - materials = [{ - "name": "skinned_clay", - "doubleSided": True, - "pbrMetallicRoughness": { - "baseColorFactor": [0.68, 0.62, 0.58, 1.0], - "metallicFactor": 0.0, - "roughnessFactor": 0.8, - }, - }] - - ibm_payload = b"".join(struct.pack("<16f", *joints.inverse_bind(i)) - for i in range(joints.count)) - ibm_accessor = builder.accessor(ibm_payload, COMPONENT_FLOAT, "MAT4", joints.count, None) - mesh_node = len(joints.names) - nodes = [] - for index, name in enumerate(joints.names): - node = {"name": name} - local = joints.local_matrix(index) - if not _is_identity(local): - node["matrix"] = [round(v, 9) for v in local] - nodes.append(node) - nodes.append({"name": "skinned_export", "mesh": 0, "skin": 0}) - for index, parent in enumerate(joints.parents): - if parent is not None: - nodes[parent].setdefault("children", []).append(index) - - scene_nodes = [joints.root, mesh_node] - gltf = { - "asset": {"version": "2.0", "generator": generator}, - "scene": 0, - "scenes": [{"name": "skinned_export", "nodes": scene_nodes}], - "nodes": nodes, - "meshes": [{"name": "skinned_export", "primitives": primitives_out}], - "materials": materials, - "accessors": builder.accessors, - "bufferViews": builder.views, - "buffers": [{"byteLength": 0}], - "skins": [{ - "name": "ped_skeleton", - "joints": list(range(joints.count)), - "skeleton": joints.root, - "inverseBindMatrices": ibm_accessor, - }], - } - builder.bin.extend(b"\x00" * ((-len(builder.bin)) % 4)) - gltf["buffers"][0]["byteLength"] = len(builder.bin) - - json_bytes = json.dumps(gltf, separators=(",", ":"), ensure_ascii=False, - allow_nan=False).encode("utf-8") - json_bytes += b" " * ((-len(json_bytes)) % 4) - total = 12 + 8 + len(json_bytes) + 8 + len(builder.bin) - payload = b"".join(( - struct.pack("<4sII", GLB_MAGIC, GLB_VERSION, total), - struct.pack(" dict: - """Build and atomically write a skinned GLB; returns its stats.""" - payload, stats = build_skinned_glb(skeleton_path, component_paths, generator=generator) - directory = os.path.dirname(os.path.abspath(path)) - if directory: - os.makedirs(directory, exist_ok=True) - # A fixed `path + ".tmp"` blocks every later export when a stale directory keeps that - # name, and two writers to one output race on the same temporary file. Use a unique name - # in the output directory so os.replace() still publishes atomically. - fd, temporary = tempfile.mkstemp( - prefix=os.path.basename(path) + ".", suffix=".tmp", dir=directory) - try: - with os.fdopen(fd, "wb") as handle: - handle.write(payload) - os.chmod(temporary, published_mode(path)) # mkstemp creates 0600 - os.replace(temporary, path) - except BaseException: - try: - # The temp was chmodded to the destination's mode before replace. On Windows a - # read-only destination leaves a read-only temp that cannot be unlinked; restore - # mkstemp's private writable mode first so a failed publish cleans up after itself. - os.chmod(temporary, 0o600) - os.unlink(temporary) - except OSError: - pass - raise - return stats - - -def main(argv=None) -> int: - parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) - parser.add_argument("output", help="output .glb path") - parser.add_argument("--skeleton", required=True, - help="decoded ped skeleton directory or its model.json") - parser.add_argument("--component", action="append", required=True, metavar="DIR", - help="decoded component directory or its model.json (repeatable)") - parser.add_argument("--generator", default="Leonida skinned_glb") - args = parser.parse_args(argv) - - # The output must never replace a file the export reads (a source's model.json, its model.glb or a - # buffer file). same_report_path also catches a case-only spelling on Windows and macOS's default - # volume; sources it cannot resolve yet are left to the normal input checks below. - for source in [args.skeleton] + args.component: - for source_path in source_input_paths(source): - if same_report_path(args.output, source_path): - print(f"error: {args.output} must not overwrite the source {source_path}", - file=sys.stderr) - return 2 - - try: - stats = write_skinned_glb(args.output, args.skeleton, args.component, - generator=args.generator) - except (SkinError, OSError) as exc: - print(f"error: {exc}", file=sys.stderr) - return 2 - print(f"wrote {args.output}: {stats['vertices']} vertices, {stats['triangles']} triangles, " - f"{stats['joints']} joints ({stats['ped_joints']} ped + " - f"{stats['component_joints']} component)") - for component in stats["components"]: - print(f" {component['mesh']}: {component['vertices']} vertices, " - f"{component['local_bones']} local bones, source weight sum " - f"{component['source_weight_sum_min']:g}..{component['source_weight_sum_max']:g}") - return 0 - - -if __name__ == "__main__": - try: # a redirected stdout is strict ANSI code page under -I - sys.stdout.reconfigure(errors="replace") - except (AttributeError, ValueError, OSError): - pass - sys.exit(main()) diff --git a/tools/smem_neg_probe.py b/tools/smem_neg_probe.py deleted file mode 100644 index 470c9b4e2..000000000 --- a/tools/smem_neg_probe.py +++ /dev/null @@ -1,166 +0,0 @@ -r"""SHADER-336: measure s_load / s_buffer_load with sOFF + IMM < 0 on an AMD GPU (tools/hw_oracle), and compare -with the translator's rule. - - python -I tools/smem_neg_probe.py # translator expectation only (no GPU) - python -I tools/smem_neg_probe.py --oracle hw # native AMD GPU, wave32 and wave64, plus the comparison - -One raw kernel per wave size. Thread 0 seeds 64 dwords at byte 0x100 of the output buffer with 0x5eed0000 + X (X = -byte offset from 0x140, the "base" every load starts from; X is negative below it), then runs each load once and -writes its destination SGPRs to out[0..]. Every load either reads inside the seeded 0x100..0x1ff bytes, or (for -`s_buffer_load`) is clipped by a NUM_RECORDS of 0x100 bytes around the base, so no row can read outside the buffer -whatever the hardware rule turns out to be. Rows the assembler rejects (a negative `s_buffer_load` IMM) are encoded -by hand as `.long` words. Standard library only; no game files. - -Exit codes: 0 every row matches the translator, 1 a mismatch, 2 harness error, 77 no hardware oracle. -Usage: `python -I tools/smem_neg_probe.py --help` lists the options. -""" -import argparse -import os -import sys - -HERE = os.path.dirname(os.path.abspath(__file__)) -sys.path.insert(0, os.path.join(HERE, "hw_oracle")) -sys.path.insert(0, HERE) - -SEED, BASE, WORDS = 0x5EED0000, 0x140, 16 -WORD3 = 0x31016FAC # V# word3 of the RX 6800 measurement (docs/design.md, Scalar/buffer memory) - - -def seed(x): - """The value seeded at byte BASE + x, or None (0) outside the seeded 0x100..0x1ff.""" - return (SEED + x) & 0xFFFFFFFF if -0x40 <= x < 0xC0 else None - - -def sbuf_raw(sdst, sbase, soff, imm): - """s_buffer_load_dword sdst, s[sbase:sbase+3], s offset:imm with a 21-bit signed IMM (GFX10 SMEM).""" - w0 = 0xF4200000 | (sdst << 6) | (sbase >> 1) - w1 = ((soff & 0x7F) << 25) | (imm & 0x1FFFFF) - return [f".long 0x{w0:08x}", f".long 0x{w1:08x}"] - - -# (name, lines, destination SGPRs, sOFF value or None, translator rule -> list of region offsets X or None) -# s_load: address = (base & ~3) + (sOFF & ~3) + sext21(IMM & ~3), 64-bit, no bound -# s_buffer_load: off = (sOFF & ~3) + (IMM & ~3) as a 32-bit value; dword i is 0 when off + 4i + 4 > NUM_RECORDS -NUM_RECORDS = 0x100 -ROWS = [ - ("sload_imm_m4", ["s_load_dword s40, s[4:5], -0x4"], [40], None, [-4]), - ("sload_imm_m40", ["s_load_dword s41, s[4:5], -0x40"], [41], None, [-0x40]), - ("sload_soff4_imm_m8", ["s_load_dword s42, s[4:5], s20 offset:-0x8"], [42], 4, [-4]), - ("sload_soff6_imm_m1", ["s_load_dword s43, s[4:5], s20 offset:-0x1"], [43], 6, [0]), - ("sload_soffc_imm_m20", ["s_load_dword s44, s[4:5], s20 offset:-0x20"], [44], 0xC, [-0x14]), - ("sload_x2_soff4_m10", ["s_load_dwordx2 s[46:47], s[4:5], s20 offset:-0x10"], [46, 47], 4, [-0xC, -8]), - ("sbuf_imm_m4", sbuf_raw(48, 12, 0x7D, -4), [48], None, None), # soff 0x7d = null - ("sbuf_soff8_imm_m4", sbuf_raw(49, 12, 20, -4), [49], 8, None), - ("sbuf_soffm4_imm8", ["s_buffer_load_dword s50, s[12:15], s20 offset:0x8"], [50], 0xFFFFFFFC, None), - ("sbuf_soffm4", ["s_buffer_load_dword s51, s[12:15], s20"], [51], 0xFFFFFFFC, None), -] - - -def translator_sbuf(soff, imm): - """The translator's s_buffer_load rule: a 32-bit offset (IMM kept as written, sOFF as is), bound-checked.""" - off = ((soff or 0) & ~3) + (imm & ~3) - off &= 0xFFFFFFFF - return [off] if off + 4 <= NUM_RECORDS else [None] - - -def expected(): - """Per row, the values the translator's rule gives (list of ints or None for 0).""" - out = {} - imms = {"sbuf_imm_m4": -4 & 0x1FFFFF, "sbuf_soff8_imm_m4": -4 & 0x1FFFFF, "sbuf_soffm4_imm8": 8, "sbuf_soffm4": 0} - for name, _lines, regs, soff, xs in ROWS: - if xs is None: - # the translator reads an s_buffer_load IMM as unsigned (llvm-mc's 20-bit field): -4 is 0x1ffffc - xs = translator_sbuf(soff, imms[name]) - out[name] = [seed(x) if x is not None else None for x in xs] - return out - - -def kernel_lines(): - lines = ["s_mov_b32 s8, s2", "s_mov_b32 s9, s3", f"s_mov_b32 s10, 0x10000", f"s_mov_b32 s11, 0x{WORD3:08x}"] - for i in range(0, 64, 4): # seed bytes 0x100..0x1ff - for k in range(4): - lines.append(f"v_mov_b32 v{1 + k}, 0x{(SEED + 0x100 + 4 * (i + k) - BASE) & 0xFFFFFFFF:08x}") - lines.append(f"buffer_store_dwordx4 v[1:4], off, s[8:11], 0 offset:{0x100 + 4 * i}") - lines += ["s_waitcnt vmcnt(0)", "s_waitcnt_vscnt null, 0x0", "s_dcache_inv", "s_waitcnt lgkmcnt(0)", - f"s_add_u32 s4, s2, 0x{BASE:x}", "s_addc_u32 s5, s3, 0", - f"s_add_u32 s12, s2, 0x{BASE:x}", "s_addc_u32 s13, s3, 0", - f"s_mov_b32 s14, 0x{NUM_RECORDS:x}", f"s_mov_b32 s15, 0x{WORD3:08x}"] - order = [] - for name, ls, regs, soff, _xs in ROWS: - if soff is not None: - lines.append(f"s_mov_b32 s20, 0x{soff & 0xFFFFFFFF:x}") - lines += ls - lines.append("s_waitcnt lgkmcnt(0)") - order += regs - for i, r in enumerate(order): - lines.append(f"v_mov_b32 v1, s{r}") - lines.append(f"buffer_store_dword v1, off, s[8:11], 0 offset:{4 * i}") - lines += ["s_waitcnt vmcnt(0)", "s_endpgm"] - return lines, order - - -def main(argv=None): - ap = argparse.ArgumentParser(description=__doc__.splitlines()[0]) - ap.add_argument("--oracle", choices=("translator", "hw"), default="translator") - a = ap.parse_args(argv) - want = expected() - if a.oracle == "translator": - for name, vals in want.items(): - print(f"{name:22} translator {' '.join('0' if v is None else hex(v) for v in vals)}") - return 0 - import asm - import runner - try: - oracle = runner.open_oracle() - except runner.Unavailable as e: - print(f"hardware oracle unavailable: {e}") - return 77 - try: - lines, order = kernel_lines() - n = len(order) - got = {} - for wave in (32, 64): - results = oracle.run([asm.Kernel(lines, wave=wave, threads=1, words=n, raw=True, vgprs=8, sgprs=64)]) - if not isinstance(results, (list, tuple)): - print(f"wave{wave}: expected list/tuple from oracle, got {type(results).__name__}") - return 2 - if len(results) != 1: - print(f"wave{wave}: expected 1 oracle result, got {len(results)}") - return 2 - res = results[0] - if isinstance(res, str): - print(f"wave{wave}: kernel rejected: {res}") - return 2 - if not isinstance(res, (list, tuple)): - print(f"wave{wave}: expected word list from oracle, got {type(res).__name__}") - return 2 - if len(res) != n: - print(f"wave{wave}: expected {n} words, got {len(res)}") - return 2 - bad_types = [type(w).__name__ for w in res if isinstance(w, bool) or not isinstance(w, int)] - if bad_types: - print(f"wave{wave}: expected {n} int words, got {bad_types[0]} element") - return 2 - got[wave] = list(res) - print(f"device: {oracle.device} ({oracle.arch})") - finally: - oracle.close() - bad, i = 0, 0 - for name, _ls, regs, _soff, _xs in ROWS: - w32 = got[32][i:i + len(regs)] - w64 = got[64][i:i + len(regs)] - i += len(regs) - exp = [0 if v is None else v for v in want[name]] - ok = w32 == exp and w64 == exp - bad += not ok - hw = " ".join(hex(v) for v in w32) + ("" if w32 == w64 else " (wave64 " + " ".join(hex(v) for v in w64) + ")") - print(f"{name:22} hw {hw:26} translator {' '.join(hex(v) for v in exp):24} {'ok' if ok else 'DIFFERS'}") - return 1 if bad else 0 - - -if __name__ == "__main__": - try: # a redirected stdout is strict ANSI code page under -I; write '?' for what it cannot encode - sys.stdout.reconfigure(errors="replace") - except (AttributeError, ValueError, OSError): - pass - sys.exit(main()) diff --git a/tools/smh_groom.py b/tools/smh_groom.py deleted file mode 100644 index c1b54101e..000000000 --- a/tools/smh_groom.py +++ /dev/null @@ -1,1968 +0,0 @@ -"""Clean-room decoder, strand generator, census tool and GLB exporter for RAGE "smh" strand grooms. - -Hair, beards, brows, lashes, body hair and animal fur in this build are stored as GPU strand groom -LOD resources rather than static triangle meshes. Each groom LOD resource is a native RAGE resource -containing a small system page (type ID ``0x7d8f3db3``) and one GPU asset buffer headed by a table -of byte offsets into per-guide, per-node and per-triangle arrays. - -Strands are not stored directly in the asset: the ``smh_gen_*_CS_InterpolateStrands`` compute shaders -scatter strand roots across the scalp triangle mesh (whose vertices are the guide roots) using a -deterministic integer RNG, then blend three guides per strand and trim to a per-strand length. -Class 0 (``smh_gen_1``) and class 1 (``smh_gen_2``/``_4``/``_8``/``_16``) are two placement sets of -one groom generated with the same points-per-strand (per-instance ``+0x54`` bits 16-23, 16 bytes/point) -and drawn together as ``(count0 + count1) * (points - 1)`` segments in one batch; neither class is -"more detailed". - -Pure Python standard library only (runs under ``python -I``, no third-party packages). - -Usage: - python -I tools/smh_groom.py inspect [--offset 0x...] [--json] - python -I tools/smh_groom.py census [ ...] [--json] [--limit N] - python -I tools/smh_groom.py export-glb [--offset 0x...] [--geometry tubes|ribbons|curves|line-strip] [--strands N] -""" -from __future__ import annotations - -import argparse -import array -import collections -import json -import math -import mmap -import os -import struct -import sys -import zlib -from collections.abc import Iterable, Iterator -from dataclasses import dataclass, field - -sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) -import glb_writer # noqa: E402 - -SYS_BASE = 0x50000000 -GPU_BASE = 0x60000000 -TYPE_ID = 0x7D8F3DB3 -PREFIX = b"\x00" * 16 + b"\x78" -HEADER_SIZE = 0xA0 -MAX_INFLATE_BYTES = 64 << 20 - -# System page +0xb8 metadata hashes and +0x48..+0x70 child-rig float sentinels. -SKEL_HEAD_HASH = 0x34C53E77 -UNUSED_HASH_FILL = 0x89EA2ED6 -FLT_MAX_U32 = 0x7F7FFFFF -NEG_FLT_MAX_U32 = 0xFF7FFFFF - -# Measured +0xcc (slot 5 of system page +0xb8) part class hashes across the corpus (30 distinct total). -PART_CLASS_NAMES: dict[int, str] = { - 0xD54A2D40: "main_hair", - 0x27B342A3: "short_hair", - 0xE61E1493: "long_hair", - 0x1CAEB442: "fuzz", - 0xE2500E92: "braids_ties", - 0x44D2709F: "beard", - 0x42C7E1D0: "beard", - 0x83A664E7: "lashes", - 0xA228CC57: "body_hair", - 0x304DD218: "animal_fur", - 0xC50E7D12: "animal_fur", -} - -MODE_LINES = 1 -MODE_LINE_STRIP = 3 -MODE_TRIANGLES = glb_writer.MODE_TRIANGLES - -# GPU asset buffer header: byte offset -> (name, bytes per element, domain). -# Domains: "G" = per guide, "N" = per node (guide-major), "T" = per triangle. -ARRAYS: dict[int, tuple[str, int, str]] = { - 0x00: ("attr_a", 4, "G"), - 0x04: ("attr_b", 4, "G"), - 0x08: ("uv", 4, "G"), - 0x0C: ("attr_c", 4, "G"), - 0x10: ("bone_index", 8, "G"), - 0x14: ("bone_weight", 8, "G"), - 0x18: ("ext_18", 12, "G"), - 0x1C: ("ext_1c", 8, "G"), - 0x24: ("ext_24", 4, "G"), - 0x28: ("direction", 4, "G"), - 0x30: ("length", 2, "G"), - 0x34: ("node_4", 4, "N"), - 0x38: ("node_2", 2, "N"), - 0x40: ("triangle", 6, "T"), - 0x44: ("position", 8, "N"), - 0x48: ("tri_count", 4, "T"), - 0x4C: ("tri_region", 1, "T"), -} -REQUIRED_ARRAYS = ("position", "triangle", "tri_count", "length", "bone_index", "bone_weight", "uv") -OPTIONAL_RAW_ARRAYS = ( - ("attr_a", 4), - ("attr_b", 4), - ("attr_c", 4), - ("ext_18", 12), - ("ext_1c", 8), - ("ext_24", 4), - ("direction", 4), - ("node_4", 4), - ("node_2", 2), -) -TAIL_OFFSET = 0x20 -SENTINEL_OFFSET = 0x2C -EXT_3C_OFFSET = 0x3C -STRAND_CLASS_SEED = (0x7C, 0x80) - -PART_NAMES = ("Scalp triangles", "Guides", "Strands (class 0)", "Strands (class 1)") -PART_COLORS = ( - (0.55, 0.55, 0.55, 1.0), - (0.85, 0.20, 0.20, 1.0), - (0.32, 0.22, 0.14, 1.0), - (0.76, 0.64, 0.42, 1.0), -) -GEOMETRY_MODES = ("tubes", "ribbons", "curves", "line-strip") - -_M32 = 0xFFFFFFFF -_M24 = 0xFFFFFF -_INV_2_24 = 2.0 ** -24 -_ATTEMPT_CONSTS = tuple( - ( - (attempt * 0x19660D + 0x86945BED) & _M32, - (((attempt * 0x19660D + 0x86945BED) & _M32) * 0x153E39CE) & _M32, - ) - for attempt in range(4) -) -_NEEDS_BYTESWAP = sys.byteorder != "little" -_UINT16_CODE = "H" if array.array("H").itemsize == 2 else None -_UINT32_CODE = "I" if array.array("I").itemsize == 4 else ("L" if array.array("L").itemsize == 4 else None) -_FLOAT32_CODE = "f" if array.array("f").itemsize == 4 else None - - -class GroomError(ValueError): - """Raised when a groom resource, buffer header or export request is invalid.""" - - -def _f32(value: float) -> float: - """Round a Python float to IEEE 754 binary32 precision.""" - return struct.unpack(" float: - return 0.0 if value == 0.0 else value - - -def inflate_stream(src: bytes | bytearray | memoryview | mmap.mmap, pos: int) -> tuple[bytes, int]: - """Inflate one zlib stream at ``pos`` -> ``(raw_bytes, next_16_aligned_offset)``.""" - decoder = zlib.decompressobj() - out = bytearray() - size = len(src) - while not decoder.eof: - if pos >= size: - raise GroomError("incomplete zlib resource stream") - chunk = src[pos:pos + 65536] - if not chunk: - raise GroomError("incomplete zlib resource stream") - try: - piece = decoder.decompress(chunk) - except zlib.error as exc: - raise GroomError(f"zlib decompression failed at {pos:#x}: {exc}") from exc - out.extend(piece) - if len(out) > MAX_INFLATE_BYTES: - raise GroomError(f"resource stream exceeds {MAX_INFLATE_BYTES} bytes") - pos += len(chunk) - len(decoder.unused_data) - return bytes(out), (pos + 15) & -16 - - -def _sys_ptr(sysd: bytes, at: int) -> int: - value = struct.unpack_from(" bool: - """Return True if ``sysd`` starts like an inflated smh groom LOD system page.""" - if len(sysd) < 0xE0 or bytes(sysd[:8]) != b"\x00" * 8: - return False - if struct.unpack_from("= 40 - ) - - -def scan_offsets( - src: bytes | bytearray | memoryview | mmap.mmap, - start: int = 0, - stop: int | None = None, - chunk: int = 64 << 20, -) -> Iterator[int]: - """Yield the byte offset of every groom LOD resource in ``src`` (16-aligned zero prefix + zlib page).""" - if isinstance(chunk, bool) or chunk <= 0: - raise GroomError(f"scan chunk size must be positive, got {chunk}") - if isinstance(src, memoryview): - if src.nbytes == 0: - return - if src.c_contiguous and 0 not in src.strides: - src = src.cast("B") - elif not (src.ndim == 1 and src.itemsize == 1): - src = src.tobytes() - size = len(src) - stop = size if stop is None else min(stop, size) - first = (max(start, 0) + 15) & -16 - overlap = len(PREFIX) - 1 - for base in range(first, stop, chunk): - window_end = min(base + chunk, stop) - limit = window_end - base - end = min(window_end + overlap, size) - block = src[base:end] - if isinstance(block, memoryview): - block = block.tobytes() - at = -1 - while True: - at = block.find(PREFIX, at + 1) - if at < 0 or at >= limit: - break - off = base + at - if off & 15: - continue - comp = src[off + 16:min(off + 16 + 4096, size)] - if isinstance(comp, memoryview) and not comp.c_contiguous: - comp = comp.tobytes() - try: - head = zlib.decompressobj().decompress(comp, 4096) - except zlib.error: - continue - if system_page_is_groom(head): - yield off - - -def _finite_f16(value: float) -> float | None: - return _clean_zero(value) if math.isfinite(value) else None - - -def _round_opt(value: float | None, digits: int = 6) -> float | None: - return None if value is None else round(value, digits) - - -def _round_style_params(params: dict | None) -> dict | None: - if params is None: - return None - out: dict = { - "strandWidth": _round_opt(params["strandWidth"]), - "longestGuideM": _round_opt(params["longestGuideM"]), - "longestGuideAltM": _round_opt(params["longestGuideAltM"]), - "braidParam": _round_opt(params["braidParam"]), - } - for key in ("curlFrizz0", "curlFrizz1"): - blk = params[key] - out[key] = { - "amounts": [_round_opt(v) for v in blk["amounts"]], - "radiiM": [_round_opt(v) for v in blk["radiiM"]], - "frequenciesPerM": [_round_opt(v) for v in blk["frequenciesPerM"]], - } - return out - - -def parse_system_page(system: bytes | bytearray | memoryview) -> dict: - """Decode structured metadata from an inflated ``smh`` groom LOD system page. - - Decodes bounding box (``+0x30``/``+0x40``), child-rig unset float sentinel detection in - ``+0x48..+0x70`` (secondary float4 bounds at ``+0x50..+0x6f`` set to ``+FLT_MAX`` - ``0x7f7fffff`` / ``-FLT_MAX`` ``0xff7fffff``), skinning bone hashes (``+0x98/+0xa0``), - region records (``+0xa8/+0xb0``), the six ``+0xb8`` metadata hashes (slots 0..3 bone - hashes, slot 4 ``+0xc8`` style preset hash, slot 5 ``+0xcc`` part class hash), strand - totals (``+0xd0``), and the ``+0xe8..+0x110`` IEEE 754 ``float16`` style parameters - (when ``len(system) >= 0x110``). - """ - sys_bytes = bytes(system) - if len(sys_bytes) < 0xE0: - raise GroomError(f"system page shorter than 0xe0 bytes ({len(sys_bytes)} bytes)") - - box_min = struct.unpack_from("<3f", sys_bytes, 0x30) - box_max = struct.unpack_from("<3f", sys_bytes, 0x40) - box = (box_min, box_max) - - # Child rigs leave the +0x50..+0x6f secondary bounds floats (within +0x48..+0x70) unset - # at +FLT_MAX (0x7f7fffff, little-endian ff ff 7f 7f) / -FLT_MAX (0xff7fffff). - rig_float_words = struct.unpack_from("<10I", sys_bytes, 0x48) - has_unset_rig_floats = any(w in (FLT_MAX_U32, NEG_FLT_MAX_U32) for w in rig_float_words) - - totals = struct.unpack_from(" len(sys_bytes): - break - n_tri, n_guide, n_s0, _pad, rid, n_s1 = struct.unpack_from("= 0x110: - h = [_finite_f16(v) for v in struct.unpack_from("<20e", sys_bytes, 0xE8)] - style_params = { - "strandWidth": h[0], # +0xe8 (typically 0.1, or 0.03 in some grooms) - "longestGuideM": h[1], # +0xea (longest guide in metres) - "longestGuideAltM": h[3], # +0xee (longest guide in metres) - "braidParam": h[4], # +0xf0 (correlates with braided styles, r = 0.75) - "curlFrizz0": { # +0xf8..+0x103 (6 half-floats: 2 amounts, 2 radii in m, 2 freqs/m) - "amounts": [h[8], h[9]], - "radiiM": [h[10], h[11]], - "frequenciesPerM": [h[12], h[13]], - }, - "curlFrizz1": { # +0x104..+0x10f (6 half-floats; +0x10a correlates with curly, r = 0.81) - "amounts": [h[14], h[15]], - "radiiM": [h[16], h[17]], - "frequenciesPerM": [h[18], h[19]], - }, - } - - return { - "box": box, - "strand_totals": totals, - "bone_hashes": bone_hashes, - "regions": regions, - "style_hashes": style_hashes, - "slot_bone_hashes": slot_bone_hashes, - "style_preset_hash": style_preset_hash, - "part_class_hash": part_class_hash, - "part_class": part_class, - "has_unset_rig_floats": has_unset_rig_floats, - "style_params": style_params, - } - - -@dataclass -class Groom: - """Decoded smh groom LOD resource.""" - - archive: str - offset: int - system: bytes = field(repr=False) - buffer: bytes = field(repr=False) - header: tuple[int, ...] = field(repr=False) - guides: int = 0 - triangles_n: int = 0 - nodes: int = 0 - nodes_per_guide: int = 0 - flags: int = 0 - box: tuple[tuple[float, float, float], tuple[float, float, float]] = ((0.0, 0.0, 0.0), (0.0, 0.0, 0.0)) - strand_totals: tuple[int, int] = (0, 0) - regions: list[dict] = field(default_factory=list) - bone_hashes: tuple[int, ...] = () - style_hashes: tuple[int, ...] = () - style_preset_hash: int | None = None - part_class_hash: int | None = None - part_class: str | None = None - has_unset_rig_floats: bool = False - style_params: dict | None = None - positions: list[list[tuple[float, float, float]]] = field(default_factory=list, repr=False) - node_w: list[list[float]] = field(default_factory=list, repr=False) - triangles: list[tuple[int, int, int]] = field(default_factory=list, repr=False) - tri_count: list[tuple[int, int, int, int]] = field(default_factory=list, repr=False) - tri_region: bytes = field(default=b"", repr=False) - lengths: list[float] = field(default_factory=list, repr=False) - uvs: list[tuple[float, float]] = field(default_factory=list, repr=False) - bone_indices: list[tuple[int, ...]] = field(default_factory=list, repr=False) - bone_weights_raw: list[tuple[int, ...]] = field(default_factory=list, repr=False) - length_random: tuple[float, float] = (0.0, 1.0) - present: dict[str, bool] = field(default_factory=dict, repr=False) - optional_raw: dict[str, bytes] = field(default_factory=dict, repr=False) - tail: bytes = field(default_factory=b"", repr=False) - sentinel_2c: int = 0xFFFFFFFF - ext_3c_offset: int = 0 - - def seed(self, strand_class: int = 0) -> int: - """Per-class RNG seed word from the GPU buffer header.""" - if strand_class not in (0, 1): - raise GroomError(f"unsupported strand class {strand_class} (expected 0 or 1)") - return self.header[STRAND_CLASS_SEED[strand_class] // 4] - - def bone_weights(self) -> list[tuple[float, ...]]: - """Sum-normalised 8-slot skin weights per guide.""" - out: list[tuple[float, ...]] = [] - for raw in self.bone_weights_raw: - total = sum(raw) - denom = float(total) if total > 0 else 1e-6 - out.append(tuple(w / denom for w in raw)) - return out - - def guide_curve_lengths(self) -> list[float]: - """Measured polyline arc length in metres for each guide.""" - out: list[float] = [] - for guide in self.positions: - acc = 0.0 - for i in range(len(guide) - 1): - p0 = guide[i] - p1 = guide[i + 1] - acc += math.hypot(p1[0] - p0[0], p1[1] - p0[1], p1[2] - p0[2]) - out.append(acc) - return out - - def tri_count_totals(self) -> list[int]: - """Sum of per-triangle strand counts for all 4 class slots.""" - totals = [0, 0, 0, 0] - for c0, c1, c2, c3 in self.tri_count: - totals[0] += c0 - totals[1] += c1 - totals[2] += c2 - totals[3] += c3 - return totals - - def summary(self) -> dict: - """Return a JSON-serializable summary of this groom LOD resource.""" - seg = self.guide_curve_lengths() - min_len = min(seg) if seg else 0.0 - mean_len = (sum(seg) / len(seg)) if seg else 0.0 - max_len = max(seg) if seg else 0.0 - max_err = max((abs(a - b) for a, b in zip(seg, self.lengths)), default=0.0) - return { - "archive": self.archive, - "offset": hex(self.offset), - "guides": self.guides, - "nodesPerGuide": self.nodes_per_guide, - "nodes": self.nodes, - "triangles": self.triangles_n, - "flags": hex(self.flags), - "box": [ - [round(c, 5) for c in self.box[0]], - [round(c, 5) for c in self.box[1]], - ], - "strandTotals": [self.strand_totals[0], self.strand_totals[1]], - "strandsFromTriangles": self.tri_count_totals(), - "regions": self.regions, - "bufferBytes": len(self.buffer), - "systemBytes": len(self.system), - "guideLengthM": [round(min_len, 5), round(mean_len, 5), round(max_len, 5)], - "storedLengthMaxErrorM": round(max_err, 6), - "lengthRandom": [round(self.length_random[0], 4), round(self.length_random[1], 4)], - "seeds": [hex(self.seed(0)), hex(self.seed(1))], - "optionalArrays": sorted( - name - for name, present in self.present.items() - if present and name.startswith(("ext", "node_", "direction")) - ), - "tailBytes": len(self.tail), - "sentinel2c": hex(self.sentinel_2c), - "hasExt3c": bool(self.ext_3c_offset), - "boneHashCount": len(self.bone_hashes), - "styleHashes": [hex(h) for h in self.style_hashes], - "stylePresetHash": hex(self.style_preset_hash) if self.style_preset_hash is not None else None, - "partClassHash": hex(self.part_class_hash) if self.part_class_hash is not None else None, - "partClass": self.part_class, - "hasUnsetRigFloats": self.has_unset_rig_floats, - "styleParams": _round_style_params(self.style_params), - } - - -def parse( - system: bytes | bytearray | memoryview | None, - buffer: bytes | bytearray | memoryview, - archive: str = "", - offset: int = 0, -) -> Groom: - """Decode one groom LOD from its inflated system page (optional) and GPU asset buffer.""" - buf = bytes(buffer) - if len(buf) < HEADER_SIZE: - raise GroomError(f"asset buffer shorter than {HEADER_SIZE}-byte header ({len(buf)} bytes)") - - header = struct.unpack_from("<40I", buf, 0) - guides = header[0x58 // 4] & 0xFFFF - tris = header[0x58 // 4] >> 16 - nodes = header[0x54 // 4] >> 8 - ppg = header[0x5C // 4] & 0xFF - if not guides or not tris or not ppg or nodes != guides * ppg: - raise GroomError(f"inconsistent counts: {guides} guides x {ppg} nodes != {nodes} (triangles={tris})") - - counts = {"G": guides, "N": nodes, "T": tris} - raw_spans: dict[str, tuple[int, int, int]] = {} - present: dict[str, bool] = {} - for at, (name, elem_size, domain) in ARRAYS.items(): - start = header[at // 4] - present[name] = bool(start) - if not start: - continue - n_elems = counts[domain] - end = start + elem_size * n_elems - if start < HEADER_SIZE or end > len(buf): - raise GroomError(f"array {name} ({start:#x}..{end:#x}) outside {len(buf)}-byte buffer") - raw_spans[name] = (start, end, n_elems) - - for needed in REQUIRED_ARRAYS: - if needed not in raw_spans: - raise GroomError(f"asset buffer missing required {needed} array") - - # Decode guide-major rest positions (half4 x, y, z, w). - pos_start, pos_end, _ = raw_spans["position"] - pos_flat = struct.unpack_from(f"<{nodes * 4}e", buf, pos_start) - if not all(math.isfinite(v) for v in pos_flat): - raise GroomError("non-finite node position") - positions: list[list[tuple[float, float, float]]] = [] - node_w: list[list[float]] = [] - idx_p = 0 - for _ in range(guides): - g_pos: list[tuple[float, float, float]] = [] - g_w: list[float] = [] - for _ in range(ppg): - g_pos.append((pos_flat[idx_p], pos_flat[idx_p + 1], pos_flat[idx_p + 2])) - g_w.append(pos_flat[idx_p + 3]) - idx_p += 4 - positions.append(g_pos) - node_w.append(g_w) - - # Decode scalp triangles (3 x u16 guide indices). - tri_start, _, _ = raw_spans["triangle"] - tri_flat = struct.unpack_from(f"<{tris * 3}H", buf, tri_start) - if tri_flat and max(tri_flat) >= guides: - raise GroomError(f"triangle references guide {max(tri_flat)} past guide count {guides}") - triangles = [(tri_flat[i], tri_flat[i + 1], tri_flat[i + 2]) for i in range(0, tris * 3, 3)] - - # Decode per-triangle strand counts (4 x u8) and optional region IDs (u8). - tc_start, tc_end, _ = raw_spans["tri_count"] - tc_bytes = buf[tc_start:tc_end] - tri_count = [ - (tc_bytes[i], tc_bytes[i + 1], tc_bytes[i + 2], tc_bytes[i + 3]) - for i in range(0, tris * 4, 4) - ] - if "tri_region" in raw_spans: - tr_start, tr_end, _ = raw_spans["tri_region"] - tri_region = buf[tr_start:tr_end] - else: - tri_region = bytes(tris) - - # Decode guide lengths (f16) and root UVs (2 x f16). - len_start, _, _ = raw_spans["length"] - lengths = list(struct.unpack_from(f"<{guides}e", buf, len_start)) - if not all(math.isfinite(v) for v in lengths): - raise GroomError("non-finite guide length") - - uv_start, _, _ = raw_spans["uv"] - uv_flat = struct.unpack_from(f"<{guides * 2}e", buf, uv_start) - if not all(math.isfinite(v) for v in uv_flat): - raise GroomError("non-finite guide UV") - uvs = [(uv_flat[i], uv_flat[i + 1]) for i in range(0, guides * 2, 2)] - - # Decode 8-slot bone indices and weights per guide. - bi_start, bi_end, _ = raw_spans["bone_index"] - bi_bytes = buf[bi_start:bi_end] - bone_indices = [tuple(bi_bytes[i:i + 8]) for i in range(0, guides * 8, 8)] - - bw_start, bw_end, _ = raw_spans["bone_weight"] - bw_bytes = buf[bw_start:bw_end] - bone_weights_raw = [tuple(bw_bytes[i:i + 8]) for i in range(0, guides * 8, 8)] - - # Keep raw slices of optional / undecoded arrays. - optional_raw: dict[str, bytes] = {} - for name, _width in OPTIONAL_RAW_ARRAYS: - if name in raw_spans: - s0, s1, _ = raw_spans[name] - optional_raw[name] = buf[s0:s1] - - # Length randomisation parameters at header +0x60 (two half floats: amount, min factor). - len_rand = struct.unpack_from("<2e", buf, 0x60) - if not (math.isfinite(len_rand[0]) and math.isfinite(len_rand[1])): - raise GroomError("non-finite length_random header field") - - # Optional variable-length tail block at header +0x20. - tail = b"" - tail_off = header[TAIL_OFFSET // 4] - ext_3c_off = header[EXT_3C_OFFSET // 4] - if tail_off: - if tail_off < HEADER_SIZE or tail_off > len(buf): - raise GroomError(f"tail offset {tail_off:#x} outside {len(buf)}-byte buffer") - starts = sorted([s for s, _, _ in raw_spans.values()] + ([ext_3c_off] if ext_3c_off else [])) - after = [s for s in starts if s > tail_off] - tail_end = after[0] if after else len(buf) - tail = buf[tail_off:tail_end] - - # Parse system page fields when present; fall back to computed box/totals for raw GPU buffers. - sys_bytes = bytes(system) if system else b"" - regions: list[dict] = [] - bone_hashes: tuple[int, ...] = () - style_hashes: tuple[int, ...] = () - style_preset_hash: int | None = None - part_class_hash: int | None = None - part_class: str | None = None - has_unset_rig_floats = False - style_params: dict | None = None - if sys_bytes: - sys_info = parse_system_page(sys_bytes) - box = sys_info["box"] - totals = sys_info["strand_totals"] - bone_hashes = sys_info["bone_hashes"] - regions = sys_info["regions"] - style_hashes = sys_info["style_hashes"] - style_preset_hash = sys_info["style_preset_hash"] - part_class_hash = sys_info["part_class_hash"] - part_class = sys_info["part_class"] - has_unset_rig_floats = sys_info["has_unset_rig_floats"] - style_params = sys_info["style_params"] - else: - xs = pos_flat[0::4] - ys = pos_flat[1::4] - zs = pos_flat[2::4] - box = ((min(xs), min(ys), min(zs)), (max(xs), max(ys), max(zs))) - tc_sum0 = sum(c[0] for c in tri_count) - tc_sum1 = sum(c[1] for c in tri_count) - totals = (tc_sum0, tc_sum1) - - return Groom( - archive=archive, - offset=offset, - system=sys_bytes, - buffer=buf, - header=header, - guides=guides, - triangles_n=tris, - nodes=nodes, - nodes_per_guide=ppg, - flags=header[0x50 // 4], - box=box, - strand_totals=totals, - regions=regions, - bone_hashes=bone_hashes, - style_hashes=style_hashes, - style_preset_hash=style_preset_hash, - part_class_hash=part_class_hash, - part_class=part_class, - has_unset_rig_floats=has_unset_rig_floats, - style_params=style_params, - positions=positions, - node_w=node_w, - triangles=triangles, - tri_count=tri_count, - tri_region=tri_region, - lengths=lengths, - uvs=uvs, - bone_indices=bone_indices, - bone_weights_raw=bone_weights_raw, - length_random=(len_rand[0], len_rand[1]), - present=present, - optional_raw=optional_raw, - tail=tail, - sentinel_2c=header[SENTINEL_OFFSET // 4], - ext_3c_offset=ext_3c_off, - ) - - -def read_resource( - src: bytes | bytearray | memoryview | mmap.mmap, - offset: int = 0, - archive: str = "", -) -> Groom: - """Read one groom LOD resource whose 16-byte zero prefix starts at ``offset``.""" - if offset < 0 or offset + 17 > len(src): - raise GroomError(f"resource offset {offset:#x} out of range") - if bytes(src[offset:offset + 16]) != b"\x00" * 16: - raise GroomError(f"expected 16-byte zero prefix at {offset:#x}") - return _read_zlib_resource(src, offset + 16, archive=archive, resource_offset=offset) - - -def _read_zlib_resource( - src: bytes | bytearray | memoryview | mmap.mmap, - zlib_offset: int, - *, - archive: str = "", - resource_offset: int = 0, -) -> Groom: - """Inflate the system page at ``zlib_offset`` followed by 16-aligned GPU buffer stream(s).""" - system, pos = inflate_stream(src, zlib_offset) - if not system_page_is_groom(system): - raise GroomError("not a groom LOD resource (system page signature mismatch)") - desc = _sys_ptr(system, 0x70) - size = struct.unpack_from("= len(src) or src[pos:pos + 1] != b"x": - raise GroomError("asset GPU buffer zlib stream missing or truncated") - chunk, pos = inflate_stream(src, pos) - gpu.extend(chunk) - return parse(system, bytes(gpu[:size]), archive=archive, offset=resource_offset) - - -def load_groom(path: str | os.PathLike, offset: int | None = None) -> Groom: - """Load one groom from an RPF archive (at ``offset`` or first match) or a carved ``.smh`` file.""" - path_str = os.fspath(path) - size = os.path.getsize(path_str) - if size == 0: - raise GroomError(f"empty input file: {path_str}") - - with open(path_str, "rb") as handle: - with mmap.mmap(handle.fileno(), 0, access=mmap.ACCESS_READ) as mm: - if offset is not None: - return read_resource(mm, offset, archive=path_str) - if mm[:17] == PREFIX: - return read_resource(mm, 0, archive=path_str) - if mm[:2] in (b"\x78\x01", b"\x78\x5e", b"\x78\x9c", b"\x78\xda"): - return _read_zlib_resource(mm, 0, archive=path_str, resource_offset=0) - if mm[:4] in (b"9FPR", b"RPF9"): - first = next(scan_offsets(mm), None) - if first is None: - raise GroomError(f"no smh groom LOD resources found in archive: {path_str}") - return read_resource(mm, first, archive=path_str) - # Standalone raw GPU asset buffer (e.g. a carved .smh GPU buffer). - return parse(None, mm[:], archive=path_str, offset=0) - - -# --- Shader-exact Class 0 RNG & barycentric strand generation ----------------------------------------- - - -def mul24(a: int, b: int) -> int: - """RDNA2 ``v_mad_u32_u24`` low-24x24->32 unsigned multiply.""" - return ((a & _M24) * (b & _M24)) & _M32 - - -def pcg_u24(state: int) -> int: - """PCG output hash folded to 24 bits (exact port of ``smh_gen_1_CS_InterpolateStrands``).""" - v = ((state & _M32) * 0x2C9277B5 + 0xAC564B05) & _M32 - w = (((v >> ((v >> 28) + 4)) ^ v) * 0x108EF2D9) & _M32 - return ((w >> 22) ^ (w & _M24)) & _M32 - - -def pcg_float(state: int) -> float: - """PCG output hash as an exact float in ``[0, 1)`` (``pcg_u24(state) * 2**-24``).""" - return pcg_u24(state) * _INV_2_24 - - -def scatter( - groom: Groom, - count: int | None = None, - strand_class: int = 0, - density_scale: float | None = None, - region_mask: Iterable[int] | None = None, - max_accepted: int | None = None, -) -> dict: - """Scatter strand roots with the exact integer RNG of ``smh_gen_1_CS_InterpolateStrands``. - - Args: - groom: Decoded ``Groom`` resource. - count: Number of strand threads (``0..count-1``). Defaults to ``groom.strand_totals[strand_class]`` - or the sum of per-triangle counts for ``strand_class``. - strand_class: ``0`` (placement set 0, exact ``smh_gen_1`` shader port) or ``1`` (placement set 1, - approximate until ``smh_gen_2``/``_4``/``_8``/``_16`` are ported; both classes are generated - alike and drawn together as one batch). - density_scale: Acceptance factor in ``saturate(tri_count * density_scale)``. Defaults to - ``1.0 / max(max_tri_count, 1.0)`` so the densest triangle is always accepted. - region_mask: Optional iterable of region IDs (1..255) to cull; region 0 is never culled. - max_accepted: Optional cap on accepted (non-culled) strand roots to collect. When ``None`` - (default), all ``count`` candidates are returned (including culled entries). When set, - candidates are evaluated in thread order ``0..count-1``, culled candidates are skipped, - and iteration stops once ``max_accepted`` accepted roots are collected, bounding memory - to ``O(max_accepted)`` instead of ``O(count)``. - - Returns: - Dict with keys ``tri`` (list[int]), ``culled`` (list[bool]), - ``bary`` (list[tuple[float, float, float]]), and ``seed`` (list[int]). - """ - if strand_class not in (0, 1): - raise GroomError(f"unsupported strand class {strand_class} (expected 0 or 1)") - - per_tri = [c[strand_class] for c in groom.tri_count] - if count is None: - count = groom.strand_totals[strand_class] or sum(per_tri) - if count < 0: - raise GroomError(f"strand count must be non-negative, got {count}") - - if max_accepted is not None and max_accepted <= 0: - return {"tri": [], "culled": [], "bary": [], "seed": []} - if count == 0: - return {"tri": [], "culled": [], "bary": [], "seed": []} - - if density_scale is None: - max_c = max(per_tri) if per_tri else 0 - density_scale = 1.0 / max(float(max_c), 1.0) - ds32 = _f32(float(density_scale)) - # Precompute IEEE 754 float32 acceptance thresholds for every possible u8 triangle count (0..255). - thresh = [min(max(_f32(float(c) * ds32), 0.0), 1.0) for c in range(256)] - - blocked = [False] * 256 - for rid in region_mask or (): - blocked[int(rid) & 255] = True - blocked[0] = False - - n_tris = groom.triangles_n - tri_region = groom.tri_region - seed_base = (groom.seed(strand_class) * 0x8A30D) & _M32 - c0_s0, c0_s8 = _ATTEMPT_CONSTS[0] - c1_s0, c1_s8 = _ATTEMPT_CONSTS[1] - c2_s0, c2_s8 = _ATTEMPT_CONSTS[2] - c3_s0, c3_s8 = _ATTEMPT_CONSTS[3] - attempts = ((c0_s0, c0_s8), (c1_s0, c1_s8), (c2_s0, c2_s8), (c3_s0, c3_s8)) - - if max_accepted is None: - tris_out: list[int] = [0] * count - culled_out: list[bool] = [False] * count - bary_out: list[tuple[float, float, float]] = [(0.0, 0.0, 0.0)] * count - seed_out: list[int] = [0] * count - else: - tris_out = [] - culled_out = [] - bary_out = [] - seed_out = [] - t_append = tris_out.append - c_append = culled_out.append - b_append = bary_out.append - s_append = seed_out.append - - sqrt = math.sqrt - for t in range(count): - v3 = (t * 0x19660D + 0xEF3EFB11) & _M32 - tri_t = 0 - v20_t = 0 - culled_t = False - for s0, s8 in attempts: - v11 = (s8 + v3) & _M32 - v5 = (v11 * 0x31CD17D1 + 0x153E39CE) & _M32 - v9 = v11 >> 16 - v6 = (v5 * v11 + 0x31CD17D1) & _M32 - v7 = (v6 * v5) & _M32 - v5 ^= v5 >> 16 - v6 ^= v6 >> 16 - v7 = (v7 + s0) & _M32 - v7 ^= v7 >> 16 - v8 = ((v9 ^ v11) + ((v7 * v5) & _M32)) & _M32 - v10 = (((v8 * v6) & _M32) + v5) & _M32 - pick = (v8 >> 16) % n_tris - v5 = (((v10 * v8) & _M32) + v6) & _M32 - v6 = (((v5 * v10) & _M32) + v7) & _M32 - - tri_t = pick - if blocked[tri_region[pick]]: - culled_t = True - continue - culled_t = False - v20_t = v5 >> 8 - if ((v6 & _M24) * _INV_2_24) < thresh[per_tri[pick]]: - break - - if max_accepted is not None and culled_t: - continue - - # Barycentric sample via 24-bit multiply cascade (v_mad_u32_u24, k = 0xC083C5). - seed_t = (0x3C1 * (tri_t & 0xFFFF) + seed_base + v20_t * 31) & _M32 - x1 = (0xC083C5 * (seed_t & _M24) + 0x3C6EF35F) & _M32 - x2 = (0xC083C5 * (x1 & _M24) + 0x3C6EF35F) & _M32 - x1 = (0xC083C5 * (x2 & _M24) + x1) & _M32 - x2 = (0xC083C5 * (x1 & _M24) + x2) & _M32 - x1 ^= x1 >> 12 - x2 ^= x2 >> 12 - x1 = (0xC083C5 * (x2 & _M24) + x1) & _M32 - a = (x1 & _M24) ^ (x1 >> 12) - x1 = (0xC083C5 * (x1 & _M24) + x2) & _M32 - b = (x1 & _M24) ^ (x1 >> 12) - - u1 = a * _INV_2_24 - u2 = b * _INV_2_24 - r = sqrt(u1) - if max_accepted is None: - tris_out[t] = tri_t - culled_out[t] = culled_t - bary_out[t] = (1.0 - r, (1.0 - u2) * r, u2 * r) - seed_out[t] = seed_t - else: - t_append(tri_t) - c_append(False) - b_append((1.0 - r, (1.0 - u2) * r, u2 * r)) - s_append(seed_t) - if len(tris_out) >= max_accepted: - break - - return {"tri": tris_out, "culled": culled_out, "bary": bary_out, "seed": seed_out} - - -def generate_strands( - groom: Groom, - count: int | None = None, - strand_class: int = 0, - density_scale: float | None = None, - region_mask: Iterable[int] | None = None, - max_strands: int | None = None, -) -> dict: - """Generate rest-pose strand polylines by barycentric blending and length trimming. - - Returns dict with keys: - - ``points``: ``list[list[tuple[float, float, float]]]`` of shape ``[n, nodes_per_guide]`` - (trimmed strands repeat their tip point on trailing nodes) - - ``live``: ``list[int]`` count of distinct nodes per strand (``1..nodes_per_guide``) - - ``length``: ``list[float]`` actual trimmed arc length in metres - - ``uv``: ``list[tuple[float, float]]`` barycentric root UV - - ``tri``: ``list[int]`` scalp triangle index - - ``bary``: ``list[tuple[float, float, float]]`` barycentric weights - """ - roots = scatter(groom, count, strand_class, density_scale, region_mask, max_strands) - r_tri = roots["tri"] - r_culled = roots["culled"] - r_bary = roots["bary"] - r_seed = roots["seed"] - - positions = groom.positions - triangles = groom.triangles - lengths = groom.lengths - uvs = groom.uvs - ppg = groom.nodes_per_guide - amount, low = groom.length_random - one_minus_low = 1.0 - low - eps_len = 2.0 ** -23 - hypot = math.hypot - - points_out: list[list[tuple[float, float, float]]] = [] - live_out: list[int] = [] - len_out: list[float] = [] - uv_out: list[tuple[float, float]] = [] - tri_out: list[int] = [] - bary_out: list[tuple[float, float, float]] = [] - - for i in range(len(r_tri)): - if r_culled[i]: - continue - if max_strands is not None and len(points_out) >= max_strands: - break - tri_i = r_tri[i] - b0, b1, b2 = r_bary[i] - g0, g1, g2 = triangles[tri_i] - - p0_list = positions[g0] - p1_list = positions[g1] - p2_list = positions[g2] - - guide_len = b0 * lengths[g0] + b1 * lengths[g1] + b2 * lengths[g2] - factor = low + pcg_float(r_seed[i]) * one_minus_low - target = guide_len * (1.0 + (factor - 1.0) * amount) - if target < 0.0: - target = 0.0 - - # Blend root position. - a0, a1, a2 = p0_list[0], p1_list[0], p2_list[0] - prev_x = b0 * a0[0] + b1 * a1[0] + b2 * a2[0] - prev_y = b0 * a0[1] + b1 * a1[1] + b2 * a2[1] - prev_z = b0 * a0[2] + b1 * a1[2] + b2 * a2[2] - - cur_x, cur_y, cur_z = prev_x, prev_y, prev_z - strand_pts: list[tuple[float, float, float]] = [(cur_x, cur_y, cur_z)] - remaining = target - total_used = 0.0 - live_nodes = 1 - - for k in range(1, ppg): - q0, q1, q2 = p0_list[k], p1_list[k], p2_list[k] - nx = b0 * q0[0] + b1 * q1[0] + b2 * q2[0] - ny = b0 * q0[1] + b1 * q1[1] + b2 * q2[1] - nz = b0 * q0[2] + b1 * q1[2] + b2 * q2[2] - - dx = nx - prev_x - dy = ny - prev_y - dz = nz - prev_z - prev_x, prev_y, prev_z = nx, ny, nz - - seg_len = hypot(dx, dy, dz) - if seg_len < eps_len: - seg_len = eps_len - - if remaining > 0.0: - use = seg_len if remaining >= seg_len else remaining - if use < 1e-9: - use = 0.0 - if use > 0.0: - scale = use / seg_len - cur_x += dx * scale - cur_y += dy * scale - cur_z += dz * scale - total_used += use - live_nodes += 1 - remaining -= seg_len - strand_pts.append((cur_x, cur_y, cur_z)) - - u0, v0 = uvs[g0] - u1, v1 = uvs[g1] - u2, v2 = uvs[g2] - points_out.append(strand_pts) - live_out.append(live_nodes) - len_out.append(total_used) - uv_out.append((b0 * u0 + b1 * u1 + b2 * u2, b0 * v0 + b1 * v1 + b2 * v2)) - tri_out.append(tri_i) - bary_out.append((b0, b1, b2)) - - return { - "points": points_out, - "live": live_out, - "length": len_out, - "uv": uv_out, - "tri": tri_out, - "bary": bary_out, - } - - -# --- Geometry builders & GLB export (pure stdlib) ----------------------------------------------------- - - -def _convert_up( - points: Iterable[tuple[float, float, float]], - up_axis: str = "z", -) -> list[tuple[float, float, float]]: - if up_axis == "y": - return [(_clean_zero(x), _clean_zero(y), _clean_zero(z)) for x, y, z in points] - # RAGE Z-up -> glTF Y-up: (x, z, -y). - return [(_clean_zero(x), _clean_zero(z), _clean_zero(-y)) for x, y, z in points] - - -def _polyline_frames( - poly: list[tuple[float, float, float]], -) -> tuple[list[tuple[float, float, float]], list[tuple[float, float, float]]]: - """Compute orthonormal (side, up) cross-section frame at each node of one polyline.""" - k = len(poly) - sides: list[tuple[float, float, float]] = [] - ups: list[tuple[float, float, float]] = [] - hypot = math.hypot - for j in range(k): - if k == 1: - tx, ty, tz = 0.0, 0.0, 1.0 - elif j == 0: - tx = poly[1][0] - poly[0][0] - ty = poly[1][1] - poly[0][1] - tz = poly[1][2] - poly[0][2] - elif j == k - 1: - tx = poly[j][0] - poly[j - 1][0] - ty = poly[j][1] - poly[j - 1][1] - tz = poly[j][2] - poly[j - 1][2] - else: - tx = 0.5 * (poly[j + 1][0] - poly[j - 1][0]) - ty = 0.5 * (poly[j + 1][1] - poly[j - 1][1]) - tz = 0.5 * (poly[j + 1][2] - poly[j - 1][2]) - norm = hypot(tx, ty, tz) - if norm > 1e-9: - inv = 1.0 / norm - tx, ty, tz = tx * inv, ty * inv, tz * inv - else: - tx, ty, tz = 0.0, 0.0, 1.0 - - # Reference vector avoids gimbal lock near +/-Z. - if abs(tz) < 0.9: - # cross(tangent, (0, 0, 1)) = (ty, -tx, 0) - sx, sy, sz = ty, -tx, 0.0 - else: - # cross(tangent, (1, 0, 0)) = (0, tz, -ty) - sx, sy, sz = 0.0, tz, -ty - sn = hypot(sx, sy, sz) - if sn > 1e-9: - inv_s = 1.0 / sn - sx, sy, sz = sx * inv_s, sy * inv_s, sz * inv_s - else: - sx, sy, sz = 1.0, 0.0, 0.0 - - # up = cross(tangent, side) - ux = ty * sz - tz * sy - uy = tz * sx - tx * sz - uz = tx * sy - ty * sx - sides.append((sx, sy, sz)) - ups.append((ux, uy, uz)) - return sides, ups - - -def build_tubes( - polylines: list[list[tuple[float, float, float]]], - live: list[int] | None = None, - *, - radius: float = 0.0004, - tip: float = 0.25, - sides: int = 3, -) -> tuple[list[tuple[float, float, float]], list[tuple[float, float, float]], list[int]]: - """Build tapered N-sided triangle tubes around polylines -> ``(verts, normals, indices)``.""" - if not polylines or sides < 3: - return [], [], [] - k = len(polylines[0]) - if k < 2: - return [], [], [] - - ring_trig = [ - (math.cos(s * (2.0 * math.pi / sides)), math.sin(s * (2.0 * math.pi / sides))) - for s in range(sides) - ] - denom = float(k - 1) - tapers = [(1.0 - (1.0 - tip) * (j / denom)) * radius for j in range(k)] - - verts: list[tuple[float, float, float]] = [] - normals: list[tuple[float, float, float]] = [] - indices: list[int] = [] - v_append = verts.append - n_append = normals.append - i_extend = indices.extend - - for idx, poly in enumerate(polylines): - base_poly = idx * k * sides - side_vecs, up_vecs = _polyline_frames(poly) - for j in range(k): - px, py, pz = poly[j] - sx, sy, sz = side_vecs[j] - ux, uy, uz = up_vecs[j] - rad = tapers[j] - for ca, sa in ring_trig: - rx = ca * sx + sa * ux - ry = ca * sy + sa * uy - rz = ca * sz + sa * uz - v_append((px + rx * rad, py + ry * rad, pz + rz * rad)) - n_append((rx, ry, rz)) - - seg_limit = (live[idx] - 1) if live is not None else (k - 1) - if seg_limit > k - 1: - seg_limit = k - 1 - for j in range(max(seg_limit, 0)): - ring0 = base_poly + j * sides - ring1 = ring0 + sides - for s in range(sides): - s_next = (s + 1) % sides - a = ring0 + s - b = ring0 + s_next - c = ring1 + s - d = ring1 + s_next - i_extend((a, b, c, b, d, c)) - - return verts, normals, indices - - -def build_ribbons( - polylines: list[list[tuple[float, float, float]]], - live: list[int] | None = None, - *, - width: float = 0.0008, - tip: float = 0.25, -) -> tuple[list[tuple[float, float, float]], list[tuple[float, float, float]], list[int]]: - """Build flat tapered quad-strip ribbons around polylines -> ``(verts, normals, indices)``.""" - if not polylines: - return [], [], [] - k = len(polylines[0]) - if k < 2: - return [], [], [] - - half_w = 0.5 * width - denom = float(k - 1) - half_tapers = [(1.0 - (1.0 - tip) * (j / denom)) * half_w for j in range(k)] - - verts: list[tuple[float, float, float]] = [] - normals: list[tuple[float, float, float]] = [] - indices: list[int] = [] - v_append = verts.append - n_append = normals.append - i_extend = indices.extend - - for idx, poly in enumerate(polylines): - base_poly = idx * k * 2 - side_vecs, up_vecs = _polyline_frames(poly) - for j in range(k): - px, py, pz = poly[j] - sx, sy, sz = side_vecs[j] - up = up_vecs[j] - hw = half_tapers[j] - v_append((px - sx * hw, py - sy * hw, pz - sz * hw)) - n_append(up) - v_append((px + sx * hw, py + sy * hw, pz + sz * hw)) - n_append(up) - - seg_limit = (live[idx] - 1) if live is not None else (k - 1) - if seg_limit > k - 1: - seg_limit = k - 1 - for j in range(max(seg_limit, 0)): - r0 = base_poly + j * 2 - r1 = r0 + 2 - i_extend((r0, r0 + 1, r1, r0 + 1, r1 + 1, r1)) - - return verts, normals, indices - - -def build_lines( - polylines: list[list[tuple[float, float, float]]], - live: list[int] | None = None, -) -> tuple[list[tuple[float, float, float]], list[int]]: - """Flatten polylines for glTF ``LINES`` (mode 1) -> ``(verts, paired_indices)``.""" - if not polylines: - return [], [] - k = len(polylines[0]) - verts: list[tuple[float, float, float]] = [] - indices: list[int] = [] - v_extend = verts.extend - i_extend = indices.extend - for idx, poly in enumerate(polylines): - base = idx * k - v_extend(poly) - seg_limit = (live[idx] - 1) if live is not None else (k - 1) - if seg_limit > k - 1: - seg_limit = k - 1 - for j in range(max(seg_limit, 0)): - a = base + j - i_extend((a, a + 1)) - return verts, indices - - -def _pack_scalar_indices(indices: list[int], vert_count: int) -> tuple[bytes, int]: - """Pack any index list (triangles, lines, or line strips) as uint16 or uint32.""" - if not indices: - raise GroomError("cannot pack empty index list") - lo = min(indices) - hi = max(indices) - if lo < 0 or hi >= vert_count: - raise GroomError(f"index out of range [0, {vert_count - 1}]: min={lo}, max={hi}") - if vert_count <= 65535: - comp_type = glb_writer.COMPONENT_UNSIGNED_SHORT - if _UINT16_CODE is not None: - arr = array.array(_UINT16_CODE, indices) - if _NEEDS_BYTESWAP: - arr.byteswap() - return arr.tobytes(), comp_type - return struct.pack(f"<{len(indices)}H", *indices), comp_type - - comp_type = glb_writer.COMPONENT_UNSIGNED_INT - if _UINT32_CODE is not None: - arr = array.array(_UINT32_CODE, indices) - if _NEEDS_BYTESWAP: - arr.byteswap() - return arr.tobytes(), comp_type - return struct.pack(f"<{len(indices)}I", *indices), comp_type - - -def _pack_vec3(values: list[tuple[float, float, float]]) -> tuple[bytes, list[float], list[float]]: - raw_bytes, floats = glb_writer._pack_f32(values, 3) - xs = floats[0::3] - ys = floats[1::3] - zs = floats[2::3] - return ( - raw_bytes, - [_clean_zero(min(xs)), _clean_zero(min(ys)), _clean_zero(min(zs))], - [_clean_zero(max(xs)), _clean_zero(max(ys)), _clean_zero(max(zs))], - ) - - -def to_glb( - groom: Groom, - *, - max_strands: int = 6000, - guide_radius: float = 0.0006, - strand_radius: float = 0.00035, - scalp: bool = True, - guides: bool = True, - classes: Iterable[int] = (0, 1), - geometry: str = "tubes", - curves: bool = False, - vertex_budget: int = 360000, - up_axis: str = "z", -) -> tuple[bytes, dict]: - """Serialize a groom LOD to binary glTF 2.0 (``.glb``) bytes plus metadata dict. - - ``geometry`` selects how guides and strands are emitted: - - ``"tubes"``: 3-sided tapered triangle tubes (glTF ``TRIANGLES``, mode 4). - - ``"ribbons"``: flat tapered quad-strip ribbons (glTF ``TRIANGLES``, mode 4, double-sided). - - ``"curves"``: indexed line segments (glTF ``LINES``, mode 1), one primitive per part. - - ``"line-strip"``: glTF ``LINE_STRIP`` (mode 3), one primitive per polyline. - - Passing ``curves=True`` overrides ``geometry`` to ``"curves"``. - """ - if curves: - geometry = "curves" - if geometry not in GEOMETRY_MODES: - raise GroomError(f"unsupported geometry mode {geometry!r} (expected one of {GEOMETRY_MODES})") - up = up_axis.lower() - if up not in ("z", "y"): - raise GroomError(f"unsupported up_axis {up_axis!r} (expected 'z' or 'y')") - cls_tuple = tuple(classes) - for cls in cls_tuple: - if cls not in (0, 1): - raise GroomError(f"unsupported strand class {cls} (expected 0 or 1)") - - bin_buf = bytearray() - buffer_views: list[dict] = [] - accessors: list[dict] = [] - gltf_materials: list[dict] = [] - part_mat_index: dict[int, int] = {} - primitives: list[dict] = [] - stats: dict = {"strands": {}, "shown": {}, "geometry": geometry} - name = f"groom_{groom.offset:x}" - - def get_material(part: int, double_sided: bool = False) -> int: - if part not in part_mat_index: - mat: dict = { - "name": PART_NAMES[part], - "pbrMetallicRoughness": { - "baseColorFactor": list(PART_COLORS[part]), - "metallicFactor": 0.0, - "roughnessFactor": 0.85, - }, - } - if double_sided: - mat["doubleSided"] = True - part_mat_index[part] = len(gltf_materials) - gltf_materials.append(mat) - return part_mat_index[part] - - def append_primitive( - part: int, - verts: list[tuple[float, float, float]], - normals: list[tuple[float, float, float]] | None, - indices: list[int], - mode: int = MODE_TRIANGLES, - double_sided: bool = False, - ) -> None: - if not verts or not indices: - return - conv_verts = _convert_up(verts, up) - pos_bytes, vmin, vmax = _pack_vec3(conv_verts) - pos_bv = glb_writer._append_buffer_view( - bin_buf, buffer_views, pos_bytes, target=glb_writer.TARGET_ARRAY_BUFFER, - ) - pos_acc = len(accessors) - accessors.append({ - "bufferView": pos_bv, - "componentType": glb_writer.COMPONENT_FLOAT, - "count": len(conv_verts), - "type": "VEC3", - "min": vmin, - "max": vmax, - }) - attributes: dict[str, int] = {"POSITION": pos_acc} - if normals is not None and len(normals) == len(conv_verts): - conv_nrm = [ - glb_writer._normalize3(*n) for n in _convert_up(normals, up) - ] - nrm_bytes, _ = glb_writer._pack_f32(conv_nrm, 3) - nrm_bv = glb_writer._append_buffer_view( - bin_buf, buffer_views, nrm_bytes, target=glb_writer.TARGET_ARRAY_BUFFER, - ) - nrm_acc = len(accessors) - accessors.append({ - "bufferView": nrm_bv, - "componentType": glb_writer.COMPONENT_FLOAT, - "count": len(conv_nrm), - "type": "VEC3", - }) - attributes["NORMAL"] = nrm_acc - - idx_bytes, idx_comp = _pack_scalar_indices(indices, len(conv_verts)) - idx_bv = glb_writer._append_buffer_view( - bin_buf, buffer_views, idx_bytes, target=glb_writer.TARGET_ELEMENT_ARRAY_BUFFER, - ) - idx_acc = len(accessors) - accessors.append({ - "bufferView": idx_bv, - "componentType": idx_comp, - "count": len(indices), - "type": "SCALAR", - }) - primitives.append({ - "attributes": attributes, - "indices": idx_acc, - "material": get_material(part, double_sided=double_sided), - "mode": mode, - "extras": {"shaderIndex": part, "part": PART_NAMES[part]}, - }) - - def append_polylines( - part: int, - polylines: list[list[tuple[float, float, float]]], - live: list[int] | None, - radius: float, - ) -> None: - if not polylines: - return - if geometry == "curves": - verts, idx = build_lines(polylines, live) - append_primitive(part, verts, None, idx, mode=MODE_LINES) - elif geometry == "line-strip": - # Share one vertex buffer view for the part and emit one LINE_STRIP primitive per strand. - all_verts: list[tuple[float, float, float]] = [] - ranges: list[tuple[int, int]] = [] - for i, poly in enumerate(polylines): - n_live = live[i] if live is not None else len(poly) - n_live = min(n_live, len(poly)) - if n_live < 2: - continue - start_v = len(all_verts) - all_verts.extend(poly[:n_live]) - ranges.append((start_v, n_live)) - if not ranges: - return - conv_verts = _convert_up(all_verts, up) - pos_bytes, vmin, vmax = _pack_vec3(conv_verts) - pos_bv = glb_writer._append_buffer_view( - bin_buf, buffer_views, pos_bytes, target=glb_writer.TARGET_ARRAY_BUFFER, - ) - pos_acc = len(accessors) - accessors.append({ - "bufferView": pos_bv, - "componentType": glb_writer.COMPONENT_FLOAT, - "count": len(conv_verts), - "type": "VEC3", - "min": vmin, - "max": vmax, - }) - mat_idx = get_material(part) - for start_v, n_live in ranges: - strip_idx = list(range(start_v, start_v + n_live)) - idx_bytes, idx_comp = _pack_scalar_indices(strip_idx, len(conv_verts)) - idx_bv = glb_writer._append_buffer_view( - bin_buf, buffer_views, idx_bytes, target=glb_writer.TARGET_ELEMENT_ARRAY_BUFFER, - ) - idx_acc = len(accessors) - accessors.append({ - "bufferView": idx_bv, - "componentType": idx_comp, - "count": n_live, - "type": "SCALAR", - }) - primitives.append({ - "attributes": {"POSITION": pos_acc}, - "indices": idx_acc, - "material": mat_idx, - "mode": MODE_LINE_STRIP, - "extras": {"shaderIndex": part, "part": PART_NAMES[part]}, - }) - elif geometry == "ribbons": - verts, nrms, idx = build_ribbons(polylines, live, width=radius * 2.0) - append_primitive(part, verts, nrms, idx, mode=MODE_TRIANGLES, double_sided=True) - else: - verts, nrms, idx = build_tubes(polylines, live, radius=radius) - append_primitive(part, verts, nrms, idx, mode=MODE_TRIANGLES) - - if scalp: - roots = [guide[0] for guide in groom.positions] - flat_tris = [i for tri in groom.triangles for i in tri] - if roots and flat_tris: - nrms = glb_writer._compute_smooth_normals(roots, flat_tris) - append_primitive(0, roots, nrms, flat_tris, mode=MODE_TRIANGLES, double_sided=True) - - if guides: - append_polylines(1, groom.positions, None, guide_radius) - - verts_per_node = 3 if geometry == "tubes" else (2 if geometry == "ribbons" else 1) - for cls in cls_tuple: - tri_sum = sum(c[cls] for c in groom.tri_count) - total = groom.strand_totals[cls] or tri_sum - stats["strands"][cls] = total - if not total or not tri_sum: - continue - if geometry in ("tubes", "ribbons"): - budget = min(max_strands, max(200, vertex_budget // max(groom.nodes_per_guide * verts_per_node, 1))) - else: - budget = max_strands - generated = generate_strands(groom, count=total, strand_class=cls, max_strands=budget) - stats["shown"][cls] = len(generated["points"]) - append_polylines(2 + cls, generated["points"], generated["live"], strand_radius) - - if not primitives: - raise GroomError("nothing to export") - - bin_pad = (-len(bin_buf)) % 4 - if bin_pad: - bin_buf.extend(b"\x00" * bin_pad) - - extras = { - "archive": groom.archive, - "member": hex(groom.offset), - "groom": groom.summary(), - "strandTotals": stats["strands"], - "strandsShown": stats["shown"], - "geometry": geometry, - "note": "Tube/ribbon radii are display sizes, not the game's runtime strand width.", - } - gltf: dict = { - "asset": {"version": "2.0", "generator": "Leonida smh_groom"}, - "scene": 0, - "scenes": [{"nodes": [0]}], - "nodes": [{"name": name, "mesh": 0}], - "meshes": [{"name": name, "primitives": primitives}], - "materials": gltf_materials, - "accessors": accessors, - "bufferViews": buffer_views, - "buffers": [{"byteLength": len(bin_buf)}], - "extras": extras, - } - json_bytes = json.dumps(gltf, separators=(",", ":"), ensure_ascii=False, allow_nan=False).encode("utf-8") - json_pad = (-len(json_bytes)) % 4 - if json_pad: - json_bytes += b" " * json_pad - - total_length = 12 + 8 + len(json_bytes) + 8 + len(bin_buf) - blob = b"".join(( - struct.pack("<4sII", glb_writer.GLB_MAGIC, glb_writer.GLB_VERSION, total_length), - struct.pack(" dict: - """Export ``groom`` to a binary ``.glb`` file atomically; returns metadata dict.""" - blob, meta = to_glb(groom, **kwargs) - glb_writer._write_bytes_atomic(os.fspath(path), blob) - meta["bytes"] = len(blob) - return meta - - -# --- LOD chain grouping & corpus census --------------------------------------------------------------- - - -def classify_placement( - box: tuple[tuple[float, float, float], tuple[float, float, float]], - longest_m: float, -) -> str: - """Heuristic placement class from stored bounding box (skeleton-root space, Z-up, metres).""" - (x0, y0, z0), (x1, y1, z1) = box - width = x1 - x0 - height = z1 - z0 - zc = 0.5 * (z0 + z1) - if abs(x0 + x1) < 0.08 and width < 0.34 and 0.44 < zc < 0.9 and z1 < 1.05 and y0 > -0.5: - if z1 > 0.745 or height > 0.24: - return "Scalp hair" - if height < 0.075 and zc > 0.62: - return "Brows and lashes" - return "Facial hair" - if ( - width < 0.9 - and -1.05 < z0 - and z1 < 0.52 - and longest_m < 0.08 - and abs(x0 + x1) < 0.12 - and (y1 - y0) < 0.45 - ): - return "Body hair" - return "Fur and other" - - -def _same_lod_asset(a: dict, b: dict) -> bool: - if a["ppg"] != b["ppg"] or a["flags"] != b["flags"] or b["guides"] >= a["guides"]: - return False - for u, v in zip(a["box"], b["box"]): - for p, q in zip(u, v): - if abs(p - q) > 0.03: - return False - if abs(a["s0"] - b["s0"]) > max(12, 0.05 * a["s0"]): - return False - if abs(a["s1"] - b["s1"]) > max(12, 0.05 * a["s1"]): - return False - return True - - -def group_lod_chains(rows: list[dict]) -> list[list[dict]]: - """Group decoded LOD summary rows into logical multi-LOD assets, rejoining split chains.""" - ok = [r for r in rows if not r.get("error")] - runs: list[list[dict]] = [] - cur: list[dict] = [] - for row in ok: - if cur and _same_lod_asset(cur[-1], row) and len(cur) < 8: - cur.append(row) - else: - if cur: - runs.append(cur) - cur = [row] - if cur: - runs.append(cur) - - assets: list[list[dict]] = [] - used: set[int] = set() - for i, run in enumerate(runs): - if i in used: - continue - full = list(run) - # Split LOD chains resume 1 to 3 runs later (LOD 0, intervening groom(s), LODs 1..3). - for j in (i + 2, i + 3, i + 1): - if j < len(runs) and j not in used and len(full) < 4 and _same_lod_asset(full[-1], runs[j][0]): - full.extend(runs[j]) - used.add(j) - break - assets.append(full) - return assets - - -def _collect_census_targets(paths: Iterable[str]) -> list[str]: - targets: list[str] = [] - for raw in paths: - if os.path.isdir(raw): - for root, dirs, files in os.walk(raw): - dirs.sort() - for name in sorted(files): - low = name.lower() - if low.endswith((".rpf", ".smh")): - targets.append(os.path.join(root, name)) - else: - targets.append(raw) - return targets - - -def run_census(paths: Iterable[str], *, limit: int | None = None) -> dict: - """Scan archives or carved ``.smh`` files and return aggregate corpus census statistics.""" - targets = _collect_census_targets(paths) - per_source: list[dict] = [] - total_lods = 0 - total_assets = 0 - total_errors = 0 - total_buffer_bytes = 0 - total_s0 = 0 - total_s1 = 0 - class0_exact_match = 0 - class1_exact_match = 0 - sentinel_non_default = 0 - ext_3c_count = 0 - unset_rig_float_assets = 0 - flags_hist: collections.Counter[str] = collections.Counter() - lod_depth_hist: collections.Counter[int] = collections.Counter() - opt_array_hist: collections.Counter[str] = collections.Counter() - placement_hist: collections.Counter[str] = collections.Counter() - part_class_hist: collections.Counter[str] = collections.Counter() - style_preset_hist: collections.Counter[str] = collections.Counter() - guides_min: int | None = None - guides_max = 0 - ppg_min: int | None = None - ppg_max = 0 - remaining = limit - - def _row_from_groom(g: Groom, off: int) -> dict: - tc_totals = g.tri_count_totals() - longest = max(g.lengths) if g.lengths else 0.0 - return { - "offset": off, - "error": None, - "guides": g.guides, - "ppg": g.nodes_per_guide, - "tris": g.triangles_n, - "flags": g.flags, - "s0": g.strand_totals[0], - "s1": g.strand_totals[1], - "tc0": tc_totals[0], - "tc1": tc_totals[1], - "bytes": len(g.buffer), - "box": g.box, - "longest": longest, - "opt": [n for n, p in g.present.items() if p and n.startswith(("ext", "node_", "direction"))], - "sentinel_2c": g.sentinel_2c, - "has_ext_3c": bool(g.ext_3c_offset), - "part_class": g.part_class, - "part_class_hash": g.part_class_hash, - "style_preset_hash": g.style_preset_hash, - "has_unset_rig_floats": g.has_unset_rig_floats, - } - - for target in targets: - if remaining is not None and remaining <= 0: - break - size = os.path.getsize(target) - rows: list[dict] = [] - if size == 0: - continue - - with open(target, "rb") as handle: - with mmap.mmap(handle.fileno(), 0, access=mmap.ACCESS_READ) as mm: - if target.lower().endswith(".rpf") or mm[:4] in (b"9FPR", b"RPF9"): - for off in scan_offsets(mm): - if remaining is not None and remaining <= 0: - break - if remaining is not None: - remaining -= 1 - try: - g = read_resource(mm, off, archive=target) - rows.append(_row_from_groom(g, off)) - except (GroomError, ValueError, IndexError) as exc: - rows.append({"offset": off, "error": str(exc)}) - else: - if remaining is not None: - remaining -= 1 - try: - g = load_groom(target) - rows.append(_row_from_groom(g, 0)) - except (GroomError, ValueError, IndexError) as exc: - rows.append({"offset": 0, "error": str(exc)}) - - ok_rows = [r for r in rows if not r["error"]] - err_rows = [r for r in rows if r["error"]] - chains = group_lod_chains(ok_rows) - - src_bytes = sum(r["bytes"] for r in ok_rows) - src_s0 = sum(chain[0]["s0"] for chain in chains) - src_s1 = sum(chain[0]["s1"] for chain in chains) - - total_lods += len(ok_rows) - total_errors += len(err_rows) - total_assets += len(chains) - total_buffer_bytes += src_bytes - total_s0 += src_s0 - total_s1 += src_s1 - - for r in ok_rows: - flags_hist[hex(r["flags"])] += 1 - for name in r["opt"]: - opt_array_hist[name] += 1 - if r["sentinel_2c"] != 0xFFFFFFFF: - sentinel_non_default += 1 - if r["has_ext_3c"]: - ext_3c_count += 1 - guides_min = r["guides"] if guides_min is None else min(guides_min, r["guides"]) - guides_max = max(guides_max, r["guides"]) - ppg_min = r["ppg"] if ppg_min is None else min(ppg_min, r["ppg"]) - ppg_max = max(ppg_max, r["ppg"]) - - for chain in chains: - lod_depth_hist[len(chain)] += 1 - lod0 = chain[0] - if lod0["tc0"] == lod0["s0"]: - class0_exact_match += 1 - if lod0["tc1"] == lod0["s1"]: - class1_exact_match += 1 - placement_hist[classify_placement(lod0["box"], lod0["longest"])] += 1 - if lod0["part_class"] is not None: - part_class_hist[lod0["part_class"]] += 1 - elif lod0["part_class_hash"] is not None: - part_class_hist[hex(lod0["part_class_hash"])] += 1 - if lod0["style_preset_hash"] is not None: - style_preset_hist[hex(lod0["style_preset_hash"])] += 1 - if lod0["has_unset_rig_floats"]: - unset_rig_float_assets += 1 - - per_source.append({ - "source": os.path.basename(target), - "lods": len(ok_rows), - "assets": len(chains), - "errors": len(err_rows), - "bufferBytes": src_bytes, - "strandsClass0": src_s0, - "strandsClass1": src_s1, - }) - - return { - "sources": per_source, - "totals": { - "lods": total_lods, - "assets": total_assets, - "errors": total_errors, - "bufferBytes": total_buffer_bytes, - "strandsClass0": total_s0, - "strandsClass1": total_s1, - "class0TriSumMatchesLod0": class0_exact_match, - "class1TriSumMatchesLod0": class1_exact_match, - "sentinel2cNonDefaultLods": sentinel_non_default, - "ext3cLods": ext_3c_count, - "unsetRigFloatAssets": unset_rig_float_assets, - "stylePresetDistinctCount": len(style_preset_hist), - "guidesRange": [guides_min or 0, guides_max], - "nodesPerGuideRange": [ppg_min or 0, ppg_max], - }, - "lodDepthHistogram": {str(k): v for k, v in sorted(lod_depth_hist.items())}, - "placementHistogram": dict(placement_hist.most_common()), - "partClassHistogram": dict(part_class_hist.most_common()), - "topStylePresets": dict(style_preset_hist.most_common(12)), - "optionalArrays": dict(opt_array_hist.most_common()), - "topFlags": dict(flags_hist.most_common(12)), - } - - -# --- CLI ---------------------------------------------------------------------------------------------- - - -def _parse_int(text: str) -> int: - try: - value = int(text, 0) - except ValueError: - raise argparse.ArgumentTypeError(f"invalid integer: {text!r}") from None - if value < 0: - raise argparse.ArgumentTypeError("value must be >= 0") - return value - - -def _parse_limit(text: str) -> int: - """--limit: at least 1; 0 stopped before the first target, so census read as an empty corpus.""" - try: - value = int(text, 0) - except ValueError: - raise argparse.ArgumentTypeError(f"invalid integer: {text!r}") from None - if value < 1: - raise argparse.ArgumentTypeError("must be at least 1") - return value - - -def _parse_classes(text: str) -> tuple[int, ...]: - if not text.strip(): - return () - out: list[int] = [] - for part in text.split(","): - val = int(part.strip()) - if val not in (0, 1): - raise argparse.ArgumentTypeError(f"strand class must be 0 or 1, got {val}") - if val not in out: - out.append(val) - return tuple(out) - - -def _format_inspect_text(summary: dict) -> str: - part_label = summary["partClass"] or "unknown" - part_hash = summary["partClassHash"] or "none" - preset_hash = summary["stylePresetHash"] or "none" - lines = [ - f"Source: {summary['archive']} @ {summary['offset']}", - f"Geometry: {summary['guides']} guides x {summary['nodesPerGuide']} nodes " - f"({summary['nodes']} nodes), {summary['triangles']} scalp triangles", - f"Flags: {summary['flags']} (sentinel +0x2c={summary['sentinel2c']}, " - f"ext_3c={summary['hasExt3c']}, unset_rig_floats={summary['hasUnsetRigFloats']})", - f"Part / preset: part_class={part_label} ({part_hash}) style_preset={preset_hash}", - f"Buffer: {summary['bufferBytes']} B GPU, {summary['systemBytes']} B system, {summary['tailBytes']} B tail", - f"Bounds (m): min={summary['box'][0]} max={summary['box'][1]}", - f"Strands: system={summary['strandTotals']} tri_sum={summary['strandsFromTriangles']}", - f"Guide length: min={summary['guideLengthM'][0]} m mean={summary['guideLengthM'][1]} m " - f"max={summary['guideLengthM'][2]} m (max stored error {summary['storedLengthMaxErrorM']} m)", - f"Length random: amount={summary['lengthRandom'][0]} min_factor={summary['lengthRandom'][1]}", - f"Seeds: class0={summary['seeds'][0]} class1={summary['seeds'][1]}", - f"Regions: {len(summary['regions'])} Bone hashes: {summary['boneHashCount']}", - f"Optional: {', '.join(summary['optionalArrays']) or 'none'}", - ] - sp = summary.get("styleParams") - if sp is not None: - c0 = sp["curlFrizz0"] - c1 = sp["curlFrizz1"] - lines.append( - f"Style (+0xe8): width={sp['strandWidth']} longest={sp['longestGuideM']}/{sp['longestGuideAltM']} m " - f"braid={sp['braidParam']} curl0(r={c0['radiiM']}, f={c0['frequenciesPerM']}) " - f"curl1(r={c1['radiiM']}, f={c1['frequenciesPerM']})" - ) - return "\n".join(lines) - - -def _format_census_text(report: dict) -> str: - t = report["totals"] - lines = [ - f"Groom census: {t['assets']} assets, {t['lods']} LOD resources, {t['errors']} decode errors", - f"GPU buffers: {t['bufferBytes']:,} bytes ({t['bufferBytes'] / (1024 * 1024):.1f} MiB)", - f"Strands: class 0 = {t['strandsClass0']:,} (tri-sum exact in {t['class0TriSumMatchesLod0']}/{t['assets']} LOD0), " - f"class 1 = {t['strandsClass1']:,} (tri-sum exact in {t['class1TriSumMatchesLod0']}/{t['assets']} LOD0)", - f"Guides range: {t['guidesRange'][0]}..{t['guidesRange'][1]} " - f"Nodes/guide range: {t['nodesPerGuideRange'][0]}..{t['nodesPerGuideRange'][1]}", - f"LOD depths: {report['lodDepthHistogram']}", - f"Placement: {report['placementHistogram']}", - f"Part classes: {report['partClassHistogram']} " - f"(style presets: {t['stylePresetDistinctCount']} distinct, unset rig floats: {t['unsetRigFloatAssets']})", - ] - for src in report["sources"]: - lines.append( - f" {src['source']}: {src['assets']} assets, {src['lods']} LODs, " - f"{src['errors']} errors, {src['bufferBytes']:,} B" - ) - return "\n".join(lines) - - -def build_parser() -> argparse.ArgumentParser: - parser = argparse.ArgumentParser( - description="Decode, inspect, census and export RAGE smh GPU strand grooms (stdlib only)." - ) - sub = parser.add_subparsers(dest="command", required=True) - - p_ins = sub.add_parser("inspect", help="Inspect one groom LOD resource or carved .smh file.") - p_ins.add_argument("path", help="Path to carved .smh/.bin file or RPF9 archive") - p_ins.add_argument("--offset", type=_parse_int, default=None, help="Byte offset inside archive (decimal or 0x hex)") - p_ins.add_argument("--json", action="store_true", help="Emit JSON summary") - - p_cen = sub.add_parser("census", help="Scan RPF9 archives, carved .smh files or directories for aggregate counts.") - p_cen.add_argument("paths", nargs="+", help="One or more archive files, .smh files or directories") - p_cen.add_argument("--json", action="store_true", help="Emit JSON report") - p_cen.add_argument("--limit", type=_parse_limit, default=None, help="Stop after N groom LOD resources") - - p_glb = sub.add_parser("export-glb", help="Export a groom LOD to binary glTF 2.0 (.glb).") - p_glb.add_argument("path", help="Path to carved .smh/.bin file or RPF9 archive") - p_glb.add_argument("output", help="Output .glb file path") - p_glb.add_argument("--offset", type=_parse_int, default=None, help="Byte offset inside archive (decimal or 0x hex)") - p_glb.add_argument( - "--geometry", - choices=GEOMETRY_MODES, - default="tubes", - help="Strand/guide representation: tubes (default), ribbons, curves (LINES), or line-strip (LINE_STRIP)", - ) - p_glb.add_argument("--curves", action="store_true", help="Shorthand for --geometry curves") - p_glb.add_argument("--strands", type=_parse_int, default=6000, help="Maximum strands per class to export") - p_glb.add_argument( - "--classes", - type=_parse_classes, - default=(0, 1), - help="Comma-separated placement classes to export (default 0,1; both sets are drawn together in one batch)", - ) - p_glb.add_argument("--no-scalp", action="store_true", help="Omit scalp triangle mesh") - p_glb.add_argument("--no-guides", action="store_true", help="Omit guide curves/tubes") - p_glb.add_argument("--guide-radius", type=float, default=0.0006, help="Display tube/ribbon radius for guides (m)") - p_glb.add_argument("--strand-radius", type=float, default=0.00035, help="Display tube/ribbon radius for strands (m)") - p_glb.add_argument("--up", choices=("z", "y"), default="z", help="Source up axis (default z -> glTF Y-up)") - - return parser - - -def main(argv: list[str] | None = None) -> int: - args = build_parser().parse_args(argv) - try: - if args.command == "inspect": - groom = load_groom(args.path, offset=args.offset) - summary = groom.summary() - if args.json: - print(json.dumps(summary, indent=2)) - else: - print(_format_inspect_text(summary)) - return 0 - - if args.command == "census": - report = run_census(args.paths, limit=args.limit) - if args.json: - print(json.dumps(report, indent=2)) - else: - print(_format_census_text(report)) - return 0 - - if args.command == "export-glb": - if os.path.exists(args.output) and os.path.exists(args.path) and os.path.samefile(args.path, args.output): - raise GroomError(f"output must not overwrite the input file: {args.path}") - groom = load_groom(args.path, offset=args.offset) - meta = write_glb( - args.output, - groom, - max_strands=args.strands, - guide_radius=args.guide_radius, - strand_radius=args.strand_radius, - scalp=not args.no_scalp, - guides=not args.no_guides, - classes=args.classes, - geometry=args.geometry, - curves=args.curves, - up_axis=args.up, - ) - print(json.dumps({ - "output": args.output, - "bytes": meta["bytes"], - "geometry": meta["geometry"], - "strandTotals": meta["strandTotals"], - "strandsShown": meta["strandsShown"], - })) - return 0 - except (GroomError, glb_writer.GlbError, OSError) as exc: - print(f"ERROR: {exc}", file=sys.stderr) - return 1 - return 0 - - -if __name__ == "__main__": - try: # a redirected stdout is strict ANSI code page under -I; write '?' for what it cannot encode - sys.stdout.reconfigure(errors="replace") - except (AttributeError, ValueError, OSError): - pass - raise SystemExit(main()) diff --git a/tools/spirv_asm.py b/tools/spirv_asm.py deleted file mode 100644 index 49d0809e1..000000000 --- a/tools/spirv_asm.py +++ /dev/null @@ -1,707 +0,0 @@ -"""Pure-Python SPIR-V binary assembler (standard library only, no external spirv-as). - -Assembles SPIR-V assembly text (.spvasm) emitted by tools/rdna2spirv.py (or any -conforming SPIR-V assembly targeting Vulkan 1.0–1.4) directly into binary SPIR-V -words in memory. - -Grammar tables in tools/spirv_asm_tables.py are derived from Khronos Group -SPIRV-Headers (MIT License): spirv.core.grammar.json, -extinst.glsl.std.450.grammar.json and extinst.nonsemantic.debugprintf.grammar.json. - -As a module: - from spirv_asm import assemble - spv_bytes = assemble(asm_text, target_env="vulkan1.2") - -As a CLI: - python3 -I tools/spirv_asm.py input.spvasm -o output.spv [--target-env vulkan1.2] -Usage: `python -I tools/spirv_asm.py --help` lists the options. -""" -import argparse -import array -import math -import os -import re -import struct -import sys -from fractions import Fraction - -_HERE = os.path.dirname(os.path.abspath(__file__)) -if _HERE not in sys.path: - sys.path.insert(0, _HERE) - -from spirv_asm_tables import ( # noqa: E402 - BIT_ENUMS, GLSL_STD_450, INSTRUCTIONS, NONSEMANTIC_DEBUGPRINTF, VALUE_ENUMS, -) - -SPIRV_MAGIC = 0x07230203 - -TARGET_ENV_VERSION = { - "vulkan1.0": 0x00010000, - "vulkan1.1": 0x00010300, - "vulkan1.1spv1.4": 0x00010400, - "vulkan1.2": 0x00010500, - "vulkan1.3": 0x00010600, - "vulkan1.4": 0x00010600, - "spv1.0": 0x00010000, - "spv1.1": 0x00010100, - "spv1.2": 0x00010200, - "spv1.3": 0x00010300, - "spv1.4": 0x00010400, - "spv1.5": 0x00010500, - "spv1.6": 0x00010600, -} - -_ID_KINDS = frozenset(("IdRef", "IdResult", "IdResultType", "IdScope", "IdMemorySemantics")) -_ID_RE = re.compile(r"%[A-Za-z0-9_]+") -_EXT_SETS = { - "GLSL.std.450": GLSL_STD_450, - "NonSemantic.DebugPrintf": NONSEMANTIC_DEBUGPRINTF, # spirv-dis writes its instruction by name -} - -# OpTypeForwardPointer takes an ID reference. Its matching OpTypePointer defines the type. -_TYPE_DEFINITIONS = frozenset( - name for name, (_, _, has_result, _) in INSTRUCTIONS.items() - if has_result and name.startswith("OpType") -) - -# Precompute fixed-arity pure-Id instructions (e.g. OpIAdd, OpFMul, OpSelect, OpStore, OpBranch) -# so the hot loop encodes ~80% of shader lines without per-operand dispatch overhead. -_PURE_ID_INSNS: dict[str, tuple[int, bool, bool, int, bool]] = {} -for _opname, (_opc, _hrt, _hres, _ospecs) in INSTRUCTIONS.items(): - if _opname in ("OpSwitch", "OpExtInst"): - continue - if all(_k in _ID_KINDS and _q in ("", "*") for _k, _q in _ospecs): - _has_var = bool(_ospecs and _ospecs[-1][1] == "*") - if not _has_var or all(_q == "" for _, _q in _ospecs[:-1]): - _min_args = len(_ospecs) - (1 if _has_var else 0) - _PURE_ID_INSNS[_opname] = (_opc, _hrt, _hres, _min_args, _has_var) - - -class SpirvAsmError(ValueError): - """Raised when SPIR-V assembly text cannot be encoded.""" - - -# Leave an unterminated literal together so the tokenizer reports its opening line. -_QUOTED_OR_COMMENT = r'"[^"\\]*(?:\\[\s\S][^"\\]*)*(?:"|(?:\\)?\Z)|;[^\r\n]*' -_ASSEMBLY_TOKEN = re.compile(_QUOTED_OR_COMMENT) -_ASSEMBLY_PART = re.compile(_QUOTED_OR_COMMENT + r'|(\r\n?|\n)') - - -def _line_break_count(text: str) -> int: - return text.count("\r") + text.count("\n") - text.count("\r\n") - - -def _instruction_lines(text): - # Most modules have only single-line operands. Keep their bulk split on the fast path. - if not any("\r" in part[0] or "\n" in part[0] for part in _ASSEMBLY_TOKEN.finditer(text)): - return enumerate(text.replace("\r\n", "\n").replace("\r", "\n").split("\n"), 1) - return _multiline_instructions(text) - - -def _multiline_instructions(text): - """Yield instruction text and its physical starting line, keeping quoted line endings.""" - start = 0 - instruction_line = physical_line = 1 - for part in _ASSEMBLY_PART.finditer(text): - if part[1] is None: - token = part[0] - physical_line += _line_break_count(token) - continue - yield instruction_line, text[start:part.start()] - physical_line += 1 - instruction_line = physical_line - start = part.end() - if start < len(text): - yield instruction_line, text[start:] - - -def _tokenize_line(line: str, lineno: int) -> list[str]: - """Split one assembly line into tokens, stripping ';' comments outside quoted strings.""" - if '"' not in line: - semi = line.find(";") - return (line[:semi] if semi >= 0 else line).split() - tokens = [] - n = len(line) - i = 0 - while i < n: - ch = line[i] - if ch <= " ": - i += 1 - continue - if ch == ";": - break - if ch == '"': - j = i + 1 - out = ['"'] - while j < n: - c = line[j] - if c == "\\" and j + 1 < n: - out.append(c) - out.append(line[j + 1]) - j += 2 - elif c == '"': - out.append('"') - j += 1 - break - else: - out.append(c) - j += 1 - else: - raise SpirvAsmError(f"line {lineno}: unterminated string literal") - token = "".join(out) - tokens.append(token) - lineno += _line_break_count(token) - i = j - continue - j = i + 1 - while j < n and line[j] > " " and line[j] != ";": - j += 1 - tokens.append(line[i:j]) - i = j - return tokens - - -def _instruction_tokens(text: str): - """Yield one token list per instruction, with its physical starting line.""" - tokens = [] - start_line = previous_line = 1 - for line, raw_line in _instruction_lines(text): - for token in _tokenize_line(raw_line, line): - if token == "=" and len(tokens) > 1 and tokens[-1].startswith("%"): - # The ID before '=' begins the next instruction, even across a newline. - result_id = tokens.pop() - yield start_line, tokens - start_line, tokens = previous_line, [result_id] - elif (tokens and tokens[-1] != "=" and token.startswith("Op") - and len(token) > 2 and "A" <= token[2] <= "Z" - and not (len(tokens) == 4 and tokens[2] == "OpSpecConstantOp")): - # OpSpecConstantOp also accepts an Op-prefixed mnemonic as its first operand. - yield start_line, tokens - tokens = [] - if not tokens: - start_line = line - tokens.append(token) - previous_line = line - if token.startswith('"'): - line += _line_break_count(token) - if tokens: - yield start_line, tokens - - -def _unquote_string(tok: str, lineno: int) -> str: - if len(tok) < 2 or tok[0] != '"' or tok[-1] != '"': - raise SpirvAsmError(f"line {lineno}: expected string literal, got {tok!r}") - raw = tok[1:-1] - if "\\" not in raw: - return raw - # SPIRV-Tools decodes \ as the literal character (e.g. \n -> 'n', \" -> '"', \\ -> '\'). - out = [] - i = 0 - n = len(raw) - while i < n: - if raw[i] == "\\" and i + 1 < n: - out.append(raw[i + 1]) - i += 2 - else: - out.append(raw[i]) - i += 1 - return "".join(out) - - -def _encode_string_words(text: str) -> list[int]: - raw = text.encode("utf-8") + b"\x00" - rem = len(raw) & 3 - if rem: - raw += b"\x00" * (4 - rem) - return list(struct.unpack(f"<{len(raw) // 4}I", raw)) - - -def _parse_int(tok: str, lineno: int) -> int: - try: - return int(tok, 0) - except ValueError as exc: - raise SpirvAsmError(f"line {lineno}: invalid integer literal {tok!r}") from exc - - -def _int_literal(tok: str, width: int, signed: bool, lineno: int) -> int: - """The bits of integer literal `tok` for a `width`-bit integer type, refused where spirv-as refuses it. - - As SPIRV-Tools reads it: an unsigned type takes 0..2^width-1 and no minus sign (not even -0); a signed type - takes -2^(width-1)..2^(width-1)-1, or a hex literal 0..2^width-1 read as the bit pattern (0xFFFF for a 16-bit - signed type is -1). Only a bare hex literal is a bit pattern: with a sign (+0xFFFF) it is a value and must fit the - signed range, as SPIRV-Tools reads it. A type narrower than 32 bits fills its word as the spec says: zero-extended when unsigned, - sign-extended when signed (0x8000 for a 16-bit signed type is 0xFFFF8000). Returns the value as an unsigned - number of max(width, 32) bits. - """ - val = _parse_int(tok, lineno) - kind = "signed" if signed else "unsigned" - if not signed: - if tok.startswith("-"): - raise SpirvAsmError(f"line {lineno}: cannot put a negative number in an unsigned literal: {tok}") - if val >> width: - raise SpirvAsmError(f"line {lineno}: integer {tok} does not fit in a {width}-bit {kind} integer") - elif re.match(r"0[xX]", tok) and val >> width == 0: - if val >> (width - 1): - val -= 1 << width - elif not -(1 << (width - 1)) <= val < 1 << (width - 1): - raise SpirvAsmError(f"line {lineno}: integer {tok} does not fit in a {width}-bit {kind} integer") - return val & ((1 << max(width, 32)) - 1) - - -def _u32_literal(tok: str, lineno: int) -> int: - """A LiteralInteger operand, or a numeric enum/mask value: one unsigned 32-bit word.""" - return _int_literal(tok, 32, False, lineno) - - -_HEX_FLOAT_RE = re.compile(r"^([+-]?)0[xX]([0-9a-fA-F]*)(?:\.([0-9a-fA-F]*))?[pP]([+-]?\d+)$") -_DECIMAL_FLOAT_RE = re.compile(r"[+-]?(?:\d+\.?\d*|\.\d+)(?:[eE][+-]?\d+)?\Z") -_FLOAT_SPEC = { # width (or "bf16") -> (exponent bits, fraction bits, exponent bias) - 16: (5, 10, 15), - 32: (8, 23, 127), - 64: (11, 52, 1023), - "bf16": (8, 7, 127), # OpTypeFloat 16 BFloat16KHR: the top half of an f32 -} -_BFLOAT16_KHR = VALUE_ENUMS["FPEncoding"]["BFloat16KHR"][0] - - -def _round_float(negative: bool, sig: int, exp: int, width, to_nearest: bool, tie_break=None): - """The bits of (-1)^negative * sig * 2^exp in the float format `width`, or None when that overflows to infinity. - - Rounds to nearest-even when `to_nearest`, otherwise toward zero; a value below the smallest subnormal becomes a - zero of the same sign. On an exact tie, `tie_break()` (when given) says whether the value the caller approximates - by sig * 2^exp lies above (> 0) or below (< 0) it, so a literal read through a wider format is rounded once. - """ - exp_bits, mant_bits, bias = _FLOAT_SPEC[width] - sign = int(negative) << (exp_bits + mant_bits) - if sig == 0: - return sign - # The weight of the last fraction bit: set by the exponent, or fixed in the subnormal range. - quantum = max(exp + sig.bit_length() - 1, 1 - bias) - mant_bits - shift = quantum - exp - if shift <= 0: - n = sig << -shift - else: - n = sig >> shift - if to_nearest: - rem, half = sig & ((1 << shift) - 1), 1 << (shift - 1) - if rem == half: - above = tie_break() if tie_break is not None else 0 - n += above > 0 or (above == 0 and n & 1) - elif rem > half: - n += 1 - # A subnormal n is its own encoding; a normal one carries its leading bit into the exponent field. - bits = ((quantum + mant_bits + bias - 1) << mant_bits) + n - if bits >= ((1 << exp_bits) - 1) << mant_bits: - return None - return sign | bits - - -def _parse_float_bits(tok: str, width, lineno: int) -> int: - """Encode a SPIR-V float literal (decimal or width-aware hex-float incl. Inf/NaN) as IEEE-754 bits. - - `width` is 16, 32 or 64, or "bf16" for a 16-bit float with the BFloat16KHR encoding. - """ - spec = _FLOAT_SPEC.get(width) - if spec is None: - raise SpirvAsmError(f"line {lineno}: unsupported float constant width {width}") - exp_bits, mant_bits, bias = spec - exp_max = (1 << exp_bits) - 1 - type_name = "bfloat16" if width == "bf16" else f"{width}-bit float" - m = _HEX_FLOAT_RE.match(tok) - if m: - sign_s, ipart, fpart, exp_s = m.groups() - fpart = fpart or "" - if not ipart and not fpart: - raise SpirvAsmError(f"line {lineno}: invalid float literal {tok!r}") - sign = 1 if sign_s == "-" else 0 - sig = int(ipart + fpart, 16) - if sig == 0: - return sign << (exp_bits + mant_bits) - exp = int(exp_s) - 4 * len(fpart) - top = sig.bit_length() - 1 - e_biased = exp + top + bias - if e_biased == exp_max: - # SPIRV-Tools hex-float spelling for Inf (0x1p+128) and NaN payloads (0x1.8p+128). - frac = sig & ((1 << top) - 1) - if top <= mant_bits: - mant = frac << (mant_bits - top) - else: - mant = frac >> (top - mant_bits) - return (sign << (exp_bits + mant_bits)) | (exp_max << mant_bits) | mant - # SPIRV-Tools (HexFloat's operator>>) drops the digits that do not fit: a hex-float is truncated toward - # zero, in the subnormal range too, and one too large for the type is an infinity. - bits = _round_float(bool(sign), sig, exp, width, False) - return (sign << (exp_bits + mant_bits)) | (exp_max << mant_bits) if bits is None else bits - # The decimal spelling the C++ stream reads: no inf, nan or digit separators, which float() would also take. - if not _DECIMAL_FLOAT_RE.match(tok): - raise SpirvAsmError(f"line {lineno}: invalid float literal {tok!r}") - fv = float(tok) - if math.isinf(fv): - raise SpirvAsmError(f"line {lineno}: float literal {tok} is out of range for a {type_name}") - if width == 64: - return struct.unpack(", and - # the same for BFloat16), so 1.0006 is 0x3C00, not the nearer 0x3C01. - sig, den = abs(struct.unpack(" int: - """1 when the decimal literal `tok` is larger in magnitude than the double `approx` read from it, -1 when smaller.""" - exact, near = abs(Fraction(tok)), Fraction(abs(approx)) - return (exact > near) - (exact < near) - - -def _encode_context_number(tok: str, type_info, lineno: int) -> list[int]: - if type_info is None: - raise SpirvAsmError(f"line {lineno}: OpConstant references unknown scalar type") - kind, width = type_info[0], type_info[1] - if kind == "int": - if width > 32 and width != 64: - raise SpirvAsmError(f"line {lineno}: unsupported integer constant width {width}") - val = _int_literal(tok, width, bool(type_info[2]), lineno) - return [val] if width <= 32 else [val & 0xFFFFFFFF, val >> 32] - if kind == "float": - bf16 = width == 16 and type_info[2] == _BFLOAT16_KHR - bits = _parse_float_bits(tok, "bf16" if bf16 else width, lineno) - if width <= 32: - return [bits & 0xFFFFFFFF] - if width == 64: - return [bits & 0xFFFFFFFF, (bits >> 32) & 0xFFFFFFFF] - raise SpirvAsmError(f"line {lineno}: unsupported float constant width {width}") - raise SpirvAsmError(f"line {lineno}: unsupported constant type {type_info!r}") - - -def assemble(text: str, target_env: str = "vulkan1.2") -> bytes: - """Assemble SPIR-V text into binary SPIR-V bytes for `target_env`.""" - version = TARGET_ENV_VERSION.get(target_env) - if version is None: - raise SpirvAsmError(f"unsupported target environment: {target_env!r}") - - # A successful line-by-line parse consists of complete instructions. Try this first - # for generated shaders, where the more expensive token grouping is rarely needed. - track_switch_types = "OpSwitch" in text - lines = ((lineno, _tokenize_line(raw, lineno)) for lineno, raw in _instruction_lines(text)) - try: - return _assemble(lines, version, track_switch_types) - except SpirvAsmError: - pass - return _assemble(_instruction_tokens(text), version, track_switch_types) - - -def _assemble(instructions, version: int, track_switch_types: bool) -> bytes: - sym_to_id: dict[str, int] = {} - next_id = 1 - defined_types: set[str] = set() - type_info: dict[int, tuple] = {} # type_id -> ('int', width, signedness) | ('float', width, encoding) - id_to_type: dict[int, int] = {} # result_id -> result_type_id - ext_imports: dict[int, dict[str, int]] = {} # ext_set_id -> {name: opcode} - - def get_id(tok: str, lineno: int) -> int: - nonlocal next_id - if not tok or tok[0] != "%": - raise SpirvAsmError(f"line {lineno}: expected %id, got {tok!r}") - vid = sym_to_id.get(tok) - if vid is None: - if not _ID_RE.fullmatch(tok): - raise SpirvAsmError(f"line {lineno}: invalid ID {tok!r}") - vid = next_id - next_id += 1 - sym_to_id[tok] = vid - return vid - - words = array.array("I", [SPIRV_MAGIC, version, 0, 0, 0]) - - def encode_operand(kind: str, toks: list[str], idx: int, lineno: int, - res_type_id: int | None, cur_ext_table: dict[str, int] | None, - switch_type: tuple | None, out: list[int]) -> int: - if kind in _ID_KINDS: - out.append(get_id(toks[idx], lineno)) - return idx + 1 - if kind == "LiteralInteger": - out.append(_u32_literal(toks[idx], lineno)) - return idx + 1 - if kind == "LiteralFloat": - out.append(_parse_float_bits(toks[idx], 32, lineno)) - return idx + 1 - if kind == "LiteralString": - out.extend(_encode_string_words(_unquote_string(toks[idx], lineno))) - return idx + 1 - if kind == "LiteralContextDependentNumber": - out.extend(_encode_context_number(toks[idx], type_info.get(res_type_id), lineno)) - return idx + 1 - if kind == "LiteralExtInstInteger": - tok = toks[idx] - if cur_ext_table is not None and tok in cur_ext_table: - out.append(cur_ext_table[tok]) - else: - out.append(_u32_literal(tok, lineno)) - return idx + 1 - if kind == "PairLiteralIntegerIdRef": - tok = toks[idx] - if switch_type is not None: - width, signed = switch_type - else: - # Selector of unknown type: one word, read as signed only when the literal is negative. - width, signed = 32, tok.startswith("-") - val = _int_literal(tok, width, signed, lineno) - if width == 64: - out.append(val & 0xFFFFFFFF) - out.append(val >> 32) - else: - out.append(val) - if idx + 1 >= len(toks): - raise SpirvAsmError(f"line {lineno}: missing label in {kind}") - out.append(get_id(toks[idx + 1], lineno)) - return idx + 2 - if kind == "PairIdRefIdRef": - if idx + 1 >= len(toks): - raise SpirvAsmError(f"line {lineno}: missing second id in {kind}") - out.append(get_id(toks[idx], lineno)) - out.append(get_id(toks[idx + 1], lineno)) - return idx + 2 - if kind == "PairIdRefLiteralInteger": - if idx + 1 >= len(toks): - raise SpirvAsmError(f"line {lineno}: missing literal in {kind}") - out.append(get_id(toks[idx], lineno)) - out.append(_u32_literal(toks[idx + 1], lineno)) - return idx + 2 - if kind == "LiteralSpecConstantOpInteger": - opname = toks[idx] - sub = INSTRUCTIONS.get(opname) or INSTRUCTIONS.get("Op" + opname) - if sub is None: - raise SpirvAsmError(f"line {lineno}: unknown OpSpecConstantOp opcode {opname!r}") - out.append(sub[0]) - idx += 1 - # Encode remaining operands of the nested opcode - for sk, sq in sub[3]: - if sq == "*": - while idx < len(toks): - idx = encode_operand(sk, toks, idx, lineno, res_type_id, cur_ext_table, switch_type, out) - elif sq == "?": - if idx < len(toks): - idx = encode_operand(sk, toks, idx, lineno, res_type_id, cur_ext_table, switch_type, out) - else: - if idx >= len(toks): - raise SpirvAsmError(f"line {lineno}: missing operand {sk} for {opname}") - idx = encode_operand(sk, toks, idx, lineno, res_type_id, cur_ext_table, switch_type, out) - return idx - - venum = VALUE_ENUMS.get(kind) - if venum is not None: - tok = toks[idx] - entry = venum.get(tok) - if entry is None: - # Allow raw numeric value fallback (e.g. hex enum value) - if tok[:1].isdigit() or tok.startswith(("0x", "0X")): - out.append(_u32_literal(tok, lineno)) - return idx + 1 - raise SpirvAsmError(f"line {lineno}: unknown {kind} value {tok!r}") - val, params = entry - out.append(val) - idx += 1 - for pk in params: - if idx >= len(toks): - raise SpirvAsmError(f"line {lineno}: missing parameter {pk} for {kind}.{tok}") - idx = encode_operand(pk, toks, idx, lineno, res_type_id, cur_ext_table, switch_type, out) - return idx - - benum = BIT_ENUMS.get(kind) - if benum is not None: - tok = toks[idx] - mask = 0 - flag_params: list[tuple[int, tuple[str, ...]]] = [] - for part in tok.split("|"): - entry = benum.get(part) - if entry is None: - if part[:1].isdigit() or part.startswith(("0x", "0X")): - mask |= _u32_literal(part, lineno) - continue - raise SpirvAsmError(f"line {lineno}: unknown {kind} flag {part!r} in {tok!r}") - bval, params = entry - mask |= bval - if params: - flag_params.append((bval, params)) - out.append(mask) - idx += 1 - # SPIR-V spec: bit-mask extra parameters appear in ascending bit-value order. - flag_params.sort(key=lambda pair: pair[0]) - for _, params in flag_params: - for pk in params: - if idx >= len(toks): - raise SpirvAsmError(f"line {lineno}: missing parameter {pk} for {kind} {tok!r}") - idx = encode_operand(pk, toks, idx, lineno, res_type_id, cur_ext_table, switch_type, out) - return idx - - raise SpirvAsmError(f"line {lineno}: unsupported operand kind {kind!r}") - - for lineno, toks in instructions: - if not toks: - continue - res_tok = None - if len(toks) >= 3 and toks[1] == "=": - res_tok = toks[0] - opname = toks[2] - arg_idx = 3 - else: - opname = toks[0] - arg_idx = 1 - - if res_tok is not None and opname in _TYPE_DEFINITIONS: - if res_tok in defined_types: - raise SpirvAsmError(f"line {lineno}: type ID {res_tok} is already defined") - defined_types.add(res_tok) - - fast = _PURE_ID_INSNS.get(opname) - if fast is not None: - opcode, has_rt, has_res, min_args, has_var = fast - if has_res != (res_tok is not None): - raise SpirvAsmError( - f"line {lineno}: {opname} " - + ("requires '%id =' result" if has_res else "does not produce a result id")) - n_rem = len(toks) - arg_idx - (1 if has_rt else 0) - if n_rem < min_args or (not has_var and n_rem != min_args): - raise SpirvAsmError(f"line {lineno}: {opname} operand count mismatch (got {n_rem})") - out = [] - if has_rt: - rt_id = get_id(toks[arg_idx], lineno) - out.append(rt_id) - arg_idx += 1 - else: - rt_id = None - if has_res: - rid = get_id(res_tok, lineno) - out.append(rid) - if track_switch_types and rt_id is not None: - id_to_type[rid] = rt_id - for k in range(arg_idx, len(toks)): - out.append(get_id(toks[k], lineno)) - word_count = 1 + len(out) - if word_count > 0xFFFF: - raise SpirvAsmError(f"line {lineno}: {opname} word count {word_count} exceeds 65535") - words.append((word_count << 16) | opcode) - words.extend(out) - continue - - spec = INSTRUCTIONS.get(opname) - if spec is None: - raise SpirvAsmError(f"line {lineno}: unknown opcode {opname!r}") - opcode, has_rt, has_res, op_specs = spec - - out: list[int] = [] - res_type_id = None - res_id = None - - if has_rt: - if arg_idx >= len(toks): - raise SpirvAsmError(f"line {lineno}: {opname} missing result type") - res_type_id = get_id(toks[arg_idx], lineno) - out.append(res_type_id) - arg_idx += 1 - - if has_res: - if res_tok is None: - raise SpirvAsmError(f"line {lineno}: {opname} requires '%id =' result") - res_id = get_id(res_tok, lineno) - out.append(res_id) - if track_switch_types and res_type_id is not None: - id_to_type[res_id] = res_type_id - elif res_tok is not None: - raise SpirvAsmError(f"line {lineno}: {opname} does not produce a result id") - - # Track scalar type widths for OpConstant / OpSwitch, and ExtInstImport sets. - if opname == "OpTypeInt" and res_id is not None and arg_idx + 1 < len(toks): - type_info[res_id] = ("int", _parse_int(toks[arg_idx], lineno), _parse_int(toks[arg_idx + 1], lineno)) - elif opname == "OpTypeFloat" and res_id is not None and arg_idx < len(toks): - # The optional FPEncoding operand (BFloat16KHR) changes how a 16-bit constant is laid out. - encoding = None - if arg_idx + 1 < len(toks): - enc_tok = toks[arg_idx + 1] - entry = VALUE_ENUMS["FPEncoding"].get(enc_tok) - encoding = entry[0] if entry is not None else _u32_literal(enc_tok, lineno) - type_info[res_id] = ("float", _parse_int(toks[arg_idx], lineno), encoding) - elif opname == "OpExtInstImport" and res_id is not None and arg_idx < len(toks): - ext_name = _unquote_string(toks[arg_idx], lineno) - if ext_name in _EXT_SETS: - ext_imports[res_id] = _EXT_SETS[ext_name] - - cur_ext_table = None - switch_type = None # (width, signed) of the OpSwitch selector's integer type - if opname == "OpExtInst" and arg_idx < len(toks): - cur_ext_table = ext_imports.get(get_id(toks[arg_idx], lineno)) - elif opname == "OpSwitch" and arg_idx < len(toks): - sel_id = get_id(toks[arg_idx], lineno) - if sel_id not in id_to_type: - # The single top-down pass has not seen a typed definition of the selector. The case literals' width - # comes from that type, so guessing 32 bits would emit a 64-bit selector's literals as one word each. - # spirv-as refuses this too, and spirv-val refuses a module whose selector block comes after the switch. - raise SpirvAsmError( - f"line {lineno}: OpSwitch selector {toks[arg_idx]} has no known type: it must be defined before " - "the OpSwitch (blocks are laid out in dominance order)") - sel_ti = type_info.get(id_to_type[sel_id]) - if sel_ti and sel_ti[0] == "int" and (sel_ti[1] <= 32 or sel_ti[1] == 64): - switch_type = (sel_ti[1], bool(sel_ti[2])) - - for kind, quant in op_specs: - if quant == "*": - while arg_idx < len(toks): - arg_idx = encode_operand(kind, toks, arg_idx, lineno, res_type_id, cur_ext_table, switch_type, out) - elif quant == "?": - if arg_idx < len(toks): - arg_idx = encode_operand(kind, toks, arg_idx, lineno, res_type_id, cur_ext_table, switch_type, out) - else: - if arg_idx >= len(toks): - raise SpirvAsmError(f"line {lineno}: {opname} missing operand ({kind})") - arg_idx = encode_operand(kind, toks, arg_idx, lineno, res_type_id, cur_ext_table, switch_type, out) - - if arg_idx != len(toks): - raise SpirvAsmError(f"line {lineno}: {opname} unexpected trailing tokens {toks[arg_idx:]!r}") - - word_count = 1 + len(out) - if word_count > 0xFFFF: - raise SpirvAsmError(f"line {lineno}: {opname} word count {word_count} exceeds 65535") - words.append((word_count << 16) | opcode) - words.extend(out) - - words[3] = next_id - if sys.byteorder != "little": - words.byteswap() - return words.tobytes() - - -def main(argv=None) -> int: - ap = argparse.ArgumentParser(description="Pure-Python SPIR-V binary assembler (no spirv-as required).") - ap.add_argument("src", help="input .spvasm file") - ap.add_argument("-o", "--out", required=True, help="output .spv binary file") - ap.add_argument("--target-env", default="vulkan1.2", choices=sorted(TARGET_ENV_VERSION), - help="target SPIR-V / Vulkan environment (default: vulkan1.2)") - args = ap.parse_args(argv) - try: - with open(args.src, encoding="utf-8", newline="") as f: - text = f.read() - data = assemble(text, target_env=args.target_env) - with open(args.out, "wb") as f: - f.write(data) - except (OSError, ValueError, SpirvAsmError) as exc: # ValueError: a source file that is not UTF-8 - print(f"ERROR: {args.src}: {exc}" if isinstance(exc, UnicodeDecodeError) else f"ERROR: {exc}", file=sys.stderr) - return 1 - return 0 - - -if __name__ == "__main__": - try: # a redirected stdout is strict ANSI code page under -I; write '?' for what it cannot encode - sys.stdout.reconfigure(errors="replace") - except (AttributeError, ValueError, OSError): - pass - sys.exit(main()) diff --git a/tools/spirv_asm_tables.py b/tools/spirv_asm_tables.py deleted file mode 100644 index a58311c14..000000000 --- a/tools/spirv_asm_tables.py +++ /dev/null @@ -1,1113 +0,0 @@ -"""SPIR-V core, GLSL.std.450 and NonSemantic.DebugPrintf grammar tables for tools/spirv_asm.py. - -Derived from Khronos Group SPIRV-Headers (MIT License): - spirv.core.grammar.json, extinst.glsl.std.450.grammar.json and - extinst.nonsemantic.debugprintf.grammar.json (unified1). -Grammar aliases have the entry of the name they stand for: instruction aliases such as -OpDemoteToHelperInvocationEXT in INSTRUCTIONS, enumerant aliases in VALUE_ENUMS and BIT_ENUMS. -spirv-as accepts either spelling. -""" - -INSTRUCTIONS = { - 'OpAbortKHR': (5121, False, False, (('IdRef', ''), ('IdRef', ''))), - 'OpAbsISubINTEL': (5587, True, True, (('IdRef', ''), ('IdRef', ''))), - 'OpAbsUSubINTEL': (5588, True, True, (('IdRef', ''), ('IdRef', ''))), - 'OpAccessChain': (65, True, True, (('IdRef', ''), ('IdRef', '*'))), - 'OpAliasDomainDeclINTEL': (5911, False, True, ()), - 'OpAliasScopeDeclINTEL': (5912, False, True, (('IdRef', ''),)), - 'OpAliasScopeListDeclINTEL': (5913, False, True, (('IdRef', '*'),)), - 'OpAll': (155, True, True, (('IdRef', ''),)), - 'OpAllocateNodePayloadsAMDX': (5074, True, True, (('IdScope', ''), ('IdRef', ''), ('IdRef', ''))), - 'OpAny': (154, True, True, (('IdRef', ''),)), - 'OpArbitraryFloatACosINTEL': (5875, True, True, (('IdRef', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''))), - 'OpArbitraryFloatACosPiINTEL': (5876, True, True, (('IdRef', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''))), - 'OpArbitraryFloatASinINTEL': (5873, True, True, (('IdRef', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''))), - 'OpArbitraryFloatASinPiINTEL': (5874, True, True, (('IdRef', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''))), - 'OpArbitraryFloatATan2INTEL': (5879, True, True, (('IdRef', ''), ('LiteralInteger', ''), ('IdRef', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''))), - 'OpArbitraryFloatATanINTEL': (5877, True, True, (('IdRef', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''))), - 'OpArbitraryFloatATanPiINTEL': (5878, True, True, (('IdRef', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''))), - 'OpArbitraryFloatAddALTERA': (5846, True, True, (('IdRef', ''), ('LiteralInteger', ''), ('IdRef', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''))), - 'OpArbitraryFloatAddINTEL': (5846, True, True, (('IdRef', ''), ('LiteralInteger', ''), ('IdRef', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''))), - 'OpArbitraryFloatCastALTERA': (5841, True, True, (('IdRef', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''))), - 'OpArbitraryFloatCastFromIntALTERA': (5842, True, True, (('IdRef', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''))), - 'OpArbitraryFloatCastFromIntINTEL': (5842, True, True, (('IdRef', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''))), - 'OpArbitraryFloatCastINTEL': (5841, True, True, (('IdRef', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''))), - 'OpArbitraryFloatCastToIntALTERA': (5843, True, True, (('IdRef', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''))), - 'OpArbitraryFloatCastToIntINTEL': (5843, True, True, (('IdRef', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''))), - 'OpArbitraryFloatCbrtALTERA': (5857, True, True, (('IdRef', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''))), - 'OpArbitraryFloatCbrtINTEL': (5857, True, True, (('IdRef', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''))), - 'OpArbitraryFloatCosINTEL': (5869, True, True, (('IdRef', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''))), - 'OpArbitraryFloatCosPiINTEL': (5872, True, True, (('IdRef', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''))), - 'OpArbitraryFloatDivALTERA': (5849, True, True, (('IdRef', ''), ('LiteralInteger', ''), ('IdRef', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''))), - 'OpArbitraryFloatDivINTEL': (5849, True, True, (('IdRef', ''), ('LiteralInteger', ''), ('IdRef', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''))), - 'OpArbitraryFloatEQALTERA': (5854, True, True, (('IdRef', ''), ('LiteralInteger', ''), ('IdRef', ''), ('LiteralInteger', ''))), - 'OpArbitraryFloatEQINTEL': (5854, True, True, (('IdRef', ''), ('LiteralInteger', ''), ('IdRef', ''), ('LiteralInteger', ''))), - 'OpArbitraryFloatExp10INTEL': (5866, True, True, (('IdRef', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''))), - 'OpArbitraryFloatExp2INTEL': (5865, True, True, (('IdRef', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''))), - 'OpArbitraryFloatExpINTEL': (5864, True, True, (('IdRef', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''))), - 'OpArbitraryFloatExpm1INTEL': (5867, True, True, (('IdRef', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''))), - 'OpArbitraryFloatGEALTERA': (5851, True, True, (('IdRef', ''), ('LiteralInteger', ''), ('IdRef', ''), ('LiteralInteger', ''))), - 'OpArbitraryFloatGEINTEL': (5851, True, True, (('IdRef', ''), ('LiteralInteger', ''), ('IdRef', ''), ('LiteralInteger', ''))), - 'OpArbitraryFloatGTALTERA': (5850, True, True, (('IdRef', ''), ('LiteralInteger', ''), ('IdRef', ''), ('LiteralInteger', ''))), - 'OpArbitraryFloatGTINTEL': (5850, True, True, (('IdRef', ''), ('LiteralInteger', ''), ('IdRef', ''), ('LiteralInteger', ''))), - 'OpArbitraryFloatHypotALTERA': (5858, True, True, (('IdRef', ''), ('LiteralInteger', ''), ('IdRef', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''))), - 'OpArbitraryFloatHypotINTEL': (5858, True, True, (('IdRef', ''), ('LiteralInteger', ''), ('IdRef', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''))), - 'OpArbitraryFloatLEALTERA': (5853, True, True, (('IdRef', ''), ('LiteralInteger', ''), ('IdRef', ''), ('LiteralInteger', ''))), - 'OpArbitraryFloatLEINTEL': (5853, True, True, (('IdRef', ''), ('LiteralInteger', ''), ('IdRef', ''), ('LiteralInteger', ''))), - 'OpArbitraryFloatLTALTERA': (5852, True, True, (('IdRef', ''), ('LiteralInteger', ''), ('IdRef', ''), ('LiteralInteger', ''))), - 'OpArbitraryFloatLTINTEL': (5852, True, True, (('IdRef', ''), ('LiteralInteger', ''), ('IdRef', ''), ('LiteralInteger', ''))), - 'OpArbitraryFloatLog10INTEL': (5862, True, True, (('IdRef', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''))), - 'OpArbitraryFloatLog1pINTEL': (5863, True, True, (('IdRef', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''))), - 'OpArbitraryFloatLog2INTEL': (5861, True, True, (('IdRef', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''))), - 'OpArbitraryFloatLogINTEL': (5860, True, True, (('IdRef', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''))), - 'OpArbitraryFloatMulALTERA': (5848, True, True, (('IdRef', ''), ('LiteralInteger', ''), ('IdRef', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''))), - 'OpArbitraryFloatMulINTEL': (5848, True, True, (('IdRef', ''), ('LiteralInteger', ''), ('IdRef', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''))), - 'OpArbitraryFloatPowINTEL': (5880, True, True, (('IdRef', ''), ('LiteralInteger', ''), ('IdRef', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''))), - 'OpArbitraryFloatPowNINTEL': (5882, True, True, (('IdRef', ''), ('LiteralInteger', ''), ('IdRef', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''))), - 'OpArbitraryFloatPowRINTEL': (5881, True, True, (('IdRef', ''), ('LiteralInteger', ''), ('IdRef', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''))), - 'OpArbitraryFloatRSqrtALTERA': (5856, True, True, (('IdRef', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''))), - 'OpArbitraryFloatRSqrtINTEL': (5856, True, True, (('IdRef', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''))), - 'OpArbitraryFloatRecipALTERA': (5855, True, True, (('IdRef', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''))), - 'OpArbitraryFloatRecipINTEL': (5855, True, True, (('IdRef', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''))), - 'OpArbitraryFloatSinCosINTEL': (5870, True, True, (('IdRef', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''))), - 'OpArbitraryFloatSinCosPiALTERA': (5840, True, True, (('IdRef', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''))), - 'OpArbitraryFloatSinCosPiINTEL': (5840, True, True, (('IdRef', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''))), - 'OpArbitraryFloatSinINTEL': (5868, True, True, (('IdRef', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''))), - 'OpArbitraryFloatSinPiINTEL': (5871, True, True, (('IdRef', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''))), - 'OpArbitraryFloatSqrtALTERA': (5859, True, True, (('IdRef', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''))), - 'OpArbitraryFloatSqrtINTEL': (5859, True, True, (('IdRef', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''))), - 'OpArbitraryFloatSubALTERA': (5847, True, True, (('IdRef', ''), ('LiteralInteger', ''), ('IdRef', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''))), - 'OpArbitraryFloatSubINTEL': (5847, True, True, (('IdRef', ''), ('LiteralInteger', ''), ('IdRef', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''))), - 'OpArithmeticFenceEXT': (6145, True, True, (('IdRef', ''),)), - 'OpArrayLength': (68, True, True, (('IdRef', ''), ('LiteralInteger', ''))), - 'OpAsmCallINTEL': (5611, True, True, (('IdRef', ''), ('IdRef', '*'))), - 'OpAsmINTEL': (5610, True, True, (('IdRef', ''), ('IdRef', ''), ('LiteralString', ''), ('LiteralString', ''))), - 'OpAsmTargetINTEL': (5609, False, True, (('LiteralString', ''),)), - 'OpAssumeTrueKHR': (5630, False, False, (('IdRef', ''),)), - 'OpAtomicAnd': (240, True, True, (('IdRef', ''), ('IdScope', ''), ('IdMemorySemantics', ''), ('IdRef', ''))), - 'OpAtomicCompareExchange': (230, True, True, (('IdRef', ''), ('IdScope', ''), ('IdMemorySemantics', ''), ('IdMemorySemantics', ''), ('IdRef', ''), ('IdRef', ''))), - 'OpAtomicCompareExchangeWeak': (231, True, True, (('IdRef', ''), ('IdScope', ''), ('IdMemorySemantics', ''), ('IdMemorySemantics', ''), ('IdRef', ''), ('IdRef', ''))), - 'OpAtomicExchange': (229, True, True, (('IdRef', ''), ('IdScope', ''), ('IdMemorySemantics', ''), ('IdRef', ''))), - 'OpAtomicFAddEXT': (6035, True, True, (('IdRef', ''), ('IdScope', ''), ('IdMemorySemantics', ''), ('IdRef', ''))), - 'OpAtomicFMaxEXT': (5615, True, True, (('IdRef', ''), ('IdScope', ''), ('IdMemorySemantics', ''), ('IdRef', ''))), - 'OpAtomicFMinEXT': (5614, True, True, (('IdRef', ''), ('IdScope', ''), ('IdMemorySemantics', ''), ('IdRef', ''))), - 'OpAtomicFlagClear': (319, False, False, (('IdRef', ''), ('IdScope', ''), ('IdMemorySemantics', ''))), - 'OpAtomicFlagTestAndSet': (318, True, True, (('IdRef', ''), ('IdScope', ''), ('IdMemorySemantics', ''))), - 'OpAtomicIAdd': (234, True, True, (('IdRef', ''), ('IdScope', ''), ('IdMemorySemantics', ''), ('IdRef', ''))), - 'OpAtomicIDecrement': (233, True, True, (('IdRef', ''), ('IdScope', ''), ('IdMemorySemantics', ''))), - 'OpAtomicIIncrement': (232, True, True, (('IdRef', ''), ('IdScope', ''), ('IdMemorySemantics', ''))), - 'OpAtomicISub': (235, True, True, (('IdRef', ''), ('IdScope', ''), ('IdMemorySemantics', ''), ('IdRef', ''))), - 'OpAtomicLoad': (227, True, True, (('IdRef', ''), ('IdScope', ''), ('IdMemorySemantics', ''))), - 'OpAtomicOr': (241, True, True, (('IdRef', ''), ('IdScope', ''), ('IdMemorySemantics', ''), ('IdRef', ''))), - 'OpAtomicSMax': (238, True, True, (('IdRef', ''), ('IdScope', ''), ('IdMemorySemantics', ''), ('IdRef', ''))), - 'OpAtomicSMin': (236, True, True, (('IdRef', ''), ('IdScope', ''), ('IdMemorySemantics', ''), ('IdRef', ''))), - 'OpAtomicStore': (228, False, False, (('IdRef', ''), ('IdScope', ''), ('IdMemorySemantics', ''), ('IdRef', ''))), - 'OpAtomicUMax': (239, True, True, (('IdRef', ''), ('IdScope', ''), ('IdMemorySemantics', ''), ('IdRef', ''))), - 'OpAtomicUMin': (237, True, True, (('IdRef', ''), ('IdScope', ''), ('IdMemorySemantics', ''), ('IdRef', ''))), - 'OpAtomicXor': (242, True, True, (('IdRef', ''), ('IdScope', ''), ('IdMemorySemantics', ''), ('IdRef', ''))), - 'OpBFloat16MulAddQCOM': (4505, True, True, (('IdRef', ''), ('IdRef', ''), ('IdRef', ''))), - 'OpBeginInvocationInterlockEXT': (5364, False, False, ()), - 'OpBitCastArrayQCOM': (4497, True, True, (('IdRef', ''),)), - 'OpBitCount': (205, True, True, (('IdRef', ''),)), - 'OpBitFieldInsert': (201, True, True, (('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''))), - 'OpBitFieldSExtract': (202, True, True, (('IdRef', ''), ('IdRef', ''), ('IdRef', ''))), - 'OpBitFieldUExtract': (203, True, True, (('IdRef', ''), ('IdRef', ''), ('IdRef', ''))), - 'OpBitReverse': (204, True, True, (('IdRef', ''),)), - 'OpBitcast': (124, True, True, (('IdRef', ''),)), - 'OpBitcastExtractEXT': (4195, True, True, (('IdRef', ''), ('IdRef', ''))), - 'OpBitwiseAnd': (199, True, True, (('IdRef', ''), ('IdRef', ''))), - 'OpBitwiseFunctionINTEL': (6242, True, True, (('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''))), - 'OpBitwiseOr': (197, True, True, (('IdRef', ''), ('IdRef', ''))), - 'OpBitwiseXor': (198, True, True, (('IdRef', ''), ('IdRef', ''))), - 'OpBranch': (249, False, False, (('IdRef', ''),)), - 'OpBranchConditional': (250, False, False, (('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('LiteralInteger', '*'))), - 'OpBufferPointerEXT': (5119, True, True, (('IdRef', ''),)), - 'OpBuildNDRange': (304, True, True, (('IdRef', ''), ('IdRef', ''), ('IdRef', ''))), - 'OpCapability': (17, False, False, (('Capability', ''),)), - 'OpCaptureEventProfilingInfo': (302, False, False, (('IdRef', ''), ('IdRef', ''), ('IdRef', ''))), - 'OpClampConvertFToSINTEL': (6424, True, True, (('IdRef', ''),)), - 'OpClampStochasticRoundFToSINTEL': (6219, True, True, (('IdRef', ''), ('IdRef', ''), ('IdRef', '?'))), - 'OpColorAttachmentReadEXT': (4160, True, True, (('IdRef', ''), ('IdRef', '?'))), - 'OpCommitReadPipe': (280, False, False, (('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''))), - 'OpCommitWritePipe': (281, False, False, (('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''))), - 'OpCompositeConstruct': (80, True, True, (('IdRef', '*'),)), - 'OpCompositeConstructContinuedINTEL': (6096, False, False, (('IdRef', '*'),)), - 'OpCompositeConstructCoopMatQCOM': (4540, True, True, (('IdRef', ''),)), - 'OpCompositeConstructReplicateEXT': (4463, True, True, (('IdRef', ''),)), - 'OpCompositeExtract': (81, True, True, (('IdRef', ''), ('LiteralInteger', '*'))), - 'OpCompositeExtractCoopMatQCOM': (4541, True, True, (('IdRef', ''),)), - 'OpCompositeInsert': (82, True, True, (('IdRef', ''), ('IdRef', ''), ('LiteralInteger', '*'))), - 'OpConditionalCapabilityINTEL': (6250, False, False, (('IdRef', ''), ('Capability', ''))), - 'OpConditionalCopyObjectINTEL': (6254, True, True, (('IdRef', '*'),)), - 'OpConditionalEntryPointINTEL': (6249, False, False, (('IdRef', ''), ('ExecutionModel', ''), ('IdRef', ''), ('LiteralString', ''), ('IdRef', '*'))), - 'OpConditionalExtensionINTEL': (6248, False, False, (('IdRef', ''), ('LiteralString', ''))), - 'OpConstant': (43, True, True, (('LiteralContextDependentNumber', ''),)), - 'OpConstantComposite': (44, True, True, (('IdRef', '*'),)), - 'OpConstantCompositeContinuedINTEL': (6091, False, False, (('IdRef', '*'),)), - 'OpConstantCompositeReplicateEXT': (4461, True, True, (('IdRef', ''),)), - 'OpConstantDataKHR': (5147, True, True, (('LiteralInteger', '*'),)), - 'OpConstantFalse': (42, True, True, ()), - 'OpConstantFunctionPointerINTEL': (5600, True, True, (('IdRef', ''),)), - 'OpConstantNull': (46, True, True, ()), - 'OpConstantPipeStorage': (323, True, True, (('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''))), - 'OpConstantSampler': (45, True, True, (('SamplerAddressingMode', ''), ('LiteralInteger', ''), ('SamplerFilterMode', ''))), - 'OpConstantSizeOfEXT': (5129, True, True, (('IdRef', ''),)), - 'OpConstantStringAMDX': (5103, False, True, (('LiteralString', ''),)), - 'OpConstantTrue': (41, True, True, ()), - 'OpControlBarrier': (224, False, False, (('IdScope', ''), ('IdScope', ''), ('IdMemorySemantics', ''))), - 'OpControlBarrierArriveEXT': (6142, False, False, (('IdScope', ''), ('IdScope', ''), ('IdMemorySemantics', ''))), - 'OpControlBarrierArriveINTEL': (6142, False, False, (('IdScope', ''), ('IdScope', ''), ('IdMemorySemantics', ''))), - 'OpControlBarrierWaitEXT': (6143, False, False, (('IdScope', ''), ('IdScope', ''), ('IdMemorySemantics', ''))), - 'OpControlBarrierWaitINTEL': (6143, False, False, (('IdScope', ''), ('IdScope', ''), ('IdMemorySemantics', ''))), - 'OpConvertBF16ToFINTEL': (6117, True, True, (('IdRef', ''),)), - 'OpConvertFToBF16INTEL': (6116, True, True, (('IdRef', ''),)), - 'OpConvertFToS': (110, True, True, (('IdRef', ''),)), - 'OpConvertFToU': (109, True, True, (('IdRef', ''),)), - 'OpConvertHandleToImageINTEL': (6529, True, True, (('IdRef', ''),)), - 'OpConvertHandleToSampledImageINTEL': (6531, True, True, (('IdRef', ''),)), - 'OpConvertHandleToSamplerINTEL': (6530, True, True, (('IdRef', ''),)), - 'OpConvertImageToUNV': (5393, True, True, (('IdRef', ''),)), - 'OpConvertPtrToU': (117, True, True, (('IdRef', ''),)), - 'OpConvertSToF': (111, True, True, (('IdRef', ''),)), - 'OpConvertSampledImageToUNV': (5396, True, True, (('IdRef', ''),)), - 'OpConvertSamplerToUNV': (5394, True, True, (('IdRef', ''),)), - 'OpConvertUToAccelerationStructureKHR': (4447, True, True, (('IdRef', ''),)), - 'OpConvertUToF': (112, True, True, (('IdRef', ''),)), - 'OpConvertUToImageNV': (5391, True, True, (('IdRef', ''),)), - 'OpConvertUToPtr': (120, True, True, (('IdRef', ''),)), - 'OpConvertUToSampledImageNV': (5395, True, True, (('IdRef', ''),)), - 'OpConvertUToSamplerNV': (5392, True, True, (('IdRef', ''),)), - 'OpCooperativeMatrixConvertNV': (5293, True, True, (('IdRef', ''),)), - 'OpCooperativeMatrixConvertUseEXT': (5293, True, True, (('IdRef', ''),)), - 'OpCooperativeMatrixGetCoordinateEXT': (5363, True, True, (('IdRef', ''), ('IdRef', ''))), - 'OpCooperativeMatrixLengthKHR': (4460, True, True, (('IdRef', ''),)), - 'OpCooperativeMatrixLengthNV': (5362, True, True, (('IdRef', ''),)), - 'OpCooperativeMatrixLoadKHR': (4457, True, True, (('IdRef', ''), ('IdRef', ''), ('IdRef', '?'), ('MemoryAccess', '?'))), - 'OpCooperativeMatrixLoadNV': (5359, True, True, (('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('MemoryAccess', '?'))), - 'OpCooperativeMatrixLoadTensorNV': (5367, True, True, (('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('MemoryAccess', ''), ('TensorAddressingOperands', ''))), - 'OpCooperativeMatrixMulAddKHR': (4459, True, True, (('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('CooperativeMatrixOperands', '?'))), - 'OpCooperativeMatrixMulAddNV': (5361, True, True, (('IdRef', ''), ('IdRef', ''), ('IdRef', ''))), - 'OpCooperativeMatrixPerElementOpEXT': (5369, True, True, (('IdRef', ''), ('IdRef', ''), ('IdRef', '*'))), - 'OpCooperativeMatrixPerElementOpNV': (5369, True, True, (('IdRef', ''), ('IdRef', ''), ('IdRef', '*'))), - 'OpCooperativeMatrixReduceEXT': (5366, True, True, (('IdRef', ''), ('CooperativeMatrixReduce', ''), ('IdRef', ''))), - 'OpCooperativeMatrixReduceNV': (5366, True, True, (('IdRef', ''), ('CooperativeMatrixReduce', ''), ('IdRef', ''))), - 'OpCooperativeMatrixStoreKHR': (4458, False, False, (('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', '?'), ('MemoryAccess', '?'))), - 'OpCooperativeMatrixStoreNV': (5360, False, False, (('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('MemoryAccess', '?'))), - 'OpCooperativeMatrixStoreTensorNV': (5368, False, False, (('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('MemoryAccess', ''), ('TensorAddressingOperands', ''))), - 'OpCooperativeMatrixTransposeNV': (5390, True, True, (('IdRef', ''),)), - 'OpCooperativeVectorLoadNV': (5302, True, True, (('IdRef', ''), ('IdRef', ''), ('MemoryAccess', '?'))), - 'OpCooperativeVectorMatrixMulAddNV': (5292, True, True, (('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', '?'), ('CooperativeMatrixOperands', '?'))), - 'OpCooperativeVectorMatrixMulNV': (5289, True, True, (('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', '?'), ('CooperativeMatrixOperands', '?'))), - 'OpCooperativeVectorOuterProductAccumulateNV': (5290, False, False, (('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', '?'))), - 'OpCooperativeVectorReduceSumAccumulateNV': (5291, False, False, (('IdRef', ''), ('IdRef', ''), ('IdRef', ''))), - 'OpCooperativeVectorStoreNV': (5303, False, False, (('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('MemoryAccess', '?'))), - 'OpCopyLogical': (400, True, True, (('IdRef', ''),)), - 'OpCopyMemory': (63, False, False, (('IdRef', ''), ('IdRef', ''), ('MemoryAccess', '?'), ('MemoryAccess', '?'))), - 'OpCopyMemorySized': (64, False, False, (('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('MemoryAccess', '?'), ('MemoryAccess', '?'))), - 'OpCopyObject': (83, True, True, (('IdRef', ''),)), - 'OpCreatePipeFromPipeStorage': (324, True, True, (('IdRef', ''),)), - 'OpCreateTensorLayoutNV': (5372, True, True, ()), - 'OpCreateTensorViewNV': (5377, True, True, ()), - 'OpCreateUserEvent': (299, True, True, ()), - 'OpCrossWorkgroupCastToPtrALTERA': (5938, True, True, (('IdRef', ''),)), - 'OpCrossWorkgroupCastToPtrINTEL': (5938, True, True, (('IdRef', ''),)), - 'OpDPdx': (207, True, True, (('IdRef', ''),)), - 'OpDPdxCoarse': (213, True, True, (('IdRef', ''),)), - 'OpDPdxFine': (210, True, True, (('IdRef', ''),)), - 'OpDPdy': (208, True, True, (('IdRef', ''),)), - 'OpDPdyCoarse': (214, True, True, (('IdRef', ''),)), - 'OpDPdyFine': (211, True, True, (('IdRef', ''),)), - 'OpDecorate': (71, False, False, (('IdRef', ''), ('Decoration', ''))), - 'OpDecorateId': (332, False, False, (('IdRef', ''), ('Decoration', ''))), - 'OpDecorateString': (5632, False, False, (('IdRef', ''), ('Decoration', ''))), - 'OpDecorateStringGOOGLE': (5632, False, False, (('IdRef', ''), ('Decoration', ''))), - 'OpDecorationGroup': (73, False, True, ()), - 'OpDemoteToHelperInvocation': (5380, False, False, ()), - 'OpDemoteToHelperInvocationEXT': (5380, False, False, ()), - 'OpDepthAttachmentReadEXT': (4161, True, True, (('IdRef', '?'),)), - 'OpDot': (148, True, True, (('IdRef', ''), ('IdRef', ''))), - 'OpEmitMeshTasksEXT': (5294, False, False, (('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', '?'))), - 'OpEmitStreamVertex': (220, False, False, (('IdRef', ''),)), - 'OpEmitVertex': (218, False, False, ()), - 'OpEndInvocationInterlockEXT': (5365, False, False, ()), - 'OpEndPrimitive': (219, False, False, ()), - 'OpEndStreamPrimitive': (221, False, False, (('IdRef', ''),)), - 'OpEnqueueKernel': (292, True, True, (('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', '*'))), - 'OpEnqueueMarker': (291, True, True, (('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''))), - 'OpEnqueueNodePayloadsAMDX': (5075, False, False, (('IdRef', ''),)), - 'OpEntryPoint': (15, False, False, (('ExecutionModel', ''), ('IdRef', ''), ('LiteralString', ''), ('IdRef', '*'))), - 'OpExecuteCallableKHR': (4446, False, False, (('IdRef', ''), ('IdRef', ''))), - 'OpExecuteCallableNV': (5344, False, False, (('IdRef', ''), ('IdRef', ''))), - 'OpExecutionMode': (16, False, False, (('IdRef', ''), ('ExecutionMode', ''))), - 'OpExecutionModeId': (331, False, False, (('IdRef', ''), ('ExecutionMode', ''))), - 'OpExpectKHR': (5631, True, True, (('IdRef', ''), ('IdRef', ''))), - 'OpExtInst': (12, True, True, (('IdRef', ''), ('LiteralExtInstInteger', ''), ('IdRef', '*'))), - 'OpExtInstImport': (11, False, True, (('LiteralString', ''),)), - 'OpExtInstWithForwardRefsKHR': (4433, True, True, (('IdRef', ''), ('LiteralExtInstInteger', ''), ('IdRef', '*'))), - 'OpExtension': (10, False, False, (('LiteralString', ''),)), - 'OpExtractSubArrayQCOM': (4542, True, True, (('IdRef', ''), ('IdRef', ''))), - 'OpFAdd': (129, True, True, (('IdRef', ''), ('IdRef', ''))), - 'OpFConvert': (115, True, True, (('IdRef', ''),)), - 'OpFDiv': (136, True, True, (('IdRef', ''), ('IdRef', ''))), - 'OpFDot2MixAcc16VALVE': (6917, True, True, (('IdRef', ''), ('IdRef', ''), ('IdRef', ''))), - 'OpFDot2MixAcc32VALVE': (6916, True, True, (('IdRef', ''), ('IdRef', ''), ('IdRef', ''))), - 'OpFDot4MixAcc32VALVE': (6918, True, True, (('IdRef', ''), ('IdRef', ''), ('IdRef', ''))), - 'OpFMod': (141, True, True, (('IdRef', ''), ('IdRef', ''))), - 'OpFMul': (133, True, True, (('IdRef', ''), ('IdRef', ''))), - 'OpFNegate': (127, True, True, (('IdRef', ''),)), - 'OpFOrdEqual': (180, True, True, (('IdRef', ''), ('IdRef', ''))), - 'OpFOrdGreaterThan': (186, True, True, (('IdRef', ''), ('IdRef', ''))), - 'OpFOrdGreaterThanEqual': (190, True, True, (('IdRef', ''), ('IdRef', ''))), - 'OpFOrdLessThan': (184, True, True, (('IdRef', ''), ('IdRef', ''))), - 'OpFOrdLessThanEqual': (188, True, True, (('IdRef', ''), ('IdRef', ''))), - 'OpFOrdNotEqual': (182, True, True, (('IdRef', ''), ('IdRef', ''))), - 'OpFPGARegALTERA': (5949, True, True, (('IdRef', ''),)), - 'OpFPGARegINTEL': (5949, True, True, (('IdRef', ''),)), - 'OpFRem': (140, True, True, (('IdRef', ''), ('IdRef', ''))), - 'OpFSub': (131, True, True, (('IdRef', ''), ('IdRef', ''))), - 'OpFUnordEqual': (181, True, True, (('IdRef', ''), ('IdRef', ''))), - 'OpFUnordGreaterThan': (187, True, True, (('IdRef', ''), ('IdRef', ''))), - 'OpFUnordGreaterThanEqual': (191, True, True, (('IdRef', ''), ('IdRef', ''))), - 'OpFUnordLessThan': (185, True, True, (('IdRef', ''), ('IdRef', ''))), - 'OpFUnordLessThanEqual': (189, True, True, (('IdRef', ''), ('IdRef', ''))), - 'OpFUnordNotEqual': (183, True, True, (('IdRef', ''), ('IdRef', ''))), - 'OpFetchMicroTriangleVertexBarycentricNV': (5301, True, True, (('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''))), - 'OpFetchMicroTriangleVertexPositionNV': (5300, True, True, (('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''))), - 'OpFinishWritingNodePayloadAMDX': (5078, True, True, (('IdRef', ''),)), - 'OpFixedCosALTERA': (5927, True, True, (('IdRef', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''))), - 'OpFixedCosINTEL': (5927, True, True, (('IdRef', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''))), - 'OpFixedCosPiALTERA': (5930, True, True, (('IdRef', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''))), - 'OpFixedCosPiINTEL': (5930, True, True, (('IdRef', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''))), - 'OpFixedExpALTERA': (5933, True, True, (('IdRef', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''))), - 'OpFixedExpINTEL': (5933, True, True, (('IdRef', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''))), - 'OpFixedLogALTERA': (5932, True, True, (('IdRef', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''))), - 'OpFixedLogINTEL': (5932, True, True, (('IdRef', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''))), - 'OpFixedRecipALTERA': (5924, True, True, (('IdRef', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''))), - 'OpFixedRecipINTEL': (5924, True, True, (('IdRef', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''))), - 'OpFixedRsqrtALTERA': (5925, True, True, (('IdRef', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''))), - 'OpFixedRsqrtINTEL': (5925, True, True, (('IdRef', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''))), - 'OpFixedSinALTERA': (5926, True, True, (('IdRef', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''))), - 'OpFixedSinCosALTERA': (5928, True, True, (('IdRef', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''))), - 'OpFixedSinCosINTEL': (5928, True, True, (('IdRef', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''))), - 'OpFixedSinCosPiALTERA': (5931, True, True, (('IdRef', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''))), - 'OpFixedSinCosPiINTEL': (5931, True, True, (('IdRef', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''))), - 'OpFixedSinINTEL': (5926, True, True, (('IdRef', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''))), - 'OpFixedSinPiALTERA': (5929, True, True, (('IdRef', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''))), - 'OpFixedSinPiINTEL': (5929, True, True, (('IdRef', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''))), - 'OpFixedSqrtALTERA': (5923, True, True, (('IdRef', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''))), - 'OpFixedSqrtINTEL': (5923, True, True, (('IdRef', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''))), - 'OpFmaKHR': (4427, True, True, (('IdRef', ''), ('IdRef', ''), ('IdRef', ''))), - 'OpFragmentFetchAMD': (5012, True, True, (('IdRef', ''), ('IdRef', ''), ('IdRef', ''))), - 'OpFragmentMaskFetchAMD': (5011, True, True, (('IdRef', ''), ('IdRef', ''))), - 'OpFreezeKHR': (5159, True, True, (('IdRef', ''),)), - 'OpFunction': (54, True, True, (('FunctionControl', ''), ('IdRef', ''))), - 'OpFunctionCall': (57, True, True, (('IdRef', ''), ('IdRef', '*'))), - 'OpFunctionEnd': (56, False, False, ()), - 'OpFunctionParameter': (55, True, True, ()), - 'OpFunctionPointerCallINTEL': (5601, True, True, (('IdRef', '*'),)), - 'OpFwidth': (209, True, True, (('IdRef', ''),)), - 'OpFwidthCoarse': (215, True, True, (('IdRef', ''),)), - 'OpFwidthFine': (212, True, True, (('IdRef', ''),)), - 'OpGenericCastToPtr': (122, True, True, (('IdRef', ''),)), - 'OpGenericCastToPtrExplicit': (123, True, True, (('IdRef', ''), ('StorageClass', ''))), - 'OpGenericPtrMemSemantics': (69, True, True, (('IdRef', ''),)), - 'OpGetDefaultQueue': (303, True, True, ()), - 'OpGetInstanceCustomIndexAtLevelAMDX': (5193, True, True, (('IdRef', ''),)), - 'OpGetInstanceIdAtLevelAMDX': (5194, True, True, (('IdRef', ''),)), - 'OpGetKernelLocalSizeForSubgroupCount': (325, True, True, (('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''))), - 'OpGetKernelMaxNumSubgroups': (326, True, True, (('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''))), - 'OpGetKernelNDrangeMaxSubGroupSize': (294, True, True, (('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''))), - 'OpGetKernelNDrangeSubGroupCount': (293, True, True, (('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''))), - 'OpGetKernelPreferredWorkGroupSizeMultiple': (296, True, True, (('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''))), - 'OpGetKernelWorkGroupSize': (295, True, True, (('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''))), - 'OpGetMaxPipePackets': (284, True, True, (('IdRef', ''), ('IdRef', ''), ('IdRef', ''))), - 'OpGetNumPipePackets': (283, True, True, (('IdRef', ''), ('IdRef', ''), ('IdRef', ''))), - 'OpGetObjectToWorldAtLevelAMDX': (5195, True, True, (('IdRef', ''),)), - 'OpGetWorldToObjectAtLevelAMDX': (5196, True, True, (('IdRef', ''),)), - 'OpGraphARM': (4183, True, True, ()), - 'OpGraphConstantARM': (4181, True, True, (('LiteralInteger', ''),)), - 'OpGraphEndARM': (4186, False, False, ()), - 'OpGraphEntryPointARM': (4182, False, False, (('IdRef', ''), ('LiteralString', ''), ('IdRef', '*'))), - 'OpGraphInputARM': (4184, True, True, (('IdRef', ''), ('IdRef', '*'))), - 'OpGraphSetOutputARM': (4185, False, False, (('IdRef', ''), ('IdRef', ''), ('IdRef', '*'))), - 'OpGroupAll': (261, True, True, (('IdScope', ''), ('IdRef', ''))), - 'OpGroupAny': (262, True, True, (('IdScope', ''), ('IdRef', ''))), - 'OpGroupAsyncCopy': (259, True, True, (('IdScope', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''))), - 'OpGroupBitwiseAndKHR': (6403, True, True, (('IdScope', ''), ('GroupOperation', ''), ('IdRef', ''))), - 'OpGroupBitwiseOrKHR': (6404, True, True, (('IdScope', ''), ('GroupOperation', ''), ('IdRef', ''))), - 'OpGroupBitwiseXorKHR': (6405, True, True, (('IdScope', ''), ('GroupOperation', ''), ('IdRef', ''))), - 'OpGroupBroadcast': (263, True, True, (('IdScope', ''), ('IdRef', ''), ('IdRef', ''))), - 'OpGroupCommitReadPipe': (287, False, False, (('IdScope', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''))), - 'OpGroupCommitWritePipe': (288, False, False, (('IdScope', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''))), - 'OpGroupDecorate': (74, False, False, (('IdRef', ''), ('IdRef', '*'))), - 'OpGroupFAdd': (265, True, True, (('IdScope', ''), ('GroupOperation', ''), ('IdRef', ''))), - 'OpGroupFAddNonUniformAMD': (5001, True, True, (('IdScope', ''), ('GroupOperation', ''), ('IdRef', ''))), - 'OpGroupFMax': (269, True, True, (('IdScope', ''), ('GroupOperation', ''), ('IdRef', ''))), - 'OpGroupFMaxNonUniformAMD': (5005, True, True, (('IdScope', ''), ('GroupOperation', ''), ('IdRef', ''))), - 'OpGroupFMin': (266, True, True, (('IdScope', ''), ('GroupOperation', ''), ('IdRef', ''))), - 'OpGroupFMinNonUniformAMD': (5002, True, True, (('IdScope', ''), ('GroupOperation', ''), ('IdRef', ''))), - 'OpGroupFMulKHR': (6402, True, True, (('IdScope', ''), ('GroupOperation', ''), ('IdRef', ''))), - 'OpGroupIAdd': (264, True, True, (('IdScope', ''), ('GroupOperation', ''), ('IdRef', ''))), - 'OpGroupIAddNonUniformAMD': (5000, True, True, (('IdScope', ''), ('GroupOperation', ''), ('IdRef', ''))), - 'OpGroupIMulKHR': (6401, True, True, (('IdScope', ''), ('GroupOperation', ''), ('IdRef', ''))), - 'OpGroupLogicalAndKHR': (6406, True, True, (('IdScope', ''), ('GroupOperation', ''), ('IdRef', ''))), - 'OpGroupLogicalOrKHR': (6407, True, True, (('IdScope', ''), ('GroupOperation', ''), ('IdRef', ''))), - 'OpGroupLogicalXorKHR': (6408, True, True, (('IdScope', ''), ('GroupOperation', ''), ('IdRef', ''))), - 'OpGroupMemberDecorate': (75, False, False, (('IdRef', ''), ('PairIdRefLiteralInteger', '*'))), - 'OpGroupNonUniformAll': (334, True, True, (('IdScope', ''), ('IdRef', ''))), - 'OpGroupNonUniformAllEqual': (336, True, True, (('IdScope', ''), ('IdRef', ''))), - 'OpGroupNonUniformAny': (335, True, True, (('IdScope', ''), ('IdRef', ''))), - 'OpGroupNonUniformBallot': (339, True, True, (('IdScope', ''), ('IdRef', ''))), - 'OpGroupNonUniformBallotBitCount': (342, True, True, (('IdScope', ''), ('GroupOperation', ''), ('IdRef', ''))), - 'OpGroupNonUniformBallotBitExtract': (341, True, True, (('IdScope', ''), ('IdRef', ''), ('IdRef', ''))), - 'OpGroupNonUniformBallotFindLSB': (343, True, True, (('IdScope', ''), ('IdRef', ''))), - 'OpGroupNonUniformBallotFindMSB': (344, True, True, (('IdScope', ''), ('IdRef', ''))), - 'OpGroupNonUniformBitwiseAnd': (359, True, True, (('IdScope', ''), ('GroupOperation', ''), ('IdRef', ''), ('IdRef', '?'))), - 'OpGroupNonUniformBitwiseOr': (360, True, True, (('IdScope', ''), ('GroupOperation', ''), ('IdRef', ''), ('IdRef', '?'))), - 'OpGroupNonUniformBitwiseXor': (361, True, True, (('IdScope', ''), ('GroupOperation', ''), ('IdRef', ''), ('IdRef', '?'))), - 'OpGroupNonUniformBroadcast': (337, True, True, (('IdScope', ''), ('IdRef', ''), ('IdRef', ''))), - 'OpGroupNonUniformBroadcastFirst': (338, True, True, (('IdScope', ''), ('IdRef', ''))), - 'OpGroupNonUniformElect': (333, True, True, (('IdScope', ''),)), - 'OpGroupNonUniformFAdd': (350, True, True, (('IdScope', ''), ('GroupOperation', ''), ('IdRef', ''), ('IdRef', '?'))), - 'OpGroupNonUniformFMax': (358, True, True, (('IdScope', ''), ('GroupOperation', ''), ('IdRef', ''), ('IdRef', '?'))), - 'OpGroupNonUniformFMin': (355, True, True, (('IdScope', ''), ('GroupOperation', ''), ('IdRef', ''), ('IdRef', '?'))), - 'OpGroupNonUniformFMul': (352, True, True, (('IdScope', ''), ('GroupOperation', ''), ('IdRef', ''), ('IdRef', '?'))), - 'OpGroupNonUniformIAdd': (349, True, True, (('IdScope', ''), ('GroupOperation', ''), ('IdRef', ''), ('IdRef', '?'))), - 'OpGroupNonUniformIMul': (351, True, True, (('IdScope', ''), ('GroupOperation', ''), ('IdRef', ''), ('IdRef', '?'))), - 'OpGroupNonUniformInverseBallot': (340, True, True, (('IdScope', ''), ('IdRef', ''))), - 'OpGroupNonUniformLogicalAnd': (362, True, True, (('IdScope', ''), ('GroupOperation', ''), ('IdRef', ''), ('IdRef', '?'))), - 'OpGroupNonUniformLogicalOr': (363, True, True, (('IdScope', ''), ('GroupOperation', ''), ('IdRef', ''), ('IdRef', '?'))), - 'OpGroupNonUniformLogicalXor': (364, True, True, (('IdScope', ''), ('GroupOperation', ''), ('IdRef', ''), ('IdRef', '?'))), - 'OpGroupNonUniformPartitionEXT': (5296, True, True, (('IdRef', ''),)), - 'OpGroupNonUniformPartitionNV': (5296, True, True, (('IdRef', ''),)), - 'OpGroupNonUniformQuadAllKHR': (5110, True, True, (('IdRef', ''),)), - 'OpGroupNonUniformQuadAnyKHR': (5111, True, True, (('IdRef', ''),)), - 'OpGroupNonUniformQuadBroadcast': (365, True, True, (('IdScope', ''), ('IdRef', ''), ('IdRef', ''))), - 'OpGroupNonUniformQuadSwap': (366, True, True, (('IdScope', ''), ('IdRef', ''), ('IdRef', ''))), - 'OpGroupNonUniformRotateKHR': (4431, True, True, (('IdScope', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', '?'))), - 'OpGroupNonUniformSMax': (356, True, True, (('IdScope', ''), ('GroupOperation', ''), ('IdRef', ''), ('IdRef', '?'))), - 'OpGroupNonUniformSMin': (353, True, True, (('IdScope', ''), ('GroupOperation', ''), ('IdRef', ''), ('IdRef', '?'))), - 'OpGroupNonUniformShuffle': (345, True, True, (('IdScope', ''), ('IdRef', ''), ('IdRef', ''))), - 'OpGroupNonUniformShuffleDown': (348, True, True, (('IdScope', ''), ('IdRef', ''), ('IdRef', ''))), - 'OpGroupNonUniformShuffleUp': (347, True, True, (('IdScope', ''), ('IdRef', ''), ('IdRef', ''))), - 'OpGroupNonUniformShuffleXor': (346, True, True, (('IdScope', ''), ('IdRef', ''), ('IdRef', ''))), - 'OpGroupNonUniformUMax': (357, True, True, (('IdScope', ''), ('GroupOperation', ''), ('IdRef', ''), ('IdRef', '?'))), - 'OpGroupNonUniformUMin': (354, True, True, (('IdScope', ''), ('GroupOperation', ''), ('IdRef', ''), ('IdRef', '?'))), - 'OpGroupReserveReadPipePackets': (285, True, True, (('IdScope', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''))), - 'OpGroupReserveWritePipePackets': (286, True, True, (('IdScope', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''))), - 'OpGroupSMax': (271, True, True, (('IdScope', ''), ('GroupOperation', ''), ('IdRef', ''))), - 'OpGroupSMaxNonUniformAMD': (5007, True, True, (('IdScope', ''), ('GroupOperation', ''), ('IdRef', ''))), - 'OpGroupSMin': (268, True, True, (('IdScope', ''), ('GroupOperation', ''), ('IdRef', ''))), - 'OpGroupSMinNonUniformAMD': (5004, True, True, (('IdScope', ''), ('GroupOperation', ''), ('IdRef', ''))), - 'OpGroupUMax': (270, True, True, (('IdScope', ''), ('GroupOperation', ''), ('IdRef', ''))), - 'OpGroupUMaxNonUniformAMD': (5006, True, True, (('IdScope', ''), ('GroupOperation', ''), ('IdRef', ''))), - 'OpGroupUMin': (267, True, True, (('IdScope', ''), ('GroupOperation', ''), ('IdRef', ''))), - 'OpGroupUMinNonUniformAMD': (5003, True, True, (('IdScope', ''), ('GroupOperation', ''), ('IdRef', ''))), - 'OpGroupWaitEvents': (260, False, False, (('IdScope', ''), ('IdRef', ''), ('IdRef', ''))), - 'OpHitObjectExecuteShaderEXT': (5319, False, False, (('IdRef', ''), ('IdRef', ''))), - 'OpHitObjectExecuteShaderNV': (5264, False, False, (('IdRef', ''), ('IdRef', ''))), - 'OpHitObjectGetAttributesEXT': (5321, False, False, (('IdRef', ''), ('IdRef', ''))), - 'OpHitObjectGetAttributesNV': (5266, False, False, (('IdRef', ''), ('IdRef', ''))), - 'OpHitObjectGetClusterIdNV': (5346, True, True, (('IdRef', ''),)), - 'OpHitObjectGetCurrentTimeEXT': (5320, True, True, (('IdRef', ''),)), - 'OpHitObjectGetCurrentTimeNV': (5265, True, True, (('IdRef', ''),)), - 'OpHitObjectGetGeometryIndexEXT': (5324, True, True, (('IdRef', ''),)), - 'OpHitObjectGetGeometryIndexNV': (5269, True, True, (('IdRef', ''),)), - 'OpHitObjectGetHitKindEXT': (5322, True, True, (('IdRef', ''),)), - 'OpHitObjectGetHitKindNV': (5267, True, True, (('IdRef', ''),)), - 'OpHitObjectGetInstanceCustomIndexEXT': (5326, True, True, (('IdRef', ''),)), - 'OpHitObjectGetInstanceCustomIndexNV': (5271, True, True, (('IdRef', ''),)), - 'OpHitObjectGetInstanceIdEXT': (5325, True, True, (('IdRef', ''),)), - 'OpHitObjectGetInstanceIdNV': (5270, True, True, (('IdRef', ''),)), - 'OpHitObjectGetIntersectionTriangleVertexPositionsEXT': (5307, True, True, (('IdRef', ''),)), - 'OpHitObjectGetLSSPositionsNV': (5434, True, True, (('IdRef', ''),)), - 'OpHitObjectGetLSSRadiiNV': (5435, True, True, (('IdRef', ''),)), - 'OpHitObjectGetObjectRayDirectionEXT': (5328, True, True, (('IdRef', ''),)), - 'OpHitObjectGetObjectRayDirectionNV': (5254, True, True, (('IdRef', ''),)), - 'OpHitObjectGetObjectRayOriginEXT': (5327, True, True, (('IdRef', ''),)), - 'OpHitObjectGetObjectRayOriginNV': (5255, True, True, (('IdRef', ''),)), - 'OpHitObjectGetObjectToWorldEXT': (5331, True, True, (('IdRef', ''),)), - 'OpHitObjectGetObjectToWorldNV': (5253, True, True, (('IdRef', ''),)), - 'OpHitObjectGetPrimitiveIndexEXT': (5323, True, True, (('IdRef', ''),)), - 'OpHitObjectGetPrimitiveIndexNV': (5268, True, True, (('IdRef', ''),)), - 'OpHitObjectGetRayFlagsEXT': (5308, True, True, (('IdRef', ''),)), - 'OpHitObjectGetRayTMaxEXT': (5333, True, True, (('IdRef', ''),)), - 'OpHitObjectGetRayTMaxNV': (5274, True, True, (('IdRef', ''),)), - 'OpHitObjectGetRayTMinEXT': (5347, True, True, (('IdRef', ''),)), - 'OpHitObjectGetRayTMinNV': (5275, True, True, (('IdRef', ''),)), - 'OpHitObjectGetShaderBindingTableRecordIndexEXT': (5348, True, True, (('IdRef', ''),)), - 'OpHitObjectGetShaderBindingTableRecordIndexNV': (5258, True, True, (('IdRef', ''),)), - 'OpHitObjectGetShaderRecordBufferHandleEXT': (5349, True, True, (('IdRef', ''),)), - 'OpHitObjectGetShaderRecordBufferHandleNV': (5257, True, True, (('IdRef', ''),)), - 'OpHitObjectGetSpherePositionNV': (5432, True, True, (('IdRef', ''),)), - 'OpHitObjectGetSphereRadiusNV': (5433, True, True, (('IdRef', ''),)), - 'OpHitObjectGetWorldRayDirectionEXT': (5329, True, True, (('IdRef', ''),)), - 'OpHitObjectGetWorldRayDirectionNV': (5272, True, True, (('IdRef', ''),)), - 'OpHitObjectGetWorldRayOriginEXT': (5330, True, True, (('IdRef', ''),)), - 'OpHitObjectGetWorldRayOriginNV': (5273, True, True, (('IdRef', ''),)), - 'OpHitObjectGetWorldToObjectEXT': (5332, True, True, (('IdRef', ''),)), - 'OpHitObjectGetWorldToObjectNV': (5252, True, True, (('IdRef', ''),)), - 'OpHitObjectIsEmptyEXT': (5350, True, True, (('IdRef', ''),)), - 'OpHitObjectIsEmptyNV': (5276, True, True, (('IdRef', ''),)), - 'OpHitObjectIsHitEXT': (5351, True, True, (('IdRef', ''),)), - 'OpHitObjectIsHitNV': (5277, True, True, (('IdRef', ''),)), - 'OpHitObjectIsLSSHitNV': (5437, True, True, (('IdRef', ''),)), - 'OpHitObjectIsMissEXT': (5352, True, True, (('IdRef', ''),)), - 'OpHitObjectIsMissNV': (5278, True, True, (('IdRef', ''),)), - 'OpHitObjectIsSphereHitNV': (5436, True, True, (('IdRef', ''),)), - 'OpHitObjectRecordEmptyEXT': (5318, False, False, (('IdRef', ''),)), - 'OpHitObjectRecordEmptyNV': (5259, False, False, (('IdRef', ''),)), - 'OpHitObjectRecordFromQueryEXT': (5304, False, False, (('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', '?'))), - 'OpHitObjectRecordHitMotionNV': (5249, False, False, (('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''))), - 'OpHitObjectRecordHitNV': (5261, False, False, (('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''))), - 'OpHitObjectRecordHitWithIndexMotionNV': (5250, False, False, (('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''))), - 'OpHitObjectRecordHitWithIndexNV': (5262, False, False, (('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''))), - 'OpHitObjectRecordMissEXT': (5305, False, False, (('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''))), - 'OpHitObjectRecordMissMotionEXT': (5306, False, False, (('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''))), - 'OpHitObjectRecordMissMotionNV': (5251, False, False, (('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''))), - 'OpHitObjectRecordMissNV': (5263, False, False, (('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''))), - 'OpHitObjectReorderExecuteShaderEXT': (5310, False, False, (('IdRef', ''), ('IdRef', ''), ('IdRef', '?'), ('IdRef', '?'))), - 'OpHitObjectSetShaderBindingTableRecordIndexEXT': (5309, False, False, (('IdRef', ''), ('IdRef', ''))), - 'OpHitObjectTraceMotionReorderExecuteEXT': (5312, False, False, (('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', '?'), ('IdRef', '?'))), - 'OpHitObjectTraceRayEXT': (5316, False, False, (('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''))), - 'OpHitObjectTraceRayMotionEXT': (5317, False, False, (('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''))), - 'OpHitObjectTraceRayMotionNV': (5256, False, False, (('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''))), - 'OpHitObjectTraceRayNV': (5260, False, False, (('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''))), - 'OpHitObjectTraceReorderExecuteEXT': (5311, False, False, (('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', '?'), ('IdRef', '?'))), - 'OpIAdd': (128, True, True, (('IdRef', ''), ('IdRef', ''))), - 'OpIAddCarry': (149, True, True, (('IdRef', ''), ('IdRef', ''))), - 'OpIAddSatINTEL': (5589, True, True, (('IdRef', ''), ('IdRef', ''))), - 'OpIAverageINTEL': (5591, True, True, (('IdRef', ''), ('IdRef', ''))), - 'OpIAverageRoundedINTEL': (5593, True, True, (('IdRef', ''), ('IdRef', ''))), - 'OpIEqual': (170, True, True, (('IdRef', ''), ('IdRef', ''))), - 'OpIMul': (132, True, True, (('IdRef', ''), ('IdRef', ''))), - 'OpIMul32x16INTEL': (5597, True, True, (('IdRef', ''), ('IdRef', ''))), - 'OpINotEqual': (171, True, True, (('IdRef', ''), ('IdRef', ''))), - 'OpISub': (130, True, True, (('IdRef', ''), ('IdRef', ''))), - 'OpISubBorrow': (150, True, True, (('IdRef', ''), ('IdRef', ''))), - 'OpISubSatINTEL': (5595, True, True, (('IdRef', ''), ('IdRef', ''))), - 'OpIgnoreIntersectionKHR': (4448, False, False, ()), - 'OpIgnoreIntersectionNV': (5335, False, False, ()), - 'OpImage': (100, True, True, (('IdRef', ''),)), - 'OpImageBlockMatchGatherSADQCOM': (4503, True, True, (('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''))), - 'OpImageBlockMatchGatherSSDQCOM': (4502, True, True, (('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''))), - 'OpImageBlockMatchSADQCOM': (4483, True, True, (('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''))), - 'OpImageBlockMatchSSDQCOM': (4482, True, True, (('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''))), - 'OpImageBlockMatchWindowSADQCOM': (4501, True, True, (('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''))), - 'OpImageBlockMatchWindowSSDQCOM': (4500, True, True, (('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''))), - 'OpImageBoxFilterQCOM': (4481, True, True, (('IdRef', ''), ('IdRef', ''), ('IdRef', ''))), - 'OpImageDrefGather': (97, True, True, (('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('ImageOperands', '?'))), - 'OpImageFetch': (95, True, True, (('IdRef', ''), ('IdRef', ''), ('ImageOperands', '?'))), - 'OpImageGather': (96, True, True, (('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('ImageOperands', '?'))), - 'OpImageGatherQCOM': (4545, True, True, (('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('ImageOperands', '?'))), - 'OpImageQueryFormat': (101, True, True, (('IdRef', ''),)), - 'OpImageQueryLevels': (106, True, True, (('IdRef', ''),)), - 'OpImageQueryLod': (105, True, True, (('IdRef', ''), ('IdRef', ''))), - 'OpImageQueryOrder': (102, True, True, (('IdRef', ''),)), - 'OpImageQuerySamples': (107, True, True, (('IdRef', ''),)), - 'OpImageQuerySize': (104, True, True, (('IdRef', ''),)), - 'OpImageQuerySizeLod': (103, True, True, (('IdRef', ''), ('IdRef', ''))), - 'OpImageRead': (98, True, True, (('IdRef', ''), ('IdRef', ''), ('ImageOperands', '?'))), - 'OpImageSampleDrefExplicitLod': (90, True, True, (('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('ImageOperands', ''))), - 'OpImageSampleDrefImplicitLod': (89, True, True, (('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('ImageOperands', '?'))), - 'OpImageSampleExplicitLod': (88, True, True, (('IdRef', ''), ('IdRef', ''), ('ImageOperands', ''))), - 'OpImageSampleFootprintNV': (5283, True, True, (('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('ImageOperands', '?'))), - 'OpImageSampleImplicitLod': (87, True, True, (('IdRef', ''), ('IdRef', ''), ('ImageOperands', '?'))), - 'OpImageSampleProjDrefExplicitLod': (94, True, True, (('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('ImageOperands', ''))), - 'OpImageSampleProjDrefImplicitLod': (93, True, True, (('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('ImageOperands', '?'))), - 'OpImageSampleProjExplicitLod': (92, True, True, (('IdRef', ''), ('IdRef', ''), ('ImageOperands', ''))), - 'OpImageSampleProjImplicitLod': (91, True, True, (('IdRef', ''), ('IdRef', ''), ('ImageOperands', '?'))), - 'OpImageSampleWeightedQCOM': (4480, True, True, (('IdRef', ''), ('IdRef', ''), ('IdRef', ''))), - 'OpImageSparseDrefGather': (315, True, True, (('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('ImageOperands', '?'))), - 'OpImageSparseFetch': (313, True, True, (('IdRef', ''), ('IdRef', ''), ('ImageOperands', '?'))), - 'OpImageSparseGather': (314, True, True, (('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('ImageOperands', '?'))), - 'OpImageSparseRead': (320, True, True, (('IdRef', ''), ('IdRef', ''), ('ImageOperands', '?'))), - 'OpImageSparseSampleDrefExplicitLod': (308, True, True, (('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('ImageOperands', ''))), - 'OpImageSparseSampleDrefImplicitLod': (307, True, True, (('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('ImageOperands', '?'))), - 'OpImageSparseSampleExplicitLod': (306, True, True, (('IdRef', ''), ('IdRef', ''), ('ImageOperands', ''))), - 'OpImageSparseSampleImplicitLod': (305, True, True, (('IdRef', ''), ('IdRef', ''), ('ImageOperands', '?'))), - 'OpImageSparseSampleProjDrefExplicitLod': (312, True, True, (('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('ImageOperands', ''))), - 'OpImageSparseSampleProjDrefImplicitLod': (311, True, True, (('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('ImageOperands', '?'))), - 'OpImageSparseSampleProjExplicitLod': (310, True, True, (('IdRef', ''), ('IdRef', ''), ('ImageOperands', ''))), - 'OpImageSparseSampleProjImplicitLod': (309, True, True, (('IdRef', ''), ('IdRef', ''), ('ImageOperands', '?'))), - 'OpImageSparseTexelsResident': (316, True, True, (('IdRef', ''),)), - 'OpImageTexelPointer': (60, True, True, (('IdRef', ''), ('IdRef', ''), ('IdRef', ''))), - 'OpImageWrite': (99, False, False, (('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('ImageOperands', '?'))), - 'OpInBoundsAccessChain': (66, True, True, (('IdRef', ''), ('IdRef', '*'))), - 'OpInBoundsPtrAccessChain': (70, True, True, (('IdRef', ''), ('IdRef', ''), ('IdRef', '*'))), - 'OpIsFinite': (158, True, True, (('IdRef', ''),)), - 'OpIsHelperInvocationEXT': (5381, True, True, ()), - 'OpIsInf': (157, True, True, (('IdRef', ''),)), - 'OpIsNan': (156, True, True, (('IdRef', ''),)), - 'OpIsNodePayloadValidAMDX': (5101, True, True, (('IdRef', ''), ('IdRef', ''))), - 'OpIsNormal': (159, True, True, (('IdRef', ''),)), - 'OpIsValidEvent': (300, True, True, (('IdRef', ''),)), - 'OpIsValidReserveId': (282, True, True, (('IdRef', ''),)), - 'OpKill': (252, False, False, ()), - 'OpLabel': (248, False, True, ()), - 'OpLessOrGreater': (161, True, True, (('IdRef', ''), ('IdRef', ''))), - 'OpLifetimeStart': (256, False, False, (('IdRef', ''), ('LiteralInteger', ''))), - 'OpLifetimeStop': (257, False, False, (('IdRef', ''), ('LiteralInteger', ''))), - 'OpLine': (8, False, False, (('IdRef', ''), ('LiteralInteger', ''), ('LiteralInteger', ''))), - 'OpLoad': (61, True, True, (('IdRef', ''), ('MemoryAccess', '?'))), - 'OpLogicalAnd': (167, True, True, (('IdRef', ''), ('IdRef', ''))), - 'OpLogicalEqual': (164, True, True, (('IdRef', ''), ('IdRef', ''))), - 'OpLogicalNot': (168, True, True, (('IdRef', ''),)), - 'OpLogicalNotEqual': (165, True, True, (('IdRef', ''), ('IdRef', ''))), - 'OpLogicalOr': (166, True, True, (('IdRef', ''), ('IdRef', ''))), - 'OpLoopControlINTEL': (5887, False, False, (('LiteralInteger', '*'),)), - 'OpLoopMerge': (246, False, False, (('IdRef', ''), ('IdRef', ''), ('LoopControl', ''))), - 'OpMaskedGatherINTEL': (6428, True, True, (('IdRef', ''), ('LiteralInteger', ''), ('IdRef', ''), ('IdRef', ''))), - 'OpMaskedScatterINTEL': (6429, False, False, (('IdRef', ''), ('IdRef', ''), ('LiteralInteger', ''), ('IdRef', ''))), - 'OpMatrixTimesMatrix': (146, True, True, (('IdRef', ''), ('IdRef', ''))), - 'OpMatrixTimesScalar': (143, True, True, (('IdRef', ''), ('IdRef', ''))), - 'OpMatrixTimesVector': (145, True, True, (('IdRef', ''), ('IdRef', ''))), - 'OpMemberDecorate': (72, False, False, (('IdRef', ''), ('LiteralInteger', ''), ('Decoration', ''))), - 'OpMemberDecorateIdEXT': (5127, False, False, (('IdRef', ''), ('LiteralInteger', ''), ('Decoration', ''))), - 'OpMemberDecorateString': (5633, False, False, (('IdRef', ''), ('LiteralInteger', ''), ('Decoration', ''))), - 'OpMemberDecorateStringGOOGLE': (5633, False, False, (('IdRef', ''), ('LiteralInteger', ''), ('Decoration', ''))), - 'OpMemberName': (6, False, False, (('IdRef', ''), ('LiteralInteger', ''), ('LiteralString', ''))), - 'OpMemoryBarrier': (225, False, False, (('IdScope', ''), ('IdMemorySemantics', ''))), - 'OpMemoryModel': (14, False, False, (('AddressingModel', ''), ('MemoryModel', ''))), - 'OpMemoryNamedBarrier': (329, False, False, (('IdRef', ''), ('IdScope', ''), ('IdMemorySemantics', ''))), - 'OpModuleProcessed': (330, False, False, (('LiteralString', ''),)), - 'OpName': (5, False, False, (('IdRef', ''), ('LiteralString', ''))), - 'OpNamedBarrierInitialize': (328, True, True, (('IdRef', ''),)), - 'OpNoLine': (317, False, False, ()), - 'OpNodePayloadArrayLengthAMDX': (5090, True, True, (('IdRef', ''),)), - 'OpNop': (0, False, False, ()), - 'OpNot': (200, True, True, (('IdRef', ''),)), - 'OpOrdered': (162, True, True, (('IdRef', ''), ('IdRef', ''))), - 'OpOuterProduct': (147, True, True, (('IdRef', ''), ('IdRef', ''))), - 'OpPauseINTEL': (6267, False, False, (('IdRef', ''),)), - 'OpPhi': (245, True, True, (('PairIdRefIdRef', '*'),)), - 'OpPoisonKHR': (5158, True, True, ()), - 'OpPredicatedLoadINTEL': (6258, True, True, (('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('MemoryAccess', '?'))), - 'OpPredicatedStoreINTEL': (6259, False, False, (('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('MemoryAccess', '?'))), - 'OpPtrAccessChain': (67, True, True, (('IdRef', ''), ('IdRef', ''), ('IdRef', '*'))), - 'OpPtrCastToCrossWorkgroupALTERA': (5934, True, True, (('IdRef', ''),)), - 'OpPtrCastToCrossWorkgroupINTEL': (5934, True, True, (('IdRef', ''),)), - 'OpPtrCastToGeneric': (121, True, True, (('IdRef', ''),)), - 'OpPtrDiff': (403, True, True, (('IdRef', ''), ('IdRef', ''))), - 'OpPtrEqual': (401, True, True, (('IdRef', ''), ('IdRef', ''))), - 'OpPtrNotEqual': (402, True, True, (('IdRef', ''), ('IdRef', ''))), - 'OpQuantizeToF16': (116, True, True, (('IdRef', ''),)), - 'OpRawAccessChainNV': (5398, True, True, (('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('RawAccessChainOperands', '?'))), - 'OpRayQueryConfirmIntersectionKHR': (4476, False, False, (('IdRef', ''),)), - 'OpRayQueryGenerateIntersectionKHR': (4475, False, False, (('IdRef', ''), ('IdRef', ''))), - 'OpRayQueryGetClusterIdNV': (5345, True, True, (('IdRef', ''), ('IdRef', ''))), - 'OpRayQueryGetIntersectionBarycentricsKHR': (6024, True, True, (('IdRef', ''), ('IdRef', ''))), - 'OpRayQueryGetIntersectionCandidateAABBOpaqueKHR': (6026, True, True, (('IdRef', ''),)), - 'OpRayQueryGetIntersectionClusterIdNV': (5345, True, True, (('IdRef', ''), ('IdRef', ''))), - 'OpRayQueryGetIntersectionFrontFaceKHR': (6025, True, True, (('IdRef', ''), ('IdRef', ''))), - 'OpRayQueryGetIntersectionGeometryIndexKHR': (6022, True, True, (('IdRef', ''), ('IdRef', ''))), - 'OpRayQueryGetIntersectionInstanceCustomIndexAtLevelAMDX': (5198, True, True, (('IdRef', ''), ('IdRef', ''), ('IdRef', ''))), - 'OpRayQueryGetIntersectionInstanceCustomIndexKHR': (6019, True, True, (('IdRef', ''), ('IdRef', ''))), - 'OpRayQueryGetIntersectionInstanceIdAtLevelAMDX': (5199, True, True, (('IdRef', ''), ('IdRef', ''), ('IdRef', ''))), - 'OpRayQueryGetIntersectionInstanceIdKHR': (6020, True, True, (('IdRef', ''), ('IdRef', ''))), - 'OpRayQueryGetIntersectionInstanceLevelAMDX': (5197, True, True, (('IdRef', ''), ('IdRef', ''))), - 'OpRayQueryGetIntersectionInstanceShaderBindingTableRecordOffsetKHR': (6021, True, True, (('IdRef', ''), ('IdRef', ''))), - 'OpRayQueryGetIntersectionLSSHitValueNV': (5431, True, True, (('IdRef', ''), ('IdRef', ''))), - 'OpRayQueryGetIntersectionLSSPositionsNV': (5429, True, True, (('IdRef', ''), ('IdRef', ''))), - 'OpRayQueryGetIntersectionLSSRadiiNV': (5430, True, True, (('IdRef', ''), ('IdRef', ''))), - 'OpRayQueryGetIntersectionObjectRayDirectionKHR': (6027, True, True, (('IdRef', ''), ('IdRef', ''))), - 'OpRayQueryGetIntersectionObjectRayOriginKHR': (6028, True, True, (('IdRef', ''), ('IdRef', ''))), - 'OpRayQueryGetIntersectionObjectToWorldAtLevelAMDX': (5200, True, True, (('IdRef', ''), ('IdRef', ''), ('IdRef', ''))), - 'OpRayQueryGetIntersectionObjectToWorldKHR': (6031, True, True, (('IdRef', ''), ('IdRef', ''))), - 'OpRayQueryGetIntersectionPrimitiveIndexKHR': (6023, True, True, (('IdRef', ''), ('IdRef', ''))), - 'OpRayQueryGetIntersectionSpherePositionNV': (5427, True, True, (('IdRef', ''), ('IdRef', ''))), - 'OpRayQueryGetIntersectionSphereRadiusNV': (5428, True, True, (('IdRef', ''), ('IdRef', ''))), - 'OpRayQueryGetIntersectionTKHR': (6018, True, True, (('IdRef', ''), ('IdRef', ''))), - 'OpRayQueryGetIntersectionTriangleVertexPositionsKHR': (5340, True, True, (('IdRef', ''), ('IdRef', ''))), - 'OpRayQueryGetIntersectionTypeKHR': (4479, True, True, (('IdRef', ''), ('IdRef', ''))), - 'OpRayQueryGetIntersectionWorldToObjectAtLevelAMDX': (5201, True, True, (('IdRef', ''), ('IdRef', ''), ('IdRef', ''))), - 'OpRayQueryGetIntersectionWorldToObjectKHR': (6032, True, True, (('IdRef', ''), ('IdRef', ''))), - 'OpRayQueryGetRayFlagsKHR': (6017, True, True, (('IdRef', ''),)), - 'OpRayQueryGetRayTMinKHR': (6016, True, True, (('IdRef', ''),)), - 'OpRayQueryGetWorldRayDirectionKHR': (6029, True, True, (('IdRef', ''),)), - 'OpRayQueryGetWorldRayOriginKHR': (6030, True, True, (('IdRef', ''),)), - 'OpRayQueryInitializeKHR': (4473, False, False, (('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''))), - 'OpRayQueryIsLSSHitNV': (5439, True, True, (('IdRef', ''), ('IdRef', ''))), - 'OpRayQueryIsSphereHitNV': (5438, True, True, (('IdRef', ''), ('IdRef', ''))), - 'OpRayQueryProceedKHR': (4477, True, True, (('IdRef', ''),)), - 'OpRayQueryTerminateKHR': (4474, False, False, (('IdRef', ''),)), - 'OpReadClockKHR': (5056, True, True, (('IdScope', ''),)), - 'OpReadPipe': (274, True, True, (('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''))), - 'OpReadPipeBlockingALTERA': (5946, False, False, (('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''))), - 'OpReadPipeBlockingINTEL': (5946, False, False, (('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''))), - 'OpReleaseEvent': (298, False, False, (('IdRef', ''),)), - 'OpReorderThreadWithHintEXT': (5314, False, False, (('IdRef', ''), ('IdRef', ''))), - 'OpReorderThreadWithHintNV': (5280, False, False, (('IdRef', ''), ('IdRef', ''))), - 'OpReorderThreadWithHitObjectEXT': (5315, False, False, (('IdRef', ''), ('IdRef', '?'), ('IdRef', '?'))), - 'OpReorderThreadWithHitObjectNV': (5279, False, False, (('IdRef', ''), ('IdRef', '?'), ('IdRef', '?'))), - 'OpReportIntersectionKHR': (5334, True, True, (('IdRef', ''), ('IdRef', ''))), - 'OpReportIntersectionNV': (5334, True, True, (('IdRef', ''), ('IdRef', ''))), - 'OpReserveReadPipePackets': (278, True, True, (('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''))), - 'OpReserveWritePipePackets': (279, True, True, (('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''))), - 'OpReservedReadPipe': (276, True, True, (('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''))), - 'OpReservedWritePipe': (277, True, True, (('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''))), - 'OpRestoreMemoryINTEL': (5820, False, False, (('IdRef', ''),)), - 'OpRetainEvent': (297, False, False, (('IdRef', ''),)), - 'OpReturn': (253, False, False, ()), - 'OpReturnValue': (254, False, False, (('IdRef', ''),)), - 'OpRoundFToTF32INTEL': (6426, True, True, (('IdRef', ''),)), - 'OpSConvert': (114, True, True, (('IdRef', ''),)), - 'OpSDiv': (135, True, True, (('IdRef', ''), ('IdRef', ''))), - 'OpSDot': (4450, True, True, (('IdRef', ''), ('IdRef', ''), ('PackedVectorFormat', '?'))), - 'OpSDotAccSat': (4453, True, True, (('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('PackedVectorFormat', '?'))), - 'OpSDotAccSatKHR': (4453, True, True, (('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('PackedVectorFormat', '?'))), - 'OpSDotKHR': (4450, True, True, (('IdRef', ''), ('IdRef', ''), ('PackedVectorFormat', '?'))), - 'OpSGreaterThan': (173, True, True, (('IdRef', ''), ('IdRef', ''))), - 'OpSGreaterThanEqual': (175, True, True, (('IdRef', ''), ('IdRef', ''))), - 'OpSLessThan': (177, True, True, (('IdRef', ''), ('IdRef', ''))), - 'OpSLessThanEqual': (179, True, True, (('IdRef', ''), ('IdRef', ''))), - 'OpSMod': (139, True, True, (('IdRef', ''), ('IdRef', ''))), - 'OpSMulExtended': (152, True, True, (('IdRef', ''), ('IdRef', ''))), - 'OpSNegate': (126, True, True, (('IdRef', ''),)), - 'OpSRem': (138, True, True, (('IdRef', ''), ('IdRef', ''))), - 'OpSUDot': (4452, True, True, (('IdRef', ''), ('IdRef', ''), ('PackedVectorFormat', '?'))), - 'OpSUDotAccSat': (4455, True, True, (('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('PackedVectorFormat', '?'))), - 'OpSUDotAccSatKHR': (4455, True, True, (('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('PackedVectorFormat', '?'))), - 'OpSUDotKHR': (4452, True, True, (('IdRef', ''), ('IdRef', ''), ('PackedVectorFormat', '?'))), - 'OpSampledImage': (86, True, True, (('IdRef', ''), ('IdRef', ''))), - 'OpSamplerImageAddressingModeNV': (5397, False, False, (('LiteralInteger', ''),)), - 'OpSatConvertSToU': (118, True, True, (('IdRef', ''),)), - 'OpSatConvertUToS': (119, True, True, (('IdRef', ''),)), - 'OpSaveMemoryINTEL': (5819, True, True, ()), - 'OpSelect': (169, True, True, (('IdRef', ''), ('IdRef', ''), ('IdRef', ''))), - 'OpSelectionMerge': (247, False, False, (('IdRef', ''), ('SelectionControl', ''))), - 'OpSetMeshOutputsEXT': (5295, False, False, (('IdRef', ''), ('IdRef', ''))), - 'OpSetUserEventStatus': (301, False, False, (('IdRef', ''), ('IdRef', ''))), - 'OpShiftLeftLogical': (196, True, True, (('IdRef', ''), ('IdRef', ''))), - 'OpShiftRightArithmetic': (195, True, True, (('IdRef', ''), ('IdRef', ''))), - 'OpShiftRightLogical': (194, True, True, (('IdRef', ''), ('IdRef', ''))), - 'OpSignBitSet': (160, True, True, (('IdRef', ''),)), - 'OpSizeOf': (321, True, True, (('IdRef', ''),)), - 'OpSource': (3, False, False, (('SourceLanguage', ''), ('LiteralInteger', ''), ('IdRef', '?'), ('LiteralString', '?'))), - 'OpSourceContinued': (2, False, False, (('LiteralString', ''),)), - 'OpSourceExtension': (4, False, False, (('LiteralString', ''),)), - 'OpSpecConstant': (50, True, True, (('LiteralContextDependentNumber', ''),)), - 'OpSpecConstantArchitectureINTEL': (6252, True, True, (('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''))), - 'OpSpecConstantCapabilitiesINTEL': (6253, True, True, (('Capability', '*'),)), - 'OpSpecConstantComposite': (51, True, True, (('IdRef', '*'),)), - 'OpSpecConstantCompositeContinuedINTEL': (6092, False, False, (('IdRef', '*'),)), - 'OpSpecConstantCompositeReplicateEXT': (4462, True, True, (('IdRef', ''),)), - 'OpSpecConstantDataKHR': (5148, True, True, (('LiteralInteger', '*'),)), - 'OpSpecConstantFalse': (49, True, True, ()), - 'OpSpecConstantOp': (52, True, True, (('LiteralSpecConstantOpInteger', ''),)), - 'OpSpecConstantStringAMDX': (5104, False, True, (('LiteralString', ''),)), - 'OpSpecConstantTargetINTEL': (6251, True, True, (('LiteralInteger', ''), ('LiteralInteger', '*'))), - 'OpSpecConstantTrue': (48, True, True, ()), - 'OpStencilAttachmentReadEXT': (4162, True, True, (('IdRef', '?'),)), - 'OpStochasticRoundFToFINTEL': (6217, True, True, (('IdRef', ''), ('IdRef', ''), ('IdRef', '?'))), - 'OpStore': (62, False, False, (('IdRef', ''), ('IdRef', ''), ('MemoryAccess', '?'))), - 'OpString': (7, False, True, (('LiteralString', ''),)), - 'OpSubgroup2DBlockLoadINTEL': (6231, False, False, (('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''))), - 'OpSubgroup2DBlockLoadTransformINTEL': (6232, False, False, (('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''))), - 'OpSubgroup2DBlockLoadTransposeINTEL': (6233, False, False, (('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''))), - 'OpSubgroup2DBlockPrefetchINTEL': (6234, False, False, (('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''))), - 'OpSubgroup2DBlockStoreINTEL': (6235, False, False, (('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''))), - 'OpSubgroupAllEqualKHR': (4430, True, True, (('IdRef', ''),)), - 'OpSubgroupAllKHR': (4428, True, True, (('IdRef', ''),)), - 'OpSubgroupAnyKHR': (4429, True, True, (('IdRef', ''),)), - 'OpSubgroupAvcBmeInitializeINTEL': (5782, True, True, (('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''))), - 'OpSubgroupAvcFmeInitializeINTEL': (5781, True, True, (('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''))), - 'OpSubgroupAvcImeAdjustRefOffsetINTEL': (5751, True, True, (('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''))), - 'OpSubgroupAvcImeConvertToMcePayloadINTEL': (5752, True, True, (('IdRef', ''),)), - 'OpSubgroupAvcImeConvertToMceResultINTEL': (5765, True, True, (('IdRef', ''),)), - 'OpSubgroupAvcImeEvaluateWithDualReferenceINTEL': (5758, True, True, (('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''))), - 'OpSubgroupAvcImeEvaluateWithDualReferenceStreaminINTEL': (5760, True, True, (('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''))), - 'OpSubgroupAvcImeEvaluateWithDualReferenceStreaminoutINTEL': (5764, True, True, (('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''))), - 'OpSubgroupAvcImeEvaluateWithDualReferenceStreamoutINTEL': (5762, True, True, (('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''))), - 'OpSubgroupAvcImeEvaluateWithSingleReferenceINTEL': (5757, True, True, (('IdRef', ''), ('IdRef', ''), ('IdRef', ''))), - 'OpSubgroupAvcImeEvaluateWithSingleReferenceStreaminINTEL': (5759, True, True, (('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''))), - 'OpSubgroupAvcImeEvaluateWithSingleReferenceStreaminoutINTEL': (5763, True, True, (('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''))), - 'OpSubgroupAvcImeEvaluateWithSingleReferenceStreamoutINTEL': (5761, True, True, (('IdRef', ''), ('IdRef', ''), ('IdRef', ''))), - 'OpSubgroupAvcImeGetBorderReachedINTEL': (5776, True, True, (('IdRef', ''), ('IdRef', ''))), - 'OpSubgroupAvcImeGetDualReferenceStreaminINTEL': (5767, True, True, (('IdRef', ''),)), - 'OpSubgroupAvcImeGetSingleReferenceStreaminINTEL': (5766, True, True, (('IdRef', ''),)), - 'OpSubgroupAvcImeGetStreamoutDualReferenceMajorShapeDistortionsINTEL': (5774, True, True, (('IdRef', ''), ('IdRef', ''), ('IdRef', ''))), - 'OpSubgroupAvcImeGetStreamoutDualReferenceMajorShapeMotionVectorsINTEL': (5773, True, True, (('IdRef', ''), ('IdRef', ''), ('IdRef', ''))), - 'OpSubgroupAvcImeGetStreamoutDualReferenceMajorShapeReferenceIdsINTEL': (5775, True, True, (('IdRef', ''), ('IdRef', ''), ('IdRef', ''))), - 'OpSubgroupAvcImeGetStreamoutSingleReferenceMajorShapeDistortionsINTEL': (5771, True, True, (('IdRef', ''), ('IdRef', ''))), - 'OpSubgroupAvcImeGetStreamoutSingleReferenceMajorShapeMotionVectorsINTEL': (5770, True, True, (('IdRef', ''), ('IdRef', ''))), - 'OpSubgroupAvcImeGetStreamoutSingleReferenceMajorShapeReferenceIdsINTEL': (5772, True, True, (('IdRef', ''), ('IdRef', ''))), - 'OpSubgroupAvcImeGetTruncatedSearchIndicationINTEL': (5777, True, True, (('IdRef', ''),)), - 'OpSubgroupAvcImeGetUnidirectionalEarlySearchTerminationINTEL': (5778, True, True, (('IdRef', ''),)), - 'OpSubgroupAvcImeGetWeightingPatternMinimumDistortionINTEL': (5780, True, True, (('IdRef', ''),)), - 'OpSubgroupAvcImeGetWeightingPatternMinimumMotionVectorINTEL': (5779, True, True, (('IdRef', ''),)), - 'OpSubgroupAvcImeInitializeINTEL': (5747, True, True, (('IdRef', ''), ('IdRef', ''), ('IdRef', ''))), - 'OpSubgroupAvcImeRefWindowSizeINTEL': (5750, True, True, (('IdRef', ''), ('IdRef', ''))), - 'OpSubgroupAvcImeSetDualReferenceINTEL': (5749, True, True, (('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''))), - 'OpSubgroupAvcImeSetEarlySearchTerminationThresholdINTEL': (5755, True, True, (('IdRef', ''), ('IdRef', ''))), - 'OpSubgroupAvcImeSetMaxMotionVectorCountINTEL': (5753, True, True, (('IdRef', ''), ('IdRef', ''))), - 'OpSubgroupAvcImeSetSingleReferenceINTEL': (5748, True, True, (('IdRef', ''), ('IdRef', ''), ('IdRef', ''))), - 'OpSubgroupAvcImeSetUnidirectionalMixDisableINTEL': (5754, True, True, (('IdRef', ''),)), - 'OpSubgroupAvcImeSetWeightedSadINTEL': (5756, True, True, (('IdRef', ''), ('IdRef', ''))), - 'OpSubgroupAvcImeStripDualReferenceStreamoutINTEL': (5769, True, True, (('IdRef', ''),)), - 'OpSubgroupAvcImeStripSingleReferenceStreamoutINTEL': (5768, True, True, (('IdRef', ''),)), - 'OpSubgroupAvcMceConvertToImePayloadINTEL': (5732, True, True, (('IdRef', ''),)), - 'OpSubgroupAvcMceConvertToImeResultINTEL': (5733, True, True, (('IdRef', ''),)), - 'OpSubgroupAvcMceConvertToRefPayloadINTEL': (5734, True, True, (('IdRef', ''),)), - 'OpSubgroupAvcMceConvertToRefResultINTEL': (5735, True, True, (('IdRef', ''),)), - 'OpSubgroupAvcMceConvertToSicPayloadINTEL': (5736, True, True, (('IdRef', ''),)), - 'OpSubgroupAvcMceConvertToSicResultINTEL': (5737, True, True, (('IdRef', ''),)), - 'OpSubgroupAvcMceGetBestInterDistortionsINTEL': (5740, True, True, (('IdRef', ''),)), - 'OpSubgroupAvcMceGetDefaultHighPenaltyCostTableINTEL': (5721, True, True, ()), - 'OpSubgroupAvcMceGetDefaultInterBaseMultiReferencePenaltyINTEL': (5713, True, True, (('IdRef', ''), ('IdRef', ''))), - 'OpSubgroupAvcMceGetDefaultInterDirectionPenaltyINTEL': (5717, True, True, (('IdRef', ''), ('IdRef', ''))), - 'OpSubgroupAvcMceGetDefaultInterMotionVectorCostTableINTEL': (5720, True, True, (('IdRef', ''), ('IdRef', ''))), - 'OpSubgroupAvcMceGetDefaultInterShapePenaltyINTEL': (5715, True, True, (('IdRef', ''), ('IdRef', ''))), - 'OpSubgroupAvcMceGetDefaultIntraChromaModeBasePenaltyINTEL': (5727, True, True, ()), - 'OpSubgroupAvcMceGetDefaultIntraLumaModePenaltyINTEL': (5725, True, True, (('IdRef', ''), ('IdRef', ''))), - 'OpSubgroupAvcMceGetDefaultIntraLumaShapePenaltyINTEL': (5719, True, True, (('IdRef', ''), ('IdRef', ''))), - 'OpSubgroupAvcMceGetDefaultLowPenaltyCostTableINTEL': (5723, True, True, ()), - 'OpSubgroupAvcMceGetDefaultMediumPenaltyCostTableINTEL': (5722, True, True, ()), - 'OpSubgroupAvcMceGetDefaultNonDcLumaIntraPenaltyINTEL': (5726, True, True, ()), - 'OpSubgroupAvcMceGetInterDirectionsINTEL': (5743, True, True, (('IdRef', ''),)), - 'OpSubgroupAvcMceGetInterDistortionsINTEL': (5739, True, True, (('IdRef', ''),)), - 'OpSubgroupAvcMceGetInterMajorShapeINTEL': (5741, True, True, (('IdRef', ''),)), - 'OpSubgroupAvcMceGetInterMinorShapeINTEL': (5742, True, True, (('IdRef', ''),)), - 'OpSubgroupAvcMceGetInterMotionVectorCountINTEL': (5744, True, True, (('IdRef', ''),)), - 'OpSubgroupAvcMceGetInterReferenceIdsINTEL': (5745, True, True, (('IdRef', ''),)), - 'OpSubgroupAvcMceGetInterReferenceInterlacedFieldPolaritiesINTEL': (5746, True, True, (('IdRef', ''), ('IdRef', ''), ('IdRef', ''))), - 'OpSubgroupAvcMceGetMotionVectorsINTEL': (5738, True, True, (('IdRef', ''),)), - 'OpSubgroupAvcMceSetAcOnlyHaarINTEL': (5728, True, True, (('IdRef', ''),)), - 'OpSubgroupAvcMceSetDualReferenceInterlacedFieldPolaritiesINTEL': (5731, True, True, (('IdRef', ''), ('IdRef', ''), ('IdRef', ''))), - 'OpSubgroupAvcMceSetInterBaseMultiReferencePenaltyINTEL': (5714, True, True, (('IdRef', ''), ('IdRef', ''))), - 'OpSubgroupAvcMceSetInterDirectionPenaltyINTEL': (5718, True, True, (('IdRef', ''), ('IdRef', ''))), - 'OpSubgroupAvcMceSetInterShapePenaltyINTEL': (5716, True, True, (('IdRef', ''), ('IdRef', ''))), - 'OpSubgroupAvcMceSetMotionVectorCostFunctionINTEL': (5724, True, True, (('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''))), - 'OpSubgroupAvcMceSetSingleReferenceInterlacedFieldPolarityINTEL': (5730, True, True, (('IdRef', ''), ('IdRef', ''))), - 'OpSubgroupAvcMceSetSourceInterlacedFieldPolarityINTEL': (5729, True, True, (('IdRef', ''), ('IdRef', ''))), - 'OpSubgroupAvcRefConvertToMcePayloadINTEL': (5783, True, True, (('IdRef', ''),)), - 'OpSubgroupAvcRefConvertToMceResultINTEL': (5790, True, True, (('IdRef', ''),)), - 'OpSubgroupAvcRefEvaluateWithDualReferenceINTEL': (5787, True, True, (('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''))), - 'OpSubgroupAvcRefEvaluateWithMultiReferenceINTEL': (5788, True, True, (('IdRef', ''), ('IdRef', ''), ('IdRef', ''))), - 'OpSubgroupAvcRefEvaluateWithMultiReferenceInterlacedINTEL': (5789, True, True, (('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''))), - 'OpSubgroupAvcRefEvaluateWithSingleReferenceINTEL': (5786, True, True, (('IdRef', ''), ('IdRef', ''), ('IdRef', ''))), - 'OpSubgroupAvcRefSetBidirectionalMixDisableINTEL': (5784, True, True, (('IdRef', ''),)), - 'OpSubgroupAvcRefSetBilinearFilterEnableINTEL': (5785, True, True, (('IdRef', ''),)), - 'OpSubgroupAvcSicConfigureIpeLumaChromaINTEL': (5794, True, True, (('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''))), - 'OpSubgroupAvcSicConfigureIpeLumaINTEL': (5793, True, True, (('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''))), - 'OpSubgroupAvcSicConfigureSkcINTEL': (5792, True, True, (('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''))), - 'OpSubgroupAvcSicConvertToMcePayloadINTEL': (5796, True, True, (('IdRef', ''),)), - 'OpSubgroupAvcSicConvertToMceResultINTEL': (5808, True, True, (('IdRef', ''),)), - 'OpSubgroupAvcSicEvaluateIpeINTEL': (5803, True, True, (('IdRef', ''), ('IdRef', ''))), - 'OpSubgroupAvcSicEvaluateWithDualReferenceINTEL': (5805, True, True, (('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''))), - 'OpSubgroupAvcSicEvaluateWithMultiReferenceINTEL': (5806, True, True, (('IdRef', ''), ('IdRef', ''), ('IdRef', ''))), - 'OpSubgroupAvcSicEvaluateWithMultiReferenceInterlacedINTEL': (5807, True, True, (('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''))), - 'OpSubgroupAvcSicEvaluateWithSingleReferenceINTEL': (5804, True, True, (('IdRef', ''), ('IdRef', ''), ('IdRef', ''))), - 'OpSubgroupAvcSicGetBestIpeChromaDistortionINTEL': (5811, True, True, (('IdRef', ''),)), - 'OpSubgroupAvcSicGetBestIpeLumaDistortionINTEL': (5810, True, True, (('IdRef', ''),)), - 'OpSubgroupAvcSicGetInterRawSadsINTEL': (5816, True, True, (('IdRef', ''),)), - 'OpSubgroupAvcSicGetIpeChromaModeINTEL': (5813, True, True, (('IdRef', ''),)), - 'OpSubgroupAvcSicGetIpeLumaShapeINTEL': (5809, True, True, (('IdRef', ''),)), - 'OpSubgroupAvcSicGetMotionVectorMaskINTEL': (5795, True, True, (('IdRef', ''), ('IdRef', ''))), - 'OpSubgroupAvcSicGetPackedIpeLumaModesINTEL': (5812, True, True, (('IdRef', ''),)), - 'OpSubgroupAvcSicGetPackedSkcLumaCountThresholdINTEL': (5814, True, True, (('IdRef', ''),)), - 'OpSubgroupAvcSicGetPackedSkcLumaSumThresholdINTEL': (5815, True, True, (('IdRef', ''),)), - 'OpSubgroupAvcSicInitializeINTEL': (5791, True, True, (('IdRef', ''),)), - 'OpSubgroupAvcSicSetBilinearFilterEnableINTEL': (5800, True, True, (('IdRef', ''),)), - 'OpSubgroupAvcSicSetBlockBasedRawSkipSadINTEL': (5802, True, True, (('IdRef', ''), ('IdRef', ''))), - 'OpSubgroupAvcSicSetIntraChromaModeCostFunctionINTEL': (5799, True, True, (('IdRef', ''), ('IdRef', ''))), - 'OpSubgroupAvcSicSetIntraLumaModeCostFunctionINTEL': (5798, True, True, (('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''))), - 'OpSubgroupAvcSicSetIntraLumaShapePenaltyINTEL': (5797, True, True, (('IdRef', ''), ('IdRef', ''))), - 'OpSubgroupAvcSicSetSkcForwardTransformEnableINTEL': (5801, True, True, (('IdRef', ''), ('IdRef', ''))), - 'OpSubgroupBallotKHR': (4421, True, True, (('IdRef', ''),)), - 'OpSubgroupBitcastShuffleINTEL': (6208, True, True, (('IdRef', ''),)), - 'OpSubgroupBlockPrefetchINTEL': (6221, False, False, (('IdRef', ''), ('IdRef', ''), ('MemoryAccess', '?'))), - 'OpSubgroupBlockReadINTEL': (5575, True, True, (('IdRef', ''),)), - 'OpSubgroupBlockWriteINTEL': (5576, False, False, (('IdRef', ''), ('IdRef', ''))), - 'OpSubgroupFirstInvocationKHR': (4422, True, True, (('IdRef', ''),)), - 'OpSubgroupImageBlockReadINTEL': (5577, True, True, (('IdRef', ''), ('IdRef', ''))), - 'OpSubgroupImageBlockWriteINTEL': (5578, False, False, (('IdRef', ''), ('IdRef', ''), ('IdRef', ''))), - 'OpSubgroupImageMediaBlockReadINTEL': (5580, True, True, (('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''))), - 'OpSubgroupImageMediaBlockWriteINTEL': (5581, False, False, (('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''))), - 'OpSubgroupMatrixMultiplyAccumulateINTEL': (6237, True, True, (('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('MatrixMultiplyAccumulateOperands', '?'))), - 'OpSubgroupReadInvocationKHR': (4432, True, True, (('IdRef', ''), ('IdRef', ''))), - 'OpSubgroupShuffleDownINTEL': (5572, True, True, (('IdRef', ''), ('IdRef', ''), ('IdRef', ''))), - 'OpSubgroupShuffleINTEL': (5571, True, True, (('IdRef', ''), ('IdRef', ''))), - 'OpSubgroupShuffleUpINTEL': (5573, True, True, (('IdRef', ''), ('IdRef', ''), ('IdRef', ''))), - 'OpSubgroupShuffleXorINTEL': (5574, True, True, (('IdRef', ''), ('IdRef', ''))), - 'OpSwitch': (251, False, False, (('IdRef', ''), ('IdRef', ''), ('PairLiteralIntegerIdRef', '*'))), - 'OpTaskSequenceAsyncALTERA': (6164, False, False, (('IdRef', ''), ('IdRef', '*'))), - 'OpTaskSequenceAsyncINTEL': (6164, False, False, (('IdRef', ''), ('IdRef', '*'))), - 'OpTaskSequenceCreateALTERA': (6163, True, True, (('IdRef', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''))), - 'OpTaskSequenceCreateINTEL': (6163, True, True, (('IdRef', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''))), - 'OpTaskSequenceGetALTERA': (6165, True, True, (('IdRef', ''),)), - 'OpTaskSequenceGetINTEL': (6165, True, True, (('IdRef', ''),)), - 'OpTaskSequenceReleaseALTERA': (6166, False, False, (('IdRef', ''),)), - 'OpTaskSequenceReleaseINTEL': (6166, False, False, (('IdRef', ''),)), - 'OpTensorLayoutSetBlockSizeNV': (5384, True, True, (('IdRef', ''), ('IdRef', '*'))), - 'OpTensorLayoutSetClampValueNV': (5376, True, True, (('IdRef', ''), ('IdRef', ''))), - 'OpTensorLayoutSetDimensionNV': (5373, True, True, (('IdRef', ''), ('IdRef', '*'))), - 'OpTensorLayoutSetStrideNV': (5374, True, True, (('IdRef', ''), ('IdRef', '*'))), - 'OpTensorLayoutSliceNV': (5375, True, True, (('IdRef', ''), ('IdRef', '*'))), - 'OpTensorQuerySizeARM': (4166, True, True, (('IdRef', ''), ('IdRef', ''))), - 'OpTensorReadARM': (4164, True, True, (('IdRef', ''), ('IdRef', ''), ('TensorOperands', '?'))), - 'OpTensorViewSetClipNV': (5382, True, True, (('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''))), - 'OpTensorViewSetDimensionNV': (5378, True, True, (('IdRef', ''), ('IdRef', '*'))), - 'OpTensorViewSetStrideNV': (5379, True, True, (('IdRef', ''), ('IdRef', '*'))), - 'OpTensorWriteARM': (4165, False, False, (('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('TensorOperands', '?'))), - 'OpTerminateInvocation': (4416, False, False, ()), - 'OpTerminateRayKHR': (4449, False, False, ()), - 'OpTerminateRayNV': (5336, False, False, ()), - 'OpTraceMotionNV': (5338, False, False, (('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''))), - 'OpTraceNV': (5337, False, False, (('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''))), - 'OpTraceRayKHR': (4445, False, False, (('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''))), - 'OpTraceRayMotionNV': (5339, False, False, (('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''))), - 'OpTranspose': (84, True, True, (('IdRef', ''),)), - 'OpTypeAccelerationStructureKHR': (5341, False, True, ()), - 'OpTypeAccelerationStructureNV': (5341, False, True, ()), - 'OpTypeArray': (28, False, True, (('IdRef', ''), ('IdRef', ''))), - 'OpTypeAvcImeDualReferenceStreaminINTEL': (5710, False, True, ()), - 'OpTypeAvcImePayloadINTEL': (5701, False, True, ()), - 'OpTypeAvcImeResultDualReferenceStreamoutINTEL': (5708, False, True, ()), - 'OpTypeAvcImeResultINTEL': (5706, False, True, ()), - 'OpTypeAvcImeResultSingleReferenceStreamoutINTEL': (5707, False, True, ()), - 'OpTypeAvcImeSingleReferenceStreaminINTEL': (5709, False, True, ()), - 'OpTypeAvcMcePayloadINTEL': (5704, False, True, ()), - 'OpTypeAvcMceResultINTEL': (5705, False, True, ()), - 'OpTypeAvcRefPayloadINTEL': (5702, False, True, ()), - 'OpTypeAvcRefResultINTEL': (5711, False, True, ()), - 'OpTypeAvcSicPayloadINTEL': (5703, False, True, ()), - 'OpTypeAvcSicResultINTEL': (5712, False, True, ()), - 'OpTypeBool': (20, False, True, ()), - 'OpTypeBufferEXT': (5115, False, True, (('StorageClass', ''),)), - 'OpTypeBufferSurfaceINTEL': (6086, False, True, (('AccessQualifier', ''),)), - 'OpTypeCooperativeMatrixKHR': (4456, False, True, (('IdRef', ''), ('IdScope', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''))), - 'OpTypeCooperativeMatrixNV': (5358, False, True, (('IdRef', ''), ('IdScope', ''), ('IdRef', ''), ('IdRef', ''))), - 'OpTypeCooperativeVectorNV': (5288, False, True, (('IdRef', ''), ('IdRef', ''))), - 'OpTypeDeviceEvent': (35, False, True, ()), - 'OpTypeEvent': (34, False, True, ()), - 'OpTypeFloat': (22, False, True, (('LiteralInteger', ''), ('FPEncoding', '?'))), - 'OpTypeForwardPointer': (39, False, False, (('IdRef', ''), ('StorageClass', ''))), - 'OpTypeFunction': (33, False, True, (('IdRef', ''), ('IdRef', '*'))), - 'OpTypeGraphARM': (4190, False, True, (('LiteralInteger', ''), ('IdRef', '*'))), - 'OpTypeHitObjectEXT': (5313, False, True, ()), - 'OpTypeHitObjectNV': (5281, False, True, ()), - 'OpTypeImage': (25, False, True, (('IdRef', ''), ('Dim', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('ImageFormat', ''), ('AccessQualifier', '?'))), - 'OpTypeInt': (21, False, True, (('LiteralInteger', ''), ('LiteralInteger', ''))), - 'OpTypeMatrix': (24, False, True, (('IdRef', ''), ('LiteralInteger', ''))), - 'OpTypeNamedBarrier': (327, False, True, ()), - 'OpTypeNodePayloadArrayAMDX': (5076, False, True, (('IdRef', ''),)), - 'OpTypeOpaque': (31, False, True, (('LiteralString', ''),)), - 'OpTypePipe': (38, False, True, (('AccessQualifier', ''),)), - 'OpTypePipeStorage': (322, False, True, ()), - 'OpTypePointer': (32, False, True, (('StorageClass', ''), ('IdRef', ''))), - 'OpTypeQueue': (37, False, True, ()), - 'OpTypeRayQueryKHR': (4472, False, True, ()), - 'OpTypeReserveId': (36, False, True, ()), - 'OpTypeRuntimeArray': (29, False, True, (('IdRef', ''),)), - 'OpTypeSampledImage': (27, False, True, (('IdRef', ''),)), - 'OpTypeSampler': (26, False, True, ()), - 'OpTypeStruct': (30, False, True, (('IdRef', '*'),)), - 'OpTypeStructContinuedINTEL': (6090, False, False, (('IdRef', '*'),)), - 'OpTypeTaskSequenceALTERA': (6199, False, True, ()), - 'OpTypeTaskSequenceINTEL': (6199, False, True, ()), - 'OpTypeTensorARM': (4163, False, True, (('IdRef', ''), ('IdRef', '?'), ('IdRef', '?'))), - 'OpTypeTensorLayoutNV': (5370, False, True, (('IdRef', ''), ('IdRef', ''))), - 'OpTypeTensorViewNV': (5371, False, True, (('IdRef', ''), ('IdRef', ''), ('IdRef', '*'))), - 'OpTypeUntypedPointerKHR': (4417, False, True, (('StorageClass', ''),)), - 'OpTypeVector': (23, False, True, (('IdRef', ''), ('LiteralInteger', ''))), - 'OpTypeVectorIdEXT': (5288, False, True, (('IdRef', ''), ('IdRef', ''))), - 'OpTypeVmeImageINTEL': (5700, False, True, (('IdRef', ''),)), - 'OpTypeVoid': (19, False, True, ()), - 'OpUAddSatINTEL': (5590, True, True, (('IdRef', ''), ('IdRef', ''))), - 'OpUAverageINTEL': (5592, True, True, (('IdRef', ''), ('IdRef', ''))), - 'OpUAverageRoundedINTEL': (5594, True, True, (('IdRef', ''), ('IdRef', ''))), - 'OpUConvert': (113, True, True, (('IdRef', ''),)), - 'OpUCountLeadingZerosINTEL': (5585, True, True, (('IdRef', ''),)), - 'OpUCountTrailingZerosINTEL': (5586, True, True, (('IdRef', ''),)), - 'OpUDiv': (134, True, True, (('IdRef', ''), ('IdRef', ''))), - 'OpUDot': (4451, True, True, (('IdRef', ''), ('IdRef', ''), ('PackedVectorFormat', '?'))), - 'OpUDotAccSat': (4454, True, True, (('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('PackedVectorFormat', '?'))), - 'OpUDotAccSatKHR': (4454, True, True, (('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('PackedVectorFormat', '?'))), - 'OpUDotKHR': (4451, True, True, (('IdRef', ''), ('IdRef', ''), ('PackedVectorFormat', '?'))), - 'OpUGreaterThan': (172, True, True, (('IdRef', ''), ('IdRef', ''))), - 'OpUGreaterThanEqual': (174, True, True, (('IdRef', ''), ('IdRef', ''))), - 'OpULessThan': (176, True, True, (('IdRef', ''), ('IdRef', ''))), - 'OpULessThanEqual': (178, True, True, (('IdRef', ''), ('IdRef', ''))), - 'OpUMod': (137, True, True, (('IdRef', ''), ('IdRef', ''))), - 'OpUMul32x16INTEL': (5598, True, True, (('IdRef', ''), ('IdRef', ''))), - 'OpUMulExtended': (151, True, True, (('IdRef', ''), ('IdRef', ''))), - 'OpUSubSatINTEL': (5596, True, True, (('IdRef', ''), ('IdRef', ''))), - 'OpUndef': (1, True, True, ()), - 'OpUnordered': (163, True, True, (('IdRef', ''), ('IdRef', ''))), - 'OpUnreachable': (255, False, False, ()), - 'OpUntypedAccessChainKHR': (4419, True, True, (('IdRef', ''), ('IdRef', ''), ('IdRef', '*'))), - 'OpUntypedArrayLengthKHR': (4425, True, True, (('IdRef', ''), ('IdRef', ''), ('LiteralInteger', ''))), - 'OpUntypedGroupAsyncCopyKHR': (4434, True, True, (('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('MemoryAccess', '?'), ('MemoryAccess', '?'))), - 'OpUntypedImageTexelPointerEXT': (5126, True, True, (('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''))), - 'OpUntypedInBoundsAccessChainKHR': (4420, True, True, (('IdRef', ''), ('IdRef', ''), ('IdRef', '*'))), - 'OpUntypedInBoundsPtrAccessChainKHR': (4424, True, True, (('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', '*'))), - 'OpUntypedPrefetchKHR': (4426, False, False, (('IdRef', ''), ('IdRef', ''), ('IdRef', '?'), ('IdRef', '?'), ('IdRef', '?'))), - 'OpUntypedPtrAccessChainKHR': (4423, True, True, (('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', '*'))), - 'OpUntypedVariableKHR': (4418, True, True, (('StorageClass', ''), ('IdRef', '?'), ('IdRef', '?'))), - 'OpUntypedVariableLengthArrayINTEL': (6244, True, True, (('IdRef', ''), ('IdRef', ''))), - 'OpVariable': (59, True, True, (('StorageClass', ''), ('IdRef', '?'))), - 'OpVariableLengthArrayINTEL': (5818, True, True, (('IdRef', ''),)), - 'OpVectorExtractDynamic': (77, True, True, (('IdRef', ''), ('IdRef', ''))), - 'OpVectorInsertDynamic': (78, True, True, (('IdRef', ''), ('IdRef', ''), ('IdRef', ''))), - 'OpVectorShuffle': (79, True, True, (('IdRef', ''), ('IdRef', ''), ('LiteralInteger', '*'))), - 'OpVectorTimesMatrix': (144, True, True, (('IdRef', ''), ('IdRef', ''))), - 'OpVectorTimesScalar': (142, True, True, (('IdRef', ''), ('IdRef', ''))), - 'OpVmeImageINTEL': (5699, True, True, (('IdRef', ''), ('IdRef', ''))), - 'OpWritePackedPrimitiveIndices4x8NV': (5299, False, False, (('IdRef', ''), ('IdRef', ''))), - 'OpWritePipe': (275, True, True, (('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''))), - 'OpWritePipeBlockingALTERA': (5947, False, False, (('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''))), - 'OpWritePipeBlockingINTEL': (5947, False, False, (('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''))), -} - -VALUE_ENUMS = { - 'AccessQualifier': {'ReadOnly': (0, ()), 'WriteOnly': (1, ()), 'ReadWrite': (2, ())}, - 'AddressingModel': {'Logical': (0, ()), 'Physical32': (1, ()), 'Physical64': (2, ()), 'PhysicalStorageBuffer64': (5348, ()), 'PhysicalStorageBuffer64EXT': (5348, ())}, - 'BuiltIn': {'Position': (0, ()), 'PointSize': (1, ()), 'ClipDistance': (3, ()), 'CullDistance': (4, ()), 'VertexId': (5, ()), 'InstanceId': (6, ()), 'PrimitiveId': (7, ()), 'InvocationId': (8, ()), 'Layer': (9, ()), 'ViewportIndex': (10, ()), 'TessLevelOuter': (11, ()), 'TessLevelInner': (12, ()), 'TessCoord': (13, ()), 'PatchVertices': (14, ()), 'FragCoord': (15, ()), 'PointCoord': (16, ()), 'FrontFacing': (17, ()), 'SampleId': (18, ()), 'SamplePosition': (19, ()), 'SampleMask': (20, ()), 'FragDepth': (22, ()), 'HelperInvocation': (23, ()), 'NumWorkgroups': (24, ()), 'WorkgroupSize': (25, ()), 'WorkgroupId': (26, ()), 'LocalInvocationId': (27, ()), 'GlobalInvocationId': (28, ()), 'LocalInvocationIndex': (29, ()), 'WorkDim': (30, ()), 'GlobalSize': (31, ()), 'EnqueuedWorkgroupSize': (32, ()), 'GlobalOffset': (33, ()), 'GlobalLinearId': (34, ()), 'SubgroupSize': (36, ()), 'SubgroupMaxSize': (37, ()), 'NumSubgroups': (38, ()), 'NumEnqueuedSubgroups': (39, ()), 'SubgroupId': (40, ()), 'SubgroupLocalInvocationId': (41, ()), 'VertexIndex': (42, ()), 'InstanceIndex': (43, ()), 'CoreIDARM': (4160, ()), 'CoreCountARM': (4161, ()), 'CoreMaxIDARM': (4162, ()), 'WarpIDARM': (4163, ()), 'WarpMaxIDARM': (4164, ()), 'SubgroupEqMask': (4416, ()), 'SubgroupEqMaskKHR': (4416, ()), 'SubgroupGeMask': (4417, ()), 'SubgroupGeMaskKHR': (4417, ()), 'SubgroupGtMask': (4418, ()), 'SubgroupGtMaskKHR': (4418, ()), 'SubgroupLeMask': (4419, ()), 'SubgroupLeMaskKHR': (4419, ()), 'SubgroupLtMask': (4420, ()), 'SubgroupLtMaskKHR': (4420, ()), 'BaseVertex': (4424, ()), 'BaseInstance': (4425, ()), 'DrawIndex': (4426, ()), 'PrimitiveShadingRateKHR': (4432, ()), 'DeviceIndex': (4438, ()), 'ViewIndex': (4440, ()), 'ShadingRateKHR': (4444, ()), 'TileOffsetQCOM': (4492, ()), 'TileDimensionQCOM': (4493, ()), 'TileApronSizeQCOM': (4494, ()), 'BaryCoordNoPerspAMD': (4992, ()), 'BaryCoordNoPerspCentroidAMD': (4993, ()), 'BaryCoordNoPerspSampleAMD': (4994, ()), 'BaryCoordSmoothAMD': (4995, ()), 'BaryCoordSmoothCentroidAMD': (4996, ()), 'BaryCoordSmoothSampleAMD': (4997, ()), 'BaryCoordPullModelAMD': (4998, ()), 'FragStencilRefEXT': (5014, ()), 'RemainingRecursionLevelsAMDX': (5021, ()), 'ShaderIndexAMDX': (5073, ()), 'SamplerHeapEXT': (5122, ()), 'ResourceHeapEXT': (5123, ()), 'HitInstanceLevelAMDX': (5190, ()), 'ViewportMaskNV': (5253, ()), 'SecondaryPositionNV': (5257, ()), 'SecondaryViewportMaskNV': (5258, ()), 'PositionPerViewNV': (5261, ()), 'ViewportMaskPerViewNV': (5262, ()), 'FullyCoveredEXT': (5264, ()), 'TaskCountNV': (5274, ()), 'PrimitiveCountNV': (5275, ()), 'PrimitiveIndicesNV': (5276, ()), 'ClipDistancePerViewNV': (5277, ()), 'CullDistancePerViewNV': (5278, ()), 'LayerPerViewNV': (5279, ()), 'MeshViewCountNV': (5280, ()), 'MeshViewIndicesNV': (5281, ()), 'BaryCoordKHR': (5286, ()), 'BaryCoordNV': (5286, ()), 'BaryCoordNoPerspKHR': (5287, ()), 'BaryCoordNoPerspNV': (5287, ()), 'FragSizeEXT': (5292, ()), 'FragmentSizeNV': (5292, ()), 'FragInvocationCountEXT': (5293, ()), 'InvocationsPerPixelNV': (5293, ()), 'PrimitivePointIndicesEXT': (5294, ()), 'PrimitiveLineIndicesEXT': (5295, ()), 'PrimitiveTriangleIndicesEXT': (5296, ()), 'CullPrimitiveEXT': (5299, ()), 'LaunchIdKHR': (5319, ()), 'LaunchIdNV': (5319, ()), 'LaunchSizeKHR': (5320, ()), 'LaunchSizeNV': (5320, ()), 'WorldRayOriginKHR': (5321, ()), 'WorldRayOriginNV': (5321, ()), 'WorldRayDirectionKHR': (5322, ()), 'WorldRayDirectionNV': (5322, ()), 'ObjectRayOriginKHR': (5323, ()), 'ObjectRayOriginNV': (5323, ()), 'ObjectRayDirectionKHR': (5324, ()), 'ObjectRayDirectionNV': (5324, ()), 'RayTminKHR': (5325, ()), 'RayTminNV': (5325, ()), 'RayTmaxKHR': (5326, ()), 'RayTmaxNV': (5326, ()), 'InstanceCustomIndexKHR': (5327, ()), 'InstanceCustomIndexNV': (5327, ()), 'ObjectToWorldKHR': (5330, ()), 'ObjectToWorldNV': (5330, ()), 'WorldToObjectKHR': (5331, ()), 'WorldToObjectNV': (5331, ()), 'HitTNV': (5332, ()), 'HitKindKHR': (5333, ()), 'HitKindNV': (5333, ()), 'CurrentRayTimeNV': (5334, ()), 'HitTriangleVertexPositionsKHR': (5335, ()), 'HitMicroTriangleVertexPositionsNV': (5337, ()), 'HitMicroTriangleVertexBarycentricsNV': (5344, ()), 'IncomingRayFlagsKHR': (5351, ()), 'IncomingRayFlagsNV': (5351, ()), 'RayGeometryIndexKHR': (5352, ()), 'HitIsSphereNV': (5359, ()), 'HitIsLSSNV': (5360, ()), 'HitSpherePositionNV': (5361, ()), 'WarpsPerSMNV': (5374, ()), 'SMCountNV': (5375, ()), 'WarpIDNV': (5376, ()), 'SMIDNV': (5377, ()), 'HitLSSPositionsNV': (5396, ()), 'HitKindFrontFacingMicroTriangleNV': (5405, ()), 'HitKindBackFacingMicroTriangleNV': (5406, ()), 'HitSphereRadiusNV': (5420, ()), 'HitLSSRadiiNV': (5421, ()), 'ClusterIDNV': (5436, ()), 'CullMaskKHR': (6021, ()), 'DeviceBarrierExecutionValidINTEL': (6186, ()), 'DeviceBarrierValidINTEL': (6186, ())}, - 'Capability': {'Matrix': (0, ()), 'Shader': (1, ()), 'Geometry': (2, ()), 'Tessellation': (3, ()), 'Addresses': (4, ()), 'Linkage': (5, ()), 'Kernel': (6, ()), 'Vector16': (7, ()), 'Float16Buffer': (8, ()), 'Float16': (9, ()), 'Float64': (10, ()), 'Int64': (11, ()), 'Int64Atomics': (12, ()), 'ImageBasic': (13, ()), 'ImageReadWrite': (14, ()), 'ImageMipmap': (15, ()), 'Pipes': (17, ()), 'Groups': (18, ()), 'DeviceEnqueue': (19, ()), 'LiteralSampler': (20, ()), 'AtomicStorage': (21, ()), 'Int16': (22, ()), 'TessellationPointSize': (23, ()), 'GeometryPointSize': (24, ()), 'ImageGatherExtended': (25, ()), 'StorageImageMultisample': (27, ()), 'UniformBufferArrayDynamicIndexing': (28, ()), 'SampledImageArrayDynamicIndexing': (29, ()), 'StorageBufferArrayDynamicIndexing': (30, ()), 'StorageImageArrayDynamicIndexing': (31, ()), 'ClipDistance': (32, ()), 'CullDistance': (33, ()), 'ImageCubeArray': (34, ()), 'SampleRateShading': (35, ()), 'ImageRect': (36, ()), 'SampledRect': (37, ()), 'GenericPointer': (38, ()), 'Int8': (39, ()), 'InputAttachment': (40, ()), 'SparseResidency': (41, ()), 'MinLod': (42, ()), 'Sampled1D': (43, ()), 'Image1D': (44, ()), 'SampledCubeArray': (45, ()), 'SampledBuffer': (46, ()), 'ImageBuffer': (47, ()), 'ImageMSArray': (48, ()), 'StorageImageExtendedFormats': (49, ()), 'ImageQuery': (50, ()), 'DerivativeControl': (51, ()), 'InterpolationFunction': (52, ()), 'TransformFeedback': (53, ()), 'GeometryStreams': (54, ()), 'StorageImageReadWithoutFormat': (55, ()), 'StorageImageWriteWithoutFormat': (56, ()), 'MultiViewport': (57, ()), 'SubgroupDispatch': (58, ()), 'NamedBarrier': (59, ()), 'PipeStorage': (60, ()), 'GroupNonUniform': (61, ()), 'GroupNonUniformVote': (62, ()), 'GroupNonUniformArithmetic': (63, ()), 'GroupNonUniformBallot': (64, ()), 'GroupNonUniformShuffle': (65, ()), 'GroupNonUniformShuffleRelative': (66, ()), 'GroupNonUniformClustered': (67, ()), 'GroupNonUniformQuad': (68, ()), 'ShaderLayer': (69, ()), 'ShaderViewportIndex': (70, ()), 'UniformDecoration': (71, ()), 'CoreBuiltinsARM': (4165, ()), 'TileImageColorReadAccessEXT': (4166, ()), 'TileImageDepthReadAccessEXT': (4167, ()), 'TileImageStencilReadAccessEXT': (4168, ()), 'TensorsARM': (4174, ()), 'StorageTensorArrayDynamicIndexingARM': (4175, ()), 'StorageTensorArrayNonUniformIndexingARM': (4176, ()), 'GraphARM': (4191, ()), 'CooperativeMatrixLayoutsARM': (4201, ()), 'Float8EXT': (4212, ()), 'Float8CooperativeMatrixEXT': (4213, ()), 'Float6EXT': (4228, ()), 'Float4EXT': (4229, ()), 'Float8UnsignedE8M0EXT': (4230, ()), 'MXInt8EXT': (4231, ()), 'BitcastExtractEXT': (4232, ()), 'FragmentShadingRateKHR': (4422, ()), 'SubgroupBallotKHR': (4423, ()), 'DrawParameters': (4427, ()), 'WorkgroupMemoryExplicitLayoutKHR': (4428, ()), 'WorkgroupMemoryExplicitLayout8BitAccessKHR': (4429, ()), 'WorkgroupMemoryExplicitLayout16BitAccessKHR': (4430, ()), 'SubgroupVoteKHR': (4431, ()), 'StorageBuffer16BitAccess': (4433, ()), 'StorageUniformBufferBlock16': (4433, ()), 'UniformAndStorageBuffer16BitAccess': (4434, ()), 'StorageUniform16': (4434, ()), 'StoragePushConstant16': (4435, ()), 'StorageInputOutput16': (4436, ()), 'DeviceGroup': (4437, ()), 'MultiView': (4439, ()), 'VariablePointersStorageBuffer': (4441, ()), 'VariablePointers': (4442, ()), 'AtomicStorageOps': (4445, ()), 'SampleMaskPostDepthCoverage': (4447, ()), 'StorageBuffer8BitAccess': (4448, ()), 'UniformAndStorageBuffer8BitAccess': (4449, ()), 'StoragePushConstant8': (4450, ()), 'DenormPreserve': (4464, ()), 'DenormFlushToZero': (4465, ()), 'SignedZeroInfNanPreserve': (4466, ()), 'RoundingModeRTE': (4467, ()), 'RoundingModeRTZ': (4468, ()), 'RayQueryProvisionalKHR': (4471, ()), 'RayQueryKHR': (4472, ()), 'UntypedPointersKHR': (4473, ()), 'RayTraversalPrimitiveCullingKHR': (4478, ()), 'RayTracingKHR': (4479, ()), 'TextureSampleWeightedQCOM': (4484, ()), 'TextureBoxFilterQCOM': (4485, ()), 'TextureBlockMatchQCOM': (4486, ()), 'TileShadingQCOM': (4495, ()), 'CooperativeMatrixConversionQCOM': (4496, ()), 'TextureBlockMatch2QCOM': (4498, ()), 'BFloat16MulAddQCOM': (4504, ()), 'SubgroupSizeQCOM': (4506, ()), 'MultipleWaitQueuesQCOM': (4539, ()), 'ImageGatherLinearQCOM': (4543, ()), 'ImageGatherExtendedModesQCOM': (4544, ()), 'Float16ImageAMD': (5008, ()), 'ImageGatherBiasLodAMD': (5009, ()), 'FragmentMaskAMD': (5010, ()), 'StencilExportEXT': (5013, ()), 'ImageReadWriteLodAMD': (5015, ()), 'Int64ImageEXT': (5016, ()), 'ShaderClockKHR': (5055, ()), 'ShaderEnqueueAMDX': (5067, ()), 'QuadControlKHR': (5087, ()), 'Int4TypeINTEL': (5112, ()), 'Int4CooperativeMatrixINTEL': (5114, ()), 'BFloat16TypeKHR': (5116, ()), 'BFloat16DotProductKHR': (5117, ()), 'BFloat16CooperativeMatrixKHR': (5118, ()), 'AbortKHR': (5120, ()), 'DescriptorHeapEXT': (5128, ()), 'ConstantDataKHR': (5146, ()), 'PoisonFreezeKHR': (5156, ()), 'WeakLinkageAMD': (5181, ()), 'RayTracingMultiLevelAccelerationStructureAMDX': (5191, ()), 'RayQueryMultiLevelAccelerationStructureAMDX': (5192, ()), 'SampleMaskOverrideCoverageNV': (5249, ()), 'GeometryShaderPassthroughNV': (5251, ()), 'ShaderViewportIndexLayerEXT': (5254, ()), 'ShaderViewportIndexLayerNV': (5254, ()), 'ShaderViewportMaskNV': (5255, ()), 'ShaderStereoViewNV': (5259, ()), 'PerViewAttributesNV': (5260, ()), 'FragmentFullyCoveredEXT': (5265, ()), 'MeshShadingNV': (5266, ()), 'ImageFootprintNV': (5282, ()), 'MeshShadingEXT': (5283, ()), 'FragmentBarycentricKHR': (5284, ()), 'FragmentBarycentricNV': (5284, ()), 'ComputeDerivativeGroupQuadsKHR': (5288, ()), 'ComputeDerivativeGroupQuadsNV': (5288, ()), 'FragmentDensityEXT': (5291, ()), 'ShadingRateNV': (5291, ()), 'GroupNonUniformPartitionedEXT': (5297, ()), 'GroupNonUniformPartitionedNV': (5297, ()), 'ShaderNonUniform': (5301, ()), 'ShaderNonUniformEXT': (5301, ()), 'RuntimeDescriptorArray': (5302, ()), 'RuntimeDescriptorArrayEXT': (5302, ()), 'InputAttachmentArrayDynamicIndexing': (5303, ()), 'InputAttachmentArrayDynamicIndexingEXT': (5303, ()), 'UniformTexelBufferArrayDynamicIndexing': (5304, ()), 'UniformTexelBufferArrayDynamicIndexingEXT': (5304, ()), 'StorageTexelBufferArrayDynamicIndexing': (5305, ()), 'StorageTexelBufferArrayDynamicIndexingEXT': (5305, ()), 'UniformBufferArrayNonUniformIndexing': (5306, ()), 'UniformBufferArrayNonUniformIndexingEXT': (5306, ()), 'SampledImageArrayNonUniformIndexing': (5307, ()), 'SampledImageArrayNonUniformIndexingEXT': (5307, ()), 'StorageBufferArrayNonUniformIndexing': (5308, ()), 'StorageBufferArrayNonUniformIndexingEXT': (5308, ()), 'StorageImageArrayNonUniformIndexing': (5309, ()), 'StorageImageArrayNonUniformIndexingEXT': (5309, ()), 'InputAttachmentArrayNonUniformIndexing': (5310, ()), 'InputAttachmentArrayNonUniformIndexingEXT': (5310, ()), 'UniformTexelBufferArrayNonUniformIndexing': (5311, ()), 'UniformTexelBufferArrayNonUniformIndexingEXT': (5311, ()), 'StorageTexelBufferArrayNonUniformIndexing': (5312, ()), 'StorageTexelBufferArrayNonUniformIndexingEXT': (5312, ()), 'RayTracingPositionFetchKHR': (5336, ()), 'RayTracingNV': (5340, ()), 'RayTracingMotionBlurNV': (5341, ()), 'VulkanMemoryModel': (5345, ()), 'VulkanMemoryModelKHR': (5345, ()), 'VulkanMemoryModelDeviceScope': (5346, ()), 'VulkanMemoryModelDeviceScopeKHR': (5346, ()), 'PhysicalStorageBufferAddresses': (5347, ()), 'PhysicalStorageBufferAddressesEXT': (5347, ()), 'ComputeDerivativeGroupLinearKHR': (5350, ()), 'ComputeDerivativeGroupLinearNV': (5350, ()), 'RayTracingProvisionalKHR': (5353, ()), 'CooperativeMatrixNV': (5357, ()), 'FragmentShaderSampleInterlockEXT': (5363, ()), 'FragmentShaderShadingRateInterlockEXT': (5372, ()), 'ShaderSMBuiltinsNV': (5373, ()), 'FragmentShaderPixelInterlockEXT': (5378, ()), 'DemoteToHelperInvocation': (5379, ()), 'DemoteToHelperInvocationEXT': (5379, ()), 'DisplacementMicromapNV': (5380, ()), 'RayTracingOpacityMicromapKHR': (5381, ()), 'RayTracingOpacityMicromapEXT': (5381, ()), 'ShaderInvocationReorderNV': (5383, ()), 'ShaderInvocationReorderEXT': (5388, ()), 'BindlessTextureNV': (5390, ()), 'RayQueryPositionFetchKHR': (5391, ()), 'CooperativeVectorNV': (5394, ()), 'AtomicFloat16VectorNV': (5404, ()), 'RayTracingDisplacementMicromapNV': (5409, ()), 'RawAccessChainsNV': (5414, ()), 'RayTracingSpheresGeometryNV': (5418, ()), 'RayTracingLinearSweptSpheresGeometryNV': (5419, ()), 'PushConstantBanksNV': (5423, ()), 'LongVectorEXT': (5425, ()), 'Shader64BitIndexingEXT': (5426, ()), 'CooperativeMatrixConversionsEXT': (5429, ()), 'CooperativeMatrixReductionsEXT': (5430, ()), 'CooperativeMatrixReductionsNV': (5430, ()), 'CooperativeMatrixConversionsNV': (5431, ()), 'CooperativeMatrixPerElementOperationsEXT': (5432, ()), 'CooperativeMatrixPerElementOperationsNV': (5432, ()), 'CooperativeMatrixTensorAddressingNV': (5433, ()), 'CooperativeMatrixBlockLoadsNV': (5434, ()), 'CooperativeVectorTrainingNV': (5435, ()), 'RayTracingClusterAccelerationStructureNV': (5437, ()), 'CooperativeMatrixGetCoordinateEXT': (5438, ()), 'TensorAddressingNV': (5439, ()), 'CooperativeMatrixDecodeVectorNV': (5447, ()), 'SubgroupShuffleINTEL': (5568, ()), 'SubgroupBufferBlockIOINTEL': (5569, ()), 'SubgroupImageBlockIOINTEL': (5570, ()), 'SubgroupImageMediaBlockIOINTEL': (5579, ()), 'RoundToInfinityINTEL': (5582, ()), 'FloatingPointModeINTEL': (5583, ()), 'IntegerFunctions2INTEL': (5584, ()), 'FunctionPointersINTEL': (5603, ()), 'IndirectReferencesINTEL': (5604, ()), 'AsmINTEL': (5606, ()), 'AtomicFloat32MinMaxEXT': (5612, ()), 'AtomicFloat64MinMaxEXT': (5613, ()), 'AtomicFloat16MinMaxEXT': (5616, ()), 'VectorComputeINTEL': (5617, ()), 'VectorAnyINTEL': (5619, ()), 'ExpectAssumeKHR': (5629, ()), 'SubgroupAvcMotionEstimationINTEL': (5696, ()), 'SubgroupAvcMotionEstimationIntraINTEL': (5697, ()), 'SubgroupAvcMotionEstimationChromaINTEL': (5698, ()), 'VariableLengthArrayINTEL': (5817, ()), 'FunctionFloatControlINTEL': (5821, ()), 'FPGAMemoryAttributesALTERA': (5824, ()), 'FPGAMemoryAttributesINTEL': (5824, ()), 'FPFastMathModeINTEL': (5837, ()), 'ArbitraryPrecisionIntegersALTERA': (5844, ()), 'ArbitraryPrecisionIntegersINTEL': (5844, ()), 'ArbitraryPrecisionFloatingPointALTERA': (5845, ()), 'ArbitraryPrecisionFloatingPointINTEL': (5845, ()), 'UnstructuredLoopControlsINTEL': (5886, ()), 'FPGALoopControlsALTERA': (5888, ()), 'FPGALoopControlsINTEL': (5888, ()), 'KernelAttributesINTEL': (5892, ()), 'FPGAKernelAttributesINTEL': (5897, ()), 'FPGAMemoryAccessesALTERA': (5898, ()), 'FPGAMemoryAccessesINTEL': (5898, ()), 'FPGAClusterAttributesALTERA': (5904, ()), 'FPGAClusterAttributesINTEL': (5904, ()), 'LoopFuseALTERA': (5906, ()), 'LoopFuseINTEL': (5906, ()), 'FPGADSPControlALTERA': (5908, ()), 'FPGADSPControlINTEL': (5908, ()), 'MemoryAccessAliasingINTEL': (5910, ()), 'FPGAInvocationPipeliningAttributesALTERA': (5916, ()), 'FPGAInvocationPipeliningAttributesINTEL': (5916, ()), 'FPGABufferLocationALTERA': (5920, ()), 'FPGABufferLocationINTEL': (5920, ()), 'ArbitraryPrecisionFixedPointALTERA': (5922, ()), 'ArbitraryPrecisionFixedPointINTEL': (5922, ()), 'USMStorageClassesALTERA': (5935, ()), 'USMStorageClassesINTEL': (5935, ()), 'RuntimeAlignedAttributeALTERA': (5939, ()), 'RuntimeAlignedAttributeINTEL': (5939, ()), 'IOPipesALTERA': (5943, ()), 'IOPipesINTEL': (5943, ()), 'BlockingPipesALTERA': (5945, ()), 'BlockingPipesINTEL': (5945, ()), 'FPGARegALTERA': (5948, ()), 'FPGARegINTEL': (5948, ()), 'DotProductInputAll': (6016, ()), 'DotProductInputAllKHR': (6016, ()), 'DotProductInput4x8Bit': (6017, ()), 'DotProductInput4x8BitKHR': (6017, ()), 'DotProductInput4x8BitPacked': (6018, ()), 'DotProductInput4x8BitPackedKHR': (6018, ()), 'DotProduct': (6019, ()), 'DotProductKHR': (6019, ()), 'RayCullMaskKHR': (6020, ()), 'CooperativeMatrixKHR': (6022, ()), 'ReplicatedCompositesEXT': (6024, ()), 'BitInstructions': (6025, ()), 'GroupNonUniformRotateKHR': (6026, ()), 'FloatControls2': (6029, ()), 'FMAKHR': (6030, ()), 'RayTracingOpacityMicromapExecutionModeKHR': (6032, ()), 'AtomicFloat32AddEXT': (6033, ()), 'AtomicFloat64AddEXT': (6034, ()), 'LongCompositesINTEL': (6089, ()), 'OptNoneEXT': (6094, ()), 'OptNoneINTEL': (6094, ()), 'AtomicFloat16AddEXT': (6095, ()), 'DebugInfoModuleINTEL': (6114, ()), 'BFloat16ConversionINTEL': (6115, ()), 'SplitBarrierEXT': (6141, ()), 'SplitBarrierINTEL': (6141, ()), 'ArithmeticFenceEXT': (6144, ()), 'FPGAClusterAttributesV2ALTERA': (6150, ()), 'FPGAClusterAttributesV2INTEL': (6150, ()), 'FPGAKernelAttributesv2INTEL': (6161, ()), 'TaskSequenceALTERA': (6162, ()), 'TaskSequenceINTEL': (6162, ()), 'FPMaxErrorINTEL': (6169, ()), 'FPGALatencyControlALTERA': (6171, ()), 'FPGALatencyControlINTEL': (6171, ()), 'FPGAArgumentInterfacesALTERA': (6174, ()), 'FPGAArgumentInterfacesINTEL': (6174, ()), 'DeviceBarrierINTEL': (6185, ()), 'GlobalVariableHostAccessINTEL': (6187, ()), 'GlobalVariableFPGADecorationsALTERA': (6189, ()), 'GlobalVariableFPGADecorationsINTEL': (6189, ()), 'SubgroupBitcastShuffleINTEL': (6207, ()), 'FloatConversionsFToFINTEL': (6215, ()), 'FloatConversionsFToSINTEL': (6216, ()), 'SubgroupBufferPrefetchINTEL': (6220, ()), 'BFloat16ArithmeticEXT': (6226, ()), 'Subgroup2DBlockIOINTEL': (6228, ()), 'Subgroup2DBlockTransformINTEL': (6229, ()), 'Subgroup2DBlockTransposeINTEL': (6230, ()), 'SubgroupMatrixMultiplyAccumulateINTEL': (6236, ()), 'TernaryBitwiseFunctionINTEL': (6241, ()), 'UntypedVariableLengthArrayINTEL': (6243, ()), 'SpecConditionalINTEL': (6245, ()), 'FunctionVariantsINTEL': (6246, ()), 'AtomicBFloat16AddINTEL': (6255, ()), 'AtomicBFloat16MinMaxINTEL': (6256, ()), 'PredicatedIOINTEL': (6257, ()), 'AtomicInt16CompareExchangeINTEL': (6260, ()), 'Int16AtomicsINTEL': (6261, ()), 'AtomicBFloat16LoadStoreINTEL': (6262, ()), 'RoundedDivideSqrtINTEL': (6265, ()), 'PauseINTEL': (6266, ()), 'GroupUniformArithmeticKHR': (6400, ()), 'TensorFloat32RoundingINTEL': (6425, ()), 'MaskedGatherScatterINTEL': (6427, ()), 'CacheControlsINTEL': (6441, ()), 'RegisterLimitsINTEL': (6460, ()), 'BindlessImagesINTEL': (6528, ()), 'DotProductFloat16AccFloat32VALVE': (6912, ()), 'DotProductFloat16AccFloat16VALVE': (6913, ()), 'DotProductBFloat16AccVALVE': (6914, ()), 'DotProductFloat8AccFloat32VALVE': (6915, ()), 'IntrinsicSAMSUNG': (7041, ())}, - 'ComponentType': {'Float16NV': (0, ()), 'Float32NV': (1, ()), 'Float64NV': (2, ()), 'SignedInt8NV': (3, ()), 'SignedInt16NV': (4, ()), 'SignedInt32NV': (5, ()), 'SignedInt64NV': (6, ()), 'UnsignedInt8NV': (7, ()), 'UnsignedInt16NV': (8, ()), 'UnsignedInt32NV': (9, ()), 'UnsignedInt64NV': (10, ()), 'SignedInt8PackedNV': (1000491000, ()), 'UnsignedInt8PackedNV': (1000491001, ()), 'FloatE4M3NV': (1000491002, ()), 'FloatE5M2NV': (1000491003, ())}, - 'CooperativeMatrixLayout': {'RowMajorKHR': (0, ()), 'ColumnMajorKHR': (1, ()), 'RowBlockedInterleavedARM': (4202, ()), 'ColumnBlockedInterleavedARM': (4203, ())}, - 'CooperativeMatrixUse': {'MatrixAKHR': (0, ()), 'MatrixBKHR': (1, ()), 'MatrixAccumulatorKHR': (2, ())}, - 'CooperativeVectorMatrixLayout': {'RowMajorNV': (0, ()), 'ColumnMajorNV': (1, ()), 'InferencingOptimalNV': (2, ()), 'TrainingOptimalNV': (3, ())}, - 'Decoration': {'RelaxedPrecision': (0, ()), 'SpecId': (1, ('LiteralInteger',)), 'Block': (2, ()), 'BufferBlock': (3, ()), 'RowMajor': (4, ()), 'ColMajor': (5, ()), 'ArrayStride': (6, ('LiteralInteger',)), 'MatrixStride': (7, ('LiteralInteger',)), 'GLSLShared': (8, ()), 'GLSLPacked': (9, ()), 'CPacked': (10, ()), 'BuiltIn': (11, ('BuiltIn',)), 'NoPerspective': (13, ()), 'Flat': (14, ()), 'Patch': (15, ()), 'Centroid': (16, ()), 'Sample': (17, ()), 'Invariant': (18, ()), 'Restrict': (19, ()), 'Aliased': (20, ()), 'Volatile': (21, ()), 'Constant': (22, ()), 'Coherent': (23, ()), 'NonWritable': (24, ()), 'NonReadable': (25, ()), 'Uniform': (26, ()), 'UniformId': (27, ('IdScope',)), 'SaturatedConversion': (28, ()), 'Stream': (29, ('LiteralInteger',)), 'Location': (30, ('LiteralInteger',)), 'Component': (31, ('LiteralInteger',)), 'Index': (32, ('LiteralInteger',)), 'Binding': (33, ('LiteralInteger',)), 'DescriptorSet': (34, ('LiteralInteger',)), 'Offset': (35, ('LiteralInteger',)), 'XfbBuffer': (36, ('LiteralInteger',)), 'XfbStride': (37, ('LiteralInteger',)), 'FuncParamAttr': (38, ('FunctionParameterAttribute',)), 'FPRoundingMode': (39, ('FPRoundingMode',)), 'FPFastMathMode': (40, ('FPFastMathMode',)), 'LinkageAttributes': (41, ('LiteralString', 'LinkageType')), 'NoContraction': (42, ()), 'InputAttachmentIndex': (43, ('LiteralInteger',)), 'Alignment': (44, ('LiteralInteger',)), 'MaxByteOffset': (45, ('LiteralInteger',)), 'AlignmentId': (46, ('IdRef',)), 'MaxByteOffsetId': (47, ('IdRef',)), 'SaturatedToLargestFloat8NormalConversionEXT': (4216, ()), 'NoSignedWrap': (4469, ()), 'NoUnsignedWrap': (4470, ()), 'WeightTextureQCOM': (4487, ()), 'BlockMatchTextureQCOM': (4488, ()), 'BlockMatchSamplerQCOM': (4499, ()), 'ExplicitInterpAMD': (4999, ()), 'NodeSharesPayloadLimitsWithAMDX': (5019, ('IdRef',)), 'NodeMaxPayloadsAMDX': (5020, ('IdRef',)), 'TrackFinishWritingAMDX': (5078, ()), 'PayloadNodeNameAMDX': (5091, ('IdRef',)), 'PayloadNodeBaseIndexAMDX': (5098, ('IdRef',)), 'PayloadNodeSparseArrayAMDX': (5099, ()), 'PayloadNodeArraySizeAMDX': (5100, ('IdRef',)), 'PayloadDispatchIndirectAMDX': (5105, ()), 'ArrayStrideIdEXT': (5124, ('IdRef',)), 'OffsetIdEXT': (5125, ('IdRef',)), 'UTFEncodedKHR': (5145, ()), 'OverrideCoverageNV': (5248, ()), 'PassthroughNV': (5250, ()), 'ViewportRelativeNV': (5252, ()), 'SecondaryViewportRelativeNV': (5256, ('LiteralInteger',)), 'PerPrimitiveEXT': (5271, ()), 'PerPrimitiveNV': (5271, ()), 'PerViewNV': (5272, ()), 'PerTaskNV': (5273, ()), 'PerVertexKHR': (5285, ()), 'PerVertexNV': (5285, ()), 'NonUniform': (5300, ()), 'NonUniformEXT': (5300, ()), 'RestrictPointer': (5355, ()), 'RestrictPointerEXT': (5355, ()), 'AliasedPointer': (5356, ()), 'AliasedPointerEXT': (5356, ()), 'MemberOffsetNV': (5358, ('LiteralInteger',)), 'HitObjectShaderRecordBufferNV': (5386, ()), 'HitObjectShaderRecordBufferEXT': (5389, ()), 'BankNV': (5397, ('LiteralInteger',)), 'BindlessSamplerNV': (5398, ()), 'BindlessImageNV': (5399, ()), 'BoundSamplerNV': (5400, ()), 'BoundImageNV': (5401, ()), 'CooperativeMatrixTransposeEXT': (5440, ()), 'SIMTCallINTEL': (5599, ('LiteralInteger',)), 'ReferencedIndirectlyINTEL': (5602, ()), 'ClobberINTEL': (5607, ('LiteralString',)), 'SideEffectsINTEL': (5608, ()), 'VectorComputeVariableINTEL': (5624, ()), 'FuncParamIOKindINTEL': (5625, ('LiteralInteger',)), 'VectorComputeFunctionINTEL': (5626, ()), 'StackCallINTEL': (5627, ()), 'GlobalVariableOffsetINTEL': (5628, ('LiteralInteger',)), 'CounterBuffer': (5634, ('IdRef',)), 'HlslCounterBufferGOOGLE': (5634, ('IdRef',)), 'UserSemantic': (5635, ('LiteralString',)), 'HlslSemanticGOOGLE': (5635, ('LiteralString',)), 'UserTypeGOOGLE': (5636, ('LiteralString',)), 'FunctionRoundingModeINTEL': (5822, ('LiteralInteger', 'FPRoundingMode')), 'FunctionDenormModeINTEL': (5823, ('LiteralInteger', 'FPDenormMode')), 'RegisterALTERA': (5825, ()), 'RegisterINTEL': (5825, ()), 'MemoryALTERA': (5826, ('LiteralString',)), 'MemoryINTEL': (5826, ('LiteralString',)), 'NumbanksALTERA': (5827, ('LiteralInteger',)), 'NumbanksINTEL': (5827, ('LiteralInteger',)), 'BankwidthALTERA': (5828, ('LiteralInteger',)), 'BankwidthINTEL': (5828, ('LiteralInteger',)), 'MaxPrivateCopiesALTERA': (5829, ('LiteralInteger',)), 'MaxPrivateCopiesINTEL': (5829, ('LiteralInteger',)), 'SinglepumpALTERA': (5830, ()), 'SinglepumpINTEL': (5830, ()), 'DoublepumpALTERA': (5831, ()), 'DoublepumpINTEL': (5831, ()), 'MaxReplicatesALTERA': (5832, ('LiteralInteger',)), 'MaxReplicatesINTEL': (5832, ('LiteralInteger',)), 'SimpleDualPortALTERA': (5833, ()), 'SimpleDualPortINTEL': (5833, ()), 'MergeALTERA': (5834, ('LiteralString', 'LiteralString')), 'MergeINTEL': (5834, ('LiteralString', 'LiteralString')), 'BankBitsALTERA': (5835, ('LiteralInteger',)), 'BankBitsINTEL': (5835, ('LiteralInteger',)), 'ForcePow2DepthALTERA': (5836, ('LiteralInteger',)), 'ForcePow2DepthINTEL': (5836, ('LiteralInteger',)), 'StridesizeALTERA': (5883, ('LiteralInteger',)), 'StridesizeINTEL': (5883, ('LiteralInteger',)), 'WordsizeALTERA': (5884, ('LiteralInteger',)), 'WordsizeINTEL': (5884, ('LiteralInteger',)), 'TrueDualPortALTERA': (5885, ()), 'TrueDualPortINTEL': (5885, ()), 'BurstCoalesceALTERA': (5899, ()), 'BurstCoalesceINTEL': (5899, ()), 'CacheSizeALTERA': (5900, ('LiteralInteger',)), 'CacheSizeINTEL': (5900, ('LiteralInteger',)), 'DontStaticallyCoalesceALTERA': (5901, ()), 'DontStaticallyCoalesceINTEL': (5901, ()), 'PrefetchALTERA': (5902, ('LiteralInteger',)), 'PrefetchINTEL': (5902, ('LiteralInteger',)), 'StallEnableALTERA': (5905, ()), 'StallEnableINTEL': (5905, ()), 'FuseLoopsInFunctionALTERA': (5907, ()), 'FuseLoopsInFunctionINTEL': (5907, ()), 'MathOpDSPModeALTERA': (5909, ('LiteralInteger', 'LiteralInteger')), 'MathOpDSPModeINTEL': (5909, ('LiteralInteger', 'LiteralInteger')), 'AliasScopeINTEL': (5914, ('IdRef',)), 'NoAliasINTEL': (5915, ('IdRef',)), 'InitiationIntervalALTERA': (5917, ('LiteralInteger',)), 'InitiationIntervalINTEL': (5917, ('LiteralInteger',)), 'MaxConcurrencyALTERA': (5918, ('LiteralInteger',)), 'MaxConcurrencyINTEL': (5918, ('LiteralInteger',)), 'PipelineEnableALTERA': (5919, ('LiteralInteger',)), 'PipelineEnableINTEL': (5919, ('LiteralInteger',)), 'BufferLocationALTERA': (5921, ('LiteralInteger',)), 'BufferLocationINTEL': (5921, ('LiteralInteger',)), 'IOPipeStorageALTERA': (5944, ('LiteralInteger',)), 'IOPipeStorageINTEL': (5944, ('LiteralInteger',)), 'FunctionFloatingPointModeINTEL': (6080, ('LiteralInteger', 'FPOperationMode')), 'SingleElementVectorINTEL': (6085, ()), 'VectorComputeCallableFunctionINTEL': (6087, ()), 'MediaBlockIOINTEL': (6140, ()), 'StallFreeALTERA': (6151, ()), 'StallFreeINTEL': (6151, ()), 'FPMaxErrorDecorationINTEL': (6170, ('LiteralFloat',)), 'LatencyControlLabelALTERA': (6172, ('LiteralInteger',)), 'LatencyControlLabelINTEL': (6172, ('LiteralInteger',)), 'LatencyControlConstraintALTERA': (6173, ('LiteralInteger', 'LiteralInteger', 'LiteralInteger')), 'LatencyControlConstraintINTEL': (6173, ('LiteralInteger', 'LiteralInteger', 'LiteralInteger')), 'ConduitKernelArgumentALTERA': (6175, ()), 'ConduitKernelArgumentINTEL': (6175, ()), 'RegisterMapKernelArgumentALTERA': (6176, ()), 'RegisterMapKernelArgumentINTEL': (6176, ()), 'MMHostInterfaceAddressWidthALTERA': (6177, ('LiteralInteger',)), 'MMHostInterfaceAddressWidthINTEL': (6177, ('LiteralInteger',)), 'MMHostInterfaceDataWidthALTERA': (6178, ('LiteralInteger',)), 'MMHostInterfaceDataWidthINTEL': (6178, ('LiteralInteger',)), 'MMHostInterfaceLatencyALTERA': (6179, ('LiteralInteger',)), 'MMHostInterfaceLatencyINTEL': (6179, ('LiteralInteger',)), 'MMHostInterfaceReadWriteModeALTERA': (6180, ('AccessQualifier',)), 'MMHostInterfaceReadWriteModeINTEL': (6180, ('AccessQualifier',)), 'MMHostInterfaceMaxBurstALTERA': (6181, ('LiteralInteger',)), 'MMHostInterfaceMaxBurstINTEL': (6181, ('LiteralInteger',)), 'MMHostInterfaceWaitRequestALTERA': (6182, ('LiteralInteger',)), 'MMHostInterfaceWaitRequestINTEL': (6182, ('LiteralInteger',)), 'StableKernelArgumentALTERA': (6183, ()), 'StableKernelArgumentINTEL': (6183, ()), 'HostAccessINTEL': (6188, ('HostAccessQualifier', 'LiteralString')), 'InitModeALTERA': (6190, ('InitializationModeQualifier',)), 'InitModeINTEL': (6190, ('InitializationModeQualifier',)), 'ImplementInRegisterMapALTERA': (6191, ('LiteralInteger',)), 'ImplementInRegisterMapINTEL': (6191, ('LiteralInteger',)), 'ConditionalINTEL': (6247, ('IdRef',)), 'CacheControlLoadINTEL': (6442, ('LiteralInteger', 'LoadCacheControl')), 'CacheControlStoreINTEL': (6443, ('LiteralInteger', 'StoreCacheControl')), 'IntrinsicSAMSUNG': (7040, ('LiteralInteger',))}, - 'Dim': {'1D': (0, ()), '2D': (1, ()), '3D': (2, ()), 'Cube': (3, ()), 'Rect': (4, ()), 'Buffer': (5, ()), 'SubpassData': (6, ()), 'TileImageDataEXT': (4173, ())}, - 'ExecutionMode': {'Invocations': (0, ('LiteralInteger',)), 'SpacingEqual': (1, ()), 'SpacingFractionalEven': (2, ()), 'SpacingFractionalOdd': (3, ()), 'VertexOrderCw': (4, ()), 'VertexOrderCcw': (5, ()), 'PixelCenterInteger': (6, ()), 'OriginUpperLeft': (7, ()), 'OriginLowerLeft': (8, ()), 'EarlyFragmentTests': (9, ()), 'PointMode': (10, ()), 'Xfb': (11, ()), 'DepthReplacing': (12, ()), 'DepthGreater': (14, ()), 'DepthLess': (15, ()), 'DepthUnchanged': (16, ()), 'LocalSize': (17, ('LiteralInteger', 'LiteralInteger', 'LiteralInteger')), 'LocalSizeHint': (18, ('LiteralInteger', 'LiteralInteger', 'LiteralInteger')), 'InputPoints': (19, ()), 'InputLines': (20, ()), 'InputLinesAdjacency': (21, ()), 'Triangles': (22, ()), 'InputTrianglesAdjacency': (23, ()), 'Quads': (24, ()), 'Isolines': (25, ()), 'OutputVertices': (26, ('LiteralInteger',)), 'OutputPoints': (27, ()), 'OutputLineStrip': (28, ()), 'OutputTriangleStrip': (29, ()), 'VecTypeHint': (30, ('LiteralInteger',)), 'ContractionOff': (31, ()), 'Initializer': (33, ()), 'Finalizer': (34, ()), 'SubgroupSize': (35, ('LiteralInteger',)), 'SubgroupsPerWorkgroup': (36, ('LiteralInteger',)), 'SubgroupsPerWorkgroupId': (37, ('IdRef',)), 'LocalSizeId': (38, ('IdRef', 'IdRef', 'IdRef')), 'LocalSizeHintId': (39, ('IdRef', 'IdRef', 'IdRef')), 'NonCoherentColorAttachmentReadEXT': (4169, ()), 'NonCoherentDepthAttachmentReadEXT': (4170, ()), 'NonCoherentStencilAttachmentReadEXT': (4171, ()), 'SubgroupUniformControlFlowKHR': (4421, ()), 'PostDepthCoverage': (4446, ()), 'DenormPreserve': (4459, ('LiteralInteger',)), 'DenormFlushToZero': (4460, ('LiteralInteger',)), 'SignedZeroInfNanPreserve': (4461, ('LiteralInteger',)), 'RoundingModeRTE': (4462, ('LiteralInteger',)), 'RoundingModeRTZ': (4463, ('LiteralInteger',)), 'NonCoherentTileAttachmentReadQCOM': (4489, ()), 'TileShadingRateQCOM': (4490, ('LiteralInteger', 'LiteralInteger', 'LiteralInteger')), 'SubgroupSizeHalfQCOM': (4507, ()), 'SubgroupSizeFullQCOM': (4508, ()), 'EarlyAndLateFragmentTestsAMD': (5017, ()), 'StencilRefReplacingEXT': (5027, ()), 'CoalescingAMDX': (5069, ()), 'IsApiEntryAMDX': (5070, ('IdRef',)), 'MaxNodeRecursionAMDX': (5071, ('IdRef',)), 'StaticNumWorkgroupsAMDX': (5072, ('IdRef', 'IdRef', 'IdRef')), 'ShaderIndexAMDX': (5073, ('IdRef',)), 'MaxNumWorkgroupsAMDX': (5077, ('IdRef', 'IdRef', 'IdRef')), 'StencilRefUnchangedFrontAMD': (5079, ()), 'StencilRefGreaterFrontAMD': (5080, ()), 'StencilRefLessFrontAMD': (5081, ()), 'StencilRefUnchangedBackAMD': (5082, ()), 'StencilRefGreaterBackAMD': (5083, ()), 'StencilRefLessBackAMD': (5084, ()), 'QuadDerivativesKHR': (5088, ()), 'RequireFullQuadsKHR': (5089, ()), 'SharesInputWithAMDX': (5102, ('IdRef', 'IdRef')), 'ArithmeticPoisonKHR': (5157, ()), 'OutputLinesEXT': (5269, ()), 'OutputLinesNV': (5269, ()), 'OutputPrimitivesEXT': (5270, ('LiteralInteger',)), 'OutputPrimitivesNV': (5270, ('LiteralInteger',)), 'DerivativeGroupQuadsKHR': (5289, ()), 'DerivativeGroupQuadsNV': (5289, ()), 'DerivativeGroupLinearKHR': (5290, ()), 'DerivativeGroupLinearNV': (5290, ()), 'OutputTrianglesEXT': (5298, ()), 'OutputTrianglesNV': (5298, ()), 'PixelInterlockOrderedEXT': (5366, ()), 'PixelInterlockUnorderedEXT': (5367, ()), 'SampleInterlockOrderedEXT': (5368, ()), 'SampleInterlockUnorderedEXT': (5369, ()), 'ShadingRateInterlockOrderedEXT': (5370, ()), 'ShadingRateInterlockUnorderedEXT': (5371, ()), 'Shader64BitIndexingEXT': (5427, ()), 'SharedLocalMemorySizeINTEL': (5618, ('LiteralInteger',)), 'RoundingModeRTPINTEL': (5620, ('LiteralInteger',)), 'RoundingModeRTNINTEL': (5621, ('LiteralInteger',)), 'FloatingPointModeALTINTEL': (5622, ('LiteralInteger',)), 'FloatingPointModeIEEEINTEL': (5623, ('LiteralInteger',)), 'MaxWorkgroupSizeINTEL': (5893, ('LiteralInteger', 'LiteralInteger', 'LiteralInteger')), 'MaxWorkDimINTEL': (5894, ('LiteralInteger',)), 'NoGlobalOffsetINTEL': (5895, ()), 'NumSIMDWorkitemsINTEL': (5896, ('LiteralInteger',)), 'SchedulerTargetFmaxMhzINTEL': (5903, ('LiteralInteger',)), 'MaximallyReconvergesKHR': (6023, ()), 'FPFastMathDefault': (6028, ('IdRef', 'IdRef')), 'OpacityMicromapIdKHR': (6031, ('IdRef',)), 'StreamingInterfaceINTEL': (6154, ('LiteralInteger',)), 'RegisterMapInterfaceINTEL': (6160, ('LiteralInteger',)), 'NamedBarrierCountINTEL': (6417, ('LiteralInteger',)), 'MaximumRegistersINTEL': (6461, ('LiteralInteger',)), 'MaximumRegistersIdINTEL': (6462, ('IdRef',)), 'NamedMaximumRegistersINTEL': (6463, ('NamedMaximumNumberOfRegisters',))}, - 'ExecutionModel': {'Vertex': (0, ()), 'TessellationControl': (1, ()), 'TessellationEvaluation': (2, ()), 'Geometry': (3, ()), 'Fragment': (4, ()), 'GLCompute': (5, ()), 'Kernel': (6, ()), 'TaskNV': (5267, ()), 'MeshNV': (5268, ()), 'RayGenerationKHR': (5313, ()), 'RayGenerationNV': (5313, ()), 'IntersectionKHR': (5314, ()), 'IntersectionNV': (5314, ()), 'AnyHitKHR': (5315, ()), 'AnyHitNV': (5315, ()), 'ClosestHitKHR': (5316, ()), 'ClosestHitNV': (5316, ()), 'MissKHR': (5317, ()), 'MissNV': (5317, ()), 'CallableKHR': (5318, ()), 'CallableNV': (5318, ()), 'TaskEXT': (5364, ()), 'MeshEXT': (5365, ())}, - 'FPDenormMode': {'Preserve': (0, ()), 'FlushToZero': (1, ())}, - 'FPEncoding': {'BFloat16KHR': (0, ()), 'Float8E4M3EXT': (4214, ()), 'Float8E5M2EXT': (4215, ()), 'Float6E2M3EXT': (4223, ()), 'Float6E3M2EXT': (4224, ()), 'Float4E2M1EXT': (4225, ()), 'Float8UnsignedE8M0EXT': (4226, ()), 'MXInt8EXT': (4227, ())}, - 'FPOperationMode': {'IEEE': (0, ()), 'ALT': (1, ())}, - 'FPRoundingMode': {'RTE': (0, ()), 'RTZ': (1, ()), 'RTP': (2, ()), 'RTN': (3, ())}, - 'FunctionParameterAttribute': {'Zext': (0, ()), 'Sext': (1, ()), 'ByVal': (2, ()), 'Sret': (3, ()), 'NoAlias': (4, ()), 'NoCapture': (5, ()), 'NoWrite': (6, ()), 'NoReadWrite': (7, ()), 'RuntimeAlignedALTERA': (5940, ()), 'RuntimeAlignedINTEL': (5940, ())}, - 'GatherModes': {'Gather4x1QCOM': (0, ()), 'GatherDQCOM': (1, ()), 'GatherH2QCOM': (2, ()), 'GatherV2QCOM': (3, ())}, - 'GroupOperation': {'Reduce': (0, ()), 'InclusiveScan': (1, ()), 'ExclusiveScan': (2, ()), 'ClusteredReduce': (3, ()), 'PartitionedReduceEXT': (6, ()), 'PartitionedReduceNV': (6, ()), 'PartitionedInclusiveScanEXT': (7, ()), 'PartitionedInclusiveScanNV': (7, ()), 'PartitionedExclusiveScanEXT': (8, ()), 'PartitionedExclusiveScanNV': (8, ())}, - 'HostAccessQualifier': {'NoneINTEL': (0, ()), 'ReadINTEL': (1, ()), 'WriteINTEL': (2, ()), 'ReadWriteINTEL': (3, ())}, - 'ImageChannelDataType': {'SnormInt8': (0, ()), 'SnormInt16': (1, ()), 'UnormInt8': (2, ()), 'UnormInt16': (3, ()), 'UnormShort565': (4, ()), 'UnormShort555': (5, ()), 'UnormInt101010': (6, ()), 'SignedInt8': (7, ()), 'SignedInt16': (8, ()), 'SignedInt32': (9, ()), 'UnsignedInt8': (10, ()), 'UnsignedInt16': (11, ()), 'UnsignedInt32': (12, ()), 'HalfFloat': (13, ()), 'Float': (14, ()), 'UnormInt24': (15, ()), 'UnormInt101010_2': (16, ()), 'UnormInt10X6EXT': (17, ()), 'UnsignedIntRaw10EXT': (19, ()), 'UnsignedIntRaw12EXT': (20, ()), 'UnormInt2_101010EXT': (21, ()), 'UnsignedInt10X6EXT': (22, ()), 'UnsignedInt12X4EXT': (23, ()), 'UnsignedInt14X2EXT': (24, ()), 'UnormInt12X4EXT': (25, ()), 'UnormInt14X2EXT': (26, ())}, - 'ImageChannelOrder': {'R': (0, ()), 'A': (1, ()), 'RG': (2, ()), 'RA': (3, ()), 'RGB': (4, ()), 'RGBA': (5, ()), 'BGRA': (6, ()), 'ARGB': (7, ()), 'Intensity': (8, ()), 'Luminance': (9, ()), 'Rx': (10, ()), 'RGx': (11, ()), 'RGBx': (12, ()), 'Depth': (13, ()), 'DepthStencil': (14, ()), 'sRGB': (15, ()), 'sRGBx': (16, ()), 'sRGBA': (17, ()), 'sBGRA': (18, ()), 'ABGR': (19, ())}, - 'ImageFormat': {'Unknown': (0, ()), 'Rgba32f': (1, ()), 'Rgba16f': (2, ()), 'R32f': (3, ()), 'Rgba8': (4, ()), 'Rgba8Snorm': (5, ()), 'Rg32f': (6, ()), 'Rg16f': (7, ()), 'R11fG11fB10f': (8, ()), 'R16f': (9, ()), 'Rgba16': (10, ()), 'Rgb10A2': (11, ()), 'Rg16': (12, ()), 'Rg8': (13, ()), 'R16': (14, ()), 'R8': (15, ()), 'Rgba16Snorm': (16, ()), 'Rg16Snorm': (17, ()), 'Rg8Snorm': (18, ()), 'R16Snorm': (19, ()), 'R8Snorm': (20, ()), 'Rgba32i': (21, ()), 'Rgba16i': (22, ()), 'Rgba8i': (23, ()), 'R32i': (24, ()), 'Rg32i': (25, ()), 'Rg16i': (26, ()), 'Rg8i': (27, ()), 'R16i': (28, ()), 'R8i': (29, ()), 'Rgba32ui': (30, ()), 'Rgba16ui': (31, ()), 'Rgba8ui': (32, ()), 'R32ui': (33, ()), 'Rgb10a2ui': (34, ()), 'Rg32ui': (35, ()), 'Rg16ui': (36, ()), 'Rg8ui': (37, ()), 'R16ui': (38, ()), 'R8ui': (39, ()), 'R64ui': (40, ()), 'R64i': (41, ())}, - 'InitializationModeQualifier': {'InitOnDeviceReprogramALTERA': (0, ()), 'InitOnDeviceReprogramINTEL': (0, ()), 'InitOnDeviceResetALTERA': (1, ()), 'InitOnDeviceResetINTEL': (1, ())}, - 'KernelEnqueueFlags': {'NoWait': (0, ()), 'WaitKernel': (1, ()), 'WaitWorkGroup': (2, ())}, - 'LinkageType': {'Export': (0, ()), 'Import': (1, ()), 'LinkOnceODR': (2, ()), 'WeakAMD': (3, ())}, - 'LoadCacheControl': {'UncachedINTEL': (0, ()), 'CachedINTEL': (1, ()), 'StreamingINTEL': (2, ()), 'InvalidateAfterReadINTEL': (3, ()), 'ConstCachedINTEL': (4, ())}, - 'MemoryModel': {'Simple': (0, ()), 'GLSL450': (1, ()), 'OpenCL': (2, ()), 'Vulkan': (3, ()), 'VulkanKHR': (3, ())}, - 'NamedMaximumNumberOfRegisters': {'AutoINTEL': (0, ())}, - 'OverflowModes': {'WRAP': (0, ()), 'SAT': (1, ()), 'SAT_ZERO': (2, ()), 'SAT_SYM': (3, ())}, - 'PackedVectorFormat': {'PackedVectorFormat4x8Bit': (0, ()), 'PackedVectorFormat4x8BitKHR': (0, ())}, - 'QuantizationModes': {'TRN': (0, ()), 'TRN_ZERO': (1, ()), 'RND': (2, ()), 'RND_ZERO': (3, ()), 'RND_INF': (4, ()), 'RND_MIN_INF': (5, ()), 'RND_CONV': (6, ()), 'RND_CONV_ODD': (7, ())}, - 'RayQueryCandidateIntersectionType': {'RayQueryCandidateIntersectionTriangleKHR': (0, ()), 'RayQueryCandidateIntersectionAABBKHR': (1, ())}, - 'RayQueryCommittedIntersectionType': {'RayQueryCommittedIntersectionNoneKHR': (0, ()), 'RayQueryCommittedIntersectionTriangleKHR': (1, ()), 'RayQueryCommittedIntersectionGeneratedKHR': (2, ())}, - 'RayQueryIntersection': {'RayQueryCandidateIntersectionKHR': (0, ()), 'RayQueryCommittedIntersectionKHR': (1, ())}, - 'SamplerAddressingMode': {'None': (0, ()), 'ClampToEdge': (1, ()), 'Clamp': (2, ()), 'Repeat': (3, ()), 'RepeatMirrored': (4, ())}, - 'SamplerFilterMode': {'Nearest': (0, ()), 'Linear': (1, ())}, - 'Scope': {'CrossDevice': (0, ()), 'Device': (1, ()), 'Workgroup': (2, ()), 'Subgroup': (3, ()), 'Invocation': (4, ()), 'QueueFamily': (5, ()), 'QueueFamilyKHR': (5, ()), 'ShaderCallKHR': (6, ())}, - 'SourceLanguage': {'Unknown': (0, ()), 'ESSL': (1, ()), 'GLSL': (2, ()), 'OpenCL_C': (3, ()), 'OpenCL_CPP': (4, ()), 'HLSL': (5, ()), 'CPP_for_OpenCL': (6, ()), 'SYCL': (7, ()), 'HERO_C': (8, ()), 'NZSL': (9, ()), 'WGSL': (10, ()), 'Slang': (11, ()), 'Zig': (12, ()), 'Rust': (13, ()), 'Pred': (14, ()), 'ApilaJai': (15, ())}, - 'StorageClass': {'UniformConstant': (0, ()), 'Input': (1, ()), 'Uniform': (2, ()), 'Output': (3, ()), 'Workgroup': (4, ()), 'CrossWorkgroup': (5, ()), 'Private': (6, ()), 'Function': (7, ()), 'Generic': (8, ()), 'PushConstant': (9, ()), 'AtomicCounter': (10, ()), 'Image': (11, ()), 'StorageBuffer': (12, ()), 'TileImageEXT': (4172, ()), 'TileAttachmentQCOM': (4491, ()), 'NodePayloadAMDX': (5068, ()), 'CallableDataKHR': (5328, ()), 'CallableDataNV': (5328, ()), 'IncomingCallableDataKHR': (5329, ()), 'IncomingCallableDataNV': (5329, ()), 'RayPayloadKHR': (5338, ()), 'RayPayloadNV': (5338, ()), 'HitAttributeKHR': (5339, ()), 'HitAttributeNV': (5339, ()), 'IncomingRayPayloadKHR': (5342, ()), 'IncomingRayPayloadNV': (5342, ()), 'ShaderRecordBufferKHR': (5343, ()), 'ShaderRecordBufferNV': (5343, ()), 'PhysicalStorageBuffer': (5349, ()), 'PhysicalStorageBufferEXT': (5349, ()), 'HitObjectAttributeNV': (5385, ()), 'TaskPayloadWorkgroupEXT': (5402, ()), 'HitObjectAttributeEXT': (5411, ()), 'CodeSectionINTEL': (5605, ()), 'DeviceOnlyALTERA': (5936, ()), 'DeviceOnlyINTEL': (5936, ()), 'HostOnlyALTERA': (5937, ()), 'HostOnlyINTEL': (5937, ())}, - 'StoreCacheControl': {'UncachedINTEL': (0, ()), 'WriteThroughINTEL': (1, ()), 'WriteBackINTEL': (2, ()), 'StreamingINTEL': (3, ())}, - 'TensorClampMode': {'Undefined': (0, ()), 'Constant': (1, ()), 'ClampToEdge': (2, ()), 'Repeat': (3, ()), 'RepeatMirrored': (4, ())}, -} - -BIT_ENUMS = { - 'CooperativeMatrixOperands': {'NoneKHR': (0, ()), 'MatrixASignedComponentsKHR': (1, ()), 'MatrixBSignedComponentsKHR': (2, ()), 'MatrixCSignedComponentsKHR': (4, ()), 'MatrixResultSignedComponentsKHR': (8, ()), 'SaturatingAccumulationKHR': (16, ())}, - 'CooperativeMatrixReduce': {'Row': (1, ()), 'Column': (2, ()), '2x2': (4, ())}, - 'FPFastMathMode': {'None': (0, ()), 'NotNaN': (1, ()), 'NotInf': (2, ()), 'NSZ': (4, ()), 'AllowRecip': (8, ()), 'Fast': (16, ()), 'AllowContract': (65536, ()), 'AllowContractFastINTEL': (65536, ()), 'AllowReassoc': (131072, ()), 'AllowReassocINTEL': (131072, ()), 'AllowTransform': (262144, ())}, - 'FragmentShadingRate': {'Vertical2Pixels': (1, ()), 'Vertical4Pixels': (2, ()), 'Horizontal2Pixels': (4, ()), 'Horizontal4Pixels': (8, ())}, - 'FunctionControl': {'None': (0, ()), 'Inline': (1, ()), 'DontInline': (2, ()), 'Pure': (4, ()), 'Const': (8, ()), 'OptNoneEXT': (65536, ()), 'OptNoneINTEL': (65536, ())}, - 'ImageOperands': {'None': (0, ()), 'Bias': (1, ('IdRef',)), 'Lod': (2, ('IdRef',)), 'Grad': (4, ('IdRef', 'IdRef')), 'ConstOffset': (8, ('IdRef',)), 'Offset': (16, ('IdRef',)), 'ConstOffsets': (32, ('IdRef',)), 'Sample': (64, ('IdRef',)), 'MinLod': (128, ('IdRef',)), 'MakeTexelAvailable': (256, ('IdScope',)), 'MakeTexelAvailableKHR': (256, ('IdScope',)), 'MakeTexelVisible': (512, ('IdScope',)), 'MakeTexelVisibleKHR': (512, ('IdScope',)), 'NonPrivateTexel': (1024, ()), 'NonPrivateTexelKHR': (1024, ()), 'VolatileTexel': (2048, ()), 'VolatileTexelKHR': (2048, ()), 'SignExtend': (4096, ()), 'ZeroExtend': (8192, ()), 'Nontemporal': (16384, ()), 'Offsets': (65536, ('IdRef',))}, - 'KernelProfilingInfo': {'None': (0, ()), 'CmdExecTime': (1, ())}, - 'LoopControl': {'None': (0, ()), 'Unroll': (1, ()), 'DontUnroll': (2, ()), 'DependencyInfinite': (4, ()), 'DependencyLength': (8, ('LiteralInteger',)), 'MinIterations': (16, ('LiteralInteger',)), 'MaxIterations': (32, ('LiteralInteger',)), 'IterationMultiple': (64, ('LiteralInteger',)), 'PeelCount': (128, ('LiteralInteger',)), 'PartialCount': (256, ('LiteralInteger',)), 'InitiationIntervalALTERA': (65536, ('LiteralInteger',)), 'InitiationIntervalINTEL': (65536, ('LiteralInteger',)), 'MaxConcurrencyALTERA': (131072, ('LiteralInteger',)), 'MaxConcurrencyINTEL': (131072, ('LiteralInteger',)), 'DependencyArrayALTERA': (262144, ('LiteralInteger',)), 'DependencyArrayINTEL': (262144, ('LiteralInteger',)), 'PipelineEnableALTERA': (524288, ('LiteralInteger',)), 'PipelineEnableINTEL': (524288, ('LiteralInteger',)), 'LoopCoalesceALTERA': (1048576, ('LiteralInteger',)), 'LoopCoalesceINTEL': (1048576, ('LiteralInteger',)), 'MaxInterleavingALTERA': (2097152, ('LiteralInteger',)), 'MaxInterleavingINTEL': (2097152, ('LiteralInteger',)), 'SpeculatedIterationsALTERA': (4194304, ('LiteralInteger',)), 'SpeculatedIterationsINTEL': (4194304, ('LiteralInteger',)), 'NoFusionALTERA': (8388608, ()), 'NoFusionINTEL': (8388608, ()), 'LoopCountALTERA': (16777216, ('LiteralInteger',)), 'LoopCountINTEL': (16777216, ('LiteralInteger',)), 'MaxReinvocationDelayALTERA': (33554432, ('LiteralInteger',)), 'MaxReinvocationDelayINTEL': (33554432, ('LiteralInteger',)), 'MultipleWaitQueuesQCOM': (268435456, ('LiteralInteger',))}, - 'MatrixMultiplyAccumulateOperands': {'None': (0, ()), 'MatrixASignedComponentsINTEL': (1, ()), 'MatrixBSignedComponentsINTEL': (2, ()), 'MatrixCBFloat16INTEL': (4, ()), 'MatrixResultBFloat16INTEL': (8, ()), 'MatrixAPackedInt8INTEL': (16, ()), 'MatrixBPackedInt8INTEL': (32, ()), 'MatrixAPackedInt4INTEL': (64, ()), 'MatrixBPackedInt4INTEL': (128, ()), 'MatrixATF32INTEL': (256, ()), 'MatrixBTF32INTEL': (512, ()), 'MatrixAPackedFloat16INTEL': (1024, ()), 'MatrixBPackedFloat16INTEL': (2048, ()), 'MatrixAPackedBFloat16INTEL': (4096, ()), 'MatrixBPackedBFloat16INTEL': (8192, ())}, - 'MemoryAccess': {'None': (0, ()), 'Volatile': (1, ()), 'Aligned': (2, ('LiteralInteger',)), 'Nontemporal': (4, ()), 'MakePointerAvailable': (8, ('IdScope',)), 'MakePointerAvailableKHR': (8, ('IdScope',)), 'MakePointerVisible': (16, ('IdScope',)), 'MakePointerVisibleKHR': (16, ('IdScope',)), 'NonPrivatePointer': (32, ()), 'NonPrivatePointerKHR': (32, ()), 'AliasScopeINTELMask': (65536, ('IdRef',)), 'NoAliasINTELMask': (131072, ('IdRef',))}, - 'MemorySemantics': {'Relaxed': (0, ()), 'None': (0, ()), 'Acquire': (2, ()), 'Release': (4, ()), 'AcquireRelease': (8, ()), 'SequentiallyConsistent': (16, ()), 'UniformMemory': (64, ()), 'SubgroupMemory': (128, ()), 'WorkgroupMemory': (256, ()), 'CrossWorkgroupMemory': (512, ()), 'AtomicCounterMemory': (1024, ()), 'ImageMemory': (2048, ()), 'OutputMemory': (4096, ()), 'OutputMemoryKHR': (4096, ()), 'MakeAvailable': (8192, ()), 'MakeAvailableKHR': (8192, ()), 'MakeVisible': (16384, ()), 'MakeVisibleKHR': (16384, ()), 'Volatile': (32768, ())}, - 'RawAccessChainOperands': {'None': (0, ()), 'RobustnessPerComponentNV': (1, ()), 'RobustnessPerElementNV': (2, ())}, - 'RayFlags': {'NoneKHR': (0, ()), 'OpaqueKHR': (1, ()), 'NoOpaqueKHR': (2, ()), 'TerminateOnFirstHitKHR': (4, ()), 'SkipClosestHitShaderKHR': (8, ()), 'CullBackFacingTrianglesKHR': (16, ()), 'CullFrontFacingTrianglesKHR': (32, ()), 'CullOpaqueKHR': (64, ()), 'CullNoOpaqueKHR': (128, ()), 'SkipTrianglesKHR': (256, ()), 'SkipBuiltinPrimitivesNV': (256, ()), 'SkipAABBsKHR': (512, ()), 'ForceOpacityMicromap2StateKHR': (1024, ()), 'ForceOpacityMicromap2StateEXT': (1024, ())}, - 'SelectionControl': {'None': (0, ()), 'Flatten': (1, ()), 'DontFlatten': (2, ())}, - 'TensorAddressingOperands': {'None': (0, ()), 'TensorView': (1, ('IdRef',)), 'DecodeFunc': (2, ('IdRef',)), 'DecodeVectorFunc': (4, ('IdRef',))}, - 'TensorOperands': {'NoneARM': (0, ()), 'NontemporalARM': (1, ()), 'OutOfBoundsValueARM': (2, ('IdRef',)), 'MakeElementAvailableARM': (4, ('IdRef',)), 'MakeElementVisibleARM': (8, ('IdRef',)), 'NonPrivateElementARM': (16, ())}, -} - -GLSL_STD_450 = { - 'Acos': 17, - 'Acosh': 23, - 'Asin': 16, - 'Asinh': 22, - 'Atan': 18, - 'Atan2': 25, - 'Atanh': 24, - 'Ceil': 9, - 'Cos': 14, - 'Cosh': 20, - 'Cross': 68, - 'Degrees': 12, - 'Determinant': 33, - 'Distance': 67, - 'Exp': 27, - 'Exp2': 29, - 'FAbs': 4, - 'FClamp': 43, - 'FMax': 40, - 'FMin': 37, - 'FMix': 46, - 'FSign': 6, - 'FaceForward': 70, - 'FindILsb': 73, - 'FindSMsb': 74, - 'FindUMsb': 75, - 'Floor': 8, - 'Fma': 50, - 'Fract': 10, - 'Frexp': 51, - 'FrexpStruct': 52, - 'IMix': 47, - 'InterpolateAtCentroid': 76, - 'InterpolateAtOffset': 78, - 'InterpolateAtSample': 77, - 'InverseSqrt': 32, - 'Ldexp': 53, - 'Length': 66, - 'Log': 28, - 'Log2': 30, - 'MatrixInverse': 34, - 'Modf': 35, - 'ModfStruct': 36, - 'NClamp': 81, - 'NMax': 80, - 'NMin': 79, - 'Normalize': 69, - 'PackDouble2x32': 59, - 'PackHalf2x16': 58, - 'PackSnorm2x16': 56, - 'PackSnorm4x8': 54, - 'PackUnorm2x16': 57, - 'PackUnorm4x8': 55, - 'Pow': 26, - 'Radians': 11, - 'Reflect': 71, - 'Refract': 72, - 'Round': 1, - 'RoundEven': 2, - 'SAbs': 5, - 'SClamp': 45, - 'SMax': 42, - 'SMin': 39, - 'SSign': 7, - 'Sin': 13, - 'Sinh': 19, - 'SmoothStep': 49, - 'Sqrt': 31, - 'Step': 48, - 'Tan': 15, - 'Tanh': 21, - 'Trunc': 3, - 'UClamp': 44, - 'UMax': 41, - 'UMin': 38, - 'UnpackDouble2x32': 65, - 'UnpackHalf2x16': 62, - 'UnpackSnorm2x16': 60, - 'UnpackSnorm4x8': 63, - 'UnpackUnorm2x16': 61, - 'UnpackUnorm4x8': 64, -} - -NONSEMANTIC_DEBUGPRINTF = { - 'DebugPrintf': 1, -} diff --git a/tools/spirv_gs_to_compute.py b/tools/spirv_gs_to_compute.py deleted file mode 100644 index 8cfaaca53..000000000 --- a/tools/spirv_gs_to_compute.py +++ /dev/null @@ -1,443 +0,0 @@ -#!/usr/bin/env python3 -"""Lower a translated geometry shader to a compute "capture" pass, for GPUs without a geometry stage (SHADER-159). - -Apple GPUs (Metal, MoltenVK) have no geometry shaders. A legacy GS can still run there as a compute pass that -writes the vertices it emits into a buffer, followed by an ordinary draw of that buffer. This rewrites a module made -by tools/rdna2spirv.py (stage `Geometry`) into a GLCompute module with one invocation per input primitive: - -- the per-vertex inputs (`BuiltIn Position`, `Location N`: Input arrays of vec4) are read from the input buffer - (set 1, binding `base_binding + 0`), `{ uint primitive_count; uint pad[3]; vec4 data[]; }`: vertex v of primitive p - has its inputs at `data[(p * VERTS_IN + v) * NUM_INPUTS + slot]`; -- the vec4 outputs become private variables, and every `OpEmitVertex` copies them to the record buffer - (set 1, binding `base_binding + 1`), `{ vec4 rec[]; }`: vertex n of primitive p at `rec[(p * MAX_VERTS + n) * NUM_OUTPUTS + slot]`; -- the meta buffer (set 1, binding `base_binding + 2`), `{ uint meta[]; }`, gets `meta[p * (MAX_VERTS + 1)]` = the - vertices primitive p emitted and `meta[p * (MAX_VERTS + 1) + 1 + n]` = 1 when `OpEndPrimitive` ends a strip after - vertex n (0 otherwise). - -`base_binding` defaults to 0 and shifts past any existing descriptor set 1 bindings in the module (such as -`--pc-tail-ubo` at binding 0); `--layout` records `base_binding` and the slots with their sizes. `PrimitiveId` reads give -p, `InvocationId` reads 0 (only `Invocations 1` is supported). The workgroup is 64x1x1; invocations past -`primitive_count` return at once. Push constants and set 0 are untouched. The draw afterwards turns each strip into -triangles (or lines, points) in emission order. - -Usage: spirv_gs_to_compute.py in.spv out.spv [--layout out.json] -Needs spirv-dis and spirv-as (SPIRV-Tools) on PATH, or SPIRV_DIS / SPIRV_AS. -""" -import io -import json -import os -import re -import subprocess -import sys -from itertools import combinations -from pathlib import Path - -LOCAL_SIZE = 64 -IN_VERTS = {"InputPoints": 1, "InputLines": 2, "InputLinesAdjacency": 4, "Triangles": 3, - "InputTrianglesAdjacency": 6} -OUT_TOPOLOGY = {"OutputPoints": "points", "OutputLineStrip": "line_strip", "OutputTriangleStrip": "triangle_strip"} -KEEP_BUILTINS = ("SubgroupLocalInvocationId", "SubgroupSize", "NumSubgroups", "SubgroupId") -FLOAT_CONTROL_MODES = {"DenormPreserve", "DenormFlushToZero", "SignedZeroInfNanPreserve", - "RoundingModeRTE", "RoundingModeRTZ"} - - -class Unsupported(Exception): - pass - - -def _assembly_lines(text): - # Only physical line endings separate instructions; Unicode separators can be part of a quoted name. - return (line.removesuffix("\n") for line in io.StringIO(text, newline=None)) - - -def parse(text): - """defs: id -> (opcode, operands) for '%id = OpX ...' lines; deco: id -> its OpDecorate operand strings.""" - defs, deco = {}, {} - for ln in _assembly_lines(text): - m = re.match(r"\s*(%\w+) = (Op\w+)(.*)$", ln) - if m: - defs[m.group(1)] = (m.group(2), m.group(3).split()) - m = re.match(r"\s*OpDecorate (%\w+) (.*)$", ln) - if m: - deco.setdefault(m.group(1), []).append(m.group(2)) - return defs, deco - - -def find_type(defs, op, operands): - return next((r for r, d in defs.items() if d == (op, operands)), None) - - -def layout_of(text): - """The shader's inputs, outputs and sizes; raises Unsupported for what the rewrite can't handle.""" - defs, deco = parse(text) - ep = re.search(r"^\s*OpEntryPoint Geometry (%\w+) ", text, re.M) - if not ep: - raise Unsupported("not a geometry shader") - main = ep.group(1) - modes = re.findall(rf"^\s*OpExecutionMode {re.escape(main)} (.*)$", text, re.M) - modes = [m.split() for m in modes] - verts_in = next((IN_VERTS[m[0]] for m in modes if m[0] in IN_VERTS), None) - topology = next((OUT_TOPOLOGY[m[0]] for m in modes if m[0] in OUT_TOPOLOGY), None) - max_verts = next((int(m[1]) for m in modes if m[0] == "OutputVertices"), None) - invocations = next((int(m[1]) for m in modes if m[0] == "Invocations"), 1) - if None in (verts_in, topology, max_verts): - raise Unsupported(f"execution modes {modes}") - if invocations != 1: - raise Unsupported(f"Invocations {invocations}") - f32 = find_type(defs, "OpTypeFloat", ["32"]) - v4 = find_type(defs, "OpTypeVector", [f32, "4"]) - - def slot(v): - ds = deco.get(v, []) - if "BuiltIn Position" in ds: - return (-1, "position") - loc = next((int(d.split()[1]) for d in ds if d.startswith("Location ")), None) - if loc is None: - raise Unsupported(f"{v}: per-vertex variable without Position or Location ({ds})") - return (loc, f"location {loc}") - - inputs, outputs, builtins = [], [], {} - for v, (op, ops) in defs.items(): - if op != "OpVariable" or ops[1:2] not in (["Input"], ["Output"]): - continue - bi = next((d.split()[1] for d in deco.get(v, []) if d.startswith("BuiltIn ")), None) - if bi in KEEP_BUILTINS or bi in ("PrimitiveId", "InvocationId"): - builtins[v] = bi - continue - pointee = defs[ops[0]][1][1] - if ops[1] == "Input": - t = defs.get(pointee, (None, [])) - if t[0] != "OpTypeArray" or t[1][0] != v4: - raise Unsupported(f"{v}: input isn't an array of vec4") - inputs.append(v) - elif pointee == v4: - outputs.append(v) - else: - raise Unsupported(f"{v}: output isn't a vec4") - inputs.sort(key=slot) - outputs.sort(key=slot) - return {"main": main, "verts_in": verts_in, "max_verts": max_verts, "topology": topology, - "inputs": [slot(v)[1] for v in inputs], "outputs": [slot(v)[1] for v in outputs], - "input_vars": inputs, "output_vars": outputs, "builtins": builtins} - - -def rewrite(text: str, *, version: tuple[int, int] = (1, 5)) -> tuple[str, dict[str, int | str | list[str]]]: - """Return (compute module text, layout dict for --layout).""" - lay = layout_of(text) - defs, deco = parse(text) - main, ins, outs, builtins = lay["main"], lay["input_vars"], lay["output_vars"], lay["builtins"] - uint = find_type(defs, "OpTypeInt", ["32", "0"]) - f32 = find_type(defs, "OpTypeFloat", ["32"]) - v4 = find_type(defs, "OpTypeVector", [f32, "4"]) - if not (uint and v4): - raise Unsupported("module has no uint or vec4 type") - v3u = find_type(defs, "OpTypeVector", [uint, "3"]) or "%gsc_v3u" - boolt = find_type(defs, "OpTypeBool", []) or "%gsc_bool" - float_ptrs = {r for r, (op, ops) in defs.items() if op == "OpTypePointer" and ops[1] == f32} - nin, nout, mv, vin = len(ins), len(outs), lay["max_verts"], lay["verts_in"] - # A GS translated with --pc-tail-ubo that reads the heap base or code base already binds %pc_tail as a Uniform - # block at (DescriptorSet 1, Binding 0); shift the capture StorageBuffers past any existing Set 1 bindings so - # two variables of different descriptor types never share (set, binding) (VUID-07990). - set1_bindings = { - int(b.split()[1]) - for ds in deco.values() - if "DescriptorSet 1" in ds - for b in ds - if b.startswith("Binding ") and len(b.split()) == 2 and b.split()[1].isdigit() - } - base_binding = (max(set1_bindings) + 1) if set1_bindings else 0 - - def k(v): - return f"%gsc_k{v}" - - # Before SPIR-V 1.3, storage buffers use Uniform with BufferBlock in core SPIR-V. - buffer_storage, buffer_block = ("StorageBuffer", "Block") if version >= (1, 3) else ("Uniform", "BufferBlock") - decos = ["OpDecorate %gsc_gid BuiltIn GlobalInvocationId", - "OpDecorate %gsc_rt_v4 ArrayStride 16", "OpDecorate %gsc_rt_u ArrayStride 4", - "OpDecorate %gsc_pad ArrayStride 4", - f"OpDecorate %gsc_in_t {buffer_block}", "OpMemberDecorate %gsc_in_t 0 Offset 0", - "OpMemberDecorate %gsc_in_t 1 Offset 4", "OpMemberDecorate %gsc_in_t 2 Offset 16", - f"OpDecorate %gsc_rec_t {buffer_block}", "OpMemberDecorate %gsc_rec_t 0 Offset 0", - f"OpDecorate %gsc_meta_t {buffer_block}", "OpMemberDecorate %gsc_meta_t 0 Offset 0", - "OpDecorate %gsc_in DescriptorSet 1", f"OpDecorate %gsc_in Binding {base_binding}", - "OpDecorate %gsc_in NonWritable", - "OpDecorate %gsc_rec DescriptorSet 1", f"OpDecorate %gsc_rec Binding {base_binding + 1}", - "OpDecorate %gsc_meta DescriptorSet 1", f"OpDecorate %gsc_meta Binding {base_binding + 2}"] - types = ([f"{v3u} = OpTypeVector {uint} 3"] if v3u == "%gsc_v3u" else []) + \ - ([f"{boolt} = OpTypeBool"] if boolt == "%gsc_bool" else []) - types += [f"{k(v)} = OpConstant {uint} {v}" for v in sorted({0, 1, 2, 3, vin, nin, nout, mv, mv + 1} - | set(range(max(nin, nout))))] - types += [f"%gsc_ptr_in_v3u = OpTypePointer Input {v3u}", - f"%gsc_rt_v4 = OpTypeRuntimeArray {v4}", f"%gsc_rt_u = OpTypeRuntimeArray {uint}", - f"%gsc_pad = OpTypeArray {uint} {k(3)}", - f"%gsc_in_t = OpTypeStruct {uint} %gsc_pad %gsc_rt_v4", - "%gsc_rec_t = OpTypeStruct %gsc_rt_v4", "%gsc_meta_t = OpTypeStruct %gsc_rt_u", - f"%gsc_ptr_in_t = OpTypePointer {buffer_storage} %gsc_in_t", - f"%gsc_ptr_rec_t = OpTypePointer {buffer_storage} %gsc_rec_t", - f"%gsc_ptr_meta_t = OpTypePointer {buffer_storage} %gsc_meta_t", - f"%gsc_ptr_sb_v4 = OpTypePointer {buffer_storage} {v4}", - f"%gsc_ptr_sb_u = OpTypePointer {buffer_storage} {uint}", - f"%gsc_ptr_sb_f = OpTypePointer {buffer_storage} {f32}", - f"%gsc_ptr_pv_v4 = OpTypePointer Private {v4}", f"%gsc_ptr_pv_f = OpTypePointer Private {f32}", - f"%gsc_ptr_pv_u = OpTypePointer Private {uint}", - "%gsc_gid = OpVariable %gsc_ptr_in_v3u Input", - f"%gsc_in = OpVariable %gsc_ptr_in_t {buffer_storage}", - f"%gsc_rec = OpVariable %gsc_ptr_rec_t {buffer_storage}", - f"%gsc_meta = OpVariable %gsc_ptr_meta_t {buffer_storage}", - f"%gsc_n = OpVariable %gsc_ptr_pv_u Private {k(0)}"] - out_vars = {v: f"%gsc_out{i}" for i, v in enumerate(outs)} - types += [f"{nv} = OpVariable %gsc_ptr_pv_v4 Private" for nv in out_vars.values()] - in_slot = {v: i for i, v in enumerate(ins)} - gone = set(ins) | set(outs) | {v for v, b in builtins.items() if b in ("PrimitiveId", "InvocationId")} - capture_interface = ["%gsc_gid"] - # Before SPIR-V 1.4, the interface only lists Input and Output variables. - if version >= (1, 4): - capture_interface += ["%gsc_in", "%gsc_rec", "%gsc_meta", "%gsc_n"] + list(out_vars.values()) - - count = 0 - - def tmp(): - nonlocal count - count += 1 - return f"%gsc_t{count}" - - out = [] - entry_label = None - cur_block = None - emit_split = set() - block_tail = {} - derived = {} # pointer id from an input or output -> the storage class it has now ("sb" or "pv") - main_start = None - state = "header" # header -> main_entry -> main_vars -> main -> other - for ln in _assembly_lines(text): - s = ln.strip() - if s == "OpCapability Geometry": - continue - m = re.match(r"OpEntryPoint Geometry (%\w+) (\"[^\"]*\")(.*)$", s) - if m: - iface = [v for v in m.group(3).split() if v not in gone] + capture_interface - out += [f"OpEntryPoint GLCompute {m.group(1)} {m.group(2)} {' '.join(iface)}", - f"OpExecutionMode {m.group(1)} LocalSize {LOCAL_SIZE} 1 1"] - continue - # Floating-point controls apply to compute too. - m = re.match(rf"OpExecutionMode {re.escape(main)} (\w+)\b", s) - if m and m.group(1) not in FLOAT_CONTROL_MODES: - continue - m = re.match(r"Op(?:Decorate|MemberDecorate|Name) (%\w+)\b", s) - if m and m.group(1) in gone: - continue - if re.match(r"OpGroupDecorate\s", s): - instruction, sep, comment = s.partition(";") - opcode, group, *targets = instruction.split() - live_targets = [target for target in targets if target not in gone] - if live_targets == targets: - out.append(ln) - elif live_targets: - rewritten = " ".join((opcode, group, *live_targets)) - out.append(rewritten + f" {sep}{comment}" if sep else rewritten) - continue - m = re.match(r"(%\w+) = (Op\w+)", s) - if decos and m and m.group(2).startswith("OpType"): - out += decos # decorations end where the first type begins - decos = [] - if m and m.group(2) == "OpVariable" and m.group(1) in gone: - continue - if m and m.group(2) == "OpFunction": - if types: - out += types - types = [] - if m.group(1) == main: - state = "main_entry" - main_start = len(out) - out.append(ln) - continue - if s == "OpFunctionEnd": - if state in ("main", "main_vars") and main_start is not None and block_tail: - # Any block split by the primitive-count check or by OpEmitVertex now terminates in its final - # merge label; update every OpPhi predecessor (including loop-header back-edges) to that label. - for idx in range(main_start, len(out)): - m_phi = re.match(r"^(\s*%\w+\s*=\s*OpPhi\s+%\w+)\s+(.*)$", out[idx]) - if m_phi: - ops = m_phi.group(2).split() - ops[1::2] = [block_tail.get(lbl, lbl) for lbl in ops[1::2]] - out[idx] = f"{m_phi.group(1)} {' '.join(ops)}" - state = "other" - cur_block = None - if state == "main_entry" and re.match(r"%\w+ = OpLabel$", s): - state = "main_vars" - entry_label = s.split()[0] - cur_block = entry_label - out.append(ln) - continue - # OpLine and OpNoLine can be intermixed with the entry block's local variables. - if state == "main_vars" and not re.match(r"(?:%\w+ = OpVariable |OpLine |OpNoLine$)", s): - # after the entry block's variables: p = GlobalInvocationId.x; return when p >= primitive_count - state = "main" - out += [f"%gsc_gidv = OpLoad {v3u} %gsc_gid", f"%gsc_prim = OpCompositeExtract {uint} %gsc_gidv 0", - f"%gsc_cntp = OpAccessChain %gsc_ptr_sb_u %gsc_in {k(0)}", f"%gsc_cnt = OpLoad {uint} %gsc_cntp", - f"%gsc_past = OpUGreaterThanEqual {boolt} %gsc_prim %gsc_cnt", - "OpSelectionMerge %gsc_body None", "OpBranchConditional %gsc_past %gsc_ret %gsc_body", - "%gsc_ret = OpLabel", "OpReturn", "%gsc_body = OpLabel", - f"%gsc_inbase = OpIMul {uint} %gsc_prim {k(vin)}", - f"%gsc_recbase = OpIMul {uint} %gsc_prim {k(mv)}", - f"%gsc_metabase = OpIMul {uint} %gsc_prim {k(mv + 1)}"] - block_tail[entry_label] = "%gsc_body" - if state not in ("main", "main_vars"): - out.append(ln) - continue - # ---- the body of main ---- - m_lbl = re.match(r"(%\w+) = OpLabel$", s) - if m_lbl: - cur_block = m_lbl.group(1) - out.append(ln) - continue - m = re.match(r"(%\w+) = Op(?:InBounds)?AccessChain (%\w+) (%\w+) (.*)$", s) - if m and m.group(3) in in_slot: - idx = m.group(4).split() - vtx = idx[0] - if defs.get(vtx, (None, [None]))[1][:1] != [uint]: - vtx = tmp() - out.append(f"{vtx} = OpBitcast {uint} {idx[0]}") - a, b, c = tmp(), tmp(), tmp() - ptr = "%gsc_ptr_sb_f" if m.group(2) in float_ptrs else "%gsc_ptr_sb_v4" - out += [f"{a} = OpIAdd {uint} %gsc_inbase {vtx}", f"{b} = OpIMul {uint} {a} {k(nin)}", - f"{c} = OpIAdd {uint} {b} {k(in_slot[m.group(3)])}", - " ".join([f"{m.group(1)} = OpAccessChain {ptr} %gsc_in {k(2)} {c}"] + idx[1:])] - derived[m.group(1)] = "sb" - continue - if m and m.group(3) in out_vars: - ptr = "%gsc_ptr_pv_f" if m.group(2) in float_ptrs else "%gsc_ptr_pv_v4" - out.append(f"{m.group(1)} = OpAccessChain {ptr} {out_vars[m.group(3)]} {m.group(4)}") - derived[m.group(1)] = "pv" - continue - # A pointer made from one of those (a further access chain, or a copy) points into the same buffer or - # private variable, so its result type takes that storage class too, not the old Input / Output (old #4126). - m = re.match(r"(%\w+) = (Op(?:InBounds)?(?:Ptr)?AccessChain|OpCopyObject) (%\w+) (%\w+)(.*)$", s) - if m and m.group(4) in derived: - pointee = defs.get(m.group(3), (None, []))[1][1:2] - if pointee not in ([v4], [f32]): - raise Unsupported(f"pointer into a geometry input or output of an unhandled type: {s}") - sc = derived[m.group(4)] - ptr = f"%gsc_ptr_{sc}_{'v4' if pointee == [v4] else 'f'}" - out.append(f"{m.group(1)} = {m.group(2)} {ptr} {m.group(4)}{m.group(5)}") - derived[m.group(1)] = sc - continue - m = re.match(r"(%\w+) = OpLoad (%\w+) (%\w+)(?:\s+.*)?$", s) - if m and builtins.get(m.group(3)) in ("PrimitiveId", "InvocationId"): - val = "%gsc_prim" if builtins[m.group(3)] == "PrimitiveId" else k(0) - out.append(f"{m.group(1)} = OpBitcast {m.group(2)} {val}" if m.group(2) != uint - else f"{m.group(1)} = OpCopyObject {uint} {val}") - continue - for v in list(in_slot) + list(out_vars) + sorted(gone - set(in_slot) - set(out_vars)): - if re.search(rf"{re.escape(v)}\b", s): - m2 = re.match(rf"OpStore {re.escape(v)} (%\w+)(?:\s+.*)?$", s) - if v in out_vars and m2: - s = f"OpStore {out_vars[v]} {m2.group(1)}" - break - raise Unsupported(f"unhandled use of {v}: {s}") - if s == "OpEmitVertex": - # Guard stores and counter increment on n < OutputVertices so over-emitting drops extra vertices - # instead of overflowing into primitive p+1's record/meta slots; %gsc_n stays <= mv for OpEndPrimitive - # and OpReturn as well (SHADER-617). - n, ok, lbl_do, lbl_end = tmp(), tmp(), tmp(), tmp() - out += [f"{n} = OpLoad {uint} %gsc_n", - f"{ok} = OpULessThan {boolt} {n} {k(mv)}", - f"OpSelectionMerge {lbl_end} None", - f"OpBranchConditional {ok} {lbl_do} {lbl_end}", - f"{lbl_do} = OpLabel"] - if out_vars: - a = tmp() - out.append(f"{a} = OpIAdd {uint} %gsc_recbase {n}") - for i, nv in enumerate(out_vars.values()): - b, c, val, p = tmp(), tmp(), tmp(), tmp() - out += [f"{b} = OpIMul {uint} {a} {k(nout)}", f"{c} = OpIAdd {uint} {b} {k(i)}", - f"{val} = OpLoad {v4} {nv}", f"{p} = OpAccessChain %gsc_ptr_sb_v4 %gsc_rec {k(0)} {c}", - f"OpStore {p} {val}"] - d, e, q, n1 = tmp(), tmp(), tmp(), tmp() - out += [f"{d} = OpIAdd {uint} %gsc_metabase {n}", f"{e} = OpIAdd {uint} {d} {k(1)}", - f"{q} = OpAccessChain %gsc_ptr_sb_u %gsc_meta {k(0)} {e}", f"OpStore {q} {k(0)}", - f"{n1} = OpIAdd {uint} {n} {k(1)}", f"OpStore %gsc_n {n1}", - f"OpBranch {lbl_end}", - f"{lbl_end} = OpLabel"] - if cur_block is not None: - block_tail[cur_block] = lbl_end - emit_split.add(cur_block) - continue - if s == "OpEndPrimitive": - # flag the last emitted vertex: meta[base + 1 + (n - 1)]; with none emitted this writes the count slot, - # which the final store overwrites - n, d, q = tmp(), tmp(), tmp() - out += [f"{n} = OpLoad {uint} %gsc_n", f"{d} = OpIAdd {uint} %gsc_metabase {n}", - f"{q} = OpAccessChain %gsc_ptr_sb_u %gsc_meta {k(0)} {d}", f"OpStore {q} {k(1)}"] - continue - if s == "OpReturn": - n, q = tmp(), tmp() - out += [f"{n} = OpLoad {uint} %gsc_n", - f"{q} = OpAccessChain %gsc_ptr_sb_u %gsc_meta {k(0)} %gsc_metabase", f"OpStore {q} {n}"] - if s.startswith("OpLoopMerge ") and cur_block in emit_split: - # Splitting a loop header with OpSelectionMerge moves OpLoopMerge into the merge block while - # back-edges still target the original header label, violating SPIR-V structured CFG rules. - raise Unsupported("OpEmitVertex in a loop header before OpLoopMerge") - if s in ("OpKill", "OpTerminateInvocation", "OpReturnValue"): - raise Unsupported(s) - out.append(s) - public = {key: lay[key] for key in ("verts_in", "max_verts", "topology", "inputs", "outputs")} - public["local_size"] = LOCAL_SIZE - if base_binding: - public["base_binding"] = base_binding - return "\n".join(out) + "\n", public - - -USAGE = "\n".join(__doc__.strip().splitlines()[-2:]) - - -def main(argv): - args = argv[1:] - if args and args[0] in ("-h", "--help"): - print(USAGE) - return 0 - lay_path = None - if "--layout" in args: - i = args.index("--layout") - lay_path = args[i + 1] - del args[i:i + 2] - if len(args) != 2: - print(USAGE, file=sys.stderr) - return 2 - paths = [("input", args[0]), ("SPIR-V output", args[1])] - if lay_path: - paths.append(("--layout output", lay_path)) - try: - resolved = [(name, Path(path).resolve()) for name, path in paths] - for (left_name, left), (right_name, right) in combinations(resolved, 2): - if left == right or (left.exists() and right.exists() and left.samefile(right)): - print(f"{left_name} and {right_name} refer to the same file: {left}", file=sys.stderr) - return 2 - except (OSError, RuntimeError, ValueError) as e: - print(f"cannot check input/output paths: {e}", file=sys.stderr) - return 2 - dis = os.environ.get("SPIRV_DIS", "spirv-dis") - asm = os.environ.get("SPIRV_AS", "spirv-as") - text = subprocess.run([dis, "--raw-id", args[0]], check=True, capture_output=True, text=True).stdout - ver = re.search(r"; Version: (\d+)\.(\d+)", text) - version = (int(ver[1]), int(ver[2])) if ver else (1, 5) - try: - new, lay = rewrite(text, version=version) - except Unsupported as e: - print(f"{args[0]}: not supported: {e}", file=sys.stderr) - return 1 - target = f"spv{version[0]}.{version[1]}" if ver else "vulkan1.2" - subprocess.run([asm, "--target-env", target, "-", "-o", args[1]], input=new, check=True, text=True) - if lay_path: - with open(lay_path, "w", encoding="utf-8", newline="\n") as f: - json.dump(lay, f, indent=1) - print(json.dumps(lay)) - return 0 - - -if __name__ == "__main__": - try: # a redirected stdout is strict ANSI code page under -I; write '?' for what it cannot encode - sys.stdout.reconfigure(errors="replace") - except (AttributeError, ValueError, OSError): - pass - sys.exit(main(sys.argv)) diff --git a/tools/spirv_interface.py b/tools/spirv_interface.py deleted file mode 100644 index e5cca9977..000000000 --- a/tools/spirv_interface.py +++ /dev/null @@ -1,534 +0,0 @@ -"""Reflect the user-defined graphics interfaces in a binary SPIR-V module. - -This reader is deliberately limited to declarations used for Vulkan stage linking. It does not -validate shader instructions, device features, or resource bindings. IDs and debug names are local -to each module; the result uses normalized types and Location/Component decorations instead. -Literal specialization constants in array lengths use their declared defaults. -""" -from __future__ import annotations - -from array import array -from collections import defaultdict -from dataclasses import dataclass -import struct - - -class InterfaceError(ValueError): - """The module's requested interface could not be reflected.""" - - -SPIRV_MAGIC = 0x07230203 -SPIRV_MAGIC_SWAPPED = 0x03022307 - -# SPIR-V core grammar. The NV/EXT spelling of PerPrimitive uses the same enumerant. -OP_ENTRY_POINT = 15 -OP_TYPE_INT = 21 -OP_TYPE_FLOAT = 22 -OP_TYPE_VECTOR = 23 -OP_TYPE_MATRIX = 24 -OP_TYPE_ARRAY = 28 -OP_TYPE_STRUCT = 30 -OP_TYPE_POINTER = 32 -OP_CONSTANT = 43 -OP_SPEC_CONSTANT = 50 -OP_VARIABLE = 59 -OP_DECORATE = 71 -OP_MEMBER_DECORATE = 72 -OP_DECORATION_GROUP = 73 -OP_GROUP_DECORATE = 74 -OP_GROUP_MEMBER_DECORATE = 75 - -TYPE_OPS = {OP_TYPE_INT, OP_TYPE_FLOAT, OP_TYPE_VECTOR, OP_TYPE_MATRIX, - OP_TYPE_ARRAY, OP_TYPE_STRUCT, OP_TYPE_POINTER} -DECLARATION_OPS = TYPE_OPS | {OP_ENTRY_POINT, OP_CONSTANT, OP_SPEC_CONSTANT, OP_VARIABLE, - OP_DECORATE, OP_MEMBER_DECORATE, OP_DECORATION_GROUP, - OP_GROUP_DECORATE, OP_GROUP_MEMBER_DECORATE} -TYPE_OPERANDS = {OP_TYPE_INT: 3, OP_TYPE_FLOAT: 2, OP_TYPE_VECTOR: 3, OP_TYPE_MATRIX: 3, - OP_TYPE_ARRAY: 3, OP_TYPE_POINTER: 3} -EXECUTION_STAGES = {0: "vs", 3: "gs", 4: "ps", 5268: "ms", 5365: "ms"} # MeshNV and MeshEXT -STORAGE_INPUT = 1 -STORAGE_OUTPUT = 3 -DEC_BLOCK = 2 -DEC_BUILTIN = 11 -DEC_PATCH = 15 -DEC_LOCATION = 30 -DEC_COMPONENT = 31 -DEC_INDEX = 32 -DEC_PASSTHROUGH_NV = 5250 -DEC_PER_PRIMITIVE = 5271 -DEC_PER_VERTEX = 5285 -DECORATION_NAMES = {DEC_BLOCK: "Block", DEC_BUILTIN: "BuiltIn", DEC_PATCH: "Patch", - DEC_LOCATION: "Location", DEC_COMPONENT: "Component", DEC_INDEX: "Index", - DEC_PASSTHROUGH_NV: "PassthroughNV", DEC_PER_PRIMITIVE: "PerPrimitiveEXT", - DEC_PER_VERTEX: "PerVertexKHR"} -VALUE_DECORATIONS = {DEC_BUILTIN, DEC_LOCATION, DEC_COMPONENT, DEC_INDEX} - -# Bound expansion of arrays from malformed modules. This is far beyond the varying space of the -# graphics stages on current Vulkan drivers. Type and layout recursion has a separate depth limit. -MAX_EXPANDED_LOCATIONS = 16384 -MAX_TYPE_DEPTH = 64 - - -@dataclass(frozen=True) -class NumericType: - kind: str - width: int - components: int = 1 - - def describe(self): - scalar = f"{self.kind}{self.width}" - return scalar if self.components == 1 else f"vec{self.components}<{scalar}>" - - def location_masks(self, component): - slots = self.components * (self.width // 32 if self.width >= 32 else 1) - if self.width == 64 and component % 2: - raise InterfaceError("a 64-bit varying starts on an odd Component") - if self.width != 64 and component + slots > 4: - raise InterfaceError("a 16-bit or 32-bit varying extends beyond its Location") - if self.width == 64 and component + slots > 4 and component: - raise InterfaceError("a 64-bit vector spanning two locations needs Component 0") - mask = ((1 << slots) - 1) << component - if mask <= 0xf: - return (mask,) - return (mask & 0xf, mask >> 4) - - -@dataclass(frozen=True) -class AggregateType: - kind: str - items: tuple[NumericType | "AggregateType", ...] - count: int = 1 - - def describe(self): - if self.kind == "struct": - return "struct{" + ", ".join(item.describe() for item in self.items) + "}" - return f"{self.kind}[{self.count}]<{self.items[0].describe()}>" - - def location_masks(self, component): - if self.kind == "struct": - if component: - raise InterfaceError("a structure cannot start at a nonzero Component") - masks = [] - for member in self.items: - member_masks = member.location_masks(0) - if len(masks) + len(member_masks) > MAX_EXPANDED_LOCATIONS: - raise InterfaceError("structure uses too many interface locations to inspect") - masks.extend(member_masks) - return tuple(masks) - element = self.items[0].location_masks(component) - if len(element) * self.count > MAX_EXPANDED_LOCATIONS: - raise InterfaceError("aggregate uses too many interface locations to inspect") - return element * self.count - - -@dataclass(frozen=True, order=True) -class Address: - location: int - component: int = 0 - index: int = 0 - - def describe(self): - suffix = f", index {self.index}" if self.index else "" - return f"location {self.location}, component {self.component}{suffix}" - - -@dataclass(frozen=True) -class Varying: - address: Address - type: NumericType | AggregateType - per_primitive: bool = False - - def occupied(self): - for offset, mask in enumerate(self.type.location_masks(self.address.component)): - for component in range(4): - if mask & (1 << component): - yield Address(self.address.location + offset, component, self.address.index) - - def describe(self): - mode = " per-primitive" if self.per_primitive else "" - return f"{self.type.describe()}{mode} at {self.address.describe()}" - - -@dataclass(frozen=True) -class Declaration: - """One standalone varying or an entire structure. Preserve member order when linking.""" - - varyings: tuple[Varying, ...] - symbol: int - structure: bool = False - block: bool = False - indexed_by_vertex_or_primitive: bool = False - - def describe(self): - parts = ", ".join(varying.describe() for varying in self.varyings) - if self.structure: - kind = "block" if self.block else "struct" - return f"{kind} %{self.symbol} ({parts})" - return f"%{self.symbol} ({parts})" - - -@dataclass(frozen=True) -class StageInterface: - stage: str - entry: str - inputs: tuple[Declaration, ...] - outputs: tuple[Declaration, ...] - - -@dataclass(frozen=True) -class EntryPoint: - model: int - name: str - interface_ids: tuple[int, ...] - - -def parse_words(data): - if len(data) < 20 or len(data) % 4: - raise InterfaceError("SPIR-V must contain a five-word header and complete 32-bit words") - words = array("I") - words.frombytes(data) - if words[0] == SPIRV_MAGIC_SWAPPED: - words.byteswap() - if words[0] != SPIRV_MAGIC: - raise InterfaceError("invalid SPIR-V magic") - if not 0x00010000 <= words[1] <= 0x00010600 or words[1] & 0xff: - raise InterfaceError(f"unsupported SPIR-V version word 0x{words[1]:08x}") - if not words[3] or words[4]: - raise InterfaceError("invalid SPIR-V ID bound or reserved header word") - return words - - -def instructions(words): - start = 5 - while start < len(words): - first = words[start] - length, opcode = first >> 16, first & 0xffff - end = start + length - if not length or end > len(words): - raise InterfaceError(f"invalid instruction length at word {start}") - if opcode in DECLARATION_OPS: - yield opcode, tuple(words[start + 1:end]), start - start = end - - -def decode_literal_string(words): - for i, word in enumerate(words): - if b"\x00" in struct.pack(" maximum): - raise InterfaceError(f"invalid operands at word {at}") - - def read_instruction(self, opcode, operands, at): - if opcode in TYPE_OPS: - required = TYPE_OPERANDS.get(opcode) - # OpTypeFloat can also carry an optional FPEncoding operand. - maximum = 3 if opcode == OP_TYPE_FLOAT else required - self.require_operands(operands, at, required or 1, maximum) - identifier, *args = operands - self.define(identifier) - self.types[identifier] = (opcode, tuple(args)) - elif opcode in (OP_CONSTANT, OP_SPEC_CONSTANT): - self.require_operands(operands, at, 3) - type_id, identifier, *literal = operands - self.require_id(type_id) - self.define(identifier) - self.constants[identifier] = (type_id, tuple(literal)) - elif opcode == OP_VARIABLE: - self.require_operands(operands, at, 3, 4) - pointer, identifier, storage = operands[:3] - self.require_id(pointer) - self.define(identifier) - self.variables[identifier] = (pointer, storage) - elif opcode == OP_ENTRY_POINT: - self.require_operands(operands, at, 3) - model, function, *rest = operands - self.require_id(function) - name, words_used = decode_literal_string(rest) - ids = tuple(rest[words_used:]) - for identifier in ids: - self.require_id(identifier) - if self.version < 0x00010400: - # OpEntryPoint permits repeated interface IDs before SPIR-V 1.4. - ids = tuple(dict.fromkeys(ids)) - elif len(set(ids)) != len(ids): - raise InterfaceError(f"duplicate entry-point interface ID in {name!r}") - self.entry_points.append(EntryPoint(model, name, ids)) - elif opcode in (OP_DECORATE, OP_MEMBER_DECORATE): - split = 1 if opcode == OP_DECORATE else 2 - self.require_operands(operands, at, split + 1) - identifier = operands[0] - self.require_id(identifier) - decoration, *extra = operands[split:] - if decoration not in DECORATION_NAMES: - return - expected = int(decoration in VALUE_DECORATIONS) - if len(extra) != expected: - raise InterfaceError(f"invalid {DECORATION_NAMES[decoration]} decoration at word {at}") - target = (self.decorations[identifier] if split == 1 - else self.member_decorations[(identifier, operands[1])]) - self.add_decoration(target, decoration, extra[0] if extra else True) - elif opcode == OP_DECORATION_GROUP: - self.require_operands(operands, at, 1, 1) - self.define(operands[0]) - self.groups.add(operands[0]) - else: - self.require_operands(operands, at, 2 if opcode == OP_GROUP_DECORATE else 3) - if opcode == OP_GROUP_MEMBER_DECORATE and len(operands) % 2 != 1: - raise InterfaceError(f"unpaired group member decoration at word {at}") - self.group_uses.append((opcode, operands)) - - @staticmethod - def add_decoration(target, decoration, value): - if decoration in target and target[decoration] != value: - raise InterfaceError(f"conflicting {DECORATION_NAMES[decoration]} decorations") - target[decoration] = value - - def apply_decoration_groups(self): - for opcode, operands in self.group_uses: - group, *targets = operands - if group not in self.groups: - raise InterfaceError(f"undefined decoration group %{group}") - source = self.decorations.get(group, {}) - if opcode == OP_GROUP_DECORATE: - destinations = ((identifier, None) for identifier in targets) - else: - destinations = zip(targets[::2], targets[1::2]) - for identifier, member in destinations: - self.require_id(identifier) - if identifier in self.groups: - raise InterfaceError("decoration groups cannot decorate each other") - target = (self.decorations[identifier] if member is None - else self.member_decorations[(identifier, member)]) - for decoration, value in source.items(): - self.add_decoration(target, decoration, value) - - def type_declaration(self, identifier): - try: - return self.types[identifier] - except KeyError: - raise InterfaceError(f"missing or unsupported varying type %{identifier}") from None - - def array_count(self, identifier): - try: - type_id, literal = self.constants[identifier] - except KeyError: - raise InterfaceError( - f"varying array length %{identifier} is not a literal OpConstant or OpSpecConstant" - ) from None - opcode, args = self.type_declaration(type_id) - if opcode != OP_TYPE_INT or args[0] not in (8, 16, 32, 64) or args[1] not in (0, 1): - raise InterfaceError("varying array length must be an integer") - width, signed = args - if len(literal) != (width + 31) // 32: - raise InterfaceError("invalid literal width for varying array length") - count = sum(word << (32 * i) for i, word in enumerate(literal)) & ((1 << width) - 1) - if not count or (signed and count >> (width - 1)): - raise InterfaceError("varying array length must be positive") - return count - - def shape(self, identifier, path=()): - if identifier in self.shape_cache: - return self.shape_cache[identifier] - if identifier in path or len(path) == MAX_TYPE_DEPTH: - raise InterfaceError("cyclic or excessively deep varying type") - opcode, args = self.type_declaration(identifier) - nested = (*path, identifier) - if opcode in (OP_TYPE_INT, OP_TYPE_FLOAT): - if opcode == OP_TYPE_FLOAT and len(args) > 1: - raise InterfaceError(f"unsupported floating-point encoding {args[1]} in graphics interface") - width = args[0] - if width not in (16, 32, 64) or (opcode == OP_TYPE_INT and args[1] not in (0, 1)): - raise InterfaceError("unsupported numeric type in graphics interface") - kind = "f" if opcode == OP_TYPE_FLOAT else ("i" if args[1] else "u") - result = NumericType(kind, width) - elif opcode == OP_TYPE_VECTOR: - element = self.shape(args[0], nested) - if not isinstance(element, NumericType) or element.components != 1 or not 2 <= args[1] <= 4: - raise InterfaceError("invalid varying vector type") - result = NumericType(element.kind, element.width, args[1]) - elif opcode in (OP_TYPE_ARRAY, OP_TYPE_MATRIX): - element = self.shape(args[0], nested) - if opcode == OP_TYPE_ARRAY: - result = AggregateType("array", (element,), self.array_count(args[1])) - else: - if (not isinstance(element, NumericType) or element.kind != "f" or element.components < 2 - or not 2 <= args[1] <= 4): - raise InterfaceError("invalid varying matrix type") - result = AggregateType("matrix", (element,), args[1]) - elif opcode == OP_TYPE_STRUCT: - if not args: - raise InterfaceError("empty structure in graphics interface") - for i in range(len(args)): - if self.member_decorations.get((identifier, i)): - raise InterfaceError("decorated nested interface structure members are unsupported") - result = AggregateType("struct", tuple(self.shape(member, nested) for member in args)) - else: - raise InterfaceError("unsupported pointer in graphics interface") - self.shape_cache[identifier] = result - return result - - def pick_entry(self, stage, entry): - named = [candidate for candidate in self.entry_points if candidate.name == entry] - matches = [candidate for candidate in named if stage is None or EXECUTION_STAGES.get(candidate.model) == stage] - if not matches: - found = ", ".join(EXECUTION_STAGES.get(candidate.model, str(candidate.model)) for candidate in named) - if found: - raise InterfaceError(f"entry point {entry!r} is {found}, expected {stage}") - raise InterfaceError(f"entry point {entry!r} not found") - if len(matches) > 1: - raise InterfaceError(f"entry point {entry!r} is ambiguous without a stage") - selected = matches[0] - if selected.model not in EXECUTION_STAGES: - raise InterfaceError(f"unsupported execution model {selected.model} for entry point {entry!r}") - return selected - - def varying_type(self, pointer, storage, stage, decorations): - opcode, args = self.type_declaration(pointer) - if opcode != OP_TYPE_POINTER or args[0] != storage: - raise InterfaceError("variable pointer type does not match its storage class") - pointee = args[1] - per_vertex = DEC_PER_VERTEX in decorations - if per_vertex and (stage, storage) != ("ps", STORAGE_INPUT): - raise InterfaceError("PerVertexKHR is only supported on fragment inputs") - primitive_array = (stage, storage) in (("gs", STORAGE_INPUT), ("ms", STORAGE_OUTPUT)) - indexed = per_vertex or primitive_array - if indexed: - # The array indexes vertices or primitives. It is outside the linked payload shape - # and does not consume locations. Its length does not need to match the other stage. - opcode, args = self.type_declaration(pointee) - if opcode != OP_TYPE_ARRAY: - raise InterfaceError(f"{stage} requires an outer per-vertex or per-primitive array") - pointee = args[0] - return pointee, indexed - - @staticmethod - def address(decorations, location=None): - location = decorations.get(DEC_LOCATION, location) - component = decorations.get(DEC_COMPONENT, 0) - index = decorations.get(DEC_INDEX, 0) - if location is None: - raise InterfaceError("user varying is missing a Location decoration") - if component > 3 or index > 1: - raise InterfaceError("invalid Component or Index decoration") - return Address(location, component, index) - - @staticmethod - def check_modes(decorations): - if DEC_PASSTHROUGH_NV in decorations: - raise InterfaceError("geometry passthrough interfaces require different matching rules") - if DEC_PATCH in decorations: - raise InterfaceError("tessellation patch interfaces are unsupported") - - def declaration(self, symbol, pointer, storage, stage): - decorations = self.decorations.get(symbol, {}) - self.check_modes(decorations) - if DEC_BUILTIN in decorations: - return None - type_id, indexed = self.varying_type(pointer, storage, stage, decorations) - opcode, args = self.type_declaration(type_id) - per_primitive = DEC_PER_PRIMITIVE in decorations - if opcode != OP_TYPE_STRUCT: - varying = Varying(self.address(decorations), self.shape(type_id), per_primitive) - return Declaration((varying,), symbol, indexed_by_vertex_or_primitive=indexed) - - member_decs = [self.member_decorations.get((type_id, i), {}) for i in range(len(args))] - if member_decs and all(DEC_BUILTIN in member for member in member_decs): - return None - if any(DEC_BUILTIN in member for member in member_decs): - raise InterfaceError("mixed built-in and user-defined structure members") - is_block = DEC_BLOCK in self.decorations.get(type_id, {}) - base_location = decorations.get(DEC_LOCATION) - if base_location is None and not is_block: - raise InterfaceError("a non-block structure needs a Location") - if DEC_COMPONENT in decorations or DEC_INDEX in decorations: - raise InterfaceError("Component or Index on an entire varying structure is unsupported") - if base_location is not None and any(DEC_LOCATION in member for member in member_decs): - raise InterfaceError("both the structure and its members declare Locations") - if not args: - raise InterfaceError("empty structure in graphics interface") - members = [] - next_location = base_location - for child, member in zip(args, member_decs): - self.check_modes(member) - address = self.address(member, next_location) - shape = self.shape(child, (type_id,)) - members.append(Varying(address, shape, per_primitive or DEC_PER_PRIMITIVE in member)) - if base_location is not None: - next_location += len(shape.location_masks(address.component)) - return Declaration(tuple(members), symbol, structure=True, block=is_block, - indexed_by_vertex_or_primitive=indexed) - - def reflect(self, stage=None, entry="main"): - selected = self.pick_entry(stage, entry) - stage = EXECUTION_STAGES[selected.model] - directions = {STORAGE_INPUT: [], STORAGE_OUTPUT: []} - slots = {STORAGE_INPUT: {}, STORAGE_OUTPUT: {}} - for symbol in selected.interface_ids: - if symbol not in self.variables: - raise InterfaceError(f"entry point references missing variable %{symbol}") - pointer, storage = self.variables[symbol] - if storage not in directions: - continue - try: - declaration = self.declaration(symbol, pointer, storage, stage) - if declaration is None: - continue - for varying in declaration.varyings: - for address in varying.occupied(): - before = slots[storage].get(address) - if before is not None: - raise InterfaceError( - f"overlap with %{before} at {address.describe()}") - slots[storage][address] = symbol - except InterfaceError as exc: - direction = "input" if storage == STORAGE_INPUT else "output" - raise InterfaceError(f"{stage} {direction} variable %{symbol}: {exc}") from exc - directions[storage].append(declaration) - key = lambda declaration: declaration.varyings[0].address - return StageInterface(stage, entry, tuple(sorted(directions[STORAGE_INPUT], key=key)), - tuple(sorted(directions[STORAGE_OUTPUT], key=key))) - - -def reflect_module(data, stage=None, entry="main"): - return Module(data).reflect(stage, entry) diff --git a/tools/spirv_metal_set0.py b/tools/spirv_metal_set0.py deleted file mode 100644 index 6d64b21dc..000000000 --- a/tools/spirv_metal_set0.py +++ /dev/null @@ -1,216 +0,0 @@ -#!/usr/bin/env python3 -"""Give set 0's descriptor arrays fixed, non-overlapping Metal argument-buffer IDs (SHADER-161). - -SPIRV-Cross (1.4.363.0) puts every runtime descriptor array of an argument buffer at one ID: with Leonida's -set 0 (sampled images at binding 0, samplers at 1, more image arrays at 3+) it comments all but one out as -"Overlapping binding", so the shader can't reach them. This rewrites a translated module for a native Metal -path only (the Vulkan module and layout stay as they are): - -- each set-0 runtime descriptor array becomes a sized array with that binding's capacity from - runtime/src/vulkan_bindless.h (`bindings`), and -- each set-0 Binding becomes the first ID of its range: the capacities of all lower bindings added up. - -Convert the result with `spirv-cross --msl --msl-argument-buffers --msl-argument-buffer-tier 1 ---msl-decoration-binding`, so the IDs are the same in every shader, whichever bindings it uses. The argument -buffer then holds binding b's element i at ID `metal_id(b) + i` (`--print-layout` prints the table). - -Usage: spirv_metal_set0.py in.spv out.spv | spirv_metal_set0.py --print-layout -Needs spirv-dis and spirv-as (SPIRV-Tools) on PATH, or SPIRV_DIS / SPIRV_AS. -""" -import os -import re -import subprocess -import sys - -ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) -BINDLESS_H = os.path.join(ROOT, "runtime", "src", "vulkan_bindless.h") - - -def capacities(path=BINDLESS_H): - """Descriptor counts by binding number, from the `bindings` table of vulkan_bindless.h.""" - with open(path, encoding="utf-8") as f: - src = f.read() - m = re.search(r"std::array\s*bindings\s*=\s*\{\{(.*?)\}\};", src, re.S) - if not m: - raise SystemExit(f"{path}: no `bindings` table") - counts = [int(c) for c in re.findall(r"\{VK_DESCRIPTOR_TYPE_\w+,\s*(\d+)\}", m.group(2))] - if len(counts) != int(m.group(1)): - raise SystemExit(f"{path}: `bindings` declares {m.group(1)} entries, found {len(counts)}") - return counts - - -def metal_ids(counts): - """First argument-buffer ID of each binding: the capacities of the lower bindings added up.""" - ids, total = [], 0 - for c in counts: - ids.append(total) - total += c - return ids - - -def _fresh_id(base, used): - """Return `base` if unused, otherwise `base_1`, `base_2`, ... and record it in `used`.""" - cand = base - i = 1 - while cand in used: - cand = f"{base}_{i}" - i += 1 - used.add(cand) - return cand - - -def rewrite(text, counts): - """Rewrite the disassembly (spirv-dis --raw-id is not needed; names are kept) of one module.""" - ids = metal_ids(counts) - lines = text.splitlines() - sets, binds = {}, {} - for ln in lines: - m = re.match(r"\s*OpDecorate (%\S+) DescriptorSet (\d+)$", ln) - if m: - sets[m.group(1)] = int(m.group(2)) - m = re.match(r"\s*OpDecorate (%\S+) Binding (\d+)$", ln) - if m: - binds[m.group(1)] = int(m.group(2)) - set0 = {v: b for v, b in binds.items() if sets.get(v) == 0} - for v, b in set0.items(): - if b >= len(counts): - raise SystemExit(f"{v}: binding {b} isn't in vulkan_bindless.h") - - defs = {} # result id -> instruction text - definition_positions: dict[str, int] = {} - for idx, ln in enumerate(lines): - m = re.match(r"\s*(%\S+) = (.*)$", ln) - if m: - defs[m.group(1)] = m.group(2) - definition_positions[m.group(1)] = idx - uint = next((r for r, d in defs.items() if d == "OpTypeInt 32 0"), None) - - candidates = [] - for order, (v, b) in enumerate(set0.items()): - var = re.match(r"OpVariable (%\S+) UniformConstant$", defs.get(v, "")) - if not var: - continue # the hash table (a storage buffer) and other non-array resources keep their type - old_ptr = var.group(1) - ptr = re.match(r"OpTypePointer UniformConstant (%\S+)$", defs.get(old_ptr, "")) - rt = re.match(r"OpTypeRuntimeArray (%\S+)$", defs.get(ptr.group(1), "")) if ptr else None - if not rt: - continue - candidates.append((b, definition_positions[old_ptr], order, v, old_ptr, rt.group(1))) - - if candidates: - if uint is None: - raise SystemExit("module has no 32-bit uint type for the array lengths") - first_pointer = min(candidate[1] for candidate in candidates) - uint_position = definition_positions[uint] - if uint_position > first_pointer: - # The generated length may precede an original declaration of its integer type. - lines.insert(first_pointer, lines.pop(uint_position)) - - used_ids = set(defs) | set(sets) | set(binds) - cap_by_bind = {} # binding -> OpConstant id (emitted once per binding) - ptr_by_key = {} # (binding, elem_type) -> new OpTypePointer id - new_types = [] # inserted right after the variable's pointer type is declared - retype = {} # resized variable or copied pointer ID -> new pointer type - for b, _, _, v, old_ptr, elem in sorted(candidates): - if (b, elem) in ptr_by_key: - retype[v] = ptr_by_key[(b, elem)] - continue - decl = [] - cap = cap_by_bind.get(b) - if cap is None: - cap = _fresh_id(f"%msl_cap_b{b}", used_ids) - cap_by_bind[b] = cap - decl.append(f"{cap} = OpConstant {uint} {counts[b]}") - arr = _fresh_id(f"%msl_arr_b{b}", used_ids) - nptr = _fresh_id(f"%msl_ptr_b{b}", used_ids) - decl.extend([ - f"{arr} = OpTypeArray {elem} {cap}", - f"{nptr} = OpTypePointer UniformConstant {arr}", - ]) - new_types.append((old_ptr, decl)) - ptr_by_key[(b, elem)] = nptr - retype[v] = nptr - - out = [] - for ln in lines: - m = re.match(r"(\s*OpDecorate (%\S+) Binding )(\d+)$", ln) - if m and m.group(2) in set0: - ln = f"{m.group(1)}{ids[int(m.group(3))]}" - m = re.match(r"(\s*(%\S+) = OpVariable )(%\S+)( UniformConstant)$", ln) - if m and m.group(2) in retype: - ln = f"{m.group(1)}{retype[m.group(2)]}{m.group(4)}" - # Retype copies by source ID so arrays sharing a type in other sets are unaffected. - m = re.match(r"(\s*(%\S+) = OpCopyObject )%\S+ (%\S+)$", ln) - if m and m.group(3) in retype: - ptr = retype[m.group(3)] - retype[m.group(2)] = ptr - ln = f"{m.group(1)}{ptr} {m.group(3)}" - out.append(ln) - m = re.match(r"\s*(%\S+) = OpTypePointer", ln) - if m: - for after, decl in new_types: - if after == m.group(1): - out.extend(decl) - return "\n".join(out) + "\n" - - -def main(argv): - rest = argv[1:] - if rest and rest[0] in ("-h", "--help"): - for line in __doc__.strip().splitlines()[-2:]: - print(line) - return 0 - counts = capacities() - if argv[1:] == ["--print-layout"]: - for b, (c, i) in enumerate(zip(counts, metal_ids(counts))): - print(f"binding {b:2}: {c:5} descriptors at IDs {i}..{i + c - 1}") - return 0 - if len(argv) != 3: - print(__doc__.strip().splitlines()[-2], file=sys.stderr) - return 2 - dis, asm = _tools() - # errors="replace": on Windows text=True decodes with the ANSI code page, and a program that answers in UTF-8 - # (a path with non-ASCII letters in its error message) would otherwise kill the reader thread and lose stderr. - text = _run([dis, argv[1]], capture_output=True, text=True, errors="replace").stdout - env = re.search(r"; Version: (\d+)\.(\d+)", text) - target = f"spv{env.group(1)}.{env.group(2)}" if env else "vulkan1.2" - _run([asm, "--target-env", target, "-", "-o", argv[2]], input=rewrite(text, counts), text=True) - return 0 - - -def _tools(): - return os.environ.get("SPIRV_DIS", "spirv-dis"), os.environ.get("SPIRV_AS", "spirv-as") - - -def _run(cmd, **kwargs): - """subprocess.run(check=True). Windows does not name the program it could not start, so name it here.""" - try: - return subprocess.run(cmd, check=True, **kwargs) - except OSError as e: - if e.filename is None: - e.filename = cmd[0] - raise - - -def cli(argv): - """main() for the command line: a SPIRV-Tools program that cannot be started, or that rejects its input, is - one ERROR line and exit 1 instead of a traceback. main() itself still raises, for callers that catch it.""" - try: - return main(argv) - except subprocess.CalledProcessError as e: - program = e.cmd[0] if isinstance(e.cmd, (list, tuple)) else e.cmd - said = next((line.strip() for line in (e.stderr or "").splitlines() if line.strip()), "") - print(f"ERROR: {program} failed with exit status {e.returncode}" + (f": {said}" if said else ""), - file=sys.stderr) - except OSError as e: - hint = " (SPIRV-Tools must be on PATH, or set SPIRV_DIS / SPIRV_AS)" if e.filename in _tools() else "" - print(f"ERROR: {e.filename or 'spirv_metal_set0.py'}: {e.strerror or e}{hint}", file=sys.stderr) - return 1 - - -if __name__ == "__main__": - try: # a redirected stdout is strict ANSI code page under -I; write '?' for what it cannot encode - sys.stdout.reconfigure(errors="replace") - except (AttributeError, ValueError, OSError): - pass - sys.exit(cli(sys.argv)) diff --git a/tools/spirv_opt.py b/tools/spirv_opt.py deleted file mode 100644 index bbd2159c5..000000000 --- a/tools/spirv_opt.py +++ /dev/null @@ -1,1205 +0,0 @@ -"""Sound dominator-tree SPIR-V optimizer for tools/rdna2spirv.py output (#884). - -Targets the main source of SPIR-V size and driver compile-time bloat in translated -RDNA2 shaders: per-instruction Function-scope register array OpAccessChain / OpLoad / -OpStore traffic, repeated OpLoad %bool %active guards (including across blocks when -%active is never stored or along single-predecessor CFG edges), duplicate immutable -Input / PushConstant loads, OpSelect on constant booleans, OpCopyObject wrappers, -round-trip OpBitcast pairs, integer/bit constant folding and algebraic identities, -trivial OpPhi nodes, dead local stores, dead Function-scope OpVariables, and dead -SSA temporaries. - -Every transform is strictly sound: - - Only Function-scope OpVariables that do not escape (never passed to OpFunctionCall, - OpAtomic*, OpCopyMemory, etc.) are tracked. - - Dynamic OpAccessChain indices (e.g. v_movrels / s_movrels) are detected per variable: - dynamic stores invalidate all cached slots of that variable in the current block; - dynamic loads prevent killing earlier stores to that variable; variables with any - dynamic index are excluded from whole-function dead-slot and never-stored-slot - elimination. - - Pure value / OpAccessChain / immutable (Input, PushConstant) OpLoad CSE runs in - dominator-tree preorder, guaranteeing SSA dominance for every replacement (including - OpPhi operands). - - Mutable Function-scope slot forwarding inherits across single-predecessor CFG edges - (where the sole predecessor strictly dominates the block) and from whole-function - read-only initializers (never-stored variables or never-stored static slots of - zero-initialized variables), resetting at multi-predecessor joins and loop headers. - Dead overwritten-store elimination stays strictly intra-block. - - Constant folding only replaces an instruction when an existing module OpConstant / - OpConstantTrue / OpConstantFalse already matches the result type and value. - - Pure DCE uses an explicit allowlist of side-effect-free opcodes and drops any - OpDecorate / OpName lines that reference deleted SSA IDs. - -As a module: - from spirv_opt import optimize - opt_spvasm = optimize(spvasm) - -As a CLI: - python3 -I tools/spirv_opt.py input.spvasm -o output.spvasm -Usage: `python -I tools/spirv_opt.py --help` lists the options. -""" -import argparse -import sys - -_PURE_OPS = frozenset(( - "OpAccessChain", - "OpCopyObject", - "OpSelect", - "OpBitcast", - "OpIAdd", "OpISub", "OpIMul", "OpUDiv", "OpSDiv", "OpUMod", "OpSMod", "OpSRem", - "OpFAdd", "OpFSub", "OpFMul", "OpFDiv", "OpFNegate", "OpFmaKHR", - "OpBitwiseOr", "OpBitwiseAnd", "OpBitwiseXor", "OpNot", - "OpShiftLeftLogical", "OpShiftRightLogical", "OpShiftRightArithmetic", - "OpBitFieldUExtract", "OpBitFieldSExtract", "OpBitFieldInsert", - "OpBitReverse", "OpBitCount", - "OpIEqual", "OpINotEqual", - "OpUGreaterThan", "OpUGreaterThanEqual", "OpULessThan", "OpULessThanEqual", - "OpSGreaterThan", "OpSGreaterThanEqual", "OpSLessThan", "OpSLessThanEqual", - "OpFOrdEqual", "OpFOrdNotEqual", - "OpFOrdGreaterThan", "OpFOrdGreaterThanEqual", "OpFOrdLessThan", "OpFOrdLessThanEqual", - "OpFUnordEqual", "OpFUnordNotEqual", - "OpFUnordGreaterThan", "OpFUnordGreaterThanEqual", "OpFUnordLessThan", "OpFUnordLessThanEqual", - "OpIsNan", "OpIsInf", - "OpLogicalAnd", "OpLogicalOr", "OpLogicalNot", "OpLogicalEqual", "OpLogicalNotEqual", - "OpCompositeConstruct", "OpCompositeExtract", "OpCompositeInsert", - "OpVectorShuffle", "OpVectorExtractDynamic", "OpVectorTimesScalar", - "OpConvertFToU", "OpConvertFToS", "OpConvertSToF", "OpConvertUToF", - "OpUConvert", "OpSConvert", "OpFConvert", "OpQuantizeToF16", - "OpIAddCarry", "OpISubBorrow", "OpUMulExtended", "OpSMulExtended", -)) - -_COMMUTATIVE_OPS = frozenset(( - "OpIAdd", "OpIMul", "OpBitwiseOr", "OpBitwiseAnd", "OpBitwiseXor", - "OpIEqual", "OpINotEqual", "OpLogicalAnd", "OpLogicalOr", - "OpLogicalEqual", "OpLogicalNotEqual", -)) - -_PURE_GLSL_EXT = frozenset(( - "FAbs", "SAbs", "FSign", "SSign", "Floor", "Trunc", "Round", "RoundEven", - "Ceil", "Fract", "Sin", "Cos", "Tan", "Asin", "Acos", "Atan", - "Sinh", "Cosh", "Tanh", "Pow", "Exp", "Log", "Exp2", "Log2", - "Sqrt", "InverseSqrt", - "FMin", "UMin", "SMin", "FMax", "UMax", "SMax", - "FClamp", "UClamp", "SClamp", "NMin", "NMax", "NClamp", - "FMix", "Step", "SmoothStep", "Fma", - "PackHalf2x16", "UnpackHalf2x16", - "PackSnorm4x8", "PackUnorm4x8", "PackSnorm2x16", "PackUnorm2x16", - "UnpackSnorm4x8", "UnpackUnorm4x8", "UnpackSnorm2x16", "UnpackUnorm2x16", - "FindILsb", "FindSMsb", "FindUMsb", "Ldexp", "FrexpStruct", "ModfStruct", -)) - - -def _parse_line(line: str): - """Return (res_id_or_None, opname, args_list) for one SPIR-V assembly line, or None if blank/comment.""" - if '"' not in line: - semi = line.find(";") - toks = (line[:semi] if semi >= 0 else line).split() - else: - # Lines with quotes only appear in module header (OpExtension, OpEntryPoint, OpName, OpString). - return None - if not toks: - return None - if len(toks) >= 3 and toks[1] == "=": - return toks[0], toks[2], toks[3:] - return None, toks[0], toks[1:] - - -def _format_inst(res: str | None, op: str, args: list[str]) -> str: - if res is not None: - return f" {res} = {op} {' '.join(args)}" if args else f" {res} = {op}" - return f" {op} {' '.join(args)}" if args else f" {op}" - - -def _to_signed(uval: int, width: int) -> int: - sign_bit = 1 << (width - 1) - return uval - (1 << width) if uval >= sign_bit else uval - - -def _build_cfg_and_dom(insts: list[list]): - """Split function instructions into basic blocks and compute CFG + dominator tree.""" - blocks: list[list[int]] = [] # block_idx -> list of inst indices (starting with OpLabel) - label_to_block: dict[str, int] = {} - cur: list[int] | None = None - for idx, (res, op, _args, _raw) in enumerate(insts): - if op == "OpLabel" and res is not None: - b = len(blocks) - label_to_block[res] = b - cur = [idx] - blocks.append(cur) - elif cur is not None: - if op == "OpFunctionEnd": - cur = None - else: - cur.append(idx) - - n_blocks = len(blocks) - if n_blocks == 0: - return blocks, [], [], [], {}, [] - - succs: list[list[int]] = [[] for _ in range(n_blocks)] - all_preds: list[set[int]] = [set() for _ in range(n_blocks)] - - for b, b_insts in enumerate(blocks): - seen_s: set[int] = set() - for idx in b_insts: - _, op, args, _ = insts[idx] - targets = () - if op == "OpBranch" and args: - targets = (args[0],) - elif op == "OpBranchConditional" and len(args) >= 3: - targets = (args[1], args[2]) - elif op == "OpSwitch" and len(args) >= 2: - targets = tuple([args[1]] + [args[k] for k in range(3, len(args), 2)]) - for t in targets: - tb = label_to_block.get(t) - if tb is not None: - all_preds[tb].add(b) - if tb not in seen_s: - seen_s.add(tb) - succs[b].append(tb) - - # Iterative DFS from block 0 to compute reverse postorder (RPO) of reachable blocks. - visited = [False] * n_blocks - postorder: list[int] = [] - stack: list[tuple[int, int]] = [(0, 0)] - visited[0] = True - while stack: - b, si = stack[-1] - if si < len(succs[b]): - stack[-1] = (b, si + 1) - nb = succs[b][si] - if not visited[nb]: - visited[nb] = True - stack.append((nb, 0)) - else: - stack.pop() - postorder.append(b) - - rpo = list(reversed(postorder)) - rpo_num = {b: i for i, b in enumerate(rpo)} - - # Cooper-Harvey-Kennedy iterative dominator algorithm on reachable blocks. - idom: dict[int, int] = {0: 0} - - def intersect(b1: int, b2: int) -> int: - while b1 != b2: - while rpo_num[b1] > rpo_num[b2]: - b1 = idom[b1] - while rpo_num[b2] > rpo_num[b1]: - b2 = idom[b2] - return b1 - - dom_changed = True - while dom_changed: - dom_changed = False - for b in rpo[1:]: - new_idom = None - for p in all_preds[b]: - if p in idom: - new_idom = p if new_idom is None else intersect(p, new_idom) - if new_idom is not None and idom.get(b) != new_idom: - idom[b] = new_idom - dom_changed = True - - dom_children: list[list[int]] = [[] for _ in range(n_blocks)] - for b in rpo[1:]: - p = idom.get(b) - if p is not None and p != b: - dom_children[p].append(b) - - return blocks, succs, all_preds, rpo, idom, dom_children - - -def _fold_int_op(op: str, res_ty: str, args: list[str], - const_int_val: dict[str, tuple[str, int, int, int]], - int_const_by_val: dict[tuple[str, int], str], - int_type_info: dict[str, tuple[int, int]], - const_true_id: str | None, const_false_id: str | None) -> str | None: - """Fold constant/algebraic integer/bit operations into an existing SSA ID, or return None.""" - n = len(args) - if op == "OpNot" and n == 2: - c1 = const_int_val.get(args[1]) - if c1 is not None: - ty, v1, w, _ = c1 - mask = (1 << w) - 1 - return int_const_by_val.get((res_ty, (~v1) & mask)) - return None - - if op == "OpUConvert" and n == 2: - c1 = const_int_val.get(args[1]) - dst_info = int_type_info.get(res_ty) - if c1 is not None and dst_info is not None: - _, v1, _, _ = c1 - dw, _ = dst_info - return int_const_by_val.get((res_ty, v1 & ((1 << dw) - 1))) - return None - - if op == "OpBitFieldUExtract" and n == 4: - base, off_id, cnt_id = args[1], args[2], args[3] - co = const_int_val.get(off_id) - cc = const_int_val.get(cnt_id) - dst_info = int_type_info.get(res_ty) - if co is not None and cc is not None and dst_info is not None: - w, _ = dst_info - off = co[1] - cnt = cc[1] - if off == 0 and cnt == w: - return base - cb = const_int_val.get(base) - if cb is not None and off <= w and cnt <= w and off + cnt <= w: - val = 0 if cnt == 0 else ((cb[1] >> off) & ((1 << cnt) - 1)) - return int_const_by_val.get((res_ty, val)) - return None - - if n != 3: - return None - - a1, a2 = args[1], args[2] - c1 = const_int_val.get(a1) - c2 = const_int_val.get(a2) - - # Full constant folding when both operands are known integer constants. - if c1 is not None and c2 is not None: - _, v1, w1, _ = c1 - _, v2, w2, _ = c2 - mask = (1 << w1) - 1 - if op == "OpIAdd": - return int_const_by_val.get((res_ty, (v1 + v2) & mask)) - if op == "OpISub": - return int_const_by_val.get((res_ty, (v1 - v2) & mask)) - if op == "OpIMul": - return int_const_by_val.get((res_ty, (v1 * v2) & mask)) - if op == "OpUDiv" and v2 != 0: - return int_const_by_val.get((res_ty, (v1 // v2) & mask)) - if op == "OpUMod" and v2 != 0: - return int_const_by_val.get((res_ty, (v1 % v2) & mask)) - if op == "OpBitwiseAnd": - return int_const_by_val.get((res_ty, (v1 & v2) & mask)) - if op == "OpBitwiseOr": - return int_const_by_val.get((res_ty, (v1 | v2) & mask)) - if op == "OpBitwiseXor": - return int_const_by_val.get((res_ty, (v1 ^ v2) & mask)) - if op == "OpShiftLeftLogical" and v2 < w1: - return int_const_by_val.get((res_ty, (v1 << v2) & mask)) - if op == "OpShiftRightLogical" and v2 < w1: - return int_const_by_val.get((res_ty, (v1 >> v2) & mask)) - if op == "OpShiftRightArithmetic" and v2 < w1: - sv1 = _to_signed(v1, w1) - return int_const_by_val.get((res_ty, (sv1 >> v2) & mask)) - if const_true_id is not None and const_false_id is not None and w1 == w2: - if op == "OpIEqual": - return const_true_id if v1 == v2 else const_false_id - if op == "OpINotEqual": - return const_true_id if v1 != v2 else const_false_id - if op == "OpULessThan": - return const_true_id if v1 < v2 else const_false_id - if op == "OpULessThanEqual": - return const_true_id if v1 <= v2 else const_false_id - if op == "OpUGreaterThan": - return const_true_id if v1 > v2 else const_false_id - if op == "OpUGreaterThanEqual": - return const_true_id if v1 >= v2 else const_false_id - sv1, sv2 = _to_signed(v1, w1), _to_signed(v2, w2) - if op == "OpSLessThan": - return const_true_id if sv1 < sv2 else const_false_id - if op == "OpSLessThanEqual": - return const_true_id if sv1 <= sv2 else const_false_id - if op == "OpSGreaterThan": - return const_true_id if sv1 > sv2 else const_false_id - if op == "OpSGreaterThanEqual": - return const_true_id if sv1 >= sv2 else const_false_id - return None - - # Algebraic identities with one constant or identical operands (all bit-exact for SPIR-V ints). - dst_info = int_type_info.get(res_ty) - dst_mask = (1 << dst_info[0]) - 1 if dst_info is not None else None - - if op == "OpIAdd": - if c2 is not None and c2[1] == 0: - return a1 - if c1 is not None and c1[1] == 0: - return a2 - elif op == "OpISub": - if c2 is not None and c2[1] == 0: - return a1 - if a1 == a2: - return int_const_by_val.get((res_ty, 0)) - elif op == "OpIMul": - if c2 is not None: - if c2[1] == 1: - return a1 - if c2[1] == 0: - return a2 - if c1 is not None: - if c1[1] == 1: - return a2 - if c1[1] == 0: - return a1 - elif op == "OpBitwiseAnd": - if a1 == a2: - return a1 - if c2 is not None: - if c2[1] == 0: - return a2 - if dst_mask is not None and c2[1] == dst_mask: - return a1 - if c1 is not None: - if c1[1] == 0: - return a1 - if dst_mask is not None and c1[1] == dst_mask: - return a2 - elif op == "OpBitwiseOr": - if a1 == a2: - return a1 - if c2 is not None: - if c2[1] == 0: - return a1 - if dst_mask is not None and c2[1] == dst_mask: - return a2 - if c1 is not None: - if c1[1] == 0: - return a2 - if dst_mask is not None and c1[1] == dst_mask: - return a1 - elif op == "OpBitwiseXor": - if a1 == a2: - return int_const_by_val.get((res_ty, 0)) - if c2 is not None and c2[1] == 0: - return a1 - if c1 is not None and c1[1] == 0: - return a2 - elif op in ("OpShiftLeftLogical", "OpShiftRightLogical", "OpShiftRightArithmetic"): - if c2 is not None and c2[1] == 0: - return a1 - if op != "OpShiftRightArithmetic" and c1 is not None and c1[1] == 0: - return a1 - elif op == "OpIEqual" and a1 == a2: - return const_true_id - elif op == "OpINotEqual" and a1 == a2: - return const_false_id - return None - - -def _optimize_function(body_lines: list[str], const_ids: set[str], const_true: set[str], - const_false: set[str], const_null_elem_zero: dict[str, str], - const_type: dict[str, str], const_int_val: dict[str, tuple[str, int, int, int]], - int_const_by_val: dict[tuple[str, int], str], - int_type_info: dict[str, tuple[int, int]], - readonly_global_vars: set[str], glsl_sets: set[str], - decorated_ids: set[str], max_passes: int = 4) -> tuple[list[str], set[str]]: - """Optimize one OpFunction ... OpFunctionEnd slice. Returns (new_lines, deleted_ids).""" - insts: list[list] = [] - for raw in body_lines: - parsed = _parse_line(raw) - if parsed is None: - insts.append([None, None, None, raw]) - else: - res, op, args = parsed - insts.append([res, op, args, raw]) - - deleted_ids: set[str] = set() - const_true_id = next(iter(const_true)) if const_true else None - const_false_id = next(iter(const_false)) if const_false else None - - for _pass in range(max_passes): - changed = False - - # 1. Discover Function-scope variables, pointer-to-slot mappings, escapes, dynamic indices, - # result types, and which variables / static slots are ever stored to. - func_vars: dict[str, str | None] = {} # var_id -> initializer_id or None - ptr_root: dict[str, str] = {} # ptr_id -> root var_id (Function or readonly global) - ptr_slot: dict[str, tuple | None] = {} # ptr_id -> (var_id, *canonical_const_indices) or None - escaped: set[str] = set() - dyn_indexed: set[str] = set() - id_type: dict[str, str] = dict(const_type) - - for res, op, args, _ in insts: - if op is None: - continue - if res is not None and args and op != "OpLabel": - id_type[res] = args[0] - if op == "OpVariable" and len(args) >= 2 and args[1] == "Function" and res: - init = args[2] if len(args) >= 3 else None - func_vars[res] = init - ptr_root[res] = res - ptr_slot[res] = (res,) - elif op == "OpAccessChain" and res and len(args) >= 2: - base = args[1] - idxs = args[2:] - if base in ptr_root: - root = ptr_root[base] - ptr_root[res] = root - base_slot = ptr_slot.get(base) - if base_slot is not None and all(i in const_int_val for i in idxs): - # Canonicalize integer index constants by unsigned value so %uint_0 and %int_0 alias. - cidxs = tuple(const_int_val[i][1] for i in idxs) - ptr_slot[res] = base_slot + cidxs - else: - ptr_slot[res] = None - if root in func_vars: - dyn_indexed.add(root) - elif base in readonly_global_vars: - ptr_root[res] = base - - slot_depths: dict[str, set[int]] = {} - for res, op, args, _ in insts: - if op is None: - continue - if op == "OpLoad": - if len(args) >= 2 and args[1] in ptr_root and ptr_root[args[1]] in func_vars: - root = ptr_root[args[1]] - if any("Volatile" in m for m in args[2:]): - escaped.add(root) - sl = ptr_slot.get(args[1]) - if sl is not None: - slot_depths.setdefault(root, set()).add(len(sl)) - for tok in args[2:]: - if tok in ptr_root and ptr_root[tok] in func_vars: - escaped.add(ptr_root[tok]) - elif op == "OpStore": - if len(args) >= 2 and args[0] in ptr_root and ptr_root[args[0]] in func_vars: - root = ptr_root[args[0]] - if any("Volatile" in m for m in args[2:]): - escaped.add(root) - sl = ptr_slot.get(args[0]) - if sl is not None: - slot_depths.setdefault(root, set()).add(len(sl)) - for tok in args[1:]: - if tok in ptr_root and ptr_root[tok] in func_vars: - escaped.add(ptr_root[tok]) - elif op == "OpAccessChain": - for tok in args[2:]: - if tok in ptr_root and ptr_root[tok] in func_vars: - escaped.add(ptr_root[tok]) - elif op != "OpVariable": - for tok in args: - if tok in ptr_root and ptr_root[tok] in func_vars: - escaped.add(ptr_root[tok]) - - # Exclude variables accessed at mixed aggregate/subobject depths (e.g. whole array + element pointer). - for root, depths in slot_depths.items(): - if len(depths) > 1: - escaped.add(root) - - trackable = {v for v in func_vars if v not in escaped} - static_trackable = {v for v in trackable if v not in dyn_indexed} - - # Identify which trackable vars and static slots ever receive an OpStore in the function. - stored_vars: set[str] = set() - stored_slots: set[tuple] = set() - for _res, op, args, _ in insts: - if op == "OpStore" and len(args) >= 2: - ptr = args[0] - root = ptr_root.get(ptr) - if root in trackable: - stored_vars.add(root) - slot = ptr_slot.get(ptr) - if slot is not None: - stored_slots.add(slot) - - # Function-wide immutable facts for never-stored trackable variables (e.g. %active in non-divergent shaders). - readonly_slot_val: dict[tuple, str] = {} - readonly_null_zero: dict[str, str] = {} - for v in trackable: - if v in stored_vars: - continue - init = func_vars[v] - if init is None: - continue - if init in const_null_elem_zero: - readonly_null_zero[v] = const_null_elem_zero[init] - elif init in const_ids: - readonly_slot_val[(v,)] = init - - # Never-stored static zero-initialized array variables: individual slots with zero stores are always zero. - static_null_zero: dict[str, str] = {} - for v in static_trackable: - init = func_vars[v] - if init is not None and init in const_null_elem_zero and (v,) not in stored_slots: - static_null_zero[v] = const_null_elem_zero[init] - - # 2. Build CFG + dominator tree and run dominator-tree preorder optimization pass. - blocks, _succs, all_preds, rpo, idom, dom_children = _build_cfg_and_dom(insts) - def_block: dict[str, int] = {} - for blk_i, b_insts in enumerate(blocks): - for inst_i in b_insts: - def_id = insts[inst_i][0] - if def_id is not None: - def_block[def_id] = blk_i - - def strictly_dominates(a: int, b: int) -> bool: - if a == b or b not in idom: - return False - cur = idom[b] - while cur != a: - nxt = idom.get(cur) - if nxt is None or nxt == cur: - return False - cur = nxt - return True - - alias: dict[str, str] = {} - - def resolve(tok: str) -> str: - cur = tok - while cur in alias: - cur = alias[cur] - if cur != tok: - alias[tok] = cur - return cur - - dead_idx: set[int] = set() - - # Scoped dominator-tree tables (maintained via undo logs during iterative DFS). - ac_cse: dict[tuple, str] = {} - val_cse: dict[tuple, str] = {} - ro_load_cse: dict[tuple, str] = {} # (res_ty, ptr_id) -> loaded_id for Input / PushConstant - bitcast_of: dict[str, tuple[str, str]] = {} # res_id -> (src_id, src_type_id) - bool_mask_of: dict[str, tuple[str, bool]] = {} # res_id -> (cond_id, True if cond->nz/!cond->0 else inverted) - ctor_elems: dict[str, list[str]] = {} # composite_id -> list of constituent IDs - logical_not_of: dict[str, str] = {} # res_id -> inner bool ID - - def process_block(b: int, slot_val: dict[tuple, str], entry_null_zero: dict[str, str], - reachable: bool): - nonlocal changed - last_store: dict[tuple, int] = {} - undo_ac: list[tuple] = [] - undo_val: list[tuple] = [] - undo_ro: list[tuple] = [] - undo_bc: list[str] = [] - undo_bm: list[str] = [] - undo_ce: list[str] = [] - undo_ln: list[str] = [] - - for idx in blocks[b]: - entry = insts[idx] - res, op, args, _ = entry - if op is None or op == "OpLabel": - continue - - if alias and args: - new_args = [resolve(t) if t.startswith("%") else t for t in args] - if new_args != args: - entry[2] = new_args - args = new_args - changed = True - - # Trivial OpPhi simplification (only when the sole non-self value strictly dominates this block). - if op == "OpPhi" and reachable and res is not None and res not in decorated_ids and len(args) >= 3: - vals = [args[k] for k in range(1, len(args), 2)] - non_self = {v for v in vals if v != res} - if len(non_self) == 1: - cand = next(iter(non_self)) - cand_blk = def_block.get(cand) - if cand_blk is None or strictly_dominates(cand_blk, b): - alias[res] = cand - dead_idx.add(idx) - deleted_ids.add(res) - changed = True - continue - - # Algebraic / copy / constant-fold / round-trip bitcast simplifications - if res is not None and res not in decorated_ids: - if op == "OpCopyObject" and len(args) == 2: - alias[res] = args[1] - dead_idx.add(idx) - deleted_ids.add(res) - changed = True - continue - if op == "OpBitcast" and len(args) == 2: - dst_ty, src = args[0], args[1] - prev_bc = bitcast_of.get(src) - if prev_bc is not None and prev_bc[1] == dst_ty: - alias[res] = prev_bc[0] - dead_idx.add(idx) - deleted_ids.add(res) - changed = True - continue - src_ty = id_type.get(src) - if src_ty is not None: - bitcast_of[res] = (src, src_ty) - undo_bc.append(res) - if op == "OpCompositeConstruct" and len(args) >= 2: - ctor_elems[res] = args[1:] - undo_ce.append(res) - if op == "OpCompositeExtract" and len(args) == 3 and args[2].isdigit(): - elems = ctor_elems.get(args[1]) - if elems is not None: - k = int(args[2]) - if k < len(elems) and all(id_type.get(e) == args[0] for e in elems): - alias[res] = elems[k] - dead_idx.add(idx) - deleted_ids.add(res) - changed = True - continue - if op == "OpSelect" and len(args) == 4: - cond, x, y = args[1], args[2], args[3] - if cond in const_true or x == y: - alias[res] = x - dead_idx.add(idx) - deleted_ids.add(res) - changed = True - continue - if cond in const_false: - alias[res] = y - dead_idx.add(idx) - deleted_ids.add(res) - changed = True - continue - if x in const_true and y in const_false: - alias[res] = cond - dead_idx.add(idx) - deleted_ids.add(res) - changed = True - continue - cx = const_int_val.get(x) - cy = const_int_val.get(y) - if cx is not None and cy is not None: - if cx[1] != 0 and cy[1] == 0: - bool_mask_of[res] = (cond, True) - undo_bm.append(res) - elif cx[1] == 0 and cy[1] != 0: - bool_mask_of[res] = (cond, False) - undo_bm.append(res) - if op == "OpLogicalNot" and len(args) == 2: - inner = args[1] - if inner in const_true and const_false_id is not None: - alias[res] = const_false_id - dead_idx.add(idx) - deleted_ids.add(res) - changed = True - continue - if inner in const_false and const_true_id is not None: - alias[res] = const_true_id - dead_idx.add(idx) - deleted_ids.add(res) - changed = True - continue - prev_not = logical_not_of.get(inner) - if prev_not is not None: - alias[res] = prev_not - dead_idx.add(idx) - deleted_ids.add(res) - changed = True - continue - logical_not_of[res] = inner - undo_ln.append(res) - if op == "OpLogicalAnd" and len(args) == 3: - a1, a2 = args[1], args[2] - if a1 == a2 or a2 in const_true: - alias[res] = a1 - dead_idx.add(idx) - deleted_ids.add(res) - changed = True - continue - if a1 in const_true: - alias[res] = a2 - dead_idx.add(idx) - deleted_ids.add(res) - changed = True - continue - if a1 in const_false: - alias[res] = a1 - dead_idx.add(idx) - deleted_ids.add(res) - changed = True - continue - if a2 in const_false: - alias[res] = a2 - dead_idx.add(idx) - deleted_ids.add(res) - changed = True - continue - if op == "OpLogicalOr" and len(args) == 3: - a1, a2 = args[1], args[2] - if a1 == a2 or a2 in const_false: - alias[res] = a1 - dead_idx.add(idx) - deleted_ids.add(res) - changed = True - continue - if a1 in const_false: - alias[res] = a2 - dead_idx.add(idx) - deleted_ids.add(res) - changed = True - continue - if a1 in const_true: - alias[res] = a1 - dead_idx.add(idx) - deleted_ids.add(res) - changed = True - continue - if a2 in const_true: - alias[res] = a2 - dead_idx.add(idx) - deleted_ids.add(res) - changed = True - continue - if op in ("OpINotEqual", "OpIEqual") and len(args) == 3: - a1, a2 = args[1], args[2] - for cand, other in ((a1, a2), (a2, a1)): - bm = bool_mask_of.get(cand) - co = const_int_val.get(other) - if bm is not None and co is not None and co[1] == 0: - cond_id, normal = bm - if (op == "OpINotEqual" and normal) or (op == "OpIEqual" and not normal): - alias[res] = cond_id - dead_idx.add(idx) - deleted_ids.add(res) - changed = True - break - if idx in dead_idx: - continue - - # Integer/bit constant folding & algebraic identities - folded = _fold_int_op( - op, args[0], args, const_int_val, int_const_by_val, - int_type_info, const_true_id, const_false_id, - ) - if folded is not None: - alias[res] = folded - dead_idx.add(idx) - deleted_ids.add(res) - changed = True - continue - - # Dominator-scoped OpAccessChain CSE - if op == "OpAccessChain" and res is not None and res not in decorated_ids: - key = tuple(args) - prev = ac_cse.get(key) - if prev is not None: - alias[res] = prev - dead_idx.add(idx) - deleted_ids.add(res) - changed = True - continue - ac_cse[key] = res - undo_ac.append(key) - continue - - # Dominator-scoped pure-value CSE (with commutative operand canonicalization) - if res is not None and res not in decorated_ids and ( - op in _PURE_OPS or (op == "OpExtInst" and len(args) >= 3 and args[1] in glsl_sets and args[2] in _PURE_GLSL_EXT) - ): - if op in _COMMUTATIVE_OPS and len(args) == 3 and args[1] > args[2]: - key = (op, (args[0], args[2], args[1])) - else: - key = (op, tuple(args)) - prev = val_cse.get(key) - if prev is not None: - alias[res] = prev - dead_idx.add(idx) - deleted_ids.add(res) - changed = True - continue - val_cse[key] = res - undo_val.append(key) - continue - - # OpLoad forwarding & CSE (Function-scope slots + immutable Input/PushConstant globals) - if op == "OpLoad" and res is not None and len(args) >= 2: - ptr = args[1] - volatile = any("Volatile" in m for m in args[2:]) - root = ptr_root.get(ptr) - if not volatile and root in trackable: - slot = ptr_slot.get(ptr) - if slot is not None: - cached = slot_val.get(slot) - if cached is None and len(slot) == 2: - if root in entry_null_zero: - cached = entry_null_zero[root] - elif root in static_null_zero and slot not in stored_slots: - cached = static_null_zero[root] - if cached is not None and res not in decorated_ids: - alias[res] = cached - dead_idx.add(idx) - deleted_ids.add(res) - changed = True - continue - slot_val[slot] = res - last_store.pop(slot, None) - else: - # Dynamic load from root: protect all pending intra-block stores to root. - for s in [k for k in last_store if k[0] == root]: - last_store.pop(s, None) - elif not volatile and (root in readonly_global_vars or ptr in readonly_global_vars) and res not in decorated_ids: - ro_key = (args[0], ptr) - prev = ro_load_cse.get(ro_key) - if prev is not None: - alias[res] = prev - dead_idx.add(idx) - deleted_ids.add(res) - changed = True - continue - ro_load_cse[ro_key] = res - undo_ro.append(ro_key) - continue - - # Function-scope OpStore tracking & redundant/overwritten store elimination - if op == "OpStore" and len(args) >= 2: - ptr, val = args[0], args[1] - volatile = any("Volatile" in m for m in args[2:]) - root = ptr_root.get(ptr) - if not volatile and root in trackable: - slot = ptr_slot.get(ptr) - if slot is not None: - cur_val = slot_val.get(slot) - if cur_val is None and root in entry_null_zero and len(slot) == 2: - cur_val = entry_null_zero[root] - if cur_val == val: - dead_idx.add(idx) - changed = True - continue - prev_st = last_store.get(slot) - if prev_st is not None: - dead_idx.add(prev_st) - changed = True - slot_val[slot] = val - last_store[slot] = idx - else: - entry_null_zero.pop(root, None) - for s in [k for k in slot_val if k[0] == root]: - slot_val.pop(s, None) - for s in [k for k in last_store if k[0] == root]: - last_store.pop(s, None) - continue - - return undo_ac, undo_val, undo_ro, undo_bc, undo_bm, undo_ce, undo_ln - - if blocks: - # Initial state for entry block 0. - entry_sv = dict(readonly_slot_val) - entry_nz = dict(readonly_null_zero) - if not all_preds[0]: - for v in trackable: - init = func_vars[v] - if init is None: - continue - if init in const_null_elem_zero: - entry_nz[v] = const_null_elem_zero[init] - elif init in const_ids: - entry_sv[(v,)] = init - - # Iterative dominator-tree preorder DFS. - dfs: list[tuple] = [("enter", 0, entry_sv, entry_nz)] - while dfs: - frame = dfs.pop() - if frame[0] == "enter": - _, b, sv, nz = frame - undos = process_block(b, sv, nz, reachable=True) - dfs.append(("exit", undos)) - for ch in reversed(dom_children[b]): - if all_preds[ch] == {b}: - dfs.append(("enter", ch, dict(sv), dict(nz))) - else: - dfs.append(("enter", ch, dict(readonly_slot_val), dict(readonly_null_zero))) - else: - undo_ac, undo_val, undo_ro, undo_bc, undo_bm, undo_ce, undo_ln = frame[1] - for k in undo_ac: - del ac_cse[k] - for k in undo_val: - del val_cse[k] - for k in undo_ro: - del ro_load_cse[k] - for k in undo_bc: - del bitcast_of[k] - for k in undo_bm: - del bool_mask_of[k] - for k in undo_ce: - del ctor_elems[k] - for k in undo_ln: - del logical_not_of[k] - - # Process any unreachable blocks (in case spirv-val inspects them) with fresh state. - reachable_set = set(rpo) - for b in range(len(blocks)): - if b not in reachable_set: - undos = process_block(b, dict(readonly_slot_val), dict(readonly_null_zero), reachable=False) - undo_ac, undo_val, undo_ro, undo_bc, undo_bm, undo_ce, undo_ln = undos - for k in undo_ac: - del ac_cse[k] - for k in undo_val: - del val_cse[k] - for k in undo_ro: - del ro_load_cse[k] - for k in undo_bc: - del bitcast_of[k] - for k in undo_bm: - del bool_mask_of[k] - for k in undo_ce: - del ctor_elems[k] - for k in undo_ln: - del logical_not_of[k] - - if dead_idx: - insts = [e for i, e in enumerate(insts) if i not in dead_idx] - - # Post-walk alias resolution sweep (updates backedge operands of OpPhi, etc.). - if alias: - for entry in insts: - _, op, args, _ = entry - if op is None or not args: - continue - new_args = [resolve(t) if t.startswith("%") else t for t in args] - if new_args != args: - entry[2] = new_args - changed = True - - # 3. Whole-function dead-slot store elimination for non-escaped, statically-indexed Function vars: - # if a slot (var, ...) has zero remaining OpLoads anywhere in the function, every OpStore to it is dead. - if static_trackable: - loaded_slots: set[tuple] = set() - for _res, op, args, _ in insts: - if op == "OpLoad" and len(args) >= 2: - slot = ptr_slot.get(args[1]) - if slot is not None and slot[0] in static_trackable: - loaded_slots.add(slot) - dead_stores: set[int] = set() - for idx, (_res, op, args, _) in enumerate(insts): - if op == "OpStore" and len(args) >= 2: - if any("Volatile" in m for m in args[2:]): - continue - slot = ptr_slot.get(args[0]) - if slot is not None and slot[0] in static_trackable and slot not in loaded_slots: - dead_stores.add(idx) - if dead_stores: - insts = [e for i, e in enumerate(insts) if i not in dead_stores] - changed = True - - # 4. Backward pure Dead-Code Elimination (DCE) + dead Function-scope OpVariable removal. - use_count: dict[str, int] = {} - for _res, op, args, _ in insts: - if op is None or not args: - continue - for tok in args: - if tok.startswith("%"): - use_count[tok] = use_count.get(tok, 0) + 1 - - def is_pure_dce_candidate(res: str, op: str, args: list[str]) -> bool: - if op in _PURE_OPS or op == "OpPhi": - return True - if op == "OpExtInst" and len(args) >= 3 and args[1] in glsl_sets and args[2] in _PURE_GLSL_EXT: - return True - if op == "OpLoad" and len(args) >= 2 and not any("Volatile" in m for m in args[2:]): - ptr = args[1] - root = ptr_root.get(ptr) - return root in trackable or root in readonly_global_vars or ptr in readonly_global_vars - if op == "OpVariable" and len(args) >= 2 and args[1] == "Function" and res in trackable: - return True - return False - - dce_dead: set[int] = set() - for idx in range(len(insts) - 1, -1, -1): - res, op, args, _ = insts[idx] - if res is None or op is None: - continue - if use_count.get(res, 0) == 0 and is_pure_dce_candidate(res, op, args): - dce_dead.add(idx) - deleted_ids.add(res) - for tok in args: - if tok.startswith("%"): - use_count[tok] = use_count.get(tok, 0) - 1 - - if dce_dead: - insts = [e for i, e in enumerate(insts) if i not in dce_dead] - changed = True - - if not changed: - break - - out_lines = [] - for res, op, args, raw in insts: - if op is None or op in ("OpFunction", "OpFunctionEnd", "OpLabel", "OpVariable"): - out_lines.append(raw) - else: - out_lines.append(_format_inst(res, op, args)) - return out_lines, deleted_ids - - -def optimize(spvasm: str, max_passes: int = 4) -> str: - """Apply sound dominator-tree SPIR-V optimizations to a SPIR-V assembly module.""" - lines = spvasm.splitlines() - - # Scan module header for constants, integer types, immutable globals, GLSL ext sets, decorations. - const_ids: set[str] = set() - const_true: set[str] = set() - const_false: set[str] = set() - const_type: dict[str, str] = {} - int_type_info: dict[str, tuple[int, int]] = {} # int_type_id -> (width, signedness) - const_int_val: dict[str, tuple[str, int, int, int]] = {} # const_id -> (type_id, uval, width, signedness) - int_const_by_val: dict[tuple[str, int], str] = {} # (type_id, uval) -> const_id - array_elem_type: dict[str, str] = {} # arr_type_id -> elem_type_id - zero_const_of_type: dict[str, str] = {} # scalar_type_id -> zero_const_id - const_null_type: dict[str, str] = {} # null_const_id -> array_type_id - readonly_global_vars: set[str] = set() # PushConstant and Input OpVariables - glsl_sets: set[str] = set() - decorated_ids: set[str] = set() - - func_ranges: list[tuple[int, int]] = [] - fn_start = None - for i, raw in enumerate(lines): - if fn_start is None: - if "OpExtInstImport" in raw and '"GLSL.std.450"' in raw: - lhs = raw.split("=", 1)[0].strip() - if lhs.startswith("%"): - glsl_sets.add(lhs) - continue - stripped = raw.lstrip() - op_tok = stripped.split(None, 1)[0] if stripped else "" - if op_tok in ("OpDecorateString", "OpDecorateStringGOOGLE"): - toks = stripped.split(None, 2) - if len(toks) >= 2 and toks[1].startswith("%"): - decorated_ids.add(toks[1]) - continue - parsed = _parse_line(raw) - if parsed is None: - continue - res, op, args = parsed - if op == "OpFunction": - fn_start = i - continue - if op == "OpDecorate" and args: - decorated_ids.add(args[0]) - elif op == "OpDecorateId" and args: - decorated_ids.add(args[0]) - for tok in args[2:]: - if tok.startswith("%"): - decorated_ids.add(tok) - elif op == "OpGroupDecorate" and len(args) >= 2: - for tok in args[1:]: - if tok.startswith("%"): - decorated_ids.add(tok) - elif op == "OpTypeInt" and res and len(args) >= 2: - try: - w, s = int(args[0]), int(args[1]) - if w in (8, 16, 32, 64): - int_type_info[res] = (w, s) - except ValueError: - pass - elif op == "OpConstant" and res and len(args) >= 2: - const_ids.add(res) - const_type[res] = args[0] - if args[1] in ("0", "0x0", "0.0"): - zero_const_of_type.setdefault(args[0], res) - info = int_type_info.get(args[0]) - if info is not None: - try: - w, s = info - uval = int(args[1], 0) & ((1 << w) - 1) - const_int_val[res] = (args[0], uval, w, s) - int_const_by_val.setdefault((args[0], uval), res) - if uval == 0: - zero_const_of_type.setdefault(args[0], res) - except ValueError: - pass - elif op == "OpConstantTrue" and res and args: - const_ids.add(res) - const_true.add(res) - const_type[res] = args[0] - elif op == "OpConstantFalse" and res and args: - const_ids.add(res) - const_false.add(res) - const_type[res] = args[0] - elif op == "OpConstantComposite" and res and args: - const_ids.add(res) - const_type[res] = args[0] - elif op == "OpConstantNull" and res and args: - const_ids.add(res) - const_type[res] = args[0] - const_null_type[res] = args[0] - elif op == "OpTypeArray" and res and args: - array_elem_type[res] = args[0] - elif op == "OpVariable" and res and len(args) >= 2 and args[1] in ("PushConstant", "Input"): - readonly_global_vars.add(res) - else: - parsed = _parse_line(raw) - if parsed is not None and parsed[1] == "OpFunctionEnd": - func_ranges.append((fn_start, i + 1)) - fn_start = None - - if not func_ranges: - return spvasm - - const_null_elem_zero: dict[str, str] = {} - for null_id, arr_ty in const_null_type.items(): - elem_ty = array_elem_type.get(arr_ty) - if elem_ty and elem_ty in zero_const_of_type: - const_null_elem_zero[null_id] = zero_const_of_type[elem_ty] - - all_deleted: set[str] = set() - opt_funcs: dict[int, list[str]] = {} - for start, end in func_ranges: - new_body, deleted = _optimize_function( - lines[start:end], const_ids, const_true, const_false, - const_null_elem_zero, const_type, const_int_val, int_const_by_val, - int_type_info, readonly_global_vars, glsl_sets, decorated_ids, - max_passes=max_passes, - ) - opt_funcs[start] = new_body - all_deleted.update(deleted) - - # Reassemble module, dropping OpDecorate / OpName lines that target deleted SSA IDs. - out: list[str] = [] - func_map = {start: (end, opt_funcs[start]) for start, end in func_ranges} - i = 0 - n = len(lines) - while i < n: - if i in func_map: - end, new_body = func_map[i] - out.extend(new_body) - i = end - continue - raw = lines[i] - if all_deleted: - stripped = raw.lstrip() - op_tok = stripped.split(None, 1)[0] if stripped else "" - if op_tok in ("OpDecorate", "OpName", "OpDecorateId", "OpDecorateString", - "OpDecorateStringGOOGLE"): - toks = stripped.split(None, 2) - if len(toks) >= 2 and toks[1] in all_deleted: - i += 1 - continue - elif op_tok == "OpGroupDecorate": - semi = raw.find(";") - code = raw[:semi] if semi >= 0 else raw - comment = raw[semi:] if semi >= 0 else "" - indent = raw[:len(raw) - len(stripped)] - toks = code.split() - if len(toks) >= 3: - kept = [t for t in toks[2:] if t not in all_deleted] - if not kept: - i += 1 - continue - if len(kept) != len(toks) - 2: - suffix = (" " + comment) if comment else "" - out.append(f"{indent}{toks[0]} {toks[1]} {' '.join(kept)}{suffix}") - i += 1 - continue - out.append(raw) - i += 1 - return "\n".join(out) + ("\n" if spvasm.endswith("\n") else "") - - -def main(argv=None) -> int: - ap = argparse.ArgumentParser(description="Sound dominator-tree SPIR-V optimizer.") - ap.add_argument("src", help="input .spvasm file") - ap.add_argument("-o", "--out", required=True, help="output .spvasm file") - ap.add_argument("--passes", type=int, default=4, help="max optimization passes (default: 4)") - args = ap.parse_args(argv) - if args.passes < 1: - ap.error("--passes must be at least 1") - with open(args.src, encoding="utf-8") as f: - text = f.read() - opt = optimize(text, max_passes=args.passes) - with open(args.out, "w", encoding="utf-8", newline="\n") as f: - f.write(opt) - return 0 - - -if __name__ == "__main__": - try: # a redirected stdout is strict ANSI code page under -I; write '?' for what it cannot encode - sys.stdout.reconfigure(errors="replace") - except (AttributeError, ValueError, OSError): - pass - sys.exit(main()) diff --git a/tools/spirv_stubs.py b/tools/spirv_stubs.py deleted file mode 100644 index be64e4229..000000000 --- a/tools/spirv_stubs.py +++ /dev/null @@ -1,316 +0,0 @@ -"""Generate minimal SPIR-V partner stubs for graphics pipeline compilation checks. - - python3 -I tools/spirv_stubs.py - -Emits binary SPIR-V 1.0 directly with the standard library (no external spirv-as needed) into -/stubs/. Stubs are deduplicated by their sorted location signature: - - vs_empty.spv, vs_0_1.spv, ... Vertex shader writing BuiltIn Position and vec4(0) to each Location - ps_empty.spv, ps_0_1.spv, ... Fragment shader reading each Location as vec4 and writing Location 0 - -Every inter-stage varying emitted by tools/rdna2spirv.py is a 32-bit vec4 float, so a single stub per -unique location set matches every shader with that interface. -""" -import json -import os -import shutil -import struct -import sys -import time -import uuid - -SPIRV_MAGIC = 0x07230203 -SPIRV_VERSION_1_0 = 0x00010000 - -# Opcodes used by the minimal stubs. -OP_CAPABILITY = 17 -OP_MEMORY_MODEL = 14 -OP_ENTRY_POINT = 15 -OP_EXECUTION_MODE = 16 -OP_TYPE_VOID = 19 -OP_TYPE_FLOAT = 22 -OP_TYPE_VECTOR = 23 -OP_TYPE_POINTER = 32 -OP_TYPE_FUNCTION = 33 -OP_CONSTANT = 43 -OP_CONSTANT_COMPOSITE = 44 -OP_FUNCTION = 54 -OP_FUNCTION_END = 56 -OP_VARIABLE = 59 -OP_LOAD = 61 -OP_STORE = 62 -OP_DECORATE = 71 -OP_FADD = 129 -OP_LABEL = 248 -OP_RETURN = 253 - -CAP_SHADER = 1 -ADDR_LOGICAL = 0 -MEM_GLSL450 = 1 -EXEC_VERTEX = 0 -EXEC_FRAGMENT = 4 -MODE_ORIGIN_UPPER_LEFT = 7 -STORAGE_INPUT = 1 -STORAGE_OUTPUT = 3 -DEC_BUILTIN = 11 -DEC_FLAT = 14 -DEC_LOCATION = 30 -BUILTIN_POSITION = 0 - - -def _inst(opcode, *words): - return [((len(words) + 1) << 16) | opcode, *words] - - -def _encode_str(text): - raw = text.encode("utf-8") + b"\x00" - pad = (-len(raw)) % 4 - raw += b"\x00" * pad - return list(struct.unpack(f"<{len(raw) // 4}I", raw)) - - -def stub_name(kind, locations): - """Canonical filename for a stub of kind ('vs' or 'ps') matching sorted unique `locations`.""" - locs = sorted({int(x) for x in locations}) - suffix = "_".join(str(x) for x in locs) if locs else "empty" - return f"{kind}_{suffix}.spv" - - -def build_vs_stub(out_locations=()): - """Minimal Vertex SPIR-V 1.0 module writing BuiltIn Position=(0,0,0,1) and vec4(0) to each Location.""" - locs = sorted({int(x) for x in out_locations}) - nid = 1 - - def alloc(): - nonlocal nid - cur = nid - nid += 1 - return cur - - id_void = alloc() - id_fn = alloc() - id_float = alloc() - id_v4 = alloc() - id_ptr_out = alloc() - id_f0 = alloc() - id_f1 = alloc() - id_pos_val = alloc() - id_zero_v4 = alloc() - id_out_pos = alloc() - out_vars = [(loc, alloc()) for loc in locs] - id_main = alloc() - id_entry = alloc() - - iface = [id_out_pos] + [vid for _, vid in out_vars] - words = [SPIRV_MAGIC, SPIRV_VERSION_1_0, 0, nid, 0] - words += _inst(OP_CAPABILITY, CAP_SHADER) - words += _inst(OP_MEMORY_MODEL, ADDR_LOGICAL, MEM_GLSL450) - words += _inst(OP_ENTRY_POINT, EXEC_VERTEX, id_main, *_encode_str("main"), *iface) - words += _inst(OP_DECORATE, id_out_pos, DEC_BUILTIN, BUILTIN_POSITION) - for loc, vid in out_vars: - words += _inst(OP_DECORATE, vid, DEC_LOCATION, loc) - - words += _inst(OP_TYPE_VOID, id_void) - words += _inst(OP_TYPE_FUNCTION, id_fn, id_void) - words += _inst(OP_TYPE_FLOAT, id_float, 32) - words += _inst(OP_TYPE_VECTOR, id_v4, id_float, 4) - words += _inst(OP_TYPE_POINTER, id_ptr_out, STORAGE_OUTPUT, id_v4) - words += _inst(OP_CONSTANT, id_float, id_f0, 0x00000000) - words += _inst(OP_CONSTANT, id_float, id_f1, 0x3F800000) - words += _inst(OP_CONSTANT_COMPOSITE, id_v4, id_pos_val, id_f0, id_f0, id_f0, id_f1) - words += _inst(OP_CONSTANT_COMPOSITE, id_v4, id_zero_v4, id_f0, id_f0, id_f0, id_f0) - words += _inst(OP_VARIABLE, id_ptr_out, id_out_pos, STORAGE_OUTPUT) - for _, vid in out_vars: - words += _inst(OP_VARIABLE, id_ptr_out, vid, STORAGE_OUTPUT) - - words += _inst(OP_FUNCTION, id_void, id_main, 0, id_fn) - words += _inst(OP_LABEL, id_entry) - words += _inst(OP_STORE, id_out_pos, id_pos_val) - for _, vid in out_vars: - words += _inst(OP_STORE, vid, id_zero_v4) - words += _inst(OP_RETURN) - words += _inst(OP_FUNCTION_END) - return struct.pack(f"<{len(words)}I", *words) - - -def build_ps_stub(in_locations=(), flat_locations=()): - """Minimal Fragment SPIR-V 1.0 module reading each Location as vec4 and writing Location 0.""" - locs = sorted({int(x) for x in in_locations}) - flat = {int(x) for x in flat_locations} - nid = 1 - - def alloc(): - nonlocal nid - cur = nid - nid += 1 - return cur - - id_void = alloc() - id_fn = alloc() - id_float = alloc() - id_v4 = alloc() - id_ptr_out = alloc() - id_ptr_in = alloc() if locs else None - id_f0 = alloc() - id_zero_v4 = alloc() - id_out0 = alloc() - in_vars = [(loc, alloc()) for loc in locs] - id_main = alloc() - id_entry = alloc() - load_add = [(vid, alloc(), alloc()) for _, vid in in_vars] - - iface = [id_out0] + [vid for _, vid in in_vars] - words = [SPIRV_MAGIC, SPIRV_VERSION_1_0, 0, nid, 0] - words += _inst(OP_CAPABILITY, CAP_SHADER) - words += _inst(OP_MEMORY_MODEL, ADDR_LOGICAL, MEM_GLSL450) - words += _inst(OP_ENTRY_POINT, EXEC_FRAGMENT, id_main, *_encode_str("main"), *iface) - words += _inst(OP_EXECUTION_MODE, id_main, MODE_ORIGIN_UPPER_LEFT) - words += _inst(OP_DECORATE, id_out0, DEC_LOCATION, 0) - for loc, vid in in_vars: - words += _inst(OP_DECORATE, vid, DEC_LOCATION, loc) - if loc in flat: - words += _inst(OP_DECORATE, vid, DEC_FLAT) - - words += _inst(OP_TYPE_VOID, id_void) - words += _inst(OP_TYPE_FUNCTION, id_fn, id_void) - words += _inst(OP_TYPE_FLOAT, id_float, 32) - words += _inst(OP_TYPE_VECTOR, id_v4, id_float, 4) - words += _inst(OP_TYPE_POINTER, id_ptr_out, STORAGE_OUTPUT, id_v4) - if id_ptr_in is not None: - words += _inst(OP_TYPE_POINTER, id_ptr_in, STORAGE_INPUT, id_v4) - words += _inst(OP_CONSTANT, id_float, id_f0, 0x00000000) - words += _inst(OP_CONSTANT_COMPOSITE, id_v4, id_zero_v4, id_f0, id_f0, id_f0, id_f0) - words += _inst(OP_VARIABLE, id_ptr_out, id_out0, STORAGE_OUTPUT) - for _, vid in in_vars: - words += _inst(OP_VARIABLE, id_ptr_in, vid, STORAGE_INPUT) - - words += _inst(OP_FUNCTION, id_void, id_main, 0, id_fn) - words += _inst(OP_LABEL, id_entry) - acc = id_zero_v4 - for vid, id_ld, id_sum in load_add: - words += _inst(OP_LOAD, id_v4, id_ld, vid) - words += _inst(OP_FADD, id_v4, id_sum, acc, id_ld) - acc = id_sum - words += _inst(OP_STORE, id_out0, acc) - words += _inst(OP_RETURN) - words += _inst(OP_FUNCTION_END) - return struct.pack(f"<{len(words)}I", *words) - - -def _interface_locations(meta, field, legacy_field=None): - if legacy_field is not None and meta.get(field) is None: - field = legacy_field - locations = meta.get(field, []) - if not isinstance(locations, (list, tuple)) or any(type(loc) is not int for loc in locations): - raise ValueError(f"{field} must be a list of integer locations") - return tuple(sorted(set(locations))) - - -def required_stubs_for_meta(meta): - """Return list of (kind, tuple(sorted_locations)) partner stubs needed for one index.json entry.""" - stage = meta.get("stage", "") - if stage == "ps": - return [("vs", _interface_locations(meta, "inputs"))] - if stage == "vs": - return [("ps", _interface_locations(meta, "outputs"))] - if stage == "ms": - return [("ps", _interface_locations(meta, "params"))] - if stage == "gs": - return [ - ("vs", _interface_locations(meta, "gs_input_locations", "gs_inputs")), - ("ps", _interface_locations(meta, "gs_output_locations", "gs_outputs")), - ] - return [] - - -def _replace_stub(source, target): - # Windows can briefly deny the rename while another writer publishes the same stub. - for delay in (0.01, 0.02, 0.04) if os.name == "nt" else (): - try: - os.replace(source, target) - return - except PermissionError as exc: - if getattr(exc, "winerror", None) not in (5, 32, 33): - raise - time.sleep(delay) - os.replace(source, target) - - -def generate_for_index(spirv_dir, index): - """Write all deduplicated partner stubs needed by `index` into /stubs/. Returns filenames written.""" - needed = set() - for name, meta in index.items(): - if isinstance(meta, dict): - try: - for spec in required_stubs_for_meta(meta): - needed.add(spec) - except (TypeError, ValueError) as e: - raise ValueError(f"{name}: invalid graphics interface locations: {e}") from e - # Validate the entire requested set before writing any stubs: negative or - # oversized locations cannot be encoded as SPIR-V unsigned literals. - for kind, locs in needed: - if any(not 0 <= loc <= 0xFFFFFFFF for loc in locs): - raise ValueError(f"invalid Location in {kind} partner stub: {locs}") - if not needed: - return [] - stubs_dir = os.path.join(spirv_dir, "stubs") - os.makedirs(stubs_dir, exist_ok=True) - written = [] - for kind, locs in sorted(needed): - fname = stub_name(kind, locs) - data = build_vs_stub(locs) if kind == "vs" else build_ps_stub(locs) - target = os.path.join(stubs_dir, fname) - # A sibling file inherits the output directory's permissions. - staged = os.path.join(stubs_dir, f".stub-{uuid.uuid4().hex}.tmp") - stream = open(staged, "xb") - try: - with stream as f: - f.write(data) - if os.name == "posix": - try: - shutil.copymode(target, staged) - except FileNotFoundError: - pass - _replace_stub(staged, target) - except BaseException: - try: - os.remove(staged) - except OSError: - pass - raise - written.append(fname) - return written - - -def main(argv=None): - argv = sys.argv[1:] if argv is None else argv - if argv in (["-h"], ["--help"]): - print(__doc__) - return 0 - if len(argv) != 1: - sys.exit(__doc__) - spirv_dir = argv[0] - idx_path = os.path.join(spirv_dir, "index.json") - if not os.path.isfile(idx_path): - sys.exit(f"missing {idx_path}") - try: - with open(idx_path, encoding="utf-8-sig") as f: - index = json.load(f) - except (OSError, ValueError) as e: - sys.exit(f"cannot read {idx_path}: {e}") - if not isinstance(index, dict): - sys.exit(f"cannot read {idx_path}: expected a JSON object of shader -> metadata entries") - try: - written = generate_for_index(spirv_dir, index) - except (OSError, ValueError, struct.error) as e: - sys.exit(f"cannot generate stubs from {idx_path}: {e}") - print(f"wrote {len(written)} stubs to {os.path.join(spirv_dir, 'stubs')}") - return 0 - - -if __name__ == "__main__": - try: # a redirected stdout is strict ANSI code page under -I; write '?' for what it cannot encode - sys.stdout.reconfigure(errors="replace") - except (AttributeError, ValueError, OSError): - pass - sys.exit(main()) diff --git a/tools/stale_build.py b/tools/stale_build.py deleted file mode 100644 index 0945e5fed..000000000 --- a/tools/stale_build.py +++ /dev/null @@ -1,50 +0,0 @@ -"""Which sources of a runtime/test program are newer than a built copy of it. - -make_game.py (vk_pipeline_check) and first_light.py (vk_harness) take a program already in runtime/build when there -is one. After a pull that changed the program, that copy is from the old sources and would run silently. The -sources are runtime/test/.cpp and the headers it pulls in with #include "..." (followed through other -headers): a change to any of them recompiles and relinks the program, so a current build is never older than them. -runtime/CMakeLists.txt isn't one: a change there that doesn't concern the program leaves it as it was. -""" -import os -import re - -_INCLUDE = re.compile(r'^\s*#\s*include\s*"([^"]+)"', re.MULTILINE) - - -def program_sources(root, name): - """The files program `name` of runtime/test is built from, as far as they exist in this checkout.""" - runtime = os.path.join(root, "runtime") - pending = [os.path.join(runtime, "test", name + ".cpp")] - found = [] - seen = set() - while pending: - path = os.path.normpath(pending.pop()) - if path in seen or not os.path.isfile(path): - continue - seen.add(path) - found.append(path) - try: - with open(path, encoding="utf-8", errors="replace") as f: - text = f.read() - except OSError: - continue - pending.extend(os.path.join(os.path.dirname(path), inc) for inc in _INCLUDE.findall(text)) - return found - - -def newer_sources(exe, root, name): - """The sources of program `name` changed after `exe` was built, relative to `root`; empty when `exe` is current - or isn't there to compare.""" - try: - built = os.path.getmtime(exe) - except OSError: - return [] - newer = [] - for path in program_sources(root, name): - try: - if os.path.getmtime(path) > built: - newer.append(os.path.relpath(path, root).replace(os.sep, "/")) - except OSError: - pass - return newer diff --git a/tools/story_index.py b/tools/story_index.py deleted file mode 100644 index 11abcb0df..000000000 --- a/tools/story_index.py +++ /dev/null @@ -1,408 +0,0 @@ -"""Index the story/minigame resource pages in an RPF9 data area or a folder of carved streams. - -The RPF9 table of contents is encrypted, so this walks the data area the same way rpf9_carve.py -does: find every zlib stream that inflates cleanly to its end, then classify the inflated bytes. -It never decrypts, never writes game data, and does not decode resources. - -The story-specific signature is `PSIN`: a section chain whose records are a four-byte tag -(`LSCH`, `LENM`, `LSNS`, `LGID`, `LRSC`, `CHKS`) followed by a big-endian u32 length that includes -the eight-byte record header. `0DRP` pages (magic at +16, version at +0x14, page count at +0x20) -and `RSC8` resource headers (version at +4) are reported with their measured fields. The tagged -auxiliary table that starts a `0DRP` second system page keeps its historical label `clip-stream` -and is reported with its entry count, tags and payload end, only when anim_index.aux_table finds -its directory and every payload inside the stream. Anything else is reported as `raw:` -instead of being guessed. - -Usage: - python -I story_index.py [--start N] [--limit BYTES] [--quiet] - python -I story_index.py [--quiet] - ---start and --limit apply to a single archive only; with a directory they are an error (exit 2). -""" -import argparse -import csv -import json -import mmap -import os -import re -import stat -import struct -import sys -import tempfile -import time -import zlib - -# -I keeps the script directory off sys.path; add it back so the sibling helpers are importable. -sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) -from anim_index import aux_table # noqa: E402 -from file_mode import published_mode # noqa: E402 -from report_paths import same_report_path # noqa: E402 -from zero_span import gap_split # noqa: E402 - -# zlib stream start, or a Bink 2 video ('KB2' + revision letter). Kept in step with rpf9_carve.py. -ZHDR = re.compile(rb"\x78[\x01\x5e\x9c\xda]|KB2[a-z]") -PSIN_TAGS = (b"LSCH", b"LENM", b"LSNS", b"LGID", b"LRSC", b"CHKS") -COLUMNS = ["offset", "stored", "size", "signature", "version", "count", "detail"] - - -def _u32(data, at): - return struct.unpack_from("= at + 4 else None - - -def _u64(data, at): - return struct.unpack_from("= at + 8 else None - - -def _be32(data, at): - return int.from_bytes(data[at:at + 4], "big") if len(data) >= at + 4 else 0 - - -def psin_sections(data): - """Return a valid PSIN section chain as [(tag, offset, length), ...]. - - The header's big-endian first-section offset at +4 is authoritative when it points at a known - tag. Otherwise every LSCH occurrence is tried and the longest chain wins. A record is tag + - big-endian u32 length, and the length counts the record header. The chain ends at CHKS or when - the next record is not a known tag. Only measured tags are accepted. - """ - def parse(at): - chain = [] - pos = at - while pos + 8 <= len(data): - tag = data[pos:pos + 4] - if tag not in PSIN_TAGS: - break - size = _be32(data, pos + 4) - if size < 8 or pos + size > len(data): - break - chain.append((tag.decode("ascii"), pos, size)) - if tag == b"CHKS": - break - pos += size - return chain - - first = _be32(data, 4) - if 8 <= first < len(data) and data[first:first + 4] in PSIN_TAGS: - chain = parse(first) - if chain: - return chain - best = [] - start = 0 - while True: - at = data.find(b"LSCH", start) - if at < 0: - break - chain = parse(at) - if len(chain) > len(best): - best = chain - start = at + 1 - return best - - -def _printable(data): - if not data: - return False - sample = data[:512] - good = sum(1 for b in sample if 32 <= b < 127 or b in (9, 10, 13)) - return len(sample) >= 64 and good / len(sample) > 0.9 - - -def _is_xml(data): - if data.startswith(b"\xef\xbb\xbf"): - data = data[3:] - return data.lstrip()[:5] == b"= 0x30 and data[16:20] == b"0DRP": - record.update(signature="page-directory", version=_u32(data, 0x14), count=_u64(data, 0x20), - detail="0DRP at +16") - elif data[:4] == b"RSC8" or data[:4] == b"RSC7": - version, declared, flags = _u32(data, 4), _u32(data, 8), _u32(data, 12) - record.update(signature=data[:4].decode("ascii").lower(), version=version, - detail=f"declared_size={declared} flags={flags}") - elif data[:4] == b"9FPR": - record.update(signature="rpf9-nested", detail=f"data_off={_u32(data, 4)} toc={_u32(data, 8)}") - elif data[:4] == b"MoVE": - record.update(signature="move", version=_u32(data, 4), detail=f"size_hint={_u32(data, 0x14)}") - elif _is_xml(data): - record.update(signature="xml", detail="XML text") - elif (len(data) >= 16 and _u32(data, 4) == 8 and _u32(data, 12) == 0 - and 0 < (_u32(data, 8) or 0) <= 4096): - record.update(signature="typehash", version=8, count=_u32(data, 8), - detail=f"type=0x{_u32(data, 0):08x}") - elif (table := aux_table(data)) is not None: - # Same validated check and record shape as anim_index (#2496): historical label kept so consumers - # group these pages as before; the count is the measured entry count, not a version. - entries, payload_end = table - record.update(signature="clip-stream", count=len(entries), - detail=f"aux-table tags={','.join(f'0x{tag:x}' for tag, _ in entries)} " - f"payload_end={payload_end}") - elif data[:3] == b"KB2" and len(data) >= 0x20: - record.update(signature="bink2", version=chr(data[3]), count=_u32(data, 8), - detail=f"{_u32(data, 0x14)}x{_u32(data, 0x18)}") - elif data[:8] == b"\x00" * 8: - record.update(signature="zero-prefix", detail="binary page") - elif _printable(data): - record.update(signature="text", detail="printable text") - else: - record.update(signature="raw:" + data[:4].hex()) - return record - - - -def scan_rpf(path, start=None, limit=None, progress=None): - """Walk an RPF9 data area. Returns (records, summary). No tables of contents are read or decrypted.""" - rows = [] - t0 = time.time() - with open(path, "rb") as fh: - # mmap refuses an empty file; an empty buffer walks the same code and finds no streams - m = mmap.mmap(fh.fileno(), 0, access=mmap.ACCESS_READ) if os.fstat(fh.fileno()).st_size else b"" - size = len(m) - first = struct.unpack_from("= 8 else 0 - pos = start if start is not None else first - if not 0 <= pos <= size: - if size: - m.close() - raise ValueError("start offset is outside the archive") - end = min(size, pos + limit) if limit else size - span_start = pos - last, zero, unread = pos, 0, 0 - while pos < end: - match = ZHDR.search(m, pos, end) - if not match: - break - s = match.start() - if m[s:s + 3] == b"KB2": - head = m[s:min(s + 0x20, end)] - blen = (_u32(head, 4) or 0) + 8 - w, h = _u32(head, 0x14), _u32(head, 0x18) - if not (64 <= blen <= end - s and w and h and 16 <= w <= 8192 and 16 <= h <= 8192): - pos = s + 1 - continue - z, u = gap_split(m, last, s) - zero += z - unread += u - record = classify(head, s, blen) - record["size"] = blen - rows.append(record) - last = pos = s + blen - continue - d = zlib.decompressobj() - chunks, p = [], s - try: - while not d.eof and p < end: - block = m[p:min(p + (1 << 20), end)] - chunks.append(d.decompress(block)) - p += len(block) # advance by the actual slice, not the requested 1 MiB - if d.unused_data or d.eof: - break - out = b"".join(chunks) + d.flush() - except zlib.error: - pos = s + 1 - continue - if not d.eof or len(out) < 64: - pos = s + 1 - continue - used = p - s - len(d.unused_data) - z, u = gap_split(m, last, s) - zero += z - unread += u - rows.append(classify(out, s, used)) - last = pos = s + used - if progress and len(rows) % 2000 == 0: - progress(len(rows), pos, end) - z, u = gap_split(m, last, end) - zero += z - unread += u - if size: - m.close() - summary = summarise(rows, end - span_start, zero, unread) - summary["mode"] = "rpf9" - summary["archive"] = path - summary["elapsed_seconds"] = round(time.time() - t0, 3) - return rows, summary - - -def scan_dir(path, progress=None, output=None): - """Index carved files, excluding the output report. Use leading hex digits for offsets when possible.""" - entries = [] - t0 = time.time() - try: - report = os.stat(output) if output is not None else None - except FileNotFoundError: - report = None - for name in sorted(os.listdir(path)): - full = os.path.join(path, name) - try: - info = os.stat(full) - except OSError: - continue - if not stat.S_ISREG(info.st_mode) or (report is not None and os.path.samestat(info, report)): - continue - # rpf9_carve.py's index.json and any .csv report sit next to the streams; they are not payloads. - if name.lower().endswith((".json", ".csv")): - continue - with open(full, "rb") as f: - data = f.read() - m = re.match(r"([0-9a-fA-F]{6,})", name) - offset = int(m.group(1), 16) if m else len(entries) - entries.append((offset, data)) - rows = [classify(data, offset, len(data)) for offset, data in entries] - summary = summarise(rows, sum(len(data) for _, data in entries), 0, 0) - summary["mode"] = "directory" - summary["directory"] = path - summary["elapsed_seconds"] = round(time.time() - t0, 3) - if progress: - progress(len(rows), len(rows), len(rows)) - return rows, summary - - -def summarise(rows, span, zero, unread): - by_sig = {} - for r in rows: - a = by_sig.setdefault(r["signature"], {"files": 0, "stored": 0, "inflated": 0}) - a["files"] += 1 - a["stored"] += r["stored"] - a["inflated"] += r["size"] - stored = sum(r["stored"] for r in rows) - return { - "files": len(rows), - "compressed_bytes": stored, - "inflated_bytes": sum(r["size"] for r in rows), - "bink2_files": sum(1 for r in rows if r["signature"] == "bink2"), - "bink2_bytes": sum(r["stored"] for r in rows if r["signature"] == "bink2"), - "zero_padding": zero, - "unread_bytes": unread, - "span": span, - "readable_fraction": round(stored / span, 6) if span else 0.0, - "signatures": by_sig, - } - - -def write_output(path, rows, summary): - """Write CSV or JSON by staging it next to `path`, then atomically replacing `path` once closed. - - The stage lives in a private TemporaryDirectory under the destination's parent, so os.replace - only ever renames within one filesystem. A late failure closes the stage and leaves any prior - report byte-for-byte intact. The destination is resolved first, so a report path that is a - symlink is published through to its target the way open(..., "w") did before. Because os.replace - unlinks the previous report file only at the destination name, other hard links to it keep the - previous contents. - """ - ext = os.path.splitext(path)[1].lower() - dest = os.path.realpath(path) - parent = os.path.dirname(dest) - with tempfile.TemporaryDirectory(dir=parent) as staging: - staged = os.path.join(staging, "story_index" + ext) - if ext == ".json": - with open(staged, "w", encoding="utf-8", newline="\n") as f: - json.dump({"summary": summary, "files": rows}, f, indent=1) - else: - with open(staged, "w", encoding="utf-8", newline="") as f: - w = csv.writer(f, lineterminator="\n") - w.writerow(COLUMNS) - for r in rows: - w.writerow([f"0x{r['offset']:x}" if i == 0 else ("" if r[c] is None else r[c]) - for i, c in enumerate(COLUMNS)]) - # os.replace hands the destination the staged file's bits; give them the destination's mode - # (an existing report's, or what open() would have made for a new file) so perms are stable. - os.chmod(staged, published_mode(dest)) - os.replace(staged, dest) - - -def byte_count(text): - """--limit: 0 or less used to scan nothing (negative) or everything (0 is falsy) without a word.""" - try: - value = int(text, 0) - except ValueError: - raise argparse.ArgumentTypeError(f"invalid int value: {text!r}") from None - if value < 1: - raise argparse.ArgumentTypeError("must be at least 1") - return value - - -def offset(text): - """--start: a negative offset would slice the archive from its end.""" - try: - value = int(text, 0) - except ValueError: - raise argparse.ArgumentTypeError(f"invalid int value: {text!r}") from None - if value < 0: - raise argparse.ArgumentTypeError("must be 0 or more") - return value - - -def main(argv=None): - ap = argparse.ArgumentParser(description=__doc__.splitlines()[0]) - ap.add_argument("source", help="an .rpf archive or a directory of carved .bin files") - ap.add_argument("out", help="output path ending in .csv or .json") - ap.add_argument("--start", type=offset, help="first byte to scan (default: the RPF data start)") - ap.add_argument("--limit", type=byte_count, help="number of bytes to scan") - ap.add_argument("--quiet", action="store_true") - a = ap.parse_args(argv) - if os.path.isdir(a.source) and (a.start is not None or a.limit is not None): - ap.error("--start and --limit apply to a single archive, not a directory") - if os.path.isdir(a.out): - ap.error(f"{a.out} is a folder, not a .csv or .json file") - if os.path.splitext(a.out)[1].lower() not in (".json", ".csv"): - ap.error("output must end in .json or .csv") - if same_report_path(a.source, a.out): - ap.error("output must not overwrite the source") - if os.path.isdir(a.source): - manifest = os.path.join(a.source, "index.json") - if same_report_path(manifest, a.out): - ap.error(f"output would overwrite the carve manifest: {a.out}") - if os.path.isfile(a.out): - for name in os.listdir(a.source): - inp = os.path.join(a.source, name) - if os.path.isfile(inp) and not name.lower().endswith((".json", ".csv")): - if same_report_path(inp, a.out): - ap.error(f"output would overwrite an input file: {a.out}") - folder = os.path.dirname(os.path.abspath(a.out)) - if not os.path.isdir(folder): - ap.error(f"{folder} is not a folder, so {a.out} cannot be written") - try: - if os.path.isdir(a.source): - rows, summary = scan_dir(a.source, output=a.out) - else: - def progress(n, pos, end): - if not a.quiet: - print(f"[{pos / max(1, end):6.1%}] {n} streams", flush=True) - rows, summary = scan_rpf(a.source, a.start, a.limit, progress) - except (OSError, ValueError) as e: - print(f"{a.source}: {e}", file=sys.stderr) - return 2 - try: - write_output(a.out, rows, summary) - except OSError as e: - print(f"{a.out}: {e.strerror or e}", file=sys.stderr) - return 2 - if not a.quiet: - top = dict(sorted(summary["signatures"].items(), key=lambda kv: -kv[1]["files"])[:15]) - print(json.dumps({k: summary[k] for k in - ("files", "compressed_bytes", "inflated_bytes", "zero_padding", "unread_bytes", - "span", "readable_fraction", "bink2_files", "elapsed_seconds")}, indent=1)) - print(f"{len(summary['signatures'])} signature classes; top 15:") - for name, counts in top.items(): - print(f" {name:24} {counts['files']:6} files {counts['stored']:12} stored {counts['inflated']:12} inflated") - return 0 - - -if __name__ == "__main__": - try: # a redirected stdout is strict ANSI code page under -I; write '?' for what it cannot encode - sys.stdout.reconfigure(errors="replace") - except (AttributeError, ValueError, OSError): - pass - sys.exit(main()) diff --git a/tools/swizzle_search.py b/tools/swizzle_search.py deleted file mode 100644 index 72c068944..000000000 --- a/tools/swizzle_search.py +++ /dev/null @@ -1,178 +0,0 @@ -"""Search for the in-tile swizzle of a GPU texture by brute force. - -Within a tile of 2^B blocks, each address bit maps to one x or one y bit. Every ordering with the right -x/y split is tried (bit k goes to the next free x or y bit), tiles are laid out row-major, and the ordering -whose block-endpoint image is smoothest wins. - -Usage: - python -I swizzle_search.py --bpe 8 --tile 65536 [--widths 1024,2048] [--tiles 48] [--out preview.png] -""" -import argparse -import itertools -import os -import sys - -import numpy as np - -sys.path.insert(0, os.path.dirname(__file__)) -from tile_probe import block_feature, score, same_report_path # noqa: E402 - - -def positions(seq, nblocks, tw, th, wblocks): - idx = np.arange(nblocks, dtype=np.int64) - per = tw * th - tile, inner = idx // per, idx % per - x = np.zeros_like(idx) - y = np.zeros_like(idx) - xi = yi = 0 - for k, c in enumerate(seq): - bit = (inner >> k) & 1 - if c == "x": - x |= bit << xi - xi += 1 - else: - y |= bit << yi - yi += 1 - tiles_x = wblocks // tw - return ((tile // tiles_x) * th + y) * wblocks + (tile % tiles_x) * tw + x - - -def search(data, bpe, tile_bytes, widths, ntiles): - raw = np.frombuffer(data[: len(data) // bpe * bpe], np.uint8).reshape(-1, bpe) - feat = block_feature(raw, bpe) - bits = int(np.log2(tile_bytes // bpe)) - results = [] - for xbits in sorted({bits // 2, (bits + 1) // 2}): - tw, th = 1 << xbits, 1 << (bits - xbits) - for wpx in widths: - wb = wpx // 4 - if wb % tw: - continue - tiles_x = wb // tw - blocks_per_row = tiles_x * tw * th - rows = min(max(1, ntiles // tiles_x), len(raw) // blocks_per_row) - if not rows: - continue - n = blocks_per_row * rows - for xs in itertools.combinations(range(bits), xbits): - seq = ["x" if k in xs else "y" for k in range(bits)] - pos = positions(seq, n, tw, th, wb) - img = np.zeros((n, 3), np.float32) - img[pos] = feat[:n] - results.append((score(img.reshape(-1, wb, 3)), wpx, "".join(seq))) - results.sort() - return results - - -def render(data, bpe, tile_bytes, wpx, seq, out): - import io - import struct - from PIL import Image - raw = np.frombuffer(data[: len(data) // bpe * bpe], np.uint8).reshape(-1, bpe) - bits = len(seq) - xbits = seq.count("x") - tw, th = 1 << xbits, 1 << (bits - xbits) - wb = wpx // 4 - hb = min(len(raw) // wb // th * th, wb // th * th or th) - n = wb * hb - pos = positions(list(seq), n, tw, th, wb) - lin = np.zeros((n, bpe), np.uint8) - lin[pos] = raw[:n] - hdr = bytearray(128) - hdr[0:4] = b"DDS " - struct.pack_into("high) {seq}") - if a.out is not None: - parent = os.path.dirname(os.path.abspath(a.out)) - try: - if parent: - os.makedirs(parent, exist_ok=True) - render(data, a.bpe, a.tile, res[0][1], res[0][2], a.out) - except (OSError, ValueError) as e: - detail = getattr(e, "strerror", None) or str(e) - print(f"ERROR: cannot write {a.out}: {detail}", file=sys.stderr) - return 2 - print("preview ->", a.out) - - -if __name__ == "__main__": - try: # a redirected stdout is strict ANSI code page under -I; write '?' for what it cannot encode - sys.stdout.reconfigure(errors="replace") - except (AttributeError, ValueError, OSError): - pass - sys.exit(main()) diff --git a/tools/tex_export.py b/tools/tex_export.py deleted file mode 100644 index e0630805d..000000000 --- a/tools/tex_export.py +++ /dev/null @@ -1,265 +0,0 @@ -"""Export textures found by tex_headers.py as standard DDS files (top mip, slice 0), detiled from AMD SW_4K_S. - -The compact TTPF mip-tail rule lives in tex_headers.py and is used by tools/ttpf_mips.py. -This carve exporter cannot apply it: the carved descriptor has no tile-mode field or native -allocation span, so the first/last heuristic below stays the only verified placement here. - -For each texture: - - element size from tex_headers.FMT_INFO (BC: 8/16 bytes per 4x4 block; uncompressed: bytes per pixel); only - 1/2/4/8/16-byte elements have a SW_4K_S equation, so 12-byte R32G32B32 stays unsupported - - the top mip is either at the data offset or at the end of the mip chain (GFX10 stores mips smallest first); - both are detiled and the smoother one wins (scored on the decoded image where Pillow can decode the format, - otherwise on raw element bytes) - - writes //___.dds and records the choice in export_log.json, - with "heuristic": true whenever two distinct placements fitted (the pick is a score, not a verified layout) - - with --png, also writes the same path with .png for every texture tools/dds_png.py can decode (BC1-BC5, BC7 - and 8-bit RGBA/BGRA, R10G10B10A2_UNORM or R11G11B10_FLOAT, with no sRGB transfer; BC5 blue is a reconstructed normal Z; - R16_FLOAT, R32_FLOAT and R16G16B16A16_FLOAT clamped to [0, 1], NaN as 0). - The rest (including BC6H) keep their - DDS only and are counted as "png unsupported". A PNG that fails to decode or write is counted as - "png error:" and its DDS stays; neither changes the exit code - -Usage: - python -I tex_export.py [--limit N] [--png] -""" -import argparse -import io -import json -import os -import struct -import sys -from collections import Counter - -import numpy as np - -sys.path.insert(0, os.path.dirname(__file__)) -from amd_swizzle import _parity, equation, load # noqa: E402 -from report_paths import same_report_path # noqa: E402 -from tex_headers import FMT_INFO # noqa: E402 - -# DXGI format -> (bytes per element, block dimension), from the indexer's table; eq4k has SW_4K_S equations -# for 1/2/4/8/16-byte elements only, so 12-byte R32G32B32 (6, 7, 8) is left out and reported unsupported. -FMT = {fmt: info for fmt, info in FMT_INFO.items() if info[0] in (1, 2, 4, 8, 16)} -PILLOW_OK = {71, 72, 74, 75, 77, 78, 80, 81, 83, 84, 98, 99, 28, 29, 87, 91} -# Pillow can't open sRGB DXGI codes; the bytes are identical to the UNORM twin, so decode with that for scoring. -DECODE_AS = {72: 71, 75: 74, 78: 77, 99: 98, 29: 28, 91: 87} - -_EQ = {} -_PATTERNS = [] # (nibbles, tables) from addrlib, read on first use so the module imports without the header - - -def eq4k(bpe): - if bpe not in _EQ: - if not _PATTERNS: - _PATTERNS.append(load()) - nib, tab = _PATTERNS[0] - e = [e for e in tab["GFX10_SW_4K_S_PATINFO"] if f" {bpe} bpe" in e[5]][0] - _EQ[bpe] = equation(nib, e, 12) - return _EQ[bpe] - - -def detile_offsets(bpe, we, he): - eq = eq4k(bpe) - elems = 4096 // bpe - lb = elems.bit_length() - 1 - bw = 1 << ((lb + 1) // 2) - bh = elems // bw - y, x = np.mgrid[0:he, 0:we].astype(np.int64) - o = np.zeros_like(x) - for bit, (mx, my) in enumerate(eq): - if mx or my: - o |= (_parity(x & mx) ^ _parity(y & my)) << bit - nbx = (we + bw - 1) // bw - return ((o + ((y // bh) * nbx + x // bw) * 4096) // bpe).reshape(-1), bw, bh - - -def level_bytes(we, he, bpe, bw, bh): - return ((we + bw - 1) // bw) * ((he + bh - 1) // bh) * 4096 - - -def dds_bytes(w, h, fmt, payload): - hdr = bytearray(128) - hdr[0:4] = b"DDS " - bpe, blk = FMT[fmt] - if blk == 1: # DDSD_PITCH: bytes in one row of the top mip - flags, pitch = 0x1007 | 0x8, w * bpe - else: # DDSD_LINEARSIZE: bytes in the whole top mip - flags, pitch = 0x1007 | 0x80000, len(payload) - struct.pack_into("= 64 else im, np.float32) - except (ImportError, NotImplementedError, OSError): - # Some Pillow installations cannot decode these formats. Score the raw elements below. - a = None - if a is None: - block = FMT[fmt][1] - we, he = (w + block - 1) // block, (h + block - 1) // block - a = np.frombuffer(payload, np.uint8).reshape(he, we, bpe)[:, :, :4].astype(np.float32) - d = sum(np.abs(np.diff(a, axis=axis)).mean() for axis in (0, 1) if a.shape[axis] > 1) - return float(d / (a.std() + 1e-6)) - - -def export_one(t, carve, out, blob_cache, png=False): - fmt = t["fmt"] - if fmt not in FMT: - return "unsupported format" - bpe, blk = FMT[fmt] - w, h = t["w"], t["h"] - we, he = (w + blk - 1) // blk, (h + blk - 1) // blk - chain_offs = tuple(off for off, _ in (t.get("gpu_chain") or ((t["gpu"], t["gpu_size"]),))) - key = (t["archive"], chain_offs) - if key not in blob_cache: - blob_cache.clear() - parts = [] - for off in chain_offs: - with open(os.path.join(carve, t["archive"], f"{off:012x}.bin"), "rb") as f: - parts.append(f.read()) - blob_cache[key] = b"".join(parts) - G = blob_cache[key] - offs, bw, bh = detile_offsets(bpe, we, he) - need = (int(offs.max()) + 1) * bpe - top = level_bytes(we, he, bpe, bw, bh) - chain = sum(level_bytes(max(1, (max(1, w >> i) + blk - 1) // blk), max(1, (max(1, h >> i) + blk - 1) // blk), bpe, bw, bh) - for i in range(max(1, t["mips"]))) - cands = [] - for place, start in (("first", t["data_off"]), ("last", t["data_off"] + chain - top)): - if start < 0 or start + need > len(G): - continue - raw = np.frombuffer(G[start:start + need], np.uint8).reshape(-1, bpe) - payload = raw[offs].tobytes() - try: - s = score_image(w, h, fmt, payload, bpe) - except Exception: # noqa: BLE001 - s = 9e9 - cands.append((s, place, payload)) - if not cands: - return "data outside GPU blob" - cands.sort(key=lambda c: c[0]) - s, place, payload = cands[0] - name = f"{t['cpu']:012x}_{t['q_index']}_{w}x{h}_{t['fmt_name']}.dds" - d = os.path.join(out, t["archive"]) - os.makedirs(d, exist_ok=True) - dds = dds_bytes(w, h, fmt, payload) - with open(os.path.join(d, name), "wb") as f: - f.write(dds) - # two placements that fit at different offsets leave the pick to the score, not to a known layout - t["export"] = {"file": name, "place": place, "score": round(s, 4), "heuristic": len(cands) > 1 and chain > top} - if png: - import dds_png # lazy: only --png pays for it - png_path = os.path.join(d, name[:-4] + ".png") - try: - data = dds_png.dds_to_png_bytes(dds) - with open(png_path, "wb") as f: - f.write(data) - t["export"]["png"] = "written" - except dds_png.DdsError: # a format it cannot decode; the payload is built here, so never a truncated one - t["export"]["png"] = "unsupported" - except Exception as e: # noqa: BLE001 the DDS is already on disk and logged: a bad PNG must not undo that - t["export"]["png"] = "error:" + type(e).__name__ - try: - os.remove(png_path) # no truncated PNG left behind - except OSError: - pass - return "ok:" + place - - -def positive_int(text): - try: - value = int(text) - except ValueError: - raise argparse.ArgumentTypeError(f"not a whole number: {text!r}") from None - if value < 1: - raise argparse.ArgumentTypeError("must be at least 1") - return value - - -def main(): - ap = argparse.ArgumentParser() - ap.add_argument("index") - ap.add_argument("carve") - ap.add_argument("out") - ap.add_argument("--limit", type=positive_int, help="export only the first N textures (N >= 1)") - ap.add_argument("--png", action="store_true", help="also write a PNG beside each DDS dds_png.py can decode") - a = ap.parse_args() - try: - with open(a.index, encoding="utf-8-sig") as f: # Notepad and PowerShell ">" save a BOM; json would refuse it - texs = json.load(f) - except (OSError, ValueError) as e: - print(f"ERROR: cannot read {a.index}: {e}", file=sys.stderr) - return 2 - if not isinstance(texs, list): - print(f"ERROR: cannot read {a.index}: expected a texture list, got {type(texs).__name__}", file=sys.stderr) - return 2 - try: - texs.sort(key=lambda t: (t["archive"], t["gpu"])) - except KeyError as e: - print(f"ERROR: cannot read {a.index}: row has no {e.args[0]!r}", file=sys.stderr) - return 2 - except TypeError as e: - print(f"ERROR: cannot read {a.index}: {e}", file=sys.stderr) - return 2 - if a.limit is not None: # 0 used to read as "no limit", and a negative N dropped the last N - texs = texs[: a.limit] - if os.path.exists(a.out) and not os.path.isdir(a.out): - print(f"ERROR: {a.out} is a file, not a folder", file=sys.stderr) - return 2 - report = os.path.join(a.out, "export_log.json") - if same_report_path(report, a.index): - print(f"ERROR: {report} must not overwrite input index {a.index}", file=sys.stderr) - return 2 - try: - os.makedirs(a.out, exist_ok=True) - except OSError as e: # a report path under an existing file, or a dangling symlink - print(f"ERROR: cannot create {a.out}: {e.strerror or e}", file=sys.stderr) - return 2 - res, cache, pngs = Counter(), {}, Counter() - io_failures = 0 - first_io_error = None - for i, t in enumerate(texs, 1): - try: - r = export_one(t, a.carve, a.out, cache, a.png) - except Exception as e: # noqa: BLE001 - r = "error:" + type(e).__name__ - if isinstance(e, OSError): - io_failures += 1 - if first_io_error is None: - first_io_error = str(e) - res[r] += 1 - if r.startswith("ok:") and "png" in t["export"]: # an "export" read from the index may be stale - pngs[t["export"]["png"]] += 1 - if i % 2000 == 0: - print(f"[{i}/{len(texs)}] {dict(res)}", flush=True) - report = os.path.join(a.out, "export_log.json") - try: - with open(report, "w", encoding="utf-8", newline="\n") as f: - json.dump(texs, f) - except OSError as e: - print(f"ERROR: cannot write {report}: {e.strerror or e}", file=sys.stderr) - return 1 - print(f"{len(texs)} textures: {dict(res)} -> {a.out}") - if a.png: - print(f"png: {dict(pngs)}") - if io_failures: - print(f"ERROR: {io_failures} texture(s) could not be read or written, first: {first_io_error}", file=sys.stderr) - return 1 - - -if __name__ == "__main__": - try: # a redirected stdout is strict ANSI code page under -I; write '?' for what it cannot encode - sys.stdout.reconfigure(errors="replace") - except (AttributeError, ValueError, OSError): - pass - sys.exit(main()) diff --git a/tools/tex_headers.py b/tools/tex_headers.py deleted file mode 100644 index 780a2bbb8..000000000 --- a/tools/tex_headers.py +++ /dev/null @@ -1,939 +0,0 @@ -"""Find texture headers in carved CPU-segment blobs and pair them with their GPU blob. - -Texture descriptor layout (qwords, found in GTA VI's resource CPU segments): - q[k-2] packed u64 (unknown: size/flags) - q[k-1] 0x980 (descriptor type) - q[k] 0x60000000 + offset (GPU data pointer into the resource's GPU segment) - q[k+4] u16 width, u16 height, u16 depth/array, u8 ?, u8 DXGI format - q[k+5] tiling / flags (0x0001 = AMD SW_4K_S verified on an R16 texture) -The GPU segment is the carved blob that follows the CPU blob. - -This module also carries the Gfx10 compact mip layout rule used by the RDS5/TTPF pools -(`tools/ttpf_mips.py`): tile-mode selection, the packed tail, and the allocation-span check. - -Usage: - python -I tex_headers.py [--archives a,b] [--out textures_index.json] -""" -import argparse -import array -import json -import os -import stat -import struct -import sys -from collections import Counter - -_UINT64_CODE = "Q" if array.array("Q").itemsize == 8 else None - -DXGI = { - 2: "R32G32B32A32_FLOAT", 3: "R32G32B32A32_UINT", 4: "R32G32B32A32_SINT", - 6: "R32G32B32_FLOAT", 7: "R32G32B32_UINT", 8: "R32G32B32_SINT", - 10: "R16G16B16A16_FLOAT", 11: "R16G16B16A16_UNORM", 12: "R16G16B16A16_UINT", - 13: "R16G16B16A16_SNORM", 14: "R16G16B16A16_SINT", - 16: "R32G32_FLOAT", 17: "R32G32_UINT", 18: "R32G32_SINT", - 24: "R10G10B10A2_UNORM", 25: "R10G10B10A2_UINT", 26: "R11G11B10_FLOAT", - 28: "R8G8B8A8_UNORM", 29: "R8G8B8A8_UNORM_SRGB", 30: "R8G8B8A8_UINT", - 31: "R8G8B8A8_SNORM", 32: "R8G8B8A8_SINT", - 34: "R16G16_FLOAT", 35: "R16G16_UNORM", 36: "R16G16_UINT", - 37: "R16G16_SNORM", 38: "R16G16_SINT", - 41: "R32_FLOAT", 42: "R32_UINT", 43: "R32_SINT", - 49: "R8G8_UNORM", 50: "R8G8_UINT", 51: "R8G8_SNORM", 52: "R8G8_SINT", - 54: "R16_FLOAT", 56: "R16_UNORM", 57: "R16_UINT", 58: "R16_SNORM", 59: "R16_SINT", - 61: "R8_UNORM", 62: "R8_UINT", 63: "R8_SNORM", 64: "R8_SINT", - 71: "BC1_UNORM", 72: "BC1_UNORM_SRGB", - 74: "BC2_UNORM", 75: "BC2_UNORM_SRGB", - 77: "BC3_UNORM", 78: "BC3_UNORM_SRGB", - 80: "BC4_UNORM", 81: "BC4_SNORM", - 83: "BC5_UNORM", 84: "BC5_SNORM", - 87: "B8G8R8A8_UNORM", 91: "B8G8R8A8_UNORM_SRGB", - 95: "BC6H_UF16", 96: "BC6H_SF16", - 98: "BC7_UNORM", 99: "BC7_UNORM_SRGB", -} - -GFX10_TO_DXGI = { - 1: 61, - 2: 63, - 5: 62, - 6: 64, - 7: 56, - 8: 58, - 11: 57, - 12: 59, - 13: 54, - 14: 49, - 15: 51, - 18: 50, - 19: 52, - 20: 42, - 21: 43, - 22: 41, - 23: 35, - 24: 37, - 27: 36, - 28: 38, - 29: 34, - 36: 26, - 50: 24, - 54: 25, - 56: 28, - 57: 31, - 60: 30, - 61: 32, - 62: 17, - 63: 18, - 64: 16, - 65: 11, - 66: 13, - 69: 12, - 70: 14, - 71: 10, - 72: 7, - 73: 8, - 74: 6, - 75: 3, - 76: 4, - 77: 2, - 130: 29, - 169: 71, - 170: 72, - 171: 74, - 172: 75, - 173: 77, - 174: 78, - 175: 80, - 176: 81, - 177: 83, - 178: 84, - 179: 95, - 180: 96, - 181: 98, - 182: 99, -} -DXGI_TO_GFX10 = {v: k for k, v in GFX10_TO_DXGI.items()} - - -def map_gfx10_format(gfx10_code): - if gfx10_code not in GFX10_TO_DXGI: - raise ValueError(f"unsupported or invalid GFX10 format: {gfx10_code}") - dxgi_id = GFX10_TO_DXGI[gfx10_code] - return dxgi_id, DXGI.get(dxgi_id, f"dxgi{dxgi_id}") - - -def dxgi_to_gfx10(dxgi_code): - if dxgi_code not in DXGI_TO_GFX10: - raise ValueError(f"unsupported DXGI format: {dxgi_code}") - return DXGI_TO_GFX10[dxgi_code] - - -def calc_mipmap_count(w, h, depth=1): - if w <= 0 or h <= 0 or depth <= 0: - return 0 - return max(w, h, depth).bit_length() - - -def calc_mipmap_dimensions(w, h, depth=1, mips=0): - if w <= 0 or h <= 0 or depth <= 0: - return [] - max_mips = calc_mipmap_count(w, h, depth) - count = max_mips if mips <= 0 else min(mips, max_mips) - return [(max(1, w >> i), max(1, h >> i), max(1, depth >> i)) for i in range(count)] - - -FMT_INFO = { - 71: (8, 4), 72: (8, 4), 80: (8, 4), 81: (8, 4), - 74: (16, 4), 75: (16, 4), 77: (16, 4), 78: (16, 4), 83: (16, 4), 84: (16, 4), - 95: (16, 4), 96: (16, 4), 98: (16, 4), 99: (16, 4), - 61: (1, 1), 62: (1, 1), 63: (1, 1), 64: (1, 1), - 49: (2, 1), 50: (2, 1), 51: (2, 1), 52: (2, 1), 54: (2, 1), 56: (2, 1), 57: (2, 1), 58: (2, 1), 59: (2, 1), - 16: (8, 1), 17: (8, 1), 18: (8, 1), - 24: (4, 1), 25: (4, 1), 26: (4, 1), 28: (4, 1), 29: (4, 1), 30: (4, 1), 31: (4, 1), 32: (4, 1), - 34: (4, 1), 35: (4, 1), 36: (4, 1), 37: (4, 1), 38: (4, 1), 41: (4, 1), 42: (4, 1), 43: (4, 1), - 87: (4, 1), 91: (4, 1), - 6: (12, 1), 7: (12, 1), 8: (12, 1), - 10: (8, 1), 11: (8, 1), 12: (8, 1), 13: (8, 1), 14: (8, 1), - 2: (16, 1), 3: (16, 1), 4: (16, 1), -} - - -def calc_mip_level_bytes(w, h, depth=1, fmt=28, align=1): - if fmt not in FMT_INFO: - raise ValueError(f"unsupported format for byte calculation: {fmt}") - bpe, blk = FMT_INFO[fmt] - we = max(1, (w + blk - 1) // blk) - he = max(1, (h + blk - 1) // blk) - slice_bytes = we * he * bpe - total = slice_bytes * max(1, depth) - if align > 1: - total = (total + align - 1) // align * align - return total - - -# AMD Gfx10 compact mip chain (the TTPF "compact" profile) and multi-slice layouts. -# -# The 9-bit descriptor mode is a low flag bit plus a 4-bit Gfx10 tile mode at -# bit 1. Tile mode 0 is SW_64KB_D; the observed 1-3 and 9-12 values are -# SW_4KB_S. Mips are stored smallest first. The last few mips share one tile at -# offset 0 instead of getting their own allocation. -COMPACT_TILE_4K = 4096 -COMPACT_TILE_64K = 65536 -COMPACT_MAX_TAIL_MIPS = {COMPACT_TILE_4K: 8, COMPACT_TILE_64K: 12} -_COMPACT_ELEMENT_LOG = {1: 0, 2: 1, 4: 2, 8: 3, 16: 4} -_COMPACT_TILE_ORIGIN = {0: (16, 16), 1: (16, 8), 2: (8, 8), 3: (8, 4), 4: (4, 4)} -# AMD Gfx10 3D SW_4KB_S micro-tile extents (blocks_w, blocks_h, blocks_d) by log2(element_bytes). -_VOLUME_4K_TILE = { - 0: (16, 16, 16), - 1: (8, 16, 16), - 2: (8, 16, 8), - 3: (8, 8, 8), - 4: (4, 8, 8), -} -# 5-bit chunk page-count codes packed in the low 20 bits of ((extra << 11) | meta), -# mapping each non-zero code to its RDS5 chunk virtual size in 4 KiB pages. -ETPF_CHUNK_CODE_PAGES = { - 1: 1, 2: 2, 3: 3, 4: 4, 5: 5, 6: 6, 7: 7, 8: 8, - 10: 12, 11: 16, 12: 24, 13: 32, 14: 48, 15: 64, 16: 128, - 21: 18, 22: 80, 23: 96, 24: 144, 26: 272, 27: 384, 28: 528, -} - - -def gfx10_tile_mode(mode): - """Return the 4-bit Gfx10 tile mode hidden in the TTPF descriptor mode.""" - if not isinstance(mode, int) or mode < 0: - raise ValueError(f"invalid descriptor mode: {mode!r}") - return (mode >> 1) & 0xF - - -def gfx10_tile_bytes(mode): - """Tile size for a descriptor mode: 64 KiB only for tile mode 0.""" - return COMPACT_TILE_64K if gfx10_tile_mode(mode) == 0 else COMPACT_TILE_4K - - -def joaat(s: str) -> int: - """Standard Jenkins One-at-a-Time 32-bit hash of lowercase ASCII string.""" - h = 0 - for c in s.lower().encode("latin-1", "replace"): - h = (h + c) & 0xFFFFFFFF - h = (h + (h << 10)) & 0xFFFFFFFF - h ^= h >> 6 - h = (h + (h << 3)) & 0xFFFFFFFF - h ^= h >> 11 - return (h + (h << 15)) & 0xFFFFFFFF - - -def is_system_pointer(val: int, max_len: int) -> bool: - """Validate that the pointer is strictly in the system page segment (0x50000000..0x5FFFFFFF).""" - if (val >> 28) != 5: - return False - offset = val & 0x0FFFFFFF - return 0 < offset + 8 <= max_len - - -def parse_texture_dict_page(data: bytes): - """Parse a small RAGE texture dictionary system page (e.g. the 400-byte stream in textures.rpf). - - Layout: - +0x20: 64-bit pointer to hash array (optional in synthetic tests) - +0x30: 64-bit pointer to grcTexture descriptor pointer array (optional in synthetic tests) - +0x38: u16 texture count (optional in synthetic tests) - +0x140..pointers_off: null-separated lower-case ASCII texture names - pointers_off (+0x170 or +0x178): array of 64-bit pointers to grcTexture descriptors (tagged 0x5...) - hashes_off (+0x180 or +0x188): array of 32-bit joaat32 name hashes - Within each grcTexture descriptor: - +0x10: dtype (0x980) - +0x18: data pointer (0x60000000 + GPU data offset) - +0x38: u16 width, u16 height, u16 depth, u8 b6, u8 DXGI format - +0x40: u64 flags (bits 16..23: mip count) - """ - if len(data) < 400: - raise ValueError(f"texture dictionary page truncated: expected >= 400 bytes, got {len(data)}") - - pointers_off = None - hashes_off = None - count = 2 - - # Check pgDictionary header at 0x20 / 0x30 - if len(data) >= 0x40: - h_cand = struct.unpack_from(" len(data): - break - raw_ptr = struct.unpack_from("> 28) != 5: - continue - ptr = raw_ptr & 0x0FFFFFFF - if ptr == 0 or ptr + 0x48 > len(data): - continue - dtype = struct.unpack_from("> 16) & 0xFF - name = names_by_hash.get(thash, f"tex_{thash:08x}") - textures.append({ - "name": name, - "hash": thash, - "width": w, - "height": height, - "depth": depth, - "b6": b6, - "mips": mips, - "flags": flags, - "format": fmt, - "format_name": DXGI.get(fmt, f"dxgi{fmt}"), - "data_offset": data_off, - "dtype": dtype, - }) - return textures - - -def parse_etpf_texture_record(record): - """Parse one 16-byte ETPF texture record (the RDS5 embedded descriptor). - - Word ``b`` packs 3-bit ``non_tail`` (bits 0..2), 7-bit DXGI ``format`` - (bits 3..9), 11-bit ``depth - 1`` (bits 10..20), 2-bit ``dimension`` - (bits 21..22), and 9-bit ``mode`` (bits 23..31). - """ - if len(record) < 16: - raise ValueError(f"ETPF texture record truncated: expected 16 bytes, got {len(record)}") - a, b, c, d = struct.unpack_from("> 14) & 0x3FFF) + 1, - "packed_mips": a >> 28, - "non_tail": b & 7, - "mips": (a >> 28) + (b & 7), - "format": (b >> 3) & 0x7F, - "depth": ((b >> 10) & 0x7FF) + 1, - "dimension": (b >> 21) & 3, - "mode": b >> 23, - "meta": c >> 21, - "extra": d, - "base": (c & 0x1FFFFF) * 4096, - } - - -def decode_etpf_chunk_pages(meta, extra): - """Decode the 43-bit ``(extra << 11) | meta`` streaming chunk-page list. - - The low 20 bits hold up to four zero-terminated 5-bit codes giving each - RDS5 chunk's virtual size in 4 KiB pages. Bits 9..18 of ``extra`` must be - zero. Returns a tuple of page counts, or ``None`` if any code or reserved - bit is invalid. - """ - if not isinstance(meta, int) or not isinstance(extra, int): - return None - if meta < 0 or meta > 0x7FF or extra < 0 or extra > 0xFFFFFFFF: - return None - if ((extra >> 9) & 0x3FF) != 0: - return None - val43 = (extra << 11) | meta - pages = [] - ended = False - for slot in range(4): - code = (val43 >> (5 * slot)) & 0x1F - if code == 0: - ended = True - continue - if ended: - return None - count = ETPF_CHUNK_CODE_PAGES.get(code) - if count is None: - return None - pages.append(count) - return tuple(pages) - - -def etpf_streaming_padding(extra): - """Return ``(align_group, pad_pages)`` from the upper 13 bits of ``extra``.""" - return (extra >> 19) & 3, extra >> 21 - - -def compact_profile_key(descriptor, element_bytes): - """The exact tuple a validated compact-profile table is keyed on.""" - return (descriptor["mode"], descriptor["width"], descriptor["height"], - descriptor["mips"], descriptor["non_tail"], element_bytes) - - -def compact_surface_layout(width, height, mips, element_bytes, block=1, - tile=COMPACT_TILE_4K): - """Compute the Gfx10 compact mip chain for one 2D texture. - - ``element_bytes`` is the size of one pixel or BC block; ``block`` is 4 for - BC formats and 1 for uncompressed formats. Returns the allocation size, - the first packed-tail mip, block tile dimensions and one entry per mip - with its offset and region size. Raises ValueError for a mip count that - cannot describe the surface or a tile/element size outside the measured - set. - """ - if width <= 0 or height <= 0: - raise ValueError(f"invalid surface dimensions {width}x{height}") - if element_bytes not in _COMPACT_ELEMENT_LOG: - raise ValueError(f"unsupported element size: {element_bytes}") - if block not in (1, 4): - raise ValueError(f"unsupported block dimension: {block}") - if tile not in COMPACT_MAX_TAIL_MIPS: - raise ValueError(f"unsupported compact tile size: {tile}") - levels = max(width, height).bit_length() - if mips < 1 or mips > levels: - raise ValueError(f"invalid mip count {mips} for {width}x{height}") - - log = _COMPACT_ELEMENT_LOG[element_bytes] - half_bits = 6 if tile == COMPACT_TILE_4K else 8 - max_tail = COMPACT_MAX_TAIL_MIPS[tile] - bw = 1 << (half_bits - log // 2) - bh = 1 << (half_bits - (log + 1) // 2) - mw, mh = _COMPACT_TILE_ORIGIN[log] - ew = (width + block - 1) // block - eh = (height + block - 1) // block - - tail = mips - sizes = [] - out = [] - for i in range(mips): - wc = max(1, (ew + (1 << i) - 1) >> i) - hc = max(1, (eh + (1 << i) - 1) >> i) - if mips > 1 and wc <= bw // 2 and hc <= bh and mips - i <= max_tail: - tail = i - break - pw = (wc + bw - 1) // bw * bw - ph = (hc + bh - 1) // bh * bh - sizes.append(pw * ph * element_bytes) - out.append({ - "index": i, "blocks_w": wc, "blocks_h": hc, "padded_w": pw, "padded_h": ph, - "pixels_w": max(1, width >> i), "pixels_h": max(1, height >> i), - "offset": 0, "region": pw * ph * element_bytes, "tile_x": 0, "tile_y": 0, - "in_tail": False, - }) - - off = tile if tail < mips else 0 - for i in range(tail - 1, -1, -1): - out[i]["offset"] = off - off += sizes[i] - for i in range(tail, mips): - entry = max_tail - 1 - (i - tail) - moff = (16 << entry) if entry > 6 else entry << 8 - x = y = 0 - for bit in range(6): - x |= ((moff >> (9 + 2 * bit)) & 1) << bit - y |= ((moff >> (8 + 2 * bit)) & 1) << bit - wc = max(1, (ew + (1 << i) - 1) >> i) - hc = max(1, (eh + (1 << i) - 1) >> i) - out.append({ - "index": i, "blocks_w": wc, "blocks_h": hc, "padded_w": bw, "padded_h": bh, - "pixels_w": max(1, width >> i), "pixels_h": max(1, height >> i), - "offset": 0, "region": tile, "tile_x": x * mw, "tile_y": y * mh, - "in_tail": True, "tail_offset": moff, - }) - return { - "size": off, "tile": tile, "first_tail": tail, "block_w": bw, "block_h": bh, - "element_bytes": element_bytes, "levels": levels, "mips": out, - } - - -def compact_layout_for_dxgi(width, height, fmt, mips, tile=COMPACT_TILE_4K): - """Compact layout using tex_headers' DXGI element-size table.""" - if fmt not in FMT_INFO: - raise ValueError(f"unsupported format for compact layout: {fmt}") - bpe, blk = FMT_INFO[fmt] - return compact_surface_layout(width, height, mips, bpe, blk, tile) - - -def array_surface_layout(width, height, depth, mips, element_bytes, block=1, - tile=COMPACT_TILE_64K): - """Compute the mip-major Gfx10 layout for a 2D texture array. - - Every slice shares the same per-mip dimensions; the packed tail (if any) - occupies ``depth * tile`` bytes at offset 0 (slice ``s`` at ``s * tile``), - followed by standalone mips from ``first_tail - 1`` down to ``0``, each - occupying ``depth * region`` bytes (slice ``s`` at ``offset + s * region``). - """ - if not isinstance(depth, int) or depth < 1: - raise ValueError(f"invalid array depth: {depth!r}") - base = compact_surface_layout(width, height, mips, element_bytes, block, tile) - first_tail = base["first_tail"] - mips_out = [dict(m) for m in base["mips"]] - off = depth * tile if first_tail < mips else 0 - for i in range(first_tail - 1, -1, -1): - mips_out[i]["offset"] = off - mips_out[i]["slice_stride"] = mips_out[i]["region"] - off += depth * mips_out[i]["region"] - for i in range(first_tail, mips): - mips_out[i]["offset"] = 0 - mips_out[i]["slice_stride"] = tile - return { - "size": off, - "slice_size": base["size"], - "tile": tile, - "first_tail": first_tail, - "block_w": base["block_w"], - "block_h": base["block_h"], - "element_bytes": element_bytes, - "levels": base["levels"], - "depth": depth, - "mip_major": True, - "mips": mips_out, - } - - -def array_layout_for_dxgi(width, height, depth, fmt, mips, tile=COMPACT_TILE_64K): - """Mip-major 2D array layout using tex_headers' DXGI element-size table.""" - if fmt not in FMT_INFO: - raise ValueError(f"unsupported format for array layout: {fmt}") - bpe, blk = FMT_INFO[fmt] - return array_surface_layout(width, height, depth, mips, bpe, blk, tile) - - -def cubemap_surface_layout(width, height, mips, element_bytes, block=1, - non_tail=0, chunk_pages=None): - """Compute the slice-major SW_4KB_S layout for a 6-face streaming cubemap. - - ``non_tail == 0`` (mode 18) stores one 6-face cubemap at offset 0. - ``non_tail in 1..3`` (modes 20/22/24) stores ``non_tail + 1`` self-contained - cubemap snapshots back-to-back in the RDS5 chunk stream; the final chunk - holds the full-resolution 6-face slice-major cubemap, zero-padded to a - 64 KiB boundary when ``6 * face_size >= 36 * 4096``. - """ - if not isinstance(non_tail, int) or not 0 <= non_tail <= 3: - raise ValueError(f"unsupported cubemap non_tail: {non_tail!r}") - face = compact_surface_layout(width, height, mips, element_bytes, block, COMPACT_TILE_4K) - face_size = face["size"] - full_bytes = 6 * face_size - if non_tail == 0: - padded_full = full_bytes - if chunk_pages is not None and len(chunk_pages) != 0: - if len(chunk_pages) != 1 or chunk_pages[0] * COMPACT_TILE_4K != padded_full: - raise ValueError( - f"non-streaming cubemap chunk_pages {chunk_pages!r} != expected ({padded_full // COMPACT_TILE_4K},)") - data_offset = 0 - total_size = full_bytes - else: - padded_full = ((full_bytes + 65535) // 65536 * 65536 - if full_bytes >= 36 * COMPACT_TILE_4K else full_bytes) - if chunk_pages is not None: - if len(chunk_pages) != non_tail + 1: - raise ValueError( - f"cubemap chunk count mismatch: expected {non_tail + 1}, got {len(chunk_pages)}") - if chunk_pages[-1] * COMPACT_TILE_4K != padded_full: - raise ValueError( - f"cubemap final chunk size {chunk_pages[-1] * COMPACT_TILE_4K} != expected {padded_full}") - data_offset = sum(chunk_pages[:-1]) * COMPACT_TILE_4K - total_size = sum(chunk_pages) * COMPACT_TILE_4K - else: - data_offset = 0 - total_size = padded_full - return { - "size": total_size, - "data_offset": data_offset, - "face_size": face_size, - "full_bytes": full_bytes, - "padded_full_bytes": padded_full, - "snapshots": non_tail + 1, - "tile": COMPACT_TILE_4K, - "first_tail": face["first_tail"], - "block_w": face["block_w"], - "block_h": face["block_h"], - "element_bytes": element_bytes, - "levels": face["levels"], - "depth": 6, - "mips": face["mips"], - } - - -def cubemap_layout_for_dxgi(width, height, fmt, mips, non_tail=0, chunk_pages=None): - """Cubemap layout using tex_headers' DXGI element-size table.""" - if fmt not in FMT_INFO: - raise ValueError(f"unsupported format for cubemap layout: {fmt}") - bpe, blk = FMT_INFO[fmt] - return cubemap_surface_layout(width, height, mips, bpe, blk, non_tail, chunk_pages) - - -def volume_surface_layout(width, height, depth, mips, element_bytes): - """Compute the AMD Gfx10 3D SW_4KB_S layout for a single-mip volume texture.""" - if width <= 0 or height <= 0 or depth <= 0: - raise ValueError(f"invalid volume dimensions {width}x{height}x{depth}") - if mips != 1: - raise ValueError(f"only single-mip 3D volumes are validated, got mips={mips}") - if element_bytes not in _COMPACT_ELEMENT_LOG: - raise ValueError(f"unsupported volume element size: {element_bytes}") - bw, bh, bd = _VOLUME_4K_TILE[_COMPACT_ELEMENT_LOG[element_bytes]] - pw = (width + bw - 1) // bw * bw - ph = (height + bh - 1) // bh * bh - pd = (depth + bd - 1) // bd * bd - z_tile_stride = (pw // bw) * (ph // bh) * COMPACT_TILE_4K - size = (pd // bd) * z_tile_stride - return { - "size": size, - "tile": COMPACT_TILE_4K, - "first_tail": 1, - "block_w": bw, - "block_h": bh, - "block_d": bd, - "padded_w": pw, - "padded_h": ph, - "padded_d": pd, - "z_tile_stride": z_tile_stride, - "element_bytes": element_bytes, - "depth": depth, - "levels": calc_mipmap_count(width, height, depth), - "mips": [{ - "index": 0, - "blocks_w": width, - "blocks_h": height, - "blocks_d": depth, - "padded_w": pw, - "padded_h": ph, - "padded_d": pd, - "pixels_w": width, - "pixels_h": height, - "pixels_d": depth, - "offset": 0, - "region": size, - "tile_x": 0, - "tile_y": 0, - "in_tail": False, - }], - } - - -def volume_layout_for_dxgi(width, height, depth, fmt, mips=1): - """Single-mip 3D SW_4KB_S volume layout using tex_headers' DXGI table.""" - if fmt not in FMT_INFO: - raise ValueError(f"unsupported format for volume layout: {fmt}") - bpe, blk = FMT_INFO[fmt] - if blk != 1: - raise ValueError(f"block-compressed 3D volumes are not supported: format {fmt}") - return volume_surface_layout(width, height, depth, mips, bpe) - - -def compact_span_matches(layout, span): - """True only when an allocation span is byte-exact for the computed chain.""" - return isinstance(span, int) and span == layout["size"] - - -DDSD_CAPS = 0x00000001 -DDSD_HEIGHT = 0x00000002 -DDSD_WIDTH = 0x00000004 -DDSD_PITCH = 0x00000008 -DDSD_PIXELFORMAT = 0x00001000 -DDSD_MIPMAPCOUNT = 0x00020000 -DDSD_LINEARSIZE = 0x00080000 -DDSD_DEPTH = 0x00800000 - -DDSCAPS_COMPLEX = 0x00000008 -DDSCAPS_MIPMAP = 0x00400000 -DDSCAPS_TEXTURE = 0x00001000 - -DDSCAPS2_CUBEMAP = 0x00000200 -DDSCAPS2_CUBEMAP_ALLFACES = 0x0000FE00 -DDSCAPS2_VOLUME = 0x00200000 - -D3D10_RESOURCE_DIMENSION_TEXTURE2D = 3 -D3D10_RESOURCE_DIMENSION_TEXTURE3D = 4 -D3D10_RESOURCE_MISC_TEXTURECUBE = 0x4 - - -def dds_header(w, h, depth=1, mips=1, fmt=28, is_cube=False, linear_size=0, array_size=1): - """Build a DX10 DDS header; array_size counts cubes for cubemaps. - - For known uncompressed formats, derive the row pitch. A nonzero linear_size - overrides the derived top mip size for compressed formats. - """ - hdr = bytearray(128) - hdr[0:4] = b"DDS " - flags = DDSD_CAPS | DDSD_HEIGHT | DDSD_WIDTH | DDSD_PIXELFORMAT - if mips > 1: - flags |= DDSD_MIPMAPCOUNT - if depth > 1: - flags |= DDSD_DEPTH - layout = FMT_INFO.get(fmt) - if layout is not None and layout[1] == 1: - flags |= DDSD_PITCH - pitch_or_size = calc_mip_level_bytes(w, 1, fmt=fmt) - else: - flags |= DDSD_LINEARSIZE - pitch_or_size = linear_size - if layout is not None and linear_size == 0: - pitch_or_size = calc_mip_level_bytes(w, h, depth=depth, fmt=fmt) - - caps = DDSCAPS_TEXTURE - if mips > 1: - caps |= DDSCAPS_COMPLEX | DDSCAPS_MIPMAP - if depth > 1 or is_cube or array_size > 1: - caps |= DDSCAPS_COMPLEX - - caps2 = 0 - if depth > 1: - caps2 |= DDSCAPS2_VOLUME - if is_cube: - caps2 |= DDSCAPS2_CUBEMAP_ALLFACES - - struct.pack_into(" 1 else 0, mips if mips > 1 else 1) - struct.pack_into(" 1 else D3D10_RESOURCE_DIMENSION_TEXTURE2D - misc = D3D10_RESOURCE_MISC_TEXTURECUBE if is_cube else 0 - dxt10 = struct.pack("> 28) == 6) & ((q >> 32) == 0))[0] - return q, hits - - -def scan_archive(carve, arch): - with open(os.path.join(carve, arch, "index.json"), encoding="utf-8-sig") as f: - files = sorted(json.load(f)["files"], key=lambda r: r["off"]) - out = [] - for i in range(len(files) - 1): - v, g = files[i], files[i + 1] - # CPU segment: starts with a zero qword but isn't zero-padded GPU data. The GPU segment is whatever - # blob follows it (texture data often starts directly with BC blocks, not a zero header). - if not (v["head"][:16] == "0" * 16 and not v["head"].startswith("0" * 32)): - continue - if g["head"].startswith("42400000") or g.get("type") == "bink2": - continue - # The GPU segment can span several consecutive blobs: everything up to the next CPU/header blob. - chain = [] - for j in range(i + 1, min(len(files), i + 257)): - r = files[j] - if r["head"].startswith("42400000") or r.get("type") == "bink2" or ( - r["head"][:16] == "0" * 16 and not r["head"].startswith("0" * 32) and chain): - break - chain.append([r["off"], r["size"]]) - with open(os.path.join(carve, arch, f"{v['off']:012x}.bin"), "rb") as f: - V = f.read() - q, hits = _find_gpu_ptr_qwords(V) - # Any GPU pointer whose header (4 qwords later) decodes to sane dimensions and a known DXGI format. - for k in hits: - k = int(k) - if k < 2 or k + 5 >= len(q): - continue - d = int(q[k + 4]).to_bytes(8, "little") - w, h, depth = int.from_bytes(d[0:2], "little"), int.from_bytes(d[2:4], "little"), int.from_bytes(d[4:6], "little") - fmt = d[7] - if fmt not in DXGI or not (1 <= w <= 16384 and 1 <= h <= 16384 and 1 <= depth <= 2048): - continue - flags = int(q[k + 5]) - mips = (flags >> 16) & 0xFF - dtype = int(q[k - 1]) - # Small dimensions need the known texture type and a mip count that fits the extent. - if min(w, h) < 4 and (dtype != 0x980 or not 1 <= mips <= calc_mipmap_count(w, h, depth)): - continue - # Real texture data is 256-byte aligned (4 KB in every verified case); unaligned hits are other structs. - if (int(q[k]) & 0xFF) != 0: - continue - out.append({"archive": arch, "cpu": v["off"], "gpu": g["off"], "gpu_size": g["size"], "gpu_chain": chain, - "data_off": int(q[k]) & 0x0FFFFFFF, "w": w, "h": h, "depth": depth, "b6": d[6], "fmt": fmt, - "fmt_name": DXGI.get(fmt, f"dxgi{fmt}"), "flags": flags, "packed": int(q[k - 2]), - "dtype": dtype, "mips": mips, "q_index": k}) - return out - - -def same_output_path(first, second): - """True when writing ``second`` would truncate ``first`` (same file, path or hard link).""" - if os.path.normcase(os.path.realpath(first)) == os.path.normcase(os.path.realpath(second)): - return True - try: - return os.path.samefile(first, second) - except OSError: - return False - - -def input_files(carve, archs): - """Yield (kind, path) for every file the scan reads from the selected carve archives. - - Each archive contributes its ``index.json`` manifest and the ``.bin`` streams next to it. - A report path only has to match one of these, not the carve folder argument itself. - """ - for arch in archs: - folder = os.path.join(carve, arch) - yield "manifest", os.path.join(folder, "index.json") - with os.scandir(folder) as entries: - for entry in entries: - if entry.is_file() and entry.name.lower().endswith(".bin"): - yield "blob", entry.path - - -def report_needs_input_check(carve, archs, path): - """Whether a report path has to be compared with every scanned input. - - A report that already exists as a regular file, is not a symlink and has one link is reachable - only through its own name. When that name is not ``index.json`` or a ``*.bin`` stream, no input - can resolve to it, so the per-file realpath/samefile checks can be skipped. A missing report, - a link, or an input-like name is always compared; an input may also be a symlink to it. - """ - try: - st = os.lstat(path) - except OSError: - return True - if not stat.S_ISREG(st.st_mode) or st.st_nlink != 1: - return True - name = os.path.basename(os.path.realpath(path)).lower() - if name == "index.json" or name.endswith(".bin"): - return True - for arch in archs: - with os.scandir(os.path.join(carve, arch)) as entries: - for entry in entries: - if entry.is_symlink(): - leaf = entry.name.lower() - if leaf == "index.json" or leaf.endswith(".bin"): - return True - return False - - -def main(): - ap = argparse.ArgumentParser() - ap.add_argument("carve") - ap.add_argument("--archives") - ap.add_argument("--out") - a = ap.parse_args() - if not os.path.isdir(a.carve): - ap.error(f"{a.carve} is not a folder") - archs = a.archives.split(",") if a.archives else sorted( - d for d in os.listdir(a.carve) if os.path.isfile(os.path.join(a.carve, d, "index.json"))) - missing = [arch for arch in archs if not os.path.isfile(os.path.join(a.carve, arch, "index.json"))] - if missing: - ap.error(f"no index.json for {', '.join(missing)} in {a.carve}") - if not archs: - ap.error(f"no carved archive (a folder with index.json) in {a.carve}") - path = a.out or os.path.join(a.carve, "textures_index.json") - if os.path.isdir(path): - ap.error(f"{path} is a directory, not a .json file") - if report_needs_input_check(a.carve, archs, path): - for kind, source in input_files(a.carve, archs): - if same_output_path(source, path): - ap.error(f"output would overwrite an input {kind}: {path}") - allt = [] - for arch in archs: - try: - t = scan_archive(a.carve, arch) - except (OSError, ValueError, KeyError, TypeError) as e: # a malformed index.json: one line, as gamedata_index - where = getattr(e, "filename", None) or os.path.join(a.carve, arch, "index.json") - print(f"ERROR: cannot read {where}: {getattr(e, 'strerror', None) or e!r}", file=sys.stderr) - return 2 - print(f"{arch}: {len(t)} texture headers", flush=True) - allt += t - parent = os.path.dirname(os.path.abspath(path)) - try: - os.makedirs(parent, exist_ok=True) - with open(path, "w", encoding="utf-8", newline="\n") as f: - json.dump(allt, f) - except OSError as e: - print(f"ERROR: cannot write {path}: {e.strerror or e}", file=sys.stderr) - return 2 - print(f"{len(allt)} textures -> {path}") - print("formats:", Counter(t["fmt_name"] for t in allt).most_common(12)) - print("flags (low 16 bits):", Counter(hex(t["flags"] & 0xFFFF) for t in allt).most_common(10)) - print("byte6:", Counter(t["b6"] for t in allt).most_common(8)) - - -if __name__ == "__main__": - try: # a redirected stdout is strict ANSI code page under -I; write '?' for what it cannot encode - sys.stdout.reconfigure(errors="replace") - except (AttributeError, ValueError, OSError): - pass - sys.exit(main()) diff --git a/tools/tex_mode_probe.py b/tools/tex_mode_probe.py deleted file mode 100644 index 5c9e37542..000000000 --- a/tools/tex_mode_probe.py +++ /dev/null @@ -1,148 +0,0 @@ -"""For textures with known size/format/mips, find which AMD swizzle mode and top-mip placement decodes cleanly. - -Candidates: every addrlib 4K/64K pattern for the element size, crossed with two placements of the top mip -(at the texture's data offset, or at the end of its mip chain, since GFX10 stores mips smallest first). -Scored with average RGB colours for BC1, BC2 and BC3 blocks (smoothness relative to the image's own spread). - -Usage: - python -I tex_mode_probe.py [--fmt BC1] [--n 12] -""" -import argparse -import json -import os -import sys -from collections import Counter - -import numpy as np - -sys.path.insert(0, os.path.dirname(__file__)) -from amd_swizzle import _parity, equation, load # noqa: E402 -from bc_feature import block_average, smoothness # noqa: E402 - -BPE = {"BC1": 8, "BC2": 16, "BC3": 16} - - -def bc_bpe(fmt_name): - return BPE.get(fmt_name.split("_", 1)[0]) - - -def _tile_shape(tile_bytes: int, bpe: int) -> tuple[int, int]: - elements = tile_bytes // bpe - width = 1 << (elements.bit_length() // 2) - return width, elements // width - - -def mip_bytes(w: int, h: int, bpe: int, align: int) -> int: - """Size of a mip in 4K/64K tiles, or its aligned linear size for other alignments.""" - bw, bh = max(1, (w + 3) // 4), max(1, (h + 3) // 4) - if align in (4096, 65536): - tw, th = _tile_shape(align, bpe) - return ((bw + tw - 1) // tw) * ((bh + th - 1) // th) * align - n = bw * bh * bpe - return (n + align - 1) // align * align - - -def offsets_for(eq, bb, bpe, wb, hb): - bw, bh = _tile_shape(1 << bb, bpe) - y, x = np.mgrid[0:hb, 0:wb].astype(np.int64) - o = np.zeros_like(x) - for bit, (mx, my) in enumerate(eq): - if mx or my: - o |= (_parity(x & mx) ^ _parity(y & my)) << bit - nbx = (wb + bw - 1) // bw - return (o + ((y // bh) * nbx + x // bw) * (1 << bb)) // bpe - - -def gpu_blob(carve, t): - """The texture's whole GPU blob: every carved part of `gpu_chain` in order (data_off counts from the first), - as tex_export.py reads it; a single `gpu` file when the index has no chain.""" - parts = [] - for off, _ in t.get("gpu_chain") or [[t["gpu"], t["gpu_size"]]]: - with open(os.path.join(carve, t["archive"], f"{off:012x}.bin"), "rb") as f: - parts.append(f.read()) - return b"".join(parts) - - -def positive_int(text): - """--n: 0 probed nothing and printed an empty ranking as a result; a negative N dropped the last N textures.""" - try: - value = int(text) - except ValueError: - raise argparse.ArgumentTypeError(f"not a whole number: {text!r}") from None - if value < 1: - raise argparse.ArgumentTypeError("must be at least 1") - return value - - -def main(): - ap = argparse.ArgumentParser() - ap.add_argument("index") - ap.add_argument("carve") - ap.add_argument("--fmt", default="BC1", help="BC1, BC2, or BC3, optionally with a DXGI suffix") - ap.add_argument("--n", type=positive_int, default=12, help="probe the first N matching textures (N >= 1)") - a = ap.parse_args() - if bc_bpe(a.fmt) is None: - ap.error(f"no color scorer for {a.fmt!r}; expected BC1, BC2, or BC3") - try: - with open(a.index, encoding="utf-8") as f: - index = json.load(f) - except (OSError, ValueError) as error: - ap.error(f"cannot read texture index {a.index}: {error}") - if not isinstance(index, list): - ap.error(f"{a.index}: texture index must contain a list") - nib, tab = load() - texs = [t for t in index if t["fmt_name"].startswith(a.fmt) - and bc_bpe(t["fmt_name"]) is not None and t["w"] >= 256 and t["h"] >= 256] - texs = texs[: a.n] - cands = {} - for tname, ents in tab.items(): - for size, bb in (("_64K_", 16), ("_4K_", 12)): - if size in tname and ("_S" in tname or "_D" in tname or "_R_X_1xaa" in tname): - for e in ents: - if f" {bc_bpe(a.fmt)} bpe" in e[5]: - eq = equation(nib, e, bb) - cands.setdefault((bb, tuple(eq)), f"{tname.replace('GFX10_SW_', '').replace('_PATINFO', '')} {e[5][:22]}") - wins = Counter() - skipped = 0 - for t in texs: - bpe = bc_bpe(t["fmt_name"]) - G = gpu_blob(a.carve, t) - wb, hb = (t["w"] + 3) // 4, (t["h"] + 3) // 4 - mips = (t["flags"] >> 16) & 0xFF - res = [] - for (bb, eq), label in cands.items(): - align = 1 << bb - top = mip_bytes(t["w"], t["h"], bpe, align) - chain = sum(mip_bytes(max(1, t["w"] >> i), max(1, t["h"] >> i), bpe, align) for i in range(max(1, mips))) - placements = [("first", t["data_off"])] - if chain != top: - placements.append(("last", t["data_off"] + chain - top)) - for place, start in placements: - o = offsets_for(list(eq), bb, bpe, wb, hb) - seg = G[start:start + (int(o.max()) + 1) * bpe] - if len(seg) < (int(o.max()) + 1) * bpe: - continue - raw = np.frombuffer(seg, np.uint8).reshape(-1, bpe) - img = block_average(raw[o.reshape(-1)], bpe).reshape(hb, wb, 3) - res.append((smoothness(img), label, place)) - res.sort() - if res: - lin_raw = np.frombuffer(G[t["data_off"]:t["data_off"] + wb * hb * bpe], np.uint8) - lin = smoothness(block_average(lin_raw.reshape(-1, bpe), bpe).reshape(hb, wb, 3)) if len(lin_raw) == wb * hb * bpe else -1 - second = f"{res[1][0]:.4f} {res[1][1]} [{res[1][2]}]" if len(res) > 1 else "n/a" - print(f"{t['w']}x{t['h']} {t['fmt_name']} mips={mips} gpu={t['gpu_size']} best {res[0][0]:.4f} {res[0][1]} [{res[0][2]}]" - f" 2nd {second} linear {lin:.4f}") - wins[(res[0][1].split(' ')[0], res[0][2])] += 1 - else: - skipped += 1 - print(f"{t['w']}x{t['h']} {t['fmt_name']} gpu={t['gpu']:#x} skipped: no candidate fits in the GPU blob") - print("winners:", wins.most_common()) - print(f"probed {len(texs) - skipped} of {len(texs)} textures; {skipped} skipped") - - -if __name__ == "__main__": - try: # a redirected stdout is strict ANSI code page under -I; write '?' for what it cannot encode - sys.stdout.reconfigure(errors="replace") - except (AttributeError, ValueError, OSError): - pass - sys.exit(main()) diff --git a/tools/texoff_probe.py b/tools/texoff_probe.py deleted file mode 100644 index 300df2938..000000000 --- a/tools/texoff_probe.py +++ /dev/null @@ -1,168 +0,0 @@ -r"""SHADER-337: measure the y and z texel-offset fields of image_sample_lz_o on an AMD GPU (tools/hw_oracle). - - python -I tools/texoff_probe.py # the rule's expectation only (no GPU) - python -I tools/texoff_probe.py --oracle hw # native AMD GPU, wave32 and wave64, compared with the rule - -docs/design.md ("Texel offsets") has x measured on hardware (signed 6-bit field at bits [5:0], bits 6-7 ignored) and the -y and z signs only from a structural test. Here a raw kernel samples a linear R32_SFLOAT texture whose texel holds its -own index, with a point sampler that clamps to the last texel, so each result names the texel that was read: - - 2D 64x64, texel (x, y) = 64 y + x: y field = offset dword bits [13:8] - 3D 64x1x64, texel (x, 0, z) = 64 z + x: z field = offset dword bits [21:16] - -Each row starts at a texel and uses one offset dword. The values are chosen so that a signed and an unsigned reading -land on different texels (or one clamps), and some rows set the bits just above a field to see whether they are -ignored. The rule checked is the translator's: every field is sign-extended from 6 bits, the bits above it ignored -(tests/test_texel_offsets.py). Standard library only; the texture is built here, no game files. - -Exit codes: 0 every row matches the rule, 1 a mismatch, 2 harness error, 77 no hardware oracle. -Usage: `python -I tools/texoff_probe.py --help` lists the options. -""" -import argparse -import os -import struct -import sys - -HERE = os.path.dirname(os.path.abspath(__file__)) -sys.path.insert(0, os.path.join(HERE, "hw_oracle")) - -W = 64 -H2D = 64 -D3D = 64 -SQ_RSRC_IMG_3D = 10 -CLAMP_LAST_TEXEL = 2 - - -def sext6(v): - v &= 0x3F - return v - 64 if v & 0x20 else v - - -def clamp(v, n): - return max(0, min(n - 1, v)) - - -# (name, dim, start (x, y_or_z), offset dword) -ROWS = [ - # y field, 2D: from row 40 (0x20 signed is -32 -> 8, unsigned 32 -> clamps to 63; 0x3c is -4 -> 36 vs 60) - ("y_0x20_from40", "2d", (5, 40), 0x20 << 8), - ("y_0x3c_from40", "2d", (5, 40), 0x3C << 8), - ("y_0x1f_from10", "2d", (5, 10), 0x1F << 8), # +31 -> 41 either way (control) - ("y_0x20_from10", "2d", (5, 10), 0x20 << 8), # signed -32 clamps to 0, unsigned 32 -> 42 - ("y_0x21_from40", "2d", (5, 40), 0x21 << 8), # -31 -> 9 vs 33 -> clamp 63 - ("y_bits14_15", "2d", (5, 40), 0xC0 << 8), # field 0 with bits 14-15 set: 40 if they are ignored - ("y_0x3f_bit14", "2d", (5, 40), 0x7F << 8), # field 0x3f (-1) with bit 14: 39 if ignored - ("y_with_x", "2d", (20, 40), (0x3C << 8) | 0x3E), # x -2, y -4 together - # z field, 3D: same values on bits [21:16] - ("z_0x20_from40", "3d", (5, 40), 0x20 << 16), - ("z_0x3c_from40", "3d", (5, 40), 0x3C << 16), - ("z_0x1f_from10", "3d", (5, 10), 0x1F << 16), - ("z_0x20_from10", "3d", (5, 10), 0x20 << 16), - ("z_0x21_from40", "3d", (5, 40), 0x21 << 16), - ("z_bits22_23", "3d", (5, 40), 0xC0 << 16), - ("z_with_x_y", "3d", (20, 40), (0x3C << 16) | (0x3F << 8) | 0x3E), # y -1 on a 1-texel-high image clamps -] - - -def expected(dim, start, off): - x0, b0 = start - x = clamp(x0 + sext6(off), W) - if dim == "2d": - y = clamp(b0 + sext6(off >> 8), H2D) - return float(y * W + x) - z = clamp(b0 + sext6(off >> 16), D3D) - return float(z * W + x) # y is clamped to the single row - - -def texture(dim): - n = W * (H2D if dim == "2d" else D3D) - return b"".join(struct.pack("AU_\\0